diff --git a/.gitignore b/.gitignore index 7cd10ef..a80076b 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,2 @@ /.rhema/ +/app/vendor/rune/target diff --git a/app/Cargo.lock b/app/Cargo.lock index 459dee3..cdffabf 100644 --- a/app/Cargo.lock +++ b/app/Cargo.lock @@ -2771,7 +2771,6 @@ dependencies = [ [[package]] name = "rune" version = "0.0.1" -source = "git+https://github.com/anomalyco/rune?rev=63ad0209edc9a3a7d2208b7f6c66f9e353da315d#63ad0209edc9a3a7d2208b7f6c66f9e353da315d" dependencies = [ "accesskit", "accesskit_macos", @@ -2839,7 +2838,6 @@ dependencies = [ [[package]] name = "rune-core" version = "0.0.1" -source = "git+https://github.com/anomalyco/rune?rev=63ad0209edc9a3a7d2208b7f6c66f9e353da315d#63ad0209edc9a3a7d2208b7f6c66f9e353da315d" dependencies = [ "js-sys", "libc", @@ -2858,7 +2856,6 @@ dependencies = [ [[package]] name = "rune-edit" version = "0.0.1" -source = "git+https://github.com/anomalyco/rune?rev=63ad0209edc9a3a7d2208b7f6c66f9e353da315d#63ad0209edc9a3a7d2208b7f6c66f9e353da315d" dependencies = [ "js-sys", "parley", @@ -2872,7 +2869,6 @@ dependencies = [ [[package]] name = "rune-gpu" version = "0.0.1" -source = "git+https://github.com/anomalyco/rune?rev=63ad0209edc9a3a7d2208b7f6c66f9e353da315d#63ad0209edc9a3a7d2208b7f6c66f9e353da315d" dependencies = [ "blake3", "bytemuck", @@ -2899,7 +2895,6 @@ dependencies = [ [[package]] name = "rune-highlights" version = "0.0.1" -source = "git+https://github.com/anomalyco/rune?rev=63ad0209edc9a3a7d2208b7f6c66f9e353da315d#63ad0209edc9a3a7d2208b7f6c66f9e353da315d" dependencies = [ "unicode-ident", "wasmparser", @@ -2908,7 +2903,6 @@ dependencies = [ [[package]] name = "rune-image" version = "0.0.1" -source = "git+https://github.com/anomalyco/rune?rev=63ad0209edc9a3a7d2208b7f6c66f9e353da315d#63ad0209edc9a3a7d2208b7f6c66f9e353da315d" dependencies = [ "blake3", "image", @@ -2925,7 +2919,6 @@ dependencies = [ [[package]] name = "rune-kit" version = "0.0.1" -source = "git+https://github.com/anomalyco/rune?rev=63ad0209edc9a3a7d2208b7f6c66f9e353da315d#63ad0209edc9a3a7d2208b7f6c66f9e353da315d" dependencies = [ "icu_normalizer", "rune", @@ -2937,7 +2930,6 @@ dependencies = [ [[package]] name = "rune-media" version = "0.0.1" -source = "git+https://github.com/anomalyco/rune?rev=63ad0209edc9a3a7d2208b7f6c66f9e353da315d#63ad0209edc9a3a7d2208b7f6c66f9e353da315d" dependencies = [ "ash", "block2 0.6.2", @@ -2966,12 +2958,10 @@ dependencies = [ [[package]] name = "rune-motion" version = "0.1.0" -source = "git+https://github.com/anomalyco/rune?rev=63ad0209edc9a3a7d2208b7f6c66f9e353da315d#63ad0209edc9a3a7d2208b7f6c66f9e353da315d" [[package]] name = "rune-notify" version = "0.0.1" -source = "git+https://github.com/anomalyco/rune?rev=63ad0209edc9a3a7d2208b7f6c66f9e353da315d#63ad0209edc9a3a7d2208b7f6c66f9e353da315d" dependencies = [ "block2 0.6.2", "objc2 0.6.5", @@ -2983,7 +2973,6 @@ dependencies = [ [[package]] name = "rune-spell" version = "0.0.1" -source = "git+https://github.com/anomalyco/rune?rev=63ad0209edc9a3a7d2208b7f6c66f9e353da315d#63ad0209edc9a3a7d2208b7f6c66f9e353da315d" dependencies = [ "js-sys", "objc2-app-kit 0.3.2", @@ -3002,7 +2991,6 @@ dependencies = [ [[package]] name = "rune-staging" version = "0.0.1" -source = "git+https://github.com/anomalyco/rune?rev=63ad0209edc9a3a7d2208b7f6c66f9e353da315d#63ad0209edc9a3a7d2208b7f6c66f9e353da315d" dependencies = [ "wgpu", "windows", @@ -3011,7 +2999,6 @@ dependencies = [ [[package]] name = "rune-taffy" version = "0.0.1" -source = "git+https://github.com/anomalyco/rune?rev=63ad0209edc9a3a7d2208b7f6c66f9e353da315d#63ad0209edc9a3a7d2208b7f6c66f9e353da315d" dependencies = [ "stacker", "taffy", @@ -3020,7 +3007,6 @@ dependencies = [ [[package]] name = "rune-text" version = "0.0.1" -source = "git+https://github.com/anomalyco/rune?rev=63ad0209edc9a3a7d2208b7f6c66f9e353da315d#63ad0209edc9a3a7d2208b7f6c66f9e353da315d" dependencies = [ "bytemuck", "fontique", @@ -3036,7 +3022,7 @@ dependencies = [ "rustc-hash 2.1.3", "skrifa", "swash", - "tiny-skia-path 0.11.4 (git+https://github.com/anomalyco/rune?rev=63ad0209edc9a3a7d2208b7f6c66f9e353da315d)", + "tiny-skia-path 0.11.4", "unicode-segmentation", "wasm-bindgen", "windows", @@ -3682,8 +3668,6 @@ dependencies = [ [[package]] name = "tiny-skia-path" version = "0.11.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9c9e7fc0c2e86a30b117d0462aa261b72b7a99b7ebd7deb3a14ceda95c5bdc93" dependencies = [ "arrayref", "bytemuck", @@ -3693,7 +3677,8 @@ dependencies = [ [[package]] name = "tiny-skia-path" version = "0.11.4" -source = "git+https://github.com/anomalyco/rune?rev=63ad0209edc9a3a7d2208b7f6c66f9e353da315d#63ad0209edc9a3a7d2208b7f6c66f9e353da315d" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9c9e7fc0c2e86a30b117d0462aa261b72b7a99b7ebd7deb3a14ceda95c5bdc93" dependencies = [ "arrayref", "bytemuck", diff --git a/app/Cargo.toml b/app/Cargo.toml index 0499a04..835d0b7 100644 --- a/app/Cargo.toml +++ b/app/Cargo.toml @@ -14,9 +14,9 @@ path = "src/main.rs" winresource = "0.1" [dependencies] -rune = { git = "https://github.com/anomalyco/rune", rev = "63ad0209edc9a3a7d2208b7f6c66f9e353da315d" } -rune-kit = { git = "https://github.com/anomalyco/rune", rev = "63ad0209edc9a3a7d2208b7f6c66f9e353da315d" } -rune-notify = { git = "https://github.com/anomalyco/rune", rev = "63ad0209edc9a3a7d2208b7f6c66f9e353da315d" } +rune = { path = "vendor/rune/crates/rune" } +rune-kit = { path = "vendor/rune/crates/rune-kit" } +rune-notify = { path = "vendor/rune/crates/rune-notify" } serde = { version = "1", features = ["derive"] } serde_json = "1" @@ -38,7 +38,9 @@ windows = { version = "0.62", features = [ "Win32_System_Threading", ] } -# Rune is patched in the workspace that builds it. A dependency's `[patch]` doesn't apply to +# Rune comes from a local checkout of the pinned rev, carrying two cherry-picked patches +# (anomalyco/rune issues 1320 and 1325) on branch `ported`. +# Rune's other crates are patched in the workspace that builds it. A dependency's `[patch]` doesn't apply # the app that depends on it, so these three copies (from rune's own vendor/) are repeated here. [patch.crates-io] wgpu-hal = { path = "vendor/wgpu-hal" } diff --git a/app/vendor/rune/.cargo/config.toml b/app/vendor/rune/.cargo/config.toml new file mode 100644 index 0000000..6ff57cc --- /dev/null +++ b/app/vendor/rune/.cargo/config.toml @@ -0,0 +1,16 @@ +# Use rustc's bundled rust-lld on Windows MSVC instead of link.exe (zero extra installs). +# On Rust 1.90+, x86_64-unknown-linux-gnu already defaults to rust-lld; `-C linker-features=+lld` +# remains unstable on Rust 1.99.1, so Linux and macOS use their toolchain defaults. +[target.x86_64-pc-windows-msvc] +linker = "rust-lld" + +[target.aarch64-pc-windows-msvc] +linker = "rust-lld" + +# Opt-in local developer shortcuts (default-members fast paths and wasm/webgl checks). +[alias] +lint = "clippy --lib --bins --tests" +lint-all = "clippy --workspace --all-targets" +check-wasm = "check -p rune --no-default-features --target wasm32-unknown-unknown" +check-webgl = "check -p rune --no-default-features --features webgl --target wasm32-unknown-unknown" +test-fast = "test -p rune -p rune-mermaid -p rune-kit --features rune-kit/markdown,rune-kit/mermaid" diff --git a/app/vendor/rune/.gitattributes b/app/vendor/rune/.gitattributes new file mode 100644 index 0000000..b6df287 --- /dev/null +++ b/app/vendor/rune/.gitattributes @@ -0,0 +1,17 @@ +# Text Rune compiles in, hashes or runs is LF in every checkout, whatever core.autocrlf says: the +# precompiled shaders are keyed to the WGSL's bytes (crates/rune/build.rs also reads CRLF as LF, +# for checkouts made before this file), and a shell script with CRLF doesn't run. +*.wgsl text eol=lf +*.luau text eol=lf +*.json text eol=lf +*.jsonl text eol=lf +*.mmd text eol=lf +*.vert text eol=lf +*.frag text eol=lf +*.sh text eol=lf + +# Precompiled shaders and raw pixel data, never converted. +*.dxbc binary +*.metallib binary +*.rgba binary +*.bin binary diff --git a/app/vendor/rune/.github/release/cloudflare-token.sh b/app/vendor/rune/.github/release/cloudflare-token.sh new file mode 100644 index 0000000..1a3cbd4 --- /dev/null +++ b/app/vendor/rune/.github/release/cloudflare-token.sh @@ -0,0 +1,110 @@ +#!/usr/bin/env bash +# Mints a short-lived Cloudflare token for the current release job from the token issuer +# (anomalyco/secrets). Run after aws-actions/configure-aws-credentials has assumed +# arn:aws:iam::604439173067:role/github/opencode-release: the Lambda identifies the role from the +# SigV4 signature and mints only the `opencode/release` token. No repo, stage, permission or TTL +# is sent in the request, and the token is pinned to the runner's IP for 30 minutes. +# +# Step-scoped by default: the token goes to $GITHUB_OUTPUT and only steps that list +# `CLOUDFLARE_API_TOKEN: ${{ steps..outputs.token }}` in their env receive it. +set -euo pipefail +set +x + +url=${CLOUDFLARE_TOKEN_URL:-https://kjivkui2evldapbok5fhrrl6oy0fctkp.lambda-url.us-east-1.on.aws/} +account=${CLOUDFLARE_ACCOUNT_ID:-15d29c8639fd3733b1b5486a2acfd968} + +# One argv value, never a line in curl's config: a newline in an override must not be able to +# inject curl options or move the AWS credentials into Basic auth. +url_pattern='^https://[a-z0-9]+\.lambda-url\.us-east-1\.on\.aws/$' +if ! [[ "$url" =~ $url_pattern ]]; then + echo "::error::CLOUDFLARE_TOKEN_URL is not the token issuer's function URL." >&2 + exit 1 +fi +case "$account" in + *[!0-9a-f]*|"") + echo "::error::CLOUDFLARE_ACCOUNT_ID must be a 32-character lowercase hex id." >&2 + exit 1 + ;; +esac +if [ ${#account} -ne 32 ]; then + echo "::error::CLOUDFLARE_ACCOUNT_ID must be a 32-character lowercase hex id." >&2 + exit 1 +fi +for name in AWS_ACCESS_KEY_ID AWS_SECRET_ACCESS_KEY AWS_SESSION_TOKEN; do + if [ -z "${!name:-}" ]; then + echo "::error::$name is not set; run aws-actions/configure-aws-credentials first." >&2 + exit 1 + fi +done + +# The response is captured, never streamed: it contains the token. AWS credentials go to curl +# through stdin, not argv, so they stay out of `ps` and any trace of this script. +response=$( + printf 'user = "%s:%s"\nheader = "x-amz-security-token: %s"\n' \ + "$AWS_ACCESS_KEY_ID" "$AWS_SECRET_ACCESS_KEY" "$AWS_SESSION_TOKEN" | + curl --config - \ + --proto '=https' --proto-redir '=https' \ + --aws-sigv4 "aws:amz:us-east-1:lambda" \ + --request POST --url "$url" \ + --fail-with-body --silent --show-error --max-time 20 +) + +token=$(printf '%s' "$response" | jq -er 'if (.token | type) == "string" then .token else error("token") end' 2>/dev/null) +expires=$(printf '%s' "$response" | jq -er 'if (.expires_on | type) == "string" then .expires_on else error("expires_on") end' 2>/dev/null) + +# Validate before any output. No error below includes the token value. +case "$token" in + ""|*[[:space:]]*) + echo "::error::The token issuer returned an invalid token." >&2 + exit 1 + ;; +esac +if [ ${#token} -lt 8 ] || [ ${#token} -gt 512 ]; then + echo "::error::The token issuer returned an invalid token length." >&2 + exit 1 +fi +case "$expires" in + ""|*[[:space:]]*) + echo "::error::The token issuer returned an invalid expires_on." >&2 + exit 1 + ;; +esac +iso_pattern='^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}(\.[0-9]+)?Z$' +if ! printf '%s' "$response" | jq -e --arg re "$iso_pattern" '(.expires_on | type) == "string" and (.expires_on | test($re))' > /dev/null; then + echo "::error::The token issuer returned an invalid expires_on." >&2 + exit 1 +fi +if ! [[ "$expires" =~ $iso_pattern ]]; then + echo "::error::The token issuer returned an invalid expires_on." >&2 + exit 1 +fi + +# GitHub masks the exact string everywhere after this, including accidental traces and our own +# error messages. This is the first output that contains it. +printf '::add-mask::%s\n' "$token" + +if [ -n "${GITHUB_OUTPUT:-}" ]; then + { + printf 'token=%s\n' "$token" + printf 'expires_on=%s\n' "$expires" + } >> "$GITHUB_OUTPUT" +elif [ -n "${GITHUB_ENV:-}" ]; then + printf 'CLOUDFLARE_API_TOKEN=%s\n' "$token" >> "$GITHUB_ENV" +fi + +# Verify immediately, with the token on curl's stdin rather than argv. A runner whose Cloudflare +# egress address differs from the address Lambda saw (IPv4 vs IPv6, or a different NAT address) +# fails here instead of part way through an upload. +verify_url="https://api.cloudflare.com/client/v4/accounts/$account/tokens/verify" +if ! verify=$(printf 'header = "Authorization: Bearer %s"\nurl = "%s"\n' "$token" "$verify_url" | + curl --config - --proto '=https' --proto-redir '=https' --silent --show-error --fail-with-body --max-time 20); then + echo "::error::Cloudflare rejected the freshly minted token. The runner's egress IP to Cloudflare may differ from the IP Lambda saw (IPv4 vs IPv6 or a different NAT address). Use a runner with stable egress." >&2 + exit 1 +fi + +if ! printf '%s' "$verify" | jq -e '.success == true and .result.status == "active"' > /dev/null; then + echo "::error::Cloudflare did not report the freshly minted token as active." >&2 + exit 1 +fi + +echo "::notice::Cloudflare token ready; expires $expires" diff --git a/app/vendor/rune/.github/workflows/file-size.yml b/app/vendor/rune/.github/workflows/file-size.yml new file mode 100644 index 0000000..d1e86ab --- /dev/null +++ b/app/vendor/rune/.github/workflows/file-size.yml @@ -0,0 +1,23 @@ +name: file size + +# The Rust file-size and folder-shape check (scripts/file-size.sh), per pull request and per push +# to dev: a few seconds on Linux. It ran inside macos-tests.yml until that moved to a schedule. +on: + push: + branches: [dev] + pull_request: + types: [opened, synchronize, reopened, ready_for_review] + +permissions: + contents: read + +concurrency: + group: file-size-${{ github.ref }} + cancel-in-progress: true + +jobs: + size: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v5 + - run: bash scripts/file-size.sh diff --git a/app/vendor/rune/.github/workflows/macos-tests.yml b/app/vendor/rune/.github/workflows/macos-tests.yml new file mode 100644 index 0000000..62259e3 --- /dev/null +++ b/app/vendor/rune/.github/workflows/macos-tests.yml @@ -0,0 +1,74 @@ +name: macOS tests + +# On a schedule and on request, never per pull request or per push (the owner's decision, +# 2026-11-12): the test job takes over an hour on a Mac runner, Mac runners are scarce and shared +# across the organisation, and changes merge straight after their pull request, so a run per +# change (twice: the pull request, then the push to dev) was mostly cancelled or ignored. Every six +# hours, `changes` (a Linux job) starts the Mac job only when dev is on a commit no run has tested +# to the end yet; workflow_dispatch always tests. The Rust file-size check that also ran here +# runs per pull request in file-size.yml. +on: + schedule: + - cron: "41 */6 * * *" + workflow_dispatch: + +permissions: + contents: read + actions: read + +# One run at a time: a newer run cancels an older one still testing. +concurrency: + group: macos-tests + cancel-in-progress: true + +jobs: + changes: + runs-on: ubuntu-latest + outputs: + test: ${{ steps.check.outputs.test }} + steps: + - id: check + env: + GH_TOKEN: ${{ github.token }} + EVENT: ${{ github.event_name }} + SHA: ${{ github.sha }} + REPO: ${{ github.repository }} + RUN_ID: ${{ github.run_id }} + run: | + # The commit the last run that finished its tests (green or red) tested: rerunning the + # same commit tells nothing new. A cancelled run doesn't count. + last=$(gh api "repos/$REPO/actions/workflows/macos-tests.yml/runs?branch=dev&per_page=50" \ + --jq "[.workflow_runs[] | select(.id != $RUN_ID and (.conclusion == \"success\" or .conclusion == \"failure\"))][0].head_sha // empty" || true) + if [ "$EVENT" = schedule ] && [ "$last" = "$SHA" ]; then + echo "test=false" >> "$GITHUB_OUTPUT" + echo "dev is still at ${SHA:0:9}, which the last run tested." >> "$GITHUB_STEP_SUMMARY" + else + echo "test=true" >> "$GITHUB_OUTPUT" + fi + + test: + needs: changes + if: needs.changes.outputs.test == 'true' + runs-on: blacksmith-6vcpu-macos-latest + timeout-minutes: 90 + env: + # One job per core: serial builds ran past the timeout with no cache, so no cache was ever saved. + CARGO_BUILD_JOBS: 3 + CARGO_INCREMENTAL: 0 + CARGO_PROFILE_TEST_DEBUG: 0 + CARGO_PROFILE_TEST_STRIP: debuginfo + steps: + - uses: actions/checkout@v5 + - uses: Swatinem/rust-cache@v2 + with: + cache-on-failure: true + # The virtual Metal adapter does not expose TIMESTAMP_QUERY. Keep the + # shader freshness, pipeline, rendering, font and menu tests enabled. + - run: >- + cargo test -p rune -p rune-core -p rune-edit -p rune-gpu -p rune-image -p rune-media -p rune-spell -p rune-text -p rune-kit + --features rune/test-gpu-counters,rune-gpu/test-gpu-counters,rune-kit/markdown,rune-kit/mermaid --no-fail-fast -- + --skip metal::compute_tests::passes_sample_timestamps_at_their_boundaries + # Kept outside the main invocation above so rune-ref (`libm/force-soft-floats`, `serde/derive`) + # and rune-i18n (`icu_provider/sync`) do not alter the core feature set. + - run: cargo test -p rune-ref + - run: cargo test -p rune-i18n diff --git a/app/vendor/rune/.github/workflows/site.yml b/app/vendor/rune/.github/workflows/site.yml new file mode 100644 index 0000000..0864652 --- /dev/null +++ b/app/vendor/rune/.github/workflows/site.yml @@ -0,0 +1,50 @@ +name: site + +# Deploys the docs site in site/. dev deploys https://dev.anoma.ly/team/rune, production deploys https://anoma.ly/team/rune. +on: + push: + branches: [dev, production] + paths: + - "site/**" + - ".github/workflows/site.yml" + +concurrency: + group: site-${{ github.ref_name }} + cancel-in-progress: false + +permissions: + contents: read + +jobs: + deploy: + runs-on: ubuntu-latest + environment: ${{ github.ref_name == 'dev' && 'dev' || 'release' }} + permissions: + id-token: write + contents: read + defaults: + run: + working-directory: site + steps: + - uses: actions/checkout@v5 + - name: Configure AWS credentials + uses: aws-actions/configure-aws-credentials@e1253824e5c10ff9df46874f81ed3ec929e19cfd # v6.3.0 + with: + role-to-assume: arn:aws:iam::604439173067:role/github/rune-${{ github.ref_name == 'dev' && 'dev' || 'release' }} + role-session-name: site-${{ github.run_id }} + aws-region: us-east-1 + - uses: actions/setup-node@v5 + with: + node-version: 22 + - uses: oven-sh/setup-bun@v2 + - run: bun install --frozen-lockfile + - name: Cloudflare token + id: cloudflare-token + run: bash "$GITHUB_WORKSPACE/.github/release/cloudflare-token.sh" + env: + CLOUDFLARE_TOKEN_URL: ${{ vars.CLOUDFLARE_TOKEN_URL }} + CLOUDFLARE_ACCOUNT_ID: ${{ vars.CLOUDFLARE_ACCOUNT_ID }} + - run: bun run deploy:${{ github.ref_name == 'production' && 'production' || 'dev' }} + env: + CLOUDFLARE_API_TOKEN: ${{ steps.cloudflare-token.outputs.token }} + CLOUDFLARE_ACCOUNT_ID: ${{ vars.CLOUDFLARE_ACCOUNT_ID }} diff --git a/app/vendor/rune/.github/workflows/www.yml b/app/vendor/rune/.github/workflows/www.yml new file mode 100644 index 0000000..2293449 --- /dev/null +++ b/app/vendor/rune/.github/workflows/www.yml @@ -0,0 +1,129 @@ +name: www + +# The public page in www/ is the Rune app in www/app. CI builds it to wasm, has the native build write its static +# HTML (`--html`), and deploys: dev to https://dev.anoma.ly/rune, production to https://anoma.ly/rune. Rune itself is +# the page, so a push that changes crates/ deploys it too. Pull requests build the dev page and deploy nothing, and +# only for a change to the page's own files: a change to crates/ merges straight after its pull request, and the +# push to dev builds it then, so building it twice told nothing. A newer push to dev replaces a dev deploy still +# running; production always finishes. +on: + push: + branches: [dev, production] + paths: + - "www/**" + - "crates/**" + - "scripts/web-build.sh" + - "Cargo.toml" + - "Cargo.lock" + - "rust-toolchain.toml" + - ".github/workflows/www.yml" + pull_request: + paths: + - "www/**" + - "scripts/web-build.sh" + - "rust-toolchain.toml" + - ".github/workflows/www.yml" + +concurrency: + group: www-${{ github.head_ref || github.ref_name }} + cancel-in-progress: ${{ github.ref_name != 'production' }} + +permissions: + contents: read + +env: + BINARYEN_VERSION: "133" + MODE: ${{ github.ref_name == 'production' && 'production' || 'dev' }} + CARGO_INCREMENTAL: "0" + +jobs: + build: + runs-on: ubuntu-latest + environment: ${{ github.ref_name == 'dev' && 'dev' || 'release' }} + permissions: + id-token: write + contents: read + defaults: + run: + working-directory: www + steps: + - uses: actions/checkout@v5 + # Pull requests build and deploy nothing, so they never assume the role. + - name: Configure AWS credentials + if: github.event_name == 'push' + uses: aws-actions/configure-aws-credentials@e1253824e5c10ff9df46874f81ed3ec929e19cfd # v6.3.0 + with: + role-to-assume: arn:aws:iam::604439173067:role/github/rune-${{ github.ref_name == 'dev' && 'dev' || 'release' }} + role-session-name: www-${{ github.run_id }} + aws-region: us-east-1 + # rust-toolchain.toml picks the toolchain. rust-src is installed up front: otherwise rustup fetches it mid-build + # from parallel rustc calls, which race and fail. + - name: Rust toolchain + working-directory: . + run: | + rustup toolchain install + rustup target add wasm32-unknown-unknown + rustup component add rust-src + - uses: Swatinem/rust-cache@v2 + with: + shared-key: www + save-if: ${{ github.event_name == 'push' }} + - name: wasm-bindgen version from Cargo.lock + id: bindgen + working-directory: . + run: echo "version=$(grep -A1 '^name = "wasm-bindgen"$' Cargo.lock | sed -n 's/^version = "\(.*\)"/\1/p')" >> "$GITHUB_OUTPUT" + - uses: taiki-e/install-action@v2 + with: + tool: wasm-bindgen@${{ steps.bindgen.outputs.version }} + - uses: actions/cache@v4 + id: binaryen + with: + path: ~/.binaryen + key: binaryen-${{ env.BINARYEN_VERSION }} + - name: Install binaryen + if: steps.binaryen.outputs.cache-hit != 'true' + run: | + mkdir -p ~/.binaryen + curl -fsSL "https://github.com/WebAssembly/binaryen/releases/download/version_$BINARYEN_VERSION/binaryen-version_$BINARYEN_VERSION-x86_64-linux.tar.gz" \ + | tar -xz -C ~/.binaryen --strip-components=1 + - run: echo "$HOME/.binaryen/bin" >> "$GITHUB_PATH" + - uses: oven-sh/setup-bun@v2 + - run: bun install --frozen-lockfile + # The native app (tests and the `--html` export) links winit's keyboard library. Its packages are cached, so a + # run doesn't need the Ubuntu mirrors (on 2026-11-11 the runners couldn't resolve them for over an hour, and + # every run failed here); a run that must fetch them retries. + - uses: actions/cache@v4 + id: debs + with: + path: ~/.debs + key: debs-libxkbcommon-${{ runner.os }}-${{ runner.arch }}-${{ env.ImageOS }} + - name: Native libraries + run: | + if [ "${{ steps.debs.outputs.cache-hit }}" != true ]; then + mkdir -p ~/.debs + for attempt in 1 2 3; do + sudo apt-get -o Acquire::Retries=3 update && + (cd ~/.debs && apt-get -o Acquire::Retries=3 download libxkbcommon-dev libxkbcommon0) && break + [ "$attempt" = 3 ] && exit 1 + sleep $((attempt * 20)) + done + fi + sudo dpkg -i ~/.debs/*.deb + - name: Test the page + working-directory: . + run: cargo test -p rune-www + - name: Build + run: bun run build --mode "$MODE" + - name: Cloudflare token + id: cloudflare-token + if: github.event_name == 'push' + run: bash "$GITHUB_WORKSPACE/.github/release/cloudflare-token.sh" + env: + CLOUDFLARE_TOKEN_URL: ${{ vars.CLOUDFLARE_TOKEN_URL }} + CLOUDFLARE_ACCOUNT_ID: ${{ vars.CLOUDFLARE_ACCOUNT_ID }} + - name: Deploy + if: github.event_name == 'push' + run: bunx cf deploy --prebuilt --mode "$MODE" + env: + CLOUDFLARE_API_TOKEN: ${{ steps.cloudflare-token.outputs.token }} + CLOUDFLARE_ACCOUNT_ID: ${{ vars.CLOUDFLARE_ACCOUNT_ID }} diff --git a/app/vendor/rune/.gitignore b/app/vendor/rune/.gitignore new file mode 100644 index 0000000..4104000 --- /dev/null +++ b/app/vendor/rune/.gitignore @@ -0,0 +1,17 @@ +target/ +perf/autoresearch/ +perf/kit-diff/ +perf/live-values/ +perf/live-edit/ +/REVIEW-TO-PARENT.md +*-FROM-PARENT.md +.DS_Store +demo/**/*.mp4 +demo/**/*-strip.png +!demo/fx/glow-strip.png +!demo/fx/motion-quarter-speed.mp4 +!demo/opencode/switch-strip.png +/captures/ +/.lab-output/ +__pycache__/ +*.pyc diff --git a/app/vendor/rune/AGENTS.md b/app/vendor/rune/AGENTS.md new file mode 100644 index 0000000..f14496b --- /dev/null +++ b/app/vendor/rune/AGENTS.md @@ -0,0 +1,71 @@ + +# Rune + +A Rust GPU UI framework (wgpu, winit) for apps that feel like SwiftUI on iOS at 120 Hz on Mac, Windows, Linux, web and iOS. Views are plain Rust. Apps pin `dev` revs. + +## Layout + +- Core crates: `crates/rune`: layout, runtime, renderer, windows, overlays, dev tooling. `crates/rune-core`: foundation primitives (colour, tokens, themes, shapes, state machines, clocks, tasks, tracked reads, growth, live values, latest-wins requests, marks, dirs, prefs; no GPU or windowing). `crates/rune-gpu`: GPU adapter selection, backend dispatch, device error logging, native Apple Metal backend and analytic GPU springs. `crates/rune-image`: content-addressed image decoding, linear-light mips, pixel buffers, SVG/AVIF codecs, OS app icons and placement math. `crates/rune-spell`: platform spellchecking (Windows `ISpellChecker`, macOS `NSSpellChecker`, web Hunspell). `crates/rune-media`: video and audio playback, zero-copy native surfaces (IOSurface, D3D shared textures, dmabufs), and audio recording. `crates/rune-text`: text shaping, layout, font discovery, glyph rasterization and icons. `crates/rune-edit`: the text editing model (`TextEdit`, keys and modifiers, IME composition, undo history, rich text and its HTML form). `crates/rune-motion`: springs and transitions. +- Layering: `rune-motion`, `rune-staging` and `rune-taffy` have no Rune dependencies; `rune-core` depends on `rune-motion`; `rune-gpu` depends on `rune-motion` (and `rune-staging` under `metal-backend`); `rune-image` and `rune-spell` depend on `rune-core`; `rune-text` depends on `rune-core`, `rune-image` and `rune-motion`; `rune-edit` depends on `rune-core` and `rune-text`; `rune-media` depends on `rune-core`, `rune-gpu`, `rune-image` and `rune-staging`; `crates/rune` depends on all of them (plus optional `procwatch`) and re-exports their public APIs so apps depend on `rune` only. Above `rune` sit `rune-kit` (also `rune-motion` and optional `rune-highlights`, `rune-mermaid`), `rune-mermaid`, `rune-knobs`, `rune-luau` and optional `rune-ref`; beside it sit `rune-fx` (`rune-motion`, `rune-staging`), `rune-light` (`rune-staging`), `rune-mac` (`rune-notify`) and `rune-perf` (`procwatch`). +- Companion crates: `crates/rune-kit`: components. `crates/rune-mermaid`: Mermaid diagrams (flowcharts, sequence and state diagrams). `crates/rune-i18n`: message catalogs generated from JSON, CLDR plurals and numbers, the system's languages. `crates/rune-fx`, `crates/rune-light`: effects. `crates/rune-ref`: reference renderer. `crates/procwatch`: an app's own memory and CPU (footprint, counting allocator, gauges, warnings, loopback JSON); libc only, no Rune dependency. +- `examples/`: apps and labs. `themes/`: themes. `site/`: the docs site (see `site/README.md`). +- `vendor/winit`: winit as published plus `vendor/winit.patch` (Windows: no TaskbarList COM call when a window is made, and system DLLs loaded with `LOAD_LIBRARY_SEARCH_SYSTEM32`; and `WindowExtWayland::content_corner_radius`, the radius a client-side frame leaves the content's bottom corners to), through `[patch.crates-io]`. When winit is bumped, run `scripts/vendor-winit.sh ` (Git Bash on Windows) and update the `[patch.crates-io]` rev in apps that build Rune. +- `vendor/sctk-adwaita`: sctk-adwaita as published plus `vendor/sctk-adwaita.patch` (the client-side frame's one-point border follows the window's rounded bottom corners, and `content_corner_radius` says what radius the content leaves them), through `[patch.crates-io]`. When it is bumped, run `scripts/vendor-sctk-adwaita.sh ` (Git Bash on Windows) and update the `[patch.crates-io]` rev in apps that build Rune. +- `vendor/tiny-skia-path`: tiny-skia-path as published plus `vendor/tiny-skia-path.patch` (Skia's own conic splitting and stroker steps, so icons stroke as Chromium's Skia strokes them), a plain path dependency of `crates/rune-text`, not a patch (resvg keeps the published one). When it is bumped, run `scripts/vendor-tiny-skia-path.sh ` (Git Bash on Windows). +- `vendor/wgpu-hal`: wgpu-hal as published plus `vendor/wgpu-hal.patch` (`dx12::Instance::expose_adapter`, FXC loaded on first compile, and Windows system DLLs loaded with `LOAD_LIBRARY_SEARCH_SYSTEM32`), through `[patch.crates-io]`. When wgpu is bumped, run `scripts/vendor-wgpu-hal.sh ` (Git Bash on Windows) and update the `[patch.crates-io]` rev in apps that build Rune. +- `PLAN.md`: direction and milestones. `research/`: notes behind decisions. `demo/`: images the docs show. + +## Commands + +- `cargo test -p rune -p rune-mermaid -p rune-kit --features rune-kit/markdown,rune-kit/mermaid` +- `cargo check --workspace --all-targets` +- `bash scripts/check-local.sh` runs opt-in local checks (file sizes, folder shape, public-repo hygiene, `cargo check`, `cargo clippy --lib --bins`; supports `--wasm`, `--all`, `--tests`). +- Cargo aliases in `.cargo/config.toml`: `cargo lint`, `cargo lint-all`, `cargo check-wasm`, `cargo check-webgl`, and `cargo test-fast`. +- Tests that count GPU work or need wgpu's no-op backend are behind features so plain builds don't compile those backends: add `--features rune/test-gpu-counters,rune-gpu/test-gpu-counters` (and `rune/test-gpu-noop` on Linux) to run them. `rune-ref` and `rune-i18n` are not default members: test them with `-p`. +- Tests run in debug. `--release` is incremental, for looking at an app. Benchmarks use `--profile perf`; the runtime bench scripts refuse other builds. +- CI's macOS tests (`.github/workflows/macos-tests.yml`) run on a schedule and on `workflow_dispatch`, not per pull request or push: the owner's decision on 2026-11-12. Don't add those triggers back; run the workflow by hand when a change needs it. + +## Changes + +- Work on `dev`. `production` deploys the site. +- `dev` is fast-forward-only: never force-push or rewrite it. Apps pin its revs, so a rewrite breaks every app's build on a clean fetch. +- For any change that can move an app's output or break its build, add `changelog/unreleased/-.md` with one top-level bullet, in the style of the `CHANGELOG.md` entries. `scripts/changelog-fold` folds them into `## dev`. +- Keep Rust files under 800 non-test lines (`#[cfg(test)]` code excluded); 1,500 is a hard cap. The point is to stop god files and edit collisions, not to chop a file that reads fine as one piece. Older files over the cap are listed in `scripts/file-size-exceptions.txt` with ceilings that only go down. Run `scripts/file-size.sh` to check. +- Keep folders shaped by capability: `x.rs` or `x/` beside two or more `x_*.rs` (or three or more `x_*.rs` alone) means move them into `x/`; a folder over 40 source files warns and over 60 is an error (tests aren't counted; `examples/`, `benches/` and `bin/` are skipped). `scripts/folder-shape.sh` runs inside `scripts/file-size.sh`; old violations are in `scripts/folder-shape-exceptions.txt` with ceilings that only go down. +- Put tests in a sibling `tests.rs` or `*_tests.rs`, and keep any test file or module under 1,000 lines. +- Before adding to a file over the cap, move the area you touch into its own module, in its own PR. +- A feature owns its state, keys and registrations so it plugs in with one line. New runtime state goes in the owning subsystem's struct, not a flat `Runtime` field. +- In `lib.rs`, keep `mod` and `pub use` lists one item per line, sorted. +- Apps build these types as literals, so adding a pub field breaks them: `AppSpec`, `Env`, `Elevation`, `PaletteSeed`, `OverlaySpec`, `TextStyle`, `RunOptions`, `ScrollSpec`, `Span`, `ByteFrame`, `SurfaceDraw`, `LayerSpec`. Add a builder method instead. + +## State + +- Behaviour with modes or phases (hover delays, drags, IME composition, scroll modes, requests and retries) is an explicit state machine: one `enum State` whose variants carry only the data valid in them, and one `fn step(state: &mut State, event: Event) -> Effects` (`rune::machine`) that returns effects instead of performing them. No clusters of booleans, `Option`s and timestamps whose combinations encode the mode. +- Timers are events: a timed variant stores its `Attempt` and due time on `Tx::clock`/the runtime clock, the caller turns its effect into `Tx::wake_at`, and `poll` (or the runtime's frame) feeds the timer back into `step`. An answer whose attempt the state no longer holds changes nothing. + +## Performance + +App-side rules live in "Launching fast" in `crates/rune/README.md` and the "Launch fast" docs page. In examples and in Rune itself: + +- Start slow work (network, indexing, status items) from `on_ready`, after the first frame. Land state that arrives just after launch with `tx.instant()`, so the first second stays still. +- `poll` returns true only when visible state changed, and a loop stops asking for frames when its work ends. An idle window draws nothing. +- Read sizes with `Cx::layout_size` or `Cx::layout_with`, not whole rects, so a scroll doesn't rebuild the view every frame. A handler that only moves a live value (scroll, zoom, a transform) calls `Tx::live_only()`. +- Build only mounted rows: `virtual_rows`, with row content built inside its closure; `memo` for rows that rarely change. +- Bound every cache in entries and in bytes, counting decoded pixels, not encoded size. +- Take numbers from `--profile perf`. Compare paired, alternating runs by median, keep outliers, and say what a headless number leaves out (GPU upload, presentation). +- A motion change passes `scripts/motion-audit` with its scenario added. Fix a finding in Rune rather than allowing it. +- No file I/O in the frame loop: never read, stat, write, sync or rename a file on the UI thread during frames, input or animation. On Windows each open and `MoveFileExW` rename runs antivirus filter callbacks and can fail with a sharing violation. +- No background rewrite churn: diagnostics and logs (`rune-perf`, traces) keep one open handle and write a summary on an incident or at shutdown, never on a repeating timer while idle. +- Keep persistence APIs free of `std::fs` and `PathBuf` so `wasm32` targets can back them with browser storage. + +## This repo is public + +Everything pushed stays public in history. Before committing, run `git diff --cached | rg -n '/Users/|/private/var/|\.ts\.net|ses_[A-Za-z0-9]{20}'` and keep these out: + +- secrets, tokens and credential file contents; +- home folder and temp paths, machine names and tailnet hostnames. Write repo-relative paths, and use `host.example.ts.net` in tests; +- session IDs, chat or Slack links, and quotes from private sessions, chats or calls; +- teammates' names attached to their plans, opinions or internal discussions, and private repos or branches; +- quotes of, or citations to, internal guides and rules. Say what the code does and why on its own terms; +- agent handoff notes (`REVIEW-TO-PARENT.md` and similar), raw evidence, logs and benchmark dumps; +- generated videos and strips nothing links to. Commit the stills a doc shows. diff --git a/app/vendor/rune/CHANGELOG.md b/app/vendor/rune/CHANGELOG.md new file mode 100644 index 0000000..35cebf5 --- /dev/null +++ b/app/vendor/rune/CHANGELOG.md @@ -0,0 +1,3239 @@ +# Changelog + +Rune has no releases yet; consumers pin `dev` revs. This lists changes that can move an app's output +without a code change (goldens, layout, input), newest first, with the rev that introduced each. + +## dev + +- `RollingText` now remembers at most 512 labels (and 256 KiB of text) per thread, dropping the least recently built; a label that comes back after that starts its roll over (t841). + +- Docs: a "Fast apps" page (rules with before and after snippets, the memo lesson) and `scripts/app-audit `, a quick grep for the slow patterns it lists; no API change. + +- **`Tx::scroll_center` and `Tx::scroll_center_in` reveal and vertically centre elements, virtual + rows and `TextHighlight`s.** Passing `"row/mark"` mounts an unrealized virtual row `row` first + and centres `mark` inside it, gliding on the scroll spring (`scroll_center_instant` and + `scroll_center_in_instant` jump, as `Tx::instant` does). A centring sent mid-glide keeps the + glide's speed without carrying past its new stop. `Tx::scroll_into_view` takes `"row/mark"` + too, and `Tx::scroll_key_to` also resolves `TextHighlight` keys. + +- **`Cx::layout` and `Cx::layout_with` read an element inside `virtual_rows` (or `virtualize`) + where it draws.** With rows culled above the mounted window, the rect read was the culled + rows' height too far down. + +- A `Tx::launch` flight re-aimed mid-flight (its row or an ancestor moved) keeps the speed it was drawn moving at, including the part a scroll view's correction under it added, instead of slowing for a frame and picking up again. `Scene::shift_travel`, which nothing called, is replaced by `Scene::retarget_drawn`, a `set_frame` that starts the new path where the renderer draws the node and at the speed it's drawn moving. The motion audit reports such a one-frame speed dip as `stall`. + +- A `memo` hit no longer deep-clones its subtree: the cached subtree is shared, its flattened nodes and layout subtree are reused when its parent didn't change, and apply skips unchanged reused subtrees. On a chat-sized test window, a keystroke's commit takes about half the CPU and 79% fewer bytes. No API change. + +- Growth stacks: a row that moves to a new place and changes height in the same animated commit now slides from where it was drawn, instead of stepping by its height change on the commit's frame. A `Tx::launch` flight whose row (or an ancestor) is moved mid-flight now heads for the new place from where it was drawn, instead of jumping by the move. And when a commit changes the padding, gap or margin above a row's contents (a row that stops sitting close to the one above it), those contents slide from where they were drawn; a sibling's new size still moves the contents under it at once. + +- **`Tx::keep_on_screen` holds a stuck header in place.** Shutting a group from its `sticky_top` header while the header is stuck (for example in a `stick_bottom` timeline scrolled into a group taller than the view) keeps the header where it's drawn for the whole commit, and the rows below fold up to it on the growth spring. Before, the header unstuck as its group shrank, the scroll jumped to bring it back, and the rows below dipped hundreds of points while the group's first rows flashed for a frame. Anchors that aren't stuck behave as before. + +- **`Latest` gains `set_waker`, `request_if_changed` and `request_opt`.** `set_waker` attaches the waker in `setup` to a `Latest::default().debounce(..)` built in `init`, keeping its debounce, pending request and answer. `request_if_changed(&key, work)` (`K: Clone + PartialEq`) does nothing when the key equals the last such request's, so `poll` can call it every time without restarting work; `request`, `request_opt` and `cancel` forget the key. `request_opt` takes work returning `Option`: `None` lands nothing and doesn't wake the window, but still supersedes older requests. + +- `El::anchored` overlays draw at their anchor's zoom: inside a subtree drawn at `El::scale(1.6)`, a popover and its text draw at 1.6 (crisp once still) beside where the anchor draws, growing away from it, with the gap zoomed and flipping, `anchored_fit` and hit testing on the drawn size. An overlay with its own `El::scale` keeps it instead of the inherited zoom, so popovers already wrapped in `.scale(zoom)` by hand don't zoom twice. One that scales a child inside it instead needs `El::anchored_unscaled()`, which keeps an overlay at window scale. + +- `El::help_when_truncated` now shows its tooltip when an `El::truncate_fade` text runs past its box, as it does for `truncate` and `max_lines`, so a faded label no longer needs a "…" to get its tooltip. The fade still draws no ellipsis. + +- **`rune::Latest`: latest-wins background requests.** `Latest::new(waker)` (the `setup` + waker), optionally `.debounce(wait)`; `request(key, |key| work(key))` from a handler runs the + work on a small shared worker pool (up to four threads, which exit when idle) and supersedes + every earlier request: one not yet started never runs, and a stale answer is dropped even when + it finishes last. The landed answer wakes the window once and `take()` returns it once, so + `poll` returns true only when it changed. `cancel()` and dropping the `Latest` stop its + requests; `is_pending()` drives a spinner. On the web the work runs on the main thread from + `spawn_local`. The debug stall warning points here. + +- A drag in a selection group reaches only text that shows: text clipped out of sight but laid out under the words (a folded part above them) no longer takes the drag, which selected everything between it and the press. + +- Growth stacks and virtual lists: rows an animated commit puts in a new order slide from where they were drawn into their new places on the layout spring (or the transaction's motion), instead of jumping there in one frame. Only rows whose order changed move; inserts, removals, window shifts, instant commits, Reduce Motion and rows out of sight before and after still land as before. A virtual list read from its top no longer re-anchors to the row that moved. + +- **Typing or streaming into a text no longer fills the layout cache with each edit's copy.** + The cache kept every version of an edited paragraph as a stale layout until its budget ran + out: about 100 copies, over 3 MB, of a 600-byte paragraph being typed into, pushing out the + layouts of views that would be shown again. When a node's text changes into an edit of + itself (most of it shared at the start and end), the old version's layouts now go at the end + of that commit unless another node still shows them; text replaced by something unrelated, + as a reader switching notes, stays cached for when it comes back. The stale budget is now + counted in estimated heap bytes (3 MB) rather than bytes of text. + +- **Resizing a window lays the last tree out again instead of running the view.** When only + the viewport changed since the last commit (same state, scale and env, no layout or caret + read that moved), a commit re-solves layout on the nodes it already has and re-breaks their + text at the new widths, skipping the view and flattening. A view that reads layout + (`Cx::layout`, `Cx::layout_size`), the caret, a breakpoint or the env still runs when what it + read changes. Virtual lists keep their mounted rows and lay them out again; the view runs + only when the viewport nears the edge of the mounted rows, or rows outside the overscan add + up to more than a viewport. A notes-sized Markdown page resizes in 2.5 ms per step, down from + 3.6 ms, with 42% fewer allocations; a virtual list of Markdown rows in 0.62 ms, down from 0.82. + +- **A dimmed box with a solid fill fades as CSS `opacity` does.** `El::dim`, which disabled + kit controls use, no longer lets the box's outer shadows show through its faded fill, and + a fill under a gradient (a contrast button's sheen) fades with it as one, still without a + layer. A disabled contrast button on white now paints the browser's light grey (about 176 + instead of 159 mid-height with the OpenCode theme), and a disabled neutral button no longer + shows its drop shadow through. A crisp offset shadow under a native material, backdrop blur + or dimmed box now leaves the interior clear too. + +- **Resizable playground columns** (`Playground::widths`): the story list and the right-hand controls column in `App::playground` drag by their separator edges to resize and double-click back to their default widths, persisted in `Prefs` by default for windowed apps or through `Playground::widths(load, save)`. + +- **Theme colours authored for sRGB blending are painted as authored now that windows blend in + sRGB.** A theme with `"blend": {"mode": "srgb"}`, the OpenCode theme's translucent tokens and + shadows, `Kit::alpha`, `Kit::on` and `Kit::from_palette`'s borders and tints re-solve alpha + only in a window that blends in linear light (`srgb_blend(false)`), so fills, selected rows, + disabled controls and status banners look as they did before the sRGB default instead of + double-compensated. Colours resolve for the blend mode of the window building the view + (`rune::theme::blends_srgb`, `rune::theme::for_blend`, `rune::theme::with_blend`), a live + `Tx::set_srgb_blend` re-resolves them (memoised rows included), and + `rune_theme_opencode::kit` returns the kit for the current mode, so get it in the view. + +- **Debug builds warn about two slow patterns, once per site, on stderr.** A `virtualize` list + handed more than 200 rows and four times what it mounts names its path and `.virtualize` call + site and points to `El::virtual_rows`, which builds only the mounted rows. A handler, `poll`, + `update` closure, `init` or `on_ready` that spends over 8 ms on the main thread and over four + times its CPU time warns as "`poll` blocked 263 ms (CPU 2 ms) on the main thread: move IO off + it with `rune::Latest` or a thread". `RUNE_PERF_WARN=0` silences both; release builds contain + neither. On macOS `libc` is now a regular dependency for the thread CPU clock. + +- Text: underlines sit on whole device pixels, and one that ends its line runs to the text box's rounded-up edge, so a link split into an element a word draws one line with no gaps at the spaces. + +- **Elements that never animate keep no motion tracks.** A property gets a track only when its + value first changes, starting from what was last drawn, so a static tree holds none: on a + 60-card settings column (about 5,300 nodes) a commit's apply phase takes about a third less + time and the heap is 12 MB smaller. A node mounted with the first frame has no + `prop::PRESENCE` track until it leaves (`Scene::get` still reads 1.0), and fill, text, + border, shadow, gradient, outline, hover and press follow the same rule, so + `AnimationStore::track_len`, `has` and `get` see only what has moved. A `Scene::set` or + `Scene::animate` that leaves a property where it already rests no longer marks the node + changed. + +- `ElementInfo` implements `Default` (a plain, opaque `el()` at rest) and adds `ElementInfo::stub(key)`, so a test that stands in for `Runtime::elements` can write `ElementInfo { focused: true, ..ElementInfo::stub("send") }` and keep building when Rune adds a field. + +- **`rune::is_headless()`, and `--script` alone runs headless.** `is_headless()` answers from the + process's arguments, parsed once, whether the run renders offscreen, so an app can skip a tray, + global shortcuts or network work before `run` without scanning argv itself; it leaves + `extra_args` for an app that passes `App::args`. A window never replayed a script, so + `--script FILE` without `--snap`, `--video` or another output used to open a real window and + ignore the script; it now replays it headless like `--frames` (`--native` still opens the window). + +- `MenuItem::keys_first()` lets the window's own key handling see a menu item's key equivalent before the item does: the focused element, modals and `on_key` get the press first, and the item runs only if none takes it (picking it in the menu always runs it). Without it AppKit hands the chord to the menu before any view, as before. + +- **`rune::set_app_icon(bytes)` sets the Dock icon from image bytes.** macOS shows an `.icns`, PNG + or any image `NSImage` reads as the app's Dock and app-switcher icon while it runs, so an app no + longer needs its own `NSImage` and `setApplicationIconImage` glue. Call it from any thread, + before `run` (applied once the app finishes launching) or after; it fails on bytes that aren't + an image and does nothing elsewhere or in a headless run. + +- `Transition::none()`, `SpringPair::NONE` and `Spring::NONE` give a node no motion at all: it shows whole the frame it mounts and unmounts the frame after it's removed, focus returns as with any transition, and the rest of the change still animates. A spring of `Spring::NONE` becomes `Curve::Instant`, so Reduce Motion no longer stretches it into a fade the way it does a 0.001 s spring. The split shell's panes use it. + +- **A compositor that asks for `wgpu::Features::IMMEDIATES` can use immediates.** + `Compositor::features` returning `IMMEDIATES` now also raises the device's + `max_immediate_size` to the adapter's (4 KB on Metal), so per-draw values set with + `RenderPass::set_immediates` travel inside the pass instead of in a uniform written through + `Queue::write_buffer` or `Frame::write_buffer`, which costs a macOS overlay frame another + command buffer. + +- **An overlay whose compositor animates over a still view no longer steps or rebuilds the view + each frame.** When the last frame asked for no other and nothing has changed since (no input, + state change, timer, live value, poll or playground), a frame only advances `Runtime::clock` + and `Runtime::t`, then draws the last build again, so a compositor reading the clock still + animates. The macOS overlay frame also waits on its present thread only once a frame is due, + reads the panel's occlusion once per loop turn, and doesn't sample the pointer for a + click-through overlay that follows nothing. + +- On web, `App::canvas_id` mounts onto an existing `` without locking `document.body`, `App::fit_content_height` sizes the canvas to its content height, `OsCursor` and `Tx::set_title` apply, macOS `⌘C`/`⌘A` and synchronous `copy` events work on `El::selectable` text, default web fonts include Inter Medium and SemiBold (with an `embedded-fonts` feature to omit them when `AppSpec::fonts` supplies its own), and a hidden semantic DOM layer mirrors headings, inline links and buttons over the canvas for assistive tech and Find-in-page. + +- **A variable font's hidden axes follow its named instances at the text's weight, as Core Text + draws them.** SF Mono's regular is wght 400 with YAXS 324.3; Rune set only wght, leaving YAXS + at the Light instance's default, so code drew thin horizontal strokes (2% less ink than + CoreText, mean error 0.66 at 2×; now 0.997 ink, 0.14). SF Italic's YAXS follows the same way. + Fonts without hidden axes (Inter, SF upright) draw as before. `coretext_compare --set mono` + measures SF Mono against AppKit's monospaced system font. + +- **Structured communication notes in `rune_kit::notes` (`markdown` feature).** `Note::new(src)` + and `notes::render_note` render `facts`, `compare`, `steps`, `size`, titled/marked code fences + (`title="…" {2-4}`), and `> [!note]` callouts alongside `Markdown` prose, tables and diagrams. + +- **Wayland overlays take right-clicks.** A layer-shell overlay passed on only the left + button, so `on_secondary_press` never fired on an overlay. Its right button now opens the + secondary gesture, as a window's does. + +- **On Linux, Rune draws on the GPU the Wayland compositor uses.** Rune took the lowest-power + adapter, so on a desktop with an integrated GPU beside the discrete card driving the display + (Hyprland on NVIDIA, for one) every window and overlay showed as a black rectangle: the + compositor couldn't show the integrated GPU's buffers. Rune now asks the compositor for its + main device (`zwp_linux_dmabuf_v1` feedback) and takes the adapter on the same PCI device, + falling back to the lowest-power adapter as before, which keeps laptops that drive their panel + from the integrated GPU on it. `WGPU_ADAPTER_NAME` (part of the adapter's name) and + `WGPU_POWER_PREF` (`low`, `high`, `none`) override the choice on every platform. A machine with + more than one GPU prints the choice and its reason to stderr once; `RUNE_GPU_LOG=1` prints it + anywhere. + +- `ConfiguredOverlay::animate_reveal`: showing an overlay no longer settles motion its state started while hidden, so a notification stack's first card plays its enter transition from the first visible frame. Without it an unretained overlay still shows settled. + +- **Text: a glyph no longer lands a pixel off when a colour span splits its line.** The pen is snapped to Parley's 1/256 px grid before it floors to CoreGraphics' subpixel steps, so f32 noise from summing advances in a different order (syntax highlighting, rich text spans) can't tip a glyph onto the next step. + +- **Mermaid flowchart and state edges are smooth curves.** Each edge leaves and enters its nodes + straight along the rank axis, keeps only the layout's bend points it needs to stay clear of + other nodes, labels and subgraph titles, and joins them with cubics, so there are no kinks or + wobbles and arrowheads sit on the line's last tangent. A label breaks the line around it + instead of sitting on a filled chip (a label left on a subgraph's border still gets one). + Hovering a node lights up its edges: `rune_mermaid::render_with_hover` (`Hover::Off`, `Edges`, + `Neighbours`, which also rings the nodes they reach, and a colour), or + `MarkdownStyle::diagram_hover(color, neighbours)`. Each node's hover area is keyed `node{i}`. + +- **`FontSmoothing` picks how text is rasterised: `On` (the macOS default, CoreText with font + smoothing on) or `Off` (the default on Linux, Windows and the web: CoreText with font + smoothing off, as `-webkit-font-smoothing: antialiased` draws).** Both run CoreGraphics' + glyph pipeline; `On` adds font smoothing's dilation. Set it app-wide with + `App::font_smoothing` or `WindowSpec::font_smoothing`, or while running with + `Tx::set_font_smoothing`; each mode keeps its own glyphs in the atlas. Blending is separate + (`srgb_blend`, on by default). `Runtime::set_font_smoothing` and `Runtime::font_smoothing` do + the same for a runtime an app draws itself. +- **Breaking: `FontSmoothing::Calibrated` (Rune's previous rasteriser) is removed, and `MacOS` is + renamed `On`.** Its quarter-pixel pens, 0.1 pt outline + grow and luminance/scale coverage curve are gone, with `rune::text::glyph_coverage_exponent`. + `TextSystem::apple_pipeline` returns an `ApplePipeline` and `TextSystem::set_apple_pipeline` + takes one (no `Option`). The `glyphs_for_layout` and `glyphs_in` `scale` arguments are now + unused. + +- Glyphs rasterize the way CoreText draws them (`FontSmoothing::pipeline`): CoreGraphics' curve flattening, its y autohinter at integer sizes 7–18 px and, for `FontSmoothing::On`, the outline dilation font smoothing applies (radius from the ink's luminance bucket and the ppem, sides and tops grown, bottoms fixed). Masks land within a few levels of CoreGraphics', and glyphs in light and dark ink rasterize separately. `TextSystem::set_font_smoothing` picks the mode for a text system used directly; `TextSystem::set_apple_pipeline` overrides its stages (`ApplePipeline::SMOOTHED`, `UNSMOOTHED`). + +- **Glyph pens floor to CoreGraphics' subpixel steps, + as CoreText's quantisation does.** The step depends on the glyph's size in device pixels: + fifths of a pixel below 8⅓ ppem, quarters to 11.1, thirds to 16.7, halves to 33.3 and whole + pixels above, at every scale. Glyphs used to round to the nearest quarter pixel. Measured + against CoreText, the report paragraph's mean error falls to 0.06 levels at 2× and 0.10 at 1×. + +- **Windows and overlays blend in sRGB-encoded space by default on every platform, as Core + Animation, CoreText and CSS do.** Text drawn at the colour's full coverage (no compensating coverage curve) + now has native weight in light and dark themes, and translucent fills, shadows and blurs + composite as AppKit's would. `App::srgb_blend(false)` (or the overlay's) keeps linear-light + blending. Rune's Metal layer is now tagged sRGB, so a wide-gamut display colour-matches its + pixels instead of showing them as display-native values. + +- **macOS overlays join other apps' full-screen Spaces.** Overlay panels add + `NSWindowCollectionBehaviorCanJoinAllApplications` to their collection behaviour, so a HUD shows + over another app's full-screen window on every macOS that has the flag, not only where the + system already allows it. + +- **macOS overlays finish, submit and present off the main thread, and compositors can stage + buffer writes.** An overlay frame with no system materials, no presents-with-transaction and + no native video surface now hands its encoder and drawable to a per-overlay present thread, + which runs `CommandEncoder::finish`, `Queue::submit` and `Queue::present`; the main thread + waits for it only before it next touches the surface. An overlay animating at 120 Hz spends + about half the main-thread time per frame it did. `Frame::write_buffer(buffer, offset, data)` + writes a buffer through Rune's staging chunks and records the copy into the frame's encoder, + so a compositor's per-frame uniform writes reuse staging memory instead of + `Queue::write_buffer`'s per-call staging buffer, and land ahead of what it records next. + A `Queue::write_buffer` made outside the compositor callback, after the frame is drawn, can + now land in that frame's submission instead of the next one; write per-frame data from the + callback, or with `Frame::write_buffer`. + +- **A scaled layer snaps the same wherever its scale is anchored.** Content within a pixel of + a layer's anchor snapped to the unscaled grid while the rest of the layer drew exact, and a + layer's resting correction faded out by how far that layer's own edges moved, so outlines on + an overlay anchored elsewhere drifted up to 0.2 px off the art beneath them during a zoom. + The unscaled-grid weight is now one value per layer, taken from the layer's edges. Each box + lets go of its resting correction over the first pixel that box moves, so content at the + anchor stays put instead of drifting. A layer counts as moving by how far it moves points + of the window. + +- **Linux builds can leave out D-Bus.** zbus, tokio and futures-util, which Rune compiled into + every Linux build, now sit behind a new default `dbus` feature (26 fewer crates without it). It + covers the desktop's light or dark preference, the system tray, global shortcuts in a Wayland + session and the FileChooser portal, which `native-file-dialog` now turns on itself. Off, a + window winit gives no theme draws dark, `Tray::new` returns `TrayError::Unsupported` on Linux + and a Wayland session's global shortcuts return `ShortcutError::Unsupported`; X11 shortcuts + keep working. An app that sets `default-features = false` and wants these adds + `features = ["dbus"]`. Other platforms are unaffected. + +- **Decoding a large image no longer needs a full-size float copy.** `ImageCache` builds mip 0 by + copying opaque pixels straight through and premultiplying the rest with sRGB lookup tables, and + builds each smaller mip from the 8-bit level above it (mip 1 from the source), so the only memory + it holds is the mips themselves. An 8192×8192 image peaked at 1.5 GiB and took about 1.25 s; it + now peaks at its 341 MiB of mips and takes 0.15–0.25 s. Mip bytes match the old float chain within + one level per channel. + +- **Scaled content lands on whole device pixels once its scale holds still.** Pixel snapping + skipped everything under an `El::scale` other than 1, so a canvas zoomed to 1.37 drew its + boxes at edges like 548.61 px, soft and up to half a pixel off unscaled outlines drawn over + it. A node with its own scale now heads a layer: while the layer's drawn rect moves (a zoom, + a pinch, a spring) its content keeps its exact sub-pixel edges, and once it holds still the + correction to the grid eases in over 0.1 s, so a zoom ends with no pop. When it moves again, + the resting correction fades out over the first pixel its edges travel. Cached subtrees snap + at once. `El::pixel_snap(false)` still opts a subtree out. + +- **Linux follows the desktop's light or dark preference.** winit reports no theme on Wayland + (and layer surfaces have none), so windows and overlays there always drew dark. When winit has + nothing they now read the XDG desktop portal's `org.freedesktop.appearance` `color-scheme`: a + worker thread reads it once and follows `SettingChanged`, a change asks every window to redraw + (as a new accent does) and the redraw rereads it, and overlays read it each time they show. The + first window waits at most 100 ms for the first answer. "No preference", no portal or no session + bus keep dark as before, and `--theme` and winit's own theme still win. + +- **An invisible effect layer no longer keeps the frame loop awake.** `FxLayer::is_animating` is + false for a layer that draws nothing whatever the time: zero opacity, or a zero intensity, + heat, amount or sparkle count (and a motion blur with no source). Such layers already drew + nothing but kept an idle window ticking at the display rate. A `PulseStyle::Ping` now reports + animating until 2.2× its duration, when its head finishes cooling, instead of stopping at 2× + and freezing the bloom mid-fade. + +- **rune-light allocates GI only when GI runs, and a bigger scene keeps its render targets.** With + `Settings::gi` off, `LightRenderer` makes none of the GI textures (media, five cascades, fluence) + and records no empty GI passes when timing; they're made the first frame GI is on. + `LightRenderer::inspect` returns black views for the GI buffers until then, and `Timings::gi` is + 0 for a frame without GI. Growing past the primitive buffer's capacity now rebuilds only the two + bind groups that read it instead of reallocating every render target. + +- The playground's list and side column keep only the keys they use (arrows, Return, J K, triggers, Tab, Esc, and typing in the filter). Every other key, ⌘-chords and digits included, reaches the open story's `AppSpec::on_key`, so its shortcuts work as soon as it opens from the list, without a click on the stage or ⇧Tab. + +- **Periodic loops keep the app's time.** Animation time drops what a covered, idle or stalled window spends, and a `.looping` track kept its phase on animation time, while apps work out `LoopSpec::delay` from their own clock. So two loops created in different commits fell out of step by whatever animation time had dropped between them. A text shimmer's window and the bright copy that slides back inside it stopped cancelling, and the copy sat a fixed distance off its label for every pass. Running periodic loops now also get the time animation time dropped, and a loop a frame's commit creates starts at that frame's presented time, so loops with delays from the app clock stay in step however late each mounts. A newly created loop starts one frame later in its cycle than before; finite sequences are unchanged. + +- **Removing an animating track completes it.** `AnimationStore::remove` and `remove_node` (so a node unmounting mid-animation) now emit `MotionEvent::Completed { finished: false }` for an animation started with a completion token, as replacing it already did, instead of dropping the token silently. + +- **`Runtime::events` stays small.** A live window, overlay or web canvas no longer formats an input marker (`press …`, `wheel …`, `key …`) on every input unless `--trace` is on, and a headless runtime keeps at most 512 unread markers, dropping the oldest half when it fills. Tests that read `rt.events` after a few inputs see the same markers as before. + +- **A steady animating frame allocates no GPU buffers.** Per-frame uploads in `Renderer`, + `FxRenderer`, `LightRenderer` and `GlassRenderer` go through reused staging chunks (the new + `rune-staging` crate) instead of `Queue::write_buffer`/`write_texture`, which allocate a fresh + staging buffer each call on native backends. `Renderer::prepare` writes only the instances that + changed and writes globals only when the viewport or sRGB flag changes. Its uploads now land + ahead of the renderer's next draw, recorded into that draw's encoder, or are submitted ahead of + `draw_range*` and `Renderer::submit`, so submit the encoder a renderer drew into. One dropped + unsubmitted is detected, and the next frame uploads everything again. On the web, writes still + go straight to the queue. A headless 2,000-instance frame takes about half the CPU time to + record and submit (`examples/upload_bench.rs`). + +- A `Tx::launch` or `El::matched` flight into a container that is still entering (its scale or fade animating) keeps the still scales above that container, such as an app-wide zoom. It used to drop every ancestor scale, so under a zoom it flew at 1/zoom size and snapped to the zoom when the container's entrance ended. The entering container's own scale is still dropped. + +- **`Recording::counts_roll`: an app whose live numbers roll can gate a count that ticks in place.** Set `rec.counts_roll = true` and a count or clock whose words change in one frame ("9s" → "10s") is a `text-swap`, as other words are; a label over its own rolling glyphs still passes. It's off by default, where a tick passes as before. + +- **The motion gate finds four more things: `lands-unseen`, `remount`, `unpinned` and `twice`.** `rune::motion_gate::check` now reports an element that travels in view and then its clip hides it the frame it rests (`lands-unseen`), words that start leaving as the same words mount under a path one segment different (`remount`: a row lost its key), a scroll pinned to its end whose content's bottom slides below the viewport with no input since (`unpinned`; an input named `event…` is data arriving and doesn't count), and an element Rune renamed `key#dupN` because two siblings share a key (`twice`). Each has a `RULES` row. An app's gate can fail on these where it passed before: fix the motion, or allow the finding with its reason. + +- **New crate `rune-mermaid`: native Mermaid diagrams in Rust.** Extracted from `rune-kit` so + apps can render Mermaid diagrams (`rune_mermaid::render` with `DiagramStyle`) without pulling + in `rune-kit` or `pulldown-cmark`, while `rune-kit`'s `mermaid` feature continues to draw + closed ```` ```mermaid ```` fences inside `Markdown`. Adds `stateDiagram` / `stateDiagram-v2` + (`[*]`, composite states, `<>`), theme-adapted node tints from `style` / `classDef` / + `:::class`, quoted edge labels, and nested brackets inside unquoted node labels. + +- **New opt-in crate `rune-register`: self-registration for stories, scenes and knob groups.** A module adds its items to a list from its own file with `register!(LIST: Type = [...])`, the list is declared with `slice!`, and `collect` reads it ordered by module path (so link order doesn't matter); `merge` folds extra items in by name. Nothing in `rune` or `rune-kit` depends on it. It uses linkme (Linux, macOS, iOS, Windows, Android and more); on wasm32 lists are empty, and on any other target linkme lacks the build fails with its compile error. + +- `rune-mac` posts system notifications: `notify::post(&Notification::new(id, title).body(..).info(k, v))` goes through `UNUserNotificationCenter` (silent, asking for permission on the first post), `notify::remove(ids)` takes them back out, `notify::on_click(f)` hands back the clicked id and user info, and `notify::app_focused()` / `notify::bring_to_front()` cover "only when the app isn't in front" and "a click opens it". Only a bundled app can post; elsewhere `notify::available()` is false and posting does nothing. + +- A child mounted under a parent past half its entrance enters on its own instead of appearing at once at the parent's opacity: a `RollingText` digit changing while its row's fade has a percent left rolls in rather than popping in place. + +- **The playground's story list is a tree, filters as you type, and the keyboard is in one column at a time.** Each `/` in a story's path nests a group, as deep as the path goes: `"Prototypes/Onboarding/Option · Pill"` lists the story in Onboarding, inside Prototypes. Group headers are bolder, with a chevron and a count, and each level indents 12 pt. Every level folds, by click or ← → ↵. `Playground::folds(load, save)` names groups by their full paths (`"Sidebar/Filter buttons"`), and saved one-level names still load. New: `Playground::start_folded(true)` starts every group folded except the open story's, which unfold each time the playground opens, including from a link at launch; with it, `folds` saves the unfolded groups instead. `Playground::group_order(&[..])` lists the named top-level groups first, scenes and stories alike, so stories can come before scenes; a name that matches no group is logged in debug builds. When two stories share a name, a lookup by name (`open_playground_at`, `--playground`) now picks the first in list order, not the first declared. A filter field over the list keeps the stories whose path contains every typed word, along with their groups. `/` or a click focuses it; ↓ moves into the matches, Return opens the first match, and Esc clears the field, then leaves it. The keyboard is in the list, the stage or the side column, and a click in a column moves it there. The column that has it shows its selection in the accent, or a ring around the stage, and the hint lists that column's keys. **Behavior change:** 1–9 pick a variant and `side_keys` hooks hear keys only while the keyboard is in the side column (→ or Tab from a story, Esc back), and the stage's `on_key` hears keys only while the stage has the keyboard, except Esc and `Playground::typing`. + +- **`TraySpec` and `TrayIcon` are built with constructors, and the tray enums can grow.** `TraySpec { id, title, tooltip, icon, menu }` becomes `TraySpec::new(id, title, icon).tooltip(..).menu(..)`, and `TrayIcon { width, height, rgba }` becomes `TrayIcon::rgba(width, height, pixels)`. Their fields are private, and `TrayItem`, `TrayEvent` and `TrayError` are `#[non_exhaustive]`, so a match on them needs a `_` arm. + +- **macOS app icons at small sizes are the app's real icon.** `app_icon_rgba` (and + `ImageCache::app_icon`) now draws the icon at 256 pixels or more and scales it down. On macOS 26 + and later, asking for a small size directly could return the system's "legacy" rendition, a + shrunken tile inside a grey rounded frame. + +- **`Tx::scroll_into_view` leaves a row taller than the viewport where it fills it.** Revealing + such a row from above lands its end at the viewport's bottom, as before, but a virtual row's + re-placement after its rows measure (or a follow frame while the list grows) no longer flips it + to its start. Before, where it ended up depended on how many placements ran, so one extra + trailing row could move it. + +- **A typed line stays clear of a scroll viewport's faded edges.** After an edit, the focused + field's caret now stops `El::scroll_margin` short of its viewport's edge, as + `Tx::scroll_into_view` does and as CSS `scroll-padding` does for a textarea, so the line being + typed never sits under a `scroll_edge_fade`. The content's own ends still stop flush. + +- **A window with placed traffic lights no longer crashes entering full screen on macOS.** Going + full screen, AppKit observes the titlebar container and puts its own KVO subclass above the one + `Chrome::traffic_lights` gave it, so the layout hook called AppKit's `-layout` through its own + class again and overflowed the stack. The hook now finds Rune's subclass in the chain and calls + the class above it, and the buttons still return to their spot on leaving full screen. + +- Add `rune-perf`, an opt-in bounded local recorder (`Recorder::start(Config::new(dir, app))`, `Frame::new(window, seq, outcome).update_ms(..)`) with rolling stats, `perf.json` snapshots, rotating logs and capped warning incidents; it reads procwatch, which gains `procwatch::usage()` (footprint, peak, resident and fds without a thread walk) and `procwatch::alloc::thread_allocated_bytes()` (this thread's requested bytes, `None` without `procwatch::alloc::Counting`). + +- **`FrameEncoded::update_ms` and `FrameEncoded::encode_ms`.** A `Drawn` frame's report says how + long the runtime took to build it and how long encoding took until submit, the numbers a + compositor gets. Logging frame timing from `App::on_frame_encoded` no longer needs a + compositor, which would turn off the window's skip of unchanged timer frames. Other outcomes + report `None`. + +- `Tx::launch` leaves from its source under an app zoom or a scrolled view when another commit landed earlier in the same frame (a state update or event just before the key that sends). It used to skip the zoom and scroll then, so the new row started off to one side, sometimes off-screen or right of where it rests. + +- **Fills, borders and clips land on whole device pixels.** A box laid out at a fractional + position (a 1.1 pt gap at 2×) drew soft, half-covered edge rows. Each painted rect now rounds + its four edges to the device grid at paint time, so edges are hard, boxes that share an edge + meet with no seam, a 0.5 pt border at 2× is one crisp pixel, and text keeps the same offset + from its fill wherever the box lands. Layout, hit testing, `Cx::layout_size` and + `Runtime::elements` keep the exact fractional rects. Motion stays smooth: a moving element's + correction eases from the one it drew with toward the rounding of where it comes to rest, in + step with the distance left, so it glides between pixels with no jump at the start or the + landing; a scroll snaps its content as one + translation, and a scale fades the snap in over its last pixel. `El::pixel_snap(false)` turns + it off for a subtree an app moves itself at sub-pixel speeds. + +- `TextSystem::layout_rich_with(text, spans, style, scale, max_width, RichLayoutOptions::new().wrap_anywhere())` lays out rich text that breaks inside a word wider than the wrap width (a long URL, hash or token) instead of running past it, as `El::wrap_anywhere()` does for elements; `RichLayoutOptions::align(..)` aligns lines as `layout_aligned` does. Apps that lay out their own text, such as editors, can now wrap an unbroken word. + +- **A key press on a resting macOS window draws at once.** A window that had stopped its + display link started it on input and waited for its first tick before drawing, so the first + frame after a key, click or paste ran its handler about 12 ms late (median, `--profile perf`). + When the last frame reached the display at least a period and a half ago, the window now draws + in the same run-loop turn, and its handlers run about 0.3 ms after the event (median). Frames while + something moves still wait for the display's tick, and a Low Power cap still spaces them. + `FrameEncoded::presents_at()` is `None` for such a frame. + +- `Tx::launch` and `El::matched` flights under a still ancestor `El::scale` (an app-wide zoom) fly at the size and place they land at. They used to draw unscaled, off the source's text, and snap to the zoom on landing. An ancestor scale that is animating is still dropped. + +- macOS: `Chrome::traffic_lights` holds. Since macOS 26 AppKit put the buttons back at (9, 9) whenever it laid the titlebar out on its own (a title or appearance change, a zoom), so they drifted off the spot and out of line with the app's title-bar controls; the titlebar views now put them back after each layout. + +- **Icons honour SVG opacity.** `opacity`, `fill-opacity` and `stroke-opacity` on an icon's + elements now scale that element's coverage, so one `Icon` can hold a graded shape (a faint + track under an arc, dots fading round a spinner). Before, they were ignored and drew solid. + +- `Tx::replay_playground()` makes the open playground story again and runs its `r` trigger, as R does, and `Tx::playground_trigger(key)` runs one of its triggers, so a deep link can open a story and replay it. + +- **Separators in application and Dock menus.** New `MenuItem::separator()` puts a separator + line among an app's custom items, placed with `.menu("File")` or `.dock()` like any item + (`NSMenuItem.separatorItem` on macOS). Separators need no id, can't be fired and are skipped + by id/title lookup. Windows and Linux still report `Unsupported` for native menus. + +- **The knobs panel's filter is a real text field.** It was a row that drew `Knobs::query` with a fake caret, so ⌘A did nothing and ← → stepped knobs and folded sections while typing. Now `/` or a click starts a single-line `text_input` bound to a private `TextEdit` in `Knobs`, with ⌘A, ← → and ⇧ to select, ⌥ and ⌘ with arrows and Backspace, paste and IME. `query` stays the field's text on every edit (`Knobs::set_query` sets both), and the filter runs as the text changes. While it edits, the field owns ← →, digits, `[` `]`, `/` and Backspace; ↑ ↓ and Tab still move the panel's row, Return stops, and Esc stops, then clears, then closes. Stopping gives focus back to the panel. `Knobs::filter(query)` starts it with text selected, and `side_key` leaves ← → to the field. +- **A text field's selection highlight no longer stretches to a fill behind it.** The highlight joined runs and took any recently drawn fill behind the first rect on a line for a chip, so a field inside a filled pill selected from the pill's edge. Fields draw their selection rects as they are. + +- **Wayland overlays take clicks while idle.** A layer-shell overlay reads input from its own + queue on winit's connection, and winit turns its loop only for its own events, so a click + on an overlay that wasn't animating waited for an unrelated wake (a timer, the pointer + leaving) and often landed late or never. A watcher thread now wakes the loop when the + compositor writes to the display, at most once per read. + +- **Overlays can hand focus to another app.** New: `rune::press_activation_token(app_id)`, an + XDG activation token from the latest pointer press on a Wayland layer-shell overlay, made with + that press's serial, seat and surface. A notification server emits it as `ActivationToken` + before `ActionInvoked`, so the app it opens may raise its window. None off Wayland, before any + press, or when the compositor lacks `xdg_activation_v1`. + +- **Filtering a `Combobox` or `PopupList` is instant by default.** A keystroke's rows and the + popover's height used to crossfade and spring (0.3 s in, 0.24 s out); they now land in the + frame, and a `PopupList` lands any change to its `items` at once, even in a commit that + animates the field it follows (`animate_edit_layout`). Opening, closing and the hover + highlight keep their motion. `.animate_filtering(true)` on either brings the crossfade back. + New: `El::instant_changes()`, which lands every change inside an element (layout, opacity, + transforms, presence of what it holds, growth rows) in any commit while its own entrance, + exit and colours keep theirs. A scroll-into-view that mounts new virtual rows now commits + them as instantly as the change that asked for it. + +- **Filtering a virtual list crossfades what shows, and motion nobody sees ends at once.** A + removed element that drew nothing last frame used to skip its exit only when it had already + faded out. It now also skips it when it, and everything it holds, lay out of the window or + clipped away, so filtering a long list no longer runs dozens of fades under its viewport's + clip. In a virtual list, rows a change to the rows (a filter, a sort) mounts now enter with + their insertion transition, and those that land out of view finish it as soon as they draw. + A change that keeps none of the rows in view no longer anchors the scroll offset to a kept + row further down, and the rows it removes no longer hold their space: they fade where they + stood while the matches fade in at the top. A kept row that was out of view and lands in + view enters too, rather than appearing whole. Rows scrolled into view still mount as they + are. New: `Scene::enter_now` and `Scene::reenter`. + +- `ConfiguredWindowOptions::macos(|native| ..)` amends the AppKit settings a preset made, so `WindowOptions::launcher_panel().macos(|n| n.corner_radius(16.0))` keeps its launcher behaviour. + +- **Trailing `RollingText` digits hold still in a width-leading row.** A trailing label's glyphs + slid on the label's own spring to cancel their row's slide, so in a parent that slides on + another spring (`width_leads`, say) they drifted 2–3 pt out and back as the label widened. The + label and its glyphs now ride their parent's trailing edge: `El::ride_trailing()` (and + `rune_motion::Scene::set_ride_trailing`) keeps an element against its parent's right edge while + the parent's width animates, so glyphs that stay, leave or enter hold their columns whatever + springs the rows around them use. The motion audit's odometer scenario adds header rows with a + usage group, and `analyze.py` no longer splits a motion at a frame or two of rest, so an + out-and-back through its start reads as a `reversal`. + +- **Big shadows and border rings cost a fraction of what they did.** A window-sized panel's + blurred shadow shaded every pixel under the panel each frame, running the erf shadow math + where the panel hides it, and a border-only ring shaded its whole empty middle. A shadow + under a solid box, and a ring with no fill, now draw as four bands around the middle they + leave blank, and a shadow skips its erf rows well inside the box. Output matches to within one + colour level; on a 5K window with a large panel the frame pass went from about 13 ms to about 4.5 ms. + +- **Playground: `--whole-window`.** A headless `--snap` with `--playground` is now the story's stage only, by default, and `--crop KEY` looks for its key on the stage. `--whole-window` snaps the whole window, list, stage and side column, and lets `--crop` take any key in it, such as `playground-list`, `playground-side` or a group header's `playground-group-N`. `--out`, `--video` and `--strip` frames are still the whole window. + +- **A story picks how the playground's stage lays it out.** `Story::stage(Stage::Scroll)` and + `Playground::stage(scene, Stage::Scroll)` make it a page for content taller than the stage: + laid out at the stage's width inside a 24 pt margin, at its own height, from the top, and the + stage scrolls. `Stage::Fill` puts it edge to edge across the whole stage, whatever size is + picked beside it. `Stage::Center`, the default, lays out as before. `rune::Stage` is new at + the crate root, so an app that glob-imports `rune::*` beside another `Stage` names one of them. + The story list now shows each group's story count on its header, and a motion mark on stories + and scenes with triggers. + +- **`Combobox` reads like a command menu.** Its search field sits borderless under a search + icon, over a divider, with no focus outline (the caret shows focus), and each option shows its + `detail` in muted text after the label. The result list fits the window like the other + dropdowns, never shorter than one row, and scrolls with faded edges. New builders: + `trigger(El)` replaces the default field trigger, `placement`, and `max_height` (192 by + default). `Popover::padding` sets the body's inset (12 by default; 0 for edge-to-edge bodies). + +- **A motion watcher can read every frame cheaply.** `Runtime::motion_elements(&mut out)` fills a + reused list with what a frame-by-frame watcher needs of each presented element (id, parent, + drawn and visible rects, opacity, scale, loop phase, a hash of its words and `MotionElement` + flags) with no strings copied, and `Runtime::element_path(id)` gives its path and key to cache. + `elements()` is unchanged. Next: the `--trace-all` motion tracer will read the same walk, + so its flags and the in-app watcher's can't drift. + +- **Apps can watch their own frames.** `App::on_frame_drawn(|rt| ..)` runs after each drawn frame + of a desktop window with the runtime as that frame presented it (`rt.elements()`, `rt.state`), + and `rune::last_input()` says when the thread last took an input event from the platform, so an + app can log a motion glitch it sees in real use. Drawing doesn't change. + +- **`MacWindowOptions::corner_radius(r)` rounds transparent, borderless macOS windows and + panels.** The content view's layer clips everything with a continuous curve + (`.corner_curve_circular()` for a circular arc), so the root view no longer needs to clip + itself to the radius; a border inside the edge is still the app's. Opaque and bordered + windows ignore it. Transparent windows with a system shadow now call `invalidateShadow` + once the first frame after each show, resize, scale change or launcher prewarm reaches the + screen, so the shadow traces the drawn shape instead of an empty or older frame. + +- **Menus show the accelerator's own key on every keyboard layout.** A `MenuItem` or + `PopupItem` key equivalent is now the character its accelerator names: `cmd+b` is ⌘B on + Dvorak too, and fires from the key that types "b", where it used to show and take ⌘X (the + key in QWERTY's B position) away from Cut. `cmd+shift+=` is "=" with ⇧⌘; arrows, Return, + Delete, Escape, Tab, Space and F-keys use AppKit's characters. The app, named, Dock and + context menus all follow it, and a custom item with a standard item's key (⌘X) now takes it + on any layout as it does on QWERTY. New `Shortcut::menu_keycaps()` gives the same label for + menus and hints; the playground bar and rune-kit's button shortcut tooltips use it. + `Shortcut::keycaps()` still names the key at the shortcut's position in the current layout, + for global shortcuts and the shortcut recorder. + +- **The playground takes an app's story table.** + - `Tx::open_playground_at(story, variant)` opens it on a story from app code, by path, name or + slug, through the same lookup as `--playground`/`--variant` and `Runtime::open_playground`. + From `App::on_open_url` a link opens straight onto the story at launch. A bad name at runtime + is logged and opens the list. `rune::playground::slug(path)` makes a story's stable link + slug (`"Timeline/Send"` is `"timeline-send"`), and every lookup takes one. The `playground` + module is public for it. + - `Story::side_keys(view, key)` and `Playground::side_keys(scene, view, key)` are `side` for + controls that take keys: → or Tab puts the keyboard on them, the view gets `active` to mark + what the keys move, and the hook gets each key first. Esc and Tab leave; ← no longer does + there. `rune_knobs::side_key(groups, lens)` is the hook for `rune_knobs::inline`: ↑↓ pick a + knob, ←→ step it. + - `Story::new`, `from_real`, `overlay`, `poll`, `trigger`, `variant` and `side`, + `Play::after`, and `Playground::page`, `trigger`, `variant`, `side` and `side_real` take any + `Fn` (`FnOnce` for a step) where they took a `fn`, so a story table can build its stories in + a loop, each capturing its row. Code passing fns compiles unchanged. `Story::trigger_tx` and + `Playground::trigger_tx` take a step that needs only the `Tx`. + - Folded groups stay folded after the playground closes, for as long as the app runs, where + they used to unfold. `Playground::folds(load, save)` keeps them from one run to the next. + +- **Children can leave the way the commit that removes them says.** `El::child_exit(t)` gives + children removed from an element in a commit the transition `t` in place of their last render's. + `RollingText` uses it so old digits leave the way new ones enter, including on a first count + down or a value that turns back mid-roll. A trailing `RollingText` now holds leaving digits in + their columns too, matches from the right like an odometer ("19s" → "100s" keeps only the + "s"), and keeps its staggered roll spring when its width changes. `rune::text::advance` gives a + line's unrounded advance. + +- rune-knobs: the side panel's keyboard choice numbers its options and 1–9 pick one. Typing no longer filters on its own: `/` (or a click on the filter) starts it, Return or Esc stops typing and keeps the matches, and a second Esc clears them. + +- Playground: a trigger's `Play::after` steps land on the same frame on every replay; due times allow for rounding in the running clock, which used to push a later replay's step one frame late. + +- **An instant commit no longer lands motion it didn't change.** `Tx::instant` still lands + every layout, colour and opacity change the commit makes, but a node already springing toward + a place or value the commit leaves alone keeps springing, so a quick key press during a layout + spring (a row of chips opening, a selection moving) doesn't snap it to the end mid-flight. + `Tx::settle` still lands every running track; use it where an instant commit was used to stop + motion in place. + +- rune-knobs: right-click a knob to put it back to its default, and a hovered group header offers Random and Reset for that group (right-click resets it). Clicking anywhere on a choice row puts ←→ on its options, and moving the pointer takes the highlight from the keyboard's row so only one row is lit. + +- **`rune_knobs::inline` fills its parent's width, so knobs fit a playground's side column.** Rows lay out from the width they get: a slider's fill and handle are a share of its track instead of math on a fixed 300 pt, and a choice reads its card's laid-out width to sit beside its label or under it (rebuilding only when the width changes). The floating ⌘⇧K panel keeps 300 pt, set by the panel and not the rows; `inline`'s signature is unchanged, and `actions` now fills its parent up to 300 pt. New `Style::light()`. `examples/knobs` hosts a story's knobs in `Story::side` (`-- --playground Knobs`). + +- **Tests can drive the playground.** `App::headless_runtime(size, env)` builds a windowless + runtime with `App::playground` attached. On it, `Runtime::open_playground(story, variant)` + opens a story as `--playground NAME --variant V` does, `Runtime::playground_trigger(key)` runs + a trigger as its key does, and `Play::after` steps run as `Runtime::frame` moves the logical + clock. `Runtime::playground_state::

()` reads the stage's state and + `Runtime::playground_element(key)` finds an element on the stage; `rt.state` stays the real + state. `Play::clear()` drops the stage's queued steps, a loop's included, so a trigger can + take over from a running one. + +- **A toolbar can float over a text selection.** `Cx::selection_rects()` returns the selection's + line boxes in window points (empty with nothing selected) and re-runs the view when one moves + more than half a point, as `Cx::layout` does; a `memo` that reads it is rebuilt when they move. + `TextSelection::backward()` says the selection was made dragging up or left, so a toolbar can + open at the pointer's end. `SelectionChange::dragging()` says a press is still making the + selection, and **`El::on_selection_change` handlers the selection is inside now hear one more + call when that press releases**, with the same selection and `dragging()` false, so a handler that treated every + call as a change sees one extra call per drag. `El::keeps_text_selection()` makes a press on an + element (a Quote button) leave the selection and the keyboard focus as they are, so its + handler can read the selection, and a drag that starts on it doesn't start a new one. + +- **`El::backdrop_blur(sigma)`: frosted glass over the window's own content.** + `el().backdrop_blur(8.0).fill(tint)` blurs what is already drawn behind the element, inside + its rounded or continuous corners and its clip, and draws the fill over it as a tint, with the + border and children on top. It works through plain `rune::run`, follows scrolling, springs and + opacity, and renders the same headless. The renderer splits the pass at the element, blurs a + copy with a half-resolution pyramid cut to the element plus three sigma, and composites it + through the corner mask. A frame blurs at most `MAX_BACKDROP_BLURS` (4) elements; later ones, + and any drawn into a target without `COPY_SRC` or a caller's own pass (`Renderer::draw_range`), + draw only their fill. Frames without one are unchanged. The web backend now asks the canvas + for `COPY_SRC`. `examples/frosted-bar` shows a list scrolling under a frosted bottom bar. + +- **Every `RollingText`'s glyphs now slide on the row's width-leading X spring**, not the plain + label spring, so glyphs that stay hold still against the row's edge while the width changes. This + moves the glyphs of every rolling label. **A right-aligned `RollingText` rolls new digits in their + columns:** `RollingText::trailing()` says the label widens to the left, so a glyph that rolls in + starts where it will rest instead of riding in from the right with the label's slide ("9s" → + "10s" no longer rolls "10" over the "s"). A trailing label's row and glyphs slide on the plain + label spring (no width lead), so a container that right-aligns it should slide on that spring + too. + +- **A `RollingText` can roll the way its number moves.** `RollingText::value(v)` is SwiftUI's + `.numericText(value:)`: while the value rises, new glyphs enter from `from` (digits move up, the + default); when it falls, they enter from the opposite edge. Text that changes while the value + holds, or with a value that isn't finite, rolls from `from`. Labels without a value are unchanged. + +- **Text selection across virtual rows.** `El::selectable` and `El::selection_group` now keep + working across unbuilt and scrolled-out rows of an `El::virtual_rows` or `El::virtualize` list: + the virtual list pins the rows holding the selection's anchor and focus (storing endpoints by + row identity, relative path and byte offset so they survive rows mounting and unmounting around + them), Cmd+A and `Tx::select_all_text(key)` select from the first row to the last row of the + virtual list, `Tx::select_text(key, range)` pins and builds an unbuilt target row without + scrolling, and Cmd+C / `Runtime::selected_text()` / `Tx::text_selection()` build any unmounted + rows between the selection's ends on demand (view only, capped at 10,000 unbuilt rows and 4 MiB + of UTF-8 text) using the same `\t` and `\n` separators as mounted rows. + +- rune-knobs: a choice's options can say what they are (`Knob::hints`), shown under the panel's list while one is hovered or picked; an app can describe all its knobs from one table (`Note`, `describe`), which wins over a knob's own label, about and hints; `Knob::describe` and `Knob::hint` read them, and `Knobs::hover` puts the pointer on a knob or option for a still or a test. `Knob` gained a pub `hints` field. + +- **Transparent windows and overlays stay clear on Windows, on every GPU.** A surface whose + adapter can't composite alpha (a Win32 Vulkan surface on AMD's integrated GPUs, any DXGI + swapchain made from an HWND) fell back to opaque, so an overlay drew a black box around its + content, silently. DX12 surfaces now present through DirectComposition, which composites alpha + on any GPU. A translucent surface gets the lowest-power adapter that can composite it, and + reuses a shared device only if that device can. An overlay that still can't be translucent + logs it, as a window already did. + +- **Playground: folding groups.** A click on a group's header folds or unfolds it, and so do ←, → and ↵ while the header is the list's selection. ↑↓ walk headers and the stories that show; J K skip the headers. Groups stay folded until the playground closes. ← leaves the side column, as Tab and Esc do. `Playground::scenes(|name| ..)` picks which of `AppSpec::scenes` the list shows. Choosing a scene, or a story whose state is new, runs its `'r'` trigger as R does, so its motion plays at once, headless `--playground NAME` included. `Playground::fresh(|real| ..)` starts scenes from the real state, and `Story::from_real(name, |real| .., view)` derives a story's state from it, each time it's made. `Playground::keep(|stage, real| ..)` copies a scene's stage back before R, a switch or Back, so tuning sticks. `Story::variant(name, |p| ..)` and `Playground::variant(scene, name, |s| ..)` add variants, listed in the side column and picked with 1 to 9. `Playground::typing(|s| ..)` gives the stage's `on_key` every key first while it's true. `Playground::dark(|s| ..)` makes the chrome follow the app's own light/dark setting. `Playground::side_real(scene, |stage, real, cx| ..)` draws a scene's side column from both states, and `Tx::keep_playground()` runs `keep` on demand. Headless, `--variant N|name` opens `--playground`'s story on a variant, and `--crop KEY` crops a `--snap` to the element with that key or path, the stage's first; `--crop x,y,w,h` still crops strip tiles. + +- **Inline code chips get real padding and a gap from the text around them.** Markdown pads + the chip `MarkdownStyle::inline_code_pad` points around the code (3.5 by default) instead of + painting one narrow space each side, and sets two unpainted narrow spaces each side, so what's + left is a small margin. Code in a link is a chip in the link's colour without an underline. + Span backgrounds snap to whole device pixels, sit balanced on the cap height rather than a + mono face's tall line box, and merge across a link's underline instead of leaving a seam at + the chip's edge. `MarkdownStyle::list(indent, gap)` sets the marker column and the gap between + items (32 and 4, as before), and `code_block_padding(x, y)` the room inside code blocks and + diffs (12 by 12). + +- **`App::on_frame_encoded` reports each frame of a desktop window.** The hook (also on + `WindowSpec`) runs on the UI thread with a `FrameEncoded`: its `FrameOutcome` (`Drawn` once + encoded, submitted and presented, the first frame and a hidden launcher's included; + `Unchanged` for a timer's frame that drew what was on screen; `Skipped` when the window was + covered, minimised or occluded or no drawable came), when encoding finished, the window's key, + a per-window sequence number, and the display link's target refresh when it paced the frame. + Frames, skips, pacing and redraws are the same with it as without; without it each frame + checks an `Option`. Headless runs, overlays and the web don't call it. + +- **`Cursor::Image` shows an app's own cursor.** `Cursor::Image(CursorImage::png(bytes, hot))` + takes a PNG drawn at 2x (a 64×64 px PNG is a 32×32 pt cursor) and a hot spot in points, + clamped into the image. The OS draws it, so a pencil over a canvas keeps up with the pointer + and reaches the window's edge. It comes and goes like the system cursors under hover, press + capture, overlays and focus changes. On macOS it's an `NSCursor` sized in points, with the + window's cursor rects off while it shows; elsewhere it's a winit custom cursor made at the + window's scale, set before the loop sleeps the first time each image is used. Each image is + decoded once and its OS cursor cached (32 images, 8 MiB). A PNG that doesn't decode, or is + over 256 px a side, shows the arrow and is logged once. `Cursor` is still `Copy` and `Eq`; + two images are equal when they have the same bytes and hot spot, which for the same bytes in + memory is an address check. New example: `examples/sketch`. + +- **`Tx::input_time()` says when a handler's input arrived.** Key, IME, pointer, wheel and + trackpad gesture handlers get `Some(instant)`: on macOS the timestamp of the `NSEvent` + AppKit dispatched, converted to an `Instant`, elsewhere the moment the window took the event + from winit. Input that piles up between frames keeps each event's own time. Timers, polls, + updates, layout callbacks and input fed to a `Runtime` directly see `None`. Nothing else + changes; handlers that don't ask pay nothing but a stamp on each queued action. + +- **`scripts/mac-app` installs and relaunches a Mac app in place.** It copies a built binary into + `~/Applications/NAME.app` with an icon, an optional URL scheme for `App::on_open_url` and an + optional microphone usage string, then starts the new copy before the old one quits, so with + `rune_mac::remember_frame` the window doesn't blink. `--wait-idle` holds an unattended swap + while the app is in use and relaunches behind the app in front; `rune_mac::busy` holds it while + the app is busy. `MAC_APP_SIGN` picks a signing identity (ad hoc by default). See "Relaunching + a Mac app" in `crates/rune/README.md`. + +- **`rune::motion_gate` lets an app gate its own motion in `cargo test`.** `Run` records the + app's real `Runtime` frame by frame on the virtual clock, `check` lists what a person would see + go wrong (pops, jumps, lurches, overshoot, flicker, text swaps, motion that never settles or + keeps waking) against the `RULES` thresholds, and `gate` runs the app's cells in parallel and + fails on findings its allowlist doesn't explain. `scripts/motion-audit/gate` runs it with a + cell filter, `--dump` and `--sheet` evidence; `scripts/motion-audit/motion-trace.py` reads an + app's own frame-cost trace from a real run. + +- **`scripts/rune-dev --local` hot-reloads on one machine.** The compiler, the edit guard and the + app run here with no build Mac, and an edit that needs a restart rebuilds and relaunches the + app. `RUNE_DEV_WRAP` runs it under a command prefix (default: plain `cargo`). + `scripts/rune-hot --manifest … --patch … [--port …]` is the same with an app script's flags. + +- **New crate `rune-knobs`: live tuning values and the ⌘⇧K panel.** A `Knob` is a named + slider or choice with a range and a default, grouped by the keyed element it tunes. The panel + comes as a side panel that pushes the page over (`side`), a floating panel (`layer`), or rows + for an app's own layout (`inline`, `actions`), such as `App::playground`'s side column. + Without the `panel` feature, knobs read their defaults and the panel isn't built. + `examples/knobs` shows it. + +- **New crate `rune-mac`: small macOS helpers for apps.** `remember_frame` and `saved_size` + reopen a window where and at the size it was, `toggle_full_screen` and `is_full_screen` drive + the green button's full screen, and `launch` and `busy` pair with the new `scripts/mac-app` + to relaunch a rebuilt app behind the app in front, and to hold a relaunch off while the app + is busy. Off macOS they do nothing. + +- **Scroll viewports measure all direct children.** `El::scroll`, `El::scroll_x` and + `El::scroll_xy` now measure their content extent across every present direct child instead of + only the first, so a scroll container holding several rows or tiles directly scrolls to its + end, follows `stick_bottom`, and reveals later children with `Tx::scroll_into_view` without + needing a wrapper column or row. Growth-stack tracking (`El::growth`) finds the growth-stack + child among direct children and warns once in debug builds if `.growth(..)` is placed on the + scroll viewport itself or followed by trailing sibling elements. + +- **Pills in static text.** `El::pill(range, PillStyle)` and `El::pills(..)` draw byte ranges of a + `text` or `rich` element as the rounded chips a field draws for `Mark::Pill`: chip colour, + label colour and icon from the `PillStyle`, a label that never splits across lines, and chip + padding that takes room in the line. Selection and copy treat the label as text, and `El::spans` + called afterwards keeps the label colours. On a field it does nothing (use `El::pill_style`). + +- **An editor the app draws gets the input method: `App::on_ime` and `El::ime_cursor`.** The + input method was on only while a `text_input` had focus, so dead keys, CJK input, the emoji + picker and dictation couldn't reach an app-drawn editor. Mark its caret `.ime_cursor()`: + while it's drawn and no field has focus, the window turns the input method on with the + candidate window at the caret, and `App::on_ime` (and `WindowSpec::on_ime`) hears + `Ime::Preedit` with its cursor range, `Ime::Commit`, and the new `Ime::Enabled` and + `Ime::Disabled`. Plain typing still arrives as keys, so nothing arrives twice; Return and + Escape mid-composition go to the input method. A focused field keeps the events and a + focused secure field keeps the input method off. An exhaustive `match` on `Ime` needs the + two new arms. + +- **File drops say where they land: `Tx::drop_point()` and `El::on_drop_move`.** In + `on_drop_files`, `on_drop_rejected` and `on_drop_hover(true)`, `tx.drop_point()` gives the + drag's point on the element (its own points, following scroll and transforms, and the + window's), so an editor can insert a dropped file where it landed. `.on_drop_move(|s, p, tx| + ..)` hears the point when the target is reached and as the drag moves over it, at most once a + frame, for a drop caret. Hosts already passed every position (AppKit's at every step, the + sampled pointer elsewhere); `Runtime::drag_files_to` now also queues a move, and asks for a + frame, when the drag moves over a target with `on_drop_move`. Nothing changes for targets + without one. + +- **Images: EXIF orientation, and a decoder panic fails only its image.** `ImageCache` turns a + JPEG upright by its EXIF orientation (a phone photo stored sideways used to draw sideways, + with its width and height swapped). A panic inside a codec on a malformed file used to end + the cache's worker, leaving that image pending forever and failing every later one with + "image worker stopped"; it now fails that image with "image decoder panicked: …" and the + worker goes on. + +- **Dropdowns fit the window, and a click shows no focus ring.** `El::anchored_fit` places an + overlay like `anchored` and, when it fits on neither side of its anchor, puts it on the side + with more room and caps its height (or width) to that room, so a scroll viewport inside + (`.shrink().min_h(0.0)`) scrolls instead of running off the window. rune-kit's `Popover`, + `Menu`, `Select` and `PopupList` use it above or below their trigger, and their rows scroll + with faded edges; a `Popover` body now shrinks. Focus shows only after keyboard navigation, + as CSS `:focus-visible`: Tab, the arrows, Home, End, Page Up and Page Down (and type-select + that moves focus) show it, while Space, Escape or typing after a click no longer do. + +- **`Drag::clicks` counts a run of presses for `on_drag`.** 1, then 2, 3 and on for presses on + the element each within the double-click interval and 4 pt of the one before (AppKit's + `clickCount`), the same on every phase, so an app-drawn editor can select by words or lines + and extend by them as a double- or triple-click drag moves. A press that drags past 4 pt + ends the run. `on_double_press` is unchanged. Code that builds a `Drag` itself (Rune's own + only; its private field keeps apps from it) sets `clicks`. + +- **`Tx::open_folder(options, on_answer)` and `FileDialogs::open_folder` pick a folder.** + An Open dialog that chooses an existing folder: rfd's `pick_folder` on macOS and Windows, + the portal's `OpenFile` with `directory` on Linux. It waits in `--tree` as a `fileDialog` + of kind `"folder"` and scripts answer it with `file-dialog` as they do a file. New + `FileDialogKind::Folder`: an exhaustive `match` on `FileDialogKind` needs its arm. + +- **`Tx::set_title(title)` sets the window's title** from a handler or `update`, without + asking for a frame. The window opens with `AppSpec`'s title and, closed and opened again, + with the last one set. Headless `--tree` output gains a `"title"` field. + +- **`Tx::key_base()`: the character a key types with no modifiers.** In a key handler it gives + the key's character under the current keyboard layout with no modifiers held, from winit's + `key_without_modifiers` on macOS, Windows and Linux: `Some('a')` for ⌥A, which arrives as + `Key::Text("å")`, and for AZERTY's A key, where `Tx::physical_key` says `KeyQ`. Bindings by + letter that follow the layout (as `DefaultKeyBinding.dict` binds ⌥-letters) match on it. A + script key with a `"code"` takes a `"base"`, else its one-character name pressed without + Shift or Option. + +- **`Player::preload` decodes a clip's first frame before anything draws it.** A clip's poster + was only requested the first frame it drew, so a page opening on a clip showed an empty box + for a few frames while a worker opened it. An app that knows which page comes next can now call + `preload()` on its clips; the first frame that + draws one shows its picture. It does nothing for audio, once a poster or player has started, + or headless, where frames decode as they draw. + +- A selection highlight also bridges the small gap a chip's icon and padding leave, and runs as tall as the line's tallest text, so words and chips on a line share one rect. + +- **`OverlayHandle::set_exclude_from_capture` changes a live overlay's capture exclusion.** + `OverlayOptions::exclude_from_capture` was fixed when the native window was made, so an app + that lets recorders see its overlays on demand (a demo mode) had to recreate them. The new + call flips macOS `sharingType` between none and read-only, and the Windows display affinity, + on the existing window, shown or hidden; `capture_exclusion` reports the new state. + +- Selectable texts flowed side by side (words around a chip) draw one continuous highlight rect per line instead of one per word, so no seams show between them. + +- **`rune::text::ink` says where text's ink sits.** Text is placed by its line box and + advance, so symbols like ↵, ⇥ and ⌘ draw off the middle of a box that centres them. + `ink(text, style)` rasterizes the text with the renderer's fonts and fallbacks at 8× and + returns a `TextInk` with the ink's bounds and centre of mass in points from the text's box, + cached per text and style; `TextInk::optical(pull)` gives a point between the two for + centring a glyph by eye. + +- **Apps receive links opened with them.** `App::on_open_url(|s, url, tx| ..)` (and + `WindowSpec::on_open_url`) runs on macOS for each `myapp://...` link the system opens with the + app, including the one that launched it, which runs before the window's first frame: the event + loop installs a get-URL Apple event handler before it starts (winit 0.30 doesn't forward these) + and keeps links until a window whose app has the hook starts, then runs them in order as + `AppHandle::update`s, waking an idle loop. Without a hook the handler goes once launch is over, + and an app's own handler is left alone. The app's bundle declares the scheme + (`CFBundleURLTypes`; see the README) and must validate the string. Other platforms never call + it. + +- **A window an `AppHandle::update` opens opens in the same turn.** The window host took the + other requests (open, show, focus, place, quit) before running the queued updates, so one an + update made waited for the next wake; a windowless app opening its window from an update + dropped the GPU it had prewarmed at launch first. Updates queued before launch now also run + before the window's first frame. + +- **`Tx::scroll_key_to` and `El::sticky_top_showing` land a new page right on its first frame.** + `scroll_key_to(key, at)` scrolls instantly so element `key`'s top sits `at` points below the + viewport's top, computed from the layout of the commit the handler causes, so it applies + before that layout draws (no marker, no correction a frame later). `sticky_top_showing(show)` + is `sticky_top` held with only the element's bottom `show` points in view, measured from its + height as laid out in the frame that draws it, so a header whose height changes (or a new + page's taller one) sticks in the right place at once instead of a frame late. + +- `Tx::copy_rich` now writes a `ClipboardContent`'s image (PNG and TIFF on macOS, PNG on the web, pixels on Windows and Linux) and its new file list (`ClipboardContent::with_files`, read back with `files()`): one file URL item per file on macOS, so Finder pastes the files, and the file list on Windows and Linux. Windows and Linux write one form per copy: the files, else the image, else HTML with the text. The text may be empty beside an image or files, and isn't written then. Pastes to hooks that take every form carry the files too. + +- The Menu key (new `Key::ContextMenu`, from winit, the web and Wayland layer shells; `ContextMenu` in headless `--keys`) and Shift+F10 open the focused element's context menu: its focused link's `on_link_secondary`, else its own or its nearest ancestor's `on_secondary_press`, at the bottom-left of the link or element. A key handler or focused field that takes the key keeps it, and with no handler nothing happens. A `match` on `Key` with a `_` arm is unaffected. + +- `El::on_link_secondary` and `Markdown::on_link_secondary` take a right-click (or macOS control-click) on a link's glyphs with its id and point, for a per-link menu. The link takes the press from ancestors' `on_secondary_press` and the text's Copy menu; elsewhere in the text they still get it. + +- **`El::on_scroll_offset` follows a scroll viewport exactly.** On a scroll viewport it is + called with a `ScrollPos` (the offset and how far it can scroll) once at first, then in + every frame scrolling moves it (the wheel, a glide, a reveal) or its content resizes, after + that frame's scroll step and before it draws. A + `Live` set from it shows in that same frame, so a header that shrinks or fades as a page + scrolls rides the scroll 1:1, where `on_drawn_layout` hears a frame late and not at all + while a glide runs. `Scene::present` presents values set after `Scene::frame` without + stepping time. `El::on_layout`, `on_screen_layout` and `on_drawn_layout` moved, unchanged, + to `layout_watch.rs`. + +- Settled elements resnap to the pixel grid when the display scale changes, without waiting for an animation or hover update. + +- Scrolling long lists and sticky sidebars spends less CPU on unchanged hover highlights, preserving their enter and exit animations. + +- **`Cx::layout_with` and `Cx::layout_size` read what a view needs from an element's rect, + re-running it only when that changes.** `layout_with(key, f)` returns `f` of the rect + `Cx::layout` would, and re-runs the view only when `f` of the new rect differs from `f` of + the old one: `layout_with("feed", |r| r[1] < 0.0)` re-runs a header on the frames the feed + scrolls past the top, not on every scrolled frame. `layout_size` is `layout_with` the + `[w, h]`, so a view sizing something from an element inside a scrolling viewport no longer + re-commits on every scroll frame. Both settle on the first layout as `Cx::layout` does, so + the first frame has the right value. `memo::layout_with` and `memo::layout_size` do the same + for components without a `Cx`, and memos that read them are reused while the value holds. + `Cx::layout` keeps its half-point threshold, but movement below it now adds up until it + counts instead of being lost frame by frame, and a memo holding a `Cx::layout` read is + reused through moves below it. Layout reads and `on_layout` report an element's width and + height as layout sized it, so moving an element no longer changes its size by a rounding + error. + +- **A tall whole row glides in no harder than a short one.** An `El::arrives_whole` row glided + on the growth spring's fixed duration however far it went, and a critically damped spring + opens with an acceleration of its distance over its duration squared, so a tall insert (a + restored turn, a long pasted prompt) and the pinned viewport following it lurched as they + started. Past `growth::WHOLE_REACH` (300 pt) the glide now lengthens with the square root of + its distance, so it opens no harder than a 300 pt glide does; shorter glides are unchanged. + +- **Markdown: an outlined table's header no longer cuts off the outline's rounded top corners.** + The header row's fill now rounds by the frame's radius less its inset (and at the bottom too + when the table has no body rows), as the `table_body` card layout already did. + +- **`App::playground`: a storybook built into the window.** ⌘⇧D (Ctrl+Shift+D off macOS, or + `Playground::shortcut`, `None` to turn it off) shows the app's scenes plus its own + `Playground::page`s and `Story`s, grouped by the part of their names before a `/`. One shows at + a time on a plain stage, live and interactive, with a column beside it for the story's `side` + view and its single-letter triggers. R makes the story's state again and runs its `'r'` + trigger; `Play::after(secs, step)` queues timed follow-ups on the logical clock, so a replay + runs the same every time. ↑↓/J K move between stories, ⌘↑ ⌘↓ go to the ends, → or Tab move + into the side column, Esc leaves. An element focused in the stage keeps its keys until Esc. + Triggers and side views name their scene as `--playground` does, by path or just name. Root + `on_paste`, `on_drop_files` and `on_window_focus` still reach the app above the bar, and the + stage's root while it's open. Scenes get a fresh state, stories their own; the real + state keeps polling and is untouched. It's on in debug builds (`.enabled`, `RUNE_PLAYGROUND=0`); + its bar takes 26 pt off the bottom of the app's content, and `.bar(false)` leaves the app's + layout as it was. Snapshots, `--scene` and goldens never include it unless `--playground + [story]` is passed. `WindowSpec::playground` gives each window its own; hot reload drops it. + `examples/playground` shows each kind. + +- **Breaking: the browser dev panel is gone.** The `rune/dev` feature (and `rune-motion/dev`), + `App::dev_panel`, the `rune::dev` module and the `tune!` macro were removed, along with + `Runtime::motion_blur_enabled` and `examples/dev-panel`. Replace each `tune!("key", default, ..)` + with its default as a plain constant (hot reload picks up edits), drop `dev = ["rune/dev"]` + from the app's features, and audit scenes, pages and overlays with `App::playground`. + `rune::scene_clock()` works without any feature. + +- **A window with a still compositor rests.** A window with a `Compositor` never counted as + resting, so each due `wake_after` built and presented a frame even when `poll` changed + nothing (four presents a second for a 250 ms timer). When `Compositor::animating` is false, + the window now rests like any other: a due timer runs `poll` alone and draws only when that + poll changed something, with one frame for that poll. A compositor's frame still never counts + as unchanged, since the same instances may composite differently. A compositor that reports + `animating` (even one that starts while the window rests) draws every frame and every due + timer, as before. For every window, a resting wake's frame that runs covered or misses its + drawable no longer polls a second time, the timers that poll armed survive the window being + occluded or minimized before its frame, and a frame that leaves a commit pending (a + compositor that updates or invalidates the state while drawing) no longer lets the window + go idle. + +- **Hover waits while layout moves content under a still pointer.** When a row expanded and + the rows below slid, each row passing under a pointer that hadn't moved took the hover for a + frame or so, flashing its hover-revealed controls. The glide hold now covers all layout + motion: frame and offset springs, growth stacks, growths, flights and app-asked glides. As on + macOS, hover lands on the row under the pointer once the motion settles, or at once when the + pointer moves or presses. The hovered element, `on_hover_change`, hover styles, the cursor + and tooltips all hold together. A wheel or trackpad scroll still hovers each row it brings + under the pointer, a press still shows and lets go, and an element that leaves the tree, + starts its exit or turns inert (a modal opening) lets go of hover at once. An element on its + way out now hears `on_hover_change(false)`, which it used to miss; with `hover_delays`, only + an element whose enter was reported hears the leave, now also when it unmounts. A held press + no longer keeps every element it passed inside: only what contains the pressed element. + +- **Adding or dropping `El::group_opacity` fades, and a shrunk-end reader sticks in the tail.** + An element that takes on a group-opacity rest level, or drops one (a parked queue row's + actions shown at rest), now fades from or to full on its motion instead of cutting, and a + dropped one leaves nothing behind once it lands; an instant opacity motion drops it at once. + A reader a collapse glided to the new end sticks to it once the rows are within half a point, + without the rows' last fraction lifting it, so rows arriving in the collapse's long spring + tail grow in under a pinned end instead of mounting below the viewport. `on_far_from_bottom` + measures from the end collapsing rows head for, so a glide landing early or rows regrowing + mid-glide don't report far for a moment. + +- **A glide the app asked for holds a still pointer's hover until it stops.** During + `Tx::scroll_to_bottom` or `Tx::scroll_to`, each row passing under a pointer that hadn't moved + took the hover for a frame, so hover-revealed controls flashed down the list. As on macOS, + hover now waits for the pointer to move or the glide to end, then lands on the row under it. + A wheel or trackpad scroll still hovers each row it brings under the pointer, and ends the + hold. Presses still let go during the glide, and a row that leaves the tree under the held + pointer still hears `on_hover_change(false)`. + +- **A new `El::group_opacity` rest level fades instead of cutting.** Changing an element's rest + level (a row's actions shown or hidden at rest) used to multiply the new level in on the next + frame, so they snapped 0↔1. The rest now moves on the element's `opacity_motion`, or the + commit's spring without one; an instant commit, Reduce Motion and a new mount land it in the + frame. + +- **Rows leaving a padded growth stack all at once hold their place.** With every row removed, + the stack forgot its top padding, so the leaving rows jumped up by it on their first frame. + They now collapse where they stood. + +- **Content shrinking under a reader who scrolled up glides to its new end.** When a growth + stack's rows left or shrank until it ended above the reader's offset, the viewport sat still, + then rode the presented end down at the collapse's own speed (thousands of points a second + from a standstill in one frame). It now glides to the layout's new end from rest on + `motion::GLIDE`, as `Tx::scroll_to` does, never past the presented end, and sticks to the end + once the rows get there. The glide follows a further removal to the newer end, ends if rows + come back past the offset, and leaves the viewport to a wheel, a fling or a kept row until + the rows settle. Settled, instant and reduced-motion changes still land at once. Any glide + whose end the content shrinks past now lands there instead of overshooting and springing back. + +- **A new window holds two drawables until it rests, on macOS.** A window's Metal surface now + starts at frame latency 1 (two drawables) and goes to its configured 2 (three) once the window + first goes idle on screen, or after its first second of frames there. A window that drew frames + back to back while coming on screen (an app animating at launch, or launch frames waiting on + the window server or on shader compiles) made CAMetalLayer allocate a third window-sized + drawable and keep it: about 12 MB more settled memory for a 980x760 window. Raising the count + allocates nothing until a frame needs it, so a window that animates later still gets its third + drawable then. + +- **A resting window's timer runs `poll` alone and draws only when it changed something.** + A due `wake_after` on a shown window with nothing moving used to build, lay out, draw and + present a frame every time, even when `poll` returned false. Now `poll` runs first, as it + does for a hidden window, and the next timer is armed; the view, layout and a frame follow + only when the poll returns true, asks for a scroll, a window frame or the next frame + (`wake_after(ZERO)`), or leaves a request the window must draw for, and that frame doesn't + poll again. An app polling a few times a second while idle builds no frames for those + polls. Motion, scrolls, queued input, hover and tooltip delays, loops, live values, + `SurfaceDraw` content and polls that step every frame take their frames as before. + +- **A resting window presents nothing for a timer frame that draws what's on screen.** When + only a due timer (`wake_after`, `poll`) wakes an idle window, the frame is built before a + drawable is taken, and when its instances, clear colour, surface size, format, scale and + blending match the last frame presented, with no glyph or image upload, `SurfaceDraw` or + system material in it, the window acquires and presents nothing. Cursor, IME, secure input, + help tags and the clipboard still follow the frame. A `poll` that returns true on every tick + with nothing new on screen no longer costs a GPU frame each time. Input, resizes, scale and + occlusion changes, animation, traces and compositors draw as before. + +- **`markdown::find(src, query, case)` (`Markdown::find`, `Case`) searches rendered Markdown text and returns source byte ranges for `Markdown::highlights`.** + Each outer entry of `Vec>>` is one non-overlapping match in document order within a single block (paragraph, heading, list item block, table cell, code block or diff block), and each inner `Vec>` lists the source UTF-8 byte ranges it covers, merged where adjacent and skipping inline markers (`**`, `*`, `~~`, `` ` ``), link and image URLs, and container prefixes. `Case::Insensitive` folds characters with `char::to_lowercase` (and Greek `'ς'` to `'σ'`) while preserving exact UTF-8 byte boundaries when lowercasing changes byte length (such as `'İ'` or `'ẞ'`/`'ß'`). `Markdown::highlights` now accepts `find` matches directly (`Vec>`, `&[Range]`, or paired with `Highlight`) as well as single `Range` items. + +- Cmd+A (and the Select All menu item) with no selection now selects all of a selectable group, so a read-only `Markdown` view needn't call `Tx::select_all_text` itself: the group holding the selection, else the one last clicked or selected in the window while it's mounted, else the window's only selectable group, else nothing. An app's `on_key` still runs first and a focused text field keeps its own. `Tx::select_text` and `select_all_text` document that the key is the element's final key, which a `memo` id replaces. + +- **A launch whose place moves mid-flight turns toward it instead of jumping.** A + `Tx::launch` flight now blends from the offsets outside the scene it left under to the ones + its destination has each frame, so a row above that grows under a growth stack's offset + moves where it lands, never where it is (a prompt growing its copy line as the steer under + it stops joining its run lurched a steer in the air by 25 pt). When a growth row launched + itself and its slot moved, the row's instant vertical place used to land the whole flight + in one frame; it now restarts its path from where it is, on a spring. + +- **Markdown table cards: review fixes.** A scrolling full-width table no longer shifts its columns while its last row streams in. `table`, `table_outline` and `table_like` now replace an earlier `table_frame` or `table_card` (`table_like` also drops the card and the header padding), the table setters treat non-finite points as zero, a table with no body rows is sized by its header's padding alone, and a header's overflow stops at the frame's rounded top corners. + +- **Markdown tables on a card.** `MarkdownStyle::table_body(fill, radius, shadows)` puts the + body rows on a card of their own, rounded and raised, with rules between body rows only and + none under the header, which sits on the frame. `table_frame(fill, ring, pad)` draws a + filled, rounded frame with an inset ring in place of the outline, `table_header_pad(x, y)` + pads header cells apart from body cells, `table_full_width(true)` stretches a table to the + text's width (columns widen in proportion to their content), and `table_margin(top, bottom)` + sets the space around a table. `table_card(&kit)` sets all of these from the kit's tokens: + a raised `bg_base` card 2 points inside a `layer_01` frame, a faint medium header and 13-point + cells. Defaults are unchanged. `MarkdownStyle` now lives in `markdown/style.rs`; its path is + the same. + +- **Instant changes, live resizes and invisible exits land in the frame; a still pointer keeps + its hover while rows mount.** An instant commit lands a pinned viewport's slack at once + instead of gliding it closed a moment later (zoom). During a window resize, rows that rewrap + land at their new height in the frame, so a pinned tail stays put instead of sliding back + after the drag; a streaming row still waits for the width to settle. A removed element that + drew nothing last frame (faded out already, or under a parent that hid at once) unmounts + with no exit, and an exit stops once it draws nothing. An instant close of a modal keeps a + focus request outside it, as an animated close did. Nodes mounting earlier in the tree no + longer drop the hover of a still pointer for a frame (a hover-revealed row's actions + flashed out while a timeline streamed). Scripts take `{"type": "resize", "dw", "dh", + "dur"}`, a person dragging the window's corner. `scripts/motion-audit/analyze.py` adds + `cut-exit`, `reversal` and `dog-leg` findings, script `expect`ations (`instant`, `follow`, + `smooth`, `leaves`) and an allowlist with `--fail`. + +- **`macos_drop` tests skip their pasteboard round trips in a session with no pasteboard.** + A headless or SSH-only Mac (no window server) has no pasteboard server, and the six tests that + write a private pasteboard panicked there. They now probe once, print a one-line skip note and + pass; the pure parts (hover stand-ins, promised types, file URLs, numbered names, URL names, + operations, step coalescing) run everywhere. No change to apps. + +- **`Tx::launch(source, destination)`: a new element leaves from another's text.** The element + keyed `destination` that mounts in this commit starts with its first text on `source`'s text + (a composer's typed words), at its own size, and travels one straight screen path to its + place on `tok::motion::REFLOW` (or the commit's `Tx::motion`). It draws above the window and + outside every clip until it lands, so a sent message can rise out of a panel into a scroll + view while the composer clears. Reduce Motion, instant commits and an already mounted + destination leave it in place. Matched flights also settle later: travel progress settles + like a scale instead of in points, so a long flight no longer ends a couple of points short + and snaps the rest in one frame. + +- **Markdown tables: the header's rule, fill and weight are set on their own.** + `MarkdownStyle::table_header_rule(c)` draws the hairline under the header in its own colour + (a web `th` with a stronger `border-bottom` than the `td`s), `table_header_fill(c)` sets the + header fill without the border, and `table_header_weight(w)` gives the header a medium weight + beside bold `strong` text. Defaults are unchanged. + +- **Multi-click and click-drag selection in `text_input`.** Double-clicking a text field selects + the word under the pointer (sharing `El::selectable`'s Unicode word boundaries), triple-clicking + selects the line in a single-line field or the `\n`-delimited paragraph in a multi-line field, + dragging after a single, double or triple press extends by characters, whole words or whole + lines from the original unit, and Shift-clicking extends from `TextEdit::anchor`. Secure fields + select the whole value on double- and triple-click without marking the secret edited. + +- **The app takes Cmd+A and Cmd+C before selected text, and code can set and read the + selection.** Key routing offers plain Cmd+A and Cmd+C to selectable text last, after both + `on_key` calls and element key handlers, so an `on_key` that returns true for them now wins + where the selection used to take them first. A focused text field keeps its own. New: + `Tx::text_selection()` (a `TextSelection` of `SelectedText`s), `Tx::select_text(key, range)`, + `Tx::select_all_text(key)`, `Tx::clear_text_selection()` (applied after the handler's + commit), `El::selection_copy(|sel| ..)` to choose what Cmd+C and the Copy menu copy, and kit's + `Markdown::copy_source(true)`, which copies the Markdown source of whole top-level blocks. + `El::on_selection_change(|s, change, tx| ..)` hears a selection start, change and clear + (`SelectionChange::started`, `cleared`, `selection`), at most once a frame. + +Entries landed since the last fold are in `changelog/unreleased/`. + +- **macOS windows take drops of file promises and image data.** winit's window took only + drags with file paths, so the screenshot thumbnail, Photos, Preview and browsers' images were + refused. The content view is now the drag destination: a file promise is received into + `$TMPDIR/rune-drops/…`, image data (PNG, JPEG, GIF, WebP, HEIC; TIFF as PNG) is written there, + and the drop reaches `El::on_drop_files` as paths. While hovering, a promise or image shows as + a stand-in path (`File.png`, `Image.png`) so `accepts_files` filters work. AppKit reports the + drag's position at every step, so macOS no longer samples the pointer for it. + +- **`Tx::follow_edge()`: pinned rows ride a moving bottom edge.** Rows stuck to a + stick-to-bottom viewport's end used to hold the room a shrinking sibling freed as slack, then + close it late on the growth spring, which suits a send (a new row grows into it) but leaves a + gap when a panel under a chat folds away. A change made with `follow_edge` carries the rows + on the viewport's edge, frame by frame, on the change's curve, until the edge reaches its + layout. Nothing changes for apps that don't call it. + +- Markdown source highlights track multiline code spans inside quotes and lists exactly. + Highlight element reporting and scroll targeting avoid quadratic work for many matches; + oversized core highlight offsets no longer wrap. Bare URL autolinking accepts uppercase + HTTP schemes and leaves image alt text alone (bare email addresses remain plain text). + +- **Markdown source-byte highlights (`Markdown::highlights`, `Highlight`), strikethrough (`~~struck~~`), and bare-URL autolinking (`Markdown::autolink`).** + `Markdown::highlights` accepts `(Range, Highlight)` pairs in source UTF-8 bytes and maps + them to rendered text across inline formatting, headings, paragraphs, lists, task items, quotes, + tables, diffs and code blocks without reshaping text or shifting line breaks (`El::text_highlight` + / `TextHighlight`). Standard matches (`Highlight::new()`) and active matches + (`Highlight::current()`) draw rounded background fills and optional inset border rings from + `MarkdownStyle` (`highlight_bg`, `highlight_current_bg`, `highlight_current_ring`, or per-match + `.bg(..)` / `.fg(..)` / `.ring(..)`), and each highlight can be scrolled into view with + `Tx::scroll_into_view` by its `.key(..)` or `Markdown::highlight_key(index)`. GFM `~~strikethrough~~` + spans now paint strike lines through `El::strike`, and bare `https://…`, `http://…` and `www.…` + URLs in plain text autolink by default (with GFM trailing punctuation and balanced-parenthesis + trimming, `http://` destination prefix for `www.`, and `.autolink(false)` to opt out). +- **`El::on_far_from_bottom(min, f)`: when a chat shows its jump-to-latest button.** On a + scroll viewport, reports whether it stands more than its own height, and at least `min` + points, above its bottom: once after its first layout, then only on change, like + `on_at_bottom`. A glide back from `Tx::scroll_to_bottom` reports near before it lands. Nothing + changes for apps that don't use it. +- **`Tx::motion_curve(anim)`: a commit's layout on any curve.** `tx.motion` takes only a + spring; `motion_curve` takes an `Anim` (a spring, or a `Curve::tween` with an `Easing`), so an + app can compare eased tweens against its spring for the same layout change. Scroll requests + and matched flights in that commit, which take only a spring, use a zero-bounce spring of the + curve's duration. The last `motion` or `motion_curve` in a handler wins. Nothing changes for + apps that don't call it. + +- **SVG images on every platform.** `ImageCache::svg(bytes, size_pt, scale)` rasterizes SVG or + SVGZ to fit `size_pt` at the window's scale, so a 16 pt mark is crisp at 2×. `load_mime` + takes a MIME type (a data URL's `image/svg+xml`), `file(path, size_pt, scale)` reads a file + on the worker and treats `.svg`/`.svgz` as vectors, and `load` now recognises SVG bytes and + rasterizes them at twice their own size. Before, only Linux app icons drew SVG. resvg moves + behind a default-on `svg` feature; apps that set `default-features = false` on `rune` add + `svg` to keep it. + +- **Secure label review fixes.** Hidden read-only labels use twelve bullets regardless of length. Secure text cannot fly, retain content hashes for layout invalidation, or expose rich links. `Runtime::element_is_secure(path)` reports protected content without changing `ElementInfo` literals. Pristine tracking stores only an edited flag; use `TextEdit::replace_text` for app replacements (including identical values). Backspace at byte zero also clears pristine hidden multi-line fields. +- **Read-only secure text labels (`text(..).secure().revealed(bool)`) and pristine replacement on hidden multi-line secure fields (`TextEdit::is_pristine`, `TextEdit::mark_edited`).** + - Read-only `text(..)` and `rich(..)` elements now support `.secure()` and `.revealed(bool)`, sharing the same protections as secure `text_input`: plaintext never enters `TextSystem::layouts`, `TextSystem::shapes`, ancestor `El::cache` rasters (`node_caches` / `resident_caches`), `ElementInfo::text`, `ElementInfo::selected`, `Debug` (`[redacted]`), or `--tree` JSON; selection and copy are disabled (even if `.selectable(true)` is called before or after `.secure()`); and owned `TextSpec` source buffers are zeroized on conceal and `Drop`. Hidden labels show a fixed twelve-bullet mask (`""` when empty), independent of length and line count. When revealed (`revealed(true)`), labels lay out and elide/clamp/wrap normally (including `.wrap_anywhere()`, `.max_lines(..)`, `.truncate()`), snap geometry and ancestor scroll immediately without height animation when concealed back to `revealed(false)`, and conceal to the mask on their first exit frame. + - `Runtime::element_is_secure(path)` (and `--tree`'s `"secure": true`) identifies both secure labels (`role: "text"`) and secure inputs (`role: "textbox"`). + - Hidden multi-line `.secure()` fields whose value has not been edited by the user since the app last set it (`TextEdit::new` or `replace_text`) are now pristine (`TextEdit::is_pristine()`, cleared by user edits or `TextEdit::mark_edited()`). While pristine and hidden, any insertion (typing or paste) replaces the entire value with the inserted text and any deletion (`Backspace`, `Delete`, `⌘⌫`, `⌥⌫`, `⌃K`) empties the field, independent of caret or selection; the first edit clears pristine so subsequent edits append or delete at the end as usual. Toggling `revealed` does not reset pristine, an empty field is never pristine, and revealed fields edit normally at the caret or selection. + +- **Stacked paint fades into a soft clip as one.** Under `clip_fade` (or a feathered mask), each + primitive faded on its own, so an image over its placeholder fill, or a label over its bubble, + let the paint beneath show through the fade: a dark image on a lighter fill brightened towards + the edge instead of fading to the background. An element that paints over its own paint (two + of fill, border, gradient, shape, pixels, shadows, text; or one of them under children) now + composites as one layer while it reaches into a soft edge, and takes the fade once. Elements + clear of the fade edges draw as before. + +- **`examples/opencode` left the repository** (it moved out). Its golden check is now `crates/rune-kit/tests/markdown_fixture.rs`: eight headless Markdown trees (mermaid, code, tables, task lists, narrow wrapping, streaming) in both OpenCode-theme appearances, compared with `crates/rune-kit/tests/golden/*.json`; accept intended changes with `RUNE_BLESS=1`. `scripts/check-ui.py`, `bench-build.py`, `bench-gpu-springs.py` and `text-bench.py` went with it, and `rune-dev`, `bench-ui.py`, `bench-startup.py`, `snap-ui.py`, `text-goldens.py` and the motion audit no longer list it. + +- **`El::arrives_whole()`: a growth-stack row whose content arrives complete glides on the growth + spring alone.** Such a row (a sent message, a finished reply loaded at once) skips the speed + limits that pace streaming text, so a large insert, and a pinned viewport following it, moves in + one critically damped glide instead of a long capped climb. Rows without it are unchanged; a row + that is also `streaming(true)` keeps the limits. + +- **`Tx::open_url`, `El::mx`/`El::my` and `rune::prefs::Prefs`.** `Tx::open_url(url)` opens + `http:`, `https:` and `mailto:` links in the system handler on macOS (`NSWorkspace`), Windows + (`ShellExecuteW`) and Linux (`xdg-open`), as `web::open_url` already did; other schemes + (`file:`, an app's own), empty and malformed links return `OpenUrlError` and open nothing. + Headless runs open nothing and keep the links for `Runtime::take_url_requests`. `mx` and `my` + set both margins of an axis. `Prefs::open(app_id)` is a JSON settings file in the platform + config directory with typed `get`/`set`, atomic saves, and a corrupt file moved to + `prefs.json.bad`; `Prefs::memory()` and `RUNE_PREFS_DIR` keep tests and headless runs off the + real file. `rune` now depends on `serde` on every target (it already did on Linux). + +- **A window comes on screen with its first frame on macOS.** A visible window (not a panel or a + hidden launcher) now draws its first frame while it's being created, before the window server + reports it on screen, instead of opening empty and drawing on a later display-link tick. The + first view build and layout now run inside window creation, right after the window-created + callbacks. Content reached the screen about 30 ms sooner at launch on an idle Mac, and about + 150 ms sooner on a busy one, where the window server is slow to report a new window visible. +- **`rune::prewarm_gpu()`: the GPU device and render pipeline start on a thread before the first + window.** On macOS, Rune's run functions now make the device and compile the uber pipeline on a + thread while AppKit starts, and the first window or overlay opened at launch picks them up + (waiting if the thread is still working) instead of making them after the window exists. Call + `rune::prewarm_gpu()` first thing in `main` to start it sooner. A window whose compositor wants + features the prewarmed device lacks gets a new device as before; with no window at launch the + result is dropped. On a first launch after an install or update, when Metal compiles the + shaders, a window's content arrived about 135 ms sooner. Elsewhere it does nothing. +- **`Gpu::instance()` no longer enables wgpu's indirect-call validation.** Rune issues no indirect + draws or dispatches, and the validation pipeline wgpu builds for every device cost about 40 ms + on a Mac's first launch after an install or update. Indirect draws a `Compositor` records on + Rune's device still run; wgpu no longer validates their argument buffers. +- **Rows inserted in the same commit as a `scroll_into_view` land at full height again.** In a + reader's virtual growth stack (unpinned, or `stick_bottom: false`), a commit that inserts + rows and calls `tx.scroll_into_view` grew the new rows from zero since growth started springing + under reveals. A search list that put a new first result above its first row and revealed it + showed only that row's header for several frames, and a row with no header showed a sliver. + New rows now land at full height under a reveal in their own commit, as they do under one left + from an earlier commit, so the reveal shows them whole on the first frame. Rows already in the + stack whose height changes keep springing, and pinned `stick_bottom` timelines are unchanged. + **Output change** for an app that inserts and reveals rows in one commit. +- **Metal shader fallback also covers pipeline creation.** If Metal accepts the precompiled + library but rejects its pipeline, `Renderer::new` retries with WGSL without an uncaptured GPU + error. Shared layout descriptors and the actual Naga options have semantic fingerprints; + unrelated Rust edits do not invalidate them. Freshness tests print replacement hash lines + when MSL is unchanged, without needing Xcode. wgpu/core/hal allow `30.0.x` patch updates. +- **Precompiled Metal uber shader on macOS (`crates/rune/src/uber.metallib`).** `Gpu` now enables + `wgpu::Features::PASSTHROUGH_SHADERS` on macOS when the adapter supports it, and `Renderer::new` loads a + committed 33 KB precompiled Metal library (`-std=macos-metal2.3 -mmacosx-version-min=11.0 + -fpreserve-invariance -O2`) via `Device::create_shader_module_passthrough`, skipping WGSL + parsing, validation, Naga MSL translation, and Metal's front-end `newLibraryWithSource` compile + on every launch (`232 ms → 85 ms` for `Renderer::new` on a cold Metal shader cache, and + `3.4 ms → 0.6 ms` warm). Falls back to the WGSL path when `PASSTHROUGH_SHADERS` is absent, + `RUNE_DISABLE_METALLIB=1` is set, the WGSL/ABI fingerprint mismatches, or library/pipeline creation fails; app + builds do not require Xcode (`scripts/precompile-metal-shaders.sh` regenerates the `.metallib` + when generated MSL or Metal compile flags change). +- **macOS: live window resizes no longer stretch the last frame.** While the user drags a window + edge, Rune draws each new size inside AppKit's resize and presents it in the same Core Animation + transaction (`presentsWithTransaction` for the drag, back to its own present on the first frame + after). Before, the old drawable was stretched to the new size until the next display tick, so + text widened with the window and snapped back. The Metal layer's contents gravity is now the + window's top left rather than `resize`, so a frame that does arrive late keeps its scale and + stays pinned to the top left instead of stretching. A slow frame now holds up the drag rather than + showing stretched. `cargo run --release -p rune --example live_resize_check` checks this + against a real window. Other platforms are unchanged. +- **`El::wrap_anywhere` and `rune_kit::TextArea::wrap_anywhere` (`overflow-wrap: anywhere`).** + `text(..)`, `rich(..)`, `text_input(..)` and `TextArea` now offer `.wrap_anywhere()`, which wraps + at normal word boundaries when words fit and breaks inside an unbroken token (such as a base64 + key or long URL) only when the token alone would overflow the line, while lowering the text's + min-content width without overriding flex shrinking (use `.shrink()` in a flex row). Multi-line + `.secure()` fields enable `wrap_anywhere` by default. +- **Multi-line secure fields (`rune_kit::TextArea::secure`, `TextArea::revealed`, and multi-line `text_input(...).secure()`).** + A multi-line field marked `.secure()` now accepts `Enter` to insert a newline (`⌘Return` / + `Ctrl+Return` still submits) and preserves newlines and tabs on paste while keeping all secure + protections (no undo/redo, copy, cut, IME composition, accessibility text, or layout/subtree + caching, with zeroized buffers and redacted `Debug`). When hidden (`!revealed`), a non-empty + multi-line secure field renders a fixed single-line bullet mask (`"••••••••••••"`) at a fixed + height so neither byte length nor line count is leaked; the visual caret pins to the end of the + mask, pointer hits place the caret at the end of the model, and any active selection highlights + the full mask. Hidden edits append or replace the whole selected value; navigation moves to + the end (Shift selects all), and Backspace deletes at the end. Reveal for interior edits. + Hiding snaps geometry and resets ancestor scrolling rather than animating old line counts. + When revealed (`revealed(true)`), multi-line fields show their real lines, wrap + long unbroken tokens with `wrap_anywhere`, scroll inside `TextArea::max_height` / `auto_grow`, + and conceal back to the fixed mask on the first exit frame. +- **`El::hover_motion_within(enter, exit)`: a subtree default for hover curves.** Every hover track + below it (and the element itself) without its own `.hover_motion(..)` uses the nearest + ancestor's pair instead of the core default (instant in, 0.1 s ease-out out), so + `.hover_motion_within(Anim::INSTANT, Anim::INSTANT)` on the view root makes kit controls' + inner hovers (`SegmentedControl` segments, `Switch` track, ...) switch at once. Hover groups + read it too. `rune_kit::root` carries the base's pair to the popups it layers beside it. + Without it nothing changes. +- **Caret geometry and focus in virtualized growth stacks with a vertical gap.** `VirtualList` + and `Stack` now include a column container's vertical flex `gap` (`style.gap.height`) in row + prefix sums, `before`/`after` padding, `stack_extent`, `reveal_row_once` and painted `row_dy`, + and `caret_rect` includes any active ancestor growth-row shift (`stack_row_dy`). Previously a + growth stack with `.gap(g)` shifted each mounted row `k` up by `k * g` when painting while + leaving `caret_rect` at the unshifted layout target and clamping `scroll.max` short by + `(mounted - 1) * g`. `sync_requested_focus` now also considers newly focused fields in + offscreen virtual rows (`virtual_inputs`) instead of clearing their `focused` flag before + `scroll_into_view` mounts them, and `follow_caret` re-commits when its scroll shift crosses a + virtual window edge. +- **A `dissolve` parent no longer isolates for a child too faint to paint.** The dissolve pass + counted any child above opacity 0; it now uses the same 0.001 threshold as painting, so a child + faded to near zero no longer forces its parent into an offscreen layer. +- **Secure `TextEdit` and `TextInput` reveal toggle (`revealed`, `set_revealed`, `is_revealed`).** + A `.secure()` field can now show its real characters with `TextEdit::revealed(true)` / + `set_revealed(true)`, `El::revealed(true)` or `rune_kit::TextInput::revealed(true)` (as in a + password manager's show/hide button) while keeping every other secure protection: no undo or redo + history, no `⌘C` or `⌘X` clipboard writes, no IME composition (`has_secure_focus()` stays `true`), + `ElementInfo::text` remains `None`, `Debug` on `TextEdit`, `InputSpec` and `TextSpec` stays + `[redacted]`, model and rendered text buffers zeroize on replace and drop, and an exiting field + conceals back to bullets on its first exit frame. Word movement (`⌥←` / `⌥→`) treats a hidden + secure field as a single masked word and steps over words normally while revealed. Secure + runs bypass the shared layout cache and use a disposable shaping context; secure fields also + disable ancestor subtree raster caches even when unfocused. Third-party shaping scratch is + released, not guaranteed zeroized. Handled key releases in secure fields are redacted in + the runtime event log too. +- **`El::span_ring`, `El::span_rings`, `LinkPaint::ring`, and `Markdown::link_ring`.** Draws an + inset border ring `(color, width)` inside a span's rounded `Span::bg` rect (`4 pt` corner radius), + so link chips remain visible when their fill is close to the page background. + Touching runs inside one ringed range merge into one rect per line, wrapped lines each get their + own ring, and the resting ring stays on hover unless `LinkPaint::ring` overrides it. Leaves `Span` + and `RichStyle` struct literals unchanged. Rings require a background, follow case conversion + and truncation, and fade with the last revealed word on each line. Ranges are static, not + rebased by text input edits. The public `Deco` literal is unchanged too. + +- **`Pick`: pick fully transparent elements.** `Runtime::element_at_with`, `element_at_in_with`, + `contains_with` and `Tx::element_at_with` / `element_at_in_with` take a `Pick` (private fields, + builder methods); `Pick::new().transparent(true)` also finds elements whose own or inherited + opacity is 0, so a design canvas can select an invisible layer. Exiting elements stay skipped. + The existing methods use `Pick::default()` and behave as before. +- **GFM task list checkboxes in `Markdown`.** `- [ ] todo` and `- [x] done` items now parse with + `pulldown_cmark::Options::ENABLE_TASKLISTS` and render as `Checkbox`-styled `"checkbox"` rows + instead of `"•"` bullets, with `label` set to the item's text and checked state on + `ElementInfo::item_selected`. Existing `Checkbox` output is unchanged. + `Markdown::on_task(|s, block_key, marker_offset, checked| ..)` and + `Markdown::on_task_tx(|s, block_key, marker_offset, checked, tx| ..)` fire on pointer press, + or focused `Space` with the top-level block's key (`block_keys` or `b{index}`), the + source byte offset of `[` in the task marker (including nested items), and the new checked + state. Task rows are read-only and outside Tab order when no `on_task` handler + is set or when `Markdown::tasks_read_only()` is called. **Output change:** markdown lists using + `- [ ]` / `- [x]` task syntax now mount checkbox controls instead of bullet text. + +- **`Markdown::block_keys`.** Top-level blocks can now take caller-supplied `(source_byte_offset, key)` pairs + instead of `b0`, `b1`, … (nested blocks inside a list item or block quote keep `b{index}` under + their parent block's key), so inserting, removing, reordering or editing blocks above others + keeps unchanged blocks' keys and springs their layout while inserted and removed blocks play + their enter and exit transitions. Offsets identify the start of each block's first source line, + including indentation; callers update offsets after edits while keeping IDs stable. Unmatched + offsets are ignored, so different parser boundaries do not shift later IDs. Missing, empty or + repeated IDs fall back to an unused `b{index}`. Without `block_keys`, index keys stay unchanged. + +- **`TextInput::plain` and `TextInput::leading_icon_size`.** `plain()` draws the field with no + fill, sheen, shadow, border, hover tint or focus outline, for sitting in a header (focus shows + as the caret and selection, invalid as red text, and disabled dims to 0.5); text, caret, icon, + trailing slot, copy/clear buttons, press-anywhere focus and `on_action` work as before, and the + horizontal padding is unchanged. `leading_icon_size(points)` sets the icon's side (default 16, + so nothing moves); the icon stays centred and the text start follows. +- **Pose and picking reads.** `ElementInfo::moving` (and so a settle loop built on it) now also + counts shadow colour and geometry springs and icon turns; rotation and scale already counted. + `Runtime::presented_pose(key)` returns a `Pose` with the presented rotation, effective scale, + shadows (geometry and colour as sprung) and a moving flag. `Runtime::element_at(x, y)` returns + the topmost drawn element at a window point (`Picked`, with `path()` and `key()`), through + rotate, scale, origin, offset, scrolling, ancestors' clips and paint order, handlers or not; + `Runtime::contains(key, x, y)` tests one element. Both are made for drivers holding the + `Runtime`; a running canvas can use `Tx::element_at(x, y, callback)` or + `Tx::element_at_in(scope, x, y, callback)` with a pointer event's window coordinates. + The callback runs before the handler's view commit; scoped picking ignores other subtrees. + Invisible geometry with nonzero element opacity remains pickable, even without a fill. + Decorative loops still report moving, so bounded settle waits should exclude looping elements. + +- **`Markdown::on_link_tx` and `Markdown::link_style`.** `on_link_tx(|s, url, tx| ..)` is `on_link` + with the press's `Tx` (`on_link` is unchanged; the two share one slot so the later call wins). + `link_style(|url| -> Option<(Span, LinkPaint)>)` gives chosen links their own resting `Span` + (colour, weight, `bg` with padding, underline; emphasis, strong and inline code inside a link + keep their styles over it) and hover paint, whose `bg` takes the resting span's `bg_pad` and + height; `None` keeps the default look, so nothing moves unless an app opts in. Touching runs of a + padded `Span::bg` now merge into one rounded rect. + +- **`PopupList::padding` and `PopupList::row_radius`.** The popover's padding and each row's + corner radius were fixed at 4 points; both builders keep 4 as the default, so nothing moves. + `PopupList::items` now documents that a commit calling `tx.instant()` swaps the rows and the + popover's height at once. + +- **Rows entering a virtual growth stack while a reveal runs land at full height.** A + `scroll_into_view` (or a `reveal_selected` list's own reveal) outlives its commit while the + viewport's springs run. Until now any later commit in that window grew its new rows from + zero instead of landing them, as a reader's virtual list does otherwise. Inside a popover whose + height springs at the same time, the two springs moved rows past their slots: a `PopupList` + above its field, filtered to one row and then given more rows while the removed ones still + collapsed, raised its last row 4 points past its slot before it sank back. **Output change:** + in a reader's virtual list (unpinned or `stick_bottom: false`), those rows now land at full + height and ride the popover's edge one way. Rows already growing under the reveal, and + `stick_bottom` timelines whose reveal is at the tail, keep growing on their spring. + +- **`SidebarRow::subtitle_color(Color)`.** A two-line row's subtitle colour, in place of the + default `text_faint`. +- **Sticky elements stay opaque under `El::scroll_edge_fade`.** `El::sticky_top`, `El::sticky_bottom` + and `El::sticky_left` no longer inherit their scroll viewport's edge fade on the edge they stick + to, so a stuck header's fill and text stay crisp and occlude rows scrolling under them, and + sections nested inside a `memo` growth row bound their sticky children to the animated row height. + The exemption also applies before the header sticks, without an opacity jump at the threshold; + explicit `clip_fade` masks and fades from outer viewports still apply. +- **Two-line `SidebarRow`s read as a title over a caption; select-only rows; launcher fields.** + **Output change** for rows with `.subtitle(..)`: the name is now medium weight (13 / 16) and the + subtitle the kit's `caption` (11 / 16) in `text_faint`, where both were 13 / 16 and the subtitle + was `text_muted`; both lines still fit the 40 pt default. The row's accessible name is now + "Name, Subtitle" (it was the name alone). `SidebarRow::title_style(..)` and `subtitle_style(..)` + override the two types. `SidebarRow::select_only()` makes a row that shows the selection but + never takes focus: out of Tab order, a press selects it and leaves an outside field focused. + `El::preserve_focus_on_press(true)` is documented as working on any element (the press still + reaches `on_press`; scrolling still cancels it). `TextInput::text_style(TextStyle)` sets the + field's type (caret, placeholder and selection follow; the box grows to fit) and + `TextInput::height(..)` its height (at least the style's line height), for a launcher-size field. + A press anywhere on a container with `role("textbox")` focuses its one reachable editor: a + supported pattern, now documented on `El::role`. `rune_theme_opencode::ember(dark, step)` (1 to + 12, else panics) and `scale(name, dark, step)` give typed colour-scale steps; `brand(dark)` is + `ember(dark, 9)`. + +- **`Toolbar`'s leading slot gives way.** The leading slot now shrinks (`shrink().min_w(0)`), + so a long leading title marked `.truncate().shrink().min_w(0.0)` truncates instead of pushing + the trailing slot past the band's end. Toolbars whose contents fit are unchanged. +- **Expressive press motion.** `El::scale` now springs between values on the element's layout + spring, or on `El::scale_motion(anim)`, instead of snapping; it lands at once under Reduce + Motion, in an instant transaction and on mount. **Output change:** an app that changed `scale` + between frames now sees it animate; pass `.scale_motion(Anim::INSTANT)` (or `tx.instant()`) to + snap. `El::origin(x, y)` sets the unit point that `scale`, `live_scale`, `press_scale` and a + transition's scale pivot about (default centre); `offset` ignores it. The first four shadows' + x, y, blur and spread now spring on the layout spring, as their colour already did, instead of + snapping. `El::rotate(radians)` turns an element and everything in it clockwise about its + origin, springing like `scale` (or on `El::rotate_motion`). A turned subtree draws into a + layer whose composite turns; hit testing follows the turned box while the reported rect uses + its upright bounds, and a turned subtree never caches. Layer records carry the turn in + `border[1..4]` (`Instance::turned`), which rune-ref now renders. `demo/motion/press.png` shows + a keycap at rest and pressed (the `expressive_press` example). + +- **`PopupList` and `PopupItem`.** `Combobox`'s virtualised popup listbox is now a standalone + `rune_kit` component (`PopupList::new(key, anchor)` with `PopupItem::new(id, label)` rows) for + anchored popovers filtered by an outside field, such as a chat composer's `@`-mention and + `/`-command popovers. Each `PopupItem` takes an optional `.description(..)`, `.leading(el)`, + `.trailing(el)` and `.disabled(true)`. `PopupList` takes no keyboard focus and pressing inside + it leaves the outside field focused, while `on_active` and `on_choose` report pointer hover and + selection. Changes to `.active(..)` reveal the selected option except on hover frames; + the listbox's accessible label stays stable. Defaults are top/start, 260 points wide and + 240 points maximum list height. `Combobox` shares the list builder but keeps its existing + row contents and 192-point viewport. `El::reveal_selected(true)` opts virtualized stacks + into selection reveal; `El::preserve_focus_on_press(true)` keeps outside focus on presses + in unfocusable popup content. Ordinary lists retain their scrolling and blur behavior. + `TextArea::animate_edit_layout(bool)` controls edit-driven layout animation. +- **`LoopSpec::easing` for slides.** `LoopSpec::slide(..).easing(Easing::LINEAR)` sweeps at a + constant speed, for a shimmer; slides stay ease-in-out by default, and reduced motion still + holds the midpoint. The curve rides in a new `LoopKind::SlideEased { from, to, easing }` variant, + so `LoopSpec` and `LoopKind::Slide` keep their fields and literals still build. **Build break + only for exhaustive matches:** a `match` over `LoopKind` with no `_` arm needs a `SlideEased` + arm, and code that tests for `LoopKind::Slide { .. }` to find slides should test for both. +- **An anchored box keeps its aligned edge while it resizes.** An `El::anchored` box whose size + springs (a pill over a composer whose label grows, a popover that shrinks) now keeps the edge + facing its anchor `gap` points away, and the edge its `Align` names on the anchor: `Align::End` + its end, `Align::Center` its centre, `Align::Start` its start, on every side. Before, its + position also sprang from where it last sat, so an End-aligned box growing by 77 points first + swung its end edge 76 points past the anchor and back, and a `Side::Top` popover shrinking from + 180 to 57 points jumped its top far above its new place and sprang back down. A box whose anchor moves or resizes + now follows the anchor's drawn edge frame by frame instead of trailing it on its own spring. +- **`rune_theme_opencode::brand(dark)`.** The opencode theme's brand colour (ember step 9) as a + typed function, so apps no longer look the token up by name. +- **Textbox padding never chooses arbitrarily between multiple editors.** Only a single + reachable editor takes a container press; hidden editors are excluded. Trailing copy/clear + buttons keep their hit targets even without handlers, and descendant resolution runs only + on presses, not hover. Explicit `Tx::blur()` also cancels pending scrim focus restoration; + only zero-size `focus_return` sentinel leaves use their parent's scope. +- **`IconButton::help` and `IconButton::shortcut` (plus `Button` and `SidebarToggle`).** + `IconButton::help("Lock").shortcut("⌘L")` (or `.shortcut("cmd+l")`) sets `El::help("Lock ⌘L")` + and supplies the accessible label when `IconButton::label` is unset. `Button` supports the same + `.help` and `.shortcut` builders, and `SplitView`'s sidebar toggle shows `"Hide sidebar ⇧⌘B"` / + `"Show sidebar ⇧⌘B"` (configurable with `SidebarToggle::shortcut`). +- **`rune_kit::shell::Page` for full-window screens in a `SplitView` window.** `Page::new(content) + .title(..).leading(..).trailing(..).titlebar_inset(..).frame_inset(..).toolbar_in_panel() + .build(&kit)` reuses `SplitView`'s toolbar band, traffic-light clearance, window-drag region + and framed content card so switching between `SplitView` and `Page` matches pixel for pixel. + `demo/kit/shell-page.png` shows it in light and dark. +- **Two-line `SidebarRow`s default to `TWO_LINE_ROW_HEIGHT` (40 pt) when `subtitle` is set** and + return focus to the selected row when inline rename ends. Previously these rows defaulted + to 28 pt; explicit `.height(..)` values are unchanged. +- **Hiding a pane or overlay keeps focus where it was outside that subtree.** `El::focus_return` + restores its trigger only when the focused control was inside the removed subtree (or pane); + hiding the sidebar with `⇧⌘B` while typing in a main-pane field keeps focus in the field + instead of moving it to the sidebar toggle, and closing a focused inspector returns focus to + the main pane first. +- **Pressing any part of a `TextInput`, `TextField` or `TextArea` focuses it.** Clicking the + leading icon, padding or a non-button trailing area focuses the inner editor and places the + caret at the nearest end without blurring an already-focused field or starting a window drag + in a titlebar; trailing buttons keep their own presses. `TextInput::trailing`, + `TextField::trailing` and `TextField::on_action` attach trailing accessories and copy handlers. +- **`Dialog::fit`.** A dialog sized to its header and body instead of the standard 368 point + height, for confirmations whose buttons otherwise sit far below one line of text. +- **A field inside a list row keeps its keys.** With focus in a text field inside a focus group + (an inline rename in a sidebar row), letters, arrows, Home and End go to the field; before, a + letter matching another row's first letter type-selected that row and took focus from the field. +- **Growth keeps springing under `Tx::scroll_into_view` and `Tx::keep_on_screen`.** Expanding + or collapsing a row in a growth stack and calling `tx.scroll_into_view` or `tx.keep_on_screen` + in the same handler no longer settles the row's growth in one frame, including in virtual + growth stacks. `Tx::scroll_into_view` now measures mounted rows from their presented growth + box and follows the target row frame by frame while the viewport's growth or layout springs + run, unpinning a `stick_bottom` viewport when needed until another scroll gesture or request + takes over. Reveals leave other viewports' reading anchors alone, stop when their target + disappears, and yield to wheel, fling, paging or explicit scroll destinations. Commits marked + with `tx.instant()` settle changed non-streaming row heights and that commit's scroll requests + in one frame, including requests made with the animated scroll methods; existing glides stay + running unless replaced. + +- **Per-corner and continuous-corner rounded clipping (`El::clip_rounded`, `El::clip_corners`).** + `El::clip_rounded` now follows the element's own per-corner radii (`El::corners`) and corner + curve (`El::continuous_corners`) with no extra call, and `El::clip_corners([tl, tr, br, bl])` + overrides the four clip corner radii directly. **Output change:** when paint radii and + `clip_rounded(radius)` differ, the paint radii now win; use `clip_corners([radius; 4])` + to retain an independent clip. Mixed radii round to 0.5 px through 63.5 px, otherwise 2 px, + saturating at 254 device pixels. Mixed corner radii pack into `Instance::fade[3]` + while uniform radii keep their exact IEEE-754 `f32` representation across the direct path, + isolated layers, native video surfaces, `CLIP_WGSL`, and `rune-ref`. + +- **`SparkleParams::count` cap raised from 32 to 64.** `rune-fx` sparkles now pack and evaluate up + to 64 four-point stars per layer (`p.count.min(64)`, 128 `vec4f` entries in the pre-allocated + 4096-entry table buffer) so wide banners can keep star density without splitting across layers. + +- **Blend modes for `rune-fx` effect and fill slots (`FxBlend`, `FxSlot::blend`).** `FxSlot::blend` + accepts `FxBlend::{Normal, Multiply, Screen, Overlay, SoftLight}` so warm glows and shader fills + can composite over light backgrounds (such as `#FAF7F2` cream paper) without washing out to + white. `Screen` uses fixed-function `wgpu::BlendState` with zero backdrop reads; + `Multiply`, `Overlay` and `SoftLight` sample the backdrop (`FxFrame::backdrop` or `EffectSite::backdrop` via + `set_layer_backdrop` / `blur_backdrop`) and fall back to `Normal` when no backdrop is available. + Separable formulas run in the frame's working colour space (linear light by default, or sRGB when + `FxRenderer::set_srgb_blend(true)` matches `Tx::set_srgb_blend`). + Multiply includes the source contribution through transparent backdrop pixels, avoiding dark + fringes in isolated layers. Overlay and SoftLight inherently have little contrast near white. + +- **rune-kit diff: the gutter stays put while code scrolls sideways.** In unified mode with + long lines, the line numbers and the +/− marker scrolled out of view with the code. Each row's + marker, both number columns and the comment "+" now sit in one `gutter` element held to the + viewport's left edge with `sticky_left`, on the gutter's own opaque fill (added, removed, + selected), so code passes under it. Elements in a row now have the path + `/gutter/{nn,no,plus}` and the marker is `/gutter/bar`. Annotation cards, folded-gap + rows and file-note rows hold their content to the left edge the way file headers do, and text + carets and `El::anchored` overlays inside sticky subtrees follow the sticky shift. Split wraps + and does not scroll sideways, so it is unchanged. + +- **A pane's width survives a wider range.** `PaneState::new(640.0).range(360.0, 960.0)` is 640 + wide and double-click resets to 640; before, `new` clamped to the stock 160–480 first, so it + was 480. +- **One undo step for grouped edits, and per-pill styles.** `TextEdit::undo_group(|e| ..)` makes + every edit inside one undo step (picking a mention: `replace_with_pill` then `insert(" ")`); + groups nest, an empty one records nothing, and typing coalescing and IME are unchanged outside + it. `El::pill_style(|id| PillStyle::default().bg(..).fg(..).icon(..))` styles each pill from a + closure that can capture app state (chip colour, label colour, icon; unset parts fall back to + `pill_colors` and `pill_icon`). `pill_icon` now takes any `Fn(&str) -> Option<&'static Icon>` + closure instead of a plain `fn` (existing `fn` items still compile; a `fn` pointer type + annotation on a stored value does not). rune-kit's `TextField`, `TextInput` and `TextArea` + forward `pill_style`. `demo/kit/pills-styled.png` shows an agent and a file pill. + +- Drag cancellation reaches native Escape and restores pane widths, column widths, sliders + and gutter selections. Delayed hover ends on window blur; raised content keeps ancestor + clips outside cached groups. Dropping offset-reordered virtual rows no longer scrolls the + list a second time, and live-only drags cannot make another handler's changes instant. + +- **`rune_kit::shell`: what a desktop agent-chat app's sidebar needs.** All additive; an app + that sets none of these draws as before, except that the sidebar's toggle no longer holds a + pressed fill while the sidebar is open (it reports `expanded` for accessibility instead). + - `SplitView::frame_inset` (default 8), `toolbar_in_panel`, `sidebar_padding(start, end)`, + `slide_sidebar_contents` and `sidebar_header` frame the window. + - `SplitView::pane_motion(PaneMotion)`: both panes move on one spring, optionally scaled by + the square root of the width (`scale_with_width`), with the contents fading over the last + part of the travel (`fade_tail`). + - `SplitView::sidebar_peek(SidebarPeek)`: resting on the leading edge or on the toggle + slides the closed sidebar over the content as a floating surface; leaving closes it and a + click docks it. + - `SidebarToggle`: the toggle's size, place past the traffic lights, `in_header` (at the end + of the sidebar's title row while open, travelling on the sidebar's spring) and an `unread` + dot that fades while closed. + - `SplitView::reduced_motion(cx.is_reduced_motion())` swaps slides for fades. + - `Sidebar::header_gap`, `header_padding`, `row_gap` and `inset`. + - `SidebarRow::avatar`, `subtitle`, `height`, `status(RowStatus)` (busy, attention, unread or + any element in a 20 point slot), `on_close` (a close button that takes the slot's place + under the pointer) and `reorder` with `shell::Reorder` (drag to a new place, Escape or + losing focus puts it back). + - `cargo run -p rune-kit --example shell` is set up with these. + +- **`Kit::interactive`, `interactive_with` and `elevate` are public**, so an app's own + elements take the kit's hover and press look and its elevation shadows. Additive. + +- **Core: `El::offset`, `El::raise`, `El::hover_delays`, cancelled drags, `Tx::animated`.** + - `El::offset(x, y)` shifts an element and its subtree without moving it in layout, with + hits following it, on its layout spring or `offset_motion`. + - `El::raise()` paints an element and takes its input above everything else, keeping its + layout, focus and accessibility order. + - `El::hover_delays(enter, leave)` makes `on_hover_change` wait for the pointer to rest. + - A held drag that ends without a drop (Escape, the window losing focus, the pointer taken + away) now hears `Phase::Up` with `Drag::cancelled()` true instead of losing its capture + silently. + - `Tx::animated()` lets a drag's move animate what it changes. + - `Cx::is_reduced_motion()` reads Reduce Motion for builders, and `ElementInfo` is exported + at the crate root. + - Behaviour change: an `opacity_motion` element only animates on a new target (one that + mounts at its resting opacity, or re-commits the same target, stays still). + - Motion traces flag elements that draw and hold nothing (`flags::BLANK`, 64). + +- **rune-kit diff: file headers span the viewport in unified mode; new `El::sticky_left`.** + When a line was wider than the view, the in-list file headers were as wide as the longest + line, so the `+N −N` counts and `header_actions` sat past the right edge and scrolled away. + Headers are now exactly the viewport wide and held to its left edge while the code scrolls + sideways, with a long path truncating before the counts. `El::sticky_left(inset)` is + `sticky_top` on the horizontal axis: it holds an element to the left edge of its nearest + `scroll_x`/`scroll_xy` viewport while its parent is in view (`ElementInfo::stuck` reads the + shift). + +- **Pinned growth stacks hold freed room as slack.** A `stick_bottom` viewport whose content + is a growth stack no longer carries its rows down when it gains room at its bottom while + pinned (a composer shrinking on send, a row removed at the bottom). The room is held under + the last row, rows growing in fill it first, and the rest closes on the stack's spring + about 120 ms after the rows stop growing, so a send only moves the rows up. A window resize, + `tx.settle` and reduced motion land it at once; scroll offsets and `on_at_bottom` are + unchanged. A pinned timeline's frames move during a send in an existing app. + +- **Five more built-in glyphs.** `rune_kit::glyphs` gains `MIC`, `KEYBOARD`, `CURSOR_TEXT`, + `ARROW_RIGHT` and `SPARKLE`, drawn like the rest of the set (16-unit view, 1-unit stroke). They + are plain statics, not `Glyphs` slots, so no theme or app literal changes: draw them with + `icon(&glyphs::MIC, 16.0)`. `demo/kit/glyphs.png` shows the whole set, light and dark + (`cargo run -p rune-kit --example glyphs`). + +- **Atlas capacity preserves glyphs already drawn in the frame, including text flights.** + At the eight-page R8 limit, requests fail without overwriting live placements and retry in + later frames. Empty outlines stay cached across eviction. The 16 MiB colour cache retires + unused scales rather than flushing visible emoji; a visible working set may exceed that soft + budget. Direct text users can call `TextSystem::begin_frame` and decode packed atlas origins + with `GlyphQuad::atlas_page`, `GlyphQuad::atlas_uv` and `Atlas::page_data`. + +- **Glyph, icon and colour-glyph atlases never exhaust or permanently drop glyphs across long zoom sessions.** + `Atlas` now separates genuinely empty glyphs (such as space, cached as `Some(None)`) from + unplaced glyphs (`Rasterized::Unplaced`, never cached), recycles 2048×2048 R8 shelf pages via a + two-page steady ping-pong pool with 1 px zeroed borders around each placed glyph (no 4 MiB buffer + zeroing on reset and no eviction of this frame's placements), spills to on-demand overflow pages when a single + frame exceeds one page and reclaims idle overflow pages on subsequent frames, and bounds the + colour-glyph RGBA cache (`COLOR_GLYPH_BUDGET`, 16 MiB). While `live_scale` is actively changing, + text and icons step through logarithmic $2^{1/4}$ scale buckets at a stable origin and + re-rasterize crisp 1:1 device-pixel glyphs once the scale holds still for `0.1 s`. + +- **Plastic fill, and liquid metal pinned per shape.** `Fx::fill(PlasticParams { .. })` paints + moulded plastic under one soft light: `color`, `roughness` (polished to matte), `dome` + (negative dishes the face like a keycap), `bevel` and light `angle`, with presets `glossy`, + `matte` and `dished`. It keeps rgb within alpha, so it blends the same with `srgb_blend` on or + off, and it never animates. It shares liquid metal's dome and rim code, and the catalog lists it + (`fill_styles()`), so `fill-presets.png` gains its presets. `LiquidMetalParams` has a new + `anchor: FillAnchor` field (`World`, the default, or `Element`, also settable with + `.anchor(FillAnchor::Element)`): with `Element` the ripples are pinned to each shape's centre, + so shapes of the same size, seed and time are pixel-identical. A full `LiquidMetalParams { .. }` + literal without `..preset` must now set `anchor`. Fills now shade at the exact pixel centre + instead of the interpolated one, which moves output by far less than one 8-bit step. + +- **Pasted images reach paste hooks.** `ClipboardContent::image()` holds a pasted image as a + `ClipboardImage` (PNG bytes via `png()`, pixel `size()`), with `with_image` to build one + and `clipboard::MAX_IMAGE_BYTES` (32 MiB as PNG) as the cap. Only targets with a hook fetch + it: a field's `on_input_paste`, the root's `on_paste_content` and `Tx::read_clipboard`; plain + and hookless rich fields read the clipboard as before. macOS reads `public.png`, else + converts `public.tiff`; Windows (`PNG`, else `CF_DIBV5`) and Linux (`image/png`) read through + arboard's `image-data` feature, now on for those targets; the web reads `image/png` from the + paste event or `navigator.clipboard.read()`. An image-only clipboard now reaches hooks + instead of nothing. Copies don't write images. Script `paste` steps take `"png": "path"`. +- **Atomic inline pills in rich text (`Mark::Pill(id)`); `Mark` is `#[non_exhaustive]`.** A + pill is a mention, file or attachment run whose label is the text under the mark. The caret + steps over it in one move, a selection reaching into it grows to cover it, `Backspace` / + `Delete` (and word deletes) remove it whole, typing and IME composition never land inside it, + and undo restores it with its id. Typing never inherits a pill and an edit that cuts into one + leaves plain text. Apps make pills with `TextEdit::insert_pill(id, label)` or + `replace_with_pill(range, id, label)` (swap a typed `@query`, one undo step) and list them with + `pills()`. The field draws each as a rounded chip that never splits across lines, + `El::pill_colors(bg, fg)` (default: the link colour at 20%) and `El::pill_icon(|id| ..)` (also + on `TextInput`, `TextArea` and `TextField`) style it. Copy writes the label as plain text and + `label` as HTML; a paste of the app's own last copy restores the + pill (`paste_html_with_pills`), while other HTML never makes one (`paste_html` drops it). + `TextEdit::allow_marks` always allows pills. Exhaustive `match`es on `Mark` need a wildcard arm. +- **Monospace text has no ligatures, and its tabs reach 4-column stops.** Mono rich spans + (`Span::mono`, so `Mark::Code` and `Block::Code` in a rich `TextEdit`, and Markdown inline + code) and `Family::Mono`/`Family::SystemMono` styles turn off `liga`, `clig` and `calt`: + Inter in the mono slot drew `->` as an arrow. A tab in monospace text now advances to the + next 4-column stop (counted from the line or the mono span's start) instead of one space; + it stays one byte. Markdown code no longer pads tabs with uncopied spaces when its style is + mono, since layout does it. Goldens with tabs or `->`-style pairs in mono text move. Code in + a rich editor uses the mono slot, which is Inter unless `AppSpec::families` names a + monospaced family; the `rich_editor` example now embeds IBM Plex Mono. +- **Effect slots (`El::effect`) at a zoom scale, under rounded clips, with per-slot backdrops (`El::effect_backdrop`), and in `srgb_blend` frames.** + `KIND_EFFECT` (`instance.params[3]`) and `EffectSite::scale` now carry the device pixels per point + at the slot (`sc * s`, combining the window's Retina factor with inherited `scale`, `press_scale`, + `live_scale` and scale transitions, where `params[3]` previously held only `s`). + `rune_fx::FxSlot::scale(f32)` overrides `FxFrame::scale` for that layer so a border, glow reach + or rib width on a zoomed canvas stays in the element's points, and `FxSlot::clip(clip, fade)` + applies `rune::render::CLIP_WGSL` (`clip_alpha`) in `rune-fx`'s fragment shader and tightens the + quad to `clip` so a slot outside an isolated layer gets the same rounded container corners and + scroll-edge feathers as Rune's own primitives. `El::effect_backdrop(true)` marks a slot that reads + what was drawn before it (`instance.params[0] = 1.0`): `Renderer::draw_with`, + `Renderer::draw_with_backdrop`, `Renderer::draw_target_range_with` and + `Renderer::encode_layers_with` / `Renderer::encode_layers_with_backdrop` keep a single render pass + across ordinary slots and split the pass only at backdrop slots, copying the target into a pooled + viewport-sized backdrop texture, calling `EffectPhase::Backdrop(encoder)` while the pass is closed + (for `FxRenderer::blur_backdrop` or `FxRenderer::set_layer_backdrop`), and re-opening the pass with + `LoadOp::Load` and `EffectSite::backdrop` set (a target without `COPY_SRC` can't be copied, so + the slot draws in the open pass with `backdrop == None`; for a slot inside an isolated layer, copying that + layer's `Rgba16Float` target at `origin` in window coordinates). When + `FxRenderer::set_srgb_blend(true)` is active, `rune-fx` decodes sRGB-encoded premultiplied + backdrop and blurred-backdrop samples to linear light before shading, so glass, lenses, distortion + and backdrop dither or halftone are no longer double-encoded on non-sRGB frame targets or inside + `Rgba16Float` isolated layers when given `EffectSite::backdrop`. Pass slot metadata separately + to `FxRenderer::prepare_with_slots`; `FxLayer` and `FxFrame` struct literals remain unchanged. + Explicit `FxFrame::backdrop` inputs still provide linear samples by default, including + hardware-decoded `*Srgb` views; `FxSlot::backdrop_srgb(bool)` overrides the input encoding + independently of output blending. Backdrop textures follow live target-format switches and + resize without reallocating when the format and viewport are unchanged. + +- **Sticky elements in scroll views: `El::sticky_top`, `El::sticky_bottom`, `El::stuck_shadow` and `Tx::keep_on_screen`.** + An element inside a vertical scroll viewport can pin to the viewport's top or bottom edge + plus an inset while its parent stays in view (`El::sticky_top(inset)`, + `El::sticky_bottom(inset)`), and is pushed out by its parent's content box (inside the + parent's padding) as the parent leaves. Sticky children paint and hit-test above later + normal siblings of their parent (and below `above` and `modal` overlays), move in the same + frame as the scroll offset without a second layout pass, and expose their stuck displacement + on `ElementInfo::stuck` (`--tree` JSON `stuck` when non-zero) and through `El::on_drawn_layout`. + `El::stuck_shadow(Shadow)` adds shadows that fade in over the first 8 pt of stuck offset. + `Tx::keep_on_screen(key)` holds a keyed element at its drawn vertical position across a + commit that collapses or expands content inside its scroll viewport (including `virtual_rows`), + compensating the scroll offset each frame while layout and growth springs keep running. + A cached subtree containing sticky content draws live, and anchored overlays follow live + transforms on sticky targets. Horizontal-only scroll ancestors are skipped; virtual headers + must share a row with their section to remain mounted while that section is visible. + `Tx::scroll_into_view` clears headers already stuck at the target edge, and `El::anchored` + follows a sticky target's drawn rect. New API only; existing output is unchanged. + +- **`rune_kit::diff`: a diff view for code review.** `diff::parse` reads `git diff` output and + `FileDiff::from_texts` diffs two texts; `DiffView` draws a `DiffState` unified or split, with + word changes, syntax colours, folded unchanged ranges, sticky file headers, app widgets + under lines (annotations), line selection from the gutter and one-side copy, on a virtual + list that keeps a 50,000-line diff at frame rate. See the rune-kit README. Additive. + +- **`El::virtual_rows_version(v)` and `El::on_visible_rows(f)`.** `virtual_rows_version` lets a + `virtual_rows` list skip calling its key closure for every row each commit: while `v` and the + row count stay the same, layout keeps the last keys. `on_visible_rows` reports the index range + of rows intersecting the scroll viewport whenever it changes, committing only when the handler + returns `true`, so a sticky header or file tree can follow the reading position without per-row + `on_layout` commits on every scroll frame. Culled virtual rows now also unmount their whole + subtree from the scene immediately. Lists without these behave as before. + +- **Rich fields: soft breaks on rebuilt drafts, leaving code blocks, allow-lists, physical keys.** + `TextEdit::with_soft_breaks` and `set_soft_breaks` restore the soft breaks `from_parts` + can't take, and `TextEdit::clear_history` drops the undo and redo stacks while keeping the + text, formatting and selection. Return on a blank last line of a code block now leaves the + block (the blank line becomes a paragraph after it, one undo step) instead of adding another + code line, and Down or Right at the very end of a trailing code block or quote adds an empty + paragraph after it; both move what a key does in an existing rich field. + `TextEdit::allow_marks` and `allow_blocks` limit a field to the formatting its app can store: + shortcuts, `toggle_mark`, `set_block` and paste skip the rest, and a disallowed + `⌘B`/`⌘I`/`⌘U` reaches the app's key handlers (`allows_mark` and `allows_block` hide toolbar + buttons). `Tx::physical_key` gives a key handler the physical key behind a logical one, so a + shifted shortcut (`⌘⇧7`) matches on every layout; a script's `{"type": "key"}` takes a + `"code"` for it. Fields without an allow-list keep their behaviour otherwise. + +- **Live-only review fixes.** A declined element key handler no longer suppresses an + ancestor's commit. Moving geometry refreshes hover handlers under a stationary pointer in + ordinary windows as well as overlays, and schedules their delivery. Debug spot checks + ignore retained exits and unrelated layout feedback before a mid-frame commit. + +- **`Tx::live_only`: an event that moves only live values doesn't re-run the view.** A handler + that changed nothing the view reads (a canvas camera's `live_offset` and `live_scale`) calls + `tx.live_only()`, and its event skips the view, diff and layout while the frame still draws + the live values, hit tests where they put elements and reports `on_drawn_layout`. It works in + pointer and key handlers with a `Tx`: wheel, pinch, rotation, drag, pointer move, keys, key releases, + physical input, presses and hover. A handler that declines its event takes it back, and an + event several handlers take is live-only only if each says so. Debug builds check a + live-only event a quarter second or more after the last commit by re-running the view + anyway, and print the handler when what it builds differs (`Runtime::check_live_only(false)` + turns that off; `Runtime::live_only_events` counts the skips). On a 2,000-card canvas a + 120-frame pinch went from one view run and 13.7 ms of CPU per frame to none and 2.0 ms + (`examples/pinch_bench.rs`). Nothing changes for a handler that doesn't call it. + +- **Element-local points for pointer moves and secondary presses.** + `El::on_pointer_move_local` and `El::on_secondary_press_local` give a `PointerEvent`: `x` and + `y` in the element's own layout points, as `Drag` and `WheelEvent` give them, and + `window_x`, `window_y` and `window()` in window points for a menu's anchor; + `on_pointer_move_local` also gets a `Tx`. `El::on_drawn_layout_tx` is `on_drawn_layout` + with a `Tx`. `on_pointer_move`, `on_secondary_press` and `on_drawn_layout` report what they + did. The crate README has a table of each handler's coordinate space. + +- **Combobox filtering springs the popup and fades rows.** Typing in a `Combobox` search used to + resize the list in one frame and pop rows in and out. The search field now animates its edit + layout, the viewport's height springs, rows fade, and the empty state stays mounted and + fades in at 0 height. Things apps can notice: the popover's tree gains a keyed `list` column + with the `viewport` and an `empty` element in it, and goldens taken mid-filter can differ. + +- **`El::animate_layout()` springs a growth row's horizontal layout.** Inside a growth-stack row + everything snaps while the row's height carries the motion, so a label changing width in place + (`"Thinking"` → `"Thought for 3s"`, `"Used 1 tool"` → `"Used 2 tools"`) jumped its neighbours. + Under `.animate_layout()` a row's contents spring x and width on their own layout spring, and + children the element gains while the row is already in place fade in; y and height stay with + growth. Nothing changes without the call. + +- **A child mounted after its parent visibly arrives enters on its own.** A child inserted under + a parent still entering used to ride the parent's entrance. The parent's presence runs on for + ~0.7 s after it reaches full opacity, so a child mounted in that tail popped in at full opacity. + It now rides only while the parent is visibly entering (presence under 1 - 1/255) or exiting. + Things apps can notice: content swapped into a freshly mounted parent plays its own + transition (a `RollingText` digit changing soon after the label fades in rolls in instead of + appearing in place), and goldens that capture it can differ. + +- **Layout nobody can see moves at once.** A node that drew nowhere in sight in the last build + (outside the window, or clipped away by a scroll or clip) and lands out of sight again now + takes its new frame, radius and opacity at once instead of springing there. Toggling a sidebar + over a long timeline used to animate ~290 off-screen rows; the first frame's CPU drops by about + a fifth. Things apps can notice: `is_animating` and settle events skip those nodes, and a + node scrolled into view mid-change starts from its new place rather than mid-spring. Shared + (`matched`) and flying elements still animate. + +- **Loops sleep below one 8-bit step of opacity.** A loop (`.cycle`, `.looping`) whose brightest + frame would draw under 1/255 opacity no longer wakes the app; the cut-off was 0.001. Things + apps can notice: a loop under a group or parent faded to between 0.001 and 0.004 stops + scheduling frames. + +- **Exits unmount once they fade out of sight.** An exiting node used to stay mounted until its + presence settled at 1e-5, about 40 frames (~325 ms) after its opacity fell under one 8-bit step. + It now unmounts the frame its transition's opacity drops below 1/255. Things apps can notice: + `exited`, focus moves, hit-testing and anything waiting on an unmount happen that much sooner; + goldens that capture the tail of an exit can differ. + +- **A tap's release no longer counts as a drag move.** Letting go where the pointer already was + used to queue a `Phase::Move` drag event, which instant-commits in most handlers: a slider tap + sprang the knob toward the tap and then jumped the rest of the way on release. A release now + sends a move only when the pointer moved since the last move. Things apps can notice: a drag + handler gets no Move for a release at the last position, and tap-to-seek controls animate + through the release. + +- **The `Tx` scroll requests take key paths**, as `Cx::layout` and `Tx::fly_text` do: + `scroll_into_view`, `scroll_to_bottom`, `scroll_page`, `scroll_to`, `scroll_to_instant`, + `scroll_to_x`, `scroll_to_y` and `Runtime::scroll_at_bottom` accept `"list/label"` (leading keys + are the element's nearest keyed ancestors) as well as a key or full path. A bare key still names + the first element with it. + +- **`rune::extra_args()` works before `run`.** It used to return nothing until `run` had + parsed the command line, so an app choosing what its window opens from its own flags had to + call `tooling::Args::parse()` first. Called earlier, it now reads Rune's flags from the + process's arguments as `run` does (`--help` and malformed flags included); the first read + still wins, so with `App::args` read it after `run` starts. + +- **A field that appears on a layout-read re-run takes the focus it asks for.** When a view + builds a `TextEdit { focused: true, .. }` field only once `Cx::layout` returns a rect (an + inline editor placed over a node), the field appears on the commit's re-run, which skipped + the focus sync, so it stayed unfocused until some later commit. The commit now syncs focus + again after the re-run. + +- **`El::inert()` makes a subtree draw and lay out without taking input.** Presses, hovers, + cursors, scrolls, drops and tooltips go to whatever is under it, as with HTML's `inert`; nothing + inside takes or keeps focus, and `ElementInfo::inert` is true for it. `on_layout` and + `Cx::layout` still see its rects. An editor can draw a document over its canvas without a + transparent shield to catch presses. + +- **`Tx::blur()` drops keyboard focus from a handler**, as a click on empty space does: the + focused field's `TextEdit::focused` turns false through `on_edit` and keys reach the window's + `on_key` again. An app no longer needs to clear `focused` in its model to hand keys back. + +- **`Tx::set_srgb_blend(bool)` switches blending live.** A handler moves its window (or + overlay, web canvas or headless run) between linear and sRGB blending from the next frame, as + if it had launched with `App::srgb_blend`. The frame that switches reconfigures the surface and + switches the renderer's pipelines once, keeping the glyph atlas, images and layer targets; asking + for the mode the window already has costs nothing. A `Compositor` sees the new `Frame::format` + on that frame. + +- **`Runtime::set_srgb_blend` is public.** A runtime the app draws itself (built with + `Runtime::with_text` for a headless snapshot, say) can blend in sRGB as an + `App::srgb_blend(true)` window does, hover and press tints included, without re-encoding the + draw list. Changing the mode now asks for a frame. Nothing changes for apps that don't call it. + +- **`Tx::open_file` and `Tx::save_file`: file dialogs from a handler.** The callback gets + `FileDialogResult` (`Ok(Some(path))`, `Ok(None)` on cancel or when the window hides or + closes, or an error) on a later frame, like `tx.read_clipboard`; the window shows the dialog + without blocking its event loop (a sheet on macOS via rfd, the window-owned dialog on + Windows, the desktop portal over zbus on Linux) and needs the `native-file-dialog` feature. + One dialog at a time: a second request while one is open, or a request on a window that + stays hidden or on an overlay, gets an error. Headless runs show it as `fileDialog` in + `--tree` until a `file-dialog` (with a `path`) or `file-dialog-cancel` script step answers + it, and `headless_run`'s `ScriptEvent` has a new `FileDialog` variant (the enum is + `#[non_exhaustive]`). Tests use `Runtime::file_dialog()` and `resolve_file_dialog`. + +- **Rejected file drops: `El::on_drop_rejected` and `El::on_drop_rejected_hover`.** A drop + target with either stops a file drag carrying none of the files it accepts, instead of + passing it to the target around it: `on_drop_rejected_hover(true/false)` follows that drag + (for a "can't drop here" state) and `on_drop_rejected` gets its files on drop. On a mixed + drop it gets the files `on_drop_files` didn't. `Runtime::drop_rejected_hovered()` reads the + state. Every host routes drops through the runtime (macOS, Windows, X11 windows, the + multi-window desktop and headless `drag_files`/`drop_files` steps), so all get it. Targets + without them behave as before. + +- **A `RollingText` reads as text in lookups.** Its row now reports the whole label as its + `ElementInfo::text`, so `--tree` JSON and tests that find an element by its text find it, + as they find a plain `text`. Its glyphs still list one grapheme each. Any element of role + `"text"` with a label and no text of its own does the same; Rune and rune-kit build no other, + so trees of apps without a `RollingText` are unchanged. + +- **rune-kit: `Button::rolling(key)` and `Button::label_with(..)`.** `rolling` draws the label + as a `RollingText`, in the button's font and ink, so "Import 3 items" → "Importing…" rolls + only the changed characters; the button's edges spring on the label's curve + (`RollingText::SPRING`, width leading), so its padding holds while the width animates. That + spring also carries the button's colour changes. `label_with(|font, ink| ..)` draws any + label element in the button's font and ink. Either way the text given to `Button::new` stays + the accessible label. Buttons without them are unchanged. + +- **`El::cache()` rasterizes settled subtrees once and composites them across pan and zoom.** + Calling `.cache()` on an `El` (with an optional `.cache_key(u64)`) rasterizes the settled + subtree into an `Rgba16Float` layer target (`layers.rs`) and elides its child instances on + subsequent frames, compositing a single quad while an ancestor's `live_offset` or `live_scale` + moves or scales it. Invalidation is automatic from the subtree's relative draw output (state, + hover, focus, text, layout, theme and scale). Subtrees that are actively animating or contain a + compositor `El::effect` slot, `NativeSurface`, native `SystemMaterial` or focused text input + draw live without offscreen thrash and re-cache once settled. Changing ancestor scales composite + the existing cached texture with bilinear filtering and re-rasterize at the new device-pixel + resolution after `0.1 s` at rest. Cached textures are capped at `4096×4096` px under an LRU + byte budget (`Renderer::set_cache_budget`, default 64 MiB). Hit testing, accessibility, + `elements()` and `on_layout` are unchanged, and apps that don't call `.cache()` pay no extra + passes or allocations. + + Review fixes: image-backed subtrees draw live so same-size publications cannot leave stale + texels. Link paint, press paint, outside hover groups and the cache root's blur invalidate + correctly. View commits always check emitted output; committed scale changes draw live until + settled instead of trusting a partial model hash. Over-budget fallbacks allocate only the + visible area when isolation is still needed. Reference replays preserve rounded layer clips, + reject unsupported layer blur, malformed cache tags and excessive nesting. +- **Grain is symmetric.** `Fx::grain` returned its light half as added light with zero coverage, + so with `srgb_blend` on each +0.02 of grain became about +40/255 on the framebuffer while the + dark half only dimmed by 2%: white snow over everything. The light half is now premultiplied + white (`vec4f(n * a)`), so grain moves a pixel toward white or black by the same fraction in + either blend mode and the mean stays put. Linear blend shifts a little too: its light half is + weaker than the old additive one, most at bright destinations. + +- **Tree and Table in rune-kit, and the core pieces they need.** `Tree` draws an app-owned + `TreeModel` (`FileTree` builds one from paths, folders first, single-child folders as one + row) with indent guides, springing chevrons, icons, change counts, type-ahead, filtering + and `reveal`. `Table` draws app-owned rows with fixed, flex and min/max columns, drag + resizing, a sticky header that shows the app's sort, zebra rows, cell builders and + tooltips for cut-short text. Both are virtualised (50,000 nodes and 100,000 rows scroll + under 4 ms a frame at p95) and keyboard driven, with tree and grid roles. New core API: + `El::on_key` (a control that takes its keys before focus navigation, is a Tab stop and + takes focus from a click inside it), `El::level` and `El::expanded` (outline rows), + `El::icon_rotation` (a glyph's turn, sprung), `El::help_when_truncated`, `Tx::mods` (the + modifiers held for a press), `Tx::scroll_into_view_in(scope, key)` (reveal a row of the + list inside one element only), new `ElementInfo` fields `level`, `expanded` and + `item_selected`, file and folder glyphs in `rune_kit::glyphs`, and + `MarkdownStyle::table_like(&TableStyle)`. Things apps can notice: the `--tree` JSON gains + `level`, `expanded` and `itemSelected` on rows that set them, so tree goldens with selected + list or menu rows move; Tab now also stops at `on_key` controls when Full Keyboard Access + is off. Nothing else changes for existing apps. +- **rune-kit has an app shell.** `rune_kit::shell` adds `SplitView` (a resizable, collapsible + sidebar, the main pane under a toolbar, an optional inspector, and a 48 point title bar band + that drags the window and clears the traffic lights), `Toolbar`, `Sidebar` with + `SidebarSection`, `SidebarHeader` and `SidebarRow` (keyboard selection, type-select, nesting, + badges, inline rename, virtualised rows), the app-owned `PaneState` and + `shell::is_sidebar_toggle`. New API only; existing output is unchanged. + +- **Rects under live transforms: `El::on_drawn_layout`, and `Drag` points in the element's + own points.** `on_drawn_layout` reports an element's rect as drawn (after scrolling and its + ancestors' `live_offset`, `live_scale`, `live_rect` and `scale`), on every frame a live value + moves it with no commit, and where a spring brings it to rest; it's the rect hit tests and + `ElementInfo::rect` already use. `Drag`'s `x`, `y`, `start_x` and `start_y`, and the pointer + in `WheelEvent`, `MagnifyEvent`, `RotateEvent` and `on_smart_magnify`, are now in the + element's own layout points: from its top-left as drawn, divided by the scale it draws at. + They were measured from its unscrolled layout box, so a drag on a row of a scrolled list + read the scroll offset too, and one on a zoomed canvas read window points from where the + element would be at rest. An unscrolled, unscaled element reads what it did. + +- **`Tx::scroll_to(key, x, y)` glides a viewport to an offset.** It runs on the spring + `scroll_to_bottom` uses, clamps each axis to the content as the glide runs (virtual rows + measure as they mount), ignores axes the viewport doesn't scroll, and a wheel, fling or new + request takes over. `scroll_to_instant` and `scroll_to_y` jump; a `stick_bottom` viewport + sent to its end follows it again. `scroll_to_x` now also mounts the virtual rows it lands on + and stops a glide in progress; otherwise it is unchanged. + +- **Canvas input: `on_wheel`, `on_magnify`, other mouse buttons and `on_key_up`.** An element + can take wheel and trackpad deltas before any scroll view (`El::on_wheel`, with modifiers, + phase, momentum and precision), trackpad pinches, rotation and smart magnify (`on_magnify`, + `on_rotate`, `on_smart_magnify`), middle, back and forward button presses and drags through + its own `on_press` and `on_drag` (`El::pointer_buttons`, `Tx::button`), and key releases + (`El::on_key_up`). Scripts gain `wheel`, `magnify`, `rotate`, `smart-magnify` and `key-up` + steps and a `button` on presses and drags; `ScriptEvent` and `PointerAction` gain variants + for them. Nothing changes for an app without these handlers, except that a scripted + vertical `scroll` goes through `wheel_xy` once some element has `on_wheel`. On Windows and + Linux a Ctrl + wheel (a trackpad pinch) over an `on_magnify` element pinches instead of + scrolling. + +- **Wakes no longer pile up in headless runs.** A coarse headless step polled once per + `wake_after` deadline that fell inside it, so a poll that asked for a wake each time it ran + (a save timer that rearms, a scripted gesture) started a new chain of wakes every frame: one + that asked for 505 ms on every poll ran 14 polls a frame by frame 400 and 34 by frame 1000. + Now a step stops for a timer no sooner than a frame interval (1/60 s) after the last poll, as + a window's timer floor already did, and each poll takes every deadline due by then: one poll a + frame at 60 fps or faster, whatever the app asks for. Coarse steps (`rt.frame(0.5)`) still + stop at deadlines at least a frame interval apart. Windows, overlays, hidden hosts and the + web already ran one poll for all due deadlines. Things apps can notice: a headless run or + hot-reload session whose deadlines fall less than 1/60 s apart polls fewer times. + +- **Attributed rich-text editing (`TextEdit` marks, blocks, decorations and HTML).** `TextEdit` + now stores inline [`MarkRange`](crates/rune/src/edit.rs)s (`Mark::Bold`, `Italic`, `Underline`, + `Strike`, `Code`, `Link(url)`) and per-paragraph [`Block`](crates/rune/src/edit.rs) attributes + (`Paragraph`, `Bullet(level)`, `Numbered(level)`, `Quote`, `Code`) alongside plain `text`, + without hidden Markdown characters in the string. Rich keys are opt-in with + `TextEdit::rich()` (on for `from_html` and `from_parts`): plain fields keep passing `⌘B` / + `⌘I` / `⌘U` to the app, insert a plain newline on `Shift+Return` and paste plain text, and lay + out and draw exactly as before. Edits shift and split ranges; typing + inherits the marks of the character before the caret (except at the start of a link or code + mark's run); `toggle_mark` / `set_mark` / `remove_mark` / `set_link` and (in a rich field) + `⌘B` / `⌘I` / `⌘U` toggle marks on the selection or arm a pending typing style on an empty + selection; and + `has_mark` / `active_marks` / `active_link` / `active_block` report the active formatting for + toolbar pressed states. List markers, quote bars and code-block backgrounds draw as layout + decorations; `Return` continues a list or ends an empty list item, `Shift+Return` inserts a + soft break in a rich field (`soft_breaks()`), `Backspace` at the start of a list item outdents or exits the + list, `Tab` / `Shift+Tab` change list nesting (`0..=3`), and inside `Block::Code` `Return` + inserts a newline, `Tab` inserts `\t` (shaped as one space, matching core text), and inline + marks do not apply. `El::spans` / `El::decorations` (and `TextInput::decorations` / + `TextArea::decorations`) paint per-frame `rune::Span`s over `text_input` without mutating the + model, shifting automatically across active IME preedit so `SyntaxTheme::spans(&ranges, + offset)` from `rune_kit::syntax::highlight` can be passed straight in; overlapping spans merge, + later ones winning. `Span` gains builders (`weight`, `bold` (600), `italic`, `mono`, `size`, + `color`, `bg(color, pad)`, `underline`). Undo, redo and IME + preserve text, marks, blocks and spans together. `TextEdit::from_html`, `to_html`, + `selected_html` and `paste_html(html, plain)` import and export a safe HTML subset (`b`/`strong`, + `i`/`em`, `u`, `s`/`del`/`strike`, `a`, `code`, `pre`, `ul`/`ol`/`li`, `blockquote`, + `p`/`div`/`br`, and inline `font-weight`/`font-style`/`text-decoration` styles; links keep + only `http`, `https`, `mailto`, `tel` and scheme-less URLs), and `from_parts`, `marks()`, + `blocks()` and `paragraphs()` (a `ParagraphInfo` per line) expose the attributed model directly. + A focused rich field joins the rich clipboard: `⌘C` / `⌘X` write `selected_html()` beside the + plain text, and paste reads the clipboard's sanitised HTML through `paste_html` when no + `on_paste` hook takes it. Plain fields still copy and paste text only. +- **Rich clipboard: copy and paste HTML and RTF beside plain text.** New `ClipboardContent` + (`ClipboardContent::new(text).with_html(..).with_rtf(..)`) and `Tx::copy_rich`, which writes + every form in one clipboard change; `copy_secret` stays plain text. A field's new + `.on_input_paste(|s, content, tx| -> bool)` hears a paste before its editor (true takes it), + the root's `.on_paste_content(..)` is `on_paste` with every form, and + `Tx::read_clipboard(|s, content, tx| ..)` reads without pasting. Pastes hold the richest form + the source offered: on macOS `public.html`, else `public.rtf` converted to HTML on the + clipboard worker; Windows CF_HTML; Linux `text/html`; the web's `text/html`. HTML from the + clipboard passes through the new `clipboard::sanitize_html` (scripts, handlers, frames, + embeds, script URLs and loading CSS removed) before an app sees it. Windows, Linux and the web + write no RTF. Tests: `MemoryClipboard::set_content`/`content`, `Runtime::paste_content`, and + the script step `{"paste": {"text": .., "html": .., "rtf": ..}}` (public as + `ScriptEvent::PasteContent`). Things apps can notice: nothing, unless they add a hook. Fields + without `on_input_paste` and text `on_paste` handlers read only the text, as before; a + clipboard with HTML and no text reaches only rich hooks. On the web, rich reads use + `navigator.clipboard.read()`, which some browsers confirm with a paste prompt. + +- **`srgb_blend` works with a `Compositor`, and compositors can draw inside layers.** Before, + `.srgb_blend(true)` was ignored (with a warning) once a compositor was set. Now the frame is + gamma-blended as without one, `Frame::srgb_blend()` reports it, and a compositor that matches + the encoding (`Frame::format`, `EffectSite`) looks the same in both modes. `El::effect(mark)` + adds a box that draws nothing but holds its place in the painter stream, and + `Renderer::draw_range_with` / `encode_layers_with` call a hook there, inside the enclosing + isolated layer's pass when there is one, so the compositor's pass takes the layer's opacity, + blur, dissolve and clip. A faded slot always gets its own layer, so its opacity can't be + skipped, and the hook runs scissored to the slot's clip rectangle. + `render::CLIP_WGSL` shares the clip maths with compositor shaders. + Apps without a compositor or effect slots render exactly as before; one that set `srgb_blend` + alongside a compositor now gets gamma blending, which its compositor must match. + `rune-fx` follows: `FxRenderer::add_format`, `draw_layer_in` and `set_srgb_blend` draw its effects + in a layer's float target and in either blend mode (`demo/fx/in-layer.png`). + +- **Traces say what animated.** Each `--trace` frame now carries `quality.why` (what kept the + frame animating: tracks, growth, scroll, reveal, loop, text-flight, …) and `tk`, the motion + tracks it sampled as `[element, property, active]`. New `--trace-all` traces unkeyed elements + too, named by path. `scripts/motion-audit/` records the example apps with it and flags snaps, + pops, neighbour jumps, overshoot, motion that never settles and animation nobody can see. + Things apps can notice: trace files are larger (the new fields, and every element with + `--trace-all`); element rows are unchanged. + +- **Syntax highlighting is shared, swappable and covers Python and Go.** The scanners behind + Markdown's coloured fences moved to `rune_kit::syntax`, which builds without the `markdown` + feature: `syntax::highlight(lang, code)` returns cached `(Range, Paint)` ranges and + `SyntaxTheme::spans(&ranges, offset)` turns them into colour-only spans for any rich text, + such as a composer's code. `Markdown::highlight(|lang, code| ...)` (or `highlighter`) swaps in + an app's own highlighter, which gets the fence's language as written, including ones the + built-in scanners don't know. New built-in languages: Python, Go and unified diffs (for + callers; ```` ```diff ```` fences keep their tinted rows). `Syntax` gains `Inserted` and + `Deleted`, and `MarkdownStyle::syntax_theme` sets every token colour at once. Things apps + can notice: ```` ```python ```` and ```` ```go ```` fences (and aliases such as `py`, + `golang`) are now coloured, so goldens with them move; turn that off with + `syntax_highlight(false)`. Other output is unchanged. +- **Tabs draw as spaces, and line up in Markdown code.** Text layout drew a tab as the font's + missing-glyph box (or nothing, depending on the font); it now shapes each tab as one space, + so byte ranges, carets and copying are unchanged. Markdown code blocks and diff lines pad + each tab with spaces to the next four-column stop; the padding isn't copied, so a copy + still gets the tab. Goldens with tabs in text move. +- **`native-file-dialog` passes `cargo deny`.** On Linux the Open and Save dialogs now call the XDG + desktop portal's FileChooser directly over zbus 6, which Rune already uses for global shortcuts, + instead of through rfd's portal backend (ashpd and zbus 5, whose `zvariant`, `zbus_names` and + `zvariant_derive` are flagged unmaintained: RUSTSEC-2026-0370, 0371 and 0372). rfd moves to 0.17 + and is only a macOS and Windows dependency, with no features; the Linux tree loses 75 crates. + Things apps can notice: on Linux a desktop with no portal FileChooser now returns an error + instead of falling back to zenity, a dialog dropped before it answers is closed, and the dialog + is parented to the focused X11 window (Wayland windows stay unparented). Paths, filters, the + starting folder, the suggested name and cancellation behave as before. Apps need no code + changes. + +- **rune-fx fills.** `Fx::fill(params)` paints a node's shape, or with `.border(w)` a band inside + its edge: liquid metal (chrome, gold, rose gold, gunmetal; also as a tube border), mesh + gradient, dither (Bayer 2×2/4×4/8×8, blue noise, white noise; of a ramp, noise, the backdrop or + an image), grain gradient (linear, radial, conic), fluted glass, metaballs, swirl, voronoi, + waves and halftone. Each has typed params, `Default` and named presets. `fill_styles()` is a + catalog for tools: ids, display names, params with ranges and units, presets, + `FillParams::get`/`set` by param id and `to_rust()`. Things apps can notice: `Fx` has a new + variant, `Fill`, so an exhaustive `match` on `Fx` needs an arm; `FillStyle` and `FillParams` + are `#[non_exhaustive]`. `demo/fx/timings.md` was re-measured on an Apple M4 Pro, so its + numbers for the older effects moved too. + +- **Reopening a Mac app brings its window back.** A click on the Dock icon, or opening the app + again from Finder, Spotlight or `open` while it runs, now shows and activates a window when + none shows: a minimized one, else the one Rune hid last (⌘W with `keep_running`, `hide`), else + the main window, and unhides an app hidden with ⌘H. Before, a window hidden that way stayed + hidden, because AppKit only brings back minimized windows and winit's app delegate didn't answer + `applicationShouldHandleReopen:hasVisibleWindows:`; Rune now adds that method. Launcher and + other nonactivating panels, overlays, windows that closed for good and accessory apps never + come back. New `App::on_reopen(|s, has_visible_windows, tx| -> bool)` (and + `WindowSpec::on_reopen`) runs first; true skips the default. Other platforms are unchanged. + Headless scripts take `{"reopen": true}`. Things apps can notice: a hidden window now comes + back on a Dock click. An app that installs its own reopen Apple event handler replaces + AppKit's, which is what asks the delegate, so neither the hook nor the default runs; drop the + handler and use `on_reopen`. + +- **Theme tokens hash.** `Color`, `TextStyle` and rune-kit's `Palette`, `StateColors`, `Type` + and `Radius` implement `Hash`, so a row can pass the tokens it reads to `memo` as its version + instead of hashing their `Debug` text. Floats hash by bits, `-0.0` as `0.0` (they compare + equal) and every NaN alike; none of them is `Eq`, since NaN isn't equal to itself. +- **A virtual list's first showing mounts its viewport, not three windows.** A new scroll + viewport has no measured height, so a virtual list shown for the first time used the window's + height as its viewport and mounted two of those either side: a 200-cell emoji grid in a + five-row viewport built all 20 of its rows. Now the first showing estimates the viewport from + the tree (the window's height less the fixed-height siblings, padding and gaps of the columns + around it, or the scroll viewport's own height; in a window that fits its content or an + out-of-flow popover, only the viewport's own height and `max_h`), and an index-built list + (`virtual_rows`) mounts the viewport's rows and half a viewport of overscan, as it does when + all its rows are new; the rest of the overscan mounts over the next few frames. An estimate + short of the laid out height retries once, with the measured viewport, before presenting, so + no frame shows blank rows. `scroll_into_view` of a row taller than its estimate now lands it + in view: each placement clamps to the end the rows it mounted measure. `virtualize` lists keep + their full overscan from the better estimate. In a launcher-shaped bench (`tree_swap --cells + 200 --lazy-grid`) the grid's first showing lays out 288 nodes instead of 629, the swap back + to a 200-row list 107 instead of 240, and their commits cost 40–50% less. Tests that count + the rows mounted or built in a list's first frame see fewer. +- **Horizontal scrolling: `El::scroll_x()` and `El::scroll_xy()`.** A viewport scrolls its + first child sideways (a filmstrip, a wide code block or table, a tab strip), or both ways. + The content takes its natural width, unwrapped, and at least the viewport's, unless it sets a + width other than `w_full`. Each axis has its + own offset, momentum and clamping. A wheel or trackpad gesture locks to the axis of its first + delta until it ends, momentum included: mostly horizontal moves the innermost horizontal + viewport under the pointer, and anything else the innermost vertical one, so a diagonal never + moves both. A web touch pan does the same. `tx.scroll_into_view` and caret follow work on both + axes, `.scroll_edge_fade` fades left and right, and `tx.scroll_to_x(key, x)` is new. + `Markdown::scroll_wide(true)` lets code blocks and tables scroll instead of wrapping and + shrinking (off by default). Scripts take `dx` on `scroll` and `vx` on `fling`. + Things apps can notice: Shift with a mouse wheel now scrolls horizontally on Windows, Linux + and the web, and a horizontal trackpad swipe that used to move a vertical list by its tiny + vertical part only does so when no horizontal viewport is under the pointer. Hosts that drive + `Runtime` themselves can report wheels through `Runtime::wheel_xy` with `wheel_began` and + `wheel_ended`; `Runtime::wheel` and `Runtime::fling` are unchanged. Glyphs wholly outside + their clip are skipped on x as they already were on y: nothing drawn changes, but the glyph + count in frame stats drops for clipped text. +- **`El::on_drop_files`: drop files in from other apps.** Files dragged from Finder, Explorer + or a file manager go to the innermost `on_drop_files` element under the pointer that accepts + any of them, in one call with the files it accepts. `.accepts_files(|path| ..)` or + `.accepts_extensions(&["png"])` filters them; a target that accepts none passes the drag to + the next accepting element around it. `.on_drop_hover(|s, over, tx| ..)` hears the drag + reach and leave the target, for a highlight. A drop over no accepting element goes to the + root's `on_drop_files` (or, while a modal is open, the modal's, and only inside it), else + it's ignored. Drop zones take no pointer events, so one laid over other elements leaves + their clicks, menus and help. winit gives no drag position, so the window + samples the system pointer while a drag is over it. macOS, Windows and X11; Wayland and the + web report no file drags. Headless scripts use `drag_files` and `drop_files` events, and + `headless_run` has `ScriptEvent::DragFiles`, `DropFiles` and `DragFilesLeave`. +- **Covered and minimized windows don't run their view.** A shown window that was fully + covered (macOS and X11 report it), minimized, or waiting out a missed frame used to build + its view and lay it out on every update, wake and due timer. Now it runs updates, `poll`, + timers, `on_close` and queued input as a hidden window does, and the view waits, dirty, for + the frame that uncovers it, which builds once with the latest state. Uncovering already + landed running motion; a window restored from minimized on Windows, which gets no occlusion + event, now lands it too, so it doesn't play out what changed meanwhile, and asks for its frame + when it comes back at the same size. So does any window whose next drawn frame follows a + minimize no event reported (X11). On macOS, whether a window can draw follows occlusion alone, + since `isMiniaturized` stays set into a deminiaturize. A `scroll_to_bottom` asked while a + window was covered or hidden lands in the frame that shows it, rather than gliding after. A + modifier change that arrives after an update, before its frame, goes to the focused handler + of the view that update builds. An app that relied on side effects in view code while covered + will see them only when the window shows. The dev panel's tree still builds on demand. +- **`Recorder`: record the microphone to a file.** `Recorder::to_file("note.m4a")` records AAC + (a `.wav` path, or `.format(RecordFormat::Wav)`, records WAV; the format decides the + file's extension) with `start`, `pause`, `resume`, + `stop` (returns a `Recording { path, duration }`) and `cancel` (deletes a recording in + progress). `state()`, `elapsed()` and a smoothed `level()` (peak and RMS in dBFS, `meter()` + in 0..1) are read without allocating; `live_level()` drives a bound meter that redraws while + recording and draws nothing while idle. `Recorder::permission()` and `request_permission` + report and ask for microphone access; starting without it ends in `Failed` with a clear + message, and a bundled macOS app without `NSMicrophoneUsageDescription` fails to start + instead of being ended by the system. macOS records with AVAudioRecorder and reports an + unplugged or switched input as `Interrupted`, keeping what was captured. Other platforms + fail with "recording isn't supported on this platform". Headless runs record from a + `FakeMicrophone` on the virtual clock and write a real WAV on stop. New exports: + `Recorder`, `Recording`, `RecorderState`, `RecordFormat`, `MicPermission`, `Level`, + `FakeMicrophone`; an app with its own type of one of these names imported by glob needs a + qualified path. +- **Web keyboard focus and composition stay with the field.** Leaving an editor returns + keyboard focus to the canvas; secure fields use an emptied password input. Taps no longer + force focus through the canvas, recomposition replaces its old range, and mobile + `beforeinput` Enter follows Rune's submit/newline rules. Rust sends only changed text + windows, continuous pointer input waits for rAF, unsupported window requests warn without + covering the app, and tab visibility updates `AppHandle::is_visible`. + +- **Web follows conditional updates and page navigation.** Browser handles use the same + `update_if` runtime path as native; the textarea routes PageUp and PageDown to Rune. + +- **Build static web apps.** `scripts/web-build.sh` packages a wasm app, JavaScript snippets + and an HTML entrypoint for HTTPS hosting. `examples/web-hello` exercises message input, + scrolling and clipboard; `WEB.md` covers app integration and browser limits. + +- **Browser clipboard, links and viewport.** Web copies and paste requests use the browser + clipboard; secret-copy requests fail explicitly. `web::open_url` opens safe link schemes + without an opener. `Cx::safe_area` exposes browser insets, and the canvas tracks the visual + viewport when the software keyboard opens. Reduced-motion preferences reach the runtime. + +- **Web text and touch input.** A hidden textarea mirrors a sliding UTF-16 context for + browser composition, predictive replacements, selection and paste. Touch pans use + momentum and a damped edge return; completed taps focus editors synchronously. + +- **Web fonts are self-contained.** The browser target bundles Inter Regular and IBM Plex + Mono Regular, accepts app-provided font bytes, and never scans system font directories. + Apps supply additional weights, symbols and scripts through `AppSpec::fonts`. + +- **Experimental WebGPU canvas host.** `App::run` on `wasm32-unknown-unknown` starts one + winit canvas with asynchronous GPU initialization and demand-driven browser frames. + `rune::time::Instant` uses the browser clock on wasm and the standard clock on native. + Overlays, extra windows, native window hooks and blocking GPU operations are unsupported. + +- **Page keys skip a scroll view with nothing to scroll, and `Tx::scroll_page`.** With a chat's + short multi-line composer focused, Page Up and Page Down paged the composer's own scroll area + (a no-op) instead of the message list beside it. Rune now skips scroll views whose content + fits when it picks one: around the focused element, then around the pointer, then the first + in the tree. A view that overflows still keeps the keys at its edge, as an NSTextView does. + New `Tx::scroll_page(key, pages)` pages a viewport by `pages` × 90% of its height with the + same rules, so an app can route the keys itself from `on_input_key` or `on_key`. +- **Selectable Markdown, and selection across texts with `El::selection_group`.** New + `Markdown::selectable(true)` lets people select and copy a whole Markdown block as one + selection: a drag runs from a paragraph through list items into a code block, Shift-click + extends, Cmd+A selects the block and Cmd+C copies the text as drawn, as a web browser does (a + newline between blocks, a tab between table cells, no list markers, fences or emphasis + markers). Links still open on a click. The highlight is the kit's `selection()`, overridden + with `MarkdownStyle::selection`. Underneath, `El::selection_group(true)` makes any element's + selectable texts one selection in tree order, and `El::uncopied(range)` marks bytes that draw + but aren't copied (Markdown's padding around inline code). A selected text no longer loses + its selection when text is appended after it (a message streaming in); a change inside the + selected part still drops it, as does its virtual row scrolling out. An elided text + (`max_lines`, `truncate`) selects through its ellipsis and copies whole. +- **`Tx::fly_text` lands on the destination's text, not its box.** The source was measured by + its laid-out lines but the destination by the whole element, so a destination wider than its + text (a message body stretched across a column) scaled the flight into a large ghost and a + small copy. Both ends now use the same rule each frame: the lines' extent from their offsets + and advances, placed by the text's alignment, clamped to the content box. A flight between + same-size text now stays at rest scale, and centred or end-aligned text flies from and to + where it's drawn. +- **Return and Escape during an input method composition only confirm or cancel it.** A + Return or Escape key event that reaches a field while it has a preedit (Japanese, Chinese + or Korean input, say) no longer runs its `on_submit`, presses the default button, inserts a + newline, blurs the field or reaches `on_key`. +- **`El::on_step` gives a slider its keyboard.** While the element is focused, Left and Down + call it with -1, Right and Up with +1, Page Down with -10 and Page Up with +10, repeating + while held; `El::on_step_limit` takes Home (`false`) and End (`true`) to the ends, and + without it they go on to the app. A slider built from `on_drag` adds them to become + focusable and adjustable from the keyboard, with role `slider`. Its keys come before its + `focus_group`'s arrows. +- **Breaking: Return no longer presses a focused button; Space does, and Return goes to the + default button.** As in AppKit, Space presses the focused button, checkbox, switch, radio, + segment or popup button, and Return presses the new `El::default_button()` in the window or + open modal, else reaches `on_key` (with `tx.focused()` naming the focused control). A + focused element that takes Return keeps it: a text field with `on_submit`, a row of a + `menu`, `listbox`, `list`, `tree` or `grid` group, a `focus_highlight` row, or a link. A + text field without `on_submit` passes Return to the default button. An app + that relied on Return pressing a focused button should mark its primary action + `.default_button()`, or handle Return in `on_key`. Return no longer opens a focused popup + button (role `combobox`) either; Space, Up and Down still do. Shift-modified keys other than + Tab and typed text no longer navigate a `focus_group` or press anything: Shift-Space, + Shift-Return and Shift-arrows go on to `on_key`. The rune README's "Key routing" has the + full table. +- **A focusable control with no `focus_ring` draws AppKit's ring.** Focused from the keyboard, + a `focusable(true)` element whose ring was never set (on it or a child, short of another + focusable) now draws a 3 pt ring just outside its border box in `cx.focus_color()`, + following its corner radii. Before, it drew nothing. Text fields, focused links, `focus_highlight` rows and + the items of `menu`, `listbox`, `list`, `tree` and `grid` groups still draw none, and rune-kit + controls keep their own rings. `El::no_focus_ring()` turns the ring off for a control that + shows focus its own way. +- **`cx.accent()` and `cx.focus_color()` follow the user's accent colour.** `rune::system_accent()` + returns a `SystemAccent`: on macOS the accent picked in System Settings + (`NSColor.controlAccentColor` and `keyboardFocusIndicatorColor`), elsewhere and headless + macOS's default blue with focus rings at 50%. Views read it for the window's appearance with + `Cx::accent` and `Cx::focus_color`. When the user picks another accent every window and + overlay re-runs its view, memos included. Tests set one with `Runtime::set_system_accent`. A + rune-kit theme can follow it with + `Kit::from_palette_focus(seed, PaletteFocus::Custom(cx.focus_color()))`. +- **`Tx::focused()` tells `on_key` whether a control has focus.** A window's `on_key` hears a + key first while nothing has focus and again after a focused control passes it on, and + couldn't tell the two apart. In key handlers `tx.focused()` is now the focused element's key + (`#n` for an unkeyed one), or `None` when nothing has focus, so plain arrows can change a + settings pane only while no control is focused. The rune README's "Key routing" lists the + whole order a key takes. +- **Mac apps get standard Edit and Window menus; `App::standard_menus()` opts accessory apps in.** + A regular app whose menu bar is still winit's default now also has Edit (Undo ⌘Z, Redo ⇧⌘Z, + Cut, Copy, Paste, Select All) and Window (Minimize ⌘M, Close ⌘W); an accessory app gets them + with `App::standard_menus()`, and never a Quit item. Items go to the first responder, so AppKit + windows (an open panel, an updater) get their editing and close keys. In a Rune window every + one of these keys still reaches text fields, `on_key` and shortcuts first, once, as before. + What changes: a ⌘W or ⌘M that nothing takes now closes or minimizes a window with that + title-bar button, as clicking it would (`on_close`, `keep_running`). A custom `MenuItem` with + the same equivalent (Close Tab ⌘W) keeps it, and new custom menus go in the Mac order (File + before Edit, Help last). Apps that set their own menu bar are unchanged. Details under + "Standard menus" in `src/shortcuts/README.md`. +- **`Tx::minimize()` and `AppHandle::minimize()` minimize a window** as its minimize button + would (winit's `set_minimized` off macOS). A close or quit in the same change wins. Hidden + windows, panels, launchers, overlays, borderless windows and windows without a minimize button + ignore it, saying so in debug builds. On `AppHandle`, `minimize` and `focus` are last-wins, a + later `open`, `hide` or `close` cancels it, and after a `show` it minimizes the shown window. +- **`KeyEvent::is_command(c)`** matches Cmd (Ctrl off macOS) plus any character, including + Cmd-Space's `Key::Text(" ")` form. The `Key::Command` docs now say it carries any character + (⌘, and ⌘1 too), lowercased, not just editing letters. +- **`El::time_scale(k)` runs one subtree's animations at `k` times normal speed.** Springs, + transitions (enter, exit, layout), implicit animations, hover and press fades, loops and word + reveals inside it advance by `dt × k`; `0.0` freezes them exactly and requests no frames, and + changing `k` carries on from the same place. Nested scales multiply, and all of them multiply + with `Cx::time_scale`, which still scales the whole window. State keeps updating (a hover is + tracked, only its fade waits), an exiting element drops its own factor and follows its + ancestors still in the tree (so an exit in a frozen subtree finishes once it resumes), and + scrolling, growth stacks and `Tween` keep the window's clock. Trees that don't use it are + unchanged. In `rune-motion`, `AnimationStore::set_node_time_scale` and + `Scene::set_time_scale` do the same per node, and `AnimationStore::logical_end` reports + store time for a scaled node (infinite while frozen). `Choreography` keeps scheduling in + store time: a cue on a frozen step's arrival waits for it to resume, and `PhaseAnimator` + advances once a frozen phase resumes. +- **A wrapping tooltip child wraps inside the box.** `Tooltip::child(text(..).wrap())` laid out + at its one-line width and drew past `TooltipStyle::max_width`; it now shrinks to the box and + wraps there without `.shrink()`, beside a chip that keeps its width. Wrapping text nested + deeper in a child still needs `.shrink()` on that child. `El::wraps()` reports whether an + element is wrapping text. +- **`App::tab_visits_controls(true)` lets Tab reach every control.** By default Tab follows + macOS: with Keyboard navigation off it visits only text fields and lists. With this opt-in + (also `WindowSpec::tab_visits_controls` and `Runtime::set_tab_visits_controls`) Tab and + Shift-Tab visit buttons and every other focusable control whatever the system setting. +- **`Cx::titlebar_inset()` says where the traffic lights end.** It is the zoom button's + trailing edge in window points, for a top bar's leading inset, and 0 when no buttons sit over + the content: in full screen, in a titled window whose content starts below its titlebar, and + off macOS. macOS windows update it on resize and when full screen starts or ends, and the + view re-runs. Leaving full screen also puts `Chrome::traffic_lights` back where the app placed + them. Headless runs, `run_windows` included, report `Chrome::titlebar_inset()` (67 pt for + AppKit's default placement; 0 for a borderless window), and `Runtime::set_titlebar_inset` + sets it in tests. +- **A modal whose field opens focused returns focus to what had it.** Opening a `.modal(..)` + in the same update that set its `text_input`'s `edit.focused` recorded the field as the place + focus returns to, so closing the modal left nothing focused. It now records what had focus + before that update, such as the button that opened it. Focus the closing update moves + outside the modal (`s.modal = false; s.search.focused = true`) stays where it was sent. +- **`rune` re-exports the motion types its transition and animation API takes.** `Vec2` (for + `Transition::scale_anchor` and `Edge::direction`), `Effect`, `Reveal`, `CubicBezier`, + `StepPosition`, `Decay`, `Blend` and `Velocity` are now nameable as `rune::…`, so an app + needn't depend on `rune-motion`. `rune::Blend` is the animation blend; the GPU blend mode stays + `rune::render::Blend`. An app that glob-imports `rune::*` and defines one of these names + itself keeps its own. +- **`Key::PageUp` and `Key::PageDown`, and page keys scroll.** Page Up and Page Down used to + reach no handler; winit, Wayland layer shells and headless `--keys` (`PageUp`, `PageDown`) + now send them. A key nobody claims scrolls the focused element's scroll view (else the one + under the pointer, else the first) by 90% of its height, and Home and End scroll it to the + top and bottom, as an NSScrollView does. Text fields pass page keys on, so the caret stays + put while the view scrolls. `Key` is now `#[non_exhaustive]`: a `match` on it needs a `_` arm. +- **A duplicate sibling key no longer closes the app.** Two siblings with one key used to stop + a debug build at an assertion and panic inside Taffy in a release build, closing the window. + Every build now keeps the first sibling's key, renames each later one `key#dup1`, `key#dup2`, + ... in tree order so it still draws, and prints the warning naming both call sites once per + key. Duplicate row keys in a `virtualize` or `virtual_rows` list, which panicked in every + build, are renamed the same way. Trees without duplicates are unchanged, and checking them + allocates nothing. +- **Ogg and WebM audio plays on macOS.** `Player::audio` on an Ogg Vorbis, Ogg Opus or + WebM/Matroska Opus clip failed at once (AVFoundation can't read them). The new default + `ogg-audio` feature decodes such a clip in pure Rust (symphonia, opuscule), streaming it to a + temporary WAV that AVPlayer plays, so state, time, seeking, rate, looping and request headers + work as for any clip. Clips are picked by extension, or by their bytes when a URL has none. + The compressed clip is held in memory while it decodes, and the WAV takes about 11 MB a + minute of 48 kHz stereo. A clip longer than a WAV holds (about 6 hours of that) fails with a + clear message. Video in those containers still fails at once, and with + `default-features = false` so does this audio. The feature adds symphonia's Ogg, Matroska + and Vorbis crates and opuscule to macOS builds. +- **Headless audio follows the virtual clock.** A headless run reported a playing audio clip + with its time stuck at 0. Its time now advances with the runtime clock of the thread that + made it, as a video's does: `pause`, `seek`, `set_rate`, looping and the end (`Ended`, and + the clip's waker hears it) behave as in a window, still without a player or any sound. A + still or `--frames` capture of a progress bar now shows it moving. Each new `Runtime` starts + that clock again at 0. +- **`Player::request(url).header(name, value)` opens media with HTTP request headers.** A + `MediaRequest` builds a player with `.audio()` or `.video()`, and every request for the clip + (load, poster, playback) sends its headers, so media behind `Authorization` streams instead + of being downloaded first. On macOS it uses AVURLAsset's HTTP header option. Header values + never print in `Debug`. `MediaSource` is unchanged. +- **`Transition::allow_small_scale()` lets a small glyph scale from below 0.9.** Transitions + keep scale within [0.9, 1.1] by default. `Transition::scale(0.6).allow_small_scale()` lowers + the floor to `SMALL_SCALE_FLOOR` (0.5), for an icon in a button that barely moves at 0.9; + nothing scales to or from 0. `Effect` gains a pub `small_scale` field: an `Effect { .. }` + literal without `..Effect::IDENTITY` needs it. +- **A node leaves with the transition of its last render.** `El::transition` was read only when + a node mounted or revived, so a later render couldn't change how it leaves. Each render now + updates a present node's transition, as in SwiftUI: removal uses the removal effect and exit + spring from the last commit before it, and a revive enters with the latest insertion. An + entrance already running keeps the look it started with. An element whose transition changes + between renders (or that drops one, falling back to `.opacity`) now exits differently than + before. +- **`El::virtual_rows(count, estimate, key, build)` builds a virtual list's rows by index.** + It is `virtualize` with rows the list builds itself: layout calls `build(state, i)` only + for the rows in the mounted window, after it knows where the window is, so a commit costs a + key check per row plus the rows it mounts. A 5,000-row list whose counter ticks every frame + no longer builds or looks up every row in the view. Rows keep their measured heights by key, + prepending or inserting keeps the reader's row in place, `scroll_into_view` reaches any row, + and a focused field keeps typing after its row scrolls out. Rows new to the window beyond + the viewport mount half a viewport per side per frame, and the list asks for frames until + they fill, so a page loaded above the reader or a jump lays out a little text each frame + instead of three viewports at once. A list's first showing mounts all of them. Write row + handlers to find their item by key or id, never by `i`. Elements in rows that aren't built + don't exist: the inspector, accessibility, Tab order and text selection see built rows + only. Both kinds of virtual list now show their last rows in the same frame when rows are + removed below the scroll offset, where the viewport used to stay blank until the next + commit. `scroll_into_view` on a row that measures taller than its estimate now lands it in + the same frame. +- **`update_if` for updates that may change nothing.** `AppHandle::update_if`, + `OverlayHandle::update_if` and `Runtime::update_if` take a closure that returns whether it + changed state the view reads, as `poll` does. On false the view doesn't re-run, a shown window + or overlay doesn't redraw, a hidden one doesn't poll, and a hidden launcher or prewarmed overlay + doesn't refresh, while the closure's `Tx` requests still happen (clipboard, close and quit, + menus, `wake_after` scheduled from now; a scroll or `fly_text` still takes a frame). A batch + drained together commits once if any returned true. Returning false after changing state the + view reads leaves the screen stale until the next change. `update` is unchanged. For a timer + that posts every 500 ms with nothing new, a 300-row view's frame drops from 0.70 ms to 0.11 ms + median (0 of 100 builds). +- **Tooltip labels wrap at the style's max width.** `Tooltip::label` and `Tooltip::text` stayed + on one line past `TooltipStyle::max_width` and drew outside the box; they now wrap inside it, + so a kit's Standard tooltip wraps at 320 pt. Tooltips without a max width are unchanged. +- **`El::aspect_fit(ratio)` sizes an element to the largest box at a ratio that fits its room.** + As SwiftUI's `.aspectRatio(ratio, contentMode: .fit)`, the element takes the free space along + its parent's main axis and the whole cross side (within `max_w` and `max_h`), then lays out at + the largest box at `ratio` inside it, so siblings such as a caption follow the fitted box and + the parent's alignment places it. Its own grow and its children never size the room, so equal + cells share a row equally. Layout runs a second pass only for trees that use it. +- **`El::max_lines(n)` clamps wrapped text to `n` lines.** Like CSS `line-clamp`, it wraps, + measures at most `n` lines tall and ends the last line with "…" when more would follow. The + cut falls between graphemes and refits on resize, inside a word too wide for the box; spans + and links keep their looks, and copy and accessibility keep the whole string. `.truncate()` + and `.truncate_fade()` turn it off, and `.max_lines` turns them off. A `text_input` ignores it + and the truncations. Text without it is unchanged. +- **Markdown tables take their own font and cell padding, and can sit flush left.** + `MarkdownStyle::table_font(TextStyle)` sets the cells' font (the body's by default; a web + table at `0.93em` is the body at 0.93 of its size), `table_cell_padding(x, y)` the padding (10 + by 6 by default) and `table_flush_left(true)` drops the first column's left padding so it lines + up with the paragraphs around it. A table without an outline (`table_outline(None)`) no longer + insets its cells by the half-point border it doesn't draw, so it sits 0.5 pt further left and + is 1 pt narrower. +- **A Markdown table that ends the text sizes to its last row.** rune-kit read a last table row + with no newline after it as still streaming in and left it out of the column widths, so a + table ending a trimmed note could wrap that row. It now does so only under the new + `Markdown::streaming(true)`, which a stream sets while its text is still arriving; otherwise + the text is taken as whole. A stream that wants its columns held passes it. +- **`ui-monospace` in `AppSpec::families` names the platform's monospaced font.** The sans and + mono slots are CSS lists, and CSS's `ui-monospace` in one now stands for `Family::SystemMono`'s + families (SF Mono on macOS, whose family name is hidden), followed by the rest of the list. With + `families: ("Inter", "ui-monospace")`, `Family::Mono`, `.mono()` and mono rich spans (rune-kit + Markdown's inline code among them) shape with the same font as a `Family::SystemMono` code + block. Where no monospaced font is installed (the web, or Linux without one) a list naming + no other family falls back to the sans slot. Apps that don't name it are unchanged. +- **Live editing for external app crates and on the desk Mac.** `scripts/rune-dev + --manifest-path APP/Cargo.toml --patch 'src/ui/**/*.rs'` hot-edits an app outside this + repo; the app adds only `hot = ["rune/hot"]`. With `--desk` the app compiles on the build + Mac and runs on this one, patched over an SSH tunnel after a binary hash and platform check. + `RUNE_HOT=1` now enables `--hot` behavior. `run_windows*`, `WindowSpec::from_app` and + `App::run` patch every window from one devserver connection, `poll` and `on_key` patch like + the view, and `--snap-on-patch` renders a `run_windows` or `App::window` app's `--window` + headless. A panicking patched view, `poll` or `on_key` falls back to the startup one in + every window, and patches reach overlays and hidden launchers too. Hot builds only; + feature-off builds are unchanged. + +- **Hidden overlays and windows don't run their view.** A hidden overlay used to build its view + and lay it out on every change (an `OverlayHandle::update`, a `setup` waker, a due + `wake_after`, a clipboard or pop-up answer), and a hidden window did on every due + `wake_after`. Now handlers, `poll`, timers, queued input, drag ends, clipboard and window + commands still run while hidden, but the view waits for the frame that shows the host, which + builds it once with the latest state. An app that relied on side effects in view code while + hidden will see them only on show. Hosts that keep a ready frame while hidden (a launcher + panel's cached pixels, a prewarmed macOS overlay's retained commit) still refresh it, but at + most every 250 ms: the first change after a quiet spell renders at once, later ones wait. A + show whose state changed since that frame renders it first, as for an update in the same + turn. A `scroll_to_bottom`, `scroll_into_view` or `fly_text` asked for while hidden counts + as a change; a `wake_after` alone doesn't. A window with `fit_content_height` whose content + changed while hidden builds it as it shows and opens at the new height. +- **Occluded windows and overlays no longer spin or leak; per-surface frame stats.** A surface + whose drawable acquisition kept failing (covered, or the displays asleep) could retry at once, + and an overlay's failed re-acquire turned the loop with `ControlFlow::Poll`. Every miss now + waits for its retry (occluded: 250 ms doubling to 2 s; outdated: 250 ms; timed out: a frame) + with the display link stopped, so neither input nor display ticks try sooner; timers due + meanwhile still run. A hidden launcher refresh that gets no drawable retries the same way and + never reveals the pixels it failed to replace. On macOS Rune reads the window's + occlusion before asking wgpu, so a covered surface makes no failed `get_current_texture` call + at all. That matters on wgpu-core 30.0.1, which leaks a texture id per failed acquisition + (fixed on wgpu's `v30` branch, unreleased); an app that wants the fix now can add + `[patch.crates-io] wgpu-core = { git = "https://github.com/gfx-rs/wgpu", branch = "v30" }`. A + display link that failed to start while the displays slept is retried after the next present. + New `WindowHandle::surface_stats()`, `OverlayHandle::surface_stats()` and + `Runtime::surface_stats()` return a `SurfaceStats` (redraws, unpaced redraws, presents, failed + acquisitions by kind, skipped acquisitions, loop turns and wakes, as current totals and + per-second rates, plus the `Pacing`). The dev panel shows them under Frames, a native `--trace` + prints them when it closes, and `App::dev_stats(fn() -> String)` adds the app's own line beside + them. A surface that fails more than 400 acquisitions, or makes more than 400 redraws that + waited for nothing (no display tick, vsync, timer or event), a second for two seconds prints + one `rune: surface has spun` line, in release builds too. +- **`memo(id, version, || el)` reuses a subtree whose inputs haven't changed.** The closure + runs again only when `version` or the window's dark mode, scale or reduced-motion preference + changes; otherwise the view gets the subtree the last build returned, with the same node ids, + hover, focus and springs. An offscreen `virtualize` row that is memoized costs a lookup, so a + long transcript whose counter ticks every frame no longer rebuilds every message. + `Cx::layout` and `Cx::caret` read inside the closure are tracked: a reuse still re-runs the + view when they move, and builds again when one returns something else. `TextEdit` now + implements `Hash` over what a field draws (text, selection, composition, focus), so a + memoized field passes the edit itself as its version. Hot reload and dev tunables drop the + cache. Virtualized lists also find their mounted rows by binary search now, rather than + walking every row each commit. +- **Markdown keeps every document on screen parsed.** `Markdown` and `markdown::parse_cached` + kept the last 32 sources, so a transcript showing more than 32 messages parsed every one of + them on every commit. The cache (and the code-colour and table-width caches beside it) now + keeps whatever the last two commits drew, and evicts the least recently drawn of the rest + past a memory budget. A streaming message reparses only from its last top-level block, and + only its newest string stays cached. + New `rune::commit_generation()` counts commits on the thread, for caches like these. +- **`El::truncate_middle()` and `El::truncate_head()`; `Type::caption()`.** Middle truncation + keeps a single line's start and end with "…" between, as `NSLineBreakByTruncatingMiddle` + does for paths; head truncation keeps the end. `.truncate()` now cuts between graphemes + instead of chars, so a combining accent or emoji sequence is never split (text without them + draws as before), and a truncated selectable text copies its whole string even across the + ellipsis. A link or span the cut hides is dropped rather than moved onto "…" (which takes + the style of the text it replaces, as AppKit draws it). `Type::caption()` is `small` on a 16-point line (11 / 16 in the built-in themes), + for secondary text under a control; it's a method, so app themes that build `Type` as a + literal get it without a change. +- **`Switch` draws as macOS 27's `NSSwitch`: a capsule track and a pill knob.** The compact + (default) switch was a 24 × 16 track with a rounded-square 12-point knob; it is now an + `NSSwitch` mini, 36 × 16 with a 21 × 14 knob inset 1 point, so it is 12 points wider. + `Switch::control_size(ControlSize)` picks the other measured sizes: Small 44 × 20 (knob + 26 × 16), Regular 54 × 24 (32 × 20), Large 64 × 28 (38 × 24) and ExtraLarge 80 × 36 (48 × 30). + `State::Hover` and `State::Pressed` stretch the knob towards the middle instead of rounding + its corners. The standard appearance keeps its 28 × 16 size with a capsule track and round + thumb. +- **Breaking (visual): a `Button` with no size set is 24 points tall, as a regular macOS + push button, not 28.** New `ControlSize { Mini, Small, Regular, Large, ExtraLarge }` (AppKit's + names, `#[non_exhaustive]`) with `Button::control_size` and `IconButton::control_size` sizes + controls as macOS 27 measures them: push buttons 16, 20, 24, 28 and 36 points tall with 8, 10, + 12, 14 and 18 points of padding a side, Mini in 9-point type and Small in `ty.small_medium`; + icon buttons are squares of the same heights. `ButtonSize` and `.size()` are deprecated and + keep their old metrics, so existing calls draw as before: for a `Button`, `Small` (24) is + `Regular`, `Normal` (28) is `Large` and `Large` (32) sits between `Large` and `ExtraLarge`; + for an `IconButton` the names match (20, 24 and 28 are `Small`, `Regular` and `Large`). Only a + `Button` that never called `.size()` moves: set `.control_size(ControlSize::Large)` to keep + 28. Toast actions now use `Regular` (same height, 12-point padding and the `md` radius). +- **`--keys` caps title-case key names.** A key name without a glyph drew upper case + ("CAPSLOCK", or "SPACE" from a script's text key under a modifier). It now draws title case + ("Capslock", "Space"), as the in-app keycaps do; single letters stay capitals and `F12` is + unchanged. +- **Hiding a window or overlay is a focus loss for its keys.** `on_physical_input` handlers + used to hear `PhysicalInput::FocusLost` only when the platform reported a blur, which a hide + on Wayland, with `release_gpu`, or of an overlay never did, and never in `--desktop` or + headless scripts. They now hear it on every hide and every `Focus(false)`, once until the + window has focus again, and a hidden window or overlay runs it without waiting to show. +- **Modifier keys on their own reach `on_key`, when an app asks.** `App::modifier_keys()` (also + `WindowSpec::modifier_keys()` and `ConfiguredOverlay::modifier_keys()`) sends Shift, Control, + Option/Alt, Command/Super and Fn going down and up as `Key::Modifier { modifier, pressed }`, + with the side in `Modifier` (`ShiftLeft`, `AltRight`, …, `Modifier::side()`). `mods` hold + the state after the change. A focused `on_physical_input` handler, such as a shortcut + recorder, hears the key first, and one it takes is never sent. A blur or hide releases every + key held. Nothing changes for apps that don't opt in, but `Key` has a new variant, so an + exhaustive `match` on `Key` with no `_` arm stops compiling: add `Key::Modifier { .. } => …` + or a `_` arm. +- **`App::try_run` returns startup errors.** `App::try_run`, `try_run_windows_with` and + `try_run_windows_with_args` return `Err(String)` when the event loop can't start (no Wayland + or X11 display, as over ssh or in CI) or fails, where `run` panics. On a Mac no one is logged + in to, an app used to start AppKit and wait forever without a window; it now fails at once + with "no window server session", and `run` panics with that message. `run` and its siblings + otherwise behave as before. +- **`Pixels::set` wakes the windows showing it.** A `Pixels` is now a live source like `Live`: + `set` (from any thread) wakes exactly the windows and overlays whose scene shows it with + `El::pixels`, and no others. Sets between frames coalesce into one wake and one upload; a + hidden or covered window sleeps and draws the latest image when it shows again; an element + keeps waking while its exit (or its parent's) draws it, and stops once it's removed or its + window closes. `LiveText` on an exiting element now keeps updating the same way, where it + used to freeze as the exit began. Apps that woke a window after `set` themselves can drop + that. Finished `ImageCache` decodes also wake the windows showing them. +- **`El::on_screen_layout` follows a window's own moves in the same frame.** An animated + resize or centre, `place()`, a position change and a resize landing used to report the new + layout against the previous origin, then correct it a frame later when the move arrived. + The window now reads its origin as soon as it sets its frame. +- **Prewarmed overlays report where they are.** A prewarmed overlay's `El::on_screen_layout` + used to report rects from (0, 0) when it warmed, and its warm frame drew at the scale winit + gave the window rather than the panel's display. A rect that moved while it was hidden + also wasn't delivered when it was shown. It now warms at its placed origin and display + scale, and the reveal delivers rects that moved while hidden. +- **A fading-out overlay clicks through on macOS.** `OverlayHandle::fade_out(d)` stopped Rune's + input at once, but a panel that wasn't prewarmed still took clicks and scrolls for the whole + fade, so they never reached the window below. It now ignores the mouse from the start of the + fade. +- **`wake_after(Duration::ZERO)` never spins the loop.** A wake due sooner than a frame asks + for the next frame. A window or overlay a display link paces (macOS) draws it on the next + tick: windows now keep their link running for it too, as overlays do. Hidden, covered, faded + out or unpaced (no display link, or not macOS), it waits a frame interval (60 Hz) from the + last poll. It used to wake the loop at once, so a poll that kept asking ran as fast as the + loop could turn while covered, after a fade-out or without a display link. +- **Overlays on macOS draw at the scale of the display they're placed on.** An overlay used to + take its scale from winit's window when shown, which for a hidden panel needn't match the + display it's about to appear on, so a panel placed on a display of another scale could draw + its first frames at the wrong scale. It now reads the panel's `backingScaleFactor` once it's + on screen, and before that the scale of the display holding most of its frame. `OverlayPlacement::Rect` on + `DisplayTarget::Primary` documents that it's a global rect that may sit on any display. +- **`El::on_screen_layout`** reports an element's rect in global screen points (from the + primary display's top-left, y down), the space of an overlay's `OverlayPlacement::Rect` on + `DisplayTarget::Primary`, so a window can open an overlay exactly over one of its elements. + It runs when the element lays out somewhere new and when its window moves. Headless runs + report against the script's virtual desktop: a window opens centred on the primary display, + or at its `position`, and `place()` moves it. +- **Overlays draw through a fade-out.** `OverlayHandle::fade_out(d)` stops input at once but + keeps drawing until the fade ends (it used to stop drawing at once), so an exit transition + started in the same turn plays out as the window fades, and the panel isn't treated as + occluded while its alpha falls. Showing again mid-fade carries that motion on instead of + settling it. A shown overlay whose poll calls `tx.wake_after(Duration::ZERO)` now keeps its + display link running and polls every frame, instead of stopping after each frame and + restarting on a timer, so a poll stepping its own animation needs no looping element. +- **`El::drag_threshold(points)`** sets how far the pointer travels before that element's + `drag_out` starts, in place of `DRAG_THRESHOLD` (4 pt, 8 on Linux), which stays the default. +- **Hidden overlays follow theme changes.** A hidden or prewarmed overlay switching between + light and dark used to keep the old theme until it was shown and the theme changed again; it + now takes the change while hidden and redraws in it before it's revealed. +- **Overlay window levels and fades on macOS.** `ConfiguredOverlay::macos_level(level)` and + `OverlayHandle::set_macos_level(level)` set the AppKit window level (e.g. 3 for + `.floating`), changeable while shown. `OverlayHandle::fade_in(d)` and `fade_out(d)` fade + the window's alpha with AppKit's ease; elsewhere they show and hide at once. Overlay panels + now go exactly where they're placed at any level, including over the menu bar, where AppKit + used to push windows below it at levels under the menu bar's. Overlays read the system + light or dark theme when their window is created rather than on the first theme change. +- **`Shadow::core_animation(x, y, radius, color)`** builds the shadow a CALayer draws for a + `shadowRadius`: Core Animation's blur has a standard deviation of about the radius, so + `blur` is twice it. +- **Continuous corners.** `El::continuous_corners()` rounds an element's fill, border, image, + outline, `clip_rounded` and system material with Apple's continuous curve (CALayer + `.continuous`, SwiftUI `.continuous`) instead of circular arcs; shadows stay circular. + `LayerSpec::clip_radius` takes a negative radius for the same shape. Adds the public field + `Visual::continuous_corners`, so a `Visual { .. }` literal without `..Default::default()` + stops building. `system_material(SystemMaterial::Glass)` turns the flag on, since + `NSGlassEffectView` draws no other curve, so the element's fill, clip and shadow hole match + the glass; `Popover` follows the flag. +- **System backdrop materials.** `El::system_material(SystemMaterial::Glass | Popover)` backs + an element with Liquid Glass (`NSGlassEffectView`, macOS 26+; the popover material before) + or the popover material, as a native view under a transparent window's Metal layer that + moves in the same Core Animation transaction as each frame. Opaque windows, other platforms + and headless renders draw the fill or a neutral tint, so goldens don't change. An outer + shadow on a material element no longer paints under its interior when the native view is + on. Each native view stays with its element while it's mounted; an element dimmed to zero + takes none. Once the last material element unmounts, the window stops presenting inside + transactions. `rune::{SystemMaterial, MAX_NATIVE_MATERIALS}` are new root exports. + `RUNE_SYSTEM_MATERIAL=legacy|unsynced|off` selects other paths. New example: + `examples/glass-card`. See the crate README's "System materials". +- **Occluded overlays and windows idle instead of spinning; their timers still fire.** A shown + overlay or window whose displays sleep or that is covered no longer turns the event loop + (about a full core before) when its drawable is occluded or times out. It runs updates, `poll` + and due `wake_after` timers without drawing, so a timer can still hide it; re-checks the surface + after 250 ms, backing off to 2 s; and redraws once when uncovered. A covered overlay commits + nothing until then, so motion started while it was covered begins on that frame. A + `wake_after` from `AppHandle::update` or `OverlayHandle::update` now arms while the window or + overlay is hidden, covered or minimised, rather than on its next drawn frame. Without a display + link (made while the displays slept) macOS motion is paced by a ~60 Hz timer rather than a busy + loop, and an overlay's 120 Hz pointer poll for `OverlayInput::Regions` rests while it is occluded. +- **Help tooltips.** `El::help("…")` shows a tooltip after the system hover delay, as SwiftUI's + `.help`. A press, scroll, key or the pointer leaving hides it until the pointer comes back. It + takes no hover or clicks. macOS windows use AppKit's own tooltip, registered per element on + device pixels and replaced only when it moves, and left out behind a modal or under a popover; + overlays and other platforms, and headless, have Rune draw one (0.5 s, the double-click time + on Windows; `Runtime::help_delay`). Headless + `--snap` shows the drawn tooltip, and `--tree` gains a top-level `tooltip` plus `help` on each + element. `ElementInfo` gains `help` and `selected`. Elements without `help` are unchanged. +- **Selectable text.** `El::selectable(true)` lets people select and copy read-only text, as + SwiftUI's `.textSelection(.enabled)`: drag, double-click a word, triple-click a paragraph, + shift-click to extend, Cmd/Ctrl+C, Cmd/Ctrl+A, and a Copy context menu on macOS. After a + click on the text, plain Cmd/Ctrl+A selects all of it and plain Cmd/Ctrl+C copies a non-empty + selection, before the view's key handlers; with Shift, Option or Control added, or nothing + selected, they fall through as before. Inside a row that handles input the row keeps its + clicks, hover, press paint and context menu; a drag that selects text doesn't press, and in a + draggable row dragging drags the row. A view that changes, removes or unselects the text drops + its selection. A link inside selectable text still opens on click. Scripts gain a + `triple-click` event. Text without `selectable` is unchanged. +- **`El::selection_color`** sets the selection highlight of a field or selectable text; both + draw it the same way, and fields draw exactly as before. Kit's `k.selection()` is the colour + its fields use (unchanged), so selectable text can match them. +- **Radial and angled linear gradients, opt-in sRGB blending, and shadow blur docs.** + `El::radial_gradient(center, radius, stops)` draws circular (`f32`) or elliptical (`[rx, ry]`) + radial gradients with up to 8 `(f32, Color)` stops in `0.0..=1.0` in the instanced uber-quad + pass (`KIND_RADIAL`), with `center` in normalized element coordinates (`[0.5, 0.5]` = centre) + and `radius` in points; `El::linear_gradient(angle, stops)` draws linear gradients at `angle` + radians (CSS convention) with up to 8 stops. Both compose with `.fill`, `.border`, `.radius`, + `.opacity` and `.blur`, and spring stop colours in Oklab. `App::srgb_blend(true)`, + `WindowSpec::srgb_blend(true)` and `ConfiguredOverlay::srgb_blend(true)` (plus + `Renderer::set_srgb_blend`, `SurfaceRenderer::set_srgb_blend`, `Runtime::srgb_blend` and + `Color::premul_srgb`) opt into gamma-space (sRGB) compositing for translucent fills, gradients, + shadows, blurs, shapes, text, premultiplied and straight-alpha images, native/video surfaces, + headless `--keys` overlays and `--snap-on-patch` so faint glows over dark backgrounds match CSS + and Core Animation (`CALayer.shadowRadius ≈ σ`, CSS `blur = 2σ`); `srgb_blend` is ignored with a + warning when a `Compositor` is set, and default linear-light rendering is unchanged. + `rune::RadialRadius` is a new root export. +- **macOS drag-out matches an AppKit drag source more closely.** New `El::on_drag_start(|s, tx|)` + runs once the system takes the drag, before its `on_drag_end`, so the app can style the source + while it's dragged (the example dims its tile to 0.28). Every start now gets exactly one end, in + order: a drag-out no system took (headless, or a cancelled press) ends `Cancelled` by the next + frame. New `DragOperation` (`Copy`, `Move`, `Link`) with `DragItem::operation(op)` to offer just + that, `allow(op)` to add one and `offers(op)`; `allow_move()` is `allow(DragOperation::Move)`, + and a drag still offers only Copy by default. Modifier keys pick among the offered operations + only when there are several. `DragItem::opaque(color)` composites the drag image over `color`, + and `DragImage::over_element()` starts a supplied image over the element (at its `size`, else + the element's full unclipped size) instead of centred under the pointer. Behaviour changes: the + default snapshot is placed at its pixel-aligned crop, so it is no longer resampled to the + element's fractional rect, and a drag let go over the app's own windows ends `Cancelled` and + slides back (winit's file-drop handler used to accept it as a Copy and queue a `DroppedFile` for + the app's own file). +- **Apps can resize and centre their window.** `Tx::resize_window(size)` animates the + window's content size on the change's spring with the top edge fixed and the window kept on + its screen; `Tx::resize_window_instant` jumps, and `Tx::center_window` centres as AppKit's + `center` does. `WindowHandle::{resize, resize_instant, center}` do the same from outside a + handler. On macOS the content follows the frame every display frame; Windows and Linux + resize at once; Wayland doesn't keep the window on screen. Headless runs move the viewport + on the virtual clock. Requested sizes stay inside the window's minimum and maximum. + `App::fit_content_height()` opts a window into following its content's natural height, with + no default minimum height. See the crate README's "Resizing and centring a window". +- **Headless recordings of the whole desktop.** `--desktop BACKDROP.png` renders every window a + multi-window app makes, each at its placed frame with rounded corners and a soft shadow (larger + for the key window), over the backdrop scaled to fill the output. Showing, hiding, placing and + focusing follow the script and the app over time, and script pointer coordinates are output + points. It works with `--video`, `--out`, `--snap`, `--strip`, `--keys` and `--pointer`; + `--tree` describes the `--window` window and lists every window's frame. `headless_run()` adds + `desktop()`, `window_frames()` and `windows_at(t)` (`rune::tooling::WindowFrame`). Runs without + `--desktop` are unchanged. `examples/launcher` records a notes app and its ⌘Space panel. +- **A scroll cancels a held press.** Scrolling a list by wheel or fling while a press inside it + is held now cancels the press, as a `UIScrollView` cancels its content's touches: the element + lets go and the release doesn't press. A drag keeps its capture, and programmatic scrolls + (a chat pinned to its bottom) don't cancel. +- **Nested scales compose.** A scaled element inside a scaled element used to scale about its + own unscaled centre, dropping its parent's anchor, so it jumped when its own scale (a press, a + live scale) turned on, and a product of 1 ignored the parent's offset. It now scales about its + centre where its parent draws it, and hit testing follows. This moves the output of apps + that nest scales; a single scale draws exactly as before. +- **Text scales with its box, and `El::scale`.** Text inside a scaled element used to keep its + full size while the box shrank around it. Under `live_scale`, `press_scale`, scale transitions + and scale beats in a sequence loop, glyphs, span backgrounds, selection and caret now scale + with the box. Text under a still scale rasterizes at the scaled size; during a spring it + samples its rest-size glyphs. This moves the output of any app that scales text. Text that + isn't under a scale is unchanged. `El::scale(k)` is a static scale on the same mechanism: + about the centre, no layout change, with hit testing on the drawn rect. A `scale` an app + changes (a zoom slider) samples rest-size glyphs until it holds still for 0.1 s, then + rasterizes at the scale rounded to 1/32, so the glyph atlas stays bounded. +- **Pictures size from their image.** An element with `pixels`/`pixels_fit` that sets only + its width or only its height takes the other side from the image's aspect ratio (it used to + take its content's size, usually 0). Pictures with both sides set, or neither, are + unchanged. `El::aspect_ratio(r)` sets a ratio on any element. A picture whose image lands + or changes shape takes its new size at once, even on a frame that re-runs the view. +- **System monospaced font.** `Family::SystemMono` shapes with SF Mono on macOS, Cascadia + Mono or Consolas on Windows, and fontconfig's `monospace` on Linux, loaded from the system + on first use and falling back to the mono slot. `Family` gains a variant, so an app's + exhaustive `match` on it needs a new arm. +- **Double press.** `El::on_double_press` runs on the second of two presses inside the system + double-click interval (now read on Windows too) and 4 pt of each other; `on_press` still runs + for both. Only clicks pair: a press that travels more than 4 pt, or is held past the interval, + is neither half of one. Scripts gain a `double-click` event. Elements without it are unchanged. +- **Press scale.** `El::press_scale(0.97)` shrinks an element about its centre while a press + on it is held and springs it back on release. Layout and hit testing keep the resting size, + and a held press keeps its hover. Reduce Motion turns it off. Nothing changes for elements + without it; rune-kit buttons don't opt in. +- **An explicit `optical_size(o)` now also picks the `trak` tracking:** text is tracked as Core + Text tracks `o`-point text scaled to the set size, so + `TextStyle::new(size * k, w).optical_size(size)` matches a SwiftUI view at `size` with + `scaleEffect(k)`. This is what Core Text does with its optical size attribute + (`kCTFontOpticalSizeAttribute`): a 28 pt font at optical size 14 lays out exactly as 14 pt + text scaled 2x. Setting only the `opsz` axis (`variations("'opsz' 14")`, or + `kCTFontVariationAttribute`) still tracks at the point size. Auto optical size is unchanged. +- **rune-kit `Markdown` colours fenced code** in ts, tsx, js, json, rust, swift, css, html, + sh/bash, sql and yaml; on by default, so code blocks in those languages render with coloured + tokens (goldens with such blocks move). Unknown languages and indented blocks stay plain, and + layout is unchanged (colour-only spans). New: `rune_kit::markdown::Syntax`, + `MarkdownStyle::syntax(kind, color)` and `syntax_highlight(bool)`. `Block` is unchanged. +- **`MarkdownStyle::diff_text(added, removed)` and `diff_text_tint(amount)`** colour the text + of a diff's added and removed lines (`diff_text_tint` blends the text colour toward the + theme's green and red). Off by default: line text keeps the body colour. +- **rune-kit `Markdown` table cells use tabular figures** (`'tnum' 1`), so numbers line up down + a column; only digits change width. New `MarkdownStyle` builders: `table_outline(Option)` + (`None` draws no outline and adds a rule under the last row), `table_rules`, + `table_header_text` and `table_tabular_figures(bool)`. `table(border, header_fill)` still sets + the outline and the rules. The default look is otherwise unchanged. +- **rune-kit `Markdown` tables no longer wrap a cell when the table has room.** Columns started + at zero width and grew by their content width, but each column's padding was reserved + first, so wide columns came up short and their longest cell wrapped. Columns now start at + their content's width and shrink in proportion to their text when the table doesn't fit. + Most tables' column widths move by a few points. +- **Video and audio playback.** `Player` (alias `Video`) plays a file or URL: + `el().video(&clip, SurfaceFit::Fit)` draws a video (muted by default), and `Player::audio` + plays audio with no element (unmuted by default). macOS uses AVFoundation; headless runs + are deterministic and silent; other platforms report `Failed`. Adds the + `objc2-av-foundation`, `objc2-core-media` and `objc2-core-graphics` macOS dependencies. + `rune::{Player, Video, MediaSource, PlayerState}` are new root exports, so a glob import + of `rune::*` can clash with an app type of the same name. See the crate README's "Playing + video and audio". +- **Headless recordings honour single-window transparency and physical size**, including + alpha in PNG and ProRes output. Default window pixels are unchanged. `--duration auto --out` + selects headless PNG recording; `--out` alone uses automatic duration unless `--native` is set. + Exact mark names such as `step-1` take precedence over time offsets, malformed offsets report + the available marks, and video filenames starting with `-` work. + `headless_run().events()` includes pop-up menu picks and dismissals. +- **Global script shortcuts only run their registered handler**, even when a window is key; + they never reach `on_key` or physical-input handlers. Unregistered chords fail the script. +- **Recording keycaps follow light and dark backgrounds.** `--keys-theme auto|light|dark` + selects the colours of their fixed screencast style; `auto` follows the app's root fill. + Overlays blend correctly over transparent frames, and a failed video encoder stops the run + and reports its exit status. +- **Headless frames can show the script's keys.** `--keys [CORNER]` draws screencast keycaps + (typing grouped into bursts, ⌃⌥⇧⌘ chords with repeat counts, glyphs for named keys) over + `--video`, `--out`, `--snap` and strip frames, and `--pointer` a ripple at each press. A + separate runtime draws them after the app, so `--tree` and `--trace` are unchanged. +- **Scripts can press global chords.** `{"type": "shortcut", "chord": "cmd+space"}` + runs the app's registered shortcut handler. `{"shortcut": …}` is unchanged. +- **Scripts can mark times.** `{"t": 3.2, "type": "mark", "name": "end"}` has no input effect; + apps read marks through `headless_run().marks()` and `mark(name)`. `--at` and `--start` + take `mark:NAME` with an optional offset (`mark:end+0.5`), and `--duration auto` (the + default for `--video`) runs to the `end` mark, or one second after the last event. +- **Apps can read the headless run.** `rune::tooling::headless_run()` returns the run's script + path, its expanded events with their times, `--scale`, `--fps`, the viewport, `--start`, the + frames it writes and its last frame's time, from `init` on. It is None in a window. +- **Headless runs can write a finished video.** `--video out.mp4` (`.mov` for ProRes 4444, + `.webm` for VP9) streams raw frames into an `ffmpeg` child at `--fps` (default 60), so no + frames touch disk; ffmpeg must be on `PATH`. Its length is `--frames N`, `--duration S`, or + through one second after the script's last event. Readback now keeps three frames in flight + and PNGs (`--out`, `--snap`) encode on worker threads. +- **rune-kit feature `mermaid` draws ```` ```mermaid ```` flowcharts and sequence diagrams + natively** inside `Markdown` once the fence closes, and through `rune_kit::mermaid::render`. + Without the feature, or for unsupported diagrams, the fence stays a code block (with a + "Diagram not supported" hint when the feature is on). New `MarkdownStyle` builders: + `diagram`, `diagram_surface`, `diagram_note`, `diagram_font`, `diagram_max_width`. +- **rune-kit `Markdown` renders GFM tables and tints ```` ```diff ```` fences.** Pipe tables + were flattened into run-on text before; they are now tables with a header row, alignment + and columns sized from their content (narrow tables wrap, then clip). `diff` and `patch` + fences tint `+`/`-` lines and dim `@@` headers instead of drawing a plain code block. + Documents with neither render exactly as before. New `MarkdownStyle` builders: `table`, + `table_min_column`, `diff`, `diff_hunk`. +- **rune-kit `Markdown` works without a `Kit`:** `Markdown::render(&MarkdownStyle)` with + `MarkdownStyle::neutral(dark)` or `MarkdownStyle::from_seed(seed)`. `build(&kit)` is unchanged. +- **rune-kit `Tooltip` works without a `Kit`:** `Tooltip::label(..).render(&TooltipStyle, + &mut layer)` with `TooltipStyle::{neutral, from_kit}` and its builders. `build(&kit)` is + unchanged. +- **`rune::text::measure(text, spans, style, max_width)`** returns a text's laid-out size outside + a frame, with the fonts the app loaded; `Some(0.0)` gives its min-content width. +- **Text in fonts with a `trak` table (the macOS system font) now has the same width at every + display scale, matching AppKit.** The font's size-specific tracking used to be looked up at + the size in device pixels, so at 2x 14 pt text was tracked as 28 pt text. It is now applied + at the point size, as Core Text does, within 0.003 pt per glyph of Core Text at 8–34 pt. At + 2x, system-font text gets narrower per glyph by 0.18 pt at 13 pt, 0.34 pt at 14 pt, 0.52 pt + at 16 pt and 0.63 pt at 17–20 pt (a 34-character 14 pt label is 11.6 pt narrower), and wider + by 0.19 pt at 11 pt and 0.36 pt at 8 pt; 12 pt and 24 pt barely move. Text at 1x moves by + at most 1/2048 em per glyph. Wrapped text can break at different words. Fonts without + `trak`, like the bundled Inter and IBM Plex Mono, are unchanged. `TextStyle::tracking` adds + to the font's tracking; `TextStyle::features("'trak' 0")` turns the font's tracking off. +- **Shortcut labels follow layouts that change under ⌘ (macOS).** `Shortcut::keycaps` (the + recorder, its error text and native menu key equivalents) now reads the key's character + under the chord's ⌘ and ⌃, so on "Dvorak – QWERTY ⌘" ⌘ plus the US-K key shows ⌘K, not ⌘T, + and menu items fire on the key they show. ⇧ and ⌥ still show the base key (⌥⌘K, not ⌥⌘˚), + as AppKit does. The key keycap is now a capital ("K", was "k"), F-keys read "F5", and on + macOS named keys use menu glyphs: ↩ ⇥ ⎋ ⌫ ⌦ ↖ ↘ ⇞ ⇟ (Space stays "Space"). `Keybind` + upper-cases only single characters, so "Space" no longer draws "SPACE". The layout lookup + also declares `UCKeyTranslate`'s string lengths at their real 8-byte width; it wrote past a + 4-byte stack slot on every call. +- **Native pop-up and context menus.** `tx.popup_menu(PopupMenu, anchor, on_pick)` opens an + `NSMenu` over an element key (a picker's selected item sits over the element, as SwiftUI's + menu-style `Picker` does) or at a `PointerPress`. `on_pick` gets the picked id after the menu + closes, or `None` on dismissal or when its window hides, closes or quits. Frames and updates + keep running while it's open. Other + platforms answer `None` on the next frame (`popup_menu_supported()` is false). New: + `PopupMenu`, `PopupItem`, `PopupAnchor`, `PopupMenuError`. Headless trees gain a `popupMenu` + object while one is open, and scripts gain `menu-pick` and `menu-cancel` events. Nothing + changes for apps that don't call it. +- **`El::matched(id)` adds shared-element motion** (SwiftUI `matchedGeometryEffect`, Motion + `layoutId`). When an element with an id leaves and another with that id mounts elsewhere in + the same commit, the new one springs from the old one's presented rect, radius, fill and + opacity to its own layout (`REFLOW` by default), painting above the window with its + children scaled to cover the moving frame. `rune_motion::Scene::match_geometry_offset` + starts a match from a rect offset outside the scene (a scroll). Apps that don't call + `matched` draw the same pixels. In `rune_motion::Scene`, screen travel + (`LayoutAnim::screen()`) now lands only once its ancestors' presence, scale, opacity and + blur settle too, so it can't jump onto a parent mid-transition. + `matched` draw the same pixels. +- **Elements can be dragged out to other apps (macOS).** `El::drag_out(|s| Some(DragItem))` + starts a system drag once the pointer passes `DRAG_THRESHOLD`, carrying file URLs, PNG data + or text to Finder, System Settings and other apps; `El::on_drag_end` reports a `DragOutcome`. + A drag-out element never runs `on_drag`, and once the system drag starts its press is + released without firing `on_press`. Elements without `drag_out` are unchanged, and other + platforms ignore it. Headless traces log `drag-out ` and `drag-end `, + and `--tree` marks the node `dragOut`. `ElementInfo` has a new pub `drag_out` field, so code + that builds it as a literal or destructures it without `..` needs updating. + `rune::{DragItem, DragImage, DragOutcome}` are new root exports, so a glob import of + `rune::*` can clash with an app type of the same name. +- **On macOS, the first `open()` of a window that doesn't exist yet now activates the app**, + like every later `open()`. Before, the new window became key while another app stayed + active, so typing and ⌘W went to that app. The window opened at launch and nonactivating + panels are unchanged. +- **`App::window` windows still open when the main window closes now run their `on_close`, + and `WindowSpec::from_app` starts from the app's `window_options`** (before, it used the + defaults, so headless runs dropped `transparent` and `physical_size`). +- **One app can host windows with different state types.** `App::window(WindowSpec)` adds + an ordinary window with its own state and returns its `AppHandle` and `WindowHandle`. + It honours `visible: false`, closes by hiding (its `on_close` runs and reopening keeps the + state), and never keeps the app running alone. `run_windows*` factories may return + `AnyWindowSpec`s (`WindowSpec::boxed()` or `.into()`) to mix state types. Factories + returning `Vec>` still compile, but a turbofish like `run_windows::(..)` + no longer does: drop it. Headless `--window KEY` and `--list-windows` include `App::window` + windows and render them with their own state. +- **Hit testing leaves out an element's right and bottom edges everywhere.** Press, hover, + secondary press, links, wheel targets and hover and press highlights now use the same + half-open test as pointer-move, `on_hover_change` and overlays (like `NSPointInRect` and + `PtInRect`). A pointer exactly on a shared edge belongs to the right or lower sibling + for every handler. A pointer exactly on a lone element's right or bottom edge no longer + hovers or presses it. +- **rune-kit `List` rows with an action are keyboard-reachable.** When any row has + `on_select`, the rows sit in a `listbox` focus group: Tab enters the list once (on the + selected row, if any), arrows move between rows, and Enter selects. Those rows show + their highlight on keyboard or pointer focus (`focus_highlight`) instead of on hover. Lists + without actions are unchanged. +- **A disabled, invalid rune-kit `TextInput` no longer has a red caret.** The caret now follows + the text colour, as `TextArea`'s does. Only that one state changes. +- **rune-light's `Scene` and `Gi` have an `emission` field.** `Scene::emission` (an optional + output-resolution texture) lets effect layers light the UI through the GI, scaled by + `Gi::emission`. Struct literals need `emission: None` and `..Default::default()`. GI media now use + sub-texel coverage, so a moving emitter no longer pops. New: `LightRenderer::inspect`, + per-cascade `Timings` and `GlassRenderer` (thick refracting glass). +- **rune-fx effects look different, and some structs gained fields.** Fire rises and narrows with + a white-yellow core and smoke, electricity strikes and re-strikes as fractal lightning, glows fall + off within about 2.5 radii, sparkles are a few crisp four-point stars, and one-shots (ripples, + pings, zaps, bursts) overlap instead of restarting. `FxLayer::opacity`, `ElectricParams::zap`, + `SparkleParams::burst` and `FireParams::smoke` are new pub fields, so struct literals without + `..Default::default()` need them. New: `OneShots`, `FxRenderer::blur_backdrop` (frosted glass) + and `FxRenderer::set_fire_sim`/`simulate` (an opt-in GPU fluid for fire and smoke). +- **Rotating icons turn their artwork, not just their outline.** An icon with + `.looping(LoopSpec::rotation(..))`, such as rune-kit's `Loader` arc, turned its quad but kept + sampling the atlas unturned, so the arc stayed put while the rotating square cropped it. The + artwork now turns with the quad and is bilinear-filtered while turned. Icons at rest + (angle 0) draw exactly as before. +- **Rune builds for Intel Macs.** `x86_64-apple-darwin` stopped compiling where Rune read + the Objective-C runtime's `BOOL`, which is `i8` there and `bool` on Apple silicon. +- **Overlay and launcher panels keep their view when something restyles winit's hidden + window.** On macOS an overlay or nonactivating launcher panel shows winit's view while + winit's own window stays hidden. That hidden window answered `contentView` with the moved + view, so AppKit calls on it that rebuild the frame (`setStyleMask:`, `setContentView:`) pulled + the view out of the panel, which then dropped every click. Starting a ScreenCaptureKit stream + in the same app does this: ReplayKit restyles the first window in `NSApp.windows`. Now only + winit gets the moved view; AppKit and other frameworks see the hidden window's real, empty + content. Likewise only winit's frame, level and mouse-ignoring calls on a launcher's hidden + window move its panel, so restyling that window no longer resizes the panel, and a title set + there also stays on the hidden window for `Window::title()`. If the view is taken anyway, + the panel puts it back on the next event-loop turn or event and releases an overlay press + it was holding, and an overlay press whose release never reached winit stops holding the + pointer after 2 s. The hidden window also keeps winit's class: Rune adds its forwards to winit's + window and view classes instead of subclassing each window, which under KVO had made + `-[window class]` return nil. +- **Borders can be dashed.** `El::border_dash(dash, gap)` dashes an element's `border` or + `border_gradient`, in points, with butt ends: + `el().radius(13.0).border(1.0, amber).border_dash(4.0, 3.0)`. Dashes follow the ring's + centre line round the corners. The pattern starts with a dash where the top edge leaves the + top-left corner and runs clockwise, and its period stretches or shrinks a little so a whole + number of dashes meets itself at that seam. `El::border_dash_phase(points)` shifts it, like + SwiftUI's `dashPhase`; a phase of `dash + gap` is one period. Border colours spring as before; + the phase is applied as given. The fill shows through the gaps, so a dashed element draws its + fill and its ring as two instances, the ring as the new `render::KIND_DASHED` (10), which + `rune-ref` renders too. Elements without dashes paint the same instances as before. + `Visual` has new `border_dash` and `border_dash_phase` fields. +- **Text can draw in capitals.** `El::text_case(TextCase::Uppercase)` (or `Lowercase`) draws + a text element's letters cased without changing its string, like SwiftUI's `textCase`: + `text("Text channels").text_case(TextCase::Uppercase)` draws "TEXT CHANNELS". Casing is + `str::to_uppercase`'s, so "ß" draws "SS". The dev tree, `ElementInfo::text`, link labels and + live text keep the authored string, and `Span` and `Link` ranges stay byte ranges of it even + when casing changes the length. Text fields ignore it and draw what is typed, so their caret + and selection are unchanged. `TextStyle` is unchanged. +- **Exiting elements are marked, and gone from lookups.** `ElementInfo` has a new `exiting` + field, true for an element playing its exit transition and for everything inside it. `--tree` + (and the hot host's tree) still lists them, now with `"exiting": true`; elements at rest add no + key, so existing tree goldens don't change. The dev panel's `tree` reply leaves them out, so a + check that something left passes as soon as it starts leaving; send + `{"type":"tree","exiting":true}` to keep them, marked. `Runtime::find`, which `--script` key + positions and the hot host's `tap` use, already skipped an exiting element and now also skips + its children; a script that tapped a child of a leaving element by key now stops with "no + element with key". `Runtime::presented` still reads exiting elements. +- **Dev-panel transitions can capture data.** `dev::Config::transition` now takes any + `impl Fn(&mut S, &mut Tx) + 'static`, so a transition can close over a scene's fixture: + `.transition("Open", "list", move |s, tx| s.open(&room, tx))`. `dev::Transition::with` builds + one for `Config::transitions`. `Transition::new` still takes a plain `fn`, so + `let t = Transition::::new;` lists keep building, but it is no longer `const`, `Transition` + is `Clone` rather than `Copy`, and its `action` field is private. +- **Held keys activate once, as in AppKit.** Auto-repeats no longer press a focused button, + menu item, row or link (Return, Space), open a popup button (arrows), dismiss another modal + (Escape), blur a field (Escape) or submit it (Return). Rune consumes those repeats. After a held + Return, Escape or Space moves focus, its later repeats reach nothing: not the app's `on_key`, + the control that took focus or its physical input handler. Other held keys keep repeating. A + rune-kit `Combobox` chooses once on a held Return and closes once on a held Escape. On X11, a + held global shortcut fires once, as on macOS and Windows. Typing, deletion, caret movement, + arrows in lists and menus, and Tab still repeat. To act on every repeat, handle the key in `on_key` and + check `tx.key_repeat()`. +- **`--script` events at t = 0 see the first layout.** A script whose first events are at + t = 0 (or omit `t`) now lays out a first frame, with the initial state and queued updates, + before running them. `{"t": 0, "type": "click", "key": "..."}` used to fail with "no element + with key", and t = 0 clicks or moves at x/y hit nothing. Frame 0 then draws the events' + effects, so changes they start animate from the mounted state rather than mounting settled. + Scripts without t = 0 events are unchanged. +- **`ConfiguredOverlay::setup(fn(&mut T, Waker))`**, like `AppSpec::setup`, so an overlay can + build its own `ImageCache` or channel instead of borrowing the main window's waker. It runs + once on the event thread when the loop starts, before the overlay's first frame and before + updates queued on its handle. A wake re-runs the overlay's view: a shown overlay draws a + frame, which polls, and a hidden one runs a frame without drawing. Headless runs don't + create overlays, so they don't call it. +- **`Cursor::Crosshair` and `Cursor::Hidden`.** A crosshair for picking a point or dragging out + a rect, and no OS cursor for views that draw their own. Windows set them, and overlays now + set an element's `Cursor` too (before, they left the OS cursor alone) while the pointer is + over a hit area of a shown overlay that takes input, including a non-key macOS overlay. + `Hidden` is a transparent cursor image, so it is per-window like any shape and never confines + the pointer. It shows the arrow again when hover leaves the element, the pointer leaves the + window (including a drag released outside it), the element is removed, the window loses focus + or hides, or the overlay hides. The cursor now comes from what's under the pointer in the + current frame, so an element playing its exit transition has no cursor and a sibling that + replaces it under a still pointer sets its own. On macOS a non-key overlay sets its cursor + only while its app is frontmost; the opt-in `macos-background-cursor` feature lifts that with + a private WindowServer property (an App Store review risk), and without it none of that code + is in the binary. `Cursor` is now `#[non_exhaustive]`: an app that matches it needs a + wildcard arm. +- **Key handlers can tell a held key's repeats from its first press.** `tx.key_repeat()` is true + in the window's `on_key`, an overlay's `.on_key`, `on_input_key` and `on_physical_input` while + the OS auto-repeats a held key, and false for the first press. `KeyEvent` is unchanged, so + existing literals keep building. Headless drivers queue a repeat with `Runtime::repeat_key`, + and `--script` keys and `physical` chords take `"repeat": true`. Built-in behaviour is + unchanged: held keys still type, move the caret, Tab through focus and press a focused button. +- **Unselected segments hover.** A `SegmentedControl` with `on_pick` now lights an unselected + segment under the pointer: the `hover` overlay fills it and its label turns `text_base`, on the + first frame in, fading out over the runtime's default 0.1 s. The selected segment and controls + without `on_pick` are unchanged. A forced `State::Hover` on an unselected segment now also + fills it, so snapshots match. +- **Native traces record when frames reach the screen.** On macOS, `--native --trace` frames + now add `target_ms` (the display link's target) and `present_ms` (Metal's `presentedTime` + for the frame's drawable), plus `present_dt_ms`, the gap from the previous presented frame + when the two were drawn back to back. A skipped drawable writes `present_ms: null`. Each line + is written once its present time arrives, so frames land in the file two or three frames + late, still in order. When the trace ends it prints a summary to stderr: present-interval + p50/p95/max, intervals under 2 ms (bunched) and over 1.5 refresh periods (missed), and the + target-to-present lag. Every other field is unchanged, and readers that ignore unknown keys + read the new traces as before. Overlays, other platforms and headless traces add no present + fields, and nothing changes without `--trace`. +- **A late frame no longer slows motion down.** Windows, overlays and the hot and dev hosts now + share one frame-step rule (`frame_clock`). Motion already running advances by the real time + since the last frame, up to 250 ms, instead of 1/30 s at most. Before, a host marked idle + mid-motion stepped only 1/120 s, so after a hitch springs fell behind and finished late. Motion + a frame starts or retargets starts at that frame's time and steps at most 1/120 s, so it no + longer jumps by a late frame's gap, and a retargeted spring turns from where it is at that + time. Both happen in one runtime pass, so poll, the motion trace and the settle flag see one + frame. While other motion runs, a 60 Hz frame now starts new motion with a 1/120 s step rather + than 1/60 s. The hot host's first frame after idle no longer steps new motion by the idle gap. + Scroll flings now integrate their decay exactly, so a fling travels about 1% less in total and + a long frame carries the same distance as the short frames it stands for. +- **Focus follows an app selection.** In a `focus_follows` group, when the app selects a + different item (a ⌘-digit shortcut, say) while focus is in the group, focus moves to the + `focus_selected` item and keeps its keyboard ring, instead of staying on the old row. +- **List arrows stop at the ends.** Up on the first row and Down on the last row of a + `list`, `tree` or `grid` focus group now stay put, like NSTableView, instead of wrapping. + Menus, select popups (`listbox`) and segmented or radio groups still wrap. +- **ShortcutRecorder can retry an unchanged chord.** `ShortcutRecorderState::mark_unregistered()` + says the shown shortcut isn't registered (its launch registration failed, say). Recording + the same chord then goes through `on_change` again instead of being a no-op, until a change + succeeds. Without the call, behavior is unchanged. +- **Global shortcuts need a modifier.** `App::global_shortcut`, `register_shortcut` and + ShortcutRecorder refuse a chord without ⌘, ⌃ or ⌥ (Ctrl, Alt or Super elsewhere), such as + Space, Enter or ⇧A, which would take the key from typing in every app. F1–F24 still work + alone. Registration returns `InvalidAccelerator("space needs ⌘, ⌃ or ⌥")`, and the recorder + shows the refused chord with "Add ⌘, ⌃ or ⌥." without calling `on_change`. Opt out with + `App::allow_unmodified_shortcuts()` and `ShortcutRecorder::allow_unmodified()`. + `Shortcut::require_modifier()` checks a chord. Apps that bound a bare key now get an error. +- **A window's first updates can register on a later window.** `run_windows` now builds every + window's host before any of them opens and drains its queued updates, so an update queued on + the first window that calls `register_shortcut` or `set_menu` on the second gets `Ok` instead + of `NotRunning`. Each window's state initializer and startup shortcuts now run before the + first window opens; windows still open in order. +- **Incremental release builds; benchmarks move to `--profile perf`**. This repo's + `[profile.release]` is now incremental, so a one-line edit in `rune` rebuilds an example in + about 1.5 s instead of about 23 s. The new `perf` profile keeps the old release codegen + (opt-level 3, 16 codegen units, no LTO, not incremental), and `cargo bench` stays + non-incremental. The runtime benches (`bench-ui`, `bench-startup`, `bench-live`, + `bench-gpu-springs`, `text-bench`, `native-pacing`) time only `target/perf/` binaries and exit + with an error on anything else. Tests in the docs now run in debug. Apps that depend on Rune + use their own profiles and are unaffected. +- **`El::border_gradient(width, top, bottom)`**. A border whose colour runs from `top` at the + element's top edge to `bottom` at its bottom edge, such as a top-lit hairline rim on a capsule. + It has `border`'s corners, coverage and antialiasing, and like `border` it doesn't affect layout. + Whichever of the two is called last wins, and both stops spring like `border`'s colour. Kind 4 + instances (`KIND_GRADIENT`) with a nonzero `params.x` now draw a filled rect with a gradient + ring (`border` at the top, `uv` at the bottom) and honour `params.z` softness. Rune only emits + them for this border, but hand-built kind 4 instances that left a border width in `params.x` + now draw a ring. `rune-ref` matches and its canonical hashes change. +- **macOS Quit runs `on_close`.** The app menu's Quit, Cmd-Q, the Dock's Quit and logout now + run `on_close` once, and flush clipboard clears, before the process ends, as the close button + does. A window already hidden under `keep_running` has closed, so its hook doesn't run again. + `AppHandle::quit` and `Tx::quit` still skip it. +- **Headless `{"physical": "alt+super+space"}` releases its modifiers.** After the key's down + and up, the script now sends the modifiers coming up, as a keyboard does, so a recorder no + longer shows ⌥⌘ held in later stills. Scripts whose stills showed held modifiers change. +- **ShortcutRecorder shows the refused chord and lets the app word the error.** After + `on_change` refuses a chord, the keycaps keep showing it (not just the held modifiers) until + another modifier starts the next chord, which also clears the error. The message under it + defaults to sentence case naming the chord ("⌃J is already in use.") instead of the + `ShortcutError` Display text; `.error_message(|error, chord| ...)` replaces it, with + `rune_kit::shortcut_error_message` as the fallback, and `ShortcutRecorderState::refused()` + reads the chord. Recorder text changes; no goldens show it. +- **`AppHandle::shortcut_owner(&Shortcut)`** names who holds a chord after a + `ShortcutError::Conflict`, when Rune or the desktop knows: this App or another Rune App in + the process (its title), or on macOS an enabled system shortcut ("Spotlight", "Mission + Control", or "macOS" for unnamed ones), named at the user's remapped chord. None otherwise, + and headless runs never ask the desktop. `Conflict` is still a unit variant. Registering a + chord another Rune App in the process holds now returns `Conflict` on every backend, the + portal included. No output change. +- **Keyboard focus scrolls into view.** Tab, Shift-Tab, arrows, Home, End and type-select + reveal the control they reach inside its scroll view, as `Tx::scroll_into_view` does, so + focus never moves off-screen. +- **Overlay drags report screen travel.** When an overlay moves its own window (`place`, + `set_placement`, `set_align`) during a drag, `Drag::dx`/`dy` keep measuring pointer travel + instead of travel relative to the moving window, so a dragged capsule follows the pointer + without feeding back. New `El::on_hover_change` reports entering and leaving an element's + rect, children included, without taking their presses or hover; a held press stays inside. +- **Mac keyboard navigation for menus, selects and lists**. Groups with role `menu`, `listbox`, + `list` or `tree` move with Up and Down only (Left and Right no longer move them), and those + plus `tablist` jump to the item whose label you type. `El::focus_highlight(color)` gives a + row one highlight for pointer and keys, as in `NSMenu`: hovering focuses the row (never + taking focus from a text field) and the first arrow reveals the current or checked item. + `El::focus_follows()` makes a group press each item it moves to (a source list). A + non-input `combobox` opens on Up and Down. rune-kit `Menu` and `Select` items use the shared + highlight, and with `on_close` an open menu or select traps focus, closes on Escape and + returns focus to its trigger. Text fields take macOS's Control bindings (Ctrl-A, E, B, F, P, + N, D, H, K). On macOS, with Keyboard navigation off in System Settings, Tab visits only text + fields and lists, as in AppKit; `Runtime::set_full_keyboard_access` overrides it. +- **Hover lands at once.** A `.hover(color)` overlay (and a hover group's `group_opacity`) used + to spring in, so a highlight trailed the pointer. Without `.hover_motion`, hover now appears on + the first frame under the pointer and fades out over 0.1 s, like a native sidebar or menu. + `.hover_motion(enter, exit)` still sets both curves. +- **App icons on Windows and Linux; aspect-fit images**. `ImageCache::app_icon` now rasterizes + an executable's or `.ico`'s icon on Windows and a `.desktop` entry's hicolor or `pixmaps` + icon (PNG or SVG) on Linux, where it used to resolve to an error, so apps that fell back on + error now draw the icon. `El::pixels_fit(&pixels, SurfaceFit::Fit | Fill)` keeps an image's + aspect ratio; `El::pixels` still stretches, unchanged. +- **Indeterminate `Progress` animates.** `Progress::new(None)` used to draw an empty track; it + now sweeps a quarter-width segment across it every 1.4 s, centred and still under Reduce + Motion. The sweep is `LoopSpec::slide(period, from, to)`, a new looping offset in fractions of + the node's own size that descendants and hit tests follow. Like other loops it draws no frames + while hidden, scrolled away or reduced, including when the segment is outside its clip. +- **`--script` taps links by id**. A script event's `"key"` (and + `Runtime::find`) falls back to the link whose id matches when no element has that key, so + `{"type":"tap","key":"https://x.dev"}` presses an `El::link` or Markdown link, aiming at its + first line box. Before, the run stopped with "no element with key". +- **Late children of virtual rows play their entrance**. A child added + to a row of a `.virtualize(..)` stack after the row first appeared (a "Copied" chip, say) now + fades in with its transition, as it would in a plain stack, instead of popping in. Rows + scrolled back into view still mount settled with their whole subtree. +- **Timers drive motion in windowless dev runs**. With the dev panel + attached and no visible window, a timer that starts a transition now animates it in real time + on hidden ticks, as a shown window would. Before, the timer's frame left the motion frozen + until the next input or panel command. +- **Stuck scrolls hold their bottom across fitting and overflowing**. + When a stick-to-bottom scroll's content goes between overflowing its viewport and fitting it + while the viewport resizes, the rows no longer jump by the size change and slide back. + Bottom-aligned rows (`justify_end` in a filling stack) stay on the bottom edge every frame; + top-aligned rows glide between the bottom and the top. A row added to a bottom-aligned stack + that fits now pushes the rows above it up as it grows, where they used to jump up first. + Settled frames and `--snap` goldens are unchanged. +- **Linux portal shortcuts use zbus 6.** zbus 5's zvariant, zbus_names and zvariant_derive are + flagged unmaintained (RUSTSEC-2026-0370, -0371, -0372) and no longer appear in Rune's default + dependency graph. Linux builds need Rust 1.89 or newer. The opt-in `native-file-dialog` feature + still reaches zbus 5 through `rfd`'s `ashpd`, which has no zbus 6 release yet. +- **Steady 60 Hz in Low Power Mode on ProMotion Macs.** Low Power Mode caps the built-in panel + at 60 Hz while macOS still reports 120 Hz, so Rune drew a few fast frames after each change + before settling. Windows and overlays on the built-in display now pace at 60 Hz in Low Power + Mode, with no fast start and about half the input-to-screen latency. `--trace` headers report + 60 Hz there. +- **`LayerSpec` literals need filter fields**. The public `blur` and + `clip_radius` fields break external `LayerSpec { opacity, blend }` literals. Add + `..Default::default()` for their previous unfiltered, rectangular behavior. +- **Rounded subtree clips and dormant dissolves**. `clip_rounded(radius)` + clips ordinary paint directly and isolated output after filtering, preserving blur from sources + beyond the clip. `dissolve()` skips isolation at opacity endpoints, where overlapping opaque + children now use source-over; it activates additive isolation during fades, including sequences. +- **Blur filters the whole subtree**. `blur`, `live_blur`, `blur_motion` + and presence blur now soften text, images and video together. `Transition::blur_replace()` peaks + at Gaussian sigma 1.5 pt instead of the old shape-only 4 pt coverage radius; its scale and timing + stay the same. The packed instance remains 128 bytes, with clip radius in attribute 7 `fade[3]`. +- **Opt-in guarded Rust view editing**. `scripts/rune-dev` patches + Settings and fixture-only OpenCode views while retaining state, scroll and springs. + Declaration, signature and other build-input changes require a restart. `rune/hot` + is off by default; measured edit-to-pixels latency remains above the one-second target. +- **`SecretCopy::pending()`** makes a copy that is never written and stays `Pending`, so a + scene can show a copy in flight without building a `Tx`. No output change. +- **`NativeSurface::set_mirrored(bool)`** flips video horizontally at draw time, for + front-camera previews. It is off by default, so existing output doesn't change. +- **Exiting password fields drop their secret.** When a secure text input starts its exit + animation, its copy of the text is wiped and replaced by its mask, so it paints the same dots + (no placeholder, no caret) through the exit without holding the password. +- **`Tx::copy_secret` returns a `SecretCopy` handle.** `state()` / `holds()` tell whether the + copy is still the last thing Rune wrote and the clipboard hasn't changed (the worker watches + the change count while a secret is held), whether a write failed, and whether it was cleared or + replaced; `clear_now()` clears it early. `Tx::clear_secret_clipboard()` clears the latest + secret from any window. Tests can share `rune::clipboard::memory()` between runtimes with + `Runtime::use_clipboard`. The worker now keeps a keyed fingerprint of the secret, not its text. +- **Command chords don't type, and single-line fields stay on one line.** Text typed with Cmd + (macOS) or Ctrl held, such as Shift-Cmd-Space, no longer inserts into any field; it goes on to + the app's `on_key` instead. Ctrl+Alt (AltGr) still types on Windows and Linux, and Option still + types on macOS. Secure and `single_line()` fields drop control characters from typing, paste and + IME commits: pasted line breaks and tabs are stripped, like ``, and + Shift/Option-Enter submits instead of inserting a newline. Multi-line fields are unchanged. +- **RollingText sets like one text.** Each rolling glyph sits at its advance in the whole label + shaped once, with kerning and contextual forms, where each used to round up to a device pixel + on its own. Rolled labels get narrower and tighter (IBM Plex Mono 11 pt "Copy password": 91 → + 86 pt) and at rest draw the same glyphs at the same positions as the plain string. New + `El::advance_in(run, at)` measures and draws a text as its grapheme in a longer run. +- **Stuck scrolls hold their bottom while they resize**. A stick-to-bottom + scroll whose own height animates (a banner opening above it, a footer below) now keeps its last + row on its bottom edge every frame. Before, the rows jumped by the size change and slid back. + Settled frames and `--snap` goldens are unchanged. +- **Editing scrolls the caret into view**. Typing, pasting, IME composition + or caret keys in a field inside a scroll viewport now scroll its nearest viewport just far enough + to show the caret line, as a browser textarea does. Before, the caret could run off the bottom. +- **Growth rows play an explicit `.transition`**. Rows inserted into a + growth stack (and elements inserted inside them) used to ignore `.transition(...)` and only grow + open. One that sets a transition now also plays its entrance; rows without one are unchanged, + and rows a virtual list remounts on scroll still appear settled. +- **Absolute children size against their parent**. `absolute`/`pin` children + now resolve `w_full`, `w_frac`, `h_full` and right/bottom pins against their parent's padding + box, as documented, instead of the window (Taffy hands them to the nearest positioned ancestor, + and elements were static). Left/top offsets were already parent-relative. Root overlays (scrims, + dialogs, toasts, anchored popovers) are unchanged; nested ones move, e.g. rune-kit `List::divider` + now spans its row. +- **Accessory apps get an app menu when showing their Dock icon.** On macOS, + `set_dock_icon(true)` installs About, Services, Hide and Quit when no main menu exists, + preserving app-supplied menus and composing with Rune's custom menu items. +- **Headless runs resolve `place()`.** A `--script` object can declare `"displays"` and a + `"pointer"`; `AppHandle::place` resolves against them (one 1920x1080-pixel display by + default), prints a `rune-placed` line and adds `"placed"` to `--tree`. A script object + without `"events"` now means no events instead of an error. +- **Launcher panels never reveal stale pixels.** A launcher shown in the same turn as an + `update()` renders one fenced hidden frame before its reveal, where it used to show the + cached pre-update frame for a frame. The update's motion is not settled; it runs on after + the reveal. Reveals with unchanged state keep the cached fast path. +- **Launcher panels run `poll` on a plain wake.** `AppHandle::wake()` and the setup `Waker` + used to skip a launcher's `poll` unless an update came with them. A shown launcher now + redraws; a hidden one polls and renders its cached frame at alpha zero when `poll` reports + a change, with no frame loop. +- **Linux builds link `libxkbcommon`** (`a7f0f56`). Display-targeted overlays added the `xkbcommon` + crate, so CI and build hosts without `libxkbcommon-dev` (Fedora: `libxkbcommon-devel`) fail at + link time. See "Linux system packages" in `crates/rune/README.md`. +- **`.truncate_fade()` fades 1.5 em instead of 1 em**. + Overflowing labels fade over a wider edge; labels that fit don't change. New + `.truncate_fade_width(em)` sets another width. +- **Emoji with `U+FE0F` draw in colour.** `❤️`, `☀️`, `✔️` and other characters a text font also + has use the colour emoji font when the emoji selector follows them; without it they keep their + text form, as before. +- **The caret and backspace step over whole graphemes.** Arrows, Shift-arrows and Backspace treat + a ZWJ family, a flag or a skin-toned hand as one character instead of splitting its code points. +- **Inline code chips draw as one rect.** Touching span backgrounds on a line merge even when + their runs have different fonts or sizes, at the height of the widest run. Markdown's padding + spaces no longer draw lighter slivers at each end of a code chip. +- **Italics.** `TextStyle::italic()` and `Span::italic` pick the family's italic face (SF's on + macOS) or lean the upright face 12° when it has none (bundled Inter). rune-kit `Markdown` draws + `*emphasis*` in italic, so its emphasis runs change pixels; advances don't move. +- **Math alphanumerics and non-Latin scripts render instead of tofu.** Math alphanumerics and + symbol blocks, plus Hebrew, Arabic, Devanagari, Bengali and Thai, load system fonts the first + time a text uses them. Text that used these characters changes pixels and advances; Latin-only + text and the existing goldens don't move. New `El::justify()` spreads wrapped lines to the + width, from the right in right-to-left text; `Align` behaves as before. +- **Colour emoji** (#7). Emoji fall back to the system's colour emoji font (Apple Color Emoji, + Segoe UI Emoji, Noto Color Emoji) and draw as colour images from the image atlas, where they + used to draw as blank gaps. Text without emoji renders as before. + +- **Prewarmed overlay reveals preserve elapsed motion.** A hidden commit keeps its animation + timing when `show()` arrives in the same poll or a later turn: a recent transition reveals + in flight, an old one at rest. Content, geometry and live values refresh before reveal; + hidden motion does not drive a frame loop. Initial preparation and ordinary overlay shows + still settle their first frame. +- **rune-kit menus open instantly**. `Menu`, + `context_menu`, submenus and `Select`'s list now appear fully on the next frame instead of fading + and scaling in from 0.96, and close with a plain `.25 / 0` fade (no scale). Menu item highlights + land the frame the pointer arrives and leave over 100 ms ease-out. No `--snap` goldens move: + they capture frame 0, where overlays already mount without an entrance. +- **Wrapped centred and end-aligned text aligns each line** (#6). A wrapping `Align::Center`/`End` + text now centres (or right-aligns) every line inside its wrap width, instead of moving the whole + block as one left-aligned paragraph. `--snap` goldens with multi-line centred text move. +- **Single-line text fields** (#6). `El::single_line()` keeps a text input on one line: it scrolls + sideways to keep the caret visible, clips to the field, and rests at the start when unfocused. + rune-kit `TextInput` (except `multiline`) and `List` search opt in; core `text_input` is unchanged. +- **Scroll views clip their content** (`3333f37`). `El::scroll` now clips its children to its box with a + hard edge, so overflowing content no longer draws, or takes presses, outside it. An explicit + `clip_soft`/`clip_fade` still sets the edge. No `--snap` goldens move. +- **Optical sizing on by default** (`2eae09d`, from `edc9892`). Text with an `opsz` axis now uses each + run's point size, as AppKit does: system SF at 13 pt renders as SF Text, so labels are slightly + wider. Layout is otherwise unchanged, but `--snap` goldens with SF text move (Scrawl: all 7, PAE + ~0.85). Opt out per style with `.optical_sizing(OpticalSize::FontDefault)`. Fonts without `opsz` + are unaffected. +- **Presses inside scrolled views land** (`b3c7bdb`, #5). A captured press is released against + where the element was drawn (after scrolling), not its unscrolled layout rect, so `on_press` now + fires for rows scrolled into view. diff --git a/app/vendor/rune/CLAUDE.md b/app/vendor/rune/CLAUDE.md new file mode 100644 index 0000000..43c994c --- /dev/null +++ b/app/vendor/rune/CLAUDE.md @@ -0,0 +1 @@ +@AGENTS.md diff --git a/app/vendor/rune/Cargo.lock b/app/vendor/rune/Cargo.lock new file mode 100644 index 0000000..acffc29 --- /dev/null +++ b/app/vendor/rune/Cargo.lock @@ -0,0 +1,6406 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "ab_glyph" +version = "0.2.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "01c0457472c38ea5bd1c3b5ada5e368271cb550be7a4ca4a0b4634e9913f6cc2" +dependencies = [ + "ab_glyph_rasterizer", + "owned_ttf_parser", +] + +[[package]] +name = "ab_glyph_rasterizer" +version = "0.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "366ffbaa4442f4684d91e2cd7c5ea7c4ed8add41959a31447066e279e432b618" + +[[package]] +name = "accesskit" +version = "0.25.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e883d1d28c5fd5568c79ed2d2bd48d9f2fd3945c8974ed0f53690ceddb051be" +dependencies = [ + "uuid", +] + +[[package]] +name = "accesskit_atspi_common" +version = "0.21.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24f5baf62e34a4a6c30e3d697e4782f821a7337049c44c3b40576a27dfbb580d" +dependencies = [ + "accesskit", + "accesskit_consumer", + "atspi-common", + "phf", + "serde", + "zvariant", +] + +[[package]] +name = "accesskit_consumer" +version = "0.39.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f3da8f27636015191b2264ee1df681503170a632cafd832fdc1edfdd4e3a2fd3" +dependencies = [ + "accesskit", + "hashbrown 0.17.1", +] + +[[package]] +name = "accesskit_macos" +version = "0.27.2" +dependencies = [ + "accesskit", + "accesskit_consumer", + "hashbrown 0.17.1", + "objc2 0.5.3", + "objc2-app-kit 0.2.2", + "objc2-foundation 0.2.2", +] + +[[package]] +name = "accesskit_unix" +version = "0.24.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "30d5192871228c54f1b0fb4a85cef000e11a3804f25d2165f14afa0daa67f3f6" +dependencies = [ + "accesskit", + "accesskit_atspi_common", + "async-channel", + "async-executor", + "async-task", + "atspi", + "futures-lite", + "futures-util", + "serde", + "zbus", +] + +[[package]] +name = "accesskit_windows" +version = "0.35.2" +dependencies = [ + "accesskit", + "accesskit_consumer", + "hashbrown 0.17.1", + "static_assertions", + "windows", + "windows-core", +] + +[[package]] +name = "adler2" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" + +[[package]] +name = "ahash" +version = "0.8.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a15f179cd60c4584b8a8c596927aadc462e27f2ca70c04e0071964a73ba7a75" +dependencies = [ + "cfg-if", + "getrandom 0.3.4", + "once_cell", + "version_check", + "zerocopy 0.8.63", +] + +[[package]] +name = "allocator-api2" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923" + +[[package]] +name = "android-activity" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0f2a1bb052857d5dd49572219344a7332b31b76405648eabac5bc68978251bcd" +dependencies = [ + "android-properties", + "bitflags 2.13.2", + "cc", + "jni", + "libc", + "log", + "ndk", + "ndk-context", + "ndk-sys", + "num_enum", + "thiserror 2.0.21", +] + +[[package]] +name = "android-properties" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc7eb209b1518d6bb87b283c20095f5228ecda460da70b44f0802523dea6da04" + +[[package]] +name = "android_system_properties" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae221649c9976a6f6c56ae1facf410f3ddb33cc661c4b7b61020a912d4237fbc" +dependencies = [ + "libc", +] + +[[package]] +name = "anyhow" +version = "1.0.104" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" + +[[package]] +name = "ar_archive_writer" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "523e5e187fff36fcb8d1d19ccf0ca4ca43ec3d158316057f66dc6f72716bc5ec" +dependencies = [ + "object", +] + +[[package]] +name = "arboard" +version = "3.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aeb9553e62312c8756a5979254fc6d7da8bbeb5986a1e17037fab932f7037917" +dependencies = [ + "clipboard-win", + "image", + "log", + "objc2 0.6.5", + "objc2-app-kit 0.3.2", + "objc2-core-foundation", + "objc2-core-graphics", + "objc2-foundation 0.3.2", + "parking_lot", + "percent-encoding", + "windows-sys 0.61.2", + "wl-clipboard-rs", + "x11rb", +] + +[[package]] +name = "arrayref" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "76a2e8124351fda1ef8aaaa3bbd7ebbcb486bbcd4225aca0aa0d84bb2db8fecb" + +[[package]] +name = "arrayvec" +version = "0.7.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3fb67a6e08acf24fdeccbac2cb6ac4305825bd1f117462e0e6f2f193345ad56" + +[[package]] +name = "as-raw-xcb-connection" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "175571dd1d178ced59193a6fc02dde1b972eb0bc56c892cde9beeceac5bf0f6b" + +[[package]] +name = "ash" +version = "0.38.0+1.3.281" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bb44936d800fea8f016d7f2311c6a4f97aebd5dc86f09906139ec848cf3a46f" +dependencies = [ + "libloading", +] + +[[package]] +name = "assert_matches" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b34d609dfbaf33d6889b2b7106d3ca345eacad44200913df5ba02bfd31d2ba9" + +[[package]] +name = "async-broadcast" +version = "0.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "435a87a52755b8f27fcf321ac4f04b2802e337c8c4872923137471ec39c37532" +dependencies = [ + "event-listener", + "event-listener-strategy", + "futures-core", + "pin-project-lite", +] + +[[package]] +name = "async-channel" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "924ed96dd52d1b75e9c1a3e6275715fd320f5f9439fb5a4a11fa51f4221158d2" +dependencies = [ + "concurrent-queue", + "event-listener-strategy", + "futures-core", + "pin-project-lite", +] + +[[package]] +name = "async-executor" +version = "1.14.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f426a31126c735126297bc5ea7a521263c9faff4f63ca415267ee625651c4f37" +dependencies = [ + "async-task", + "concurrent-queue", + "fastrand", + "futures-lite", + "pin-project-lite", + "slab", +] + +[[package]] +name = "async-io" +version = "2.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "456b8a8feb6f42d237746d4b3e9a178494627745c3c56c6ea55d92ba50d026fc" +dependencies = [ + "autocfg", + "cfg-if", + "concurrent-queue", + "futures-io", + "futures-lite", + "parking", + "polling", + "rustix 1.1.5", + "slab", + "windows-sys 0.61.2", +] + +[[package]] +name = "async-lock" +version = "3.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0876700b0d007ad25d5508865a4259c3af9af6d296bf663a0d586d0bc3369f6f" +dependencies = [ + "event-listener", + "event-listener-strategy", + "pin-project-lite", +] + +[[package]] +name = "async-process" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc50921ec0055cdd8a16de48773bfeec5c972598674347252c0399676be7da75" +dependencies = [ + "async-channel", + "async-io", + "async-lock", + "async-signal", + "async-task", + "blocking", + "cfg-if", + "event-listener", + "futures-lite", + "rustix 1.1.5", +] + +[[package]] +name = "async-recursion" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4f8abc12baad266b1c8cec146854c195b5864b4221d4b2ca7296a7ae82d9e451" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "async-signal" +version = "0.2.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52b5aaafa020cf5053a01f2a60e8ff5dccf550f0f77ec54a4e47285ac2bab485" +dependencies = [ + "async-io", + "async-lock", + "atomic-waker", + "cfg-if", + "futures-core", + "futures-io", + "rustix 1.1.5", + "signal-hook-registry", + "slab", + "windows-sys 0.61.2", +] + +[[package]] +name = "async-task" +version = "4.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b75356056920673b02621b35afd0f7dda9306d03c79a30f5c56c44cf256e3de" + +[[package]] +name = "async-trait" +version = "0.1.92" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "82f6aeea286b8eb4dd3431a1be1b59d290ace00f5bfd8e2a159bc2a05e2c1667" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "atomic-waker" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" + +[[package]] +name = "atomig" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd0f41f4bb89f5c6450325e283fb78c4a3d042181b54f3855ee2f872919f9863" +dependencies = [ + "atomig-macro", +] + +[[package]] +name = "atomig-macro" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "49c98dba06b920588de7d63f6acc23f1e6a9fade5fd6198e564506334fb5a4f5" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "atspi" +version = "0.29.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c77886257be21c9cd89a4ae7e64860c6f0eefca799bb79127913052bd0eefb3d" +dependencies = [ + "atspi-common", + "atspi-proxies", +] + +[[package]] +name = "atspi-common" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20c5617155740c98003016429ad13fe43ce7a77b007479350a9f8bf95a29f63d" +dependencies = [ + "enumflags2", + "serde", + "static_assertions", + "zbus", + "zbus-lockstep", + "zbus-lockstep-macros", + "zbus_names", + "zvariant", +] + +[[package]] +name = "atspi-proxies" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2230e48787ed3eb4088996eab66a32ca20c0b67bbd4fd6cdfe79f04f1f04c9fc" +dependencies = [ + "atspi-common", + "serde", + "zbus", +] + +[[package]] +name = "autocfg" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" + +[[package]] +name = "avif-decode" +version = "3.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1eee11893966d77d3e18c66fdcfb1c30e2d8df050346609c775ce8eec3390344" +dependencies = [ + "avif-parse", + "bytemuck", + "imgref", + "lodepng", + "log", + "quick-error 2.0.1", + "rav1d", + "rgb", + "yuv", +] + +[[package]] +name = "avif-parse" +version = "2.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "048e72663e14be27bfd8a9e01e8a0bf27610511ffd5f74c7955f4e4847ce2530" +dependencies = [ + "arrayvec", + "bitreader", + "byteorder", + "fallible_collections", + "leb128", + "log", +] + +[[package]] +name = "background" +version = "0.0.1" +dependencies = [ + "rune", +] + +[[package]] +name = "base64" +version = "0.22.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" + +[[package]] +name = "bincode-next" +version = "3.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d6626829353ae29293be5c86f42de5f0468bc758af074b0c7d08f07e538ccbc" +dependencies = [ + "pastey", + "rapidhash", + "serde", + "unty-next", +] + +[[package]] +name = "bit-set" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2f926cc3060f09db9ebc5b52823d85268d24bb917e472c0c4bea35780a7d" +dependencies = [ + "bit-vec 0.9.1", +] + +[[package]] +name = "bit-set" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "56d87354e4229f54a44f7bf2435906a4656dba36026ab6eaca629a2c436a691c" +dependencies = [ + "bit-vec 0.10.1", +] + +[[package]] +name = "bit-vec" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b71798fca2c1fe1086445a7258a4bc81e6e49dcd24c8d0dd9a1e57395b603f51" + +[[package]] +name = "bit-vec" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5727b15fa97d4f4fee0a3b7c3d550ed0269f54329207b86388de918604e31269" +dependencies = [ + "borsh", + "serde", +] + +[[package]] +name = "bitflags" +version = "1.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" + +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" + +[[package]] +name = "bitreader" +version = "0.3.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "886559b1e163d56c765bc3a985febb4eee8009f625244511d8ee3c432e08c066" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "blake3" +version = "1.8.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6d9e454fc11f76977dc803893aff6304ed33d6a26efae8696573bea74baa27ae" +dependencies = [ + "arrayvec", + "cc", + "cfg-if", + "constant_time_eq", + "cpufeatures 0.3.1", +] + +[[package]] +name = "block-buffer" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" +dependencies = [ + "generic-array", +] + +[[package]] +name = "block2" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2c132eebf10f5cad5289222520a4a058514204aed6d791f1cf4fe8088b82d15f" +dependencies = [ + "objc2 0.5.3", +] + +[[package]] +name = "block2" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cdeb9d870516001442e364c5220d3574d2da8dc765554b4a617230d33fa58ef5" +dependencies = [ + "objc2 0.6.5", +] + +[[package]] +name = "blocking" +version = "1.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a70e4329df6cb94385eed412ec92375c3cdd8a6e502493d1229b6414e4036dfa" +dependencies = [ + "async-channel", + "async-task", + "futures-io", + "futures-lite", + "piper", +] + +[[package]] +name = "borsh" +version = "1.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "553c5d846a6ba5150c65e3b1b8ec073bcf1abc20f9b7220de384a4443ea4e20a" +dependencies = [ + "borsh-derive", + "bytes", + "cfg_aliases", +] + +[[package]] +name = "borsh-derive" +version = "1.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "12cdfe656708a01f89b451a7d36466e6fe6c414de0aa18fc54f864f6f9ca9f56" +dependencies = [ + "once_cell", + "proc-macro-crate", + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "bstr" +version = "1.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6bb31b46c14244e20ee9984b11bf5c992b91fb6939fea616e3512c8baecdbe5f" +dependencies = [ + "memchr", + "serde_core", +] + +[[package]] +name = "bumpalo" +version = "3.20.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649" + +[[package]] +name = "bytemuck" +version = "1.25.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "95832e849adfb21180ccb6826a99da14e5d266ae5c2e668e1602cf234f153797" +dependencies = [ + "bytemuck_derive", +] + +[[package]] +name = "bytemuck_derive" +version = "1.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6a1f896587b6f2c069c73d2f0913e2d590c3990285cd2f0b6aa02b786b4c679c" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "byteorder" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" + +[[package]] +name = "byteorder-lite" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f1fe948ff07f4bd06c30984e69f5b4899c516a3ef74f34df92a2df2ab535495" + +[[package]] +name = "bytes" +version = "1.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" + +[[package]] +name = "calloop" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b99da2f8558ca23c71f4fd15dc57c906239752dd27ff3c00a1d56b685b7cbfec" +dependencies = [ + "bitflags 2.13.2", + "log", + "polling", + "rustix 0.38.44", + "slab", + "thiserror 1.0.69", +] + +[[package]] +name = "calloop-wayland-source" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "95a66a987056935f7efce4ab5668920b5d0dac4a7c99991a67395f13702ddd20" +dependencies = [ + "calloop", + "rustix 0.38.44", + "wayland-backend", + "wayland-client", +] + +[[package]] +name = "cc" +version = "1.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "877bf67ac8e52449eb2f9e98a344ea163beb70dd1f9eebe3cc5357dcfeaee4df" +dependencies = [ + "find-msvc-tools", + "jobserver", + "libc", + "shlex", +] + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "cfg_aliases" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527" + +[[package]] +name = "chacha20" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06" +dependencies = [ + "cfg-if", + "cpufeatures 0.3.1", + "rand_core 0.10.1", +] + +[[package]] +name = "clipboard-win" +version = "5.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bde03770d3df201d4fb868f2c9c59e66a3e4e2bd06692a0fe701e7103c7e84d4" +dependencies = [ + "error-code", +] + +[[package]] +name = "codespan-reporting" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af491d569909a7e4dee0ad7db7f5341fef5c614d5b8ec8cf765732aba3cff681" +dependencies = [ + "serde", + "termcolor", + "unicode-width", +] + +[[package]] +name = "color_quant" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d7b894f5411737b7867f4827955924d7c254fc9f4d91a6aad6b097804b1018b" + +[[package]] +name = "combine" +version = "4.6.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4356eba6976435498d05a311ee9fc486da3bc81c200d3f0d7dd9703b41913f92" +dependencies = [ + "bytes", + "memchr", +] + +[[package]] +name = "concurrent-queue" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ca0197aee26d1ae37445ee532fefce43251d24cc7c166799f4d46817f1d3973" +dependencies = [ + "crossbeam-utils", +] + +[[package]] +name = "console_error_panic_hook" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a06aeb73f470f66dcdbf7223caeebb85984942f22f1adb2a088cf9668146bbbc" +dependencies = [ + "cfg-if", + "wasm-bindgen", +] + +[[package]] +name = "const_format" +version = "0.2.36" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4481a617ad9a412be3b97c5d403fef8ed023103368908b9c50af598ff467cc1e" +dependencies = [ + "const_format_proc_macros", + "konst", +] + +[[package]] +name = "const_format_proc_macros" +version = "0.2.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d57c2eccfb16dbac1f4e61e206105db5820c9d26c3c472bc17c774259ef7744" +dependencies = [ + "proc-macro2", + "quote", + "unicode-xid", +] + +[[package]] +name = "constant_time_eq" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d52eff69cd5e647efe296129160853a42795992097e8af39800e1060caeea9b" + +[[package]] +name = "core-foundation" +version = "0.9.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "91e195e091a93c46f7102ec7818a2aa394e1e1771c3ab4825963fa03e45afb8f" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "core-foundation-sys" +version = "0.8.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" + +[[package]] +name = "core-graphics" +version = "0.23.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c07782be35f9e1140080c6b96f0d44b739e2278479f64e02fdab4e32dfd8b081" +dependencies = [ + "bitflags 1.3.2", + "core-foundation", + "core-graphics-types", + "foreign-types", + "libc", +] + +[[package]] +name = "core-graphics-types" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "45390e6114f68f718cc7a830514a96f903cccd70d02a8f6d9f643ac4ba45afaf" +dependencies = [ + "bitflags 1.3.2", + "core-foundation", + "libc", +] + +[[package]] +name = "core_detect" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f8f80099a98041a3d1622845c271458a2d73e688351bf3cb999266764b81d48" + +[[package]] +name = "cpufeatures" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" +dependencies = [ + "libc", +] + +[[package]] +name = "cpufeatures" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566" +dependencies = [ + "libc", +] + +[[package]] +name = "crc32fast" +version = "1.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ba106e844045ddc02c20768ac4b0b7cb45f2cc2ecbd833ac9f5dacb183c2055" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "crossbeam-utils" +version = "0.8.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6" + +[[package]] +name = "crunchy" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5" + +[[package]] +name = "crypto-common" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" +dependencies = [ + "generic-array", + "typenum", +] + +[[package]] +name = "cursed-settings" +version = "0.0.1" +dependencies = [ + "bytemuck", + "rune", + "rune-fx", + "rune-kit", + "rune-light", + "rune-motion", + "rune-theme-opencode", + "wgpu", +] + +[[package]] +name = "cursor-icon" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f27ae1dd37df86211c42e150270f82743308803d90a6f6e6651cd730d5e1732f" + +[[package]] +name = "data-encoding" +version = "2.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4583a4551df46e2792f82ceeac45e850d2e2d5debba0b91f102385cda5b11f06" + +[[package]] +name = "data-url" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "be1e0bca6c3637f992fc1cc7cbc52a78c1ef6db076dbf1059c4323d6a2048376" + +[[package]] +name = "derive_more" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d751e9e49156b02b44f9c1815bcb94b984cdcc4396ecc32521c739452808b134" +dependencies = [ + "derive_more-impl", +] + +[[package]] +name = "derive_more-impl" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "799a97264921d8623a957f6c3b9011f3b5492f557bbb7a5a19b7fa6d06ba8dcb" +dependencies = [ + "proc-macro2", + "quote", + "rustc_version", + "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 = "dioxus-cli-config" +version = "0.7.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "322d10f47effebd85ee0662a2cb083ff920d40dd6295a4afd8cfa4f9bc2e05c6" + +[[package]] +name = "dioxus-core" +version = "0.7.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1b232228ada232c0adc151e41ebd9ef70cc04683db097fa0dc6015979fa01722" +dependencies = [ + "anyhow", + "const_format", + "dioxus-core-types", + "futures-channel", + "futures-util", + "generational-box", + "longest-increasing-subsequence", + "rustc-hash 2.1.3", + "rustversion", + "serde", + "slab", + "slotmap", + "subsecond", + "tracing", +] + +[[package]] +name = "dioxus-core-types" +version = "0.7.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "96007ed6cbad951dfed82d83c581aabd95bc591f351f5666d454ddbe7845b324" + +[[package]] +name = "dioxus-devtools" +version = "0.7.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "434cebb282b3f820a341582ebfd37dab907d5a25c3eeafd87802468afcd2a959" +dependencies = [ + "dioxus-cli-config", + "dioxus-core", + "dioxus-devtools-types", + "dioxus-signals", + "serde", + "serde_json", + "subsecond", + "thiserror 2.0.21", + "tracing", + "tungstenite", +] + +[[package]] +name = "dioxus-devtools-types" +version = "0.7.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dfd6f3475e38c93be245a664a9ce11679a8f2b99832620705cf7837f42aa39ce" +dependencies = [ + "dioxus-core", + "serde", + "subsecond-types", +] + +[[package]] +name = "dioxus-signals" +version = "0.7.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "95d85e36fcaf7abdc986836801bf248776da7d5961f5fac65fdbf5ed491afb4f" +dependencies = [ + "dioxus-core", + "futures-channel", + "futures-util", + "generational-box", + "parking_lot", + "rustc-hash 2.1.3", + "tracing", + "warnings", +] + +[[package]] +name = "dispatch" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bd0c93bb4b0c6d9b77f4435b0ae98c24d17f1c45b2ff844c6151a07256ca923b" + +[[package]] +name = "dispatch2" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e0e367e4e7da84520dedcac1901e4da967309406d1e51017ae1abfb97adbd38" +dependencies = [ + "bitflags 2.13.2", + "block2 0.6.2", + "libc", + "objc2 0.6.5", +] + +[[package]] +name = "displaydoc" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "dlib" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ab8ecd87370524b461f8557c119c405552c396ed91fc0a8eec68679eab26f94a" +dependencies = [ + "libloading", +] + +[[package]] +name = "document-features" +version = "0.2.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d4b8a88685455ed29a21542a33abd9cb6510b6b129abadabdcef0f4c55bc8f61" +dependencies = [ + "litrs", +] + +[[package]] +name = "downcast-rs" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "75b325c5dbd37f80359721ad39aca5a29fb04c89279657cffdda8736d0c0b9d2" + +[[package]] +name = "dpi" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d8b14ccef22fc6f5a8f4d7d768562a182c04ce9a3b3157b91390b52ddfdf1a76" + +[[package]] +name = "drag-out" +version = "0.0.1" +dependencies = [ + "rune", +] + +[[package]] +name = "drop-files" +version = "0.0.1" +dependencies = [ + "rune", +] + +[[package]] +name = "either" +version = "1.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be" + +[[package]] +name = "either-or-both" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6717164c227120ba9ddf3e2b32305fc0122741d3ee41a54968eae7573ee01933" +dependencies = [ + "indexmap", + "serde", +] + +[[package]] +name = "encoding_rs" +version = "0.8.42" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e985e0451871ad22fb8d2b6b076e2028a502a0d3950998c2c5c0a4f9b5d9679" +dependencies = [ + "cfg-if", + "core_detect", + "multiversion_no_op", + "rustversion", + "scopeguard", + "simdutf8", +] + +[[package]] +name = "endi" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "66b7e2430c6dff6a955451e2cfc438f09cea1965a9d6f87f7e3b90decc014099" + +[[package]] +name = "enumflags2" +version = "0.7.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1027f7680c853e056ebcec683615fb6fbbc07dbaa13b4d5d9442b146ded4ecef" +dependencies = [ + "enumflags2_derive", + "serde", +] + +[[package]] +name = "enumflags2_derive" +version = "0.7.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67c78a4d8fdf9953a5c9d458f9efe940fd97a0cab0941c075a813ac594733827" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "equivalent" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" + +[[package]] +name = "erased-serde" +version = "0.4.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e59b668157f32d3459d4bd634861a06ffa2503a461ca5f0916b9f0252605e66" +dependencies = [ + "serde", + "serde_core", + "typeid", +] + +[[package]] +name = "errno" +version = "0.3.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "error-code" +version = "3.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b5343afd4a8365a643ac588dab4cf234a190c7f6c88c9f6dd6ffe00837661b7" + +[[package]] +name = "euclid" +version = "0.22.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1a05365e3b1c6d1650318537c7460c6923f1abdd272ad6842baa2b509957a06" +dependencies = [ + "num-traits", +] + +[[package]] +name = "event-listener" +version = "5.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a23add41df1562121a9393cb065eab5146a1242410f23a644851e90cfd669d2" +dependencies = [ + "parking", + "pin-project-lite", +] + +[[package]] +name = "event-listener-strategy" +version = "0.5.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8be9f3dfaaffdae2972880079a491a1a8bb7cbed0b8dd7a347f668b4150a3b93" +dependencies = [ + "event-listener", + "pin-project-lite", +] + +[[package]] +name = "fallible_collections" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dab93c7205280c4785c44517fe84d99751b81f6deb8450cb196da6be88e332bb" + +[[package]] +name = "fastrand" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" + +[[package]] +name = "fax" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "caf1079563223d5d59d83c85886a56e586cfd5c1a26292e971a0fa266531ac5a" + +[[package]] +name = "fdeflate" +version = "0.3.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e6853b52649d4ac5c0bd02320cddc5ba956bdb407c4b75a2c6b75bf51500f8c" +dependencies = [ + "simd-adler32", +] + +[[package]] +name = "find-msvc-tools" +version = "0.1.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48" + +[[package]] +name = "fixed_decimal" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2214fb00f669ee96bee5bb29dfb1ddabe058b2bc426817efc79afa03c9bc55ae" +dependencies = [ + "displaydoc", + "ryu", + "smallvec", + "writeable", +] + +[[package]] +name = "fixedbitset" +version = "0.5.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d674e81391d1e1ab681a28d99df07927c6d4aa5b027d7da16ba32d1d21ecd99" + +[[package]] +name = "flate2" +version = "1.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e634e2e0ebac1ee034020da1ca582e17ffe4e0f5e985823721e168928136dcb" +dependencies = [ + "crc32fast", + "miniz_oxide 0.9.1", + "zlib-rs", +] + +[[package]] +name = "float-cmp" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "98de4bbd547a563b716d8dfa9aad1cb19bfab00f4fa09a6a4ed21dbcf44ce9c4" + +[[package]] +name = "fnv" +version = "1.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" + +[[package]] +name = "foldhash" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2" + +[[package]] +name = "foldhash" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" + +[[package]] +name = "font-types" +version = "0.12.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "835ae9d781464a79026cde387f9cbc650c9a4909d7cf7e658b127e3c35d2f35d" +dependencies = [ + "bytemuck", +] + +[[package]] +name = "fontique" +version = "0.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbf1df16263783918b7da396077521f92b729ef7c429444dfcf03581f1448b77" +dependencies = [ + "hashbrown 0.17.1", + "linebender_resource_handle", + "memmap2", + "objc2 0.6.5", + "objc2-core-foundation", + "objc2-core-text", + "objc2-foundation 0.3.2", + "parlance", + "read-fonts", + "roxmltree 0.21.2", + "smallvec", + "windows", + "windows-core", + "yeslogic-fontconfig-sys", +] + +[[package]] +name = "foreign-types" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d737d9aa519fb7b749cbc3b962edcf310a8dd1f4b67c91c4f83975dbdd17d965" +dependencies = [ + "foreign-types-macros", + "foreign-types-shared", +] + +[[package]] +name = "foreign-types-macros" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ea5190182e6915eb873ddbc16e23b711b6eb1f9c00a0d0a3a91b5f6228475225" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "foreign-types-shared" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aa9a19cbb55df58761df49b23516a86d432839add4af60fc256da840f66ed35b" + +[[package]] +name = "frosted-bar" +version = "0.0.1" +dependencies = [ + "rune", +] + +[[package]] +name = "futures-channel" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1f9e3d69d39e4862ffed03ed071a76f9a13ba1d9109d355b0f0aa6b15e393c4" +dependencies = [ + "futures-core", +] + +[[package]] +name = "futures-core" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" + +[[package]] +name = "futures-io" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53c0fa8157de1303bfffdaa1cc2a673bfffb60102f76b0ef4441659124373fed" + +[[package]] +name = "futures-lite" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f78e10609fe0e0b3f4157ffab1876319b5b0db102a2c60dc4626306dc46b44ad" +dependencies = [ + "fastrand", + "futures-core", + "futures-io", + "parking", + "pin-project-lite", +] + +[[package]] +name = "futures-macro" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9fb9654ba8355388abeb8dcb4fc62f511300867002afc858860463bdd9fe0c44" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "futures-task" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd" + +[[package]] +name = "futures-util" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" +dependencies = [ + "futures-core", + "futures-macro", + "futures-task", + "pin-project-lite", + "slab", +] + +[[package]] +name = "generational-box" +version = "0.7.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8b2dc9b873cd1a8adb80aa5dcef9a8205f781a8a313d5ffb867248cb3bcb764" +dependencies = [ + "parking_lot", + "tracing", +] + +[[package]] +name = "generic-array" +version = "0.14.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" +dependencies = [ + "typenum", + "version_check", +] + +[[package]] +name = "gethostname" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1bd49230192a3797a9a4d6abe9b3eed6f7fa4c8a8a4947977c6f80025f92cbd8" +dependencies = [ + "rustix 1.1.5", + "windows-link", +] + +[[package]] +name = "getrandom" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd" +dependencies = [ + "cfg-if", + "libc", + "r-efi 5.3.0", + "wasip2", +] + +[[package]] +name = "getrandom" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" +dependencies = [ + "cfg-if", + "libc", + "r-efi 6.0.0", + "rand_core 0.10.1", +] + +[[package]] +name = "gif" +version = "0.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee8cfcc411d9adbbaba82fb72661cc1bcca13e8bba98b364e62b2dba8f960159" +dependencies = [ + "color_quant", + "weezl", +] + +[[package]] +name = "gl_generator" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1a95dfc23a2b4a9a2f5ab41d194f8bfda3cabec42af4e39f08c339eb2a0c124d" +dependencies = [ + "khronos_api", + "log", + "xml-rs", +] + +[[package]] +name = "glass-card" +version = "0.0.1" +dependencies = [ + "rune", +] + +[[package]] +name = "glass-panel" +version = "0.0.1" +dependencies = [ + "rune", +] + +[[package]] +name = "glow" +version = "0.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29038e1c483364cc6bb3cf78feee1816002e127c331a1eec55a4d202b9e1adb5" +dependencies = [ + "js-sys", + "slotmap", + "wasm-bindgen", + "web-sys", +] + +[[package]] +name = "glutin_wgl_sys" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2c4ee00b289aba7a9e5306d57c2d05499b2e5dc427f84ac708bd2c090212cf3e" +dependencies = [ + "gl_generator", +] + +[[package]] +name = "gpu-allocator" +version = "0.28.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "51255ea7cfaadb6c5f1528d43e92a82acb2b96c43365989a28b2d44ee38f8795" +dependencies = [ + "ash", + "hashbrown 0.16.1", + "log", + "presser", + "thiserror 2.0.21", + "windows", +] + +[[package]] +name = "gungraun" +version = "0.20.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c041375e48b8ef7cd2d0e70715598154af627c1a551e41c35fdb4a2b3910831a" +dependencies = [ + "bincode-next", + "derive_more", + "gungraun-common", + "gungraun-macros", + "gungraun-runner", +] + +[[package]] +name = "gungraun-common" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bc270ba55639babb5806b62d4bfbc35e15ca15791e3ec00c7b92b39c62a9d8eb" + +[[package]] +name = "gungraun-macros" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08472a9e996a98a5b4274dd342fb32ebe1a5cfeb2662b6578d0c7bf1dd203129" +dependencies = [ + "derive_more", + "proc-macro-error3", + "proc-macro2", + "quote", + "rustc_version", + "serde", + "serde_json", + "syn 3.0.9", +] + +[[package]] +name = "gungraun-runner" +version = "0.20.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e1460377fe936c3efbe8e27c422b745fa54ebaea81ffe4a53a6f17c7a478683" +dependencies = [ + "either-or-both", + "serde", +] + +[[package]] +name = "half" +version = "2.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ea2d84b969582b4b1864a92dc5d27cd2b77b622a8d79306834f1be5ba20d84b" +dependencies = [ + "cfg-if", + "crunchy", + "num-traits", + "zerocopy 0.8.63", +] + +[[package]] +name = "harfrust" +version = "0.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c03d949a14aa089bbb282f7dd76a498a7f684428e4257202efc119ec010376f9" +dependencies = [ + "bitflags 2.13.2", + "bytemuck", + "read-fonts", + "smallvec", +] + +[[package]] +name = "hashbrown" +version = "0.15.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1" +dependencies = [ + "foldhash 0.1.5", +] + +[[package]] +name = "hashbrown" +version = "0.16.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100" +dependencies = [ + "allocator-api2", + "equivalent", + "foldhash 0.2.0", +] + +[[package]] +name = "hashbrown" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" +dependencies = [ + "foldhash 0.2.0", +] + +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + +[[package]] +name = "hello" +version = "0.0.1" +dependencies = [ + "rune", +] + +[[package]] +name = "hermit-abi" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e17592d60ebacc7d5e169f4663c5f84f9161cc90328abcfe8456f41e4dfcb284" + +[[package]] +name = "hex" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" + +[[package]] +name = "http" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0" +dependencies = [ + "bytes", + "itoa", +] + +[[package]] +name = "httparse" +version = "1.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" + +[[package]] +name = "icu_collections" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fa68d21081c4a05d5a901a1c62add574c77048b6a1c67be3b50ce0b60d4ca513" +dependencies = [ + "displaydoc", + "potential_utf", + "utf8_iter", + "yoke", + "zerofrom", + "zerovec", +] + +[[package]] +name = "icu_decimal" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9eb8f655bba2d0c0459e43a5b0e6cd3cd388109898fb3d85d048165e8b0abd08" +dependencies = [ + "displaydoc", + "fixed_decimal", + "icu_decimal_data", + "icu_locale_core", + "icu_locale_fallback", + "icu_plurals", + "icu_provider", + "writeable", + "zerovec", +] + +[[package]] +name = "icu_decimal_data" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e4c887fc7d4c297cf3f9436864af9e3dba7f8be9415a6c2a7f392f3b1636298c" + +[[package]] +name = "icu_list" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a5c625125085fac4bf9ad111888a90c6ab9dc7bcaec392ca79cab417f46e3fb" +dependencies = [ + "icu_list_data", + "icu_locale_fallback", + "icu_provider", + "regex-automata", + "writeable", + "zerovec", +] + +[[package]] +name = "icu_list_data" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ffef91ee351bd195a803115615a034dfb9f02bb48850980548c31cb78568a91" + +[[package]] +name = "icu_locale" +version = "2.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "785f595c61ef57169a467eeed7b4b6936a66f6cacbb116a96ee86da983251bf4" +dependencies = [ + "icu_collections", + "icu_locale_core", + "icu_locale_data", + "icu_locale_fallback", + "icu_provider", + "tinystr", + "zerovec", +] + +[[package]] +name = "icu_locale_core" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d56e28588da92eee5c3201a6eff33fabdd49b62269c8938d4ff050ce4d900deb" +dependencies = [ + "displaydoc", + "litemap", + "serde", + "tinystr", + "writeable", + "zerovec", +] + +[[package]] +name = "icu_locale_data" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d37d91460e362a5cf58907cd7ce871411775ee6294e49a5cc8e6cec16dfa75ea" + +[[package]] +name = "icu_locale_fallback" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "251af8e57c9400e3eb58242fe5b8b1152b2a64fdf4cf632f923c38ccee6f2fa9" +dependencies = [ + "icu_locale_core", + "icu_locale_fallback_data", + "icu_provider", + "potential_utf", + "tinystr", + "zerovec", +] + +[[package]] +name = "icu_locale_fallback_data" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "decf2a22ec8fa68f1a0c1129a3f8583f8f8bc24e8b9ccbe98ead99f62a4dc3a8" + +[[package]] +name = "icu_normalizer" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "12f9cf5f235641ed274641dd81c3f28d870e276763d0797aeeab72317b1c646f" +dependencies = [ + "icu_collections", + "icu_normalizer_data", + "icu_properties", + "icu_provider", + "smallvec", + "zerovec", +] + +[[package]] +name = "icu_normalizer_data" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1563da1ed3e0b3bf3d74c9b85917ac9c56464d2f57242270c09c9e752f8021a0" + +[[package]] +name = "icu_plurals" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e475e6766ef87b1d3c1f97be6363995b0bfaeddbc789671615df598a97ff0593" +dependencies = [ + "fixed_decimal", + "icu_locale_fallback", + "icu_plurals_data", + "icu_provider", + "zerovec", +] + +[[package]] +name = "icu_plurals_data" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1251aa39a95e1333888e499b1263e1c196447a28948acf5bdabd82c046f153bf" + +[[package]] +name = "icu_properties" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e7ca276ad3145661a65914e6daf131ca5120cd3dcee8f8f3214b8875184a148" +dependencies = [ + "displaydoc", + "icu_collections", + "icu_locale_core", + "icu_properties_data", + "icu_provider", + "zerotrie", + "zerovec", +] + +[[package]] +name = "icu_properties_data" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e590f038c1464a96894fd6d10127e90a8be4509f56ff7ecef851b15cee0b7caa" + +[[package]] +name = "icu_provider" +version = "2.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d27bbb9d3abbefac45d55f647c9de1d44aafcd1186eb91879afef17c396c3e73" +dependencies = [ + "displaydoc", + "icu_locale_core", + "serde", + "stable_deref_trait", + "writeable", + "yoke", + "zerofrom", + "zerotrie", + "zerovec", +] + +[[package]] +name = "icu_segmenter" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "82d07aafccd67af15d02512a6adf5896fbc5ed00f2e99b471d2efa14016db3db" +dependencies = [ + "icu_collections", + "icu_locale_fallback", + "icu_provider", + "icu_segmenter_data", + "potential_utf", + "smallvec", + "utf8_iter", + "zerovec", +] + +[[package]] +name = "icu_segmenter_data" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae293c039020f9ec10710af98d29ce6aa2051486638b49c9a6409f3b4a9e98ad" + +[[package]] +name = "image" +version = "0.25.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85ab80394333c02fe689eaf900ab500fbd0c2213da414687ebf995a65d5a6104" +dependencies = [ + "bytemuck", + "byteorder-lite", + "color_quant", + "gif", + "image-webp", + "moxcms", + "num-traits", + "png 0.18.1", + "tiff", + "zune-core", + "zune-jpeg", +] + +[[package]] +name = "image-webp" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "525e9ff3e1a4be2fbea1fdf0e98686a6d98b4d8f937e1bf7402245af1909e8c3" +dependencies = [ + "byteorder-lite", + "quick-error 2.0.1", +] + +[[package]] +name = "imagesize" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "edcd27d72f2f071c64249075f42e205ff93c9a4c5f6c6da53e79ed9f9832c285" + +[[package]] +name = "imgref" +version = "1.12.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e44b0a4eaa4c82f441d50a963f2d5f05a787240aeee097597033e72accfd22f" + +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown 0.17.1", +] + +[[package]] +name = "inotify" +version = "0.11.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4cc00ea907cab49550b7da656f80ebb97be1b997d931fbcd28d39734e17ce592" +dependencies = [ + "bitflags 2.13.2", + "inotify-sys", + "libc", +] + +[[package]] +name = "inotify-sys" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c033f80b2c113cdf91ab7a33faa9cbc014726dcad99880c8609af2a370edf37d" +dependencies = [ + "libc", +] + +[[package]] +name = "itoa" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" + +[[package]] +name = "jni" +version = "0.22.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5efd9a482cf3a427f00d6b35f14332adc7902ce91efb778580e180ff90fa3498" +dependencies = [ + "cfg-if", + "combine", + "jni-macros", + "jni-sys 0.4.1", + "log", + "simd_cesu8", + "thiserror 2.0.21", + "walkdir", + "windows-link", +] + +[[package]] +name = "jni-macros" +version = "0.22.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a00109accc170f0bdb141fed3e393c565b6f5e072365c3bd58f5b062591560a3" +dependencies = [ + "proc-macro2", + "quote", + "rustc_version", + "simd_cesu8", + "syn 2.0.119", +] + +[[package]] +name = "jni-sys" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41a652e1f9b6e0275df1f15b32661cf0d4b78d4d87ddec5e0c3c20f097433258" +dependencies = [ + "jni-sys 0.4.1", +] + +[[package]] +name = "jni-sys" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6377a88cb3910bee9b0fa88d4f42e1d2da8e79915598f65fb0c7ee14c878af2" +dependencies = [ + "jni-sys-macros", +] + +[[package]] +name = "jni-sys-macros" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38c0b942f458fe50cdac086d2f946512305e5631e720728f2a61aabcd47a6264" +dependencies = [ + "quote", + "syn 2.0.119", +] + +[[package]] +name = "jobserver" +version = "0.1.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c00acbd29eabad4a2392fa0e921c874934dbbf4194312ad20f04a0ed67a3cb3" +dependencies = [ + "getrandom 0.4.3", + "libc", +] + +[[package]] +name = "js-sys" +version = "0.3.106" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7883d941dae510fb2d978fc3fe018c71c9e2892fd38854de3e8b92c2e5ad9cc5" +dependencies = [ + "cfg-if", + "futures-util", + "wasm-bindgen", +] + +[[package]] +name = "khronos-egl" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6aae1df220ece3c0ada96b8153459b67eebe9ae9212258bb0134ae60416fdf76" +dependencies = [ + "libc", + "libloading", + "pkg-config", +] + +[[package]] +name = "khronos_api" +version = "3.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e2db585e1d738fc771bf08a151420d3ed193d9d895a36df7f6f8a9456b911ddc" + +[[package]] +name = "kit-gallery" +version = "0.0.1" +dependencies = [ + "rune", + "rune-kit", + "rune-theme-opencode", + "wgpu", +] + +[[package]] +name = "knobs" +version = "0.0.1" +dependencies = [ + "rune", + "rune-knobs", +] + +[[package]] +name = "konst" +version = "0.2.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "128133ed7824fcd73d6e7b17957c5eb7bacb885649bd8c69708b2331a10bcefb" +dependencies = [ + "konst_macro_rules", +] + +[[package]] +name = "konst_macro_rules" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4933f3f57a8e9d9da04db23fb153356ecaf00cbd14aee46279c33dc80925c37" + +[[package]] +name = "kqueue" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8d763e5b24120b4ddf50de6c92308156765aabfbbccebf401da7cff2d70a41ea" +dependencies = [ + "kqueue-sys", + "libc", +] + +[[package]] +name = "kqueue-sys" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "07293a4e297ac234359b510362495713f75ea345d5307140414f20c69ffeb087" +dependencies = [ + "bitflags 2.13.2", + "libc", +] + +[[package]] +name = "kurbo" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c62026ae44756f8a599ba21140f350303d4f08dcdcc71b5ad9c9bb8128c13c62" +dependencies = [ + "arrayvec", + "euclid", + "smallvec", +] + +[[package]] +name = "lab" +version = "0.0.1" +dependencies = [ + "bytemuck", + "rune", + "rune-fx", + "rune-light", + "rune-motion", + "wgpu", +] + +[[package]] +name = "launcher" +version = "0.0.1" +dependencies = [ + "rune", +] + +[[package]] +name = "lazy_static" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb" + +[[package]] +name = "leb128" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c83bff1d572d6b9aeef67ddfc8448e4a3737909cb28e81f97c791b9018703e52" + +[[package]] +name = "libc" +version = "0.2.191" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" + +[[package]] +name = "libloading" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d7c4b02199fee7c5d21a5ae7d8cfa79a6ef5bb2fc834d6e9058e89c825efdc55" +dependencies = [ + "cfg-if", + "windows-link", +] + +[[package]] +name = "libm" +version = "0.2.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981" + +[[package]] +name = "libredox" +version = "0.1.25" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "61ff90caf6077a803a240f62fdbe88645a890bbca49ef8174c3cb0404362171d" +dependencies = [ + "bitflags 2.13.2", + "libc", + "plain", + "redox_syscall 0.9.5", +] + +[[package]] +name = "linebender_resource_handle" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d4a5ff6bcca6c4867b1c4fd4ef63e4db7436ef363e0ad7531d1558856bae64f4" + +[[package]] +name = "linkme" +version = "0.3.37" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3045e122bd98aef8ec3ad58ce84f0791f64e70163d1a02710af4aa11a4d54cc5" +dependencies = [ + "linkme-impl", +] + +[[package]] +name = "linkme-impl" +version = "0.3.37" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77060ebe535362c3da75682cd17b0431017b6e7c5661e714fc69a7ad017d1301" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "linux-raw-sys" +version = "0.4.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d26c52dbd32dccf2d10cac7725f8eae5296885fb5703b261f7d0a0739ec807ab" + +[[package]] +name = "linux-raw-sys" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" + +[[package]] +name = "litemap" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae" + +[[package]] +name = "litrs" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4744e383959f0db86ede514b809b1c53251889093803c05267acc7d4e7030d70" + +[[package]] +name = "live-values" +version = "0.0.1" +dependencies = [ + "rune", +] + +[[package]] +name = "lock_api" +version = "0.4.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965" +dependencies = [ + "scopeguard", +] + +[[package]] +name = "lodepng" +version = "3.12.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe7982db11054edc023a1b424dddcc65be18f71fa46ec6bde2efcfc1fb6b22da" +dependencies = [ + "crc32fast", + "flate2", + "libc", + "rgb", +] + +[[package]] +name = "log" +version = "0.4.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6" + +[[package]] +name = "longest-increasing-subsequence" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b3bd0dd2cd90571056fdb71f6275fada10131182f84899f4b2a916e565d81d86" + +[[package]] +name = "luau-panel" +version = "0.0.1" +dependencies = [ + "rune", + "rune-luau", + "serde", + "wasm-bindgen", +] + +[[package]] +name = "luau0-src" +version = "0.23.0+luau745" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "44a77f4ce1adc38145ccd67a0e4b1928e642aedf906d1131d7f703e573c31162" +dependencies = [ + "cc", +] + +[[package]] +name = "matched" +version = "0.0.1" +dependencies = [ + "rune", +] + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "memfd" +version = "0.6.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "57804b2c9b69967f1536a56f86297e367a33b19e98852ed624b84551cdbc0d90" +dependencies = [ + "rustix 1.1.5", +] + +[[package]] +name = "memmap2" +version = "0.9.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6b0ca1155a9ecc25aa12e8313a119f32edf0255fea2f44839c4ac0a12b2ac157" +dependencies = [ + "libc", +] + +[[package]] +name = "memoffset" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "488016bfae457b036d996092f6cb448677611ce4449e970ceaf42695203f218a" +dependencies = [ + "autocfg", +] + +[[package]] +name = "miniz_oxide" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fa76a2c86f704bdb222d66965fb3d63269ce38518b83cb0575fca855ebb6316" +dependencies = [ + "adler2", + "simd-adler32", +] + +[[package]] +name = "miniz_oxide" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b63fbc4a50860e98e7b2aa7804ded1db5cbc3aff9193adaff57a6931bf7c4b4c" +dependencies = [ + "adler2", + "simd-adler32", +] + +[[package]] +name = "mio" +version = "1.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1788edb87fdc09c7e26304471e2f5be8cdefb1b6930d6e3985fc02ff53bf86ee" +dependencies = [ + "libc", + "log", + "wasi", + "windows-sys 0.61.2", +] + +[[package]] +name = "mlua" +version = "0.12.2" +source = "git+https://github.com/mlua-rs/mlua?rev=a0ad4535fc72ba89967a931c5be57b162b5f0f3f#a0ad4535fc72ba89967a931c5be57b162b5f0f3f" +dependencies = [ + "bstr", + "either", + "erased-serde", + "libc", + "mlua-sys", + "num-traits", + "parking_lot", + "rustc-hash 2.1.3", + "serde", + "serde-value", +] + +[[package]] +name = "mlua-sys" +version = "0.13.0" +source = "git+https://github.com/mlua-rs/mlua?rev=a0ad4535fc72ba89967a931c5be57b162b5f0f3f#a0ad4535fc72ba89967a931c5be57b162b5f0f3f" +dependencies = [ + "cc", + "cfg-if", + "libc", + "luau0-src", + "pkg-config", +] + +[[package]] +name = "motion-bento" +version = "0.0.1" +dependencies = [ + "motion-bento-chaos", + "rune", + "rune-kit", +] + +[[package]] +name = "motion-bento-chaos" +version = "0.0.1" +dependencies = [ + "libc", + "procwatch", + "windows-sys 0.61.2", +] + +[[package]] +name = "moxcms" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb85c154ba489f01b25c0d36ae69a87e4a1c73a72631fc6c0eb6dde34a73e44b" +dependencies = [ + "num-traits", + "pxfm", +] + +[[package]] +name = "multiversion_no_op" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "743fb55ba31b18fb1ecef6bdc9aa2743314978ac084044301a7eee33fb99a20d" + +[[package]] +name = "naga" +version = "30.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a616d2fb8c89516ac2723a581f69d6c18576046bed761bd6b305e5618e6ae130" +dependencies = [ + "arrayvec", + "bit-set 0.10.0", + "bitflags 2.13.2", + "cfg-if", + "cfg_aliases", + "codespan-reporting", + "half", + "hashbrown 0.17.1", + "indexmap", + "libm", + "log", + "naga-types", + "num-traits", + "once_cell", + "rustc-hash 1.1.0", + "spirv", + "thiserror 2.0.21", + "unicode-ident", +] + +[[package]] +name = "naga-types" +version = "30.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "590afbf58a6f4f62873cd5cff4468061844bafa1cdf399cc954537c22d768d49" +dependencies = [ + "hashbrown 0.17.1", + "indexmap", + "rustc-hash 1.1.0", + "thiserror 2.0.21", +] + +[[package]] +name = "nasm-rs" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "706bf8a5e8c8ddb99128c3291d31bd21f4bcde17f0f4c20ec678d85c74faa149" +dependencies = [ + "jobserver", + "log", +] + +[[package]] +name = "ndk" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3f42e7bbe13d351b6bead8286a43aac9534b82bd3cc43e47037f012ebfd62d4" +dependencies = [ + "bitflags 2.13.2", + "jni-sys 0.3.1", + "log", + "ndk-sys", + "num_enum", + "raw-window-handle", + "thiserror 1.0.69", +] + +[[package]] +name = "ndk-context" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27b02d87554356db9e9a873add8782d4ea6e3e58ea071a9adb9a2e8ddb884a8b" + +[[package]] +name = "ndk-sys" +version = "0.6.0+11769913" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee6cda3051665f1fb8d9e08fc35c96d5a244fb1be711a03b71118828afc9a873" +dependencies = [ + "jni-sys 0.3.1", +] + +[[package]] +name = "nom" +version = "8.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df9761775871bdef83bee530e60050f7e54b1105350d6884eb0fb4f46c2f9405" +dependencies = [ + "memchr", +] + +[[package]] +name = "notify" +version = "8.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "82f812702fbc75d35416d3f884e04925be7e9498f4eceea2e24ba34559284674" +dependencies = [ + "bitflags 2.13.2", + "inotify", + "kqueue", + "libc", + "log", + "mio", + "notify-types", + "objc2-core-foundation", + "objc2-core-services", + "walkdir", + "windows-sys 0.61.2", +] + +[[package]] +name = "notify-types" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0a437a9308232ce794b1e7fdf540d38ea37efc3c73492640c13b4c8568b8f108" +dependencies = [ + "bitflags 2.13.2", +] + +[[package]] +name = "num-traits" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" +dependencies = [ + "autocfg", + "libm", +] + +[[package]] +name = "num_enum" +version = "0.7.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d0bca838442ec211fa11de3a8b0e0e8f3a4522575b5c4c06ed722e005036f26" +dependencies = [ + "num_enum_derive", + "rustversion", +] + +[[package]] +name = "num_enum_derive" +version = "0.7.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "680998035259dcfcafe653688bf2aa6d3e2dc05e98be6ab46afb089dc84f1df8" +dependencies = [ + "proc-macro-crate", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "objc-sys" +version = "0.3.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cdb91bdd390c7ce1a8607f35f3ca7151b65afc0ff5ff3b34fa350f7d7c7e4310" + +[[package]] +name = "objc2" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "19d5490aaf8f1d7cf7688dfa9b0ce07900e168852c45cd2c03f534dfd27cfd0b" +dependencies = [ + "objc-sys", + "objc2-encode", +] + +[[package]] +name = "objc2" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08849bbd4767dfae9457696856ae1c84fe4e0281bbe4a7abff2d0e06fb7981f8" +dependencies = [ + "objc2-encode", +] + +[[package]] +name = "objc2-app-kit" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e4e89ad9e3d7d297152b17d39ed92cd50ca8063a89a9fa569046d41568891eff" +dependencies = [ + "bitflags 2.13.2", + "block2 0.5.1", + "libc", + "objc2 0.5.3", + "objc2-core-data", + "objc2-core-image", + "objc2-foundation 0.2.2", + "objc2-quartz-core 0.2.2", +] + +[[package]] +name = "objc2-app-kit" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d49e936b501e5c5bf01fda3a9452ff86dc3ea98ad5f283e1455153142d97518c" +dependencies = [ + "bitflags 2.13.2", + "block2 0.6.2", + "objc2 0.6.5", + "objc2-core-foundation", + "objc2-core-graphics", + "objc2-foundation 0.3.2", +] + +[[package]] +name = "objc2-av-foundation" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "478ae33fcac9df0a18db8302387c666b8ef08a3e2d62b510ca4fc278a384b6c0" +dependencies = [ + "bitflags 2.13.2", + "objc2 0.6.5", + "objc2-core-foundation", + "objc2-core-graphics", + "objc2-core-media", + "objc2-core-video", + "objc2-foundation 0.3.2", +] + +[[package]] +name = "objc2-cloud-kit" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "74dd3b56391c7a0596a295029734d3c1c5e7e510a4cb30245f8221ccea96b009" +dependencies = [ + "bitflags 2.13.2", + "block2 0.5.1", + "objc2 0.5.3", + "objc2-core-location", + "objc2-foundation 0.2.2", +] + +[[package]] +name = "objc2-contacts" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a5ff520e9c33812fd374d8deecef01d4a840e7b41862d849513de77e44aa4889" +dependencies = [ + "block2 0.5.1", + "objc2 0.5.3", + "objc2-foundation 0.2.2", +] + +[[package]] +name = "objc2-core-audio" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e1eebcea8b0dbff5f7c8504f3107c68fc061a3eb44932051c8cf8a68d969c3b2" +dependencies = [ + "dispatch2", + "objc2 0.6.5", + "objc2-core-audio-types", + "objc2-core-foundation", +] + +[[package]] +name = "objc2-core-audio-types" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a89f2ec274a0cf4a32642b2991e8b351a404d290da87bb6a9a9d8632490bd1c" +dependencies = [ + "bitflags 2.13.2", + "objc2 0.6.5", +] + +[[package]] +name = "objc2-core-data" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "617fbf49e071c178c0b24c080767db52958f716d9eabdf0890523aeae54773ef" +dependencies = [ + "bitflags 2.13.2", + "block2 0.5.1", + "objc2 0.5.3", + "objc2-foundation 0.2.2", +] + +[[package]] +name = "objc2-core-foundation" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2a180dd8642fa45cdb7dd721cd4c11b1cadd4929ce112ebd8b9f5803cc79d536" +dependencies = [ + "bitflags 2.13.2", + "dispatch2", + "objc2 0.6.5", +] + +[[package]] +name = "objc2-core-graphics" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e022c9d066895efa1345f8e33e584b9f958da2fd4cd116792e15e07e4720a807" +dependencies = [ + "bitflags 2.13.2", + "dispatch2", + "objc2 0.6.5", + "objc2-core-foundation", + "objc2-io-surface", +] + +[[package]] +name = "objc2-core-image" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "55260963a527c99f1819c4f8e3b47fe04f9650694ef348ffd2227e8196d34c80" +dependencies = [ + "block2 0.5.1", + "objc2 0.5.3", + "objc2-foundation 0.2.2", + "objc2-metal 0.2.2", +] + +[[package]] +name = "objc2-core-location" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "000cfee34e683244f284252ee206a27953279d370e309649dc3ee317b37e5781" +dependencies = [ + "block2 0.5.1", + "objc2 0.5.3", + "objc2-contacts", + "objc2-foundation 0.2.2", +] + +[[package]] +name = "objc2-core-media" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "05ec576860167a15dd9fce7fbee7512beb4e31f532159d3482d1f9c6caedf31d" +dependencies = [ + "bitflags 2.13.2", + "dispatch2", + "objc2 0.6.5", + "objc2-core-audio", + "objc2-core-audio-types", + "objc2-core-foundation", + "objc2-core-video", +] + +[[package]] +name = "objc2-core-services" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "583300ad934cba24ff5292aee751ecc070f7ca6b39a574cc21b7b5e588e06a0b" +dependencies = [ + "libc", + "objc2-core-foundation", +] + +[[package]] +name = "objc2-core-text" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0cde0dfb48d25d2b4862161a4d5fcc0e3c24367869ad306b0c9ec0073bfed92d" +dependencies = [ + "bitflags 2.13.2", + "objc2-core-foundation", +] + +[[package]] +name = "objc2-core-video" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d425caf1df73233f29fd8a5c3e5edbc30d2d4307870f802d18f00d83dc5141a6" +dependencies = [ + "bitflags 2.13.2", + "objc2 0.6.5", + "objc2-core-foundation", + "objc2-core-graphics", + "objc2-io-surface", + "objc2-metal 0.3.2", +] + +[[package]] +name = "objc2-encode" +version = "4.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ef25abbcd74fb2609453eb695bd2f860d389e457f67dc17cafc8b8cbc89d0c33" + +[[package]] +name = "objc2-foundation" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ee638a5da3799329310ad4cfa62fbf045d5f56e3ef5ba4149e7452dcf89d5a8" +dependencies = [ + "bitflags 2.13.2", + "block2 0.5.1", + "dispatch", + "libc", + "objc2 0.5.3", +] + +[[package]] +name = "objc2-foundation" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3e0adef53c21f888deb4fa59fc59f7eb17404926ee8a6f59f5df0fd7f9f3272" +dependencies = [ + "bitflags 2.13.2", + "objc2 0.6.5", + "objc2-core-foundation", +] + +[[package]] +name = "objc2-io-surface" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "180788110936d59bab6bd83b6060ffdfffb3b922ba1396b312ae795e1de9d81d" +dependencies = [ + "bitflags 2.13.2", + "objc2 0.6.5", + "objc2-core-foundation", +] + +[[package]] +name = "objc2-link-presentation" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a1a1ae721c5e35be65f01a03b6d2ac13a54cb4fa70d8a5da293d7b0020261398" +dependencies = [ + "block2 0.5.1", + "objc2 0.5.3", + "objc2-app-kit 0.2.2", + "objc2-foundation 0.2.2", +] + +[[package]] +name = "objc2-metal" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dd0cba1276f6023976a406a14ffa85e1fdd19df6b0f737b063b95f6c8c7aadd6" +dependencies = [ + "bitflags 2.13.2", + "block2 0.5.1", + "objc2 0.5.3", + "objc2-foundation 0.2.2", +] + +[[package]] +name = "objc2-metal" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a0125f776a10d00af4152d74616409f0d4a2053a6f57fa5b7d6aa2854ac04794" +dependencies = [ + "bitflags 2.13.2", + "block2 0.6.2", + "objc2 0.6.5", + "objc2-core-foundation", + "objc2-foundation 0.3.2", +] + +[[package]] +name = "objc2-quartz-core" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e42bee7bff906b14b167da2bac5efe6b6a07e6f7c0a21a7308d40c960242dc7a" +dependencies = [ + "bitflags 2.13.2", + "block2 0.5.1", + "objc2 0.5.3", + "objc2-foundation 0.2.2", + "objc2-metal 0.2.2", +] + +[[package]] +name = "objc2-quartz-core" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "96c1358452b371bf9f104e21ec536d37a650eb10f7ee379fff67d2e08d537f1f" +dependencies = [ + "bitflags 2.13.2", + "objc2 0.6.5", + "objc2-core-foundation", + "objc2-core-graphics", + "objc2-foundation 0.3.2", + "objc2-metal 0.3.2", +] + +[[package]] +name = "objc2-symbols" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0a684efe3dec1b305badae1a28f6555f6ddd3bb2c2267896782858d5a78404dc" +dependencies = [ + "objc2 0.5.3", + "objc2-foundation 0.2.2", +] + +[[package]] +name = "objc2-ui-kit" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8bb46798b20cd6b91cbd113524c490f1686f4c4e8f49502431415f3512e2b6f" +dependencies = [ + "bitflags 2.13.2", + "block2 0.5.1", + "objc2 0.5.3", + "objc2-cloud-kit", + "objc2-core-data", + "objc2-core-image", + "objc2-core-location", + "objc2-foundation 0.2.2", + "objc2-link-presentation", + "objc2-quartz-core 0.2.2", + "objc2-symbols", + "objc2-uniform-type-identifiers", + "objc2-user-notifications", +] + +[[package]] +name = "objc2-uniform-type-identifiers" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "44fa5f9748dbfe1ca6c0b79ad20725a11eca7c2218bceb4b005cb1be26273bfe" +dependencies = [ + "block2 0.5.1", + "objc2 0.5.3", + "objc2-foundation 0.2.2", +] + +[[package]] +name = "objc2-user-notifications" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "76cfcbf642358e8689af64cee815d139339f3ed8ad05103ed5eaf73db8d84cb3" +dependencies = [ + "bitflags 2.13.2", + "block2 0.5.1", + "objc2 0.5.3", + "objc2-core-location", + "objc2-foundation 0.2.2", +] + +[[package]] +name = "object" +version = "0.39.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2e5a6c098c7a3b6547378093f5cc30bc54fd361ce711e05293a5cc589562739b" +dependencies = [ + "memchr", +] + +[[package]] +name = "odometer" +version = "0.0.1" +dependencies = [ + "rune", + "rune-kit", +] + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "opuscule" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "418827b94acaa183462024021324b6e733086466375604eb60e584c7acd4462c" + +[[package]] +name = "orbclient" +version = "0.3.55" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5df339f526ea9a60e371768d50efc2f2508c7203290731565d1f7a6f71d21747" +dependencies = [ + "libc", + "libredox", +] + +[[package]] +name = "ordered-float" +version = "2.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "68f19d67e5a2795c94e73e0bb1cc1a7edeb2e28efd39e2e1c9b7a40c1108b11c" +dependencies = [ + "num-traits", +] + +[[package]] +name = "ordered-float" +version = "5.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8c7c9e0d9b23589f26070720bac724174bfec1083e82f7854cdd0267518343c0" +dependencies = [ + "num-traits", +] + +[[package]] +name = "ordered-stream" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9aa2b01e1d916879f73a53d01d1d6cee68adbb31d6d9177a8cfce093cced1d50" +dependencies = [ + "futures-core", + "pin-project-lite", +] + +[[package]] +name = "os_pipe" +version = "1.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7d8fae84b431384b68627d0f9b3b1245fcf9f46f6c0e3dc902e9dce64edd1967" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "overlay" +version = "0.0.1" +dependencies = [ + "rune", +] + +[[package]] +name = "overlay-lab" +version = "0.0.1" +dependencies = [ + "rune", +] + +[[package]] +name = "owned_ttf_parser" +version = "0.25.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "36820e9051aca1014ddc75770aab4d68bc1e9e632f0f5627c4086bc216fb583b" +dependencies = [ + "ttf-parser", +] + +[[package]] +name = "parking" +version = "2.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f38d5652c16fde515bb1ecef450ab0f6a219d619a7274976324d5e377f7dceba" + +[[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 0.5.18", + "smallvec", + "windows-link", +] + +[[package]] +name = "parlance" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "73072a9470554c8e794778acece2312661218aaabb635600957d952cf01c716e" + +[[package]] +name = "parley" +version = "0.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "61bd0c0c1737f0b3d3726dc06b225083af213b61913e4fbae1670613a106c6ce" +dependencies = [ + "fontique", + "hashbrown 0.17.1", + "linebender_resource_handle", + "parlance", + "parley_engine", + "smallvec", +] + +[[package]] +name = "parley_data" +version = "0.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c43b63f808f6cc8f4a3b07de0d62a977bddd2e0bb5c232bd9e93ba8ef92e5e4b" +dependencies = [ + "icu_collections", + "icu_properties", +] + +[[package]] +name = "parley_emoji" +version = "0.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9c4482d912d7671a7cd2089794f90ef3bb5f5f8c738230fb0fcd50fa020f0ed3" + +[[package]] +name = "parley_engine" +version = "0.12.0" +dependencies = [ + "fontique", + "harfrust", + "hashbrown 0.17.1", + "icu_locale_core", + "icu_normalizer", + "icu_properties", + "icu_segmenter", + "linebender_resource_handle", + "parlance", + "parley_data", + "parley_emoji", + "skrifa", +] + +[[package]] +name = "paste" +version = "1.0.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "57c0d7b74b563b49d38dae00a0c37d4d6de9b432382b2892f0574ddcae73fd0a" + +[[package]] +name = "pastey" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ee67f1008b1ba2321834326597b8e186293b049a023cdef258527550b9935b4" + +[[package]] +name = "percent-encoding" +version = "2.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" + +[[package]] +name = "petgraph" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8701b58ea97060d5e5b155d383a69952a60943f0e6dfe30b04c287beb0b27455" +dependencies = [ + "fixedbitset", + "hashbrown 0.15.5", + "indexmap", +] + +[[package]] +name = "phf" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "010378780309880b08997fae13be7834dba947d36393bd372f2b1556deb2a2f6" +dependencies = [ + "phf_macros", + "phf_shared", + "serde", +] + +[[package]] +name = "phf_generator" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aeb62e0959d5a1bebc965f4d15d9e2b7cea002b6b0f5ba8cde6cc26738467100" +dependencies = [ + "fastrand", + "phf_shared", +] + +[[package]] +name = "phf_macros" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5fa8d0ca26d424d27630da600c6624696e7dec8bf7b3b492b383c5dc49e5e085" +dependencies = [ + "phf_generator", + "phf_shared", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "phf_shared" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6fd9027e2d9319be6349febd1db4e8d02aa544921200c9b777720ac34a3aa89" +dependencies = [ + "siphasher", +] + +[[package]] +name = "pico-args" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5be167a7af36ee22fe3115051bc51f6e6c7054c9348e28deb4f49bd6f705a315" + +[[package]] +name = "pin-project" +version = "1.1.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2466b2336ed02bcdca6b294417127b90ec92038d1d5c4fbeac971a922e0e0924" +dependencies = [ + "pin-project-internal", +] + +[[package]] +name = "pin-project-internal" +version = "1.1.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c96395f0a926bc13b1c17622aaddda1ecb55d49c8f1bf9777e4d877800a43f8b" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "pin-project-lite" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" + +[[package]] +name = "piper" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c835479a4443ded371d6c535cbfd8d31ad92c5d23ae9770a61bc155e4992a3c1" +dependencies = [ + "atomic-waker", + "fastrand", + "futures-io", +] + +[[package]] +name = "pkg-config" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548" + +[[package]] +name = "plain" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b4596b6d070b27117e987119b4dac604f3c58cfb0b191112e24771b2faeac1a6" + +[[package]] +name = "playground" +version = "0.0.1" +dependencies = [ + "rune", +] + +[[package]] +name = "png" +version = "0.17.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "82151a2fc869e011c153adc57cf2789ccb8d9906ce52c0b39a6b5697749d7526" +dependencies = [ + "bitflags 1.3.2", + "crc32fast", + "fdeflate", + "flate2", + "miniz_oxide 0.8.9", +] + +[[package]] +name = "png" +version = "0.18.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "60769b8b31b2a9f263dae2776c37b1b28ae246943cf719eb6946a1db05128a61" +dependencies = [ + "bitflags 2.13.2", + "crc32fast", + "fdeflate", + "flate2", + "miniz_oxide 0.8.9", +] + +[[package]] +name = "polling" +version = "3.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d0e4f59085d47d8241c88ead0f274e8a0cb551f3625263c05eb8dd897c34218" +dependencies = [ + "cfg-if", + "concurrent-queue", + "hermit-abi", + "pin-project-lite", + "rustix 1.1.5", + "windows-sys 0.61.2", +] + +[[package]] +name = "pollster" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bc6355899e1c9462875b6757c79f3caa011a1fdae12bbb1a2e72dd1f234f8336" + +[[package]] +name = "portable-atomic" +version = "1.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "05c8b63e8d9609db387f0324918f81d68fe27748f084ef092fb35954d0539a85" + +[[package]] +name = "portable-atomic-util" +version = "0.2.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10ab3eb7f3becc3a1cbc4f2c6f20267996cfc1a6467a873763411b136a122715" +dependencies = [ + "portable-atomic", +] + +[[package]] +name = "potential_utf" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d83eb9bc6d8e5cf568e7a1101d60ee05e81ed50ea106026f3d18deeb046d7661" +dependencies = [ + "serde_core", + "writeable", + "zerovec", +] + +[[package]] +name = "ppv-lite86" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9" +dependencies = [ + "zerocopy 0.8.63", +] + +[[package]] +name = "presser" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e8cf8e6a8aa66ce33f63993ffc4ea4271eb5b0530a9002db8455ea6050c77bfa" + +[[package]] +name = "proc-macro-crate" +version = "3.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e67ba7e9b2b56446f1d419b1d807906278ffa1a658a8a5d8a39dcb1f5a78614f" +dependencies = [ + "toml_edit", +] + +[[package]] +name = "proc-macro-error-attr3" +version = "3.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e564d14133360e1ae169ffde5da25881b5fa47261665b8e5713c212c27799da" +dependencies = [ + "proc-macro2", + "quote", +] + +[[package]] +name = "proc-macro-error3" +version = "3.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f0d4471b3436c22106b21913b1dda531558918ae9b7ec55d58aa84b43552233" +dependencies = [ + "proc-macro-error-attr3", + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "procwatch" +version = "0.1.0" +dependencies = [ + "libc", + "serde_json", +] + +[[package]] +name = "profiling" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d595e54a326bc53c1c197b32d295e14b169e3cfeaa8dc82b529f947fba6bcf5" + +[[package]] +name = "proptest" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8530004ccb15eae51c7e40009fbe317f341f804db54dc033eec1c50be28cfa0" +dependencies = [ + "bit-set 0.11.1", + "bit-vec 0.10.1", + "bitflags 2.13.2", + "chacha20", + "core_detect", + "num-traits", + "rand 0.10.3", + "rand_xorshift", + "regex-syntax", + "rusty-fork", + "tempfile", + "unarray", +] + +[[package]] +name = "psm" +version = "0.1.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4dcd034599e63b970727f70d79e02d62390a4a84f7c6b827c27c46d5ac3fa622" +dependencies = [ + "ar_archive_writer", + "cc", +] + +[[package]] +name = "pulldown-cmark" +version = "0.13.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "278e9268c93b9e498a2da46c34d90ba93a3255eb99009646398f34bc73ab36eb" +dependencies = [ + "bitflags 2.13.2", + "memchr", + "unicase", +] + +[[package]] +name = "pxfm" +version = "0.1.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d55d956fa96f5ec02be2e13af0e20391a5aa83d6a074e3ad368959d0fab299ea" + +[[package]] +name = "quick-error" +version = "1.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a1d01941d82fa2ab50be1e79e6714289dd7cde78eba4c074bc5a4374f650dfe0" + +[[package]] +name = "quick-error" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a993555f31e5a609f617c12db6250dedcac1b0a85076912c436e6fc9b2c8e6a3" + +[[package]] +name = "quick-xml" +version = "0.41.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e660451e55124f798a69a5af3f49ccfbefbd41910eefd25caf2393e1f3473ec1" +dependencies = [ + "memchr", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "r-efi" +version = "5.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f" + +[[package]] +name = "r-efi" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" + +[[package]] +name = "rand" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9ef1d0d795eb7d84685bca4f72f3649f064e6641543d3a8c415898726a57b41" +dependencies = [ + "rand_chacha", + "rand_core 0.9.5", +] + +[[package]] +name = "rand" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65c9fb96cbc91e3478eaae79a69fcd3f1ae4ad052e471fe6732fff548984b4af" +dependencies = [ + "getrandom 0.4.3", + "rand_core 0.10.1", +] + +[[package]] +name = "rand_chacha" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb" +dependencies = [ + "ppv-lite86", + "rand_core 0.9.5", +] + +[[package]] +name = "rand_core" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c" +dependencies = [ + "getrandom 0.3.4", +] + +[[package]] +name = "rand_core" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69" + +[[package]] +name = "rand_xorshift" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "60aa6af80be32871323012e02e6e65f8a7cc7890931ae421d217ad8fe0df2ccf" +dependencies = [ + "rand_core 0.10.1", +] + +[[package]] +name = "range-alloc" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca45419789ae5a7899559e9512e58ca889e41f04f1f2445e9f4b290ceccd1d08" + +[[package]] +name = "rapidhash" +version = "4.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5da7e78a036ce858e8d55b7e7dc8ba3a88b78350fd2155d3591bbd966b58589e" +dependencies = [ + "rustversion", +] + +[[package]] +name = "rav1d" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1932f060d5e7bd49dc9f8b272c1dc5e9ce0ffe141c28be900265d3989b36c9ed" +dependencies = [ + "assert_matches", + "atomig", + "bitflags 2.13.2", + "cc", + "cfg-if", + "libc", + "nasm-rs", + "parking_lot", + "paste", + "raw-cpuid", + "strum", + "to_method", + "zerocopy 0.7.35", +] + +[[package]] +name = "raw-cpuid" +version = "11.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "498cd0dc59d73224351ee52a95fee0f1a617a2eae0e7d9d720cc622c73a54186" +dependencies = [ + "bitflags 2.13.2", +] + +[[package]] +name = "raw-window-handle" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20675572f6f24e9e76ef639bc5552774ed45f1c30e2951e1e99c59888861c539" + +[[package]] +name = "raw-window-metal" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "40d213455a5f1dc59214213c7330e074ddf8114c9a42411eb890c767357ce135" +dependencies = [ + "objc2 0.6.5", + "objc2-core-foundation", + "objc2-foundation 0.3.2", + "objc2-quartz-core 0.3.2", +] + +[[package]] +name = "read-fonts" +version = "0.41.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "046a7d674daf459825b32f5062056d6882db0d2f5a479fbd76ccfc870ac18709" +dependencies = [ + "bytemuck", + "font-types", + "once_cell", +] + +[[package]] +name = "redox_syscall" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4722d768eff46b75989dd134e5c353f0d6296e5aaa3132e776cbdb56be7731aa" +dependencies = [ + "bitflags 1.3.2", +] + +[[package]] +name = "redox_syscall" +version = "0.5.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d" +dependencies = [ + "bitflags 2.13.2", +] + +[[package]] +name = "redox_syscall" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "580c875845b41ecb1564ad1ae4703044cef774145e3d7a94dc2b3fa7c97868fd" +dependencies = [ + "bitflags 2.13.2", +] + +[[package]] +name = "regex-automata" +version = "0.4.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2" + +[[package]] +name = "regex-syntax" +version = "0.8.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" + +[[package]] +name = "renderdoc-sys" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "19b30a45b0cd0bcca8037f3d0dc3421eaf95327a17cad11964fb8179b4fc4832" + +[[package]] +name = "resvg" +version = "0.45.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a8928798c0a55e03c9ca6c4c6846f76377427d2c1e1f7e6de3c06ae57942df43" +dependencies = [ + "log", + "pico-args", + "rgb", + "svgtypes", + "tiny-skia", + "usvg", +] + +[[package]] +name = "rfd" +version = "0.17.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20dafead71c16a34e1ff357ddefc8afc11e7d51d6d2b9fbd07eaa48e3e540220" +dependencies = [ + "block2 0.6.2", + "dispatch2", + "js-sys", + "libc", + "log", + "objc2 0.6.5", + "objc2-app-kit 0.3.2", + "objc2-core-foundation", + "objc2-foundation 0.3.2", + "percent-encoding", + "raw-window-handle", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", + "windows-sys 0.61.2", +] + +[[package]] +name = "rgb" +version = "0.8.53" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47b34b781b31e5d73e9fbc8689c70551fd1ade9a19e3e28cfec8580a79290cc4" +dependencies = [ + "bytemuck", +] + +[[package]] +name = "rich-clipboard" +version = "0.0.1" +dependencies = [ + "rune", +] + +[[package]] +name = "roxmltree" +version = "0.20.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c20b6793b5c2fa6553b250154b78d6d0db37e72700ae35fad9387a46f487c97" + +[[package]] +name = "roxmltree" +version = "0.21.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9da7f59328b09405b181fee1018925fad50f157afb43c0c0f5c522c256dd5907" +dependencies = [ + "memchr", +] + +[[package]] +name = "rune" +version = "0.0.1" +dependencies = [ + "accesskit", + "accesskit_macos", + "accesskit_unix", + "accesskit_windows", + "arboard", + "async-channel", + "async-executor", + "async-io", + "blake3", + "block2 0.6.2", + "bytemuck", + "console_error_panic_hook", + "dioxus-devtools", + "futures-lite", + "half", + "image", + "js-sys", + "libc", + "libloading", + "log", + "objc2 0.6.5", + "objc2-app-kit 0.3.2", + "objc2-core-foundation", + "objc2-core-graphics", + "objc2-core-video", + "objc2-foundation 0.3.2", + "objc2-metal 0.3.2", + "parley", + "png 0.18.1", + "pollster", + "procwatch", + "raw-window-handle", + "rfd", + "rune-core", + "rune-edit", + "rune-gpu", + "rune-image", + "rune-media", + "rune-motion", + "rune-spell", + "rune-staging", + "rune-taffy", + "rune-text", + "rustc-demangle", + "rustc-hash 2.1.3", + "serde", + "serde_json", + "subsecond", + "swash", + "taffy", + "unicode-segmentation", + "wasm-bindgen", + "wasm-bindgen-futures", + "wayland-backend", + "wayland-client", + "wayland-protocols", + "wayland-protocols-wlr", + "web-sys", + "wgpu", + "windows", + "windows-core", + "windows-sys 0.61.2", + "winit", + "x11rb", + "xkbcommon", + "zbus", + "zeroize", +] + +[[package]] +name = "rune-core" +version = "0.0.1" +dependencies = [ + "js-sys", + "libc", + "portable-atomic", + "rune-motion", + "rustc-hash 2.1.3", + "serde", + "serde_json", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", + "web-time", + "windows-sys 0.61.2", +] + +[[package]] +name = "rune-edit" +version = "0.0.1" +dependencies = [ + "js-sys", + "parley", + "rune-core", + "rune-text", + "serde_json", + "unicode-segmentation", + "zeroize", +] + +[[package]] +name = "rune-fx" +version = "0.0.1" +dependencies = [ + "ab_glyph", + "bytemuck", + "png 0.18.1", + "rune", + "rune-motion", + "rune-staging", + "wgpu", +] + +[[package]] +name = "rune-gpu" +version = "0.0.1" +dependencies = [ + "blake3", + "bytemuck", + "libc", + "objc2 0.6.5", + "objc2-core-foundation", + "objc2-foundation 0.3.2", + "objc2-metal 0.3.2", + "objc2-quartz-core 0.3.2", + "parking_lot", + "pollster", + "raw-window-metal", + "rune-core", + "rune-motion", + "rune-staging", + "wayland-client", + "wayland-protocols", + "wgpu", + "wgpu-naga-bridge", + "windows", + "windows-sys 0.61.2", +] + +[[package]] +name = "rune-highlights" +version = "0.0.1" +dependencies = [ + "unicode-ident", + "wasmparser 0.245.1", +] + +[[package]] +name = "rune-i18n" +version = "0.1.0" +dependencies = [ + "fixed_decimal", + "icu_decimal", + "icu_list", + "icu_locale", + "icu_plurals", + "icu_provider", + "js-sys", + "objc2-foundation 0.3.2", + "serde_json", + "web-sys", + "windows", + "writeable", +] + +[[package]] +name = "rune-image" +version = "0.0.1" +dependencies = [ + "avif-decode", + "blake3", + "image", + "js-sys", + "objc2 0.6.5", + "objc2-foundation 0.3.2", + "png 0.18.1", + "resvg", + "rune-core", + "wasm-bindgen", + "wasm-bindgen-futures", + "windows-sys 0.61.2", +] + +[[package]] +name = "rune-kit" +version = "0.0.1" +dependencies = [ + "icu_normalizer", + "js-sys", + "miniz_oxide 0.9.1", + "procwatch", + "pulldown-cmark", + "resvg", + "rune", + "rune-highlights", + "rune-mermaid", + "rune-motion", + "rune-theme-opencode", + "serde_json", + "skrifa", + "tiny-skia", + "unicode-segmentation", + "wasm-bindgen", + "wasmi", + "web-sys", +] + +[[package]] +name = "rune-knobs" +version = "0.0.1" +dependencies = [ + "rune", + "rune-knobs", +] + +[[package]] +name = "rune-light" +version = "0.0.1" +dependencies = [ + "bytemuck", + "pollster", + "rune", + "rune-fx", + "rune-staging", + "wgpu", + "winit", +] + +[[package]] +name = "rune-luau" +version = "0.0.1" +dependencies = [ + "js-sys", + "mlua", + "notify", + "rune", + "rustc-hash 2.1.3", + "serde", + "serde_json", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", +] + +[[package]] +name = "rune-mac" +version = "0.0.1" +dependencies = [ + "objc2 0.6.5", + "rune-notify", +] + +[[package]] +name = "rune-media" +version = "0.0.1" +dependencies = [ + "ash", + "block2 0.6.2", + "bytemuck", + "libc", + "objc2 0.6.5", + "objc2-av-foundation", + "objc2-core-foundation", + "objc2-core-graphics", + "objc2-core-media", + "objc2-core-video", + "objc2-foundation 0.3.2", + "objc2-io-surface", + "objc2-metal 0.3.2", + "opuscule", + "pollster", + "rune-core", + "rune-gpu", + "rune-image", + "rune-staging", + "symphonia", + "wgpu", + "windows", + "windows-sys 0.61.2", +] + +[[package]] +name = "rune-mermaid" +version = "0.0.1" +dependencies = [ + "rune", +] + +[[package]] +name = "rune-motion" +version = "0.1.0" +dependencies = [ + "serde", +] + +[[package]] +name = "rune-notify" +version = "0.0.1" +dependencies = [ + "block2 0.6.2", + "objc2 0.6.5", + "windows", + "windows-core", + "windows-registry", +] + +[[package]] +name = "rune-perf" +version = "0.1.0" +dependencies = [ + "procwatch", + "serde_json", + "tempfile", +] + +[[package]] +name = "rune-ref" +version = "0.0.1" +dependencies = [ + "blake3", + "gungraun", + "half", + "libm", + "proptest", + "rune", + "rune-fx", + "serde", + "serde_json", + "wgpu", +] + +[[package]] +name = "rune-register" +version = "0.1.0" +dependencies = [ + "linkme", +] + +[[package]] +name = "rune-spell" +version = "0.0.1" +dependencies = [ + "js-sys", + "objc2-app-kit 0.3.2", + "objc2-foundation 0.3.2", + "rune-core", + "rustc-hash 2.1.3", + "spellbook", + "unicode-segmentation", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", + "windows", + "windows-sys 0.61.2", +] + +[[package]] +name = "rune-staging" +version = "0.0.1" +dependencies = [ + "wgpu", + "windows", +] + +[[package]] +name = "rune-taffy" +version = "0.0.1" +dependencies = [ + "stacker", + "taffy", +] + +[[package]] +name = "rune-text" +version = "0.0.1" +dependencies = [ + "bytemuck", + "fontique", + "icu_properties", + "icu_segmenter", + "objc2 0.6.5", + "objc2-core-foundation", + "objc2-core-text", + "parley", + "parley_engine", + "rune-core", + "rune-image", + "rune-motion", + "rustc-hash 2.1.3", + "serde_json", + "skrifa", + "swash", + "tiny-skia-path 0.11.4", + "unicode-segmentation", + "wasm-bindgen", + "windows", + "windows-core", + "windows-sys 0.61.2", + "zeroize", +] + +[[package]] +name = "rune-theme-opencode" +version = "0.0.1" +dependencies = [ + "rune", + "rune-kit", + "serde_json", +] + +[[package]] +name = "rune-www" +version = "0.0.1" +dependencies = [ + "rune", + "rune-kit", + "rune-motion", + "wasm-bindgen", +] + +[[package]] +name = "rustc-demangle" +version = "0.1.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b74b56ffa8bb2830709a538c2cbcae9aa062db0d2a42563bfb09bdaae44020eb" + +[[package]] +name = "rustc-hash" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08d43f7aa6b08d49f382cde6a7982047c3426db949b1424bc4b7ec9ae12c6ce2" + +[[package]] +name = "rustc-hash" +version = "2.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d" + +[[package]] +name = "rustc_version" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92" +dependencies = [ + "semver", +] + +[[package]] +name = "rustix" +version = "0.38.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fdb5bc1ae2baa591800df16c9ca78619bf65c0488b41b96ccec5d11220d8c154" +dependencies = [ + "bitflags 2.13.2", + "errno", + "libc", + "linux-raw-sys 0.4.15", + "windows-sys 0.59.0", +] + +[[package]] +name = "rustix" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "891efababe418670775f199f0d233d84843c227a0949a883ce15b37c78d6629d" +dependencies = [ + "bitflags 2.13.2", + "errno", + "libc", + "linux-raw-sys 0.12.1", + "windows-sys 0.61.2", +] + +[[package]] +name = "rustversion" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" + +[[package]] +name = "rusty-fork" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc6bf79ff24e648f6da1f8d1f011e9cac26491b619e6b9280f2b47f1774e6ee2" +dependencies = [ + "fnv", + "quick-error 1.2.3", + "tempfile", + "wait-timeout", +] + +[[package]] +name = "ryu" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" + +[[package]] +name = "same-file" +version = "1.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502" +dependencies = [ + "winapi-util", +] + +[[package]] +name = "scoped-tls" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e1cf6437eb19a8f4a6cc0f7dca544973b0b78843adbfeb3683d1a94a0024a294" + +[[package]] +name = "scopeguard" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" + +[[package]] +name = "sctk-adwaita" +version = "0.10.1" +dependencies = [ + "log", + "smithay-client-toolkit", + "tiny-skia", +] + +[[package]] +name = "semver" +version = "1.0.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde-value" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f3a1a3341211875ef120e117ea7fd5228530ae7e7036a779fdc9117be6b3282c" +dependencies = [ + "ordered-float 2.10.1", + "serde", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "serde_json" +version = "1.0.154" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "serde_repr" +version = "0.1.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8d3b1629de253c70a0508c3899572da79ca359fdab27c7920ff00406df418906" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "settings" +version = "0.0.1" +dependencies = [ + "procwatch", + "rune", +] + +[[package]] +name = "sha1" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a978451301f4db1d02937a4ab3ccce137717b81826e79b7d49ffe3244a13c3b8" +dependencies = [ + "cfg-if", + "cpufeatures 0.2.17", + "digest", +] + +[[package]] +name = "shapes" +version = "0.0.1" +dependencies = [ + "rune", +] + +[[package]] +name = "shlex" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" + +[[package]] +name = "showreel" +version = "0.0.1" +dependencies = [ + "rune", + "rune-fx", + "rune-motion", + "wgpu", +] + +[[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]] +name = "simd-adler32" +version = "0.3.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea" + +[[package]] +name = "simd_cesu8" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "11031e251abf8611c80f460e19dbdeb54a66db918e49c65a7065b46ac7aec520" +dependencies = [ + "rustc_version", + "simdutf8", +] + +[[package]] +name = "simdutf8" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e" + +[[package]] +name = "simplecss" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7a9c6883ca9c3c7c90e888de77b7a5c849c779d25d74a1269b0218b14e8b136c" +dependencies = [ + "log", +] + +[[package]] +name = "siphasher" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33f4fe9184a62d842c9ef383018f3306d8ba224fd9d836f56d7288308847c256" + +[[package]] +name = "site-scenes" +version = "0.0.1" +dependencies = [ + "rune", + "rune-fx", + "rune-light", + "wgpu", +] + +[[package]] +name = "sketch" +version = "0.0.1" +dependencies = [ + "rune", +] + +[[package]] +name = "skrifa" +version = "0.44.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "819ab7d62b1d3e72d9d9dea5650bac30424f9111364bb94928dbf5ecad1baa68" +dependencies = [ + "bytemuck", + "read-fonts", +] + +[[package]] +name = "slab" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" + +[[package]] +name = "slotmap" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bdd58c3c93c3d278ca835519292445cb4b0d4dc59ccfdf7ceadaab3f8aeb4038" +dependencies = [ + "serde", + "version_check", +] + +[[package]] +name = "smallvec" +version = "1.16.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5b3dc8af474f516a851ff4bd12db780f948b9250ad37211e4eec0bccea54e01b" + +[[package]] +name = "smithay-client-toolkit" +version = "0.19.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3457dea1f0eb631b4034d61d4d8c32074caa6cd1ab2d59f2327bd8461e2c0016" +dependencies = [ + "bitflags 2.13.2", + "calloop", + "calloop-wayland-source", + "cursor-icon", + "libc", + "log", + "memmap2", + "rustix 0.38.44", + "thiserror 1.0.69", + "wayland-backend", + "wayland-client", + "wayland-csd-frame", + "wayland-cursor", + "wayland-protocols", + "wayland-protocols-wlr", + "wayland-scanner", + "xkeysym", +] + +[[package]] +name = "smol_str" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dd538fb6910ac1099850255cf94a94df6551fbdd602454387d0adb2d1ca6dead" +dependencies = [ + "serde", +] + +[[package]] +name = "spellbook" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d204abcbdf8e88729306a8d0ca01a79d8a49969fe1f84696909d6dbc4321c1a" +dependencies = [ + "foldhash 0.2.0", + "hashbrown 0.17.1", +] + +[[package]] +name = "spin" +version = "0.9.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3763264f6b73151db08c50ff20d7d8a0b8796e021cdea7ceedad07b80155fa0e" + +[[package]] +name = "spirv" +version = "0.4.0+sdk-1.4.341.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d9571ea910ebd84c86af4b3ed27f9dbdc6ad06f17c5f96146b2b671e2976744f" +dependencies = [ + "bitflags 2.13.2", +] + +[[package]] +name = "stable_deref_trait" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" + +[[package]] +name = "stacker" +version = "0.1.25" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "707f49d46706bacf8a2b00d51dace3f9de527c13eec3778f570c411f89e69967" +dependencies = [ + "cc", + "cfg-if", + "libc", + "psm", + "windows-sys 0.61.2", +] + +[[package]] +name = "static_assertions" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f" + +[[package]] +name = "strict-num" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6637bab7722d379c8b41ba849228d680cc12d0a45ba1fa2b48f2a30577a06731" +dependencies = [ + "float-cmp", +] + +[[package]] +name = "strum" +version = "0.26.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8fec0f0aef304996cf250b31b5a10dee7980c85da9d759361292b8bca5a18f06" +dependencies = [ + "strum_macros", +] + +[[package]] +name = "strum_macros" +version = "0.26.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4c6bee85a5a24955dc440386795aa378cd9cf82acd5f764469152d2270e581be" +dependencies = [ + "heck", + "proc-macro2", + "quote", + "rustversion", + "syn 2.0.119", +] + +[[package]] +name = "subsecond" +version = "0.7.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d350d5788fa94d560d92269266a50efc77b036bfca6675e420b64df7b3211f37" +dependencies = [ + "js-sys", + "libc", + "libloading", + "memfd", + "memmap2", + "serde", + "subsecond-types", + "thiserror 2.0.21", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", +] + +[[package]] +name = "subsecond-types" +version = "0.7.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dcf32d66269b5fbb8558334e8d22b657b2f7af0dd2ef56c231541099a862e464" +dependencies = [ + "serde", +] + +[[package]] +name = "svgtypes" +version = "0.15.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "68c7541fff44b35860c1a7a47a7cadf3e4a304c457b58f9870d9706ece028afc" +dependencies = [ + "kurbo", + "siphasher", +] + +[[package]] +name = "swash" +version = "0.2.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c2499c2d826531388872b2268718aed907a39bd785ab0dcfe57fab26283f92e" +dependencies = [ + "skrifa", + "yazi", + "zeno", +] + +[[package]] +name = "symphonia" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5773a4c030a19d9bfaa090f49746ff35c75dfddfa700df7a5939d5e076a57039" +dependencies = [ + "lazy_static", + "symphonia-codec-vorbis", + "symphonia-core", + "symphonia-format-mkv", + "symphonia-format-ogg", + "symphonia-metadata", +] + +[[package]] +name = "symphonia-codec-vorbis" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f025837c309cd69ffef572750b4a2257b59552c5399a5e49707cc5b1b85d1c73" +dependencies = [ + "log", + "symphonia-core", + "symphonia-utils-xiph", +] + +[[package]] +name = "symphonia-core" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ea00cc4f79b7f6bb7ff87eddc065a1066f3a43fe1875979056672c9ef948c2af" +dependencies = [ + "arrayvec", + "bitflags 1.3.2", + "bytemuck", + "lazy_static", + "log", +] + +[[package]] +name = "symphonia-format-mkv" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "122d786d2c43a49beb6f397551b4a050d8229eaa54c7ddf9ee4b98899b8742d0" +dependencies = [ + "lazy_static", + "log", + "symphonia-core", + "symphonia-metadata", + "symphonia-utils-xiph", +] + +[[package]] +name = "symphonia-format-ogg" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b4955c67c1ed3aa8ae8428d04ca8397fbef6a19b2b051e73b5da8b1435639cb" +dependencies = [ + "log", + "symphonia-core", + "symphonia-metadata", + "symphonia-utils-xiph", +] + +[[package]] +name = "symphonia-metadata" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "36306ff42b9ffe6e5afc99d49e121e0bd62fe79b9db7b9681d48e29fa19e6b16" +dependencies = [ + "encoding_rs", + "lazy_static", + "log", + "symphonia-core", +] + +[[package]] +name = "symphonia-utils-xiph" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee27c85ab799a338446b68eec77abf42e1a6f1bb490656e121c6e27bfbab9f16" +dependencies = [ + "symphonia-core", + "symphonia-metadata", +] + +[[package]] +name = "syn" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "3.0.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d78c8dee4c7bf0e14673097256fed6142ce9d3b85a408189d07482442145823b" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "synstructure" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "901704edd0dfe137f1987838ee4f259e4e063c31371bdb423f7ae38ec6f77f02" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "taffy" +version = "0.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c8480887e8803986d96a7173729565520d4bbb721ad6b7ad6941a22897207aa" +dependencies = [ + "serde", + "slotmap", + "smallvec", +] + +[[package]] +name = "tempfile" +version = "3.27.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" +dependencies = [ + "fastrand", + "getrandom 0.4.3", + "once_cell", + "rustix 1.1.5", + "windows-sys 0.61.2", +] + +[[package]] +name = "termcolor" +version = "1.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06794f8f6c5c898b3275aebefa6b8a1cb24cd2c6c79397ab15774837a0bc5755" +dependencies = [ + "winapi-util", +] + +[[package]] +name = "thiserror" +version = "1.0.69" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52" +dependencies = [ + "thiserror-impl 1.0.69", +] + +[[package]] +name = "thiserror" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e" +dependencies = [ + "thiserror-impl 2.0.21", +] + +[[package]] +name = "thiserror-impl" +version = "1.0.69" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "tiff" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b63feaf3343d35b6ca4d50483f94843803b0f51634937cc2ec519fc32232bc52" +dependencies = [ + "fax", + "flate2", + "half", + "quick-error 2.0.1", + "weezl", + "zune-jpeg", +] + +[[package]] +name = "tiny-skia" +version = "0.11.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "83d13394d44dae3207b52a326c0c85a8bf87f1541f23b0d143811088497b09ab" +dependencies = [ + "arrayref", + "arrayvec", + "bytemuck", + "cfg-if", + "log", + "png 0.17.16", + "tiny-skia-path 0.11.4 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "tiny-skia-path" +version = "0.11.4" +dependencies = [ + "arrayref", + "bytemuck", + "strict-num", +] + +[[package]] +name = "tiny-skia-path" +version = "0.11.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9c9e7fc0c2e86a30b117d0462aa261b72b7a99b7ebd7deb3a14ceda95c5bdc93" +dependencies = [ + "arrayref", + "bytemuck", + "strict-num", +] + +[[package]] +name = "tinystr" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1e27c91459209c2986af3dcf603a5a74a4368754ce37414f59acc971167f643" +dependencies = [ + "displaydoc", + "serde_core", + "zerovec", +] + +[[package]] +name = "to_method" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c7c4ceeeca15c8384bbc3e011dbd8fccb7f068a440b752b7d9b32ceb0ca0e2e8" + +[[package]] +name = "todo" +version = "0.0.1" +dependencies = [ + "rune", +] + +[[package]] +name = "tokio" +version = "1.54.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b52fd3255258d26fac7264ab5a76b53c13367136dc011d3d6ad4f8ed070396a3" +dependencies = [ + "pin-project-lite", +] + +[[package]] +name = "toml_datetime" +version = "1.1.2+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b86d767906c6c42421dcba507eb9d203e779497710a47782a224bb871653053" +dependencies = [ + "serde_core", +] + +[[package]] +name = "toml_edit" +version = "0.25.17+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3641d5bbb5349a79e1020a242d251efbc546ad8048d133958323ce9c40a9c9c" +dependencies = [ + "indexmap", + "toml_datetime", + "toml_parser", + "winnow", +] + +[[package]] +name = "toml_parser" +version = "1.1.5+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "baa693a8032d7e1cada7d0041e96126df243179ff061456783ac7f12bda4744c" +dependencies = [ + "winnow", +] + +[[package]] +name = "tracing" +version = "0.1.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" +dependencies = [ + "pin-project-lite", + "tracing-attributes", + "tracing-core", +] + +[[package]] +name = "tracing-attributes" +version = "0.1.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "tracing-core" +version = "0.1.36" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" +dependencies = [ + "once_cell", +] + +[[package]] +name = "tree_magic_mini" +version = "3.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8765b90061cba6c22b5831f675da109ae5561588290f9fa2317adab2714d5a6" +dependencies = [ + "memchr", + "nom", + "petgraph", +] + +[[package]] +name = "ttf-parser" +version = "0.25.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2df906b07856748fa3f6e0ad0cbaa047052d4a7dd609e231c4f72cee8c36f31" + +[[package]] +name = "tungstenite" +version = "0.28.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8628dcc84e5a09eb3d8423d6cb682965dea9133204e8fb3efee74c2a0c259442" +dependencies = [ + "bytes", + "data-encoding", + "http", + "httparse", + "log", + "rand 0.9.5", + "sha1", + "thiserror 2.0.21", + "utf-8", +] + +[[package]] +name = "typeid" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bc7d623258602320d5c55d1bc22793b57daff0ec7efc270ea7d55ce1d5f5471c" + +[[package]] +name = "typenum" +version = "1.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" + +[[package]] +name = "uds_windows" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2f6fb2847f6742cd76af783a2a2c49e9375d0a111c7bef6f71cd9e738c72d6e" +dependencies = [ + "memoffset", + "tempfile", + "windows-sys 0.61.2", +] + +[[package]] +name = "unarray" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eaea85b334db583fe3274d12b4cd1880032beab409c0d774be044d4480ab9a94" + +[[package]] +name = "unicase" +version = "2.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "357cc3acc6a036009fd6c973ed009037c732d60d0b4f6c673e9041497482a28f" + +[[package]] +name = "unicode-ident" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" + +[[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.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b4ac048d71ede7ee76d585517add45da530660ef4390e49b098733c6e897f254" + +[[package]] +name = "unicode-xid" +version = "0.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853" + +[[package]] +name = "unty-next" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "16062d030850f35054e37746427b9febb74a2f24c9c6dd6fa2d0c13c5f53221e" + +[[package]] +name = "usvg" +version = "0.45.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "80be9b06fbae3b8b303400ab20778c80bbaf338f563afe567cf3c9eea17b47ef" +dependencies = [ + "base64", + "data-url", + "flate2", + "imagesize", + "kurbo", + "log", + "pico-args", + "roxmltree 0.20.0", + "simplecss", + "siphasher", + "strict-num", + "svgtypes", + "tiny-skia-path 0.11.4 (registry+https://github.com/rust-lang/crates.io-index)", + "xmlwriter", +] + +[[package]] +name = "utf-8" +version = "0.7.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09cc8ee72d2a9becf2f2febe0205bbed8fc6615b7cb429ad062dc7b7ddd036a9" + +[[package]] +name = "utf8_iter" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be" + +[[package]] +name = "uuid" +version = "1.28.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7cc1186384beb7dd8eedea376413fd654937285ea6c9cfbb928dc3043ea4b606" +dependencies = [ + "js-sys", + "serde_core", + "wasm-bindgen", +] + +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + +[[package]] +name = "video-player" +version = "0.0.1" +dependencies = [ + "rune", +] + +[[package]] +name = "video-tiles" +version = "0.0.1" +dependencies = [ + "rune", + "serde_json", + "wgpu", +] + +[[package]] +name = "wait-timeout" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ac3b126d3914f9849036f826e054cbabdc8519970b8998ddaf3b5bd3c65f11" +dependencies = [ + "libc", +] + +[[package]] +name = "walkdir" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29790946404f91d9c5d06f9874efddea1dc06c5efe94541a7d6863108e3a5e4b" +dependencies = [ + "same-file", + "winapi-util", +] + +[[package]] +name = "warnings" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "64f68998838dab65727c9b30465595c6f7c953313559371ca8bf31759b3680ad" +dependencies = [ + "pin-project", + "tracing", + "warnings-macro", +] + +[[package]] +name = "warnings-macro" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59195a1db0e95b920366d949ba5e0d3fc0e70b67c09be15ce5abb790106b0571" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + +[[package]] +name = "wasip2" +version = "1.0.4+wasi-0.2.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b67efb37e106e55ce722a510d6b5f9c17f083e5fc79afc2badeb12cc313d9487" +dependencies = [ + "wit-bindgen", +] + +[[package]] +name = "wasm-bindgen" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9bb54f33acc68fd454578d9820b0bde1a1a3d17aa17bb7b6595806d02886d409" +dependencies = [ + "cfg-if", + "once_cell", + "rustversion", + "wasm-bindgen-macro", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-futures" +version = "0.4.79" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3cbab34de2d982e9b48e18d216d04c4a6f641066ff19ffb699980f591ee3610e" +dependencies = [ + "js-sys", + "tokio", + "wasm-bindgen", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2e29d0c35b16e224a7eeb5cd2d25e3e1968fbd65604117b44d3b789d00ee8535" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6f501a8bc3719dba86ef8ae4728879c08001bea749eb1333ac5b91e040e2a6b7" +dependencies = [ + "bumpalo", + "proc-macro2", + "quote", + "syn 3.0.9", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23f0c9c52aa7cd7d77769a4cfe2a9adb1b331f489a41d912ce14513d5ab995c6" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "wasmi" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2300d0f78cba12f14e29e8dd157ea64050c0a688179aefdb2050105805594a0c" +dependencies = [ + "spin", + "wasmi_collections", + "wasmi_core", + "wasmi_ir", + "wasmparser 0.239.0", +] + +[[package]] +name = "wasmi_collections" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8a8c42a2a76148d43097b1d7cc2a5bf33d5c23bd4dd69015fc887e311767884" + +[[package]] +name = "wasmi_core" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9013136083d988725953390bf668b64b7a218fabf26f8b913bbc59546b97ee27" +dependencies = [ + "libm", +] + +[[package]] +name = "wasmi_ir" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba1fa003f79156f406d62ef0e1464dc03e11ace37170e9fa7524299a75ad8f68" +dependencies = [ + "wasmi_core", +] + +[[package]] +name = "wasmparser" +version = "0.239.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8c9d90bb93e764f6beabf1d02028c70a2156a6583e63ac4218dd07ef733368b0" +dependencies = [ + "bitflags 2.13.2", +] + +[[package]] +name = "wasmparser" +version = "0.245.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4f08c9adee0428b7bddf3890fc27e015ac4b761cc608c822667102b8bfd6995e" +dependencies = [ + "bitflags 2.13.2", + "indexmap", +] + +[[package]] +name = "wayland-backend" +version = "0.3.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38a91b4eaddff87b1cd1074985e3713da4af2c49742d1b356b2c01670a67a078" +dependencies = [ + "cc", + "downcast-rs", + "rustix 1.1.5", + "scoped-tls", + "smallvec", + "wayland-sys", +] + +[[package]] +name = "wayland-client" +version = "0.31.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3c36a0f861ad76d0901f2800b46321410d9f73f2ea88aac0650d86c32688073" +dependencies = [ + "bitflags 2.13.2", + "rustix 1.1.5", + "wayland-backend", + "wayland-scanner", +] + +[[package]] +name = "wayland-csd-frame" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "625c5029dbd43d25e6aa9615e88b829a5cad13b2819c4ae129fdbb7c31ab4c7e" +dependencies = [ + "bitflags 2.13.2", + "cursor-icon", + "wayland-backend", +] + +[[package]] +name = "wayland-cursor" +version = "0.31.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a52d18780be9b1314328a3de5f930b73d2200112e3849ca6cb11822793fb34d" +dependencies = [ + "rustix 1.1.5", + "wayland-client", + "xcursor", +] + +[[package]] +name = "wayland-protocols" +version = "0.32.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23d0c813de3daa2ed6520af85a3bd49b0e722a3078506899aa9686fea58dc4b6" +dependencies = [ + "bitflags 2.13.2", + "wayland-backend", + "wayland-client", + "wayland-scanner", +] + +[[package]] +name = "wayland-protocols-plasma" +version = "0.3.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b6d8cf1eb2c1c31ed1f5643c88a6e53538129d4af80030c8cabd1f9fa884d91" +dependencies = [ + "bitflags 2.13.2", + "wayland-backend", + "wayland-client", + "wayland-protocols", + "wayland-scanner", +] + +[[package]] +name = "wayland-protocols-wlr" +version = "0.3.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eb04e52f7836d7c7976c78ca0250d61e33873c34156a2a1fc9474828ec268234" +dependencies = [ + "bitflags 2.13.2", + "wayland-backend", + "wayland-client", + "wayland-protocols", + "wayland-scanner", +] + +[[package]] +name = "wayland-scanner" +version = "0.31.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "338e30461b3a2b67d70eb30a6d89f8e0c93a833e07d2ae89085cd070c4a00ac0" +dependencies = [ + "proc-macro2", + "quick-xml", + "quote", +] + +[[package]] +name = "wayland-sys" +version = "0.31.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d8eab23fefc9e41f8e841df4a9c707e8a8c4ed26e944ef69297184de2785e3be" +dependencies = [ + "dlib", + "log", + "once_cell", + "pkg-config", +] + +[[package]] +name = "web-hello" +version = "0.0.1" +dependencies = [ + "rune", + "wasm-bindgen", +] + +[[package]] +name = "web-showcase" +version = "0.0.1" +dependencies = [ + "rune", + "wasm-bindgen", +] + +[[package]] +name = "web-sys" +version = "0.3.106" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "88261b9deccee56594c11a3460c462c41f58d148598fe70ad77070126a68aba4" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "web-time" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a6580f308b1fad9207618087a65c04e7a10bc77e02c8e84e9b00dd4b12fa0bb" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "weezl" +version = "0.1.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a28ac98ddc8b9274cb41bb4d9d4d5c425b6020c50c46f25559911905610b4a88" + +[[package]] +name = "wgpu" +version = "30.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "527ccdf43dd5b2e8676eed9984ce00e2bbb0a1b85b70c1969dcb6cd2eb55ab9e" +dependencies = [ + "arrayvec", + "bitflags 2.13.2", + "bytemuck", + "cfg-if", + "cfg_aliases", + "document-features", + "hashbrown 0.17.1", + "js-sys", + "log", + "naga", + "parking_lot", + "portable-atomic", + "profiling", + "raw-window-handle", + "smallvec", + "static_assertions", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", + "wgpu-core", + "wgpu-hal", + "wgpu-types", +] + +[[package]] +name = "wgpu-core" +version = "30.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "14c018fce9b6270aa203c2fdd56f3cce996713534bd757e4ea58c8560b121f14" +dependencies = [ + "arrayvec", + "bit-set 0.10.0", + "bit-vec 0.9.1", + "bitflags 2.13.2", + "bytemuck", + "cfg_aliases", + "document-features", + "hashbrown 0.17.1", + "indexmap", + "log", + "naga", + "naga-types", + "once_cell", + "parking_lot", + "portable-atomic", + "profiling", + "raw-window-handle", + "rustc-hash 1.1.0", + "smallvec", + "thiserror 2.0.21", + "wgpu-core-deps-apple", + "wgpu-core-deps-wasm", + "wgpu-core-deps-windows-linux-android", + "wgpu-hal", + "wgpu-naga-bridge", + "wgpu-types", +] + +[[package]] +name = "wgpu-core-deps-apple" +version = "30.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "061f3d319a40d39d00b1ecc2c33b89fe21d4e6fe01859df3500a3a8ecccd6b68" +dependencies = [ + "wgpu-hal", +] + +[[package]] +name = "wgpu-core-deps-wasm" +version = "30.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d260ca2ca8adc654f513a869bf3cac0b47f5b8d3f87803d6942015f8de597aae" +dependencies = [ + "wgpu-hal", +] + +[[package]] +name = "wgpu-core-deps-windows-linux-android" +version = "30.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7586165fd5f6d881cb9ce4bb71f40d6caab2c0f1837e3fc1d9788a197fb6004f" +dependencies = [ + "wgpu-hal", +] + +[[package]] +name = "wgpu-hal" +version = "30.0.1" +dependencies = [ + "android_system_properties", + "arrayvec", + "ash", + "bit-set 0.10.0", + "bitflags 2.13.2", + "block2 0.6.2", + "bytemuck", + "cfg-if", + "cfg_aliases", + "glow", + "glutin_wgl_sys", + "gpu-allocator", + "hashbrown 0.17.1", + "js-sys", + "khronos-egl", + "libc", + "libloading", + "log", + "naga", + "naga-types", + "ndk-sys", + "objc2 0.6.5", + "objc2-core-foundation", + "objc2-core-graphics", + "objc2-foundation 0.3.2", + "objc2-metal 0.3.2", + "objc2-quartz-core 0.3.2", + "once_cell", + "ordered-float 5.5.0", + "parking_lot", + "portable-atomic", + "portable-atomic-util", + "profiling", + "range-alloc", + "raw-window-handle", + "raw-window-metal", + "renderdoc-sys", + "smallvec", + "static_assertions", + "thiserror 2.0.21", + "wasm-bindgen", + "wayland-sys", + "web-sys", + "wgpu-naga-bridge", + "wgpu-types", + "windows", + "windows-core", + "windows-result", +] + +[[package]] +name = "wgpu-naga-bridge" +version = "30.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2f62e73117bb7a62bfd9c5a5841438a823f6566c6442a808ee269d2d055c081" +dependencies = [ + "naga", + "wgpu-types", +] + +[[package]] +name = "wgpu-types" +version = "30.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "99dad6f1fbdbbdb4c278a6508b059d44688f5cebddf78d005a46a31340269286" +dependencies = [ + "bitflags 2.13.2", + "bytemuck", + "js-sys", + "log", + "naga-types", + "raw-window-handle", + "static_assertions", + "web-sys", +] + +[[package]] +name = "winapi-util" +version = "0.1.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "windows" +version = "0.62.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "527fadee13e0c05939a6a05d5bd6eec6cd2e3dbd648b9f8e447c6518133d8580" +dependencies = [ + "windows-collections", + "windows-core", + "windows-future", + "windows-numerics", +] + +[[package]] +name = "windows-collections" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23b2d95af1a8a14a3c7367e1ed4fc9c20e0a26e79551b1454d72583c97cc6610" +dependencies = [ + "windows-core", +] + +[[package]] +name = "windows-core" +version = "0.62.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb" +dependencies = [ + "windows-implement", + "windows-interface", + "windows-link", + "windows-result", + "windows-strings", +] + +[[package]] +name = "windows-future" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e1d6f90251fe18a279739e78025bd6ddc52a7e22f921070ccdc67dde84c605cb" +dependencies = [ + "windows-core", + "windows-link", + "windows-threading", +] + +[[package]] +name = "windows-implement" +version = "0.60.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "windows-interface" +version = "0.59.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-numerics" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e2e40844ac143cdb44aead537bbf727de9b044e107a0f1220392177d15b0f26" +dependencies = [ + "windows-core", + "windows-link", +] + +[[package]] +name = "windows-registry" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "02752bf7fbdcce7f2a27a742f798510f3e5ad88dbe84871e5168e2120c3d5720" +dependencies = [ + "windows-link", + "windows-result", + "windows-strings", +] + +[[package]] +name = "windows-result" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-strings" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-sys" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" +dependencies = [ + "windows-targets", +] + +[[package]] +name = "windows-sys" +version = "0.59.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b" +dependencies = [ + "windows-targets", +] + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-targets" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" +dependencies = [ + "windows_aarch64_gnullvm", + "windows_aarch64_msvc", + "windows_i686_gnu", + "windows_i686_gnullvm", + "windows_i686_msvc", + "windows_x86_64_gnu", + "windows_x86_64_gnullvm", + "windows_x86_64_msvc", +] + +[[package]] +name = "windows-threading" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3949bd5b99cafdf1c7ca86b43ca564028dfe27d66958f2470940f73d86d75b37" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" + +[[package]] +name = "windows_i686_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" + +[[package]] +name = "windows_i686_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" + +[[package]] +name = "winit" +version = "0.30.13" +dependencies = [ + "ahash", + "android-activity", + "atomic-waker", + "bitflags 2.13.2", + "block2 0.5.1", + "bytemuck", + "calloop", + "cfg_aliases", + "concurrent-queue", + "core-foundation", + "core-graphics", + "cursor-icon", + "dpi", + "js-sys", + "libc", + "memmap2", + "ndk", + "objc2 0.5.3", + "objc2-app-kit 0.2.2", + "objc2-foundation 0.2.2", + "objc2-ui-kit", + "orbclient", + "percent-encoding", + "pin-project", + "raw-window-handle", + "redox_syscall 0.4.1", + "rustix 0.38.44", + "sctk-adwaita", + "smithay-client-toolkit", + "smol_str", + "tracing", + "unicode-segmentation", + "wasm-bindgen", + "wasm-bindgen-futures", + "wayland-backend", + "wayland-client", + "wayland-protocols", + "wayland-protocols-plasma", + "web-sys", + "web-time", + "windows-sys 0.52.0", + "x11-dl", + "x11rb", + "xkbcommon-dl", +] + +[[package]] +name = "winnow" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23b97319f7b8343df12cc98938e5c3eb436064524c8d2b4e30a1d3a36eecdf81" +dependencies = [ + "memchr", +] + +[[package]] +name = "wit-bindgen" +version = "0.57.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e" + +[[package]] +name = "wl-clipboard-rs" +version = "0.9.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4d7888ccd4896447b2d14d3a9350a85df2aeb6f181e2e7a31349d104ac46cac1" +dependencies = [ + "libc", + "log", + "os_pipe", + "rustix 1.1.5", + "thiserror 2.0.21", + "tree_magic_mini", + "wayland-backend", + "wayland-client", + "wayland-protocols", + "wayland-protocols-wlr", +] + +[[package]] +name = "writeable" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc" + +[[package]] +name = "x11-dl" +version = "2.21.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38735924fedd5314a6e548792904ed8c6de6636285cb9fec04d5b1db85c1516f" +dependencies = [ + "libc", + "once_cell", + "pkg-config", +] + +[[package]] +name = "x11rb" +version = "0.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9993aa5be5a26815fe2c3eacfc1fde061fc1a1f094bf1ad2a18bf9c495dd7414" +dependencies = [ + "as-raw-xcb-connection", + "gethostname", + "libc", + "libloading", + "once_cell", + "rustix 1.1.5", + "x11rb-protocol", +] + +[[package]] +name = "x11rb-protocol" +version = "0.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ea6fc2961e4ef194dcbfe56bb845534d0dc8098940c7e5c012a258bfec6701bd" + +[[package]] +name = "xcursor" +version = "0.3.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "163b33ed8786455e2fa5d72f554057ce3f3182425434f756cd39c99839d88e23" + +[[package]] +name = "xkbcommon" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7a974f48060a14e95705c01f24ad9c3345022f4d97441b8a36beb7ed5c4a02d" +dependencies = [ + "libc", + "memmap2", + "xkeysym", +] + +[[package]] +name = "xkbcommon-dl" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d039de8032a9a8856a6be89cea3e5d12fdd82306ab7c94d74e6deab2460651c5" +dependencies = [ + "bitflags 2.13.2", + "dlib", + "log", + "once_cell", + "xkeysym", +] + +[[package]] +name = "xkeysym" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9cc00251562a284751c9973bace760d86c0276c471b4be569fe6b068ee97a56" + +[[package]] +name = "xml-rs" +version = "0.8.29" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e450f9b2ed1dff33c94c12589a87338689467b9c4f5d8a5710bd09a847d2c8a7" + +[[package]] +name = "xmlwriter" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec7a2a501ed189703dba8b08142f057e887dfc4b2cc4db2d343ac6376ba3e0b9" + +[[package]] +name = "yazi" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e01738255b5a16e78bbb83e7fbba0a1e7dd506905cfc53f4622d89015a03fbb5" + +[[package]] +name = "yeslogic-fontconfig-sys" +version = "6.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d8b8abf912b9a29ff112e1671c97c33636903d13a69712037190e6805af4f76" +dependencies = [ + "dlib", + "once_cell", + "pkg-config", +] + +[[package]] +name = "yoke" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "709fe23a0424b6a435d82152b1bd3fdfb0833487d5fa90d05d42762a9891fef5" +dependencies = [ + "stable_deref_trait", + "yoke-derive", + "zerofrom", +] + +[[package]] +name = "yoke-derive" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec8ebde2db3681e8c9980cc27822030e68752690ddfa9473e739aeb4dbde6d71" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", + "synstructure", +] + +[[package]] +name = "yuv" +version = "0.8.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d109d1eacc7b034329873d2d848039b365c65ab7d751b19ee84e4921c62c607" +dependencies = [ + "num-traits", +] + +[[package]] +name = "zbus" +version = "5.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5db4be7c075cb421e4b7ee645541604239bd243ba7c357511f4ff3a74b555907" +dependencies = [ + "async-broadcast", + "async-executor", + "async-io", + "async-lock", + "async-process", + "async-recursion", + "async-task", + "async-trait", + "blocking", + "enumflags2", + "event-listener", + "futures-core", + "futures-lite", + "hex", + "libc", + "ordered-stream", + "rustix 1.1.5", + "serde", + "serde_repr", + "tracing", + "uds_windows", + "uuid", + "windows-sys 0.61.2", + "winnow", + "zbus_macros", + "zbus_names", + "zvariant", +] + +[[package]] +name = "zbus-lockstep" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6998de05217a084b7578728a9443d04ea4cd80f2a0839b8d78770b76ccd45863" +dependencies = [ + "zbus_xml", + "zvariant", +] + +[[package]] +name = "zbus-lockstep-macros" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10da05367f3a7b7553c8cdf8fa91aee6b64afebe32b51c95177957efc47ca3a0" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", + "zbus-lockstep", + "zbus_xml", + "zvariant", +] + +[[package]] +name = "zbus_macros" +version = "5.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2990635d09ade6df1868f72f8cac69a876a90981e8bd3c40b1be413f8dc88f40" +dependencies = [ + "proc-macro-crate", + "proc-macro2", + "quote", + "syn 3.0.9", + "zbus_names", + "zvariant", + "zvariant_utils", +] + +[[package]] +name = "zbus_names" +version = "4.3.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "812a12be4ead7a59e18ea8f047d08add0066b73bc62fc1467066a2472ae088dd" +dependencies = [ + "serde", + "winnow", + "zvariant", +] + +[[package]] +name = "zbus_xml" +version = "5.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d1586c021a01ca0a9216dcd874e546382e156a5cbab5fab6cb5f10087e22682a" +dependencies = [ + "serde", + "winnow", + "zbus_names", + "zvariant", +] + +[[package]] +name = "zcheapstr" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d1afec51604565183aeb5c54c20aeab286120d4e4460f7f76e3e8bb8c0d99473" +dependencies = [ + "serde", +] + +[[package]] +name = "zeno" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6df3dc4292935e51816d896edcd52aa30bc297907c26167fec31e2b0c6a32524" + +[[package]] +name = "zerocopy" +version = "0.7.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1b9b4fd18abc82b8136838da5d50bae7bdea537c574d8dc1a34ed098d6c166f0" +dependencies = [ + "byteorder", + "zerocopy-derive 0.7.35", +] + +[[package]] +name = "zerocopy" +version = "0.8.63" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5fe1f8f1b06191a00962174c61aa5005e0bb391a6d80d07e24d115c01a92ed8" +dependencies = [ + "zerocopy-derive 0.8.63", +] + +[[package]] +name = "zerocopy-derive" +version = "0.7.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fa4f8080344d4671fb4e831a13ad1e68092748387dfc4f55e356242fae12ce3e" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "zerocopy-derive" +version = "0.8.63" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "863ad3ac83293fb4d740aedbfdc9240dd8d1a50c1099acd76ce80ce7c7230c7f" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "zerofrom" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272" +dependencies = [ + "zerofrom-derive", +] + +[[package]] +name = "zerofrom-derive" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f75b4683f6c7f45248d4d64056a24298c6281e0993356d7d1b4a1a962ef10d4a" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", + "synstructure", +] + +[[package]] +name = "zeroize" +version = "1.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e13084392c5e4bc371903e2935a5eaeed24905a7511356b883835e18a78f6879" + +[[package]] +name = "zerotrie" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ea269c3bd32f0a32c321907a2ae912ba6f4649bb0fc764a15627e99a7095a3f" +dependencies = [ + "displaydoc", + "yoke", + "zerofrom", + "zerovec", +] + +[[package]] +name = "zerovec" +version = "0.11.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb0464e17806c1d976d5cba29399c7f08e516e279e2ba493f63123b5fca67dd8" +dependencies = [ + "serde", + "yoke", + "zerofrom", + "zerovec-derive", +] + +[[package]] +name = "zerovec-derive" +version = "0.11.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "34df6fc39dbd26ddc9c10e6a2984476e13acce22e64e4487636ef494369225da" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "zlib-rs" +version = "0.6.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b268e58e7c693d7c271f93ffc4ba3b380412554231c85bf61ca7af91042a4112" + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" + +[[package]] +name = "zune-core" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d56377fd46368984a170bc5aac5567e52ca5da874caa60bea39fcbca78fb658b" + +[[package]] +name = "zune-jpeg" +version = "0.5.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27bc9d5b815bc103f142aa054f561d9187d191692ec7c2d1e2b4737f8dbd7296" +dependencies = [ + "zune-core", +] + +[[package]] +name = "zvariant" +version = "5.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "80bf6d6cd6a4b601acb64cfb8284cdc643fcfa75ef26ae3c46ec8aa4e8a1fbb7" +dependencies = [ + "endi", + "enumflags2", + "serde", + "winnow", + "zcheapstr", + "zvariant_derive", + "zvariant_utils", +] + +[[package]] +name = "zvariant_derive" +version = "5.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ef2672456ba1cb54b5eaec136e63135b3c7495fb938e53b28a62e633496d486d" +dependencies = [ + "proc-macro-crate", + "proc-macro2", + "quote", + "syn 3.0.9", + "zvariant_utils", +] + +[[package]] +name = "zvariant_utils" +version = "4.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bad0294361a320b694a328460dc73add56c306150f5cb6bfafc44446120008a3" +dependencies = [ + "proc-macro2", + "quote", + "serde", + "syn 3.0.9", + "winnow", +] diff --git a/app/vendor/rune/Cargo.toml b/app/vendor/rune/Cargo.toml new file mode 100644 index 0000000..daa3401 --- /dev/null +++ b/app/vendor/rune/Cargo.toml @@ -0,0 +1,292 @@ +[workspace] +resolver = "3" +members = [ + "crates/rune", + "crates/rune-core", + "crates/rune-edit", + "crates/rune-gpu", + "crates/rune-image", + "crates/rune-media", + "crates/rune-spell", + "crates/rune-text", + "crates/rune-ref", + "crates/rune-motion", + "crates/rune-i18n", + "crates/rune-staging", + "crates/rune-kit", + "crates/rune-highlights", + "crates/rune-fx", + "crates/rune-light", + "crates/procwatch", + "crates/rune-register", + "crates/rune-knobs", + "crates/rune-mac", + "crates/rune-notify", + "crates/rune-mermaid", + "crates/rune-perf", + "crates/rune-luau", + "crates/rune-taffy", + "themes/opencode", + "examples/hello", + "examples/web-hello", + "examples/web-showcase", + "www/app", + "examples/todo", + "examples/settings", + "examples/playground", + "examples/knobs", + "examples/kit-gallery", + "examples/background", + "examples/live-values", + "examples/shapes", + "examples/overlay", + "examples/overlay-lab", + "examples/lab", + "examples/showreel", + "examples/video-player", + "examples/video-tiles", + "examples/cursed-settings", + "examples/drag-out", + "examples/sketch", + "examples/drop-files", + "examples/rich-clipboard", + "examples/matched", + "examples/launcher", + "examples/glass-card", + "examples/glass-panel", + "examples/frosted-bar", + "examples/odometer", + "examples/motion-bento", + "examples/motion-bento/chaos", + "examples/site-scenes", + "examples/luau-panel", +] +# Default cargo check/test targets: the core framework, libraries and theme. +# Excludes examples/*, www/app, rune-luau (C++ Luau build via cc/mlua), rune-notify/rune-mac +# (WinRT features on `windows`), rune-ref (`libm/force-soft-floats` and `serde/derive`), and +# rune-i18n (`icu_provider/sync`, `writeable/default`, `smallvec/const_generics`); pass +# `--workspace` to check everything. +default-members = [ + "crates/rune", + "crates/rune-core", + "crates/rune-edit", + "crates/rune-gpu", + "crates/rune-image", + "crates/rune-media", + "crates/rune-spell", + "crates/rune-text", + "crates/rune-motion", + "crates/rune-staging", + "crates/rune-kit", + "crates/rune-highlights", + "crates/rune-fx", + "crates/rune-light", + "crates/procwatch", + "crates/rune-register", + "crates/rune-knobs", + "crates/rune-mermaid", + "crates/rune-perf", + "crates/rune-taffy", + "themes/opencode", +] +exclude = ["tools/rune-dev-guard", "tools/ratex-math-wasm", "tools/ratex-math-wasm/pack", "vendor/accesskit_macos", "vendor/accesskit_windows", "vendor/parley_engine", "vendor/sctk-adwaita", "vendor/tiny-skia-path", "vendor/wgpu-hal", "vendor/winit"] + +# wgpu-hal as published plus `vendor/wgpu-hal.patch`: `dx12::Instance::expose_adapter` (a `wgpu::Adapter` for the +# one adapter Rune picks through DXGI, with no device made on the others, `crates/rune-gpu/src/pick.rs`), FXC loaded on +# the first compile rather than with the instance (Rune's uber shader is precompiled), partial presents +# (`Surface::set_present_rects`: `Present1` dirty rectangles on a sequential flip-model swap chain, for +# `render::damaged`), Windows system DLLs (`d3d12.dll`, `dxgi.dll`, `dcomp.dll`, `d3dcompiler_47.dll`, +# `opengl32.dll`) loaded with `LOAD_LIBRARY_SEARCH_SYSTEM32`, a removed D3D12 device's work left +# pending rather than read as finished (`Device::reached`; Rune sees the removal through +# `rune_gpu::health::removed`), and GPU-written drain markers (`WriteBufferImmediate`) on software +# adapters (`DXGI_ADAPTER_FLAG_SOFTWARE`, WARP) so releasing a removed WARP device or unconfiguring +# its surface waits until queued command lists finish executing instead of freeing resources under +# its worker threads (`DrainTracker`; hardware adapters pay zero marker cost, while skipping +# `ExecuteCommandLists` and `allocator.Reset()` once removed on every adapter). Re-made by +# `scripts/vendor-wgpu-hal.sh ` when wgpu is bumped. An app that builds Rune patches it too: +# a dependency's `[patch]` doesn't apply to the workspace that depends on it. +[patch.crates-io] +wgpu-hal = { path = "vendor/wgpu-hal" } +# winit as published plus `vendor/winit.patch`: on Windows a new window isn't added again to the +# taskbar it's already on (that took CoInitializeEx and a TaskbarList COM object, about 7,800 µs +# and nine shell DLLs, before every window's first frame), a window given a position is made there, so it is +# born at that display's scale instead of crossing to it and being resized, and Windows system DLLs +# (`uxtheme.dll`, `user32.dll`, `shcore.dll`, `ntdll.dll`) load via `LoadLibraryExA` with +# `LOAD_LIBRARY_SEARCH_SYSTEM32`; and +# `WindowExtWayland::content_corner_radius` tells an app the radius its content leaves its bottom +# corners to while a client-side frame rounds the window (see `vendor/sctk-adwaita`). Re-made by +# `scripts/vendor-winit.sh ` when winit is bumped; apps that build Rune patch it too. +winit = { path = "vendor/winit" } +# sctk-adwaita as published plus `vendor/sctk-adwaita.patch`: the visible one-point border a +# Wayland client-side frame draws follows the window's rounded bottom corners, as the headerbar it +# draws above them rounds the top two, instead of drawing a square L over the shadow's rounded +# cut-out; and `AdwaitaFrame::content_corner_radius` says what radius the content's own bottom +# corners take, for the app to clear outside (`window/surface/corners.rs`). Re-made by +# `scripts/vendor-sctk-adwaita.sh ` when sctk-adwaita is bumped; apps that build Rune +# patch it too. +sctk-adwaita = { path = "vendor/sctk-adwaita" } +# parley_engine as published plus `vendor/parley_engine.patch`: UAX #9 rule L1 for a paragraph's +# trailing whitespace and isolates (BidiTest.txt 770,241 of 770,241; 644,283 without it), and +# shaping that stops redoing work from the same inputs: an analyzer keeps the ICU segmenters it +# made, and a run's or a style's font metrics are made once per font instance and size (14% off +# a text's shaping, layouts identical). Re-made by `scripts/vendor-parley-engine.sh ` when parley is bumped; apps that build +# Rune patch it too. +parley_engine = { path = "vendor/parley_engine" } +# accesskit_windows as published plus `vendor/accesskit_windows.patch`: headings and landmarks reach +# UI Automation (HeadingLevel, LandmarkType, LocalizedLandmarkType), which Narrator's and NVDA's +# heading and landmark navigation read; and a field past Rune's 64 KiB text-run limit keeps its text +# pattern, its lines answered from its value when a reader asks (`src/long_text.rs`). Re-made by +# `scripts/vendor-accesskit-windows.sh ` +# when AccessKit is bumped; apps that build Rune patch it too. +accesskit_windows = { path = "vendor/accesskit_windows" } +# accesskit_macos as published plus `vendor/accesskit_macos.patch`: headings reach NSAccessibility as +# AppKit's `AXHeading` with their level as the value (the published role, `Heading`, is none VoiceOver +# knows), so VoiceOver's rotor and VO-Command-H find them and say their level; and the accessibility +# children, focused element and hit test leave the adapter alone off the main thread, which AppKit +# calls them on while the process queries itself, so they answer from the superclass instead of +# racing or panicking on the main thread's borrow; and a field past Rune's 64 KiB text-run limit keeps +# its line, string and selection ranges, answered from its value when a reader asks. Re-made by +# `scripts/vendor-accesskit-macos.sh ` when AccessKit is bumped; apps that build Rune patch it too. +accesskit_macos = { path = "vendor/accesskit_macos" } + +[workspace.package] +edition = "2024" +license = "MIT" + +[workspace.dependencies] +# Internal workspace crates. +procwatch = { path = "crates/procwatch" } +rune = { path = "crates/rune", default-features = false } +rune-core = { path = "crates/rune-core" } +rune-edit = { path = "crates/rune-edit" } +rune-fx = { path = "crates/rune-fx" } +rune-gpu = { path = "crates/rune-gpu", default-features = false } +rune-highlights = { path = "crates/rune-highlights" } +rune-image = { path = "crates/rune-image", default-features = false } +rune-kit = { path = "crates/rune-kit", default-features = false } +rune-knobs = { path = "crates/rune-knobs" } +rune-light = { path = "crates/rune-light" } +rune-luau = { path = "crates/rune-luau" } +rune-media = { path = "crates/rune-media", default-features = false } +rune-mermaid = { path = "crates/rune-mermaid" } +rune-motion = { path = "crates/rune-motion" } +rune-notify = { path = "crates/rune-notify" } +rune-ref = { path = "crates/rune-ref" } +rune-spell = { path = "crates/rune-spell" } +rune-staging = { path = "crates/rune-staging" } +rune-taffy = { path = "crates/rune-taffy" } +rune-text = { path = "crates/rune-text", default-features = false } +rune-theme-opencode = { path = "themes/opencode" } + +# Shared external crates. +blake3 = "1" +block2 = "0.6" +bytemuck = { version = "1.25", features = ["derive"] } +half = "2" +image = { version = "0.25", default-features = false } +js-sys = "0.3" +libc = "0.2" +miniz_oxide = { version = "0.9", default-features = false, features = ["with-alloc"] } +objc2 = "0.6" +objc2-app-kit = { version = "0.3", default-features = false } +objc2-core-foundation = { version = "0.3", default-features = false } +objc2-core-graphics = { version = "0.3", default-features = false } +objc2-core-video = { version = "0.3", default-features = false } +objc2-foundation = { version = "0.3", default-features = false } +objc2-metal = { version = "0.3", default-features = false } +parley = { version = "0.12", default-features = false } +parley_engine = { version = "0.12", default-features = false } +png = "0.18" +pollster = "1" +resvg = { version = "0.45", default-features = false } +rustc-hash = "2" +serde = "1" +serde_json = "1" +skrifa = "0.44" +swash = "0.2.10" +taffy = { version = "0.15", default-features = false } +tiny-skia = { version = "0.11", default-features = false, features = ["std", "simd"] } +unicode-segmentation = "1.13" +wasm-bindgen = "0.2" +wasm-bindgen-futures = "0.4" +wasmi = { version = "1.1", default-features = false } +web-sys = "0.3" +wgpu = { version = "~30.0.1", default-features = false } +wgpu-naga-bridge = "~30.0.1" +windows = "0.62" +windows-core = "0.62" +windows-sys = "0.61" +winit = { version = "0.30.13", default-features = false } +zeroize = "1.8" + +# Full debug info for the workspace crates made a single `rune` test build use 18-23 GB of RAM; +# line tables keep backtraces and file:line in panics at a fraction of that. +[profile.dev] +debug = "line-tables-only" + +[profile.dev.package."*"] +debug = false + +[profile.release] +codegen-units = 16 +incremental = true + +# Keep the optional `math` sandbox interpreter compact (saves ~558 KiB in FAT-LTO release builds +# with zero effect on the UI thread since math typesets on a background worker and caches results). +[profile.release.package.wasmi] +opt-level = "z" +[profile.release.package.wasmi_core] +opt-level = "z" +[profile.release.package.wasmi_ir] +opt-level = "z" +[profile.release.package.wasmi_collections] +opt-level = "z" +[profile.release.package.wasmparser] +opt-level = "z" + +# Benchmarks and perf numbers. Same codegen as release, without incremental, which can move +# frame timings. The runtime bench scripts refuse binaries built with any other profile. +[profile.perf] +inherits = "release" +opt-level = 3 +codegen-units = 16 +lto = false +debug = false +incremental = false + +# `cargo bench` inherits release; scripts/check-reference-instructions.sh compares its instruction +# counts across revisions. +[profile.bench] +incremental = false + +[profile.rune-hot] +inherits = "dev" +debug = 0 +incremental = true + +[profile.rune-hot.package.png] +opt-level = 3 + +[profile.rune-hot.package.fdeflate] +opt-level = 3 + +[workspace.lints.rust] +# shared-lints begin +unsafe_op_in_unsafe_fn = "deny" +unused_must_use = "deny" +# shared-lints end +unsafe_code = "deny" # pure-Rust crates use #![forbid(unsafe_code)]; FFI/SIMD leaf modules opt in locally + +[workspace.lints.clippy] +# shared-lints begin +await_holding_lock = "deny" +await_holding_refcell_ref = "deny" +dbg_macro = "deny" +disallowed_methods = "deny" +disallowed_types = "deny" +expect_used = "warn" +let_underscore_must_use = "deny" +todo = "warn" +undocumented_unsafe_blocks = "deny" +unwrap_used = "warn" +# shared-lints end diff --git a/app/vendor/rune/LICENSE b/app/vendor/rune/LICENSE new file mode 100644 index 0000000..66aed12 --- /dev/null +++ b/app/vendor/rune/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 Anomaly + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/app/vendor/rune/PLAN.md b/app/vendor/rune/PLAN.md new file mode 100644 index 0000000..69d438b --- /dev/null +++ b/app/vendor/rune/PLAN.md @@ -0,0 +1,617 @@ +# Rune: plan + +*Research notes behind every claim are in [`research/`](research/). Numbers marked "target" are commitments to +measure against, not results.* + +## The short version + +Rune is a Rust UI framework with its own renderer, text, layout, state, +animation and platform shells, built to feel like SwiftUI-on-iOS at 120 Hz and to be written and checked by agents. + +**Direction:** Rune apps carry **their own design language on every +platform, Mac included**, rather than imitating each OS. Rune itself bakes in no brand: it ships a token-driven theming +system, and OpenCode's theme is the first theme built on it and the reference example. The flagship test is +**recreating OpenCode Desktop** in Rune and raising its bar, which makes Windows and Linux +first-class from the start. Native stays where it's behaviour, not looks: text input/IME, accessibility, window +management, clipboard, scroll momentum. A Rust component library with the same names as `@opencode/ui`, gallery +and screenshot tests, and Hex Settings as the first real screen fold in here instead of becoming a second stack on +Slint. + +| Layer | Pick | Instead of | +|---|---|---| +| Language | Rust (2024), thin `objc2`/Swift shims on Apple | Zig, C++, Swift, Mojo | +| GPU | wgpu on every platform first (one backend ships Mac, Windows, Linux and web); a raw Metal backend later only where a measured need shows up (live-resize sync, IOSurface video), via wgpu-hal escape hatches first | Raw Metal first, Vulkan/D3D12 by hand | +| Renderer | One instanced "uber-quad" SDF pass + glyph atlas + Slug for big/animated text and icons + `vello_gpu` sparse strips for complex vectors; soft-edge masks in-shader on every clip | Full compute Vello, Skia, MSAA path textures | +| Look | Unbranded core with a token-driven theming system (semantic tokens, themes with light/dark, runtime switching, codegen); the same look on every platform. OpenCode's theme (from `@opencode/ui`) is the first theme and the main example, kept outside the core | A theme baked into the framework; per-OS native look; Liquid Glass as the base (it's an optional Apple extra) | +| Text | Parley + HarfRust + skrifa + fontique, GPUI-style two-tier line cache, kitlangton/gpui glyph dilation | CoreText-only, cosmic-text | +| Text editing / IME | Zed's `sum_tree` + rope; each platform's own text protocol, implemented directly (`NSTextInputClient`, `UITextInput`, …) | winit's IME, a hidden native text field | +| Layout | Taffy (flex, grid, block) on Rune's own node arena, plus a sum-tree height index for huge lists | Own layout engine, SwiftUI-style proposals | +| State | Keyed retained tree rebuilt from plain view functions; typed models; reads subscribe; handlers queued with `&mut` | Signals, GPUI entities, immediate mode | +| Animation | Render thread owns the presented tree; every property is an analytic spring track (duration + bounce, SwiftUI's formula) that retargets with velocity | Animating through view re-renders on the main thread | +| Accessibility | AccessKit, and the same tree is the agent inspector's tree | Own a11y bridges | +| Shells | winit to start (the prototype runs on it); own thin shells per platform (borrowing from Zed's Apache-2.0 `gpui_macos`/`gpui_windows`/`gpui_linux`/`gpui_ios`/`gpui_web`) as soon as text input lands, because winit's IME is incomplete | winit forever, SDL3 | +| Hot reload | Tokens and live literals with no rebuild (≤ 100 ms), subsecond hot-patching for structural Rust edits on Mac (~1 s measured, goal 300 ms), **split-process dev mode** for the iPhone (renderer on the phone, app code on the Mac) | A view DSL interpreter, code loading on the device | +| Platform order | macOS + Windows + Linux together (one wgpu backend) → web (docs site, demos) → iOS → Android | | + +**Top three risks:** text input and text quality (IME on three desktops, then iOS `UITextInput`), matching +OpenCode Desktop's Chromium-rendered look closely enough (text above all), and sheer scope. + +**First milestones:** Rune's theming system plus an OpenCode theme generated from `@opencode/ui` as its first +consumer, and a component gallery styled by it; Hex's Settings as the first real screen on Mac, Windows and Linux; then OpenCode Desktop's main screens. +A docs/marketing site comes first to explain it. + +--- + +## 1. Why build this at all + +Kit has rebuilt the same small surfaces three times in ten days: +the Scrawl pill went GPUI → hand-written Metal → SwiftUI helper process, the launcher app went GPUI → SwiftUI with a +Core Animation glass morph, and Hex's native branch stalled because Hex also ships on Windows and Linux. Each time, +the reasons were the same: + +1. **No backdrop or glass.** GPUI draws one forward pass into one layer; Liquid Glass only exists in the window server. +2. **Animation waited behind the main thread.** The Metal pill dropped 85 frames on finish until it got its own + display-link thread. +3. **Windows and focus were wrong for HUDs and launchers** (late focus events, Dock policy, no non-activating panels, + per-frame window resizes). +4. **Text looked thin and colours were off,** and unseen glyphs stalled the first frame by ~13 ms. +5. **No springs or layout animation,** so every app hand-rolled them. +6. **Upstream was frozen** at 0.2.2 for Kit's apps, so every fix lived in a fork. + +Upstream GPUI has since moved a lot: Zed's tree at `5447804` has `gpui_ios`, `gpui_web`, a wgpu backend, +`spring.rs`, AccessKit and subsecond hot reload (verified in a clone). It still redraws the whole window every dirty +frame, has no layer compositing or group opacity, runs animations by re-rendering views on the main thread, and +panics on re-entrant entity borrows ([01](research/01-gpui-zed-warp.md)). Those are the exact things that sent Kit +to Apple frameworks, and they're architectural. **Verdict: don't fork GPUI; start fresh and lift its best parts** +(rope/sum_tree, BoundsTree, line layout cache, the macOS/iOS IME code, the web textarea bridge, the shader fixes in +Kit's fork) under its Apache-2.0 licence. + +## 2. Tenets + +1. **Feel is the product.** 120 Hz, interruptible springs, nothing pops, jumps or hard-clips. Kit's motion rules + are runtime defaults, not discipline. +2. **Animation never runs through app code.** Views state targets; the render thread animates. +3. **Everything observable.** Every frame, node, layout rect, spring and timing can be queried, traced and replayed. + The agent's view of the app is the same tree as accessibility's. +4. **One way to do things.** Small explicit APIs, no macro DSL for views, errors that say how to fix. +5. **Native behaviour, one look.** Text input, accessibility, scroll momentum, clipboard and window behaviour are + native per platform. Controls, type, motion and materials come from the app's theme, the same on every platform, + Mac included. The framework ships no brand of its own. +6. **Owned, not wrapped.** Depend on foundational crates (Taffy, Parley, AccessKit), never on another UI framework. +7. **Optimise for performance, correctness, speed of change and prototyping; not for human readability**. + Agents write and maintain the code, so: + - **Fast path plus reference path.** Each hard subsystem (layout, text, renderer, springs) has a slow, obviously + correct reference implementation (CPU, no tricks) and a fast one (SoA, SIMD, `unsafe` where measured, specialised, + duplicated). Every change differential-tests the fast one against the reference on generated inputs. Correctness + comes from the reference and the oracles, not from the fast code being easy to read. + - **Data-oriented everything:** flat arenas indexed by ids, struct-of-arrays, no `Rc`/`RefCell`, zero allocation + per frame (enforced by a counting allocator in tests), precomputed tables, pipelines built ahead of time. + - **Specialise by codegen, not by generics.** Generated, repetitive, per-component code is fine; deep trait towers + and proc-macro DSLs are not, because they slow compiles and bury errors. Debug builds stay type-erased and fast + to compile; release builds specialise. + - **Edits are safe because checks are instant:** invariants as `debug_assert`s everywhere, scenes, goldens, + motion/layout lint and exact perf counters run on every change, so an agent sees breakage in seconds. + - **Comments state invariants and intent for the next agent,** not prose for a human reader. + - **Perf is measured by counts** (instructions, instances, glyphs, layout nodes, allocations) so gates are exact + and bisectable; wall-clock numbers come from reserved hardware. + - **Prototypes are cheap and throwaway:** live literals, scenes, the playground and hot reload make trying ten variants + faster than debating one. + +## 3. Architecture + +``` + ┌──────────────────────── dev only: same protocol over USB/Wi-Fi ────────────────────────┐ + │ │ +┌────────────────┴─────────────────────────────┐ commands: tree diff, ┌──────────────────────┴─────────────────────────┐ +│ APP SIDE (platform main thread by default) │ layout rects, targets, │ RENDER THREAD (display-link paced) │ +│ │ springs, text runs │ │ +│ models (typed state, keyed by stable ids) │ ───────────────────────────────▶ │ presented tree (what's on screen right now) │ +│ view fns → keyed El tree → diff │ │ property tracks: analytic springs, retarget │ +│ Taffy layout at the *target* state │ ◀─────────────────────────────── │ presence (exiting nodes), layout edge tracks │ +│ Parley shaping, line cache │ events: hits, gestures, │ scroll physics, drag bindings (1:1, local) │ +│ handlers: queued, get &mut model │ settles, presented-frame ids│ scene build → instance buffers │ +│ AccessKit tree updates │ │ encode (Metal / wgpu) → present │ +└──────────────┬───────────────────────────────┘ └──────────────┬─────────────────────────────────┘ + │ platform calls │ CATransaction: Metal drawable + +┌──────────────┴───────────────────────────────┐ ┌───────────────┴────────────────────────────────┐ +│ SHELL (per platform) │ │ NATIVE LAYERS (Apple) │ +│ windows/panels, menus, clipboard, DnD, │ │ NSGlassEffectView / UIGlassEffect underlays, │ +│ IME protocol, a11y adapter, lifecycle │ │ AVPlayerLayer, MapKit; masks driven per frame │ +└──────────────────────────────────────────────┘ └────────────────────────────────────────────────┘ + background pool: image decode, big-paragraph shaping, vector flattening, file IO + inspector socket (dev + test builds): tree, rects, a11y, source locations, springs, timings, traces, input injection +``` + +The one boundary that matters is the **command channel between the app side and the render thread**. It carries +tree diffs, target layout rects, shaped text runs and spring targets one way, and hits, gesture results, settles and +presented-frame ids the other. Three things fall out of making it a real, serializable protocol: + +- **Animations survive a busy app.** When one value animates, the app side does no work at all: no view re-run, no + layout, no diff ([06](research/06-reactivity-animation.md)). +- **The iPhone hot-reload path.** In dev, the channel can run over USB: the renderer runs on the phone and the app + side runs on the Mac, where subsecond hot-patches it (§5). +- **Agents and tests get the same stream.** Recording the channel gives deterministic replay, frame traces and an + inspector for free (§6). + +## 4. Each layer + +### 4.1 Language: Rust + +Rust is the only option with production text, layout and accessibility crates (Taffy, Parley, HarfRust, fontations, +AccessKit), no GC, reach to every target including wasm, and a working hot-patcher (subsecond). Agents write it well; +the borrow checker is the main cost, which the state model below is designed around (no `RefCell` re-entry, no +borrows held across async). Zig lacks the ecosystem and a dependable incremental patch path on Mach-O; Swift is great +on Apple and weak everywhere else; C++ gives up safety and agent reliability for nothing; Mojo isn't a UI language +yet ([04 §1](research/04-language-gpu-renderer.md)). Swift is used only for thin host pieces Apple exposes no other +way (SwiftUI-only glass morphing, the `RuneView` representable). + +### 4.2 GPU API: wgpu everywhere, raw Metal on Apple only where measured + +wgpu runs on every platform, since the desktop trio ships together. Zed's own move from blade to wgpu in 2026 is +the evidence that it's good enough ([04 §2](research/04-language-gpu-renderer.md), +[01](research/01-gpui-zed-warp.md)). A raw Metal (`objc2-metal`) backend behind a thin internal trait is a later +optimization, added only where measurements show wgpu falls short: precompiled `.metallib` (no shader compile at +launch), `IOSurface` zero-copy video, framebuffer fetch for cheap group opacity on Apple silicon, and exact control +of `CAMetalLayer` presentation (`presentsWithTransaction`, drawable count). Rejected: hand-written Vulkan/D3D12 (Zed +just deleted theirs). + +### 4.3 Renderer + +A typical frame is one render pass. Six primitives, all instanced, all clipped by a GPU clip table that gives +rounded clips **and soft gradient edges per side for free**, so "no hard edges" costs nothing extra +([04 §3](research/04-language-gpu-renderer.md)): + +| Primitive | Does | +|---|---| +| `UberQuad` | rounded/squircle rects, borders, analytic Gaussian shadows (inner/outer), Oklab gradients with dithering, surface material | +| `AtlasSprite` | body text from a greyscale glyph atlas, images, emoji | +| `Slug` | big, rotating or scaling text and icons straight from Bézier curves (patent dedicated to the public domain on 2026-03-17; reference shaders MIT/Apache) | +| `SparseStrips` | complex vector art via `vello_gpu` (Linebender moved compute Vello to `research/` in 2026) | +| `Backdrop` | in-app blur/saturate of what's already drawn (dual Kawase, scissored), with Scrawl's peak-alpha boost for legible blurred text | +| `NativeSurface` | zero-copy video and camera frames | + +Plus: offscreen layers only when needed (group opacity with blur, cached complex subtrees), dirty-rect scissoring +for idle-ish frames, linear-light blending, Display P3, and dithering on every gradient and shadow (Kit's GPUI fork (`kitlangton/gpui`) +fixes, now partly upstream). + +**Frame pacing and latency.** `CADisplayLink` with `preferredFrameRateRange` up to 120 while anything animates, zero +ticks at rest. Discrete input (key, click) draws immediately instead of waiting for the next tick, with at most two +drawables in flight. Animation time is the display link's *target* timestamp, so a late frame still lands on the +right pose. `CAMetalDisplayLink` is suspect: one 2026 measurement shows windowed macOS scheduling it 3–5 refreshes +ahead ([04 §4](research/04-language-gpu-renderer.md)); spike S3 checks this before we rely on either. + +### 4.4 Compositing with native layers (Apple) + +*Optional now that Rune carries OpenCode's look on every platform; kept for Kit's Mac surfaces (M4).* + +Rune can't draw Liquid Glass: the shaders that sample behind the window live in the window server. So the Apple +shell composes **native underlays and overlays** with Rune's Metal layer: a system glass view sits behind a +transparent region of the Metal layer, and its shape is driven by a mask layer that the render thread updates in the +same `CATransaction` as the drawable (`presentsWithTransaction`). This is how Scrawl's Metal pill already hosts +`NSGlassEffectView`, and the launcher's CA glass recipe is the fallback material backend +([11 §2](research/11-platform-shells.md)). Popovers, HUDs and pills use a +fixed, transparent, max-size surface with shape hit-testing, never per-frame window resizes. + +Two caveats: glass *morphing* between shapes is SwiftUI-only on iOS, and NSViews are main-thread objects. Spike S2 +measures whether a glass underlay can track a Rune-animated shape at 120 Hz with the main thread blocked. + +### 4.5 Text + +- **Fonts and shaping:** HarfRust (pure-Rust HarfBuzz port), skrifa/fontations (hinting, variable fonts, COLRv1), + fontique (system fonts and fallback), plus SF's tracking tables on Apple. +- **Layout:** Parley for bidi, line breaking, rich text and inline boxes, wrapped in GPUI's two-tier cache (shaped + runs separate from wrap points), so resizing a container never re-shapes text + ([05](research/05-text-ime-a11y-layout.md)). Overflow is a soft fade mask by default, never an ellipsis. +- **Rasterizing:** greyscale atlas, 4× horizontal subpixel positioning, and the kitlangton/gpui luminance glyph dilation + that fixed "thin text" by matching macOS font smoothing. Text under a scale animation switches to Slug outlines so + springs never re-rasterize glyphs every frame. +- **Quality bar:** a side-by-side diff against CoreText on the same strings (spike S5). If Rune text doesn't match + native on a Retina Mac, nothing else matters. + +### 4.6 Text editing and IME + +Zed's `sum_tree` and rope for storage (O(log n) UTF-8↔UTF-16 offsets, large files). Each platform's real protocol, +implemented directly: `NSTextInputClient` (with `doCommandBySelector:` for Kit's key bindings), `UITextInput` plus +`UITextInteraction` on iOS (selection handles, loupe, autocorrect, dictation, marked text), `InputConnection` on +Android, TSF on Windows, `text-input-v3` on Wayland, and a sliding-window hidden `\">t", "

t"), + ("<script>x</script>t", "t"), + ("<script>x</script>", ""), + ("<form action=https://evil.example><button formaction=javascript:y>b</button></form>", "<button>b</button>"), + ("<details open ontoggle=x>t</details>", "<details open>t</details>"), + ("<scr<script>ipt>alert(1)</script>", "<scr>ipt>alert(1)"), + ("<img srcset=\"a.png 1x, javascript:x 2x\">", "<img>"), + ("t<script>never closed", "t"), + ("t<img src=x", "t"), + ("t<a href=\"unterminated>", "t"), + ("a\0b", "ab"), + ]; + for (dirty, want) in cases { assert_eq!(clean(dirty), want, "{dirty}"); } +} + +#[test] +fn clean_is_stable() { + for html in [ + "<p><b>x</b><img src=y onload=z></p>", + "<a href='mailto:a@b.c'>m</a>", + "<style>a{}</style>", + "<div title=\"<script>alert(1)</script>\">x</div>", + "<scr<script>ipt>alert(1)</script>", + ] { + let once = clean(html); + assert_eq!(clean(&once), once, "{html}"); + } +} + +#[test] +fn stays_linear_and_panic_free_on_huge_and_nested_inputs() { + let start = crate::time::now(); + let many_scripts = "<script>alert(1)</script><b>ok</b>".repeat(5_000); + assert_eq!(clean(&many_scripts), "<b>ok</b>".repeat(5_000)); + + let deep = format!("{}text{}", "<div>".repeat(5_000), "</div>".repeat(5_000)); + assert_eq!(clean(&deep), deep); + + let unclosed = "<a href=\"https://example.com\" ".repeat(5_000); + assert_eq!(clean(&unclosed), ""); + + let multibyte = "café 🦀 <b title=\"🎉\">bold</b>".repeat(2_000); + assert!(clean(&multibyte).contains("🦀")); + assert!(start.elapsed() < std::time::Duration::from_secs(2), "sanitizer took {:?}", start.elapsed()); +} + +#[test] +fn cf_html_uses_utf8_byte_offsets_and_tolerates_minus_one_offsets() { + let fragment = "<b>Héllo 🦀</b> <i>world</i>"; + let packed = pack_cf_html(fragment); + assert_eq!(unpack_cf_html(packed.as_bytes()).as_deref(), Some(fragment)); + let mut nul_padded = packed.into_bytes(); + nul_padded.extend_from_slice(b"\0\0\0"); + assert_eq!(unpack_cf_html(&nul_padded).as_deref(), Some(fragment)); + + // Apps that omit context or fragment offsets write -1 (or -000000001) and rely on the markers or StartHTML. + let minus_one_context = "Version:0.9\r\nStartHTML:-1\r\nEndHTML:-1\r\nStartFragment:0000000109\r\nEndFragment:0000000124\r\n<!--StartFragment--><b>Hi café</b><!--EndFragment-->"; + assert_eq!(unpack_cf_html(minus_one_context.as_bytes()).as_deref(), Some("<b>Hi café</b>")); + + let minus_one_frag = "Version:0.9\r\nStartHTML:-000000001\r\nEndHTML:-000000001\r\nStartFragment:-000000001\r\nEndFragment:-000000001\r\n<html><body><!--StartFragment--><i>markers</i><!--EndFragment--></body></html>"; + assert_eq!(unpack_cf_html(minus_one_frag.as_bytes()).as_deref(), Some("<i>markers</i>")); + + let html_offsets_only = "Version:0.9\r\nStartHTML:0000000043\r\nEndHTML:0000000059\r\n<p>doc slice</p>"; + assert_eq!(unpack_cf_html(html_offsets_only.as_bytes()).as_deref(), Some("<p>doc slice</p>")); + + let out_of_bounds = "Version:0.9\r\nStartHTML:0000000100\r\nEndHTML:0000099999\r\nStartFragment:0000000500\r\nEndFragment:0000099999\r\n<b>fallback</b>"; + assert_eq!(unpack_cf_html(out_of_bounds.as_bytes()).as_deref(), Some("<b>fallback</b>")); +} diff --git a/app/vendor/rune/crates/rune/src/clipboard/macos.rs b/app/vendor/rune/crates/rune/src/clipboard/macos.rs new file mode 100644 index 0000000..f943814 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/clipboard/macos.rs @@ -0,0 +1,334 @@ +//! The macOS pasteboard's rich forms. Every form is written after one `clearContents`, so the +//! change count moves once; RTF from apps that offer nothing richer (TextEdit, Notes, Pages) +//! is converted to HTML. Runs on the clipboard worker: AppKit's RTF reader and HTML writer +//! don't need the main thread (its HTML *reader* does, and isn't used). A TIFF image (what +//! most Mac apps copy) is converted to PNG there too, by `NSBitmapImageRep`, and a copied PNG +//! to TIFF. + +#![allow(unsafe_code)] + +use std::path::PathBuf; +use objc2::rc::{Retained, autoreleasepool}; +use objc2::runtime::{AnyObject, ProtocolObject}; +use objc2::AnyThread; +use objc2_app_kit::{ + NSAttributedStringAppKitDocumentFormats, NSAttributedStringDocumentFormats, NSBitmapImageFileType, NSBitmapImageRep, + NSCharacterEncodingDocumentAttribute, NSDocumentTypeDocumentAttribute, NSHTMLTextDocumentType, NSPasteboard, NSPasteboardItem, + NSPasteboardTypeFileURL, NSPasteboardTypeHTML, NSPasteboardTypePNG, NSPasteboardTypeRTF, NSPasteboardTypeString, NSPasteboardTypeTIFF, +}; +use objc2_foundation::{ + NSArray, NSAttributedString, NSData, NSDictionary, NSNumber, NSRange, NSString, NSURL, NSUTF8StringEncoding, +}; +use zeroize::Zeroizing; +use super::{ClipboardContent, ClipboardImage, MAX_IMAGE_BYTES}; +use super::html::MAX_RICH_BYTES; + +/// Refuse to hand AppKit's RTF parser multi-megabyte blobs (e.g. embedded images). +const MAX_RTF_CONVERT_BYTES: usize = 1024 * 1024; + +/// Replaces the pasteboard's contents with every form `content` carries. The first pasteboard +/// item holds the text (unless it's empty and another form isn't), HTML, RTF and the image as +/// PNG and TIFF (for apps that take only TIFF); each file is an item of its own with its file +/// URL, as Finder writes a copy of several files, so a file manager pastes them all. +pub(super) fn write(pb: &NSPasteboard, content: &ClipboardContent) -> Result<(), String> { + // SAFETY: `pb` is a live `NSPasteboard`, every Foundation/AppKit argument and static + // pasteboard type constant is valid, and `autoreleasepool` bounds autoreleased temporaries. + autoreleasepool(|_| unsafe { + let refused = |form: &str| format!("the pasteboard refused the {form}"); + let items: Vec<Retained<NSPasteboardItem>> = (0..content.files().len().max(1)).map(|_| NSPasteboardItem::new()).collect(); + let first = &items[0]; + let text = content.text(); + if (!text.is_empty() || !content.is_rich()) && !first.setString_forType(&NSString::from_str(text), NSPasteboardTypeString) { + return Err(refused("text")); + } + if let Some(html) = content.html() && !first.setString_forType(&NSString::from_str(&declare_utf8(html)), NSPasteboardTypeHTML) { + return Err(refused("HTML")); + } + if let Some(rtf) = content.rtf() && !first.setData_forType(&NSData::with_bytes(rtf.as_bytes()), NSPasteboardTypeRTF) { + return Err(refused("RTF")); + } + if let Some(image) = content.image() { + let tiff = png_to_tiff(image.png()).ok_or_else(|| "the image didn't convert to TIFF".to_string())?; + if !first.setData_forType(&NSData::with_bytes(image.png()), NSPasteboardTypePNG) || !first.setData_forType(&tiff, NSPasteboardTypeTIFF) { + return Err(refused("image")); + } + } + for (item, path) in items.iter().zip(content.files()) { + let url = path.to_str().and_then(|p| NSURL::fileURLWithPath(&NSString::from_str(p)).absoluteString()); + if !url.is_some_and(|url| item.setString_forType(&url, NSPasteboardTypeFileURL)) { return Err(refused("file")); } + } + pb.clearContents(); + let objects: Vec<_> = items.into_iter().map(ProtocolObject::from_retained).collect(); + let objects = NSArray::from_retained_slice(&objects); + if !pb.writeObjects(&objects) { return Err(refused("content")); } + Ok(()) + }) +} + +/// Plain text, HTML and RTF, with HTML made from the RTF when the pasteboard has no HTML, and +/// with `all`, the pasteboard's PNG (or its TIFF as PNG) and its file URLs too. +pub(super) fn read(pb: &NSPasteboard, all: bool) -> Option<ClipboardContent> { + // SAFETY: `pb` is a live `NSPasteboard`, the pasteboard type constants are immutable + // AppKit statics, and `autoreleasepool` bounds autoreleased temporaries. + autoreleasepool(|_| unsafe { + let text = pb.stringForType(NSPasteboardTypeString).map(|s| Zeroizing::new(s.to_string())); + let html = pb.stringForType(NSPasteboardTypeHTML).map(|s| s.to_string()).filter(|h| !h.is_empty() && h.len() <= MAX_RICH_BYTES); + let rtf = pb.dataForType(NSPasteboardTypeRTF) + .filter(|d| !d.is_empty() && d.len() <= MAX_RICH_BYTES) + .map(|d| Zeroizing::new(d.to_vec())); + let image = if all { read_image(pb) } else { None }; + let files = if all { read_files(pb) } else { Vec::new() }; + if text.is_none() && html.is_none() && rtf.is_none() && image.is_none() && files.is_empty() { return None; } + let html = html.or_else(|| rtf.as_deref().and_then(|rtf| rtf_to_html(rtf))); + let mut content = ClipboardContent::from(text.unwrap_or_default()).with_files(files); + if let Some(html) = html { content = content.with_html(html); } + if let Some(rtf) = rtf { content = content.with_rtf(String::from_utf8_lossy(&rtf)); } + if let Some(image) = image { content = content.with_image(image); } + Some(content) + }) +} + +/// The path of each pasteboard item's file URL, in order. +fn read_files(pb: &NSPasteboard) -> Vec<PathBuf> { + let Some(items) = pb.pasteboardItems() else { return Vec::new() }; + // SAFETY: each `item` is a live `NSPasteboardItem` from `items` and `NSPasteboardTypeFileURL` is an immutable AppKit static. + items.iter().filter_map(|item| unsafe { item.stringForType(NSPasteboardTypeFileURL) }.and_then(|url| crate::platform::macos::drop::file_path(&url))).collect() +} + +/// TIFF for PNG bytes, through `NSBitmapImageRep`. +fn png_to_tiff(png: &[u8]) -> Option<Retained<NSData>> { + NSBitmapImageRep::imageRepWithData(&NSData::with_bytes(png))?.TIFFRepresentation() +} + +const MAX_TIFF_BYTES: usize = 8 * MAX_IMAGE_BYTES; + +/// The pasteboard's PNG as is, else its TIFF converted. +fn read_image(pb: &NSPasteboard) -> Option<ClipboardImage> { + let fits = |d: &Retained<NSData>| !d.is_empty() && d.len() <= MAX_IMAGE_BYTES; + // SAFETY: `pb` is a live `NSPasteboard` and the PNG/TIFF type constants are immutable AppKit statics. + unsafe { + if let Some(png) = pb.dataForType(NSPasteboardTypePNG).filter(fits).and_then(|d| ClipboardImage::from_png(d.as_bytes_unchecked())) { + return Some(png); + } + // TIFF is uncompressed more often than not: allow it more room than the PNG it becomes. + let tiff = pb.dataForType(NSPasteboardTypeTIFF).filter(|d| !d.is_empty() && d.len() <= MAX_TIFF_BYTES)?; + tiff_to_png(tiff.as_bytes_unchecked()) + } +} + +/// PNG for TIFF bytes (the first image of a multi-page TIFF), through `NSBitmapImageRep`. +pub(crate) fn tiff_to_png(tiff: &[u8]) -> Option<ClipboardImage> { + if tiff.is_empty() || tiff.len() > MAX_TIFF_BYTES || !tiff_dimensions_ok(tiff) { + return None; + } + // SAFETY: `NSData::with_bytes` owns a copy of `tiff`, dimensions were validated above, + // and `autoreleasepool` bounds autoreleased AppKit temporaries. + autoreleasepool(|_| unsafe { + let rep = NSBitmapImageRep::imageRepWithData(&NSData::with_bytes(tiff))?; + let (w, h) = (rep.pixelsWide(), rep.pixelsHigh()); + if w <= 0 || h <= 0 || !super::valid_image_size(w as u32, h as u32) { + return None; + } + let png = rep.representationUsingType_properties(NSBitmapImageFileType::PNG, &NSDictionary::new())?; + if png.len() > MAX_IMAGE_BYTES { return None; } + ClipboardImage::from_png(png.as_bytes_unchecked()) + }) +} + +/// Checks the first TIFF IFD's `ImageWidth` (256) and `ImageLength` (257) before handing the +/// bytes to AppKit, so a compressed decompression bomb cannot allocate a giant bitmap. +fn tiff_dimensions_ok(tiff: &[u8]) -> bool { + if tiff.len() < 8 { + return false; + } + let le = match &tiff[..4] { + b"II\x2a\x00" => true, + b"MM\x00\x2a" => false, + _ => return false, + }; + let u16_at = |at: usize| { + let b: [u8; 2] = tiff.get(at..at + 2)?.try_into().ok()?; + Some(if le { u16::from_le_bytes(b) } else { u16::from_be_bytes(b) }) + }; + let u32_at = |at: usize| { + let b: [u8; 4] = tiff.get(at..at + 4)?.try_into().ok()?; + Some(if le { u32::from_le_bytes(b) } else { u32::from_be_bytes(b) }) + }; + let Some(ifd) = u32_at(4).map(|o| o as usize) else { return false }; + let Some(entries) = u16_at(ifd).map(usize::from) else { return false }; + let (mut width, mut height) = (None, None); + for i in 0..entries.min(4096) { + let Some(base) = ifd.checked_add(2).and_then(|b| b.checked_add(i.checked_mul(12)?)) else { break }; + if base + 12 > tiff.len() { + break; + } + let (Some(tag), Some(kind), Some(count)) = (u16_at(base), u16_at(base + 2), u32_at(base + 4)) else { break }; + if (tag == 256 || tag == 257) && count == 1 { + let val = match kind { + 1 => tiff.get(base + 8).copied().map(u32::from), + 3 => u16_at(base + 8).map(u32::from), + 4 => u32_at(base + 8), + _ => None, + }; + if tag == 256 { + width = val; + } else { + height = val; + } + } + } + width.zip(height).is_some_and(|(w, h)| super::valid_image_size(w, h)) +} + +/// A UTF-8 HTML document for RTF, through `NSAttributedString`. +pub(super) fn rtf_to_html(rtf: &[u8]) -> Option<String> { + if rtf.is_empty() || rtf.len() > MAX_RTF_CONVERT_BYTES { return None; } + // SAFETY: the RTF data and attribute objects are valid Foundation instances, the range + // is `0..string.length()`, and `autoreleasepool` bounds autoreleased temporaries. + autoreleasepool(|_| unsafe { + let string = NSAttributedString::initWithRTF_documentAttributes(NSAttributedString::alloc(), &NSData::with_bytes(rtf), None)?; + let html_type: &AnyObject = NSHTMLTextDocumentType; + let utf8 = NSNumber::new_usize(NSUTF8StringEncoding); + let utf8: &AnyObject = &utf8; + let attributes = NSDictionary::from_slices(&[NSDocumentTypeDocumentAttribute, NSCharacterEncodingDocumentAttribute], &[html_type, utf8]); + let data = string.dataFromRange_documentAttributes_error(NSRange::new(0, string.length()), &attributes).ok()?; + if data.len() > MAX_RICH_BYTES { return None; } + String::from_utf8(data.to_vec()).ok() + }) +} + +/// Browsers read pasteboard HTML without a charset as Latin-1; say it's UTF-8. +fn declare_utf8(html: &str) -> std::borrow::Cow<'_, str> { + let head = &html.as_bytes()[..html.len().min(1024)]; + if head.windows(7).any(|w| w.eq_ignore_ascii_case(b"charset")) { return html.into(); } + format!("<meta charset=\"utf-8\">{html}").into() +} + +#[cfg(test)] +mod tests { + use super::*; + + const RTF: &str = r"{\rtf1\ansi\ansicpg1252\cocoartf2761 +{\fonttbl\f0\fswiss\fcharset0 Helvetica;} +\pard\f0\fs24 Hello \b bold\b0 and \i italic\i0 caf\'e9}"; + + /// Off the main thread, as on the clipboard worker, and bounded so a main-thread wait in + /// AppKit fails the test instead of hanging it. + #[test] + fn rtf_becomes_html_off_the_main_thread() { + let (send, recv) = std::sync::mpsc::channel(); + std::thread::spawn(move || { send.send(rtf_to_html(RTF.as_bytes())).ok(); }); + let html = recv.recv_timeout(std::time::Duration::from_secs(20)).expect("conversion finished").expect("converted"); + let text: String = super::super::sanitize_html(&html); + assert!(text.contains("Hello") && text.contains("bold") && text.contains("café"), "{text}"); + assert!(html.contains("font-weight: bold") || html.contains("<b>"), "{html}"); + assert!(rtf_to_html(b"not rtf").is_none()); + assert!(rtf_to_html(&[]).is_none()); + assert!(rtf_to_html(&vec![b'a'; MAX_RTF_CONVERT_BYTES + 1]).is_none(), "oversized RTF is refused before AppKit"); + } + + /// A private pasteboard, never the user's. Skipped where there is no pasteboard server (a + /// build machine's SSH session). + #[test] + fn every_form_round_trips_in_one_change() { + use objc2::ClassType; + // SAFETY: `+[NSPasteboard pasteboardWithUniqueName]` takes no arguments and returns an owned or nil `NSPasteboard`. + let pb: Option<Retained<NSPasteboard>> = unsafe { objc2::msg_send![NSPasteboard::class(), pasteboardWithUniqueName] }; + let Some(pb) = pb else { return eprintln!("no pasteboard server; skipped") }; + let before = pb.changeCount(); + let content = ClipboardContent::new("Hi there").with_html("<b>Hi</b> there").with_rtf(RTF); + write(&pb, &content).unwrap(); + assert_eq!(pb.changeCount(), before + 1); + let back = read(&pb, true).unwrap(); + assert_eq!(back.text(), "Hi there"); + assert!(back.html().unwrap().ends_with("<b>Hi</b> there")); + assert_eq!(back.rtf(), Some(RTF)); + + // SAFETY: `pb` is a live retained `NSPasteboard`, the `NSData` is valid, and `NSPasteboardTypeRTF` is an immutable static. + unsafe { + pb.clearContents(); + pb.setData_forType(Some(&NSData::with_bytes(RTF.as_bytes())), NSPasteboardTypeRTF); + } + let rtf_only = read(&pb, true).unwrap(); + assert_eq!(rtf_only.text(), "Hello bold and italic café", "the pasteboard derives text from RTF"); + assert!(rtf_only.html().unwrap().contains("bold")); + + let tiff = tiff_of(&png_2x3()); + // SAFETY: `pb` is a live retained `NSPasteboard`, the `NSData` is valid, and `NSPasteboardTypeTIFF` is an immutable static. + unsafe { + pb.clearContents(); + pb.setData_forType(Some(&NSData::with_bytes(&tiff)), NSPasteboardTypeTIFF); + } + assert_eq!(read(&pb, true).unwrap().image().map(ClipboardImage::size), Some((2, 3)), "a TIFF image pastes as PNG"); + assert!(read(&pb, false).is_none(), "an image is read only when asked for"); + // SAFETY: `pb` is a live retained `NSPasteboard`, the `NSString`/`NSData` values are valid, and the type constants are immutable statics. + unsafe { + pb.clearContents(); + pb.setString_forType(&NSString::from_str("shot.png"), NSPasteboardTypeString); + pb.setData_forType(Some(&NSData::with_bytes(&png_2x3())), NSPasteboardTypePNG); + } + let both = read(&pb, true).unwrap(); + assert_eq!((both.text(), both.image().map(|i| i.png().to_vec())), ("shot.png", Some(png_2x3())), "PNG passes through as is"); + // SAFETY: `pb` is a private pasteboard from `pasteboardWithUniqueName` and is not used after `releaseGlobally`. + let _: () = unsafe { objc2::msg_send![&pb, releaseGlobally] }; + } + + /// An image Rune copies goes on as PNG and TIFF with no empty text beside it; files go on + /// one item each, with every other form on the first. + #[test] + fn images_and_files_are_written_for_other_apps() { + use objc2::ClassType; + // SAFETY: `+[NSPasteboard pasteboardWithUniqueName]` takes no arguments and returns an owned or nil `NSPasteboard`. + let pb: Option<Retained<NSPasteboard>> = unsafe { objc2::msg_send![NSPasteboard::class(), pasteboardWithUniqueName] }; + let Some(pb) = pb else { return eprintln!("no pasteboard server; skipped") }; + let before = pb.changeCount(); + let image = ClipboardImage::from_png(png_2x3()).unwrap(); + write(&pb, &ClipboardContent::default().with_image(image.clone())).unwrap(); + assert_eq!(pb.changeCount(), before + 1); + // SAFETY: `pb` is a live retained `NSPasteboard` and the pasteboard type constants are immutable AppKit statics. + unsafe { + assert_eq!(pb.dataForType(NSPasteboardTypePNG).map(|d| d.to_vec()), Some(png_2x3())); + assert_eq!(pb.dataForType(NSPasteboardTypeTIFF).and_then(|d| tiff_to_png(d.as_bytes_unchecked())).map(|i| i.size()), Some((2, 3))); + assert!(pb.stringForType(NSPasteboardTypeString).is_none(), "an empty text isn't written beside the image"); + } + assert_eq!(read(&pb, true).unwrap(), ClipboardContent::default().with_image(image), "the image pastes back as is"); + + let files = [PathBuf::from("/fixtures/a.txt"), PathBuf::from("/fixtures/b c.png")]; + write(&pb, &ClipboardContent::new("a.txt b c.png").with_html("<b>files</b>").with_files(files.clone())).unwrap(); + let items = pb.pasteboardItems().unwrap(); + assert_eq!(items.count(), 2, "one item per file"); + // SAFETY: `items.count() == 2` was asserted above, so index 1 is in bounds, and `NSPasteboardTypeFileURL` is an immutable static. + let url = unsafe { items.objectAtIndex(1).stringForType(NSPasteboardTypeFileURL) }.unwrap().to_string(); + assert_eq!(url, "file:///fixtures/b%20c.png"); + // SAFETY: `items.count() == 2` was asserted above, so index 1 is in bounds, and `NSPasteboardTypeString` is an immutable static. + assert!(unsafe { items.objectAtIndex(1).stringForType(NSPasteboardTypeString) }.is_none(), "other forms ride on the first item"); + let back = read(&pb, true).unwrap(); + assert_eq!((back.text(), back.files()), ("a.txt b c.png", &files[..])); + assert!(read(&pb, false).unwrap().files().is_empty(), "files are read only when asked for"); + // SAFETY: `pb` is a private pasteboard from `pasteboardWithUniqueName` and is not used after `releaseGlobally`. + let _: () = unsafe { objc2::msg_send![&pb, releaseGlobally] }; + } + + fn png_2x3() -> Vec<u8> { + let rgba: Vec<u8> = (0..6u8).flat_map(|i| [i * 40, 255 - i * 40, 128, 255]).collect(); + crate::drag_out::encode_png(2, 3, &rgba).unwrap() + } + + fn tiff_of(png: &[u8]) -> Vec<u8> { png_to_tiff(png).unwrap().to_vec() } + + #[test] + fn tiff_becomes_png_off_the_main_thread() { + let (send, recv) = std::sync::mpsc::channel(); + std::thread::spawn(move || { send.send(tiff_to_png(&tiff_of(&png_2x3())).map(|i| (i.size(), i.png().starts_with(b"\x89PNG")))).ok(); }); + let converted = recv.recv_timeout(std::time::Duration::from_secs(20)).expect("conversion finished"); + assert_eq!(converted, Some(((2, 3), true))); + assert!(tiff_to_png(b"not a tiff").is_none()); + assert!(tiff_to_png(&[]).is_none()); + // A tiny TIFF header claiming 65535×65535 pixels (~4.3 GP) is refused before AppKit. + let mut bomb = Vec::from(&b"II\x2a\x00\x08\x00\x00\x00\x02\x00"[..]); + bomb.extend_from_slice(&[0x00, 0x01, 0x03, 0x00, 0x01, 0x00, 0x00, 0x00, 0xff, 0xff, 0x00, 0x00]); + bomb.extend_from_slice(&[0x01, 0x01, 0x03, 0x00, 0x01, 0x00, 0x00, 0x00, 0xff, 0xff, 0x00, 0x00]); + assert!(!tiff_dimensions_ok(&bomb)); + assert!(tiff_to_png(&bomb).is_none()); + } +} diff --git a/app/vendor/rune/crates/rune/src/clipboard/native.rs b/app/vendor/rune/crates/rune/src/clipboard/native.rs new file mode 100644 index 0000000..2c0c554 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/clipboard/native.rs @@ -0,0 +1,230 @@ +//! The OS clipboard: one worker thread over arboard, and the per-OS reads and writes. + +use super::*; + +impl Client { + pub(super) fn read_for(&self, purpose: Purpose) { + worker().send(Request::Read { purpose, reply: self.sender.clone(), wake: self.wake.clone() }).ok(); + } + pub(crate) fn flush_core(&self, rt: &mut crate::runtime::RuntimeCore) { + if rt.edit.has_clipboard() { return flush_memory(rt); } + #[cfg(test)] + if let Some(m) = &self.memory { return flush_to_memory(rt, m); } + #[cfg(target_os = "linux")] + self.flush_primary(rt); + // Nothing to clear before the first write. + if std::mem::take(&mut rt.edit.clear_secret_request) && let Some(w) = WORKER.get() { w.sender.send(Request::Clear(None)).ok(); } + if let Some(copy) = rt.copy_request.take() { + let worker = worker(); + copy.bind(Route::System(worker.clone())); + worker.send(Request::Write(copy, Some(Notify { changed: self.changed.clone(), wake: self.wake.clone() }))).ok(); + } + if let Some(target) = rt.edit.paste_request.take() { self.read_for(Purpose::paste(rt, target)); } + for id in std::mem::take(&mut rt.edit.read_requests) { self.read_for(Purpose::Read(id)); } + } +} + +static WORKER: OnceLock<Worker> = OnceLock::new(); +pub(super) struct Worker { + pub(super) sender: mpsc::Sender<Request>, + join: Mutex<Option<(std::thread::JoinHandle<()>, mpsc::Receiver<()>)>>, +} +impl Worker { + pub(super) fn spawn<B: Backend + 'static>(open: impl FnMut() -> Option<B> + Send + 'static) -> Self { + let (sender, recv) = mpsc::channel(); + let (done, completed) = mpsc::channel(); + let handle = std::thread::Builder::new().name("rune-clipboard".into()).spawn(move || { + run_worker(recv, open); + // Backend dropped (including Linux handoff) before acknowledging completion. + done.send(()).ok(); + }).expect("clipboard worker"); + Self { sender, join: Mutex::new(Some((handle, completed))) } + } + pub(super) fn stop(&self) { + let Some((handle, completed)) = self.join.lock().unwrap().take() else { return }; + self.sender.send(Request::Shutdown).ok(); + // A hung clipboard owner must not hang application exit. Join only after completion. + if completed.recv_timeout(Duration::from_millis(250)).is_ok() { handle.join().ok(); } + } +} +#[cfg(not(any(target_os = "ios", target_os = "android")))] +fn worker() -> &'static mpsc::Sender<Request> { + if cfg!(test) { + panic!("unit test reached the OS clipboard; install a test clipboard (`rt.use_clipboard` or `Client::use_memory`)"); + } + &WORKER.get_or_init(|| Worker::spawn(|| arboard::Clipboard::new().ok())).sender +} + +#[cfg(any(target_os = "ios", target_os = "android"))] +fn worker() -> &'static mpsc::Sender<Request> { + &WORKER.get_or_init(|| Worker::spawn(|| None::<Board>)).sender +} + +/// Called by the shared event-loop exit path, including overlay-only applications. +/// `clipboard::clear_secret_now`: the worker clears the last secret if it still holds the clipboard. +#[cfg(target_os = "windows")] +pub(super) fn clear_secret_now() { + if let Some(w) = WORKER.get() { w.sender.send(Request::Clear(None)).ok(); } +} + +pub(super) fn shutdown() { + if let Some(worker) = WORKER.get() { worker.stop(); } +} + +#[cfg(not(any(target_os = "ios", target_os = "android")))] +impl Backend for arboard::Clipboard { + fn write(&mut self, copy: &ClipboardWrite) -> Result<(), String> { write(self, copy) } + fn text(&mut self) -> Option<Zeroizing<String>> { self.get_text().ok().map(Zeroizing::new) } + #[cfg(target_os = "macos")] + fn content(&mut self, all: bool) -> Option<ClipboardContent> { + macos::read(&objc2_app_kit::NSPasteboard::generalPasteboard(), all) + } + /// Text, HTML, and with `all` an image and files; RTF isn't read here. Windows and Linux + /// images come through arboard as pixels (Windows `PNG` or `CF_DIBV5`, Linux `image/png`), + /// encoded as PNG again. + #[cfg(not(target_os = "macos"))] + fn content(&mut self, all: bool) -> Option<ClipboardContent> { + let text = self.text(); + #[cfg(target_os = "windows")] + let html = windows_read_html().or_else(|| self.get().html().ok()).filter(|h| !h.is_empty() && h.len() <= html::MAX_RICH_BYTES); + #[cfg(not(target_os = "windows"))] + let html = self.get().html().ok().filter(|h| !h.is_empty() && h.len() <= html::MAX_RICH_BYTES); + #[cfg(any(target_os = "windows", all(unix, not(any(target_os = "ios", target_os = "android")))))] + let image = all.then(|| self.get_image().ok()).flatten() + .and_then(|i| u32::try_from(i.width).ok().zip(u32::try_from(i.height).ok()).and_then(|(w, h)| ClipboardImage::from_rgba(w, h, &i.bytes))); + #[cfg(not(any(target_os = "windows", all(unix, not(any(target_os = "ios", target_os = "android"))))))] + let image: Option<ClipboardImage> = None; + let files = if all { self.get().file_list().unwrap_or_default() } else { Vec::new() }; + if text.is_none() && html.is_none() && image.is_none() && files.is_empty() { return None; } + let mut content = ClipboardContent::from(text.unwrap_or_default()).with_files(files); + if let Some(html) = html { content = content.with_html(html); } + if let Some(image) = image { content = content.with_image(image); } + Some(content) + } + fn revision(&self) -> Option<u64> { revision() } + fn clear(&mut self) -> Result<(), String> { arboard::Clipboard::clear(self).map_err(|e| e.to_string()) } +} + +fn run_worker<B: Backend>(recv: mpsc::Receiver<Request>, mut open: impl FnMut() -> Option<B>) { + let mut clipboard: Option<B> = None; + let mut core = Core::default(); + loop { + let request = match core.next_check() { + Some(at) => recv.recv_timeout(at.saturating_duration_since(crate::time::now())), + None => recv.recv().map_err(|_| mpsc::RecvTimeoutError::Disconnected), + }; + if let Some(cb) = &mut clipboard { core.tick(cb); } + let request = match request { + Ok(Request::Shutdown) | Err(mpsc::RecvTimeoutError::Disconnected) => break, + Ok(request) => request, + Err(mpsc::RecvTimeoutError::Timeout) => continue, + }; + if matches!(request, Request::Clear(_)) && core.hold.is_free() { continue; } + if clipboard.is_none() { clipboard = open(); } + let Some(cb) = &mut clipboard else { + if let Request::Write(copy, notify) = request && let Some(slot) = copy.slot() { + slot.set(SecretState::Failed("no clipboard".into())); + if let Some(n) = notify { n.send(); } + } + continue; + }; + core.handle(cb, request); + } + if let Some(cb) = clipboard.as_mut() { core.clear(cb, None); } + drop(clipboard); +} + +#[cfg(not(any(target_os = "ios", target_os = "android")))] +fn write(cb: &mut arboard::Clipboard, copy: &ClipboardWrite) -> Result<(), String> { + let content = &copy.content; + if copy.clear_after.is_none() && content.is_rich() { + #[cfg(target_os = "macos")] + { return macos::write(&objc2_app_kit::NSPasteboard::generalPasteboard(), content); } + #[cfg(not(target_os = "macos"))] + return write_one_form(cb, content); + } + write_text(cb, copy).map_err(|e| e.to_string()) +} + +/// Windows and Linux hold one of Rune's forms per write: the files, else the image, else HTML +/// beside the text (CF_HTML, `text/html`), else the text. RTF isn't written. +#[cfg(all(not(target_os = "macos"), not(target_os = "ios"), not(target_os = "android")))] +fn write_one_form(cb: &mut arboard::Clipboard, content: &ClipboardContent) -> Result<(), String> { + let error = |e: arboard::Error| e.to_string(); + if !content.files().is_empty() { return cb.set().file_list(content.files()).map_err(error); } + #[cfg(any(target_os = "windows", all(unix, not(any(target_os = "ios", target_os = "android")))))] + if let Some(rgba) = content.image().and_then(ClipboardImage::to_rgba) { + let (width, height) = (rgba.width() as usize, rgba.height() as usize); + return cb.set_image(arboard::ImageData { width, height, bytes: rgba.into_raw().into() }).map_err(error); + } + match content.html() { + Some(html) => cb.set().html(html, Some(content.text())).map_err(error), + None => cb.set_text(content.text()).map_err(error), + } +} + +#[cfg(not(any(target_os = "ios", target_os = "android")))] +fn write_text(cb: &mut arboard::Clipboard, copy: &ClipboardWrite) -> Result<(), arboard::Error> { + let text = copy.content.text(); + if copy.clear_after.is_none() { return cb.set_text(text); } + #[cfg(target_os = "macos")] + { use arboard::SetExtApple; return cb.set().exclude_from_history().text(text); } + #[cfg(target_os = "windows")] + { use arboard::SetExtWindows; return cb.set().exclude_from_monitoring().text(text); } + #[cfg(all(unix, not(target_os = "macos"), not(target_os = "ios"), not(target_os = "android")))] + { use arboard::SetExtLinux; return cb.set().exclude_from_history().text(text); } + #[allow(unreachable_code)] + cb.set_text(text) +} + +#[cfg(not(any(target_os = "ios", target_os = "android")))] +#[allow(unsafe_code)] +fn revision() -> Option<u64> { + #[cfg(target_os = "macos")] + { return Some(objc2_app_kit::NSPasteboard::generalPasteboard().changeCount() as u64); } + #[cfg(target_os = "windows")] + // SAFETY: `GetClipboardSequenceNumber` takes no pointers and is safe to call from any thread. + { return Some(unsafe { windows_sys::Win32::System::DataExchange::GetClipboardSequenceNumber() } as u64); } + // Linux's portable clipboard API has no generation counter; compare the current text. + #[allow(unreachable_code)] + None +} + +/// Reads Windows `CF_HTML` (`HTML Format`) directly so `-1` offsets and `<!--StartFragment-->` +/// markers from other apps work instead of failing `clipboard-win`'s unsigned offset parser. +#[cfg(target_os = "windows")] +#[allow(unsafe_code)] +fn windows_read_html() -> Option<String> { + use windows_sys::Win32::System::DataExchange::{ + CloseClipboard, GetClipboardData, IsClipboardFormatAvailable, OpenClipboard, RegisterClipboardFormatW, + }; + use windows_sys::Win32::System::Memory::{GlobalLock, GlobalSize, GlobalUnlock}; + const NAME: &[u16] = &[b'H' as u16, b'T' as u16, b'M' as u16, b'L' as u16, b' ' as u16, b'F' as u16, b'o' as u16, b'r' as u16, b'm' as u16, b'a' as u16, b't' as u16, 0]; + // SAFETY: `NAME` is NUL-terminated; the clipboard is held open around `GetClipboardData` and + // closed before returning, and `ptr` is non-null and locked via `GlobalLock` for `size` bytes. + unsafe { + let format = RegisterClipboardFormatW(NAME.as_ptr()); + if format == 0 || IsClipboardFormatAvailable(format) == 0 { return None; } + let mut opened = false; + for _ in 0..5 { + if OpenClipboard(core::ptr::null_mut()) != 0 { opened = true; break; } + std::thread::sleep(Duration::from_millis(5)); + } + if !opened { return None; } + let handle = GetClipboardData(format); + let out = if !handle.is_null() { + let size = GlobalSize(handle); + let ptr = GlobalLock(handle) as *const u8; + let res = (!ptr.is_null() && size > 0 && size <= html::MAX_RICH_BYTES * 2) + .then(|| html::unpack_cf_html(core::slice::from_raw_parts(ptr, size))) + .flatten(); + if !ptr.is_null() { let _ = GlobalUnlock(handle); } + res + } else { + None + }; + let _ = CloseClipboard(); + out + } +} + diff --git a/app/vendor/rune/crates/rune/src/clipboard/primary.rs b/app/vendor/rune/crates/rune/src/clipboard/primary.rs new file mode 100644 index 0000000..613f578 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/clipboard/primary.rs @@ -0,0 +1,52 @@ +//! Linux's primary selection on the OS (X11 `PRIMARY`, Wayland's primary selection through +//! data control): its own worker over arboard, beside the clipboard's, so a primary read never +//! waits behind a clipboard read and a secret's hold never sees it. What goes on it and where a +//! middle click pastes it is the runtime's (`runtime/input/primary_selection.rs`). +use arboard::{GetExtLinux, LinuxClipboardKind, SetExtLinux}; + +use super::*; + +enum Request { + Write(String), + /// Paste it into field `target`: the answer comes back as that field's paste. + Read { target: String, reply: mpsc::Sender<Reply>, wake: Waker }, +} + +static WORKER: OnceLock<mpsc::Sender<Request>> = OnceLock::new(); + +fn worker() -> &'static mpsc::Sender<Request> { + if cfg!(test) { + panic!("unit test reached the OS primary selection; install a test clipboard (`rt.use_clipboard` or `Client::use_memory`)"); + } + WORKER.get_or_init(|| { + let (sender, requests) = mpsc::channel(); + std::thread::Builder::new().name("rune-primary".into()).spawn(move || run(requests)).ok(); + sender + }) +} + +fn run(requests: mpsc::Receiver<Request>) { + let mut board: Option<arboard::Clipboard> = None; + for request in requests { + if board.is_none() { board = arboard::Clipboard::new().ok(); } + let Some(cb) = board.as_mut() else { continue }; + match request { + Request::Write(text) => { cb.set().clipboard(LinuxClipboardKind::Primary).text(text).ok(); } + Request::Read { target, reply, wake } => { + let text = cb.get().clipboard(LinuxClipboardKind::Primary).text().ok().filter(|t| !t.is_empty()); + let answer = Purpose::Paste(Some(target), Forms::Text).reply(text.map(|t| ClipboardContent::from(Zeroizing::new(t)))); + if let Some(answer) = answer && reply.send(answer).is_ok() { wake(); } + } + } + } +} + +impl Client { + /// Hands the worker what the runtime asked of the primary selection. + pub(super) fn flush_primary(&self, rt: &mut crate::runtime::RuntimeCore) { + if let Some(text) = rt.edit.primary.write.take() { worker().send(Request::Write(text)).ok(); } + if let Some(target) = rt.edit.primary.paste.take() { + worker().send(Request::Read { target, reply: self.sender.clone(), wake: self.wake.clone() }).ok(); + } + } +} diff --git a/app/vendor/rune/crates/rune/src/clipboard/secret.rs b/app/vendor/rune/crates/rune/src/clipboard/secret.rs new file mode 100644 index 0000000..cd62798 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/clipboard/secret.rs @@ -0,0 +1,287 @@ +//! A secret copy's life, as two machines. A [`Secret`] is the copy itself, shared by every clone +//! of its write: what it reports, and whether `clear_now` ran. A [`Hold`] is one clipboard's +//! record of the secret it wrote last, so a clone written to two clipboards is cleaned up on each +//! and neither's report can disarm the other. +use std::sync::{Arc, Mutex, OnceLock, Weak}; +use crate::machine::{Attempt, Effects, Seq}; +use crate::time::Instant; +use super::{Notify, Request, Route, lock}; + +/// What became of a secret copy. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub enum SecretState { + /// Not written yet. + #[default] + Pending, + /// On the clipboard: the last copy Rune wrote, and the clipboard hasn't changed since. + Holding, + /// Cleared by Rune: its delay ran out, or `clear_now` or `Tx::clear_secret_clipboard` ran. + Cleared, + /// Something else took its place: a later copy, a change by another app, or a newer copy + /// before this one was written. Its countdown should end quietly. + Replaced, + /// The write failed, and the clipboard didn't change; or the clipboard refused Rune's wipe, + /// and may still hold the secret. + Failed(String), +} + +/// A secret copy: the last thing reported about it, whether it may be written again, and how many +/// clipboards have a [`Hold`] on it. +#[derive(Clone, Debug, PartialEq, Eq)] +pub(super) enum Secret { + /// `clear_now` hasn't run: a clone of its write can still be written, even after it expired. + Live { report: Report, holds: u32 }, + /// `clear_now` ran: no clone of its write is written again, whatever it last reported. + Cancelled { report: Report, holds: u32 }, +} +impl Default for Secret { + fn default() -> Self { Self::Live { report: Report::Said(SecretState::Pending), holds: 0 } } +} +impl Secret { + fn report(&self) -> &Report { + let (Self::Live { report, .. } | Self::Cancelled { report, .. }) = self; + report + } +} + +/// What a secret copy last reported. +#[derive(Clone, Debug, PartialEq, Eq)] +pub(super) enum Report { + Said(SecretState), + /// The clipboard refused Rune's wipe. Its handle says `Failed`, but this is no failed write: + /// nothing is left for `clear_now` to recover. + Refused, +} +impl Report { + fn shown(&self) -> SecretState { + match self { + Self::Said(state) => state.clone(), + Self::Refused => SecretState::Failed(REFUSED.into()), + } + } + fn failed_write(&self) -> bool { matches!(self, Self::Said(SecretState::Failed(_))) } +} + +/// What a secret reports when the clipboard refused Rune's wipe. +pub(super) const REFUSED: &str = "the clipboard refused the wipe"; + +#[derive(Debug)] +pub(super) enum SecretEvent { + /// `clear_now` ran. + Cancel, + /// A clipboard took a hold on this copy. + Held, + /// A clipboard's hold ended, with this outcome. + Released(Report), + /// A write of this copy failed; the latest report stands. + Report(SecretState), + /// The last clone of its write was dropped. + Dropped, +} + +#[derive(Debug, PartialEq, Eq)] +pub(super) enum SecretEffect { + /// Ask the clipboard this copy was first written to for a clear. + Clear, +} + +pub(super) fn step(secret: &mut Secret, event: SecretEvent) -> Effects<SecretEffect> { + match event { + SecretEvent::Cancel => { + let (Secret::Live { report, holds } | Secret::Cancelled { report, holds }) = std::mem::take(secret); + // A failed replay reports `Failed` while its earlier write is still on the clipboard. + let held = report == Report::Said(SecretState::Holding) || (report.failed_write() && holds > 0); + *secret = Secret::Cancelled { report, holds }; + if held { Effects::one(SecretEffect::Clear) } else { Effects::none() } + } + SecretEvent::Held => { + let (Secret::Live { report, holds } | Secret::Cancelled { report, holds }) = secret; + *report = Report::Said(SecretState::Holding); + *holds += 1; + Effects::none() + } + SecretEvent::Released(next) => { + let (Secret::Live { report, holds } | Secret::Cancelled { report, holds }) = secret; + *report = next; + *holds = holds.saturating_sub(1); + Effects::none() + } + SecretEvent::Report(next) => { + let (Secret::Live { report, .. } | Secret::Cancelled { report, .. }) = secret; + *report = Report::Said(next); + Effects::none() + } + SecretEvent::Dropped => { + match secret { + Secret::Live { report: report @ Report::Said(SecretState::Pending), .. } => *report = Report::Said(SecretState::Replaced), + Secret::Cancelled { report: report @ Report::Said(SecretState::Pending), .. } => *report = Report::Said(SecretState::Cleared), + _ => {} + } + Effects::none() + } + } +} + +#[derive(Default)] +pub(super) struct Slot { + secret: Mutex<Secret>, + pub(super) route: OnceLock<Route>, +} +impl Slot { + fn step(&self, event: SecretEvent) -> Effects<SecretEffect> { step(&mut lock(&self.secret), event) } + pub(super) fn set(&self, state: SecretState) { self.step(SecretEvent::Report(state)); } + /// A write of it failed: a refused wipe isn't one. + pub(super) fn failed(&self) -> bool { lock(&self.secret).report().failed_write() } + pub(super) fn held(&self) { self.step(SecretEvent::Held); } + pub(super) fn released(&self, report: Report) { self.step(SecretEvent::Released(report)); } + pub(super) fn cancelled(&self) -> bool { matches!(*lock(&self.secret), Secret::Cancelled { .. }) } + fn state(&self) -> SecretState { lock(&self.secret).report().shown() } +} + +/// Settles a secret write that was dropped before reaching a clipboard (replaced in its +/// handler, cancelled, or left in a headless runtime with no clipboard). +pub(super) struct Unwritten(pub(super) Arc<Slot>); +impl Drop for Unwritten { + fn drop(&mut self) { self.0.step(SecretEvent::Dropped); } +} + +/// A secret copy from `Tx::copy_secret`. It holds no text, and is cheap to clone and send. +/// Its state is updated by the clipboard worker; asking never reads the OS clipboard. +#[derive(Clone)] +pub struct SecretCopy(pub(super) Arc<Slot>); +impl SecretCopy { + /// A copy that is never written and stays `Pending`, for scenes and tests that show a copy + /// in flight without a `Tx`. + pub fn pending() -> Self { Self(Arc::default()) } + pub fn state(&self) -> SecretState { + if let Some(Route::Memory(m)) = self.0.route.get() { m.tick(); } + self.0.state() + } + /// Still the last copy Rune wrote, and the clipboard hasn't changed since. The OS + /// clipboard is checked a few times a second while a secret is held. + pub fn holds(&self) -> bool { self.state() == SecretState::Holding } + /// Clear the clipboard now if this copy still holds it, on the clipboard worker. A copy not + /// yet written is never written. Idempotent. + pub fn clear_now(&self) { + for effect in self.0.step(SecretEvent::Cancel) { + match effect { + SecretEffect::Clear => { + if let Some(route) = self.0.route.get() { route.send(Request::Clear(Some(self.0.clone()))); } + } + } + } + } +} +impl std::fmt::Debug for SecretCopy { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_tuple("SecretCopy").field(&self.0.state()).finish() + } +} + +/// A timed clear the clipboard's owner is waiting on. It only counts while its attempt is the +/// one the [`Hold`] still has. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) struct Alarm { + pub(super) attempt: Attempt, + pub(super) due: Instant, +} + +/// One clipboard's record of the secret Rune wrote to it last. +#[derive(Default)] +pub(super) enum Hold { + /// Nothing of ours to clean up. + #[default] + Free, + /// The clipboard may still hold this secret. + Holding { + attempt: Attempt, + /// The slot owns the first clipboard's route. A hold must wipe even if nobody + /// is left to receive its report, but must not keep that clipboard alive. + slot: Weak<Slot>, + notify: Option<Notify>, + /// `None` only when the delay is too long for the clock to represent. + due: Option<Instant>, + /// The clipboard's change count after the write, where it has one. + revision: Option<u64>, + /// A keyed hash of the text, so the text needn't stay in memory until the clear. + print: u64, + }, +} +impl Hold { + pub(super) fn is_free(&self) -> bool { matches!(self, Self::Free) } + /// Whether a clear of `which`, or of whichever secret is held, applies here. + pub(super) fn answers(&self, which: Option<&Arc<Slot>>) -> bool { + match self { + Self::Free => false, + Self::Holding { slot, .. } => which.is_none_or(|w| std::ptr::eq(slot.as_ptr(), Arc::as_ptr(w))), + } + } + pub(super) fn armed(&self, alarm: Attempt) -> bool { + matches!(self, Self::Holding { attempt, .. } if *attempt == alarm) + } + pub(super) fn next_check(&self, watch: Instant) -> Option<Instant> { + let Self::Holding { due, .. } = self else { return None }; + Some(due.map_or(watch, |d| d.min(watch))) + } +} + +pub(super) enum HoldEvent { + /// A secret reached the clipboard and has been reported as holding it. + Written { slot: Arc<Slot>, notify: Option<Notify>, due: Option<Instant>, revision: Option<u64>, print: u64 }, + /// A later write took its place, or the clipboard changed under it. + Lost, + /// A clear was asked for; `ours` says whether the clipboard still has what Rune wrote. + Clear { ours: bool }, + /// The caller wiped the clipboard itself and confirmed it. + Wiped, + /// An alarm came due. + Due { attempt: Attempt, ours: bool }, + /// The answer to [`HoldEffect::Wipe`]: whether the clipboard took it. + Swept { ok: bool }, +} + +pub(super) enum HoldEffect { + /// Wipe the clipboard, and answer with [`HoldEvent::Swept`]. + Wipe, + Release(Arc<Slot>, Report), + Notify(Notify), + /// Replace the alarm being waited on: a new hold never inherits the last one's. + Arm(Option<Alarm>), +} + +pub(super) fn step_hold(seq: &mut Seq, hold: &mut Hold, event: HoldEvent) -> Effects<HoldEffect> { + match event { + HoldEvent::Written { slot, notify, due, revision, print } => { + let mut effects = release(hold, said(SecretState::Replaced)); + let attempt = seq.next(); + *hold = Hold::Holding { attempt, slot: Arc::downgrade(&slot), notify: notify.clone(), due, revision, print }; + effects.push(HoldEffect::Arm(due.map(|due| Alarm { attempt, due }))); + if let Some(notify) = notify { effects.push(HoldEffect::Notify(notify)); } + effects + } + HoldEvent::Lost => release(hold, said(SecretState::Replaced)), + HoldEvent::Clear { ours } => settle(hold, ours), + HoldEvent::Wiped => release(hold, said(SecretState::Cleared)), + HoldEvent::Due { attempt, ours } if hold.armed(attempt) => settle(hold, ours), + HoldEvent::Due { .. } => Effects::none(), + HoldEvent::Swept { ok: true } => release(hold, said(SecretState::Cleared)), + // Final: trying again could erase a copy another app made after the check. + HoldEvent::Swept { ok: false } => release(hold, Report::Refused), + } +} + +/// Ends a hold on a clear: wipes only what is still ours. +fn settle(hold: &mut Hold, ours: bool) -> Effects<HoldEffect> { + if hold.is_free() || !ours { return release(hold, said(SecretState::Replaced)); } + Effects::one(HoldEffect::Wipe) +} + +fn said(state: SecretState) -> Report { Report::Said(state) } + +fn release(hold: &mut Hold, report: Report) -> Effects<HoldEffect> { + let Hold::Holding { slot, notify, .. } = std::mem::take(hold) else { return Effects::none() }; + let mut effects = Effects::none(); + if let Some(slot) = slot.upgrade() { effects.push(HoldEffect::Release(slot, report)); } + if let Some(notify) = notify { effects.push(HoldEffect::Notify(notify)); } + effects +} diff --git a/app/vendor/rune/crates/rune/src/clipboard/secret_tests.rs b/app/vendor/rune/crates/rune/src/clipboard/secret_tests.rs new file mode 100644 index 0000000..b789cf5 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/clipboard/secret_tests.rs @@ -0,0 +1,753 @@ +//! Every order of clipboard events, through the machines and through a transcription of the +//! flags they replaced. The two have to agree on everything an app or another app can see. +use std::cell::Cell; +use std::rc::Rc; +use std::sync::atomic::AtomicUsize; +use crate::machine::Effects; +use super::secret::{REFUSED, Report, Secret, SecretEffect, SecretEvent, step}; +use super::*; + +#[path = "hold_tests.rs"] +mod hold; + +const LONG: Duration = Duration::from_secs(3600); +const PAST_LONG: Duration = Duration::from_secs(3601); +const SECRET: &str = "fixture-secret"; +const PILLS: &str = "a <span data-pill=\"agent:x\">@x</span> b"; + +/// The logic before the machines, kept as it was: a state, a cancel flag beside it, and a held +/// record per clipboard. +mod flags { + use super::*; + + pub type Queue = mpsc::Sender<Arc<Slot>>; + + #[derive(Default)] + pub struct Slot { + pub state: Mutex<SecretState>, + pub cancel: AtomicBool, + pub route: OnceLock<Queue>, + // differs from dev: counts the clipboards holding this secret, for `clear_now`. + pub holders: AtomicUsize, + } + impl Slot { + pub fn set(&self, state: SecretState) { *lock(&self.state) = state; } + } + + pub struct Unwritten(pub Arc<Slot>); + impl Drop for Unwritten { + fn drop(&mut self) { + let mut state = lock(&self.0.state); + if *state == SecretState::Pending { + *state = if self.0.cancel.load(Ordering::SeqCst) { SecretState::Cleared } else { SecretState::Replaced }; + } + } + } + + #[derive(Clone)] + pub struct Write { + pub content: ClipboardContent, + pub clear_after: Option<Duration>, + pub secret: Option<Arc<Unwritten>>, + } + impl Write { + pub fn slot(&self) -> Option<&Arc<Slot>> { self.secret.as_ref().map(|u| &u.0) } + } + + // differs from dev: a refused wipe reports Failed too (r128), and isn't a failed write. + fn failed_write(state: &SecretState) -> bool { matches!(state, SecretState::Failed(e) if e != REFUSED) } + + #[derive(Clone)] + pub struct Copy(pub Arc<Slot>); + impl Copy { + pub fn clear_now(&self) { + self.0.cancel.store(true, Ordering::SeqCst); + let holding = *lock(&self.0.state) == SecretState::Holding; + // differs from dev: a failed replay leaves its earlier write held, and is cleared too. + let holding = holding || (failed_write(&lock(&self.0.state)) && self.0.holders.load(Ordering::SeqCst) > 0); + if holding && let Some(route) = self.0.route.get() { route.send(self.0.clone()).ok(); } + } + } + + struct Held { + slot: Option<Arc<Slot>>, + notify: Option<Notify>, + deadline: Option<Instant>, + revision: Option<u64>, + print: u64, + } + + struct OwnPills { + revision: Option<u64>, + text_print: u64, + pills: Vec<(std::ops::Range<usize>, String)>, + } + + #[derive(Default)] + pub struct Core { keys: RandomState, held: Option<Held>, own_pills: Option<OwnPills> } + impl Core { + pub fn watching(&self) -> bool { self.held.is_some() } + + pub fn answer(&mut self, cb: &mut Fake, purpose: Purpose) -> Option<Reply> { + let mut reply = purpose.answer(cb)?; + if let Some(own) = &self.own_pills { + let rev_ok = match (own.revision, cb.revision()) { + (Some(a), Some(b)) => a == b, + (None, None) => true, + _ => false, + }; + let html_ok = reply.content.html().is_some_and(|h| { + let frag = crate::TextEdit::from_html(h); + frag.pills().count() == own.pills.len() + && frag.pills().zip(&own.pills).all(|((r1, id1), (r2, id2))| r1 == *r2 && id1 == id2) + }); + if rev_ok && self.keys.hash_one(reply.content.text()) == own.text_print && html_ok { + reply.content.own_pills = true; + } + } + Some(reply) + } + + pub fn write(&mut self, cb: &mut Fake, copy: Write, notify: Option<Notify>, steps: &dyn WriteSteps) { + let slot = copy.slot().cloned(); + let notify = notify.filter(|_| slot.is_some()); + let cancelled = |slot: &Option<Arc<Slot>>| slot.as_ref().is_some_and(|s| s.cancel.load(Ordering::SeqCst)); + if cancelled(&slot) { return; } + if let Err(error) = cb.land(&copy.content) { + if let Some(s) = &slot { s.set(SecretState::Failed(error)); } + if let Some(n) = &notify { n.send(); } + return; + } + self.release(SecretState::Replaced); + let rev = cb.revision(); + self.own_pills = copy + .clear_after + .is_none() + .then(|| copy.content.html()) + .flatten() + .filter(|h| h.contains("<span data-pill=")) + .map(|h| { + let frag = crate::TextEdit::from_html(h); + OwnPills { + revision: rev, + text_print: self.keys.hash_one(copy.content.text()), + pills: frag.pills().map(|(r, id)| (r, id.to_owned())).collect(), + } + }) + .filter(|o| !o.pills.is_empty()); + if let Some(delay) = copy.clear_after { + if let Some(s) = &slot { + // differs from dev: counts the hold. + s.holders.fetch_add(1, Ordering::SeqCst); + s.set(SecretState::Holding); + } + self.held = Some(Held { + slot: slot.clone(), + notify: notify.clone(), + deadline: steps.now().checked_add(delay), + revision: rev, + print: { + steps.hashing(); + self.keys.hash_one(copy.content.text()) + }, + }); + if let Some(n) = &notify { n.send(); } + if cancelled(&slot) { self.clear(cb, slot.as_ref()); } + } + } + + fn release(&mut self, state: SecretState) { + let Some(held) = self.held.take() else { return }; + if let Some(s) = &held.slot { + // differs from dev: counts the hold ending. + s.holders.fetch_sub(1, Ordering::SeqCst); + s.set(state); + } + if let Some(n) = &held.notify { n.send(); } + } + + fn unchanged(&self, cb: &mut Fake) -> bool { + let Some(held) = &self.held else { return false }; + held.revision == cb.revision() && cb.text().is_some_and(|t| self.keys.hash_one(t.as_str()) == held.print) + } + + pub fn clear(&mut self, cb: &mut Fake, which: Option<&Arc<Slot>>) { + let Some(held) = &self.held else { return }; + if which.is_some_and(|w| !held.slot.as_ref().is_some_and(|s| Arc::ptr_eq(s, w))) { return; } + // differs from dev: dev sent no clear for a failed replay. This one keeps the hold and + // its deadline unless the wipe is confirmed, so the timeout still clears the secret. + if which.is_some_and(|w| failed_write(&lock(&w.state))) { + // differs from dev: a copy arriving between this check and the wipe is erased here, + // where dev sent no clear. It's the same race as dev's clear_now; r130 fixes it for + // every wipe. + if !self.unchanged(cb) || cb.clear().is_err() || self.unchanged(cb) { return; } + self.own_pills = None; + return self.release(SecretState::Cleared); + } + if self.unchanged(cb) { + // differs from dev: a wipe the clipboard refuses is final and reported as Failed + // (r128); dev reported Cleared. + let refused = cb.clear().is_err(); + self.own_pills = None; + self.release(if refused { SecretState::Failed(REFUSED.into()) } else { SecretState::Cleared }); + } else { + self.release(SecretState::Replaced); + } + } + + pub fn tick(&mut self, cb: &mut Fake, now: Instant) { + if let Some(own) = &self.own_pills + && let Some(rev) = own.revision + && cb.revision() != Some(rev) + { + self.own_pills = None; + } + let Some(held) = &self.held else { return }; + if held.deadline.is_some_and(|d| now >= d) { return self.clear(cb, None); } + let changed = match held.revision { + Some(revision) => cb.revision() != Some(revision), + None => !self.unchanged(cb), + }; + if changed { self.release(SecretState::Replaced); } + } + } +} + +/// What a sequence can see happen, in order. +#[derive(Clone, Debug, PartialEq, Eq)] +enum Logged { + Wrote(usize), + Wiped(usize), + Woke(usize, SecretState, SecretState), + /// A write read the clock, with what `S` and `T` reported then. + ReadClock(SecretState, SecretState), + /// A write began hashing its secret. + Hashing(SecretState, SecretState), +} +type Log = Arc<Mutex<Vec<Logged>>>; + +/// How a clipboard responds to being wiped. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum WipeMode { + Works, + Refused, + /// Says it worked, and changes nothing. + NoEffect, + /// Refused, and the clipboard is locked for reading from then on. + RefusedAndLocks, +} + +/// A clipboard with a scripted interruption during its next write. +struct Fake { + id: usize, + content: Option<ClipboardContent>, + count: u64, + counted: bool, + /// The change count when `SECRET` last landed. + landed: Option<u64>, + /// The last change was another app's. + others: bool, + fail: Option<String>, + unreadable: bool, + wipe: WipeMode, + log: Log, + during_write: Option<Box<dyn FnOnce(&mut Fake)>>, +} +impl Fake { + fn land(&mut self, content: &ClipboardContent) -> Result<(), String> { + let result = match &self.fail { + Some(error) => Err(error.clone()), + None => { + self.content = Some(content.clone()); + self.count += 1; + self.others = false; + if content.text() == SECRET { self.landed = Some(self.count); } + lock(&self.log).push(Logged::Wrote(self.id)); + Ok(()) + } + }; + if let Some(hook) = self.during_write.take() { hook(self); } + result + } + fn other_app(&mut self, text: &str) { + self.content = Some(ClipboardContent::new(text)); + self.count += 1; + self.others = true; + } + fn failing(&self) -> bool { self.unreadable || self.wipe != WipeMode::Works } + /// Still exactly the secret Rune wrote. + fn ours(&self) -> bool { self.landed == Some(self.count) } + /// Another app's copy Rune can tell from its own. + fn others_copy(&self) -> Option<&ClipboardContent> { + self.content.as_ref().filter(|c| self.others && (self.counted || c.text() != SECRET)) + } +} +impl Backend for Fake { + fn write(&mut self, copy: &ClipboardWrite) -> Result<(), String> { self.land(&copy.content) } + fn text(&mut self) -> Option<Zeroizing<String>> { + if self.unreadable { return None; } + self.content.as_ref().filter(|c| c.has_plain()).map(|c| Zeroizing::new(c.text().to_owned())) + } + fn content(&mut self, all: bool) -> Option<ClipboardContent> { + if self.unreadable { return None; } + self.content.clone().and_then(|c| if all { Some(c) } else { c.text_forms() }) + } + fn revision(&self) -> Option<u64> { self.counted.then_some(self.count) } + fn clear(&mut self) -> Result<(), String> { + match self.wipe { + WipeMode::Works => {} + WipeMode::Refused => return Err("locked".into()), + WipeMode::NoEffect => return Ok(()), + WipeMode::RefusedAndLocks => { + self.unreadable = true; + return Err("locked".into()); + } + } + self.content = None; + self.count += 1; + self.others = false; + lock(&self.log).push(Logged::Wiped(self.id)); + Ok(()) + } +} + +/// The two implementations, behind what the rig drives. +trait Engine: Default { + type Write: Clone; + type Copy: Clone + 'static; + type Queued; + fn secret(text: &str, after: Duration) -> (Self::Write, Self::Copy); + fn pills() -> Self::Write; + fn bind(write: &Self::Write, queue: &mpsc::Sender<Self::Queued>); + fn clear_now(copy: &Self::Copy); + fn state(copy: &Self::Copy) -> SecretState; + fn cancelled(copy: &Self::Copy) -> bool; + fn write(&mut self, cb: &mut Fake, write: Self::Write, notify: Notify, steps: &dyn WriteSteps); + fn tick(&mut self, cb: &mut Fake, now: Instant); + fn read(&mut self, cb: &mut Fake) -> Option<Reply>; + fn clear_held(&mut self, cb: &mut Fake); + fn run(&mut self, cb: &mut Fake, queued: Self::Queued); + fn watching(&self) -> bool; +} + +impl Engine for Core { + type Write = ClipboardWrite; + type Copy = SecretCopy; + type Queued = Request; + fn secret(text: &str, after: Duration) -> (ClipboardWrite, SecretCopy) { ClipboardWrite::secret(text.into(), after) } + fn pills() -> ClipboardWrite { ClipboardWrite::new(ClipboardContent::new("a @x b").with_html(PILLS)) } + fn bind(write: &ClipboardWrite, queue: &mpsc::Sender<Request>) { write.bind(Route::System(queue.clone())); } + fn clear_now(copy: &SecretCopy) { copy.clear_now(); } + fn state(copy: &SecretCopy) -> SecretState { copy.state() } + fn cancelled(copy: &SecretCopy) -> bool { copy.0.cancelled() } + fn write(&mut self, cb: &mut Fake, write: ClipboardWrite, notify: Notify, steps: &dyn WriteSteps) { Core::write(self, cb, write, Some(notify), steps); } + fn tick(&mut self, cb: &mut Fake, now: Instant) { self.tick_at(cb, now); } + fn read(&mut self, cb: &mut Fake) -> Option<Reply> { self.answer(cb, Purpose::Read(1)) } + fn clear_held(&mut self, cb: &mut Fake) { self.clear(cb, None); } + fn run(&mut self, cb: &mut Fake, queued: Request) { self.handle(cb, queued); } + fn watching(&self) -> bool { !self.hold.is_free() } +} + +impl Engine for flags::Core { + type Write = flags::Write; + type Copy = flags::Copy; + type Queued = Arc<flags::Slot>; + fn secret(text: &str, after: Duration) -> (flags::Write, flags::Copy) { + let slot = Arc::new(flags::Slot::default()); + let write = flags::Write { content: ClipboardContent::new(text), clear_after: Some(after), secret: Some(Arc::new(flags::Unwritten(slot.clone()))) }; + (write, flags::Copy(slot)) + } + fn pills() -> flags::Write { + flags::Write { content: ClipboardContent::new("a @x b").with_html(PILLS), clear_after: None, secret: None } + } + fn bind(write: &flags::Write, queue: &flags::Queue) { + if let Some(slot) = write.slot() { slot.route.set(queue.clone()).ok(); } + } + fn clear_now(copy: &flags::Copy) { copy.clear_now(); } + fn state(copy: &flags::Copy) -> SecretState { lock(&copy.0.state).clone() } + fn cancelled(copy: &flags::Copy) -> bool { copy.0.cancel.load(Ordering::SeqCst) } + fn write(&mut self, cb: &mut Fake, write: flags::Write, notify: Notify, steps: &dyn WriteSteps) { flags::Core::write(self, cb, write, Some(notify), steps); } + fn tick(&mut self, cb: &mut Fake, now: Instant) { flags::Core::tick(self, cb, now); } + fn read(&mut self, cb: &mut Fake) -> Option<Reply> { self.answer(cb, Purpose::Read(1)) } + fn clear_held(&mut self, cb: &mut Fake) { self.clear(cb, None); } + fn run(&mut self, cb: &mut Fake, queued: Arc<flags::Slot>) { self.clear(cb, Some(&queued)); } + fn watching(&self) -> bool { flags::Core::watching(self) } +} + +/// One thing that can happen. `A` and `B` are two clipboards; `S` is a secret whose write is +/// cloned for every replay, `T` a different one. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Ev { + WriteSA, + WriteSB, + WriteTA, + /// A secret whose delay is too long for the clock, so it has no deadline. + WriteForeverA, + WritePillsA, + /// `S` to A, with the backend taking longer than the secret's delay. + WriteSASlow, + /// `S` to A, with hashing it taking longer than its delay. + WriteSASlowHash, + /// `S` to A, with `clear_now` landing during the backend write. + WriteSACancelInWrite, + /// `S` to A, with another app's copy landing right after the backend write. + WriteSAOtherInWrite, + /// `S` to A, with `clear_now` and then another app's copy landing during the backend write. + WriteSACancelOtherInWrite, + /// `S` to A, with `clear_now` landing during the write's notification. + WriteSACancelInWake, + ReadA, + ReadB, + CancelS, + /// The clock passes every delay so far; each worker sees it on its next turn. + Timeout, + OtherA, + OtherB, + /// Another app copies the secret's exact text onto both. + OtherSameText, + /// A's writes start or stop failing, with a new error each time. + ToggleFailA, + /// A's reads start or stop failing. + ToggleUnreadableA, + /// A's wipes move on to their next way of failing, or back to working. + CycleWipeA, + ClearHeldA, + ShutdownA, + /// The workers reach the clears `clear_now` queued. Until then, reads are ahead of them. + Pump, + /// The app's own copies of the writes go away. + DropWrites, +} +use Ev::*; + +/// The rig's clock, as a write sees it. +struct Steps<'a, E: Engine> { + clock: &'a Cell<Instant>, + slow_hash: bool, + log: &'a Log, + s: &'a E::Copy, + t: &'a E::Copy, +} +impl<E: Engine> WriteSteps for Steps<'_, E> { + fn now(&self) -> Instant { + lock(self.log).push(Logged::ReadClock(E::state(self.s), E::state(self.t))); + self.clock.get() + } + fn hashing(&self) { + lock(self.log).push(Logged::Hashing(E::state(self.s), E::state(self.t))); + if self.slow_hash { self.clock.set(self.clock.get() + PAST_LONG); } + } +} + +struct Rig<E: Engine> { + boards: [Fake; 2], + engines: [E; 2], + alive: [bool; 2], + queues: [(mpsc::Sender<E::Queued>, mpsc::Receiver<E::Queued>); 2], + notify: [Notify; 2], + s: E::Copy, + t: E::Copy, + forever: E::Copy, + s_write: Option<E::Write>, + t_write: Option<E::Write>, + forever_write: Option<E::Write>, + cancel_on_wake: Arc<AtomicBool>, + log: Log, + reads: [Option<(ClipboardContent, bool)>; 2], + /// The board `S` was first sent to: the only one `clear_now` reaches. + first: Option<usize>, + clock: Rc<Cell<Instant>>, + fails: usize, +} + +impl<E: Engine> Rig<E> { + fn new(counted: [bool; 2], start: Instant) -> Self + where E::Copy: Send + Sync { + let log = Log::default(); + let (s_write, s) = E::secret(SECRET, LONG); + let (t_write, t) = E::secret("fixture-other", LONG); + let (forever_write, forever) = E::secret("fixture-forever", Duration::MAX); + let cancel_on_wake = Arc::new(AtomicBool::new(false)); + let board = |id| Fake { id, content: None, count: 0, counted: counted[id], landed: None, others: false, fail: None, unreadable: false, wipe: WipeMode::Works, log: log.clone(), during_write: None }; + let notify = |id: usize| { + let (log, s, t, arm) = (log.clone(), s.clone(), t.clone(), cancel_on_wake.clone()); + Notify { + changed: Arc::default(), + wake: Arc::new(move || { + if arm.swap(false, Ordering::SeqCst) { E::clear_now(&s); } + lock(&log).push(Logged::Woke(id, E::state(&s), E::state(&t))); + }), + } + }; + Self { + boards: [board(0), board(1)], + engines: [E::default(), E::default()], + alive: [true, true], + queues: [mpsc::channel(), mpsc::channel()], + notify: [notify(0), notify(1)], + s_write: Some(s_write), + t_write: Some(t_write), + forever_write: Some(forever_write), + s, + t, + forever, + cancel_on_wake, + log, + reads: [None, None], + first: None, + clock: Rc::new(Cell::new(start)), + fails: 0, + } + } + + /// The worker's turn on board `b`: it looks at the clipboard before every request. + fn turn(&mut self, b: usize) -> bool { + if self.alive[b] { self.engines[b].tick(&mut self.boards[b], self.clock.get()); } + self.alive[b] + } + + fn write(&mut self, b: usize, write: Option<E::Write>) { self.write_with(b, write, false); } + + fn write_with(&mut self, b: usize, write: Option<E::Write>, slow_hash: bool) { + let Some(write) = write else { return }; + E::bind(&write, &self.queues[b].0); + if !self.turn(b) { return; } + let steps = Steps::<E> { clock: &self.clock, slow_hash, log: &self.log, s: &self.s, t: &self.t }; + self.engines[b].write(&mut self.boards[b], write, self.notify[b].clone(), &steps); + } + + fn read(&mut self, b: usize) { + if !self.turn(b) { return; } + self.reads[b] = self.engines[b].read(&mut self.boards[b]).map(|r| { + let own = r.content.has_own_pills(); + (r.content, own) + }); + } + + fn apply(&mut self, ev: Ev) where E::Copy: 'static { + let target = match ev { + WriteSA | WriteSASlow | WriteSASlowHash | WriteSACancelInWrite | WriteSAOtherInWrite | WriteSACancelOtherInWrite | WriteSACancelInWake => Some(0), + WriteSB => Some(1), + _ => None, + }; + if self.first.is_none() && self.s_write.is_some() { self.first = target; } + match ev { + WriteSA => self.write(0, self.s_write.clone()), + WriteSB => self.write(1, self.s_write.clone()), + WriteTA => self.write(0, self.t_write.clone()), + WriteForeverA => self.write(0, self.forever_write.clone()), + WritePillsA => self.write(0, Some(E::pills())), + WriteSASlow => { + let clock = self.clock.clone(); + self.boards[0].during_write = Some(Box::new(move |_| clock.set(clock.get() + PAST_LONG))); + self.write(0, self.s_write.clone()); + self.boards[0].during_write = None; + } + WriteSASlowHash => self.write_with(0, self.s_write.clone(), true), + WriteSACancelInWrite => { + let s = self.s.clone(); + self.boards[0].during_write = Some(Box::new(move |_| E::clear_now(&s))); + self.write(0, self.s_write.clone()); + self.boards[0].during_write = None; + } + WriteSAOtherInWrite => { + self.boards[0].during_write = Some(Box::new(|f| f.other_app("theirs"))); + self.write(0, self.s_write.clone()); + self.boards[0].during_write = None; + } + WriteSACancelOtherInWrite => { + let s = self.s.clone(); + self.boards[0].during_write = Some(Box::new(move |f| { E::clear_now(&s); f.other_app("theirs"); })); + self.write(0, self.s_write.clone()); + self.boards[0].during_write = None; + } + WriteSACancelInWake => { + self.cancel_on_wake.store(true, Ordering::SeqCst); + self.write(0, self.s_write.clone()); + self.cancel_on_wake.store(false, Ordering::SeqCst); + } + ReadA => self.read(0), + ReadB => self.read(1), + CancelS => E::clear_now(&self.s), + Timeout => self.clock.set(self.clock.get() + PAST_LONG), + OtherA => self.boards[0].other_app("theirs"), + OtherB => self.boards[1].other_app("theirs"), + OtherSameText => for board in &mut self.boards { board.other_app(SECRET); }, + ToggleFailA => { + self.fails += 1; + self.boards[0].fail = self.boards[0].fail.is_none().then(|| format!("denied {}", self.fails)); + } + ToggleUnreadableA => self.boards[0].unreadable = !self.boards[0].unreadable, + CycleWipeA => self.boards[0].wipe = match self.boards[0].wipe { + WipeMode::Works => WipeMode::Refused, + WipeMode::Refused => WipeMode::NoEffect, + WipeMode::NoEffect => WipeMode::RefusedAndLocks, + WipeMode::RefusedAndLocks => WipeMode::Works, + }, + ClearHeldA => if self.turn(0) { self.engines[0].clear_held(&mut self.boards[0]); }, + ShutdownA => if self.turn(0) { + self.engines[0].clear_held(&mut self.boards[0]); + self.alive[0] = false; + }, + Pump => for b in 0..2 { + let queued: Vec<_> = self.queues[b].1.try_iter().collect(); + for request in queued { + if self.turn(b) { self.engines[b].run(&mut self.boards[b], request); } + } + }, + DropWrites => { self.s_write = None; self.t_write = None; self.forever_write = None; } + } + } +} + +/// Fails if the two rigs differ in anything observable, and in what decides their futures. +fn same(a: &Rig<Core>, b: &Rig<flags::Core>) -> Result<(), String> { + let differ = |what: &str, x: &dyn std::fmt::Debug, y: &dyn std::fmt::Debug| Err(format!("{what}: machines {x:?}, flags {y:?}")); + for i in 0..2 { + if a.boards[i].content != b.boards[i].content { return differ("content", &text_of(&a.boards[i]), &text_of(&b.boards[i])); } + if a.boards[i].count != b.boards[i].count { return differ("change count", &a.boards[i].count, &b.boards[i].count); } + if a.reads[i] != b.reads[i] { return differ("read", &a.reads[i].as_ref().map(|r| r.1), &b.reads[i].as_ref().map(|r| r.1)); } + if a.engines[i].watching() != Engine::watching(&b.engines[i]) { return differ("watching", &a.engines[i].watching(), &Engine::watching(&b.engines[i])); } + } + let (sa, sb) = (Core::state(&a.s), <flags::Core as Engine>::state(&b.s)); + if sa != sb { return differ("S reported", &sa, &sb); } + let (ta, tb) = (Core::state(&a.t), <flags::Core as Engine>::state(&b.t)); + if ta != tb { return differ("T reported", &ta, &tb); } + let (fa, fb) = (Core::state(&a.forever), <flags::Core as Engine>::state(&b.forever)); + if fa != fb { return differ("forever reported", &fa, &fb); } + let (ca, cb) = (Core::cancelled(&a.s), <flags::Core as Engine>::cancelled(&b.s)); + if ca != cb { return differ("S cancelled", &ca, &cb); } + let (la, lb) = (lock(&a.log), lock(&b.log)); + if *la != *lb { return differ("order of events", &*la, &*lb); } + Ok(()) +} +fn text_of(board: &Fake) -> Option<&str> { board.content.as_ref().map(|c| c.text()) } + +/// Drives one sequence through both, comparing after every event. +fn check(sequence: &[Ev], counted: [bool; 2], start: Instant) -> Result<(), String> { + let mut machines = Rig::<Core>::new(counted, start); + let mut reference = Rig::<flags::Core>::new(counted, start); + for (i, &ev) in sequence.iter().enumerate() { + machines.apply(ev); + reference.apply(ev); + same(&machines, &reference).map_err(|why| format!("{:?} with change counts {counted:?}, after event {i}: {why}", sequence))?; + } + keeps_clear_nows_promise(&mut machines, &mut reference).map_err(|why| format!("{:?} with change counts {counted:?}, then clear_now: {why}", sequence)) +} + +/// Whatever came before: `clear_now` wipes the board it reaches if it still holds the secret and +/// the copy reports `Holding` or `Failed`, takes no other app's copy, and leaves other boards be. +fn keeps_clear_nows_promise(machines: &mut Rig<Core>, reference: &mut Rig<flags::Core>) -> Result<(), String> { + let reached = machines.first.filter(|&b| machines.alive[b]); + let reachable = match machines.s.state() { + SecretState::Holding => true, + SecretState::Failed(e) => e != REFUSED, + _ => false, + }; + let ours = reachable && reached.is_some_and(|b| machines.boards[b].ours() && machines.engines[b].watching() && !machines.boards[b].failing()); + let others = [0, 1].map(|b| machines.boards[b].others_copy().cloned()); + let before = [0, 1].map(|b| machines.boards[b].content.clone()); + for ev in [CancelS, Pump] { + machines.apply(ev); + reference.apply(ev); + same(machines, reference)?; + } + for b in 0..2 { + if ours && reached == Some(b) && machines.boards[b].ours() { return Err(format!("board {b} still holds the secret")); } + if others[b].is_some() && machines.boards[b].content != others[b] { return Err(format!("board {b} lost another app's copy")); } + if machines.first != Some(b) && machines.boards[b].content != before[b] { return Err(format!("board {b} was out of reach but changed")); } + } + let state = machines.s.state(); + if ours && state != SecretState::Cleared { return Err(format!("reported {state:?} after a wipe")); } + Ok(()) +} + +/// Every sequence of up to six events, on either layout of change counts. +fn exhaust_all(alphabet: &[Ev]) { + for counted in COUNTS { + for len in 1..=6 { assert_eq!(exhaust(alphabet, len, counted), alphabet.len().pow(len)); } + } +} + +/// Every sequence of exactly `len` events, across threads. Returns how many ran. +fn exhaust(alphabet: &[Ev], len: u32, counted: [bool; 2]) -> usize { + let total = alphabet.len().pow(len); + let start = crate::time::now(); + let next = AtomicUsize::new(0); + let threads = std::thread::available_parallelism().map_or(4, |n| n.get()); + const CHUNK: usize = 4096; + let failure = Mutex::new(None); + std::thread::scope(|scope| { + for _ in 0..threads { + scope.spawn(|| { + let mut sequence = vec![alphabet[0]; len as usize]; + loop { + let from = next.fetch_add(CHUNK, Ordering::Relaxed); + if from >= total || lock(&failure).is_some() { return; } + for index in from..(from + CHUNK).min(total) { + let mut rest = index; + for slot in sequence.iter_mut() { + *slot = alphabet[rest % alphabet.len()]; + rest /= alphabet.len(); + } + if let Err(why) = check(&sequence, counted, start) { + *lock(&failure) = Some(why); + return; + } + } + } + }); + } + }); + if let Some(why) = failure.into_inner().unwrap() { panic!("{why}"); } + total +} + +const COUNTS: [[bool; 2]; 2] = [[true, false], [false, true]]; + +/// Writes and replays across boards against everything that can end a hold. +const BOARDS: &[Ev] = &[WriteSA, WriteSB, WriteTA, ReadA, ReadB, CancelS, Pump, Timeout, OtherA, OtherB, ClearHeldA, ToggleFailA]; +/// Interruptions during a write, against what follows them on the same board. +const IN_FLIGHT: &[Ev] = &[WriteSA, WriteSASlow, WriteSASlowHash, WriteSACancelInWrite, WriteSAOtherInWrite, WriteSACancelOtherInWrite, WriteSACancelInWake, ReadA, CancelS, Pump, OtherA, ToggleFailA, Timeout]; +/// How a copy's life ends: shutdown, dropped writes, pills, a look-alike from another app. +/// A failed replay against clipboards that won't read or wipe. +const FAILURES: &[Ev] = &[WriteSA, WriteSB, ToggleFailA, ToggleUnreadableA, CycleWipeA, CancelS, Pump, Timeout, ReadA, OtherA, ClearHeldA]; +const ENDINGS: &[Ev] = &[WriteSA, WriteSB, WriteTA, WriteForeverA, WritePillsA, ReadA, CancelS, Pump, Timeout, OtherSameText, ShutdownA, DropWrites]; + +#[test] +fn every_six_events_across_boards_match_the_flags() { + exhaust_all(BOARDS); +} + +#[test] +fn every_six_events_around_a_write_match_the_flags() { + exhaust_all(IN_FLIGHT); +} + +#[test] +fn every_six_events_with_a_failing_clipboard_match_the_flags() { + exhaust_all(FAILURES); +} + +#[test] +fn every_six_events_ending_a_copy_match_the_flags() { + exhaust_all(ENDINGS); +} + +/// The whole alphabet at once; too long for the normal run. Run with `--ignored`, one test per job. +const ALL: &[Ev] = &[ + WriteSA, WriteSB, WriteTA, WriteForeverA, WritePillsA, WriteSASlow, WriteSASlowHash, WriteSACancelInWrite, WriteSAOtherInWrite, WriteSACancelOtherInWrite, WriteSACancelInWake, + ReadA, ReadB, CancelS, Timeout, OtherA, OtherB, OtherSameText, ToggleFailA, ToggleUnreadableA, CycleWipeA, ClearHeldA, ShutdownA, Pump, DropWrites, +]; + +fn exhaust_whole_alphabet(counted: [bool; 2]) { + for len in 1..=6 { assert_eq!(exhaust(ALL, len, counted), ALL.len().pow(len)); } +} + +#[test] +#[ignore] +fn every_six_events_from_the_whole_alphabet_with_a_counted_first_board() { exhaust_whole_alphabet(COUNTS[0]); } + +#[test] +#[ignore] +fn every_six_events_from_the_whole_alphabet_with_a_counted_second_board() { exhaust_whole_alphabet(COUNTS[1]); } diff --git a/app/vendor/rune/crates/rune/src/clipboard/tests.rs b/app/vendor/rune/crates/rune/src/clipboard/tests.rs new file mode 100644 index 0000000..fadf6d8 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/clipboard/tests.rs @@ -0,0 +1,263 @@ +use super::*; +use super::native::Worker; + +#[derive(Default)] +struct State { text: String, revision: u64, clears: usize, drops: usize } +struct Fake { state: Arc<Mutex<State>>, dropped: Option<mpsc::Sender<()>> } +impl Backend for Fake { + fn write(&mut self, copy: &ClipboardWrite) -> Result<(), String> { + let mut s = self.state.lock().unwrap(); + s.text = copy.to_string(); s.revision += 1; + Ok(()) + } + fn text(&mut self) -> Option<Zeroizing<String>> { Some(Zeroizing::new(self.state.lock().unwrap().text.clone())) } + fn revision(&self) -> Option<u64> { Some(self.state.lock().unwrap().revision) } + fn clear(&mut self) -> Result<(), String> { let mut s = self.state.lock().unwrap(); s.text.clear(); s.clears += 1; Ok(()) } +} +impl Drop for Fake { + fn drop(&mut self) { + self.state.lock().unwrap().drops += 1; + if let Some(dropped) = &self.dropped { dropped.send(()).ok(); } + } +} + +const LONG: Duration = Duration::from_secs(3600); + +fn copy(m: &MemoryClipboard, text: &str, clear_after: Duration) -> SecretCopy { + let (write, handle) = ClipboardWrite::secret(text.into(), clear_after); + write.bind(Route::Memory(m.clone())); + m.handle(Request::Write(write, None)); + handle +} +fn text(m: &MemoryClipboard) -> Option<String> { m.text().map(|t| t.to_string()) } + +#[test] +fn shutdown_expires_only_our_pending_secret_before_dropping_backend() { + for replacement in [None, Some("new value"), Some("fixture")] { + let state = Arc::new(Mutex::new(State::default())); + let shared = state.clone(); + let worker = Worker::spawn(move || Some(Fake { state: shared.clone(), dropped: None })); + worker.sender.send(Request::Write(ClipboardWrite::secret("fixture".into(), LONG).0, None)).unwrap(); + let (reply, received) = mpsc::channel(); + worker.sender.send(Request::Read { purpose: Purpose::Paste(None, Forms::Text), reply, wake: Arc::new(|| {}) }).unwrap(); + received.recv_timeout(Duration::from_secs(1)).unwrap(); // Write and revision recorded. + if let Some(text) = replacement { + let mut s = state.lock().unwrap(); s.text = text.into(); s.revision += 1; + } + worker.stop(); worker.stop(); + let s = state.lock().unwrap(); + assert_eq!(s.text, replacement.unwrap_or("")); + assert_eq!(s.clears, usize::from(replacement.is_none())); + assert_eq!(s.drops, 1, "normal shutdown joins after clipboard handoff/drop"); + } +} + +#[test] +fn shutdown_does_not_wait_indefinitely_for_a_blocked_backend() { + let (entered, waiting) = mpsc::channel(); + let (release, released) = mpsc::channel(); + let (dropped, finished) = mpsc::channel(); + let worker = Worker::spawn(move || { + entered.send(()).unwrap(); + released.recv().unwrap(); + Some(Fake { state: Arc::default(), dropped: Some(dropped.clone()) }) + }); + worker.sender.send(Request::Write(ClipboardWrite::secret("fixture".into(), LONG).0, None)).unwrap(); + waiting.recv_timeout(Duration::from_secs(1)).unwrap(); + let start = crate::time::now(); + worker.stop(); + assert!(start.elapsed() < Duration::from_secs(1)); + release.send(()).unwrap(); + finished.recv_timeout(Duration::from_secs(1)).unwrap(); +} + +/// The OS worker reports the write, then notices another app's change on its own. +#[test] +fn worker_reports_the_write_and_watches_for_outside_changes() { + let state = Arc::new(Mutex::new(State::default())); + let shared = state.clone(); + let worker = Worker::spawn(move || Some(Fake { state: shared.clone(), dropped: None })); + let (woke, wakes) = mpsc::channel(); + let notify = Notify { changed: Arc::default(), wake: Arc::new(move || { woke.send(()).ok(); }) }; + let (write, handle) = ClipboardWrite::secret("fixture".into(), LONG); + write.bind(Route::System(worker.sender.clone())); + worker.sender.send(Request::Write(write, Some(notify.clone()))).unwrap(); + wakes.recv_timeout(Duration::from_secs(1)).unwrap(); + assert!(handle.holds() && notify.changed.load(Ordering::SeqCst)); + { let mut s = state.lock().unwrap(); s.text = "theirs".into(); s.revision += 1; } + wakes.recv_timeout(WATCH * 8).unwrap(); + assert_eq!(handle.state(), SecretState::Replaced); + handle.clear_now(); + worker.stop(); + assert_eq!(state.lock().unwrap().text, "theirs"); +} + +#[test] +fn holds_until_a_later_copy_or_an_outside_change() { + let m = memory(); + let first = copy(&m, "fixture", LONG); + assert!(first.holds()); + let second = copy(&m, "fixture", LONG); + assert_eq!(first.state(), SecretState::Replaced, "identical text from a later copy still supersedes"); + assert!(second.holds()); + m.set_text("theirs"); + assert_eq!(second.state(), SecretState::Replaced); + let expired = copy(&m, "brief", Duration::ZERO); + assert_eq!(expired.state(), SecretState::Cleared); + assert_eq!(text(&m), None); + assert!(!format!("{expired:?} {m:?}").contains("brief")); +} + +#[test] +fn clear_now_clears_only_while_it_holds() { + let m = memory(); + let replaced = copy(&m, "secret", LONG); + m.set_text("theirs"); + replaced.clear_now(); + assert_eq!(text(&m).as_deref(), Some("theirs")); + let held = copy(&m, "secret", LONG); + held.clear_now(); + held.clear_now(); + assert_eq!((held.state(), text(&m)), (SecretState::Cleared, None)); + let (write, unwritten) = ClipboardWrite::secret("never".into(), LONG); + write.bind(Route::Memory(m.clone())); + unwritten.clear_now(); + m.handle(Request::Write(write, None)); + assert_eq!((unwritten.state(), text(&m)), (SecretState::Cleared, None)); + let (write, dropped) = ClipboardWrite::secret("dropped".into(), LONG); + drop(write); + assert_eq!(dropped.state(), SecretState::Replaced); +} + +#[test] +fn a_failed_write_reports_and_keeps_the_earlier_copy() { + let m = memory(); + let earlier = copy(&m, "earlier", LONG); + m.fail_writes(Some("pasteboard denied")); + let failed = copy(&m, "later", LONG); + assert_eq!(failed.state(), SecretState::Failed("pasteboard denied".into())); + assert!(earlier.holds()); + assert_eq!(text(&m).as_deref(), Some("earlier")); +} + +#[test] +fn two_runtimes_share_a_memory_clipboard() { + use crate::{col, Cx, El, Env}; + fn view(_: &Option<SecretCopy>, _: &mut Cx<Option<SecretCopy>>) -> El { col() } + let m = memory(); + let [mut a, mut b] = [0, 1].map(|_| { + let mut rt = Runtime::new(None, view, (100.0, 100.0), Env::new(true, 1.0)); + rt.use_clipboard(&m); + rt.frame(0.0); + rt + }); + a.update(|s, tx| *s = Some(tx.copy_secret("from a", LONG))); a.frame(0.0); + assert!(a.state.as_ref().unwrap().holds()); + b.update(|s, tx| *s = Some(tx.copy_secret("from b", LONG))); b.frame(0.0); + assert_eq!(text(&m).as_deref(), Some("from b")); + assert_eq!(a.state.as_ref().unwrap().state(), SecretState::Replaced); + a.update(|_, tx| tx.clear_secret_clipboard()); a.frame(0.0); + assert_eq!(text(&m), None, "either window clears the latest secret"); + assert_eq!(b.state.as_ref().unwrap().state(), SecretState::Cleared); + + a.update(|s, tx| *s = Some(tx.copy_secret("no frame", LONG))); + assert_eq!(text(&m).as_deref(), Some("no frame"), "update writes without waiting for a frame"); + + let mut headless = Runtime::new(None, view, (100.0, 100.0), Env::new(true, 1.0)); + headless.update(|s, tx| *s = Some(tx.copy_secret("nowhere", LONG))); headless.frame(0.0); + assert_eq!(headless.state.as_ref().unwrap().state(), SecretState::Pending, "no clipboard, no write"); +} + +#[test] +fn rich_copies_carry_every_form_and_secrets_stay_plain() { + use crate::{col, Cx, El, Env}; + fn view(_: &u8, _: &mut Cx<u8>) -> El { col() } + let m = memory(); + let mut rt = Runtime::new(0, view, (100.0, 100.0), Env::new(true, 1.0)); + rt.use_clipboard(&m); + rt.frame(0.0); + let rich = ClipboardContent::new("Ship it").with_html("<b>Ship</b> it").with_rtf(r"{\rtf1 {\b Ship} it}"); + rt.update(|_, tx| tx.copy_rich(rich.clone())); + assert_eq!(m.content().as_ref(), Some(&rich), "HTML is written as given; only reads are sanitised"); + assert_eq!(text(&m).as_deref(), Some("Ship it")); + assert!(!format!("{rich:?} {:?}", ClipboardWrite::new(rich.clone())).contains("Ship")); + + rt.update(|_, tx| { tx.copy_secret("hunter2", LONG); }); + let secret = m.content().unwrap(); + assert!(!secret.is_rich() && secret.text() == "hunter2", "no HTML or RTF copy of a secret"); + rt.update(|_, tx| tx.clear_secret_clipboard()); + assert_eq!(m.content(), None); +} + +/// A plain paste leaves an empty clipboard alone; a read always answers. +#[test] +fn the_worker_answers_reads_with_sanitised_content() { + let state = Arc::new(Mutex::new(State::default())); + let shared = state.clone(); + let worker = Worker::spawn(move || Some(Fake { state: shared.clone(), dropped: None })); + state.lock().unwrap().text = "<script>".into(); + let (reply, replies) = mpsc::channel(); + worker.sender.send(Request::Read { purpose: Purpose::Read(7), reply, wake: Arc::new(|| {}) }).unwrap(); + let answer = replies.recv_timeout(Duration::from_secs(1)).unwrap(); + assert_eq!((answer.purpose, answer.content.text()), (Purpose::Read(7), "<script>"), "plain text is never rewritten"); + worker.stop(); + assert!(Purpose::Paste(None, Forms::Rich).reply(None).is_none()); + let mut board = Board { content: Some(ClipboardContent::new("t").with_html("<b>t</b>")), ..Board::default() }; + let plain = Purpose::Paste(None, Forms::Text).answer(&mut board).unwrap().content; + assert!(!plain.is_rich() && plain.text() == "t", "a plain target reads only the text, as before"); + let read = Purpose::Read(1).reply(Some(ClipboardContent::new("").with_html("<p onclick=x>t</p>"))).unwrap(); + assert_eq!(read.content.html(), Some("<p>t</p>")); + assert_eq!(Purpose::Read(2).reply(None).unwrap().content, ClipboardContent::default()); +} + +/// `on_close` runs through `update`, and a hidden window only polls: both must reach the +/// clipboard before any frame. +#[test] +fn clears_from_on_close_and_a_hidden_poll_need_no_frame() { + use crate::{col, Cx, El, Env}; + fn view(_: &u8, _: &mut Cx<u8>) -> El { col() } + let m = memory(); + let mut rt = Runtime::new(0, view, (100.0, 100.0), Env::new(true, 1.0)); + rt.use_clipboard(&m); + rt.frame(0.0); + let on_close: fn(&mut u8, &mut crate::Tx) = |_, tx| tx.clear_secret_clipboard(); + let held = copy(&m, "secret", LONG); + rt.update(on_close); + assert_eq!((held.state(), text(&m)), (SecretState::Cleared, None)); + + rt.poll = Some(|_, _, tx| { tx.clear_secret_clipboard(); false }); + let held = copy(&m, "secret", LONG); + rt.poll_hidden(); + assert_eq!((held.state(), text(&m)), (SecretState::Cleared, None)); +} + +#[test] +fn a_clear_after_an_unwritten_copy_drops_the_stale_secret() { + use crate::{col, Cx, El, Env}; + fn view(_: &Option<SecretCopy>, _: &mut Cx<Option<SecretCopy>>) -> El { col() } + // No clipboard: the copy waits for the shell, as it does between window flushes. + let mut rt = Runtime::new(None, view, (100.0, 100.0), Env::new(true, 1.0)); + rt.update(|s, tx| *s = Some(tx.copy_secret("stale", LONG))); + rt.update(|_, tx| tx.clear_secret_clipboard()); + assert!(rt.copy_request.is_none() && rt.edit.clear_secret_request); + assert_eq!(rt.state.as_ref().unwrap().state(), SecretState::Replaced); + + // The same in one handler, and with a memory clipboard on the next flush. + let m = memory(); + rt.use_clipboard(&m); + rt.update(|s, tx| { *s = Some(tx.copy_secret("stale", LONG)); tx.clear_secret_clipboard(); }); + rt.frame(0.0); + assert_eq!(text(&m), None); + assert_eq!(rt.state.as_ref().unwrap().state(), SecretState::Replaced); +} + +#[test] +fn a_staged_pending_copy_stays_pending_and_clear_now_is_a_no_op() { + let copy = SecretCopy::pending(); + let clone = copy.clone(); + drop(copy); + assert_eq!(clone.state(), SecretState::Pending); + clone.clear_now(); + assert_eq!(clone.state(), SecretState::Pending); + assert!(!clone.holds()); +} diff --git a/app/vendor/rune/crates/rune/src/clipboard/tx.rs b/app/vendor/rune/crates/rune/src/clipboard/tx.rs new file mode 100644 index 0000000..becc55f --- /dev/null +++ b/app/vendor/rune/crates/rune/src/clipboard/tx.rs @@ -0,0 +1,70 @@ +//! `Tx`'s clipboard requests, carried out by the shell's clipboard worker after the handler. +use std::rc::Rc; +use crate::Tx; + +pub(crate) type ReadFn = Box<dyn FnOnce(crate::states::States<'_>, &crate::ClipboardContent, &mut Tx)>; + +/// A `Tx::read_clipboard` callback. `Tx` is `Clone`; clones share it and the runtime takes it once. +#[derive(Clone)] +pub(crate) struct ClipboardRead(Rc<std::cell::Cell<Option<ReadFn>>>); +impl ClipboardRead { + pub(crate) fn take(&self) -> Option<ReadFn> { self.0.take() } +} +impl std::fmt::Debug for ClipboardRead { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.write_str("ClipboardRead") } +} + +impl Tx { + /// Request a clipboard write from the shell after this handler finishes. + pub fn copy(&mut self, text: impl Into<String>) { + self.copy = Some(crate::ClipboardWrite::new(crate::ClipboardContent::new(text))); + } + + /// Copy several forms at once: plain text for every app, HTML and RTF for apps that paste + /// formatting (Mail, Notes, Pages, Google Docs), an image, and files for a file manager. + /// macOS writes every form. Windows and Linux write one: the files if there are any, else + /// the image, else the HTML beside the text, else the text. The web writes text, HTML and + /// the image. Forms a platform can't hold are skipped silently. + /// + /// ```ignore + /// tx.copy_rich(ClipboardContent::new("Ship it").with_html("<b>Ship</b> it")); + /// tx.copy_rich(ClipboardContent::default().with_image(image)); + /// tx.copy_rich(ClipboardContent::default().with_files([path])); + /// ``` + pub fn copy_rich(&mut self, content: crate::ClipboardContent) { + self.copy = Some(crate::ClipboardWrite::new(content)); + } + + /// Exclude this text from clipboard histories and clear it after `clear_after` if unchanged. + /// The handle reports whether the copy still holds the clipboard, and can clear it early. + pub fn copy_secret(&mut self, text: impl Into<String>, clear_after: std::time::Duration) -> crate::SecretCopy { + let (write, copy) = crate::ClipboardWrite::secret(text.into(), clear_after); + self.copy = Some(write); + copy + } + + /// Clear the secret Rune copied last, from any window, if the clipboard still holds it + /// (on lock, say). A secret copy asked for earlier in this handler is dropped. + pub fn clear_secret_clipboard(&mut self) { + if self.copy.as_ref().is_some_and(crate::ClipboardWrite::is_secret) { self.copy = None; } + self.clear_secret = true; + } + + /// Read the OS clipboard asynchronously and paste into the focused field or root `on_paste`. + pub fn request_paste(&mut self) { self.paste = true; } + + /// Read the clipboard off the event thread and hand what it holds to `f`, as an update, + /// once it arrives: an empty [`ClipboardContent`](crate::ClipboardContent) when it holds + /// nothing readable. HTML is sanitised, and on macOS made from RTF when that's all there + /// is. Nothing is pasted anywhere. The web asks the browser, which may prompt or refuse. + /// + /// ```ignore + /// tx.read_clipboard(|s: &mut Composer, content, _| s.preview = content.html().map(Into::into)); + /// ``` + pub fn read_clipboard<S: 'static>(&mut self, f: impl FnOnce(&mut S, &crate::ClipboardContent, &mut Tx) + 'static) { + let f: ReadFn = Box::new(move |s, content, tx| { + if let Some(s) = s.cast::<S>() { f(s, content, tx); } + }); + self.clipboard_reads.push(ClipboardRead(Rc::new(std::cell::Cell::new(Some(f))))); + } +} diff --git a/app/vendor/rune/crates/rune/src/clipboard/web.rs b/app/vendor/rune/crates/rune/src/clipboard/web.rs new file mode 100644 index 0000000..7e85be2 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/clipboard/web.rs @@ -0,0 +1,87 @@ +//! The browser's clipboard: reads and writes go through the Clipboard API and DOM paste events. + +use super::*; + +impl Client { + pub(super) fn read_for(&self, purpose: Purpose) { + // Start the permission-sensitive operation before yielding the input handler. + let forms = purpose.forms(); + let promise = crate::platform::web::platform::read_clipboard(forms != Forms::Text, forms == Forms::All, MAX_IMAGE_BYTES as u32); + let (sender, wake) = (self.sender.clone(), self.wake.clone()); + wasm_bindgen_futures::spawn_local(async move { + let content = match wasm_bindgen_futures::JsFuture::from(promise).await { + Ok(value) => { + let field = |name: &str| js_sys::Reflect::get(&value, &name.into()).ok().and_then(|v| v.as_string()); + let html = field("html").filter(|h| !h.is_empty()); + let text = field("text"); + let image = web_png(js_sys::Reflect::get(&value, &"png".into()).ok()); + (text.is_some() || html.is_some() || image.is_some()).then(|| { + let mut content = ClipboardContent::new(text.unwrap_or_default()); + if let Some(html) = html { content = content.with_html(html); } + if let Some(image) = image { content = content.with_image(image); } + content + }) + } + Err(_) => { + web_sys::console::warn_1(&"Clipboard read denied; use the browser's Paste command.".into()); + None + } + }; + if let Some(reply) = purpose.reply(content) && sender.send(reply).is_ok() { wake(); } + }); + } + /// A DOM paste into the focused field: the text and HTML come with the event, and when it + /// carried an image, `png` reads its bytes, only if the target takes images. + #[inline(always)] + pub fn paste_event<S: 'static>(&self, rt: &mut Runtime<S>, content: ClipboardContent, png: Option<impl FnOnce() -> js_sys::Promise>) { + self.paste_event_core(rt.core_mut(), content, png); + } + fn paste_event_core(&self, rt: &mut crate::runtime::RuntimeCore, content: ClipboardContent, png: Option<impl FnOnce() -> js_sys::Promise>) { + let purpose = Purpose::paste(rt, rt.paste_target()); + let content = if purpose.forms() == Forms::Text { ClipboardContent::new(content.text()) } else { content }; + let Some(png) = png.filter(|_| purpose.forms() == Forms::All) else { return rt.paste_content(content) }; + let promise = png(); + let (sender, wake) = (self.sender.clone(), self.wake.clone()); + wasm_bindgen_futures::spawn_local(async move { + let image = web_png(wasm_bindgen_futures::JsFuture::from(promise).await.ok()); + let content = match image { Some(image) => content.with_image(image), None => content }; + if let Some(reply) = purpose.reply(Some(content)) && sender.send(reply).is_ok() { wake(); } + }); + } + pub(crate) fn flush_core(&self, rt: &mut crate::runtime::RuntimeCore) { + if rt.edit.has_clipboard() { return flush_memory(rt); } + #[cfg(test)] + if let Some(m) = &self.memory { return flush_to_memory(rt, m); } + rt.edit.clear_secret_request = false; + if let Some(copy) = rt.copy_request.take() { + if copy.is_secret() { + if let Some(slot) = copy.slot() { + slot.set(SecretState::Failed("secret clipboard writes are unsupported on web".into())); + self.changed.store(true, Ordering::SeqCst); + (self.wake)(); + } + } else { + // The browser's Clipboard API takes plain text, HTML and PNG; RTF and files stay behind. + let content = copy.content(); + let png = content.image().map_or(&[][..], ClipboardImage::png); + let promise = crate::platform::web::platform::write_clipboard(content.text(), content.html().unwrap_or(""), png); + wasm_bindgen_futures::spawn_local(async move { + if wasm_bindgen_futures::JsFuture::from(promise).await.is_err() { + web_sys::console::warn_1(&"Clipboard write denied by the browser.".into()); + } + }); + } + } + if let Some(target) = rt.edit.paste_request.take() { self.read_for(Purpose::paste(rt, target)); } + for id in std::mem::take(&mut rt.edit.read_requests) { self.read_for(Purpose::Read(id)); } + } +} + +/// A `Uint8Array` of PNG bytes from the browser. +fn web_png(value: Option<wasm_bindgen::JsValue>) -> Option<ClipboardImage> { + use wasm_bindgen::JsCast; + let bytes = value?.dyn_into::<js_sys::Uint8Array>().ok()?; + if bytes.length() as usize > MAX_IMAGE_BYTES { return None; } + ClipboardImage::from_png(bytes.to_vec()) +} + diff --git a/app/vendor/rune/crates/rune/src/compose.rs b/app/vendor/rune/crates/rune/src/compose.rs new file mode 100644 index 0000000..ad053ec --- /dev/null +++ b/app/vendor/rune/crates/rune/src/compose.rs @@ -0,0 +1,144 @@ +//! Compositor hook: an app takes over drawing each frame (lighting, effect layers) while Rune +//! keeps layout, animation, input, the window and the headless tooling. `rune::run` never +//! builds one, so the default path is unchanged; `rune::run_with` or `App::compositor` attaches +//! one. + +use crate::render::{Instance, Kind, Renderer}; +use crate::runtime::Runtime; + +/// Draws a frame in place of Rune's default. +/// +/// To paint custom content at `El::effect` slots, draw the frame with `Renderer::draw_with` and +/// paint in its hook: it runs at each slot in painter order, inside the slot's isolated layers, +/// so the slot's opacity (an exit fade included), clip and transform already apply. Keep +/// resources per `EffectSite::mark`, read the slot's `EffectSite::data`, and drop a mark's +/// resources once a frame passes without it: +/// +/// ```ignore +/// struct Hud { waves: HashMap<u32, Wave>, seen: HashSet<u32> } +/// +/// impl Compositor<App> for Hud { +/// fn render(&mut self, f: &mut Frame<'_, App>) { +/// let (device, queue, clear) = (f.device, f.queue, f.rt.clear_color()); +/// f.ui.prepare(device, queue, &mut f.rt.text.atlas, &f.rt.instances, f.size); +/// self.seen.clear(); +/// f.ui.draw_with(f.encoder, f.target, clear, &mut |pass, site| { +/// self.seen.insert(site.mark); +/// let wave = self.waves.entry(site.mark).or_insert_with(|| Wave::new(device)); +/// wave.draw(device, queue, pass, site, site.data); +/// }); +/// self.waves.retain(|mark, _| self.seen.contains(mark)); +/// } +/// } +/// ``` +pub trait Compositor<S: 'static>: 'static { + /// Device features to request when the adapter has them (e.g. `TIMESTAMP_QUERY`). + /// `IMMEDIATES` also raises `max_immediate_size` to the adapter's (4 KB on Metal): per-draw + /// values set with `RenderPass::set_immediates` travel inside the pass, where a uniform + /// written through the queue or `Frame::write_buffer` costs the frame another command buffer. + fn features(&self) -> wgpu::Features { + wgpu::Features::empty() + } + + /// Draws the frame into `f.target`. Runs after `Runtime::frame` built the instances, in the + /// window and headless alike. Nothing has been recorded yet; `El::pixels` images are uploaded. + /// `f.device` can change between frames (an overlay shown again on another GPU): keep + /// resources made on it with `f.device_key()`, and make them again when it changes. Never + /// compare `wgpu::Device`s for this: wgpu compares them by id, and every Rune GPU has its + /// own instance, whose first device has the same id as the last one's (hex#982). + fn render(&mut self, f: &mut Frame<'_, S>); + + /// True while something the compositor draws moves on its own: the window keeps its display + /// link running. False lets it go idle (no frames at rest) and rest: a due `wake_after` + /// runs `poll` alone and draws only when that poll changed something. + fn animating(&self) -> bool { + false + } + + /// Whether the last frame drew anything of the compositor's own, besides `Frame::draw_ui`. + /// False lets the window treat it as Rune's default frame: a due timer whose frame would + /// build the same instances draws nothing, as in a window with no compositor. A compositor + /// that only sometimes draws (Office pages in their slots) says false while it doesn't. + fn draws_own(&self) -> bool { + true + } + /// Printed after a headless run (e.g. GPU timings). + fn summary(&mut self, _device: &wgpu::Device) -> Option<String> { + None + } +} + +/// One frame handed to a compositor. +pub struct Frame<'a, S: 'static> { + pub device: &'a wgpu::Device, + pub queue: &'a wgpu::Queue, + pub encoder: &'a mut wgpu::CommandEncoder, + /// The window surface or the offscreen target. + pub target: &'a wgpu::TextureView, + pub format: wgpu::TextureFormat, + /// Target size in device pixels. + pub size: (u32, u32), + /// Real seconds since the previous frame (0 on the first). + pub dt: f64, + /// CPU milliseconds `Runtime::frame` took this frame (handlers, view, layout, animation). + pub update_ms: f64, + /// Instances, `marks`, the clock (`t`), the pointer, element rects and app state. + pub rt: &'a mut Runtime<S>, + /// Rune's own renderer: `prepare_lists`, `encode_layers`, then `draw_range` draw complete + /// painter scopes into any target (`add_format` for non-target formats). Layer begin/end + /// records must remain balanced; do not partition a scope by primitive kind. + pub ui: &'a mut Renderer, +} + +/// Which device a frame draws on, unique for the process: a new device never has an earlier +/// key, as a `wgpu::Device` can have an earlier id. Keep it beside resources made with +/// `Frame::device`. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub struct DeviceKey(u64); + +impl DeviceKey { + pub(crate) fn next() -> DeviceKey { + static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + DeviceKey(NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed)) + } +} + +impl<S: 'static> Frame<'_, S> { + /// The device `device` is, as a key that changes whenever the frame moves to another one. + pub fn device_key(&self) -> DeviceKey { + self.ui.device_key() + } + + /// True when the frame is sRGB-blended (`App::srgb_blend`): `target` is a non-sRGB view and + /// premultiplied colours, in `ui` passes and in layers, are sRGB-encoded. False: linear + /// premultiplied values, encoded by the `*Srgb` target on write. Build effect pipelines and + /// encode their output to match (`FxRenderer::set_srgb_blend` in rune-fx). + pub fn srgb_blend(&self) -> bool { + self.ui.srgb_blend() + } + + /// Packed explicit scroll-fade stops for this frame (`FxRenderer::set_fade_stops` in rune-fx + /// or `clip_alpha_stops` in `CLIP_WGSL`). + pub fn fade_stops(&self) -> [f32; 2] { + self.rt.fade_stops() + } + + /// `queue.write_buffer` without its per-call staging buffer: `data` goes through Rune's + /// reused staging memory and lands in `buffer` at `offset` ahead of the commands recorded + /// into `encoder` after this call. `offset` and `data.len()` are multiples of 4. + pub fn write_buffer(&mut self, buffer: &wgpu::Buffer, offset: u64, data: &[u8]) { + self.ui.write_buffer(self.device, self.queue, self.encoder, buffer, offset, data); + } + + /// The default frame: every instance into the target, cleared to the window colour. + pub fn draw_ui(&mut self) { + let clear = self.rt.clear_color(); + self.ui.set_fade_stops(self.rt.fade_stops()); + self.ui.prepare_ui(self.device, self.queue, &mut self.rt.text.atlas, &self.rt.instances, self.size); + self.ui.draw(self.encoder, self.target, clear); + } +} + +pub fn is_glyph(i: &Instance) -> bool { + i.kind() == Some(Kind::Glyph) +} diff --git a/app/vendor/rune/crates/rune/src/drag_out/macos.rs b/app/vendor/rune/crates/rune/src/drag_out/macos.rs new file mode 100644 index 0000000..5cf5645 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/drag_out/macos.rs @@ -0,0 +1,305 @@ +//! `NSDraggingSource` for [`super::begin`]. The session starts inside winit's `mouseDragged:` +//! (which dispatches `CursorMoved` synchronously), so `NSApp.currentEvent` is the drag event. +//! Pasteboard types follow what Finder and System Settings' privacy lists accept for a file. + +#![allow(unsafe_code)] + +use super::{DragImage, DragItem, DragOperation, DragOutStart, DragOutcome, path_text}; +use std::cell::{Cell, RefCell}; +use objc2::{AnyThread, DefinedClass, MainThreadMarker, MainThreadOnly, define_class, msg_send, rc::Retained, sel, + runtime::{AnyObject, NSObjectProtocol, ProtocolObject}}; +use objc2_app_kit::{NSApplication, NSDragOperation, NSDraggingContext, NSDraggingFormation, NSDraggingItem, + NSDraggingSession, NSDraggingSource, NSEvent, NSEventModifierFlags, NSEventType, NSImage, + NSPasteboardItem, NSPasteboardTypeFileURL, NSPasteboardTypePNG, NSPasteboardTypeString, NSPasteboardTypeURL, + NSPasteboardType, NSView, NSWindow}; +use objc2_foundation::{NSArray, NSData, NSObject, NSPoint, NSRect, NSSize, NSString, NSURL}; + +type Done = Box<dyn FnOnce(DragOutcome)>; +type Muted = Vec<(Retained<NSWindow>, Retained<NSArray<NSPasteboardType>>)>; + +struct Ivars { + done: RefCell<Option<Done>>, + mask: Cell<NSDragOperation>, + /// The app's own windows are offered the drag too (`DragItem::within_app`). + within_app: Cell<bool>, + /// The app's windows that stop taking drops while this session runs, with the types each + /// had registered. + muted: RefCell<Muted>, +} + +/// Runs the end callback, which must not unwind into AppKit. +fn report(done: Done, outcome: DragOutcome) { + if std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| done(outcome))).is_err() { + eprintln!("rune: drag end callback panicked"); + } +} + +impl Drop for Ivars { + /// A session AppKit never ended (say, one started after the button was already up) still + /// reports once, when the next drag replaces its source. + fn drop(&mut self) { + unmute(std::mem::take(self.muted.get_mut())); + if let Some(done) = self.done.get_mut().take() { report(done, DragOutcome::Cancelled); } + } +} + +define_class!( + #[unsafe(super(NSObject))] + #[thread_kind = MainThreadOnly] + #[name = "RuneDragOutSource"] + #[ivars = Ivars] + struct Source; + + // SAFETY: `Source` inherits from `NSObject`, which implements `NSObjectProtocol`. + unsafe impl NSObjectProtocol for Source {} + + // SAFETY: `Source` is `MainThreadOnly` and each method matches AppKit's `NSDraggingSource` selector ABI. + unsafe impl NSDraggingSource for Source { + #[unsafe(method(draggingSession:sourceOperationMaskForDraggingContext:))] + fn mask(&self, _session: &NSDraggingSession, context: NSDraggingContext) -> NSDragOperation { + mask_in(self.ivars().mask.get(), context, self.ivars().within_app.get()) + } + #[unsafe(method(draggingSession:endedAtPoint:operation:))] + fn ended(&self, _session: &NSDraggingSession, _point: NSPoint, operation: NSDragOperation) { + unmute(std::mem::take(&mut *self.ivars().muted.borrow_mut())); + let done = self.ivars().done.borrow_mut().take(); + if let Some(done) = done { report(done, outcome(operation)); } + } + #[unsafe(method(ignoreModifierKeysForDraggingSession:))] + fn ignore_modifiers(&self, _session: &NSDraggingSession) -> bool { single(self.ivars().mask.get()) } + } +); + +thread_local! { + // AppKit's session doesn't document retaining its source; one drag runs at a time, so the + // newest source is kept until the next drag replaces it. + static LIVE: RefCell<Option<Retained<Source>>> = const { RefCell::new(None) }; +} + +fn outcome(operation: NSDragOperation) -> DragOutcome { + if operation.contains(NSDragOperation::Copy) { DragOutcome::Copied } + else if operation.intersects(NSDragOperation::Move | NSDragOperation::Delete | NSDragOperation::Generic) { DragOutcome::Moved } + else if operation.contains(NSDragOperation::Link) { DragOutcome::Linked } + else { DragOutcome::Cancelled } +} + +/// The operations the source offers: what the item allows, ignoring modifier keys. +fn mask(item: &DragItem) -> NSDragOperation { + [(DragOperation::Copy, NSDragOperation::Copy), (DragOperation::Move, NSDragOperation::Move), (DragOperation::Link, NSDragOperation::Link)] + .into_iter().filter(|&(op, _)| item.offers(op)).fold(NSDragOperation::None, |m, (_, ns)| m | ns) +} + +/// The app's own windows are offered nothing unless the item lets them take it: Rune windows +/// take no drops from their own drags by default. +fn mask_in(mask: NSDragOperation, context: NSDraggingContext, within_app: bool) -> NSDragOperation { + if context == NSDraggingContext::WithinApplication && !within_app { NSDragOperation::None } else { mask } +} + +/// Modifier keys pick among several offered operations (Cmd+Option for a link in Finder); with +/// one on offer they'd only turn the drop into a refusal. +fn single(mask: NSDragOperation) -> bool { mask.bits().count_ones() <= 1 } + +/// winit's windows accept any file drag and answer Copy whatever the source offers, ignoring an +/// empty mask, so a drag let go over the app would end Copied without sliding back (and hand +/// the app its own file). The app's drop-taking windows stop taking drops for the session. +fn mute(mtm: MainThreadMarker) -> Muted { + let winit_types = || NSArray::from_retained_slice(&[NSString::from_str("NSFilenamesPboardType")]); + // SAFETY: window and delegate calls on the main thread. NSWindow answers + // `registeredDraggedTypes` like NSView, though only NSView declares it; without it, the + // types are winit's. + unsafe { + NSApplication::sharedApplication(mtm).windows().into_iter() + .filter(|w| w.delegate().is_some_and(|d| d.respondsToSelector(sel!(draggingEntered:)))) + .filter_map(|w| { + let types: Retained<NSArray<NSPasteboardType>> = if w.respondsToSelector(sel!(registeredDraggedTypes)) { + msg_send![&*w, registeredDraggedTypes] + } else { winit_types() }; + if types.is_empty() { return None; } + w.unregisterDraggedTypes(); + Some((w, types)) + }) + .collect() + } +} + +/// Gives the windows back exactly the drag types they had. +fn unmute(windows: Muted) { + // `muted` is only filled on the main thread, and its owner, a main-thread-only source, + // drops there. + for (w, types) in windows { w.registerForDraggedTypes(&types); } +} + +pub(super) fn begin(window: &winit::window::Window, start: DragOutStart, picture: Option<DragImage>, done: Done) { + // The previous source drops first (reporting if it never ended, and giving back the drag + // types it took), so this session's muting isn't undone. Outside the borrow: it reports. + let previous = LIVE.with(|live| live.take()); + drop(previous); + let Some(mtm) = MainThreadMarker::new() else { return done(DragOutcome::Cancelled) }; + let Some(view) = crate::platform::macos::content_view(window) else { return done(DragOutcome::Cancelled) }; + let Some(event) = drag_event(mtm, &view) else { return done(DragOutcome::Cancelled) }; + // SAFETY: AppKit calls on the main thread with live objects; the source outlives the + // session through LIVE. + unsafe { + let (image, frame) = image_and_frame(&start, picture.as_ref()); + let items = pasteboard_items(&start); + if items.is_empty() { return done(DragOutcome::Cancelled); } + let dragging: Vec<Retained<NSDraggingItem>> = items.iter().enumerate().map(|(i, item)| { + let d = NSDraggingItem::initWithPasteboardWriter(NSDraggingItem::alloc(), ProtocolObject::from_ref(&**item)); + // Extra files trail a little behind the first, as Finder stacks them. + let offset = (i.min(4) as f64) * 3.0; + let f = NSRect::new(NSPoint::new(frame.origin.x + offset, frame.origin.y + offset), frame.size); + d.setDraggingFrame_contents(f, image.as_deref().map(|i| &**i as &AnyObject)); + d + }).collect(); + // A drag the app's windows take leaves their drop registration alone. + let within_app = start.item.drops_within_app(); + let muted = if within_app { Muted::new() } else { mute(mtm) }; + let source = mtm.alloc::<Source>().set_ivars(Ivars { done: RefCell::new(Some(done)), mask: Cell::new(mask(&start.item)), within_app: Cell::new(within_app), muted: RefCell::new(muted) }); + let source: Retained<Source> = msg_send![super(source), init]; + LIVE.with(|live| *live.borrow_mut() = Some(source.clone())); + let session = view.beginDraggingSessionWithItems_event_source(&NSArray::from_retained_slice(&dragging), &event, ProtocolObject::from_ref(&*source)); + // A drop nowhere slides the image back over the element. + session.setAnimatesToStartingPositionsOnCancelOrFail(true); + session.setDraggingFormation(NSDraggingFormation::None); + } +} + +/// The mouse event the session starts from: the event being dispatched when it's a left-button +/// press or drag, else one synthesised at the pointer (an overlay's polled pointer runs outside +/// event dispatch). +fn drag_event(mtm: MainThreadMarker, view: &NSView) -> Option<Retained<NSEvent>> { + let current = NSApplication::sharedApplication(mtm).currentEvent(); + if let Some(event) = &current { + if matches!(event.r#type(), NSEventType::LeftMouseDragged | NSEventType::LeftMouseDown) { return current; } + } + // With the button already up, AppKit would never end the session. + if NSEvent::pressedMouseButtons() & 1 == 0 { return None; } + let window = view.window()?; + let at = window.mouseLocationOutsideOfEventStream(); + let time = current.as_ref().map_or(0.0, |e| e.timestamp()); + NSEvent::mouseEventWithType_location_modifierFlags_timestamp_windowNumber_context_eventNumber_clickCount_pressure( + NSEventType::LeftMouseDragged, at, NSEventModifierFlags::empty(), time, window.windowNumber(), None, 0, 1, 1.0) +} + +/// The drag image and where it starts, in the view's (flipped, top-left) points. +fn image_and_frame(start: &DragOutStart, picture: Option<&DragImage>) -> (Option<Retained<NSImage>>, NSRect) { + // SAFETY: NSImage and NSWorkspace calls on the main thread (`begin`'s only caller context). + unsafe { + let [x, y, w, h] = start.rect; + let image = picture.and_then(|p| { + let image = NSImage::initWithData(NSImage::alloc(), &NSData::with_bytes(p.png_data()))?; + let natural = image.size(); + let [fx, fy, fw, fh] = p.frame(start.bounds, start.press, (natural.width as f32, natural.height as f32)); + // The frame's size scales the picture; setting it on the image too keeps a + // high-resolution snapshot at its point size. + image.setSize(NSSize::new(fw as f64, fh as f64)); + Some((image, NSRect::new(NSPoint::new(fx as f64, fy as f64), NSSize::new(fw as f64, fh as f64)))) + }); + if let Some((image, frame)) = image { return (Some(image), frame); } + // No picture: the first file's Finder icon, else the element's outline only. + let icon = start.item.paths().first().map(|path| { + let workspace: Retained<AnyObject> = msg_send![objc2::class!(NSWorkspace), sharedWorkspace]; + let icon: Retained<NSImage> = msg_send![&workspace, iconForFile: &*NSString::from_str(&path_text(path))]; + icon.setSize(NSSize::new(64.0, 64.0)); + icon + }); + match icon { + Some(icon) => (Some(icon), NSRect::new(NSPoint::new(start.press.0 as f64 - 32.0, start.press.1 as f64 - 32.0), NSSize::new(64.0, 64.0))), + None => (None, NSRect::new(NSPoint::new(x as f64, y as f64), NSSize::new(w.max(1.0) as f64, h.max(1.0) as f64))), + } + } +} + +/// One pasteboard item per file, the PNG and text riding on the first (or alone without files). +fn pasteboard_items(start: &DragOutStart) -> Vec<Retained<NSPasteboardItem>> { + // SAFETY: Foundation and AppKit pasteboard calls with live objects; AppKit's type + // constants are immutable statics. + unsafe { + let item = &start.item; + let mut out = Vec::new(); + for path in item.paths() { + let text = path_text(path); + let ns_path = NSString::from_str(&text); + let url = NSURL::fileURLWithPath(&ns_path); + let Some(url) = url.absoluteString() else { continue }; + let p = NSPasteboardItem::new(); + p.setString_forType(&url, NSPasteboardTypeFileURL); + p.setString_forType(&url, NSPasteboardTypeURL); + if item.plain_text().is_none() { p.setString_forType(&ns_path, NSPasteboardTypeString); } + out.push(p); + } + if item.png_data().is_some() || item.plain_text().is_some() { + let p = match out.first() { Some(p) => p.clone(), None => { out.push(NSPasteboardItem::new()); out[0].clone() } }; + if let Some(png) = item.png_data() { p.setData_forType(&NSData::with_bytes(png), NSPasteboardTypePNG); } + if let Some(text) = item.plain_text() { p.setString_forType(&NSString::from_str(text), NSPasteboardTypeString); } + } + out + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_mask_offers_what_the_item_allows() { + assert_eq!(mask(&DragItem::new()), NSDragOperation::Copy); + assert_eq!(mask(&DragItem::new().allow_move()), NSDragOperation::Copy | NSDragOperation::Move); + assert_eq!(mask(&DragItem::new().operation(DragOperation::Move)), NSDragOperation::Move); + assert_eq!(mask(&DragItem::new().operation(DragOperation::Link).allow(DragOperation::Copy)), NSDragOperation::Link | NSDragOperation::Copy); + } + + #[test] + fn nothing_is_offered_to_the_apps_own_windows() { + let m = NSDragOperation::Copy | NSDragOperation::Link; + assert_eq!(mask_in(m, NSDraggingContext::OutsideApplication, false), m); + assert_eq!(mask_in(m, NSDraggingContext::WithinApplication, false), NSDragOperation::None); + // `DragItem::within_app` offers the app's own windows the same operations. + assert_eq!(mask_in(m, NSDraggingContext::WithinApplication, true), m); + assert_eq!(mask_in(m, NSDraggingContext::OutsideApplication, true), m); + } + + #[test] + fn modifier_keys_only_count_when_several_operations_are_offered() { + assert!(single(mask(&DragItem::new()))); + assert!(!single(mask(&DragItem::new().allow(DragOperation::Link)))); + assert!(!single(mask(&DragItem::new().allow_move()))); + } + + #[test] + fn operations_map_to_outcomes() { + assert_eq!(outcome(NSDragOperation::Copy), DragOutcome::Copied); + assert_eq!(outcome(NSDragOperation::Move), DragOutcome::Moved); + assert_eq!(outcome(NSDragOperation::Delete), DragOutcome::Moved); + assert_eq!(outcome(NSDragOperation::Generic), DragOutcome::Moved); + assert_eq!(outcome(NSDragOperation::Link), DragOutcome::Linked); + assert_eq!(outcome(NSDragOperation::None), DragOutcome::Cancelled); + } + + fn ivars(log: &std::rc::Rc<RefCell<Vec<DragOutcome>>>) -> Ivars { + let log = log.clone(); + Ivars { done: RefCell::new(Some(Box::new(move |o| log.borrow_mut().push(o)))), mask: Cell::new(NSDragOperation::Copy), within_app: Cell::new(false), muted: RefCell::default() } + } + + #[test] + fn a_session_that_never_ended_reports_cancelled_once_on_drop() { + let log = std::rc::Rc::default(); + drop(ivars(&log)); + assert_eq!(*log.borrow(), [DragOutcome::Cancelled]); + } + + #[test] + fn an_ended_session_does_not_report_again_on_drop() { + let log = std::rc::Rc::default(); + let ivars = ivars(&log); + let done = ivars.done.borrow_mut().take().unwrap(); + report(done, DragOutcome::Copied); + drop(ivars); + assert_eq!(*log.borrow(), [DragOutcome::Copied]); + } + + #[test] + fn a_panicking_end_callback_does_not_unwind() { + report(Box::new(|_| panic!("boom")), DragOutcome::Cancelled); + } +} diff --git a/app/vendor/rune/crates/rune/src/drag_out/mod.rs b/app/vendor/rune/crates/rune/src/drag_out/mod.rs new file mode 100644 index 0000000..a94be23 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/drag_out/mod.rs @@ -0,0 +1,419 @@ +//! Dragging data out of a window into other apps: an OS drag source. +//! +//! An element marked [`crate::El::drag_out`] starts a system drag session once the pointer +//! travels [`DRAG_THRESHOLD`] points from the press. The session carries a [`DragItem`] (file +//! URLs, PNG data, plain text) and shows a [`DragImage`], by default a snapshot of the element +//! as the window last drew it, starting exactly over the element. [`crate::El::on_drag_start`] +//! and [`crate::El::on_drag_end`] bracket the session, so the app can style the source while +//! it's dragged; [`DragOutcome`] says how the drop ended. Rune windows take no drops from their +//! own app's drags unless [`DragItem::within_app`] says so, so a drag let go over the app ends +//! [`DragOutcome::Cancelled`] and the image slides back. +//! +//! macOS runs the session with `NSDraggingSource`, Windows with OLE's `DoDragDrop` and the shell's +//! drag image (`windows`). Wayland and X11 don't start one yet: there `drag_out` is ignored and the +//! element keeps its ordinary press and `on_drag` behaviour; their backends slot in behind the +//! same types. +//! +//! Windows start the session from the mouse-dragged event AppKit is delivering. Overlay panels +//! track the pointer by polling, so there may be no such event; the overlay then builds a +//! dragged event at the current mouse location. Both paths have GUI tests on a real desktop +//! (`tests/macos_drag_out.rs`, and `tests/macos_overlay_drag_out.rs` for a non-activating +//! overlay that takes input only on its hit regions). + +use crate::color::{Color, srgb_decode, srgb_encode}; +use std::path::{Path, PathBuf}; + +#[cfg(target_os = "macos")] +mod macos; +#[cfg(target_os = "windows")] +mod windows; + +/// Whether this platform's windows start OS drag sessions. +pub(crate) const SUPPORTED: bool = cfg!(any(target_os = "macos", target_os = "windows")); + +/// Pointer travel (points, straight-line) from the press before a drag session starts. +/// AppKit views commonly use 4; GTK's default is 8; Windows' `SM_CXDRAG` is 4 pixels. +pub const DRAG_THRESHOLD: f32 = if cfg!(all(unix, not(target_os = "macos"), not(target_os = "ios"), not(target_os = "android"))) { 8.0 } else { 4.0 }; + +/// Whether a pointer that went down at `from` and is now at `to` has travelled past +/// `threshold` points. [`crate::El::drag_threshold`] sets it per element. +pub(crate) fn past_threshold(from: (f32, f32), to: (f32, f32), threshold: f32) -> bool { + let (dx, dy) = (to.0 - from.0, to.1 - from.1); + dx * dx + dy * dy > threshold * threshold +} + +/// What a drag carries to another app: any of file URLs, PNG data and plain text, plus the +/// picture shown under the pointer. +/// +/// ``` +/// # use rune::drag_out::DragItem; +/// let item = DragItem::new().file("/Applications/Example.app"); +/// assert_eq!(item.paths().len(), 1); +/// ``` +#[derive(Clone, Debug, PartialEq)] +pub struct DragItem { + files: Vec<PathBuf>, + png: Option<Vec<u8>>, + text: Option<String>, + image: Option<DragImage>, + operations: u8, + backing: Option<Color>, + within_app: bool, +} + +impl Default for DragItem { + fn default() -> Self { + Self { files: Vec::new(), png: None, text: None, image: None, operations: DragOperation::Copy.bit(), backing: None, within_app: false } + } +} + +impl DragItem { + pub fn new() -> Self { Self::default() } + + /// Add a file (or folder or app bundle) by path; repeat for several. Finder copies it, + /// and System Settings' privacy lists accept an app bundle. + pub fn file(mut self, path: impl Into<PathBuf>) -> Self { + self.files.push(path.into()); + self + } + + /// PNG-encoded image data, for targets that take an image rather than a file. + pub fn png(mut self, bytes: impl Into<Vec<u8>>) -> Self { + self.png = Some(bytes.into()); + self + } + + /// Straight-alpha sRGB RGBA8 pixels, encoded as PNG data. Ignored if the sizes disagree. + pub fn rgba(self, width: u32, height: u32, pixels: &[u8]) -> Self { + match encode_png(width, height, pixels) { + Some(png) => self.png(png), + None => self, + } + } + + /// Plain text. Without it, a file's path is offered as text. + pub fn text(mut self, text: impl Into<String>) -> Self { + self.text = Some(text.into()); + self + } + + /// The picture under the pointer. Defaults to a snapshot of the element. + pub fn image(mut self, image: DragImage) -> Self { + self.image = Some(image); + self + } + + /// Show the drag image composited over `color`, so it's opaque even where the element or + /// its window is transparent (an overlay panel, a translucent window material). AppKit + /// still draws its drag window at about 90% opacity, as it does for every app's drag. + /// + /// ``` + /// # use rune::{Color, DragItem}; + /// let item = DragItem::new().text("row").opaque(Color::WHITE); + /// assert_eq!(item.backing(), Some(Color::WHITE)); + /// ``` + pub fn opaque(mut self, color: Color) -> Self { + self.backing = Some(color.alpha(1.0)); + self + } + + /// Offer only `operation` to the target, instead of the default [`DragOperation::Copy`]. + /// + /// ``` + /// # use rune::{DragItem, DragOperation}; + /// let item = DragItem::new().text("row").operation(DragOperation::Link); + /// assert!(item.offers(DragOperation::Link) && !item.offers(DragOperation::Copy)); + /// ``` + pub fn operation(mut self, operation: DragOperation) -> Self { + self.operations = operation.bit(); + self + } + + /// Offer `operation` as well as those already offered; the target picks one. + pub fn allow(mut self, operation: DragOperation) -> Self { + self.operations |= operation.bit(); + self + } + + /// Let the target move files instead of copying them (Finder moves within one volume). + /// By default a drag only offers a copy, whatever modifier keys are held. + pub fn allow_move(self) -> Self { self.allow(DragOperation::Move) } + + /// Offer the drag to this app's own windows too, so their `on_drop_files` targets receive + /// its files as a drop from Finder would (an image dragged from a timeline into the + /// composer). By default the app's windows take no drops from its own drags. A drag let go + /// over a window with no target that accepts it ends [`DragOutcome::Copied`] without sliding + /// back, as the window takes any file drag. + /// + /// ``` + /// # use rune::DragItem; + /// assert!(DragItem::new().file("/a.png").within_app().drops_within_app()); + /// assert!(!DragItem::new().drops_within_app()); + /// ``` + pub fn within_app(mut self) -> Self { + self.within_app = true; + self + } + + pub fn paths(&self) -> &[PathBuf] { &self.files } + pub fn png_data(&self) -> Option<&[u8]> { self.png.as_deref() } + pub fn plain_text(&self) -> Option<&str> { self.text.as_deref() } + pub fn drag_image(&self) -> Option<&DragImage> { self.image.as_ref() } + pub fn allows_move(&self) -> bool { self.offers(DragOperation::Move) } + /// Whether the app's own windows take this drag's drop ([`DragItem::within_app`]). + pub fn drops_within_app(&self) -> bool { self.within_app } + /// Whether the drag offers `operation` to the target. + pub fn offers(&self, operation: DragOperation) -> bool { self.operations & operation.bit() != 0 } + /// The colour the drag image is shown over, from [`DragItem::opaque`]. + pub fn backing(&self) -> Option<Color> { self.backing } + /// Carries nothing a target could receive. + pub fn is_empty(&self) -> bool { self.files.is_empty() && self.png.is_none() && self.text.is_none() } +} + +/// What a drag lets the target do with the data. A drag offers [`DragOperation::Copy`] unless +/// [`DragItem::operation`] or [`DragItem::allow`] say otherwise, and modifier keys don't change +/// the offer. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[non_exhaustive] +pub enum DragOperation { + /// The target copies the data. + Copy, + /// The target moves the files. + Move, + /// The target makes a link or alias to the files. + Link, +} + +impl DragOperation { + fn bit(self) -> u8 { + match self { Self::Copy => 1, Self::Move => 2, Self::Link => 4 } + } +} + +/// The picture a drag shows under the pointer, as PNG data. +#[derive(Clone, Debug, PartialEq)] +pub struct DragImage { + png: Vec<u8>, + /// Display size in points; `None` draws one pixel per point at the window's scale. + size: Option<(f32, f32)>, + placement: Placement, +} + +/// Where a drag image starts, in window points. +#[derive(Clone, Copy, Debug, PartialEq)] +enum Placement { + /// Centred under the press. + Pointer, + /// Over the element's top-left, at the element's full (unclipped) size unless sized. + Element, + /// Top-left at this point, at the image's own size (the snapshot's pixel-aligned crop). + At(f32, f32), +} + +impl DragImage { + pub fn png(bytes: impl Into<Vec<u8>>) -> Self { Self { png: bytes.into(), size: None, placement: Placement::Pointer } } + + /// Straight-alpha sRGB RGBA8 pixels. `None` if `pixels` isn't `width * height * 4` bytes. + pub fn rgba(width: u32, height: u32, pixels: &[u8]) -> Option<Self> { + encode_png(width, height, pixels).map(Self::png) + } + + /// Draw it this many points wide and high. + pub fn size(mut self, width: f32, height: f32) -> Self { + self.size = Some((width, height)); + self + } + + /// Start the drag with the image over the element, filling its bounds (scaled to fit), as + /// the default snapshot does, instead of centred under the pointer. Use it for a picture + /// rendered at the element's size, so the drag appears to lift the element itself. With + /// [`DragImage::size`] it keeps that size, from the element's top-left. A row scrolled + /// partly out of view still gets its whole size, not the visible strip. + pub fn over_element(mut self) -> Self { + self.placement = Placement::Element; + self + } + + pub fn png_data(&self) -> &[u8] { &self.png } + pub fn points(&self) -> Option<(f32, f32)> { self.size } + + /// Where the drag image starts, x, y, w, h in window points: `bounds` is the element's + /// unclipped rect, and `natural` the image's size in points when [`DragImage::size`] + /// wasn't set. + #[cfg_attr(not(any(target_os = "macos", target_os = "windows")), allow(dead_code))] + pub(crate) fn frame(&self, bounds: [f32; 4], press: (f32, f32), natural: (f32, f32)) -> [f32; 4] { + let (w, h) = self.size.unwrap_or(natural); + match self.placement { + Placement::Pointer => [press.0 - w / 2.0, press.1 - h / 2.0, w, h], + Placement::Element => { + let (w, h) = self.size.unwrap_or((bounds[2], bounds[3])); + [bounds[0], bounds[1], w.max(1.0), h.max(1.0)] + } + Placement::At(x, y) => [x, y, w, h], + } + } + + /// The image composited over an opaque `backing`, blended in linear light as the window + /// blends. `None` if the PNG doesn't decode. + #[cfg_attr(not(any(target_os = "macos", target_os = "windows")), allow(dead_code))] + pub(crate) fn over(&self, backing: Color) -> Option<Self> { + let mut rgba = crate::image::png_rgba8(&self.png).ok()?; + let bg = [backing.r, backing.g, backing.b]; + for p in rgba.pixels_mut() { + let a = p[3] as f32 / 255.0; + for c in 0..3 { + let v = srgb_decode(p[c] as f32 / 255.0) * a + bg[c] * (1.0 - a); + p[c] = (srgb_encode(v) * 255.0).round().clamp(0.0, 255.0) as u8; + } + p[3] = 255; + } + let png = encode_png(rgba.width(), rgba.height(), rgba.as_raw())?; + Some(Self { png, ..self.clone() }) + } +} + +/// How a drag out of the window ended. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[non_exhaustive] +pub enum DragOutcome { + /// The target copied the data. + Copied, + /// The target moved the files (only offered after [`DragItem::allow_move`] or + /// [`DragOperation::Move`]), or the drop + /// asked the source to delete them (the Trash). + Moved, + /// The target made a link or alias to the files. + Linked, + /// Dropped nowhere that accepted it, or cancelled with Escape. + Cancelled, +} + +/// A drag the runtime asked the host to start, inside the pointer event that crossed the +/// threshold. +pub(crate) struct DragOutStart { + pub path: String, + pub item: DragItem, + /// The element's visible drawn rect in window points: x, y, w, h. + pub rect: [f32; 4], + /// The element's whole drawn rect, before scroll clipping. + #[cfg_attr(not(any(target_os = "macos", target_os = "windows")), allow(dead_code))] + pub bounds: [f32; 4], + /// Where the pointer went down, in window points. + #[cfg_attr(not(any(target_os = "macos", target_os = "windows")), allow(dead_code))] + pub press: (f32, f32), +} + +pub(crate) type DragEnds = std::rc::Rc<std::cell::RefCell<Vec<(String, DragOutcome)>>>; + +pub(crate) fn encode_png(width: u32, height: u32, rgba: &[u8]) -> Option<Vec<u8>> { + if width == 0 || height == 0 || rgba.len() != (width as usize) * (height as usize) * 4 { return None; } + let mut out = Vec::new(); + let mut enc = png::Encoder::new(&mut out, width, height); + enc.set_color(png::ColorType::Rgba); + enc.set_depth(png::BitDepth::Eight); + enc.set_source_srgb(png::SrgbRenderingIntent::Perceptual); + let mut w = enc.write_header().ok()?; + w.write_image_data(rgba).ok()?; + w.finish().ok()?; + Some(out) +} + +/// Draws the last frame's instances again offscreen and reads back `rect` (window points), so +/// the drag shows what the user grabbed. `None` for formats it can't read back. +pub(crate) fn snapshot(gpu: &crate::render::Gpu, renderer: &crate::render::Renderer, size: (u32, u32), scale: f32, clear: [f32; 4], rect: [f32; 4]) -> Option<DragImage> { + let format = renderer.format(); + let bgra = match format { + wgpu::TextureFormat::Bgra8UnormSrgb | wgpu::TextureFormat::Bgra8Unorm => true, + wgpu::TextureFormat::Rgba8UnormSrgb | wgpu::TextureFormat::Rgba8Unorm => false, + _ => return None, + }; + let px = crop(rect, scale, size)?; + let [x, y, w, h] = px; + let texture = gpu.device.create_texture(&wgpu::TextureDescriptor { + label: Some("drag image"), + size: wgpu::Extent3d { width: size.0, height: size.1, depth_or_array_layers: 1 }, + mip_level_count: 1, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + format, + usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC, + view_formats: &[], + }); + let view = texture.create_view(&Default::default()); + let readback = rune_staging::Readback::new(&gpu.device, "drag image readback", w, h, 4); + let mut enc = gpu.device.create_command_encoder(&Default::default()); + renderer.draw(&mut enc, &view, clear); + readback.copy_from_origin(&mut enc, &texture, wgpu::Origin3d { x, y, z: 0 }); + gpu.queue.submit([enc.finish()]); + readback.buffer().slice(..).map_async(wgpu::MapMode::Read, |_| {}); + rune_gpu::health::poll(&gpu.device, wgpu::PollType::wait_indefinitely()).ok()?; + let mut rgba = readback.try_take_mapped()?; + to_straight_rgba(&mut rgba, bgra, format.is_srgb()); + let mut image = DragImage::rgba(w, h, &rgba)?.size(w as f32 / scale, h as f32 / scale); + // The crop rounds out to whole pixels, so the image sits exactly over what was drawn. + image.placement = Placement::At(x as f32 / scale, y as f32 / scale); + Some(image) +} + +/// `rect` (points) in device pixels, clamped to the frame: x, y, w, h. `None` when empty. +fn crop(rect: [f32; 4], scale: f32, size: (u32, u32)) -> Option<[u32; 4]> { + let x0 = (rect[0] * scale).floor().clamp(0.0, size.0 as f32) as u32; + let y0 = (rect[1] * scale).floor().clamp(0.0, size.1 as f32) as u32; + let x1 = ((rect[0] + rect[2]) * scale).ceil().clamp(0.0, size.0 as f32) as u32; + let y1 = ((rect[1] + rect[3]) * scale).ceil().clamp(0.0, size.1 as f32) as u32; + (x1 > x0 && y1 > y0).then_some([x0, y0, x1 - x0, y1 - y0]) +} + +/// Frame pixels are premultiplied, in the surface's channel order. On `*Srgb` targets the bytes +/// hold `srgb_encode(linear_rgb * a)` and must be un-premultiplied in linear light; on non-sRGB +/// targets (`srgb_blend`) they hold `srgb_encode(linear_rgb) * a` and divide directly. +fn to_straight_rgba(pixels: &mut [u8], bgra: bool, srgb_target: bool) { + if bgra { + for p in pixels.chunks_exact_mut(4) { + p.swap(0, 2); + } + } + if srgb_target { + crate::render::surface_alpha::straight_alpha(pixels); + } else { + for p in pixels.chunks_exact_mut(4) { + let a = p[3]; + if a == 0 { + p[..3].fill(0); + } else if a != 255 { + for c in &mut p[..3] { + *c = ((*c as u32 * 255 + a as u32 / 2) / a as u32).min(255) as u8; + } + } + } + } +} + +/// Starts the OS drag session for `start` from inside the pointer event that crossed the +/// threshold. `done` runs once with how it ended (also when it couldn't start: `Cancelled`). +#[cfg_attr(not(any(target_os = "macos", target_os = "windows")), allow(unused_variables))] +pub(crate) fn begin(window: &winit::window::Window, start: DragOutStart, snapshot: Option<DragImage>, done: Box<dyn FnOnce(DragOutcome)>) { + #[cfg(target_os = "macos")] + { let picture = picture(&start.item, snapshot); macos::begin(window, start, picture, done); } + #[cfg(target_os = "windows")] + { let picture = picture(&start.item, snapshot); windows::begin(window, start, picture, done); } + #[cfg(not(any(target_os = "macos", target_os = "windows")))] + done(DragOutcome::Cancelled); +} + +/// The item's own image, else the snapshot, over the item's backing colour if it has one. +#[cfg_attr(not(any(target_os = "macos", target_os = "windows")), allow(dead_code))] +fn picture(item: &DragItem, snapshot: Option<DragImage>) -> Option<DragImage> { + let picture = item.drag_image().cloned().or(snapshot)?; + match item.backing() { + Some(backing) => picture.over(backing).or(Some(picture)), + None => Some(picture), + } +} + +/// The path offered as text when a file drag has no text of its own. +#[cfg_attr(not(any(target_os = "macos", target_os = "windows")), allow(dead_code))] +fn path_text(path: &Path) -> String { path.to_string_lossy().into_owned() } + +#[cfg(test)] +mod tests; diff --git a/app/vendor/rune/crates/rune/src/drag_out/tests.rs b/app/vendor/rune/crates/rune/src/drag_out/tests.rs new file mode 100644 index 0000000..e280012 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/drag_out/tests.rs @@ -0,0 +1,182 @@ +use super::*; + +#[test] +fn threshold_is_straight_line_travel_beyond_the_platform_distance() { + let t = DRAG_THRESHOLD; + assert!(!past_threshold((10.0, 10.0), (10.0, 10.0), t)); + assert!(!past_threshold((10.0, 10.0), (10.0 + t, 10.0), t), "exactly the threshold doesn't start"); + assert!(past_threshold((10.0, 10.0), (10.0 + t + 0.1, 10.0), t)); + let d = t * 0.75; + assert!(past_threshold((0.0, 0.0), (d, d), t), "diagonal travel counts its length"); +} + +#[test] +fn a_drag_item_collects_files_image_and_text() { + let item = DragItem::new().file("/a.png").file("/b.txt").text("hello").png(vec![1, 2, 3]); + assert_eq!(item.paths(), [PathBuf::from("/a.png"), PathBuf::from("/b.txt")]); + assert_eq!(item.plain_text(), Some("hello")); + assert_eq!(item.png_data(), Some(&[1u8, 2, 3][..])); + assert!(!item.allows_move() && item.drag_image().is_none() && !item.is_empty()); + assert!(DragItem::new().is_empty()); + assert!(DragItem::new().allow_move().allows_move()); +} + +#[test] +fn a_drag_offers_copy_unless_told_otherwise() { + let item = DragItem::new(); + assert!(item.offers(DragOperation::Copy) && !item.offers(DragOperation::Move) && !item.offers(DragOperation::Link)); + let item = DragItem::new().allow_move(); + assert!(item.offers(DragOperation::Copy) && item.offers(DragOperation::Move)); + let item = DragItem::new().operation(DragOperation::Move); + assert!(!item.offers(DragOperation::Copy) && item.offers(DragOperation::Move) && item.allows_move()); + let item = DragItem::new().operation(DragOperation::Link).allow(DragOperation::Copy); + assert!(item.offers(DragOperation::Copy) && item.offers(DragOperation::Link) && !item.offers(DragOperation::Move)); +} + +#[test] +fn drag_image_frames_start_over_the_element_or_under_the_pointer() { + let rect = [20.0, 40.0, 200.0, 32.0]; + let press = (50.0, 60.0); + let image = DragImage::rgba(1, 1, &[0; 4]).unwrap(); + assert_eq!(image.frame(rect, press, (64.0, 64.0)), [18.0, 28.0, 64.0, 64.0], "a supplied picture is centred under the press"); + assert_eq!(image.clone().size(10.0, 20.0).frame(rect, press, (64.0, 64.0)), [45.0, 50.0, 10.0, 20.0]); + assert_eq!(image.clone().over_element().frame(rect, press, (64.0, 64.0)), rect, "over_element fills the element's bounds"); + assert_eq!(image.clone().size(10.0, 12.0).over_element().frame(rect, press, (64.0, 64.0)), [20.0, 40.0, 10.0, 12.0], "an explicit size wins"); + assert_eq!(image.over_element().frame([5.0, 5.0, 0.0, 0.0], press, (1.0, 1.0)), [5.0, 5.0, 1.0, 1.0], "never an empty frame"); +} + +#[test] +fn the_snapshot_frame_is_its_pixel_aligned_crop() { + let mut image = DragImage::rgba(41, 21, &[0; 41 * 21 * 4]).unwrap().size(20.5, 10.5); + image.placement = Placement::At(10.0, 5.0); + assert_eq!(image.frame([10.2, 5.3, 20.0, 10.0], (0.0, 0.0), (41.0, 21.0)), [10.0, 5.0, 20.5, 10.5]); +} + +#[test] +fn an_opaque_backing_fills_transparent_pixels_and_keeps_opaque_ones() { + let image = DragImage::rgba(3, 1, &[255, 0, 0, 255, 0, 0, 0, 0, 255, 255, 255, 128]).unwrap().size(3.0, 1.0).over_element(); + let flat = image.over(Color { r: 0.0, g: 0.0, b: 1.0, a: 1.0 }).unwrap(); + assert_eq!((flat.points(), flat.placement), (Some((3.0, 1.0)), Placement::Element), "size and placement survive"); + let rgba = image::load_from_memory(flat.png_data()).unwrap().to_rgba8(); + assert_eq!(rgba.get_pixel(0, 0).0, [255, 0, 0, 255]); + assert_eq!(rgba.get_pixel(1, 0).0, [0, 0, 255, 255]); + let half = rgba.get_pixel(2, 0).0; + assert_eq!(half[3], 255); + assert!(half[0] == half[1] && half[0] > 150 && half[2] == 255, "half white over blue, mixed in linear light: {half:?}"); +} + +#[test] +fn the_picture_is_the_items_image_else_the_snapshot_over_the_backing() { + let snap = DragImage::rgba(1, 1, &[0, 0, 0, 0]).unwrap(); + let own = DragImage::rgba(1, 1, &[1, 2, 3, 255]).unwrap(); + assert_eq!(picture(&DragItem::new(), Some(snap.clone())), Some(snap.clone())); + assert_eq!(picture(&DragItem::new().image(own.clone()), Some(snap.clone())), Some(own)); + assert_eq!(picture(&DragItem::new(), None), None); + let flat = picture(&DragItem::new().opaque(Color::WHITE), Some(snap)).unwrap(); + assert_eq!(image::load_from_memory(flat.png_data()).unwrap().to_rgba8().get_pixel(0, 0).0, [255, 255, 255, 255]); +} + +#[test] +fn rgba_encodes_png_and_rejects_a_wrong_length() { + let item = DragItem::new().rgba(1, 1, &[255, 0, 0, 255]); + let png = item.png_data().unwrap(); + assert_eq!(&png[1..4], b"PNG"); + assert!(DragItem::new().rgba(2, 2, &[0; 4]).png_data().is_none()); + assert!(DragImage::rgba(0, 0, &[]).is_none()); + assert_eq!(DragImage::rgba(1, 1, &[0; 4]).unwrap().size(8.0, 8.0).points(), Some((8.0, 8.0))); +} + +#[test] +fn snapshot_crop_clamps_to_the_frame_in_device_pixels() { + assert_eq!(crop([10.0, 5.0, 20.0, 10.0], 2.0, (400, 300)), Some([20, 10, 40, 20])); + assert_eq!(crop([-5.0, -5.0, 10.0, 10.0], 2.0, (400, 300)), Some([0, 0, 10, 10])); + assert_eq!(crop([190.0, 0.0, 50.0, 10.0], 2.0, (400, 300)), Some([380, 0, 20, 20])); + assert_eq!(crop([500.0, 0.0, 10.0, 10.0], 2.0, (400, 300)), None); +} + +#[test] +fn readback_unpremultiplies_and_swaps_bgra() { + let mut unorm = [0, 0, 128, 128, 10, 20, 30, 255, 50, 60, 70, 0]; + to_straight_rgba(&mut unorm, true, false); + assert_eq!(unorm, [255, 0, 0, 128, 30, 20, 10, 255, 0, 0, 0, 0]); + + // Straight linear (0.25, 0.5, 0.125) tested at multiple alphas on both sRGB and non-sRGB targets. + let lin = [0.25_f32, 0.5, 0.125]; + let straight = lin.map(|v| (srgb_encode(v) * 255.0).round() as u8); + for a_u8 in [64u8, 128, 192, 255] { + let a = f32::from(a_u8) / 255.0; + // *Srgb target bytes: srgb_encode(linear_rgb * a), in BGRA and RGBA order. + let srgb_rgba = [ + (srgb_encode(lin[0] * a) * 255.0).round() as u8, + (srgb_encode(lin[1] * a) * 255.0).round() as u8, + (srgb_encode(lin[2] * a) * 255.0).round() as u8, + a_u8, + ]; + let mut from_rgba = srgb_rgba; + to_straight_rgba(&mut from_rgba, false, true); + let mut from_bgra = [srgb_rgba[2], srgb_rgba[1], srgb_rgba[0], srgb_rgba[3]]; + to_straight_rgba(&mut from_bgra, true, true); + assert_eq!(from_rgba, from_bgra); + for c in 0..3 { + assert!(from_rgba[c].abs_diff(straight[c]) <= 2, "srgb alpha {a_u8} ch {c}: got {} expected {}", from_rgba[c], straight[c]); + } + assert_eq!(from_rgba[3], a_u8); + + // Non-sRGB target bytes (`srgb_blend`): srgb_encode(linear_rgb) * a. + let unorm_rgba = [ + (srgb_encode(lin[0]) * a * 255.0).round() as u8, + (srgb_encode(lin[1]) * a * 255.0).round() as u8, + (srgb_encode(lin[2]) * a * 255.0).round() as u8, + a_u8, + ]; + let mut from_unorm = [unorm_rgba[2], unorm_rgba[1], unorm_rgba[0], unorm_rgba[3]]; + to_straight_rgba(&mut from_unorm, true, false); + for c in 0..3 { + assert!(from_unorm[c].abs_diff(straight[c]) <= 2, "unorm alpha {a_u8} ch {c}: got {} expected {}", from_unorm[c], straight[c]); + } + assert_eq!(from_unorm[3], a_u8); + } + let mut zero_srgb = [99, 137, 71, 0]; + to_straight_rgba(&mut zero_srgb, true, true); + assert_eq!(zero_srgb, [0, 0, 0, 0]); +} + +#[test] +fn snapshot_unpremultiplies_correctly_on_srgb_and_unorm_targets() { + use crate::render::{Gpu, Instance, KIND_RECT, NO_CLIP, Renderer}; + let gpu = Gpu::headless(); + let expected_rgb = [0.25_f32, 0.5, 0.125].map(|v| (srgb_encode(v) * 255.0).round() as u8); + let expected_a = (0.5_f32 * 255.0).round() as u8; + for (format, srgb_blend) in [ + (wgpu::TextureFormat::Bgra8UnormSrgb, false), + (wgpu::TextureFormat::Bgra8Unorm, true), + ] { + let mut renderer = Renderer::new(&gpu.device, format); + renderer.set_srgb_blend(srgb_blend); + let color = Color { r: 0.25, g: 0.5, b: 0.125, a: 0.5 }; + let fill = if srgb_blend { color.premul_srgb(1.0) } else { color.premul(1.0) }; + let inst = Instance { + rect: [0.0, 0.0, 8.0, 8.0], + radii: [0.0; 4], + fill, + border: [0.0; 4], + params: [0.0, KIND_RECT, 0.0, 1.0], + uv: [0.0; 4], + clip: NO_CLIP, + fade: [0; 4], + }; + let mut atlas = crate::text::Atlas::new(); + renderer.prepare_ui(&gpu.device, &gpu.queue, &mut atlas, &[inst], (8, 8)); + let shot = snapshot(&gpu, &renderer, (8, 8), 1.0, [0.0; 4], [0.0, 0.0, 8.0, 8.0]).expect("snapshot"); + let rgba = crate::image::png_rgba8(shot.png_data()).expect("valid png"); + let px = rgba.get_pixel(4, 4).0; + for c in 0..3 { + assert!( + px[c].abs_diff(expected_rgb[c]) <= 2, + "{format:?}: channel {c} got {}, expected {} (pixel {px:?})", + px[c], expected_rgb[c], + ); + } + assert!(px[3].abs_diff(expected_a) <= 1, "{format:?}: alpha got {}, expected {expected_a}", px[3]); + } +} diff --git a/app/vendor/rune/crates/rune/src/drag_out/windows.rs b/app/vendor/rune/crates/rune/src/drag_out/windows.rs new file mode 100644 index 0000000..a9a8b90 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/drag_out/windows.rs @@ -0,0 +1,293 @@ +//! OLE drag source for [`super::begin`]: `DoDragDrop` with a shell data object and the shell's +//! drag image (`IDragSourceHelper`), so Explorer, browsers and chat apps take the drag as they +//! take one from Explorer. +//! +//! `DoDragDrop` runs its own modal loop until the drop. Started inside winit's handler for the +//! pointer move, the windows would stop drawing and their timers would wait until it ended, so +//! the session is posted to the window and runs from the message loop instead, as the window +//! menu does (`platform::win32::frame`): the app keeps drawing (the source's dragging style, +//! hovers) while the drag is out. +//! +//! The data: files as the shell's own list of items when they share a folder (what Explorer +//! itself puts on a drag, `CFSTR_SHELLIDLIST` and `CF_HDROP` among others), else a `CF_HDROP`; +//! PNG data under the registered `PNG` format; text as `CF_UNICODETEXT`. The picture is the +//! element's snapshot or the item's image, handed to the shell's drag image manager, which draws +//! it with the drop description every Windows drag shows; a file drag without a picture gets +//! the shell's own image of the files. + +#![allow(unsafe_code)] + +use std::cell::{Cell, RefCell}; +use std::sync::{OnceLock, atomic::{AtomicUsize, Ordering}}; + +use windows::Win32::Foundation::{DRAGDROP_S_CANCEL, DRAGDROP_S_DROP, DRAGDROP_S_USEDEFAULTCURSORS, HGLOBAL, POINT, SIZE, S_OK}; +use windows::Win32::Graphics::Gdi::HBITMAP; +use windows::Win32::System::Com::{CLSCTX_INPROC_SERVER, CoCreateInstance, DVASPECT_CONTENT, FORMATETC, IDataObject, STGMEDIUM, STGMEDIUM_0, TYMED_HGLOBAL}; +use windows::Win32::System::Ole::{CF_HDROP, CF_UNICODETEXT, DROPEFFECT, DROPEFFECT_COPY, DROPEFFECT_LINK, DROPEFFECT_MOVE, DROPEFFECT_NONE, DoDragDrop, IDropSource, IDropSource_Impl, OleInitialize}; +use windows::Win32::System::SystemServices::{MK_LBUTTON, MODIFIERKEYS_FLAGS}; +use windows::Win32::UI::Shell::Common::ITEMIDLIST; +use windows::Win32::UI::Shell::{CLSID_DragDropHelper, IDragSourceHelper, ILClone, ILCreateFromPathW, ILFindLastID, ILFree, ILIsParent, ILRemoveLastID, SHCreateDataObject, SHDRAGIMAGE}; +use windows::core::{BOOL, HRESULT, PCWSTR, implement}; + +use super::{DragImage, DragItem, DragOperation, DragOutStart, DragOutcome, path_text}; + +type Done = Box<dyn FnOnce(DragOutcome)>; + +/// A session waiting for its posted message. +struct Pending { + hwnd: usize, + id: usize, + start: DragOutStart, + picture: Option<DragImage>, + done: Done, + scale: f32, +} + +static NEXT_DRAG: AtomicUsize = AtomicUsize::new(0x5255_4e47); + +thread_local! { + static PENDING: RefCell<Option<Pending>> = const { RefCell::new(None) }; + static DRAGGING: Cell<bool> = const { Cell::new(false) }; +} + +struct DragGuard; + +impl Drop for DragGuard { + fn drop(&mut self) { + DRAGGING.with(|d| d.set(false)); + } +} + +fn message() -> u32 { + static MESSAGE: OnceLock<u32> = OnceLock::new(); + // SAFETY: the name is NUL-terminated. + *MESSAGE.get_or_init(|| unsafe { windows_sys::Win32::UI::WindowsAndMessaging::RegisterWindowMessageW(wide("Rune::DragOut").as_ptr()) }) +} + +pub(super) fn begin(window: &winit::window::Window, start: DragOutStart, picture: Option<DragImage>, done: Done) { + // Refuse re-entrant drag loops while `DoDragDrop` is already on the stack. + if DRAGGING.with(Cell::get) { return done(DragOutcome::Cancelled); } + let Some(hwnd) = crate::platform::win32::hwnd(window) else { return done(DragOutcome::Cancelled) }; + let id = NEXT_DRAG.fetch_add(1, Ordering::Relaxed); + let pending = Pending { hwnd: hwnd as usize, id, start, picture, done, scale: window.scale_factor() as f32 }; + use windows_sys::Win32::UI::Shell::{RemoveWindowSubclass, SetWindowSubclass}; + use windows_sys::Win32::UI::WindowsAndMessaging::{IsWindow, PostMessageW}; + // One drag at a time: remove any earlier window's pending subclass and cancel it. + if let Some(old) = PENDING.with(|p| p.borrow_mut().replace(pending)) { + // SAFETY: removes the old drag's subclass if its window is still live. + unsafe { + if IsWindow(old.hwnd as _) != 0 { + RemoveWindowSubclass(old.hwnd as _, Some(procedure), old.id); + } + } + (old.done)(DragOutcome::Cancelled); + } + // SAFETY: Win32 calls on a live window this thread owns; the subclass keeps no pointer. + let posted = unsafe { + SetWindowSubclass(hwnd, Some(procedure), id, 0) != 0 + && (PostMessageW(hwnd, message(), id, 0) != 0 + || { RemoveWindowSubclass(hwnd, Some(procedure), id); false }) + }; + if !posted { + if let Some(p) = PENDING.with(|p| { + let mut slot = p.borrow_mut(); + slot.as_ref().is_some_and(|cur| cur.id == id).then(|| slot.take()).flatten() + }) { + (p.done)(DragOutcome::Cancelled); + } + } +} + +unsafe extern "system" fn procedure(hwnd: windows_sys::Win32::Foundation::HWND, msg: u32, w: usize, l: isize, id: usize, _: usize) -> isize { + use windows_sys::Win32::UI::Shell::{DefSubclassProc, RemoveWindowSubclass}; + use windows_sys::Win32::UI::WindowsAndMessaging::WM_NCDESTROY; + if (msg == message() && w == id) || msg == WM_NCDESTROY { + // SAFETY: removes this subclass from the window it was set on. + unsafe { RemoveWindowSubclass(hwnd, Some(procedure), id) }; + if msg == message() { + run(hwnd as usize, id); + return 0; + } + if let Some(p) = PENDING.with(|p| { + let mut slot = p.borrow_mut(); + slot.as_ref().is_some_and(|cur| cur.hwnd == hwnd as usize && cur.id == id).then(|| slot.take()).flatten() + }) { + std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| (p.done)(DragOutcome::Cancelled))).ok(); + } + } + // SAFETY: passes every other message on. + unsafe { DefSubclassProc(hwnd, msg, w, l) } +} + +/// Runs the pending session to its end and reports how it ended. +fn run(hwnd: usize, id: usize) { + let Some(p) = PENDING.with(|p| { + let mut slot = p.borrow_mut(); + slot.as_ref().is_some_and(|cur| cur.hwnd == hwnd && cur.id == id).then(|| slot.take()).flatten() + }) else { return }; + if DRAGGING.with(|d| d.replace(true)) { + std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| (p.done)(DragOutcome::Cancelled))).ok(); + return; + } + let _guard = DragGuard; + let outcome = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| session(&p))) + .ok() + .flatten() + .unwrap_or(DragOutcome::Cancelled); + if std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| (p.done)(outcome))).is_err() { + eprintln!("rune: drag end callback panicked"); + } +} + +fn session(p: &Pending) -> Option<DragOutcome> { + let item = &p.start.item; + // SAFETY: the UI thread is OLE's apartment (the drop target made it one; again is a no-op). + // Every object made here is released when it drops; media handed to `SetData` with + // `fRelease` belong to the data object. + unsafe { + OleInitialize(None).ok(); + let data = data_object(item)?; + if let Some(png) = item.png_data() { set(&data, png_format(), hglobal(png)?); } + let text = item.plain_text().map(str::to_owned).or_else(|| item.paths().first().map(|f| native(f))); + if let Some(text) = text { + let units: Vec<u16> = text.encode_utf16().chain([0]).collect(); + set(&data, CF_UNICODETEXT.0, hglobal(std::slice::from_raw_parts(units.as_ptr().cast(), units.len() * 2))?); + } + if let Ok(helper) = CoCreateInstance::<_, IDragSourceHelper>(&CLSID_DragDropHelper, None, CLSCTX_INPROC_SERVER) { + let picture = p.picture.as_ref().and_then(|pic| drag_image(pic, &p.start, p.scale)); + match picture { + Some(shdi) => if helper.InitializeFromBitmap(&shdi, &data).is_err() { windows_sys::Win32::Graphics::Gdi::DeleteObject(shdi.hbmpDragImage.0); }, + // The shell's own picture of the files, under the pointer. + None if !item.paths().is_empty() => { helper.InitializeFromWindow(None, None, &data).ok(); } + None => {} + } + } + let within_app = item.drops_within_app(); + if !within_app { crate::platform::win32::drop_target::mute(true); } + let source: IDropSource = Source.into(); + let mut effect = DROPEFFECT_NONE; + let result = DoDragDrop(&data, &source, effects(item), &mut effect); + if !within_app { crate::platform::win32::drop_target::mute(false); } + Some(if result == DRAGDROP_S_DROP { outcome(effect) } else { DragOutcome::Cancelled }) + } +} + +/// The shell's data object for the files (their folder's items, when they share one), else an +/// empty one; the shell's takes any format `SetData` gives it, which the drag image needs. +unsafe fn data_object(item: &DragItem) -> Option<IDataObject> { + // SAFETY: each ID list made here is freed before returning; the data object copies them. + unsafe { + let full: Vec<*mut ITEMIDLIST> = item.paths().iter().map(|f| ILCreateFromPathW(PCWSTR(wide(&native(f)).as_ptr()))).collect(); + let shell = if !full.is_empty() && full.iter().all(|p| !p.is_null()) { + let parent = ILClone(full[0]); + let ok = !parent.is_null() && ILRemoveLastID(Some(parent)).as_bool() && full.iter().all(|&f| ILIsParent(parent, f, true).as_bool()); + let children: Vec<*const ITEMIDLIST> = full.iter().map(|&f| ILFindLastID(f) as *const _).collect(); + let data = ok.then(|| SHCreateDataObject::<_, IDataObject>(Some(parent), Some(&children), None).ok()).flatten(); + if !parent.is_null() { ILFree(Some(parent)); } + data + } else { None }; + for f in full.into_iter().filter(|p| !p.is_null()) { ILFree(Some(f)); } + if let Some(data) = shell { return Some(data); } + let data = SHCreateDataObject::<_, IDataObject>(None, None, None).ok()?; + if !item.paths().is_empty() { set(&data, CF_HDROP.0, drop_files(item)?); } + Some(data) + } +} + +/// A `CF_HDROP` medium: `DROPFILES` and the paths, each NUL-terminated, then one more NUL. +fn drop_files(item: &DragItem) -> Option<HGLOBAL> { + let mut units: Vec<u16> = item.paths().iter().flat_map(|f| native(f).encode_utf16().chain([0]).collect::<Vec<_>>()).collect(); + units.push(0); + // DROPFILES: pFiles, pt, fNC, fWide. + let header: [u32; 5] = [20, 0, 0, 0, 1]; + let mut bytes: Vec<u8> = header.iter().flat_map(|v| v.to_le_bytes()).collect(); + bytes.extend(units.iter().flat_map(|u| u.to_le_bytes())); + hglobal(&bytes) +} + +fn hglobal(bytes: &[u8]) -> Option<HGLOBAL> { + use windows_sys::Win32::System::Memory::{GMEM_MOVEABLE, GlobalAlloc, GlobalLock, GlobalUnlock}; + // SAFETY: a new movable block of the bytes' size, filled while locked. + unsafe { + let h = GlobalAlloc(GMEM_MOVEABLE, bytes.len().max(1)); + if h.is_null() { return None; } + let p = GlobalLock(h); + if p.is_null() { return None; } + std::ptr::copy_nonoverlapping(bytes.as_ptr(), p.cast(), bytes.len()); + GlobalUnlock(h); + Some(HGLOBAL(h)) + } +} + +/// Hands `medium` to `data` as `format`; the data object owns it from then on. +unsafe fn set(data: &IDataObject, format: u16, medium: HGLOBAL) { + let format = FORMATETC { cfFormat: format, ptd: std::ptr::null_mut(), dwAspect: DVASPECT_CONTENT.0, lindex: -1, tymed: TYMED_HGLOBAL.0 as u32 }; + let medium = STGMEDIUM { tymed: TYMED_HGLOBAL.0 as u32, u: STGMEDIUM_0 { hGlobal: medium }, pUnkForRelease: std::mem::ManuallyDrop::new(None) }; + // SAFETY: a valid format and an HGLOBAL medium the call takes ownership of. + unsafe { data.SetData(&format, &medium, true).ok(); } +} + +fn png_format() -> u16 { + static PNG: OnceLock<u16> = OnceLock::new(); + // SAFETY: the name is NUL-terminated. + *PNG.get_or_init(|| unsafe { windows_sys::Win32::System::DataExchange::RegisterClipboardFormatW(wide("PNG").as_ptr()) as u16 }) +} + +/// The picture as the drag image manager takes it: a top-down 32-bit DIB of premultiplied BGRA, +/// with where the pointer sits in it. +fn drag_image(picture: &DragImage, start: &DragOutStart, scale: f32) -> Option<SHDRAGIMAGE> { + let rgba = crate::image::png_rgba8(picture.png_data()).ok()?; + let (w, h) = (rgba.width() as i32, rgba.height() as i32); + let [fx, fy, fw, fh] = picture.frame(start.bounds, start.press, (w as f32 / scale, h as f32 / scale)); + let offset = POINT { + x: (((start.press.0 - fx) / fw.max(1.0)) * w as f32).round().clamp(0.0, w as f32) as i32, + y: (((start.press.1 - fy) / fh.max(1.0)) * h as f32).round().clamp(0.0, h as f32) as i32, + }; + use windows_sys::Win32::Graphics::Gdi::{BI_RGB, BITMAPINFO, BITMAPINFOHEADER, CreateDIBSection, DIB_RGB_COLORS}; + // SAFETY: a plain C struct, all zeroes valid. + let mut info: BITMAPINFO = unsafe { std::mem::zeroed() }; + info.bmiHeader = BITMAPINFOHEADER { biSize: size_of::<BITMAPINFOHEADER>() as u32, biWidth: w, biHeight: -h, biPlanes: 1, biBitCount: 32, biCompression: BI_RGB, biSizeImage: 0, biXPelsPerMeter: 0, biYPelsPerMeter: 0, biClrUsed: 0, biClrImportant: 0 }; + let mut bits: *mut std::ffi::c_void = std::ptr::null_mut(); + // SAFETY: a DIB section of w x h 32-bit pixels, which `bits` then points into. + let bitmap = unsafe { CreateDIBSection(std::ptr::null_mut(), &info, DIB_RGB_COLORS, &mut bits, std::ptr::null_mut(), 0) }; + if bitmap.is_null() || bits.is_null() { return None; } + // SAFETY: the section holds exactly w * h * 4 bytes. + let out = unsafe { std::slice::from_raw_parts_mut(bits.cast::<u8>(), (w * h * 4) as usize) }; + for (o, p) in out.chunks_exact_mut(4).zip(rgba.pixels()) { + let a = u32::from(p[3]); + let pre = |c: u8| ((u32::from(c) * a + 127) / 255) as u8; + o.copy_from_slice(&[pre(p[2]), pre(p[1]), pre(p[0]), p[3]]); + } + Some(SHDRAGIMAGE { sizeDragImage: SIZE { cx: w, cy: h }, ptOffset: offset, hbmpDragImage: HBITMAP(bitmap), crColorKey: windows::Win32::Foundation::COLORREF(0xFFFF_FFFF) }) +} + +fn effects(item: &DragItem) -> DROPEFFECT { + [(DragOperation::Copy, DROPEFFECT_COPY), (DragOperation::Move, DROPEFFECT_MOVE), (DragOperation::Link, DROPEFFECT_LINK)] + .into_iter().filter(|&(op, _)| item.offers(op)).fold(DROPEFFECT_NONE, |m, (_, e)| m | e) +} + +fn outcome(effect: DROPEFFECT) -> DragOutcome { + if effect.0 & DROPEFFECT_COPY.0 != 0 { DragOutcome::Copied } + else if effect.0 & DROPEFFECT_MOVE.0 != 0 { DragOutcome::Moved } + else if effect.0 & DROPEFFECT_LINK.0 != 0 { DragOutcome::Linked } + else { DragOutcome::Cancelled } +} + +fn wide(s: &str) -> Vec<u16> { s.encode_utf16().chain([0]).collect() } + +/// A path as the shell parses it: backslashes. +fn native(path: &std::path::Path) -> String { path_text(path).replace('/', "\\") } + +/// Ends the drag when the left button comes up, cancels it on Escape; the system's cursors. +#[implement(IDropSource)] +struct Source; + +impl IDropSource_Impl for Source_Impl { + fn QueryContinueDrag(&self, escape: BOOL, keys: MODIFIERKEYS_FLAGS) -> HRESULT { + if escape.as_bool() { return DRAGDROP_S_CANCEL; } + if keys.0 & MK_LBUTTON.0 == 0 { return DRAGDROP_S_DROP; } + S_OK + } + + fn GiveFeedback(&self, _: DROPEFFECT) -> HRESULT { DRAGDROP_S_USEDEFAULTCURSORS } +} diff --git a/app/vendor/rune/crates/rune/src/el.rs b/app/vendor/rune/crates/rune/src/el.rs new file mode 100644 index 0000000..5f0f296 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/el.rs @@ -0,0 +1,432 @@ +//! The element tree that view functions return. Plain data plus type-erased handlers. + +use std::rc::Rc; + +use rune_motion::{Anim, Spring, Transition}; +use rune_taffy::prelude::*; + +use crate::color::Color; +use crate::edit::TextEdit; +use crate::growth::{GROWTH, StreamEdge, edge}; +use crate::shape::Shape; +use crate::states::{downcast, edit_fn}; +use crate::text::{Icon, Link, Span}; +use crate::tok::TextStyle; + +mod a11y; +mod anchor; +mod backdrop; +mod child_exit; +mod direction; +pub(crate) mod drop; +pub(crate) mod effect; +mod element_info; +mod enter_delay; +mod focus; +pub(crate) mod grid; +mod growth; +mod handler_set; +mod handlers; +mod help; +mod input; +mod isolates; +mod layout; +pub(crate) mod layout_watch; +mod live_colors; +pub mod motion; +mod paragraphs; +mod pills; +mod pixel_snap; +mod rare; +mod ride_trailing; +mod scroll; +mod selection_style; +mod sticky; +mod text; +mod text_spec; +mod tx; +pub(crate) mod virtual_list; +pub(crate) mod virtual_rows; +mod visual; +mod visuals; + +pub use a11y::LiveRegion; +pub(crate) use a11y::{A11y, Checked}; +pub use anchor::{Anchor, Side, anchor_rect}; +pub(crate) use crate::clipboard::tx::{ClipboardRead, ReadFn}; +pub use crate::cursor::{Cursor, CursorImage}; +pub use direction::Direction; +pub(crate) use direction::{DirEffect, DirEvent, Flow, Pin, mirror_anchor, mirror_side, mirror_visual, step as step_direction}; +pub(crate) use drop::{DropHoverFn, DropSpec}; +pub(crate) use focus::FocusSpec; +pub(crate) use focus::ModalSpec; +pub(crate) use handler_set::Handlers; +pub use grid::{GridRow, grid}; +pub use handlers::{Drag, Phase, PointerEvent, PointerPress}; +pub(crate) use handlers::{DragEndFn, DragFn, DragOutFn, InputKeyFn, PointerFn, PressFn, StepFn, StepLimitFn, WindowDrag}; +pub(crate) use help::{HELP_KEY, HELP_ROW, help_words}; +pub use input::{InputSpec, auto_grow, edit_access, text_input}; +pub use pills::{InlineIcon, InlineImage}; +pub(crate) use rare::{ElCold, ElFlags, RoleTag}; +pub use rune_motion::Cycle; +pub(crate) use scroll::FadeStyle; +pub use scroll::ScrollFade; +pub use scroll::ScrollSpec; +pub(crate) use scroll::{AtBottomFn, ScrollAxes, ScrollEdges, VisibleRowsFn}; +pub use selection_style::SelectionStyle; +pub(crate) use sticky::{Sticky, StickyEdge}; +pub(crate) use text_spec::{Elide, TextDir, TextDirEvent, step_text_dir}; +pub use text_spec::TextSpec; +pub(crate) use tx::{Commit, FocusAsk, MotionSource, SelectRequest, TraceCalls}; +pub use tx::{Shell, Tx}; +pub(crate) use visual::VisualFlags; +pub use visual::{Visual, VisualCold}; +pub(crate) use visuals::{GradientGeometry, RadialGradient}; +pub use visuals::{Outline, RadialRadius, Shadow}; + +/// An effect slot (`El::effect`): size it like any box. +pub fn effect(mark: u32) -> El { + base(FlexDirection::Row).effect(mark) +} + +pub fn text(content: impl Into<String>) -> El { + let mut e = base(FlexDirection::Row); + e.role = RoleTag::TEXT; + e.text = Some(crate::cold::SharedBox::new(TextSpec::new(content.into()))); + e +} + +pub(crate) type EditFn = Rc<dyn for<'a> Fn(crate::states::States<'a>) -> &'a mut TextEdit>; + +/// A growth stack (the session timeline): children are rows whose heights ease on `spring` +/// with per-second speed limits; positions derive from the presented heights above. Rows an +/// animated commit puts in a new order slide from where they were drawn into their new places. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct GrowthSpec { + pub spring: Spring, + pub edge: StreamEdge, +} + +impl Default for GrowthSpec { + fn default() -> Self { + GrowthSpec { spring: GROWTH, edge: edge::FEATHER } + } +} + +/// The selection highlight until [`El::selection_color`] or [`El::caret`] sets one. +pub(crate) const DEFAULT_SELECTION: Color = Color { r: 1.0, g: 1.0, b: 1.0, a: 0.2 }; + +pub use rune_image::Align; + +/// [`El::on_link`]'s handler. +#[derive(Clone)] +pub(crate) struct LinkFn(pub LinkHandler); +pub(crate) type LinkHandler = Rc<dyn Fn(crate::states::States<'_>, &str, &mut Tx)>; + +impl std::fmt::Debug for LinkFn { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("LinkFn") + } +} +/// [`El::on_link_secondary`]'s handler. +#[derive(Clone)] +pub(crate) struct LinkSecondaryFn(pub Rc<dyn Fn(crate::states::States<'_>, &str, PointerPress, &mut Tx)>); +impl std::fmt::Debug for LinkSecondaryFn { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.write_str("LinkSecondaryFn") } +} + +/// Default `truncate_fade` edge, in ems. +pub(crate) const TRUNCATE_FADE_EM: f32 = 1.5; + +/// A root paste handler; `rich` is true only for [`El::on_paste_content`], so a plain +/// [`El::on_paste`] never asks the OS clipboard for HTML or RTF. +#[derive(Clone)] +pub(crate) struct PasteFn { + pub(crate) rich: bool, + pub(crate) call: InputPasteFn, +} +/// A pill's leading icon by its id; see [`El::pill_icon`]. +pub(crate) type PillIconFn = Rc<dyn Fn(&str) -> Option<&'static crate::Icon>>; +/// A pill's look by its id; see [`El::pill_style`]. +pub(crate) type PillStyleFn = Rc<dyn Fn(&str) -> PillStyle>; +pub(crate) type PillSecondaryFn = Rc<dyn Fn(crate::states::States<'_>, &str, PointerPress, &mut Tx) -> bool>; + +/// How one [`Mark::Pill`](crate::Mark::Pill) chip looks: any part left unset falls back to +/// [`El::pill_colors`] and [`El::pill_icon`], then the field's defaults. Build one with +/// `PillStyle::default().bg(..).icon(..)`. +#[derive(Clone, Copy, Debug, Default)] +pub struct PillStyle { + pub(crate) bg: Option<Color>, + pub(crate) fg: Option<Color>, + pub(crate) icon: Option<&'static crate::Icon>, +} + +impl PillStyle { + pub const fn new() -> Self { + Self { bg: None, fg: None, icon: None } + } + /// The chip's colour. + pub const fn bg(mut self, bg: Color) -> Self { + self.bg = Some(bg); + self + } + /// The label and icon colour. + pub const fn fg(mut self, fg: Color) -> Self { + self.fg = Some(fg); + self + } + /// The leading icon, in the label's colour. + pub const fn icon(mut self, icon: &'static crate::Icon) -> Self { + self.icon = Some(icon); + self + } +} +pub(crate) type InputPasteFn = Rc<dyn Fn(crate::states::States<'_>, &crate::ClipboardContent, &mut Tx) -> bool>; +pub(crate) type PickFn = Box<dyn FnOnce(crate::states::States<'_>, Option<crate::Picked>, &mut Tx)>; + +#[derive(Clone)] +pub(crate) struct PickRead { + pub within: Option<String>, + pub x: f32, + pub y: f32, + pub pick: crate::Pick, + pub(crate) f: Rc<std::cell::Cell<Option<PickFn>>>, +} +impl PickRead { + pub fn take(&self) -> Option<PickFn> { self.f.take() } +} +impl std::fmt::Debug for PickRead { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.write_str("PickRead") } +} + +/// What an `El::selection_copy` element copies for a selection inside it. +pub(crate) type SelectionCopy = Rc<dyn Fn(&crate::TextSelection) -> Option<String>>; +/// `El::on_selection_change`. +pub(crate) type SelectionChangeFn = Rc<dyn Fn(crate::states::States<'_>, &crate::SelectionChange, &mut Tx)>; + +pub(crate) type LayoutFn = Rc<dyn Fn(crate::states::States<'_>, [f32; 4])>; +pub(crate) type LayoutTxFn = Rc<dyn Fn(crate::states::States<'_>, [f32; 4], &mut Tx)>; +pub(crate) type ScrollOffsetFn = Rc<dyn Fn(crate::ScrollPos)>; +pub(crate) type WindowFocusFn = Rc<dyn Fn(crate::states::States<'_>, bool, &mut Tx)>; +pub(crate) type LanguagesFn = Rc<dyn Fn(crate::states::States<'_>, Vec<String>, &mut Tx)>; + +/// An element: layout, paint, children and handlers. Hot fields sit inline in three cache lines; +/// the rest wait behind `cold`, allocated on the first write. +#[derive(Clone)] +pub struct El { + pub(crate) style: CompactStyle, + pub(crate) vis: Visual, + pub(crate) children: Vec<El>, + pub(crate) key: Option<String>, + pub(crate) text: Option<crate::cold::SharedBox<TextSpec>>, + pub(crate) handlers: crate::cold::Cold<Handlers>, + /// The cached [`memo`](crate::memo) subtree this placeholder came from. Its children come + /// before `children`; once the placeholder is expanded or given extra children, + /// `ElFlags::MEMO_EXTENDED` says it is no longer that subtree itself. + pub(crate) memo: Option<Rc<crate::memo::Built>>, + pub(crate) cold: crate::cold::Cold<ElCold>, + pub(crate) scale: f32, + pub(crate) flags: ElFlags, + pub(crate) role: RoleTag, + pub(crate) vis_flags: VisualFlags, + #[cfg(debug_assertions)] + pub(crate) key_source: Option<&'static std::panic::Location<'static>>, +} + +#[cfg(all(target_pointer_width = "64", not(debug_assertions)))] +const _: () = assert!(std::mem::size_of::<El>() == 192); +#[cfg(all(target_pointer_width = "64", not(debug_assertions)))] +const _: () = assert!(std::mem::size_of::<Option<El>>() == 192); +#[cfg(target_pointer_width = "64")] +const _: () = assert!(std::mem::size_of::<Visual>() == 40); + +#[inline] +fn base(dir: FlexDirection) -> El { + El { + // Relative makes every element the containing block for its absolute children, so they + // size and pin against their parent's padding box. Taffy's default (static) hands them + // to the window instead, as CSS does. + style: CompactStyle::rune_base(dir), + vis: Visual::default(), + children: Vec::new(), + key: None, + text: None, + handlers: crate::cold::Cold::NONE, + memo: None, + cold: crate::cold::Cold::NONE, + scale: 1.0, + flags: ElFlags::default(), + role: RoleTag::GROUP, + vis_flags: VisualFlags::default(), + #[cfg(debug_assertions)] + key_source: None, + } +} + +#[inline] +pub fn row() -> El { + base(FlexDirection::Row) +} + +#[inline] +pub fn col() -> El { + base(FlexDirection::Column) +} + +/// A plain box. +#[inline] +pub fn el() -> El { + base(FlexDirection::Row) +} + +/// Takes the free space along its parent's main axis. +#[inline] +pub fn spacer() -> El { + base(FlexDirection::Row).grow(1.0) +} + +/// A 1 pt horizontal divider scaled vertically by half at paint time (`height: 1px; transform: +/// scaleY(0.5)`), matching Chromium's sub-pixel hairline coverage at 1x, 1.5x and 2x while taking +/// 1 pt of layout height. +pub fn hairline(c: Color) -> El { + el().h(1.0).fill(c).hairline() +} + +/// A horizontal rule as a CSS `border-top: <width>px` on an empty box draws and lays out: its +/// width snapped to device pixels as a border's is (one whole pixel under a pixel), and that +/// many pixels of room in its column. So `rule(0.5, c)` between two rows takes 1 point at 1x, +/// 0.8 at 1.25x and 0.667 at 1.5x, where `el().h(0.5)` takes 0.5 at every scale, and a list of +/// rows split by Desktop's `border-bottom: 0.5px` ends where Chromium's does. It stretches +/// across its column; give it `w_full` or margins as a `<div>` takes them. +pub fn rule(width: f32, c: Color) -> El { + base(FlexDirection::Row).border_sides([width, 0.0, 0.0, 0.0], c).border_layout() +} + +/// Text with styled byte ranges; wraps at its width. +pub fn rich(content: impl Into<String>, spans: Vec<Span>) -> El { + let mut e = text(content); + if let Some(t) = &mut e.text { + t.spans = if spans.len() <= 1 || spans.windows(2).all(|w| w[0].start < w[0].end && w[0].end <= w[1].start) { + spans + } else { + crate::text::flatten_spans(&spans) + }; + t.wrap = true; + } + e +} + +/// An SVG icon from a catalog, `size` points square (or what [`crate::text::set_icon_swap_size`] +/// gives a swapped icon), tinted with `.color()`. +pub fn icon(i: &'static Icon, size: f32) -> El { + let size = crate::text::icon::swapped_size(i, size); + let mut e = base(FlexDirection::Row).size(size, size); + e.role = RoleTag::ICON; + e.vis.cold_mut().icon = Some((i, Color::WHITE)); + e +} + +/// An element that paints `shape`; size it like any element. +pub fn canvas(shape: Shape) -> El { + let mut e = base(FlexDirection::Row).shape(shape); + e.role = RoleTag::IMAGE; + e +} + +impl El { + + /// Bind opacity directly to a latest-wins value, without rebuilding or laying out the view. + pub fn live_opacity(mut self, value: impl Into<crate::live::Binding<f32>>) -> Self { + self.bind_live(crate::live::Bound::new(value, crate::live::Property::Opacity)); self + } + + /// Bind a subtree's Gaussian blur (sigma in points), optionally smoothed with `Live::smooth`. + pub fn live_blur(mut self, value: impl Into<crate::live::Binding<f32>>) -> Self { + self.bind_live(crate::live::Bound::new(value, crate::live::Property::Blur)); + self + } + /// Bind an additive parent-space offset in points. Descendants and hit tests follow it. + pub fn live_offset(mut self, value: impl Into<crate::live::Binding<[f32; 2]>>) -> Self { + self.bind_live(crate::live::Bound::new(value, crate::live::Property::Offset)); self + } + /// Bind uniform scale around the node's centre; layout remains at its target size. Text, + /// icons and images in the subtree scale with it, as under [`El::scale`]. Text rasterizes + /// at the scale rounded to 1/32, so a dragged value doesn't fill the glyph atlas. + pub fn live_scale(mut self, value: impl Into<crate::live::Binding<f32>>) -> Self { + self.bind_live(crate::live::Bound::new(value, crate::live::Property::Scale)); self + } + /// Bind the [start, end] span of a shape's strokes that draws, as fractions (0 to 1) of + /// their combined length, as [`Shape::trimmed`](crate::Shape::trimmed) cuts them. A + /// [`Tween`](crate::Tween) runs a countdown ring or a travelling dash without rebuilding. + pub fn live_trim(mut self, value: impl Into<crate::live::Binding<[f32; 2]>>) -> Self { + self.bind_live(crate::live::Bound::new(value, crate::live::Property::Trim)); self + } + pub fn live_fill(mut self, value: impl Into<crate::live::Binding<Color>>) -> Self { + self.bind_live(crate::live::Bound::new(value, crate::live::Property::Fill)); self + } + /// Bind presentation [x, y, width, height] in parent points. Does not reflow siblings or + /// rewrap text; use ordinary layout for those changes. Width/height clamp at zero. + pub fn live_rect(mut self, value: impl Into<crate::live::Binding<[f32; 4]>>) -> Self { + self.bind_live(crate::live::Bound::new(value, crate::live::Property::Rect)); self + } + fn bind_live(&mut self, bound: crate::live::Bound) { + if let Some(old) = self.cold_mut().live.iter_mut().find(|b| b.property == bound.property) { *old = bound; } + else { self.cold_mut().live.push(bound); } + } + + pub(crate) fn key_location(&self) -> String { + #[cfg(debug_assertions)] + if let Some(source) = self.key_source { return source.to_string(); } + "unknown (build with debug assertions for source locations)".into() + } + + /// Identity among siblings. Siblings need unique keys: when two share one, the first keeps + /// it, each later one is renamed `key#dup1`, `key#dup2`, ... and Rune prints a warning naming + /// both call sites once per key. + #[cfg_attr(debug_assertions, track_caller)] + #[inline] + pub fn key(mut self, key: impl Into<String>) -> Self { + self.set_key(key); + self + } + /// [`El::key`] in place. + #[cfg_attr(debug_assertions, track_caller)] + #[inline] + pub fn set_key(&mut self, key: impl Into<String>) -> &mut Self { + self.key = Some(key.into()); + #[cfg(debug_assertions)] + { self.key_source = Some(std::panic::Location::caller()); } + self + } + #[inline] + pub fn child(mut self, child: El) -> Self { + self.push_child(child); + self + } + /// [`El::child`] in place. + #[inline] + pub fn push_child(&mut self, child: El) -> &mut Self { + self.flags.set(ElFlags::MEMO_EXTENDED, self.memo.is_some()); + if child.flags.has(ElFlags::HAS_VIRTUAL) { + self.flags.set(ElFlags::HAS_VIRTUAL, true); + } + self.children.push(child); + self + } + #[inline] + pub fn children(mut self, children: impl IntoIterator<Item = El>) -> Self { + self.extend_children(children); + self + } + /// [`El::children`] in place. + #[inline] + pub fn extend_children(&mut self, children: impl IntoIterator<Item = El>) -> &mut Self { + self.flags.set(ElFlags::MEMO_EXTENDED, self.memo.is_some()); + let start = self.children.len(); + self.children.extend(children); + if self.children[start..].iter().any(|c| c.flags.has(ElFlags::HAS_VIRTUAL)) { + self.flags.set(ElFlags::HAS_VIRTUAL, true); + } + self + } +} diff --git a/app/vendor/rune/crates/rune/src/el/a11y.rs b/app/vendor/rune/crates/rune/src/el/a11y.rs new file mode 100644 index 0000000..5537f2a --- /dev/null +++ b/app/vendor/rune/crates/rune/src/el/a11y.rs @@ -0,0 +1,305 @@ +//! What an element tells assistive technology beyond its role and label: description, value, +//! state, live updates and its place in a set. Screen readers, Voice Control and automation +//! tools read it through the OS accessibility tree (`crate::a11y`). + +use std::borrow::Cow; +use crate::El; + +/// How assistive technology announces changes to an element's text ([`El::live_region`]), as ARIA's +/// `aria-live`. Role `"status"` is polite and `"alert"` assertive unless set. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] +pub enum LiveRegion { + /// Changes aren't announced. + #[default] + Off, + /// Announced when the user is idle: a status line, a saved notice. + Polite, + /// Announced at once, interrupting: an error. + Assertive, +} + +/// A checkbox's, switch's or toggle button's state for accessibility ([`El::checked`]). +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub(crate) enum Checked { + False, + True, + Mixed, +} + +/// A range control's value ([`El::range_value`]). +#[derive(Clone, Copy, Debug, PartialEq)] +pub(crate) struct Range { + pub value: f64, + pub min: f64, + pub max: f64, + pub step: Option<f64>, +} + +/// The rarer accessibility properties, boxed so an element without them stays small. +#[derive(Clone, Debug, Default, PartialEq)] +pub(crate) struct A11yMore { + pub description: Option<Cow<'static, str>>, + pub value: Option<String>, + pub range: Option<Range>, + /// 1-based position and the set's size. + pub set: Option<(usize, usize)>, + pub shortcut: Option<String>, + /// `El::active_descendant`'s key. + pub active: Option<String>, + pub invalid: bool, + pub read_only: bool, + /// `El::sorted`: ascending or descending. + pub sorted: Option<bool>, + /// `El::href`: the URL this element links to. + pub href: Option<String>, + /// `El::labelled_by`'s key. + pub labelled_by: Option<Cow<'static, str>>, + /// `El::described_by`'s key. + pub described_by: Option<Cow<'static, str>>, + /// `El::busy`. + pub busy: bool, +} + +/// Accessibility state beyond role and label (`El::level`, `El::expanded`, `El::secure`, and +/// this file's builders). +#[derive(Clone, Debug, Default, PartialEq)] +pub(crate) struct A11y { + pub level: Option<u32>, + pub expanded: Option<bool>, + pub secure: bool, + pub checked: Option<Checked>, + pub disabled: bool, + pub hidden: bool, + /// `El::unselectable`: a web page's mirror leaves this subtree's text out of the selection. + pub unselectable: bool, + pub live: Option<LiveRegion>, + pub more: Option<Box<A11yMore>>, +} + +impl A11y { + pub(crate) const EMPTY: A11y = A11y { + level: None, expanded: None, secure: false, checked: None, disabled: false, hidden: false, unselectable: false, + live: None, more: None, + }; + + fn more(&mut self) -> &mut A11yMore { + self.more.get_or_insert_with(Default::default) + } +} + +impl El { + /// Make this element a link to `url`, as an HTML `<a href>` is: its role is `"link"`, a + /// press opens `url` with [`Tx::open_url`](crate::Tx::open_url), and on web the semantic + /// mirror puts a real `<a href>` over it, so middle-click, ⌘-click, "Copy Link", the + /// keyboard and crawlers treat it as one. A static page export (`--html`) writes it as one + /// too. `url` may be relative to the page (`/docs`) or a fragment (`#install`); natively + /// those don't open. Its label is its text unless [`El::label`] sets one. + pub fn href(mut self, url: impl Into<String>) -> Self { + let url = url.into(); + self.cold_mut().a11y.more().href = Some(url.clone()); + self.set_role_name("link"); + self.handlers.on_press = Some(std::rc::Rc::new(move |_, tx: &mut crate::Tx| { + if url.contains(':') { tx.open_url(&url).ok(); } + })); + self + } + + /// The URL [`El::href`] set. + pub fn link_url(&self) -> Option<&str> { + self.cold.a11y.more.as_ref()?.href.as_deref() + } + + /// A longer explanation than the label, read after it (ARIA `aria-description`): what a + /// setting does, or the shortcut a button has. The label stays short. Without one, an + /// [`El::help`] tooltip describes the element; `description("")` turns that off. + pub fn description(mut self, text: impl Into<String>) -> Self { + self.cold_mut().a11y.more().description = Some(Cow::Owned(text.into())); + self + } + /// [`El::description`] from a string that lives for the program (a translated message, a + /// literal): kept as it is, with nothing copied, so a view that runs every frame pays + /// nothing for it. + pub fn description_static(mut self, text: &'static str) -> Self { + self.cold_mut().a11y.more().description = Some(Cow::Borrowed(text)); + self + } + /// The element whose content is active while this one keeps keyboard focus (ARIA + /// `aria-activedescendant`): the highlighted row of a tree, table or suggestion list whose + /// container or search field holds focus. `key` names it as `Cx::layout` does; an empty + /// one names none, and costs nothing. + pub fn active_descendant(mut self, key: impl Into<String>) -> Self { + let key = key.into(); + if key.is_empty() { + return self; + } + self.cold_mut().a11y.more().active = Some(key); + self + } + /// The element whose text names this one (ARIA `aria-labelledby`): a setting's title for + /// its switch, a dialog's heading for the dialog. `key` names it as `Cx::layout` does, and the + /// nearest element with that key counts: the first inside this one's parent, else inside its + /// grandparent, and so on, so a component's controls can all name their own `"title"`. A label + /// set with [`El::label`] wins. + pub fn labelled_by(mut self, key: impl Into<String>) -> Self { + self.cold_mut().a11y.more().labelled_by = Some(Cow::Owned(key.into())); + self + } + /// The element whose text describes this one (ARIA `aria-describedby`): a setting's + /// explanation for its switch, a dialog's message for the dialog. + pub fn described_by(mut self, key: impl Into<String>) -> Self { + self.cold_mut().a11y.more().described_by = Some(Cow::Owned(key.into())); + self + } + /// The element is still changing and a reader should wait for it to settle (ARIA + /// `aria-busy`): a turn while the reply streams, a tool call while it runs. + pub fn busy(mut self, busy: bool) -> Self { + if busy || self.cold.a11y.more.is_some() { self.cold_mut().a11y.more().busy = busy; } + self + } + /// Whether the value entered here fails validation (ARIA `aria-invalid`). + pub fn invalid(mut self, invalid: bool) -> Self { + self.cold_mut().a11y.more().invalid = invalid; + self + } + /// A control whose value can be read but not changed now (ARIA `aria-readonly`): a + /// checklist shown in a finished document. + pub fn read_only(mut self, read_only: bool) -> Self { + self.cold_mut().a11y.more().read_only = read_only; + self + } + /// How a column header sorts its table: `Some(true)` ascending, `Some(false)` descending + /// (ARIA `aria-sort`). + pub fn sorted(mut self, ascending: Option<bool>) -> Self { + self.cold_mut().a11y.more().sorted = ascending; + self + } + /// The value assistive technology reads for a control whose value isn't its text: a + /// picker's chosen item, a colour well's colour, a step counter's "3 of 5". Text fields + /// report their text and range controls their number without it. + pub fn a11y_value(mut self, text: impl Into<String>) -> Self { + self.cold_mut().a11y.more().value = Some(text.into()); + self + } + /// A slider's or progress bar's number, between `min` and `max` (ARIA `aria-valuenow`, + /// `aria-valuemin` and `aria-valuemax`). Assistive technology increments it through + /// [`El::on_step`]. + pub fn range_value(mut self, value: f64, min: f64, max: f64) -> Self { + let step = self.cold.a11y.more.as_ref().and_then(|m| m.range).and_then(|r| r.step); + self.cold_mut().a11y.more().range = Some(Range { value, min, max, step }); + self + } + /// The amount one step of [`El::on_step`] moves a [`range_value`](Self::range_value). + pub fn range_step(mut self, step: f64) -> Self { + let more = self.cold_mut().a11y.more(); + let range = more.range.get_or_insert(Range { value: 0.0, min: 0.0, max: 0.0, step: None }); + range.step = Some(step); + self + } + /// Whether a checkbox, switch, radio button or toggle button is on (ARIA `aria-checked` + /// or `aria-pressed`). Leave it unset on controls that can't be. + pub fn checked(mut self, on: bool) -> Self { + self.cold_mut().a11y.checked = Some(if on { Checked::True } else { Checked::False }); + self + } + /// A checkbox that is partly on: some of what it controls is (ARIA `aria-checked="mixed"`). + pub fn checked_mixed(mut self) -> Self { + self.cold_mut().a11y.checked = Some(Checked::Mixed); + self + } + /// A control that can't be used now: assistive technology reads it as dimmed. It also + /// stops it taking focus; leave its press handler off as well. + pub fn disabled(mut self, disabled: bool) -> Self { + if disabled || !self.cold.is_empty() { + let cold = self.cold_mut(); + cold.a11y.disabled = disabled; + if disabled { let f = &mut *cold.focus; f.enabled = false; f.opt_out = true; } + } + self + } + /// Leave this element and everything inside it out of the accessibility tree: decoration, + /// or a duplicate of what another element already says. It still draws and takes input. + pub fn a11y_hidden(mut self) -> Self { + self.cold_mut().a11y.hidden = true; + self + } + /// Keep the text in this element and everything inside it out of a web page's selection + /// (CSS `user-select: none`). A page ([`App::web_document`](crate::App::web_document)) lets + /// people select and copy its text as any web page does, except text inside something that + /// takes the pointer: a press, drag or gesture handler, a button, link or field. Use this + /// for other text that shouldn't select, such as a wordmark drawn as text. + /// [`El::selectable`] text inside still selects. Outside a web page it changes nothing. + pub fn unselectable(mut self) -> Self { + self.cold_mut().a11y.unselectable = true; + self + } + /// How changes to this element's text are announced (ARIA `aria-live`), for status text + /// that updates while the user does something else. + pub fn live_region(mut self, live: LiveRegion) -> Self { + self.cold_mut().a11y.live = Some(live); + self + } + /// This element's place in its set, 1-based, and the set's size (ARIA `aria-posinset` and + /// `aria-setsize`): a row of a list that builds only some of its rows says where it is. + /// Rows of `virtual_rows` and `virtualize` lists get it without this. + pub fn position_in_set(mut self, position: usize, size: usize) -> Self { + self.cold_mut().a11y.more().set = Some((position, size)); + self + } + /// The keyboard shortcut that does what this control does, as the platform writes it + /// (`"Ctrl+S"`, `"⌘S"`), for assistive technology to read. + pub fn shortcut_hint(mut self, keys: impl Into<String>) -> Self { + self.cold_mut().a11y.more().shortcut = Some(keys.into()); + self + } +} + +impl El { + /// The element's accessible role. `"textbox"` on a container also makes a press anywhere + /// on it (padding, a leading icon, a trailing label) focus its one reachable text editor and + /// place the caret at the nearer end, without blurring a focused field or dragging the + /// window; buttons and other controls inside keep their own presses. With zero or more + /// than one reachable editor inside, the container does nothing special. + #[inline] + pub fn role(mut self, role: &'static str) -> Self { + self.set_role(role); + self + } + /// [`El::role`] in place. + #[inline] + pub fn set_role(&mut self, role: &'static str) -> &mut Self { + self.set_role_name(role); + self + } + #[inline] + pub fn label(mut self, label: impl Into<String>) -> Self { + self.set_label(label); + self + } + /// [`El::label`] from a string that lives for the program (a translated message, a + /// literal): kept as it is, with nothing copied, so a view that runs every frame pays + /// nothing for its names. + #[inline] + pub fn label_static(mut self, label: &'static str) -> Self { + self.cold_mut().label = Some(Cow::Borrowed(label)); + self + } + /// [`El::label`] in place. + #[inline] + pub fn set_label(&mut self, label: impl Into<String>) -> &mut Self { + self.cold_mut().label = Some(Cow::Owned(label.into())); + self + } + /// An outline row's depth for accessibility, 1 at the top (ARIA `aria-level`), as a + /// `treeitem` carries it. The element tree reports it as `level`. + pub fn level(mut self, level: u32) -> Self { + self.cold_mut().a11y.level = Some(level); + self + } + /// Whether a disclosure (a tree row with children, a collapsible header) is open, for + /// accessibility (ARIA `aria-expanded`). Leave it unset on an element that can't open. + /// The element tree reports it as `expanded`. + pub fn expanded(mut self, open: bool) -> Self { + self.cold_mut().a11y.expanded = Some(open); + self + } +} diff --git a/app/vendor/rune/crates/rune/src/el/anchor.rs b/app/vendor/rune/crates/rune/src/el/anchor.rs new file mode 100644 index 0000000..9dfe013 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/el/anchor.rs @@ -0,0 +1,96 @@ +//! Anchored overlays: `El::anchored`, `El::anchored_fit` and `El::above`. Where they go is +//! worked out in `runtime/anchor.rs`. +use crate::el::{Align, El}; + +/// Which side of its anchor an [`El::anchored`] overlay sits on. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Side { + Top, + Bottom, + Left, + Right, +} + +#[derive(Clone, Debug, PartialEq)] +pub struct Anchor { + pub key: String, + pub side: Side, + pub align: Align, + pub gap: f32, + /// [`El::anchored_fit`]: at most as long as the room on the side it goes to. + pub fit: bool, + /// [`El::anchored_unscaled`]: at window scale, not its anchor's zoom. + pub unscaled: bool, + /// [`El::anchored_round`]: at whole points. + pub round: bool, +} + +impl El { + /// Position an out-of-flow overlay above an earlier keyed element, clamped to the window. + /// Attach the overlay at the root to escape the anchor's clipping ancestors. + pub fn above(self, key: impl Into<String>, gutter: f32) -> Self { + self.anchored(key, Side::Top, Align::Start, gutter) + } + /// Position an out-of-flow overlay on `side` of an earlier keyed element, aligned along that + /// side, `gap` points away. It flips to the opposite side when it doesn't fit, and stays + /// 8 points inside the window. Attach it at the root (after the anchor) so it draws above + /// later siblings and escapes clipping ancestors. + /// + /// It draws at its anchor's zoom: inside a page drawn at [`El::scale`]`(1.6)`, the overlay + /// and its text draw 1.6 times their size too, growing away from the anchor. Its gap zooms + /// with it, and flipping, fitting and the 8-point window margin use its drawn size. Its own + /// [`El::scale`] replaces the inherited zoom; [`El::anchored_unscaled`] keeps it at window + /// scale. + pub fn anchored(mut self, key: impl Into<String>, side: Side, align: Align, gap: f32) -> Self { + self.style.set_position_absolute(); + self.cold_mut().above = Some(Anchor { key: key.into(), side, align, gap, fit: false, unscaled: false, round: false }); + self + } + /// [`El::anchored`], sized to the window as Floating UI's `size` middleware sizes a + /// dropdown: when the overlay fits on neither side, it goes to the side with more room and + /// is at most that room long (tall beside a Top or Bottom anchor, wide beside Left or + /// Right), 8 points inside the window. Let a scroll viewport inside it shrink (`.shrink()` + /// and `.min_h(0.0)` on it and on the columns around it), so a long list scrolls instead of + /// running off the window. + pub fn anchored_fit(self, key: impl Into<String>, side: Side, align: Align, gap: f32) -> Self { + let mut e = self.anchored(key, side, align, gap); + if let Some(a) = e.cold.get_mut_if_some().and_then(|c| c.above.as_mut()) { + a.fit = true; + } + e + } + /// Keep this [`El::anchored`] overlay at window scale instead of its anchor's zoom, for an + /// overlay that zooms its own content (or must not zoom). Call it after `anchored`. + pub fn anchored_unscaled(mut self) -> Self { + if let Some(a) = self.cold.get_mut_if_some().and_then(|c| c.above.as_mut()) { + a.unscaled = true; + } + self + } + /// Put this [`El::anchored`] overlay at whole points, rounding where it goes as Kobalte's + /// popper rounds Floating UI's position (`Math.round` on x and y), so a menu under a trigger + /// at half a point lands where a web menu does. Call it after `anchored`. + pub fn anchored_round(mut self) -> Self { + if let Some(a) = self.cold.get_mut_if_some().and_then(|c| c.above.as_mut()) { + a.round = true; + } + self + } +} + +/// Where an overlay of `size` (width, height) goes next to `trigger` (x0, y0, x1, y1) in a +/// `window` of that size, as the rect (x0, y0, x1, y1) [`El::anchored`] would place it at: on +/// `side` of the trigger, aligned along it, `gap` points away, flipped to the opposite side +/// (and alignment) when it doesn't fit, then kept 8 points inside the window. +/// +/// ``` +/// use rune::{Align, Side, anchor_rect}; +/// // A 100 x 80 menu under a trigger near the bottom of a 400 x 300 window flips above it. +/// let r = anchor_rect([20.0, 250.0, 60.0, 270.0], (100.0, 80.0), Side::Bottom, Align::Start, 4.0, (400.0, 300.0)); +/// assert_eq!(r, [20.0, 166.0, 120.0, 246.0]); +/// ``` +pub fn anchor_rect(trigger: [f32; 4], size: (f32, f32), side: Side, align: Align, gap: f32, window: (f32, f32)) -> [f32; 4] { + let a = Anchor { key: String::new(), side, align, gap, fit: false, unscaled: false, round: false }; + let (x, y) = crate::runtime::anchor_position(&a, trigger, size, window); + [x, y, x + size.0, y + size.1] +} diff --git a/app/vendor/rune/crates/rune/src/el/backdrop.rs b/app/vendor/rune/crates/rune/src/el/backdrop.rs new file mode 100644 index 0000000..acb348f --- /dev/null +++ b/app/vendor/rune/crates/rune/src/el/backdrop.rs @@ -0,0 +1,41 @@ +//! Backdrops: system materials behind the window (`El::system_material`) and blur of the +//! window's own content (`El::backdrop_blur`). +use crate::El; + +impl El { + /// Back this node with a system backdrop material: the platform blurs what is behind the + /// window under the node's rect and corner radius (the largest of its corners), which follow + /// layout and animation like any other paint. Native on macOS in transparent windows, where + /// it replaces the fill and the node's shadows skip its interior; elsewhere, in opaque + /// windows and in headless renders, the fill (or a neutral tint without one) draws instead. + /// Native materials sit under everything the window draws and ignore ancestor clips. + /// `Glass` also turns on `continuous_corners`, the only curve `NSGlassEffectView` draws, so + /// the fill, clip and shadow hole match the glass; `Popover` follows `continuous_corners`. + pub fn system_material(mut self, material: crate::SystemMaterial) -> Self { + if material == crate::SystemMaterial::Glass { self.vis_flags.set(crate::el::VisualFlags::CONTINUOUS_CORNERS, true); } + self.cold_mut().material = Some(material); + self + } + + /// Blurs what is already drawn behind this element in the same window, inside its rounded + /// (or continuous) corners and clip, then draws the element's fill over the blur as a tint, + /// with its border and children on top: `el().backdrop_blur(8.0).fill(tint)` is a frosted + /// bar. `sigma` is the Gaussian standard deviation in points, as in CSS + /// `backdrop-filter: blur()`; 0 turns it off. Blurs past about 78 points at 2x stop growing. + /// + /// Unlike `El::system_material`, which shows what is behind the window, this blurs Rune's + /// own content and looks the same on every platform. The element's opacity fades the blur + /// with it, and its outer shadows leave the blurred interior clear. The first + /// `MAX_BACKDROP_BLURS` blurred elements in a frame blur; any past that, and any drawn into a + /// target that can't be copied (no `COPY_SRC`, or a caller's own `wgpu::RenderPass` via + /// `Renderer::draw_range`), draw only their fill. Inside an ancestor drawn as one layer + /// (`El::group_opacity`, `El::blur`, `El::cache`) the backdrop is what that layer has drawn + /// so far, as in CSS. + pub fn backdrop_blur(mut self, sigma: f32) -> Self { + let s = if sigma.is_finite() { sigma.max(0.0) } else { 0.0 }; + if s != 0.0 || !self.vis.cold.is_empty() { + self.vis.cold_mut().backdrop_blur = s; + } + self + } +} diff --git a/app/vendor/rune/crates/rune/src/el/child_exit.rs b/app/vendor/rune/crates/rune/src/el/child_exit.rs new file mode 100644 index 0000000..d37e377 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/el/child_exit.rs @@ -0,0 +1,16 @@ +//! `El::child_exit`: children removed in a commit leave the way that commit says. +use rune_motion::Transition; + +use crate::el::El; + +impl El { + /// Children removed from this element leave with `t` instead of the transition from their + /// last render. A node normally leaves the way it was last drawn, before anyone knew why it + /// would go; a rolling counter's old digit has to leave the way the new one enters, which + /// only the commit that removes it knows. Set it on each build with that build's direction. + /// Children still present, and those already leaving, keep their own transitions. + pub fn child_exit(mut self, t: Transition) -> Self { + self.vis.cold_mut().child_exit = Some(Box::new(t)); + self + } +} diff --git a/app/vendor/rune/crates/rune/src/el/direction.rs b/app/vendor/rune/crates/rune/src/el/direction.rs new file mode 100644 index 0000000..b333545 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/el/direction.rs @@ -0,0 +1,216 @@ +//! Layout direction: `El::dir` lays a subtree out right to left (or left to right inside one +//! that is), as HTML's `dir` attribute does, and `El::mirror_in_rtl` flips a directional icon. +//! +//! Layout runs left to right; a right-to-left element then mirrors where its children sit inside +//! it, so a row's first child is at its right, start and end alignment swap, and an absolute +//! child's left inset is its right. Its own padding, border sides, corner radii, soft clip +//! edges and linear gradients swap left and right with it, as CSS's logical `start` and `end` +//! resolve: in this model `left` means start (`El::unmirrored` keeps an element physical). +//! An `El::anchored` overlay's `Left` and `Right` sides and a `Top` or `Bottom` overlay's +//! `Start` and `End` alignment swap too. Shadows, `El::offset` and other visual transforms +//! stay physical, as CSS's do. Text lays out with a right-to-left paragraph +//! direction (bidi base level), so its `Start` alignment is its right edge. +//! +//! Each element's direction resolves as one step down the tree ([`step`]), from its parent's +//! [`Flow`] and its own [`DirEvent`]. Nothing is mirrored in a window that sets no +//! right-to-left direction: layout reads one small enum per element. +use super::*; + +pub use rune_text::Direction; +pub(crate) use rune_text::Flow; +use rune_text::first_strong_char; + +impl El { + /// Lays this element and its subtree out in `dir` (see [`Direction`]): `Rtl` mirrors rows, + /// start and end alignment, padding, border sides, corner radii, anchored overlays and + /// horizontal scrolling, and gives text a right-to-left paragraph direction; `Ltr` inside a + /// right-to-left subtree keeps an island in its own order (a path, a command, code), and + /// `Auto` takes the direction of the text it holds (a title, a name, a message). Elements + /// that set none take their parent's; the window's root runs left to right. + pub fn dir(mut self, dir: Direction) -> Self { + self.flags.set_dir(dir); + self + } + + /// Keeps this element where left-to-right layout puts it inside a right-to-left parent, + /// unmirrored, as a CSS physical `left` or `right` inset stays put under `dir="rtl"`: room + /// kept clear of the window's own controls (Windows' caption buttons stay on the right, + /// macOS's traffic lights on the left), or a pin that must not swap sides. Its own subtree + /// still lays out in its direction. + pub fn unmirrored(mut self) -> Self { + self.flags.set(ElFlags::UNMIRRORED, true); + self + } + + /// Flips this element's icon left to right when it lays out right to left, for an icon + /// that points along the line (a chevron, an arrow, a back button), as `@opencode/ui`'s + /// `data-directional` icons do. Icons that don't point keep their drawing. A turned element + /// or icon (`El::rotate`, `El::icon_rotation`) turns the other way, as a CSS `scaleX(-1)` + /// outside its rotation: a collapsed disclosure's chevron turned to point right points left. + pub fn mirror_in_rtl(mut self) -> Self { + self.vis.cold_mut().mirror_rtl = true; + self + } +} + +/// Where an element sits in its parent: where its parent's flow puts it, or where left-to-right +/// layout does whatever the flow (`El::unmirrored`). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(crate) enum Pin { + #[default] + Flowing, + Physical, +} + +impl Pin { + pub(crate) fn of(el: &El) -> Pin { + if el.flags.has(ElFlags::UNMIRRORED) { Pin::Physical } else { Pin::Flowing } + } +} + +/// What an element says about its own direction, the event that steps its parent's flow to its. +pub(crate) enum DirEvent<'a> { + /// No `El::dir`: it takes its parent's. + Inherit, + /// `El::dir(Ltr)` or `El::dir(Rtl)`. + Set(Flow), + /// `El::dir(Auto)`: its first strong character decides, its parent's flow when none does. + Auto(&'a El), +} + +impl<'a> DirEvent<'a> { + pub(crate) fn of(el: &'a El) -> DirEvent<'a> { + // A field Ctrl+Shift set lays out that way, its padding and placeholder with it. + if let Some(flow) = el.cold.input.as_ref().and_then(|i| i.edit.forced_dir()) { + return DirEvent::Set(flow); + } + match el.flags.dir() { + None => DirEvent::Inherit, + Some(Direction::Ltr) => DirEvent::Set(Flow::Ltr), + Some(Direction::Rtl) => DirEvent::Set(Flow::Rtl), + Some(Direction::Auto) => DirEvent::Auto(el), + } + } +} + +/// What flattening does to an element once its flow is known. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum DirEffect { + /// Left to right: as authored. + Keep, + /// Right to left: its own left and right sides (`mirror_visual`) and its anchored + /// overlay's side (`mirror_anchor`) swap. + Mirror, +} + +/// One step down the tree: the parent's flow and the element's own direction give its flow, +/// and what it has to mirror. +pub(crate) fn step(parent: Flow, event: DirEvent<'_>) -> (Flow, DirEffect) { + let flow = match event { + DirEvent::Inherit => parent, + DirEvent::Set(flow) => flow, + // With no strong character (empty, digits, a path alone) it reads the way its parent + // does: an empty field in an Arabic window starts at the right. + DirEvent::Auto(el) => match first_strong(el) { + Some(Direction::Rtl) => Flow::Rtl, + Some(_) => Flow::Ltr, + None => parent, + }, + }; + let effect = match flow { + Flow::Ltr => DirEffect::Keep, + Flow::Rtl => DirEffect::Mirror, + }; + (flow, effect) +} + +/// The first strong direction in `el`'s text, then its children's in order, skipping children +/// that set their own direction. +fn first_strong(el: &El) -> Option<Direction> { + // A by-paragraph field reads as a `contenteditable` with `dir="auto"`: its text across its + // lines, each mention pill (a `dir="auto"` span) skipped, and none while it's empty (its + // placeholder is another element). + if let (Some(t), Some(_)) = (&el.text, el.cold.input.as_ref()) + && matches!(t.dir, TextDir::Plaintext(_)) + { + let mut at = 0; + for p in t.cold.pills.iter().map(|p| (p.start as usize, p.end as usize)).chain([(t.content.len(), t.content.len())]) { + if let Some(d) = t.content.get(at..p.0).and_then(|s| first_strong_char(s, true)) { + return Some(d); + } + at = at.max(p.1); + } + return None; + } + if let Some(t) = &el.text + && let Some(d) = Direction::of(&t.content) + { + return Some(d); + } + // An empty field reads its placeholder, as the placeholder shows in its place. + if let Some(i) = el.cold.input.as_ref().filter(|i| !i.edit.is_secure()) + && let Some(d) = Direction::of(if i.edit.text.is_empty() { &i.placeholder } else { &i.edit.text }) + { + return Some(d); + } + el.all_children().filter(|c| c.flags.dir().is_none()).find_map(first_strong) +} + +/// Mirrors what a right-to-left element draws on its own left and right: corner radii, border +/// sides, soft clip edges and an angled linear gradient's run. +pub(crate) fn mirror_visual(vis: &mut Visual) { + // Uniform corners (most boxes) and no extras: nothing to mirror, nothing touched. + if vis.radius.is_nan() { + let [tl, tr, br, bl] = vis.radii(); + vis.set_radii([tr, tl, bl, br]); + } + let Some(cold) = vis.cold.get() else { return }; + let turns = cold.mirror_rtl && (cold.rotate != 0.0 || cold.icon_turn != 0.0); + let flips = turns || cold.border_sides.is_some() || cold.clip.is_some() || cold.clip_corners.is_some() + || cold.radial.as_ref().is_some_and(|r| matches!(r.geometry, GradientGeometry::Linear { .. })); + if !flips { + return; + } + let cold = vis.cold_mut(); + if cold.mirror_rtl { + // A mirrored drawing turns the other way. + cold.rotate = -cold.rotate; + cold.icon_turn = -cold.icon_turn; + } + if let Some(r) = &mut cold.radial + && let GradientGeometry::Linear { angle } = &mut r.geometry + { + // CSS angles run clockwise from up: a left-to-right ramp runs right to left. + *angle = -*angle; + } + if let Some([t, r, b, l]) = cold.border_sides { + cold.border_sides = Some([t, l, b, r]); + } + if let Some([l, t, r, b]) = cold.clip { + cold.clip = Some([r, t, l, b]); + } + if let Some([tl, tr, br, bl]) = cold.clip_corners { + cold.clip_corners = Some([tr, tl, bl, br]); + } +} +/// Mirrors `Side::Left` and `Side::Right` in right-to-left layout. +pub(crate) fn mirror_side(s: Side) -> Side { + match s { + Side::Left => Side::Right, + Side::Right => Side::Left, + other => other, + } +} + +/// An anchored overlay's placement as a right-to-left element means it: `Left` and `Right` +/// swap, and along a `Top` or `Bottom` side so do `Start` and `End`. +pub(crate) fn mirror_anchor(a: &mut Anchor) { + a.side = mirror_side(a.side); + if matches!(a.side, Side::Top | Side::Bottom) { + a.align = match a.align { + Align::Start => Align::End, + Align::End => Align::Start, + Align::Center => Align::Center, + }; + } +} diff --git a/app/vendor/rune/crates/rune/src/el/drop.rs b/app/vendor/rune/crates/rune/src/el/drop.rs new file mode 100644 index 0000000..85fd0ce --- /dev/null +++ b/app/vendor/rune/crates/rune/src/el/drop.rs @@ -0,0 +1,135 @@ +//! Files dropped on an element from another app: `El::on_drop_files` and the hover, move +//! and reject callbacks around it, and `Tx::drop_point`. `runtime/input/drop.rs` routes the drag. +use std::rc::Rc; + +use crate::el::{El, PointerEvent, Tx}; +use crate::states::downcast; + +pub(crate) type DropFilesFn = Rc<dyn Fn(crate::states::States<'_>, &[std::path::PathBuf], &mut Tx)>; + +/// [`El::on_drop_files`], [`El::accepts_files`], [`El::on_drop_hover`], [`El::on_drop_move`], +/// [`El::on_drop_rejected`] and [`El::on_drop_rejected_hover`]. +#[derive(Clone, Default)] +pub(crate) struct DropSpec { + pub on_drop: Option<DropFilesFn>, + pub accepts: Option<AcceptsFn>, + pub on_hover: Option<DropHoverFn>, + pub on_reject: Option<DropFilesFn>, + pub on_reject_hover: Option<DropHoverFn>, + pub on_move: Option<DropMoveFn>, +} +pub(crate) type AcceptsFn = Rc<dyn Fn(&std::path::Path) -> bool>; +pub(crate) type DropHoverFn = Rc<dyn Fn(crate::states::States<'_>, bool, &mut Tx)>; +pub(crate) type DropMoveFn = Rc<dyn Fn(crate::states::States<'_>, PointerEvent, &mut Tx)>; + +impl DropSpec { + /// The files of `paths` this element takes, when it's a drop target, and the rest. + pub(crate) fn split(&self, paths: &[std::path::PathBuf]) -> (Vec<std::path::PathBuf>, Vec<std::path::PathBuf>) { + if self.on_drop.is_none() { return (Vec::new(), paths.to_vec()); } + paths.iter().cloned().partition(|p| self.accepts.as_ref().is_none_or(|f| f(p))) + } + /// It stops a drag it takes none of, rather than passing it to the target around it. + pub(crate) fn claims_rejects(&self) -> bool { self.on_reject.is_some() || self.on_reject_hover.is_some() } + /// Its hover callback for a drag it takes (`accepted`) or rejects. + pub(crate) fn hover_fn(&self, accepted: bool) -> Option<DropHoverFn> { + if accepted { self.on_hover.clone() } else { self.on_reject_hover.clone() } + } +} + +impl El { + /// Take files dropped on this element from another app (Finder, Explorer, a file manager). + /// The innermost target under the drop that accepts any of the files gets the ones it + /// accepts, all in one call; files it doesn't accept are left out. A drop no target takes + /// is ignored: put `on_drop_files` on the root as well to catch drops anywhere. While a modal + /// is open, its root stands in for the window's, and a drop outside it reaches nothing. A drop + /// target takes no pointer events, so one laid over other elements leaves their clicks, + /// context menus and help. + /// + /// ``` + /// # use rune::el::el; + /// # use std::path::PathBuf; + /// # struct App { attachments: Vec<PathBuf>, over: bool } + /// # let s = App { attachments: Vec::new(), over: false }; + /// el().fill(if s.over { rune::Color::WHITE.alpha(0.1) } else { rune::Color::TRANSPARENT }) + /// .on_drop_files(|s: &mut App, files, _| s.attachments.extend_from_slice(files)) + /// .accepts_extensions(&["png", "jpg", "m4a"]) + /// .on_drop_hover(|s: &mut App, over, _| s.over = over); + /// ``` + /// + /// [`Tx::drop_point`] says where on the element the files landed, to insert them there. + /// + /// macOS, Windows and X11. Wayland reports no file drags in winit 0.30, and the web build + /// has no paths to give. Headless scripts drop files with `drop_files` events. + pub fn on_drop_files<S: 'static>(mut self, f: impl Fn(&mut S, &[std::path::PathBuf], &mut Tx) + 'static) -> Self { + self.handlers.drop.get_or_insert_default().on_drop = Some(Rc::new(move |s, files, tx| f(downcast::<S>(s), files, tx))); + self + } + /// Only the files `accepts` returns true for reach this element's [`El::on_drop_files`]. A + /// drag carrying none of them passes this element over: the next accepting ancestor takes + /// the drop and shows the drop hover. + pub fn accepts_files(mut self, accepts: impl Fn(&std::path::Path) -> bool + 'static) -> Self { + self.handlers.drop.get_or_insert_default().accepts = Some(Rc::new(accepts)); + self + } + /// [`El::accepts_files`] for files with one of these extensions, compared without case. + pub fn accepts_extensions(self, extensions: &[&str]) -> Self { + let extensions: Vec<String> = extensions.iter().map(|e| e.trim_start_matches('.').to_ascii_lowercase()).collect(); + self.accepts_files(move |path| path.extension().and_then(|e| e.to_str()) + .is_some_and(|e| extensions.iter().any(|x| x.eq_ignore_ascii_case(e)))) + } + /// Called with `true` when a file drag over the window makes this element the drop target + /// (the innermost [`El::on_drop_files`] under the pointer that accepts the files), and with + /// `false` when the drag moves off it, leaves the window, or drops, or when the element goes + /// away under the drag. Draw a drop highlight from it. With `true`, [`Tx::drop_point`] says + /// where the drag came in. + pub fn on_drop_hover<S: 'static>(mut self, f: impl Fn(&mut S, bool, &mut Tx) + 'static) -> Self { + self.handlers.drop.get_or_insert_default().on_hover = Some(Rc::new(move |s, over, tx| f(downcast::<S>(s), over, tx))); + self + } + /// Follow a file drag this element takes ([`El::on_drop_files`]) while it's over it: `f` + /// hears the drag's point on the element, in the element's own points as + /// [`El::on_pointer_move_local`] gives them, when it becomes the target and then as the drag + /// moves, at most once a frame. Draw a drop caret from it, cleared by + /// [`El::on_drop_hover`]'s `false`, and insert where [`Tx::drop_point`] says on the drop. + /// Only an element with this asks the window for frames as the drag moves over it, and a + /// drag the platform gives no position for is never heard here. Scripts move a drag with + /// further `drag_files` events. + pub fn on_drop_move<S: 'static>(mut self, f: impl Fn(&mut S, PointerEvent, &mut Tx) + 'static) -> Self { + self.handlers.drop.get_or_insert_default().on_move = Some(Rc::new(move |s, p, tx| f(downcast::<S>(s), p, tx))); + self + } + /// Hear the files dropped on this element that it doesn't accept ([`El::accepts_files`]), + /// to say why ("that isn't an export"). With this, or [`El::on_drop_rejected_hover`], the + /// element stops a drag carrying none of the files it takes instead of passing it to the + /// target around it, and a drop of only those files comes here. On a drop of some files it + /// takes and some it doesn't, [`El::on_drop_files`] gets the first and this the rest. + /// + /// ``` + /// # use rune::el::el; + /// # struct App { error: Option<String>, wrong: bool } + /// el().on_drop_files(|s: &mut App, _, _| s.error = None) + /// .accepts_extensions(&["json"]) + /// .on_drop_rejected(|s: &mut App, files, _| s.error = Some(format!("{} isn't an export", files[0].display()))) + /// .on_drop_rejected_hover(|s: &mut App, over, _| s.wrong = over); + /// ``` + pub fn on_drop_rejected<S: 'static>(mut self, f: impl Fn(&mut S, &[std::path::PathBuf], &mut Tx) + 'static) -> Self { + self.handlers.drop.get_or_insert_default().on_reject = Some(Rc::new(move |s, files, tx| f(downcast::<S>(s), files, tx))); + self + } + /// [`El::on_drop_hover`] for a drag this element stops but takes none of (see + /// [`El::on_drop_rejected`]): `true` when the drag reaches it, `false` when it moves off, + /// leaves the window or drops, or when the element goes away under it. Draw a "can't drop + /// here" state from it. + pub fn on_drop_rejected_hover<S: 'static>(mut self, f: impl Fn(&mut S, bool, &mut Tx) + 'static) -> Self { + self.handlers.drop.get_or_insert_default().on_reject_hover = Some(Rc::new(move |s, over, tx| f(downcast::<S>(s), over, tx))); + self + } +} + +impl Tx { + /// In [`El::on_drop_files`], [`El::on_drop_rejected`], [`El::on_drop_move`] and + /// [`El::on_drop_hover`]'s `true`: where the file drag is on the element, in its own points + /// (`x`, `y`, following its scroll and transforms) and in the window's. `None` when the + /// platform gave no position and in every other handler. + pub fn drop_point(&self) -> Option<PointerEvent> { self.drop_point } +} diff --git a/app/vendor/rune/crates/rune/src/el/effect.rs b/app/vendor/rune/crates/rune/src/el/effect.rs new file mode 100644 index 0000000..7a71639 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/el/effect.rs @@ -0,0 +1,73 @@ +//! Effect slots (`El::effect`): places in the painter stream a compositor paints into. +use crate::El; + +/// An effect slot's settings (`El::effect` and its builders). +#[derive(Clone, Copy, Debug, Default)] +pub(crate) struct EffectSlot { + /// Points past the rect the compositor may paint (`El::effect_bleed`). + pub bleed: f32, + /// Asks for a backdrop copy (`El::effect_backdrop`). + pub backdrop: bool, + /// The app's payload (`El::effect_data`). + pub data: [f32; 4], +} + +impl PartialEq for EffectSlot { + // Bitwise, so a NaN-packed payload still lets a memoized row be reused. + fn eq(&self, o: &Self) -> bool { + self.bleed == o.bleed && self.backdrop == o.backdrop && self.data.map(f32::to_bits) == o.data.map(f32::to_bits) + } +} + +impl El { + /// Makes this element an effect slot for a compositor, tagged `mark`. It draws nothing + /// itself but keeps its place in the painter stream with its rect, clip, rounded clip and + /// enclosing isolated layer (opacity, blur, dissolve), so a compositor can paint its own + /// pass there. See `Renderer::draw_with` and the pattern on `compose::Compositor`. + /// + /// The hook gets the slot as an `EffectSite`: `mark` says which slot it is and `data` + /// carries [`Self::effect_data`]. Give each slot that can be on screen at once its own mark, + /// such as one per page, so an outgoing slot and its replacement keep separate resources: + /// + /// ```ignore + /// effect(HUD_BASE + page.id).effect_data([page.wave_id as f32, page.phase, 0.0, 0.0]) + /// .key(page.id).transition(Transition::opacity()) + /// ``` + /// + /// The slot is where the element is presented: `El::scale`, `El::offset`, `live_scale`, + /// and a transition's scale and offset while it enters or leaves move and scale its rect, + /// and set `EffectSite::scale` (device pixels per point). A partial opacity, including an + /// enter or exit fade, puts the slot in its own isolated layer that applies it. Rotation is + /// not in the slot's record: under `El::rotate` the slot draws upright inside a turned + /// isolated layer (`EffectSite::in_layer`), and Rune turns what the hook painted. + pub fn effect(mut self, mark: u32) -> Self { + if mark != 0 || !self.vis.cold.is_empty() { + self.vis.cold_mut().mark = mark; + } + self.vis.cold_mut().effect.get_or_insert_with(EffectSlot::default); + self + } + /// Points past the rect an effect slot may paint (a glow's reach). Grows the bounds of an + /// enclosing isolated layer; the clip still applies. + pub fn effect_bleed(mut self, pt: f32) -> Self { + self.vis.cold_mut().effect.get_or_insert_with(EffectSlot::default).bleed = pt.max(0.0); + self + } + /// Request a backdrop copy up to this effect slot (`EffectSite::backdrop`) when drawn with + /// `Renderer::draw_with`, `Renderer::draw_with_backdrop`, or `Renderer::encode_layers_with`. + /// Ordinary slots (`false`, the default) stay inside the open render pass with no copy. + /// A target without `COPY_SRC` usage can't be copied: the slot draws in the open pass with `backdrop == None`. + pub fn effect_backdrop(mut self, on: bool) -> Self { + self.vis.cold_mut().effect.get_or_insert_with(EffectSlot::default).backdrop = on; + self + } + /// Four floats this effect slot hands its compositor as `EffectSite::data`, such as which + /// snapshot of data to draw, a seed or a phase. They travel bit for bit in the slot's + /// record, so `f32::from_bits` round-trips a 32-bit id. A removed element keeps the payload + /// it was last built with through its exit transition, with no bookkeeping in the app. + /// Makes the element an effect slot if it isn't one yet (tag 0 unless `El::effect` sets one). + pub fn effect_data(mut self, data: [f32; 4]) -> Self { + self.vis.cold_mut().effect.get_or_insert_with(EffectSlot::default).data = data; + self + } +} diff --git a/app/vendor/rune/crates/rune/src/el/element_info.rs b/app/vendor/rune/crates/rune/src/el/element_info.rs new file mode 100644 index 0000000..8041c2a --- /dev/null +++ b/app/vendor/rune/crates/rune/src/el/element_info.rs @@ -0,0 +1,77 @@ +//! A whole `ElementInfo` to build from, so a stub doesn't break when Rune adds a field. +use crate::{Color, ElementInfo}; + +/// A plain, fully opaque element at rest with no key: `el()` with nothing set, before layout +/// (zero rects). Stubs fill in what they test: `ElementInfo { focused: true, ..ElementInfo::stub("send") }`. +impl Default for ElementInfo { + fn default() -> Self { + ElementInfo { + trace_name: None, + trace_namespace: None, + loop_phase: None, + focusable: false, + focused: false, + focus_visible: false, + inert: false, + exiting: false, + path: String::new(), + key: None, + role: "group", + label: None, + text: None, + rect: [0.0; 4], + target: [0.0; 4], + opacity: 1.0, + scale: 1.0, + blur: 0.0, + radius: 0.0, + fill: Color::TRANSPARENT, + text_color: None, + hover: 0.0, + press: 0.0, + moving: false, + parent: None, + visible: [0.0; 4], + revealing: false, + in_growing_row: false, + scrolling: false, + scrolled: [0.0; 2], + virtual_extent: false, + live_intent: 0, + caret: None, + edit_range: None, + drag_out: false, + help: None, + selected: None, + level: None, + expanded: None, + item_selected: false, + stuck: 0.0, + } + } +} + +impl ElementInfo { + /// The default element keyed `key` (its path is the key too), for a test that stands in for + /// `Runtime::elements`. + pub fn stub(key: impl Into<String>) -> Self { + let key = key.into(); + ElementInfo { path: key.clone(), key: Some(key), ..ElementInfo::default() } + } +} + +#[cfg(test)] +mod tests { + use crate::{Cx, El, ElementInfo, Env, Runtime, el}; + + #[test] + fn a_stub_matches_what_a_plain_keyed_element_reports() { + let mut rt = Runtime::new((), |_: &(), _: &mut Cx<()>| -> El { el().key("send") }, (100.0, 100.0), Env::new(true, 1.0)); + rt.frame(0.0); + let real = rt.elements().into_iter().find(|e| e.key.as_deref() == Some("send")).unwrap(); + let stub = ElementInfo { rect: real.rect, target: real.target, visible: real.visible, path: real.path.clone(), ..ElementInfo::stub("send") }; + assert_eq!(format!("{stub:?}"), format!("{real:?}")); + let focused = ElementInfo { focused: true, ..ElementInfo::stub("send") }; + assert_eq!((focused.key.as_deref(), focused.path.as_str(), focused.focused, focused.opacity), (Some("send"), "send", true, 1.0)); + } +} diff --git a/app/vendor/rune/crates/rune/src/el/enter_delay.rs b/app/vendor/rune/crates/rune/src/el/enter_delay.rs new file mode 100644 index 0000000..6990f52 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/el/enter_delay.rs @@ -0,0 +1,41 @@ +//! `El::enter_delay`: a new element holds its whole entrance, then plays it. +use crate::el::El; + +impl El { + /// Hold this element's entrance `seconds` after it mounts, then play all of it on its + /// [`transition`](Self::transition)'s enter spring. Until then it waits at the insertion + /// effect: offset, scale, blur, opacity and reveal stay at their absent values and leave + /// together, so a row that slides and fades is still where it starts when it begins to + /// show. It takes its place in layout at once, as any entrance does. Stagger a list with + /// [`Stagger`](crate::Stagger): + /// + /// ``` + /// # use rune::{El, Stagger, Transition, col, el}; + /// # let items = ["Welcome", "Pick a theme", "Sign in"]; + /// let stagger = Stagger::new(0.06); + /// let rows = items.iter().enumerate().map(|(i, item)| { + /// el().key(*item).h(44.0) + /// .transition(Transition::offset(0.0, 12.0).combined(Transition::opacity())) + /// .enter_delay(stagger.delay(i, items.len())) + /// }); + /// let list: El = col().children(rows); + /// ``` + /// + /// The delay runs on the element's clock, so [`El::time_scale`] and the window's time scale + /// stretch it with the entrance. Under Reduce Motion it is kept: the entrance turns into + /// the short fade, at the same time. Only a fresh mount waits. An entrance nobody would + /// see lands at once and ignores it: the first frame, a [`Tx::instant`](crate::Tx::instant) + /// or [`Tx::settle`](crate::Tx::settle) commit (`Runtime::settle_all` also lands one still + /// waiting), a hidden window, an element out of sight. So does an element that comes back + /// while it's leaving. Removed while it waits, it goes at once when its insertion effect + /// is invisible (it fades in), or else leaves from that effect on the exit spring. Changing + /// the delay after it mounts does nothing. + /// + /// [`opacity_motion`](Self::opacity_motion) animates the element's own opacity, which + /// multiplies the entrance's: its own delay applies to that change only. + pub fn enter_delay(mut self, seconds: f32) -> Self { + let seconds = if seconds.is_finite() { seconds.max(0.0) } else { 0.0 }; + self.vis.cold_mut().enter_delay = seconds; + self + } +} diff --git a/app/vendor/rune/crates/rune/src/el/focus.rs b/app/vendor/rune/crates/rune/src/el/focus.rs new file mode 100644 index 0000000..845b958 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/el/focus.rs @@ -0,0 +1,308 @@ +//! What `El` holds for focus and keys: `FocusSpec`, kept behind `Cold` because most elements set none of it. + +use std::rc::Rc; + +use crate::color::Color; +use crate::el::{El, InputKeyFn, Outline, PressFn, RoleTag, StepFn, StepLimitFn, Tx}; +use crate::states::downcast; + +#[derive(Clone)] +pub(crate) struct FocusSpec { + pub physical: Option<crate::input::physical_input::Handler>, + pub enabled: bool, + /// `focusable(false)`: not a Tab stop even where [`crate::Cx::web_focus`] would make it one. + pub opt_out: bool, + /// [`crate::El::autofocus`]. + pub autofocus: bool, + pub order: i32, + pub group: bool, + pub selected: bool, + pub reveal_selected: bool, + pub preserve_on_press: crate::runtime::selectable::OnPress, + pub ring: Option<Outline>, + /// `focus_within_ring`: `ring` shows while focus is on this element or inside it, from + /// the pointer or the keyboard. + pub within: bool, + /// `no_focus_ring`: no default ring on this control, and none from this element. + pub ring_off: bool, + /// `focus_within_flat`: no outer or inset shadows and no hover fill while focus is on this + /// element or inside it. + pub flat_within: bool, + /// `focus_visible_within_ring`: the within ring shows only while the keyboard put focus there. + pub within_keyboard: bool, + /// [`crate::El::focus_ring_for`]: `ring` shows while the keyboard has the element with this key focused. + pub ring_for: Option<Rc<str>>, + /// `default_button`: Return presses it. + pub default: bool, + pub highlight: Option<Color>, + /// `focus_fill`: painted over the element while it shows keyboard focus. + pub fill: Option<Color>, + pub follows: bool, + pub return_to: Option<String>, + /// [`crate::El::press_focuses_below`]. + pub below: bool, + /// `on_step`: a slider's arrow and page keys. + pub step: Option<StepFn>, + /// `on_step_limit`: a slider's Home and End. + pub step_limit: Option<StepLimitFn>, + /// `on_key_up`. + pub key_up: Option<InputKeyFn>, + /// `El::on_key`: keys while this element or one inside it has focus. + pub key: Option<InputKeyFn>, +} + +impl crate::cold::Empty for FocusSpec { + const EMPTY: &'static Self = &FocusSpec { + physical: None, + enabled: false, + opt_out: false, + autofocus: false, + order: 0, + group: false, + selected: false, + reveal_selected: false, + preserve_on_press: crate::runtime::selectable::OnPress { focus: false, selection: false }, + ring: None, + within: false, + ring_off: false, + flat_within: false, + within_keyboard: false, + ring_for: None, + default: false, + highlight: None, + fill: None, + follows: false, + return_to: None, + below: false, + step: None, + step_limit: None, + key_up: None, + key: None, + }; +} + +#[derive(Clone)] +pub(crate) struct ModalSpec { + pub dismiss: PressFn, + pub outside: bool, +} + +impl El { + /// Keys while this element, or a control inside it, has focus: `f` sees each key before + /// focus navigation (arrows in a group, Return and Space presses), the default button and + /// the window's `on_key`, and returns true to consume it. Keys typed into a focused text + /// field stay the field's. Nested handlers run innermost first. + /// + /// With `focusable(true)`, this is a control that owns its keyboard, like a virtualised + /// list whose rows aren't all built: it keeps focus while its rows scroll in and out, and a + /// click anywhere inside it focuses it (an NSTableView). + pub fn on_key<S: 'static>(mut self, f: impl Fn(&mut S, &crate::KeyEvent, &mut Tx) -> bool + 'static) -> Self { + self.cold_mut().focus.key = Some(Rc::new(move |s, key, tx| f(downcast::<S>(s), key, tx))); + self + } + /// Opt into keyboard and pointer focus. Disabled controls must set this false, which also + /// keeps a pressable control out of the Tab order under [`Cx::web_focus`](crate::Cx::web_focus). + pub fn focusable(mut self, enabled: bool) -> Self { + // Recorded even on a bare element: under `Cx::web_focus` it keeps a pressable control + // out of the Tab order. + let focus = &mut self.cold_mut().focus; + focus.enabled = enabled; + focus.opt_out = !enabled; + self + } + /// Positive overrides precede document order (0); negative values skip Tab only. + pub fn tab_index(mut self, order: i32) -> Self { + if order != 0 || !self.cold.focus.is_empty() { + self.cold_mut().focus.order = order; + } + self + } + /// Arrow keys rove among focusable descendants; Tab visits only the current/selected item. + /// Groups with role `menu`, `listbox`, `list` or `tree` move on Up and Down only; other + /// groups (segments, tabs, radios, toolbars) move on Left and Right as well. Home and End + /// jump to the ends. `list`, `tree` and `grid` stop at their ends, as NSTableView does; + /// menus, popups and segments wrap. + pub fn focus_group(mut self) -> Self { + self.cold_mut().focus.group = true; + self + } + pub fn focus_selected(mut self, selected: bool) -> Self { + if selected || !self.cold.focus.is_empty() { + self.cold_mut().focus.selected = selected; + } + self + } + /// On a virtualized stack, reveal its selected row when the selected key changes, + /// even while another control owns keyboard focus. Frames dispatching `on_hover` + /// do not scroll, so hover-driven selection does not move the row under the pointer. + /// Off by default; useful for suggestions controlled by an outside text field. + pub fn reveal_selected(mut self, enabled: bool) -> Self { + if enabled || !self.cold.focus.is_empty() { + self.cold_mut().focus.reveal_selected = enabled; + } + self + } + /// A press on this element or its unfocusable descendants leaves the current field + /// focused instead of blurring it. Works on any element, not only popups: a list row, a + /// button, a toolbar. The press still reaches `on_press` and the other handlers, and a + /// scroll still cancels it as usual. Focusable descendants still take focus normally. + pub fn preserve_focus_on_press(mut self, enabled: bool) -> Self { + if enabled || !self.cold.focus.is_empty() { + self.cold_mut().focus.preserve_on_press.focus = enabled; + } + self + } + /// On a focus group: arrow keys and type-select also press the item they focus, so + /// selection follows focus (a source list). Radio and tab items always do. + pub fn focus_follows(mut self) -> Self { + self.cold_mut().focus.follows = true; + self + } + /// A menu or list row's highlight: painted while focused from the keyboard or pointer, + /// and moving the pointer over the row focuses it, so keys and mouse share one + /// highlight (NSMenu). Use instead of `hover` and `focus_ring`. + pub fn focus_highlight(mut self, color: Color) -> Self { + self.cold_mut().focus.highlight = Some(color); + self + } + /// A fill laid over this element while it shows keyboard focus, as CSS + /// `:focus-visible { background }` paints one: a list row that Tab reaches. Unlike + /// [`El::focus_highlight`] the pointer neither paints it nor moves focus. A row that shows + /// focus by its fill alone also sets [`El::no_focus_ring`]. + pub fn focus_fill(mut self, color: Color) -> Self { + self.cold_mut().focus.fill = Some(color); + self + } + /// The window's default button, which Return presses (AppKit's `keyEquivalent = "\r"`). + /// Return goes to it from anywhere in the window, or the open modal, unless the focused + /// element takes Return itself: a text field with `on_submit`, a link, or a row of a + /// `menu`, `listbox`, `list`, `tree` or `grid` group or a `focus_highlight` row, which + /// Return presses. With several, the last one shown wins (a + /// sheet's over its window's). It needs an `on_press`, and stays out of reach while hidden + /// or behind a modal. A focused button presses on Space, and passes Return on to this. + pub fn default_button(mut self) -> Self { + self.cold_mut().focus.default = true; + self + } + /// A slider's keyboard, as NSSlider's: while this element is focused, Left and Down call + /// `f` with -1, Right and Up with +1, Page Down with -10 and Page Up with +10, repeating + /// while held. `f` moves the value by that many of its steps and clamps it. The element + /// becomes focusable, and its role `slider` unless it has another. Home and End go to the + /// ends with [`El::on_step_limit`]. + pub fn on_step<S: 'static>(mut self, f: impl Fn(&mut S, i32, &mut Tx) + 'static) -> Self { + self.cold_mut().focus.step = Some(Rc::new(move |s, delta, tx| f(downcast::<S>(s), delta, tx))); + self.cold_mut().focus.enabled = true; + if self.role == RoleTag::GROUP { + self.role = RoleTag::SLIDER; + } + self + } + /// A slider's Home and End (see [`El::on_step`]): `f` gets `false` for Home, which goes to + /// the minimum, and `true` for End, the maximum. Without it they scroll, as elsewhere. + pub fn on_step_limit<S: 'static>(mut self, f: impl Fn(&mut S, bool, &mut Tx) + 'static) -> Self { + self.cold_mut().focus.step_limit = Some(Rc::new(move |s, max, tx| f(downcast::<S>(s), max, tx))); + self + } + /// Return focus to this keyed trigger (or its first focusable child) when removed. + pub fn focus_return(mut self, trigger: impl Into<String>) -> Self { + self.cold_mut().focus.return_to = Some(trigger.into()); + self + } + /// A press on this layer (the scrim under a context menu) focuses what a press there would + /// focus without it: the focusable scroll region under the pointer, as a web page's press + /// outside a menu focuses the `tabIndex` scroller it lands on, else nothing. + pub fn press_focuses_below(mut self) -> Self { + self.cold_mut().focus.below = true; + self + } + /// The control a [`El::modal`] focuses when it opens, as HTML's `autofocus` attribute in a + /// dialog: a Cancel button, say. Without one the modal focuses its first text field, else + /// its first Tab stop, or itself under [`Cx::web_focus`](crate::Cx::web_focus). + pub fn autofocus(mut self) -> Self { + self.cold_mut().focus.autofocus = true; + self + } + /// Keyboard-only ring, on this element or a visual child of the focused control. A + /// control with no ring of its own draws the default one (see [`El::no_focus_ring`]). + pub fn focus_ring(mut self, width: f32, offset: f32, color: Color) -> Self { + self.cold_mut().focus.ring = Some(Outline { width, offset, color }); + self.cold_mut().focus.within = false; + self.cold_mut().focus.within_keyboard = false; + self.cold_mut().focus.ring_off = false; + self.cold_mut().focus.ring_for = None; + self + } + /// A ring drawn while focus is on this element or anywhere inside it, whether the pointer or + /// the keyboard put it there, as CSS `:focus-within` draws a text field's box: e.g. + /// `focus_within_ring(1.0, -1.0, c)` for `outline: 1px solid; outline-offset: -1px`, a ring + /// just inside the border box. It isn't a Tab stop by itself. + pub fn focus_within_ring(mut self, width: f32, offset: f32, color: Color) -> Self { + self.cold_mut().focus.ring = Some(Outline { width, offset, color }); + self.cold_mut().focus.within = true; + self.cold_mut().focus.within_keyboard = false; + self.cold_mut().focus.ring_off = false; + self.cold_mut().focus.ring_for = None; + self + } + /// [`El::focus_within_ring`] that shows only while the keyboard put focus on this element or + /// inside it (a Tab, an arrow, `Tx::focus` with a ring), as a web field's own keyboard-focus + /// ring does: not for a click, a focus handed over without a ring, or the window coming back + /// to the front with focus where it was. A text field's frame (a prompt's) takes it. + pub fn focus_visible_within_ring(mut self, width: f32, offset: f32, color: Color) -> Self { + self = self.focus_within_ring(width, offset, color); + self.cold_mut().focus.within_keyboard = true; + self + } + /// A keyboard-only ring drawn on this element while the element keyed `key` (the last part of + /// its path) has focus, as a CSS sibling's `:has(:focus-visible) ~ ::after` ring: a scroll + /// region's ring drawn by an overlay painted after the header and the dock that cover the + /// region's own edges. Give the focused element [`El::no_focus_ring`]. This element isn't a + /// Tab stop by itself. + pub fn focus_ring_for(mut self, key: impl Into<String>, width: f32, offset: f32, color: Color) -> Self { + self = self.focus_ring(width, offset, color); + self.cold_mut().focus.ring_for = Some(Rc::from(key.into())); + self + } + /// While focus is on this element or anywhere inside it, from the pointer or the keyboard, + /// it draws none of its [`El::box_shadow`]s and no [`El::hover`] fill, as a CSS field whose + /// `:focus-within` rule sets `box-shadow: none` and whose hover rule is + /// `:not(:focus-within)`: the [`El::focus_within_ring`] stands in for its raised edge. + pub fn focus_within_flat(mut self) -> Self { + self.cold_mut().focus.flat_within = true; + self + } + /// No focus ring: not the default one, and not one set with [`El::focus_ring`]. A control + /// that shows focus its own way (a fill, an outline it animates) sets it on itself or on + /// the child that would draw the ring. + /// + /// Without it, a `focusable` element focused from the keyboard draws the default ring when + /// neither it nor a child (short of another focusable) sets `focus_ring`: the view's + /// [`Cx::focus_ring`](crate::Cx::focus_ring), else AppKit's, 3 points wide in + /// [`Cx::focus_color`](crate::Cx::focus_color), just outside its border box, following + /// its corner radii. Text fields, focused links, `focus_highlight` rows and the items of a `menu`, + /// `listbox`, `list`, `tree` or `grid` group draw none, as in AppKit: their caret, + /// highlight or selection shows focus. + pub fn no_focus_ring(mut self) -> Self { + self.cold_mut().focus.ring = None; + self.cold_mut().focus.within = false; + self.cold_mut().focus.ring_off = true; + self + } + /// Trap focus and make the background inert while mounted. Escape requests dismissal. + pub fn modal<S: 'static>(mut self, click_outside: bool, dismiss: impl Fn(&mut S) + 'static) -> Self { + self.handlers.modal = Some(ModalSpec { outside: click_outside, + dismiss: Rc::new(move |s, _| dismiss(downcast::<S>(s))) }); + self + } + /// [`El::modal`] whose dismissal gets the change's [`Tx`]: a dialog that closes at once + /// (`tx.instant()`), say. + pub fn modal_tx<S: 'static>(mut self, click_outside: bool, dismiss: impl Fn(&mut S, &mut Tx) + 'static) -> Self { + self.handlers.modal = Some(ModalSpec { outside: click_outside, + dismiss: Rc::new(move |s, tx| dismiss(downcast::<S>(s), tx)) }); + self + } + pub fn modal_click_outside(mut self, enabled: bool) -> Self { + if let Some(h) = self.handlers.get_mut_if_some() && let Some(m) = &mut h.modal { m.outside = enabled; } + self + } +} diff --git a/app/vendor/rune/crates/rune/src/el/grid.rs b/app/vendor/rune/crates/rune/src/el/grid.rs new file mode 100644 index 0000000..49f59e4 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/el/grid.rs @@ -0,0 +1,186 @@ +//! A terminal's screen as one element ([`grid`]): rows of cells on a fixed monospace grid, +//! painted directly instead of as an element per row and per wide cell. +//! +//! A row is its narrow cells' text with styled spans (one shaped line), the cells that must sit +//! exactly on their column (wide CJK, emoji, glyphs of other widths), background and selection +//! runs, and a vector layer over the text (box drawing, curly underlines). It draws exactly as +//! that row drew built from elements (`rich` line, a `text` per pinned cell, `el` fills, a +//! `canvas`): the same layouts, glyph masks and pixel snapping. A row is shaped once and keeps +//! its layout while the app hands back the same [`GridRow`], so a screen where one row changed +//! shapes that row only. + +use std::cell::RefCell; +use std::rc::Rc; + +use rune_taffy::prelude::*; + +use super::{El, TextSpec, base}; +use crate::color::Color; +use crate::shape::Shape; +use parley::Layout; + +use crate::text::{Ink, Span}; +use crate::tok::TextStyle; + +/// One row of a [`grid`]. Build it once per row the terminal shows and hand the same `Rc` back +/// while the row is unchanged: it keeps its shaped layout. +pub struct GridRow { + pub(crate) line: TextSpec, + pub(crate) cells: Vec<GridCell>, + pub(crate) fills: Vec<GridFill>, + pub(crate) over: Option<Shape>, + /// The row's shaped line and cells at the scale and width they were shaped for. + pub(crate) laid: RefCell<Option<LaidRow>>, + /// What the row drew last, to draw again while nothing it depends on changed. + pub(crate) drawn: RefCell<Option<DrawnRow>>, + /// [`GridRow::wraps`]. + pub(crate) wraps: bool, +} + +pub(crate) struct GridCell { + pub(crate) col: u16, + pub(crate) width: u16, + pub(crate) spec: TextSpec, +} + +#[derive(Clone, Copy)] +pub(crate) struct GridFill { + pub(crate) start: u16, + pub(crate) end: u16, + pub(crate) color: Color, +} + +/// A row's instances as it last painted them, with the key of everything they depend on (its +/// place, clip, opacity and the text system's `emit_key`) and the atlas pages its glyphs +/// sample, with their texels, for the frame that draws them again to keep resident. +pub(crate) struct DrawnRow { + pub(crate) key: u64, + pub(crate) instances: Vec<crate::render::Instance>, + pub(crate) pages: Vec<(u16, u32)>, + pub(crate) glyphs: usize, +} + +pub(crate) struct LaidRow { + pub(crate) scale: u32, + pub(crate) width: u32, + pub(crate) line: Rc<Layout<Ink>>, + pub(crate) cells: Vec<Rc<Layout<Ink>>>, +} + +impl GridRow { + /// A row whose narrow cells read `text` (a space for each empty or pinned cell), styled by + /// `spans` (colour, weight, italic, single underline) over `style`. + pub fn new(text: impl Into<String>, spans: Vec<Span>, style: TextStyle) -> GridRow { + let line = super::rich(text, spans).font(style).truncate_fade_width(0.0); + GridRow { line: spec_of(line), cells: Vec::new(), fills: Vec::new(), over: None, laid: RefCell::new(None), drawn: RefCell::new(None), wraps: false } + } + + /// A cell drawn on its own at column `col`, `width` columns wide: a wide or fallback glyph + /// that mustn't move the columns after it. The line holds a space for each of its columns. + pub fn cell(mut self, col: u16, width: u16, text: impl Into<String>, style: TextStyle, color: Color) -> GridRow { + self.cells.push(GridCell { col, width: width.max(1), spec: spec_of(super::text(text).font(style).color(color)) }); + self + } + + /// The row runs on into the next (the terminal wrapped a line longer than the screen is + /// wide): a screen reader reads the two as one line of text, with no line break between + /// them. Every other row ends its line. + pub fn wraps(mut self, wraps: bool) -> GridRow { + self.wraps = wraps; + self + } + + /// Fills columns `start..end` (a background run, or the selection over one) under the text. + pub fn fill(mut self, start: u16, end: u16, color: Color) -> GridRow { + if end > start { + self.fills.push(GridFill { start, end, color }); + } + self + } + + /// Vector strokes and fills over the text, in the row's points (box drawing, curly and + /// double underlines, strikethrough). + pub fn shape(mut self, shape: Shape) -> GridRow { + self.over = (!shape.is_empty()).then_some(shape); + self + } + + /// What a reader reads of the row: the line with each pinned cell's text in its columns, + /// trailing spaces dropped, and for each character the column it starts in and how many it + /// spans. + pub(crate) fn reading(&self) -> (String, Vec<(u16, u16)>) { + let mut cols: Vec<(String, u16)> = self.line.content.chars().map(|c| (c.to_string(), 1)).collect(); + for c in &self.cells { + let (at, w) = (usize::from(c.col), usize::from(c.width)); + if cols.len() < at + w { + cols.resize(at + w, (" ".to_owned(), 1)); + } + cols[at] = (c.spec.content.clone(), c.width); + cols[at + 1..at + w].iter_mut().for_each(|s| *s = (String::new(), 0)); + } + let end = cols.iter().rposition(|(s, _)| !s.trim().is_empty()).map_or(0, |i| i + 1); + let (mut text, mut places) = (String::new(), Vec::new()); + for (col, (s, w)) in cols.into_iter().take(end).enumerate() { + for (k, ch) in s.chars().enumerate() { + text.push(ch); + // Marks combining onto a cell's first character take no room of their own. + places.push((col as u16, if k == 0 { w } else { 0 })); + } + } + (text, places) + } +} + +/// `e`'s text, laid out left to right as a terminal's cells are (`paint_grid` lays it out again +/// in an element whose flow is right to left). +fn spec_of(e: El) -> TextSpec { + let mut spec = e.text.map(crate::cold::SharedBox::into_inner).expect("a text element has a spec"); + spec.dir = crate::el::step_text_dir(spec.dir, crate::el::TextDirEvent::Flatten(Some(crate::el::Flow::Ltr))); + spec +} + +/// What [`grid`] paints. +pub(crate) struct Grid { + pub(crate) cols: u16, + pub(crate) cell: [f32; 2], + pub(crate) rows: Vec<Rc<GridRow>>, + /// The cursor's cell (column, row), as the accessibility tree's caret. + pub(crate) caret: Option<(u16, u16)>, +} + +impl std::fmt::Debug for Grid { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("Grid").field("cell", &self.cell).field("rows", &self.rows.len()).finish() + } +} + +/// A terminal's screen: `rows` top to bottom, each `cell_h` points tall and `cols` columns of` +/// `cell_w` points wide from the element's left edge. Size the element like any box; rows past its +/// height are clipped by it as any content is. Accessibility reads it as a terminal with a +/// text line per row, each ending in a line break unless it [wraps](GridRow::wraps) on. +pub fn grid(cols: u16, cell_w: f32, cell_h: f32, rows: Vec<Rc<GridRow>>) -> El { + let mut e = base(FlexDirection::Row); + e.vis.cold_mut().grid = Some(Rc::new(Grid { cols, cell: [cell_w, cell_h], rows, caret: None })); + e.set_role_name("terminal"); + e +} + +impl El { + /// The cell (`col`, `row`) a [`grid`]'s cursor is on, which a screen reader follows as its + /// caret: it reads the character there and moves from it by character, word and line. It + /// draws nothing; leave it unset while the program hides its cursor. + pub fn grid_caret(mut self, col: u16, row: u16) -> Self { + if let Some(g) = self.vis.cold_mut().grid.as_mut().and_then(Rc::get_mut) { + g.caret = Some((col, row)); + } + self + } +} + +impl GridRow { + /// The index in [`Self::reading`]'s text of the character at column `col`: the one that + /// starts there or covers it, or the end of the text past it. + pub(crate) fn char_at(places: &[(u16, u16)], col: u16) -> usize { + places.iter().position(|&(c, w)| c + w.max(1) > col).unwrap_or(places.len()) + } +} diff --git a/app/vendor/rune/crates/rune/src/el/growth.rs b/app/vendor/rune/crates/rune/src/el/growth.rs new file mode 100644 index 0000000..4f3b05b --- /dev/null +++ b/app/vendor/rune/crates/rune/src/el/growth.rs @@ -0,0 +1,76 @@ +//! Growth stacks and their rows: `El::growth`, `El::streaming` and `El::arrives_whole`. The +//! heights are tracked in `crate::growth` and stepped in the runtime. + +use super::*; + +impl El { + /// The keyed face of a complete growth row. Consecutive such rows hold the seam + /// between their faces through a live reorder; an intervening row opens it as it passes. + /// Individual row identity, layout and accessibility order do not change. + pub fn joined_row_face(mut self, face: &'static str) -> Self { + self.vis.cold_mut().row_face = Some(face); + self + } + /// Make this column a growth stack (see [`GrowthSpec`]). Required alongside + /// [`El::virtualize`] on the same element. + pub fn growth(mut self, spec: GrowthSpec) -> Self { + self.cold_mut().growth = Some(Box::new(spec)); + self + } + /// Rounds each content- or length-sized in-flow child's height on a non-wrapping flex column + /// to a whole point (`(h + 0.5).floor()`, matching `Math.round`), inside Taffy's flexbox + /// solver, as TanStack Virtual's `measureElement` returning `Math.round(borderBoxSize.blockSize)` + /// places OpenCode Desktop's timeline rows (`app/src/session/timeline/virtualizer.tsx:362,370,1081`). + /// Padding, gaps and child margins keep their exact values; percentage heights, aspect-ratio + /// heights and flexed (`flex_grow` / `flex_shrink`) sizes stay fractional (base sizes round + /// before free space is shared). Taffy computes the container's own box, wrappers, siblings, + /// scroll extents, centring, `flex_grow`, and out-of-flow or anchored children from the + /// rounded item heights in the same layout pass, and a virtual list on such a column rounds + /// its `virtual_estimate` the same way, so with whole top, padding, gap and zero/whole child + /// margins (and no percentage, aspect-ratio or flexed row heights), every row's top, stored + /// virtual heights, unmeasured spacers and the list's extent are whole points (whole CSS px) + /// at any scale. Non-column or wrapping containers ignore the flag (with a debug warning), + /// and `Display::None` or out-of-flow children are skipped. A child's content keeps its own + /// layout from the child's top, so up to half a point hangs below its box or is left empty. + /// Off by default. + pub fn whole_rows(mut self) -> Self { + self.style.set_whole_rows(); + self + } + /// A growth-stack row that is streaming: slows near its target and reveals through the + /// feathered edge. + pub fn streaming(mut self, on: bool) -> Self { + self.flags.set(ElFlags::STREAMING, on); + self + } + /// A growth-stack row whose content arrives complete, like a sent message: its height + /// changes glide on the growth spring alone, without the speed limits that pace streaming + /// text, so a large insert and the pinned viewport following it move in one quick glide. + pub fn arrives_whole(mut self) -> Self { + self.flags.set(ElFlags::WHOLE, true); + self + } + /// A growth-stack row that folds open and shut, like a disclosure: its height changes glide + /// on its own `spring`, in place of the stack's, for the spring's own time however far + /// they go, keeping their velocity when a change reverses one mid-glide. Only what shows + /// moves: the part of a change below the window's bottom edge (where the row last drew) + /// lands at once, before the glide when shutting and after it when opening. Hold the row's + /// header with [`crate::Tx::keep_on_screen`] so its top stays put. Implies + /// [`El::arrives_whole`]. + pub fn fold_glide(mut self, spring: rune_motion::Spring) -> Self { + self.flags.set(ElFlags::WHOLE, true); + self.cold_mut().glide = Some(crate::growth::FoldGlide { spring, feather: self.cold.glide.and_then(|g| g.feather) }); + self + } + /// How deep, in points, a [`El::fold_glide`] row's moving bottom edge feathers as it folds + /// open or shut, in place of its stack's `StreamEdge::mask_max`. It deepens as the edge + /// starts moving and thins as it lands, so nothing is feathered at rest. Call after + /// `fold_glide`. + pub fn fold_feather(mut self, pt: f32) -> Self { + debug_assert!(self.cold.glide.is_some(), "fold_feather without fold_glide"); + if let Some(g) = self.cold.get_mut_if_some().and_then(|c| c.glide.as_mut()) { + g.feather = Some(pt.max(0.0)); + } + self + } +} diff --git a/app/vendor/rune/crates/rune/src/el/handler_set.rs b/app/vendor/rune/crates/rune/src/el/handler_set.rs new file mode 100644 index 0000000..a36b64a --- /dev/null +++ b/app/vendor/rune/crates/rune/src/el/handler_set.rs @@ -0,0 +1,145 @@ +//! Event, gesture, layout-watch and pointer-feedback handlers shared by `El` and `Node` behind +//! `Cold<Handlers>`, so elements without callbacks pay one pointer. +use crate::cold::Empty; +use crate::el::{ + AtBottomFn, Cursor, DragEndFn, DragFn, DragOutFn, DropSpec, LanguagesFn, LayoutFn, LayoutTxFn, ModalSpec, + PasteFn, PointerFn, PressFn, ScrollOffsetFn, SelectionChangeFn, SelectionCopy, VisibleRowsFn, + WindowFocusFn, +}; + +#[derive(Clone)] +pub(crate) struct Handlers { + pub on_paste: Option<PasteFn>, + pub on_window_focus: Option<WindowFocusFn>, + /// `El::on_spellcheck`: the app's spell checking setting and what flips it. + pub on_spellcheck: Option<(bool, WindowFocusFn)>, + /// `El::on_spellcheck_languages`: keeps the dictionaries a field's menu chose. + pub on_spellcheck_languages: Option<LanguagesFn>, + pub modal: Option<ModalSpec>, + pub on_press: Option<PressFn>, + pub on_double_press: Option<PressFn>, + pub on_secondary_press: Option<PointerFn>, + /// `El::on_middle_press`. + pub on_middle_press: Option<PressFn>, + pub on_hover: Option<PressFn>, + pub on_hover_change: Option<WindowFocusFn>, + /// Seconds the pointer must stay inside, then outside, before `on_hover_change` hears it. + pub hover_delay: [f32; 2], + pub on_pointer_move: Option<PointerFn>, + /// `on_wheel`, `on_magnify` and the other canvas handlers (`canvas_input.rs`). + pub gestures: Option<Box<crate::input::canvas_input::CanvasInput>>, + pub on_drag: Option<DragFn>, + pub drag_out: Option<DragOutFn>, + pub drag_threshold: Option<f32>, + /// `El::touch_drags_at_once`. + pub touch_at_once: bool, + /// `El::press_on_down`. + pub press_on_down: bool, + pub on_drag_start: Option<PressFn>, + pub on_drag_end: Option<DragEndFn>, + pub drop: Option<Box<DropSpec>>, + pub on_at_bottom: Option<AtBottomFn>, + /// `on_far_from_bottom`: its least distance, the key of the frame whose height counts in + /// place of the viewport's own (`on_far_from_bottom_under`), and its handler. + pub on_far_from_bottom: Option<(f32, Option<std::rc::Rc<str>>, AtBottomFn)>, + pub on_visible_rows: Option<VisibleRowsFn>, + pub on_layout: Option<LayoutTxFn>, + pub on_screen_layout: Option<LayoutFn>, + pub on_drawn_layout: Option<LayoutTxFn>, + /// `El::on_visible`: the element came on screen (`true`) or left it. + pub on_visible: Option<WindowFocusFn>, + /// `El::drawn_rect_into`: where each frame draws the element. + pub drawn_rect: Option<crate::Live<[f32; 4]>>, + pub on_scroll_offset: Option<ScrollOffsetFn>, + pub selection_copy: Option<SelectionCopy>, + pub on_selection_change: Option<SelectionChangeFn>, + pub cursor: Option<Cursor>, + pub press_scale: Option<f32>, + /// Debug builds: where the app set the handlers the commit warnings name. + #[cfg(debug_assertions)] + pub sites: HandlerSites, +} + +#[cfg(debug_assertions)] +type Site = Option<&'static std::panic::Location<'static>>; + +/// Where `on_hover`, `on_hover_change`, `on_pointer_move`, `on_layout`, `on_drawn_layout` and +/// `on_visible_rows` were set. +#[cfg(debug_assertions)] +#[derive(Clone, Copy, Default)] +pub(crate) struct HandlerSites { + pub hover: Site, + pub hover_change: Site, + pub pointer_move: Site, + pub layout: Site, + pub drawn_layout: Site, + pub visible_rows: Site, +} + +impl Handlers { + #[inline] + pub(crate) fn has_primary(&self) -> bool { + self.on_press.is_some() + || self.on_double_press.is_some() + || self.on_hover.is_some() + || self.on_drag.is_some() + || self.drag_out.is_some() + } + + #[inline] + pub(crate) fn takes_hit(&self) -> bool { + self.on_pointer_move.is_some() + || self.on_press.is_some() + || self.on_double_press.is_some() + || self.on_secondary_press.is_some() + || self.on_middle_press.is_some() + || self.on_hover.is_some() + || self.on_hover_change.is_some() + || self.on_drag.is_some() + || self.drag_out.is_some() + || self.modal.is_some() + || self.gestures.as_ref().is_some_and(|g| g.takes_gestures()) + } +} + +impl Empty for Handlers { + const EMPTY: &'static Self = &Handlers { + on_paste: None, + on_window_focus: None, + on_spellcheck: None, + on_spellcheck_languages: None, + modal: None, + on_press: None, + on_double_press: None, + on_secondary_press: None, + on_middle_press: None, + on_hover: None, + on_hover_change: None, + hover_delay: [0.0; 2], + on_pointer_move: None, + gestures: None, + on_drag: None, + drag_out: None, + drag_threshold: None, + touch_at_once: false, + press_on_down: false, + on_drag_start: None, + on_drag_end: None, + drop: None, + on_at_bottom: None, + on_far_from_bottom: None, + on_visible_rows: None, + on_layout: None, + on_screen_layout: None, + on_drawn_layout: None, + on_visible: None, + drawn_rect: None, + on_scroll_offset: None, + selection_copy: None, + on_selection_change: None, + cursor: None, + press_scale: None, + #[cfg(debug_assertions)] + sites: HandlerSites { hover: None, hover_change: None, pointer_move: None, layout: None, drawn_layout: None, visible_rows: None }, + }; +} diff --git a/app/vendor/rune/crates/rune/src/el/handlers.rs b/app/vendor/rune/crates/rune/src/el/handlers.rs new file mode 100644 index 0000000..8df5d8f --- /dev/null +++ b/app/vendor/rune/crates/rune/src/el/handlers.rs @@ -0,0 +1,305 @@ +//! Handlers: queued, run between frames with `&mut S`. + +use super::*; + +impl El { + pub fn on_press<S: 'static>(self, f: impl Fn(&mut S) + 'static) -> Self { + self.on_press_tx(move |s: &mut S, _tx: &mut Tx| f(s)) + } + #[inline] + pub fn on_press_tx<S: 'static>(mut self, f: impl Fn(&mut S, &mut Tx) + 'static) -> Self { + self.set_on_press_tx(f); + self + } + /// [`El::on_press_tx`] in place. + pub fn set_on_press_tx<S: 'static>(&mut self, f: impl Fn(&mut S, &mut Tx) + 'static) -> &mut Self { + self.handlers.on_press = Some(Rc::new(move |s, tx| f(downcast::<S>(s), tx))); + if self.role == RoleTag::GROUP { + self.role = RoleTag::BUTTON; + } + self + } + /// A press on a surface that isn't a control: a pane that clears a selection or takes + /// keyboard routing when clicked, a scrim that closes what it covers. It runs as + /// [`El::on_press`] does under the pointer, but the element stays what its role says (it + /// doesn't become a button), takes no keyboard focus and isn't a Tab stop; assistive + /// technology can still press it. + pub fn on_background_press<S: 'static>(self, f: impl Fn(&mut S) + 'static) -> Self { + self.on_background_press_tx(move |s: &mut S, _tx: &mut Tx| f(s)) + } + /// [`El::on_background_press`] with the transaction. + pub fn on_background_press_tx<S: 'static>(mut self, f: impl Fn(&mut S, &mut Tx) + 'static) -> Self { + self.handlers.on_press = Some(Rc::new(move |s, tx| f(downcast::<S>(s), tx))); + self.focusable(false) + } + /// Runs on the second of two presses on this element, as a double-click does: the second + /// press lands within the system double-click interval of the first and within 4 pt of it, + /// and releases inside. `on_press` still runs for each press, the first one right away, so a + /// row selects on the first click and opens on the second, as in AppKit. A third press starts + /// a new pair. Pointer only: the keyboard runs `on_press` (Space, and Return on a row). + pub fn on_double_press<S: 'static>(self, f: impl Fn(&mut S) + 'static) -> Self { + self.on_double_press_tx(move |s: &mut S, _tx: &mut Tx| f(s)) + } + pub fn on_double_press_tx<S: 'static>(mut self, f: impl Fn(&mut S, &mut Tx) + 'static) -> Self { + self.handlers.on_double_press = Some(Rc::new(move |s, tx| f(downcast::<S>(s), tx))); + self + } + /// A middle click (a browser's `auxclick` with the wheel button): the middle button went + /// down on this element, or one inside it that doesn't take the middle button itself, and + /// came up over it. A tab closes this way, a row opens in the background. A press that leaves + /// first runs nothing. It changes no focus, starts no drag (`on_drag` hears only the buttons + /// [`El::pointer_buttons`] names) and, where the platform has it, keeps the middle button's + /// autoscroll from starting. + pub fn on_middle_press<S: 'static>(mut self, f: impl Fn(&mut S, &mut Tx) + 'static) -> Self { + self.handlers.on_middle_press = Some(Rc::new(move |s, tx| f(downcast::<S>(s), tx))); + self + } + /// Receives Down, Move, then Up. Up also ends a cancelled gesture: always check + /// [`Drag::cancelled`] before committing a drop or notifying an application callback. + /// Save the original value on Down (in state, or [`Drag::data`]) and restore it on cancel. + /// Move commits are instant unless the handler calls [`Tx::animated`]. + pub fn on_drag<S: 'static>(mut self, f: impl Fn(&mut S, &mut Drag, &mut Tx) + 'static) -> Self { + self.handlers.on_drag = Some(Rc::new(move |s, d, tx| f(downcast::<S>(s), d, tx))); + self + } + /// [`El::on_drag`] for a component that doesn't read the app's state (a scroll bar that + /// only scrolls through its `Tx`), so it works in any app. + pub fn on_drag_any(mut self, f: impl Fn(&mut Drag, &mut Tx) + 'static) -> Self { + self.handlers.on_drag = Some(Rc::new(move |_, d, tx| f(d, tx))); + self + } + /// Drag this element out of the window into another app, as a file, image or text. Once + /// the pointer travels [`crate::drag_out::DRAG_THRESHOLD`] from the press, `f` reads the + /// state and returns what to carry (`None`: no drag this time, the press stays a press), + /// and the system takes over the pointer until the drop. The drag shows a snapshot of the + /// element unless the item sets [`crate::DragItem::image`]. + /// + /// ``` + /// # use rune::{DragItem, el::el}; + /// # struct App { bundle: std::path::PathBuf } + /// el().drag_out(|s: &App| Some(DragItem::new().file(&s.bundle))); + /// ``` + /// + /// A drag-out element never runs its `on_drag`; a press released before the threshold still + /// runs `on_press`. macOS only for now: on other platforms the system drag doesn't start, + /// and the element behaves as if it had no `drag_out`. Headless tools record `drag-out + /// <path>` in the trace and `dragOut` in the tree instead. Overlay panels start the same + /// session; see [`crate::drag_out`] for how far that path is tested. + pub fn drag_out<S: 'static>(mut self, f: impl Fn(&S) -> Option<crate::DragItem> + 'static) -> Self { + self.handlers.drag_out = Some(Rc::new(move |s| f(s.cast::<S>().expect("handler registered for a different state type than the app's")))); + self + } + /// How far (points, straight-line) the pointer travels from the press before this + /// element's [`El::drag_out`] starts, instead of [`crate::drag_out::DRAG_THRESHOLD`]. A + /// port of a native control that used another distance keeps its feel this way. + /// + /// ``` + /// # use rune::{DragItem, el::el}; + /// # struct App; + /// el().drag_out(|_: &App| Some(DragItem::new().text("row"))).drag_threshold(3.0); + /// ``` + /// A finger on this [`El::on_drag`] element drags it from where it lands: no 8-point slop, + /// no long press (a finger held still keeps dragging, as a game's paddle wants), and never a + /// pan of the page under it. A mouse is unchanged. + pub fn touch_drags_at_once(mut self) -> Self { + self.handlers.touch_at_once = true; + self + } + /// A menu button: a mouse's primary button runs [`El::on_press`] as it goes down, and that + /// press's release runs nothing (the web's Kobalte `Menu.Trigger` opens on `pointerdown`). + /// A press that's then cancelled or released elsewhere has already run it. A key, a screen + /// reader's Invoke and a finger's tap run it on the click, as without this. + pub fn press_on_down(mut self) -> Self { + self.handlers.press_on_down = true; + self + } + pub fn drag_threshold(mut self, points: f32) -> Self { + self.handlers.drag_threshold = Some(points.max(0.0)); + self + } + /// Called when a [`El::drag_out`] drag starts, after the drag image was taken, so the app + /// can style the source while it's dragged. Every start is followed by exactly one + /// [`El::on_drag_end`], also when the system couldn't start the session. + /// + /// ``` + /// # use rune::{DragItem, el::el}; + /// # struct App { file: std::path::PathBuf, dragging: bool } + /// # let s = App { file: "/tmp/a.txt".into(), dragging: false }; + /// el().opacity(if s.dragging { 0.28 } else { 1.0 }) + /// .drag_out(|s: &App| Some(DragItem::new().file(&s.file))) + /// .on_drag_start(|s: &mut App, _| s.dragging = true) + /// .on_drag_end(|s: &mut App, _, _| s.dragging = false); + /// ``` + pub fn on_drag_start<S: 'static>(mut self, f: impl Fn(&mut S, &mut Tx) + 'static) -> Self { + self.handlers.on_drag_start = Some(Rc::new(move |s, tx| f(downcast::<S>(s), tx))); + self + } + /// Called once when a [`El::drag_out`] drag ends, with what the drop did. + pub fn on_drag_end<S: 'static>(mut self, f: impl Fn(&mut S, crate::DragOutcome, &mut Tx) + 'static) -> Self { + self.handlers.on_drag_end = Some(Rc::new(move |s, outcome, tx| f(downcast::<S>(s), outcome, tx))); + self + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Phase { + Down, + Move, + Up, +} + +/// A pointer gesture on an element. `x`, `y`, `start_x`, `start_y`, `w` and `h` are in the +/// element's own layout points: from its top-left as drawn (after scrolling and live +/// offsets), divided by any scale it draws at, so they hold on a zoomed canvas. +#[derive(Clone, Copy, Debug)] +pub struct Drag { + pub phase: Phase, + pub x: f32, + pub y: f32, + pub w: f32, + pub h: f32, + pub start_x: f32, + pub start_y: f32, + /// Pointer travel since the press, in window points (independent of the element moving). + pub dx: f32, + pub dy: f32, + /// Scratch kept across one gesture's phases (e.g. a grab offset). + pub data: f32, + /// Which click of a run the press is, the same on every phase: 1, then 2 and 3 (and on, as + /// AppKit's `clickCount`) for presses on this element each within the double-click + /// interval and 4 pt of the one before. A press that drags past 4 pt ends the run. A text + /// view selects by words on 2 and lines on 3, and extends by them as the drag moves. + pub clicks: u32, + pub(crate) cancelled: bool, + /// The pointer in window points. + pub(crate) window: [f32; 2], + /// The pointer in desktop pixels, when a native window hosts the view. + pub(crate) screen: Option<(i32, i32)>, +} + +impl Drag { + /// On `Phase::Up`: the gesture ended without a drop (Escape, the window lost focus, or the + /// pointer was taken away). Put back whatever the drag moved. + pub fn cancelled(&self) -> bool { + self.cancelled + } + + /// The pointer in window points from the window's top-left, whatever scale the element + /// draws at. + pub fn window_point(&self) -> [f32; 2] { + self.window + } + + /// The pointer in physical desktop pixels, the space `WindowOptions::position` and + /// `WindowHandle::set_position` take: for opening a window under the pointer, as a tab + /// dragged out of its strip does. `None` without a native window (headless runs, the web) + /// and where the system hides window positions (Wayland). + pub fn screen_point(&self) -> Option<(i32, i32)> { + self.screen + } +} + +/// What a press on an element does to the window (`El::window_drag`, `El::no_window_drag`). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(crate) enum WindowDrag { + /// Nothing of its own: a press goes to what's under it. + #[default] + None, + /// A press moves the window, and a double press zooms it. + Drag, + /// A press stays here, inside a `Drag` element, and does nothing to the window. + NoDrag, +} + +pub(crate) type PressFn = Rc<dyn Fn(crate::states::States<'_>, &mut Tx)>; +pub(crate) type InputKeyFn = Rc<dyn Fn(crate::states::States<'_>, &crate::KeyEvent, &mut Tx) -> bool>; +pub(crate) type StepFn = Rc<dyn Fn(crate::states::States<'_>, i32, &mut Tx)>; +pub(crate) type StepLimitFn = Rc<dyn Fn(crate::states::States<'_>, bool, &mut Tx)>; + +/// A press position in window points, suitable for a context-menu anchor. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct PointerPress { + pub x: f32, + pub y: f32, +} + +/// Where the pointer is, for [`El::on_pointer_move_local`] and +/// [`El::on_secondary_press_local`]: `x` and `y` in the element's own layout points, as +/// [`Drag`] and [`crate::WheelEvent`] give them (from its top-left as drawn, divided by any +/// scale it draws at, so they hold on a zoomed canvas), and the same point in window points +/// for a context menu's anchor. +#[non_exhaustive] +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub struct PointerEvent { + pub x: f32, + pub y: f32, + pub window_x: f32, + pub window_y: f32, +} + +impl PointerEvent { + /// The point in window points, as `on_pointer_move` and `on_secondary_press` give it: a + /// popup or context menu's anchor. + pub fn window(&self) -> PointerPress { + PointerPress { x: self.window_x, y: self.window_y } + } +} + +pub(crate) type PointerFn = Rc<dyn Fn(crate::states::States<'_>, PointerEvent, &mut Tx)>; +pub(crate) type DragFn = Rc<dyn Fn(crate::states::States<'_>, &mut Drag, &mut Tx)>; +pub(crate) type DragOutFn = Rc<dyn Fn(crate::states::StatesRef<'_>) -> Option<crate::DragItem>>; +pub(crate) type DragEndFn = Rc<dyn Fn(crate::states::States<'_>, crate::DragOutcome, &mut Tx)>; + +impl El { + /// On the root, receive native window activation/deactivation (not text-field focus). + /// Also works on interactive overlays. Headless hosts may call Runtime::window_focus. + pub fn on_window_focus<S: 'static>(mut self, f: impl Fn(&mut S, bool, &mut Tx) + 'static) -> Self { + self.handlers.on_window_focus = Some(Rc::new(move |s, focused, tx| f(downcast::<S>(s), focused, tx))); + self + } + /// On the root (or modal root), handle paste when no text field is focused. + /// Native clipboard reads are asynchronous. Script `paste` uses the same handler. + /// It hears the plain text; [`El::on_paste_content`] hears every form. + pub fn on_paste<S: 'static>(mut self, f: impl Fn(&mut S, &str, &mut Tx) + 'static) -> Self { + self.handlers.on_paste = Some(PasteFn { + rich: false, + call: Rc::new(move |s, content, tx| { + content.has_plain() && { f(downcast::<S>(s), content.text(), tx); true } + }), + }); + self + } + /// [`El::on_paste`] with everything the clipboard held: plain text and, when the source + /// offered them, sanitised HTML and RTF. Replaces an `on_paste` on the same element. + pub fn on_paste_content<S: 'static>(mut self, f: impl Fn(&mut S, &crate::ClipboardContent, &mut Tx) + 'static) -> Self { + self.handlers.on_paste = Some(PasteFn { + rich: true, + call: Rc::new(move |s, content, tx| { f(downcast::<S>(s), content, tx); true }), + }); + self + } + /// Secondary release inside the captured element (right-click or macOS control-click), at a + /// point in window points: a context menu's anchor. [`El::on_secondary_press_local`] gives + /// the element's own points as well. The Menu key and Shift+F10 call it too, while this + /// element or one inside it is focused and no key handler took the key, at the focused + /// element's bottom-left. + pub fn on_secondary_press<S: 'static>(mut self, f: impl Fn(&mut S, PointerPress, &mut Tx) + 'static) -> Self { + self.handlers.on_secondary_press = Some(Rc::new(move |s, p, tx| { + f(downcast::<S>(s), p.window(), tx); + })); + self + } + /// [`El::on_secondary_press`] with the point in this element's own layout points too, as + /// [`Drag`] gives them, so a canvas finds what was right-clicked at any zoom. Open the menu + /// at [`PointerEvent::window`]. + /// + /// ```ignore + /// .on_secondary_press_local(|s: &mut Canvas, p, tx| { + /// s.menu = Some((s.shape_at(p.x, p.y), p.window())); + /// }) + /// ``` + pub fn on_secondary_press_local<S: 'static>(mut self, f: impl Fn(&mut S, PointerEvent, &mut Tx) + 'static) -> Self { + self.handlers.on_secondary_press = Some(Rc::new(move |s, p, tx| f(downcast::<S>(s), p, tx))); + self + } +} diff --git a/app/vendor/rune/crates/rune/src/el/help.rs b/app/vendor/rune/crates/rune/src/el/help.rs new file mode 100644 index 0000000..2b12d3b --- /dev/null +++ b/app/vendor/rune/crates/rune/src/el/help.rs @@ -0,0 +1,98 @@ +//! Tooltip text, rows and keycaps. + +use super::El; + +/// Parts a help text from each of its [`El::help_keys`] keycaps. +pub(crate) const HELP_KEY: char = '\u{1f}'; + +/// Parts a help text's rows ([`El::help_row`]). +pub(crate) const HELP_ROW: char = '\u{1e}'; + +/// A help text as words: each row's keycaps after it, a space apart, and its rows a line apart. +pub(crate) fn help_words(help: &str) -> std::borrow::Cow<'_, str> { + if help.contains([HELP_KEY, HELP_ROW]) { help.replace(HELP_KEY, " ").replace(HELP_ROW, "\n").into() } else { help.into() } +} + +impl El { + /// A tooltip shown after the system's hover delay while the pointer rests on this element, + /// as SwiftUI's `.help`. A press, scroll, key or the pointer leaving hides it; it takes no + /// input itself. On macOS it is AppKit's own tooltip; elsewhere Rune draws it. The element + /// tree (`Runtime::elements`, `--tree`) carries it as the element's help text. + #[inline] + pub fn help(mut self, text: impl Into<String>) -> Self { + self.set_help(text); + self + } + /// [`El::help`] in place. + pub fn set_help(&mut self, text: impl Into<String>) -> &mut Self { + let text = text.into(); + if !text.is_empty() || !self.cold.is_empty() { + let cold = self.cold_mut(); + cold.help = (!text.is_empty()).then_some(text); + cold.help_cut = false; + } + self + } + /// [`El::help`] that shows only while this text is cut short ([`truncate`](Self::truncate), `max_lines` + /// or `truncate_fade`), as AppKit's expansion tooltips show a table cell's whole text. + pub fn help_when_truncated(self, text: impl Into<String>) -> Self { + let mut e = self.help(text); + e.cold_mut().help_cut = true; + e + } + /// Another row under this element's [`El::help`] tooltip, as a web tooltip lists two + /// commands, each with its own keybind: + /// `.help("Save").help_keys(["Enter"]).help_row("Send").help_keys(["Ctrl", "Enter"])`. Rows + /// stack [`HelpLook::row_gap`](crate::HelpLook::row_gap) apart, each its words then its + /// keycaps, from the tooltip's start edge. Call it after `help`, which replaces every row. + /// The element tree and assistive technology read the rows a line apart. Without `help` + /// first, it sets the first row. + pub fn help_row(mut self, text: impl Into<String>) -> Self { + let text = text.into(); + match self.cold.get_mut_if_some().and_then(|c| c.help.as_mut()) { + Some(h) => { + h.push(HELP_ROW); + h.push_str(&text); + } + None => { + self.set_help(text); + } + } + self + } + /// Keycaps drawn after this element's [`El::help`] text, as a web tooltip shows its + /// command's keybind: `.help("Toggle review").help_keys(["Ctrl", "Shift", "R"])`. Call it + /// after `help`, which replaces them, or after a [`El::help_row`], for that row's keys. The + /// element tree and assistive technology read them after the text, a space apart. + pub fn help_keys<K: Into<String>>(mut self, keys: impl IntoIterator<Item = K>) -> Self { + if let Some(h) = self.cold.get_mut_if_some().and_then(|c| c.help.as_mut()) { + for k in keys.into_iter().map(Into::into).filter(|k| !k.is_empty()) { + h.push(HELP_KEY); + h.push_str(&k); + } + } + self + } + /// Shows this element's [`El::help`] tooltip above it, 4 points clear, and below only when + /// there's no room above, as a web page's `placement="top"` tooltip sits over its button. + /// Short for `help_side(Side::Top)`. + pub fn help_above(self) -> Self { + self.help_side(crate::Side::Top) + } + /// Keeps the tooltip showing whatever the pointer does while `open` is true, as a + /// `Tooltip forceOpen` does: a Copy button's "Copied" for a moment after the press, even + /// though a press hides a tooltip. Only one shows at a time; with several, the first drawn. + pub fn help_open(mut self, open: bool) -> Self { + if open || !self.cold.is_empty() { self.cold_mut().help_open = open; } + self + } + /// Shows this element's [`El::help`] tooltip on `side` of it, as a web page's `placement` + /// does: under it ([`HelpLook::gap`](crate::HelpLook::gap)'s first gap clear, the default), + /// or above it, or left or right of it (its second gap clear), on the opposite side when + /// there's no room on `side`. A tooltip under or above it is centred across it; one left or + /// right of it, centred down it (`placement="right"`). Each stays inside the window. + pub fn help_side(mut self, side: crate::Side) -> Self { + self.cold_mut().help_side = (side != crate::Side::Bottom).then_some(side); + self + } +} diff --git a/app/vendor/rune/crates/rune/src/el/input.rs b/app/vendor/rune/crates/rune/src/el/input.rs new file mode 100644 index 0000000..f634ce6 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/el/input.rs @@ -0,0 +1,224 @@ +//! Text-field construction, security and editing callbacks. + +use super::*; + +/// A text field bound to a [`TextEdit`] in app state. +#[derive(Clone)] +pub struct InputSpec { + /// Text edits are immediate, but dependent layout (e.g. filtered results) may animate. + pub animate_layout: bool, + pub edit: TextEdit, + pub placeholder: String, + pub placeholder_color: Color, + /// [`El::placeholder_font`]: the placeholder's own style, as CSS's `::placeholder`; else the field's. + pub placeholder_style: Option<TextStyle>, + pub caret: Color, + pub selection: Color, + /// One unwrapped line that scrolls sideways to keep the caret visible, like `<input>`. + pub single_line: bool, + /// `placeholder_color`, and `caret` with `selection`, came from [`El::placeholder`] and + /// [`El::caret`]; the others follow the window's foreground ([`Cx::foreground`](crate::Cx::foreground)). + pub(crate) placeholder_inked: bool, + pub(crate) caret_inked: bool, + pub(crate) revealed_override: Option<bool>, + pub(crate) decorations: Vec<Span>, + pub(crate) rich_style: crate::edit::RichStyle, + pub(crate) pill_icon: Option<PillIconFn>, + pub(crate) pill_style: Option<PillStyleFn>, + pub(crate) on_pill_secondary: Option<PillSecondaryFn>, + pub(crate) access: Option<EditFn>, + pub(crate) submit: Option<PressFn>, + pub(crate) key: Option<InputKeyFn>, + pub(crate) change: Option<PressFn>, + pub(crate) paste: Option<InputPasteFn>, + /// `El::spellcheck`: the platform's checker marks misspelled words. + pub(crate) spellcheck: bool, + /// [`El::selection_style`]: the selection's highlight and ink, by window focus, over `selection`. + pub(crate) selection_style: Option<SelectionStyle>, +} + +impl std::fmt::Debug for InputSpec { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("InputSpec") + .field("animate_layout", &self.animate_layout) + .field("edit", &self.edit) + .field("placeholder", &self.placeholder) + .field("placeholder_color", &self.placeholder_color) + .field("caret", &self.caret) + .field("selection", &self.selection) + .field("single_line", &self.single_line) + .finish_non_exhaustive() + } +} + +/// A text field showing `edit`; route edits back with `.on_edit(|s| &mut s.field)`. +/// +/// Multi-line by default (see [`El::single_line`]). Plain Return in a paragraph submits (calling +/// [`El::on_submit`], or pressing the [`El::default_button`] when none is set) while Shift+Return +/// and Option+Return insert a line break; a document editor that wants plain Return to break +/// paragraphs attaches `.on_submit(|s, _| s.field.insert("\n"))`. +pub fn text_input(edit: &TextEdit, style: TextStyle) -> El { + // An app may have assigned `edit.text` directly: clamp stale marks, blocks and caret to it. + let mut edit = edit.clone(); + edit.set_single_line(false); + edit.sync_invariants(); + let (content, _) = edit.display(); + let mut e = text(content).font(style); + e.role = RoleTag::TEXTBOX; + e.cold_mut().a11y.secure = edit.is_secure(); + if let Some(t) = &mut e.text { + t.wrap = true; + t.wrap_anywhere = edit.is_secure(); + t.redacted = edit.is_secure(); + } + e.cold_mut().input = Some(Box::new(InputSpec { + animate_layout: false, + edit, + placeholder: String::new(), + placeholder_color: Color::WHITE.alpha(0.4), + placeholder_style: None, + caret: Color::WHITE, + selection: DEFAULT_SELECTION, + single_line: false, + placeholder_inked: false, + caret_inked: false, + revealed_override: None, + decorations: Vec::new(), + rich_style: crate::edit::RichStyle::default(), + pill_icon: None, + pill_style: None, + on_pill_secondary: None, + access: None, + submit: None, + key: None, + change: None, + paste: None, + spellcheck: false, + selection_style: None, + })); + e.sync_input_pills(); + e.sync_input_rich(); + e +} + +/// Fits a multi-line [`text_input`] to its text: `min_lines` tall at least, growing with each +/// wrapped line up to `max_lines`, then scrolling inside with the caret kept in view. The height +/// springs on the element's motion. Returns `field` inside a scroll viewport keyed `"scroll"`, so +/// key the field and attach its handlers first. A smaller `.max_h(..)` caps it in points. +#[cfg_attr(debug_assertions, track_caller)] +pub fn auto_grow(field: El, min_lines: usize, max_lines: usize) -> El { + let line = field.text.as_ref().map_or(0.0, |t| t.style.line_px()); + let (min, max) = (min_lines.max(1), max_lines.max(min_lines.max(1))); + col().key("scroll").w_full().shrink().min_h(min as f32 * line).max_h(max as f32 * line) + .scroll(ScrollSpec { stick_bottom: false }) + .child(field.animate_edit_layout()) +} + +/// Pins a closure to the signature [`El::on_edit`] needs, so Rust ties the returned borrow to +/// the state: `.on_edit(edit_access(move |s: &mut App| &mut s.rows[i].name))`. +pub fn edit_access<S, F: for<'a> Fn(&'a mut S) -> &'a mut TextEdit>(f: F) -> F { + f +} + +impl El { + /// On the root or around text fields: the app's spell checking setting, `on`, which the + /// fields' menus show as a Spellcheck item with a check mark, as a browser's do. Picking it + /// calls `f` with the setting flipped; the app keeps it and passes it to its fields' + /// [`El::spellcheck`]. + pub fn on_spellcheck<S: 'static>(mut self, on: bool, f: impl Fn(&mut S, bool, &mut Tx) + 'static) -> Self { + self.handlers.on_spellcheck = Some((on, Rc::new(move |s, on, tx| f(downcast::<S>(s), on, tx)))); + self + } + /// Beside [`El::on_spellcheck`], where the platform has dictionaries to choose + /// ([`crate::spell::available_languages`]): the fields' menus add a Spellcheck Languages + /// submenu, as Chromium's do off macOS. Picking a dictionary checks with the new choice at + /// once ([`crate::spell::set_languages`]) and calls `f` with it, for the app to keep and + /// pass to `set_languages` at its next launch. + pub fn on_spellcheck_languages<S: 'static>(mut self, f: impl Fn(&mut S, Vec<String>, &mut Tx) + 'static) -> Self { + self.handlers.on_spellcheck_languages = Some(Rc::new(move |s, tags, tx| f(downcast::<S>(s), tags, tx))); + self + } + /// Mask a text element or text input before layout; disable undo, copy, cut, selection and + /// IME composition, omit accessibility text, redact [`Debug`], bypass layout/raster caches, + /// and zeroize owned buffers on conceal and drop. + /// + /// Non-empty read-only [`text`] and [`rich`] labels show a fixed twelve-bullet mask on + /// one line, hiding their length as well as their content. Explicit labels and help must + /// describe the field, not contain its secret value. Links and rolling text are disabled. + /// Pair with [`revealed`](Self::revealed) to toggle plaintext display. + pub fn secure(mut self) -> Self { + self.cold_mut().a11y.secure = true; + if let Some(input) = self.cold.get_mut_if_some().and_then(|c| c.input.as_deref_mut()) { + input.edit.set_secure(true); + let single = input.single_line; + if let Some(text) = &mut self.text { + text.replace_content(input.edit.display().0); + text.redacted = true; + if !single { + text.wrap_anywhere = true; + } + } + self.sync_input_pills(); + self.sync_input_rich(); + } else if let Some(text) = &mut self.text { + text.redacted = true; + if text.selectable { + text.selectable = false; + if self.handlers.cursor == Some(Cursor::Text) { + self.handlers.cursor = None; + } + } + } + self + } + + /// Show the plain characters of a [`secure`](Self::secure) text element or text input while + /// keeping all other secure protections (no undo, copy, cut, selection, IME or accessibility + /// text, redacted [`Debug`], uncached shaping/raster, and zeroized buffers). Prefer + /// [`TextEdit::revealed`] or [`TextEdit::set_revealed`] when an input model owns the state. + pub fn revealed(mut self, revealed: bool) -> Self { + if let Some(input) = self.cold.get_mut_if_some().and_then(|c| c.input.as_deref_mut()) { + input.edit.set_revealed(revealed); + input.revealed_override = Some(revealed); + if let Some(text) = &mut self.text { + text.replace_content(input.edit.display().0); + } + self.sync_input_pills(); + self.sync_input_rich(); + } else if let Some(text) = &mut self.text { + text.cold.secure_revealed = revealed; + } + self + } + /// Called after a focused field's text changes, with the updated model available. + pub fn on_input_change<S: 'static>(mut self, f: impl Fn(&mut S, &mut Tx) + 'static) -> Self { + if let Some(input) = self.cold.get_mut_if_some().and_then(|c| c.input.as_deref_mut()) { + input.change = Some(Rc::new(move |s, tx| f(downcast::<S>(s), tx))); + } + self + } + /// Handle a paste into this focused text field before the editor, with every form the + /// clipboard held ([`ClipboardContent`](crate::ClipboardContent): plain text, and sanitised + /// HTML and RTF when the source offered them). Return true when the app took it; false lets + /// the editor paste the plain text as usual. Without it a field pastes plain text only. + /// + /// ```ignore + /// text_input(&s.draft).on_input_paste(|s: &mut Chat, content, _| match content.html() { + /// Some(html) => { s.draft_rich.paste_html(html, content.text()); true } + /// None => false, + /// }) + /// ``` + pub fn on_input_paste<S: 'static>(mut self, f: impl Fn(&mut S, &crate::ClipboardContent, &mut Tx) -> bool + 'static) -> Self { + if let Some(input) = self.cold.get_mut_if_some().and_then(|c| c.input.as_deref_mut()) { + input.paste = Some(Rc::new(move |s, content, tx| f(downcast::<S>(s), content, tx))); + } + self + } + /// Handle a focused text field's key before the editor. Return true to consume it. + pub fn on_input_key<S: 'static>(mut self, f: impl Fn(&mut S, &crate::KeyEvent, &mut Tx) -> bool + 'static) -> Self { + if let Some(input) = self.cold.get_mut_if_some().and_then(|c| c.input.as_deref_mut()) { + input.key = Some(Rc::new(move |s, key, tx| f(downcast::<S>(s), key, tx))); + } + self + } +} diff --git a/app/vendor/rune/crates/rune/src/el/isolates.rs b/app/vendor/rune/crates/rune/src/el/isolates.rs new file mode 100644 index 0000000..c6a40c6 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/el/isolates.rs @@ -0,0 +1,138 @@ +//! `El::isolate`: a run of a static text that keeps its own order whatever text is around it, as +//! HTML's `<bdi>` and CSS's `unicode-bidi: isolate` keep a name, a path or a command whole. +use std::ops::Range; + +use super::*; + +/// UTF-8 length of each isolate mark (LRI, RLI, FSI and PDI are all three bytes). +const MARK: u32 = 3; + +impl El { + /// Lays bytes `range` of a [`text`](crate::text) or [`rich`](crate::rich) element out as an + /// isolate (UAX #9 LRI, RLI or FSI .. PDI): it reads in `dir` (`Auto` from its own first + /// strong character) and the text around it reads as if it were one neutral character, so + /// `src/app.ts`, `-v` or `npm install` in an Arabic sentence keeps its own order, and an + /// Arabic name in an English one doesn't take the punctuation after it. A paragraph's own + /// direction skips it. The marks draw nothing and copying leaves them out. + /// + /// Ranges are authored UTF-8 bytes on char boundaries, as spans and links are; an empty or + /// out-of-range one, or one that crosses another isolate, is skipped (nest none). A pill + /// ([`El::pill`]) is an `Auto` isolate unless one is set over it. On a field this does + /// nothing: a field isolates its own pills. + /// + /// ```ignore + /// rich(text, spans).isolate(code.clone(), Direction::Ltr) + /// ``` + pub fn isolate(mut self, range: Range<usize>, dir: Direction) -> Self { + if self.cold.input.is_some() { + return self; + } + let Some(t) = &mut self.text else { return self }; + let ok = range.start < range.end && range.end <= t.content.len() && t.content.is_char_boundary(range.start) && t.content.is_char_boundary(range.end); + let (a, b) = (range.start as u32, range.end as u32); + if !ok || t.cold.isolates.iter().any(|&(s, e, _)| s < b && a < e) { + return self; + } + let at = t.cold.isolates.partition_point(|r| r.0 < a); + t.cold.isolates.insert(at, (a, b, dir)); + t.shape = None; + self + } +} + +impl TextSpec { + /// Writes each isolate's marks into `content` (its opening mark before it, PDI after), moves + /// every byte range onto the marked text, and leaves the marks out of copies. Pills without + /// an isolate over them become `Auto` isolates. Once applied there are none left to apply. + pub(crate) fn apply_isolates(&mut self) { + if self.redacted || self.cold.advance_in.is_some() || (self.cold.isolates.is_empty() && self.cold.pills.iter().all(|p| p.bare.is_some())) { + return; + } + let mut isolates = std::mem::take(&mut self.cold.isolates); + // A text laid out again keeps the marks it has. + let marked_pill = |p: &crate::text::PillChip| { + self.content[..p.start as usize].ends_with(['\u{2066}', '\u{2067}', '\u{2068}']) && self.content[p.end as usize..].starts_with('\u{2069}') + }; + for p in self.cold.pills.iter().filter(|p| p.bare.is_none() && !marked_pill(p)) { + if !isolates.iter().any(|&(a, b, _)| a < p.end && p.start < b) { + let at = isolates.partition_point(|r| r.0 < p.start); + isolates.insert(at, (p.start, p.end, Direction::Auto)); + } + } + if isolates.is_empty() { + return; + } + let marked = Marks(&isolates); + let mut content = String::with_capacity(self.content.len() + (2 * MARK as usize) * isolates.len()); + let mut at = 0; + for &(a, b, dir) in &isolates { + content.push_str(&self.content[at..a as usize]); + content.push(match dir { + Direction::Ltr => '\u{2066}', + Direction::Rtl => '\u{2067}', + Direction::Auto => '\u{2068}', + }); + content.push_str(&self.content[a as usize..b as usize]); + content.push('\u{2069}'); + at = b as usize; + } + content.push_str(&self.content[at..]); + for s in &mut self.spans { + (s.start, s.end) = marked.range(s.start, s.end); + } + let cold = &mut self.cold; + for l in &mut cold.links { + (l.start, l.end) = marked.range(l.start, l.end); + } + for r in &mut cold.uncopied { + *r = marked.range(r.0, r.1); + } + for r in &mut cold.rings { + (r.0, r.1) = marked.range(r.0, r.1); + } + for r in &mut cold.strikes { + (r.0, r.1) = marked.range(r.0, r.1); + } + for h in &mut cold.highlights { + (h.start, h.end) = marked.range(h.start, h.end); + } + for p in &mut cold.pills { + (p.start, p.end) = marked.range(p.start, p.end); + } + for (k, &(a, b, _)) in isolates.iter().enumerate() { + // Each mark sits after the marks of the isolates before this one. + let before = 2 * MARK * k as u32; + let at = cold.uncopied.partition_point(|r| r.0 < a + before); + cold.uncopied.insert(at, (a + before, a + before + MARK)); + let at = cold.uncopied.partition_point(|r| r.0 < b + before + MARK); + cold.uncopied.insert(at, (b + before + MARK, b + before + 2 * MARK)); + } + self.content = content; + self.shape = None; + } +} + +/// The sorted, disjoint isolates whose marks a text now holds, to move byte ranges with. +struct Marks<'a>(&'a [(u32, u32, Direction)]); + +impl Marks<'_> { + /// Authored range `start..end` in the marked text. A range inside an isolate stays inside + /// its marks; one that holds an isolate's end holds its PDI, and one that starts at an + /// isolate's start without ending inside it starts before the opening mark. + fn range(&self, start: u32, end: u32) -> (u32, u32) { + let shift = |p: u32, open_at_p: bool, close_at_p: bool| { + let opens = self.0.iter().filter(|r| r.0 < p || (open_at_p && r.0 == p)).count() as u32; + let closes = self.0.iter().filter(|r| r.1 < p || (close_at_p && r.1 == p)).count() as u32; + p + MARK * (opens + closes) + }; + let inside = |r: &&(u32, u32, Direction)| r.0 <= start && end <= r.1; + let within = self.0.iter().find(inside); + // A start at an isolate's start is inside it only when the range ends inside it; a + // start at an isolate's end is past its PDI. + let s = shift(start, within.is_some_and(|r| r.0 == start), true); + // An end at an isolate's end takes its PDI unless the range lies inside the isolate; an + // end at an isolate's start stops before its opening mark. + let e = shift(end, false, within.is_none_or(|r| r.1 != end)); + (s, e.max(s)) + } +} diff --git a/app/vendor/rune/crates/rune/src/el/layout.rs b/app/vendor/rune/crates/rune/src/el/layout.rs new file mode 100644 index 0000000..9427df2 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/el/layout.rs @@ -0,0 +1,757 @@ +//! Layout builders: size, padding, gaps, flex and grid placement, absolute pins, and the +//! pointer, cursor and hover handlers that sit with them. + +use super::*; + +impl El { + #[inline] + pub fn w(mut self, w: f32) -> Self { + self.set_w(w); + self + } + /// [`El::w`] in place. + #[inline] + pub fn set_w(&mut self, w: f32) -> &mut Self { + self.style.set_width(length(w)); + self + } + #[inline] + pub fn h(mut self, h: f32) -> Self { + self.set_h(h); + self + } + /// [`El::h`] in place. + #[inline] + pub fn set_h(&mut self, h: f32) -> &mut Self { + self.style.set_height(length(h)); + self + } + #[inline] + pub fn size(mut self, w: f32, h: f32) -> Self { + self.set_size(w, h); + self + } + /// [`El::size`] in place. + #[inline] + pub fn set_size(&mut self, w: f32, h: f32) -> &mut Self { + self.set_w(w).set_h(h) + } + /// Width over height, as CSS `aspect-ratio`: with one side set (or stretched by the parent) + /// the other follows; a box with both sides set ignores it. A picture that sets only one + /// side already takes its image's ratio ([`pixels`](Self::pixels)); use this for video or + /// any other box. Anything not positive removes it. + #[inline] + pub fn aspect_ratio(mut self, ratio: f32) -> Self { + self.set_aspect_ratio(ratio); + self + } + /// [`El::aspect_ratio`] in place. + #[inline] + pub fn set_aspect_ratio(&mut self, ratio: f32) -> &mut Self { + self.style.set_aspect_ratio((ratio.is_finite() && ratio > 0.0).then_some(ratio)); + self + } + /// The largest box at `ratio` (width over height) that fits the room the element is given, + /// as SwiftUI's `.aspectRatio(ratio, contentMode: .fit)` or CSS `object-fit: contain` for + /// the element itself. The room is the free space along the parent's main axis and its + /// whole cross side, within `max_w` and `max_h`; siblings keep theirs, so a caption under + /// a picture sits under the picture. The parent's alignment places the fitted box. Use it + /// for a picture or video in a bounded cell: `el().aspect_fit(w / h).pixels_fit(p, Fill)`. + /// In a column with no bounded height, bound it with `max_h`. It sets both sides, so `w` + /// and `h` don't apply; anything not positive removes it. + pub fn aspect_fit(mut self, ratio: f32) -> Self { + let ratio = if ratio.is_finite() && ratio > 0.0 { ratio } else { 0.0 }; + if ratio > 0.0 || !self.cold.is_empty() { + self.cold_mut().aspect_fit = ratio; + } + self + } + #[inline] + pub fn w_full(mut self) -> Self { + self.set_w_full(); + self + } + /// [`El::w_full`] in place. + #[inline] + pub fn set_w_full(&mut self) -> &mut Self { + self.style.set_width(percent(1.0)); + self + } + /// Width as a fraction of the parent's (CSS `width: 40%` is `.w_frac(0.4)`). + #[inline] + pub fn w_frac(mut self, f: f32) -> Self { + self.set_w_frac(f); + self + } + /// [`El::w_frac`] in place. + #[inline] + pub fn set_w_frac(&mut self, f: f32) -> &mut Self { + self.style.set_width(percent(f)); + self + } + #[inline] + pub fn h_full(mut self) -> Self { + self.set_h_full(); + self + } + /// [`El::h_full`] in place. + #[inline] + pub fn set_h_full(&mut self) -> &mut Self { + self.style.set_height(percent(1.0)); + self + } + /// Take a `g` share of the free space along the parent's main axis (CSS `flex: g 1 0`). + /// + /// This also sets flex-basis to 0 and allows shrinking, so the element's own content does + /// not size it: it is only as big as the space the parent has left over. Inside a parent + /// with no bounded height (an auto-height column) there is no free space, and a grown + /// `.scroll(..)` viewport collapses to 0 pt. Bound an ancestor's height (`.h(..)`, + /// `.h_full()`, or a grown child of a bounded parent), or use `.min_h(..)` for a floor. + /// A grown column that holds its own flex content also needs `.min_h(0.0)` (see + /// [`El::min_h`]). + #[inline] + pub fn grow(mut self, g: f32) -> Self { + self.set_grow(g); + self + } + /// [`El::grow`] in place. + #[inline] + pub fn set_grow(&mut self, g: f32) -> &mut Self { + self.style.set_grow(g); + self + } + #[inline] + pub fn padding(mut self, p: f32) -> Self { + self.set_padding(p); + self + } + /// [`El::padding`] in place. + #[inline] + pub fn set_padding(&mut self, p: f32) -> &mut Self { + self.style.set_padding_all(p); + self + } + #[inline] + pub fn px(mut self, p: f32) -> Self { + self.set_px(p); + self + } + /// [`El::px`] in place. + #[inline] + pub fn set_px(&mut self, p: f32) -> &mut Self { + self.style.set_pad_left(p); + self.style.set_pad_right(p); + self + } + #[inline] + pub fn py(mut self, p: f32) -> Self { + self.set_py(p); + self + } + /// [`El::py`] in place. + #[inline] + pub fn set_py(&mut self, p: f32) -> &mut Self { + self.style.set_pad_top(p); + self.style.set_pad_bottom(p); + self + } + #[inline] + pub fn pt(mut self, p: f32) -> Self { + self.set_pt(p); + self + } + /// [`El::pt`] in place. + #[inline] + pub fn set_pt(&mut self, p: f32) -> &mut Self { + self.style.set_pad_top(p); + self + } + #[inline] + pub fn pb(mut self, p: f32) -> Self { + self.set_pb(p); + self + } + /// [`El::pb`] in place. + #[inline] + pub fn set_pb(&mut self, p: f32) -> &mut Self { + self.style.set_pad_bottom(p); + self + } + #[inline] + pub fn pl(mut self, p: f32) -> Self { + self.set_pl(p); + self + } + /// [`El::pl`] in place. + #[inline] + pub fn set_pl(&mut self, p: f32) -> &mut Self { + self.style.set_pad_left(p); + self + } + #[inline] + pub fn ml(mut self, m: f32) -> Self { + self.set_ml(m); + self + } + /// [`El::ml`] in place. + #[inline] + pub fn set_ml(&mut self, m: f32) -> &mut Self { + self.style.set_margin_left(m); + self + } + #[inline] + pub fn mr(mut self, m: f32) -> Self { + self.set_mr(m); + self + } + /// [`El::mr`] in place. + #[inline] + pub fn set_mr(&mut self, m: f32) -> &mut Self { + self.style.set_margin_right(m); + self + } + #[inline] + pub fn gap(mut self, g: f32) -> Self { + self.set_gap(g); + self + } + /// [`El::gap`] in place. + #[inline] + pub fn set_gap(&mut self, g: f32) -> &mut Self { + self.style.set_gap(g, g); + self + } + /// Centre children on the cross axis. + #[inline] + pub fn center_y(mut self) -> Self { + self.set_center_y(); + self + } + /// [`El::center_y`] in place. + #[inline] + pub fn set_center_y(&mut self) -> &mut Self { + self.style.set_align_items(AlignItems::CENTER); + self + } + #[inline] + pub fn center(mut self) -> Self { + self.set_center(); + self + } + /// [`El::center`] in place. + #[inline] + pub fn set_center(&mut self) -> &mut Self { + self.style.set_align_items(AlignItems::CENTER); + self.style.set_justify_content(JustifyContent::CENTER); + self + } + #[inline] + pub fn justify_between(mut self) -> Self { + self.set_justify_between(); + self + } + /// [`El::justify_between`] in place. + #[inline] + pub fn set_justify_between(&mut self) -> &mut Self { + self.style.set_justify_content(JustifyContent::SPACE_BETWEEN); + self + } + #[inline] + pub fn justify_end(mut self) -> Self { + self.set_justify_end(); + self + } + /// [`El::justify_end`] in place. + #[inline] + pub fn set_justify_end(&mut self) -> &mut Self { + self.style.set_justify_content(JustifyContent::FLEX_END); + self + } + /// Wrap children onto new lines (CSS `flex-wrap: wrap`). + #[inline] + pub fn flex_wrap(mut self) -> Self { + self.set_flex_wrap(); + self + } + /// [`El::flex_wrap`] in place. + #[inline] + pub fn set_flex_wrap(&mut self) -> &mut Self { + self.style.set_flex_wrap(FlexWrap::Wrap); + self + } + /// Align children to the start of the cross axis (CSS `align-items: flex-start`). + #[inline] + pub fn items_start(mut self) -> Self { + self.set_items_start(); + self + } + /// [`El::items_start`] in place. + #[inline] + pub fn set_items_start(&mut self) -> &mut Self { + self.style.set_align_items(AlignItems::FLEX_START); + self + } + /// Align children to the end of the cross axis (CSS `align-items: flex-end`). + #[inline] + pub fn items_end(mut self) -> Self { + self.set_items_end(); + self + } + /// [`El::items_end`] in place. + #[inline] + pub fn set_items_end(&mut self) -> &mut Self { + self.style.set_align_items(AlignItems::FLEX_END); + self + } + /// Centre children on the cross axis (CSS `align-items: center`; same as `center_y`). + #[inline] + pub fn items_center(mut self) -> Self { + self.set_items_center(); + self + } + /// [`El::items_center`] in place. + #[inline] + pub fn set_items_center(&mut self) -> &mut Self { + self.style.set_align_items(AlignItems::CENTER); + self + } + /// Stretch children across the cross axis (CSS `align-items: stretch`). + #[inline] + pub fn items_stretch(mut self) -> Self { + self.set_items_stretch(); + self + } + /// [`El::items_stretch`] in place. + #[inline] + pub fn set_items_stretch(&mut self) -> &mut Self { + self.style.set_align_items(AlignItems::STRETCH); + self + } + /// This element's own cross-axis alignment (CSS `align-self`). + #[inline] + pub fn self_start(mut self) -> Self { + self.set_self_start(); + self + } + /// [`El::self_start`] in place. + #[inline] + pub fn set_self_start(&mut self) -> &mut Self { + self.style.set_align_self(Some(AlignSelf::FLEX_START)); + self + } + #[inline] + pub fn self_center(mut self) -> Self { + self.set_self_center(); + self + } + /// [`El::self_center`] in place. + #[inline] + pub fn set_self_center(&mut self) -> &mut Self { + self.style.set_align_self(Some(AlignSelf::CENTER)); + self + } + #[inline] + pub fn self_end(mut self) -> Self { + self.set_self_end(); + self + } + /// [`El::self_end`] in place. + #[inline] + pub fn set_self_end(&mut self) -> &mut Self { + self.style.set_align_self(Some(AlignSelf::FLEX_END)); + self + } + #[inline] + pub fn self_stretch(mut self) -> Self { + self.set_self_stretch(); + self + } + /// [`El::self_stretch`] in place. + #[inline] + pub fn set_self_stretch(&mut self) -> &mut Self { + self.style.set_align_self(Some(AlignSelf::STRETCH)); + self + } + /// Pack children at the start of the main axis (CSS `justify-content: flex-start`). + #[inline] + pub fn justify_start(mut self) -> Self { + self.set_justify_start(); + self + } + /// [`El::justify_start`] in place. + #[inline] + pub fn set_justify_start(&mut self) -> &mut Self { + self.style.set_justify_content(JustifyContent::FLEX_START); + self + } + /// Centre children on the main axis (CSS `justify-content: center`). + #[inline] + pub fn justify_center(mut self) -> Self { + self.set_justify_center(); + self + } + /// [`El::justify_center`] in place. + #[inline] + pub fn set_justify_center(&mut self) -> &mut Self { + self.style.set_justify_content(JustifyContent::CENTER); + self + } + /// CSS `justify-content: space-around`. + pub fn justify_around(mut self) -> Self { + self.style.set_justify_content(JustifyContent::SPACE_AROUND); + self + } + /// CSS `justify-content: space-evenly`. + pub fn justify_evenly(mut self) -> Self { + self.style.set_justify_content(JustifyContent::SPACE_EVENLY); + self + } + #[inline] + pub fn min_w(mut self, w: f32) -> Self { + self.set_min_w(w); + self + } + /// [`El::min_w`] in place. + #[inline] + pub fn set_min_w(&mut self, w: f32) -> &mut Self { + self.style.set_min_width(length(w)); + self + } + #[inline] + pub fn max_h(mut self, h: f32) -> Self { + self.set_max_h(h); + self + } + /// [`El::max_h`] in place. + #[inline] + pub fn set_max_h(&mut self, h: f32) -> &mut Self { + self.style.set_max_height(length(h)); + self + } + /// Separate row and column gaps (CSS `row-gap`, `column-gap`). + #[inline] + pub fn gaps(mut self, row: f32, column: f32) -> Self { + self.set_gaps(row, column); + self + } + /// [`El::gaps`] in place. + #[inline] + pub fn set_gaps(&mut self, row: f32, column: f32) -> &mut Self { + self.style.set_gap(column, row); + self + } + #[inline] + pub fn max_w(mut self, w: f32) -> Self { + self.set_max_w(w); + self + } + /// [`El::max_w`] in place. + #[inline] + pub fn set_max_w(&mut self, w: f32) -> &mut Self { + self.style.set_max_width(length(w)); + self + } + /// Minimum height in points. + /// + /// Flex items default to a minimum of their content height (CSS `min-height: auto`), so a + /// nested flex column with tall content overflows its parent instead of shrinking, and a + /// scroll viewport inside it never gets to scroll. Put `.min_h(0.0)` on each flex column + /// between the bounded ancestor and the viewport: + /// + /// ```ignore + /// col().h_full().child(header).child( + /// col().grow(1.0).min_h(0.0).child(col().scroll(ScrollSpec { stick_bottom: false }).grow(1.0).child(list)), + /// ) + /// ``` + #[inline] + pub fn min_h(mut self, h: f32) -> Self { + self.set_min_h(h); + self + } + /// [`El::min_h`] in place. + #[inline] + pub fn set_min_h(&mut self, h: f32) -> &mut Self { + self.style.set_min_height(length(h)); + self + } + /// Left and right margin together (CSS `margin-inline`). + #[inline] + pub fn mx(mut self, m: f32) -> Self { + self.set_mx(m); + self + } + /// [`El::mx`] in place. + #[inline] + pub fn set_mx(&mut self, m: f32) -> &mut Self { + self.style.set_margin_x(m); + self + } + /// Top and bottom margin together (CSS `margin-block`). + #[inline] + pub fn my(mut self, m: f32) -> Self { + self.set_my(m); + self + } + /// [`El::my`] in place. + #[inline] + pub fn set_my(&mut self, m: f32) -> &mut Self { + self.style.set_margin_y(m); + self + } + #[inline] + pub fn mt(mut self, m: f32) -> Self { + self.set_mt(m); + self + } + /// [`El::mt`] in place. + #[inline] + pub fn set_mt(&mut self, m: f32) -> &mut Self { + self.style.set_margin_top(m); + self + } + #[inline] + pub fn mb(mut self, m: f32) -> Self { + self.set_mb(m); + self + } + /// [`El::mb`] in place. + #[inline] + pub fn set_mb(&mut self, m: f32) -> &mut Self { + self.style.set_margin_bottom(m); + self + } + #[inline] + pub fn pr(mut self, p: f32) -> Self { + self.set_pr(p); + self + } + /// [`El::pr`] in place. + #[inline] + pub fn set_pr(&mut self, p: f32) -> &mut Self { + self.style.set_pad_right(p); + self + } + /// Allow shrinking below content size along the parent's main axis. + #[inline] + pub fn shrink(mut self) -> Self { + self.set_shrink(); + self + } + /// [`El::shrink`] in place. + #[inline] + pub fn set_shrink(&mut self) -> &mut Self { + self.style.set_flex_shrink(1.0); + self.style.set_min_width(length(0.0)); + self + } + /// Lay children out in `n` equal columns, each as wide as the widest child needs (CSS + /// `grid-template-columns: repeat(n, 1fr)`), or sharing the width the element is given. + /// Children fill the cells in order unless placed with `grid_cell`. + pub fn equal_columns(mut self, n: usize) -> Self { + self.style.set_equal_columns(n); + self + } + /// Place this child of an `equal_columns` element in `column` (0-based) of the first row. + /// Children in the same cell overlap in order, so a moving highlight can sit under a label. + pub fn grid_cell(mut self, column: usize) -> Self { + self.style.set_grid_cell(column); + self + } + /// Out of flow, positioned at `left, top` inside the parent's padding box. + #[inline] + pub fn absolute(mut self, left: f32, top: f32) -> Self { + self.set_absolute(left, top); + self + } + /// [`El::absolute`] in place. + #[inline] + pub fn set_absolute(&mut self, left: f32, top: f32) -> &mut Self { + self.style.set_absolute_inset(Rect { left: length(left), top: length(top), right: auto(), bottom: auto() }); + self + } + /// Out of flow, pinned to the given edges of the parent's padding box (`None` leaves an + /// edge free); pinning both opposite edges stretches the element between them. + #[inline] + pub fn pin(mut self, left: Option<f32>, top: Option<f32>, right: Option<f32>, bottom: Option<f32>) -> Self { + self.set_pin(left, top, right, bottom); + self + } + /// [`El::pin`] in place. + #[inline] + pub fn set_pin(&mut self, left: Option<f32>, top: Option<f32>, right: Option<f32>, bottom: Option<f32>) -> &mut Self { + let edge = |v: Option<f32>| v.map_or(auto(), length); + self.style.set_absolute_inset(Rect { left: edge(left), top: edge(top), right: edge(right), bottom: edge(bottom) }); + self + } + /// The pointer's shape while it is over this element or a descendant that sets none. + /// Applies while the pointer is over a hit target (a pressable, draggable, hoverable or + /// text element) inside this one. + pub fn cursor(mut self, cursor: Cursor) -> Self { + self.handlers.cursor = Some(cursor); + self + } + /// Pressing this element moves the window, as a title bar does, and a double press zooms or + /// minimises it as the system's titlebar setting says. Hit targets inside it (buttons, + /// fields) keep their presses. + pub fn window_drag(mut self) -> Self { + self.flags.set_window_drag(WindowDrag::Drag); + self + } + /// A part of a `.window_drag()` band that keeps its presses: a press, double press or + /// secondary click on it, or on a bare child of it, neither moves, zooms nor opens the menu + /// of the window. Controls (`on_press`, `on_drag`, focusable elements, text fields) already + /// keep theirs; this is for the parts between them, such as the gaps of a toolbar group. + /// Like any hit target, it takes presses from what lies under it. + pub fn no_window_drag(mut self) -> Self { + self.flags.set_window_drag(WindowDrag::NoDrag); + self + } + /// The caret of an editor the app draws itself rather than with `text_input`: while this + /// element is drawn and no text field has focus, the window turns its input method on (dead + /// keys, CJK, the emoji picker, dictation), places the candidate window at this element's + /// drawn rect, and hands what it composes to [`App::on_ime`](crate::App::on_ime). Put it on + /// the caret you draw, only while the editor has the keyboard. A focused field's caret wins, + /// and a focused secure field keeps the input method off. + pub fn ime_cursor(mut self) -> Self { + self.flags.set(ElFlags::IME_CURSOR, true); + self + } + /// With [`Self::ime_cursor`]: on macOS, while this caret has the input method, Option is the + /// Alt key. A key pressed with it arrives as the key it's on with `mods.alt` (`Tx::key_base` + /// its character) instead of the character the layout makes with Option, and the input method + /// composes nothing for it (winit's `OptionAsAlt::Both`): a terminal's Option-as-Meta. It + /// changes nothing elsewhere, nor while `on` is false. + pub fn ime_option_as_alt(mut self, on: bool) -> Self { + if on || !self.cold.is_empty() { + self.cold_mut().option_as_alt = on; + } + self + } + /// Mark the drawn, ancestor-clipped rectangle as native overlay input. Does not add a handler. + pub fn hit(mut self) -> Self { + self.vis_flags.set(VisualFlags::HIT, true); + self + } + + /// Observe the pointer moving over this element, in window points, without making a native + /// overlay input region. [`El::on_pointer_move_local`] gives the element's own points. + #[track_caller] + pub fn on_pointer_move<S: 'static>(mut self, f: impl Fn(&mut S, PointerPress) + 'static) -> Self { + self.handlers.on_pointer_move = Some(Rc::new(move |s, p, _| f(downcast::<S>(s), p.window()))); + #[cfg(debug_assertions)] + { self.handlers.sites.pointer_move = Some(std::panic::Location::caller()); } + self + } + /// [`El::on_pointer_move`] with the point in this element's own layout points as well as + /// the window's (see [`PointerEvent`]), and a [`Tx`]: a canvas tracks the pointer in its own + /// coordinates at any zoom, and a handler that only moves a [`Live`](crate::Live) value + /// (a crosshair) says so with [`Tx::live_only`]. + /// + /// ```ignore + /// .on_pointer_move_local(|s: &mut Canvas, p, tx| { + /// s.crosshair.set([p.x, p.y]); + /// tx.live_only(); + /// }) + /// ``` + #[track_caller] + pub fn on_pointer_move_local<S: 'static>(mut self, f: impl Fn(&mut S, PointerEvent, &mut Tx) + 'static) -> Self { + self.handlers.on_pointer_move = Some(Rc::new(move |s, p, tx| f(downcast::<S>(s), p, tx))); + #[cfg(debug_assertions)] + { self.handlers.sites.pointer_move = Some(std::panic::Location::caller()); } + self + } + /// [`El::on_pointer_move_local`] for a component that doesn't read the app's state (a scroll + /// bar that widens under the pointer), so it works in any app. + #[track_caller] + pub fn on_pointer_move_any(mut self, f: impl Fn(PointerEvent, &mut Tx) + 'static) -> Self { + self.handlers.on_pointer_move = Some(Rc::new(move |_, p, tx| f(p, tx))); + #[cfg(debug_assertions)] + { self.handlers.sites.pointer_move = Some(std::panic::Location::caller()); } + self + } + + /// Called once when the pointer enters this hit target, not on animation frames. + #[track_caller] + pub fn on_hover<S: 'static>(mut self, f: impl Fn(&mut S) + 'static) -> Self { + self.handlers.on_hover = Some(Rc::new(move |s, _| f(downcast::<S>(s)))); + #[cfg(debug_assertions)] + { self.handlers.sites.hover = Some(std::panic::Location::caller()); } + self + } + + /// Called with `true` when the pointer enters this element's visible rect and `false` when + /// it leaves, descendants included (moving onto a child button is not a leave). It is not a + /// hit target, so it never takes presses or hover from its children. A held press keeps the + /// pointer inside until it releases. + #[track_caller] + pub fn on_hover_change<S: 'static>(mut self, f: impl Fn(&mut S, bool, &mut Tx) + 'static) -> Self { + self.handlers.on_hover_change = Some(Rc::new(move |s, inside, tx| f(downcast::<S>(s), inside, tx))); + #[cfg(debug_assertions)] + { self.handlers.sites.hover_change = Some(std::panic::Location::caller()); } + self + } + /// [`El::on_hover_change`] for a component that doesn't read the app's state. + #[track_caller] + pub fn on_hover_change_any(mut self, f: impl Fn(bool, &mut Tx) + 'static) -> Self { + self.handlers.on_hover_change = Some(Rc::new(move |_, inside, tx| f(inside, tx))); + #[cfg(debug_assertions)] + { self.handlers.sites.hover_change = Some(std::panic::Location::caller()); } + self + } + /// [`El::on_hover_change_any`] after any hover handler the element already has, which keeps + /// running: a component that follows the hover of an element it doesn't build. The change is + /// live-only when both handlers say so. + #[doc(hidden)] + pub fn chain_hover_change_any(mut self, f: impl Fn(bool, &mut Tx) + 'static) -> Self { + self.handlers.on_hover_change = Some(match self.handlers.get_mut_if_some().and_then(|h| h.on_hover_change.take()) { + Some(prev) => Rc::new(move |s, inside, tx| { + prev(s, inside, tx); + let prev_live = std::mem::take(&mut tx.live_only); + f(inside, tx); + tx.live_only &= prev_live; + }), + None => Rc::new(move |_, inside, tx| f(inside, tx)), + }); + self + } + + /// Delay [`Self::on_hover_change`]: `true` arrives once the pointer has rested inside for + /// `enter`, and `false` once it has stayed out for `leave`. A pass shorter than the delay + /// reports nothing, and a held button never starts the wait (a press during it cancels it; + /// the wait starts again when the pointer next moves). Losing window focus ends a shown hover + /// and cancels a wait; the pointer's next move over the window, still unfocused, starts the + /// wait again, so tooltips and hover cards open in a window behind another. A sidebar that + /// peeks open when the pointer rests at the window's edge uses `hover_delays(40 ms, 0)`. + pub fn hover_delays(mut self, enter: std::time::Duration, leave: std::time::Duration) -> Self { + let d = [enter.as_secs_f32(), leave.as_secs_f32()]; + if d != [0.0; 2] || !self.handlers.is_empty() { + self.handlers.hover_delay = d; + } + self + } + + #[doc(hidden)] + pub fn wrap_scroll_area(mut self, fallback_site: (&'static str, u32, u32)) -> (String, String, Self, Self) { + let key = self.key.clone().unwrap_or_else(|| { + use std::hash::{Hash, Hasher}; + let mut h = std::collections::hash_map::DefaultHasher::new(); + fallback_site.hash(&mut h); + let v = h.finish(); + let k = format!("scroll-{:08x}", (v ^ (v >> 32)) as u32); + self.key = Some(k.clone()); + k + }); + let area = format!("{key}-scroll-area"); + let mut outer = col().key(area.clone()); + outer.style = self.style.take_box_placement(); + if let Some(c) = self.cold.get_mut_if_some() { + let (fit, above, transition) = (std::mem::replace(&mut c.aspect_fit, 0.0), c.above.take(), c.transition.take()); + if fit > 0.0 || above.is_some() || transition.is_some() { + let o = outer.cold_mut(); + (o.aspect_fit, o.above, o.transition) = (fit, above, transition); + } + } + outer.vis.cold_mut().clip_to_content = true; + (area, key, outer, self) + } +} diff --git a/app/vendor/rune/crates/rune/src/el/layout_watch.rs b/app/vendor/rune/crates/rune/src/el/layout_watch.rs new file mode 100644 index 0000000..9ec1fc4 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/el/layout_watch.rs @@ -0,0 +1,164 @@ +//! Following where an element is: `El::on_layout` and `El::on_screen_layout` with its laid-out +//! rect, `El::on_drawn_layout` with where a frame drew it, and on a scroll viewport +//! `El::on_scroll_offset` with its offset in the frame that draws it. The runtime side is in +//! `runtime/layout_read.rs` and `runtime/scroll/watch.rs`. +use std::rc::Rc; + +use crate::states::downcast; +use crate::{El, Tx}; + +/// Where a scroll viewport is scrolled to, for [`El::on_scroll_offset`]: `offset` points from +/// the top-left of its content, `[x, y]`, out of the `max` it can scroll on each axis, in a +/// viewport `viewport` points wide and tall. `drawn` is the size the frame draws the viewport +/// at: `viewport` at rest, and where its size has got to while a layout spring resizes it, so +/// the handler hears every frame of that. `direction` is the way the viewport runs +/// ([`El::dir`]), `Ltr` or `Rtl`: a right-to-left one starts at its right edge, and its scroll bar +/// sits on its left, as a browser puts a `dir="rtl"` box's. +#[non_exhaustive] +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub struct ScrollPos { + pub offset: [f32; 2], + pub max: [f32; 2], + pub viewport: [f32; 2], + pub drawn: [f32; 2], + pub direction: crate::Direction, +} + +impl El { + /// Called with this element's laid-out rect `[x, y, w, h]` in window points, after scrolling + /// (as [`Cx::window_layout`](crate::Cx::window_layout) reads it): once after its first + /// layout, then when it moves or resizes by more than half a point, which inside a scroll + /// viewport is every frame of a scroll. Never per animation frame: the rect is where layout + /// puts the element, not where its spring is on the way there. Each report is a state + /// change, so the view runs again, unless the handler says [`Tx::live_only`] (see + /// [`El::on_layout_tx`]). + #[track_caller] + pub fn on_layout<S: 'static>(mut self, f: impl Fn(&mut S, [f32; 4]) + 'static) -> Self { + self.handlers.on_layout = Some(Rc::new(move |s, r, _| f(downcast::<S>(s), r))); + #[cfg(debug_assertions)] + { self.handlers.sites.layout = Some(std::panic::Location::caller()); } + self + } + /// [`El::on_layout`] with a [`Tx`]. A handler that only moves live values (a marker beside + /// a scrolling row, by its own [`El::live_offset`]) says [`Tx::live_only`], and a scroll + /// runs no view. + /// + /// ```ignore + /// .on_layout_tx(|s: &mut Board, [_, y, _, _], tx| { + /// s.marker_y.set(y); + /// tx.live_only(); + /// }) + /// ``` + #[track_caller] + pub fn on_layout_tx<S: 'static>(mut self, f: impl Fn(&mut S, [f32; 4], &mut Tx) + 'static) -> Self { + self.handlers.on_layout = Some(Rc::new(move |s, r, tx| f(downcast::<S>(s), r, tx))); + #[cfg(debug_assertions)] + { self.handlers.sites.layout = Some(std::panic::Location::caller()); } + self + } + /// [`El::on_layout`] in global screen points: `[x, y, w, h]` from the top-left of the + /// primary display, y down. That's the space of an overlay's + /// [`OverlayPlacement::Rect`](crate::OverlayPlacement) on + /// [`DisplayTarget::Primary`](crate::DisplayTarget), so an overlay can open over the + /// element. It also runs when the window moves without a relayout. On macOS points are one + /// space across displays of any scale. Elsewhere the window's desktop pixel position is + /// divided by its own scale, so it's exact on the primary display and wherever displays + /// share a scale; on Wayland, which hides window positions, the origin reads `(0, 0)`. + /// Headless runs place windows on the script's virtual desktop. + pub fn on_screen_layout<S: 'static>(mut self, f: impl Fn(&mut S, [f32; 4]) + 'static) -> Self { + self.handlers.on_screen_layout = Some(Rc::new(move |s, r| f(downcast::<S>(s), r))); + self + } + /// [`El::on_layout`] as drawn: `[x, y, w, h]` in window points where this frame put the + /// element, after scrolling and its ancestors' [`El::live_offset`], [`El::live_scale`], + /// [`El::live_rect`] and [`El::scale`], so an element on a zoomed canvas reports where it + /// shows (the rect hit tests use, and [`ElementInfo::rect`](crate::ElementInfo)). It runs + /// once after the element is first drawn, then when that rect moves by more than half a + /// point, including on every frame a live value moves it (a camera pan, with no commit). A + /// spring moving it, its own or an ancestor's, reports where it comes to rest, as + /// `on_layout` does. Its handler runs on the next frame. Keep it to the few elements + /// something follows (a selection a toolbar floats over), not every node on a canvas: each + /// report is a state change, so the view runs again, unless the handler says + /// [`Tx::live_only`] (see [`El::on_drawn_layout_tx`]). + #[track_caller] + pub fn on_drawn_layout<S: 'static>(mut self, f: impl Fn(&mut S, [f32; 4]) + 'static) -> Self { + self.handlers.on_drawn_layout = Some(Rc::new(move |s, r, _| f(downcast::<S>(s), r))); + #[cfg(debug_assertions)] + { self.handlers.sites.drawn_layout = Some(std::panic::Location::caller()); } + self + } + /// [`El::on_drawn_layout`] with a [`Tx`]. A toolbar that floats over a selection by its own + /// [`El::live_offset`] follows a camera pan with no view re-run at all: the handler sets + /// the toolbar's live offset and says [`Tx::live_only`]. + /// + /// ```ignore + /// .on_drawn_layout_tx(|s: &mut Canvas, [x, y, w, _], tx| { + /// s.toolbar_at.set([x + w / 2.0 - TOOLBAR_W / 2.0, y - TOOLBAR_H - 8.0]); + /// tx.live_only(); + /// }) + /// ``` + #[track_caller] + pub fn on_drawn_layout_tx<S: 'static>(mut self, f: impl Fn(&mut S, [f32; 4], &mut Tx) + 'static) -> Self { + self.handlers.on_drawn_layout = Some(Rc::new(move |s, r, tx| f(downcast::<S>(s), r, tx))); + #[cfg(debug_assertions)] + { self.handlers.sites.drawn_layout = Some(std::panic::Location::caller()); } + self + } + /// Called with `true` when this element comes on screen and `false` when it leaves, as a + /// web page's `IntersectionObserver` reports: on screen is half of it showing in the window + /// (or it covering half the window), where the frame drew it after scroll viewports and a + /// web page's own scroll ([`App::web_document`](crate::App::web_document)). It starts off + /// screen, so the first report is the first time it shows. Use it to play a demo when the + /// reader reaches it, or to stop a loop nobody can see. + pub fn on_visible<S: 'static>(mut self, f: impl Fn(&mut S, bool, &mut Tx) + 'static) -> Self { + self.handlers.on_visible = Some(Rc::new(move |s, on, tx| f(downcast::<S>(s), on, tx))); + self + } + /// Writes where each frame draws this element into `rect`: `[x, y, w, h]` in window points, + /// the rect [`El::on_drawn_layout`] reports, on every frame it moves, through a scroll, a + /// glide and its own or an ancestor's spring. It runs no handler and commits nothing, so a + /// scroll stays free of view runs. State code reads it with [`Live::get`](crate::Live::get) + /// when it needs to (where to open a popover). An element bound to `rect` (a highlight at + /// the window's top-left with [`El::live_rect`]) follows it a frame behind, since the rect + /// is known once the frame is drawn; to ride a scroll in the same frame, follow the offset + /// with [`El::on_scroll_offset`]. + /// + /// ```ignore + /// let ring = Live::new([0.0; 4]); + /// row.drawn_rect_into(&ring); + /// // at the root, outside the scroll: + /// el().pin(Some(0.0), Some(0.0), None, None).live_rect(&ring).border(1.0, accent) + /// ``` + pub fn drawn_rect_into(mut self, rect: &crate::Live<[f32; 4]>) -> Self { + self.handlers.drawn_rect = Some(rect.clone()); + self + } + /// On a scroll viewport: called with where it's scrolled to once it's first laid out, in + /// the frame that draws a commit giving it a new handler, and in every frame that scrolling + /// moves it, or it or its content resizes, before that frame draws. A [`Live`](crate::Live) it + /// sets shows in the same frame, so an element can follow the scroll exactly: a header that + /// shrinks as the page scrolls, or a shadow that fades in past the top. It can't change + /// state; set live values from it. + /// + /// ```ignore + /// let title_k = Live::new(1.0); + /// let k = title_k.clone(); + /// col().scroll(ScrollSpec::default()).on_scroll_offset(move |at: ScrollPos| k.set(1.0 - (at.offset[1] / 80.0).clamp(0.0, 1.0) * 0.4)) + /// ``` + pub fn on_scroll_offset(mut self, f: impl Fn(ScrollPos) + 'static) -> Self { + self.handlers.on_scroll_offset = Some(Rc::new(f)); + self + } + + #[doc(hidden)] + pub fn chain_scroll_offset(mut self, f: impl Fn(ScrollPos) + 'static) -> Self { + self.handlers.on_scroll_offset = Some(match self.handlers.get_mut_if_some().and_then(|h| h.on_scroll_offset.take()) { + Some(prev) => Rc::new(move |at| { + prev(at); + f(at); + }), + None => Rc::new(f), + }); + self + } +} diff --git a/app/vendor/rune/crates/rune/src/el/live_colors.rs b/app/vendor/rune/crates/rune/src/el/live_colors.rs new file mode 100644 index 0000000..36e7265 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/el/live_colors.rs @@ -0,0 +1,29 @@ +//! Live colours past the fill: a text's colour, the border, the first shadow and a two-stop +//! gradient, bound like [`El::live_fill`] so a tint that drifts repaints without a view rerun. +use crate::live::{Binding, Bound, Property}; +use crate::{Color, El}; + +impl El { + /// Bind a text's colour (or an icon's), optionally smoothed with `Live::smooth`. Views and + /// layout don't rerun; the text isn't shaped again. + pub fn live_text_color(mut self, value: impl Into<Binding<Color>>) -> Self { + self.bind_live(Bound::new(value, Property::TextColor)); + self + } + /// Bind the border's colour. The border's width comes from [`El::border`] as usual. + pub fn live_border(mut self, value: impl Into<Binding<Color>>) -> Self { + self.bind_live(Bound::new(value, Property::Border)); + self + } + /// Bind the first shadow's colour. Its offset and blur come from [`El::shadow`] as usual. + pub fn live_shadow(mut self, value: impl Into<Binding<Color>>) -> Self { + self.bind_live(Bound::new(value, Property::Shadow)); + self + } + /// Bind both stops of the vertical gradient [`El::gradient`] sets, top and bottom. + pub fn live_gradient(mut self, top: impl Into<Binding<Color>>, bottom: impl Into<Binding<Color>>) -> Self { + self.bind_live(Bound::new(top, Property::GradientTop)); + self.bind_live(Bound::new(bottom, Property::GradientBottom)); + self + } +} diff --git a/app/vendor/rune/crates/rune/src/el/motion.rs b/app/vendor/rune/crates/rune/src/el/motion.rs new file mode 100644 index 0000000..8d6a1f3 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/el/motion.rs @@ -0,0 +1,285 @@ +//! Motion builders: springs, offsets, raises, leads, layout animation and transitions. + +use super::*; + +/// Authored motion traits for [`El::motion_intent`], inherited by descendants. Motion checks +/// (`rune::motion_gate` and `--trace`) read these marks so deliberate overshoots, kicks, shakes +/// and discrete typing cuts pass without broad allowlist rules. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] +pub struct MotionIntent(u16); + +impl MotionIntent { + pub const NONE: Self = Self(0); + /// Deliberately passes its rest value and settles back (a bouncy spring or elastic curve). + pub const OVERSHOOT: Self = Self(1 << 0); + /// Deliberate wind-up, anticipation or out-and-back bump (`reversal`). + pub const RECOIL: Self = Self(1 << 1); + /// Deliberate shake or oscillation (`jiggle`, `reversal`). + pub const JIGGLE: Self = Self(1 << 2); + /// Deliberate sudden launch velocity or multi-rate lead (`jerk`). + pub const IMPULSE: Self = Self(1 << 3); + /// Deliberate discrete step without transition (`jump`, `appear-then-jump`, `snap`). + pub const STEP: Self = Self(1 << 4); + /// Deliberate instant mount, unmount or swap (`pop-in`, `pop-out`, `cut-exit`, `fade-snap`, `text-swap`, `snap`). + pub const CUT: Self = Self(1 << 5); + /// Deliberate brief flash or dip-and-recover (`flicker`, `flash`). + pub const PULSE: Self = Self(1 << 6); + + /// A bouncy or elastic element (`OVERSHOOT | RECOIL | JIGGLE`). + pub const BOUNCE: Self = Self(Self::OVERSHOOT.0 | Self::RECOIL.0 | Self::JIGGLE.0); + /// A ballistic launch or impact (`BOUNCE | IMPULSE`). + pub const KICK: Self = Self(Self::BOUNCE.0 | Self::IMPULSE.0); + /// Discrete typing: keycaps, typed runs, carets and placeholders (`STEP | CUT`). + pub const TYPING: Self = Self(Self::STEP.0 | Self::CUT.0); + + #[inline] + pub const fn bits(self) -> u16 { + self.0 + } + + #[inline] + pub const fn from_bits(bits: u16) -> Self { + Self(bits) + } + + #[inline] + pub const fn contains(self, other: Self) -> bool { + (self.0 & other.0) == other.0 + } + + #[inline] + pub const fn union(self, other: Self) -> Self { + Self(self.0 | other.0) + } +} + +impl std::ops::BitOr for MotionIntent { + type Output = Self; + #[inline] + fn bitor(self, rhs: Self) -> Self { + Self(self.0 | rhs.0) + } +} + +impl std::ops::BitOrAssign for MotionIntent { + #[inline] + fn bitor_assign(&mut self, rhs: Self) { + self.0 |= rhs.0; + } +} + +impl El { + /// Marks deliberate motion traits (`OVERSHOOT`, `KICK`, `JIGGLE`, `STEP`, `CUT`, `PULSE`) on + /// this element and its subtree so motion checks treat them as authored rather than bugs. + pub fn motion_intent(mut self, intent: MotionIntent) -> Self { + if intent != MotionIntent::NONE { + self.vis.cold_mut().motion_intent |= intent; + } + self + } + + /// The spring for this subtree's layout and colour changes (inherited). + /// Presence uses the transition's own enter/exit springs. + /// + /// [`Spring::NONE`] written here lands this element's changes at once, and motion checks + /// (`rune::motion_gate`) take that as the design for the properties it governs on this + /// element: its fill, border, shadow, gradient and outline colours, corners, shadow and + /// blur. Not for its children, which inherit the spring but not the mark. A spring from a + /// theme or token goes through [`token_motion`](Self::token_motion) instead. + pub fn motion(mut self, s: Spring) -> Self { + self.set_motion(s, s == Spring::NONE); + self + } + /// [`motion`](Self::motion) with a spring a theme or token chose rather than this element: + /// a [`Spring::NONE`] here still lands at once, but motion checks still report what snaps. + pub fn token_motion(mut self, s: Spring) -> Self { + self.set_motion(s, false); + self + } + fn set_motion(&mut self, s: Spring, authored_instant: bool) { + self.cold_mut().motion = Some(s); + if authored_instant || self.vis.instant_motion { + self.vis.cold_mut().instant_motion = authored_instant; + } + } + /// Shift this element and its subtree by `(x, y)` points without moving it in layout: + /// siblings keep their places, and hit tests follow the shift. A change springs on the + /// element's layout spring (or [`Self::offset_motion`]); under Reduce Motion, and in an + /// instant transaction, it lands at once. A reordered row slides aside this way while a + /// dragged one passes it. When a commit both changes the offset and moves the element in a + /// growth or virtual list (whose rows lay out at once), the offset starts from where the + /// element was drawn, so a dropped row that clears its offset slides into its new place. + /// Not for an element with a `live_offset` or a sliding loop, which own the same shift. + pub fn offset(mut self, x: f32, y: f32) -> Self { + let ok = |v: f32| if v.is_finite() { v } else { 0.0 }; + let o = [ok(x), ok(y)]; + if o != [0.0; 2] || !self.vis.cold.is_empty() { + self.vis.cold_mut().offset = o; + } + self + } + /// The curve [`Self::offset`] changes on. + pub fn offset_motion(mut self, anim: impl Into<Anim>) -> Self { + self.vis.cold_mut().offset_motion = Some(Box::new(anim.into())); + self + } + /// Paint this element and its subtree above everything else in the window, and give it + /// pointer input first, as if it came last in the tree. Its layout, focus order and + /// accessibility order stay where it is, and its ancestors' clips, offsets and opacity + /// still apply, though an ancestor that composites its children as a group (a partial + /// opacity, a blur) no longer groups it. Raised elements stack in tree order. A floating + /// sidebar sliding over the content beside it, or a dragged row over its neighbours. + pub fn raise(mut self) -> Self { + self.vis_flags.set(VisualFlags::RAISE, true); + self + } + /// Where this element paints among its siblings, as CSS `z-index` orders positioned + /// siblings: a higher order paints over siblings with a lower one, wherever they come in + /// the tree, and takes the pointer first where they overlap; equal orders paint in tree + /// order. 0 by default. Its focus order and accessibility order stay where it is in the + /// tree, and unlike [`Self::raise`] it stays inside its parent's layers. A floating button + /// placed before the page in the tree, for its Tab order, still paints over the page. + pub fn paint_order(mut self, order: i16) -> Self { + if order != 0 || !self.vis.cold.is_empty() { + self.vis.cold_mut().paint_order = order; + } + self + } + /// Override the curve this element's own opacity changes on, with an optional delay + /// ([`AnimExt::delay`](crate::AnimExt::delay)). The first paint and explicit + /// instant/settle transactions still land immediately. A new element's entrance runs on + /// its [`transition`](Self::transition) and multiplies this opacity; hold all of it with + /// [`enter_delay`](Self::enter_delay). + pub fn opacity_motion(mut self, anim: impl Into<Anim>) -> Self { + self.cold_mut().opacity_motion = Some(Box::new(anim.into())); + self + } + /// When this element travels, its leading edge moves on `lead` and its trailing edge on `trail` + /// (width leads). + pub fn lead(mut self, lead: Spring, trail: Spring) -> Self { + self.cold_mut().lead = Some((lead, trail)); + self + } + /// The X axis springs faster (`0.78×` duration) when this element resizes or travels. + pub fn width_leads(mut self) -> Self { + self.flags.set(ElFlags::WIDTH_LEADS, true); + self + } + /// Spring this subtree's horizontal layout (x and width) inside a growth-stack row, and + /// fade in children it gains while the row is in place. A row's contents otherwise snap + /// while the row's height carries the motion, so a label that changes width in place jumps + /// its neighbours. Vertical place stays with the row's growth. + pub fn animate_layout(mut self) -> Self { + self.flags.set(ElFlags::ANIMATE_LAYOUT, true); + self + } + /// Land every change inside this element at once, as a [`Tx::instant`] commit would, even + /// in a commit that animates the rest of the window: its own and its subtree's layout, + /// opacity and transforms, the elements it gains or loses, and growth rows. Its own entrance + /// and exit keep their transition, and colours (a hover highlight) keep their springs. A + /// popup of search results under a field whose edits animate the layout around it. + pub fn instant_changes(mut self) -> Self { + self.flags.set(ElFlags::INSTANT_CHANGES, true); + self + } + /// Stop an ancestor's [`Self::instant_changes`] at this element: it and what it holds enter, + /// exit and change on their own motion again. A favicon that fades in as it loads, inside a + /// panel whose contents land at once. + pub fn animated_changes(mut self) -> Self { + self.cold_mut().animated_changes = true; + self + } + /// How this element enters and exits when mounted or removed after the first frame + /// (default: [`Transition::opacity()`] — a 0.2 s enter and 0.15 s exit fade). Because + /// every element has this default fade, removing an element in an animated commit + /// (`AppSpec::on_key`, `El::on_key`, `on_submit`, `on_press`) fades it out over 0.15 s, + /// whereas commits that set [`Tx::instant`] or [`Tx::settle`] (such as typing in a + /// focused input or clicking into a text field) unmount removed elements in the same + /// frame. Call `tx.instant()` or `tx.settle()` in the handler when a key or button + /// action should unmount elements at once. Rows inserted into a growth stack only grow + /// open unless they set one, so `.transition(Transition::offset(0.0, 8.0).combined(Transition::opacity()))` + /// on a row also slides and fades it in. Rows a virtual list remounts on scroll never replay it. + /// [`enter_delay`](Self::enter_delay) holds the whole entrance, as a staggered list does. + /// + /// Motion has a cause, in every window an app opens: an entrance or exit plays only in a commit an input in this window + /// caused (a click, a key, a drag, a hover, a scroll). A commit nothing in the window's input + /// asked for (a poll, a wake, data a server brought, a launch's frames after the first) + /// applies as an instant one does: it mounts and unmounts at once, its layout lands (a + /// container that grows to fit what arrived doesn't ease), rows new to a growth stack land at + /// their height, and text it mounts shows whole. Motion already running keeps running, and + /// streaming growth and loops keep moving. A handler that means the motion anyway calls + /// [`Tx::animated`](crate::Tx::animated). + pub fn transition(mut self, t: Transition) -> Self { + self.cold_mut().transition = Some(Box::new(t)); + self + } + /// Shared-element motion (SwiftUI `matchedGeometryEffect`, Motion `layoutId`). When an + /// element with `id` leaves the tree in the same commit that another with `id` mounts + /// somewhere else, the new one starts exactly where the old one was seen, with its + /// velocity, corner radius, fill and opacity, and springs to its own layout on one straight + /// path. The old one disappears at once; neither plays its transition. + /// + /// Ids are per window. While it flies the element draws above the whole window at its own + /// opacity, inside its destination's clips (a scroll viewport included), and its children + /// keep their final layout, scaled uniformly to cover the moving frame and clipped to it, + /// so a `pixels_fit(.., SurfaceFit::Fill)` picture zooms without distorting. Text moves + /// with its box but keeps its size, as it does under any scale. The spring is + /// `tok::motion::REFLOW` unless the commit's `Tx::motion` or this element's + /// [`motion`](Self::motion) sets one. Under Reduce Motion nothing is matched: the old one + /// exits and the new one enters by their own transitions, in place. + /// When two elements share an id in one tree, the last one in tree order is matched. + pub fn matched(mut self, id: impl Into<String>) -> Self { + self.cold_mut().matched = Some(Rc::from(id.into())); + self + } + /// While this [`matched`](Self::matched) element flies, its children keep their final + /// layout at their own size, from the moving frame's leading edge and centred on its + /// height, cropped to it, rather than scaled to cover it: for a row whose width changes as + /// it flies, as a tab moving between a titlebar's strip and a sidebar, whose avatar and title + /// would otherwise scale up or slide off its leading edge. + pub fn matched_crop(mut self) -> Self { + self.vis.cold_mut().flight_crop = true; + self + } + /// When an animated commit changes this element's width (a side panel springing open + /// beside a column of text), it and everything in it take the layout they land at in + /// that frame, so text wraps once rather than on every frame of the travel, and the whole + /// slides as one: its first child that drew last frame starts where it was drawn and + /// glides to its new place on this element's spring. Heights its growth rows change land + /// with it. Motion checks take that frame's re-layout as designed. A window resize, an + /// instant commit and Reduce Motion land as they otherwise would. + pub fn hold_landing_width(mut self) -> Self { + self.vis.cold_mut().hold_landing = true; + self + } +} + +impl El { + /// A stable motion-lint name, independent of keys and generations. Defaults to the NodeId + /// in MotionTrace; tooling retains its keyed path fallback. Stored without copying the name. + /// Give simultaneous generations distinct names when comparing their motion separately. + pub fn trace_name(mut self, name: &'static str) -> Self { + self.cold_mut().trace_name = Some(name); + self + } + + /// Class and host for this subtree's trace metadata (descendants may override them). + /// motion-lint pairs names by class too: use `("gpui", "pill")` to match a native Metal trace. + /// The labels share the element's lazily allocated storage with its other rare fields. + pub fn trace_namespace(mut self, class: &'static str, host: &'static str) -> Self { + self.cold_mut().trace_namespace = Some((class, host)); + self + } + /// A finite opacity/scale sequence on the shared render clock. The final pose holds; + /// reduced motion and explicit settle land it immediately. A new key replays it; dropping + /// the loop and putting it back carries on from where it was. + pub fn sequence(self, frames: rune_motion::Sequence) -> Self { + self.looping(rune_motion::LoopSpec::sequence(frames)) + } + + /// A renderer-owned periodic or finite presentation track, on the shared clock. + pub fn looping(mut self, spec: rune_motion::LoopSpec) -> Self { + self.cold_mut().looping = Some(Box::new(spec)); + self + } +} diff --git a/app/vendor/rune/crates/rune/src/el/paragraphs.rs b/app/vendor/rune/crates/rune/src/el/paragraphs.rs new file mode 100644 index 0000000..9716f95 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/el/paragraphs.rs @@ -0,0 +1,119 @@ +//! `El::dir_by_paragraph`: each paragraph of a text in the direction of its own words, as CSS's +//! `unicode-bidi: plaintext` lays a block's paragraphs out. +use super::*; +use rune_text::paragraph_ranges as paragraphs; + +impl El { + /// Lays out each newline-ended line as its own [`Layout`](crate::text::Layout), reusing + /// unchanged lines across commits (shaping only changed lines; per-commit keying still hashes + /// each line when spans are present, and long plain/colour-only ASCII interiors wait as runs) + /// while staying one selectable text element in its own direction. + /// + /// Silently falls back to a single layout when the text does not wrap, is truncated or + /// line-clamped, is live (`El::live` / `El::advance_in`), is redacted, or is a shared-run + /// cell (multi-line inputs already lay out by paragraph with greedy wrapping); a text flight + /// landing on a `by_line` node is dropped so the text appears in place without flying. + pub fn by_line(mut self) -> El { + if let Some(t) = self.text.as_mut() { + t.by_line = true; + } + self + } + + /// Lays each paragraph of this text (a line a newline ends) out in the direction of its own + /// first strong character, as CSS's `unicode-bidi: plaintext` does: right to left when that's + /// Arabic or Hebrew, else left to right, left to right too when it has none, whatever + /// direction the element itself lays out in. Each paragraph's lines start at its own start + /// edge. The element's box, padding and place stay where its direction puts them. + /// + /// Call it last, after the text's spans, links, pills, highlights and copy settings. A text + /// whose paragraphs all take one direction stays one text. One whose paragraphs differ + /// becomes a column of one text per paragraph, which a selection crosses as one inside a + /// [`El::selection_group`] and copies joined by newlines. A multi-line text field stays one + /// field and lays each paragraph out in its own direction as it's edited, its mention pills + /// isolated (`@src/app.ts` stays left to right on an Arabic line), as a `contenteditable` + /// with `unicode-bidi: plaintext` does; its own direction (`El::dir(Direction::Auto)`) + /// comes from its text outside its pills, and left to right while it's empty, its + /// placeholder laid out in the placeholder's own. A secure, live, truncated or + /// line-clamped text, or a one-line field, stays one text in its first paragraph's direction. + pub fn dir_by_paragraph(mut self) -> El { + let Some(t) = self.text.as_mut() else { return self }; + t.dir = step_text_dir(t.dir, TextDirEvent::ByParagraph); + t.shape = None; + if self.cold.input.is_some() { + return self; + } + // Each paragraph's direction skips its isolates, and its piece takes their marks. + t.apply_isolates(); + let paragraphs = paragraphs(&t.content); + // A paragraph with no strong character reads the way the one before it does, and the + // first ones the way the element does (None here, as it isn't flattened yet). + let dirs: Vec<Option<Direction>> = paragraphs + .iter() + .scan(None, |last, &(a, b)| { + *last = Direction::of(&t.content[a..b]).or(*last); + Some(*last) + }) + .collect(); + let whole = t.redacted || t.cold.live.is_some() || t.cold.advance_in.is_some() || t.truncate || t.truncate_fade || t.max_lines > 0; + if whole || dirs.iter().all(|&d| d == dirs[0]) { + return self; + } + let Some(t) = self.text.take() else { return self }; + let cursor = self.handlers.cursor; + let last = paragraphs.len() - 1; + let pieces: Vec<El> = paragraphs.iter().enumerate().map(|(k, &range)| { + let mut e = text(String::new()).key(format!("p{k}")); + // A line of digits or punctuation under an Arabic one reads right to left with it. + if let Some(d) = dirs[k].filter(|_| Direction::of(&t.content[range.0..range.1]).is_none()) { + e = e.dir(d); + } + let links = paragraph(&t, k, range, k == last, &mut e); + if let Some(c) = cursor { e = e.cursor(c); } + if links { e.cold_mut().focus.enabled = true; } + e + }).collect(); + // The links' Tab stops went with them. + if !t.cold.links.is_empty() && let Some(c) = self.cold.get_mut_if_some() { c.focus.enabled = false; } + if self.role == RoleTag::TEXT { self.role = RoleTag::GROUP; } + self.style.set_flex_direction(FlexDirection::Column); + let kept = std::mem::take(&mut self.children); + self.children = pieces.into_iter().chain(kept).collect(); + self + } +} + +/// Fills `e` with paragraph `k` of `t`, bytes `a..b`: its words and the spans, links, pills, +/// highlights and marks over them, copying with a newline either side but where `t` began or +/// ended. Whether it has links. +fn paragraph(t: &TextSpec, k: usize, (a, b): (usize, usize), last: bool, e: &mut El) -> bool { + let (a32, b32) = (a as u32, b as u32); + let clip = |s: u32, e: u32| { + let (s, e) = (s.max(a32), e.min(b32)); + (s < e).then(|| (s - a32, e - a32)) + }; + let mut p = t.clone(); + p.content = t.content[a..b].to_owned(); + p.spans = t.spans.iter().filter_map(|s| clip(s.start, s.end).map(|(start, end)| crate::text::Span { start, end, ..s.clone() })).collect(); + // A plain text's paragraphs share its empty cold fields. + if !t.cold.is_empty() { + let cold = &mut *p.cold; + cold.links = t.cold.links.iter().filter_map(|l| clip(l.start, l.end).map(|(start, end)| Link { start, end, ..l.clone() })).collect(); + cold.uncopied = t.cold.uncopied.iter().filter_map(|&(s, e)| clip(s, e)).collect(); + cold.rings = t.cold.rings.iter().filter_map(|&(s, e, c, w)| clip(s, e).map(|(s, e)| (s, e, c, w))).collect(); + cold.strikes = t.cold.strikes.iter().filter_map(|&(s, e, c)| clip(s, e).map(|(s, e)| (s, e, c))).collect(); + cold.highlights = t.cold.highlights.iter().filter_map(|h| clip(h.start, h.end).map(|(start, end)| crate::text::TextHighlight { start, end, ..h.clone() })).collect(); + // A chip lies inside one line; one across a newline has no paragraph to sit in. + cold.pills = t.cold.pills.iter().filter(|c| a32 <= c.start && c.end <= b32).map(|c| crate::text::PillChip { start: c.start - a32, end: c.end - a32, ..c.clone() }).collect(); + cold.blocks = t.cold.blocks.get(k).copied().into_iter().collect(); + cold.soft_breaks.clear(); + cold.copy_breaks = [if k == 0 { t.cold.copy_breaks[0] } else { 1 }, if last { t.cold.copy_breaks[1] } else { 1 }]; + cold.copy_prefix = if k == 0 { t.cold.copy_prefix.clone() } else { None }; + } + // Fractional line heights, so the stacked paragraphs keep the one text's line pitch. + p.exact_lines = true; + p.shape = None; + let links = !p.cold.links.is_empty(); + e.text = Some(crate::cold::SharedBox::new(p)); + links +} diff --git a/app/vendor/rune/crates/rune/src/el/pills.rs b/app/vendor/rune/crates/rune/src/el/pills.rs new file mode 100644 index 0000000..a758199 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/el/pills.rs @@ -0,0 +1,193 @@ +//! `El::pill` and `El::pills`: rounded chips around byte ranges of static text, drawn and +//! wrapped like a [`text_input`](crate::text_input)'s [`Mark::Pill`](crate::Mark::Pill) chips. +use std::ops::Range; + +use crate::Color; +use crate::el::{El, PillStyle}; +use crate::text::{BareIcon, PillChip, Replace, Span}; + +impl El { + /// Draws bytes `range` of a [`text`](crate::text) or [`rich`](crate::rich) element as a + /// pill: a rounded chip in `style`'s colour (default: the rich style's link colour at 20%, + /// or [`El::pill_colors`]) with its label in `style`'s text colour and its icon before it, + /// the way a field draws a [`Mark::Pill`](crate::Mark::Pill). The label never splits across + /// lines, and the chip's padding takes room in the line, so the text around it moves aside. + /// Selection and copy treat the label as text. Ranges are authored UTF-8 bytes on char + /// boundaries; empty, out-of-range or overlapping ones are skipped. On a field this does + /// nothing: style its pills with [`El::pill_style`]. + /// + /// ```ignore + /// text("ask @reviewer to look").pill(4..13, PillStyle::new().bg(chip).fg(ink)) + /// ``` + pub fn pill(self, range: Range<usize>, style: PillStyle) -> Self { + self.pills([(range, style)]) + } + + /// [`El::pill`] for several ranges. + pub fn pills(mut self, pills: impl IntoIterator<Item = (Range<usize>, PillStyle)>) -> Self { + if self.cold.input.is_some() { + return self; + } + let Some(t) = &mut self.text else { return self }; + for (r, st) in pills { + let ok = r.start < r.end && t.content.is_char_boundary(r.start) && t.content.is_char_boundary(r.end) && r.end <= t.content.len(); + let (start, end) = (r.start as u32, r.end as u32); + if !ok || t.cold.pills.iter().any(|p| p.start < end && start < p.end) { + continue; + } + let at = t.cold.pills.partition_point(|p| p.start < start); + t.cold.pills.insert(at, PillChip { start, end, icon: st.icon, bg: st.bg, fg: st.fg, bare: None }); + } + t.spans = with_pill_colors(&t.spans, &t.cold.pills); + self + } +} + +impl El { + /// Sets `icon` inline in a [`text`](crate::text) or [`rich`](crate::rich) element, before + /// byte `at` (a char boundary), in room of its own that moves the text after it aside. It + /// stays on the line of the word that follows it, as an icon before a link does on a web + /// page, and sits centred on that word's letters. Its glyph takes `icon`'s colour or the + /// element's; an image (a site's favicon) draws as it is. Selection and copy skip it. With no + /// word after `at`, or over a pill, it draws nothing. + /// + /// ```ignore + /// rich("see the docs", spans).inline_icon(8, InlineIcon::glyph(&GLOBE).size(14.0).gap(4.0)) + /// ``` + pub fn inline_icon(mut self, at: usize, icon: InlineIcon) -> Self { + if self.cold.input.is_some() { + return self; + } + let Some(t) = &mut self.text else { return self }; + if at >= t.content.len() || !t.content.is_char_boundary(at) { + return self; + } + let word = t.content[at..].find(char::is_whitespace).unwrap_or(t.content.len() - at); + let (start, end) = (at as u32, (at + word) as u32); + if word == 0 || t.cold.pills.iter().any(|p| p.start < end && start < p.end) { + return self; + } + let at = t.cold.pills.partition_point(|p| p.start < start); + let InlineIcon { icon, image, size, gap, radius, color } = icon; + let bare = Some(Box::new(BareIcon { size, gap, radius, image, replace: None })); + t.cold.pills.insert(at, PillChip { start, end, icon, bg: None, fg: color, bare }); + self + } + + /// Draws `image` in place of bytes `range` of a [`text`](crate::text) or + /// [`rich`](crate::rich) element, standing on the baseline as a glyph does (rendered math + /// in a sentence). The bytes take no room and draw nothing, but selection, copy and search + /// still see them. A line grows to fit a taller or deeper image, and one too wide for the + /// rest of a line moves whole to the next. Ranges are UTF-8 bytes on char boundaries with + /// no newline; empty, out-of-range or overlapping ones are skipped. On a field this does + /// nothing. + /// + /// ```ignore + /// text("so $e^x$ grows").inline_image(3..8, InlineImage::new(pixels, 14.0, 9.0, 0.5)) + /// ``` + pub fn inline_image(mut self, range: Range<usize>, image: InlineImage) -> Self { + if self.cold.input.is_some() { + return self; + } + let Some(t) = &mut self.text else { return self }; + let c = &t.content; + let ok = range.start < range.end + && range.end <= c.len() + && c.is_char_boundary(range.start) + && c.is_char_boundary(range.end) + && !c.as_bytes()[range.clone()].contains(&b'\n'); + let (start, end) = (range.start as u32, range.end as u32); + if !ok || t.cold.pills.iter().any(|p| p.start < end && start < p.end) { + return self; + } + let at = t.cold.pills.partition_point(|p| p.start < start); + let InlineImage { pixels, width, ascent, descent, bleed } = image; + let replace = Some(Replace { width, ascent, descent, bleed }); + let bare = Some(Box::new(BareIcon { size: 0.0, gap: 0.0, radius: 0.0, image: Some(pixels), replace })); + t.cold.pills.insert(at, PillChip { start, end, icon: None, bg: None, fg: None, bare }); + self + } +} + +/// An image set in text by [`El::inline_image`]: `width` points wide, `ascent` points above +/// the baseline and `descent` below it, the image scaled to fit that box. +#[derive(Clone, Debug)] +pub struct InlineImage { + pixels: crate::Pixels, + width: f32, + ascent: f32, + descent: f32, + bleed: f32, +} + +fn points(v: f32) -> f32 { + if v.is_finite() { v.max(0.0) } else { 0.0 } +} + +impl InlineImage { + pub fn new(pixels: crate::Pixels, width: f32, ascent: f32, descent: f32) -> Self { + Self { pixels, width: points(width), ascent: points(ascent), descent: points(descent), bleed: 0.0 } + } + /// Draws the image `points` past each edge of its box, for an image with clear margins + /// (rendered math's padding) that the line shouldn't make room for. + pub fn bleed(mut self, points: f32) -> Self { + self.bleed = self::points(points); + self + } +} + +/// An icon set inline in text by [`El::inline_icon`]: a glyph or an image, `size` points square +/// (14 by default), `gap` points before the text after it (4). +#[derive(Clone, Debug)] +pub struct InlineIcon { + icon: Option<&'static crate::Icon>, + image: Option<crate::Pixels>, + size: f32, + gap: f32, + radius: f32, + color: Option<Color>, +} + +impl InlineIcon { + /// `icon`, drawn in [`Self::color`] or the element's text colour. + pub fn glyph(icon: &'static crate::Icon) -> Self { + Self { icon: Some(icon), image: None, size: 14.0, gap: 4.0, radius: 0.0, color: None } + } + /// An image (decoded pixels, such as a site's favicon), scaled to fit the square. + pub fn image(pixels: crate::Pixels) -> Self { + Self { icon: None, image: Some(pixels), size: 14.0, gap: 4.0, radius: 0.0, color: None } + } + /// Its side in points. + pub fn size(mut self, points: f32) -> Self { + self.size = if points.is_finite() { points.max(0.0) } else { 0.0 }; + self + } + /// Its room after it, before the text, in points. + pub fn gap(mut self, points: f32) -> Self { + self.gap = if points.is_finite() { points.max(0.0) } else { 0.0 }; + self + } + /// An image's corner radius in points. + pub fn radius(mut self, points: f32) -> Self { + self.radius = if points.is_finite() { points.max(0.0) } else { 0.0 }; + self + } + /// A glyph's colour. + pub fn color(mut self, c: Color) -> Self { + self.color = Some(c); + self + } +} + +/// `spans` with each pill's label colour over it. +pub(crate) fn with_pill_colors(spans: &[Span], pills: &[PillChip]) -> Vec<Span> { + if pills.iter().all(|p| p.fg.is_none()) { + return crate::text::flatten_spans(spans); + } + let mut all = spans.to_vec(); + all.extend(pills.iter().filter_map(|p| Some(Span { start: p.start, end: p.end, color: Some(p.fg?), ..Span::default() }))); + crate::text::flatten_spans(&all) +} + +#[cfg(test)] +mod tests; diff --git a/app/vendor/rune/crates/rune/src/el/pills/tests.rs b/app/vendor/rune/crates/rune/src/el/pills/tests.rs new file mode 100644 index 0000000..b36d37e --- /dev/null +++ b/app/vendor/rune/crates/rune/src/el/pills/tests.rs @@ -0,0 +1,220 @@ +use crate::color::Color; +use crate::el::{PillStyle, rich, text, text_input}; +use crate::text::{Span, TextSystem}; +use parley::Alignment; +use crate::{TextEdit, TextStyle}; + +const INK: Color = Color { r: 1.0, g: 0.0, b: 0.0, a: 1.0 }; +const CHIP: Color = Color { r: 0.0, g: 0.0, b: 1.0, a: 0.2 }; + +#[test] +fn pills_record_sorted_chips_and_skip_bad_ranges() { + let body = "ask @code-reviewer about @src/main.rs — é"; + let at = |s: &str| body.find(s).unwrap(); + let agent = at("@code-reviewer")..at("@code-reviewer") + 14; + let file = at("@src/main.rs")..at("@src/main.rs") + 12; + let e = text(body).pills([ + (file.clone(), PillStyle::new().bg(CHIP)), + (agent.clone(), PillStyle::new().fg(INK)), + (agent.start + 1..agent.end + 2, PillStyle::new()), + (5..5, PillStyle::new()), + (body.len() - 1..body.len(), PillStyle::new()), + (0..body.len() + 1, PillStyle::new()), + ]); + let t = e.text.as_ref().unwrap(); + let got: Vec<(u32, u32, Option<Color>, Option<Color>)> = t.cold.pills.iter().map(|p| (p.start, p.end, p.bg, p.fg)).collect(); + assert_eq!(got, [(agent.start as u32, agent.end as u32, None, Some(INK)), (file.start as u32, file.end as u32, Some(CHIP), None)]); +} + +#[test] +fn a_pill_colours_its_label_and_keeps_it_through_later_spans() { + let body = "ask @reviewer to look"; + let e = rich(body, vec![Span::new(0, 3).bold()]).pill(4..13, PillStyle::new().fg(INK)).spans(vec![Span::new(14, 16).italic()]); + let t = e.text.as_ref().unwrap(); + let ink: Vec<(u32, u32)> = t.spans.iter().filter(|s| s.color == Some(INK)).map(|s| (s.start, s.end)).collect(); + assert_eq!(ink, [(4, 13)]); + assert!(t.spans.iter().any(|s| s.italic && (s.start, s.end) == (14, 16))); +} + +#[test] +fn a_field_ignores_static_pills() { + let e = text_input(&TextEdit::new("ask @reviewer"), TextStyle::new(14.0, 400.0)).pill(4..13, PillStyle::new().fg(INK)); + assert!(e.text.as_ref().unwrap().cold.pills.is_empty()); +} + +#[test] +fn a_pill_label_stays_on_one_line_and_takes_room() { + let body = "please ask @recursive-self-improvement about it"; + let at = body.find('@').unwrap(); + let end = at + "@recursive-self-improvement".len(); + let mut ts = TextSystem::default(); + let plain = text(body).wrap(); + let pilled = text(body).wrap().pill(at..end, PillStyle::new()); + let mut width = |e: &crate::El, w| ts.layout_for_spec(&e.text.as_ref().unwrap().as_text_input(1.0, false), 1.0, w, Alignment::Start).full_width(); + let (wide_plain, wide_pill) = (width(&plain, None), width(&pilled, None)); + assert!(wide_pill > wide_plain + 4.0, "the chip's padding takes room: {wide_plain} vs {wide_pill}"); + // Narrow enough that plain text breaks at the label's hyphens, wide enough for the pill. + let layout = ts.layout_for_spec(&pilled.text.as_ref().unwrap().as_text_input(1.0, false), 1.0, Some(210.0), Alignment::Start); + let split = layout.lines().any(|l| { + let r = l.text_range(); + r.start > at && r.start < end + }); + assert!(!split, "a label that fits a line never splits across lines"); + let narrow = ts.layout_for_spec(&pilled.text.as_ref().unwrap().as_text_input(1.0, false), 1.0, Some(110.0), Alignment::Start); + assert!(narrow.width() <= 110.5, "one wider than the line wraps inside it: {}", narrow.width()); +} + +fn image(w: u32, h: u32) -> crate::Pixels { + let p = crate::Pixels::new(); + p.set(w, h, vec![255; (w * h * 4) as usize]); + p +} + +#[test] +fn an_inline_image_replaces_its_bytes_on_the_baseline_and_grows_the_line() { + let body = "so $e^x$ grows"; + let style = TextStyle::new(14.0, 400.0).lh(20.0); + let mut ts = TextSystem::default(); + let mut lay = |e: &crate::El, w| ts.layout_for_spec(&e.text.as_ref().unwrap().as_text_input(2.0, false), 2.0, w, Alignment::Start); + let plain = lay(&text(body).font(style), None); + let flat = text(body).font(style).inline_image(3..8, crate::InlineImage::new(image(40, 20), 20.0, 8.0, 2.0)); + let with = lay(&flat, None); + let without_label = lay(&text("so grows").font(style), None); + // The bytes take no room: only the image's 20 points (40 px at 2x) replace them. + let grew = with.full_width() - without_label.full_width(); + assert!((grew - 40.0).abs() < 1.5, "{grew}"); + assert!(with.full_width() < plain.full_width() + 40.0); + // Short enough to sit inside the line: its height stays 20 points. + assert_eq!(with.height(), plain.height()); + let mut boxes = Vec::new(); + let t = flat.text.as_ref().unwrap(); + crate::text::bare_icons(&with, &t.cold.pills, 2.0, [0.0, 0.0], &mut boxes); + let baseline = with.lines().next().unwrap().metrics().baseline; + let [(0, at, size)] = boxes[..] else { panic!("{boxes:?}") }; + assert_eq!(size, [40.0, 20.0]); + // Its top is its ascent above the baseline. + assert!((at[1] + 16.0 - baseline).abs() <= 1.0, "{at:?} vs baseline {baseline}"); + // A tall, deep one grows the line both ways. + let tall = lay(&text(body).font(style).inline_image(3..8, crate::InlineImage::new(image(40, 60), 20.0, 18.0, 12.0)), None); + assert!(tall.height() >= 60.0, "{}", tall.height()); +} + +#[test] +fn an_inline_image_too_wide_for_the_rest_of_a_line_moves_whole_to_the_next() { + let body = "some words then $\\frac{a}{b} + c$ after"; + let at = body.find('$').unwrap(); + let end = body.rfind('$').unwrap() + 1; + let style = TextStyle::new(14.0, 400.0).lh(20.0); + let mut ts = TextSystem::default(); + let e = text(body).font(style).wrap().inline_image(at..end, crate::InlineImage::new(image(120, 40), 60.0, 14.0, 6.0)); + let w = ts.layout_for_spec(&e.text.as_ref().unwrap().as_text_input(1.0, false), 1.0, None, Alignment::Start).full_width(); + let narrow = ts.layout_for_spec(&e.text.as_ref().unwrap().as_text_input(1.0, false), 1.0, Some(w - 50.0), Alignment::Start); + let starts: Vec<usize> = narrow.lines().map(|l| l.text_range().start).collect(); + assert!(starts.contains(&at), "the image starts a line: {starts:?}"); + assert!(!starts.iter().any(|&s| s > at && s < end), "never split: {starts:?}"); +} + +// In a running app: selection, copy, wrapping and streaming over pilled text. + +mod live { + use std::ops::Range; + + use crate::el::{PillStyle, col, text}; + use crate::{Cx, El, Env, Key, KeyEvent, Mods, Runtime, TextStyle}; + + struct S { + body: String, + pills: Vec<Range<usize>>, + width: f32, + } + + fn view(s: &S, _: &mut Cx<S>) -> El { + let t = text(s.body.clone()).key("t").font(TextStyle::new(14.0, 400.0).lh(20.0)).w(s.width).wrap().selectable(true); + col().key("root").padding(10.0).child(t.pills(s.pills.iter().map(|r| (r.clone(), PillStyle::new())))) + } + + fn runtime(body: &str, pills: &[Range<usize>], width: f32) -> Runtime<S> { + let s = S { body: body.into(), pills: pills.to_vec(), width }; + let mut rt = Runtime::new(s, view, (600.0, 400.0), Env::new(true, 1.0)); + rt.frame(0.0); + rt + } + + fn rect(rt: &Runtime<S>) -> [f32; 4] { + rt.elements().into_iter().find(|e| e.key.as_deref() == Some("t")).unwrap().rect + } + + /// Each line's byte range in the text's layout. + fn lines(rt: &Runtime<S>) -> Vec<Range<usize>> { + let n = rt.tree.nodes.iter().find(|n| n.key.as_deref() == Some("t")).unwrap(); + n.text_layout.as_ref().and_then(crate::text::TextLayout::single).unwrap().lines().map(|l| l.text_range()).collect() + } + + fn drag(rt: &mut Runtime<S>, from: (f32, f32), to: (f32, f32)) { + rt.pointer_down(from.0, from.1); + rt.pointer_move(to.0, to.1); + rt.pointer_up(to.0, to.1); + rt.frame(0.0); + } + + #[test] + fn a_selection_and_copy_across_a_pill_give_its_label_text() { + let body = "ask @reviewer to look"; + let mut rt = runtime(body, &[4..13], 400.0); + let r = rect(&rt); + let y = r[1] + r[3] * 0.5; + drag(&mut rt, (r[0] + 1.0, y), (r[0] + r[2] - 1.0, y)); + assert_eq!(rt.selected_text().as_deref(), Some(body)); + // The highlight follows the selected range, which covers the whole label. + let (_, range) = rt.text_selection().unwrap(); + assert!(range.start <= 4 && range.end >= 13, "{range:?}"); + rt.key(KeyEvent { key: Key::Command('c'), mods: Mods { cmd: true, ..Mods::default() } }); + rt.frame(0.0); + let copied = rt.copy_request.as_ref().map(|w| w.content().text().to_owned()); + assert_eq!(copied.as_deref(), Some(body)); + } + + #[test] + fn every_pill_label_stays_on_one_line() { + let body = "ping @recursive-self-improvement and @code-review-standards-and-spec today"; + let at = |s: &str| body.find(s).unwrap()..body.find(s).unwrap() + s.len(); + let pills = [at("@recursive-self-improvement"), at("@code-review-standards-and-spec")]; + let rt = runtime(body, &pills, 260.0); + let ls = lines(&rt); + assert!(ls.len() >= 2, "narrow enough to wrap: {ls:?}"); + let n = rt.tree.nodes.iter().find(|n| n.key.as_deref() == Some("t")).unwrap(); + let t = n.text.as_ref().unwrap(); + for (authored, chip) in pills.iter().zip(&t.cold.pills) { + // Layout ranges include each pill's bidi isolate marks. + let p = chip.start as usize..chip.end as usize; + assert_eq!(&t.content[p.clone()], &body[authored.clone()]); + assert!(!ls.iter().any(|l| l.start > p.start && l.start < p.end), "{p:?} splits across {ls:?}"); + } + } + + #[test] + fn pills_survive_streaming_appends_and_bad_ranges_are_ignored() { + let mut rt = runtime("ask @reviewer", &[4..13], 400.0); + let pilled = |rt: &Runtime<S>| { + let n = rt.tree.nodes.iter().find(|n| n.key.as_deref() == Some("t")).unwrap(); + let t = n.text.as_ref().unwrap(); + t.cold.pills.iter().map(|p| (p.start..p.end, t.content[p.start as usize..p.end as usize].to_owned())).collect::<Vec<_>>() + }; + let mut w = rect(&rt)[2]; + for more in [" to", " look at", " the é diff"] { + rt.update(|s, _| s.body.push_str(more)); + rt.frame(1.0 / 60.0); + assert_eq!(pilled(&rt), [(7..16, "@reviewer".into())], "after {more:?}"); + assert!(rect(&rt)[2] >= w); + w = rect(&rt)[2]; + } + // Past the end, inside "é", or empty: skipped, and the frame still draws. + let e = rt.state.body.find('é').unwrap(); + rt.update(|s, _| s.pills = vec![4..13, e + 1..e + 2, 30..400, 20..20]); + rt.frame(2.0 / 60.0); + assert_eq!(pilled(&rt), [(7..16, "@reviewer".into())]); + rt.update(|s, _| s.body.truncate(8)); + rt.frame(3.0 / 60.0); + assert!(pilled(&rt).is_empty(), "a range the text no longer reaches is dropped"); + } +} diff --git a/app/vendor/rune/crates/rune/src/el/pixel_snap.rs b/app/vendor/rune/crates/rune/src/el/pixel_snap.rs new file mode 100644 index 0000000..62cdd6f --- /dev/null +++ b/app/vendor/rune/crates/rune/src/el/pixel_snap.rs @@ -0,0 +1,53 @@ +//! `El::pixel_snap`. The snapping itself is in `runtime/paint/pixel_snap.rs`. +use crate::el::El; + +impl El { + /// Whether this element and its children snap their fills, borders and clips to whole + /// device pixels when they paint. On by default: a box laid out at a fractional position + /// (a 1.1 pt gap at 2×) still draws hard edges, and boxes that share an edge still meet + /// with no seam. Layout, hit testing and [`Cx::layout_size`](crate::Cx::layout_size) keep + /// the exact fractional rects either way. + /// + /// While an element animates, its correction eases toward the pixels for where it comes to + /// rest, in step with the distance left, so motion stays smooth and starts and lands + /// without a jump. Content under an `El::scale` (a zoomed canvas) draws at its exact + /// sub-pixel edges while the scale moves and eases onto whole pixels once it holds still. + /// Turn it off for an element an app moves itself frame by frame at sub-pixel speeds + /// (`El::offset` from a value it animates), so it glides instead of stepping a pixel at a + /// time. + pub fn pixel_snap(mut self, on: bool) -> Self { + self.vis_flags.set(crate::el::VisualFlags::NO_PIXEL_SNAP, !on); + self + } + + /// Snaps this element's children as Blink does inside a box with paint containment + /// (`contain: paint`, `content` or `strict`) whose top-left is `origin`, in window points: + /// that box's origin rounds to a whole device pixel on its own, and each child's position + /// in it rounds again, with no carry between the two. At 1.875x a box at 44 pt (82.5 px) + /// starts at 83, so a child 17 pt into it (31.875 px) lands on 115, not on 114 where its + /// own position would round. Pass the containing box's origin even when this element + /// isn't it (a panel inset inside a `main` that has the containment). + pub fn paint_contained(mut self, origin: [f32; 2]) -> Self { + self.vis.cold_mut().paint_contain = Some(origin); + self + } + + /// While it moves, this element and everything in it snap to whole device pixels every + /// frame, as Chromium paints a box that layout moves (a width or position that springs): + /// its fill, border, shadow and ring keep the profile they have at rest, stepping a pixel + /// at a time. By default a moving box glides at sub-pixel precision, as Chromium draws a + /// CSS transform, and its edges blend over the pixels they cross. + pub fn motion_snaps(mut self) -> Self { + self.vis.cold_mut().motion_snaps = true; + self + } + + /// Scales this element's thin axis by half around its midpoint at paint time, matching + /// Chromium's `height: 1px; transform: scaleY(0.5)` (or vertical `width: 1px; transform: scaleX(0.5)`): + /// 0.50 coverage in one pixel at 1x, and 0.625 / 0.375 across two pixels at 1.5x, while layout + /// keeps its full 1 pt slot. + pub fn hairline(mut self) -> Self { + self.vis.cold_mut().hairline = true; + self + } +} \ No newline at end of file diff --git a/app/vendor/rune/crates/rune/src/el/rare.rs b/app/vendor/rune/crates/rune/src/el/rare.rs new file mode 100644 index 0000000..e32dd20 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/el/rare.rs @@ -0,0 +1,252 @@ +//! What keeps `El` at three cache lines: rarely set fields behind `Cold<ElCold>`, booleans packed +//! into `ElFlags`, and the role as a one-byte `RoleTag`. A plain row, column, box or text +//! allocates none of them. + +use std::rc::Rc; + +use rune_motion::{Anim, Spring, Transition}; + +use crate::cold::{Cold, Empty}; +use crate::el::{A11y, Anchor, FocusSpec, GrowthSpec, InputSpec, ScrollAxes, ScrollEdges, ScrollSpec, Sticky, WindowDrag}; + +/// Element fields most elements leave at their defaults. +#[derive(Clone)] +pub(crate) struct ElCold { + pub(crate) focus: Cold<FocusSpec>, + pub(crate) looping: Option<Box<rune_motion::LoopSpec>>, + pub(crate) trace_name: Option<&'static str>, + pub(crate) trace_namespace: Option<(&'static str, &'static str)>, + /// A role outside `RoleTag`'s table, read when the tag is `RoleTag::CUSTOM`. + pub(crate) role: &'static str, + pub(crate) label: Option<std::borrow::Cow<'static, str>>, + pub(crate) live: Vec<crate::live::Bound>, + pub(crate) above: Option<Anchor>, + pub(crate) motion: Option<Spring>, + pub(crate) opacity_motion: Option<Box<Anim>>, + pub(crate) lead: Option<(Spring, Spring)>, + /// `El::animated_changes`: an ancestor's `El::instant_changes` stops here. + pub(crate) animated_changes: bool, + /// `El::ime_option_as_alt`. + pub(crate) option_as_alt: bool, + pub(crate) transition: Option<Box<Transition>>, + pub(crate) matched: Option<Rc<str>>, + pub(crate) scroll: Option<ScrollSpec>, + pub(crate) scroll_axes: ScrollAxes, + /// `El::wheel_scrolls`: the viewport a wheel over this element scrolls, in place of what it + /// starts on. + pub(crate) wheel_scrolls: Option<Box<str>>, + pub(crate) sticky: Option<Box<Sticky>>, + pub(crate) scroll_edges: ScrollEdges, + pub(crate) growth: Option<Box<GrowthSpec>>, + pub(crate) virtual_estimate: Option<f32>, + /// Rows `El::virtual_rows` builds at layout time, in place of `children`. + pub(crate) virtual_rows: Option<Rc<crate::el::virtual_rows::RowSource>>, + /// [`El::virtual_rows_version`](crate::El::virtual_rows_version), hashed. + pub(crate) virtual_rows_version: Option<u64>, + /// The memo this element was expanded from (`El::expand_memo`) to mount virtual rows. + pub(crate) expanded_memo: Option<Rc<crate::memo::Built>>, + pub(crate) glide: Option<crate::growth::FoldGlide>, + pub(crate) input: Option<Box<InputSpec>>, + pub(crate) time_scale: f32, + pub(crate) help: Option<String>, + /// `El::help_when_truncated`: the tooltip shows only while the text is cut short. + pub(crate) help_cut: bool, + /// `El::help_side`: the side the tooltip shows on; None for under the element. + pub(crate) help_side: Option<crate::Side>, + /// `El::help_open`: the tooltip shows whatever the pointer does. + pub(crate) help_open: bool, + pub(crate) material: Option<crate::SystemMaterial>, + /// `El::aspect_fit`'s width over height; 0 when unset. + pub(crate) aspect_fit: f32, + /// Outside disc: logical ascent, descent and line height; resolved with this commit's scale. + pub(crate) list_disc: Option<[f32; 3]>, + /// `El::level` and `El::expanded`. + pub(crate) a11y: A11y, + #[cfg(debug_assertions)] + pub(crate) scroll_source: Option<&'static std::panic::Location<'static>>, + #[cfg(debug_assertions)] + pub(crate) virtual_source: Option<&'static std::panic::Location<'static>>, +} + +impl Empty for ElCold { + const EMPTY: &'static Self = &ElCold { + focus: Cold::NONE, + looping: None, + trace_name: None, + trace_namespace: None, + role: "group", + label: None, + live: Vec::new(), + above: None, + motion: None, + opacity_motion: None, + lead: None, + animated_changes: false, + option_as_alt: false, + transition: None, + matched: None, + scroll: None, + scroll_axes: ScrollAxes::Y, + wheel_scrolls: None, + sticky: None, + scroll_edges: ScrollEdges { fade: 0.0, fade_style: crate::el::FadeStyle::SMOOTH, margin: 0.0, anchor: false }, + growth: None, + virtual_estimate: None, + virtual_rows: None, + virtual_rows_version: None, + expanded_memo: None, + glide: None, + input: None, + time_scale: 1.0, + help: None, + help_cut: false, + help_side: None, + help_open: false, + material: None, + aspect_fit: 0.0, + list_disc: None, + a11y: A11y::EMPTY, + #[cfg(debug_assertions)] + scroll_source: None, + #[cfg(debug_assertions)] + virtual_source: None, + }; +} + +/// An element's booleans and small enums, one bit (or two) each. +#[derive(Clone, Copy, Default, PartialEq, Eq)] +pub(crate) struct ElFlags(u16); + +impl ElFlags { + /// This element or anything under it uses `virtualize` or `virtual_rows`. + pub(crate) const HAS_VIRTUAL: u16 = 1; + pub(crate) const WIDTH_LEADS: u16 = 1 << 1; + pub(crate) const ANIMATE_LAYOUT: u16 = 1 << 2; + pub(crate) const INSTANT_CHANGES: u16 = 1 << 3; + pub(crate) const VIRTUAL_MOUNT: u16 = 1 << 4; + pub(crate) const STREAMING: u16 = 1 << 5; + pub(crate) const WHOLE: u16 = 1 << 6; + /// `El::ime_cursor`. + pub(crate) const IME_CURSOR: u16 = 1 << 7; + pub(crate) const SELECTION_GROUP: u16 = 1 << 8; + pub(crate) const INERT: u16 = 1 << 9; + /// The memo placeholder was expanded or given extra children: it shares its cached + /// children still, but is no longer the cached subtree itself. + pub(crate) const MEMO_EXTENDED: u16 = 1 << 10; + const DRAG_SHIFT: u16 = 11; + const DRAG_MASK: u16 = 0b11 << Self::DRAG_SHIFT; + /// `El::dir`: none (its parent's), `Ltr`, `Rtl` or `Auto`. + const DIR_SHIFT: u16 = 13; + const DIR_MASK: u16 = 0b11 << Self::DIR_SHIFT; + /// `El::unmirrored`: a right-to-left parent doesn't mirror where it sits. + pub(crate) const UNMIRRORED: u16 = 1 << 15; + + #[inline(always)] + pub(crate) fn dir(self) -> Option<crate::Direction> { + match (self.0 & Self::DIR_MASK) >> Self::DIR_SHIFT { + 1 => Some(crate::Direction::Ltr), + 2 => Some(crate::Direction::Rtl), + 3 => Some(crate::Direction::Auto), + _ => None, + } + } + + #[inline(always)] + pub(crate) fn set_dir(&mut self, dir: crate::Direction) { + let bits = match dir { + crate::Direction::Ltr => 1, + crate::Direction::Rtl => 2, + crate::Direction::Auto => 3, + }; + self.0 = (self.0 & !Self::DIR_MASK) | (bits << Self::DIR_SHIFT); + } + + #[inline(always)] + pub(crate) fn has(self, bit: u16) -> bool { + self.0 & bit != 0 + } + + #[inline(always)] + pub(crate) fn set(&mut self, bit: u16, on: bool) { + if on { self.0 |= bit } else { self.0 &= !bit } + } + + #[inline(always)] + pub(crate) fn window_drag(self) -> WindowDrag { + match (self.0 & Self::DRAG_MASK) >> Self::DRAG_SHIFT { + 1 => WindowDrag::Drag, + 2 => WindowDrag::NoDrag, + _ => WindowDrag::None, + } + } + + #[inline(always)] + pub(crate) fn set_window_drag(&mut self, drag: WindowDrag) { + let bits = match drag { + WindowDrag::None => 0, + WindowDrag::Drag => 1, + WindowDrag::NoDrag => 2, + }; + self.0 = (self.0 & !Self::DRAG_MASK) | (bits << Self::DRAG_SHIFT); + } +} + +/// An element's accessible role as an index into [`crate::a11y::roles::ROLES`]; +/// `CUSTOM` reads `ElCold::role`. +#[derive(Clone, Copy, PartialEq, Eq)] +pub(crate) struct RoleTag(u8); + +impl RoleTag { + const fn known(role: &str) -> RoleTag { + match crate::a11y::roles::index(role) { + Some(i) => RoleTag(i), + None => panic!("unknown RoleTag constant"), + } + } + + pub(crate) const GROUP: RoleTag = RoleTag::known("group"); + pub(crate) const TEXT: RoleTag = RoleTag::known("text"); + pub(crate) const BUTTON: RoleTag = RoleTag::known("button"); + pub(crate) const ICON: RoleTag = RoleTag::known("icon"); + pub(crate) const IMAGE: RoleTag = RoleTag::known("image"); + pub(crate) const TEXTBOX: RoleTag = RoleTag::known("textbox"); + pub(crate) const SLIDER: RoleTag = RoleTag::known("slider"); + pub(crate) const CUSTOM: RoleTag = RoleTag(u8::MAX); + + /// The tag for `role`, or `None` when it isn't in the canonical role table. + #[inline] + pub(crate) fn of(role: &str) -> Option<RoleTag> { + crate::a11y::roles::ROLES.iter().position(|r| r.name == role).map(|i| RoleTag(i as u8)) + } + + /// The role's name; `CUSTOM` has none of its own. + #[inline(always)] + pub(crate) fn name(self) -> Option<&'static str> { + crate::a11y::roles::ROLES.get(self.0 as usize).map(|r| r.name) + } +} + +impl crate::El { + /// The accessible role, as [`role`](crate::El::role) set it. + #[inline] + pub(crate) fn role_name(&self) -> &'static str { + self.role.name().unwrap_or(self.cold.role) + } + + #[inline] + pub(crate) fn set_role_name(&mut self, role: &'static str) { + match RoleTag::of(role) { + Some(tag) => self.role = tag, + None => { + self.role = RoleTag::CUSTOM; + self.cold_mut().role = role; + } + } + } + + /// The rarely set fields, for writing: the first write allocates them. + #[inline] + pub(crate) fn cold_mut(&mut self) -> &mut ElCold { + &mut self.cold + } +} diff --git a/app/vendor/rune/crates/rune/src/el/ride_trailing.rs b/app/vendor/rune/crates/rune/src/el/ride_trailing.rs new file mode 100644 index 0000000..733b644 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/el/ride_trailing.rs @@ -0,0 +1,17 @@ +//! `El::ride_trailing`: an element that keeps its place against its parent's trailing edge. +use crate::el::El; + +impl El { + /// While its parent's width animates, this element keeps its place against the parent's + /// trailing (right) edge instead of riding its leading one. Children normally ride the + /// parent's left edge, so in a row that widens to the left (right-aligned, or against a + /// spacer) a child that holds its column moves right in the row on its own spring while the + /// row's left edge moves left on another, and on screen it drifts out and back. Riding the + /// trailing edge it doesn't move at all, whatever springs the ancestors use; one that also + /// moves against that edge travels only that difference, on its own curve. Children + /// leaving hold their place the same way. + pub fn ride_trailing(mut self) -> Self { + self.vis_flags.set(crate::el::VisualFlags::RIDE_TRAILING, true); + self + } +} diff --git a/app/vendor/rune/crates/rune/src/el/scroll.rs b/app/vendor/rune/crates/rune/src/el/scroll.rs new file mode 100644 index 0000000..3b04e43 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/el/scroll.rs @@ -0,0 +1,376 @@ +//! Scroll viewport builders: the axes a viewport moves on, its bottom callbacks, edge fades +//! and reveal margin. + +use super::*; + +impl El { + /// A vertical scroll viewport over its children. + /// + /// The viewport needs a bounded height to scroll: a fixed `.h(..)`, or a `.grow(1.0)` share + /// of a parent whose height is itself bounded. Every flex column between that bounded + /// ancestor and the viewport needs `.min_h(0.0)`, or it grows to fit the content and the + /// viewport never overflows. Debug builds warn once per call site when a viewport inside a + /// `.grow()` container resolves to 0 pt tall while its content is not. + #[cfg_attr(debug_assertions, track_caller)] + #[inline] + pub fn scroll(mut self, spec: ScrollSpec) -> Self { + self.set_scroll(spec); + self + } + /// [`El::scroll`] in place. + #[cfg_attr(debug_assertions, track_caller)] + pub fn set_scroll(&mut self, spec: ScrollSpec) -> &mut Self { + self.viewport(spec, ScrollAxes::Y, taffy::Overflow::Hidden, taffy::Overflow::Scroll); + self + } + #[cfg_attr(debug_assertions, track_caller)] + fn viewport(&mut self, spec: ScrollSpec, axes: ScrollAxes, x: taffy::Overflow, y: taffy::Overflow) { + let cold = self.cold_mut(); + cold.scroll = Some(spec); + cold.scroll_axes = axes; + #[cfg(debug_assertions)] + { cold.scroll_source = Some(std::panic::Location::caller()); } + self.style.set_overflow(x, y); + } + /// A horizontal scroll viewport over its children: a filmstrip, a wide code block or + /// table, a tab strip that overflows. + /// + /// The content is laid out at its natural width, unwrapped as SwiftUI's + /// `ScrollView(.horizontal)` proposes, and at least as wide as the viewport (CSS + /// `width: max-content; min-width: 100%`), and never shrinks. `w_full` content does the + /// same; any other width it sets stays, narrower than the viewport too. The viewport takes its parent's width as any element does; its height is the + /// content's unless set, and the content fills a set height unless it sets its own. + /// + /// The wheel, a trackpad and touch move it like a vertical viewport, with Rune's own + /// momentum after a fling. A mostly-vertical trackpad swipe or touch pan that starts over + /// it scrolls the vertical viewport around it instead, and the axis holds for the whole + /// gesture, as in AppKit. Shift with a mouse wheel scrolls it on Windows, Linux and the web + /// (macOS does that itself). Left and Right arrows don't scroll it (text fields own them), + /// nor do Page Up and Page Down. [`El::scroll_edge_fade`] fades its left and right edges, + /// and [`Tx::scroll_into_view`] scrolls it to show a row. `El::virtualize` and + /// `El::virtual_rows` window vertical lists only. + #[cfg_attr(debug_assertions, track_caller)] + #[inline] + pub fn scroll_x(mut self) -> Self { + self.set_scroll_x(); + self + } + /// [`El::scroll_x`] in place. + #[cfg_attr(debug_assertions, track_caller)] + pub fn set_scroll_x(&mut self) -> &mut Self { + self.viewport(ScrollSpec { stick_bottom: false }, ScrollAxes::X, taffy::Overflow::Scroll, taffy::Overflow::Hidden); + self + } + /// A viewport that scrolls both ways over its children (a wide timeline, a large + /// table): [`El::scroll`] and [`El::scroll_x`] together. A trackpad gesture moves it along + /// the axis it starts on, as AppKit's predominant-axis scrolling does. It keeps the + /// `stick_bottom` of an earlier [`El::scroll`] call. Needs a bounded height like + /// [`El::scroll`]. The content takes its natural width as in [`El::scroll_x`] and its + /// natural height. + #[cfg_attr(debug_assertions, track_caller)] + #[inline] + pub fn scroll_xy(mut self) -> Self { + self.set_scroll_xy(); + self + } + /// [`El::scroll_xy`] in place. + #[cfg_attr(debug_assertions, track_caller)] + pub fn set_scroll_xy(&mut self) -> &mut Self { + let spec = self.cold.scroll.unwrap_or(ScrollSpec { stick_bottom: false }); + self.viewport(spec, ScrollAxes::Both, taffy::Overflow::Scroll, taffy::Overflow::Scroll); + self + } + /// On a scroll viewport, called with whether it shows its bottom (within a point): once + /// after its first layout, then only when that changes, never per frame. Pair with + /// [`Tx::scroll_to_bottom`] for a "jump to latest" button. + pub fn on_at_bottom<S: 'static>(self, f: impl Fn(&mut S, bool) + 'static) -> Self { + self.on_at_bottom_if(move |s, at| { f(s, at); true }) + } + /// Like [`Self::on_at_bottom`], but a report that returns false does not rebuild the view. + /// The first report after mounting can confirm state the app already drew. + pub fn on_at_bottom_if<S: 'static>(mut self, f: impl Fn(&mut S, bool) -> bool + 'static) -> Self { + self.handlers.on_at_bottom = Some(Rc::new(move |s, at| f(downcast::<S>(s), at))); + self + } + /// On a scroll viewport, called with whether it stands more than its own height, and at + /// least `min` points, above its bottom: where a chat shows its "jump to latest" button and + /// hides it again near the end. Once after its first layout, then only when that changes. + pub fn on_far_from_bottom<S: 'static>(self, min: f32, f: impl Fn(&mut S, bool) + 'static) -> Self { + self.on_far_from_bottom_if(min, None, move |s, far| { f(s, far); true }) + } + /// [`El::on_far_from_bottom`] for a viewport that runs under a frame, the nearest ancestor + /// keyed `frame` (a chat's pane, with a header and a dock over its scroll): far is more than + /// the frame's height above the bottom, and at least `min`. The height is measured as it + /// scrolls, so the view never reads it and a resize re-runs no view. + pub fn on_far_from_bottom_under<S: 'static>(self, min: f32, frame: &str, f: impl Fn(&mut S, bool) + 'static) -> Self { + self.on_far_from_bottom_if(min, Some(frame), move |s, far| { f(s, far); true }) + } + /// Like [`Self::on_far_from_bottom`] (under `frame` if given), but the callback returns + /// whether its report changed the view. A stationary viewport still receives its first report. + pub fn on_far_from_bottom_if<S: 'static>(mut self, min: f32, frame: Option<&str>, f: impl Fn(&mut S, bool) -> bool + 'static) -> Self { + self.handlers.on_far_from_bottom = Some((min, frame.map(Rc::from), Rc::new(move |s, far| f(downcast::<S>(s), far)))); + self + } + /// On a scroll viewport, fade its top and bottom edges over `width` points (16–32 reads well), + /// each only while content is hidden under it: the fade's strength is the hidden extent / 15 + /// points, so a viewport at its top (or bottom, or stuck to it) shows that edge hard. Replaces + /// any top/bottom [`El::clip_fade`] widths; left/right ones still apply. On a horizontal + /// viewport ([`El::scroll_x`]) the left and right edges fade the same way instead, and on + /// [`El::scroll_xy`] all four. Sticky elements ([`El::sticky_top`], [`El::sticky_bottom`], + /// [`El::sticky_left`]) are not faded on the edge they stick to, so a header's fill stays + /// opaque while rows scrolling under it fade. This also applies before the element sticks; + /// explicit [`El::clip_fade`] masks and outer viewports' fades still apply. Pair with + /// [`El::scroll_margin`] so rows brought into view stop clear of the fade. + pub fn scroll_edge_fade(self, width: f32) -> Self { + self.scroll_fade(ScrollFade::strength(width)) + } + /// On a scroll viewport, fade its edges with the content hidden under them, as `fade` + /// describes: [`ScrollFade::strength`] (as [`El::scroll_edge_fade`]), a + /// [`ScrollFade::feather`] as wide as what's hidden, linear ramps, or a top fade under the + /// header stuck there. Everything [`El::scroll_edge_fade`] says of sticky elements, explicit + /// masks and [`El::scroll_margin`] applies. + pub fn scroll_fade(mut self, fade: ScrollFade) -> Self { + self.cold_mut().scroll_edges.fade = fade.width; + self.cold_mut().scroll_edges.fade_style = fade.style; + self + } + /// On a scroll viewport, the space [`Tx::scroll_into_view`] leaves between a revealed row and + /// the edge it scrolls to, like CSS `scroll-padding`. The content's own ends still stop flush. + pub fn scroll_margin(mut self, pts: f32) -> Self { + self.cold_mut().scroll_edges.margin = pts.max(0.0); + self + } + /// On a vertical scroll viewport, keep the row at the top of the view where it is when a + /// commit changes the content above it (rows inserted, removed, grown or reflowed by a new + /// width), as CSS `overflow-anchor: auto` does in a browser. The row is the first child + /// drawn in the view, or within a child that starts above the view, the first of its + /// children, and so on down. It holds only while the viewport is still and scrolled off + /// its top, and not following its bottom (`stick_bottom`): at the very top new content + /// above shows. A [`Tx::keep_on_screen`] in the same commit wins, and so does a scroll. + /// [`El::virtual_rows`] lists already keep their first visible row this way. + pub fn scroll_anchor(mut self) -> Self { + self.cold_mut().scroll_edges.anchor = true; + self + } + /// A wheel over this element turns the scroll viewport keyed `key` (or the nearest one + /// containing it) instead of starting on what is drawn here: an overlay scroll bar's track, + /// which draws over its viewport's edge but sits beside it in the tree, so a wheel there + /// would otherwise find no scroller above it. The viewport's wheel is then Chromium's, whose + /// scrollbar belongs to its scroller: it scrolls this viewport on the axis the wheel turned, + /// and chains on up from it when that one is at its end. A press or drag here still does + /// whatever this element's handlers do, and an [`El::on_wheel`] handler under the pointer still + /// hears the wheel first: this decides where a wheel the handlers leave scrolls, not who hears + /// it, and a handler on the named viewport itself doesn't, since the pointer is over this + /// element rather than the viewport. + /// + /// `key` names an element as [`Cx::layout`](crate::Cx::layout) does, here and in the other + /// scroll requests, and is resolved in this element's own place: looked up inside this element + /// itself, then inside its parent, then its parent's parent and so on, the first that holds + /// such an element wins. So two panes that key their viewports alike (a chat and a sidebar + /// both with `list`, or every wide markdown table, each keyed `scroll`) each take the wheel + /// over their own bar. Nothing keyed `key` leaves the wheel as it was. + #[cfg_attr(debug_assertions, track_caller)] + #[inline] + pub fn wheel_scrolls(mut self, key: impl Into<String>) -> Self { + self.set_wheel_scrolls(key); + self + } + /// [`El::wheel_scrolls`] in place. + pub fn set_wheel_scrolls(&mut self, key: impl Into<String>) -> &mut Self { + self.cold_mut().wheel_scrolls = Some(key.into().into_boxed_str()); + self + } +} + +/// How a scroll viewport's edges fade with the content hidden under them ([`El::scroll_fade`]). +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct ScrollFade { + width: f32, + style: FadeStyle, +} + +/// The parts of a [`ScrollFade`] besides its width, kept on the viewport. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub(crate) struct FadeStyle { + /// The fade is as wide as what's hidden, up to its width, rather than full width at a + /// strength that follows it. + pub(crate) feather: bool, + pub(crate) linear: bool, + /// Optional interior `(position, alpha)` stops in `(0, 1)` for a piecewise-linear ramp + /// anchored at `(0, 0)` and `(1, 1)` (matching CSS `mask-image: linear-gradient(...)`). + pub(crate) stops: Option<[(f32, f32); 3]>, + /// The top fade starts under the header stuck there, for the rows of that header's section. + pub(crate) below_sticky: bool, + /// Only the bottom (or right) edge follows the scroll; the other keeps the viewport's clip. + pub(crate) end_only: bool, + /// Points hidden at which a strength fade is full; 0 for 15. + pub(crate) full_at: f32, + /// The end edge's own fade (`ScrollFade::with_end`): its width, ramp and full-at. + pub(crate) end: Option<EndFade>, +} + +/// How the end edge (bottom, or right) fades when it differs from the start (`ScrollFade::with_end`). +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub(crate) struct EndFade { + pub(crate) width: f32, + pub(crate) linear: bool, + pub(crate) stops: Option<[(f32, f32); 3]>, + pub(crate) full_at: f32, +} + +impl FadeStyle { + pub(crate) const SMOOTH: FadeStyle = FadeStyle { feather: false, linear: false, stops: None, below_sticky: false, end_only: false, full_at: 0.0, end: None }; + + /// The style and width (points) the edge with `end` set fades by: the end edge's own when + /// [`ScrollFade::with_end`] gave it one. + pub(crate) fn edge(self, width: f32, end: bool) -> (FadeStyle, f32) { + match self.end.filter(|_| end) { + Some(e) => (FadeStyle { linear: e.linear, stops: e.stops, full_at: e.full_at, end: None, ..self }, e.width), + None => (self, width), + } + } + + /// Packs any explicit piecewise-linear stops on this fade or its `end` fade into two exact + /// 24-bit `f32` integers for `Globals::flags[2..4]` (`1/200` quantization, exact for CSS + /// quarter/percent stops like `(0.25, 0.16), (0.5, 0.5), (0.75, 0.84)`). + pub(crate) fn packed_stops(self) -> Option<[f32; 2]> { + let end_stops = self.end.and_then(|e| e.stops); + if let (Some(a), Some(b)) = (self.stops, end_stops) { + debug_assert_eq!(a, b, "ScrollFade::stops supports one explicit stop curve per window; start and end fades differ"); + } + let [(t1, a1), (t2, a2), (t3, a3)] = self.stops.or(end_stops)?; + let q = |v: f32| (v.clamp(0.0, 1.0) * 200.0).round() as u32; + let lo = q(t1) | (q(a1) << 8) | (q(t2) << 16); + let hi = q(a2) | (q(t3) << 8) | (q(a3) << 16); + Some([lo as f32, hi as f32]) + } +} + +impl ScrollFade { + /// Each edge fades over `width` points (16-32 reads well) at a strength that follows the + /// content hidden under it, full once 15 points are hidden: the edge itself shows + /// `1 - strength`. A viewport at its top (or bottom, or stuck to it) shows that edge hard. + /// Desktop's search lists fade so (`search-list.tsx`). + pub fn strength(width: f32) -> Self { + ScrollFade { width: width.clamp(0.0, 65504.0), style: FadeStyle::SMOOTH } + } + /// Each edge feathers by as much as is hidden under it, up to `max` points, on a linear ramp + /// from nothing at the edge: CSS `mask-image: linear-gradient(transparent, black + /// min(max, scrollTop))`, as Desktop's vertical tabs do. It appears and leaves without a jump. + pub fn feather(max: f32) -> Self { + ScrollFade { width: max.clamp(0.0, 65504.0), style: FadeStyle { feather: true, linear: true, ..FadeStyle::SMOOTH } } + } + /// A [`Self::strength`] fade is full once `points` are hidden, rather than 15: a small value + /// shows the whole fade as soon as anything is hidden, as a mask a scroll listener toggles + /// on and off does (Desktop's projects list). + pub fn full_at(mut self, points: f32) -> Self { + self.style.full_at = points.max(0.01); + self + } + /// Only the end the content runs on past (the bottom, or the right of a sideways viewport) + /// follows the scroll; the start keeps the viewport's own [`El::clip_fade`] or + /// [`El::clip_fade_linear`], such as a fixed fade over a field's top padding. + pub fn end_only(mut self) -> Self { + self.style.end_only = true; + self + } + /// Ramps alpha linearly across the fade, as a CSS `linear-gradient` mask does, rather than + /// on smoothstep. + pub fn linear(mut self) -> Self { + self.style.linear = true; + self.style.stops = None; + self + } + /// Ramps alpha piecewise-linearly through up to three interior `(position, alpha)` stops in + /// `[0, 1]`, anchored at `(0, 0)` (edge) and `(1, 1)` (full width), matching multi-stop CSS + /// `mask-image: linear-gradient(...)` masks (such as `[(0.25, 0.16), (0.5, 0.5), (0.75, 0.84)]`). + /// + /// Stops are sorted by `position` and must have non-decreasing `alpha` (checked with + /// `debug_assert!` and clamped monotonically in release builds so partial-strength inversion + /// stays exact). All explicit-stop fades active in a window share one per-frame stop curve; + /// distinct stop curves in the same tree trigger a `debug_assert!`. + pub fn stops(mut self, stops: &[(f32, f32)]) -> Self { + let mut pts: Vec<(f32, f32)> = stops + .iter() + .filter(|&&(t, a)| t.is_finite() && a.is_finite()) + .map(|&(t, a)| (t.clamp(0.0, 1.0), a.clamp(0.0, 1.0))) + .take(3) + .collect(); + pts.sort_by(|a, b| a.0.total_cmp(&b.0).then_with(|| a.1.total_cmp(&b.1))); + let mut max_a = 0.0f32; + for pt in &mut pts { + debug_assert!(pt.1 >= max_a, "ScrollFade::stops requires non-decreasing alpha (got {} after {max_a})", pt.1); + max_a = max_a.max(pt.1); + pt.1 = max_a; + } + let mut arr = [(1.0, 1.0); 3]; + for (slot, pt) in arr.iter_mut().zip(pts) { + *slot = pt; + } + self.style.linear = false; + self.style.stops = Some(arr); + self + } + /// The top fade starts under the [`El::sticky_top`] header stuck at the viewport's top, for + /// the rows of that header's section (the header's later siblings), at the strength of what + /// the section hides under the header; a header being pushed away by the next leaves the + /// rows clear, and the incoming one starts clear. With no header stuck, the viewport's own + /// top fades. Desktop's palettes fade their sections so (`search-list.css`), drawing the + /// fade over the rows in the list's surface colour. + pub fn below_sticky(mut self) -> Self { + self.style.below_sticky = true; + self + } + /// The end edge (the bottom, or the right of a sideways viewport) fades as `end` does, with + /// its own width, ramp and strength, while the start keeps this fade: Desktop's model dialog + /// fades its rows 16 points under a stuck header on an eased curve but 24 points at its bottom + /// on a linear mask (`search-list.css`). Only `end`'s width, ramp and full-at count. + pub fn with_end(mut self, end: ScrollFade) -> Self { + self.style.end = Some(EndFade { width: end.width, linear: end.style.linear, stops: end.style.stops, full_at: end.style.full_at }); + self + } +} + +/// A vertical scroll viewport. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct ScrollSpec { + /// Follow the end: while scrolled to the bottom, growth keeps the bottom in view, and a new + /// viewport opens at the bottom on its first frame. When the content is a growth stack, room + /// the viewport gains at its bottom (a composer shrinking under it) is held under the last + /// row and closes on the stack's spring once its rows stop growing, so a send only moves + /// the rows up. + pub stick_bottom: bool, +} + +/// A scroll viewport's content-aware edges: `El::scroll_edge_fade`, `El::scroll_margin` and +/// `El::scroll_anchor`. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub(crate) struct ScrollEdges { + /// Fade width (points) for the top and bottom edges; 0 for none. + pub(crate) fade: f32, + /// How the fade follows the content hidden under each edge (`El::scroll_fade`). + pub(crate) fade_style: FadeStyle, + /// Space `Tx::scroll_into_view` leaves between a revealed row and the viewport's edge. + pub(crate) margin: f32, + /// The viewport keeps its top row where it is when content above it changes. + pub(crate) anchor: bool, +} + +/// The axes a scroll viewport moves on: `El::scroll` (vertical), `El::scroll_x`, `El::scroll_xy`. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(crate) enum ScrollAxes { + #[default] + Y, + X, + Both, +} + +impl ScrollAxes { + pub(crate) fn x(self) -> bool { self != ScrollAxes::Y } + pub(crate) fn y(self) -> bool { self != ScrollAxes::X } + /// Whether it moves on the horizontal axis (`true`) or the vertical one. + pub(crate) fn has(self, horizontal: bool) -> bool { if horizontal { self.x() } else { self.y() } } +} + +pub(crate) type AtBottomFn = Rc<dyn Fn(crate::states::States<'_>, bool) -> bool>; +pub(crate) type VisibleRowsFn = Rc<dyn Fn(crate::states::States<'_>, std::ops::Range<usize>) -> bool>; diff --git a/app/vendor/rune/crates/rune/src/el/selection_style.rs b/app/vendor/rune/crates/rune/src/el/selection_style.rs new file mode 100644 index 0000000..3f93cf3 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/el/selection_style.rs @@ -0,0 +1,50 @@ +//! How a text field or selectable text paints its selection +//! ([`El::selection_style`](crate::El::selection_style)): the highlight under the selected text +//! and the ink the selected glyphs take, while the window is active and while it isn't, as a +//! browser paints `::selection`. + +use crate::color::Color; + +/// Selection colours: active while the window has focus, inactive while it doesn't. +/// `None` ink keeps the text's own colours. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct SelectionStyle { + active: Color, + active_ink: Option<Color>, + inactive: Color, + inactive_ink: Option<Color>, +} + +impl SelectionStyle { + /// Chromium's default selection on Windows and Linux in either color scheme: its + /// `kDefaultActiveSelectionBgColor` (#1967D2) and `kDefaultInactiveSelectionBgColor` + /// (#C8C8C8) made see-through by `Color::BlendWithWhite` (alpha 0.8, so they look the same + /// over white), with white text, and #323232 text while the window is inactive. + pub fn chromium() -> Self { + let c = |h: &str| crate::color::hex(h).unwrap_or(Color::TRANSPARENT); + SelectionStyle { active: c("#0041c6cc"), active_ink: Some(Color::WHITE), inactive: c("#bababacc"), inactive_ink: Some(c("#323232")) } + } + + /// `highlight` under the selected text, active or not, the text keeping its colours. + pub const fn new(highlight: Color) -> Self { + SelectionStyle { active: highlight, active_ink: None, inactive: highlight, inactive_ink: None } + } + + /// The selected glyphs take `ink` while the window is active. + pub const fn ink(mut self, ink: Color) -> Self { + self.active_ink = Some(ink); + self + } + + /// While the window is inactive, `highlight` under the selected text and `ink`, if any, on it. + pub const fn inactive(mut self, highlight: Color, ink: Option<Color>) -> Self { + self.inactive = highlight; + self.inactive_ink = ink; + self + } + + /// The highlight and ink for a window that is `active`. + pub(crate) fn pick(&self, active: bool) -> (Color, Option<Color>) { + if active { (self.active, self.active_ink) } else { (self.inactive, self.inactive_ink) } + } +} diff --git a/app/vendor/rune/crates/rune/src/el/sticky.rs b/app/vendor/rune/crates/rune/src/el/sticky.rs new file mode 100644 index 0000000..82641a5 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/el/sticky.rs @@ -0,0 +1,113 @@ +//! Sticky elements: `El::sticky_top`, `El::sticky_top_showing`, `El::sticky_bottom`, +//! `El::sticky_left` and `El::stuck_shadow`. The shifts are worked out in `runtime/scroll/sticky.rs`. +use crate::el::El; +use crate::el::Shadow; + +/// Which viewport edge an [`El::sticky_top`], [`El::sticky_bottom`] or [`El::sticky_left`] +/// element holds to. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum StickyEdge { Top, Bottom, Left } + +/// `El::sticky_top`, `El::sticky_bottom`, `El::sticky_left` and `El::stuck_shadow`. +#[derive(Clone, Debug, Default, PartialEq)] +pub(crate) struct Sticky { + pub edge: Option<StickyEdge>, + pub inset: f32, + /// `inset` counts from the element's bottom (`El::sticky_top_showing`). + pub tail: bool, + pub shadows: Vec<Shadow>, + /// `El::stuck_fade`: lead and span, in points. + pub fade: Option<[f32; 2]>, + /// `El::stuck_reveal`: the parent's shift, in points, at which this element shows whole. + pub reveal: Option<f32>, +} + +impl El { + /// Hold this element `inset` points below the top of the nearest vertical scroll viewport + /// around it while its parent is in view, as CSS `position: sticky; top: inset` does: a + /// section header that stays put while its section scrolls under it. Its parent's bottom + /// edge (inside its padding) pushes it up and out, so the next section's header takes over. + /// It never moves above where scrolling puts it. + /// + /// The shift is worked out each frame from that frame's scroll offset, so it never lags a + /// scroll. Layout doesn't move; drawing, hit testing, the focus ring, children, + /// [`El::on_drawn_layout`] and [`ElementInfo::rect`](crate::runtime::ElementInfo) follow the + /// drawn place, and [`ElementInfo::stuck`](crate::runtime::ElementInfo) reads the shift. It + /// draws, and hit tests, above its later siblings, and [`El::scroll_edge_fade`] skips the + /// edge it sticks to so its fill and text stay opaque while rows scrolling under it fade. + /// Give it a fill, so rows don't show through, and see [`El::stuck_shadow`] for a shadow or + /// divider while it's stuck. + /// + /// In [`El::virtual_rows`] a header sticks inside its own row: make each section one row + /// (its header and its items) so the header shows whenever any of the section does. A + /// header in a separate virtual row disappears when that row is unmounted. Without a + /// vertical scroll ancestor this is a no-op (a horizontal-only viewport is skipped). + /// Cached subtrees containing sticky elements draw live rather than baking their shifts. + pub fn sticky_top(mut self, inset: f32) -> Self { + let s = self.cold_mut().sticky.get_or_insert_with(Default::default); + s.edge = Some(StickyEdge::Top); + s.inset = if inset.is_finite() { inset } else { 0.0 }; + s.tail = false; + self + } + /// [`El::sticky_top`] held with only its bottom `show` points in view: an item page's header + /// that scrolls up until just its bar is left, then stays. Unlike `sticky_top(show - h)` it + /// follows the element's height as laid out in the frame that draws it, so a header that + /// grows or a new page's taller one sticks in the right place on its first frame. + pub fn sticky_top_showing(mut self, show: f32) -> Self { + self = self.sticky_top(show); + if let Some(s) = self.cold.get_mut_if_some().and_then(|c| c.sticky.as_mut()) { s.tail = true; } + self + } + /// [`El::sticky_top`] against the viewport's bottom edge: held `inset` points above it while + /// its parent is in view, and pushed down by its parent's top edge (a section footer). + pub fn sticky_bottom(mut self, inset: f32) -> Self { + let s = self.cold_mut().sticky.get_or_insert_with(Default::default); + s.edge = Some(StickyEdge::Bottom); + s.inset = if inset.is_finite() { inset } else { 0.0 }; + self + } + /// Hold this element `inset` points right of the left edge of the nearest horizontal scroll + /// viewport around it ([`El::scroll_x`] or [`El::scroll_xy`]) while its parent is in view: + /// [`El::sticky_top`] on the other axis. Give it the viewport's width (not the scrolling + /// content's) so it spans what shows: a row header whose end controls stay in view while + /// the code under it scrolls sideways (horizontal scrolling starts at the left edge, so + /// there is no `sticky_right`). Its parent's right edge pushes it out. Without a + /// horizontal scroll ancestor this is a no-op. [`ElementInfo::stuck`](crate::runtime::ElementInfo) + /// reads the shift to the right. + pub fn sticky_left(mut self, inset: f32) -> Self { + let s = self.cold_mut().sticky.get_or_insert_with(Default::default); + s.edge = Some(StickyEdge::Left); + s.inset = if inset.is_finite() { inset } else { 0.0 }; + self + } + /// A shadow drawn only while this [`El::sticky_top`], [`El::sticky_bottom`] or + /// [`El::sticky_left`] element is stuck, fading in over its first 8 points of shift, so it + /// follows the scroll exactly: an elevation under a stuck header, or a hairline divider with + /// `Shadow { y: 0.5, color, ..Default::default() }` under an opaque one. Several stack. + pub fn stuck_shadow(mut self, shadow: Shadow) -> Self { + self.cold_mut().sticky.get_or_insert_with(Default::default).shadows.push(shadow); + self + } + /// Fades this [`El::sticky_top`] element's first child (its title), not its own fill or its + /// other children (a cover above it, a gradient under it), as the next sticky-top sibling + /// rises to it: whole while that sibling's top is `lead + span` points or + /// more below this one's drawn top, gone once it's `lead` below, linearly between, frame by + /// frame with the scroll. Desktop's Home fades a stuck day header's title so as the next day + /// comes up (`home/scroll.ts`), its fill still covering the rows under it until the next + /// header, a later sibling drawn over it, takes its place. A header with no sticky sibling + /// after it stays whole. + pub fn stuck_fade(mut self, lead: f32, span: f32) -> Self { + self.cold_mut().sticky.get_or_insert_with(Default::default).fade = Some([lead, span.max(0.0)]); + self + } + /// Shows this child of a [`El::sticky_top`] element as far as its parent is stuck: hidden + /// at rest, whole once the parent has held `span` points, linearly between, frame by frame + /// with the scroll. A gradient hung under a stuck header with it fades in as rows scroll + /// beneath, as Desktop's model dialog fades its header's `::after` by how far its rows have + /// scrolled under it (`select-dialog.tsx` `--model-dialog-header-fade`). + pub fn stuck_reveal(mut self, span: f32) -> Self { + self.cold_mut().sticky.get_or_insert_with(Default::default).reveal = Some(span.max(1e-3)); + self + } +} diff --git a/app/vendor/rune/crates/rune/src/el/text.rs b/app/vendor/rune/crates/rune/src/el/text.rs new file mode 100644 index 0000000..a8d07ea --- /dev/null +++ b/app/vendor/rune/crates/rune/src/el/text.rs @@ -0,0 +1,721 @@ +//! Text builders: font, spans and decorations, input pills, wrapping and truncation, reveal, +//! links, placeholder and caret, selection, and edit callbacks. + +use super::*; + +impl El { + /// Keeps this text's height its lines' own, unrounded (22.4 points for a line at a 22.4 + /// line height, 24.375 device pixels for a 19.5 point line at 1.25x), as a browser lays out + /// a paragraph: a stack of texts lands where a web page's does rather than gaining up to a + /// pixel per text. Every text does this unless it asks for [`El::rounded_lines`]. + pub fn exact_lines(mut self) -> Self { + if let Some(t) = &mut self.text { + t.exact_lines = true; + } + self + } + /// Rounds this text's height up to whole device pixels instead of keeping its lines' own + /// ([`El::exact_lines`]), as Rune laid out every text before: a box sized by one text keeps + /// its edges on the pixel grid at any scale. + pub fn rounded_lines(mut self) -> Self { + if let Some(t) = &mut self.text { + t.exact_lines = false; + } + self + } + #[inline] + pub fn font(mut self, s: TextStyle) -> Self { + self.set_font(s); + self + } + /// Replaces the string of a [`text`] element, keeping its style, colour and every other + /// setting: a styled text cloned as a template takes each use's words. Spans and other byte + /// ranges of the old string are dropped. Does nothing to other elements or to a text input. + pub fn set_content(&mut self, content: impl Into<String>) -> &mut Self { + if self.cold.input.is_none() + && let Some(t) = &mut self.text + { + t.content = content.into(); + t.spans.clear(); + if let Some(cold) = t.cold.get_mut_if_some() { + cold.links.clear(); + cold.uncopied.clear(); + cold.strikes.clear(); + cold.highlights.clear(); + cold.pills.clear(); + cold.rings.clear(); + cold.blocks.clear(); + cold.soft_breaks.clear(); + } + t.source = None; + } + self + } + /// [`El::font`] in place. + #[inline] + pub fn set_font(&mut self, s: TextStyle) -> &mut Self { + if let Some(t) = &mut self.text { + t.style = s; + } + if self.cold.input.is_some() { + self.sync_input_rich(); + } + self + } + /// Per-frame styled or coloured byte ranges (syntax highlights, mentions, inline styles) + /// painted over a [`text`], [`rich`] or [`text_input`] element without mutating [`TextEdit`]. + /// On a [`text_input`], byte offsets are relative to `edit.text` and shift automatically + /// across any active IME preedit. + pub fn spans(mut self, spans: impl Into<Vec<Span>>) -> Self { + let spans = spans.into(); + if let Some(inp) = self.cold.get_mut_if_some().and_then(|c| c.input.as_deref_mut()) { + inp.decorations = spans; + self.sync_input_rich(); + } else if let Some(t) = &mut self.text { + t.spans = crate::el::pills::with_pill_colors(&spans, &t.cold.pills); + } + self + } + /// Alias for [`El::spans`]: per-frame syntax or highlight [`Span`]s painted over text + /// (for example `SyntaxTheme::from_kit(&kit).spans(&highlights, code_offset)`). + pub fn decorations(self, spans: impl Into<Vec<Span>>) -> Self { + self.spans(spans) + } + /// An inset `color` border ring `width` points wide inside the rounded [`Span::bg`] of bytes + /// `start..end`. Touching runs of the range on one line share one ring; wrapped lines each + /// get their own. No background means no ring. Later overlapping rings win. + /// Ranges refer to authored UTF-8 bytes and follow text case and truncation. For static + /// text only: editable text does not rebase these ranges after edits. Rebuild ranges when + /// replacing the content. During streaming reveal a ringed chip fades with its last word + /// on each line; selection is painted over the chip and below the glyphs. + pub fn span_ring(mut self, start: usize, end: usize, color: Color, width: f32) -> Self { + if let Some(t) = &mut self.text && start < end && width > 0.0 && width.is_finite() { + t.cold.rings.push((start as u32, end as u32, color, width)); + } + self + } + /// The corner radius in points of this text's rounded [`Span::bg`] backgrounds (4 by + /// default), as a stylesheet's `border-radius` on one kind of span: a diff's changed words + /// at 3, say, while inline code keeps 4. + pub fn span_radius(mut self, radius: f32) -> Self { + if let Some(t) = &mut self.text && radius.is_finite() { + t.cold.span_radius = radius.max(0.0); + } + self + } + /// Inset border rings `(start, end, color, width)` for multiple byte ranges (see [`El::span_ring`]). + pub fn span_rings(mut self, rings: impl IntoIterator<Item = (usize, usize, Color, f32)>) -> Self { + for (start, end, color, width) in rings { + self = self.span_ring(start, end, color, width); + } + self + } + /// A strikethrough line across bytes `start..end` in `color` (`None`: the span's or text's + /// colour). Wrapped lines each get their own segment. + pub fn strike(mut self, start: usize, end: usize, color: Option<Color>) -> Self { + if let Some(t) = &mut self.text && start < end { + t.cold.strikes.push((start as u32, end as u32, color)); + } + self + } + /// Strikethrough lines `(start, end, color)` for multiple byte ranges (see [`El::strike`]). + pub fn strikes(mut self, strikes: impl IntoIterator<Item = (usize, usize, Option<Color>)>) -> Self { + for (start, end, color) in strikes { + self = self.strike(start, end, color); + } + self + } + /// A paint-only [`TextHighlight`](crate::TextHighlight) over bytes of the text. + /// + /// Drawn from the shaped layout's glyph boxes without splitting runs, so adding, moving or + /// clearing highlights never reshapes text or shifts line breaks. + pub fn text_highlight(mut self, highlight: crate::text::TextHighlight) -> Self { + if let Some(t) = &mut self.text && highlight.start < highlight.end { + t.cold.highlights.push(highlight); + } + self + } + /// Paint-only [`TextHighlight`](crate::TextHighlight)s over bytes of the text (see [`El::text_highlight`]). + pub fn text_highlights(mut self, highlights: impl IntoIterator<Item = crate::text::TextHighlight>) -> Self { + for h in highlights { + self = self.text_highlight(h); + } + self + } + /// Set the visual palette for rich inline marks (`code`, `link`) and paragraph blocks + /// (`quote`, `code block`, list markers) on a [`text_input`]. + pub fn rich_style(mut self, style: crate::edit::RichStyle) -> Self { + if let Some(inp) = self.cold.get_mut_if_some().and_then(|c| c.input.as_deref_mut()) { + inp.rich_style = style; + self.sync_input_rich(); + } else if let Some(t) = &mut self.text { + t.cold.rich_style = Some(style); + } + self + } + /// The chip colour of each [`Mark::Pill`](crate::Mark::Pill) in a [`text_input`], and its + /// label and icon colour (`None`: the text's). The chip defaults to the rich style's link + /// colour at 20% opacity. + pub fn pill_colors(mut self, bg: Color, fg: Option<Color>) -> Self { + if let Some(t) = &mut self.text { + t.cold.pill_colors = Some((bg, fg)); + } + if self.cold.input.is_some() { + self.sync_input_rich(); + } + self + } + /// The leading icon for each [`Mark::Pill`](crate::Mark::Pill) chip in a [`text_input`], + /// by the pill's id (`None`: no icon). The icon takes the label's colour. + /// + /// ```ignore + /// text_input(s.draft.clone(), body).pill_icon(|id| id.starts_with("file:").then_some(&FILE)) + /// ``` + /// + /// The closure may capture state; it runs each time the field is built, so a pill follows + /// whatever it captured. For colours too, see [`El::pill_style`]. + pub fn pill_icon(mut self, icon: impl Fn(&str) -> Option<&'static crate::Icon> + 'static) -> Self { + if let Some(inp) = self.cold.get_mut_if_some().and_then(|c| c.input.as_deref_mut()) { + inp.pill_icon = Some(Rc::new(icon)); + self.sync_input_pills(); + self.sync_input_rich(); + } + self + } + /// The look of each [`Mark::Pill`](crate::Mark::Pill) chip in a [`text_input`] by the + /// pill's id: chip colour, label colour and icon, so a person and an agent can differ. + /// What the style leaves unset falls back to [`El::pill_colors`] and [`El::pill_icon`]. + /// The closure may capture app state; it runs each time the field is built, and what it + /// returns is drawn, so a cached subtree restyles when that state changes. + /// + /// ```ignore + /// text_input(s.draft.clone(), body).pill_style({ + /// let agents = s.agents.clone(); + /// move |id| if agents.contains(id) { PillStyle::default().bg(PURPLE).icon(&BOT) } else { PillStyle::default() } + /// }) + /// ``` + pub fn pill_style(mut self, style: impl Fn(&str) -> PillStyle + 'static) -> Self { + if let Some(inp) = self.cold.get_mut_if_some().and_then(|c| c.input.as_deref_mut()) { + inp.pill_style = Some(Rc::new(style)); + self.sync_input_pills(); + self.sync_input_rich(); + } + self + } + + /// Secondary press (right-click or macOS control-click) on a [`Mark::Pill`](crate::Mark::Pill) + /// inside this [`text_input`](crate::text_input). Called with the pill's id and the press point + /// in window points; return `true` to handle it (opening a pill-specific menu) or `false` to + /// fall through to the field's standard context menu. + pub fn on_pill_secondary<S: 'static>(mut self, f: impl Fn(&mut S, &str, PointerPress, &mut Tx) -> bool + 'static) -> Self { + if let Some(inp) = self.cold.get_mut_if_some().and_then(|c| c.input.as_deref_mut()) { + inp.on_pill_secondary = Some(Rc::new(move |s, id, press, tx| f(downcast::<S>(s), id, press, tx))); + } + self + } + pub(super) fn sync_input_pills(&mut self) { + let (Some(inp), Some(t)) = (&self.cold.input, &mut self.text) else { return }; + if inp.edit.is_plain() { + t.cold.pills.clear(); + return; + } + t.cold.pills = inp + .edit + .display_pills() + .into_iter() + .map(|(start, end, id)| { + let st = inp.pill_style.as_ref().map(|f| f(id)).unwrap_or_default(); + let icon = st.icon.or_else(|| inp.pill_icon.as_ref().and_then(|f| f(id))); + crate::text::PillChip { start, end, icon, bg: st.bg, fg: st.fg, bare: None } + }) + .collect(); + } + pub(crate) fn sync_input_rich(&mut self) { + let (Some(inp), Some(t)) = (&self.cold.input, &mut self.text) else { return }; + t.cold.rich_style = Some(inp.rich_style); + if inp.edit.is_plain() && inp.decorations.is_empty() { + // A plain field lays out and draws exactly as before rich editing existed. + t.spans.clear(); + t.cold.strikes.clear(); + t.cold.blocks.clear(); + t.cold.soft_breaks.clear(); + t.cold.pills.clear(); + return; + } + let (mut base_spans, strikes, rich_links, blocks) = + inp.edit.rich_display_specs(t.style, inp.rich_style); + for d in &inp.decorations { + for (ds, de) in inp.edit.map_range_to_display(d.start as usize, d.end as usize) { + let mut sp = d.clone(); + sp.start = ds; + sp.end = de; + base_spans.push(sp); + } + } + let pill_fg = t.cold.pill_colors.and_then(|(_, fg)| fg); + base_spans.extend(t.cold.pills.iter().filter_map(|p| { + Some(Span { start: p.start, end: p.end, color: Some(p.fg.or(pill_fg)?), ..Span::default() }) + })); + let mut flat = crate::text::flatten_spans(&base_spans); + for s in &mut flat { + if s.underline == Some(Color::TRANSPARENT) { + s.underline = Some(s.color.unwrap_or(t.color)); + } + } + t.spans = flat; + t.cold.strikes = strikes; + t.cold.blocks = blocks; + t.cold.soft_breaks = inp.edit.soft_breaks().to_vec(); + // Replace links generated from `Mark::Link` while keeping any explicit `.link(...)` calls. + t.cold.links = rich_links; + } + /// Wrap text at the element's width. + #[inline] + pub fn wrap(mut self) -> Self { + self.set_wrap(); + self + } + /// [`El::wrap`] in place. + #[inline] + pub fn set_wrap(&mut self) -> &mut Self { + if let Some(t) = &mut self.text { + t.wrap = true; + } + self + } + /// Wrap text at the element's width, breaking inside a word only when the word alone would + /// overflow the line (`overflow-wrap: anywhere`) while breaking normal words at spaces, and + /// lowering the text's min-content width. Does not change flex shrinking; use + /// [`El::shrink`] to allow a flex row to narrow the element. + pub fn wrap_anywhere(mut self) -> Self { + if self.cold.input.as_ref().is_some_and(|i| i.single_line) { + return self; + } + if let Some(t) = &mut self.text { + t.wrap = true; + t.wrap_anywhere = true; + } + self + } + /// Break this text's lines greedily when the app wraps text prettily + /// ([`crate::text::set_pretty_wrap`]): text that grows while it's read, such as a reply + /// still streaming in, whose last lines would move as each word arrives. + pub fn wrap_greedy(mut self) -> Self { + if let Some(t) = &mut self.text { + t.greedy = true; + } + self + } + /// Whether this is text that wraps (`.wrap()`), for containers that let such text shrink + /// to their width. + pub fn wraps(&self) -> bool { + self.text.as_ref().is_some_and(|t| t.wrap) + } + /// One line, cut with "…" when wider than the element; the element may shrink below its + /// text's width. A [`text_input`] ignores it and the other truncations. + #[inline] + pub fn truncate(mut self) -> Self { + self.set_truncate(); + self + } + /// [`El::truncate`] in place. + #[inline] + pub fn set_truncate(&mut self) -> &mut Self { + self.set_elide(Elide::End); + self + } + /// [`El::truncate`] keeping both ends: "…" replaces the middle, as AppKit's + /// `NSLineBreakByTruncatingMiddle` does for paths and file names. Cuts fall between + /// graphemes and refit when the element resizes; copying and the accessibility text keep + /// the whole string. + pub fn truncate_middle(mut self) -> Self { + self.set_elide(Elide::Middle); + self + } + /// [`El::truncate`] keeping the end: "…" replaces the start. + pub fn truncate_head(mut self) -> Self { + self.set_elide(Elide::Head); + self + } + fn set_elide(&mut self, elide: Elide) { + // A field's caret and selection index its own text, which a cut would break. + if self.cold.input.is_some() { return; } + self.set_one_line(|t| { + t.truncate = true; + t.elide = elide; + t.truncate_fade = false; + }); + } + /// One unwrapped line that shrinks with its parent; `cut` sets how an overflow is cut. + fn one_line(mut self, cut: impl FnOnce(&mut TextSpec)) -> Self { + self.set_one_line(cut); + self + } + fn set_one_line(&mut self, cut: impl FnOnce(&mut TextSpec)) { + if let Some(t) = &mut self.text { + t.wrap = false; + t.wrap_anywhere = false; + t.max_lines = 0; + cut(t); + } + self.style.set_flex_shrink(1.0); + self.style.set_min_width(length(0.0)); + } + /// Wrapped text that stops after `lines` lines, "…" ending the last when more would follow, + /// as CSS's `line-clamp`. The element measures at most `lines` lines tall. The cut falls + /// between graphemes and refits when the element resizes; spans and links keep their + /// looks up to it, and copying and the accessibility text keep the whole string. 0 shows + /// every line. A [`text_input`] ignores it; use [`auto_grow`] there. + pub fn max_lines(mut self, lines: usize) -> Self { + if self.cold.input.is_some() { return self; } + if let Some(t) = &mut self.text { + t.wrap = true; + t.max_lines = lines; + t.truncate = false; + t.truncate_fade = false; + } + self + } + /// One line, clipped with a 1.5 em trailing fade only when it overflows. No ellipsis. + pub fn truncate_fade(self) -> Self { + self.truncate_fade_width(TRUNCATE_FADE_EM) + } + /// [`El::truncate_fade`] with a fade `em` ems wide. + pub fn truncate_fade_width(self, em: f32) -> Self { + self.one_line(|t| { + t.truncate = false; + t.truncate_fade = true; + t.fade_em = em.max(0.0); + }) + } + /// Streaming word reveal (see [`TextSpec::reveal`]). + pub fn reveal(mut self, word_fade: f32) -> Self { + if let Some(t) = &mut self.text { + t.reveal = word_fade.max(0.0); + } + self + } + /// Keep a text field to one line: long text scrolls sideways under the caret instead of + /// wrapping. Fields are multi-line by default. + pub fn single_line(mut self) -> Self { + if let Some(i) = self.cold.get_mut_if_some().and_then(|c| c.input.as_deref_mut()) { + i.single_line = true; + i.edit.set_single_line(true); + if let Some(t) = &mut self.text { + t.wrap = false; + t.wrap_anywhere = false; + if i.edit.is_masked() { + t.replace_content(i.edit.display().0); + } + } + } + self + } + /// Make a byte range of this text pressable (see [`Link`]). Only the range's shaped glyph + /// boxes take the pointer, which shows a hand over them; the rest of the text stays + /// transparent to input. Each link is a Tab stop that Enter or Space presses. + pub fn link(mut self, link: Link) -> Self { + if let Some(t) = &mut self.text { + t.cold.links.push(link); + self.cold_mut().focus.enabled = true; + if self.handlers.cursor.is_none() { + self.handlers.cursor = Some(Cursor::Pointer); + } + } + self + } + /// Called with a [`Link`]'s id when it is clicked, or pressed with Enter or Space while + /// focused. A middle click on a link calls it too, as a browser opens a link in a new tab: + /// [`Tx::button`] is then [`PointerButton::Middle`](crate::PointerButton::Middle), for a + /// handler whose link only opens in place to ignore. + pub fn on_link<S: 'static>(mut self, f: impl Fn(&mut S, &str, &mut Tx) + 'static) -> Self { + if let Some(t) = &mut self.text { + t.cold.on_link = Some(LinkFn(Rc::new(move |s, id, tx| f(downcast::<S>(s), id, tx)))); + } + self + } + /// Called with a [`Link`]'s id and the point (window points) when a secondary press + /// (right-click, macOS control-click) lands on its glyphs: a menu for that link. It takes + /// the press, so ancestors' [`El::on_secondary_press`] and the text's Copy menu don't see + /// it; elsewhere in the text they still do. + pub fn on_link_secondary<S: 'static>(mut self, f: impl Fn(&mut S, &str, PointerPress, &mut Tx) + 'static) -> Self { + if let Some(t) = &mut self.text { + t.cold.on_link_secondary = Some(LinkSecondaryFn(Rc::new(move |s, id, p, tx| f(downcast::<S>(s), id, p, tx)))); + } + self + } + /// Mark this text field's misspelled words, as a browser's `spellcheck` does: the platform's + /// checker (Windows' spell checking API, AppKit's `NSSpellChecker`; none on Linux or the + /// web) puts a red marker under each word the caret has left, and the field's menu offers its + /// suggestions and Learn Spelling. Off by default; a secure field never checks. + pub fn spellcheck(mut self, on: bool) -> Self { + if let Some(i) = self.cold.get_mut_if_some().and_then(|c| c.input.as_deref_mut()) { + i.spellcheck = on; + } + self + } + pub fn placeholder(mut self, s: impl Into<String>, c: Color) -> Self { + if let Some(i) = self.cold.get_mut_if_some().and_then(|c| c.input.as_deref_mut()) { + i.placeholder = s.into(); + i.placeholder_color = c; + i.placeholder_inked = true; + } + self + } + /// Lay this field's placeholder out in `style` rather than the field's own, as CSS's + /// `::placeholder` can: a phone's field types at 16 pt (so iOS doesn't zoom to it) while its + /// hint keeps the design's size. + pub fn placeholder_font(mut self, style: TextStyle) -> Self { + if let Some(i) = self.cold.get_mut_if_some().and_then(|c| c.input.as_deref_mut()) { + i.placeholder_style = Some(style); + } + self + } + pub fn caret(mut self, caret: Color, selection: Color) -> Self { + if let Some(i) = self.cold.get_mut_if_some().and_then(|c| c.input.as_deref_mut()) { + i.caret = caret; + i.selection = selection; + i.caret_inked = true; + } + self + } + /// Lets people select this read-only text and copy it, as SwiftUI's + /// `.textSelection(.enabled)`: drag across it, double-click a word, triple-click a paragraph, + /// shift-click to extend; Cmd+C (Ctrl+C elsewhere) copies and Cmd+A selects all of it while it + /// holds the selection; a right-click offers Copy on macOS. It shows the I-beam, isn't a Tab + /// stop, and a press anywhere else clears the selection. Selecting never re-lays out the + /// text. Set the highlight with [`El::selection_color`]. + /// + /// Inside a row that handles input, the row keeps it: a click on the text presses the row, + /// hover and press paint reach it, and its `on_secondary_press` wins over Copy. A drag that + /// selects text doesn't press. Inside a draggable (`on_drag`, `drag_out`) row, dragging + /// drags the row, and double- and triple-clicks still select. + #[inline] + pub fn selectable(mut self, on: bool) -> Self { + self.set_selectable(on); + self + } + /// [`El::selectable`] in place. + pub fn set_selectable(&mut self, on: bool) -> &mut Self { + if let Some(t) = &mut self.text { + if self.cold.input.is_some() || t.redacted { return self; } + t.selectable = on; + if on && (self.handlers.cursor.is_none() || (!t.cold.links.is_empty() && self.handlers.cursor == Some(Cursor::Pointer))) { + self.handlers.cursor = Some(Cursor::Text); + } + } + self + } + /// Makes the [`El::selectable`] texts inside this element one selection, in tree order, as + /// the paragraphs of a web page are: a drag from one into another selects across them (the + /// gaps between included), Shift-click extends into any of them, Cmd+A selects them all and + /// Cmd+C copies their text joined by a newline (or the blank line [`El::copy_breaks`] asks + /// for, after any [`El::copy_prefix`]), or a tab between texts side by side (table cells). Double- and triple-clicks still take a word or paragraph of one text. Text that + /// isn't selectable (a list marker) is skipped. Outside a group each text is its own. + pub fn selection_group(mut self, on: bool) -> Self { + self.flags.set(ElFlags::SELECTION_GROUP, on); + self + } + /// What copying a text selection inside this element puts on the clipboard (Cmd+C and the + /// Copy menu) instead of the selected text as drawn, so a document drawn from source can + /// copy the source. `f` sees every [`El::selectable`] text inside this element that the + /// selection could reach (those of its selection group), in tree order, each with its + /// selected range (empty when it isn't selected) and its path relative to this element. + /// Return `None` to copy the drawn text after all ([`TextSelection::text`]). The nearest + /// such element around both ends of the selection answers. Kit's `Markdown::copy_source` + /// is one. + /// + /// ```ignore + /// col().selection_group(true) + /// .selection_copy(move |sel| sel.texts().iter().all(|t| t.is_whole()).then(|| note.clone())) + /// ``` + /// + /// [`TextSelection::text`]: crate::TextSelection::text + pub fn selection_copy(mut self, f: impl Fn(&crate::TextSelection) -> Option<String> + 'static) -> Self { + self.handlers.selection_copy = Some(Rc::new(f)); + self + } + /// Hears the [`El::selectable`] text selection change inside this element: when one starts + /// (the first selected character of a drag, a double-click's word, Cmd+A, + /// [`Tx::select_text`]), changes, leaves this element or clears. [`SelectionChange`] holds + /// the whole selection while any of it is inside this element, `None` otherwise, and says + /// whether it [`started`](crate::SelectionChange::started) or + /// [`cleared`](crate::SelectionChange::cleared) here. It runs at most once a frame, however + /// many times a drag moved the selection, before that frame's commit, and once more when the + /// press making it releases ([`dragging`](crate::SelectionChange::dragging)). A press leaving + /// only a caret isn't heard. Call [`Tx::live_only`] when the view reads nothing that changed. + /// + /// ```ignore + /// col().selection_group(true).on_selection_change(|s: &mut Notes, change, _| { + /// if change.started() { s.whole_note_highlight = false; } + /// }) + /// ``` + /// + /// [`SelectionChange`]: crate::SelectionChange + pub fn on_selection_change<S: 'static>(mut self, f: impl Fn(&mut S, &crate::SelectionChange, &mut Tx) + 'static) -> Self { + self.handlers.on_selection_change = Some(Rc::new(move |s, change, tx| f(downcast::<S>(s), change, tx))); + self + } + /// Draws and lays out, but the pointer and keyboard pass through this element and + /// everything inside it, as with HTML's `inert`: a press, hover, scroll, drop or tooltip + /// goes to whatever is under it (an ancestor or an element drawn below), along with that + /// element's cursor. Handlers inside never run from input, nothing inside takes focus (Tab + /// skips it, a field asking for focus doesn't get it, and focus already inside drops), and + /// accessibility reports it inert. `on_layout` and `Cx::layout` still see its rects. For a + /// document drawn under an editor that takes its presses itself. + pub fn inert(mut self) -> Self { + self.flags.set(ElFlags::INERT, true); + self + } + /// Bytes of [`El::selectable`] text that draw but aren't copied, such as the spacing + /// characters Markdown pads inline code with. A double-click's word stops at them. + pub fn uncopied(mut self, range: std::ops::Range<usize>) -> Self { + if let Some(t) = &mut self.text && range.start < range.end { + let at = t.cold.uncopied.partition_point(|r| (r.0 as usize) < range.start); + t.cold.uncopied.insert(at, (range.start as u32, range.end as u32)); + } + self + } + /// How many newlines copying puts between this [`El::selectable`] text and the text copied + /// before it, and the text after it, when a [`El::selection_group`] selection takes more than + /// one: the larger of the two texts' asks, one by default. Two leaves a blank line, as a web + /// page's paragraphs copy. Texts side by side still take a tab. + /// + /// ```ignore + /// text(para).selectable(true).copy_breaks(2, 2) // "first para\n\nsecond para" + /// ``` + pub fn copy_breaks(mut self, before: u8, after: u8) -> Self { + if let Some(t) = &mut self.text { t.cold.copy_breaks = [before, after]; } + self + } + /// Text copying puts before this [`El::selectable`] text when a selection takes it from its + /// start along with other texts, without drawing it: a list item's `"- "` or `"1. "`, whose + /// drawn marker isn't selectable. A copy of this text alone leaves it out. + pub fn copy_prefix(mut self, prefix: impl Into<std::rc::Rc<str>>) -> Self { + if let Some(t) = &mut self.text { t.cold.copy_prefix = Some(prefix.into()); } + self + } + /// A selection as a browser paints `::selection`, in a text field or [`El::selectable`] + /// text: its highlight and the ink its selected glyphs take, one pair while the window is + /// active and another while it isn't ([`SelectionStyle::chromium`](crate::SelectionStyle::chromium) + /// is Chromium's default). It takes over [`El::caret`]'s and [`El::selection_color`]'s + /// highlight. + pub fn selection_style(mut self, style: crate::SelectionStyle) -> Self { + if let Some(i) = self.cold.get_mut_if_some().and_then(|c| c.input.as_deref_mut()) { i.selection_style = Some(style); } + if let Some(t) = &mut self.text { t.cold.selection_style = Some(style); } + self + } + /// The selection highlight of [`El::selectable`] text or a text field, drawn alike for both. + pub fn selection_color(mut self, color: Color) -> Self { + if let Some(i) = self.cold.get_mut_if_some().and_then(|c| c.input.as_deref_mut()) { i.selection = color; } + if let Some(t) = &mut self.text { t.cold.selection = color; } + self + } + /// Binds the field to a `TextEdit` in app state. `f` may capture (a row index, say); wrap + /// a closure in [`edit_access`] so its returned borrow is tied to the state. + pub fn on_edit<S: 'static>(mut self, f: impl for<'a> Fn(&'a mut S) -> &'a mut TextEdit + 'static) -> Self { + if let Some(i) = self.cold.get_mut_if_some().and_then(|c| c.input.as_deref_mut()) { + i.access = Some(Rc::new(edit_fn(move |s| f(downcast::<S>(s))))); + } + self + } + /// Called when Return submits this text field. In a multi-line field (the default), + /// Shift+Return and Option+Return insert a newline (as does plain Return inside a list, quote + /// or code block), while plain Return in a paragraph calls `on_submit` — or presses the + /// [`El::default_button`] when the field has none. + pub fn on_submit<S: 'static>(mut self, f: impl Fn(&mut S, &mut Tx) + 'static) -> Self { + if let Some(i) = self.cold.get_mut_if_some().and_then(|c| c.input.as_deref_mut()) { + i.submit = Some(Rc::new(move |s, tx| f(downcast::<S>(s), tx))); + } + self + } + /// Let dependent layout reflow when this input changes; the typed text remains immediate. + pub fn animate_edit_layout(mut self) -> Self { + if let Some(i) = self.cold.get_mut_if_some().and_then(|c| c.input.as_deref_mut()) { i.animate_layout = true; } + self + } +} + +impl El { + /// Paint the latest text in this element's fixed layout box. `text("00:00")` reserves + /// that placeholder's size; explicit `.size(w, h)` also works. Updates never resize the + /// box or reflow siblings, and overflow is clipped. Plain single-line text only. + pub fn live_text(mut self, value: &crate::LiveText) -> Self { + assert!(self.cold.input.is_none(), "live_text cannot bind a text editor"); + let spec = self.text.as_mut().expect("live_text requires a text element"); + spec.cold.live = Some(value.clone()); + self + } + #[inline] + pub fn color(mut self, c: Color) -> Self { + self.set_color(c); + self + } + /// [`El::color`] in place. + #[inline] + pub fn set_color(&mut self, c: Color) -> &mut Self { + if let Some(t) = &mut self.text { + t.color = c; + t.inked = true; + } + if let Some(cold) = self.vis.cold.get_mut_if_some() && let Some((_, ic)) = &mut cold.icon { + *ic = c; + cold.icon_inked = true; + } + if self.cold.input.is_some() { + self.sync_input_rich(); + } + self + } + #[inline] + pub fn align(mut self, a: Align) -> Self { + self.set_align(a); + self + } + /// [`El::align`] in place. + #[inline] + pub fn set_align(&mut self, a: Align) -> &mut Self { + if let Some(t) = &mut self.text { + t.align = a; + } + self + } + /// Draw this text in capitals or lower case without changing its string, like SwiftUI's + /// `textCase`: `text("Text channels").text_case(TextCase::Uppercase)` draws "TEXT CHANNELS". + /// The dev tree, tools and link labels keep the authored text, and [`Span`] and [`Link`] + /// ranges stay byte ranges of it. Casing follows `str::to_uppercase`, so "ß" draws "SS". + /// Text fields draw what is typed and ignore it. + pub fn text_case(mut self, case: crate::TextCase) -> Self { + if let Some(t) = &mut self.text { + t.case = Some(case); + } + self + } + /// Spread each wrapped line but the last to fill the width; the last line and unwrapped text + /// keep [`El::align`]. + pub fn justify(mut self) -> Self { + if let Some(t) = &mut self.text { + t.justify = true; + } + self + } + /// Measure this text as the grapheme at byte `at` of `run`, shaped as one line in the same + /// style, instead of on its own rounded up to a device pixel. Neighbouring cells of one run + /// then sit at its fractional, kerned advances and together take its width, and each draws + /// the run's own glyphs for its grapheme (contextual forms included). + pub fn advance_in(mut self, run: &crate::text::Run, at: usize) -> Self { + if let Some(t) = &mut self.text { + t.cold.advance_in = Some((run.clone(), at)); + } + self + } + /// A filled disc in a list's outside marker column. The column's inline end is where the + /// item's text begins; its top is the top of the first line. Its width, and thus wrapping, + /// is up to the caller. The disc's diameter and inset resolve from the primary font's + /// metrics in whole device pixels during layout, also after a zoom or display change. + pub fn outside_list_disc(mut self, font: TextStyle) -> Self { + let (a, d) = crate::text::primary_extents(font).unwrap_or((0.8, 0.2)); + self.cold_mut().list_disc = Some([a * font.size, d.abs() * font.size, font.line_px()]); + self.radius(999.0).a11y_hidden() + } +} diff --git a/app/vendor/rune/crates/rune/src/el/text_spec.rs b/app/vendor/rune/crates/rune/src/el/text_spec.rs new file mode 100644 index 0000000..b5b7e4b --- /dev/null +++ b/app/vendor/rune/crates/rune/src/el/text_spec.rs @@ -0,0 +1,424 @@ +//! [`TextSpec`]: what a text element shows and how it lays out. +use crate::cold::{Cold, Empty}; +use crate::color::Color; +use crate::el::{Align, LinkFn, LinkSecondaryFn}; +use crate::text::{Link, Span}; +use crate::tok::TextStyle; + +/// A text element's record. What most texts set stays inline; what few set (links, rings, +/// pills, copy rules, a run to measure in, live text) waits behind `cold`, allocated on the +/// first write, so building a plain text allocates one small block. +#[derive(Clone)] +pub struct TextSpec { + pub content: String, + pub style: TextStyle, + pub color: Color, + pub spans: Vec<Span>, + /// Wrapped lines shown before "…" ends the last (see [`El::max_lines`](crate::El::max_lines)); 0 for all. + pub(crate) max_lines: usize, + /// The scale's bits and [`crate::text::shape_key`] at it, once the content is final (see + /// [`TextSpec::key_shape`]). + pub(crate) shape: Option<(u32, u64)>, + /// The authored string once `case` has replaced `content` with the drawn one. + pub(crate) source: Option<Box<crate::text::CaseSource>>, + pub(crate) cold: Cold<TextCold>, + /// Streaming word reveal: words that arrive after mount fade in over this many seconds + /// (negative: no reveal tracking). + pub reveal: f32, + /// The `truncate_fade` edge's width in ems (see [`El::truncate_fade_width`](crate::El::truncate_fade_width)). + pub(crate) fade_em: f32, + pub align: Align, + /// `color` came from [`El::color`](crate::El::color); without it the text takes the + /// window's foreground ([`Cx::foreground`](crate::Cx::foreground)) when the view sets one. + pub(crate) inked: bool, + /// Wrap at the element's width (its height follows the text). + pub wrap: bool, + /// One line, cut with an ellipsis when wider than the element. + pub truncate: bool, + /// Which part `truncate` cuts (see [`El::truncate_middle`](crate::El::truncate_middle)). + pub(crate) elide: Elide, + /// Fade the overflowing trailing edge rather than replacing text with an ellipsis. + pub truncate_fade: bool, + /// Spread wrapped lines to fill the width (see [`El::justify`](crate::El::justify)). + pub justify: bool, + /// See [`El::text_case`](crate::El::text_case); applied when the element is laid out. + pub(crate) case: Option<crate::TextCase>, + /// See [`El::selectable`](crate::El::selectable). + pub(crate) selectable: bool, + pub(crate) redacted: bool, + pub(crate) wrap_anywhere: bool, + /// See [`El::wrap_greedy`](crate::El::wrap_greedy). + pub(crate) greedy: bool, + /// See [`El::exact_lines`](crate::El::exact_lines): the height is its lines' own, unrounded, + /// unless [`El::rounded_lines`](crate::El::rounded_lines) rounds it to device pixels. + pub(crate) exact_lines: bool, + /// See [`El::by_line`](crate::El::by_line): one shaped [`Layout`](crate::text::Layout) per line. + pub(crate) by_line: bool, + /// The paragraph direction it lays out in (see [`TextDir`]). + pub(crate) dir: TextDir, +} + +pub(crate) use rune_text::TextDir; + +/// What moves a text's [`TextDir`]. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum TextDirEvent { + /// `El::dir_by_paragraph`. + ByParagraph, + /// Flattening resolved the element's direction: `None` when nothing above it sets one. + Flatten(Option<crate::el::Flow>), +} + +/// One step of a text's [`TextDir`]: by-paragraph text keeps its own directions whatever +/// direction the element resolves to. +pub(crate) fn step_text_dir(state: TextDir, event: TextDirEvent) -> TextDir { + match (state, event) { + (TextDir::Plaintext(flow), TextDirEvent::ByParagraph) => TextDir::Plaintext(flow), + (_, TextDirEvent::ByParagraph) => TextDir::Plaintext(None), + (TextDir::Plaintext(_), TextDirEvent::Flatten(flow)) => TextDir::Plaintext(flow), + (_, TextDirEvent::Flatten(Some(flow))) => TextDir::Fixed(flow), + (_, TextDirEvent::Flatten(None)) => TextDir::Auto, + } +} + +/// What few texts set: written through `TextSpec::cold`, which allocates it on the first write. +#[derive(Clone)] +pub(crate) struct TextCold { + /// Plain live run. Layout is measured from the authored placeholder before latching it. + pub(crate) live: Option<crate::LiveText>, + pub(crate) links: Vec<Link>, + pub(crate) on_link: Option<LinkFn>, + pub(crate) on_link_secondary: Option<LinkSecondaryFn>, + /// Measured as its slice at this byte of the run (see [`El::advance_in`](crate::El::advance_in)). + pub(crate) advance_in: Option<(crate::text::Run, usize)>, + /// See [`El::selection_color`](crate::El::selection_color). + pub(crate) selection: Color, + /// See [`El::selection_style`](crate::El::selection_style): it takes over `selection`. + pub(crate) selection_style: Option<crate::SelectionStyle>, + /// See [`El::uncopied`](crate::El::uncopied): byte ranges of `content`, sorted. + pub(crate) uncopied: Vec<(u32, u32)>, + /// See [`El::copy_breaks`](crate::El::copy_breaks): newlines before and after it. + pub(crate) copy_breaks: [u8; 2], + /// See [`El::copy_prefix`](crate::El::copy_prefix). + pub(crate) copy_prefix: Option<std::rc::Rc<str>>, + /// Inset border rings `(start, end, color, width)` on rounded span backgrounds. + pub(crate) rings: Vec<(u32, u32, Color, f32)>, + /// See [`El::span_radius`](crate::El::span_radius), in points. + pub(crate) span_radius: f32, + /// Strikethrough byte ranges `(start, end, color)` of `content`. + pub(crate) strikes: Vec<(u32, u32, Option<Color>)>, + /// Paint-only highlight byte ranges of `content`. + pub(crate) highlights: Vec<crate::text::TextHighlight>, + /// Per-paragraph [`Block`](crate::Block) attributes for `content`. + pub(crate) blocks: Vec<crate::edit::Block>, + /// Line indices (`> 0`) created by `Shift+Return` (`<br>`). + pub(crate) soft_breaks: Vec<u32>, + /// [`Mark::Pill`](crate::Mark::Pill) chips in `content`, sorted. + pub(crate) pills: Vec<crate::text::PillChip>, + /// See [`El::isolate`](crate::El::isolate): byte ranges of `content` still to mark, sorted. + pub(crate) isolates: Vec<(u32, u32, crate::Direction)>, + /// See [`El::pill_colors`](crate::El::pill_colors). + pub(crate) pill_colors: Option<(Color, Option<Color>)>, + /// Visual palette for rich block and inline decorations; the default's when unset. + pub(crate) rich_style: Option<crate::edit::RichStyle>, + pub(crate) secure_revealed: bool, +} + +impl Empty for TextCold { + const EMPTY: &'static Self = &TextCold { + live: None, + links: Vec::new(), + on_link: None, + on_link_secondary: None, + advance_in: None, + selection: crate::el::DEFAULT_SELECTION, + selection_style: None, + uncopied: Vec::new(), + copy_breaks: [1, 1], + copy_prefix: None, + rings: Vec::new(), + span_radius: crate::text::SPAN_RADIUS, + strikes: Vec::new(), + highlights: Vec::new(), + blocks: Vec::new(), + soft_breaks: Vec::new(), + pills: Vec::new(), + isolates: Vec::new(), + pill_colors: None, + rich_style: None, + secure_revealed: false, + }; +} + +#[cfg(target_pointer_width = "64")] +const _: () = assert!(std::mem::size_of::<TextSpec>() == 224); + +impl TextSpec { + /// A plain text showing `content`, in the body style. + pub(crate) fn new(content: String) -> TextSpec { + TextSpec { + content, + style: crate::tok::type_::BODY, + color: Color::WHITE, + spans: Vec::new(), + max_lines: 0, + shape: None, + source: None, + cold: Cold::NONE, + reveal: -1.0, + fade_em: crate::el::TRUNCATE_FADE_EM, + align: Align::Start, + inked: false, + wrap: false, + truncate: false, + elide: Elide::End, + truncate_fade: false, + justify: false, + case: None, + selectable: false, + redacted: false, + wrap_anywhere: false, + greedy: false, + exact_lines: true, + by_line: false, + dir: TextDir::Auto, + } + } + + /// Borrowed read-only layout inputs for `rune-text`. + pub(crate) fn as_text_input(&self, scale: f32, input: bool) -> crate::text::TextInput<'_> { + crate::text::TextInput { + content: &self.content, + spans: &self.spans, + blocks: &self.cold.blocks, + pills: &self.cold.pills, + style: self.style, + shape_key: self.shape_key(scale), + wrap_anywhere: self.wrap_anywhere, + pretty: self.pretty(), + redacted: self.redacted, + by_line: self.by_line, + by_paragraph: self.by_paragraph(input), + dir: self.dir, + } + } + + /// The palette its rich decorations draw in. + pub(crate) fn rich_style(&self) -> crate::edit::RichStyle { + self.cold.rich_style.unwrap_or_default() + } +} +impl std::fmt::Debug for TextSpec { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("TextSpec") + .field("content", &if self.redacted { "[redacted]" } else { &self.content }) + .field("style", &self.style) + .field("color", &self.color) + .field("align", &self.align) + .field("spans", &self.spans) + .field("wrap", &self.wrap) + .field("reveal", &self.reveal) + .field("truncate", &self.truncate) + .field("max_lines", &self.max_lines) + .field("truncate_fade", &self.truncate_fade) + .field("justify", &self.justify) + .field("selectable", &self.selectable) + .finish_non_exhaustive() + } +} + +impl Drop for TextSpec { + fn drop(&mut self) { + if self.redacted { + use zeroize::Zeroize; + self.content.zeroize(); + if let Some(src) = &mut self.source { + src.text.zeroize(); + } + } + } +} + +impl TextSpec { + /// Hashes what shaping depends on once, so measuring and laying the text out at each width + /// this commit reuses it. Secure text keeps no content-derived key. + pub(crate) fn key_shape(&mut self, scale: f32) { + self.shape = (!self.redacted).then(|| (scale.to_bits(), self.fresh_shape_key(scale))); + } + + /// The key [`Self::key_shape`] kept at `scale`. + pub(crate) fn shape_key(&self, scale: f32) -> Option<u64> { + let (_, key) = self.shape.filter(|s| s.0 == scale.to_bits())?; + debug_assert_eq!(key, self.fresh_shape_key(scale), "a text changed after its shape key was taken"); + Some(key) + } + + /// Whether its lines break as Chromium's `text-wrap-style: pretty` does ([`crate::text::set_pretty_wrap`]). + pub(crate) fn pretty(&self) -> bool { + crate::text::pretty_wrap() && !self.greedy && !self.redacted && !self.justify + } + + /// [`crate::text::shape_key`] of this text in its direction. + pub(crate) fn fresh_shape_key(&self, scale: f32) -> u64 { + let key = crate::text::shape_key(&self.content, &self.spans, self.style, scale, self.wrap_anywhere, &self.cold.pills); + crate::text::directed(key, self.base()) + } + + /// The paragraph direction it lays out in as one layout. + pub(crate) fn base(&self) -> parley::BaseDirection { + match self.dir { + TextDir::Fixed(flow) => flow.base(), + TextDir::Auto => parley::BaseDirection::Auto, + // A paragraph with no strong character reads the way the element does. + TextDir::Plaintext(flow) => match crate::Direction::of(&self.content) { + Some(crate::Direction::Rtl) => parley::BaseDirection::Rtl, + Some(_) => parley::BaseDirection::Ltr, + None => flow.unwrap_or_default().base(), + }, + } + } + + /// Whether it lays out one paragraph at a time ([`crate::text::ParagraphLayout`]), so an + /// edit shapes only the paragraphs it changed: a wrapped, uncut field's text of more than + /// one paragraph, or of any when each paragraph takes its own direction. Others stay one + /// layout (a static text splits into one text per paragraph instead). + pub(crate) fn by_paragraph(&self, input: bool) -> bool { + (input || self.by_line) && self.wrap && !self.redacted && !self.truncate && !self.truncate_fade + && self.max_lines == 0 && self.cold.live.is_none() && self.cold.advance_in.is_none() + && (self.by_line || matches!(self.dir, TextDir::Plaintext(_)) || self.content.contains('\n')) + } + + /// Zeroizes the shown string and shows `content` instead. + pub(crate) fn replace_content(&mut self, content: String) { + use zeroize::Zeroize; + self.content.zeroize(); + self.content = content; + self.shape = None; + } + + /// The string as authored, before [`El::text_case`](crate::El::text_case). + pub(crate) fn source_text(&self) -> &str { + self.source.as_ref().map_or(&self.content, |s| &s.text) + } + + /// The authored text of `content[start..end]`. + pub(crate) fn source_slice(&self, start: u32, end: u32) -> Option<&str> { + match &self.source { + None => self.content.get(start as usize..end as usize), + Some(s) => s.text.get(s.source(start, false) as usize..s.source(end, true) as usize), + } + } + + /// The authored text of `content[start..end]` as copying takes it, without its + /// [`El::uncopied`](crate::El::uncopied) bytes. + pub(crate) fn copy_slice(&self, start: u32, end: u32) -> Option<String> { + if self.redacted { + return None; + } + let mut out = String::new(); + let mut at = start; + for &(a, b) in self.cold.uncopied.iter().filter(|r| r.1 > start && r.0 < end) { + if a > at { out.push_str(self.source_slice(at, a)?); } + at = at.max(b); + } + if at < end { out.push_str(self.source_slice(at, end)?); } + Some(out) + } + + /// Masks `self.content` in place and zeroizes the plain string (for layout of a hidden + /// secure label or an exiting revealed one). + pub(crate) fn conceal(&mut self) { + if !self.redacted { + return; + } + + self.shape = None; + let mask = if self.content.is_empty() { + String::new() + } else { + crate::edit::MULTILINE_SECURE_MASK.to_owned() + }; + use zeroize::Zeroize; + self.content.zeroize(); + self.content = mask; + if let Some(mut src) = self.source.take() { + src.text.zeroize(); + } + self.case = None; + self.spans.clear(); + if let Some(cold) = self.cold.get_mut_if_some() { + cold.secure_revealed = false; + cold.links.clear(); + cold.rings.clear(); + cold.strikes.clear(); + cold.blocks.clear(); + cold.soft_breaks.clear(); + cold.pills.clear(); + cold.uncopied.clear(); + } + self.wrap = false; + self.wrap_anywhere = false; + self.max_lines = 0; + } + + /// Replaces `content` (the authored string) with its cased form and moves span and link + /// ranges onto it. + pub(crate) fn apply_case(&mut self) { + self.shape = None; + if self.redacted { + self.case = None; + return; + } + // Ring boundaries need distinct brushes even when the surrounding styles match. + // Do this once before shaping, not once per glyph run at paint time. + if !self.cold.rings.is_empty() { + let mut spans = Vec::new(); + for span in &self.spans { + let mut bounds = vec![span.start, span.end]; + for &(a, b, _, _) in &self.cold.rings { + bounds.extend([a, b].into_iter().filter(|&p| span.start < p && p < span.end)); + } + bounds.sort_unstable(); + bounds.dedup(); + spans.extend(bounds.windows(2).map(|w| Span { start: w[0], end: w[1], ..span.clone() })); + } + self.spans = spans; + } + let Some(case) = self.case else { return }; + let (shown, source) = crate::text::CaseSource::new(case, std::mem::take(&mut self.content)); + for span in &mut self.spans { + (span.start, span.end) = (source.shown(span.start, false), source.shown(span.end, true)); + } + if let Some(cold) = self.cold.get_mut_if_some() { + for link in &mut cold.links { + (link.start, link.end) = (source.shown(link.start, false), source.shown(link.end, true)); + } + for r in &mut cold.uncopied { + *r = (source.shown(r.0, false), source.shown(r.1, true)); + } + for r in &mut cold.rings { + (r.0, r.1) = (source.shown(r.0, false), source.shown(r.1, true)); + } + for r in &mut cold.strikes { + (r.0, r.1) = (source.shown(r.0, false), source.shown(r.1, true)); + } + for h in &mut cold.highlights { + (h.start, h.end) = (source.shown(h.start, false), source.shown(h.end, true)); + } + } + self.content = shown; + self.source = Some(Box::new(source)); + } +} + +/// The part of an overflowing `truncate`d text the ellipsis replaces. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(crate) enum Elide { + /// [`El::truncate`](crate::El::truncate): keeps the start. + #[default] + End, + /// [`El::truncate_middle`](crate::El::truncate_middle): keeps the start and the end. + Middle, + /// [`El::truncate_head`](crate::El::truncate_head): keeps the end. + Head, +} diff --git a/app/vendor/rune/crates/rune/src/el/tx.rs b/app/vendor/rune/crates/rune/src/el/tx.rs new file mode 100644 index 0000000..5ad7ee8 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/el/tx.rs @@ -0,0 +1,755 @@ +//! `Tx`: what a handler may say about the commit it causes. + +use std::rc::Rc; + +use rune_motion::{Anim, Spring}; + +use crate::el::*; + +mod keys; +mod press; +mod scroll; + +#[cfg(test)] +mod tests; + +/// What a handler may say about the commit it causes. +#[derive(Clone, Debug, Default)] +pub struct Tx { + pub(crate) shortcut_activation_token: Option<String>, + pub(crate) key_repeat: bool, + /// `Tx::drag_repeat`. + pub(crate) drag_repeat: bool, + /// `Tx::drag_repeat_after`. + pub(crate) drag_repeat_after: Option<std::time::Duration>, + /// `Tx::input_time`. + pub(crate) input_time: Option<crate::time::Instant>, + /// `Tx::input_waiting`. + pub(crate) input_waiting: bool, + pub(crate) physical_key: Option<crate::PhysicalKeyCode>, + pub(crate) key_base: Option<char>, + pub(crate) focused: Option<String>, + /// What this change does with motion ([`Tx::instant`], [`Tx::animated`], [`Tx::settle`]). + pub(crate) commit: Commit, + /// The motion this change's layout moves on ([`Tx::motion`], [`Tx::motion_curve`]). + pub(crate) motion: Option<MotionSource>, + /// `Tx::follow_edge`. + pub(crate) follow_edge: bool, + /// No input in this window caused this commit and no handler asked for motion + /// (`Tx::animated`): what it mounts and unmounts appears and goes in its final state. + /// Set by the runtime for each frame's commit. + pub(crate) unprompted: bool, + /// A handler called [`Self::animated`]. + pub(crate) asked_motion: bool, + /// Virtual growth stacks whose visible tail may grow for this commit alone. + pub(crate) live_growth: Vec<(String, bool)>, // selector, carry row ink + pub(crate) tail_rooms: Vec<(String, String, String)>, + /// A resting poll changed the model but hasn't committed its tree yet. + pub(crate) polled_change: bool, + pub(crate) color_motion: Option<Spring>, + pub(crate) relayout: bool, + /// The viewport moved only because the window's own resize animation stepped it. + pub(crate) window_step: bool, + pub(crate) copy: Option<crate::ClipboardWrite>, + pub(crate) paste: bool, + pub(crate) clipboard_reads: Vec<ClipboardRead>, + pub(crate) pick_reads: Vec<PickRead>, + pub(crate) clear_secret: bool, + pub(crate) text_flights: Vec<(String, String)>, + /// `Tx::launch`: (source, destination). + pub(crate) launches: Vec<(String, String)>, + /// `Tx::unclipped_flights`. + pub(crate) unclipped_flights: bool, + /// Rows to reveal or centre (`Tx::scroll_into_view` and `Tx::scroll_center`). + pub(crate) scroll_to: Vec<crate::runtime::ScrollReveal>, + /// Scroll viewports to send to their bottom: (key, animated). + pub(crate) scroll_bottom: Vec<(String, bool)>, + /// Scroll viewports to page: (key, pages). + pub(crate) scroll_pages: Vec<(String, i32)>, + /// Scroll viewports to move to offsets (`Tx::scroll_to` and kin). + pub(crate) scroll_offsets: Vec<crate::runtime::ScrollRequest>, + /// Elements to hold where they show across this commit (`Tx::keep_on_screen`). + pub(crate) keep_on_screen: Vec<String>, + pub(crate) wakes: Vec<std::time::Duration>, + pub(crate) shell: Option<Shell>, + pub(crate) minimize_order: Option<std::num::NonZeroU64>, + /// `Tx::toggle_maximized`. + pub(crate) toggle_maximized: bool, + /// `Tx::toggle_full_screen`. + pub(crate) toggle_full_screen: bool, + /// `Tx::send_key`, in order. + pub(crate) keys: Vec<crate::KeyEvent>, + /// `Tx::drop_point`. + pub(crate) drop_point: Option<PointerEvent>, + pub(crate) title: Option<String>, + /// `Tx::announce`: what a screen reader says after this handler. + pub(crate) announce: Option<(String, crate::LiveRegion)>, + pub(crate) open_urls: Vec<crate::open_url::Link>, + pub(crate) trace: Option<TraceCalls>, + pub(crate) popups: Vec<crate::popup_menu::Call>, + pub(crate) file_dialogs: Vec<crate::file_dialog::Call>, + pub(crate) window_frame: Option<crate::window::frame::FrameRequest>, + /// The mouse button driving this press or drag (`Tx::button`). + pub(crate) button: crate::PointerButton, + pub(crate) touch_tap: bool, + /// Modifier keys held as the handler runs. + pub(crate) mods: crate::Mods, + pub(crate) srgb_blend: Option<bool>, + /// `Tx::record_rewind`. + pub(crate) rewind: Option<Option<crate::rewind::Rewind>>, + pub(crate) font_smoothing: Option<crate::text::FontSmoothing>, + pub(crate) font_families: Option<(String, String)>, + pub(crate) blur: bool, + /// `Tx::focus` and `Tx::return_focus`: the key, whether its ring shows, and which asked. + pub(crate) focus_to: Option<(String, bool, FocusAsk)>, + /// `Tx::focus_visible`. + pub(crate) focus_visible: bool, + /// `Tx::assistive_technology`. + pub(crate) assistive: bool, + /// `Tx::by_keys`. + pub(crate) by_keys: bool, + /// The text selection as the event arrived (`Tx::text_selection`). + pub(crate) selection: Option<Rc<crate::TextSelection>>, + /// `Tx::select_text`, `Tx::select_all_text` and `Tx::clear_text_selection`; the last wins. + pub(crate) select: Option<SelectRequest>, + /// `select` came from an `El::on_selection_change` handler, so applying it must not queue + /// another `on_selection_change` round for that change. + pub(crate) select_from_change: bool, + /// `Tx::live_only`: this handler changed nothing the view reads. + pub(crate) live_only: bool, + /// `Tx::open_playground` and kin, and the playground's own controls. + pub(crate) playground: Vec<crate::playground::Request>, + /// `Tx::invalidate_memos_by_prefix`. + pub(crate) evict_memos: Vec<String>, + /// `Tx::clock`. + pub(crate) clock: f64, +} + +/// Which asked for focus: [`Tx::focus`], [`Tx::focus_when_shown`], or [`Tx::return_focus`] +/// handing it back. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum FocusAsk { + Focus, + WhenShown, + Return, +} + +/// A change to the text selection a handler asked for, carried out after its commit. +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) enum SelectRequest { + Range(String, std::ops::Range<usize>), + All(String), + Clear, +} + +/// What a change does with motion, from `Tx::instant`, `Tx::animated` and `Tx::settle`, where +/// the last call in a handler wins. Two facts live in it so neither can disagree with the +/// other: whether this change's own layout applies at once, and whether it lands every running +/// track. `settle` then `animated` keeps the second without the first. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(crate) enum Commit { + /// Animate this change; motion an earlier change set going keeps running. + #[default] + Animate, + /// Only the lack of an input cause made this commit instant. An explicit instant wins + /// even over a request to animate a list's tail. + Unprompted, + /// Apply this change at once; motion an earlier change set going keeps running. + Instant, + /// Apply this change at once and land every running track. + Settle, + /// Land every running track, and still animate this change's own layout: `settle` then + /// `animated`. + SettleAnimated, +} + +impl Commit { + pub(crate) fn without_input(self) -> Self { + if self == Self::Animate { Self::Unprompted } else { self.instant() } + } + + /// The two facts as one intent. + pub(crate) fn new(snaps: bool, lands: bool) -> Commit { + match (snaps, lands) { + (false, false) => Commit::Animate, + (true, false) => Commit::Instant, + (true, true) => Commit::Settle, + (false, true) => Commit::SettleAnimated, + } + } + + /// This change's own layout applies at once instead of moving on its spring. + pub(crate) fn snaps(self) -> bool { + matches!(self, Commit::Unprompted | Commit::Instant | Commit::Settle) + } + + /// This change lands every running track: growth, reveals and follow-the-end. + pub(crate) fn lands(self) -> bool { + matches!(self, Commit::Settle | Commit::SettleAnimated) + } + + /// Set or clear the snap, keeping whether running tracks land. + pub(crate) fn snap(self, snaps: bool) -> Commit { + Commit::new(snaps, self.lands()) + } + + /// `Tx::instant`: this change applies at once. + pub(crate) fn instant(self) -> Commit { + self.snap(true) + } + + /// `Tx::animated`: this change animates, while running tracks still land if they were asked + /// to, and a later `instant` in the same change wins. + pub(crate) fn animated(self) -> Commit { + self.snap(false) + } + + /// Two handlers' asks for one commit: either may snap or land it. + pub(crate) fn merge(self, one: Commit) -> Commit { + Commit::new(self.snaps() || one.snaps(), self.lands() || one.lands()) + } +} + +/// The motion a change's layout moves on: `Tx::motion`'s spring, or a whole curve from +/// `Tx::motion_curve`. Read as one source, so the curve and the spring stand-in that only +/// spring-taking motion uses can never disagree. +#[derive(Clone, Copy, Debug, PartialEq)] +pub(crate) enum MotionSource { + /// A spring, as Rune's layout springs normally are. + Spring(Spring), + /// A curve, with the zero-bounce spring of its duration for what the layout moves but only + /// takes a spring (matched flights). Scroll requests aren't one: they glide on the spring + /// they name. + Curve { anim: Anim, spring: Spring }, +} + +impl MotionSource { + /// `Tx::motion_curve`'s source: the curve, and its stand-in spring. + pub(crate) fn curve(anim: Anim) -> MotionSource { + let spring = match anim.curve { + rune_motion::Curve::Spring(s) => s, + c => Spring::new(c.logical_duration().max(0.01), 0.0), + }; + MotionSource::Curve { anim, spring } + } + + /// The spring this change's layout moves on. + pub(crate) fn spring(self) -> Spring { + match self { + MotionSource::Spring(spring) | MotionSource::Curve { spring, .. } => spring, + } + } + + /// The curve this change's layout moves on, for what draws progress rather than stepping a + /// spring. + pub(crate) fn anim(self) -> Anim { + match self { + MotionSource::Spring(spring) => spring.into(), + MotionSource::Curve { anim, .. } => anim, + } + } +} + +#[derive(Clone, Debug, Default)] +pub(crate) struct TraceCalls { + pub events: Vec<String>, + pub channels: Vec<(&'static str, &'static str, f32)>, +} + +/// What a handler asks of the window and the app (`Tx::close_window`, `Tx::quit`); the later +/// variant wins when several handlers ask. +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)] +pub enum Shell { + /// Close the window as if the user had: `App::keep_running` keeps the app and its state. + Close, + Quit, + /// Quit, then start the app again (`Tx::relaunch`). + Relaunch, +} + +impl Shell { + /// What follows the app's exit for this request, when it quits. + pub(crate) fn after(self) -> Option<crate::quit::After> { + match self { + Shell::Close => None, + Shell::Quit => Some(crate::quit::After::Exit), + Shell::Relaunch => Some(crate::quit::After::Relaunch), + } + } +} + +impl Tx { + /// Pick from the last presented frame, with the geometry and visibility rules of + /// [`Runtime::element_at`](crate::Runtime::element_at). Runs `f` after this handler, + /// before its view commit. Pass `PointerEvent::window_x` and `window_y`, not local points. + /// No picking data is copied or maintained when this is unused. Queries made by `f` + /// itself wait until the next frame. + pub fn element_at<S: 'static>(&mut self, x: f32, y: f32, f: impl FnOnce(&mut S, Option<crate::Picked>, &mut Tx) + 'static) { + self.pick_read(None, x, y, crate::Pick::default(), f); + } + + /// [`Tx::element_at`] with options ([`Pick`](crate::Pick)). + pub fn element_at_with<S: 'static>(&mut self, x: f32, y: f32, pick: crate::Pick, f: impl FnOnce(&mut S, Option<crate::Picked>, &mut Tx) + 'static) { + self.pick_read(None, x, y, pick, f); + } + + /// [`Tx::element_at`] restricted to `within` and its descendants. The scope accepts a + /// key or key path like [`Cx::layout`](crate::Cx::layout); other drawn subtrees do not + /// occlude this query. A missing scope returns `None`. + pub fn element_at_in<S: 'static>(&mut self, within: impl Into<String>, x: f32, y: f32, f: impl FnOnce(&mut S, Option<crate::Picked>, &mut Tx) + 'static) { + self.pick_read(Some(within.into()), x, y, crate::Pick::default(), f); + } + + /// [`Tx::element_at_in`] with options ([`Pick`](crate::Pick)). + pub fn element_at_in_with<S: 'static>(&mut self, within: impl Into<String>, x: f32, y: f32, pick: crate::Pick, f: impl FnOnce(&mut S, Option<crate::Picked>, &mut Tx) + 'static) { + self.pick_read(Some(within.into()), x, y, pick, f); + } + + fn pick_read<S: 'static>(&mut self, within: Option<String>, x: f32, y: f32, pick: crate::Pick, f: impl FnOnce(&mut S, Option<crate::Picked>, &mut Tx) + 'static) { + let f: PickFn = Box::new(move |s, picked, tx| { + if let Some(s) = s.cast::<S>() { f(s, picked, tx); } + }); + self.pick_reads.push(PickRead { within, x, y, pick, f: Rc::new(std::cell::Cell::new(Some(f))) }); + } + + /// [`Runtime::invalidate_memos_by_prefix`](crate::Runtime::invalidate_memos_by_prefix) on + /// this window, from a handler or `poll`: e.g. a plugin host evicting the subtrees an + /// unloading library built. + pub fn invalidate_memos_by_prefix(&mut self, prefix: impl Into<String>) { + self.evict_memos.push(prefix.into()); + } + + /// Whether this runtime has an attached motion or tooling trace. + pub fn tracing(&self) -> bool { self.trace.is_some() } + + /// Work only a frame carries out that changes its pixels without a model change: a scroll + /// or a text flight. A `wake_after` only schedules. + pub(crate) fn frame_work(&self) -> bool { + !self.pick_reads.is_empty() || !self.scroll_to.is_empty() || !self.scroll_bottom.is_empty() || !self.scroll_pages.is_empty() || !self.scroll_offsets.is_empty() + || !self.keep_on_screen.is_empty() || !self.text_flights.is_empty() || !self.launches.is_empty() || self.select.is_some() + } + + /// An app marker on the next frame, e.g. `tx.trace_event(format_args!("lab:{step:?}"))`. + /// Formatting is skipped when tracing is off. Avoid eagerly constructing a `String`. + pub fn trace_event(&mut self, event: impl std::fmt::Display) { + if let Some(trace) = &mut self.trace { trace.events.push(event.to_string()); } + } + + /// A sample-and-hold scalar (`position`, `level`, or `phase`), e.g. `phase:recording`. + /// No allocation when tracing is off. Use a compositor's `Runtime::trace_channel` for + /// presented geometry that changes between commits. + pub fn trace_channel(&mut self, name: &'static str, kind: &'static str, value: f32) { + if let Some(trace) = &mut self.trace { trace.channels.push((name, kind, value)); } + } + + /// Wake the app's poll hook after an unscaled duration. Every deadline due by a frame + /// collapses into that frame's one poll, so asking on every poll never adds polls. + /// This schedules a frame, not a view commit; poll returns true if state changed. + /// For debounce, keep the latest due time in app state and reschedule the remaining + /// duration when an earlier wake arrives. No timer thread is created. + /// + /// `wake_after(Duration::ZERO)` from the poll asks for the next frame: a poll that steps + /// its own animation from the frame clock keeps a shown window or overlay drawing at the + /// display's rate this way, until it stops asking. That needs a display link pacing the + /// surface (macOS); hidden, covered, faded out or unpaced, a wake due sooner than a frame + /// waits about a frame (60 Hz), so a poll that keeps asking never spins the loop. + #[cfg_attr(feature = "frame-profile", track_caller)] + pub fn wake_after(&mut self, duration: std::time::Duration) { + #[cfg(feature = "frame-profile")] + crate::frame::live_log::waker(std::panic::Location::caller(), duration); + self.wakes.push(duration); + } + + /// The window's logical clock in seconds as this handler or poll runs: the `clock` `poll` + /// gets, and the frame's for a handler. Headless runs step it virtually, so a state + /// machine that stamps its timers with it (`rune::machine`) runs the same in a script. + /// 0 for a `Tx` no runtime made. + pub fn clock(&self) -> f64 { + self.clock + } + + /// Wake the app's poll hook once the clock reaches `due` (seconds on [`Tx::clock`]), as + /// [`Tx::wake_after`] does for the time left; a deadline already past wakes the next + /// frame. A timed state stores its deadline and asks for it here, and its poll checks + /// `clock >= due` to fire the timer as an event. + #[cfg_attr(feature = "frame-profile", track_caller)] + pub fn wake_at(&mut self, due: f64) { + #[cfg(feature = "frame-profile")] + crate::frame::live_log::waker(std::panic::Location::caller(), std::time::Duration::from_secs_f64((due - self.clock).max(0.0))); + self.wakes.push(std::time::Duration::from_secs_f64((due - self.clock).max(0.0))); + } + + /// Close the window after this handler, as the close button would (`App::on_close` runs). + pub fn close_window(&mut self) { + self.shell = self.shell.max(Some(Shell::Close)); + } + + /// Quit the app after this handler, whether or not it keeps running without a window. Every + /// open window's `App::on_quit` runs as it ends; no `on_close` does. + pub fn quit(&mut self) { + self.shell = self.shell.max(Some(Shell::Quit)); + } + + /// Quit the app as [`Tx::quit`] does, then start it again, with the same arguments, once + /// this process has exited, as Electron's `app.relaunch()` and `app.quit()` do: a menu's + /// Restart, or an update put in place. A system shutdown or logoff that ends the app first + /// doesn't start it again. + pub fn relaunch(&mut self) { + self.shell = Some(Shell::Relaunch); + } + + /// Minimize this window after this handler, as its minimize button would (winit's + /// `set_minimized` off macOS). Does nothing (logging in debug builds) where a window + /// can't minimize: an overlay, a panel or launcher, a borderless window, or one without a + /// minimize button. + /// A close or quit asked in the same change wins. + pub fn minimize(&mut self) { + self.minimize_order = Some(crate::app::window_request_order()); + } + + /// Maximize this window after this handler, or restore it when it is maximized, as its + /// maximize button would (macOS zooms). Does nothing for overlays and headless runs. + pub fn toggle_maximized(&mut self) { + self.toggle_maximized = true; + } + + /// Take this window full screen after this handler, or bring it back, as macOS's green + /// button and Electron's `setFullScreen` do: on Windows and Linux a borderless window over + /// its display, which hides a custom titlebar's caption buttons (`Cx::chrome_insets`). + /// Does nothing for overlays and headless runs. + pub fn toggle_full_screen(&mut self) { + self.toggle_full_screen = true; + } + + /// Deliver `ev` once this handler is done, as if it were typed: to the focused field, then + /// the key handlers, as the keyboard routes it. For a menu the app draws itself, whose Edit + /// items send Ctrl+C (⌘C) and the rest to the field that has focus, as AppKit's standard + /// Edit items do. Keys sent in one handler arrive in order. + pub fn send_key(&mut self, ev: crate::KeyEvent) { + self.keys.push(ev); + } + + /// Set this window's title after this handler, in its title bar and the Window menu. The + /// window starts with `AppSpec`'s title and keeps the last one set when it's closed and + /// opened again. Headless `--tree` output shows it as `"title"`. An overlay has no title. + pub fn set_title(&mut self, title: impl Into<String>) { + self.title = Some(title.into()); + } + + /// Have a screen reader say `text` after this handler, without moving focus: a reply that + /// finished, a request that arrived, an item that moved. `Polite` waits for the reader to + /// finish what it's saying; `Assertive` interrupts it (errors and requests that block + /// work). Each window keeps one announcement, a live region of its own that draws nothing; + /// the last call in a frame wins, and saying the same words again says them again. With no + /// assistive technology listening it costs one string. + pub fn announce(&mut self, text: impl Into<String>, how: crate::LiveRegion) { + if how != crate::LiveRegion::Off { self.announce = Some((text.into(), how)); } + } + + /// Open `url` in the system's default handler once this handler's frame is done: a browser + /// for `http:` and `https:`, the mail app for `mailto:`. Other schemes (`file:`, an app's + /// own) and malformed links are refused here with the reason and nothing opens. Headless + /// runs and tests open nothing; read the requests with `Runtime::take_url_requests`. + pub fn open_url(&mut self, url: &str) -> Result<(), crate::open_url::OpenUrlError> { + self.open_urls.push(crate::open_url::Link { url: crate::open_url::check(url)?, same_tab: false }); + Ok(()) + } + + /// `open_url`, but on web the link replaces this page instead of opening a tab: the app's + /// [`App::same_tab_router`](crate::App::same_tab_router) gets it first (a single-page app + /// routes it with `history.pushState`), else the browser loads it with `location.assign`. + /// On web a link without a scheme (`/notes/42`) is relative to the page. Native opens it as + /// `open_url` does, and headless runs record it with the others. + pub fn open_url_same_tab(&mut self, url: &str) -> Result<(), crate::open_url::OpenUrlError> { + self.open_urls.push(crate::open_url::Link { url: crate::open_url::check_same_tab(url)?, same_tab: true }); + Ok(()) + } + + /// Resize this window's content to `size` points, as an onboarding window changes height + /// per step. The top edge stays put and the window stays on its screen. The frame moves + /// on this change's spring (`Tx::motion`, else `tok::motion::DEFAULT`), so content laid + /// out against the window's edges follows it frame by frame; `Tx::instant` or reduced + /// motion jumps. On macOS it animates; Windows and Linux resize at once, and Wayland + /// can't keep the window on screen. Headless runs resize the viewport on the virtual + /// clock, so `--tree` and scripts see it; their frames keep the launch canvas size. + /// Overlays ignore it: use `OverlayHandle::resize`. + pub fn resize_window(&mut self, size: (f32, f32)) { + self.frame_request(crate::window::frame::FrameRequest { size: Some(size), animate: true, ..Default::default() }); + } + + /// [`Tx::resize_window`] without the animation. + pub fn resize_window_instant(&mut self, size: (f32, f32)) { + self.frame_request(crate::window::frame::FrameRequest { size: Some(size), ..Default::default() }); + } + + /// Centre the window on its screen as AppKit's `center` does: centred across, slightly + /// above the middle. With [`Tx::resize_window`] in the same change it centres the new + /// size, on the same spring; alone it jumps, or retargets a resize already moving. + /// Wayland and headless runs ignore it. + pub fn center_window(&mut self) { + self.frame_request(crate::window::frame::FrameRequest { center: true, ..Default::default() }); + } + + /// Drop keyboard focus, as a click on empty space does: after this handler, nothing is + /// focused, the focused field's `TextEdit::focused` turns false (through its `on_edit` + /// accessor) and keys go to the window's `on_key` again. A field focused only by setting + /// `focused` in the model without `on_edit` takes focus back on the next frame unless the + /// model clears it too. Does nothing when nothing has focus. + pub fn blur(&mut self) { + self.blur = true; + } + + /// Focus the element keyed `key` once this handler's change is on screen, as a web page's + /// `element.focus()`: a menu's trigger as the menu closes, say. The first shown, focusable + /// element with that key takes it (or its first focusable child), drawing its focus ring when + /// `ring` (`:focus-visible`). A text field focused through its model (`TextEdit::focused`) + /// in the same change wins over it. Nothing happens when no such element shows. + pub fn focus(&mut self, key: impl Into<String>, ring: bool) { + self.focus_to = Some((key.into(), ring, FocusAsk::Focus)); + } + + /// [`Tx::focus`] for an element that may not be shown yet: content still loading, a card that + /// comes in with the next build, a window that isn't drawing. The request waits, through any + /// number of commits, until an element with the key shows, and focuses it then, however long + /// its loading or motion takes, whatever focus did meanwhile (a closing palette leaving it on + /// the prompt). It's dropped when the user presses a key or a pointer button, or when another + /// focus is asked for. + pub fn focus_when_shown(&mut self, key: impl Into<String>, ring: bool) { + self.focus_to = Some((key.into(), ring, FocusAsk::WhenShown)); + } + + /// [`Tx::focus`] for focus a closing menu or popover hands back to its trigger, as a web + /// menu's `onCloseAutoFocus` does after the change that closed it. A modal that opens in the + /// same change (a dialog a menu's pick opens) keeps focus, and as it closes hands it back to + /// where focus was before that change, as a web dialog that opened from a menu item records + /// that item: when it's gone, nothing has focus. Focus this change already asked for (a + /// pick that focused something with [`Tx::focus`]) stays asked, as a web menu's restore + /// finds focus moved outside the menu and leaves it. + pub fn return_focus(&mut self, key: impl Into<String>, ring: bool) { + if self.focus_to.as_ref().is_none_or(|(.., ask)| *ask == FocusAsk::Return) { + self.focus_to = Some((key.into(), ring, FocusAsk::Return)); + } + } + + /// Whether an assistive client (a screen reader, Voice Access, an automation tool) is + /// reading this window's accessibility tree: the tree is built only then. Work done only for + /// one, such as deciding what [`Tx::announce`] says, can wait for it and cost nothing without. + /// In a browser it's always true: a page can't tell whether a screen reader reads it, and + /// its mirror and live regions are always there. + pub fn assistive_technology(&self) -> bool { + self.assistive + } + + /// Whether keyboard focus was showing its ring (`:focus-visible`) as this event arrived: + /// the keyboard, not the pointer, has been driving. A menu that opens with it returns focus + /// to its trigger with the ring. + pub fn focus_visible(&self) -> bool { + self.focus_visible + } + + /// Whether a key brought this change: a key handler, or a control that Return or Space + /// pressed. A menu that opens from it is a keyboard open (Kobalte's `keyboard` gesture), + /// which lights its first row and hands focus back to its trigger with the ring, whatever + /// put focus on the trigger before. + pub fn by_keys(&self) -> bool { + self.by_keys + } + + /// The [`El::selectable`] text selection as this event arrived: the texts it covers with + /// their selected ranges, and the text as copying takes it. `None` when nothing is + /// selected (a single click leaves only a caret-sized selection, which reads as `None`). + /// What this handler asks with [`Tx::select_text`] and kin shows from the next event on. + pub fn text_selection(&self) -> Option<&crate::TextSelection> { + self.selection.as_deref() + } + + /// Select bytes `range` of the [`El::selectable`] text named `key` (a key, path or key + /// path, as [`Cx::layout`](crate::Cx::layout) takes), as if dragged across, after this + /// handler's commit: an element the same change builds can be selected, and an unbuilt + /// [`El::virtual_rows`] or [`El::virtualize`] row is built and pinned without scrolling. + /// The range is clamped to the text and its character boundaries; Cmd+C then copies it and Cmd+A selects all of its text or group. + /// Nothing happens when `key` (the element's final key; a [`memo`](crate::memo)'s id replaces one set inside) names no selectable text. + pub fn select_text(&mut self, key: impl Into<String>, range: std::ops::Range<usize>) { + self.select = Some(SelectRequest::Range(key.into(), range)); + self.select_from_change = false; + } + + /// Select all of the [`El::selectable`] text named `key`, or, for any other element, every + /// selectable text inside it that shares the first one's [`El::selection_group`], as Cmd+A + /// does (including from the first to the last row of a virtual list): `select_all_text("note")` + /// on a selectable `Markdown` keyed `note` selects the whole document. After this handler's commit, as [`Tx::select_text`], with its `key` rules. + pub fn select_all_text(&mut self, key: impl Into<String>) { + self.select = Some(SelectRequest::All(key.into())); + self.select_from_change = false; + } + + /// Clear the [`El::selectable`] text selection, as a click elsewhere does. + pub fn clear_text_selection(&mut self) { + self.select = Some(SelectRequest::Clear); + self.select_from_change = false; + } + + /// Switch this window between linear and sRGB (gamma-space) blending from the next frame, + /// as if it had launched with `App::srgb_blend(enabled)`: a canvas can follow the document + /// it shows. The window reconfigures its surface and rebuilds its renderer's pipelines once, + /// on the frame that switches; asking for the mode it already has costs nothing. A + /// `Compositor` sees the new `Frame::format` and `Frame::srgb_blend` on that frame. + /// Windows, overlays, the web canvas and headless runs all follow. + pub fn set_srgb_blend(&mut self, enabled: bool) { + self.srgb_blend = Some(enabled); + } + + /// Record this window's presented frames into `rewind` from the next frame, or stop with + /// `None` (see [`crate::rewind`]). Nothing records until a handler asks. + pub fn record_rewind(&mut self, rewind: Option<&crate::rewind::Rewind>) { + self.rewind = Some(rewind.cloned()); + } + + /// Rasterise and place this window's glyphs in `mode` from the next frame, as if it had + /// launched with `App::font_smoothing(mode)`; glyphs are rasterised again for the new mode + /// (each mode's stay cached). Blending is separate ([`Self::set_srgb_blend`]). + pub fn set_font_smoothing(&mut self, mode: crate::text::FontSmoothing) { + self.font_smoothing = Some(mode); + } + + /// Put `sans` and `mono` (CSS family lists, as `App::families` takes them) behind the + /// `Family::Sans` and `Family::Mono` slots of every window and overlay, from the next + /// frame, and of those opened later: a font picker. Each window drops what it shaped and measured in the old families + /// (memoized subtrees included), lays out again and draws one frame. A family that isn't + /// registered or installed falls back as it would at launch. Asking for the families the + /// slots already hold costs nothing. [`rune::text::measure`](crate::text::measure) follows + /// too, and caches of measured sizes can key on [`rune::text::font_epoch`](crate::text::font_epoch). Tests that switch families + /// on parallel threads isolate `measure` with [`rune::text::with_families`](crate::text::with_families). + pub fn set_font_families(&mut self, sans: impl Into<String>, mono: impl Into<String>) { + self.font_families = Some((sans.into(), mono.into())); + } + + /// Shapes and breaks the text of `view` into the window's layout cache in its next idle turn, + /// laid out as the window would lay it out (at its own size, or at `size` in points), without + /// mounting it: nothing draws, hits, animates or is announced, and no handler runs. A view shown + /// later with the same texts at the same widths finds them laid out. For the most it from the + /// window's own root, as the next frame will lay it out (the session under a resting pointer + /// shown where the open one is). Prepared layouts no view holds are kept to about 1 MiB by the + /// cache's own count, oldest out first, and all go at the window's next rest. One request is + /// held, the latest, for the window whose state `view` reads; it never runs on a turn with + /// input waiting, and an idle window wakes for it no more once it ran. + pub fn prepare_text<S: 'static>(&mut self, view: fn(&S, &mut crate::Cx<S>) -> crate::El, size: Option<(f32, f32)>) { + PREPARE.with_borrow_mut(|a| *a = Some((Box::new(view), size))); + } + + /// Takes `prepare_text`'s request if it is for a window of state `S`. + pub(crate) fn take_prepared<S: 'static>() -> Option<(fn(&S, &mut crate::Cx<S>) -> crate::El, Option<(f32, f32)>)> { + if !Self::prepare_owed::<S>() { return None; } + let (view, size) = PREPARE.with_borrow_mut(Option::take)?; + Some((*view.downcast::<fn(&S, &mut crate::Cx<S>) -> crate::El>().ok()?, size)) + } + + /// Whether `prepare_text` holds a request for a window of state `S`. + pub(crate) fn prepare_owed<S: 'static>() -> bool { + PREPARE.with_borrow(|a| a.as_ref().is_some_and(|(view, _)| view.is::<fn(&S, &mut crate::Cx<S>) -> crate::El>())) + } + + fn frame_request(&mut self, request: crate::window::frame::FrameRequest) { + self.window_frame = Some(self.window_frame.unwrap_or_default().merge(request)); + } + + /// This handler changed only [`Live`](crate::Live) values (a canvas camera's + /// `live_offset` and `live_scale`), or nothing else the view reads, so its event doesn't + /// re-run the view or lay it out. The frame still draws the new live values, hit tests + /// against where they put elements, and reports [`El::on_drawn_layout`]. Whatever else the + /// handler asked of its `Tx` (a scroll, a copy, `wake_after`) still happens. It works in + /// pointer, gesture, key, press and hover handlers and in [`El::on_layout_tx`] and + /// [`El::on_drawn_layout_tx`]. + /// Editing, paste and file-drop actions still commit Rune's own changes. A handler that + /// declines its event (returns false) takes it back, and an event several handlers take is + /// live-only only if each says so. It's the handler form of + /// [`Runtime::update_if`](crate::Runtime::update_if) returning false. + /// + /// ```ignore + /// .on_magnify(|s: &mut Canvas, e, tx| { + /// s.camera.zoom_about(e.x, e.y, 1.0 + e.delta); // sets Live values only + /// tx.live_only(); + /// true + /// }) + /// ``` + /// + /// Changing state the view reads and calling this leaves the screen stale until the next + /// commit. Debug builds look for that: a live-only event a quarter second or more after + /// the last commit still re-runs the view, and if the elements, layout, text or colours + /// it builds differ from what's on screen, Rune prints the handler that said `live_only`. + /// This is a heuristic, not a state-mutation check: a view that reads a clock or other + /// external state can also differ. Use [`Runtime::check_live_only`](crate::Runtime::check_live_only) + /// to turn it off for such a view. It does no checking in release builds. + pub fn live_only(&mut self) { + self.live_only = true; + } + /// A handler that declined its event (`taken` false) takes back its `live_only`. + pub(crate) fn took(taken: bool, tx: &mut Tx) -> bool { + if !taken { tx.live_only = false; } + taken + } + /// Apply this change with no animation (direct manipulation): layout snaps, and any + /// newly mounted or removed elements enter or unmount at once without playing their + /// [`El::transition`] fade. Typing in a text field, focusing an input on pointer-down + /// and drag moves set `instant` automatically; `AppSpec::on_key`, `El::on_key`, `on_submit` + /// and `on_press` commits animate by default unless the handler calls `instant()` or + /// [`Self::settle`]. + /// Changed non-streaming row heights and scroll requests in this commit also land + /// immediately, including requests made with `scroll_to` or `scroll_to_bottom`. + /// Motion an earlier commit started toward a place or value this commit leaves alone keeps + /// running too, so a quick key during a layout spring doesn't land it mid-flight. + /// An already-running scroll glide is not settled unless this commit replaces it; + /// use [`Tx::settle`] to land running tracks. + pub fn instant(&mut self) { + self.commit = self.commit.instant(); + } + /// Animate this change even where the runtime would apply it at once, as it does a drag's + /// moves, or a commit no input in this window caused (`El::transition`: those mount and + /// unmount at once otherwise): the rows a dragged row passes step aside on their springs, while the dragged row + /// follows the pointer exactly with `El::offset_motion(Anim::INSTANT)`. + /// This clears this handler's snap; another handler's `instant()` in the same frame still + /// wins. A `settle()` in the same change keeps its landing of running tracks. It neither + /// requests a commit after `live_only()`. `motion()` still chooses the layout spring. The + /// last call to `instant()` or `animated()` in this handler wins. + pub fn animated(&mut self) { + self.commit = self.commit.animated(); + self.asked_motion = true; + } + /// Animate this change's layout with `spring` instead of each element's own. Scroll + /// requests keep the spring they name; see [`Self::motion_curve`]. + pub fn motion(&mut self, spring: Spring) { + self.motion = Some(MotionSource::Spring(spring)); + } + /// Animate this change's layout on `anim` instead of each element's own spring: a spring, + /// or a fixed-duration eased tween to compare against one + /// (`tx.motion_curve(Curve::tween(0.35, Easing::cubic(0.16, 1.0, 0.3, 1.0)))`). What + /// moves with the layout but only takes a spring (matched flights) uses a zero-bounce + /// spring of the curve's duration. Scroll requests don't follow it: each glides on the + /// spring it names, [`Self::scroll_to_with`]'s or `tok::motion::GLIDE`. The last `motion` or + /// `motion_curve` wins. + pub fn motion_curve(&mut self, anim: impl Into<Anim>) { + self.motion = Some(MotionSource::curve(anim.into())); + } + /// Rows pinned to a stick-to-bottom viewport's bottom ride its edge through this change: + /// room the edge frees (a question dock folding back into a composer under a chat) carries + /// the rows down on the change's curve, frame by frame, instead of waiting under the last + /// row as slack for a new row to grow into, as a send's room does. + pub fn follow_edge(&mut self) { + self.follow_edge = true; + } + /// Apply this change with no animation and land every running track: growth, reveals and + /// follow-the-end (opening or returning to a session, guarantee 8). + pub fn settle(&mut self) { + self.commit = Commit::Settle; + } + /// Animate this change's colours with `spring` (a theme change uses `tok::motion::CALM`). + pub fn color_motion(&mut self, spring: Spring) { + self.color_motion = Some(spring); + } +} + +thread_local! { + /// `Tx::prepare_text`'s latest request on this thread: the view, boxed, and its size in points + /// if not the window's. + static PREPARE: std::cell::RefCell<Option<(Box<dyn std::any::Any>, Option<(f32, f32)>)>> = const { std::cell::RefCell::new(None) }; +} diff --git a/app/vendor/rune/crates/rune/src/el/tx/keys.rs b/app/vendor/rune/crates/rune/src/el/tx/keys.rs new file mode 100644 index 0000000..27d9cc4 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/el/tx/keys.rs @@ -0,0 +1,63 @@ +//! `Tx`'s reads about the key a key handler is seeing: repeat, physical key, unmodified +//! character, modifiers and the focused element. + +use crate::Tx; + +impl Tx { + /// Whether the key a key handler is seeing is the OS auto-repeat of a held key: true for + /// each repeat, false for the first press and outside key handlers. One-shot actions + /// (start recording on Enter, say) can return early on a repeat; arrows and Tab usually + /// want every repeat. + pub fn key_repeat(&self) -> bool { self.key_repeat } + + /// In a key handler, the physical key behind the logical key it's seeing: where the key + /// sits, whatever the keyboard layout and Shift make it type. `KeyEvent` carries the + /// character, which moves between layouts once Shift is held (`⌘⇧7` arrives as + /// `Key::Command('&')` on a US layout and `Key::Command('/')` on a German one), so a shifted + /// shortcut matches this instead: `tx.physical_key() == Some(PhysicalKeyCode::Digit7)`. + /// `None` for a key with no physical origin (`Runtime::key`, a script's `"key"` without a + /// `"code"`) and outside key handlers. + pub fn physical_key(&self) -> Option<crate::PhysicalKeyCode> { self.physical_key } + + /// In a key handler, the character the key types under the current keyboard layout with + /// no modifiers held: `'a'` for ⌥A (which arrives as `Key::Text("å")` on a US Mac layout) + /// and ⇧A, and `'a'` for AZERTY's A key, which sits where QWERTY's Q does. A binding by + /// letter, as macOS's `DefaultKeyBinding.dict` binds ⌥-letters, matches this rather than + /// [`Tx::physical_key`], which names where the key sits (`KeyQ` there). `None` off + /// macOS, Windows and Linux, for a key that types no single character (arrows, Return), + /// for a key with no physical origin (`Runtime::key`, a script's `"key"` without a + /// `"code"`) and outside key handlers. + pub fn key_base(&self) -> Option<char> { self.key_base } + + /// The modifier keys held as this handler runs, so a click can tell Shift-click (extend a + /// list's selection) and Cmd-click (toggle a row) from a plain one. A key handler reads + /// the key's own [`KeyEvent::mods`](crate::KeyEvent) instead. + pub fn mods(&self) -> crate::Mods { self.mods } + + /// When the input this handler runs for arrived, to measure input-to-photon latency + /// against [`FrameEncoded`](crate::FrameEncoded): on macOS the timestamp of the `NSEvent` + /// AppKit dispatched it in, elsewhere when the window took it from winit. Input that piles + /// up between frames keeps each event's own time. `None` in handlers no input caused + /// (timers, polls, updates, layout callbacks) and for input fed to a `Runtime` directly + /// (`Runtime::key` and kin, headless scripts). + pub fn input_time(&self) -> Option<crate::time::Instant> { self.input_time } + + /// In `poll`: whether the user's input (a key, a press, the pointer, the wheel, text) is + /// waiting for this frame's handlers, which run after `poll`. Work that can wait a frame (a + /// background start, a cache warm-up) waits, so the input's frame comes without it. False + /// everywhere else. + pub fn input_waiting(&self) -> bool { self.input_waiting } + + /// The key of the element that had focus when the event arrived, `None` when nothing had: + /// in a key handler, when the key arrived; in a press handler, after the press moved focus (a + /// menu opened there remembers it to hand focus back). Timers, polls and updates read the focus + /// as they run. An unkeyed element reads as `#n`, its + /// index among its siblings, and a focused [`Link`](crate::Link) as its id. A window's `on_key` hears + /// a key either before anything else (nothing focused) or after the focused control passed + /// it on, so `tx.focused().is_none()` picks out the first case: plain arrows can drive the + /// window (a settings pane) only while no control has focus, as in System Settings. The + /// whole order is under "Key routing" in the rune README. + pub fn focused(&self) -> Option<&str> { + self.focused.as_deref() + } +} diff --git a/app/vendor/rune/crates/rune/src/el/tx/press.rs b/app/vendor/rune/crates/rune/src/el/tx/press.rs new file mode 100644 index 0000000..d1d29d6 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/el/tx/press.rs @@ -0,0 +1,31 @@ +//! `Tx`'s held-press repeat: a drag handler hears a press it holds still again, as AppKit +//! repeats a held scroll bar track or stepper. + +use std::time::Duration; + +use crate::Tx; + +impl Tx { + /// Whether this `on_press` came from a touch tap. A mouse click, keyboard + /// activation or accessibility action returns false, including on touch-capable hosts. + pub fn touch_tap(&self) -> bool { self.touch_tap } + + /// From a drag handler: while this press stays held, send the handler the pointer again as + /// a [`Phase::Move`](crate::Phase::Move) after `delay`, moved or not. [`Tx::drag_repeat`] + /// tells that move from the hand's. Ask again from the repeat, with the repeat interval, to + /// keep going; releasing or cancelling the press ends it. + /// + /// ```ignore + /// .on_drag_any(|d, tx| { + /// if d.phase == Phase::Down || tx.drag_repeat() { + /// tx.scroll_page("list", 1); + /// tx.drag_repeat_after(Duration::from_millis(if tx.drag_repeat() { 60 } else { 300 })); + /// } + /// }) + /// ``` + pub fn drag_repeat_after(&mut self, delay: Duration) { self.drag_repeat_after = Some(delay); } + + /// Whether the drag handler is hearing the repeat it asked for with + /// [`Tx::drag_repeat_after`]; false for the hand's moves and outside drag handlers. + pub fn drag_repeat(&self) -> bool { self.drag_repeat } +} diff --git a/app/vendor/rune/crates/rune/src/el/tx/scroll.rs b/app/vendor/rune/crates/rune/src/el/tx/scroll.rs new file mode 100644 index 0000000..65f4587 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/el/tx/scroll.rs @@ -0,0 +1,175 @@ +//! `Tx`'s scroll requests: revealing a row, moving a viewport to its end, a page or an +//! offset, and holding an element where it shows. +//! +//! None of them follows the change's motion ([`Tx::motion`], [`Tx::motion_curve`]): a glide +//! runs on `tok::motion::GLIDE`, or on the spring [`Tx::scroll_to_with`] takes, and every other +//! request moves at once. + +#[cfg(doc)] +use crate::El; +use crate::Tx; + +impl Tx { + /// Let newly inserted and resizing rows at the visible end of this virtual growth stack + /// grow through a linear feather on their usual springs. For a live arrival, not a page + /// load. Rows that trade places carry their contents with them. The selector names the + /// stack, not the scroll viewport. This neither scrolls to the end nor animates other + /// layout or chrome. A reader scrolled away, a resizing viewport, reduced motion, the + /// first paint and an explicit `instant()` or `settle()` still land. + pub fn grow_visible_tail(&mut self, stack: impl Into<String>) { + self.request_live_growth(stack.into(), false); + } + + /// Like [`Self::grow_visible_tail`], but a row crossing a neighbour also carries its + /// changing paint and child exits. A resizing row carries its inset, and a stationary + /// neighbour can round its joined corners. This applies only to this live commit. + pub fn grow_visible_tail_with_ink(&mut self, stack: impl Into<String>) { + self.request_live_growth(stack.into(), true); + } + + pub(crate) fn request_live_growth(&mut self, stack: String, ink: bool) { + if let Some((_, carry)) = self.live_growth.iter_mut().find(|(key, _)| *key == stack) { + *carry |= ink; + } else { + self.live_growth.push((stack, ink)); + } + } + + /// A newly delivered `row` in `stack` takes room from a panel immediately below its + /// viewport. If the panel gives the viewport exactly the height it loses, move that + /// shared edge on the incoming row's growth, not a second spring. Otherwise the usual + /// `grow_visible_tail` rules apply. `panel` names its occupied space, excluding overlaps. + pub fn grow_visible_tail_from(&mut self, stack: impl Into<String>, row: impl Into<String>, panel: impl Into<String>) { + let stack = stack.into(); + self.grow_visible_tail(stack.clone()); + self.tail_rooms.push((stack, row.into(), panel.into())); + } + + /// Reveal a keyed row, including a currently unrealized virtual row. It scrolls the nearest + /// vertical viewport around the row and, through [`El::scroll_x`] or [`El::scroll_xy`], the + /// nearest horizontal one, each just far enough. The vertical reveal follows the presented + /// row while layout or growth moves it; wheel input, a fling or another scroll request wins. + /// + /// `key` names an element as [`Cx::layout`](crate::Cx::layout) does, here and in the other + /// scroll requests: a key (the first element with it), a full path, or a key path such as + /// `"inspector/label"` whose leading keys are the element's nearest keyed ancestors, which + /// tells apart an app's `label` from a component's. + pub fn scroll_into_view(&mut self, key: impl Into<String>) { + self.scroll_to.push(crate::runtime::ScrollReveal::into_view(None, key.into())); + } + /// [`Tx::scroll_into_view`] for row `key` inside the element keyed `scope` only, so lists + /// that key their rows alike (a file tree and a diff, both by path) don't reveal each + /// other's rows. + pub fn scroll_into_view_in(&mut self, scope: impl Into<String>, key: impl Into<String>) { + self.scroll_to.push(crate::runtime::ScrollReveal::into_view(Some(scope.into()), key.into())); + } + /// Reveal and vertically centre a keyed element, virtual row or [`crate::TextHighlight`], + /// gliding on the spring [`Tx::scroll_to`] uses (a jump under [`Tx::instant`], reduced + /// motion or a settled frame). `"row/mark"` mounts virtual row `row` first and centres + /// `mark` inside it. + pub fn scroll_center(&mut self, key: impl Into<String>) { + self.scroll_to.push(crate::runtime::ScrollReveal::center(None, key.into(), true)); + } + /// [`Tx::scroll_center`] inside the element keyed `scope` only. + pub fn scroll_center_in(&mut self, scope: impl Into<String>, key: impl Into<String>) { + self.scroll_to.push(crate::runtime::ScrollReveal::center(Some(scope.into()), key.into(), true)); + } + /// [`Tx::scroll_center_in`] without the glide. + pub fn scroll_center_in_instant(&mut self, scope: impl Into<String>, key: impl Into<String>) { + self.scroll_to.push(crate::runtime::ScrollReveal::center(Some(scope.into()), key.into(), false)); + } + /// Glide the scroll viewport keyed `key` (or the one containing it) to its bottom, as a + /// "jump to latest" button does. A `stick_bottom` viewport follows the end again once it + /// lands. Long distances cut to two viewports from the end first; reduced motion jumps. + pub fn scroll_to_bottom(&mut self, key: impl Into<String>) { + self.scroll_bottom.push((key.into(), true)); + } + /// [`Tx::scroll_to_bottom`] without the glide. + pub fn scroll_to_bottom_instant(&mut self, key: impl Into<String>) { + self.scroll_bottom.push((key.into(), false)); + } + /// Page the scroll viewport keyed `key` (or the one containing it) by `pages` pages, down + /// for positive, as Page Up and Page Down do: a page is 90% of its height, the move is + /// instant and clamped, and a `stick_bottom` viewport that lands on its end follows it + /// again. An app routes the page keys itself with it, e.g. from a composer's + /// `on_input_key` to the message list. + pub fn scroll_page(&mut self, key: impl Into<String>, pages: i32) { + self.scroll_pages.push((key.into(), pages)); + } + /// Move the horizontal scroll viewport keyed `key` (or the nearest one containing it) so it + /// shows its content from `x` points in, clamped to its ends: 0 is the start, as a carousel's + /// "back to the first" does. Instant; any momentum stops. See [`El::scroll_x`]. + pub fn scroll_to_x(&mut self, key: impl Into<String>, x: f32) { + self.scroll_offsets.push(crate::runtime::ScrollRequest { key: key.into(), x: Some(x), y: None, glide: None, anchor: crate::runtime::ScrollAnchor::None }); + } + /// Move the vertical scroll viewport keyed `key` (or the nearest one containing it) so it + /// shows its content from `y` points down, clamped to its ends. Instant; any momentum or + /// glide stops, and a `stick_bottom` viewport that lands on its end follows it again. + pub fn scroll_to_y(&mut self, key: impl Into<String>, y: f32) { + self.scroll_offsets.push(crate::runtime::ScrollRequest { key: key.into(), x: None, y: Some(y), glide: None, anchor: crate::runtime::ScrollAnchor::None }); + } + /// Glide the scroll viewport keyed `key` (or the nearest one containing it) to show its + /// content from (`x`, `y`) points in, on the spring [`Tx::scroll_to_bottom`] uses, as a + /// "focus" or "back to the start" button does. Each offset is clamped to the content, + /// rechecked as the glide runs (virtual rows measure as they mount); axes the viewport + /// doesn't scroll are ignored, so a vertical list takes `y` alone. The wheel, a fling or + /// another request takes over mid-glide, a request keeping its speed. Reduced motion, and a + /// settled frame, jump. [`Tx::scroll_to_with`] picks the spring. + pub fn scroll_to(&mut self, key: impl Into<String>, x: f32, y: f32) { + self.scroll_offsets.push(crate::runtime::ScrollRequest { key: key.into(), x: Some(x), y: Some(y), glide: Some(crate::tok::motion::GLIDE), anchor: crate::runtime::ScrollAnchor::None }); + } + /// [`Tx::scroll_to`] on `spring` instead of the default glide. A request that arrives + /// mid-glide keeps the glide's speed, so a selection moved by key repeat, each press asking + /// for the next row, scrolls in one continuous motion rather than in steps. A quicker spring + /// covers more of the way on the first frame: + /// + /// ``` + /// # let mut tx = rune::Tx::default(); + /// # let row_top = 640.0; + /// // ↓ moved the selection: keep its row in view, on a quicker spring than the default. + /// tx.scroll_to_with("board", 0.0, row_top, rune::Spring::new(0.18, 0.0)); + /// ``` + pub fn scroll_to_with(&mut self, key: impl Into<String>, x: f32, y: f32, spring: crate::Spring) { + self.scroll_offsets.push(crate::runtime::ScrollRequest { key: key.into(), x: Some(x), y: Some(y), glide: Some(spring), anchor: crate::runtime::ScrollAnchor::None }); + } + /// [`Tx::scroll_to`] without the glide. An app stepping its own glide calls it each frame: + /// hover under a still pointer then holds while the content moves and resolves once the + /// frame after the last step, as it does for a glide. + pub fn scroll_to_instant(&mut self, key: impl Into<String>, x: f32, y: f32) { + self.scroll_offsets.push(crate::runtime::ScrollRequest { key: key.into(), x: Some(x), y: Some(y), glide: None, anchor: crate::runtime::ScrollAnchor::None }); + } + /// Move the vertical scroll viewport around the element or [`crate::TextHighlight`] keyed + /// `key` so its top sits `at` points below the viewport's top, clamped to the content's ends: + /// a page that opens on a heading lands it just under its bar. It's placed from the layout of the commit this + /// handler causes, so the frame that first draws a new page draws it there, and unlike + /// [`Tx::scroll_into_view`] where it lands doesn't depend on where the view was or what was + /// stuck over it. Instant; any momentum or glide stops. A virtual row that isn't mounted + /// lands too: the jump goes where its list's estimates put it, which mounts it, and is placed + /// again from its layout before the frame draws, the rows it mounts there showing at once. + /// `"row/mark"` lands element or highlight `mark` anywhere inside the element keyed `row`, + /// including a virtual row that isn't mounted yet: one request, one jump. + pub fn scroll_key_to(&mut self, key: impl Into<String>, at: f32) { + self.scroll_offsets.push(crate::runtime::ScrollRequest { key: key.into(), x: None, y: Some(at), glide: None, anchor: crate::runtime::ScrollAnchor::Top }); + } + /// Move the vertical scroll viewport around the element or [`crate::TextHighlight`] keyed + /// `key` so its vertical midpoint sits `center_y` points below the viewport's top, snapped to + /// whole device pixels (`round(offset * scale) / scale`) as Chromium's `scrollTo({ top })` + /// does. For a [`crate::TextHighlight`], the midpoint is taken from the highlight's inline + /// font-metric box (`[baseline - ascent, baseline + descent]`, matching Blink's + /// `Range::getBoundingClientRect()`). Instant; any momentum or glide stops. + pub fn scroll_key_center_at(&mut self, key: impl Into<String>, center_y: f32) { + self.scroll_offsets.push(crate::runtime::ScrollRequest { key: key.into(), x: None, y: Some(center_y), glide: None, anchor: crate::runtime::ScrollAnchor::CenterSnapped }); + } + /// Keep the element keyed `key` (or at that path) where it shows on screen across the + /// commit this handler causes, by moving the nearest vertical scroll viewport around it. A + /// stuck [`El::sticky_top`] header that collapses its section stays under the pointer + /// instead of jumping up with the content, and one that expands stays put as its rows open + /// below it. Its top edge is what holds, measured where the last frame drew it, stuck shift + /// included; the offset is clamped to the content, and a `stick_bottom` viewport that lands + /// on its end follows it again. Scroll compensation follows the drawn element while + /// layout and growth springs run; other rows keep animating. A scroll asked for in the + /// same handler, or subsequent wheel input, wins. + pub fn keep_on_screen(&mut self, key: impl Into<String>) { + self.keep_on_screen.push(key.into()); + } +} diff --git a/app/vendor/rune/crates/rune/src/el/tx/tests.rs b/app/vendor/rune/crates/rune/src/el/tx/tests.rs new file mode 100644 index 0000000..682bb84 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/el/tx/tests.rs @@ -0,0 +1,265 @@ +//! The commit intent walk: every order of the `Tx` calls that set motion intent, checked after +//! every call against `origin/dev`'s two flags and two motion slots, transcribed below. + +use super::*; +use rune_motion::{Curve, Easing}; + +use crate::tok::motion; + +/// The spring of the node being laid out, for reads that fall back to it. +const NODE: Spring = Spring::new(0.4, 0.1); +/// The spring of a matched flight, for reads that fall back to it. +const MATCHED: Spring = Spring::new(0.2, 0.0); + +fn tween() -> Anim { + Anim { delay: 0.05, ..Anim::new(Curve::tween(0.35, Easing::cubic(0.16, 1.0, 0.3, 1.0))) } +} + +fn glide() -> Anim { + Anim::new(Curve::linear(0.2)) +} + +/// `origin/dev`'s `Tx` for one handler, transcribed: the two flags any handler may set, the two +/// motion slots, and the `live_only` bit, with dev's own setters and merge. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +struct Dev { + instant: bool, + settle: bool, + motion: Option<Spring>, + motion_curve: Option<Anim>, + live_only: bool, +} + +impl Dev { + fn instant(&mut self) { + self.instant = true; + } + + fn animated(&mut self) { + self.instant = false; + } + + fn settle(&mut self) { + self.instant = true; + self.settle = true; + } + + fn motion(&mut self, spring: Spring) { + self.motion = Some(spring); + self.motion_curve = None; + } + + fn motion_curve(&mut self, anim: Anim) { + self.motion = Some(match anim.curve { + Curve::Spring(s) => s, + c => Spring::new(c.logical_duration().max(0.01), 0.0), + }); + self.motion_curve = Some(anim); + } + + fn live_only(&mut self) { + self.live_only = true; + } + + /// `merge(&mut Tx, Tx)`'s three lines for these fields: either handler's snap or settle is + /// taken, and the later handler's motion only when it set one. + fn merge(&mut self, one: &Dev) { + self.instant |= one.instant; + self.settle |= one.settle; + if one.motion.is_some() { + self.motion = one.motion; + self.motion_curve = one.motion_curve; + } + } +} + +/// The reads every motion-intent site makes, and nothing else. +#[derive(Debug, PartialEq)] +struct Seen { + /// `apply`: this change's own layout applies at once. + snaps: bool, + /// `apply`: this change lands every running track. + lands: bool, + /// `apply`: a growth row's duration scale. + scale: f32, + /// `apply`: the node's layout springs. + layout: (Spring, Anim), + /// `flights`: the spring a matched flight takes. + flight: Spring, + /// `latch_requests`: the window frame's spring, `None` on an instant change. + window: Option<Spring>, +} + +/// What the runtime makes of a change, read the way the sites read it. +fn seen(tx: &Tx) -> Seen { + Seen { + snaps: tx.commit.snaps(), + lands: tx.commit.lands(), + scale: tx.motion.map_or(0.0, |m| m.spring().duration * 1.15), + layout: tx.motion.map_or((NODE, NODE.into()), |m| (m.spring(), m.anim())), + flight: tx.motion.map(MotionSource::spring).or(Some(MATCHED)).unwrap_or(motion::REFLOW), + window: (!tx.commit.snaps()).then(|| tx.motion.map_or(motion::DEFAULT, MotionSource::spring)), + } +} + +/// The same reads, from dev's fields. +fn seen_dev(dev: &Dev) -> Seen { + let spring_l = dev.motion.unwrap_or(NODE); + let anim_l: Anim = dev.motion_curve.unwrap_or_else(|| spring_l.into()); + Seen { + snaps: dev.instant, + lands: dev.settle, + scale: dev.motion.map_or(0.0, |m| m.duration * 1.15), + layout: (spring_l, anim_l), + flight: dev.motion.or(Some(MATCHED)).unwrap_or(motion::REFLOW), + window: (!dev.instant).then(|| dev.motion.unwrap_or(motion::DEFAULT)), + } +} + +/// One call a handler can make that sets commit intent. +#[derive(Clone, Copy, Debug, PartialEq)] +enum Op { + Instant, + Animated, + Settle, + Motion, + Curve, + Tween, + LiveOnly, +} + +const OPS: [Op; 7] = [Op::Instant, Op::Animated, Op::Settle, Op::Motion, Op::Curve, Op::Tween, Op::LiveOnly]; + +impl Op { + fn call(self, tx: &mut Tx) { + match self { + Op::Instant => tx.instant(), + Op::Animated => tx.animated(), + Op::Settle => tx.settle(), + Op::Motion => tx.motion(MATCHED), + Op::Curve => tx.motion_curve(glide()), + Op::Tween => tx.motion_curve(tween()), + Op::LiveOnly => tx.live_only(), + } + } + + fn dev(self, dev: &mut Dev) { + match self { + Op::Instant => dev.instant(), + Op::Animated => dev.animated(), + Op::Settle => dev.settle(), + Op::Motion => dev.motion(MATCHED), + Op::Curve => dev.motion_curve(glide()), + Op::Tween => dev.motion_curve(tween()), + Op::LiveOnly => dev.live_only(), + } + } +} + +/// Every sequence of `OPS` up to `len`, in order. +fn sequences(len: usize) -> Vec<Vec<Op>> { + let mut all = vec![Vec::new()]; + let mut frontier = vec![Vec::new()]; + for _ in 0..len { + let mut next = Vec::new(); + for prefix in &frontier { + for op in OPS { + let mut seq = prefix.clone(); + seq.push(op); + next.push(seq); + } + } + all.extend(next.iter().cloned()); + frontier = next; + } + all +} + +/// Runs `seq` to its end, checking the production `Tx` against dev after every call. +fn walk(seq: &[Op]) -> (Tx, Dev) { + let mut tx = Tx::default(); + let mut dev = Dev::default(); + for (i, op) in seq.iter().enumerate() { + op.call(&mut tx); + op.dev(&mut dev); + assert_eq!(seen(&tx), seen_dev(&dev), "after {i} of {seq:?}"); + assert_eq!(tx.live_only, dev.live_only, "live_only after {i} of {seq:?}"); + } + (tx, dev) +} + +/// Every order of the calls that set motion intent commits as dev's flags did, including which +/// call wins when two conflict (`settle` then `animated`, `motion` then `motion_curve`). +#[test] +fn every_order_of_commit_intent_commits_as_dev_did() { + let mut reached = std::collections::BTreeSet::new(); + for seq in sequences(5) { + let (tx, _) = walk(&seq); + reached.insert(format!("{:?}", seen(&tx))); + } + // Every combination dev's flags and slots can hold, so the walk covered the whole state, + // not a corner of it: four flag states, and no motion, a spring or one of two curves. + assert_eq!(reached.len(), 4 * 4, "{reached:#?}"); +} + +/// Two handlers in one frame merge as dev's `|=` and last-`Some`-wins did, in either order. +#[test] +fn two_handlers_merge_as_dev_did() { + let states = sequences(2); + for a in &states { + for b in &states { + let (mut tx, mut dev) = walk(a); + let (one, one_dev) = walk(b); + crate::runtime::action::merge(&mut tx, one); + dev.merge(&one_dev); + assert_eq!(seen(&tx), seen_dev(&dev), "{a:?} then {b:?}"); + } + } +} + +/// The writes that set the intent directly rather than through a `Tx` setter: typing sets or +/// clears the snap and leaves running tracks landing (`keys.rs`), and a handler that declined +/// its event clears the whole intent (`action.rs`). +#[test] +fn a_direct_write_of_the_intent_matches_devs_flags() { + let starts = [Commit::Animate, Commit::Instant, Commit::Settle, Commit::SettleAnimated]; + for start in starts { + for animate_layout in [true, false] { + let mut tx = Tx { commit: start, ..Tx::default() }; + let mut dev = Dev { instant: start.snaps(), settle: start.lands(), ..Dev::default() }; + tx.commit = tx.commit.snap(!animate_layout); + dev.instant = !animate_layout; + assert_eq!((tx.commit.snaps(), tx.commit.lands()), (dev.instant, dev.settle), "{start:?} typing"); + + let mut tx = Tx { commit: start, ..Tx::default() }; + let mut dev = Dev { instant: start.snaps(), settle: start.lands(), ..Dev::default() }; + tx.commit = Commit::Animate; + dev.instant = false; + dev.settle = false; + assert_eq!((tx.commit.snaps(), tx.commit.lands()), (dev.instant, dev.settle), "{start:?} declined"); + } + } +} + +/// A handler that declines its event takes back its `live_only`, and its commit intent stands. +#[test] +fn a_declined_handler_takes_back_only_live_only() { + let mut tx = Tx::default(); + tx.settle(); + tx.live_only(); + assert!(!Tx::took(false, &mut tx)); + assert!(!tx.live_only); + assert_eq!((tx.commit.snaps(), tx.commit.lands()), (true, true)); + + let mut tx = Tx::default(); + tx.live_only(); + tx.instant(); + assert!(!Tx::took(false, &mut tx)); + assert_eq!((tx.commit.snaps(), tx.commit.lands()), (true, false)); + + // A handler that took its event keeps both. + let mut tx = Tx::default(); + tx.live_only(); + assert!(Tx::took(true, &mut tx)); + assert!(tx.live_only); +} diff --git a/app/vendor/rune/crates/rune/src/el/virtual_list.rs b/app/vendor/rune/crates/rune/src/el/virtual_list.rs new file mode 100644 index 0000000..e05b83d --- /dev/null +++ b/app/vendor/rune/crates/rune/src/el/virtual_list.rs @@ -0,0 +1,653 @@ +//! Virtual row bookkeeping. Only geometry outside the mounted window is estimated. + +use std::cell::{Cell, Ref, RefCell}; +use std::ops::Range; + +use rune_taffy::CompactStyle; +use taffy::style::{Display, FlexDirection, FlexWrap, LengthPercentage, LengthPercentageAuto, Position}; + +use crate::El; +use crate::runtime::{HashMap, HashSet}; + +/// Each row's place in `keys`, found by its key's hash: a table of indices, not a second copy +/// of every key, so a list of 100,000 rows takes new keys without 100,000 allocations. A key whose +/// hash another key took first is kept by name. +#[derive(Debug, Default)] +struct Places { + by_hash: HashMap<u64, usize>, + collided: HashMap<String, usize>, +} + +impl Places { + fn hash(key: &str) -> u64 { + use std::hash::{BuildHasher, Hash, Hasher}; + let mut h = rustc_hash::FxBuildHasher.build_hasher(); + key.hash(&mut h); + h.finish() + } + + /// The places of `keys`, which must be unique. + fn of(keys: &[String]) -> Places { + let mut places = Places { by_hash: HashMap::with_capacity_and_hasher(keys.len(), Default::default()), collided: HashMap::default() }; + for (i, key) in keys.iter().enumerate() { + match places.by_hash.entry(Self::hash(key)) { + std::collections::hash_map::Entry::Vacant(e) => { + e.insert(i); + } + std::collections::hash_map::Entry::Occupied(e) => { + assert!(keys[*e.get()] != *key, "virtual row keys must be unique"); + assert!(places.collided.insert(key.clone(), i).is_none(), "virtual row keys must be unique"); + } + } + } + places + } + + /// Where `key` is in `keys` (those `self` was made of). + fn get(&self, keys: &[String], key: &str) -> Option<usize> { + match self.by_hash.get(&Self::hash(key)) { + Some(&i) if keys[i] == key => Some(i), + _ if self.collided.is_empty() => None, + _ => self.collided.get(key).copied(), + } + } +} + +#[derive(Debug, Default)] +pub(crate) struct VirtualList { + /// Row keys in order; replace them with [`VirtualList::set_keys`]. + pub keys: Vec<String>, + places: Places, + /// Each row's measured height, once it has been laid out, in `keys` order. + measured: Vec<Option<f32>>, + /// The commit each row in `keys` first appeared in. + born: Vec<u64>, + /// `keys` changed since the frame began ([`VirtualList::frame_begins`]). + keys_fresh: bool, + /// The last change to `keys` kept a row the reader could see. + held: bool, + /// Rows mounted with their insertion transition and not yet drawn; the runtime lands the + /// ones that drew nothing (`runtime/unseen_presence.rs`). + pub entering: HashSet<String>, + /// Each row's height, measured or estimated, in `keys` order. + row_heights: Vec<f32>, + /// Running totals of `row_heights` (one longer), rebuilt when one changes. Every frame reads + /// them, so a long list doesn't hash every key to find its window. + sums: RefCell<Vec<f32>>, + sums_stale: Cell<bool>, + pub range: Range<usize>, + pub before: f32, + pub after: f32, + estimate: f32, + /// Rows are built by index (`El::virtual_rows`), so a commit costs only the rows it mounts. + /// Such a list moves its window in small steps and spreads rows new to it over frames. + pub indexed: bool, + /// The rows the last applied commit mounted. Every measurement of a commit compares with + /// these, not with the pass before it. + pub shown: HashSet<String>, + /// The rows drawn inside the viewport on the last frame (`Runtime::note_drawn_rows`). + pub drawn: Vec<String>, + /// The row holding the focused element, kept while that row is scrolled out. + pub focused_row: Option<String>, + /// Offscreen row state for text selection: the rows its anchor and focus pin, their texts + /// and their row source, plus the kept rows a stored list builds from. + pub selection: crate::runtime::selectable::virtual_selection::PinnedSelection, + /// The selected row on the last commit of an `El::reveal_selected(true)` stack. + pub selected_row: Option<String>, + pub reveal_selected: Option<String>, + pub scroll_path: String, + pub viewport: f32, + pub top: f32, + /// The list lies in a row of another virtual list with the same scroll viewport (an open + /// section of a long list, itself long): it windows against that viewport where the row + /// places it ([`VirtualList::top`]), and only that viewport, not this list, is pinned to its + /// end ([`VirtualList::locate`]). + pub nested: bool, + /// How far the viewport's content runs on under a nested list, as last laid out: where its + /// window stands while the viewport is pinned to its end. + pub tail: f32, + /// A nested list wholly above the viewport's top holds no reader, so it anchors nothing: + /// its rows changing height move the rows under it, which the list around it anchors. + passed: bool, + pub pad_top: f32, + pub pad_bottom: f32, + gap: f32, + pub anchor: Option<(String, f32)>, + /// The `El::virtual_rows_version` that `keys` came with. + pub keys_version: Option<u64>, + /// The visible row range last sent to `El::on_visible_rows`. + pub reported_visible: Option<Range<usize>>, + /// What the last applied commit mounted, for a memo holding this list to keep its nodes. + pub mounted: Option<Mounted>, + /// What the last pass that built the rows read building them. + pub row_reads: crate::memo::Reads, +} + +/// The rows a virtual list mounted and the padding standing in for the rest. +#[derive(Debug, Clone, PartialEq)] +pub(crate) struct Mounted { + range: Range<usize>, + before: f32, + after: f32, + pad_top: f32, + pad_bottom: f32, +} + +impl Mounted { + pub(crate) fn of(v: &VirtualList) -> Self { + Mounted { range: v.range.clone(), before: v.before, after: v.after, pad_top: v.pad_top, pad_bottom: v.pad_bottom } + } +} + +/// The most an element can be tall before layout, so a list's first showing, which has no +/// measured viewport yet, mounts what its viewport can show rather than the window's height. +/// Its own height in points wins; otherwise `avail`, what its parent leaves it. An estimate +/// short of the laid-out height only costs a retry pass, which never presents a blank. +pub(crate) fn height_bound(style: &CompactStyle, avail: f32) -> f32 { + let h = style.size().height.into_option().unwrap_or(avail); + let h = length(style.max_size().height).map_or(h, |m| h.min(m)); + length(style.min_size().height).map_or(h, |m| h.max(m)) +} + +/// A column flex container's vertical gap in points; zero for non-column containers. +pub(crate) fn gap_y(style: &CompactStyle) -> f32 { + let column = style.display() == Display::Flex && style.flex_wrap() == FlexWrap::NoWrap + && matches!(style.flex_direction(), FlexDirection::Column | FlexDirection::ColumnReverse); + if !column { return 0.0; } + match style.gap().height.expand() { + taffy::style::ExpandedLengthPercentage::Length(x) => x, + _ => 0.0, + } +} + +/// The most each child of an element whose bound is `bound` can be tall: what padding leaves +/// and, in a column, what siblings of fixed height and gaps don't take. A scroll viewport's +/// content is unbounded, as is an out-of-flow child not pinned to both its parent's top and +/// bottom. +pub(crate) fn child_bounds(style: &CompactStyle, scrolls: bool, bound: f32, children: &[El]) -> ChildBounds { + if scrolls { return ChildBounds { outer: f32::INFINITY, inner: f32::INFINITY, fixed: 0.0, column: false } } + let points = |p: LengthPercentage| match p.expand() { + taffy::style::ExpandedLengthPercentage::Length(x) => x, + _ => 0.0, + }; + let pad = style.padding(); + let inner = bound - points(pad.top) - points(pad.bottom); + let column = style.display() == Display::Flex && style.flex_wrap() == FlexWrap::NoWrap + && matches!(style.flex_direction(), FlexDirection::Column | FlexDirection::ColumnReverse); + if !column || children.len() < 2 { return ChildBounds { outer: bound, inner, fixed: 0.0, column: false } } + let gaps = points(style.gap().height) * children.iter().filter(|c| in_flow(&c.style)).count().saturating_sub(1) as f32; + ChildBounds { outer: bound, inner: inner - gaps, fixed: children.iter().map(|c| fixed_height(&c.style)).sum(), column } +} + +pub(crate) struct ChildBounds { + /// The parent's bound: an absolute child's insets are from its padding box. + outer: f32, + inner: f32, + fixed: f32, + column: bool, +} + +impl ChildBounds { + pub fn of(&self, child: &El) -> f32 { + let style = &child.style; + let bound = if style.position() == Position::Absolute { + let inset = style.inset(); + match (length(inset.top), length(inset.bottom)) { + (Some(top), Some(bottom)) => self.outer - top - bottom, + _ => f32::INFINITY, + } + } else if self.column && in_flow(style) { + self.inner - (self.fixed - fixed_height(style)) + } else { + self.inner + }; + bound.max(0.0) + } +} + +fn length(d: LengthPercentageAuto) -> Option<f32> { + match d.expand() { + taffy::style::ExpandedLengthPercentageAuto::Length(x) => Some(x), + _ => None, + } +} + +fn in_flow(style: &CompactStyle) -> bool { + style.display() != Display::None && style.position() != Position::Absolute +} + +/// The height a column's child takes whatever the others need: its own height when it can't +/// shrink, and its minimum. +fn fixed_height(style: &CompactStyle) -> f32 { + if !in_flow(style) { return 0.0 } + let min = length(style.min_size().height).unwrap_or(0.0); + if style.flex_shrink() > 0.0 { return min } + let h = style.size().height.into_option().unwrap_or(0.0); + length(style.max_size().height).map_or(h, |m| h.min(m)).max(min) +} + +/// How far ahead an index-built list keeps rows mounted, in viewports either side. +const OVERSCAN: f32 = 2.0; +/// An index-built list moves its window once the viewport comes this close to its edge. +const INDEXED_EDGE: f32 = 1.75; +/// How much of an index-built list's overscan, in viewports per side, may be new in one commit. +/// Rows past it mount over the next frames, so a jump or a prepended page doesn't shape it all +/// in one frame. +const INDEXED_BUDGET: f32 = 0.5; +/// The fewest rows a list pinned to its end keeps mounted above the end, whatever its overscan. +const PINNED_ROWS: usize = 32; + +impl VirtualList { + pub fn height(&self, key: &str) -> f32 { + self.index_of(key).and_then(|i| self.measured[i]).unwrap_or(self.estimate) + } + + pub fn has(&self, key: &str) -> bool { + self.index_of(key).is_some() + } + + pub fn index_of(&self, key: &str) -> Option<usize> { + self.places.get(&self.keys, key) + } + + /// Whether row `i`, mounting in `commit`, skips its insertion transition. A row scrolled into + /// view was there all along, so it does. One new to the rows enters as an insertion, and so + /// does one that a change to the rows this frame (a filter, a sort) mounts: the rows it + /// replaces leave with their exits. Rows mounting with their transition are noted in + /// `entering`, and the runtime lands the ones that drew out of view, so only what shows fades. + pub fn mounts_quietly(&mut self, i: usize, commit: u64) -> bool { + let quiet = self.born[i] < commit && !(self.keys_fresh && !self.shown.contains(&self.keys[i])); + if !quiet { self.entering.insert(self.keys[i].clone()); } + quiet + } + + /// The rows changed this frame and none the reader could see stayed (a filter): the rows + /// that leave hold no place, so what comes in shows where they stood. + pub fn replaced_view(&self) -> bool { + self.keys_fresh && !self.held + } + + /// A new frame: what changed the keys before it has been drawn. Within a frame a scroll the + /// change asks for (`Tx::scroll_into_view`) commits again, and the rows it brings in are + /// still the change's. + pub fn frame_begins(&mut self) { + self.keys_fresh = false; + } + + /// Whether the rows are exactly `keys`, in order. + pub fn same_keys<'a>(&self, keys: impl ExactSizeIterator<Item = Option<&'a str>>) -> bool { + keys.len() == self.keys.len() && keys.zip(&self.keys).all(|(a, b)| a == Some(b.as_str())) + } + + /// Replaces the rows. Keys that stay keep their measured height and birth; new ones are born + /// at `commit`. Returns the first row visible at `offset` (when given) that stays, with its + /// top before the change, to anchor the reader to: none when no row in view stays. + pub fn set_keys(&mut self, keys: Vec<String>, commit: u64, offset: Option<f32>) -> Option<(String, f32)> { + let places = Places::of(&keys); + let mut born = Vec::with_capacity(keys.len()); + let mut heights = Vec::with_capacity(keys.len()); + let mut measured = Vec::with_capacity(keys.len()); + for key in &keys { + let old = self.index_of(key); + let height = old.and_then(|i| self.measured[i]); + born.push(old.map_or(commit, |i| self.born[i])); + heights.push(height.unwrap_or(self.estimate)); + measured.push(height); + } + let stays = |k: &str| places.get(&keys, k).is_some(); + // A change that keeps none of the rows in view (a filter) leaves nothing to hold. + let anchor = offset.and_then(|offset| self.first_visible(offset, &stays)) + .filter(|(_, top)| offset.is_some_and(|offset| *top < offset + self.viewport)); + if keys != self.keys { + self.keys_fresh = true; + self.held = if offset.is_some() { anchor.is_some() } else { self.keys.iter().any(|k| stays(k)) }; + } + self.places = places; + self.measured = measured; + self.born = born; + self.keys = keys; + self.row_heights = heights; + self.sums_stale.set(true); + self.reported_visible = None; + anchor + } + + /// The list's own scroll offset, and whether its window is pinned to its end, for its + /// viewport scrolled to `scroll` (`pinned`: the viewport holds its end). A nested list + /// is never pinned itself: it stands where the viewport's end leaves it. + pub fn at(&self, scroll: f32, pinned: bool) -> (f32, bool) { + if !self.nested { + return ((scroll - self.top).max(0.0), pinned); + } + let offset = if pinned { self.extent() + self.tail - self.viewport } else { scroll - self.top }; + (offset.max(0.0), false) + } + + /// [`VirtualList::at`], noting whether a nested list lies wholly above the viewport's top + /// and so anchors nothing (`select`, `hold` and the commits that anchor the reader). + pub fn locate(&mut self, scroll: f32, pinned: bool) -> (f32, bool) { + let at = self.at(scroll, pinned); + self.passed = self.nested && at.0 >= self.extent(); + at + } + + /// Whether the list is nested and wholly above the viewport's top, so it anchors nothing + /// ([`VirtualList::locate`]). + pub fn passed(&self) -> bool { + self.passed + } + + /// The rows' extent, their padding included. + fn extent(&self) -> f32 { + self.pad_top + self.prefix(self.keys.len()) + self.pad_bottom + } + + pub fn set_estimate(&mut self, estimate: f32) { + if estimate != self.estimate { + self.estimate = estimate; + self.row_heights = self.keys.iter().map(|k| self.height(k)).collect(); + self.sums_stale.set(true); + } + } + + pub fn set_gap(&mut self, gap: f32) { + if gap != self.gap { + self.gap = gap; + self.sums_stale.set(true); + } + } + + pub fn set_height(&mut self, key: &str, height: f32) { + let Some(i) = self.index_of(key) else { return }; + self.measured[i] = Some(height); + if self.row_heights[i] != height { + self.row_heights[i] = height; + self.sums_stale.set(true); + } + } + + fn sums(&self) -> Ref<'_, Vec<f32>> { + if self.sums_stale.replace(false) || self.sums.borrow().len() != self.row_heights.len() + 1 { + let mut sums = self.sums.borrow_mut(); + sums.clear(); + sums.push(0.0); + let mut y = 0.0; + for h in &self.row_heights { + y += h + self.gap; + sums.push(y); + } + } + self.sums.borrow() + } + + pub fn prefix(&self, end: usize) -> f32 { + let sums = self.sums(); + if end == 0 || end < self.keys.len() { sums[end] } else { sums[end] - self.gap } + } + + /// The bottom of the first `end` rows (without the gap after row `end - 1`). + pub fn row_end(&self, end: usize) -> f32 { + if end == 0 { 0.0 } else { self.sums()[end] - self.gap } + } + + /// The first row still visible at `offset`, among those `keep` accepts, and its top. + pub fn first_visible(&self, offset: f32, keep: impl Fn(&str) -> bool) -> Option<(String, f32)> { + let sums = self.sums(); + let first = sums[1..].partition_point(|&s| self.pad_top + s - self.gap <= offset); + (first..self.keys.len()) + .find(|&i| keep(&self.keys[i])) + .map(|i| (self.keys[i].clone(), self.pad_top + sums[i])) + } + + /// The furthest the rows can scroll: their extent less the viewport. + pub fn max_offset(&self) -> f32 { + (self.pad_top + self.prefix(self.keys.len()) + self.pad_bottom - self.viewport).max(0.0) + } + + /// The row index range intersecting the scroll viewport (`offset .. offset + viewport`). + pub fn visible_range(&self, offset: f32, pinned: bool) -> Range<usize> { + if self.keys.is_empty() { + return 0..0; + } + let offset = if pinned { self.max_offset() } else { offset.clamp(0.0, self.max_offset()) }; + let sums = self.sums(); + let start = sums[1..].partition_point(|&s| self.pad_top + s - self.gap <= offset); + let end = sums[..self.keys.len()].partition_point(|&s| self.pad_top + s < offset + self.viewport).max(start); + start..end + } + + /// Picks the rows to mount for `offset`, clamped to the rows' extent. With `budget` (the + /// rows shown last commit), at most [`INDEXED_BUDGET`] of rows not among them mount per + /// side beyond the viewport. + pub fn select(&mut self, offset: f32, pinned: bool, budget: Option<&HashSet<String>>) { + let offset = if pinned { self.max_offset() } else { offset.min(self.max_offset()) }; + let (start, end) = self.overscan(offset); + let (mut start, mut end) = { + let sums = self.sums(); + if let Some(shown) = budget.filter(|_| !pinned) { + let mounted = |k: &str| shown.contains(k); + // The viewport's own rows always mount; the overscan takes new rows up to a budget. + let first = sums[1..].partition_point(|&s| self.pad_top + s - self.gap <= offset).max(start); + let last = sums[..self.keys.len()].partition_point(|&s| self.pad_top + s < offset + self.viewport).max(first); + let budget = self.viewport * INDEXED_BUDGET; + let mut spent = 0.0; + let mut from = first; + while from > start { + let i = from - 1; + if !mounted(&self.keys[i]) { + if spent >= budget { break; } + spent += self.row_heights[i] + self.gap; + } + from = i; + } + let mut spent = 0.0; + let mut to = last.min(end); + while to < end { + if !mounted(&self.keys[to]) { + if spent >= budget { break; } + spent += self.row_heights[to] + self.gap; + } + to += 1; + } + (from, to.max(from)) + } else { + (start, end) + } + }; + // Rows drawn in the viewport stay while motion still shows them where layout has moved + // them out (rows below a fold gliding open), within an overscan of the window. + let (mut lo, mut hi) = (start, end); + for i in self.drawn.iter().filter_map(|k| self.index_of(k)) { + if i < start && self.prefix(start) - self.prefix(i) <= self.viewport * OVERSCAN { lo = lo.min(i); } + if i >= end && self.row_end(i + 1) - self.row_end(end) <= self.viewport * OVERSCAN { hi = hi.max(i + 1); } + } + (start, end) = (lo, hi); + // A row still at its estimate grows or shrinks once measured; anchoring to it would move + // the measured rows below, such as the reader's row under a page that just landed. + self.anchor = if pinned || self.passed { None } else { self.anchor_at(offset) }; + if pinned { start = start.min(end.saturating_sub(PINNED_ROWS)); } + end = end.max(start); + self.place(start..end); + } + + /// Keeps the rows mounted now (clamped to the rows), sets the anchor for `offset` as + /// [`select`](Self::select) does, and re-derives the space above and below them. + pub fn hold(&mut self, offset: f32, pinned: bool) { + let offset = if pinned { self.max_offset() } else { offset.min(self.max_offset()) }; + self.anchor = if pinned || self.passed { None } else { self.anchor_at(offset) }; + let len = self.keys.len(); + self.place(self.range.start.min(len)..self.range.end.min(len)); + } + + fn place(&mut self, range: Range<usize>) { + let total = self.prefix(self.keys.len()); + let (start, end) = (range.start, range.end.max(range.start)); + self.range = start..end; + self.before = self.prefix(start); + self.after = if start < end { total - self.row_end(end) } else { total - self.before }; + } + + fn anchor_at(&self, offset: f32) -> Option<(String, f32)> { + let range = self.visible_range(offset, false); + let sums = self.sums(); + range.into_iter().find(|&i| self.measured[i].is_some()) + .map(|i| (self.keys[i].clone(), self.pad_top + sums[i])) + .or_else(|| self.first_visible(offset, |_| true)) + } + + /// The rows within the overscan around `offset`: rows ending at or above its top go, rows + /// starting above its bottom stay. + fn overscan(&self, offset: f32) -> (usize, usize) { + let lo = offset - self.viewport * OVERSCAN; + let hi = offset + self.viewport * (1.0 + OVERSCAN); + let sums = self.sums(); + let start = sums[1..].partition_point(|&s| self.pad_top + s - self.gap <= lo); + (start, sums[..self.keys.len()].partition_point(|&s| self.pad_top + s < hi)) + } + + /// How tall the mounted rows outside the overscan around `offset` are: rows that grew since + /// the window was picked and lay out for nothing. + pub(crate) fn spare(&self, offset: f32, pinned: bool) -> f32 { + if pinned || self.keys.is_empty() { return 0.0; } + let (start, end) = self.overscan(offset.min(self.max_offset())); + let above = self.prefix(start.min(self.range.end)) - self.prefix(self.range.start.min(start)); + let below = self.row_end(self.range.end) - self.row_end(end.max(self.range.start).min(self.range.end)); + above.max(0.0) + below.max(0.0) + } + + pub fn anchor_delta(&self) -> f32 { + let Some((key, old)) = &self.anchor else { return 0.0 }; + let Some(i) = self.index_of(key) else { return 0.0 }; + self.pad_top + self.prefix(i) - old + } + + pub fn needs_window(&self, offset: f32, pinned: bool) -> bool { + if self.keys.is_empty() { return false; } + if pinned { return self.range.end != self.keys.len(); } + let edge = self.viewport * if self.indexed { INDEXED_EDGE } else { 0.5 }; + let top = self.pad_top + self.before; + let bottom = self.pad_top + self.row_end(self.range.end); + (self.range.start > 0 && offset < top + edge) + || (self.range.end < self.keys.len() && offset + self.viewport > bottom - edge) + } + + /// How many rows of the overscan around `offset` are still unmounted: zero when the window + /// is filled. The fill measures this at its bound to tell a list that is still making + /// progress from one whose heights keep changing under it. Only the overscan's own rows + /// count: after a jump the mounted window may lie wholly above or below it, and the rows + /// between the two are wanted by neither. A pinned list wants the overscan at its end, and + /// at least [`PINNED_ROWS`] rows, as [`select`](Self::select) mounts them. + pub(crate) fn unfilled(&self, offset: f32, pinned: bool) -> usize { + if self.keys.is_empty() { return 0; } + let (start, end) = if pinned { + let (start, end) = self.overscan(self.max_offset()); + (start.min(end.saturating_sub(PINNED_ROWS)), end) + } else { + self.overscan(offset.min(self.max_offset())) + }; + let mounted = self.range.end.min(end).saturating_sub(self.range.start.max(start)); + end.saturating_sub(start) - mounted + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::{col, el}; + + #[test] + fn gaps_surround_a_virtual_window_without_a_trailing_gap() { + let mut v = VirtualList::default(); + v.set_estimate(20.0); + v.set_gap(7.0); + v.set_keys((0..100).map(|i| format!("r{i}")).collect(), 0, None); + v.viewport = 40.0; + assert_eq!(v.prefix(100), 2693.0); + assert_eq!(v.prefix(50), 1350.0); + assert_eq!(v.row_end(50), 1343.0); + // In a gap the next row is the first visible row, not the one above it. + assert_eq!(v.first_visible(21.0, |_| true), Some(("r1".into(), 27.0))); + v.select(1350.0, false, None); + let n = v.range.len(); + let mounted = n as f32 * 20.0 + n.saturating_sub(1) as f32 * 7.0; + assert_eq!(v.before + mounted + v.after, 2693.0); + assert_eq!(v.before, v.range.start as f32 * 27.0); + v.set_height("r0", 35.0); + assert_eq!(v.prefix(50), 1365.0, "measured heights replace only the estimate, not the gap"); + v.set_gap(3.0); + assert_eq!(v.prefix(100), 2312.0, "a changed gap invalidates prefix sums"); + v.set_keys(Vec::new(), 1, None); + assert_eq!(v.prefix(0), 0.0); + } + + #[test] + fn growth_gap_uses_the_vertical_axis_only() { + assert_eq!(gap_y(&col().gaps(7.0, 19.0).style), 7.0); + assert_eq!(gap_y(&crate::row().gaps(7.0, 19.0).style), 0.0); + } + + #[test] + fn an_absolute_child_is_bounded_only_when_pinned_top_and_bottom() { + let children = [ + el().pin(Some(0.0), Some(10.0), Some(0.0), Some(20.0)), + el().absolute(0.0, 10.0), + el().h(40.0), + el(), + ]; + let parent = col().h(100.0).pt(5.0); + let bounds = child_bounds(&parent.style, false, 100.0, &children); + assert_eq!(bounds.of(&children[0]), 70.0, "between its insets in the padding box"); + assert_eq!(bounds.of(&children[1]), f32::INFINITY, "free to grow past its parent"); + assert_eq!(bounds.of(&children[3]), 55.0, "in flow, what padding and the fixed sibling leave"); + } + + /// The unfilled count is the overscan's rows the window doesn't hold, wherever the window + /// sits: a window wholly above or below the overscan after a jump leaves exactly the + /// overscan to fill, not the rows between them, and no row counts twice. + #[test] + fn unfilled_counts_only_the_overscan_rows_the_window_lacks() { + let mut v = VirtualList::default(); + v.set_estimate(20.0); + v.set_keys((0..100).map(|i| format!("r{i}")).collect(), 0, None); + v.viewport = 40.0; + // At 1080 the overscan runs from 1000 to 1200: rows 50 to 59. + let (offset, wanted) = (1080.0, 50..60); + for a in 0..=100 { + for b in a..=100 { + v.range = a..b; + let missing = wanted.clone().filter(|i| !(a..b).contains(i)).count(); + assert_eq!(v.unfilled(offset, false), missing, "window {a}..{b}"); + } + } + v.range = 0..10; + assert_eq!(v.unfilled(offset, false), 10, "a window above the overscan after a jump"); + v.range = 90..100; + assert_eq!(v.unfilled(offset, false), 10, "a window below the overscan after a jump"); + } + + /// A list pinned to its end counts the rows of its end window the mounted ones don't hold: + /// the overscan at the end, or the last 32 rows when that is fewer. A window left far above + /// it after many rows land counts that end window alone, and rows above the window count too. + #[test] + fn pinned_unfilled_counts_only_the_end_window_rows_the_window_lacks() { + let mut v = VirtualList::default(); + v.set_estimate(20.0); + v.set_keys((0..100).map(|i| format!("r{i}")).collect(), 0, None); + // A 40 tall viewport ends at 2000, its overscan from 1880: six rows, fewer than 32. + // A 300 tall one's overscan runs from 1100: rows 55 on. + for (viewport, wanted) in [(40.0, 68..100), (300.0, 55..100)] { + v.viewport = viewport; + for a in 0..=100 { + for b in a..=100 { + v.range = a..b; + let missing = wanted.clone().filter(|i| !(a..b).contains(i)).count(); + // The offset passed is ignored: a pinned list sits at its end. + assert_eq!(v.unfilled(0.0, true), missing, "viewport {viewport}, window {a}..{b}"); + } + } + } + v.viewport = 40.0; + v.range = 0..10; + assert_eq!(v.unfilled(0.0, true), 32, "a window left at the top after rows landed below it"); + } +} diff --git a/app/vendor/rune/crates/rune/src/el/virtual_rows.rs b/app/vendor/rune/crates/rune/src/el/virtual_rows.rs new file mode 100644 index 0000000..01462c5 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/el/virtual_rows.rs @@ -0,0 +1,154 @@ +//! Index-built virtual rows: [`El::virtual_rows`](crate::El::virtual_rows) gives a virtual +//! list a row count, a key per index and a builder per index. Layout builds only the rows in +//! the mounted window, so a commit costs a key check per row plus the rows it mounts, however +//! long the list is. + +use std::borrow::Cow; +use std::rc::Rc; + +use crate::El; +use crate::el::ElFlags; +use crate::states::downcast; + +impl El { + /// Window keyed rows of a growth stack inside a vertical scroll viewport. + /// Unvisited rows use an estimated height; measurement preserves the visible anchor. + /// Offscreen rows have no layout, text or scene nodes. + /// + /// Use [`El::virtual_rows`] unless the list is short: the view still builds every row + /// handed to `virtualize` on every commit, mounted or not. Debug builds warn once per list + /// that builds more than 200 rows and four times what it mounts. + /// + /// The same element must also be a growth stack: call `.growth(GrowthSpec)` on it as well + /// as `.virtualize(..)`, and put it inside a `.scroll(..)` viewport: as its content, or + /// under or among other content in it, at any depth (a page whose figures sit above a long + /// list in one scroll). It windows against the nearest viewport around it. Layout panics + /// with the element's path otherwise. + /// + /// ```ignore + /// col().scroll(ScrollSpec { stick_bottom: false }).grow(1.0).child( + /// col().key("rows").growth(GrowthSpec::default()).virtualize(32.0).children(rows), + /// ) + /// ``` + #[cfg_attr(debug_assertions, track_caller)] + pub fn virtualize(mut self, estimated_row_height: f32) -> Self { + self.cold_mut().virtual_estimate = Some(estimated_row_height.max(1.0)); + self.flags.set(ElFlags::HAS_VIRTUAL, true); + #[cfg(debug_assertions)] + { self.cold_mut().virtual_source = Some(std::panic::Location::caller()); } + self + } + + /// [`El::virtualize`] with rows built by index: `count` rows, row `i` keyed `key(s, i)` and + /// built by `build(s, i)`. Layout calls `build` only for the rows in the mounted window (the + /// viewport and up to two viewports either side), after it knows where that window is, so a + /// commit costs one `key` call per row plus the rows it mounts, however long the list is. + /// Rows new to the window beyond the viewport mount half a viewport per side per frame, so a + /// jump or a prepended page doesn't lay out three viewports of text at once. + /// Both closures get the window's state, so they capture nothing borrowed. + /// + /// Everything `virtualize` does holds: rows keep their measured heights by key while the key + /// stays, unvisited rows use the estimate, inserting or prepending rows keeps the reader's + /// row in place, and `Tx::scroll_into_view` reaches any row by key. A row's key is + /// `key(s, i)`, whatever key its element had. The same element needs `.growth(GrowthSpec)` + /// and must be inside a `.scroll(..)` viewport (see [`El::virtualize`]), and holds no other + /// children. + /// + /// A row outside the window isn't built, so it has no elements at all: the inspector, + /// `Runtime::elements`, accessibility, Tab order, text selection and matched elements see the + /// built rows only. A focused field in a row that scrolls out keeps its focus and typing (its + /// row is built for that, not mounted); a field focused from state in a row that isn't built + /// takes focus once the row is. A [`memo`](crate::memo) inside `build` keeps its subtree while + /// the row stays built; a row built again after scrolling out builds afresh. + /// + /// Handlers in a row must find their item by its key or id, never by `i`. An index is only + /// where the item sat when the row was built: a row kept by `memo` keeps its handlers while + /// rows are inserted or removed above it, so a handler holding `i` would act on whatever + /// item moved into that slot. + /// + /// ```ignore + /// col().scroll(ScrollSpec { stick_bottom: true }).grow(1.0).child( + /// col().key("rows").growth(GrowthSpec::default()).virtual_rows(s.messages.len(), 72.0, + /// |s: &App, i| s.messages[i].id.as_str().into(), + /// |s: &App, i| { + /// let m = &s.messages[i]; + /// let id = m.id.clone(); + /// memo(&m.id, m.revision, || message(m).on_press(move |s: &mut App| s.open(&id))) + /// }), + /// ) + /// ``` + pub fn virtual_rows<S: 'static>( + mut self, + count: usize, + estimated_row_height: f32, + key: impl for<'a> Fn(&'a S, usize) -> Cow<'a, str> + 'static, + build: impl Fn(&S, usize) -> El + 'static, + ) -> Self { + self.cold_mut().virtual_rows = Some(Rc::new(RowSource::new(count, key, build))); + self.virtualize(estimated_row_height) + } + + /// Tells [`El::virtual_rows`] its keys are those of the last commit that gave the same + /// `version`, so layout skips calling `key` for every row to find out. A list of tens of + /// thousands of rows then commits in time independent of its length. Change `version` + /// whenever rows are reordered, replaced or any row's key changes while the row count stays + /// the same (a change in `count` is always detected without a bump); with a stale version on + /// an in-place change the rows keep their old keys. + pub fn virtual_rows_version(mut self, version: impl std::hash::Hash) -> Self { + self.cold_mut().virtual_rows_version = Some(crate::memo::hash_of(&version)); + self + } + + /// On a virtual list ([`El::virtualize`] or [`El::virtual_rows`]), called with the index + /// range `start..end` of rows currently visible in its scroll viewport: once after its + /// first layout, then whenever that range or the rows change. Return `true` when `f` + /// changed state the view reads (so the view runs again), or `false` when it only updated + /// bookkeeping (so scrolling through rows that don't change the view's output doesn't + /// re-run the view). + #[track_caller] + pub fn on_visible_rows<S: 'static>( + mut self, + f: impl Fn(&mut S, std::ops::Range<usize>) -> bool + 'static, + ) -> Self { + self.handlers.on_visible_rows = Some(Rc::new(move |s, r| f(downcast::<S>(s), r))); + #[cfg(debug_assertions)] + { self.handlers.sites.visible_rows = Some(std::panic::Location::caller()); } + self + } +} + +pub(crate) type KeyFn = dyn for<'a> Fn(crate::states::StatesRef<'a>, usize) -> Cow<'a, str>; +pub(crate) type BuildFn = dyn Fn(crate::states::StatesRef<'_>, usize) -> El; + +/// The rows of an index-built list, built at layout time from the window's state. +pub(crate) struct RowSource { + pub(crate) count: usize, + pub(crate) key: Box<KeyFn>, + pub(crate) build: Box<BuildFn>, +} + +fn key_fn<F: for<'a> Fn(crate::states::StatesRef<'a>, usize) -> Cow<'a, str>>(f: F) -> F { + f +} + +fn state<S: 'static>(s: crate::states::StatesRef<'_>) -> &S { + s.cast::<S>().expect("virtual rows registered for a different state type than the window's") +} + +impl RowSource { + pub(crate) fn new<S: 'static>( + count: usize, + key: impl for<'a> Fn(&'a S, usize) -> Cow<'a, str> + 'static, + build: impl Fn(&S, usize) -> El + 'static, + ) -> Self { + RowSource { + count, + key: Box::new(key_fn(move |s, i| key(state::<S>(s), i))), + build: Box::new(move |s, i| build(state::<S>(s), i)), + } + } +} + +#[cfg(test)] +#[path = "virtual_rows_tests.rs"] +mod tests; diff --git a/app/vendor/rune/crates/rune/src/el/virtual_rows_tests.rs b/app/vendor/rune/crates/rune/src/el/virtual_rows_tests.rs new file mode 100644 index 0000000..166c725 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/el/virtual_rows_tests.rs @@ -0,0 +1,801 @@ +use std::cell::{Cell, RefCell}; + +use crate::{Cx, El, Env, GrowthSpec, Runtime, ScrollSpec, col, el, memo, text}; + +thread_local! { + static VIEWS: Cell<usize> = const { Cell::new(0) }; + static VIEW_NS: Cell<u128> = const { Cell::new(0) }; + static BUILT: RefCell<Vec<usize>> = const { RefCell::new(Vec::new()) }; + /// Calls of `grid_rows`' builder for its first row: one per measurement pass. + static PASSES: Cell<usize> = const { Cell::new(0) }; +} + +#[derive(Clone, Copy, PartialEq)] +enum Mode { + /// `virtualize` with every row a `memo` the view makes. + Memo, + /// `virtual_rows`, each built row a `memo`. + Index, +} + +struct Chat { + ids: Vec<u64>, + keys: Vec<String>, + tick: u64, + markdown: bool, + mode: Mode, + /// Room above the first row, as a timeline's top padding. + pad: f32, +} + +impl Chat { + fn new(n: u64, markdown: bool, mode: Mode) -> Self { + let mut chat = Chat { ids: Vec::new(), keys: Vec::new(), tick: 0, markdown, mode, pad: 0.0 }; + chat.splice(0, (0..n).map(|i| 100_000 + i)); + chat + } + + fn splice(&mut self, at: usize, ids: impl Iterator<Item = u64>) { + let ids: Vec<u64> = ids.collect(); + self.keys.splice(at..at, ids.iter().map(|id| format!("m{id}"))); + self.ids.splice(at..at, ids); + } +} + +fn body(id: u64, markdown: bool) -> El { + if !markdown { + return col().w_full().h(72.0).padding(8.0).gap(4.0).children([ + text(format!("Message {id}")).key("title"), + text(format!("Body of message {id}, a line of text that is long enough to wrap twice")).wrap().w_full().key("body"), + text(format!("{id} min ago")).key("time"), + ]); + } + let para = |n: u64| format!("Paragraph {n} of message {id}: {}", "some prose with `code`, **bold** words and links to wrap ".repeat((id % 4 + 1) as usize)); + col().w_full().padding(8.0).gap(6.0).children([ + text(format!("## Heading for message {id}")).key("h"), + text(para(1)).wrap().w_full().key("p1"), + text(para(2)).wrap().w_full().key("p2"), + text(format!("fn message_{id}() -> u64 {{ {id} }}")).key("code"), + ]) +} + +fn view(s: &Chat, _: &mut Cx<Chat>) -> El { + let start = crate::time::now(); + let stack = col().key("rows").w_full().pt(s.pad).growth(GrowthSpec::default()); + let stack = match s.mode { + Mode::Memo => stack.virtualize(72.0).children(s.ids.iter().map(|&id| memo(format!("m{id}"), 0, || body(id, s.markdown)))), + Mode::Index => stack.virtual_rows(s.ids.len(), 72.0, |s: &Chat, i| s.keys[i].as_str().into(), |s: &Chat, i| { + BUILT.with_borrow_mut(|b| b.push(i)); + memo(s.keys[i].as_str(), 0, || body(s.ids[i], s.markdown)) + }), + }; + let root = col().w_full().h_full().children([ + text(format!("tick {}", s.tick)).key("counter"), + col().key("scroll").w_full().grow(1.0).scroll(ScrollSpec { stick_bottom: true }).child(stack), + ]); + VIEWS.set(VIEWS.get() + 1); + VIEW_NS.set(VIEW_NS.get() + start.elapsed().as_nanos()); + root +} + +fn commit<S: 'static>(rt: &mut Runtime<S>) { + rt.invalidate(); + rt.frame(1.0 / 120.0); +} + +fn chat(n: u64, markdown: bool, mode: Mode) -> Runtime<Chat> { + let mut rt = Runtime::new(Chat::new(n, markdown, mode), view, (600.0, 800.0), Env::new(true, 2.0)); + rt.frame(0.0); + rt +} + +fn built() -> Vec<usize> { + let mut b = BUILT.with_borrow_mut(std::mem::take); + b.sort_unstable(); + b.dedup(); + b +} + +/// Visible rows' keys and rects. +fn visible<S: 'static>(rt: &Runtime<S>) -> Vec<(String, [f32; 4])> { + rt.elements().into_iter() + .filter(|e| e.visible[3] > 0.0) + .filter_map(|e| Some((e.path.strip_prefix("#0/scroll/rows/").filter(|k| !k.contains('/'))?.to_owned(), e.rect))) + .collect() +} + +/// Rows `r{i}` of height `s[i]`, estimated at 50 points, in a 500-point viewport that starts +/// at the top. +fn fixed_view(s: &Vec<u32>, _: &mut Cx<Vec<u32>>) -> El { + col().w_full().h_full().child( + col().key("scroll").w_full().grow(1.0).scroll(ScrollSpec { stick_bottom: false }).child( + col().key("rows").w_full().growth(GrowthSpec::default()).virtual_rows(s.len(), 50.0, + |_: &Vec<u32>, i| format!("r{i}").into(), + |s: &Vec<u32>, i| memo(format!("r{i}"), s[i], || { + BUILT.with_borrow_mut(|b| b.push(i)); + el().w_full().h(s[i] as f32) + }))), + ) +} + +fn fixed(n: usize) -> Runtime<Vec<u32>> { + let mut rt = Runtime::new(vec![50; n], fixed_view, (300.0, 500.0), Env::new(true, 1.0)); + rt.frame(0.0); + rt +} + +/// Draws frames while the runtime asks for them, as an idle host does. +fn until_idle<S: 'static>(rt: &mut Runtime<S>) -> usize { + let mut frames = 0; + while rt.frame(1.0 / 120.0) { + frames += 1; + assert!(frames < 60, "never rests"); + } + frames +} + +#[test] +fn only_the_window_builds_and_scrolling_builds_what_comes_in() { + let mut rt = chat(5000, false, Mode::Index); + let first = built(); + assert!(!first.is_empty() && first.len() < 60, "built {} rows", first.len()); + assert!(first.iter().all(|&i| i >= 4900), "pinned to the bottom, the tail builds: {first:?}"); + assert!(rt.tree.nodes.len() < 400, "{} nodes", rt.tree.nodes.len()); + let (count, commits) = (first.len(), rt.stats.commits); + for _ in 0..5 { + rt.state.tick += 1; + commit(&mut rt); + } + let ticks = built(); + assert!(rt.stats.commits >= commits + 5); + assert!(ticks.len() <= count, "a tick builds the window only: {}", ticks.len()); + + for _ in 0..80 { + rt.wheel(300.0, 400.0, 400.0); + rt.frame(1.0 / 120.0); + } + assert!(built().iter().any(|&i| i < 4900), "scrolling builds rows it brings in"); + rt.state.tick += 1; + commit(&mut rt); + let top = rt.state.keys.iter().position(|k| visible(&rt)[0].0 == *k).unwrap(); + assert!(top < 4600, "{top}"); + // The window is the viewport and two viewports either side; rows here are 72 points. + let now = built(); + assert!(now.iter().all(|&i| i + 25 >= top && i <= top + 36), "only rows near the viewport build: {now:?} vs top {top}"); +} + +#[test] +fn index_rows_lay_out_as_virtualize_does_while_paging_and_prepending() { + let mut a = chat(600, true, Mode::Memo); + let mut b = chat(600, true, Mode::Index); + let same = |a: &Runtime<Chat>, b: &Runtime<Chat>, step: &str| { + let (va, vb) = (visible(a), visible(b)); + assert!(!va.is_empty(), "{step}"); + assert_eq!(va.len(), vb.len(), "{step}"); + for ((ka, ra), (kb, rb)) in va.iter().zip(&vb) { + assert_eq!(ka, kb, "{step}"); + assert!(ra.iter().zip(rb).all(|(x, y)| (x - y).abs() < 0.05), "{step}: {ka} {ra:?} vs {rb:?}"); + } + }; + for step in 0..120 { + same(&a, &b, &format!("step {step}")); + let dy = if step < 80 { 211.5 } else { -97.0 }; + for rt in [&mut a, &mut b] { + rt.wheel(300.0, 400.0, dy); + rt.frame(1.0 / 120.0); + } + } + let before = visible(&b); + for rt in [&mut a, &mut b] { + let first = rt.state.ids[0]; + rt.state.splice(0, first - 60..first); + commit(rt); + } + same(&a, &b, "prepended"); + let after = visible(&b); + assert_eq!(before[0].0, after[0].0, "prepending keeps the reader's row"); + assert!((before[0].1[1] - after[0].1[1]).abs() < 0.05, "in place: {:?} vs {:?}", before[0], after[0]); + for _ in 0..40 { + for rt in [&mut a, &mut b] { + rt.wheel(300.0, 400.0, 3000.0); + rt.frame(1.0 / 120.0); + } + } + same(&a, &b, "scrolled into the prepended page"); + assert_eq!(visible(&b)[0].0, "m99940", "reached the top"); +} + +#[test] +fn a_page_prepended_above_the_reader_at_the_top_keeps_them_in_place() { + let mut rt = chat(300, true, Mode::Index); + for _ in 0..20 { + rt.wheel(300.0, 400.0, 100_000.0); + rt.frame(1.0 / 120.0); + } + let before = visible(&rt); + assert_eq!(before[0].0, "m100000", "at the top"); + built(); + let first = rt.state.ids[0]; + rt.state.splice(0, first - 60..first); + commit(&mut rt); + let after = visible(&rt); + assert_eq!(before.len(), after.len()); + for ((kb, rb), (ka, ra)) in before.iter().zip(&after) { + assert_eq!(kb, ka); + assert!(rb.iter().zip(ra).all(|(x, y)| (x - y).abs() < 0.05), "{kb} moved: {rb:?} vs {ra:?}"); + } + let page = built(); + assert!(page.iter().all(|&i| i < 60 + 40), "{page:?}"); + // The page above mounts a little per frame, not two viewports of new rows at once. + assert!(page.iter().filter(|&&i| i < 60).count() <= 10, "{page:?}"); + for _ in 0..10 { + rt.frame(1.0 / 120.0); + } + assert_eq!(visible(&rt), after, "and nothing drifts after"); +} + +#[test] +fn a_page_prepended_while_the_top_padding_shows_keeps_the_reader_in_place() { + // At the very top the padding above the first row shows, so the reader's row starts + // below the offset. Once the page lands, that gap is the end of the row above it, still + // at its estimate: measuring it must not push the reader's row down. + let mut rt = chat(300, true, Mode::Index); + rt.state.pad = 8.0; + commit(&mut rt); + for _ in 0..20 { + rt.wheel(300.0, 400.0, 100_000.0); + rt.frame(1.0 / 120.0); + } + let before = visible(&rt); + assert_eq!(before[0].0, "m100000", "at the top"); + let first = rt.state.ids[0]; + rt.state.splice(0, first - 60..first); + commit(&mut rt); + for _ in 0..10 { + let after = visible(&rt); + for (key, was) in &before { + let now = after.iter().find(|(k, _)| k == key).map(|(_, r)| r); + assert!(now.is_some_and(|now| (now[1] - was[1]).abs() < 0.05), "{key} moved: {was:?} vs {now:?}"); + } + rt.frame(1.0 / 120.0); + } +} + +#[test] +fn scroll_into_view_reaches_a_row_never_built() { + let mut rt = chat(5000, true, Mode::Index); + built(); + rt.update(|s, tx| tx.scroll_into_view(s.keys[10].clone())); + for _ in 0..3 { + rt.frame(1.0 / 120.0); + } + let shown = visible(&rt); + assert!(shown.iter().any(|(k, _)| *k == rt.state.keys[10]), "{:?}", shown.iter().map(|(k, _)| k).collect::<Vec<_>>()); + // The update's own commit, before the reveal, builds the tail it was at. + let now = built(); + assert!(now.iter().all(|&i| i < 60 || i >= 4900), "only rows near it build: {now:?}"); +} + +#[test] +fn a_count_shrunk_below_the_offset_shows_the_rows_left_in_the_same_frame() { + let mut rt = fixed(1000); + rt.wheel(150.0, 250.0, -40_000.0); + until_idle(&mut rt); + assert_eq!(visible(&rt)[0].0, "r800"); + rt.state.truncate(10); + commit(&mut rt); + let shown: Vec<_> = visible(&rt).into_iter().map(|(k, _)| k).collect(); + assert_eq!(shown, (0..10).map(|i| format!("r{i}")).collect::<Vec<_>>()); +} + +#[test] +fn scroll_into_view_lands_a_row_taller_than_its_estimate_in_one_frame() { + let mut rt = chat(5000, true, Mode::Index); + for _ in 0..20 { + rt.wheel(300.0, 400.0, 100_000.0); + rt.frame(1.0 / 120.0); + } + assert_eq!(visible(&rt)[0].0, "m100000", "at the top"); + let key = rt.state.keys[500].clone(); + rt.update(|_, tx| tx.scroll_into_view(key.clone())); + rt.frame(1.0 / 120.0); + let viewport = rt.elements().into_iter().find(|e| e.path == "#0/scroll").unwrap().rect; + let (_, row) = visible(&rt).into_iter().find(|(k, _)| *k == key).expect("revealed"); + assert!(row[3] > 90.0, "taller than the 72-point estimate: {row:?}"); + assert!(row[1] >= viewport[1] - 0.5 && row[1] + row[3] <= viewport[1] + viewport[3] + 0.5, "{row:?} in {viewport:?}"); +} + +/// Rows shown last commit that the first measurement pass leaves out and a retry brings +/// back keep their memos and stay mounted, and a retry mounts its full overscan. +#[test] +fn a_retry_pass_keeps_what_the_last_commit_showed() { + let mut rt = fixed(1000); + rt.wheel(150.0, 250.0, -10_000.0); + until_idle(&mut rt); + assert_eq!(rt.commit.virtuals()["#0/scroll/rows"].range, 180..230); + // Too small a step to move the window. + rt.wheel(150.0, 250.0, -100.0); + rt.frame(1.0 / 120.0); + assert_eq!(rt.commit.virtuals()["#0/scroll/rows"].range, 180..230); + built(); + // The first pass, at 10,100, leaves out rows 180 and 181. The rows it mounts collapse, + // which moves the reader's row up and leaves the viewport short, so a retry mounts from + // row 162 down, 180 and 181 among them. + for h in &mut rt.state[182..232] { *h = 1; } + commit(&mut rt); + let v = &rt.commit.virtuals()["#0/scroll/rows"]; + assert_eq!(v.range.start, 162, "a retry isn't held to the per-frame budget"); + let now = built(); + assert!(!now.contains(&180) && !now.contains(&181), "their memos stay: {now:?}"); + assert!(now.len() < 120, "built {} rows", now.len()); + assert!(!rt.commit.virtual_culled().iter().any(|p| p.ends_with("/r180") || p.ends_with("/r181")), "{:?}", rt.commit.virtual_culled()); +} + +#[test] +fn an_idle_window_mounts_all_its_overscan() { + let mut rt = fixed(1000); + assert_eq!(rt.commit.virtuals()["#0/scroll/rows"].range, 0..15, "the first commit mounts the viewport and half a viewport"); + until_idle(&mut rt); + assert_eq!(rt.commit.virtuals()["#0/scroll/rows"].range, 0..30, "then the full overscan"); + rt.wheel(150.0, 250.0, -10_000.0); + let frames = until_idle(&mut rt); + assert_eq!(rt.commit.virtuals()["#0/scroll/rows"].range, 180..230, "after {frames} frames"); + assert!(!rt.frame(1.0 / 120.0), "then it rests"); +} + +/// A launcher's emoji grid: `s.1` rows of 74.4 points under a 100-point header and above a +/// 50-point footer in a 500-point window, so the viewport is 350 points, under five rows. +/// `s.0` shows the grid; until then the body is a label. +fn grid_view(s: &(bool, usize), _: &mut Cx<(bool, usize)>) -> El { + let body = if s.0 { + col().key("scroll").w_full().grow(1.0).min_h(0.0).scroll(ScrollSpec { stick_bottom: false }).child(grid_rows::<(bool, usize)>(s.1, 74.4)) + } else { + text("root").key("root") + }; + col().w_full().h_full().children([el().key("header").w_full().h(100.0), body, el().key("footer").w_full().h(50.0)]) +} + +/// `n` index-built rows `g{i}` that lay out at 74.4 points, estimated at `estimate`. +fn grid_rows<S: 'static>(n: usize, estimate: f32) -> El { + col().key("rows").w_full().growth(GrowthSpec::default()).virtual_rows(n, estimate, + |_: &S, i| format!("g{i}").into(), + |_: &S, i| { + if i == 0 { PASSES.set(PASSES.get() + 1) } + memo(format!("g{i}"), 0, || { + BUILT.with_borrow_mut(|b| b.push(i)); + el().w_full().h(74.4) + }) + }) +} + +/// The viewport's rows: none missing between its top and bottom. +fn assert_covered<S: 'static>(rt: &Runtime<S>, step: &str) { + let viewport = rt.elements().into_iter().find(|e| e.path == "#0/scroll").expect("scroll").rect; + let mut rows: Vec<_> = visible(rt).into_iter().map(|(_, r)| (r[1], r[1] + r[3])).collect(); + rows.sort_by(|a, b| a.0.total_cmp(&b.0)); + let mut y = viewport[1]; + for (top, bottom) in rows { + assert!(top <= y + 0.5, "{step}: blank from {y} to {top} in {viewport:?}"); + y = y.max(bottom); + } + assert!(y >= viewport[1] + viewport[3] - 0.5, "{step}: blank below {y} in {viewport:?}"); +} + +#[test] +fn a_first_showing_builds_its_viewport_not_the_window_times_overscan() { + let mut rt = Runtime::new((false, 20), grid_view, (300.0, 500.0), Env::new(true, 1.0)); + rt.frame(0.0); + built(); + rt.update(|s, _| s.0 = true); + rt.frame(1.0 / 120.0); + assert_covered(&rt, "first showing"); + let first = built(); + // The viewport's rows and half a viewport of overscan, from its 350 points, not the + // window's 500 times the full overscan. + assert_eq!(first, (0..8).collect::<Vec<_>>()); + // The rows' entrance outlasts the fill; the overscan fills within a few frames of it. + for frame in 1..=6 { + rt.frame(1.0 / 120.0); + assert_covered(&rt, &format!("frame {frame}")); + } + assert_eq!(rt.commit.virtuals()["#0/scroll/rows"].range, 0..14, "then rows until its edge is 1.75 viewports away"); + assert_eq!(built(), (8..14).collect::<Vec<_>>(), "building only rows new to it"); +} + +/// A header that takes less than its height (a negative margin) makes the first showing's +/// estimate short, 90 points of a 430-point viewport; one retry, measuring the viewport, +/// fills it before anything is presented. +#[test] +fn a_first_showing_estimated_short_still_fills_its_viewport() { + fn view(s: &(bool, usize), cx: &mut Cx<(bool, usize)>) -> El { + let mut root = grid_view(s, cx); + root.children[0] = el().key("header").w_full().h(360.0).mb(-340.0); + root + } + let mut rt = Runtime::new((false, 20), view, (300.0, 500.0), Env::new(true, 1.0)); + rt.frame(0.0); + rt.update(|s, _| s.0 = true); + PASSES.set(0); + rt.frame(1.0 / 120.0); + assert_covered(&rt, "first showing"); + assert_eq!(rt.elements().into_iter().find(|e| e.path == "#0/scroll").unwrap().rect[3], 430.0); + assert_eq!(PASSES.get(), 2, "the estimate's pass and one retry"); + assert!(rt.commit.virtuals()["#0/scroll/rows"].range.end < 20, "not every row"); +} + +/// A window that fits its content has no height to bound its root: a results list opening +/// under a 56-point search bar estimates its viewport from its own `max_h`. +#[test] +fn a_first_showing_in_a_window_that_fits_its_content_estimates_from_max_h() { + fn view(s: &bool, _: &mut Cx<bool>) -> El { + let results = s.then(|| col().key("scroll").w_full().max_h(350.0).scroll(ScrollSpec { stick_bottom: false }) + .child(grid_rows::<bool>(20, 74.4))); + col().w_full().child(el().key("search").w_full().h(56.0)).children(results) + } + let mut rt = Runtime::new(false, view, (300.0, 500.0), Env::new(true, 1.0)); + rt.host.fit_height = true; + let height = rt.content_height(); + rt.set_viewport((300.0, height), 1.0); + rt.frame(0.0); + assert_eq!(rt.viewport.1, 56.0); + rt.update(|s, _| *s = true); + PASSES.set(0); + rt.frame(1.0 / 120.0); + assert_eq!(PASSES.get(), 1, "measured once"); + assert_eq!(rt.commit.virtuals()["#0/scroll/rows"].range, 0..8, "350 points' rows and the overscan budget"); +} + +/// An out-of-flow popover isn't bounded by the 32-point header it hangs from, only by its +/// own `max_h`. +#[test] +fn a_first_showing_in_an_absolute_popover_estimates_from_its_own_max_h() { + fn view(s: &bool, _: &mut Cx<bool>) -> El { + let popover = s.then(|| col().key("scroll").absolute(0.0, 32.0).w_full().max_h(300.0) + .scroll(ScrollSpec { stick_bottom: false }).child(grid_rows::<bool>(20, 74.4))); + col().w_full().h_full().child(el().key("header").w_full().h(32.0).children(popover)) + } + let mut rt = Runtime::new(false, view, (300.0, 500.0), Env::new(true, 1.0)); + rt.frame(0.0); + rt.update(|s, _| *s = true); + PASSES.set(0); + rt.frame(1.0 / 120.0); + assert_eq!(PASSES.get(), 1, "measured once"); + assert_eq!(rt.commit.virtuals()["#0/header/scroll/rows"].range, 0..8, "300 points' rows and the overscan budget"); +} + +/// Rows estimated short of their height: revealing the last on the first showing measures +/// the rows it mounts on the way, and lands it in view against the end they make. +#[test] +fn a_first_showing_reveals_its_last_row_taller_than_estimated() { + fn view(s: &(bool, usize), cx: &mut Cx<(bool, usize)>) -> El { + let mut root = grid_view(s, cx); + if s.0 { root.children[1].children[0] = grid_rows::<(bool, usize)>(s.1, 50.0) } + root + } + let mut rt = Runtime::new((false, 20), view, (300.0, 500.0), Env::new(true, 1.0)); + rt.frame(0.0); + rt.update(|s, tx| { s.0 = true; tx.scroll_into_view("g19") }); + rt.frame(1.0 / 120.0); + let viewport = rt.elements().into_iter().find(|e| e.path == "#0/scroll").unwrap().rect; + let (_, row) = visible(&rt).into_iter().find(|(k, _)| k == "g19").expect("g19 mounted"); + assert!(row[1] >= viewport[1] - 0.5 && row[1] + row[3] <= viewport[1] + viewport[3] + 0.5, "{row:?} in {viewport:?}"); + assert_covered(&rt, "revealed"); +} + +#[test] +fn a_first_showing_reveals_a_row_below_its_first_window() { + let mut rt = Runtime::new((false, 20), grid_view, (300.0, 500.0), Env::new(true, 1.0)); + rt.frame(0.0); + rt.update(|s, tx| { s.0 = true; tx.scroll_into_view("g16") }); + rt.frame(1.0 / 120.0); + assert_covered(&rt, "revealed"); + let viewport = rt.elements().into_iter().find(|e| e.path == "#0/scroll").unwrap().rect; + let (_, row) = visible(&rt).into_iter().find(|(k, _)| k == "g16").expect("revealed in the first frame"); + assert!(row[1] >= viewport[1] - 0.5 && row[1] + row[3] <= viewport[1] + viewport[3] + 0.5, "{row:?} in {viewport:?}"); +} + +#[test] +fn tooling_records_duplicate_keys_inside_a_row() { + fn view(s: &usize, _: &mut Cx<usize>) -> El { + col().key("scroll").size(200.0, 200.0).scroll(ScrollSpec { stick_bottom: false }).child( + col().key("rows").w_full().growth(GrowthSpec::default()).virtual_rows(*s, 40.0, + |_: &usize, i| format!("r{i}").into(), + |_: &usize, i| col().child(el().key("a").h(20.0)).child(el().key(if i == 1 { "a" } else { "b" }).h(20.0)))) + } + let mut rt = Runtime::new(4, view, (200.0, 200.0), Env::new(true, 1.0)); + rt.commit.enable_key_warnings(); + rt.frame(0.0); + let warnings = rt.commit.key_warnings().unwrap(); + assert_eq!(warnings.len(), 1, "{warnings:?}"); + assert!(warnings[0].contains("duplicate sibling key \"a\" under \"scroll/rows/r1\""), "{warnings:?}"); + let mut rt = Runtime::new(4, view, (200.0, 200.0), Env::new(true, 1.0)); + rt.frame(0.0); + assert!(rt.elements().iter().any(|e| e.key.as_deref() == Some("a#dup1")), "the row lays out with the duplicate renamed"); +} + +#[test] +fn duplicate_row_keys_are_renamed_instead_of_panicking() { + fn view(indexed: &bool, _: &mut Cx<bool>) -> El { + let rows = col().key("rows").w_full().growth(GrowthSpec::default()); + let rows = if *indexed { + rows.virtual_rows(3, 40.0, |_: &bool, _| "dup".into(), |_: &bool, _| el().h(20.0)) + } else { + rows.children((0..3).map(|_| el().key("dup").h(20.0))).virtualize(40.0) + }; + col().key("scroll").size(200.0, 200.0).scroll(ScrollSpec { stick_bottom: false }).child(rows) + } + for indexed in [true, false] { + let mut rt = Runtime::new(indexed, view, (200.0, 200.0), Env::new(true, 1.0)); + rt.commit.enable_key_warnings(); + rt.frame(0.0); + rt.frame(1.0); + let keys: Vec<_> = rt.elements().into_iter().filter_map(|e| e.key).filter(|k| k.starts_with("dup")).collect(); + assert_eq!(keys, ["dup", "dup#dup1", "dup#dup2"], "indexed {indexed}"); + let warnings = rt.commit.key_warnings().unwrap(); + assert!(warnings.iter().any(|w| w.contains("duplicate virtual row key \"dup\" under \"scroll/rows\"")), "{warnings:?}"); + } +} + +/// A row holding an `aspect_fit` element measures at its fitted height, so rows below it sit +/// where the second layout pass put it. +#[test] +fn rows_measure_an_aspect_fit_element_at_its_fitted_size() { + fn view(s: &usize, _: &mut Cx<usize>) -> El { + col().w_full().h_full().child( + col().key("scroll").w_full().grow(1.0).scroll(ScrollSpec { stick_bottom: false }).child( + col().key("rows").w_full().growth(GrowthSpec::default()).virtual_rows(*s, 50.0, + |_: &usize, i| format!("r{i}").into(), + |_: &usize, _| col().w_full().child(el().key("pic").max_h(80.0).aspect_fit(2.0))))) + } + let mut rt = Runtime::new(20, view, (300.0, 500.0), Env::new(true, 1.0)); + rt.frame(0.0); + until_idle(&mut rt); + let rects: Vec<_> = rt.elements().into_iter().filter(|e| e.visible[3] > 0.0).map(|e| (e.path, e.rect)).collect(); + for i in 0..6 { + let pic = rects.iter().find(|(p, _)| *p == format!("#0/scroll/rows/r{i}/pic")).expect("built").1; + assert_eq!(pic, [0.0, i as f32 * 80.0, 160.0, 80.0], "r{i}"); + } + assert_eq!(rt.commit.virtuals()["#0/scroll/rows"].height("r3"), 80.0); +} + +#[test] +fn heights_persist_for_rows_scrolled_away() { + let mut rt = chat(800, true, Mode::Index); + let key = rt.state.keys[795].clone(); + let measured = visible(&rt).into_iter().find(|(k, _)| *k == key).expect("near the tail").1[3]; + assert!((measured - 72.0).abs() > 1.0, "a markdown row isn't the estimate: {measured}"); + for _ in 0..10 { + rt.wheel(300.0, 400.0, 2000.0); + rt.frame(1.0 / 120.0); + } + assert!(rt.find(&key).is_none(), "scrolled away, unbuilt"); + let v = &rt.commit.virtuals()["#0/scroll/rows"]; + assert_eq!(v.height(&key), measured, "its height stays measured"); + assert_eq!(v.height(&rt.state.keys[400]), 72.0, "a row never seen is estimated"); +} + +#[test] +fn a_focused_field_in_a_row_scrolled_out_keeps_typing() { + use crate::{Key, KeyEvent, TextEdit, TextStyle, text_input}; + fn view(s: &Vec<TextEdit>, _: &mut Cx<Vec<TextEdit>>) -> El { + col().key("viewport").size(200.0, 200.0).scroll(ScrollSpec { stick_bottom: false }).clip_soft(0.0) + .child(col().key("rows").w_full().growth(GrowthSpec::default()).virtual_rows(s.len(), 40.0, + // A `/` in a key doesn't lose the row. + |_: &Vec<TextEdit>, i| format!("row/{i}").into(), + |s: &Vec<TextEdit>, i| col().size(200.0, 40.0).child(text_input(&s[i], TextStyle::new(14.0, 400.0)).key("field") + .size(200.0, 40.0).on_edit(move |s: &mut Vec<TextEdit>| &mut s[i])))) + } + let mut state: Vec<_> = (0..1000).map(|_| TextEdit::new("")).collect(); + state[0].focused = true; + let mut rt = Runtime::new(state, view, (200.0, 200.0), Env::new(true, 1.0)); + rt.frame(0.0); + rt.wheel(100.0, 100.0, -20_000.0); + rt.frame(0.0); + assert!(rt.find("row/0/field").is_none(), "the focused row scrolled out"); + rt.key(KeyEvent { key: Key::Text("offscreen".into()), mods: Default::default() }); + rt.frame(0.0); + assert_eq!(rt.state[0].text, "offscreen"); + assert!(rt.state[0].focused); + rt.wheel(100.0, 100.0, 20_000.0); + rt.frame(0.0); + assert!(rt.find("row/0/field").is_some(), "back in view"); +} + +#[test] +fn a_version_skips_checking_every_key_until_it_changes() { + thread_local! { static KEYS: Cell<usize> = const { Cell::new(0) }; } + // (tick, version, key prefix, count) + type S = (u32, u32, &'static str, usize); + fn view(s: &S, _: &mut Cx<S>) -> El { + col().key("scroll").w_full().h_full().scroll(ScrollSpec { stick_bottom: false }).child( + col().key("rows").w_full().growth(GrowthSpec::default()) + .virtual_rows(s.3, 20.0, + |s: &S, i| { + KEYS.set(KEYS.get() + 1); + format!("{}{i}", s.2).into() + }, + |s: &S, i| text(format!("{} {i}", s.0)).h(20.0)) + .virtual_rows_version(s.1)) + } + let mut rt = Runtime::new((0, 0, "a", 10_000), view, (300.0, 400.0), Env::default()); + rt.frame(0.0); + KEYS.set(0); + rt.state.0 += 1; + rt.invalidate(); + rt.frame(1.0 / 60.0); + assert!(KEYS.get() < 1000, "the same version checks no keys: {}", KEYS.get()); + assert!(rt.find("a0").is_some()); + rt.state.2 = "b"; + rt.state.1 += 1; + rt.invalidate(); + rt.frame(1.0 / 60.0); + assert!(rt.find("b0").is_some() && rt.find("a0").is_none(), "a new version takes the new keys"); + // Changing the row count refreshes keys even if the caller forgot to bump `version`. + rt.state.2 = "c"; + rt.state.3 = 10_001; + rt.invalidate(); + rt.frame(1.0 / 60.0); + assert!(rt.find("c0").is_some() && rt.find("b0").is_none(), "a count change refreshes keys without a version bump"); +} + +#[test] +fn visible_rows_reports_range_without_committing_when_unchanged() { + // (visible range, commit on change) + type S = (std::ops::Range<usize>, bool); + fn view(_: &S, _: &mut Cx<S>) -> El { + col().key("scroll").w_full().h_full().scroll(ScrollSpec { stick_bottom: false }).child( + col().key("rows").w_full().growth(GrowthSpec::default()) + .virtual_rows(1_000, 20.0, + |_: &S, i| format!("r{i}").into(), + |_: &S, i| text(format!("row {i}")).h(20.0)) + .virtual_rows_version(0u32) + .on_visible_rows(|s: &mut S, r| { + s.0 = r; + s.1 + })) + } + let mut rt = Runtime::new((0..0, false), view, (300.0, 200.0), Env::default()); + for _ in 0..6 { + rt.frame(1.0 / 60.0); + } + assert_eq!(rt.state.0, 0..10); + let commits = rt.stats.commits; + // Scrolling within the mounted overscan updates the visible range without re-running the view. + rt.wheel(150.0, 100.0, -40.0); + rt.frame(1.0 / 60.0); + assert_eq!(rt.state.0, 2..12); + assert_eq!(rt.stats.commits, commits, "returning false from on_visible_rows skips a commit"); + // Returning true triggers a commit when the visible range changes. + rt.state.1 = true; + rt.wheel(150.0, 100.0, -40.0); + rt.frame(1.0 / 60.0); + assert_eq!(rt.state.0, 4..14); + assert_eq!(rt.stats.commits, commits + 1, "returning true commits"); +} + +#[test] +fn culled_rows_unmount_their_whole_subtree_immediately() { + fn view(_: &(), _: &mut Cx<()>) -> El { + col().key("scroll").w_full().h_full().scroll(ScrollSpec { stick_bottom: false }).child( + col().key("rows").w_full().growth(GrowthSpec::default()) + .virtual_rows(500, 20.0, + |_: &(), i| format!("r{i}").into(), + |_: &(), i| col().h(20.0).child(col().key("cell").child(text(format!("row {i}")).key("txt"))))) + } + let mut rt = Runtime::new((), view, (300.0, 200.0), Env::default()); + for _ in 0..6 { + rt.frame(1.0 / 60.0); + } + assert!(rt.tree.nodes.iter().any(|n| n.path.ends_with("/r0/cell/txt"))); + // Scroll far enough down that row 0 leaves the mounted overscan window. + rt.wheel(150.0, 100.0, -2_000.0); + rt.frame(1.0 / 60.0); + assert!( + !rt.tree.nodes.iter().any(|n| n.path.contains("/r0/")), + "culled row descendants are unmounted immediately, not left orphaned in nodes" + ); +} + +#[test] +fn memo_rows_build_once_while_they_stay_in_the_window() { + thread_local! { static BUILDS: Cell<usize> = const { Cell::new(0) }; } + fn view(s: &(u32, u32), _: &mut Cx<(u32, u32)>) -> El { + col().w_full().h_full().children([ + text(format!("tick {}", s.0)).key("counter"), + col().key("scroll").w_full().grow(1.0).scroll(ScrollSpec { stick_bottom: true }).child( + col().key("rows").w_full().growth(GrowthSpec::default()).virtual_rows(s.1 as usize, 40.0, + |_: &(u32, u32), i| format!("r{i}").into(), + |_: &(u32, u32), i| memo(format!("r{i}"), 0, || { + BUILDS.set(BUILDS.get() + 1); + text(format!("row {i}")).h(40.0) + }))), + ]) + } + let mut rt = Runtime::new((0, 2000), view, (300.0, 400.0), Env::default()); + rt.frame(0.0); + let first = BUILDS.get(); + assert!(first > 0 && first < 60, "{first}"); + for _ in 0..10 { + rt.state.0 += 1; + rt.invalidate(); + rt.frame(1.0 / 60.0); + } + assert_eq!(BUILDS.get(), first, "ticks reuse every mounted row"); + rt.state.1 += 1; + rt.invalidate(); + rt.frame(1.0 / 60.0); + assert!(rt.find("r2000").is_some(), "an appended row mounts at the pinned tail"); + assert_eq!(BUILDS.get(), first + 1, "and only it builds"); +} + +/// `cargo test -p rune --profile perf --lib virtual_rows_time -- --ignored --nocapture` +#[test] +#[ignore] +fn virtual_rows_time() { + for mode in [Mode::Memo, Mode::Index] { + let name = if mode == Mode::Memo { "memo " } else { "index" }; + for n in [500, 2000, 5000] { + let mut rt = chat(n, false, mode); + for _ in 0..30 { + rt.state.tick += 1; + commit(&mut rt); + } + let frames = 300; + VIEW_NS.set(0); + let start = crate::time::now(); + for _ in 0..frames { + rt.state.tick += 1; + commit(&mut rt); + } + let per = start.elapsed().as_secs_f64() * 1e6 / f64::from(frames); + let view = VIEW_NS.get() as f64 / 1e3 / f64::from(frames); + println!("{name} tick rows {n:5}: {per:8.1} µs per frame ({view:7.1} µs in the view)"); + } + + // Older messages load at the top while the reader is there. + for _ in 0..3 { + let mut rt = chat(3700, true, mode); + for _ in 0..10 { + rt.wheel(300.0, 400.0, 100_000.0); + rt.frame(1.0 / 120.0); + } + let (views, shaped) = (VIEWS.get(), rt.text.shaped); + VIEW_NS.set(0); + let first = rt.state.ids[0]; + rt.state.splice(0, first - 60..first); + let start = crate::time::now(); + commit(&mut rt); + let ms = start.elapsed().as_secs_f64() * 1e3; + // An index-built list mounts the rest of the page above over the next frames. + let mut after = 0.0f64; + for _ in 0..30 { + let start = crate::time::now(); + rt.frame(1.0 / 120.0); + after = after.max(start.elapsed().as_secs_f64() * 1e3); + } + println!("{name} prepend 60 to 3700: {ms:6.2} ms, {} view runs ({:.2} ms), {} shaped, {} nodes; slowest frame after {after:.2} ms", + VIEWS.get() - views, VIEW_NS.get() as f64 / 1e6, rt.text.shaped - shaped, rt.tree.nodes.len()); + } + + // Reading up through history: which frames are slow, and do they shape? + let mut rt = chat(3700, true, mode); + let mut slow = Vec::new(); + let mut times = Vec::new(); + for f in 0..400 { + rt.wheel(300.0, 400.0, 30.0); + let (shaped, commits, views) = (rt.text.shaped, rt.stats.commits, VIEWS.get()); + VIEW_NS.set(0); + let start = crate::time::now(); + rt.frame(1.0 / 120.0); + let us = start.elapsed().as_secs_f64() * 1e6; + times.push(us); + if us > 1000.0 { + slow.push(format!("f{f}: {us:.0} µs, {} commits, {} views ({:.0} µs), {} shaped", + rt.stats.commits - commits, VIEWS.get() - views, VIEW_NS.get() as f64 / 1e3, rt.text.shaped - shaped)); + } + } + times.sort_by(f64::total_cmp); + println!("{name} scroll 400 frames: p50 {:.0} µs, p90 {:.0} µs, max {:.0} µs; {} over 1 ms:", times[200], times[360], times[399], slow.len()); + for s in slow.iter().take(6) { println!(" {s}"); } + } +} diff --git a/app/vendor/rune/crates/rune/src/el/visual.rs b/app/vendor/rune/crates/rune/src/el/visual.rs new file mode 100644 index 0000000..80ee2e7 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/el/visual.rs @@ -0,0 +1,378 @@ +//! `Visual`: hot inline paint fields on `El` and `Node`, with rarely set extras behind `Cold`. +use std::ops::Deref; +use std::rc::Rc; + +use rune_motion::{Anim, Transition}; + +use crate::cold::{Cold, Empty}; +use crate::color::Color; +use crate::el::{Outline, RadialGradient, Shadow}; +use crate::shape::Shape; +use crate::text::Icon; + +/// Rarely set visual extras shared behind `Cold<VisualCold>` so common boxes and text pay 8 bytes. +#[doc(hidden)] +#[derive(Clone, Debug)] +pub struct VisualCold { + pub surface: Option<(crate::NativeSurface, crate::SurfaceFit)>, + /// Where a surface or `pixels_fit` image sits in the rect (`El::surface_anchor`, `El::surface_unscaled`). + pub(crate) surface_place: crate::native_surface::place::SurfacePlace, + /// Bottom colour of a vertical border gradient whose top is `border` (`El::border_gradient`). + pub border_bottom: Option<Color>, + /// Per-side border widths `[top, right, bottom, left]` in points (`El::border_sides`). + pub(crate) border_sides: Option<[f32; 4]>, + /// The border takes room in layout, snapped to device pixels (`El::border_layout`). + pub(crate) border_layout: bool, + /// Dash and gap lengths of a dashed border, in points (`El::border_dash`). + pub border_dash: Option<[f32; 2]>, + /// Points into the dash pattern where it starts (`El::border_dash_phase`). + pub border_dash_phase: f32, + pub shadows: Vec<Shadow>, + pub blur_motion: Option<Box<Anim>>, + /// Soft clip of children to this rect: fade widths left, top, right, bottom. A negative + /// width ramps linearly (`El::clip_fade_linear`). + pub clip: Option<[f32; 4]>, + /// Rounded clip of this element and its subtree, applied after subtree filters. + pub clip_radius: Option<f32>, + /// Per-corner clip radii override (`[tl, tr, br, bl]`, in points). + pub(crate) clip_corners: Option<[f32; 4]>, + /// A round hole through this element and its subtree (`El::cutout_circle`): centre x and y + /// from the element's top-left, and the radii it's clear within and whole from, in points. + pub(crate) cutout: Option<[f32; 4]>, + pub icon: Option<(&'static Icon, Color)>, + /// The icon's colour came from `El::color`; without it the icon takes the window's + /// foreground (`Cx::foreground`) when the view sets one. + pub(crate) icon_inked: bool, + /// A colour icon draws as its silhouette in the icon's colour (`El::icon_one_color`). + pub(crate) icon_one_color: bool, + /// Vertical linear gradient (top, bottom) painted over the fill, under hover/press overlays. + pub gradient: Option<Box<[Color; 2]>>, + /// Radial or angled linear gradient painted over the fill, under hover/press overlays. + pub(crate) radial: Option<Box<RadialGradient>>, + pub outline: Option<Outline>, + /// Vector strokes and fills in the element's own points, over the fill. + pub shape: Option<Rc<Shape>>, + /// A terminal's cell grid (`grid`), painted over the fill. + pub(crate) grid: Option<Rc<crate::el::grid::Grid>>, + /// An RGBA image scaled into the element's rect, over the fill and shape. + pub pixels: Option<crate::pixels::Pixels>, + /// How `pixels` keeps its aspect ratio; `None` stretches it to the rect. + pub pixels_fit: Option<crate::SurfaceFit>, + /// An effect slot (`El::effect`). + pub(crate) effect: Option<crate::el::effect::EffectSlot>, + /// Backdrop blur standard deviation in points (`El::backdrop_blur`); 0 is off. + pub(crate) backdrop_blur: f32, + /// The hover track's enter and exit curves (default: snappy spring both ways). + pub hover_motion: Option<Rc<(Anim, Anim)>>, + /// Hover curves for this element and the hover tracks below it without their own. + pub(crate) hover_within: Option<Rc<(Anim, Anim)>>, + /// Opacity factor (rest, hovered) following the nearest ancestor group's hover. + pub group_opacity: Option<[f32; 2]>, + /// Text or icon colour while the nearest ancestor group is hovered. + pub group_color: Option<Color>, + /// `El::hover_alone`: while the pointer is on this element, the hover tracks of the + /// elements it sits inside stay off. + pub hover_alone: bool, + /// `El::hover_group_shared`: the key of the elements whose hover this group shares. + pub(crate) hover_share: Option<Rc<str>>, + /// `El::icon_rotation`: the icon's turn in radians, clockwise. + pub(crate) icon_turn: f32, + /// Optional app-supplied key mixed into the cached subtree's signature (`El::cache_key`). + pub(crate) cache_key: Option<u64>, + pub(crate) offset_motion: Option<Box<Anim>>, + /// The curve `El::scale` changes on. + pub(crate) scale_motion: Option<Box<Anim>>, + /// `El::origin`: the unit point scale and rotation pivot about; `None` is the centre. + pub(crate) origin: Option<[f32; 2]>, + /// The curve `El::rotate` changes on. + pub(crate) rotate_motion: Option<Box<Anim>>, + /// `El::child_exit`: how children removed in a commit leave, in place of their own. + pub(crate) child_exit: Option<Box<Transition>>, + /// `El::enter_delay`: seconds a new element holds its insertion effect before entering. + pub(crate) enter_delay: f32, + /// `El::motion_intent`: authored motion traits inherited by this subtree. + pub(crate) motion_intent: crate::el::motion::MotionIntent, + /// `El::motion(Spring::NONE)` written on this element itself, not inherited or from a + /// token: what that spring governs here lands at once by design. + pub(crate) instant_motion: bool, + /// A scroll area's wrapper (`El::wrap_scroll_area`): rectangular clips and fades set on it + /// go to its first child, the viewport, so what it draws beside that stays whole. + pub(crate) clip_to_content: bool, + /// `El::matched_crop`: a matched flight keeps the content at its own size, cropped. + pub(crate) flight_crop: bool, + /// `El::hold_landing_width`: an animated width change lands its contents and slides them. + pub(crate) hold_landing: bool, + pub(crate) row_face: Option<&'static str>, + /// `El::press_color`: its text and icons' colour while a press on it is held. + pub(crate) press_color: Option<Color>, + /// `El::paint_contained`: the origin (window points) its children snap against. + pub(crate) paint_contain: Option<[f32; 2]>, + /// `El::motion_snaps`: while it moves, it and its subtree snap every frame. + pub(crate) motion_snaps: bool, + /// `El::hairline`: scales its thin axis by half around its midpoint at paint time, matching + /// CSS `height: 1px; transform: scaleY(0.5)` across DPI scales. + pub(crate) hairline: bool, + /// `El::offset`: a visual shift in points. + pub(crate) offset: [f32; 2], + /// Static alpha of this element's own paint; never inherited or isolated. + pub paint_alpha: f32, + /// `El::layer_opacity`: static alpha its whole subtree composites at, as one layer. + pub(crate) layer_opacity: f32, + pub blur: f32, + /// `El::rotate`, in radians clockwise. + pub(crate) rotate: f32, + /// App-defined tag a compositor reads per instance (`Runtime::marks`); 0 inherits the parent's. + pub mark: u32, + /// `El::mirror_in_rtl`: its icon flips left to right in a right-to-left element. + pub(crate) mirror_rtl: bool, + /// `El::paint_order`: where it paints among its siblings; 0 is tree order. + pub(crate) paint_order: i16, +} + +impl Empty for VisualCold { + const EMPTY: &'static Self = &VisualCold { + surface: None, + surface_place: crate::native_surface::place::SurfacePlace::CENTRED, + border_bottom: None, + border_sides: None, + border_layout: false, + border_dash: None, + border_dash_phase: 0.0, + shadows: Vec::new(), + blur_motion: None, + clip: None, + clip_radius: None, + clip_corners: None, + cutout: None, + icon: None, + icon_inked: false, + icon_one_color: false, + gradient: None, + radial: None, + outline: None, + shape: None, + grid: None, + pixels: None, + pixels_fit: None, + effect: None, + backdrop_blur: 0.0, + hover_motion: None, + hover_within: None, + group_opacity: None, + group_color: None, + hover_alone: false, + hover_share: None, + icon_turn: 0.0, + cache_key: None, + offset_motion: None, + scale_motion: None, + origin: None, + rotate_motion: None, + child_exit: None, + enter_delay: 0.0, + motion_intent: crate::el::motion::MotionIntent::NONE, + instant_motion: false, + clip_to_content: false, + flight_crop: false, + hold_landing: false, + row_face: None, + press_color: None, + paint_contain: None, + motion_snaps: false, + hairline: false, + offset: [0.0; 2], + paint_alpha: 1.0, + layer_opacity: 1.0, + blur: 0.0, + rotate: 0.0, + mark: 0, + mirror_rtl: false, + paint_order: 0, + }; +} + +/// Border, hover and press colours and per-corner radii: interactive boxes set them, most +/// boxes don't, so they wait behind `Cold<VisualBox>`. +#[derive(Clone, Debug, PartialEq)] +pub(crate) struct VisualBox { + pub(crate) border: Color, + pub(crate) hover: Color, + pub(crate) press: Color, + /// Per-corner radii `[tl, tr, br, bl]`, read when `Visual::radius` is NaN. + pub(crate) corners: [f32; 4], + pub(crate) border_width: f32, +} + +impl Empty for VisualBox { + const EMPTY: &'static Self = &VisualBox { + border: Color::TRANSPARENT, + hover: Color::TRANSPARENT, + press: Color::TRANSPARENT, + corners: [0.0; 4], + border_width: 0.0, + }; +} + +/// The paint fields every box may set; the rest wait behind `box_paint` and `cold`. +#[derive(Clone, Debug)] +pub struct Visual { + pub fill: Color, + /// The corner radius; NaN when the corners differ, which `box_paint.corners` then holds. + pub(crate) radius: f32, + pub opacity: f32, + pub(crate) box_paint: Cold<VisualBox>, + pub(crate) cold: Cold<VisualCold>, +} + +impl Visual { + #[inline] + pub(crate) fn cold_mut(&mut self) -> &mut VisualCold { + &mut self.cold + } + + #[inline] + pub(crate) fn box_paint_mut(&mut self) -> &mut VisualBox { + &mut self.box_paint + } + + /// The corner radii `[tl, tr, br, bl]`. + #[inline] + pub(crate) fn radii(&self) -> [f32; 4] { + if self.radius.is_nan() { self.box_paint.corners } else { [self.radius; 4] } + } + + /// Sets the corner radii, inline when they're all the same. + #[inline] + pub(crate) fn set_radii(&mut self, r: [f32; 4]) { + if r == [r[0]; 4] { + self.radius = r[0]; + } else { + self.radius = f32::NAN; + self.box_paint_mut().corners = r; + } + } + + #[inline] + pub(crate) fn border(&self) -> Color { + self.box_paint.border + } + + #[inline] + pub(crate) fn border_width(&self) -> f32 { + self.box_paint.border_width + } + + #[inline] + pub(crate) fn hover(&self) -> Color { + self.box_paint.hover + } + + #[inline] + pub(crate) fn press(&self) -> Color { + self.box_paint.press + } + + /// Sets the hover colour, allocating `box_paint` only for one that isn't the default. + #[inline] + pub(crate) fn set_hover(&mut self, c: Color) { + if c != Color::TRANSPARENT || !self.box_paint.is_empty() { + self.box_paint_mut().hover = c; + } + } + + /// Sets the press colour, allocating `box_paint` only for one that isn't the default. + #[inline] + pub(crate) fn set_press(&mut self, c: Color) { + if c != Color::TRANSPARENT || !self.box_paint.is_empty() { + self.box_paint_mut().press = c; + } + } + + /// Sets the border's colour alone, allocating `box_paint` only for a change. + #[inline] + pub(crate) fn set_border_color(&mut self, c: Color) { + if c != self.box_paint.border { + self.box_paint_mut().border = c; + } + } + + /// Sets the border, allocating `box_paint` only for one that isn't the default. + #[inline] + pub(crate) fn set_border(&mut self, width: f32, c: Color) { + if width != 0.0 || c != Color::TRANSPARENT || !self.box_paint.is_empty() { + let b = self.box_paint_mut(); + b.border_width = width; + b.border = c; + } + } +} + +impl Deref for Visual { + type Target = VisualCold; + #[inline(always)] + fn deref(&self) -> &VisualCold { + &self.cold + } +} + +impl Default for Visual { + #[inline] + fn default() -> Self { + Visual { fill: Color::TRANSPARENT, radius: 0.0, opacity: 1.0, box_paint: Cold::NONE, cold: Cold::NONE } + } +} + +/// `Visual`'s flags, one bit each, kept beside it on `El` and `Node`. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(crate) struct VisualFlags(u8); + +impl VisualFlags { + /// Rectangular native input region for overlays using `OverlayInput::Regions`. + pub(crate) const HIT: u8 = 1; + /// Corners follow Apple's continuous curve instead of circular arcs (`El::continuous_corners`). + pub(crate) const CONTINUOUS_CORNERS: u8 = 1 << 1; + /// Composites with `Blend::PlusLighter` (`El::plus_lighter`). + pub(crate) const PLUS_LIGHTER: u8 = 1 << 2; + /// Tracks hover for its descendants' `group_*` styles even without a hover colour. Any + /// element with a hover colour is a group too. + pub(crate) const HOVER_GROUP: u8 = 1 << 3; + /// Rasterize this subtree once into an offscreen texture when settled (`El::cache`). + pub(crate) const CACHE: u8 = 1 << 4; + /// `El::raise`: paints and takes input above the rest of the window. + pub(crate) const RAISE: u8 = 1 << 5; + /// `El::pixel_snap(false)`: this subtree paints at its exact fractional rects. + pub(crate) const NO_PIXEL_SNAP: u8 = 1 << 6; + /// `El::ride_trailing`: x holds against the parent's trailing edge while its width moves. + pub(crate) const RIDE_TRAILING: u8 = 1 << 7; + + #[inline(always)] + pub(crate) fn set(&mut self, bit: u8, on: bool) { + if on { self.0 |= bit } else { self.0 &= !bit } + } + + #[inline(always)] + pub(crate) fn hit(self) -> bool { self.0 & Self::HIT != 0 } + #[inline(always)] + pub(crate) fn continuous_corners(self) -> bool { self.0 & Self::CONTINUOUS_CORNERS != 0 } + #[inline(always)] + pub(crate) fn blend(self) -> crate::render::Blend { + if self.0 & Self::PLUS_LIGHTER != 0 { crate::render::Blend::PlusLighter } else { crate::render::Blend::SourceOver } + } + #[inline(always)] + pub(crate) fn hover_group(self) -> bool { self.0 & Self::HOVER_GROUP != 0 } + #[inline(always)] + pub(crate) fn cache(self) -> bool { self.0 & Self::CACHE != 0 } + #[inline(always)] + pub(crate) fn raise(self) -> bool { self.0 & Self::RAISE != 0 } + #[inline(always)] + pub(crate) fn no_pixel_snap(self) -> bool { self.0 & Self::NO_PIXEL_SNAP != 0 } + #[inline(always)] + pub(crate) fn ride_trailing(self) -> bool { self.0 & Self::RIDE_TRAILING != 0 } +} + +impl Visual { + /// Whether a press on it shows (an `El::press` overlay or an `El::press_color`). + pub(crate) fn tracks_press(&self) -> bool { + self.press().a > 0.0 || self.cold.get().is_some_and(|c| c.press_color.is_some()) + } +} diff --git a/app/vendor/rune/crates/rune/src/el/visuals.rs b/app/vendor/rune/crates/rune/src/el/visuals.rs new file mode 100644 index 0000000..9ad793b --- /dev/null +++ b/app/vendor/rune/crates/rune/src/el/visuals.rs @@ -0,0 +1,720 @@ +//! Visual builders: fill, corners, borders, shadows, gradients, opacity, blur, transforms, +//! clips and hover groups. + +use super::*; + +impl El { + #[inline] + pub fn fill(mut self, c: Color) -> Self { + self.set_fill(c); + self + } + /// [`El::fill`] in place. + #[inline] + pub fn set_fill(&mut self, c: Color) -> &mut Self { + self.vis.fill = c; + self + } + #[inline] + pub fn radius(mut self, r: f32) -> Self { + self.set_radius(r); + self + } + /// [`El::radius`] in place. + #[inline] + pub fn set_radius(&mut self, r: f32) -> &mut Self { + self.vis.set_radii([r; 4]); + self + } + /// Round the corners with Apple's continuous curve (`CALayerCornerCurve.continuous`, SwiftUI's + /// `.continuous` style), which eases into the straight edges over about 1.53 times the radius + /// instead of meeting them at a circular arc. Applies to the fill, border, image, outline, + /// `clip_rounded` and system material; shadows keep circular corners, like a CALayer + /// shadow from a `CGPath(roundedRect:)`. + pub fn continuous_corners(mut self) -> Self { + self.vis_flags.set(VisualFlags::CONTINUOUS_CORNERS, true); + self + } + /// Per-corner radius: top-left, top-right, bottom-right, bottom-left. + pub fn corners(mut self, r: [f32; 4]) -> Self { + self.vis.set_radii(r); + self + } + /// A ring `width` points wide just inside the border box, following the corner radii, as a + /// CSS `border` draws with `box-sizing: border-box`. It takes no layout space and draws over + /// the fill, which runs under it to the outer edge, so a translucent border on a filled box + /// shows the fill through it, as in CSS. Inset [`Self::box_shadow`]s draw between the two, + /// inside the ring. The width snaps to device pixels as a CSS border's does: under one pixel + /// it draws one, above that it floors to whole pixels. For a ring at its exact fractional + /// width, as CSS `box-shadow: inset 0 0 0 0.5px` draws, use an inset [`Self::box_shadow`] + /// with that spread. + #[inline] + pub fn border(mut self, width: f32, c: Color) -> Self { + self.set_border(width, c); + self + } + /// [`El::border`] in place. + #[inline] + pub fn set_border(&mut self, width: f32, c: Color) -> &mut Self { + self.vis.set_border(width, c); + if let Some(cold) = self.vis.cold.get_mut_if_some() { + cold.border_bottom = None; + cold.border_sides = None; + } + self + } + /// A border with its own width on each side, `[top, right, bottom, left]` points, in one + /// colour, as CSS `border-top`, `border-right`, `border-bottom` and `border-left` draw: a + /// zero side draws nothing, and the ring follows the corner radii, narrowing round a corner + /// from one side's width to the other's. Drawn like [`Self::border`], over the fill and + /// taking no layout space, with each width snapped to device pixels the same way. So a + /// `border-bottom: 0.5px` hairline is `.border_sides([0.0, 0.0, 0.5, 0.0], c)`, its one + /// device pixel the box's last row. Dashes and gradients draw the widest side all round. + /// Replaces any `border`, and `border` replaces it. + pub fn border_sides(mut self, widths: [f32; 4], c: Color) -> Self { + let widths = widths.map(|w| if w.is_finite() { w.max(0.0) } else { 0.0 }); + self.vis.set_border(widths.into_iter().fold(0.0, f32::max), c); + let uniform = widths.iter().all(|&w| w == widths[0]); + if !uniform || self.vis.cold.get_mut_if_some().is_some() { + let cold = self.vis.cold_mut(); + cold.border_bottom = None; + cold.border_sides = (!uniform).then_some(widths); + } + self + } + /// Makes this element's [`Self::border`] or [`Self::border_sides`] take room in layout, as a + /// CSS border does: its padding and content lay out inside it, each side as wide as it + /// draws, snapped as Chromium snaps a border width to device pixels. So a + /// `border-bottom: 0.5px` row is one whole device pixel taller at any scale (0.8 points at + /// 1.25x), and a stack of them ends where a web page's does. + pub fn border_layout(mut self) -> Self { + self.vis.cold_mut().border_layout = true; + self + } + /// Draws a colour icon (one whose body names its own colours, such as a file-type badge) as + /// its silhouette in this element's colour, as an SVG mask of the icon filled with + /// `currentColor` draws it (`@opencode/ui` FileIcon's `mono`): a file tab's badge in one + /// colour until the tab is selected or hovered. A monochrome icon draws as it always does. + pub fn icon_one_color(mut self) -> Self { + self.vis.cold_mut().icon_one_color = true; + self + } + /// A border whose colour runs from `top` at the top edge to `bottom` at the bottom edge, + /// e.g. a top-lit hairline rim. Drawn like [`El::border`], inside the box over the fill. + /// Replaces any `border`, and `border` replaces it. + pub fn border_gradient(mut self, width: f32, top: Color, bottom: Color) -> Self { + self.vis.set_border(width, top); + let cold = self.vis.cold_mut(); + cold.border_bottom = Some(bottom); + cold.border_sides = None; + self + } + /// Dashes the border (`border` or `border_gradient`): `dash` points on, `gap` points off, + /// with butt ends, along the ring's centre line, round the corners too. The pattern starts + /// with a dash where the top edge leaves the top-left corner and runs clockwise. The period + /// stretches or shrinks a little so a whole number of dashes fits, and the last gap meets the + /// first dash cleanly. The fill shows through the gaps, and the dashes draw over it as a + /// solid border does. A zero `dash` or `gap` keeps the border solid. + pub fn border_dash(mut self, dash: f32, gap: f32) -> Self { + let valid = dash.is_finite() && gap.is_finite() && dash > 0.0 && gap > 0.0; + let v = valid.then_some([dash, gap]); + if v.is_some() || !self.vis.cold.is_empty() { + self.vis.cold_mut().border_dash = v; + } + self + } + /// Starts the dash pattern `phase` points into itself (SwiftUI's `dashPhase`), so growing it + /// marches the dashes anticlockwise. A phase of `dash + gap` is one whole period. It is + /// applied as given every frame and never springs (a spring would run a wrapped phase + /// backwards), so drive it from a clock for marching ants. + pub fn border_dash_phase(mut self, phase: f32) -> Self { + let p = if phase.is_finite() { phase } else { 0.0 }; + if p != 0.0 || !self.vis.cold.is_empty() { + self.vis.cold_mut().border_dash_phase = p; + } + self + } + /// An outer drop shadow offset by `(0, y)` with CSS `blur` radius (`blur = 2σ`; pass + /// `2.0 * r` to match `CALayer.shadowRadius`). Springs like [`Self::box_shadow`]. + pub fn shadow(mut self, y: f32, blur: f32, color: Color) -> Self { + self.vis.cold_mut().shadows.push(Shadow { y, blur, color, ..Shadow::default() }); + self + } + /// A full box shadow (offset, spread, inset), e.g. one layer of a CSS elevation token. + /// `s.blur` follows CSS (`blur = 2σ`, twice `CALayer.shadowRadius`). The first four + /// shadows spring: a change to one's offset, blur or spread moves on the element's layout + /// spring and its colour on the colour spring, so a pressed card's shadow tightens as it + /// sinks. Under Reduce Motion, and in an instant transaction, the geometry lands at once. + pub fn box_shadow(mut self, s: Shadow) -> Self { + self.vis.cold_mut().shadows.push(s); + self + } + /// A vertical gradient from `top` to `bottom` painted over the fill (CSS `linear-gradient(180deg, ..)`). + pub fn gradient(mut self, top: Color, bottom: Color) -> Self { + self.vis.cold_mut().gradient = Some(Box::new([top, bottom])); + self + } + /// A radial gradient painted over the fill and clipped to the element's rounded corners. + /// + /// `center` is in normalized element coordinates (`[0.5, 0.5]` is the centre, `[0.0, 0.0]` top-left). + /// `radius` is in points (`f32` for a circle or `[rx, ry]` for an ellipse). + /// `stops` are up to 16 `(position, color)` pairs along `0.0..=1.0` from `center` (`0.0`) to + /// `radius` (`1.0`). The first 8 stops' colours spring in Oklab when changed; all interpolate + /// in premultiplied colour across the quad, matching [`El::gradient`]. + pub fn radial_gradient( + mut self, + center: [f32; 2], + radius: impl Into<RadialRadius>, + stops: impl AsRef<[(f32, Color)]>, + ) -> Self { + let [rx, ry] = radius.into().0; + let valid = center[0].is_finite() + && center[1].is_finite() + && rx.is_finite() + && ry.is_finite() + && rx > 0.0 + && ry > 0.0; + let r = valid + .then(|| normalize_gradient_stops(GradientGeometry::Radial { center, radius: [rx, ry] }, stops.as_ref())) + .flatten() + .map(Box::new); + if r.is_some() || !self.vis.cold.is_empty() { + self.vis.cold_mut().radial = r; + } + self + } + /// A linear gradient at `angle` radians (CSS convention: `0.0` is bottom-to-top, `PI / 2` is + /// left-to-right, `PI` is top-to-bottom like [`El::gradient`]) with up to 16 stops, painted over + /// the fill: enough for the eased gradients CSS writes as a stop list, such as a scrim that + /// fades out on an easing curve (`linear-gradient(180deg, bg 0%, … 16 stops …, transparent)`). + pub fn linear_gradient(mut self, angle: f32, stops: impl AsRef<[(f32, Color)]>) -> Self { + let r = angle + .is_finite() + .then(|| normalize_gradient_stops(GradientGeometry::Linear { angle }, stops.as_ref())) + .flatten() + .map(Box::new); + if r.is_some() || !self.vis.cold.is_empty() { + self.vis.cold_mut().radial = r; + } + self + } + /// Paints `shape` (strokes and fills in this element's points, origin top-left) over the + /// fill and under any text. It does not affect layout or hit testing. + pub fn shape(mut self, shape: Shape) -> Self { + let sh = (!shape.is_empty()).then(|| Rc::new(shape)); + if sh.is_some() || !self.vis.cold.is_empty() { + self.vis.cold_mut().shape = sh; + } + self + } + /// Shows `pixels`, scaled into the element's rect and clipped to its corner radius. The image + /// can change without the view re-running: the next frame draws its latest contents. + /// An element that sets only its width (`w`, `w_full`) or only its height takes the other + /// side from the image's aspect ratio, updating when the image decodes or changes shape; + /// [`aspect_ratio`](Self::aspect_ratio) overrides it. + pub fn pixels(mut self, pixels: &crate::pixels::Pixels) -> Self { + let cold = self.vis.cold_mut(); + cold.pixels = Some(pixels.clone()); + cold.pixels_fit = None; + self + } + /// Shows `pixels` at its own aspect ratio, centred: `Fit` letterboxes the whole image inside + /// the rect (the corner radius rounds the image), `Fill` covers the rect and crops the overflow. + pub fn pixels_fit(mut self, pixels: &crate::pixels::Pixels, fit: crate::SurfaceFit) -> Self { + let cold = self.vis.cold_mut(); + cold.pixels = Some(pixels.clone()); + cold.pixels_fit = Some(fit); + self + } + /// A ring `offset` points outside the border box (CSS `outline` + `outline-offset`). Width + /// and offset snap to device pixels as [`Self::border`]'s width does. + pub fn outline(mut self, width: f32, offset: f32, color: Color) -> Self { + self.vis.cold_mut().outline = Some(Outline { width, offset, color }); + self + } + #[inline] + pub fn opacity(mut self, o: f32) -> Self { + self.set_opacity(o); + self + } + /// [`El::opacity`] in place. + #[inline] + pub fn set_opacity(&mut self, o: f32) -> &mut Self { + self.vis.opacity = o; + self + } + /// Gaussian blur of the completed subtree, in points (standard deviation). Zero has no + /// filter cost. The renderer caps sigma at 64 device pixels; bounds grow by three sigma. + pub fn blur(mut self, sigma: f32) -> Self { + let sigma = sigma.max(0.0); + if sigma != 0.0 || !self.vis.cold.is_empty() { + self.vis.cold_mut().blur = sigma; + } + self + } + /// Override the blur target's curve. Ordinary changes use the element's motion spring. + pub fn blur_motion(mut self, anim: impl Into<Anim>) -> Self { + self.vis.cold_mut().blur_motion = Some(Box::new(anim.into())); + self + } + /// Dim each paint leaf in the currently built subtree, independently. Unlike `opacity`, + /// overlapping draws retain their individual coverage and no group layer is introduced. A + /// box with a solid fill still fades as `opacity` would: its outer shadows stay outside it + /// and its fill and gradient fade as one. + /// Call after adding children. Useful for static disabled styling; animation and hit-test + /// opacity still belong to `opacity` / `live_opacity`. + pub fn dim(mut self, alpha: f32) -> Self { + fn apply(e: &mut El, alpha: f32) { + e.expand_memo(); + if alpha < 1.0 || !e.vis.cold.is_empty() { + e.vis.cold_mut().paint_alpha *= alpha; + } + for child in &mut e.children { apply(child, alpha); } + } + apply(&mut self, alpha.clamp(0.0, 1.0)); + self + } + /// Fade the whole subtree as one composited layer, like CSS `opacity`: a label over its + /// button's fill shows the fill as it is, not faded through, and overlapping children don't + /// show through each other. Static, as [`Self::dim`] is: a change lands at once, and + /// animation and hit-test opacity still belong to `opacity` / `live_opacity`. Only an + /// element below 1 whose paint overlaps (children, or more than one paint of its own) draws + /// offscreen; anything else just takes the alpha. Repeated calls multiply. + pub fn layer_opacity(mut self, alpha: f32) -> Self { + let alpha = alpha.clamp(0.0, 1.0); + if alpha < 1.0 || !self.vis.cold.is_empty() { + self.vis.cold_mut().layer_opacity *= alpha; + } + self + } + /// Add children's premultiplied colours while a direct child is between opacity 0 and 1. + /// Give two overlaid states opacity `1-t` and `t` for a dissolve without a midpoint alpha dip. + /// Put a shared background outside this scope; its own paint also participates in addition. + /// At rest (all direct children at 0 or 1), draw normally without a dissolve layer. Overlapping + /// opaque states therefore use source-over at rest; this API is for replacing states. + pub fn dissolve(mut self) -> Self { + self.vis_flags.set(VisualFlags::PLUS_LIGHTER, true); + self + } + /// Rasterize this subtree once into an offscreen texture when settled and composite that + /// texture until the subtree's draw output changes, including while an ancestor's + /// [`live_offset`](Self::live_offset) or [`live_scale`](Self::live_scale) moves it. While a + /// spring, transition, or effect slot inside the subtree is active, it draws live and + /// re-caches once settled. + pub fn cache(mut self) -> Self { + self.vis_flags.set(VisualFlags::CACHE, true); + self + } + /// Cache this subtree like [`Self::cache`], also mixing `key` into its invalidation signature. + pub fn cache_key(mut self, key: u64) -> Self { + self.vis_flags.set(VisualFlags::CACHE, true); + self.vis.cold_mut().cache_key = Some(key); + self + } + /// Tags this element's instances (and its descendants', until one sets its own) for a + /// compositor: `Runtime::marks` runs parallel to `Runtime::instances`. + pub fn mark(mut self, mark: u32) -> Self { + if mark != 0 || !self.vis.cold.is_empty() { + self.vis.cold_mut().mark = mark; + } + self + } + /// Overlay drawn over the fill while hovered. + #[inline] + pub fn hover(mut self, c: Color) -> Self { + self.set_hover(c); + self + } + /// [`El::hover`] in place. + #[inline] + pub fn set_hover(&mut self, c: Color) -> &mut Self { + self.vis.set_hover(c); + self + } + /// Overlay drawn over the fill while pressed. + #[inline] + pub fn press(mut self, c: Color) -> Self { + self.set_press(c); + self + } + /// [`El::press`] in place. + #[inline] + pub fn set_press(&mut self, c: Color) -> &mut Self { + self.vis.set_press(c); + self + } + /// Shrink to `scale` about the centre while a press on this element is held, as iOS tiles + /// and buttons do (0.96 to 0.97), springing back on release or when the pointer leaves. + /// Put it on the element with `on_press`. Layout and hit testing keep the resting size, and + /// Reduce Motion turns it off. `1.0` (or anything not positive) removes it. + pub fn press_scale(mut self, scale: f32) -> Self { + let s = (scale.is_finite() && scale > 0.0 && scale != 1.0).then_some(scale); + if s.is_some() || !self.handlers.is_empty() { + self.handlers.press_scale = s; + } + self + } + /// Draw this element and everything in it `k` times its size about its centre, like + /// SwiftUI's `scaleEffect`: fills, borders, text, icons and images all scale, and text + /// rasterizes at the scaled size once it rests. Layout keeps the unscaled size, so siblings + /// don't move; hit testing follows the scaled rect. A change springs on the element's layout + /// spring (or [`Self::scale_motion`]); under Reduce Motion, and in an instant transaction, it + /// lands at once. Multiplies with transitions, `live_scale` and `press_scale`. Anything not + /// finite or below zero is `1.0`. + pub fn scale(mut self, k: f32) -> Self { + self.scale = if k.is_finite() && k >= 0.0 { k } else { 1.0 }; + self + } + /// The curve [`Self::scale`] changes on. + pub fn scale_motion(mut self, anim: impl Into<Anim>) -> Self { + self.vis.cold_mut().scale_motion = Some(Box::new(anim.into())); + self + } + /// Draw this element and everything in it turned `radians` clockwise about its + /// [`origin`](Self::origin), like SwiftUI's `rotationEffect`: fills, borders, shadows, + /// text, icons and images all turn. Layout keeps the upright box, so siblings don't move. + /// A change springs on the element's layout spring (or [`Self::rotate_motion`]); under + /// Reduce Motion, and in an instant transaction, it lands at once. While turned, the + /// subtree draws into its own layer, and a native surface inside it (a video, a web view) + /// stays upright. Hit testing follows the turned box; the reported rect uses its upright + /// bounding box. Anything not finite is `0.0`. + pub fn rotate(mut self, radians: f32) -> Self { + let r = if radians.is_finite() { radians } else { 0.0 }; + if r != 0.0 || !self.vis.cold.is_empty() { + self.vis.cold_mut().rotate = r; + } + self + } + /// The curve [`Self::rotate`] changes on. + pub fn rotate_motion(mut self, anim: impl Into<Anim>) -> Self { + self.vis.cold_mut().rotate_motion = Some(Box::new(anim.into())); + self + } + /// The point this element scales and rotates about, in units of its own size: `(0.5, 0.5)` + /// (the default) is its centre, `(0.5, 1.0)` the middle of its bottom edge, which stays put + /// while a keycap sinks. Like SwiftUI's `anchor:`. [`Self::scale`], [`Self::rotate`], + /// `live_scale`, `press_scale` and a transition's scale all pivot here once it's set; + /// [`Self::offset`] ignores it. Values outside 0..1 pivot outside the element; anything not + /// finite is the centre. + pub fn origin(mut self, x: f32, y: f32) -> Self { + let o = (x.is_finite() && y.is_finite() && (x, y) != (0.5, 0.5)).then_some([x, y]); + if o.is_some() || !self.vis.cold.is_empty() { + self.vis.cold_mut().origin = o; + } + self + } + /// Run the animations of this element and everything in it at `k` times normal speed: + /// springs, transitions (enter, exit, layout), implicit animations, hover and press + /// fades, loops and word reveals. `0.0` freezes them exactly where they are, `0.5` is slow + /// motion, and changing `k` carries on from the same place. Nested scales multiply, and + /// all of them multiply with the window's [`Cx::time_scale`](crate::Cx::time_scale). + /// + /// Only time slows. State still updates at once: a hover or press is tracked as usual and + /// only its fade waits. An exiting element drops its own factor and follows its ancestors + /// still in the tree, so one under a frozen subtree stays mid-exit until that scale rises, + /// then finishes and is removed. A frozen subtree requests no frames. + /// Scrolling, growth stacks and `Tween` keep the window's clock: they follow input and + /// layout, and a frozen scroll view would ignore the wheel. Anything not finite or below + /// zero is `1.0`. + pub fn time_scale(mut self, k: f32) -> Self { + let k = if k.is_finite() && k >= 0.0 { k } else { 1.0 }; + if k != 1.0 || !self.cold.is_empty() { + self.cold_mut().time_scale = k; + } + self + } + /// A scroll area's wrapper passes its clip to the viewport, beside which it draws the bar. + fn set_clip(&mut self, clip: [f32; 4]) { + if self.vis.clip_to_content + && let Some(viewport) = self.children.first_mut() + { + viewport.vis.cold_mut().clip = Some(clip); + } else { + self.vis.cold_mut().clip = Some(clip); + } + } + /// Clip children to this box with soft gradient edges (never a hard crop). + #[inline] + pub fn clip_soft(mut self, fade: f32) -> Self { + self.set_clip_soft(fade); + self + } + /// [`El::clip_soft`] in place. + pub fn set_clip_soft(&mut self, fade: f32) -> &mut Self { + self.set_clip([fade; 4]); + self + } + /// Clip this element and its descendants to its presented rounded rectangle. Follows + /// [`El::corners`] and [`El::continuous_corners`] when set on this element; otherwise rounds + /// all four corners by `radius` points (capped at half the shorter edge). Filters run before + /// this mask. Nested masks intersect without moving either rectangle's corners; complex + /// intersections use a layer. Hit testing uses the rectangular clip bounds, including visually + /// clipped corner areas. + pub fn clip_rounded(mut self, radius: f32) -> Self { + let cold = self.vis.cold_mut(); + cold.clip_corners = None; + cold.clip_radius = Some(radius.max(0.0)); + self + } + /// Clip this element and its descendants to its presented rectangle with per-corner radii + /// `[top_left, top_right, bottom_right, bottom_left]` in points, capped at half the shorter + /// edge and following [`El::continuous_corners`]. Unlike [`El::clip_rounded`], ignores the + /// element's paint radii. Hit testing still uses the rectangular clip bounds. + pub fn clip_corners(mut self, radii: [f32; 4]) -> Self { + let clamped = radii.map(|r| r.max(0.0)); + let cold = self.vis.cold_mut(); + cold.clip_corners = Some(clamped); + cold.clip_radius = Some(clamped.into_iter().fold(0.0, f32::max)); + self + } + /// Punch a round hole through this element and everything it and its descendants draw: clear + /// within `inner` points of `center` (points from the element's top-left, which may lie + /// outside it), whole from `outer` points, and ramping linearly between, as CSS + /// `mask-image: radial-gradient(circle at x y, transparent inner, black outer)` does. Equal + /// radii cut an anti-aliased edge. Room for a badge over an avatar's corner: + /// `.cutout_circle([16.0, 0.0], 4.0, 5.0)` under a 6 point dot at the corner. The subtree + /// draws in an isolated layer, whose composite cuts the hole; hit testing ignores it. + pub fn cutout_circle(mut self, center: [f32; 2], inner: f32, outer: f32) -> Self { + let inner = inner.max(0.0); + self.vis.cold_mut().cutout = Some([center[0], center[1], inner, outer.max(inner)]); + self + } + /// Soft clip with a fade width per side (left, top, right, bottom). + pub fn clip_fade(mut self, left: f32, top: f32, right: f32, bottom: f32) -> Self { + self.set_clip([left, top, right, bottom].map(|w| w.clamp(0.0, 65504.0))); + self + } + /// [`Self::clip_fade`] with linear ramps: alpha falls in proportion to distance, from whole + /// `width` in from each side to nothing at it, rather than easing at both ends. A mask that + /// runs straight into an edge, such as a transcript fading into the top of a composer. + pub fn clip_fade_linear(mut self, left: f32, top: f32, right: f32, bottom: f32) -> Self { + self.set_clip([left, top, right, bottom].map(|w| -w.clamp(0.0, 65504.0))); + self + } + /// Track hover for descendants' `group_*` styles (see [`Visual::hover_group`]). Keyboard + /// focus on the group or inside it lights it too, as CSS `:is(:hover, :has(:focus-visible))` + /// does, so controls it reveals show when Tab reaches them. + pub fn hover_group(mut self) -> Self { + self.vis_flags.set(VisualFlags::HOVER_GROUP, true); + self + } + /// [`Self::hover_group`], shared by every element on screen with the same `key`: the pointer + /// over any of them hovers them all, so one group can span elements that don't nest, such as + /// a reply's text and the footer under it in separate rows of a virtual list. + pub fn hover_group_shared(mut self, key: impl Into<Rc<str>>) -> Self { + self.vis_flags.set(VisualFlags::HOVER_GROUP, true); + self.vis.cold_mut().hover_share = Some(key.into()); + self + } + /// [`Self::hover_group`], which follows keyboard focus as well now. + #[doc(hidden)] + pub fn hover_group_focus(self) -> Self { + self.hover_group() + } + /// Curves for this element's hover track: `enter` when the pointer arrives, `exit` when it + /// leaves (e.g. a delayed reveal). + pub fn hover_motion(mut self, enter: impl Into<Anim>, exit: impl Into<Anim>) -> Self { + self.vis.cold_mut().hover_motion = Some(Rc::new((enter.into(), exit.into()))); + self + } + /// Default hover curves for this element and everything below it: any hover track (an + /// element with [`Self::hover`] or [`Self::hover_group`]) without its own + /// [`Self::hover_motion`] uses the nearest ancestor's pair, and [`Self::anchored`] overlays + /// inherit from their anchor, so kit controls whose inner elements you can't reach follow it + /// too. Set it on the root of the view (or on what you pass to `rune_kit::root`, which + /// carries it to the overlays it layers beside the view). Without any, hover lands at once + /// and fades out over 0.1 s. Rows highlighted by `focus_highlight` (menu items, select + /// options) are never faded. + pub fn hover_motion_within(mut self, enter: impl Into<Anim>, exit: impl Into<Anim>) -> Self { + self.vis.cold_mut().hover_within = Some(Rc::new((enter.into(), exit.into()))); + self + } + /// The pair set by [`Self::hover_motion_within`]. + pub fn hover_within_curves(&self) -> Option<(Anim, Anim)> { + self.vis.hover_within.as_deref().copied() + } + /// Opacity factor `rest` normally and `hovered` while the nearest ancestor group is hovered. + pub fn group_opacity(mut self, rest: f32, hovered: f32) -> Self { + self.vis.cold_mut().group_opacity = Some([rest, hovered]); + self + } + /// Text or icon colour while the nearest ancestor group is hovered. + pub fn group_color(mut self, c: Color) -> Self { + self.vis.cold_mut().group_color = Some(c); + self + } + /// While a press on this element is held, the text and icons in it (its own included) draw + /// in `c`, on the same track as a [`Self::press`] overlay, with or without one: a ghost + /// button whose icon brightens under the press, as CSS `:active { color }` does. + pub fn press_color(mut self, c: Color) -> Self { + self.vis.cold_mut().press_color = Some(c); + self + } + /// Hovering this element shows only its own hover: while the pointer is on it, the + /// elements it sits inside show no hover overlay and their `group_*` styles rest, as if the + /// pointer had left them. A face or button inside a hoverable row, for one. Paint only: it + /// changes no layout and needs no commit. + pub fn hover_alone(mut self) -> Self { + self.vis.cold_mut().hover_alone = true; + self + } + /// Wall-clock opacity loop, using the shared loop engine and host wake deadline. + pub fn cycle(self, c: Cycle) -> Self { + self.looping(rune_motion::LoopSpec::cycle(c)) + } +} + +/// A CSS-style box shadow. Outer shadows draw behind the element; `inset` ones draw inside its +/// shape, over the fill. A zero-blur, zero-offset outer shadow with a spread is a ring outside +/// the border box (drawn as a ring, so translucent fills don't show it through). +/// +/// `blur` is the CSS `box-shadow` blur radius (`blur = 2σ`, so Gaussian standard deviation +/// `σ = blur * 0.5`). `CALayer.shadowRadius` and Sketch / Figma shadow blur specify `r ≈ σ`, +/// so pass `blur = 2.0 * r` to match a `CALayer` shadow radius (whereas [`El::blur`] takes `σ` directly). +#[derive(Clone, Copy, Debug, PartialEq, Default)] +pub struct Shadow { + pub x: f32, + pub y: f32, + /// Twice the Gaussian's standard deviation, in points (CSS blur radius). + pub blur: f32, + pub spread: f32, + pub color: Color, + pub inset: bool, +} + +/// Radius of [`El::radial_gradient`], in points: a circle (`f32`) or an `[rx, ry]` ellipse. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct RadialRadius(pub [f32; 2]); + +impl From<f32> for RadialRadius { + fn from(r: f32) -> Self { + Self([r, r]) + } +} + +impl From<[f32; 2]> for RadialRadius { + fn from(r: [f32; 2]) -> Self { + Self(r) + } +} + +impl From<(f32, f32)> for RadialRadius { + fn from((rx, ry): (f32, f32)) -> Self { + Self([rx, ry]) + } +} + +/// CSS writes an eased fade as a list of stops: 16 holds the eased gradients Desktop draws. +pub(crate) const MAX_GRADIENT_STOPS: usize = 16; + +#[derive(Clone, Copy, Debug, PartialEq)] +pub(crate) enum GradientGeometry { + Radial { center: [f32; 2], radius: [f32; 2] }, + Linear { angle: f32 }, +} + +/// A radial or angled linear gradient painted over an element's fill. +#[derive(Clone, Debug, PartialEq)] +pub(crate) struct RadialGradient { + pub(crate) geometry: GradientGeometry, + /// Sorted `(t, color)` stops in `0.0..=1.0`, capped at [`MAX_GRADIENT_STOPS`]. + pub(crate) stops: Vec<(f32, Color)>, +} + +fn normalize_gradient_stops(geometry: GradientGeometry, raw: &[(f32, Color)]) -> Option<RadialGradient> { + let mut stops: Vec<(f32, Color)> = raw + .iter() + .copied() + .filter(|(t, _)| t.is_finite()) + .map(|(t, c)| (t.clamp(0.0, 1.0), c)) + .collect(); + if stops.is_empty() { + return None; + } + stops.sort_by(|a, b| a.0.total_cmp(&b.0)); + stops.truncate(MAX_GRADIENT_STOPS); + if stops.len() == 1 { + let c = stops[0].1; + stops = vec![(0.0, c), (1.0, c)]; + } + Some(RadialGradient { geometry, stops }) +} + +impl Shadow { + /// A CALayer shadow: `shadowRadius` `radius`, `shadowOffset` (`x`, `y`) with y down as in a + /// flipped view, and `shadowColor` at `shadowOpacity` folded into `color`. Core Animation's + /// blur has a standard deviation of about `shadowRadius` (0.97 to 1.02 times it, measured + /// from 1.5 to 32 pt), so `blur` is twice the radius. Corners stay circular, as with a + /// `CGPath(roundedRect:)` shadow path. With `srgb_blend(true)` it also composites as one. + pub fn core_animation(x: f32, y: f32, radius: f32, color: Color) -> Shadow { + Shadow { x, y, blur: 2.0 * radius, color, ..Shadow::default() } + } +} + +/// A ring drawn `offset` points outside the border box, `width` points wide (CSS `outline`). +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Outline { + pub width: f32, + pub offset: f32, + pub color: Color, +} + +impl El { + /// Paint the newest video frame inside this node. Node dimensions are in points. + pub fn native_surface(mut self, surface: &crate::NativeSurface, fit: crate::SurfaceFit) -> Self { + self.vis.cold_mut().surface = Some((surface.clone(), fit)); + self + } + /// Which edges a surface or [`pixels_fit`](Self::pixels_fit) image sticks to inside this + /// node, as (horizontal, vertical): `Start` is left and top, `End` is right and bottom. It + /// positions the spare space `Fit` leaves and the overflow `Fill` crops; the default is + /// `Center` on both axes. Applies to [`native_surface`](Self::native_surface), + /// [`video`](Self::video) and `pixels_fit`. + /// + /// ``` + /// # use rune::{Align, SurfaceFit, el}; + /// # let stream = rune::NativeSurface::new(); + /// // A streamed page that keeps its top-left corner while the panel is resized. + /// let view = el().native_surface(&stream, SurfaceFit::Fill).surface_anchor(Align::Start, Align::Start); + /// ``` + pub fn surface_anchor(mut self, horizontal: Align, vertical: Align) -> Self { + self.vis.cold_mut().surface_place.anchor = [horizontal, vertical]; + self + } + /// Draw a surface or `pixels_fit` image at one texel per device pixel instead of scaling it + /// to the node, so `SurfaceFit` no longer applies. A node bigger than the image leaves the + /// rest empty; a smaller one crops it. Combine with + /// [`surface_anchor`](Self::surface_anchor) to choose which edges stay put. It suits a + /// stream rendered at the window's scale, whose last frame should hold still, not stretch, + /// until the next one arrives at the node's new size. + /// + /// ``` + /// # use rune::{Align, SurfaceFit, el}; + /// # let stream = rune::NativeSurface::new(); + /// let view = el() + /// .native_surface(&stream, SurfaceFit::Fill) + /// .surface_anchor(Align::Start, Align::Start) + /// .surface_unscaled(true); + /// ``` + pub fn surface_unscaled(mut self, unscaled: bool) -> Self { + self.vis.cold_mut().surface_place.unscaled = unscaled; + self + } + /// Play `video` inside this node: `Fit` letterboxes, `Fill` crops. Frames come from the + /// display link while it plays; a paused video draws no frames of its own. Audio players + /// need no element. + pub fn video(self, video: &crate::Player, fit: crate::SurfaceFit) -> Self { + self.native_surface(video.surface(), fit) + } + /// Turn this element's icon by `radians`, clockwise about its centre: a disclosure chevron + /// pointing right when closed and down when open. A change springs on the element's + /// [`motion`](Self::motion) and jumps under reduced motion. Only the glyph turns; layout and + /// hit testing keep the upright box. + pub fn icon_rotation(mut self, radians: f32) -> Self { + let r = if radians.is_finite() { radians } else { 0.0 }; + if r != 0.0 || !self.vis.cold.is_empty() { + self.vis.cold_mut().icon_turn = r; + } + self + } +} diff --git a/app/vendor/rune/crates/rune/src/file_dialog.rs b/app/vendor/rune/crates/rune/src/file_dialog.rs new file mode 100644 index 0000000..952a35d --- /dev/null +++ b/app/vendor/rune/crates/rune/src/file_dialog.rs @@ -0,0 +1,366 @@ +//! Inject native dialogs in the shell, scripted responses in headless fixtures. +//! Native futures use rfd on macOS and Windows, and the XDG desktop portal's FileChooser +//! over zbus on Linux. +//! +//! A handler can also ask with [`Tx::open_file`], [`Tx::save_file`] or [`Tx::open_folder`]: the window shows the +//! dialog once the handler's frame is done, and the answer runs the callback as an action on +//! a later frame. Headless runs keep the dialog open in `--tree` (`fileDialog`) until a +//! script's `{"type": "file-dialog", "path": …}` or `{"type": "file-dialog-cancel"}` answers it. +use std::cell::RefCell; +use std::collections::VecDeque; +use std::future::Future; +use std::path::PathBuf; +use std::pin::Pin; +use std::rc::Rc; +use std::sync::{Arc, Mutex}; +use std::task::{Context, Poll}; + +use crate::Tx; +use crate::runtime::Waker; + +#[cfg(all(feature = "native-file-dialog", target_os = "linux"))] +mod portal; +#[cfg(any(all(feature = "native-file-dialog", target_os = "linux"), all(test, unix)))] +mod portal_format; +#[cfg(all(feature = "native-file-dialog", target_os = "linux"))] +pub(crate) use portal::window_focus; +#[cfg(all(feature = "native-file-dialog", target_os = "linux"))] +use portal::show as native; + +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct FileDialogOptions { + pub title: String, + pub directory: Option<PathBuf>, + pub file_name: Option<String>, + pub filters: Vec<(String, Vec<String>)>, +} +impl FileDialogOptions { + pub fn filter(mut self, name: impl Into<String>, extensions: &[&str]) -> Self { + self.filters.push((name.into(), extensions.iter().map(|s| (*s).into()).collect())); self + } +} + +/// Which dialog: Open picks an existing file, Save names a file to write, Folder picks an +/// existing folder (its options' filters and file name don't apply). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum FileDialogKind { Open, Save, Folder } + +impl FileDialogKind { + fn name(self) -> &'static str { match self { Self::Open => "open", Self::Save => "save", Self::Folder => "folder" } } +} + +/// Expected request and its response. `None` is cancellation, not a missing fixture. +#[derive(Clone, Debug)] +pub struct ScriptedFileDialog { + pub kind: FileDialogKind, + pub path: Option<PathBuf>, +} + +#[derive(Clone)] +pub struct FileDialogs(Backend); +#[derive(Clone)] +enum Backend { + #[cfg(feature = "native-file-dialog")] + Native, + Scripted(Arc<Mutex<VecDeque<ScriptedFileDialog>>>), +} +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct FileDialogError(pub String); +impl std::fmt::Display for FileDialogError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.write_str(&self.0) } +} +impl std::error::Error for FileDialogError {} + +impl FileDialogs { + /// Native dialogs are opt-in at the app's capability boundary. Headless apps inject + /// `scripted` instead, so tests never depend on filesystem UI or a display server. + /// Poll asynchronously: blocking the window's main thread (for example with + /// `pollster::block_on`) deadlocks Cocoa's dialog presentation. On Linux, `open` and + /// `save` return an error when the desktop has no XDG portal FileChooser. + #[cfg(feature = "native-file-dialog")] + pub fn native() -> Self { Self(Backend::Native) } + pub fn scripted(responses: impl IntoIterator<Item = ScriptedFileDialog>) -> Self { + Self(Backend::Scripted(Arc::new(Mutex::new(responses.into_iter().collect())))) + } + pub async fn open(&self, options: FileDialogOptions) -> Result<Option<PathBuf>, FileDialogError> { + self.show(FileDialogKind::Open, options).await + } + pub async fn save(&self, options: FileDialogOptions) -> Result<Option<PathBuf>, FileDialogError> { + self.show(FileDialogKind::Save, options).await + } + pub async fn open_folder(&self, options: FileDialogOptions) -> Result<Option<PathBuf>, FileDialogError> { + self.show(FileDialogKind::Folder, options).await + } + async fn show(&self, kind: FileDialogKind, options: FileDialogOptions) -> Result<Option<PathBuf>, FileDialogError> { + match &self.0 { + Backend::Scripted(responses) => { + let mut responses = responses.lock().unwrap(); + let response = responses.front().ok_or_else(|| FileDialogError("file dialog fixture exhausted".into()))?; + if response.kind != kind { + return Err(FileDialogError(format!("expected {:?} dialog, received {kind:?}", response.kind))); + } + let _ = options; + Ok(responses.pop_front().unwrap().path) + } + #[cfg(feature = "native-file-dialog")] + Backend::Native => native(kind, options).await, + } + } +} + +#[cfg(all(feature = "native-file-dialog", any(target_os = "macos", target_os = "windows")))] +async fn native(kind: FileDialogKind, options: FileDialogOptions) -> Result<Option<PathBuf>, FileDialogError> { + rfd_show(rfd_dialog(options), kind).await +} +#[cfg(all(feature = "native-file-dialog", any(target_os = "macos", target_os = "windows")))] +fn rfd_dialog(options: FileDialogOptions) -> rfd::AsyncFileDialog { + let mut dialog = rfd::AsyncFileDialog::new().set_title(options.title); + if let Some(directory) = options.directory { dialog = dialog.set_directory(directory); } + if let Some(file_name) = options.file_name { dialog = dialog.set_file_name(file_name); } + for (name, extensions) in options.filters { dialog = dialog.add_filter(name, &extensions); } + dialog +} +/// Calling this starts the dialog (on macOS, a sheet over the parent); awaiting reads it. +#[cfg(all(feature = "native-file-dialog", any(target_os = "macos", target_os = "windows")))] +fn rfd_show(dialog: rfd::AsyncFileDialog, kind: FileDialogKind) -> impl Future<Output = Result<Option<PathBuf>, FileDialogError>> { + let file: Pin<Box<dyn Future<Output = Option<rfd::FileHandle>> + Send>> = match kind { + FileDialogKind::Open => Box::pin(dialog.pick_file()), + FileDialogKind::Save => Box::pin(dialog.save_file()), + FileDialogKind::Folder => Box::pin(dialog.pick_folder()), + }; + async move { Ok(file.await.map(|file| file.path().to_path_buf())) } +} +#[cfg(all(feature = "native-file-dialog", not(any(target_os = "linux", target_os = "macos", target_os = "windows"))))] +async fn native(_: FileDialogKind, _: FileDialogOptions) -> Result<Option<PathBuf>, FileDialogError> { + Err(FileDialogError("native file dialogs aren't supported on this platform".into())) +} + +/// What a [`Tx::open_file`], [`Tx::save_file`] or [`Tx::open_folder`] callback gets: the chosen path, `Ok(None)` +/// when the user cancels, or why no dialog could show. +pub type FileDialogResult = Result<Option<PathBuf>, FileDialogError>; + +pub(crate) type AnswerFn = Box<dyn FnOnce(crate::states::States<'_>, FileDialogResult, &mut Tx)>; + +pub(crate) struct Request { + pub kind: FileDialogKind, + pub options: FileDialogOptions, + pub on_answer: AnswerFn, +} + +/// A `Tx`'s dialog request. `Tx` is `Clone`; clones share the request and the runtime takes it once. +#[derive(Clone)] +pub(crate) struct Call(Rc<RefCell<Option<Request>>>); + +impl Call { + pub(crate) fn take(&self) -> Option<Request> { self.0.borrow_mut().take() } +} + +impl std::fmt::Debug for Call { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + let request = self.0.borrow(); + f.debug_tuple("FileDialogCall").field(&request.as_ref().map(|r| (r.kind, &r.options))).finish() + } +} + +/// The runtime's dialog, from the request until its answer is queued. +pub(crate) struct Pending { + pub id: u64, + pub kind: FileDialogKind, + pub options: FileDialogOptions, +} + +/// The runtime's one file dialog. Its answer carries its `id`, so an answer to a dialog that +/// has since closed changes nothing (OpenCode Desktop's +/// `packages/desktop/src/main/files/attachment-picker-machine.ts` fences picks the same way). +#[derive(Default)] +pub(crate) enum DialogState { + /// None asked for, or the last one's answer is queued. + #[default] + Closed, + /// Asked for; a host shows it next. + Requested(Pending), + /// A host has it on screen. + Showing(Pending), +} + +impl DialogState { + pub(crate) fn pending(&self) -> Option<&Pending> { + match self { + DialogState::Closed => None, + DialogState::Requested(p) | DialogState::Showing(p) => Some(p), + } + } + + pub(crate) fn is_open(&self) -> bool { !matches!(self, DialogState::Closed) } + + /// The host takes a requested dialog to show; nothing while one shows. + pub(crate) fn show(&mut self) -> Option<&Pending> { + let DialogState::Requested(_) = self else { return None }; + let DialogState::Requested(p) = std::mem::take(self) else { unreachable!() }; + *self = DialogState::Showing(p); + self.pending() + } + + /// Dialog `id` was answered: it closes, if it's the one open. + pub(crate) fn answered(&mut self, id: u64) { + if self.pending().is_some_and(|p| p.id == id) { *self = DialogState::Closed; } + } + + /// Closes whatever is open, for its `None` answer. + pub(crate) fn take(&mut self) -> Option<Pending> { + match std::mem::take(self) { + DialogState::Closed => None, + DialogState::Requested(p) | DialogState::Showing(p) => Some(p), + } + } +} + +impl Pending { + pub(crate) fn to_json(&self) -> serde_json::Value { + let o = &self.options; + let filters: Vec<_> = o.filters.iter().map(|(name, ext)| serde_json::json!({ "name": name, "extensions": ext })).collect(); + let mut v = serde_json::json!({ "kind": self.kind.name(), "title": o.title, "filters": filters }); + if let Some(dir) = &o.directory { v["directory"] = dir.display().to_string().into(); } + if let Some(name) = &o.file_name { v["fileName"] = name.clone().into(); } + v + } +} + +impl Tx { + /// Show an Open dialog once this handler's frame is done. `on_answer` runs, as an action on + /// a later frame, with the chosen file, `Ok(None)` when the user cancels (or the window + /// hides or closes), or an error when no dialog could show: a second dialog asked for while + /// one is open, a window that stays hidden, an overlay, the web, or a build without the + /// `native-file-dialog` feature. Asked for in the same turn that shows a hidden window, it + /// shows with the window. The window keeps drawing and handling events while the dialog is + /// up: it's a sheet on macOS, owned by the window on Windows, and the desktop portal's + /// chooser on Linux. + /// + /// ```ignore + /// .on_press_tx(|_: &mut App, tx: &mut Tx| { + /// let options = FileDialogOptions { title: "Import".into(), ..Default::default() }.filter("Export", &["json"]); + /// tx.open_file(options, |s: &mut App, result, _| match result { + /// Ok(Some(path)) => s.import(path), + /// Ok(None) => {} + /// Err(e) => s.error = Some(e.to_string()), + /// }); + /// }) + /// ``` + pub fn open_file<S: 'static>(&mut self, options: FileDialogOptions, on_answer: impl FnOnce(&mut S, FileDialogResult, &mut Tx) + 'static) { + self.file_dialog(FileDialogKind::Open, options, on_answer); + } + + /// [`Tx::open_file`] for a Save dialog: the path to write, which may not exist yet. + pub fn save_file<S: 'static>(&mut self, options: FileDialogOptions, on_answer: impl FnOnce(&mut S, FileDialogResult, &mut Tx) + 'static) { + self.file_dialog(FileDialogKind::Save, options, on_answer); + } + + /// [`Tx::open_file`] for a folder: an Open dialog that picks an existing folder, as an app + /// opening a project or choosing where exports go. `options`' title and directory apply; + /// its filters and file name don't. A script answers it as it does a file dialog. + pub fn open_folder<S: 'static>(&mut self, options: FileDialogOptions, on_answer: impl FnOnce(&mut S, FileDialogResult, &mut Tx) + 'static) { + self.file_dialog(FileDialogKind::Folder, options, on_answer); + } + + fn file_dialog<S: 'static>(&mut self, kind: FileDialogKind, options: FileDialogOptions, on_answer: impl FnOnce(&mut S, FileDialogResult, &mut Tx) + 'static) { + let on_answer: AnswerFn = Box::new(move |s, result, tx| { + // None once the playground has dropped the stage that asked. + if let Some(s) = s.cast::<S>() { on_answer(s, result, tx); } + }); + self.file_dialogs.push(Call(Rc::new(RefCell::new(Some(Request { kind, options, on_answer }))))); + } +} + +/// One window's native file dialog: shows what its runtime asks for, and queues the answer +/// after `wake` brings the host back to poll it. The dialog's future owns copies of the +/// options and the window's handle, never the app's state or the runtime. +pub(crate) struct Presenter { + showing: Option<(u64, Pin<Box<dyn Future<Output = FileDialogResult>>>)>, + #[cfg(all(feature = "native-file-dialog", target_os = "macos"))] + sheet_parent: Option<objc2::rc::Retained<objc2_app_kit::NSWindow>>, + wake: std::task::Waker, +} + +struct Wake(Waker); +impl std::task::Wake for Wake { + fn wake(self: Arc<Self>) { (self.0)() } + fn wake_by_ref(self: &Arc<Self>) { (self.0)() } +} + +impl Presenter { + pub(crate) fn new(wake: Waker) -> Self { + Self { + showing: None, + #[cfg(all(feature = "native-file-dialog", target_os = "macos"))] + sheet_parent: None, + wake: Arc::new(Wake(wake)).into(), + } + } + + /// Queues the answer of a dialog that closed. True when one did. + pub(crate) fn answer_core(&mut self, rt: &mut crate::runtime::RuntimeCore) -> bool { + let Some((id, future)) = &mut self.showing else { return false }; + let Poll::Ready(result) = future.as_mut().poll(&mut Context::from_waker(&self.wake)) else { return false }; + let id = *id; + self.showing = None; + #[cfg(all(feature = "native-file-dialog", target_os = "macos"))] + { + self.sheet_parent = None; + } + rt.answer_file_dialog(id, result); + true + } + + /// Shows the runtime's dialog over `window`, starting it before this returns, so nothing + /// blocks the event loop. A dialog asked for while the window is hidden waits for it to + /// show. True when an answer was queued. + pub(crate) fn open_core(&mut self, rt: &mut crate::runtime::RuntimeCore, window: Option<&winit::window::Window>) -> bool { + let Some(window) = window.filter(|_| self.showing.is_none()) else { return false }; + let Some((id, kind, options)) = rt.take_file_dialog() else { return false }; + #[cfg(all(feature = "native-file-dialog", target_os = "macos"))] + { + self.sheet_parent = crate::platform::macos::ns_window(window); + } + self.showing = Some((id, show_over(kind, options, window))); + self.answer_core(rt) + } + + /// The window is going away (hidden, closed or quitting): any attached sheet is ended and + /// the open or waiting dialog is answered `Ok(None)` while its state is alive. + pub(crate) fn cancel_core(&mut self, rt: &mut crate::runtime::RuntimeCore, app: &mut dyn crate::runtime::AppDriver) { + self.stop(); + rt.cancel_file_dialogs(app); + } + + fn stop(&mut self) { + self.showing = None; + #[cfg(all(feature = "native-file-dialog", target_os = "macos"))] + if let Some(window) = self.sheet_parent.take() { + if let Some(sheet) = window.attachedSheet() { + window.endSheet(&sheet); + } + } + } +} + +impl Drop for Presenter { + fn drop(&mut self) { self.stop(); } +} + +fn show_over(kind: FileDialogKind, options: FileDialogOptions, window: &winit::window::Window) -> Pin<Box<dyn Future<Output = FileDialogResult>>> { + #[cfg(all(feature = "native-file-dialog", any(target_os = "macos", target_os = "windows")))] + return Box::pin(rfd_show(rfd_dialog(options).set_parent(window), kind)); + // The portal's parent is the focused window (`window_focus`). + #[cfg(all(feature = "native-file-dialog", target_os = "linux"))] + return { let _ = window; Box::pin(native(kind, options)) }; + #[cfg(all(feature = "native-file-dialog", not(any(target_os = "linux", target_os = "macos", target_os = "windows"))))] + return { let _ = window; Box::pin(native(kind, options)) }; + #[cfg(not(feature = "native-file-dialog"))] + { + let _ = (kind, options, window); + Box::pin(std::future::ready(Err(FileDialogError("file dialogs need Rune's native-file-dialog feature".into())))) + } +} + +#[cfg(test)] +mod tests; diff --git a/app/vendor/rune/crates/rune/src/file_dialog/portal.rs b/app/vendor/rune/crates/rune/src/file_dialog/portal.rs new file mode 100644 index 0000000..6fa5476 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/file_dialog/portal.rs @@ -0,0 +1,158 @@ +//! xdg-desktop-portal FileChooser over zbus. Dialog tasks run on the shared portal worker +//! (`platform::portal::spawn`), so any executor can poll them, the event loop never blocks, +//! and no thread is leaked per call. Dropping the future closes the portal request. +use super::{FileDialogError, FileDialogKind, FileDialogOptions}; +use super::portal_format::{filters, outcome, parent_window, path_bytes}; +use crate::platform::portal::{self, DEST, PATH, RequestError, RequestTimeouts}; +use futures_lite::FutureExt; +use std::{collections::HashMap, path::PathBuf, sync::atomic::{AtomicU32, Ordering}, time::Duration}; +use winit::raw_window_handle::{HasWindowHandle, RawWindowHandle}; +use zbus::{Connection, Proxy, zvariant::{OwnedValue, Value}}; + +const INTERFACE: &str = "org.freedesktop.portal.FileChooser"; +/// Connecting, D-Bus activation of the portal and the method call. The user's choice itself +/// has no timeout. +const RPC_TIMEOUT: Duration = Duration::from_secs(30); + +/// The focused X11 window, the dialog's parent. 0 is none, and Wayland windows stay 0. +static PARENT: AtomicU32 = AtomicU32::new(0); + +pub(crate) fn window_focus(window: &winit::window::Window, focused: bool) { + let Ok(handle) = window.window_handle() else { return }; + let id = match handle.as_raw() { + RawWindowHandle::Xlib(w) => u32::try_from(w.window).unwrap_or(0), + RawWindowHandle::Xcb(w) => w.window.get(), + _ => 0, + }; + if id == 0 { return; } + if focused { PARENT.store(id, Ordering::Relaxed); } + else { PARENT.compare_exchange(id, 0, Ordering::Relaxed, Ordering::Relaxed).ok(); } +} + +fn unavailable() -> FileDialogError { FileDialogError("no XDG desktop portal FileChooser is available".into()) } +fn dbus_error(e: zbus::Error) -> FileDialogError { + if portal::is_unavailable(&e) { + return unavailable(); + } + FileDialogError(e.to_string()) +} + +fn request_options<'a>(kind: FileDialogKind, options: &'a FileDialogOptions, token: &'a str) -> HashMap<&'static str, Value<'a>> { + let mut map = HashMap::from([("handle_token", Value::from(token)), ("modal", Value::from(true))]); + let filters = filters(options); + if !filters.is_empty() && kind != FileDialogKind::Folder { map.insert("filters", Value::from(filters)); } + if let Some(bytes) = options.directory.as_deref().and_then(path_bytes) { + map.insert("current_folder", Value::from(bytes)); + } + if kind == FileDialogKind::Folder { map.insert("directory", Value::from(true)); } + if kind == FileDialogKind::Save && let Some(name) = options.file_name.as_deref().filter(|s| !s.is_empty()) { + map.insert("current_name", Value::from(name)); + } + map +} +/// A reply's `uris`, empty when absent or mistyped. +fn uris(results: &HashMap<String, OwnedValue>) -> Vec<String> { + results.get("uris").and_then(|v| v.try_clone().ok()).and_then(|v| Vec::<String>::try_from(v).ok()).unwrap_or_default() +} + +pub(super) async fn show(kind: FileDialogKind, options: FileDialogOptions) -> Result<Option<PathBuf>, FileDialogError> { + let (reply, result) = async_channel::bounded(1); + let parent = parent_window(PARENT.load(Ordering::Relaxed)); + portal::spawn(move || run(kind, options, parent, reply)).map_err(FileDialogError)?; + result.recv().await.unwrap_or_else(|_| Err(FileDialogError("file dialog worker stopped".into()))) +} + +async fn run(kind: FileDialogKind, options: FileDialogOptions, parent: String, reply: async_channel::Sender<Result<Option<PathBuf>, FileDialogError>>) { + let token = portal::next_token("file_dialog"); + let conn = match portal::timeout(RPC_TIMEOUT, async { + reply.closed().await; + Ok(None) + }.or(async { + // No session bus means this desktop cannot supply the portal. + Connection::session().await.map(Some).map_err(|_| unavailable()) + })).await { + Some(Ok(Some(conn))) => conn, + Some(Ok(None)) => return, + Some(Err(e)) => { reply.try_send(Err(e)).ok(); return; } + None => { reply.try_send(Err(FileDialogError("file dialog portal timed out".into()))).ok(); return; } + }; + let portal_proxy = match portal::timeout(RPC_TIMEOUT, async { + reply.closed().await; + Ok(None) + }.or(async { + Proxy::new(&conn, DEST, PATH, INTERFACE).await.map(Some).map_err(dbus_error) + })).await { + Some(Ok(Some(proxy))) => proxy, + Some(Ok(None)) => { conn.close().await.ok(); return; } + Some(Err(e)) => { conn.close().await.ok(); reply.try_send(Err(e)).ok(); return; } + None => { conn.close().await.ok(); reply.try_send(Err(FileDialogError("file dialog portal timed out".into()))).ok(); return; } + }; + // A folder is OpenFile's `directory` choice (portal version 3). + let method = match kind { FileDialogKind::Open | FileDialogKind::Folder => "OpenFile", FileDialogKind::Save => "SaveFile" }; + let body = (parent.as_str(), options.title.as_str(), request_options(kind, &options, &token)); + let response = portal::request( + &conn, + &portal_proxy, + &token, + method, + &body, + RequestTimeouts { rpc: RPC_TIMEOUT, response: None }, + reply.closed(), + ).await; + conn.close().await.ok(); + match response { + Ok((status, results)) => { reply.try_send(outcome(status, &uris(&results))).ok(); } + Err(RequestError::Cancelled) => {} + Err(RequestError::Dbus(e)) => { reply.try_send(Err(dbus_error(e))).ok(); } + Err(RequestError::Unavailable) => { reply.try_send(Err(unavailable())).ok(); } + Err(RequestError::TimedOut) => { reply.try_send(Err(FileDialogError("file dialog portal timed out".into()))).ok(); } + Err(RequestError::Disconnected) => { reply.try_send(Err(FileDialogError("file dialog portal disconnected".into()))).ok(); } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use zbus::fdo; + #[test] + fn reply_uris_are_read_from_the_results_map() { + let list = vec!["file:///tmp/a%20b".to_string(), "file:///tmp/c".to_string()]; + let results = HashMap::from([("uris".to_string(), OwnedValue::try_from(Value::from(list.clone())).unwrap())]); + assert_eq!(uris(&results), list); + assert_eq!(outcome(0, &uris(&results)).unwrap(), Some(PathBuf::from("/tmp/a b"))); + assert!(uris(&HashMap::new()).is_empty()); + let mistyped = HashMap::from([("uris".to_string(), OwnedValue::try_from(Value::from(7u32)).unwrap())]); + assert!(uris(&mistyped).is_empty()); + } + #[test] + fn options_carry_token_filters_folder_and_save_name() { + let options = FileDialogOptions { title: "Import".into(), directory: Some("/home/a/Downloads".into()), + file_name: Some("export.csv".into()), filters: vec![] }.filter("Exports", &["csv"]); + let open = request_options(FileDialogKind::Open, &options, "t1"); + assert_eq!(open.get("handle_token"), Some(&Value::from("t1"))); + assert_eq!(open.get("filters"), Some(&Value::from(vec![("Exports".to_string(), vec![(0u32, "*.csv".to_string())])]))); + assert_eq!(open.get("current_folder"), Some(&Value::from(b"/home/a/Downloads\0".to_vec()))); + assert!(!open.contains_key("current_name")); + assert!(!open.contains_key("directory")); + let folder = request_options(FileDialogKind::Folder, &options, "t4"); + assert_eq!(folder.get("directory"), Some(&Value::from(true))); + assert!(!folder.contains_key("filters")); + assert_eq!(folder.get("current_folder"), Some(&Value::from(b"/home/a/Downloads\0".to_vec()))); + let save = request_options(FileDialogKind::Save, &options, "t2"); + assert_eq!(save.get("current_name"), Some(&Value::from("export.csv"))); + let empty = FileDialogOptions { directory: Some(PathBuf::new()), file_name: Some(String::new()), ..Default::default() } + .filter("Empty", &[]); + let empty_save = request_options(FileDialogKind::Save, &empty, "t3"); + assert!(!empty_save.contains_key("filters")); + assert!(!empty_save.contains_key("current_folder")); + assert!(!empty_save.contains_key("current_name")); + } + #[test] + fn missing_portal_is_a_clear_error() { + let fdo = |e| zbus::Error::FDO(Box::new(e)); + assert_eq!(dbus_error(fdo(fdo::Error::ServiceUnknown("portal".into()))), unavailable()); + assert_eq!(dbus_error(fdo(fdo::Error::UnknownMethod("OpenFile".into()))), unavailable()); + assert_eq!(dbus_error(fdo(fdo::Error::SpawnChildExited("portal".into()))), unavailable()); + assert_ne!(dbus_error(fdo(fdo::Error::Failed("x".into()))), unavailable()); + } +} diff --git a/app/vendor/rune/crates/rune/src/file_dialog/portal_format.rs b/app/vendor/rune/crates/rune/src/file_dialog/portal_format.rs new file mode 100644 index 0000000..c68451e --- /dev/null +++ b/app/vendor/rune/crates/rune/src/file_dialog/portal_format.rs @@ -0,0 +1,121 @@ +//! The FileChooser portal's argument and reply formats, kept free of D-Bus so they're tested on +//! every Unix host. +use super::{FileDialogError, FileDialogOptions}; +use std::os::unix::ffi::{OsStrExt, OsStringExt}; +use std::path::{Path, PathBuf}; + +/// `x11:<hex xid>`, or empty for no parent. +pub(super) fn parent_window(xid: u32) -> String { if xid == 0 { String::new() } else { format!("x11:{xid:x}") } } + +pub(super) type Filter = (String, Vec<(u32, String)>); +/// Portal filters are glob (0) or MIME (1) patterns; Rune's filters are extensions. +/// The portal rejects filters with an empty name or an empty pattern list. +pub(super) fn filters(options: &FileDialogOptions) -> Vec<Filter> { + options.filters.iter().filter(|(_, extensions)| !extensions.is_empty()).map(|(name, extensions)| { + let patterns: Vec<_> = extensions.iter().map(|ext| (0, glob(ext))).collect(); + let label = if name.is_empty() { + patterns.iter().map(|(_, g)| g.as_str()).collect::<Vec<_>>().join(", ") + } else { + name.clone() + }; + (label, patterns) + }).collect() +} +fn glob(extension: &str) -> String { + let ext = extension.trim_start_matches('*').trim_start_matches('.'); + if ext.is_empty() || ext == "*" { "*".into() } else { format!("*.{ext}") } +} + +/// The portal takes folders as NUL-terminated bytes with no interior NULs. +pub(super) fn path_bytes(path: &Path) -> Option<Vec<u8>> { + let bytes = path.as_os_str().as_bytes(); + (!bytes.is_empty() && !bytes.contains(&0)).then(|| { + let mut out = Vec::with_capacity(bytes.len() + 1); + out.extend_from_slice(bytes); + out.push(0); + out + }) +} + +/// The `Response` signal: 0 is a choice, 1 a cancelled dialog, 2 a dialog that ended another +/// way (for example closed with its parent), which is also no choice. +pub(super) fn outcome(status: u32, uris: &[String]) -> Result<Option<PathBuf>, FileDialogError> { + match status { + 0 => uris.first().map(|uri| uri_path(uri)).transpose(), + 1 | 2 => Ok(None), + n => Err(FileDialogError(format!("file dialog portal response {n}"))), + } +} + +/// A local `file://` URI as a path, percent-decoded to raw bytes. +pub(super) fn uri_path(uri: &str) -> Result<PathBuf, FileDialogError> { + let invalid = || FileDialogError(format!("file dialog returned a non-local URI: {uri}")); + let rest = uri.strip_prefix("file://").ok_or_else(invalid)?; + let path = match rest.find('/') { + Some(0) => rest, + Some(at) if rest[..at].eq_ignore_ascii_case("localhost") => &rest[at..], + _ => return Err(invalid()), + }; + let bytes = path.split(['?', '#']).next().unwrap_or_default().as_bytes(); + let hex = |b: u8| (b as char).to_digit(16).map(|d| d as u8); + let mut out = Vec::with_capacity(bytes.len()); + let mut i = 0; + while i < bytes.len() { + if bytes[i] == b'%' && i + 2 < bytes.len() + && let (Some(hi), Some(lo)) = (hex(bytes[i + 1]), hex(bytes[i + 2])) { + out.push(hi << 4 | lo); + i += 3; + } else { + out.push(bytes[i]); + i += 1; + } + } + Ok(PathBuf::from(std::ffi::OsString::from_vec(out))) +} + +#[cfg(test)] +mod tests { + use super::*; + fn uris(list: &[&str]) -> Vec<String> { list.iter().map(|s| (*s).into()).collect() } + #[test] + fn chosen_uris_become_percent_decoded_paths() { + assert_eq!(outcome(0, &uris(&["file:///home/a/My%20Export%20%E5%BD%95.csv"])).unwrap(), + Some(PathBuf::from("/home/a/My Export 录.csv"))); + assert_eq!(outcome(0, &uris(&["file://localhost/tmp/a%2fb", "file:///tmp/second"])).unwrap(), + Some(PathBuf::from("/tmp/a/b"))); + assert_eq!(outcome(0, &uris(&["file://LOCALHOST/tmp/a"])).unwrap(), Some(PathBuf::from("/tmp/a"))); + assert_eq!(outcome(0, &[]).unwrap(), None); + // A malformed or truncated escape stays literal. + assert_eq!(uri_path("file:///tmp/100%").unwrap(), PathBuf::from("/tmp/100%")); + assert_eq!(uri_path("file:///tmp/1%2").unwrap(), PathBuf::from("/tmp/1%2")); + assert_eq!(uri_path("file:///tmp/%zz").unwrap(), PathBuf::from("/tmp/%zz")); + // Non-UTF-8 names survive as bytes. + assert_eq!(uri_path("file:///tmp/%FF").unwrap().as_os_str().as_bytes(), b"/tmp/\xff"); + assert!(uri_path("file://server/share/a").is_err()); + assert!(uri_path("https://example.com/a").is_err()); + } + #[test] + fn cancelled_or_ended_dialog_is_no_choice() { + assert_eq!(outcome(1, &uris(&["file:///tmp/a"])).unwrap(), None); + assert_eq!(outcome(2, &[]).unwrap(), None); + assert!(outcome(3, &[]).is_err()); + } + #[test] + fn filters_folders_and_parents_use_portal_formats() { + let options = FileDialogOptions::default() + .filter("Exports", &["csv", ".json", "*.txt"]) + .filter("Empty", &[]) + .filter("", &["wav"]) + .filter("All files", &["*"]); + assert_eq!(filters(&options), vec![ + ("Exports".to_string(), vec![(0, "*.csv".to_string()), (0, "*.json".to_string()), (0, "*.txt".to_string())]), + ("*.wav".to_string(), vec![(0, "*.wav".to_string())]), + ("All files".to_string(), vec![(0, "*".to_string())]), + ]); + assert_eq!(path_bytes(Path::new("/home/a/Downloads")).as_deref(), Some(&b"/home/a/Downloads\0"[..])); + assert_eq!(path_bytes(Path::new("")), None); + assert_eq!(path_bytes(Path::new("/tmp/a\0b")), None); + assert_eq!(parent_window(0), ""); + assert_eq!(parent_window(0x3a0000f), "x11:3a0000f"); + } +} diff --git a/app/vendor/rune/crates/rune/src/file_dialog/tests.rs b/app/vendor/rune/crates/rune/src/file_dialog/tests.rs new file mode 100644 index 0000000..ab278c2 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/file_dialog/tests.rs @@ -0,0 +1,156 @@ +use super::*; +#[test] +fn scripted_dialogs_preserve_order_unicode_paths_and_cancellation() { + let path = PathBuf::from("/fixture/录音.wav"); + let dialogs = FileDialogs::scripted([ + ScriptedFileDialog { kind: FileDialogKind::Open, path: Some(path.clone()) }, + ScriptedFileDialog { kind: FileDialogKind::Save, path: None }, + ScriptedFileDialog { kind: FileDialogKind::Folder, path: Some("/fixture/Projects".into()) }, + ]); + let options = FileDialogOptions::default().filter("Audio", &["wav", "flac"]); + assert!(pollster::block_on(dialogs.save(options.clone())).is_err()); + assert_eq!(pollster::block_on(dialogs.open(options.clone())).unwrap(), Some(path)); + assert_eq!(pollster::block_on(dialogs.clone().save(options.clone())).unwrap(), None); + assert!(pollster::block_on(dialogs.open(options.clone())).is_err(), "a folder fixture doesn't answer an Open"); + assert_eq!(pollster::block_on(dialogs.open_folder(options.clone())).unwrap(), Some("/fixture/Projects".into())); + assert!(pollster::block_on(dialogs.open(options)).is_err()); +} + +use crate::{Cx, El, Env, Runtime, el}; + +#[derive(Default)] +struct Import { answers: Vec<Result<Option<PathBuf>, String>> } + +fn import(_: &Import, _: &mut Cx<Import>) -> El { + el().key("import").size(80.0, 20.0).on_press_tx(|_: &mut Import, tx: &mut Tx| { + let options = FileDialogOptions { title: "Import".into(), ..Default::default() }.filter("Export", &["json"]); + tx.open_file(options, |s: &mut Import, result, _| s.answers.push(result.map_err(|e| e.0))); + }) +} + +fn press(rt: &mut Runtime<Import>) { + rt.pointer_down(10.0, 10.0); + rt.pointer_up(10.0, 10.0); + rt.frame(1.0 / 60.0); +} + +#[test] +fn a_handlers_dialog_waits_open_and_its_answer_runs_on_a_later_frame() { + let mut rt = Runtime::new(Import::default(), import, (200.0, 100.0), Env::new(true, 1.0)); + rt.frame(0.0); + press(&mut rt); + let (kind, options) = rt.file_dialog().expect("the press asked for a dialog"); + assert_eq!((kind, options.title.as_str(), options.filters.as_slice()), (FileDialogKind::Open, "Import", &[("Export".to_owned(), vec!["json".to_owned()])][..])); + assert_eq!(rt.file_dialog_json().unwrap(), serde_json::json!({ "kind": "open", "title": "Import", "filters": [{ "name": "Export", "extensions": ["json"] }] })); + rt.frame(2.0 / 60.0); + assert!(rt.state.answers.is_empty() && rt.file_dialog().is_some(), "it stays open across frames"); + + rt.resolve_file_dialog(Some("/exports/录音.json".into())).unwrap(); + assert!(rt.file_dialog().is_none() && rt.state.answers.is_empty(), "closed; the answer waits for a frame"); + assert!(rt.has_pending_input(), "so the host draws one"); + rt.frame(3.0 / 60.0); + assert_eq!(rt.state.answers, [Ok(Some("/exports/录音.json".into()))]); + + press(&mut rt); + rt.resolve_file_dialog(None).unwrap(); + rt.frame(5.0 / 60.0); + assert_eq!(rt.state.answers[1], Ok(None), "cancelling answers None"); + assert!(rt.resolve_file_dialog(None).is_err(), "nothing is open"); +} + +#[test] +fn a_folder_dialog_waits_open_as_a_folder_and_answers_with_the_folder() { + fn view(_: &Import, _: &mut Cx<Import>) -> El { + el().key("open").size(80.0, 20.0).on_press_tx(|_: &mut Import, tx: &mut Tx| { + let options = FileDialogOptions { title: "Open Project".into(), directory: Some("/work".into()), ..Default::default() }; + tx.open_folder(options, |s: &mut Import, result, _| s.answers.push(result.map_err(|e| e.0))); + }) + } + let mut rt = Runtime::new(Import::default(), view, (200.0, 100.0), Env::new(true, 1.0)); + rt.frame(0.0); + press(&mut rt); + assert_eq!(rt.file_dialog().map(|(kind, o)| (kind, o.title.clone())), Some((FileDialogKind::Folder, "Open Project".into()))); + assert_eq!(rt.file_dialog_json().unwrap(), serde_json::json!({ "kind": "folder", "title": "Open Project", "filters": [], "directory": "/work" })); + rt.resolve_file_dialog(Some("/work/notes".into())).unwrap(); + rt.frame(2.0 / 60.0); + assert_eq!(rt.state.answers, [Ok(Some("/work/notes".into()))]); +} + +#[test] +fn a_second_dialog_while_one_is_open_is_refused_and_the_first_stays() { + let mut rt = Runtime::new(Import::default(), import, (200.0, 100.0), Env::new(true, 1.0)); + rt.frame(0.0); + press(&mut rt); + press(&mut rt); + rt.frame(3.0 / 60.0); + assert_eq!(rt.state.answers, [Err("a file dialog is already open".to_owned())]); + rt.update(|_, tx| tx.save_file(FileDialogOptions::default(), |s: &mut Import, result, _| s.answers.push(result.map_err(|e| e.0)))); + rt.frame(4.0 / 60.0); + assert_eq!(rt.state.answers.len(), 2, "an update's dialog too"); + assert_eq!(rt.file_dialog().map(|(kind, _)| kind), Some(FileDialogKind::Open)); + rt.resolve_file_dialog(Some("a.json".into())).unwrap(); + rt.frame(5.0 / 60.0); + assert_eq!(rt.state.answers[2], Ok(Some("a.json".into()))); + + rt.update(|_, tx| tx.save_file(FileDialogOptions { file_name: Some("out.json".into()), ..Default::default() }, |s: &mut Import, result, _| s.answers.push(result.map_err(|e| e.0)))); + assert_eq!(rt.file_dialog().map(|(kind, o)| (kind, o.file_name.clone())), Some((FileDialogKind::Save, Some("out.json".into()))), "once it closed the next opens"); +} + +#[test] +fn a_host_shows_the_dialog_once_and_answers_it_by_id() { + let mut rt = Runtime::new(Import::default(), import, (200.0, 100.0), Env::new(true, 1.0)); + rt.frame(0.0); + press(&mut rt); + let (id, kind, _) = rt.take_file_dialog().expect("the host takes it"); + assert_eq!(kind, FileDialogKind::Open); + assert!(rt.take_file_dialog().is_none(), "showing, so not taken again"); + rt.answer_file_dialog(id, Err(FileDialogError("no portal".into()))); + rt.frame(2.0 / 60.0); + assert_eq!(rt.state.answers, [Err("no portal".to_owned())]); + + press(&mut rt); + rt.refuse_file_dialog("unsupported"); + rt.frame(4.0 / 60.0); + assert_eq!(rt.state.answers[1], Err("unsupported".to_owned()), "a host without dialogs refuses it"); +} + +#[test] +fn an_overlay_refuses_file_dialogs() { + let mut rt = Runtime::new(Import::default(), import, (200.0, 100.0), Env::new(true, 1.0)); + rt.host.native_overlay = true; + rt.frame(0.0); + press(&mut rt); + assert!(rt.file_dialog().is_none(), "overlays never leave a dialog pending"); + assert!(rt.keys_queued(), "hidden_input delivers the refusal without waiting for a show"); + rt.frame(2.0 / 60.0); + assert_eq!(rt.state.answers, [Err("overlays cannot open file dialogs".to_owned())]); +} + +#[test] +fn closing_or_hiding_cancels_open_and_queued_file_dialogs() { + let mut rt = Runtime::new(Import::default(), import, (200.0, 100.0), Env::new(true, 1.0)); + rt.frame(0.0); + rt.update(|_, tx| { + tx.open_file(FileDialogOptions::default(), |s: &mut Import, result, tx| { + s.answers.push(result.map_err(|e| e.0)); + tx.save_file(FileDialogOptions::default(), |s: &mut Import, follow, _| { + s.answers.push(follow.map_err(|e| e.0)); + }); + }); + tx.save_file(FileDialogOptions::default(), |s: &mut Import, result, _| { + s.answers.push(result.map_err(|e| e.0)); + }); + }); + assert!(rt.file_dialog().is_some()); + rt.cancel_file_dialogs(); + assert!(rt.file_dialog().is_none()); + assert_eq!( + rt.state.answers, + [ + Err("a file dialog is already open".to_owned()), + Ok(None), + Ok(None), + ], + "queued answers, the open dialog, and a dialog asked for in its callback all settle before the host drops" + ); +} diff --git a/app/vendor/rune/crates/rune/src/flight.rs b/app/vendor/rune/crates/rune/src/flight.rs new file mode 100644 index 0000000..dc90f5e --- /dev/null +++ b/app/vendor/rune/crates/rune/src/flight.rs @@ -0,0 +1,198 @@ +//! `Tx::fly_text` and `Tx::launch` requests, and the text handoff in screen coordinates. The destination is measured after growth and scroll +//! each frame. One analytic growth-spring progress interpolates source to live destination, +//! so the copy joins the bubble without a second spring lagging behind scroll follow. + +use rune_motion::{Animated, PropClass, Rect}; +use crate::growth::GROWTH; +use crate::render::Instance; +use crate::Tx; + +impl Tx { + /// Fly the visible text of an existing keyed field to a newly mounted keyed text node. + /// The runtime captures the previous presentation and measures the live destination each + /// frame, after row growth and scroll. Either side is a key unique in the view, or a key + /// path such as `"msg-42/body"`: the `body` text whose nearest keyed ancestor is `msg-42`, + /// so every row can reuse the same local keys. + pub fn fly_text(&mut self, source: impl Into<String>, destination: impl Into<String>) { + self.text_flights.push((source.into(), destination.into())); + } + + /// Launch an element that mounts in this commit from where another element's text shows, + /// as a sent message leaves its composer. The element keyed `destination` starts with its + /// first text on `source`'s text, at its own size, and travels one straight screen path to + /// its place on the `tok::motion::REFLOW` spring (or the commit's [`Tx::motion`]). Until it + /// lands it draws above the whole window and outside every clip, so it can rise out of a + /// panel into a scroll view; the source can clear in the same commit. Keys and key paths + /// work as in [`Tx::fly_text`]. Under Reduce Motion, or when the destination was already + /// mounted, it does nothing. + pub fn launch(&mut self, source: impl Into<String>, destination: impl Into<String>) { + self.launches.push((source.into(), destination.into())); + } + + /// The `El::matched` flights this change starts draw outside every clip until they land, as + /// a [`Tx::launch`] does, rather than inside their destinations' clips: for elements that + /// move between parts of the window that clip them, as tabs moving from a titlebar's strip + /// into a sidebar that opens as they land, where a clip would hide them for most of the way. + pub fn unclipped_flights(&mut self) { + self.unclipped_flights = true; + } +} + +pub(crate) struct TextFlight { + pub source_key: String, + pub target_key: String, + pub source: Rect, + pub source_clip: [f32; 4], + pub glyphs: Vec<Instance>, + pub scale: f32, + pub destination: Rect, + progress: Animated<f32>, + born: f64, + pub presented: Rect, + pub clip: [f32; 4], + pub source_alpha: f32, + pub target_alpha: f32, +} + +impl TextFlight { + pub fn new(source_key: String, target_key: String, source: Rect, source_clip: [f32; 4], glyphs: Vec<Instance>, scale: f32, now: f64) -> Self { + let mut progress = Animated::new(0.0).with_class(PropClass::Opacity); + progress.animate_to(1.0, GROWTH, now); + Self { source_key, target_key, source, source_clip, glyphs, scale, + destination: source, progress, born: now, presented: source, + clip: source_clip, source_alpha: 1.0, target_alpha: 0.0 } + } + + pub fn progress(&self, now: f64, reduced: bool) -> f32 { + if reduced { ((now - self.born) / 0.15).clamp(0.0, 1.0) as f32 } + else { self.progress.sample(now).clamp(0.0, 1.0) } + } + + pub fn measure(&mut self, target: Rect, now: f64, reduced: bool) -> bool { + self.destination = target; + let p = if reduced { 1.0 } else { self.progress(now, false) }; + let from = self.source; + self.presented = Rect::new(from.x + (target.x - from.x) * p, from.y + (target.y - from.y) * p, + from.w + (target.w - from.w) * p, from.h + (target.h - from.h) * p); + if reduced { self.progress(now, true) >= 1.0 } else { self.progress.is_settled(now) } + } + + /// The node at `path` keyed `key` is this flight's source. + pub fn departs(&self, path: &str, key: Option<&str>) -> bool { + selects(&self.source_key, path, key) + } + + /// The node at `path` keyed `key` is this flight's destination. + pub fn lands(&self, path: &str, key: Option<&str>) -> bool { + selects(&self.target_key, path, key) + } + + pub fn alphas(&self, target: Rect, now: f64, reduced: bool) -> (f32, f32) { + let p = self.progress(now, reduced); + if reduced { return (1.0 - p, p); } + let rewrap = (target.h - self.source.h).abs() > 2.0; + let (out, end) = if rewrap { (0.25, 0.4) } else { (0.4, 0.5) }; + ((1.0 - p / out).clamp(0.0, 1.0), + if rewrap { ((p - 0.1) / (end - 0.1)).clamp(0.0, 1.0) } else { (p / end).clamp(0.0, 1.0) }) + } +} + +/// Whether `selector` names the node at `path` keyed `key`: either its key, or a key path such +/// as `msg-42/body` whose leading keys are the node's nearest keyed ancestors (unkeyed ones are +/// skipped), so repeated row-local keys can be told apart. +pub(crate) fn selects(selector: &str, path: &str, key: Option<&str>) -> bool { + let Some(key) = key else { return false }; + if selector == key { return true; } + let Some(scope) = selector.strip_suffix(key).and_then(|s| s.strip_suffix('/')) else { return false }; + let Some(above) = path.strip_suffix(key).and_then(|s| s.strip_suffix('/')) else { return false }; + let mut keyed = above.rsplit('/').filter(|seg| !seg.starts_with('#')); + scope.rsplit('/').all(|seg| keyed.next() == Some(seg)) +} + +/// Whether `selector` names a highlight keyed `key` in the text at `path`: [`selects`] for +/// `{path}/{key}`, without building it. +pub(crate) fn selects_under(selector: &str, path: &str, key: &str) -> bool { + if selector == key { return true; } + let Some(scope) = selector.strip_suffix(key).and_then(|s| s.strip_suffix('/')) else { return false }; + let mut keyed = path.rsplit('/').filter(|seg| !seg.starts_with('#')); + scope.rsplit('/').all(|seg| keyed.next() == Some(seg)) +} + +/// Transform glyph geometry without changing its atlas footprint. Clip edges share the same +/// transform; a soft inset handles lines that were only partly visible in the source editor. +pub(crate) fn transformed(mut q: Instance, from: Rect, to: Rect, scale: f32, alpha: f32, clip: [f32; 4], fade: [f32; 4]) -> Instance { + let zoom = to.w / from.w.max(0.01); + let map = |v: f32, from: f32, to: f32| (to + (v / scale - from) * zoom) * scale; + if q.kind() == Some(crate::render::Kind::Glyph) && q.radii[3] > 0.0 { + // An outline glyph (`text::Outline`) moves its pen and magnifies its pixel: crisp in flight. + q.radii = [map(q.radii[0], from.x, to.x), map(q.radii[1], from.y, to.y), q.radii[2], q.radii[3] * zoom]; + } else { + q.uv[2] = q.rect[2]; + q.uv[3] = q.rect[3]; + } + q.rect = [ + (to.x + (q.rect[0] / scale - from.x) * zoom) * scale, + (to.y + (q.rect[1] / scale - from.y) * zoom) * scale, + q.rect[2] * zoom, + q.rect[3] * zoom, + ]; + q.fill = q.fill.map(|v| v * alpha); + q.clip = clip.map(|v| v * scale); + q.fade = crate::render::pack_fade(fade.map(|v| (v * scale).clamp(-65504.0, 65504.0)), q.clip, q.clip); + q +} + +#[cfg(test)] +mod tests { + use super::*; + + fn flight() -> TextFlight { + TextFlight::new("source".into(), "target".into(), Rect::new(40.0, 400.0, 500.0, 40.0), + [40.0, 400.0, 540.0, 440.0], Vec::new(), 2.0, 0.0) + } + + #[test] + fn moving_destination_uses_shared_progress_without_restarting_it() { + let mut f = flight(); + f.measure(Rect::new(120.0, 260.0, 400.0, 22.0), 0.0, false); + let p = f.progress.sample(0.08); + let v = f.progress.velocity(0.08); + f.measure(Rect::new(120.0, 220.0, 400.0, 22.0), 0.08, false); + assert_eq!(f.progress.sample(0.08), p); + assert_eq!(f.progress.velocity(0.08), v); + assert_eq!(f.presented.y, 400.0 + (220.0 - 400.0) * p); + assert!(f.measure(Rect::new(120.0, 220.0, 400.0, 22.0), 2.0, false)); + } + + #[test] + fn flight_is_time_based_and_reduced_motion_only_fades() { + let target = Rect::new(120.0, 260.0, 400.0, 22.0); + let mut slow = flight(); + let mut fast = flight(); + slow.measure(target, 0.0, false); + fast.measure(target, 0.0, false); + for i in 1..=30 { + slow.measure(target, i as f64 / 30.0, false); + for j in (i * 4 - 3)..=i * 4 { fast.measure(target, j as f64 / 120.0, false); } + assert_eq!(slow.presented, fast.presented); + } + let mut f = flight(); + assert!(!f.measure(target, 0.075, true)); + assert_eq!(f.presented, target); + assert_eq!(f.alphas(target, 0.075, true), (0.5, 0.5)); + assert!(f.measure(target, 0.15, true)); + } + + #[test] + fn selectors_match_a_key_or_its_keyed_ancestors() { + let path = "#0/scroll/#0/msg-42/#1/body"; + assert!(selects("body", path, Some("body")), "a plain key still matches"); + assert!(selects("msg-42/body", path, Some("body")), "unkeyed wrappers are skipped"); + assert!(selects("scroll/msg-42/body", path, Some("body"))); + assert!(!selects("msg-41/body", path, Some("body"))); + assert!(!selects("scroll/body", path, Some("body")), "the scope is the nearest keyed ancestors"); + assert!(!selects("msg-42", path, Some("body"))); + assert!(!selects("body", "#0/#1", None), "unkeyed nodes never match"); + assert!(!selects("x/msg-42/body", path, Some("body")), "more scope than ancestors"); + } +} diff --git a/app/vendor/rune/crates/rune/src/frame.rs b/app/vendor/rune/crates/rune/src/frame.rs new file mode 100644 index 0000000..0f24843 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/frame.rs @@ -0,0 +1,11 @@ +pub(crate) mod clock; +pub(crate) mod encoded; +pub(crate) mod host_clock; +pub(crate) mod host_step; +#[cfg(feature = "frame-profile")] +pub(crate) mod live_log; +pub(crate) mod present_time; +#[cfg(target_os = "macos")] +pub(crate) mod present_worker; +pub(crate) mod profile; +pub(crate) mod surface_stats; diff --git a/app/vendor/rune/crates/rune/src/frame/clock.rs b/app/vendor/rune/crates/rune/src/frame/clock.rs new file mode 100644 index 0000000..d6c9fd8 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/frame/clock.rs @@ -0,0 +1,203 @@ +//! How far each presented frame moves animation time. Windows, overlays and the headless hosts +//! share this rule so they can't drift apart. +//! +//! Like Core Animation, a late frame never loses time: motion already running advances by the +//! real gap between this frame's target presentation time and the previous frame's, so after +//! a 49 ms hitch it is where an unbroken cadence would have it. Motion that starts or is +//! retargeted on the frame starts at the frame's time and shows one small step, so it never +//! jumps by the gap. Both happen in one runtime pass ([`Runtime::frame_split`]). +//! +//! A frame can be late because of what it did itself: a commit that took 50 ms presents the +//! motion it started 50 ms after its target. That motion then starts from when it showed, as +//! Core Animation starts what a transaction adds when the transaction commits: the next frame +//! moves it one frame on rather than charging it the overrun ([`FrameClock::presented`]). + +use crate::machine::Effects; +use crate::time::Instant; +use rune_motion::TrackId; +#[cfg(test)] +use crate::runtime::Runtime; +use crate::runtime::{AppDriver, RuntimeCore}; + +/// The most a frame steps motion it starts. Its first frame shows one 120 Hz frame of movement, +/// instead of repeating its start pose or jumping ahead by a late frame's gap or the time +/// spent idle. +pub(crate) const RESUME_STEP: f64 = 1.0 / 120.0; + +/// The longest gap, in seconds, charged to running motion. A hitch someone sees lasts a few +/// frames; 250 ms is 30 frames at 120 Hz, past any hitch worth keeping time through and still +/// shorter than a typical spring takes to settle. A longer gap means the host was suspended +/// (App Nap, a debugger, sleep, a stalled main thread), hidden or occluded, so running motion +/// moves at most this far rather than teleporting to its end. +pub(crate) const MAX_GAP: f64 = 0.25; + +#[derive(Clone, Copy, Debug, PartialEq)] +pub(crate) struct Step { + /// Charged only to motion already running, before this frame's commits. + pub catch_up: f64, + /// This frame's step for all motion, including what its commits start. + pub dt: f64, +} + +impl Step { + pub(crate) fn total(self) -> f64 { + self.catch_up + self.dt + } +} + +/// The step for a frame `gap` seconds after the last. `running`: motion was still running +/// after the previous frame. Running motion gets the whole gap, at most [`MAX_GAP`]; what +/// starts on the frame gets at most [`RESUME_STEP`] of it. With nothing running the frame +/// steps [`RESUME_STEP`], so motion it starts moves one frame, however long the idle. +pub(crate) fn split(gap: f64, running: bool) -> Step { + if !running { return Step { catch_up: 0.0, dt: RESUME_STEP }; } + let total = gap.clamp(0.0, MAX_GAP); + let dt = total.min(RESUME_STEP); + Step { catch_up: total - dt, dt } +} + +/// Steps `rt` by a frame `gap` seconds after the last, for hosts without presentation times +/// (the hot loop). Without a wall clock, timers and poll still see the +/// whole gap. +#[cfg(any(test, feature = "hot"))] +pub(crate) fn advance_by_core(rt: &mut RuntimeCore, app: &mut dyn AppDriver, gap: f64) -> bool { + let step = split(gap, rt.animating); + rt.clock += (gap - step.total()).max(0.0); + rt.frame_split(app, step.catch_up, step.dt) +} + +#[cfg(test)] +#[inline(always)] +pub(crate) fn advance_by<S: 'static>(rt: &mut Runtime<S>, gap: f64) -> bool { + let (core, mut app) = rt.split_mut(); + advance_by_core(core, &mut app, gap) +} + +#[derive(Debug)] +pub(crate) struct FrameClock { + phase: Phase, + /// Recycle the allocation between frames. Only Stepped owns pending starts. + spare: Vec<TrackId>, +} + +#[derive(Debug)] +enum Phase { + Idle { last: Instant }, + Stepped { last: Instant, starts: Vec<TrackId> }, + Presented { last: Instant }, +} + +enum Event { + Hold(Instant), + Advance { at: Instant, running: bool }, + Present(Instant), +} + +enum Effect<'a> { + Frame(Step, &'a mut Vec<TrackId>), + Delay(f64, &'a mut [TrackId]), +} + +impl FrameClock { + pub(crate) fn new(now: Instant) -> Self { + Self { phase: Phase::Idle { last: now }, spare: Vec::new() } + } + + /// The target time of the last frame the clock stepped to. + pub(crate) fn last(&self) -> Instant { + match self.phase { + Phase::Idle { last } | Phase::Stepped { last, .. } | Phase::Presented { last } => last, + } + } + + #[inline] + fn step(&mut self, event: Event) -> Effects<Effect<'_>> { + let last = self.last(); + match event { + Event::Hold(at) => { + if let Phase::Stepped { starts, .. } = &mut self.phase { + self.spare = std::mem::take(starts); + } + self.phase = Phase::Idle { last: last.max(at) }; + Effects::none() + } + Event::Advance { at, running } => { + let gap = at.saturating_duration_since(last).as_secs_f64(); + let last = last.max(at); + if let Phase::Stepped { last: target, .. } = &mut self.phase { + *target = last; + } else { + self.phase = Phase::Stepped { last, starts: std::mem::take(&mut self.spare) }; + } + let Phase::Stepped { starts, .. } = &mut self.phase else { unreachable!() }; + starts.clear(); + Effects::one(Effect::Frame(split(gap, running), starts)) + } + Event::Present(done) => { + let Phase::Stepped { starts, .. } = &mut self.phase else { return Effects::none() }; + self.spare = std::mem::take(starts); + self.phase = Phase::Presented { last }; + if self.spare.is_empty() { return Effects::none(); } + let late = done.saturating_duration_since(last).as_secs_f64().min(MAX_GAP); + if late > 0.0 { Effects::one(Effect::Delay(late, &mut self.spare)) } else { Effects::none() } + } + } + } + + /// A frame at `at` that steps no time (prewarm, hidden), or one that caught motion up to + /// `at`. Display-link targets run ahead of `Instant::now()`, so the clock never goes back. + pub(crate) fn hold(&mut self, at: Instant) { + self.step(Event::Hold(at)); + } + + /// The step for a frame presented at `at`. See [`split`]. + fn begin(&mut self, at: Instant, running: bool) -> (Step, &mut Vec<TrackId>) { + let Effects::One(Effect::Frame(step, starts)) = self.step(Event::Advance { at, running }) else { unreachable!() }; + (step, starts) + } + + pub(crate) fn frame_step(&mut self, at: Instant, running: bool) -> Step { + self.begin(at, running).0 + } + + /// Steps `rt` to the frame presented at `at`, in one runtime pass. `compositing`: a + /// compositor's own animation was still running after the previous frame. Returns whether + /// anything still animates and the seconds stepped. + #[cfg(test)] + #[inline(always)] + pub(crate) fn advance<S: 'static>(&mut self, rt: &mut Runtime<S>, at: Instant, compositing: bool) -> (bool, f64) { + let (core, mut app) = rt.split_mut(); + self.advance_core(core, &mut app, at, compositing) + } + + pub(crate) fn advance_core(&mut self, rt: &mut RuntimeCore, app: &mut dyn AppDriver, at: Instant, compositing: bool) -> (bool, f64) { + let (step, starts) = self.begin(at, rt.animating || compositing); + rt.frame.set_frame_target(at); + let animating = rt.frame_split(app, step.catch_up, step.dt); + starts.extend_from_slice(rt.scene.store().started()); + (animating, step.total()) + } + + /// The frame last stepped to finished at `done`. When that's past its target, the motion it + /// started holds its first pose for the overrun, so the next frame moves it about a frame + /// rather than by how late this one was. Motion already running keeps real time. + #[cfg(test)] + #[inline(always)] + pub(crate) fn presented<S: 'static>(&mut self, rt: &mut Runtime<S>, done: Instant) { + self.presented_core(rt.core_mut(), done); + } + + pub(crate) fn presented_core(&mut self, rt: &mut RuntimeCore, done: Instant) { + if let Effects::One(Effect::Delay(late, starts)) = self.step(Event::Present(done)) { + rt.scene.store_mut().delay(starts, late * f64::from(rt.time_scale)); + } + } +} + +#[cfg(test)] +#[path = "clock_walk_tests.rs"] +mod walk_tests; + +#[cfg(test)] +#[path = "clock_tests.rs"] +mod tests; diff --git a/app/vendor/rune/crates/rune/src/frame/clock_tests.rs b/app/vendor/rune/crates/rune/src/frame/clock_tests.rs new file mode 100644 index 0000000..1a25f4d --- /dev/null +++ b/app/vendor/rune/crates/rune/src/frame/clock_tests.rs @@ -0,0 +1,224 @@ +use super::*; +use crate::{Cx, El, Env}; +use std::time::Duration; + +const FRAME: Duration = Duration::from_micros(16_667); + +#[test] +fn running_motion_keeps_real_time_and_new_motion_takes_one_small_step() { + let start = crate::time::now(); + let ms = |n: u64| Duration::from_millis(n); + let mut clock = FrameClock::new(start); + let fresh = Step { catch_up: 0.0, dt: RESUME_STEP }; + assert_eq!(clock.frame_step(start + ms(5), false), fresh, "first frame"); + assert_eq!(clock.frame_step(start + ms(2005), false), fresh, "after idle, however long"); + let late = clock.frame_step(start + ms(2054), true); + assert!((late.total() - 0.049).abs() < 1e-9 && late.dt == RESUME_STEP, "a late running frame keeps its time: {late:?}"); + let short = clock.frame_step(start + ms(2058), true); + assert!((short.dt - 0.004).abs() < 1e-9 && short.catch_up == 0.0, "a short frame steps its gap: {short:?}"); + let suspended = clock.frame_step(start + ms(5058), true); + assert!((suspended.total() - MAX_GAP).abs() < 1e-9 && suspended.dt == RESUME_STEP, + "a suspension moves running motion at most MAX_GAP: {suspended:?}"); + clock.hold(start + ms(6000)); + assert_eq!(clock.frame_step(start + ms(6000), true), Step { catch_up: 0.0, dt: 0.0 }); + // A display-link target ran ahead; a later `now` before it must not rewind the clock. + clock.hold(start + ms(6010)); + clock.hold(start + ms(6002)); + let next = clock.frame_step(start + ms(6018), true); + assert!((next.total() - 0.008).abs() < 1e-9, "the gap counts from the latest target: {next:?}"); +} + +#[derive(Clone, Copy, Default)] +struct Pair { a: f32, b: f32, polls: u32 } + +/// `a` and `b` stack in a column, so both share x and snap alike. +fn view(s: &Pair, _: &mut Cx<Pair>) -> El { + crate::col().children([crate::el().key("a").size(s.a, 8.0), crate::el().key("b").size(s.b, 8.0)]) +} + +fn runtime() -> Runtime<Pair> { + let mut rt = Runtime::new(Pair { a: 12.0, b: 12.0, polls: 0 }, view, (400.0, 50.0), Env::default()); + rt.poll = Some(|s, _, _| { s.polls += 1; false }); + rt +} + +fn width(rt: &Runtime<Pair>, key: &str) -> f32 { + rt.presented(key).unwrap().0[2] +} + +/// The window host's path: `a` springs from `FRAME`, frames present at `times` and `on` +/// runs just before the frame at `at`. Returns `(time, a, b)` after each frame. +fn run(times: &[Duration], at: Duration, on: fn(&mut Runtime<Pair>)) -> Vec<(Duration, f32, f32)> { + let start = crate::time::now(); + let mut clock = FrameClock::new(start); + let mut rt = runtime(); + times.iter().map(|&t| { + if t == FRAME { rt.update(|s, _| s.a = 212.0); } + if t == at { on(&mut rt); } + clock.advance(&mut rt, start + t, false); + (t, width(&rt, "a"), width(&rt, "b")) + }).collect() +} + +fn at(frames: &[(Duration, f32, f32)], t: Duration) -> (f32, f32) { + frames.iter().find(|f| f.0 == t).map(|f| (f.1, f.2)).unwrap() +} + +const LATE: Duration = Duration::from_micros(6 * 16_667 + 49_300); + +fn cadence() -> Vec<Duration> { + (0..=6).map(|k| k * FRAME).collect() +} + +#[test] +fn window_late_frame_lands_where_an_unbroken_cadence_would() { + let after = [LATE, LATE + FRAME, LATE + 2 * FRAME]; + let mut steady: Vec<_> = (0..=8).map(|k| k * FRAME).collect(); + steady.extend(after); + let mut hitched = cadence(); + hitched.extend(after); + let steady = run(&steady, Duration::MAX, |_| {}); + let hitched = run(&hitched, Duration::MAX, |_| {}); + for t in after { + let (expected, _) = at(&steady, t); + let (got, _) = at(&hitched, t); + assert!(expected < 211.0, "the spring must still be moving at {t:?}: {expected}"); + assert!((got - expected).abs() < 0.01, "at {t:?} width={got}, unbroken cadence={expected}"); + } +} + +#[test] +fn window_motion_starting_after_idle_takes_one_frame_step() { + let first_pose = |idle: Duration| { + let start = crate::time::now(); + let mut clock = FrameClock::new(start); + let mut rt = runtime(); + clock.advance(&mut rt, start, false); + assert!(!clock.advance(&mut rt, start + FRAME, false).0); + rt.update(|s, _| s.b = 212.0); + clock.advance(&mut rt, start + FRAME + idle, false); + width(&rt, "b") + }; + let short = first_pose(FRAME); + let long = first_pose(Duration::from_secs(2)); + assert!(short > 12.0 && short < 20.0, "the first frame shows one step of motion: {short}"); + assert!((long - short).abs() < 0.001, "idle time must not age motion that starts after it: {long} vs {short}"); +} + +#[test] +fn motion_starting_on_a_late_frame_takes_one_small_step_while_running_motion_catches_up() { + let fresh = { + let start = crate::time::now(); + let mut clock = FrameClock::new(start); + let mut rt = runtime(); + clock.advance(&mut rt, start, false); + rt.update(|s, _| s.b = 212.0); + clock.advance(&mut rt, start + FRAME, false); + width(&rt, "b") + }; + let mut plain = cadence(); + plain.push(LATE); + let (expected, _) = at(&run(&plain, Duration::MAX, |_| {}), LATE); + let (a, b) = at(&run(&plain, LATE, |rt| rt.update(|s, _| s.b = 212.0)), LATE); + assert!(expected < 211.0 && (a - expected).abs() < 0.01, "running motion catches up the whole gap: a={a}, expected={expected}"); + assert!((b - fresh).abs() < 0.01, "new motion takes one 1/120 s step, not the 49 ms gap: b={b}, one step={fresh}"); +} + +#[test] +fn motion_a_frame_starts_and_runs_late_on_moves_one_frame_next_while_running_motion_keeps_time() { + // `a` springs from FRAME; `b` starts on the frame at 3 × FRAME, whose own work then runs + // 50 ms past its target. The next frame comes a frame after that. + let overrun = Duration::from_millis(50); + let starts = 3 * FRAME; + let next = starts + overrun + FRAME; + let poses = |late: bool| { + let start = crate::time::now(); + let mut clock = FrameClock::new(start); + let mut rt = runtime(); + for t in [Duration::ZERO, FRAME, 2 * FRAME, starts, next] { + if t == FRAME { rt.update(|s, _| s.a = 212.0); } + if t == starts { rt.update(|s, _| s.b = 212.0); } + clock.advance(&mut rt, start + t, false); + clock.presented(&mut rt, start + t + if late && t == starts { overrun } else { Duration::ZERO }); + } + (width(&rt, "a"), width(&rt, "b")) + }; + let one_frame_on = { + let start = crate::time::now(); + let mut clock = FrameClock::new(start); + let mut rt = runtime(); + clock.advance(&mut rt, start, false); + rt.update(|s, _| s.b = 212.0); + clock.advance(&mut rt, start + FRAME, false); + clock.advance(&mut rt, start + 2 * FRAME, false); + width(&rt, "b") + }; + let (a, b) = poses(true); + let (on_time_a, on_time_b) = poses(false); + assert!((b - one_frame_on).abs() < 0.01, "b moved one frame from its first pose: b={b}, one frame on={one_frame_on}"); + assert!(on_time_b - b > 5.0, "without the overrun, b moves the whole gap: {on_time_b} vs {b}"); + assert!(a < 211.0 && (a - on_time_a).abs() < 0.01, "running motion keeps real time: a={a}, on time={on_time_a}"); +} + +#[test] +fn a_spring_retargeted_on_a_late_frame_turns_from_its_pose_at_that_time() { + let back = |rt: &mut Runtime<Pair>| rt.update(|s, _| s.a = 12.0); + let mut hitched = cadence(); + hitched.extend([LATE, LATE + FRAME, LATE + 2 * FRAME]); + // The same frames with one more presented just before the late one's new-motion step: + // the spring reaches that time on its old curve, then turns. + let turn = LATE - Duration::from_secs_f64(RESUME_STEP); + let mut reference = cadence(); + reference.extend([turn, LATE, LATE + FRAME, LATE + 2 * FRAME]); + let hitched = run(&hitched, LATE, back); + let reference = run(&reference, LATE, back); + for t in [LATE, LATE + FRAME, LATE + 2 * FRAME] { + let (got, _) = at(&hitched, t); + let (expected, _) = at(&reference, t); + assert!((got - expected).abs() < 0.01, "at {t:?} a={got}, turning on its old curve gives {expected}"); + } +} + +#[test] +fn one_presented_frame_is_one_runtime_pass() { + let start = crate::time::now(); + let mut clock = FrameClock::new(start); + let mut rt = runtime(); + let (trace, buffer) = rune_motion::MotionTrace::in_memory(&rune_motion::TraceHeader { + launch: "frames".into(), width: 400.0, height: 50.0, hz: 60.0, scale: 1.0, + }); + rt.scene.set_trace(Some(trace)); + clock.advance(&mut rt, start, false); + rt.update(|s, _| s.a = 212.0); + for k in 1..=3 { clock.advance(&mut rt, start + k * FRAME, false); } + let polls = rt.state.polls; + // `Window::show` settles everything, then the next frame is late with motion running. + rt.settle_all(); + assert!(rt.animating); + clock.advance(&mut rt, start + 3 * FRAME + Duration::from_millis(49), false); + assert_eq!(rt.state.polls - polls, 1, "poll runs once per presented frame"); + assert!(rt.settled, "the settle cut must survive into the presented frame"); + rt.scene.take_trace().unwrap().flush().unwrap(); + let frames = buffer.contents().lines().filter(|line| line.starts_with(r#"{"t":"#)).count(); + assert_eq!(frames, 5, "the motion trace records one frame per presented frame"); +} + +#[test] +fn headless_frames_start_new_motion_with_a_small_step_after_idle() { + let mut rt = runtime(); + rt.frame(0.0); + let clock = rt.clock; + rt.update(|s, _| s.b = 212.0); + advance_by(&mut rt, 1.0); + let b = width(&rt, "b"); + assert!(b > 12.0 && b < 20.0, "a tap after a second of idle starts with one small step: {b}"); + assert!((rt.clock - clock - 1.0).abs() < 1e-9, "timers still see the whole second: {}", rt.clock - clock); + // Then running motion keeps real time. + let mut steady = runtime(); + steady.frame(0.0); + steady.update(|s, _| s.b = 212.0); + steady.frame(RESUME_STEP); + steady.frame(0.049); + advance_by(&mut rt, 0.049); + assert!((width(&rt, "b") - width(&steady, "b")).abs() < 0.01, "a late headless frame keeps its time"); +} diff --git a/app/vendor/rune/crates/rune/src/frame/clock_walk_tests.rs b/app/vendor/rune/crates/rune/src/frame/clock_walk_tests.rs new file mode 100644 index 0000000..34c99b4 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/frame/clock_walk_tests.rs @@ -0,0 +1,100 @@ +use super::*; +use rune_motion::{AnimationStore, NodeId, Prop, PropClass}; +use std::time::Duration; + +#[derive(Clone, Copy, Debug)] +enum Input<'a> { + Hold(Instant), + Advance(Instant, bool, &'a [TrackId]), + Present(Instant), +} + +#[derive(Debug, PartialEq)] +enum Output { + None, + Frame(Step), + Delay(Vec<TrackId>, f64), +} + +// Keep the previous clock's fields and branches independent of the machine, including split. +struct Reference { + last: Instant, + starts: Vec<TrackId>, +} + +impl Reference { + fn hold(&mut self, at: Instant) { + self.last = self.last.max(at); + self.starts.clear(); + } + + fn apply(&mut self, input: Input<'_>) -> Output { + match input { + Input::Hold(at) => { self.hold(at); Output::None } + Input::Advance(at, running, started) => { + let gap = at.saturating_duration_since(self.last).as_secs_f64(); + self.hold(at); + let step = if !running { Step { catch_up: 0.0, dt: 1.0 / 120.0 } } else { + let total = gap.clamp(0.0, 0.25); + let dt = total.min(1.0 / 120.0); + Step { catch_up: total - dt, dt } + }; + self.starts.clear(); + self.starts.extend_from_slice(started); + Output::Frame(step) + } + Input::Present(done) => { + let late = done.saturating_duration_since(self.last).as_secs_f64().min(0.25); + let effect = if late > 0.0 && !self.starts.is_empty() { + Output::Delay(self.starts.clone(), late) + } else { Output::None }; + self.starts.clear(); + effect + } + } + } +} + +#[test] +fn clock_walk_matches_previous_frames() { + let start = crate::time::now(); + let at = |ms| start + Duration::from_millis(ms); + let mut store = AnimationStore::new(); + let x = Prop::<f32>::custom(64, PropClass::Spatial); + let a = store.set(NodeId(1), x, 0.0); + let b = store.set(NodeId(2), x, 0.0); + use Input::*; + let alphabet = [Hold(at(1)), Hold(at(12)), Advance(at(4), true, &[a]), + Advance(at(35), false, &[b, a]), Advance(at(300), true, &[]), + Present(at(4)), Present(at(60)), Present(at(600))]; + for sequence in 0..alphabet.len().pow(5) { + let mut clock = FrameClock::new(start); + let mut reference = Reference { last: start, starts: Vec::new() }; + let mut n = sequence; + for _ in 0..5 { + let input = alphabet[n % alphabet.len()]; + n /= alphabet.len(); + let expected = reference.apply(input); + let got = match input { + Hold(at) => { clock.hold(at); Output::None } + Advance(at, running, started) => { + let (step, starts) = clock.begin(at, running); + starts.extend_from_slice(started); + Output::Frame(step) + } + Present(done) => match clock.step(Event::Present(done)) { + Effects::None => Output::None, + Effects::One(Effect::Delay(late, starts)) => Output::Delay(starts.to_vec(), late), + _ => panic!("unexpected presentation effect"), + }, + }; + assert_eq!(got, expected, "sequence {sequence}, input {input:?}"); + assert_eq!(clock.last(), reference.last, "sequence {sequence}, input {input:?}"); + let pending = match &clock.phase { + Phase::Stepped { starts, .. } => starts.as_slice(), + _ => &[], + }; + assert_eq!(pending, reference.starts, "sequence {sequence}, input {input:?}"); + } + } +} diff --git a/app/vendor/rune/crates/rune/src/frame/encoded.rs b/app/vendor/rune/crates/rune/src/frame/encoded.rs new file mode 100644 index 0000000..41d0bd8 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/frame/encoded.rs @@ -0,0 +1,137 @@ +//! `App::on_frame_encoded`: what each of a window's frames came to, for apps that log their +//! own frame timing. + +use std::rc::Rc; + +use crate::time::Instant; + +/// `App::on_frame_encoded`'s hook. +pub(crate) type OnFrameEncoded = Box<dyn FnMut(&FrameEncoded)>; + +/// `App::on_frame_drawn`'s hook. +pub(crate) type OnFrameDrawn<S> = Box<dyn FnMut(&crate::Runtime<S>)>; + +/// One frame a window ran, as `App::on_frame_encoded` reports it. +#[derive(Clone, Debug)] +pub struct FrameEncoded { + at: Instant, + outcome: FrameOutcome, + window: Option<Rc<str>>, + seq: u64, + presents_at: Option<Instant>, + started: Option<Instant>, + refresh_hz: Option<f64>, + update_ms: Option<f64>, + encode_ms: Option<f64>, +} + +/// What a frame came to. +#[non_exhaustive] +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum FrameOutcome { + /// Encoded and submitted to the GPU, then presented: a visible window's frame, its first + /// frame during creation included, or a hidden launcher's. + Drawn, + /// A frame only a timer asked for, whose build draws what is already on screen: it took + /// no drawable and encoded nothing. + Unchanged, + /// Due but not drawn: the window is covered, minimised or occluded, or no drawable came in + /// time. The runtime may still have stepped. + Skipped, +} + +impl FrameEncoded { + /// For `Drawn`, when encoding finished: right after the frame's commands were submitted, + /// before it was presented. Otherwise, when the window decided to draw nothing. + pub fn at(&self) -> Instant { self.at } + + pub fn outcome(&self) -> FrameOutcome { self.outcome } + + /// The window's key (`WindowSpec::new`; `"main"` for `App::run`). + pub fn window(&self) -> Option<&str> { self.window.as_deref() } + + /// This window's reports so far, from 0: one per call, whatever the outcome. + pub fn seq(&self) -> u64 { self.seq } + + /// The display refresh the window's display link aimed this frame at, when one paced it: + /// macOS windows that are visible and not being resized. `None` elsewhere, for `Skipped` + /// frames, and for a frame drawn at once after the window rested (the first after a key + /// press, say), which aims at the next refresh without waiting for a tick. + pub fn presents_at(&self) -> Option<Instant> { self.presents_at } + + /// For `Drawn`, when the frame started, after its drawable came: `at` minus the update and + /// the encode. A display-paced window starts each frame on a refresh, so the gaps between + /// starts are the gaps between frames on screen. `None` otherwise. + pub fn started(&self) -> Option<Instant> { self.started } + + /// The refresh rate of the display the window was on, in Hz: the display link's on macOS + /// (120 on a ProMotion panel), else what the monitor reports. `None` when neither knows. + pub fn refresh_hz(&self) -> Option<f64> { self.refresh_hz } + + /// For `Drawn`, the milliseconds from the frame's start (after its drawable came) until the + /// runtime had built it: events, `poll`, the view, layout and paint. The same value a + /// compositor gets as `Frame::update_ms`. `None` otherwise. + pub fn update_ms(&self) -> Option<f64> { self.update_ms } + + /// For `Drawn`, the milliseconds from the end of the update until the frame's commands were + /// submitted (`at`): uploads, the renderer's prepare and draw, or a compositor's `render`. + /// CPU wall time; not GPU time, and not the wait to present. `None` otherwise. + pub fn encode_ms(&self) -> Option<f64> { self.encode_ms } +} + +/// A window's hook and the count it numbers reports with. Without a hook every call is one +/// `Option` check and nothing else, so reporting never changes how the window draws. +#[derive(Default)] +pub(crate) struct FrameReports(Option<Reporter>); + +struct Reporter { + hook: OnFrameEncoded, + window: Option<Rc<str>>, + seq: u64, + refresh_hz: Option<f64>, +} + +impl FrameReports { + pub(crate) fn new(hook: Option<OnFrameEncoded>, window: Option<&str>) -> Self { + Self(hook.map(|hook| Reporter { hook, window: window.map(Rc::from), seq: 0, refresh_hz: None })) + } + + /// The time to report a `Drawn` frame at, taken only when there's a hook. + pub(crate) fn stamp(&self) -> Option<Instant> { self.0.as_ref().map(|_| crate::time::now()) } + + /// Whether anyone reads the reports, so a host asks for what only they need. + pub(crate) fn wanted(&self) -> bool { self.0.is_some() } + + /// The display refresh the next reports carry, until it changes. + pub(crate) fn set_refresh(&mut self, hz: Option<f64>) { + if let Some(r) = &mut self.0 { r.refresh_hz = hz.filter(|hz| hz.is_finite() && *hz > 0.0); } + } + + /// A frame encoded at `at` (from `stamp`), which started at `started` and spent `update_ms` + /// of that building. + pub(crate) fn drawn(&mut self, at: Option<Instant>, presents_at: Option<Instant>, started: Instant, update_ms: f64) { + let Some(at) = at else { return }; + let encode_ms = (at.saturating_duration_since(started).as_secs_f64() * 1000.0 - update_ms).max(0.0); + self.report(FrameOutcome::Drawn, at, presents_at, Some((started, update_ms, encode_ms))); + } + + pub(crate) fn unchanged(&mut self, presents_at: Option<Instant>) { + if self.0.is_some() { self.report(FrameOutcome::Unchanged, crate::time::now(), presents_at, None); } + } + + pub(crate) fn skipped(&mut self) { + if self.0.is_some() { self.report(FrameOutcome::Skipped, crate::time::now(), None, None); } + } + + fn report(&mut self, outcome: FrameOutcome, at: Instant, presents_at: Option<Instant>, work: Option<(Instant, f64, f64)>) { + let Some(r) = &mut self.0 else { return }; + let (started, update_ms, encode_ms) = (work.map(|w| w.0), work.map(|w| w.1), work.map(|w| w.2)); + let frame = FrameEncoded { at, outcome, window: r.window.clone(), seq: r.seq, presents_at, started, refresh_hz: r.refresh_hz, update_ms, encode_ms }; + r.seq += 1; + (r.hook)(&frame); + } +} + +#[cfg(test)] +#[path = "encoded_tests.rs"] +mod tests; diff --git a/app/vendor/rune/crates/rune/src/frame/encoded_tests.rs b/app/vendor/rune/crates/rune/src/frame/encoded_tests.rs new file mode 100644 index 0000000..3da0672 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/frame/encoded_tests.rs @@ -0,0 +1,115 @@ +//! `App::on_frame_encoded`: reports carry what the window said, and reporting decides nothing. +use std::cell::RefCell; +use std::time::Duration; + +use super::*; +use crate::{App, AppSpec, WindowSpec}; + +type Log = Rc<RefCell<Vec<FrameEncoded>>>; + +fn logging() -> (Log, OnFrameEncoded) { + let log = Log::default(); + let sink = log.clone(); + (log, Box::new(move |f: &FrameEncoded| sink.borrow_mut().push(f.clone()))) +} + +#[test] +fn reports_number_each_frame_of_their_window() { + let (log, hook) = logging(); + let mut reports = FrameReports::new(Some(hook), Some("main")); + let target = crate::time::now() + Duration::from_millis(8); + let started = crate::time::now(); + let encoded = reports.stamp(); + assert!(encoded.is_some(), "a hook takes the encode time"); + reports.drawn(encoded, Some(target), started, 0.0); + reports.unchanged(Some(target)); + reports.skipped(); + let log = log.borrow(); + let seen: Vec<_> = log.iter().map(|f| (f.seq(), f.outcome(), f.window(), f.presents_at())).collect(); + assert_eq!(seen, vec![ + (0, FrameOutcome::Drawn, Some("main"), Some(target)), + (1, FrameOutcome::Unchanged, Some("main"), Some(target)), + (2, FrameOutcome::Skipped, Some("main"), None), + ]); + assert_eq!(log[0].at(), encoded.unwrap(), "a drawn frame reports when encoding finished"); + assert!(log[1].at() >= log[0].at() && log[2].at() >= log[1].at()); +} + +#[test] +fn a_drawn_frame_splits_its_work_into_update_and_encode() { + let (log, hook) = logging(); + let mut reports = FrameReports::new(Some(hook), Some("main")); + let started = crate::time::now(); + let encoded = started + Duration::from_millis(5); + reports.drawn(Some(encoded), None, started, 2.0); + // A clock step can put the stamp before the update ended: encode time is never negative. + reports.drawn(Some(started), None, started, 2.0); + reports.unchanged(None); + reports.skipped(); + let log = log.borrow(); + assert_eq!(log[0].update_ms(), Some(2.0)); + assert!((log[0].encode_ms().unwrap() - 3.0).abs() < 1e-9, "{:?}", log[0].encode_ms()); + assert_eq!(log[1].encode_ms(), Some(0.0)); + assert_eq!(log[0].started(), Some(started), "a drawn frame says when it started"); + for f in &log[2..] { + assert_eq!((f.update_ms(), f.encode_ms(), f.started()), (None, None, None), "{:?} frames did no work to time", f.outcome()); + } +} + +#[test] +fn reports_carry_the_display_refresh_the_host_last_set() { + let (log, hook) = logging(); + let mut reports = FrameReports::new(Some(hook), Some("main")); + assert!(reports.wanted()); + reports.skipped(); + reports.set_refresh(Some(120.0)); + reports.unchanged(None); + reports.drawn(reports.stamp(), None, crate::time::now(), 0.0); + reports.set_refresh(Some(0.0)); + reports.skipped(); + let hz: Vec<_> = log.borrow().iter().map(FrameEncoded::refresh_hz).collect(); + assert_eq!(hz, vec![None, Some(120.0), Some(120.0), None], "a rate that isn't one reads as unknown"); +} + +#[test] +fn without_a_hook_nothing_is_timed_or_counted() { + let mut reports = FrameReports::new(None, Some("main")); + assert_eq!(reports.stamp(), None); + reports.drawn(None, None, crate::time::now(), 1.0); + reports.unchanged(None); + reports.skipped(); + reports.set_refresh(Some(60.0)); + assert!(!reports.wanted()); + assert!(reports.0.is_none()); +} + +#[test] +fn a_window_spec_keeps_its_app_s_hook_until_it_sets_its_own() { + fn spec() -> AppSpec<()> { AppSpec::new("test", (100.0, 100.0), || (), |_, _| crate::el()) } + let calls = Rc::new(RefCell::new(Vec::new())); + let (app_calls, window_calls) = (calls.clone(), calls.clone()); + let window = WindowSpec::from_app("main", App::new(spec()).on_frame_encoded(move |_| app_calls.borrow_mut().push("app"))); + let mut reports = FrameReports::new(window.app.on_frame_encoded, Some("main")); + reports.skipped(); + let window = WindowSpec::from_app("main", App::new(spec()).on_frame_encoded(|_| unreachable!())) + .on_frame_encoded(move |_| window_calls.borrow_mut().push("window")); + let mut reports = FrameReports::new(window.app.on_frame_encoded, Some("main")); + reports.skipped(); + assert!(WindowSpec::new("plain", spec()).app.on_frame_encoded.is_none()); + assert_eq!(*calls.borrow(), vec!["app", "window"]); +} + +#[test] +fn a_drawn_frame_s_inspector_reads_the_runtime_it_presented() { + fn spec() -> AppSpec<u32> { AppSpec::new("test", (100.0, 100.0), || 7, |_, _| crate::el().key("box").size(20.0, 20.0)) } + let seen = Rc::new(RefCell::new(Vec::new())); + let sink = seen.clone(); + let mut window = WindowSpec::from_app("main", App::new(spec()).on_frame_drawn(move |rt| { + sink.borrow_mut().push((rt.state, rt.elements().iter().any(|e| e.key.as_deref() == Some("box")))); + })); + let mut rt = crate::Runtime::new(7u32, |_, _| crate::el().key("box").size(20.0, 20.0), (100.0, 100.0), crate::Env::new(true, 1.0)); + rt.frame(0.0); + if let Some(hook) = window.app.on_frame_drawn.as_mut() { hook(&rt); } + assert_eq!(*seen.borrow(), vec![(7, true)]); + assert!(WindowSpec::new("plain", spec()).app.on_frame_drawn.is_none(), "without one, inspecting is an Option check"); +} diff --git a/app/vendor/rune/crates/rune/src/frame/host_clock.rs b/app/vendor/rune/crates/rune/src/frame/host_clock.rs new file mode 100644 index 0000000..8e880b8 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/frame/host_clock.rs @@ -0,0 +1,150 @@ +//! The host's monotonic clock in nanoseconds and the calling thread's CPU time, both precise: +//! Windows reads `QueryPerformanceCounter` and `QueryThreadCycleTime`, never `GetThreadTimes`, +//! which moves in 15.6 ms ticks. + +#![allow(unsafe_code)] + +/// Nanoseconds on the host's monotonic clock: Windows `QueryPerformanceCounter` scaled with +/// 128-bit math, `mach_absolute_time` through its timebase, else `CLOCK_MONOTONIC`. +#[cfg(not(target_arch = "wasm32"))] +#[cfg_attr(not(windows), allow(dead_code))] +pub(crate) fn now_ns() -> u64 { + #[cfg(windows)] + { + use windows_sys::Win32::System::Performance::{QueryPerformanceCounter, QueryPerformanceFrequency}; + static FREQ: std::sync::OnceLock<u64> = std::sync::OnceLock::new(); + let freq = *FREQ.get_or_init(|| { + let mut f = 0i64; + // SAFETY: `f` is a live, writable i64. + unsafe { QueryPerformanceFrequency(&mut f) }; + f.max(1) as u64 + }); + let mut count = 0i64; + // SAFETY: `count` is a live, writable i64. + unsafe { QueryPerformanceCounter(&mut count) }; + (count as u128 * 1_000_000_000 / freq as u128) as u64 + } + #[cfg(target_vendor = "apple")] + { + #[repr(C)] + struct Timebase { numer: u32, denom: u32 } + unsafe extern "C" { + fn mach_timebase_info(info: *mut Timebase) -> i32; + fn mach_absolute_time() -> u64; + } + static BASE: std::sync::OnceLock<(u32, u32)> = std::sync::OnceLock::new(); + let (numer, denom) = *BASE.get_or_init(|| { + let mut info = Timebase { numer: 0, denom: 0 }; + // SAFETY: `info` is a live, writable timebase struct. + unsafe { mach_timebase_info(&mut info) }; + (info.numer.max(1), info.denom.max(1)) + }); + // SAFETY: no preconditions. + let ticks = unsafe { mach_absolute_time() }; + (ticks as u128 * numer as u128 / denom as u128) as u64 + } + #[cfg(all(unix, not(target_vendor = "apple")))] + { + let mut t = libc::timespec { tv_sec: 0, tv_nsec: 0 }; + // SAFETY: `t` is a live, writable timespec. + unsafe { libc::clock_gettime(libc::CLOCK_MONOTONIC, &mut t) }; + t.tv_sec as u64 * 1_000_000_000 + t.tv_nsec as u64 + } +} + +/// The calling thread's CPU time in raw units: cycles on Windows, nanoseconds elsewhere; `None` +/// when the OS can't say. [`cpu_ns`] converts. +#[cfg(any(unix, windows))] +pub(crate) fn thread_cpu() -> Option<u64> { + #[cfg(windows)] + { + use windows_sys::Win32::System::{Threading::GetCurrentThread, WindowsProgramming::QueryThreadCycleTime}; + let mut cycles = 0u64; + // SAFETY: the pseudo-handle is valid for the calling thread; `cycles` is live and writable. + let ok = unsafe { QueryThreadCycleTime(GetCurrentThread(), &mut cycles) }; + (ok != 0).then_some(cycles) + } + #[cfg(unix)] + { + let mut t = libc::timespec { tv_sec: 0, tv_nsec: 0 }; + // SAFETY: `t` is a live, writable timespec and the clock needs no handle. + let ok = unsafe { libc::clock_gettime(libc::CLOCK_THREAD_CPUTIME_ID, &mut t) }; + (ok == 0).then(|| t.tv_sec as u64 * 1_000_000_000 + t.tv_nsec as u64) + } +} + +/// Raw [`thread_cpu`] units in nanoseconds; `None` on Windows until [`cycles_per_ns`] knows the +/// rate. +#[cfg(any(unix, windows))] +pub(crate) fn cpu_ns(raw: u64) -> Option<f64> { + #[cfg(windows)] + return cycles_per_ns().map(|rate| raw as f64 / rate); + #[cfg(unix)] + return Some(raw as f64); +} + +/// The span [`cycles_per_ns`] measures the rate over: long enough that reading the two clocks a +/// few microseconds apart moves the rate by under 0.1 %. +#[cfg(all(windows, target_arch = "x86_64"))] +const RATE_SPAN_NS: u64 = 20_000_000; + +/// A (QPC, TSC) pair is kept only when the two QPC readings around the TSC's are this close: a +/// thread preempted between them would skew the rate for the rest of the process. +#[cfg(all(windows, target_arch = "x86_64"))] +const PAIR_SLACK_NS: u64 = 100_000; + +/// Thread cycles per nanosecond, without waiting or spinning: Windows counts a thread's cycles at +/// the TSC's constant rate on every core (P-cores and E-cores alike), so the rate is the TSC's +/// against QPC between this process's first call and one at least [`RATE_SPAN_NS`] later. `None` +/// until then (callers fall back to the wall clock), when the readings make no sense, and on +/// Windows on ARM, where the cycles aren't a fixed-rate counter's. +#[cfg(windows)] +pub(crate) fn cycles_per_ns() -> Option<f64> { + static RATE: std::sync::OnceLock<f64> = std::sync::OnceLock::new(); + if let Some(rate) = RATE.get() { + return Some(*rate); + } + #[cfg(target_arch = "x86_64")] + { + static FIRST: std::sync::OnceLock<(u64, u64)> = std::sync::OnceLock::new(); + let now = pair()?; + let first = *FIRST.get_or_init(|| now); + let span = now.0.checked_sub(first.0).filter(|&ns| ns >= RATE_SPAN_NS)?; + let rate = now.1.checked_sub(first.1)? as f64 / span as f64; + // A TSC runs at 0.5-10 GHz; anything else is a misread, and the wall clock stays. + (0.5..=10.0).contains(&rate).then(|| *RATE.get_or_init(|| rate)) + } + #[cfg(not(target_arch = "x86_64"))] + { + None + } +} + +/// QPC (ns, the middle of two readings) and the TSC between them; `None` when the thread was held +/// between them for more than [`PAIR_SLACK_NS`]. +#[cfg(all(windows, target_arch = "x86_64"))] +fn pair() -> Option<(u64, u64)> { + let before = now_ns(); + // SAFETY: RDTSC has no preconditions on x86-64. + #[allow(unused_unsafe)] + let tsc = unsafe { core::arch::x86_64::_rdtsc() }; + let after = now_ns(); + after.checked_sub(before).filter(|&d| d <= PAIR_SLACK_NS).map(|d| (before + d / 2, tsc)) +} + +/// [`cycles_per_ns`] for benches and profiles, which want a reading on their first call: waits +/// (sleeping) until the rate is known, at most 50 ms. Never on a path a window waits for. +#[cfg(windows)] +#[cfg_attr(not(feature = "frame-profile"), allow(dead_code))] +pub(crate) fn cycles_per_ns_waiting() -> Option<f64> { + for _ in 0..50 { + if let Some(rate) = cycles_per_ns() { + return Some(rate); + } + if cfg!(not(target_arch = "x86_64")) { + return None; + } + std::thread::sleep(std::time::Duration::from_millis(1)); + } + None +} \ No newline at end of file diff --git a/app/vendor/rune/crates/rune/src/frame/host_step.rs b/app/vendor/rune/crates/rune/src/frame/host_step.rs new file mode 100644 index 0000000..9385520 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/frame/host_step.rs @@ -0,0 +1,631 @@ +//! Shared host frame sequencer: one definition of the order every host (window, overlay, Apple +//! layer, headless, virtual desktop, and web) drives a frame through. +//! +//! The sequence is governed by an explicit phase state machine ([`Phase`], [`Event`], +//! [`Effect`], [`step`]) so every ordering invariant — acquiring a drawable before stepping on +//! normal frames, stepping before acquiring on quiet timer frames without double-stepping on a +//! miss, dropping the old drawable before post-step reconfiguration and re-acquisition, and +//! reporting presentation to [`FrameClock`] and interaction timing — is enforced in one place. +//! Each host supplies only its host-specific work through [`FrameHost`]. + +use crate::frame::clock::FrameClock; +use crate::machine::Effects; +use crate::render::{Gpu, Renderer}; +use crate::runtime::RuntimeCore; +use crate::time::Instant; +use crate::window::Missed; + +/// Final outcome of one [`run`] call. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum Outcome { + /// The gate declined to draw (covered, occluded, suspended, backed off, waiting for a swap + /// chain slot, or display-link Wait). + Skipped, + /// A resting timer frame built the same pixels already on screen and skipped presentation. + Unchanged, + /// Acquisition, surface reconfiguration, or a forced miss ended the frame without presenting. + Missed, + /// Rendering could not prepare its target (e.g. a CPU-boot frame needs the GPU or lacked a + /// buffer, or the web host rejected unsupported native surfaces) and deferred to the host's + /// recovery path. + #[cfg(any(test, target_os = "windows", target_arch = "wasm32"))] + Aborted, + /// A frame was drawn, submitted/presented, recorded on the clock and interaction tracker, and + /// settled. + Presented, +} + +/// Which frame path [`FrameHost::gate`] selected. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum GateKind { + Skip, + Draw, + QuietTimer, + PreStepped, +} + +/// Decision returned by [`FrameHost::gate`] before touching the surface. +#[derive(Clone, Copy, Debug)] +pub(crate) enum Gate { + /// Do not draw a frame this turn. + Skip, + /// Normal acquire-before-step frame. + Draw, + /// Resting window or overlay woken only by a due timer: step first, and skip acquisition + /// and presentation when nothing visible changed. + QuietTimer, + /// Multi-window tooling host whose runtime step already ran before compositing visible + /// windows in z-order. + PreStepped(StepInfo), +} + +impl Gate { + #[inline(always)] + fn kind(&self) -> GateKind { + match self { + Gate::Skip => GateKind::Skip, + Gate::Draw => GateKind::Draw, + Gate::QuietTimer => GateKind::QuietTimer, + Gate::PreStepped(_) => GateKind::PreStepped, + } + } +} + +/// Result of [`FrameHost::acquire`]. +#[derive(Debug)] +pub(crate) enum Acquire<D> { + Ready(D), + Missed(Missed), +} + +/// Why an acquired drawable must be dropped and re-acquired after the runtime stepped. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum ReacquireReason { + /// Native system materials (e.g. macOS visual effect views) turned on during the step; the + /// host rebuilds with native materials enabled before re-acquiring. + #[cfg(any(test, target_os = "macos"))] + NativeMaterials, + /// A handler changed `Tx::set_srgb_blend`; the surface and renderer reconfigure for the new + /// target format before re-acquiring. + Reblend, +} + +/// Result of [`FrameHost::post_step_check`]. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum PostStepCheck { + /// Keep the current drawable and proceed to sync and render. + Keep, + /// Drop the current drawable, reconfigure for `ReacquireReason`, and acquire a replacement. + Reacquire(ReacquireReason), + /// Drop the current drawable and treat the frame as missed (used by diagnostic miss hooks). + #[cfg(any(test, feature = "frame-profile"))] + Missed(Missed), +} + +/// Result of [`FrameHost::prepare_render`]. +#[derive(Debug)] +pub(crate) enum RenderPrep<P> { + Ready(P), + #[cfg(any(test, target_os = "windows", target_arch = "wasm32"))] + Abort, +} + +/// Timing and motion summary carried from the runtime step into sync, render, present and settle. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub(crate) struct StepInfo { + /// Whether the runtime itself (before any compositor pass) reported motion still running. + pub(crate) runtime_animating: bool, + /// Whether either the runtime, native layers, or a compositor reported motion still running. + pub(crate) animating: bool, + /// Seconds stepped for this frame. + pub(crate) dt: f64, + /// CPU milliseconds spent updating and laying out the frame before rendering. + pub(crate) update_ms: f64, + /// Display-link target presentation time, when paced. + pub(crate) presents_at: Option<Instant>, +} + +/// Explicit phase of a single host frame. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum Phase { + Start, + Gating, + FrameMoving, + PreReblending { stepped: bool }, + QuietStepping, + Acquiring { stepped: bool }, + Stepping, + PostStepChecking { reacquired: u8 }, + Reacquiring { reacquired: u8 }, + Syncing, + Preparing, + Rendering, + Presenting, + RecordingPresented, + Settling, + Done(Outcome), +} + +impl Phase { + #[inline(always)] + fn outcome(self) -> Outcome { + match self { + Phase::Done(outcome) => outcome, + other => unreachable!("host_step ended in non-terminal phase {other:?}"), + } + } +} + +/// Events fed into [`step`] as each host hook finishes. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum Event { + Begin, + Gate(GateKind), + FrameMoved, + ReblendOk, + ReblendFailed, + QuietUnchanged, + QuietChanged, + Acquired, + AcquireMissed(Missed), + Stepped, + PostStepKeep, + PostStepReacquire(ReacquireReason), + #[cfg(any(test, feature = "frame-profile"))] + PostStepMissed(Missed), + Reacquired, + ReacquireMissed(Missed), + Synced, + Prepared, + #[cfg(any(test, target_os = "windows", target_arch = "wasm32"))] + PrepareAborted, + Rendered, + Presented, + Recorded, + Settled, +} + +/// Coarse host action returned by [`step`]. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum Effect { + Gate, + FrameMove, + PreReblend, + QuietStep, + Unchanged, + Acquire, + Step, + PostStepCheck, + DropAndReacquire(ReacquireReason), + #[cfg(any(test, feature = "frame-profile"))] + DropAndMiss(Missed), + Missed { missed: Missed, stepped: bool }, + Sync, + Prepare, + Render, + Present, + RecordPresented, + Settle, +} + +/// Pure transition function for a single host frame. +/// +/// The `stepped` flag carried by `PreReblending` and `Acquiring` guarantees that a frame missed +/// after a quiet pre-step or after a post-step reconfiguration never runs the runtime a second +/// time. `PostStepChecking` caps re-acquisition to two passes (native materials and blend switch). +#[inline(always)] +pub(crate) fn step(phase: &mut Phase, event: Event) -> Effects<Effect> { + match (*phase, event) { + (Phase::Start, Event::Begin) => { + *phase = Phase::Gating; + Effects::one(Effect::Gate) + } + (Phase::Gating, Event::Gate(GateKind::Skip)) => { + *phase = Phase::Done(Outcome::Skipped); + Effects::none() + } + (Phase::Gating, Event::Gate(GateKind::Draw)) => { + *phase = Phase::FrameMoving; + Effects::one(Effect::FrameMove) + } + (Phase::Gating, Event::Gate(GateKind::QuietTimer)) => { + *phase = Phase::QuietStepping; + Effects::one(Effect::QuietStep) + } + (Phase::Gating, Event::Gate(GateKind::PreStepped)) => { + *phase = Phase::PreReblending { stepped: true }; + Effects::one(Effect::PreReblend) + } + (Phase::FrameMoving, Event::FrameMoved) => { + *phase = Phase::PreReblending { stepped: false }; + Effects::one(Effect::PreReblend) + } + (Phase::PreReblending { stepped }, Event::ReblendOk) => { + *phase = Phase::Acquiring { stepped }; + Effects::one(Effect::Acquire) + } + (Phase::PreReblending { stepped }, Event::ReblendFailed) => { + *phase = Phase::Done(Outcome::Missed); + Effects::one(Effect::Missed { missed: Missed::Unconfigured, stepped }) + } + (Phase::QuietStepping, Event::QuietUnchanged) => { + *phase = Phase::Done(Outcome::Unchanged); + Effects::one(Effect::Unchanged) + } + (Phase::QuietStepping, Event::QuietChanged) => { + *phase = Phase::Acquiring { stepped: true }; + Effects::one(Effect::Acquire) + } + (Phase::Acquiring { stepped: false }, Event::Acquired) => { + *phase = Phase::Stepping; + Effects::one(Effect::Step) + } + (Phase::Acquiring { stepped: true }, Event::Acquired) => { + *phase = Phase::PostStepChecking { reacquired: 0 }; + Effects::one(Effect::PostStepCheck) + } + (Phase::Acquiring { stepped }, Event::AcquireMissed(missed)) => { + *phase = Phase::Done(Outcome::Missed); + Effects::one(Effect::Missed { missed, stepped }) + } + (Phase::Stepping, Event::Stepped) => { + *phase = Phase::PostStepChecking { reacquired: 0 }; + Effects::one(Effect::PostStepCheck) + } + (Phase::PostStepChecking { .. }, Event::PostStepKeep) => { + *phase = Phase::Syncing; + Effects::one(Effect::Sync) + } + (Phase::PostStepChecking { reacquired }, Event::PostStepReacquire(reason)) if reacquired < 2 => { + *phase = Phase::Reacquiring { reacquired: reacquired + 1 }; + Effects::one(Effect::DropAndReacquire(reason)) + } + (Phase::PostStepChecking { .. }, Event::PostStepReacquire(_)) => { + *phase = Phase::Syncing; + Effects::one(Effect::Sync) + } + #[cfg(any(test, feature = "frame-profile"))] + (Phase::PostStepChecking { .. }, Event::PostStepMissed(missed)) => { + *phase = Phase::Done(Outcome::Missed); + Effects::one(Effect::DropAndMiss(missed)) + } + (Phase::Reacquiring { reacquired }, Event::Reacquired) => { + *phase = Phase::PostStepChecking { reacquired }; + Effects::one(Effect::PostStepCheck) + } + (Phase::Reacquiring { .. }, Event::ReacquireMissed(missed)) => { + *phase = Phase::Done(Outcome::Missed); + Effects::one(Effect::Missed { missed, stepped: true }) + } + (Phase::Syncing, Event::Synced) => { + *phase = Phase::Preparing; + Effects::one(Effect::Prepare) + } + (Phase::Preparing, Event::Prepared) => { + *phase = Phase::Rendering; + Effects::one(Effect::Render) + } + #[cfg(any(test, target_os = "windows", target_arch = "wasm32"))] + (Phase::Preparing, Event::PrepareAborted) => { + *phase = Phase::Done(Outcome::Aborted); + Effects::none() + } + (Phase::Rendering, Event::Rendered) => { + *phase = Phase::Presenting; + Effects::one(Effect::Present) + } + (Phase::Presenting, Event::Presented) => { + *phase = Phase::RecordingPresented; + Effects::one(Effect::RecordPresented) + } + (Phase::RecordingPresented, Event::Recorded) => { + *phase = Phase::Settling; + Effects::one(Effect::Settle) + } + (Phase::Settling, Event::Settled) => { + *phase = Phase::Done(Outcome::Presented); + Effects::none() + } + (state, ev) => unreachable!("invalid host_step transition: {state:?} + {ev:?}"), + } +} + +/// Host-specific callbacks driven in one shared order by [`run`]. +pub(crate) trait FrameHost { + /// Acquired drawable handle held across the step and dropped before any post-step + /// reconfiguration/re-acquisition. Zero-sized `()` for offscreen and CPU hosts. + type Drawable; + /// Prepared render state passed from [`Self::prepare_render`] through [`Self::render`] to + /// [`Self::submit_and_present`]. + type Prepared; + + /// Decides whether a frame proceeds and which path it takes (normal draw, quiet resting timer, + /// pre-stepped multi-window render, or skip). + fn gate(&mut self) -> Gate; + + /// Moves an animated window frame before surface reconfiguration and drawable acquisition. + #[inline] + fn before_acquire(&mut self) {} + + /// Whether the surface/renderer blend mode or format needs updating before acquisition. + #[inline] + fn needs_reblend(&self) -> bool { false } + + /// Reconfigures the surface and rebuilds the renderer to match `rt.srgb_blend()`. Returns + /// `false` when the surface refused the new configuration. + #[inline] + fn reblend(&mut self) -> bool { true } + + /// Steps a resting timer frame before acquiring a drawable (only called after + /// [`Gate::QuietTimer`]). + #[inline] + fn step_quiet(&mut self) -> StepInfo { + unreachable!("host returned Gate::QuietTimer without implementing step_quiet") + } + + /// Whether the quiet timer frame produced identical pixels and needs no presentation. + #[inline] + fn is_unchanged(&mut self, _info: &StepInfo) -> bool { false } + + /// Syncs platform state and stops pacing when a quiet timer frame skips presentation. + #[inline] + fn on_unchanged(&mut self, _info: &StepInfo) {} + + /// Prepares pacing or present-worker state once a quiet timer frame discovers it must draw. + #[inline] + fn on_quiet_will_draw(&mut self) {} + + /// Acquires the next drawable. + fn acquire(&mut self) -> Acquire<Self::Drawable>; + + /// Advances the frame clock and runs the runtime pass for this frame. + fn step_runtime(&mut self) -> StepInfo; + + /// Checks after stepping whether the acquired drawable must be replaced (macOS native + /// materials or `Tx::set_srgb_blend`) or treated as missed. + #[inline] + fn post_step_check(&mut self, _info: &mut StepInfo) -> PostStepCheck { PostStepCheck::Keep } + + /// Rebuilds or reconfigures after [`run`] has dropped the old drawable, right before the + /// replacement [`Self::acquire`]. Returning `false` ends the frame with + /// `Missed::Unconfigured`. + #[inline] + fn prepare_reacquire(&mut self, _reason: ReacquireReason, _info: &mut StepInfo) -> bool { true } + + /// Handles a missed acquire or failed reconfiguration. `stepped` is `true` iff the runtime + /// already stepped for this frame, so the host must not step it a second time. + #[inline] + fn on_missed(&mut self, _missed: Missed, _stepped: bool) {} + + /// Syncs host state and requests after stepping (clipboard, IME, cursor, secure input, help, + /// hit regions, unsupported request dropping, headless popups/placement). + #[inline] + fn sync_after_step(&mut self, _info: &mut StepInfo) {} + + /// Uploads images, prepares native surfaces, and creates the view and command encoder. + fn prepare_render(&mut self, drawable: Self::Drawable, info: &mut StepInfo) -> RenderPrep<Self::Prepared>; + + /// Encodes either the app's custom compositor or the default UI pass. Returns `true` when a + /// compositor reported that it is still animating. + fn render(&mut self, prepared: &mut Self::Prepared, info: &StepInfo) -> bool; + + /// Submits GPU work, presents the drawable, performs any post-present GPU sync, and returns + /// the submission timestamp recorded on the frame clock and interaction tracker. + fn submit_and_present(&mut self, prepared: Self::Prepared, info: &StepInfo) -> Instant; + + /// Supplies the wall-clock [`FrameClock`] (when the host has one) and [`RuntimeCore`] so + /// [`run`] itself records presentation on both the clock and interaction latency tracker. + fn present_targets(&mut self) -> (Option<&mut FrameClock>, &mut RuntimeCore); + + /// Updates idle/presented state, frame reports, traces, and next-frame scheduling. + #[inline] + fn settle(&mut self, _submitted: Instant, _info: &StepInfo) {} +} + +#[inline(always)] +fn run_pre_reblend<H: FrameHost>(phase: &mut Phase, host: &mut H) -> bool { + let ok = !host.needs_reblend() || host.reblend(); + let event = if ok { Event::ReblendOk } else { Event::ReblendFailed }; + match step(phase, event) { + Effects::One(Effect::Acquire) => true, + Effects::One(Effect::Missed { missed, stepped }) => { + host.on_missed(missed, stepped); + false + } + _ => unreachable!(), + } +} + +#[inline(always)] +fn run_acquire<H: FrameHost>(phase: &mut Phase, host: &mut H) -> Option<H::Drawable> { + match host.acquire() { + Acquire::Ready(drawable) => { + let _ = step(phase, Event::Acquired); + Some(drawable) + } + Acquire::Missed(missed) => { + let Effects::One(Effect::Missed { missed, stepped }) = step(phase, Event::AcquireMissed(missed)) else { unreachable!() }; + host.on_missed(missed, stepped); + None + } + } +} + +/// Runs one frame through the shared [`step`] state machine for `host`. +#[inline] +pub(crate) fn run<H: FrameHost>(host: &mut H) -> Outcome { + let mut phase = Phase::Start; + let Effects::One(Effect::Gate) = step(&mut phase, Event::Begin) else { unreachable!() }; + let gate = host.gate(); + let (mut drawable, mut info) = match step(&mut phase, Event::Gate(gate.kind())) { + Effects::None => return phase.outcome(), + Effects::One(Effect::FrameMove) => { + host.before_acquire(); + let Effects::One(Effect::PreReblend) = step(&mut phase, Event::FrameMoved) else { unreachable!() }; + if !run_pre_reblend(&mut phase, host) { + return phase.outcome(); + } + let Some(drawable) = run_acquire(&mut phase, host) else { + return phase.outcome(); + }; + debug_assert_eq!(phase, Phase::Stepping); + let info = host.step_runtime(); + let Effects::One(Effect::PostStepCheck) = step(&mut phase, Event::Stepped) else { unreachable!() }; + (drawable, info) + } + Effects::One(Effect::QuietStep) => { + let info = host.step_quiet(); + let event = if host.is_unchanged(&info) { Event::QuietUnchanged } else { Event::QuietChanged }; + match step(&mut phase, event) { + Effects::One(Effect::Unchanged) => { + host.on_unchanged(&info); + return phase.outcome(); + } + Effects::One(Effect::Acquire) => { + host.on_quiet_will_draw(); + let Some(drawable) = run_acquire(&mut phase, host) else { + return phase.outcome(); + }; + (drawable, info) + } + _ => unreachable!(), + } + } + Effects::One(Effect::PreReblend) => { + let Gate::PreStepped(info) = gate else { unreachable!() }; + if !run_pre_reblend(&mut phase, host) { + return phase.outcome(); + } + let Some(drawable) = run_acquire(&mut phase, host) else { + return phase.outcome(); + }; + (drawable, info) + } + _ => unreachable!(), + }; + + loop { + let event = match host.post_step_check(&mut info) { + PostStepCheck::Keep => Event::PostStepKeep, + PostStepCheck::Reacquire(reason) => Event::PostStepReacquire(reason), + #[cfg(any(test, feature = "frame-profile"))] + PostStepCheck::Missed(missed) => Event::PostStepMissed(missed), + }; + match step(&mut phase, event) { + Effects::One(Effect::Sync) => break, + Effects::One(Effect::DropAndReacquire(reason)) => { + drop(drawable); + let reacquired = if host.prepare_reacquire(reason, &mut info) { + host.acquire() + } else { + Acquire::Missed(Missed::Unconfigured) + }; + match reacquired { + Acquire::Ready(next) => { + drawable = next; + let Effects::One(Effect::PostStepCheck) = step(&mut phase, Event::Reacquired) else { unreachable!() }; + } + Acquire::Missed(missed) => { + let Effects::One(Effect::Missed { missed, stepped }) = step(&mut phase, Event::ReacquireMissed(missed)) else { unreachable!() }; + host.on_missed(missed, stepped); + return phase.outcome(); + } + } + } + #[cfg(any(test, feature = "frame-profile"))] + Effects::One(Effect::DropAndMiss(missed)) => { + drop(drawable); + host.on_missed(missed, true); + return phase.outcome(); + } + _ => unreachable!(), + } + } + + host.sync_after_step(&mut info); + let Effects::One(Effect::Prepare) = step(&mut phase, Event::Synced) else { unreachable!() }; + let mut prepared = match host.prepare_render(drawable, &mut info) { + RenderPrep::Ready(prepared) => { + let Effects::One(Effect::Render) = step(&mut phase, Event::Prepared) else { unreachable!() }; + prepared + } + #[cfg(any(test, target_os = "windows", target_arch = "wasm32"))] + RenderPrep::Abort => { + let Effects::None = step(&mut phase, Event::PrepareAborted) else { unreachable!() }; + return phase.outcome(); + } + }; + let comp_animating = host.render(&mut prepared, &info); + info.animating |= comp_animating; + let Effects::One(Effect::Present) = step(&mut phase, Event::Rendered) else { unreachable!() }; + let submitted = host.submit_and_present(prepared, &info); + let Effects::One(Effect::RecordPresented) = step(&mut phase, Event::Presented) else { unreachable!() }; + { + let (clock, rt) = host.present_targets(); + if let Some(clock) = clock { + clock.presented_core(rt, submitted); + } + rt.interaction_presented(submitted, info.presents_at); + } + let Effects::One(Effect::Settle) = step(&mut phase, Event::Recorded) else { unreachable!() }; + host.settle(submitted, &info); + let Effects::None = step(&mut phase, Event::Settled) else { unreachable!() }; + phase.outcome() +} + +/// Uploads dirty images, optionally kicks off asynchronous native-surface pipeline compilation, +/// runs `before_surfaces` (for example Windows DirectComposition video layers), prepares native +/// surfaces, and registers the frame wake for off-thread pipeline builds. +#[inline] +pub(crate) fn prepare_gpu_resources_with( + renderer: &mut Renderer, + gpu: &Gpu, + rt: &mut RuntimeCore, + size: (u32, u32), + async_surfaces: bool, + before_surfaces: impl FnOnce(&mut Renderer, &RuntimeCore), +) { + renderer.upload_images(&gpu.device, &gpu.queue, &mut rt.images); + if async_surfaces { + renderer.build_surfaces(&gpu.device, &rt.surfaces, rt.live_notifier()); + } + before_surfaces(renderer, rt); + renderer.prepare_surfaces(&gpu.device, &gpu.queue, &rt.surfaces, size); + if async_surfaces { + renderer.set_frame_wake(rt.live_wake()); + } +} + +/// Uploads dirty images and prepares native surfaces (with async build and frame wake when +/// `async_surfaces` is true). +#[inline] +pub(crate) fn prepare_gpu_resources( + renderer: &mut Renderer, + gpu: &Gpu, + rt: &mut RuntimeCore, + size: (u32, u32), + async_surfaces: bool, +) { + prepare_gpu_resources_with(renderer, gpu, rt, size, async_surfaces, |_, _| {}); +} + +/// Default UI render pass when a host has no custom [`crate::Compositor`]: uploads glyph atlas +/// and instance buffers, then draws into `target` with `clear`. +#[inline] +pub(crate) fn draw_ui( + renderer: &mut Renderer, + gpu: &Gpu, + encoder: &mut wgpu::CommandEncoder, + target: &wgpu::TextureView, + rt: &mut RuntimeCore, + size: (u32, u32), + clear: [f32; 4], +) { + renderer.set_fade_stops(rt.fade_stops()); + renderer.prepare_ui(&gpu.device, &gpu.queue, &mut rt.text.atlas, &rt.instances, size); + renderer.draw(encoder, target, clear); +} + +#[cfg(test)] +#[path = "host_step_tests.rs"] +mod tests; diff --git a/app/vendor/rune/crates/rune/src/frame/host_step_tests.rs b/app/vendor/rune/crates/rune/src/frame/host_step_tests.rs new file mode 100644 index 0000000..b26664b --- /dev/null +++ b/app/vendor/rune/crates/rune/src/frame/host_step_tests.rs @@ -0,0 +1,580 @@ +use std::cell::RefCell; +use std::collections::VecDeque; +use std::rc::Rc; +use std::time::Duration; + +use super::*; +use crate::frame::clock::FrameClock; +use crate::{Cx, El, Env, Runtime, el}; + +struct TrackedDrawable { + id: u32, + log: Rc<RefCell<Vec<String>>>, + consumed: bool, +} + +impl Drop for TrackedDrawable { + fn drop(&mut self) { + if !self.consumed { + self.log.borrow_mut().push(format!("drop_drawable:{}", self.id)); + } + } +} + +struct FakeHost { + rt: Runtime<u32>, + clock: Option<FrameClock>, + log: Rc<RefCell<Vec<String>>>, + gate: Gate, + pre_reblend_needed: bool, + pre_reblend_ok: bool, + quiet_unchanged: bool, + acquires: VecDeque<Result<(), Missed>>, + next_drawable: u32, + first_frame: bool, + step_at: Instant, + submit_at: Instant, + presents_at: Option<Instant>, + post_checks: VecDeque<PostStepCheck>, + reacquire_ok: VecDeque<bool>, + prepare_abort: bool, + compositor_animating: bool, + settled_info: Option<StepInfo>, +} + +impl FakeHost { + fn new(start: Instant) -> Self { + fn view(w: &u32, _: &mut Cx<u32>) -> El { + el().child(el().key("box").size(*w as f32 + 12.0, 8.0)) + } + let mut rt = Runtime::new(0u32, view, (300.0, 40.0), Env::default()); + rt.set_system_reduced_motion(false); + rt.wall_start = Some(start); + Self { + rt, + clock: Some(FrameClock::new(start)), + log: Rc::new(RefCell::new(Vec::new())), + gate: Gate::Draw, + pre_reblend_needed: false, + pre_reblend_ok: true, + quiet_unchanged: false, + acquires: VecDeque::from([Ok(())]), + next_drawable: 1, + first_frame: false, + step_at: start, + submit_at: start, + presents_at: None, + post_checks: VecDeque::new(), + reacquire_ok: VecDeque::new(), + prepare_abort: false, + compositor_animating: false, + settled_info: None, + } + } + + fn record(&self, item: impl Into<String>) { + self.log.borrow_mut().push(item.into()); + } + + fn events(&self) -> Vec<String> { + self.log.borrow().clone() + } +} + +impl FrameHost for FakeHost { + type Drawable = TrackedDrawable; + type Prepared = u32; + + fn gate(&mut self) -> Gate { + self.record(format!("gate:{:?}", self.gate.kind())); + self.gate + } + + fn before_acquire(&mut self) { + self.record("before_acquire"); + } + + fn needs_reblend(&self) -> bool { + self.record(format!("needs_reblend:{}", self.pre_reblend_needed)); + self.pre_reblend_needed + } + + fn reblend(&mut self) -> bool { + self.record(format!("reblend:{}", self.pre_reblend_ok)); + self.pre_reblend_ok + } + + fn step_quiet(&mut self) -> StepInfo { + self.record("step_quiet"); + let (core, mut app) = self.rt.split_mut(); + let (animating, dt) = self.clock.as_mut().unwrap().advance_core(core, &mut app, self.step_at, false); + StepInfo { runtime_animating: animating, animating, dt, update_ms: 0.0, presents_at: self.presents_at } + } + + fn is_unchanged(&mut self, _info: &StepInfo) -> bool { + self.record(format!("is_unchanged:{}", self.quiet_unchanged)); + self.quiet_unchanged + } + + fn on_unchanged(&mut self, _info: &StepInfo) { + self.record("on_unchanged"); + } + + fn on_quiet_will_draw(&mut self) { + self.record("on_quiet_will_draw"); + } + + fn acquire(&mut self) -> Acquire<Self::Drawable> { + match self.acquires.pop_front().unwrap_or(Ok(())) { + Ok(()) => { + let id = self.next_drawable; + self.next_drawable += 1; + self.record(format!("acquire:ok:{id}")); + Acquire::Ready(TrackedDrawable { id, log: self.log.clone(), consumed: false }) + } + Err(missed) => { + self.record(format!("acquire:missed:{missed:?}")); + Acquire::Missed(missed) + } + } + } + + fn step_runtime(&mut self) -> StepInfo { + self.record("step_runtime"); + let (core, mut app) = self.rt.split_mut(); + let (animating, dt) = if self.first_frame { + if let Some(clock) = self.clock.as_mut() { + clock.hold(self.step_at); + } + (core.frame(&mut app, 0.0), 0.0) + } else if let Some(clock) = self.clock.as_mut() { + clock.advance_core(core, &mut app, self.step_at, self.compositor_animating) + } else { + (core.frame(&mut app, 1.0 / 60.0), 1.0 / 60.0) + }; + StepInfo { runtime_animating: animating, animating, dt, update_ms: 0.5, presents_at: self.presents_at } + } + + fn post_step_check(&mut self, _info: &mut StepInfo) -> PostStepCheck { + let check = self.post_checks.pop_front().unwrap_or(PostStepCheck::Keep); + self.record(format!("post_step_check:{check:?}")); + check + } + + fn prepare_reacquire(&mut self, reason: ReacquireReason, _info: &mut StepInfo) -> bool { + let ok = self.reacquire_ok.pop_front().unwrap_or(true); + self.record(format!("prepare_reacquire:{reason:?}:{ok}")); + ok + } + + fn on_missed(&mut self, missed: Missed, stepped: bool) { + self.record(format!("on_missed:{missed:?}:stepped={stepped}")); + } + + fn sync_after_step(&mut self, _info: &mut StepInfo) { + self.record("sync_after_step"); + } + + fn prepare_render(&mut self, mut drawable: Self::Drawable, _info: &mut StepInfo) -> RenderPrep<Self::Prepared> { + let id = drawable.id; + drawable.consumed = true; + if self.prepare_abort { + self.record(format!("prepare_render:abort:{id}")); + RenderPrep::Abort + } else { + self.record(format!("prepare_render:ok:{id}")); + RenderPrep::Ready(id) + } + } + + fn render(&mut self, prepared: &mut Self::Prepared, _info: &StepInfo) -> bool { + self.record(format!("render:{prepared}:comp={}", self.compositor_animating)); + self.compositor_animating + } + + fn submit_and_present(&mut self, prepared: Self::Prepared, _info: &StepInfo) -> Instant { + self.record(format!("submit_and_present:{prepared}")); + self.submit_at + } + + fn present_targets(&mut self) -> (Option<&mut FrameClock>, &mut RuntimeCore) { + self.record("present_targets"); + (self.clock.as_mut(), self.rt.core_mut()) + } + + fn settle(&mut self, _submitted: Instant, info: &StepInfo) { + self.settled_info = Some(*info); + self.record(format!("settle:rt_anim={}:anim={}", info.runtime_animating, info.animating)); + } +} + +#[test] +fn normal_frame_follows_canonical_order() { + let start = crate::time::now(); + let mut host = FakeHost::new(start); + assert_eq!(run(&mut host), Outcome::Presented); + assert_eq!( + host.events(), + [ + "gate:Draw", + "before_acquire", + "needs_reblend:false", + "acquire:ok:1", + "step_runtime", + "post_step_check:Keep", + "sync_after_step", + "prepare_render:ok:1", + "render:1:comp=false", + "submit_and_present:1", + "present_targets", + "settle:rt_anim=false:anim=false", + ] + ); +} + +#[test] +fn hidden_or_occluded_gate_skips_without_touching_surface() { + let start = crate::time::now(); + let mut host = FakeHost::new(start); + host.gate = Gate::Skip; + assert_eq!(run(&mut host), Outcome::Skipped); + assert_eq!(host.events(), ["gate:Skip"]); +} + +#[test] +fn missed_drawable_before_step_reports_stepped_false() { + let start = crate::time::now(); + let mut host = FakeHost::new(start); + host.acquires = VecDeque::from([Err(Missed::Timeout)]); + assert_eq!(run(&mut host), Outcome::Missed); + assert_eq!( + host.events(), + [ + "gate:Draw", + "before_acquire", + "needs_reblend:false", + "acquire:missed:Timeout", + "on_missed:Timeout:stepped=false", + ] + ); +} + +#[test] +fn pre_reblend_failure_reports_unconfigured_with_stepped_false() { + let start = crate::time::now(); + let mut host = FakeHost::new(start); + host.pre_reblend_needed = true; + host.pre_reblend_ok = false; + assert_eq!(run(&mut host), Outcome::Missed); + assert_eq!( + host.events(), + [ + "gate:Draw", + "before_acquire", + "needs_reblend:true", + "reblend:false", + "on_missed:Unconfigured:stepped=false", + ] + ); +} + +#[test] +fn resize_runs_before_reblend_and_acquire() { + let start = crate::time::now(); + let mut host = FakeHost::new(start); + host.pre_reblend_needed = true; + assert_eq!(run(&mut host), Outcome::Presented); + let events = host.events(); + let pos = |prefix: &str| events.iter().position(|e| e.starts_with(prefix)).unwrap(); + assert!(pos("before_acquire") < pos("reblend:"), "frame move must run before reblend: {events:?}"); + assert!(pos("reblend:") < pos("acquire:"), "reblend must run before acquire: {events:?}"); + assert!(pos("acquire:") < pos("step_runtime"), "acquire must run before step: {events:?}"); +} + +#[test] +fn quiet_timer_frame_unchanged_never_acquires_or_presents() { + let start = crate::time::now(); + let mut host = FakeHost::new(start); + host.gate = Gate::QuietTimer; + host.quiet_unchanged = true; + assert_eq!(run(&mut host), Outcome::Unchanged); + assert_eq!( + host.events(), + [ + "gate:QuietTimer", + "step_quiet", + "is_unchanged:true", + "on_unchanged", + ] + ); +} + +#[test] +fn quiet_timer_frame_changed_draws_without_stepping_twice() { + let start = crate::time::now(); + let mut host = FakeHost::new(start); + host.gate = Gate::QuietTimer; + host.quiet_unchanged = false; + assert_eq!(run(&mut host), Outcome::Presented); + assert_eq!( + host.events(), + [ + "gate:QuietTimer", + "step_quiet", + "is_unchanged:false", + "on_quiet_will_draw", + "acquire:ok:1", + "post_step_check:Keep", + "sync_after_step", + "prepare_render:ok:1", + "render:1:comp=false", + "submit_and_present:1", + "present_targets", + "settle:rt_anim=false:anim=false", + ] + ); +} + +#[test] +fn quiet_timer_frame_that_misses_acquire_reports_stepped_true() { + let start = crate::time::now(); + let mut host = FakeHost::new(start); + host.gate = Gate::QuietTimer; + host.quiet_unchanged = false; + host.acquires = VecDeque::from([Err(Missed::Occluded)]); + assert_eq!(run(&mut host), Outcome::Missed); + assert_eq!( + host.events(), + [ + "gate:QuietTimer", + "step_quiet", + "is_unchanged:false", + "on_quiet_will_draw", + "acquire:missed:Occluded", + "on_missed:Occluded:stepped=true", + ] + ); +} + +#[test] +fn post_step_materials_and_reblend_drop_drawable_before_reacquiring() { + let start = crate::time::now(); + let mut host = FakeHost::new(start); + host.acquires = VecDeque::from([Ok(()), Ok(()), Ok(())]); + host.post_checks = VecDeque::from([ + PostStepCheck::Reacquire(ReacquireReason::NativeMaterials), + PostStepCheck::Reacquire(ReacquireReason::Reblend), + PostStepCheck::Keep, + ]); + assert_eq!(run(&mut host), Outcome::Presented); + assert_eq!( + host.events(), + [ + "gate:Draw", + "before_acquire", + "needs_reblend:false", + "acquire:ok:1", + "step_runtime", + "post_step_check:Reacquire(NativeMaterials)", + "drop_drawable:1", + "prepare_reacquire:NativeMaterials:true", + "acquire:ok:2", + "post_step_check:Reacquire(Reblend)", + "drop_drawable:2", + "prepare_reacquire:Reblend:true", + "acquire:ok:3", + "post_step_check:Keep", + "sync_after_step", + "prepare_render:ok:3", + "render:3:comp=false", + "submit_and_present:3", + "present_targets", + "settle:rt_anim=false:anim=false", + ] + ); +} + +#[test] +fn post_step_reblend_failure_drops_drawable_and_misses_with_stepped_true() { + let start = crate::time::now(); + let mut host = FakeHost::new(start); + host.post_checks = VecDeque::from([PostStepCheck::Reacquire(ReacquireReason::Reblend)]); + host.reacquire_ok = VecDeque::from([false]); + assert_eq!(run(&mut host), Outcome::Missed); + assert_eq!( + host.events(), + [ + "gate:Draw", + "before_acquire", + "needs_reblend:false", + "acquire:ok:1", + "step_runtime", + "post_step_check:Reacquire(Reblend)", + "drop_drawable:1", + "prepare_reacquire:Reblend:false", + "on_missed:Unconfigured:stepped=true", + ] + ); +} + +#[test] +fn first_frame_and_compositor_preserve_runtime_and_compositor_animating() { + let start = crate::time::now(); + let mut host = FakeHost::new(start); + host.first_frame = true; + host.compositor_animating = true; + assert_eq!(run(&mut host), Outcome::Presented); + let info = host.settled_info.unwrap(); + assert!(!info.runtime_animating, "runtime itself is at rest on first frame"); + assert!(info.animating, "compositor animating must be OR'd before settle"); + assert_eq!(info.dt, 0.0, "first frame holds clock at dt 0"); +} + +#[test] +fn presented_records_clock_overrun_so_new_motion_does_not_jump() { + let start = crate::time::now(); + let frame = Duration::from_micros(16_667); + let overrun = Duration::from_millis(50); + let mut host = FakeHost::new(start); + + // Frame 0: settle initial layout. + host.step_at = start; + host.submit_at = start; + assert_eq!(run(&mut host), Outcome::Presented); + + // Frame 1: start a spring on an overrunning frame. + host.rt.update(|w, _| *w = 200); + let f1 = start + frame; + host.step_at = f1; + host.submit_at = f1 + overrun; + assert_eq!(run(&mut host), Outcome::Presented); + let w1 = host.rt.presented("box").unwrap().0[2]; + + // Frame 2: one frame after presentation finished; overrun was delayed by host_step::run. + let f2 = f1 + overrun + frame; + host.step_at = f2; + host.submit_at = f2; + assert_eq!(run(&mut host), Outcome::Presented); + let w2 = host.rt.presented("box").unwrap().0[2]; + + // Compare with a reference without overrun delay: delayed frame moves much less than 66 ms. + let mut plain_clock = FrameClock::new(start); + let mut plain = Runtime::new(0u32, |w: &u32, _: &mut Cx<u32>| el().child(el().key("box").size(*w as f32 + 12.0, 8.0)), (300.0, 40.0), Env::default()); + plain.set_system_reduced_motion(false); + plain.wall_start = Some(start); + plain_clock.advance(&mut plain, start, false); + plain.update(|w, _| *w = 200); + plain_clock.advance(&mut plain, f1, false); + plain_clock.advance(&mut plain, f2, false); + let plain_w2 = plain.presented("box").unwrap().0[2]; + + assert!(w2 > w1, "spring advanced on frame 2: w1={w1}, w2={w2}"); + assert!(plain_w2 - w2 > 5.0, "host_step::run must call clock.presented_core to delay overrun: w2={w2}, undelayed={plain_w2}"); +} + +#[test] +fn pre_stepped_path_reblends_acquires_renders_and_records_presented() { + let start = crate::time::now(); + let mut host = FakeHost::new(start); + host.clock = None; + host.pre_reblend_needed = true; + host.gate = Gate::PreStepped(StepInfo { + runtime_animating: false, + animating: false, + dt: 1.0 / 60.0, + update_ms: 0.4, + presents_at: None, + }); + assert_eq!(run(&mut host), Outcome::Presented); + assert_eq!( + host.events(), + [ + "gate:PreStepped", + "needs_reblend:true", + "reblend:true", + "acquire:ok:1", + "post_step_check:Keep", + "sync_after_step", + "prepare_render:ok:1", + "render:1:comp=false", + "submit_and_present:1", + "present_targets", + "settle:rt_anim=false:anim=false", + ] + ); +} + +#[test] +fn prepare_abort_stops_before_render_or_present() { + let start = crate::time::now(); + let mut host = FakeHost::new(start); + host.prepare_abort = true; + assert_eq!(run(&mut host), Outcome::Aborted); + assert_eq!( + host.events(), + [ + "gate:Draw", + "before_acquire", + "needs_reblend:false", + "acquire:ok:1", + "step_runtime", + "post_step_check:Keep", + "sync_after_step", + "prepare_render:abort:1", + ] + ); +} + +#[test] +fn post_step_forced_miss_drops_drawable_and_reports_stepped_true() { + let start = crate::time::now(); + let mut host = FakeHost::new(start); + host.post_checks = VecDeque::from([PostStepCheck::Missed(Missed::Timeout)]); + assert_eq!(run(&mut host), Outcome::Missed); + assert_eq!( + host.events(), + [ + "gate:Draw", + "before_acquire", + "needs_reblend:false", + "acquire:ok:1", + "step_runtime", + "post_step_check:Missed(Timeout)", + "drop_drawable:1", + "on_missed:Timeout:stepped=true", + ] + ); +} + +#[test] +fn post_step_reacquire_miss_reports_stepped_true() { + let start = crate::time::now(); + let mut host = FakeHost::new(start); + host.acquires = VecDeque::from([Ok(()), Err(Missed::Outdated)]); + host.post_checks = VecDeque::from([PostStepCheck::Reacquire(ReacquireReason::Reblend)]); + assert_eq!(run(&mut host), Outcome::Missed); + assert_eq!( + host.events(), + [ + "gate:Draw", + "before_acquire", + "needs_reblend:false", + "acquire:ok:1", + "step_runtime", + "post_step_check:Reacquire(Reblend)", + "drop_drawable:1", + "prepare_reacquire:Reblend:true", + "acquire:missed:Outdated", + "on_missed:Outdated:stepped=true", + ] + ); +} + +#[test] +fn post_step_reacquire_is_capped_at_two_passes() { + let mut phase = Phase::PostStepChecking { reacquired: 2 }; + let effects = step(&mut phase, Event::PostStepReacquire(ReacquireReason::Reblend)); + assert_eq!(phase, Phase::Syncing); + assert_eq!(effects, Effects::one(Effect::Sync)); +} + diff --git a/app/vendor/rune/crates/rune/src/frame/live_log.rs b/app/vendor/rune/crates/rune/src/frame/live_log.rs new file mode 100644 index 0000000..631f4cd --- /dev/null +++ b/app/vendor/rune/crates/rune/src/frame/live_log.rs @@ -0,0 +1,163 @@ +//! `frame-profile` diagnostics for a live window: with `RUNE_FRAME_LOG=FILE`, each frame a +//! window draws is written to FILE as one JSON line, split by stage in nanoseconds: the input +//! handled since the last frame, the drawable wait, the build (view, commit, layout, text, +//! paint, apply), the upload, encode, submit and present, and the thread's CPU. Headless runs +//! write their own log (`profile::Log`). Ordinary builds compile none of this. + +use std::cell::{Cell, RefCell}; +use std::io::Write; + +use super::host_clock::{cpu_ns, now_ns, thread_cpu}; +use super::profile::PHASES; + +thread_local! { + static OUT: RefCell<Option<Option<std::io::BufWriter<std::fs::File>>>> = const { RefCell::new(None) }; + /// Input events handled since the last logged frame, and their time on this thread (ns). + static INPUT: Cell<(u32, u64)> = const { Cell::new((0, 0)) }; + /// Wakes (updates from other threads, timers) handled since the last logged frame, and their time. + static WAKE: Cell<(u32, u64)> = const { Cell::new((0, 0)) }; + /// Where frames were asked for since the last logged frame (Win::request_redraw callers). + /// Tx::wake_after and wake_at callers since the last logged frame, with the shortest wait. + static WAKERS: RefCell<Vec<(&'static std::panic::Location<'static>, std::time::Duration)>> = const { RefCell::new(Vec::new()) }; + static ASKED: RefCell<Vec<&'static std::panic::Location<'static>>> = const { RefCell::new(Vec::new()) }; + /// Frames missed since the last drawn one (occluded, timeout, outdated, unconfigured), and + /// surfaces `acquire` reconfigured and got a drawable from. + static MISSED: Cell<([u32; 4], u32)> = const { Cell::new(([0; 4], 0)) }; +} + +/// Whether frames are logged in this process. +pub(crate) fn on() -> bool { + OUT.with_borrow_mut(|out| { + out.get_or_insert_with(|| { + let path = std::env::var_os("RUNE_FRAME_LOG")?; + std::fs::File::create(&path).ok().map(std::io::BufWriter::new) + }) + .is_some() + }) +} + +/// An input event handled outside a frame, from `start` (ns) to now. +pub(crate) fn input(start: u64) { + let (n, ns) = INPUT.get(); + INPUT.set((n + 1, ns + now_ns().saturating_sub(start))); +} + +/// A wake (WakeEvent) handled outside a frame, from start (ns) to now. +pub(crate) fn wake(start: u64) { + let (n, ns) = WAKE.get(); + WAKE.set((n + 1, ns + now_ns().saturating_sub(start))); +} + +/// A frame asked for at t. +pub(crate) fn asked(at: &'static std::panic::Location<'static>) { + ASKED.with_borrow_mut(|a| if !a.contains(&at) { a.push(at) }); +} + +/// A frame that got no drawable: `kind` 0 occluded, 1 timeout, 2 outdated, 3 unconfigured. +pub(crate) fn missed(kind: usize) { + let (mut m, r) = MISSED.get(); + m[kind.min(3)] += 1; + MISSED.set((m, r)); +} + +/// `acquire` found its surface outdated, reconfigured it, and went on. +pub(crate) fn reconfigured() { + let (m, r) = MISSED.get(); + MISSED.set((m, r + 1)); +} + +/// A timer asked for at t, due after wait. +pub(crate) fn waker(at: &'static std::panic::Location<'static>, wait: std::time::Duration) { + WAKERS.with_borrow_mut(|w| match w.iter_mut().find(|(l, _)| *l == at) { + Some(e) => e.1 = e.1.min(wait), + None => w.push((at, wait)), + }); +} + +/// Now on the monotonic clock, in ns. +pub(crate) fn now() -> u64 { now_ns() } + +/// The clocks at a stage boundary: monotonic and this thread's CPU, in ns. +#[derive(Clone, Copy)] +pub(crate) struct Stamp { pub(crate) wall: u64, pub(crate) cpu: u64 } + +impl Stamp { + pub(crate) fn now() -> Self { Stamp { wall: now_ns(), cpu: thread_cpu().and_then(cpu_ns).unwrap_or(0.0) as u64 } } +} + +/// One drawn frame's stage boundaries and counts. +pub(crate) struct Frame { + /// The draw began: a timer's frame builds before it takes a drawable (prebuild). + pub(crate) entry: Stamp, + pub(crate) start: Stamp, + pub(crate) acquired: Stamp, + pub(crate) built: Stamp, + pub(crate) uploaded: Stamp, + pub(crate) encoded: Stamp, + pub(crate) submitted: Stamp, + pub(crate) presented: Stamp, + /// Wall ms per `profile::Phase` (view, commit, layout, text, paint, apply), then CPU ms. + pub(crate) phases: [f64; 2 * PHASES], + pub(crate) nodes: usize, + pub(crate) shaped: u32, + pub(crate) instances: usize, + pub(crate) animating: bool, + pub(crate) why: u16, + /// Why the window draws another frame: motion, a window frame moving, a commit due, a + /// relayout or queued action, pending input, a live value, a frame request, a timer due by the next tick. + pub(crate) next: u16, + /// The poll's and motion's next timers, in seconds after the last poll. + pub(crate) poll_due: Option<f64>, + pub(crate) loop_due: Option<f64>, + /// The drawn nodes with a running loop, while one wakes the window. + pub(crate) loops: Vec<String>, + /// The rectangle the frame presented (`[x0, y0, x1, y1]`), or None for all of it. + pub(crate) damage: Option<Vec<[i32; 4]>>, + /// Why it drew all of the window (an effect, a layer, a changed image, or most of it changed). + pub(crate) whole: Option<&'static str>, + /// The bounds of what changed (`[x0, y0, x1, y1]`), however much it drew. + pub(crate) change: Option<[u32; 4]>, + /// Only its loops stepped (`Runtime::loop_step`): the instances it wrote, else None. + pub(crate) looped: Option<usize>, + /// Why it wasn't loop-only, when only its loops might have asked for it. + pub(crate) loop_why: Option<&'static str>, + /// `RUNE_LOOP_CHECK=1`: the instances that differ from what the loop-only step would have + /// drawn, and the largest difference. + pub(crate) loop_check: Option<(usize, f32)>, +} + +pub(crate) fn frame(f: Frame) { + let (inputs, input_ns) = INPUT.replace((0, 0)); + let (wakes, wake_ns) = WAKE.replace((0, 0)); + let wakers: Vec<String> = WAKERS.with_borrow_mut(std::mem::take).iter().map(|(l, d)| format!("{}:{} {}ms", l.file(), l.line(), d.as_millis())).collect(); + let asked: Vec<String> = ASKED.with_borrow_mut(std::mem::take).iter().map(|l| format!("{}:{}", l.file(), l.line())).collect(); + let d = |a: Stamp, b: Stamp| b.wall.saturating_sub(a.wall); + let ns = |ms: f64| (ms * 1e6) as u64; + let p = &f.phases; + let next: Vec<&str> = ["motion", "frame_move", "commit", "relayout_or_queue", "input", "live", "window_frame", "timer"] + .into_iter().enumerate().filter(|(i, _)| f.next & (1 << i) != 0).map(|(_, n)| n).collect(); + let line = serde_json::json!({ + "t": f.entry.wall, "inputs": inputs, "input": input_ns, "wakes": wakes, "wake": wake_ns, "asked": asked, "wakers": wakers, + "prebuild": d(f.entry, f.start), "acquire": d(f.start, f.acquired), "build": d(f.acquired, f.built), + "view": ns(p[0]), "commit": ns(p[1]), "layout": ns(p[2]), "text": ns(p[3]), "paint": ns(p[4]), "apply": ns(p[5]), + "upload": d(f.built, f.uploaded), "encode": d(f.uploaded, f.encoded), "submit": d(f.encoded, f.submitted), + "present": d(f.submitted, f.presented), "total": d(f.entry, f.presented), + "cpu": f.presented.cpu.saturating_sub(f.entry.cpu), "build_cpu": f.built.cpu.saturating_sub(f.acquired.cpu), "acquire_cpu": f.acquired.cpu.saturating_sub(f.start.cpu), "encode_cpu": f.encoded.cpu.saturating_sub(f.uploaded.cpu), "submit_cpu": f.submitted.cpu.saturating_sub(f.encoded.cpu), "present_cpu": f.presented.cpu.saturating_sub(f.submitted.cpu), + "nodes": f.nodes, "shaped": f.shaped, "instances": f.instances, "animating": f.animating, + "why": crate::runtime::CommitWhy::names(f.why), + "next": next, "poll_due": f.poll_due, "loop_due": f.loop_due, "loops": f.loops, "damage": f.damage, "whole": f.whole, "change": f.change, + }); + // Apart from the rest: one more key there passes `json!`'s recursion limit. + let mut line = line; + line["looped"] = serde_json::json!(f.looped); + line["loop_why"] = serde_json::json!(f.loop_why); + let (missed, reconfigured) = MISSED.replace(([0; 4], 0)); + if missed != [0; 4] || reconfigured > 0 { line["missed"] = serde_json::json!({ "occluded": missed[0], "timeout": missed[1], "outdated": missed[2], "unconfigured": missed[3], "reconfigured": reconfigured }); } + line["loop_check"] = serde_json::json!(f.loop_check.map(|(n, d)| [n as f64, if d.is_finite() { f64::from(d) } else { -1.0 }])); + OUT.with_borrow_mut(|out| { + if let Some(Some(w)) = out.as_mut() { + writeln!(w, "{line}").ok(); + w.flush().ok(); + } + }); +} diff --git a/app/vendor/rune/crates/rune/src/frame/present_time.rs b/app/vendor/rune/crates/rune/src/frame/present_time.rs new file mode 100644 index 0000000..7323f92 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/frame/present_time.rs @@ -0,0 +1,493 @@ +//! When each traced frame reached the screen, next to when it was meant to. +//! +//! A native `--trace` stamps frames at CPU submission (`t`) and, on macOS, at the display +//! link's target (`target_ms`). Neither shows whether frames reach the screen evenly: two +//! frames can present a fraction of a millisecond apart and leave a gap after them, which +//! reads as a hitch even when every frame's motion is right. On macOS the traced window's +//! layer reports each drawable's Metal `presentedTime`, and the trace writes it as +//! `present_ms`, with `present_dt_ms` from the previous presented frame. Other platforms +//! have no reliable source and write neither. + +use std::collections::VecDeque; +use std::fmt::Write as _; +use std::sync::Arc; +use std::time::Duration; +use crate::machine::Effects; +use crate::time::Instant; + +/// A drawable's sequence number and when it reached the screen, or `None` when the system +/// skipped it. +pub(crate) type Presented = (u64, Option<Instant>); + +/// Where present times come from. Implementations are filled from another thread. +pub(crate) trait Source: Send + Sync { + fn take(&self, out: &mut Vec<Presented>); +} + +/// A frame whose present time hasn't arrived after this many later frames is written +/// without one. Presentation runs two or three frames behind submission. +const WAIT_FRAMES: u32 = 32; + +/// Trace lines held until their frame's present time is known, so each frame's line carries +/// it. Lines stay in submission order. +pub(crate) struct Presents { + source: Arc<dyn Source>, + start: Instant, + pending: VecDeque<Pending>, + cadence: Cadence, + scratch: Vec<Presented>, +} + +struct Pending { + /// The line without its closing brace. + line: String, + present: Present, + /// The previous traced frame asked for this one right away, so the gap between their + /// presents is cadence, not idle time. + continuous: bool, + age: u32, +} + +/// Where a queued frame stands with its present time. +#[derive(Clone, Copy, Debug, PartialEq)] +enum Present { + /// The frame presented no drawable the source tracks. + NoDrawable, + /// Drawable `seq` hasn't reported yet. + Waiting { seq: u64 }, + /// Drawable `seq` reached the screen `at` ms after the trace's start. + Landed { seq: u64, at: f64 }, + /// Metal skipped drawable `seq`. + Skipped { seq: u64 }, +} + +impl Present { + fn new(seq: Option<u64>) -> Present { + seq.map_or(Present::NoDrawable, |seq| Present::Waiting { seq }) + } + + fn seq(self) -> Option<u64> { + match self { + Present::NoDrawable => None, + Present::Waiting { seq } | Present::Landed { seq, .. } | Present::Skipped { seq } => Some(seq), + } + } +} + +/// Whether the next written line's present starts an interval. +#[derive(Clone, Copy, Debug, PartialEq)] +enum Cadence { + /// The last written frame didn't reach the screen, or none was written. + Broken, + /// The last written frame reached the screen `at` ms in. + After(f64), +} + +/// A line leaves the queue: its frame's present, and whether it was drawn right after the frame +/// before. +#[derive(Clone, Copy, Debug)] +struct Written { + present: Present, + continuous: bool, +} + +/// What a written line carries. +#[derive(Clone, Copy, Debug, PartialEq)] +enum Field { + /// `present_ms`, and `present_dt_ms` when the frame before was presented back to back. + At { at: f64, dt: Option<f64> }, + /// `present_ms: null`: Metal skipped the drawable. + Null, +} + +/// An interval spans only frames drawn back to back that both reached the screen. +fn step(cadence: &mut Cadence, event: Written) -> Effects<Field> { + let last = match *cadence { + Cadence::After(last) if event.continuous => Some(last), + _ => None, + }; + match event.present { + Present::Landed { at, .. } => { + *cadence = Cadence::After(at); + Effects::one(Field::At { at, dt: last.map(|last| r3(at - last)) }) + } + Present::Skipped { .. } => { + *cadence = Cadence::Broken; + Effects::one(Field::Null) + } + Present::NoDrawable | Present::Waiting { .. } => { + *cadence = Cadence::Broken; + Effects::none() + } + } +} + +/// Milliseconds from `start`, rounded like the trace's `t`, negative before it. +pub(crate) fn ms_since(start: Instant, at: Instant) -> f64 { + let ms = match at.checked_duration_since(start) { + Some(d) => d.as_secs_f64() * 1000.0, + None => -start.duration_since(at).as_secs_f64() * 1000.0, + }; + r3(ms) +} + +fn r3(v: f64) -> f64 { + (v * 1000.0).round() / 1000.0 +} + +impl Presents { + pub(crate) fn new(source: Arc<dyn Source>, start: Instant) -> Self { + Self { source, start, pending: VecDeque::new(), cadence: Cadence::Broken, scratch: Vec::new() } + } + + /// Queues a frame's line (without its closing brace) and writes every line now complete. + /// `seq`: the drawable the frame presented, if the source tracks it. + pub(crate) fn push(&mut self, line: String, seq: Option<u64>, continuous: bool, out: &mut impl std::io::Write) { + for p in &mut self.pending { p.age += 1; } + self.pending.push_back(Pending { line, present: Present::new(seq), continuous, age: 0 }); + self.poll(); + self.write_ready(out, false); + } + + /// Whether any line still waits for its present time. + pub(crate) fn waiting(&mut self) -> bool { + self.poll(); + self.pending.iter().any(|p| matches!(p.present, Present::Waiting { .. })) + } + + /// Writes every queued line, with or without its present time. + pub(crate) fn flush(&mut self, out: &mut impl std::io::Write) { + self.poll(); + self.write_ready(out, true); + } + + fn poll(&mut self) { + self.source.take(&mut self.scratch); + for (seq, at) in self.scratch.drain(..) { + if let Some(p) = self.pending.iter_mut().find(|p| p.present.seq() == Some(seq)) { + p.present = match at { + Some(at) => Present::Landed { seq, at: ms_since(self.start, at) }, + None => Present::Skipped { seq }, + }; + } + } + } + + fn write_ready(&mut self, out: &mut impl std::io::Write, all: bool) { + while let Some(p) = self.pending.front() { + if !(all || !matches!(p.present, Present::Waiting { .. }) || p.age >= WAIT_FRAMES) { break; } + let p = self.pending.pop_front().unwrap(); + let line = self.finish(p); + writeln!(out, "{line}").ok(); + } + } + + fn finish(&mut self, p: Pending) -> String { + let mut line = p.line; + for field in step(&mut self.cadence, Written { present: p.present, continuous: p.continuous }) { + match field { + Field::At { at, dt } => { + write!(line, r#","present_ms":{at}"#).ok(); + if let Some(dt) = dt { write!(line, r#","present_dt_ms":{dt}"#).ok(); } + } + Field::Null => line.push_str(r#","present_ms":null"#), + } + } + line.push('}'); + line + } +} + +/// Percentiles of a sample, nearest rank. +#[derive(Clone, Copy, Debug, PartialEq)] +pub(crate) struct Spread { + pub p50: f64, + pub p95: f64, + pub max: f64, +} + +impl Spread { + fn of(mut values: Vec<f64>) -> Option<Spread> { + if values.is_empty() { return None; } + values.sort_by(f64::total_cmp); + let rank = |p: f64| values[((p * values.len() as f64).ceil() as usize).clamp(1, values.len()) - 1]; + Some(Spread { p50: rank(0.5), p95: rank(0.95), max: values[values.len() - 1] }) + } +} + +/// Present cadence over a trace. +#[derive(Clone, Debug, PartialEq)] +pub(crate) struct Summary { + pub hz: f64, + pub frames: usize, + /// Frames with a present time. + pub presented: usize, + /// Frames the system skipped (`present_ms: null`). + pub skipped: usize, + /// Present-to-present intervals between frames drawn back to back. + pub interval: Option<Spread>, + /// Intervals under [`BUNCHED_MS`]: frames that reached the screen together. + pub bunched: usize, + /// Intervals over 1.5 refresh periods: a refresh showed nothing new. + pub missed: usize, + /// Present time minus the display link's target. + pub lag: Option<Spread>, +} + +pub(crate) const BUNCHED_MS: f64 = 2.0; + +impl Summary { + /// Summarizes a trace's text. `None` for traces without present times, including every + /// trace written before they existed. + pub(crate) fn of_trace(text: &str) -> Option<Summary> { + let mut lines = text.lines().filter_map(|l| serde_json::from_str::<serde_json::Value>(l).ok()); + let header = lines.next()?; + let hz = header["hz"].as_f64().filter(|hz| *hz > 0.0).unwrap_or(60.0); + let (mut frames, mut presented, mut skipped, mut timed) = (0, 0, 0, false); + let (mut intervals, mut lags) = (Vec::new(), Vec::new()); + for frame in lines.filter(|l| l.get("t").is_some()) { + frames += 1; + let Some(present) = frame.get("present_ms") else { continue }; + timed = true; + let Some(present) = present.as_f64() else { skipped += 1; continue }; + presented += 1; + if let Some(dt) = frame["present_dt_ms"].as_f64() { intervals.push(dt); } + if let Some(target) = frame["target_ms"].as_f64() { lags.push(present - target); } + } + if !timed { return None; } + let missed_ms = 1.5 * 1000.0 / hz; + Some(Summary { + hz, frames, presented, skipped, + bunched: intervals.iter().filter(|dt| **dt < BUNCHED_MS).count(), + missed: intervals.iter().filter(|dt| **dt > missed_ms).count(), + interval: Spread::of(intervals), + lag: Spread::of(lags), + }) + } +} + +impl std::fmt::Display for Summary { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + let spread = |s: Option<Spread>| s.map_or("none".into(), |s| format!("p50 {:.2} p95 {:.2} max {:.2} ms", s.p50, s.p95, s.max)); + write!(f, "present: {} frames, {} presented, {} skipped at {:.0} Hz; interval {}; {} bunched (<{} ms), {} missed (>{:.2} ms); lag {}", + self.frames, self.presented, self.skipped, self.hz, spread(self.interval), self.bunched, BUNCHED_MS, + self.missed, 1.5 * 1000.0 / self.hz, spread(self.lag)) + } +} + +/// How long a finished trace waits for its last frames' present times. +pub(crate) const SETTLE: Duration = Duration::from_millis(150); + +#[cfg(target_os = "macos")] +#[allow(unsafe_code)] +pub(crate) mod metal { + //! Present times from a CAMetalLayer. wgpu acquires and presents the drawable itself and + //! exposes neither, so the traced window's layer becomes an instance of a subclass of its + //! own class whose `nextDrawable` adds a Metal presented handler to each drawable it + //! returns. Only that layer changes, only while tracing or while a transparent window with + //! a shadow needs to know when its frames land (`macos_window_shape`), and it gets its + //! class back when the hook drops. + + use super::{Presented, Source}; + use objc2_metal::MTLDrawable; + use objc2::rc::Retained; + use objc2::runtime::{AnyClass, AnyObject, ClassBuilder, ProtocolObject, Sel}; + use objc2::{Message, msg_send, sel}; + use std::ptr::NonNull; + use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; + use std::ffi::CString; + use std::sync::{Arc, Mutex}; + use std::time::{Duration, Instant}; + + #[link(name = "QuartzCore", kind = "framework")] + unsafe extern "C" { fn CACurrentMediaTime() -> f64; } + + #[link(name = "CoreFoundation", kind = "framework")] + unsafe extern "C" { + fn CFRunLoopGetMain() -> *mut std::ffi::c_void; + fn CFRunLoopWakeUp(run_loop: *mut std::ffi::c_void); + } + + /// Wakes the main run loop for another turn. Callable from any thread. + pub(crate) fn wake_main() { + // SAFETY: CFRunLoopWakeUp is thread-safe; the main run loop lives as long as the process. + unsafe { CFRunLoopWakeUp(CFRunLoopGetMain()) } + } + + /// Drawables acquired and presented on a hooked layer. + #[derive(Default)] + pub(crate) struct Log { + next: AtomicU64, + acquired: AtomicU64, + /// `(seq, presentedTime)`: host seconds, 0 for a skipped drawable. Kept only while tracing. + presented: Mutex<Vec<(u64, f64)>>, + untraced: bool, + /// The newest drawable that reached the screen. + on_screen: AtomicU64, + /// Wake the main run loop when a drawable reaches the screen. + watch: AtomicBool, + } + + impl Log { + /// A log that only tracks which drawable is on screen, for a window that isn't traced. + pub(crate) fn untraced() -> Self { Log { untraced: true, ..Default::default() } } + + /// The drawable the last `nextDrawable` returned, once. + pub(crate) fn acquired(&self) -> Option<u64> { + Some(self.acquired.swap(0, Ordering::AcqRel)).filter(|seq| *seq != 0) + } + + /// The drawable the last `nextDrawable` returned (0 before the first). + pub(crate) fn last_acquired(&self) -> u64 { self.next.load(Ordering::Acquire) } + + /// The newest drawable Metal reported on screen (0 before the first). + pub(crate) fn on_screen(&self) -> u64 { self.on_screen.load(Ordering::Acquire) } + + /// While on, each drawable that reaches the screen wakes the main run loop. + pub(crate) fn watch(&self, on: bool) { self.watch.store(on, Ordering::Release); } + } + + impl Source for Log { + fn take(&self, out: &mut Vec<Presented>) { + let mut presented = self.presented.lock().unwrap(); + if presented.is_empty() { return; } + // SAFETY: CACurrentMediaTime has no preconditions. + let (now, media_now) = (crate::time::now(), unsafe { CACurrentMediaTime() }); + out.extend(presented.drain(..).map(|(seq, at)| (seq, (at > 0.0).then(|| instant_at(now, media_now, at))))); + } + } + + /// The instant of host time `media` (CACurrentMediaTime seconds), given both clocks now. + pub(crate) fn instant_at(now: Instant, media_now: f64, media: f64) -> Instant { + let delta = Duration::from_secs_f64((media - media_now).abs()); + if media >= media_now { now + delta } else { now.checked_sub(delta).unwrap_or(now) } + } + + /// A hooked layer: its address, original class and log. + struct Hooked { addr: usize, base: &'static AnyClass, log: Arc<Log> } + + static LAYERS: Mutex<Vec<Hooked>> = Mutex::new(Vec::new()); + + unsafe extern "C-unwind" fn next_drawable(this: &AnyObject, _: Sel) -> *mut AnyObject { + let addr = this as *const AnyObject as usize; + let hooked = LAYERS.lock().unwrap().iter().find(|h| h.addr == addr).map(|h| (h.base, h.log.clone())); + let base = match hooked { + Some((base, _)) => base, + // The hook dropped while another subclass (key-value observing) sat on top of ours, + // so the class stayed. Skip every hooked class, or `super` lands back here. + None => original_class(this.class()), + }; + // SAFETY: `base` is the layer's original CAMetalLayer class; the result is +0. + let drawable: *mut AnyObject = unsafe { msg_send![super(this, base), nextDrawable] }; + if let (Some((_, log)), Some(raw)) = (hooked, NonNull::new(drawable)) { + let seq = log.next.fetch_add(1, Ordering::Relaxed) + 1; + log.acquired.store(seq, Ordering::Release); + let handler = block2::RcBlock::new(move |d: NonNull<ProtocolObject<dyn MTLDrawable>>| { + // SAFETY: Metal passes the presented drawable for the handler's duration. + let at = unsafe { d.as_ref() }.presentedTime(); + if !log.untraced { log.presented.lock().unwrap().push((seq, at)); } + if at > 0.0 { + log.on_screen.fetch_max(seq, Ordering::AcqRel); + if log.watch.load(Ordering::Acquire) { wake_main(); } + } + }); + // SAFETY: nextDrawable returns a CAMetalDrawable, which conforms to MTLDrawable; + // Metal copies the block. + unsafe { + let drawable = raw.cast::<ProtocolObject<dyn MTLDrawable>>().as_ref(); + drawable.addPresentedHandler(block2::RcBlock::as_ptr(&handler)); + } + } + drawable + } + + const HOOKED_PREFIX: &str = "RunePresentTimed_"; + + /// The superclass of the hooked class nearest the root in `class`'s chain. + fn original_class(class: &'static AnyClass) -> &'static AnyClass { + let mut hooked = None; + let mut next = Some(class); + while let Some(class) = next { + if class.name().to_bytes().starts_with(HOOKED_PREFIX.as_bytes()) { hooked = Some(class); } + next = class.superclass(); + } + hooked.and_then(AnyClass::superclass).expect("next_drawable only runs on a hooked class") + } + + /// The hooked subclass of `base`, made once per class. + fn hooked_class(base: &AnyClass) -> Option<&'static AnyClass> { + static CLASSES: Mutex<Vec<(usize, &'static AnyClass)>> = Mutex::new(Vec::new()); + let mut classes = CLASSES.lock().unwrap(); + let key = base as *const AnyClass as usize; + if let Some((_, class)) = classes.iter().find(|(k, _)| *k == key) { return Some(class); } + let name = CString::new(format!("{HOOKED_PREFIX}{}", base.name().to_str().ok()?)).ok()?; + let class = match ClassBuilder::new(&name, base) { + Some(mut builder) => { + // SAFETY: the signature matches -[CAMetalLayer nextDrawable]. + unsafe { builder.add_method(sel!(nextDrawable), next_drawable as unsafe extern "C-unwind" fn(_, _) -> _); } + builder.register() + } + None => AnyClass::get(&name)?, + }; + classes.push((key, class)); + Some(class) + } + + /// A surface's layer, reporting present times to a [`Log`] until dropped. + pub(crate) struct LayerHook { + layer: Retained<AnyObject>, + base: &'static AnyClass, + class: &'static AnyClass, + } + + impl LayerHook { + /// `None` when the surface isn't a plain CAMetalLayer on Metal. + pub(crate) fn attach(surface: &wgpu::Surface<'_>, log: Arc<Log>) -> Option<Self> { + // SAFETY: the layer is only retained and has its class swapped for a subclass of its + // class without state; wgpu keeps using it as a CAMetalLayer. + // Under wgpu's lock until the class is swapped, so wgpu doesn't use the layer in between. + crate::gpu::with_layer(surface, |layer| Self::hook(layer.retain(), log))? + } + + fn hook(layer: Retained<AnyObject>, log: Arc<Log>) -> Option<Self> { + let metal = AnyClass::get(c"CAMetalLayer")?; + let base = layer.class(); + // SAFETY: isKindOfClass: takes any class. + let is_metal: bool = unsafe { msg_send![&*layer, isKindOfClass: metal] }; + if !is_metal { return None; } + let class = hooked_class(base)?; + LAYERS.lock().unwrap().push(Hooked { addr: Retained::as_ptr(&layer) as usize, base, log }); + // SAFETY: the subclass adds no ivars, so the instance layout is unchanged. + unsafe { AnyObject::set_class(&layer, class) }; + Some(LayerHook { layer, base, class }) + } + } + + impl Drop for LayerHook { + fn drop(&mut self) { + // Leave a class someone else swapped in since (key-value observing) alone. + if std::ptr::eq(self.layer.class(), self.class) { + // SAFETY: restores the original class; layouts are identical. + unsafe { AnyObject::set_class(&self.layer, self.base) }; + } + let addr = Retained::as_ptr(&self.layer) as usize; + LAYERS.lock().unwrap().retain(|h| h.addr != addr); + } + } + + #[cfg(test)] + #[test] + fn host_time_maps_onto_instants() { + let now = crate::time::now(); + assert_eq!(instant_at(now, 100.0, 100.008), now + Duration::from_millis(8)); + assert_eq!(instant_at(now, 100.0, 99.992), now - Duration::from_millis(8)); + } +} + +#[cfg(test)] +#[path = "present_time_tests.rs"] +mod tests; + +#[cfg(test)] +#[path = "present_time_walk_tests.rs"] +mod walk_tests; diff --git a/app/vendor/rune/crates/rune/src/frame/present_time_tests.rs b/app/vendor/rune/crates/rune/src/frame/present_time_tests.rs new file mode 100644 index 0000000..08faafe --- /dev/null +++ b/app/vendor/rune/crates/rune/src/frame/present_time_tests.rs @@ -0,0 +1,153 @@ +use super::*; +use std::sync::Mutex; + +#[derive(Default)] +struct Fake(Mutex<Vec<Presented>>); +impl Source for Fake { + fn take(&self, out: &mut Vec<Presented>) { out.append(&mut self.0.lock().unwrap()); } +} + +fn written(out: &[u8]) -> Vec<serde_json::Value> { + String::from_utf8_lossy(out).lines().map(|l| serde_json::from_str(l).unwrap()).collect() +} + +#[test] +fn lines_wait_for_their_present_time_and_keep_their_order() { + let start = crate::time::now(); + let ms = |n: u64| start + Duration::from_micros(n); + let fake = Arc::new(Fake::default()); + let mut presents = Presents::new(fake.clone(), start); + let mut out = Vec::new(); + presents.push(r#"{"t":1"#.into(), Some(1), false, &mut out); + presents.push(r#"{"t":2"#.into(), Some(2), true, &mut out); + assert!(out.is_empty(), "no line before its present time"); + // Frame 2's present arrives first; frame 1 still holds it back. + fake.0.lock().unwrap().push((2, Some(ms(33_333)))); + presents.push(r#"{"t":3"#.into(), None, true, &mut out); + assert!(out.is_empty() && presents.waiting()); + fake.0.lock().unwrap().extend([(1, Some(ms(25_000)))]); + presents.push(r#"{"t":4"#.into(), Some(3), true, &mut out); + let lines = written(&out); + assert_eq!(lines.len(), 3, "frames 1–3 complete in order: {lines:?}"); + assert_eq!(lines[0]["present_ms"], 25.0); + assert!(lines[0].get("present_dt_ms").is_none(), "the first present has no interval"); + assert_eq!(lines[1]["present_ms"], 33.333); + assert_eq!(lines[1]["present_dt_ms"], 8.333); + assert!(lines[2].get("present_ms").is_none(), "a frame without a drawable has no present field"); + fake.0.lock().unwrap().push((3, None)); + presents.flush(&mut out); + let lines = written(&out); + assert_eq!(lines[3]["t"], 4); + assert!(lines[3]["present_ms"].is_null(), "a skipped drawable is null"); +} + +#[test] +fn idle_gaps_and_lost_presents_do_not_count_as_intervals() { + let start = crate::time::now(); + let fake = Arc::new(Fake::default()); + let mut presents = Presents::new(fake.clone(), start); + let mut out = Vec::new(); + presents.push(r#"{"t":0"#.into(), Some(1), false, &mut out); + fake.0.lock().unwrap().push((1, Some(start))); + // After idle: presented 500 ms later, no interval. + presents.push(r#"{"t":500"#.into(), Some(2), false, &mut out); + fake.0.lock().unwrap().push((2, Some(start + Duration::from_millis(500)))); + // Never reported: written without a present after WAIT_FRAMES later frames. + presents.push(r#"{"t":508"#.into(), Some(3), true, &mut out); + for k in 0..WAIT_FRAMES { presents.push(format!(r#"{{"t":{}"#, 600 + k), None, true, &mut out); } + let lines = written(&out); + assert_eq!(lines.len(), 3 + WAIT_FRAMES as usize); + assert!(lines[1].get("present_dt_ms").is_none(), "an idle gap is not cadence"); + assert!(lines[2].get("present_ms").is_none(), "a present that never came is left out, not faked"); +} + +/// Frames `(seq, continuous, present ms)` around a gap; `None` present: never reported. +/// Returns the last line, which presented 508 ms in, right after the frame before it. +fn after_gap(frames: &[(Option<u64>, bool, Option<Option<u64>>)]) -> serde_json::Value { + let start = crate::time::now(); + let fake = Arc::new(Fake::default()); + let mut presents = Presents::new(fake.clone(), start); + let mut out = Vec::new(); + presents.push(r#"{"t":0"#.into(), Some(100), true, &mut out); + fake.0.lock().unwrap().push((100, Some(start))); + for (k, &(seq, continuous, present)) in frames.iter().enumerate() { + presents.push(format!(r#"{{"t":{}"#, k + 1), seq, continuous, &mut out); + if let (Some(seq), Some(at)) = (seq, present) { + fake.0.lock().unwrap().push((seq, at.map(|ms| start + Duration::from_millis(ms)))); + } + } + presents.push(r#"{"t":"last""#.into(), Some(200), true, &mut out); + fake.0.lock().unwrap().push((200, Some(start + Duration::from_millis(508)))); + presents.flush(&mut out); + let last = written(&out).pop().unwrap(); + assert_eq!((last["t"].as_str(), last["present_ms"].as_f64()), (Some("last"), Some(508.0))); + last +} + +#[test] +fn a_skipped_first_frame_after_idle_starts_no_interval() { + let last = after_gap(&[(Some(1), false, Some(None))]); + assert!(last.get("present_dt_ms").is_none(), "the idle gap is not cadence: {last}"); +} + +#[test] +fn a_frame_without_a_drawable_breaks_the_interval() { + let last = after_gap(&[(None, true, None)]); + assert!(last.get("present_dt_ms").is_none(), "{last}"); +} + +#[test] +fn a_present_that_never_came_breaks_the_interval() { + let last = after_gap(&[(Some(1), true, None)]); + assert!(last.get("present_dt_ms").is_none(), "{last}"); + // The interval still spans two presented frames drawn back to back. + assert_eq!(after_gap(&[(Some(1), true, Some(Some(500)))])["present_dt_ms"], 8.0); +} + +const HEADER: &str = r#"{"type":"header","launch":"rune","width":480,"height":120,"hz":120.0,"scale":2,"clock":"wall"}"#; + +#[test] +fn summary_counts_bunched_and_missed_intervals_and_lag() { + let mut trace = vec![HEADER.to_owned()]; + // target, present, interval + let frames: [(f64, Option<f64>, Option<f64>); 7] = [ + (8.0, Some(25.0), None), + (16.4, Some(33.3), Some(8.3)), + (24.7, Some(33.8), Some(0.5)), // bunched + (33.0, Some(34.6), Some(0.8)), // bunched + (41.4, Some(58.3), Some(23.7)), // missed (> 12.5 ms) + (49.7, None, None), // skipped + (58.0, Some(66.7), Some(8.4)), + ]; + for (k, (target, present, dt)) in frames.into_iter().enumerate() { + let mut line = serde_json::json!({ "t": k, "n": 1, "target_ms": target }); + line["present_ms"] = present.into(); + if let Some(dt) = dt { line["present_dt_ms"] = dt.into(); } + trace.push(line.to_string()); + } + let s = Summary::of_trace(&trace.join("\n")).unwrap(); + assert_eq!((s.frames, s.presented, s.skipped, s.bunched, s.missed), (7, 6, 1, 2, 1)); + let i = s.interval.unwrap(); + assert_eq!((i.p50, i.p95, i.max), (8.3, 23.7, 23.7)); + let lag = s.lag.unwrap(); + assert!((lag.p50 - 9.1).abs() < 1e-9 && (lag.max - 17.0).abs() < 1e-9, "{lag:?}"); + assert!(s.to_string().contains("2 bunched (<2 ms), 1 missed (>12.50 ms)"), "{s}"); +} + +#[test] +fn traces_without_present_times_have_no_summary() { + let old = [HEADER, r#"{"t":0,"n":1,"quality":{"cpu_ms":0.2}}"#, r#"{"t":8.33,"n":1,"e":[[1,0,0,10,10,1,0,0]]}"#].join("\n"); + assert_eq!(Summary::of_trace(&old), None); + // A trace with targets but no present source (another platform) has none either. + let targets = [HEADER, r#"{"t":0,"n":1,"target_ms":8.0}"#].join("\n"); + assert_eq!(Summary::of_trace(&targets), None); + assert_eq!(Summary::of_trace(""), None); +} + +#[test] +fn spread_uses_nearest_rank() { + let s = Spread::of((1..=20).map(f64::from).collect()).unwrap(); + assert_eq!((s.p50, s.p95, s.max), (10.0, 19.0, 20.0)); + assert_eq!(Spread::of(vec![4.0]), Some(Spread { p50: 4.0, p95: 4.0, max: 4.0 })); + assert_eq!(Spread::of(Vec::new()), None); +} diff --git a/app/vendor/rune/crates/rune/src/frame/present_time_walk_tests.rs b/app/vendor/rune/crates/rune/src/frame/present_time_walk_tests.rs new file mode 100644 index 0000000..5763431 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/frame/present_time_walk_tests.rs @@ -0,0 +1,198 @@ +//! Every short sequence of frames, present reports, flushes and waits through [`Presents`], +//! since Metal reports presents in whatever order and at whatever time it likes. Beside the real +//! queue and its [`step`] runs `Old`, a transcription of the fields and branches they replaced, +//! which calls none of them; both must write the same bytes and answer `waiting` the same. + +use super::*; +use std::sync::Mutex; + +// The old code. + +fn old_ms_since(start: Instant, at: Instant) -> f64 { + let ms = match at.checked_duration_since(start) { + Some(d) => d.as_secs_f64() * 1000.0, + None => -start.duration_since(at).as_secs_f64() * 1000.0, + }; + old_r3(ms) +} + +fn old_r3(v: f64) -> f64 { + (v * 1000.0).round() / 1000.0 +} + +struct OldPending { + line: String, + seq: Option<u64>, + present: Option<Option<f64>>, + continuous: bool, + age: u32, +} + +struct Old { + reports: Vec<Presented>, + start: Instant, + pending: VecDeque<OldPending>, + last_present: Option<f64>, + scratch: Vec<Presented>, +} + +impl Old { + fn new(start: Instant) -> Self { + Self { reports: Vec::new(), start, pending: VecDeque::new(), last_present: None, scratch: Vec::new() } + } + + fn push(&mut self, line: String, seq: Option<u64>, continuous: bool, out: &mut impl std::io::Write) { + for p in &mut self.pending { p.age += 1; } + self.pending.push_back(OldPending { line, seq, present: None, continuous, age: 0 }); + self.poll(); + self.write_ready(out, false); + } + + fn waiting(&mut self) -> bool { + self.poll(); + self.pending.iter().any(|p| p.seq.is_some() && p.present.is_none()) + } + + fn flush(&mut self, out: &mut impl std::io::Write) { + self.poll(); + self.write_ready(out, true); + } + + fn poll(&mut self) { + self.scratch.append(&mut self.reports); + for (seq, at) in self.scratch.drain(..) { + if let Some(p) = self.pending.iter_mut().find(|p| p.seq == Some(seq)) { + p.present = Some(at.map(|at| old_ms_since(self.start, at))); + } + } + } + + fn write_ready(&mut self, out: &mut impl std::io::Write, all: bool) { + while let Some(p) = self.pending.front() { + if !(all || p.seq.is_none() || p.present.is_some() || p.age >= WAIT_FRAMES) { break; } + let p = self.pending.pop_front().unwrap(); + let line = self.finish(p); + writeln!(out, "{line}").ok(); + } + } + + fn finish(&mut self, p: OldPending) -> String { + let mut line = p.line; + if !p.continuous { self.last_present = None; } + match (p.seq, p.present) { + (Some(_), Some(Some(at))) => { + write!(line, r#","present_ms":{at}"#).ok(); + if let Some(last) = self.last_present { + write!(line, r#","present_dt_ms":{}"#, old_r3(at - last)).ok(); + } + self.last_present = Some(at); + } + (Some(_), Some(None)) => { + line.push_str(r#","present_ms":null"#); + self.last_present = None; + } + _ => self.last_present = None, + } + line.push('}'); + line + } +} + +// The walk. + +#[derive(Default)] +struct Fake(Mutex<Vec<Presented>>); + +impl Source for Fake { + fn take(&self, out: &mut Vec<Presented>) { out.append(&mut self.0.lock().unwrap()); } +} + +#[derive(Clone, Copy, Debug)] +enum Ev { + Push { seq: Option<u64>, continuous: bool }, + /// Drawable `seq` landed (`Some`, at a time set by the event's place) or was skipped. + Report { seq: u64, landed: bool }, + Flush, + Waiting, + /// `WAIT_FRAMES` frames without a drawable, so every line still waiting expires. + Expire, +} + +const ALPHABET: [Ev; 9] = [ + Ev::Push { seq: Some(1), continuous: true }, + Ev::Push { seq: Some(2), continuous: false }, + Ev::Push { seq: None, continuous: true }, + Ev::Report { seq: 1, landed: true }, + Ev::Report { seq: 2, landed: true }, + Ev::Report { seq: 1, landed: false }, + Ev::Flush, + Ev::Waiting, + Ev::Expire, +]; + +fn walk(events: &[Ev]) { + let start = crate::time::now(); + let fake = Arc::new(Fake::default()); + let mut new = Presents::new(fake.clone(), start); + let mut old = Old::new(start); + let (mut new_out, mut old_out) = (Vec::new(), Vec::new()); + let mut frame = 0; + for (k, &ev) in events.iter().enumerate() { + match ev { + Ev::Push { seq, continuous } => { + frame += 1; + new.push(format!(r#"{{"t":{frame}"#), seq, continuous, &mut new_out); + old.push(format!(r#"{{"t":{frame}"#), seq, continuous, &mut old_out); + } + Ev::Report { seq, landed } => { + let at = landed.then(|| start + Duration::from_micros(7_333 * (k as u64 + 1))); + fake.0.lock().unwrap().push((seq, at)); + old.reports.push((seq, at)); + } + Ev::Flush => { + new.flush(&mut new_out); + old.flush(&mut old_out); + } + Ev::Waiting => assert_eq!(new.waiting(), old.waiting(), "waiting after {:?}", &events[..=k]), + Ev::Expire => for _ in 0..WAIT_FRAMES { + frame += 1; + new.push(format!(r#"{{"t":{frame}"#), None, true, &mut new_out); + old.push(format!(r#"{{"t":{frame}"#), None, true, &mut old_out); + }, + } + assert_eq!(String::from_utf8_lossy(&new_out), String::from_utf8_lossy(&old_out), "after {:?}", &events[..=k]); + } + new.flush(&mut new_out); + old.flush(&mut old_out); + assert_eq!(String::from_utf8_lossy(&new_out), String::from_utf8_lossy(&old_out), "flushed after {events:?}"); +} + +#[test] +fn every_sequence_of_frames_and_reports_writes_what_the_old_queue_wrote() { + const LEN: u32 = 5; + let mut seq = Vec::with_capacity(LEN as usize); + for len in 1..=LEN { + for n in 0..ALPHABET.len().pow(len) { + seq.clear(); + let mut n = n; + for _ in 0..len { + seq.push(ALPHABET[n % ALPHABET.len()]); + n /= ALPHABET.len(); + } + walk(&seq); + } + } +} + +#[test] +fn an_interval_needs_two_landed_frames_drawn_back_to_back() { + let mut cadence = Cadence::Broken; + let landed = |at| Written { present: Present::Landed { seq: 1, at }, continuous: true }; + assert_eq!(step(&mut cadence, landed(10.0)), Effects::one(Field::At { at: 10.0, dt: None })); + assert_eq!(step(&mut cadence, landed(18.5)), Effects::one(Field::At { at: 18.5, dt: Some(8.5) })); + let idle = Written { present: Present::Landed { seq: 2, at: 500.0 }, continuous: false }; + assert_eq!(step(&mut cadence, idle), Effects::one(Field::At { at: 500.0, dt: None })); + assert_eq!(step(&mut cadence, Written { present: Present::Skipped { seq: 3 }, continuous: true }), Effects::one(Field::Null)); + assert_eq!(cadence, Cadence::Broken); + assert_eq!(step(&mut cadence, Written { present: Present::Waiting { seq: 4 }, continuous: true }), Effects::none()); +} diff --git a/app/vendor/rune/crates/rune/src/frame/present_worker.rs b/app/vendor/rune/crates/rune/src/frame/present_worker.rs new file mode 100644 index 0000000..07a96b7 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/frame/present_worker.rs @@ -0,0 +1,123 @@ +//! A thread that finishes, submits and presents a surface's frames, so the event loop's thread +//! records a frame and moves on: wgpu-core encodes the recorded passes at `finish`, and +//! `finish`, `submit` and `present` are most of a simple frame's CPU time. +//! +//! One job is in flight at most. The owner calls `wait` before it next touches the surface +//! (acquire, configure, drop), because wgpu lends a surface one texture at a time. + +use std::sync::mpsc; +use std::thread::JoinHandle; + +use crate::machine::Effects; + +type Job = Box<dyn FnOnce() + Send>; + +pub(crate) struct PresentWorker { + state: State, + done: mpsc::Receiver<std::thread::Result<()>>, + thread: Option<JoinHandle<()>>, +} + +/// Where jobs run. +enum State { + /// On the thread, which has finished the job before. + Idle(mpsc::Sender<Job>), + /// On the thread, which may still be running the last job sent. + Busy(mpsc::Sender<Job>), + /// On the owner's thread: a job panicked, or the worker is closing. + Inline, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Event { + /// The owner waits for the job in flight. + Wait, + /// The thread took a job. + Sent, + /// The job waited for panicked. + Panicked, + /// The worker drops. + Close, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Effect { + /// Block for the job in flight's result. + Recv, +} + +fn step(state: &mut State, event: Event) -> Effects<Effect> { + let mut effects = Effects::none(); + *state = match (std::mem::replace(state, State::Inline), event) { + (State::Busy(jobs), Event::Wait) => { + effects.push(Effect::Recv); + State::Idle(jobs) + } + (State::Idle(jobs), Event::Sent) => State::Busy(jobs), + (_, Event::Panicked | Event::Close) => State::Inline, + (state, _) => state, + }; + effects +} + +impl PresentWorker { + /// `None` when the thread can't be made; the caller presents on its own thread. + pub(crate) fn spawn() -> Option<PresentWorker> { + let (jobs, inbox) = mpsc::channel::<Job>(); + let (finished, done) = mpsc::channel(); + let thread = std::thread::Builder::new().name("rune present".into()).spawn(move || { + #[cfg(target_os = "macos")] + interactive(); + while let Ok(job) = inbox.recv() { + let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(job)); + if finished.send(result).is_err() { break; } + } + }).ok()?; + Some(PresentWorker { state: State::Idle(jobs), done, thread: Some(thread) }) + } + + /// Runs `job` on the thread once the job before it has finished. + pub(crate) fn run(&mut self, job: impl FnOnce() + Send + 'static) { + self.wait(); + let State::Idle(jobs) = &self.state else { return job() }; + match jobs.send(Box::new(job)) { + Ok(()) => { step(&mut self.state, Event::Sent); } + Err(mpsc::SendError(job)) => job(), + } + } + + /// Blocks until the job in flight, if any, has finished. A job that panicked panics here, + /// on the owner's thread, as it would have without the worker. + pub(crate) fn wait(&mut self) { + for Effect::Recv in step(&mut self.state, Event::Wait) { + if let Ok(Err(panic)) = self.done.recv() { + step(&mut self.state, Event::Panicked); + std::panic::resume_unwind(panic); + } + } + } +} + +impl Drop for PresentWorker { + fn drop(&mut self) { + if matches!(self.state, State::Busy(_)) && !std::thread::panicking() { self.wait(); } + step(&mut self.state, Event::Close); + if let Some(thread) = self.thread.take() { thread.join().ok(); } + } +} + +/// Presents keep pace with the display only at the main thread's priority. +#[cfg(target_os = "macos")] +#[allow(unsafe_code)] +fn interactive() { + const QOS_CLASS_USER_INTERACTIVE: u32 = 0x21; + unsafe extern "C" { + fn pthread_set_qos_class_self_np(class: u32, relative_priority: i32) -> i32; + } + // SAFETY: sets the calling thread's own QoS class. + unsafe { pthread_set_qos_class_self_np(QOS_CLASS_USER_INTERACTIVE, 0) }; +} + +#[cfg(test)] +#[path = "present_worker_tests.rs"] +mod tests; diff --git a/app/vendor/rune/crates/rune/src/frame/present_worker_tests.rs b/app/vendor/rune/crates/rune/src/frame/present_worker_tests.rs new file mode 100644 index 0000000..139b120 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/frame/present_worker_tests.rs @@ -0,0 +1,196 @@ +use super::*; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::{Arc, Mutex}; +use std::time::Duration; + +#[test] +fn jobs_run_off_the_callers_thread_in_order_and_wait_sees_them_done() { + let mut worker = PresentWorker::spawn().expect("a thread"); + let caller = std::thread::current().id(); + let log = Arc::new(Mutex::new(Vec::new())); + for i in 0..4 { + let log = log.clone(); + worker.run(move || { + std::thread::sleep(Duration::from_millis(5)); + assert_ne!(std::thread::current().id(), caller); + log.lock().unwrap().push(i); + }); + } + worker.wait(); + assert_eq!(*log.lock().unwrap(), [0, 1, 2, 3]); +} + +#[test] +fn run_returns_before_its_job_finishes() { + let mut worker = PresentWorker::spawn().expect("a thread"); + let (release, gate) = std::sync::mpsc::channel::<()>(); + let done = Arc::new(AtomicUsize::new(0)); + let flag = done.clone(); + worker.run(move || { + gate.recv().unwrap(); + flag.store(1, Ordering::SeqCst); + }); + assert_eq!(done.load(Ordering::SeqCst), 0, "the caller went on while the job waited"); + release.send(()).unwrap(); + worker.wait(); + assert_eq!(done.load(Ordering::SeqCst), 1); +} + +#[test] +fn dropping_the_worker_finishes_the_job_in_flight() { + let done = Arc::new(AtomicUsize::new(0)); + let flag = done.clone(); + let mut worker = PresentWorker::spawn().expect("a thread"); + worker.run(move || { + std::thread::sleep(Duration::from_millis(20)); + flag.store(1, Ordering::SeqCst); + }); + drop(worker); + assert_eq!(done.load(Ordering::SeqCst), 1); +} + +#[test] +fn a_panicking_job_panics_on_the_owners_thread() { + let mut worker = PresentWorker::spawn().expect("a thread"); + worker.run(|| panic!("device lost")); + let caught = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| worker.wait())); + let message = caught.expect_err("the panic came back").downcast::<&str>().map(|m| *m); + assert_eq!(message.ok(), Some("device lost")); + let ran = Arc::new(AtomicUsize::new(0)); + let flag = ran.clone(); + worker.run(move || { flag.store(1, Ordering::SeqCst); }); + worker.wait(); + assert_eq!(ran.load(Ordering::SeqCst), 1, "later jobs run on the caller's thread"); +} + +// Every short sequence of jobs, panicking jobs and waits, then the drop, through the real worker +// and its `step`, beside `Old`: a transcription of the fields and branches they replaced +// (`jobs: Option<Sender>`, `in_flight: bool`), which calls none of them. Both must run the same +// jobs on the same threads in the same order, and panic at the same calls with the same payload. + +type OldJob = Box<dyn FnOnce() + Send>; + +struct Old { + jobs: Option<std::sync::mpsc::Sender<OldJob>>, + done: std::sync::mpsc::Receiver<std::thread::Result<()>>, + in_flight: bool, + thread: Option<std::thread::JoinHandle<()>>, +} + +impl Old { + // The thread's QoS class isn't observable here, so the transcription leaves it out. + fn spawn() -> Option<Old> { + let (jobs, inbox) = std::sync::mpsc::channel::<OldJob>(); + let (finished, done) = std::sync::mpsc::channel(); + let thread = std::thread::Builder::new().name("old present".into()).spawn(move || { + while let Ok(job) = inbox.recv() { + let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(job)); + if finished.send(result).is_err() { break; } + } + }).ok()?; + Some(Old { jobs: Some(jobs), done, in_flight: false, thread: Some(thread) }) + } + + fn run(&mut self, job: impl FnOnce() + Send + 'static) { + self.wait(); + let Some(jobs) = &self.jobs else { return job() }; + match jobs.send(Box::new(job)) { + Ok(()) => self.in_flight = true, + Err(std::sync::mpsc::SendError(job)) => job(), + } + } + + fn wait(&mut self) { + if !std::mem::take(&mut self.in_flight) { return; } + if let Ok(Err(panic)) = self.done.recv() { + self.jobs = None; + std::panic::resume_unwind(panic); + } + } +} + +impl Drop for Old { + fn drop(&mut self) { + if self.in_flight && !std::thread::panicking() { self.wait(); } + self.jobs = None; + if let Some(thread) = self.thread.take() { thread.join().ok(); } + } +} + +#[derive(Clone, Copy, Debug)] +enum Ev { + Run, + RunPanicking, + Wait, +} + +/// Jobs that ran: `(id, on the caller's thread)`. +type Log = Arc<Mutex<Vec<(usize, bool)>>>; + +fn job(log: &Log, id: usize, panics: bool) -> impl FnOnce() + Send + 'static { + let (log, caller) = (log.clone(), std::thread::current().id()); + move || { + log.lock().unwrap().push((id, std::thread::current().id() == caller)); + if panics { std::panic::panic_any(id); } + } +} + +/// What a call did: `None`, or the id the job that panicked into it carried. +fn outcome(f: impl FnOnce()) -> Option<usize> { + std::panic::catch_unwind(std::panic::AssertUnwindSafe(f)).err().map(|p| *p.downcast::<usize>().expect("a job's id")) +} + +fn walk(events: &[Ev]) { + let (new_log, old_log) = (Log::default(), Log::default()); + let mut new = PresentWorker::spawn().expect("a thread"); + let mut old = Old::spawn().expect("a thread"); + for (id, &ev) in events.iter().enumerate() { + let (n, o) = match ev { + Ev::Run | Ev::RunPanicking => { + let panics = matches!(ev, Ev::RunPanicking); + let (nj, oj) = (job(&new_log, id, panics), job(&old_log, id, panics)); + (outcome(|| new.run(nj)), outcome(|| old.run(oj))) + } + Ev::Wait => (outcome(|| new.wait()), outcome(|| old.wait())), + }; + assert_eq!(n, o, "call {id} of {events:?}"); + if let Ev::Wait = ev { + assert_eq!(*new_log.lock().unwrap(), *old_log.lock().unwrap(), "after wait {id} of {events:?}"); + } + } + assert_eq!(outcome(move || drop(new)), outcome(move || drop(old)), "drop after {events:?}"); + assert_eq!(*new_log.lock().unwrap(), *old_log.lock().unwrap(), "after drop of {events:?}"); +} + +#[test] +fn every_sequence_of_jobs_and_waits_runs_as_the_old_worker_did() { + const ALPHABET: [Ev; 3] = [Ev::Run, Ev::RunPanicking, Ev::Wait]; + const LEN: u32 = 6; + let mut seq = Vec::with_capacity(LEN as usize); + for len in 0..=LEN { + for n in 0..ALPHABET.len().pow(len) { + seq.clear(); + let mut n = n; + for _ in 0..len { + seq.push(ALPHABET[n % ALPHABET.len()]); + n /= ALPHABET.len(); + } + walk(&seq); + } + } +} + +#[test] +fn the_state_holds_the_sender_only_while_jobs_go_to_the_thread() { + let (jobs, _inbox) = std::sync::mpsc::channel::<Job>(); + let mut state = State::Idle(jobs); + assert!(step(&mut state, Event::Wait).is_empty(), "nothing in flight"); + assert!(step(&mut state, Event::Sent).is_empty()); + assert!(matches!(state, State::Busy(_))); + assert_eq!(step(&mut state, Event::Wait), Effects::one(Effect::Recv)); + assert!(matches!(state, State::Idle(_))); + step(&mut state, Event::Panicked); + assert!(matches!(state, State::Inline)); + assert!(step(&mut state, Event::Sent).is_empty() && step(&mut state, Event::Wait).is_empty()); + assert!(matches!(state, State::Inline), "a panicked worker runs jobs inline for good"); +} diff --git a/app/vendor/rune/crates/rune/src/frame/profile.rs b/app/vendor/rune/crates/rune/src/frame/profile.rs new file mode 100644 index 0000000..3f9f033 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/frame/profile.rs @@ -0,0 +1,243 @@ +//! Opt-in headless phase timings. No clocks or allocator hooks in ordinary builds. +//! Commit and Layout include their nested phases; these overlapping times must not be summed. +#[derive(Clone, Copy)] +pub(crate) enum Phase { View, Commit, Layout, Text, Paint, Apply } + +/// Phases timed, each with a wall and a CPU column. +#[cfg_attr(not(feature = "frame-profile"), allow(dead_code))] +pub const PHASES: usize = 6; + +/// CPU consumed by this thread, excluding time the scheduler runs other work. Debug builds +/// time app callbacks with it for `perf_warn`, and interaction timing its input frames. +/// On Windows it counts the thread's cycles (`QueryThreadCycleTime`), so short phases read +/// true; `GetThreadTimes` moves in 15.6 ms ticks. +pub(crate) fn cpu_ms() -> Option<f64> { + #[cfg(any(unix, windows))] + { super::host_clock::thread_cpu().and_then(super::host_clock::cpu_ns).map(|ns| ns / 1e6) } + #[cfg(not(any(unix, windows)))] + { None } +} + +#[cfg(feature = "frame-profile")] +mod enabled { + use super::{PHASES, Phase, cpu_ms}; + use crate::time::Instant; + use std::cell::Cell; + + thread_local! { + static TIMES: Cell<[f64; 2 * PHASES]> = const { Cell::new([0.0; 2 * PHASES]) }; + } + + pub(crate) struct Scope(Phase, Instant, Option<f64>); + impl Scope { + pub(crate) fn new(phase: Phase) -> Self { Self(phase, crate::time::now(), cpu_ms()) } + } + impl Drop for Scope { + fn drop(&mut self) { + if crate::tooling::perf_warn::budget::on() { crate::tooling::perf_warn::budget::add(self.0, self.1.elapsed().as_secs_f64() * 1000.0); } + if crate::tooling::interaction::active() { crate::tooling::interaction::add(self.0, self.1.elapsed().as_secs_f64() * 1000.0); } + TIMES.with(|times| { + let mut row = times.get(); + row[self.0 as usize] += self.1.elapsed().as_secs_f64() * 1000.0; + if let (Some(start), Some(end)) = (self.2, cpu_ms()) { row[self.0 as usize + PHASES] += end - start; } + times.set(row); + }); + } + } + pub(crate) fn take() -> [f64; 2 * PHASES] { TIMES.replace([0.0; 2 * PHASES]) } +} + +#[cfg(feature = "frame-profile")] +pub(crate) use enabled::{Scope, take}; + +/// One headless frame: phase times (wall then CPU), the update and encode split, and counts. +#[cfg(feature = "frame-profile")] +pub(crate) struct Row { + pub phases: [f64; 2 * PHASES], + pub update_ms: f64, + pub encode_ms: f64, + /// Script events delivered before this frame. + pub events: usize, + pub allocations: u64, + pub commits: u64, + /// Why the frame committed, as `runtime::commit_why::CommitWhy` bits. + pub why: u16, + pub shaped: u32, + pub animating: bool, + pub cpu_ms: Option<f64>, +} + +/// A headless run's frames. With `RUNE_FRAME_LOG=FILE`, each frame is also written to FILE as a +/// JSON line as it ends, then a closing line with the process's memory footprint, so a run can +/// be read as a distribution (p99, worst, frames over budget) rather than the summary's means. +#[cfg(feature = "frame-profile")] +pub(crate) struct Log { + rows: Vec<Row>, + out: Option<std::io::BufWriter<std::fs::File>>, +} + +#[cfg(feature = "frame-profile")] +impl Log { + pub(crate) fn new(frames: usize) -> Self { + install_text_hook(); + let out = std::env::var_os("RUNE_FRAME_LOG").map(|path| { + let file = std::fs::File::create(&path).unwrap_or_else(|e| panic!("RUNE_FRAME_LOG {}: {e}", path.to_string_lossy())); + std::io::BufWriter::new(file) + }); + Self { rows: Vec::with_capacity(frames), out } + } + + pub(crate) fn push(&mut self, row: Row) { + if let Some(out) = self.out.as_mut() { + use std::io::Write; + let p = &row.phases; + let mut line = serde_json::json!({ + "k": self.rows.len(), "ms": row.update_ms + row.encode_ms, "cpu_ms": row.cpu_ms, "events": row.events, "update_ms": row.update_ms, "encode_ms": row.encode_ms, + "view_cpu": p[PHASES], "commit_cpu": p[PHASES + 1], "layout_cpu": p[PHASES + 2], "text_cpu": p[PHASES + 3], + "paint_cpu": p[PHASES + 4], "apply_cpu": p[PHASES + 5], "allocations": row.allocations, + "commits": row.commits, "shaped": row.shaped, "animating": row.animating, + }); + if row.commits > 0 { line["why"] = crate::runtime::CommitWhy::names(row.why).into(); } + writeln!(out, "{line}").expect("RUNE_FRAME_LOG write"); + } + self.rows.push(row); + } + + /// Prints the `rune-frame-profile` means (first frame left out) and closes the log. + pub(crate) fn report(&mut self) { + let rows = &self.rows[usize::from(self.rows.len() > 1)..]; + let n = rows.len() as f64; + let avg = |f: &dyn Fn(&Row) -> f64| rows.iter().map(f).sum::<f64>() / n; + let cpu = rows.first().and_then(|r| r.cpu_ms).is_some(); + let phase_cpu = |i: usize| cpu.then(|| avg(&|r| r.phases[PHASES + i])); + eprintln!("rune-frame-profile {}", serde_json::json!({ + "view_ms": avg(&|r| r.phases[0]), "commit_inclusive_ms": avg(&|r| r.phases[1]), + "layout_inclusive_ms": avg(&|r| r.phases[2]), "shape_ms": avg(&|r| r.phases[3]), + "paint_ms": avg(&|r| r.phases[4]), "apply_ms": avg(&|r| r.phases[5]), + "update_ms": avg(&|r| r.update_ms), "encode_submit_ms": avg(&|r| r.encode_ms), + "allocations": avg(&|r| r.allocations as f64), "commits": avg(&|r| r.commits as f64), + "shaped": avg(&|r| r.shaped as f64), "animating_fraction": avg(&|r| u8::from(r.animating) as f64), + "thread_cpu_ms": cpu.then(|| avg(&|r| r.cpu_ms.unwrap_or(0.0))), + "view_cpu_ms": phase_cpu(0), "commit_cpu_ms": phase_cpu(1), "layout_cpu_ms": phase_cpu(2), + "shape_cpu_ms": phase_cpu(3), "paint_cpu_ms": phase_cpu(4), "apply_cpu_ms": phase_cpu(5), + })); + if let Some(mut out) = self.out.take() { + use std::io::Write; + let mem = procwatch::snapshot(); + let line = serde_json::json!({ + "end": true, "frames": self.rows.len(), + "footprint": mem.as_ref().map(|m| m.footprint), "footprint_peak": mem.as_ref().map(|m| m.footprint_peak), + "resident": mem.as_ref().map(|m| m.resident), + "heap_live": mem.as_ref().and_then(|m| m.heap.as_ref()).map(|h| h.live), + }); + writeln!(out, "{line}").and_then(|()| out.flush()).expect("RUNE_FRAME_LOG write"); + } + } +} + +/// Wall then CPU milliseconds per phase (view, commit, layout, text, paint, apply) on this thread +/// since the last call, for benches that drive a `Runtime` themselves. +#[cfg(feature = "frame-profile")] +pub fn take_frame_phases() -> [f64; 2 * PHASES] { + install_text_hook(); + take() +} + +/// This thread's CPU clock in milliseconds. On Windows its first call waits (at most 50 ms) for the +/// cycles' rate, so a bench's first reading is a real one, not 0. +#[cfg(feature = "frame-profile")] +pub fn thread_cpu_ms() -> f64 { + #[cfg(windows)] + super::host_clock::cycles_per_ns_waiting(); + cpu_ms().unwrap_or(0.0) +} + +/// This thread's own CPU time in nanoseconds: its cycles on Windows (`QueryThreadCycleTime`), +/// `CLOCK_THREAD_CPUTIME_ID` elsewhere. It stands still while the thread waits or the system +/// runs something else, so a budget kept on it charges only work the thread did. `None` where +/// there is no such clock (the browser, Windows on ARM), when the OS can't read it, and on Windows +/// for the first 20 ms after the process first asks, while the cycles' rate is measured. +pub fn thread_cpu_ns() -> Option<f64> { + #[cfg(any(unix, windows))] + return super::host_clock::thread_cpu().and_then(super::host_clock::cpu_ns); + #[cfg(not(any(unix, windows)))] + None +} +/// A reading of this thread's CPU clock in its raw units ([`thread_cpu_mark`]), taken now and +/// converted later ([`thread_cpu_since`]): a mark taken before Windows knows the cycles' rate still +/// measures from that moment once it does. +#[derive(Clone, Copy, Debug)] +pub struct ThreadCpuMark(u64); + +/// This thread's CPU clock now, raw; `None` where there is none or it can't be read. On Windows it +/// also starts measuring the cycles' rate (no wait). +pub fn thread_cpu_mark() -> Option<ThreadCpuMark> { + #[cfg(windows)] + super::host_clock::cycles_per_ns(); + #[cfg(any(unix, windows))] + return super::host_clock::thread_cpu().map(ThreadCpuMark); + #[cfg(not(any(unix, windows)))] + None +} + +/// Nanoseconds of this thread's CPU time since `mark` (taken on this thread); `None` until the +/// rate is known (Windows, the first 20 ms) or when the clock can't be read. +pub fn thread_cpu_since(mark: ThreadCpuMark) -> Option<f64> { + #[cfg(any(unix, windows))] + return super::host_clock::thread_cpu().and_then(|now| super::host_clock::cpu_ns(now.saturating_sub(mark.0))); + #[cfg(not(any(unix, windows)))] + { + let _ = mark; + None + } +} + +/// Without `frame-profile`, a phase is timed only for `RUNE_COMMIT_BUDGET_MS` +/// (`perf_warn::budget`) and in a frame interaction timing follows (`tooling::interaction`), +/// and otherwise costs a cached flag and a thread-local one. +#[cfg(not(feature = "frame-profile"))] +pub(crate) struct Scope(Option<(Phase, crate::time::Instant)>); +#[cfg(not(feature = "frame-profile"))] +impl Scope { + #[inline(always)] + pub(crate) fn new(phase: Phase) -> Self { + Self((crate::tooling::perf_warn::budget::on() || crate::tooling::interaction::active()).then(|| (phase, crate::time::now()))) + } +} +#[cfg(not(feature = "frame-profile"))] +impl Drop for Scope { + #[inline(always)] + fn drop(&mut self) { + let Some((phase, start)) = self.0 else { return }; + let ms = start.elapsed().as_secs_f64() * 1000.0; + if crate::tooling::perf_warn::budget::on() { crate::tooling::perf_warn::budget::add(phase, ms); } + if crate::tooling::interaction::active() { crate::tooling::interaction::add(phase, ms); } + } +} + +thread_local! { + static TEXT_SCOPES: std::cell::RefCell<Vec<Scope>> = const { std::cell::RefCell::new(Vec::new()) }; +} + +fn enter_text_phase() -> crate::text::profile::Token { + #[cfg(not(feature = "frame-profile"))] + if !crate::tooling::perf_warn::budget::on() && !crate::tooling::interaction::active() { + return 0; + } + TEXT_SCOPES.with_borrow_mut(|scopes| scopes.push(Scope::new(Phase::Text))); + 1 +} + +fn exit_text_phase(_token: crate::text::profile::Token) { + TEXT_SCOPES.with_borrow_mut(|scopes| { + scopes.pop(); + }); +} + +/// Registers this crate's `Phase::Text` timing hooks with `rune-text`, once per process. +pub(crate) fn install_text_hook() { + static INSTALLED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + if !INSTALLED.swap(true, std::sync::atomic::Ordering::Relaxed) { + crate::text::profile::set_text_phase_hooks(enter_text_phase, exit_text_phase); + } +} diff --git a/app/vendor/rune/crates/rune/src/frame/surface_stats.rs b/app/vendor/rune/crates/rune/src/frame/surface_stats.rs new file mode 100644 index 0000000..22adee5 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/frame/surface_stats.rs @@ -0,0 +1,290 @@ +//! What each window and overlay surface asked for, drew and missed, as totals and per-second +//! rates. A surface that keeps failing to get drawables, or redraws unpaced, hundreds of times +//! a second for more than two seconds is a bug (it spins a core and, on wgpu 30.0.1, leaks a +//! texture id per failed acquisition), so the meter says so once, in release builds too. + +use std::sync::{Arc, Mutex}; +use std::time::Duration; +use crate::time::Instant; + +use crate::machine::Effects; +use crate::window::Missed; + +/// Counts of one surface's frame work. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +#[non_exhaustive] +pub struct SurfaceCounts { + /// Frames the host set out to draw while shown, once its display link (if running) gave it + /// the frame. + pub redraws: u64, + /// Redraws that waited for nothing: no display tick, vsync, timer or event came first. + pub unpaced: u64, + /// Frames presented. + pub presents: u64, + /// Acquisitions skipped because the surface was known to be occluded, so wgpu was never asked. + pub skipped: u64, + /// `get_current_texture` calls that gave no drawable: occluded. + pub occluded: u64, + /// ...timed out, or failed some other passing way. + pub timeouts: u64, + /// ...outdated or lost, after reconfiguring. + pub outdated: u64, + /// Event-loop turns while the surface's host lived. + pub turns: u64, + /// Turns a deadline or poll started, rather than an event. + pub wakes: u64, +} + +impl SurfaceCounts { + /// Every `get_current_texture` call that gave no drawable. + pub fn failed(&self) -> u64 { self.occluded + self.timeouts + self.outdated } + + fn since(&self, earlier: &SurfaceCounts) -> SurfaceCounts { + SurfaceCounts { + redraws: self.redraws - earlier.redraws, + unpaced: self.unpaced - earlier.unpaced, + presents: self.presents - earlier.presents, + skipped: self.skipped - earlier.skipped, + occluded: self.occluded - earlier.occluded, + timeouts: self.timeouts - earlier.timeouts, + outdated: self.outdated - earlier.outdated, + turns: self.turns - earlier.turns, + wakes: self.wakes - earlier.wakes, + } + } + + /// Per second over `secs`, rounded. + fn per(&self, secs: f64) -> SurfaceCounts { + let r = |n: u64| (n as f64 / secs).round() as u64; + SurfaceCounts { + redraws: r(self.redraws), unpaced: r(self.unpaced), presents: r(self.presents), skipped: r(self.skipped), + occluded: r(self.occluded), timeouts: r(self.timeouts), outdated: r(self.outdated), turns: r(self.turns), wakes: r(self.wakes), + } + } +} + +/// What paces a surface's frames. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +#[non_exhaustive] +pub enum Pacing { + /// Not drawing: idle, hidden or occluded. + #[default] + Idle, + /// A running display link (macOS). + DisplayLink, + /// Moving with no display link running: a frame-interval timer paces it (macOS). + Unpaced, + /// The present queue paces it (platforms without a display link). + Vsync, + /// The display link couldn't be made (every display asleep, say); CoreVideo's status. + Failed(i32), +} + +impl std::fmt::Display for Pacing { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Pacing::Idle => f.write_str("idle"), + Pacing::DisplayLink => f.write_str("display link"), + Pacing::Unpaced => f.write_str("unpaced"), + Pacing::Vsync => f.write_str("vsync"), + Pacing::Failed(status) => write!(f, "display link failed ({status})"), + } + } +} + +/// One surface's frame counts: `WindowHandle::surface_stats`, `OverlayHandle::surface_stats` +/// and `Runtime::surface_stats`. Totals and pacing are current; rates roll over once a second. +#[derive(Clone, Debug, Default, PartialEq)] +#[non_exhaustive] +pub struct SurfaceStats { + /// The window's key, or the overlay's name. + pub name: String, + pub totals: SurfaceCounts, + /// Over the last second the surface was busy; zero once it has rested two seconds. + pub per_second: SurfaceCounts, + pub pacing: Pacing, + published: Option<Instant>, +} + +impl SurfaceStats { + /// Rates older than two seconds describe a surface that has since gone quiet. + fn aged(mut self, now: Instant) -> Self { + if self.published.is_none_or(|at| now.saturating_duration_since(at) > STALE) { self.per_second = SurfaceCounts::default(); } + self + } + + /// One line: `main: 120 presents/s, 0 failed/s (...), pacing: display link`. + pub fn summary(&self) -> String { + let (t, r) = (&self.totals, &self.per_second); + format!( + "{}: {} redraws/s ({} unpaced), {} presents/s, {} failed acquires/s (occluded {}, timeout {}, outdated {}), {} skipped/s, {} loop turns/s ({} wakes); totals {} presents, {} failed, {} skipped; pacing: {}", + self.name, r.redraws, r.unpaced, r.presents, r.failed(), r.occluded, r.timeouts, r.outdated, r.skipped, r.turns, r.wakes, + t.presents, t.failed(), t.skipped, self.pacing, + ) + } +} + +/// A surface with more failed acquisitions or unpaced redraws a second than this is spinning: +/// above any display's refresh rate. +const SPIN_RATE: u64 = 400; +/// Seconds in a row over `SPIN_RATE` before the meter says so. +const SPIN_SECONDS: u32 = 2; +const WINDOW: Duration = Duration::from_secs(1); +const STALE: Duration = Duration::from_secs(2); + +/// Counts one surface's frames, rolls them into per-second rates and publishes them. +pub(crate) struct SurfaceMeter { + totals: SurfaceCounts, + /// `totals` when the current one-second window began. + base: SurfaceCounts, + started: Instant, + pacing: Pacing, + /// A timer or event came since the last redraw. + waited: bool, + spin: Spin, + shared: Arc<Mutex<SurfaceStats>>, +} + +/// Whether the surface is spinning, by whole one-second windows. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Spin { + /// The last window was under `SPIN_RATE`, or none has rolled. + Calm, + /// `seconds` windows in a row over `SPIN_RATE`, fewer than `SPIN_SECONDS`. + Hot { seconds: u32 }, + /// The meter said so; it never says so again. + Warned, +} + +/// A one-second window rolled over, `spinning` when its rates were over `SPIN_RATE`. +#[derive(Clone, Copy, Debug)] +struct Rolled { + spinning: bool, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum SpinEffect { + /// Say the surface has spun for `seconds`. + Warn { seconds: u32 }, +} + +fn step(spin: &mut Spin, event: Rolled) -> Effects<SpinEffect> { + let seconds = match *spin { + Spin::Warned => return Effects::none(), + Spin::Calm => 0, + Spin::Hot { seconds } => seconds, + }; + // A long quiet window averages low, which also ends a hot streak. + let seconds = if event.spinning { seconds + 1 } else { 0 }; + if seconds >= SPIN_SECONDS { + *spin = Spin::Warned; + return Effects::one(SpinEffect::Warn { seconds }); + } + *spin = if seconds == 0 { Spin::Calm } else { Spin::Hot { seconds } }; + Effects::none() +} + +impl SurfaceMeter { + pub(crate) fn new(name: &str, shared: Arc<Mutex<SurfaceStats>>) -> Self { + shared.lock().unwrap().name = name.to_owned(); + Self { + totals: SurfaceCounts::default(), base: SurfaceCounts::default(), started: crate::time::now(), pacing: Pacing::Idle, + waited: false, spin: Spin::Calm, shared, + } + } + + pub(crate) fn shared(&self) -> Arc<Mutex<SurfaceStats>> { self.shared.clone() } + #[cfg_attr(not(any(test, target_os = "macos")), allow(dead_code))] + pub(crate) fn totals(&self) -> SurfaceCounts { self.totals } + + /// A redraw. `paced` when a display tick or vsync paces it; otherwise it's unpaced unless + /// a timer or event (`waited`) came since the last one. + pub(crate) fn redraw(&mut self, paced: bool) { + self.totals.redraws += 1; + if !paced && !self.waited { self.totals.unpaced += 1; } + self.waited = false; + self.tick(crate::time::now()); + } + + /// An event the surface's host handled, which may ask for the next redraw. + pub(crate) fn waited(&mut self) { self.waited = true; } + + pub(crate) fn presented(&mut self) { + self.totals.presents += 1; + self.tick(crate::time::now()); + } + + #[cfg_attr(not(target_os = "macos"), allow(dead_code))] + pub(crate) fn skipped(&mut self) { + self.totals.skipped += 1; + self.tick(crate::time::now()); + } + + pub(crate) fn failed(&mut self, missed: Missed) { + match missed { + Missed::Occluded => self.totals.occluded += 1, + Missed::Timeout => self.totals.timeouts += 1, + Missed::Outdated | Missed::Unconfigured => self.totals.outdated += 1, + } + self.tick(crate::time::now()); + } + + /// An event-loop turn, `woke` by a deadline or poll rather than an event. A deadline that + /// was still ahead when the loop slept (`waited`) paces the redraw it asks for. + pub(crate) fn turn(&mut self, woke: bool, waited: bool) { + self.totals.turns += 1; + if woke { self.totals.wakes += 1; } + self.waited |= waited; + self.tick(crate::time::now()); + } + + pub(crate) fn set_pacing(&mut self, pacing: Pacing) { + self.pacing = pacing; + self.shared.lock().unwrap().pacing = pacing; + } + + /// Publishes the totals, and rolls the rates over once a second has passed; the spin + /// warning, if this roll is it. + fn tick(&mut self, now: Instant) -> Option<String> { + let elapsed = now.saturating_duration_since(self.started); + let (summary, effects) = { + let mut stats = self.shared.lock().unwrap(); + stats.totals = self.totals; + if elapsed < WINDOW { return None; } + stats.per_second = self.totals.since(&self.base).per(elapsed.as_secs_f64()); + stats.published = Some(now); + let rates = stats.per_second; + let effects = step(&mut self.spin, Rolled { spinning: rates.failed() > SPIN_RATE || rates.unpaced > SPIN_RATE }); + (stats.summary(), effects) + }; + self.base = self.totals; + self.started = now; + let mut warned = None; + for effect in effects { + let SpinEffect::Warn { seconds } = effect; + let warning = format!("rune: surface has spun for {seconds} s, a bug in Rune: {summary}"); + eprintln!("{warning}"); + warned = Some(warning); + } + warned + } +} + +/// Whether the loop turned on a deadline that was still ahead when it slept: an overdue one +/// turns it at once, as a poll does. +pub(crate) fn slept(cause: winit::event::StartCause) -> bool { + matches!(cause, winit::event::StartCause::ResumeTimeReached { start, requested_resume } if requested_resume > start) +} + +/// The published stats, with rates zeroed once they are stale. +pub(crate) fn read(shared: &Mutex<SurfaceStats>) -> SurfaceStats { + shared.lock().unwrap().clone().aged(crate::time::now()) +} + +#[cfg(test)] +#[path = "surface_stats_tests.rs"] +mod tests; + +#[cfg(test)] +#[path = "surface_stats_walk_tests.rs"] +mod walk_tests; diff --git a/app/vendor/rune/crates/rune/src/frame/surface_stats_tests.rs b/app/vendor/rune/crates/rune/src/frame/surface_stats_tests.rs new file mode 100644 index 0000000..f27c8bf --- /dev/null +++ b/app/vendor/rune/crates/rune/src/frame/surface_stats_tests.rs @@ -0,0 +1,112 @@ +use super::*; + +fn meter() -> (SurfaceMeter, Instant) { + let meter = SurfaceMeter::new("main", Arc::default()); + let start = meter.started; + (meter, start) +} + +#[test] +fn rates_are_per_second_over_the_last_window_and_go_stale() { + let (mut meter, start) = meter(); + for _ in 0..120 { meter.redraw(true); meter.presented(); } + for _ in 0..3 { meter.failed(Missed::Timeout); } + meter.skipped(); + meter.turn(false, false); + meter.turn(true, false); + meter.set_pacing(Pacing::DisplayLink); + assert_eq!(meter.shared.lock().unwrap().per_second, SurfaceCounts::default(), "rates wait for a whole second"); + assert!(meter.tick(start + Duration::from_millis(1000)).is_none()); + let stats = meter.shared.lock().unwrap().clone(); + assert_eq!(stats.name, "main"); + assert_eq!((stats.per_second.redraws, stats.per_second.unpaced, stats.per_second.presents), (120, 0, 120)); + assert_eq!((stats.per_second.timeouts, stats.per_second.failed(), stats.per_second.skipped), (3, 3, 1)); + assert_eq!((stats.per_second.turns, stats.per_second.wakes), (2, 1)); + assert_eq!(stats.pacing, Pacing::DisplayLink); + assert_eq!(stats.totals.presents, 120); + + // Half the work over the next two seconds: rates are per second, totals keep counting. + for _ in 0..60 { meter.redraw(false); meter.presented(); } + meter.tick(start + Duration::from_millis(3000)); + let stats = meter.shared.lock().unwrap().clone(); + assert_eq!((stats.per_second.redraws, stats.per_second.unpaced, stats.per_second.presents), (30, 30, 30)); + assert_eq!((stats.totals.redraws, stats.totals.presents), (180, 180)); + assert_eq!(meter.totals(), stats.totals); + + let fresh = stats.clone().aged(start + Duration::from_millis(4000)); + assert_eq!(fresh.per_second.presents, 30); + let stale = stats.aged(start + Duration::from_millis(5500)); + assert_eq!(stale.per_second, SurfaceCounts::default(), "a surface quiet for two seconds reports no rate"); + assert_eq!(stale.totals.presents, 180); +} + +#[test] +fn totals_and_pacing_publish_at_once() { + // A window that draws for less than a second, then rests, still reports what it drew. + let (mut meter, _) = meter(); + meter.set_pacing(Pacing::DisplayLink); + assert_eq!(read(&meter.shared).pacing, Pacing::DisplayLink, "pacing set after the frame's counts still lands"); + for _ in 0..3 { meter.redraw(true); meter.presented(); } + meter.set_pacing(Pacing::Idle); + let stats = read(&meter.shared); + assert_eq!((stats.totals.redraws, stats.totals.presents), (3, 3)); + assert_eq!(stats.pacing, Pacing::Idle); + assert_eq!(stats.per_second, SurfaceCounts::default()); + assert!(stats.summary().contains("totals 3 presents"), "{}", stats.summary()); +} + +#[test] +fn only_redraws_that_waited_for_nothing_are_unpaced() { + let (mut meter, _) = meter(); + meter.redraw(true); + assert_eq!(meter.totals().unpaced, 0, "a display tick or vsync paces it"); + meter.waited(); + meter.redraw(false); + assert_eq!(meter.totals().unpaced, 0, "an event asked for it"); + meter.turn(true, true); + meter.redraw(false); + assert_eq!(meter.totals().unpaced, 0, "a timer that was still ahead paced it"); + meter.turn(true, false); + meter.redraw(false); + assert_eq!(meter.totals().unpaced, 1, "an overdue deadline or poll waited for nothing"); + meter.waited(); + meter.redraw(true); + meter.redraw(false); + assert_eq!(meter.totals().unpaced, 2, "each wait paces one redraw"); +} + +#[test] +fn the_guard_warns_once_after_two_seconds_of_spinning() { + let (mut meter, start) = meter(); + let at = |ms| start + Duration::from_millis(ms); + let spin = |meter: &mut SurfaceMeter, n| for _ in 0..n { meter.redraw(true); meter.failed(Missed::Occluded); }; + meter.set_pacing(Pacing::Failed(-6661)); + spin(&mut meter, 5000); + assert!(meter.tick(at(1000)).is_none(), "one hot second isn't a spin"); + spin(&mut meter, 5000); + let warning = meter.tick(at(2000)).expect("two hot seconds are"); + assert!(warning.contains("main") && warning.contains("5000 failed acquires/s") && warning.contains("occluded 5000"), "{warning}"); + assert!(warning.contains("display link failed (-6661)"), "{warning}"); + spin(&mut meter, 5000); + assert!(meter.tick(at(3000)).is_none(), "it warns once"); + + // Unpaced redraws spin too; a calm second in between resets the streak. + let (mut meter, start) = super::tests::meter(); + let at = |ms| start + Duration::from_millis(ms); + let unpaced = |meter: &mut SurfaceMeter, n| for _ in 0..n { meter.redraw(false); meter.presented(); }; + unpaced(&mut meter, 1000); + assert!(meter.tick(at(1000)).is_none()); + unpaced(&mut meter, 60); + assert!(meter.tick(at(2000)).is_none(), "a 60 Hz second resets the streak"); + unpaced(&mut meter, 1000); + assert!(meter.tick(at(3000)).is_none()); + unpaced(&mut meter, 1000); + assert!(meter.tick(at(4000)).is_some_and(|w| w.contains("1000 redraws/s (1000 unpaced)"))); + + // A display's own rate, even 360 Hz, never trips it. + let (mut meter, start) = super::tests::meter(); + for second in 1..=5 { + unpaced(&mut meter, 360); + assert!(meter.tick(start + Duration::from_secs(second)).is_none()); + } +} diff --git a/app/vendor/rune/crates/rune/src/frame/surface_stats_walk_tests.rs b/app/vendor/rune/crates/rune/src/frame/surface_stats_walk_tests.rs new file mode 100644 index 0000000..7e9e6c5 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/frame/surface_stats_walk_tests.rs @@ -0,0 +1,278 @@ +//! Every short sequence of busy, spinning, calm and quiet seconds through a [`SurfaceMeter`]. +//! The real meter and its spin [`step`] run beside `Old`, a transcription of the fields and +//! branches they replaced (`hot`, `warned`), which calls none of them; both must publish the +//! same stats and warn at the same roll with the same words. + +use super::*; + +// The old code. + +#[derive(Clone, Copy, Debug, Default, PartialEq)] +struct OldCounts { + redraws: u64, + unpaced: u64, + presents: u64, + skipped: u64, + occluded: u64, + timeouts: u64, + outdated: u64, + turns: u64, + wakes: u64, +} + +impl OldCounts { + fn failed(&self) -> u64 { self.occluded + self.timeouts + self.outdated } + + fn since(&self, earlier: &OldCounts) -> OldCounts { + OldCounts { + redraws: self.redraws - earlier.redraws, + unpaced: self.unpaced - earlier.unpaced, + presents: self.presents - earlier.presents, + skipped: self.skipped - earlier.skipped, + occluded: self.occluded - earlier.occluded, + timeouts: self.timeouts - earlier.timeouts, + outdated: self.outdated - earlier.outdated, + turns: self.turns - earlier.turns, + wakes: self.wakes - earlier.wakes, + } + } + + fn per(&self, secs: f64) -> OldCounts { + let r = |n: u64| (n as f64 / secs).round() as u64; + OldCounts { + redraws: r(self.redraws), unpaced: r(self.unpaced), presents: r(self.presents), skipped: r(self.skipped), + occluded: r(self.occluded), timeouts: r(self.timeouts), outdated: r(self.outdated), turns: r(self.turns), wakes: r(self.wakes), + } + } +} + +fn old_pacing(pacing: Pacing) -> String { + match pacing { + Pacing::Idle => "idle".into(), + Pacing::DisplayLink => "display link".into(), + Pacing::Unpaced => "unpaced".into(), + Pacing::Vsync => "vsync".into(), + Pacing::Failed(status) => format!("display link failed ({status})"), + } +} + +#[derive(Clone, Debug, Default)] +struct OldStats { + name: String, + totals: OldCounts, + per_second: OldCounts, + pacing: Pacing, + published: Option<Instant>, +} + +impl OldStats { + fn summary(&self) -> String { + let (t, r) = (&self.totals, &self.per_second); + format!( + "{}: {} redraws/s ({} unpaced), {} presents/s, {} failed acquires/s (occluded {}, timeout {}, outdated {}), {} skipped/s, {} loop turns/s ({} wakes); totals {} presents, {} failed, {} skipped; pacing: {}", + self.name, r.redraws, r.unpaced, r.presents, r.failed(), r.occluded, r.timeouts, r.outdated, r.skipped, r.turns, r.wakes, + t.presents, t.failed(), t.skipped, old_pacing(self.pacing), + ) + } +} + +struct Old { + totals: OldCounts, + base: OldCounts, + started: Instant, + pacing: Pacing, + waited: bool, + hot: u32, + warned: bool, + shared: OldStats, +} + +impl Old { + fn new(name: &str, started: Instant) -> Self { + let shared = OldStats { name: name.to_owned(), ..OldStats::default() }; + Old { totals: OldCounts::default(), base: OldCounts::default(), started, pacing: Pacing::Idle, waited: false, hot: 0, warned: false, shared } + } + + fn redraw(&mut self, paced: bool) { + self.totals.redraws += 1; + if !paced && !self.waited { self.totals.unpaced += 1; } + self.waited = false; + self.tick(crate::time::now()); + } + + fn waited(&mut self) { self.waited = true; } + + fn presented(&mut self) { + self.totals.presents += 1; + self.tick(crate::time::now()); + } + + fn skipped(&mut self) { + self.totals.skipped += 1; + self.tick(crate::time::now()); + } + + fn failed(&mut self, missed: Missed) { + match missed { + Missed::Occluded => self.totals.occluded += 1, + Missed::Timeout => self.totals.timeouts += 1, + Missed::Outdated | Missed::Unconfigured => self.totals.outdated += 1, + } + self.tick(crate::time::now()); + } + + fn turn(&mut self, woke: bool, waited: bool) { + self.totals.turns += 1; + if woke { self.totals.wakes += 1; } + self.waited |= waited; + self.tick(crate::time::now()); + } + + fn set_pacing(&mut self, pacing: Pacing) { + self.pacing = pacing; + self.shared.pacing = pacing; + } + + fn tick(&mut self, now: Instant) -> Option<String> { + let elapsed = now.saturating_duration_since(self.started); + let summary = { + let stats = &mut self.shared; + stats.totals = self.totals; + if elapsed < WINDOW { return None; } + stats.per_second = self.totals.since(&self.base).per(elapsed.as_secs_f64()); + stats.published = Some(now); + let rates = stats.per_second; + self.hot = if rates.failed() > SPIN_RATE || rates.unpaced > SPIN_RATE { self.hot + 1 } else { 0 }; + stats.summary() + }; + self.base = self.totals; + self.started = now; + if self.hot < SPIN_SECONDS || std::mem::replace(&mut self.warned, true) { return None; } + let warning = format!("rune: surface has spun for {} s, a bug in Rune: {summary}", self.hot); + Some(warning) + } +} + +// The walk. + +#[derive(Clone, Copy, Debug)] +enum Ev { + /// Over `SPIN_RATE` failed acquisitions, then a one-second roll. + Failing, + /// Over `SPIN_RATE` unpaced redraws, then a one-second roll. + Unpaced, + /// A 60 Hz second, then a one-second roll. + Calm, + /// Redraws after an event, a timer still ahead and a poll; no roll. + Waits, + /// A tick half a second after the last roll: too soon to roll. + Early, + /// Three seconds with nothing, then a roll. + Quiet, + /// The display link failed. + Pace, +} + +const ALPHABET: [Ev; 7] = [Ev::Failing, Ev::Unpaced, Ev::Calm, Ev::Waits, Ev::Early, Ev::Quiet, Ev::Pace]; + +fn counts(c: &SurfaceCounts) -> [u64; 9] { + [c.redraws, c.unpaced, c.presents, c.skipped, c.occluded, c.timeouts, c.outdated, c.turns, c.wakes] +} + +fn old_counts(c: &OldCounts) -> [u64; 9] { + [c.redraws, c.unpaced, c.presents, c.skipped, c.occluded, c.timeouts, c.outdated, c.turns, c.wakes] +} + +fn walk(events: &[Ev]) { + // Rolls happen only at the walk's times: every count's own tick lands before `start`. + let start = crate::time::now() + Duration::from_secs(3600); + let mut new = SurfaceMeter::new("main", Arc::default()); + new.started = start; + let mut old = Old::new("main", start); + let mut at = start; + for (k, &ev) in events.iter().enumerate() { + let (n, o) = (&mut new, &mut old); + let tick = match ev { + Ev::Failing => { + for _ in 0..=SPIN_RATE { n.failed(Missed::Occluded); o.failed(Missed::Occluded); } + n.failed(Missed::Timeout); o.failed(Missed::Timeout); + n.failed(Missed::Outdated); o.failed(Missed::Outdated); + Some(Duration::from_secs(1)) + } + Ev::Unpaced => { + for _ in 0..=SPIN_RATE { n.redraw(false); o.redraw(false); } + Some(Duration::from_secs(1)) + } + Ev::Calm => { + for _ in 0..60 { n.redraw(true); o.redraw(true); n.presented(); o.presented(); } + n.skipped(); o.skipped(); + n.turn(true, false); o.turn(true, false); + Some(Duration::from_secs(1)) + } + Ev::Waits => { + n.waited(); o.waited(); + n.redraw(false); o.redraw(false); + n.turn(true, true); o.turn(true, true); + n.redraw(false); o.redraw(false); + n.turn(false, false); o.turn(false, false); + n.redraw(false); o.redraw(false); + n.waited(); o.waited(); + None + } + Ev::Early => { + let early = at + Duration::from_millis(500); + assert_eq!(n.tick(early), o.tick(early), "early tick after {:?}", &events[..=k]); + None + } + Ev::Quiet => Some(Duration::from_secs(3)), + Ev::Pace => { + n.set_pacing(Pacing::Failed(-6661)); o.set_pacing(Pacing::Failed(-6661)); + None + } + }; + if let Some(dt) = tick { + at += dt; + assert_eq!(new.tick(at), old.tick(at), "roll after {:?}", &events[..=k]); + } + let stats = new.shared.lock().unwrap().clone(); + let o = &old.shared; + assert_eq!( + (stats.name.as_str(), counts(&stats.totals), counts(&stats.per_second), stats.pacing, stats.published), + (o.name.as_str(), old_counts(&o.totals), old_counts(&o.per_second), o.pacing, o.published), + "stats after {:?}", &events[..=k], + ); + assert_eq!(counts(&new.totals()), old_counts(&old.totals), "totals after {:?}", &events[..=k]); + } +} + +#[test] +fn every_sequence_of_seconds_publishes_and_warns_as_the_old_meter_did() { + const LEN: u32 = 5; + let mut seq = Vec::with_capacity(LEN as usize); + for len in 1..=LEN { + for n in 0..ALPHABET.len().pow(len) { + seq.clear(); + let mut n = n; + for _ in 0..len { + seq.push(ALPHABET[n % ALPHABET.len()]); + n /= ALPHABET.len(); + } + walk(&seq); + } + } +} + +#[test] +fn spinning_warns_once_on_the_second_hot_second_in_a_row() { + let mut spin = Spin::Calm; + let roll = |spin: &mut Spin, spinning| step(spin, Rolled { spinning }); + assert!(roll(&mut spin, true).is_empty()); + assert_eq!(spin, Spin::Hot { seconds: 1 }); + assert!(roll(&mut spin, false).is_empty()); + assert_eq!(spin, Spin::Calm, "a calm second ends the streak"); + roll(&mut spin, true); + assert_eq!(roll(&mut spin, true), Effects::one(SpinEffect::Warn { seconds: 2 })); + assert_eq!(spin, Spin::Warned); + assert!(roll(&mut spin, true).is_empty() && roll(&mut spin, false).is_empty() && roll(&mut spin, true).is_empty()); + assert_eq!(spin, Spin::Warned); +} diff --git a/app/vendor/rune/crates/rune/src/hot.rs b/app/vendor/rune/crates/rune/src/hot.rs new file mode 100644 index 0000000..0448c21 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/hot.rs @@ -0,0 +1,427 @@ +//! Desktop development only. Use `scripts/rune-dev`: it validates edits before dx sees them. +//! Long-lived state belongs to Runtime, never to tip-crate statics or cached view trait objects. + +use std::path::Path; +use std::panic::{AssertUnwindSafe, catch_unwind}; +use std::sync::{Arc, Mutex, OnceLock, atomic::{AtomicBool, AtomicU64, Ordering}}; +use std::time::{Duration, UNIX_EPOCH}; + +use serde_json::{Value, json}; + +use crate::render::{Gpu, OFFSCREEN_FORMAT, Offscreen, Renderer}; +use crate::runtime::{AppDriver, Env, RuntimeCore, Waker}; +use crate::tooling::{AppSpec, Args, initial_state, runtime_for, tree_json_core}; +use crate::{Cx, El, KeyEvent, Tx}; +use std::any::Any; + +// The hot tip crate owns only these thin typed adapters. Runtime<HostState>, layout, +// shell and headless loop are instantiated in the stable rune library, not recompiled per app edit. +// Any's vtable supplies type_id/drop only; no patchable behavior is cached in it. +pub(crate) struct HostState { + pub(crate) value: Box<dyn Any>, + spec: Box<dyn Any>, + view: fn(&HostState, &mut Cx<HostState>) -> El, + poll: fn(&mut HostState, f64, &mut Tx) -> bool, + setup: fn(&mut HostState, Waker), + key: fn(&mut HostState, &KeyEvent, &mut Tx) -> bool, +} + +thread_local! { + static INITIAL: std::cell::RefCell<Option<HostState>> = const { std::cell::RefCell::new(None) }; + static ORIGINAL_ONLY: std::cell::Cell<bool> = const { std::cell::Cell::new(false) }; +} + +/// Runs `f` with views built by their startup code, skipping the patch table: the fallback +/// after a patched view, or a row it built, panicked. +pub(crate) fn original_only<R>(f: impl FnOnce() -> R) -> R { + struct Reset(bool); + impl Drop for Reset { + fn drop(&mut self) { ORIGINAL_ONLY.set(self.0); } + } + let _reset = Reset(ORIGINAL_ONLY.replace(true)); + f() +} + +/// Whether views run as built at startup, inside [`original_only`]. +pub(crate) fn originals_only() -> bool { + ORIGINAL_ONLY.get() +} + +fn view_adapter<S: 'static>(host: &HostState, cx: &mut Cx<HostState>) -> El { + let spec = host.spec.downcast_ref::<AppSpec<S>>().unwrap(); + let state = host.value.downcast_ref::<S>().unwrap(); + view_or_original(spec.view, state, cx, |state, typed| subsecond::HotFn::current(spec.view).call((state, typed))) +} + +fn view_or_original<S>(original: fn(&S, &mut Cx<S>) -> El, state: &S, cx: &mut Cx<HostState>, patched: impl FnOnce(&S, &mut Cx<S>) -> El) -> El { + let mut typed = cx.retype(); + if ORIGINAL_ONLY.get() { + let tree = original(state, &mut typed); + cx.settings_from(typed); + return tree; + } + let tree = match catch_unwind(AssertUnwindSafe(|| patched(state, &mut typed))) { + Ok(tree) => tree, + Err(_) => { + eprintln!("rune-hot: view panicked; rendering the original view"); + // Discard context writes from the failed view and bypass the patch table. + typed = cx.retype(); + original(state, &mut typed) + } + }; + cx.settings_from(typed); + tree +} + +/// Calls `f` through the patch table; if the patched code panics, calls the startup `f` once +/// instead, as a panicking view renders the original. Side effects of the panicked call stay. +macro_rules! patched_or_original { + ($what:literal, $f:expr, $($arg:expr),* $(,)?) => {{ + let f = $f; + match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| subsecond::HotFn::current(f).call(($($arg,)*)))) { + Ok(value) => value, + Err(_) => { + eprintln!(concat!("rune-hot: patched ", $what, " panicked; calling the original")); + f($($arg),*) + } + } + }}; +} +pub(crate) use patched_or_original; + +fn poll_adapter<S: 'static>(host: &mut HostState, t: f64, tx: &mut Tx) -> bool { + let spec = host.spec.downcast_ref::<AppSpec<S>>().unwrap(); + let Some(f) = spec.poll else { return false }; + patched_or_original!("poll", f, host.value.downcast_mut::<S>().unwrap(), t, &mut *tx) +} + +fn setup_adapter<S: 'static>(host: &mut HostState, waker: Waker) { + let spec = host.spec.downcast_ref::<AppSpec<S>>().unwrap(); + if let Some(f) = spec.setup { f(host.value.downcast_mut::<S>().unwrap(), waker); } +} + +fn key_adapter<S: 'static>(host: &mut HostState, key: &KeyEvent, tx: &mut Tx) -> bool { + let spec = host.spec.downcast_ref::<AppSpec<S>>().unwrap(); + let Some(f) = spec.on_key else { return false }; + patched_or_original!("on_key", f, host.value.downcast_mut::<S>().unwrap(), key, &mut *tx) +} + +pub(crate) fn run<S: 'static>(spec: AppSpec<S>, args: Args) { + run_app(crate::App::new(spec), args); +} + +pub(crate) fn run_app<S: 'static>(app: crate::App<S>, mut args: Args) { + if args.list_scenes { + for (name, _) in app.spec.scenes { println!("{name}"); } + return; + } + let frame = (app.chrome, app.titlebar); + let scene = args.scene.take(); + let (spec, state, _, runtime) = app.into_parts(scene.as_deref()); + let value = Box::new(state); + let shell = AppSpec { + title: spec.title, size: spec.size, min_size: spec.min_size, fonts: spec.fonts, families: spec.families, + scenes: &[], init: || INITIAL.with(|s| s.borrow_mut().take().expect("hot initial state")), + view: |s: &HostState, cx| (s.view)(s, cx), + poll: Some(|s: &mut HostState, t, tx| (s.poll)(s, t, tx)), + setup: Some(|s: &mut HostState, wake| (s.setup)(s, wake)), + on_key: Some(|s: &mut HostState, key, tx| (s.key)(s, key, tx)), + }; + let state = HostState { value, spec: Box::new(spec), view: view_adapter::<S>, poll: poll_adapter::<S>, setup: setup_adapter::<S>, key: key_adapter::<S> }; + run_host(shell, state, args, runtime.retype_settings(), frame); +} + +#[inline(never)] +fn run_host(spec: AppSpec<HostState>, state: HostState, args: Args, runtime: crate::app::RuntimeConfig<HostState>, frame: (crate::Chrome, Option<crate::Titlebar>)) { + INITIAL.with(|slot| { assert!(slot.borrow().is_none()); *slot.borrow_mut() = Some(state); }); + if args.snap_on_patch.is_some() { + let state = initial_state(&spec, args.scene.as_deref()); + return headless(&spec, state, args, runtime); + } + let mut app = crate::App::new(spec); + app.runtime = runtime; + // The window's frame is the app's, as without hot reload. + (app.chrome, app.titlebar) = frame; + if args.headless() { crate::tooling::headless(app, args); } + else if let Err(error) = crate::window::run(app, args) { panic!("{error}"); } +} + +/// `--snap-on-patch` for a window from `run_windows*`, `WindowSpec::from_app` or `App::window`: +/// the same typed `Runtime<S>` a native window builds, so its view, poll and on_key patch the +/// way they do on screen. +pub(crate) fn snap_window<S: 'static>(app: crate::App<S>, args: Args) { + let (spec, state, _, runtime) = app.into_parts(args.scene.as_deref()); + headless(&spec, state, args, runtime); +} + +static ENABLED: AtomicBool = AtomicBool::new(false); + +pub(crate) fn enable() { + assert!(std::env::var_os("RUNE_DEV_GUARDED").is_some(), "use scripts/rune-dev: unguarded Rust patches can change live state layouts"); + if let Some(path) = std::env::var_os("RUNE_HOT_PARK") { + // Desk mode: another Mac runs this binary. The build Mac's copy only reports where dx + // built it, and exits before it can connect and take the patches meant for the desk. + let exe = std::env::current_exe().expect("rune-hot: current exe"); + atomic_write(Path::new(&path), exe.as_os_str().as_encoded_bytes()); + eprintln!("rune-hot: parked {}; the desk Mac runs it", exe.display()); + std::process::exit(0); + } + ENABLED.store(true, Ordering::Release); +} + +/// `RUNE_HOT=1` enables live editing like `--hot`, for apps that keep their argv from Rune. +pub(crate) fn enable_from_env() { + static ONCE: std::sync::Once = std::sync::Once::new(); + ONCE.call_once(|| if std::env::var_os("RUNE_HOT").is_some_and(|v| v == "1") { enable() }); +} + +pub fn enabled() -> bool { + enable_from_env(); + ENABLED.load(Ordering::Acquire) +} + +/// One devserver connection per process: dx patches for the last pid and ASLR base that +/// connected, and every connection would apply each patch again. Windows share it. +#[derive(Default)] +pub(crate) struct Hub { + generation: AtomicU64, + next: AtomicU64, + wakers: Mutex<Vec<(u64, Waker)>>, +} + +impl Hub { + pub(crate) fn patched(&self) { + self.generation.fetch_add(1, Ordering::Release); + let wakers: Vec<Waker> = self.wakers.lock().unwrap().iter().map(|(_, w)| w.clone()).collect(); + for wake in wakers { wake(); } + } +} + +fn hub() -> &'static Hub { + static HUB: OnceLock<Hub> = OnceLock::new(); + let mut fresh = false; + let hub = HUB.get_or_init(|| { fresh = true; Hub::default() }); + if fresh { + subsecond::register_handler(Arc::new(|| hub.patched())); + connect(); + } + hub +} + +#[allow(unsafe_code)] +fn connect() { + // dioxus-devtools reads the same variables and connects silently, or not at all. + let var = rune_core::env::var; + let Some(addr) = var("DIOXUS_DEVSERVER_IP").zip(var("DIOXUS_DEVSERVER_PORT")) + .and_then(|(ip, port)| Some(std::net::SocketAddr::new(ip.parse().ok()?, port.parse().ok()?))) + else { + eprintln!("rune-hot: DIOXUS_DEVSERVER_IP/PORT are unset; edits will not patch (use scripts/rune-dev)"); + return; + }; + if let Err(error) = std::net::TcpStream::connect_timeout(&addr, Duration::from_secs(3)) { + eprintln!("rune-hot: no devserver at {addr} ({error}); edits will not patch"); + return; + } + let pid = std::process::id(); + dioxus_devtools::connect(move |msg| { + if let dioxus_devtools::DevserverMsg::HotReload(msg) = msg + && let Some(table) = msg.jump_table + && msg.for_pid == Some(pid) + { + let lib = table.lib.clone(); + // SAFETY: rune-dev's guard admits only edits that keep every type, static and + // signature; the patch was linked against this binary's ASLR reference. + if let Err(error) = unsafe { subsecond::apply_patch(table) } { + eprintln!("rune-hot: patch {} did not load: {error}", lib.display()); + } + } + }); +} + +pub(crate) struct Session { + hub: &'static Hub, + id: u64, + seen: u64, +} + +impl Session { + pub(crate) fn connect(wake: Waker) -> Self { Self::join(hub(), wake) } + + fn join(hub: &'static Hub, wake: Waker) -> Self { + let id = hub.next.fetch_add(1, Ordering::Relaxed); + hub.wakers.lock().unwrap().push((id, wake)); + Self { hub, id, seen: hub.generation.load(Ordering::Acquire) } + } + + pub(crate) fn changed(&mut self) -> bool { + let next = self.hub.generation.load(Ordering::Acquire); + let changed = next != self.seen; + self.seen = next; + changed + } + + pub(crate) fn pending(&self) -> bool { self.hub.generation.load(Ordering::Acquire) != self.seen } + + /// Moves this session, waker and all, to a test's own hub, so a test patch reaches only it. + #[cfg(test)] + pub(crate) fn move_to(&mut self, hub: &'static Hub) { + let wake = { + let mut wakers = self.hub.wakers.lock().unwrap(); + let at = wakers.iter().position(|(id, _)| *id == self.id).unwrap(); + wakers.remove(at).1 + }; + *self = Self::join(hub, wake); + } +} + +#[cfg(test)] +pub(crate) fn enable_for_tests() { ENABLED.store(true, Ordering::Release); } + +impl Drop for Session { + fn drop(&mut self) { self.hub.wakers.lock().unwrap().retain(|(id, _)| *id != self.id); } +} + +fn atomic_write(path: &Path, bytes: &[u8]) { + if let Some(parent) = path.parent() { std::fs::create_dir_all(parent).unwrap(); } + let temp = path.with_extension("tmp"); + std::fs::write(&temp, bytes).unwrap(); + std::fs::rename(temp, path).unwrap(); +} + +#[cfg(test)] +#[inline] +fn control_input<S: 'static>(rt: &mut crate::Runtime<S>, command: &Value) { + let (core, mut app) = rt.split_mut(); + control_input_core(core, &mut app, command); +} + +fn control_input_core(core: &mut RuntimeCore, app: &mut dyn AppDriver, command: &Value) { + if let Some(tap) = command.get("tap") { + if let Some((x, y)) = tap.as_str().and_then(|key| core.find(key)) { + core.pointer_move(app, x, y); + core.pointer_down(app, x, y); + core.pointer_up(app, x, y); + } else { + eprintln!("rune-hot: skipping tap: expected an existing element key"); + } + } + if let Some(scroll) = command.get("scroll") { + match serde_json::from_value::<[f32; 3]>(scroll.clone()) { + Ok([x, y, dy]) if [x, y, dy].iter().all(|v| v.is_finite()) => core.wheel(x, y, dy), + _ => eprintln!("rune-hot: skipping scroll: expected three finite numbers [x,y,dy]"), + } + } +} + +/// Persistent offscreen GPU session. A control file is an atomically replaced JSON request: +/// `{"id":1,"tap":"login"}`, `{"id":2,"scroll":[800,400,100]}`, +/// `{"id":3,"pause":true}`, `{"id":4,"step":0.05}`, or `{"id":5,"quit":true}`. +/// Every request and patch publishes a PNG + JSON tree, then a flushed completion marker. +#[inline] +fn headless<S: 'static>(spec: &AppSpec<S>, state: S, args: Args, runtime: crate::app::RuntimeConfig<S>) { + assert!(enabled(), "--snap-on-patch requires --hot or RUNE_HOT=1 (use scripts/rune-dev)"); + let size = args.size.unwrap_or(spec.size); + let scale = args.scale.unwrap_or(2.0); + let (wake, sleep) = std::sync::mpsc::channel(); + let mut rt = runtime_for(spec, state, size, Env { system_dark: args.theme.as_deref() != Some("light"), scale }, Arc::new(move || { wake.send(()).ok(); })); + rt.configure(runtime); + let state_addr = format!("{:p}", crate::runtime::handler_state_ref(&rt.state) as *const dyn Any as *const ()); + let (core, mut app) = rt.split_mut(); + headless_core(core, &mut app, state_addr, size, scale, args, sleep); +} + +fn headless_core( + core: &mut RuntimeCore, + app: &mut dyn AppDriver, + state_addr: String, + size: (f32, f32), + scale: f32, + args: Args, + sleep: std::sync::mpsc::Receiver<()>, +) { + if let Some(bars) = args.scroll_bars { core.set_system_scroll_bars(bars); } + let gpu = Gpu::new(Gpu::instance(), None); + let srgb_blend = core.srgb_blend(); + let target_format = if srgb_blend { OFFSCREEN_FORMAT.remove_srgb_suffix() } else { OFFSCREEN_FORMAT }; + let mut renderer = Renderer::new(&gpu.device, target_format); + renderer.set_srgb_blend(srgb_blend); + let (w, h) = ((size.0 * scale).round() as u32, (size.1 * scale).round() as u32); + let mut target = Offscreen::with_format(&gpu.device, w, h, target_format); + let png = args.snap_on_patch.as_ref().unwrap(); + let mut first = true; + let mut paused = false; + let mut command = Value::Null; + let mut previous = crate::time::now(); + let mut woken = true; + loop { + let now = crate::time::now(); + let elapsed = (now - previous).as_secs_f64(); + // `None`: a frame `elapsed` after the last, under the shared frame rule. + let mut fixed = (first || paused).then_some(0.0); + previous = now; + let mut requested = false; + if !first && let Some(path) = &args.hot_control + && let Ok(bytes) = std::fs::read(path) + && let Ok(next) = serde_json::from_slice::<Value>(&bytes) + && next != command + { + command = next; + if command["quit"] == true { break; } + if let Some(pause) = command["pause"].as_bool() { paused = pause; fixed = Some(0.0); } + if let Some(step) = command["step"].as_f64() { fixed = Some(step.clamp(0.0, 10.0)); } + control_input_core(core, app, &command); + requested = true; + } + let timer_due = core.wake_deadline().is_some_and(|deadline| deadline <= core.clock + elapsed); + if !first && !requested && !core.frame.hot().unwrap().pending() && (paused || (!woken && !core.animating && !timer_due)) { + // Paused/idle sessions must not compete with their own patch compiler. + if !paused { core.clock += elapsed; } + woken = sleep.recv_timeout(Duration::from_millis(16)).is_ok(); + continue; + } + let before = core.frame.hot().unwrap().seen; + match fixed { + Some(dt) => { core.frame(app, dt); } + None => { crate::frame::clock::advance_by_core(core, app, elapsed); } + } + let generation = core.frame.hot().unwrap().seen; + if first || requested || before != generation { + if renderer.srgb_blend() != core.srgb_blend() { + let format = if core.srgb_blend() { OFFSCREEN_FORMAT.remove_srgb_suffix() } else { OFFSCREEN_FORMAT }; + crate::window::rebuild_renderer_core(&gpu.device, &mut renderer, format, core); + target = Offscreen::with_format(&gpu.device, w, h, format); + } + renderer.upload_images(&gpu.device, &gpu.queue, &mut core.images); + renderer.prepare_surfaces(&gpu.device, &gpu.queue, &core.surfaces, (w, h)); + renderer.set_fade_stops(core.fade_stops()); + renderer.prepare_ui(&gpu.device, &gpu.queue, &mut core.text.atlas, &core.instances, (w, h)); + let mut enc = gpu.device.create_command_encoder(&Default::default()); + renderer.draw(&mut enc, &target.view, core.clear_color()); + target.copy(&mut enc); + gpu.queue.submit([enc.finish()]); + let pixels = target.read(&gpu.device); + let pixels_ns = crate::time::system_now().duration_since(UNIX_EPOCH).unwrap().as_nanos(); + let temp = png.with_extension("tmp.png"); + if let Some(parent) = temp.parent() { std::fs::create_dir_all(parent).unwrap(); } + let mut encoder = png::Encoder::new(std::io::BufWriter::new(std::fs::File::create(&temp).unwrap()), w, h); + encoder.set_color(png::ColorType::Rgba); + encoder.set_depth(png::BitDepth::Eight); + encoder.set_compression(png::Compression::Fastest); + encoder.write_header().unwrap().write_image_data(&pixels).expect("hot snapshot"); + std::fs::rename(temp, png).expect("publish hot snapshot"); + let mut tree = tree_json_core(core, core.clock); + tree["hot"] = json!({"generation": generation, "pid": std::process::id(), "state": state_addr, "request": command["id"], "pixels_ns": pixels_ns, "scrolls": core.hot_scrolls(), "motion": core.tree.hot_motion(&core.scene)}); + atomic_write(&png.with_extension("json"), &serde_json::to_vec_pretty(&tree).unwrap()); + println!("rune-hot-pixels {}", tree["hot"]); + use std::io::Write; + std::io::stdout().flush().unwrap(); + first = false; + } + // The patch callback wakes immediately; control files are checked at a bounded cadence. + woken = sleep.recv_timeout(Duration::from_millis(16)).is_ok(); + } +} + +#[cfg(test)] +#[path = "hot_tests.rs"] +mod tests; diff --git a/app/vendor/rune/crates/rune/src/hot_tests.rs b/app/vendor/rune/crates/rune/src/hot_tests.rs new file mode 100644 index 0000000..58efb84 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/hot_tests.rs @@ -0,0 +1,329 @@ +use super::*; +use crate::{Key, TextEdit, col, el, text_input}; + +struct State { pressed: bool, hovered: bool, secondary: bool, changed: bool, keyed: bool, edit: TextEdit } + +fn runtime<S: Default + 'static>(view: fn(&S, &mut Cx<S>) -> El) -> crate::Runtime<HostState> { + let spec = AppSpec::new("test", (300.0, 200.0), S::default, view); + let host = HostState { value: Box::new((spec.init)()), spec: Box::new(spec), view: view_adapter::<S>, poll: poll_adapter::<S>, setup: setup_adapter::<S>, key: key_adapter::<S> }; + crate::Runtime::new(host, |s, cx| (s.view)(s, cx), (300.0, 200.0), Env::new(true, 1.0)) +} + +#[test] +fn one_patch_reaches_every_window_once_and_closed_windows_leave() { + let hub: &'static Hub = Box::leak(Box::default()); + let woken = Arc::new(AtomicU64::new(0)); + let waker = |n: u64| -> Waker { let woken = woken.clone(); Arc::new(move || { woken.fetch_add(n, Ordering::Relaxed); }) }; + let mut main = Session::join(hub, waker(1)); + let mut settings = Session::join(hub, waker(10)); + assert!(!main.changed() && !settings.changed()); + hub.patched(); + assert_eq!(woken.load(Ordering::Relaxed), 11); + assert!(main.pending() && main.changed() && !main.changed()); + assert!(settings.changed()); + drop(settings); + hub.patched(); + assert_eq!(woken.load(Ordering::Relaxed), 12, "a closed window's waker is not called"); + // A window opened after a patch starts from the patched code; it has nothing to recommit. + let late = Session::join(hub, waker(100)); + assert!(!late.pending()); + assert!(main.changed()); +} + +thread_local! { + static CALLS: std::cell::Cell<u32> = const { std::cell::Cell::new(0) }; +} + +/// The first call stands in for a panicking patch: with no patch loaded, the patch table +/// and the startup pointer are the same function. +fn panics_once() { + CALLS.set(CALLS.get() + 1); + if CALLS.get() == 1 { panic!("broken patched body"); } +} + +#[test] +fn a_typed_window_survives_a_panicking_view_and_its_memos_rebuild() { + CALLS.set(0); + fn view(s: &u32, cx: &mut Cx<u32>) -> El { + cx.time_scale(0.25); + col().child(crate::memo("card", *s, || { + panics_once(); + el().key("card").size(40.0, 40.0).on_press(|s: &mut u32| *s += 1) + })) + } + let mut rt = crate::Runtime::new(5u32, view, (200.0, 100.0), Env::new(true, 1.0)); + rt.frame(0.0); + assert_eq!(CALLS.get(), 2, "the startup view runs once after the patched one panics"); + assert!(rt.find("card").is_some()); + assert_eq!(rt.time_scale, 0.25, "context writes come from the view that built the tree"); + let (x, y) = rt.find("card").unwrap(); + rt.pointer_down(x, y); + rt.pointer_up(x, y); + rt.frame(0.0); + assert_eq!(rt.state, 6); + assert_eq!(CALLS.get(), 3, "the memo cache works again: a new version builds once"); + rt.update(|_, _| {}); + rt.frame(0.0); + assert_eq!(CALLS.get(), 3, "and an unchanged version is reused"); +} + +/// Index-built rows run the app's closures after the view returns; a patched one that +/// panics falls back like the view, and what the fallback memoized outlives its commit. +#[test] +fn a_panicking_index_built_row_falls_back_and_keeps_its_memos() { + CALLS.set(0); + fn view(s: &(u32, bool), _: &mut Cx<(u32, bool)>) -> El { + col().key("scroll").size(200.0, 200.0).scroll(crate::ScrollSpec { stick_bottom: false }).child( + col().key("rows").w_full().growth(crate::GrowthSpec::default()).virtual_rows(s.0 as usize, 40.0, + |_: &(u32, bool), i| format!("r{i}").into(), + |s: &(u32, bool), i| crate::memo(format!("r{i}"), s.1, || { + if s.1 && i == 0 { panics_once(); } + el().w_full().h(40.0) + }))) + } + let mut rt = crate::Runtime::new((20u32, false), view, (200.0, 200.0), Env::new(true, 1.0)); + rt.frame(0.0); + for _ in 0..3 { + rt.update(|_, _| {}); + rt.frame(0.0); + } + rt.update(|s, _| s.1 = true); + rt.frame(0.0); + assert_eq!(CALLS.get(), 2, "the startup view builds the row once after the patched one panics"); + assert!(rt.find("r0").is_some()); + rt.update(|_, _| {}); + rt.frame(0.0); + assert_eq!(CALLS.get(), 2, "the fallback's memo is reused"); +} + +#[test] +fn panicking_poll_and_on_key_patches_fall_back_to_the_startup_callbacks() { + CALLS.set(0); + let mut rt = crate::Runtime::new(0u32, |_: &u32, _: &mut Cx<u32>| el().size(10.0, 10.0), (100.0, 100.0), Env::new(true, 1.0)); + rt.on_key = Some(|s, _, _| { panics_once(); *s += 1; true }); + rt.frame(0.0); + rt.key(KeyEvent { key: Key::Function(5), mods: Default::default() }); + rt.frame(0.0); + assert_eq!((rt.state, CALLS.get()), (1, 2)); + CALLS.set(0); + rt.poll = Some(|s, _, _| { panics_once(); *s += 10; true }); + rt.frame(0.0); + assert_eq!((rt.state, CALLS.get()), (11, 2)); + // Through the type-erased host as well: its adapters dispatch through the table too. + CALLS.set(0); + fn view(_: &usize, _: &mut Cx<usize>) -> El { el().size(10.0, 10.0) } + let mut host = runtime::<usize>(view); + let spec = host.state.spec.downcast_mut::<AppSpec<usize>>().unwrap(); + spec.on_key = Some(|s, _, _| { panics_once(); *s += 1; true }); + host.on_key = Some(|s: &mut HostState, key, tx| (s.key)(s, key, tx)); + host.frame(0.0); + host.key(KeyEvent { key: Key::Function(5), mods: Default::default() }); + host.frame(0.0); + assert_eq!((*host.state.value.downcast_ref::<usize>().unwrap(), CALLS.get()), (1, 2)); +} + +#[test] +fn app_try_run_snaps_the_selected_secondary_window_at_its_own_size() { + ENABLED.store(true, Ordering::Release); + let dir = std::env::temp_dir().join(format!("rune-hot-snap-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let (png, control) = (dir.join("settings.png"), dir.join("control.json")); + // Read after the first snapshot, so the loop ends once it is published. + std::fs::write(&control, r#"{"quit":true}"#).unwrap(); + let mut app = crate::App::new(AppSpec::new("main", (120.0, 90.0), || 0u8, |_, _| el().key("main-root").size(10.0, 10.0))); + app.window(crate::WindowSpec::from_app("settings", + crate::App::new(AppSpec::new("settings", (60.0, 40.0), || 0u16, |_, _| el().key("settings-root").size(10.0, 10.0))))); + let args = ["--snap-on-patch", png.to_str().unwrap(), "--hot-control", control.to_str().unwrap(), "--window", "settings", "--scale", "1"]; + app.args(args.map(String::from)).try_run().unwrap(); + let tree: Value = serde_json::from_slice(&std::fs::read(png.with_extension("json")).unwrap()).unwrap(); + let png_size = png::Decoder::new(std::io::BufReader::new(std::fs::File::open(&png).unwrap())).read_info().unwrap().info().size(); + std::fs::remove_dir_all(&dir).unwrap(); + let keys: Vec<&str> = tree["elements"].as_array().unwrap().iter().filter_map(|e| e["key"].as_str()).collect(); + assert_eq!(keys, ["settings-root"], "--window picks App::window's window, not main"); + assert_eq!(png_size, (60, 40)); +} + +#[test] +fn a_pending_patch_keeps_a_window_stale_until_a_frame_rebuilds_it() { + let hub: &'static Hub = Box::leak(Box::default()); + let mut rt = crate::Runtime::new(0u8, |_: &u8, _: &mut Cx<u8>| el().size(10.0, 10.0), (100.0, 100.0), Env::new(true, 1.0)); + rt.frame.set_hot(Session::join(hub, Arc::new(|| {}))); + rt.frame(0.0); + assert!(!rt.needs_commit() && !rt.stale()); + hub.patched(); + // A hidden launcher reveals its cached frame unless this says it is out of date, and + // refreshes that frame when its hidden poll (the patch's wake) reports it, poll or not. + assert!(rt.needs_commit() && rt.stale()); + assert!(rt.poll_hidden()); + rt.poll = Some(|_, _, _| false); + assert!(rt.poll_hidden()); + rt.frame(0.0); + assert!(!rt.needs_commit() && !rt.stale() && !rt.poll_hidden()); +} + +#[test] +fn snap_on_patch_is_a_headless_window_tool() { + let args = Args::parse_from(vec!["--snap-on-patch".into(), "out.png".into(), "--window".into(), "settings".into()]); + assert!(args.headless(), "run_windows must render the selected window headless, not open one"); +} + +#[test] +fn panicking_patch_falls_back_without_losing_state_or_context() { + fn original(s: &usize, _: &mut Cx<usize>) -> El { + el().key(format!("count-{s}")).on_press(|s: &mut usize| *s += 1) + } + let mut rt = runtime(original); + *rt.state.value.downcast_mut::<usize>().unwrap() = 7; + let address = rt.state.value.as_ref() as *const dyn Any as *const (); + rt.state.view = |host, cx| { + let state = host.value.downcast_ref::<usize>().unwrap(); + let original = host.spec.downcast_ref::<AppSpec<usize>>().unwrap().view; + view_or_original(original, state, cx, |_, typed| { + typed.time_scale(0.125); + panic!("broken patched view") + }) + }; + rt.frame(0.0); + assert!(rt.find("count-7").is_some()); + assert_eq!(rt.time_scale, 1.0, "failed view's context writes must be discarded"); + control_input(&mut rt, &json!({"tap": "count-7"})); + rt.frame(0.0); + assert!(rt.find("count-8").is_some(), "original handlers still operate on retained state"); + assert_eq!(rt.state.value.as_ref() as *const dyn Any as *const (), address); + // A later healthy patch is still attempted rather than latching the failure. + rt.state.view = |host, cx| { + let state = host.value.downcast_ref::<usize>().unwrap(); + view_or_original(original, state, cx, |s, _| el().key(format!("recovered-{s}"))) + }; + rt.update(|_, _| {}); + rt.frame(0.0); + assert!(rt.find("recovered-8").is_some()); +} + +#[test] +fn invalid_control_input_is_skipped_and_later_requests_still_work() { + let mut rt = runtime(|_: &usize, _: &mut Cx<usize>| el().key("button").on_press(|s: &mut usize| *s += 1)); + rt.frame(0.0); + for command in [ + json!({"tap": "missing"}), json!({"tap": 1}), + json!({"scroll": null}), json!({"scroll": "down"}), + json!({"scroll": [1, 2]}), json!({"scroll": [1, 2, 3, 4]}), + json!({"scroll": [1, "bad", 3]}), json!({"scroll": [1, 2, 1e100]}), + ] { + control_input(&mut rt, &command); + rt.frame(0.0); + } + assert_eq!(*rt.state.value.downcast_ref::<usize>().unwrap(), 0); + control_input(&mut rt, &json!({"tap": "button", "scroll": [10, 10, 20]})); + rt.frame(0.0); + assert_eq!(*rt.state.value.downcast_ref::<usize>().unwrap(), 1); +} + +#[test] +fn erased_host_routes_focus_physical_links_and_window_callbacks() { + #[derive(Default)] + struct Events { presses: usize, physical: usize, dismisses: usize, links: Vec<String>, paste: String, focused: bool, moved: bool, layout: Option<[f32; 4]> } + fn view(_: &Events, _: &mut Cx<Events>) -> El { + col().size(300.0, 200.0) + .on_paste(|s: &mut Events, text, _| s.paste = text.into()) + .on_window_focus(|s: &mut Events, focused, _| s.focused = focused) + .modal(false, |s: &mut Events| s.dismisses += 1) + .child(el().key("button").size(100.0, 30.0).focusable(true) + .on_press(|s: &mut Events| s.presses += 1) + .on_pointer_move(|s: &mut Events, _| s.moved = true) + .on_layout(|s: &mut Events, rect| s.layout = Some(rect)) + .on_physical_input(|s: &mut Events, ev, _| { + if matches!(ev, crate::PhysicalInput::Modifiers(_)) { s.physical += 1; } + false + })) + .child(crate::text("docs").link(crate::Link::new(0..4, "docs")) + .on_link(|s: &mut Events, id, _| s.links.push(id.into()))) + } + let mut rt = runtime(view); + rt.frame(0.0); + rt.frame(0.0); // Deliver the first layout report. + rt.window_focus(true); + rt.paste("window paste"); + // The modal focuses its first control; Space presses it (Return would go to the default button). + rt.key(KeyEvent { key: Key::Text(" ".into()), mods: Default::default() }); + rt.physical_input(crate::PhysicalInput::Modifiers(Default::default())); + rt.frame(0.0); + let (x, y) = rt.find("button").unwrap(); + rt.pointer_move(x, y); + rt.key(KeyEvent { key: Key::Tab, mods: Default::default() }); + rt.key(KeyEvent { key: Key::Enter, mods: Default::default() }); + rt.key(KeyEvent { key: Key::Escape, mods: Default::default() }); + rt.frame(0.0); + let s = rt.state.value.downcast_ref::<Events>().unwrap(); + assert_eq!((s.presses, s.physical, s.dismisses), (1, 1, 1)); + assert_eq!(s.links, ["docs"]); + assert_eq!(s.paste, "window paste"); + assert!(s.focused && s.moved); + assert_eq!(s.layout.unwrap()[2..], [100.0, 30.0]); +} + +#[test] +fn erased_host_preserves_context_reads_and_host_motion_preference() { + #[derive(Default)] + struct Reads { edit: TextEdit, seen: std::cell::RefCell<(bool, Option<[f32; 4]>, Option<[f32; 4]>)> } + fn view(s: &Reads, cx: &mut Cx<Reads>) -> El { + *s.seen.borrow_mut() = (cx.system_reduced_motion(), cx.layout("input"), cx.caret("input")); + col().child(text_input(&s.edit, crate::TextStyle::new(14.0, 400.0)).key("input").size(180.0, 30.0) + .on_edit(|s: &mut Reads| &mut s.edit)) + } + let mut rt = runtime(view); + rt.set_system_reduced_motion(true); + rt.frame(0.0); + let (x, y) = rt.find("input").unwrap(); + rt.pointer_down(x, y); + rt.pointer_up(x, y); + rt.paste("caret"); + rt.frame(0.0); + rt.frame(0.0); + let s = rt.state.value.downcast_ref::<Reads>().unwrap(); + let (reduced, layout, caret) = *s.seen.borrow(); + assert!(reduced); + assert_eq!(layout.unwrap()[2..], [180.0, 30.0]); + assert!(caret.unwrap()[0] > 0.0); + assert_eq!(s.edit.text, "caret"); +} + +#[test] +fn erased_host_routes_handlers_and_context_to_the_typed_state() { + fn view(s: &State, cx: &mut Cx<State>) -> El { + cx.time_scale(0.75); + col().child(el().key("button").size(80.0, 30.0).on_press(|s: &mut State| s.pressed = true) + .on_hover(|s: &mut State| s.hovered = true) + .on_secondary_press(|s: &mut State, _, _| s.secondary = true)) + .child(text_input(&s.edit, crate::tok::TextStyle::new(14.0, 400.0)).key("input").size(180.0, 30.0) + .on_input_change(|s: &mut State, _| s.changed = true) + .on_input_key(|s: &mut State, _, _| { s.keyed = true; false }) + .on_edit(|s: &mut State| &mut s.edit).on_submit(|s: &mut State, tx| { tx.copy(s.edit.text.clone()); })) + } + let spec = AppSpec::new("test", (200.0, 150.0), || State { pressed: false, hovered: false, secondary: false, changed: false, keyed: false, edit: TextEdit::new("") }, view); + let host = HostState { value: Box::new((spec.init)()), spec: Box::new(spec), view: view_adapter::<State>, poll: poll_adapter::<State>, setup: setup_adapter::<State>, key: key_adapter::<State> }; + let mut rt = crate::Runtime::new(host, |s, cx| (s.view)(s, cx), (200.0, 150.0), Env { system_dark: true, scale: 1.0 }); + rt.frame(0.0); + assert_eq!(rt.time_scale, 0.75); + let (x, y) = rt.find("button").unwrap(); + rt.secondary_down(x, y); + rt.secondary_up(x, y); + rt.frame(0.0); + for key in ["button", "input"] { + let (x, y) = rt.find(key).unwrap(); + rt.pointer_move(x, y); + rt.pointer_down(x, y); + rt.pointer_up(x, y); + rt.frame(0.0); + } + rt.paste("state kept"); + rt.frame(0.0); + rt.key(KeyEvent { key: Key::Enter, mods: Default::default() }); + rt.frame(0.0); + let s = rt.state.value.downcast_ref::<State>().unwrap(); + assert!(s.pressed); + assert!(s.hovered); + assert!(s.secondary && s.changed && s.keyed); + assert_eq!(s.edit.text, "state kept"); + assert_eq!(rt.copy_request.as_deref(), Some("state kept")); +} diff --git a/app/vendor/rune/crates/rune/src/input.rs b/app/vendor/rune/crates/rune/src/input.rs new file mode 100644 index 0000000..c822bb4 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/input.rs @@ -0,0 +1,16 @@ +pub(crate) mod canvas_input; +pub(crate) mod chord; +mod chord_label; +pub(crate) mod cursor; +pub(crate) mod drop_pointer; +#[cfg(target_os = "macos")] +pub(crate) mod fn_key; +pub(crate) mod host_events; +pub(crate) mod key_diagnostics; +pub(crate) mod key_table; +pub(crate) mod keycaps; +pub(crate) mod physical_input; +#[cfg(any(test, target_os = "windows", all(unix, not(target_os = "macos"), not(target_os = "ios"), not(target_os = "android"))))] +pub(crate) mod pointer_observer; +pub(crate) mod secure_input; +pub(crate) mod time; diff --git a/app/vendor/rune/crates/rune/src/input/canvas_input.rs b/app/vendor/rune/crates/rune/src/input/canvas_input.rs new file mode 100644 index 0000000..f845c5e --- /dev/null +++ b/app/vendor/rune/crates/rune/src/input/canvas_input.rs @@ -0,0 +1,216 @@ +//! Input a canvas app needs beyond presses and scrolling: wheel deltas an element takes before +//! any scroll view does, trackpad pinch, rotation and smart magnify, the middle and other mouse +//! buttons, and key releases. Runtime dispatch is in `runtime/input/gesture.rs`. +use std::rc::Rc; + +use crate::{El, KeyEvent, Mods, Tx}; + +/// Where a wheel or trackpad gesture is. A mouse wheel, which reports no phases, is always +/// `Moved`. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum GesturePhase { + /// The fingers touched down (or momentum began). + Began, + #[default] + Moved, + /// The fingers lifted or the system cancelled the gesture. Its delta is often zero. + Ended, +} + +/// A wheel or trackpad scroll an [`El::on_wheel`] handler sees. +#[non_exhaustive] +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub struct WheelEvent { + /// Points to move content by, positive moving it right and down (the fingers' direction + /// with natural scrolling). + pub dx: f32, + pub dy: f32, + /// The pointer in the handling element's own layout points: from its top-left as drawn, + /// divided by any scale it draws at (a canvas camera's `live_scale`). + pub x: f32, + pub y: f32, + pub mods: Mods, + pub phase: GesturePhase, + /// The content is coasting after the fingers lifted (macOS momentum). + pub momentum: bool, + /// Point-precise deltas (a trackpad or a free-spinning wheel), rather than the line steps of + /// a notched mouse wheel, which an app may want to smooth. + pub precise: bool, + /// Whole notches of a mouse wheel on a platform whose browsers ease them (Windows): an + /// unclaimed delta eases there as Chromium's does (`Runtime::set_wheel_glide`). + pub notch: bool, +} + +impl WheelEvent { + /// A delta of (dx, dy) points. Hand it to [`crate::Runtime::wheel_event`] with + /// [`WheelEvent::at`] in window points. + pub fn new(dx: f32, dy: f32) -> Self { Self { dx, dy, ..Self::default() } } + pub fn at(mut self, x: f32, y: f32) -> Self { self.x = x; self.y = y; self } + pub fn mods(mut self, mods: Mods) -> Self { self.mods = mods; self } + pub fn phase(mut self, phase: GesturePhase) -> Self { self.phase = phase; self } + pub fn precise(mut self, precise: bool) -> Self { self.precise = precise; self } + pub fn notch(mut self, notch: bool) -> Self { self.notch = notch; self } +} + +/// A pinch an [`El::on_magnify`] handler sees. +#[non_exhaustive] +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub struct MagnifyEvent { + /// The change in magnification: scale by `1.0 + delta`. Positive zooms in. + pub delta: f32, + /// The pointer in the handling element's own layout points: from its top-left as drawn, + /// divided by any scale it draws at (a canvas camera's `live_scale`). + pub x: f32, + pub y: f32, + pub phase: GesturePhase, +} + +impl MagnifyEvent { + /// A pinch of `delta`. Hand it to [`crate::Runtime::magnify_event`] with + /// [`MagnifyEvent::at`] in window points. + pub fn new(delta: f32) -> Self { Self { delta, ..Self::default() } } + pub fn at(mut self, x: f32, y: f32) -> Self { self.x = x; self.y = y; self } + pub fn phase(mut self, phase: GesturePhase) -> Self { self.phase = phase; self } +} + +/// A two-finger rotation an [`El::on_rotate`] handler sees. +#[non_exhaustive] +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub struct RotateEvent { + /// Degrees turned since the last event, positive counterclockwise. + pub degrees: f32, + pub x: f32, + pub y: f32, + pub phase: GesturePhase, +} + +impl RotateEvent { + pub fn new(degrees: f32) -> Self { Self { degrees, ..Self::default() } } + pub fn at(mut self, x: f32, y: f32) -> Self { self.x = x; self.y = y; self } + pub fn phase(mut self, phase: GesturePhase) -> Self { self.phase = phase; self } +} + +/// A mouse button. Only `Primary` reaches `on_press` and `on_drag` unless an element opts in to +/// others with [`El::pointer_buttons`]; `Secondary` always goes to `on_secondary_press`. +#[non_exhaustive] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] +pub enum PointerButton { + #[default] + Primary, + Secondary, + Middle, + Back, + Forward, + /// Any other button, by the platform's number for it. + Other(u16), +} + +impl PointerButton { + /// Its bit in [`CanvasInput::buttons`]; none for the primary and secondary buttons. + pub(crate) fn bit(self) -> u8 { + match self { + Self::Primary | Self::Secondary => 0, + Self::Middle => 1, + Self::Back => 2, + Self::Forward => 4, + Self::Other(_) => 8, + } + } +} + +type WheelFn = Rc<dyn Fn(crate::states::States<'_>, WheelEvent, &mut Tx) -> bool>; +type MagnifyFn = Rc<dyn Fn(crate::states::States<'_>, MagnifyEvent, &mut Tx) -> bool>; +type RotateFn = Rc<dyn Fn(crate::states::States<'_>, RotateEvent, &mut Tx) -> bool>; +type SmartMagnifyFn = Rc<dyn Fn(crate::states::States<'_>, f32, f32, &mut Tx) -> bool>; + +/// An element's canvas handlers, boxed: few elements have any. +#[derive(Clone, Default)] +pub(crate) struct CanvasInput { + pub wheel: Option<WheelFn>, + pub magnify: Option<MagnifyFn>, + pub rotate: Option<RotateFn>, + pub smart_magnify: Option<SmartMagnifyFn>, + /// [`PointerButton::bit`]s of the buttons besides the primary that press and drag it. + pub buttons: u8, +} + +impl CanvasInput { + /// It takes a gesture, so it hit-tests like an element with a press handler. + pub(crate) fn takes_gestures(&self) -> bool { + self.wheel.is_some() || self.magnify.is_some() || self.rotate.is_some() || self.smart_magnify.is_some() + } +} + +fn state<S: 'static>(s: crate::states::States<'_>) -> &mut S { + s.cast::<S>().expect("handler registered for a different state type than the app's") +} + +impl El { + fn canvas_input(&mut self) -> &mut CanvasInput { + self.handlers.gestures.get_or_insert_with(Default::default) + } + + /// Wheel and trackpad scrolls over this element, before any scroll view around or under + /// the pointer moves: return true to take the delta, false to let it scroll as usual. The + /// innermost handler under the pointer hears it first, up to and including the nearest + /// scroll view. Once a handler takes a gesture's first delta it gets the rest of that + /// gesture, its momentum included, wherever the pointer goes, as a scroll view keeps the + /// axis it locked to. + /// + /// A canvas pans with plain deltas and zooms with ⌘ (`mods.cmd`) or pinch + /// ([`El::on_magnify`]). Off macOS a trackpad pinch arrives as a Ctrl + wheel, which goes + /// to `on_magnify` when an element here has one. + pub fn on_wheel<S: 'static>(mut self, f: impl Fn(&mut S, WheelEvent, &mut Tx) -> bool + 'static) -> Self { + self.canvas_input().wheel = Some(Rc::new(move |s, e, tx| f(state::<S>(s), e, tx))); + self + } + + /// Trackpad pinches over this element: return true to take one. The innermost handler + /// under the pointer hears it first. macOS reports pinches; on Windows, Linux and the web + /// a pinch (and Ctrl + mouse wheel) comes as a Ctrl + wheel delta, turned into a delta of + /// `-dy / 200` per point. + pub fn on_magnify<S: 'static>(mut self, f: impl Fn(&mut S, MagnifyEvent, &mut Tx) -> bool + 'static) -> Self { + self.canvas_input().magnify = Some(Rc::new(move |s, e, tx| f(state::<S>(s), e, tx))); + self + } + + /// Two-finger trackpad rotation over this element (macOS): return true to take it. + pub fn on_rotate<S: 'static>(mut self, f: impl Fn(&mut S, RotateEvent, &mut Tx) -> bool + 'static) -> Self { + self.canvas_input().rotate = Some(Rc::new(move |s, e, tx| f(state::<S>(s), e, tx))); + self + } + + /// A two-finger double tap over this element (macOS smart magnify), with the pointer in + /// its own layout points (as [`WheelEvent::x`] and `y`): return true to take it. + pub fn on_smart_magnify<S: 'static>(mut self, f: impl Fn(&mut S, f32, f32, &mut Tx) -> bool + 'static) -> Self { + self.canvas_input().smart_magnify = Some(Rc::new(move |s, x, y, tx| f(state::<S>(s), x, y, tx))); + self + } + + /// Mouse buttons besides the primary that press and drag this element: its `on_press` and + /// `on_drag` hear them too, and [`Tx::button`] says which. A middle-button drag pans a + /// canvas this way. The secondary button keeps opening `on_secondary_press`. + pub fn pointer_buttons(mut self, buttons: impl IntoIterator<Item = PointerButton>) -> Self { + let bits = buttons.into_iter().fold(0, |bits, b| bits | b.bit()); + self.canvas_input().buttons |= bits; + self + } + + /// Key releases. A release goes to the focused element's handler, then each ancestor's up + /// to the root; with nothing focused, to the root's (or an open modal's), so a handler on a + /// window's root hears every release nothing else took. Return true to take it. The key is + /// logical, as `on_key` sees it: Space is `Key::Text(" ")`. A canvas that pans while Space + /// is held starts on Space's press in `on_key` and stops here. + pub fn on_key_up<S: 'static>(mut self, f: impl Fn(&mut S, &KeyEvent, &mut Tx) -> bool + 'static) -> Self { + self.cold_mut().focus.key_up = Some(Rc::new(move |s, e, tx| f(state::<S>(s), e, tx))); + self + } +} + +impl Tx { + /// In `on_press` and `on_drag`, the button that drove it, which is + /// [`PointerButton::Primary`] unless the element opted in to others with + /// [`El::pointer_buttons`]; in `on_link`, `Middle` for a middle click on the link; in + /// [`El::on_middle_press`], `Middle`. Other handlers see `Primary`. + pub fn button(&self) -> PointerButton { self.button } +} diff --git a/app/vendor/rune/crates/rune/src/input/chord.rs b/app/vendor/rune/crates/rune/src/input/chord.rs new file mode 100644 index 0000000..1fddd2d --- /dev/null +++ b/app/vendor/rune/crates/rune/src/input/chord.rs @@ -0,0 +1,350 @@ +//! In-app key chords: "mod+shift+t" as data, matched against a `KeyEvent` and drawn per +//! platform. `mod` is the platform's primary modifier (⌘ on macOS, Ctrl elsewhere); `ctrl`, +//! `alt`, `shift` and `super` name keys. Both sides of a match resolve to the keys held on +//! the platform, so "mod+b" and "ctrl+b" are the same chord on Windows and Linux, and +//! different ones (⌘B and ⌃B) on macOS. `Keybind` adds alternatives and per-platform chords. +use std::{fmt, hash::{Hash, Hasher}, str::FromStr}; + +use super::key_table::{char_named, chord_key_from_key, chord_key_named, modifier_named, parse_function_key}; +pub use crate::edit::KeyPlatform; +use crate::edit::{ALT, CTRL, PRIMARY, SHIFT, SUPER, fold, held}; +use crate::{Key, KeyEvent, PhysicalKeyCode}; + +/// One modifier as a chord names it. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum ChordMod { + /// "mod": ⌘ on macOS, Ctrl elsewhere. + Primary, + /// "ctrl": the Control key. Off macOS it is the primary modifier, so it equals `Primary`. + Ctrl, + /// "alt": Option on macOS. + Alt, + Shift, + /// "super": the logo key (Windows key, Super); ⌘ on macOS, where it equals `Primary`. + Super, +} + +impl ChordMod { + pub(super) const fn bit(self) -> u8 { + match self { Self::Primary => PRIMARY, Self::Ctrl => CTRL, Self::Alt => ALT, Self::Shift => SHIFT, Self::Super => SUPER } + } +} + +/// The key a chord ends in. A character is the one the key types without Shift ('t', '[', +/// '1', ','), lowercase; name the unshifted key and add `shift` ("mod+shift+[", not "mod+{"). +#[non_exhaustive] +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum ChordKey { + Char(char), + Enter, + Tab, + Escape, + Backspace, + Delete, + Insert, + Home, + End, + PageUp, + PageDown, + Left, + Right, + Up, + Down, + /// F1 through F24. + Function(u8), + ContextMenu, + PrintScreen, + ScrollLock, + Pause, +} + +/// A key with modifiers, as an app binds it: `Chord::parse("mod+shift+t")`. Parsing is +/// case-insensitive and ignores spaces around each "+"; modifiers are `mod` (alias `primary`), +/// `ctrl` (`control`), `alt` (`option`, `opt`), `shift` and `super` (`cmd`, `command`, `meta`, +/// `win`, `logo`: the literal ⌘ or logo key, which is rarely what a cross-platform binding +/// wants). Keys are a character or a name: `enter` (`return`), `tab`, `escape` (`esc`), +/// `backspace`, `delete` (`del`), `insert`, `home`, `end`, `pageup`, `pagedown`, +/// `left`/`right`/`up`/`down` (`arrowleft`, …), `space`, `plus` (or a trailing "+": +/// "mod++"), `comma`, the punctuation names (`minus`, `bracketleft`, …), `f1`–`f24`, +/// `contextmenu` (`menu`), `printscreen`, `scrolllock` and `pause`. "{" and "}" read as Shift +/// with "[" and "]", the keys that type them on a US layout. `Display` writes the canonical +/// form back ("mod+shift+t"), for settings files. +#[derive(Clone, Copy, Debug)] +pub struct Chord { + mods: u8, + key: ChordKey, +} + +/// A chord or keybind string that doesn't parse. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct ChordError(String); + +impl fmt::Display for ChordError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "invalid key chord: {}", self.0) } +} + +impl std::error::Error for ChordError {} + +impl Chord { + /// The key alone; add modifiers with `with`. The key is stored as parsing would write it: + /// a character lowercased, '{' and '}' as Shift with '[' and ']', a tab, newline, escape, + /// backspace or delete character as that key, and a function key within F1–F24. + pub const fn new(key: ChordKey) -> Self { + let (mods, key) = match key { + ChordKey::Char('{') => (SHIFT, ChordKey::Char('[')), + ChordKey::Char('}') => (SHIFT, ChordKey::Char(']')), + ChordKey::Char('\t') => (0, ChordKey::Tab), + ChordKey::Char('\n' | '\r') => (0, ChordKey::Enter), + ChordKey::Char('\u{1b}') => (0, ChordKey::Escape), + ChordKey::Char('\u{8}') => (0, ChordKey::Backspace), + ChordKey::Char('\u{7f}') => (0, ChordKey::Delete), + ChordKey::Char(c) => (0, ChordKey::Char(c.to_ascii_lowercase())), + ChordKey::Function(n) => (0, ChordKey::Function(if n < 1 { 1 } else if n > 24 { 24 } else { n })), + key => (0, key), + }; + Self { mods, key } + } + + /// This chord with `m` held too. + pub const fn with(self, m: ChordMod) -> Self { Self { mods: self.mods | m.bit(), key: self.key } } + + pub fn parse(s: &str) -> Result<Self, ChordError> { s.parse() } + + /// The key, a character lowercased. + pub fn key(&self) -> ChordKey { + match self.key { ChordKey::Char(c) => ChordKey::Char(lower(c)), key => key } + } + + /// Whether the chord names `m`, as written (before platform resolution). + pub fn has(&self, m: ChordMod) -> bool { self.mods & m.bit() != 0 } + + /// Whether `ev` is this chord on this platform: the same keys held, no more and no fewer, + /// and the same key. Letters match either case. A shifted character also matches the key + /// that types it unshifted on a US layout ('{' for "shift+["); use `matches_tx` in a key + /// handler to follow the user's layout instead. + pub fn matches(&self, ev: &KeyEvent) -> bool { self.matches_on(ev, KeyPlatform::current()) } + + /// `matches`, also comparing a character chord with `tx.key_base()`, the character the + /// key types with no modifiers under the current layout (⌥B types "∫" on a Mac, ⇧[ types + /// "{"), so the binding follows the layout as the menu bar's does. Where neither that + /// character nor the typed one is ASCII (a Cyrillic or Greek layout, "ü" on German) an + /// ASCII chord falls back to `tx.physical_key()`, the key in that place on a US layout. + pub fn matches_tx(&self, ev: &KeyEvent, tx: &crate::Tx) -> bool { self.matches_tx_on(ev, tx, KeyPlatform::current()) } + + /// `matches`, resolving the chord with `platform`'s conventions: for tests, or an app that + /// lets the user pick a keymap. `ev.mods` reads as this build reports them. + pub fn matches_on(&self, ev: &KeyEvent, platform: KeyPlatform) -> bool { self.matches_with(ev, None, None, platform) } + + /// `matches_tx` with `platform`'s conventions; see `matches_on`. + pub fn matches_tx_on(&self, ev: &KeyEvent, tx: &crate::Tx, platform: KeyPlatform) -> bool { + self.matches_with(ev, tx.key_base(), tx.physical_key(), platform) + } + + /// Whether `self` and `other` are the same keys on `platform`: "mod+b" and "ctrl+b" are + /// on Windows and Linux, not on macOS. For conflict checks in a shortcut table or editor. + pub fn same_keys(&self, other: &Chord, platform: KeyPlatform) -> bool { + self.key() == other.key() && fold(self.mods, platform) == fold(other.mods, platform) + } + + /// The modifiers this chord needs on `platform`, in label order: ⌃⌥⇧⌘ on macOS, where + /// `Super` folds into `Primary`; Ctrl, Alt, Shift, Super elsewhere, where `Ctrl` does. + pub fn mods_on(&self, platform: KeyPlatform) -> Vec<ChordMod> { + let bits = fold(self.mods, platform); + let order = if platform == KeyPlatform::Mac { + [ChordMod::Ctrl, ChordMod::Alt, ChordMod::Shift, ChordMod::Primary] + } else { + [ChordMod::Primary, ChordMod::Alt, ChordMod::Shift, ChordMod::Super] + }; + order.into_iter().filter(|m| bits & m.bit() != 0).collect() + } + + fn matches_with(&self, ev: &KeyEvent, base: Option<char>, physical: Option<PhysicalKeyCode>, platform: KeyPlatform) -> bool { + let (want, held) = (fold(self.mods, platform), held(ev.mods, platform)); + let ChordKey::Char(c) = self.key() else { return want == held && chord_key_from_key(&ev.key) == Some(self.key) }; + let Some(typed) = typed(&ev.key) else { return false }; + let base = base.map(lower); + // Past the typed character, the key's own: its unmodified character when the layout + // gives one, else the US key that types it shifted, and past a non-Latin character + // the US key in its place, as browsers' shortcut handling falls back to `code`. + let us = || c.is_ascii() && !typed.is_ascii() && physical.and_then(crate::shortcuts::us_char) == Some(c); + if want == held { + return typed == c || match base { + Some(b) => b == c || (!b.is_ascii() && us()), + None => (ev.mods.shift && us_unshifted(typed) == Some(c)) || us(), + }; + } + // A chord on a shifted character ("mod+plus") is that character with or without the + // Shift that types it: Ctrl+Shift+= on a US layout, Ctrl++ on a German one. + held == want | SHIFT && !c.is_alphanumeric() && typed == c && base != Some(c) + } +} + +impl PartialEq for Chord { + fn eq(&self, other: &Self) -> bool { self.mods == other.mods && self.key() == other.key() } +} + +impl Eq for Chord {} + +impl Hash for Chord { + fn hash<H: Hasher>(&self, state: &mut H) { + self.mods.hash(state); + self.key().hash(state); + } +} + +impl FromStr for Chord { + type Err = ChordError; + fn from_str(input: &str) -> Result<Self, Self::Err> { + let invalid = || ChordError(input.into()); + let mut parts: Vec<&str> = input.split('+').map(str::trim).collect(); + // Two empty parts at the end are the plus key: "mod++", "mod + +", "+". + let plus = parts.len() >= 2 && parts[parts.len() - 2..].iter().all(|p| p.is_empty()); + if plus { + parts.truncate(parts.len() - 2); + if parts == [""] { parts.clear(); } + } + let mut mods = 0; + let mut key = plus.then_some(ChordKey::Char('+')); + for part in parts { + let part = part.to_lowercase(); + if let Some(m) = modifier_named(&part) { + if key.is_some() || mods & m.bit() != 0 { return Err(invalid()); } + mods |= m.bit(); + continue; + } + if key.is_some() { return Err(invalid()); } + key = Some(key_named(&part).ok_or_else(invalid)?); + } + let chord = Self::new(key.ok_or_else(invalid)?); + Ok(Self { mods: mods | chord.mods, key: chord.key }) + } +} + +/// A command's chords: any of several alternatives ("mod+t, mod+n"), with other chords on +/// some platforms. `Keybind::new("mod+b").on(KeyPlatform::Windows, "alt+home")` is ⌘B on +/// macOS, Ctrl+B on Linux and Alt+Home on Windows. "" and "none" bind nothing. +#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)] +pub struct Keybind { + chords: Vec<Chord>, + platforms: Vec<(KeyPlatform, Vec<Chord>)>, +} + +impl Keybind { + /// A keybind from a literal in the app's code. Panics if it doesn't parse; parse user + /// input (a settings file) with `str::parse` instead. + #[track_caller] + pub fn new(spec: &str) -> Self { + spec.parse().unwrap_or_else(|e| panic!("{e}")) + } + + /// These chords instead on `platform`. Panics if `spec` doesn't parse, as `new` does. + #[track_caller] + pub fn on(self, platform: KeyPlatform, spec: &str) -> Self { + self.on_chords(platform, &parse_list(spec).unwrap_or_else(|e| panic!("{e}"))) + } + + /// `chords` instead on `platform`: `on` for chords built as data. + pub fn on_chords(mut self, platform: KeyPlatform, chords: &[Chord]) -> Self { + self.platforms.retain(|(p, _)| *p != platform); + self.platforms.push((platform, chords.to_vec())); + self + } + + /// The chords that apply on `platform`. + pub fn chords_on(&self, platform: KeyPlatform) -> &[Chord] { + self.platforms.iter().find(|(p, _)| *p == platform).map_or(&self.chords, |(_, c)| c) + } + + /// The chords that apply here. + pub fn chords(&self) -> &[Chord] { self.chords_on(KeyPlatform::current()) } + + /// Whether `ev` is any of this platform's chords; see `Chord::matches`. + pub fn matches(&self, ev: &KeyEvent) -> bool { self.matches_on(ev, KeyPlatform::current()) } + + /// Whether `ev` is any of this platform's chords; see `Chord::matches_tx`. + pub fn matches_tx(&self, ev: &KeyEvent, tx: &crate::Tx) -> bool { self.matches_tx_on(ev, tx, KeyPlatform::current()) } + + /// Whether `ev` is any of `platform`'s chords; see `Chord::matches_on`. + pub fn matches_on(&self, ev: &KeyEvent, platform: KeyPlatform) -> bool { + self.chords_on(platform).iter().any(|c| c.matches_on(ev, platform)) + } + + /// Whether `ev` is any of `platform`'s chords; see `Chord::matches_tx_on`. + pub fn matches_tx_on(&self, ev: &KeyEvent, tx: &crate::Tx, platform: KeyPlatform) -> bool { + self.chords_on(platform).iter().any(|c| c.matches_tx_on(ev, tx, platform)) + } + + /// The first chord's label here ("⇧⌘T", "Ctrl+Shift+T"), or "" when nothing is bound. + pub fn label(&self) -> String { self.label_on(KeyPlatform::current()) } + + /// The first chord's label on `platform`, or "" when nothing is bound there. + pub fn label_on(&self, platform: KeyPlatform) -> String { + self.chords_on(platform).first().map(|c| c.label_on(platform)).unwrap_or_default() + } + + /// The string `parse` reads back as `platform`'s chords: "mod+t, mod+n", or "none". + pub fn spec_on(&self, platform: KeyPlatform) -> String { + let chords = self.chords_on(platform); + if chords.is_empty() { return "none".into(); } + chords.iter().map(Chord::to_string).collect::<Vec<_>>().join(", ") + } +} + +impl From<Chord> for Keybind { + fn from(chord: Chord) -> Self { Self { chords: vec![chord], platforms: Vec::new() } } +} + +impl From<&[Chord]> for Keybind { + fn from(chords: &[Chord]) -> Self { Self { chords: chords.to_vec(), platforms: Vec::new() } } +} + +impl FromStr for Keybind { + type Err = ChordError; + fn from_str(spec: &str) -> Result<Self, Self::Err> { + Ok(Self { chords: parse_list(spec)?, platforms: Vec::new() }) + } +} + +/// The chords that apply here, comma-separated (`spec_on` the current platform), so a +/// settings file written here reads back as what this platform binds. +impl fmt::Display for Keybind { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.write_str(&self.spec_on(KeyPlatform::current())) } +} + +fn parse_list(spec: &str) -> Result<Vec<Chord>, ChordError> { + let spec = spec.trim(); + if spec.is_empty() || spec.eq_ignore_ascii_case("none") { return Ok(Vec::new()); } + spec.split(',').map(str::parse).collect() +} + +fn key_named(name: &str) -> Option<ChordKey> { + if let Some(key) = chord_key_named(name) { return Some(key); } + if let Some(c) = char_named(name) { return Some(ChordKey::Char(c)); } + if let Some(n) = parse_function_key(name, 'f') { return Some(ChordKey::Function(n)); } + let mut chars = name.chars(); + match (chars.next(), chars.next()) { (Some(c), None) => Some(ChordKey::Char(lower(c))), _ => None } +} + +/// The one character `key` types, lowercased. +fn typed(key: &Key) -> Option<char> { + match key { + Key::Command(c) => Some(lower(*c)), + Key::Text(t) => { + let mut chars = t.chars(); + match (chars.next(), chars.next()) { (Some(c), None) => Some(lower(c)), _ => None } + } + _ => None, + } +} + +/// `c` lowercased when that is one character. +pub(super) fn lower(c: char) -> char { + let mut l = c.to_lowercase(); + match (l.next(), l.next()) { (Some(l), None) => l, _ => c } +} + +/// The key that types `c` with Shift on a US layout. +fn us_unshifted(c: char) -> Option<char> { + let (shifted, plain) = ("~!@#$%^&*()_+{}|:\"<>?", "`1234567890-=[]\\;',./"); + shifted.chars().position(|s| s == c).and_then(|i| plain.chars().nth(i)) +} diff --git a/app/vendor/rune/crates/rune/src/input/chord_label.rs b/app/vendor/rune/crates/rune/src/input/chord_label.rs new file mode 100644 index 0000000..917db4b --- /dev/null +++ b/app/vendor/rune/crates/rune/src/input/chord_label.rs @@ -0,0 +1,47 @@ +//! How a `Chord` reads: canonical text for settings files, and keycaps per platform. +//! Driven by the canonical modifier, key and punctuation tables in `input::key_table`. +use std::fmt; + +use super::chord::{Chord, ChordKey, KeyPlatform}; +use super::key_table; + +impl Chord { + /// How the chord reads here: "⇧⌘T" on macOS, "Ctrl+Shift+T" on Windows and Linux. + pub fn label(&self) -> String { self.label_on(KeyPlatform::current()) } + + /// How the chord reads on `platform`: macOS glyphs run together in Apple's order + /// (⌃⌥⇧⌘), elsewhere words join with "+" in Ctrl, Alt, Shift, Win (Super) order. + pub fn label_on(&self, platform: KeyPlatform) -> String { + self.keycaps_on(platform).join(if platform == KeyPlatform::Mac { "" } else { "+" }) + } + + /// One label per key, modifiers first, for drawing each as a keycap. + pub fn keycaps_on(&self, platform: KeyPlatform) -> Vec<String> { + let mut caps: Vec<String> = self.mods_on(platform).into_iter() + .map(|m| key_table::modifier_label(m, platform).to_owned()) + .collect(); + caps.push(match self.key() { + ChordKey::Char(' ') => "Space".into(), + ChordKey::Char(c) => key_table::capital_keycap(&c.to_string()), + ChordKey::Function(n) => format!("F{n}"), + key => key_table::chord_key_label(key, platform).to_owned(), + }); + caps + } +} + +/// The canonical form `parse` reads back: modifiers in mod, ctrl, alt, shift, super order, +/// then the key ("mod+shift+t", "ctrl+tab", "mod+comma"). +impl fmt::Display for Chord { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + for m in key_table::MODS { + if self.has(m.chord) { write!(f, "{}+", m.aliases[0])?; } + } + match self.key() { + ChordKey::Char(c @ (' ' | '+' | ',')) => f.write_str(key_table::char_name(c).unwrap_or("")), + ChordKey::Char(c) => write!(f, "{c}"), + ChordKey::Function(n) => write!(f, "f{n}"), + key => f.write_str(key_table::chord_key_canonical(key)), + } + } +} diff --git a/app/vendor/rune/crates/rune/src/input/cursor.rs b/app/vendor/rune/crates/rune/src/input/cursor.rs new file mode 100644 index 0000000..91652d9 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/input/cursor.rs @@ -0,0 +1,181 @@ +//! The pointer's shape over an element. + +pub(crate) mod image; +pub(crate) mod os; + +/// The pointer's shape over an element (CSS `cursor`). Elements without one inherit their +/// nearest ancestor's; text fields default to [`Cursor::Text`], everything else to the arrow. +/// +/// A macOS overlay is rarely the key window, so it sets its cursor directly while the pointer +/// is over its hit area. macOS honours that only while the overlay's app is frontmost, unless +/// `rune` is built with the `macos-background-cursor` feature. That feature uses a private +/// WindowServer property (`SetsCursorInBackground`), so App Store review may reject the app. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)] +#[non_exhaustive] +pub enum Cursor { + #[default] + Default, + Pointer, + Text, + Grab, + Grabbing, + NotAllowed, + Move, + ResizeColumn, + ResizeRow, + /// A precise-selection cross (CSS `crosshair`), for picking a point or dragging out a rect. + Crosshair, + /// A thick white plus (CSS `cell`), over a spreadsheet's cells. Windows has no such system + /// cursor, so there it draws Chromium's. + Cell, + /// The system's magnifier with a plus (CSS `zoom-in`), at the size of every other system + /// cursor: over a picture that opens larger. + ZoomIn, + /// The magnifier with a minus (CSS `zoom-out`). + ZoomOut, + /// No OS cursor (CSS `none`), for views that draw their own. It shows again as soon as the + /// pointer leaves the element or the window, the element goes away, or the host loses the + /// pointer: a window losing focus, an overlay hiding. + Hidden, + /// An app's own image (CSS `url()`), such as a pencil over a canvas. The OS draws it, so + /// it keeps up with the pointer and shows right to the window's edge. It comes and goes + /// like any other cursor. If its PNG doesn't decode, the arrow shows instead, and that's + /// logged once. + Image(CursorImage), +} + +/// The picture for [`Cursor::Image`]: a PNG drawn at 2x, so a 64×64 px PNG makes a +/// 32×32 pt cursor, and its hot spot (the point that clicks) in points from the top-left, +/// clamped into the image. +/// +/// ```ignore +/// const PENCIL: CursorImage = CursorImage::png(include_bytes!("pencil.png"), [2.0, 30.0]); +/// canvas.cursor(Cursor::Image(PENCIL)) +/// ``` +/// +/// Two images are the same cursor when they have the same bytes and hot spot. Comparing one +/// image with itself checks only the address, so it costs nothing per frame; a `const` may be +/// copied to another address at each use, which then compares the bytes. Each image is +/// decoded once and its OS cursor kept, up to 32 of them; a side may be up to 256 px. +#[derive(Clone, Copy)] +pub struct CursorImage { + bytes: &'static [u8], + hot: [f32; 2], + /// Resampled to the OS cursor's scale pixel for pixel, for a 1-bit cursor drawn on a grid. + crisp: bool, +} + +/// [`Cursor::Cell`] where the OS has none: Chromium's Windows `cell` cursor, each pixel of its +/// 32 px bitmap doubled. +#[cfg_attr(not(windows), allow(dead_code))] +pub(crate) const CELL: CursorImage = CursorImage { bytes: include_bytes!("cursor/cell.png"), hot: [7.0, 7.0], crisp: true }; + +/// The pan cursor a middle-click autoscroll shows (`runtime/input/autoscroll.rs`): Chromium's +/// Windows `pan_*` cursors, each pixel of their 32 px bitmaps doubled, which Blink picks the way +/// this does: while it scrolls, an arrow the way it goes; at rest, a mark of the axes +/// (horizontal, vertical) it can scroll on. +pub(crate) fn pan(axes: (bool, bool), velocity: (f32, f32)) -> CursorImage { + let pan = |bytes: &'static [u8]| CursorImage { bytes, hot: [16.0, 16.0], crisp: true }; + let (east, west, south, north) = (velocity.0 > 0.0, velocity.0 < 0.0, velocity.1 > 0.0, velocity.1 < 0.0); + match (north, south, east, west) { + (true, _, true, _) => pan(include_bytes!("cursor/pan_north_east.png")), + (true, _, _, true) => pan(include_bytes!("cursor/pan_north_west.png")), + (true, ..) => pan(include_bytes!("cursor/pan_north.png")), + (_, true, true, _) => pan(include_bytes!("cursor/pan_south_east.png")), + (_, true, _, true) => pan(include_bytes!("cursor/pan_south_west.png")), + (_, true, ..) => pan(include_bytes!("cursor/pan_south.png")), + (_, _, true, _) => pan(include_bytes!("cursor/pan_east.png")), + (_, _, _, true) => pan(include_bytes!("cursor/pan_west.png")), + _ => match axes { + (true, false) => pan(include_bytes!("cursor/pan_middle_horizontal.png")), + (false, true) => pan(include_bytes!("cursor/pan_middle_vertical.png")), + _ => pan(include_bytes!("cursor/pan_middle.png")), + }, + } +} + +impl CursorImage { + /// A PNG drawn at 2x, with its hot spot in points from the top-left. + pub const fn png(bytes: &'static [u8], hot: [f32; 2]) -> Self { + CursorImage { bytes, hot, crisp: false } + } + + pub(crate) fn bytes(&self) -> &'static [u8] { + self.bytes + } + + pub(crate) fn hot(&self) -> [f32; 2] { + self.hot + } + + #[cfg_attr(target_arch = "wasm32", allow(dead_code))] + pub(crate) fn crisp(&self) -> bool { + self.crisp + } + +} + +impl PartialEq for CursorImage { + fn eq(&self, other: &Self) -> bool { + self.hot.map(f32::to_bits) == other.hot.map(f32::to_bits) + && self.crisp == other.crisp + && (std::ptr::eq(self.bytes, other.bytes) || self.bytes == other.bytes) + } +} + +impl Eq for CursorImage {} + +impl std::hash::Hash for CursorImage { + fn hash<H: std::hash::Hasher>(&self, state: &mut H) { + (self.bytes.len(), self.hot.map(f32::to_bits)).hash(state); + } +} + +impl std::fmt::Debug for CursorImage { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("CursorImage").field("png_bytes", &self.bytes.len()).field("hot", &self.hot).finish() + } +} + +/// Which AppKit cursor backs each [`Cursor`] variant, kept cross-platform so adding a new +/// [`Cursor`] variant fails to compile until its macOS mapping is explicit. +#[cfg_attr(not(any(target_os = "macos", test)), allow(dead_code))] +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum MacCursor { + Arrow, + PointingHand, + IBeam, + OpenHand, + ClosedHand, + NotAllowed, + ResizeLeftRight, + ResizeUpDown, + Crosshair, + ZoomIn, + ZoomOut, + Transparent, + MoveImage, + CellImage, + Custom(CursorImage), +} + +#[cfg_attr(not(any(target_os = "macos", test)), allow(dead_code))] +pub(crate) fn mac_cursor(cursor: Cursor) -> MacCursor { + match cursor { + Cursor::Default => MacCursor::Arrow, + Cursor::Pointer => MacCursor::PointingHand, + Cursor::Text => MacCursor::IBeam, + Cursor::Grab => MacCursor::OpenHand, + Cursor::Grabbing => MacCursor::ClosedHand, + Cursor::NotAllowed => MacCursor::NotAllowed, + Cursor::ResizeColumn => MacCursor::ResizeLeftRight, + Cursor::ResizeRow => MacCursor::ResizeUpDown, + Cursor::Crosshair => MacCursor::Crosshair, + Cursor::ZoomIn => MacCursor::ZoomIn, + Cursor::ZoomOut => MacCursor::ZoomOut, + Cursor::Hidden => MacCursor::Transparent, + Cursor::Move => MacCursor::MoveImage, + Cursor::Cell => MacCursor::CellImage, + Cursor::Image(image) => MacCursor::Custom(image), + } +} diff --git a/app/vendor/rune/crates/rune/src/input/cursor/cell.png b/app/vendor/rune/crates/rune/src/input/cursor/cell.png new file mode 100644 index 0000000..a7341ee Binary files /dev/null and b/app/vendor/rune/crates/rune/src/input/cursor/cell.png differ diff --git a/app/vendor/rune/crates/rune/src/input/cursor/image.rs b/app/vendor/rune/crates/rune/src/input/cursor/image.rs new file mode 100644 index 0000000..8cb11b7 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/input/cursor/image.rs @@ -0,0 +1,139 @@ +//! [`Cursor::Image`](crate::Cursor::Image) pixels for the OS: decoding, scaling, and a bounded +//! cache of the OS cursors made from them. On web the browser decodes and scales the PNG +//! itself, from the CSS [`css`] writes. + +use crate::cursor::CursorImage; + +/// Pixels per point in a [`CursorImage`] PNG. +pub(crate) const SOURCE_SCALE: f32 = 2.0; +/// The largest side a cursor PNG may have, in pixels. +const MAX_SIDE: u32 = 256; +pub(crate) const MAX_ENTRIES: usize = 32; +#[cfg(not(target_arch = "wasm32"))] +const MAX_BYTES: usize = 8 << 20; + +/// A PNG's size in pixels, read from its header. +#[cfg(any(target_arch = "wasm32", test))] +fn png_size(bytes: &[u8]) -> Option<[u32; 2]> { + let header = bytes.get(..24)?; + let side = |at: usize| u32::from_be_bytes(header[at..at + 4].try_into().unwrap()); + (header[..8] == *b"\x89PNG\r\n\x1a\n" && header[12..16] == *b"IHDR").then(|| [side(16), side(20)]) +} + +/// The CSS `cursor` value for `image` loaded from `url`: the PNG at its 2x, so the browser draws +/// it at its size in points on any display, with the hot spot clamped into it in CSS pixels. +#[cfg(any(target_arch = "wasm32", test))] +pub(crate) fn css(image: CursorImage, url: &str) -> Result<String, String> { + let [w, h] = png_size(image.bytes()).ok_or("not a PNG")?; + if w > MAX_SIDE || h > MAX_SIDE || w == 0 || h == 0 { + return Err(format!("{w}×{h} px is empty or over the {MAX_SIDE} px limit")); + } + let [x, y] = [(image.hot()[0], w), (image.hot()[1], h)] + .map(|(p, side)| (p.floor().max(0.0) as u32).min((side as f32 / SOURCE_SCALE).ceil() as u32 - 1)); + Ok(format!("image-set(url(\"{url}\") {SOURCE_SCALE}x) {x} {y}, auto")) +} + +/// A cursor image at `scale` pixels per point: straight-alpha RGBA, hot spot in pixels. +#[cfg(not(target_arch = "wasm32"))] +pub(crate) struct Decoded { + pub rgba: Vec<u8>, + pub width: u32, + pub height: u32, + pub hot: [u32; 2], + #[cfg_attr(not(target_os = "macos"), allow(dead_code))] + pub scale: f32, +} + +/// Decodes `image` and resamples it to `scale` pixels per point (the OS cursor's own scale), +/// clamping its hot spot into the result. +#[cfg(not(target_arch = "wasm32"))] +pub(crate) fn decode(image: CursorImage, scale: f32) -> Result<Decoded, String> { + let src = crate::image::png_rgba8(image.bytes()).map_err(|e| e.to_string())?; + let (w, h) = src.dimensions(); + if w > MAX_SIDE || h > MAX_SIDE { + return Err(format!("{w}×{h} px is over the {MAX_SIDE} px limit")); + } + let scale = if scale.is_finite() && scale > 0.0 { scale } else { SOURCE_SCALE }; + let k = scale / SOURCE_SCALE; + let (width, height) = (((w as f32 * k).round() as u32).max(1), ((h as f32 * k).round() as u32).max(1)); + let rgba = match ((width, height) == (w, h), image.crisp()) { + (true, _) => src.into_raw(), + (false, true) => ::image::imageops::resize(&src, width, height, ::image::imageops::FilterType::Nearest).into_raw(), + (false, false) => resample(src, width, height), + }; + let hot = [(image.hot()[0], width), (image.hot()[1], height)].map(|(p, side)| ((p * scale).floor().max(0.0) as u32).min(side - 1)); + Ok(Decoded { rgba, width, height, hot, scale }) +} + +/// Resizes in premultiplied alpha, so transparent pixels' colour doesn't bleed into edges. +#[cfg(not(target_arch = "wasm32"))] +fn resample(mut src: ::image::RgbaImage, width: u32, height: u32) -> Vec<u8> { + for p in src.pixels_mut() { + let a = p[3] as u32; + for c in &mut p.0[..3] { *c = ((*c as u32 * a + 127) / 255) as u8; } + } + let mut out = ::image::imageops::resize(&src, width, height, ::image::imageops::FilterType::Triangle); + for p in out.pixels_mut() { + let a = p[3] as u32; + for c in &mut p.0[..3] { *c = if a == 0 { 0 } else { ((*c as u32 * 255 + a / 2) / a).min(255) as u8 }; } + } + out.into_raw() +} + +#[cfg(not(target_arch = "wasm32"))] +struct Entry<T> { + key: (CursorImage, u32), + /// `None` when the image didn't decode or the OS refused it: the arrow shows. + cursor: Option<T>, + bytes: usize, +} + +/// OS cursors made from cursor images, oldest first, bounded in entries and decoded bytes. +/// A failure is kept too, so it's decoded and logged once. +#[cfg(not(target_arch = "wasm32"))] +pub(crate) struct ImageCursors<T> { + entries: Vec<Entry<T>>, + bytes: usize, + pub decodes: usize, +} + +#[cfg(not(target_arch = "wasm32"))] +impl<T: Clone> ImageCursors<T> { + pub const fn new() -> Self { + ImageCursors { entries: Vec::new(), bytes: 0, decodes: 0 } + } + + /// `Some` once `image` at `scale` has been made: its cursor, or `None` if it failed. + pub fn cached(&mut self, image: CursorImage, scale: f32) -> Option<Option<T>> { + let key = (image, scale.to_bits()); + let i = self.entries.iter().position(|e| e.key == key)?; + let entry = self.entries.remove(i); + let cursor = entry.cursor.clone(); + self.entries.push(entry); + Some(cursor) + } + + /// The OS cursor for `image` at `scale`, decoded and handed to `make` the first time. + pub fn get(&mut self, image: CursorImage, scale: f32, make: impl FnOnce(&Decoded) -> Result<T, String>) -> Option<T> { + if let Some(cursor) = self.cached(image, scale) { return cursor; } + self.decodes += 1; + let made = decode(image, scale).and_then(|d| make(&d).map(|cursor| (cursor, d.rgba.len()))); + let (cursor, bytes) = match made { + Ok((cursor, bytes)) => (Some(cursor), bytes), + Err(problem) => { + eprintln!("rune: cursor image ({} bytes) shows the arrow instead: {problem}", image.bytes().len()); + (None, 0) + } + }; + self.bytes += bytes; + self.entries.push(Entry { key: (image, scale.to_bits()), cursor: cursor.clone(), bytes }); + while self.entries.len() > 1 && (self.entries.len() > MAX_ENTRIES || self.bytes > MAX_BYTES) { + self.bytes -= self.entries.remove(0).bytes; + } + cursor + } +} + +#[cfg(test)] +#[path = "image_tests.rs"] +mod tests; diff --git a/app/vendor/rune/crates/rune/src/input/cursor/image_tests.rs b/app/vendor/rune/crates/rune/src/input/cursor/image_tests.rs new file mode 100644 index 0000000..f03a57d --- /dev/null +++ b/app/vendor/rune/crates/rune/src/input/cursor/image_tests.rs @@ -0,0 +1,156 @@ +use super::*; +use crate::{Cursor, Cx, El, Env, Runtime, el}; + +/// A `w`×`h` px PNG, opaque red with a transparent left column. +fn png(w: u32, h: u32) -> &'static [u8] { + let img = ::image::RgbaImage::from_fn(w, h, |x, _| if x == 0 { ::image::Rgba([0, 0, 255, 0]) } else { ::image::Rgba([255, 0, 0, 255]) }); + let mut out = std::io::Cursor::new(Vec::new()); + img.write_to(&mut out, ::image::ImageFormat::Png).unwrap(); + Box::leak(out.into_inner().into_boxed_slice()) +} + +#[test] +fn an_element_resolves_to_its_image_cursor_and_its_children_inherit_it() { + static PENCIL: std::sync::LazyLock<CursorImage> = std::sync::LazyLock::new(|| CursorImage::png(png(64, 64), [2.0, 30.0])); + fn view(_: &(), _: &mut Cx<()>) -> El { + el().size(200.0, 200.0) + .child(el().key("canvas").size(200.0, 100.0).cursor(Cursor::Image(*PENCIL)).on_press(|_: &mut ()| {}) + .child(el().key("swatch").size(40.0, 40.0))) + } + let mut rt = Runtime::new((), view, (200.0, 200.0), Env::new(true, 2.0)); + rt.frame(0.0); + rt.pointer_move(100.0, 50.0); + assert_eq!(rt.cursor(), Cursor::Image(*PENCIL)); + rt.pointer_move(20.0, 20.0); + assert_eq!(rt.cursor(), Cursor::Image(*PENCIL), "inherited"); + rt.pointer_down(100.0, 50.0); + rt.pointer_move(100.0, 150.0); + assert_eq!(rt.cursor(), Cursor::Image(*PENCIL), "a held press keeps it"); + rt.pointer_up(100.0, 150.0); + assert_eq!(rt.cursor(), Cursor::Default); +} + +#[test] +fn images_are_equal_by_bytes_and_hot_spot() { + static A: [u8; 8] = [1, 2, 3, 4, 5, 6, 7, 8]; + static B: [u8; 8] = [1, 2, 3, 4, 5, 6, 7, 8]; + static C: [u8; 8] = [1, 2, 3, 4, 5, 6, 7, 9]; + let a = CursorImage::png(&A, [1.0, 2.0]); + assert_eq!(a, CursorImage::png(&A, [1.0, 2.0])); + assert_eq!(Cursor::Image(a), Cursor::Image(CursorImage::png(&A, [1.0, 2.0]))); + assert_eq!(a, CursorImage::png(&B, [1.0, 2.0]), "the same bytes elsewhere (a const copied at each use)"); + assert_ne!(a, CursorImage::png(&C, [1.0, 2.0])); + assert_ne!(a, CursorImage::png(&A[..7], [1.0, 2.0])); + assert_ne!(a, CursorImage::png(&A, [1.0, 2.5]), "another hot spot is another cursor"); + use std::hash::BuildHasher; + let state = std::hash::RandomState::new(); + assert_eq!(state.hash_one(a), state.hash_one(CursorImage::png(&B, [1.0, 2.0]))); + assert_eq!(format!("{a:?}"), "CursorImage { png_bytes: 8, hot: [1.0, 2.0] }"); +} + +#[test] +fn the_cache_decodes_each_image_once_per_scale() { + let image = CursorImage::png(png(32, 32), [4.0, 4.0]); + let mut cache = ImageCursors::<u32>::new(); + let mut made = 0; + for _ in 0..3 { + assert_eq!(cache.get(image, 2.0, |d| { made += 1; Ok(d.width) }), Some(32)); + } + assert_eq!((cache.decodes, made), (1, 1), "hit, not decoded again"); + let copy: &'static [u8] = Box::leak(image.bytes().to_vec().into_boxed_slice()); + assert_eq!(cache.get(CursorImage::png(copy, [4.0, 4.0]), 2.0, |_| Ok(0)), Some(32), "a copy of the bytes hits too"); + assert_eq!(cache.decodes, 1); + assert_eq!(cache.get(image, 1.0, |d| Ok(d.width)), Some(16), "another display's scale is another cursor"); + assert_eq!(cache.decodes, 2); + assert_eq!(cache.cached(image, 2.0), Some(Some(32))); +} + +#[test] +fn the_cache_is_bounded_and_keeps_the_newest() { + let mut cache = ImageCursors::<usize>::new(); + let bytes = png(8, 8); + for i in 0..MAX_ENTRIES + 5 { + cache.get(CursorImage::png(bytes, [i as f32, 0.0]), 2.0, |_| Ok(i)); + } + assert_eq!(cache.entries.len(), MAX_ENTRIES); + assert_eq!(cache.cached(CursorImage::png(bytes, [0.0, 0.0]), 2.0), None, "the oldest went"); + let last = MAX_ENTRIES + 4; + assert_eq!(cache.cached(CursorImage::png(bytes, [last as f32, 0.0]), 2.0), Some(Some(last))); + assert!(cache.bytes <= MAX_BYTES); +} + +#[test] +fn the_hot_spot_is_clamped_into_the_image() { + let bytes = png(32, 20); + let hot = |p: [f32; 2], scale| decode(CursorImage::png(bytes, p), scale).unwrap().hot; + assert_eq!(hot([3.5, 2.0], 2.0), [7, 4], "points at 2x"); + assert_eq!(hot([3.5, 2.0], 1.0), [3, 2], "and at 1x"); + assert_eq!(hot([100.0, -5.0], 2.0), [31, 0]); + assert_eq!(hot([f32::NAN, f32::INFINITY], 2.0), [0, 19]); + assert_eq!(hot([16.0, 10.0], 1.0), [15, 9], "the far edge is just outside a 16×10 px image"); +} + +#[test] +fn decoding_scales_to_the_display_and_keeps_edges_clean() { + let d = decode(CursorImage::png(png(32, 20), [0.0, 0.0]), 1.0).unwrap(); + assert_eq!((d.width, d.height, d.rgba.len()), (16, 10, 16 * 10 * 4)); + let edge = &d.rgba[..4]; + assert_eq!(edge[2], 0, "no blue from the transparent column bleeds in: {edge:?}"); + let d = decode(CursorImage::png(png(32, 20), [0.0, 0.0]), 3.0).unwrap(); + assert_eq!((d.width, d.height), (48, 30)); +} + +#[test] +fn a_bad_png_falls_back_to_the_arrow_once() { + static NOT_PNG: &[u8] = b"not a png"; + let image = CursorImage::png(NOT_PNG, [0.0, 0.0]); + let mut cache = ImageCursors::<()>::new(); + let mut made = false; + assert_eq!(cache.get(image, 2.0, |_| { made = true; Ok(()) }), None); + assert!(!made); + assert_eq!(cache.get(image, 2.0, |_| Ok(())), None); + assert_eq!(cache.decodes, 1, "remembered, so decoded and logged once"); + assert_eq!(cache.cached(image, 2.0), Some(None)); + assert!(decode(CursorImage::png(png(300, 8), [0.0, 0.0]), 2.0).is_err(), "too big"); + let refused = CursorImage::png(png(8, 8), [0.0, 0.0]); + assert_eq!(cache.get(refused, 2.0, |_| Err::<(), _>("the OS refused it".into())), None); +} + +#[test] +fn web_css_names_the_png_at_2x_with_the_hot_spot_in_points() { + let css = |bytes, hot| super::css(CursorImage::png(bytes, hot), "blob:x"); + assert_eq!(css(png(64, 40), [2.0, 30.0]).unwrap(), r#"image-set(url("blob:x") 2x) 2 19, auto"#, "clamped into the 20 pt height"); + assert_eq!(css(png(64, 40), [3.7, f32::NAN]).unwrap(), r#"image-set(url("blob:x") 2x) 3 0, auto"#); + assert_eq!(css(png(5, 5), [9.0, 9.0]).unwrap(), r#"image-set(url("blob:x") 2x) 2 2, auto"#, "an odd side rounds up"); + assert!(css(png(300, 8), [0.0, 0.0]).is_err(), "too big"); + assert!(css(&b"not a png at all, just some text"[..], [0.0, 0.0]).is_err()); + assert!(css(&png(8, 8)[..20], [0.0, 0.0]).is_err(), "cut short"); +} + +/// The NSCursor `Cursor::Image` sets: its image is sized in points with the PNG's pixels as +/// its bitmap, and its hot spot is in points. +#[cfg(target_os = "macos")] +#[test] +#[allow(unsafe_code)] +fn a_macos_image_cursor_is_sized_in_points() { + use objc2::rc::Retained; + use objc2::runtime::AnyObject; + use objc2::msg_send; + use objc2_foundation::{NSPoint, NSSize}; + let d = decode(CursorImage::png(png(64, 40), [2.0, 30.0]), SOURCE_SCALE).unwrap(); + let cursor = crate::platform::macos::cursor::ns_cursor(&d).unwrap(); + // SAFETY: reading back AppKit objects made above. + let (size, hot, pixels) = unsafe { + let image: Retained<AnyObject> = msg_send![&*cursor, image]; + let size: NSSize = msg_send![&*image, size]; + let hot: NSPoint = msg_send![&*cursor, hotSpot]; + let reps: Retained<AnyObject> = msg_send![&*image, representations]; + let rep: Retained<AnyObject> = msg_send![&*reps, firstObject]; + let (w, h): (isize, isize) = (msg_send![&*rep, pixelsWide], msg_send![&*rep, pixelsHigh]); + (size, hot, (w, h)) + }; + println!("NSCursor image {}×{} pt, bitmap {}×{} px, hot spot ({}, {}) pt", size.width, size.height, pixels.0, pixels.1, hot.x, hot.y); + assert_eq!((size.width, size.height), (32.0, 20.0), "points, not pixels"); + assert_eq!(pixels, (64, 40), "the 2x pixels stay"); + assert_eq!((hot.x, hot.y), (2.0, 19.5), "the hot spot in points, clamped into the 20 pt height"); +} diff --git a/app/vendor/rune/crates/rune/src/input/cursor/os.rs b/app/vendor/rune/crates/rune/src/input/cursor/os.rs new file mode 100644 index 0000000..8e564e6 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/input/cursor/os.rs @@ -0,0 +1,281 @@ +//! The OS cursor a winit host last applied. +//! +//! `Cursor::Hidden` sets a transparent cursor image rather than winit's +//! `set_cursor_visible(false)`: on Windows that call also confines the pointer to the centre of +//! a focused window, and its `ShowCursor` count is process-wide. A cursor image is per-window +//! like any other shape, so the OS drops it when the pointer leaves the window or the window +//! goes away. +//! +//! `Cursor::Image` goes through winit's custom cursors, made at the window's scale so the +//! image keeps its size in points. winit makes those only with the event loop at hand, so a +//! window's first use of an image waits for [`make_pending`] before the loop sleeps. On macOS +//! winit would size the image in pixels, twice too big on Retina, so `macos_cursor` sets it. +//! With the window's cursor rects off, nothing in AppKit puts the image back once the system +//! shows another cursor (a window coming or going over the pointer, another app's click-through +//! overlay), so while it holds the pointer the host sets it again every [`REASSERT`], frame or +//! no frame. On web the canvas's CSS names the PNG itself (`cursor/web.rs`). + +use std::sync::Arc; +use std::time::Duration; + +use crate::time::Instant; + +use winit::event_loop::ActiveEventLoop; +use winit::window::{CursorIcon, Window}; + +use crate::el::Cursor; + +/// How often an image cursor is set again while it holds the pointer and nothing redraws. +pub(crate) const REASSERT: Duration = Duration::from_millis(50); + +pub(crate) struct OsCursor { + applied: (bool, Cursor), + /// The scale an image cursor was last made at: a window moving to a display with another + /// scale makes it again. + scale: f32, +} + +impl OsCursor { + pub(crate) fn new() -> Self { + OsCursor { applied: (false, Cursor::Default), scale: 0.0 } + } + + /// Applies `want` while the host is `active` (the pointer is over its window or its hit + /// area), and the arrow once when it stops being active. winit sets some cursors at once + /// (Win32 `SetCursor`), so an inactive host must leave the cursor to whichever window has + /// the pointer. + pub(crate) fn apply(&mut self, window: &Arc<Window>, want: Cursor, active: bool) { + let scale = image_scale(window); + let rescaled = active && os_image(want).is_some() && std::mem::replace(&mut self.scale, scale) != scale; + let Some(next) = next(&mut self.applied, want, active).or(rescaled.then_some(want)) else { + self.reassert(); + return; + }; + #[cfg(target_os = "macos")] + let Some(next) = crate::platform::macos::cursor::window_cursor(window, next) else { return }; + #[cfg(not(target_os = "macos"))] + images::forget(window); + clear::forget(window); + match next { + Cursor::Hidden => clear::set(window), + #[cfg(not(target_os = "macos"))] + Cursor::Image(image) => images::set(window, image, scale), + #[cfg(windows)] + Cursor::Cell => images::set(window, crate::cursor::CELL, scale), + other => window.set_cursor(icon(other)), + } + } + + /// When to set the image cursor again: while one holds the pointer, on macOS. + pub(crate) fn reassert_at(&self, now: Instant) -> Option<Instant> { + (cfg!(target_os = "macos") && holds_image(self.applied)).then(|| now + REASSERT) + } + + /// Sets the image cursor again, if one holds the pointer. + pub(crate) fn reassert(&self) { + #[cfg(target_os = "macos")] + if let (true, Cursor::Image(image)) = self.applied { crate::platform::macos::cursor::reassert(image); } + } +} + +/// The 1×1 clear cursor `Cursor::Hidden` sets, one per thread, made the first time a window +/// hides the cursor, before the loop sleeps (`make_pending`): making it takes ~1,000 µs, too +/// long for every window's creation. On web it is kept for the page's life: winit makes a custom +/// cursor asynchronously, and dropping one before it's ready leaves the browser calling a freed +/// closure, as a web app unmounted just after it mounts would. +mod clear { + use std::cell::{OnceCell, RefCell}; + use std::sync::{Arc, Weak}; + + use winit::event_loop::ActiveEventLoop; + use winit::window::{CustomCursor, Window}; + + thread_local! { + static CLEAR: OnceCell<CustomCursor> = const { OnceCell::new() }; + static PENDING: RefCell<Vec<Weak<Window>>> = const { RefCell::new(Vec::new()) }; + } + + pub(super) fn set(window: &Arc<Window>) { + match CLEAR.with(|c| c.get().cloned()) { + Some(clear) => window.set_cursor(clear), + None => PENDING.with(|p| p.borrow_mut().push(Arc::downgrade(window))), + } + } + + /// Drops a hide `window` asked for and no longer wants. + pub(super) fn forget(window: &Arc<Window>) { + PENDING.with(|p| p.borrow_mut().retain(|w| !std::ptr::eq(w.as_ptr(), Arc::as_ptr(window)))); + } + + pub(super) fn make_pending(event_loop: &ActiveEventLoop) { + let waiting = PENDING.with(|p| std::mem::take(&mut *p.borrow_mut())); + if waiting.is_empty() { return; } + let clear = CLEAR.with(|c| c.get_or_init(|| { + let source = CustomCursor::from_rgba(vec![0u8; 4], 1, 1, 0, 0).expect("a 1x1 cursor image is valid"); + event_loop.create_custom_cursor(source) + }).clone()); + for window in waiting.iter().filter_map(Weak::upgrade) { window.set_cursor(clear.clone()); } + } +} + +/// The image the OS cursor for `c` is made from, if it's one: an app's, or one the OS lacks. +fn os_image(c: Cursor) -> Option<crate::cursor::CursorImage> { + match c { + Cursor::Image(image) => Some(image), + #[cfg(windows)] + Cursor::Cell => Some(crate::cursor::CELL), + _ => None, + } +} + +fn holds_image(applied: (bool, Cursor)) -> bool { + matches!(applied, (true, Cursor::Image(_))) +} + +/// Pixels per point in the OS cursors made for `window`. +fn image_scale(window: &Window) -> f32 { + if cfg!(any(target_os = "macos", target_arch = "wasm32")) { crate::cursor::image::SOURCE_SCALE } else { window.scale_factor() as f32 } +} + +/// Makes the image cursors windows asked for since the loop last slept, and sets them. +pub(crate) fn make_pending(event_loop: &ActiveEventLoop) { + #[cfg(not(target_os = "macos"))] + images::make_pending(event_loop); + clear::make_pending(event_loop); +} + +#[cfg(target_arch = "wasm32")] +#[path = "web.rs"] +mod images; + +#[cfg(not(any(target_os = "macos", target_arch = "wasm32")))] +mod images { + use std::cell::RefCell; + use std::sync::{Arc, Weak}; + + use winit::event_loop::ActiveEventLoop; + use winit::window::{CursorIcon, CustomCursor, Window}; + + use crate::cursor::CursorImage; + use crate::cursor::image::ImageCursors; + + thread_local! { + static CURSORS: RefCell<ImageCursors<CustomCursor>> = const { RefCell::new(ImageCursors::new()) }; + static PENDING: RefCell<Vec<(Weak<Window>, CursorImage, f32)>> = const { RefCell::new(Vec::new()) }; + } + + pub(super) fn set(window: &Arc<Window>, image: CursorImage, scale: f32) { + match CURSORS.with(|c| c.borrow_mut().cached(image, scale)) { + Some(Some(cursor)) => window.set_cursor(cursor), + Some(None) => window.set_cursor(CursorIcon::Default), + None => PENDING.with(|p| p.borrow_mut().push((Arc::downgrade(window), image, scale))), + } + } + + /// Drops a cursor `window` asked for and no longer wants. + pub(super) fn forget(window: &Arc<Window>) { + PENDING.with(|p| p.borrow_mut().retain(|(w, ..)| !std::ptr::eq(w.as_ptr(), Arc::as_ptr(window)))); + } + + pub(super) fn make_pending(event_loop: &ActiveEventLoop) { + for (window, image, scale) in PENDING.with(|p| std::mem::take(&mut *p.borrow_mut())) { + let Some(window) = window.upgrade() else { continue }; + let cursor = CURSORS.with(|c| c.borrow_mut().get(image, scale, |d| { + let side = |n: u32| u16::try_from(n).map_err(|_| format!("{n} px is too big")); + let source = CustomCursor::from_rgba(d.rgba.clone(), side(d.width)?, side(d.height)?, d.hot[0] as u16, d.hot[1] as u16) + .map_err(|e| e.to_string())?; + Ok(event_loop.create_custom_cursor(source)) + })); + match cursor { + Some(cursor) => window.set_cursor(cursor), + None => window.set_cursor(CursorIcon::Default), + } + } + } +} + +/// The cursor to set, if the (active, cursor) pair changed and the host owns the cursor or +/// just gave it up. +fn next(applied: &mut (bool, Cursor), want: Cursor, active: bool) -> Option<Cursor> { + let want = if active { want } else { Cursor::Default }; + let was = std::mem::replace(applied, (active, want)); + (was != (active, want) && (active || was.0)).then_some(want) +} + +/// winit's shape for `c`. An image that never became an OS cursor is the arrow. +fn icon(c: Cursor) -> CursorIcon { + match c { + Cursor::Default | Cursor::Hidden | Cursor::Image(_) => CursorIcon::Default, + Cursor::Pointer => CursorIcon::Pointer, + Cursor::Text => CursorIcon::Text, + Cursor::Grab => CursorIcon::Grab, + Cursor::Grabbing => CursorIcon::Grabbing, + Cursor::NotAllowed => CursorIcon::NotAllowed, + Cursor::Move => CursorIcon::Move, + Cursor::ResizeColumn => CursorIcon::ColResize, + Cursor::ResizeRow => CursorIcon::RowResize, + Cursor::Crosshair => CursorIcon::Crosshair, + Cursor::Cell => CursorIcon::Cell, + Cursor::ZoomIn => CursorIcon::ZoomIn, + Cursor::ZoomOut => CursorIcon::ZoomOut, + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_host_sets_its_cursor_while_active_and_the_arrow_once_when_it_stops() { + let mut applied = (false, Cursor::Default); + assert_eq!(next(&mut applied, Cursor::Crosshair, false), None, "never while inactive"); + assert_eq!(next(&mut applied, Cursor::Crosshair, true), Some(Cursor::Crosshair)); + assert_eq!(next(&mut applied, Cursor::Hidden, true), Some(Cursor::Hidden)); + assert_eq!(next(&mut applied, Cursor::Hidden, true), None); + assert_eq!(next(&mut applied, Cursor::Hidden, false), Some(Cursor::Default), "the arrow once on leaving"); + assert_eq!(next(&mut applied, Cursor::Hidden, false), None, "then another window's cursor stays"); + assert_eq!(next(&mut applied, Cursor::Pointer, false), None); + assert_eq!(next(&mut applied, Cursor::Default, true), Some(Cursor::Default), "entering claims the cursor"); + assert_eq!(next(&mut applied, Cursor::Default, true), None); + } + + #[test] + fn only_an_image_holding_the_pointer_is_set_again() { + static PNG: [u8; 4] = [1, 2, 3, 4]; + let image = Cursor::Image(crate::cursor::CursorImage::png(&PNG, [0.0, 0.0])); + let mut applied = (false, Cursor::Default); + next(&mut applied, image, true); + assert!(holds_image(applied)); + next(&mut applied, image, false); + assert!(!holds_image(applied), "not once the pointer leaves"); + next(&mut applied, Cursor::Crosshair, true); + assert!(!holds_image(applied), "nor for a system shape, which the window's cursor rects keep"); + } + + #[test] + fn every_cursor_variant_maps_explicitly_for_macos() { + use crate::cursor::{MacCursor, mac_cursor}; + static PNG: [u8; 4] = [1, 2, 3, 4]; + let image = crate::cursor::CursorImage::png(&PNG, [0.0, 0.0]); + let pairs = [ + (Cursor::Default, MacCursor::Arrow), + (Cursor::Pointer, MacCursor::PointingHand), + (Cursor::Text, MacCursor::IBeam), + (Cursor::Grab, MacCursor::OpenHand), + (Cursor::Grabbing, MacCursor::ClosedHand), + (Cursor::NotAllowed, MacCursor::NotAllowed), + (Cursor::ResizeColumn, MacCursor::ResizeLeftRight), + (Cursor::ResizeRow, MacCursor::ResizeUpDown), + (Cursor::Crosshair, MacCursor::Crosshair), + (Cursor::ZoomIn, MacCursor::ZoomIn), + (Cursor::ZoomOut, MacCursor::ZoomOut), + (Cursor::Hidden, MacCursor::Transparent), + (Cursor::Move, MacCursor::MoveImage), + (Cursor::Cell, MacCursor::CellImage), + (Cursor::Image(image), MacCursor::Custom(image)), + ]; + for (cursor, expected) in pairs { + assert_eq!(mac_cursor(cursor), expected); + } + } +} diff --git a/app/vendor/rune/crates/rune/src/input/cursor/pan_east.png b/app/vendor/rune/crates/rune/src/input/cursor/pan_east.png new file mode 100644 index 0000000..8b85b0c Binary files /dev/null and b/app/vendor/rune/crates/rune/src/input/cursor/pan_east.png differ diff --git a/app/vendor/rune/crates/rune/src/input/cursor/pan_middle.png b/app/vendor/rune/crates/rune/src/input/cursor/pan_middle.png new file mode 100644 index 0000000..ff52476 Binary files /dev/null and b/app/vendor/rune/crates/rune/src/input/cursor/pan_middle.png differ diff --git a/app/vendor/rune/crates/rune/src/input/cursor/pan_middle_horizontal.png b/app/vendor/rune/crates/rune/src/input/cursor/pan_middle_horizontal.png new file mode 100644 index 0000000..c7d9a8f Binary files /dev/null and b/app/vendor/rune/crates/rune/src/input/cursor/pan_middle_horizontal.png differ diff --git a/app/vendor/rune/crates/rune/src/input/cursor/pan_middle_vertical.png b/app/vendor/rune/crates/rune/src/input/cursor/pan_middle_vertical.png new file mode 100644 index 0000000..d628608 Binary files /dev/null and b/app/vendor/rune/crates/rune/src/input/cursor/pan_middle_vertical.png differ diff --git a/app/vendor/rune/crates/rune/src/input/cursor/pan_north.png b/app/vendor/rune/crates/rune/src/input/cursor/pan_north.png new file mode 100644 index 0000000..5c1cffb Binary files /dev/null and b/app/vendor/rune/crates/rune/src/input/cursor/pan_north.png differ diff --git a/app/vendor/rune/crates/rune/src/input/cursor/pan_north_east.png b/app/vendor/rune/crates/rune/src/input/cursor/pan_north_east.png new file mode 100644 index 0000000..b70169a Binary files /dev/null and b/app/vendor/rune/crates/rune/src/input/cursor/pan_north_east.png differ diff --git a/app/vendor/rune/crates/rune/src/input/cursor/pan_north_west.png b/app/vendor/rune/crates/rune/src/input/cursor/pan_north_west.png new file mode 100644 index 0000000..a62410b Binary files /dev/null and b/app/vendor/rune/crates/rune/src/input/cursor/pan_north_west.png differ diff --git a/app/vendor/rune/crates/rune/src/input/cursor/pan_south.png b/app/vendor/rune/crates/rune/src/input/cursor/pan_south.png new file mode 100644 index 0000000..8bcce53 Binary files /dev/null and b/app/vendor/rune/crates/rune/src/input/cursor/pan_south.png differ diff --git a/app/vendor/rune/crates/rune/src/input/cursor/pan_south_east.png b/app/vendor/rune/crates/rune/src/input/cursor/pan_south_east.png new file mode 100644 index 0000000..c275ba6 Binary files /dev/null and b/app/vendor/rune/crates/rune/src/input/cursor/pan_south_east.png differ diff --git a/app/vendor/rune/crates/rune/src/input/cursor/pan_south_west.png b/app/vendor/rune/crates/rune/src/input/cursor/pan_south_west.png new file mode 100644 index 0000000..a922863 Binary files /dev/null and b/app/vendor/rune/crates/rune/src/input/cursor/pan_south_west.png differ diff --git a/app/vendor/rune/crates/rune/src/input/cursor/pan_west.png b/app/vendor/rune/crates/rune/src/input/cursor/pan_west.png new file mode 100644 index 0000000..a8b60bc Binary files /dev/null and b/app/vendor/rune/crates/rune/src/input/cursor/pan_west.png differ diff --git a/app/vendor/rune/crates/rune/src/input/cursor/web.rs b/app/vendor/rune/crates/rune/src/input/cursor/web.rs new file mode 100644 index 0000000..a1aed07 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/input/cursor/web.rs @@ -0,0 +1,61 @@ +//! `Cursor::Image` on web: the canvas's CSS cursor names the PNG itself at 2x, so the browser +//! decodes it and draws it at its size in points, and the wasm build carries no PNG decoder for +//! cursors. winit's custom cursors would need the pixels and draw them in CSS pixels, twice too +//! big on a 2x display. +//! +//! winit holds the arrow while Rune's CSS shows, so it has no cursor of its own to put back over +//! it, and [`forget`] clears the CSS before winit sets the next shape. + +use std::cell::RefCell; +use std::sync::Arc; + +use winit::event_loop::ActiveEventLoop; +use winit::platform::web::WindowExtWebSys; +use winit::window::{CursorIcon, Window}; + +use crate::cursor::CursorImage; +use crate::cursor::image::{MAX_ENTRIES, css}; +use crate::platform::web::platform::{object_url, revoke_url, set_cursor}; + +thread_local! { + /// The CSS for each image set so far, oldest first, with the object URL it holds; `None` for + /// an image that isn't a PNG Rune takes, logged once. + static MADE: RefCell<Vec<(CursorImage, Option<(String, String)>)>> = const { RefCell::new(Vec::new()) }; +} + +pub(super) fn set(window: &Arc<Window>, image: CursorImage, _scale: f32) { + window.set_cursor(CursorIcon::Default); + let Some(canvas) = window.canvas() else { return }; + if let Some(css) = made(image) { set_cursor(&canvas, &css); } +} + +pub(super) fn forget(window: &Arc<Window>) { + if let Some(canvas) = window.canvas() { set_cursor(&canvas, ""); } +} + +pub(super) fn make_pending(_: &ActiveEventLoop) {} + +fn made(image: CursorImage) -> Option<String> { + MADE.with(|made| { + let mut made = made.borrow_mut(); + let entry = match made.iter().position(|(key, _)| *key == image) { + Some(i) => made.remove(i), + None => { + let url = object_url(image.bytes(), "image/png"); + let entry = match css(image, &url) { + Ok(css) => Some((css, url)), + Err(problem) => { + revoke_url(&url); + eprintln!("rune: cursor image ({} bytes) shows the arrow instead: {problem}", image.bytes().len()); + None + } + }; + (image, entry) + } + }; + let css = entry.1.as_ref().map(|(css, _)| css.clone()); + made.push(entry); + if made.len() > MAX_ENTRIES && let (_, Some((_, url))) = made.remove(0) { revoke_url(&url); } + css + }) +} diff --git a/app/vendor/rune/crates/rune/src/input/drop_pointer.rs b/app/vendor/rune/crates/rune/src/input/drop_pointer.rs new file mode 100644 index 0000000..4751c63 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/input/drop_pointer.rs @@ -0,0 +1,69 @@ +//! Where a file drag from another app is over a window. winit 0.30 reports file drags without +//! a position on every platform (macOS has no `draggingUpdated:`, and Windows and X11 drop +//! the point they're given), and no pointer moves arrive while the drag lasts. The host +//! samples the system pointer instead, when the drag enters, each frame while it's over the +//! window, and when it drops. +use winit::window::Window; + +#[derive(Default)] +pub(crate) struct DropPointer { + /// A connection kept for the drag, so sampling 60 times a second doesn't reconnect. + #[cfg(all(unix, not(target_os = "macos"), not(target_os = "ios"), not(target_os = "android")))] + x11: Option<(x11rb::rust_connection::RustConnection, u32)>, +} + +impl DropPointer { + pub(crate) fn new() -> Self { + #[cfg(all(unix, not(target_os = "macos"), not(target_os = "ios"), not(target_os = "android")))] + return Self { + x11: x11rb::connect(None).ok().and_then(|(c, screen)| { + use x11rb::connection::Connection as _; + let root = c.setup().roots.get(screen)?.root; + Some((c, root)) + }), + }; + #[allow(unreachable_code)] + Self::default() + } + + /// The pointer over `window`'s content, in the points of a view zoomed `zoom` times + /// (`Cx::zoom`) from its top-left, when the platform can say. + pub(crate) fn sample(&self, window: &Window, zoom: f32) -> Option<(f32, f32)> { + self.sample_window(window).map(|(x, y)| (x / zoom, y / zoom)) + } + + /// The pointer over `window`'s content, in window points. + fn sample_window(&self, window: &Window) -> Option<(f32, f32)> { + #[cfg(target_os = "macos")] + { + let view = crate::platform::macos::content_view(window)?; + let ns = view.window()?; + let p = view.convertPoint_fromView(ns.mouseLocationOutsideOfEventStream(), None); + let y = if view.isFlipped() { p.y } else { view.bounds().size.height - p.y }; + return Some((p.x as f32, y as f32)); + } + #[cfg(target_os = "windows")] + { + let (x, y) = crate::platform::win32::pointer_position()?; + return screen_to_window(window, (x, y)); + } + #[cfg(all(unix, not(target_os = "macos"), not(target_os = "ios"), not(target_os = "android")))] + { + use x11rb::protocol::xproto::ConnectionExt as _; + let (c, root) = self.x11.as_ref()?; + let p = c.query_pointer(*root).ok()?.reply().ok()?; + return p.same_screen.then(|| screen_to_window(window, (i32::from(p.root_x), i32::from(p.root_y)))).flatten(); + } + #[allow(unreachable_code)] + { let _ = window; None } + } +} + +/// A screen point in physical pixels, in `window`'s content in points. `None` when the window +/// can't say where it is (Wayland, including an X11 connection under XWayland). +#[cfg(any(target_os = "windows", all(unix, not(target_os = "macos"), not(target_os = "ios"), not(target_os = "android"))))] +fn screen_to_window(window: &Window, (x, y): (i32, i32)) -> Option<(f32, f32)> { + let origin = window.inner_position().ok()?; + let scale = window.scale_factor() as f32; + Some(((x - origin.x) as f32 / scale, (y - origin.y) as f32 / scale)) +} diff --git a/app/vendor/rune/crates/rune/src/input/fn_key.rs b/app/vendor/rune/crates/rune/src/input/fn_key.rs new file mode 100644 index 0000000..61532a5 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/input/fn_key.rs @@ -0,0 +1,58 @@ +//! The Fn (Globe) key on macOS, for `Key::Modifier`. winit sends no event for it: its +//! flagsChanged handler makes key events only for Shift, Control, Option and Command, and +//! `ModifiersState` has no Fn flag. A local event monitor sees the flagsChanged AppKit sends +//! the key window, and the host feeds it to the runtime as `PhysicalKeyCode::Fn`. + +#![allow(unsafe_code)] + +use objc2::rc::Retained; +use objc2::{ClassType, msg_send}; +use objc2_app_kit::{NSEvent, NSView, NSWindow}; +use objc2_foundation::NSObject; +use std::{cell::RefCell, rc::Rc}; + +const FLAGS_CHANGED: usize = 1 << 12; +const KEY_CODE_FN: u16 = 0x3f; +const FLAG_FUNCTION: usize = 1 << 23; + +pub(crate) struct FnKey { + token: Retained<NSObject>, + /// Fn going down (true) or up, oldest first, since the last `take`. + changes: Rc<RefCell<Vec<bool>>>, +} + +impl FnKey { + /// Watch Fn in the window showing winit's content view, which is the panel once one + /// adopts it. + pub(crate) fn new(window: &winit::window::Window) -> Option<Self> { + let view: Retained<NSView> = crate::platform::macos::content_view(window)?; + let changes = Rc::new(RefCell::new(Vec::new())); + let seen = changes.clone(); + let handler = block2::RcBlock::new(move |event: *mut NSEvent| -> *mut NSEvent { + // SAFETY: AppKit passes a live flagsChanged event on the main thread. + unsafe { + let code: u16 = msg_send![event, keyCode]; + let target: *mut NSWindow = msg_send![event, window]; + if code == KEY_CODE_FN && view.window().is_some_and(|w| Retained::as_ptr(&w).cast_mut() == target) { + let flags: usize = msg_send![event, modifierFlags]; + seen.borrow_mut().push(flags & FLAG_FUNCTION != 0); + } + } + event + }); + // SAFETY: the handler outlives the monitor, which `Drop` removes. + let token: Option<Retained<NSObject>> = unsafe { + msg_send![NSEvent::class(), addLocalMonitorForEventsMatchingMask: FLAGS_CHANGED, handler: &*handler] + }; + Some(Self { token: token?, changes }) + } + + pub(crate) fn take(&self) -> Vec<bool> { std::mem::take(&mut *self.changes.borrow_mut()) } +} + +impl Drop for FnKey { + fn drop(&mut self) { + // SAFETY: the token came from addLocalMonitorForEventsMatchingMask. + unsafe { let _: () = msg_send![NSEvent::class(), removeMonitor: &*self.token]; } + } +} diff --git a/app/vendor/rune/crates/rune/src/input/host_events.rs b/app/vendor/rune/crates/rune/src/input/host_events.rs new file mode 100644 index 0000000..7a9948b --- /dev/null +++ b/app/vendor/rune/crates/rune/src/input/host_events.rs @@ -0,0 +1,550 @@ +//! Shared event translation used by desktop windows (`window::host`), window-backed overlays +//! (`overlay`) and the web host (`platform::web`), so input units, modifiers, gestures, IME and +//! keyboard routing stay identical across hosts. Host-neutral `*_core` functions operate on plain +//! Rune values so both winit and DOM-bridge callers share one translation and unit tests run +//! natively. + +use std::ops::Range; + +use winit::dpi::{LogicalPosition, LogicalSize}; +use winit::event::{ElementState, Ime as WIme, MouseScrollDelta, TouchPhase}; +use winit::keyboard::{ModifiersState, PhysicalKey}; +use winit::window::Window; + +use crate::edit::Ime; +use crate::runtime::{AppDriver, RuntimeCore, Unhandled}; +use crate::window::{key_base, map_key_event, map_mods}; + +/// Host-neutral key input over plain Rune types. +pub(crate) struct KeyInput { + pub physical: Option<crate::PhysicalKeyCode>, + pub logical: Option<crate::KeyEvent>, + pub base: Option<char>, + pub mods: crate::Mods, + pub pressed: bool, + pub repeat: bool, + pub unhandled: Option<Unhandled>, +} + +/// Host-neutral wheel input in window points (before dividing by `rt.zoom()`). +#[derive(Clone, Copy, Debug)] +pub(crate) struct WheelInput { + pub dx: f32, + pub dy: f32, + pub mods: crate::Mods, + pub phase: crate::GesturePhase, + pub precise: bool, + pub notch: bool, + /// Whether Ctrl+wheel tries `pinch_wheel` before scrolling (true off macOS). + pub pinch: bool, +} + +/// How [`wheel_core`] handled a wheel input. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum WheelOutcome { + /// Delivered to an `on_magnify` handler via Ctrl+wheel pinch. + Pinched, + /// Delivered as a `WheelEvent` (or pointer-less phase boundary notification). + Scrolled, + /// No pointer and no pointer-less phase boundary to report. + Ignored, +} + +/// Host-neutral mouse button input at view point `(x, y)`. +#[derive(Clone, Copy, Debug)] +#[cfg_attr(not(any(target_arch = "wasm32", test)), allow(dead_code))] +pub(crate) struct MouseButtonInput { + pub x: f32, + pub y: f32, + pub button: crate::PointerButton, + pub pressed: bool, + pub mods: crate::Mods, + pub ctrl_click_is_secondary: bool, + pub queue_mods_on_primary_down: bool, +} + +/// Resolved mouse button action after macOS Ctrl+click mapping. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[cfg_attr(not(any(target_arch = "wasm32", test)), allow(dead_code))] +pub(crate) enum ButtonAction { + PrimaryDown, + PrimaryUp, + SecondaryDown, + SecondaryUp, + OtherDown(crate::PointerButton), + OtherUp(crate::PointerButton), +} + +/// Converts physical surface pixels into view points (dividing by `rt.input_scale()` = scale × zoom). +#[cfg_attr(not(any(target_arch = "wasm32", test)), allow(dead_code))] +pub(crate) fn physical_point(rt: &RuntimeCore, x: f64, y: f64) -> (f32, f32) { + let scale = rt.input_scale(); + (x as f32 / scale, y as f32 / scale) +} + +/// Converts logical window points (CSS pixels on web) into view points (dividing by `rt.zoom()`). +#[cfg_attr(not(any(target_arch = "wasm32", test)), allow(dead_code))] +pub(crate) fn window_point(rt: &RuntimeCore, x: f32, y: f32) -> (f32, f32) { + let zoom = rt.zoom(); + (x / zoom, y / zoom) +} + +/// Classifies a mouse button press/release, turning primary Ctrl+click into a secondary click +/// when `ctrl_click_is_secondary` is true (macOS) and pairing its release via `control_click`. +#[cfg_attr(not(any(target_arch = "wasm32", test)), allow(dead_code))] +pub(crate) fn mouse_button_action( + button: crate::PointerButton, + pressed: bool, + ctrl_held: bool, + ctrl_click_is_secondary: bool, + control_click: &mut bool, +) -> ButtonAction { + match button { + crate::PointerButton::Primary => { + if pressed { + *control_click = ctrl_click_is_secondary && ctrl_held; + } + let secondary = *control_click; + if !pressed { + *control_click = false; + } + match (pressed, secondary) { + (true, true) => ButtonAction::SecondaryDown, + (false, true) => ButtonAction::SecondaryUp, + (true, false) => ButtonAction::PrimaryDown, + (false, false) => ButtonAction::PrimaryUp, + } + } + crate::PointerButton::Secondary => { + if pressed { ButtonAction::SecondaryDown } else { ButtonAction::SecondaryUp } + } + other => { + if pressed { ButtonAction::OtherDown(other) } else { ButtonAction::OtherUp(other) } + } + } +} + +/// Dispatches a host-neutral mouse button event through the runtime, returning the resolved +/// [`ButtonAction`] so callers can run host-specific side effects. +#[cfg_attr(not(any(target_arch = "wasm32", test)), allow(dead_code))] +pub(crate) fn mouse_button_core( + rt: &mut RuntimeCore, + app: &mut dyn AppDriver, + input: MouseButtonInput, + control_click: &mut bool, +) -> ButtonAction { + let action = mouse_button_action( + input.button, + input.pressed, + input.mods.ctrl, + input.ctrl_click_is_secondary, + control_click, + ); + match action { + ButtonAction::PrimaryDown => { + rt.pointer_down(app, input.x, input.y); + if input.queue_mods_on_primary_down { + rt.physical_input(crate::PhysicalInput::Modifiers(input.mods)); + } + } + ButtonAction::PrimaryUp => rt.pointer_up(app, input.x, input.y), + ButtonAction::SecondaryDown => rt.secondary_down(input.x, input.y), + ButtonAction::SecondaryUp => rt.secondary_up(app, input.x, input.y), + ButtonAction::OtherDown(b) => rt.button_down(app, input.x, input.y, b), + ButtonAction::OtherUp(b) => rt.button_up(app, input.x, input.y, b), + } + action +} + +/// Maps a winit touch/gesture phase to Rune's `GesturePhase`. +pub(crate) fn gesture_phase(phase: TouchPhase) -> crate::GesturePhase { + match phase { + TouchPhase::Started => crate::GesturePhase::Began, + TouchPhase::Moved => crate::GesturePhase::Moved, + TouchPhase::Ended | TouchPhase::Cancelled => crate::GesturePhase::Ended, + } +} + +/// Whether the mouse message being handled is one Windows synthesized from a touch or pen +/// (`GetMessageExtraInfo` carries `MI_WP_SIGNATURE`). +#[cfg(target_os = "windows")] +#[allow(unsafe_code)] +pub(crate) fn touch_promoted() -> bool { + const MI_WP_SIGNATURE: u32 = 0xFF51_5700; + // SAFETY: reads the calling thread's current message info; no pointers involved. + let info = unsafe { windows_sys::Win32::UI::WindowsAndMessaging::GetMessageExtraInfo() } as u32; + info & 0xFFFF_FF00 == MI_WP_SIGNATURE +} + +#[cfg(not(target_os = "windows"))] +#[cfg_attr(target_arch = "wasm32", allow(dead_code))] +pub(crate) fn touch_promoted() -> bool { false } + +/// Builds a `ModifiersState` from individual shift/ctrl/alt/meta flags. +#[cfg_attr(not(any(target_arch = "wasm32", test)), allow(dead_code))] +pub(crate) fn modifiers_from_flags(shift: bool, ctrl: bool, alt: bool, meta: bool) -> ModifiersState { + let mut state = ModifiersState::empty(); + if shift { state |= ModifiersState::SHIFT; } + if ctrl { state |= ModifiersState::CONTROL; } + if alt { state |= ModifiersState::ALT; } + if meta { state |= ModifiersState::SUPER; } + state +} + +/// Notifies the runtime of the current modifier state; returns whether a redraw is needed. +pub(crate) fn modifiers_core( + rt: &mut RuntimeCore, + app: &mut dyn AppDriver, + mods: crate::Mods, +) -> bool { + rt.physical_observation(app, crate::PhysicalInput::Modifiers(mods)) +} + +/// Updates tracked modifiers and notifies the runtime; returns whether a redraw is needed. +pub(crate) fn modifiers( + rt: &mut RuntimeCore, + app: &mut dyn AppDriver, + mods: &mut ModifiersState, + next: ModifiersState, +) -> bool { + *mods = next; + modifiers_core(rt, app, map_mods(*mods)) +} + +/// Updates tracked modifiers and notifies the runtime only when `next` differs from `*mods`. +/// Used where both DOM capture refresh and winit's `ModifiersChanged` report the same transition. +#[cfg_attr(not(any(target_arch = "wasm32", test)), allow(dead_code))] +pub(crate) fn sync_modifiers( + rt: &mut RuntimeCore, + app: &mut dyn AppDriver, + mods: &mut ModifiersState, + next: ModifiersState, +) -> bool { + if *mods == next { return false; } + modifiers(rt, app, mods, next) +} + +/// Translates a host-neutral key input into runtime physical/logical key calls, including +/// clipboard paste read on non-physical fallback keys. Returns whether a redraw is needed. +pub(crate) fn keyboard_core( + rt: &mut RuntimeCore, + app: &mut dyn AppDriver, + clipboard: &crate::clipboard::Client, + input: KeyInput, +) -> bool { + if let Some(key) = input.physical { + rt.physical_then( + app, + crate::PhysicalInput::Key { key, mods: input.mods, pressed: input.pressed, repeat: input.repeat }, + input.logical, + input.base, + input.unhandled, + ) + } else if let Some(ev) = input.logical { + if !input.pressed { + rt.key_up(app, ev) + } else { + if ev.edit_command() == Some('v') && rt.accepts_paste() { + clipboard.read_core(rt); + } else if input.repeat { + rt.repeat_key(ev); + } else { + rt.key(ev); + } + true + } + } else { + false + } +} + +/// Translates a non-synthetic winit `KeyboardInput` into runtime physical/logical key calls, +/// including clipboard paste read on non-physical fallback keys. Returns whether a redraw is +/// needed. +pub(crate) fn keyboard( + rt: &mut RuntimeCore, + app: &mut dyn AppDriver, + clipboard: &crate::clipboard::Client, + event: &winit::event::KeyEvent, + mods: ModifiersState, + unhandled: Option<Unhandled>, +) -> bool { + let pressed = event.state == ElementState::Pressed; + // A release's logical key only matters to `on_key_up` handlers. + let logical = (pressed || rt.wants_key_up()).then(|| map_key_event(event, mods)).flatten(); + let physical = match event.physical_key { + PhysicalKey::Code(key) => Some(key), + PhysicalKey::Unidentified(_) => None, + }; + keyboard_core( + rt, + app, + clipboard, + KeyInput { + physical, + logical, + base: key_base(event), + mods: map_mods(mods), + pressed, + repeat: event.repeat, + unhandled, + }, + ) +} + +/// Translates a host-neutral wheel input (window points) into runtime pinch-wheel, `WheelEvent`, +/// or pointer-less phase begin/end notifications, scaled into view points. +pub(crate) fn wheel_core(rt: &mut RuntimeCore, input: WheelInput) -> WheelOutcome { + match rt.pointer() { + // Off macOS a trackpad pinch is a Ctrl + wheel. + Some((x, y)) if input.pinch && input.mods.ctrl && rt.pinch_wheel(x, y, input.dy) => WheelOutcome::Pinched, + Some((x, y)) => { + let zoom = rt.zoom(); + rt.wheel_event( + crate::WheelEvent::new(input.dx / zoom, input.dy / zoom) + .at(x, y) + .mods(input.mods) + .phase(input.phase) + .precise(input.precise) + .notch(input.notch), + ); + WheelOutcome::Scrolled + } + None if input.phase == crate::GesturePhase::Began => { + rt.wheel_began(); + WheelOutcome::Scrolled + } + None if input.phase == crate::GesturePhase::Ended => { + rt.wheel_ended(); + WheelOutcome::Scrolled + } + None => WheelOutcome::Ignored, + } +} + +/// Converts browser `WheelEvent.DOM_DELTA_PAGE` page counts (positive moving content right and +/// down) into window points, matching Chromium's 0.875 page fraction and Shift-axis turn. +#[cfg_attr(not(any(target_arch = "wasm32", test)), allow(dead_code))] +pub(crate) fn wheel_page_delta(rt: &RuntimeCore, dx_pages: f32, dy_pages: f32, shift: bool) -> (f32, f32) { + const PAGE_FRACTION: f32 = 0.875; + let (w, h) = rt.window_viewport(); + if shift && dx_pages == 0.0 { + (dy_pages * w * PAGE_FRACTION, 0.0) + } else { + (dx_pages * w * PAGE_FRACTION, dy_pages * h * PAGE_FRACTION) + } +} + +/// Translates a browser wheel delta in window points through [`wheel_core`], applying browser +/// policies: Ctrl+wheel only pinches outside document mode (unclaimed Ctrl+wheel stays with +/// browser zoom), and `fit_height` canvases leave vertical wheel to the page. +/// Returns `(redraw, sync_wheel_used)`. +#[cfg_attr(not(any(target_arch = "wasm32", test)), allow(dead_code))] +pub(crate) fn web_wheel( + rt: &mut RuntimeCore, + dx: f32, + dy: f32, + mods: crate::Mods, + phase: crate::GesturePhase, + precise: bool, + document: bool, + fit_height: bool, +) -> (bool, Option<bool>) { + let Some((x, y)) = rt.pointer() else { return (false, None) }; + // A page's pinch is the browser's zoom; elsewhere unclaimed Ctrl+wheel stays with browser + // zoom instead of falling through to scroll. + if mods.ctrl { + let used = !document && rt.pinch_wheel(x, y, dy); + return (used, Some(used)); + } + // On a content-sized embedded canvas, vertical wheel belongs to the page unless a + // horizontal strip is being scrolled. + if fit_height && dx.abs() <= dy.abs() { + return (false, None); + } + let outcome = wheel_core( + rt, + WheelInput { dx, dy, mods, phase, precise, notch: false, pinch: false }, + ); + (outcome != WheelOutcome::Ignored, None) +} + +/// Translates a winit `MouseWheel` event into runtime pinch-wheel, `WheelEvent`, or +/// pointer-less phase begin/end notifications, scaled into view points. +#[cfg_attr(target_arch = "wasm32", allow(dead_code))] +pub(crate) fn wheel( + rt: &mut RuntimeCore, + delta: MouseScrollDelta, + phase: crate::GesturePhase, + scale: f32, + mods: ModifiersState, +) { + let shift = crate::runtime::SHIFT_TURNS_WHEEL && mods.shift_key(); + // In window points: a wheel turns as far on screen at any zoom, as Chromium's does, + // and a pinch is the same gesture whatever the zoom. + #[cfg(target_os = "windows")] + let points = rt.windows_wheel_points(delta, shift); + #[cfg(not(target_os = "windows"))] + let points = crate::runtime::LINE_POINTS; + let (dx, dy) = crate::runtime::wheel_delta(delta, scale, shift, points); + let precise = matches!(delta, MouseScrollDelta::PixelDelta(_)); + // Whole lines are a notched wheel; a free-spinning wheel or a precision touchpad + // sends fractions (the run decides, `WheelLock::notched`). On Linux winit gives a + // wheel's detents as whole lines too and a touchpad's as fractions or pixels. + let notch = cfg!(any(target_os = "windows", target_os = "linux")) + && matches!(delta, MouseScrollDelta::LineDelta(x, y) if x.fract() == 0.0 && y.fract() == 0.0); + let _ = wheel_core( + rt, + WheelInput { + dx, + dy, + mods: map_mods(mods), + phase, + precise, + notch, + pinch: !cfg!(target_os = "macos"), + }, + ); +} + +/// Translates a winit `PinchGesture` at the current pointer; returns true when delivered. +#[cfg_attr(target_arch = "wasm32", allow(dead_code))] +pub(crate) fn magnify(rt: &mut RuntimeCore, delta: f64, phase: crate::GesturePhase) -> bool { + let Some((x, y)) = rt.pointer() else { return false }; + rt.magnify_event(crate::MagnifyEvent::new(delta as f32).at(x, y).phase(phase)); + true +} + +/// Translates a winit `RotationGesture` at the current pointer; returns true when delivered. +#[cfg_attr(target_arch = "wasm32", allow(dead_code))] +pub(crate) fn rotate(rt: &mut RuntimeCore, delta: f32, phase: crate::GesturePhase) -> bool { + let Some((x, y)) = rt.pointer() else { return false }; + rt.rotate_event(crate::RotateEvent::new(delta).at(x, y).phase(phase)); + true +} + +/// Translates a winit `DoubleTapGesture` at the current pointer; returns true when delivered. +#[cfg_attr(target_arch = "wasm32", allow(dead_code))] +pub(crate) fn smart_magnify(rt: &mut RuntimeCore) -> bool { + let Some((x, y)) = rt.pointer() else { return false }; + rt.smart_magnify(x, y); + true +} + +/// Translates a host-neutral IME event (with any reconversion selection range) into the runtime. +#[cfg_attr(target_arch = "wasm32", allow(dead_code))] +pub(crate) fn ime_core(rt: &mut RuntimeCore, select: Option<Range<usize>>, ime: Ime) { + // A reconversion the input method confirmed comes first: the composition it starts replaces + // that range. + if let Some(range) = select { + rt.ime(Ime::Select(range)); + } + rt.ime(ime); +} + +/// Translates a winit `Ime` event (plus any native reconversion range and clauses) into the +/// runtime. +#[cfg_attr(target_arch = "wasm32", allow(dead_code))] +pub(crate) fn ime(rt: &mut RuntimeCore, window: &Window, ime: WIme) { + let select = crate::platform::ime::take_select(window); + let event = match ime { + WIme::Preedit(s, cur) => { + let clauses = crate::platform::ime::take_clauses(window, &s); + Ime::Preedit(s, cur, clauses) + } + WIme::Commit(s) => Ime::Commit(s), + WIme::Enabled => Ime::Enabled, + WIme::Disabled => Ime::Disabled, + }; + ime_core(rt, select, event); +} + +/// Returns the current IME cursor area converted to window points. +pub(crate) fn ime_area_window(rt: &RuntimeCore) -> Option<[f32; 4]> { + rt.ime_area.map(|a| rt.to_window(a)) +} + +/// Takes any pending IME reset flag and returns the current IME cursor area in window points. +pub(crate) fn ime_sync_state(rt: &mut RuntimeCore) -> (bool, Option<[f32; 4]>) { + let reset = std::mem::take(&mut rt.edit.ime_reset); + let area = ime_area_window(rt); + (reset, area) +} + +/// Releases held keys, cancels active pointer/drag capture, finishes open IME composition, +/// and clears host modifier/control-click tracking when a host hides without a blur. +#[cfg_attr(not(any(target_arch = "wasm32", test)), allow(dead_code))] +pub(crate) fn hide_reset( + rt: &mut RuntimeCore, + mods: &mut ModifiersState, + control_click: &mut bool, +) { + *mods = ModifiersState::empty(); + *control_click = false; + rt.cancel_pointer(); + rt.finish_composition(); + rt.keys_lost(); +} + +/// Cancels active pointer/drag/secondary capture on pointer cancel or abnormal capture loss. +/// When `only_if_captured` is true (e.g. `lostpointercapture`, which also fires after a +/// normal `pointerup`), does nothing if no pointer capture is currently held, so hover is +/// preserved. Returns whether anything was cancelled and needs a frame. +#[cfg_attr(not(any(target_arch = "wasm32", test)), allow(dead_code))] +pub(crate) fn pointer_cancel( + rt: &mut RuntimeCore, + control_click: &mut bool, + only_if_captured: bool, +) -> bool { + if only_if_captured && !rt.pointer_captured() && !*control_click { + return false; + } + *control_click = false; + rt.cancel_pointer(); + true +} + +/// Synchronizes a window's OS IME allowance, cursor area, and published text with the runtime. +#[cfg_attr(target_arch = "wasm32", allow(dead_code))] +pub(crate) fn sync_ime(window: &Window, rt: &mut RuntimeCore, ime_state: &mut bool, focused: bool) { + let (reset, area) = ime_sync_state(rt); + let ime_allowed = area.is_some() && !rt.has_secure_focus() && focused; + if reset { crate::platform::ime::cancel(window); } + if reset || ime_allowed != *ime_state { + window.set_ime_allowed(false); + window.set_ime_allowed(ime_allowed); + *ime_state = ime_allowed; + } + #[cfg(target_os = "macos")] + { + use winit::platform::macos::{OptionAsAlt, WindowExtMacOS}; + let want = if ime_allowed && rt.edit.ime_option_as_alt { OptionAsAlt::Both } else { OptionAsAlt::None }; + if window.option_as_alt() != want { + window.set_option_as_alt(want); + } + } + crate::platform::ime::sync(window, if ime_allowed { rt.ime_text() } else { None }); + if let Some(a) = area { + window.set_ime_cursor_area( + LogicalPosition::new(a[0] as f64, a[1] as f64), + LogicalSize::new(a[2] as f64, a[3] as f64), + ); + } +} + +/// Refreshes OS accessibility and appearance preferences sampled on window/overlay focus changes. +#[cfg_attr(target_arch = "wasm32", allow(dead_code))] +pub(crate) fn refresh_focus_preferences( + rt: &mut RuntimeCore, + scroll_bars_override: Option<crate::platform::scroll_bars::ScrollBars>, +) { + rt.set_system_reduced_motion(crate::platform::preferences::reduced_motion()); + rt.set_system_contrast(crate::platform::preferences::contrast()); + rt.set_system_increased_contrast(crate::platform::preferences::increased_contrast()); + rt.set_full_keyboard_access(crate::platform::preferences::full_keyboard_access()); + rt.set_system_scroll_bars_state(crate::platform::scroll_bars::reread().with_override(scroll_bars_override)); +} + +#[cfg(test)] +#[path = "host_events_tests.rs"] +mod tests; diff --git a/app/vendor/rune/crates/rune/src/input/host_events_tests.rs b/app/vendor/rune/crates/rune/src/input/host_events_tests.rs new file mode 100644 index 0000000..6b3d894 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/input/host_events_tests.rs @@ -0,0 +1,586 @@ +use winit::dpi::PhysicalPosition; +use winit::event::{MouseScrollDelta, TouchPhase}; +use winit::keyboard::ModifiersState; + +use super::*; +use crate::{Cx, El, Env, GesturePhase, Runtime, WheelEvent, el}; + +#[test] +fn gesture_phase_maps_every_winit_touch_phase() { + assert_eq!(gesture_phase(TouchPhase::Started), GesturePhase::Began); + assert_eq!(gesture_phase(TouchPhase::Moved), GesturePhase::Moved); + assert_eq!(gesture_phase(TouchPhase::Ended), GesturePhase::Ended); + assert_eq!(gesture_phase(TouchPhase::Cancelled), GesturePhase::Ended); +} + +#[test] +fn shared_wheel_translates_pixel_and_line_deltas_with_zoom_and_modifiers() { + #[derive(Default)] + struct S { events: Vec<WheelEvent> } + fn view(_: &S, cx: &mut Cx<S>) -> El { + cx.zoom(2.0); + el().size(200.0, 200.0) + .hit() + .on_wheel(|s: &mut S, ev, _| { s.events.push(ev); true }) + } + let mut rt = Runtime::new(S::default(), view, (200.0, 200.0), Env::new(true, 2.0)); + rt.frame(0.0); + // View point (50, 50) at scale 2.0, zoom 2.0. + rt.pointer_move(50.0, 50.0); + + // PixelDelta(0, -40) at scale 2.0 -> window delta -20 pt -> view delta -10 pt at zoom 2.0. + wheel(rt.core_mut(), MouseScrollDelta::PixelDelta(PhysicalPosition::new(0.0, -40.0)), gesture_phase(TouchPhase::Moved), 2.0, ModifiersState::ALT); + rt.frame(0.0); + assert_eq!(rt.state.events.len(), 1); + let ev = rt.state.events[0]; + assert_eq!((ev.dx, ev.dy), (0.0, -10.0)); + assert!(ev.precise && !ev.notch && ev.mods.alt); + assert_eq!(ev.phase, GesturePhase::Moved); + + // Magnify / rotate / smart_magnify require a pointer and return false when pointer is None. + assert!(magnify(rt.core_mut(), 0.25, gesture_phase(TouchPhase::Moved))); + assert!(rotate(rt.core_mut(), 15.0, gesture_phase(TouchPhase::Moved))); + assert!(smart_magnify(rt.core_mut())); + rt.pointer_leave(); + assert!(!magnify(rt.core_mut(), 0.25, gesture_phase(TouchPhase::Moved))); + assert!(!rotate(rt.core_mut(), 15.0, gesture_phase(TouchPhase::Moved))); + assert!(!smart_magnify(rt.core_mut())); +} + +#[test] +fn shared_modifiers_updates_state_and_notifies_physical_handlers() { + #[derive(Default)] + struct S { seen: Vec<crate::Mods> } + fn view(_: &S, _: &mut Cx<S>) -> El { + el().key("root").size(100.0, 100.0).focusable(true).on_physical_input(|s: &mut S, ev, _| { + if let crate::PhysicalInput::Modifiers(m) = ev { + s.seen.push(*m); + return true; + } + false + }) + } + let mut rt = Runtime::new(S::default(), view, (100.0, 100.0), Env::default()); + rt.frame(0.0); + rt.update(|_, tx| tx.focus("root", false)); + rt.frame(0.0); + let mut mods = ModifiersState::empty(); + let redraw = { + let (core, mut app) = rt.split_mut(); + modifiers(core, &mut app, &mut mods, ModifiersState::SHIFT | ModifiersState::ALT) + }; + assert!(redraw); + assert_eq!(mods, ModifiersState::SHIFT | ModifiersState::ALT); + rt.frame(0.0); + assert_eq!(rt.state.seen.last().map(|m| (m.shift, m.alt)), Some((true, true))); +} + +#[test] +fn pointer_wheel_hover_and_ime_area_scale_by_view_zoom() { + #[derive(Default)] + struct S { clicks: Vec<&'static str>, wheels: Vec<WheelEvent>, pinches: Vec<f32>, edit: crate::TextEdit } + fn view(s: &S, cx: &mut Cx<S>) -> El { + cx.zoom(1.5); + crate::col().size(200.0, 200.0) + .on_wheel(|s: &mut S, ev, _| { s.wheels.push(ev); true }) + .on_magnify(|s: &mut S, ev, _| { s.pinches.push(ev.delta); true }) + .child(el().key("top").size(100.0, 50.0).on_press(|s: &mut S| s.clicks.push("top"))) + .child(el().key("mid").size(100.0, 50.0).on_press(|s: &mut S| s.clicks.push("mid"))) + .child(crate::text_input(&s.edit, crate::TextStyle::new(14.0, 400.0)) + .key("field").size(100.0, 40.0).on_edit(|s: &mut S| &mut s.edit)) + } + // Scale 2.0, zoom 1.5 -> input_scale = 3.0. + // "mid" sits at view y in [50, 100), i.e. window y in [75, 150), physical y in [150, 300). + let mut rt = Runtime::new(S::default(), view, (300.0, 300.0), Env::new(true, 2.0)); + rt.frame(0.0); + + // Physical (120, 180) -> window (60, 90) -> view (40, 60) which hits "mid" (not "top"). + let (vx, vy) = physical_point(rt.core(), 120.0, 180.0); + assert!((vx - 40.0).abs() < 1e-4 && (vy - 60.0).abs() < 1e-4); + rt.pointer_move(vx, vy); + rt.pointer_down(vx, vy); + rt.pointer_up(vx, vy); + rt.frame(0.0); + assert_eq!(rt.state.clicks, ["mid"]); + + // Window point (45, 30) -> view (30, 20) which hits "top". + let (hx, hy) = window_point(rt.core(), 45.0, 30.0); + assert!((hx - 30.0).abs() < 1e-4 && (hy - 20.0).abs() < 1e-4); + rt.pointer_move(hx, hy); + rt.pointer_down(hx, hy); + rt.pointer_up(hx, hy); + rt.frame(0.0); + assert_eq!(rt.state.clicks, ["mid", "top"]); + + // Wheel delta -30 window points -> -20 view points at zoom 1.5. + let (redraw, used) = web_wheel( + rt.core_mut(), 0.0, -30.0, crate::Mods::default(), GesturePhase::Moved, true, false, false, + ); + assert!(redraw && used.is_none()); + rt.frame(0.0); + assert_eq!(rt.state.wheels.len(), 1); + assert!((rt.state.wheels[0].dy - (-20.0)).abs() < 1e-4); + + // Ctrl+wheel pinches in un-zoomed window points; document mode leaves it to the browser. + let ctrl = crate::Mods { ctrl: true, cmd: true, ..crate::Mods::default() }; + let (redraw, used) = web_wheel(rt.core_mut(), 0.0, -40.0, ctrl, GesturePhase::Moved, true, false, false); + assert!(redraw && used == Some(true)); + rt.frame(0.0); + assert_eq!(rt.state.pinches.len(), 1); + let (redraw, used) = web_wheel(rt.core_mut(), 0.0, -40.0, ctrl, GesturePhase::Moved, true, true, false); + assert!(!redraw && used == Some(false)); + + // fit_height leaves vertical wheel to the page, while keeping horizontal wheel. + let (redraw, used) = web_wheel(rt.core_mut(), 0.0, -30.0, crate::Mods::default(), GesturePhase::Moved, true, false, true); + assert!(!redraw && used.is_none()); + let (redraw, used) = web_wheel(rt.core_mut(), -30.0, 0.0, crate::Mods::default(), GesturePhase::Moved, true, false, true); + assert!(redraw && used.is_none()); + + // IME area in window points scales by zoom (1.5x view ime_area). + let (fx, fy) = rt.find("field").unwrap(); + rt.pointer_down(fx, fy); + rt.pointer_up(fx, fy); + rt.frame(0.0); + let view_ime = rt.ime_area.expect("focused field sets ime_area"); + let win_ime = ime_area_window(rt.core()).expect("window ime_area"); + for i in 0..4 { + assert!((win_ime[i] - view_ime[i] * 1.5).abs() < 1e-3); + } +} + +#[test] +fn web_page_wheel_scales_by_viewport_zoom_and_respects_shift_without_double_swapping() { + #[derive(Default)] + struct S { wheels: Vec<WheelEvent> } + fn view(_: &S, cx: &mut Cx<S>) -> El { + cx.zoom(2.0); + el().size(200.0, 100.0).hit().on_wheel(|s: &mut S, ev, _| { s.wheels.push(ev); true }) + } + // Window viewport 400x200 at zoom 2.0 -> view viewport 200x100. + let mut rt = Runtime::new(S::default(), view, (400.0, 200.0), Env::new(true, 1.0)); + rt.frame(0.0); + rt.pointer_move(50.0, 50.0); + + // 1 vertical page down -> -1.0 * 200 * 0.875 = -175 window pt -> -87.5 view pt. + let (dx, dy) = wheel_page_delta(rt.core(), 0.0, -1.0, false); + assert!((dx - 0.0).abs() < 1e-4 && (dy - (-175.0)).abs() < 1e-4); + let (redraw, _) = web_wheel(rt.core_mut(), dx, dy, crate::Mods::default(), GesturePhase::Moved, false, false, false); + assert!(redraw); + rt.frame(0.0); + assert_eq!(rt.state.wheels.len(), 1); + assert!((rt.state.wheels[0].dy - (-87.5)).abs() < 1e-4); + assert!(!rt.state.wheels[0].precise && rt.state.wheels[0].phase == GesturePhase::Moved); + + // Shift + vertical page when browser kept dx == 0 turns horizontal using window width (400 * 0.875 = 350 -> 175 view pt). + let (dx, dy) = wheel_page_delta(rt.core(), 0.0, -1.0, true); + assert!((dx - (-350.0)).abs() < 1e-4 && dy == 0.0); + let shift = crate::Mods { shift: true, ..crate::Mods::default() }; + let (redraw, _) = web_wheel(rt.core_mut(), dx, dy, shift, GesturePhase::Moved, false, false, false); + assert!(redraw); + rt.frame(0.0); + assert!((rt.state.wheels[1].dx - (-175.0)).abs() < 1e-4 && rt.state.wheels[1].dy == 0.0); + + // When the browser already swapped axes (dx != 0, dy == 0), Shift must not double-swap. + let (dx, dy) = wheel_page_delta(rt.core(), -1.0, 0.0, true); + assert!((dx - (-350.0)).abs() < 1e-4 && dy == 0.0); + let (dx_px, dy_px) = crate::runtime::wheel_delta( + MouseScrollDelta::PixelDelta(PhysicalPosition::new(-40.0, 0.0)), + 1.0, + true, + 40.0, + ); + assert_eq!((dx_px, dy_px), (-40.0, 0.0)); +} + +#[test] +fn sync_modifiers_observes_changes_updates_press_mods_and_deduplicates_repeats() { + #[derive(Default)] + struct S { physical: Vec<crate::Mods>, click_mods: Vec<crate::Mods> } + fn view(_: &S, _: &mut Cx<S>) -> El { + el().key("btn").size(100.0, 100.0).focusable(true) + .on_physical_input(|s: &mut S, ev, _| { + if let crate::PhysicalInput::Modifiers(m) = ev { + s.physical.push(*m); + return true; + } + false + }) + .on_press_tx(|s: &mut S, tx| s.click_mods.push(tx.mods())) + } + let mut rt = Runtime::new(S::default(), view, (100.0, 100.0), Env::default()); + rt.frame(0.0); + rt.update(|_, tx| tx.focus("btn", false)); + rt.frame(0.0); + + let mut mods = ModifiersState::empty(); + let shift_ctrl = modifiers_from_flags(true, true, false, false); + assert_eq!(shift_ctrl, ModifiersState::SHIFT | ModifiersState::CONTROL); + + let redraw = { + let (core, mut app) = rt.split_mut(); + sync_modifiers(core, &mut app, &mut mods, shift_ctrl) + }; + assert!(redraw); + rt.frame(0.0); + assert_eq!(rt.state.physical.len(), 1); + assert!(rt.state.physical[0].shift && rt.state.physical[0].ctrl); + + // Repeating the same state (winit's ModifiersChanged after DOM capture) is a no-op. + let dup = { + let (core, mut app) = rt.split_mut(); + sync_modifiers(core, &mut app, &mut mods, shift_ctrl) + }; + assert!(!dup); + rt.frame(0.0); + assert_eq!(rt.state.physical.len(), 1); + + // A click after modifier refresh sees the held modifiers via tx.mods(). + rt.pointer_move(50.0, 50.0); + rt.pointer_down(50.0, 50.0); + rt.pointer_up(50.0, 50.0); + rt.frame(0.0); + assert_eq!(rt.state.click_mods.len(), 1); + assert!(rt.state.click_mods[0].shift && rt.state.click_mods[0].ctrl); +} + +#[test] +fn keyboard_core_handles_unidentified_repeat_paste_fallback_and_release_gating() { + #[derive(Default)] + struct S { + edit: crate::TextEdit, + keys: Vec<(crate::Key, Option<crate::PhysicalKeyCode>, Option<char>, bool)>, + ups: Vec<crate::Key>, + listen_up: bool, + } + fn view(s: &S, _: &mut Cx<S>) -> El { + let root = crate::col().size(200.0, 100.0) + .child(crate::text_input(&s.edit, crate::TextStyle::new(14.0, 400.0)) + .key("field").size(160.0, 40.0).on_edit(|s: &mut S| &mut s.edit)); + if s.listen_up { + root.on_key_up(|s: &mut S, ev, _| { s.ups.push(ev.key.clone()); true }) + } else { + root + } + } + let mut rt = Runtime::new(S::default(), view, (200.0, 100.0), Env::default()); + let mem = crate::clipboard::memory(); + mem.set_text("pasted"); + rt.use_clipboard(&mem); + rt.on_key = Some(|s, ev, tx| { + s.keys.push((ev.key.clone(), tx.physical_key(), tx.key_base(), tx.key_repeat())); + true + }); + rt.frame(0.0); + + let client = crate::clipboard::Client::default(); + + // Unidentified physical key with repeat: true uses repeat_key (tx.key_repeat() == true). + let redraw = { + let (core, mut app) = rt.split_mut(); + keyboard_core(core, &mut app, &client, KeyInput { + physical: None, + logical: Some(crate::KeyEvent { key: crate::Key::Down, mods: crate::Mods::default() }), + base: None, + mods: crate::Mods::default(), + pressed: true, + repeat: true, + unhandled: None, + }) + }; + assert!(redraw); + rt.frame(0.0); + assert_eq!(rt.state.keys, [(crate::Key::Down, None, None, true)]); + + // Unhandled key release with no on_key_up returns false (no redraw). + let redraw = { + let (core, mut app) = rt.split_mut(); + keyboard_core(core, &mut app, &client, KeyInput { + physical: Some(crate::PhysicalKeyCode::ArrowDown), + logical: None, + base: None, + mods: crate::Mods::default(), + pressed: false, + repeat: false, + unhandled: None, + }) + }; + assert!(!redraw); + + // Physical key press delivers physical_key, key_base, and key_repeat. + let redraw = { + let (core, mut app) = rt.split_mut(); + keyboard_core(core, &mut app, &client, KeyInput { + physical: Some(crate::PhysicalKeyCode::KeyA), + logical: Some(crate::KeyEvent { key: crate::Key::Text("A".into()), mods: crate::Mods { shift: true, ..Default::default() } }), + base: Some('a'), + mods: crate::Mods { shift: true, ..Default::default() }, + pressed: true, + repeat: false, + unhandled: None, + }) + }; + assert!(redraw); + rt.frame(0.0); + assert_eq!(rt.state.keys.last(), Some(&(crate::Key::Text("A".into()), Some(crate::PhysicalKeyCode::KeyA), Some('a'), false))); + + // Unidentified physical key Command('v') on a focused text field reads the clipboard instead of falling through. + let (fx, fy) = rt.find("field").unwrap(); + rt.pointer_down(fx, fy); + rt.pointer_up(fx, fy); + rt.frame(0.0); + let cmd = crate::Mods { cmd: true, ..crate::Mods::default() }; + let redraw = { + let (core, mut app) = rt.split_mut(); + keyboard_core(core, &mut app, &client, KeyInput { + physical: None, + logical: Some(crate::KeyEvent { key: crate::Key::Command('v'), mods: cmd }), + base: None, + mods: cmd, + pressed: true, + repeat: false, + unhandled: None, + }) + }; + assert!(redraw); + assert!(client.receive_core(rt.core_mut())); + rt.frame(0.0); + assert_eq!(rt.state.edit.text, "pasted"); + + // With an on_key_up listener, unidentified release delivers key_up and requests redraw. + rt.update(|s, _| s.listen_up = true); + rt.frame(0.0); + let redraw = { + let (core, mut app) = rt.split_mut(); + keyboard_core(core, &mut app, &client, KeyInput { + physical: None, + logical: Some(crate::KeyEvent { key: crate::Key::Escape, mods: crate::Mods::default() }), + base: None, + mods: crate::Mods::default(), + pressed: false, + repeat: false, + unhandled: None, + }) + }; + assert!(redraw); + rt.frame(0.0); + assert_eq!(rt.state.ups, [crate::Key::Escape]); +} + +#[test] +fn mouse_button_core_handles_macos_ctrl_click_left_down_mods_and_middle_buttons() { + #[derive(Default)] + struct S { + primary: Vec<crate::Mods>, + secondary: usize, + middle: usize, + physical_mods: Vec<crate::Mods>, + } + fn view(_: &S, _: &mut Cx<S>) -> El { + el().key("target").size(100.0, 100.0).focusable(true) + .on_press_tx(|s: &mut S, tx| s.primary.push(tx.mods())) + .on_secondary_press(|s: &mut S, _, _| s.secondary += 1) + .on_middle_press(|s: &mut S, _| s.middle += 1) + .on_physical_input(|s: &mut S, ev, _| { + if let crate::PhysicalInput::Modifiers(m) = ev { + s.physical_mods.push(*m); + return true; + } + false + }) + } + let mut rt = Runtime::new(S::default(), view, (100.0, 100.0), Env::default()); + rt.frame(0.0); + rt.pointer_move(50.0, 50.0); + + let ctrl = crate::Mods { ctrl: true, cmd: true, ..Default::default() }; + let mut control_click = false; + + // On macOS (ctrl_click_is_secondary = true), Ctrl+Left is secondary even if Ctrl lifts before mouse-up. + let down = { + let (core, mut app) = rt.split_mut(); + mouse_button_core(core, &mut app, MouseButtonInput { + x: 50.0, y: 50.0, button: crate::PointerButton::Primary, pressed: true, + mods: ctrl, ctrl_click_is_secondary: true, queue_mods_on_primary_down: true, + }, &mut control_click) + }; + assert_eq!(down, ButtonAction::SecondaryDown); + assert!(control_click); + let up = { + let (core, mut app) = rt.split_mut(); + mouse_button_core(core, &mut app, MouseButtonInput { + x: 50.0, y: 50.0, button: crate::PointerButton::Primary, pressed: false, + mods: crate::Mods::default(), ctrl_click_is_secondary: true, queue_mods_on_primary_down: true, + }, &mut control_click) + }; + assert_eq!(up, ButtonAction::SecondaryUp); + assert!(!control_click); + rt.frame(0.0); + assert_eq!((rt.state.primary.len(), rt.state.secondary), (0, 1)); + + // Off macOS (ctrl_click_is_secondary = false), Ctrl+Left stays primary and queues modifiers for the newly focused element. + let down = { + let (core, mut app) = rt.split_mut(); + mouse_button_core(core, &mut app, MouseButtonInput { + x: 50.0, y: 50.0, button: crate::PointerButton::Primary, pressed: true, + mods: ctrl, ctrl_click_is_secondary: false, queue_mods_on_primary_down: true, + }, &mut control_click) + }; + assert_eq!(down, ButtonAction::PrimaryDown); + let up = { + let (core, mut app) = rt.split_mut(); + mouse_button_core(core, &mut app, MouseButtonInput { + x: 50.0, y: 50.0, button: crate::PointerButton::Primary, pressed: false, + mods: ctrl, ctrl_click_is_secondary: false, queue_mods_on_primary_down: true, + }, &mut control_click) + }; + assert_eq!(up, ButtonAction::PrimaryUp); + rt.frame(0.0); + assert_eq!((rt.state.primary.len(), rt.state.secondary), (1, 1)); + assert!(rt.state.primary[0].ctrl); + assert!(rt.state.physical_mods.last().is_some_and(|m| m.ctrl)); + + // Middle button routes through button_down / button_up. + let down = { + let (core, mut app) = rt.split_mut(); + mouse_button_core(core, &mut app, MouseButtonInput { + x: 50.0, y: 50.0, button: crate::PointerButton::Middle, pressed: true, + mods: crate::Mods::default(), ctrl_click_is_secondary: false, queue_mods_on_primary_down: false, + }, &mut control_click) + }; + assert_eq!(down, ButtonAction::OtherDown(crate::PointerButton::Middle)); + let up = { + let (core, mut app) = rt.split_mut(); + mouse_button_core(core, &mut app, MouseButtonInput { + x: 50.0, y: 50.0, button: crate::PointerButton::Middle, pressed: false, + mods: crate::Mods::default(), ctrl_click_is_secondary: false, queue_mods_on_primary_down: false, + }, &mut control_click) + }; + assert_eq!(up, ButtonAction::OtherUp(crate::PointerButton::Middle)); + rt.frame(0.0); + assert_eq!(rt.state.middle, 1); +} + +#[test] +fn hide_reset_cancels_drag_commits_ime_releases_keys_and_clears_host_state() { + #[derive(Default)] + struct S { + edit: crate::TextEdit, + drag_cancelled: bool, + focus_lost: usize, + } + fn view(s: &S, _: &mut Cx<S>) -> El { + crate::col().size(200.0, 200.0) + .child(el().key("drag").size(100.0, 50.0).focusable(true) + .on_drag(|s: &mut S, d: &mut crate::Drag, _| { + if d.cancelled { s.drag_cancelled = true; } + }) + .on_physical_input(|s: &mut S, ev, _| { + if matches!(ev, crate::PhysicalInput::FocusLost) { s.focus_lost += 1; return true; } + false + })) + .child(crate::text_input(&s.edit, crate::TextStyle::new(14.0, 400.0)) + .key("field").size(160.0, 40.0).on_edit(|s: &mut S| &mut s.edit)) + } + let mut rt = Runtime::new(S::default(), view, (200.0, 200.0), Env::default()); + rt.frame(0.0); + + // Focus field and open an IME composition. + let (fx, fy) = rt.find("field").unwrap(); + rt.pointer_down(fx, fy); + rt.pointer_up(fx, fy); + rt.frame(0.0); + ime_core(rt.core_mut(), None, Ime::Preedit("nihon".into(), Some((5, 5)), Vec::new())); + rt.frame(0.0); + assert_eq!(rt.state.edit.preedit().map(|(s, _)| s), Some("nihon")); + + // Start a drag on "drag" (moves focus there, holds pointer capture). + let (dx, dy) = rt.find("drag").unwrap(); + rt.pointer_move(dx, dy); + rt.pointer_down(dx, dy); + rt.frame(0.0); + assert!(rt.pointer_captured()); + + let mut mods = ModifiersState::SHIFT | ModifiersState::CONTROL; + let mut control_click = true; + hide_reset(rt.core_mut(), &mut mods, &mut control_click); + assert!(mods.is_empty() && !control_click); + let (reset, _) = ime_sync_state(rt.core_mut()); + assert!(reset, "finish_composition sets ime_reset for the host"); + rt.frame(0.0); + + assert!(rt.state.drag_cancelled, "hide cancels active drag with cancelled = true"); + assert_eq!(rt.state.focus_lost, 1, "hide delivers FocusLost to release held keys"); + assert!(!rt.pointer_captured()); + assert_eq!(rt.pointer(), None); +} + +#[test] +fn pointer_cancel_distinguishes_lost_capture_at_rest_from_active_capture_and_cancel() { + #[derive(Default)] + struct S { cancelled: usize } + fn view(_: &S, _: &mut Cx<S>) -> El { + el().key("drag").size(100.0, 100.0) + .on_drag(|s: &mut S, d: &mut crate::Drag, _| { + if d.cancelled { s.cancelled += 1; } + }) + } + let mut rt = Runtime::new(S::default(), view, (100.0, 100.0), Env::default()); + rt.frame(0.0); + rt.pointer_move(50.0, 50.0); + rt.frame(0.0); + + // At rest (no capture held, e.g. lostpointercapture after a normal pointerup): no-op, hover preserved. + let mut control_click = false; + assert!(!pointer_cancel(rt.core_mut(), &mut control_click, true)); + assert_eq!(rt.pointer(), Some((50.0, 50.0))); + + // With an active drag capture, lostpointercapture cancels the drag and drops pointer. + rt.pointer_down(50.0, 50.0); + rt.frame(0.0); + assert!(rt.pointer_captured()); + assert!(pointer_cancel(rt.core_mut(), &mut control_click, true)); + rt.frame(0.0); + assert_eq!(rt.state.cancelled, 1); + assert!(!rt.pointer_captured() && rt.pointer().is_none()); + + // Unconditional pointercancel (only_if_captured = false) ends hover even at rest. + rt.pointer_move(40.0, 40.0); + rt.frame(0.0); + assert!(pointer_cancel(rt.core_mut(), &mut control_click, false)); + assert_eq!(rt.pointer(), None); +} + +#[test] +fn ime_sync_state_reset_preserves_mirror_diff_when_empty_field_blurs() { + #[derive(Default)] + struct S { edit: crate::TextEdit } + fn view(s: &S, _: &mut Cx<S>) -> El { + crate::col().size(200.0, 120.0) + .child(el().key("btn").size(100.0, 40.0).focusable(true)) + .child(crate::text_input(&s.edit, crate::TextStyle::new(14.0, 400.0)) + .key("field").size(160.0, 40.0).on_edit(|s: &mut S| &mut s.edit)) + } + let mut rt = Runtime::new(S::default(), view, (200.0, 120.0), Env::default()); + rt.frame(0.0); + let mut mirror = crate::runtime::web_runtime::Mirror::default(); + + // Focus empty text field and sync mirror. + let (fx, fy) = rt.find("field").unwrap(); + rt.pointer_down(fx, fy); + rt.pointer_up(fx, fy); + rt.frame(0.0); + assert!(rt.core().web_context(&mut mirror)); + assert!(!mirror.key.is_empty()); + + // Blurring the empty field sets ime_reset and leaves focused_input() == None. + // web_context must still report a change (key -> "") when mirror.key is not cleared first. + let (bx, by) = rt.find("btn").unwrap(); + rt.pointer_down(bx, by); + rt.pointer_up(bx, by); + rt.frame(0.0); + let (reset, area) = ime_sync_state(rt.core_mut()); + assert!(area.is_none()); + let changed = rt.core().web_context(&mut mirror); + assert!(changed || reset, "mirror must sync back to empty key so DOM focus returns to canvas"); + assert!(mirror.key.is_empty()); +} diff --git a/app/vendor/rune/crates/rune/src/input/key_diagnostics.rs b/app/vendor/rune/crates/rune/src/input/key_diagnostics.rs new file mode 100644 index 0000000..4880ce2 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/input/key_diagnostics.rs @@ -0,0 +1,264 @@ +//! Sibling key checks and repair. They run on the view before virtualization, so offscreen +//! siblings are checked too; a `virtualize` list's own rows are checked as it windows them. +use std::cell::RefCell; +use std::collections::{HashMap, HashSet}; +use std::hash::{Hash, Hasher}; + +use crate::El; + +/// A sibling key used twice under one parent. +#[derive(Debug, Clone, PartialEq)] +pub(crate) struct Duplicate { + pub key: String, + pub message: String, +} + +/// Whether no two of these siblings share a key. A hash collision can say false for unique +/// keys, which only sends the caller to the exact check. Allocates nothing once `hashes` has +/// grown to the widest parent. +fn unique(shared: &[El], own: &[El], hashes: &mut Vec<u64>) -> bool { + let keys = shared.iter().chain(own).filter_map(|c| c.key.as_deref()); + let n = keys.clone().count(); + if n < 2 { return true; } + if n <= 8 { + return keys.clone().enumerate().all(|(i, a)| keys.clone().skip(i + 1).all(|b| a != b)); + } + hashes.clear(); + hashes.extend(keys.map(|k| { + let mut h = rustc_hash::FxHasher::default(); + k.hash(&mut h); + h.finish() + })); + hashes.sort_unstable(); + hashes.windows(2).all(|w| w[0] != w[1]) +} + +/// The sibling sets under `el` that need checking: a memo's shared children were checked when +/// it built, and a virtual list's rows are checked as it windows them. +fn checks_siblings(el: &El) -> bool { + el.cold.virtual_estimate.is_none() && !(el.memo_children().is_some() && el.children.is_empty()) +} + +fn shared_children(el: &El) -> &[El] { + el.memo_children().map_or(&[], |m| &m.children) +} + +fn clean_with(el: &El, hashes: &mut Vec<u64>) -> bool { + if el.memo_children().is_some_and(|m| m.duplicate_keys) { return false; } + if checks_siblings(el) && !unique(shared_children(el), &el.children, hashes) { return false; } + el.children.iter().all(|c| clean_with(c, hashes)) +} + +/// Whether no parent in `root` has two children with one key: the per-commit check, which +/// allocates nothing and skips the subtrees of memos (checked once, when they build). +pub(crate) fn clean(root: &El) -> bool { + thread_local! { static HASHES: RefCell<Vec<u64>> = const { RefCell::new(Vec::new()) }; } + HASHES.with_borrow_mut(|hashes| clean_with(root, hashes)) +} + +/// Whether a memo's children, as built, hold duplicate keys anywhere below the memo's root. +pub(crate) fn memo_children_have_duplicates(root: &El, children: &[El]) -> bool { + let mut hashes = Vec::new(); + (root.cold.virtual_estimate.is_none() && !unique(children, &[], &mut hashes)) + || !children.iter().all(|c| clean_with(c, &mut hashes)) +} + +/// The duplicates under `root`, with messages naming both call sites. Only for trees [`clean`] +/// rejected: paths are built only down to the duplicates. +fn find(root: &El, path: &str) -> Vec<Duplicate> { + fn walk(el: &El, path: &str, hashes: &mut Vec<u64>, out: &mut Vec<Duplicate>) { + let shared = el.memo_children().is_some_and(|m| m.duplicate_keys); + if checks_siblings(el) || (shared && el.cold.virtual_estimate.is_none()) { + let mut seen: HashMap<&str, &El> = HashMap::new(); + for child in el.all_children() { + let Some(key) = &child.key else { continue }; + if let Some(first) = seen.get(key.as_str()) { + out.push(Duplicate { + key: key.clone(), + message: format!( + "duplicate sibling key {key:?} under {path:?}: first at {}, again at {}; give siblings unique keys", + first.key_location(), child.key_location(), + ), + }); + } else { + seen.insert(key, child); + } + } + } + for (index, child) in el.all_children().enumerate() { + if clean_with(child, hashes) { continue; } + let segment = child.key.clone().unwrap_or_else(|| format!("#{index}")); + walk(child, &format!("{path}/{segment}"), hashes, out); + } + } + let mut out = Vec::new(); + walk(root, path, &mut Vec::new(), &mut out); + out +} + +fn root_path(root: &El) -> &str { + root.key.as_deref().unwrap_or("#0") +} + +#[cfg(test)] +pub(crate) fn warnings(root: &El) -> Vec<String> { + find(root, root_path(root)).into_iter().map(|d| d.message).collect() +} + +/// Renames each later copy of a key `key#dup1`, `key#dup2`, ... in order, skipping names +/// already taken, so the first keeps its key. Returns each renamed index with its old key. +pub(crate) fn rename_duplicates<'a>(keys: impl Iterator<Item = &'a mut String>) -> Vec<(usize, String)> { + let mut keys: Vec<&mut String> = keys.collect(); + // Unique keys, the usual case, are found so by borrowing them: no copy of each. + let mut seen: crate::runtime::HashSet<&str> = crate::runtime::HashSet::with_capacity_and_hasher(keys.len(), Default::default()); + if keys.iter().all(|k| seen.insert(k.as_str())) { + return Vec::new(); + } + drop(seen); + let mut taken: HashSet<String> = keys.iter().map(|k| k.to_string()).collect(); + let mut kept: HashSet<String> = HashSet::new(); + let mut renamed = Vec::new(); + for (i, key) in keys.iter_mut().enumerate() { + if kept.insert(key.to_string()) { continue; } + let name = (1..).map(|n| format!("{key}#dup{n}")).find(|k| !taken.contains(k)).unwrap(); + taken.insert(name.clone()); + kept.insert(name.clone()); + renamed.push((i, std::mem::replace(*key, name))); + } + renamed +} + +/// Makes sibling keys unique so the layout tree never sees two siblings share a node. The first +/// sibling keeps its key; each later one is renamed `key#dup1`, `key#dup2`, ... in tree order, so +/// it still draws and keeps a stable identity across builds. Returns what it renamed; a tree +/// without duplicates costs one allocation-free walk. +pub(crate) fn repair(root: &mut El) -> Vec<Duplicate> { + if clean(root) { return Vec::new(); } + let path = root_path(root).to_owned(); + repair_at(root, &path) +} + +/// [`repair`] for a subtree whose root sits at `path`. +pub(crate) fn repair_at(root: &mut El, path: &str) -> Vec<Duplicate> { + if clean(root) { return Vec::new(); } + let found = find(root, path); + if found.is_empty() { return found; } + // Only memos on the way to a duplicate are copied out of the cache. + fn walk(el: &mut El, hashes: &mut Vec<u64>) { + let shared = el.memo_children().is_some_and(|m| m.duplicate_keys); + let siblings = checks_siblings(el) && !unique(shared_children(el), &el.children, hashes); + if shared || siblings { el.expand_memo(); } + if siblings || (shared && el.cold.virtual_estimate.is_none()) { + rename_duplicates(el.children.iter_mut().filter_map(|c| c.key.as_mut())); + } + for child in &mut el.children { + if !clean_with(child, hashes) { walk(child, hashes); } + } + } + walk(root, &mut Vec::new()); + found +} + +/// Prints each duplicate once per key for the life of the process. +pub(crate) fn warn_once(found: &[Duplicate]) { + thread_local! { static WARNED: RefCell<HashSet<String>> = Default::default(); } + if found.is_empty() { return; } + WARNED.with_borrow_mut(|warned| { + for d in found { + if warned.insert(d.key.clone()) { eprintln!("rune: {}; the later one is renamed {:?}", d.message, format!("{}#dupN", d.key)); } + } + }); +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::{col, el}; + + #[test] + fn duplicate_keys_report_both_sources_and_allow_other_parents() { + let first = el().key("card"); + let second = el().key("card"); + let first_source = first.key_location(); + let second_source = second.key_location(); + let tree = col().key("cards").children([first, second]); + let found = warnings(&tree); + assert_eq!(found.len(), 1); + assert!(found[0].contains("\"card\"")); + assert!(found[0].contains(&first_source)); + assert!(found[0].contains(&second_source)); + #[cfg(debug_assertions)] + assert_ne!(first_source, second_source); + assert!(warnings(&col().children([ + col().key("a").child(el().key("card")), + col().key("b").child(el().key("card")), + el(), el(), + ])).is_empty()); + } + + /// A memo's children are checked once, when it builds: a clean memo is skipped and left + /// shared, and repair copies out only the memo holding the duplicate. + #[test] + fn memos_are_checked_when_built_and_only_a_dirty_one_is_expanded() { + fn memo(key: &str, children: Vec<El>) -> El { + let mut root = el().key(key); + let duplicate_keys = memo_children_have_duplicates(&root, &children); + let children = std::rc::Rc::new(crate::memo::Shared { children, focused_input: false, duplicate_keys, has_virtual: false, reusable: false }); + root.memo = Some(std::rc::Rc::new(crate::memo::Built { id: 0, reusable: false, region: false, root: el(), children })); + root + } + let clean_memo = || memo("a", vec![el().key("x"), el().key("y").child(el().key("z"))]); + let tree = col().children([clean_memo(), memo("b", vec![el().key("x")])]); + assert!(clean(&tree)); + let dirty = memo("c", vec![el().key("p").children([el().key("x"), el().key("x")])]); + assert!(dirty.memo_children().unwrap().duplicate_keys); + let mut tree = col().children([clean_memo(), dirty]); + assert!(!clean(&tree)); + let found = repair(&mut tree); + assert_eq!(found.len(), 1, "{found:?}"); + assert!(found[0].message.contains("under \"#0/c/p\""), "{}", found[0].message); + assert!(tree.children[0].memo_children().is_some(), "the clean memo stays shared"); + assert!(tree.children[1].memo_children().is_none()); + let keys: Vec<_> = tree.children[1].children[0].children.iter().map(|c| c.key.clone().unwrap()).collect(); + assert_eq!(keys, ["x", "x#dup1"]); + assert!(clean(&tree)); + // Sibling keys past the short-list compare go through the hashes. + let wide = |dup: bool| col().children((0..40).map(|i| el().key(if dup && i == 39 { "k3".to_string() } else { format!("k{i}") }))); + assert!(clean(&wide(false))); + assert!(!clean(&wide(true))); + } + + /// The per-commit repair of a 3,700-row tree without duplicates allocates nothing. + #[test] + fn repairing_a_tree_without_duplicates_allocates_nothing() { + let row = |i: usize| el().key(format!("row:{i}")).children([el().key("title"), el().key("meta").child(el().key("time"))]); + let mut tree = col().key("root").children([col().key("rows").children((0..3700).map(row)), el().key("footer")]); + assert!(repair(&mut tree).is_empty()); + let before = crate::tooling::test_alloc::allocs(); + let t = crate::time::now(); + assert!(repair(&mut tree).is_empty()); + let elapsed = t.elapsed(); + assert_eq!(crate::tooling::test_alloc::allocs() - before, 0); + eprintln!("clean 3,700-row repair: {elapsed:?}"); + } + + #[test] + fn repair_keeps_the_first_and_renames_later_duplicates_deterministically() { + let keys = |el: &El| el.children.iter().map(|c| c.key.clone().unwrap_or_default()).collect::<Vec<_>>(); + let build = || col().children([ + el().key("row:R-94"), el().key("row:R-94#dup1"), el(), el().key("row:R-94"), el().key("row:R-94"), + col().key("inner").children([el().key("x"), el().key("x")]), + ]); + let mut tree = build(); + let found = repair(&mut tree); + assert_eq!(found.iter().map(|d| d.key.as_str()).collect::<Vec<_>>(), ["row:R-94", "row:R-94", "x"]); + assert_eq!(keys(&tree), ["row:R-94", "row:R-94#dup1", "", "row:R-94#dup2", "row:R-94#dup3", "inner"]); + assert_eq!(keys(&tree.children[5]), ["x", "x#dup1"]); + assert!(warnings(&tree).is_empty()); + let mut again = build(); + repair(&mut again); + assert_eq!(keys(&again), keys(&tree), "the same tree repairs the same way every build"); + let mut clean = col().children([el().key("a"), el().key("b")]); + assert!(repair(&mut clean).is_empty()); + } +} diff --git a/app/vendor/rune/crates/rune/src/input/key_table.rs b/app/vendor/rune/crates/rune/src/input/key_table.rs new file mode 100644 index 0000000..89182be --- /dev/null +++ b/app/vendor/rune/crates/rune/src/input/key_table.rs @@ -0,0 +1,437 @@ +//! Canonical single source of truth for named keys, modifier tables, punctuation key names, +//! and keycap formatting. Shared by winit key mapping, browser DOM key events, headless scripts, +//! key chords, global shortcuts, and the `--keys` overlay. + +use winit::keyboard::NamedKey; + +use super::chord::{ChordKey, ChordMod, KeyPlatform}; +use crate::edit::{Key, Mods}; + +/// One modifier's parse aliases (canonical first) and keycap labels per platform. +#[derive(Clone, Copy, Debug)] +pub(crate) struct ModSpec { + pub chord: ChordMod, + /// Lowercase names, canonical first (`Chord`'s `Display` writes `aliases[0]`). + pub aliases: &'static [&'static str], + /// macOS and `--keys` overlay glyph (`⌃`, `⌥`, `⇧`, `⌘`). + pub glyph: &'static str, + /// Word label off macOS (`"Ctrl"`, `"Alt"`, `"Shift"`, `"Super"`). + pub word: &'static str, + /// Windows `Chord` word label (`"Win"` for Super, otherwise `word`). + pub win_word: &'static str, +} + +/// Modifiers in `Chord`'s canonical `Display` order: `mod`, `ctrl`, `alt`, `shift`, `super`. +pub(crate) const MODS: &[ModSpec] = &[ + ModSpec { chord: ChordMod::Primary, aliases: &["mod", "primary"], glyph: "⌘", word: "Ctrl", win_word: "Ctrl" }, + ModSpec { chord: ChordMod::Ctrl, aliases: &["ctrl", "control"], glyph: "⌃", word: "Ctrl", win_word: "Ctrl" }, + ModSpec { chord: ChordMod::Alt, aliases: &["alt", "option", "opt"], glyph: "⌥", word: "Alt", win_word: "Alt" }, + ModSpec { chord: ChordMod::Shift, aliases: &["shift"], glyph: "⇧", word: "Shift", win_word: "Shift" }, + ModSpec { chord: ChordMod::Super, aliases: &["super", "cmd", "command", "meta", "win", "logo"], glyph: "⌘", word: "Super", win_word: "Win" }, +]; + +/// Metadata for one non-character, non-function named key across every input and display layer. +pub(crate) struct NamedKeySpec { + pub chord: ChordKey, + pub key: Key, + pub winit: NamedKey, + /// DOM `KeyboardEvent.key` name (e.g. `"ArrowLeft"`, `"Enter"`). + pub dom_name: &'static str, + /// Headless script key name (e.g. `"Left"`, `"Enter"`). + pub script_name: &'static str, + /// Lowercase chord / shortcut aliases, canonical first. + pub aliases: &'static [&'static str], + /// macOS keycap label. + pub mac_label: &'static str, + /// Non-macOS `Chord` keycap label. + pub pc_label: &'static str, + /// Non-macOS `Shortcut` keycap label (`"Return"` for Enter, else `pc_label`). + pub shortcut_pc_label: &'static str, + /// Compact `--keys` overlay cap label. + pub overlay_label: &'static str, +} + +impl NamedKeySpec { + const fn new( + chord: ChordKey, + key: Key, + winit: NamedKey, + dom_name: &'static str, + aliases: &'static [&'static str], + mac_label: &'static str, + pc_label: &'static str, + ) -> Self { + Self { + chord, + key, + winit, + dom_name, + script_name: dom_name, + aliases, + mac_label, + pc_label, + shortcut_pc_label: pc_label, + overlay_label: mac_label, + } + } + + const fn script(mut self, name: &'static str) -> Self { self.script_name = name; self } + const fn shortcut_pc(mut self, label: &'static str) -> Self { self.shortcut_pc_label = label; self } + const fn overlay(mut self, label: &'static str) -> Self { self.overlay_label = label; self } +} + +/// Every non-function named key Rune handles. +pub(crate) const NAMED_KEYS: &[NamedKeySpec] = &[ + NamedKeySpec::new(ChordKey::Enter, Key::Enter, NamedKey::Enter, "Enter", &["enter", "return"], "↩", "Enter").shortcut_pc("Return"), + NamedKeySpec::new(ChordKey::Tab, Key::Tab, NamedKey::Tab, "Tab", &["tab"], "⇥", "Tab"), + NamedKeySpec::new(ChordKey::Escape, Key::Escape, NamedKey::Escape, "Escape", &["escape", "esc"], "⎋", "Esc"), + NamedKeySpec::new(ChordKey::Backspace, Key::Backspace, NamedKey::Backspace, "Backspace", &["backspace"], "⌫", "Backspace"), + NamedKeySpec::new(ChordKey::Delete, Key::Delete, NamedKey::Delete, "Delete", &["delete", "del"], "⌦", "Delete"), + NamedKeySpec::new(ChordKey::Insert, Key::Insert, NamedKey::Insert, "Insert", &["insert", "ins"], "Insert", "Insert").overlay("Ins"), + NamedKeySpec::new(ChordKey::Home, Key::Home, NamedKey::Home, "Home", &["home"], "↖", "Home"), + NamedKeySpec::new(ChordKey::End, Key::End, NamedKey::End, "End", &["end"], "↘", "End"), + NamedKeySpec::new(ChordKey::PageUp, Key::PageUp, NamedKey::PageUp, "PageUp", &["pageup", "pgup"], "⇞", "Page Up"), + NamedKeySpec::new(ChordKey::PageDown, Key::PageDown, NamedKey::PageDown, "PageDown", &["pagedown", "pgdn"], "⇟", "Page Down"), + NamedKeySpec::new(ChordKey::Left, Key::Left, NamedKey::ArrowLeft, "ArrowLeft", &["left", "arrowleft"], "←", "←").script("Left"), + NamedKeySpec::new(ChordKey::Right, Key::Right, NamedKey::ArrowRight, "ArrowRight", &["right", "arrowright"], "→", "→").script("Right"), + NamedKeySpec::new(ChordKey::Up, Key::Up, NamedKey::ArrowUp, "ArrowUp", &["up", "arrowup"], "↑", "↑").script("Up"), + NamedKeySpec::new(ChordKey::Down, Key::Down, NamedKey::ArrowDown, "ArrowDown", &["down", "arrowdown"], "↓", "↓").script("Down"), + NamedKeySpec::new(ChordKey::ContextMenu, Key::ContextMenu, NamedKey::ContextMenu, "ContextMenu", &["contextmenu", "menu"], "Menu", "Menu").overlay("≣"), + NamedKeySpec::new(ChordKey::PrintScreen, Key::PrintScreen, NamedKey::PrintScreen, "PrintScreen", &["printscreen", "prtsc"], "Print Screen", "Print Screen").overlay("PrtSc"), + NamedKeySpec::new(ChordKey::ScrollLock, Key::ScrollLock, NamedKey::ScrollLock, "ScrollLock", &["scrolllock"], "Scroll Lock", "Scroll Lock").overlay("ScrLk"), + NamedKeySpec::new(ChordKey::Pause, Key::Pause, NamedKey::Pause, "Pause", &["pause", "break"], "Pause", "Pause"), +]; + +const WINIT_FUNCTION_KEYS: &[NamedKey] = &[ + NamedKey::F1, NamedKey::F2, NamedKey::F3, NamedKey::F4, NamedKey::F5, NamedKey::F6, + NamedKey::F7, NamedKey::F8, NamedKey::F9, NamedKey::F10, NamedKey::F11, NamedKey::F12, + NamedKey::F13, NamedKey::F14, NamedKey::F15, NamedKey::F16, NamedKey::F17, NamedKey::F18, + NamedKey::F19, NamedKey::F20, NamedKey::F21, NamedKey::F22, NamedKey::F23, NamedKey::F24, +]; + +/// Printable punctuation keys whose stable name differs from their symbol. +pub(crate) const PUNCTUATION: &[(char, &str, &str)] = &[ + ('-', "minus", "-"), + ('=', "equal", "="), + (',', "comma", ","), + ('.', "period", "."), + ('/', "slash", "/"), + (';', "semicolon", ";"), + ('\'', "quote", "'"), + ('[', "bracketleft", "["), + (']', "bracketright", "]"), + ('\\', "backslash", "\\"), + ('`', "backquote", "`"), +]; + +// ── Modifiers ──────────────────────────────────────────────────────────────── + +/// Builds `Mods` from raw platform modifier keys: `cmd` follows Super on macOS, Ctrl on +/// Windows/Linux, and either Super or Ctrl on `wasm32`. +pub(crate) const fn mods_from_keys(shift: bool, ctrl: bool, alt: bool, logo: bool) -> Mods { + let cmd = if cfg!(target_arch = "wasm32") { + logo || ctrl + } else if cfg!(target_os = "macos") { + logo + } else { + ctrl + }; + Mods { shift, cmd, alt, ctrl, logo } +} + +/// Builds `Mods` for browser DOM bridge events, where either Meta/Super or Ctrl is `cmd` +/// regardless of the host target running tests. +#[cfg_attr(not(target_arch = "wasm32"), allow(dead_code))] +pub(crate) const fn web_mods(shift: bool, ctrl: bool, alt: bool, logo: bool) -> Mods { + Mods { shift, cmd: logo || ctrl, alt, ctrl, logo } +} + +/// Builds `Mods` for a headless script step: `"cmd"` sets the platform's primary key alongside +/// `cmd`, so `"cmd": true` matches Super on macOS and Ctrl elsewhere. +pub(crate) const fn mods_from_script(shift: bool, ctrl: bool, alt: bool, logo: bool, cmd: bool) -> Mods { + let mac = cfg!(target_os = "macos"); + Mods { shift, cmd, alt, ctrl: ctrl || (cmd && !mac), logo: logo || (cmd && mac) } +} + +pub(crate) const fn mod_spec(m: ChordMod) -> &'static ModSpec { + match m { + ChordMod::Primary => &MODS[0], + ChordMod::Ctrl => &MODS[1], + ChordMod::Alt => &MODS[2], + ChordMod::Shift => &MODS[3], + ChordMod::Super => &MODS[4], + } +} + +/// Parses a lowercased modifier name (`"mod"`, `"ctrl"`, `"option"`, `"cmd"`, ...). +pub(crate) fn modifier_named(name: &str) -> Option<ChordMod> { + MODS.iter().find(|m| m.aliases.contains(&name)).map(|m| m.chord) +} + +/// A modifier's keycap label for `Chord::keycaps_on(platform)`. +pub(crate) fn modifier_label(m: ChordMod, platform: KeyPlatform) -> &'static str { + let s = mod_spec(m); + match platform { + KeyPlatform::Mac => s.glyph, + KeyPlatform::Windows => s.win_word, + KeyPlatform::Linux => s.word, + } +} + +fn held_mod_specs(m: Mods) -> impl Iterator<Item = &'static ModSpec> { + let mac = cfg!(target_os = "macos"); + [ + (m.ctrl || (!mac && m.cmd), ChordMod::Ctrl), + (m.alt, ChordMod::Alt), + (m.shift, ChordMod::Shift), + (m.logo || (mac && m.cmd), ChordMod::Super), + ] + .into_iter() + .filter_map(|(on, cm)| on.then(|| mod_spec(cm))) +} + +/// Apple's order: Control, Option, Shift, Command (`⌃⌥⇧⌘`), for the `--keys` overlay. +/// `cmd` folds into Control off macOS and Command on macOS. +pub(crate) fn modifier_glyphs(m: Mods) -> String { + held_mod_specs(m).map(|s| s.glyph).collect() +} + +/// Keycaps for held modifiers (`rune::modifier_keycaps`): glyphs on macOS, words elsewhere. +pub(crate) fn modifier_keycaps(m: Mods) -> Vec<String> { + let mac = cfg!(target_os = "macos"); + held_mod_specs(m).map(|s| if mac { s.glyph } else { s.word }.to_owned()).collect() +} + +// ── Named & Function Keys ──────────────────────────────────────────────────── + +/// Parses `"F1"`..`"F24"` (with `prefix = 'F'`) or `"f1"`..`"f24"` (with `prefix = 'f'`), +/// rejecting `"F0"`, `"F01"`, `"F+1"`, and `"F25"`. +pub(crate) fn parse_function_key(s: &str, prefix: char) -> Option<u8> { + let digits = s.strip_prefix(prefix)?; + if digits.is_empty() || digits.starts_with(['0', '+']) { return None; } + let n: u8 = digits.parse().ok()?; + (1..=24).contains(&n).then_some(n) +} + +/// Maps a winit `NamedKey` to a Rune `Key`. +pub(crate) fn key_from_winit(n: NamedKey) -> Option<Key> { + if n == NamedKey::Space { return Some(Key::Text(" ".into())); } + if let Some(i) = WINIT_FUNCTION_KEYS.iter().position(|&f| f == n) { + return Some(Key::Function((i + 1) as u8)); + } + NAMED_KEYS.iter().find(|k| k.winit == n).map(|k| k.key.clone()) +} + +/// Maps a DOM `KeyboardEvent.key` or headless script key name (including `"F1"`–`"F24"`) to a +/// Rune `Key`. Case-sensitive (`"Enter"`, `"ArrowLeft"` / `"Left"`, `"F1"`..`"F24"`). +pub(crate) fn named_key_from_str(name: &str) -> Option<Key> { + if let Some(n) = parse_function_key(name, 'F') { + return Some(Key::Function(n)); + } + NAMED_KEYS.iter().find(|k| k.dom_name == name || k.script_name == name).map(|k| k.key.clone()) +} + +fn named_by_alias(alias: &str) -> Option<&'static NamedKeySpec> { + NAMED_KEYS.iter().find(|k| k.aliases.contains(&alias)) +} + +/// Lowercase chord / shortcut alias to `ChordKey` (non-function named keys). +pub(crate) fn chord_key_named(name: &str) -> Option<ChordKey> { + named_by_alias(name).map(|k| k.chord) +} + +/// Converts a named or function `Key` to its `ChordKey`. +pub(crate) fn chord_key_from_key(key: &Key) -> Option<ChordKey> { + if let Key::Function(n) = key { return Some(ChordKey::Function(*n)); } + NAMED_KEYS.iter().find(|k| k.key == *key).map(|k| k.chord) +} + +/// Canonical lowercase name for a named `ChordKey` (`Chord`'s `Display`). +pub(crate) fn chord_key_canonical(key: ChordKey) -> &'static str { + NAMED_KEYS.iter().find(|k| k.chord == key).map_or("", |k| k.aliases[0]) +} + +/// Keycap label for a named `ChordKey` on `platform` (`Chord::keycaps_on`). +pub(crate) fn chord_key_label(key: ChordKey, platform: KeyPlatform) -> &'static str { + let mac = platform == KeyPlatform::Mac; + NAMED_KEYS.iter().find(|k| k.chord == key).map_or("", |k| if mac { k.mac_label } else { k.pc_label }) +} + +/// Normalizes a lowercase named-key alias (`"esc"` → `"escape"`, `"arrowleft"` → `"left"`). +pub(crate) fn canonical_named_alias(alias: &str) -> Option<&'static str> { + named_by_alias(alias).map(|k| k.aliases[0]) +} + +/// Keycap label for a `Shortcut`'s stable lowercase named/function key (`"space"`, `"f5"`, +/// `"enter"`, `"left"`, ...). Returns `None` for letters, digits, and punctuation. +pub(crate) fn shortcut_named_label(name: &str) -> Option<String> { + if name == "space" { return Some("Space".into()); } + if let Some(n) = parse_function_key(name, 'f') { return Some(format!("F{n}")); } + let spec = named_by_alias(name)?; + Some(if cfg!(target_os = "macos") { spec.mac_label } else { spec.shortcut_pc_label }.into()) +} + +/// Compact cap glyph for a named `Key` in the `--keys` overlay. +pub(crate) fn overlay_key_label(key: &Key) -> Option<&'static str> { + NAMED_KEYS.iter().find(|k| k.key == *key).map(|k| k.overlay_label) +} + +/// Compact cap label for a `Shortcut`'s stable lowercase key name in the `--keys` overlay. +pub(crate) fn overlay_named_label(name: &str) -> String { + if name == "space" { return "␣".to_owned(); } + if let Some(spec) = named_by_alias(name) { return spec.overlay_label.to_owned(); } + if let Some(sym) = punctuation_symbol(name) { return sym.to_owned(); } + title_case(name) +} + +// ── Punctuation & Character Names ──────────────────────────────────────────── + +/// Parses a lowercased character name in a `Chord` string (`"space"`, `"plus"`, `"minus"`, ...). +pub(crate) fn char_named(name: &str) -> Option<char> { + match name { + "space" => Some(' '), + "plus" => Some('+'), + _ => PUNCTUATION.iter().find(|p| p.1 == name).map(|p| p.0), + } +} + +/// Canonical name for a character in `Chord`'s `Display` (`' '` → `"space"`, `'+'` → `"plus"`, +/// `','` → `"comma"`, ...). +pub(crate) fn char_name(c: char) -> Option<&'static str> { + match c { + ' ' => Some("space"), + '+' => Some("plus"), + _ => PUNCTUATION.iter().find(|p| p.0 == c).map(|p| p.1), + } +} + +/// Maps a stable punctuation name (`"minus"`, `"bracketleft"`) to its US symbol (`"-"`, `"["`). +pub(crate) fn punctuation_symbol(name: &str) -> Option<&'static str> { + PUNCTUATION.iter().find(|p| p.1 == name).map(|p| p.2) +} + +/// Maps a US punctuation symbol (`"-"`, `"["`) to its stable name (`"minus"`, `"bracketleft"`). +pub(crate) fn punctuation_name(sym: &str) -> Option<&'static str> { + PUNCTUATION.iter().find(|p| p.2 == sym).map(|p| p.1) +} + +// ── Keycap Capitalization ──────────────────────────────────────────────────── + +/// Capitalizes a single character for a keycap ("k" → "K"), leaving characters whose uppercase +/// isn't one reversible character ("ß", Turkish "ı") untouched. +fn cap_char(c: char) -> char { + let mut upper = c.to_uppercase(); + let (Some(u), None) = (upper.next(), upper.next()) else { return c }; + let mut lower = u.to_lowercase(); + if (lower.next(), lower.next()) == (Some(c), None) { u } else { c } +} + +/// Capitalizes a single-character keycap label ("k" → "K"); multi-character labels stay as given. +pub(crate) fn capital_keycap(label: &str) -> String { + let mut chars = label.chars(); + match (chars.next(), chars.next()) { + (Some(c), None) => cap_char(c).to_string(), + _ => label.to_owned(), + } +} + +/// Title-cases a keycap label ("k" → "K", "capslock" → "Capslock", "SPACE" → "Space"), +/// leaving characters whose capital doesn't roundtrip ("ß", Turkish "ı") as typed. +pub(crate) fn title_case(name: &str) -> String { + let mut chars = name.chars(); + let Some(first) = chars.next() else { return String::new() }; + format!("{}{}", cap_char(first), chars.as_str().to_lowercase()) +} + +#[cfg(test)] +mod tests { + use std::collections::HashSet; + + use super::*; + + #[test] + fn tables_have_unique_entries_and_consistent_mappings() { + let mut mod_aliases = HashSet::new(); + for (i, m) in MODS.iter().enumerate() { + assert_eq!(mod_spec(m.chord).chord, m.chord); + assert_eq!(MODS[i].chord, m.chord); + assert!(!m.aliases.is_empty()); + for &a in m.aliases { + assert!(mod_aliases.insert(a), "duplicate modifier alias: {a}"); + assert_eq!(modifier_named(a), Some(m.chord)); + } + } + + let mut key_aliases = HashSet::new(); + let mut chords = HashSet::new(); + let mut winit_keys = HashSet::new(); + for k in NAMED_KEYS { + assert!(chords.insert(k.chord), "duplicate ChordKey: {:?}", k.chord); + assert!(winit_keys.insert(k.winit), "duplicate NamedKey: {:?}", k.winit); + assert_eq!(key_from_winit(k.winit), Some(k.key.clone())); + assert_eq!(named_key_from_str(k.dom_name), Some(k.key.clone())); + assert_eq!(named_key_from_str(k.script_name), Some(k.key.clone())); + assert_eq!(chord_key_from_key(&k.key), Some(k.chord)); + assert_eq!(chord_key_canonical(k.chord), k.aliases[0]); + assert_eq!(overlay_key_label(&k.key), Some(k.overlay_label)); + assert_eq!(overlay_named_label(k.aliases[0]), k.overlay_label); + for &a in k.aliases { + assert!(key_aliases.insert(a), "duplicate key alias: {a}"); + assert_eq!(chord_key_named(a), Some(k.chord)); + assert_eq!(canonical_named_alias(a), Some(k.aliases[0])); + } + } + + assert_eq!(WINIT_FUNCTION_KEYS.len(), 24); + for n in 1..=24u8 { + let f_upper = format!("F{n}"); + let f_lower = format!("f{n}"); + assert_eq!(key_from_winit(WINIT_FUNCTION_KEYS[(n - 1) as usize]), Some(Key::Function(n))); + assert_eq!(named_key_from_str(&f_upper), Some(Key::Function(n))); + assert_eq!(parse_function_key(&f_upper, 'F'), Some(n)); + assert_eq!(parse_function_key(&f_lower, 'f'), Some(n)); + assert_eq!(shortcut_named_label(&f_lower), Some(f_upper)); + } + for bad in ["F", "F0", "F01", "F+1", "F25", "f1"] { + assert_eq!(named_key_from_str(bad), None, "should reject {bad:?}"); + } + } + + #[test] + fn punctuation_and_keycap_formatting_match_every_platform() { + for &(ch, name, sym) in PUNCTUATION { + assert_eq!(char_named(name), Some(ch)); + assert_eq!(char_name(ch), Some(name)); + assert_eq!(punctuation_symbol(name), Some(sym)); + assert_eq!(punctuation_name(sym), Some(name)); + assert_eq!(overlay_named_label(name), sym); + } + assert_eq!(char_named("space"), Some(' ')); + assert_eq!(char_named("plus"), Some('+')); + assert_eq!(char_name(' '), Some("space")); + assert_eq!(char_name('+'), Some("plus")); + + assert_eq!(modifier_label(ChordMod::Super, KeyPlatform::Mac), "⌘"); + assert_eq!(modifier_label(ChordMod::Super, KeyPlatform::Windows), "Win"); + assert_eq!(modifier_label(ChordMod::Super, KeyPlatform::Linux), "Super"); + assert_eq!(chord_key_label(ChordKey::Enter, KeyPlatform::Mac), "↩"); + assert_eq!(chord_key_label(ChordKey::Enter, KeyPlatform::Windows), "Enter"); + assert_eq!(shortcut_named_label("enter").as_deref(), Some(if cfg!(target_os = "macos") { "↩" } else { "Return" })); + assert_eq!(overlay_named_label("space"), "␣"); + assert_eq!(overlay_named_label("insert"), "Ins"); + assert_eq!(overlay_named_label("contextmenu"), "≣"); + + assert_eq!(capital_keycap("k"), "K"); + assert_eq!(capital_keycap("K"), "K"); + assert_eq!(capital_keycap("ß"), "ß"); + assert_eq!(capital_keycap("ı"), "ı"); + assert_eq!(capital_keycap("/"), "/"); + assert_eq!(capital_keycap("Space"), "Space"); + assert_eq!(title_case("k"), "K"); + assert_eq!(title_case("ß"), "ß"); + assert_eq!(title_case("ı"), "ı"); + assert_eq!(title_case("capslock"), "Capslock"); + assert_eq!(title_case("SPACE"), "Space"); + assert_eq!(title_case(""), ""); + } +} diff --git a/app/vendor/rune/crates/rune/src/input/keycaps.rs b/app/vendor/rune/crates/rune/src/input/keycaps.rs new file mode 100644 index 0000000..c059441 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/input/keycaps.rs @@ -0,0 +1,351 @@ +//! `--keys` and `--pointer`: screencast-style keycaps and click ripples drawn over headless +//! frames. A separate runtime draws them, so they never enter the app's tree. +//! +//! That runtime is a second instance of `Runtime` (about 1.46 MB of code in an app's release exe), +//! so a release build has the overlay only with Rune's `keys-overlay` feature; debug builds always +//! do. Without it `--keys` and `--pointer` stop the run with a message naming the feature. +#![cfg_attr(not(any(debug_assertions, feature = "keys-overlay")), allow(dead_code, unused_imports))] + +use super::key_table; +use crate::edit::{Key, KeyEvent, Mods}; +use crate::el::{El, col, el, text}; +use crate::runtime::{Cx, Env, Runtime}; +use crate::{Color, Transition, oklcha}; + +/// Typing within this many seconds of the last key joins its cap. +const BURST: f64 = 1.0; +/// A cap stays this long after its last key, then fades out. +const HOLD: f64 = 1.5; +/// Caps on screen at once; older ones leave early. +const SHOWN: usize = 3; +/// Typed characters a cap shows before eliding the oldest. +const TYPED: usize = 24; +/// A ripple holds this long before it expands and fades. +const RIPPLE: f64 = 0.12; +const MARGIN: f32 = 24.0; + +/// Where the caps sit. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(crate) enum Corner { + #[default] + BottomLeft, + Bottom, + BottomRight, + TopLeft, + Top, + TopRight, +} + +impl Corner { + pub(crate) fn parse(s: &str) -> Option<Corner> { + Some(match s { + "bottom-left" => Corner::BottomLeft, + "bottom" => Corner::Bottom, + "bottom-right" => Corner::BottomRight, + "top-left" => Corner::TopLeft, + "top" => Corner::Top, + "top-right" => Corner::TopRight, + _ => return None, + }) + } +} + +/// One keycap: a burst of typing, or a chord with its repeat count. +#[derive(Clone, Debug, PartialEq)] +pub(crate) struct Cap { + pub id: u64, + text: String, + typing: bool, + count: u32, + last: f64, +} + +impl Cap { + pub(crate) fn label(&self) -> String { + if self.typing { + if self.text.trim().is_empty() { return "␣".repeat(self.text.chars().count().min(TYPED)); } + let n = self.text.chars().count(); + if n <= TYPED { return self.text.clone(); } + return format!("…{}", self.text.chars().skip(n - (TYPED - 1)).collect::<String>()); + } + if self.count > 1 { format!("{} ×{}", self.text, self.count) } else { self.text.clone() } + } +} + +/// Groups key presses into caps. +#[derive(Default)] +pub(crate) struct Keycaps { + caps: Vec<Cap>, + next: u64, +} + +impl Keycaps { + /// A logical key from the script. + pub(crate) fn key(&mut self, t: f64, ev: &KeyEvent) { + if matches!(ev.key, Key::Modifier { pressed: false, .. }) { return; } + let (label, typing) = key_label(ev); + self.push(t, label, typing); + } + + /// A chord (a global shortcut or a physical key press). + pub(crate) fn chord(&mut self, t: f64, shortcut: &crate::Shortcut) { + let name = shortcut.to_string(); + let key = name.rsplit('+').next().unwrap_or_default(); + self.push(t, format!("{}{}", key_table::modifier_glyphs(shortcut.modifiers()), key_table::overlay_named_label(key)), false); + } + + fn push(&mut self, t: f64, label: String, typing: bool) { + if let Some(last) = self.caps.last_mut() + && t - last.last <= BURST + && last.typing == typing + && (typing || last.text == label) + { + if typing { last.text.push_str(&label) } else { last.count += 1 } + last.last = t; + return; + } + self.caps.push(Cap { id: self.next, text: label, typing, count: 1, last: t }); + self.next += 1; + } + + /// The caps on screen at `t`, oldest first; forgets those that have left. + pub(crate) fn visible(&mut self, t: f64) -> Vec<Cap> { + self.caps.retain(|c| t - c.last < HOLD); + let skip = self.caps.len().saturating_sub(SHOWN); + self.caps[skip..].to_vec() + } +} + +/// The cap text for a key, and whether it is plain typing (no ⌘, ⌃ or ⌥). +fn key_label(ev: &KeyEvent) -> (String, bool) { + let m = ev.mods; + let chord = m.cmd || m.ctrl || m.alt || m.logo; + let key = match &ev.key { + Key::Text(s) if !chord => return (s.clone(), true), + Key::Text(s) if s == " " => "␣".to_owned(), + Key::Text(s) => key_table::title_case(s), + Key::Command(c) => { + let mods = Mods { cmd: true, ..m }; + let label = if *c == ' ' { "␣".to_owned() } else { key_table::title_case(&c.to_string()) }; + return (format!("{}{label}", key_table::modifier_glyphs(mods)), false); + } + Key::Function(n) => format!("F{n}"), + // Its own flag is already in `mods`. + Key::Modifier { modifier: crate::Modifier::Fn, .. } => "fn".into(), + Key::Modifier { .. } => return (key_table::modifier_glyphs(m), false), + other => key_table::overlay_key_label(other).unwrap_or("").to_owned(), + }; + (format!("{}{key}", key_table::modifier_glyphs(m)), false) +} + +#[cfg(any(debug_assertions, feature = "keys-overlay"))] +#[derive(Clone, Default, PartialEq)] +pub(crate) struct Scene { + caps: Vec<(u64, String)>, + ripples: Vec<(u64, f32, f32)>, + corner: Corner, + dark: bool, +} + +/// `--keys-theme`: dark or light caps, or (None) whichever matches the app's theme. +pub(crate) fn parse_theme(s: &str) -> Option<Option<bool>> { + Some(match s { + "auto" => None, + "light" => Some(false), + "dark" => Some(true), + _ => return None, + }) +} + +#[cfg(any(debug_assertions, feature = "keys-overlay"))] +/// The overlay's own runtime: caps and ripples as keyed elements whose enter and exit run on +/// the motion system's springs. +pub(crate) struct Overlay { + rt: Runtime<Scene>, + keys: Option<Keycaps>, + ripples: Option<(Vec<(u64, f32, f32, f64)>, u64)>, + theme: Option<bool>, +} + +#[cfg(any(debug_assertions, feature = "keys-overlay"))] +impl Overlay { + pub(crate) fn new(size: (f32, f32), scale: f32, keys: Option<Corner>, theme: Option<bool>, pointer: bool) -> Overlay { + let scene = Scene { corner: keys.unwrap_or_default(), ..Scene::default() }; + let rt = Runtime::new(scene, view, size, Env::new(true, scale)); + Overlay { rt, keys: keys.map(|_| Keycaps::default()), ripples: pointer.then(|| (Vec::new(), 0)), theme } + } + + pub(crate) fn set_srgb_blend(&mut self, enabled: bool) { + self.rt.set_srgb_blend(enabled); + } + + pub(crate) fn key(&mut self, t: f64, ev: &KeyEvent) { + if let Some(k) = &mut self.keys { k.key(t, ev) } + } + + pub(crate) fn chord(&mut self, t: f64, shortcut: &crate::Shortcut) { + if let Some(k) = &mut self.keys { k.chord(t, shortcut) } + } + + pub(crate) fn press(&mut self, t: f64, x: f32, y: f32) { + if let Some((ripples, next)) = &mut self.ripples { + ripples.push((*next, x, y, t)); + *next += 1; + } + } + + /// Advances to `t` (`dt` after the last frame) over an app that is `app_dark`, and returns + /// the instances to draw. + pub(crate) fn frame(&mut self, t: f64, dt: f64, app_dark: bool) -> &mut Runtime<Scene> { + let dark = self.theme.unwrap_or(app_dark); + let caps = self.keys.as_mut().map(|k| k.visible(t).iter().map(|c| (c.id, c.label())).collect()).unwrap_or_default(); + let ripples = match &mut self.ripples { + Some((r, _)) => { r.retain(|&(.., t0)| t - t0 < RIPPLE); r.iter().map(|&(id, x, y, _)| (id, x, y)).collect() } + None => Vec::new(), + }; + let s = &self.rt.state; + if s.caps != caps || s.ripples != ripples || s.dark != dark { + self.rt.update(move |s, _| { s.caps = caps; s.ripples = ripples; s.dark = dark; }); + } + self.rt.frame(dt); + &mut self.rt + } +} + +#[cfg(any(debug_assertions, feature = "keys-overlay"))] +fn view(s: &Scene, _: &mut Cx<Scene>) -> El { + let caps = col().gap(8.0).children(s.caps.iter().map(|(id, label)| cap(*id, label, s.dark))); + let m = Some(MARGIN); + let caps = match s.corner { + Corner::BottomLeft => caps.items_start().pin(m, None, None, m), + Corner::Bottom => caps.items_center().pin(Some(0.0), None, Some(0.0), m), + Corner::BottomRight => caps.items_end().pin(None, None, m, m), + Corner::TopLeft => caps.items_start().pin(m, m, None, None), + Corner::Top => caps.items_center().pin(Some(0.0), m, Some(0.0), None), + Corner::TopRight => caps.items_end().pin(None, m, m, None), + }; + el().w_full().h_full().child(caps).children(s.ripples.iter().map(|&(id, x, y)| ripple(id, x, y))) +} + +#[cfg(any(debug_assertions, feature = "keys-overlay"))] +fn cap(id: u64, label: &str, dark: bool) -> El { + // Blending is linear, so a dark cap needs a high alpha to read as dark over light content. + let (fill, border, ink, shadow) = if dark { + (oklcha(0.22, 0.0, 0.0, 0.96), oklcha(1.0, 0.0, 0.0, 0.16), Color::WHITE, 0.4) + } else { + (oklcha(0.99, 0.0, 0.0, 0.96), oklcha(0.0, 0.0, 0.0, 0.12), oklcha(0.2, 0.0, 0.0, 1.0), 0.18) + }; + el().key(format!("cap-{id}")).px(12.0).py(6.0).radius(9.0) + .fill(fill) + .border(1.0, border) + .shadow(4.0, 14.0, oklcha(0.0, 0.0, 0.0, shadow)) + .child(text(label).font(crate::TextStyle::new(18.0, 600.0)).color(ink)) + // Leaving caps keep their slot as it collapses, so the rest slide instead of jumping. + .transition(Transition::asymmetric(Transition::scale(0.85), Transition::opacity()).hold_layout()) +} + +#[cfg(any(debug_assertions, feature = "keys-overlay"))] +fn ripple(id: u64, x: f32, y: f32) -> El { + const R: f32 = 14.0; + el().key(format!("ripple-{id}")).absolute(x - R, y - R).size(2.0 * R, 2.0 * R).radius(R) + // Mid grey with a white rim and a dark halo reads over light and dark apps alike. + .fill(oklcha(0.5, 0.0, 0.0, 0.3)) + .border(2.0, oklcha(1.0, 0.0, 0.0, 0.95)) + .shadow(0.0, 6.0, oklcha(0.0, 0.0, 0.0, 0.55)) + .transition(Transition::asymmetric(Transition::scale(0.4), Transition::scale(2.2))) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn typed(c: &str) -> KeyEvent { KeyEvent { key: Key::Text(c.into()), mods: Mods::default() } } + + fn labels(k: &mut Keycaps, t: f64) -> Vec<String> { k.visible(t).iter().map(Cap::label).collect() } + + #[test] + fn bursts_of_typing_share_one_cap_and_chords_get_their_own() { + let mut k = Keycaps::default(); + for (i, c) in "Hi there".chars().enumerate() { k.key(0.1 * i as f64, &typed(&c.to_string())); } + assert_eq!(labels(&mut k, 0.8), ["Hi there"]); + let cmd_k = KeyEvent { key: Key::Command('k'), mods: Mods { cmd: true, ..Mods::default() } }; + k.key(0.9, &cmd_k); + k.key(1.0, &typed("x")); + let cmd_k = if cfg!(target_os = "macos") { "⌘K" } else { "⌃K" }; + assert_eq!(labels(&mut k, 1.0), ["Hi there", cmd_k, "x"], "a chord ends the burst"); + // A pause longer than the burst starts a new cap. + k.key(2.1, &typed("y")); + assert_eq!(labels(&mut k, 2.1), [cmd_k, "x", "y"], "and the oldest leaves early: at most three show"); + assert_eq!(labels(&mut k, 4.1), Vec::<String>::new(), "every cap fades once its hold ends"); + } + + #[test] + fn repeated_chords_count_and_named_keys_use_glyphs() { + let mut k = Keycaps::default(); + let down = KeyEvent { key: Key::Down, mods: Mods::default() }; + for i in 0..3 { k.key(0.2 * i as f64, &down); } + let shift_tab = KeyEvent { key: Key::Tab, mods: Mods { shift: true, ..Mods::default() } }; + k.key(0.6, &shift_tab); + let all = KeyEvent { key: Key::Text(" ".into()), mods: Mods { ctrl: true, alt: true, shift: true, cmd: true, logo: true } }; + k.key(0.7, &all); + assert_eq!(labels(&mut k, 0.7), ["↓ ×3", "⇧⇥", "⌃⌥⇧⌘␣"]); + k.chord(0.8, &"cmd+space".parse().unwrap()); + k.key(0.9, &KeyEvent { key: Key::Escape, mods: Mods::default() }); + k.key(1.0, &KeyEvent { key: Key::Enter, mods: Mods::default() }); + // `cmd` in a `Shortcut` is always `Super` (`⌘` in the overlay); `mod` is the platform primary. + assert_eq!(labels(&mut k, 1.0), ["⌘␣", "⎋", "↩"]); + k.chord(1.1, &"mod+space".parse().unwrap()); + let primary = if cfg!(target_os = "macos") { "⌘" } else { "⌃" }; + assert_eq!(labels(&mut k, 1.1), ["⎋".into(), "↩".into(), format!("{primary}␣")]); + } + + #[test] + fn key_names_are_title_case_and_letters_capitals() { + let mut k = Keycaps::default(); + k.chord(0.0, &"alt+shift+k".parse().unwrap()); + k.chord(0.1, &"alt+f12".parse().unwrap()); + let ctrl = |s: &str| KeyEvent { key: Key::Text(s.into()), mods: Mods { ctrl: true, ..Mods::default() } }; + k.key(0.2, &ctrl("SPACE")); + assert_eq!(labels(&mut k, 0.2), ["⌥⇧K", "⌥F12", "⌃Space"]); + assert_eq!((key_table::title_case("ı"), key_table::title_case("ß"), key_table::title_case("capslock")), ("ı".into(), "ß".into(), "Capslock".into())); + } + + #[test] + fn long_typing_elides_its_start_and_spaces_alone_show_as_glyphs() { + let mut k = Keycaps::default(); + for (i, c) in "the quick brown fox jumps over".chars().enumerate() { k.key(0.05 * i as f64, &typed(&c.to_string())); } + assert_eq!(labels(&mut k, 1.5), ["…ck brown fox jumps over"]); + let mut k = Keycaps::default(); + k.key(0.0, &typed(" ")); + assert_eq!(labels(&mut k, 0.0), ["␣"]); + } + + #[test] + fn corners_and_themes_parse() { + assert_eq!(Corner::parse("top-right"), Some(Corner::TopRight)); + assert_eq!(Corner::parse("middle"), None); + assert_eq!((parse_theme("auto"), parse_theme("light"), parse_theme("dark"), parse_theme("blue")), + (Some(None), Some(Some(false)), Some(Some(true)), None)); + } +} + +/// Without `keys-overlay` in a release build: no overlay can exist, so its runtime isn't linked. +#[cfg(not(any(debug_assertions, feature = "keys-overlay")))] +pub(crate) struct Overlay(std::convert::Infallible); + +#[cfg(not(any(debug_assertions, feature = "keys-overlay")))] +impl Overlay { + pub(crate) fn new(_: (f32, f32), _: f32, _: Option<Corner>, _: Option<bool>, _: bool) -> Overlay { + crate::tooling::die("--keys and --pointer need Rune's `keys-overlay` feature in a release build (rune = { ..., features = [\"keys-overlay\"] }); debug builds always have it") + } + pub(crate) fn set_srgb_blend(&mut self, _: bool) { match self.0 {} } + pub(crate) fn key(&mut self, _: f64, _: &KeyEvent) { match self.0 {} } + pub(crate) fn chord(&mut self, _: f64, _: &crate::Shortcut) { match self.0 {} } + pub(crate) fn press(&mut self, _: f64, _: f32, _: f32) { match self.0 {} } + pub(crate) fn frame(&mut self, _: f64, _: f64, _: bool) -> &mut Runtime<Scene> { match self.0 {} } +} + +/// The type the overlay's frame names; never built without the feature. +#[cfg(not(any(debug_assertions, feature = "keys-overlay")))] +#[derive(Clone, Default, PartialEq)] +pub(crate) struct Scene; \ No newline at end of file diff --git a/app/vendor/rune/crates/rune/src/input/physical_input.rs b/app/vendor/rune/crates/rune/src/input/physical_input.rs new file mode 100644 index 0000000..8d82ea7 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/input/physical_input.rs @@ -0,0 +1,23 @@ +//! Physical input is queued with its logical fallback, so a preceding click can claim it. +use crate::{Mods, PhysicalKeyCode}; + +#[derive(Clone, Copy, Debug)] +pub enum PhysicalInput { + Key { key: PhysicalKeyCode, mods: Mods, pressed: bool, repeat: bool }, + Modifiers(Mods), + FocusLost, +} + +pub(crate) type Handler = std::rc::Rc<dyn Fn(crate::states::States<'_>, &PhysicalInput, &mut crate::Tx) -> bool>; + +impl crate::El { + /// Receives physical keys before logical editing, app shortcuts and focus navigation. + /// Return true to consume the event. FocusLost also arrives on window deactivation. + pub fn on_physical_input<S: 'static>(mut self, + f: impl Fn(&mut S, &PhysicalInput, &mut crate::Tx) -> bool + 'static) -> Self { + self.cold_mut().focus.physical = Some(std::rc::Rc::new(move |state, event, tx| { + state.cast::<S>().is_some_and(|s| f(s, event, tx)) + })); + self + } +} diff --git a/app/vendor/rune/crates/rune/src/input/pointer_observer.rs b/app/vendor/rune/crates/rune/src/input/pointer_observer.rs new file mode 100644 index 0000000..ec6427f --- /dev/null +++ b/app/vendor/rune/crates/rune/src/input/pointer_observer.rs @@ -0,0 +1,112 @@ +//! A small native-pointer mailbox. Global movement outside the canvas wakes the owner only +//! on exit or a followed-display change. No application state or native API runs under its lock. +use std::sync::Mutex; + +/// Where the pointer was at the last observation, and the last display it was seen in. The +/// display outlives the observation that found it, so a move through the gap between displays +/// only wakes its owner when it reaches the next one. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +enum Presence { + /// Off the canvas, and in no display yet. + #[default] + Outside, + /// Off the canvas, in `display` or in the gap after it. + OffCanvas { display: usize }, + /// On the canvas, in `display` when the canvas sits in one. + OnCanvas { display: Option<usize> }, +} + +/// Whether `point` is inside the rectangle. +fn contains(r: &[i32; 4], point: (i32, i32)) -> bool { + point.0 >= r[0] && point.1 >= r[1] && point.0 < r[2] && point.1 < r[3] +} + +impl Presence { + /// What observing `point` makes of the pointer, and whether that observation wakes its + /// owner: it is on the canvas, has just left it, or reached another display while the + /// overlay follows the pointer. + fn step(self, point: (i32, i32), canvas: [i32; 4], displays: &[[i32; 4]], follow: bool) -> (Self, bool) { + let on_canvas = contains(&canvas, point); + let display = displays.iter().position(|d| contains(d, point)).or(self.display()); + let changed = follow && display != self.display(); + let next = match (on_canvas, display) { + (true, display) => Self::OnCanvas { display }, + (false, Some(display)) => Self::OffCanvas { display }, + (false, None) => Self::Outside, + }; + (next, on_canvas || self.on_canvas() || changed) + } + + /// The last display the pointer was seen in. + fn display(self) -> Option<usize> { + match self { + Self::Outside => None, + Self::OffCanvas { display } => Some(display), + Self::OnCanvas { display } => display, + } + } + + /// Whether the pointer was on the canvas at the last observation. + fn on_canvas(self) -> bool { matches!(self, Self::OnCanvas { .. }) } +} + +#[derive(Default)] +struct Sample { + canvas: [i32; 4], displays: Vec<[i32; 4]>, follow: bool, + presence: Presence, last: Option<(i32, i32)>, pending: Option<(i32, i32)>, +} +pub(crate) struct Observer { sample: Mutex<Sample>, wake: Option<crate::Waker> } +impl Observer { + pub fn new(wake: Option<crate::Waker>) -> Self { Self { sample: Mutex::default(), wake } } + pub fn needs_geometry(&self, canvas: [i32; 4], follow: bool) -> bool { + let s = self.sample.lock().unwrap(); + s.canvas != canvas || s.follow != follow + } + pub fn configure(&self, canvas: [i32; 4], displays: Vec<[i32; 4]>, follow: bool) { + let mut s = self.sample.lock().unwrap(); + if s.canvas != canvas || s.displays != displays || s.follow != follow { s.last = None; } + s.canvas = canvas; s.displays = displays; s.follow = follow; + } + pub fn take(&self) -> Option<(i32, i32)> { self.sample.lock().unwrap().pending.take() } + pub fn observe(&self, point: (i32, i32)) { + let wake = { + let mut s = self.sample.lock().unwrap(); + let (presence, interested) = s.presence.step(point, s.canvas, &s.displays, s.follow); + s.presence = presence; + if interested && s.last != Some(point) { s.last = Some(point); s.pending = Some(point); true } else { false } + }; + if wake && let Some(wake) = &self.wake { wake(); } + } +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn overlay_observation_sleeps_outside_canvas_and_preserves_gap_display() { + use std::sync::{Arc, atomic::{AtomicUsize, Ordering}}; + let wakes = Arc::new(AtomicUsize::new(0)); + let count = wakes.clone(); + let observer = Observer::new(Some(Arc::new(move || { count.fetch_add(1, Ordering::Relaxed); }))); + observer.configure([10, 10, 30, 30], vec![[0, 0, 100, 100], [200, 0, 300, 100]], true); + observer.observe((5, 5)); // Initial display resolution. + assert_eq!(observer.take(), Some((5, 5))); + for x in 31..100 { observer.observe((x, 5)); } + assert!(observer.take().is_none()); + observer.observe((15, 15)); + assert_eq!(observer.take(), Some((15, 15))); + observer.observe((50, 50)); // One exit. + assert_eq!(observer.take(), Some((50, 50))); + observer.observe((150, 50)); // Gap retains the previous display. + assert!(observer.take().is_none()); + observer.observe((250, 50)); + assert_eq!(observer.take(), Some((250, 50))); + observer.observe((260, 50)); + assert!(observer.take().is_none()); + assert_eq!(wakes.load(Ordering::Relaxed), 4); + assert!(observer.needs_geometry([240, 40, 280, 60], true)); + observer.configure([240, 40, 280, 60], vec![[0, 0, 100, 100], [200, 0, 300, 100]], true); + observer.observe((260, 50)); + assert_eq!(observer.take(), Some((260, 50)), "moving the canvas under a stationary pointer must wake"); + } +} diff --git a/app/vendor/rune/crates/rune/src/input/secure_input.rs b/app/vendor/rune/crates/rune/src/input/secure_input.rs new file mode 100644 index 0000000..4ae1685 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/input/secure_input.rs @@ -0,0 +1,93 @@ +//! One balanced native secure-input claim per focused, visible password window. + +#![allow(unsafe_code)] + +#[derive(Default)] +pub(crate) struct SecureInput(bool); + +impl SecureInput { + pub(crate) fn set(&mut self, active: bool) { + if active == self.0 { return; } + // Tests never take the claim: it would block every other app's key events. + #[cfg(all(target_os = "macos", not(test)))] + // SAFETY: Carbon secure-input FFI takes no pointers; `self.0` ensures `DisableSecureEventInput` + // only balances a prior successful `EnableSecureEventInput`. + unsafe { + if active { + self.0 = EnableSecureEventInput() == 0; + } else { + DisableSecureEventInput(); + self.0 = false; + } + } + #[cfg(any(not(target_os = "macos"), test))] + { self.0 = active; } + } + + /// The window gained or lost focus. Losing it releases the claim at once: an idle window + /// builds no frame to do it. Gaining it waits for a frame that sees a focused secure field. + pub(crate) fn window_focus(&mut self, focused: bool) { + if !focused { self.set(false); } + } +} + +impl Drop for SecureInput { + fn drop(&mut self) { self.set(false); } +} + +#[cfg(all(target_os = "macos", not(test)))] +#[link(name = "Carbon", kind = "framework")] +unsafe extern "C" { + fn EnableSecureEventInput() -> i32; + fn DisableSecureEventInput() -> i32; +} + +#[cfg(test)] +mod tests { + use super::SecureInput; + use crate::runtime::Runtime; + use crate::{Cx, El, Env, TextEdit, TextStyle}; + + fn view(s: &TextEdit, _: &mut Cx<TextEdit>) -> El { + crate::text_input(s, TextStyle::new(16.0, 400.0)).single_line().secure() + .key("secret").size(200.0, 40.0).on_edit(|s: &mut TextEdit| s) + } + + /// A window that goes to the background with its password field focused holds no claim, + /// though the field keeps its focus and no frame is built. + #[test] + fn a_background_window_with_a_focused_secure_field_holds_no_claim() { + let mut edit = TextEdit::new("hunter2"); + edit.focused = true; + let mut rt = Runtime::new(edit, view, (200.0, 40.0), Env::new(true, 1.0)); + rt.frame(0.0); + let mut claim = SecureInput::default(); + claim.set(rt.has_secure_focus()); + assert!(claim.0, "a focused secure field in the key window claims secure input"); + + // As the host does for `WindowEvent::Focused(false)`, with no frame after it. + rt.window_focus(false); + claim.window_focus(false); + assert!(rt.has_secure_focus(), "the field keeps its focus"); + assert!(!claim.0, "the background window released the claim"); + + claim.window_focus(true); + assert!(!claim.0, "focus alone doesn't claim before a frame sees the field"); + } + + /// A window with no secure field never claims, focused or not. + #[test] + fn a_window_without_a_secure_field_never_claims() { + fn plain(s: &TextEdit, _: &mut Cx<TextEdit>) -> El { + crate::text_input(s, TextStyle::new(16.0, 400.0)).single_line() + .key("plain").size(200.0, 40.0).on_edit(|s: &mut TextEdit| s) + } + let mut edit = TextEdit::new(""); + edit.focused = true; + let mut rt = Runtime::new(edit, plain, (200.0, 40.0), Env::new(true, 1.0)); + rt.frame(0.0); + let mut claim = SecureInput::default(); + claim.set(rt.has_secure_focus()); + assert!(!claim.0); + } +} diff --git a/app/vendor/rune/crates/rune/src/input/time.rs b/app/vendor/rune/crates/rune/src/input/time.rs new file mode 100644 index 0000000..c47ab87 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/input/time.rs @@ -0,0 +1,109 @@ +//! When the input a handler runs for arrived (`Tx::input_time`). A host dispatches each input +//! event inside a scope holding its arrival time; the runtime stamps the actions that event +//! queues with it, and each handler sees its own action's stamp. + +use std::cell::Cell; + +use crate::time::Instant; + +thread_local! { + static CURRENT: Cell<Option<Instant>> = const { Cell::new(None) }; + static LAST: Cell<Option<Instant>> = const { Cell::new(None) }; +} + +/// When this thread's windows last took an input event (a key, the pointer, a wheel or a +/// gesture) from the platform: the moment it was dispatched, not its `Tx::input_time`, so +/// input dispatched after a frame is always later than that frame. `None` before any. +pub fn last_input() -> Option<Instant> { LAST.with(Cell::get) } + +/// Input the platform delivered outside a window event (a browser page's own text field): it +/// counts for [`last_input`]. +#[cfg_attr(not(target_arch = "wasm32"), allow(dead_code))] +pub(crate) fn typed() { LAST.with(|c| c.set(Some(crate::time::now()))); } + +/// The arrival time of the input being dispatched on this thread, if any. +pub(crate) fn current() -> Option<Instant> { CURRENT.with(Cell::get) } + +/// Holds an arrival time until dropped, then restores the one before it. +#[must_use] +pub(crate) struct Scope(Option<Instant>); + +/// Dispatch with `at` as the input's arrival time (`None` for work no input caused). +pub(crate) fn scope(at: Option<Instant>) -> Scope { Scope(CURRENT.with(|c| c.replace(at))) } + +impl Drop for Scope { + fn drop(&mut self) { CURRENT.with(|c| c.set(self.0)); } +} + +/// The input events whose handlers see an arrival time. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Kind { + Key, + Mouse, + Wheel, + Magnify, + Rotate, + SmartMagnify, +} + +impl Kind { + fn of(event: &winit::event::WindowEvent) -> Option<Self> { + use winit::event::WindowEvent as E; + Some(match event { + E::KeyboardInput { .. } | E::ModifiersChanged(_) | E::Ime(_) => Kind::Key, + E::MouseInput { .. } | E::CursorMoved { .. } | E::CursorLeft { .. } => Kind::Mouse, + E::MouseWheel { .. } => Kind::Wheel, + E::PinchGesture { .. } => Kind::Magnify, + E::RotationGesture { .. } => Kind::Rotate, + E::DoubleTapGesture { .. } => Kind::SmartMagnify, + _ => return None, + }) + } +} + +/// A scope for dispatching `event` when it is input, holding when it arrived: on macOS the +/// timestamp of the `NSEvent` AppKit is dispatching, when it is that kind of event; else now. +pub(crate) fn arrived(event: &winit::event::WindowEvent) -> Option<Scope> { + let kind = Kind::of(event)?; + LAST.with(|c| c.set(Some(crate::time::now()))); + Some(scope(Some(native(kind).unwrap_or_else(crate::time::now)))) +} + +#[cfg(target_os = "macos")] +fn native(kind: Kind) -> Option<Instant> { + use objc2::MainThreadMarker; + use objc2_app_kit::{NSApplication, NSEventType as T}; + use objc2_foundation::NSProcessInfo; + let mtm = MainThreadMarker::new()?; + let event = NSApplication::sharedApplication(mtm).currentEvent()?; + let (ty, timestamp) = (event.r#type(), event.timestamp()); + let matches = match kind { + Kind::Key => matches!(ty, T::KeyDown | T::KeyUp | T::FlagsChanged), + Kind::Mouse => matches!(ty, T::LeftMouseDown | T::LeftMouseUp | T::RightMouseDown | T::RightMouseUp + | T::OtherMouseDown | T::OtherMouseUp | T::MouseMoved | T::LeftMouseDragged | T::RightMouseDragged + | T::OtherMouseDragged | T::MouseExited), + Kind::Wheel => ty == T::ScrollWheel, + Kind::Magnify => ty == T::Magnify, + Kind::Rotate => ty == T::Rotate, + Kind::SmartMagnify => ty == T::SmartMagnify, + }; + // The uptime is read after the event, so never before its timestamp. + matches.then(|| since_boot(crate::time::now(), NSProcessInfo::processInfo().systemUptime(), timestamp)) +} + +#[cfg(not(target_os = "macos"))] +fn native(_: Kind) -> Option<Instant> { None } + +/// The `Instant` of an `NSEvent` timestamp, in seconds since boot like `uptime`, the system +/// uptime read at `now`. Both count `mach_absolute_time`, as `Instant` does on macOS. An +/// event stamped after `uptime` (or unreadable) arrived `now`. +#[cfg_attr(not(target_os = "macos"), allow(dead_code))] +fn since_boot(now: Instant, uptime: f64, timestamp: f64) -> Instant { + let age = uptime - timestamp; + if !age.is_finite() || age <= 0.0 { return now; } + now.checked_sub(std::time::Duration::from_secs_f64(age)).unwrap_or(now) +} + +#[cfg(test)] +#[path = "time_tests.rs"] +mod tests; diff --git a/app/vendor/rune/crates/rune/src/input/time_tests.rs b/app/vendor/rune/crates/rune/src/input/time_tests.rs new file mode 100644 index 0000000..4e5d38a --- /dev/null +++ b/app/vendor/rune/crates/rune/src/input/time_tests.rs @@ -0,0 +1,83 @@ +//! `Tx::input_time`: each handler sees its own input's arrival time, and only input handlers +//! see one. +use std::time::Duration; + +use super::*; +use crate::{Cx, El, Env, Key, KeyEvent, Mods, PhysicalInput, PhysicalKeyCode, Runtime, Tx, el}; + +#[test] +fn an_event_timestamp_is_the_instant_that_long_before_the_uptime_read() { + let now = crate::time::now() + Duration::from_secs(10); + assert_eq!(since_boot(now, 1000.25, 1000.0), now - Duration::from_millis(250)); + assert_eq!(since_boot(now, 5.5, 2.0), now - Duration::from_millis(3500)); + assert_eq!(since_boot(now, 1000.0, 1000.0), now, "stamped as the uptime was read"); + assert_eq!(since_boot(now, 1000.0, 1000.5), now, "a stamp after the read is now"); + assert_eq!(since_boot(now, 1000.0, f64::NAN), now); +} + +#[derive(Default)] +struct Seen { + keys: Vec<(Key, Option<Instant>)>, + presses: Vec<Option<Instant>>, + polls: Vec<Option<Instant>>, +} + +fn view(_: &Seen, _: &mut Cx<Seen>) -> El { + el().size(100.0, 100.0) + .child(el().key("button").size(40.0, 40.0).on_press_tx(|s: &mut Seen, tx: &mut Tx| s.presses.push(tx.input_time()))) +} + +fn app() -> Runtime<Seen> { + let mut rt = Runtime::new(Seen::default(), view, (100.0, 100.0), Env::new(true, 1.0)); + rt.on_key = Some(|s, e, tx| { s.keys.push((e.key.clone(), tx.input_time())); true }); + rt.frame(0.0); + rt +} + +fn physical(code: PhysicalKeyCode, key: Key) -> (PhysicalInput, Option<KeyEvent>) { + (PhysicalInput::Key { key: code, mods: Mods::default(), pressed: true, repeat: false }, Some(KeyEvent { key, mods: Mods::default() })) +} + +#[test] +fn input_that_piles_up_between_frames_keeps_each_event_s_time() { + let mut rt = app(); + let t0 = crate::time::now(); + let [t1, t2, t3] = [1, 2, 3].map(|ms| t0 + Duration::from_millis(ms)); + { + let _input = scope(Some(t1)); + let (event, key) = physical(PhysicalKeyCode::ArrowDown, Key::Down); + rt.physical_then(event, key, None, None); + } + { + let _input = scope(Some(t2)); + let (event, key) = physical(PhysicalKeyCode::ArrowUp, Key::Up); + rt.physical_then(event, key, None, None); + } + { + let _input = scope(Some(t3)); + rt.pointer_move(20.0, 20.0); + rt.pointer_down(20.0, 20.0); + rt.pointer_up(20.0, 20.0); + } + rt.frame(0.0); + assert_eq!(rt.state.keys, vec![(Key::Down, Some(t1)), (Key::Up, Some(t2))]); + assert_eq!(rt.state.presses, vec![Some(t3)]); +} + +#[test] +fn handlers_no_input_caused_see_no_input_time() { + let mut rt = app(); + rt.poll = Some(|s, _, tx| { s.polls.push(tx.input_time()); false }); + { + // A frame run while a host dispatches input still polls without its time. + let _input = scope(Some(crate::time::now())); + rt.frame(0.0); + } + assert_eq!(rt.state.polls, vec![None]); + rt.update(|s, tx| s.polls.push(tx.input_time())); + assert_eq!(rt.state.polls, vec![None, None], "an update"); + rt.key(KeyEvent { key: Key::Down, mods: Mods::default() }); + rt.frame(0.0); + assert_eq!(rt.state.keys, vec![(Key::Down, None)], "input a program feeds the runtime itself"); + assert_eq!(current(), None, "every scope restored what it held"); +} diff --git a/app/vendor/rune/crates/rune/src/jump_list.rs b/app/vendor/rune/crates/rune/src/jump_list.rs new file mode 100644 index 0000000..18122ff --- /dev/null +++ b/app/vendor/rune/crates/rune/src/jump_list.rs @@ -0,0 +1,77 @@ +//! The app's jump list: what a right-click on its taskbar button (Windows) offers besides its +//! windows, as tasks (New window) and named categories of recent things (Recent projects). Each +//! entry starts the app's own executable with one argument, which a running app receives +//! through `single_instance` like any second launch's arguments, so a link the app opens +//! (`App::on_open_url`) is the natural argument. +//! +//! [`set_jump_list`] returns at once: the list is built and committed on a thread of its own +//! (made on the first call, asleep in between), never on the UI thread, and a list equal to the +//! last one does nothing. Entries the person removed from the list stay out of it, as Windows +//! asks. On Windows the list belongs to the process's AppUserModelID, so call it after the app +//! took its identity. +//! +//! macOS shows the same list as the Dock icon's menu (when the app's own menus put nothing in the +//! Dock): a pick arrives as the link the app opens (`App::on_open_url`), in the running app. +//! Linux's counterpart, the launcher's actions, are static in a `.desktop` file, not built here. + +/// One entry: a title, and the single argument the app starts with when it's picked. +#[derive(Clone, Debug, PartialEq, Eq, Hash)] +pub struct JumpItem { + pub(crate) title: String, + pub(crate) argument: String, + pub(crate) description: String, +} + +impl JumpItem { + pub fn new(title: impl Into<String>, argument: impl Into<String>) -> Self { + Self { title: title.into(), argument: argument.into(), description: String::new() } + } + + /// The tooltip over the entry. + pub fn description(mut self, description: impl Into<String>) -> Self { + self.description = description.into(); + self + } +} + +/// Tasks first, then each category under its name. +#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)] +pub struct JumpList { + pub(crate) tasks: Vec<JumpItem>, + pub(crate) categories: Vec<(String, Vec<JumpItem>)>, + pub(crate) lead: Option<String>, +} + +impl JumpList { + pub fn new() -> Self { Self::default() } + + pub fn task(mut self, item: JumpItem) -> Self { + self.tasks.push(item); + self + } + + /// One argument every entry starts the app with before its own (Windows): a run's own data + /// folder, so a pick reaches that run and not the app's usual profile. + pub fn lead(mut self, argument: impl Into<String>) -> Self { + self.lead = Some(argument.into()); + self + } + + /// A category of entries under `name`; an empty one isn't shown. + pub fn category(mut self, name: impl Into<String>, items: Vec<JumpItem>) -> Self { + if !items.is_empty() { self.categories.push((name.into(), items)); } + self + } +} + +/// Replaces the app's jump list with `list`: on Windows off the UI thread, on macOS as the Dock +/// menu (call it on the main thread). Does nothing elsewhere, and for headless runs. +pub fn set_jump_list(list: JumpList) { + if crate::is_headless() { return; } + #[cfg(target_os = "windows")] + crate::platform::win32::jump_list::set(list); + #[cfg(target_os = "macos")] + crate::native_menu::set_jump_menu(&list); + #[cfg(not(any(target_os = "windows", target_os = "macos")))] + let _ = list; +} diff --git a/app/vendor/rune/crates/rune/src/labels.rs b/app/vendor/rune/crates/rune/src/labels.rs new file mode 100644 index 0000000..ae48b0b --- /dev/null +++ b/app/vendor/rune/crates/rune/src/labels.rs @@ -0,0 +1,130 @@ +//! The words Rune itself puts on screen: a text field's menu (Cut, Copy, Paste, Select All and +//! the spelling items), selectable text's Copy, and on macOS the menu bar's standard items and +//! menus. They are English until the app names them in its own language with [`set_labels`], +//! and [`set_locale`] says which language that is. +//! +//! Rune asks each time it shows one, so after the app's language changes the next menu opened +//! speaks it. The macOS menu bar takes the new names at the next [`AppHandle::set_menu`]. +//! +//! [`AppHandle::set_menu`]: crate::AppHandle::set_menu +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::{Arc, RwLock}; + +/// Something Rune names on screen. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +#[non_exhaustive] +pub enum Label<'a> { + Cut, + Copy, + Paste, + SelectAll, + Undo, + Redo, + /// A misspelled word's item that adds the word to the user's dictionary. + LearnSpelling, + /// Shown, disabled, in place of the suggestions when the checker has none. + NoGuesses, + /// The field menu's checkbox for the app's spellcheck setting (`El::on_spellcheck`). + Spellcheck, + /// The field menu's submenu of dictionaries (`El::on_spellcheck_languages`). + SpellcheckLanguages, + /// A dictionary in that submenu, by its language tag (`en-US`). Without a name from the app + /// it's named in the app's language ([`set_locale`]) where the platform can, else in + /// English. The submenu lists them in the order of their names. + Language(&'a str), + /// A top-level menu of the macOS menu bar, by the name its items give (`MenuItem::menu`): + /// Rune's own "Edit" and "Window", or one of the app's. + Menu(&'a str), + /// The Window menu's items. + Minimize, + Close, + /// The app menu's items; some carry the app's name. + About(&'a str), + Services, + Hide(&'a str), + HideOthers, + ShowAll, + Quit(&'a str), + /// A Markdown block's marker before `n` lines nested past the container bound. + MoreNestedLines(usize), +} + +type Namer = Arc<dyn Fn(Label<'_>) -> Option<String> + Send + Sync>; + +static NAMER: RwLock<Option<Namer>> = RwLock::new(None); +static LOCALE: RwLock<Option<String>> = RwLock::new(None); +static RTL: AtomicBool = AtomicBool::new(false); + +/// Names Rune's own labels with `names`, for every window. `None` keeps a label's English. +pub fn set_labels(names: impl Fn(Label<'_>) -> Option<String> + Send + Sync + 'static) { + if let Ok(mut namer) = NAMER.write() { + *namer = Some(Arc::new(names)); + } +} + +/// The language the app's labels are in, as a BCP 47 tag (`de`, `zh-Hant`). Rune names the +/// spellcheck dictionaries in it when the app doesn't (`Label::Language`), as a browser's +/// `Intl.DisplayNames(locale)` would, and sorts them as it sorts text (`localeCompare`). +pub fn set_locale(tag: &str) { + if let Ok(mut locale) = LOCALE.write() { + *locale = Some(tag.to_owned()); + } +} + +/// The way the app's language reads, which Rune's native menus take, as a browser's menus take +/// its interface language's: right to left, a Windows pop-up, window or tray menu lays out right +/// to left (its checkmarks and submenu arrows on the left, shortcuts at the left edge) and opens +/// leftward from its point or under its anchor's right edge, and a macOS pop-up menu's items +/// align right. Left to right (`Ltr` or `Auto`) until the app says. +pub fn set_direction(direction: crate::Direction) { + RTL.store(direction == crate::Direction::Rtl, Ordering::Relaxed); +} + +/// Whether the app's language reads right to left ([`set_direction`]). +pub(crate) fn rtl() -> bool { + RTL.load(Ordering::Relaxed) +} + +/// What `label` reads now: the app's name for it, else Rune's English. +pub fn label(label: Label<'_>) -> String { + named(label).unwrap_or_else(|| english(label)) +} + +/// The app's name for `label`, if it gave one. +pub(crate) fn named(label: Label<'_>) -> Option<String> { + let namer = NAMER.read().ok().and_then(|namer| namer.clone()); + namer.and_then(|names| names(label)) +} + +/// The app's language ([`set_locale`]), if it said. +pub(crate) fn locale() -> Option<String> { + LOCALE.read().ok().and_then(|locale| locale.clone()) +} + +fn english(label: Label<'_>) -> String { + match label { + Label::Cut => "Cut".into(), + Label::Copy => "Copy".into(), + Label::Paste => "Paste".into(), + Label::SelectAll => "Select All".into(), + Label::Undo => "Undo".into(), + Label::Redo => "Redo".into(), + Label::LearnSpelling => "Learn Spelling".into(), + Label::NoGuesses => "No Guesses Found".into(), + Label::Spellcheck => "Spellcheck".into(), + Label::SpellcheckLanguages => "Spellcheck Languages".into(), + // The field menu names a dictionary itself when the app doesn't (`spell::language_name`). + Label::Language(tag) => tag.into(), + Label::Menu(name) => name.into(), + Label::Minimize => "Minimize".into(), + Label::Close => "Close".into(), + Label::About(app) => format!("About {app}"), + Label::Services => "Services".into(), + Label::Hide(app) => format!("Hide {app}"), + Label::HideOthers => "Hide Others".into(), + Label::ShowAll => "Show All".into(), + Label::Quit(app) => format!("Quit {app}"), + Label::MoreNestedLines(1) => "1 more nested line".into(), + Label::MoreNestedLines(n) => format!("{n} more nested lines"), + } +} diff --git a/app/vendor/rune/crates/rune/src/lib.rs b/app/vendor/rune/crates/rune/src/lib.rs new file mode 100644 index 0000000..24053db --- /dev/null +++ b/app/vendor/rune/crates/rune/src/lib.rs @@ -0,0 +1,428 @@ +//! Rune, first slice: keyed element tree from plain view functions, Taffy layout, analytic +//! spring tracks, an instanced wgpu uber-quad renderer with Parley text, pointer and keyboard +//! input, scroll viewports, growth stacks, streaming reveals, themes as data, and headless agent +//! tooling. + +#[cfg(all(target_arch = "wasm32", any(feature = "hot", feature = "native-file-dialog")))] +compile_error!("web does not support Rune's hot or native-file-dialog features; disable them for wasm32"); + +mod a11y; +mod app; +mod flight; +mod frame; +mod input; +mod native_menu; +mod open_url; +mod overlay; +mod platform; +mod popup_menu; +mod quit; +mod shortcuts; +mod states; +mod system_material; +mod window; + +pub mod clipboard; +pub mod compose; +pub mod drag_out; +pub mod el; +pub mod file_dialog; +#[cfg(feature = "hot")] +pub mod hot; +pub mod jump_list; +pub mod labels; +pub mod memo; +pub mod motion_gate; +pub mod playground; +pub mod render; +pub mod rewind; +pub mod runtime; +pub mod taskbar; +pub mod text; +pub mod tooling; +pub mod tray; + +pub(crate) use input::cursor; +pub(crate) use quit::relaunch; +pub(crate) use rune_core::cold; +pub(crate) use rune_gpu as gpu; +pub(crate) use rune_image::pixels; +pub(crate) use rune_media::recorder; +pub(crate) use rune_media::video; +pub(crate) use tooling::virtual_desktop as desktop; +pub(crate) use window::titlebar; + +/// AccessKit's types, for [`Runtime::accessibility_tree`] and [`Runtime::accessibility_action`]. +pub use a11y::AccessibilityLink; +pub use accesskit; +pub use app::App; +pub use app::AppHandle; +pub use clipboard::ClipboardContent; +pub use clipboard::ClipboardImage; +pub use clipboard::ClipboardWrite; +pub use clipboard::SecretCopy; +pub use clipboard::SecretState; +pub use color::Color; +pub use color::oklch; +pub use color::oklcha; +pub use compose::Compositor; +pub use compose::Frame; +pub use drag_out::DragImage; +pub use drag_out::DragItem; +pub use drag_out::DragOperation; +pub use drag_out::DragOutcome; +pub use edit::Block; +pub use edit::Clause; +pub use edit::Ime; +pub use edit::Key; +pub use edit::KeyEvent; +pub use edit::KeySide; +pub use edit::MAX_LIST_LEVEL; +pub use edit::Mark; +pub use edit::MarkRange; +pub use edit::Modifier; +pub use edit::Mods; +pub use edit::ParagraphInfo; +pub use edit::RichStyle; +pub use edit::TextEdit; +pub use el::Align; +pub use el::Anchor; +pub use el::Cursor; +pub use el::CursorImage; +pub use el::Cycle; +pub use el::Direction; +pub use el::Drag; +pub use el::El; +pub use el::GridRow; +pub use el::GrowthSpec; +pub use el::{InlineIcon, InlineImage}; +pub use el::LiveRegion; +pub use el::Outline; +pub use el::Phase; +pub use el::PillStyle; +pub use el::PointerEvent; +pub use el::PointerPress; +pub use el::RadialRadius; +pub use el::ScrollFade; +pub use el::ScrollSpec; +pub use el::SelectionStyle; +pub use el::Shadow; +pub use el::Shell; +pub use el::Side; +pub use el::Tx; +pub use el::anchor_rect; +pub use el::auto_grow; +pub use el::canvas; +pub use el::col; +pub use el::edit_access; +pub use el::effect; +pub use el::el; +pub use el::grid; +pub use el::hairline; +pub use el::icon; +pub use el::layout_watch::ScrollPos; +pub use el::motion::MotionIntent; +pub use el::rich; +pub use el::row; +pub use el::rule; +pub use el::spacer; +pub use el::text; +pub use el::text_input; +pub use file_dialog::FileDialogError; +pub use file_dialog::FileDialogKind; +pub use file_dialog::FileDialogOptions; +pub use file_dialog::FileDialogResult; +pub use file_dialog::FileDialogs; +pub use file_dialog::ScriptedFileDialog; +pub use frame::encoded::FrameEncoded; +pub use frame::encoded::FrameOutcome; +#[cfg(feature = "frame-profile")] +#[doc(hidden)] +pub use frame::profile::PHASES; +#[cfg(feature = "frame-profile")] +#[doc(hidden)] +pub use frame::profile::take_frame_phases; +#[cfg(feature = "frame-profile")] +#[doc(hidden)] +pub use frame::profile::thread_cpu_ms; +pub use frame::profile::{ThreadCpuMark, thread_cpu_mark, thread_cpu_ns, thread_cpu_since}; +pub use frame::surface_stats::Pacing; +pub use frame::surface_stats::SurfaceCounts; +pub use frame::surface_stats::SurfaceStats; +pub use gpu::backend::GpuBackend; +pub use gpu::backend::describe as describe_gpu; +#[cfg(all(target_vendor = "apple", feature = "metal-backend"))] +#[doc(hidden)] +pub use gpu::metal::bench::dispatch_overhead as __metal_dispatch_overhead; +pub use gpu::springs as gpu_springs; +pub use growth::GROWTH; +pub use growth::StreamEdge; +pub use growth::edge; +pub use image::Image; +pub use image::ImageCache; +pub use image::ImageError; +pub use image::ImageId; +pub use input::canvas_input::GesturePhase; +pub use input::canvas_input::MagnifyEvent; +pub use input::canvas_input::PointerButton; +pub use input::canvas_input::RotateEvent; +pub use input::canvas_input::WheelEvent; +pub use input::chord::Chord; +pub use input::chord::ChordError; +pub use input::chord::ChordKey; +pub use input::chord::ChordMod; +pub use input::chord::KeyPlatform; +pub use input::chord::Keybind; +pub use input::physical_input::PhysicalInput; +pub use input::time::last_input; +pub use jump_list::JumpItem; +pub use jump_list::JumpList; +pub use jump_list::set_jump_list; +pub use labels::Label; +pub use labels::set_labels; +pub use latest::Latest; +pub use live::Live; +pub use live::LiveText; +pub use live::Tween; +pub use memo::memo; +pub use memo::region; +pub use memo::region_with; +pub use native_menu::MenuError; +pub use native_menu::MenuItem; +pub use native_surface::NativeSurface; +pub use native_surface::SurfaceFit; +pub use open_url::OpenUrlError; +pub use open_url::instance::release_instance; +pub use open_url::instance::single_instance; +pub use overlay::Availability; +pub use overlay::OverlayHandle; +pub use overlay::OverlaySpec; +pub use overlay::ScreenEdge; +pub use overlay::options::ConfiguredOverlay; +pub use overlay::options::DisplayId; +pub use overlay::options::DisplayTarget; +pub use overlay::options::KeyPolicy; +pub use overlay::options::NativeDisplayId; +pub use overlay::options::OverlayCapabilities; +pub use overlay::options::OverlayCreated; +pub use overlay::options::OverlayInput; +pub use overlay::options::OverlayLevel; +pub use overlay::options::OverlayOptions; +pub use overlay::options::OverlayPlacement; +pub use overlay::options::OverlaySupport; +pub use pixels::Pixels; +pub use platform::accent::SystemAccent; +pub use platform::accent::system_accent; +pub use platform::app_icon::set_app_icon; +#[cfg(target_os = "windows")] +pub use platform::app_icon::set_app_icon_resource; +#[cfg(target_vendor = "apple")] +pub use platform::embed; +#[cfg(target_os = "macos")] +#[doc(hidden)] +pub use platform::macos::appearance as macos_appearance; +#[cfg(target_os = "macos")] +#[doc(hidden)] +pub use platform::macos::panel_bridge as macos_panel_bridge; +pub use platform::preferences::SystemContrast; +pub use platform::scroll_bars::ScrollBars; +#[doc(hidden)] +pub use platform::scroll_bars::current_runtime_id; +pub use platform::scroll_bars::system_scroll_bars; +pub use platform::scroll_bars::system_scroller_jumps; +pub use platform::scroll_bars::system_scroller_overlay; +#[cfg(target_arch = "wasm32")] +pub use platform::web; +/// Windows: raises this process's threads whose name passes the filter to a priority floor, walking +/// only this process's threads. +#[cfg(target_os = "windows")] +pub use platform::win32::raise_threads; +pub use playground::Play; +pub use playground::Playground; +pub use playground::Stage; +pub use playground::Step; +pub use playground::Story; +pub use popup_menu::PopupAnchor; +pub use popup_menu::PopupItem; +pub use popup_menu::PopupMenu; +pub use popup_menu::PopupMenuError; +pub use popup_menu::popup_menu_supported; +#[cfg(not(target_arch = "wasm32"))] +pub use quit::exit_deadline; +pub use quit::fast_exit; +pub use quit::orderly_exit; +pub use quit::quitting; +pub use recorder::FakeMicrophone; +pub use recorder::Level; +pub use recorder::MicPermission; +pub use recorder::RecordFormat; +pub use recorder::Recorder; +pub use recorder::RecorderState; +pub use recorder::Recording; +pub use render::MAX_BACKDROP_BLURS; +pub use render::gpu_events::GpuEvent; +pub use render::gpu_events::on_gpu; +pub use render::prewarm_gpu; +pub use render::prewarm_gpu_on; +pub use render::warm_gpu; +pub use render::warm_gpu_with; +pub use rune_core::color; +pub use rune_core::dirs; +pub use rune_core::env; +pub use rune_core::growth; +pub use rune_core::latest; +pub use rune_core::live; +pub use rune_core::machine; +pub use rune_core::marks; +pub use rune_core::prefs; +pub use rune_core::shape; +pub use rune_core::task; +pub use rune_core::theme; +pub use rune_core::time; +pub use rune_core::tok; +pub use rune_core::tracked; +pub use rune_edit as edit; +pub use rune_image as image; +pub use rune_media::native_surface; +pub use rune_motion::Anim; +pub use rune_motion::AnimExt; +pub use rune_motion::Beat; +pub use rune_motion::Blend; +pub use rune_motion::Clock; +pub use rune_motion::CubicBezier; +pub use rune_motion::Curve; +pub use rune_motion::Decay; +pub use rune_motion::Easing; +pub use rune_motion::Edge; +pub use rune_motion::Effect; +pub use rune_motion::LayoutAnim; +pub use rune_motion::LoopKind; +pub use rune_motion::LoopSpec; +pub use rune_motion::NodeId; +pub use rune_motion::Phase as PresencePhase; +pub use rune_motion::Presented; +pub use rune_motion::Reveal; +pub use rune_motion::Sequence; +pub use rune_motion::Spring; +pub use rune_motion::SpringPair; +pub use rune_motion::Stagger; +pub use rune_motion::StaggerFrom; +pub use rune_motion::StepPosition; +pub use rune_motion::Transition; +pub use rune_motion::Travel; +pub use rune_motion::Vec2; +pub use rune_motion::Velocity; +pub use rune_spell as spell; +pub use runtime::Cx; +pub use runtime::ElementInfo; +pub use runtime::Env; +pub use runtime::HelpLook; +pub use runtime::MotionElement; +pub use runtime::Pick; +pub use runtime::Picked; +pub use runtime::Pose; +pub use runtime::Runtime; +pub use runtime::SelectedText; +pub use runtime::SelectionChange; +pub use runtime::TextMark; +pub use runtime::TextSelection; +pub use runtime::TitlebarAction; +pub use runtime::TouchPhase; +pub use runtime::Waker; +pub use runtime::commit_generation; +#[doc(hidden)] +pub use runtime::scroll_watch_state; +pub use shape::LineCap; +pub use shape::Path; +pub use shape::Shape; +pub use shortcuts::PhysicalKeyCode; +pub use shortcuts::Shortcut; +pub use shortcuts::ShortcutError; +pub use shortcuts::ShortcutId; +pub use shortcuts::modifier_keycaps; +pub use system_material::MAX_NATIVE_MATERIALS; +pub use system_material::SystemMaterial; +pub use taskbar::Taskbar; +pub use taskbar::TaskbarProgress; +pub use text::FontSmoothing; +pub use text::Icon; +pub use text::Link; +pub use text::LinkPaint; +pub use text::SmoothingSupport; +pub use text::Span; +pub use text::TextCase; +pub use text::TextHighlight; +pub use theme::Theme; +pub use time::LocalTime; +pub use titlebar::ChromeInsets; +pub use titlebar::Titlebar; +pub use tok::Family; +pub use tok::OpticalSize; +pub use tok::TextStyle; +pub use tooling::AppSpec; +pub use tooling::Chrome; +pub use tooling::extra_args; +pub use tooling::is_headless; +pub use tooling::run; +pub use tooling::run_windows; +pub use tooling::run_windows_with; +pub use tooling::run_windows_with_args; +pub use tooling::run_with; +pub use tooling::set_app_id; +pub use tooling::try_run_windows_with; +pub use tooling::try_run_windows_with_args; +pub use tracked::Reads; +pub use tracked::Tracked; +pub use tracked::tracked_reads; +pub use tray::Tray; +pub use tray::TrayError; +pub use tray::TrayEvent; +pub use tray::TrayIcon; +pub use tray::TrayItem; +pub use tray::TraySpec; +pub use video::MediaRequest; +pub use video::MediaSource; +pub use video::Player; +pub use video::PlayerState; +pub use video::Video; +pub use window::WindowHandle; +pub use window::spec as windows; +pub use windows::AnyWindowSpec; +pub use windows::ConfiguredWindowOptions; +pub use windows::Display; +pub use windows::MacWindowOptions; +pub use windows::RunOptions; +pub use windows::WindowOptions; +pub use windows::WindowPlacement; +pub use windows::WindowSpec; +pub use windows::open_window; +pub use winit::raw_window_handle; + +/// The logical clock a scene fn (`AppSpec::scenes`) builds its state against. `--scene` starts +/// at time zero. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +#[non_exhaustive] +pub struct SceneClock { + pub now: f64, + pub dt: f64, +} + +thread_local! { + static SCENE_CLOCK: std::cell::Cell<SceneClock> = const { std::cell::Cell::new(SceneClock { now: 0.0, dt: 0.0 }) }; +} + +/// Readable from scene fns, `AppSpec::init` and `AppSpec::setup`; zero anywhere else. +pub fn scene_clock() -> SceneClock { + SCENE_CLOCK.get() +} + +/// Runs `f` (a scene fn or `init`) with `clock` as the scene clock. +pub(crate) fn with_scene_clock<T>(clock: SceneClock, f: impl FnOnce() -> T) -> T { + struct Restore(SceneClock); + impl Drop for Restore { + fn drop(&mut self) { SCENE_CLOCK.set(self.0); } + } + + let _restore = Restore(SCENE_CLOCK.replace(clock)); + f() +} diff --git a/app/vendor/rune/crates/rune/src/memo.rs b/app/vendor/rune/crates/rune/src/memo.rs new file mode 100644 index 0000000..23fb50e --- /dev/null +++ b/app/vendor/rune/crates/rune/src/memo.rs @@ -0,0 +1,670 @@ +//! [`memo`]: reuse a subtree whose inputs haven't changed instead of building it again. +//! +//! A view runs top to bottom every commit, so a transcript of 500 messages builds 500 messages +//! every frame its counter ticks. Wrapping each in `memo(id, version, || ...)` builds a message +//! once per version: later commits get the element the first build returned, without calling +//! the closure. Children reach the element tree only when the element mounts, so the rows a +//! `virtualize` list leaves offscreen cost a lookup each and nothing else. +//! +//! What a reused subtree keeps, and what invalidates it: +//! +//! - **Identity.** A reused subtree is the same elements under the same key paths, so node ids, +//! hover and press, focus, scroll offsets and running springs carry on exactly as if it had +//! been built again. The inspector, `--tree`, `Runtime::elements` and accessibility read the +//! element tree after the subtree is in it, and see it like any other. +//! - **Handlers** in the subtree are the ones its build made. They see what they captured then, +//! so anything a handler captures that can change must be part of `version`. Handlers that +//! only send a message or an id never go stale. A row's position is one of those things: a +//! handler in a list row should capture the row's id, never its index, which shifts when +//! rows are inserted or removed above it while the memo keeps the old handler. +//! - **Live values and pixels** stay bound: a `Live`, `LiveText` or `Pixels` is a shared handle, +//! so a reused subtree shows its newest value or image without a rebuild. +//! - **Environment.** The window's dark mode, scale, reduced-motion preference, system accent +//! (`Cx::accent`, `Cx::focus_color`) and blend mode (`theme::blends_srgb`, which theme +//! colours resolve by) are part of every version, so changing any of them builds +//! again. App state the closure reads (a theme, a locale, a selection) must be part of +//! `version`. For a text field that's the +//! `TextEdit` itself, which hashes its text, selection, composition and focus. +//! - **`Cx` reads.** `Cx::layout`, `Cx::layout_with`, `Cx::layout_size`, `Cx::window_layout`, +//! `Cx::window_layout_with` and `Cx::caret` called inside the closure are recorded with +//! what they returned. A reuse counts them as read +//! again, so the view still re-runs when they move, and builds again when one returns +//! something else. They needn't be in `version`. +//! - **Hot reload** (`rune/hot`) drops every cached subtree, so new code always builds. +//! - **Virtual rows** that scroll out keep their cached subtree as long as the view still +//! creates them (virtualized rows always are); scrolling back in mounts it again without a +//! build. A memo the view stops creating is dropped once the commit that stopped creating it +//! applies (a commit may build its view more than once). Rows `El::virtual_rows` builds count +//! as part of the view build, so a memo in one is kept while its row stays in the mounted +//! window and dropped once the row leaves it. +//! +//! The id names the subtree within the window, so it must be unique among the memos of one +//! view build (a message id, say). A memo inside another's closure is named within it, so +//! `memo("b0", ..)` inside each message's memo doesn't collide. A second memo with an id +//! already used in the same build just builds, uncached. +//! +//! Layout isn't stored: a reused subtree still lays out each commit it is mounted, but Taffy +//! keeps each unchanged node's measured size, so this is cheap while width and constraints hold. + +use std::cell::RefCell; +use std::hash::{Hash, Hasher}; +use std::rc::Rc; + +use crate::El; +use crate::runtime::HashMap; +use crate::runtime::layout_read::{LayoutRects, SELECTION, note_read}; + +mod built; +mod reads; +mod region; +pub(crate) mod snapshot; +#[cfg(test)] +mod tests; + +pub(crate) use built::Built; +#[cfg(test)] +pub(crate) use built::Shared; +pub(crate) use built::has_focused_input; +pub(crate) use reads::Reads; +pub(crate) use reads::Replayed; +pub(crate) use reads::read_caret; +pub(crate) use reads::read_layout; +pub(crate) use reads::read_layout_with; +pub(crate) use reads::read_selection; +pub(crate) use reads::recording; +use reads::{Read, Seen, dedup_states}; + +pub use reads::layout; +pub use reads::layout_size; +pub use reads::layout_with; +pub use reads::window_layout; +pub use reads::window_layout_with; +pub use region::region; +pub use region::region_warnings; +pub use region::region_with; +pub use snapshot::snapshot; + +struct Entry { + id: Rc<str>, + version: u64, + built: Rc<Built>, + key: Option<String>, + /// The `Cx` reads its build made, its nested memos' included. + reads: Vec<Read>, + /// Memos built inside this one's closure, kept while this one is reused. + nested: Vec<Rc<str>>, + /// The view build that last used it. + pass: u64, + /// `0` when built in `view`, else [`virtual_row_tag`] of the `virtual_rows` row that built it. + virtual_row: u64, +} + +/// One window's cached subtrees. +#[derive(Default)] +pub(crate) struct MemoCache { + entries: HashMap<Rc<str>, Entry>, + pub(crate) flattened: crate::runtime::HashMap<u64, crate::runtime::memo_reuse::FlattenedMemo>, + pub(crate) pending_scratch: Vec<crate::runtime::memo_reuse::PendingFlat>, + pub(crate) reused_scratch: Vec<crate::runtime::memo_reuse::ReusedSpan>, + pub(crate) skip_scratch: Vec<crate::runtime::memo_reuse::CleanApplySpan>, + pub(crate) split_scratch: Vec<bool>, + pub(crate) taken_paths_scratch: Vec<(u32, u32)>, + pub(crate) path_scratch: String, + id_scratch: String, + pure_counts: HashMap<(u64, u64, u64), u32>, + nested_scratch: Vec<(Rc<str>, u64)>, + pub(crate) present_len: usize, + pass: u64, + #[cfg(test)] + pub(crate) builds: usize, +} + +impl MemoCache { + pub(crate) fn clear(&mut self) { + self.entries.clear(); + self.flattened.clear(); + self.present_len = 0; + } + + /// No memos, counting passes on from this cache's, for a build that must start from scratch. + #[cfg(feature = "hot")] + pub(crate) fn emptied(&self) -> MemoCache { + MemoCache { pass: self.pass, ..MemoCache::default() } + } + + #[cfg(test)] + pub(crate) fn len(&self) -> usize { + self.entries.len() + } + + /// The pass the next view build will be. + pub(crate) fn next_pass(&self) -> u64 { + self.pass + 1 + } + + /// Drops the memos whose own id starts with `prefix`, wherever they nest, and those built + /// inside them. + pub(crate) fn evict_prefix(&mut self, prefix: &str) { + let before = self.entries.len(); + self.entries.retain(|id, _| !(id.starts_with(prefix) || id.match_indices('/').any(|(i, _)| id[i + 1..].starts_with(prefix)))); + if self.entries.len() < before { + let live: crate::runtime::HashSet<u64> = self.entries.values().map(|e| e.built.id).collect(); + self.flattened.retain(|id, _| live.contains(id)); + } + } + + /// Drops the memos no build since pass `since` (a [`MemoCache::next_pass`]) used: a commit + /// keeps what any of its view builds used. + pub(crate) fn keep_since(&mut self, since: u64) { + // A commit that didn't build the view used no memos, and drops none. + if self.pass < since { return; } + let before = self.entries.len(); + self.entries.retain(|_, e| e.pass >= since); + if self.entries.len() < before && !self.flattened.is_empty() { + let live: crate::runtime::HashSet<u64> = self.entries.values().map(|e| e.built.id).collect(); + self.flattened.retain(|id, _| live.contains(id)); + } + } +} + +impl crate::runtime::RuntimeCore { + pub(crate) fn invalidate_memos_by_prefix(&mut self, prefix: &str) { + self.commit.evict_memo_prefix(prefix); + self.invalidate(); + } +} + +struct Scope { + cache: MemoCache, + env: u64, + scale: f32, + virtual_row: u64, + /// The ids of the memos whose closures are running, innermost last. + path: Vec<Rc<str>>, + /// The memos each running closure has created so far. + nested: Vec<Vec<Rc<str>>>, + /// The `Cx` reads each running closure has made so far. + reads: Vec<Vec<Read>>, + seen: Seen, + replayed: Replayed, +} + +impl Scope { + /// Counts `reads` toward the running closure, if any. + fn note(&mut self, reads: &[Read]) { + let Some(frame) = self.reads.last_mut() else { return }; + for read in reads { + // State reads can number in the hundreds: they're deduplicated once, when the memo ends. + if matches!(read, Read::State(..)) || !frame.contains(read) { + frame.push(read.clone()); + } + } + } +} + +thread_local! { + static SCOPES: RefCell<Vec<Scope>> = const { RefCell::new(Vec::new()) }; +} + +/// Makes `cache` the one [`memo`] uses until [`Guard::finish`], for one view build. +/// `caret` and `layout` are what the view's `Cx` returns. +#[allow(clippy::too_many_arguments)] +pub(crate) fn enter( + mut cache: MemoCache, + env: crate::Env, + accent: crate::SystemAccent, + reduced_motion: bool, + srgb_blend: bool, + chrome: [u32; 4], + caret: Option<(String, [f32; 4])>, + layout: LayoutRects, +) -> Guard { + cache.pass += 1; + cache.pure_counts.clear(); + let accent = [accent.accent(env.system_dark), accent.focus(env.system_dark)].map(|c| [c.r, c.g, c.b, c.a].map(f32::to_bits)); + let scale = env.scale; + // Theme colours resolve per blend mode (`theme::blends_srgb`), so a switch rebuilds memos. + // So does a change to what the window's controls take (`Cx::chrome_insets`), and to the icon + // swap, whose icons can take another size (`text::set_icon_swap_size`). + let icons = crate::text::icon::swap_state(); + let env = hash_of(&(env.system_dark, scale.to_bits(), reduced_motion, accent, crate::platform::scroll_bars::scoped(), srgb_blend, chrome, icons)); + let scope = Scope { + cache, + env, + scale, + virtual_row: 0, + path: Vec::new(), + nested: Vec::new(), + reads: Vec::new(), + seen: Seen { caret, layout }, + replayed: Replayed::default(), + }; + SCOPES.with_borrow_mut(|s| s.push(scope)); + Guard(true) +} + +pub(crate) fn virtual_row_tag(list_path: &str, row_key: &str) -> u64 { + hash_of(&(list_path, row_key)).max(1) +} + +struct VirtualRowGuard(Option<u64>); + +impl Drop for VirtualRowGuard { + fn drop(&mut self) { + if let Some(prev) = self.0 { + SCOPES.with_borrow_mut(|scopes| { + if let Some(s) = scopes.last_mut() { + s.virtual_row = prev; + } + }); + } + } +} + +fn enter_virtual_row(tag: u64) -> VirtualRowGuard { + VirtualRowGuard(SCOPES.with_borrow_mut(|scopes| { + scopes.last_mut().map(|s| std::mem::replace(&mut s.virtual_row, tag)) + })) +} + +#[inline] +pub(crate) fn in_virtual_row<R>(tag: u64, f: impl FnOnce() -> R) -> R { + let _reset = enter_virtual_row(tag); + f() +} + +/// [`enter`] for a commit that skips running `view` and builds only newly entering virtual rows, +/// keeping memos built in `view` (`virtual_row == 0`) or in rows `kept_rows` stays mounted on. +#[allow(clippy::too_many_arguments)] +pub(crate) fn enter_partial( + mut cache: MemoCache, + kept_rows: &crate::runtime::HashSet<u64>, + env: crate::Env, + accent: crate::SystemAccent, + reduced_motion: bool, + srgb_blend: bool, + chrome: [u32; 4], + caret: Option<(String, [f32; 4])>, + layout: LayoutRects, +) -> Guard { + let next = cache.pass + 1; + let mut nested = std::mem::take(&mut cache.nested_scratch); + nested.clear(); + for e in cache.entries.values_mut() { + if e.virtual_row == 0 || kept_rows.contains(&e.virtual_row) { + e.pass = next; + nested.extend(e.nested.iter().map(|id| (id.clone(), e.virtual_row))); + } + } + if !nested.is_empty() { + keep_nested_rows(&mut cache, &mut nested, next); + } + cache.nested_scratch = nested; + enter(cache, env, accent, reduced_motion, srgb_blend, chrome, caret, layout) +} + +/// Ends the view build [`enter`] began; dropped without [`Guard::finish`] (a panicking view), +/// it discards the cache. +pub(crate) struct Guard(bool); + +impl Guard { + /// The cache back, and the `Cx` reads of the memos this build reused. Unused memos stay + /// until [`MemoCache::keep_since`], since a commit may build its view more than once. + pub(crate) fn finish(mut self) -> (MemoCache, Replayed) { + self.0 = false; + let Scope { cache, replayed, .. } = SCOPES.with_borrow_mut(|s| s.pop()).expect("memo scope"); + (cache, replayed) + } +} + +impl Drop for Guard { + fn drop(&mut self) { + if self.0 { + SCOPES.with_borrow_mut(|s| s.pop()); + } + } +} + +pub(crate) fn hash_of(v: &impl Hash) -> u64 { + let mut h = rustc_hash::FxHasher::default(); + v.hash(&mut h); + h.finish() +} + +/// `el` keyed `key`; debug builds warn once per call site when it already had another key. +#[cfg_attr(debug_assertions, track_caller)] +fn keyed(el: El, key: String) -> El { + #[cfg(debug_assertions)] + if let Some(existing) = &el.key { + crate::tooling::perf_warn::memo_key_replaced(&key, existing, std::panic::Location::caller()); + } + el.key(key) +} + +fn bump_pass() { + SCOPES.with_borrow_mut(|s| { + if let Some(s) = s.last_mut() { + s.cache.pass += 1; + } + }); +} + +/// Runs `f` inside the view build in progress as if it were the next build, and the rest of the +/// build carries on as that one: memos used so far may be used once more, as the following frame +/// would use them. For tooling that measures what a rebuild costs a frame: a surface rebuilt +/// many times in one build to time it, its unchanged inner memos reused each time. Outside a +/// view build it just runs `f`. +#[inline] +pub fn as_next_build<R>(f: impl FnOnce() -> R) -> R { + bump_pass(); + f() +} + +/// The subtree `build` returns, keyed `id`, built again only when `version` (or the window's +/// environment) differs from the last build's. Otherwise `build` isn't called and the +/// previous subtree is reused, with the same node ids and state. +/// +/// ```ignore +/// col().growth(GrowthSpec::default()).virtualize(72.0).children(s.messages.iter().map(|m| { +/// memo(format!("msg-{}", m.id), (m.revision, s.theme), || message_view(m)) +/// })) +/// ``` +/// +/// Anything the closure reads that can change belongs in `version`, apart from `Cx::layout`, +/// `Cx::layout_with`, `Cx::layout_size` and `Cx::caret`, which are tracked; see the +/// [module docs](crate::memo) for handlers, live values and what else invalidates. Outside a view (a test calling a view function directly) +/// it just builds. +#[inline] +#[cfg_attr(debug_assertions, track_caller)] +pub fn memo(id: impl Into<String>, version: impl Hash, build: impl FnOnce() -> El) -> El { + memo_with_hash(id, hash_of(&version), build) +} + +/// [`memo`] with a version already hashed to a `u64`, for a caller that keeps its own +/// hashes (a plugin across a C ABI, where `impl Hash` can't cross). The window's environment +/// still joins it, as it does `memo`'s. +#[inline] +#[cfg_attr(debug_assertions, track_caller)] +pub fn memo_with_hash(id: impl Into<String>, version: u64, build: impl FnOnce() -> El) -> El { + let mut build = Some(build); + memo_inner(id.into(), version, false, &mut || build.take().expect("memo builds once")()) +} + +/// A memo, or with `region` a [`region`]: a region's reads of [`Tracked`](crate::Tracked) +/// values join its reads. A memo's don't: its version says when it builds again, as it always +/// has, so a cell that moves every frame (a clock) it reads doesn't rebuild it. +#[cfg_attr(debug_assertions, track_caller)] +fn memo_inner(key: String, version: u64, region: bool, build: &mut dyn FnMut() -> El) -> El { + enum Step { + Reuse(Rc<Built>), + Build { id: Rc<str>, version: u64, store: bool }, + Plain, + } + let step = SCOPES.with_borrow_mut(|scopes| { + let Some(s) = scopes.last_mut() else { return Step::Plain }; + let version = hash_of(&(version, s.env)); + let name: &str = if let Some(p) = s.path.last() { + s.cache.id_scratch.clear(); + s.cache.id_scratch.reserve(p.len() + 1 + key.len()); + s.cache.id_scratch.push_str(p); + s.cache.id_scratch.push('/'); + s.cache.id_scratch.push_str(&key); + &s.cache.id_scratch + } else { + &key + }; + let pass = s.cache.pass; + let has_parent = !s.nested.is_empty(); + let mut reused = None; + let mut store = true; + if let Some(e) = s.cache.entries.get_mut(name) { + if e.pass == pass { + store = false; + } else if { report_miss(&key, e.version == version, &e.reads, &s.seen); e.version == version && e.reads.iter().all(|r| s.seen.holds(r)) } { + e.pass = pass; + e.virtual_row = s.virtual_row; + for read in &e.reads { + match read { + Read::Caret(..) => s.replayed.caret = true, + Read::Layout(k, _) => note_read(&mut s.replayed.layout, k, None), + Read::LayoutWith(k, same, _) => note_read(&mut s.replayed.layout, k, Some(same.clone())), + Read::Selection(_) => note_read(&mut s.replayed.layout, SELECTION, None), + Read::State(..) => {} + } + } + let parent_reads = if s.reads.is_empty() || e.reads.is_empty() { Vec::new() } else { e.reads.clone() }; + s.cache.nested_scratch.extend(e.nested.iter().map(|id| (id.clone(), s.virtual_row))); + reused = Some((has_parent.then(|| e.id.clone()), e.built.clone(), parent_reads)); + } + } + if let Some((parent_id, built, reads)) = reused { + if !s.cache.nested_scratch.is_empty() { + let mut scratch = std::mem::take(&mut s.cache.nested_scratch); + keep_nested_rows(&mut s.cache, &mut scratch, pass); + s.cache.nested_scratch = scratch; + } + if !reads.is_empty() { + s.note(&reads); + } + if let (Some(parent), Some(id)) = (s.nested.last_mut(), parent_id) { + parent.push(id); + } + return Step::Reuse(built); + } + let id: Rc<str> = name.into(); + if let Some(parent) = s.nested.last_mut() { + parent.push(id.clone()); + } + s.path.push(id.clone()); + s.nested.push(Vec::new()); + s.reads.push(Vec::new()); + Step::Build { id, version, store } + }); + let (id, version, store) = match step { + Step::Reuse(built) => return built.placeholder(Some(key)), + Step::Plain => return keyed(build(), key), + Step::Build { id, version, store } => (id, version, store), + }; + // A region's `Tracked` reads join its reads; a memo's closure records none of its own (a + // region inside it still does, and they reach it as any nested read does). + let (el, states) = if region { + crate::tracked::begin(); + let el = keyed(build(), key); + (el, crate::tracked::end()) + } else { + let paused = crate::tracked::pause(); + let el = keyed(build(), key); + crate::tracked::resume(paused); + (el, Vec::new()) + }; + SCOPES.with_borrow_mut(|scopes| { + let Some(s) = scopes.last_mut() else { return el }; + s.path.pop(); + let nested = s.nested.pop().unwrap_or_default(); + let mut reads = s.reads.pop().unwrap_or_default(); + reads.extend(states.into_iter().map(|(id, version)| Read::State(id, version))); + dedup_states(&mut reads); + s.note(&reads); + #[cfg(test)] + { + s.cache.builds += 1; + } + if !store { + return el; + } + let (built, key) = Built::new(el, s.scale, region); + let el = built.placeholder(key.clone()); + let pass = s.cache.pass; + let virtual_row = s.virtual_row; + let entry_id = id.clone(); + s.cache.entries.insert(id, Entry { id: entry_id, version, built, key, reads, nested, pass, virtual_row }); + el + }) +} + +/// With `RUNE_REGION_MISS` set, prints what made a memo or region build again: the first read +/// that no longer holds (`state <cell> v<version>` for a [`Tracked`](crate::Tracked) value, +/// `layout <key>`, `caret <key>`, `selection`), or `version` when its version changed. For +/// finding what keeps a region rebuilding; `Tracked::id` names the cells. +fn report_miss(key: &str, same_version: bool, reads: &[Read], seen: &Seen) { + static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + if !*ON.get_or_init(|| std::env::var_os("RUNE_REGION_MISS").is_some()) { return; } + if !same_version { return eprintln!("rune-miss {key} version"); } + let Some(r) = reads.iter().find(|r| !seen.holds(r)) else { return }; + let why = match r { + Read::State(id, v) => format!("state {id} v{v}"), + Read::Layout(k, _) | Read::LayoutWith(k, _, _) => format!("layout {k}"), + Read::Caret(k, _) => format!("caret {k}"), + Read::Selection(_) => "selection".into(), + }; + eprintln!("rune-miss {key} {why}"); +} + +#[doc(hidden)] +pub fn digest(input: &(impl Hash + ?Sized)) -> (u64, u64) { + let h1 = hash_of(&input); + let mut h2 = std::collections::hash_map::DefaultHasher::new(); + input.hash(&mut h2); + (h1, h2.finish()) +} + +/// Caches a pure-data subtree by a 128-bit [`digest`] and its occurrence ordinal in the +/// current view pass (or `virtual_rows` row), preserving `el.key` (`None` when unkeyed). +#[inline] +#[doc(hidden)] +pub fn cached(digest: (u64, u64), build: impl FnOnce() -> El) -> El { + let mut build = Some(build); + cached_inner(digest, &mut || build.take().expect("cached builds once")()) +} + +fn cached_inner((h1, h2): (u64, u64), build: &mut dyn FnMut() -> El) -> El { + enum Step { + Reuse(Rc<Built>, Option<String>), + Build { id: Rc<str>, version: u64 }, + Plain, + } + let step = SCOPES.with_borrow_mut(|scopes| { + let Some(s) = scopes.last_mut() else { return Step::Plain }; + let occ = *s + .cache + .pure_counts + .entry((s.virtual_row, h1, h2)) + .and_modify(|c| *c += 1) + .or_insert(0); + let version = hash_of(&(h1, h2, s.env)); + { + use std::fmt::Write; + s.cache.id_scratch.clear(); + if let Some(p) = s.path.last() { + s.cache.id_scratch.push_str(p); + s.cache.id_scratch.push('/'); + } + write!(s.cache.id_scratch, "\0{}:{h1:016x}:{h2:016x}:{occ}", s.virtual_row).ok(); + } + let pass = s.cache.pass; + let has_parent = !s.nested.is_empty(); + let mut reused = None; + if let Some(e) = s.cache.entries.get_mut(s.cache.id_scratch.as_str()) + && e.pass != pass + && e.version == version + && e.reads.iter().all(|r| s.seen.holds(r)) + { + e.pass = pass; + e.virtual_row = s.virtual_row; + for read in &e.reads { + match read { + Read::Caret(..) => s.replayed.caret = true, + Read::Layout(k, _) => note_read(&mut s.replayed.layout, k, None), + Read::LayoutWith(k, same, _) => note_read(&mut s.replayed.layout, k, Some(same.clone())), + Read::Selection(_) => note_read(&mut s.replayed.layout, SELECTION, None), + Read::State(..) => {} + } + } + let parent_reads = if s.reads.is_empty() || e.reads.is_empty() { Vec::new() } else { e.reads.clone() }; + s.cache.nested_scratch.extend(e.nested.iter().map(|id| (id.clone(), s.virtual_row))); + reused = Some((has_parent.then(|| e.id.clone()), e.built.clone(), e.key.clone(), parent_reads)); + } + if let Some((parent_id, built, key, reads)) = reused { + if !s.cache.nested_scratch.is_empty() { + let mut scratch = std::mem::take(&mut s.cache.nested_scratch); + keep_nested_rows(&mut s.cache, &mut scratch, pass); + s.cache.nested_scratch = scratch; + } + if !reads.is_empty() { + s.note(&reads); + } + if let (Some(parent), Some(id)) = (s.nested.last_mut(), parent_id) { + parent.push(id); + } + return Step::Reuse(built, key); + } + let id: Rc<str> = s.cache.id_scratch.as_str().into(); + if let Some(parent) = s.nested.last_mut() { + parent.push(id.clone()); + } + s.path.push(id.clone()); + s.nested.push(Vec::new()); + s.reads.push(Vec::new()); + Step::Build { id, version } + }); + let (id, version) = match step { + Step::Reuse(built, key) => return built.placeholder(key), + Step::Plain => return build(), + Step::Build { id, version } => (id, version), + }; + let el = build(); + SCOPES.with_borrow_mut(|scopes| { + let Some(s) = scopes.last_mut() else { return el }; + s.path.pop(); + let nested = s.nested.pop().unwrap_or_default(); + let reads = s.reads.pop().unwrap_or_default(); + s.note(&reads); + #[cfg(test)] + { + s.cache.builds += 1; + } + let (built, key) = Built::new(el, s.scale, false); + let el = built.placeholder(key.clone()); + let pass = s.cache.pass; + let virtual_row = s.virtual_row; + let entry_id = id.clone(); + s.cache.entries.insert(id, Entry { id: entry_id, version, built, key, reads, nested, pass, virtual_row }); + el + }) +} + +/// Marks the memos built inside a reused one as used, so they survive to its next build. +fn keep_nested_rows(cache: &mut MemoCache, ids: &mut Vec<(Rc<str>, u64)>, pass: u64) { + while let Some((id, virtual_row)) = ids.pop() { + if let Some(e) = cache.entries.get_mut(&id) + && e.pass != pass + { + e.pass = pass; + e.virtual_row = virtual_row; + ids.extend(e.nested.iter().map(|nested| (nested.clone(), virtual_row))); + } + } +} + +/// Whether the memo built as `id` is in the last commit's nodes, so its subtree can be reused. +pub(crate) fn flattened(id: u64) -> bool { + SCOPES.with_borrow(|scopes| scopes.last().is_some_and(|s| s.cache.flattened.contains_key(&id))) +} + +/// Marks the memos `virtual_rows` rows tagged `tags` built as used this pass, with the memos +/// built inside them: a list kept whole builds none of its rows, and they stay for when it does. +pub(crate) fn keep_rows(tags: impl Iterator<Item = u64>) { + SCOPES.with_borrow_mut(|scopes| { + let Some(s) = scopes.last_mut() else { return }; + let tags: crate::runtime::HashSet<u64> = tags.collect(); + let pass = s.cache.pass; + let mut nested = std::mem::take(&mut s.cache.nested_scratch); + nested.clear(); + for e in s.cache.entries.values_mut().filter(|e| tags.contains(&e.virtual_row)) { + e.pass = pass; + nested.extend(e.nested.iter().map(|id| (id.clone(), e.virtual_row))); + } + keep_nested_rows(&mut s.cache, &mut nested, pass); + s.cache.nested_scratch = nested; + }); +} diff --git a/app/vendor/rune/crates/rune/src/memo/built.rs b/app/vendor/rune/crates/rune/src/memo/built.rs new file mode 100644 index 0000000..a1c3426 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/memo/built.rs @@ -0,0 +1,155 @@ +//! Cached subtree representation ([`Built`], [`Shared`]), placeholder expansion on [`El`], +//! and flatten-reusability and text-prekeying checks. + +use std::rc::Rc; +use std::sync::atomic::{AtomicU64, Ordering}; + +use crate::El; +use crate::el::ElFlags; + +/// The children a memo's placeholders share. +#[derive(Clone)] +pub(crate) struct Shared { + pub(crate) children: Vec<El>, + /// Whether a focused field is among them, so an offscreen virtual row that has none isn't + /// searched for one. + pub(crate) focused_input: bool, + /// Whether two siblings anywhere among them share a key, so the per-commit key check can + /// skip a memo without any. + pub(crate) duplicate_keys: bool, + /// Whether any descendant uses `virtualize` or `virtual_rows`. + pub(crate) has_virtual: bool, + /// Whether every descendant can reuse its flattened `Node` and Taffy subtree across commits. + pub(crate) reusable: bool, +} + +impl El { + /// Every child: those shared with a memo cache, then the element's own. + pub(crate) fn all_children(&self) -> impl Iterator<Item = &El> { + self.memo_children().into_iter().flat_map(|c| c.children.iter()).chain(&self.children) + } + + /// The children shared with a memo cache, which come before `children`. + #[inline] + pub(crate) fn memo_children(&self) -> Option<&Rc<Shared>> { + self.memo.as_ref().map(|b| &b.children) + } + + /// The cached subtree this placeholder is, unless it was expanded or given extra children. + #[inline] + pub(crate) fn memo_built(&self) -> Option<&Rc<Built>> { + self.memo.as_ref().filter(|_| !self.flags.has(ElFlags::MEMO_EXTENDED)) + } + + /// Copies in the children shared with a memo cache, so the element owns all of them. + pub(crate) fn expand_memo(&mut self) { + let whole = !self.flags.has(ElFlags::MEMO_EXTENDED); + self.flags.set(ElFlags::MEMO_EXTENDED, false); + if let Some(built) = self.memo.take() { + if built.children.has_virtual { + self.flags.set(ElFlags::HAS_VIRTUAL, true); + // Its virtual lists mount their rows into the copy: flattening records the copy + // as the memo's nodes, so a later commit whose windows match keeps them. + if whole && built.reusable { + self.cold_mut().expanded_memo = Some(built.clone()); + } + } + let shared = Rc::unwrap_or_clone(built.children.clone()).children; + let own = std::mem::replace(&mut self.children, shared); + self.children.extend(own); + } + } +} + +fn el_flatten_reusable(e: &El) -> bool { + let c = &*e.cold; + // A list whose rows `virtual_rows` builds is reused with them while it mounts the same rows + // (`Measurement::keeps_windows`); one built from children isn't. + let indexed = c.virtual_rows.is_some(); + (c.virtual_estimate.is_none() || indexed) + && (c.growth.is_none() || indexed) + && c.aspect_fit <= 0.0 + && c.above.is_none() + && c.input.is_none() + && e.handlers.get().is_none_or(|h| h.modal.is_none()) + && e.text.as_ref().is_none_or(|t| !t.redacted && t.cold.live.is_none()) + && e.memo_children().is_none_or(|m| m.reusable && !m.duplicate_keys) + && e.children.iter().all(el_flatten_reusable) +} + +/// Precomputes `shape` on plain, non-input, non-cased text specs at `scale` while the freshly +/// built subtree is still uniquely owned, so flattening never has to copy a shared `TextSpec`. +fn prekey_text_shapes(el: &mut El, scale: f32) { + if el.cold.input.is_none() + && let Some(t) = &el.text + && !t.redacted + && t.case.is_none() + && t.cold.rings.is_empty() + && t.shape.is_none_or(|s| s.0 != scale.to_bits()) + && let Some(t) = &mut el.text + { + t.key_shape(scale); + } + for child in &mut el.children { + prekey_text_shapes(child, scale); + } +} + +/// Whether `el` or anything under it is a focused field. +pub(crate) fn has_focused_input(el: &El) -> bool { + el.cold.input.as_ref().is_some_and(|i| i.edit.focused) + || el.memo_children().is_some_and(|m| m.focused_input) + || el.children.iter().any(has_focused_input) +} + +/// A built subtree: its root without children (or key, supplied per placeholder), and the +/// children placeholders share. +pub(crate) struct Built { + pub(crate) id: u64, + pub(crate) reusable: bool, + /// Built by a [`region`](super::region): what it shows is what it read, so its virtual lists' + /// rows can be kept with it while their reads hold. + pub(crate) region: bool, + pub(crate) root: El, + pub(crate) children: Rc<Shared>, +} + +static NEXT_BUILT_ID: AtomicU64 = AtomicU64::new(1); + +impl Built { + pub(super) fn new(mut el: El, scale: f32, region: bool) -> (Rc<Built>, Option<String>) { + let key = el.key.take(); + el.flags.set(ElFlags::MEMO_EXTENDED, false); + let shared = if el.children.is_empty() && let Some(built) = el.memo.take() { + prekey_text_shapes(&mut el, scale); + built.children.clone() + } else { + el.expand_memo(); + prekey_text_shapes(&mut el, scale); + let children = std::mem::take(&mut el.children); + let focused_input = children.iter().any(has_focused_input); + let duplicate_keys = crate::input::key_diagnostics::memo_children_have_duplicates(&el, &children); + let has_virtual = children.iter().any(|c| c.flags.has(ElFlags::HAS_VIRTUAL)); + let reusable = !duplicate_keys && children.iter().all(el_flatten_reusable); + Rc::new(Shared { children, focused_input, duplicate_keys, has_virtual, reusable }) + }; + el.flags.set(ElFlags::HAS_VIRTUAL, el.cold.virtual_estimate.is_some()); + let reusable = shared.reusable && !shared.duplicate_keys && el_flatten_reusable(&el); + let id = NEXT_BUILT_ID.fetch_add(1, Ordering::Relaxed); + (Rc::new(Built { id, reusable, region, root: el, children: shared }), key) + } + + /// The root, with its children shared rather than copied. + // Called on every memo hit from `memo.rs`; `#[inline]` keeps it visible across codegen + // units so callers avoid copying the `key` argument into a temporary before the call. + #[inline] + pub(super) fn placeholder(self: &Rc<Self>, key: Option<String>) -> El { + let mut el = self.root.clone(); + el.key = key; + if self.children.has_virtual { + el.flags.set(ElFlags::HAS_VIRTUAL, true); + } + el.memo = Some(self.clone()); + el + } +} diff --git a/app/vendor/rune/crates/rune/src/memo/reads.rs b/app/vendor/rune/crates/rune/src/memo/reads.rs new file mode 100644 index 0000000..f2a748d --- /dev/null +++ b/app/vendor/rune/crates/rune/src/memo/reads.rs @@ -0,0 +1,210 @@ +//! Layout, caret, selection and [`Tracked`](crate::Tracked) reads recorded inside a memo build, +//! validated on reuse, and replayed toward the enclosing view. + +use std::rc::Rc; + +use crate::runtime::layout_read::{LayoutRects, SELECTION, Same, boxes_moved, moved, note_read, seen_rect, size, window_key}; + +use super::SCOPES; + +/// A `Cx` read made while a memo built, with what it returned. +#[derive(Clone)] +pub(super) enum Read { + Caret(String, Option<[f32; 4]>), + Layout(String, Option<[f32; 4]>), + /// A `Cx::layout_with` read: its function's check, and the rect it was given. + LayoutWith(String, Same, Option<[f32; 4]>), + /// A `Cx::selection_rects` read, and the boxes it returned. + Selection(Rc<[[f32; 4]]>), + /// A [`Tracked`](crate::Tracked) cell read, at its version then. + State(u32, u64), +} + +impl PartialEq for Read { + fn eq(&self, other: &Read) -> bool { + match (self, other) { + (Read::Caret(a, x), Read::Caret(b, y)) | (Read::Layout(a, x), Read::Layout(b, y)) => a == b && x == y, + (Read::LayoutWith(a, f, x), Read::LayoutWith(b, g, y)) => a == b && f.is(g) && x == y, + (Read::Selection(a), Read::Selection(b)) => a == b, + (Read::State(a, x), Read::State(b, y)) => a == b && x == y, + _ => false, + } + } +} + +/// What the `Cx` of the view being built would return now. +pub(super) struct Seen { + pub(super) caret: Option<(String, [f32; 4])>, + pub(super) layout: LayoutRects, +} + +impl Seen { + pub(super) fn holds(&self, read: &Read) -> bool { + match read { + Read::Caret(key, rect) => crate::runtime::caret_of(&self.caret, key) == *rect, + Read::Layout(key, rect) => !moved(*rect, seen_rect(&self.layout, key)), + Read::LayoutWith(key, same, rect) => !same.moved(*rect, seen_rect(&self.layout, key)), + Read::Selection(boxes) => !boxes_moved(boxes, &self.layout.selection), + Read::State(id, version) => crate::tracked::version(*id) == *version, + } + } +} + +/// Each `Read::State` once, the latest version a frame recorded for its cell. +pub(super) fn dedup_states(reads: &mut Vec<Read>) { + if reads.iter().filter(|r| matches!(r, Read::State(..))).count() < 2 { return; } + let (mut states, rest): (Vec<Read>, Vec<Read>) = std::mem::take(reads).into_iter().partition(|r| matches!(r, Read::State(..))); + states.sort_unstable_by_key(|r| match r { Read::State(id, v) => (*id, std::cmp::Reverse(*v)), _ => (0, std::cmp::Reverse(0)) }); + states.dedup_by_key(|r| match r { Read::State(id, _) => *id, _ => 0 }); + *reads = rest; + reads.extend(states); +} + +/// `Cx` reads made by memos this build reused, which the view's `Cx` didn't see. +#[derive(Default)] +pub(crate) struct Replayed { + pub(crate) caret: bool, + pub(crate) layout: crate::runtime::layout_read::LayoutReads, +} + +/// Records a `Cx::caret` read for the memo building, if any. +pub(crate) fn read_caret(key: &str, rect: Option<[f32; 4]>) { + record(|| Read::Caret(key.to_owned(), rect)); +} + +/// Records a `Cx::layout` read for the memo building, if any. +pub(crate) fn read_layout(key: &str, rect: Option<[f32; 4]>) { + record(|| Read::Layout(key.to_owned(), rect)); +} + +/// Records a `Cx::selection_rects` read for the memo building, if any. +pub(crate) fn read_selection(boxes: &Rc<[[f32; 4]]>) { + record(|| Read::Selection(boxes.clone())); +} + +/// Records a `Cx::layout_with` read for the memo building, if any. +pub(crate) fn read_layout_with(key: &str, same: &Same, rect: Option<[f32; 4]>) { + record(|| Read::LayoutWith(key.to_owned(), same.clone(), rect)); +} + +/// [`Cx::layout`](crate::Cx::layout) for a component that builds inside a view without taking +/// [`Cx`](crate::Cx); `None` outside a view build. +pub fn layout(key: &str) -> Option<[f32; 4]> { + read_outside_cx(key, |rect| Read::Layout(key.to_owned(), rect)).flatten() +} + +/// [`Cx::layout_with`](crate::Cx::layout_with) for a component that builds inside a view +/// without taking [`Cx`](crate::Cx); `None` outside a view build. +pub fn layout_with<T: PartialEq + 'static>(key: &str, f: impl Fn([f32; 4]) -> T + 'static) -> Option<T> { + let mut value = None; + let found = read_outside_cx(key, |rect| { + value = rect.map(&f); + let same = Same::new(f); + Read::LayoutWith(key.to_owned(), same, rect) + }); + found.and(value) +} + +/// [`Cx::layout_size`](crate::Cx::layout_size) for a component that builds inside a view +/// without taking [`Cx`](crate::Cx); `None` outside a view build. +pub fn layout_size(key: &str) -> Option<[f32; 2]> { + layout_with(key, size) +} + +/// [`Cx::window_layout`](crate::Cx::window_layout) for a component that builds inside a view +/// without taking [`Cx`](crate::Cx); `None` outside a view build. +pub fn window_layout(key: &str) -> Option<[f32; 4]> { + layout(&window_key(key)) +} + +/// [`Cx::window_layout_with`](crate::Cx::window_layout_with) for a component that builds +/// inside a view without taking [`Cx`](crate::Cx); `None` outside a view build. +pub fn window_layout_with<T: PartialEq + 'static>(key: &str, f: impl Fn([f32; 4]) -> T + 'static) -> Option<T> { + layout_with(&window_key(key), f) +} + +/// A layout read of `key` made without a `Cx`, counted toward the view and the memo building, +/// if any: `read` turns the rect the view sees into its record. The rect, or `None` outside a +/// view build. +fn read_outside_cx(key: &str, read: impl FnOnce(Option<[f32; 4]>) -> Read) -> Option<Option<[f32; 4]>> { + SCOPES.with_borrow_mut(|scopes| { + let s = scopes.last_mut()?; + let rect = seen_rect(&s.seen.layout, key); + let made = read(rect); + let same = match &made { Read::LayoutWith(_, same, _) => Some(same.clone()), _ => None }; + note_read(&mut s.replayed.layout, key, same); + if !s.reads.is_empty() { + s.note(&[made]); + } + Some(rect) + }) +} + +fn record(read: impl FnOnce() -> Read) { + SCOPES.with_borrow_mut(|scopes| { + if let Some(s) = scopes.last_mut() + && !s.reads.is_empty() + { + s.note(&[read()]); + } + }); +} + +/// What a build read, as a region's reads: its [`Tracked`](crate::Tracked) values, layout rects +/// and caret, and those of the memos it built or reused. +#[derive(Default, Clone)] +pub(crate) struct Reads(Vec<Read>); + +impl std::fmt::Debug for Reads { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "Reads({})", self.0.len()) + } +} + +impl Reads { + /// Whether everything read still reads the same. + pub(crate) fn hold(&self) -> bool { + SCOPES.with_borrow(|scopes| scopes.last().is_none_or(|s| self.0.iter().all(|r| s.seen.holds(r)))) + } + + /// Counts the reads as made again, as a reused memo's are: what was built from them is + /// used again without being built. + pub(crate) fn replay(&self) { + SCOPES.with_borrow_mut(|scopes| { + let Some(s) = scopes.last_mut() else { return }; + for read in &self.0 { + match read { + Read::Caret(..) => s.replayed.caret = true, + Read::Layout(k, _) => note_read(&mut s.replayed.layout, k, None), + Read::LayoutWith(k, same, _) => note_read(&mut s.replayed.layout, k, Some(same.clone())), + Read::Selection(_) => note_read(&mut s.replayed.layout, SELECTION, None), + Read::State(..) => {} + } + } + s.note(&self.0); + }); + } +} + +fn begin_recording() -> bool { + let framed = SCOPES.with_borrow_mut(|scopes| scopes.last_mut().map(|s| s.reads.push(Vec::new())).is_some()); + crate::tracked::begin(); + framed +} + +fn end_recording(framed: bool) -> Reads { + let states = crate::tracked::end(); + let mut reads = SCOPES.with_borrow_mut(|scopes| scopes.last_mut().filter(|_| framed).and_then(|s| s.reads.pop())).unwrap_or_default(); + reads.extend(states.into_iter().map(|(id, version)| Read::State(id, version))); + dedup_states(&mut reads); + SCOPES.with_borrow_mut(|scopes| if let Some(s) = scopes.last_mut() { s.note(&reads) }); + Reads(reads) +} + +/// Runs `f` recording what it reads, for a caller that reuses what `f` built while the reads hold. +#[inline] +pub(crate) fn recording<R>(f: impl FnOnce() -> R) -> (R, Reads) { + let framed = begin_recording(); + let out = f(); + (out, end_recording(framed)) +} diff --git a/app/vendor/rune/crates/rune/src/memo/region.rs b/app/vendor/rune/crates/rune/src/memo/region.rs new file mode 100644 index 0000000..c630149 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/memo/region.rs @@ -0,0 +1,98 @@ +//! [`region`] and [`region_with`]: subtrees keyed by their [`Tracked`](crate::Tracked) and `Cx` +//! reads, with debug stale-region checking. + +#[cfg(debug_assertions)] +use std::cell::RefCell; +use std::hash::Hash; + +use crate::El; + +use super::{hash_of, memo_inner}; + +/// The version every [`region`] passes: a region's reads are its version. +const REGION: u64 = 0x7265_6769_6f6e_0001; + +/// The subtree `build` returns, keyed `id`, built again only when something it read changed: +/// a [`Tracked`](crate::Tracked) value it read was written, a `Cx` layout or caret read it made +/// moved, or the window's environment changed. Otherwise `build` isn't called and the previous +/// subtree is reused whole, as a [`memo`](super::memo)'s is, with the same node ids and state. +/// +/// A region must read the state it shows through `Tracked` values: anything else it reads (a +/// plain field, a global, a `Cell`) can change without it noticing. Debug builds build every +/// reused region again and print the first element that differs, naming the region. +#[inline] +#[cfg_attr(debug_assertions, track_caller)] +pub fn region(id: impl Into<String>, build: impl FnOnce() -> El) -> El { + region_with(id, (), build) +} + +/// [`region`] that also rebuilds when `inputs` change: values the closure uses that aren't +/// [`Tracked`](crate::Tracked) or read inside it, such as a palette or a size computed by the +/// caller. Debug builds check its reuse as `region`'s. +#[inline] +#[cfg_attr(debug_assertions, track_caller)] +pub fn region_with(id: impl Into<String>, inputs: impl Hash, build: impl FnOnce() -> El) -> El { + let mut build = Some(build); + region_inner(id.into(), hash_of(&(REGION, inputs)), &mut || build.take().expect("a region builds once")()) +} + +#[cfg_attr(debug_assertions, track_caller)] +fn region_inner(key: String, version: u64, build: &mut dyn FnMut() -> El) -> El { + #[cfg(not(debug_assertions))] + { + memo_inner(key, version, true, build) + } + #[cfg(debug_assertions)] + { + let check = key.clone(); + let mut called = false; + let el = memo_inner(key, version, true, &mut || { + called = true; + build() + }); + // Reused: debug builds build it again to show it was right to. + if !called { + let fresh = build(); + let (mut a, mut b) = (Vec::new(), Vec::new()); + print_el(&el, "", &mut a); + print_el(&fresh, "", &mut b); + if let Some(i) = (0..a.len().max(b.len())).find(|&i| a.get(i) != b.get(i)) { + REGION_WARNINGS.with_borrow_mut(|w| { + if w.iter().any(|x: &String| x.starts_with(&format!("rune: region {check:?} "))) { return; } + let warning = format!( + "rune: region {check:?} was reused, but building it again gives something else at element {i}: \ + reused {:?}, built {:?}. It reads state that isn't Tracked.", + a.get(i).map_or("(none)", String::as_str), b.get(i).map_or("(none)", String::as_str)); + eprintln!("{warning}"); + w.push(warning); + }); + } + } + el + } +} + +#[cfg(debug_assertions)] +thread_local! { + static REGION_WARNINGS: RefCell<Vec<String>> = const { RefCell::new(Vec::new()) }; +} + +/// The stale-region warnings debug builds printed (`region`); always empty in release builds. +pub fn region_warnings() -> Vec<String> { + #[cfg(debug_assertions)] + { REGION_WARNINGS.with_borrow(Clone::clone) } + #[cfg(not(debug_assertions))] + { Vec::new() } +} + +/// One line per element of `el`'s subtree, in order: its place, role, style, visuals and text, +/// without its handlers. What a region's debug check compares. +#[cfg(debug_assertions)] +fn print_el(el: &El, parent: &str, out: &mut Vec<String>) { + let path = format!("{parent}/{}", el.key.as_deref().unwrap_or("#")); + let text = el.text.as_ref().map(|t| format!("{:?} {:?} {}/{} {} spans", t.content, t.color, t.style.size, t.style.weight, t.spans.len())); + out.push(format!("{path} {} {:?} {:?} {:?}", el.role_name(), el.style, el.vis, text)); + for child in el.all_children() { + print_el(child, &path, out); + } +} diff --git a/app/vendor/rune/crates/rune/src/memo/snapshot.rs b/app/vendor/rune/crates/rune/src/memo/snapshot.rs new file mode 100644 index 0000000..b7f9aeb --- /dev/null +++ b/app/vendor/rune/crates/rune/src/memo/snapshot.rs @@ -0,0 +1,48 @@ +//! Component history is read from the start of a commit, even when measurement retries. + +use std::any::{Any, TypeId}; +use std::cell::RefCell; +use std::collections::HashMap; +use std::rc::Rc; + +type Snapshots = HashMap<(TypeId, String), Rc<dyn Any>>; + +thread_local! { + static SCOPES: RefCell<Vec<Snapshots>> = const { RefCell::new(Vec::new()) }; +} + +/// A component's history before this commit first built it. +/// +/// A view may run several times in one commit while layout reads, focus, caret or virtual +/// rows settle. Components that remember previous content or a first-seen flag must compare +/// each build against this snapshot, then write their new history, rather than comparing +/// against a discarded measurement's writes. `key` names the history within its type; give +/// independent components different keys. Outside a runtime commit this just clones `value`. +/// +/// The snapshot lives only until the commit ends. `Clone` must copy the history itself, not +/// share mutable cells with it. This is for component history, not application state or I/O. +pub fn snapshot<T: Clone + 'static>(key: &str, value: &T) -> Rc<T> { + SCOPES.with_borrow_mut(|scopes| { + let Some(scope) = scopes.last_mut() else { return Rc::new(value.clone()) }; + scope.entry((TypeId::of::<T>(), key.to_owned())) + .or_insert_with(|| Rc::new(value.clone())) + .clone().downcast::<T>().ok().expect("snapshot type is part of its key") + }) +} + +pub(crate) struct Guard; + +/// One scope surrounds every measurement pass, not each invocation of the view. +pub(crate) fn enter() -> Guard { + SCOPES.with_borrow_mut(|scopes| scopes.push(HashMap::new())); + Guard +} + +impl Drop for Guard { + fn drop(&mut self) { + SCOPES.with_borrow_mut(|scopes| { scopes.pop(); }); + } +} + +#[cfg(test)] +mod tests; diff --git a/app/vendor/rune/crates/rune/src/memo/snapshot/tests.rs b/app/vendor/rune/crates/rune/src/memo/snapshot/tests.rs new file mode 100644 index 0000000..a0c5f08 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/memo/snapshot/tests.rs @@ -0,0 +1,32 @@ +use super::*; + +#[test] +fn first_seen_and_previous_values_are_stable_for_every_pass_of_one_commit() { + let mut seen = false; + let mut count = 9; + { + let _commit = enter(); + for _ in 0..4 { + assert!(!*snapshot("item", &seen)); + assert_eq!(*snapshot("item", &count), 9, "types have separate histories"); + seen = true; + count = 8; + } + } + let _next_commit = enter(); + assert!(*snapshot("item", &seen)); + assert_eq!(*snapshot("item", &count), 8); + assert_eq!(*snapshot("other", &12), 12); +} + +#[test] +fn nested_commits_and_unwinds_restore_the_outer_scope() { + let _outer = enter(); + assert_eq!(*snapshot("item", &9), 9); + std::panic::catch_unwind(|| { + let _inner = enter(); + assert_eq!(*snapshot("item", &8), 8); + panic!("discard inner scope"); + }).ok(); + assert_eq!(*snapshot("item", &7), 9); +} diff --git a/app/vendor/rune/crates/rune/src/memo/tests.rs b/app/vendor/rune/crates/rune/src/memo/tests.rs new file mode 100644 index 0000000..61d5b25 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/memo/tests.rs @@ -0,0 +1,406 @@ +use std::cell::Cell; + +use super::*; +use crate::{Cx, Env, GrowthSpec, Runtime, ScrollSpec, col, el, text}; + +thread_local! { + static BUILDS: Cell<usize> = const { Cell::new(0) }; +} + +fn counted(e: El) -> El { + BUILDS.set(BUILDS.get() + 1); + e +} + +struct S { + version: u32, + ticks: u32, + presses: u32, +} + +fn view(s: &S, _: &mut Cx<S>) -> El { + col().size(200.0, 200.0).children([ + memo("card", s.version, || { + counted(col().child(el().key("button").size(40.0, 40.0).fill(crate::Color::WHITE).on_press(|s: &mut S| s.presses += 1))) + }), + text(format!("tick {}", s.ticks)).key("tick"), + ]) +} + +fn commit<S>(rt: &mut Runtime<S>) { + rt.invalidate(); + rt.frame(1.0 / 60.0); +} + +#[test] +fn an_unchanged_version_reuses_the_subtree_and_a_new_version_or_theme_builds() { + BUILDS.set(0); + let mut rt = Runtime::new(S { version: 0, ticks: 0, presses: 0 }, view, (200.0, 200.0), Env::new(true, 1.0)); + rt.frame(0.0); + assert_eq!(BUILDS.get(), 1); + let id = |rt: &Runtime<S>| rt.tree.nodes.iter().find(|n| n.key.as_deref() == Some("button")).unwrap().id; + let first = id(&rt); + for _ in 0..3 { + rt.state.ticks += 1; + commit(&mut rt); + } + assert_eq!(BUILDS.get(), 1, "other state changing doesn't build the memo"); + assert_eq!(id(&rt), first, "the reused subtree keeps its node ids"); + let (x, y) = rt.find("button").unwrap(); + rt.pointer_down(x, y); + rt.pointer_up(x, y); + rt.frame(1.0 / 60.0); + assert_eq!(rt.state.presses, 1, "handlers in a reused subtree run"); + assert_eq!(BUILDS.get(), 1); + rt.state.version += 1; + commit(&mut rt); + assert_eq!(BUILDS.get(), 2, "a new version builds"); + rt.set_system_dark(false); + rt.frame(1.0 / 60.0); + assert_eq!(BUILDS.get(), 3, "a theme change builds"); + rt.set_viewport((200.0, 200.0), 2.0); + rt.frame(1.0 / 60.0); + assert_eq!(BUILDS.get(), 4, "a scale change builds"); + rt.commit.clear_memo(); + commit(&mut rt); + assert_eq!(BUILDS.get(), 5, "a cleared cache (hot patch, tunables) builds"); + assert!(rt.elements().iter().any(|e| e.key.as_deref() == Some("button")), "tools see reused nodes"); +} + +#[test] +fn a_view_panicking_inside_a_memo_leaves_no_scope_for_the_next_build() { + let panicked = std::panic::catch_unwind(|| { + let _scope = enter(MemoCache::default(), Env::new(true, 1.0), crate::SystemAccent::DEFAULT, false, true, [0; 4], None, LayoutRects::default()); + memo("outer", 0, || memo("inner", 0, || panic!("view panicked"))) + }); + assert!(panicked.is_err()); + assert!(SCOPES.with_borrow(|s| s.is_empty()), "unwinding pops the build's scope"); + BUILDS.set(0); + let mut rt = Runtime::new(S { version: 0, ticks: 0, presses: 0 }, view, (200.0, 200.0), Env::new(true, 1.0)); + rt.frame(0.0); + commit(&mut rt); + assert_eq!(BUILDS.get(), 1, "the next window's memos cache as usual"); +} + +#[test] +fn a_memo_inside_a_reused_memo_survives_to_the_outer_ones_next_build() { + BUILDS.set(0); + fn view(s: &(u32, u32), _: &mut Cx<(u32, u32)>) -> El { + col().child(memo("outer", s.0, || { + counted(col().children([memo("inner", s.1, || counted(text("inner").key("t"))), text(format!("outer {}", s.0))])) + })) + } + let mut rt = Runtime::new((0, 0), view, (200.0, 200.0), Env::default()); + rt.frame(0.0); + assert_eq!(BUILDS.get(), 2); + commit(&mut rt); + commit(&mut rt); + assert_eq!(BUILDS.get(), 2); + rt.state.0 += 1; + commit(&mut rt); + assert_eq!(BUILDS.get(), 3, "the outer builds and finds the inner unchanged"); + rt.state.1 += 1; + commit(&mut rt); + assert_eq!(BUILDS.get(), 3, "the outer's version gates its closure, inner included"); +} + +#[test] +fn an_id_used_twice_in_one_build_builds_both() { + BUILDS.set(0); + fn view(_: &(), _: &mut Cx<()>) -> El { + col().children([ + col().key("a").child(memo("same", 0, || counted(text("a").key("t")))), + col().key("b").child(memo("same", 0, || counted(text("b").key("t")))), + ]) + } + let mut rt = Runtime::new((), view, (200.0, 200.0), Env::default()); + rt.frame(0.0); + commit(&mut rt); + let texts: Vec<_> = rt.elements().into_iter().filter_map(|e| e.text).collect(); + assert_eq!(texts, ["a", "b"]); + assert_eq!(BUILDS.get(), 3, "the first is reused, the duplicate builds each time"); +} + +struct Rows { + n: usize, + tick: u64, + memo: bool, +} + +fn row(i: usize) -> El { + col().w_full().h(72.0).padding(8.0).gap(4.0).children([ + text(format!("Message {i}")).key("title"), + text(format!("Body of message {i}, a line of text that is long enough to wrap twice")).wrap().w_full().key("body"), + text(format!("{i} min ago")).key("time"), + ]) +} + +fn rows(s: &Rows, _: &mut Cx<Rows>) -> El { + let stack = col().key("rows").w_full().growth(GrowthSpec::default()).virtualize(72.0).children((0..s.n).map(|i| { + let key = format!("r{i}"); + if s.memo { memo(key, 0, || counted(row(i))) } else { counted(row(i)).key(key) } + })); + col().w_full().h_full().children([ + text(format!("tick {}", s.tick)).key("counter"), + col().key("scroll").w_full().grow(1.0).scroll(ScrollSpec { stick_bottom: true }).child(stack), + ]) +} + +#[test] +fn virtual_rows_scroll_out_and_back_in_without_building() { + BUILDS.set(0); + let mut rt = Runtime::new(Rows { n: 500, tick: 0, memo: true }, rows, (400.0, 600.0), Env::default()); + rt.frame(0.0); + assert_eq!(BUILDS.get(), 500, "a miss builds in the view, mounted or not"); + assert!(rt.tree.nodes.len() < 200, "offscreen rows' children never reach the element tree: {}", rt.tree.nodes.len()); + for _ in 0..5 { + rt.state.tick += 1; + commit(&mut rt); + } + let scroll = |rt: &mut Runtime<Rows>, dy: f32| { + for _ in 0..40 { + rt.wheel(200.0, 300.0, dy); + rt.state.tick += 1; + commit(rt); + } + }; + scroll(&mut rt, 400.0); + assert!(rt.find("r499/title").is_none(), "scrolled up, the last row unmounts"); + scroll(&mut rt, -400.0); + assert!(rt.find("r499/title").is_some(), "scrolled back down, it mounts again"); + assert_eq!(BUILDS.get(), 500, "ticks and scrolling build no row"); +} + +#[test] +fn a_focused_field_in_an_offscreen_memo_row_keeps_focus_and_typing() { + use crate::{TextEdit, TextStyle, text_input}; + fn view(s: &Vec<TextEdit>, _: &mut Cx<Vec<TextEdit>>) -> El { + col().key("viewport").size(200.0, 200.0).scroll(ScrollSpec { stick_bottom: false }).clip_soft(0.0) + .child(col().key("rows").w_full().growth(GrowthSpec::default()).virtualize(40.0) + .children(s.iter().enumerate().map(|(i, edit)| { + memo(format!("row-{i}"), edit, || { + col().size(200.0, 40.0).child(text_input(edit, TextStyle::new(14.0, 400.0)).key("field") + .size(200.0, 40.0).on_edit(move |s: &mut Vec<TextEdit>| &mut s[i])) + }) + }))) + } + let mut state: Vec<_> = (0..100).map(|_| TextEdit::new("")).collect(); + state[0].focused = true; + let mut rt = Runtime::new(state, view, (200.0, 200.0), Env::new(true, 1.0)); + rt.frame(0.0); + rt.wheel(100.0, 100.0, -2000.0); + rt.frame(0.0); + assert!(rt.find("row-0/field").is_none(), "the focused row scrolled out"); + rt.key(crate::KeyEvent { key: crate::Key::Text("offscreen".into()), mods: Default::default() }); + rt.frame(0.0); + assert_eq!(rt.state[0].text, "offscreen"); +} + +#[test] +fn a_memoized_field_redraws_its_caret_and_composition() { + use crate::{Ime, Key, KeyEvent, TextEdit, TextStyle, text_input}; + fn view(s: &TextEdit, _: &mut Cx<TextEdit>) -> El { + col().size(200.0, 100.0).child(memo("field", s, || { + text_input(s, TextStyle::new(14.0, 400.0)).size(200.0, 40.0).on_edit(|s: &mut TextEdit| s) + })) + } + let mut edit = TextEdit::new("ab"); + edit.focused = true; + let mut rt = Runtime::new(edit, view, (200.0, 100.0), Env::new(true, 1.0)); + rt.frame(0.0); + rt.key(KeyEvent { key: Key::Left, mods: Default::default() }); + rt.frame(1.0 / 60.0); + rt.ime(Ime::Preedit("X".into(), None, Vec::new())); + rt.frame(1.0 / 60.0); + let shown = rt.elements().into_iter().find(|e| e.key.as_deref() == Some("field")).and_then(|e| e.text); + assert_eq!(shown.as_deref(), Some("aXb"), "the composition draws at the moved caret"); + let mut edit = TextEdit::new("ab"); + let caret = hash_of(&edit); + edit.anchor = 0; + assert_ne!(hash_of(&edit), caret, "a selection changes the version"); +} + +struct Probe { + width: f32, + ticks: u32, +} + +fn probe(s: &Probe, cx: &mut Cx<Probe>) -> El { + col().size(300.0, 300.0).children([ + el().key("probe").w(s.width).h(10.0), + memo("label", 0, || { + let width = cx.layout("probe").map_or(-1.0, |r| r[2]); + counted(text(format!("width {width}")).key("label")) + }), + text(format!("tick {}", s.ticks)).key("tick"), + ]) +} + +fn label<S>(rt: &Runtime<S>) -> Option<String> { + rt.elements().into_iter().find(|e| e.key.as_deref() == Some("label")).and_then(|e| e.text) +} + +#[test] +fn a_layout_read_inside_a_memo_rebuilds_it_when_the_rect_changes() { + BUILDS.set(0); + let mut rt = Runtime::new(Probe { width: 100.0, ticks: 0 }, probe, (300.0, 300.0), Env::default()); + rt.frame(0.0); + assert_eq!(label(&rt).as_deref(), Some("width 100"), "the first commit settles the read"); + let builds = BUILDS.get(); + for _ in 0..3 { + rt.state.ticks += 1; + commit(&mut rt); + } + assert_eq!(BUILDS.get(), builds, "an unmoved read reuses"); + rt.state.width = 150.0; + commit(&mut rt); + assert_eq!(label(&rt).as_deref(), Some("width 150"), "a moved read builds, though the version didn't change"); +} + +struct Moving { + top: f32, + width: f32, + ticks: u32, +} + +fn moving(s: &Moving, cx: &mut Cx<Moving>) -> El { + let shown = |key: &str, v: Option<[f32; 2]>| counted(text(format!("{v:?}")).key(key)); + col().size(300.0, 300.0).children([ + el().key("gap").w(10.0).h(s.top), + el().key("probe").w(s.width).h(10.0), + memo("cx", 0, || shown("cx", cx.layout_size("probe"))), + memo("free", 0, || shown("free", layout_size("probe"))), + memo("rect", 0, || shown("rect", cx.layout("probe").map(|r| [r[2], r[3]]))), + text(format!("tick {}", s.ticks)).key("tick"), + ]) +} + +#[test] +fn a_size_read_inside_a_memo_rebuilds_it_only_when_the_size_changes() { + BUILDS.set(0); + let mut rt = Runtime::new(Moving { top: 0.0, width: 100.0, ticks: 0 }, moving, (300.0, 300.0), Env::default()); + rt.frame(0.0); + let shown = |rt: &Runtime<Moving>, key| rt.elements().into_iter().find(|e| e.key.as_deref() == Some(key)).and_then(|e| e.text); + assert_eq!(shown(&rt, "cx").as_deref(), Some("Some([100.0, 10.0])"), "settled on the first commit"); + assert_eq!(shown(&rt, "free"), shown(&rt, "cx")); + let builds = BUILDS.get(); + rt.state.top = 40.0; + rt.state.ticks += 1; + commit(&mut rt); + assert_eq!(BUILDS.get(), builds + 1, "a move rebuilds only the whole-rect read"); + rt.state.width = 150.0; + commit(&mut rt); + assert_eq!(BUILDS.get(), builds + 4, "a resize rebuilds all three"); + assert_eq!(shown(&rt, "cx").as_deref(), Some("Some([150.0, 10.0])")); + assert_eq!(shown(&rt, "free"), shown(&rt, "cx")); +} + +fn scrolled(s: &Probe, cx: &mut Cx<Probe>) -> El { + let rows = (0..20).fold(col().w_full(), |c, i| c.child(el().key(format!("r{i}")).w_full().h(30.0))); + col().size(300.0, 300.0).children([ + col().key("scroll").w_full().h(200.0).scroll(ScrollSpec { stick_bottom: false }).child(rows), + memo("label", 0, || counted(text(format!("{:?}", cx.window_layout("r3"))).key("label"))), + text(format!("tick {}", s.ticks)).key("tick"), + ]) +} + +#[test] +fn a_whole_rect_read_inside_a_memo_holds_through_a_move_below_the_threshold() { + BUILDS.set(0); + let mut rt = Runtime::new(Probe { width: 0.0, ticks: 0 }, scrolled, (300.0, 300.0), Env::default()); + rt.frame(0.0); + let builds = BUILDS.get(); + rt.wheel(100.0, 100.0, -0.3); + rt.frame(1.0 / 60.0); + rt.state.ticks += 1; + commit(&mut rt); + assert_eq!(BUILDS.get(), builds, "0.3 pt is within the half point a whole-rect read ignores"); + rt.wheel(100.0, 100.0, -0.3); + rt.frame(1.0 / 60.0); + rt.state.ticks += 1; + commit(&mut rt); + assert_eq!(BUILDS.get(), builds + 1, "0.6 pt from what it read builds"); +} + +#[test] +fn a_caret_read_inside_a_reused_memo_keeps_following_the_caret() { + use crate::{Key, KeyEvent, TextEdit, TextStyle, text_input}; + fn view(s: &TextEdit, cx: &mut Cx<TextEdit>) -> El { + col().size(300.0, 300.0).children([ + text_input(s, TextStyle::new(14.0, 400.0)).key("field").size(300.0, 40.0).on_edit(|s: &mut TextEdit| s), + memo("label", 0, || { + let x = cx.caret("field").map_or(-1.0, |r| r[0]); + text(format!("caret {x}")).key("label") + }), + ]) + } + let mut edit = TextEdit::new(""); + edit.focused = true; + let mut rt = Runtime::new(edit, view, (300.0, 300.0), Env::default()); + rt.frame(0.0); + rt.frame(1.0 / 60.0); + let at_start = label(&rt); + assert_ne!(at_start.as_deref(), Some("caret -1"), "{at_start:?}"); + for _ in 0..3 { + rt.key(KeyEvent { key: Key::Text("w".into()), mods: Default::default() }); + rt.frame(1.0 / 60.0); + rt.frame(1.0 / 60.0); + } + assert_ne!(label(&rt), at_start, "typing moved the caret the label shows"); +} + +#[test] +fn a_memo_names_its_callers_line_for_key_warnings() { + let line = line!() + 1; + let built = memo("id", 0, el); + assert!(built.key_location().starts_with(&format!("{}:{line}:", file!())), "{}", built.key_location()); +} + +#[test] +fn cached_unkeyed_siblings_keep_index_paths_and_leave_no_key_warnings() { + fn view(tick: &u32, _: &mut Cx<u32>) -> El { + let _ = *tick; + col().w_full().children([ + cached(digest("same"), || counted(text("one"))), + cached(digest("same"), || counted(text("one"))), + cached(digest("other"), || counted(text("two"))).key("named"), + ]) + } + BUILDS.set(0); + let mut rt = Runtime::new(0u32, view, (200.0, 200.0), Env::new(true, 1.0)); + rt.commit.enable_key_warnings(); + rt.frame(0.0); + assert_eq!(BUILDS.get(), 3); + assert!(rt.commit.key_warnings().unwrap().is_empty(), "{:?}", rt.commit.key_warnings()); + let paths: Vec<_> = rt.elements().into_iter().map(|e| e.path).collect(); + assert_eq!(paths, vec!["#0", "#0/#0", "#0/#1", "#0/named"]); + + rt.update(|t, _| *t += 1); + rt.frame(1.0 / 120.0); + assert_eq!(BUILDS.get(), 3, "reused all three cached subtrees"); + assert!(rt.commit.key_warnings().unwrap().is_empty()); +} + +/// `cargo test -p rune --profile perf --lib memo_build_time -- --ignored --nocapture` +#[test] +#[ignore] +fn memo_build_time() { + for memo in [false, true] { + for n in [100, 500, 2000] { + let mut rt = Runtime::new(Rows { n, tick: 0, memo }, rows, (400.0, 600.0), Env::new(true, 2.0)); + rt.frame(0.0); + for _ in 0..30 { + rt.state.tick += 1; + commit(&mut rt); + } + let frames = 300; + let start = crate::time::now(); + for _ in 0..frames { + rt.state.tick += 1; + commit(&mut rt); + } + let per = start.elapsed().as_secs_f64() * 1e6 / f64::from(frames); + println!("memo {memo:5} rows {n:5}: {per:8.1} µs per frame"); + } + } +} diff --git a/app/vendor/rune/crates/rune/src/motion_gate/check.rs b/app/vendor/rune/crates/rune/src/motion_gate/check.rs new file mode 100644 index 0000000..246df86 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/motion_gate/check.rs @@ -0,0 +1,794 @@ +//! Frame-by-frame motion checks over a run's element tree. +//! +//! [`Recording::sample`] takes every element's presented rect, visible part and opacity each +//! frame of a run on the virtual clock; [`check`] reads them back and lists what a person would +//! see go wrong: things that appear or vanish with no transition, jump in one frame, lurch, +//! turn back, overshoot, flicker or never settle. Elements are tracked by their tree path, so a +//! keyed row keeps its identity however the rows around it change. +//! +//! Nothing here knows about the app: thresholds live in [`RULES`], one row per finding kind. +//! [`super::Run`] drives a runtime and records it; [`super::gate`] runs and reports the cells. + +use std::collections::{HashMap, HashSet}; +use std::fmt; +use std::sync::Arc; + +use crate::ElementInfo; + +mod commits; +mod evidence; +mod kicks; +mod loops; +pub mod paint; +mod painted; +pub mod raster; +mod regions; +mod series; + +pub use evidence::{dump, sheet}; +use paint::Paint; + +/// One finding kind, its threshold and what it means. The checker reads its numbers from here. +pub struct Rule { + pub kind: &'static str, + pub threshold: f32, + pub means: &'static str, +} + +pub const RULES: &[Rule] = &[ + Rule { kind: "pop-in", threshold: 0.5, means: "mounts at or above this opacity, at full size, with no fade, growth or scale (and no ancestor transitioning)" }, + Rule { kind: "pop-out", threshold: 0.5, means: "unmounts at or above this opacity: it vanished instead of leaving" }, + Rule { kind: "cut-exit", threshold: 0.05, means: "unmounts above this opacity, below pop-out's: a fade cut short" }, + Rule { kind: "jump", threshold: 2.0, means: "an edge moves at least this many pt in one frame between still frames, where it shows (its visible part, or what it holds that shows, moves with it, or it brings what it holds into view with no input)" }, + Rule { kind: "offset-jump", threshold: 2.0, means: "a jump of a scroll's content: every row in it moved by the same delta in one frame" }, + Rule { kind: "appear-then-jump", threshold: 2.0, means: "mounts, then moves at least this many pt on its next frame" }, + Rule { kind: "jerk", threshold: 10.0, means: "a moving edge's per-frame step changes by more than this many pt from one frame to the next" }, + Rule { kind: "stop-start", threshold: 3.0, means: "a travelling edge rests (under 0.5 s) and sets off again the same way this many times in 2 s, with no input but data arriving: it moves in kicks, not one glide" }, + Rule { kind: "reversal", threshold: 1.0, means: "a travelling edge heads this many pt the wrong way and turns back, with no input mid-flight (one monotonic path)" }, + Rule { kind: "overshoot", threshold: 1.0, means: "passes where it comes to rest by this many pt (bounce 0)" }, + Rule { kind: "jiggle", threshold: 1.0, means: "an edge reverses twice or more within one motion, over at least this many pt" }, + Rule { kind: "text-swap", threshold: 0.5, means: "a text element's words change in one frame at or above this opacity, with no roll or crossfade (streaming text excepted)" }, + Rule { kind: "fade-snap", threshold: 0.5, means: "a mounted element's opacity steps by at least this in one frame: it blinks on or off instead of fading" }, + Rule { kind: "flicker", threshold: 0.3, means: "opacity dips by at least this much and comes back within 0.3 s, or an element vanishes and comes back at its place" }, + Rule { kind: "faint", threshold: 0.25, means: "geometry checks skip frames fainter than this opacity: a row fading out can't be seen to lurch" }, + Rule { kind: "load-motion", threshold: 1.0, means: "a row that loaded with the view moves or fades by more than this after its first frame (no animation on load)" }, + Rule { kind: "never-settles", threshold: 0.05, means: "still changing by more than this in the last half second of the run, long after the last input (loops excepted)" }, + Rule { kind: "loop-jump", threshold: 0.03, means: "a loop's phase steps this many periods off its usual step in one frame: it restarted or skipped (a remount, or a new loop where one was running)" }, + Rule { kind: "wakes-after-end", threshold: 1.0, means: "still asking for frames this many seconds after the cell's motion ended (a run that finished)" }, + Rule { kind: "lands-unseen", threshold: 40.0, means: "travels at least this many pt in plain view, then its clip cuts it from view in one frame where it rests: it flew somewhere you can't see" }, + Rule { kind: "remount", threshold: 2.0, means: "words start leaving while the same words mount elsewhere within this many frames: one thing fades out at its old place as its copy fades in (its row lost its key)" }, + Rule { kind: "unpinned", threshold: 2.0, means: "a scroll pinned to its end has its content's bottom this many pt below the viewport with no input since: it stopped following" }, + Rule { kind: "scroll-commit", threshold: 0.25, means: "the app ran its view (its `poll`, a handler or a layout read) on 6 or more of a scroll's frames and at least this share of them: a scroll needs no commit, so each one is a frame's whole view rebuilt mid-gesture" }, + Rule { kind: "snap", threshold: 1.0, means: "a painted property steps by at least this in one frame between frames that hold still, with no input, `Tx::instant` commit or mark asking for it: a colour by OKLab ΔE 0.08 (weighted by the area that shows and its opacity), a corner by 3 pt, a blur by 2 pt, a border by 1 pt, a new image, or two surfaces trading places (z-order). `(pixels)`: a region of the composited window, where no element changed" }, + Rule { kind: "flash", threshold: 0.5, means: "a painted property (or a region of the window) steps out by at least this and comes at least halfway back within 0.4 s, or drifts out and snaps back: a surface that drops out for a frame, or blinks before what replaces it fades in" }, + Rule { kind: "changes-twice", threshold: 0.25, means: "a painted property (or region) changes, rests from 2 frames to this many seconds, then carries on the same way with no input between: one change landed as two" }, + Rule { kind: "twice", threshold: 0.0, means: "two siblings share one key (Rune's `#dup`), so one thing shows twice, as an optimistic copy beside the server's" }, +]; + +/// Isolate controls draw no words: appending inside an isolate still grows the same text. +fn starts_with_words(text: &str, prefix: &str) -> bool { + let visible = |c: &char| !matches!(c, '\u{2066}'..='\u{2069}'); + let mut text = text.chars().filter(visible); + prefix.chars().filter(visible).all(|c| text.next() == Some(c)) +} + +/// Whether `old` → `new` is a number changing in otherwise the same words. +fn ticks(old: &str, new: &str) -> bool { + let shape = |t: &str| { + let mut out = String::new(); + for ch in t.chars() { + if !ch.is_ascii_digit() { + out.push(ch); + } else if !out.ends_with('#') { + out.push('#'); + } + } + out + }; + shape(old) == shape(new) +} + +pub fn rule(kind: &str) -> f32 { + RULES.iter().find(|r| r.kind == kind).map_or(f32::INFINITY, |r| r.threshold) +} + +const EXITING: u8 = 1; +const SCROLLING: u8 = 2; +const GROWING: u8 = 4; +const LIVE: u8 = 8; +const VIRTUAL: u8 = 16; +const TEXT: u8 = 32; +/// It or something inside it paints (a fill, words, or a leaf such as an icon) at an opacity +/// that shows. Without it an opacity change draws nothing. +const INK: u8 = 128; + +#[derive(Clone, Copy, Debug)] +pub struct Snap { + pub rect: [f32; 4], + pub vis: [f32; 4], + pub op: f32, + pub scale: f32, + pub flags: u8, + /// A loop's phase (0 to 1); NaN without one. + pub phase: f32, + /// How far scrolling carries it, x and y ([`ElementInfo::scrolled`]). + pub scrolled: [f32; 2], +} + +pub struct Track { + pub path: String, + pub parent: Option<usize>, + /// Frame index → presented state, for the frames it was mounted (sorted). + pub frames: Vec<(usize, Snap)>, + pub text: Option<String>, + /// Its words each time they changed, from the frame they showed. + pub words: Vec<(usize, String)>, + /// A field's own words each time they changed (typed, pasted, set or cleared), which + /// `words` leaves out. + pub edits: Vec<(usize, String)>, + /// What it painted on each of `frames` (empty when the recording has no paint). + pub paint: Vec<Option<Paint>>, +} + +impl Track { + fn at(&self, k: usize) -> Option<&Snap> { + self.frames.binary_search_by_key(&k, |f| f.0).ok().map(|i| &self.frames[i].1) + } + + /// What it painted on frame `k`. + pub fn paint_at(&self, k: usize) -> Option<&Paint> { + let i = self.frames.binary_search_by_key(&k, |f| f.0).ok()?; + self.paint.get(i)?.as_ref() + } +} + +#[derive(Default)] +pub struct Recording { + pub size: (f32, f32), + pub hz: f64, + pub tracks: Vec<Track>, + index: HashMap<String, usize>, + /// Frames an input or a scripted event landed on, with what it was. One named `event…` is + /// data arriving, not a hand on the app: it doesn't let a pinned scroll go (see `unpinned`). + pub inputs: Vec<(usize, String)>, + /// Frames sampled so far. + pub frames: usize, + /// Frames before this are the settled start: what's mounted there loaded with the view. + pub start: usize, + /// Frames at which the view loaded content that must arrive still (see `load-motion`). + pub loads: Vec<usize>, + /// Per frame: whether the runtime wanted another. + pub awake: Vec<bool>, + /// The frame the cell's motion ended on (see `wakes-after-end`). + pub quiet_from: Option<usize>, + /// The app rolls its live numbers, so a count or a clock ticking in place ("9s" → "10s") is + /// a `text-swap` too. By default a tick passes. + pub counts_roll: bool, + /// Per frame [`super::Run`] stepped: whether a viewport scrolled, and the app's reasons + /// for the view to run again (`CommitWhy` bits: its `poll`, a handler, a layout read). + scrolled: Vec<(bool, u16)>, + /// Per frame: a commit landed at once (`Tx::instant`), so what it changed steps by design. + pub instant: Vec<bool>, + /// Per frame: the composited window in cells ([`raster`]), shared while it's unchanged. + pub grids: Vec<Option<Arc<raster::Grid>>>, + /// Per frame: the box (x y w h, points) of the tooltip Rune drew for `El::help`, which + /// shows and hides at once after a rest, as AppKit's does. + pub tips: Vec<Option<[f32; 4]>>, +} + +impl Recording { + pub fn new(size: (f32, f32), hz: f64) -> Self { + Recording { size, hz, ..Default::default() } + } + + /// The frame just run: `scrolling` while a viewport moved, `why` its commits' reasons. + pub(crate) fn commits(&mut self, scrolling: bool, why: u16) { + use crate::runtime::CommitWhy as W; + self.scrolled.push((scrolling, why & (W::POLL | W::INPUT | W::LAYOUT | W::READ))); + self.instant.push(why & W::INSTANT != 0); + } + + /// The frame just sampled's composited window. + pub fn grid(&mut self, grid: Option<Arc<raster::Grid>>) { + self.grids.resize(self.frames.saturating_sub(1), None); + self.grids.push(grid); + } + + fn track(&mut self, path: &str, parent: Option<usize>) -> usize { + if let Some(&i) = self.index.get(path) { + return i; + } + let i = self.tracks.len(); + self.tracks.push(Track { path: path.to_owned(), parent, frames: Vec::new(), text: None, words: Vec::new(), edits: Vec::new(), paint: Vec::new() }); + self.index.insert(path.to_owned(), i); + i + } + + pub fn input(&mut self, what: impl Into<String>) { + self.inputs.push((self.frames, what.into())); + } + + /// Takes one frame of the element tree. + pub fn sample(&mut self, els: &[ElementInfo]) { + self.sample_with(els, None); + } + + /// Takes one frame of the element tree and what each element painted, by path and whether + /// it's leaving (`Runtime::paints`). + pub(crate) fn sample_with(&mut self, els: &[ElementInfo], paints: Option<&crate::runtime::HashMap<(String, bool), Paint>>) { + let k = self.frames; + self.frames += 1; + // An element exiting beside a live one at the same path (a key re-added mid-exit) is + // its own track. + let live: HashSet<&str> = els.iter().filter(|e| !e.exiting).map(|e| e.path.as_str()).collect(); + let mut ids = vec![usize::MAX; els.len()]; + // Children follow their parent, so one pass from the end carries ink up the tree. + let mut ink = vec![false; els.len()]; + let mut parent_of = vec![false; els.len()]; + for e in els { + if let Some(p) = e.parent.filter(|&p| p < els.len()) { parent_of[p] = true; } + } + for (i, e) in els.iter().enumerate().rev() { + let paints = e.fill.a > 0.01 || e.text.as_deref().is_some_and(|t| !t.is_empty()) || !parent_of[i]; + ink[i] |= paints && e.opacity > 0.02; + if ink[i] && let Some(p) = e.parent.filter(|&p| p < els.len()) { ink[p] = true; } + } + for (i, e) in els.iter().enumerate() { + let path = if e.exiting && live.contains(e.path.as_str()) { format!("{} (leaving)", e.path) } else { e.path.clone() }; + let parent = e.parent.and_then(|p| ids.get(p).copied()).filter(|&p| p != usize::MAX); + let t = self.track(&path, parent); + ids[i] = t; + let mut flags = 0; + if e.exiting { flags |= EXITING } + if e.scrolling { flags |= SCROLLING } + if e.in_growing_row || e.revealing { flags |= GROWING } + if e.live_intent != 0 { flags |= LIVE } + if e.virtual_extent { flags |= VIRTUAL } + if e.role == "text" { flags |= TEXT } + if ink[i] { flags |= INK } + let track = &mut self.tracks[t]; + if track.frames.last().is_some_and(|f| f.0 == k) { + continue; // a duplicate path this frame: keep the first + } + track.parent = parent.or(track.parent); + if track.text.is_none() { track.text = e.text.clone().filter(|t| !t.is_empty()); } + // A field's words change as they're typed (a link's words are its own). + if let Some(words) = e.text.as_deref().filter(|t| !t.is_empty() && (!e.focusable || e.role == "link")) + && track.words.last().is_none_or(|w| w.1 != words) + { + track.words.push((k, words.to_owned())); + } + if e.focusable && e.role != "link" { + let words = e.text.as_deref().unwrap_or(""); + if track.edits.last().map_or(!words.is_empty(), |w| w.1 != words) { track.edits.push((k, words.to_owned())); } + } + track.frames.push((k, Snap { rect: e.rect, vis: e.visible, op: e.opacity, scale: e.scale, flags, phase: e.loop_phase.map_or(f32::NAN, |p| p as f32), scrolled: e.scrolled })); + if let Some(paints) = paints { + track.paint.resize(track.frames.len() - 1, None); + track.paint.push(paints.get(&(e.path.clone(), e.exiting)).cloned()); + } + } + } +} + +#[derive(Clone, Debug)] +pub struct Finding { + pub kind: &'static str, + pub element: String, + pub frame: usize, + pub detail: String, +} + +impl fmt::Display for Finding { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "{:<16} {:<44} @{:<4} {}", self.kind, self.element, self.frame, self.detail) + } +} + +/// A readable name: its keyed segments from the row down (`row-3/bubble`). +pub fn short(path: &str) -> String { + let segs: Vec<&str> = path.split('/').collect(); + let keyed: Vec<usize> = (0..segs.len()).filter(|&i| !segs[i].starts_with('#')).collect(); + let from = keyed.len().saturating_sub(2); + let start = keyed.get(from).copied().unwrap_or(0); + segs[start..].join("/") +} + +fn area(r: &[f32; 4]) -> f32 { + r[2].max(0.0) * r[3].max(0.0) +} + +fn on_window(r: &[f32; 4], (w, h): (f32, f32)) -> [f32; 4] { + let (x0, y0) = (r[0].max(0.0), r[1].max(0.0)); + let (x1, y1) = ((r[0] + r[2]).min(w), (r[1] + r[3]).min(h)); + [x0, y0, (x1 - x0).max(0.0), (y1 - y0).max(0.0)] +} + +fn seen(s: &Snap, size: (f32, f32)) -> bool { + s.op > 0.02 && area(&on_window(&s.vis, size)) >= 1.0 +} + +fn edge(s: &Snap, axis: usize) -> f32 { + s.rect[axis] +} + +/// An edge of what shows: the visible part, in the window, where one wholly past the window's +/// edge would come in. An edge its clips hide on both frames moves nobody can see. +fn shown_edge(s: &Snap, axis: usize, size: (f32, f32)) -> f32 { + let r = on_window(&s.vis, size); + [r[0].min(size.0), r[1].min(size.1), r[2], r[3]][axis] +} + +/// An edge against the content it scrolls with: a node gliding inside a list that follows its +/// end makes one motion there, however the scroll adds to it on screen. +fn own_edge(s: &Snap, axis: usize) -> f32 { + s.rect[axis] + s.scrolled.get(axis).copied().unwrap_or(0.0) +} + +const AXES: [&str; 4] = ["x", "y", "w", "h"]; + +pub fn check(rec: &Recording) -> Vec<Finding> { + let size = rec.size; + let n = rec.frames; + let tr = &rec.tracks; + let mut out = Vec::new(); + let input_frames: Vec<usize> = rec.inputs.iter().map(|i| i.0).collect(); + let input_between = |a: usize, b: usize| input_frames.iter().any(|&k| k >= a && k <= b); + let born = |t: &Track| t.frames.first().map(|f| f.0); + // A label over its own glyphs (a rolling text) changes its words as they move. + let parents: HashSet<usize> = tr.iter().filter_map(|t| t.parent).collect(); + let died = |t: &Track| t.frames.last().map(|f| f.0 + 1).filter(|&k| k < n); + let gaps = |t: &Track| t.frames.windows(2).filter(|w| w[1].0 != w[0].0 + 1).map(|w| (w[0].0 + 1, w[1].0)).collect::<Vec<_>>(); + + // An ancestor changing opacity or scale over frames a..=b carries whatever mounts or + // unmounts inside it (one that grows but doesn't clip it doesn't: see `grows`). + let transitioning = |t: usize, a: usize, b: usize| -> bool { + let mut p = tr[t].parent; + while let Some(i) = p { + let s: Vec<&Snap> = (a.saturating_sub(1)..=b).filter_map(|k| tr[i].at(k)).collect(); + if s.windows(2).any(|w| (w[0].op - w[1].op).abs() > 0.005 || (w[0].scale - w[1].scale).abs() > 0.001) + || s.iter().any(|s| s.flags & (GROWING | EXITING) != 0) + { + return true; + } + p = tr[i].parent; + } + false + }; + + // Loops (a spinner's dots, a busy ring, a blinking caret) change on most frames they're + // mounted, as one element or as siblings taking turns; their wraps are their design. + let loops = loops::loops(rec); + + // Pops: births and deaths after the settled start, reported at the outermost element. + let births: HashMap<usize, Vec<usize>> = tr.iter().enumerate().fold(HashMap::new(), |mut m, (i, t)| { + let mut ks: Vec<usize> = born(t).into_iter().collect(); + ks.extend(gaps(t).iter().map(|g| g.1)); + for k in ks.into_iter().filter(|&k| k > rec.start) { m.entry(k).or_default().push(i); } + m + }); + let deaths: HashMap<usize, Vec<usize>> = tr.iter().enumerate().fold(HashMap::new(), |mut m, (i, t)| { + let mut ks: Vec<usize> = died(t).into_iter().collect(); + ks.extend(gaps(t).iter().map(|g| g.0)); + for k in ks.into_iter().filter(|&k| k > rec.start) { m.entry(k).or_default().push(i); } + m + }); + let outermost = |ids: &[usize]| -> Vec<usize> { + let set: HashSet<usize> = ids.iter().copied().collect(); + ids.iter().copied().filter(|&i| { + let mut p = tr[i].parent; + while let Some(j) = p { + if set.contains(&j) { return false; } + p = tr[j].parent; + } + true + }).collect() + }; + let mut left: HashMap<usize, Vec<(usize, Snap)>> = HashMap::new(); // frame → (track, last state) of pop-outs + let mut ks: Vec<&usize> = deaths.keys().collect(); + ks.sort(); + for &k in ks { + for i in outermost(&deaths[&k]) { + let Some(last) = tr[i].at(k - 1).copied() else { continue }; + if !seen(&last, size) || area(&last.vis) < 16.0 || loops.contains(&i) || last.flags & VIRTUAL != 0 { + continue; + } + // Back at the same place a few frames later: a blink, not a removal. + if let Some(&(_, back)) = tr[i].frames.iter().find(|f| f.0 > k && f.0 <= k + 12) { + if (back.rect[1] - last.rect[1]).abs() < 4.0 && seen(&back, size) { + out.push(Finding { kind: "flicker", element: short(&tr[i].path), frame: k, + detail: format!("vanished at opacity {:.2} and came back {} frames later at the same place", last.op, tr[i].frames.iter().find(|f| f.0 > k).unwrap().0 - k) }); + continue; + } + } + if last.op >= rule("pop-out") { + left.entry(k).or_default().push((i, last)); + out.push(Finding { kind: "pop-out", element: short(&tr[i].path), frame: k, + detail: format!("unmounted at opacity {:.2}, {:.0}×{:.0} at ({:.0},{:.0}){}", last.op, last.rect[2], last.rect[3], last.rect[0], last.rect[1], + if transitioning(i, k - 1, k - 1) { " inside a moving container" } else { "" }) }); + } else if last.op > rule("cut-exit") { + out.push(Finding { kind: "cut-exit", element: short(&tr[i].path), frame: k, + detail: format!("unmounted at opacity {:.2} before its fade reached 0", last.op) }); + } + } + } + let mut ks: Vec<&usize> = births.keys().collect(); + ks.sort(); + for &k in ks { + for i in outermost(&births[&k]) { + let t = &tr[i]; + let Some(first) = t.at(k).copied() else { continue }; + if first.op < rule("pop-in") || !seen(&first, size) || area(&on_window(&first.vis, size)) < 16.0 || first.flags & (GROWING | VIRTUAL) != 0 || loops.contains(&i) { + continue; + } + let next: Vec<Snap> = (k + 1..=k + 2).filter_map(|j| t.at(j).copied()).collect(); + let grows = next.iter().any(|s| (s.op - first.op).abs() > 0.01 || (s.scale - first.scale).abs() > 0.002 + || (s.rect[2] - first.rect[2]).abs() > 0.5 || (s.rect[3] - first.rect[3]).abs() > 0.5 + || (s.vis[2] - first.vis[2]).abs() > 0.5 || (s.vis[3] - first.vis[3]).abs() > 0.5) + // A row mounting under a point tall that grows open, however gently it starts. + || first.rect[3] < 1.0 && (k + 1..=k + (0.25 * rec.hz) as usize).filter_map(|j| t.at(j)).any(|s| s.rect[3] >= 1.0); + if grows || transitioning(i, k, k + 2) { + continue; + } + let moved = next.first().map(|s| (s.rect[0] - first.rect[0]).abs().max((s.rect[1] - first.rect[1]).abs())).unwrap_or(0.0); + let handoff = left.get(&k).and_then(|l| l.iter().find(|(j, _)| tr[*j].text.is_some() && tr[*j].text == t.text || last_seg(&tr[*j].path) == last_seg(&t.path))); + let mut detail = format!("mounted at opacity {:.2}, {:.0}×{:.0} at ({:.0},{:.0}) with no transition", first.op, first.rect[2], first.rect[3], first.rect[0], first.rect[1]); + if let Some((j, s)) = handoff { + detail += &format!("; replaces {} which vanished from ({:.0},{:.0}) this frame (identity lost)", short(&tr[*j].path), s.rect[0], s.rect[1]); + } + if moved >= rule("appear-then-jump") { + out.push(Finding { kind: "appear-then-jump", element: short(&t.path), frame: k, detail: format!("{detail}, then moved {moved:.0} pt") }); + } else { + out.push(Finding { kind: "pop-in", element: short(&t.path), frame: k, detail }); + } + } + } + + // Geometry, per track and axis. + let riding = |i: usize, k: usize, axis: usize, d: f32| -> bool { + if axis >= 2 { return false; } + let Some(p) = tr[i].parent else { return false }; + match (tr[p].at(k), tr[p].at(k - 1)) { + (Some(a), Some(b)) => (edge(a, axis) - edge(b, axis) - d).abs() < 0.25, + _ => false, + } + }; + // An instant toggle (a disclosure opening on a tap) reflows what's beside it in that frame. + // An element pushed by exactly the height another changed by, the edge between them moving + // with it, on an input's frame, is that toggle's; it's reported where the height changed. + let inside = |a: &str, b: &str| a.len() > b.len() && a.starts_with(b) && a.as_bytes()[b.len()] == b'/'; + let pushed = |i: usize, k: usize, axis: usize, d: f32| -> bool { + if axis != 1 || !input_between(k - 1, k) { return false; } + let Some(a) = tr[i].at(k - 1) else { return false }; + tr.iter().enumerate().any(|(j, o)| { + if j == i || inside(&tr[i].path, &o.path) || inside(&o.path, &tr[i].path) { return false; } + let (Some(oa), Some(ob)) = (o.at(k - 1), o.at(k)) else { return false }; + if ((ob.rect[3] - oa.rect[3]).abs() - d.abs()).abs() > 0.25 { return false; } + let (top, bottom) = (ob.rect[1] - oa.rect[1], ob.rect[1] + ob.rect[3] - oa.rect[1] - oa.rect[3]); + let above = oa.rect[1] + oa.rect[3] <= a.rect[1] + 0.5 && (bottom - d).abs() < 0.25; + let below = oa.rect[1] >= a.rect[1] + a.rect[3] - 0.5 && (top - d).abs() < 0.25; + above || below + }) + }; + // How many of what `i` holds show on frames k - 1 and k and move there by `d` with it, as a + // scroll's rows do when its content jumps though the content's visible part stays put. + // With `entering`, also those it brings into view from just off it with no input on the + // way: content that teleports pops in a row that didn't show the frame before. + let carried = |i: usize, k: usize, axis: usize, d: f32, entering: bool| -> usize { + if axis >= 2 { return 0; } + let entering = entering && !input_between(k - 1, k); + tr.iter().filter(|c| inside(&c.path, &tr[i].path)).filter(|c| { + let (Some(a), Some(b)) = (c.at(k - 1), c.at(k)) else { return false }; + if !seen(b, size) || (edge(b, axis) - edge(a, axis) - d).abs() >= 0.25 { return false; } + if seen(a, size) { return (shown_edge(b, axis, size) - shown_edge(a, axis, size) - d).abs() < 0.25 } + entering && b.op >= rule("faint") && b.flags & INK != 0 && b.flags & (GROWING | EXITING) == 0 + }).count() + }; + let mut geo: Vec<(usize, Finding)> = painted::painted(rec, &loops); + for (i, t) in tr.iter().enumerate() { + if loops.contains(&i) || t.frames.len() < 3 { continue; } + for axis in 0..4 { + // Deltas between consecutive frames, None across a gap. + let fs = &t.frames; + let d: Vec<Option<f32>> = (1..fs.len()).map(|j| (fs[j].0 == fs[j - 1].0 + 1).then(|| edge(&fs[j].1, axis) - edge(&fs[j - 1].1, axis))).collect(); + // A jump or jerk is judged on what shows: the visible part moves with it, or what it + // holds that shows does. A fold dropping its rows above the window steps its top and + // height with the scroll offset, and nothing that shows moves. + let vd = |j: usize| if fs[j].0 == fs[j - 1].0 + 1 { shown_edge(&fs[j].1, axis, size) - shown_edge(&fs[j - 1].1, axis, size) } else { 0.0 }; + let clipped = |j: usize| area(&on_window(&fs[j].1.vis, size)) + 1.0 < area(&fs[j].1.rect); + let quiet = |j: usize| fs[j].1.flags & (LIVE | VIRTUAL) != 0 || !seen(&fs[j].1, size) || fs[j].1.op < rule("faint"); + // The box of words still arriving (a streaming link's) takes each new word at once. + let grew = |k: usize| t.words.iter().position(|w| w.0 == k).is_some_and(|p| p > 0 && starts_with_words(&t.words[p].1, &t.words[p - 1].1)); + for j in 1..fs.len() { + let Some(step) = d[j - 1] else { continue }; + let k = fs[j].0; + if k <= rec.start || quiet(j) || quiet(j - 1) || fs[j].1.flags & GROWING != 0 && axis == 3 { continue; } + // A scroll under a hand, or one gliding over frames, moves as it should. One that + // lands in a single frame with nothing asking for it is a teleport. + let scrolling = (fs[j].1.flags | fs[j - 1].1.flags) & SCROLLING != 0; + let before = if j >= 2 { d[j - 2].unwrap_or(0.0) } else { 0.0 }; + let after = d.get(j).copied().flatten().unwrap_or(0.0); + let name = short(&t.path); + let riders = |entering| if clipped(j) || clipped(j - 1) { carried(i, k, axis, step, entering) } else { 0 }; + if step.abs() >= rule("jump") && before.abs() < 0.5 && after.abs() < 0.5 { + // An input's scroll cut moves a row with the content it scrolls in. A virtual + // list's stack can move by less, as rows above it unmount into its space. + let cut = axis < 2 && input_between(k - 1, k) && (own_edge(&fs[j].1, axis) - own_edge(&fs[j - 1].1, axis)).abs() < 0.25; + if scrolling && input_between(k - 1, k) || cut || riding(i, k, axis, step) || pushed(i, k, axis, step) || grew(k) { continue; } + let riders = riders(true); + if vd(j).abs() < rule("jump") && riders == 0 { continue; } + let appeared = born(t) == Some(fs[j - 1].0) && fs[j - 1].0 > rec.start; + let scroll_content = axis == 1 && fs[j].1.rect[3] > fs[j].1.vis[3] + 1.0 && riders >= 3; + let kind = if appeared { "appear-then-jump" } else if scroll_content { "offset-jump" } else { "jump" }; + geo.push((i, Finding { kind, element: name, frame: k, + detail: format!("{} {:.1} → {:.1} ({:+.1} pt) in one frame{}", AXES[axis], edge(&fs[j - 1].1, axis), edge(&fs[j].1, axis), step, + if scroll_content { format!(", carrying {riders} elements") } else { String::new() }) })); + } else if !scrolling && (step - before).abs() > rule("jerk") && before.abs() >= 0.5 && step.abs() >= 0.5 { + if riding(i, k, axis, step) { continue; } + if j >= 2 && (vd(j) - vd(j - 1)).abs() <= rule("jerk") && riders(false) == 0 { continue; } + geo.push((i, Finding { kind: "jerk", element: name, frame: k, + detail: format!("{} step {:+.1} → {:+.1} pt/frame ({:.0} → {:.0} pt/s)", AXES[axis], before, step, before as f64 * rec.hz, step as f64 * rec.hz) })); + } + } + // Motion segments: frames that move this edge against its scroll, through the odd + // still frame at a turn (a spring's peak), until it rests three frames. + let d: Vec<Option<f32>> = (1..fs.len()).map(|j| (fs[j].0 == fs[j - 1].0 + 1).then(|| own_edge(&fs[j].1, axis) - own_edge(&fs[j - 1].1, axis))).collect(); + let moving = |j: usize| d[j - 1].is_some_and(|x| x.abs() > 0.01); + let mut j = 1; + while j < fs.len() { + if !moving(j) { j += 1; continue; } + let a = j; + let mut b = j; + while j < fs.len() && d[j - 1].is_some() && j - b <= 3 { + if moving(j) { b = j; } + j += 1; + } + j = b + 1; // fs[a-1..=b] is the segment + if b - a + 1 < 3 { continue; } + let seg = &fs[a - 1..=b]; + let (k0, k1) = (seg[0].0, seg[seg.len() - 1].0); + if k1 <= rec.start || seg.iter().all(|f| !seen(&f.1, size) || f.1.op < rule("faint")) || seg.iter().any(|f| f.1.flags & (LIVE | VIRTUAL) != 0) { continue; } + if input_between(k0 + 1, k1) { continue; } // retargeted mid-flight + let vals: Vec<f32> = seg.iter().map(|f| own_edge(&f.1, axis)).collect(); + let (start, rest) = (vals[0], vals[vals.len() - 1]); + let travel = rest - start; + let mut signs = Vec::new(); + let mut last = start; + for &v in &vals[1..] { + if (v - last).abs() > 0.05 { + let s = (v - last).signum(); + if signs.last() != Some(&s) { signs.push(s); } + last = v; + } + } + let reversals = signs.len().saturating_sub(1); + if reversals == 0 { continue; } + let dir = if travel.abs() > 0.5 { travel.signum() } else { signs[0] }; + let past = vals.iter().map(|v| (v - rest) * dir).fold(0.0f32, f32::max); + let back = vals.iter().map(|v| (start - v) * dir).fold(0.0f32, f32::max); + let amp = vals.iter().cloned().fold(f32::MIN, f32::max) - vals.iter().cloned().fold(f32::MAX, f32::min); + let name = short(&t.path); + let (kind, detail) = if past >= rule("overshoot") && travel.abs() > 0.5 { + ("overshoot", format!("{} {start:.1} → {rest:.1} passes its rest by {past:.1} pt ({:.0}%)", AXES[axis], 100.0 * past / travel.abs())) + } else if reversals >= 2 && amp >= rule("jiggle") { + ("jiggle", format!("{} reverses {reversals}× over {amp:.1} pt ({start:.1} → {rest:.1})", AXES[axis])) + } else if back >= rule("reversal") { + ("reversal", format!("{} {start:.1} → {rest:.1} heads {back:.1} pt the wrong way first", AXES[axis])) + } else if travel.abs() <= 0.5 && amp >= rule("reversal") { + ("reversal", format!("{} goes {amp:.1} pt out from {start:.1} and back", AXES[axis])) + } else { continue }; + geo.push((i, Finding { kind, element: name, frame: k0 + 1, detail: format!("{detail} over frames {}–{k1}", k0 + 1) })); + } + } + // Opacity dips that come back. + let fs = &t.frames; + let mut spans = Vec::new(); + let mut j = 0; + while j < fs.len() { + let s = fs[j].1; + if fs[j].0 <= rec.start || s.op < 0.6 || s.flags & EXITING != 0 || s.flags & INK == 0 || !seen(&s, size) { j += 1; continue; } + let horizon = fs[j].0 + (0.3 * rec.hz) as usize; + let mut low = s.op; + let mut low_at = j; + let mut back = None; + let mut m = j + 1; + while m < fs.len() && fs[m].0 <= horizon && fs[m].0 == fs[m - 1].0 + 1 { + if fs[m].1.op < low { low = fs[m].1.op; low_at = m; } + if low <= s.op - rule("flicker") && fs[m].1.op >= s.op - 0.1 { back = Some(m); break; } + m += 1; + } + // One input taking it away and another bringing it back (a toggle pressed twice + // quickly) is them answered, not a flicker. + let answered = |m: usize| rec.inputs.iter().filter(|x| x.0 > fs[j].0 && x.0 <= fs[m].0).count() >= 2; + if let Some(m) = back.filter(|&m| answered(m)) { + j = m + 1; + } else if let Some(m) = back { + geo.push((i, Finding { kind: "flicker", element: short(&t.path), frame: fs[low_at].0, + detail: format!("opacity {:.2} → {:.2} → {:.2} over frames {}–{}", s.op, low, fs[m].1.op, fs[j].0, fs[m].0) })); + spans.push((fs[j].0, fs[m].0)); + j = m + 1; + } else { + j += 1; + } + } + // Words that change in place instead of rolling or crossfading. Words that grow or + // shrink from the same start (streaming, a reveal) aren't a swap, nor is a count or a + // clock ticking ("1s" → "2s", "54.4K" → "64.6K") unless the app rolls its numbers. + for w in t.words.windows(2) { + let ((_, old), (k, new)) = (&w[0], &w[1]); + let (Some(a), Some(b)) = (t.at(k.wrapping_sub(1)), t.at(*k)) else { continue }; + if *k <= rec.start || parents.contains(&i) || starts_with_words(new, old) || starts_with_words(old, new) || !rec.counts_roll && ticks(old, new) { continue; } + if (a.flags | b.flags) & (LIVE | EXITING | VIRTUAL) != 0 || a.op.min(b.op) < rule("text-swap") || !seen(b, size) { continue; } + geo.push((i, Finding { kind: "text-swap", element: short(&t.path), frame: *k, detail: format!("\"{old}\" → \"{new}\" in one frame") })); + } + // Opacity that steps instead of fading. + for w in fs.windows(2) { + let (a, b) = (&w[0].1, &w[1].1); + if w[1].0 != w[0].0 + 1 || w[1].0 <= rec.start || (a.op - b.op).abs() < rule("fade-snap") { continue; } + let shown = if b.op > a.op { b } else { a }; + if spans.iter().any(|&(a, b)| w[1].0 >= a && w[1].0 <= b) { continue; } + if !seen(shown, size) || shown.flags & INK == 0 || area(&on_window(&shown.vis, size)) < 16.0 || (a.flags | b.flags) & (EXITING | VIRTUAL) != 0 { continue; } + geo.push((i, Finding { kind: "fade-snap", element: short(&t.path), frame: w[1].0, + detail: format!("opacity {:.2} → {:.2} in one frame", a.op, b.op) })); + } + } + // A child that rides its parent's motion is reported at the parent. + let reported: HashSet<(usize, &str, usize)> = geo.iter().map(|(i, f)| (*i, f.kind, f.frame)).collect(); + for (i, f) in geo.iter() { + let mut p = tr[*i].parent; + let mut dup = false; + while let Some(j) = p { + if ["reversal", "overshoot", "jiggle", "flicker", "jerk", "fade-snap", "snap", "flash", "changes-twice"].contains(&f.kind) && (0..=2).any(|o| reported.contains(&(j, f.kind, f.frame.saturating_sub(o))) || reported.contains(&(j, f.kind, f.frame + o))) { + dup = true; + break; + } + p = tr[j].parent; + } + if !dup { out.push(f.clone()); } + } + + // Rows that loaded with the view stay put after their first frame. + for &load in &rec.loads { + let quiet_until = input_frames.iter().chain(&rec.loads).copied().filter(|&k| k > load + 1).min().unwrap_or(n); + let mut hits: Vec<(usize, Finding)> = Vec::new(); + for (i, t) in tr.iter().enumerate() { + let Some(b) = born(t) else { continue }; + if b < load || b > load + 2 || loops.contains(&i) { continue; } + let Some(first) = t.at(b + 1).copied() else { continue }; + for k in b + 2..quiet_until.min(n) { + let Some(s) = t.at(k) else { break }; + let dy = (0..4).map(|a| (s.rect[a] - first.rect[a]).abs()).fold(0.0, f32::max); + let dop = (s.op - first.op).abs(); + if (dy > rule("load-motion") || dop > 0.1) && seen(s, size) { + hits.push((i, Finding { kind: "load-motion", element: short(&t.path), frame: k, + detail: format!("loaded at frame {b}, then {} by frame {k}", if dy > rule("load-motion") { format!("moved {dy:.1} pt") } else { format!("faded {:.2} → {:.2}", first.op, s.op) }) })); + break; + } + } + } + let set: HashSet<usize> = hits.iter().map(|h| h.0).collect(); + for (i, f) in hits { + if !tr[i].parent.is_some_and(|p| set.contains(&p)) { out.push(f); } + } + } + + // Settling: nothing but loops changes in the last half second, if it's well after input. + let last_input = input_frames.iter().copied().max().unwrap_or(0); + let tail = (0.5 * rec.hz) as usize; + if n > tail && n - tail > last_input + (0.5 * rec.hz) as usize { + let mut still: Vec<(usize, f32)> = Vec::new(); + for (i, t) in tr.iter().enumerate() { + if loops.contains(&i) { continue; } + let fs: Vec<&(usize, Snap)> = t.frames.iter().filter(|f| f.0 >= n - tail).collect(); + let moved = fs.windows(2).map(|w| (0..4).map(|a| (w[1].1.rect[a] - w[0].1.rect[a]).abs()).fold((w[1].1.op - w[0].1.op).abs(), f32::max)).fold(0.0, f32::max); + if moved > rule("never-settles") && fs.iter().any(|f| seen(&f.1, size)) { still.push((i, moved)); } + } + let set: HashSet<usize> = still.iter().map(|s| s.0).collect(); + for (i, moved) in still { + if tr[i].parent.is_some_and(|p| set.contains(&p)) { continue; } + out.push(Finding { kind: "never-settles", element: short(&tr[i].path), frame: n - tail, detail: format!("still moving {moved:.2} pt/frame in the last 0.5 s") }); + } + } + loops::jumps(rec, &mut out); + commits::scroll_commits(rec, &mut out); + kicks::kicks(rec, &loops, &mut out); + // Words that leave as the same words mount: a row remounted under a new key. + let window = rule("remount") as usize; + let leaving = |i: usize, k: usize| { + let mut p = Some(i); + while let Some(j) = p { + if tr[j].at(k).is_some_and(|s| s.flags & EXITING != 0) { return true; } + p = tr[j].parent; + } + false + }; + fn words_at(t: &Track, k: usize) -> Option<&str> { + t.words.iter().rev().find(|w| w.0 <= k).map(|w| w.1.as_str()).or(t.text.as_deref()) + } + // The same element under another key: its path differs in one segment. (An item moving to + // another list, or turning into another element, is a different element on purpose.) + let rekeyed = |a: &str, b: &str| { + let (a, b) = (a.trim_end_matches(" (leaving)"), b.trim_end_matches(" (leaving)")); + let (a, b): (Vec<_>, Vec<_>) = (a.split('/').collect(), b.split('/').collect()); + a.len() == b.len() && a.iter().zip(&b).filter(|(x, y)| x != y).count() == 1 + }; + for (i, t) in tr.iter().enumerate() { + let Some(k) = t.frames.windows(2).find(|w| w[1].0 == w[0].0 + 1 && w[0].0 > rec.start && !leaving(i, w[0].0) && leaving(i, w[1].0) && seen(&w[0].1, size)).map(|w| w[1].0) else { continue }; + let Some(words) = words_at(t, k).filter(|w| w.trim().len() >= 8) else { continue }; + if let Some(copy) = tr.iter().enumerate().find(|&(j, o)| j != i && rekeyed(&t.path, &o.path) + && born(o).is_some_and(|b| b > rec.start && b + window >= k && b <= k + window && !leaving(j, b) && words_at(o, b) == Some(words))).map(|(_, o)| o) { + out.push(Finding { kind: "remount", element: short(&t.path), frame: k, detail: format!("\"{}\" leaves as a copy mounts at {}", words.chars().take(40).collect::<String>(), short(&copy.path)) }); + } + } + // A scroll pinned to its end lets go with no one touching it: its content's bottom slides + // below the viewport's. Inputs named `event…` (data arriving) don't count as touching it. + let touched = |a: usize, b: usize| rec.inputs.iter().any(|(k, what)| *k >= a && *k <= b && !what.starts_with("event")); + for t in tr { + let Some(parent) = t.parent.map(|p| &tr[p]) else { continue }; + let mut pinned: Option<usize> = None; + for (k, s) in &t.frames { + // A scroll's content: taller than the viewport it fills. + let viewport = parent.at(*k).is_some_and(|v| (0..4).all(|a| (v.rect[a] - s.vis[a]).abs() < 0.5)); + if !viewport || s.rect[3] <= s.vis[3] + 1.0 { pinned = None; continue; } + let below = s.rect[1] + s.rect[3] - (s.vis[1] + s.vis[3]); + if below.abs() < 0.5 { pinned = Some(*k); continue; } + let Some(p) = pinned else { continue }; + if *k > rec.start && below >= rule("unpinned") && !touched(p, *k) { + out.push(Finding { kind: "unpinned", element: short(&t.path), frame: *k, detail: format!("its end, pinned at frame {p}, is {below:.1} pt below the viewport") }); + pinned = None; + } + } + } + // Rune names a second sibling under one key `key#dupN`: the same thing shows twice. + for t in tr.iter().filter(|t| t.path.rsplit('/').next().is_some_and(|s| s.contains("#dup"))) { + if let Some((k, _)) = t.frames.iter().find(|f| f.1.op >= rule("faint") && f.1.vis[2] > 0.0 && f.1.vis[3] > 0.0) { + out.push(Finding { kind: "twice", element: short(&t.path), frame: *k, detail: "a second element under its key".into() }); + } + } + // A flight draws unclipped and keeps its size, so one that lands out of view (below the + // window, or under a clip) shows whole all the way there, then vanishes the frame it rests. + let window = (1.5 * rec.hz) as usize; + let mut unseen: HashMap<usize, usize> = HashMap::new(); + for (i, t) in tr.iter().enumerate() { + let fs = &t.frames; + let hit = (1..fs.len()).find(|&j| { + let ((ka, a), (kb, b)) = (fs[j - 1], fs[j]); + let whole = a.rect[2] >= 4.0 && a.rect[3] >= 4.0 && area(&a.vis) >= 0.9 * area(&a.rect); + let still = (0..4).all(|x| (a.rect[x] - b.rect[x]).abs() < 0.5); + let shown = a.op >= rule("faint") && a.flags & INK != 0 && (a.flags | b.flags) & EXITING == 0; + if kb != ka + 1 || !whole || !still || !shown || area(&on_window(&b.vis, size)) >= 1.0 { return false; } + fs[..j].iter().rev().take_while(|f| f.0 + window >= ka).any(|f| { + let same_size = (2..4).all(|x| (f.1.rect[x] - a.rect[x]).abs() < 1.0); + let travel = (f.1.rect[0] - a.rect[0]).abs() + (f.1.rect[1] - a.rect[1]).abs(); + same_size && seen(&f.1, size) && travel >= rule("lands-unseen") + }) + }); + let Some(j) = hit else { continue }; + let k = fs[j].0; + unseen.insert(i, k); + if t.parent.and_then(|p| unseen.get(&p)) == Some(&k) { continue; } + out.push(Finding { kind: "lands-unseen", element: short(&t.path), frame: k, detail: "travelled in view, then its clip hid it where it rests".into() }); + } + if let Some(q) = rec.quiet_from { + let from = q + (f64::from(rule("wakes-after-end")) * rec.hz) as usize; + if let Some(k) = (from..n).find(|&k| rec.awake.get(k) == Some(&true)) { + out.push(Finding { kind: "wakes-after-end", element: "frame".into(), frame: k, detail: format!("asked for a frame {:.2} s after the motion ended", (k - q) as f64 / rec.hz) }); + } + } + // A load swaps the page in on its frame: what mounts, unmounts or moves then is the swap. + out.retain(|f| !(["pop-in", "pop-out", "jump", "offset-jump", "appear-then-jump", "fade-snap"].contains(&f.kind) + && rec.loads.iter().any(|&l| f.frame >= l && f.frame <= l + 2))); + painted::intended(rec, &mut out); + let pixels = regions::regions(rec, &loops, &out); + out.extend(pixels); + out.sort_by_key(|f| (f.frame, f.kind)); + out +} + +fn last_seg(path: &str) -> &str { + path.rsplit('/').next().unwrap_or(path) +} + +#[cfg(test)] +#[path = "check_tests.rs"] +mod tests; diff --git a/app/vendor/rune/crates/rune/src/motion_gate/check/commits.rs b/app/vendor/rune/crates/rune/src/motion_gate/check/commits.rs new file mode 100644 index 0000000..1f39ae9 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/motion_gate/check/commits.rs @@ -0,0 +1,35 @@ +//! `scroll-commit`: an app running its whole view on most frames of a scroll. Rune moves a +//! scroll's content, mounts a virtual list's rows and paints hover with no commit, so a scroll +//! that commits on most frames is the app asking: its `poll`, a handler or a layout read. Debug +//! builds name the site in a `rune:` warning as it happens. + +use super::{Finding, Recording, rule}; +use crate::runtime::CommitWhy; + +/// Committing frames a scroll may take before the share counts: a list loading its next page +/// commits a few times. +const COMMITS: usize = 6; + +pub(super) fn scroll_commits(rec: &Recording, out: &mut Vec<Finding>) { + let share = rule("scroll-commit"); + let mut k = 0; + while k < rec.scrolled.len() { + if !rec.scrolled[k].0 { + k += 1; + continue; + } + let from = k; + while k < rec.scrolled.len() && rec.scrolled[k].0 { k += 1; } + let run = &rec.scrolled[from..k]; + let committed: Vec<usize> = (from..k).filter(|&f| rec.scrolled[f].1 != 0).collect(); + if committed.len() < COMMITS || (committed.len() as f32) < share * run.len() as f32 { continue; } + let why = run.iter().fold(0, |b, f| b | f.1); + out.push(Finding { + kind: "scroll-commit", + element: "frame".into(), + frame: committed[0], + detail: format!("ran the view on {} of the {} frames of a scroll ({}): the debug build's `rune:` warning names the site", + committed.len(), run.len(), CommitWhy::names(why).join(", ")), + }); + } +} diff --git a/app/vendor/rune/crates/rune/src/motion_gate/check/evidence.rs b/app/vendor/rune/crates/rune/src/motion_gate/check/evidence.rs new file mode 100644 index 0000000..6cb7bf2 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/motion_gate/check/evidence.rs @@ -0,0 +1,103 @@ +//! Evidence for a finding: a dump of the tracks around it and a contact strip of its frames. + +use super::paint::{self, CHANNELS, Paint}; +use super::{Recording, Snap}; + +fn paint_line(p: &Paint) -> String { + let mut out = String::new(); + for ch in CHANNELS { + let v = paint::value(p, ch.name); + let quiet = matches!(v.as_str(), "none" | "0.0" | "#00000000") || v.ends_with("00") && v.len() == 9; + if !quiet { out += &format!(" {}={v}", ch.name); } + } + out += &format!(" z={}", p.rank); + if p.intent != 0 { out += &format!(" intent={:#x}", p.intent); } + if p.instant { out += " instant"; } + out +} + +/// Frames `from..to` of every track whose path contains `filter`, one line per frame: +/// `frame rect visible opacity flags` and what it paints. For reading a finding's +/// neighbourhood. +pub fn dump(rec: &Recording, filter: &str, from: usize, to: usize) -> String { + let mut out = String::new(); + for t in rec.tracks.iter().filter(|t| t.path.contains(filter)) { + out += &format!("{}\n", t.path); + for (j, (k, s)) in t.frames.iter().enumerate().filter(|(_, f)| f.0 >= from && f.0 < to) { + out += &format!(" {k:4} [{:7.1} {:7.1} {:6.1} {:6.1}] vis [{:6.1} {:6.1} {:6.1} {:6.1}] op {:.3} sc {:.3} {:02b}{}{}\n", + s.rect[0], s.rect[1], s.rect[2], s.rect[3], s.vis[0], s.vis[1], s.vis[2], s.vis[3], s.op, s.scale, s.flags, + if rec.instant.get(*k) == Some(&true) { " INSTANT" } else { "" }, + t.paint.get(j).and_then(Option::as_ref).map_or(String::new(), paint_line)); + } + } + out +} + +const Z: f32 = 0.25; +const SWATCH: u32 = 10; + +/// A contact strip of frames `at-4..=at+4`: the composited window (see `raster`), every +/// element's visible rect as an outline over it, as strong as its opacity, `focus`'s in red. +/// Under each frame, a swatch per colour `focus` paints (fill, border, text, shadow, gradient, +/// outline), so the colour that broke shows frame by frame. Secondary evidence: the findings are +/// the gate. +pub fn sheet(rec: &Recording, at: usize, focus: &str) -> ::image::RgbImage { + let (w, h) = ((rec.size.0 * Z) as u32, (rec.size.1 * Z) as u32); + let frames: Vec<usize> = (at.saturating_sub(4)..=at + 4).filter(|&k| k < rec.frames).collect(); + let gap = 6; + let hot = |path: &str| !focus.is_empty() && path.contains(focus); + // The colours the focus paints anywhere in the strip. + let used: Vec<usize> = (0..paint::COLORS).filter(|&c| rec.tracks.iter().filter(|t| hot(&t.path)) + .any(|t| frames.iter().any(|&k| t.paint_at(k).is_some_and(|p| p.colors[c].a > 0.02)))).collect(); + let strip = used.len() as u32 * (SWATCH + 2); + let bg = ::image::Rgb([16, 18, 22]); + let mut img = ::image::RgbImage::from_pixel((w + gap) * frames.len() as u32, h + strip + 4, bg); + let srgb = |c: crate::color::Color| [c.r, c.g, c.b].map(|v| (crate::color::srgb_encode(v.clamp(0.0, 1.0)) * 255.0).round() as u8); + for (col, &k) in frames.iter().enumerate() { + let x0 = col as u32 * (w + gap); + if let Some(g) = rec.grids.get(k).and_then(|g| g.as_deref()) { + for py in 0..h { + for px in 0..w { + let (cx, cy) = (((px as f32 / Z) / super::raster::CELL) as usize, ((py as f32 / Z) / super::raster::CELL) as usize); + if cx < g.w && cy < g.h { img.put_pixel(x0 + px, py, ::image::Rgb(srgb(g.color(cy * g.w + cx)))); } + } + } + } + if k == at { + for x in x0..x0 + w { img.put_pixel(x, 0, ::image::Rgb([255, 210, 80])); } + } + for t in &rec.tracks { + let Some(s) = t.at(k) else { continue }; + outline(&mut img, x0, (w, h), s, hot(&t.path)); + } + let focus_paint = rec.tracks.iter().filter(|t| hot(&t.path)).find_map(|t| t.paint_at(k)); + for (row, &c) in used.iter().enumerate() { + let Some(p) = focus_paint else { continue }; + let y = h + 4 + row as u32 * (SWATCH + 2); + // Over a checker of black and white, so alpha shows. + for py in 0..SWATCH { + for px in 0..w.min(80) { + let under = if (px / 5 + py / 5) % 2 == 0 { crate::color::Color::BLACK } else { crate::color::Color::WHITE }; + let [r, g, b, _] = crate::color::over(p.colors[c].premul(1.0), under.premul(1.0)); + img.put_pixel(x0 + px, y + py, ::image::Rgb(srgb(crate::color::Color { r, g, b, a: 1.0 }))); + } + } + } + } + img +} + +fn outline(img: &mut ::image::RgbImage, x0: u32, (w, h): (u32, u32), s: &Snap, hot: bool) { + let a = s.op.clamp(0.0, 1.0) * if hot { 1.0 } else { 0.5 }; + let ink = if hot { [255.0, 70.0, 70.0] } else { [200.0, 205.0, 215.0] }; + let [x, y, rw, rh] = s.vis.map(|v| v * Z); + if rw < 1.0 || rh < 1.0 { return; } + let mut plot = |px: f32, py: f32| { + let (px, py) = (px as u32, py as u32); + if px >= w || py >= h { return; } + let p = img.get_pixel_mut(x0 + px, py); + for c in 0..3 { p.0[c] = (p.0[c] as f32 * (1.0 - a) + ink[c] * a) as u8; } + }; + for i in 0..rw as u32 { plot(x + i as f32, y); plot(x + i as f32, y + rh - 1.0); } + for i in 0..rh as u32 { plot(x, y + i as f32); plot(x + rw - 1.0, y + i as f32); } +} diff --git a/app/vendor/rune/crates/rune/src/motion_gate/check/kicks.rs b/app/vendor/rune/crates/rune/src/motion_gate/check/kicks.rs new file mode 100644 index 0000000..973089d --- /dev/null +++ b/app/vendor/rune/crates/rune/src/motion_gate/check/kicks.rs @@ -0,0 +1,92 @@ +//! `stop-start`: an edge that travels in kicks. Each time data arrives it sets off, slows, rests +//! a moment and sets off again the same way, like a reply's scroll that stops and kicks per +//! line, where one steady glide was meant. Each kick passes `jerk` and `jump` on its own. + +use std::collections::HashSet; + +use super::{Finding, Recording, edge, rule, seen, short}; + +/// A frame step under this many points is no motion. +const STILL: f32 = 0.005; +/// Points a kick travels before it rests: a creep in under a pixel a frame isn't one. +const KICK: f32 = 0.25; +/// Frames still before setting off again counts as a rest. +const REST: usize = 3; +/// Rests up to this many seconds are a stop within one travel; a longer one ends it. +const PAUSE: f64 = 0.5; +/// Seconds the restarts are counted over. +const WINDOW: f64 = 2.0; + +pub(super) fn kicks(rec: &Recording, loops: &HashSet<usize>, out: &mut Vec<Finding>) { + let tr = &rec.tracks; + let (pause, window) = ((PAUSE * rec.hz) as usize, (WINDOW * rec.hz) as usize); + let need = rule("stop-start") as usize; + // Data arriving (`event…`) is what kicks it; a hand on the app may start a motion each time. + let touched = |a: usize, b: usize| rec.inputs.iter().any(|(k, what)| *k >= a && *k <= b && !what.starts_with("event")); + let mut hits: Vec<(usize, Finding)> = Vec::new(); + for (i, t) in tr.iter().enumerate().filter(|(i, _)| !loops.contains(i)) { + for axis in 0..2 { + let mut restarts: Vec<usize> = Vec::new(); + let (mut prev, mut dir, mut still, mut went) = (None::<(usize, f32)>, 0.0, 0, 0.0); + for (k, s) in &t.frames { + if *k <= rec.start || s.op < rule("faint") || !seen(s, rec.size) { + (prev, dir, still, went) = (None, 0.0, 0, 0.0); + continue; + } + let at = edge(s, axis); + if let Some((_, was)) = prev.filter(|p| p.0 + 1 == *k) { + let d = at - was; + if d.abs() < STILL { + still += 1; + } else { + if still >= REST { + if still <= pause && d.signum() == dir && went >= KICK { + restarts.push(*k); + } + went = 0.0; + } + went += d.abs(); + (dir, still) = (d.signum(), 0); + } + } + prev = Some((*k, at)); + } + let burst = (0..restarts.len()).find(|&j| { + restarts.get(j + need - 1).is_some_and(|&last| last - restarts[j] <= window && !touched(restarts[j], last)) + }); + if let Some(j) = burst { + let k = restarts[j]; + let n = restarts[j..].iter().take_while(|&&r| r - k <= window).count(); + hits.push((i, Finding { + kind: "stop-start", + element: short(&t.path), + frame: k, + detail: format!("{} rests and sets off again {n} times in {WINDOW} s", ["x", "y"][axis]), + })); + break; + } + } + } + // A scroll's rows all kick together: report the outermost, once among its siblings and + // everything inside them. + let family = |i: usize| { + let mut up = vec![i]; + let mut p = tr[i].parent; + while let Some(j) = p { + up.push(j); + p = tr[j].parent; + } + up + }; + let mut kept: Vec<(usize, usize)> = Vec::new(); + hits.sort_by_key(|(i, f)| (family(*i).len(), f.frame)); + for (i, f) in hits { + let up = family(i); + let near = |&(j, k): &(usize, usize)| k.abs_diff(f.frame) <= window && (up.contains(&j) || tr[j].parent.is_some_and(|p| up.contains(&p))); + if kept.iter().any(near) { + continue; + } + kept.push((i, f.frame)); + out.push(f); + } +} diff --git a/app/vendor/rune/crates/rune/src/motion_gate/check/loops.rs b/app/vendor/rune/crates/rune/src/motion_gate/check/loops.rs new file mode 100644 index 0000000..4ea4bcf --- /dev/null +++ b/app/vendor/rune/crates/rune/src/motion_gate/check/loops.rs @@ -0,0 +1,107 @@ +//! Which tracks loop: motion that keeps going of its own accord, its wraps and turns its design. +//! +//! A loop is told from the trace. A clock loop (`El::looping`) reports a phase: a periodic one +//! wraps from near 1 to 0 and steps on until the capture ends, while a finite sequence (a +//! one-shot fade) climbs from 0 to 1 and holds 1 at rest, which is a transition that settled, +//! not a loop. Without a phase, an element that changes on most frames and keeps turning back +//! loops, unless its turns follow inputs: a list a person keeps toggling turns too. + +use std::collections::{HashMap, HashSet}; + +use super::{Finding, Recording, Snap, Track, rule, short}; + +/// A finite sequence that played out: its phase rests at 1, which a periodic phase never reaches. +fn plays_out(t: &Track) -> bool { + t.frames.windows(2).any(|w| w[0].1.phase == 1.0 && w[1].1.phase == 1.0) +} + +/// Its phase wraps, or steps on to the capture's last frame, and it never played out. +fn periodic_phase(t: &Track, n: usize) -> bool { + let ph: Vec<(usize, f32)> = t.frames.iter().filter(|f| !f.1.phase.is_nan()).map(|f| (f.0, f.1.phase)).collect(); + let steps = || ph.windows(2).filter(|w| w[1].0 == w[0].0 + 1); + let wraps = steps().any(|w| w[1].1 < w[0].1 - 0.5); + let to_end = ph.last().is_some_and(|l| l.0 + 1 == n) && steps().last().is_some_and(|w| w[1].1 != w[0].1); + (wraps || to_end) && !plays_out(t) +} + +/// Every track that loops, with everything inside one. +pub(super) fn loops(rec: &Recording) -> HashSet<usize> { + let tr = &rec.tracks; + // How long an input's answer may take: its spring, the scroll that follows it. + let answer = (0.5 * rec.hz) as usize; + let answering = |k: usize| rec.inputs.iter().any(|i| i.0 <= k && k <= i.0 + answer); + let changed = |a: &Snap, b: &Snap| (0..4).any(|i| (a.rect[i] - b.rect[i]).abs() > 0.01) || (a.op - b.op).abs() > 0.002; + let mut busy = vec![0usize; tr.len()]; + let mut group_busy: HashMap<usize, HashSet<usize>> = HashMap::new(); + for (i, t) in tr.iter().enumerate() { + for w in t.frames.windows(2) { + if w[1].0 == w[0].0 + 1 && changed(&w[0].1, &w[1].1) { + busy[i] += 1; + if let Some(p) = t.parent { group_busy.entry(p).or_default().insert(w[1].0); } + } + } + } + // Busy alone would take a long stream or a slow spring for a loop; a loop also comes back, + // by itself: a turn soon after an input answers it. + let periodic = |t: &Track| { + let turns = |v: &dyn Fn(&Snap) -> f32, eps: f32| { + let (mut n, mut last, mut dir) = (0, v(&t.frames[0].1), 0.0f32); + for f in &t.frames[1..] { + let x = v(&f.1); + if (x - last).abs() > eps { + let s = (x - last).signum(); + if dir != 0.0 && s != dir && !answering(f.0) { n += 1; } + dir = s; + last = x; + } + } + n + }; + turns(&|s| s.op, 0.01) >= 4 || (0..4).any(|a| turns(&|s| s.rect[a], 0.25) >= 4) + }; + let busy_most = |i: usize, frames: usize| tr[i].frames.len() >= 60 && frames * 10 >= tr[i].frames.len() * 6; + let mut loops: HashSet<usize> = (0..tr.len()) + .filter(|&i| periodic_phase(&tr[i], rec.frames) || busy_most(i, busy[i]) && periodic(&tr[i])) + .collect(); + // Siblings taking turns (a typing indicator's dots) loop together. + for (&p, ks) in &group_busy { + if busy_most(p, ks.len()) && tr.iter().any(|c| c.parent == Some(p) && c.frames.len() >= 2 && periodic(c)) { + loops.extend((0..tr.len()).filter(|&c| tr[c].parent == Some(p))); + } + } + loop { + let more: Vec<usize> = (0..tr.len()).filter(|i| !loops.contains(i) && tr[*i].parent.is_some_and(|p| loops.contains(&p))).collect(); + if more.is_empty() { break; } + loops.extend(more); + } + loops +} + +/// A periodic loop keeps its rhythm: each moving frame steps its phase as the last did, and one +/// back from a blink comes back where its rhythm has got to. One that restarted or skipped (a +/// remount, or a new loop where one was running) steps off it. A phase held still (a delay, +/// reduced motion) and a sequence that played out aren't checked. +pub(super) fn jumps(rec: &Recording, out: &mut Vec<Finding>) { + let blink = (0.1 * rec.hz) as usize; + for t in rec.tracks.iter().filter(|t| !plays_out(t)) { + let ph: Vec<(usize, f32)> = t.frames.iter().filter(|f| !f.1.phase.is_nan()).map(|f| (f.0, f.1.phase)).collect(); + // (frame, frames since the last, phase step) + let steps: Vec<(usize, usize, f32)> = ph.windows(2).filter(|w| w[1].0 - w[0].0 <= blink) + .map(|w| (w[1].0, w[1].0 - w[0].0, (w[1].1 - w[0].1).rem_euclid(1.0))) + .collect(); + // A step out of a hold starts partway through a frame. + let moving: Vec<(usize, usize, f32)> = steps.windows(2).filter(|w| w[0].2 > 0.0 && w[1].2 > 0.0).map(|w| w[1]).collect(); + let mut sorted: Vec<f32> = moving.iter().filter(|s| s.1 == 1).map(|s| s.2).collect(); + if sorted.len() < 4 { continue; } + sorted.sort_by(f32::total_cmp); + let usual = sorted[sorted.len() / 2]; + let off = |&(_, frames, d): &(usize, usize, f32)| { + let x = (d - frames as f32 * usual).rem_euclid(1.0); + x.min(1.0 - x) + }; + if let Some(&(k, frames, d)) = moving.iter().find(|s| off(s) > rule("loop-jump")) { + let over = if frames > 1 { format!(" over {frames} frames") } else { String::new() }; + out.push(Finding { kind: "loop-jump", element: short(&t.path), frame: k, detail: format!("phase stepped {d:.3}{over} where it steps {usual:.3} a frame") }); + } + } +} diff --git a/app/vendor/rune/crates/rune/src/motion_gate/check/paint.rs b/app/vendor/rune/crates/rune/src/motion_gate/check/paint.rs new file mode 100644 index 0000000..1d6e7e9 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/motion_gate/check/paint.rs @@ -0,0 +1,228 @@ +//! What an element paints on one frame, beside its rect and opacity: its colours, corners, +//! blurs, shadow, effect payload, image and place in the paint order, and how far apart two +//! frames of it look. + +use crate::color::{Color, over}; +use crate::el::motion::MotionIntent; + +/// Colours an element paints, in linear RGBA (`C_*` index them). +pub const COLORS: usize = 6; +pub const C_FILL: usize = 0; +pub const C_BORDER: usize = 1; +pub const C_TEXT: usize = 2; +pub const C_SHADOW: usize = 3; +pub const C_GRADIENT: usize = 4; +pub const C_OUTLINE: usize = 5; + +/// Sizes an element paints, in points (`S_*` index them). +pub const SIZES: usize = 5; +pub const S_RADIUS: usize = 0; +pub const S_BORDER: usize = 1; +pub const S_BLUR: usize = 2; +pub const S_BACKDROP: usize = 3; +pub const S_SHADOW: usize = 4; + +/// Every painted property an element presents on one frame. +#[derive(Clone, Debug, PartialEq)] +pub struct Paint { + /// Fill (with its hover and press overlays and its paint alpha), border, text or icon, + /// shadows together, gradient (its mean), outline. + pub colors: [Color; COLORS], + /// Corner radius, border width, blur, backdrop blur, shadow blur. + pub sizes: [f32; SIZES], + /// The second gradient colour (bottom, or a radial gradient's last stop). + pub gradient_end: Color, + /// `El::effect_data`, when it has an effect. + pub effect: Option<[f32; 4]>, + /// Which image content it shows (`El::pixels`), changing with each new frame of it. + pub image: Option<(u64, u64)>, + /// Its place in the paint order: higher paints over lower. + pub rank: u32, + /// [`MotionIntent`] bits marked on it or an element it sits in. + pub intent: u16, + /// It or its parent changes at once by design (`El::instant_changes`). + pub instant: bool, + /// Channels (a bit per index in [`CHANNELS`]) it lands at once by design: those its own + /// `El::motion(Spring::NONE)` or `El::blur_motion(Spring::NONE)` governs (see [`at_once`]). + pub at_once: u16, + /// How hovered and how pressed it shows, 0 to 1 (hovered: its own hover, or its group's + /// when it has a `group_color`). A highlight lands with the pointer by design, so a fill or + /// group colour that steps with these isn't a snap. + pub pointer: [f32; 2], +} + +impl Default for Paint { + fn default() -> Self { + Paint { colors: [Color::TRANSPARENT; COLORS], sizes: [0.0; SIZES], gradient_end: Color::TRANSPARENT, effect: None, image: None, rank: 0, intent: 0, instant: false, at_once: 0, pointer: [0.0; 2] } + } +} + +impl Paint { + /// Whether channel `i` of [`CHANNELS`] lands at once on it by design. + pub fn at_once(&self, i: usize) -> bool { + self.at_once & (1 << i) != 0 + } + + pub fn intends(&self, any: MotionIntent) -> bool { + self.intent & any.bits() != 0 + } + + /// Whether it paints a box whose corners show. + pub fn shows_corners(&self) -> bool { + self.colors[C_FILL].a > 0.02 || self.colors[C_BORDER].a > 0.02 && self.sizes[S_BORDER] > 0.0 || self.colors[C_GRADIENT].a > 0.02 || self.sizes[S_BACKDROP] > 0.0 + } + + /// Whether its own fill hides what it covers. + pub fn opaque(&self) -> bool { + self.colors[C_FILL].a > 0.6 || self.colors[C_GRADIENT].a > 0.6 || self.image.is_some() + } +} + +/// OKLab with its lightness through Ottosson's toe (`L_r`), which follows CIELAB's near black: +/// plain OKLab's cube root makes the last percent of a fade to black look like a big step. +pub fn toe([l, a, b]: [f32; 3]) -> [f32; 3] { + const K1: f32 = 0.206; + const K2: f32 = 0.03; + const K3: f32 = (1.0 + K1) / (1.0 + K2); + let x = K3 * l - K1; + let lr = 0.5 * (x + (x * x + 4.0 * K2 * K3 * l).max(0.0).sqrt()); + let s = if l > 1e-4 { lr / l } else { 0.0 }; + [lr, a * s, b * s] +} + +fn seen(c: Color) -> [f32; 3] { + let [l, a, b, _] = c.to_oklab(); + toe([l, a, b]) +} + +/// Perceptual distance between two colours as they'd show on black and on white, whichever is +/// larger, in OKLab (0 is the same, 1 is black to white). An alpha change counts as far as it +/// shows. +pub fn oklab_de(a: Color, b: Color) -> f32 { + let on = |c: Color, bg: Color| -> [f32; 3] { + let [r, g, b, al] = over(c.premul(1.0), bg.premul(1.0)); + seen(Color { r, g, b, a: al }) + }; + [Color::BLACK, Color::WHITE].into_iter().map(|bg| { + let (x, y) = (on(a, bg), on(b, bg)); + ((x[0] - y[0]).powi(2) + (x[1] - y[1]).powi(2) + (x[2] - y[2]).powi(2)).sqrt() + }).fold(0.0, f32::max) +} + +/// How much a change over `area` pt² counts against a 40×40 control: a large surface's +/// change shows more, a speck's less, and one under 16 pt² not at all. +pub fn area_weight(area: f32) -> f32 { + if area < 16.0 { 0.0 } else { (area / 1600.0).powf(0.25).clamp(0.5, 2.5) } +} + +/// One painted property the checks follow: where a frame's value sits, so that how far apart +/// two frames' points are is how different they look, and how much of it shows. +pub struct Channel { + pub name: &'static str, + /// Its value as a point, scaled so a distance of 1 is a change a person sees at once on a + /// 40×40 control. + pub embed: fn(&Paint) -> V, + /// How much a change counts for, given the visible part `rect` (see [`area_weight`]). + pub weight: fn(&Paint, &[f32; 4]) -> f32, +} + +pub type V = [f32; 6]; + +fn ring(r: &[f32; 4], width: f32) -> f32 { + (2.0 * (r[2] + r[3]) * width.max(0.0)).min(r[2] * r[3]) +} + +/// A colour as it shows on black and on white, in OKLab, scaled so ΔE 0.08 is 1. +fn lab(c: Color) -> V { + let on = |bg: Color| { + let [r, g, b, al] = over(c.premul(1.0), bg.premul(1.0)); + seen(Color { r, g, b, a: al }) + }; + let (k, w) = (on(Color::BLACK), on(Color::WHITE)); + [k[0], k[1], k[2], w[0], w[1], w[2]].map(|v| v / (0.08 * std::f32::consts::SQRT_2)) +} + +fn size(v: f32, unit: f32) -> V { + [v / unit, 0.0, 0.0, 0.0, 0.0, 0.0] +} + +/// A point for each distinct value of a hash, all √2 apart: a swap is a step of 1.4 and a swap +/// back returns where it was. +fn token(h: u64) -> V { + let mut x = h ^ 0x9E37_79B9_7F4A_7C15; + std::array::from_fn(|_| { + x ^= x >> 33; + x = x.wrapping_mul(0xff51_afd7_ed55_8ccd); + x ^= x >> 29; + (x >> 40) as f32 / (1u64 << 24) as f32 * 2.0 - 1.0 + }).map(|v: f32| v / 1.41) +} + +fn area(r: &[f32; 4]) -> f32 { + r[2].max(0.0) * r[3].max(0.0) +} + +/// Every channel the element checks follow. +pub const CHANNELS: &[Channel] = &[ + Channel { name: "fill", embed: |p| lab(p.colors[C_FILL]), weight: |_, r| area_weight(area(r)) }, + Channel { name: "border", embed: |p| lab(p.colors[C_BORDER]), weight: |p, r| area_weight(ring(r, p.sizes[S_BORDER].max(1.0)) * 6.0) }, + Channel { name: "text-color", embed: |p| lab(p.colors[C_TEXT]), weight: |_, r| area_weight(0.4 * area(r)) }, + Channel { name: "shadow", embed: |p| lab(p.colors[C_SHADOW]), weight: |_, r| area_weight(0.5 * area(r)) }, + Channel { name: "gradient", embed: |p| { + let (a, b) = (lab(p.colors[C_GRADIENT]), lab(p.gradient_end)); + std::array::from_fn(|i| (a[i] + b[i]) / 2.0) + }, weight: |_, r| area_weight(area(r)) }, + Channel { name: "outline", embed: |p| lab(p.colors[C_OUTLINE]), weight: |_, r| area_weight(ring(r, 2.0) * 6.0) }, + Channel { name: "radius", embed: |p| size(p.sizes[S_RADIUS], 3.0), weight: |p, _| if p.shows_corners() { 1.0 } else { 0.0 } }, + Channel { name: "border-width", embed: |p| size(p.sizes[S_BORDER], 1.0), weight: |p, _| if p.colors[C_BORDER].a > 0.05 { 1.0 } else { 0.0 } }, + Channel { name: "blur", embed: |p| size(p.sizes[S_BLUR], 2.0), weight: |_, _| 1.0 }, + Channel { name: "backdrop-blur", embed: |p| size(p.sizes[S_BACKDROP], 4.0), weight: |_, _| 1.0 }, + Channel { name: "shadow-blur", embed: |p| size(p.sizes[S_SHADOW], 4.0), weight: |p, _| if p.colors[C_SHADOW].a > 0.05 { 1.0 } else { 0.0 } }, + Channel { name: "effect", embed: |p| match p.effect { + Some(d) => [d[0], d[1], d[2], d[3], 0.0, 1.0].map(|v| v / 0.5), + None => [0.0; 6], + }, weight: |_, r| if area(r) >= 16.0 { 1.0 } else { 0.0 } }, + Channel { name: "image", embed: |p| p.image.map_or([0.0; 6], |(id, g)| token(id.wrapping_mul(31).wrapping_add(g))), weight: |_, r| if area(r) >= 16.0 { 1.0 } else { 0.0 } }, +]; + +/// The [`Paint::at_once`] bits for an element whose own `El::motion` is `Spring::NONE` +/// (`motion`) and whose own blur curve is instant (`blur`; `Some(false)` when it has a curve of +/// its own that isn't). Its colours, corners and shadow land on that spring, and its blur too +/// unless it has its own curve; text colour keeps a short fade, and border width, backdrop +/// blur, effect and image don't spring at all. +pub fn at_once(motion: bool, blur: Option<bool>) -> u16 { + let sprung: &[&str] = &["fill", "border", "shadow", "gradient", "outline", "radius", "shadow-blur"]; + let blurs = blur.unwrap_or(motion); + CHANNELS.iter().enumerate() + .filter(|(_, c)| motion && sprung.contains(&c.name) || blurs && c.name == "blur") + .fold(0, |bits, (i, _)| bits | 1 << i) +} + +/// The colour a channel shows, for evidence: its swatch. +pub fn swatch(p: &Paint, channel: &str) -> Option<Color> { + Some(match channel { + "fill" => p.colors[C_FILL], + "border" => p.colors[C_BORDER], + "text-color" => p.colors[C_TEXT], + "shadow" => p.colors[C_SHADOW], + "gradient" => p.colors[C_GRADIENT], + "outline" => p.colors[C_OUTLINE], + _ => return None, + }) +} + +/// A channel's value as text, for evidence. +pub fn value(p: &Paint, channel: &str) -> String { + if let Some(c) = swatch(p, channel) { return c.hex(); } + match channel { + "radius" => format!("{:.1}", p.sizes[S_RADIUS]), + "border-width" => format!("{:.1}", p.sizes[S_BORDER]), + "blur" => format!("{:.1}", p.sizes[S_BLUR]), + "backdrop-blur" => format!("{:.1}", p.sizes[S_BACKDROP]), + "shadow-blur" => format!("{:.1}", p.sizes[S_SHADOW]), + "effect" => p.effect.map_or("none".into(), |d| format!("[{:.2} {:.2} {:.2} {:.2}]", d[0], d[1], d[2], d[3])), + "image" => p.image.map_or("none".into(), |(id, g)| format!("#{id}.{g}")), + "z-order" => p.rank.to_string(), + _ => String::new(), + } +} diff --git a/app/vendor/rune/crates/rune/src/motion_gate/check/painted.rs b/app/vendor/rune/crates/rune/src/motion_gate/check/painted.rs new file mode 100644 index 0000000..68cd45a --- /dev/null +++ b/app/vendor/rune/crates/rune/src/motion_gate/check/painted.rs @@ -0,0 +1,165 @@ +//! `snap`, `flash` and `changes-twice` on what an element paints: each colour, corner, blur, +//! shadow, effect payload and image it presents (see [`paint::CHANNELS`]), and its place in the +//! paint order against what it overlaps (`z-order`). A colour that springs or fades has no +//! one-frame step and passes. Changes an input asked for on its frame, a hover or press highlight +//! landing (it lands with the pointer, even on content sliding under a still one), a +//! `Tx::instant` commit, an `El::instant_changes` element, a matching `El::motion_intent` mark, +//! and a `motion(Spring::NONE)` written on the element itself (for what that spring governs) are +//! the design. + +use std::collections::{HashMap, HashSet}; + +use super::paint::{self, CHANNELS, Paint}; +use super::series::{self, Tune}; +use super::{EXITING, Finding, GROWING, LIVE, Recording, Snap, Track, area, on_window, rule, seen, short}; +use crate::el::motion::MotionIntent; + +/// The `MotionIntent` marks that make a finding of `kind` the design. +pub fn intent_for(kind: &str) -> MotionIntent { + match kind { + "overshoot" => MotionIntent::OVERSHOOT, + "reversal" => MotionIntent::RECOIL | MotionIntent::JIGGLE, + "jiggle" => MotionIntent::JIGGLE, + "jerk" | "stop-start" => MotionIntent::IMPULSE, + "jump" | "appear-then-jump" | "offset-jump" | "changes-twice" => MotionIntent::STEP, + "pop-in" | "pop-out" | "cut-exit" | "fade-snap" | "text-swap" => MotionIntent::CUT, + "flicker" | "flash" => MotionIntent::PULSE, + "snap" => MotionIntent::STEP | MotionIntent::CUT, + _ => MotionIntent::NONE, + } +} + +/// Element tunes: a distance of 1 is a change seen at once (see `paint::CHANNELS`). +pub fn tune(hz: f64) -> Tune { + Tune { + snap: rule("snap"), + flash: rule("flash"), + still: 0.04, + horizon: (0.4 * hz).round() as usize, + rest: (2, (rule("changes-twice") as f64 * hz).round() as usize), + } +} + +/// Whether a change on frame `k` of `t` is marked as the design for `kind`. +pub fn marked(t: &Track, k: usize, kind: &str) -> bool { + let bits = intent_for(kind); + bits != MotionIntent::NONE && [k.saturating_sub(1), k].iter().any(|&j| t.paint_at(j).is_some_and(|p| p.intends(bits))) +} + +/// Drops findings an element marked with the matching `El::motion_intent` (or sitting in one). +pub fn intended(rec: &Recording, out: &mut Vec<Finding>) { + let mut by_name: HashMap<String, Vec<&Track>> = HashMap::new(); + for t in rec.tracks.iter().filter(|t| t.paint.iter().any(|p| p.as_ref().is_some_and(|p| p.intent != 0))) { + by_name.entry(short(&t.path)).or_default().push(t); + } + if by_name.is_empty() { return; } + out.retain(|f| !by_name.get(&f.element).is_some_and(|ts| ts.iter().any(|t| marked(t, f.frame, f.kind)))); +} + +fn shows(s: &Snap, size: (f32, f32)) -> bool { + seen(s, size) && s.op >= rule("faint") && s.flags & (EXITING | LIVE) == 0 +} + +/// Every channel's discontinuities, for each track. +pub fn painted(rec: &Recording, loops: &HashSet<usize>) -> Vec<(usize, Finding)> { + let tune = tune(rec.hz); + let n = rec.frames; + let mut out = Vec::new(); + let input_in = |a: usize, b: usize| rec.inputs.iter().filter(|x| x.0 >= a && x.0 <= b).count(); + for (i, t) in rec.tracks.iter().enumerate() { + if loops.contains(&i) || t.paint.is_empty() { continue; } + // Frame → (presented state, paint) where it shows and changes only by animation. + let at: Vec<Option<(&Snap, &Paint)>> = (0..n).map(|k| { + let s = t.at(k)?; + let p = t.paint_at(k)?; + (k >= rec.start && shows(s, rec.size) && !p.instant).then_some((s, p)) + }).collect(); + if at.iter().all(Option::is_none) { continue; } + for (c, ch) in CHANNELS.iter().enumerate() { + // An element's own `motion(Spring::NONE)` lands what it governs at once by design. + let vals: Vec<Option<series::V>> = at.iter().map(|x| x.filter(|(_, p)| !p.at_once(c)).map(|(_, p)| (ch.embed)(p))).collect(); + let w = |k: usize| -> f32 { + let one = |j: usize| at.get(j).copied().flatten().map_or(0.0, |(s, p)| (ch.weight)(p, &on_window(&s.vis, rec.size)) * s.op.min(1.0)); + one(k).max(one(k.wrapping_sub(1))) + }; + // A hover or press highlight landing, even on content that slid under a still pointer: + // a fill, or text in its hovered group's colour (`El::group_color`). + let pointer = |a: usize, b: usize| { + matches!(ch.name, "fill" | "text-color") && (a.max(1)..=b).any(|j| at[j].zip(at[j - 1]).is_some_and(|((_, p), (_, q))| p.pointer != q.pointer)) + }; + for e in series::events(&vals, &tune, &w) { + let k = e.k; + let skip = match e.kind { + "snap" => input_in(k.saturating_sub(1), k) > 0 || rec.instant.get(k) == Some(&true) || pointer(k, k), + "flash" => input_in(e.span.0 + 1, e.span.1) >= 2 || pointer(e.span.0 + 1, e.span.1), + _ => input_in(e.span.0 + 1, e.span.1) > 0 || pointer(e.span.0 + 1, e.span.1), + }; + if skip || marked(t, k, e.kind) || rec.loads.iter().any(|&l| k >= l && k <= l + 2) { continue; } + let v = |j: usize| at.get(j).copied().flatten().map_or_else(|| "–".into(), |(_, p)| paint::value(p, ch.name)); + let detail = match e.kind { + "snap" => format!("{} {} → {} in one frame", ch.name, v(k - 1), v(k)), + "flash" => format!("{} {} → {} → {} over frames {}–{}", ch.name, v(e.span.0), v(k), v(e.span.1), e.span.0, e.span.1), + _ => format!("{} {} → {}, rests, then → {} over frames {}–{}", ch.name, v(e.span.0), v(k - 1), v(e.span.1), e.span.0, e.span.1), + }; + out.push((i, Finding { kind: e.kind, element: short(&t.path), frame: k, detail })); + } + } + } + out.extend(z_order(rec)); + out +} + +/// Two overlapping opaque surfaces trading places in the paint order in one frame: one shows +/// through where the other was. Back within the flash window, it's a `flash`. +fn z_order(rec: &Recording) -> Vec<(usize, Finding)> { + let n = rec.frames; + let horizon = (0.4 * rec.hz).round() as usize; + let tr = &rec.tracks; + let inside = |a: &str, b: &str| a.len() > b.len() && a.starts_with(b) && a.as_bytes()[b.len()] == b'/'; + // Frame → the solid surfaces showing, with their rank and visible part. + let solid = |k: usize| -> Vec<(usize, u32, [f32; 4])> { + tr.iter().enumerate().filter_map(|(i, t)| { + let (s, p) = (t.at(k)?, t.paint_at(k)?); + (shows(s, rec.size) && s.flags & GROWING == 0 && s.op >= 0.5 && p.opaque() && area(&s.vis) >= 64.0).then_some((i, p.rank, s.vis)) + }).collect() + }; + let meets = |a: &[f32; 4], b: &[f32; 4]| area(&meet(a, b)) >= 64.0; + let mut out = Vec::new(); + let mut prev = solid(rec.start); + let mut flipped: HashSet<(usize, usize)> = HashSet::new(); + for k in rec.start + 1..n { + let cur = solid(k); + let before: HashMap<usize, (u32, [f32; 4])> = prev.iter().map(|&(i, r, v)| (i, (r, v))).collect(); + for (x, &(a, ra, va)) in cur.iter().enumerate() { + let Some(&(pa, pva)) = before.get(&a) else { continue }; + for &(b, rb, vb) in &cur[x + 1..] { + let Some(&(pb, pvb)) = before.get(&b) else { continue }; + if (ra > rb) == (pa > pb) || !meets(&va, &vb) || !meets(&pva, &pvb) || inside(&tr[a].path, &tr[b].path) || inside(&tr[b].path, &tr[a].path) { continue; } + if rec.inputs.iter().any(|x| x.0 + 1 >= k && x.0 <= k) || flipped.contains(&(a.min(b), a.max(b))) { continue; } + // Back within the window: the order it had returns. + let back = (k + 1..n.min(k + horizon + 1)).find(|&j| { + let (Some(p), Some(q)) = (tr[a].paint_at(j), tr[b].paint_at(j)) else { return false }; + (p.rank > q.rank) == (pa > pb) + }); + let kind = if back.is_some() { "flash" } else { "snap" }; + if kind == "snap" && rec.instant.get(k) == Some(&true) { continue; } + // Reported at the one whose place changed most. + let (who, other) = if (ra as i64 - pa as i64).abs() >= (rb as i64 - pb as i64).abs() { (a, b) } else { (b, a) }; + if marked(&tr[who], k, kind) { continue; } + let over = if who == a { ra > rb } else { rb > ra }; + flipped.insert((a.min(b), a.max(b))); + out.push((who, Finding { kind, element: short(&tr[who].path), frame: k, + detail: format!("z-order: paints {} {} in one frame{}", if over { "over" } else { "under" }, short(&tr[other].path), + back.map_or(String::new(), |j| format!(", and back at frame {j}"))) })); + } + } + prev = cur; + } + out +} + +/// Where two rects `[x, y, w, h]` overlap. +pub fn meet(a: &[f32; 4], b: &[f32; 4]) -> [f32; 4] { + let (x0, y0) = (a[0].max(b[0]), a[1].max(b[1])); + [x0, y0, ((a[0] + a[2]).min(b[0] + b[2]) - x0).max(0.0), ((a[1] + a[3]).min(b[1] + b[3]) - y0).max(0.0)] +} diff --git a/app/vendor/rune/crates/rune/src/motion_gate/check/raster.rs b/app/vendor/rune/crates/rune/src/motion_gate/check/raster.rs new file mode 100644 index 0000000..6cb5bd7 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/motion_gate/check/raster.rs @@ -0,0 +1,322 @@ +//! A coarse picture of the window each frame, for the region checks: the painter stream +//! (`Runtime::instances`) rasterized on the CPU into cells a few points across, or a GPU frame +//! averaged into the same cells. Each cell holds its mean colour in OKLab, over black. +//! +//! The raster is approximate where precision costs: corners are square, a glyph covers a share +//! of its quad, a shadow's blur is a three-step ramp and a radial gradient its mean colour. +//! Effects, backdrop blurs and inset shadows draw nothing. What it keeps is what a person sees +//! change: a surface's colour where it sits, through its layers' opacity. + +use crate::color::{Color, over, srgb_decode}; +use crate::render::{Instance, Kind}; + +/// Points per cell. +pub const CELL: f32 = 12.0; + +/// One frame's cells, row-major, in OKLab scaled by [`Q`]. +#[derive(Clone, Debug, PartialEq)] +pub struct Grid { + pub w: usize, + pub h: usize, + lab: Vec<[i16; 3]>, +} + +const Q: f32 = 8192.0; + +impl Grid { + fn new(w: usize, h: usize, cells: &[[f32; 4]]) -> Grid { + let lab = cells.iter().map(|&c| { + let [r, g, b, _] = over(c, [0.0, 0.0, 0.0, 1.0]); + let [l, a, bb, _] = Color { r, g, b, a: 1.0 }.to_oklab(); + [l, a, bb].map(|v| (v * Q).round().clamp(-32767.0, 32767.0) as i16) + }).collect(); + Grid { w, h, lab } + } + + pub fn lab(&self, i: usize) -> [f32; 3] { + self.lab[i].map(|v| v as f32 / Q) + } + + /// The colour of cell `i`, for evidence. + pub fn color(&self, i: usize) -> Color { + let [l, a, b] = self.lab(i); + Color::from_oklab([l, a, b, 1.0]) + } + + /// Cell `i`'s rect in points. + pub fn rect(&self, i: usize) -> [f32; 4] { + [(i % self.w) as f32 * CELL, (i / self.w) as f32 * CELL, CELL, CELL] + } +} + +/// Cells for a window `size` points across. +pub fn dims(size: (f32, f32)) -> (usize, usize) { + ((size.0 / CELL).ceil().max(1.0) as usize, (size.1 / CELL).ceil().max(1.0) as usize) +} + +/// One shape to cover cells with: `outer` less `hole` (device px boxes `[x0, y0, x1, y1]`) at +/// `density`, in premultiplied `color`, or running to `bottom` down `outer`. +struct Draw { + outer: [f32; 4], + hole: Option<[f32; 4]>, + density: f32, + color: [f32; 4], + bottom: Option<[f32; 4]>, +} + +fn boxed(r: [f32; 4]) -> [f32; 4] { + [r[0], r[1], r[0] + r[2], r[1] + r[3]] +} + +fn meet(a: [f32; 4], b: [f32; 4]) -> [f32; 4] { + [a[0].max(b[0]), a[1].max(b[1]), a[2].min(b[2]), a[3].min(b[3])] +} + +fn grow(b: [f32; 4], d: f32) -> [f32; 4] { + [b[0] - d, b[1] - d, b[2] + d, b[3] + d] +} + +fn overlap(a: [f32; 4], b: [f32; 4]) -> f32 { + let m = meet(a, b); + (m[2] - m[0]).max(0.0) * (m[3] - m[1]).max(0.0) +} + +fn lerp(a: [f32; 4], b: [f32; 4], t: f32) -> [f32; 4] { + std::array::from_fn(|i| a[i] + (b[i] - a[i]) * t) +} + +fn draws(q: &Instance, apron: bool) -> Vec<Draw> { + let outer = boxed(q.rect); + let solid = |color: [f32; 4], density: f32| Draw { outer, hole: None, density, color, bottom: None }; + let ring = |color: [f32; 4], width: f32, density: f32| Draw { outer, hole: Some(grow(outer, -width)), density, color, bottom: None }; + let mut out = Vec::new(); + match q.kind() { + Some(Kind::Rect) => { + out.push(solid(q.fill, 1.0)); + if q.params[0] > 0.0 { out.push(ring(q.border, q.params[0], 1.0)); } + } + Some(Kind::Gradient) => { + if q.params[0] > 0.0 { + out.push(Draw { bottom: Some(q.uv), ..ring(q.border, q.params[0], 1.0) }); + } else { + out.push(Draw { bottom: Some(q.uv), ..solid(q.fill, 1.0) }); + } + } + Some(Kind::Glyph) => { + // Off the pixel grid an icon samples one transparent texel past each edge, which it + // drops on the grid (`icon_inst`): leave that apron out, so it covers the same cells. + let t = if apron && q.uv[2] > 2.0 && q.uv[3] > 2.0 { [q.rect[2] / q.uv[2], q.rect[3] / q.uv[3]] } else { [0.0; 2] }; + let core = [outer[0] + t[0], outer[1] + t[1], outer[2] - t[0], outer[3] - t[1]]; + out.push(Draw { outer: core, ..solid(q.fill, 0.35) }); + } + Some(Kind::Radial) => { + let t = (q.params[3] % 2.0 - q.params[0] % 2.0).abs().clamp(0.0, 1.0); + out.push(solid(lerp(q.fill, q.border, 0.5), t)); + } + Some(Kind::Dashed) => { + out.push(Draw { bottom: Some(q.border), ..ring(q.fill, q.params[0], 0.5) }); + } + Some(Kind::Segment) => { + let [x0, y0, x1, y1] = q.radii; + let hw = q.params[0]; + let b = [x0.min(x1) - hw, y0.min(y1) - hw, x0.max(x1) + hw, y0.max(y1) + hw]; + let area = ((b[2] - b[0]) * (b[3] - b[1])).max(1e-3); + let len = ((x1 - x0).powi(2) + (y1 - y0).powi(2)).sqrt(); + out.push(Draw { outer: b, ..solid(q.fill, ((len + 2.0 * hw) * 2.0 * hw / area).min(1.0)) }); + } + Some(Kind::Triangle) => { + let [ax, ay, bx, by] = q.radii; + let (cx, cy) = (q.uv[0], q.uv[1]); + let b = [ax.min(bx).min(cx), ay.min(by).min(cy), ax.max(bx).max(cx), ay.max(by).max(cy)]; + out.push(Draw { outer: b, ..solid(q.fill, 0.5) }); + } + Some(Kind::Image) => { + let a = q.fill[3]; + out.push(solid([0.5 * a, 0.5 * a, 0.5 * a, a], 1.0)); + } + Some(Kind::Shadow) => { + let sigma = q.params[2].max(0.5); + let [u0, u1, u2, u3] = q.uv; + // A negative `uv.z` gives the band of the shadow this instance draws; any other `uv` a + // hole it leaves over the box casting it. + let window = if u2 < 0.0 { [q.rect[0] + u0, q.rect[1] + u1, q.rect[0] - u2, q.rect[1] + u3] } else { [f32::NEG_INFINITY, f32::NEG_INFINITY, f32::INFINITY, f32::INFINITY] }; + let hole = (u2 > 0.0).then(|| [q.rect[0] + u0, q.rect[1] + u1, q.rect[0] + u0 + u2, q.rect[1] + u1 + u3]); + for d in [-sigma, 0.0, sigma] { + out.push(Draw { outer: meet(grow(outer, d), window), hole, density: 1.0 / 3.0, color: q.fill, bottom: None }); + } + } + Some(Kind::Inset | Kind::Layer | Kind::LayerEnd | Kind::Effect | Kind::BackdropBlur) | None => {} + } + out +} + +/// One scope of the painter stream: its cells, opacity and clip. +struct Scope { + cells: Vec<[f32; 4]>, + opacity: f32, + clip: [f32; 4], +} + +/// Rasterizes `instances` (device pixels, `scale` per point) for a window `size` points across. +pub fn rasterize(instances: &[Instance], size: (f32, f32), scale: f32) -> Grid { + rasterize_with(instances, size, scale, &[], &Default::default()) +} + +/// [`rasterize`], knowing which glyphs are icons drawn through their apron (`apron_key`), and +/// how far a gliding glyph's ink sits down its quad (`TextSystem::glyph_shifts`). +pub(crate) fn rasterize_with(instances: &[Instance], size: (f32, f32), scale: f32, aprons: &[[u32; 3]], shifts: &std::collections::HashMap<[u32; 3], f32>) -> Grid { + let (w, h) = dims(size); + let px = CELL * scale; + let full = [f32::NEG_INFINITY, f32::NEG_INFINITY, f32::INFINITY, f32::INFINITY]; + let mut stack = vec![Scope { cells: vec![[0.0; 4]; w * h], opacity: 1.0, clip: full }]; + let cell_area = px * px; + for q in instances { + match q.kind() { + Some(Kind::Layer) => { + let clip = meet(stack.last().unwrap().clip, q.clip); + stack.push(Scope { cells: vec![[0.0; 4]; w * h], opacity: q.fill[3].clamp(0.0, 1.0), clip }); + continue; + } + Some(Kind::LayerEnd) => { + if stack.len() > 1 { + let top = stack.pop().unwrap(); + let parent = &mut stack.last_mut().unwrap().cells; + for (d, s) in parent.iter_mut().zip(&top.cells) { + *d = over(s.map(|v| v * top.opacity), *d); + } + } + continue; + } + _ => {} + } + let clip = meet(stack.last().unwrap().clip, q.clip); + let cells = &mut stack.last_mut().unwrap().cells; + let key = (q.kind() == Some(Kind::Glyph)).then(|| crate::runtime::apron_key(q)); + let apron = key.is_some_and(|k| aprons.contains(&k)); + let mut q = *q; + if let Some(dy) = key.and_then(|k| shifts.get(&k)) { q.rect[1] += dy; } + for d in draws(&q, apron) { + if d.color[3] <= 1e-4 || d.density <= 0.0 { continue; } + let b = meet(d.outer, clip); + if b[2] <= b[0] || b[3] <= b[1] { continue; } + let (cx0, cy0) = ((b[0] / px).floor().max(0.0) as usize, (b[1] / px).floor().max(0.0) as usize); + let (cx1, cy1) = (((b[2] / px).ceil() as usize).min(w), ((b[3] / px).ceil() as usize).min(h)); + let height = (d.outer[3] - d.outer[1]).max(1e-3); + for cy in cy0..cy1 { + for cx in cx0..cx1 { + let cell = [cx as f32 * px, cy as f32 * px, (cx + 1) as f32 * px, (cy + 1) as f32 * px]; + let mut cover = overlap(b, cell); + if let Some(hole) = d.hole { cover -= overlap(meet(hole, b), cell); } + let k = (cover / cell_area).clamp(0.0, 1.0) * d.density; + if k <= 0.0 { continue; } + let color = match d.bottom { + Some(bottom) => lerp(d.color, bottom, (((cell[1] + cell[3]) / 2.0 - d.outer[1]) / height).clamp(0.0, 1.0)), + None => d.color, + }; + let i = cy * w + cx; + cells[i] = over(color.map(|v| v * k), cells[i]); + } + } + } + } + while stack.len() > 1 { + let top = stack.pop().unwrap(); + let parent = &mut stack.last_mut().unwrap().cells; + for (d, s) in parent.iter_mut().zip(&top.cells) { *d = over(s.map(|v| v * top.opacity), *d); } + } + Grid::new(w, h, &stack[0].cells) +} + +/// A GPU frame `pw`×`ph` of 8-bit sRGB RGBA (straight alpha, as a readback gives it) averaged +/// into the cells of a window `size` points across. +pub fn from_pixels(rgba: &[u8], pw: u32, ph: u32, size: (f32, f32)) -> Grid { + let (w, h) = dims(size); + let (sx, sy) = (pw as f32 / size.0.max(1.0), ph as f32 / size.1.max(1.0)); + let lut: [f32; 256] = std::array::from_fn(|v| srgb_decode(v as f32 / 255.0)); + let mut cells = vec![[0.0f32; 4]; w * h]; + for cy in 0..h { + for cx in 0..w { + let (x0, y0) = ((cx as f32 * CELL * sx) as u32, (cy as f32 * CELL * sy) as u32); + let (x1, y1) = ((((cx + 1) as f32 * CELL * sx) as u32).min(pw), (((cy + 1) as f32 * CELL * sy) as u32).min(ph)); + // Every other pixel each way: a cell's mean needs no more. + let (mut sum, mut n) = ([0.0f32; 3], 0.0f32); + for y in (y0..y1).step_by(2) { + for x in (x0..x1).step_by(2) { + let p = ((y * pw + x) * 4) as usize; + let a = rgba[p + 3] as f32 / 255.0; + for c in 0..3 { sum[c] += lut[rgba[p + c] as usize] * a; } + n += 1.0; + } + } + if n > 0.0 { cells[cy * w + cx] = [sum[0] / n, sum[1] / n, sum[2] / n, 1.0]; } + } + } + Grid::new(w, h, &cells) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::render::{KIND_GLYPH, KIND_LAYER, KIND_LAYER_END, KIND_RECT}; + use bytemuck::Zeroable; + + fn rect(r: [f32; 4], c: Color, op: f32) -> Instance { + Instance { rect: r, fill: c.premul(op), params: [0.0, KIND_RECT, 0.0, 0.0], clip: [-1e9, -1e9, 1e9, 1e9], ..Instance::zeroed() } + } + + #[test] + fn a_rect_colours_the_cells_it_covers_through_its_layer() { + let red = Color { r: 1.0, g: 0.0, b: 0.0, a: 1.0 }; + let g = rasterize(&[rect([0.0, 0.0, 48.0, 24.0], red, 1.0)], (48.0, 48.0), 2.0); + assert_eq!((g.w, g.h), (4, 4)); + assert!((g.color(0).r - 1.0).abs() < 0.02 && g.color(15).r < 0.01); + let mut layer = Instance::zeroed(); + layer.params[1] = KIND_LAYER; + layer.fill[3] = 0.5; + layer.clip = [-1e9, -1e9, 1e9, 1e9]; + let mut end = Instance::zeroed(); + end.params[1] = KIND_LAYER_END; + let half = rasterize(&[layer, rect([0.0, 0.0, 96.0, 96.0], red, 1.0), end], (48.0, 48.0), 2.0); + assert!((half.color(0).r - 0.5).abs() < 0.02, "{:?}", half.color(0)); + } + + #[test] + fn an_icon_covers_the_same_cells_on_the_pixel_grid_as_off_it() { + // `icon_inst`: on the grid it loads its 16 texels directly; off it, the quad and its + // span grow by one transparent texel each side for filtering. + let glyph = |r: [f32; 4], span: f32| Instance { + rect: r, fill: Color::WHITE.premul(1.0), params: [0.0, KIND_GLYPH, 0.0, 1.0], uv: [7.0, 9.0, span, span], + clip: [-1e9, -1e9, 1e9, 1e9], ..Instance::zeroed() + }; + let (on, off) = (glyph([48.0, 24.0, 16.0, 16.0], 0.0), glyph([47.0, 23.0, 18.0, 18.0], 18.0)); + let aprons = [crate::runtime::apron_key(&off)]; + let (a, b) = (rasterize_with(&[on], (96.0, 72.0), 1.0, &aprons, &Default::default()), rasterize_with(&[off], (96.0, 72.0), 1.0, &aprons, &Default::default())); + let ink = |g: &Grid| (0..g.w * g.h).map(|i| g.lab(i)[0]).collect::<Vec<_>>(); + for (i, (a, b)) in ink(&a).iter().zip(ink(&b)).enumerate() { + assert!((a - b).abs() < 0.01, "cell {i}: {a} on the grid, {b} off it"); + } + // A zoomed text glyph's span is its own texels, with no apron: all of it is ink. + let whole = rasterize(&[off], (96.0, 72.0), 1.0); + assert!(ink(&whole) != ink(&b), "only an icon's apron is left out"); + } + + #[test] + fn a_gpu_frame_averages_into_the_same_cells() { + let mut px = vec![0u8; 24 * 24 * 4]; + for p in px.chunks_mut(4).take(24 * 12) { p.copy_from_slice(&[255, 255, 255, 255]); } + let g = from_pixels(&px, 24, 24, (24.0, 24.0)); + assert_eq!((g.w, g.h), (2, 2)); + assert!(g.lab(0)[0] > 0.99 && g.lab(3)[0] < 0.01); + } + + #[test] + fn from_pixels_srgb_decode_matches_inline_formula_bit_for_bit() { + let inline = |v: u8| { + let c = v as f32 / 255.0; + if c <= 0.04045 { c / 12.92 } else { ((c + 0.055) / 1.055).powf(2.4) } + }; + for v in 0..=255u8 { + assert_eq!(srgb_decode(v as f32 / 255.0).to_bits(), inline(v).to_bits(), "byte {v}"); + } + } +} diff --git a/app/vendor/rune/crates/rune/src/motion_gate/check/regions.rs b/app/vendor/rune/crates/rune/src/motion_gate/check/regions.rs new file mode 100644 index 0000000..f5871b7 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/motion_gate/check/regions.rs @@ -0,0 +1,190 @@ +//! The pixel backstop: `snap`, `flash` and `changes-twice` in the composited window, cell by +//! cell (see `raster`). It sees what no one element's own values show: a surface that drops out +//! one frame before what replaces it fades in, a layer's opacity, a clip, two elements trading +//! places. A region is reported at the top element painting it the frame before. +//! +//! Cells under what travels (an element moving on a frame and the next or last, the step in line +//! with its motion) at any frame of the event, a loop, a live binding or words that change (a +//! field's too, set without a key as dictation does) are skipped, as are Rune's own tooltip +//! (`El::help`) and cells an element marked with the matching `El::motion_intent` covers. A +//! region `snap` or `changes-twice` needs no element there to have changed on its frame (each +//! element's own rules report those) and a `snap` no `Tx::instant` commit; a region `flash` is +//! reported unless an element's `flash` or `flicker` there already is. + +use std::collections::{HashMap, HashSet}; + +use super::painted::marked; +use super::raster::{CELL, Grid}; +use super::series::{self, Tune, V}; +use super::{Finding, LIVE, Recording, Snap, Track, short}; + +const BLOCKED: u8 = 1; +const PULSE: u8 = 2; +const CUT: u8 = 4; +const STEP: u8 = 8; +const CHANGED: u8 = 16; + +fn moved(a: &Snap, b: &Snap) -> f32 { + let d = (0..4).map(|i| (a.rect[i] - b.rect[i]).abs().max((a.vis[i] - b.vis[i]).abs())).fold(0.0, f32::max); + d.max((a.scale - b.scale).abs() * 100.0) +} + +fn painted_differs(t: &Track, k: usize) -> bool { + match (t.paint_at(k - 1), t.paint_at(k)) { + (Some(a), Some(b)) => a.colors != b.colors || a.sizes != b.sizes || a.gradient_end != b.gradient_end || a.effect != b.effect || a.image != b.image, + _ => false, + } +} + +/// Per cell, on frame `k`: why a change there is no region's to report. +fn guard(rec: &Recording, loops: &HashSet<usize>, k: usize, (w, h): (usize, usize)) -> Vec<u8> { + let mut m = vec![0u8; w * h]; + let mut mark = |r: [f32; 4], pad: f32, bit: u8| { + if r[2] <= 0.0 && r[3] <= 0.0 { return; } + let (x0, y0) = (((r[0] - pad) / CELL).floor().max(0.0) as usize, ((r[1] - pad) / CELL).floor().max(0.0) as usize); + let (x1, y1) = ((((r[0] + r[2] + pad) / CELL).ceil().max(0.0) as usize).min(w), (((r[1] + r[3] + pad) / CELL).ceil().max(0.0) as usize).min(h)); + for y in y0..y1 { for x in x0..x1 { m[y * w + x] |= bit; } } + }; + for (i, t) in rec.tracks.iter().enumerate() { + let s = |j: usize| t.at(j); + let (pp, p, c, nx) = (k.checked_sub(2).and_then(s), s(k - 1), s(k), s(k + 1)); + let pad = [k - 1, k].iter().filter_map(|&j| t.paint_at(j)).map(|p| p.sizes[super::paint::S_SHADOW] + 3.0 * p.sizes[super::paint::S_BLUR]).fold(0.0, f32::max); + let span = |bit: u8, m: &mut dyn FnMut([f32; 4], f32, u8)| { + for s in [p, c, nx].into_iter().flatten() { m(s.vis, pad + CELL, bit); } + }; + let step = |a: Option<&Snap>, b: Option<&Snap>| a.zip(b).map_or(0.0, |(a, b)| moved(a, b)); + let (d0, d1, d2) = (step(pp, p), step(p, c), step(c, nx)); + let born_or_gone = p.is_some() != c.is_some(); + let faded = p.zip(c).is_some_and(|(a, b)| (a.op - b.op).abs() > 0.001); + // Any motion counts: pixel snapping draws a glide's last fractions of a point as an + // occasional whole-pixel step, which is the glide, not a region changing on its own. + if born_or_gone || d1 > 0.01 || faded || painted_differs(t, k) { + for s in [p, c].into_iter().flatten() { mark(s.vis, pad, CHANGED); } + } + let shown: Vec<&Snap> = [p, c].into_iter().flatten().filter(|s| s.op > 0.02).collect(); + if shown.is_empty() { continue; } + let around = d0.max(d2); + let travelling = d1 > 0.25 && around > 0.25 && d1 <= 3.0 * around + 2.0; + let words = t.words.iter().chain(&t.edits).any(|w| w.0 + 1 >= k && w.0 <= k + 1); + let live = shown.iter().any(|s| s.flags & LIVE != 0); + if travelling || words || live || loops.contains(&i) { span(BLOCKED, &mut mark); } + if marked(t, k, "flash") { span(PULSE, &mut mark); } + if marked(t, k, "snap") { span(CUT, &mut mark); } + if marked(t, k, "changes-twice") { span(STEP, &mut mark); } + } + for tip in [k - 1, k].iter().filter_map(|&j| rec.tips.get(j).copied().flatten()) { mark(tip, CELL, BLOCKED); } + m +} + +/// The region tune: cells' colours in OKLab, ΔE 0.08 a step of 1, as the element checks. +fn tune(hz: f64) -> Tune { + let t = super::painted::tune(hz); + Tune { still: 0.06, ..t } +} + +pub fn regions(rec: &Recording, loops: &HashSet<usize>, found: &[Finding]) -> Vec<Finding> { + let n = rec.frames; + let Some(g0) = rec.grids.iter().flatten().next() else { return Vec::new() }; + if rec.grids.len() < n || rec.grids.iter().any(Option::is_none) { return Vec::new(); } + let (w, h) = (g0.w, g0.h); + let grid = |k: usize| -> &Grid { rec.grids[k].as_deref().unwrap() }; + let tune = tune(rec.hz); + let v = |k: usize, i: usize| -> V { + let [l, a, b] = super::paint::toe(grid(k).lab(i)); + [l / 0.08, a / 0.08, b / 0.08, 0.0, 0.0, 0.0] + }; + // (kind, frame) → the cells that showed it, with each one's event. + let mut hits: HashMap<(&'static str, usize), Vec<(usize, series::Event)>> = HashMap::new(); + let floor = tune.flash.min(tune.snap); + for i in 0..w * h { + let changes = (1..n).any(|k| !std::ptr::eq(grid(k), grid(k - 1)) && series::dist(&v(k, i), &v(k - 1, i)) >= floor); + if !changes { continue; } + let vals: Vec<Option<V>> = (0..n).map(|k| (k >= rec.start).then(|| v(k, i))).collect(); + for e in series::events(&vals, &tune, &|_| 1.0) { + hits.entry((e.kind, e.k)).or_default().push((i, e)); + } + } + let input_in = |a: usize, b: usize| rec.inputs.iter().any(|x| x.0 >= a && x.0 <= b); + let mut guards: HashMap<usize, Vec<u8>> = HashMap::new(); + let mut keys: Vec<(&'static str, usize)> = hits.keys().copied().collect(); + keys.sort_by_key(|k| (k.1, k.0)); + let mut out = Vec::new(); + for key in keys { + let (kind, k) = key; + if k <= rec.start || input_in(k.saturating_sub(1), k) || rec.loads.iter().any(|&l| k >= l && k <= l + 2) { continue; } + if kind == "snap" && rec.instant.get(k) == Some(&true) { continue; } + // A cell is vetoed by what holds anywhere in its event's frames (something travelling + // across it shows out and back), and by an element changing there on the frame itself. + let frames = |e: &series::Event| e.span.0.max(1).min(k)..=e.span.1.max(k); + for (_, e) in &hits[&key] { + for j in frames(e) { guards.entry(j).or_insert_with(|| guard(rec, loops, j, (w, h))); } + } + let veto = BLOCKED | match kind { "flash" => PULSE, "snap" => CUT, _ => STEP }; + let vetoed = |i: usize, e: &series::Event| { + kind != "flash" && guards[&k][i] & CHANGED != 0 || frames(e).any(|j| guards[&j][i] & veto != 0) + }; + let cells: HashMap<usize, &series::Event> = hits[&key].iter().filter(|(i, e)| !vetoed(*i, e) && !(kind == "changes-twice" && input_in(e.span.0, e.span.1))).map(|(i, e)| (*i, e)).collect(); + // Connected regions of two cells or more. + let mut seen: HashSet<usize> = HashSet::new(); + let mut starts: Vec<usize> = cells.keys().copied().collect(); + starts.sort(); + for s in starts { + if !seen.insert(s) { continue; } + let mut region = vec![s]; + let mut q = vec![s]; + while let Some(c) = q.pop() { + let (x, y) = (c % w, c / w); + let near = [(x > 0).then(|| c - 1), (x + 1 < w).then(|| c + 1), (y > 0).then(|| c - w), (y + 1 < h).then(|| c + w)]; + for nb in near.into_iter().flatten() { + if cells.contains_key(&nb) && seen.insert(nb) { region.push(nb); q.push(nb); } + } + } + if region.len() < 2 { continue; } + let (x0, y0) = (region.iter().map(|c| c % w).min().unwrap(), region.iter().map(|c| c / w).min().unwrap()); + let (x1, y1) = (region.iter().map(|c| c % w).max().unwrap() + 1, region.iter().map(|c| c / w).max().unwrap() + 1); + let rect = [x0 as f32 * CELL, y0 as f32 * CELL, (x1 - x0) as f32 * CELL, (y1 - y0) as f32 * CELL]; + if explained(rec, found, kind, k, &rect) { continue; } + let worst = *region.iter().max_by(|a, b| cells[a].size.total_cmp(&cells[b].size)).unwrap(); + let e = cells[&worst]; + let hex = |j: usize| grid(j).color(worst).hex(); + let colors = match kind { + "snap" => format!("{} → {}", hex(k - 1), hex(k)), + _ => format!("{} → {} → {}", hex(e.span.0), hex(k), hex(e.span.1)), + }; + // The top surface there before or after, whichever changed on the frame. + let (was, now) = (top(rec, k - 1, &rect), top(rec, k, &rect)); + let changed = |t: &&Track| t.at(k - 1).map(|s| (s.rect, s.op)) != t.at(k).map(|s| (s.rect, s.op)) || painted_differs(t, k); + let who = was.filter(changed).or(now.filter(changed)).or(was).or(now).map_or_else(|| "window".into(), |t| short(&t.path)); + out.push(Finding { kind, element: format!("{who} (pixels)"), frame: k, + detail: format!("{} cells ({:.0}×{:.0} pt at {:.0},{:.0}) {colors} over frames {}–{}", region.len(), rect[2], rect[3], rect[0], rect[1], e.span.0, e.span.1) }); + } + } + out +} + +fn overlaps(a: &[f32; 4], b: &[f32; 4]) -> bool { + super::area(&super::painted::meet(a, b)) > 0.0 +} + +/// An element's own finding of the same nature covers this region around frame `k`. +fn explained(rec: &Recording, found: &[Finding], kind: &str, k: usize, rect: &[f32; 4]) -> bool { + let kinds: &[&str] = match kind { + "flash" => &["flash", "flicker"], + "snap" => &["snap", "fade-snap", "pop-in", "pop-out", "cut-exit", "jump", "offset-jump", "appear-then-jump", "text-swap"], + _ => &["changes-twice", "stop-start"], + }; + found.iter().filter(|f| kinds.contains(&f.kind) && f.frame + 1 >= k && f.frame <= k + 1).any(|f| { + rec.tracks.iter().filter(|t| short(&t.path) == f.element).any(|t| (k.saturating_sub(1)..=k).filter_map(|j| t.at(j)).any(|s| overlaps(&s.vis, rect))) + }) +} + +/// The element painting highest over the middle of `rect` on frame `k`. +fn top<'a>(rec: &'a Recording, k: usize, rect: &[f32; 4]) -> Option<&'a Track> { + let (cx, cy) = (rect[0] + rect[2] / 2.0, rect[1] + rect[3] / 2.0); + rec.tracks.iter().filter_map(|t| { + let (s, p) = (t.at(k)?, t.paint_at(k)?); + let paints = p.colors.iter().any(|c| c.a > 0.05) || p.image.is_some(); + let over = s.vis[0] <= cx && cx <= s.vis[0] + s.vis[2] && s.vis[1] <= cy && cy <= s.vis[1] + s.vis[3]; + (paints && over && s.op > 0.02).then_some((p.rank, t)) + }).max_by_key(|x| x.0).map(|x| x.1) +} diff --git a/app/vendor/rune/crates/rune/src/motion_gate/check/series.rs b/app/vendor/rune/crates/rune/src/motion_gate/check/series.rs new file mode 100644 index 0000000..bdaf9df --- /dev/null +++ b/app/vendor/rune/crates/rune/src/motion_gate/check/series.rs @@ -0,0 +1,226 @@ +//! The three discontinuities of one value over frames, shared by an element's painted +//! properties and a composited region of the window: +//! +//! - `snap`: it steps in one frame between frames that hold (nearly) still. +//! - `flash`: it steps out of a still state and within `horizon` frames comes back at least +//! halfway, or drifts away and snaps back. A one-frame blink, or a surface that drops out and +//! fades back in, is one. +//! - `changes-twice`: it changes, rests a moment, then carries on the same way, where one change +//! was meant. +//! +//! A cross-fade or a spring transition moves a little each frame and has no isolated step, so +//! none of them fires on it. + +/// A value at one frame, embedded so that Euclidean distance is how different it looks. +pub type V = [f32; 6]; + +pub fn dist(a: &V, b: &V) -> f32 { + a.iter().zip(b).map(|(x, y)| (x - y) * (x - y)).sum::<f32>().sqrt() +} + +/// How far `p` is from the straight path `a` → `b`. +pub fn off_path(p: &V, a: &V, b: &V) -> f32 { + let ab: Vec<f32> = (0..6).map(|i| b[i] - a[i]).collect(); + let len2: f32 = ab.iter().map(|x| x * x).sum(); + if len2 < 1e-12 { return dist(p, a); } + let t = ((0..6).map(|i| (p[i] - a[i]) * ab[i]).sum::<f32>() / len2).clamp(0.0, 1.0); + let q: V = std::array::from_fn(|i| a[i] + ab[i] * t); + dist(p, &q) +} + +/// Thresholds, in the units of the embedding, and windows in frames. +#[derive(Clone, Copy)] +pub struct Tune { + /// A one-frame step at least this big is a `snap`. + pub snap: f32, + /// An excursion at least this big is a `flash`, and each half of a `changes-twice`. + pub flash: f32, + /// A change under this between frames is holding still. + pub still: f32, + /// Frames a flash comes back within. + pub horizon: usize, + /// Frames of rest between the two halves of a `changes-twice`. + pub rest: (usize, usize), +} + +#[derive(Clone, Debug, PartialEq)] +pub struct Event { + pub kind: &'static str, + /// The frame it shows on: the step, or where the second change starts. + pub k: usize, + /// The frames it spans, first to last. + pub span: (usize, usize), + /// Its size in the embedding, before weighting. + pub size: f32, +} + +/// Every discontinuity in `vals` (`None` where there's no value). `weight(k)` scales what a +/// change at frame `k` counts for: how much of it shows. +pub fn events(vals: &[Option<V>], tune: &Tune, weight: &dyn Fn(usize) -> f32) -> Vec<Event> { + let n = vals.len(); + let d = |k: usize| -> Option<f32> { + if k == 0 || k >= n { return None; } + Some(dist(vals[k].as_ref()?, vals[k - 1].as_ref()?)) + }; + let still = |k: usize| d(k).is_none_or(|x| x < tune.still); + let mut out = Vec::new(); + let mut taken = vec![false; n]; + for k in 1..n { + let Some(step) = d(k) else { continue }; + let w = weight(k); + if w <= 0.0 || step * w < tune.flash.min(tune.snap) { continue; } + let (prev, next) = (d(k - 1).unwrap_or(0.0), d(k + 1).unwrap_or(0.0)); + let (a, b) = (vals[k - 1].unwrap(), vals[k].unwrap()); + // Out of a still state: where it rests within the horizon. + if prev < step / 4.0 { + let mut m = k + 1; + while m < n.min(k + tune.horizon + 1) && vals[m].is_some() && !(still(m) && still(m + 1)) { m += 1; } + let rest = vals[m.min(n - 1)].or(vals[m - 1]).unwrap(); + let e = off_path(&b, &a, &rest); + if e >= 0.5 * step && e * w >= tune.flash { + out.push(Event { kind: "flash", k, span: (k - 1, m.min(n - 1)), size: e }); + taken[k] = true; + if let Some(back) = (k + 1..=m.min(n - 1)).find(|&j| d(j).is_some_and(|x| x >= step / 2.0)) { taken[back] = true; } + continue; + } + } + // Into a still state after drifting from one: a snap back. + if next < step / 4.0 && !taken[k] { + let from = k.saturating_sub(tune.horizon).max(2); + if let Some(j) = (from..k - 1).rev().find(|&j| still(j) && still(j - 1) && vals[j].is_some()) + && (j + 1..k).all(|i| d(i).is_some_and(|x| x < step / 2.0)) + { + let s = vals[j].unwrap(); + let e = off_path(&a, &s, &b); + if e >= 0.5 * step && e * w >= tune.flash { + out.push(Event { kind: "flash", k, span: (j, k), size: e }); + taken[k] = true; + continue; + } + } + } + if !taken[k] && step * w >= tune.snap && prev < step / 4.0 && next < step / 4.0 { + out.push(Event { kind: "snap", k, span: (k - 1, k), size: step }); + } + } + // Motion segments: runs of frames that change, then the rest between them. + let mut segs: Vec<(usize, usize)> = Vec::new(); + let mut k = 1; + while k < n { + if d(k).is_none_or(|x| x < tune.still) { k += 1; continue; } + let a = k; + while k < n && d(k).is_some_and(|x| x >= tune.still) { k += 1; } + segs.push((a, k - 1)); + } + for w in segs.windows(2) { + let ((a1, b1), (a2, b2)) = (w[0], w[1]); + let rest = a2 - b1 - 1; + if rest < tune.rest.0 || rest > tune.rest.1 || (a1..=b2).any(|j| vals[j].is_none()) { continue; } + // The second change counts from where the rest ends: a slow tail that creeps on below + // `still` and then lands is one change. + let (v0, v1, r, v2) = (vals[a1 - 1].unwrap(), vals[b1].unwrap(), vals[a2 - 1].unwrap(), vals[b2].unwrap()); + let (first, second) = (dist(&v0, &v1), dist(&r, &v2)); + let wk = weight(a2); + if first * wk < tune.flash || second * wk < tune.flash { continue; } + let dot: f32 = (0..6).map(|i| (v1[i] - v0[i]) * (v2[i] - r[i])).sum(); + // Each half one step, so neither is a transition: those are `snap`'s alone. + if dot > 0.7 * first * second && !(taken[a2] || out.iter().any(|e| e.k == a1 || e.k == a2)) { + out.push(Event { kind: "changes-twice", k: a2, span: (a1 - 1, b2), size: first + second }); + } + } + out.sort_by_key(|e| e.k); + out +} + +#[cfg(test)] +mod tests { + use super::*; + + const TUNE: Tune = Tune { snap: 1.0, flash: 0.5, still: 0.01, horizon: 24, rest: (2, 15) }; + + fn run(xs: &[f32]) -> Vec<&'static str> { + let vals: Vec<Option<V>> = xs.iter().map(|&x| Some([x, 0.0, 0.0, 0.0, 0.0, 0.0])).collect(); + events(&vals, &TUNE, &|_| 1.0).into_iter().map(|e| e.kind).collect() + } + + fn ease(from: f32, to: f32, frames: usize) -> Vec<f32> { + (1..=frames).map(|i| { let t = i as f32 / frames as f32; from + (to - from) * t * t * (3.0 - 2.0 * t) }).collect() + } + + #[test] + fn a_step_between_still_frames_snaps() { + assert_eq!(run(&[0.0, 0.0, 0.0, 2.0, 2.0, 2.0]), ["snap"]); + } + + #[test] + fn a_transition_neither_snaps_nor_flashes() { + let mut xs = vec![0.0; 4]; + xs.extend(ease(0.0, 2.0, 12)); + xs.extend([2.0; 6]); + assert!(run(&xs).is_empty(), "{:?}", run(&xs)); + } + + #[test] + fn a_cross_fade_through_a_dip_is_no_flash() { + // Two layers trading places: the mix dips a little and comes back, smoothly. + let xs: Vec<f32> = (0..30).map(|k| if k < 4 { 1.0 } else { 1.0 - 0.3 * ((k - 4) as f32 / 20.0 * std::f32::consts::PI).sin().max(0.0) }).collect(); + assert!(run(&xs).is_empty(), "{:?}", run(&xs)); + } + + #[test] + fn dropping_out_and_fading_back_flashes() { + let mut xs = vec![2.0; 4]; + xs.push(0.0); + xs.extend(ease(0.0, 2.0, 12)); + xs.extend([2.0; 6]); + assert_eq!(run(&xs), ["flash"]); + } + + #[test] + fn a_one_frame_blink_flashes_once() { + assert_eq!(run(&[1.0, 1.0, 1.0, 0.0, 1.0, 1.0, 1.0]), ["flash"]); + } + + #[test] + fn drifting_away_and_snapping_back_flashes() { + let mut xs = vec![0.0; 4]; + xs.extend(ease(0.0, 1.5, 10)); + xs.extend([0.0; 6]); + assert_eq!(run(&xs), ["flash"]); + } + + #[test] + fn two_steps_the_same_way_snap_each_and_no_more() { + assert_eq!(run(&[0.0, 0.0, 1.0, 1.0, 1.0, 1.0, 2.0, 2.0, 2.0]), ["snap", "snap"]); + } + + #[test] + fn a_transition_that_rests_and_carries_on_changes_twice() { + let mut xs = vec![0.0; 3]; + xs.extend(ease(0.0, 1.0, 8)); + xs.extend([1.0; 4]); + xs.extend(ease(1.0, 2.0, 8)); + xs.extend([2.0; 4]); + assert_eq!(run(&xs), ["changes-twice"]); + } + + #[test] + fn a_tail_that_creeps_then_lands_changes_once() { + let mut xs = vec![0.0; 3]; + xs.extend(ease(0.0, 1.0, 8)); + xs.extend((1..=14).map(|i| 1.0 + 0.009 * i as f32)); + let last = *xs.last().unwrap(); + xs.extend([last + 0.4; 6]); + assert!(run(&xs).is_empty(), "{:?}", run(&xs)); + } + + #[test] + fn going_there_and_back_later_changes_once_each_way() { + let mut xs = vec![0.0; 3]; + xs.extend(ease(0.0, 1.0, 8)); + xs.extend([1.0; 4]); + xs.extend(ease(1.0, 0.0, 8)); + xs.extend([0.0; 4]); + assert!(run(&xs).is_empty(), "{:?}", run(&xs)); + } +} diff --git a/app/vendor/rune/crates/rune/src/motion_gate/check_tests.rs b/app/vendor/rune/crates/rune/src/motion_gate/check_tests.rs new file mode 100644 index 0000000..ea9d8b9 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/motion_gate/check_tests.rs @@ -0,0 +1,259 @@ +use super::*; + +fn rec(tracks: Vec<(&str, Vec<(usize, [f32; 4], f32)>)>, frames: usize) -> Recording { + let mut r = Recording::new((1000.0, 1000.0), 120.0); + r.frames = frames; + for (path, fs) in tracks { + let i = r.track(path, None); + r.tracks[i].frames = fs.into_iter().map(|(k, rect, op)| (k, Snap { rect, vis: rect, op, scale: 1.0, flags: INK, phase: f32::NAN, scrolled: [0.0; 2] })).collect(); + } + r +} + +fn kinds(r: &Recording) -> Vec<&'static str> { + check(r).into_iter().map(|f| f.kind).collect() +} + +#[test] +fn a_spring_passes_and_a_snap_jumps() { + let smooth: Vec<_> = (0..60).map(|k| { let p = 1.0 - (-(k as f32) / 8.0).exp(); (k, [0.0, 300.0 - 200.0 * p, 100.0, 40.0], 1.0) }).collect(); + assert!(kinds(&rec(vec![("a", smooth)], 60)).is_empty()); + let snap: Vec<_> = (0..60).map(|k| (k, [0.0, if k < 30 { 300.0 } else { 100.0 }, 100.0, 40.0], 1.0)).collect(); + assert_eq!(kinds(&rec(vec![("a", snap)], 60)), ["jump"]); + // Gliding at 4 pt a frame, then lurching to 20. + let mut y = 0.0; + let lurch: Vec<_> = (0..60).map(|k| { if k > 0 && k < 40 { y += if k < 20 { 4.0 } else { 20.0 } } (k, [0.0, y, 100.0, 40.0], 1.0) }).collect(); + assert_eq!(kinds(&rec(vec![("a", lurch)], 60)), ["jerk"]); +} + +/// Climbing 3 pt per word, a word every 0.3 s: as kicks that glide out and rest, or one glide. +#[test] +fn a_climb_in_kicks_is_stop_start_and_a_steady_one_passes() { + let n = 600; + // Drawn rects move in 1/128 pt steps. + let path = |y: fn(usize) -> f32| -> Vec<_> { (0..n).map(|k| (k, [0.0, ((500.0 - y(k)) * 128.0).round() / 128.0, 100.0, 40.0], 1.0)).collect() }; + let mut kicks = rec(vec![("reply", path(|k| 3.0 * (k / 36) as f32 + 3.0 * (1.0 - (-((k % 36) as f32) / 3.0).exp())))], n); + for k in (0..n).step_by(36) { kicks.inputs.push((k, "event".into())); } + assert!(kinds(&kicks).contains(&"stop-start"), "{:?}", kinds(&kicks)); + let steady = rec(vec![("reply", path(|k| k.min(480) as f32 / 12.0))], n); + assert!(kinds(&steady).is_empty(), "{:?}", kinds(&steady)); + // The last of a glide creeping in under a pixel a frame rests between steps, but isn't kicking. + let creep = rec(vec![("reply", path(|k| 3.0 - 3.0 * (-(k as f32) / 240.0).exp()))], n); + assert!(!kinds(&creep).contains(&"stop-start"), "{:?}", kinds(&creep)); + // Each kick answering a hand on the app is that hand's. + for i in &mut kicks.inputs { i.1 = "tap".into(); } + assert!(!kinds(&kicks).contains(&"stop-start")); +} + +#[test] +fn an_instant_toggle_is_reported_where_the_height_changed() { + let group: Vec<_> = (0..60).map(|k| (k, [0.0, 100.0, 100.0, if k < 30 { 28.0 } else { 84.0 }], 1.0)).collect(); + let below: Vec<_> = (0..60).map(|k| (k, [0.0, if k < 30 { 128.0 } else { 184.0 }, 100.0, 40.0], 1.0)).collect(); + let mut r = rec(vec![("g", group), ("b", below)], 60); + assert_eq!(kinds(&r), ["jump", "jump"], "with no input, the row below jumps on its own"); + r.inputs.push((30, "tap".into())); + let f = check(&r); + assert_eq!(f.iter().map(|f| (f.kind, f.element.as_str())).collect::<Vec<_>>(), [("jump", "g")]); +} + +#[test] +fn pops_overshoot_reversal_and_flicker() { + let pop: Vec<_> = (20..60).map(|k| (k, [0.0, 0.0, 100.0, 40.0], 1.0)).collect(); + assert_eq!(kinds(&rec(vec![("a", pop)], 60)), ["pop-in"]); + // A row mounting a sliver tall that opens slowly grows in. + let opens: Vec<_> = (20..60).map(|k| (k, [0.0, 0.0, 100.0, 0.4 + 0.1 * (k - 20) as f32], 1.0)).collect(); + assert!(kinds(&rec(vec![("a", opens)], 60)).is_empty()); + let gone: Vec<_> = (0..20).map(|k| (k, [0.0, 0.0, 100.0, 40.0], 1.0)).collect(); + assert_eq!(kinds(&rec(vec![("a", gone)], 60)), ["pop-out"]); + let over: Vec<_> = (0..60).map(|k| { let t = k as f32 / 8.0; (k, [0.0, 100.0 + 100.0 * (1.0 - (-t).exp() * (t * 1.5).cos()), 100.0, 40.0], 1.0) }).collect(); + let k = kinds(&rec(vec![("a", over)], 60)); + assert!(k.contains(&"overshoot"), "{k:?}"); + let dogleg: Vec<_> = (0..60).map(|k| { let t = k as f32 / 59.0; (k, [0.0, 100.0 - 40.0 * (t * 3.0).min(1.0) * (1.0 - t) * 4.0 + 200.0 * t * t, 100.0, 40.0], 1.0) }).collect(); + let k = kinds(&rec(vec![("a", dogleg)], 60)); + assert!(k.contains(&"reversal"), "{k:?}"); + let blink: Vec<_> = (0..60).map(|k| (k, [0.0, 0.0, 100.0, 40.0], if (20..24).contains(&k) { 0.3 } else { 1.0 })).collect(); + assert_eq!(kinds(&rec(vec![("a", blink.clone())], 60)), ["flicker"]); + // A container whose contents are all hidden draws nothing as it dips. + let mut r = rec(vec![("a", blink)], 60); + for f in &mut r.tracks[0].frames { f.1.flags = 0; } + assert!(kinds(&r).is_empty()); +} + +#[test] +fn words_that_swap_in_place_are_a_text_swap_but_a_ticking_count_is_not() { + let still: Vec<(usize, [f32; 4], f32)> = (0..60).map(|k| (k, [0.0, 0.0, 100.0, 20.0], 1.0)).collect(); + let with = |words: &[(usize, &str)]| { + let mut r = rec(vec![("a", still.clone())], 60); + r.tracks[0].words = words.iter().map(|(k, w)| (*k, w.to_string())).collect(); + kinds(&r) + }; + assert_eq!(with(&[(0, "Read backoff.ts"), (30, "Grep retryBudget")]), ["text-swap"]); + assert!(with(&[(0, "9s"), (30, "10s")]).is_empty(), "a clock ticks"); + assert!(with(&[(0, "Looks"), (30, "Looks right")]).is_empty(), "streaming words grow"); + assert!(with(&[(0, "run \u{2066}t\u{2069}"), (30, "run \u{2066}th\u{2069}")]).is_empty(), "words grow inside an isolate"); + assert_eq!(with(&[(0, "run \u{2066}test\u{2069}"), (30, "run \u{2066}build\u{2069}")]), ["text-swap"]); + // A streaming link's box widens with its next word. + let link: Vec<_> = (0..60).map(|k| (k, [0.0, 0.0, if k < 30 { 40.0 } else { 85.0 }, 20.0], 1.0)).collect(); + let mut r = rec(vec![("a", link)], 60); + assert_eq!(kinds(&r), ["jump"]); + r.tracks[0].words = vec![(0, "health".into()), (30, "health check".into())]; + assert!(kinds(&r).is_empty(), "{:?}", kinds(&r)); +} + +#[test] +fn a_loop_that_restarts_jumps_and_a_finished_run_goes_quiet() { + let still: Vec<(usize, [f32; 4], f32)> = (0..120).map(|k| (k, [0.0, 0.0, 100.0, 20.0], 1.0)).collect(); + let looping = |restart: Option<usize>| { + let mut r = rec(vec![("a", still.clone())], 120); + for (k, f) in r.tracks[0].frames.iter_mut() { + let t = restart.filter(|&at| *k >= at).map_or(*k, |at| *k - at); + f.phase = (t as f32 / 144.0).rem_euclid(1.0); + } + r + }; + // Wrapping round from 1 to 0 is a usual step. + assert!(kinds(&looping(None)).is_empty()); + assert_eq!(kinds(&looping(Some(60))), ["loop-jump"]); + let mut r = rec(vec![("a", (0..300).map(|k| (k, [0.0, 0.0, 100.0, 20.0], 1.0)).collect())], 300); + r.quiet_from = Some(100); + r.awake = (0..300).map(|k| k < 180).collect(); + assert!(kinds(&r).is_empty(), "settling within a second is fine"); + r.awake[260] = true; + assert_eq!(kinds(&r), ["wakes-after-end"]); +} + +#[test] +fn a_row_that_loses_its_key_remounts_but_one_that_becomes_another_element_does_not() { + let fade = |from: usize, to: usize, out: bool| -> Vec<(usize, [f32; 4], f32)> { + (from..to).map(|k| (k, [0.0, 0.0, 300.0, 20.0], if out && k >= 30 { 1.0 - (k - 29) as f32 / 10.0 } else if !out { ((k - 29) as f32 / 10.0).min(1.0) } else { 1.0 })).collect() + }; + let found = |old: &str, new: &str| { + let mut r = rec(vec![(old, fade(0, 40, true)), (new, fade(30, 60, false))], 60); + for f in r.tracks[0].frames.iter_mut().filter(|f| f.0 >= 30) { f.1.flags |= EXITING; } + for t in &mut r.tracks { t.text = Some("Got it, I'll look.".into()); } + kinds(&r).contains(&"remount") + }; + assert!(found("list/row-0/label", "list/row-1/label")); + assert!(!found("tray/pending/label", "list/row/text")); +} + +#[test] +fn a_pinned_scroll_that_stops_following_is_unpinned_unless_someone_scrolled() { + let view: Vec<_> = (0..60).map(|k| (k, [0.0, 0.0, 100.0, 200.0], 1.0)).collect(); + let grows = |follows: bool| -> Vec<(usize, [f32; 4], f32)> { + (0..60usize).map(|k| { let h = 400.0 + k.saturating_sub(30) as f32; (k, [0.0, if follows { 200.0 - h } else { -200.0 }, 100.0, h], 1.0) }).collect() + }; + let unpinned = |follows: bool, input: Option<&str>| { + let mut r = rec(vec![("scroll", view.clone()), ("scroll/content", grows(follows))], 60); + r.tracks[1].parent = Some(0); + for f in &mut r.tracks[1].frames { f.1.vis = [0.0, 0.0, 100.0, 200.0]; } + r.inputs.extend(input.map(|what| (31, what.to_owned()))); + kinds(&r).contains(&"unpinned") + }; + assert!(!unpinned(true, None)); + assert!(unpinned(false, None)); + assert!(unpinned(false, Some("event (3 left)")), "data arriving isn't a hand on the scroll"); + assert!(!unpinned(false, Some("scroll up"))); +} + +#[test] +fn a_second_sibling_under_one_key_shows_twice() { + let row = |y: f32| -> Vec<(usize, [f32; 4], f32)> { (0..60).map(|k| (k, [0.0, y, 100.0, 20.0], 1.0)).collect() }; + assert!(kinds(&rec(vec![("list/row-7", row(0.0))], 60)).is_empty()); + assert_eq!(kinds(&rec(vec![("list/row-7", row(0.0)), ("list/row-7#dup1", row(20.0))], 60)), ["twice"]); +} + +#[test] +fn a_flight_that_lands_under_a_clip_lands_unseen() { + let flight: Vec<_> = (0..60).map(|k| { + let t = (k as f32 / 30.0).min(1.0); + (k, [0.0, 100.0 + 300.0 * t * t * (3.0 - 2.0 * t), 100.0, 40.0], 1.0) + }).collect(); + let landed = |clipped: bool, moved: bool| { + let fs = if moved { flight.clone() } else { (0..60).map(|k| (k, [0.0, 400.0, 100.0, 40.0], 1.0)).collect() }; + let mut r = rec(vec![("flight", fs)], 60); + for f in r.tracks[0].frames.iter_mut().filter(|f| clipped && f.0 >= 40) { f.1.vis = [0.0, 0.0, 0.0, 0.0]; } + kinds(&r) + }; + assert!(landed(false, true).is_empty(), "{:?}", landed(false, true)); + assert_eq!(landed(true, true), ["lands-unseen"]); + assert!(landed(true, false).is_empty(), "a still element a clip covers didn't fly there"); +} + +#[test] +fn where_counts_roll_a_ticking_count_is_a_text_swap_but_a_rolling_label_is_not() { + let still: Vec<(usize, [f32; 4], f32)> = (0..60).map(|k| (k, [0.0, 0.0, 100.0, 20.0], 1.0)).collect(); + let mut r = rec(vec![("count", still.clone())], 60); + r.tracks[0].words = vec![(0, "9s".into()), (30, "10s".into())]; + assert!(kinds(&r).is_empty()); + r.counts_roll = true; + assert_eq!(kinds(&r), ["text-swap"], "a clock that snaps instead of rolling"); + // The label over its rolling glyphs reads "9s" then "10s" as its digits roll. + let glyph = r.track("count/digit-1", Some(0)); + r.tracks[glyph].frames = (0..60).map(|k| (k, Snap { rect: [0.0, 0.0, 8.0, 20.0], vis: [0.0, 0.0, 8.0, 20.0], op: 1.0, scale: 1.0, flags: INK, phase: f32::NAN, scrolled: [0.0; 2] })).collect(); + assert!(kinds(&r).is_empty()); +} + +#[test] +fn motion_inside_a_scroll_is_judged_against_the_scroll() { + // A list follows its growing end, carrying its content up 2 pt a frame, while a node in it + // moves on its own. `scrolled` is how far the scroll carries the node. + let offset = |k: usize| 2.0 * k as f32; + let run = |own: &dyn Fn(usize) -> f32, flags: u8, told: bool| { + let fs: Vec<_> = (0..60).map(|k| (k, [0.0, 300.0 + own(k) - offset(k), 100.0, 40.0], 1.0)).collect(); + let mut r = rec(vec![("list/node", fs)], 60); + for (k, f) in &mut r.tracks[0].frames { + f.flags |= flags; + if told { f.scrolled = [0.0, offset(*k)]; } + } + kinds(&r) + }; + // Gliding down 60 pt: fast at first, so on screen it falls, then rises with the scroll. + let glide = |k: usize| 60.0 * (1.0 - (-(k as f32) / 8.0).exp()); + assert_eq!(run(&glide, 0, false), ["reversal"], "on screen the glide and the scroll turn back"); + assert!(run(&glide, 0, true).is_empty(), "against the scroll it is one glide"); + assert!(run(&glide, SCROLLING, true).is_empty()); + // Wobbling in place: on screen the scroll's 2 pt a frame hides the turns. + let wobble = |k: usize| 2.5 * (k as f32 * 0.6).sin(); + assert!(run(&wobble, 0, false).is_empty(), "on screen it only ever rises"); + assert_eq!(run(&wobble, 0, true), ["jiggle"], "against the scroll it wobbles"); + assert_eq!(run(&wobble, SCROLLING, true), ["jiggle"], "a scroll that moves doesn't excuse it"); +} + +/// A list's content, scrolled into a 400 pt viewport at the window's top, and rows in it: each +/// track's rect per frame, its visible part the rect cut to the viewport. +fn scrolled_list(tracks: Vec<(&str, Vec<[f32; 4]>)>) -> Recording { + let mut r = Recording::new((1000.0, 1000.0), 120.0); + r.frames = 60; + for (path, rects) in tracks { + let parent = path.rsplit_once('/').map(|(p, _)| r.tracks.iter().position(|t| t.path == p).unwrap()); + let i = r.track(path, parent); + r.tracks[i].frames = rects.into_iter().enumerate().map(|(k, rect)| { + let (y0, y1) = (rect[1].max(0.0), (rect[1] + rect[3]).min(400.0)); + let vis = [rect[0], y0, rect[2], (y1 - y0).max(0.0)]; + (k, Snap { rect, vis, op: 1.0, scale: 1.0, flags: INK, phase: f32::NAN, scrolled: [0.0, 600.0] }) + }).collect(); + } + r +} + +#[test] +fn a_jump_is_what_shows_jumping() { + let at = |k: usize, a: [f32; 4], b: [f32; 4]| if k < 30 { a } else { b }; + let still = |rect: [f32; 4]| vec![rect; 60]; + // A row teleported 100 pt while it shows, the list still. + let list = still([0.0, -600.0, 100.0, 2000.0]); + let row: Vec<_> = (0..60).map(|k| at(k, [0.0, 100.0, 100.0, 40.0], [0.0, 200.0, 100.0, 40.0])).collect(); + assert_eq!(kinds(&scrolled_list(vec![("list", list.clone()), ("list/row", row)])), ["jump"]); + // A fold drops 900 pt above the window with the offset: the content's top and height step, + // its visible part and the rows that show stay put. + let content: Vec<_> = (0..60).map(|k| at(k, [0.0, -1100.0, 100.0, 1500.0], [0.0, -200.0, 100.0, 600.0])).collect(); + let fold: Vec<_> = (0..60).map(|k| at(k, [0.0, -900.0, 100.0, 1200.0], [0.0, 0.0, 100.0, 300.0])).collect(); + let shown = |y: f32| still([0.0, y, 100.0, 40.0]); + let r = scrolled_list(vec![("list", content), ("list/fold", fold), ("list/fold/a", shown(100.0)), ("list/fold/b", shown(200.0)), ("list/c", shown(320.0))]); + assert!(kinds(&r).is_empty(), "{:?}", check(&r)); + // The content jumps 100 pt and the rows that show jump with it: one offset jump. + let content: Vec<_> = (0..60).map(|k| at(k, [0.0, -600.0, 100.0, 2000.0], [0.0, -500.0, 100.0, 2000.0])).collect(); + let row = |y: f32| (0..60).map(|k| at(k, [0.0, y, 100.0, 40.0], [0.0, y + 100.0, 100.0, 40.0])).collect::<Vec<_>>(); + assert_eq!(kinds(&scrolled_list(vec![("list", content), ("list/a", row(0.0)), ("list/b", row(100.0)), ("list/c", row(200.0))])), ["offset-jump"]); +} diff --git a/app/vendor/rune/crates/rune/src/motion_gate/gate.rs b/app/vendor/rune/crates/rune/src/motion_gate/gate.rs new file mode 100644 index 0000000..179adf4 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/motion_gate/gate.rs @@ -0,0 +1,229 @@ +//! Running an app's cells and reporting their findings against its allowlist. + + +use super::check::{Finding, RULES, Recording, check, dump, sheet}; + +/// A finding that is the design: `(kind, element contains, cell contains, why)`, the first three +/// matched as substrings ("" for any). Every row needs its reason. +pub type Allow = (&'static str, &'static str, &'static str, &'static str); + +/// Builds and records one cell. +pub type Job = Box<dyn FnOnce() -> Recording + Send>; + +/// One cell's findings. +pub struct Cell { + pub name: String, + pub findings: Vec<Finding>, + pub frames: usize, + /// Fewer than 10 frames were recorded: its setup didn't apply. + pub skipped: bool, +} + +/// An allowlist row: a finding that is the design. `kind` matches exactly ("" for any), +/// `element` as a substring, and `cell` as a substring or any of several joined by `|` +/// (`"island-auto|island-click"`). `max` caps how many findings it covers in a run, so a +/// row written for one finding doesn't quietly cover the next ten. Prefer an +/// `El::motion_intent` mark where the motion is written to a row here. +#[derive(Clone, Copy, Debug)] +pub struct AllowRow { + pub kind: &'static str, + pub element: &'static str, + pub cell: &'static str, + pub why: &'static str, + pub max: Option<usize>, +} + +impl AllowRow { + pub const fn new(kind: &'static str, element: &'static str, cell: &'static str, why: &'static str) -> Self { + AllowRow { kind, element, cell, why, max: None } + } + + /// Covers at most `n` findings in a run; the rest fail. + pub const fn max(mut self, n: usize) -> Self { + self.max = Some(n); + self + } + + pub fn matches(&self, f: &Finding, cell: &str) -> bool { + (self.kind.is_empty() || f.kind == self.kind) && f.element.contains(self.element) && self.in_cell(cell) + } + + fn in_cell(&self, cell: &str) -> bool { + self.cell.split('|').any(|c| cell.contains(c)) + } +} + +impl From<Allow> for AllowRow { + fn from((kind, element, cell, why): Allow) -> Self { + AllowRow::new(kind, element, cell, why) + } +} + +/// Why `f` in `cell` is allowed, if a row of `allow` matches it. +pub fn allowed(allow: &[Allow], f: &Finding, cell: &str) -> Option<&'static str> { + allow.iter().map(|&a| AllowRow::from(a)).find(|r| r.matches(f, cell)).map(|r| r.why) +} + +fn rows(allow: &[Allow]) -> Vec<AllowRow> { + allow.iter().map(|&a| a.into()).collect() +} + +/// Runs every cell whose name contains `filter`, in parallel on large stacks, and checks each +/// recording, in the order given. `MOTION_GATE_DUMP` and `MOTION_GATE_SHEET` write evidence for +/// the cell they name. +pub fn run(cells: Vec<(String, Job)>, filter: &str) -> Vec<Cell> { + let jobs: Vec<(usize, (String, Job))> = cells.into_iter().filter(|c| c.0.contains(filter)).enumerate().collect(); + let jobs = std::sync::Mutex::new(jobs); + let out = std::sync::Mutex::new(Vec::new()); + #[cfg(target_arch = "wasm32")] + { + for (i, (name, job)) in jobs.into_inner().unwrap() { + let rec = job(); + evidence(&name, &rec, rune_core::env::var("MOTION_GATE_OUT")); + let cell = Cell { skipped: rec.frames < 10, frames: rec.frames, findings: check(&rec), name }; + out.lock().unwrap().push((i, cell)); + } + } + #[cfg(not(target_arch = "wasm32"))] + { + let threads = std::thread::available_parallelism().map_or(4, |n| n.get()).min(12); + std::thread::scope(|scope| { + for _ in 0..threads { + std::thread::Builder::new() + .stack_size(64 << 20) + .spawn_scoped(scope, || loop { + let Some((i, (name, job))) = jobs.lock().unwrap().pop() else { break }; + let rec = job(); + evidence(&name, &rec, rune_core::env::var("MOTION_GATE_OUT")); + let cell = Cell { skipped: rec.frames < 10, frames: rec.frames, findings: check(&rec), name }; + out.lock().unwrap().push((i, cell)); + }) + .unwrap(); + } + }); + } + let mut cells = out.into_inner().unwrap(); + cells.sort_by_key(|c| c.0); + cells.into_iter().map(|c| c.1).collect() +} + +/// Writes the evidence `MOTION_GATE_DUMP` and `MOTION_GATE_SHEET` ask for when their cell part +/// is `cell` or empty, beside `out`. +pub(crate) fn evidence(cell: &str, rec: &Recording, out: Option<String>) { + if let Some(spec) = rune_core::env::var("MOTION_GATE_DUMP") { + let mut p = spec.split('|'); + if let (Some(c), Some(path)) = (p.next(), p.next()) + && (c.is_empty() || c == cell) + { + let from = p.next().and_then(|x| x.parse().ok()).unwrap_or(0); + let to = p.next().and_then(|x| x.parse().ok()).unwrap_or(usize::MAX); + let text = dump(rec, path, from, to); + match &out { + Some(out) => std::fs::write(format!("{out}.dump"), text).unwrap(), + None => eprint!("{text}"), + } + } + } + #[cfg(not(target_arch = "wasm32"))] + if let Some(spec) = rune_core::env::var("MOTION_GATE_SHEET") { + let mut p = spec.split('|'); + if let (Some(c), Some(Ok(at))) = (p.next(), p.next().map(str::parse)) + && (c.is_empty() || c == cell) + { + let out = out.unwrap_or_else(|| std::env::temp_dir().join("motion-gate").display().to_string()); + sheet(rec, at, p.next().unwrap_or("")).save(format!("{out}.sheet.png")).unwrap(); + } + } +} + +/// What a run found. +pub struct Report { + /// The summary line, then a line per finding that isn't allowed (and per allowed one, when + /// asked), then what each kind found means. + pub text: String, + pub summary: String, + /// Findings that aren't allowed, plus skipped cells. + pub failing: usize, + pub allowed: usize, + /// Allow rows that matched nothing in the cells they scope. + pub unused: usize, +} + +/// Reads `cells` against `allow`; `list_allowed` lists allowed findings too. +pub fn report(cells: &[Cell], allow: &[Allow], list_allowed: bool, secs: f32) -> Report { + report_rows(cells, &rows(allow), list_allowed, secs) +} + +/// [`report`] with [`AllowRow`]s. A row covers findings up to its `max`; past it they fail. +/// Rows that matched nothing in the cells they scope are listed as unused. +pub fn report_rows(cells: &[Cell], rows: &[AllowRow], list_allowed: bool, secs: f32) -> Report { + report_with(cells, rows, list_allowed, true, secs) +} + +/// `whole`: every cell ran, so a row that matched nothing is worth listing. +fn report_with(cells: &[Cell], rows: &[AllowRow], list_allowed: bool, whole: bool, secs: f32) -> Report { + let mut used = vec![0usize; rows.len()]; + let mut text = String::new(); + let (mut failing, mut allowed_n) = (0, 0); + let mut failed_kinds: Vec<&str> = Vec::new(); + for c in cells { + if c.skipped { + failing += 1; + text += &format!("SKIP {} (its setup didn't apply)\n", c.name); + } + for f in &c.findings { + let row = rows.iter().position(|r| r.matches(f, &c.name)); + let over = row.and_then(|i| { + used[i] += 1; + rows[i].max.filter(|&m| used[i] > m) + }); + match (row, over) { + (Some(i), None) => { + allowed_n += 1; + if list_allowed { + text += &format!("allowed {} in {} ({})\n", f, c.name, rows[i].why); + } + } + _ => { + failing += 1; + failed_kinds.push(f.kind); + let past = over.map_or(String::new(), |m| format!(" (past its allow row's max of {m})")); + text += &format!("{} in {}{past}\n", f, c.name); + } + } + } + } + let ran = |r: &AllowRow| cells.iter().any(|c| !c.skipped && r.in_cell(&c.name)); + let unused: Vec<&AllowRow> = rows.iter().zip(&used).filter(|(r, n)| whole && **n == 0 && ran(r)).map(|(r, _)| r).collect(); + for r in &unused { + text += &format!("unused allow row (\"{}\", \"{}\", \"{}\"): {}\n", r.kind, r.element, r.cell, r.why); + } + let frames: usize = cells.iter().map(|c| c.frames).sum(); + let summary = format!("motion gate: {} cells, {frames} frames, {failing} findings ({allowed_n} allowed, {} unused allow rows) in {secs:.1} s\n", cells.len(), unused.len()); + failed_kinds.sort(); + failed_kinds.dedup(); + for r in RULES.iter().filter(|r| failed_kinds.contains(&r.kind)) { + text += &format!(" {}: {} ({})\n", r.kind, r.means, r.threshold); + } + Report { text: summary.clone() + &text, summary, failing, allowed: allowed_n, unused: unused.len() } +} + +/// The gate as a test: runs the cells `MOTION_GATE` keeps, writes the report to +/// `MOTION_GATE_OUT`, and panics with it when a finding isn't allowed. Unused allow rows are +/// listed only when `MOTION_GATE` is unset, since a filtered run leaves most rows idle. +pub fn gate(cells: Vec<(String, Job)>, allow: &[Allow]) { + gate_rows(cells, &rows(allow)); +} + +/// [`gate`] with [`AllowRow`]s (cell scopes and match caps). +pub fn gate_rows(cells: Vec<(String, Job)>, allow: &[AllowRow]) { + let filter = rune_core::env::var("MOTION_GATE").unwrap_or_default(); + let started = crate::time::now(); + let cells = run(cells, &filter); + let r = report_with(&cells, allow, std::env::var_os("MOTION_GATE_ALLOWED").is_some(), filter.is_empty(), started.elapsed().as_secs_f32()); + if let Some(path) = rune_core::env::var("MOTION_GATE_OUT") { + std::fs::write(path, &r.text).unwrap(); + } + assert!(r.failing == 0, "{}", r.text); + eprint!("{}", r.summary); +} diff --git a/app/vendor/rune/crates/rune/src/motion_gate/loop_tests.rs b/app/vendor/rune/crates/rune/src/motion_gate/loop_tests.rs new file mode 100644 index 0000000..1127019 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/motion_gate/loop_tests.rs @@ -0,0 +1,130 @@ +use super::*; +use crate::{Beat, Cx, El, Env, GrowthSpec, ScrollSpec, Sequence, col, el, oklch}; + +fn kinds(rec: &Recording) -> Vec<&'static str> { + check(rec).into_iter().map(|f| f.kind).collect() +} + +#[derive(Default)] +struct Badge { + shown: bool, + right: bool, +} + +const FADE_IN: &[Beat] = &[Beat::new(0.0).opacity(0.0), Beat::new(0.2).easing(rune_motion::Easing::EASE_OUT)]; + +fn badge(s: &Badge, _: &mut Cx<Badge>) -> El { + let b = el().key("badge").size(100.0, 40.0).fill(oklch(0.6, 0.1, 250.0)).sequence(Sequence::new(FADE_IN)); + let b = if s.right { b.ml(200.0) } else { b }; + col().w_full().h_full().children(s.shown.then_some(b)) +} + +#[test] +fn a_one_shot_fade_that_settles_is_not_a_loop() { + let mut r = Run::new(Runtime::new(Badge::default(), badge, (400.0, 200.0), Env::new(true, 1.0)), 120.0); + r.idle(0.5); + r.step(); + r.act("show", |rt| rt.update(|s, _| s.shown = true)); + r.play(1.0); + assert!(kinds(&r.rec).is_empty(), "{:?}", check(&r.rec)); + // Nor does it hide what the element does after: a snap is still a jump. + r.act("move", |rt| rt.update(|s, tx| { s.right = true; tx.instant(); })); + r.play(0.5); + assert_eq!(kinds(&r.rec), ["jump"], "{:?}", check(&r.rec)); +} + +#[derive(Default)] +struct Spinner { + on: bool, +} + +fn spinner(s: &Spinner, _: &mut Cx<Spinner>) -> El { + let spin = el().key("spin").size(20.0, 20.0).fill(oklch(0.6, 0.1, 250.0)).looping(rune_motion::LoopSpec::rotation(1.0)); + col().w_full().h_full().children(s.on.then_some(spin)) +} + +/// A spinner turning, then, with `restart`, gone for a frame and back: the new one starts its +/// turn again from the top. +fn spin(restart: bool) -> Recording { + let mut r = Run::new(Runtime::new(Spinner { on: true }, spinner, (200.0, 200.0), Env::new(true, 1.0)), 120.0); + r.idle(0.5); + r.step(); + r.play(0.6); + if restart { + r.act("hide", |rt| rt.update(|s, tx| { s.on = false; tx.instant(); })); + r.act("show", |rt| rt.update(|s, tx| { s.on = true; tx.instant(); })); + } + r.play(0.6); + r.rec +} + +#[test] +fn a_spinner_keeps_its_rhythm_unless_it_restarts() { + assert!(!kinds(&spin(false)).contains(&"loop-jump"), "{:?}", check(&spin(false))); + assert!(kinds(&spin(true)).contains(&"loop-jump"), "{:?}", check(&spin(true))); +} + +struct Timeline { + open: bool, + rows: usize, + /// Bumped every frame, so the view runs on each, as an app's clock or stream does. + tick: u32, +} + +/// A pinned list of 40 pt rows, its 56th a fold: a 28 pt header over 40 steps of 28 pt when +/// open, in a 300 pt viewport. +fn timeline(s: &Timeline, _: &mut Cx<Timeline>) -> El { + let open = s.open; + let rows = col().key("rows").w_full().growth(GrowthSpec::default()).virtual_rows(s.rows, 40.0, + |_: &Timeline, i| format!("r{i}").into(), + move |_: &Timeline, i| { + let ink = oklch(0.6, 0.1, 250.0); + if i != 55 { return el().w_full().h(40.0).fill(ink); } + let mut group = col().key("group").w_full().child(el().key("hdr").w_full().h(28.0).fill(ink)); + if open { + group = group.child(col().key("steps").w_full().children((0..40).map(|k| el().key(format!("step-{k}")).w_full().h(28.0).fill(ink)))); + } + col().w_full().fold_glide(crate::Spring::new(0.18, 0.0)).child(group) + }); + col().key("scroll").size(400.0, 300.0).scroll(ScrollSpec { stick_bottom: true }).child(rows) +} + +/// Taps the fold, holding each state for `toggles[i]` seconds, then runs `last` if any. +fn fold(toggles: &[f64], last: Option<fn(&mut Timeline, &mut crate::Tx)>) -> Recording { + let mut r = Run::new(Runtime::new(Timeline { open: false, rows: 60, tick: 0 }, timeline, (400.0, 300.0), Env::new(true, 1.0)), 120.0); + r.idle(1.0); + r.step(); + let play = |r: &mut Run<Timeline>, secs: f64| { + for _ in 0..(secs * 120.0).round() as usize { + r.rt.update(|s, _| s.tick += 1); + r.step(); + } + }; + for &secs in toggles { + r.act("tap", |rt| rt.update(|s, tx| { s.open = !s.open; tx.keep_on_screen("hdr"); })); + play(&mut r, secs); + } + if let Some(last) = last { + r.act("remove", |rt| rt.update(last)); + play(&mut r, 0.5); + } + r.rec +} + +#[test] +fn rows_under_a_fold_gliding_open_stay_mounted_while_they_show() { + // The open fold is taller than the overscan, so the next window ends at it, while the rows + // under it still show as it glides open. + let rec = fold(&[1.0], None); + assert!(!kinds(&rec).contains(&"pop-out"), "{:?}", check(&rec)); +} + +#[test] +fn a_list_toggled_over_and_over_is_not_a_loop() { + // Its height turns back at each tap; that answers the taps, so what goes wrong in it shows. + let rec = fold(&[0.3, 0.3, 0.3, 0.3, 0.3, 0.06, 0.5, 0.8], Some(|s, tx| { s.rows = 59; tx.instant(); })); + let found = check(&rec); + assert!(found.iter().any(|f| f.kind == "pop-out" && f.element.ends_with("r59")), "{found:?}"); +} + + diff --git a/app/vendor/rune/crates/rune/src/motion_gate/mod.rs b/app/vendor/rune/crates/rune/src/motion_gate/mod.rs new file mode 100644 index 0000000..aa9aee7 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/motion_gate/mod.rs @@ -0,0 +1,250 @@ +//! A motion gate for an app's own tests: drive the real app headless on the virtual clock, record +//! every element's presented rect, visible part and opacity each frame, and list what a person +//! would see go wrong (see [`check`] and [`RULES`]). +//! +//! An app lists cells, one scenario in one circumstance each, and runs them in a test: +//! +//! ```ignore +//! use rune::motion_gate::{self, AllowRow, Job, Run}; +//! +//! const ALLOW: &[AllowRow] = &[ +//! AllowRow::new("fade-snap", "badge", "add-row", "the badge swaps at once, by design").max(1), +//! ]; +//! +//! fn add_row() -> motion_gate::Recording { +//! let mut r = Run::new(Runtime::new(State::default(), view, (800.0, 600.0), Env::new(true, 1.0)), 120.0); +//! r.idle(1.0); +//! r.step(); // frame 0: the settled start +//! r.act("tap add", |rt| Run::tap(rt, "add")); +//! r.play(1.0); +//! r.rec +//! } +//! +//! #[test] +//! fn motion_gate() { +//! motion_gate::gate_rows(vec![("add-row/wide".into(), Box::new(add_row) as Job)], ALLOW); +//! } +//! ``` +//! +//! [`gate`] reads its settings from the environment, which `scripts/motion-audit/gate` sets: +//! `MOTION_GATE` keeps cells whose name contains it, `MOTION_GATE_OUT` names a file for the full +//! report, `MOTION_GATE_ALLOWED` lists allowed findings too, `MOTION_GATE_DUMP=<cell>|<path +//! part>[|from|to]` writes those tracks' frames to `MOTION_GATE_OUT`.dump, and +//! `MOTION_GATE_SHEET=<cell>|<frame>[|<path part>]` writes a contact strip of the frames around +//! `frame` to `MOTION_GATE_OUT`.sheet.png. An empty cell part matches any cell, and headless +//! `rune` under `RUNE_MOTION_GATE` writes them beside its report. +//! +//! Beside geometry and opacity, each element's painted properties are followed frame by frame +//! (its colours in OKLab, corners, blurs, shadow, effect payload, image and place in the paint +//! order), and the composited window as a grid of cells a few points across: a CPU raster of +//! the painter stream, or a GPU frame through [`Run::pixels`]. `snap`, `flash` and +//! `changes-twice` find a property or a region that steps, blinks or changes twice. An input +//! ([`Run::act`]), a hover or press highlight landing, a `Tx::instant` commit, +//! `El::instant_changes` and `El::motion_intent` marks keep a deliberate change from counting. +//! So does `El::motion(Spring::NONE)` written on the element itself, for the properties that +//! spring governs there (colours but text, corners, shadow, blur; `El::blur_motion(Spring::NONE)` +//! for blur alone). A `Spring::NONE` it inherits, takes from a theme or token +//! (`El::token_motion`) or gets under Reduce Motion marks nothing, since no one chose it there. + +pub mod check; +mod gate; + +pub use check::{Finding, RULES, Recording, Rule, Snap, Track, check, dump, rule, sheet, short}; +pub use gate::{Allow, AllowRow, Cell, Job, Report, allowed, gate, gate_rows, report, report_rows, run}; +pub(crate) use gate::evidence; + +use std::sync::Arc; + +use crate::{ElementInfo, Runtime}; + +/// A frame's pixels, for [`Run::pixels`]: width, height and 8-bit sRGB RGBA rows. +pub type Pixels = (u32, u32, Vec<u8>); + +/// A runtime being recorded: every [`step`](Run::step) frames it on the virtual clock and samples +/// its element tree, what each element paints and the composited window into `rec`. +pub struct Run<S: 'static> { + pub rt: Runtime<S>, + pub rec: Recording, + /// Seconds per frame. + pub dt: f64, + /// Reads a drawn frame for the region checks in place of the CPU raster ([`Run::pixels`]). + draw: Option<Box<dyn FnMut(&mut Runtime<S>) -> Option<Pixels>>>, + raster: Raster, +} + +/// The CPU raster of a runtime's painter stream, reused while the stream is unchanged. +#[derive(Default)] +struct Raster(Option<(u64, Arc<check::raster::Grid>)>); + +impl Raster { + fn of(&mut self, rt: &crate::runtime::RuntimeCore, size: (f32, f32)) -> Arc<check::raster::Grid> { + use std::hash::{Hash, Hasher}; + let mut hasher = std::collections::hash_map::DefaultHasher::new(); + bytemuck::cast_slice::<_, u8>(&rt.instances).hash(&mut hasher); + let key = hasher.finish(); + if let Some((k, g)) = &self.0 && *k == key { return g.clone(); } + let g = Arc::new(check::raster::rasterize_with(&rt.instances, size, rt.env.scale, rt.paint.icon_aprons(), &rt.text.glyph_shifts())); + self.0 = Some((key, g.clone())); + g + } +} + +/// Samples a frame `rt` just took into `rec`: why it committed, its elements, what they paint +/// and the composited window (`grid`, else the CPU raster). +fn sample(rt: &mut crate::runtime::RuntimeCore, rec: &mut Recording, raster: &mut Raster, grid: Option<Arc<check::raster::Grid>>) { + let why = rt.commit.take_commit_why(); + rec.commits(rt.scrolling(), why); + let els: Vec<ElementInfo> = rt.elements(); + let paints = rt.paints(); + rec.sample_with(&els, Some(&paints)); + let grid = grid.unwrap_or_else(|| raster.of(rt, rec.size)); + rec.grid(Some(grid)); + rec.tips.resize(rec.frames.saturating_sub(1), None); + rec.tips.push(rt.help_tooltip().map(|t| t.1)); +} + +/// Records a runtime someone else steps, as headless `rune` does under `RUNE_MOTION_GATE`: +/// call [`input`](Sampler::input) for each input before its frame and +/// [`frame`](Sampler::frame) after each frame. +pub struct Sampler { + pub rec: Recording, + raster: Raster, +} + +impl Sampler { + pub fn new<S>(rt: &mut Runtime<S>, hz: f64) -> Self { + rt.paint.enable_paint_rank(); + Sampler { rec: Recording::new(rt.viewport, hz), raster: Raster::default() } + } + + /// An input on the next frame. + pub fn input(&mut self, what: &str) { + self.rec.input(what); + } + + /// Clears what the last frame left, before `rt.frame`. + pub fn before<S>(&mut self, rt: &mut Runtime<S>) { + rt.commit.clear_commit_why(); + } + + /// Samples the frame `rt` just took; `awake` is what `rt.frame` returned. + pub fn frame<S>(&mut self, rt: &mut Runtime<S>, awake: bool) { + self.rec.awake.push(awake); + sample(rt.core_mut(), &mut self.rec, &mut self.raster, None); + } +} + +fn run_init(core: &mut crate::runtime::RuntimeCore, app: &mut dyn crate::runtime::AppDriver, hz: f64) -> (Recording, f64) { + core.paint.enable_paint_rank(); + core.frame(app, 0.0); + (Recording::new(core.viewport, hz), 1.0 / hz) +} + +fn run_idle(core: &mut crate::runtime::RuntimeCore, app: &mut dyn crate::runtime::AppDriver, dt: f64, secs: f64) { + for _ in 0..(secs / dt).round() as usize { + core.frame(app, dt); + } +} + +fn run_step_frame(core: &mut crate::runtime::RuntimeCore, app: &mut dyn crate::runtime::AppDriver, rec: &mut Recording, dt: f64) { + core.commit.clear_commit_why(); + let played = app.playground_played(); + let awake = core.frame(app, dt); + if app.playground_played() > played { rec.input("a story step's key"); } + rec.awake.push(awake); +} + +fn run_step_sample(core: &mut crate::runtime::RuntimeCore, rec: &mut Recording, raster: &mut Raster, pixels: Option<Pixels>) { + let size = rec.size; + let drawn = pixels.map(|(w, h, rgba)| Arc::new(check::raster::from_pixels(&rgba, w, h, size))); + sample(core, rec, raster, drawn); +} + +fn run_tap(core: &mut crate::runtime::RuntimeCore, app: &mut dyn crate::runtime::AppDriver, key: &str) { + let (x, y) = core.find(key).unwrap_or_else(|| panic!("no {key}")); + core.pointer_move(app, x, y); + core.pointer_down(app, x, y); + core.pointer_up(app, x, y); +} + +impl<S: 'static> Run<S> { + /// Records `rt` at `hz` frames a second, after its first frame. Settle it with + /// [`idle`](Run::idle) and set the scene up, then the first [`step`](Run::step) is the settled + /// start the first action changes. + #[inline] + pub fn new(mut rt: Runtime<S>, hz: f64) -> Self { + let (core, mut app) = rt.split_mut(); + let (rec, dt) = run_init(core, &mut app, hz); + Run { rt, rec, dt, draw: None, raster: Raster::default() } + } + + /// Reads each recorded frame's pixels with `draw` (a GPU render of the runtime) for the + /// region checks, in place of rasterizing its painter stream on the CPU. `None` from it + /// falls back to the raster for that frame. + pub fn pixels(&mut self, draw: impl FnMut(&mut Runtime<S>) -> Option<Pixels> + 'static) { + self.draw = Some(Box::new(draw)); + } + + /// Steps `secs` unrecorded (setting up, before the run). + #[inline] + pub fn idle(&mut self, secs: f64) { + let (core, mut app) = self.rt.split_mut(); + run_idle(core, &mut app, self.dt, secs); + } + + /// Records one frame. A key a playground story's step pressed on it (`Play::press`) is an + /// input there, as [`act`](Run::act)'s are. + #[inline] + pub fn step(&mut self) { + let (core, mut app) = self.rt.split_mut(); + run_step_frame(core, &mut app, &mut self.rec, self.dt); + let pixels = self.draw.as_mut().and_then(|draw| draw(&mut self.rt)); + run_step_sample(self.rt.core_mut(), &mut self.rec, &mut self.raster, pixels); + } + + pub fn step_n(&mut self, n: usize) { + for _ in 0..n { + self.step(); + } + } + + /// Records `secs` of frames. + pub fn play(&mut self, secs: f64) { + self.step_n((secs / self.dt).round() as usize); + } + + /// An input on the next frame: `f` runs, then the frame it lands on is recorded. Motion + /// retargeted by an input isn't held to one path. + pub fn act(&mut self, what: &str, f: impl FnOnce(&mut Runtime<S>)) { + self.rec.input(what); + f(&mut self.rt); + self.step(); + } + + /// Marks the cell's motion as over from the next frame: frames asked for well after it are + /// `wakes-after-end`. + pub fn quiet(&mut self) { + self.rec.quiet_from = Some(self.rec.frames); + } + + /// A click at the middle of the element keyed `key`. + #[inline] + pub fn tap(rt: &mut Runtime<S>, key: &str) { + let (core, mut app) = rt.split_mut(); + run_tap(core, &mut app, key); + } + + /// What the checker finds in the recording. + pub fn finish(&self) -> Vec<Finding> { + check(&self.rec) + } +} + +#[cfg(test)] +mod tests; +#[cfg(test)] +mod loop_tests; +#[cfg(test)] +mod paint_tests; +#[cfg(test)] +mod spring_none_tests; diff --git a/app/vendor/rune/crates/rune/src/motion_gate/paint_tests.rs b/app/vendor/rune/crates/rune/src/motion_gate/paint_tests.rs new file mode 100644 index 0000000..f22a696 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/motion_gate/paint_tests.rs @@ -0,0 +1,240 @@ +//! `snap`, `flash` and `changes-twice` on painted properties and pixel regions, recorded from +//! a real runtime: each catches what it should and passes the deliberate version. +use super::*; +use crate::el::motion::MotionIntent; +use crate::{Color, Cx, El, Env, ScrollSpec, Spring, Transition, col, el, oklch}; + +#[derive(Clone, Copy, Default)] +struct S { + warm: bool, + thick: bool, + swapped: bool, + carded: bool, + cross: bool, + pulse: bool, +} + +const AT: (f32, f32, f32, f32) = (40.0, 200.0, 200.0, 80.0); + +fn view(s: &S, _: &mut Cx<S>) -> El { + let (blue, orange, card) = (oklch(0.6, 0.15, 250.0), oklch(0.7, 0.16, 50.0), oklch(0.78, 0.1, 250.0)); + let swatch = el().key("swatch").absolute(40.0, 40.0).size(120.0, 80.0).fill(if s.warm { orange } else { blue }) + .radius(4.0).border(if s.thick { 4.0 } else { 1.0 }, oklch(0.9, 0.02, 250.0)); + let pair = [("a", 300.0, 40.0, orange), ("b", 340.0, 70.0, blue)] + .map(|(k, x, y, c)| el().key(k).absolute(x, y).size(120.0, 80.0).fill(c)); + let [a, b] = pair; + let (first, second) = if s.swapped { (b, a) } else { (a, b) }; + let mut page = col().w_full().h_full().fill(oklch(0.18, 0.01, 260.0)).child(swatch).child(first).child(second); + // The Launch Room's flash: a plate that lands at once, under a card that fades in. + let (x, y, w, h) = AT; + let plate = el().key("plate").instant_changes().fill(card); + let plate = if s.carded { plate.absolute(0.0, 0.0).size(0.0, 0.0) } else { plate.absolute(x, y).size(w, h) }; + if !s.cross { + page = page.child(plate); + } else { + page = page.child(el().key("old").absolute(x, y).size(w, h).fill(card).transition(Transition::opacity())); + } + if s.carded || s.cross { + let fresh = el().key("card").absolute(x, y).size(w, h).fill(card).transition(Transition::opacity()); + page = page.child(fresh); + } + if s.pulse { + page = page.child(el().key("blink").absolute(420.0, 200.0).size(120.0, 80.0).fill(orange).instant_changes()); + } + page +} + +/// Settles on `start`, then makes `change` on a frame of its own: by a hand on the app when +/// `input`, or on its own (a poll, a timer) when not. +fn record(start: S, input: bool, change: impl FnOnce(&mut S, &mut crate::Tx)) -> Run<S> { + let mut r = Run::new(Runtime::new(start, view, (600.0, 400.0), Env::new(true, 1.0)), 120.0); + r.idle(0.5); + r.step(); + if input { + r.act("tap", |rt| rt.update(change)); + } else { + r.rt.update(change); + r.step(); + } + r +} + +fn found(r: &mut Run<S>) -> Vec<(&'static str, String)> { + r.play(1.0); + r.finish().into_iter().map(|f| (f.kind, f.element)).collect() +} + +#[test] +fn a_colour_that_cross_fades_on_its_own_passes() { + let mut r = record(S::default(), false, |s, _| s.warm = true); + assert_eq!(found(&mut r), []); +} + +#[test] +fn a_border_that_thickens_on_its_own_snaps_unless_a_hand_asked() { + let mut r = record(S::default(), false, |s, _| s.thick = true); + let f = r.play_and_check(); + assert_eq!(f.iter().map(|f| (f.kind, f.element.as_str())).collect::<Vec<_>>(), [("snap", "swatch")], "{f:?}"); + assert!(f[0].detail.starts_with("border-width 1.0 → 4.0"), "{}", f[0].detail); + let mut tapped = record(S::default(), true, |s, _| s.thick = true); + assert_eq!(found(&mut tapped), []); + let mut instant = record(S::default(), false, |s, tx| { s.thick = true; tx.instant(); }); + assert_eq!(found(&mut instant), [], "a Tx::instant commit lands at once by design"); +} + +#[test] +fn two_surfaces_trading_places_on_their_own_snap_in_the_paint_order() { + let mut r = record(S::default(), false, |s, _| s.swapped = true); + let f = r.play_and_check(); + assert!(f.iter().any(|f| f.kind == "snap" && f.detail.starts_with("z-order")), "{f:?}"); + let mut tapped = record(S::default(), true, |s, _| s.swapped = true); + assert_eq!(found(&mut tapped), []); +} + +#[test] +fn a_plate_that_drops_out_before_its_card_fades_in_flashes_in_the_pixels() { + let mut r = record(S::default(), false, |s, _| s.carded = true); + let f = r.play_and_check(); + let flash = f.iter().find(|f| f.kind == "flash").unwrap_or_else(|| panic!("{f:?}")); + assert_eq!(flash.element, "plate (pixels)", "{f:?}"); + assert!(flash.detail.contains("(204×96 pt at 36,192)"), "{}", flash.detail); + // The fix: both changes on one frame. The card landing at once is the existing `pop-in`. + let mut fixed = record(S::default(), false, |s, tx| { s.carded = true; tx.instant(); }); + assert_eq!(found(&mut fixed), [("pop-in", "card".to_string())]); +} + +#[test] +fn a_deliberate_cross_fade_between_two_surfaces_is_no_flash() { + let mut r = record(S::default(), false, |s, _| s.cross = true); + assert_eq!(found(&mut r), []); +} + +#[test] +fn a_surface_that_blinks_for_one_frame_flashes_unless_marked_a_pulse() { + let blink = |r: &mut Run<S>| { + r.step_n(30); + r.rt.update(|s, tx| { s.pulse = true; tx.instant(); }); + r.step(); + r.rt.update(|s, tx| { s.pulse = false; tx.instant(); }); + r.step(); + }; + let flashes = |f: Vec<Finding>| f.into_iter().filter(|f| f.kind == "flash").map(|f| f.element).collect::<Vec<_>>(); + let mut r = record(S::default(), false, |_, _| {}); + blink(&mut r); + let f = r.play_and_check(); + assert!(f.iter().any(|f| f.kind == "flash" && f.element == "blink (pixels)"), "{f:?}"); + let marked = |s: &S, cx: &mut Cx<S>| view(s, cx).motion_intent(MotionIntent::PULSE); + let mut r = Run::new(Runtime::new(S::default(), marked, (600.0, 400.0), Env::new(true, 1.0)), 120.0); + r.idle(0.5); + r.step(); + blink(&mut r); + assert_eq!(flashes(r.play_and_check()), Vec::<String>::new()); +} + +#[test] +fn a_highlight_landing_on_a_row_that_slides_under_a_still_pointer_is_no_snap() { + fn list(_: &(), _: &mut Cx<()>) -> El { + let row = |k: usize| el().key(format!("row-{k}")).w_full().h(40.0).fill(oklch(0.26, 0.015, 250.0)).hover(Color::WHITE.alpha(0.06)); + let rows = col().key("rows").w_full().children((0..30).map(row)); + let board = col().key("board").w_full().h(300.0).scroll(ScrollSpec { stick_bottom: false }).child(rows); + col().w_full().h_full().fill(oklch(0.18, 0.01, 250.0)).child(board) + } + let mut r = Run::new(Runtime::new((), list, (400.0, 400.0), Env::new(true, 1.0)), 120.0); + r.rt.pointer_move(200.0, 150.0); + r.idle(0.5); + r.step(); + r.rt.update(|_, tx| tx.scroll_to_with("board", 0.0, 400.0, Spring::new(0.3, 0.0))); + r.play(1.0); + let landed = r.rec.tracks.iter().filter(|t| (1..r.rec.frames).any(|k| t.paint_at(k).zip(t.paint_at(k - 1)).is_some_and(|(p, q)| p.pointer[0] == 1.0 && q.pointer[0] == 0.0))).count(); + assert!(landed >= 1, "the highlight never lands"); + let f = r.finish(); + assert!(!f.iter().any(|f| f.detail.starts_with("fill")), "{f:?}"); +} + +#[test] +fn a_list_settling_its_scroll_steps_whole_pixels_and_no_region_snaps() { + // The scroll snaps as one rounded translation, so over a glide's last fractions of a point + // the rows step a whole pixel now and then: that's the glide, not a snap. + fn list(_: &(), _: &mut Cx<()>) -> El { + let shade = |k: usize| if k % 2 == 0 { oklch(0.3, 0.02, 250.0) } else { oklch(0.7, 0.02, 250.0) }; + let rows = col().key("rows").w_full().children((0..60).map(|k| el().key(format!("row-{k}")).w_full().h(13.0).fill(shade(k)))); + let board = col().key("board").w_full().h(300.0).scroll(ScrollSpec { stick_bottom: false }).child(rows); + col().w_full().h_full().fill(oklch(0.18, 0.01, 250.0)).child(board) + } + let mut r = Run::new(Runtime::new((), list, (400.0, 400.0), Env::new(true, 1.0)), 120.0); + r.idle(0.5); + r.step(); + r.rt.update(|_, tx| tx.scroll_to_with("board", 0.0, 301.3, Spring::new(0.6, 0.0))); + r.play(1.5); + let f = r.finish(); + assert!(!f.iter().any(|f| f.element.ends_with("(pixels)")), "{f:#?}"); +} + +#[test] +fn a_tooltip_showing_after_its_rest_is_no_region_snap() { + // Rune's own tooltip lands at once after the pointer rests, as AppKit's does, with no input + // on that frame. + fn button(_: &(), _: &mut Cx<()>) -> El { + let b = el().key("b").absolute(40.0, 40.0).size(28.0, 28.0).fill(oklch(0.3, 0.02, 250.0)).help("Stop dictation ⇧⌘M"); + col().w_full().h_full().fill(oklch(0.18, 0.01, 250.0)).child(b) + } + let mut r = Run::new(Runtime::new((), button, (400.0, 400.0), Env::new(true, 1.0)), 120.0); + r.idle(0.5); + r.step(); + r.act("point at the button", |rt| rt.pointer_move(54.0, 54.0)); + r.play(1.0); + assert!(r.rt.help_tooltip().is_some(), "the tooltip shows"); + let f = r.finish(); + assert!(!f.iter().any(|f| f.element.ends_with("(pixels)")), "{f:#?}"); +} + +#[test] +fn an_icon_gliding_off_the_pixel_grid_marks_its_apron_and_shows_no_region_flash() { + // Mid-glide an icon off the pixel grid samples a transparent texel past each edge + // (`icon_inst`) and drops it whenever it lands on a whole pixel; the raster leaves that + // apron out, so the icon inks the same cells either way. + fn at(x: &f32, _: &mut Cx<f32>) -> El { + static DOT: crate::Icon = crate::Icon { name: "test-dot", view: 16.0, body: r#"<rect x="2" y="2" width="12" height="12" fill="currentColor"/>"# }; + let dot = crate::icon(&DOT, 16.0).key("dot").color(Color::WHITE).absolute(40.0, 40.0).offset(*x, 0.0).motion(Spring::new(1.2, 0.0)); + col().w_full().h_full().fill(oklch(0.18, 0.01, 250.0)).child(dot) + } + let mut r = Run::new(Runtime::new(0.0, at, (200.0, 120.0), Env::new(true, 1.0)), 120.0); + r.idle(0.5); + r.step(); + r.rt.update(|x, _| *x = 60.0); + let mut aproned = false; + for _ in 0..240 { + r.step(); + aproned |= !r.rt.paint.icon_aprons().is_empty(); + } + assert!(aproned, "the icon glides off the pixel grid"); + let f = r.finish(); + assert!(!f.iter().any(|f| f.element.ends_with("(pixels)")), "{f:#?}"); +} + +#[test] +fn words_set_in_a_field_without_a_key_are_no_region_snap() { + // Dictation puts its words at the caret from a poll, with no key: a field's words land at + // once, typed or not. + fn form(s: &crate::TextEdit, _: &mut Cx<crate::TextEdit>) -> El { + let field = crate::text_input(s, crate::TextStyle::new(14.0, 400.0)).key("prompt").size(360.0, 60.0).on_edit(|s: &mut crate::TextEdit| s); + col().w_full().h_full().padding(20.0).fill(oklch(0.18, 0.01, 250.0)).child(field) + } + let mut r = Run::new(Runtime::new(crate::TextEdit::new(""), form, (400.0, 120.0), Env::new(true, 1.0)), 120.0); + r.idle(0.5); + r.step(); + r.rt.update(|s, _| s.insert("Can you also check the reconnect jitter?")); + r.play(0.5); + r.rt.update(|s, _| *s = crate::TextEdit::new("")); + r.play(0.5); + let f = r.finish(); + assert!(!f.iter().any(|f| f.element.ends_with("(pixels)")), "{f:#?}"); +} + +impl Run<S> { + fn play_and_check(&mut self) -> Vec<Finding> { + self.play(1.0); + self.finish() + } +} + diff --git a/app/vendor/rune/crates/rune/src/motion_gate/spring_none_tests.rs b/app/vendor/rune/crates/rune/src/motion_gate/spring_none_tests.rs new file mode 100644 index 0000000..ed43e9b --- /dev/null +++ b/app/vendor/rune/crates/rune/src/motion_gate/spring_none_tests.rs @@ -0,0 +1,88 @@ +//! A `motion(Spring::NONE)` written on the element itself marks what that spring governs there +//! as landing at once by design; one that arrives any other way marks nothing. +use super::*; +use crate::{Cx, El, Env, Spring, col, el, oklch}; + +#[derive(Clone, Copy, Default, PartialEq)] +enum Source { + #[default] + Own, + Parent, + Token, + Reduced, + /// Inherited `Spring::NONE`, with the swatch's own `blur_motion(Spring::NONE)`. + OwnBlur, +} + +#[derive(Clone, Copy, Default)] +struct S { + source: Source, + warm: bool, + thick: bool, + blurred: bool, +} + +fn view(s: &S, cx: &mut Cx<S>) -> El { + let (blue, orange) = (oklch(0.6, 0.15, 250.0), oklch(0.7, 0.16, 50.0)); + let swatch = el().key("swatch").absolute(40.0, 40.0).size(120.0, 80.0) + .fill(if s.warm { orange } else { blue }) + .radius(if s.warm { 24.0 } else { 4.0 }) + .border(if s.thick { 4.0 } else { 1.0 }, if s.warm { oklch(0.4, 0.1, 50.0) } else { oklch(0.9, 0.02, 250.0) }) + .blur(if s.blurred { 6.0 } else { 0.0 }); + let swatch = match s.source { + Source::Own => swatch.motion(Spring::NONE), + Source::Token => swatch.token_motion(Spring::NONE), + Source::OwnBlur => swatch.blur_motion(Spring::NONE), + Source::Parent | Source::Reduced => swatch, + }; + if s.source == Source::Reduced { cx.reduced_motion(true); } + let page = col().key("page").w_full().h_full().fill(oklch(0.18, 0.01, 260.0)); + let page = if matches!(s.source, Source::Parent | Source::OwnBlur) { page.motion(Spring::NONE) } else { page }; + page.child(swatch) +} + +/// Settles with `from`, then makes `change` on a frame of its own with no input, and returns +/// what the swatch's snaps changed. +fn snaps(from: Source, change: impl FnOnce(&mut S)) -> Vec<String> { + let mut r = Run::new(Runtime::new(S { source: from, ..S::default() }, view, (400.0, 300.0), Env::new(true, 1.0)), 120.0); + r.idle(0.5); + r.step(); + r.rt.update(|s, _| change(s)); + r.step(); + r.play(1.0); + let f = r.finish(); + assert!(f.iter().all(|f| f.kind == "snap" && f.element == "page/swatch"), "{f:#?}"); + let mut changed: Vec<String> = f.iter().map(|f| f.detail.split(' ').next().unwrap_or_default().to_string()).collect(); + changed.sort(); + changed +} + +#[test] +fn an_explicit_spring_none_on_the_element_is_an_authored_instant_change() { + assert_eq!(snaps(Source::Own, |s| s.warm = true), Vec::<String>::new()); + assert_eq!(snaps(Source::Own, |s| s.blurred = true), Vec::<String>::new()); +} + +#[test] +fn a_spring_none_inherited_from_a_parent_still_snaps() { + assert_eq!(snaps(Source::Parent, |s| s.warm = true), ["border", "fill", "radius"]); +} + +#[test] +fn a_spring_none_from_a_theme_token_still_snaps() { + assert_eq!(snaps(Source::Token, |s| s.warm = true), ["border", "fill", "radius"]); +} + +#[test] +fn a_change_reduce_motion_lands_at_once_still_snaps() { + // Reduce Motion lands corners and blur at once and gives colours a short fade. + assert_eq!(snaps(Source::Reduced, |s| { s.warm = true; s.blurred = true; }), ["blur", "radius"]); +} + +#[test] +fn an_explicit_spring_none_excuses_only_what_it_governs() { + // `motion` doesn't spring border width, so its `Spring::NONE` says nothing about it. + assert_eq!(snaps(Source::Own, |s| s.thick = true), ["border-width"]); + // An instant blur curve of its own excuses its blur, not its inherited colours and corners. + assert_eq!(snaps(Source::OwnBlur, |s| { s.warm = true; s.blurred = true; }), ["border", "fill", "radius"]); +} diff --git a/app/vendor/rune/crates/rune/src/motion_gate/tests.rs b/app/vendor/rune/crates/rune/src/motion_gate/tests.rs new file mode 100644 index 0000000..cd13a50 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/motion_gate/tests.rs @@ -0,0 +1,212 @@ +use super::*; +use crate::{Cx, El, Env, Spring, col, el, oklch}; + +#[derive(Default)] +struct S { + right: bool, + shown: bool, +} + +fn view(s: &S, _: &mut Cx<S>) -> El { + let ink = oklch(0.6, 0.15, 25.0); + let mover = el().key("mover").size(100.0, 40.0).fill(ink).motion(Spring::new(0.3, 0.0)); + let mover = if s.right { mover.ml(300.0) } else { mover }; + let mut page = col().w_full().h_full().child(mover); + if s.shown { + page = page.child(el().key("box").size(100.0, 40.0).fill(ink)); + } + page +} + +fn cell(change: fn(&mut S, &mut crate::Tx)) -> Recording { + let mut r = Run::new(Runtime::new(S::default(), view, (600.0, 400.0), Env::new(true, 1.0)), 120.0); + r.idle(0.5); + r.step(); + r.act("change", |rt| rt.update(change)); + r.play(1.0); + r.rec +} + +fn kinds(rec: &Recording) -> Vec<&'static str> { + check(rec).into_iter().map(|f| f.kind).collect() +} + +#[test] +fn a_run_records_a_spring_as_clean_and_a_snap_as_a_jump() { + let spring = cell(|s, _| s.right = true); + assert_eq!(spring.frames, 122, "the settled start, the input's frame and a second"); + assert!(kinds(&spring).is_empty(), "{:?}", check(&spring)); + let snap = cell(|s, tx| { + s.right = true; + tx.instant(); + }); + assert_eq!(kinds(&snap), ["jump"], "{:?}", check(&snap)); +} + +#[test] +fn a_box_that_mounts_with_no_transition_pops_in_unless_allowed() { + let rec = cell(|s, tx| { + s.shown = true; + tx.instant(); + }); + let findings = check(&rec); + assert!(findings.iter().any(|f| f.kind == "pop-in" && f.element.contains("box")), "{findings:?}"); + let cells = [Cell { name: "show/wide".into(), frames: rec.frames, skipped: false, findings }]; + let open = report(&cells, &[], false, 0.0); + assert!(open.failing > 0 && open.text.contains("pop-in") && open.text.contains("mounts at or above")); + const ALLOW: &[Allow] = &[("pop-in", "box", "show/", "the box appears at once, by design")]; + let allowed = report(&cells, ALLOW, true, 0.0); + assert_eq!((allowed.failing, allowed.allowed), (0, 1)); + assert!(allowed.text.contains("allowed") && allowed.text.contains("by design")); + assert_eq!(report(&cells, &[("pop-in", "box", "narrow", "")], false, 0.0).failing, 1, "the cell must match too"); +} + +#[test] +fn allow_rows_cap_what_they_cover_and_report_when_unused() { + let f = |el: &str| Finding { kind: "flash", element: el.into(), frame: 3, detail: String::new() }; + let cells = [ + Cell { name: "island-auto/dark".into(), frames: 10, skipped: false, findings: vec![f("plate"), f("plate")] }, + Cell { name: "parks/dark".into(), frames: 10, skipped: false, findings: vec![] }, + ]; + let one = [AllowRow::new("flash", "plate", "island-auto|island-click", "the plate's hand-off").max(1)]; + let r = report_rows(&cells, &one, false, 0.0); + assert_eq!((r.failing, r.allowed, r.unused), (1, 1, 0)); + assert!(r.text.contains("past its allow row's max of 1"), "{}", r.text); + let rows = [AllowRow::new("", "plate", "island-auto", "any kind"), AllowRow::new("jump", "x", "parks", "stale"), AllowRow::new("jump", "x", "game", "not run")]; + let r = report_rows(&cells, &rows, false, 0.0); + assert_eq!((r.failing, r.allowed, r.unused), (0, 2, 1), "only a row whose cells ran counts as unused"); + assert!(r.text.contains("unused allow row (\"jump\", \"x\", \"parks\")"), "{}", r.text); +} + +#[test] +fn run_keeps_the_filtered_cells_in_order_and_flags_one_that_recorded_nothing() { + let jobs: Vec<(String, Job)> = vec![ + ("move/wide".into(), Box::new(|| cell(|s, _| s.right = true))), + ("move/narrow".into(), Box::new(|| cell(|s, _| s.right = true))), + ("empty/wide".into(), Box::new(|| Recording::new((10.0, 10.0), 120.0))), + ("show/wide".into(), Box::new(|| panic!("filtered out"))), + ]; + let cells = run(jobs, "m"); + let names: Vec<&str> = cells.iter().map(|c| c.name.as_str()).collect(); + assert_eq!(names, ["move/wide", "move/narrow", "empty/wide"]); + assert!(cells[2].skipped && !cells[0].skipped); + assert_eq!(report(&cells, &[], false, 0.0).failing, 1); +} + +struct Feed { + polls_change: bool, +} + +fn feed(_: &Feed, _: &mut Cx<Feed>) -> El { + let rows = (0..40).fold(col().w_full(), |c, i| c.child(el().key(format!("row{i}")).w_full().h(40.0).fill(oklch(0.3, 0.02, 250.0)))); + col().w_full().h_full().child(col().key("feed").w_full().h(300.0).scroll(crate::ScrollSpec { stick_bottom: false }).child(rows)) +} + +fn scroll_cell(polls_change: bool) -> Recording { + let mut rt = Runtime::new(Feed { polls_change }, feed, (400.0, 300.0), Env::new(true, 1.0)); + rt.poll = Some(|s, _, _| s.polls_change); + let mut r = Run::new(rt, 120.0); + r.idle(0.5); + r.step(); + for _ in 0..30 { + r.act("wheel", |rt| rt.wheel(200.0, 150.0, -12.0)); + } + r.play(0.5); + r.rec +} + +#[test] +fn an_app_that_runs_its_view_through_a_scroll_fails_the_gate() { + let still = scroll_cell(false); + assert!(!kinds(&still).contains(&"scroll-commit"), "{:?}", check(&still)); + let busy = scroll_cell(true); + let f: Vec<_> = check(&busy).into_iter().filter(|f| f.kind == "scroll-commit").collect(); + assert_eq!(f.len(), 1, "{f:?}"); + assert!(f[0].detail.contains("(poll)"), "it names the cause: {}", f[0].detail); +} + +/// Rows in a list drawn at 1.6×, each gliding on `spring` when the first drops by `drop`. +#[derive(Clone, Copy)] +struct Zoomed { + drop: f32, + spring: Spring, + down: bool, +} + +fn zoomed(s: &Zoomed, _: &mut Cx<Zoomed>) -> El { + let ink = oklch(0.6, 0.15, 25.0); + let rows = (0..30).fold(col().key("rows").w_full(), |c, i| { + let row = el().key(format!("row{i}")).w_full().h(40.0).fill(ink).motion(s.spring); + c.child(if i == 0 && s.down { row.mt(s.drop) } else { row }) + }); + col().key("zoom").w_full().h_full().scale(1.6) + .child(col().key("feed").w_full().h_full().scroll(crate::ScrollSpec { stick_bottom: false }).child(rows)) +} + +fn zoomed_cell(drop: f32, spring: Spring) -> Recording { + let mut r = Run::new(Runtime::new(Zoomed { drop, spring, down: false }, zoomed, (600.0, 600.0), Env::new(true, 1.0)), 120.0); + r.rt.update(|_, tx| tx.scroll_to_instant("feed", 0.0, 200.0)); + r.idle(0.5); + r.step(); + // Data arriving, not a hand: an input would excuse a path that turns. + r.rt.update(|s, tx| { s.down = true; tx.scroll_to("feed", 0.0, 400.0); }); + r.play(1.0); + r.rec +} + +#[test] +fn motion_inside_a_zoomed_scroll_is_judged_against_the_scroll() { + // A glide carries the rows up 200 pt, 320 pt on screen, while they glide 60 pt down the + // list: on screen they only rise, and against the list they only move down. Taking the + // scroll back at the list's own scale, not the window's, turns that into a dip and climb. + let paths = |rec: &Recording, kinds: &[&str]| -> Vec<String> { + check(rec).into_iter().filter(|f| kinds.contains(&f.kind)).map(|f| f.to_string()).collect() + }; + let glide = zoomed_cell(60.0, Spring::new(0.2, 0.0)); + let row = glide.tracks.iter().find(|t| t.path.ends_with("row12")).unwrap(); + assert!(row.frames.windows(2).all(|w| w[1].1.rect[1] <= w[0].1.rect[1] + 0.01), "on screen it only rises"); + let turns = paths(&glide, &["reversal", "jiggle", "overshoot"]); + assert!(turns.is_empty(), "{turns:#?}"); + // A row that overshoots its place in the list still does, the scroll subtracted. + let wobble = zoomed_cell(60.0, Spring::new(0.3, 0.5)); + let turns = paths(&wobble, &["reversal", "jiggle", "overshoot"]); + assert!(turns.iter().any(|f| f.contains("row12")), "{turns:#?}"); +} + +/// A 300 pt list whose first row starts just under the viewport, below 300 pt of padding. +fn padded(_: &(), _: &mut Cx<()>) -> El { + let rows = (0..20).fold(col().key("rows").w_full().pt(300.0), |c, i| c.child(el().key(format!("row{i}")).w_full().h(40.0).fill(oklch(0.3, 0.02, 250.0)))); + col().w_full().h_full().child(col().key("list").w_full().h(300.0).scroll(crate::ScrollSpec { stick_bottom: false }).child(rows)) +} + +/// The jumps, jerks and steps `scroll` makes in the padded list, as the gate reports them. +fn padded_jumps(scroll: fn(&mut Run<()>)) -> Vec<String> { + let mut r = Run::new(Runtime::new((), padded, (400.0, 400.0), Env::new(true, 1.0)), 120.0); + r.idle(0.5); + r.step(); + scroll(&mut r); + r.play(1.0); + r.finish().into_iter().filter(|f| ["jump", "offset-jump", "jerk", "appear-then-jump"].contains(&f.kind)).map(|f| f.to_string()).collect() +} + +#[test] +fn a_scroll_that_teleports_a_row_into_view_with_no_input_jumps() { + // The offset jumps 40 pt with no hand on the app: the first row, just off screen, pops + // 40 pt into view, though nothing showed on both frames to be seen moving. + let instant = padded_jumps(|r| { + r.rt.update(|_, tx| tx.scroll_to_instant("list", 0.0, 40.0)); + r.step(); + }); + assert_eq!(instant.len(), 1, "{instant:#?}"); + assert!(instant[0].starts_with("jump") && instant[0].contains("rows"), "{instant:#?}"); + // A wheel, a scroll a tap asks for and a glide bring it in as you'd expect. + let wheel = padded_jumps(|r| for _ in 0..4 { r.act("wheel", |rt| rt.wheel(200.0, 150.0, -10.0)) }); + assert!(wheel.is_empty(), "{wheel:#?}"); + let tapped = padded_jumps(|r| r.act("tap", |rt| rt.update(|_, tx| tx.scroll_to_instant("list", 0.0, 40.0)))); + assert!(tapped.is_empty(), "{tapped:#?}"); + let glide = padded_jumps(|r| { + r.rt.update(|_, tx| tx.scroll_to("list", 0.0, 40.0)); + r.step(); + }); + assert!(glide.is_empty(), "{glide:#?}"); +} diff --git a/app/vendor/rune/crates/rune/src/native_menu/default_macos.rs b/app/vendor/rune/crates/rune/src/native_menu/default_macos.rs new file mode 100644 index 0000000..dc7e636 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/native_menu/default_macos.rs @@ -0,0 +1,278 @@ +//! The winit 0.30 app menu for an accessory app becoming a regular app, and the standard +//! Edit and Window items. Creating a custom Rune menu uses the same root, so either +//! installation order composes. + +#![allow(unsafe_code)] + +use std::{cell::RefCell, collections::HashSet}; +use super::standard::Equivalent; +use crate::Label; +use objc2::{MainThreadMarker, msg_send, rc::Retained, runtime::Sel, sel}; +use objc2_app_kit::{NSApplication, NSEventModifierFlags, NSMenu, NSMenuItem}; +use objc2_foundation::{NSProcessInfo, NSString}; + +thread_local! { + /// The empty app menu of a menu bar `App::standard_menus` made, filled when the app + /// first shows its Dock icon. + static PENDING: RefCell<Option<Retained<NSMenu>>> = const { RefCell::new(None) }; +} + +/// Preserve any existing menu, including an app-supplied empty menu. AppKit owns +/// the fallback for the app's lifetime; removing Rune's custom items leaves it alone. +pub(crate) fn ensure(app: &NSApplication) -> Retained<NSMenu> { + // SAFETY: NSApplication and its menus are main-thread-only. All objects are + // retained and the standard selectors use AppKit's responder chain, as in winit. + unsafe { + if let Some(root) = app.mainMenu() { return root; } + let root = empty_root(app); + let menu = PENDING.with(|p| p.borrow_mut().take()).expect("empty_root leaves its app menu"); + add_app_items(app, &menu); + root + } +} + +/// `ensure` for an app showing its Dock icon: a standard-menus bar gets its app menu now. +pub(crate) fn promote(app: &NSApplication) { + ensure(app); + // SAFETY: main thread; the pending menu is retained and still in the menu bar's first slot. + unsafe { + if let Some(menu) = PENDING.with(|p| p.borrow_mut().take()) { add_app_items(app, &menu); } + } +} + +/// Lays `menu` and its submenus out the way the app's language reads +/// (`labels::set_direction`): right to left, their items align right, with checkmarks and +/// shortcuts on the other sides, as a menu in a right-to-left localization's. +pub(crate) fn set_layout_direction(menu: &NSMenu) { + // NSUserInterfaceLayoutDirection: left to right 0, right to left 1. + let direction: isize = if crate::labels::rtl() { 1 } else { 0 }; + // SAFETY: main-thread menus and items, indices bounded by the item count; the setter + // (macOS 10.11 and later) takes an NSInteger. + unsafe { + let _: () = msg_send![menu, setUserInterfaceLayoutDirection: direction]; + for i in 0..menu.numberOfItems() { + if let Some(submenu) = menu.itemAtIndex(i).and_then(|item| item.submenu()) { set_layout_direction(&submenu); } + } + } +} + +/// A menu bar whose first item is an empty app menu, waiting in `PENDING`. +pub(crate) fn empty_root(app: &NSApplication) -> Retained<NSMenu> { + let mtm = MainThreadMarker::from(app); + let root = NSMenu::new(mtm); + let top = NSMenuItem::new(mtm); + let menu = NSMenu::new(mtm); + top.setSubmenu(Some(&menu)); + root.addItem(&top); + app.setMainMenu(Some(&root)); + PENDING.with(|p| *p.borrow_mut() = Some(menu)); + root +} + +/// winit's app menu items, appended after any custom items already in `menu`. +unsafe fn add_app_items(app: &NSApplication, menu: &NSMenu) { + // SAFETY: as `ensure`. + unsafe { + let mtm = MainThreadMarker::from(app); + let services = NSMenu::new(mtm); + let services_item = item(mtm, "", None, ""); + services_item.setSubmenu(Some(&services)); + let hide_others = item(mtm, "", Some(sel!(hideOtherApplications:)), "h"); + hide_others.setKeyEquivalentModifierMask(NSEventModifierFlags::Option + | NSEventModifierFlags::Command); + for entry in [ + item(mtm, "", Some(sel!(orderFrontStandardAboutPanel:)), ""), + NSMenuItem::separatorItem(mtm), + services_item, + item(mtm, "", Some(sel!(hide:)), "h"), + hide_others, + item(mtm, "", Some(sel!(unhideAllApplications:)), ""), + NSMenuItem::separatorItem(mtm), + item(mtm, "", Some(sel!(terminate:)), "q"), + ] { + entry.setTag(APP_ITEM); + menu.addItem(&entry); + } + app.setServicesMenu(Some(&services)); + relabel_app_items(menu); + } +} + +/// The app menu items `add_app_items` made, titled with the app's labels (`rune::set_labels`). +unsafe fn relabel_app_items(menu: &NSMenu) { + let name = NSProcessInfo::processInfo().processName().to_string(); + for entry in (0..menu.numberOfItems()).filter_map(|i| menu.itemAtIndex(i)).filter(|i| i.tag() == APP_ITEM) { + let label = match entry.action().and_then(|a| a.name().to_str().ok()) { + Some("orderFrontStandardAboutPanel:") => Label::About(&name), + Some("hide:") => Label::Hide(&name), + Some("hideOtherApplications:") => Label::HideOthers, + Some("unhideAllApplications:") => Label::ShowAll, + Some("terminate:") => Label::Quit(&name), + _ if !entry.isSeparatorItem() && entry.submenu().is_some() => Label::Services, + _ => continue, + }; + entry.setTitle(&NSString::from_str(&crate::labels::label(label))); + } +} + +/// Retitles the menus and items Rune made with the app's current labels (`rune::set_labels`), +/// after its language changed. +pub(crate) fn relabel(app: &NSApplication) { + // SAFETY: main thread; setting titles of retained menus and items. + unsafe { + let Some(root) = app.mainMenu() else { return }; + for (index, top) in (0..root.numberOfItems()).filter_map(|i| root.itemAtIndex(i)).enumerate() { + let Some(menu) = top.submenu() else { continue }; + if index == 0 { relabel_app_items(&menu); } + if let Some(name) = identifier(&top) { + let title = NSString::from_str(&crate::labels::label(Label::Menu(&name))); + top.setTitle(&title); + menu.setTitle(&title); + } + for entry in (0..menu.numberOfItems()).filter_map(|i| menu.itemAtIndex(i)).filter(|i| i.tag() == STANDARD) { + if let Some(standard) = entry.action().and_then(|a| a.name().to_str().ok()).and_then(super::standard::by_action) { + entry.setTitle(&NSString::from_str(&crate::labels::label(standard.label()))); + } + } + } + } +} + +/// The name a top-level menu Rune made goes by (`MenuItem::menu`), else its title. +pub(crate) fn name(top: &NSMenuItem) -> String { + identifier(top).unwrap_or_else(|| top.title().to_string()) +} + +/// Marks the identifier of a top-level menu Rune made, ahead of its name. +const NAMED: &str = "rune.menu."; + +fn identifier(top: &NSMenuItem) -> Option<String> { + // SAFETY: NSMenuItem implements NSUserInterfaceItemIdentification; main thread. + let id: Option<Retained<NSString>> = unsafe { msg_send![top, identifier] }; + id.and_then(|id| id.to_string().strip_prefix(NAMED).map(str::to_owned)) +} + +/// Whether the menu bar is still the one winit installs for a regular app. +pub(crate) fn is_winit_default(app: &NSApplication) -> bool { + let Some(root) = app.mainMenu() else { return false }; + let first = (root.numberOfItems() > 0).then(|| root.itemAtIndex(0)).flatten().and_then(|i| i.submenu()); + let actions: Vec<Option<String>> = first.map(|m| (0..m.numberOfItems()).filter_map(|i| m.itemAtIndex(i)) + .map(|i| i.action().map(|a| a.name().to_string_lossy().into_owned())).collect()).unwrap_or_default(); + let actions: Vec<Option<&str>> = actions.iter().map(Option::as_deref).collect(); + super::standard::is_winit_default(root.numberOfItems() as usize, &actions) +} + +/// Tags the items `add_standard` makes. +const STANDARD: isize = 0x5255_4e45; +/// Tags the app menu items `add_app_items` makes. +const APP_ITEM: isize = 0x5255_4e46; + +/// The standard items, into menus of their titles (made if absent) in the menu bar, or in a +/// new one whose empty app menu waits for `promote`. An action a menu already has is skipped. +/// Never adds Quit. +pub(crate) fn add_standard(app: &NSApplication) { + let mtm = MainThreadMarker::from(app); + // SAFETY: main-thread AppKit calls on retained menus; nil-target items keep no target. + unsafe { + let root = app.mainMenu().unwrap_or_else(|| empty_root(app)); + for standard in &super::standard::ITEMS { + let menu = top(mtm, &root, standard.menu); + let action = Sel::register(&std::ffi::CString::new(standard.action).expect("selector")); + if (0..menu.numberOfItems()).filter_map(|i| menu.itemAtIndex(i)).any(|i| i.action() == Some(action)) { continue; } + if standard.separator_before && menu.numberOfItems() > 0 { menu.addItem(&NSMenuItem::separatorItem(mtm)); } + let entry = item(mtm, &crate::labels::label(standard.label()), Some(action), &standard.key.to_string()); + let mut flags = NSEventModifierFlags::Command; + if standard.shift { flags |= NSEventModifierFlags::Shift; } + entry.setKeyEquivalentModifierMask(flags); + entry.setTag(STANDARD); + menu.addItem(&entry); + } + } + sync_standard(app); +} + +/// Adds an app's own items in `add`: AppKit drops the key equivalent of an item added while +/// the menu bar already has it, so the standard items let go of theirs first and take back +/// only those no other item claims (`sync_standard`). +pub(crate) fn adding<R>(app: &NSApplication, add: impl FnOnce() -> R) -> R { + set_standard_keys(app, |_| false); + let added = add(); + sync_standard(app); + added +} + +/// After the menu bar's items change: each standard item keeps its key equivalent unless +/// another item in the menu bar has the same one, so an app's own item (Close Tab ⌘W) wins +/// whichever was added first. +pub(crate) fn sync_standard(app: &NSApplication) { + let mut claimed = HashSet::new(); + // SAFETY: main thread; reading retained menus. + if let Some(root) = app.mainMenu() { unsafe { claims(&root, &mut claimed) }; } + set_standard_keys(app, |equivalent| !claimed.contains(equivalent)); +} + +fn set_standard_keys(app: &NSApplication, keep: impl Fn(&Equivalent) -> bool) { + let Some(root) = app.mainMenu() else { return }; + for menu in (0..root.numberOfItems()).filter_map(|i| root.itemAtIndex(i)?.submenu()) { + for entry in (0..menu.numberOfItems()).filter_map(|i| menu.itemAtIndex(i)).filter(|i| i.tag() == STANDARD) { + let Some(standard) = entry.action().and_then(|a| a.name().to_str().ok()).and_then(super::standard::by_action) else { continue }; + let equivalent = standard.equivalent(); + entry.setKeyEquivalent(&NSString::from_str(if keep(&equivalent) { &equivalent.key } else { "" })); + } + } +} + +/// The key equivalents of every item but the standard ones, submenus included. +unsafe fn claims(menu: &NSMenu, out: &mut HashSet<Equivalent>) { + // SAFETY: as `sync_standard`. + unsafe { + for entry in (0..menu.numberOfItems()).filter_map(|i| menu.itemAtIndex(i)) { + if entry.tag() != STANDARD { + let flags = entry.keyEquivalentModifierMask(); + let has = |f| flags.contains(f); + out.extend(Equivalent::new(&entry.keyEquivalent().to_string(), + has(NSEventModifierFlags::Command), has(NSEventModifierFlags::Shift), + has(NSEventModifierFlags::Option), has(NSEventModifierFlags::Control))); + } + if let Some(sub) = entry.submenu() { claims(&sub, out); } + } + } +} + +/// A new top-level menu named `name` in the Mac order (`standard::top_index`): File before the +/// standard Edit, the app's other menus before Window, Help last. Its title is the app's label +/// for the name (`Label::Menu`). +pub(crate) fn add_top(mtm: MainThreadMarker, root: &NSMenu, name: &str) -> (Retained<NSMenuItem>, Retained<NSMenu>) { + // SAFETY: main thread; every object is retained. + unsafe { + let tops: Vec<String> = (0..root.numberOfItems()).filter_map(|i| root.itemAtIndex(i)).map(|i| self::name(&i)).collect(); + let title = NSString::from_str(&crate::labels::label(Label::Menu(name))); + let menu = NSMenu::new(mtm); + menu.setTitle(&title); + let entry = NSMenuItem::new(mtm); + entry.setTitle(&title); + let _: () = msg_send![&entry, setIdentifier: &*NSString::from_str(&format!("{NAMED}{name}"))]; + entry.setSubmenu(Some(&menu)); + root.insertItem_atIndex(&entry, super::standard::top_index(name, &tops) as isize); + (entry, menu) + } +} + +/// Removes a top-level menu its maker no longer uses, unless other items (the standard ones) +/// still live in it. +pub(crate) fn remove_top_if_empty(root: &NSMenu, top: &NSMenuItem) { + if top.submenu().is_none_or(|m| m.numberOfItems() == 0) && root.indexOfItem(top) >= 0 { root.removeItem(top); } +} + +unsafe fn top(mtm: MainThreadMarker, root: &NSMenu, name: &str) -> Retained<NSMenu> { + let existing = (0..root.numberOfItems()).filter_map(|i| root.itemAtIndex(i)) + .find(|i| self::name(i) == name).and_then(|i| i.submenu()); + existing.unwrap_or_else(|| add_top(mtm, root, name).1) +} + +fn item(mtm: MainThreadMarker, title: &str, action: Option<Sel>, key: &str) -> Retained<NSMenuItem> { + // SAFETY: Standard NSMenuItem initializer on the main thread; nil target lets + // AppKit route the action. NSMenuItem defaults to Command for its key equivalent. + unsafe { NSMenuItem::initWithTitle_action_keyEquivalent(mtm.alloc(), + &NSString::from_str(title), action, &NSString::from_str(key)) } +} diff --git a/app/vendor/rune/crates/rune/src/native_menu/key_equivalent.rs b/app/vendor/rune/crates/rune/src/native_menu/key_equivalent.rs new file mode 100644 index 0000000..3108789 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/native_menu/key_equivalent.rs @@ -0,0 +1,52 @@ +//! A shortcut as an AppKit menu key equivalent. AppKit matches a menu item by the character a +//! key types, so the equivalent is the character the accelerator names ("cmd+b" is "b"), not +//! the one its physical key types in the current layout: on Dvorak that is "x", and the item +//! would take ⌘X from Cut. A layout that switches to QWERTY under ⌘ is AppKit's to handle. +//! Plain data, testable on every platform. +use crate::{PhysicalKeyCode, Shortcut}; + +/// `NSEventModifierFlags` bits. Never the function-key flag, which AppKit draws as 🌐. +pub(crate) const SHIFT: usize = 1 << 17; +pub(crate) const CONTROL: usize = 1 << 18; +pub(crate) const OPTION: usize = 1 << 19; +pub(crate) const COMMAND: usize = 1 << 20; + +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) struct KeyEquivalent { + /// `NSMenuItem.keyEquivalent`: a lowercase letter, a digit or symbol, or AppKit's + /// character for a named key (↩ ⇥ ⎋ ⌫ ⌦, arrows, F-keys). + pub key: String, + /// `NSMenuItem.keyEquivalentModifierMask`. + pub mask: usize, +} + +impl KeyEquivalent { + /// Shift stays in the mask with the unshifted character: "cmd+shift+z" is "z" with ⇧⌘ + /// and "cmd+shift+=" is "=" with ⇧⌘ (shown ⇧⌘=), as the accelerator names them. AppKit + /// matches either on any layout, where the shifted symbol ("+") would depend on the layout. + pub(crate) fn new(shortcut: &Shortcut) -> Self { + use PhysicalKeyCode::*; + let scalar = match shortcut.physical_key() { + Escape => 0x1b, Enter => 0x0d, Tab => 9, Backspace => 8, Space => 32, + ArrowUp => 0xf700, ArrowDown => 0xf701, ArrowLeft => 0xf702, ArrowRight => 0xf703, + Insert => 0xf727, Delete => 0xf728, Home => 0xf729, End => 0xf72b, PageUp => 0xf72c, PageDown => 0xf72d, + key if (F1..=F24).contains(&key) => 0xf704 + key as u32 - F1 as u32, + _ => 0, + }; + // A letter, digit or symbol: its menu keycap ("B", "="), lowercased. + let key = char::from_u32(scalar).filter(|_| scalar != 0).map_or_else( + || shortcut.menu_keycaps().pop().unwrap_or_default().to_lowercase(), String::from); + let mods = shortcut.modifiers(); + let mask = [(mods.ctrl, CONTROL), (mods.alt, OPTION), (mods.shift, SHIFT), (mods.logo, COMMAND)] + .into_iter().filter(|(on, _)| *on).fold(0, |mask, (_, bit)| mask | bit); + Self { key, mask } + } +} + +/// Shows `shortcut` beside the item, or nothing. +#[cfg(target_os = "macos")] +pub(crate) fn set_key_equivalent(item: &objc2_app_kit::NSMenuItem, shortcut: Option<&Shortcut>) { + let (key, mask) = shortcut.map(KeyEquivalent::new).map_or((String::new(), 0), |e| (e.key, e.mask)); + item.setKeyEquivalent(&objc2_foundation::NSString::from_str(&key)); + item.setKeyEquivalentModifierMask(objc2_app_kit::NSEventModifierFlags(mask)); +} diff --git a/app/vendor/rune/crates/rune/src/native_menu/key_equivalent_tests.rs b/app/vendor/rune/crates/rune/src/native_menu/key_equivalent_tests.rs new file mode 100644 index 0000000..6baf55e --- /dev/null +++ b/app/vendor/rune/crates/rune/src/native_menu/key_equivalent_tests.rs @@ -0,0 +1,87 @@ +use super::key_equivalent::*; +use crate::Shortcut; + +fn equivalent(accelerator: &str) -> (String, usize) { + let e = KeyEquivalent::new(&accelerator.parse().unwrap()); + (e.key, e.mask) +} +fn eq(key: &str, mask: usize) -> (String, usize) { (key.into(), mask) } + +#[test] +fn equivalents_are_the_characters_the_accelerators_name() { + assert_eq!(equivalent("cmd+b"), eq("b", COMMAND)); + assert_eq!(equivalent("cmd+="), eq("=", COMMAND)); + assert_eq!(equivalent("cmd+-"), eq("-", COMMAND)); + assert_eq!(equivalent("cmd+r"), eq("r", COMMAND)); + assert_eq!(equivalent("cmd+1"), eq("1", COMMAND)); + assert_eq!(equivalent("ctrl+cmd+s"), eq("s", CONTROL | COMMAND)); + // ⌃⌘F, never the function-key flag (1 << 23) that AppKit draws as 🌐. + assert_eq!(equivalent("ctrl+cmd+f"), eq("f", CONTROL | COMMAND)); + // Shift stays in the mask beside the unshifted character. + assert_eq!(equivalent("cmd+shift+z"), eq("z", SHIFT | COMMAND)); + assert_eq!(equivalent("cmd+shift+="), eq("=", SHIFT | COMMAND)); + assert_eq!(equivalent("ctrl+alt+shift+cmd+k"), eq("k", CONTROL | OPTION | SHIFT | COMMAND)); +} + +#[test] +fn named_keys_use_appkit_characters() { + assert_eq!(equivalent("alt+cmd+left"), eq("\u{f702}", OPTION | COMMAND)); + assert_eq!(equivalent("cmd+up"), eq("\u{f700}", COMMAND)); + assert_eq!(equivalent("f5"), eq("\u{f708}", 0)); + assert_eq!(equivalent("shift+f24"), eq("\u{f71b}", SHIFT)); + assert_eq!(equivalent("cmd+enter"), eq("\r", COMMAND)); + assert_eq!(equivalent("cmd+backspace"), eq("\u{8}", COMMAND)); + assert_eq!(equivalent("cmd+delete"), eq("\u{f728}", COMMAND)); + assert_eq!(equivalent("cmd+escape"), eq("\u{1b}", COMMAND)); + assert_eq!(equivalent("ctrl+tab"), eq("\t", CONTROL)); + assert_eq!(equivalent("cmd+space"), eq(" ", COMMAND)); +} + +#[test] +fn every_key_has_one_lowercase_character() { + let names = ["a", "z", "0", "9", "minus", "equal", "comma", "period", "slash", "semicolon", "quote", + "bracketleft", "bracketright", "backslash", "backquote", "f1", "f24", "escape", "enter", "space", "tab", + "backspace", "delete", "insert", "home", "end", "pageup", "pagedown", "left", "right", "up", "down"]; + for name in names { + let (key, _) = equivalent(&format!("cmd+{name}")); + assert_eq!(key.chars().count(), 1, "{name}: {key:?}"); + assert_eq!(key.to_lowercase(), key, "{name}: a capital would add Shift"); + } +} + +#[test] +fn menu_keycaps_show_the_accelerator() { + let caps = |s: &str| s.parse::<Shortcut>().unwrap().menu_keycaps(); + let mac = cfg!(target_os = "macos"); + assert_eq!(caps("cmd+b"), [if mac { "⌘" } else { "Super" }, "B"]); + assert_eq!(caps("ctrl+cmd+f").last().unwrap(), "F"); + assert_eq!(caps("cmd+=").last().unwrap(), "="); + assert_eq!(caps("cmd+shift+z").last().unwrap(), "Z"); + assert_eq!(caps("ctrl+f5").last().unwrap(), "F5"); + assert_eq!(caps("ctrl+left").last().unwrap(), "←"); +} + +/// Dvorak's characters at QWERTY positions, by Carbon key code, under any modifiers. +#[cfg(target_os = "macos")] +fn dvorak(key: u32, _modifiers: u32) -> Option<String> { + Some(match key { 11 => "x", 45 => "b", 3 => "u", 16 => "f", 15 => "p", 1 => "o", 6 => ";", 24 => "]", 27 => "[", _ => return None }.into()) +} + +#[cfg(target_os = "macos")] +#[test] +fn dvorak_moves_keycaps_but_not_menu_equivalents() { + crate::shortcuts::force_layout(Some(dvorak)); + let shortcut = |s: &str| s.parse::<Shortcut>().unwrap(); + // Layout labels follow the key's position: QWERTY B types "x" on Dvorak. + assert_eq!(shortcut("cmd+b").keycaps(), ["⌘", "X"]); + assert_eq!(shortcut("cmd+=").keycaps(), ["⌘", "]"]); + for (accelerator, key, mask) in [("cmd+b", "b", COMMAND), ("cmd+=", "=", COMMAND), ("cmd+-", "-", COMMAND), + ("cmd+r", "r", COMMAND), ("ctrl+cmd+s", "s", CONTROL | COMMAND), ("ctrl+cmd+f", "f", CONTROL | COMMAND), + ("cmd+shift+z", "z", SHIFT | COMMAND), ("cmd+left", "\u{f702}", COMMAND), ("f5", "\u{f708}", 0)] { + assert_eq!(equivalent(accelerator), eq(key, mask), "{accelerator}"); + let caps = shortcut(accelerator).menu_keycaps(); + let label = caps.last().unwrap(); + assert!(key.chars().all(|c| c as u32 >= 0xf700) || *label == key.to_uppercase(), "{accelerator}: {caps:?}"); + } + crate::shortcuts::force_layout(None); +} diff --git a/app/vendor/rune/crates/rune/src/native_menu/macos.rs b/app/vendor/rune/crates/rune/src/native_menu/macos.rs new file mode 100644 index 0000000..83aa682 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/native_menu/macos.rs @@ -0,0 +1,230 @@ +//! Main-thread AppKit adapter. Adds one optional selector to winit's existing delegate; +//! never replaces the delegate or any existing method. The hook returns nil after teardown. + +#![allow(unsafe_code)] + +use super::{Description, Location, MenuError}; +use std::{cell::{Cell, RefCell}, ffi::{c_char, c_void}, sync::Arc}; +use objc2::{DefinedClass, MainThreadMarker, MainThreadOnly, define_class, msg_send, sel, rc::Retained, + runtime::{AnyClass, AnyObject, Bool, Sel}}; +use objc2_app_kit::{NSApplication, NSMenu, NSMenuItem}; +use objc2_foundation::{NSObject, NSString}; + +type Sink = Arc<dyn Fn(&str) + Send + Sync>; +struct Action { id: String, enabled: bool, keys_first: bool, sink: Sink } +define_class!( + #[unsafe(super(NSObject))] + #[thread_kind = MainThreadOnly] + #[name = "RuneNativeMenuTarget"] + #[ivars = Action] + struct MenuTarget; + + impl MenuTarget { + #[unsafe(method(runeMenuAction:))] + fn perform(&self, _sender: &NSMenuItem) { + let Action { id, enabled, keys_first, sink } = self.ivars(); + if *enabled && std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + let (id, sink) = (id.clone(), sink.clone()); + let run: Arc<dyn Fn() + Send + Sync> = Arc::new(move || sink(&id)); + if !*keys_first || !super::standard_macos::defer_key(run.clone()) { run(); } + })).is_err() { eprintln!("rune: native menu callback panicked"); } + } + #[unsafe(method(validateMenuItem:))] + fn validate(&self, _sender: &NSMenuItem) -> bool { self.ivars().enabled } + } +); + +thread_local! { + static OWNED: Cell<bool> = const { Cell::new(false) }; + static DOCK: RefCell<Option<Retained<NSMenu>>> = const { RefCell::new(None) }; + /// The jump list's Dock menu (`set_jump_list`), shown when the app's menus put nothing there. + static JUMP: RefCell<Option<(Retained<NSMenu>, Vec<Retained<MenuTarget>>)>> = const { RefCell::new(None) }; + static HOOKED: Cell<*const AnyClass> = const { Cell::new(std::ptr::null()) }; +} +unsafe extern "C" { + fn class_addMethod(class: *const AnyClass, selector: Sel, implementation: *const c_void, types: *const c_char) -> Bool; +} +extern "C" fn dock_menu(_: *mut AnyObject, _: Sel, _: *mut AnyObject) -> *mut AnyObject { + DOCK.with(|slot| slot.try_borrow().ok().and_then(|s| s.as_ref().map(|m| &**m as *const NSMenu as *mut AnyObject))) + .or_else(|| JUMP.with(|slot| slot.try_borrow().ok().and_then(|s| s.as_ref().map(|(m, _)| &**m as *const NSMenu as *mut AnyObject)))) + .unwrap_or(std::ptr::null_mut()) +} + +/// The jump list as the Dock menu: its tasks, then each category under a disabled title. A pick +/// arrives as a link the app opens (`App::on_open_url`), as a Windows jump list entry does. +pub(crate) fn set_jump_menu(list: &crate::jump_list::JumpList) { + let Some(mtm) = MainThreadMarker::new() else { return }; + let app = NSApplication::sharedApplication(mtm); + if install_dock_hook(&app).is_err() { return; } + let sink: Sink = Arc::new(|argument: &str| crate::open_url::incoming::receive(argument.to_owned())); + let menu = NSMenu::new(mtm); + let mut targets = Vec::new(); + // SAFETY: AppKit calls on the main thread; each item's target is kept in JUMP for as long as + // the menu holds the item. + unsafe { + let mut add = |title: &str, argument: Option<&str>| { + let item = NSMenuItem::initWithTitle_action_keyEquivalent(mtm.alloc(), &NSString::from_str(title), argument.map(|_| sel!(runeMenuAction:)), &NSString::from_str("")); + if let Some(argument) = argument { + let target: Retained<MenuTarget> = msg_send![super(mtm.alloc().set_ivars(Action { id: argument.to_owned(), enabled: true, keys_first: false, sink: sink.clone() })), init]; + item.setTarget(Some(&target)); + targets.push(target); + } else { + item.setEnabled(false); + } + menu.addItem(&item); + }; + for task in &list.tasks { add(&task.title, Some(&task.argument)); } + for (name, items) in &list.categories { + if menu.numberOfItems() > 0 { menu.addItem(&NSMenuItem::separatorItem(mtm)); } + add(name, None); + for item in items { add(&item.title, Some(&item.argument)); } + } + } + JUMP.with(|slot| *slot.borrow_mut() = Some((menu, targets))); +} +fn install_dock_hook(app: &NSApplication) -> Result<(), MenuError> { + // SAFETY: AppKit calls and Objective-C runtime mutation occur only on the main thread. + // The added selector has the exact NSObject*, SEL, NSApplication* -> NSMenu* ABI. + unsafe { + let delegate: *mut AnyObject = msg_send![app, delegate]; + let delegate = delegate.as_ref().ok_or_else(|| MenuError::Backend("missing application delegate".into()))?; + let class = delegate.class(); + if HOOKED.with(|slot| std::ptr::eq(slot.get(), class)) { return Ok(()); } + let selector = sel!(applicationDockMenu:); + let exists: bool = msg_send![delegate, respondsToSelector: selector]; + if exists { return Err(MenuError::Backend("application delegate already supplies a Dock menu".into())); } + if !class_addMethod(class, selector, dock_menu as *const c_void, c"@@:@".as_ptr()).as_bool() { + return Err(MenuError::Backend("could not install Dock menu hook".into())); + } + HOOKED.with(|slot| slot.set(class)); + // Refresh AppKit's optional-selector cache, retaining the exact winit delegate. + let _: () = msg_send![app, setDelegate: delegate]; + } + Ok(()) +} + +pub(super) struct Native { + mtm: MainThreadMarker, + entries: Vec<(Retained<NSMenu>, Retained<NSMenuItem>)>, + /// Top-level menus it made, in their menu bars. + tops: Vec<(Retained<NSMenu>, Retained<NSMenuItem>)>, + targets: Vec<Retained<MenuTarget>>, +} +impl Native { + pub(super) fn new() -> Result<Self, MenuError> { + let mtm = MainThreadMarker::new().ok_or_else(|| MenuError::Backend("menus require the main thread".into()))?; + if OWNED.with(|owned| owned.replace(true)) { return Err(MenuError::InUse); } + Ok(Self { mtm, entries: Vec::new(), tops: Vec::new(), targets: Vec::new() }) + } + fn clear(&mut self) { + for (menu, item) in self.entries.drain(..) { + // SAFETY: AppKit's target is non-retaining. Clear it before releasing our target, + // even if a currently tracking menu keeps the removed item alive. + unsafe { item.setTarget(None); item.setAction(None); menu.removeItem(&item); } + } + // A menu the standard items joined stays for them. + for (root, top) in self.tops.drain(..) { super::default_macos::remove_top_if_empty(&root, &top); } + self.targets.clear(); + DOCK.with(|slot| *slot.borrow_mut() = None); + super::default_macos::sync_standard(&NSApplication::sharedApplication(self.mtm)); + } + pub(super) fn set(&mut self, descriptions: &[Description], sink: Sink) -> Result<(), MenuError> { + // SAFETY: self carries a main-thread marker. All menus/items are owned here or + // retained from AppKit, indices are bounded, and targets outlive their items. + unsafe { + let app = NSApplication::sharedApplication(self.mtm); + if descriptions.iter().any(|d| d.location == Location::Dock) { install_dock_hook(&app)?; } + // Construct all targets before removing the previous snapshot. + let prepared: Vec<_> = descriptions.iter().map(|d| { + if d.separator { return (d, NSMenuItem::separatorItem(self.mtm), None); } + // SAFETY: NSObject initialization follows set_ivars; the main-thread target is + // kept alive until its menu item is removed and its non-retaining target cleared. + let target: Retained<MenuTarget> = msg_send![super(self.mtm.alloc().set_ivars(Action { + id: d.id.clone(), enabled: d.enabled, keys_first: d.keys_first, sink: sink.clone(), + })), init]; + let item = NSMenuItem::initWithTitle_action_keyEquivalent(self.mtm.alloc(), + &NSString::from_str(&d.title), Some(sel!(runeMenuAction:)), &NSString::from_str("")); + item.setTarget(Some(&target)); + item.setEnabled(d.enabled); + item.setState(if d.checked { 1 } else { 0 }); + super::set_key_equivalent(&item, d.equivalent.as_ref()); + (d, item, Some(target)) + }).collect(); + self.clear(); + super::default_macos::adding(&app, || { + let mut app_index = 0; + // Items placed so far by id, and the last one placed after each anchor. + let mut placed: Vec<(&str, Retained<NSMenuItem>)> = Vec::new(); + let mut chained: Vec<(&str, Retained<NSMenuItem>)> = Vec::new(); + for (d, item, target) in prepared { + let location = &d.location; + let menu = if *location == Location::Dock { + DOCK.with(|slot| slot.borrow_mut().get_or_insert_with(|| NSMenu::new(self.mtm)).clone()) + } else { + let root = super::ensure_default_menu(&app); + // An app-supplied empty root is preserved. Reserve its first slot for + // the app menu even when a named-menu item appears first in the snapshot. + if root.numberOfItems() == 0 { self.add_top(&root, "Application"); } + match location { + Location::App => { + if let Some(first) = (root.numberOfItems() > 0).then(|| root.itemAtIndex(0)).flatten().and_then(|i| i.submenu()) { first } + else { self.add_top(&root, "Application") } + } + Location::Named(name) => { + let existing = (0..root.numberOfItems()).filter_map(|i| root.itemAtIndex(i)) + .find(|i| super::default_macos::name(i) == *name).and_then(|i| i.submenu()); + existing.unwrap_or_else(|| self.add_top(&root, name)) + } + Location::Dock => unreachable!(), + } + }; + let anchor = d.after.as_deref().and_then(|a| anchor_index(&menu, a, &placed, &chained).map(|i| (a, i))); + if let Some((a, index)) = anchor { + menu.insertItem_atIndex(&item, index + 1); + chained.retain(|(c, _)| *c != a); + chained.push((a, item.clone())); + } else if *location == Location::App { + // App items follow the app menu's About item, where AppKit apps list Check + // for Updates… and Settings…; an app menu without one takes them first. + let first = (menu.numberOfItems() > 0).then(|| menu.itemAtIndex(0)).flatten(); + let about = first.and_then(|i| i.action()) == Some(sel!(orderFrontStandardAboutPanel:)); + menu.insertItem_atIndex(&item, app_index + isize::from(about)); + app_index += 1; + } else { + menu.addItem(&item); + } + if !d.separator { placed.push((&d.id, item.clone())); } + self.entries.push((menu, item)); self.targets.extend(target); + } + }); + // Each menu reads the app's way; the bar keeps the system's order of its menus. + if let Some(root) = app.mainMenu() { + for top in (0..root.numberOfItems()).filter_map(|i| root.itemAtIndex(i)).filter_map(|i| i.submenu()) { + super::set_layout_direction(&top); + } + } + Ok(()) + } + } + fn add_top(&mut self, root: &Retained<NSMenu>, name: &str) -> Retained<NSMenu> { + let (top, menu) = super::default_macos::add_top(self.mtm, root, name); + self.tops.push((root.clone(), top)); + menu + } +} + +/// Where `MenuItem::after`'s `anchor` is in `menu`: the last item already placed after it, else +/// this app's item with that id, else a native item with that AppKit action. +fn anchor_index(menu: &NSMenu, anchor: &str, placed: &[(&str, Retained<NSMenuItem>)], chained: &[(&str, Retained<NSMenuItem>)]) -> Option<isize> { + let index_of = |item: &NSMenuItem| Some(menu.indexOfItem(item)).filter(|&i| i >= 0); + let find = |list: &[(&str, Retained<NSMenuItem>)]| list.iter().filter(|(a, _)| *a == anchor).find_map(|(_, item)| index_of(item)); + find(chained).or_else(|| find(placed)).or_else(|| { + (0..menu.numberOfItems()).find(|&i| menu.itemAtIndex(i).and_then(|item| item.action()).is_some_and(|a| a.name().to_str() == Ok(anchor))) + }) +} +impl Drop for Native { + fn drop(&mut self) { + self.clear(); + OWNED.with(|owned| owned.set(false)); + } +} diff --git a/app/vendor/rune/crates/rune/src/native_menu/mod.rs b/app/vendor/rune/crates/rune/src/native_menu/mod.rs new file mode 100644 index 0000000..fcdd059 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/native_menu/mod.rs @@ -0,0 +1,574 @@ +//! Native application and Dock menus. One App owns the process-wide custom menu at a time: +//! the one whose window last took focus, so with a window per App (`run_windows`) the menu bar +//! holds the key window's items and they act in it. Default AppKit/winit items are preserved. +//! Other native platforms return Unsupported; headless scripts use the same item lookup and +//! action dispatch on every platform. +use std::sync::{Arc, Mutex, Weak}; +use crate::machine::{Attempt, Seq}; +use crate::{App, AppHandle, Shortcut, Tx, app::Shared}; + +#[cfg(target_os = "macos")] +mod macos; +#[cfg(target_os = "macos")] +mod default_macos; +#[cfg_attr(not(target_os = "macos"), allow(dead_code))] +mod key_equivalent; +#[cfg(test)] +mod key_equivalent_tests; +#[cfg_attr(not(target_os = "macos"), allow(dead_code))] +mod standard; +#[cfg(target_os = "macos")] +mod standard_macos; +#[cfg(target_os = "macos")] +pub(crate) use default_macos::{ensure as ensure_default_menu, promote as promote_default_menu, set_layout_direction}; +#[cfg(target_os = "macos")] +pub(crate) use standard_macos::{adopt as adopt_standard_view, install as install_standard_menus}; +#[cfg(target_os = "macos")] +pub(crate) use key_equivalent::set_key_equivalent; + +#[derive(Clone, Debug, PartialEq, Eq)] +enum Location { App, Named(String), Dock } + +#[derive(Clone)] +struct Description { + id: String, + title: String, + location: Location, + after: Option<String>, + equivalent: Option<Shortcut>, + keys_first: bool, + enabled: bool, + checked: bool, + separator: bool, +} + +/// A custom native item. Defaults to the app menu (after its About item, in the order given), +/// enabled and unchecked, with its title as id. +pub struct MenuItem<S> { description: Description, action: fn(&mut S, &mut Tx) } +impl<S> Clone for MenuItem<S> { + fn clone(&self) -> Self { Self { description: self.description.clone(), action: self.action } } +} +impl<S> MenuItem<S> { + pub fn new(title: impl Into<String>, action: fn(&mut S, &mut Tx)) -> Self { + let title = title.into(); + Self { description: Description { id: title.clone(), title, location: Location::App, after: None, + equivalent: None, keys_first: false, enabled: true, checked: false, separator: false }, action } + } + /// A separator line, placed with `menu` or `dock` like an item. It has no id or title, + /// can't be fired, and needs no unique id. + pub fn separator() -> Self { + let mut item = Self::new("", |_, _| {}); + item.description.separator = true; + item + } + pub fn id(mut self, id: impl Into<String>) -> Self { self.description.id = id.into(); self } + /// Place this item in a named top-level menu. Existing native menus are reused. A menu + /// Rune makes is titled with the app's `Label::Menu(name)`, so the name stays the same in + /// every language (`rune::set_labels`). + pub fn menu(mut self, title: impl Into<String>) -> Self { self.description.location = Location::Named(title.into()); self } + pub fn dock(mut self) -> Self { self.description.location = Location::Dock; self } + /// Place this item right after `anchor` in its menu: another of this app's items by id, or + /// a native item by its AppKit action (`"paste:"`, `"selectAll:"`), as Electron's menu + /// items name the item they follow. Items after the same anchor keep the order given. A + /// menu without the anchor takes the item at its end, as without one. + pub fn after(mut self, anchor: impl Into<String>) -> Self { self.description.after = Some(anchor.into()); self } + pub fn key_equivalent(mut self, shortcut: Shortcut) -> Self { self.description.equivalent = Some(shortcut); self } + /// Let the window's own key handling see this item's key equivalent first. AppKit gives a + /// menu equivalent to the menu before any view, so by default the item takes the chord + /// even while a field, a modal or `on_key` wants it. With this, the press goes to the key + /// window like any other key (the focused element, then modals, then `on_key`), and the + /// item runs only if no handler takes it. Picking the item in the menu always runs it. + pub fn keys_first(mut self) -> Self { self.description.keys_first = true; self } + pub fn enabled(mut self, enabled: bool) -> Self { self.description.enabled = enabled; self } + pub fn checked(mut self, checked: bool) -> Self { self.description.checked = checked; self } +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum MenuError { + Unsupported, + NotRunning, + InUse, + Invalid(String), + UnknownItem(String), + AmbiguousTitle(String), + Disabled(String), + Backend(String), +} +impl std::fmt::Display for MenuError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::Unsupported => f.write_str("native menus are unsupported on this platform"), + Self::NotRunning => f.write_str("the menu's app is not running"), + Self::InUse => f.write_str("another Rune app owns the native menu"), + Self::Invalid(message) => write!(f, "invalid menu: {message}"), + Self::UnknownItem(item) => write!(f, "unknown menu item: {item}"), + Self::AmbiguousTitle(item) => write!(f, "ambiguous menu title: {item}; use its id"), + Self::Disabled(item) => write!(f, "menu item is disabled: {item}"), + Self::Backend(message) => write!(f, "native menu: {message}"), + } + } +} +impl std::error::Error for MenuError {} + +/// Whether an App's window is running, and whether it runs with no native menu bar. +enum Presence { + /// No window of the App runs: `set_menu` says NotRunning and a click goes nowhere. + Absent, + /// A window runs. Headless runs the menu actions on the state thread with no bar. + Running { headless: bool }, +} +impl Presence { + fn running(&self) -> bool { matches!(self, Self::Running { .. }) } + fn headless(&self) -> bool { matches!(self, Self::Running { headless: true }) } +} + +struct CoreState { + descriptions: Vec<Description>, + /// Incremented whenever `descriptions` is cleared without holding the typed actions lock, so + /// the typed table discards stale actions before its next read or write. + clear_gen: u64, + /// Each new set of items is a new attempt: a click on an item from an earlier set, or a + /// guard that drained one, is stale. It is the version of `descriptions`, so it outlives a run. + revision: Seq, + presence: Presence, + errors: Vec<MenuError>, +} + +impl CoreState { + fn clear(&mut self) { + self.descriptions.clear(); + self.clear_gen += 1; + } + + fn check_set(&self, descriptions: &[Description]) -> Result<(), MenuError> { + if !cfg!(target_os = "macos") && !self.presence.headless() { return Err(MenuError::Unsupported); } + if !self.presence.running() { return Err(MenuError::NotRunning); } + validate(descriptions) + } +} + +struct HubCore { + state: Mutex<CoreState>, +} + +impl Default for HubCore { + fn default() -> Self { + Self { + state: Mutex::new(CoreState { + descriptions: Vec::new(), + clear_gen: 0, + revision: Seq::default(), + presence: Presence::Absent, + errors: Vec::new(), + }), + } + } +} + +impl HubCore { + fn take_errors(&self) -> Vec<MenuError> { + std::mem::take(&mut self.state.lock().unwrap().errors) + } +} + +pub(crate) struct Hub<S> { + core: Arc<HubCore>, + actions: Mutex<(u64, Vec<fn(&mut S, &mut Tx)>)>, +} + +impl<S> Default for Hub<S> { + fn default() -> Self { + Self { core: Arc::default(), actions: Mutex::new((0, Vec::new())) } + } +} + +impl<S> Hub<S> { + fn push(&self, item: MenuItem<S>) { + let mut state = self.core.state.lock().unwrap(); + let mut actions = self.actions.lock().unwrap(); + if actions.0 != state.clear_gen { + actions.1.clear(); + actions.0 = state.clear_gen; + } + state.descriptions.push(item.description); + actions.1.push(item.action); + state.revision.next(); + } + + fn set(&self, descriptions: Vec<Description>, new_actions: Vec<fn(&mut S, &mut Tx)>) -> Result<(), MenuError> { + let mut state = self.core.state.lock().unwrap(); + state.check_set(&descriptions)?; + let mut actions = self.actions.lock().unwrap(); + state.descriptions = descriptions; + *actions = (state.clear_gen, new_actions); + state.revision.next(); + Ok(()) + } + + fn resolve_action(&self, revision: Attempt, id: &str) -> Option<fn(&mut S, &mut Tx)> { + let state = self.core.state.lock().unwrap(); + if !state.presence.running() || state.revision.current() != revision { return None; } + let index = lookup(&state, id).ok()?; + let actions = self.actions.lock().unwrap(); + (actions.0 == state.clear_gen).then(|| actions.1.get(index).copied()).flatten() + } +} + +fn validate(descriptions: &[Description]) -> Result<(), MenuError> { + let mut ids = std::collections::HashSet::new(); + for d in descriptions { + if matches!(&d.location, Location::Named(title) if title.trim().is_empty()) { return Err(MenuError::Invalid("empty menu title".into())); } + if d.separator { continue; } + if d.id.trim().is_empty() || d.title.trim().is_empty() { return Err(MenuError::Invalid("empty id or title".into())); } + if !ids.insert(&d.id) { return Err(MenuError::Invalid(format!("duplicate id {}", d.id))); } + } + Ok(()) +} + +impl<S: 'static> App<S> { + /// Add a custom native item at startup. Deferred failures (including Unsupported on + /// Windows/Linux) are available through AppHandle::take_menu_errors(). + pub fn menu_item(self, item: MenuItem<S>) -> Self { + self.shared.menus.push(item); + self + } +} +impl<S: 'static> AppHandle<S> { + /// Replace all this App's custom items, preserving native defaults. Validates and queues + /// the new snapshot; enabled/checked changes reach AppKit on the next event-loop drain. + /// Native installation failures are retained by take_menu_errors(). On Windows/Linux this + /// returns Unsupported without changing anything (except inside a headless run). On macOS + /// the menus and standard items Rune made also take the app's current labels + /// (`rune::set_labels`), so an app calls this again after its language changes. + pub fn set_menu(&self, items: impl IntoIterator<Item = MenuItem<S>>) -> Result<(), MenuError> { + let (descriptions, actions): (Vec<_>, Vec<_>) = items.into_iter().map(|i| (i.description, i.action)).unzip(); + self.shared.menus.set(descriptions, actions)?; + self.shared.core.wake(); + Ok(()) + } + #[inline] + pub fn take_menu_errors(&self) -> Vec<MenuError> { + self.shared.menus.core.take_errors() + } +} + +fn lookup(state: &CoreState, selector: &str) -> Result<usize, MenuError> { + if !state.presence.running() { return Err(MenuError::NotRunning); } + let items = state.descriptions.iter().enumerate().filter(|(_, d)| !d.separator); + let index = if let Some((index, _)) = items.clone().find(|(_, d)| d.id == selector) { index } + else { + let mut matches = items.filter(|(_, d)| d.title == selector); + let index = matches.next().ok_or_else(|| MenuError::UnknownItem(selector.into()))?.0; + if matches.next().is_some() { return Err(MenuError::AmbiguousTitle(selector.into())); } + index + }; + if !state.descriptions[index].enabled { return Err(MenuError::Disabled(selector.into())); } + Ok(index) +} + +/// The window host, for a key press it maps to `key`: what to do if no handler takes it, when +/// a menu item (a standard ⌘W or ⌘M, or `MenuItem::keys_first`) is handing Rune that key. +/// The jump list as the Dock menu (`set_jump_list` on macOS). +#[cfg(target_os = "macos")] +pub(crate) fn set_jump_menu(list: &crate::jump_list::JumpList) { + macos::set_jump_menu(list); +} + +pub(crate) fn take_unhandled(key: Option<&crate::KeyEvent>) -> Option<crate::runtime::Unhandled> { + #[cfg(target_os = "macos")] + { key.and_then(standard_macos::take_unhandled) } + #[cfg(not(target_os = "macos"))] + { let _ = key; None } +} + +type Dispatch = Arc<dyn Fn(Attempt, String) + Send + Sync>; + +fn enqueue_core(core: &HubCore, dispatch: &dyn Fn(Attempt, String), selector: &str, expected: Option<Attempt>) -> Result<(), MenuError> { + let state = core.state.lock().unwrap(); + let revision = state.revision.current(); + if expected.is_some_and(|r| r != revision) { return Ok(()); } + let index = lookup(&state, selector)?; + let id = state.descriptions[index].id.clone(); + drop(state); + dispatch(revision, id); + Ok(()) +} + +fn dispatch_typed<S: 'static>(shared: &Arc<Shared<S>>, revision: Attempt, id: String) { + let weak = Arc::downgrade(shared); + AppHandle { shared: shared.clone() }.update(move |s, tx| { + let Some(shared) = weak.upgrade() else { return }; + if let Some(action) = shared.menus.resolve_action(revision, &id) { + action(s, tx); + } + }); +} + +#[cfg(test)] +pub(crate) fn fire<S: 'static>(shared: &Arc<Shared<S>>, selector: &str) -> Result<(), MenuError> { + enqueue_core(&shared.menus.core, &|revision, id| dispatch_typed(shared, revision, id), selector, None) +} + +/// Who holds the macOS menu bar's custom items: nobody, or the guard of the App whose window +/// last took focus (`MenuGuard::claim`), with the items it put there. +#[cfg(target_os = "macos")] +enum Bar { + Free, + Owned { guard: u64, native: macos::Native }, +} + +#[cfg(target_os = "macos")] +thread_local! { + static BAR: std::cell::RefCell<Bar> = const { std::cell::RefCell::new(Bar::Free) }; + static NEXT_GUARD: std::cell::Cell<u64> = const { std::cell::Cell::new(1) }; +} + +pub(crate) struct MenuGuard { + core: Weak<HubCore>, + dispatch: Dispatch, + /// Whether the bar holds this guard's items. + placed: Placed, + /// This guard's name in `BAR`. + #[cfg(target_os = "macos")] + id: u64, +} + +/// Where this guard's items stand: not in the bar yet, or the set it last put there. +#[derive(Clone, Copy)] +enum Placed { + /// Its first drain, or another App's window took the bar since. + Fresh, + /// The bar holds the items of this revision. + Synced(Attempt), +} + +impl MenuGuard { + pub(crate) fn attach<S: 'static>(shared: &Arc<Shared<S>>, headless: bool) -> Self { + let weak = Arc::downgrade(shared); + let dispatch: Dispatch = Arc::new(move |revision, id| { + if let Some(shared) = weak.upgrade() { + dispatch_typed(&shared, revision, id); + } + }); + Self::attach_core(&shared.menus.core, dispatch, headless) + } + + fn attach_core(core: &Arc<HubCore>, dispatch: Dispatch, headless: bool) -> Self { + let mut state = core.state.lock().unwrap(); + state.presence = Presence::Running { headless }; + if let Err(error) = validate(&state.descriptions) { + state.clear(); + state.errors.push(error); + } + drop(state); + let mut guard = Self { + core: Arc::downgrade(core), + dispatch, + placed: Placed::Fresh, + #[cfg(target_os = "macos")] + id: NEXT_GUARD.with(|n| n.replace(n.get() + 1)), + }; + guard.drain(); + guard + } + + pub(crate) fn fire(&self, selector: &str) -> Result<(), MenuError> { + let Some(core) = self.core.upgrade() else { return Err(MenuError::NotRunning) }; + enqueue_core(&core, &*self.dispatch, selector, None) + } + + /// This App's window took focus: its items take the menu bar, so they act in it. An App + /// without items of its own leaves the bar to the one that has it. + pub(crate) fn claim(&mut self) { + #[cfg(target_os = "macos")] + { + let Some(core) = self.core.upgrade() else { return }; + let state = core.state.lock().unwrap(); + if state.presence.headless() || state.descriptions.is_empty() { return; } + drop(state); + let taken = BAR.with(|bar| match &*bar.borrow() { + Bar::Owned { guard, .. } => *guard != self.id, + Bar::Free => true, + }); + if taken { + // The previous holder's items leave with its `Native`, before this one's go in. + BAR.with(|bar| *bar.borrow_mut() = Bar::Free); + self.placed = Placed::Fresh; + self.drain(); + } + } + } + + pub(crate) fn drain(&mut self) { + let Some(core) = self.core.upgrade() else { return }; + let state = core.state.lock().unwrap(); + if matches!(self.placed, Placed::Synced(at) if at == state.revision.current()) { return; } + let (descriptions, revision, headless) = (state.descriptions.clone(), state.revision.current(), state.presence.headless()); + drop(state); + let result = validate(&descriptions).and_then(|()| { + if headless { return Ok(()); } + #[cfg(target_os = "macos")] + { + let weak = self.core.clone(); + let dispatch = self.dispatch.clone(); + let sink = Arc::new(move |id: &str| { + if let Some(core) = weak.upgrade() + && let Err(error) = enqueue_core(&core, &*dispatch, id, Some(revision)) + { + eprintln!("rune: {error}"); + } + }); + BAR.with(|bar| { + let mut bar = bar.borrow_mut(); + let (next, result) = match std::mem::replace(&mut *bar, Bar::Free) { + // Another window's App has the bar until this one's window takes focus. + Bar::Owned { guard, native } if guard != self.id => (Bar::Owned { guard, native }, Ok(())), + // Dropping the `Native` takes its items out. + Bar::Owned { .. } | Bar::Free if descriptions.is_empty() => (Bar::Free, Ok(())), + Bar::Owned { mut native, .. } => { + let result = native.set(&descriptions, sink); + (Bar::Owned { guard: self.id, native }, result) + } + Bar::Free => match macos::Native::new() { + Ok(mut native) => { + let result = native.set(&descriptions, sink); + (Bar::Owned { guard: self.id, native }, result) + } + Err(error) => (Bar::Free, Err(error)), + }, + }; + *bar = next; + result + }) + } + #[cfg(not(target_os = "macos"))] + { if descriptions.is_empty() { Ok(()) } else { Err(MenuError::Unsupported) } } + }); + // The app's labels may have changed with its language since the menus were made. + #[cfg(target_os = "macos")] + if !headless && let Some(mtm) = objc2::MainThreadMarker::new() { + default_macos::relabel(&objc2_app_kit::NSApplication::sharedApplication(mtm)); + } + self.placed = Placed::Synced(revision); + if let Err(error) = result { + eprintln!("rune: {error}"); + core.state.lock().unwrap().errors.push(error); + } + } +} + +impl Drop for MenuGuard { + fn drop(&mut self) { + if let Some(core) = self.core.upgrade() { + let mut state = core.state.lock().unwrap(); + state.presence = Presence::Absent; + state.clear(); + } + // The bar waits for the next window to take focus (`claim`). + #[cfg(target_os = "macos")] + BAR.try_with(|bar| { + let mut bar = bar.borrow_mut(); + if matches!(&*bar, Bar::Owned { guard, .. } if *guard == self.id) { *bar = Bar::Free; } + }).ok(); + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::{AppSpec, el}; + fn app() -> App<Vec<u32>> { App::new(AppSpec::new("menu", (100.0, 100.0), Vec::new, |_, _| el())) } + fn item(id: &str) -> MenuItem<Vec<u32>> { MenuItem::new("Open Quick Panel", |s: &mut Vec<u32>, _| s.push(1)).id(id) } + fn drain(app: &App<Vec<u32>>, s: &mut Vec<u32>) { + for update in app.shared.take().updates { update(s, &mut Tx::default()); } + } + + #[test] + fn title_and_id_dispatch_on_the_state_thread_with_reentrant_menu_updates() { + let app = app().menu_item(item("quick")).menu_item(MenuItem::new("Dock", |s: &mut Vec<u32>, tx| { s.push(2); tx.quit(); }).dock()); + let _guard = MenuGuard::attach(&app.shared, true); + let handle = app.handle(); + let shared = app.shared.clone(); + std::thread::spawn(move || fire(&shared, "Open Quick Panel").unwrap()).join().unwrap(); + let mut state = Vec::new(); + assert!(state.is_empty()); + drain(&app, &mut state); + assert_eq!(state, [1]); + fire(&app.shared, "quick").unwrap(); + drain(&app, &mut state); + assert_eq!(state, [1, 1]); + let h = handle.clone(); + handle.update(move |_, _| h.set_menu([item("replacement").checked(true)]).unwrap()); + drain(&app, &mut state); + assert_eq!(app.shared.menus.core.state.lock().unwrap().descriptions[0].id, "replacement"); + } + + #[test] + fn replacement_disable_and_shutdown_cancel_stale_actions() { + let app = app().menu_item(item("quick")); + let guard = MenuGuard::attach(&app.shared, true); + let handle = app.handle(); + fire(&app.shared, "quick").unwrap(); + handle.set_menu([item("quick").enabled(false).checked(true)]).unwrap(); + let mut state = Vec::new(); drain(&app, &mut state); + assert!(state.is_empty()); + assert_eq!(fire(&app.shared, "quick"), Err(MenuError::Disabled("quick".into()))); + assert!(app.shared.menus.core.state.lock().unwrap().descriptions[0].checked); + handle.set_menu([item("quick")]).unwrap(); + fire(&app.shared, "quick").unwrap(); + drop(guard); drain(&app, &mut state); + assert!(state.is_empty()); + assert_eq!(fire(&app.shared, "quick"), Err(MenuError::NotRunning)); + } + + #[test] + fn validation_is_atomic_and_ambiguous_titles_require_ids() { + let app = app().menu_item(item("first")).menu_item(item("second").menu("Tools")); + let _guard = MenuGuard::attach(&app.shared, true); + assert_eq!(fire(&app.shared, "Open Quick Panel"), Err(MenuError::AmbiguousTitle("Open Quick Panel".into()))); + assert!(fire(&app.shared, "first").is_ok()); + assert!(matches!(app.handle().set_menu([item("duplicate"), item("duplicate")]), Err(MenuError::Invalid(_)))); + assert_eq!(app.shared.menus.core.state.lock().unwrap().descriptions.len(), 2); + assert!(matches!(fire(&app.shared, "missing"), Err(MenuError::UnknownItem(_)))); + let invalid = self::app().menu_item(item("same")).menu_item(item("same")); + let _guard = MenuGuard::attach(&invalid.shared, true); + assert!(matches!(invalid.handle().take_menu_errors().as_slice(), [MenuError::Invalid(_)])); + assert!(matches!(fire(&invalid.shared, "same"), Err(MenuError::UnknownItem(_)))); + } + + #[test] + fn separators_need_no_ids_and_never_fire() { + let file = |title: &str| MenuItem::new(title, |s: &mut Vec<u32>, _| s.push(3)).menu("File"); + let app = app().menu_item(file("New")).menu_item(MenuItem::separator().menu("File")) + .menu_item(file("Close")).menu_item(MenuItem::separator().menu("File")).menu_item(MenuItem::separator().dock()); + let _guard = MenuGuard::attach(&app.shared, true); + assert!(app.handle().take_menu_errors().is_empty()); + assert_eq!(fire(&app.shared, ""), Err(MenuError::UnknownItem(String::new()))); + fire(&app.shared, "Close").unwrap(); + let mut state = Vec::new(); drain(&app, &mut state); + assert_eq!(state, [3]); + app.handle().set_menu([file("New"), MenuItem::separator().menu("File"), MenuItem::separator().menu("File")]).unwrap(); + assert!(app.shared.menus.core.state.lock().unwrap().descriptions[1].separator); + assert!(matches!(app.handle().set_menu([MenuItem::separator().menu(" ")]), Err(MenuError::Invalid(_)))); + } + + #[test] + fn equivalent_and_non_send_state_remain_builder_compatible() { + fn send_sync<T: Send + Sync>() {} + send_sync::<AppHandle<std::rc::Rc<()>>>(); + let shortcut: Shortcut = "cmd+shift+k".parse().unwrap(); + let item = item("quick").key_equivalent(shortcut.clone()); + assert_eq!(item.description.equivalent, Some(shortcut)); + assert!(!item.description.keys_first && item.keys_first().description.keys_first); + } + + #[cfg(not(target_os = "macos"))] + #[test] + fn unsupported_native_platform_is_a_noop_but_headless_works() { + let app = app().menu_item(item("quick")); + let _guard = MenuGuard::attach(&app.shared, false); + assert_eq!(app.handle().take_menu_errors(), [MenuError::Unsupported]); + assert_eq!(app.handle().set_menu([item("other")]), Err(MenuError::Unsupported)); + assert_eq!(app.shared.menus.core.state.lock().unwrap().descriptions[0].id, "quick"); + } +} diff --git a/app/vendor/rune/crates/rune/src/native_menu/standard.rs b/app/vendor/rune/crates/rune/src/native_menu/standard.rs new file mode 100644 index 0000000..e297c1d --- /dev/null +++ b/app/vendor/rune/crates/rune/src/native_menu/standard.rs @@ -0,0 +1,230 @@ +//! The standard items `App::standard_menus` installs on macOS, and a regular app gets with +//! winit's default menu: an Edit menu and a Window menu with Minimize and Close, each sent to +//! the first responder (nil target). Plain data and routing decisions, testable on every +//! platform; `standard_macos` installs them. + +/// What a standard item does. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum Role { Undo, Redo, Cut, Copy, Paste, SelectAll, Minimize, Close } + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct Standard { + pub role: Role, + /// The top-level menu it goes in, reused if the menu bar already has one by that title. + pub menu: &'static str, + pub title: &'static str, + /// The AppKit action sent to the first responder. + pub action: &'static str, + /// Its key equivalent with Command, and Shift when `shift`. + pub key: char, + pub shift: bool, + pub separator_before: bool, + /// The ANSI virtual key code of `key`, for a key event made when a click picks the item. + pub key_code: u16, +} + +const fn item(role: Role, menu: &'static str, title: &'static str, action: &'static str, key: char, key_code: u16) -> Standard { + Standard { role, menu, title, action, key, shift: false, separator_before: false, key_code } +} + +/// In menu-bar order. No Quit: an app that asks before quitting owns that item. +pub(crate) const ITEMS: [Standard; 8] = [ + item(Role::Undo, "Edit", "Undo", "undo:", 'z', 0x06), + Standard { shift: true, ..item(Role::Redo, "Edit", "Redo", "redo:", 'z', 0x06) }, + Standard { separator_before: true, ..item(Role::Cut, "Edit", "Cut", "cut:", 'x', 0x07) }, + item(Role::Copy, "Edit", "Copy", "copy:", 'c', 0x08), + item(Role::Paste, "Edit", "Paste", "paste:", 'v', 0x09), + item(Role::SelectAll, "Edit", "Select All", "selectAll:", 'a', 0x00), + item(Role::Minimize, "Window", "Minimize", "performMiniaturize:", 'm', 0x2e), + item(Role::Close, "Window", "Close", "performClose:", 'w', 0x0d), +]; + +pub(crate) fn by_action(action: &str) -> Option<&'static Standard> { + ITEMS.iter().find(|i| i.action == action) +} + +impl Standard { + /// What the app calls it (`rune::set_labels`); `title` is its English. + pub(crate) fn label(&self) -> crate::Label<'static> { + match self.role { + Role::Undo => crate::Label::Undo, + Role::Redo => crate::Label::Redo, + Role::Cut => crate::Label::Cut, + Role::Copy => crate::Label::Copy, + Role::Paste => crate::Label::Paste, + Role::SelectAll => crate::Label::SelectAll, + Role::Minimize => crate::Label::Minimize, + Role::Close => crate::Label::Close, + } + } +} + +/// A key-down event as AppKit reports it: `charactersIgnoringModifiers` and its modifiers. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub(crate) struct KeyDown { pub chars: String, pub cmd: bool, pub shift: bool, pub alt: bool, pub ctrl: bool } + +impl Standard { + /// Whether `key` is this item's own equivalent, so it can reach Rune as it is. + pub(crate) fn matches(&self, key: &KeyDown) -> bool { + key.chars.to_lowercase() == self.key.to_string() && key.cmd && key.shift == self.shift && !key.alt && !key.ctrl + } +} + +/// A key equivalent as AppKit matches it: the key lowercased, a capital counting as Shift. +#[derive(Clone, Debug, PartialEq, Eq, Hash)] +pub(crate) struct Equivalent { pub key: String, pub cmd: bool, pub shift: bool, pub alt: bool, pub ctrl: bool } + +impl Equivalent { + /// `None` for an item without one. + pub(crate) fn new(key: &str, cmd: bool, shift: bool, alt: bool, ctrl: bool) -> Option<Self> { + if key.is_empty() { return None; } + let lower = key.to_lowercase(); + Some(Self { shift: shift || lower != key, key: lower, cmd, alt, ctrl }) + } +} + +impl Standard { + pub(crate) fn equivalent(&self) -> Equivalent { + Equivalent { key: self.key.to_string(), cmd: true, shift: self.shift, alt: false, ctrl: false } + } +} + +/// Where a new top-level menu named `name` goes among the menus named `tops` (index 0 the app +/// menu), in the Mac order: the app menu, File, Edit, the app's other menus, Window, Help. It +/// goes before the first menu that comes later in that order, else last. Names are the ones +/// items place themselves with, whatever language the menus' titles are in. +pub(crate) fn top_index(name: &str, tops: &[String]) -> usize { + fn rank(name: &str) -> u8 { match name { "File" => 1, "Edit" => 2, "Window" => 4, "Help" => 5, _ => 3 } } + (1..tops.len()).find(|&i| rank(&tops[i]) > rank(name)).unwrap_or(tops.len()) +} + +/// What a Rune view does with a standard action the menu sent it: always hand Rune the key, +/// as when no menu item matched, so text fields, `on_key` and shortcuts see it once. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct Route { + /// The event that fired the item, when it is the item's own equivalent; otherwise a + /// made-up ⌘-key press of the item's key (a click on the item, a remapped equivalent). + pub current: bool, + /// When no handler takes the key, close or minimize as the window's title-bar button would. + pub then_button: bool, +} + +/// `button` is whether the window has the item's title-bar button, enabled. A window without +/// one (borderless, an overlay panel) gets ⌘W and ⌘M only as keys. +pub(crate) fn route(item: &Standard, button: bool, current: Option<&KeyDown>) -> Route { + Route { + current: current.is_some_and(|key| item.matches(key)), + then_button: button && matches!(item.role, Role::Close | Role::Minimize), + } +} + +/// Whether a menu bar with these top-level menus, the first holding these actions, is the one +/// winit installs for a regular app: a lone app menu ending in Quit. A regular app whose +/// menu bar is still that gets the standard items; one that set its own is left alone. +pub(crate) fn is_winit_default(tops: usize, app_menu: &[Option<&str>]) -> bool { + tops == 1 && app_menu.first() == Some(&Some("orderFrontStandardAboutPanel:")) && app_menu.last() == Some(&Some("terminate:")) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn key(chars: &str, shift: bool) -> KeyDown { KeyDown { chars: chars.into(), cmd: true, shift, ..KeyDown::default() } } + + #[test] + fn standard_items_are_the_mac_set_without_quit() { + let plan: Vec<_> = ITEMS.iter().map(|i| (i.menu, i.title, i.action, i.key, i.shift)).collect(); + assert_eq!(plan, [ + ("Edit", "Undo", "undo:", 'z', false), + ("Edit", "Redo", "redo:", 'z', true), + ("Edit", "Cut", "cut:", 'x', false), + ("Edit", "Copy", "copy:", 'c', false), + ("Edit", "Paste", "paste:", 'v', false), + ("Edit", "Select All", "selectAll:", 'a', false), + ("Window", "Minimize", "performMiniaturize:", 'm', false), + ("Window", "Close", "performClose:", 'w', false), + ]); + assert!(ITEMS.iter().all(|i| i.action != "terminate:" && i.key != 'q')); + let mut keys: Vec<_> = ITEMS.iter().map(|i| (i.key, i.shift)).collect(); + keys.sort_unstable(); + keys.dedup(); + assert_eq!(keys.len(), ITEMS.len(), "no two items share an equivalent"); + assert_eq!(ITEMS.iter().filter(|i| i.separator_before).map(|i| i.title).collect::<Vec<_>>(), ["Cut"]); + assert_eq!(by_action("copy:").map(|i| i.role), Some(Role::Copy)); + assert_eq!(by_action("terminate:"), None); + } + + #[test] + fn key_codes_are_the_ansi_keys_of_the_letters() { + // kVK_ANSI_*: what the physical keys of these letters report on a US layout. + let codes: Vec<_> = ITEMS.iter().map(|i| (i.key, i.key_code)).collect(); + assert_eq!(codes, [('z', 6), ('z', 6), ('x', 7), ('c', 8), ('v', 9), ('a', 0), ('m', 46), ('w', 13)]); + } + + #[test] + fn close_and_minimize_are_keys_first_then_the_button() { + let close = by_action("performClose:").unwrap(); + let minimize = by_action("performMiniaturize:").unwrap(); + assert_eq!(route(close, true, Some(&key("w", false))), Route { current: true, then_button: true }); + assert_eq!(route(minimize, true, None), Route { current: false, then_button: true }); + // A borderless window or an overlay panel has no button: ⌘W stays only a key. + assert_eq!(route(close, false, Some(&key("w", false))), Route { current: true, then_button: false }); + assert_eq!(route(minimize, false, Some(&key("m", false))), Route { current: true, then_button: false }); + } + + #[test] + fn edit_actions_always_reach_rune_as_keys() { + let copy = by_action("copy:").unwrap(); + let redo = by_action("redo:").unwrap(); + let key_only = |current| Route { current, then_button: false }; + // A focused Rune view gets the very event that fired the item, as before the menu. + assert_eq!(route(copy, true, Some(&key("c", false))), key_only(true), "Edit items never act on the window"); + assert_eq!(route(copy, false, Some(&key("C", false))), key_only(true)); + // ⇧⌘Z reports "Z"; ⌘Z isn't Redo's own equivalent. + assert_eq!(route(redo, false, Some(&key("Z", true))), key_only(true)); + assert_eq!(route(redo, false, Some(&key("z", false))), key_only(false)); + // A click on the item, or an equivalent remapped in System Settings, makes ⌘C. + assert_eq!(route(copy, false, None), key_only(false)); + let remapped = KeyDown { alt: true, ..key("c", false) }; + assert_eq!(route(copy, false, Some(&remapped)), key_only(false)); + assert_eq!(route(copy, false, Some(&KeyDown { cmd: false, ..key("c", false) })), key_only(false)); + } + + #[test] + fn new_menus_take_the_mac_order_around_the_standard_ones() { + let tops = |t: &[&str]| t.iter().map(|s| s.to_string()).collect::<Vec<_>>(); + let standard = tops(&["App", "Edit", "Window"]); + assert_eq!(top_index("File", &standard), 1, "File before Edit"); + assert_eq!(top_index("View", &standard), 2, "the app's menus between Edit and Window"); + assert_eq!(top_index("Help", &standard), 3, "Help last"); + assert_eq!(top_index("Tools", &tops(&["App", "File", "Edit", "View", "Window", "Help"])), 4, "after the app's other menus"); + // The standard menus joining an app's own bar. + assert_eq!(top_index("Edit", &tops(&["App", "File", "View", "Help"])), 2); + assert_eq!(top_index("Window", &tops(&["App", "File", "Edit", "View", "Help"])), 4); + assert_eq!(top_index("View", &tops(&["App"])), 1); + assert_eq!(top_index("File", &[]), 0); + } + + #[test] + fn equivalents_compare_as_appkit_matches_them() { + let close = by_action("performClose:").unwrap().equivalent(); + assert_eq!(Equivalent::new("w", true, false, false, false), Some(close.clone())); + assert_ne!(Equivalent::new("w", true, true, false, false), Some(close.clone()), "⇧⌘W is another key"); + assert_ne!(Equivalent::new("w", false, false, false, false), Some(close)); + let redo = by_action("redo:").unwrap().equivalent(); + assert_eq!(Equivalent::new("Z", true, false, false, false), Some(redo.clone()), "a capital means Shift"); + assert_eq!(Equivalent::new("z", true, true, false, false), Some(redo)); + assert_eq!(Equivalent::new("", true, false, false, false), None); + } + + #[test] + fn only_winits_untouched_app_menu_counts_as_the_default() { + let winit = [Some("orderFrontStandardAboutPanel:"), None, None, Some("hide:"), Some("hideOtherApplications:"), + Some("unhideAllApplications:"), None, Some("terminate:")]; + assert!(is_winit_default(1, &winit)); + assert!(!is_winit_default(2, &winit), "an app that added a menu set its own"); + assert!(!is_winit_default(1, &winit[..7]), "no Quit: not winit's"); + assert!(!is_winit_default(1, &[]), "an accessory app's empty app menu"); + assert!(!is_winit_default(0, &[])); + } +} diff --git a/app/vendor/rune/crates/rune/src/native_menu/standard_macos.rs b/app/vendor/rune/crates/rune/src/native_menu/standard_macos.rs new file mode 100644 index 0000000..bf31caa --- /dev/null +++ b/app/vendor/rune/crates/rune/src/native_menu/standard_macos.rs @@ -0,0 +1,167 @@ +//! Installs the standard items in `NSApp.mainMenu` (`default_macos::add_standard`) and adds +//! their actions to winit's view, so a focused Rune window answers them instead of AppKit +//! swallowing the keys. AppKit consumes a +//! key equivalent whose item is disabled (no responder implements its action), so without +//! these methods ⌘C would never reach Rune's own text editing. Main thread only. + +#![allow(unsafe_code)] + +use super::{default_macos, standard::{self, KeyDown, Standard, ITEMS}}; +use crate::runtime::Unhandled; +use std::{cell::Cell, ffi::{c_char, c_void}, sync::Arc}; +use objc2::{ClassType, MainThreadMarker, msg_send, rc::Retained, runtime::{AnyClass, AnyObject, Bool, Sel}}; +use objc2_app_kit::{NSApplication, NSEvent, NSEventModifierFlags, NSEventType, NSPanel, NSView, NSWindow, NSWindowButton}; +use objc2_foundation::{NSObjectProtocol, NSPoint, NSProcessInfo, NSString}; + +thread_local! { + static INSTALLED: Cell<bool> = const { Cell::new(false) }; + /// Whether a window start has looked for winit's default menu yet. + static CHECKED: Cell<bool> = const { Cell::new(false) }; + static HOOKED: Cell<bool> = const { Cell::new(false) }; + /// What the key a menu item is handing Rune does if no handler takes it: a standard item's + /// own ⌘-letter, or whatever key an app's `keys_first` item was picked by. + static UNHANDLED: Cell<Option<(Option<char>, Unhandled)>> = const { Cell::new(None) }; +} +unsafe extern "C" { + fn class_addMethod(class: *const AnyClass, selector: Sel, implementation: *const c_void, types: *const c_char) -> Bool; +} + +/// At a window's start: the standard items, when the app asked (`App::standard_menus`) or the +/// menu bar is still winit's default for a regular app as the first window starts. Once per +/// process. +pub(crate) fn install(opt_in: bool) { + let Some(mtm) = MainThreadMarker::new() else { return }; + if INSTALLED.with(Cell::get) { return; } + let app = NSApplication::sharedApplication(mtm); + let default = !CHECKED.with(|c| c.replace(true)) && default_macos::is_winit_default(&app); + if !opt_in && !default { return; } + INSTALLED.with(|i| i.set(true)); + default_macos::add_standard(&app); + hook_view_class(); +} + +/// The window host, for a key press it maps to `key`: what to do if no handler takes it, when +/// a menu item is handing Rune that very key. +pub(crate) fn take_unhandled(key: &crate::KeyEvent) -> Option<Unhandled> { + let (c, then) = UNHANDLED.with(Cell::take)?; + c.is_none_or(|c| key.key == crate::Key::Command(c) && !key.mods.alt && !key.mods.ctrl).then_some(then) +} + +/// An app's `keys_first` item picked by its key equivalent while a Rune window's view has the +/// keyboard: the key goes to that view, so the window's handlers see it first, and `run` +/// happens only if none takes it. False when a click picked the item, or the keyboard is +/// elsewhere (another view, an overlay panel): the caller runs it. +pub(super) fn defer_key(run: Arc<dyn Fn() + Send + Sync>) -> bool { + let (Some(mtm), Some(class)) = (MainThreadMarker::new(), AnyClass::get(c"WinitView")) else { return false }; + // SAFETY: main thread (a menu action); the event, window and view are retained. + unsafe { + let app = NSApplication::sharedApplication(mtm); + let Some(event) = app.currentEvent().filter(|e| e.r#type() == NSEventType::KeyDown) else { return false }; + let Some(window) = app.keyWindow().filter(|w| !w.isKindOfClass(NSPanel::class())) else { return false }; + let Some(responder) = window.firstResponder().filter(|r| r.isKindOfClass(class)) else { return false }; + let view: Retained<NSView> = Retained::cast_unchecked(responder); + UNHANDLED.with(|u| u.set(Some((None, Unhandled::Menu(run.clone()))))); + commit_composition(&view); + view.keyDown(&event); + // Nothing took the press (winit made no logical key of it): the item runs as before. + if UNHANDLED.with(Cell::take).is_some() { run(); } + } + true +} + +/// After each window creation: winit registers its view class with the first window. +pub(crate) fn adopt() { hook_view_class(); } + +fn hook_view_class() { + if !INSTALLED.with(Cell::get) || HOOKED.with(Cell::get) { return; } + // Every Rune window's content view is a WinitView (or a per-instance subclass of it). + let Some(class) = AnyClass::get(c"WinitView") else { return }; + for item in &ITEMS { + let sel = Sel::register(&std::ffi::CString::new(item.action).expect("selector")); + // SAFETY: runtime mutation on the main thread. The implementation has the exact + // `-(void)action:(id)sender` ABI. Adding never replaces a method the class defines. + let added = unsafe { class_addMethod(class, sel, action as *const c_void, c"v@:@".as_ptr()) }; + if !added.as_bool() { eprintln!("rune: standard menus: the window view already answers {}", item.action); } + } + HOOKED.with(|h| h.set(true)); +} + +extern "C" fn action(this: *mut AnyObject, selector: Sel, _sender: *mut AnyObject) { + let Some(item) = selector.name().to_str().ok().and_then(standard::by_action) else { return }; + // SAFETY: AppKit sends menu actions on the main thread to a live WinitView. + let view = unsafe { &*(this as *const NSView) }; + // SAFETY: `view` is a live `WinitView` on the main thread, as `perform` requires. + if std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| unsafe { perform(view, item) })).is_err() { + eprintln!("rune: standard menu action panicked"); + } +} + +unsafe fn perform(view: &NSView, item: &Standard) { + // SAFETY: main thread (a menu action); the view, its window and the events are retained. + unsafe { + let mtm = MainThreadMarker::from(view); + let window = view.window(); + let (kind, then) = match item.role { + standard::Role::Close => (Some(NSWindowButton::CloseButton), Some(Unhandled::Close)), + standard::Role::Minimize => (Some(NSWindowButton::MiniaturizeButton), Some(Unhandled::Minimize)), + _ => (None, None), + }; + // A titled panel can show an enabled miniaturize button, but Rune never minimizes one. + let panel = window.as_ref().is_some_and(|w| w.isKindOfClass(NSPanel::class())); + let button = !panel && window.as_ref().zip(kind).and_then(|(w, kind)| w.standardWindowButton(kind)).is_some_and(|b| b.isEnabled()); + let current = NSApplication::sharedApplication(mtm).currentEvent().filter(|e| e.r#type() == NSEventType::KeyDown); + let route = standard::route(item, button, current.as_deref().map(key_down).as_ref()); + // winit hands the press to the host synchronously, which takes this; clear it anyway. + UNHANDLED.with(|u| u.set(then.filter(|_| route.then_button).map(|then| (Some(item.key), then)))); + commit_composition(view); + match current.filter(|_| route.current) { + Some(event) => view.keyDown(&event), + None => press(view, item, window.as_deref()), + } + UNHANDLED.with(|u| u.set(None)); + } +} + +/// An IME composition (or a dead key's accent) in the view ends before the command, as in an +/// NSTextView: the input method commits it, so the text lands in the field first; one that +/// doesn't is dropped. Then the key reaches Rune instead of the input method, which would +/// otherwise swallow it as part of the composition. +unsafe fn commit_composition(view: &NSView) { + // SAFETY: main thread; the view is a live WinitView, which implements NSTextInputClient. + unsafe { + let marked: bool = msg_send![view, hasMarkedText]; + if !marked { return; } + // The input method answers with `insertText:`, which winit reports as `Ime::Commit`. + let context: *mut AnyObject = msg_send![view, inputContext]; + if let Some(context) = context.as_ref() { let _: () = msg_send![context, discardMarkedText]; } + // Back to winit's ground state whether or not it committed: right after a commit winit + // treats the next key as part of it and drops it. + let _: () = msg_send![view, unmarkText]; + } +} + +fn key_down(event: &NSEvent) -> KeyDown { + let flags = event.modifierFlags(); + KeyDown { + chars: event.charactersIgnoringModifiers().map(|s| s.to_string()).unwrap_or_default(), + cmd: flags.contains(NSEventModifierFlags::Command), + shift: flags.contains(NSEventModifierFlags::Shift), + alt: flags.contains(NSEventModifierFlags::Option), + ctrl: flags.contains(NSEventModifierFlags::Control), + } +} + +/// A click picked the item (or its equivalent was remapped): press and release its ⌘-key in +/// the view, releasing with the modifiers actually held so Rune doesn't see ⌘ stuck down. +unsafe fn press(view: &NSView, item: &Standard, window: Option<&NSWindow>) { + let number = window.map_or(0, |w| w.windowNumber()); + let key = if item.shift { item.key.to_ascii_uppercase() } else { item.key }; + let chars = NSString::from_str(&key.to_string()); + let time = NSProcessInfo::processInfo().systemUptime(); + let event = |kind, flags| NSEvent::keyEventWithType_location_modifierFlags_timestamp_windowNumber_context_characters_charactersIgnoringModifiers_isARepeat_keyCode( + kind, NSPoint::new(0.0, 0.0), flags, time, number, None, &chars, &chars, false, item.key_code); + let mut flags = NSEventModifierFlags::Command; + if item.shift { flags |= NSEventModifierFlags::Shift; } + if let Some(down) = event(NSEventType::KeyDown, flags) { view.keyDown(&down); } + if let Some(up) = event(NSEventType::KeyUp, NSEvent::modifierFlags_class()) { view.keyUp(&up); } +} diff --git a/app/vendor/rune/crates/rune/src/open_url.rs b/app/vendor/rune/crates/rune/src/open_url.rs new file mode 100644 index 0000000..0e5abf4 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/open_url.rs @@ -0,0 +1,299 @@ +//! Open a link in the system's default handler: [`Tx::open_url`](crate::Tx::open_url). +//! +//! Only `http:`, `https:` and `mailto:` links open, the same set the web build allows. Anything +//! else (`file:`, custom app schemes, `javascript:`) is refused with +//! [`OpenUrlError::UnsupportedScheme`] before anything runs, as are empty links and links with +//! spaces or control characters. The check runs when the handler calls `open_url`; the open +//! itself happens once the handler's frame is done. +//! +//! macOS asks `NSWorkspace`, Windows `ShellExecuteW`, Linux runs `xdg-open`. Headless runs and +//! tests never open anything: they keep the requests for [`crate::Runtime::take_url_requests`]. + +pub(crate) mod incoming; +pub(crate) mod instance; + +const MAX_LEN: usize = 8192; + +/// Why a link was refused or didn't open. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum OpenUrlError { + /// Nothing to open. + Empty, + /// Not a link: too long, has whitespace or control characters, or lacks a scheme or host. + Invalid, + /// A scheme other than `http`, `https` or `mailto` (lowercased). + UnsupportedScheme(String), + /// The system couldn't open it, or this platform has no way to. + Failed(String), +} + +impl std::fmt::Display for OpenUrlError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::Empty => f.write_str("empty link"), + Self::Invalid => f.write_str("not a valid link"), + Self::UnsupportedScheme(s) => write!(f, "links with the {s}: scheme can't be opened"), + Self::Failed(why) => write!(f, "couldn't open the link: {why}"), + } + } +} +impl std::error::Error for OpenUrlError {} + +/// A link a handler asked to open, already checked. +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) struct Link { + pub url: String, + /// `Tx::open_url_same_tab`: replace the page on web rather than open a tab. + pub same_tab: bool, +} + +/// The link to open, trimmed and with a lowercase scheme, or why it can't be. +pub(crate) fn check(url: &str) -> Result<String, OpenUrlError> { check_link(url, false) } + +/// `check` for a same-tab link: on web a link without a scheme (`/notes/42`, `?q=a`, `#top`) +/// is relative to the page, and the browser resolves it. +pub(crate) fn check_same_tab(url: &str) -> Result<String, OpenUrlError> { check_link(url, cfg!(target_arch = "wasm32")) } + +fn check_link(url: &str, relative: bool) -> Result<String, OpenUrlError> { + let url = url.trim(); + if url.is_empty() { return Err(OpenUrlError::Empty); } + if url.len() > MAX_LEN + || url.chars().any(|c| c.is_whitespace() || c.is_control() + || matches!(c, '\\' | '"' | '<' | '>' | '`' | '^' | '{' | '|' | '}')) + || bad_percent(url.as_bytes()) + { + return Err(OpenUrlError::Invalid); + } + if relative && url.find([':', '/', '?', '#']).is_none_or(|i| url.as_bytes()[i] != b':') { + return Ok(url.to_owned()); + } + let (scheme, rest) = url.split_once(':').ok_or(OpenUrlError::Invalid)?; + let scheme = scheme.to_ascii_lowercase(); + if scheme.is_empty() || !scheme.starts_with(|c: char| c.is_ascii_alphabetic()) + || !scheme.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '-' | '.')) { + return Err(OpenUrlError::Invalid); + } + match scheme.as_str() { + "http" | "https" => { + let after = rest.strip_prefix("//").ok_or(OpenUrlError::Invalid)?; + let tail_start = after.find(['/', '?', '#']).unwrap_or(after.len()); + let (authority, tail) = after.split_at(tail_start); + if tail.contains(['[', ']']) || !valid_authority(authority) { + return Err(OpenUrlError::Invalid); + } + } + "mailto" => { + if rest.is_empty() || rest.starts_with("//") || rest.contains(['[', ']']) { + return Err(OpenUrlError::Invalid); + } + } + _ => return Err(OpenUrlError::UnsupportedScheme(scheme)), + } + Ok(format!("{scheme}:{rest}")) +} + +fn bad_percent(bytes: &[u8]) -> bool { + let mut i = 0; + while i < bytes.len() { + if bytes[i] == b'%' { + let (Some(&a), Some(&b)) = (bytes.get(i + 1), bytes.get(i + 2)) else { return true }; + if !a.is_ascii_hexdigit() || !b.is_ascii_hexdigit() || (a == b'0' && b == b'0') { + return true; + } + i += 3; + } else { + i += 1; + } + } + false +} + +fn valid_authority(authority: &str) -> bool { + let (userinfo, host_port) = match authority.rsplit_once('@') { + Some((u, hp)) => (Some(u), hp), + None => (None, authority), + }; + if userinfo.is_some_and(|u| u.is_empty() || u.contains(['[', ']', '@'])) { return false; } + let port = if let Some(rest) = host_port.strip_prefix('[') { + let Some((ipv6, port)) = rest.split_once(']') else { return false }; + if ipv6.len() < 2 || !ipv6.contains(':') || ipv6.starts_with('.') || ipv6.contains("..") + || !ipv6.chars().all(|c| c.is_ascii_hexdigit() || matches!(c, ':' | '.')) + { + return false; + } + if !port.is_empty() && !port.starts_with(':') { return false; } + port.strip_prefix(':') + } else if host_port.contains(['[', ']']) { + return false; + } else { + let (host, port) = match host_port.split_once(':') { + Some((h, p)) => (h, Some(p)), + None => (host_port, None), + }; + if host.is_empty() || host.starts_with('.') || host.contains("..") || host.contains(['%', ':']) { + return false; + } + port + }; + port.is_none_or(|p| !p.is_empty() && p.parse::<u16>().is_ok()) +} + +impl crate::runtime::HostState { + pub(crate) fn open_urls(&mut self, links: Vec<Link>) { + for link in links { + if self.open_urls_natively { + #[cfg(target_arch = "wasm32")] + let opened = if link.same_tab { crate::platform::web::open_url_same_tab(&link.url).map_err(OpenUrlError::Failed) } else { open(&link.url) }; + #[cfg(not(target_arch = "wasm32"))] + let opened = open(&link.url); + if let Err(e) = opened { eprintln!("rune: open_url({}): {e}", link.url); } + } else { + self.push_url_request(link.url); + } + } + } +} + +impl crate::runtime::RuntimeCore { + #[inline] + pub(crate) fn open_urls(&mut self, links: Vec<Link>) { + self.host.open_urls(links); + } +} + +#[cfg(target_arch = "wasm32")] +fn open(url: &str) -> Result<(), OpenUrlError> { crate::platform::web::open_url(url).map_err(OpenUrlError::Failed) } + +#[cfg(target_os = "macos")] +#[allow(unsafe_code)] +fn open(url: &str) -> Result<(), OpenUrlError> { + use objc2::{class, msg_send, rc::{Retained, autoreleasepool}}; + use objc2_foundation::{NSString, NSURL}; + let ascii = percent_encode_non_ascii(url); + // SAFETY: NSWorkspace's shared instance lives for the process; `openURL:` takes an NSURL + // and returns BOOL. Handlers run on the UI thread. + autoreleasepool(|_| unsafe { + let ns = NSString::from_str(&ascii); + let url: Option<Retained<NSURL>> = NSURL::URLWithString(&ns); + let url = url.ok_or(OpenUrlError::Invalid)?; + let workspace: *mut objc2::runtime::AnyObject = msg_send![class!(NSWorkspace), sharedWorkspace]; + if workspace.is_null() { return Err(OpenUrlError::Failed("NSWorkspace unavailable".into())); } + let opened: objc2::runtime::Bool = msg_send![workspace, openURL: &*url]; + if opened.as_bool() { Ok(()) } else { Err(OpenUrlError::Failed("no app opened it".into())) } + }) +} + +#[cfg(target_os = "macos")] +fn percent_encode_non_ascii(url: &str) -> std::borrow::Cow<'_, str> { + if url.is_ascii() { return std::borrow::Cow::Borrowed(url); } + let mut out = String::with_capacity(url.len() + 16); + for &b in url.as_bytes() { + if b < 0x80 { + out.push(b as char); + } else { + use std::fmt::Write; + write!(out, "%{b:02X}").ok(); + } + } + std::borrow::Cow::Owned(out) +} + +#[cfg(target_os = "windows")] +#[allow(unsafe_code)] +fn open(url: &str) -> Result<(), OpenUrlError> { + use windows_sys::Win32::UI::{Shell::ShellExecuteW, WindowsAndMessaging::SW_SHOWNORMAL}; + let wide = |s: &str| s.encode_utf16().chain([0]).collect::<Vec<u16>>(); + let (verb, target) = (wide("open"), wide(url)); + // SAFETY: both strings are NUL-terminated and outlive the call; the other pointers are null. + let result = unsafe { ShellExecuteW(std::ptr::null_mut(), verb.as_ptr(), target.as_ptr(), std::ptr::null(), std::ptr::null(), SW_SHOWNORMAL) }; + // Values above 32 are success. + if result as usize > 32 { Ok(()) } else { Err(OpenUrlError::Failed(format!("ShellExecute returned {}", result as usize))) } +} + +#[cfg(all(unix, not(any(target_os = "macos", target_os = "ios", target_os = "android"))))] +fn open(url: &str) -> Result<(), OpenUrlError> { + debug_assert!(!url.starts_with('-')); + // xdg-open's argument loop rejects `--` as an unknown option; `check` guarantees a scheme prefix. + let mut child = std::process::Command::new("xdg-open").arg(url) + .stdin(std::process::Stdio::null()).stdout(std::process::Stdio::null()).stderr(std::process::Stdio::null()) + .spawn().map_err(|e| OpenUrlError::Failed(e.to_string()))?; + // Reap it so it doesn't linger as a zombie. + std::thread::spawn(move || { child.wait().ok(); }); + Ok(()) +} + +#[cfg(not(any(target_arch = "wasm32", target_os = "macos", target_os = "windows", all(unix, not(any(target_os = "ios", target_os = "android"))))))] +fn open(_: &str) -> Result<(), OpenUrlError> { Err(OpenUrlError::Failed("this platform can't open links".into())) } + +#[cfg(test)] +mod tests { + use super::*; + use crate::{Cx, Env, Runtime, el::{El, el}}; + + #[test] + fn allows_web_and_mail_links_only() { + assert_eq!(check(" https://example.com/a?b=1#c ").as_deref(), Ok("https://example.com/a?b=1#c")); + assert_eq!(check("HTTP://example.com").as_deref(), Ok("http://example.com")); + assert_eq!(check("https://[::1]:8080/path").as_deref(), Ok("https://[::1]:8080/path")); + assert_eq!(check("mailto:someone@example.com?subject=Hi").as_deref(), Ok("mailto:someone@example.com?subject=Hi")); + assert_eq!(check("file:///etc/passwd"), Err(OpenUrlError::UnsupportedScheme("file".into()))); + assert_eq!(check("JavaScript:alert(1)"), Err(OpenUrlError::UnsupportedScheme("javascript".into()))); + assert_eq!(check("myapp://do/thing"), Err(OpenUrlError::UnsupportedScheme("myapp".into()))); + assert_eq!(check(""), Err(OpenUrlError::Empty)); + assert_eq!(check(" "), Err(OpenUrlError::Empty)); + for bad in [ + "example.com", "https:", "https://", "https:///x", "https://a b", "https://a\n.com", + "mailto:", "mailto://example.com", "1http://x", "://x", + "https://\\evil.com", "https://example.com/\"--flag", "https://example.com/a\\b", + "https://example.com/%ZZ", "https://example.com/%00", "https://example.com/%2", + "https://@/", "https://user@/", "https://:80/", "https://example.com:abc/", + "https://evil%2f.com/", "https://.example.com", "https://a..b.com", + "https://example.com/a[0]", "https://[not-ipv6]/", "https://[::1]abc/", + ] { + assert_eq!(check(bad), Err(OpenUrlError::Invalid), "{bad:?}"); + } + } + + #[test] + fn same_tab_links_may_be_relative_only_on_web() { + for relative in ["/notes/42", "notes/42?x=1", "?q=a", "#top", "../c", "a/b:c"] { + assert_eq!(check_link(relative, true).as_deref(), Ok(relative), "{relative:?}"); + assert_eq!(check_link(relative, false), Err(OpenUrlError::Invalid), "{relative:?}"); + } + assert_eq!(check_link("javascript:alert(1)", true), Err(OpenUrlError::UnsupportedScheme("javascript".into()))); + assert_eq!(check_link("/a b", true), Err(OpenUrlError::Invalid)); + assert_eq!(check_link("HTTPS://example.com/x", true).as_deref(), Ok("https://example.com/x")); + assert_eq!(check_same_tab("/notes/42"), Err(OpenUrlError::Invalid), "native has no page to resolve against"); + } + + #[test] + fn headless_runs_record_the_request_and_open_nothing() { + fn view(seen: &Vec<&'static str>, _: &mut Cx<Vec<&'static str>>) -> El { + let _ = seen; + el().key("btn").size(10.0, 10.0).on_press_tx(|seen: &mut Vec<&'static str>, tx| { + seen.push("handler"); + tx.open_url("https://example.com/clicked").unwrap(); + }) + } + let mut rt = Runtime::new(Vec::new(), view, (50.0, 50.0), Env::new(true, 1.0)); + rt.frame(0.0); + let mut results = Vec::new(); + rt.update(|_, tx| { + results.push(tx.open_url("https://example.com/docs")); + results.push(tx.open_url("file:///etc/hosts")); + results.push(tx.open_url("mailto:a@example.com")); + results.push(tx.open_url_same_tab("https://example.com/here")); + }); + rt.pointer_down(5.0, 5.0); + rt.pointer_up(5.0, 5.0); + rt.frame(0.0); + assert_eq!(results, [Ok(()), Err(OpenUrlError::UnsupportedScheme("file".into())), Ok(()), Ok(())]); + assert_eq!(rt.take_url_requests(), [ + "https://example.com/docs", + "mailto:a@example.com", + "https://example.com/here", + "https://example.com/clicked", + ]); + assert!(rt.take_url_requests().is_empty()); + } +} diff --git a/app/vendor/rune/crates/rune/src/open_url/incoming.rs b/app/vendor/rune/crates/rune/src/open_url/incoming.rs new file mode 100644 index 0000000..a0014cd --- /dev/null +++ b/app/vendor/rune/crates/rune/src/open_url/incoming.rs @@ -0,0 +1,319 @@ +//! Receiving links the system opens with this app (`myapp://...`): `App::on_open_url`. +//! +//! winit 0.30 doesn't forward them, so on macOS Rune listens for the get-URL Apple event itself +//! (`kInternetEventClass`/`kAEGetURL`). The event loop installs the handler before it starts +//! (`prepare`) and keeps the links that arrive until a window whose app has the hook starts +//! (`listen`), so the link that launched the app arrives too, whichever window has the hook. +//! Once every window has started (`settle`), the handler goes again if none had a hook. An app +//! that installed its own handler before the loop keeps it unless one of its windows has the +//! hook. +//! +//! The first listening window that's still running receives the links; when it goes the next +//! one does. A link becomes an `AppHandle::update` running the hook: it runs before the window's +//! first frame when it arrived first, in arrival order on the main thread in a normal +//! transaction (state commits and the window redraws), and wakes an idle loop. The link is +//! passed through as the system gave it; it comes from outside the app, so the hook must parse +//! and validate it. +//! +//! Windows hands a link to a new process as a launch argument: the links among the first +//! process's arguments are kept as the launching link is on macOS, and `single_instance` sends +//! a later launch's links here from the first process's pipe (`instance`). Links that arrive +//! before the loop starts are kept too. Linux does the same through a Unix socket. iOS (winit +//! owns the scene delegate) is a follow-up. +// The web build runs no native window, so nothing here is reached there. +#![cfg_attr(target_arch = "wasm32", allow(dead_code))] +use std::sync::{Arc, Mutex}; + +use crate::app::{App, AppHandle}; +use crate::el::Tx; + +/// `App::on_open_url`'s hook. +pub(crate) type OnOpenUrl<S> = fn(&mut S, &str, &mut Tx); + +type Sink = Arc<dyn Fn(String) + Send + Sync>; + +/// The platform's get-URL handler. +pub(crate) trait Glue { + /// Something else (the app itself) already handles get-URL events. + fn handled_elsewhere(&self) -> bool; + /// Makes Rune's handler the one; false when it can't (off the main thread, another platform). + fn install(&self) -> bool; + fn remove(&self); +} + +/// Where a link goes, from launch until every window has started. +enum Funnel { + /// Nothing installed here (or the handler can't be): a link is kept for the first window + /// whose app has the hook, as on Windows before the loop starts. + Unprepared { kept: Vec<String> }, + /// The get-URL handler is Rune's; links wait here for the first window with the hook. + Launch { kept: Vec<String> }, + /// A window listens: a link goes to the first one still running, in start order. Nothing + /// waits for a later window, including after every window has started. + Listening { listeners: Vec<(u64, Sink)> }, + /// No handler is installed and no window listens: a link is dropped. + Closed, +} + +struct State { + funnel: Funnel, + next: u64, +} + +/// Where links go. +pub(crate) struct Inbox { + state: Mutex<State>, +} + +impl Inbox { + pub(crate) const fn new() -> Self { + Inbox { state: Mutex::new(State { funnel: Funnel::Unprepared { kept: Vec::new() }, next: 0 }) } + } + + /// Before the event loop: install the handler and keep links until a window listens, + /// unless something else handles them already. + pub(crate) fn prepare(&self, glue: &dyn Glue) { + let mut state = self.state.lock().unwrap(); + state.funnel = match std::mem::replace(&mut state.funnel, Funnel::Closed) { + Funnel::Unprepared { kept } if !glue.handled_elsewhere() && glue.install() => Funnel::Launch { kept }, + funnel => funnel, + }; + } + + /// The links the app was launched with, ahead of any that arrived since. + #[cfg_attr(not(any(target_os = "windows", target_os = "linux")), allow(dead_code))] + pub(crate) fn launched(&self, urls: Vec<String>) { + if urls.is_empty() { return; } + let mut state = self.state.lock().unwrap(); + if let Funnel::Unprepared { kept } | Funnel::Launch { kept } = &mut state.funnel { kept.splice(0..0, urls); } + } + + /// Sends links to `app`'s hook while the returned guard lives, after the links kept so far, + /// if the app has the hook. Installs the handler if `prepare` didn't. + #[inline] + pub(crate) fn listen<S: 'static>(&'static self, app: &App<S>, glue: &dyn Glue) -> Option<Listening> { + let hook = app.on_open_url?; + let handle: AppHandle<S> = app.handle(); + self.listen_sink(glue, Arc::new(move |url: String| handle.update(move |s, tx| hook(s, &url, tx)))) + } + + fn listen_sink(&'static self, glue: &dyn Glue, sink: Sink) -> Option<Listening> { + let mut state = self.state.lock().unwrap(); + let (mut listeners, kept) = match std::mem::replace(&mut state.funnel, Funnel::Closed) { + // `Listening` and `Launch` already have the handler; `Unprepared` and `Closed` + // install it here. + Funnel::Listening { listeners } => (listeners, Vec::new()), + Funnel::Launch { kept } => (Vec::new(), kept), + Funnel::Unprepared { kept } => { + if !glue.install() { + state.funnel = Funnel::Unprepared { kept }; + return None; + } + (Vec::new(), kept) + } + Funnel::Closed => { + if !glue.install() { + state.funnel = Funnel::Closed; + return None; + } + (Vec::new(), Vec::new()) + } + }; + let id = state.next; + state.next += 1; + listeners.push((id, sink.clone())); + state.funnel = Funnel::Listening { listeners }; + drop(state); + for url in kept { sink(url); } + Some(Listening { inbox: self, id }) + } + + /// Every window has started: stop keeping links, and remove the handler if none listens. + pub(crate) fn settle(&self, glue: &dyn Glue) { + let mut state = self.state.lock().unwrap(); + state.funnel = match std::mem::replace(&mut state.funnel, Funnel::Closed) { + Funnel::Listening { listeners } if !listeners.is_empty() => Funnel::Listening { listeners }, + Funnel::Launch { .. } | Funnel::Listening { .. } => { glue.remove(); Funnel::Closed }, + Funnel::Unprepared { .. } | Funnel::Closed => Funnel::Closed, + }; + } + + /// A link arrived: to the first listener, kept before one exists, else dropped. + #[cfg_attr(not(any(test, target_os = "macos", target_os = "windows", target_os = "linux")), allow(dead_code))] + pub(crate) fn receive(&self, url: String) { + let sink = { + let mut state = self.state.lock().unwrap(); + match &mut state.funnel { + Funnel::Unprepared { kept } | Funnel::Launch { kept } => { + kept.push(url); + return; + } + Funnel::Listening { listeners } => match listeners.first() { + Some((_, sink)) => sink.clone(), + None => return, + }, + Funnel::Closed => return, + } + }; + sink(url); + } +} + +/// A window's place among the listeners, held by its host; dropping it stops its links. +pub(crate) struct Listening { + inbox: &'static Inbox, + id: u64, +} + +impl Drop for Listening { + fn drop(&mut self) { + if let Ok(mut state) = self.inbox.state.lock() + && let Funnel::Listening { listeners } = &mut state.funnel { + listeners.retain(|(id, _)| *id != self.id); + } + } +} + +static INBOX: Inbox = Inbox::new(); + +struct Native; + +impl Glue for Native { + fn handled_elsewhere(&self) -> bool { platform::handled_elsewhere() } + fn install(&self) -> bool { platform::install() } + fn remove(&self) { platform::remove() } +} + +/// Before the event loop starts (see the module docs). +pub(crate) fn prepare() { + INBOX.prepare(&Native); + #[cfg(any(target_os = "windows", target_os = "linux"))] + INBOX.launched(super::instance::launch_links()); +} + +/// A link from a later launch of the app (Windows, Linux, `single_instance`), or the Dock menu's +/// jump list entry (macOS, `native_menu`). +#[cfg(any(target_os = "windows", target_os = "linux", target_os = "macos"))] +pub(crate) fn receive(url: String) { INBOX.receive(url); } + +/// For a starting window: its app's links, while the guard lives. +pub(crate) fn listen<S: 'static>(app: &App<S>) -> Option<Listening> { INBOX.listen(app, &Native) } + +/// After every window at launch has started. +pub(crate) fn settle() { INBOX.settle(&Native); } + +#[cfg(target_os = "macos")] +use mac as platform; + +/// Windows and Linux: links come in launch arguments and down `single_instance`'s pipe or socket, +/// so there is no handler to install, and nothing else can have taken it. +#[cfg(any(target_os = "windows", target_os = "linux"))] +mod platform { + pub(super) fn handled_elsewhere() -> bool { false } + pub(super) fn install() -> bool { true } + pub(super) fn remove() {} +} + +#[cfg(not(any(target_os = "macos", target_os = "windows", target_os = "linux")))] +mod platform { + pub(super) fn handled_elsewhere() -> bool { false } + pub(super) fn install() -> bool { false } + pub(super) fn remove() {} +} + +#[cfg(target_os = "macos")] +#[allow(unsafe_code)] +mod mac { + use std::ffi::c_void; + use std::sync::OnceLock; + use objc2::rc::autoreleasepool; + use objc2::runtime::{AnyClass, AnyObject, ClassBuilder, NSObject, Sel}; + use objc2::{ClassType, MainThreadMarker, class, msg_send, sel}; + use objc2_foundation::NSString; + + /// `'GURL'`: `kInternetEventClass` and `kAEGetURL`. + const GET_URL: u32 = u32::from_be_bytes(*b"GURL"); + /// `'----'`: `keyDirectObject`, the event's URL string. + const DIRECT_OBJECT: u32 = u32::from_be_bytes(*b"----"); + + #[link(name = "CoreServices", kind = "framework")] + unsafe extern "C" { + fn AEGetEventHandler(class: u32, id: u32, handler: *mut *const c_void, refcon: *mut *mut c_void, system: u8) -> i16; + } + + /// The URL string of a get-URL event. + pub(super) fn url_of(event: &AnyObject) -> Option<String> { + // SAFETY: `event` is an NSAppleEventDescriptor; both messages are nil-safe and return + // an autoreleased object or nil, released with the pool. + autoreleasepool(|_| unsafe { + let param: *mut AnyObject = msg_send![event, paramDescriptorForKeyword: DIRECT_OBJECT]; + let string: *mut NSString = msg_send![param.as_ref()?, stringValue]; + Some(string.as_ref()?.to_string()) + }) + } + + extern "C" fn get_url(_: &AnyObject, _: Sel, event: *mut AnyObject, _reply: *mut AnyObject) { + let caught = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + // SAFETY: AppKit passes the event, or nil. + if let Some(url) = unsafe { event.as_ref() }.and_then(url_of) { super::INBOX.receive(url); } + })); + if caught.is_err() { eprintln!("rune: open-url handler panicked"); } + } + + pub(super) fn handled_elsewhere() -> bool { + let (mut handler, mut refcon) = (std::ptr::null(), std::ptr::null_mut()); + // SAFETY: reads the installed handler into the two out-pointers; 0 is noErr. + unsafe { AEGetEventHandler(GET_URL, GET_URL, &mut handler, &mut refcon, 0) == 0 } + } + + /// Rune's handler object, made once and never released (the event manager doesn't retain it). + fn handler() -> Option<*mut AnyObject> { + static HANDLER: OnceLock<usize> = OnceLock::new(); + let made = *HANDLER.get_or_init(|| { + const NAME: &std::ffi::CStr = c"RuneOpenUrlHandler"; + let class = AnyClass::get(NAME).or_else(|| { + let mut builder = ClassBuilder::new(NAME, NSObject::class())?; + // SAFETY: the function matches `handleGetURLEvent:withReplyEvent:` (two objects, void). + unsafe { builder.add_method(sel!(handleGetURLEvent:withReplyEvent:), get_url as extern "C" fn(_, _, _, _)); } + Some(builder.register()) + }); + let Some(class) = class else { return 0 }; + // SAFETY: `new` on an NSObject subclass; the +1 reference is kept for the process. + let made: *mut AnyObject = unsafe { msg_send![class, new] }; + made as usize + }); + (made != 0).then_some(made as *mut AnyObject) + } + + fn manager() -> *mut AnyObject { + // SAFETY: a class method returning the process's shared manager. + unsafe { msg_send![class!(NSAppleEventManager), sharedAppleEventManager] } + } + + /// Makes Rune's object the handler of get-URL Apple events. Main thread only. + pub(super) fn install() -> bool { + if MainThreadMarker::new().is_none() { return false; } + let Some(handler) = handler() else { return false }; + // SAFETY: Foundation calls on the main thread, with the handler alive for the process. + autoreleasepool(|_| unsafe { + let Some(manager) = manager().as_ref() else { return false }; + let _: () = msg_send![manager, setEventHandler: handler, andSelector: sel!(handleGetURLEvent:withReplyEvent:), + forEventClass: GET_URL, andEventID: GET_URL]; + true + }) + } + + pub(super) fn remove() { + if MainThreadMarker::new().is_none() { return; } + // SAFETY: Foundation calls on the main thread. + autoreleasepool(|_| unsafe { + if let Some(manager) = manager().as_ref() { + let _: () = msg_send![manager, removeEventHandlerForEventClass: GET_URL, andEventID: GET_URL]; + } + }) + } +} + +#[cfg(test)] +#[path = "incoming_tests.rs"] +mod tests; diff --git a/app/vendor/rune/crates/rune/src/open_url/incoming_tests.rs b/app/vendor/rune/crates/rune/src/open_url/incoming_tests.rs new file mode 100644 index 0000000..26d79fb --- /dev/null +++ b/app/vendor/rune/crates/rune/src/open_url/incoming_tests.rs @@ -0,0 +1,163 @@ +use std::cell::Cell; +use std::sync::Arc; +use std::sync::atomic::{AtomicUsize, Ordering}; + +use super::{Glue, Inbox}; +use crate::el::el; +use crate::runtime::{Cx, Env, Runtime}; +use crate::{App, AppSpec}; + +type Links = Vec<String>; + +/// A get-URL handler that records what was asked of it. +#[derive(Default)] +struct Fake { + elsewhere: bool, + refuse: bool, + installs: Cell<usize>, + removes: Cell<usize>, +} + +impl Glue for Fake { + fn handled_elsewhere(&self) -> bool { self.elsewhere } + fn install(&self) -> bool { self.installs.set(self.installs.get() + 1); !self.refuse } + fn remove(&self) { self.removes.set(self.removes.get() + 1); } +} + +fn inbox() -> &'static Inbox { Box::leak(Box::new(Inbox::new())) } + +fn app() -> App<Links> { + let spec = AppSpec::new("links", (100.0, 100.0), Links::new, |_: &Links, _: &mut Cx<Links>| el()); + App::new(spec).on_open_url(|links, url, _| links.push(url.to_owned())) +} + +fn plain() -> App<Links> { + App::new(AppSpec::new("plain", (100.0, 100.0), Links::new, |_: &Links, _: &mut Cx<Links>| el())) +} + +/// What a window host does as it starts and when woken: run the queued updates. +fn deliver(app: &App<Links>, rt: &mut Runtime<Links>) -> usize { + let updates = app.shared.take_updates(); + let n = updates.len(); + for f in updates { rt.update_if(f); } + n +} + +fn runtime() -> Runtime<Links> { + Runtime::new(Links::new(), |_: &Links, _: &mut Cx<Links>| el(), (100.0, 100.0), Env::default()) +} + +#[test] +fn without_a_hook_nothing_listens_and_the_launch_handler_goes() { + let (inbox, glue) = (inbox(), Fake::default()); + inbox.prepare(&glue); + inbox.receive("app://kept".into()); + assert!(inbox.listen(&plain(), &glue).is_none()); + inbox.settle(&glue); + assert_eq!((glue.installs.get(), glue.removes.get()), (1, 1), "installed for launch, removed after it"); + let late = app(); + inbox.receive("app://dropped".into()); + let _listening = inbox.listen(&late, &glue).unwrap(); + assert!(late.shared.take_updates().is_empty(), "links from before settling are gone"); +} + +#[test] +fn links_before_the_first_window_arrive_once_in_order_as_it_starts() { + let (inbox, glue, app) = (inbox(), Fake::default(), app()); + inbox.prepare(&glue); + inbox.receive("app://one".into()); + inbox.receive("app://two?x=1".into()); + let _listening = inbox.listen(&app, &glue).unwrap(); + inbox.settle(&glue); + let mut rt = runtime(); + assert!(rt.state.is_empty(), "nothing runs before the host starts"); + assert_eq!(deliver(&app, &mut rt), 2); + assert_eq!(rt.state, ["app://one", "app://two?x=1"]); + assert!(rt.needs_commit(), "the transaction commits and redraws"); + assert_eq!(deliver(&app, &mut rt), 0, "delivered once"); + assert_eq!((glue.installs.get(), glue.removes.get()), (1, 0)); +} + +#[test] +fn a_later_window_with_the_hook_gets_the_launch_link() { + let (inbox, glue, first, second) = (inbox(), Fake::default(), plain(), app()); + inbox.prepare(&glue); + inbox.receive("app://launch".into()); + assert!(inbox.listen(&first, &glue).is_none()); + let _listening = inbox.listen(&second, &glue).unwrap(); + inbox.settle(&glue); + assert_eq!(second.shared.take_updates().len(), 1); + assert_eq!(glue.removes.get(), 0); +} + +#[test] +fn links_while_running_wake_the_loop_and_arrive() { + let (inbox, glue, app) = (inbox(), Fake::default(), app()); + let _listening = inbox.listen(&app, &glue).unwrap(); + let wakes = Arc::new(AtomicUsize::new(0)); + let w = wakes.clone(); + app.shared.connect(Arc::new(move || { w.fetch_add(1, Ordering::SeqCst); })); + let before = wakes.load(Ordering::SeqCst); + inbox.receive("app://later".into()); + assert_eq!(wakes.load(Ordering::SeqCst), before + 1); + let mut rt = runtime(); + assert_eq!(deliver(&app, &mut rt), 1); + assert_eq!(rt.state, ["app://later"]); +} + +#[test] +fn when_the_listening_window_goes_the_next_one_takes_over() { + let (inbox, glue, first, second) = (inbox(), Fake::default(), app(), app()); + let listening = inbox.listen(&first, &glue).unwrap(); + let _second = inbox.listen(&second, &glue).unwrap(); + inbox.receive("app://a".into()); + drop(listening); + inbox.receive("app://b".into()); + assert_eq!(first.shared.take_updates().len(), 1, "a closed window gets nothing more"); + assert_eq!(second.shared.take_updates().len(), 1); + assert_eq!(glue.installs.get(), 1, "installed once"); +} + +#[test] +fn an_apps_own_handler_stays_unless_a_window_has_the_hook() { + let (inbox, glue) = (inbox(), Fake { elsewhere: true, ..Fake::default() }); + inbox.prepare(&glue); + inbox.receive("app://theirs".into()); + inbox.settle(&glue); + assert_eq!((glue.installs.get(), glue.removes.get()), (0, 0)); + let app = app(); + let _listening = inbox.listen(&app, &glue).unwrap(); + assert_eq!(glue.installs.get(), 1); + assert!(app.shared.take_updates().is_empty()); +} + +#[test] +fn a_handler_that_cant_install_listens_to_nothing() { + let (inbox, app) = (inbox(), app()); + assert!(inbox.listen(&app, &Fake { refuse: true, ..Fake::default() }).is_none(), "off the main thread, or another platform"); + inbox.receive("app://dropped".into()); + assert!(app.shared.take_updates().is_empty()); + assert!(inbox.listen(&app, &Fake::default()).is_some()); +} + +#[cfg(target_os = "macos")] +#[test] +#[allow(unsafe_code)] +fn the_url_is_the_events_direct_object() { + use objc2::rc::autoreleasepool; + use objc2::runtime::AnyObject; + use objc2::{class, msg_send}; + use objc2_foundation::NSString; + let code = |s: &[u8; 4]| u32::from_be_bytes(*s); + // SAFETY: Foundation constructors; the event is built, never sent. + autoreleasepool(|_| unsafe { + let event: *mut AnyObject = msg_send![class!(NSAppleEventDescriptor), appleEventWithEventClass: code(b"GURL"), + eventID: code(b"GURL"), targetDescriptor: std::ptr::null_mut::<AnyObject>(), returnID: -1i16, transactionID: 0i32]; + let event = event.as_ref().unwrap(); + assert_eq!(super::mac::url_of(event), None, "no direct object"); + let url = NSString::from_str("myapp://open?id=1"); + let param: *mut AnyObject = msg_send![class!(NSAppleEventDescriptor), descriptorWithString: &*url]; + let _: () = msg_send![event, setParamDescriptor: param, forKeyword: code(b"----")]; + assert_eq!(super::mac::url_of(event).as_deref(), Some("myapp://open?id=1")); + }); +} diff --git a/app/vendor/rune/crates/rune/src/open_url/instance.rs b/app/vendor/rune/crates/rune/src/open_url/instance.rs new file mode 100644 index 0000000..538c07a --- /dev/null +++ b/app/vendor/rune/crates/rune/src/open_url/instance.rs @@ -0,0 +1,259 @@ +//! One running process per app: [`single_instance`](crate::single_instance). +//! +//! Windows starts a new process for every launch: a Start menu click, a `myapp://` link, a +//! clicked notification that opens a link. The first process of the app claims a named pipe +//! for the signed-in user's session (`\\.\pipe\rune-instance-<session>-<user>-<id>`); a later +//! one finds it taken, lets the first take the foreground (`AllowSetForegroundWindow`, since +//! Windows gives it only to the process the user just started), sends its launch arguments down +//! the pipe and exits. The first process reads them on a thread of its own: the links among +//! them go to `App::on_open_url` as a link the system opened with the app would, and a launch +//! without links reopens the app, which brings its front window forward. +//! +//! Linux starts a new process for every launch too (a desktop entry, `xdg-open myapp://…`). The +//! first process binds a Unix socket in the user's runtime folder +//! (`$XDG_RUNTIME_DIR/rune-instance-<id>.sock`, which only the user can reach); a later one +//! connects, sends the same message and waits for the same answer. A socket left by a process +//! that died refuses the connection: the launch removes it and binds its own. One held by a +//! process that doesn't answer is taken over the same way, as Windows passes over its name. +//! Launches claim one at a time (a lock beside the socket), so two can't both take one over. +//! +//! The links of the launch that started the first process come from its arguments +//! ([`launch_links`]), so `App::on_open_url` gets those too. +//! +//! macOS keeps one process per app itself and hands links to it, so there this only says yes. + +/// Makes this process the app's only running one, before it opens a window (Windows, Linux). +/// +/// Returns false when another process of the app already runs: this launch's links went to +/// its `App::on_open_url`, or, without links, it brought its front window forward, so return +/// from `main` without opening a window. Returns true when this is the first process, which +/// from now on receives the launches that follow, and also when the first can't be reached +/// (it hangs or is exiting), so the launch still opens a window. A launch that reaches the first +/// while it quits (its windows closing) starts the app again once that process has exited, as +/// `Tx::relaunch` does, instead of being lost with it. `id` names the app (its +/// reverse-DNS identifier); builds that should run side by side use different ids. +/// +/// macOS and other platforms: always true. macOS already reaches the running app. +pub fn single_instance(id: &str) -> bool { + // A relaunch (`Tx::relaunch`) claims once the process it restarts has let go. + crate::relaunch::wait_for_previous(); + #[cfg(target_os = "windows")] + { + windows::claim(id) + } + #[cfg(target_os = "linux")] + { + linux::claim(id) + } + #[cfg(not(any(target_os = "windows", target_os = "linux")))] + { + let _ = id; + true + } +} + +/// Lets go of the app's single-instance name before the process ends (Windows, Linux): call it +/// once the app holds nothing a next process of it needs (its files closed). A launch that came +/// while the app quit was handed on to a new process (`single_instance`), which claims the name as +/// soon as this returns rather than when this process is gone. Without it the name goes with the +/// process. Elsewhere it does nothing. +pub fn release_instance() { + #[cfg(target_os = "windows")] + windows::release(); + #[cfg(target_os = "linux")] + linux::release(); +} + +/// Whether a launch argument is a link: `scheme://…`, with a scheme of at least two letters, +/// digits, `+`, `-` or `.`, starting with a letter. A Windows path (`C:\…`) and a flag aren't. +#[cfg_attr(not(any(target_os = "windows", target_os = "linux")), allow(dead_code))] +pub(crate) fn is_link(arg: &str) -> bool { + let Some((scheme, _)) = arg.split_once("://") else { return false }; + scheme.len() >= 2 + && scheme.starts_with(|c: char| c.is_ascii_alphabetic()) + && scheme.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '-' | '.')) +} + +/// The links among this process's launch arguments (Windows passes a link to the process it +/// starts for it as an argument). +#[cfg_attr(not(target_os = "windows"), allow(dead_code))] +pub(crate) fn launch_links() -> Vec<String> { + std::env::args().skip(1).filter(|a| is_link(a)).collect() +} + +/// The loop's side of a later launch without links (`on_relaunch`), and the window it brings +/// forward (Windows). +#[cfg(any(target_os = "windows", target_os = "linux"))] +pub(crate) use handoff::{exited, launches_waiting, on_relaunch, served}; +#[cfg(target_os = "windows")] +pub(crate) use windows::raise_front; + +/// What Windows' pipe and Linux's socket share: the message, its answers and their waits, and +/// what the first process does with a launch it took. +#[cfg(any(target_os = "windows", target_os = "linux"))] +mod handoff { + use std::sync::Mutex; + use std::sync::atomic::{AtomicBool, Ordering}; + use std::time::{Duration, Instant}; + + /// Opens every message, so a stray client's bytes aren't taken for arguments: a length and + /// the arguments follow, and the sender waits for one byte back (`ACCEPTED`, `QUITTING`). + pub(super) const MAGIC: &[u8] = b"rune-instance 2\0"; + /// The running process took the launch. + pub(super) const ACCEPTED: u8 = b'A'; + /// The running process quits: the launch claims the instance once it lets go. + pub(super) const QUITTING: u8 = b'Q'; + /// How long a launch waits for the running process to answer before it takes the name for + /// held by nobody. A healthy process answers in 63-82 µs (p50-p95, Windows, release); this + /// leaves room for one that waits for a busy CPU, and is what a launch pays while a killed + /// process's pipe lingers and its pid can't be read. + pub(super) const ANSWER_WITHIN: Duration = Duration::from_millis(50); + /// The most a launch's arguments may take. + pub(super) const MAX_MESSAGE: usize = 1 << 20; + /// How long a later launch keeps trying to reach the first process. + pub(super) const REACH_FOR: Duration = Duration::from_secs(5); + /// How long a launch handed on by a quitting process waits for it to let go of the name. + pub(super) const HANDED_WAIT: Duration = Duration::from_secs(10); + + /// The argument that carries a launch's id: each launch sends one, the same on every ask, and + /// the running process acts on an id once (`relaunched`). A launch it acted on whose answer + /// never reached it asks again, and that ask is a no-op, so one click opens once whatever the + /// pipe's flush reports. A process from before it takes it for an argument it doesn't know. + pub(super) const ID_ARG: &str = "--rune-launch-id="; + /// How many acted-on launch ids the running process remembers. + const IDS_KEPT: usize = 64; + + /// This launch's id: random, once per process. + fn launch_id() -> &'static str { + static ID: std::sync::OnceLock<String> = std::sync::OnceLock::new(); + ID.get_or_init(|| { + use std::hash::{BuildHasher, Hash, Hasher}; + let half = |salt: u8| { + let mut h = std::collections::hash_map::RandomState::new().build_hasher(); + (salt, std::process::id(), crate::time::now()).hash(&mut h); + h.finish() + }; + format!("{:016x}{:016x}", half(0), half(1)) + }) + } + + /// This launch's message: `MAGIC`, the body's length (u32, little-endian), and the body (its + /// id, then the arguments, NUL-separated). + pub(super) fn message() -> Vec<u8> { + let id = format!("{ID_ARG}{}", launch_id()); + let body = std::iter::once(id).chain(std::env::args().skip(1).filter(|a| !a.starts_with(ID_ARG))).collect::<Vec<_>>().join("\0").into_bytes(); + let mut message = MAGIC.to_vec(); + message.extend((body.len() as u32).to_le_bytes()); + message.extend(body); + message + } + + /// A message's body as the launch's arguments; none when it isn't UTF-8. + #[cfg_attr(target_os = "windows", allow(dead_code))] + pub(super) fn arguments(body: &[u8]) -> Option<Vec<String>> { + Some(std::str::from_utf8(body).ok()?.split('\0').filter(|a| !a.is_empty()).map(str::to_owned).collect()) + } + type Relaunch = Box<dyn Fn() -> bool + Send>; + + /// Sends a launch without links to the loop as a reopen; set once the loop runs. + static RELAUNCH: Mutex<Option<Relaunch>> = Mutex::new(None); + + /// Launches handed to the loop (a reopen, or links for `App::on_open_url`) that no shown + /// window has served yet; once the loop has ended (`exited`), a launch starts the app again + /// instead. + struct Waiting { + launches: Vec<(Instant, Vec<String>)>, + exited: bool, + } + + static WAITING: Mutex<Waiting> = Mutex::new(Waiting { launches: Vec::new(), exited: false }); + /// The ids of the last launches acted on (`ID_ARG`), oldest first. + static ACTED: Mutex<std::collections::VecDeque<String>> = Mutex::new(std::collections::VecDeque::new()); + /// Whether `WAITING` holds a launch: the loop's per-turn check costs a load. + static PENDING: AtomicBool = AtomicBool::new(false); + /// A launch older than this when the loop ends was served by a window that went later (an app + /// that runs on without windows, then quits): it doesn't start the app again. + const UNSERVED_FOR: Duration = Duration::from_secs(5); + + /// Whether a launch waits for a shown window to serve it. + pub(crate) fn launches_waiting() -> bool { + PENDING.load(Ordering::Acquire) + } + + /// The loop goes on with a window shown: the launches so far reached it. + pub(crate) fn served() { + WAITING.lock().unwrap_or_else(|e| e.into_inner()).launches.clear(); + PENDING.store(false, Ordering::Release); + } + + /// The loop ended: each launch no window served starts the app again once this process lets + /// go of the instance, as does every launch from now on. + pub(crate) fn exited() { + let launches = { + let mut waiting = WAITING.lock().unwrap_or_else(|e| e.into_inner()); + waiting.exited = true; + std::mem::take(&mut waiting.launches) + }; + for (at, args) in launches { + if at.elapsed() < UNSERVED_FOR { + crate::relaunch::spawn_with(args); + } + } + } + + /// The loop runs: a launch without links calls `relaunch` from now on (`WakeEvent::Reopen`). + pub(crate) fn on_relaunch(relaunch: impl Fn() -> bool + Send + 'static) { + *RELAUNCH.lock().unwrap_or_else(|e| e.into_inner()) = Some(Box::new(relaunch)); + } + + /// A later launch's arguments: its links to `App::on_open_url`, or, without links, a reopen. + /// One that comes while the app quits, or that the loop hadn't taken when it ended, starts the + /// app again with them once this process has exited, as `Tx::relaunch` does: the windows it + /// would reach are closing, and the launch would be lost. A launch whose id was acted on + /// already (it asked again because its answer didn't reach it) is skipped: false. + pub(super) fn relaunched(args: Vec<String>) -> bool { + let (ids, args): (Vec<String>, Vec<String>) = args.into_iter().partition(|a| a.starts_with(ID_ARG)); + if let Some(id) = ids.into_iter().next() { + let mut acted = ACTED.lock().unwrap_or_else(|e| e.into_inner()); + if acted.contains(&id) { + return false; + } + acted.push_back(id); + if acted.len() > IDS_KEPT { + acted.pop_front(); + } + } + if crate::quit::quitting() { + crate::relaunch::spawn_with(args); + return true; + } + let links: Vec<String> = args.iter().filter(|a| super::is_link(a)).cloned().collect(); + { + let mut waiting = WAITING.lock().unwrap_or_else(|e| e.into_inner()); + if waiting.exited { + drop(waiting); + crate::relaunch::spawn_with(args); + return true; + } + waiting.launches.push((crate::time::now(), args)); + PENDING.store(true, Ordering::Release); + } + if links.is_empty() { + let sent = RELAUNCH.lock().unwrap_or_else(|e| e.into_inner()).as_ref().is_some_and(|relaunch| relaunch()); + if !sent { + exited(); + } + return true; + } + for link in links { + super::super::incoming::receive(link); + } + true + } +} + +#[cfg(target_os = "windows")] +mod windows; + +#[cfg(target_os = "linux")] +mod linux; \ No newline at end of file diff --git a/app/vendor/rune/crates/rune/src/open_url/instance/linux.rs b/app/vendor/rune/crates/rune/src/open_url/instance/linux.rs new file mode 100644 index 0000000..e8ae79f --- /dev/null +++ b/app/vendor/rune/crates/rune/src/open_url/instance/linux.rs @@ -0,0 +1,203 @@ +use std::io::{ErrorKind, Read, Write}; +use std::os::unix::fs::{DirBuilderExt, MetadataExt, PermissionsExt}; +use std::os::unix::net::{UnixListener, UnixStream}; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::{Mutex, OnceLock}; +use std::time::Duration; + +use super::handoff::{ACCEPTED, ANSWER_WITHIN, HANDED_WAIT, MAGIC, MAX_MESSAGE, QUITTING, REACH_FOR, arguments, message, relaunched}; + +/// `sockaddr_un`'s path holds 108 bytes, its NUL included. +const PATH_MAX: usize = 107; + +/// The claimed socket's path and inode (a launch that took it over binds its own there, which +/// `release` leaves alone), and the listener's thread. +static CLAIMED: OnceLock<(PathBuf, u64)> = OnceLock::new(); +static LISTENER: Mutex<Option<std::thread::JoinHandle<()>>> = Mutex::new(None); +/// `release` asked the listener to stop. +static RELEASED: AtomicBool = AtomicBool::new(false); + +pub(super) fn claim(id: &str) -> bool { + // No runtime folder of the user's own: run unclaimed rather than not at all. + let Some(path) = socket_path(id) else { return true }; + let handed = crate::relaunch::handed_from().map(|pid| (pid, crate::time::now() + HANDED_WAIT)); + // One launch at a time decides: between finding the socket stale (or its process hung) and + // binding its own, no other launch looks. The kernel lets go of a killed holder's lock. + let Ok(lock) = std::fs::OpenOptions::new().create(true).truncate(false).write(true).open(path.with_extension("lock")) else { return true }; + if lock.lock().is_err() { + return true; + } + let deadline = crate::time::now() + REACH_FOR; + loop { + match UnixListener::bind(&path) { + Ok(listener) => return claimed(path, listener), + Err(e) if e.kind() == ErrorKind::AddrInUse => {} + Err(_) => return true, + } + // A launch a quitting process handed on waits for it to let go (`release_instance`). + if let Some((pid, until)) = handed + && crate::time::now() < until + && crate::relaunch::alive(pid) + { + std::thread::sleep(Duration::from_millis(1)); + continue; + } + match send(&path) { + Sent::Delivered => return false, + Sent::Quitting => wait_free(&path), + // Nobody listens there: the process that bound it is gone. Or one listens and + // doesn't answer (hung): the launches from now on are this process's. + Sent::Refused | Sent::Nobody => { + std::fs::remove_file(&path).ok(); + } + // Removed between the bind and the connect: bind again. + Sent::Gone if crate::time::now() < deadline => {} + Sent::Gone => return true, + } + } +} + +/// The socket's path: in `$XDG_RUNTIME_DIR` (the user's own, mode 0700), else in a folder of +/// the user's own under the temporary folder. None when neither can be had, or the path is +/// too long for a socket. +fn socket_path(id: &str) -> Option<PathBuf> { + let clean: String = id.chars().map(|c| if c.is_ascii_alphanumeric() || matches!(c, '.' | '-' | '_') { c } else { '-' }).collect(); + let dir = match std::env::var_os("XDG_RUNTIME_DIR").map(PathBuf::from).filter(|d| d.is_absolute() && d.is_dir()) { + Some(dir) => dir, + None => own_temp_dir()?, + }; + let path = dir.join(format!("rune-instance-{clean}.sock")); + (path.as_os_str().len() <= PATH_MAX).then_some(path) +} + +/// `<temp>/rune-<uid>`, made 0700; none when it's someone else's or others may write to it. +#[allow(unsafe_code)] +fn own_temp_dir() -> Option<PathBuf> { + // SAFETY: getuid has no preconditions and can't fail. + let uid = unsafe { libc::getuid() }; + let dir = std::env::temp_dir().join(format!("rune-{uid}")); + match std::fs::DirBuilder::new().mode(0o700).create(&dir) { + Ok(()) => {} + Err(e) if e.kind() == ErrorKind::AlreadyExists => {} + Err(_) => return None, + } + let meta = std::fs::symlink_metadata(&dir).ok()?; + (meta.is_dir() && meta.uid() == uid && meta.permissions().mode() & 0o077 == 0).then_some(dir) +} + +fn claimed(path: PathBuf, listener: UnixListener) -> bool { + let inode = std::fs::metadata(&path).map_or(0, |m| m.ino()); + CLAIMED.set((path, inode)).ok(); + let spawned = std::thread::Builder::new().name("rune-instance".into()).spawn(move || { + for stream in listener.incoming() { + if RELEASED.load(Ordering::Acquire) { + return; + } + let Ok(mut stream) = stream else { continue }; + // A client that connects and sends nothing doesn't hold the next launch up for long. + stream.set_read_timeout(Some(Duration::from_secs(1))).ok(); + let Some(args) = read(&mut stream) else { continue }; + let quitting = crate::quit::quitting(); + // A sender that stopped waiting (this process didn't answer in time, and the launch + // went on without it) has closed its end: the answer fails and the launch is its own. + let told = stream.write_all(&[if quitting { QUITTING } else { ACCEPTED }]).is_ok(); + drop(stream); + // A launch told the app quits claims the instance itself. + if told && !quitting { + relaunched(args); + } + } + }); + if let Ok(listener) = spawned { + *LISTENER.lock().unwrap_or_else(|e| e.into_inner()) = Some(listener); + } + true +} + +/// Stops listening: a launch from now on binds the name itself (the socket is removed if it's +/// still this process's), and one already connected is told the app quits. Returns once the +/// listener has ended. +pub(super) fn release() { + let Some((path, inode)) = CLAIMED.get() else { return }; + if RELEASED.swap(true, Ordering::AcqRel) { + return; + } + // A launch took the name over while this process didn't answer: the socket there is its, + // and this listener, which nothing reaches any more, goes with the process. + if !std::fs::metadata(path).is_ok_and(|m| m.ino() == *inode) { + return; + } + // An empty connection wakes the listener from `accept`; it's made before the socket goes. + let wake = UnixStream::connect(path).ok(); + std::fs::remove_file(path).ok(); + if let Some(listener) = LISTENER.lock().unwrap_or_else(|e| e.into_inner()).take().filter(|_| wake.is_some()) { + listener.join().ok(); + } +} + +/// One client's message (`MAGIC`, the body's length, the body); none for anything else. +fn read(stream: &mut UnixStream) -> Option<Vec<String>> { + let mut head = [0u8; MAGIC.len() + 4]; + stream.read_exact(&mut head).ok()?; + let len = u32::from_le_bytes(head.strip_prefix(MAGIC)?.try_into().ok()?) as usize; + if len > MAX_MESSAGE { + return None; + } + let mut body = vec![0u8; len]; + stream.read_exact(&mut body).ok()?; + arguments(&body) +} + +enum Sent { + /// The running process took the launch. + Delivered, + /// The running process quits: it removes the socket once it has closed what it holds. + Quitting, + /// No socket there now. + Gone, + /// A socket and nobody listening: its process died without removing it. + Refused, + /// A process listens and doesn't answer within `ANSWER_WITHIN` (hung, or stopped). + Nobody, +} + +/// Sends this launch's arguments to the process listening at `path` and waits, at most +/// `ANSWER_WITHIN`, for its answer. +fn send(path: &Path) -> Sent { + let deadline = crate::time::now() + ANSWER_WITHIN; + let mut stream = match UnixStream::connect(path) { + Ok(stream) => stream, + Err(e) if e.kind() == ErrorKind::ConnectionRefused => return Sent::Refused, + Err(e) if e.kind() == ErrorKind::NotFound => return Sent::Gone, + Err(_) => return Sent::Nobody, + }; + let left = || Some(deadline.saturating_duration_since(crate::time::now()).max(Duration::from_millis(1))); + stream.set_write_timeout(left()).ok(); + let mut answer = [0u8; 1]; + let answered = stream.write_all(&message()).is_ok() && { + crate::marks::mark("instance.sent"); + stream.set_read_timeout(left()).ok(); + stream.read_exact(&mut answer).is_ok() + }; + crate::marks::mark("instance.answered"); + match (answered, answer[0]) { + (true, ACCEPTED) => Sent::Delivered, + (true, QUITTING) => Sent::Quitting, + _ => Sent::Nobody, + } +} + +/// Waits, at most `HANDED_WAIT`, for a quitting process to remove its socket (or to die with +/// it); a socket still there then is taken over. +fn wait_free(path: &Path) { + let until = crate::time::now() + HANDED_WAIT; + while crate::time::now() < until { + match UnixStream::connect(path) { + Err(e) if e.kind() == ErrorKind::NotFound => return, + Err(e) if e.kind() == ErrorKind::ConnectionRefused => break, + _ => std::thread::sleep(Duration::from_millis(1)), + } + } + std::fs::remove_file(path).ok(); +} diff --git a/app/vendor/rune/crates/rune/src/open_url/instance/windows.rs b/app/vendor/rune/crates/rune/src/open_url/instance/windows.rs new file mode 100644 index 0000000..28c887b --- /dev/null +++ b/app/vendor/rune/crates/rune/src/open_url/instance/windows.rs @@ -0,0 +1,520 @@ +#![allow(unsafe_code)] + +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::{Mutex, OnceLock}; +use std::time::{Duration, Instant}; + +use windows_sys::Win32::Foundation::{ + CloseHandle, ERROR_ACCESS_DENIED, ERROR_BROKEN_PIPE, ERROR_FILE_NOT_FOUND, ERROR_IO_PENDING, ERROR_PIPE_BUSY, ERROR_PIPE_CONNECTED, + GENERIC_READ, GENERIC_WRITE, GetLastError, HANDLE, HWND, INVALID_HANDLE_VALUE, LPARAM, WAIT_OBJECT_0, WAIT_TIMEOUT, +}; +use windows_sys::Win32::Storage::FileSystem::{ + CreateFileW, FILE_FLAG_FIRST_PIPE_INSTANCE, FILE_FLAG_OVERLAPPED, FlushFileBuffers, OPEN_EXISTING, PIPE_ACCESS_DUPLEX, ReadFile, + WriteFile, +}; +use windows_sys::Win32::System::IO::{CancelIoEx, GetOverlappedResult, OVERLAPPED}; +use windows_sys::Win32::System::Pipes::{ + ConnectNamedPipe, CreateNamedPipeW, DisconnectNamedPipe, GetNamedPipeServerProcessId, PIPE_READMODE_BYTE, PIPE_REJECT_REMOTE_CLIENTS, + PIPE_TYPE_BYTE, PIPE_UNLIMITED_INSTANCES, PIPE_WAIT, WaitNamedPipeW, +}; +use windows_sys::Win32::System::RemoteDesktop::ProcessIdToSessionId; +use windows_sys::Win32::System::Threading::{CreateEventW, GetCurrentProcessId, OpenProcess, PROCESS_SYNCHRONIZE, WaitForSingleObject}; +use windows_sys::Win32::UI::WindowsAndMessaging::{ + AllowSetForegroundWindow, EnumWindows, GW_OWNER, GWL_EXSTYLE, GetWindow, GetWindowLongW, GetWindowThreadProcessId, IsIconic, + IsWindowVisible, SW_RESTORE, SetForegroundWindow, ShowWindow, WS_EX_TOOLWINDOW, +}; + +use super::handoff::{ACCEPTED, ANSWER_WITHIN, HANDED_WAIT, MAGIC, MAX_MESSAGE, QUITTING, REACH_FOR, relaunched}; + +/// An older build's message: the arguments until the sender closes, and no answer. +const MAGIC_V1: &[u8] = b"rune-instance 1\0"; +/// Names tried before a launch runs unclaimed (each held by a process that doesn't answer). +const GENERATIONS: u32 = 8; +/// How long a launch waits for a running copy's answer after its first, quick ask +/// (`ANSWER_WITHIN`) went unanswered: a copy that's alive is only slow (a loaded machine). +const ANSWER_LIVE: Duration = Duration::from_secs(1); +/// How long a launch keeps handing itself to a running copy that's alive but doesn't answer +/// before it takes it for hung and starts beside it on the next name, as before. While it +/// waits, the person sees the pointer Windows shows for an app that's starting; then the +/// running copy's window comes forward with what they clicked. +const LIVE_WAIT: Duration = Duration::from_secs(5); + +/// The claimed name, and the listener's thread, for `release`. +static CLAIMED: OnceLock<Vec<u16>> = OnceLock::new(); +static LISTENER: Mutex<Option<std::thread::JoinHandle<()>>> = Mutex::new(None); +/// `release` asked the listener to close the name. +static RELEASED: AtomicBool = AtomicBool::new(false); + +/// Closes the name: the listener takes what's connected (a launch then is handed on, since +/// the app is quitting), closes its handle and ends; this returns once it has. +pub(super) fn release() { + let Some(name) = CLAIMED.get() else { return }; + if RELEASED.swap(true, Ordering::AcqRel) { + return; + } + // An empty connection wakes the listener from ConnectNamedPipe; one that's busy with a + // launch sees the flag once it's done with it. + // SAFETY: `name` is NUL-terminated; the handle, when opened, is closed once. + let woken = unsafe { + let wake = CreateFileW(name.as_ptr(), GENERIC_WRITE, 0, std::ptr::null(), OPEN_EXISTING, 0, std::ptr::null_mut()); + if wake != INVALID_HANDLE_VALUE { + CloseHandle(wake); + true + } else { + GetLastError() == ERROR_PIPE_BUSY + } + }; + // A listener that can't be woken keeps the name until the process ends. + if let Some(listener) = LISTENER.lock().unwrap_or_else(|e| e.into_inner()).take().filter(|_| woken) { + listener.join().ok(); + } +} + +pub(super) fn claim(id: &str) -> bool { + // A launch a quitting process handed on (`relaunch::spawn_with`) waits for that process to + // let go of the name (`release_instance`, or its end): sending to it would only come back. + let handed = crate::relaunch::handed_from().map(|pid| (pid, crate::time::now() + HANDED_WAIT)); + // A name held by a process that doesn't answer (killed, and still being torn down: its + // pipe stays until the last of its threads goes) is passed over for the next. + for generation in 0..GENERATIONS { + let name = wide(&pipe_name(id, generation)); + let deadline = crate::time::now() + REACH_FOR; + // Set once a running copy that's alive doesn't answer in time. + let mut slow: Option<Instant> = None; + loop { + match create(&name) { + Ok(pipe) => return claimed(name, pipe), + Err(ERROR_ACCESS_DENIED) => {} + // Not a pipe name this process may use: run unclaimed rather than not at all. + Err(_) => return true, + } + if let Some((pid, until)) = handed + && crate::time::now() < until + && crate::relaunch::alive(pid) + { + std::thread::sleep(Duration::from_millis(1)); + continue; + } + match send(&name, if slow.is_some() { ANSWER_LIVE } else { ANSWER_WITHIN }) { + Sent::Delivered => return false, + // It quits: the name is free once it has closed what it holds. + Sent::Quitting(server) => match wait_free(&name, server) { + Free::Claimed(pipe) => return claimed(name, pipe), + // Still not ended after the wait (a debugger holding an exiting thread, a + // driver that doesn't let go): pass this name over, as a quit's own wait does. + Free::Held => break, + Free::Ask => continue, + }, + // The first process went between the two calls: claim the name again. + Sent::Gone if crate::time::now() < deadline => continue, + Sent::Gone => return true, + // Alive, and slow: asked again, never started beside, until `LIVE_WAIT` says + // it's hung. Each ask it didn't answer it also didn't act on (`listen`). + Sent::Busy if crate::time::now() < *slow.get_or_insert_with(|| crate::time::now() + LIVE_WAIT) => {} + Sent::Busy | Sent::Nobody => break, + } + } + } + // Every name is held by a process that doesn't answer: run unclaimed rather than not at all. + true +} + +fn claimed(name: Vec<u16>, pipe: HANDLE) -> bool { + CLAIMED.set(name).ok(); + listen(pipe); + true +} + +/// How waiting for a quitting process's name ended. +enum Free { + /// The name is this process's. + Claimed(HANDLE), + /// The process still hasn't ended after `HANDED_WAIT`: the next name is tried. + Held, + /// The process has ended, or the name is someone else's now: the name is asked again. + Ask, +} + +/// Claims `name` as soon as the quitting `server` lets go of it, for at most `HANDED_WAIT`. +fn wait_free(name: &[u16], server: u32) -> Free { + let until = crate::time::now() + HANDED_WAIT; + // One handle for the whole wait: once `server` is gone its pid can be another process's. + let process = Process::open(server); + let mut gone_at = None; + while crate::time::now() < until { + match create(name) { + // The name can come free before the rest of what `server` holds (its files): + // keep the name, but answer only once the process object is signalled. + Ok(pipe) => { + process.wait_until(until); + return Free::Claimed(pipe); + } + Err(ERROR_ACCESS_DENIED) => {} + Err(_) => return Free::Ask, + } + // Gone, yet its name is still held: not for long, or not by it. + if process.ended() && gone_at.get_or_insert_with(crate::time::now).elapsed() > ANSWER_WITHIN { + return Free::Ask; + } + std::thread::sleep(Duration::from_millis(1)); + } + if process.ended() { Free::Ask } else { Free::Held } +} + +/// A process to wait for, held by handle (`SYNCHRONIZE`). None when it couldn't be opened: +/// it has already ended. +struct Process(Option<HANDLE>); + +impl Process { + fn open(pid: u32) -> Process { + // SAFETY: a plain handle request; a process that has ended answers null. + let handle = unsafe { OpenProcess(PROCESS_SYNCHRONIZE, 0, pid) }; + Process((!handle.is_null()).then_some(handle)) + } + + /// Its process object is signalled: it has closed everything it held. + fn ended(&self) -> bool { + // SAFETY: the handle is open until `drop`. + self.0.is_none_or(|h| unsafe { WaitForSingleObject(h, 0) } != WAIT_TIMEOUT) + } + + fn wait_until(&self, until: Instant) { + let Some(h) = self.0 else { return }; + let left = until.saturating_duration_since(crate::time::now()).as_millis().min(u128::from(u32::MAX - 1)) as u32; + // SAFETY: the handle is open until `drop`. + unsafe { WaitForSingleObject(h, left) }; + } +} + +impl Drop for Process { + fn drop(&mut self) { + if let Some(h) = self.0 { + // SAFETY: opened in `open`, closed once. + unsafe { CloseHandle(h) }; + } + } +} + +/// Per user and session, so another account's app, or this account's in another session, +/// never takes this one's launches. Generation 0 is the name every build used; a later one is +/// tried when the names before it are held by processes that don't answer. +fn pipe_name(id: &str, generation: u32) -> String { + let mut session = 0; + // SAFETY: writes the session id into `session`. + unsafe { ProcessIdToSessionId(GetCurrentProcessId(), &mut session) }; + let user = user_sid(); + let clean = |s: &str| s.chars().map(|c| if c == '\\' || c.is_control() { '-' } else { c }).collect::<String>(); + let suffix = if generation == 0 { String::new() } else { format!("-{generation}") }; + let name = format!(r"\\.\pipe\rune-instance-{session}-{}-{}{suffix}", clean(&user), clean(id)); + name.chars().take(256).collect() +} + +/// The user's SID from this process's token, as hex: what names the account without asking the +/// LSA (`GetUserNameW` loads SspiCli.dll and calls into the LSA before the first frame). +fn user_sid() -> String { + use windows_sys::Win32::Security::{GetLengthSid, GetTokenInformation, TOKEN_QUERY, TOKEN_USER, TokenUser}; + use windows_sys::Win32::System::Threading::{GetCurrentProcess, OpenProcessToken}; + let mut token = std::ptr::null_mut(); + let mut buf = [0u64; 64]; + let mut len = 0u32; + // SAFETY: this process's token, queried into a buffer of `size_of_val(&buf)` bytes (8-aligned, + // as TOKEN_USER needs), closed after; the SID it points at lives in that buffer. + unsafe { + if OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &mut token) == 0 { return String::new(); } + let ok = GetTokenInformation(token, TokenUser, buf.as_mut_ptr().cast(), std::mem::size_of_val(&buf) as u32, &mut len) != 0; + CloseHandle(token); + if !ok { return String::new(); } + let sid = (*(buf.as_ptr() as *const TOKEN_USER)).User.Sid; + let bytes = std::slice::from_raw_parts(sid as *const u8, GetLengthSid(sid) as usize); + bytes.iter().map(|b| format!("{b:02x}")).collect() + } +} + +fn wide(s: &str) -> Vec<u16> { + s.encode_utf16().chain(Some(0)).collect() +} + +/// The pipe's first instance, or the error that says why not (`ERROR_ACCESS_DENIED`: another +/// process has it). +fn create(name: &[u16]) -> Result<HANDLE, u32> { + // SAFETY: `name` is NUL-terminated and outlives the call; no security attributes means + // the default ACL, which lets only this user (and administrators) write to it. + let pipe = unsafe { + CreateNamedPipeW( + name.as_ptr(), + PIPE_ACCESS_DUPLEX | FILE_FLAG_FIRST_PIPE_INSTANCE, + PIPE_TYPE_BYTE | PIPE_READMODE_BYTE | PIPE_WAIT | PIPE_REJECT_REMOTE_CLIENTS, + PIPE_UNLIMITED_INSTANCES, + 16, + 64 * 1024, + 0, + std::ptr::null(), + ) + }; + // SAFETY: reads this thread's last error. + if pipe == INVALID_HANDLE_VALUE { Err(unsafe { GetLastError() }) } else { Ok(pipe) } +} + +/// Reads one launch at a time from the pipe until `release` (or the process ends), and answers +/// each (`ACCEPTED`, or `QUITTING` while the app quits: the launch then claims the instance +/// itself once this process lets go). The handle stays open meanwhile, so the name stays this +/// process's. +fn listen(pipe: HANDLE) { + let pipe = pipe as usize; + let spawned = std::thread::Builder::new().name("rune-instance".into()).spawn(move || { + let pipe = pipe as HANDLE; + loop { + // SAFETY: `pipe` is the open server handle; a client that connected before this + // call answers ERROR_PIPE_CONNECTED. + let connected = unsafe { ConnectNamedPipe(pipe, std::ptr::null_mut()) } != 0 || unsafe { GetLastError() } == ERROR_PIPE_CONNECTED; + if connected && let Some(launch) = read(pipe) { + hold(); + let quitting = crate::quit::quitting(); + // A launch that waits for its answer is acted on only once it has read it: one + // that gave up first (the flush fails once it closes its end) asks again, and + // that ask is the one acted on, so a click opens once. + let told = !launch.answers || { + let answer = [if quitting { QUITTING } else { ACCEPTED }]; + let mut written = 0; + // SAFETY: one byte from `answer` to the connected client; the flush waits + // for the client to read it (or to close), so the disconnect below + // doesn't discard it. The error is read right after the call that failed. + let (wrote, flushed) = unsafe { + let wrote = WriteFile(pipe, answer.as_ptr(), 1, &mut written, std::ptr::null_mut()) != 0 && written == 1; + let wrote_error = GetLastError(); + let flushed = wrote && FlushFileBuffers(pipe) != 0; + (if wrote { Ok(()) } else { Err(wrote_error) }, if flushed || !wrote { Ok(()) } else { Err(GetLastError()) }) + }; + if let Err(e) = wrote.and(flushed) { + eprintln!("rune-instance: a launch gave up before it read its answer ({} failed, error {e}); not acted on", if wrote.is_err() { "write" } else { "flush" }); + } + wrote.is_ok() && flushed.is_ok() + }; + // A launch told the app quits claims the instance itself; one that couldn't + // be told (an older sender) is started again once this process exits. + if told && !(quitting && launch.answers) { + let acted = relaunched(launch.args); + // Counted by the harness (no arguments: they may hold what the person typed). + if HOLD.get().is_some_and(|ms| *ms > 0) { + eprintln!("rune-instance: {}", if acted { "acted on a launch" } else { "a launch asked again after it was acted on; skipped" }); + } + } + } + // SAFETY: ends this client's connection, so the next can connect. + unsafe { DisconnectNamedPipe(pipe) }; + if RELEASED.load(Ordering::Acquire) { + // SAFETY: the server handle this thread owns, closed once: the name is free. + unsafe { CloseHandle(pipe) }; + return; + } + } + }); + match spawned { + Ok(listener) => *LISTENER.lock().unwrap_or_else(|e| e.into_inner()) = Some(listener), + // SAFETY: the handle no thread took. + Err(_) => unsafe { + CloseHandle(pipe as HANDLE); + }, + } +} + +/// A harness's stand-in for a busy machine: `RUNE_INSTANCE_HOLD_MS` holds each launch that long +/// before it's answered. Only under `RUNE_DIRS_ROOT`, a scratch run's. +static HOLD: OnceLock<u64> = OnceLock::new(); + +fn hold() { + let ms = *HOLD.get_or_init(|| { + rune_core::env::var("RUNE_DIRS_ROOT").and(rune_core::env::var("RUNE_INSTANCE_HOLD_MS")).and_then(|v| v.parse().ok()).unwrap_or(0) + }); + if ms > 0 { + std::thread::sleep(Duration::from_millis(ms)); + } +} + +/// A launch read from the pipe: its arguments, and whether its sender waits for an answer. +struct Launch { + args: Vec<String>, + answers: bool, +} + +/// One client's message: `MAGIC`, the body's length (u32, little-endian) and the body, after +/// which the client waits for its answer; or, from an older sender, `MAGIC_V1` and the body +/// until it closes its end. None for anything else. +fn read(pipe: HANDLE) -> Option<Launch> { + let mut message = Vec::new(); + let mut buf = [0u8; 4096]; + let complete = |m: &[u8]| { + let len = m.strip_prefix(MAGIC)?.get(..4)?; + let len = u32::from_le_bytes(len.try_into().ok()?) as usize; + (m.len() >= MAGIC.len() + 4 + len).then_some(len) + }; + let (body, answers) = loop { + if let Some(len) = complete(&message) { + break (message[MAGIC.len() + 4..MAGIC.len() + 4 + len].to_vec(), true); + } + let mut got = 0; + // SAFETY: reads at most `buf.len()` bytes into `buf`. + let ok = unsafe { ReadFile(pipe, buf.as_mut_ptr(), buf.len() as u32, &mut got, std::ptr::null_mut()) } != 0; + message.extend_from_slice(&buf[..got as usize]); + if message.len() > MAX_MESSAGE { + return None; + } + // SAFETY: reads this thread's last error. + if !ok && unsafe { GetLastError() } == ERROR_BROKEN_PIPE { + break (message.strip_prefix(MAGIC_V1)?.to_vec(), false); + } + if !ok { + return None; + } + }; + let text = std::str::from_utf8(&body).ok()?; + Some(Launch { args: text.split('\0').filter(|a| !a.is_empty()).map(str::to_owned).collect(), answers }) +} + +enum Sent { + /// The running process took the launch. + Delivered, + /// The running process quits: it lets go of the name once it has closed what it holds. + Quitting(u32), + /// No process has the name now. + Gone, + /// A process has the name and doesn't answer (killed and still being torn down, or gone + /// with an inherited handle left): nobody is there to take the launch. + Nobody, + /// A running process has the name and didn't answer in time (or talks to another launch): + /// slow, or hung. + Busy, +} + +/// Sends this launch's arguments to the process that has the pipe and waits, at most +/// `within`, for its answer. +fn send(name: &[u16], within: Duration) -> Sent { + let deadline = crate::time::now() + within; + let left = || u32::try_from(deadline.saturating_duration_since(crate::time::now()).as_millis()).unwrap_or(u32::MAX); + let pipe = loop { + // SAFETY: `name` is NUL-terminated; opens the pipe's client end, overlapped so the + // answer can be waited for with a deadline. + let pipe = unsafe { CreateFileW(name.as_ptr(), GENERIC_READ | GENERIC_WRITE, 0, std::ptr::null(), OPEN_EXISTING, FILE_FLAG_OVERLAPPED, std::ptr::null_mut()) }; + if pipe != INVALID_HANDLE_VALUE { + break pipe; + } + // SAFETY: reads this thread's last error. + match unsafe { GetLastError() } { + ERROR_FILE_NOT_FOUND => return Sent::Gone, + // Another launch is talking to it: wait for the pipe to be free. + // SAFETY: `name` is NUL-terminated. + ERROR_PIPE_BUSY if left() > 0 => unsafe { + WaitNamedPipeW(name.as_ptr(), left()); + }, + // Still talking to another launch. + ERROR_PIPE_BUSY => return Sent::Busy, + _ => return Sent::Nobody, + } + }; + let mut server = 0; + // SAFETY: `pipe` is the open client handle. The first process may take the foreground + // for the window this launch asks for, as this process, which the user just started, could. + unsafe { + if GetNamedPipeServerProcessId(pipe, &mut server) != 0 { + AllowSetForegroundWindow(server); + } + } + // A killed process's pipe outlasts its exit code until the kernel closes its handles: + // nobody reads it, and the name comes free once it's gone. Wait for that (as for a quit) + // rather than take the next name and start beside a process that still holds files. + if server != 0 && crate::relaunch::ending(server) { + // SAFETY: the client handle, closed once. + unsafe { CloseHandle(pipe) }; + return Sent::Quitting(server); + } + // Held by a process that is gone (an inherited handle): nobody reads it. + if server != 0 && !crate::relaunch::alive(server) { + // SAFETY: the client handle, closed once. + unsafe { CloseHandle(pipe) }; + return Sent::Nobody; + } + let message = super::handoff::message(); + let mut answer = [0u8; 1]; + + let answered = io(pipe, deadline, |o| { + // SAFETY: writes `message`, which outlives the wait in `io`, to the open pipe. + unsafe { WriteFile(pipe, message.as_ptr(), message.len() as u32, std::ptr::null_mut(), o) } + }) + .filter(|n| *n as usize == message.len()) + .inspect(|_| crate::marks::mark("instance.sent")) + .and_then(|_| { + io(pipe, deadline, |o| { + // SAFETY: reads at most one byte into `answer`, which outlives the wait in `io`. + unsafe { ReadFile(pipe, answer.as_mut_ptr(), 1, std::ptr::null_mut(), o) } + }) + }); + // SAFETY: the client handle, closed once. + unsafe { CloseHandle(pipe) }; + crate::marks::mark("instance.answered"); + match (answered, answer[0]) { + (Some(1), ACCEPTED) => Sent::Delivered, + (Some(1), QUITTING) => Sent::Quitting(server), + // It's alive (checked above) and didn't answer in time. + _ if server != 0 => Sent::Busy, + _ => Sent::Nobody, + } +} + +/// One overlapped read or write on `pipe`, waited for until `deadline`: the bytes it moved, or +/// none when it failed. One that didn't finish in time is cancelled, but if it completed as the +/// wait ran out, what it moved counts: an answer read is an answer the other end saw taken. +fn io(pipe: HANDLE, deadline: Instant, start: impl FnOnce(*mut OVERLAPPED) -> i32) -> Option<u32> { + // SAFETY: a manual-reset event, unnamed; closed once below. + let event = unsafe { CreateEventW(std::ptr::null(), 1, 0, std::ptr::null()) }; + if event.is_null() { + return None; + } + // SAFETY: an all-zero OVERLAPPED is a valid start for an operation; it lives until the + // operation is done or cancelled and waited for. + let mut o: OVERLAPPED = unsafe { std::mem::zeroed() }; + o.hEvent = event; + let left = u32::try_from(deadline.saturating_duration_since(crate::time::now()).as_millis()).unwrap_or(u32::MAX); + // SAFETY: `o` outlives the operation: it's waited for, or cancelled and waited for, below. + unsafe { + let started = start(&mut o) != 0 || GetLastError() == ERROR_IO_PENDING; + let finished = started && WaitForSingleObject(event, left) == WAIT_OBJECT_0; + if started && !finished { + CancelIoEx(pipe, &o); + } + let mut n = 0; + let ok = started && GetOverlappedResult(pipe, &o, &mut n, 1) != 0; + CloseHandle(event); + ok.then_some(n) + } +} + +/// Restores and activates this process's front app window: its topmost visible top-level +/// window that isn't owned or a tool window (an overlay). +pub(crate) fn raise_front() { + unsafe extern "system" fn each(hwnd: HWND, found: LPARAM) -> i32 { + // SAFETY: `found` points at the `HWND` `raise_front` passed, alive for the walk. + unsafe { + let mut pid = 0; + GetWindowThreadProcessId(hwnd, &mut pid); + let tool = GetWindowLongW(hwnd, GWL_EXSTYLE) as u32 & WS_EX_TOOLWINDOW != 0; + let owned = !GetWindow(hwnd, GW_OWNER).is_null(); + if pid == GetCurrentProcessId() && IsWindowVisible(hwnd) != 0 && !tool && !owned { + *(found as *mut HWND) = hwnd; + return 0; + } + 1 + } + } + let mut found: HWND = std::ptr::null_mut(); + // SAFETY: the callback only writes `found`, which outlives the walk, front to back. + unsafe { + EnumWindows(Some(each), &mut found as *mut HWND as LPARAM); + if found.is_null() { + return; + } + if IsIconic(found) != 0 { + ShowWindow(found, SW_RESTORE); + } + SetForegroundWindow(found); + } +} diff --git a/app/vendor/rune/crates/rune/src/overlay.rs b/app/vendor/rune/crates/rune/src/overlay.rs new file mode 100644 index 0000000..96e8fbb --- /dev/null +++ b/app/vendor/rune/crates/rune/src/overlay.rs @@ -0,0 +1,760 @@ +//! Overlays: surfaces beside the app's window (a recording HUD, meeting capsules). Each has +//! its own state type and `Runtime`, is fed from any thread through an `OverlayHandle`, and is +//! drawn transparent above other apps. Bare specs preserve edge placement on the primary +//! display and never request keyboard focus. `OverlaySpec::options` adds display targeting, +//! full-display/rect placement, regional input and explicit nonactivating keyboard policy. +//! +//! - Wayland: layer-shell (`layer_shell.rs`) with output-local input regions and a private +//! seat queue. Hidden means destroyed. No global pointer observation or capture exclusion. +//! Without layer-shell (GNOME), an overlay that takes no input shows on XWayland instead +//! (`x11/xwayland.rs`): an override-redirect ARGB window with an empty input shape. One that +//! takes the pointer does too when its host opts in (`OverlayOptions::xwayland_input`). +//! - X11: an override-redirect notification window, with an empty input shape unless +//! interactive. A `KeyPolicy::OnDemand` one sets the input focus itself on `request_keys` and +//! on a click. +//! - macOS: winit's view moved into a non-activating `NSPanel` at status level on every space, +//! observing pointer movement even through transparent regions, ordered front without key +//! focus unless explicitly requested. Its window number is available for capture filters. +//! - Windows: a topmost tool window with `WS_EX_NOACTIVATE` (plus `WS_EX_TRANSPARENT` and +//! `WS_EX_LAYERED` unless interactive), shown with `SW_SHOWNOACTIVATE`. A `KeyPolicy::OnDemand` +//! one is made without `WS_EX_NOACTIVATE`, so a click or `request_keys` activates it. +//! - With `release_gpu_when_hidden`, hidden means destroyed on Windows and macOS too. + +use std::cell::RefCell; +use std::rc::Rc; +use std::sync::atomic::{AtomicU8, Ordering}; +use std::sync::{Arc, Mutex, Weak}; +use std::time::Duration; +use crate::time::Instant; + +use winit::dpi::LogicalSize; +use winit::event::{StartCause, WindowEvent}; +use winit::event_loop::ActiveEventLoop; +use winit::window::{Window, WindowId, WindowLevel}; + +use crate::el::{Align, El, Tx}; +use crate::frame::clock::FrameClock; +use crate::render::{Gpu, Renderer}; +use crate::runtime::{Cx, RuntimeCore, Waker}; +use crate::window::{AnyHost, WakeEvent}; +#[cfg(target_os = "windows")] +use crate::window::slot::{Slot, Take}; +use crate::{DisplayTarget, KeyPolicy, OverlayInput, OverlayOptions, OverlayPlacement, OverlaySupport}; + +#[path = "overlay/any_host.rs"] +mod any_host; +#[path = "overlay/app.rs"] +mod app; +#[path = "overlay/draw.rs"] +mod draw; +#[path = "overlay/frame.rs"] +mod frame; +use frame::{OverlayRenderArgs, idle_after, render_frame, step}; +#[path = "overlay/input.rs"] +mod input; +pub(crate) mod keys; +#[path = "overlay/lifetime.rs"] +mod lifetime; +pub(crate) mod options; +#[path = "overlay/placement.rs"] +mod placement; +#[cfg(not(target_os = "macos"))] +pub(crate) use placement::monitor_at; +use placement::{monitor, position}; +mod presence; +use presence::{Presence, Release}; +mod requests; +use requests::{Requests, Update, Visibility}; +#[path = "overlay/surface.rs"] +mod surface; +#[path = "overlay/xwayland.rs"] +mod xwayland; + +pub(crate) use app::OverlayHost; +use app::OverlayApp; +#[cfg(test)] +use crate::compose::{Compositor, Frame}; +#[cfg(test)] +use crate::tooling::AppSpec; +#[cfg(test)] +use app::Overlay; + +/// The screen edge an overlay sits on. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum ScreenEdge { + #[default] + Top, + Bottom, +} + +pub struct OverlaySpec<T: 'static> { + /// The window title, or the layer-shell namespace on Wayland. + pub name: &'static str, + /// In points. + pub size: (f32, f32), + pub edge: ScreenEdge, + /// Distance from the edge, in points. + pub margin: f32, + /// Along the edge: centred, or at the start (left) or end (right) `inset` points in. + pub align: Align, + pub inset: f32, + /// Clicks reach the view (meeting capsule buttons); otherwise they pass through. + pub interactive: bool, + /// The overlay's view. Its root should have no fill: whatever it leaves clear stays + /// transparent. + pub view: fn(&T, &mut Cx<T>) -> El, +} + +/// Whether the platform could show the overlay, known after its first `show`. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Availability { + Unknown, + Available, + /// Wayland without layer-shell, or its window, surface or show failed (`OverlayHandle::failure`). + Unavailable, +} + +/// Where an overlay sits and how big it is, in points. +#[derive(Clone, Copy, Debug, PartialEq)] +pub(crate) struct Placement { + pub size: (f32, f32), + pub edge: ScreenEdge, + pub margin: f32, + pub align: Align, + pub inset: f32, +} + +/// Non-generic shared state backing [`OverlayHandle<T>`] and [`OverlayCore`]. +#[derive(Default)] +pub(in crate::overlay) struct SharedCore { + pub(in crate::overlay) native: Mutex<(Option<u32>, crate::OverlayCapabilities)>, + pub(in crate::overlay) requests: Mutex<Requests>, + pub(in crate::overlay) availability: AtomicU8, + /// Why the platform could not create or show the overlay, while it can't. + pub(in crate::overlay) failure: Mutex<Option<String>>, + /// What draws the overlay: backend, adapter and alpha mode, once its surface exists. + pub(in crate::overlay) surface: Mutex<Option<String>>, + /// The event loop's wake-up for this overlay; empty until the loop runs. + pub(in crate::overlay) wake: Mutex<Option<Waker>>, + /// What the overlay's meter last published. + pub(in crate::overlay) stats: Arc<Mutex<crate::SurfaceStats>>, +} + +impl SharedCore { + pub(super) fn wake(&self) { + let wake = self.wake.lock().unwrap().clone(); + if let Some(wake) = wake { + wake(); + } + } + + fn request(&self, f: impl FnOnce(&mut Requests)) { + f(&mut self.requests.lock().unwrap()); + self.wake(); + } + + fn set_input(&self, input: OverlayInput) { self.request(|q| q.input = Some(input)); } + fn set_follow_pointer(&self, follow: bool) { self.request(|q| q.follow_pointer = Some(follow)); } + fn refollow_pointer(&self) { self.request(|q| q.refollow = true); } + fn set_placement(&self, placement: Option<OverlayPlacement>) { self.request(|q| q.placement = Some(placement)); } + fn set_display(&self, display: DisplayTarget) { self.request(|q| q.display = Some(display)); } + fn request_keys(&self) { self.request(|q| q.request_keys = true); } + fn window_number(&self) -> Option<u32> { self.native.lock().unwrap().0 } + fn capture_exclusion(&self) -> OverlaySupport { self.capabilities().capture_exclusion } + fn capabilities(&self) -> crate::OverlayCapabilities { self.native.lock().unwrap().1 } + fn set_exclude_from_capture(&self, exclude: bool) { self.request(|q| q.exclude_from_capture = Some(exclude)); } + fn set_xwayland_input(&self, allow: bool) { self.request(|q| q.xwayland_input = Some(allow)); } + fn surface_stats(&self) -> crate::SurfaceStats { crate::frame::surface_stats::read(&self.stats) } + fn show(&self) { self.request(|q| q.visibility = Some(Visibility::Show(Duration::ZERO))); } + fn hide(&self) { self.request(|q| q.visibility = Some(Visibility::Hide(Duration::ZERO))); } + fn fade_in(&self, duration: Duration) { self.request(|q| q.visibility = Some(Visibility::Show(duration))); } + fn fade_out(&self, duration: Duration) { self.request(|q| q.visibility = Some(Visibility::Hide(duration))); } + fn set_macos_level(&self, level: isize) { self.request(|q| q.macos_level = Some(level)); } + fn set_edge(&self, edge: ScreenEdge) { self.request(|q| q.edge = Some(edge)); } + fn place(&self, edge: ScreenEdge, margin: f32) { + self.request(|q| { + q.edge = Some(edge); + q.margin = Some(margin); + }); + } + fn set_align(&self, align: Align, inset: f32) { self.request(|q| q.align = Some((align, inset))); } + fn resize(&self, size: (f32, f32)) { self.request(|q| q.size = Some(size)); } + fn availability(&self) -> Availability { + match self.availability.load(Ordering::Acquire) { + 1 => Availability::Available, + 2 => Availability::Unavailable, + _ => Availability::Unknown, + } + } + fn failure(&self) -> Option<String> { self.failure.lock().unwrap().clone() } + fn surface_description(&self) -> Option<String> { self.surface.lock().unwrap().clone() } +} + +pub(in crate::overlay) struct Shared<T> { + pub(in crate::overlay) core: Arc<SharedCore>, + pub(in crate::overlay) updates: Mutex<Vec<Update<T>>>, +} + +#[cfg(test)] +impl<T> Default for Shared<T> { + fn default() -> Self { + Self { core: Arc::default(), updates: Mutex::default() } + } +} + +/// Shows, hides, moves and feeds an overlay from any thread; every call wakes the event loop. +pub struct OverlayHandle<T: 'static> { + shared: Arc<Shared<T>>, +} + +impl<T> Clone for OverlayHandle<T> { + fn clone(&self) -> Self { + OverlayHandle { shared: self.shared.clone() } + } +} + +impl<T: 'static> OverlayHandle<T> { + /// Takes effect on the next event-loop turn, or after the current owned drag releases. + #[inline(always)] + pub fn set_input(&self, input: OverlayInput) { self.shared.core.set_input(input); } + #[inline(always)] + pub fn set_follow_pointer(&self, follow: bool) { self.shared.core.set_follow_pointer(follow); } + /// Moves a shown [`DisplayTarget::UnderPointer`] overlay to the display under the pointer + /// when two calls in a row find it on the same other display; at once, without taking + /// focus. A caller's own pace + /// (a HUD's few checks a second) instead of `follow_pointer`'s pointer watch. Windows and + /// X11; elsewhere it does nothing. + #[inline(always)] + pub fn refollow_pointer(&self) { self.shared.core.refollow_pointer(); } + /// None restores the spec's legacy edge placement. + #[inline(always)] + pub fn set_placement(&self, placement: Option<OverlayPlacement>) { self.shared.core.set_placement(placement); } + #[inline(always)] + pub fn set_display(&self, display: DisplayTarget) { self.shared.core.set_display(display); } + + /// Request keyboard focus without application activation, for a shown `KeyPolicy::OnDemand` + /// overlay where `capabilities().nonactivating_keys` is `Supported` (see `KeyPolicy`). + #[inline(always)] + pub fn request_keys(&self) { self.shared.core.request_keys(); } + + /// macOS panel CGWindowID for an explicit ScreenCaptureKit exclusion filter. Available + /// at native creation (see `on_created`/`prewarm`); a new one with each window made. + #[inline(always)] + pub fn window_number(&self) -> Option<u32> { self.shared.core.window_number() } + + /// Result of the native capture-exclusion request. Linux reports Unsupported. + #[inline(always)] + pub fn capture_exclusion(&self) -> OverlaySupport { self.shared.core.capture_exclusion() } + #[inline(always)] + pub fn capabilities(&self) -> crate::OverlayCapabilities { self.shared.core.capabilities() } + /// Changes `OverlayOptions::exclude_from_capture` on the live window. It applies only while + /// the overlay is shown; set while hidden, it takes effect at the next show, so there is no + /// need to toggle it around show and hide. + #[inline(always)] + pub fn set_exclude_from_capture(&self, exclude: bool) { self.shared.core.set_exclude_from_capture(exclude); } + /// Changes `OverlayOptions::xwayland_input`. It applies when the surface is next made, so + /// a call before `show` in the same turn covers that show. + #[inline(always)] + pub fn set_xwayland_input(&self, allow: bool) { self.shared.core.set_xwayland_input(allow); } + + /// The overlay's frame counts: redraws, presents, failed drawable acquisitions, loop turns + /// and pacing: current totals, and per-second rates updated once a second while it draws. + #[inline(always)] + pub fn surface_stats(&self) -> crate::SurfaceStats { self.shared.core.surface_stats() } + + /// Reveal the overlay. Prewarmed macOS overlays refresh hidden changes before reveal, + /// preserving motion elapsed since each commit, even when show arrives in a later turn. + /// Unretained hosts show settled, unless built with `ConfiguredOverlay::animate_reveal`. + #[inline(always)] + pub fn show(&self) { self.shared.core.show(); } + + #[inline(always)] + pub fn hide(&self) { self.shared.core.hide(); } + + /// Like `show`, fading the window's alpha in from zero over `duration` on macOS + /// (AppKit's default ease). Elsewhere the overlay appears at once. + #[inline(always)] + pub fn fade_in(&self, duration: Duration) { self.shared.core.fade_in(duration); } + + /// Like `hide`, fading the window's alpha out over `duration` on macOS and Windows before + /// it goes. Input stops at once, but the overlay keeps drawing until the fade ends, so + /// motion started in the same turn (an exit transition, a poll stepping its own animation) + /// plays out during it, and frames still queued for the screen reach it. A GPU surface + /// given back while hidden goes only once the fade ends. Showing again cancels the fade, + /// and that motion carries on from where it is. Elsewhere the overlay hides at once. + #[inline(always)] + pub fn fade_out(&self, duration: Duration) { self.shared.core.fade_out(duration); } + + /// Change the macOS window level (`NSWindow.Level`, e.g. 3 for `.floating`), shown or not. + /// Overrides `OverlayOptions::level`; other platforms ignore it. + #[inline(always)] + pub fn set_macos_level(&self, level: isize) { self.shared.core.set_macos_level(level); } + + #[inline(always)] + pub fn set_edge(&self, edge: ScreenEdge) { self.shared.core.set_edge(edge); } + + /// Moves the overlay to `edge`, `margin` points in. + #[inline(always)] + pub fn place(&self, edge: ScreenEdge, margin: f32) { self.shared.core.place(edge, margin); } + + /// Moves the overlay along its edge: centred, or `inset` points from the start or end. + #[inline(always)] + pub fn set_align(&self, align: Align, inset: f32) { self.shared.core.set_align(align, inset); } + + /// Resizes the overlay (points), keeping its edge and alignment. + #[inline(always)] + pub fn resize(&self, size: (f32, f32)) { self.shared.core.resize(size); } + + /// Change the overlay's state on the UI thread, in call order, shown or not. + /// `Tx::wake_after` invokes the configured poll at its deadline, including while hidden. + /// A hidden overlay's view doesn't run for it: the frame that shows the overlay builds it + /// once, with the latest state. A prewarmed macOS overlay commits hidden changes at most + /// every 250 ms to keep its retained frame close. + pub fn update(&self, f: impl FnOnce(&mut T, &mut Tx) + Send + 'static) { + self.update_if(move |s, tx| { f(s, tx); true }); + } + + /// `update` for a timer or feed that often finds nothing new: `f` returns whether it changed + /// state the view reads, as `OverlayOptions::poll` does. On false the view doesn't re-run + /// and the overlay neither draws nor refreshes while hidden, while what `f` asked of its + /// `Tx` still happens: clipboard, menus, `wake_after`, and scrolls, which take a frame. + /// + /// Returning false after changing state the view reads leaves the screen stale until the + /// next change. + pub fn update_if(&self, f: impl FnOnce(&mut T, &mut Tx) -> bool + Send + 'static) { + self.shared.updates.lock().unwrap().push(Box::new(f)); + self.shared.core.wake(); + } + + #[inline(always)] + pub fn availability(&self) -> Availability { self.shared.core.availability() } + + /// Why the overlay is `Unavailable`: the window, its GPU surface, or showing it failed. + #[inline(always)] + pub fn failure(&self) -> Option<String> { self.shared.core.failure() } + + /// What draws the overlay, such as `Dx12 on Intel(R) UHD Graphics (IntegratedGpu), + /// PreMultiplied`, once its surface exists; for logs. + #[inline(always)] + pub fn surface_description(&self) -> Option<String> { self.shared.core.surface_description() } +} + +/// An overlay before the event loop runs: the shell gives it a wake-up and the GPU pool. +pub(crate) trait PendingOverlay: AnyHost { + fn connect(&mut self, wake: Waker, frame_wake: Waker, slot_wake: Waker, gpu: Rc<RefCell<Weak<Gpu>>>); +} + +enum Backing { + Window(Arc<Window>), + #[cfg(all(unix, not(target_os = "macos"), not(target_os = "ios"), not(target_os = "android")))] + Layer(crate::platform::layer_shell::LayerSurface), + /// Wayland without layer-shell: an X11 window on XWayland, for overlays that take no input + /// or whose host opted in to pointer input there. + #[cfg(all(unix, not(target_os = "macos"), not(target_os = "ios"), not(target_os = "android")))] + Xwayland(crate::platform::x11::xwayland::XwaylandSurface), +} + +impl Backing { + fn window(&self) -> Option<&Arc<Window>> { + match self { + Backing::Window(w) => Some(w), + #[cfg(all(unix, not(target_os = "macos"), not(target_os = "ios"), not(target_os = "android")))] + Backing::Layer(_) | Backing::Xwayland(_) => None, + } + } +} + +/// A shown overlay. The wgpu surface drops before what it draws into. +struct Live { + /// The OS accessibility adapter for this surface. + a11y: Option<crate::a11y::Adapter>, + /// Presents plain frames off the event loop's thread; joined before the surface drops. + #[cfg(target_os = "macos")] + present: Option<crate::frame::present_worker::PresentWorker>, + #[cfg(target_os = "macos")] + pacing: Option<crate::platform::display_link::DisplayLink>, + /// `El::system_material` views behind the Metal layer. + #[cfg(target_os = "macos")] + materials: crate::system_material::macos::Materials, + /// Fn presses, which winit doesn't send, while the overlay wants modifier keys. + #[cfg(target_os = "macos")] + fn_key: Option<crate::input::fn_key::FnKey>, + /// Whether the swap chain can take the next frame, and the wait when it can't + /// (`window::slot`). Before the surface so an outstanding wait goes first. + #[cfg(target_os = "windows")] + slot: Slot, + alpha: Option<crate::render::surface_alpha::AlphaSurface>, + surface: wgpu::Surface<'static>, + config: wgpu::SurfaceConfiguration, + backing: Backing, + scale: f32, +} + +/// All non-generic state of an overlay host, compiled once. +pub(in crate::overlay) struct OverlayCore { + on_created: Option<Box<dyn FnMut(crate::OverlayCreated)>>, + pending_input: Option<OverlayInput>, + presence: Presence, + animate_reveal: bool, // `ConfiguredOverlay::animate_reveal` + options: OverlayOptions, + canvas_size: (f32, f32), + name: &'static str, + at: Placement, + /// Where `place_window` last put the window, to carry the pointer across a move. + origin: Option<winit::dpi::PhysicalPosition<i32>>, + interactive: bool, + /// `ConfiguredOverlay::macos_level` or the last `set_macos_level`. + #[cfg_attr(not(target_os = "macos"), allow(dead_code))] + macos_level: Option<isize>, + shared: Arc<SharedCore>, + clipboard: crate::clipboard::Client, + popup: crate::popup_menu::Presenter, + /// The non-activating panel holding winit's view (macOS), kept with the window. Declared + /// before the window so the view goes back to it first. + #[cfg(target_os = "macos")] + panel: Option<crate::platform::macos::Panel>, + #[cfg(target_os = "windows")] + native: Option<crate::platform::win32::OverlayWindow>, + #[cfg(all(unix, not(target_os = "macos"), not(target_os = "ios"), not(target_os = "android")))] + x11: Option<crate::platform::x11::overlay::InputWindow>, + surface: surface::Surface, + /// `ConfiguredOverlay::release_gpu_when_hidden` or `release_gpu_after`. + release: Release, + cursor: Option<crate::cursor::os::OsCursor>, + mods: winit::keyboard::ModifiersState, + control_click: bool, + ime_allowed: bool, + renderer: Option<Renderer>, + gpu: Option<Arc<Gpu>>, + gpu_pool: Rc<RefCell<Weak<Gpu>>>, + dark: bool, + dirty: bool, + idle: bool, + /// After the last frame the runtime asked for no other; only the compositor animates. + runtime_idle: bool, + quiet: frame::Quiet, + /// Whether this event-loop turn already stepped or missed a frame (`frame::TurnFrame`). + turn_frame: frame::TurnFrame, + clock: FrameClock, + /// This loop turn already read the panel's occlusion (`sync_occlusion`). + #[cfg(target_os = "macos")] + occlusion_read: bool, + /// When to try a frame again that had no drawable, or the next frame of motion with no + /// display link to pace it, and the waits behind it (`window::Backoff`). + backoff: crate::window::Backoff, + /// When a hidden retained overlay commits the changes it hasn't yet. + hidden_pace: crate::window::HiddenPace, + #[cfg(target_os = "macos")] + frame_wake: Option<Waker>, + /// Windows: asks the loop for the frame whose swap chain has room (`WakeEvent::FrameSlot`). + #[cfg(target_os = "windows")] + slot_wake: Option<Waker>, + meter: crate::frame::surface_stats::SurfaceMeter, + /// The display `refollow_pointer` last found the pointer on, away from the overlay's. + refollow_away: Option<winit::monitor::MonitorHandle>, +} + +impl OverlayCore { + #[allow(clippy::too_many_arguments)] + pub(super) fn new( + rt: &mut RuntimeCore, + shared: Arc<SharedCore>, + name: &'static str, + at: Placement, + interactive: bool, + options: OverlayOptions, + on_created: Option<Box<dyn FnMut(crate::OverlayCreated)>>, + macos_level: Option<isize>, + animate_reveal: bool, + release_after: Option<Duration>, + ) -> Self { + let meter = crate::frame::surface_stats::SurfaceMeter::new(name, shared.stats.clone()); + rt.set_system_reduced_motion(crate::platform::preferences::reduced_motion()); + crate::platform::accent::watch(); + rt.set_system_accent(crate::system_accent()); + crate::platform::scroll_bars::watch(); + rt.set_system_scroll_bars_state(crate::platform::scroll_bars::current()); + rt.wall_start = Some(crate::time::now()); + rt.host.native_overlay = true; + rt.set_os_drag(crate::drag_out::SUPPORTED); + rt.host.surface_stats = Some(meter.shared()); + OverlayCore { + on_created, + pending_input: None, + presence: Presence::default(), + animate_reveal, + options, + canvas_size: at.size, + name, + at, + origin: None, + interactive, + macos_level, + shared, + clipboard: Default::default(), + popup: Default::default(), + surface: Default::default(), + release: Release::new(release_after), + cursor: None, + #[cfg(target_os = "macos")] + panel: None, + #[cfg(target_os = "windows")] + native: None, + #[cfg(all(unix, not(target_os = "macos"), not(target_os = "ios"), not(target_os = "android")))] + x11: None, + mods: Default::default(), + control_click: false, + ime_allowed: false, + renderer: None, + gpu: None, + gpu_pool: Rc::default(), + dark: true, + dirty: true, + idle: true, + runtime_idle: false, + quiet: Default::default(), + turn_frame: Default::default(), + clock: FrameClock::new(crate::time::now()), + #[cfg(target_os = "macos")] + occlusion_read: false, + backoff: Default::default(), + hidden_pace: Default::default(), + #[cfg(target_os = "macos")] + frame_wake: None, + #[cfg(target_os = "windows")] + slot_wake: None, + meter, + refollow_away: None, + } + } + + fn set_availability(&self, a: Availability) { + let v = match a { + Availability::Unknown => 0, + Availability::Available => 1, + Availability::Unavailable => 2, + }; + self.shared.availability.store(v, Ordering::Release); + } + + /// Marks the overlay `Unavailable` and keeps why, for `OverlayHandle::failure`. + fn fail(&self, reason: String) { + eprintln!("rune: overlay {} can't show: {reason}", self.name); + *self.shared.failure.lock().unwrap() = Some(reason); + self.set_availability(Availability::Unavailable); + } + + pub(super) fn accent_changed(&mut self, rt: &mut RuntimeCore, accent: crate::SystemAccent) { + if accent == rt.system_accent() { return; } + rt.set_system_accent(accent); + self.dirty = true; + } + + pub(super) fn scroll_bars_changed(&mut self, rt: &mut RuntimeCore, bars: crate::platform::scroll_bars::SystemScrollBars) { + if bars == rt.system_scroll_bars_state() { return; } + rt.set_system_scroll_bars_state(bars); + self.dirty = true; + } + + pub(super) fn theme_changed(&mut self, rt: &mut RuntimeCore, dark: bool) { + self.dark = dark; + rt.set_system_dark(dark); + self.dirty = true; + } + + /// Moving the window under a still pointer (`place`, `set_placement`, a resize that keeps + /// the far edge) keeps the runtime's pointer and a held drag in step, so a drag that moves + /// its own overlay reports pointer travel. Hosts that place asynchronously catch up on the + /// next pointer event. + fn place_window(&mut self, rt: &mut RuntimeCore, event_loop: &ActiveEventLoop, window: &Window) { + self.position_window(event_loop, window); + // From the window itself: `window()` places it before it's live. + self.sync_origin(rt, window); + let Ok(origin) = window.outer_position() else { return }; + if let Some(before) = self.origin.replace(origin) && before != origin { + let scale = window.scale_factor(); + let points = |a: i32, b: i32| (f64::from(a - b) / scale) as f32; + rt.window_moved(points(origin.x, before.x), points(origin.y, before.y)); + } + } + + /// Tells the runtime where the overlay's content is on screen (see `El::on_screen_layout`). + fn sync_origin(&mut self, rt: &mut RuntimeCore, window: &Window) { + rt.set_window_pixels(window.inner_position().ok().map(|p| (p.x, p.y))); + if let Some(origin) = crate::window::screen_origin(window) { self.origin_moved(rt, origin); } + } + + fn sync_live_origin(&mut self, rt: &mut RuntimeCore) { + let Some(Backing::Window(window)) = self.surface.live().map(|l| &l.backing) else { return }; + let window = window.clone(); + self.sync_origin(rt, &window); + } + + /// Hidden too, the moved rects wait in the queue and mark the overlay dirty, so a retained + /// reveal steps once (`refresh_for_reveal_at`) and delivers them; only a drawing overlay + /// turns the loop for them now. + pub(super) fn origin_moved(&mut self, rt: &mut RuntimeCore, origin: (f32, f32)) { + if !rt.set_window_origin(origin) { return; } + self.dirty = true; + if self.presence.drawing() { self.idle = false; } + } + + fn position_window(&self, event_loop: &ActiveEventLoop, window: &Window) { + #[cfg(target_os = "macos")] + if let Some(panel) = &self.panel { + panel.place(self.at, &self.options); + return; + } + if let Some(p) = position(event_loop, self.at, &self.options) { + window.set_outer_position(p); + } + #[cfg(all(unix, not(target_os = "macos"), not(target_os = "ios"), not(target_os = "android")))] + if let Some(x11) = &self.x11 { x11.update_geometry(); } + } + + /// Puts the window on screen without focusing it or activating the app. + fn show_window(&mut self, window: &Window, fade: Duration) { + #[cfg(target_os = "macos")] + if let Some(panel) = &self.panel { + panel.show(fade); + return; + } + let _ = fade; + #[cfg(target_os = "windows")] + { + let _ = window; + if let Some(native) = &mut self.native { + match native.show() { + Ok(()) => if self.shared.failure.lock().unwrap().take().is_some() { self.set_availability(Availability::Available) }, + Err(error) => self.fail(error), + } + } + } + #[cfg(not(target_os = "windows"))] + window.set_visible(true); + #[cfg(all(unix, not(target_os = "macos"), not(target_os = "ios"), not(target_os = "android")))] + if let Some(x11) = &self.x11 { x11.show(self.options.level); } + } + + fn resized(&mut self, app: &mut dyn OverlayApp, event_loop: &ActiveEventLoop) { + // A parked window takes the size now; its surface is made at it. + if let Some(Backing::Window(w)) = self.surface.parked() { + let w = w.clone(); + let _size = w.request_inner_size(LogicalSize::new(self.at.size.0 as f64, self.at.size.1 as f64)); + return self.place_window(app.rt_mut(), event_loop, &w); + } + let Some(live) = self.surface.live_mut() else { return }; + match &mut live.backing { + Backing::Window(w) => { + let _size = w.request_inner_size(LogicalSize::new(self.at.size.0 as f64, self.at.size.1 as f64)); + } + #[cfg(all(unix, not(target_os = "macos"), not(target_os = "ios"), not(target_os = "android")))] + Backing::Layer(layer) => { + layer.place(self.at); + layer.commit(); + } + #[cfg(all(unix, not(target_os = "macos"), not(target_os = "ios"), not(target_os = "android")))] + Backing::Xwayland(surface) => surface.place(self.at, &self.options), + } + if let Some(gpu) = self.gpu.clone() { + let scale = live.scale; + live.scale = 0.0; + self.rescale(app, &gpu, scale); + } + if let Some(Backing::Window(w)) = self.surface.live().map(|l| &l.backing) { + let w = w.clone(); + self.place_window(app.rt_mut(), event_loop, &w); + if let Some(gpu) = self.gpu.clone() { self.rescale(app, &gpu, crate::window::backing_scale(&w)); } + } + } + + fn resolve_size(&mut self, event_loop: &ActiveEventLoop) { + let at = Placement { size: self.canvas_size, ..self.at }; + #[cfg(target_os = "macos")] + if let Some(rect) = self.panel.as_ref().map_or_else(|| crate::platform::macos::overlay_rect(at, &self.options), |panel| panel.rect(at, &self.options)) { + self.at.size = (rect.size.width as f32, rect.size.height as f32); + return; + } + if let Some(monitor) = monitor(event_loop, &self.options.display) { + let area = monitor.size().to_logical::<f32>(monitor.scale_factor()); + let rect = crate::overlay::options::local_rect(at, self.options.placement, (area.width, area.height)); + self.at.size = (rect[2], rect[3]); + } + } + + #[cfg(not(any(target_os = "macos", target_os = "ios", target_os = "android")))] + fn follow_pointer(&mut self, app: &mut dyn OverlayApp, event_loop: &ActiveEventLoop, point: (i32, i32)) { + if !self.options.follow_pointer { return; } + self.move_to_pointer_display(app, event_loop, point); + } + + /// The pointer in desktop pixels, read now, where an overlay may follow it. + #[cfg(target_os = "windows")] + fn sample_pointer(_: &ActiveEventLoop) -> Option<(i32, i32)> { + crate::platform::win32::pointer_position() + } + + #[cfg(all(unix, not(target_os = "macos"), not(target_os = "ios"), not(target_os = "android")))] + fn sample_pointer(event_loop: &ActiveEventLoop) -> Option<(i32, i32)> { + (!crate::window::is_wayland(event_loop)).then(crate::platform::x11::overlay::pointer_position).flatten() + } + + #[cfg(not(any(target_os = "windows", all(unix, not(target_os = "macos"), not(target_os = "ios"), not(target_os = "android")))))] + fn sample_pointer(_: &ActiveEventLoop) -> Option<(i32, i32)> { + None + } + + /// The display containing `point` when a window-backed `UnderPointer` overlay isn't on it. + fn pointer_display_away(&self, event_loop: &ActiveEventLoop, point: (i32, i32)) -> Option<winit::monitor::MonitorHandle> { + if self.options.display != DisplayTarget::UnderPointer { return None; } + let Some(Backing::Window(window)) = self.surface.live().map(|l| &l.backing) else { return None }; + event_loop.available_monitors().find(|m| { + let (p, s) = (m.position(), m.size()); + point.0 >= p.x && point.1 >= p.y && i64::from(point.0) < i64::from(p.x) + i64::from(s.width) + && i64::from(point.1) < i64::from(p.y) + i64::from(s.height) + }).filter(|target| window.current_monitor().as_ref() != Some(target)) + } + + /// `refollow_pointer`'s check: the overlay moves once two checks in a row find the pointer + /// on the same other display, so a pointer crossing back and forth over a display's edge + /// doesn't flip it between them. + fn refollow(&mut self, app: &mut dyn OverlayApp, event_loop: &ActiveEventLoop, point: (i32, i32)) { + let away = self.pointer_display_away(event_loop, point); + if away.is_some() && away == self.refollow_away { + self.refollow_away = None; + self.move_to_pointer_display(app, event_loop, point); + } else { + self.refollow_away = away; + } + } + + fn move_to_pointer_display(&mut self, app: &mut dyn OverlayApp, event_loop: &ActiveEventLoop, point: (i32, i32)) { + if let Some(target) = self.pointer_display_away(event_loop, point) { + // Pin the sampled target across size and position resolution, then resume following. + self.options.display = DisplayTarget::Id(crate::DisplayId::from_monitor(target, crate::window::is_wayland(event_loop))); + self.resolve_size(event_loop); + self.resized(app, event_loop); + self.options.display = DisplayTarget::UnderPointer; + } + } +} + +#[cfg(test)] +#[path = "overlay/tests.rs"] +mod tests; + +#[cfg(test)] +#[path = "overlay/state_walk_tests.rs"] +mod state_walk_tests; + +#[cfg(all(test, target_os = "macos"))] +#[path = "overlay/lost_release_tests.rs"] +mod lost_release_tests; + +/// A Windows overlay's alpha (255 opaque) at `now`, fading out linearly over `length` until `end`. +#[cfg_attr(not(target_os = "windows"), allow(dead_code))] +fn fade_alpha(end: Instant, length: Duration, now: Instant) -> u8 { + if length.is_zero() { return 0; } + let left = end.saturating_duration_since(now).as_secs_f64() / length.as_secs_f64(); + (left.clamp(0.0, 1.0) * 255.0).round() as u8 +} diff --git a/app/vendor/rune/crates/rune/src/overlay/any_host.rs b/app/vendor/rune/crates/rune/src/overlay/any_host.rs new file mode 100644 index 0000000..b2f3d22 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/overlay/any_host.rs @@ -0,0 +1,369 @@ +//! The overlay as a host on the shared event loop: its window events, wake deadline and +//! connection. + +use super::*; + +impl OverlayCore { + /// Windows: its next frame waits for room in the swap chain, and comes when there is + /// (`slot`). + fn waits_for_slot(&self) -> bool { + #[cfg(target_os = "windows")] + return self.surface.live().is_some_and(|l| l.slot.waiting()); + #[cfg(not(target_os = "windows"))] + false + } + + pub(super) fn wake_deadline(&self, rt: &RuntimeCore) -> Option<Instant> { + // A running display link consumes due runtime timers. Keep the independent + // pointer deadline, but do not spin on an overdue animation timer. Without one (hidden, + // covered, faded out or unpaced), a timer due sooner than a frame waits a frame. + let deadline = crate::window::timer_deadline_core(rt); + // A frame waiting for room in the swap chain comes when there is (`slot`): its timers + // would turn the loop at once until then. + let deadline = deadline.filter(|_| !self.waits_for_slot()); + #[cfg(target_os = "macos")] + let deadline = deadline.filter(|_| !self.surface.live().and_then(|l| l.pacing.as_ref()).is_some_and(|p| p.running())); + #[cfg(target_os = "macos")] + let deadline = deadline.into_iter().chain(self.panel.as_ref().and_then(|p| p.pointer_deadline(self.presence.occluded()))).min(); + // A Windows fade-out steps its alpha once a frame. + #[cfg(target_os = "windows")] + let deadline = deadline.into_iter().chain(self.presence.fading().then(|| crate::time::now() + crate::window::TIMER_FRAME)).min(); + deadline.into_iter().chain(self.backoff.deadline().filter(|_| self.presence.drawing())).chain(self.presence.deadline()) + .chain(self.hidden_pace.deadline().filter(|_| !self.presence.drawing())).min() + } + + /// Answers what assistive clients asked of the overlay and sends its tree's changes. An + /// action draws the frame that runs it. + fn a11y_turn(&mut self, rt: &mut RuntimeCore) -> bool { + let Some(adapter) = self.surface.live_mut().and_then(|l| l.a11y.as_mut()) else { return false }; + let queued = adapter.service_core(rt, self.name); + if queued { + self.dirty = true; + self.idle = false; + } + queued + } + + pub(super) fn connect(&mut self, app: &mut dyn OverlayApp, wake: Waker, _frame_wake: Waker, _slot_wake: Waker, gpu: Rc<RefCell<Weak<Gpu>>>) { + #[cfg(target_os = "macos")] + { self.frame_wake = Some(_frame_wake); } + #[cfg(target_os = "windows")] + { self.slot_wake = Some(_slot_wake); } + // All live sources (including Pixels) must share this registration: a second + // set_live_waker call replaces the wake lane and resets its subscriptions. + { + let rt = app.rt_mut(); + rt.set_live_waker(wake.clone()); + rt.host.open_urls_natively = true; + rt.frame.set_record_events(false); + } + self.clipboard.connect(wake.clone()); + self.popup.connect(wake.clone()); + self.gpu_pool = gpu; + *self.shared.wake.lock().unwrap() = Some(wake.clone()); + let rerun = || -> Waker { + let shared = self.shared.clone(); + Arc::new(move || { + let first = !std::mem::replace(&mut shared.requests.lock().unwrap().woken, true); + if first { shared.wake(); } + }) + }; + // A live-edit patch re-runs the view like new data does, shown or hidden. + #[cfg(feature = "hot")] + if crate::hot::enabled() && !app.rt().frame.has_hot() { + app.rt_mut().frame.set_hot(crate::hot::Session::connect(rerun())); + } + app.run_setup(rerun()); + // Requests made before the loop existed. + wake(); + } +} + +impl AnyHost for OverlayHost { + fn new_events(&mut self, _event_loop: &ActiveEventLoop, cause: StartCause) { + self.core.meter.turn(matches!(cause, StartCause::ResumeTimeReached { .. } | StartCause::Poll), crate::frame::surface_stats::slept(cause)); + self.core.turn_frame.step(frame::TurnEvent::NewEvents); + #[cfg(target_os = "macos")] + { self.core.occlusion_read = false; } + if matches!(cause, StartCause::ResumeTimeReached { .. } | StartCause::Poll) { + let now = crate::time::now(); + self.core.wake_due(&mut *self.app, now); + } + } + + fn wake_deadline(&self) -> Option<Instant> { + self.core.wake_deadline(self.app.rt()) + } + + fn resumed(&mut self, event_loop: &ActiveEventLoop) { + self.core.sync(&mut *self.app, event_loop); + } + + fn vanish(&mut self) { self.core.hide(&mut *self.app); } + + fn user_event(&mut self, event_loop: &ActiveEventLoop, event: WakeEvent) { + self.core.meter.waited(); + #[cfg(target_os = "windows")] + if matches!(event, WakeEvent::FrameSlot(_)) { + // The frame that waited for room in the swap chain draws now, after what changed + // meanwhile. It waited from a turn `frame::turn` said had a frame to draw, and that + // turn left `dirty` and `idle` as they were, so the gate still does. + if let Some(live) = self.core.surface.live_mut() && live.slot.waiting() { + live.slot.came_back(); + } + } + #[cfg(target_os = "macos")] + if matches!(event, WakeEvent::DisplayTick(_)) + && self.core.surface.live().and_then(|l| l.pacing.as_ref()).is_some_and(|p| p.running()) { + self.core.draw(&mut *self.app); + } + if let WakeEvent::App(_) = event { + self.core.sync(&mut *self.app, event_loop); + } + } + + fn owns(&self, id: WindowId) -> bool { + let window = match self.core.surface.backing() { + Some(Backing::Window(w)) => Some(w), + _ => None, + }; + window.is_some_and(|w| w.id() == id) + } + + fn window_event(&mut self, event_loop: &ActiveEventLoop, _id: WindowId, event: WindowEvent) { + let core = &mut self.core; + let app = &mut *self.app; + if !matches!(event, WindowEvent::RedrawRequested) { core.meter.waited(); } + #[cfg(target_os = "macos")] + if matches!(event, WindowEvent::Moved(_) | WindowEvent::ScaleFactorChanged { .. } | WindowEvent::Occluded(_)) + && let Some(live) = core.surface.live_mut() && let Some(pacing) = &mut live.pacing { + let Backing::Window(window) = &live.backing; + pacing.update_display(window); + } + // The panel's own state, which winit's source window forwards; kept while hidden too. + #[cfg(target_os = "macos")] + if let WindowEvent::Occluded(occluded) = event { + let occluded = core.panel.as_ref().map_or(occluded, |p| p.occluded()); + core.occluded(app, occluded); + return; + } + if let WindowEvent::Focused(focused) = &event { + #[cfg(target_os = "macos")] + if core.panel.as_ref().is_some_and(|p| p.is_key() != *focused) { return; } + app.window_focus(*focused); + if !*focused { + core.control_click = false; + if core.options.keys == KeyPolicy::OnDemand + && let Some(window) = core.surface.live().and_then(|l| l.backing.window()) + { + crate::platform::ime::cancel(window); + window.set_ime_allowed(false); + core.ime_allowed = false; + } + } + app.rt_mut().ignore_minimize("an overlay"); + match app.rt_mut().shell_request.take() { + Some(crate::el::Shell::Close) => core.hide(app), + Some(crate::el::Shell::Quit) => event_loop.exit(), + Some(crate::el::Shell::Relaunch) => { + let _ = crate::quit::send(crate::quit::Event::Start { ending: false, after: crate::quit::After::Relaunch }); + event_loop.exit(); + } + None => {} + } + } + // Hidden too, so the retained surface redraws in the new theme before it's revealed. + if let WindowEvent::ThemeChanged(theme) = event { + return core.theme_changed(app.rt_mut(), theme == winit::window::Theme::Dark); + } + // Hidden too: the queued rects are delivered with the next shown frame. + if matches!(event, WindowEvent::Moved(_) | WindowEvent::Resized(_) | WindowEvent::ScaleFactorChanged { .. }) { + core.sync_live_origin(app.rt_mut()); + } + if !core.presence.shown() { return; } + #[cfg(all(unix, not(target_os = "macos"), not(target_os = "ios"), not(target_os = "android")))] + if matches!(event, WindowEvent::Moved(_) | WindowEvent::Resized(_) | WindowEvent::ScaleFactorChanged { .. }) + && let Some(x11) = &core.x11 { x11.update_geometry(); } + // A click gives an overlay that may take keys the focus, as it does the macOS panel; the + // window manager gives an override-redirect window none. + #[cfg(all(unix, not(target_os = "macos"), not(target_os = "ios"), not(target_os = "android")))] + if let WindowEvent::MouseInput { state: winit::event::ElementState::Pressed, .. } = event && let Some(x11) = &core.x11 { x11.request_keys(); } + use crate::input::host_events; + if matches!(event, WindowEvent::CursorMoved { .. } | WindowEvent::CursorLeft { .. } | WindowEvent::MouseInput { .. }) + && (app.rt().touching() || host_events::touch_promoted()) { return; } + let input_enabled = core.options.input.resolved(core.interactive) != OverlayInput::None; + match event { + WindowEvent::Moved(_) => { + if let Some(live) = core.surface.live() && let Some(w) = live.backing.window() { + let scale = crate::window::backing_scale(w); + if (scale - live.scale).abs() > f32::EPSILON && let Some(gpu) = core.gpu.clone() { + core.rescale(app, &gpu, scale); + } + } + } + WindowEvent::ScaleFactorChanged { scale_factor, .. } => { + if let Some(gpu) = core.gpu.clone() { + core.rescale(app, &gpu, scale_factor as f32); + } + } + WindowEvent::RedrawRequested | WindowEvent::Resized(_) => { + // A new accent or scroller style asks every window to redraw (`accent::watch`, `scroll_bars::watch`). + core.accent_changed(app.rt_mut(), crate::system_accent()); + core.scroll_bars_changed(app.rt_mut(), crate::platform::scroll_bars::current()); + core.dirty = true; + } + WindowEvent::CursorMoved { position, .. } if input_enabled => { + let input_scale = app.rt().input_scale(); + let (x, y) = (position.x as f32 / input_scale, position.y as f32 / input_scale); + #[cfg(target_os = "macos")] + if let Some(pointer) = core.native_pointer() { return core.native_moved(app, &pointer, x, y); } + core.cursor_moved(app, x, y); + } + WindowEvent::CursorLeft { .. } if input_enabled => { + app.rt_mut().pointer_leave(); + core.dirty = true; + } + WindowEvent::MouseWheel { delta, phase, .. } if input_enabled => { + let scale = core.surface.live().map_or(1.0, |l| l.scale); + host_events::wheel(app.rt_mut(), delta, host_events::gesture_phase(phase), scale, core.mods); + core.dirty = true; + } + WindowEvent::PinchGesture { delta, phase, .. } if input_enabled => { + core.dirty |= host_events::magnify(app.rt_mut(), delta, host_events::gesture_phase(phase)); + } + WindowEvent::RotationGesture { delta, phase, .. } if input_enabled => { + core.dirty |= host_events::rotate(app.rt_mut(), delta, host_events::gesture_phase(phase)); + } + WindowEvent::DoubleTapGesture { .. } if input_enabled => { + core.dirty |= host_events::smart_magnify(app.rt_mut()); + } + WindowEvent::Touch(touch) if input_enabled => { + app.touch(&touch); + core.dirty = true; + } + WindowEvent::ModifiersChanged(m) => { + core.dirty |= app.modifiers(&mut core.mods, m.state()); + } + WindowEvent::Focused(_) => { + host_events::refresh_focus_preferences(app.rt_mut(), None); + core.dirty = true; + } + WindowEvent::KeyboardInput { event, is_synthetic: false, .. } if core.options.keys == KeyPolicy::OnDemand => { + core.dirty |= app.keyboard(&core.clipboard, &event, core.mods); + } + WindowEvent::Ime(ime) if core.options.keys == KeyPolicy::OnDemand => { + if let Some(window) = core.surface.live().and_then(|l| l.backing.window()) { + host_events::ime(app.rt_mut(), window, ime); + core.dirty = true; + } + } + WindowEvent::MouseInput { state, button: winit::event::MouseButton::Left, .. } => { + let pressed = state.is_pressed(); + if pressed { + core.control_click = cfg!(target_os = "macos") && core.mods.control_key(); + } + if core.control_click { + if input_enabled && let Some((x, y)) = app.rt().pointer() { + if pressed { app.rt_mut().secondary_down(x, y); } else { app.secondary_up(x, y); } + core.dirty = true; + } + if !pressed { core.control_click = false; } + core.apply_input(app.rt()); + return; + } + #[cfg(target_os = "macos")] + { + match core.native_pointer() { + Some(pointer) => core.native_left(app, &pointer, pressed), + None => core.left_edge(app, None, pressed, None), + } + if !pressed && let Some(panel) = &core.panel { panel.pointer_released(); } + } + #[cfg(not(target_os = "macos"))] + if input_enabled { + #[cfg(target_os = "windows")] + let point = core.native.as_ref().and_then(|p| p.take_click(pressed)); + #[cfg(not(target_os = "windows"))] + let point: Option<(f32, f32)> = None; + core.left_button(app, pressed, point); + } + core.apply_input(app.rt()); + } + WindowEvent::MouseInput { state, button: winit::event::MouseButton::Right, .. } if input_enabled => { + if let Some((x, y)) = app.rt().pointer() { + if state.is_pressed() { app.rt_mut().secondary_down(x, y); } else { app.secondary_up(x, y); } + core.dirty = true; + } + core.apply_input(app.rt()); + } + WindowEvent::MouseInput { state, button, .. } if input_enabled => { + if let Some((x, y)) = app.rt().pointer() { + let button = crate::window::pointer_button(button); + if state.is_pressed() { app.button_down(x, y, button); } else { app.button_up(x, y, button); } + core.dirty = true; + } + core.apply_input(app.rt()); + } + _ => {} + } + } + + fn about_to_wait(&mut self, _event_loop: &ActiveEventLoop) -> bool { + let core = &mut self.core; + let app = &mut *self.app; + #[cfg(target_os = "macos")] + core.fn_key(app); + // A window switched the font families (`Tx::set_font_families`). + core.dirty |= app.rt_mut().follow_font_families(); + // A fading-out overlay takes no input; it only draws its exit. + if !core.presence.shown() { + core.hidden_input(app); + let more = core.draw(app); + return core.a11y_turn(app.rt_mut()) || more; + } + #[cfg(all(unix, not(target_os = "macos"), not(target_os = "ios"), not(target_os = "android")))] + if let Some(live) = core.surface.live() && let Some(x11) = &core.x11 && let Some((point, desktop)) = x11.take_pointer(live.scale) { + core.observe_pointer(app, point.0, point.1); + core.follow_pointer(app, _event_loop, desktop); + } + #[cfg(target_os = "windows")] + if core.surface.live().is_some() && let Some(point) = core.native.as_ref().and_then(|p| p.take_pointer()) && app.rt().pointer() != Some(point) { + core.observe_pointer(app, point.0, point.1); + if let Some(point) = crate::platform::win32::pointer_position() { core.follow_pointer(app, _event_loop, point); } + } + // Covering or sleeping displays can come without an event the overlay sees. + #[cfg(target_os = "macos")] + if core.surface.live().is_some() { core.sync_occlusion(app); } + #[cfg(target_os = "macos")] + if core.surface.live().is_some() && let Some(panel) = &core.panel { + // Covered or asleep, the 120 Hz regions poll rests; input events still sample. + panel.observe_pointer(crate::time::now(), !core.presence.occluded()); + let pointer = panel.pointer_state(); + if let Some((x, y)) = core.turn_position(app, &pointer) && app.rt().pointer() != Some((x, y)) { + core.observe_pointer(app, x, y); + if core.options.follow_pointer && core.options.display == DisplayTarget::UnderPointer { + let size = core.at.size; + core.resolve_size(_event_loop); + if size != core.at.size { core.resized(app, _event_loop); } + else if let Some(panel) = &core.panel { panel.place(core.at, &core.options); } + core.sync_live_origin(app.rt_mut()); + } + } + } + let more = core.draw(app); + core.apply_cursor(app.rt()); + core.a11y_turn(app.rt_mut()) || more + } + + fn keeps_loop(&self) -> bool { + false + } + + fn cancel_menus(&mut self) { self.app.popup_cancel(&mut self.core.popup); } +} + +impl PendingOverlay for OverlayHost { + fn connect(&mut self, wake: Waker, frame_wake: Waker, slot_wake: Waker, gpu: Rc<RefCell<Weak<Gpu>>>) { + self.core.connect(&mut *self.app, wake, frame_wake, slot_wake, gpu); + } +} diff --git a/app/vendor/rune/crates/rune/src/overlay/app.rs b/app/vendor/rune/crates/rune/src/overlay/app.rs new file mode 100644 index 0000000..d0a6f9e --- /dev/null +++ b/app/vendor/rune/crates/rune/src/overlay/app.rs @@ -0,0 +1,450 @@ +//! Non-generic boundary between [`super::OverlayCore`] and the typed `Runtime<T>`, +//! `Compositor<T>`, `setup` hook and `Shared<T>` updates queue, plus the concrete non-generic +//! [`OverlayHost`] and the `#[cfg(test)]` [`Overlay<T>`] test harness. + +use std::sync::Arc; +#[cfg(test)] +use std::cell::RefCell; +#[cfg(test)] +use std::rc::Rc; +#[cfg(test)] +use std::sync::Weak; +#[cfg(test)] +use std::time::Duration; + +use winit::window::Window; + +use super::frame::OverlayRenderArgs; +use super::{OverlayCore, OverlayHandle, Placement, Shared, SharedCore}; +#[cfg(test)] +use super::requests::Update; +use crate::compose::{Compositor, Frame}; +use crate::el::Tx; +use crate::frame::clock::FrameClock; +use crate::runtime::{AppDriver, Env, Runtime, RuntimeCore, Waker}; +use crate::text::TextSystem; +use crate::time::Instant; +use crate::tooling::AppSpec; +use crate::ConfiguredOverlay; + +/// Everything the non-generic overlay host needs of its typed state `T`. +pub(super) trait OverlayApp { + fn rt(&self) -> &RuntimeCore; + fn rt_mut(&mut self) -> &mut RuntimeCore; + fn with_driver(&mut self, f: &mut dyn FnMut(&mut RuntimeCore, &mut dyn AppDriver)); + fn has_poll(&self) -> bool; + fn run_setup(&mut self, waker: Waker); + /// Drains queued typed updates into `rt`, returning `(queued, updated)`. + fn drain_updates(&mut self) -> (bool, bool); + fn has_compositor(&self) -> bool; + fn compositor_features(&self) -> wgpu::Features; + fn compositor_animating(&self) -> bool; + fn render_compositor(&mut self, args: OverlayRenderArgs<'_>) -> bool; +} + +impl dyn OverlayApp + '_ { + fn driver<R>(&mut self, f: impl FnOnce(&mut RuntimeCore, &mut dyn AppDriver) -> R) -> R { + let mut f = Some(f); + let mut out = None; + self.with_driver(&mut |core, app| { + out = Some(f.take().unwrap()(core, app)); + }); + out.unwrap() + } + + pub(super) fn frame(&mut self, dt: f64) -> bool { + self.driver(|rt, app| rt.frame(app, dt)) + } + + pub(super) fn frame_split(&mut self, catch_up: f64, dt: f64) -> bool { + self.driver(|rt, app| rt.frame_split(app, catch_up, dt)) + } + + pub(super) fn clock_advance(&mut self, clock: &mut FrameClock, at: Instant, compositing: bool) -> (bool, f64) { + self.driver(|rt, app| clock.advance_core(rt, app, at, compositing)) + } + + pub(super) fn poll_hidden(&mut self) -> bool { + self.driver(|rt, app| rt.poll_hidden(app)) + } + + pub(super) fn window_focus(&mut self, focused: bool) { + self.driver(|rt, app| rt.window_focus(app, focused)); + } + + pub(super) fn set_live_visible(&mut self, visible: bool) { + self.driver(|rt, app| rt.set_live_visible(app, visible)); + } + + pub(super) fn popup_answer(&mut self, popup: &mut crate::popup_menu::Presenter) -> bool { + self.driver(|rt, app| popup.answer_core(rt, app)) + } + + pub(super) fn popup_open(&mut self, popup: &mut crate::popup_menu::Presenter, window: Option<&Arc<Window>>, paints: bool) -> bool { + self.driver(|rt, app| popup.open_core(rt, app, window, paints)) + } + + pub(super) fn popup_cancel(&mut self, popup: &mut crate::popup_menu::Presenter) { + self.driver(|rt, app| popup.cancel_core(rt, app)); + } + + pub(super) fn observe_pointer(&mut self, x: f32, y: f32) -> bool { + self.driver(|rt, app| rt.observe_pointer(app, x, y)) + } + + pub(super) fn pointer_move(&mut self, x: f32, y: f32) { + self.driver(|rt, app| rt.pointer_move(app, x, y)); + } + + pub(super) fn pointer_down(&mut self, x: f32, y: f32) { + self.driver(|rt, app| rt.pointer_down(app, x, y)); + } + + pub(super) fn pointer_up(&mut self, x: f32, y: f32) { + self.driver(|rt, app| rt.pointer_up(app, x, y)); + } + + #[cfg(target_os = "macos")] + pub(super) fn pointer_release_lost(&mut self, x: f32, y: f32) { + self.driver(|rt, app| rt.pointer_release_lost(app, x, y)); + } + + pub(super) fn secondary_up(&mut self, x: f32, y: f32) { + self.driver(|rt, app| rt.secondary_up(app, x, y)); + } + + pub(super) fn button_down(&mut self, x: f32, y: f32, button: crate::PointerButton) { + self.driver(|rt, app| rt.button_down(app, x, y, button)); + } + + pub(super) fn button_up(&mut self, x: f32, y: f32, button: crate::PointerButton) { + self.driver(|rt, app| rt.button_up(app, x, y, button)); + } + + pub(super) fn touch(&mut self, touch: &winit::event::Touch) { + self.driver(|rt, app| crate::window::touch_core(rt, app, touch)); + } + + #[cfg(all(unix, not(target_os = "macos"), not(target_os = "ios"), not(target_os = "android")))] + pub(super) fn key_up(&mut self, key: crate::KeyEvent) -> bool { + self.driver(|rt, app| rt.key_up(app, key)) + } + + pub(super) fn modifiers(&mut self, mods: &mut winit::keyboard::ModifiersState, next: winit::keyboard::ModifiersState) -> bool { + self.driver(|rt, app| crate::input::host_events::modifiers(rt, app, mods, next)) + } + + pub(super) fn keyboard( + &mut self, + clipboard: &crate::clipboard::Client, + event: &winit::event::KeyEvent, + mods: winit::keyboard::ModifiersState, + ) -> bool { + self.driver(|rt, app| crate::input::host_events::keyboard(rt, app, clipboard, event, mods, None)) + } + + #[cfg(any(target_os = "macos", all(unix, not(target_os = "macos"), not(target_os = "ios"), not(target_os = "android"))))] + pub(super) fn physical_with_fallback(&mut self, event: crate::PhysicalInput, key: Option<crate::KeyEvent>) -> bool { + self.driver(|rt, app| rt.physical_with_fallback(app, event, key)) + } +} + +/// The only per-state-type structure owned by a live overlay host. +pub(super) struct TypedOverlayApp<T: 'static> { + pub(super) rt: Runtime<T>, + pub(super) compositor: Option<Box<dyn Compositor<T>>>, + pub(super) setup: Option<fn(&mut T, Waker)>, + pub(super) shared: Arc<Shared<T>>, +} + +impl<T: 'static> OverlayApp for TypedOverlayApp<T> { + fn rt(&self) -> &RuntimeCore { self.rt.core() } + + fn rt_mut(&mut self) -> &mut RuntimeCore { self.rt.core_mut() } + + fn with_driver(&mut self, f: &mut dyn FnMut(&mut RuntimeCore, &mut dyn AppDriver)) { + let (core, mut driver) = self.rt.split_mut(); + f(core, &mut driver); + } + + fn has_poll(&self) -> bool { self.rt.poll.is_some() } + + fn run_setup(&mut self, waker: Waker) { + if let Some(setup) = self.setup.take() { + setup(&mut self.rt.state, waker); + } + } + + fn drain_updates(&mut self) -> (bool, bool) { + let updates = std::mem::take(&mut *self.shared.updates.lock().unwrap()); + let queued = !updates.is_empty(); + let mut updated = false; + for f in updates { + updated |= self.rt.update_if(f); + } + (queued, updated) + } + + fn has_compositor(&self) -> bool { self.compositor.is_some() } + + fn compositor_features(&self) -> wgpu::Features { + self.compositor.as_ref().map_or(wgpu::Features::empty(), |c| c.features()) + } + + fn compositor_animating(&self) -> bool { + self.compositor.as_ref().is_some_and(|c| c.animating()) + } + + fn render_compositor(&mut self, args: OverlayRenderArgs<'_>) -> bool { + let Some(c) = self.compositor.as_mut() else { return false }; + let mut f = Frame { + device: args.device, + queue: args.queue, + encoder: args.encoder, + target: args.target, + format: args.format, + size: args.size, + dt: args.dt, + update_ms: args.update_ms, + rt: &mut self.rt, + ui: args.ui, + }; + c.render(&mut f); + c.animating() + } +} + +/// Non-generic overlay host stored in `App::overlays` and `Windows::hosts`. +pub(crate) struct OverlayHost { + pub(super) core: OverlayCore, + pub(super) app: Box<dyn OverlayApp>, +} + +fn build_parts<S, T: 'static>( + configured: ConfiguredOverlay<T>, + state: T, + app: &AppSpec<S>, +) -> (OverlayCore, TypedOverlayApp<T>, OverlayHandle<T>) { + let ConfiguredOverlay { + spec, options, on_key, on_created, poll, compositor, setup, runtime, macos_level, + animate_reveal, release_after, + } = configured; + let shared_core = Arc::new(SharedCore::default()); + let shared = Arc::new(Shared { core: shared_core.clone(), updates: Default::default() }); + let text = TextSystem::for_window(app.fonts, app.families); + let mut rt = Runtime::with_text(state, spec.view, spec.size, Env::default(), text); + rt.configure(runtime); + rt.on_key = on_key; + // App and overlay may use different state types. Downcast the function pointer + // once, without a per-frame adapter or changing App::overlay's generic API. + rt.poll = poll.or_else(|| app.poll.and_then(|f| { + (&f as &dyn std::any::Any).downcast_ref::<fn(&mut T, f64, &mut Tx) -> bool>().copied() + })); + rt.set_live_visible(false); + let at = Placement { size: spec.size, edge: spec.edge, margin: spec.margin, align: spec.align, inset: spec.inset }; + let core = OverlayCore::new( + rt.core_mut(), + shared_core, + spec.name, + at, + spec.interactive, + options, + on_created, + macos_level, + animate_reveal, + release_after, + ); + let typed = TypedOverlayApp { rt, compositor, setup, shared: shared.clone() }; + (core, typed, OverlayHandle { shared }) +} + +impl OverlayHost { + pub(crate) fn new<S, T: 'static>(configured: impl Into<ConfiguredOverlay<T>>, state: T, app: &AppSpec<S>) -> (Self, OverlayHandle<T>) { + let (core, typed, handle) = build_parts(configured.into(), state, app); + (OverlayHost { core, app: Box::new(typed) }, handle) + } +} + +/// Thin typed wrapper used only by unit tests so tests can inspect `rt.state`, `compositor`, and +/// `OverlayCore` fields while exercising the real non-generic `OverlayCore` methods. +#[cfg(test)] +pub(super) struct Overlay<T: 'static> { + pub(super) core: OverlayCore, + pub(super) rt: Runtime<T>, + pub(super) compositor: Option<Box<dyn Compositor<T>>>, + pub(super) setup: Option<fn(&mut T, Waker)>, + pub(super) shared: Arc<Shared<T>>, +} + +#[cfg(test)] +impl<T: 'static> std::ops::Deref for Overlay<T> { + type Target = OverlayCore; + fn deref(&self) -> &OverlayCore { &self.core } +} + +#[cfg(test)] +impl<T: 'static> std::ops::DerefMut for Overlay<T> { + fn deref_mut(&mut self) -> &mut OverlayCore { &mut self.core } +} + +#[cfg(test)] +struct BorrowOverlayApp<'a, T: 'static> { + rt: &'a mut Runtime<T>, + compositor: &'a mut Option<Box<dyn Compositor<T>>>, + setup: &'a mut Option<fn(&mut T, Waker)>, + shared: &'a Arc<Shared<T>>, +} + +#[cfg(test)] +impl<T: 'static> OverlayApp for BorrowOverlayApp<'_, T> { + fn rt(&self) -> &RuntimeCore { self.rt.core() } + fn rt_mut(&mut self) -> &mut RuntimeCore { self.rt.core_mut() } + fn with_driver(&mut self, f: &mut dyn FnMut(&mut RuntimeCore, &mut dyn AppDriver)) { + let (core, mut driver) = self.rt.split_mut(); + f(core, &mut driver); + } + fn has_poll(&self) -> bool { self.rt.poll.is_some() } + fn run_setup(&mut self, waker: Waker) { + if let Some(setup) = self.setup.take() { setup(&mut self.rt.state, waker); } + } + fn drain_updates(&mut self) -> (bool, bool) { + let updates = std::mem::take(&mut *self.shared.updates.lock().unwrap()); + let queued = !updates.is_empty(); + let mut updated = false; + for f in updates { updated |= self.rt.update_if(f); } + (queued, updated) + } + fn has_compositor(&self) -> bool { self.compositor.is_some() } + fn compositor_features(&self) -> wgpu::Features { + self.compositor.as_ref().map_or(wgpu::Features::empty(), |c| c.features()) + } + fn compositor_animating(&self) -> bool { + self.compositor.as_ref().is_some_and(|c| c.animating()) + } + fn render_compositor(&mut self, args: OverlayRenderArgs<'_>) -> bool { + let Some(c) = self.compositor.as_mut() else { return false }; + let mut f = Frame { + device: args.device, + queue: args.queue, + encoder: args.encoder, + target: args.target, + format: args.format, + size: args.size, + dt: args.dt, + update_ms: args.update_ms, + rt: &mut *self.rt, + ui: args.ui, + }; + c.render(&mut f); + c.animating() + } +} + +#[cfg(test)] +macro_rules! with_app { + ($self:ident, |$core:ident, $app:ident| $body:expr) => {{ + let $core = &mut $self.core; + #[allow(unused_mut)] + let mut $app = BorrowOverlayApp { + rt: &mut $self.rt, + compositor: &mut $self.compositor, + setup: &mut $self.setup, + shared: &$self.shared, + }; + $body + }}; +} + +#[cfg(test)] +impl<T: 'static> Overlay<T> { + pub(super) fn new<S>(configured: impl Into<ConfiguredOverlay<T>>, state: T, app: &AppSpec<S>) -> (Self, OverlayHandle<T>) { + let (core, typed, handle) = build_parts(configured.into(), state, app); + let TypedOverlayApp { rt, compositor, setup, shared } = typed; + (Overlay { core, rt, compositor, setup, shared }, handle) + } + + pub(super) fn wake_deadline(&self) -> Option<Instant> { self.core.wake_deadline(self.rt.core()) } + pub(super) fn connect(&mut self, wake: Waker, frame_wake: Waker, slot_wake: Waker, gpu: Rc<RefCell<Weak<crate::render::Gpu>>>) { + with_app!(self, |core, app| core.connect(&mut app, wake, frame_wake, slot_wake, gpu)) + } + pub(super) fn draw(&mut self) -> bool { with_app!(self, |core, app| core.draw(&mut app)) } + #[cfg(target_os = "macos")] + pub(super) fn warm(&mut self) { with_app!(self, |core, app| core.warm(&mut app)) } + pub(super) fn warm_offscreen(&mut self, size: (u32, u32)) { with_app!(self, |core, app| core.warm_offscreen(&mut app, size)) } + pub(super) fn advance(&mut self) { with_app!(self, |core, app| core.advance(&mut app)) } + #[cfg(target_os = "macos")] + pub(super) fn advance_at(&mut self, now: Instant) { with_app!(self, |core, app| core.advance_at(&mut app, now)) } + pub(super) fn wake_due(&mut self, now: Instant) { with_app!(self, |core, app| core.wake_due(&mut app, now)) } + pub(super) fn hide(&mut self) { with_app!(self, |core, app| core.hide(&mut app)) } + pub(super) fn hide_fading(&mut self, fade: Duration) { with_app!(self, |core, app| core.hide_fading(&mut app, fade)) } + pub(super) fn presence_due(&mut self, now: Instant) { with_app!(self, |core, app| core.presence_due(&mut app, now)) } + pub(super) fn accent_changed(&mut self, accent: crate::SystemAccent) { self.core.accent_changed(self.rt.core_mut(), accent) } + pub(super) fn scroll_bars_changed(&mut self, bars: crate::platform::scroll_bars::SystemScrollBars) { self.core.scroll_bars_changed(self.rt.core_mut(), bars) } + pub(super) fn theme_changed(&mut self, dark: bool) { self.core.theme_changed(self.rt.core_mut(), dark) } + #[cfg(target_os = "macos")] + pub(super) fn origin_moved(&mut self, origin: (f32, f32)) { self.core.origin_moved(self.rt.core_mut(), origin) } + #[cfg(target_os = "macos")] + pub(super) fn refresh_for_reveal_at(&mut self, now: Instant) { with_app!(self, |core, app| core.refresh_for_reveal_at(&mut app, now)) } + pub(super) fn resume_live(&mut self) { with_app!(self, |core, app| core.resume_live(&mut app)) } + pub(super) fn settle_before_reveal(&mut self) { self.core.settle_before_reveal(self.rt.core_mut()) } + pub(super) fn hidden_input(&mut self) { with_app!(self, |core, app| core.hidden_input(&mut app)) } + pub(super) fn apply_input(&mut self) { self.core.apply_input(self.rt.core()) } + pub(super) fn left_button(&mut self, pressed: bool, point: Option<(f32, f32)>) { with_app!(self, |core, app| core.left_button(&mut app, pressed, point)) } + pub(super) fn drag_ends_due(&mut self) { with_app!(self, |core, app| core.drag_ends_due(&mut app)) } + pub(super) fn missed(&mut self, missed: crate::window::Missed, paced: bool, stepped: bool) { with_app!(self, |core, app| core.missed(&mut app, missed, paced, stepped)) } + pub(super) fn acquire_missed(&mut self, missed: crate::window::Missed, paced: bool, prewarm: bool, built: bool) { + with_app!(self, |core, app| core.acquire_missed(&mut app, missed, paced, prewarm, built)) + } + pub(super) fn apply_wake(&mut self, woken: bool, updates: Vec<Update<T>>) { + let queued = !updates.is_empty(); + let mut updated = false; + for f in updates { updated |= self.rt.update_if(f); } + with_app!(self, |core, app| core.apply_wake_drained(&mut app, woken, queued, updated)) + } + pub(super) fn step_frame(&mut self, at: Instant, prewarm: bool) -> (bool, f64) { + with_app!(self, |core, app| super::frame::step(&mut app, &mut core.clock, at, prewarm)) + } + pub(super) fn quiet_step_frame(&mut self, presented: &crate::window::Presented, config: &wgpu::SurfaceConfiguration, now: Instant, next_tick: Option<Instant>) -> Option<(bool, f64)> { + with_app!(self, |core, app| super::frame::quiet_step(&mut app, &mut core.clock, presented, config, now, next_tick)) + } + pub(super) fn rests_now(&mut self, runtime_idle: bool, dirty: bool) -> bool { + with_app!(self, |_core, app| super::frame::rests(&app, runtime_idle, dirty)) + } + pub(super) fn rest_frame(&mut self, frame_time: Instant) -> (bool, f64) { + with_app!(self, |core, app| super::frame::rest(&mut app, &mut core.clock, frame_time)) + } + pub(super) fn render_offscreen(&mut self, gpu: &crate::render::Gpu, enc: &mut wgpu::CommandEncoder, target: &wgpu::TextureView, format: wgpu::TextureFormat, size: (u32, u32), dt: f64) -> bool { + with_app!(self, |core, app| { + let renderer = core.renderer.as_mut().unwrap(); + super::frame::render_frame(&mut app, OverlayRenderArgs { + device: &gpu.device, queue: &gpu.queue, encoder: enc, target, format, size, dt, update_ms: 0.0, ui: renderer, + }) + }) + } + #[cfg(target_os = "macos")] + pub(super) fn occluded(&mut self, occluded: bool) { with_app!(self, |core, app| core.occluded(&mut app, occluded)) } + #[cfg(target_os = "macos")] + pub(super) fn set_occluded(&mut self, occluded: bool) { with_app!(self, |core, app| core.set_occluded(&mut app, occluded)) } + #[cfg(target_os = "macos")] + pub(super) fn sync_occlusion(&mut self) { with_app!(self, |core, app| core.sync_occlusion(&mut app)) } + #[cfg(target_os = "macos")] + pub(super) fn left_edge(&mut self, lost: Option<(f32, f32)>, pressed: bool, point: Option<(f32, f32)>) { + with_app!(self, |core, app| core.left_edge(&mut app, lost, pressed, point)) + } + #[cfg(target_os = "macos")] + pub(super) fn native_left(&mut self, pointer: &crate::platform::macos::PointerState, pressed: bool) { + with_app!(self, |core, app| core.native_left(&mut app, pointer, pressed)) + } + #[cfg(target_os = "macos")] + pub(super) fn native_moved(&mut self, pointer: &crate::platform::macos::PointerState, x: f32, y: f32) { + with_app!(self, |core, app| core.native_moved(&mut app, pointer, x, y)) + } + #[cfg(target_os = "macos")] + pub(super) fn turn_position(&mut self, pointer: &crate::platform::macos::PointerState) -> Option<(f32, f32)> { + with_app!(self, |core, app| core.turn_position(&mut app, pointer)) + } + #[cfg(target_os = "macos")] + pub(super) fn observe_pointer(&mut self, x: f32, y: f32) { + with_app!(self, |core, app| core.observe_pointer(&mut app, x, y)) + } +} diff --git a/app/vendor/rune/crates/rune/src/overlay/draw.rs b/app/vendor/rune/crates/rune/src/overlay/draw.rs new file mode 100644 index 0000000..eaa899f --- /dev/null +++ b/app/vendor/rune/crates/rune/src/overlay/draw.rs @@ -0,0 +1,650 @@ +//! An overlay's frame on its surface: whether one is due, the acquire, the step and the draw, +//! and the occlusion and pacing that decide when the next comes. + +use super::*; +use crate::frame::host_step::{ + self, Acquire, FrameHost, Gate, PostStepCheck, ReacquireReason, RenderPrep, StepInfo, + draw_ui, prepare_gpu_resources, +}; + +struct PreparedOverlayFrame { + frame: wgpu::SurfaceTexture, + view: wgpu::TextureView, + encoder: wgpu::CommandEncoder, + target_format: wgpu::TextureFormat, + size: (u32, u32), +} + +struct OverlayFrame<'a> { + core: &'a mut OverlayCore, + app: &'a mut dyn OverlayApp, + prewarm: bool, + read_occlusion: bool, + paced: bool, + #[cfg(target_os = "macos")] + target: Option<Instant>, + #[cfg(target_os = "macos")] + materials_checked: bool, + now: Option<Instant>, + more: bool, +} + +impl OverlayFrame<'_> { + fn reblend_surface(&mut self) -> bool { + let (Some(live), Some(renderer), Some(gpu)) = ( + self.core.surface.live_mut(), + self.core.renderer.as_mut(), + self.core.gpu.as_ref(), + ) else { + return false; + }; + #[cfg(target_os = "windows")] + live.slot.reset(); + crate::window::reblend_core(&live.surface, gpu, &mut live.config, renderer, &mut live.alpha, self.app.rt_mut()) + } +} + +impl FrameHost for OverlayFrame<'_> { + type Drawable = wgpu::SurfaceTexture; + type Prepared = PreparedOverlayFrame; + + fn gate(&mut self) -> Gate { + let timer = !self.core.quiet.step(frame::QuietEvent::FrameStarts).is_empty(); + #[cfg(all(unix, not(target_os = "macos"), not(target_os = "ios"), not(target_os = "android")))] + if let Some(Live { backing: Backing::Layer(layer), .. }) = self.core.surface.live_mut() { + let changes = layer.dispatch(); + if changes.closed { + self.core.hide(self.app); + return Gate::Skip; + } + for input in changes.input { self.core.surface_input(self.app, input); } + if let Some((w, h)) = changes.size { + let size = (if w == 0 { self.core.at.size.0 } else { w as f32 }, if h == 0 { self.core.at.size.1 } else { h as f32 }); + if size != self.core.at.size { + self.core.at.size = size; + if let Some(live) = self.core.surface.live_mut() { live.scale = 0.0; } + } + } + if let Some(scale) = changes.scale { + if let Some(Live { backing: Backing::Layer(layer), .. }) = self.core.surface.live_mut() { layer.set_buffer_scale(scale); } + if let Some(gpu) = self.core.gpu.clone() { + self.core.rescale(self.app, &gpu, scale as f32); + } + } + if self.core.surface.live().is_some_and(|l| l.scale == 0.0) && let Some(gpu) = self.core.gpu.clone() { + // Read before `app` is reborrowed for `rescale`. + let scale = self.app.rt().env.scale; + self.core.rescale(self.app, &gpu, scale); + } + } + #[cfg(all(unix, not(target_os = "macos"), not(target_os = "ios"), not(target_os = "android")))] + if let Some(Live { backing: Backing::Xwayland(surface), .. }) = self.core.surface.live_mut() { + let input = surface.dispatch(); + for input in input { self.core.surface_input(self.app, input); } + } + self.core.apply_input(self.app.rt()); + if self.core.surface.live().is_none() || self.core.renderer.is_none() || self.core.gpu.is_none() { + return Gate::Skip; + } + // `sync_occlusion` below reads, once a turn, the panel hosting the surface: the window + // the acquire would check again. + #[cfg(target_os = "macos")] + { self.read_occlusion = !self.prewarm && self.core.panel.is_some(); } + #[cfg(not(target_os = "macos"))] + { self.read_occlusion = false; } + // Even an idle overlay looks again on its retry while occluded: the occlusion + // notification that should uncover it may never come. + #[cfg(target_os = "macos")] + if !self.prewarm { self.core.sync_occlusion(self.app); } + let gate = frame::Gate { + prewarm: self.prewarm, + occluded: cfg!(target_os = "macos") && self.core.presence.occluded(), + dirty: self.core.dirty, + idle: self.core.idle, + retry: self.core.backoff.deadline(), + missed_this_turn: self.core.turn_frame.missed(), + }; + match frame::turn(gate, crate::time::now) { + frame::Turn::Occluded { recheck } => { + if recheck { + self.core.meter.skipped(); + self.core.missed(self.app, crate::window::Missed::Occluded, false, self.core.turn_frame.stepped()); + } + return Gate::Skip; + } + // `wake_due` runs due timers while it backs off. + frame::Turn::Rest | frame::Turn::BackedOff => return Gate::Skip, + frame::Turn::Draw => if !self.prewarm { self.core.backoff_step(crate::window::BackoffEvent::Lapsed); }, + } + // The swap chain still holds a frame the compositor hasn't shown: this one draws when it + // has room, built from what changed by then (`slot`). + #[cfg(target_os = "windows")] + if let Some(wake) = self.core.slot_wake.clone() && let Some(live) = self.core.surface.live_mut() { + if live.slot.take_surface(&live.surface, move || wake()) == Take::Later { + // The registered wait asks for this frame (`WakeEvent::FrameSlot`): not a miss, + // and no timer of its own to turn the loop with (`waits_for_slot`). + return Gate::Skip; + } + } + let (Some(live), Some(renderer)) = (self.core.surface.live_mut(), self.core.renderer.as_ref()) else { + return Gate::Skip; + }; + // Only a timer woke the resting overlay: build the frame first, and take neither a + // drawable nor a display tick when it draws what's on screen. The link, stopped, would + // draw it at once anyway (`defers_start`). + let quiet = self.core.quiet.presented().is_some() + && timer && !self.prewarm && !self.app.has_compositor() + && !self.app.rt().has_pending_input() + && renderer.srgb_blend() == self.app.rt().srgb_blend(); + #[cfg(target_os = "macos")] + let quiet = quiet && live.pacing.as_ref().is_none_or(|p| p.defers_start(crate::time::now())); + if quiet { + return Gate::QuietTimer; + } + // Claim display pacing before any step when not deferring a quiet timer frame, matching + // `window/host/draw.rs` so a Wait never discards a frame `quiet_step` already stepped. + #[cfg(target_os = "macos")] + { + let opportunity = if self.prewarm { None } else { live.pacing.as_mut().map(|p| p.next_frame()) }; + let Some(target) = frame::claim(opportunity, || live.settle()) else { return Gate::Skip }; + self.target = target; + self.paced = live.pacing.as_ref().is_some_and(|p| p.running()); + } + #[cfg(not(target_os = "macos"))] + { + live.settle(); + self.paced = false; + } + // The present queue's vsync paces redraws where no display link does. + if !self.prewarm { self.core.meter.redraw(self.paced || !cfg!(target_os = "macos")); } + Gate::Draw + } + + fn needs_reblend(&self) -> bool { + self.core.renderer.as_ref().is_some_and(|r| r.srgb_blend() != self.app.rt().srgb_blend()) + } + + fn reblend(&mut self) -> bool { self.reblend_surface() } + + fn step_quiet(&mut self) -> StepInfo { + let now = crate::time::now(); + self.now = Some(now); + #[cfg(target_os = "macos")] + if let Some(live) = self.core.surface.live() { + self.app.rt_mut().paint.set_native_materials(live.materials.native()); + } + let (animating, dt) = self.app.clock_advance(&mut self.core.clock, now, false); + StepInfo { runtime_animating: animating, animating, dt, update_ms: 0.0, presents_at: None } + } + + fn is_unchanged(&mut self, info: &StepInfo) -> bool { + let (Some(live), Some(presented)) = (self.core.surface.live(), self.core.quiet.presented()) else { + return false; + }; + #[cfg(target_os = "macos")] + let next_tick = { + let now = self.now.unwrap_or_else(crate::time::now); + live.pacing.as_ref().map(|p| p.tick_after(now)) + }; + #[cfg(not(target_os = "macos"))] + let next_tick = None; + presented.unchanged_core(self.app.rt(), &live.config, info.animating, next_tick) + } + + fn on_unchanged(&mut self, _info: &StepInfo) { + self.more = self.core.unchanged_frame(self.app); + } + + fn on_quiet_will_draw(&mut self) { + if let Some(live) = self.core.surface.live_mut() { + #[cfg(target_os = "macos")] + { + if let Some(pacing) = live.pacing.as_mut() { let _ = pacing.next_frame(); } + live.settle(); + self.paced = live.pacing.as_ref().is_some_and(|p| p.running()); + } + #[cfg(not(target_os = "macos"))] + { + live.settle(); + self.paced = false; + } + } + if !self.prewarm { self.core.meter.redraw(self.paced || !cfg!(target_os = "macos")); } + } + + fn acquire(&mut self) -> Acquire<wgpu::SurfaceTexture> { + let (Some(live), Some(gpu)) = (self.core.surface.live(), self.core.gpu.as_ref()) else { + return Acquire::Missed(crate::window::Missed::Unconfigured); + }; + match crate::window::acquire_checked( + &live.surface, + gpu, + &live.config, + true, + if self.prewarm { 2 } else { 1 }, + &mut self.core.meter, + !self.read_occlusion, + ) { + Ok(frame) => Acquire::Ready(frame), + Err(missed) => Acquire::Missed(missed), + } + } + + fn step_runtime(&mut self) -> StepInfo { + let now = crate::time::now(); + self.now = Some(now); + #[cfg(not(target_os = "macos"))] + let frame_time = now; + #[cfg(target_os = "macos")] + let frame_time = self.target.unwrap_or(now); + #[cfg(target_os = "macos")] + if let Some(live) = self.core.surface.live() { + self.app.rt_mut().paint.set_native_materials(live.materials.native()); + } + let (animating, dt) = if !self.prewarm && frame::rests(self.app, self.core.runtime_idle, self.core.dirty) { + frame::rest(self.app, &mut self.core.clock, frame_time) + } else { + step(self.app, &mut self.core.clock, frame_time, self.prewarm) + }; + #[cfg(target_os = "macos")] + let presents_at = self.target; + #[cfg(not(target_os = "macos"))] + let presents_at = None; + StepInfo { runtime_animating: animating, animating, dt, update_ms: 0.0, presents_at } + } + + fn post_step_check(&mut self, _info: &mut StepInfo) -> PostStepCheck { + #[cfg(target_os = "macos")] + if !self.materials_checked { + self.materials_checked = true; + if let Some(live) = self.core.surface.live_mut() { + let Backing::Window(window) = &live.backing; + if live.materials.update(self.app.rt().transparent, !self.app.rt().paint.materials().is_empty(), window, &live.surface) { + return PostStepCheck::Reacquire(ReacquireReason::NativeMaterials); + } + } + } + if self.needs_reblend() { + return PostStepCheck::Reacquire(ReacquireReason::Reblend); + } + PostStepCheck::Keep + } + + fn prepare_reacquire(&mut self, reason: ReacquireReason, info: &mut StepInfo) -> bool { + match reason { + #[cfg(any(test, target_os = "macos"))] + ReacquireReason::NativeMaterials => { + // This drawable presents without the views: build again natively into a new one, + // so prewarm and reveal show the material from this frame. + self.app.rt_mut().paint.set_native_materials(true); + let more = self.app.frame(0.0); + info.runtime_animating |= more; + info.animating |= more; + true + } + ReacquireReason::Reblend => { + let _ = info; + self.reblend_surface() + } + } + } + + fn on_missed(&mut self, missed: crate::window::Missed, stepped: bool) { + self.core.acquire_missed(self.app, missed, self.paced, self.prewarm, stepped); + self.more = false; + } + + fn sync_after_step(&mut self, info: &mut StepInfo) { + let now = self.now.unwrap_or_else(crate::time::now); + info.update_ms = if self.app.has_compositor() { now.elapsed().as_secs_f64() * 1000.0 } else { 0.0 }; + super::input::drop_window_requests(self.app.rt_mut()); + self.core.clipboard.flush_core(self.app.rt_mut()); + self.core.sync_ime(self.app); + // Publish the geometry just rendered, never a layout cached from the preceding frame. + self.core.publish_regions(self.app.rt()); + } + + fn prepare_render(&mut self, drawable: wgpu::SurfaceTexture, _info: &mut StepInfo) -> RenderPrep<PreparedOverlayFrame> { + let (Some(live), Some(renderer), Some(gpu)) = ( + self.core.surface.live(), + self.core.renderer.as_mut(), + self.core.gpu.as_ref(), + ) else { + unreachable!("overlay surface, renderer and gpu live across frame"); + }; + let target_format = if self.app.rt().srgb_blend() { live.config.format.remove_srgb_suffix() } else { live.config.format }; + let view = drawable.texture.create_view(&wgpu::TextureViewDescriptor { + format: (target_format != live.config.format).then_some(target_format), + ..Default::default() + }); + let size = (live.config.width, live.config.height); + prepare_gpu_resources(renderer, gpu, self.app.rt_mut(), size, true); + let encoder = gpu.device.create_command_encoder(&Default::default()); + RenderPrep::Ready(PreparedOverlayFrame { frame: drawable, view, encoder, target_format, size }) + } + + fn render(&mut self, prepared: &mut PreparedOverlayFrame, info: &StepInfo) -> bool { + let (Some(live), Some(renderer), Some(gpu)) = ( + self.core.surface.live(), + self.core.renderer.as_mut(), + self.core.gpu.as_ref(), + ) else { + return false; + }; + let target = live.alpha.as_ref().map_or(&prepared.view, |a| &a.view); + let comp_animating = if self.app.has_compositor() { + self.app.render_compositor(OverlayRenderArgs { + device: &gpu.device, + queue: &gpu.queue, + encoder: &mut prepared.encoder, + target, + format: prepared.target_format, + size: prepared.size, + dt: info.dt, + update_ms: info.update_ms, + ui: renderer, + }) + } else { + draw_ui(renderer, gpu, &mut prepared.encoder, target, self.app.rt_mut(), prepared.size, [0.0; 4]); + false + }; + if let Some(alpha) = &live.alpha { + alpha.draw(&mut prepared.encoder, &prepared.view); + } + comp_animating + } + + fn submit_and_present(&mut self, prepared: PreparedOverlayFrame, _info: &StepInfo) -> Instant { + let (Some(live), Some(renderer), Some(gpu)) = ( + self.core.surface.live_mut(), + self.core.renderer.as_ref(), + self.core.gpu.as_ref(), + ) else { + return crate::time::now(); + }; + frame::submit_and_present(live, renderer, gpu, self.app.rt(), prepared.encoder, prepared.frame, self.prewarm); + // The next frame waits for the room this one took (`slot`). + #[cfg(target_os = "windows")] + live.slot.presented_surface(&live.surface); + crate::render::gpu_events::presented(); + crate::time::now() + } + + fn present_targets(&mut self) -> (Option<&mut FrameClock>, &mut RuntimeCore) { + (Some(&mut self.core.clock), self.app.rt_mut()) + } + + fn settle(&mut self, submitted: Instant, info: &StepInfo) { + if !self.prewarm { self.core.meter.presented(); } + self.core.dirty = false; + let Some(live) = self.core.surface.live_mut() else { + self.more = false; + return; + }; + #[cfg(target_os = "macos")] + let next_tick = live.pacing.as_ref().filter(|p| !self.prewarm && p.running()).map(|p| submitted + Duration::from_secs_f64(1.0 / p.refresh_hz())); + #[cfg(not(target_os = "macos"))] + let next_tick = None; + self.core.idle = idle_after(self.app.rt(), info.animating, next_tick); + self.core.runtime_idle = !self.prewarm && idle_after(self.app.rt(), info.runtime_animating, next_tick); + let rt = self.app.rt(); + self.core.quiet.presented_frame(!self.prewarm && self.core.idle && !self.app.has_compositor(), |slot| { + crate::window::Presented::record_core(slot, rt, &live.config, false); + }); + if !self.prewarm { self.core.backoff.step(crate::window::BackoffEvent::Presented); } + // The display link wakes this overlay, never ControlFlow::Poll. Without one (it can't + // be made while the displays sleep, or didn't start), a timer paces its motion. + #[cfg(target_os = "macos")] + { + let now = self.now.unwrap_or(submitted); + let idle = self.core.idle; + let paced = live.pacing.as_mut().is_some_and(|pacing| { + pacing.presented(submitted); + if self.prewarm || idle { pacing.stop(); } + pacing.running() + }); + if !paced && !self.prewarm && !idle { self.core.backoff.step(crate::window::BackoffEvent::At(now + crate::window::TIMER_FRAME)); } + // A display link that couldn't be made while the displays slept: they're back. + if !self.prewarm && live.pacing.is_none() && let Some(wake) = &self.core.frame_wake { + let Backing::Window(window) = &live.backing; + live.pacing = crate::platform::display_link::DisplayLink::retry(window, wake.clone()); + } + if !self.prewarm { self.core.meter.set_pacing(crate::platform::display_link::pacing(live.pacing.as_ref(), !idle)); } + self.more = false; + } + #[cfg(not(target_os = "macos"))] + { + let _ = submitted; + if !self.prewarm { self.core.meter.set_pacing(if self.core.idle { crate::Pacing::Idle } else { crate::Pacing::Vsync }); } + self.more = !self.core.idle; + } + } +} + +impl OverlayCore { + /// Draws a frame if one is due; true while it needs more (animating). + pub(super) fn draw(&mut self, app: &mut dyn OverlayApp) -> bool { + self.presence_due(app, crate::time::now()); + if !self.presence.drawing() { + self.drain_hidden(app); + return false; + } + let more = self.draw_frame(app, false); + self.open_popup(app); + more + } + + /// A layer surface kept while hidden (prewarmed, not shown yet) still hears the compositor. + fn drain_hidden(&mut self, app: &mut dyn OverlayApp) { + #[cfg(all(unix, not(target_os = "macos"), not(target_os = "ios"), not(target_os = "android")))] + if let Some(Live { backing: Backing::Layer(layer), .. }) = self.surface.live_mut() && layer.drain() { + self.hide(app); + } + #[cfg(not(all(unix, not(target_os = "macos"), not(target_os = "ios"), not(target_os = "android"))))] + let _ = app; + } + + /// One input event a layer or XWayland surface read on its own connection. + #[cfg(all(unix, not(target_os = "macos"), not(target_os = "ios"), not(target_os = "android")))] + fn surface_input(&mut self, app: &mut dyn OverlayApp, input: crate::platform::layer_shell::Input) { + use crate::platform::layer_shell::Input; + match input { + Input::Move(x, y) => { + let zoom = app.rt().zoom(); + self.dirty |= app.observe_pointer(x / zoom, y / zoom); + return; + } + Input::Leave => app.rt_mut().pointer_leave(), + Input::Button(down) => if let Some((x, y)) = app.rt().pointer() { + if down { app.pointer_down(x, y); } else { app.pointer_up(x, y); } + }, + Input::Secondary(down) => if let Some((x, y)) = app.rt().pointer() { if down { app.rt_mut().secondary_down(x, y) } else { app.secondary_up(x, y) } }, + Input::Focus(focused) => { + app.window_focus(focused); + app.rt_mut().ignore_minimize("an overlay"); + if matches!(app.rt_mut().shell_request.take(), Some(crate::el::Shell::Close)) { + self.hide(app); + return; + } + } + Input::Key(key) => app.rt_mut().key(key), + Input::KeyUp(key) => { + self.dirty |= app.key_up(key); + return; + } + Input::Physical(event, fallback) => { + let keep = matches!(event, crate::PhysicalInput::Key { pressed: true, .. }) || app.rt().wants_key_up(); + self.dirty |= app.physical_with_fallback(event, fallback.filter(|_| keep)); + return; + } + } + self.dirty = true; + } + + /// Opens the pop-up menu a handler asked for over the overlay's panel. A hidden or occluded + /// overlay answers `None`, committed with its next frame. One anchored to an element waits + /// for the frame that commits what changed since the last. + pub(super) fn open_popup(&mut self, app: &mut dyn OverlayApp) { + let window = match self.surface.live().map(|l| &l.backing) { + Some(Backing::Window(w)) if self.presence.shown() && !self.presence.occluded() => Some(w.clone()), + _ => None, + }; + if app.popup_open(&mut self.popup, window.as_ref(), true) { self.dirty = true; } + } + + /// Syncs OS IME allowance and cursor area for overlays that accept on-demand keyboard focus. + fn sync_ime(&mut self, app: &mut dyn OverlayApp) { + if self.options.keys == KeyPolicy::OnDemand + && let Some(window) = self.surface.live().and_then(|l| l.backing.window()) + { + #[cfg(target_os = "macos")] + let focused = self.panel.as_ref().map_or_else(|| window.has_focus(), |p| p.is_key()); + #[cfg(not(target_os = "macos"))] + let focused = window.has_focus(); + crate::input::host_events::sync_ime(window, app.rt_mut(), &mut self.ime_allowed, focused); + } + } + + pub(super) fn draw_frame(&mut self, app: &mut dyn OverlayApp, prewarm: bool) -> bool { + let mut frame = OverlayFrame { + core: self, + app, + prewarm, + read_occlusion: false, + paced: false, + #[cfg(target_os = "macos")] + target: None, + #[cfg(target_os = "macos")] + materials_checked: false, + now: None, + more: false, + }; + host_step::run(&mut frame); + frame.more + } + + /// Handles a failed drawable acquisition during `draw_frame`. + pub(super) fn acquire_missed(&mut self, app: &mut dyn OverlayApp, missed: crate::window::Missed, paced: bool, prewarm: bool, built: bool) { + if missed == crate::window::Missed::Unconfigured { + if built { + super::input::drop_window_requests(app.rt_mut()); + self.clipboard.flush_core(app.rt_mut()); + } + self.surface_refused(app, "its GPU surface refused a new configuration".into()); + return; + } + if !prewarm { + #[cfg(target_os = "macos")] + if missed == crate::window::Missed::Occluded { self.set_occluded(app, true); } + self.missed(app, missed, paced, built); + } + } + + /// A timer frame that would draw what's on screen: what a drawn frame does besides drawing. + fn unchanged_frame(&mut self, app: &mut dyn OverlayApp) -> bool { + super::input::drop_window_requests(app.rt_mut()); + self.clipboard.flush_core(app.rt_mut()); + self.sync_ime(app); + // Hit regions paint nothing, so a frame can change only them (a full-screen drawing + // surface turning on); no presentation follows to commit them. + #[cfg(all(unix, not(target_os = "macos"), not(target_os = "ios"), not(target_os = "android")))] + if self.publish_regions(app.rt()) && let Some(Live { backing: Backing::Layer(layer), .. }) = self.surface.live_mut() { layer.commit(); } + #[cfg(not(all(unix, not(target_os = "macos"), not(target_os = "ios"), not(target_os = "android"))))] + self.publish_regions(app.rt()); + self.meter.redraw(true); + self.dirty = false; + self.idle = true; + self.runtime_idle = true; + self.meter.set_pacing(self.pacing_state(false)); + false + } + + /// Records whether the shown panel is on screen. Occluded, it stops its display link, + /// ambient loops and live values; uncovered, it redraws once and resumes them. A + /// fading-out panel never becomes occluded (`Presence::set_occluded`). + #[cfg(target_os = "macos")] + pub(super) fn occluded(&mut self, app: &mut dyn OverlayApp, occluded: bool) { + if !self.presence.set_occluded(occluded) { return; } + self.idle = true; + // What it last presented may not be what shows once uncovered. + self.quiet.step(frame::QuietEvent::Forget); + if occluded { + if let Some(live) = self.surface.live_mut() && let Some(pacing) = &mut live.pacing { pacing.stop(); } + app.set_live_visible(false); + } else if self.presence.drawing() { + self.dirty = true; + self.backoff_step(crate::window::BackoffEvent::Revealed); + app.set_live_visible(true); + self.ensure_pacing(); + } + } + + /// Reads the panel's occlusion directly: one shown onto covered or sleeping displays gets + /// no event saying so. Once a loop turn: the tick's draw and `about_to_wait` share it, and + /// `Occluded` events land in between. + #[cfg(target_os = "macos")] + pub(super) fn sync_occlusion(&mut self, app: &mut dyn OverlayApp) { + if std::mem::replace(&mut self.occlusion_read, true) { return; } + let occluded = self.panel.as_ref().is_some_and(|p| p.occluded()); + self.set_occluded(app, occluded); + } + + /// Applies an occlusion reading when it changes what the panel holds. + #[cfg(target_os = "macos")] + pub(super) fn set_occluded(&mut self, app: &mut dyn OverlayApp, occluded: bool) { + if occluded != self.presence.occluded() { self.occluded(app, occluded); } + } + + /// A display link made while the displays slept fails; try again once they may be back. One + /// that exists follows the panel to the display it is on now. + #[cfg(target_os = "macos")] + pub(super) fn ensure_pacing(&mut self) { + let (Some(live), Some(wake)) = (self.surface.live_mut(), &self.frame_wake) else { return }; + let Backing::Window(window) = &live.backing; + match &mut live.pacing { + Some(pacing) => pacing.update_display(window), + None => live.pacing = crate::platform::display_link::DisplayLink::new(window, wake.clone()), + } + } + + /// Warm glyphs/pipelines and, on macOS, the retained alpha-zero host's actual surface. + pub(super) fn warm(&mut self, app: &mut dyn OverlayApp) { + app.frame(0.0); + app.rt_mut().settle_all(); + app.frame(0.0); + self.clock.hold(crate::time::now()); + self.warm_frame(app); + } + + pub(super) fn warm_frame(&mut self, app: &mut dyn OverlayApp) { + self.publish_regions(app.rt()); + #[cfg(target_os = "macos")] + if let Some(panel) = &self.panel { + let _prewarm = panel.prewarm(); + self.dirty = true; + self.draw_frame(app, true); + if let Some(gpu) = &self.gpu { rune_gpu::health::poll(&gpu.device, wgpu::PollType::wait_indefinitely()).ok(); } + return; + } + let Some(live) = self.surface.live() else { return }; + self.warm_offscreen(app, (live.config.width, live.config.height)); + } + + pub(super) fn warm_offscreen(&mut self, app: &mut dyn OverlayApp, size: (u32, u32)) { + let (Some(renderer), Some(gpu)) = (&mut self.renderer, &self.gpu) else { return }; + let target = gpu.device.create_texture(&wgpu::TextureDescriptor { + label: Some("overlay prewarm"), size: wgpu::Extent3d { width: size.0, height: size.1, depth_or_array_layers: 1 }, + mip_level_count: 1, sample_count: 1, dimension: wgpu::TextureDimension::D2, + format: renderer.format(), usage: wgpu::TextureUsages::RENDER_ATTACHMENT, view_formats: &[], + }); + let view = target.create_view(&Default::default()); + let mut enc = gpu.device.create_command_encoder(&Default::default()); + render_frame(app, OverlayRenderArgs { + device: &gpu.device, queue: &gpu.queue, encoder: &mut enc, + target: &view, format: renderer.format(), size, + dt: 0.0, update_ms: 0.0, ui: renderer, + }); + renderer.submit(&gpu.queue, enc); + rune_gpu::health::poll(&gpu.device, wgpu::PollType::wait_indefinitely()).ok(); + } +} diff --git a/app/vendor/rune/crates/rune/src/overlay/frame.rs b/app/vendor/rune/crates/rune/src/overlay/frame.rs new file mode 100644 index 0000000..bdc2fe9 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/overlay/frame.rs @@ -0,0 +1,303 @@ +//! An overlay frame's steps apart from its window: the animation step, the compositor or +//! default draw, whether anything asks for another frame, and the submit and present. + +use super::app::OverlayApp; +use super::{Backing, Live}; +use crate::frame::clock::FrameClock; +use crate::machine::Effects; +use crate::render::{Gpu, Renderer}; +use crate::runtime::RuntimeCore; +use crate::time::Instant; +use crate::window::Presented; + +/// Non-generic arguments passed to [`OverlayApp::render_compositor`], which constructs +/// [`crate::compose::Frame<'_, T>`] in place. +pub(super) struct OverlayRenderArgs<'a> { + pub device: &'a wgpu::Device, + pub queue: &'a wgpu::Queue, + pub encoder: &'a mut wgpu::CommandEncoder, + pub target: &'a wgpu::TextureView, + pub format: wgpu::TextureFormat, + pub size: (u32, u32), + pub dt: f64, + pub update_ms: f64, + pub ui: &'a mut Renderer, +} + +/// Whether nothing asks for the frame after one just presented. `next_tick` is the running +/// display link's next tick, if one paces the overlay: a timer due by then counts as asking, +/// so a poll stepping its own animation with `Tx::wake_after(Duration::ZERO)` gets every frame +/// at the display's rate instead of the link stopping after each frame. Unpaced, the timer +/// waits a frame in `wake_deadline` and never keeps the loop turning. +pub(super) fn idle_after(rt: &RuntimeCore, animating: bool, next_tick: Option<Instant>) -> bool { + !(animating || rt.stale() || rt.live_pending() || crate::window::timer_wants_frame_core(rt, next_tick)) +} + +/// `draw_frame`'s animation step, apart from the surface so tests can drive it. +pub(super) fn step(app: &mut dyn OverlayApp, clock: &mut FrameClock, frame_time: Instant, prewarm: bool) -> (bool, f64) { + if prewarm { + clock.hold(frame_time); + return (app.frame(0.0), 0.0); + } + let animating = app.compositor_animating(); + app.clock_advance(clock, frame_time, animating) +} + +/// What a shown overlay's last frame drew while it rests, and whether only a due timer asked +/// for the next. That frame builds before it takes a drawable or starts the display link, and +/// draws nothing when it would draw the same pixels: a poll that wakes on a timer and changes +/// nothing on screen presents nothing. +#[derive(Debug, PartialEq, Eq)] +pub(super) enum Quiet<P = Presented> { + /// What it presented isn't known: nothing drawn yet, or motion, a compositor or a prewarm + /// frame drew it, or it was covered or hidden since. + Unknown, + /// It rests on `presented`. `timer`: only a due timer asked for the next frame, which is + /// that frame's alone. + Rests { presented: P, timer: bool }, +} + +#[derive(Debug, PartialEq, Eq)] +pub(super) enum QuietEvent<P = Presented> { + /// A due timer asks for a frame; `resting`: nothing else does (idle, nothing dirty). + TimerDue { resting: bool }, + /// `draw_frame` begins. + FrameStarts, + /// A frame presented: it rests on `Some` (recorded into what `slot` took), or its pixels + /// are no longer known. + Presented(Option<P>), + /// Covered or hidden: what it last presented may not be what shows next. + Forget, +} + +#[derive(Debug, PartialEq, Eq)] +pub(super) enum QuietEffect { + /// The frame starting is a resting overlay's timer frame: it builds first, and draws + /// nothing when it would draw `presented` again. + TimerFrame, +} + +impl<P> Default for Quiet<P> { + fn default() -> Self { Quiet::Unknown } +} + +impl<P> Quiet<P> { + pub(super) fn step(&mut self, event: QuietEvent<P>) -> Effects<QuietEffect> { + match (self, event) { + (Quiet::Rests { timer, .. }, QuietEvent::TimerDue { resting: true }) => *timer = true, + (_, QuietEvent::TimerDue { .. }) => {} + (Quiet::Rests { timer, .. }, QuietEvent::FrameStarts) => if std::mem::take(timer) { return Effects::one(QuietEffect::TimerFrame) }, + (Quiet::Unknown, QuietEvent::FrameStarts) => {} + (this, QuietEvent::Presented(Some(presented))) => *this = Quiet::Rests { presented, timer: false }, + (this, QuietEvent::Presented(None) | QuietEvent::Forget) => *this = Quiet::Unknown, + } + Effects::none() + } + + /// The frame it rests on. + pub(super) fn presented(&self) -> Option<&P> { + match self { + Quiet::Rests { presented, .. } => Some(presented), + Quiet::Unknown => None, + } + } + + /// After a frame presents: it rests on that frame (`record` writes it over the last one's + /// buffers), or its pixels are no longer known (a prewarm frame, motion, a compositor). + pub(super) fn presented_frame(&mut self, rests: bool, record: impl FnOnce(&mut Option<P>)) { + let presented = rests.then(|| { + let mut slot = match std::mem::take(self) { + Quiet::Rests { presented, .. } => Some(presented), + Quiet::Unknown => None, + }; + record(&mut slot); + slot + }).flatten(); + self.step(QuietEvent::Presented(presented)); + } +} + +/// What a turn's frame does once the surface can draw, before it takes a drawable. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum Turn { + /// Shown but none of it on screen (macOS): it draws nothing. `recheck`: its retry is due, + /// or it has none, so a miss runs what the frame would have and waits again. + Occluded { recheck: bool }, + /// Nothing changed and nothing moves. + Rest, + /// Waiting out a missed frame's retry, or the timer pacing unpaced motion. + BackedOff, + /// A frame is due. A timer frame may still find nothing new to present (`Quiet`). + Draw, +} + +/// Whether this event-loop turn has already stepped or missed a frame for this overlay, so +/// `wake_due` + occluded recheck or a paced `DisplayTick` miss + `about_to_wait` never advance +/// the runtime twice in one turn. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(super) enum TurnFrame { + #[default] + Idle, + /// `wake_due` already stepped the runtime for a due timer this turn. + WakeStepped, + /// A frame missed in this turn: wait for the next turn or tick instead of retrying in + /// `about_to_wait`. + Missed, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum TurnEvent { + NewEvents, + WakeStepped, + FrameMissed, +} + +impl TurnFrame { + pub(super) fn step(&mut self, event: TurnEvent) { + *self = match (*self, event) { + (_, TurnEvent::NewEvents) => TurnFrame::Idle, + (TurnFrame::Idle, TurnEvent::WakeStepped) => TurnFrame::WakeStepped, + (state, TurnEvent::WakeStepped) => state, + (_, TurnEvent::FrameMissed) => TurnFrame::Missed, + }; + } + + pub(super) fn stepped(self) -> bool { + !matches!(self, TurnFrame::Idle) + } + + pub(super) fn missed(self) -> bool { + matches!(self, TurnFrame::Missed) + } +} + +/// What `turn` decides from. `occluded` is the panel's reading this turn (macOS). +#[derive(Clone, Copy, Debug)] +pub(super) struct Gate { + pub(super) prewarm: bool, + pub(super) occluded: bool, + pub(super) dirty: bool, + pub(super) idle: bool, + pub(super) retry: Option<Instant>, + pub(super) missed_this_turn: bool, +} + +/// Until it's uncovered, only the retry (or a due timer, in `wake_due`) steps an occluded +/// overlay, however often other windows turn the loop; input waits for the retry too. A +/// prewarm frame draws regardless of both. `now` is read only where a retry is compared. +pub(super) fn turn(gate: Gate, now: impl Fn() -> Instant) -> Turn { + if !gate.prewarm && gate.missed_this_turn { + return Turn::BackedOff; + } + if !gate.prewarm && gate.occluded { + return Turn::Occluded { recheck: gate.retry.is_none_or(|retry| retry <= now()) }; + } + if !gate.dirty && gate.idle { return Turn::Rest; } + if !gate.prewarm && gate.retry.is_some_and(|retry| retry > now()) { return Turn::BackedOff; } + Turn::Draw +} + +/// A resting overlay's timer frame, stepped before any drawable: `None` when it draws what +/// `presented` shows and nothing asks for the next (`next_tick`: the display link's next tick, +/// had it run), else the step's `(animating, dt)` to draw with. +#[cfg(test)] +pub(super) fn quiet_step(app: &mut dyn OverlayApp, clock: &mut FrameClock, presented: &Presented, + config: &wgpu::SurfaceConfiguration, now: Instant, next_tick: Option<Instant>) -> Option<(bool, f64)> { + let (animating, dt) = app.clock_advance(clock, now, false); + (!presented.unchanged_core(app.rt(), config, animating, next_tick)).then_some((animating, dt)) +} + +/// Whether a frame can leave the runtime as it is, drawing its last build again: after the +/// last frame it asked for no other (`runtime_idle`: only the compositor animates), nothing +/// marked the overlay dirty since, and no input, live value, timer, playground or poll (which +/// runs on every frame drawn) waits. An overlay without a compositor draws nothing then. +pub(super) fn rests(app: &dyn OverlayApp, runtime_idle: bool, dirty: bool) -> bool { + let rt = app.rt(); + runtime_idle && !dirty && !app.has_poll() && !rt.tree.has_playground && rt.wake_deadline().is_none() && rt.rests() +} + +/// `step` for a runtime that `rests`: its clocks (`clock`, `t`) move to the frame as a step +/// would move them, so a compositor reading them animates the same, and nothing runs or builds. +pub(super) fn rest(app: &mut dyn OverlayApp, clock: &mut FrameClock, frame_time: Instant) -> (bool, f64) { + let elapsed = clock.frame_step(frame_time, app.compositor_animating()).total(); + let rt = app.rt_mut(); + rt.frame.set_frame_target(frame_time); + rt.clock = rt.wall_start.map_or(rt.clock + elapsed, |t0| t0.elapsed().as_secs_f64()); + rt.t += elapsed * rt.time_scale as f64; + rt.scene.set_time(rt.t); + (false, elapsed) +} + +/// A due frame's target presentation time, or `None` when the display link says wait. The +/// opportunity is claimed before `settle` waits for the frame still on the present thread, so +/// a turn that draws nothing (the loop's second look after a tick drew) never blocks on it. +#[cfg(target_os = "macos")] +pub(super) fn claim(opportunity: Option<crate::platform::display_link::Opportunity>, settle: impl FnOnce()) -> Option<Option<Instant>> { + let target = match opportunity { Some(opportunity) => opportunity.target()?, None => None }; + settle(); + Some(target) +} + +/// Both native surface frames and offscreen prewarming use the same compositor path. +pub(super) fn render_frame(app: &mut dyn OverlayApp, f: OverlayRenderArgs<'_>) -> bool { + { + let rt = app.rt_mut(); + f.ui.upload_images(f.device, f.queue, &mut rt.images); + f.ui.build_surfaces(f.device, &rt.surfaces, rt.live_notifier()); + f.ui.prepare_surfaces(f.device, f.queue, &rt.surfaces, f.size); + f.ui.set_frame_wake(rt.live_wake()); + } + if app.has_compositor() { + app.render_compositor(f) + } else { + let rt = app.rt_mut(); + f.ui.set_fade_stops(rt.fade_stops()); + f.ui.prepare_ui(f.device, f.queue, &mut rt.text.atlas, &rt.instances, f.size); + f.ui.draw(f.encoder, f.target, [0.0; 4]); + false + } +} + +/// Submits the frame's commands and presents its drawable. On macOS a plain frame (no material +/// views to move with the drawable, no transaction, no native video surface waiting on the +/// submission) is finished, submitted and presented on the overlay's present thread, so the +/// event loop's thread spends none of wgpu's encode, submit and present on it. Prewarm frames +/// present here, before the window is revealed. +pub(super) fn submit_and_present(live: &mut Live, renderer: &Renderer, gpu: &Gpu, rt: &RuntimeCore, + encoder: wgpu::CommandEncoder, frame: wgpu::SurfaceTexture, prewarm: bool) { + #[allow(irrefutable_let_patterns)] + if let Backing::Window(w) = &live.backing { + w.pre_present_notify(); + } + #[cfg(target_os = "macos")] + { + if !prewarm && live.materials.presents_plainly() && renderer.submits_plainly() && !crate::gpu::native(&gpu.queue) { + if live.present.is_none() { live.present = crate::frame::present_worker::PresentWorker::spawn(); } + if let Some(worker) = &mut live.present { + let mut encoder = encoder; + renderer.before_submit(&mut encoder); + let queue = gpu.queue.clone(); + return worker.run(move || { + queue.submit([encoder.finish()]); + queue.present(frame); + }); + } + } + renderer.submit(&gpu.queue, encoder); + live.materials.present(rt.paint.materials(), rt.env.scale, || gpu.queue.present(frame)); + } + #[cfg(not(target_os = "macos"))] + { + let _ = (rt, prewarm); + renderer.submit(&gpu.queue, encoder); + gpu.queue.present(frame); + } +} + +impl Live { + /// Waits for the frame on the present thread, before the surface is touched again. + pub(super) fn settle(&mut self) { + #[cfg(target_os = "macos")] + if let Some(worker) = &mut self.present { worker.wait(); } + } +} diff --git a/app/vendor/rune/crates/rune/src/overlay/input.rs b/app/vendor/rune/crates/rune/src/overlay/input.rs new file mode 100644 index 0000000..bd973ab --- /dev/null +++ b/app/vendor/rune/crates/rune/src/overlay/input.rs @@ -0,0 +1,497 @@ +//! An overlay's pointer, cursor and input regions, its drag-out, and when it advances, commits, +//! wakes and syncs with its handle's requests. + +use super::*; + +/// An overlay has no window to ask: whatever a step requested of one is dropped. +pub(super) fn drop_window_requests(rt: &mut RuntimeCore) { + rt.shell_request = None; + rt.ignore_minimize("an overlay"); + // Overlays size through `OverlayHandle::resize`, not `Tx::resize_window`. + rt.host.window_frame = None; +} + +impl OverlayCore { + /// The runtime's cursor while the pointer is over a hit area of a shown overlay that takes + /// input; the arrow once when it leaves, so `Cursor::Hidden` never outlives the overlay or + /// the hover, and a click-through area leaves the cursor to the window under it. A Wayland + /// layer overlay sets it through cursor-shape-v1; without that, the pointer keeps the cursor + /// it arrived with. + pub(super) fn apply_cursor(&mut self, rt: &RuntimeCore) { + let input = self.options.input.resolved(self.interactive); + let over = rt.pointer().is_some_and(|(x, y)| { + x >= 0.0 && y >= 0.0 && x < self.at.size.0 && y < self.at.size.1 + && (input != OverlayInput::Regions || rt.pointer_captured() + || rt.hit_regions().iter().any(|r| crate::overlay::options::contains(*r, x, y))) + }); + let active = self.presence.shown() && input != OverlayInput::None && over; + let want = rt.cursor(); + #[cfg(all(unix, not(target_os = "macos"), not(target_os = "ios"), not(target_os = "android")))] + if let Some(Live { backing: Backing::Layer(layer), .. }) = self.surface.live_mut() { + layer.set_cursor(if active { want } else { crate::el::Cursor::Default }); + return; + } + let (Some(Live { backing: Backing::Window(window), .. }), Some(cursor)) = (self.surface.live(), &mut self.cursor) else { return }; + cursor.apply(window, want, active); + #[cfg(target_os = "macos")] + if let Some(panel) = &self.panel { panel.set_cursor(active.then_some(want)); } + } + + #[cfg_attr(any(target_os = "ios", target_os = "android"), allow(dead_code))] + pub(super) fn observe_pointer(&mut self, app: &mut dyn OverlayApp, x: f32, y: f32) { + if app.rt().pointer_captured() || (x >= 0.0 && y >= 0.0 && x < self.at.size.0 && y < self.at.size.1) { + self.dirty |= app.observe_pointer(x, y); + self.begin_drag_out(app.rt_mut()); + } else if app.rt().pointer().is_some() { + app.rt_mut().pointer_leave(); + self.dirty = true; + } + } + + /// Starts the OS drag a pointer move asked for, before the move event returns. + pub(super) fn begin_drag_out(&mut self, rt: &mut RuntimeCore) { + let Some(start) = rt.take_drag_out() else { return }; + self.dirty = true; + let (sink, path) = (rt.drag_end_sink(), start.path.clone()); + #[allow(irrefutable_let_patterns)] + let Some(Live { backing: Backing::Window(window), config, scale, .. }) = self.surface.live() else { + sink.borrow_mut().push((path, crate::DragOutcome::Cancelled)); + return; + }; + let image = match (&self.gpu, &self.renderer) { + (Some(gpu), Some(renderer)) if start.item.drag_image().is_none() => + crate::drag_out::snapshot(gpu, renderer, (config.width, config.height), *scale, rt.clear_color(), start.rect), + _ => None, + }; + let wake = self.shared.wake.lock().unwrap().clone(); + crate::drag_out::begin(window, start, image, Box::new(move |outcome| { + sink.borrow_mut().push((path, outcome)); + if let Some(wake) = wake { wake(); } + })); + // The system drag swallows the button release, so let go of the panel's capture now + // rather than after its missed-release grace: the panel turns click-through outside + // its regions (so drops land on the windows below) and deferred input changes apply. + #[cfg(target_os = "macos")] + if let Some(panel) = &self.panel { panel.pointer_released(); } + self.apply_input(rt); + self.apply_cursor(rt); + } + + /// A left press or release, at the panel's click point when it has one. + pub(super) fn left_button(&mut self, app: &mut dyn OverlayApp, pressed: bool, point: Option<(f32, f32)>) { + if pressed { + if let Some((x, y)) = point { app.pointer_move(x, y); } + if let Some((x, y)) = app.rt().pointer() { + app.pointer_down(x, y); + app.rt_mut().physical_input(crate::PhysicalInput::Modifiers(crate::window::map_mods(self.mods))); + } + } else if let Some((x, y)) = point.or(app.rt().pointer()) { + // `pointer_up` moves to the release point itself, after disarming a drag-out: a + // release never starts an OS drag. + app.pointer_up(x, y); + } + self.dirty = true; + } + + /// winit reported the pointer at (x, y). + pub(super) fn cursor_moved(&mut self, app: &mut dyn OverlayApp, x: f32, y: f32) { + self.dirty |= app.observe_pointer(x, y); + self.begin_drag_out(app.rt_mut()); + } + + #[cfg(target_os = "macos")] + pub(super) fn native_pointer(&self) -> Option<Rc<crate::platform::macos::PointerState>> { + self.panel.as_ref().map(|panel| panel.pointer_state()) + } + + /// A release lost before the click a position belongs to ends first, so the press that lost + /// it never hears that position. + #[cfg(target_os = "macos")] + pub(super) fn before_position(&mut self, app: &mut dyn OverlayApp, pointer: &crate::platform::macos::PointerState) { + let lost = pointer.take_lost_before_position(); + self.release_lost(app, lost); + } + + /// winit reported a position on the panel. With the button known up, the held press can't + /// start an OS drag: the session needs the button held, and this is the Up's own position or + /// one from before it. + #[cfg(target_os = "macos")] + pub(super) fn native_moved(&mut self, app: &mut dyn OverlayApp, pointer: &crate::platform::macos::PointerState, x: f32, y: f32) { + self.before_position(app, pointer); + if pointer.button_up() { app.rt_mut().disarm_drag_out(); } + self.cursor_moved(app, x, y); + } + + /// winit dispatched a left press or release on the panel. + #[cfg(target_os = "macos")] + pub(super) fn native_left(&mut self, app: &mut dyn OverlayApp, pointer: &crate::platform::macos::PointerState, pressed: bool) { + let (lost, point) = pointer.take_edge(pressed); + self.left_edge(app, lost, pressed, point); + } + + /// A turn's pointer work once the panel has sampled: the position to report, if any. + #[cfg(target_os = "macos")] + pub(super) fn turn_position(&mut self, app: &mut dyn OverlayApp, pointer: &crate::platform::macos::PointerState) -> Option<(f32, f32)> { + self.before_position(app, pointer); + pointer.take_position() + } + + /// Ends the runtime's press if the panel lost its release: the runtime hears no drop. + #[cfg(target_os = "macos")] + pub(super) fn release_lost(&mut self, app: &mut dyn OverlayApp, lost: Option<(f32, f32)>) { + if let Some((x, y)) = lost && app.rt().pointer_captured() { + app.pointer_release_lost(x, y); + self.dirty = true; + } + } + + /// A left press or release from the panel. A release it already gave up on lands first, so + /// it can't end this press, and a late Up can't turn it into a drop. + #[cfg(target_os = "macos")] + pub(super) fn left_edge(&mut self, app: &mut dyn OverlayApp, lost: Option<(f32, f32)>, pressed: bool, point: Option<(f32, f32)>) { + self.release_lost(app, lost); + if self.options.input.resolved(self.interactive) != OverlayInput::None { self.left_button(app, pressed, point); } + } + + /// Delivers clipboard replies or secret-copy changes from the worker. A shown overlay steps + /// them on its next drawn frame; a hidden or occluded one advances now. + pub(super) fn clipboard_due(&mut self, app: &mut dyn OverlayApp) { + if !self.clipboard.receive_core(app.rt_mut()) { return; } + self.dirty = true; + if self.frameless() { self.advance(app); } + } + + /// Delivers drag ends a host reported. An `on_drag_start` may have hidden the overlay; + /// its `on_drag_end` still runs. + pub(super) fn drag_ends_due(&mut self, app: &mut dyn OverlayApp) { + if !app.rt().drag_ends_pending() { return; } + self.dirty = true; + if self.frameless() { self.advance(app); } + } + + /// True when a layer surface's input region changed and waits for a commit. + pub(super) fn publish_regions(&mut self, rt: &RuntimeCore) -> bool { + // An X11 window's input shape applies at once, with no commit to wait for. + #[cfg(all(unix, not(target_os = "macos"), not(target_os = "ios"), not(target_os = "android")))] + if let Some(Live { backing: Backing::Xwayland(surface), .. }) = self.surface.live_mut() { + surface.regions(rt.hit_regions()); + return false; + } + let Some(live) = self.surface.live() else { return false }; + #[cfg(target_os = "macos")] + if let Some(panel) = &self.panel { panel.set_regions(rt.hit_regions()); } + #[cfg(target_os = "windows")] + if let Some(native) = &self.native { native.set_regions(rt.hit_regions(), live.scale); } + #[cfg(all(unix, not(target_os = "macos"), not(target_os = "ios"), not(target_os = "android")))] + if self.options.input.resolved(self.interactive) == OverlayInput::Regions && let Some(x11) = &mut self.x11 { x11.regions(rt.hit_regions(), live.scale); } + #[cfg(all(unix, not(target_os = "macos"), not(target_os = "ios"), not(target_os = "android")))] + if let Backing::Layer(layer) = &live.backing { return layer.input_regions(rt.hit_regions(), self.interactive); } + let _ = (live, rt); + false + } + + pub(super) fn apply_input(&mut self, rt: &RuntimeCore) { + if rt.pointer_captured() { return; } + #[cfg(target_os = "macos")] + if self.panel.as_ref().is_some_and(|panel| panel.pointer_captured()) { return; } + let Some(input) = self.pending_input.take() else { return }; + self.options.input = input; + let resolved = input.resolved(self.interactive); + #[cfg(any(target_arch = "wasm32", target_os = "ios", target_os = "android"))] + let _ = resolved; + #[cfg(target_os = "macos")] + if let Some(panel) = &self.panel { panel.set_input(resolved); } + #[cfg(target_os = "windows")] + if let Some(native) = &mut self.native { native.set_input(resolved); } + #[cfg(all(unix, not(target_os = "macos"), not(target_os = "ios"), not(target_os = "android")))] + { + if let Some(x11) = &mut self.x11 { x11.set_input(resolved); } + match self.surface.live_mut() { + Some(Live { backing: Backing::Layer(layer), .. }) => layer.set_input(resolved), + Some(Live { backing: Backing::Xwayland(surface), .. }) => surface.set_input(resolved), + _ => {} + } + } + self.publish_regions(rt); + #[cfg(all(unix, not(target_os = "macos"), not(target_os = "ios"), not(target_os = "android")))] + if let Some(Live { backing: Backing::Layer(layer), .. }) = self.surface.live_mut() { layer.commit(); } + } + + pub(super) fn advance(&mut self, app: &mut dyn OverlayApp) { self.advance_at(app, crate::time::now()); } + + /// An overlay that draws nothing delivers queued input without drawing, such as the + /// releases of the modifier keys held when it hid, rather than when it next shows. + pub(super) fn hidden_input(&mut self, app: &mut dyn OverlayApp) { + if !self.presence.drawing() && app.rt().keys_queued() { self.advance(app); } + } + + /// Fn changes the monitor saw since the loop last turned. A hidden overlay drops them: its + /// hide released Fn, and it takes no keys. + #[cfg(target_os = "macos")] + pub(super) fn fn_key(&mut self, app: &mut dyn OverlayApp) { + let Some(changes) = self.surface.live().and_then(|l| l.fn_key.as_ref()).map(|f| f.take()) else { return }; + if !self.presence.shown() || self.options.keys != KeyPolicy::OnDemand { return; } + for pressed in changes { + self.dirty |= app.physical_with_fallback(crate::PhysicalInput::Key { + key: winit::keyboard::KeyCode::Fn, mods: crate::window::map_mods(self.mods), pressed, repeat: false, + }, None); + } + } + + /// Handle updates, and the `setup` waker (new data arrived) re-runs the view. A shown + /// overlay draws a frame, which polls; a hidden one polls now, as for a due timer, and + /// re-runs the view when it shows (`advance_at`). + /// Updates that changed nothing (`update_if`) only deliver their requests. + pub(super) fn apply_wake(&mut self, app: &mut dyn OverlayApp, woken: bool) { + let (queued, updated) = app.drain_updates(); + self.apply_wake_drained(app, woken, queued, updated); + } + + pub(super) fn apply_wake_drained(&mut self, app: &mut dyn OverlayApp, woken: bool, queued: bool, updated: bool) { + if woken { app.rt_mut().invalidate(); } + if queued || woken { self.clipboard.flush_core(app.rt_mut()); } + if !woken && !updated { + if !queued { return; } + // A pop-up they asked for may be answered at once, running its callback: a change. + let stale = app.rt().needs_commit(); + self.open_popup(app); + if (stale || !app.rt().needs_commit()) && !app.rt().has_pending_input() { + app.rt_mut().schedule_pending_wakes(); + return; + } + self.clipboard.flush_core(app.rt_mut()); + } + self.dirty = true; // Queued updates already invalidate the cache before polling. + if self.frameless() { + // Register timer requests even before the first show; hidden or occluded overlays + // don't draw. + self.advance(app); + } + } + + /// Hidden, or shown but not on screen: no frame will come to run what's due. + pub(super) fn frameless(&self) -> bool { + !self.presence.drawing() || self.presence.occluded() + } + + pub(super) fn advance_at(&mut self, app: &mut dyn OverlayApp, now: Instant) { + // Covered or asleep, a shown overlay only polls. What it would commit waits for the + // first uncovered frame, which resumes running motion and starts new motion fresh + // (`step`). Hidden, an overlay only polls too, and its view waits for the frame that + // shows it; a retained one commits at most every `HIDDEN_REFRESH` to keep its cached + // frame near. Input and drag ends still run their handlers now. + let handlers = app.rt().has_pending_input() || app.rt().drag_ends_pending(); + let polls_only = !handlers && if self.presence.drawing() { self.presence.shown() && self.presence.occluded() } else { !self.retained() || !self.hidden_pace.ready(now) }; + if !polls_only { return self.commit_at(app, now); } + app.poll_hidden(); + if app.rt().has_pending_input() { return self.commit_at(app, now); } + drop_window_requests(app.rt_mut()); + self.clipboard.flush_core(app.rt_mut()); + self.open_popup(app); + if self.presence.drawing() { + self.dirty = true; + } else if app.rt().needs_commit() { + self.dirty = true; + if self.retained() { self.hidden_pace.changed(now); } + } + } + + /// Runs a frame without drawing: handlers, poll, the view and layout. + pub(super) fn commit_at(&mut self, app: &mut dyn OverlayApp, now: Instant) { + let commits = app.rt().stats.commits; + if self.retained() { + app.frame_split(now.saturating_duration_since(self.clock.last()).as_secs_f64(), 0.0); + self.clock.hold(now); + } else { + app.frame(0.0); + } + drop_window_requests(app.rt_mut()); + self.clipboard.flush_core(app.rt_mut()); + self.open_popup(app); + let rt = app.rt(); + if !self.presence.drawing() && rt.stats.commits != commits { self.hidden_pace.rendered(now); } + // Even a transition that finished in this step needs its current pixels submitted. + // A scheduling-only poll with no motion still preserves the prepared frame. + if rt.stats.commits != commits || rt.animating || !self.idle { + self.dirty = true; + self.idle = false; + } + } + + pub(super) fn wake_due(&mut self, app: &mut dyn OverlayApp, now: Instant) { + self.presence_due(app, now); + // Paced to a frame interval: a hidden or covered overlay's poll that keeps asking for + // the next frame runs once a frame, however often other events turn the loop. + let deadline = crate::window::timer_deadline_core(app.rt()); + if deadline.is_some_and(|deadline| deadline <= now) { + // Backing off, the frame waits for the retry and would leave the timer due. + if !self.frameless() && !self.backing_off(now) { + // Like the window host, poll once in the upcoming frame, after acquiring + // the drawable. A false poll result does not keep the display loop alive. + // Resting, it may draw nothing new (`Quiet`). + self.quiet.step(frame::QuietEvent::TimerDue { resting: self.idle && !self.dirty }); + self.dirty = true; + } else { + // No frame will come to run it in time: a hidden, occluded or backing-off + // overlay steps without drawing, so its timers fire (and may hide it) on time. + self.advance(app); + self.turn_frame.step(frame::TurnEvent::WakeStepped); + } + } + // A hidden retained overlay's paced commit of what changed since its last. + if !self.presence.drawing() && self.hidden_pace.take_due(now) { self.advance_at(app, now); } + if self.backoff.deadline().is_some_and(|at| at <= now) { + self.backoff_step(crate::window::BackoffEvent::Lapsed); + self.dirty = true; + } + } + + /// A frame with no drawable still runs what it would have (updates, poll, due timers) + /// without drawing, as a hidden overlay does, unless it already `stepped`. The next try + /// waits, with the display link stopped so no tick tries sooner. + pub(super) fn missed(&mut self, app: &mut dyn OverlayApp, missed: crate::window::Missed, paced: bool, stepped: bool) { + let now = crate::time::now(); + self.quiet.step(frame::QuietEvent::Forget); + self.turn_frame.step(frame::TurnEvent::FrameMissed); + if stepped { + drop_window_requests(app.rt_mut()); + self.clipboard.flush_core(app.rt_mut()); + } else { + self.advance_at(app, now); + } + self.backoff_step(crate::window::BackoffEvent::Missed { missed, paced, now }); + let pacing = self.pacing_state(missed != crate::window::Missed::Occluded); + self.meter.set_pacing(pacing); + } + + /// Steps the overlay's wait after a frame it couldn't draw, and carries out what that asks: + /// a display link that would draw sooner than the wait stops. + pub(super) fn backoff_step(&mut self, event: crate::window::BackoffEvent) { + for effect in self.backoff.step(event) { + match effect { + crate::window::BackoffEffect::StopPacing => { + #[cfg(target_os = "macos")] + if let Some(pacing) = self.surface.live_mut().and_then(|l| l.pacing.as_mut()) { pacing.stop(); } + } + } + } + } + + /// Waiting for a missed frame's retry, or for the timer pacing unpaced motion. + pub(super) fn backing_off(&self, now: Instant) -> bool { self.backoff.waiting(now) } + + /// What paces the overlay's frames, for its stats. + pub(super) fn pacing_state(&self, moving: bool) -> crate::Pacing { + #[cfg(target_os = "macos")] + return crate::platform::display_link::pacing(self.surface.live().and_then(|l| l.pacing.as_ref()), moving); + #[cfg(not(target_os = "macos"))] + if moving { crate::Pacing::Vsync } else { crate::Pacing::Idle } + } + + /// Applies requests from other threads: updates, edge, show and hide. + pub(super) fn sync(&mut self, app: &mut dyn OverlayApp, event_loop: &ActiveEventLoop) { + self.clipboard_due(app); + if app.popup_answer(&mut self.popup) { + self.dirty = true; + if self.frameless() { self.advance(app); } + } + if app.rt().live_pending() { self.dirty = true; } + self.drag_ends_due(app); + let requests = std::mem::take(&mut *self.shared.requests.lock().unwrap()); + if let Some(input) = requests.input { self.pending_input = Some(input); } + self.apply_input(app.rt()); + if let Some(exclude) = requests.exclude_from_capture { self.set_capture_exclusion(exclude); } + if let Some(allow) = requests.xwayland_input { self.options.xwayland_input = allow; } + if let Some(follow) = requests.follow_pointer { + self.options.follow_pointer = follow; + #[cfg(target_os = "macos")] + if let Some(panel) = &self.panel { panel.set_follow_pointer(follow); } + #[cfg(target_os = "windows")] + if let Some(native) = &mut self.native { native.set_follow_pointer(follow); } + #[cfg(all(unix, not(target_os = "macos"), not(target_os = "ios"), not(target_os = "android")))] + if let Some(x11) = &self.x11 { x11.set_follow_pointer(follow); } + } + let options_changed = requests.placement.is_some() || requests.display.is_some(); + #[cfg(all(unix, not(target_os = "macos"), not(target_os = "ios"), not(target_os = "android")))] + let recreate_layer = options_changed && matches!(self.surface.live().map(|l| &l.backing), Some(Backing::Layer(_))); + #[cfg(all(unix, not(target_os = "macos"), not(target_os = "ios"), not(target_os = "android")))] + let layer_was_visible = self.presence.shown(); + #[cfg(all(unix, not(target_os = "macos"), not(target_os = "ios"), not(target_os = "android")))] + if recreate_layer { self.hide(app); } + if let Some(placement) = requests.placement { self.options.placement = placement; } + if let Some(display) = requests.display { self.options.display = display; } + self.apply_wake(app, requests.woken); + let mut at = self.at; + at.edge = requests.edge.unwrap_or(at.edge); + at.margin = requests.margin.unwrap_or(at.margin); + if let Some((align, inset)) = requests.align { + (at.align, at.inset) = (align, inset); + } + let old_size = self.at.size; + if let Some(size) = requests.size { self.canvas_size = size; } + at.size = requests.size.unwrap_or(at.size); + if at != self.at || options_changed { + self.at = at; + self.resolve_size(event_loop); + if self.at.size != old_size { + self.resized(app, event_loop); + } else { + match self.surface.live_mut().map(|l| &mut l.backing) { + Some(Backing::Window(w)) => { + let w = w.clone(); + self.place_window(app.rt_mut(), event_loop, &w); + if let Some(gpu) = self.gpu.clone() { self.rescale(app, &gpu, crate::window::backing_scale(&w)); } + } + #[cfg(all(unix, not(target_os = "macos"), not(target_os = "ios"), not(target_os = "android")))] + Some(Backing::Layer(layer)) => { + layer.place(at); + layer.commit(); + } + #[cfg(all(unix, not(target_os = "macos"), not(target_os = "ios"), not(target_os = "android")))] + Some(Backing::Xwayland(surface)) => surface.place(at, &self.options), + None => {} + } + } + } + if self.options.prewarm && self.shared.availability.load(Ordering::Acquire) == 0 { self.prepare(app, event_loop, false); } + if let Some(level) = requests.macos_level { + self.macos_level = Some(level); + #[cfg(target_os = "macos")] + if let Some(panel) = &self.panel { panel.set_level(level); } + } + match requests.visibility { + Some(Visibility::Show(fade)) => self.show_fading(app, event_loop, fade), + Some(Visibility::Hide(fade)) => self.hide_fading(app, fade), + None => {} + } + #[cfg(all(unix, not(target_os = "macos"), not(target_os = "ios"), not(target_os = "android")))] + if recreate_layer && self.surface.live().is_none() { + if layer_was_visible && !matches!(requests.visibility, Some(Visibility::Hide(_))) { self.show_fading(app, event_loop, Duration::ZERO); } + else if self.options.prewarm { self.prepare(app, event_loop, false); } + } + if requests.refollow && self.presence.shown() && let Some(point) = Self::sample_pointer(event_loop) { + self.refollow(app, event_loop, point); + } + self.apply_input(app.rt()); + if self.presence.shown() { + #[cfg(target_os = "macos")] + if let Some(panel) = &self.panel { self.shared.native.lock().unwrap().1.global_pointer = panel.global_pointer(); } + #[cfg(target_os = "windows")] + if let Some(native) = &self.native { self.shared.native.lock().unwrap().1.global_pointer = native.global_pointer(); } + #[cfg(all(unix, not(target_os = "macos"), not(target_os = "ios"), not(target_os = "android")))] + if let Some(x11) = &self.x11 { self.shared.native.lock().unwrap().1.global_pointer = x11.global_pointer(); } + } + #[cfg(target_os = "macos")] + if requests.request_keys && self.presence.shown() && self.options.keys == KeyPolicy::OnDemand + && let Some(panel) = &self.panel { panel.request_keys(); } + #[cfg(all(unix, not(target_os = "macos"), not(target_os = "ios"), not(target_os = "android")))] + if requests.request_keys && self.presence.shown() && self.options.keys == KeyPolicy::OnDemand + && let Some(Live { backing: Backing::Layer(layer), .. }) = self.surface.live() { layer.request_keys(); } + #[cfg(all(unix, not(target_os = "macos"), not(target_os = "ios"), not(target_os = "android")))] + if requests.request_keys && self.presence.shown() && self.options.keys == KeyPolicy::OnDemand + && let Some(x11) = &self.x11 { x11.request_keys(); } + #[cfg(target_os = "windows")] + if requests.request_keys && self.presence.shown() && self.options.keys == KeyPolicy::OnDemand + && let Some(native) = &self.native { native.request_keys(); } + } +} diff --git a/app/vendor/rune/crates/rune/src/overlay/keys.rs b/app/vendor/rune/crates/rune/src/overlay/keys.rs new file mode 100644 index 0000000..6b9acf9 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/overlay/keys.rs @@ -0,0 +1,26 @@ +//! Keyboard focus for an overlay on a window of its own (X11, Windows), and what the macOS panel +//! and those windows report as `nonactivating_keys`, kept cross-platform so it compiles and runs +//! tests on every host. As with the macOS panel and a layer-shell surface, `KeyPolicy::OnDemand` +//! lets the window take the keys when `OverlayHandle::request_keys` asks or the user clicks it, +//! and showing alone never does; `KeyPolicy::None` never takes them. + +use crate::{KeyPolicy, OverlaySupport}; + +/// Whether an overlay window with `policy` may take keyboard focus. Windows makes one that may +/// without `WS_EX_NOACTIVATE`; X11 gives it the focus on `request_keys` and on a click. +#[cfg_attr(not(any(target_os = "windows", all(unix, not(target_os = "ios"), not(target_os = "android")))), allow(dead_code))] +pub(crate) fn can_take_keys(policy: KeyPolicy) -> bool { + policy == KeyPolicy::OnDemand +} + +/// What an overlay with `policy` reports as `OverlayCapabilities::nonactivating_keys`. +/// `focuser`: the platform piece that focuses it is there (X11's own connection, which a server +/// without the SHAPE extension doesn't get; always there for the macOS panel and on Windows). +#[cfg_attr(not(any(target_os = "windows", all(unix, not(target_os = "ios"), not(target_os = "android")))), allow(dead_code))] +pub(crate) fn keys_support(policy: KeyPolicy, focuser: bool) -> OverlaySupport { + if can_take_keys(policy) && focuser { OverlaySupport::Supported } else { OverlaySupport::Unsupported } +} + +#[cfg(test)] +#[path = "keys_tests.rs"] +mod tests; diff --git a/app/vendor/rune/crates/rune/src/overlay/keys_tests.rs b/app/vendor/rune/crates/rune/src/overlay/keys_tests.rs new file mode 100644 index 0000000..3837acc --- /dev/null +++ b/app/vendor/rune/crates/rune/src/overlay/keys_tests.rs @@ -0,0 +1,26 @@ +use super::{can_take_keys, keys_support}; +use crate::{KeyPolicy, OverlayInput, OverlaySupport}; + +#[test] +fn only_an_on_demand_overlay_window_takes_keys() { + assert!(!can_take_keys(KeyPolicy::None), "never activates, as today"); + assert!(can_take_keys(KeyPolicy::OnDemand)); + assert_eq!(keys_support(KeyPolicy::None, true), OverlaySupport::Unsupported); + assert_eq!(keys_support(KeyPolicy::OnDemand, true), OverlaySupport::Supported); + assert_eq!(keys_support(KeyPolicy::OnDemand, false), OverlaySupport::Unsupported, "no X11 connection to focus it with"); +} + +/// `KeyPolicy` means the same on every backend that can take keys: `OnDemand` may, `None` never +/// does. Only XWayland, whose override-redirect window never takes focus, refuses `OnDemand`. +#[test] +fn key_policy_agrees_across_backends() { + use crate::platform::layer_shell_machine::keyboard::supports_keys as layer; + use crate::overlay::xwayland::xwayland_allowed; + for policy in [KeyPolicy::None, KeyPolicy::OnDemand] { + let wants = policy == KeyPolicy::OnDemand; + assert_eq!(can_take_keys(policy), wants, "X11 and Windows windows, {policy:?}"); + assert_eq!(keys_support(policy, true) == OverlaySupport::Supported, wants, "macOS panel, X11 and Windows windows, {policy:?}"); + assert_eq!(layer(policy, 4, true), wants, "layer-shell, {policy:?}"); + assert_eq!(xwayland_allowed(OverlayInput::None, policy, true), !wants, "XWayland, {policy:?}"); + } +} diff --git a/app/vendor/rune/crates/rune/src/overlay/lifetime.rs b/app/vendor/rune/crates/rune/src/overlay/lifetime.rs new file mode 100644 index 0000000..615a41b --- /dev/null +++ b/app/vendor/rune/crates/rune/src/overlay/lifetime.rs @@ -0,0 +1,394 @@ +//! An overlay's lifetime: making its native window and GPU surface, showing, hiding and +//! fading it, and giving its GPU back while hidden. + +use super::*; + +impl OverlayCore { + pub(super) fn show_fading(&mut self, app: &mut dyn OverlayApp, event_loop: &ActiveEventLoop, fade: Duration) { + if self.presence.shown() { return; } + // Hidden, it missed the redraws a new accent asks for (`accent::watch`). + app.rt_mut().set_system_dark(crate::platform::preferences::dark().unwrap_or(self.dark)); + self.accent_changed(app.rt_mut(), crate::system_accent()); + self.scroll_bars_changed(app.rt_mut(), crate::platform::scroll_bars::current()); + // Shown again mid fade-out: the window is still up with current pixels, and its motion + // carries on rather than settling. + let fading = self.presence.fading(); + let size = self.at.size; + self.resolve_size(event_loop); + if self.surface.live().is_none() { + self.prepare(app, event_loop, true); + if self.shared.failure.lock().unwrap().is_some() { return; } + } + if self.surface.live().is_none() { return; } + self.resume_live(app); + if size != self.at.size { self.resized(app, event_loop); } + if self.surface.live().is_none() { return; } + if !fading { self.settle_before_reveal(app.rt_mut()); } + if let Some(Backing::Window(window)) = self.surface.live().map(|l| &l.backing) { + let window = window.clone(); + self.place_window(app.rt_mut(), event_loop, &window); + if let Some(gpu) = self.gpu.clone() { self.rescale(app, &gpu, crate::window::backing_scale(&window)); } + if self.surface.live().is_none() { return; } + // Retained alpha-zero hosts already have pixels. A hidden update must reach + // the surface before exposing it, rather than flashing the old frame. + if !fading { self.refresh_for_reveal_at(app, crate::time::now()); } + self.show_window(&window, fade); + } + let effects = self.presence.step(presence::Event::Show, self.release); + self.carry_out(app, effects); + self.hidden_pace.reset(); + self.backoff_step(crate::window::BackoffEvent::Revealed); + // Shown onto sleeping displays or under another window, the panel stays occluded. + #[cfg(target_os = "macos")] + { + self.occlusion_read = false; + self.sync_occlusion(app); + if !self.presence.occluded() { self.ensure_pacing(); } + } + if !self.retained() { self.dirty = true; } + self.idle &= !(app.rt().animating || app.compositor_animating()); + } + + /// Makes the overlay's native window and GPU surface: at startup for a prewarmed overlay + /// (`showing` false), or for the show. A prewarmed `release_gpu_when_hidden` overlay makes + /// only its window at startup and parks it; its surface, and the GPU device for the first, + /// wait for the show. + pub(super) fn prepare(&mut self, app: &mut dyn OverlayApp, event_loop: &ActiveEventLoop, showing: bool) { + if self.surface.live().is_some() { return; } + let surface = showing || !self.defers_gpu(); + let wayland = crate::window::is_wayland(event_loop); + // Only an X11 window waits parked for its surface. A Wayland overlay's window is its + // surface, and a Windows or macOS one that gives its GPU back is made for each show + // (`park`): both wait. + let parks = cfg!(all(unix, not(target_os = "macos"), not(target_os = "ios"), not(target_os = "android"))) && !wayland; + if !surface && !parks { return; } + self.resolve_size(event_loop); + let made = if wayland { + self.layer(app, event_loop).or_else(|| self.xwayland(app)) + } else if self.surface.parked().is_some() || self.window(app, event_loop).is_some() { + // macOS made the surface with its panel; elsewhere the window waits parked. + match self.surface.take_live() { + Some(live) => Some(live), + None if surface => self.unpark(app), + None => return self.ready(app, showing), + } + } else { + None + }; + match made { + Some(live) => { + self.surface.made(live); + // An earlier attempt's failure no longer holds. + self.shared.failure.lock().unwrap().take(); + // The surface was made before the panel was adopted and placed; its display's + // scale is known now, before `warm` draws. + if let Some(Backing::Window(window)) = self.surface.live().map(|l| &l.backing) && let Some(gpu) = self.gpu.clone() { + let scale = crate::window::backing_scale(window); + self.rescale(app, &gpu, scale); + if self.shared.failure.lock().unwrap().is_some() { return; } + } + self.ready(app, showing); + } + None => if self.shared.failure.lock().unwrap().is_none() { + self.fail("the platform could not create its window or surface".into()); + } else { + self.set_availability(Availability::Unavailable); + }, + } + } + + /// The window exists, with its surface or parked: the overlay can show. A prewarmed one + /// warms what it has (parked, only the view); one that makes its surface for each show + /// draws its own first frame instead. + pub(super) fn ready(&mut self, app: &mut dyn OverlayApp, showing: bool) { + self.set_availability(Availability::Available); + if !self.animate_reveal { app.rt_mut().settle_all(); } + self.dirty = true; + self.idle = true; + if self.options.prewarm && !(showing && self.defers_gpu()) { self.warm(app); } + if !self.surface.announced() && let Some(created) = &mut self.on_created { + self.surface.announce(); + let (window_number, capabilities) = *self.shared.native.lock().unwrap(); + created(crate::OverlayCreated { window_number, capabilities }); + } + } + + // A retained host can be prepared while hidden. Resume sampling before warm/reveal so + // hidden publications reach that first visible frame, without waking hidden hosts. + pub(super) fn resume_live(&mut self, app: &mut dyn OverlayApp) { + app.set_live_visible(true); + if app.rt().live_pending() { self.dirty = true; } + } + + pub(super) fn settle_before_reveal(&mut self, rt: &mut RuntimeCore) { + // Initial retained pixels were settled by warm(). Leaving a settle flag pending here + // would snap changes arriving after that frame, in the same turn as show(). + if !self.retained() && !self.animate_reveal { rt.settle_all(); } + } + + /// macOS keeps a prewarmed host's alpha-zero surface, and its pixels, while hidden, unless + /// it gives its GPU back. + pub(super) fn retained(&self) -> bool { cfg!(target_os = "macos") && self.options.prewarm && !self.defers_gpu() } + + pub(super) fn refresh_for_reveal_at(&mut self, app: &mut dyn OverlayApp, now: Instant) { + if self.retained() && (self.dirty || app.rt().animating) { + self.commit_at(app, now); + self.warm_frame(app); + } + } + + pub(super) fn hide(&mut self, app: &mut dyn OverlayApp) { self.hide_fading(app, Duration::ZERO) } + + pub(super) fn hide_fading(&mut self, app: &mut dyn OverlayApp, fade: Duration) { + // Any Fn change the monitor saw reaches the view while it's still shown; the hide + // then releases what it held. + #[cfg(target_os = "macos")] + self.fn_key(app); + // Only macOS and Windows fade the window; elsewhere it goes at once, and so does drawing. + let fade = if cfg!(any(target_os = "macos", target_os = "windows")) { fade } else { Duration::ZERO }; + let effects = self.presence.step(presence::Event::Hide { fade, now: crate::time::now() }, self.release); + self.carry_out(app, effects); + } + + /// A fade-out's end, or a hidden surface's release, may be due. Ending the fade finishes + /// native hiding too: AppKit's completion may stall while displays sleep. On Windows, steps + /// a fading window's alpha until then. + pub(super) fn presence_due(&mut self, app: &mut dyn OverlayApp, now: Instant) { + let effects = self.presence.step(presence::Event::Due { now }, self.release); + self.carry_out(app, effects); + #[cfg(target_os = "windows")] + if let Presence::FadingOut { until, length, .. } = self.presence && let Some(native) = &self.native { + native.fade(fade_alpha(until, length, now)); + } + } + + pub(super) fn carry_out(&mut self, app: &mut dyn OverlayApp, effects: crate::machine::Effects<presence::Effect>) { + for effect in effects { + match effect { + presence::Effect::StopDrawing => self.stop_drawing(app), + presence::Effect::HideWindow { fade } => self.hide_window(app, fade), + presence::Effect::ReleaseGpu => self.park(), + } + } + } + + /// A hidden overlay draws nothing more: its display link, timer frames and live values stop. + fn stop_drawing(&mut self, app: &mut dyn OverlayApp) { + #[cfg(target_os = "macos")] + if let Some(live) = self.surface.live_mut() && let Some(pacing) = &mut live.pacing { pacing.stop(); } + app.set_live_visible(false); + self.backoff_step(crate::window::BackoffEvent::Lapsed); + self.quiet.step(frame::QuietEvent::Forget); + } + + /// Input stops, and the native window hides over `fade`. A fading window stays up while + /// `presence_due` steps its alpha (Windows), then hides it. + fn hide_window(&mut self, app: &mut dyn OverlayApp, fade: Duration) { + // A hide need not report a blur, and a hidden overlay hears none: what it held is + // released. + if self.options.keys == KeyPolicy::OnDemand { app.rt_mut().keys_lost(); } + self.mods = Default::default(); + self.control_click = false; + self.ime_allowed = false; + app.popup_cancel(&mut self.popup); + app.rt_mut().cancel_pointer(); + self.apply_cursor(app.rt()); + self.hidden_input(app); + let Some(live) = self.surface.live() else { return }; + match &live.backing { + Backing::Window(window) => { + if self.options.keys == KeyPolicy::OnDemand { + crate::platform::ime::cancel(window); + window.set_ime_allowed(false); + } + #[cfg(all(unix, not(target_os = "macos"), not(target_os = "ios"), not(target_os = "android")))] + if let Some(x11) = &self.x11 { x11.hide(); } + #[cfg(target_os = "windows")] + { + let _ = (window, fade); + if let Some(native) = &mut self.native { + if self.presence.fading() { native.fade(255) } else { native.hide() } + } + } + #[cfg(target_os = "macos")] + if let Some(panel) = &self.panel { + panel.hide(fade); + } + #[cfg(not(any(target_os = "macos", target_os = "windows")))] + let _ = fade; + #[cfg(not(target_os = "windows"))] + window.set_visible(false); + } + #[cfg(all(unix, not(target_os = "macos"), not(target_os = "ios"), not(target_os = "android")))] + Backing::Layer(_) | Backing::Xwayland(_) => { self.surface.take_live(); } + } + } + + #[cfg(all(unix, not(target_os = "macos"), not(target_os = "ios"), not(target_os = "android")))] + pub(super) fn layer(&mut self, app: &mut dyn OverlayApp, event_loop: &ActiveEventLoop) -> Option<Live> { + use winit::raw_window_handle::HasDisplayHandle; + use winit::platform::wayland::MonitorHandleExtWayland; + let display = event_loop.display_handle().ok()?.as_raw(); + let monitor = monitor(event_loop, &self.options.display); + let scale = monitor.as_ref().map_or(1.0, |m| m.scale_factor()).ceil() as i32; + // With no target, the compositor chooses an output; global pointer querying is forbidden. + let output = match &self.options.display { + DisplayTarget::Id(id) if event_loop.available_monitors().any(|m| m == id.0) => Some(id.0.native_id()), + DisplayTarget::Native(crate::NativeDisplayId::Wayland(id)) if event_loop.available_monitors().any(|m| m.native_id() == *id) => Some(*id), + _ => None, + }; + let wake = self.shared.wake.lock().unwrap().clone(); + let mut layer = crate::platform::layer_shell::LayerSurface::new(display, self.name, self.at, self.interactive, &self.options, output, wake)?; + layer.set_buffer_scale(scale); + if let Some((w, h)) = layer.configured_size() { + if w > 0 { self.at.size.0 = w as f32; } + if h > 0 { self.at.size.1 = h as f32; } + } + self.shared.native.lock().unwrap().1 = crate::OverlayCapabilities { + capture_exclusion: OverlaySupport::Unsupported, global_pointer: OverlaySupport::Unsupported, + nonactivating_keys: if layer.supports_keys() { OverlaySupport::Supported } else { OverlaySupport::Unsupported }, + }; + self.attach(app, Backing::Layer(layer), scale as f32) + } + + #[cfg(not(all(unix, not(target_os = "macos"), not(target_os = "ios"), not(target_os = "android"))))] + pub(super) fn layer(&mut self, _app: &mut dyn OverlayApp, _event_loop: &ActiveEventLoop) -> Option<Live> { + None + } + + /// Makes the native window: on macOS with its GPU surface (`live`), which binds winit's view + /// before the view moves into the panel; elsewhere without one (`parked`). + pub(super) fn window(&mut self, app: &mut dyn OverlayApp, event_loop: &ActiveEventLoop) -> Option<()> { + let mut attrs = Window::default_attributes() + .with_title(self.name) + .with_inner_size(LogicalSize::new(self.at.size.0 as f64, self.at.size.1 as f64)) + .with_decorations(false) + .with_resizable(false) + .with_transparent(true) + .with_active(false) + .with_visible(false) + .with_window_level(WindowLevel::AlwaysOnTop); + if let Some(p) = position(event_loop, self.at, &self.options) { + attrs = attrs.with_position(p); + } + #[cfg(all(unix, not(target_os = "macos"), not(target_os = "ios"), not(target_os = "android")))] + { + use winit::platform::x11::{WindowAttributesExtX11, WindowType}; + attrs = attrs.with_override_redirect(true).with_x11_window_type(vec![WindowType::Notification]); + if let Some(id) = crate::tooling::app_id() { + attrs = attrs.with_name(id, id); + } + } + #[cfg(target_os = "windows")] + { + use winit::platform::windows::WindowAttributesExtWindows; + // DirectComposition draws the overlay (`Gpu::instance`); without a redirection bitmap + // nothing under it paints the window black. + attrs = attrs.with_skip_taskbar(true).with_undecorated_shadow(false).with_no_redirection_bitmap(true); + } + #[cfg(target_os = "macos")] + { + use winit::platform::macos::WindowAttributesExtMacOS; + attrs = attrs.with_has_shadow(false); + } + let window = match event_loop.create_window(attrs) { + Ok(window) => Arc::new(window), + Err(error) => { + self.fail(format!("could not create its window: {error}")); + return None; + } + }; + #[cfg(target_os = "macos")] + crate::native_menu::adopt_standard_view(); + self.dark = window.theme().map_or_else(|| crate::platform::preferences::desktop_dark(&window).unwrap_or(true), |t| t == winit::window::Theme::Dark); + app.rt_mut().set_system_dark(self.dark); + if self.cursor.is_none() { self.cursor = Some(crate::cursor::os::OsCursor::new()); } + // The surface first: on macOS it binds winit's view and its layer, which then move + // into the panel. + #[cfg(target_os = "macos")] + let live = self.attach(app, Backing::Window(window.clone()), crate::window::backing_scale(&window))?; + #[cfg(target_os = "macos")] + { + let wake = self.shared.wake.lock().unwrap().clone(); + self.panel = Some(crate::platform::macos::Panel::adopt(&window, self.at, self.interactive, &self.options, wake)?); + let panel = self.panel.as_ref().unwrap(); + if let Some(level) = self.macos_level { panel.set_level(level); } + let native = (Some(panel.window_number()), crate::OverlayCapabilities { + capture_exclusion: panel.capture_exclusion(), nonactivating_keys: super::keys::keys_support(self.options.keys, true), global_pointer: OverlaySupport::Supported, + }); + *self.shared.native.lock().unwrap() = native; + } + #[cfg(not(target_os = "macos"))] + { + window.set_cursor_hittest(self.options.input.resolved(self.interactive) == OverlayInput::All).ok(); + #[cfg(all(unix, not(target_os = "ios"), not(target_os = "android")))] + { + self.x11 = crate::platform::x11::overlay::InputWindow::new(&window, self.shared.wake.lock().unwrap().clone(), self.options.input.resolved(self.interactive), self.options.follow_pointer, self.options.keys); + if self.options.input == OverlayInput::Regions && self.x11.is_none() { return None; } + self.shared.native.lock().unwrap().1 = crate::OverlayCapabilities { + capture_exclusion: OverlaySupport::Unsupported, nonactivating_keys: super::keys::keys_support(self.options.keys, self.x11.is_some()), global_pointer: OverlaySupport::Supported, + }; + } + #[cfg(target_os = "windows")] + { + let wake = self.shared.wake.lock().unwrap().clone(); + match crate::platform::win32::OverlayWindow::new(&window, self.interactive, &self.options, wake) { + Ok(native) => self.native = Some(native), + Err(error) => { + self.fail(error); + return None; + } + } + self.shared.native.lock().unwrap().1 = crate::OverlayCapabilities { + capture_exclusion: self.native.as_ref().unwrap().capture_exclusion(), nonactivating_keys: super::keys::keys_support(self.options.keys, true), global_pointer: OverlaySupport::Supported, + }; + } + } + self.place_window(app.rt_mut(), event_loop, &window); + #[cfg(target_os = "macos")] + self.surface.made(live); + #[cfg(not(target_os = "macos"))] + self.surface.park(Backing::Window(window)); + Some(()) + } + + /// The parked window's GPU surface, and the device for the first surface. Failing, the + /// window stays parked for the next show to try again. + pub(super) fn unpark(&mut self, app: &mut dyn OverlayApp) -> Option<Live> { + let Some(Backing::Window(window)) = self.surface.take_parked() else { return None }; + let live = self.attach(app, Backing::Window(window.clone()), crate::window::backing_scale(&window)); + if live.is_none() { self.surface.park(Backing::Window(window)); } + live + } + + /// `release_gpu_when_hidden` or `release_gpu_after` (see `Release::new`). + pub(super) fn defers_gpu(&self) -> bool { self.release != Release::Keep } + + /// `release_gpu_when_hidden`: the hidden overlay gives back its surface, swapchain and + /// renderer, and its hold on the GPU device, which waits a while for the next surface + /// (`render::park_gpu`) once no other surface draws with it. The + /// window stays parked on X11 only. On Windows a hidden topmost window, often + /// display-sized, in a process that draws with DXGI is enough for game capture tools such + /// as NVIDIA's Instant Replay to take the app for the running game; on macOS 27 hidden + /// screen-sized panels that join every Space empty Mission Control's Space thumbnails. + /// There the window goes too, and the next show makes a new one. + pub(super) fn park(&mut self) { + if !matches!(self.surface.live().map(|l| &l.backing), Some(Backing::Window(_))) { return; } + #[cfg(any(target_os = "windows", target_os = "macos"))] + self.release(); + #[cfg(not(any(target_os = "windows", target_os = "macos")))] + { + let Some(Live { alpha, surface, backing, .. }) = self.surface.take_live() else { return }; + // The surface goes before the device that made it and the window it draws into. + drop(alpha); + drop(surface); + self.surface.park(backing); + } + // The device goes to the next surface rather than with this one; one another + // surface still draws with stays there. + if let (Some(gpu), Some(renderer)) = (self.gpu.take(), self.renderer.take()) && let Ok(gpu) = Arc::try_unwrap(gpu) { + crate::render::park_gpu(gpu, renderer); + } + *self.shared.surface.lock().unwrap() = None; + } +} diff --git a/app/vendor/rune/crates/rune/src/overlay/lost_release_tests.rs b/app/vendor/rune/crates/rune/src/overlay/lost_release_tests.rs new file mode 100644 index 0000000..bb30067 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/overlay/lost_release_tests.rs @@ -0,0 +1,436 @@ +//! Drives every short sequence of native and winit pointer events through the overlay host and +//! the panel's `Hold`, and checks what the runtime's drags hear against a reference. +//! +//! The reference sees only the inputs. It keeps its own clock and history, predicts each letter's +//! callbacks, capture and deadline before production runs it, and production's answers are +//! compared with those predictions. Each point carries the press it belongs to, so the +//! invariants can name a position reaching an earlier press. +//! +//! winit can only dispatch a click the monitor saw, in order; a Down the panel gave up on never +//! arrives, but an Up may still arrive late. A press the monitor never saw is out of scope, and +//! the reference expects a winit move during the grace to reach the drag, as it always has. + +use super::*; +use crate::platform::macos::PointerState; +use std::collections::{BTreeMap, VecDeque}; +use std::sync::atomic::AtomicUsize; + +type Point = (f32, f32); + +const LENGTH: usize = 6; +const SLOP: f32 = 4.0; +const UNSEEN_UP_GRACE: Duration = Duration::from_millis(100); +const QUEUED_UP_GRACE: Duration = Duration::from_secs(2); + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Letter { SeenDown, SeenUp, ReadUp, ReadDown, CursorMoved, MouseDown, MouseUp, Turn, Grace, Occlude, ViewLost } + +const ALPHABET: [Letter; 11] = [Letter::SeenDown, Letter::SeenUp, Letter::ReadUp, Letter::ReadDown, Letter::CursorMoved, + Letter::MouseDown, Letter::MouseUp, Letter::Turn, Letter::Grace, Letter::Occlude, Letter::ViewLost]; + +/// Whether presses, and readings and moves, land within the click slop of the last or far off. +#[derive(Clone, Copy, Debug)] +struct Plan { far_presses: bool, far_readings: bool } + +const PLANS: [Plan; 3] = [Plan { far_presses: false, far_readings: false }, Plan { far_presses: false, far_readings: true }, Plan { far_presses: true, far_readings: true }]; + +/// Unique per event: `y` stays inside the slop and names the event. +fn point(index: usize, far: bool) -> Point { + (if far { 100.0 + 30.0 * index as f32 } else { 10.0 }, 10.0 + 0.125 * index as f32) +} + +fn event_of(point: Point) -> usize { ((point.1 - 10.0) / 0.125).round() as usize } + +fn within_slop(a: Point, b: Point) -> bool { (a.0 - b.0).abs() <= SLOP && (a.1 - b.1).abs() <= SLOP } + +/// What a drag's handlers hear. +#[derive(Clone, Copy, Debug, PartialEq)] +enum Heard { Down(Point, u32), Move(Point), Up(Point), Cancel(Point), Press } + +#[derive(Clone, Copy)] +struct Queued { down: bool, at: Point, press: usize, /// The panel gave up on it, so it arrives with no point. + forgotten: bool, /// A Down whose press before it never got its Up. + owes: bool } + +/// The runtime's held drag, as predicted. +#[derive(Clone, Copy)] +struct Predicted { press: usize, down: Point, moved: bool } + +/// What one letter is, for the driver to play and the invariants to read. +struct Played { at: Option<Point>, reading: Option<(usize, Point, Duration)>, dispatched: Option<Queued>, expect: Vec<Heard> } + +struct Reference { + plan: Plan, + clock: Duration, + queue: VecDeque<Queued>, + seen: usize, + /// The press each event's point belongs to. + owner: Vec<usize>, + /// By press: its own Up, where the button first read up, where it was last read down. + ups: Vec<Option<Point>>, + rose: Vec<Option<Point>>, + latest: Vec<Point>, + buttons: usize, + at: Point, + /// The button read up then down with no Down seen: readings belong to the next press. + next_press_under_way: bool, + last_read: Option<Point>, + pending: Option<Point>, + holding: bool, + /// When the button read up, while a press is held. + rising: Option<Duration>, + rebounded: bool, + /// A release was given up on and the runtime hasn't heard. + owed: bool, + given_up: usize, + occluded: bool, + drag: Option<Predicted>, + runtime_at: Point, + /// The run of clicks: its last press and count. + run: Option<(Point, u32)>, + // The invariants' own view of what was heard. + open: Option<Predicted>, + last_press: Option<(Point, bool, u32)>, +} + +enum Outcome { Illegal, Passed, Failed(&'static str, String) } + +impl Reference { + fn new(plan: Plan, runtime_at: Point) -> Self { + Self { plan, clock: Duration::ZERO, queue: VecDeque::new(), seen: 0, owner: vec![0], ups: vec![None], rose: vec![None], latest: vec![point(0, false)], + buttons: 0, at: point(0, false), next_press_under_way: false, last_read: None, pending: None, holding: false, rising: None, rebounded: false, + owed: false, given_up: 0, occluded: false, drag: None, runtime_at, run: None, open: None, last_press: None } + } + + fn event(&mut self, far: bool, owner: usize) -> Point { + let index = self.owner.len(); + self.owner.push(owner); + point(index, far) + } + + fn reading_owner(&self) -> usize { self.seen + usize::from(self.next_press_under_way) } + + fn live(&self) -> impl DoubleEndedIterator<Item = &Queued> { self.queue.iter().filter(|click| !click.forgotten) } + + fn deadline(&self) -> Option<Duration> { + let since = self.rising.filter(|_| self.holding)?; + Some(since + if self.live().any(|click| !click.down) { QUEUED_UP_GRACE } else { UNSEEN_UP_GRACE }) + } + + /// One sample of the current button and point. + fn read(&mut self) -> (usize, Point, Duration) { + if self.holding { + if self.buttons != 0 { + if self.rising.take().is_some() { self.rebounded = true; } else if !self.rebounded { self.latest[self.seen] = self.at; } + } else if self.rising.is_none() { + self.rising = Some(self.clock); + self.rebounded = false; + if self.rose[self.seen].is_none() { self.rose[self.seen] = Some(self.at); } + } else if self.deadline().is_some_and(|due| self.clock >= due) { + self.give_up(); + for click in &mut self.queue { click.forgotten = true; } + self.queue.retain(|click| !click.down); + } + } + if self.last_read != Some(self.at) { + self.last_read = Some(self.at); + self.pending = Some(self.at); + } + (self.buttons, self.at, self.clock) + } + + fn give_up(&mut self) { + self.holding = false; + self.rising = None; + self.rebounded = false; + self.given_up = self.seen; + self.owed |= self.drag.is_some(); + } + + /// Where a press that lost its release let go. + fn expected_cancel(&self, press: usize) -> Point { + self.ups[press].or(self.rose[press]).unwrap_or(self.latest[press]) + } + + fn land_lost(&mut self, expect: &mut Vec<Heard>) { + if !std::mem::take(&mut self.owed) { return; } + let Some(drag) = self.drag.take() else { return }; + let at = self.expected_cancel(drag.press); + expect.push(Heard::Cancel(at)); + if drag.moved || !within_slop(drag.down, at) { self.run = None; } + self.runtime_at = at; + } + + fn before_position(&mut self, expect: &mut Vec<Heard>) { + if let Some(front) = self.queue.iter_mut().find(|click| !click.forgotten) && std::mem::take(&mut front.owes) { self.owed = true; } + self.land_lost(expect); + } + + fn position(&mut self, at: Point, expect: &mut Vec<Heard>) { + if self.runtime_at == at { return; } + self.runtime_at = at; + if let Some(drag) = &mut self.drag { + expect.push(Heard::Move(at)); + drag.moved |= !within_slop(drag.down, at); + } + } + + /// Predicts one letter. `None` when winit couldn't have delivered it. + fn play(&mut self, letter: Letter) -> Option<Played> { + let (mut at, mut reading, mut dispatched, mut expect) = (None, None, None, Vec::new()); + match letter { + Letter::SeenDown => { + let owes = self.holding && self.live().next_back().is_none_or(|click| click.down); + self.seen += 1; + self.next_press_under_way = false; + let point = self.event(self.plan.far_presses, self.seen); + self.ups.push(None); + self.rose.push(None); + self.latest.push(point); + self.queue.push_back(Queued { down: true, at: point, press: self.seen, forgotten: false, owes }); + self.holding = true; + self.rising = None; + self.rebounded = false; + (self.buttons, self.at, at) = (1, point, Some(point)); + } + Letter::SeenUp => { + let point = self.event(self.plan.far_readings, self.seen); + if self.ups[self.seen].is_none() && self.seen > self.given_up { self.ups[self.seen] = Some(point); } + self.queue.push_back(Queued { down: false, at: point, press: self.seen, forgotten: false, owes: false }); + (self.buttons, self.at, at) = (0, point, Some(point)); + } + Letter::ReadUp => { + self.at = self.event(self.plan.far_readings, self.reading_owner()); + self.buttons = 0; + reading = Some(self.read()); + } + Letter::ReadDown => { + if self.buttons == 0 && self.seen > 0 { self.next_press_under_way = true; } + self.at = self.event(self.plan.far_readings, self.reading_owner()); + self.buttons = 1; + reading = Some(self.read()); + } + Letter::CursorMoved => { + // winit reports a click's position just before the click. + let point = match self.queue.front() { Some(click) => click.at, None => self.event(self.plan.far_readings, self.seen) }; + self.before_position(&mut expect); + self.position(point, &mut expect); + at = Some(point); + } + Letter::MouseDown => { + let click = self.queue.pop_front().filter(|click| click.down); + let Some(click) = click else { return None }; + self.owed |= click.owes; + self.land_lost(&mut expect); + let clicks = match self.run { Some((was, count)) if within_slop(was, click.at) => count + 1, _ => 1 }; + self.run = Some((click.at, clicks)); + self.runtime_at = click.at; + self.drag = Some(Predicted { press: click.press, down: click.at, moved: false }); + expect.push(Heard::Down(click.at, clicks)); + dispatched = Some(click); + } + Letter::MouseUp => { + if !self.queue.front().is_some_and(|click| !click.down) { return None; } + let click = self.queue.pop_front()?; + self.land_lost(&mut expect); + let released = if click.forgotten { self.runtime_at } else { click.at }; + self.position(released, &mut expect); + if let Some(drag) = self.drag.take() { + expect.extend([Heard::Up(released), Heard::Press]); + if drag.moved { self.run = None; } + } + let holding = self.live().any(|click| click.down); + self.holding = holding; + if !holding { (self.rising, self.rebounded) = (None, false); } + reading = Some(self.read()); + dispatched = Some(click); + } + Letter::Turn => { + reading = Some(self.read()); + self.before_position(&mut expect); + let ahead = self.holding && (self.rising.is_some() || self.rebounded || self.live().next().is_some()); + if !ahead && let Some(point) = self.pending.take() { self.position(point, &mut expect); } + } + Letter::Grace => if let Some(due) = self.deadline() { + self.clock = due; + reading = Some(self.read()); + }, + Letter::Occlude => self.occluded = !self.occluded, + Letter::ViewLost => { + // With nothing newer read, the held press ends where it was last known. + self.give_up(); + self.queue.clear(); + } + } + Some(Played { at, reading, dispatched, expect }) + } + + /// The invariants, on what one letter made the runtime hear. + fn check(&mut self, letter: Letter, dispatched: Option<Queued>, heard: &[Heard]) -> Result<(), (&'static str, String)> { + let mut dropped = false; + for item in heard { + let (at, up) = match *item { + Heard::Press => { + if !std::mem::take(&mut dropped) { return Err(("no-drop-after-cancel", "a press fired without a normal release".into())); } + continue; + } + Heard::Down(down, clicks) => { + dropped = false; + if self.open.is_some() { return Err(("ends-exactly-once", "a press replaced a drag that hadn't ended".into())); } + let Some(click) = dispatched.filter(|click| click.down && letter == Letter::MouseDown) else { + return Err(("ends-exactly-once", "a drag began without a dispatched press".into())); + }; + if down != click.at { return Err(("own-point", format!("press at {:?} began at {down:?}", click.at))); } + let want = match self.last_press { Some((was, false, count)) if within_slop(was, down) => count + 1, _ => 1 }; + if clicks != want { return Err(("click-counts", format!("{clicks} clicks, reference {want}"))); } + self.last_press = Some((down, false, clicks)); + self.open = Some(Predicted { press: click.press, down, moved: false }); + continue; + } + Heard::Move(at) => (at, false), + Heard::Up(at) | Heard::Cancel(at) => (at, true), + }; + dropped = false; + let Some(open) = &mut self.open else { return Err(("ends-exactly-once", format!("{item:?} on a drag already ended"))); }; + let owner = self.owner[event_of(at)]; + if owner > open.press { return Err(("no-later-press-position", format!("press {} heard {item:?}, from press {owner}", open.press))); } + open.moved |= !within_slop(open.down, at); + let (press, moved) = (open.press, open.moved); + if let Some(last) = &mut self.last_press { last.1 = moved; } + if !up { continue; } + if matches!(item, Heard::Cancel(_)) { + let want = self.expected_cancel(press); + if at != want { return Err(("own-point", format!("press {press} cancelled at {at:?}, reference {want:?}"))); } + } else { + let own = dispatched.is_some_and(|click| !click.down && click.press == press) && letter == Letter::MouseUp; + if !own || press <= self.given_up { return Err(("no-drop-after-cancel", format!("press {press} ended normally after losing its release"))); } + dropped = true; + } + self.open = None; + } + Ok(()) + } +} + +fn overlay() -> Overlay<u32> { + fn view(_: &u32, _: &mut Cx<u32>) -> El { + crate::el().w_full().h_full().hit().on_drag(|_: &mut u32, _, _| {}).on_press(|_: &mut u32| {}) + } + let app = AppSpec { + title: "sequences", size: (1000.0, 100.0), min_size: None, init: || 0, view, + scenes: &[], fonts: &[], families: ("sans-serif", "monospace"), setup: None, poll: None, on_key: None, + }; + let spec = OverlaySpec::new("sequences", app.size, view).options(OverlayOptions { input: OverlayInput::All, ..Default::default() }); + let (mut overlay, _) = Overlay::new(spec, 0, &app); + overlay.rt.frame(0.0); + overlay +} + +/// Plays a letter on production: the only place the test touches it. +fn drive(overlay: &mut Overlay<u32>, pointer: &PointerState, letter: Letter, played: &Played, base: Instant) -> Vec<Heard> { + let read = |pointer: &PointerState| if let Some((buttons, at, clock)) = played.reading { pointer.read(buttons, base + clock, at, true, false); }; + let at = played.at.unwrap_or_default(); + match letter { + Letter::SeenDown => pointer.record_click(true, at.0, at.1), + Letter::SeenUp => pointer.record_click(false, at.0, at.1), + Letter::ReadUp | Letter::ReadDown | Letter::Grace => read(pointer), + Letter::CursorMoved => overlay.native_moved(pointer, at.0, at.1), + Letter::MouseDown => overlay.native_left(pointer, true), + Letter::MouseUp => { + overlay.native_left(pointer, false); + pointer.released(); + read(pointer); + } + Letter::Turn => { + read(pointer); + if let Some((x, y)) = overlay.turn_position(pointer) && overlay.rt.pointer() != Some((x, y)) { overlay.observe_pointer(x, y); } + } + Letter::Occlude => {} + Letter::ViewLost => pointer.view_lost(), + } + overlay.rt.take_queued_pointer().into_iter().map(|item| match item { + None => Heard::Press, + Some(drag) => { + let at = (drag.window[0], drag.window[1]); + match drag.phase { + crate::Phase::Down => Heard::Down(at, drag.clicks), + crate::Phase::Up if drag.cancelled() => Heard::Cancel(at), + crate::Phase::Up => Heard::Up(at), + _ => Heard::Move(at), + } + } + }).collect() +} + +fn run(overlay: &mut Overlay<u32>, plan: Plan, sequence: &[Letter]) -> Outcome { + let start = (5.0, 5.0); + overlay.rt.cancel_pointer(); + overlay.rt.end_click_run(); + overlay.rt.pointer_move(start.0, start.1); + overlay.rt.take_queued_pointer(); + let pointer = PointerState::new(OverlayInput::All, false); + let base = crate::time::now(); + let mut model = Reference::new(plan, start); + let (buttons, at, clock) = model.read(); + pointer.read(buttons, base + clock, at, true, false); + // Then the button comes to rest and the grace runs out, however the sequence left things. + for &letter in sequence.iter().chain(&[Letter::ReadUp, Letter::Grace, Letter::Turn]) { + let Some(played) = model.play(letter) else { return Outcome::Illegal }; + let heard = drive(overlay, &pointer, letter, &played, base); + if let Err((invariant, why)) = model.check(letter, played.dispatched, &heard) { return Outcome::Failed(invariant, why); } + if heard != played.expect { return Outcome::Failed("predicted-callbacks", format!("after {letter:?} heard {heard:?}, predicted {:?}", played.expect)); } + if pointer.captured() != model.holding { return Outcome::Failed("predicted-capture", format!("after {letter:?} captured {}, predicted {}", pointer.captured(), model.holding)); } + let (deadline, predicted) = (pointer.deadline(None, model.occluded), model.deadline().map(|due| base + due)); + if deadline != predicted { return Outcome::Failed("predicted-deadline", format!("after {letter:?} {deadline:?}, predicted {predicted:?}")); } + } + if model.open.is_some() || model.drag.is_some() { return Outcome::Failed("ends-exactly-once", "the drag never ended".into()); } + Outcome::Passed +} + +#[derive(Default)] +struct Tally { ran: usize, failures: BTreeMap<&'static str, (usize, String)> } + +fn visit(overlay: &mut Overlay<u32>, plan: Plan, sequence: &mut Vec<Letter>, tally: &mut Tally) { + match run(overlay, plan, sequence) { + Outcome::Illegal => return, + Outcome::Passed => tally.ran += 1, + Outcome::Failed(invariant, why) => { + tally.ran += 1; + let entry = tally.failures.entry(invariant).or_insert_with(|| (0, format!("{plan:?} {sequence:?}: {why}"))); + entry.0 += 1; + } + } + if sequence.len() == LENGTH { return; } + for letter in ALPHABET { + sequence.push(letter); + visit(overlay, plan, sequence, tally); + sequence.pop(); + } +} + +#[test] +fn every_short_sequence_of_pointer_events_keeps_the_drag_invariants() { + let jobs: Vec<(Plan, Letter)> = PLANS.iter().flat_map(|plan| ALPHABET.iter().map(|letter| (*plan, *letter))).collect(); + let next = AtomicUsize::new(0); + let total = Mutex::new(Tally::default()); + let workers = std::thread::available_parallelism().map_or(4, |n| n.get()).min(8); + std::thread::scope(|scope| for _ in 0..workers { + scope.spawn(|| { + let mut overlay = overlay(); + let mut tally = Tally::default(); + while let Some((plan, letter)) = jobs.get(next.fetch_add(1, Ordering::Relaxed)) { + visit(&mut overlay, *plan, &mut vec![*letter], &mut tally); + } + let mut total = total.lock().unwrap(); + total.ran += tally.ran; + for (invariant, (count, first)) in tally.failures { + let entry = total.failures.entry(invariant).or_insert((0, first)); + entry.0 += count; + } + }); + }); + let total = total.into_inner().unwrap(); + println!("{} sequences up to length {LENGTH}", total.ran); + assert!(total.ran > 100_000, "only {} sequences were legal", total.ran); + assert!(total.failures.is_empty(), "{} sequences, failures: {:#?}", total.ran, total.failures); +} diff --git a/app/vendor/rune/crates/rune/src/overlay/more_tests.rs b/app/vendor/rune/crates/rune/src/overlay/more_tests.rs new file mode 100644 index 0000000..26f0a06 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/overlay/more_tests.rs @@ -0,0 +1,967 @@ +#[test] +fn overlay_pixels_wake_only_while_shown_and_catch_up_on_show() { + use std::sync::atomic::AtomicUsize; + fn init() -> crate::Pixels { crate::Pixels::new() } + fn view(pixels: &crate::Pixels, _: &mut Cx<crate::Pixels>) -> El { + crate::el().size(4.0, 4.0).pixels(pixels) + } + let app = AppSpec::new("pixels overlay", (4.0, 4.0), init, view); + let spec = OverlaySpec::new("pixels overlay", app.size, view).options(OverlayOptions { + prewarm: true, keys: KeyPolicy::OnDemand, ..Default::default() + }); + let pixels = init(); + let (mut overlay, _) = Overlay::new(spec, pixels.clone(), &app); + let wakes = Arc::new(AtomicUsize::new(0)); + let count = wakes.clone(); + overlay.rt.set_live_waker(Arc::new(move || { count.fetch_add(1, Ordering::Relaxed); })); + overlay.rt.frame(0.0); + overlay.dirty = false; + overlay.resume_live(); + assert!(!overlay.dirty, "the warmed frame already drew the image"); + overlay.rt.set_live_visible(false); + pixels.set(1, 1, vec![255; 4]); + assert_eq!(wakes.load(Ordering::Relaxed), 0, "a hidden overlay isn't woken"); + overlay.dirty = false; + overlay.resume_live(); + assert!(overlay.dirty, "showing draws the image set while hidden"); + assert_eq!(wakes.load(Ordering::Relaxed), 1); + overlay.rt.frame(0.0); + pixels.set(1, 1, vec![0; 4]); + pixels.set(1, 1, vec![1; 4]); + assert_eq!(wakes.load(Ordering::Relaxed), 2, "shown, sets wake it once per frame"); + overlay.rt.frame(0.0); + overlay.hide(); + pixels.set(1, 1, vec![2; 4]); + assert_eq!(wakes.load(Ordering::Relaxed), 2, "hidden again, it sleeps"); +} + +#[test] +fn overlay_input_switch_waits_for_owned_drag_release() { + fn view(_: &Vec<crate::Phase>, _: &mut Cx<Vec<crate::Phase>>) -> El { + crate::el().w_full().h_full().hit().on_drag(|phases: &mut Vec<crate::Phase>, drag, _| phases.push(drag.phase)) + } + let app = AppSpec { + title: "input switch", size: (100.0, 100.0), min_size: None, init: Vec::new, view, + scenes: &[], fonts: &[], families: ("sans-serif", "monospace"), setup: None, poll: None, on_key: None, + }; + let spec = OverlaySpec::new("input switch", app.size, view).options(OverlayOptions { input: OverlayInput::All, ..Default::default() }); + let (mut overlay, handle) = Overlay::new(spec, Vec::new(), &app); + overlay.rt.frame(0.0); + overlay.rt.pointer_down(10.0, 10.0); + handle.set_input(OverlayInput::Regions); + handle.set_input(OverlayInput::None); + overlay.core.pending_input = overlay.shared.core.requests.lock().unwrap().input.take(); + overlay.apply_input(); + assert_eq!(overlay.options.input, OverlayInput::All, "an owned gesture retains its old native mode"); + overlay.rt.pointer_move(150.0, 150.0); + overlay.rt.pointer_up(150.0, 150.0); + overlay.apply_input(); + overlay.rt.frame(0.0); + assert_eq!(overlay.options.input, OverlayInput::None); + assert_eq!(overlay.rt.state.first(), Some(&crate::Phase::Down)); + assert_eq!(overlay.rt.state.last(), Some(&crate::Phase::Up), "release is delivered even outside the canvas"); + assert!(!overlay.rt.pointer_captured()); +} + +#[cfg(target_os = "macos")] +fn lost_release_overlay() -> Overlay<Vec<(crate::Phase, bool)>> { + type State = Vec<(crate::Phase, bool)>; + fn view(_: &State, _: &mut Cx<State>) -> El { + crate::el().w_full().h_full().hit().on_drag(|s: &mut State, drag, _| s.push((drag.phase, drag.cancelled()))) + } + let app = AppSpec { + title: "lost release", size: (100.0, 100.0), min_size: None, init: Vec::new, view, + scenes: &[], fonts: &[], families: ("sans-serif", "monospace"), setup: None, poll: None, on_key: None, + }; + let spec = OverlaySpec::new("lost release", app.size, view).options(OverlayOptions { input: OverlayInput::All, ..Default::default() }); + let (mut overlay, _) = Overlay::new(spec, Vec::new(), &app); + overlay.rt.frame(0.0); + overlay +} + +#[cfg(target_os = "macos")] +#[test] +fn overlay_late_up_after_a_lost_release_is_no_drop() { + let mut overlay = lost_release_overlay(); + overlay.left_edge(None, true, Some((10.0, 10.0))); + overlay.left_edge(Some((30.0, 10.0)), false, None); + overlay.rt.frame(0.0); + let ups: Vec<_> = overlay.rt.state.iter().filter(|d| d.0 == crate::Phase::Up).map(|d| d.1).collect(); + assert_eq!(ups, [true], "the recovery lands before the late Up"); +} + +#[cfg(target_os = "macos")] +#[test] +fn overlay_press_that_beats_a_lost_release_ends_the_old_drag_first() { + let mut overlay = lost_release_overlay(); + overlay.left_edge(None, true, Some((10.0, 10.0))); + overlay.left_edge(Some((30.0, 10.0)), true, Some((50.0, 10.0))); + overlay.left_edge(None, false, Some((50.0, 10.0))); + overlay.rt.frame(0.0); + let ups: Vec<_> = overlay.rt.state.iter().filter(|d| d.0 == crate::Phase::Up).map(|d| d.1).collect(); + assert_eq!(ups, [true, false], "the old drag is cancelled, the new one ends normally"); + assert!(!overlay.rt.state.iter().any(|d| d.0 == crate::Phase::Move), "the old drag never hears the new press's point"); +} + +#[cfg(target_os = "macos")] +#[test] +fn overlay_cursor_move_for_the_next_press_cancels_the_old_drag_first() { + let mut overlay = lost_release_overlay(); + let pointer = crate::platform::macos::PointerState::new(OverlayInput::All, false); + pointer.record_click(true, 10.0, 10.0); + overlay.native_left(&pointer, true); + pointer.read(0, crate::time::now(), (12.0, 10.0), true, false); + pointer.record_click(true, 50.0, 10.0); + overlay.native_moved(&pointer, 50.0, 10.0); // winit reports the click's position just before the click + overlay.native_left(&pointer, true); + overlay.rt.frame(0.0); + assert_eq!(overlay.rt.state.iter().filter(|d| d.0 == crate::Phase::Up).map(|d| d.1).collect::<Vec<_>>(), [true]); + assert!(!overlay.rt.state.iter().any(|d| d.0 == crate::Phase::Move), "the old drag never hears the new press's point"); +} + +#[cfg(target_os = "macos")] +#[derive(Default)] +struct DragOutCount { starts: u32 } + +#[cfg(target_os = "macos")] +fn drag_out_overlay() -> Overlay<DragOutCount> { + fn view(_: &DragOutCount, _: &mut Cx<DragOutCount>) -> El { + crate::el().w_full().h_full().hit() + .drag_out(|_: &DragOutCount| Some(crate::DragItem::new().file("/Applications/Example.app"))) + .on_drag_start(|s: &mut DragOutCount, _| s.starts += 1) + } + let app = AppSpec { + title: "drag out", size: (200.0, 100.0), min_size: None, init: DragOutCount::default, view, + scenes: &[], fonts: &[], families: ("sans-serif", "monospace"), setup: None, poll: None, on_key: None, + }; + let spec = OverlaySpec::new("drag out", app.size, view).options(OverlayOptions { input: OverlayInput::All, ..Default::default() }); + let (mut overlay, _) = Overlay::new(spec, DragOutCount::default(), &app); + overlay.rt.frame(0.0); + overlay +} + +#[cfg(target_os = "macos")] +#[test] +fn overlay_release_past_the_drag_threshold_starts_no_os_drag() { + let mut overlay = drag_out_overlay(); + let pointer = crate::platform::macos::PointerState::new(OverlayInput::All, false); + pointer.record_click(true, 10.0, 10.0); + overlay.native_moved(&pointer, 10.0, 10.0); + overlay.native_left(&pointer, true); + // A quick flick: no drag event reaches the view before the Up, whose position is far off. + pointer.record_click(false, 60.0, 10.0); + overlay.native_moved(&pointer, 60.0, 10.0); + overlay.native_left(&pointer, false); + pointer.released(); + overlay.rt.frame(0.0); + assert_eq!(overlay.rt.state.starts, 0, "the button was up: no OS drag"); + assert!(!overlay.rt.pointer_captured()); +} + +#[cfg(target_os = "macos")] +#[test] +fn overlay_a_stale_up_ahead_of_an_unmatched_press_leaves_its_drag_out_armed() { + let mut overlay = drag_out_overlay(); + let pointer = crate::platform::macos::PointerState::new(OverlayInput::All, false); + pointer.record_click(true, 10.0, 10.0); + overlay.native_moved(&pointer, 10.0, 10.0); + overlay.native_left(&pointer, true); + // A's Up is seen but winit never delivers it, so it stays queued ahead of B's Down. + pointer.record_click(false, 12.0, 10.0); + pointer.record_click(true, 12.0, 10.0); + overlay.native_moved(&pointer, 12.0, 10.0); + overlay.native_left(&pointer, true); + assert!(overlay.rt.pointer_captured(), "B is held, unmatched"); + overlay.native_moved(&pointer, 60.0, 10.0); + overlay.rt.frame(0.0); + assert_eq!(overlay.rt.state.starts, 1, "A's stale Up says nothing about B's button: B's drag starts, as on dev"); +} + +#[cfg(target_os = "macos")] +#[test] +fn overlay_a_stale_click_taken_for_the_next_press_leaves_its_drag_out_armed() { + let mut overlay = drag_out_overlay(); + let pointer = crate::platform::macos::PointerState::new(OverlayInput::All, false); + let click = |overlay: &mut Overlay<DragOutCount>, down: bool| { + pointer.record_click(down, 10.0, 10.0); + overlay.native_moved(&pointer, 10.0, 10.0); + overlay.native_left(&pointer, down); + if !down { pointer.released(); } + }; + click(&mut overlay, true); // A + pointer.record_click(false, 10.0, 10.0); // A's Up is swallowed: seen, never delivered + click(&mut overlay, true); // B, unmatched behind A's Up + click(&mut overlay, false); // B's Up takes A's queued Up, leaving B's Down and Up queued + click(&mut overlay, true); // C takes B's stale Down + assert!(overlay.rt.pointer_captured(), "C is held"); + overlay.native_moved(&pointer, 60.0, 10.0); + overlay.rt.frame(0.0); + assert_eq!(overlay.rt.state.starts, 1, "B's stale Up says nothing about C's button: C's drag starts, as on dev"); +} + +#[cfg(target_os = "macos")] +#[test] +fn overlay_drag_past_the_threshold_with_the_button_down_starts_an_os_drag() { + let mut overlay = drag_out_overlay(); + let pointer = crate::platform::macos::PointerState::new(OverlayInput::All, false); + pointer.record_click(true, 10.0, 10.0); + overlay.native_moved(&pointer, 10.0, 10.0); + overlay.native_left(&pointer, true); + overlay.native_moved(&pointer, 60.0, 10.0); + overlay.rt.frame(0.0); + assert_eq!(overlay.rt.state.starts, 1); +} + +#[test] +fn handle_requests_collapse_and_updates_keep_their_order() { + let shared = Arc::new(Shared::<u32>::default()); + let handle = OverlayHandle { shared: shared.clone() }; + assert_eq!(handle.availability(), Availability::Unknown); + handle.show(); + handle.update(|n, _| *n += 1); + handle.place(ScreenEdge::Bottom, 24.0); + handle.set_align(Align::End, 12.0); + handle.resize((300.0, 80.0)); + handle.update(|n, _| *n *= 3); + handle.hide(); + let q = std::mem::take(&mut *shared.core.requests.lock().unwrap()); + let updates = std::mem::take(&mut *shared.updates.lock().unwrap()); + assert_eq!(q.visible(), Some(false), "the latest show/hide wins"); + assert_eq!((q.edge, q.margin), (Some(ScreenEdge::Bottom), Some(24.0))); + assert_eq!((q.align, q.size), (Some((Align::End, 12.0)), Some((300.0, 80.0)))); + let mut n = 0; + for f in updates { + f(&mut n, &mut Tx::default()); + } + assert_eq!(n, 3); + shared.core.availability.store(2, Ordering::Release); + assert_eq!(handle.availability(), Availability::Unavailable); +} + +#[test] +fn hidden_overlay_update_wakes_once_without_a_surface() { + use std::time::Duration; + fn view(_: &Vec<f64>, _: &mut Cx<Vec<f64>>) -> El { crate::el() } + let app = AppSpec { families: ("sans-serif", "monospace"), ..AppSpec::new("timer test", (20.0, 20.0), Vec::<f64>::new, view) }; + let spec = OverlaySpec { + name: "timer test", size: (20.0, 20.0), edge: ScreenEdge::Top, + margin: 0.0, align: Align::Center, inset: 0.0, interactive: false, view, + }; + let (mut overlay, handle) = Overlay::new(spec.options(Default::default()).poll(|seen, now, _| { seen.push(now); false }), Vec::new(), &app); + // The runtime's virtual clock makes scheduling exact; the host maps it to wall time. + overlay.rt.wall_start = None; + handle.update(|_, tx| tx.wake_after(Duration::from_millis(250))); + let updates = std::mem::take(&mut *overlay.shared.updates.lock().unwrap()); + overlay.apply_wake(false, updates); + assert_eq!(overlay.rt.state, [0.0]); + assert_eq!(overlay.rt.wake_deadline(), Some(0.25)); + let start = crate::time::now(); + overlay.rt.wall_start = Some(start); + assert_eq!(overlay.wake_deadline(), Some(start + Duration::from_millis(250))); + overlay.wake_due(start + Duration::from_millis(249)); + assert_eq!(overlay.rt.state.len(), 1, "not before the deadline"); + overlay.rt.wall_start = Some(crate::time::now() - Duration::from_millis(250)); + overlay.wake_due(crate::time::now()); + assert_eq!(overlay.rt.state.len(), 2); + assert!(overlay.rt.state[1] >= 0.25); + assert_eq!(overlay.wake_deadline(), None); + overlay.wake_due(crate::time::now()); + assert!(!overlay.draw(), "hidden overlays do not acquire or animate a surface"); + assert_eq!(overlay.rt.state.len(), 2, "no polling after the one wake"); + assert!(overlay.surface.live().is_none() && overlay.gpu.is_none()); +} + +thread_local! { static BUILDS: std::cell::Cell<u32> = const { std::cell::Cell::new(0) }; } + +fn counter_view(n: &u32, _: &mut Cx<u32>) -> El { + BUILDS.set(BUILDS.get() + 1); + crate::el().child(crate::text(n.to_string()).key("n")) +} + +fn counter_text(overlay: &Overlay<u32>) -> Option<String> { + overlay.rt.elements().into_iter().find(|e| e.key.as_deref() == Some("n")).and_then(|e| e.text) +} + +/// A hidden overlay whose state changes ten times a second, from updates and their timers, +/// builds no view and lays nothing out. The frame that shows it builds once, with the +/// latest state. +#[test] +fn a_hidden_overlay_builds_nothing_until_it_shows() { + let app = AppSpec::new("hidden counter", (200.0, 50.0), || 0, counter_view); + let (mut overlay, handle) = Overlay::new(OverlaySpec::new("hidden counter", app.size, counter_view).options(Default::default()), 0, &app); + let start = crate::time::now(); + overlay.rt.wall_start = Some(start); + present(&mut overlay, start); + assert_eq!(counter_text(&overlay).as_deref(), Some("0")); + let (builds, commits) = (BUILDS.get(), overlay.rt.stats.commits); + for k in 1..=10 { + handle.update(|n, tx| { *n += 1; tx.wake_after(Duration::from_millis(50)); }); + let requests = std::mem::take(&mut *overlay.shared.core.requests.lock().unwrap()); + let updates = std::mem::take(&mut *overlay.shared.updates.lock().unwrap()); + overlay.apply_wake(requests.woken, updates); + // Its timer comes due before the next update. + overlay.rt.wall_start = Some(crate::time::now() - k * Duration::from_millis(100)); + overlay.wake_due(crate::time::now()); + } + assert_eq!(overlay.rt.state, 10); + assert_eq!(BUILDS.get() - builds, 0, "no view builds while hidden"); + assert_eq!(overlay.rt.stats.commits, commits, "no layout while hidden"); + assert_eq!(overlay.wake_deadline(), None, "and nothing left to wake it"); + + // Shown: `show_fading` settles an unretained overlay and asks for a frame. + overlay.presence = Presence::Shown { occluded: false }; + overlay.rt.set_live_visible(true); + overlay.settle_before_reveal(); + overlay.dirty = true; + present(&mut overlay, crate::time::now()); + assert_eq!(BUILDS.get() - builds, 1, "the frame that shows it builds once"); + assert_eq!(counter_text(&overlay).as_deref(), Some("10"), "with the latest state"); +} + +/// Updates that change nothing neither draw a shown overlay nor refresh a hidden one, and +/// still schedule their timers. +#[test] +fn updates_that_change_nothing_leave_an_overlay_alone() { + let app = AppSpec::new("quiet counter", (200.0, 50.0), || 0, counter_view); + let (mut overlay, handle) = Overlay::new(OverlaySpec::new("quiet counter", app.size, counter_view).options(Default::default()), 0, &app); + overlay.rt.wall_start = None; + overlay.rt.frame(0.0); + let (builds, commits) = (BUILDS.get(), overlay.rt.stats.commits); + let apply = |overlay: &mut Overlay<u32>| { + let requests = std::mem::take(&mut *overlay.shared.core.requests.lock().unwrap()); + let updates = std::mem::take(&mut *overlay.shared.updates.lock().unwrap()); + overlay.apply_wake(requests.woken, updates); + }; + for visible in [false, true] { + overlay.presence = if visible { Presence::Shown { occluded: false } } else { Presence::default() }; + for _ in 0..100 { + overlay.dirty = false; + handle.update_if(|_, tx| { tx.wake_after(Duration::from_millis(500)); false }); + apply(&mut overlay); + assert!(!overlay.dirty && !overlay.rt.stale(), "visible {visible}"); + } + } + assert_eq!((BUILDS.get() - builds, overlay.rt.stats.commits - commits), (0, 0)); + assert_eq!(overlay.rt.wake_deadline(), Some(0.5)); + handle.update_if(|_, _| false); + handle.update_if(|n, _| { *n = 3; true }); + apply(&mut overlay); + assert!(overlay.dirty, "a change in the batch draws"); + // A hidden overlay answers a pop-up menu at once; its callback's change draws. + overlay.presence = Presence::default(); + overlay.dirty = false; + overlay.rt.frame(1.0); + handle.update_if(|_, tx| { + tx.popup_menu(crate::PopupMenu::new().item(crate::PopupItem::new("a", "A")), (0.0, 0.0), |n: &mut u32, _, _| *n = 7); + false + }); + apply(&mut overlay); + assert_eq!(overlay.rt.state, 7); + assert!(overlay.dirty); +} + +/// A prewarmed overlay keeps its frame ready while hidden, but commits state that changes +/// ten times a second at most every `HIDDEN_REFRESH`. Its reveal commits what's left once. +#[cfg(target_os = "macos")] +#[test] +fn a_hidden_prewarmed_overlay_commits_at_most_every_refresh() { + use crate::window::HIDDEN_REFRESH; + let app = AppSpec::new("prewarmed counter", (200.0, 50.0), || 0, counter_view); + let spec = OverlaySpec::new("prewarmed counter", app.size, counter_view).options(OverlayOptions { prewarm: true, ..Default::default() }); + let (mut overlay, _) = Overlay::new(spec, 0, &app); + overlay.rt.wall_start = None; + overlay.warm(); + overlay.dirty = false; + let start = overlay.clock.last(); + let builds = BUILDS.get(); + let mut pace_wakes = Vec::new(); + for tick in 1..=100 { + let now = start + tick * Duration::from_millis(10); + if tick % 10 == 0 { + overlay.rt.update(|n, _| *n += 1); + overlay.dirty = true; + overlay.advance_at(now); + } + if let Some(wake) = overlay.wake_deadline().filter(|&wake| wake <= now) { + pace_wakes.push(wake - start); + overlay.wake_due(now); + } + } + let hidden = BUILDS.get() - builds; + let bound = 1 + (Duration::from_secs(1).as_millis() / HIDDEN_REFRESH.as_millis()) as u32; + assert!((2..=bound).contains(&hidden), "{hidden} builds in a hidden second, want at most {bound}; paced wakes at {pace_wakes:?}"); + assert_eq!(overlay.rt.state, 10); + assert_ne!(counter_text(&overlay).as_deref(), Some("10"), "the last change waits for the pace or the reveal"); + let before = BUILDS.get(); + overlay.refresh_for_reveal_at(start + Duration::from_millis(1005)); + assert_eq!(BUILDS.get() - before, 1, "the reveal builds once"); + assert_eq!(counter_text(&overlay).as_deref(), Some("10"), "with the latest state"); +} + +#[test] +fn overlay_poll_inherits_overrides_and_wakes_visible_state_once() { + use std::time::Duration; + #[derive(Default)] + struct State { polls: usize, value: f32 } + fn view(s: &State, _: &mut Cx<State>) -> El { + crate::el().child(crate::el().key("value").size(10.0 + s.value, 10.0)) + } + fn poll(s: &mut State, _: f64, tx: &mut Tx) -> bool { + s.polls += 1; + if s.polls == 1 { tx.wake_after(Duration::from_millis(250)); return false; } + if s.polls == 2 { s.value = 7.0; tx.instant(); return true; } + false + } + let app = AppSpec { poll: Some(poll), ..AppSpec::new("poll", (30.0, 20.0), State::default, view) }; + let (mut overlay, _) = Overlay::new(OverlaySpec::new("poll", app.size, view), State::default(), &app); + overlay.presence = Presence::Shown { occluded: false }; + overlay.rt.wall_start = None; + assert!(!overlay.rt.frame(0.0)); + assert_eq!(overlay.rt.state.polls, 1); + assert_eq!(overlay.rt.wake_deadline(), Some(0.25), "false still registers wake_after"); + overlay.dirty = false; + let start = crate::time::now() - Duration::from_millis(251); + overlay.rt.wall_start = Some(start); + overlay.wake_due(start + Duration::from_millis(249)); + assert!(!overlay.dirty); + overlay.wake_due(crate::time::now()); + assert!(overlay.dirty, "visible wake schedules the frame"); + assert_eq!(overlay.rt.state.polls, 1, "do not poll twice: the drawable frame owns the poll"); + assert!(!overlay.rt.frame(0.0), "true means changed state, not continuous animation"); + assert_eq!(overlay.rt.state.polls, 2); + assert_eq!(overlay.rt.presented("value").unwrap().0[2], 17.0); + assert_eq!(overlay.wake_deadline(), None); + overlay.dirty = false; + overlay.wake_due(crate::time::now()); + assert!(!overlay.dirty, "no timer or animation means no more scheduled frames"); + + let configured = OverlaySpec::new("override", app.size, view).options(Default::default()) + .poll(|s, _, _| { s.polls += 10; false }); + let (mut other, _) = Overlay::new(configured, State::default(), &app); + other.rt.frame(0.0); + assert_eq!(other.rt.state.polls, 10, "builder overrides inherited poll"); + assert_eq!(other.wake_deadline(), None); + + fn other_view(_: &u32, _: &mut Cx<u32>) -> El { crate::el() } + let (mut different, _) = Overlay::new(OverlaySpec::new("different", app.size, other_view), 0_u32, &app); + assert!(different.rt.poll.is_none(), "never apply a poll to a different state type"); + different.rt.frame(0.0); + assert_eq!(different.rt.state, 0); +} + +/// Covered, or shown while the displays sleep: no frame comes, yet `wake_after` still fires +/// and can hide the overlay, and a missed frame waits instead of polling. +#[cfg(target_os = "macos")] +#[test] +fn overlay_occluded_runs_due_timers_without_frames() { + use crate::window::{Missed, OCCLUDED_MAX, OCCLUDED_RETRY}; + #[derive(Default)] + struct State { polls: usize, handle: Option<OverlayHandle<State>> } + fn view(_: &State, _: &mut Cx<State>) -> El { crate::el() } + fn poll(s: &mut State, _: f64, tx: &mut Tx) -> bool { + s.polls += 1; + if s.polls == 1 { tx.wake_after(Duration::from_millis(250)); } else { s.handle.as_ref().unwrap().hide(); } + false + } + let app = AppSpec { poll: Some(poll), ..AppSpec::new("occluded", (30.0, 20.0), State::default, view) }; + let (mut overlay, handle) = Overlay::new(OverlaySpec::new("occluded", app.size, view), State::default(), &app); + overlay.rt.state.handle = Some(handle.clone()); + overlay.presence = Presence::Shown { occluded: false }; + overlay.rt.wall_start = None; + // Shown onto sleeping displays: the first frame misses, and still polls. + overlay.occluded(true); + overlay.missed(Missed::Occluded, false, false); + assert_eq!(overlay.rt.state.polls, 1); + assert_eq!(overlay.rt.wake_deadline(), Some(0.25)); + overlay.backoff = Default::default(); + let start = crate::time::now() - Duration::from_millis(251); + overlay.rt.wall_start = Some(start); + assert!(overlay.wake_deadline().is_some_and(|at| at <= crate::time::now()), "the timer stays armed while occluded"); + overlay.dirty = false; + overlay.wake_due(crate::time::now()); + assert_eq!(overlay.rt.state.polls, 2, "the due timer runs without waiting for a drawable"); + assert_eq!(handle.shared.core.requests.lock().unwrap().visible(), Some(false), "and its hide() goes through"); + assert_eq!(overlay.wake_deadline(), None); + + // Each missed frame waits, longer while it stays occluded; a timeout waits for the + // display link that is still running. + let mut waits = Vec::new(); + for _ in 0..6 { + let before = crate::time::now(); + overlay.missed(Missed::Occluded, false, false); + let retry = overlay.backoff.deadline().expect("an occluded miss re-checks later"); + assert_eq!(overlay.wake_deadline(), Some(retry)); + waits.push(retry - before); + } + assert!(waits[0] >= OCCLUDED_RETRY && waits.windows(2).all(|w| w[1] + Duration::from_millis(1) >= w[0]), "{waits:?}"); + assert!(waits[5] >= OCCLUDED_MAX && waits.iter().all(|&w| w <= OCCLUDED_MAX + Duration::from_millis(50)), "{waits:?}"); + overlay.missed(Missed::Timeout, true, false); + assert_eq!(overlay.backoff.deadline(), None); + overlay.occluded(false); + assert!(overlay.dirty, "uncovered, it redraws once"); + let now = crate::time::now(); + let mut probe = overlay.backoff; + probe.step(crate::window::BackoffEvent::Missed { missed: Missed::Occluded, paced: false, now }); + assert_eq!(probe.deadline(), Some(now + OCCLUDED_RETRY), "uncovered, the wait starts over"); + + // An update arriving while it is covered arms its timer at once, not on a later retry. + overlay.occluded(true); + overlay.apply_wake(false, vec![Box::new(|_: &mut State, tx: &mut Tx| { tx.wake_after(Duration::from_secs(5)); true })]); + let deadline = overlay.wake_deadline().expect("the update's timer is armed while occluded"); + assert!(deadline > crate::time::now() + Duration::from_secs(4), "{:?}", deadline - crate::time::now()); +} + +/// Uncovering an overlay keeps the retry a missed frame already asked for: the wait was set for +/// a frame nobody could draw, and being uncovered doesn't show that the surface can. Only the +/// wait after it starts over. +#[cfg(target_os = "macos")] +#[test] +fn uncovering_an_overlay_keeps_its_outstanding_retry() { + use crate::window::{Missed, OCCLUDED_RETRY}; + #[derive(Default)] + struct State { polls: usize } + fn view(_: &State, _: &mut Cx<State>) -> El { crate::el() } + fn poll(_: &mut State, _: f64, _: &mut Tx) -> bool { false } + let app = AppSpec { poll: Some(poll), ..AppSpec::new("uncovered", (30.0, 20.0), State::default, view) }; + let (mut overlay, _handle) = Overlay::new(OverlaySpec::new("uncovered", app.size, view), State::default(), &app); + overlay.presence = Presence::Shown { occluded: false }; + overlay.rt.wall_start = None; + overlay.occluded(true); + // Two covered misses: the second waits longer than the first. + overlay.missed(Missed::Occluded, false, false); + let first = overlay.backoff.deadline().expect("a covered miss re-checks later"); + overlay.missed(Missed::Occluded, false, false); + let retry = overlay.backoff.deadline().expect("so does the next"); + assert!(retry > first, "the covered wait doubles while it stays covered"); + assert_eq!(overlay.wake_deadline(), Some(retry), "frames wait for that re-check"); + // Uncovered, the retry the missed frame set stands... + overlay.occluded(false); + assert_eq!(overlay.backoff.deadline(), Some(retry), "uncovering keeps the outstanding retry"); + assert_eq!(overlay.wake_deadline(), Some(retry), "and the re-check it asks for is still due"); + // ...and the wait after it starts over at the shortest occluded retry. + let now = crate::time::now(); + overlay.missed(Missed::Occluded, false, false); + let next = overlay.backoff.deadline().expect("a covered miss waits again"); + assert!(next >= now + OCCLUDED_RETRY && next < now + OCCLUDED_RETRY * 2, "{:?}", next - now); +} + +/// Any miss that sets a retry backs off: frames wait for it, a fading-out overlay's too, +/// and a timer due meanwhile runs without asking for a frame that wouldn't come. +#[test] +fn overlay_misses_back_off_until_their_retry() { + use crate::window::{Missed, OCCLUDED_RETRY, TIMEOUT_RETRY}; + #[derive(Default)] + struct State { polls: usize } + fn view(_: &State, _: &mut Cx<State>) -> El { crate::el() } + fn poll(s: &mut State, _: f64, tx: &mut Tx) -> bool { + s.polls += 1; + tx.wake_after(Duration::from_millis(250)); + false + } + let app = AppSpec { poll: Some(poll), ..AppSpec::new("backoff", (30.0, 20.0), State::default, view) }; + let (mut overlay, _handle) = Overlay::new(OverlaySpec::new("backoff", app.size, view), State::default(), &app); + overlay.presence = Presence::Shown { occluded: false }; + overlay.rt.wall_start = None; + + let now = crate::time::now(); + overlay.missed(Missed::Timeout, false, false); + assert_eq!(overlay.rt.state.polls, 1, "the missed frame still polls"); + assert!(overlay.backoff.deadline().is_some_and(|at| at >= now + TIMEOUT_RETRY)); + assert!(overlay.backing_off(crate::time::now()), "an unpaced timeout waits for its retry"); + overlay.missed(Missed::Outdated, true, true); + assert_eq!(overlay.rt.state.polls, 1, "a frame that already stepped doesn't step again"); + assert!(overlay.backoff.deadline().is_some_and(|at| at >= now + OCCLUDED_RETRY) && overlay.backing_off(crate::time::now()), + "an outdated surface waits even while a display link runs"); + + // A timer comes due while it backs off: it runs now, and the next deadline is a frame on. + overlay.rt.wall_start = Some(crate::time::now() - Duration::from_millis(251)); + overlay.dirty = false; + let due = crate::time::now(); + overlay.wake_due(due); + assert_eq!(overlay.rt.state.polls, 2, "the due timer runs without a frame"); + assert!(overlay.wake_deadline().is_some_and(|at| at > due), "and doesn't leave the loop spinning on it"); + + // Fading out, an occluded miss can't mark it occluded, yet it still waits. + overlay.presence = Presence::FadingOut { until: crate::time::now() + Duration::from_secs(1), length: Duration::from_secs(1), occluded: false }; + overlay.backoff = Default::default(); + overlay.missed(Missed::Occluded, false, false); + assert!(overlay.presence.drawing() && overlay.backing_off(crate::time::now())); + overlay.backoff_step(crate::window::BackoffEvent::At(crate::time::now())); + assert!(!overlay.backing_off(crate::time::now() + Duration::from_millis(1)), "a due retry draws"); +} + +#[cfg(feature = "hot")] +#[test] +fn a_live_edit_patch_wakes_a_hidden_overlay_and_its_next_frame_rebuilds_the_view() { + thread_local! { static BUILDS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) }; } + fn view(_: &u8, _: &mut Cx<u8>) -> El { + crate::memo("body", 0, || { BUILDS.set(BUILDS.get() + 1); crate::el().size(10.0, 10.0) }) + } + crate::hot::enable_for_tests(); + let app = AppSpec::new("hot", (30.0, 20.0), || 0u8, view); + let (mut overlay, _) = Overlay::new(OverlaySpec::new("hot", app.size, view).options(Default::default()), 0u8, &app); + overlay.rt.wall_start = None; + let (tx, rx) = std::sync::mpsc::channel(); + overlay.connect(Arc::new(move || { tx.send(()).ok(); }), Arc::new(|| {}), Arc::new(|| {}), Rc::default()); + let hub: &'static crate::hot::Hub = Box::leak(Box::default()); + overlay.rt.frame.hot_mut().expect("connect attaches the overlay to live edits").move_to(hub); + while rx.try_recv().is_ok() {} + let take = |overlay: &mut Overlay<u8>| ( + std::mem::take(&mut *overlay.shared.core.requests.lock().unwrap()), + std::mem::take(&mut *overlay.shared.updates.lock().unwrap()), + ); + let _ = take(&mut overlay); + overlay.rt.frame(0.0); + let built = BUILDS.get(); + overlay.rt.invalidate(); + overlay.rt.frame(0.0); + assert_eq!(BUILDS.get(), built, "an unchanged memo is reused"); + hub.patched(); + rx.recv_timeout(Duration::from_secs(5)).expect("the patch wakes the event loop"); + let (requests, updates) = take(&mut overlay); + assert!(requests.woken); + overlay.apply_wake(requests.woken, updates); + assert!(overlay.dirty && overlay.rt.needs_commit(), "hidden, the patch waits for the frame that shows it"); + overlay.presence = Presence::Shown { occluded: false }; + overlay.advance(); + assert_eq!(BUILDS.get(), built + 1, "that frame rebuilds the memo with the patched code"); +} + +#[test] +fn overlay_setup_runs_once_with_a_waker_that_redraws_the_overlay() { + use std::sync::atomic::AtomicUsize; + use std::time::Duration; + #[derive(Default)] + struct State { setups: usize, polls: usize, cache: Option<crate::image::ImageCache>, icon: Option<crate::image::Image>, saw_icon: std::cell::Cell<bool> } + fn view(s: &State, _: &mut Cx<State>) -> El { + s.saw_icon.set(s.icon.as_ref().is_some_and(|i| i.is_ready())); + crate::el() + } + let app = AppSpec { families: ("sans-serif", "monospace"), ..AppSpec::new("setup", (30.0, 20.0), State::default, view) }; + let configured = OverlaySpec::new("setup", app.size, view).options(Default::default()) + .setup(|s, waker| { s.setups += 1; s.cache = Some(crate::image::ImageCache::new(waker)); }) + .poll(|s, _, _| { s.polls += 1; false }); + let (mut overlay, _) = Overlay::new(configured, State::default(), &app); + overlay.rt.wall_start = None; + assert_eq!(overlay.rt.state.setups, 0, "not before the event loop"); + let loop_wakes = Arc::new(AtomicUsize::new(0)); + let (tx, rx) = std::sync::mpsc::channel(); + let counter = loop_wakes.clone(); + let wake: Waker = Arc::new(move || { counter.fetch_add(1, Ordering::SeqCst); tx.send(()).ok(); }); + overlay.connect(wake.clone(), Arc::new(|| {}), Arc::new(|| {}), Rc::default()); + overlay.connect(wake, Arc::new(|| {}), Arc::new(|| {}), Rc::default()); + assert_eq!(overlay.rt.state.setups, 1, "setup runs once"); + while rx.try_recv().is_ok() {} + let take = |overlay: &mut Overlay<State>| ( + std::mem::take(&mut *overlay.shared.core.requests.lock().unwrap()), + std::mem::take(&mut *overlay.shared.updates.lock().unwrap()), + ); + let _ = take(&mut overlay); + + // Hidden: a background decode wakes the loop, and the overlay polls; the view waits + // for the frame that shows it. + overlay.advance(); + assert!(!overlay.rt.state.saw_icon.get()); + let state = &mut overlay.rt.state; + state.icon = Some(state.cache.as_ref().unwrap().rgba(1, 1, vec![20, 40, 60, 255])); + rx.recv_timeout(Duration::from_secs(5)).expect("the decode wakes the event loop"); + let (requests, updates) = take(&mut overlay); + assert!(requests.woken); + overlay.apply_wake(requests.woken, updates); + assert!(!overlay.rt.state.saw_icon.get(), "a hidden overlay's view doesn't run"); + assert!(overlay.dirty && overlay.rt.needs_commit()); + let polls = overlay.rt.state.polls; + overlay.presence = Presence::Shown { occluded: false }; + overlay.advance(); // the frame that shows it + assert!(overlay.rt.state.saw_icon.get(), "shown, the view saw the decoded image"); + + // Shown: the next wake schedules a frame that re-runs the view. + overlay.rt.state.icon = None; + overlay.rt.invalidate(); + overlay.advance(); + assert!(!overlay.rt.state.saw_icon.get()); + overlay.dirty = false; + overlay.idle = true; + let polls_shown = overlay.rt.state.polls; + let state = &mut overlay.rt.state; + state.icon = Some(state.cache.as_ref().unwrap().rgba(1, 1, vec![60, 40, 20, 255])); + rx.recv_timeout(Duration::from_secs(5)).expect("the decode wakes the event loop"); + let (requests, updates) = take(&mut overlay); + overlay.apply_wake(requests.woken, updates); + assert!(overlay.dirty, "a shown overlay draws a frame"); + assert_eq!(overlay.rt.state.polls, polls_shown, "the drawn frame owns the poll"); + overlay.advance(); // the drawn frame + assert!(overlay.rt.state.saw_icon.get(), "the view saw the decoded image"); + assert!(polls >= 1); + + // Wakes before the loop drains them coalesce into one loop wake. + while rx.try_recv().is_ok() {} + let before = loop_wakes.load(Ordering::SeqCst); + let state = &mut overlay.rt.state; + let cache = state.cache.as_ref().unwrap(); + let _a = cache.rgba(1, 1, vec![1, 2, 3, 255]); + let _b = cache.rgba(1, 1, vec![4, 5, 6, 255]); + rx.recv_timeout(Duration::from_secs(5)).expect("the decodes wake the event loop"); + std::thread::sleep(Duration::from_millis(100)); + assert_eq!(loop_wakes.load(Ordering::SeqCst), before + 1, "one loop wake until the overlay takes it"); + assert!(take(&mut overlay).0.woken); + assert!(loop_wakes.load(Ordering::SeqCst) >= 2); +} + +#[test] +fn overlay_compositor_observes_prewarm_and_each_rendered_frame() { + use crate::render::{Offscreen, OFFSCREEN_FORMAT}; + struct Trace(Rc<RefCell<Vec<f32>>>); + impl Compositor<f32> for Trace { + fn render(&mut self, f: &mut Frame<'_, f32>) { + f.draw_ui(); + let element = f.rt.elements().into_iter().find(|e| e.key.as_deref() == Some("box")).unwrap(); + self.0.borrow_mut().push(element.rect[2]); + } + fn animating(&self) -> bool { self.0.borrow().len() < 3 } + } + fn view(width: &f32, _: &mut Cx<f32>) -> El { + crate::el().size(32.0, 16.0).child(crate::el().key("box").size(*width, 8.0).fill(crate::Color::WHITE)) + } + let app = AppSpec::new("trace", (32.0, 16.0), || 8.0, view); + let trace = Rc::new(RefCell::new(Vec::new())); + let spec = OverlaySpec::new("trace", app.size, view).options(OverlayOptions { prewarm: true, ..Default::default() }) + .compositor(Trace(trace.clone())); + let (mut overlay, _) = Overlay::new(spec, 8.0, &app); + let gpu = Arc::new(Gpu::headless()); + overlay.renderer = Some(Renderer::new(&gpu.device, OFFSCREEN_FORMAT)); + overlay.gpu = Some(gpu.clone()); + overlay.rt.transparent = true; + overlay.rt.frame(0.0); + overlay.warm_offscreen((32, 16)); + assert_eq!(*trace.borrow(), [8.0], "offscreen prewarm must use the compositor too"); + assert!(!overlay.presence.shown()); + + let target = Offscreen::new(&gpu.device, 32, 16); + for (width, more) in [(12.0, true), (20.0, false)] { + overlay.rt.update(|s, tx| { *s = width; tx.instant(); }); + overlay.rt.frame(1.0 / 60.0); + let mut enc = gpu.device.create_command_encoder(&Default::default()); + let animating = overlay.render_offscreen(&gpu, &mut enc, &target.view, OFFSCREEN_FORMAT, (32, 16), 1.0 / 60.0); + assert_eq!(animating, more, "honour compositor-driven animation and stop when it settles"); + target.copy(&mut enc); + overlay.renderer.as_mut().unwrap().submit(&gpu.queue, enc); + let pixels = target.read(&gpu.device); + assert_eq!(&pixels[4..8], &[255; 4], "draw_ui renders the overlay content"); + assert_eq!(&pixels[(15*32+31)*4..(15*32+32)*4], &[0; 4], "draw_ui preserves the transparent clear"); + } + assert_eq!(*trace.borrow(), [8.0, 12.0, 20.0], "one observation per rendered frame, with current geometry"); +} + +#[derive(Default)] +struct Drags { starts: u32, ended: Vec<crate::DragOutcome> } + +fn drag_overlay(name: &'static str) -> Overlay<Drags> { + fn view(_: &Drags, _: &mut Cx<Drags>) -> El { + crate::el().child(crate::el().key("tile").size(100.0, 40.0) + .drag_out(|_: &Drags| Some(crate::DragItem::new().text("tile"))) + .on_drag_start(|s: &mut Drags, _| s.starts += 1) + .on_drag_end(|s: &mut Drags, outcome, _| s.ended.push(outcome))) + } + let app = AppSpec::new(name, (200.0, 50.0), Drags::default, view); + let (mut overlay, _) = Overlay::new(OverlaySpec::new(name, app.size, view).options(Default::default()), Drags::default(), &app); + overlay.rt.wall_start = None; + present(&mut overlay, crate::time::now()); + overlay +} + +#[test] +fn a_release_past_the_threshold_does_not_start_a_drag_out() { + let mut overlay = drag_overlay("flick"); + overlay.rt.pointer_move(10.0, 10.0); + overlay.left_button(true, None); + overlay.left_button(false, Some((60.0, 10.0))); + assert!(overlay.rt.take_drag_out().is_none()); + present(&mut overlay, crate::time::now()); + assert_eq!(overlay.rt.state.starts, 0); +} + +#[test] +fn a_hidden_overlay_still_runs_on_drag_end() { + let mut overlay = drag_overlay("hidden drag end"); + assert!(!overlay.presence.shown()); + overlay.rt.drag_end_sink().borrow_mut().push(("#0/tile".into(), crate::DragOutcome::Copied)); + overlay.drag_ends_due(); + assert_eq!(overlay.rt.state.ended, [crate::DragOutcome::Copied]); +} + +/// A card that arrives while the overlay is hidden, in the update that shows it, enters from +/// the first visible frame with `animate_reveal`; without it the overlay shows settled. +#[test] +fn an_animated_reveal_lets_the_first_card_enter() { + fn view(card: &bool, _: &mut Cx<bool>) -> El { + let card = card.then(|| crate::el().key("card").size(100.0, 40.0).transition(crate::Transition::offset(0.0, -24.0))); + crate::el().children(card) + } + let app = AppSpec::new("stack", (200.0, 100.0), || false, view); + for animate in [true, false] { + let mut spec = OverlaySpec::new("stack", app.size, view).options(Default::default()); + if animate { spec = spec.animate_reveal(); } + let (mut overlay, _) = Overlay::new(spec, false, &app); + overlay.rt.wall_start = None; + let start = crate::time::now(); + present(&mut overlay, start); + overlay.rt.update(|card, _| *card = true); + overlay.presence = Presence::Shown { occluded: false }; + overlay.settle_before_reveal(); + present(&mut overlay, start + Duration::from_secs(5)); + let y = overlay.rt.presented("card").unwrap().0[1]; + if animate { + assert!(y < -10.0 && overlay.rt.animating, "the first frame shows the card entering: y={y}"); + present(&mut overlay, start + Duration::from_secs(5) + FRAME * 6); + let later = overlay.rt.presented("card").unwrap().0[1]; + assert!(later > y, "and it moves: {y} then {later}"); + } else { + assert_eq!(y, 0.0, "an ordinary show lands at rest"); + } + } +} + +#[cfg(target_os = "macos")] +#[test] +fn a_turn_whose_frame_is_not_due_never_waits_on_the_present_thread() { + use crate::platform::display_link::Opportunity; + let mut waits = 0; + assert_eq!(frame::claim(Some(Opportunity::Wait), || waits += 1), None); + assert_eq!(waits, 0); + let at = crate::time::now(); + assert_eq!(frame::claim(Some(Opportunity::Tick(at)), || waits += 1), Some(Some(at))); + assert_eq!(frame::claim(Some(Opportunity::Now), || waits += 1), Some(None)); + assert_eq!(frame::claim(None, || waits += 1), Some(None)); + assert_eq!(waits, 3); +} + +#[test] +fn a_runtime_at_rest_builds_nothing_while_its_compositor_animates() { + struct Spin; + impl Compositor<f32> for Spin { + fn render(&mut self, _: &mut Frame<'_, f32>) {} + fn animating(&self) -> bool { true } + } + let mut overlay = width_overlay("resting runtime"); + overlay.compositor = Some(Box::new(Spin)); + let start = crate::time::now(); + let (animating, _) = overlay.step_frame(start, false); + let idle = idle_after(overlay.rt.core(), animating, Some(start + FRAME)); + assert!(idle && overlay.rests_now(idle, false)); + let (commits, instances, t) = (overlay.rt.stats.commits, overlay.rt.instances.len(), overlay.rt.t); + let (animating, dt) = overlay.rest_frame(start + FRAME); + assert!(!animating); + assert!((dt - FRAME.as_secs_f64()).abs() < 1e-6, "the compositor still steps the frame's time: {dt}"); + assert_eq!((overlay.rt.stats.commits, overlay.rt.instances.len()), (commits, instances)); + assert!((overlay.rt.t - t - FRAME.as_secs_f64()).abs() < 1e-6, "a compositor reading `t` sees it move"); + assert!(!overlay.rests_now(false, false), "the runtime asked for the frame"); + assert!(!overlay.rests_now(idle, true), "something marked the overlay dirty"); + overlay.rt.update(|width, _| *width = 20.0); + assert!(!overlay.rests_now(idle, false), "state changed"); + overlay.rt.frame(0.0); + overlay.rt.poll = Some(|_, _, _| false); + assert!(!overlay.rests_now(idle, false), "a poll runs on every frame drawn"); + overlay.rt.poll = None; + overlay.rt.update(|_, tx| tx.wake_after(std::time::Duration::from_secs(1))); + overlay.rt.frame(0.0); + assert!(!overlay.rests_now(idle, false), "a timer is pending"); +} + +#[cfg(target_os = "macos")] +#[test] +fn an_overlay_reads_its_occlusion_once_a_turn() { + let mut overlay = width_overlay("occlusion once"); + overlay.presence = Presence::Shown { occluded: false }; + overlay.sync_occlusion(); + assert!(overlay.occlusion_read && !overlay.presence.occluded()); + overlay.presence = Presence::Shown { occluded: true }; + overlay.sync_occlusion(); + assert!(overlay.presence.occluded(), "the turn's reading isn't taken again"); + overlay.occlusion_read = false; + overlay.sync_occlusion(); + assert!(!overlay.presence.occluded(), "the next turn reads it again"); +} + +/// A hidden overlay with `release_gpu_after` gives its GPU surface back that long after the hide +/// (macOS keeps it): the loop wakes then, and a second hide doesn't push the time back. +#[test] +fn release_gpu_after_counts_from_the_hide() { + use std::time::Duration; + fn view(_: &(), _: &mut Cx<()>) -> El { crate::el() } + let app = AppSpec::new("release after", (20.0, 20.0), || (), view); + let spec = OverlaySpec::new("release after", app.size, view).options(Default::default()).release_gpu_after(Duration::from_secs(5)); + let (mut overlay, _) = Overlay::new(spec, (), &app); + overlay.presence = Presence::Shown { occluded: false }; + let before = crate::time::now(); + overlay.hide(); + if cfg!(target_os = "macos") { + assert_eq!(overlay.presence.release_at(), None); + return; + } + let at = overlay.presence.release_at().expect("the release waits for its time"); + assert!(at >= before + Duration::from_secs(5)); + assert_eq!(overlay.wake_deadline(), Some(at), "the loop wakes for it"); + overlay.hide(); + assert_eq!(overlay.presence.release_at(), Some(at), "hiding a hidden overlay keeps the time"); + overlay.presence_due(at - Duration::from_millis(1)); + assert_eq!(overlay.presence.release_at(), Some(at), "not before its time"); + overlay.presence_due(at); + assert_eq!(overlay.presence.release_at(), None); +} + +#[test] +fn only_an_opted_in_overlay_takes_the_pointer_on_xwayland() { + use super::xwayland::xwayland_allowed; + assert!(xwayland_allowed(OverlayInput::None, KeyPolicy::None, false), "a HUD always may"); + assert!(!xwayland_allowed(OverlayInput::All, KeyPolicy::None, false), "off by default"); + assert!(!xwayland_allowed(OverlayInput::Regions, KeyPolicy::None, false)); + assert!(xwayland_allowed(OverlayInput::All, KeyPolicy::None, true)); + assert!(xwayland_allowed(OverlayInput::Regions, KeyPolicy::None, true)); + assert!(!xwayland_allowed(OverlayInput::All, KeyPolicy::OnDemand, true), "never keys"); +} + +/// A fade-out gives the GPU surface back only once the fade ends, so the exit plays out on the +/// window and its last frames reach the screen before the surface (and on Windows and macOS, +/// the window) goes; where windows don't fade, the hide releases at once. +#[test] +fn a_fade_out_releases_the_gpu_after_the_fade() { + use std::time::Duration; + fn view(_: &(), _: &mut Cx<()>) -> El { crate::el() } + let app = AppSpec::new("fade release", (20.0, 20.0), || (), view); + let spec = OverlaySpec::new("fade release", app.size, view).options(Default::default()).release_gpu_after(Duration::from_secs(5)); + let (mut overlay, _) = Overlay::new(spec, (), &app); + if cfg!(target_os = "macos") { return; } // A prewarmed macOS panel keeps its pixels instead. + overlay.presence = Presence::FadingOut { until: crate::time::now() + Duration::from_millis(200), length: Duration::from_millis(200), occluded: false }; + overlay.presence_due(crate::time::now()); + assert_eq!(overlay.presence.release_at(), None, "a fading overlay keeps its surface"); + overlay.presence = Presence::Shown { occluded: false }; + let before = crate::time::now(); + overlay.hide_fading(Duration::from_millis(200)); + if !cfg!(target_os = "windows") { + assert!(!overlay.presence.fading() && overlay.presence.release_at().is_some(), "no fade here: released at the hide"); + return; + } + let end = overlay.presence.fade_end().expect("fading"); + assert!(overlay.presence.drawing(), "frames keep drawing through the fade"); + assert_eq!(overlay.presence.release_at(), None, "nothing is released mid-fade"); + overlay.presence_due(end - Duration::from_millis(1)); + assert_eq!(overlay.presence.release_at(), None, "not before the fade ends"); + overlay.presence_due(end); + assert!(!overlay.presence.drawing()); + let at = overlay.presence.release_at().expect("released once the fade ends"); + assert!(at >= before + Duration::from_secs(5), "counted from the hide that ended the fade"); +} + +#[test] +fn a_windows_fade_steps_alpha_down_to_zero() { + use std::time::Duration; + let now = crate::time::now(); + let length = Duration::from_millis(200); + let end = now + length; + assert_eq!(fade_alpha(end, length, now), 255); + assert_eq!(fade_alpha(end, length, now + Duration::from_millis(100)), 128); + assert_eq!(fade_alpha(end, length, end), 0); + assert_eq!(fade_alpha(end, length, end + Duration::from_millis(50)), 0, "past the end stays clear"); + assert_eq!(fade_alpha(end, Duration::ZERO, now), 0); +} diff --git a/app/vendor/rune/crates/rune/src/overlay/options.rs b/app/vendor/rune/crates/rune/src/overlay/options.rs new file mode 100644 index 0000000..86af1a0 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/overlay/options.rs @@ -0,0 +1,344 @@ +//! Placement and input policy for native overlays. Coordinates inside a display are points. + +use crate::{Align, Cx, El, OverlaySpec, ScreenEdge}; + +/// An opaque display identity, valid for this event-loop session. Obtain it from `Display::id`. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct DisplayId(pub(crate) winit::monitor::MonitorHandle, Option<NativeDisplayId>); + +/// Native display identity. Windows handles retain their full pointer width. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum NativeDisplayId { + MacOS(u32), Windows(isize), + /// winit identifies X11 monitors by RandR CRTC. Output IDs can also be targeted below. + X11Crtc(u32), X11Output(u32), + /// Registry-global wl_output name, not a client-local protocol object ID. + Wayland(u32), +} + +impl DisplayId { + pub fn native_id(&self) -> Option<NativeDisplayId> { self.1 } + + pub(crate) fn from_monitor(monitor: winit::monitor::MonitorHandle, _wayland: bool) -> Self { + #[cfg(target_os = "macos")] + let native = { use winit::platform::macos::MonitorHandleExtMacOS; Some(NativeDisplayId::MacOS(monitor.native_id())) }; + #[cfg(target_os = "windows")] + let native = { use winit::platform::windows::MonitorHandleExtWindows; Some(NativeDisplayId::Windows(monitor.hmonitor())) }; + #[cfg(all(unix, not(target_os = "macos"), not(target_os = "ios"), not(target_os = "android")))] + let native = Some(if _wayland { + use winit::platform::wayland::MonitorHandleExtWayland; + NativeDisplayId::Wayland(monitor.native_id()) + } else { + use winit::platform::x11::MonitorHandleExtX11; + NativeDisplayId::X11Crtc(monitor.native_id()) + }); + #[cfg(any(target_os = "ios", target_os = "android", target_arch = "wasm32"))] + let native = None; + Self(monitor, native) + } +} + +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub enum DisplayTarget { + #[default] + Primary, + UnderPointer, + Id(DisplayId), + /// Resolve a native capture/display ID; disconnected IDs fall back to primary. + Native(NativeDisplayId), +} + +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum OverlayPlacement { + Edge { edge: ScreenEdge, margin: f32, align: Align, inset: f32 }, + /// Points from the selected display's top-left, not desktop pixels. The rect isn't kept + /// on that display, so on [`DisplayTarget::Primary`] it's a global rect that may sit on + /// any display: the space [`El::on_screen_layout`] reports in, so an overlay can open + /// exactly over an element of a window. On macOS one point space spans displays of any + /// scale, and the overlay draws at the backing scale of the display it lands on. + /// Elsewhere a rect off the primary display is exact only where displays share a scale. + Rect { x: f32, y: f32, width: f32, height: f32 }, + FullScreen, +} + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum OverlayLevel { + #[default] + Status, + AboveStatus, + /// Above Rune's status and picker overlays (macOS level 27). + AboveOverlays, +} + +/// Whether an overlay may take keyboard focus. `OverlayCapabilities::nonactivating_keys` says +/// whether the backend it got can. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum KeyPolicy { + /// Never takes keys; a click neither focuses nor activates it. + #[default] + None, + /// Permit `OverlayHandle::request_keys`, and a click on the overlay takes the keys too; + /// showing alone never requests focus. macOS: the panel becomes key without activating the + /// app. Wayland: layer-shell v4's on-demand keyboard interactivity; XWayland can't. X11: the + /// override-redirect window sets the input focus itself; when it hides, focus reverts to the + /// root window for the window manager to hand on. Windows: the window is made without + /// `WS_EX_NOACTIVATE`, and `request_keys` takes the foreground only when Windows lets this + /// process (it just had the user's input, or was given the right); a click always does. + OnDemand, +} + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum OverlayInput { + /// Preserve `OverlaySpec::interactive` (whole surface or complete pass-through). + #[default] + Legacy, + /// Pass every click through, and hear no hover. Following remains available when enabled; + /// use Regions without `.hit()` elements for a hover-only canvas. + None, + /// Only elements marked `El::hit()` intercept the pointer. + Regions, + All, +} + +impl OverlayInput { + pub(crate) fn resolved(self, interactive: bool) -> Self { + match self { Self::Legacy => if interactive { Self::All } else { Self::None }, other => other } + } +} + +/// An overlay shows its elements' [`Cursor`](crate::Cursor)s while the pointer is over a hit +/// area (with [`OverlayInput::Regions`], a hit region). On macOS that works for a non-key +/// overlay only while its app is frontmost, unless `rune` is built with the +/// `macos-background-cursor` feature, which uses private API (an App Store review risk). +#[derive(Clone, Debug, Default)] +pub struct OverlayOptions { + /// None preserves the spec's edge, margin, alignment and inset. + pub placement: Option<OverlayPlacement>, + pub display: DisplayTarget, + /// Re-resolve UnderPointer while visible. Unsupported on Wayland. + pub follow_pointer: bool, + pub level: OverlayLevel, + /// Native best effort, not a security boundary. Use the window number in capture filters. + /// Applies only while shown, including the exit fade. On macOS, hidden panels order out + /// before restoring sharing, even when prewarmed: alpha zero and a sharing reset alone + /// must not leave an excluded window on every Space. Exclusion resumes before ordering in. + /// `OverlayHandle::set_exclude_from_capture` changes it later. + pub exclude_from_capture: bool, + pub keys: KeyPolicy, + pub input: OverlayInput, + /// Create and warm a hidden native host on the event thread at startup. Desktop hosts + /// retain their window and GPU surface across hide/show (unless + /// `ConfiguredOverlay::release_gpu_when_hidden`); Wayland must recreate on hide. + /// macOS orders the panel in at alpha zero only for a scoped prewarm, then orders it out. + /// Initial preparation settles the view. Later reveals refresh content, geometry and + /// live values while preserving motion elapsed since each hidden commit. Hidden motion + /// catches up on poll/reveal without driving a frame loop. + pub prewarm: bool, + /// Wayland without layer-shell (GNOME): lets an overlay that takes pointer input show on + /// XWayland, as an override-redirect window that takes clicks in its input shape and never + /// keyboard focus. Off by default: connecting starts XWayland on GNOME, so a host opts in + /// explicitly, having checked that it already runs. `KeyPolicy::OnDemand` overlays still + /// can't use it. Read when the surface is made, at each show on Wayland; + /// `OverlayHandle::set_xwayland_input` changes it. + pub xwayland_input: bool, +} + +/// Keeps existing exhaustive `OverlaySpec` literals source compatible. +pub struct ConfiguredOverlay<T: 'static> { + pub spec: OverlaySpec<T>, + pub options: OverlayOptions, + pub on_key: Option<fn(&mut T, &crate::KeyEvent, &mut crate::Tx) -> bool>, + pub on_created: Option<Box<dyn FnMut(OverlayCreated)>>, + pub(crate) poll: Option<fn(&mut T, f64, &mut crate::Tx) -> bool>, + pub(crate) compositor: Option<Box<dyn crate::compose::Compositor<T>>>, + pub(crate) setup: Option<fn(&mut T, crate::Waker)>, + pub(crate) runtime: crate::app::RuntimeConfig<T>, + pub(crate) macos_level: Option<isize>, + pub(crate) animate_reveal: bool, + pub(crate) release_after: Option<std::time::Duration>, +} + +#[derive(Clone, Copy, Debug)] +pub struct OverlayCreated { + /// The actual macOS panel CGWindowID, available before its first show. + pub window_number: Option<u32>, + pub capabilities: OverlayCapabilities, +} + +impl<T: 'static> ConfiguredOverlay<T> { + pub fn on_focus(mut self, f: fn(&mut T, bool, &mut crate::Tx)) -> Self { self.runtime.on_focus = Some(f); self } + /// Composite this overlay's translucent fills, blurs, shadows, images, video and text in + /// sRGB (gamma) space instead of linear light, matching CSS and Core Animation (on by + /// default). With a `Compositor`, `Frame::srgb_blend` says which encoding its passes must + /// match. + pub fn srgb_blend(mut self, enabled: bool) -> Self { self.runtime.srgb_blend = enabled; self } + /// Called before each frame; true means state changed, not that another frame is due. + /// Defaults to the app's poll when its state type matches this overlay's. Other state + /// types have no inherited poll. Use `Tx::wake_after` for the next timed update; + /// deadlines also run while hidden, like the window host, without drawing. + pub fn poll(mut self, f: fn(&mut T, f64, &mut crate::Tx) -> bool) -> Self { self.poll = Some(f); self } + /// Draw every rendered overlay frame, including hidden prewarm frames, through this + /// compositor. `Frame::draw_ui` keeps the overlay's transparent clear. Runtime-only + /// hidden timer updates do not render or call the compositor. + pub fn compositor(mut self, compositor: impl crate::compose::Compositor<T>) -> Self { + self.compositor = Some(Box::new(compositor)); + self + } + pub fn on_key(mut self, f: fn(&mut T, &crate::KeyEvent, &mut crate::Tx) -> bool) -> Self { self.on_key = Some(f); self } + /// Like `App::modifier_keys`: send modifier keys pressed and released on their own + /// (`Key::Modifier`) to `on_key` and the focused input. Off by default. + pub fn modifier_keys(mut self) -> Self { self.runtime.modifier_keys = true; self } + /// Like `AppSpec::setup`: called once with a waker other threads use when new data arrives + /// (an `ImageCache` decode, a channel). It runs on the event thread when the event loop + /// starts, before the overlay's first frame and before updates queued through its handle. + /// Waking a shown overlay draws a frame, which polls; a hidden one runs a frame without + /// drawing. Headless runs don't create overlays, so they don't call it. + pub fn setup(mut self, f: fn(&mut T, crate::Waker)) -> Self { self.setup = Some(f); self } + /// Called on the event thread after native creation, before the first show, and again for + /// each window made later (Windows and macOS make a new one for each show with + /// `release_gpu_when_hidden`), so a window number in a capture filter stays current. + /// Use `prewarm: true` to create at startup rather than waiting for `show()`. + pub fn on_created(mut self, f: impl FnMut(OverlayCreated) + 'static) -> Self { self.on_created = Some(Box::new(f)); self } + /// Showing doesn't settle motion: what the state started while hidden plays from the + /// first visible frame, such as a notification stack's first card entering. By default + /// an unretained overlay shows settled, at its target. + pub fn animate_reveal(mut self) -> Self { self.animate_reveal = true; self } + /// While hidden, the overlay holds no GPU surface, swapchain or renderer. Each show makes the + /// surface, and each hide drops it. Away from macOS, the GPU device and renderer then wait + /// five minutes for the next surface (a window's or overlay's) before they go, so an overlay + /// shown often (a HUD on each dictation) keeps one device rather than making one per show + /// (hex#1268). On Windows and macOS the window comes and goes with the surface, and a + /// prewarmed one makes nothing at startup, so a hidden overlay there has no window at all + /// (NVIDIA's Instant Replay took a hidden display-sized window for a game on Windows, and + /// macOS 27's Mission Control lost its Space thumbnails to hidden screen-sized panels). On X11 + /// a prewarmed one makes only its window at startup and keeps it. A show then waits for the + /// surface (a few milliseconds), and with no device to take, for a new device and its + /// pipelines too (over half a second on some Windows PCs). For overlays that show rarely and + /// cover a display, such as a drawing layer or a picker: hidden, their swapchains hold tens + /// of megabytes. By default a prewarmed overlay makes its surface at startup and keeps it, + /// so it shows at once. + pub fn release_gpu_when_hidden(mut self) -> Self { self.release_after = Some(std::time::Duration::ZERO); self } + /// `release_gpu_when_hidden`, once the overlay has stayed hidden for `after`: shows in + /// a burst (a HUD across a few dictations) keep their surface and show at once, and an app + /// at rest gives the device back. A prewarmed one still makes its surface only to show. + /// macOS ignores it: a prewarmed panel retains its pixels at alpha zero. + pub fn release_gpu_after(mut self, after: std::time::Duration) -> Self { self.release_after = Some(after); self } + /// The macOS window level (`NSWindow.Level`, e.g. 3 for `.floating`), in place of + /// `OverlayOptions::level`; `OverlayHandle::set_macos_level` changes it later. At any + /// level a macOS overlay goes exactly where it's placed, over the menu bar too. + pub fn macos_level(mut self, level: isize) -> Self { self.macos_level = Some(level); self } +} + +impl<T: 'static> OverlaySpec<T> { + pub fn new(name: &'static str, size: (f32, f32), view: fn(&T, &mut Cx<T>) -> El) -> Self { + Self { name, size, edge: ScreenEdge::Top, margin: 0.0, align: Align::Center, inset: 0.0, interactive: false, view } + } + + pub fn options(self, options: OverlayOptions) -> ConfiguredOverlay<T> { + ConfiguredOverlay { + spec: self, options, on_key: None, on_created: None, poll: None, compositor: None, + setup: None, runtime: crate::app::RuntimeConfig::default(), macos_level: None, + animate_reveal: false, release_after: None, + } + } +} + +impl<T: 'static> From<OverlaySpec<T>> for ConfiguredOverlay<T> { + fn from(spec: OverlaySpec<T>) -> Self { spec.options(OverlayOptions::default()) } +} + +/// Native capability, distinct from whether an overlay could be created. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum OverlaySupport { + #[default] + Unknown, + Supported, + /// The OS accepted a capture-exclusion request; capture clients may still need a filter. + Requested, + Unsupported, + Failed, +} + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct OverlayCapabilities { + pub capture_exclusion: OverlaySupport, + pub nonactivating_keys: OverlaySupport, + pub global_pointer: OverlaySupport, +} + +/// Bounds in logical points, local to a display. Also shared by native placement tests. +pub(crate) fn local_rect(at: crate::overlay::Placement, placement: Option<OverlayPlacement>, area: (f32, f32)) -> [f32; 4] { + let (edge, margin, align, inset) = match placement { + Some(OverlayPlacement::FullScreen) => return [0.0, 0.0, area.0, area.1], + Some(OverlayPlacement::Rect { x, y, width, height }) => return [x, y, width.max(1.0), height.max(1.0)], + Some(OverlayPlacement::Edge { edge, margin, align, inset }) => (edge, margin, align, inset), + None => (at.edge, at.margin, at.align, at.inset), + }; + let (w, h) = (at.size.0.max(1.0), at.size.1.max(1.0)); + let x = match align { Align::Start => inset, Align::Center => (area.0 - w) / 2.0, Align::End => area.0 - w - inset }; + let y = match edge { ScreenEdge::Top => margin, ScreenEdge::Bottom => area.1 - h - margin }; + [x, y, w, h] +} + +pub(crate) fn contains(rect: [f32; 4], x: f32, y: f32) -> bool { + x >= rect[0] && y >= rect[1] && x < rect[2] && y < rect[3] +} + +/// Bounds and pointer share one native coordinate space. Never rescale desktop origins. +pub(crate) fn choose_display(bounds: &[[f64; 4]], primary: Option<usize>, requested: Option<usize>, pointer: Option<(f64, f64)>) -> Option<usize> { + requested.filter(|i| *i < bounds.len()).or_else(|| pointer.and_then(|(x, y)| { + bounds.iter().position(|r| x >= r[0] && y >= r[1] && x < r[2] && y < r[3]) + })).or(primary.filter(|i| *i < bounds.len())).or_else(|| (!bounds.is_empty()).then_some(0)) +} + +/// The scale of the display holding most of `frame` (`[x, y, w, h]`), as AppKit picks a +/// window's backing scale; `None` when it's on none. `displays` are `(frame, scale)` in the +/// same space. +#[cfg_attr(not(target_os = "macos"), allow(dead_code))] +pub(crate) fn scale_under(frame: [f64; 4], displays: &[([f64; 4], f64)]) -> Option<f64> { + let overlap = |d: [f64; 4]| { + let w = (frame[0] + frame[2]).min(d[0] + d[2]) - frame[0].max(d[0]); + let h = (frame[1] + frame[3]).min(d[1] + d[3]) - frame[1].max(d[1]); + w.max(0.0) * h.max(0.0) + }; + displays.iter().map(|&(d, scale)| (overlap(d), scale)).filter(|(area, _)| *area > 0.0) + .max_by(|a, b| a.0.total_cmp(&b.0)).map(|(_, scale)| scale) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_frame_takes_the_scale_of_the_display_holding_most_of_it() { + // A 2x laptop with a 1x monitor to its right, in one global space. + let displays = [([0.0, 0.0, 1512.0, 982.0], 2.0), ([1512.0, 0.0, 1920.0, 1080.0], 1.0)]; + assert_eq!(scale_under([100.0, 100.0, 400.0, 300.0], &displays), Some(2.0)); + assert_eq!(scale_under([1400.0, 100.0, 400.0, 300.0], &displays), Some(1.0), "mostly on the monitor"); + assert_eq!(scale_under([1400.0, 100.0, 200.0, 300.0], &displays), Some(2.0), "mostly on the laptop"); + assert_eq!(scale_under([-900.0, 0.0, 400.0, 300.0], &displays), None, "on no display"); + } + + #[test] + fn display_selection_handles_negative_origins_shared_edges_and_disconnects() { + // Native pixels, so a 2x display can have a larger rectangle than the primary. + let bounds = [[-3840.0, -200.0, 0.0, 1960.0], [0.0, 0.0, 1920.0, 1080.0]]; + assert_eq!(choose_display(&bounds, Some(1), None, Some((-100.0, 0.0))), Some(0)); + assert_eq!(choose_display(&bounds, Some(1), None, Some((0.0, 0.0))), Some(1)); + assert_eq!(choose_display(&bounds, Some(1), Some(0), None), Some(0)); + assert_eq!(choose_display(&bounds, Some(1), Some(4), None), Some(1)); + assert_eq!(choose_display(&bounds, None, None, None), Some(0)); + assert_eq!(choose_display(&[], None, None, None), None); + } + + #[test] + fn edge_and_rect_use_display_local_points() { + let at = crate::overlay::Placement { size: (300.0, 80.0), edge: ScreenEdge::Bottom, margin: 24.0, align: Align::End, inset: 12.0 }; + assert_eq!(local_rect(at, None, (960.0, 540.0)), [648.0, 436.0, 300.0, 80.0]); + assert_eq!(local_rect(at, Some(OverlayPlacement::FullScreen), (960.0, 540.0)), [0.0, 0.0, 960.0, 540.0]); + assert_eq!(local_rect(at, Some(OverlayPlacement::Rect { x: -10.0, y: 20.0, width: 100.0, height: 50.0 }), (960.0, 540.0)), [-10.0, 20.0, 100.0, 50.0]); + // A 2x display left of primary: scale local offsets, never the desktop origin. + let r = local_rect(at, None, (960.0, 540.0)); + assert_eq!((-1920 + (r[0] * 2.0) as i32, -100 + (r[1] * 2.0) as i32), (-624, 772)); + } +} diff --git a/app/vendor/rune/crates/rune/src/overlay/placement.rs b/app/vendor/rune/crates/rune/src/overlay/placement.rs new file mode 100644 index 0000000..a61cdf3 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/overlay/placement.rs @@ -0,0 +1,71 @@ +//! Where an overlay goes: its screen and its position on that screen's edge. + +use winit::dpi::PhysicalPosition; +use winit::event_loop::ActiveEventLoop; + +use super::{Placement, ScreenEdge}; +use crate::el::Align; +use crate::{DisplayTarget, OverlayOptions}; + +/// On the primary screen's top or bottom edge, `margin` points in, centred or `inset` points +/// from a side. +pub(super) fn position(event_loop: &ActiveEventLoop, at: Placement, options: &OverlayOptions) -> Option<PhysicalPosition<i32>> { + let monitor = monitor(event_loop, &options.display)?; + let scale = monitor.scale_factor(); + let (origin, area) = (monitor.position(), monitor.size()); + if options.placement.is_some() { + let r = crate::overlay::options::local_rect(at, options.placement, (area.width as f32 / scale as f32, area.height as f32 / scale as f32)); + return Some(PhysicalPosition::new(origin.x + (r[0] as f64 * scale).round() as i32, origin.y + (r[1] as f64 * scale).round() as i32)); + } + let px = |v: f32| (v as f64 * scale).round() as i32; + let (w, h) = (px(at.size.0), px(at.size.1)); + let x = match at.align { + Align::Start => origin.x + px(at.inset), + Align::Center => origin.x + (area.width as i32 - w) / 2, + Align::End => origin.x + area.width as i32 - w - px(at.inset), + }; + #[allow(unused_mut)] + let (mut top, mut bottom) = (origin.y, origin.y + area.height as i32); + // Inside the taskbar and app bars of whichever Windows display it's on. + #[cfg(target_os = "windows")] + if let Some(work) = crate::platform::win32::work_area(&monitor) { + (top, bottom) = work; + } + let y = match at.edge { + ScreenEdge::Top => top + px(at.margin), + ScreenEdge::Bottom => bottom - h - px(at.margin), + }; + Some(PhysicalPosition::new(x, y)) +} + +pub(super) fn monitor(event_loop: &ActiveEventLoop, target: &DisplayTarget) -> Option<winit::monitor::MonitorHandle> { + monitor_at(event_loop, target, None) +} + +pub(crate) fn monitor_at(event_loop: &ActiveEventLoop, target: &DisplayTarget, sampled: Option<(i32, i32)>) -> Option<winit::monitor::MonitorHandle> { + let monitors: Vec<_> = event_loop.available_monitors().collect(); + let primary = event_loop.primary_monitor().and_then(|p| monitors.iter().position(|m| *m == p)); + #[cfg(all(unix, not(target_os = "macos"), not(target_os = "ios"), not(target_os = "android")))] + let resolved = if let DisplayTarget::Native(crate::NativeDisplayId::X11Output(output)) = target { + if !crate::window::is_wayland(event_loop) { crate::platform::x11::overlay::output_crtc(*output).map(|id| DisplayTarget::Native(crate::NativeDisplayId::X11Crtc(id))) } else { None } + } else { None }; + #[cfg(all(unix, not(target_os = "macos"), not(target_os = "ios"), not(target_os = "android")))] + let target = resolved.as_ref().unwrap_or(target); + let requested = match target { + DisplayTarget::Id(id) => monitors.iter().position(|m| *m == id.0), + DisplayTarget::Native(id) => monitors.iter().position(|m| crate::DisplayId::from_monitor(m.clone(), crate::window::is_wayland(event_loop)).native_id() == Some(*id)), + _ => None, + }; + let bounds: Vec<_> = monitors.iter().map(|m| { + let (p, s) = (m.position(), m.size()); + [f64::from(p.x), f64::from(p.y), f64::from(p.x) + f64::from(s.width), f64::from(p.y) + f64::from(s.height)] + }).collect(); + #[cfg(target_os = "windows")] + let pointer = (*target == DisplayTarget::UnderPointer).then(crate::platform::win32::pointer_position).flatten(); + #[cfg(all(unix, not(target_os = "macos"), not(target_os = "ios"), not(target_os = "android")))] + let pointer = if *target == DisplayTarget::UnderPointer && !crate::window::is_wayland(event_loop) { crate::platform::x11::overlay::pointer_position() } else { None }; + #[cfg(any(target_os = "macos", target_os = "ios", target_os = "android", target_arch = "wasm32"))] + let pointer: Option<(i32, i32)> = None; + let i = crate::overlay::options::choose_display(&bounds, primary, requested, sampled.or(pointer).map(|(x, y)| (f64::from(x), f64::from(y))))?; + Some(monitors[i].clone()) +} diff --git a/app/vendor/rune/crates/rune/src/overlay/presence.rs b/app/vendor/rune/crates/rune/src/overlay/presence.rs new file mode 100644 index 0000000..00fcb7f --- /dev/null +++ b/app/vendor/rune/crates/rune/src/overlay/presence.rs @@ -0,0 +1,165 @@ +//! Whether an overlay is shown, hidden or fading out, and when a hidden one gives its GPU +//! surface back. The overlay carries the effects out: its display link, native window and +//! surface. + +use std::time::Duration; + +use crate::machine::Effects; +use crate::time::Instant; + +/// What a hidden overlay does with its GPU surface. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum Release { + /// Keeps it, and its pixels, for the next show. + Keep, + /// Gives it back as it hides (`release_gpu_when_hidden`). + Now, + /// Gives it back once it has stayed hidden this long (`release_gpu_after`). + After(Duration), +} + +impl Release { + /// From `ConfiguredOverlay`'s release delay. macOS honours only `release_gpu_when_hidden`: + /// a prewarmed panel with `release_gpu_after` (a HUD) retains its pixels. + pub(super) fn new(after: Option<Duration>) -> Release { + match after { + Some(after) if after.is_zero() => Release::Now, + Some(after) if !cfg!(target_os = "macos") => Release::After(after), + _ => Release::Keep, + } + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum Presence { + /// Takes no input and draws nothing. With [`Release::After`], its GPU surface goes at + /// `release_at`. + Hidden { release_at: Option<Instant> }, + /// Takes input and draws. `occluded` (macOS): none of it is on screen, covered or on + /// sleeping displays. + Shown { occluded: bool }, + /// Hidden by `OverlayHandle::fade_out`: takes no input but keeps drawing its exit until + /// `until`. `length` is the whole fade, for its alpha (Windows). A panel fading toward + /// alpha zero reads as covered, so it never becomes `occluded` mid-fade; one that was + /// stays so. + FadingOut { until: Instant, length: Duration, occluded: bool }, +} + +impl Default for Presence { + fn default() -> Self { Presence::Hidden { release_at: None } } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum Event { + /// The overlay is on screen now. + Show, + /// `hide` or `fade_out` at `now`; `fade` is zero where the platform doesn't fade windows. + Hide { fade: Duration, now: Instant }, + /// A deadline (`Presence::deadline`) may have passed. + Due { now: Instant }, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum Effect { + /// Its display link, timer frames and live values stop. + StopDrawing, + /// Input stops and the native window hides, fading over `fade`. + HideWindow { fade: Duration }, + /// Give the GPU surface back now. + ReleaseGpu, +} + +impl Presence { + pub(super) fn step(&mut self, event: Event, release: Release) -> Effects<Effect> { + match (*self, event) { + (Presence::Shown { .. }, Event::Show) => Effects::none(), + (_, Event::Show) => { + *self = Presence::Shown { occluded: false }; + Effects::none() + } + // Fading again restarts the fade, and the window's alpha with it. + (Presence::Shown { occluded } | Presence::FadingOut { occluded, .. }, Event::Hide { fade, now }) if !fade.is_zero() => { + *self = Presence::FadingOut { until: now + fade, length: fade, occluded }; + Effects::one(Effect::HideWindow { fade }) + } + (Presence::Hidden { .. }, Event::Hide { fade, .. }) => Effects::two(Effect::StopDrawing, Effect::HideWindow { fade }), + (_, Event::Hide { now, .. }) => self.hide_now(now, release), + (Presence::FadingOut { until, .. }, Event::Due { now }) if until <= now => self.hide_now(now, release), + (Presence::Hidden { release_at: Some(at) }, Event::Due { now }) if at <= now => { + *self = Presence::Hidden { release_at: None }; + Effects::one(Effect::ReleaseGpu) + } + (_, Event::Due { .. }) => Effects::none(), + } + } + + /// Shown or fading out, it hides now: drawing stops, then the window goes, and the GPU + /// surface now or later. A fade-out kept the surface until here, so the exit played out + /// on the window and its last frames reached the screen. + fn hide_now(&mut self, now: Instant, release: Release) -> Effects<Effect> { + let release_at = match release { + Release::After(after) => Some(now + after), + Release::Keep | Release::Now => None, + }; + *self = Presence::Hidden { release_at }; + let mut effects = Effects::two(Effect::StopDrawing, Effect::HideWindow { fade: Duration::ZERO }); + if release == Release::Now { effects.push(Effect::ReleaseGpu); } + effects + } + + /// Takes input: shown, not fading out. + pub(super) fn shown(&self) -> bool { matches!(self, Presence::Shown { .. }) } + + /// Shown, or fading out: frames still draw. + pub(super) fn drawing(&self) -> bool { !matches!(self, Presence::Hidden { .. }) } + + pub(super) fn fading(&self) -> bool { matches!(self, Presence::FadingOut { .. }) } + + pub(super) fn occluded(&self) -> bool { + matches!(self, Presence::Shown { occluded: true } | Presence::FadingOut { occluded: true, .. }) + } + + /// Takes an occlusion reading; false when it doesn't apply: a fading-out panel reads as + /// covered once its alpha nears zero, but it's still drawing its exit. A hidden overlay + /// keeps none, and a show reads it again. + #[cfg_attr(not(target_os = "macos"), allow(dead_code))] + pub(super) fn set_occluded(&mut self, covered: bool) -> bool { + match self { + Presence::FadingOut { .. } if covered => false, + Presence::Shown { occluded } | Presence::FadingOut { occluded, .. } => { + *occluded = covered; + true + } + Presence::Hidden { .. } => true, + } + } + + #[cfg(test)] + pub(super) fn fade_end(&self) -> Option<Instant> { + match *self { + Presence::FadingOut { until, .. } => Some(until), + _ => None, + } + } + + #[cfg(test)] + pub(super) fn release_at(&self) -> Option<Instant> { + match *self { + Presence::Hidden { release_at } => release_at, + _ => None, + } + } + + /// When `step` next wants a `Due`: the end of a fade-out, or a hidden surface's release. + pub(super) fn deadline(&self) -> Option<Instant> { + match *self { + Presence::Hidden { release_at } => release_at, + Presence::Shown { .. } => None, + Presence::FadingOut { until, .. } => Some(until), + } + } +} + +#[cfg(test)] +#[path = "presence_tests.rs"] +mod tests; diff --git a/app/vendor/rune/crates/rune/src/overlay/presence_tests.rs b/app/vendor/rune/crates/rune/src/overlay/presence_tests.rs new file mode 100644 index 0000000..c168ef6 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/overlay/presence_tests.rs @@ -0,0 +1,131 @@ +use std::time::Duration; + +use super::{Effect, Event, Presence, Release}; + +const FADE: Duration = Duration::from_millis(200); +const AFTER: Duration = Duration::from_secs(5); + +fn effects(presence: &mut Presence, event: Event, release: Release) -> Vec<Effect> { + presence.step(event, release).into_iter().collect() +} + +fn shown() -> Presence { Presence::Shown { occluded: false } } + +#[test] +fn a_fade_out_keeps_drawing_without_input_until_it_ends() { + let t0 = crate::time::now(); + let mut p = shown(); + assert_eq!(effects(&mut p, Event::Hide { fade: FADE, now: t0 }, Release::Now), [Effect::HideWindow { fade: FADE }], + "nothing stops and nothing is released while the exit plays"); + assert!(!p.shown() && p.drawing() && p.fading()); + assert_eq!(p.deadline(), Some(t0 + FADE)); + assert!(p.step(Event::Due { now: t0 + FADE / 2 }, Release::Now).is_empty()); + assert_eq!(effects(&mut p, Event::Due { now: t0 + FADE }, Release::Now), + [Effect::StopDrawing, Effect::HideWindow { fade: Duration::ZERO }, Effect::ReleaseGpu]); + assert_eq!(p, Presence::Hidden { release_at: None }); +} + +#[test] +fn hiding_at_once_stops_drawing_then_releases_by_policy() { + let t0 = crate::time::now(); + let hide = Event::Hide { fade: Duration::ZERO, now: t0 }; + let mut keep = shown(); + assert_eq!(effects(&mut keep, hide, Release::Keep), [Effect::StopDrawing, Effect::HideWindow { fade: Duration::ZERO }]); + assert_eq!(keep, Presence::Hidden { release_at: None }); + let mut later = shown(); + assert_eq!(effects(&mut later, hide, Release::After(AFTER)), [Effect::StopDrawing, Effect::HideWindow { fade: Duration::ZERO }]); + assert_eq!(later, Presence::Hidden { release_at: Some(t0 + AFTER) }); + assert!(later.step(Event::Due { now: t0 + AFTER / 2 }, Release::After(AFTER)).is_empty()); + assert_eq!(effects(&mut later, Event::Due { now: t0 + AFTER }, Release::After(AFTER)), [Effect::ReleaseGpu]); + assert_eq!(later.deadline(), None, "released once"); +} + +#[test] +fn showing_cancels_a_fade_and_its_end_is_stale() { + let t0 = crate::time::now(); + let mut p = shown(); + p.step(Event::Hide { fade: FADE, now: t0 }, Release::Now); + assert!(p.step(Event::Show, Release::Now).is_empty()); + assert_eq!(p, shown()); + assert!(p.step(Event::Due { now: t0 + FADE * 2 }, Release::Now).is_empty(), "the cancelled fade's end hides nothing"); + assert!(p.shown()); +} + +#[test] +fn showing_cancels_a_pending_release_and_its_time_is_stale() { + let t0 = crate::time::now(); + let release = Release::After(AFTER); + let mut p = shown(); + p.step(Event::Hide { fade: Duration::ZERO, now: t0 }, release); + p.step(Event::Show, release); + assert_eq!(p.deadline(), None); + let t1 = t0 + AFTER / 2; + p.step(Event::Hide { fade: Duration::ZERO, now: t1 }, release); + assert!(p.step(Event::Due { now: t0 + AFTER }, release).is_empty(), "the first hide's release time is past for nothing"); + assert_eq!(effects(&mut p, Event::Due { now: t1 + AFTER }, release), [Effect::ReleaseGpu]); +} + +#[test] +fn fading_again_restarts_the_fade() { + let t0 = crate::time::now(); + let mut p = shown(); + p.step(Event::Hide { fade: FADE, now: t0 }, Release::Keep); + let t1 = t0 + FADE / 2; + assert_eq!(effects(&mut p, Event::Hide { fade: FADE * 2, now: t1 }, Release::Keep), [Effect::HideWindow { fade: FADE * 2 }]); + assert_eq!(p, Presence::FadingOut { until: t1 + FADE * 2, length: FADE * 2, occluded: false }); + assert!(p.step(Event::Due { now: t0 + FADE }, Release::Keep).is_empty(), "the first fade's end is stale"); +} + +#[test] +fn hiding_mid_fade_without_one_ends_it_now() { + let t0 = crate::time::now(); + let mut p = shown(); + p.step(Event::Hide { fade: FADE, now: t0 }, Release::After(AFTER)); + let t1 = t0 + FADE / 2; + assert_eq!(effects(&mut p, Event::Hide { fade: Duration::ZERO, now: t1 }, Release::After(AFTER)), + [Effect::StopDrawing, Effect::HideWindow { fade: Duration::ZERO }]); + assert_eq!(p, Presence::Hidden { release_at: Some(t1 + AFTER) }); +} + +#[test] +fn hiding_a_hidden_overlay_leaves_its_release_alone() { + let t0 = crate::time::now(); + let mut p = Presence::Hidden { release_at: Some(t0 + AFTER) }; + assert_eq!(effects(&mut p, Event::Hide { fade: FADE, now: t0 + AFTER / 2 }, Release::After(AFTER)), + [Effect::StopDrawing, Effect::HideWindow { fade: FADE }], "nothing to fade, and no new release"); + assert_eq!(p, Presence::Hidden { release_at: Some(t0 + AFTER) }); + let mut never = Presence::default(); + assert_eq!(effects(&mut never, Event::Hide { fade: Duration::ZERO, now: t0 }, Release::Now), + [Effect::StopDrawing, Effect::HideWindow { fade: Duration::ZERO }], "a never-shown overlay keeps its prewarmed surface"); +} + +#[test] +fn a_fading_panel_never_becomes_covered_but_one_that_was_stays_so() { + let t0 = crate::time::now(); + let mut p = shown(); + p.step(Event::Hide { fade: FADE, now: t0 }, Release::Keep); + assert!(!p.set_occluded(true) && !p.occluded(), "a panel fading toward alpha zero isn't occluded"); + let mut covered = Presence::Shown { occluded: true }; + covered.step(Event::Hide { fade: FADE, now: t0 }, Release::Keep); + assert!(covered.occluded()); + assert!(covered.set_occluded(false) && !covered.occluded(), "uncovered mid-fade, it draws its exit"); +} + +#[test] +fn a_hidden_overlay_keeps_no_occlusion_and_a_show_reads_it_again() { + let mut p = Presence::default(); + assert!(p.set_occluded(true), "the reading still applies its side effects"); + assert!(!p.occluded()); + let mut covered = Presence::Shown { occluded: true }; + covered.step(Event::Hide { fade: Duration::ZERO, now: crate::time::now() }, Release::Keep); + covered.step(Event::Show, Release::Keep); + assert_eq!(covered, shown()); +} + +#[test] +fn release_follows_the_platform() { + assert_eq!(Release::new(None), Release::Keep); + assert_eq!(Release::new(Some(Duration::ZERO)), Release::Now); + let after = Release::new(Some(AFTER)); + if cfg!(target_os = "macos") { assert_eq!(after, Release::Keep) } else { assert_eq!(after, Release::After(AFTER)) } +} diff --git a/app/vendor/rune/crates/rune/src/overlay/requests.rs b/app/vendor/rune/crates/rune/src/overlay/requests.rs new file mode 100644 index 0000000..1035b27 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/overlay/requests.rs @@ -0,0 +1,61 @@ +//! What other threads ask of an overlay, applied on its next event-loop turn, and the +//! requests that change a live window's native options. + +use std::time::Duration; + +use crate::el::Tx; + +use super::OverlayCore; + +pub(super) type Update<T> = Box<dyn FnOnce(&mut T, &mut Tx) -> bool + Send>; + +/// A show or a hide, fading the window's alpha over its duration (zero: at once; see +/// `OverlayHandle::fade_in` and `fade_out` for where windows fade). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum Visibility { + Show(Duration), + Hide(Duration), +} + +#[derive(Default)] +pub(super) struct Requests { + pub input: Option<crate::OverlayInput>, + pub follow_pointer: Option<bool>, + pub placement: Option<Option<crate::OverlayPlacement>>, + pub display: Option<crate::DisplayTarget>, + pub request_keys: bool, + /// Move to the display under the pointer now (`OverlayHandle::refollow_pointer`). + pub refollow: bool, + /// The latest show or hide wins. + pub visibility: Option<Visibility>, + pub edge: Option<super::ScreenEdge>, + pub margin: Option<f32>, + pub align: Option<(crate::Align, f32)>, + pub size: Option<(f32, f32)>, + pub macos_level: Option<isize>, + pub exclude_from_capture: Option<bool>, + pub xwayland_input: Option<bool>, + /// The `setup` waker fired. + pub woken: bool, +} + +#[cfg(test)] +impl Requests { + /// Whether the latest request shows (`Some(true)`) or hides the overlay. + pub fn visible(&self) -> Option<bool> { self.visibility.map(|v| matches!(v, Visibility::Show(_))) } +} + +impl OverlayCore { + /// Keeps the window out of screen recordings, or lets recorders see it again. A window + /// made later (Wayland recreates on hide) starts from the same option. + pub(super) fn set_capture_exclusion(&mut self, exclude: bool) { + self.options.exclude_from_capture = exclude; + #[cfg(target_os = "macos")] + let support = self.panel.as_ref().map(|panel| panel.set_capture_exclusion(exclude)); + #[cfg(target_os = "windows")] + let support = self.native.as_mut().map(|native| native.set_capture_exclusion(exclude)); + #[cfg(not(any(target_os = "macos", target_os = "windows")))] + let support: Option<crate::OverlaySupport> = None; + if let Some(support) = support { self.shared.native.lock().unwrap().1.capture_exclusion = support; } + } +} diff --git a/app/vendor/rune/crates/rune/src/overlay/state_walk_tests.rs b/app/vendor/rune/crates/rune/src/overlay/state_walk_tests.rs new file mode 100644 index 0000000..adf19f6 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/overlay/state_walk_tests.rs @@ -0,0 +1,626 @@ +//! Every short sequence of what reaches an overlay's frame and surface state, driven through +//! `Quiet`, `turn`, `Surface` and `Backoff`, checked after every event against a literal +//! transcription of the fields and branches they replaced. + +use std::time::Duration; + +use super::frame::{Gate, Quiet, QuietEffect, QuietEvent, Turn, turn}; +use crate::window::{Backoff, BackoffEvent, Missed, OCCLUDED_MAX, OCCLUDED_RETRY, TIMEOUT_RETRY, TIMER_FRAME}; +use super::surface::{Surface, SurfaceEffect}; +use crate::time::Instant; + +/// Every sequence of `alphabet` up to `len` long, prefixes first. +fn walk<E: Copy>(alphabet: &[E], len: usize, mut run: impl FnMut(&[E])) { + let mut seq = Vec::new(); + fn go<E: Copy>(alphabet: &[E], len: usize, seq: &mut Vec<E>, run: &mut impl FnMut(&[E])) { + run(seq); + if seq.len() == len { return; } + for &e in alphabet { + seq.push(e); + go(alphabet, len, seq, run); + seq.pop(); + } + } + go(alphabet, len, &mut seq, &mut run); +} + +#[derive(Clone, Copy, Debug)] +enum QuietOp { + /// `wake_due` with a due timer and a frame coming; `resting`: `idle && !dirty`. + TimerDue { resting: bool }, + /// A `draw_frame`: `None` returns before presenting (or draws nothing new), `Some(rests)` + /// presents a frame the overlay may rest on. + Draw { presents: Option<bool> }, + /// `occluded` or `stop_drawing`. + Forget, +} + +/// origin/dev's `frame::Quiet`, as it was. +#[derive(Default)] +struct DevQuiet { + timer: bool, + presented: Option<u32>, +} + +impl DevQuiet { + /// Returns the frame's quiet candidate and what `Presented::record` was handed. + fn apply(&mut self, op: QuietOp, n: u32) -> (Option<u32>, Option<Option<u32>>) { + match op { + QuietOp::TimerDue { resting } => { + self.timer |= resting; + (None, None) + } + QuietOp::Draw { presents } => { + let timer = std::mem::take(&mut self.timer); + let candidate = self.presented.filter(|_| timer); + let mut seen = None; + if let Some(rests) = presents { + if rests { + seen = Some(self.presented); + *self.presented.get_or_insert(n) = n; + } else { + self.presented = None; + } + } + (candidate, seen) + } + QuietOp::Forget => { + *self = Default::default(); + (None, None) + } + } + } +} + +fn apply_quiet(quiet: &mut Quiet<u32>, op: QuietOp, n: u32) -> (Option<u32>, Option<Option<u32>>) { + match op { + QuietOp::TimerDue { resting } => { + assert!(quiet.step(QuietEvent::TimerDue { resting }).is_empty()); + (None, None) + } + QuietOp::Draw { presents } => { + let timer = match quiet.step(QuietEvent::FrameStarts).into_iter().next() { + Some(QuietEffect::TimerFrame) => true, + None => false, + }; + let candidate = quiet.presented().copied().filter(|_| timer); + let mut seen = None; + if let Some(rests) = presents { + quiet.presented_frame(rests, |slot| { + seen = Some(*slot); + *slot.get_or_insert(n) = n; + }); + } + (candidate, seen) + } + QuietOp::Forget => { + assert!(quiet.step(QuietEvent::Forget).is_empty()); + (None, None) + } + } +} + +#[test] +fn quiet_matches_dev_for_every_sequence() { + let alphabet = [ + QuietOp::TimerDue { resting: false }, + QuietOp::TimerDue { resting: true }, + QuietOp::Draw { presents: None }, + QuietOp::Draw { presents: Some(false) }, + QuietOp::Draw { presents: Some(true) }, + QuietOp::Forget, + ]; + let mut cases = 0; + walk(&alphabet, 6, |seq| { + cases += 1; + let (mut dev, mut quiet) = (DevQuiet::default(), Quiet::<u32>::default()); + for (i, &op) in seq.iter().enumerate() { + let n = i as u32 + 1; + assert_eq!(apply_quiet(&mut quiet, op, n), dev.apply(op, n), "{seq:?} at {i}"); + assert_eq!(quiet.presented().copied(), dev.presented, "{seq:?} at {i}"); + // Dev's timer with nothing presented was never read: the next frame took it first. + let timer = matches!(quiet, Quiet::Rests { timer: true, .. }); + assert_eq!(timer, dev.timer && dev.presented.is_some(), "{seq:?} at {i}"); + } + }); + assert_eq!(cases, (0..=6).map(|k| 6usize.pow(k)).sum::<usize>()); +} + +/// origin/dev's `Missed::retry` for an occluded miss: waits `occluded_wait` out (held to +/// `OCCLUDED_RETRY..=OCCLUDED_MAX`), then doubles it. +fn dev_occluded_retry(now: Instant, wait: &mut Duration) -> Option<Instant> { + let at = now + (*wait).clamp(OCCLUDED_RETRY, OCCLUDED_MAX); + *wait = (*wait * 2).min(OCCLUDED_MAX); + Some(at) +} + +/// origin/dev's `draw_frame` from the occlusion read to the drawable, as it was (after +/// `sync_occlusion`, which only sets `occluded` on macOS): whether it returned, whether it +/// counted an occluded miss, and the retry it left. An occluded miss runs `missed`, which +/// schedules the next re-check and backs off. +fn dev_gate(prewarm: bool, occluded: bool, dirty: bool, idle: bool, retry: &mut Option<Instant>, wait: &mut Duration, now: Instant) -> (bool, bool, Option<Instant>) { + if !prewarm && occluded { + if retry.is_none_or(|retry| retry <= now) { + *retry = dev_occluded_retry(now, wait); + return (true, true, *retry); + } + return (true, false, *retry); + } + if !dirty && idle { return (true, false, *retry); } + if !prewarm && retry.is_some_and(|retry| retry > now) { return (true, false, *retry); } + if !prewarm { *retry = None; } + (false, false, *retry) +} + +/// `draw_frame`'s arms for each answer, as the branch writes them: an occluded miss steps the +/// backoff, and a drawn frame clears the wait before it takes its drawable. +fn ours_gate(decided: Turn, prewarm: bool, backoff: &mut Backoff, now: Instant) -> (bool, bool, Option<Instant>) { + match decided { + Turn::Occluded { recheck } => { + if recheck { backoff.step(BackoffEvent::Missed { missed: Missed::Occluded, paced: false, now }); } + (true, recheck, backoff.deadline()) + } + Turn::Rest | Turn::BackedOff => (true, false, backoff.deadline()), + Turn::Draw => { + if !prewarm { backoff.step(BackoffEvent::Lapsed); } + (false, false, backoff.deadline()) + } + } +} + +/// A backoff the overlay starts with: it may draw again at `at`, and its occluded wait starts +/// at `wait` (as a long covered spell leaves it, or as dev's fields did). +fn backoff_start(at: Option<Instant>, wait: Duration) -> Backoff { + let mut backoff = Backoff::seeded(wait, TIMEOUT_RETRY); + if let Some(at) = at { backoff.step(BackoffEvent::At(at)); } + backoff +} + +/// The occluded wait behind `backoff`'s deadline, which no query shows: a miss now, on a copy. +fn occluded_wait(backoff: Backoff, now: Instant) -> Duration { + let mut probe = backoff; + probe.step(BackoffEvent::Missed { missed: Missed::Occluded, paced: false, now }); + probe.deadline().expect("an occluded miss always re-checks") - now +} + +#[test] +fn turn_matches_dev_for_every_gate() { + let now = crate::time::now(); + let ms = Duration::from_millis(1); + let retries = [None, Some(now - ms), Some(now), Some(now + ms)]; + let waits = [OCCLUDED_RETRY, Duration::from_millis(600), OCCLUDED_MAX]; + let mut cases = 0; + for bits in 0..16u8 { + let [prewarm, occluded, dirty, idle] = [0, 1, 2, 3].map(|b| bits & (1 << b) != 0); + for start in retries { + for start_wait in waits { + cases += 1; + let reads = std::cell::Cell::new(0); + let decided = turn(Gate { prewarm, occluded, dirty, idle, retry: start, missed_this_turn: false }, || { reads.set(reads.get() + 1); now }); + let (mut dev_retry, mut dev_wait) = (start, start_wait); + let mut ours = backoff_start(start, start_wait); + let arms = ours_gate(decided, prewarm, &mut ours, now); + assert_eq!(arms, dev_gate(prewarm, occluded, dirty, idle, &mut dev_retry, &mut dev_wait, now), "{decided:?} {prewarm} {occluded} {dirty} {idle} {start:?} {start_wait:?}"); + assert_eq!(occluded_wait(ours, now), dev_wait, "the wait it leaves: {decided:?} {start_wait:?}"); + assert!(reads.get() <= 1 && (start.is_some() || reads.get() == 0), "the clock is read only to compare a retry"); + } + } + } + assert_eq!(cases, 192); +} + +/// Each event happens `delta` after the last, so a re-check comes due and misses again, backing +/// the wait off towards its cap. +#[derive(Clone, Copy, Debug)] +struct TurnOp { delta: Duration, occluded: bool } + +#[test] +fn occluded_misses_back_off_like_dev() { + let base = crate::time::now(); + let alphabet = [ + TurnOp { delta: Duration::ZERO, occluded: true }, + TurnOp { delta: Duration::from_millis(100), occluded: true }, + TurnOp { delta: Duration::from_millis(260), occluded: true }, + TurnOp { delta: Duration::from_secs(3), occluded: true }, + TurnOp { delta: Duration::from_secs(3), occluded: false }, + ]; + walk(&alphabet, 5, |seq| { + let mut dev = (None, OCCLUDED_RETRY); + let mut ours = backoff_start(None, OCCLUDED_RETRY); + let mut now = base; + for (i, &op) in seq.iter().enumerate() { + now = now + op.delta; + let decided = turn(Gate { prewarm: false, occluded: op.occluded, dirty: false, idle: true, retry: ours.deadline(), missed_this_turn: false }, || now); + let ours_arms = ours_gate(decided, false, &mut ours, now); + let dev_arms = dev_gate(false, op.occluded, false, true, &mut dev.0, &mut dev.1, now); + assert_eq!(ours_arms, dev_arms, "{seq:?} at {i}"); + assert_eq!(ours.deadline(), dev.0, "{seq:?} at {i}"); + assert_eq!(occluded_wait(ours, now), dev.1, "{seq:?} at {i}"); + } + }); +} + +/// origin/dev's overlay fields, as they were: `retry` and `occluded_wait`, written by `missed`, +/// `wake_due`, `draw_frame`, `stop_drawing`, a show and an occlusion change. +#[derive(Clone, Copy)] +struct DevBackoff { + retry: Option<Instant>, + wait: Duration, +} + +impl DevBackoff { + fn new(wait: Duration) -> Self { DevBackoff { retry: None, wait } } + + /// `missed`, through origin/dev's `Missed::retry` rule copied literally (above). + fn missed(&mut self, missed: Missed, paced: bool, now: Instant) { + self.retry = match missed { + Missed::Occluded => dev_occluded_retry(now, &mut self.wait), + Missed::Timeout if paced => None, + Missed::Timeout => Some(now + TIMEOUT_RETRY), + Missed::Outdated | Missed::Unconfigured => Some(now + OCCLUDED_RETRY), + }; + } +} + +/// One thing that reached the overlay's wait, as `overlay/input.rs`, `overlay/draw.rs` and +/// `overlay/lifetime.rs` fed it. +#[derive(Clone, Copy, Debug)] +enum BackoffOp { + /// `missed`: a shown frame got no drawable. `paced`: a display link runs, whose next tick + /// draws the frame itself. + Missed { missed: Missed, paced: bool }, + /// `wake_due`: a retry due at the manual clock is cleared and asks for a frame. + Due, + /// `draw_frame`: the frame draws (`presents`: and presents), clearing the wait first. + Frame { presents: bool }, + /// A timer paces motion with no display link to pace it (macOS). + At, + /// `occluded(false)` or a show: the occluded wait starts over; a wait stands. + Reveal, + /// `stop_drawing`, on hide: nothing waits. + Stop, +} + +/// Both sides take `seq` on a manual clock, checked after every event. `prewarm`: a prewarm +/// frame, which leaves the wait alone. `scale`: how far each event is from the last. +fn holds_up(seq: &[BackoffOp], prewarm: bool, scale: u32) { + let t0 = crate::time::now(); + let mut dev = DevBackoff::new(OCCLUDED_RETRY); + let mut ours = Backoff::default(); + for (k, &op) in seq.iter().enumerate() { + let now = t0 + Duration::from_millis(11) * scale * k as u32; + match op { + BackoffOp::Missed { missed, paced } => { + let effect = ours.step(BackoffEvent::Missed { missed, paced, now }); + dev.missed(missed, paced, now); + assert_eq!(!effect.is_empty(), dev.retry.is_some(), "a wait stops the display link: {op:?} at {k}"); + } + BackoffOp::Due => { + if ours.deadline().is_some_and(|at| at <= now) { ours.step(BackoffEvent::Lapsed); } + if dev.retry.is_some_and(|at| at <= now) { dev.retry = None; } + } + BackoffOp::Frame { presents } => { + if !prewarm { + ours.step(BackoffEvent::Lapsed); + dev.retry = None; + } + if presents && !prewarm { + ours.step(BackoffEvent::Presented); + dev.wait = OCCLUDED_RETRY; + } + } + BackoffOp::At => if !prewarm { + ours.step(BackoffEvent::At(now + TIMER_FRAME)); + dev.retry = Some(now + TIMER_FRAME); + }, + BackoffOp::Reveal => { + ours.step(BackoffEvent::Revealed); + dev.wait = OCCLUDED_RETRY; + } + BackoffOp::Stop => { + ours.step(BackoffEvent::Lapsed); + dev.retry = None; + } + } + assert_eq!(ours.deadline(), dev.retry, "{op:?} at {k}, prewarm {prewarm}, scale {scale}"); + assert_eq!(ours.waiting(now), dev.retry.is_some_and(|at| at > now), "waiting after {op:?} at {k}"); + assert_eq!(occluded_wait(ours, now), dev.wait, "the wait after {op:?} at {k}, prewarm {prewarm}"); + } +} + +#[test] +fn overlay_backoff_matches_dev_for_every_sequence() { + let alphabet = [ + BackoffOp::Missed { missed: Missed::Occluded, paced: false }, + BackoffOp::Missed { missed: Missed::Timeout, paced: false }, + BackoffOp::Missed { missed: Missed::Timeout, paced: true }, + BackoffOp::Missed { missed: Missed::Outdated, paced: false }, + BackoffOp::Missed { missed: Missed::Unconfigured, paced: false }, + BackoffOp::Due, + BackoffOp::Frame { presents: false }, + BackoffOp::Frame { presents: true }, + BackoffOp::At, + BackoffOp::Reveal, + BackoffOp::Stop, + ]; + // Sparse events leave waits pending; a slow clock runs them out and climbs to the cap. + for (prewarm, scale) in [(false, 1), (true, 1), (false, 64)] { + walk(&alphabet, 5, |seq| holds_up(seq, prewarm, scale)); + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Platform { Mac, Windows, X11, Wayland } + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Kind { Window, Layer } + +/// A window or surface, numbered by the step that made it. +type Made = (u32, Kind); + +/// Which owner gave the window back on `release`. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Owner { Live, Parked } + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Outcome { + /// The window is made, its GPU surface attaches, and its new scale configures. + Ok, + /// No native window. + Window, + /// The window is made; attaching its GPU surface fails. + Attach, + /// The surface attaches; configuring it at the overlay's scale fails. + Rescale, +} + +#[derive(Clone, Copy, Debug)] +enum SurfaceOp { + /// `prepare(showing)`. + Prepare { showing: bool, outcome: Outcome }, + /// `hide_window`'s surface: a layer or XWayland surface goes with the hide. + HideWindow, + /// `park`, for `release_gpu_when_hidden`. + Park, + /// `release`: `surface_refused` or the overlay dropping. + Release, +} + +#[derive(Clone, Copy)] +struct Config { platform: Platform, defers: bool, callback: bool } + +/// origin/dev's `live`, `parked` and `announced`, written as `prepare`, `window`, `unpark`, +/// `ready`, `hide_window`, `park` and `release` wrote them. +#[derive(Default)] +struct DevSurface { + live: Option<Made>, + parked: Option<Made>, + announced: bool, + heard: Vec<Option<Made>>, + released: Vec<(Owner, Made)>, +} + +impl DevSurface { + fn apply(&mut self, c: Config, op: SurfaceOp, n: u32) { + let kind = if c.platform == Platform::Wayland { Kind::Layer } else { Kind::Window }; + match op { + SurfaceOp::Prepare { showing, outcome } => { + if self.live.is_some() { return; } + let (creation, attach, rescale) = match outcome { + Outcome::Ok => (true, true, true), + Outcome::Window => (false, true, true), + Outcome::Attach => (true, false, true), + Outcome::Rescale => (true, true, false), + }; + let surface = showing || !c.defers; + let parks = c.platform == Platform::X11; + if !surface && !parks { return; } + let made = if c.platform == Platform::Wayland { + creation.then_some((n, kind)) + } else if self.parked.is_some() || self.window(c, creation, attach, n) { + match self.live.take() { + Some(live) => Some(live), + None if surface => self.unpark(attach), + None => return self.ready(c), + } + } else { + None + }; + if let Some(live) = made { + self.live = Some(live); + // The surface's display scale is known now; one that can't take it leaves + // the overlay live but not ready, so nothing is announced. + if live.1 == Kind::Window && !rescale { return; } + self.ready(c); + } + } + SurfaceOp::HideWindow => { + let Some(live) = &self.live else { return }; + if live.1 == Kind::Layer { self.live.take(); } + } + SurfaceOp::Park => { + if !matches!(self.live, Some((_, Kind::Window))) { return; } + if matches!(c.platform, Platform::Mac | Platform::Windows) { + self.release(); + } else { + let Some(live) = self.live.take() else { return }; + self.parked = Some(live); + } + } + SurfaceOp::Release => self.release(), + } + } + + /// Failing to make the window leaves nothing; failing to attach its surface parks nothing. + fn window(&mut self, c: Config, creation: bool, attach: bool, n: u32) -> bool { + if !creation { return false; } + if c.platform == Platform::Mac { + if !attach { return false; } + self.live = Some((n, Kind::Window)); + } else { + self.parked = Some((n, Kind::Window)); + } + true + } + + fn unpark(&mut self, attach: bool) -> Option<Made> { + let window = self.parked.take()?; + if attach { return Some(window); } + self.parked = Some(window); + None + } + + fn ready(&mut self, c: Config) { + if !self.announced && c.callback { + self.announced = true; + self.heard.push(self.live.or(self.parked)); + } + } + + fn release(&mut self) { + let released = self.live.take().map(|live| (Owner::Live, live)).or_else(|| self.parked.take().map(|backing| (Owner::Parked, backing))); + self.released.extend(released); + self.announced = false; + } +} + +/// `Overlay`'s same functions, through `Surface` as they now write it. +struct Ours { + surface: Surface<Made, Made>, + heard: Vec<Option<Made>>, + released: Vec<(Owner, Made)>, +} + +impl Ours { + fn apply(&mut self, c: Config, op: SurfaceOp, n: u32) { + let kind = if c.platform == Platform::Wayland { Kind::Layer } else { Kind::Window }; + match op { + SurfaceOp::Prepare { showing, outcome } => { + if self.surface.live().is_some() { return; } + let (creation, attach, rescale) = match outcome { + Outcome::Ok => (true, true, true), + Outcome::Window => (false, true, true), + Outcome::Attach => (true, false, true), + Outcome::Rescale => (true, true, false), + }; + let surface = showing || !c.defers; + let parks = c.platform == Platform::X11; + if !surface && !parks { return; } + let made = if c.platform == Platform::Wayland { + creation.then_some((n, kind)) + } else if self.surface.parked().is_some() || self.window(c, creation, attach, n) { + match self.surface.take_live() { + Some(live) => Some(live), + None if surface => self.unpark(attach), + None => return self.ready(c), + } + } else { + None + }; + if let Some(live) = made { + self.surface.made(live); + if live.1 == Kind::Window && !rescale { return; } + self.ready(c); + } + } + SurfaceOp::HideWindow => { + let Some(live) = self.surface.live() else { return }; + if live.1 == Kind::Layer { self.surface.take_live(); } + } + SurfaceOp::Park => { + if !matches!(self.surface.live(), Some((_, Kind::Window))) { return; } + if matches!(c.platform, Platform::Mac | Platform::Windows) { + self.release(); + } else { + let Some(live) = self.surface.take_live() else { return }; + self.surface.park(live); + } + } + SurfaceOp::Release => self.release(), + } + } + + fn window(&mut self, c: Config, creation: bool, attach: bool, n: u32) -> bool { + if !creation { return false; } + if c.platform == Platform::Mac { + if !attach { return false; } + self.surface.made((n, Kind::Window)); + } else { + self.surface.park((n, Kind::Window)); + } + true + } + + fn unpark(&mut self, attach: bool) -> Option<Made> { + let window = self.surface.take_parked()?; + if attach { return Some(window); } + self.surface.park(window); + None + } + + fn ready(&mut self, c: Config) { + if !self.surface.announced() && c.callback { + self.surface.announce(); + self.heard.push(self.surface.live().or(self.surface.parked()).copied()); + } + } + + fn release(&mut self) { + match self.surface.release() { + Some(SurfaceEffect::Live(live)) => self.released.push((Owner::Live, live)), + Some(SurfaceEffect::Parked(backing)) => self.released.push((Owner::Parked, backing)), + None => {} + } + } +} + +#[test] +fn surface_matches_dev_for_every_sequence() { + let alphabet = [ + SurfaceOp::Prepare { showing: false, outcome: Outcome::Ok }, + SurfaceOp::Prepare { showing: true, outcome: Outcome::Ok }, + SurfaceOp::Prepare { showing: false, outcome: Outcome::Window }, + SurfaceOp::Prepare { showing: true, outcome: Outcome::Window }, + SurfaceOp::Prepare { showing: false, outcome: Outcome::Attach }, + SurfaceOp::Prepare { showing: true, outcome: Outcome::Attach }, + SurfaceOp::Prepare { showing: false, outcome: Outcome::Rescale }, + SurfaceOp::Prepare { showing: true, outcome: Outcome::Rescale }, + SurfaceOp::HideWindow, + SurfaceOp::Park, + SurfaceOp::Release, + ]; + // Each failure leaves a different state, so the walk must reach all of them. + let (mut parked_after_attach, mut live_after_rescale) = (0, 0); + let (mut released_live, mut released_parked) = (0, 0); + for platform in [Platform::Mac, Platform::Windows, Platform::X11, Platform::Wayland] { + for (defers, callback) in [(false, false), (false, true), (true, false), (true, true)] { + let c = Config { platform, defers, callback }; + walk(&alphabet, 5, |seq| { + let mut dev = DevSurface::default(); + let mut ours = Ours { surface: Surface::default(), heard: Vec::new(), released: Vec::new() }; + for (i, &op) in seq.iter().enumerate() { + let n = i as u32 + 1; + let (before_live, before_released) = (dev.live, dev.released.len()); + dev.apply(c, op, n); + ours.apply(c, op, n); + if let SurfaceOp::Prepare { outcome, .. } = op { + if outcome == Outcome::Attach && before_live.is_none() && dev.parked.is_some() { parked_after_attach += 1; } + if outcome == Outcome::Rescale && before_live.is_none() && dev.live.is_some() { live_after_rescale += 1; } + } + for &(owner, _) in &dev.released[before_released..] { + if owner == Owner::Live { released_live += 1; } else { released_parked += 1; } + } + let at = || format!("{platform:?} defers {defers} callback {callback}: {seq:?} at {i}"); + assert_eq!(ours.surface.live().map(|live| *live), dev.live, "{}", at()); + assert_eq!(ours.surface.parked().map(|backing| *backing), dev.parked, "{}", at()); + assert_eq!(ours.surface.announced(), dev.announced, "{}", at()); + assert_eq!(ours.heard, dev.heard, "{}", at()); + assert_eq!(ours.released, dev.released, "{}", at()); + } + }); + } + } + assert!(parked_after_attach > 0, "an attach that fails leaves its window parked"); + assert!(live_after_rescale > 0, "a rescale that fails leaves the overlay live"); + assert!(released_live > 0 && released_parked > 0, "release gives a live or a parked window back"); +} diff --git a/app/vendor/rune/crates/rune/src/overlay/surface.rs b/app/vendor/rune/crates/rune/src/overlay/surface.rs new file mode 100644 index 0000000..3b8c286 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/overlay/surface.rs @@ -0,0 +1,380 @@ +//! An overlay's GPU surface: making it (and the device, for the first), resizing it, and +//! dropping it with the native window's owners. + +use super::*; +use crate::machine::Effects; + +/// What the overlay holds of its native window. On macOS, and for a Wayland layer or XWayland +/// surface, the window is made with its GPU surface; elsewhere it waits `Parked` for one, as it +/// does on X11 once a hidden overlay gives its GPU back. +/// +/// `announced`: `on_created` heard of the native window. Releasing the window's owners +/// (`Overlay::release`) clears it, so the next window made is announced; a hide that destroys a +/// Wayland surface without that release leaves it set. +pub(super) enum Surface<L = Live, B = Backing> { + /// No native window: none made yet, or released or destroyed since. + None { announced: bool }, + /// The native window without a GPU surface. + Parked { backing: B, announced: bool }, + /// The native window and its GPU surface. + Live { live: L, announced: bool }, +} + +impl<L, B> Default for Surface<L, B> { + fn default() -> Self { Surface::None { announced: false } } +} + +#[derive(Debug, PartialEq, Eq)] +pub(super) enum SurfaceEvent<L = Live, B = Backing> { + /// A window was made with its GPU surface, or a parked one got its surface. It holds no + /// window then. + Made(L), + /// A window without a GPU surface waits: just made, given its GPU back, or its surface + /// failed. It holds no other window then. + Park(B), + /// The live window and surface go: parked again, or a Wayland surface destroyed on hide. + TakeLive, + /// The parked window goes to be given a surface. + TakeParked, + /// `on_created` hears of the native window. + Announce, + /// The window's owners are released: the next window made is announced again. + Release, +} + +/// What leaves the overlay's hold, for the caller to keep or drop in its order. +#[derive(Debug, PartialEq, Eq)] +pub(super) enum SurfaceEffect<L = Live, B = Backing> { + Live(L), + Parked(B), +} + +impl<L, B> Surface<L, B> { + pub(super) fn step(&mut self, event: SurfaceEvent<L, B>) -> Effects<SurfaceEffect<L, B>> { + let announced = self.announced(); + match event { + SurfaceEvent::Made(live) => { + debug_assert!(matches!(self, Surface::None { .. }), "an overlay makes a window only while it holds none"); + *self = Surface::Live { live, announced }; + } + SurfaceEvent::Park(backing) => { + debug_assert!(matches!(self, Surface::None { .. }), "an overlay parks a window only while it holds none"); + *self = Surface::Parked { backing, announced }; + } + SurfaceEvent::TakeLive if matches!(self, Surface::Live { .. }) => { + let Surface::Live { live, .. } = std::mem::replace(self, Surface::None { announced }) else { unreachable!() }; + return Effects::one(SurfaceEffect::Live(live)); + } + SurfaceEvent::TakeParked if matches!(self, Surface::Parked { .. }) => { + let Surface::Parked { backing, .. } = std::mem::replace(self, Surface::None { announced }) else { unreachable!() }; + return Effects::one(SurfaceEffect::Parked(backing)); + } + SurfaceEvent::TakeLive | SurfaceEvent::TakeParked => {} + SurfaceEvent::Announce => match self { + Surface::None { announced } | Surface::Parked { announced, .. } | Surface::Live { announced, .. } => *announced = true, + }, + SurfaceEvent::Release => match std::mem::take(self) { + Surface::Live { live, .. } => return Effects::one(SurfaceEffect::Live(live)), + Surface::Parked { backing, .. } => return Effects::one(SurfaceEffect::Parked(backing)), + Surface::None { .. } => {} + }, + } + Effects::none() + } + + pub(super) fn live(&self) -> Option<&L> { + match self { + Surface::Live { live, .. } => Some(live), + _ => None, + } + } + + pub(super) fn live_mut(&mut self) -> Option<&mut L> { + match self { + Surface::Live { live, .. } => Some(live), + _ => None, + } + } + + pub(super) fn parked(&self) -> Option<&B> { + match self { + Surface::Parked { backing, .. } => Some(backing), + _ => None, + } + } + + pub(super) fn announced(&self) -> bool { + match *self { + Surface::None { announced } | Surface::Parked { announced, .. } | Surface::Live { announced, .. } => announced, + } + } + + pub(super) fn announce(&mut self) { self.step(SurfaceEvent::Announce); } + + pub(super) fn made(&mut self, live: L) { self.step(SurfaceEvent::Made(live)); } + + pub(super) fn park(&mut self, backing: B) { self.step(SurfaceEvent::Park(backing)); } + + pub(super) fn take_live(&mut self) -> Option<L> { + match self.step(SurfaceEvent::TakeLive).into_iter().next() { + Some(SurfaceEffect::Live(live)) => Some(live), + _ => None, + } + } + + pub(super) fn take_parked(&mut self) -> Option<B> { + match self.step(SurfaceEvent::TakeParked).into_iter().next() { + Some(SurfaceEffect::Parked(backing)) => Some(backing), + _ => None, + } + } + + /// Everything it held: the next window made is announced again. + pub(super) fn release(&mut self) -> Option<SurfaceEffect<L, B>> { + self.step(SurfaceEvent::Release).into_iter().next() + } +} + +impl Surface { + /// The native window's backing, with a surface or parked. + pub(super) fn backing(&self) -> Option<&Backing> { + match self { + Surface::Live { live, .. } => Some(&live.backing), + Surface::Parked { backing, .. } => Some(backing), + Surface::None { .. } => None, + } + } +} + +impl OverlayCore { + /// Creates the wgpu surface (and the GPU device, if this is the first surface). + #[allow(unsafe_code)] + pub(super) fn attach(&mut self, app: &mut dyn OverlayApp, backing: Backing, scale: f32) -> Option<Live> { + // First, before the surface binds the view (macOS may observe it). + let a11y = self.shared.wake.lock().unwrap().clone().and_then(|wake| match &backing { + Backing::Window(window) => crate::a11y::Adapter::new(window, wake), + #[cfg(all(unix, not(target_os = "macos"), not(target_os = "ios"), not(target_os = "android")))] + Backing::Layer(_) | Backing::Xwayland(_) => crate::a11y::Adapter::windowless(wake), + }); + #[cfg(target_os = "macos")] + let moved = self.panel.as_ref().map(|p| p.raw_handles()); + let make = |instance: &wgpu::Instance| -> Option<wgpu::Surface<'static>> { + match &backing { + Backing::Window(w) => { + #[cfg(target_os = "macos")] + if let Some((display, window)) = moved { + // SAFETY: the panel keeps the view (and its layer) alive while the + // overlay holds this surface; AppKit's display handle carries nothing. + return unsafe { + instance.create_surface_unsafe(wgpu::SurfaceTargetUnsafe::RawHandle { + raw_display_handle: Some(display), + raw_window_handle: window, + }) + } + .ok(); + } + instance.create_surface(w.clone()).ok() + } + #[cfg(all(unix, not(target_os = "macos"), not(target_os = "ios"), not(target_os = "android")))] + Backing::Layer(layer) => { + let (display, window) = layer.raw_handles(); + // SAFETY: the layer surface outlives this wgpu surface (`Live` drops the + // surface first), and winit keeps the display alive. + unsafe { + instance.create_surface_unsafe(wgpu::SurfaceTargetUnsafe::RawHandle { + raw_display_handle: Some(display), + raw_window_handle: window, + }) + } + .ok() + } + #[cfg(all(unix, not(target_os = "macos"), not(target_os = "ios"), not(target_os = "android")))] + Backing::Xwayland(surface) => { + let (display, window) = surface.raw_handles()?; + // SAFETY: the X window and its connection outlive this wgpu surface (`Live` + // drops the surface first). + unsafe { + instance.create_surface_unsafe(wgpu::SurfaceTargetUnsafe::RawHandle { + raw_display_handle: Some(display), + raw_window_handle: window, + }) + } + .ok() + } + } + }; + let features = app.compositor_features(); + // A device that died while the overlay was hidden (a driver reset, a resume from + // Modern Standby) can configure nothing: the next surface gets a new one. + if self.gpu.as_ref().is_some_and(|gpu| gpu.is_lost()) { + self.gpu = None; + self.renderer = None; + } + // The overlay's own device was already the best for its surface, translucent or not; a + // device shared from another overlay must composite this one's translucent pixels. + let pooled = self.gpu.clone().map(|gpu| (gpu, false)).or_else(|| self.gpu_pool.borrow().upgrade().filter(|gpu| { + !gpu.is_lost() && gpu.device.features().contains(features & gpu.adapter.features()) + }).map(|gpu| (gpu, true))); + let reused = pooled.and_then(|(gpu, translucent)| make(&gpu.instance).filter(|s| crate::render::translucency::serves(&gpu, s, features, translucent)).map(|s| (gpu, s))); + let mut prewarmed = None; + let surface = match reused { + Some((gpu, surface)) => { self.gpu = Some(gpu); surface } + None => { + let made = Gpu::for_surface(features, true, |instance| make(instance).ok_or_else(|| "could not create its GPU surface".to_owned())); + let (gpu, surface, renderer) = match made { + Ok(made) => made, + Err(error) => { + self.fail(error); + return None; + } + }; + prewarmed = renderer; + // The old renderer's buffers live on the old device; a new one is made below. + self.renderer = None; + let gpu = Arc::new(gpu); + *self.gpu_pool.borrow_mut() = Arc::downgrade(&gpu); + crate::render::surface_gpu(&gpu); + self.gpu = Some(gpu); + surface + } + }; + let gpu = self.gpu.clone()?; + let (w, h) = ((self.at.size.0 * scale).round() as u32, (self.at.size.1 * scale).round() as u32); + let rt = app.rt_mut(); + let (mut config, translucent) = crate::window::surface_config(&surface, &gpu.adapter, (w, h), rt.srgb_blend())?; + match translucent { + Some(mode) => config.alpha_mode = mode, + // Windows composites an overlay's pixels only through DirectComposition; drawn + // opaque on its window they never show. + None if cfg!(target_os = "windows") => { + let info = gpu.adapter.get_info(); + self.fail(format!("{:?} on {} can't composite transparent pixels; Windows overlays need DX12 with DirectComposition", info.backend, info.name)); + return None; + } + None => eprintln!("transparency unavailable for overlay {}; drawing it opaque", self.name), + } + let info = gpu.adapter.get_info(); + *self.shared.surface.lock().unwrap() = Some(format!("{:?} on {} ({:?}), {:?}, {:?}", info.backend, info.name, info.device_type, config.alpha_mode, config.format)); + // A surface the driver refuses costs this overlay alone, never the app's other windows + // (hex#979). The surface drops before its backing. + if let Err(error) = crate::window::configure(&surface, &gpu, &config) { + self.fail(format!("could not configure its GPU surface on {:?} {}: {error}", info.backend, info.name)); + return None; + } + #[cfg(target_os = "macos")] + crate::platform::macos::pin_contents_top_left(&surface); + let target_format = if rt.srgb_blend() { config.format.remove_srgb_suffix() } else { config.format }; + if let Some(renderer) = &mut self.renderer { + crate::window::rebuild_renderer_core(&gpu.device, renderer, target_format, rt); + } else { + let mut renderer = prewarmed.unwrap_or_else(|| Renderer::new(&gpu.device, target_format)); + crate::window::rebuild_renderer_core(&gpu.device, &mut renderer, target_format, rt); + self.renderer = Some(renderer); + rt.text.atlas.invalidate(); + rt.images.invalidate(); + } + // Core Animation composites premultiplied pixels even in wgpu's PostMultiplied mode; + // other straight-alpha surfaces get the conversion pass. + let alpha = (config.alpha_mode == wgpu::CompositeAlphaMode::PostMultiplied && gpu.adapter.get_info().backend != wgpu::Backend::Metal) + .then(|| crate::render::surface_alpha::AlphaSurface::new(&gpu.device, target_format, (config.width, config.height))); + rt.transparent = true; + rt.set_viewport(self.at.size, scale); + #[cfg(target_os = "macos")] + let pacing = self.frame_wake.clone().and_then(|wake| { + let Backing::Window(window) = &backing; + crate::platform::display_link::DisplayLink::new(window, wake) + }); + #[cfg(target_os = "macos")] + let fn_key = match &backing { + Backing::Window(window) if rt.modifier_keys() => crate::input::fn_key::FnKey::new(window), + _ => None, + }; + Some(Live { + #[cfg(target_os = "macos")] + pacing, + #[cfg(target_os = "macos")] + materials: crate::system_material::macos::Materials::new(), + #[cfg(target_os = "macos")] + fn_key, + #[cfg(target_os = "macos")] + present: None, + // A new swap chain holds none of ours, and its waitable object is its own. + #[cfg(target_os = "windows")] + slot: Slot::default(), + a11y, alpha, surface, config, backing, scale, + }) + } + + pub(super) fn rescale(&mut self, app: &mut dyn OverlayApp, gpu: &Gpu, scale: f32) { + let Some(live) = self.surface.live_mut() else { return }; + if (live.scale - scale).abs() < f32::EPSILON { + return; + } + live.scale = scale; + live.config.width = (self.at.size.0 * scale).round().max(1.0) as u32; + live.config.height = (self.at.size.1 * scale).round().max(1.0) as u32; + live.settle(); + // `configure` waits for the present queue to drain, so unregister any outstanding wait + // before reconfiguring the swap chain (and keep it cleared if `configure` fails). + #[cfg(target_os = "windows")] + live.slot.reset(); + if let Err(error) = crate::window::configure(&live.surface, gpu, &live.config) { + self.surface_refused(app, format!("could not resize its GPU surface: {error}")); + return; + } + if let Some(alpha) = &mut live.alpha { + alpha.resize(&gpu.device, (live.config.width, live.config.height)); + } + app.rt_mut().set_viewport(self.at.size, scale); + self.dirty = true; + } +} + +impl Drop for OverlayCore { + fn drop(&mut self) { + *self.shared.native.lock().unwrap() = Default::default(); + self.set_availability(Availability::Unavailable); + self.release(); + } +} + +impl OverlayCore { + /// Its surface refused a new configuration: the overlay hides and drops it, so wgpu never + /// panics on its next drawable. The next show tries a new one. + pub(super) fn surface_refused(&mut self, app: &mut dyn OverlayApp, reason: String) { + self.hide(app); + self.release(); + self.fail(reason); + } + + /// Drops the surface and every native owner of its window; the next show makes new ones. + pub(super) fn release(&mut self) { + // The surface must disappear before returning the adopted view or removing subclasses. + // Keep winit's Window alive until after those native owners have unwound, too. + let backing = match self.surface.release() { + #[cfg_attr(not(target_os = "macos"), allow(unused_mut))] + Some(SurfaceEffect::Live(mut live)) => { + // The present worker joins, and the display link stops, before the surface goes. + #[cfg(target_os = "macos")] + { live.present.take(); live.pacing.take(); } + // The wait for the swap chain's room is unregistered before the surface drops. + #[cfg(target_os = "windows")] + live.slot.reset(); + let Live { alpha, surface, backing, .. } = live; + drop(alpha); + drop(surface); + Some(backing) + } + Some(SurfaceEffect::Parked(backing)) => Some(backing), + None => None, + }; + #[cfg(target_os = "macos")] + self.panel.take(); + #[cfg(target_os = "windows")] + self.native.take(); + #[cfg(all(unix, not(target_os = "macos"), not(target_os = "ios"), not(target_os = "android")))] + self.x11.take(); + drop(backing); + self.shared.native.lock().unwrap().0 = None; + } +} diff --git a/app/vendor/rune/crates/rune/src/overlay/tests.rs b/app/vendor/rune/crates/rune/src/overlay/tests.rs new file mode 100644 index 0000000..6a64607 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/overlay/tests.rs @@ -0,0 +1,952 @@ +use super::*; +use std::time::Duration; + +const FRAME: Duration = Duration::from_micros(16_667); + +fn width_overlay(name: &'static str) -> Overlay<f32> { + fn view(width: &f32, _: &mut Cx<f32>) -> El { + crate::el().child(crate::el().key("box").size(*width, 8.0)) + } + let app = AppSpec::new(name, (400.0, 50.0), || 12.0, view); + let (mut overlay, _) = Overlay::new(OverlaySpec::new(name, app.size, view).options(Default::default()), 12.0, &app); + overlay.rt.wall_start = None; + overlay +} + +/// One `draw_frame` without a surface, paced by a display link: the frame step, then the +/// idle bookkeeping after present. +fn present<T: 'static>(overlay: &mut Overlay<T>, at: Instant) { + present_paced(overlay, at, true); +} + +fn present_paced<T: 'static>(overlay: &mut Overlay<T>, at: Instant, paced: bool) { + // These synthetic frames exercise animation, independent of the host's Reduce Motion setting. + overlay.rt.set_system_reduced_motion(false); + let (animating, _) = overlay.step_frame(at, false); + overlay.dirty = false; + overlay.idle = idle_after(overlay.rt.core(), animating, paced.then_some(at + FRAME)); +} + +/// An overlay whose poll asks for the next frame every time it runs, counting its polls. +fn frame_hungry(name: &'static str) -> Overlay<u32> { + fn view(_: &u32, _: &mut Cx<u32>) -> El { crate::el().key("box").size(10.0, 10.0) } + fn poll(polls: &mut u32, _: f64, tx: &mut Tx) -> bool { + *polls += 1; + tx.wake_after(Duration::ZERO); + false + } + let app = AppSpec { poll: Some(poll), ..AppSpec::new(name, (100.0, 50.0), || 0, view) }; + Overlay::new(OverlaySpec::new(name, app.size, view).options(Default::default()), 0, &app).0 +} + +/// Polls in one simulated second of the event loop as winit turns it: `about_to_wait` (an +/// unpaced frame drawn if one is due), a `WaitUntil` on `wake_deadline`, then the wake at +/// that time. The wall clock is moved back to simulate the wait, so a deadline at or before +/// the current time (a spin) makes no progress and runs out the turn budget instead. +fn polls_in_a_second(overlay: &mut Overlay<u32>) -> u32 { + let start = crate::time::now(); + overlay.rt.wall_start = Some(start); + // An update asks for the next frame, as a poll would. + overlay.apply_wake(false, vec![Box::new(|_: &mut u32, tx: &mut Tx| { tx.wake_after(Duration::ZERO); true })]); + let before = overlay.rt.state; + for _ in 0..10_000 { + if overlay.dirty && !overlay.frameless() { present_paced(overlay, crate::time::now(), false); } + let Some(wake) = overlay.wake_deadline() else { break }; + let t0 = overlay.rt.wall_start.unwrap(); + let at = wake.saturating_duration_since(t0).max(t0.elapsed()); + if at > Duration::from_secs(1) { break; } + let now = crate::time::now(); + overlay.rt.wall_start = Some(now - at); + overlay.wake_due(now + Duration::from_micros(1)); + } + overlay.rt.state - before +} + +fn assert_frame_rate(polls: u32, what: &str) { + assert!((50..=61).contains(&polls), "{what}: a poll asking for every frame ran {polls} times in a second, want at most ~60"); +} + +/// A prewarmed overlay moved while hidden reports the new screen rect when it's revealed, +/// though the reveal draws nothing new (its retained pixels stand). +#[cfg(target_os = "macos")] +#[test] +fn a_retained_overlay_moved_while_hidden_reports_its_screen_rect_on_show() { + fn view(_: &Option<[f32; 4]>, _: &mut Cx<Option<[f32; 4]>>) -> El { + crate::el().child(crate::el().key("box").absolute(10.0, 5.0).size(20.0, 8.0) + .on_screen_layout(|s: &mut Option<[f32; 4]>, r| *s = Some(r))) + } + let app = AppSpec::new("moved hidden", (100.0, 50.0), || None, view); + let options = OverlayOptions { prewarm: true, ..Default::default() }; + let (mut overlay, _) = Overlay::new(OverlaySpec::new("moved hidden", app.size, view).options(options), None, &app); + overlay.rt.wall_start = None; + overlay.warm(); + assert_eq!(overlay.rt.state, Some([10.0, 5.0, 20.0, 8.0])); + overlay.dirty = false; + overlay.idle = true; + + overlay.origin_moved((300.0, 200.0)); + assert!(overlay.dirty, "the moved rect waits for the next step"); + assert!(overlay.idle, "a hidden overlay doesn't turn the loop for it"); + assert_eq!(overlay.rt.state, Some([10.0, 5.0, 20.0, 8.0])); + overlay.refresh_for_reveal_at(crate::time::now()); + assert_eq!(overlay.rt.state, Some([310.0, 205.0, 20.0, 8.0]), "the reveal delivers it"); +} + +/// `Tx::wake_after(Duration::ZERO)` asks for the next frame. With no display link to take +/// that from, it waits a frame interval: it never wakes the loop at once, which spins. +#[test] +fn a_poll_asking_for_every_frame_runs_at_the_frame_rate_without_a_display_link() { + // Shown with no display link (one couldn't be made, or not macOS). + let mut overlay = frame_hungry("unpaced"); + overlay.presence = Presence::Shown { occluded: false }; + overlay.rt.set_live_visible(true); + assert_frame_rate(polls_in_a_second(&mut overlay), "unpaced"); + + // Faded out, or hidden. + let mut overlay = frame_hungry("faded out"); + overlay.presence = Presence::Shown { occluded: false }; + overlay.hide_fading(Duration::from_millis(150)); + if let Some(end) = overlay.presence.fade_end() { overlay.wake_due(end); } + assert!(!overlay.presence.drawing()); + assert_frame_rate(polls_in_a_second(&mut overlay), "faded out"); + + // Covered, or the displays asleep. + #[cfg(target_os = "macos")] + { + let mut overlay = frame_hungry("occluded"); + overlay.presence = Presence::Shown { occluded: false }; + overlay.occluded(true); + assert_frame_rate(polls_in_a_second(&mut overlay), "occluded"); + } +} + +fn width<T: 'static>(overlay: &Overlay<T>, key: &str) -> f32 { + overlay.rt.presented(key).unwrap().0[2] +} + +/// A spring started at `FRAME`, presented at `times` (from `start`); `before` runs ahead of +/// the frame at `at`. Returns the width after each frame. +fn widths(times: &[Duration], at: Duration, before: fn(&mut Overlay<f32>)) -> Vec<(Duration, f32)> { + let mut overlay = width_overlay("late frame"); + let start = crate::time::now(); + times.iter().map(|&t| { + if t == FRAME { overlay.rt.update(|width, _| *width = 212.0); } + if t == at { before(&mut overlay); } + present(&mut overlay, start + t); + (t, width(&overlay, "box")) + }).collect() +} + +/// A 49 ms frame mid-spring lands where an unbroken 16.7 ms cadence is at that time, and so +/// do the frames after it: no hitch followed by a slow catch-up. `before` runs just ahead +/// of the late frame. +fn assert_late_frame_keeps_time(before: fn(&mut Overlay<f32>), what: &str) { + let late = 6 * FRAME + Duration::from_micros(49_300); + let mut steady: Vec<_> = (0..=8).map(|k| k * FRAME).collect(); + let after = [late, late + FRAME, late + 2 * FRAME]; + steady.extend(after); + let mut hitched: Vec<_> = (0..=6).map(|k| k * FRAME).collect(); + hitched.extend(after); + let steady = widths(&steady, Duration::MAX, |_| {}); + let hitched = widths(&hitched, late, before); + for t in after { + let expected = steady.iter().find(|w| w.0 == t).unwrap().1; + let got = hitched.iter().find(|w| w.0 == t).unwrap().1; + assert!(expected < 211.0, "the spring must still be moving at {t:?}: {expected}"); + assert!((got - expected).abs() < 0.01, "{what}: at {t:?} width={got}, unbroken cadence={expected}"); + } +} + +#[cfg(target_os = "macos")] +#[test] +fn a_fading_out_overlay_draws_its_exit_until_the_fade_ends() { + let mut overlay = width_overlay("fade out"); + overlay.presence = Presence::Shown { occluded: false }; + overlay.rt.set_live_visible(true); + let start = crate::time::now(); + present(&mut overlay, start); + // The handler that fades the overlay out starts its exit in the same turn. + overlay.rt.update(|width, _| *width = 212.0); + overlay.dirty = true; + overlay.hide_fading(Duration::from_millis(150)); + assert!(!overlay.presence.shown(), "input stops at once"); + assert!(overlay.presence.drawing() && !overlay.frameless(), "frames keep coming during the fade"); + assert!(overlay.rt.live_visible()); + overlay.set_occluded(true); + assert!(!overlay.presence.occluded(), "a panel fading toward alpha zero isn't occluded"); + let end = overlay.presence.fade_end().expect("fading out"); + assert!(overlay.wake_deadline().is_some_and(|due| due <= end), "the loop wakes to end the fade"); + let mut last = width(&overlay, "box"); + for k in 1..=6 { + present(&mut overlay, start + k * FRAME); + let now = width(&overlay, "box"); + assert!(now > last, "frame {k}: the exit moves ({last} -> {now})"); + last = now; + } + assert!(!overlay.idle); + overlay.apply_wake(true, Vec::new()); + assert!(overlay.dirty && !overlay.idle, "a wake mid-fade waits for the next drawn frame"); + overlay.wake_due(end); + assert!(!overlay.presence.drawing() && overlay.frameless(), "drawing stops when the fade ends"); + assert!(!overlay.rt.live_visible()); + assert_eq!(overlay.wake_deadline(), None); +} + +#[test] +fn hiding_without_a_fade_stops_drawing_at_once() { + let mut overlay = width_overlay("hide"); + overlay.presence = Presence::Shown { occluded: false }; + overlay.rt.set_live_visible(true); + overlay.hide_fading(Duration::ZERO); + assert!(!overlay.presence.drawing() && overlay.frameless() && !overlay.rt.live_visible()); + overlay.hide_fading(Duration::from_millis(150)); + assert!(!overlay.presence.drawing(), "fading out an overlay that's already hidden draws nothing"); +} + +#[test] +fn a_poll_asking_for_the_next_frame_keeps_a_shown_overlay_stepping() { + fn view(_: &u32, _: &mut Cx<u32>) -> El { crate::el().key("box").size(10.0, 10.0) } + // Steps its own animation from the frame clock, as a port of a display-link loop does. + fn poll(steps: &mut u32, _: f64, tx: &mut Tx) -> bool { + *steps += 1; + if *steps < 4 { tx.wake_after(Duration::ZERO); } + true + } + let app = AppSpec { poll: Some(poll), ..AppSpec::new("frame poll", (100.0, 50.0), || 0, view) }; + let (mut overlay, _) = Overlay::new(OverlaySpec::new("frame poll", app.size, view).options(Default::default()), 0, &app); + overlay.presence = Presence::Shown { occluded: false }; + let start = crate::time::now(); + let idle: Vec<_> = (1..=5).map(|k| { + present(&mut overlay, start + k * FRAME); + overlay.idle + }).collect(); + assert_eq!(overlay.rt.state, 5); + assert_eq!(idle, [false, false, false, true, true], "the display link runs while the poll asks for frames, and stops after"); +} + +#[test] +fn a_hidden_overlay_takes_a_new_accent_and_redraws_before_reveal() { + let mut overlay = width_overlay("accent"); + present(&mut overlay, crate::time::now()); + assert!(!overlay.presence.shown() && !overlay.dirty); + overlay.accent_changed(overlay.rt.system_accent()); + assert!(!overlay.dirty, "the same accent redraws nothing"); + let pink = crate::Color { r: 1.0, g: 0.05, b: 0.4, a: 1.0 }; + let pink = crate::SystemAccent::new(pink, pink); + overlay.accent_changed(pink); + assert_eq!(overlay.rt.system_accent(), pink); + assert!(overlay.dirty, "a retained surface redraws in the new accent before it's revealed"); +} + +#[test] +fn a_hidden_overlay_takes_a_scroll_bar_change_and_redraws_before_reveal() { + let mut overlay = width_overlay("scroll-bars"); + present(&mut overlay, crate::time::now()); + assert!(!overlay.presence.shown() && !overlay.dirty); + overlay.scroll_bars_changed(overlay.rt.system_scroll_bars_state()); + assert!(!overlay.dirty, "the same scroll-bar preference redraws nothing"); + let always = crate::platform::scroll_bars::SystemScrollBars { + bars: crate::ScrollBars::Always, + scroller_overlay: false, + jump_to_click: false, + }; + overlay.scroll_bars_changed(always); + assert_eq!(overlay.rt.system_scroll_bars_state(), always); + assert!(overlay.dirty, "a retained surface redraws for the new scroll-bar style before reveal"); +} + +#[test] +fn a_hidden_overlay_takes_a_theme_change_and_redraws_before_reveal() { + let mut overlay = width_overlay("theme"); + present(&mut overlay, crate::time::now()); + assert!(!overlay.presence.shown() && !overlay.dirty); + let dark = !overlay.rt.env.system_dark; + overlay.theme_changed(dark); + assert_eq!(overlay.rt.env.system_dark, dark); + assert!(overlay.dirty, "a retained surface redraws in the new theme before it's revealed"); + assert_eq!(overlay.dark, dark, "show reapplies this theme"); +} + +#[test] +fn overlay_late_frame_lands_where_an_unbroken_cadence_would() { + assert_late_frame_keeps_time(|_| {}, "late frame"); +} + +#[test] +fn overlay_idle_flag_left_set_mid_motion_cannot_shrink_the_step() { + // The motion trace's case: something marks the host idle while a spring is in flight. + assert_late_frame_keeps_time(|overlay| overlay.idle = true, "idle flag left set"); + // The source on macOS: an unoccluded notice with no occlusion before it. + #[cfg(target_os = "macos")] + assert_late_frame_keeps_time(|overlay| overlay.occluded(false), "Occluded(false) mid-motion"); +} + +#[test] +fn overlay_motion_starting_after_idle_takes_one_frame_step() { + let first_pose = |idle: Duration| { + let mut overlay = width_overlay("after idle"); + let start = crate::time::now(); + present(&mut overlay, start); + present(&mut overlay, start + FRAME); + assert!(overlay.idle); + overlay.rt.update(|width, _| *width = 212.0); + present(&mut overlay, start + FRAME + idle); + width(&overlay, "box") + }; + let short = first_pose(FRAME); + let long = first_pose(Duration::from_secs(2)); + assert!(short > 12.0 && short < 20.0, "the first frame shows one step of motion: {short}"); + assert!((long - short).abs() < 0.001, "idle time must not age motion that starts after it: {long} vs {short}"); +} + +#[test] +fn overlay_resume_keeps_running_motion_and_starts_new_motion_fresh() { + #[derive(Clone, Copy)] + struct Pair { a: f32, b: f32 } + fn view(s: &Pair, _: &mut Cx<Pair>) -> El { + crate::el().children([crate::el().key("a").size(s.a, 8.0), crate::el().key("b").size(s.b, 8.0)]) + } + let app = AppSpec::new("resume", (500.0, 50.0), || Pair { a: 12.0, b: 12.0 }, view); + // `a` springs from FRAME; `pause` runs after 3 frames, and `b` starts on the frame + // presented `gap` later. + let run_with = |options: OverlayOptions, pause: fn(&mut Overlay<Pair>), resume: fn(&mut Overlay<Pair>), gap: Duration| { + let (mut overlay, _) = Overlay::new(OverlaySpec::new("resume", app.size, view).options(options), Pair { a: 12.0, b: 12.0 }, &app); + overlay.rt.wall_start = None; + let start = crate::time::now(); + present(&mut overlay, start); + overlay.rt.update(|s, _| s.a = 212.0); + for k in 1..=3 { present(&mut overlay, start + k * FRAME); } + pause(&mut overlay); + overlay.rt.update(|s, _| s.b = 212.0); + resume(&mut overlay); + present(&mut overlay, start + 3 * FRAME + gap); + (width(&overlay, "a"), width(&overlay, "b")) + }; + let run = |pause: fn(&mut Overlay<Pair>), resume: fn(&mut Overlay<Pair>), gap: Duration| run_with(Default::default(), pause, resume, gap); + let fresh = { + let mut overlay = width_overlay("fresh"); + let start = crate::time::now(); + present(&mut overlay, start); + overlay.rt.update(|width, _| *width = 212.0); + present(&mut overlay, start + FRAME); + width(&overlay, "box") + }; + // Running motion keeps real time up to the resume cap. + let (capped, _) = run(|_| {}, |_| {}, Duration::from_secs_f64(crate::frame::clock::MAX_GAP)); + type Case = (&'static str, fn(&mut Overlay<Pair>), fn(&mut Overlay<Pair>)); + let hidden: Case = ("hidden", |o| o.hide(), |o| o.presence = Presence::Shown { occluded: false }); + #[cfg(target_os = "macos")] + let cases: [Case; 2] = [hidden, ("occluded", |o| o.occluded(true), |o| o.occluded(false))]; + #[cfg(not(target_os = "macos"))] + let cases: [Case; 1] = [hidden]; + for (what, pause, resume) in cases { + let (a, b) = run(pause, resume, Duration::from_secs(3)); + // `b` sits beside `a`, so its edges snap to a different 1/64 pt grid than `fresh`. + assert!((b - fresh).abs() < 0.02, "{what}: motion starting on the resume frame must not jump: b={b}, fresh={fresh}"); + assert!(capped < 211.0 && (a - capped).abs() < 0.01, "{what}: running motion resumes {:?} along: a={a}, expected={capped}", crate::frame::clock::MAX_GAP); + } + // A missed frame while covered or asleep polls but commits nothing, retained or not: `b` + // starts on the first uncovered frame, as above. + #[cfg(target_os = "macos")] + for prewarm in [false, true] { + let options = OverlayOptions { prewarm, ..Default::default() }; + let (a, b) = run_with(options, |o| { o.presence = Presence::Shown { occluded: false }; o.occluded(true); }, + |o| { o.missed(crate::window::Missed::Occluded, false, false); o.occluded(false); }, Duration::from_secs(3)); + assert!((b - fresh).abs() < 0.02, "missed while occluded (prewarm: {prewarm}): b={b}, fresh={fresh}"); + assert!((a - capped).abs() < 0.01, "missed while occluded (prewarm: {prewarm}): a={a}, expected={capped}"); + } +} + +#[cfg(target_os = "macos")] +#[test] +fn overlay_hidden_commit_keeps_elapsed_motion_on_later_reveal() { + use std::time::Duration; + struct State { width: f32, enter: bool, live: crate::LiveText } + fn init() -> State { State { width: 12.0, enter: false, live: crate::LiveText::new("00") } } + fn view(s: &State, _: &mut Cx<State>) -> El { + crate::el().children([ + crate::el().key("box").size(s.width, 8.0), + crate::text(if s.width == 12.0 { "A" } else { "B" }).key("content"), + crate::text("00").key("live").live_text(&s.live), + ]) + } + fn poll(s: &mut State, _: f64, _: &mut Tx) -> bool { + if !std::mem::take(&mut s.enter) { return false; } + s.width = 20.0; + true + } + let app = AppSpec { poll: Some(poll), ..AppSpec::new("delayed entry", (100.0, 50.0), init, view) }; + for delay in [Duration::from_millis(16), Duration::from_secs(2)] { + let spec = OverlaySpec::new("delayed entry", app.size, view) + .options(OverlayOptions { prewarm: true, ..Default::default() }); + let (mut overlay, handle) = Overlay::new(spec, init(), &app); + overlay.rt.set_system_reduced_motion(false); + overlay.rt.wall_start = None; + overlay.warm(); + overlay.dirty = false; // Successful submission of A, without a native window. + let commit = overlay.clock.last() + Duration::from_secs(10); + overlay.rt.state.enter = true; + overlay.advance_at(commit); // Hidden turn 1 commits B; no show request yet. + assert_eq!(handle.shared.core.requests.lock().unwrap().visible(), None); + assert_eq!(overlay.rt.presented("box").unwrap().0[2], 12.0, "idle before B must not age B"); + assert!(!overlay.draw(), "hidden motion must not drive frames"); + assert_eq!(overlay.wake_deadline(), None); + overlay.rt.state.live.set("01"); + handle.show(); // Turn 2, after B has been committed. + overlay.resume_live(); + overlay.settle_before_reveal(); + overlay.refresh_for_reveal_at(commit + delay); + let width = overlay.rt.presented("box").unwrap().0[2]; + if delay.as_secs() == 0 { + assert!(overlay.rt.animating && width > 12.0 && width < 14.0, + "16ms reveal must be near A and moving: width={width}, moving={}", overlay.rt.animating); + } else { + assert_eq!(width, 20.0, "2s reveal must have reached B"); + assert!(!overlay.rt.animating); + } + let elements = overlay.rt.elements(); + assert_eq!(elements.iter().find(|e| e.key.as_deref() == Some("content")).unwrap().text.as_deref(), Some("B")); + assert_eq!(elements.iter().find(|e| e.key.as_deref() == Some("live")).unwrap().text.as_deref(), Some("01")); + } +} + +#[cfg(target_os = "macos")] +#[test] +fn overlay_hidden_retarget_samples_old_motion_before_committing_new_target() { + use std::time::Duration; + fn view(width: &f32, _: &mut Cx<f32>) -> El { + crate::el().child(crate::el().key("box").size(*width, 8.0)) + } + let app = AppSpec::new("retarget", (100.0, 50.0), || 12.0, view); + for (scale, millis) in [(0.0, 16), (0.25, 16), (1.0, 16), (0.0, 2000), (0.25, 2000), (1.0, 2000)] { + let delay = Duration::from_millis(millis); + let spec = OverlaySpec::new("retarget", app.size, view) + .options(OverlayOptions { prewarm: true, ..Default::default() }); + let (mut overlay, _) = Overlay::new(spec, 12.0, &app); + overlay.rt.set_system_reduced_motion(false); + overlay.rt.wall_start = None; + overlay.rt.time_scale = scale; + overlay.warm(); + overlay.dirty = false; + let commit = overlay.clock.last() + Duration::from_secs(10); + overlay.rt.update(|width, _| *width = 20.0); + overlay.advance_at(commit); + overlay.advance_at(commit + Duration::from_millis(8)); // Unchanged intervening poll. + overlay.rt.update(|width, _| *width = 30.0); // Newly observed at reveal, not 2s ago. + overlay.refresh_for_reveal_at(commit + delay); + + // A visible reference ages B first and only then commits C. Compare the next + // moving frame too: retargeting must preserve velocity, not just position. + let mut reference = crate::runtime::Runtime::new(12.0, view, app.size, crate::runtime::Env::default()); + reference.time_scale = scale; + reference.frame(0.0); + reference.update(|width, _| *width = 20.0); + reference.frame(0.0); + reference.frame(delay.as_secs_f64()); + reference.update(|width, _| *width = 30.0); + reference.frame(0.0); + for dt in [0.0, 0.016] { + overlay.rt.frame(dt); + reference.frame(dt); + let width = overlay.rt.presented("box").unwrap().0[2]; + let expected = reference.presented("box").unwrap().0[2]; + assert!((width - expected).abs() < 0.001, "scale={scale}: width={width}, expected={expected}"); + assert!(width < 30.0, "the fresh target must not inherit the hidden gap"); + } + } +} + +#[cfg(target_os = "macos")] +#[test] +fn overlay_hidden_poll_can_show_and_animate_from_the_cached_pose() { + #[derive(Default)] + struct State { width: f32, enter: bool, instant: bool, handle: Option<OverlayHandle<State>> } + fn view(s: &State, _: &mut Cx<State>) -> El { + crate::el().child(crate::el().key("box").size(s.width, 8.0)) + } + fn poll(s: &mut State, _: f64, tx: &mut Tx) -> bool { + if !std::mem::take(&mut s.enter) { return false; } + s.width = 20.0; + if s.instant { tx.instant(); } + s.handle.as_ref().unwrap().show(); + true + } + let app = AppSpec { poll: Some(poll), ..AppSpec::new("entry", (100.0, 50.0), State::default, view) }; + for (prewarm, stale, instant, queued) in [ + (true, false, false, false), (true, true, false, false), + (false, false, false, false), (true, false, true, false), + (true, false, false, true), + ] { + let spec = OverlaySpec::new("entry", app.size, view) + .options(OverlayOptions { prewarm, ..Default::default() }); + let (mut overlay, handle) = Overlay::new(spec, State { width: 12.0, instant, ..Default::default() }, &app); + overlay.rt.set_system_reduced_motion(false); + overlay.rt.state.handle = Some(handle.clone()); + overlay.warm(); + // No native window in this test: model successful submission of the warmed pose. + overlay.dirty = false; + assert_eq!(overlay.rt.presented("box").unwrap().0[2], 12.0); + overlay.advance(); + assert!(!overlay.dirty, "an unchanged hidden poll preserves the prepared frame"); + if stale { overlay.apply_wake(false, vec![Box::new(|s, _| { s.width = 16.0; true })]); } + overlay.rt.state.enter = true; // External event observed by the next hidden poll. + if queued { + // An app's original kick: a no-op update invalidates the prepared frame + // before the hidden poll commits B and requests show. + handle.update(|_, _| {}); + let updates = std::mem::take(&mut *handle.shared.updates.lock().unwrap()); + overlay.apply_wake(false, updates); + assert!(overlay.dirty); + } else { + overlay.advance(); + } + assert_eq!(handle.shared.core.requests.lock().unwrap().visible(), Some(true)); + overlay.settle_before_reveal(); + overlay.refresh_for_reveal_at(crate::time::now()); + if queued { + assert!(overlay.rt.animating && overlay.rt.presented("box").unwrap().0[2] < 20.0, + "a queued update kick must not settle the entry during reveal"); + } + if prewarm && !stale { assert!(!overlay.idle, "the new target needs a visible frame even with instant motion"); } + let moving = overlay.rt.frame(1.0 / 60.0); + let width = overlay.rt.presented("box").unwrap().0[2]; + if prewarm && !instant { + assert!(moving && (12.0..20.0).contains(&width), + "same-poll show must animate from A: width={width}, moving={moving}"); + } else { + assert_eq!(width, 20.0, "instant changes and unretained frames land at their target"); + assert!(!moving); + } + } +} + +#[cfg(target_os = "macos")] +#[test] +fn overlay_cached_reveal_does_not_settle_a_same_tick_update() { + fn view(width: &f32, _: &mut Cx<f32>) -> El { + crate::el().child(crate::el().key("box").size(*width, 8.0)) + } + let app = AppSpec::new("reveal", (100.0, 50.0), || 8.0, view); + for prewarm in [true, false] { + let spec = OverlaySpec::new("reveal", app.size, view) + .options(OverlayOptions { prewarm, ..Default::default() }); + let (mut overlay, _) = Overlay::new(spec, 8.0, &app); + overlay.rt.set_system_reduced_motion(false); + overlay.rt.frame(0.0); + overlay.rt.update(|width, _| *width = 12.0); + overlay.warm(); + assert_eq!(overlay.rt.presented("box").unwrap().0[2], 12.0, "hidden changes settle in prewarm"); + overlay.settle_before_reveal(); + // A show and update can arrive in one event-loop turn, after the cached frame. + overlay.rt.update(|width, _| *width = 20.0); + let moving = overlay.rt.frame(1.0 / 60.0); + let width = overlay.rt.presented("box").unwrap().0[2]; + if prewarm { + assert!(moving && width < 20.0, "cached reveal erased new motion: width={width}, moving={moving}"); + } else { assert_eq!(width, 20.0, "ordinary show retains its settled first-frame contract"); } + } +} + +#[test] +fn window_panel_overlay_focus_callback_is_connected_before_first_show() { + fn view(_: &Vec<bool>, _: &mut Cx<Vec<bool>>) -> El { crate::el() } + let app = AppSpec::new("focus", (100.0, 100.0), Vec::new, view); + let spec = OverlaySpec::new("focus", app.size, view).options(Default::default()) + .on_focus(|s, focused, tx| { s.push(focused); if !focused { tx.close_window(); } }); + let (mut overlay, _) = Overlay::new(spec, Vec::new(), &app); + overlay.rt.window_focus(true); + overlay.rt.window_focus(false); + assert_eq!(overlay.rt.state, [true, false]); + assert_eq!(overlay.rt.shell_request, Some(crate::el::Shell::Close)); + assert!(overlay.surface.live().is_none()); +} + +#[test] +fn hiding_a_key_overlay_releases_the_modifiers_it_held() { + use crate::{Key, Modifier, Mods, PhysicalInput, PhysicalKeyCode as Code}; + fn view(_: &Vec<(Modifier, bool)>, _: &mut Cx<Vec<(Modifier, bool)>>) -> El { crate::el() } + let app = AppSpec::new("keys", (100.0, 100.0), Vec::new, view); + let spec = OverlaySpec::new("keys", app.size, view) + .options(OverlayOptions { keys: KeyPolicy::OnDemand, ..Default::default() }) + .on_key(|s, ev, _| match ev.key { Key::Modifier { modifier, pressed } => { s.push((modifier, pressed)); true } _ => false }); + let (mut overlay, _) = Overlay::new(spec, Vec::new(), &app); + overlay.rt.set_modifier_keys(true); + overlay.rt.frame(0.0); + let press = |overlay: &mut Overlay<_>, key| { + overlay.presence = Presence::Shown { occluded: false }; + overlay.rt.window_focus(true); + overlay.rt.physical_with_fallback(PhysicalInput::Key { key, mods: Mods::default(), pressed: true, repeat: false }, None); + overlay.advance(); + }; + press(&mut overlay, Code::AltRight); + press(&mut overlay, Code::Fn); + // Hidden from its own handler: no blur reaches it, and no frame draws. + overlay.hide(); + assert_eq!(overlay.rt.state, [(Modifier::AltRight, true), (Modifier::Fn, true), (Modifier::AltRight, false), (Modifier::Fn, false)]); + overlay.rt.window_focus(false); + overlay.hidden_input(); + assert_eq!(overlay.rt.state.len(), 4, "the blur after the hide releases nothing again"); + press(&mut overlay, Code::AltRight); + assert_eq!(overlay.rt.state[4..], [(Modifier::AltRight, true)], "shown again, the key is heard"); +} + +#[test] +fn overlay_live_values_resume_before_retained_reveal_and_stop_on_hide() { + use std::sync::atomic::AtomicUsize; + fn init() -> crate::LiveText { crate::LiveText::new("00") } + fn view(value: &crate::LiveText, _: &mut Cx<crate::LiveText>) -> El { + crate::text("00").live_text(value) + } + let app = AppSpec::new("live overlay", (80.0, 40.0), init, view); + let spec = OverlaySpec::new("live overlay", app.size, view).options(OverlayOptions { + prewarm: true, keys: KeyPolicy::OnDemand, ..Default::default() + }); + let value = init(); + let (mut overlay, _) = Overlay::new(spec, value.clone(), &app); + let wakes = Arc::new(AtomicUsize::new(0)); + let count = wakes.clone(); + overlay.rt.set_live_waker(Arc::new(move || { count.fetch_add(1, Ordering::Relaxed); })); + overlay.rt.frame(0.0); + value.set("01"); + assert_eq!(wakes.load(Ordering::Relaxed), 0, "prewarming isn't visibility"); + overlay.dirty = false; + overlay.resume_live(); + assert!(overlay.dirty, "the retained surface must redraw before reveal"); + overlay.rt.frame(0.0); + assert_eq!(overlay.rt.elements()[0].text.as_deref(), Some("01")); + overlay.hide(); + let before = wakes.load(Ordering::Relaxed); + value.set("02"); + assert_eq!(wakes.load(Ordering::Relaxed), before); + overlay.dirty = false; + overlay.resume_live(); + assert!(overlay.dirty); + overlay.rt.frame(0.0); + assert_eq!(overlay.rt.elements()[0].text.as_deref(), Some("02")); +} + + +/// A resting overlay's timer frame builds before it takes a drawable or a display tick: one +/// whose poll changes state but nothing on screen draws nothing, and one that changes what +/// it shows draws, with the step it already took. +#[test] +fn a_timer_frame_that_changes_nothing_on_screen_draws_nothing() { + #[derive(Default)] + struct S { polls: u32, width: f32, grow: bool } + fn view(s: &S, _: &mut Cx<S>) -> El { + crate::el().child(crate::el().key("box").size(10.0 + s.width, 8.0).fill(crate::Color::WHITE)) + } + fn poll(s: &mut S, _: f64, tx: &mut Tx) -> bool { + s.polls += 1; + if s.grow { s.width += 1.0; } + tx.wake_after(Duration::from_millis(33)); + true + } + let app = AppSpec { poll: Some(poll), ..AppSpec::new("quiet timer", (100.0, 40.0), S::default, view) }; + let (mut overlay, _) = Overlay::new(OverlaySpec::new("quiet timer", app.size, view).options(Default::default()), S::default(), &app); + overlay.rt.wall_start = None; + let config = wgpu::SurfaceConfiguration { + usage: wgpu::TextureUsages::RENDER_ATTACHMENT, + format: wgpu::TextureFormat::Bgra8UnormSrgb, + width: 200, + height: 80, + present_mode: wgpu::PresentMode::AutoVsync, + desired_maximum_frame_latency: 2, + alpha_mode: wgpu::CompositeAlphaMode::PreMultiplied, + view_formats: vec![], + color_space: Default::default(), + }; + let start = crate::time::now(); + present(&mut overlay, start); + assert!(overlay.idle, "only the timer asks for another frame"); + let mut quiet = frame::Quiet::default(); + let record = |slot: &mut Option<crate::window::Presented>| crate::window::Presented::record(slot, &overlay.rt, &config, false); + quiet.presented_frame(false, record); + assert!(quiet.presented().is_none(), "a frame it doesn't rest on records nothing"); + quiet.presented_frame(true, record); + let presented = quiet.presented().unwrap(); + + let at = start + Duration::from_millis(33); + let polls = overlay.rt.state.polls; + assert_eq!(overlay.quiet_step_frame(presented, &config, at, Some(at + FRAME)), None); + assert_eq!(overlay.rt.state.polls, polls + 1, "the timer's poll ran"); + + overlay.rt.state.grow = true; + let at = at + Duration::from_millis(33); + assert!(overlay.quiet_step_frame(presented, &config, at, Some(at + FRAME)).is_some(), + "a poll that changes what's on screen draws"); +} + +#[test] +fn quiet_timer_frame_that_misses_its_drawable_steps_only_once() { + #[derive(Default)] + struct S { polls: u32, width: f32 } + fn view(s: &S, _: &mut Cx<S>) -> El { + crate::el().child(crate::el().key("box").size(10.0 + s.width, 8.0).fill(crate::Color::WHITE)) + } + fn poll(s: &mut S, _: f64, tx: &mut Tx) -> bool { + s.polls += 1; + s.width += 1.0; + tx.wake_after(Duration::from_millis(33)); + true + } + let app = AppSpec { poll: Some(poll), ..AppSpec::new("quiet miss", (100.0, 40.0), S::default, view) }; + let (mut overlay, _) = Overlay::new(OverlaySpec::new("quiet miss", app.size, view).options(Default::default()), S::default(), &app); + overlay.presence = Presence::Shown { occluded: false }; + overlay.rt.wall_start = None; + let config = wgpu::SurfaceConfiguration { + usage: wgpu::TextureUsages::RENDER_ATTACHMENT, + format: wgpu::TextureFormat::Bgra8UnormSrgb, + width: 200, + height: 80, + present_mode: wgpu::PresentMode::AutoVsync, + desired_maximum_frame_latency: 2, + alpha_mode: wgpu::CompositeAlphaMode::PreMultiplied, + view_formats: vec![], + color_space: Default::default(), + }; + let start = crate::time::now(); + present(&mut overlay, start); + overlay.core.quiet.presented_frame(true, |slot| crate::window::Presented::record(slot, &overlay.rt, &config, false)); + let mut presented = None; + crate::window::Presented::record(&mut presented, &overlay.rt, &config, false); + let presented = presented.unwrap(); + + let polls_before = overlay.rt.state.polls; + let at = start + Duration::from_millis(33); + let built = overlay.quiet_step_frame(&presented, &config, at, Some(at + FRAME)); + assert!(built.is_some(), "quiet_step stepped the runtime once"); + assert_eq!(overlay.rt.state.polls, polls_before + 1); + + // Drawable acquisition now fails after quiet_step already stepped the runtime. + overlay.acquire_missed(crate::window::Missed::Timeout, false, false, built.is_some()); + assert_eq!( + overlay.rt.state.polls, + polls_before + 1, + "a missed drawable after quiet_step must not advance the runtime a second time" + ); + assert!(overlay.quiet.presented().is_none(), "a missed frame forgets what it rested on"); +} + +#[test] +fn missed_frame_in_turn_prevents_second_step_in_same_turn() { + use frame::{Gate, Turn, TurnEvent}; + #[derive(Default)] + struct S { polls: u32 } + fn view(_: &S, _: &mut Cx<S>) -> El { crate::el() } + fn poll(s: &mut S, _: f64, tx: &mut Tx) -> bool { + s.polls += 1; + tx.wake_after(Duration::from_millis(250)); + false + } + let app = AppSpec { poll: Some(poll), ..AppSpec::new("turn guard", (40.0, 20.0), S::default, view) }; + let (mut overlay, _) = Overlay::new(OverlaySpec::new("turn guard", app.size, view).options(Default::default()), S::default(), &app); + overlay.presence = Presence::Shown { occluded: true }; + overlay.rt.wall_start = None; + overlay.advance(); + assert_eq!(overlay.rt.state.polls, 1); + + // Same turn: both a timer and the backoff retry are due while occluded. + let now = crate::time::now(); + overlay.rt.wall_start = Some(now - Duration::from_millis(300)); + overlay.backoff_step(crate::window::BackoffEvent::At(now)); + overlay.core.turn_frame.step(TurnEvent::NewEvents); + overlay.wake_due(now); + assert_eq!(overlay.rt.state.polls, 2, "wake_due steps the due timer once"); + assert!(overlay.core.turn_frame.stepped(), "turn records that wake_due stepped"); + + // Occluded recheck in the same turn sees `stepped() == true` and does not step again. + let stepped = overlay.core.turn_frame.stepped(); + overlay.missed(crate::window::Missed::Occluded, false, stepped); + assert_eq!(overlay.rt.state.polls, 2, "occluded recheck must not step a second time in the same turn"); + assert!(overlay.core.turn_frame.missed()); + + // A paced timeout miss in `DisplayTick` clears backoff, so `about_to_wait` in the same turn + // must back off via `missed_this_turn` rather than retrying immediately. + let decided = frame::turn(Gate { + prewarm: false, + occluded: false, + dirty: true, + idle: false, + retry: None, + missed_this_turn: overlay.core.turn_frame.missed(), + }, || now); + assert_eq!(decided, Turn::BackedOff); + + // Next turn resets the per-turn guard and allows drawing again. + overlay.core.turn_frame.step(TurnEvent::NewEvents); + let next = frame::turn(Gate { + prewarm: false, + occluded: false, + dirty: true, + idle: false, + retry: None, + missed_this_turn: overlay.core.turn_frame.missed(), + }, || now); + assert_eq!(next, Turn::Draw); +} + +#[test] +fn overlay_idle_after_stays_awake_when_stale_or_live_pending() { + let value = crate::LiveText::new("a"); + let v = value.clone(); + fn view(value: &crate::LiveText, _: &mut Cx<crate::LiveText>) -> El { + crate::text("a").live_text(value) + } + let app = AppSpec::new("idle-stale", (80.0, 40.0), || crate::LiveText::new("a"), view); + let (mut overlay, _) = Overlay::new(OverlaySpec::new("idle-stale", app.size, view).options(Default::default()), v, &app); + overlay.rt.set_live_visible(true); + overlay.rt.frame(0.0); + assert!(idle_after(overlay.rt.core(), false, None), "resting overlay with no work goes idle"); + + // A compositor invalidating state during render leaves rt.stale() true. + overlay.rt.invalidate(); + assert!(!idle_after(overlay.rt.core(), false, None), "stale overlay must stay awake to draw the invalidation"); + overlay.rt.frame(0.0); + assert!(idle_after(overlay.rt.core(), false, None)); + + // A live value changing during render leaves rt.live_pending() true. + value.set("b"); + assert!(overlay.rt.live_pending()); + assert!(!idle_after(overlay.rt.core(), false, None), "live-pending overlay must stay awake to draw the new value"); +} + +#[test] +fn overlay_render_registers_frame_wake_on_renderer() { + let Ok(gpu) = crate::render::Gpu::try_new(crate::render::Gpu::instance(), None) else { return }; + let mut overlay = width_overlay("frame-wake"); + overlay.rt.frame(0.0); + let renderer = crate::render::Renderer::new(&gpu.device, crate::render::OFFSCREEN_FORMAT); + overlay.core.gpu = Some(Arc::new(gpu)); + overlay.core.renderer = Some(renderer); + overlay.warm_offscreen((40, 20)); + assert!( + overlay.core.renderer.as_ref().unwrap().has_frame_wake(), + "overlay render must register rt.live_wake() on the renderer so off-thread pipelines wake resting overlays" + ); +} + +#[test] +fn overlay_post_step_unconfigured_miss_flushes_clipboard_and_drops_requests() { + let mut overlay = width_overlay("reblend-miss"); + let clipboard = crate::clipboard::memory(); + overlay.core.clipboard.use_memory(&clipboard); + overlay.presence = Presence::Shown { occluded: false }; + overlay.rt.update(|_, tx| { + tx.copy("overlay-copy"); + tx.close_window(); + tx.minimize(); + }); + overlay.rt.frame(0.0); + // Simulate a post-step reblend or re-acquire Unconfigured failure routed through acquire_missed. + overlay.acquire_missed(crate::window::Missed::Unconfigured, false, false, true); + assert!(overlay.rt.copy_request.is_none(), "post-step Unconfigured miss must flush clipboard writes"); + assert_eq!( + clipboard.text().as_deref().map(String::as_str), + Some("overlay-copy"), + "post-step Unconfigured miss must deliver clipboard writes to the clipboard" + ); + assert!(overlay.rt.shell_request.is_none(), "post-step Unconfigured miss must drop unsupported shell requests"); + assert!(!overlay.rt.host.minimize.field(), "post-step Unconfigured miss must clear minimize requests"); + assert!(!overlay.presence.shown(), "surface_refused hides the overlay"); +} + +#[test] +fn clipboard_receive_marks_shown_overlay_dirty_without_advancing_and_advances_frameless() { + #[derive(Default)] + struct State { + polls: u32, + pasted: Vec<String>, + } + fn view(s: &State, _: &mut Cx<State>) -> El { + crate::el() + .on_paste(|s: &mut State, text, _| s.pasted.push(text.to_owned())) + .child(crate::text(s.pasted.len().to_string()).key("count")) + } + fn poll(s: &mut State, _: f64, _: &mut Tx) -> bool { + s.polls += 1; + false + } + let app_spec = AppSpec { poll: Some(poll), ..AppSpec::new("clipboard-sync", (100.0, 40.0), State::default, view) }; + let (overlay, _) = Overlay::new( + OverlaySpec::new("clipboard-sync", app_spec.size, view).options(Default::default()), + State::default(), + &app_spec, + ); + let Overlay { mut core, rt, compositor, setup, shared } = overlay; + let mut app = app::TypedOverlayApp { rt, compositor, setup, shared }; + let clipboard = crate::clipboard::memory(); + app.rt.use_clipboard(&clipboard); + app.rt.wall_start = None; + app.rt.frame(0.0); + + // No pending clipboard reply leaves a clean shown overlay untouched. + core.presence = Presence::Shown { occluded: false }; + core.dirty = false; + core.idle = true; + let (polls_before, commits_before) = (app.rt.state.polls, app.rt.stats.commits); + core.clipboard_due(&mut app); + assert!(!core.dirty); + assert_eq!((app.rt.state.polls, app.rt.stats.commits), (polls_before, commits_before)); + + // Shown (non-frameless): receiving a clipboard reply marks dirty and leaves stepping to draw. + clipboard.set_text("shown"); + core.clipboard.read_core(app.rt.core()); + core.clipboard_due(&mut app); + assert!(core.dirty, "shown overlay must be marked dirty for the next frame draw"); + assert!(app.rt.has_pending_input(), "clipboard reply must wait for the drawn frame"); + assert_eq!(app.rt.state.polls, polls_before, "shown overlay must not step poll outside draw"); + assert_eq!(app.rt.stats.commits, commits_before, "shown overlay must not commit outside draw"); + assert!(app.rt.state.pasted.is_empty(), "paste handler must run in the drawn frame, not sync"); + app.rt.frame(0.0); + assert!(!app.rt.has_pending_input()); + assert_eq!(app.rt.state.polls, polls_before + 1, "drawn frame steps poll once"); + assert_eq!(app.rt.state.pasted, ["shown"]); + + // Fading out (still drawing, non-frameless): also leaves stepping to draw. + core.presence = Presence::FadingOut { + until: crate::time::now() + Duration::from_secs(1), + length: Duration::from_secs(1), + occluded: false, + }; + assert!(!core.frameless()); + core.dirty = false; + let (polls_before, commits_before) = (app.rt.state.polls, app.rt.stats.commits); + clipboard.set_text("fading"); + core.clipboard.read_core(app.rt.core()); + core.clipboard_due(&mut app); + assert!(core.dirty); + assert!(app.rt.has_pending_input(), "fading overlay still draws frames and must not advance in sync"); + assert_eq!((app.rt.state.polls, app.rt.stats.commits), (polls_before, commits_before)); + app.rt.frame(0.0); + assert_eq!(app.rt.state.pasted, ["shown", "fading"]); + + // Hidden (frameless): advances immediately so the clipboard reply is delivered without a frame. + core.presence = Presence::default(); + assert!(core.frameless()); + core.dirty = false; + let polls_before = app.rt.state.polls; + clipboard.set_text("hidden"); + core.clipboard.read_core(app.rt.core()); + core.clipboard_due(&mut app); + assert!(core.dirty); + assert!(!app.rt.has_pending_input(), "hidden overlay must drain the clipboard reply immediately"); + assert_eq!(app.rt.state.polls, polls_before + 1, "hidden overlay advances once"); + assert_eq!(app.rt.state.pasted, ["shown", "fading", "hidden"]); + + // Shown but occluded (frameless): advances immediately since no frame will draw while covered. + core.presence = Presence::Shown { occluded: true }; + assert!(core.frameless()); + core.dirty = false; + let polls_before = app.rt.state.polls; + clipboard.set_text("occluded"); + core.clipboard.read_core(app.rt.core()); + core.clipboard_due(&mut app); + assert!(core.dirty); + assert!(!app.rt.has_pending_input(), "occluded overlay must drain the clipboard reply immediately"); + assert_eq!(app.rt.state.polls, polls_before + 1, "occluded overlay advances once"); + assert_eq!(app.rt.state.pasted, ["shown", "fading", "hidden", "occluded"]); +} + + +include!("more_tests.rs"); diff --git a/app/vendor/rune/crates/rune/src/overlay/xwayland.rs b/app/vendor/rune/crates/rune/src/overlay/xwayland.rs new file mode 100644 index 0000000..328f84c --- /dev/null +++ b/app/vendor/rune/crates/rune/src/overlay/xwayland.rs @@ -0,0 +1,33 @@ +//! An overlay's XWayland backing, for a Wayland compositor without layer-shell. + +use super::*; + +impl OverlayCore { + /// The compositor has no layer-shell (GNOME): an overlay that takes no input shows on + /// XWayland when there is one, and so does one that takes the pointer when its host opted + /// in (`OverlayOptions::xwayland_input`). + #[cfg(all(unix, not(target_os = "macos"), not(target_os = "ios"), not(target_os = "android")))] + pub(super) fn xwayland(&mut self, app: &mut dyn OverlayApp) -> Option<Live> { + let input = self.options.input.resolved(self.interactive); + if !xwayland_allowed(input, self.options.keys, self.options.xwayland_input) { return None; } + let wake = self.shared.wake.lock().unwrap().clone(); + let surface = crate::platform::x11::xwayland::XwaylandSurface::new(self.name, self.at, &self.options, input, wake)?; + let scale = surface.scale(); + self.shared.native.lock().unwrap().1 = crate::OverlayCapabilities { + capture_exclusion: OverlaySupport::Unsupported, global_pointer: OverlaySupport::Unsupported, nonactivating_keys: OverlaySupport::Unsupported, + }; + self.attach(app, Backing::Xwayland(surface), scale) + } + + #[cfg(not(all(unix, not(target_os = "macos"), not(target_os = "ios"), not(target_os = "android"))))] + pub(super) fn xwayland(&mut self, _app: &mut dyn OverlayApp) -> Option<Live> { + None + } +} + +/// Whether an overlay may show on XWayland: one that takes no input always may; one that takes +/// the pointer only by its host's opt-in; one that asks for keys never does. +#[cfg_attr(not(all(unix, not(target_os = "macos"), not(target_os = "ios"), not(target_os = "android"))), allow(dead_code))] +pub(super) fn xwayland_allowed(input: OverlayInput, keys: KeyPolicy, opted_in: bool) -> bool { + keys != KeyPolicy::OnDemand && (input == OverlayInput::None || opted_in) +} diff --git a/app/vendor/rune/crates/rune/src/platform.rs b/app/vendor/rune/crates/rune/src/platform.rs new file mode 100644 index 0000000..00dbd91 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/platform.rs @@ -0,0 +1,36 @@ +pub(crate) mod accent; +#[cfg(all(unix, not(target_os = "macos"), not(target_os = "ios"), not(target_os = "android")))] +pub(crate) mod activation; +pub(crate) mod app_icon; +#[cfg(target_os = "macos")] +pub(crate) mod display_link; +#[cfg(target_vendor = "apple")] +pub mod embed; +#[cfg(any(test, target_vendor = "apple"))] +pub(crate) mod embed_frame; +pub(crate) mod ime; +#[cfg(all(unix, not(target_os = "macos"), not(target_os = "ios"), not(target_os = "android")))] +pub(crate) mod layer_shell; +#[cfg(any(test, all(unix, not(target_os = "macos"), not(target_os = "ios"), not(target_os = "android"))))] +pub(crate) mod layer_shell_machine; +#[cfg(target_os = "macos")] +pub(crate) mod macos; +#[cfg(target_os = "macos")] +pub(crate) use rune_core::main_queue; +#[cfg(any(test, all(target_os = "linux", feature = "dbus")))] +pub(crate) mod portal; +#[cfg(all(target_os = "linux", feature = "dbus"))] +pub(crate) mod portal_appearance; +pub(crate) mod preferences; +#[cfg(not(target_arch = "wasm32"))] +pub(crate) mod ready_signal; +pub(crate) mod reopen; +pub(crate) mod scroll_bars; +#[cfg(target_arch = "wasm32")] +pub mod web; +#[cfg(any(target_arch = "wasm32", test))] +pub(crate) mod web_math; +#[cfg(target_os = "windows")] +pub(crate) mod win32; +#[cfg(all(unix, not(target_os = "macos"), not(target_os = "ios"), not(target_os = "android")))] +pub(crate) mod x11; diff --git a/app/vendor/rune/crates/rune/src/platform/accent.rs b/app/vendor/rune/crates/rune/src/platform/accent.rs new file mode 100644 index 0000000..a170153 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/platform/accent.rs @@ -0,0 +1,176 @@ +//! The user's accent colour and keyboard focus ring colour. macOS reads `controlAccentColor` and +//! `keyboardFocusIndicatorColor` and follows changes; other platforms use macOS's default blue. + +use crate::Color; + +/// The user's accent colour and the colour of keyboard focus rings, each for a light and a dark +/// appearance. Read it with [`system_accent`], or in a view with [`Cx::accent`](crate::Cx::accent) +/// and [`Cx::focus_color`](crate::Cx::focus_color), which pick the window's appearance and re-run +/// the view when the user picks another accent. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct SystemAccent { + accent: [Color; 2], + focus: [Color; 2], +} + +impl SystemAccent { + /// macOS's default blue (`#007AFF` light, `#0A84FF` dark) and its focus ring at 50%: what + /// platforms without an accent setting, and headless runs, report. + pub const DEFAULT: SystemAccent = SystemAccent::new( + Color { r: 0.0, g: 0.194_618, b: 1.0, a: 1.0 }, + Color { r: 0.003_035, g: 0.230_74, b: 1.0, a: 1.0 }, + ); + + /// An accent in light and dark, with focus rings in the same colour at 50%, as AppKit draws + /// them. For tests: `Runtime::set_system_accent(SystemAccent::new(..))`. + pub const fn new(light: Color, dark: Color) -> SystemAccent { + SystemAccent { accent: [light, dark], focus: [half(light), half(dark)] } + } + + /// The same accent with focus rings in these colours. + pub const fn with_focus(self, light: Color, dark: Color) -> SystemAccent { + SystemAccent { focus: [light, dark], ..self } + } + + /// The accent colour for a dark or light appearance. + pub fn accent(&self, dark: bool) -> Color { + self.accent[dark as usize] + } + + /// The keyboard focus ring colour for a dark or light appearance. + pub fn focus(&self, dark: bool) -> Color { + self.focus[dark as usize] + } +} + +const fn half(c: Color) -> Color { + Color { r: c.r, g: c.g, b: c.b, a: c.a * 0.5 } +} + +impl Default for SystemAccent { + fn default() -> Self { SystemAccent::DEFAULT } +} + +/// The user's accent and focus ring colours. On macOS, the accent picked in System Settings +/// (`NSColor.controlAccentColor` and `keyboardFocusIndicatorColor`), read on the main thread +/// and kept up to date while a window is open; elsewhere [`SystemAccent::DEFAULT`]. +pub fn system_accent() -> SystemAccent { + #[cfg(target_os = "macos")] + return mac::current(); + #[cfg(not(target_os = "macos"))] + SystemAccent::DEFAULT +} + +/// Starts following accent changes (`NSSystemColorsDidChangeNotification`), once per process: +/// each change rereads the colours and asks every window to redraw, which hands them to its +/// runtime. Main thread. +pub(crate) fn watch() { + #[cfg(target_os = "macos")] + mac::watch(); +} + +#[cfg(target_os = "macos")] +#[allow(unsafe_code)] +mod mac { + use super::SystemAccent; + use crate::Color; + use objc2::{MainThreadMarker, class, msg_send, rc::Retained, runtime::{AnyObject, Bool, Sel}, sel}; + use objc2_foundation::NSString; + use std::{cell::Cell, rc::Rc, sync::Mutex}; + + static CURRENT: Mutex<Option<SystemAccent>> = Mutex::new(None); + + pub(super) fn current() -> SystemAccent { + let mut current = CURRENT.lock().unwrap_or_else(|e| e.into_inner()); + if current.is_none() && MainThreadMarker::new().is_some() { *current = Some(read()); } + current.unwrap_or_default() + } + + fn read() -> SystemAccent { + let resolve = |selector: Sel| ["NSAppearanceNameAqua", "NSAppearanceNameDarkAqua"].map(|name| resolve(selector, name)); + let ([Some(light), Some(dark)], focus) = (resolve(sel!(controlAccentColor)), resolve(sel!(keyboardFocusIndicatorColor))) + else { return SystemAccent::DEFAULT }; + let accent = SystemAccent::new(light, dark); + match focus { + [Some(light), Some(dark)] => accent.with_focus(light, dark), + _ => accent, + } + } + + /// `NSColor`'s `selector` as `appearance` draws it, in linear sRGB. + fn resolve(selector: Sel, appearance: &str) -> Option<Color> { + let out = Rc::new(Cell::new(None)); + let found = out.clone(); + let read = move || { + // SAFETY: main thread; NSColor's class colours and sRGB conversion return + // autoreleased objects or nil, and the component getters return CGFloat. + unsafe { + let color: *mut AnyObject = msg_send![class!(NSColor), performSelector: selector]; + if color.is_null() { return; } + let space: *mut AnyObject = msg_send![class!(NSColorSpace), sRGBColorSpace]; + let srgb: *mut AnyObject = msg_send![color, colorUsingColorSpace: space]; + if srgb.is_null() { return; } + let [r, g, b, a]: [f64; 4] = [msg_send![srgb, redComponent], msg_send![srgb, greenComponent], + msg_send![srgb, blueComponent], msg_send![srgb, alphaComponent]]; + let d = |v: f64| crate::color::srgb_decode(v.clamp(0.0, 1.0) as f32); + found.set(Some(Color { r: d(r), g: d(g), b: d(b), a: a.clamp(0.0, 1.0) as f32 })); + } + }; + // SAFETY: main thread (callers check); `appearanceNamed:` returns nil for unknown names, + // and the block runs synchronously before `performAsCurrentDrawingAppearance:` returns. + unsafe { + let name = NSString::from_str(appearance); + let appearance: *mut AnyObject = msg_send![class!(NSAppearance), appearanceNamed: &*name]; + let draws: Bool = if appearance.is_null() { Bool::NO } + else { msg_send![appearance, respondsToSelector: sel!(performAsCurrentDrawingAppearance:)] }; + if draws.as_bool() { + let block = block2::RcBlock::new(read); + let _: () = msg_send![appearance, performAsCurrentDrawingAppearance: &*block]; + } else { + read(); + } + } + out.get() + } + + pub(super) fn watch() { + thread_local! { static WATCHING: Cell<bool> = const { Cell::new(false) }; } + if !MainThreadMarker::new().is_some() || WATCHING.replace(true) { return; } + *CURRENT.lock().unwrap_or_else(|e| e.into_inner()) = Some(read()); + let block = block2::RcBlock::new(|_: *mut AnyObject| { + *CURRENT.lock().unwrap_or_else(|e| e.into_inner()) = Some(read()); + // SAFETY: main thread (the observer has no queue, and AppKit posts this there); + // `windows` is an NSArray of NSWindow, each with a content view or nil. + unsafe { + let app: *mut AnyObject = msg_send![class!(NSApplication), sharedApplication]; + let windows: *mut AnyObject = msg_send![app, windows]; + let count: usize = msg_send![windows, count]; + for i in 0..count { + let window: *mut AnyObject = msg_send![windows, objectAtIndex: i]; + let view: *mut AnyObject = msg_send![window, contentView]; + if !view.is_null() { let _: () = msg_send![view, setNeedsDisplay: Bool::YES]; } + } + } + }); + // SAFETY: main thread; the observer lives for the process, so its token is leaked. + unsafe { + let center: Retained<AnyObject> = msg_send![class!(NSNotificationCenter), defaultCenter]; + let name = NSString::from_str("NSSystemColorsDidChangeNotification"); + let token: Option<Retained<AnyObject>> = msg_send![&*center, addObserverForName: &*name, + object: std::ptr::null::<AnyObject>(), queue: std::ptr::null::<AnyObject>(), usingBlock: &*block]; + std::mem::forget(token); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_default_is_macos_blue_with_rings_at_half() { + let a = SystemAccent::DEFAULT; + assert_eq!((a.accent(false).hex(), a.accent(true).hex()), ("#007affff".into(), "#0a84ffff".into())); + assert_eq!((a.focus(false).hex(), a.focus(true).hex()), ("#007aff80".into(), "#0a84ff80".into())); + } +} diff --git a/app/vendor/rune/crates/rune/src/platform/activation.rs b/app/vendor/rune/crates/rune/src/platform/activation.rs new file mode 100644 index 0000000..7e30fb4 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/platform/activation.rs @@ -0,0 +1,88 @@ +//! Focusing an already-mapped Wayland window with a forwarded XDG activation token. winit 0.30 +//! uses a token only while creating a window (`focus_window` is a no-op on Wayland), so this +//! binds `xdg_activation_v1` on winit's own display connection, in a private queue, and +//! activates winit's surface. + +use raw_window_handle::{HasDisplayHandle, HasWindowHandle, RawDisplayHandle, RawWindowHandle}; +use wayland_backend::client::{Backend, ObjectId}; +use wayland_client::globals::{GlobalListContents, registry_queue_init}; +use wayland_client::protocol::wl_registry::WlRegistry; +use wayland_client::protocol::wl_surface::WlSurface; +use wayland_client::{Connection, Dispatch, EventQueue, Proxy, QueueHandle}; +use wayland_protocols::xdg::activation::v1::client::xdg_activation_v1::XdgActivationV1; +use winit::window::Window; + +struct State; + +impl Dispatch<WlRegistry, GlobalListContents> for State { + fn event( + _: &mut Self, + _: &WlRegistry, + _: <WlRegistry as Proxy>::Event, + _: &GlobalListContents, + _: &Connection, + _: &QueueHandle<Self>, + ) { + } +} + +impl Dispatch<XdgActivationV1, ()> for State { + fn event( + _: &mut Self, + _: &XdgActivationV1, + _: <XdgActivationV1 as Proxy>::Event, + _: &(), + _: &Connection, + _: &QueueHandle<Self>, + ) { + } +} + +/// One window's activation binding, made on first use and kept with the window. +pub(crate) struct Activator { + queue: EventQueue<State>, + activation: XdgActivationV1, + surface: WlSurface, +} + +impl Activator { + /// None off Wayland or when the compositor lacks `xdg_activation_v1`. + #[allow(unsafe_code)] + pub fn new(window: &Window) -> Option<Activator> { + let (RawDisplayHandle::Wayland(display), RawWindowHandle::Wayland(handle)) = ( + window.display_handle().ok()?.as_raw(), + window.window_handle().ok()?.as_raw(), + ) else { + return None; + }; + // SAFETY: winit owns this `wl_display` and keeps it alive for the event loop, which + // outlives every window; a foreign backend never closes it. + let backend = unsafe { Backend::from_foreign_display(display.display.as_ptr().cast()) }; + let conn = Connection::from_backend(backend); + let (globals, queue) = registry_queue_init::<State>(&conn).ok()?; + let activation = globals.bind::<XdgActivationV1, _, _>(&queue.handle(), 1..=1, ()).ok()?; + // SAFETY: the pointer is the live `wl_surface` proxy winit created for this window, and + // the activator is dropped before the window. + let id = unsafe { ObjectId::from_ptr(WlSurface::interface(), handle.surface.as_ptr().cast()) }.ok()?; + let surface = WlSurface::from_id(&conn, id).ok()?; + Some(Activator { + queue, + activation, + surface, + }) + } + + /// Asks the compositor to focus the window. It decides: an expired or foreign token is + /// ignored, or only marks the window urgent. + pub fn activate(&mut self, token: &str) { + self.activation.activate(token.to_owned(), &self.surface); + self.queue.flush().ok(); + } +} + +impl Drop for Activator { + fn drop(&mut self) { + self.activation.destroy(); + self.queue.flush().ok(); + } +} diff --git a/app/vendor/rune/crates/rune/src/platform/app_icon.rs b/app/vendor/rune/crates/rune/src/platform/app_icon.rs new file mode 100644 index 0000000..f79fe1f --- /dev/null +++ b/app/vendor/rune/crates/rune/src/platform/app_icon.rs @@ -0,0 +1,144 @@ +//! The app's icon from image bytes (the Dock's on macOS, its windows' and the taskbar's on +//! Windows), so an app needs no platform glue of its own. + +#[cfg(any(target_os = "macos", target_os = "windows"))] +use std::sync::Mutex; +#[cfg(target_os = "macos")] +use std::sync::atomic::{AtomicBool, Ordering}; + +/// The icon waiting for the main thread, newest wins. +#[cfg(target_os = "macos")] +static PENDING: Mutex<Option<Vec<u8>>> = Mutex::new(None); +/// The event loop has started, so AppKit is ours to call. +#[cfg(target_os = "macos")] +static LAUNCHED: AtomicBool = AtomicBool::new(false); + +/// The app's icon while it runs, in place of the bundle's or executable's. Call it from any +/// thread. A headless run sets nothing. Fails when the bytes aren't an image. +/// +/// - **macOS:** `bytes` is an `.icns`, PNG, TIFF or anything else `NSImage` reads, shown as the +/// Dock and app-switcher icon. Before `run`, Rune sets it once the app finishes launching; a +/// later call replaces it. (`AppHandle::set_dock_icon` shows or hides the Dock icon instead.) +/// - **Windows:** `bytes` is a PNG or JPEG, best square and 256 px or more. Each window opened +/// after the call shows it in its title bar, on the taskbar and in Alt+Tab, so call it before +/// `run`. +/// - Does nothing elsewhere. +pub fn set_app_icon(bytes: impl Into<Vec<u8>>) -> Result<(), String> { + #[cfg(target_os = "macos")] + { + let bytes = bytes.into(); + if decode(&bytes).is_none() { return Err("set_app_icon: the bytes aren't an image AppKit reads".into()); } + *PENDING.lock().unwrap_or_else(|e| e.into_inner()) = Some(bytes); + if LAUNCHED.load(Ordering::Acquire) { crate::platform::main_queue::on_main(apply); } + } + #[cfg(target_os = "windows")] + { + let image = image::load_from_memory(&bytes.into()).map_err(|e| format!("set_app_icon: {e}"))?.into_rgba8(); + let size = |px: u32| image::imageops::resize(&image, px, px, image::imageops::FilterType::Lanczos3).into_raw(); + *WINDOWS.lock().unwrap_or_else(|e| e.into_inner()) = Some(WindowsIcon::Pixels { small: size(SMALL), big: size(BIG) }); + } + #[cfg(not(any(target_os = "macos", target_os = "windows")))] + let _ = bytes; + Ok(()) +} + +/// Windows: the app's icon from the executable's own icon resource `id` (the one Explorer shows), +/// in place of `set_app_icon`'s bytes: each window loads it at the size it shows with +/// `LoadImageW`, so nothing is decoded or resized at launch. Give the resource bitmap images up to +/// 128 px (a PNG-compressed image larger than that is never asked for). Call it before `run`. +#[cfg(target_os = "windows")] +pub fn set_app_icon_resource(id: u16) { + *WINDOWS.lock().unwrap_or_else(|e| e.into_inner()) = Some(WindowsIcon::Resource(id)); +} + +/// Windows: where each new window's `HICON`s come from. The small one draws in the title bar and +/// the taskbar's small mode; the big one on the taskbar and in Alt+Tab, where Windows scales it to +/// the display's DPI. +#[cfg(target_os = "windows")] +enum WindowsIcon { + /// Pixels at the two sizes, from `set_app_icon`. + Pixels { small: Vec<u8>, big: Vec<u8> }, + /// The executable's icon resource, from `set_app_icon_resource`. + Resource(u16), +} + +#[cfg(target_os = "windows")] +static WINDOWS: Mutex<Option<WindowsIcon>> = Mutex::new(None); +#[cfg(target_os = "windows")] +const SMALL: u32 = 32; +#[cfg(target_os = "windows")] +const BIG: u32 = 256; +/// The big icon taken from the exe's resources: the largest size an icon resource keeps as a +/// bitmap. Its 256 px image is a PNG, which `LoadImageW` decodes through WIC (`WindowsCodecs.dll` +/// and `IconCodecService.dll` loaded on the UI thread before the first frame); 128 px still +/// covers the taskbar and Alt+Tab at 400%. +#[cfg(target_os = "windows")] +const BIG_RESOURCE: u32 = 128; + +/// Windows: `attrs` with the app's icon, once `set_app_icon` has one. +#[cfg(target_os = "windows")] +pub(crate) fn with_icon(attrs: winit::window::WindowAttributes) -> winit::window::WindowAttributes { + use winit::platform::windows::{IconExtWindows, WindowAttributesExtWindows}; + use winit::window::Icon; + let icon = WINDOWS.lock().unwrap_or_else(|e| e.into_inner()); + let (small, big) = match icon.as_ref() { + None => return attrs, + Some(WindowsIcon::Pixels { small, big }) => (Icon::from_rgba(small.clone(), SMALL, SMALL).ok(), Icon::from_rgba(big.clone(), BIG, BIG).ok()), + Some(WindowsIcon::Resource(id)) => { + let at = |px: u32| Icon::from_resource(*id, Some(winit::dpi::PhysicalSize::new(px, px))).ok(); + (at(SMALL), at(BIG_RESOURCE)) + } + }; + attrs.with_window_icon(small).with_taskbar_icon(big) +} + +/// The event loop exists: sets an icon asked for before `run` once the main queue drains, which +/// is after AppKit finishes launching (it would show the bundle's icon over an earlier one). +#[cfg(target_os = "macos")] +pub(crate) fn launched() { + LAUNCHED.store(true, Ordering::Release); + crate::platform::main_queue::on_main(apply); +} + +#[cfg(target_os = "macos")] +fn decode(bytes: &[u8]) -> Option<objc2::rc::Retained<objc2_app_kit::NSImage>> { + use objc2::AnyThread; + use objc2_app_kit::NSImage; + use objc2_foundation::NSData; + // NSImage may be created and read on any thread; it's nil for data it can't read. + let image = NSImage::initWithData(NSImage::alloc(), &NSData::with_bytes(bytes))?; + // An image with no readable representation has no size. + let size = image.size(); + (size.width > 0.0 && size.height > 0.0).then_some(image) +} + +#[cfg(target_os = "macos")] +#[allow(unsafe_code)] +fn apply() { + let Some(mtm) = objc2::MainThreadMarker::new() else { return }; + let Some(bytes) = PENDING.lock().unwrap_or_else(|e| e.into_inner()).take() else { return }; + let Some(image) = decode(&bytes) else { return }; + let app = objc2_app_kit::NSApplication::sharedApplication(mtm); + // SAFETY: on the main thread, with an image AppKit decoded. + unsafe { app.setApplicationIconImage(Some(&image)) }; +} + +#[cfg(all(test, target_os = "macos"))] +mod tests { + use super::*; + + fn png() -> Vec<u8> { + let mut out = std::io::Cursor::new(Vec::new()); + image::RgbaImage::from_pixel(16, 16, image::Rgba([40, 120, 220, 255])).write_to(&mut out, image::ImageFormat::Png).unwrap(); + out.into_inner() + } + + #[test] + fn an_icon_must_be_an_image_and_waits_for_launch() { + assert!(set_app_icon(b"not an image".to_vec()).is_err()); + assert!(set_app_icon(png()).is_ok()); + // Without an event loop nothing touches NSApplication, so a headless run stays windowless. + assert!(!LAUNCHED.load(Ordering::Acquire)); + assert!(PENDING.lock().unwrap().is_some()); + } +} diff --git a/app/vendor/rune/crates/rune/src/platform/display_link.rs b/app/vendor/rune/crates/rune/src/platform/display_link.rs new file mode 100644 index 0000000..b1b59f1 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/platform/display_link.rs @@ -0,0 +1,338 @@ +//! One drawable submission per display tick. Metal's drawable pool is not a frame clock: +//! acquisition may return immediately even with FIFO presentation enabled. The exception is a +//! frame after rest, such as the first after a key press: it draws at once (`rested`). +//! +//! Low Power Mode caps a ProMotion panel at 60 Hz while CVDisplayLink, CADisplayLink and +//! NSScreen all still report 120 Hz. Submitting on every tick then fills the drawable queue +//! with a few fast frames before backpressure settles it at 60 Hz, so pace at the cap instead. +#![allow(deprecated)] // CVDisplayLink supports the same macOS versions as winit. +#![allow(unsafe_code)] + +use std::ffi::c_void; +use std::ptr::NonNull; +use std::sync::Mutex; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; +use std::time::{Duration, Instant}; +use objc2_core_foundation::CFRetained; +use objc2_core_video::{CVDisplayLink, CVGetCurrentHostTime, CVGetHostClockFrequency, CVOptionFlags, CVReturn, CVTimeStamp, CVTimeStampFlags}; +use winit::{platform::macos::MonitorHandleExtMacOS, window::Window}; + +struct Callback { + target: AtomicU64, + period_ns: AtomicU64, + wake: crate::runtime::Waker, + host_frequency: f64, +} + +pub(crate) struct DisplayLink { + link: CFRetained<CVDisplayLink>, + // Stable allocation, retained until stop has joined the callback thread. + callback: Box<Callback>, + last_present: Option<Instant>, + last_target: Option<Instant>, + display: Option<u32>, + capped: bool, + running: bool, +} + +const LOW_POWER_FRAME: Duration = Duration::from_nanos(1_000_000_000 / 60); +static CREATE_FAILED: AtomicBool = AtomicBool::new(false); +/// The last creation's CoreVideo status (0 once one succeeds), and when it failed. +static LAST_FAILURE: Mutex<Option<(i32, Instant)>> = Mutex::new(None); +/// How long after a failed creation `retry` tries again. +const RETRY: Duration = Duration::from_secs(1); + +/// Why the last display link couldn't be made, while no creation has succeeded since. +pub(crate) fn failure() -> Option<i32> { LAST_FAILURE.lock().unwrap().map(|(status, _)| status) } + +/// How a surface's frames are paced, from its display link (or the lack of one). +pub(crate) fn pacing(link: Option<&DisplayLink>, moving: bool) -> crate::frame::surface_stats::Pacing { + use crate::frame::surface_stats::Pacing; + match (link, failure()) { + (Some(link), _) if link.running() => Pacing::DisplayLink, + (None, Some(status)) => Pacing::Failed(status), + _ if moving => Pacing::Unpaced, + _ => Pacing::Idle, + } +} + +#[link(name = "CoreGraphics", kind = "framework")] +unsafe extern "C" { fn CGDisplayIsBuiltin(display: u32) -> u32; } + +fn low_power_caps(display: Option<u32>) -> bool { + use objc2_foundation::{NSObjectProtocol, NSProcessInfo}; + let info = NSProcessInfo::processInfo(); + // SAFETY: `CGDisplayIsBuiltin` accepts any `CGDirectDisplayID`. + display.is_some_and(|display| unsafe { CGDisplayIsBuiltin(display) } != 0) + && info.respondsToSelector(objc2::sel!(isLowPowerModeEnabled)) + && info.isLowPowerModeEnabled() +} + +unsafe extern "C-unwind" fn tick( + _: NonNull<CVDisplayLink>, _: NonNull<CVTimeStamp>, output: NonNull<CVTimeStamp>, + _: CVOptionFlags, _: NonNull<CVOptionFlags>, context: *mut c_void, +) -> CVReturn { + // SAFETY: CoreVideo borrows the boxed context until DisplayLink::drop stops the link. + let callback = unsafe { &*context.cast::<Callback>() }; + // SAFETY: CoreVideo provides a valid timestamp for this callback invocation. + let output = unsafe { output.as_ref() }; + if output.videoTimeScale > 0 && output.videoRefreshPeriod > 0 { + let period = Duration::from_secs_f64(output.videoRefreshPeriod as f64 / output.videoTimeScale as f64); + callback.period_ns.store(period.as_nanos() as u64, Ordering::Relaxed); + } + let target = if output.flags & CVTimeStampFlags::HostTimeValid.0 != 0 { + output.hostTime + } else { + CVGetCurrentHostTime() + (callback.period_ns.load(Ordering::Relaxed) as f64 * 1e-9 * callback.host_frequency) as u64 + }; + let pending = callback.target.swap(target, Ordering::Release) != 0; + // Coalesce a backed-up event loop; missed refreshes never become a catch-up burst. + // Never call Window::request_redraw here: winit synchronously waits on the main + // thread on macOS, which can itself be waiting in CVDisplayLinkStop. + if !pending { (callback.wake)(); } + 0 +} + +impl DisplayLink { + pub(crate) fn running(&self) -> bool { self.running } + pub(crate) fn refresh_hz(&self) -> f64 { 1.0 / self.frame_period().as_secs_f64() } + + fn frame_period(&self) -> Duration { + let period = Duration::from_nanos(self.callback.period_ns.load(Ordering::Relaxed)); + if self.capped { period.max(LOW_POWER_FRAME) } else { period } + } + + pub(crate) fn new(window: &Window, wake: crate::runtime::Waker) -> Option<Self> { + let mut raw = std::ptr::null_mut(); + // SAFETY: valid out pointer; the create rule transfers one retained reference. + let status = unsafe { CVDisplayLink::create_with_active_cg_displays(NonNull::from(&mut raw)) }; + // Every display asleep fails this until one wakes, so say so once per sleep. + if status != 0 { + if !CREATE_FAILED.swap(true, Ordering::Relaxed) { eprintln!("display link creation failed: {status}"); } + *LAST_FAILURE.lock().unwrap() = Some((status, crate::time::now())); + return None; + } + if CREATE_FAILED.swap(false, Ordering::Relaxed) { eprintln!("display link created once a display woke"); } + *LAST_FAILURE.lock().unwrap() = None; + // SAFETY: `create_with_active_cg_displays` succeeded (`status == 0`), so non-null `raw` is a +1 retained `CVDisplayLink` per the Create Rule. + let link = unsafe { CFRetained::from_raw(NonNull::new(raw)?) }; + let mut callback = Box::new(Callback { + target: AtomicU64::new(0), + period_ns: AtomicU64::new(1_000_000_000 / 60), + wake, + host_frequency: CVGetHostClockFrequency(), + }); + // SAFETY: `tick` matches `CVDisplayLinkOutputCallback`, and `callback` stays at a stable heap address until `DisplayLink::drop` stops the link. + let status = unsafe { link.set_output_callback(Some(tick), (&mut *callback as *mut Callback).cast()) }; + if status != 0 { eprintln!("display link callback failed: {status}"); return None; } + let mut pacing = Self { link, callback, last_present: None, last_target: None, display: None, capped: false, running: false }; + pacing.update_display(window); + Some(pacing) + } + + /// A surface presenting without a display link (its creation failed while the displays + /// slept) tries again after each present, at most once a `RETRY` across surfaces. + pub(crate) fn retry(window: &Window, wake: crate::runtime::Waker) -> Option<Self> { + if LAST_FAILURE.lock().unwrap().is_some_and(|(_, at)| at.elapsed() < RETRY) { return None; } + Self::new(window, wake) + } + + /// AppKit monitor lookup is only needed on creation and display/visibility changes. + pub(crate) fn update_display(&mut self, window: &Window) { + let display = window.current_monitor().map(|m| m.native_id()); + if display != self.display { + if let Some(display) = display { self.link.set_current_cg_display(display); } + self.display = display; + } + self.capped = low_power_caps(self.display); + } + + /// Starts the link if it was stopped; false if Core Video refused to start it. + pub(crate) fn start(&mut self) -> bool { + if !self.running { + let status = self.link.start(); + if status != 0 { eprintln!("display link start failed: {status}"); return false; } + self.running = true; + // Power state can change while idle; each burst rechecks it. + self.capped = low_power_caps(self.display); + } + true + } + + /// Claims one display opportunity: a tick and its target presentation time, or at once + /// when the surface has rested (`rested`). Consume before rendering so a tick arriving + /// during rendering can queue the next opportunity. + pub(crate) fn next_frame(&mut self) -> Opportunity { + if !self.start() { return Opportunity::Now; } + let host_target = self.callback.target.swap(0, Ordering::Acquire); + let now = crate::time::now(); + let tick = (host_target != 0).then(|| target_time(now, CVGetCurrentHostTime(), host_target, self.callback.host_frequency)); + let next = opportunity(tick, self.last_present, self.last_target, now, self.frame_period()); + match next { + Opportunity::Tick(target) => self.last_target = Some(target), + Opportunity::Now => self.last_target = Some(now), + Opportunity::Wait => {} + } + next + } + + /// Whether a frame that may draw nothing (a timer's, on a resting surface) can decide that + /// before starting the link: it's stopped, and `next_frame` would answer `Now` whenever + /// asked from here on, so starting it once the frame turns out to draw paces it the same. + pub(crate) fn defers_start(&self, now: Instant) -> bool { + defers_start(self.running, self.last_present, self.last_target, now, self.frame_period()) + } + + /// The tick after `now`, as if the link were running. + pub(crate) fn tick_after(&self, now: Instant) -> Instant { now + self.frame_period() } + + pub(crate) fn presented(&mut self, at: Instant) { + self.last_present = Some(at); + } + + pub(crate) fn stop(&mut self) { + if self.running { self.link.stop(); self.running = false; } + self.callback.target.store(0, Ordering::Relaxed); + } +} + +impl Drop for DisplayLink { + fn drop(&mut self) { self.stop(); } +} + +fn target_time(now: Instant, host_now: u64, host_target: u64, frequency: f64) -> Instant { + let delta = Duration::from_secs_f64(host_target.abs_diff(host_now) as f64 / frequency); + if host_target >= host_now { now + delta } else { now - delta } +} + +/// When a surface's next frame draws. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum Opportunity { + /// On this tick, which presents at its target. + Tick(Instant), + /// At once, aimed at no tick (`rested`). + Now, + /// On a later tick. + Wait, +} + +impl Opportunity { + /// The frame's target presentation time if it draws now (`None` when aimed at no tick), or + /// `None` when it waits. + pub(crate) fn target(self) -> Option<Option<Instant>> { + match self { + Self::Tick(target) => Some(Some(target)), + Self::Now => Some(None), + Self::Wait => None, + } + } +} + +/// A fresh tick wins. Without one, a surface that has rested draws at once rather than wait +/// for the link to start or tick, which after idle took one to two refreshes. +fn opportunity(tick: Option<Instant>, last: Option<Instant>, last_target: Option<Instant>, now: Instant, period: Duration) -> Opportunity { + // A late render followed by an on-time tick must skip, not submit two frames + // together. Also discard stale callbacks after main-thread stalls. + match tick { + Some(target) if permits(last, last_target, target, now, period) => Opportunity::Tick(target), + _ if rested(last, last_target, now, period) => Opportunity::Now, + _ => Opportunity::Wait, + } +} + +fn permits(last: Option<Instant>, last_target: Option<Instant>, target: Instant, now: Instant, period: Duration) -> bool { + let half = period / 2; + now < target && last_target.is_none_or(|last| target >= last + period * 3 / 4) + && last.is_none_or(|last| now.saturating_duration_since(last) >= half) +} + +/// Whether the last frame has surely reached the display: its target has passed, and a whole +/// refresh has gone by since it was submitted, plus half of one for the GPU. Another frame then +/// can't queue behind it, so one at once costs no pacing: it shows at the next refresh. +fn rested(last: Option<Instant>, last_target: Option<Instant>, now: Instant, period: Duration) -> bool { + last_target.is_none_or(|target| target <= now) + && last.is_none_or(|last| now.saturating_duration_since(last) >= period * 3 / 2) +} + +/// A stopped link has no tick waiting (`stop` clears it), so a rested surface's next frame is +/// `Now` until the link starts: deciding first costs it no pacing. +fn defers_start(running: bool, last: Option<Instant>, last_target: Option<Instant>, now: Instant, period: Duration) -> bool { + !running && rested(last, last_target, now, period) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_frame_defers_starting_the_link_only_when_it_would_draw_at_once_anyway() { + let t = crate::time::now(); + let ms = |n| t + Duration::from_millis(n); + let period = Duration::from_millis(8); + // A timer 33 ms after the last frame: whenever it starts the link, it draws at once. + assert!(defers_start(false, Some(ms(100)), Some(ms(104)), ms(133), period)); + for later in [133, 134, 150, 500] { + assert_eq!(opportunity(None, Some(ms(100)), Some(ms(104)), ms(later), period), Opportunity::Now); + } + assert!(defers_start(false, None, None, ms(0), period)); + // The last frame may still be queued: start the link now and wait for its tick. + assert!(!defers_start(false, Some(ms(100)), Some(ms(100)), ms(105), period)); + assert!(!defers_start(false, Some(ms(100)), Some(ms(130)), ms(120), period)); + // A running link already paces the surface. + assert!(!defers_start(true, Some(ms(100)), Some(ms(104)), ms(133), period)); + } + #[test] + fn late_frames_and_idle_restarts_cannot_catch_up_in_a_burst() { + let t = crate::time::now(); + let ms = |n| t + Duration::from_millis(n); + let period = Duration::from_millis(16); + assert!(permits(None, None, ms(16), ms(1), period)); + assert!(!permits(Some(ms(15)), Some(ms(16)), ms(32), ms(17), period)); + assert!(!permits(Some(ms(15)), Some(ms(16)), ms(32), ms(33), period)); + assert!(!permits(Some(ms(15)), Some(ms(32)), ms(32), ms(30), period)); + assert!(permits(Some(ms(15)), Some(ms(16)), ms(32), ms(30), period)); + assert!(!permits(Some(ms(100)), Some(ms(112)), ms(128), ms(102), period)); + assert_eq!(target_time(t, 100, 116, 1000.0), ms(16)); + assert_eq!(target_time(ms(32), 132, 116, 1000.0), ms(16)); + } + + #[test] + fn a_capped_period_skips_ticks_between_frames() { + let t = crate::time::now(); + let ms = |n| t + Duration::from_millis(n); + let capped = Duration::from_millis(16); + assert!(!permits(Some(ms(0)), Some(ms(8)), ms(16), ms(9), capped)); + assert!(permits(Some(ms(2)), Some(ms(8)), ms(24), ms(17), capped)); + assert!(permits(Some(ms(2)), Some(ms(8)), ms(16), ms(9), Duration::from_millis(8))); + } + + #[test] + fn input_at_rest_draws_without_waiting_for_a_tick() { + let t = crate::time::now(); + let ms = |n| t + Duration::from_millis(n); + let period = Duration::from_millis(8); + // The link just started after idle: no tick yet, the last frame long gone. + assert_eq!(opportunity(None, Some(ms(0)), Some(ms(8)), ms(500), period), Opportunity::Now); + assert_eq!(opportunity(None, None, None, ms(0), period), Opportunity::Now); + // A stale tick after a stall doesn't hold a rested surface either. + assert_eq!(opportunity(Some(ms(400)), Some(ms(0)), Some(ms(8)), ms(500), period), Opportunity::Now); + // A fresh tick keeps its target. + assert_eq!(opportunity(Some(ms(510)), Some(ms(0)), Some(ms(8)), ms(500), period), Opportunity::Tick(ms(510))); + } + + #[test] + fn a_frame_still_on_its_way_to_the_display_waits_for_a_tick() { + let t = crate::time::now(); + let ms = |n| t + Duration::from_millis(n); + let period = Duration::from_millis(8); + // Submitted under a refresh and a half ago: it may still be queued. + assert_eq!(opportunity(None, Some(ms(100)), Some(ms(100)), ms(111), period), Opportunity::Wait); + assert_eq!(opportunity(None, Some(ms(100)), Some(ms(100)), ms(112), period), Opportunity::Now); + // Its target hasn't passed. + assert_eq!(opportunity(None, Some(ms(100)), Some(ms(130)), ms(120), period), Opportunity::Wait); + // A Low Power cap stretches the period, and with it the rest. + assert_eq!(opportunity(None, Some(ms(100)), Some(ms(100)), ms(118), Duration::from_millis(16)), Opportunity::Wait); + // While moving, a rejected tick right after a frame waits for the next one. + assert_eq!(opportunity(Some(ms(116)), Some(ms(100)), Some(ms(108)), ms(102), period), Opportunity::Wait); + } +} diff --git a/app/vendor/rune/crates/rune/src/platform/embed.rs b/app/vendor/rune/crates/rune/src/platform/embed.rs new file mode 100644 index 0000000..da567e0 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/platform/embed.rs @@ -0,0 +1,362 @@ +//! Embedded `CAMetalLayer` host for UIKit, SwiftUI and AppKit views that own their own window +//! and event loop (e.g. a `UIViewRepresentable` driven by `CADisplayLink` on iOS). + +#![allow(unsafe_code)] + +use std::ffi::c_void; +use std::sync::{Arc, OnceLock}; + +use crate::compose::{Compositor, Frame}; +use crate::frame::clock::FrameClock; +use crate::frame::host_step::{self, Acquire}; +use crate::platform::embed_frame::{self, EmbedSurface, FrameSummary}; +use crate::render::{Gpu, Renderer}; +use crate::runtime::{AppDriver, Env, Runtime, RuntimeCore, Waker}; +use crate::time::Instant; +use crate::tooling::{AppSpec, runtime_for}; +use crate::window::Missed; + +static SHARED_GPU: OnceLock<Result<Arc<Gpu>, String>> = OnceLock::new(); + +fn shared_gpu() -> Result<Arc<Gpu>, String> { + SHARED_GPU + .get_or_init(|| Gpu::try_new(Gpu::instance(), None).map(Arc::new)) + .clone() +} + +/// Warms the shared Metal device and compiles the default `Bgra8Unorm` uber pipeline on a +/// background thread so the first embedded `LayerHost` opens without shader-compile latency. +pub fn prewarm() { + static STARTED: OnceLock<()> = OnceLock::new(); + STARTED.get_or_init(|| { + std::thread::Builder::new().name("rune-embed-prewarm".into()).spawn(|| { + if let Ok(gpu) = shared_gpu() { + let _ = Renderer::new(&gpu.device, wgpu::TextureFormat::Bgra8Unorm); + } + }).ok(); + }); +} + +/// Outcome of one [`LayerHost::frame`] pass. +#[derive(Clone, Copy, Debug, Default)] +pub struct EmbedFrame { + /// Whether a drawable was acquired and presented. + pub drew: bool, + /// True while springs, reveals, pending input or live bindings need another display-link tick. + pub animating: bool, + /// Seconds until the next scheduled timer wake (`None` when none is pending). + pub wake_after_secs: Option<f64>, + /// CPU time spent stepping layout/motion and encoding GPU work, in microseconds. + pub cpu_us: u64, +} + +impl From<FrameSummary> for EmbedFrame { + fn from(s: FrameSummary) -> Self { + Self { + drew: s.drew, + animating: s.animating, + wake_after_secs: s.wake_after_secs, + cpu_us: s.cpu_us, + } + } +} + +pub(crate) struct PreparedEmbedFrame { + frame: wgpu::SurfaceTexture, + target: wgpu::TextureView, + encoder: wgpu::CommandEncoder, + size: (u32, u32), + format: wgpu::TextureFormat, +} + +struct LayerHostCore { + gpu: Arc<Gpu>, + surface: wgpu::Surface<'static>, + config: wgpu::SurfaceConfiguration, + renderer: Renderer, + clock: FrameClock, + suspended: bool, +} + +impl LayerHostCore { + unsafe fn new(layer: *mut c_void, viewport: (f32, f32), scale: f32) -> Result<(Self, (f32, f32), f32, Instant), String> { + if layer.is_null() { + return Err("null CAMetalLayer pointer".into()); + } + let gpu = shared_gpu()?; + // SAFETY: caller guarantees non-null `layer` is a valid `CAMetalLayer` outliving this surface on an allowed thread. + let surface = unsafe { + gpu.instance + .create_surface_unsafe(wgpu::SurfaceTargetUnsafe::CoreAnimationLayer(layer)) + .map_err(|e| format!("create_surface_unsafe: {e}"))? + }; + let scale = scale.max(1.0); + let max_dim = gpu.device.limits().max_texture_dimension_2d.max(1); + let px_w = ((viewport.0.max(1.0) * scale).round() as u32).clamp(1, max_dim); + let px_h = ((viewport.1.max(1.0) * scale).round() as u32).clamp(1, max_dim); + let srgb_blend = true; + let (config, _) = crate::window::surface_config(&surface, &gpu.adapter, (px_w, px_h), srgb_blend) + .ok_or_else(|| "CAMetalLayer has no supported wgpu surface configuration".to_owned())?; + crate::window::configure(&surface, &gpu, &config)?; + let target_format = config.format.remove_srgb_suffix(); + let mut renderer = Renderer::new(&gpu.device, target_format); + renderer.set_srgb_blend(true); + let size = (px_w as f32 / scale, px_h as f32 / scale); + let now = crate::time::now(); + let core = Self { + gpu, + surface, + config, + renderer, + clock: FrameClock::new(now), + suspended: viewport.0 <= 0.0 || viewport.1 <= 0.0, + }; + Ok((core, size, scale, now)) + } + + fn configure_runtime(&mut self, rt: &mut RuntimeCore, now: Instant) { + rt.set_srgb_blend(true); + rt.set_os_drag(false); + rt.wall_start = Some(now); + rt.frame.set_record_events(false); + let target_format = if rt.srgb_blend() { self.config.format.remove_srgb_suffix() } else { self.config.format }; + crate::window::rebuild_renderer_core(&self.gpu.device, &mut self.renderer, target_format, rt); + } + + fn resize(&mut self, rt: &mut RuntimeCore, viewport: (f32, f32), scale: f32) { + if viewport.0 <= 0.0 || viewport.1 <= 0.0 { + self.suspended = true; + return; + } + self.suspended = false; + let scale = scale.max(1.0); + let max_dim = self.gpu.device.limits().max_texture_dimension_2d.max(1); + let px_w = ((viewport.0 * scale).round() as u32).clamp(1, max_dim); + let px_h = ((viewport.1 * scale).round() as u32).clamp(1, max_dim); + if self.config.width != px_w || self.config.height != px_h { + self.config.width = px_w; + self.config.height = px_h; + if let Err(error) = crate::window::configure(&self.surface, &self.gpu, &self.config) { + eprintln!("rune: embedded layer surface refused its new size: {error}"); + } + } + rt.set_viewport((px_w as f32 / scale, px_h as f32 / scale), scale); + } + + /// Acquires the next drawable, reconfiguring and retrying once on `Outdated`/`Lost`. + fn acquire(&mut self) -> Acquire<wgpu::SurfaceTexture> { + let mut retries = 1u8; + loop { + match self.surface.get_current_texture() { + wgpu::CurrentSurfaceTexture::Success(f) | wgpu::CurrentSurfaceTexture::Suboptimal(f) => return Acquire::Ready(f), + wgpu::CurrentSurfaceTexture::Outdated | wgpu::CurrentSurfaceTexture::Lost => { + if let Err(error) = crate::window::configure(&self.surface, &self.gpu, &self.config) { + eprintln!("rune: embedded layer surface refused reconfiguration: {error}"); + return Acquire::Missed(Missed::Unconfigured); + } + if retries == 0 { return Acquire::Missed(Missed::Outdated); } + retries -= 1; + } + _ => return Acquire::Missed(Missed::Timeout), + } + } + } + + fn reblend(&mut self, rt: &mut RuntimeCore) -> bool { + let mut alpha = None; + crate::window::reblend_core(&self.surface, &self.gpu, &mut self.config, &mut self.renderer, &mut alpha, rt) + } + + fn prepare_draw(&mut self, rt: &mut RuntimeCore, frame: wgpu::SurfaceTexture) -> PreparedEmbedFrame { + let target_format = if rt.srgb_blend() { self.config.format.remove_srgb_suffix() } else { self.config.format }; + let target = frame.texture.create_view(&wgpu::TextureViewDescriptor { + format: (target_format != self.config.format).then_some(target_format), + ..Default::default() + }); + let size = (self.config.width, self.config.height); + host_step::prepare_gpu_resources(&mut self.renderer, &self.gpu, rt, size, true); + let encoder = self.gpu.device.create_command_encoder(&Default::default()); + PreparedEmbedFrame { frame, target, encoder, size, format: target_format } + } + + fn draw_default(&mut self, rt: &mut RuntimeCore, prepared: &mut PreparedEmbedFrame) { + let clear = rt.clear_color(); + host_step::draw_ui(&mut self.renderer, &self.gpu, &mut prepared.encoder, &prepared.target, rt, prepared.size, clear); + } + + fn submit_and_present(&mut self, prepared: PreparedEmbedFrame) -> Instant { + self.renderer.submit(&self.gpu.queue, prepared.encoder); + self.gpu.queue.present(prepared.frame); + crate::render::gpu_events::presented(); + crate::time::now() + } +} + +/// Drives one Rune [`Runtime`] and [`Renderer`] directly onto a `CAMetalLayer`. +/// +/// Pause display-link calls while the host app is backgrounded on iOS: Metal forbids drawable +/// acquisition and command-buffer submission after `didEnterBackground`. +pub struct LayerHost<S: 'static> { + core: LayerHostCore, + compositor: Option<Box<dyn Compositor<S>>>, + rt: Runtime<S>, +} + +impl<S: 'static> LayerHost<S> { + /// Attaches a new Rune runtime and Metal surface to `layer` (`CAMetalLayer *`), blending in + /// sRGB space (`srgb_blend = true`, matching Apple's native text compositing). + /// + /// # Safety + /// `layer` must be a valid `CAMetalLayer` pointer that outlives this `LayerHost`, and surface + /// creation / presentation must run on a thread allowed to touch that layer (the UI thread). + pub unsafe fn from_core_animation_layer( + layer: *mut c_void, + spec: &AppSpec<S>, + state: S, + viewport: (f32, f32), + scale: f32, + dark: bool, + wake: Waker, + ) -> Result<Self, String> { + // SAFETY: caller upholds `from_core_animation_layer`'s safety contract (`layer` is a valid `CAMetalLayer` outliving `LayerHost`, on the UI thread). + let (mut core, size, scale, now) = unsafe { LayerHostCore::new(layer, viewport, scale) }?; + let mut rt = runtime_for(spec, state, size, Env::new(dark, scale), wake); + core.configure_runtime(rt.core_mut(), now); + Ok(Self { core, compositor: None, rt }) + } + + /// Attaches a custom [`Compositor`] (e.g. for [`El::effect`](crate::El::effect) shader passes) + /// and turns on `Runtime::track_marks` so `rt.marks` aligns with `rt.instances`. + pub fn with_compositor(mut self, compositor: impl Compositor<S>) -> Self { + self.rt.track_marks = true; + self.compositor = Some(Box::new(compositor)); + self + } + + pub fn runtime(&self) -> &Runtime<S> { + &self.rt + } + + pub fn runtime_mut(&mut self) -> &mut Runtime<S> { + &mut self.rt + } + + /// Updates the viewport in points and display scale, reconfiguring the Metal swapchain only + /// when its clamped device-pixel dimensions change. + pub fn resize(&mut self, viewport: (f32, f32), scale: f32) { + self.core.resize(self.rt.core_mut(), viewport, scale); + } + + /// Steps animations and layout to `Instant::now()` and presents one Metal frame, following + /// the shared [`crate::frame::host_step`] order. + pub fn frame(&mut self) -> EmbedFrame { + embed_frame::run_embed_frame(self).into() + } +} + +impl<S: 'static> EmbedSurface for LayerHost<S> { + type Drawable = wgpu::SurfaceTexture; + type Prepared = PreparedEmbedFrame; + + fn suspended(&self) -> bool { self.core.suspended } + fn renderer_srgb_blend(&self) -> bool { self.core.renderer.srgb_blend() } + fn rt_srgb_blend(&self) -> bool { self.rt.core().srgb_blend() } + fn reblend(&mut self) -> bool { self.core.reblend(self.rt.core_mut()) } + fn acquire(&mut self) -> Acquire<wgpu::SurfaceTexture> { self.core.acquire() } + fn prepare(&mut self, drawable: wgpu::SurfaceTexture) -> PreparedEmbedFrame { + self.core.prepare_draw(self.rt.core_mut(), drawable) + } + fn compositor_animating(&self) -> bool { self.compositor.as_ref().is_some_and(|c| c.animating()) } + + fn render(&mut self, prepared: &mut PreparedEmbedFrame, dt: f64, update_ms: f64) -> bool { + if let Some(comp) = &mut self.compositor { + let mut f = Frame { + device: &self.core.gpu.device, + queue: &self.core.gpu.queue, + encoder: &mut prepared.encoder, + target: &prepared.target, + format: prepared.format, + size: prepared.size, + dt, + update_ms, + rt: &mut self.rt, + ui: &mut self.core.renderer, + }; + comp.render(&mut f); + comp.animating() + } else { + self.core.draw_default(self.rt.core_mut(), prepared); + false + } + } + + fn submit_and_present(&mut self, prepared: PreparedEmbedFrame) -> Instant { + self.core.submit_and_present(prepared) + } + + fn clock_and_rt_mut(&mut self) -> (&mut FrameClock, &mut RuntimeCore) { + (&mut self.core.clock, self.rt.core_mut()) + } + + fn with_driver<R>(&mut self, f: impl FnOnce(&mut FrameClock, &mut RuntimeCore, &mut dyn AppDriver) -> R) -> R { + let (rt, mut app) = self.rt.split_mut(); + f(&mut self.core.clock, rt, &mut app) + } +} + +#[cfg(all(test, target_os = "macos"))] +mod tests { + use std::sync::atomic::{AtomicU32, Ordering}; + use std::sync::Arc; + + use objc2::{ + msg_send, + rc::Retained, + runtime::{AnyClass, AnyObject}, + }; + + use super::LayerHost; + use crate::compose::{Compositor, Frame}; + use crate::render::KIND_EFFECT; + use crate::tooling::AppSpec; + use crate::{Cx, El, col, effect}; + + struct MarkProbe(Arc<AtomicU32>); + + impl Compositor<()> for MarkProbe { + fn render(&mut self, f: &mut Frame<'_, ()>) { + for (idx, inst) in f.rt.instances.iter().enumerate() { + if inst.params[1] == KIND_EFFECT { + self.0.store(f.rt.marks.get(idx).copied().unwrap_or(0), Ordering::Relaxed); + } + } + f.draw_ui(); + } + } + + #[test] + fn layer_host_runs_compositor_with_tracked_marks() { + // SAFETY: `CAMetalLayer` is a QuartzCore class whose `+new` returns a retained instance. + let layer: Retained<AnyObject> = unsafe { msg_send![AnyClass::get(c"CAMetalLayer").expect("QuartzCore"), new] }; + let seen = Arc::new(AtomicU32::new(0)); + let view = |_: &(), _: &mut Cx<()>| -> El { col().size(120.0, 80.0).child(effect(42).size(60.0, 20.0)) }; + let spec = AppSpec::new("embed-test", (120.0, 80.0), || (), view); + // SAFETY: `layer` is a valid retained `CAMetalLayer` owned by this test and outlives `host` (dropped before `layer`). + let host = unsafe { + LayerHost::from_core_animation_layer( + Retained::as_ptr(&layer) as *mut std::ffi::c_void, + &spec, + (), + (120.0, 80.0), + 2.0, + true, + Arc::new(|| {}), + ) + }; + let Ok(mut host) = host else { return }; + host = host.with_compositor(MarkProbe(seen.clone())); + let out = host.frame(); + assert!(out.drew); + assert_eq!(seen.load(Ordering::Relaxed), 42); + } +} diff --git a/app/vendor/rune/crates/rune/src/platform/embed_frame.rs b/app/vendor/rune/crates/rune/src/platform/embed_frame.rs new file mode 100644 index 0000000..130e0e4 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/platform/embed_frame.rs @@ -0,0 +1,266 @@ +//! Non-Metal per-frame pipeline logic shared by [`super::embed::LayerHost`], compiled on all +//! test targets so the frame-step ordering, clock hand-off and request draining are verified +//! off-Apple too. + +use crate::frame::clock::FrameClock; +use crate::frame::host_step::{ + self, Acquire, FrameHost, Gate, PostStepCheck, ReacquireReason, RenderPrep, StepInfo, +}; +use crate::runtime::{AppDriver, RuntimeCore}; +use crate::time::Instant; +use crate::window::Missed; + +/// Summary produced after presenting (or missing) one embedded layer frame. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub(crate) struct FrameSummary { + pub(crate) drew: bool, + pub(crate) animating: bool, + pub(crate) wake_after_secs: Option<f64>, + pub(crate) cpu_us: u64, +} + +/// Surface and draw callbacks supplied by [`super::embed::LayerHost`] (or a fake surface in +/// off-Apple unit tests) to [`run_embed_frame`]. +pub(crate) trait EmbedSurface { + type Drawable; + type Prepared; + + fn suspended(&self) -> bool; + fn renderer_srgb_blend(&self) -> bool; + fn rt_srgb_blend(&self) -> bool; + fn reblend(&mut self) -> bool; + fn acquire(&mut self) -> Acquire<Self::Drawable>; + fn prepare(&mut self, drawable: Self::Drawable) -> Self::Prepared; + fn compositor_animating(&self) -> bool; + fn render(&mut self, prepared: &mut Self::Prepared, dt: f64, update_ms: f64) -> bool; + fn submit_and_present(&mut self, prepared: Self::Prepared) -> Instant; + fn clock_and_rt_mut(&mut self) -> (&mut FrameClock, &mut RuntimeCore); + fn with_driver<R>(&mut self, f: impl FnOnce(&mut FrameClock, &mut RuntimeCore, &mut dyn AppDriver) -> R) -> R; +} + +struct EmbedFrameHost<'a, E: EmbedSurface> { + surface: &'a mut E, + t0: Option<Instant>, + summary: FrameSummary, +} + +impl<E: EmbedSurface> FrameHost for EmbedFrameHost<'_, E> { + type Drawable = E::Drawable; + type Prepared = E::Prepared; + + #[inline] + fn gate(&mut self) -> Gate { + if self.surface.suspended() { + return Gate::Skip; + } + let (_, rt) = self.surface.clock_and_rt_mut(); + let _ = rt.follow_font_families(); + Gate::Draw + } + + #[inline] + fn needs_reblend(&self) -> bool { + self.surface.renderer_srgb_blend() != self.surface.rt_srgb_blend() + } + + #[inline] + fn reblend(&mut self) -> bool { + self.surface.reblend() + } + + #[inline] + fn acquire(&mut self) -> Acquire<Self::Drawable> { + self.surface.acquire() + } + + #[inline] + fn step_runtime(&mut self) -> StepInfo { + let t0 = crate::time::now(); + self.t0 = Some(t0); + let compositing = self.surface.compositor_animating(); + let (animating, dt, update_ms) = self.surface.with_driver(|clock, rt, app| { + step_and_flush(clock, rt, app, t0, compositing) + }); + StepInfo { + runtime_animating: animating, + animating, + dt, + update_ms, + presents_at: None, + } + } + + #[inline] + fn post_step_check(&mut self, _info: &mut StepInfo) -> PostStepCheck { + if self.needs_reblend() { + PostStepCheck::Reacquire(ReacquireReason::Reblend) + } else { + PostStepCheck::Keep + } + } + + #[inline] + fn prepare_reacquire(&mut self, reason: ReacquireReason, _info: &mut StepInfo) -> bool { + match reason { + ReacquireReason::Reblend => self.surface.reblend(), + #[cfg(any(test, target_os = "macos"))] + ReacquireReason::NativeMaterials => true, + } + } + + #[inline] + fn on_missed(&mut self, missed: Missed, stepped: bool) { + let t0 = self.t0.unwrap_or_else(crate::time::now); + let retry_now = missed == Missed::Outdated; + let comp_animating = self.surface.compositor_animating(); + self.summary = if stepped { + let (_, rt) = self.surface.clock_and_rt_mut(); + missed_after_step(rt, t0, comp_animating, retry_now) + } else { + self.surface.with_driver(|_, rt, app| missed_step(rt, app, t0, comp_animating, retry_now)) + }; + } + + #[inline] + fn prepare_render(&mut self, drawable: Self::Drawable, _info: &mut StepInfo) -> RenderPrep<Self::Prepared> { + RenderPrep::Ready(self.surface.prepare(drawable)) + } + + #[inline] + fn render(&mut self, prepared: &mut Self::Prepared, info: &StepInfo) -> bool { + self.surface.render(prepared, info.dt, info.update_ms) + } + + #[inline] + fn submit_and_present(&mut self, prepared: Self::Prepared, _info: &StepInfo) -> Instant { + self.surface.submit_and_present(prepared) + } + + #[inline] + fn present_targets(&mut self) -> (Option<&mut FrameClock>, &mut RuntimeCore) { + let (clock, rt) = self.surface.clock_and_rt_mut(); + (Some(clock), rt) + } + + #[inline] + fn settle(&mut self, submitted: Instant, info: &StepInfo) { + let t0 = self.t0.unwrap_or(submitted); + let (_, rt) = self.surface.clock_and_rt_mut(); + self.summary = frame_summary_presented(rt, submitted, t0, info.animating); + } +} + +/// Runs one embedded layer frame through the shared [`crate::frame::host_step::run`] sequencer. +#[inline] +pub(crate) fn run_embed_frame<E: EmbedSurface>(surface: &mut E) -> FrameSummary { + let mut host = EmbedFrameHost { + surface, + t0: None, + summary: FrameSummary::default(), + }; + host_step::run(&mut host); + host.summary +} + +/// Drains and discards host requests an embedded layer cannot serve (window close/minimize/frame, +/// native pop-ups, native file dialogs) and flushes in-memory clipboard writes. +pub(crate) fn flush_requests(rt: &mut RuntimeCore, app: &mut dyn AppDriver) { + crate::clipboard::flush_memory(rt); + if rt.popup_menu().is_some() { + rt.cancel_popups(app); + } + rt.refuse_file_dialog("native file dialogs are unsupported in embedded views"); + rt.shell_request = None; + rt.ignore_minimize("an embedded layer"); + rt.host.window_frame = None; +} + +/// Advances the runtime on `clock` for a frame whose drawable has already been acquired, passing +/// `compositing` so a compositor-driven animation keeps real frame gaps instead of clamping to +/// `RESUME_STEP`. +pub(crate) fn step_and_flush( + clock: &mut FrameClock, + rt: &mut RuntimeCore, + app: &mut dyn AppDriver, + t0: Instant, + compositing: bool, +) -> (bool, f64, f64) { + let (animating, dt) = clock.advance_core(rt, app, t0, compositing); + let update_ms = t0.elapsed().as_secs_f64() * 1000.0; + flush_requests(rt, app); + (animating, dt, update_ms) +} + +/// Runs due timers, `poll` and queued input when drawable acquisition failed before stepping, +/// without advancing `FrameClock` (matching `window/host/draw.rs::missed_frame`). +pub(crate) fn missed_step( + rt: &mut RuntimeCore, + app: &mut dyn AppDriver, + t0: Instant, + comp_animating: bool, + retry_now: bool, +) -> FrameSummary { + rt.covered_wake(app); + flush_requests(rt, app); + missed_after_step(rt, t0, comp_animating, retry_now) +} + +/// Computes the missed-frame summary when the runtime has already stepped (e.g. a post-step +/// blend-mode switch refused reconfiguration or re-acquisition failed). +pub(crate) fn missed_after_step( + rt: &RuntimeCore, + t0: Instant, + comp_animating: bool, + retry_now: bool, +) -> FrameSummary { + FrameSummary { + drew: false, + animating: retry_now || comp_animating || rt.animating || rt.stale() || rt.has_pending_input() || rt.live_pending(), + wake_after_secs: wake_after_secs(rt), + cpu_us: t0.elapsed().as_micros() as u64, + } +} + +/// Computes the presented-frame summary after [`host_step::run`] has recorded presentation on +/// `clock` and interaction timing. +fn frame_summary_presented( + rt: &RuntimeCore, + submitted: Instant, + t0: Instant, + animating: bool, +) -> FrameSummary { + let cpu_us = submitted.saturating_duration_since(t0).as_micros() as u64; + let keep_ticking = animating || rt.stale() || rt.has_pending_input() || rt.live_pending(); + FrameSummary { + drew: true, + animating: keep_ticking, + wake_after_secs: wake_after_secs(rt), + cpu_us, + } +} + +/// Records presentation on `clock` and interaction timing, then computes the frame outcome. +#[cfg(test)] +pub(crate) fn post_present( + clock: &mut FrameClock, + rt: &mut RuntimeCore, + submitted: Instant, + t0: Instant, + animating: bool, + comp_animating: bool, +) -> FrameSummary { + clock.presented_core(rt, submitted); + rt.interaction_presented(submitted, None); + frame_summary_presented(rt, submitted, t0, animating || comp_animating) +} + +pub(crate) fn wake_after_secs(rt: &RuntimeCore) -> Option<f64> { + rt.wake_deadline().and_then(|d| { + let elapsed = rt.wall_start?.elapsed().as_secs_f64(); + Some((d - elapsed).max(0.0)) + }) +} + +#[cfg(test)] +#[path = "embed_frame_tests.rs"] +mod tests; diff --git a/app/vendor/rune/crates/rune/src/platform/embed_frame_tests.rs b/app/vendor/rune/crates/rune/src/platform/embed_frame_tests.rs new file mode 100644 index 0000000..5b5aac2 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/platform/embed_frame_tests.rs @@ -0,0 +1,266 @@ +use std::time::Duration; + +use super::*; +use crate::frame::clock::{FrameClock, RESUME_STEP}; +use crate::{Cx, El, Env, Runtime, el}; + +const FRAME_60HZ: Duration = Duration::from_micros(16_667); + +#[test] +fn compositor_animating_keeps_real_frame_gap_instead_of_clamping_to_resume_step() { + fn view(_: &(), _: &mut Cx<()>) -> El { el().size(40.0, 20.0) } + let start = crate::time::now(); + let mut clock = FrameClock::new(start); + let mut rt = Runtime::new((), view, (40.0, 20.0), Env::default()); + rt.wall_start = Some(start); + + // First frame settles runtime (not animating). + { + let (core, mut app) = rt.split_mut(); + step_and_flush(&mut clock, core, &mut app, start, false); + } + assert!(!rt.animating); + + // Second frame 16.67 ms later while only a compositor animates must step the real 16.67 ms + // gap, not clamp to RESUME_STEP (8.33 ms). + let (_, dt, _) = { + let (core, mut app) = rt.split_mut(); + step_and_flush(&mut clock, core, &mut app, start + FRAME_60HZ, true) + }; + assert!( + (dt - FRAME_60HZ.as_secs_f64()).abs() < 1e-5, + "compositor animation must keep real 60 Hz dt (~16.67 ms), got {dt} (RESUME_STEP={RESUME_STEP})" + ); +} + +#[test] +fn post_present_delays_overrunning_new_motion_and_reports_stale_and_requests_dropped() { + #[derive(Default)] + struct S { width: f32 } + fn view(s: &S, _: &mut Cx<S>) -> El { + el().child(el().key("box").size(s.width, 8.0)) + } + let start = crate::time::now(); + let overrun = Duration::from_millis(50); + + let run = |with_present: bool| { + let mut clock = FrameClock::new(start); + let mut rt = Runtime::new(S { width: 12.0 }, view, (300.0, 40.0), Env::default()); + rt.set_system_reduced_motion(false); + rt.wall_start = Some(start); + { + let (core, mut app) = rt.split_mut(); + let (anim, _, _) = step_and_flush(&mut clock, core, &mut app, start, false); + if with_present { post_present(&mut clock, core, start, start, anim, false); } + } + // Start a spring on frame 1, which overruns by 50 ms before presenting. + rt.update(|s, tx| { + s.width = 212.0; + tx.close_window(); + tx.minimize(); + }); + let f1 = start + FRAME_60HZ; + { + let (core, mut app) = rt.split_mut(); + let (anim, _, _) = step_and_flush(&mut clock, core, &mut app, f1, false); + assert!(core.shell_request.is_none(), "unsupported shell request must be cleared"); + assert!(!core.host.minimize.field(), "unsupported minimize request must be cleared"); + if with_present { post_present(&mut clock, core, f1 + overrun, f1, anim, false); } + } + // Next frame arrives 1 frame after presentation finished. + let f2 = f1 + overrun + FRAME_60HZ; + { + let (core, mut app) = rt.split_mut(); + let (anim, _, _) = step_and_flush(&mut clock, core, &mut app, f2, false); + if with_present { post_present(&mut clock, core, f2, f2, anim, false); } + } + rt.presented("box").unwrap().0[2] + }; + + let delayed = run(true); + let undelayed = run(false); + assert!( + undelayed - delayed > 5.0, + "post_present must delay newly started motion by the frame overrun: delayed={delayed}, undelayed={undelayed}" + ); +} + +#[test] +fn missed_step_runs_poll_without_advancing_frame_clock() { + #[derive(Default)] + struct S { polls: u32 } + fn view(_: &S, _: &mut Cx<S>) -> El { el() } + let start = crate::time::now(); + let mut clock = FrameClock::new(start); + let mut rt = Runtime::new(S::default(), view, (40.0, 20.0), Env::default()); + rt.poll = Some(|s, _, _| { s.polls += 1; false }); + rt.wall_start = Some(start); + + let summary = { + let (core, mut app) = rt.split_mut(); + missed_step(core, &mut app, start + FRAME_60HZ, false, true) + }; + assert!(!summary.drew); + assert!(summary.animating, "outdated/lost retry asks display link to keep ticking"); + assert_eq!(rt.state.polls, 1, "missed drawable still runs poll/timers"); + assert_eq!(clock.last(), start, "missed drawable must not advance FrameClock"); + + // Invalidation marks summary.animating true via rt.stale(). + rt.invalidate(); + let stale_summary = post_present(&mut clock, rt.core_mut(), start, start, false, false); + assert!(stale_summary.drew && stale_summary.animating, "stale runtime must request another frame"); +} + +#[derive(Default)] +struct EmbedTestState { + polls: u32, + switch_blend: bool, + invalidate_on_poll: bool, +} + +struct MockEmbedSurface { + rt: Runtime<EmbedTestState>, + clock: FrameClock, + suspended: bool, + renderer_srgb: bool, + reblend_succeeds: bool, + acquires: std::collections::VecDeque<Acquire<u32>>, + comp_animating: bool, + log: Vec<String>, +} + +impl MockEmbedSurface { + fn new(start: Instant) -> Self { + fn view(_: &EmbedTestState, _: &mut Cx<EmbedTestState>) -> El { el().size(40.0, 20.0) } + fn poll(s: &mut EmbedTestState, _: f64, tx: &mut crate::Tx) -> bool { + s.polls += 1; + if std::mem::take(&mut s.switch_blend) { + tx.set_srgb_blend(false); + } + std::mem::take(&mut s.invalidate_on_poll) + } + let mut rt = Runtime::new(EmbedTestState::default(), view, (40.0, 20.0), Env::default()); + rt.poll = Some(poll); + rt.wall_start = Some(start); + rt.set_srgb_blend(true); + Self { + rt, + clock: FrameClock::new(start), + suspended: false, + renderer_srgb: true, + reblend_succeeds: true, + acquires: std::collections::VecDeque::from([Acquire::Ready(1)]), + comp_animating: false, + log: Vec::new(), + } + } +} + +impl EmbedSurface for MockEmbedSurface { + type Drawable = u32; + type Prepared = u32; + + fn suspended(&self) -> bool { self.suspended } + fn renderer_srgb_blend(&self) -> bool { self.renderer_srgb } + fn rt_srgb_blend(&self) -> bool { self.rt.core().srgb_blend() } + + fn reblend(&mut self) -> bool { + self.log.push(format!("reblend:{}", self.reblend_succeeds)); + if self.reblend_succeeds { + self.renderer_srgb = self.rt.core().srgb_blend(); + true + } else { + false + } + } + + fn acquire(&mut self) -> Acquire<u32> { + let got = self.acquires.pop_front().unwrap_or(Acquire::Ready(99)); + self.log.push(match &got { + Acquire::Ready(id) => format!("acquire:ok:{id}"), + Acquire::Missed(m) => format!("acquire:missed:{m:?}"), + }); + got + } + + fn prepare(&mut self, drawable: u32) -> u32 { + self.log.push(format!("prepare:{drawable}")); + drawable + } + + fn compositor_animating(&self) -> bool { self.comp_animating } + + fn render(&mut self, prepared: &mut u32, _dt: f64, _update_ms: f64) -> bool { + self.log.push(format!("render:{prepared}")); + self.comp_animating + } + + fn submit_and_present(&mut self, prepared: u32) -> Instant { + self.log.push(format!("present:{prepared}")); + crate::time::now() + } + + fn clock_and_rt_mut(&mut self) -> (&mut FrameClock, &mut RuntimeCore) { + (&mut self.clock, self.rt.core_mut()) + } + + fn with_driver<R>(&mut self, f: impl FnOnce(&mut FrameClock, &mut RuntimeCore, &mut dyn AppDriver) -> R) -> R { + self.log.push("step".into()); + let (rt, mut app) = self.rt.split_mut(); + f(&mut self.clock, rt, &mut app) + } +} + +#[test] +fn run_embed_frame_follows_shared_acquire_step_reblend_present_order() { + let start = crate::time::now(); + let mut surface = MockEmbedSurface::new(start); + surface.rt.state.switch_blend = true; + surface.acquires = std::collections::VecDeque::from([Acquire::Ready(1), Acquire::Ready(2)]); + let out = run_embed_frame(&mut surface); + assert!(out.drew); + assert_eq!( + surface.log, + ["acquire:ok:1", "step", "reblend:true", "acquire:ok:2", "prepare:2", "render:2", "present:2"] + ); +} + +#[test] +fn run_embed_frame_suspended_touches_nothing() { + let start = crate::time::now(); + let mut surface = MockEmbedSurface::new(start); + surface.suspended = true; + let out = run_embed_frame(&mut surface); + assert_eq!(out, FrameSummary::default()); + assert!(surface.log.is_empty()); +} + +#[test] +fn run_embed_frame_post_step_reblend_miss_preserves_stale_and_live_pending_without_double_step() { + let start = crate::time::now(); + let mut surface = MockEmbedSurface::new(start); + surface.rt.state.switch_blend = true; + surface.reblend_succeeds = false; + surface.acquires = std::collections::VecDeque::from([Acquire::Ready(1)]); + // Run a frame where reblend fails after step while a pending input arrives before miss. + let out = run_embed_frame(&mut surface); + assert!(!out.drew); + assert_eq!(surface.rt.state.polls, 1, "post-step reblend failure must not step poll twice"); + + // Verify missed_after_step reports animating when rt.stale() or rt.has_pending_input() is true. + surface.rt.invalidate(); + let stale_miss = missed_after_step(surface.rt.core(), start, false, false); + assert!(!stale_miss.drew && stale_miss.animating, "post-step miss must keep animating when rt.stale()"); + + // Verify re-acquire Outdated after a post-step blend switch requests an immediate retry tick + // without running poll a second time. + let mut surface2 = MockEmbedSurface::new(start); + surface2.rt.state.switch_blend = true; + surface2.reblend_succeeds = true; + surface2.acquires = std::collections::VecDeque::from([Acquire::Ready(1), Acquire::Missed(Missed::Outdated)]); + let out2 = run_embed_frame(&mut surface2); + assert!(!out2.drew); + assert!(out2.animating, "Outdated re-acquire after blend switch keeps ticking"); + assert_eq!(surface2.rt.state.polls, 1, "post-step re-acquire miss must not step poll twice"); +} + diff --git a/app/vendor/rune/crates/rune/src/platform/ime.rs b/app/vendor/rune/crates/rune/src/platform/ime.rs new file mode 100644 index 0000000..045ff80 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/platform/ime.rs @@ -0,0 +1,98 @@ +//! Telling the platform's input method that Rune ended a composition itself (a blur, a click, +//! the window going inactive): the field already wrote what it showed, so the input method +//! drops its own copy rather than carry it into the next field. winit only switches the input +//! method off and on, which leaves the composition in Windows' input context and in AppKit's. +//! And what winit's input method handling leaves out: clauses and reconversion (`windows`, +//! `macos`). + +#[cfg(target_os = "windows")] +mod windows; +#[cfg(target_os = "windows")] +pub(crate) use windows::{sync, take_clauses, take_select}; +#[cfg(target_os = "macos")] +pub(crate) use macos::{sync, take_clauses, take_select}; + +/// macOS: through the vendored winit's `NSTextInputClient` (`platform::macos::set_ime_text` +/// and the rest), which reads `setMarkedText:`'s clause attributes and answers `selectedRange` +/// and `attributedSubstringForProposedRange:` from the text published here. +#[cfg(target_os = "macos")] +mod macos { + use std::cell::Cell; + use std::ops::Range; + + use crate::edit::{Clause, ImeText}; + + thread_local! { + /// Where the published text starts in its field, in bytes. + static START: Cell<usize> = const { Cell::new(0) }; + } + + pub(crate) fn sync(_window: &winit::window::Window, text: Option<ImeText>) { + START.set(text.as_ref().map_or(0, |t| t.start)); + winit::platform::macos::set_ime_text(text.map(|t| (t.text.clone(), t.selection.clone()))); + } + + pub(crate) fn take_clauses(_window: &winit::window::Window, preedit: &str) -> Vec<Clause> { + winit::platform::macos::take_ime_clauses(preedit).into_iter().map(|(range, target)| { + let clause = Clause::new(range); + if target { clause.target() } else { clause } + }).collect() + } + + pub(crate) fn take_select(_window: &winit::window::Window) -> Option<Range<usize>> { + let start = START.get(); + winit::platform::macos::take_ime_replacement().map(|r| start + r.start..start + r.end) + } +} + +/// Publishes the focused field's text for the input method (reconversion). On Wayland and X11 +/// winit gives the input method no text to read (text-input-v3's surrounding text, XIM's +/// string conversion), and the web's field holds its own. +#[cfg(not(any(target_os = "windows", target_os = "macos")))] +pub(crate) fn sync(_window: &winit::window::Window, _text: Option<crate::edit::ImeText>) {} + +/// The clauses the platform gave composition `preedit`: none where winit doesn't pass them. +#[cfg(not(any(target_os = "windows", target_os = "macos")))] +pub(crate) fn take_clauses(_window: &winit::window::Window, _preedit: &str) -> Vec<crate::edit::Clause> { Vec::new() } + +/// A reconversion's range of the field's text. +#[cfg(not(any(target_os = "windows", target_os = "macos")))] +pub(crate) fn take_select(_window: &winit::window::Window) -> Option<std::ops::Range<usize>> { None } + +/// Drops the window's open composition, if any. +#[cfg(target_os = "windows")] +#[allow(unsafe_code)] +pub(crate) fn cancel(window: &winit::window::Window) { + use windows_sys::Win32::UI::Input::Ime::{CPS_CANCEL, ImmGetContext, ImmNotifyIME, ImmReleaseContext, NI_COMPOSITIONSTR}; + let Some(hwnd) = super::win32::hwnd(window) else { return }; + // SAFETY: `hwnd` is this thread's live window; a context it hands out is released here. + unsafe { + let himc = ImmGetContext(hwnd); + if himc.is_null() { return; } + ImmNotifyIME(himc, NI_COMPOSITIONSTR, CPS_CANCEL, 0); + ImmReleaseContext(hwnd, himc); + } +} + +/// Drops the window's open composition, if any. +#[cfg(target_os = "macos")] +#[allow(unsafe_code)] +pub(crate) fn cancel(window: &winit::window::Window) { + use winit::raw_window_handle::{HasWindowHandle, RawWindowHandle}; + let Ok(handle) = window.window_handle() else { return }; + let RawWindowHandle::AppKit(h) = handle.as_raw() else { return }; + // SAFETY: `ns_view` is the window's live content view on the main thread; `inputContext` + // returns it or nil, and `discardMarkedText` takes no arguments. + unsafe { + let view = h.ns_view.as_ptr().cast::<objc2::runtime::AnyObject>(); + let context: *mut objc2::runtime::AnyObject = objc2::msg_send![view, inputContext]; + if !context.is_null() { + let () = objc2::msg_send![context, discardMarkedText]; + } + } +} + +/// Wayland's and X11's input methods end the composition when winit turns them off, as the +/// web's text field does when it blurs. +#[cfg(not(any(target_os = "windows", target_os = "macos")))] +pub(crate) fn cancel(_window: &winit::window::Window) {} diff --git a/app/vendor/rune/crates/rune/src/platform/ime/windows.rs b/app/vendor/rune/crates/rune/src/platform/ime/windows.rs new file mode 100644 index 0000000..1e6c390 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/platform/ime/windows.rs @@ -0,0 +1,188 @@ +//! Windows: what winit's IMM32 handling leaves out, from a subclass of the window's procedure. +//! - **Clauses:** a composition's clause boundaries (`GCS_COMPCLAUSE`) and which clause is being +//! converted (`GCS_COMPATTR`), read as each `WM_IME_COMPOSITION` arrives, before winit turns +//! it into a preedit with only the target range. +//! - **Reconversion and document feed:** `WM_IME_REQUEST`'s `IMR_RECONVERTSTRING` and +//! `IMR_DOCUMENTFEED` answered with the focused field's paragraph (the runtime publishes it +//! each frame), and `IMR_CONFIRMRECONVERTSTRING`'s range kept for the runtime to select, so the +//! composition the input method starts replaces it. +//! +//! The input method sends these synchronously from inside the message loop; the runtime isn't +//! reachable there, so each answer comes from what it published, and each finding waits for it +//! in a cell, taken in order before the preedit it belongs to. + +#![allow(unsafe_code)] + +use std::cell::RefCell; +use std::collections::HashMap; +use std::ops::Range; + +use windows_sys::Win32::Foundation::{HWND, LPARAM, LRESULT, WPARAM}; +use windows_sys::Win32::UI::Input::Ime::{ + ATTR_TARGET_CONVERTED, ATTR_TARGET_NOTCONVERTED, GCS_COMPATTR, GCS_COMPCLAUSE, GCS_COMPSTR, IMR_CONFIRMRECONVERTSTRING, + IMR_DOCUMENTFEED, IMR_RECONVERTSTRING, ImmGetCompositionStringW, ImmGetContext, ImmReleaseContext, RECONVERTSTRING, +}; +use windows_sys::Win32::UI::Shell::{DefSubclassProc, RemoveWindowSubclass, SetWindowSubclass}; +use windows_sys::Win32::UI::WindowsAndMessaging::{WM_IME_COMPOSITION, WM_IME_REQUEST, WM_NCDESTROY}; + +use crate::edit::{Clause, ImeText}; + +const SUBCLASS: usize = 0x5255_4e49; // "RUNI" + +/// One window's published text and the findings waiting for the runtime. +#[derive(Default)] +struct Window { + text: Option<ImeText>, + /// The last composition string read and its clauses. + clauses: Option<(String, Vec<Clause>)>, + /// A reconversion's range of the field's text, in bytes. + select: Option<Range<usize>>, +} + +thread_local! { + static WINDOWS: RefCell<HashMap<usize, Window>> = RefCell::new(HashMap::new()); +} + +fn key(window: &winit::window::Window) -> Option<(HWND, usize)> { + let hwnd = crate::platform::win32::hwnd(window)?; + Some((hwnd, hwnd as usize)) +} + +/// Publishes the focused field's text for the input method, subclassing the window the first +/// time. +pub(crate) fn sync(window: &winit::window::Window, text: Option<ImeText>) { + let Some((hwnd, k)) = key(window) else { return }; + WINDOWS.with_borrow_mut(|all| { + if !all.contains_key(&k) { + // SAFETY: this thread's live window; the subclass removes its entry when the window goes. + if unsafe { SetWindowSubclass(hwnd, Some(procedure), SUBCLASS, 0) } == 0 { return; } + } + all.entry(k).or_default().text = text; + }); +} + +/// The clauses Windows gave composition `preedit`, if it's the one last read. +pub(crate) fn take_clauses(window: &winit::window::Window, preedit: &str) -> Vec<Clause> { + let Some((_, k)) = key(window) else { return Vec::new() }; + WINDOWS.with_borrow_mut(|all| match all.get_mut(&k).and_then(|w| w.clauses.take()) { + Some((text, clauses)) if text == preedit => clauses, + _ => Vec::new(), + }) +} + +/// A reconversion's range of the field's text, once. +pub(crate) fn take_select(window: &winit::window::Window) -> Option<Range<usize>> { + let (_, k) = key(window)?; + WINDOWS.with_borrow_mut(|all| all.get_mut(&k).and_then(|w| w.select.take())) +} + +unsafe extern "system" fn procedure(hwnd: HWND, message: u32, wparam: WPARAM, lparam: LPARAM, _: usize, _: usize) -> LRESULT { + match message { + WM_IME_COMPOSITION if lparam as u32 & GCS_COMPSTR != 0 => { + // SAFETY: this window's own input context, released at once. + let clauses = unsafe { read_clauses(hwnd) }; + WINDOWS.with_borrow_mut(|all| { if let Some(w) = all.get_mut(&(hwnd as usize)) { w.clauses = clauses; } }); + } + WM_IME_REQUEST if matches!(wparam as u32, IMR_RECONVERTSTRING | IMR_DOCUMENTFEED) => { + let feed = wparam as u32 == IMR_DOCUMENTFEED; + let answer = WINDOWS.with_borrow(|all| all.get(&(hwnd as usize)).and_then(|w| w.text.clone())); + if let Some(text) = answer { + // SAFETY: `lparam` is null (asking the size) or the input method's buffer of that size. + return unsafe { reconvert_string(&text, feed, lparam as *mut RECONVERTSTRING) }; + } + } + WM_IME_REQUEST if wparam as u32 == IMR_CONFIRMRECONVERTSTRING && lparam != 0 => { + WINDOWS.with_borrow_mut(|all| { + let Some(w) = all.get_mut(&(hwnd as usize)) else { return }; + let Some(text) = &w.text else { return }; + // SAFETY: the input method's RECONVERTSTRING, as this window wrote it. + let rs = unsafe { &*(lparam as *const RECONVERTSTRING) }; + let units: Vec<u16> = text.text.encode_utf16().collect(); + let from = (rs.dwCompStrOffset / 2) as usize; + let to = from + rs.dwCompStrLen as usize; + if to <= units.len() { + let byte = |u: usize| String::from_utf16_lossy(&units[..u]).len(); + w.select = Some(text.start + byte(from)..text.start + byte(to)); + } + }); + return 1; + } + WM_NCDESTROY => { + WINDOWS.with_borrow_mut(|all| { all.remove(&(hwnd as usize)); }); + // SAFETY: removes this subclass from the window it was installed on. + unsafe { RemoveWindowSubclass(hwnd, Some(procedure), SUBCLASS); } + } + _ => {} + } + // SAFETY: the next procedure in this window's chain. + unsafe { DefSubclassProc(hwnd, message, wparam, lparam) } +} + +/// The composition string's clauses: byte ranges from `GCS_COMPCLAUSE`'s UTF-16 boundaries, +/// the target from `GCS_COMPATTR`. +unsafe fn read_clauses(hwnd: HWND) -> Option<(String, Vec<Clause>)> { + // SAFETY: the caller's window; the context is released before returning. + unsafe { + let himc = ImmGetContext(hwnd); + if himc.is_null() { return None; } + let read = |what: u32| -> Vec<u8> { + let n = ImmGetCompositionStringW(himc, what, std::ptr::null_mut(), 0); + if n <= 0 { return Vec::new(); } + let mut buf = vec![0u8; n as usize]; + let got = ImmGetCompositionStringW(himc, what, buf.as_mut_ptr().cast(), n as u32); + buf.truncate(got.max(0) as usize); + buf + }; + let (comp, clause, attr) = (read(GCS_COMPSTR), read(GCS_COMPCLAUSE), read(GCS_COMPATTR)); + ImmReleaseContext(hwnd, himc); + let units: Vec<u16> = comp.chunks_exact(2).map(|b| u16::from_le_bytes([b[0], b[1]])).collect(); + let text = String::from_utf16(&units).ok()?; + let bounds: Vec<usize> = clause.chunks_exact(4).map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]]) as usize).collect(); + let byte = |u: usize| String::from_utf16_lossy(&units[..u.min(units.len())]).len(); + let clauses = bounds.windows(2).filter(|w| w[0] < w[1] && w[1] <= units.len()).map(|w| { + let c = Clause::new(byte(w[0])..byte(w[1])); + match attr.get(w[0]).map(|&a| a as u32) { + Some(ATTR_TARGET_CONVERTED | ATTR_TARGET_NOTCONVERTED) => c.target(), + _ => c, + } + }).collect(); + Some((text, clauses)) + } +} + +/// Answers `IMR_RECONVERTSTRING` (the selection, else the word at the caret, to convert again) +/// or `IMR_DOCUMENTFEED` (the paragraph around the caret, so conversion reads its context): the +/// size when `rs` is null, else the struct and the paragraph written there. +unsafe fn reconvert_string(text: &ImeText, feed: bool, rs: *mut RECONVERTSTRING) -> LRESULT { + let units: Vec<u16> = text.text.encode_utf16().collect(); + let head = std::mem::size_of::<RECONVERTSTRING>(); + let size = head + (units.len() + 1) * 2; + if rs.is_null() { return size as LRESULT; } + let unit = |byte: usize| text.text[..byte.min(text.text.len())].encode_utf16().count() as u32; + let (a, b) = match (feed, &text.selection) { + (true, s) => (unit(s.end), unit(s.end)), + (false, s) if !s.is_empty() => (unit(s.start), unit(s.end)), + (false, s) => { + let w = text.word_at(s.start); + (unit(w.start), unit(w.end)) + } + }; + // SAFETY: the input method's buffer holds `size` bytes: the struct, then the string. + unsafe { + if ((*rs).dwSize as usize) < size { return 0; } + *rs = RECONVERTSTRING { + dwSize: size as u32, + dwVersion: 0, + dwStrLen: units.len() as u32, + dwStrOffset: head as u32, + dwCompStrLen: b - a, + dwCompStrOffset: a * 2, + dwTargetStrLen: b - a, + dwTargetStrOffset: a * 2, + }; + let out = rs.cast::<u8>().add(head).cast::<u16>(); + std::ptr::copy_nonoverlapping(units.as_ptr(), out, units.len()); + *out.add(units.len()) = 0; + } + size as LRESULT +} diff --git a/app/vendor/rune/crates/rune/src/platform/layer_shell.rs b/app/vendor/rune/crates/rune/src/platform/layer_shell.rs new file mode 100644 index 0000000..bb97c95 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/platform/layer_shell.rs @@ -0,0 +1,593 @@ +//! A Wayland layer-shell surface for overlays: `zwlr_layer_shell_v1` on winit's own display +//! connection, in a private event queue with its own seat. The surface reserves no space; +//! input regions and the rendered buffer share a commit. Global pointer observation and +//! capture exclusion are unavailable. wgpu draws through the raw `wl_surface`. + +use std::os::fd::{AsRawFd, RawFd}; +use std::ptr::NonNull; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::{Arc, Condvar, Mutex}; +use std::time::Duration; + +use winit::raw_window_handle::{RawDisplayHandle, RawWindowHandle, WaylandDisplayHandle, WaylandWindowHandle}; +use wayland_backend::client::Backend; +use wayland_client::globals::{GlobalListContents, registry_queue_init}; +use wayland_client::protocol::wl_compositor::WlCompositor; +use wayland_client::protocol::wl_region::WlRegion; +use wayland_client::protocol::wl_registry::WlRegistry; +use wayland_client::protocol::wl_surface::{self, WlSurface}; +use wayland_client::protocol::{wl_output::{self, WlOutput}, wl_seat::{self, WlSeat}, wl_pointer::{self, WlPointer}, wl_keyboard::{self, WlKeyboard}, wl_touch::{self, WlTouch}}; +use wayland_client::{Connection, Dispatch, EventQueue, Proxy, QueueHandle}; +use wayland_protocols::wp::cursor_shape::v1::client::wp_cursor_shape_device_v1::{Shape, WpCursorShapeDeviceV1}; +use wayland_protocols::wp::cursor_shape::v1::client::wp_cursor_shape_manager_v1::WpCursorShapeManagerV1; +use wayland_protocols_wlr::layer_shell::v1::client::zwlr_layer_shell_v1::{Layer, ZwlrLayerShellV1}; +use wayland_protocols_wlr::layer_shell::v1::client::zwlr_layer_surface_v1::{self, Anchor, KeyboardInteractivity, ZwlrLayerSurfaceV1}; + +use super::layer_shell_machine::{keyboard, readiness, touch}; +use crate::el::Align; +use crate::overlay::{Placement, ScreenEdge}; +use crate::runtime::Waker; +use crate::{OverlayInput, OverlayOptions, OverlayPlacement}; + +pub(crate) enum Input { + Move(f32, f32), Leave, Button(bool), Secondary(bool), Focus(bool), Key(crate::KeyEvent), KeyUp(crate::KeyEvent), + Physical(crate::PhysicalInput, Option<crate::KeyEvent>), +} + +/// Whether the pointer is over the surface: the serial of its enter, which setting a cursor +/// needs, and the cursor the surface set since (none: the one it arrived with). +#[derive(Clone, Copy, Debug, Default, PartialEq)] +enum Over { + #[default] + Outside, + Inside { serial: u32, cursor: Option<crate::el::Cursor> }, +} + +impl Over { + fn inside(self) -> bool { matches!(self, Over::Inside { .. }) } +} + +#[derive(Default)] +struct State { + /// How far the compositor has got with the surface: its first configure is what makes it + /// drawable, and closing it is final. + readiness: readiness::State, + input: Vec<Input>, + surface: Option<WlSurface>, + over: Over, + keyboard_focus: keyboard::FocusState, + want_pointer: bool, + want_keys: bool, + capabilities: Option<wl_seat::Capability>, + pointer: Option<WlPointer>, + /// A finger on the surface acts as the primary button, so a tap is a click. + touch: Option<WlTouch>, + finger: touch::State, + /// `wp_cursor_shape_manager_v1` when the compositor has it, and its device for `pointer`. + shapes: Option<WpCursorShapeManagerV1>, + shape: Option<WpCursorShapeDeviceV1>, + keyboard: Option<WlKeyboard>, + xkb: Option<xkbcommon::xkb::State>, + mod_state: Option<keyboard::ModState>, +} + +impl Dispatch<WlOutput, ()> for State { + fn event(_: &mut Self, _: &WlOutput, _: wl_output::Event, _: &(), _: &Connection, _: &QueueHandle<Self>) {} +} +impl Dispatch<WlSeat, ()> for State { + fn event(state: &mut Self, seat: &WlSeat, event: wl_seat::Event, _: &(), _: &Connection, qh: &QueueHandle<Self>) { + if let wl_seat::Event::Capabilities { capabilities: wayland_client::WEnum::Value(caps) } = event { + state.capabilities = Some(caps); + state.update_seat(seat, qh); + } + } +} +impl State { + fn step_keyboard_focus(&mut self, event: keyboard::FocusEvent) { + for effect in keyboard::step(&mut self.keyboard_focus, event) { + let keyboard::FocusEffect::Focus(focused) = effect; + self.input.push(Input::Focus(focused)); + } + } + + fn update_seat(&mut self, seat: &WlSeat, qh: &QueueHandle<Self>) { + let caps = self.capabilities.unwrap_or_else(wl_seat::Capability::empty); + let pointer = self.want_pointer && caps.contains(wl_seat::Capability::Pointer); + let keyboard = self.want_keys && caps.contains(wl_seat::Capability::Keyboard); + if pointer && self.pointer.is_none() { + let p = seat.get_pointer(qh, ()); + self.shape = self.shapes.as_ref().map(|shapes| shapes.get_pointer(&p, qh, ())); + self.pointer = Some(p); + } + let touch = self.want_pointer && caps.contains(wl_seat::Capability::Touch); + if touch && self.touch.is_none() { self.touch = Some(seat.get_touch(qh, ())); } + if keyboard && self.keyboard.is_none() { self.keyboard = Some(seat.get_keyboard(qh, ())); } + if !pointer && let Some(p) = self.pointer.take() { + if let Some(shape) = self.shape.take() { shape.destroy(); } + if p.version() >= 3 { p.release(); } + self.over = Over::Outside; + } + if !touch && let Some(t) = self.touch.take() { + if t.version() >= 3 { t.release(); } + touch::step(&mut self.finger, touch::Event::Gone); + } + if !keyboard && let Some(k) = self.keyboard.take() { + if k.version() >= 3 { k.release(); } + self.xkb = None; + self.mod_state = None; + self.step_keyboard_focus(keyboard::FocusEvent::KeyboardGone); + } + } +} +impl Dispatch<WlPointer, ()> for State { + fn event(state: &mut Self, _: &WlPointer, event: wl_pointer::Event, _: &(), _: &Connection, _: &QueueHandle<Self>) { + match event { + wl_pointer::Event::Enter { serial, surface, surface_x, surface_y } => { + // Until the surface sets a cursor, the pointer keeps the one it arrived with. + let inside = state.surface.as_ref() == Some(&surface); + state.over = if inside { Over::Inside { serial, cursor: None } } else { Over::Outside }; + if inside { state.input.push(Input::Move(surface_x as f32, surface_y as f32)); } + } + wl_pointer::Event::Motion { surface_x, surface_y, .. } if state.over.inside() => state.input.push(Input::Move(surface_x as f32, surface_y as f32)), + wl_pointer::Event::Leave { surface, .. } if state.surface.as_ref() == Some(&surface) => { + state.over = Over::Outside; + state.input.push(Input::Leave); + } + wl_pointer::Event::Button { button: 0x110, state: wayland_client::WEnum::Value(button), .. } if state.over.inside() => { + let pressed = button == wl_pointer::ButtonState::Pressed; + state.input.push(Input::Button(pressed)); + if pressed && let Some(xkb) = &state.xkb { + state.input.push(Input::Physical(crate::PhysicalInput::Modifiers(key_mods(xkb)), None)); + } + } + // BTN_RIGHT: the secondary gesture, as a window's right button is. + wl_pointer::Event::Button { button: 0x111, state: wayland_client::WEnum::Value(button), .. } if state.over.inside() => { + state.input.push(Input::Secondary(button == wl_pointer::ButtonState::Pressed)); + } + _ => {} + } + } +} +impl Dispatch<WlTouch, ()> for State { + fn event(state: &mut Self, _: &WlTouch, event: wl_touch::Event, _: &(), _: &Connection, _: &QueueHandle<Self>) { + use touch::Event as Touch; + let event = match event { + wl_touch::Event::Down { surface, id, x, y, .. } if state.surface.as_ref() == Some(&surface) => Touch::Down { id, x: x as f32, y: y as f32 }, + wl_touch::Event::Motion { id, x, y, .. } => Touch::Motion { id, x: x as f32, y: y as f32 }, + wl_touch::Event::Up { id, .. } => Touch::Up { id }, + wl_touch::Event::Cancel => Touch::Cancel, + _ => return, + }; + for effect in touch::step(&mut state.finger, event) { + state.input.push(match effect { + touch::Effect::Move(x, y) => Input::Move(x, y), + touch::Effect::Press => Input::Button(true), + touch::Effect::Release => Input::Button(false), + touch::Effect::Leave => Input::Leave, + }); + } + } +} +impl Dispatch<WlKeyboard, ()> for State { + fn event(state: &mut Self, _: &WlKeyboard, event: wl_keyboard::Event, _: &(), _: &Connection, _: &QueueHandle<Self>) { + use xkbcommon::xkb; + match event { + wl_keyboard::Event::Enter { surface, .. } => { + let focus_event = if state.surface.as_ref() == Some(&surface) { + keyboard::FocusEvent::EnterOurs + } else { + keyboard::FocusEvent::EnterOther + }; + state.step_keyboard_focus(focus_event); + } + wl_keyboard::Event::Leave { surface, .. } if state.surface.as_ref() == Some(&surface) => { + state.step_keyboard_focus(keyboard::FocusEvent::LeaveOurs); + } + wl_keyboard::Event::Keymap { format: wayland_client::WEnum::Value(wl_keyboard::KeymapFormat::XkbV1), fd, size } => { + use std::io::Read; + let mut map = String::new(); + if size <= 16 * 1024 * 1024 && std::fs::File::from(fd).take(u64::from(size)).read_to_string(&mut map).is_ok() { + let context = xkb::Context::new(xkb::CONTEXT_NO_FLAGS); + state.xkb = xkb::Keymap::new_from_string(&context, map.trim_end_matches('\0').to_owned(), xkb::KEYMAP_FORMAT_TEXT_V1, xkb::COMPILE_NO_FLAGS).map(|map| { + let mut xkb_state = xkb::State::new(&map); + if let Some(m) = state.mod_state { + xkb_state.update_mask(m.depressed, m.latched, m.locked, 0, 0, m.group); + } + xkb_state + }); + } + } + wl_keyboard::Event::Modifiers { mods_depressed, mods_latched, mods_locked, group, .. } => { + state.mod_state = Some(keyboard::ModState { depressed: mods_depressed, latched: mods_latched, locked: mods_locked, group }); + if let Some(xkb) = &mut state.xkb { + xkb.update_mask(mods_depressed, mods_latched, mods_locked, 0, 0, group); + state.input.push(Input::Physical(crate::PhysicalInput::Modifiers(key_mods(xkb)), None)); + } + } + wl_keyboard::Event::Key { key, state: wayland_client::WEnum::Value(pressed), .. } if state.keyboard_focus.focused() => { + use winit::platform::scancode::PhysicalKeyExtScancode; + if let Some(xkb) = &state.xkb { + let pressed = pressed == wl_keyboard::KeyState::Pressed; + let physical = match crate::PhysicalKeyCode::from_scancode(key) { + winit::keyboard::PhysicalKey::Code(code) => Some(code), + _ => None, + }; + let fallback = key_event(xkb, key, physical); + if let Some(code) = physical { + state.input.push(Input::Physical(crate::PhysicalInput::Key { key: code, mods: key_mods(xkb), pressed, repeat: false }, fallback)); + } else if let Some(key) = fallback { + state.input.push(if pressed { Input::Key(key) } else { Input::KeyUp(key) }); + } + } + } + _ => {} + } + } +} + +fn key_mods(state: &xkbcommon::xkb::State) -> crate::Mods { + use xkbcommon::xkb; + let active = |name: &str| state.mod_name_is_active(name, xkb::STATE_MODS_EFFECTIVE); + crate::input::key_table::mods_from_keys(active(xkb::MOD_NAME_SHIFT), active(xkb::MOD_NAME_CTRL), active(xkb::MOD_NAME_ALT), active(xkb::MOD_NAME_LOGO)) +} + +fn key_event(state: &xkbcommon::xkb::State, key: u32, physical: Option<crate::PhysicalKeyCode>) -> Option<crate::KeyEvent> { + use xkbcommon::xkb; + let code = xkb::Keycode::new(key + 8); + let sym = state.key_get_one_sym(code); + let mods = key_mods(state); + let text = state.key_get_utf8(code); + keyboard::key_event_from(named_keysym(sym.raw()), xkb::keysym_to_utf32(sym), text, mods, physical) +} + +/// The named key an XKB keysym is, or None for one that types (or nothing Rune names). +fn named_keysym(symbol: u32) -> Option<crate::Key> { + Some(match symbol { + 0xff1b => crate::Key::Escape, 0xff0d => crate::Key::Enter, 0xff08 => crate::Key::Backspace, + 0xffff => crate::Key::Delete, 0xff09 | 0xfe20 => crate::Key::Tab, + 0xff50 => crate::Key::Home, 0xff57 => crate::Key::End, 0xff55 => crate::Key::PageUp, 0xff56 => crate::Key::PageDown, + 0xff51 => crate::Key::Left, 0xff52 => crate::Key::Up, 0xff53 => crate::Key::Right, 0xff54 => crate::Key::Down, + 0xffbe..=0xffd5 => crate::Key::Function((symbol - 0xffbe + 1) as u8), + 0xff67 => crate::Key::ContextMenu, + 0xff63 => crate::Key::Insert, 0xff61 | 0xff15 => crate::Key::PrintScreen, + 0xff14 => crate::Key::ScrollLock, 0xff13 | 0xff6b => crate::Key::Pause, + _ => return None, + }) +} + +impl Dispatch<WlRegistry, GlobalListContents> for State { + fn event(_: &mut Self, _: &WlRegistry, _: <WlRegistry as Proxy>::Event, _: &GlobalListContents, _: &Connection, _: &QueueHandle<Self>) {} +} +impl Dispatch<WlCompositor, ()> for State { + fn event(_: &mut Self, _: &WlCompositor, _: <WlCompositor as Proxy>::Event, _: &(), _: &Connection, _: &QueueHandle<Self>) {} +} +impl Dispatch<WlRegion, ()> for State { + fn event(_: &mut Self, _: &WlRegion, _: <WlRegion as Proxy>::Event, _: &(), _: &Connection, _: &QueueHandle<Self>) {} +} +impl Dispatch<ZwlrLayerShellV1, ()> for State { + fn event(_: &mut Self, _: &ZwlrLayerShellV1, _: <ZwlrLayerShellV1 as Proxy>::Event, _: &(), _: &Connection, _: &QueueHandle<Self>) {} +} +impl Dispatch<WpCursorShapeManagerV1, ()> for State { + fn event(_: &mut Self, _: &WpCursorShapeManagerV1, _: <WpCursorShapeManagerV1 as Proxy>::Event, _: &(), _: &Connection, _: &QueueHandle<Self>) {} +} +impl Dispatch<WpCursorShapeDeviceV1, ()> for State { + fn event(_: &mut Self, _: &WpCursorShapeDeviceV1, _: <WpCursorShapeDeviceV1 as Proxy>::Event, _: &(), _: &Connection, _: &QueueHandle<Self>) {} +} + +/// The cursor-shape-v1 shape for `c`, as `os_cursor` maps winit's. An image is the arrow. +fn shape(c: crate::el::Cursor) -> Shape { + use crate::el::Cursor; + match c { + Cursor::Default | Cursor::Hidden | Cursor::Image(_) => Shape::Default, + Cursor::Pointer => Shape::Pointer, + Cursor::Text => Shape::Text, + Cursor::Grab => Shape::Grab, + Cursor::Grabbing => Shape::Grabbing, + Cursor::NotAllowed => Shape::NotAllowed, + Cursor::Move => Shape::Move, + Cursor::ResizeColumn => Shape::ColResize, + Cursor::ResizeRow => Shape::RowResize, + Cursor::Crosshair => Shape::Crosshair, + Cursor::Cell => Shape::Cell, + Cursor::ZoomIn => Shape::ZoomIn, + Cursor::ZoomOut => Shape::ZoomOut, + } +} +impl Dispatch<WlSurface, ()> for State { + fn event(state: &mut Self, _: &WlSurface, event: wl_surface::Event, _: &(), _: &Connection, _: &QueueHandle<Self>) { + if let wl_surface::Event::PreferredBufferScale { factor } = event { + readiness::step(&mut state.readiness, readiness::Event::Scale(factor.max(1))); + } + } +} +impl Dispatch<ZwlrLayerSurfaceV1, ()> for State { + fn event(state: &mut Self, layer: &ZwlrLayerSurfaceV1, event: zwlr_layer_surface_v1::Event, _: &(), _: &Connection, _: &QueueHandle<Self>) { + match event { + zwlr_layer_surface_v1::Event::Configure { serial, width, height } => { + layer.ack_configure(serial); + readiness::step(&mut state.readiness, readiness::Event::Configure { width, height }); + } + zwlr_layer_surface_v1::Event::Closed => readiness::step(&mut state.readiness, readiness::Event::Closed), + _ => {} + } + } +} + +/// Wakes the event loop when the compositor writes to the display. winit turns its loop only +/// for its own queue's events, so input for this surface's queue (a click on an idle overlay) +/// would otherwise wait for an unrelated wake. An XWayland overlay watches its X connection +/// the same way. +pub(crate) struct Watch { + stop: Arc<AtomicBool>, + /// How many times the overlay has dispatched, so the watcher waits for the loop to read + /// what woke it instead of spinning on a socket that stays readable until then. + turns: Arc<(Mutex<u64>, Condvar)>, +} + +impl Watch { + #[allow(unsafe_code)] + pub(crate) fn spawn(fd: RawFd, wake: Waker) -> Watch { + let stop = Arc::new(AtomicBool::new(false)); + let turns = Arc::new((Mutex::new(0u64), Condvar::new())); + let (stopped, seen) = (stop.clone(), turns.clone()); + std::thread::Builder::new().name("rune-layer-watch".into()).spawn(move || { + while !stopped.load(Ordering::Relaxed) { + let mut poll = libc::pollfd { fd, events: libc::POLLIN, revents: 0 }; + // SAFETY: one pollfd for a display socket. winit's outlives the event loop; an + // XWayland surface drops its watch before closing its connection, so at worst a + // reused descriptor wakes the loop once more before this thread stops. + if unsafe { libc::poll(&mut poll, 1, 250) } <= 0 { continue; } + let (count, turned) = &*seen; + let before = *count.lock().unwrap(); + wake(); + turned.wait_timeout_while(count.lock().unwrap(), Duration::from_millis(100), |n| *n == before).ok(); + } + }).ok(); + Watch { stop, turns } + } + + pub(crate) fn turned(&self) { + let (count, turned) = &*self.turns; + *count.lock().unwrap() += 1; + turned.notify_all(); + } +} + +impl Drop for Watch { + /// The thread notices within one poll timeout; joining would stall hiding. + fn drop(&mut self) { self.stop.store(true, Ordering::Relaxed); } +} + +/// What the overlay needs to know after the compositor talked to the surface. +pub(crate) struct Changes { + pub size: Option<(u32, u32)>, + pub input: Vec<Input>, + pub scale: Option<i32>, + pub closed: bool, +} + +pub(crate) struct LayerSurface { + registry: WlRegistry, + seat_global: Option<(u32, u32)>, + regions: std::cell::RefCell<Option<Vec<[i32; 4]>>>, + compositor: WlCompositor, + output: Option<WlOutput>, + seat: Option<WlSeat>, + options: OverlayOptions, + queue: EventQueue<State>, + state: State, + layer: ZwlrLayerSurfaceV1, + surface: WlSurface, + display: NonNull<std::ffi::c_void>, + watch: Option<Watch>, +} + +impl LayerSurface { + /// None when the display isn't Wayland or the compositor lacks layer-shell. + #[allow(unsafe_code)] + pub fn new(display: RawDisplayHandle, namespace: &str, at: Placement, interactive: bool, options: &OverlayOptions, output_id: Option<u32>, wake: Option<Waker>) -> Option<LayerSurface> { + let RawDisplayHandle::Wayland(display) = display else { return None }; + // SAFETY: winit owns this `wl_display` for the life of the event loop, which outlives + // every overlay; a foreign backend never closes it. + let backend = unsafe { Backend::from_foreign_display(display.display.as_ptr().cast()) }; + let conn = Connection::from_backend(backend); + let (globals, queue) = registry_queue_init::<State>(&conn).ok()?; + let qh = queue.handle(); + let compositor: WlCompositor = globals.bind(&qh, 1..=6, ()).ok()?; + let shell: ZwlrLayerShellV1 = globals.bind(&qh, 1..=4, ()).ok()?; + let output = output_id.and_then(|id| { + globals.contents().with_list(|list| list.iter().find(|g| g.name == id && g.interface == "wl_output").map(|g| { + globals.registry().bind::<WlOutput, _, _>(g.name, g.version.min(4), &qh, ()) + })) + }); + let want_pointer = options.input.resolved(interactive) != OverlayInput::None; + let want_keys = options.keys == crate::KeyPolicy::OnDemand; + let registry = globals.registry().clone(); + let seat_global = globals.contents().with_list(|list| list.iter().find(|g| g.interface == "wl_seat").map(|g| (g.name, g.version.min(8)))); + let seat = if want_pointer || want_keys { seat_global.map(|(name, version)| registry.bind::<WlSeat, _, _>(name, version, &qh, ())) } else { None }; + let surface = compositor.create_surface(&qh, ()); + let region = compositor.create_region(&qh, ()); + surface.set_input_region(Some(&region)); + region.destroy(); + // Preserve existing overlay-layer semantics. There is no layer above Overlay; + // relative ordering of peers is compositor policy, unlike AppKit's numeric levels. + let layer = shell.get_layer_surface(&surface, output.as_ref(), Layer::Overlay, namespace.to_owned(), &qh, ()); + layer.set_keyboard_interactivity(KeyboardInteractivity::None); + layer.set_exclusive_zone(0); + let shapes = globals.bind::<WpCursorShapeManagerV1, _, _>(&qh, 1..=1, ()).ok(); + let state = State { surface: Some(surface.clone()), want_pointer, want_keys, shapes, ..State::default() }; + let watch = wake.map(|wake| Watch::spawn(conn.backend().poll_fd().as_raw_fd(), wake)); + let mut this = LayerSurface { registry, seat_global, regions: std::cell::RefCell::new(Some(Vec::new())), compositor, output, seat, options: options.clone(), queue, state, layer, surface, display: display.display, watch }; + this.place(at); + this.surface.commit(); + while !this.state.readiness.configured() { + this.queue.blocking_dispatch(&mut this.state).ok()?; + } + (!this.state.readiness.closed()).then_some(this) + } + + pub fn place(&mut self, at: Placement) { + match self.options.placement { + Some(OverlayPlacement::FullScreen) => { + self.layer.set_size(0, 0); + self.layer.set_anchor(Anchor::Top | Anchor::Bottom | Anchor::Left | Anchor::Right); + self.layer.set_margin(0, 0, 0, 0); + return; + } + Some(OverlayPlacement::Rect { x, y, width, height }) => { + self.layer.set_size(width.ceil().max(1.0) as u32, height.ceil().max(1.0) as u32); + self.layer.set_anchor(Anchor::Top | Anchor::Left); + self.layer.set_margin(y.round() as i32, 0, 0, x.round() as i32); + return; + } + _ => {} + } + let at = match self.options.placement { + Some(OverlayPlacement::Edge { edge, margin, align, inset }) => Placement { size: at.size, edge, margin, align, inset }, + _ => at, + }; + let (margin, inset) = (at.margin.round() as i32, at.inset.round() as i32); + let (vertical, top, bottom) = match at.edge { + ScreenEdge::Top => (Anchor::Top, margin, 0), + ScreenEdge::Bottom => (Anchor::Bottom, 0, margin), + }; + let (horizontal, left, right) = match at.align { + Align::Start => (Anchor::Left, inset, 0), + Align::Center => (Anchor::empty(), 0, 0), + Align::End => (Anchor::Right, 0, inset), + }; + self.layer.set_size(at.size.0.ceil() as u32, at.size.1.ceil() as u32); + self.layer.set_anchor(vertical | horizontal); + self.layer.set_margin(top, right, bottom, left); + } + + pub fn configured_size(&self) -> Option<(u32, u32)> { self.state.readiness.size() } + + /// Sets the surface's pending input region; true when it changed, so it waits for a commit. + pub fn input_regions(&self, regions: &[[f32; 4]], interactive: bool) -> bool { + let next = match self.options.input.resolved(interactive) { + OverlayInput::All => None, + OverlayInput::Regions => Some(regions.iter().filter_map(|r| { + let (x, y) = (r[0].floor() as i32, r[1].floor() as i32); + let (w, h) = (r[2].ceil() as i32 - x, r[3].ceil() as i32 - y); + (w > 0 && h > 0).then_some([x, y, w, h]) + }).collect()), + _ => Some(Vec::new()), + }; + if *self.regions.borrow() == next { return false; } + if let Some(rects) = &next { + let region = self.compositor.create_region(&self.queue.handle(), ()); + for &[x, y, w, h] in rects { region.add(x, y, w, h); } + self.surface.set_input_region(Some(&region)); + region.destroy(); + } else { + self.surface.set_input_region(None); + } + *self.regions.borrow_mut() = next; + // No commit here: a drawn frame's presentation commits input and pixels together, and a + // frame that draws nothing commits it alone (`Overlay::unchanged_frame`). + true + } + + pub fn set_input(&mut self, input: OverlayInput) { + self.options.input = input; + self.state.want_pointer = input != OverlayInput::None; + if self.seat.is_none() && self.state.want_pointer { + self.seat = self.seat_global.map(|(name, version)| self.registry.bind(name, version, &self.queue.handle(), ())); + } + if let Some(seat) = &self.seat { self.state.update_seat(seat, &self.queue.handle()); } + } + + pub fn request_keys(&self) -> bool { + if !keyboard::can_request_keys(self.options.keys, self.layer.version()) { return false; } + self.layer.set_keyboard_interactivity(KeyboardInteractivity::OnDemand); + self.surface.commit(); + self.queue.flush().ok(); + true + } + + pub fn supports_keys(&self) -> bool { + keyboard::supports_keys(self.options.keys, self.layer.version(), self.seat.is_some()) + } + + /// Shows `want` while the pointer is over the surface, once per change. Without + /// cursor-shape-v1 only `Cursor::Hidden` applies; others keep the cursor the pointer + /// arrived with, such as a terminal's I-beam. + pub fn set_cursor(&mut self, want: crate::el::Cursor) { + let (Over::Inside { serial, cursor }, Some(pointer)) = (self.state.over, &self.state.pointer) else { return }; + if cursor == Some(want) { return; } + match (want, &self.state.shape) { + (crate::el::Cursor::Hidden, _) => pointer.set_cursor(serial, None, 0, 0), + (want, Some(device)) => device.set_shape(serial, shape(want)), + (_, None) => return, + } + self.state.over = Over::Inside { serial, cursor: Some(want) }; + self.queue.flush().ok(); + } + + /// Commit role state (placement) without a new buffer; wgpu's present commits buffers. + pub fn commit(&mut self) { + self.surface.commit(); + self.queue.flush().ok(); + } + + pub fn set_buffer_scale(&mut self, scale: i32) { + if self.surface.version() >= 3 { + self.surface.set_buffer_scale(scale); + } + } + + /// Handles what the compositor sent since the last call (winit reads the socket). + pub fn dispatch(&mut self) -> Changes { + self.turn(); + Changes { + size: self.state.readiness.take_size(), + input: std::mem::take(&mut self.state.input), + scale: self.state.readiness.take_scale(), + closed: self.state.readiness.closed(), + } + } + + /// Handles what the compositor sent to a hidden surface and drops its input, keeping size + /// and scale for the next `dispatch`; true once the compositor closed it. libwayland frees + /// an undispatched event without closing its fd, so a queue left alone leaks every + /// `wl_keyboard.keymap` (each virtual keyboard a paste tool makes sends a few). + pub fn drain(&mut self) -> bool { + self.turn(); + self.state.input.clear(); + self.state.readiness.closed() + } + + fn turn(&mut self) { + self.queue.dispatch_pending(&mut self.state).ok(); + self.queue.flush().ok(); + if let Some(watch) = &self.watch { watch.turned(); } + } + + pub fn raw_handles(&self) -> (RawDisplayHandle, RawWindowHandle) { + let surface = NonNull::new(self.surface.id().as_ptr().cast()).expect("live wl_surface"); + ( + RawDisplayHandle::Wayland(WaylandDisplayHandle::new(self.display)), + RawWindowHandle::Wayland(WaylandWindowHandle::new(surface)), + ) + } +} + +impl Drop for LayerSurface { + fn drop(&mut self) { + if let Some(shape) = self.state.shape.take() { shape.destroy(); } + if let Some(shapes) = self.state.shapes.take() { shapes.destroy(); } + if let Some(pointer) = self.state.pointer.take() && pointer.version() >= 3 { pointer.release(); } + if let Some(touch) = self.state.touch.take() && touch.version() >= 3 { touch.release(); } + if let Some(keyboard) = self.state.keyboard.take() && keyboard.version() >= 3 { keyboard.release(); } + if let Some(seat) = self.seat.take() && seat.version() >= 5 { seat.release(); } + if let Some(output) = self.output.take() && output.version() >= 3 { output.release(); } + self.layer.destroy(); + self.surface.destroy(); + self.queue.flush().ok(); + } +} + +#[cfg(test)] +#[path = "layer_shell_tests.rs"] +mod tests; diff --git a/app/vendor/rune/crates/rune/src/platform/layer_shell_machine.rs b/app/vendor/rune/crates/rune/src/platform/layer_shell_machine.rs new file mode 100644 index 0000000..0b751c9 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/platform/layer_shell_machine.rs @@ -0,0 +1,249 @@ +//! The layer surface's own state, kept out of `platform/layer_shell.rs` (which only builds on +//! unix) so its tests run headless on every host: which finger the surface has, and how far the +//! compositor has got with saying how big it is. + +/// One touch on the surface. It takes one finger at a time: a second finger's events are ignored +/// until the first lifts, so a tap is exactly one press and one release. +pub(crate) mod touch { + use crate::machine::Effects; + + #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] + pub(crate) enum State { + /// No finger down. + #[default] + Up, + /// `id`'s finger is down. + Down { id: i32 }, + } + + /// What the compositor said about a touch. + #[derive(Clone, Copy, Debug, PartialEq)] + pub(crate) enum Event { + Down { id: i32, x: f32, y: f32 }, + Motion { id: i32, x: f32, y: f32 }, + Up { id: i32 }, + /// The compositor took the touch for a system gesture of its own. + Cancel, + /// The seat went away: nothing more arrives for this finger. + Gone, + } + + /// What a touch means for the surface's input, in the order it means it. + #[derive(Clone, Copy, Debug, PartialEq)] + pub(crate) enum Effect { + Move(f32, f32), + Press, + Release, + Leave, + } + + /// The finger after `event`, and the input the caller queues. + pub(crate) fn step(state: &mut State, event: Event) -> Effects<Effect> { + match (*state, event) { + (State::Up, Event::Down { id, x, y }) => { + *state = State::Down { id }; + Effects::two(Effect::Move(x, y), Effect::Press) + } + (State::Down { id }, Event::Motion { id: moving, x, y }) if id == moving => Effects::one(Effect::Move(x, y)), + (State::Down { id }, Event::Up { id: lifted }) if id == lifted => { + *state = State::Up; + Effects::two(Effect::Release, Effect::Leave) + } + // Leave before releasing, so the gesture isn't a click where the finger landed. + (State::Down { .. }, Event::Cancel) => { + *state = State::Up; + Effects::two(Effect::Leave, Effect::Release) + } + (_, Event::Gone) => { + *state = State::Up; + Effects::none() + } + _ => Effects::none(), + } + } +} + +/// How far the compositor has got with the surface. Nothing can be drawn before its first +/// configure; the size it asks for and the buffer scale it prefers are each read once, by +/// `dispatch`, in whatever order they arrive; and once it closes the surface it is final. +pub(crate) mod readiness { + /// What the compositor said about the surface. + #[derive(Clone, Copy, Debug, PartialEq, Eq)] + pub(crate) enum Event { + /// The compositor's size for the surface; 0 on a side means the size asked for. + Configure { width: u32, height: u32 }, + /// The buffer scale it prefers. + Scale(i32), + /// It destroyed the surface. + Closed, + } + + #[derive(Clone, Copy, Debug, PartialEq, Eq)] + pub(crate) enum State { + /// No configure yet, so there is no size to draw at. A preferred buffer scale may have + /// arrived first; it is kept for the first read. + Configuring { scale: Option<i32> }, + /// Configured. `size` and `scale` are what the compositor said that `dispatch` hasn't + /// read yet. + Ready { size: Option<(u32, u32)>, scale: Option<i32> }, + /// Destroyed by the compositor: it says nothing more that counts. + Closed, + } + + impl Default for State { + fn default() -> Self { State::Configuring { scale: None } } + } + + /// The surface after `event`. No effect: what it said is read with the accessors below. + pub(crate) fn step(state: &mut State, event: Event) { + match (&*state, event) { + (State::Closed, _) => {} + (_, Event::Closed) => *state = State::Closed, + (State::Configuring { scale }, Event::Configure { width, height }) => *state = State::Ready { size: Some((width, height)), scale: *scale }, + (State::Ready { scale, .. }, Event::Configure { width, height }) => *state = State::Ready { size: Some((width, height)), scale: *scale }, + (State::Configuring { .. }, Event::Scale(scale)) => *state = State::Configuring { scale: Some(scale) }, + (State::Ready { size, .. }, Event::Scale(scale)) => *state = State::Ready { size: *size, scale: Some(scale) }, + } + } + + impl State { + /// The compositor configured a size, so the surface can be drawn on. + pub(crate) fn configured(&self) -> bool { !matches!(self, State::Configuring { .. }) } + + /// The compositor destroyed the surface. + pub(crate) fn closed(&self) -> bool { matches!(self, State::Closed) } + + /// The size the compositor asked for that `dispatch` hasn't read yet. + pub(crate) fn size(&self) -> Option<(u32, u32)> { + match self { + State::Ready { size, .. } => *size, + State::Configuring { .. } | State::Closed => None, + } + } + + /// Takes the newest size reported since the last read; readiness doesn't depend on it. + pub(crate) fn take_size(&mut self) -> Option<(u32, u32)> { + match self { + State::Ready { size, .. } => size.take(), + State::Configuring { .. } | State::Closed => None, + } + } + + /// Takes the newest buffer scale reported since the last read. + pub(crate) fn take_scale(&mut self) -> Option<i32> { + match self { + State::Configuring { scale } | State::Ready { scale, .. } => scale.take(), + State::Closed => None, + } + } + } +} + +/// Layer-shell keyboard focus transitions, persisted modifier masks, command-chord translation, +/// and `KeyPolicy` capability checks, kept cross-platform so they compile and run tests on every +/// host. +pub(crate) mod keyboard { + use crate::machine::Effects; + + #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] + pub(crate) enum FocusState { + #[default] + Unfocused, + Focused, + } + + impl FocusState { + #[cfg_attr(not(all(unix, not(target_os = "macos"), not(target_os = "ios"), not(target_os = "android"))), allow(dead_code))] + pub(crate) fn focused(self) -> bool { matches!(self, FocusState::Focused) } + } + + #[derive(Clone, Copy, Debug, PartialEq, Eq)] + pub(crate) enum FocusEvent { + EnterOurs, + EnterOther, + LeaveOurs, + KeyboardGone, + } + + #[derive(Clone, Copy, Debug, PartialEq, Eq)] + pub(crate) enum FocusEffect { + Focus(bool), + } + + /// Transitions keyboard focus and emits `Focus(true)` / `Focus(false)` only on real edges. + pub(crate) fn step(state: &mut FocusState, event: FocusEvent) -> Effects<FocusEffect> { + match (*state, event) { + (FocusState::Unfocused, FocusEvent::EnterOurs) => { + *state = FocusState::Focused; + Effects::one(FocusEffect::Focus(true)) + } + (FocusState::Focused, FocusEvent::EnterOther | FocusEvent::LeaveOurs | FocusEvent::KeyboardGone) => { + *state = FocusState::Unfocused; + Effects::one(FocusEffect::Focus(false)) + } + _ => Effects::none(), + } + } + + /// Last modifier mask sent by `wl_keyboard.modifiers`, reapplied whenever a new `keymap` + /// replaces the XKB state (e.g. layout switch or `Modifiers` arriving before `Keymap`). + #[cfg_attr(not(all(unix, not(target_os = "macos"), not(target_os = "ios"), not(target_os = "android"))), allow(dead_code))] + #[derive(Clone, Copy, Debug, PartialEq, Eq)] + pub(crate) struct ModState { + pub(crate) depressed: u32, + pub(crate) latched: u32, + pub(crate) locked: u32, + pub(crate) group: u32, + } + + /// Translates an XKB key press into Rune's logical `KeyEvent`, matching `window/keys.rs`: + /// ignores NUL/control characters under `Ctrl` (such as pressing Shift while holding Ctrl), + /// keeps `Ctrl+Space` as `Key::Text(" ")`, and maps non-ASCII layout chords (such as Russian + /// `Ctrl+М`) through `us_char` to their US physical command key (`Command('v')`). + pub(crate) fn key_event_from( + named: Option<crate::Key>, + utf32: u32, + text: String, + mods: crate::Mods, + physical: Option<crate::PhysicalKeyCode>, + ) -> Option<crate::KeyEvent> { + let key = match named { + Some(key) => key, + None if mods.cmd => { + let ch = char::from_u32(utf32).filter(|c| !c.is_control())?; + if ch == ' ' { + crate::Key::Text(" ".to_owned()) + } else if !ch.is_ascii() + && let Some(us) = physical.and_then(crate::shortcuts::us_char) + { + crate::Key::Command(us) + } else { + crate::Key::Command(ch.to_ascii_lowercase()) + } + } + None => { + if !text.is_empty() && !text.chars().any(char::is_control) { + crate::Key::Text(text) + } else { + return None; + } + } + }; + Some(crate::KeyEvent { key, mods }) + } + + /// Whether a layer-shell overlay with `policy` may request keyboard interactivity on + /// `zwlr_layer_surface_v1` `layer_version`. + pub(crate) fn can_request_keys(policy: crate::KeyPolicy, layer_version: u32) -> bool { + policy == crate::KeyPolicy::OnDemand && layer_version >= 4 + } + + /// Whether a layer-shell overlay reports `nonactivating_keys` support. + pub(crate) fn supports_keys(policy: crate::KeyPolicy, layer_version: u32, has_seat: bool) -> bool { + can_request_keys(policy, layer_version) && has_seat + } +} + +#[cfg(test)] +#[path = "layer_shell_machine_tests.rs"] +mod tests; diff --git a/app/vendor/rune/crates/rune/src/platform/layer_shell_machine_tests.rs b/app/vendor/rune/crates/rune/src/platform/layer_shell_machine_tests.rs new file mode 100644 index 0000000..f226e7f --- /dev/null +++ b/app/vendor/rune/crates/rune/src/platform/layer_shell_machine_tests.rs @@ -0,0 +1,249 @@ +//! Every short sequence through the layer surface's two machines, since both are fed by events +//! whose order the compositor chooses: a configure, a preferred scale and a close can arrive in +//! any order, as can a finger's down, motion, lift and cancel. Touch is checked against a +//! transcription of the code it replaced, so the conversion can't quietly change what an app sees. + +use super::{readiness, touch}; + +/// Every sequence of up to `depth` symbols, shortest first, through `each`. +fn each_sequence<T: Copy>(alphabet: &[T], depth: usize, seq: &mut Vec<T>, each: &mut impl FnMut(&[T])) { + each(seq); + if seq.len() == depth { + return; + } + for &symbol in alphabet { + seq.push(symbol); + each_sequence(alphabet, depth, seq, each); + seq.pop(); + } +} + +/// The old `touch_id: Option<i32>` and the input it pushed, transcribed. +#[derive(Default)] +struct OldTouch { + id: Option<i32>, +} + +impl OldTouch { + fn step(&mut self, event: touch::Event) -> Vec<touch::Effect> { + use touch::Effect; + match event { + touch::Event::Down { id, x, y } if self.id.is_none() => { + self.id = Some(id); + vec![Effect::Move(x, y), Effect::Press] + } + touch::Event::Motion { id, x, y } if self.id == Some(id) => vec![Effect::Move(x, y)], + touch::Event::Up { id } if self.id == Some(id) => { + self.id = None; + vec![Effect::Release, Effect::Leave] + } + touch::Event::Cancel if self.id.is_some() => { + self.id = None; + vec![Effect::Leave, Effect::Release] + } + touch::Event::Gone => { + self.id = None; + Vec::new() + } + _ => Vec::new(), + } + } +} + +#[test] +fn every_touch_sequence_matches_what_the_old_finger_did() { + use touch::{Effect, Event}; + let alphabet = [ + Event::Down { id: 0, x: 1.0, y: 2.0 }, + Event::Down { id: 1, x: 3.0, y: 4.0 }, + Event::Motion { id: 0, x: 5.0, y: 6.0 }, + Event::Motion { id: 1, x: 7.0, y: 8.0 }, + Event::Up { id: 0 }, + Event::Up { id: 1 }, + Event::Cancel, + Event::Gone, + ]; + each_sequence(&alphabet, 5, &mut Vec::new(), &mut |seq| { + let (mut finger, mut old) = (touch::State::default(), OldTouch::default()); + let (mut presses, mut releases, mut orphaned) = (0usize, 0usize, 0usize); + for (i, &event) in seq.iter().enumerate() { + // The seat going away lifts the finger without a release: the only press that ends + // without one. + if event == Event::Gone && old.id.is_some() { + orphaned += 1; + } + let got: Vec<Effect> = touch::step(&mut finger, event).into_iter().collect(); + assert_eq!(got, old.step(event), "event {i} of {seq:?}"); + for effect in &got { + match effect { + Effect::Press => presses += 1, + Effect::Release => releases += 1, + Effect::Move(..) | Effect::Leave => {} + } + } + assert_eq!(matches!(finger, touch::State::Down { .. }), old.id.is_some(), "finger after {seq:?}"); + if let (touch::State::Down { id }, Some(old_id)) = (finger, old.id) { + assert_eq!(id, old_id, "finger after {seq:?}"); + } + // One finger: it never releases twice, and only a vanished seat leaves a press behind. + assert!(releases <= presses && presses - releases <= 1 + orphaned, "presses {presses}, releases {releases}, orphaned {orphaned} in {seq:?}"); + } + }); +} + +/// The old `configured`/`scale`/`closed` fields, transcribed literally: `configured` was the +/// size the compositor asked for (taken by a read, which is why it couldn't say "ready"), `scale` +/// the last one it sent, and `closed` latched. All three kept taking new values after a close; +/// nothing read them, because the caller hides on `closed`. `ever` is what readiness means, kept +/// beside them so the machine's `configured()` can be compared on every step. +#[derive(Default)] +struct OldReadiness { + configured: Option<(u32, u32)>, + scale: Option<i32>, + closed: bool, + ever: bool, +} + +impl OldReadiness { + fn step(&mut self, event: readiness::Event) { + match event { + readiness::Event::Configure { width, height } => { + self.configured = Some((width, height)); + self.ever = true; + } + readiness::Event::Scale(scale) => self.scale = Some(scale), + readiness::Event::Closed => self.closed = true, + } + } +} + +/// What `overlay/draw.rs` uses from one `dispatch`: it hides on `closed`, and reads a size and a +/// scale only while the surface is still open. Both sides are projected through this, so a read +/// after a close is compared like any other instead of being skipped. +#[derive(Debug, PartialEq)] +struct Used { + closed: bool, + size: Option<(u32, u32)>, + scale: Option<i32>, +} + +fn used(closed: bool, size: Option<(u32, u32)>, scale: Option<i32>) -> Used { + match closed { + true => Used { closed, size: None, scale: None }, + false => Used { closed, size, scale }, + } +} + +#[test] +fn every_readiness_sequence_reports_the_same_size_and_scale() { + #[derive(Clone, Copy, Debug)] + enum Symbol { + Event(readiness::Event), + Read, + } + use readiness::Event; + let alphabet = [ + Symbol::Event(Event::Configure { width: 10, height: 20 }), + Symbol::Event(Event::Configure { width: 30, height: 40 }), + Symbol::Event(Event::Scale(2)), + Symbol::Event(Event::Scale(3)), + Symbol::Event(Event::Closed), + Symbol::Read, + ]; + each_sequence(&alphabet, 6, &mut Vec::new(), &mut |seq| { + let (mut state, mut old) = (readiness::State::default(), OldReadiness::default()); + for (i, symbol) in seq.iter().enumerate() { + match symbol { + Symbol::Event(event) => { + readiness::step(&mut state, *event); + old.step(*event); + } + Symbol::Read => { + let got = used(state.closed(), state.take_size(), state.take_scale()); + let was = used(old.closed, old.configured.take(), old.scale.take()); + assert_eq!(got, was, "read {i} of {seq:?}"); + } + } + assert_eq!(state.closed(), old.closed, "closed after {seq:?}"); + assert_eq!(state.configured(), old.ever || old.closed, "configured after {seq:?}"); + } + }); +} + +#[test] +fn a_second_configure_replaces_the_size_nobody_read() { + let mut state = readiness::State::default(); + readiness::step(&mut state, readiness::Event::Scale(2)); + assert!(!state.configured()); + assert_eq!(state.size(), None, "no size before the first configure"); + readiness::step(&mut state, readiness::Event::Configure { width: 10, height: 20 }); + assert!(state.configured()); + readiness::step(&mut state, readiness::Event::Configure { width: 30, height: 40 }); + assert_eq!(state.size(), Some((30, 40))); + assert_eq!(state.take_size(), Some((30, 40))); + assert_eq!(state.take_size(), None, "read once"); + assert!(state.configured(), "reading the size doesn't unconfigure the surface"); + assert_eq!(state.take_scale(), Some(2), "a scale sent before the first configure is kept"); + readiness::step(&mut state, readiness::Event::Closed); + assert!(state.closed()); + assert_eq!(state.take_size(), None); +} + +#[test] +fn keyboard_focus_emits_focus_edges_and_releases_on_seat_loss_or_other_surface() { + use super::keyboard::{FocusEffect, FocusEvent, FocusState, step}; + let mut state = FocusState::default(); + assert!(step(&mut state, FocusEvent::LeaveOurs).is_empty(), "leave while unfocused is a no-op"); + assert_eq!( + step(&mut state, FocusEvent::EnterOurs).into_iter().collect::<Vec<_>>(), + [FocusEffect::Focus(true)] + ); + assert!(step(&mut state, FocusEvent::EnterOurs).is_empty(), "duplicate enter emits nothing"); + assert_eq!( + step(&mut state, FocusEvent::EnterOther).into_iter().collect::<Vec<_>>(), + [FocusEffect::Focus(false)], + "entering another surface loses focus on ours" + ); + assert_eq!( + step(&mut state, FocusEvent::EnterOurs).into_iter().collect::<Vec<_>>(), + [FocusEffect::Focus(true)] + ); + assert_eq!( + step(&mut state, FocusEvent::KeyboardGone).into_iter().collect::<Vec<_>>(), + [FocusEffect::Focus(false)], + "seat losing keyboard capability notifies focus loss" + ); + assert!(step(&mut state, FocusEvent::LeaveOurs).is_empty()); +} + +#[test] +fn layer_shell_key_translation_handles_ctrl_modifiers_space_and_non_ascii_layouts() { + use super::keyboard::{can_request_keys, key_event_from, supports_keys}; + use crate::{Key, KeyPolicy, Mods, PhysicalKeyCode}; + + let ctrl = Mods { ctrl: true, cmd: true, ..Default::default() }; + // Holding Ctrl and pressing Shift/Alt yields utf32 == 0 -> must return None, never Command('\0'). + assert_eq!(key_event_from(None, 0, String::new(), ctrl, Some(PhysicalKeyCode::ShiftLeft)), None); + // Ctrl+Space stays text space, matching window/keys.rs. + assert_eq!( + key_event_from(None, ' ' as u32, " ".into(), ctrl, Some(PhysicalKeyCode::Space)).map(|e| e.key.clone()), + Some(Key::Text(" ".into())) + ); + // Ctrl+V on Russian layout ('м' on KeyV) maps to US Command('v'), matching window/keys.rs. + assert_eq!( + key_event_from(None, 'м' as u32, "м".into(), ctrl, Some(PhysicalKeyCode::KeyV)).map(|e| e.key.clone()), + Some(Key::Command('v')) + ); + // Plain Ctrl+C maps to Command('c'). + assert_eq!( + key_event_from(None, 'C' as u32, "C".into(), ctrl, Some(PhysicalKeyCode::KeyC)).map(|e| e.key.clone()), + Some(Key::Command('c')) + ); + // KeyPolicy::None must never report or request keyboard interactivity even with a seat. + assert!(!can_request_keys(KeyPolicy::None, 4)); + assert!(!supports_keys(KeyPolicy::None, 4, true)); + assert!(can_request_keys(KeyPolicy::OnDemand, 4)); + assert!(supports_keys(KeyPolicy::OnDemand, 4, true)); + assert!(!supports_keys(KeyPolicy::OnDemand, 3, true)); + assert!(!supports_keys(KeyPolicy::OnDemand, 4, false)); +} diff --git a/app/vendor/rune/crates/rune/src/platform/layer_shell_tests.rs b/app/vendor/rune/crates/rune/src/platform/layer_shell_tests.rs new file mode 100644 index 0000000..0fea9cd --- /dev/null +++ b/app/vendor/rune/crates/rune/src/platform/layer_shell_tests.rs @@ -0,0 +1,14 @@ +use super::named_keysym; +use crate::Key; + +#[test] +fn special_keysyms_are_named_keys() { + for (symbol, key) in [ + (0xff14, Key::ScrollLock), (0xff13, Key::Pause), (0xff6b, Key::Pause), (0xff67, Key::ContextMenu), + (0xff61, Key::PrintScreen), (0xff15, Key::PrintScreen), (0xff63, Key::Insert), + (0xffbe, Key::Function(1)), (0xffd5, Key::Function(24)), (0xff55, Key::PageUp), + ] { + assert_eq!(named_keysym(symbol), Some(key), "keysym {symbol:#x}"); + } + assert_eq!(named_keysym(0x61), None); +} diff --git a/app/vendor/rune/crates/rune/src/platform/macos.rs b/app/vendor/rune/crates/rune/src/platform/macos.rs new file mode 100644 index 0000000..51a1dd0 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/platform/macos.rs @@ -0,0 +1,352 @@ +//! AppKit activation policy, overlay windows, and visibility without activation. + +use objc2_app_kit::{NSApplication, NSApplicationActivationPolicy}; +use objc2::{ClassType, DefinedClass, MainThreadMarker, define_class, msg_send}; +use objc2::rc::Retained; +use objc2_app_kit::{NSEvent, NSPanel, NSWindow, NSResponder, NSScreen, NSView}; +use objc2_foundation::{NSObject, NSPoint, NSRect, NSSize}; +use crate::{KeyPolicy, OverlayInput, OverlayLevel, OverlayOptions, OverlaySupport}; +use std::{cell::{Cell, RefCell}, rc::Rc, time::Instant}; + +#[doc(hidden)] +pub mod appearance; +pub(crate) mod cursor; +pub(crate) mod drop; +mod geometry; +mod hold; +pub(crate) mod help; +#[doc(hidden)] +pub mod panel_bridge; +mod pointer; +pub(crate) mod presence; +mod presentation; +mod surface; +pub(crate) mod traffic_lights; +pub(crate) mod window_shape; + +pub(crate) use geometry::{backing_scale, content_origin, display_bounds, outer_size, overlay_rect, place_window, pointer_display, set_window_frame, window_geometry}; +pub(crate) use pointer::PointerState; +pub(crate) use presentation::Prewarm; +#[cfg(test)] +pub(crate) use surface::layer_occluded; +pub(crate) use surface::{PresumeShown, pin_contents_top_left, present_with_transaction, surface_occluded, window_occluded}; +use geometry::{overlay_rect_on, screen_id}; +use pointer::MouseMonitors; +use presence::Presence; +use surface::occlusion_hidden; + +#[allow(unsafe_code)] +mod overlay_panel { + use super::*; + + pub(super) struct PanelFlags { + pub(super) keys: bool, + pub(super) presence: Rc<Cell<Presence>>, + pub(super) constrain: bool, + } + + // Initialized nonactivating panel. No application activation call. + define_class!( + #[unsafe(super(NSPanel, NSWindow, NSResponder, NSObject))] + #[name = "RuneOverlayPanel"] + #[ivars = PanelFlags] + pub(super) struct OverlayPanel; + + impl OverlayPanel { + #[unsafe(method(canBecomeKeyWindow))] + fn can_become_key(&self) -> bool { self.ivars().keys } + #[unsafe(method(canBecomeMainWindow))] + fn can_become_main(&self) -> bool { false } + #[unsafe(method(occlusionState))] + fn occlusion_state(&self) -> usize { + // wgpu skips nextDrawable for occluded windows. Permit only the explicit + // alpha-zero prewarm acquisition and a fade in or out, which AppKit reports as + // occluded while its alpha is near zero; other visibility readbacks stay native. + if self.ivars().presence.get().draws_occluded() { + 2 + } else { + // SAFETY: `OverlayPanel` inherits from `NSPanel` (`MainThreadOnly`), whose `occlusionState` returns `NSWindowOcclusionState` (`usize`). + unsafe { msg_send![super(self), occlusionState] } + } + } + // AppKit keeps windows below the menu bar's level out from under it; an overlay goes + // exactly where it's placed at any level. + #[unsafe(method(constrainFrameRect:toScreen:))] + fn constrain_frame_rect(&self, frame: NSRect, screen: *mut NSScreen) -> NSRect { + // SAFETY: `OverlayPanel` inherits from `NSPanel` (`MainThreadOnly`); `frame` and `screen` match `constrainFrameRect:toScreen:`. + if self.ivars().constrain { unsafe { msg_send![super(self), constrainFrameRect: frame, toScreen: screen] } } + else { frame } + } + #[unsafe(method(sendEvent:))] + fn send_event(&self, event: &NSEvent) { + // Without its view the panel would swallow this click and every later one. + if crate::platform::macos::panel_bridge::reattach(self.as_super()) { eprintln!("rune: panel lost its view; reattached on input"); } + // SAFETY: `OverlayPanel` inherits from `NSPanel` (`MainThreadOnly`); `event` is the live `NSEvent` passed by AppKit. + unsafe { let _: () = msg_send![super(self), sendEvent: event]; } + } + } + ); +} +use overlay_panel::{OverlayPanel, PanelFlags}; + +/// Whether the user is dragging the window's edge. +#[allow(unsafe_code)] +pub(crate) fn in_live_resize(window: &winit::window::Window) -> bool { + // SAFETY: a property read on the main thread. + ns_window(window).is_some_and(|window| unsafe { msg_send![&*window, inLiveResize] }) +} + +/// Regular (Dock icon and app menu) or accessory (menu-bar only). Called on the main thread. +pub(crate) fn set_dock_icon(visible: bool) { + let Some(mtm) = MainThreadMarker::new() else { return }; + let policy = if visible { NSApplicationActivationPolicy::Regular } else { NSApplicationActivationPolicy::Accessory }; + let app = NSApplication::sharedApplication(mtm); + if visible { crate::native_menu::promote_default_menu(&app); } + app.setActivationPolicy(policy); +} + +/// winit's content view. Once a [`Panel`] adopts it, its window is the panel. +#[allow(unsafe_code)] +pub(crate) fn content_view(window: &winit::window::Window) -> Option<Retained<objc2_app_kit::NSView>> { + use winit::raw_window_handle::{HasWindowHandle, RawWindowHandle}; + let RawWindowHandle::AppKit(handle) = window.window_handle().ok()?.as_raw() else { return None }; + // SAFETY: winit's content view is alive as long as its window, which the caller holds. + unsafe { Retained::retain(handle.ns_view.as_ptr().cast()) } +} + +pub(crate) fn ns_window(window: &winit::window::Window) -> Option<Retained<NSWindow>> { + content_view(window)?.window() +} + +pub(crate) fn configure_window(window: &winit::window::Window, options: &crate::MacWindowOptions) { + crate::platform::macos::appearance::install(); + if let Some(window) = ns_window(window) { configure_native(&window, options); } +} + +#[allow(unsafe_code)] +fn configure_native(window: &NSWindow, options: &crate::MacWindowOptions) { + if let Some(shadow) = options.shadow { window.setHasShadow(shadow); } + if let Some(level) = options.level { window.setLevel(level); } + // SAFETY: every caller runs on the AppKit main thread. + unsafe { + if let Some(bits) = options.collection_behavior { + let _: () = msg_send![window, setCollectionBehavior: bits]; + } + } + if let Some(exclude) = options.exclude_from_capture { set_sharing(window, exclude); } +} + +/// `sharingType` none keeps the window out of captures; read-only lets recorders see it. +/// Captures follow every change, but on recent macOS the `sharingType` getter and +/// CGWindowList's sharing state can keep reporting none after the first switch back, so +/// neither confirms a toggle. +#[allow(unsafe_code)] +fn set_sharing(window: &NSWindow, exclude: bool) { + // SAFETY: every caller runs on the AppKit main thread. + unsafe { let _: () = msg_send![window, setSharingType: if exclude { 0usize } else { 1usize }]; } +} + +/// Orders a window front without making it key or activating the app. +pub(crate) fn show_without_focus(window: &winit::window::Window) { + let Some(w) = ns_window(window) else { return }; + w.orderFrontRegardless(); +} + +/// An overlay's non-activating panel. winit's content view (with the Metal layer wgpu draws +/// into) moves into it, so clicks reach Rune through winit while the app never activates and +/// the panel only becomes key on request. winit's own window stays hidden and gets its view back on drop. +pub(crate) struct Panel { + bridge: Option<crate::platform::macos::panel_bridge::Bridge>, + monitors: RefCell<Option<MouseMonitors>>, + pointer: Rc<PointerState>, + options: OverlayOptions, + follow_pointer: Cell<bool>, + pointer_poll: Cell<Option<Instant>>, + /// Prewarmed, shown or fading, under one fence, and the requested capture exclusion, + /// applied only while shown. While a fade runs the panel reads as visible, so a fading-out + /// overlay can still draw its exit. + presence: Rc<Cell<Presence>>, + wake: Option<crate::Waker>, + panel: objc2::rc::Retained<objc2_app_kit::NSPanel>, + window: objc2::rc::Retained<objc2_app_kit::NSWindow>, + view: objc2::rc::Retained<objc2_app_kit::NSView>, +} + +impl Panel { + pub fn adopt(window: &winit::window::Window, at: crate::overlay::Placement, interactive: bool, options: &OverlayOptions, wake: Option<crate::Waker>) -> Option<Panel> { + Self::adopt_kind(window, at, interactive, options, wake, false) + } + + pub fn adopt_window(window: &winit::window::Window, size: (f32, f32), native: &crate::MacWindowOptions) -> Option<Panel> { + let options = OverlayOptions { input: OverlayInput::All, keys: KeyPolicy::OnDemand, prewarm: native.launcher, ..Default::default() }; + let panel = Self::adopt_kind(window, crate::windows::PlaceRequest::at(size), true, &options, None, true)?; + let mut native = native.clone(); + if let Some(exclude) = native.exclude_from_capture.take() { panel.set_capture_exclusion(exclude); } + configure_native(&panel.panel, &native); + Some(panel) + } + + #[allow(unsafe_code)] + fn adopt_kind(window: &winit::window::Window, at: crate::overlay::Placement, interactive: bool, options: &OverlayOptions, wake: Option<crate::Waker>, ordinary: bool) -> Option<Panel> { + use objc2_app_kit::{NSBackingStoreType, NSColor, NSWindowCollectionBehavior, NSWindowStyleMask}; + let mtm = MainThreadMarker::new()?; + crate::platform::macos::appearance::install(); + let view = content_view(window)?; + let ns_window = view.window()?; + let rect = NSRect::new(NSPoint::new(0.0, 0.0), NSSize::new(at.size.0 as f64, at.size.1 as f64)); + let presence = Rc::new(Cell::new(Presence::new(options.exclude_from_capture))); + let style = if ordinary { ns_window.styleMask() } else { NSWindowStyleMask::Borderless }; + // SAFETY: `mtm` proves main-thread execution; `OverlayPanel` inherits from `NSPanel`, so + // `initWithContentRect:styleMask:backing:defer:` and the upcast to `NSPanel` are valid. + let panel = unsafe { + let panel: Retained<OverlayPanel> = msg_send![super(mtm.alloc().set_ivars(PanelFlags { keys: options.keys == KeyPolicy::OnDemand, presence: presence.clone(), constrain: ordinary })), + initWithContentRect: rect, + styleMask: style | NSWindowStyleMask::NonactivatingPanel, + backing: NSBackingStoreType::Buffered, + defer: false]; + panel.into_super() + }; + // SAFETY: `panel` is a live retained `NSPanel` configured on the AppKit main thread (`mtm` checked above). + unsafe { + panel.setReleasedWhenClosed(false); + panel.setFloatingPanel(true); + panel.setBecomesKeyOnlyIfNeeded(options.keys == KeyPolicy::None); + panel.setHidesOnDeactivate(false); + panel.setBackgroundColor(Some(&NSColor::clearColor())); + panel.setCollectionBehavior( + NSWindowCollectionBehavior::CanJoinAllSpaces + | NSWindowCollectionBehavior::Stationary + | NSWindowCollectionBehavior::IgnoresCycle + | NSWindowCollectionBehavior::FullScreenAuxiliary + // Over other apps' full-screen Spaces too (macOS 13+; earlier ignores the bit). + | NSWindowCollectionBehavior::CanJoinAllApplications, + ); + } + let native = crate::MacWindowOptions::default().shadow(false) + .level(match options.level { OverlayLevel::Status => 25, OverlayLevel::AboveStatus => 26, OverlayLevel::AboveOverlays => 27 }); + configure_native(&panel, &native); + if ordinary { + panel.setTitle(&ns_window.title()); + panel.setLevel(3); + panel.setHasShadow(ns_window.hasShadow()); + panel.setContentMinSize(ns_window.contentMinSize()); + panel.setContentMaxSize(ns_window.contentMaxSize()); + panel.setFrame_display(ns_window.frame(), false); + } + panel.setOpaque(false); + panel.setIgnoresMouseEvents(options.input.resolved(interactive) != OverlayInput::All); + panel.setAcceptsMouseMovedEvents(true); + if options.prewarm { + panel.setAlphaValue(0.0); + panel.setIgnoresMouseEvents(true); + } + // defer:NO creates the WindowServer identity while hidden. Never publish a sentinel + // (-1/0) cast to CGWindowID as a successful native creation. + if panel.windowNumber() <= 0 { return None; } + ns_window.setContentView(None); + panel.setContentView(Some(&view)); + let pointer = Rc::new(PointerState::new(options.input.resolved(interactive), options.follow_pointer)); + let bridge = if ordinary { crate::platform::macos::panel_bridge::Bridge::new_window(&ns_window, &panel, &view) } + else { crate::platform::macos::panel_bridge::Bridge::new(&ns_window, &panel, &view, Some(pointer.clone())) }; + if bridge.is_none() { + panel.setContentView(None); + ns_window.setContentView(Some(&view)); + return None; + } + panel.setDelegate(ns_window.delegate().as_deref()); + Some(Panel { bridge, monitors: RefCell::new(None), pointer, options: options.clone(), follow_pointer: Cell::new(options.follow_pointer), pointer_poll: Cell::new(None), presence, wake, panel, window: ns_window, view }) + } + + /// On the primary screen (the one with the menu bar), in AppKit's bottom-left coordinates. + pub fn place(&self, at: crate::overlay::Placement, options: &OverlayOptions) { + let Some(rect) = self.rect(at, options) else { return }; + if self.panel.frame() != rect { + self.window.setFrame_display(rect, false); + self.panel.setFrame_display(rect, true); + if self.presence.get().visible() { self.pointer.observe(&self.panel, self.wake.as_ref()); } + } + } + + pub fn rect(&self, at: crate::overlay::Placement, options: &OverlayOptions) -> Option<NSRect> { + overlay_rect_on(at, options, self.panel.screen().map(|s| screen_id(&s))) + } + + /// Reattaches winit's view if something outside Rune took it from the panel, here or in + /// `sendEvent:`. Clicks recorded while it was gone were never delivered, so native capture + /// starts over, and a press the runtime still holds is released where the pointer was. + #[allow(unsafe_code)] + fn keep_view(&self) { + // SAFETY: plain readbacks on the main thread; nothing is retained. + let (content, window): (*const NSView, *const NSWindow) = unsafe { + (msg_send![&*self.panel, contentView], msg_send![&*self.view, window]) + }; + let attached = std::ptr::eq(content, &*self.view) && std::ptr::eq(window.cast::<NSPanel>(), &*self.panel); + if !attached && crate::platform::macos::panel_bridge::reattach(&self.panel) { eprintln!("rune: panel lost its view; reattached"); } + if crate::platform::macos::panel_bridge::take_reattached(&self.panel) { self.pointer.view_lost(); } + } + + /// Whether none of the panel is on screen: covered, or its displays asleep. Reads as + /// visible during a prewarm acquisition. + pub fn occluded(&self) -> bool { + occlusion_hidden(&self.panel) + } + + /// The panel's AppKit window level (`NSWindow.Level`), changeable while shown. + pub fn set_level(&self, level: isize) { self.panel.setLevel(level); } + + /// The moved view, for a new wgpu surface (winit's window handle would look for the view + /// in winit's window, where it no longer is). + pub fn raw_handles(&self) -> (winit::raw_window_handle::RawDisplayHandle, winit::raw_window_handle::RawWindowHandle) { + use winit::raw_window_handle::{AppKitDisplayHandle, AppKitWindowHandle, RawDisplayHandle, RawWindowHandle}; + let view = std::ptr::NonNull::from(&*self.view).cast(); + (RawDisplayHandle::AppKit(AppKitDisplayHandle::new()), RawWindowHandle::AppKit(AppKitWindowHandle::new(view))) + } + + pub fn window_number(&self) -> u32 { self.panel.windowNumber() as u32 } + pub fn capture_exclusion(&self) -> OverlaySupport { + if self.presence.get().requested() { OverlaySupport::Requested } else { OverlaySupport::Unknown } + } + pub fn request_keys(&self) { + if self.options.keys == KeyPolicy::OnDemand { + self.panel.makeFirstResponder(Some(&self.view)); + self.panel.makeKeyWindow(); + } + } + pub fn is_key(&self) -> bool { self.panel.isKeyWindow() } +} + +impl Drop for Panel { + fn drop(&mut self) { + self.monitors.get_mut().take(); + self.panel.setDelegate(None); + self.bridge.take(); + self.panel.orderOut(None); + self.panel.setContentView(None); + self.window.setContentView(Some(&self.view)); + } +} + +thread_local! { + /// Each window's count (`WindowHandle::set_taskbar`); the Dock shows their sum. + static BADGES: std::cell::RefCell<std::collections::HashMap<u64, u32>> = std::cell::RefCell::new(std::collections::HashMap::new()); +} + +/// `window`'s count for the Dock icon's badge, which is the app's: the sum over its windows, none +/// at 0. Main thread. +#[allow(unsafe_code)] +pub(crate) fn dock_badge(window: &winit::window::Window, count: u32) { + let Some(mtm) = MainThreadMarker::new() else { return }; + let total: u32 = BADGES.with_borrow_mut(|b| { + b.insert(u64::from(window.id()), count); + b.values().sum() + }); + let app = NSApplication::sharedApplication(mtm); + // SAFETY: AppKit's Dock tile, on the main thread; nil clears the badge. + unsafe { + let tile: *mut objc2::runtime::AnyObject = msg_send![&app, dockTile]; + if tile.is_null() { return; } + let label = (total > 0).then(|| objc2_foundation::NSString::from_str(&total.to_string())); + let label: *const objc2::runtime::AnyObject = label.as_deref().map_or(std::ptr::null(), |l| (l as *const objc2_foundation::NSString).cast()); + let _: () = msg_send![tile, setBadgeLabel: label]; + } +} \ No newline at end of file diff --git a/app/vendor/rune/crates/rune/src/platform/macos/appearance.rs b/app/vendor/rune/crates/rune/src/platform/macos/appearance.rs new file mode 100644 index 0000000..846474f --- /dev/null +++ b/app/vendor/rune/crates/rune/src/platform/macos/appearance.rs @@ -0,0 +1,88 @@ +//! winit 0.30 (and master) observes `effectiveAppearance` on each window and treats both KVO +//! values as `NSAppearance`. AppKit reports `NSNull` while a window's frame view is rebuilt +//! (ReplayKit, which ScreenCaptureKit starts, calls `setStyleMask:` on every app window), so +//! winit messages `NSNull` inside a callback that cannot unwind and the process aborts. +//! Wrap winit's observer once per process: nil transitions are held back, and the last real +//! appearance stands in for a nil old value, so real changes still reach winit's `ThemeChanged`. + +#![allow(unsafe_code)] + +use std::{ffi::c_void, sync::atomic::{AtomicUsize, Ordering}}; +use objc2::{msg_send, sel, runtime::{AnyClass, AnyObject, Sel}}; +use objc2_foundation::ns_string; + +type Observe = unsafe extern "C" fn(*mut AnyObject, Sel, *mut AnyObject, *mut AnyObject, *mut AnyObject, *mut c_void); + +unsafe extern "C" { + fn class_getInstanceMethod(class: *const AnyClass, selector: Sel) -> *const c_void; + fn method_getImplementation(method: *const c_void) -> *const c_void; + fn method_setImplementation(method: *const c_void, imp: *const c_void) -> *const c_void; + fn objc_getAssociatedObject(object: *const AnyObject, key: *const c_void) -> *mut AnyObject; + fn objc_setAssociatedObject(object: *const AnyObject, key: *const c_void, value: *const AnyObject, policy: usize); +} +#[link(name = "Foundation", kind = "framework")] +unsafe extern "C" { + static NSKeyValueChangeOldKey: *mut AnyObject; + static NSKeyValueChangeNewKey: *mut AnyObject; +} + +const RETAIN_NONATOMIC: usize = 1; +static ORIGINAL: AtomicUsize = AtomicUsize::new(0); +static LAST_APPEARANCE: u8 = 0; + +/// Main thread, after winit has created a window (its delegate class registers lazily). +#[doc(hidden)] +pub fn install() { + if ORIGINAL.load(Ordering::Relaxed) != 0 { return; } + let (Some(delegate), Some(object)) = (AnyClass::get(c"WinitWindowDelegate"), AnyClass::get(c"NSObject")) else { return }; + let selector = sel!(observeValueForKeyPath:ofObject:change:context:); + // SAFETY: called on the main thread after winit registers `WinitWindowDelegate`; `delegate` and `object` + // are valid classes, `ORIGINAL` is stored before swapping the IMP, and `observe` matches the KVO selector ABI. + unsafe { + let method = class_getInstanceMethod(delegate, selector); + // Only winit's own override; never NSObject's inherited implementation. + if method.is_null() || method == class_getInstanceMethod(object, selector) { return; } + ORIGINAL.store(method_getImplementation(method) as usize, Ordering::Relaxed); + method_setImplementation(method, observe as *const c_void); + } +} + +unsafe fn appearance(value: *mut AnyObject) -> bool { + let Some(class) = AnyClass::get(c"NSAppearance") else { return false }; + // SAFETY: `value` is checked non-null and caller guarantees it is a valid ObjC object; `class` is `NSAppearance`. + !value.is_null() && unsafe { msg_send![value, isKindOfClass: class] } +} + +unsafe fn remember(window: *mut AnyObject, value: *mut AnyObject) { + // SAFETY: caller guarantees `window` and `value` are valid ObjC objects; `&LAST_APPEARANCE` is a unique static key. + unsafe { objc_setAssociatedObject(window, (&LAST_APPEARANCE as *const u8).cast(), value, RETAIN_NONATOMIC) } +} + +unsafe extern "C" fn observe(this: *mut AnyObject, cmd: Sel, key_path: *mut AnyObject, window: *mut AnyObject, change: *mut AnyObject, context: *mut c_void) { + // SAFETY: set before this implementation was installed. + let original: Observe = unsafe { std::mem::transmute(ORIGINAL.load(Ordering::Relaxed)) }; + let key: &AnyObject = ns_string!("effectiveAppearance"); + let watched = !key_path.is_null() && !window.is_null() && !change.is_null() + // SAFETY: `key_path` is non-null and passed as an `NSString` by KVO; `key` is a valid `NSString`. + && unsafe { msg_send![key_path, isEqualToString: key] }; + // SAFETY: `original` is winit's original KVO IMP with the same ABI and arguments passed by AppKit. + if !watched { return unsafe { original(this, cmd, key_path, window, change, context) } } + // SAFETY: KVO guarantees non-null `window` and `change` (`NSDictionary`) are live ObjC objects, + // `NSKeyValueChange*Key` are valid Foundation keys, and `patched` from `mutableCopy` is released after forwarding. + unsafe { + let old: *mut AnyObject = msg_send![change, objectForKey: NSKeyValueChangeOldKey]; + let new: *mut AnyObject = msg_send![change, objectForKey: NSKeyValueChangeNewKey]; + match (appearance(old), appearance(new)) { + (true, true) => { remember(window, new); original(this, cmd, key_path, window, change, context) } + (old_known, false) => if old_known { remember(window, old) }, + (false, true) => { + let last = objc_getAssociatedObject(window, (&LAST_APPEARANCE as *const u8).cast()); + let patched: *mut AnyObject = msg_send![change, mutableCopy]; + let _: () = msg_send![patched, setObject: if last.is_null() { new } else { last }, forKey: NSKeyValueChangeOldKey]; + remember(window, new); + original(this, cmd, key_path, window, patched, context); + let _: () = msg_send![patched, release]; + } + } + } +} diff --git a/app/vendor/rune/crates/rune/src/platform/macos/cursor.rs b/app/vendor/rune/crates/rune/src/platform/macos/cursor.rs new file mode 100644 index 0000000..c0d829d --- /dev/null +++ b/app/vendor/rune/crates/rune/src/platform/macos/cursor.rs @@ -0,0 +1,229 @@ +//! AppKit cursors set directly: for overlays, which are rarely the key window, and for image +//! cursors, which winit would size in pixels (twice too big on Retina). + +#![allow(unsafe_code)] + +use std::cell::RefCell; +#[cfg(feature = "macos-background-cursor")] +use std::cell::Cell; + +use objc2::rc::Retained; +use objc2::msg_send; +use objc2_foundation::{NSObject, NSPoint, NSSize}; + +use crate::cursor::CursorImage; +use crate::cursor::image::{Decoded, ImageCursors, SOURCE_SCALE}; +use crate::el::Cursor; + +thread_local! { + static IMAGES: RefCell<ImageCursors<Retained<NSObject>>> = const { RefCell::new(ImageCursors::new()) }; +} + +/// The NSCursor for `image`, made once. `None` if it didn't decode. +fn native(image: CursorImage) -> Option<Retained<NSObject>> { + IMAGES.with(|c| c.borrow_mut().get(image, SOURCE_SCALE, ns_cursor)) +} + +/// Sets an image cursor on `window` itself, with the window's cursor rects (winit's cursor) +/// off so AppKit doesn't put winit's back on entering, focus or a rect rebuild. Gives +/// winit's cursor back, turning the rects on, for any other cursor. `None` when the image is +/// set; otherwise the cursor for winit, the arrow for an image that didn't decode. +pub(crate) fn window_cursor(window: &winit::window::Window, next: Cursor) -> Option<Cursor> { + let Some(ns_window) = crate::platform::macos::ns_window(window) else { return Some(next) }; + if let Cursor::Image(image) = next && let Some(cursor) = native(image) { + // SAFETY: NSWindow and NSCursor on the main thread, where winit applies cursors. + unsafe { + let _: () = msg_send![&*ns_window, disableCursorRects]; + let _: () = msg_send![&*cursor, set]; + } + return None; + } + let next = if matches!(next, Cursor::Image(_)) { Cursor::Default } else { next }; + // SAFETY: as above. + unsafe { + let enabled: bool = msg_send![&*ns_window, areCursorRectsEnabled]; + if !enabled { + let _: () = msg_send![&*ns_window, enableCursorRects]; + if let Some(view) = crate::platform::macos::content_view(window) { let _: () = msg_send![&*ns_window, invalidateCursorRectsForView: &*view]; } + // The rects come back on AppKit's next pass, and not at all once the pointer has + // left: the image mustn't stay until then. + set_ns_cursor(next); + } + } + Some(next) +} + +/// Sets an image cursor again while it holds the pointer: the system may have shown another +/// on the way (a window edge's resize arrows), and the window's rects are off. +pub(crate) fn reassert(image: CursorImage) { + let Some(Some(cursor)) = IMAGES.with(|c| c.borrow_mut().cached(image, SOURCE_SCALE)) else { return }; + // SAFETY: NSCursor on the main thread. + unsafe { let _: () = msg_send![&*cursor, set]; } +} + +/// An NSCursor whose image is sized in points with `d`'s pixels as its bitmap, so a 2x PNG is +/// sharp on Retina and its size in points everywhere. winit sizes the image in pixels. +pub(crate) fn ns_cursor(d: &Decoded) -> Result<Retained<NSObject>, String> { + use objc2::rc::Allocated; + use objc2::runtime::{AnyClass, AnyObject, Bool}; + use objc2_foundation::NSString; + let class = |name: &std::ffi::CStr| AnyClass::get(name).ok_or_else(|| format!("{} is unavailable", name.to_string_lossy())); + let (bitmap, image, cursor, color_space) = (class(c"NSBitmapImageRep")?, class(c"NSImage")?, class(c"NSCursor")?, class(c"NSColorSpace")?); + let (w, h) = (d.width as isize, d.height as isize); + // SAFETY: AppKit image and cursor construction; every object is retained, the bitmap + // written only within its rows. + objc2::rc::autoreleasepool(|_| unsafe { + let rep: Allocated<AnyObject> = msg_send![bitmap, alloc]; + let null: *mut *mut u8 = std::ptr::null_mut(); + // Default bitmapFormat: premultiplied alpha-last RGBA. + let rep: Option<Retained<AnyObject>> = msg_send![rep, + initWithBitmapDataPlanes: null, pixelsWide: w, pixelsHigh: h, bitsPerSample: 8isize, + samplesPerPixel: 4isize, hasAlpha: Bool::YES, isPlanar: Bool::NO, + colorSpaceName: &*NSString::from_str("NSDeviceRGBColorSpace"), bitmapFormat: 0usize, + bytesPerRow: w * 4, bitsPerPixel: 32isize]; + let rep = rep.ok_or("could not allocate a cursor bitmap")?; + let data: *mut u8 = msg_send![&*rep, bitmapData]; + let stride: isize = msg_send![&*rep, bytesPerRow]; + if data.is_null() || stride < w * 4 { return Err("the cursor bitmap has no pixels".into()); } + for (y, row) in d.rgba.chunks_exact(w as usize * 4).enumerate() { + let out = std::slice::from_raw_parts_mut(data.offset(y as isize * stride), w as usize * 4); + for (o, p) in out.chunks_exact_mut(4).zip(row.chunks_exact(4)) { + for i in 0..3 { o[i] = ((p[i] as u32 * p[3] as u32 + 127) / 255) as u8; } + o[3] = p[3]; + } + } + let srgb: *mut AnyObject = msg_send![color_space, sRGBColorSpace]; + let tagged: Option<Retained<AnyObject>> = msg_send![&*rep, bitmapImageRepByRetaggingWithColorSpace: srgb]; + let rep = tagged.unwrap_or(rep); + let size = NSSize::new(d.width as f64 / d.scale as f64, d.height as f64 / d.scale as f64); + let ns_image: Allocated<NSObject> = msg_send![image, alloc]; + let ns_image: Option<Retained<NSObject>> = msg_send![ns_image, initWithSize: size]; + let ns_image = ns_image.ok_or("NSImage refused the size")?; + let _: () = msg_send![&*ns_image, addRepresentation: &*rep]; + let [x, y] = d.hot.map(|h| h as f64 / d.scale as f64); + let ns_cursor: Allocated<NSObject> = msg_send![cursor, alloc]; + let ns_cursor: Option<Retained<NSObject>> = msg_send![ns_cursor, initWithImage: &*ns_image, hotSpot: NSPoint::new(x, y)]; + ns_cursor.ok_or_else(|| "NSCursor refused the image".into()) + }) +} + +/// `[NSCursor set]` with winit's shape for each cursor. Main thread. +pub(crate) fn set_ns_cursor(cursor: Cursor) { + use crate::cursor::{MacCursor as M, mac_cursor}; + thread_local! { + static TRANSPARENT: Option<Retained<NSObject>> = image_cursor(None); + static MOVE: Option<Retained<NSObject>> = image_cursor(Some("move")); + static CELL: Option<Retained<NSObject>> = image_cursor(Some("cell")); + } + let Some(class) = objc2::runtime::AnyClass::get(c"NSCursor") else { return }; + #[cfg(feature = "macos-background-cursor")] + sets_cursor_in_background(); + // SAFETY: NSCursor class methods and -set on the main thread. + unsafe { + let ns: Option<Retained<NSObject>> = match mac_cursor(cursor) { + M::Arrow => arrow(class), + M::PointingHand => msg_send![class, pointingHandCursor], + M::IBeam => msg_send![class, IBeamCursor], + M::OpenHand => msg_send![class, openHandCursor], + M::ClosedHand => msg_send![class, closedHandCursor], + M::NotAllowed => msg_send![class, operationNotAllowedCursor], + M::ResizeLeftRight => msg_send![class, resizeLeftRightCursor], + M::ResizeUpDown => msg_send![class, resizeUpDownCursor], + M::Crosshair => msg_send![class, crosshairCursor], + // Public from macOS 15; before that only as the private selectors winit uses. + M::ZoomIn => named(class, &[objc2::sel!(zoomInCursor), objc2::sel!(_zoomInCursor)]), + M::ZoomOut => named(class, &[objc2::sel!(zoomOutCursor), objc2::sel!(_zoomOutCursor)]), + // No built-in NSCursor class method: loaded from the system/app image, falling back to + // the arrow if unavailable. + M::Transparent => TRANSPARENT.with(Clone::clone).or_else(|| arrow(class)), + M::MoveImage => MOVE.with(Clone::clone).or_else(|| arrow(class)), + M::CellImage => CELL.with(Clone::clone).or_else(|| arrow(class)), + M::Custom(image) => native(image).or_else(|| arrow(class)), + }; + if let Some(ns) = ns { let _: () = msg_send![&*ns, set]; } + } +} + +/// `[NSCursor arrowCursor]`. +/// +/// # Safety +/// Main thread; `class` is `NSCursor`. +unsafe fn arrow(class: &objc2::runtime::AnyClass) -> Option<Retained<NSObject>> { + // SAFETY: caller guarantees main thread and `NSCursor` class. + unsafe { msg_send![class, arrowCursor] } +} + +/// The first of `selectors` NSCursor answers, else the arrow. +/// +/// # Safety +/// Main thread; each selector is a class method returning an NSCursor. +unsafe fn named(class: &objc2::runtime::AnyClass, selectors: &[objc2::runtime::Sel]) -> Option<Retained<NSObject>> { + for &sel in selectors { + // SAFETY: the caller's; `respondsToSelector:` guards the send. + unsafe { + let responds: bool = msg_send![class, respondsToSelector: sel]; + if responds { return msg_send![class, performSelector: sel]; } + } + } + // SAFETY: as above. + unsafe { msg_send![class, arrowCursor] } +} + +/// The window server ignores `[NSCursor set]` from an app that isn't active, which an overlay's +/// app usually isn't. WindowServer's per-connection `SetsCursorInBackground` property lifts +/// that; it's private, so it's opt-in (`macos-background-cursor`), looked up at run time and +/// skipped if it's gone. Without the feature none of its names are in the binary. +#[cfg(feature = "macos-background-cursor")] +fn sets_cursor_in_background() { + use std::ffi::{c_char, c_void}; + thread_local! { static DONE: Cell<bool> = const { Cell::new(false) }; } + if DONE.with(|done| done.replace(true)) { return; } + unsafe extern "C" { fn dlsym(handle: *mut c_void, symbol: *const c_char) -> *mut c_void; } + #[link(name = "CoreFoundation", kind = "framework")] + unsafe extern "C" { static kCFBooleanTrue: *const c_void; } + const RTLD_DEFAULT: *mut c_void = -2isize as *mut c_void; + // SAFETY: both symbols have these C signatures; the key and value outlive the call. + unsafe { + let (main, set) = (dlsym(RTLD_DEFAULT, c"_CGSDefaultConnection".as_ptr()), dlsym(RTLD_DEFAULT, c"CGSSetConnectionProperty".as_ptr())); + if main.is_null() || set.is_null() { return; } + let main: extern "C" fn() -> i32 = std::mem::transmute(main); + let set: extern "C" fn(i32, i32, *const c_void, *const c_void) -> i32 = std::mem::transmute(set); + let key = objc2_foundation::NSString::from_str("SetsCursorInBackground"); + let connection = main(); + set(connection, connection, (&*key as *const objc2_foundation::NSString).cast(), kCFBooleanTrue); + } +} + +/// A transparent cursor (`None`), or one of the system's WebKit cursors as winit loads them. +fn image_cursor(name: Option<&str>) -> Option<Retained<NSObject>> { + use objc2::runtime::AnyClass; + use objc2_foundation::NSString; + // A 16x16 transparent GIF. + const TRANSPARENT: &[u8] = &[ + 0x47, 0x49, 0x46, 0x38, 0x39, 0x61, 0x10, 0x00, 0x10, 0x00, 0xf0, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x21, 0xf9, 0x04, 0x01, 0x00, 0x00, 0x00, 0x00, 0x2c, 0x00, 0x00, + 0x00, 0x00, 0x10, 0x00, 0x10, 0x00, 0x00, 0x02, 0x0e, 0x84, 0x8f, 0xa9, 0xcb, 0xed, 0x0f, + 0xa3, 0x9c, 0xb4, 0xda, 0x8b, 0xb3, 0x3e, 0x05, 0x00, 0x3b, + ]; + let (image_class, cursor_class) = (AnyClass::get(c"NSImage")?, AnyClass::get(c"NSCursor")?); + // SAFETY: AppKit image and cursor construction on the main thread; every object is retained. + unsafe { + let image: Option<Retained<NSObject>> = match name { + None => { + let data: Option<Retained<NSObject>> = msg_send![objc2::class!(NSData), dataWithBytes: TRANSPARENT.as_ptr().cast::<std::ffi::c_void>(), length: TRANSPARENT.len()]; + let image: objc2::rc::Allocated<NSObject> = msg_send![image_class, alloc]; + msg_send![image, initWithData: &*data?] + } + Some(name) => { + let path = NSString::from_str(&format!("/System/Library/Frameworks/ApplicationServices.framework/Versions/A/Frameworks/HIServices.framework/Versions/A/Resources/cursors/{name}/cursor.pdf")); + let image: objc2::rc::Allocated<NSObject> = msg_send![image_class, alloc]; + msg_send![image, initByReferencingFile: &*path] + } + }; + let image = image?; + let size: NSSize = msg_send![&*image, size]; + let hot = if name.is_some() { NSPoint::new(size.width / 2.0, size.height / 2.0) } else { NSPoint::new(0.0, 0.0) }; + let cursor: objc2::rc::Allocated<NSObject> = msg_send![cursor_class, alloc]; + msg_send![cursor, initWithImage: &*image, hotSpot: hot] + } +} diff --git a/app/vendor/rune/crates/rune/src/platform/macos/drop.rs b/app/vendor/rune/crates/rune/src/platform/macos/drop.rs new file mode 100644 index 0000000..5568223 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/platform/macos/drop.rs @@ -0,0 +1,376 @@ +//! Drags from other apps onto a window, on macOS. winit's window takes only file paths, so a +//! drag carrying none was refused: the screenshot thumbnail, Photos and browsers' images send a +//! file promise, Safari and canvases bare image data. The content view becomes the window's +//! drag destination instead (a per-instance subclass, as `own_window_dragging` makes): a file +//! promise is received into a temporary folder and image data is written there as a file, so a +//! drop still reaches `El::on_drop_files` as paths. AppKit says where the drag is at every step, +//! so the host needn't sample the pointer. + +#![allow(unsafe_code)] + +use std::cell::RefCell; +use std::collections::HashMap; +use std::path::{Path, PathBuf}; +use std::sync::{Arc, Mutex}; +use objc2::rc::{Retained, autoreleasepool}; +use objc2::runtime::{AnyClass, AnyObject, Bool, ClassBuilder, Sel}; +use objc2::{class, msg_send, sel}; +use objc2_app_kit::{NSPasteboard, NSPasteboardItem, NSView}; +use objc2_foundation::{NSArray, NSDictionary, NSError, NSPoint, NSString, NSURL}; + +use crate::window::FileStep; + +#[derive(Default)] +struct Dest { + steps: Vec<FileStep>, + /// A drag this view takes is over it. + over: bool, +} + +thread_local! { + /// Each content view's steps since its host last took them, by the view's address. + static DESTS: RefCell<HashMap<usize, Dest>> = RefCell::default(); +} + +const FILE_URL: &str = "public.file-url"; +const PROMISED_TYPE: &str = "com.apple.pasteboard.promised-file-content-type"; +/// Image data a drop writes to a file, by pasteboard type, with the file's extension. TIFF, what +/// most Mac apps drag, is written as PNG. +const IMAGES: [(&str, &str); 6] = [ + ("public.png", "png"), ("public.jpeg", "jpg"), ("com.compuserve.gif", "gif"), + ("org.webmproject.webp", "webp"), ("public.heic", "heic"), ("public.tiff", "png"), +]; + +/// What one pasteboard item gives a drop. +#[derive(Debug, PartialEq)] +enum Item { + File(PathBuf), + /// A file the source writes when asked, with its type's extension when known. + Promise(Option<&'static str>), + /// Image data: its pasteboard type and file extension. + Image(&'static str, &'static str), +} + +impl Item { + /// The path a drag over the window reports: the file, else a stand-in named for its type, + /// which is all an `El::accepts_files` filter reads. + fn hover_path(&self) -> PathBuf { + match self { + Item::File(path) => path.clone(), + Item::Promise(ext) => PathBuf::from(ext.map_or("File".into(), |e| format!("File.{e}"))), + Item::Image(_, ext) => PathBuf::from(format!("Image.{ext}")), + } + } +} + +/// The content view of `window` takes drags of files, file promises and image data. +pub(crate) fn install(window: &winit::window::Window) { + let Some(view) = crate::platform::macos::content_view(window) else { return }; + // SAFETY: main thread (windows are created there), on winit's live content view. + unsafe { + let base = view.class(); + if !base.name().to_string_lossy().contains("RuneDrops_") { + let Ok(name) = std::ffi::CString::new(format!("RuneDrops_{}", base.name().to_string_lossy())) else { return }; + let class = match ClassBuilder::new(&name, base) { + Some(mut b) => { + b.add_method(sel!(draggingEntered:), entered as unsafe extern "C" fn(_, _, _) -> _); + b.add_method(sel!(draggingUpdated:), updated as unsafe extern "C" fn(_, _, _) -> _); + b.add_method(sel!(draggingExited:), exited as unsafe extern "C" fn(_, _, _)); + b.add_method(sel!(prepareForDragOperation:), prepare as unsafe extern "C" fn(_, _, _) -> _); + b.add_method(sel!(performDragOperation:), perform as unsafe extern "C" fn(_, _, _) -> _); + b.register() + } + None => match AnyClass::get(&name) { Some(c) => c, None => return }, + }; + // Only this instance's class changes, to a subclass without ivars. + AnyObject::set_class(&view, class); + } + view.registerForDraggedTypes(&NSArray::from_retained_slice(&registered_types())); + } +} + +/// The steps of drags over `window` since the last call. +pub(crate) fn take(window: &winit::window::Window) -> Vec<FileStep> { + let Some(view) = crate::platform::macos::content_view(window) else { return Vec::new() }; + let key = Retained::as_ptr(&view) as usize; + DESTS.with(|d| d.borrow_mut().get_mut(&key).map(|d| std::mem::take(&mut d.steps)).unwrap_or_default()) +} + +fn push(key: usize, step: FileStep) { + DESTS.with(|d| { + let mut d = d.borrow_mut(); + let dest = d.entry(key).or_default(); + // A move replaces the move before it: the host wants only the latest position. + if matches!(step, FileStep::Move(_)) && matches!(dest.steps.last(), Some(FileStep::Move(_))) { dest.steps.pop(); } + match step { + FileStep::Enter(..) | FileStep::Move(_) => dest.over = true, + FileStep::Drop(..) | FileStep::Leave => dest.over = false, + } + dest.steps.push(step); + }); +} + +fn over(key: usize) -> bool { DESTS.with(|d| d.borrow().get(&key).is_some_and(|d| d.over)) } + +fn registered_types() -> Vec<Retained<NSString>> { + let mut types: Vec<Retained<NSString>> = [FILE_URL, "NSFilenamesPboardType"].into_iter() + .chain(IMAGES.iter().map(|(t, _)| *t)).map(NSString::from_str).collect(); + types.extend(promise_types()); + types +} + +/// The types a file promise's item carries, new (`NSFilePromiseProvider`) and old. +fn promise_types() -> Vec<Retained<NSString>> { + // SAFETY: a class method returning an array of strings. + unsafe { + let types: Retained<NSArray<NSString>> = msg_send![class!(NSFilePromiseReceiver), readableDraggedTypes]; + types.to_vec() + } +} + +/// The operation a drag gets: copy, else what the source calls generic, else none (a Rune +/// window's own drag-out offers nothing to the app). +fn operation(mask: usize) -> usize { + const COPY: usize = 1; + const GENERIC: usize = 4; + if mask & COPY != 0 { COPY } else if mask & GENERIC != 0 { GENERIC } else { 0 } +} + +/// What each item of `pb` gives a drop, in order. An item that gives nothing is left out. +unsafe fn items(pb: &NSPasteboard) -> Vec<(Retained<NSPasteboardItem>, Item)> { + let promises: Vec<String> = promise_types().iter().map(|t| t.to_string()).collect(); + let Some(list) = pb.pasteboardItems() else { return Vec::new() }; + list.to_vec().into_iter().filter_map(|item| { + let types: Vec<String> = item.types().iter().map(|t| t.to_string()).collect(); + let has = |t: &str| types.iter().any(|x| x == t); + let found = if has(FILE_URL) { + let url = item.stringForType(&NSString::from_str(FILE_URL))?; + file_path(&url).map(Item::File) + } else if types.iter().any(|t| promises.contains(t)) { + let uti = item.stringForType(&NSString::from_str(PROMISED_TYPE)).map(|s| s.to_string()); + Some(Item::Promise(uti.as_deref().and_then(extension))) + } else { + IMAGES.iter().find(|(t, _)| has(t)).map(|&(t, ext)| Item::Image(t, ext)) + }; + found.map(|f| (item, f)) + }).collect() +} + +/// The path of a `file://` URL, resolving the file-reference form (`file:///.file/id=…`). +pub(crate) fn file_path(url: &NSString) -> Option<PathBuf> { + let url = NSURL::URLWithString(url)?; + let url = url.filePathURL()?; + Some(PathBuf::from(url.path()?.to_string())) +} + +/// A file extension for a few common types a promise names. +fn extension(uti: &str) -> Option<&'static str> { + Some(match uti { + "public.png" => "png", + "public.jpeg" => "jpg", + "public.tiff" => "tiff", + "public.heic" => "heic", + "com.compuserve.gif" => "gif", + "org.webmproject.webp" => "webp", + "com.adobe.pdf" => "pdf", + "public.plain-text" | "public.utf8-plain-text" => "txt", + "com.apple.quicktime-movie" => "mov", + "public.mpeg-4" => "mp4", + _ => return None, + }) +} + +/// A new folder for one drop's files under the system's temporary folder. +fn drop_dir() -> Option<PathBuf> { + static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + let n = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + let stamp = crate::time::system_now().duration_since(std::time::UNIX_EPOCH).map_or(0, |d| d.as_millis()); + let dir = std::env::temp_dir().join("rune-drops").join(format!("{}-{stamp}-{n}", std::process::id())); + std::fs::create_dir_all(&dir).ok().map(|_| dir) +} + +/// `stem.ext` in `dir`, numbered when the name is taken. +fn free_name(dir: &Path, stem: &str, ext: &str) -> PathBuf { + (1..).map(|i| dir.join(if i == 1 { format!("{stem}.{ext}") } else { format!("{stem} {i}.{ext}") })) + .find(|p| !p.exists()).unwrap_or_else(|| dir.join(format!("{stem}.{ext}"))) +} + +/// The name an image takes from the URL it came from, if the item has one (a browser's image). +fn image_stem(item: &NSPasteboardItem) -> String { + let url = item.stringForType(&NSString::from_str("public.url")).map(|u| u.to_string()); + url.as_deref().and_then(url_stem).unwrap_or_else(|| "Image".into()) +} + +fn url_stem(url: &str) -> Option<String> { + let (_, rest) = url.split_once("://")?; + let (_, path) = rest.split(['?', '#']).next()?.split_once('/')?; + let last = path.trim_end_matches('/').rsplit('/').next()?; + let stem = last.rsplit_once('.').map_or(last, |(s, _)| s); + let stem: String = stem.chars().filter(|c| !matches!(c, ':' | '\\' | '\0')).take(80).collect(); + (!stem.is_empty() && !stem.starts_with('.')).then_some(stem) +} + +/// Writes an item's image to `dir`, as PNG when it's TIFF. +unsafe fn write_image(item: &NSPasteboardItem, kind: &str, ext: &str, dir: &Path) -> Option<PathBuf> { + let data = item.dataForType(&NSString::from_str(kind))?; + // SAFETY: `data` is retained for the duration of this function and is not mutated while borrowed. + let bytes = unsafe { data.as_bytes_unchecked() }; + let png; + let bytes = if kind == "public.tiff" { + png = crate::clipboard::tiff_to_png(bytes)?; + png.png() + } else { bytes }; + let path = free_name(dir, &image_stem(item), ext); + std::fs::write(&path, bytes).ok().map(|_| path) +} + +/// The drag's position in `view`, in points from its top-left. +unsafe fn location(view: &NSView, info: &AnyObject) -> (f32, f32) { + // SAFETY: `info` is a live `NSDraggingInfo` from AppKit on the main thread; `-draggingLocation` returns `NSPoint`. + let p: NSPoint = unsafe { msg_send![info, draggingLocation] }; + let p = view.convertPoint_fromView(p, None); + let y = if view.isFlipped() { p.y } else { view.bounds().size.height - p.y }; + (p.x as f32, y as f32) +} + +fn key(view: &AnyObject) -> usize { view as *const AnyObject as usize } + +unsafe fn view(this: &AnyObject) -> &NSView { + // SAFETY: these methods are only on the content view's subclass. + unsafe { &*(this as *const AnyObject).cast::<NSView>() } +} + +unsafe fn pasteboard(info: &AnyObject) -> Retained<NSPasteboard> { + // SAFETY: `info` is a live `NSDraggingInfo` from AppKit on the main thread; `-draggingPasteboard` returns a non-null `NSPasteboard`. + unsafe { msg_send![info, draggingPasteboard] } +} + +/// A drag entered or moved: Enter when it starts to be taken, then Move. +unsafe fn update(this: &AnyObject, info: &AnyObject) -> usize { + autoreleasepool(|_| { + // SAFETY: called on the main thread from AppKit drag destination callbacks; `this` is this + // subclassed `NSView`, `info` is a live `NSDraggingInfo`, and the selectors match `NSDraggingInfo`. + unsafe { + let key = key(this); + let mask: usize = msg_send![info, draggingSourceOperationMask]; + let op = operation(mask); + let at = location(view(this), info); + if op == 0 { + if over(key) { push(key, FileStep::Leave); } + return 0; + } + if over(key) { + push(key, FileStep::Move(at)); + return op; + } + let paths: Vec<PathBuf> = items(&pasteboard(info)).iter().map(|(_, item)| item.hover_path()).collect(); + if paths.is_empty() { return 0; } + push(key, FileStep::Enter(paths, Some(at))); + op + } + }) +} + +unsafe extern "C" fn entered(this: &AnyObject, _: Sel, info: &AnyObject) -> usize { + // SAFETY: AppKit invokes `-draggingEntered:` on the main thread with this subclassed `NSView` and a live `NSDraggingInfo`. + unsafe { update(this, info) } +} + +unsafe extern "C" fn updated(this: &AnyObject, _: Sel, info: &AnyObject) -> usize { + // SAFETY: AppKit invokes `-draggingUpdated:` on the main thread with this subclassed `NSView` and a live `NSDraggingInfo`. + unsafe { update(this, info) } +} + +unsafe extern "C" fn exited(this: &AnyObject, _: Sel, _info: *mut AnyObject) { + if over(key(this)) { push(key(this), FileStep::Leave); } +} + +unsafe extern "C" fn prepare(this: &AnyObject, _: Sel, _info: &AnyObject) -> Bool { Bool::new(over(key(this))) } + +/// The drop: files at once, image data once written, and file promises once their sources +/// have written them, all in one `FileStep::Drop`. +unsafe extern "C" fn perform(this: &AnyObject, _: Sel, info: &AnyObject) -> Bool { + let key = key(this); + autoreleasepool(|_| { + // SAFETY: AppKit invokes `-performDragOperation:` on the main thread with this subclassed + // `NSView` and a live `NSDraggingInfo`. + unsafe { + let at = location(view(this), info); + let pb = pasteboard(info); + let items = items(&pb); + let mut dir = None; + let mut paths = Vec::new(); + let mut promised = false; + for (item, found) in &items { + match found { + Item::File(path) => paths.push(path.clone()), + Item::Image(kind, ext) => { + if dir.is_none() { dir = drop_dir(); } + if let Some(path) = dir.as_deref().and_then(|d| write_image(item, kind, ext, d)) { paths.push(path); } + } + Item::Promise(_) => promised = true, + } + } + if promised && let Some(dir) = dir.or_else(drop_dir) && receive(key, &pb, &dir, paths.clone(), at) { + return Bool::YES; + } + if paths.is_empty() { + push(key, FileStep::Leave); + return Bool::NO; + } + push(key, FileStep::Drop(paths, Some(at))); + Bool::YES + } + }) +} + +/// Asks each promise's source to write its files into `dir`. Once all have answered, `paths` +/// and the promised files drop at `at`. +unsafe fn receive(key: usize, pb: &NSPasteboard, dir: &Path, paths: Vec<PathBuf>, at: (f32, f32)) -> bool { + // SAFETY: called on the main thread with a live `NSPasteboard`; Objective-C selectors match + // `NSPasteboard`/`NSFilePromiseReceiver`/`NSOperationQueue`, `keep` retains each receiver + // until its reader block finishes (where AppKit passes a live `NSURL` when `error` is null), + // and `deliver` hops back to `mainQueue` before touching thread-local state. + unsafe { + let classes = NSArray::from_retained_slice(&[Retained::<AnyObject>::retain(class!(NSFilePromiseReceiver) as *const AnyClass as *mut AnyObject).unwrap()]); + let Some(receivers): Option<Retained<NSArray<AnyObject>>> = msg_send![pb, readObjectsForClasses: &*classes, options: &*NSDictionary::<NSString, AnyObject>::new()] + else { return false }; + let receivers = receivers.to_vec(); + let files: usize = receivers.iter().map(|r| { + let types: Retained<NSArray<NSString>> = msg_send![r, fileTypes]; + types.count().max(1) + }).sum(); + if files == 0 { return false; } + // The sources write off the main thread; the drop is queued back on it. + let queue: Retained<AnyObject> = msg_send![class!(NSOperationQueue), new]; + let pending = Arc::new(Mutex::new((files, paths))); + let destination = NSURL::fileURLWithPath_isDirectory(&NSString::from_str(&dir.to_string_lossy()), true); + for receiver in &receivers { + let pending = pending.clone(); + // The receiver lives until its files are in. + let keep = receiver.clone(); + let reader = block2::RcBlock::new(move |url: *mut NSURL, error: *mut NSError| { + let _ = &keep; + let path = if error.is_null() { url.as_ref().and_then(|u| u.path()).map(|p| PathBuf::from(p.to_string())) } else { None }; + let mut p = pending.lock().unwrap_or_else(|e| e.into_inner()); + p.0 = p.0.saturating_sub(1); + p.1.extend(path); + if p.0 > 0 { return; } + let paths = std::mem::take(&mut p.1); + drop(p); + let deliver = block2::RcBlock::new(move || { + if paths.is_empty() { push(key, FileStep::Leave) } else { push(key, FileStep::Drop(paths.clone(), Some(at))) } + }); + let main: Retained<AnyObject> = msg_send![class!(NSOperationQueue), mainQueue]; + let _: () = msg_send![&main, addOperationWithBlock: &*deliver]; + }); + let _: () = msg_send![receiver, receivePromisedFilesAtDestination: &*destination, options: &*NSDictionary::<NSString, AnyObject>::new(), + operationQueue: &*queue, reader: &*reader]; + } + true + } +} + +#[cfg(test)] +#[path = "drop_tests.rs"] +mod tests; diff --git a/app/vendor/rune/crates/rune/src/platform/macos/drop_tests.rs b/app/vendor/rune/crates/rune/src/platform/macos/drop_tests.rs new file mode 100644 index 0000000..33e3980 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/platform/macos/drop_tests.rs @@ -0,0 +1,189 @@ +#![allow(unsafe_code)] + +use super::*; +use objc2_foundation::NSData; + +/// Whether this session has a pasteboard server. A headless or SSH-only session (no window +/// server) has none, and `pasteboardWithUniqueName` returns nil there, so the round-trip +/// tests skip with a note instead of panicking. +fn pasteboard_available() -> bool { + static AVAILABLE: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + *AVAILABLE.get_or_init(|| { + let probe = std::panic::catch_unwind(|| { + // SAFETY: probes whether the session's pasteboard server accepts a temporary unique + // pasteboard and releases it before returning. + unsafe { + let pb: Option<Retained<NSPasteboard>> = msg_send![class!(NSPasteboard), pasteboardWithUniqueName]; + let Some(pb) = pb else { return false }; + pb.clearContents(); + let item = NSPasteboardItem::new(); + let kind = NSString::from_str("public.utf8-plain-text"); + let ok = item.setString_forType(&NSString::from_str("probe"), &kind) + && pb.writeObjects(&NSArray::from_retained_slice(&[objc2::runtime::ProtocolObject::from_retained(item)])) + && pb.stringForType(&kind).is_some_and(|s| s.to_string() == "probe"); + let () = msg_send![&*pb, releaseGlobally]; + ok + } + }); + let ok = probe.unwrap_or(false); + if !ok { eprintln!("macos_drop: no pasteboard in this session (headless?); skipping pasteboard round-trip tests"); } + ok + }) +} + +/// A private pasteboard, released when dropped. +struct Board(Retained<NSPasteboard>); + +impl Drop for Board { + fn drop(&mut self) { + // SAFETY: `self.0` is a private pasteboard created via `pasteboardWithUniqueName` and released once on drop. + unsafe { msg_send![&*self.0, releaseGlobally] } + } +} + +impl std::ops::Deref for Board { + type Target = NSPasteboard; + fn deref(&self) -> &NSPasteboard { &self.0 } +} + +/// A private pasteboard holding `items`, or None without a pasteboard. +fn board(items: &[&[(&str, &[u8])]]) -> Option<Board> { + if !pasteboard_available() { return None; } + let pb = Board(NSPasteboard::pasteboardWithUniqueName()); + pb.clearContents(); + let items: Vec<Retained<NSPasteboardItem>> = items.iter().map(|types| { + let item = NSPasteboardItem::new(); + for (t, data) in *types { item.setData_forType(&NSData::with_bytes(data), &NSString::from_str(t)); } + item + }).collect(); + let objects: Vec<Retained<objc2::runtime::ProtocolObject<dyn objc2_app_kit::NSPasteboardWriting>>> = + items.into_iter().map(|i| objc2::runtime::ProtocolObject::from_retained(i)).collect(); + assert!(pb.writeObjects(&NSArray::from_retained_slice(&objects))); + Some(pb) +} + +fn png() -> Vec<u8> { + let mut out = Vec::new(); + let mut e = png::Encoder::new(&mut out, 2, 1); + e.set_color(png::ColorType::Rgba); + e.write_header().unwrap().write_image_data(&[255, 0, 0, 255, 0, 255, 0, 255]).unwrap(); + out +} + +fn found(pb: &NSPasteboard) -> Vec<Item> { + // SAFETY: `pb` is a live `NSPasteboard` created by this test. + unsafe { items(pb) }.into_iter().map(|(_, i)| i).collect() +} + +#[test] +fn a_file_url_is_its_path() { + let Some(pb) = board(&[&[(FILE_URL, b"file:///tmp/notes%20one.txt")]]) else { return }; + assert_eq!(found(&pb), [Item::File("/tmp/notes one.txt".into())]); +} + +#[test] +fn image_data_without_a_file_is_an_image() { + let Some(pb) = board(&[&[("public.png", &png())], &[("public.url", b"https://e.com/a.png"), ("public.tiff", b"II*\0")]]) else { return }; + assert_eq!(found(&pb), [Item::Image("public.png", "png"), Item::Image("public.tiff", "png")]); +} + +#[test] +fn a_file_url_wins_over_the_image_beside_it() { + let Some(pb) = board(&[&[(FILE_URL, b"file:///tmp/a.png"), ("public.png", &png())]]) else { return }; + assert_eq!(found(&pb), [Item::File("/tmp/a.png".into())]); +} + +#[test] +fn a_promise_is_named_for_its_type() { + let Some(pb) = board(&[&[("com.apple.NSFilePromiseItemMetaData", b"x"), (PROMISED_TYPE, b"public.png")]]) else { return }; + assert_eq!(found(&pb), [Item::Promise(Some("png"))]); +} + +#[test] +fn hover_paths_stand_in_for_files_to_come() { + assert_eq!(Item::File("/tmp/a.txt".into()).hover_path(), PathBuf::from("/tmp/a.txt")); + assert_eq!(Item::Promise(Some("png")).hover_path(), PathBuf::from("File.png")); + assert_eq!(Item::Promise(None).hover_path(), PathBuf::from("File")); + assert_eq!(Item::Image("public.tiff", "png").hover_path(), PathBuf::from("Image.png")); +} + +#[test] +fn promised_types_map_to_extensions() { + assert_eq!(extension("public.jpeg"), Some("jpg")); + assert_eq!(extension("com.adobe.pdf"), Some("pdf")); + assert_eq!(extension("public.data"), None); +} + +#[test] +fn file_urls_resolve_to_paths() { + assert_eq!(file_path(&NSString::from_str("file:///tmp/notes%20one.txt")), Some(PathBuf::from("/tmp/notes one.txt"))); + assert_eq!(file_path(&NSString::from_str("https://e.com/a.png")), None); +} + +#[test] +fn taken_names_are_numbered() { + let dir = drop_dir().unwrap(); + assert_eq!(free_name(&dir, "Image", "png"), dir.join("Image.png")); + std::fs::write(dir.join("Image.png"), b"").unwrap(); + std::fs::write(dir.join("Image 2.png"), b"").unwrap(); + assert_eq!(free_name(&dir, "Image", "png"), dir.join("Image 3.png")); + std::fs::remove_dir_all(dir).unwrap(); +} + +#[test] +fn text_alone_gives_nothing() { + let Some(pb) = board(&[&[("public.utf8-plain-text", b"hello")], &[("public.url", b"https://e.com/")]]) else { return }; + assert!(found(&pb).is_empty()); +} + +#[test] +fn images_are_written_named_for_their_url() { + let Some(pb) = board(&[&[("public.png", &png())], &[("public.png", &png())], &[("public.url", b"https://e.com/img/kitten.jpg?w=2"), ("public.png", &png())]]) else { return }; + let dir = drop_dir().unwrap(); + // SAFETY: `pb` is a live `NSPasteboard` created by this test. + let entries = unsafe { items(&pb) }; + let paths: Vec<PathBuf> = entries.iter().filter_map(|(item, f)| match f { + Item::Image(k, e) => { + // SAFETY: `item` is a live `NSPasteboardItem` returned from `items(&pb)`. + unsafe { write_image(item, k, e, &dir) } + } + _ => None, + }).collect(); + let names: Vec<_> = paths.iter().map(|p| p.file_name().unwrap().to_string_lossy().into_owned()).collect(); + assert_eq!(names, ["Image.png", "Image 2.png", "kitten.png"]); + assert_eq!(std::fs::read(&paths[0]).unwrap(), png()); + std::fs::remove_dir_all(dir).unwrap(); +} + +#[test] +fn url_stems() { + assert_eq!(url_stem("https://e.com/a/cat.photo.png?x=1").as_deref(), Some("cat.photo")); + assert_eq!(url_stem("https://e.com/"), None); + assert_eq!(url_stem("https://e.com"), None); + assert_eq!(url_stem("data:image/png;base64,AAAA"), None); +} + +#[test] +fn the_operation_follows_the_source() { + assert_eq!(operation(1 | 2 | 16), 1); + assert_eq!(operation(4), 4); + assert_eq!(operation(0), 0); + assert_eq!(operation(2), 0); +} + +#[test] +fn moves_coalesce_and_steps_track_the_drag() { + let key = 0xd0d0; + push(key, FileStep::Enter(vec!["a".into()], Some((1.0, 1.0)))); + push(key, FileStep::Move((2.0, 2.0))); + push(key, FileStep::Move((3.0, 3.0))); + assert!(over(key)); + push(key, FileStep::Drop(vec!["a".into()], Some((3.0, 3.0)))); + assert!(!over(key)); + let steps = DESTS.with(|d| std::mem::take(&mut d.borrow_mut().get_mut(&key).unwrap().steps)); + assert_eq!(steps, [ + FileStep::Enter(vec!["a".into()], Some((1.0, 1.0))), + FileStep::Move((3.0, 3.0)), + FileStep::Drop(vec!["a".into()], Some((3.0, 3.0))), + ]); +} diff --git a/app/vendor/rune/crates/rune/src/platform/macos/geometry.rs b/app/vendor/rune/crates/rune/src/platform/macos/geometry.rs new file mode 100644 index 0000000..5de4457 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/platform/macos/geometry.rs @@ -0,0 +1,154 @@ +//! Display selection and window geometry in AppKit and Rune coordinates. + +use crate::{DisplayTarget, OverlayOptions}; +use objc2::{MainThreadMarker, msg_send}; +use objc2_app_kit::{NSEvent, NSScreen}; +use objc2_foundation::{NSPoint, NSRect, NSSize}; +use super::ns_window; + +#[link(name = "CoreGraphics", kind = "framework")] +#[allow(unsafe_code)] +unsafe extern "C" { fn CGDisplayBounds(display: u32) -> NSRect; } + +/// CoreGraphics queries are thread-safe; snapshot the display before queuing a UI request. +#[allow(unsafe_code)] +pub(crate) fn pointer_display() -> Option<u32> { + #[link(name = "CoreGraphics", kind = "framework")] + unsafe extern "C" { + fn CGEventCreate(source: *const std::ffi::c_void) -> *const std::ffi::c_void; + fn CGEventGetLocation(event: *const std::ffi::c_void) -> NSPoint; + fn CGGetDisplaysWithPoint(point: NSPoint, max: u32, displays: *mut u32, count: *mut u32) -> i32; + } + #[link(name = "CoreFoundation", kind = "framework")] + unsafe extern "C" { fn CFRelease(object: *const std::ffi::c_void); } + // SAFETY: the created event is released exactly once; output buffers live through the call. + unsafe { + let event = CGEventCreate(std::ptr::null()); + if event.is_null() { return None; } + let point = CGEventGetLocation(event); + CFRelease(event); + let (mut id, mut count) = (0, 0); + (CGGetDisplaysWithPoint(point, 1, &mut id, &mut count) == 0 && count > 0).then_some(id) + } +} + +pub(crate) fn place_window(window: &winit::window::Window, size: (f32, f32), request: &crate::windows::PlaceRequest) { + let options = OverlayOptions { display: request.display.clone(), placement: Some(request.placement), ..Default::default() }; + if let (Some(window), Some(rect)) = (ns_window(window), overlay_rect(crate::windows::PlaceRequest::at(size), &options)) + && window.frame() != rect { + window.setFrame_display(rect, true); + } +} + +/// A window's outer frame, the visible area of its screen and its backing scale, in +/// top-down global points (AppKit's are bottom-up from the primary screen). +pub(crate) fn window_geometry(window: &winit::window::Window) -> Option<([f32; 4], [f32; 4], f32)> { + let mtm = MainThreadMarker::new()?; + let ns = ns_window(window)?; + let screens = NSScreen::screens(mtm); + let primary = screens.iter().next()?.frame().size.height; + let screen = ns.screen().or_else(|| NSScreen::mainScreen(mtm))?; + let flip = |r: NSRect| [r.origin.x as f32, (primary - r.origin.y - r.size.height) as f32, r.size.width as f32, r.size.height as f32]; + Some((flip(ns.frame()), flip(screen.visibleFrame()), ns.backingScaleFactor() as f32)) +} + +/// A window's content top-left in top-down global points: the panel's once one adopts it. +pub(crate) fn content_origin(window: &winit::window::Window) -> Option<(f32, f32)> { + let mtm = MainThreadMarker::new()?; + let ns = ns_window(window)?; + let primary = NSScreen::screens(mtm).iter().next()?.frame().size.height; + let r = ns.contentRectForFrameRect(ns.frame()); + Some((r.origin.x as f32, (primary - r.origin.y - r.size.height) as f32)) +} + +/// The backing scale `window` draws at: its screen's while it's on one, else that of the screen +/// holding most of its frame, where ordering it in will put it. +pub(crate) fn backing_scale(window: &winit::window::Window) -> Option<f32> { + let mtm = MainThreadMarker::new()?; + let ns = ns_window(window)?; + if ns.isVisible() { return Some(ns.backingScaleFactor() as f32); } + let f = ns.frame(); + let screens: Vec<_> = NSScreen::screens(mtm).iter().map(|s| { + let r = s.frame(); + ([r.origin.x, r.origin.y, r.size.width, r.size.height], s.backingScaleFactor()) + }).collect(); + let scale = crate::overlay::options::scale_under([f.origin.x, f.origin.y, f.size.width, f.size.height], &screens); + Some(scale.unwrap_or_else(|| ns.backingScaleFactor()) as f32) +} + +/// The outer size of a window whose content is `content` points. +pub(crate) fn outer_size(window: &winit::window::Window, (w, h): (f32, f32)) -> Option<(f32, f32)> { + let ns = ns_window(window)?; + let frame = ns.frameRectForContentRect(NSRect::new(NSPoint::new(0.0, 0.0), NSSize::new(f64::from(w), f64::from(h)))); + Some((frame.size.width as f32, frame.size.height as f32)) +} + +/// Moves a window's outer frame to `rect` (top-down global points) without drawing: the +/// caller draws its content at the new size in the same frame. +pub(crate) fn set_window_frame(window: &winit::window::Window, [x, y, w, h]: [f32; 4]) { + let (Some(mtm), Some(ns)) = (MainThreadMarker::new(), ns_window(window)) else { return }; + let Some(primary) = NSScreen::screens(mtm).iter().next().map(|s| s.frame().size.height) else { return }; + let rect = NSRect::new(NSPoint::new(f64::from(x), primary - f64::from(y) - f64::from(h)), NSSize::new(f64::from(w), f64::from(h))); + if ns.frame() != rect { ns.setFrame_display(rect, false); } +} + +#[allow(unsafe_code)] +pub(crate) fn display_bounds(id: u32) -> [f64; 4] { + // SAFETY: `CGDisplayBounds` is a pure CoreGraphics query accepting any `CGDirectDisplayID` (zero rect if invalid). + let r = unsafe { CGDisplayBounds(id) }; + [r.origin.x, r.origin.y, r.size.width, r.size.height] +} + +pub(crate) fn overlay_rect(at: crate::overlay::Placement, options: &OverlayOptions) -> Option<NSRect> { + overlay_rect_on(at, options, None) +} + +#[allow(unsafe_code)] +pub(super) fn screen_id(screen: &NSScreen) -> u32 { + // SAFETY: `screen` is a live `NSScreen` on the main thread; `deviceDescription` returns an `NSDictionary`, + // and messaging a possibly-nil `NSNumber` with `unsignedIntValue` returns 0 in ObjC. + unsafe { + let description: *mut objc2::runtime::AnyObject = msg_send![screen, deviceDescription]; + let key = objc2_foundation::NSString::from_str("NSScreenNumber"); + let number: *mut objc2::runtime::AnyObject = msg_send![description, objectForKey: &*key]; + msg_send![number, unsignedIntValue] + } +} + +pub(super) fn contains_pointer(screen: &NSScreen, pointer: NSPoint) -> bool { + contains_appkit_rect(screen.frame(), pointer) +} + +fn contains_appkit_rect(r: NSRect, pointer: NSPoint) -> bool { + pointer.x >= r.origin.x && pointer.x < r.origin.x + r.size.width + && pointer.y > r.origin.y && pointer.y <= r.origin.y + r.size.height +} + +pub(super) fn overlay_rect_on(at: crate::overlay::Placement, options: &OverlayOptions, previous: Option<u32>) -> Option<NSRect> { + use winit::platform::macos::MonitorHandleExtMacOS; + let mtm = MainThreadMarker::new()?; + let screens = NSScreen::screens(mtm); + let pointer = NSEvent::mouseLocation(); + let screen = screens.iter().find(|screen| match &options.display { + DisplayTarget::UnderPointer => { + contains_pointer(screen, pointer) + } + DisplayTarget::Id(_) | DisplayTarget::Native(_) => { + let native = screen_id(screen); + match options.display { + DisplayTarget::Id(ref id) => native == id.0.native_id(), + DisplayTarget::Native(crate::NativeDisplayId::MacOS(id)) => native == id, + _ => false, + } + }, + DisplayTarget::Primary => false, + }).or_else(|| screens.iter().find(|s| options.display == DisplayTarget::UnderPointer && previous == Some(screen_id(s)))) + .or_else(|| screens.iter().next())?; + let frame = screen.frame(); + let [x, y, w, h] = crate::overlay::options::local_rect(at, options.placement, (frame.size.width as f32, frame.size.height as f32)); + Some(NSRect::new(NSPoint::new(frame.origin.x + x as f64, frame.origin.y + frame.size.height - (y + h) as f64), NSSize::new(w as f64, h as f64))) +} + +#[cfg(test)] +#[path = "geometry_tests.rs"] +mod tests; diff --git a/app/vendor/rune/crates/rune/src/platform/macos/geometry_tests.rs b/app/vendor/rune/crates/rune/src/platform/macos/geometry_tests.rs new file mode 100644 index 0000000..9b3ea3d --- /dev/null +++ b/app/vendor/rune/crates/rune/src/platform/macos/geometry_tests.rs @@ -0,0 +1,11 @@ +use super::*; + +#[test] +fn overlay_appkit_top_row_belongs_to_secondary_display() { + let secondary = NSRect::new(NSPoint::new(-1920.0, 0.0), NSSize::new(1920.0, 1080.0)); + assert!(contains_appkit_rect(secondary, NSPoint::new(-100.0, 1080.0))); + assert!(!contains_appkit_rect(secondary, NSPoint::new(-100.0, 0.0))); + assert!(!contains_appkit_rect(secondary, NSPoint::new(0.0, 500.0))); + let below = NSRect::new(NSPoint::new(-1920.0, -1080.0), NSSize::new(1920.0, 1080.0)); + assert!(contains_appkit_rect(below, NSPoint::new(-100.0, 0.0))); +} diff --git a/app/vendor/rune/crates/rune/src/platform/macos/help.rs b/app/vendor/rune/crates/rune/src/platform/macos/help.rs new file mode 100644 index 0000000..7aa54b8 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/platform/macos/help.rs @@ -0,0 +1,106 @@ +//! `El::help` as AppKit's own tooltips. Each help element's visible rect is a tooltip rect on +//! winit's (flipped, point-sized) content view, so AppKit owns the delay, look, placement and +//! hiding, as for SwiftUI's `.help`. Rects are snapped to device pixels and synced one by one: +//! only a region that moved or changed text is removed and added again, so scrolling a list +//! doesn't restart a still toolbar button's tooltip. A tooltip's owner is its text: AppKit +//! shows the owner's `description` when it doesn't answer +//! `view:stringForToolTip:point:userData:`, and an `NSString` describes itself. +use objc2::msg_send; +use objc2::rc::Retained; +use objc2_app_kit::NSView; +use objc2_foundation::{NSPoint, NSRect, NSSize, NSString}; + +struct Region { + rect: [f32; 4], + text: String, + tag: isize, + /// AppKit doesn't retain tooltip owners: each lives here until its rect is removed. + _owner: Retained<NSString>, +} + +#[derive(Default)] +pub(crate) struct NativeHelp { + regions: Vec<Region>, + view: Option<Retained<NSView>>, +} + +/// `r` (window points, x0 y0 x1 y1) on the device pixel grid at `scale`. +fn snap(r: [f32; 4], scale: f32) -> [f32; 4] { + r.map(|v| (v * scale).round() / scale) +} + +/// Which registered regions `have` stay (true) and which wanted regions `want` they already +/// cover (true); the rest of `have` is removed and the rest of `want` added. +fn diff(have: &[([f32; 4], &str)], want: &[([f32; 4], &str)]) -> (Vec<bool>, Vec<bool>) { + let mut covered = vec![false; want.len()]; + let stays = have.iter().map(|h| { + let k = want.iter().enumerate().position(|(k, w)| !covered[k] && w == h); + if let Some(k) = k { covered[k] = true; } + k.is_some() + }).collect(); + (stays, covered) +} + +impl NativeHelp { + /// Registers `regions` (window points, x0 y0 x1 y1) with `window`'s content view, adding and + /// removing only the ones that changed since the last sync. Main thread. + #[allow(unsafe_code)] + pub(crate) fn sync(&mut self, window: &winit::window::Window, regions: &[([f32; 4], String)]) { + let scale = window.scale_factor() as f32; + let want: Vec<([f32; 4], &str)> = regions.iter() + .map(|(r, t)| (snap(*r, scale), t.as_str())) + .filter(|(r, _)| r[2] > r[0] && r[3] > r[1]) + .collect(); + let have: Vec<([f32; 4], &str)> = self.regions.iter().map(|g| (g.rect, g.text.as_str())).collect(); + let (stays, covered) = diff(&have, &want); + if stays.iter().all(|&s| s) && covered.iter().all(|&c| c) { return; } + let Some(view) = crate::platform::macos::content_view(window) else { return }; + let (kept, gone): (Vec<_>, Vec<_>) = std::mem::take(&mut self.regions).into_iter().zip(stays).partition(|(_, s)| *s); + for (g, _) in gone { + // SAFETY: an AppKit call on the main thread, before `g` drops the owner its tag names. + unsafe { let _: () = msg_send![&view, removeToolTip: g.tag]; } + } + self.regions = kept.into_iter().map(|(g, _)| g).collect(); + for (k, (r, text)) in want.iter().enumerate() { + if covered[k] { continue; } + let owner = NSString::from_str(text); + let rect = NSRect::new(NSPoint::new(r[0] as f64, r[1] as f64), NSSize::new((r[2] - r[0]) as f64, (r[3] - r[1]) as f64)); + // SAFETY: an AppKit call on the main thread; `regions` keeps the owner alive until + // its tag is removed. + let tag: isize = unsafe { msg_send![&view, addToolTipRect: rect, owner: &*owner, userData: std::ptr::null_mut::<std::ffi::c_void>()] }; + self.regions.push(Region { rect: *r, text: (*text).to_owned(), tag, _owner: owner }); + } + self.view = Some(view); + } + + #[allow(unsafe_code)] + fn clear(&mut self) { + if let Some(view) = self.view.take() { + // SAFETY: an AppKit call on the main thread, before the owners it names drop. + unsafe { let _: () = msg_send![&view, removeAllToolTips]; } + } + self.regions.clear(); + } +} + +impl Drop for NativeHelp { + fn drop(&mut self) { self.clear(); } +} + +#[cfg(test)] +mod tests { + use super::{diff, snap}; + + #[test] + fn only_changed_regions_are_replaced() { + let toolbar = ([10.0, 4.0, 30.0, 24.0], "Copy"); + let row = |y: f32| ([0.0, y, 200.0, y + 20.0], "Open"); + // A list scrolled under a still toolbar button: the button's tooltip stays registered. + let (stays, covered) = diff(&[toolbar, row(40.0)], &[toolbar, row(30.0)]); + assert_eq!((stays, covered), (vec![true, false], vec![true, false])); + // Two identical regions each keep one registration. + let (stays, covered) = diff(&[toolbar, toolbar], &[toolbar]); + assert_eq!((stays, covered), (vec![true, false], vec![true])); + assert_eq!(snap([10.3, 4.74, 30.0, 24.2], 2.0), [10.5, 4.5, 30.0, 24.0], "rects snap to device pixels"); + } +} diff --git a/app/vendor/rune/crates/rune/src/platform/macos/hold.rs b/app/vendor/rune/crates/rune/src/platform/macos/hold.rs new file mode 100644 index 0000000..9d4f605 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/platform/macos/hold.rs @@ -0,0 +1,241 @@ +//! The press an overlay's panel holds: from the local monitor seeing a Down until the runtime +//! has its Up. While held, the panel keeps taking mouse events, even off its hit area, so the +//! release reaches it. +//! +//! The monitor sees a click before winit dispatches it, so the seen clicks wait in a queue, and +//! another Down can already be queued when the runtime hears the Up before it. A release can also +//! be lost: the button reads up and winit never dispatches an Up. `Releasing` waits out a grace +//! for one, then gives up and asks the runtime to end the press ([`Effect::ReleaseLost`]). + +use std::{collections::VecDeque, time::{Duration, Instant}}; +use crate::machine::Effects; + +pub(super) type Point = (f32, f32); + +/// How long an Up the monitor saw may wait: winit dispatches one within the turn, so one still +/// queued this much later was never delivered (the panel lost its view). +const QUEUED_UP_GRACE: Duration = Duration::from_secs(2); +/// How long the button may read up with no Up seen at all. +const UNSEEN_UP_GRACE: Duration = Duration::from_millis(100); + +#[derive(Clone, Copy, Debug, PartialEq)] +pub(super) struct Click { + pub(super) down: bool, + pub(super) at: Point, + /// On a Down: the point where the press before it lost its release, to end that press first. + pub(super) ends: Option<Point>, +} + +impl Click { + fn up(at: Point) -> Self { Self { down: false, at, ends: None } } +} + +#[derive(Clone, Debug, PartialEq)] +pub(super) enum Hold { + /// No press is held. `ups` are releases still to dispatch, of presses the monitor never saw. + Free { ups: VecDeque<Point> }, + /// A press is held, the button down or its Up still on the way. `at` is the newest press's + /// Down, then where the button was last read down. + Pressed { clicks: VecDeque<Click>, at: Point }, + /// The button read up at `at` and `since`, and the runtime hasn't had the Up. + Releasing { clicks: VecDeque<Click>, since: Instant, at: Point }, + /// The button read up at `at`, then down again before any click was seen: the next Down's + /// event may be on its way. + Rebound { clicks: VecDeque<Click>, at: Point }, +} + +impl Default for Hold { + fn default() -> Self { Self::Free { ups: VecDeque::new() } } +} + +impl Hold { + pub(super) fn captured(&self) -> bool { !matches!(self, Self::Free { .. }) } + + /// When a lost release gives up, for the event loop to sample the pointer then even if + /// nothing else moves. + pub(super) fn deadline(&self) -> Option<Instant> { + let Self::Releasing { clicks, since, .. } = self else { return None }; + let queued_up = clicks.iter().any(|click| !click.down); + Some(*since + if queued_up { QUEUED_UP_GRACE } else { UNSEEN_UP_GRACE }) + } + + pub(super) fn into_clicks(self) -> VecDeque<Click> { + match self { + Self::Free { ups } => ups.into_iter().map(Click::up).collect(), + Self::Pressed { clicks, .. } | Self::Releasing { clicks, .. } | Self::Rebound { clicks, .. } => clicks, + } + } + + fn queued_down(&self) -> bool { + match self { + Self::Free { .. } => false, + Self::Pressed { clicks, .. } | Self::Releasing { clicks, .. } | Self::Rebound { clicks, .. } => clicks.iter().any(|click| click.down), + } + } + + /// Whether a sampled position is newer than the press the runtime holds: the button has + /// risen since, or a click is still on its way to it. + pub(super) fn ahead_of_clicks(&self) -> bool { + match self { + Self::Free { .. } => false, + Self::Releasing { .. } | Self::Rebound { .. } => true, + Self::Pressed { clicks, .. } => !clicks.is_empty(), + } + } + + /// Whether any click the monitor saw is still waiting for winit. + pub(super) fn queued(&self) -> bool { + match self { + Self::Free { ups, .. } => !ups.is_empty(), + Self::Pressed { clicks, .. } | Self::Releasing { clicks, .. } | Self::Rebound { clicks, .. } => !clicks.is_empty(), + } + } + + /// Whether the button is known to be up for the press the runtime holds: a sample read it + /// rise, or the monitor saw an Up that winit hasn't delivered yet. + pub(super) fn button_up(&self) -> bool { + match self { + Self::Free { ups, .. } => !ups.is_empty(), + Self::Releasing { .. } | Self::Rebound { .. } => true, + Self::Pressed { clicks, .. } => clicks.front().is_some_and(|click| !click.down), + } + } + + /// Where the press the runtime holds let go, if that's known: its own queued Up, the point a + /// queued press carries for it, or where the button rose. + fn lost_point(&self) -> Option<Point> { + let (clicks, rose) = match self { + Self::Free { .. } => return None, + Self::Pressed { clicks, at } | Self::Releasing { clicks, at, .. } | Self::Rebound { clicks, at } => (clicks, *at), + }; + clicks.front().and_then(|click| if click.down { click.ends } else { Some(click.at) }).or(Some(rose)) + } + + /// Where the press before a new Down lost its release, if no Up is queued between them. + fn lost_before(&self) -> Option<Point> { + let (clicks, rose) = match self { + Self::Free { .. } => return None, + Self::Pressed { clicks, at } | Self::Releasing { clicks, at, .. } | Self::Rebound { clicks, at } => (clicks, *at), + }; + clicks.back().is_none_or(|click| click.down).then_some(rose) + } +} + +#[derive(Clone, Copy, Debug, PartialEq)] +pub(super) enum Event { + /// The local monitor saw a click; `over` is whether it fell on the hit area. + Seen { down: bool, at: Point, over: bool }, + /// winit dispatched a press (`down`) or a release. + Dispatched { down: bool }, + /// winit is about to report a position, which belongs to the click at the front of the queue. + Positioning, + /// The runtime has had the release, or a system drag took it. + Released, + /// A sample of the pointer and the primary button. + Sampled { button_down: bool, now: Instant, at: Point }, + /// winit's view was out of the panel, so the clicks seen meanwhile never reached it. + ViewLost { last: Option<Point> }, + /// The panel hid. + Stopped, +} + +#[derive(Clone, Copy, Debug, PartialEq)] +pub(super) enum Effect { + /// Where the click winit just dispatched happened. + Deliver(Point), + /// The press ended without an Up: the runtime should give it up at this point. + ReleaseLost(Point), +} + +pub(super) fn step(hold: &mut Hold, event: Event) -> Effects<Effect> { + match event { + Event::Seen { down, at, over } => { + match hold { + Hold::Free { .. } if !over => {} + Hold::Free { ups } if !down => ups.push_back(at), + Hold::Pressed { clicks, .. } | Hold::Releasing { clicks, .. } | Hold::Rebound { clicks, .. } if !down => clicks.push_back(Click::up(at)), + _ => { + let ends = hold.lost_before(); + let mut clicks = std::mem::take(hold).into_clicks(); + clicks.push_back(Click { down: true, at, ends }); + *hold = Hold::Pressed { clicks, at }; + } + } + Effects::none() + } + Event::Dispatched { down } => { + let click = match hold { + Hold::Free { ups } if !down => ups.pop_front().map(Click::up), + Hold::Pressed { clicks, .. } | Hold::Releasing { clicks, .. } | Hold::Rebound { clicks, .. } if clicks.front().is_some_and(|click| click.down == down) => + clicks.pop_front(), + _ => None, + }; + let Some(click) = click else { return Effects::none() }; + // The press before this one ends first, so this one can't replace it. + let mut effects = click.ends.map_or(Effects::none(), |at| Effects::one(Effect::ReleaseLost(at))); + effects.push(Effect::Deliver(click.at)); + effects + } + Event::Positioning => { + let ends = match hold { + Hold::Free { .. } => None, + Hold::Pressed { clicks, .. } | Hold::Releasing { clicks, .. } | Hold::Rebound { clicks, .. } => + clicks.front_mut().and_then(|click| click.ends.take()), + }; + ends.map_or(Effects::none(), |at| Effects::one(Effect::ReleaseLost(at))) + } + Event::Released => { + // Native callbacks can queue another Down before winit dispatches this Up, and + // what the button did since is that press's. + if !hold.queued_down() { + let clicks = std::mem::take(hold).into_clicks(); + *hold = Hold::Free { ups: clicks.into_iter().map(|click| click.at).collect() }; + } + Effects::none() + } + Event::Sampled { button_down, now, at } => sampled(hold, button_down, now, at), + Event::ViewLost { last } => { + let lost = hold.lost_point().or(last); + *hold = Hold::default(); + lost.map_or(Effects::none(), |at| Effects::one(Effect::ReleaseLost(at))) + } + Event::Stopped => { + *hold = Hold::default(); + Effects::none() + } + } +} + +fn sampled(hold: &mut Hold, button_down: bool, now: Instant, point: Point) -> Effects<Effect> { + let due = hold.deadline(); + match hold { + Hold::Free { .. } => Effects::none(), + Hold::Pressed { at, .. } if button_down => { + *at = point; + Effects::none() + } + Hold::Rebound { .. } if button_down => Effects::none(), + Hold::Pressed { clicks, .. } => { + *hold = Hold::Releasing { clicks: std::mem::take(clicks), since: now, at: point }; + Effects::none() + } + Hold::Rebound { clicks, at } => { + *hold = Hold::Releasing { clicks: std::mem::take(clicks), since: now, at: *at }; + Effects::none() + } + Hold::Releasing { clicks, at, .. } if button_down => { + *hold = Hold::Rebound { clicks: std::mem::take(clicks), at: *at }; + Effects::none() + } + Hold::Releasing { .. } => { + if due.is_some_and(|due| now < due) { return Effects::none(); } + let lost = hold.lost_point(); + *hold = Hold::default(); + lost.map_or(Effects::none(), |at| Effects::one(Effect::ReleaseLost(at))) + } + } +} + +#[cfg(test)] +#[path = "hold_tests.rs"] +mod tests; diff --git a/app/vendor/rune/crates/rune/src/platform/macos/hold_tests.rs b/app/vendor/rune/crates/rune/src/platform/macos/hold_tests.rs new file mode 100644 index 0000000..68b144e --- /dev/null +++ b/app/vendor/rune/crates/rune/src/platform/macos/hold_tests.rs @@ -0,0 +1,209 @@ +use super::*; + +const DOWN: Event = Event::Seen { down: true, at: (20.0, 20.0), over: true }; +const UP: Event = Event::Seen { down: false, at: (100.0, 100.0), over: true }; + +fn sample(button_down: bool, now: Instant, at: Point) -> Event { Event::Sampled { button_down, now, at } } + +fn effects(hold: &mut Hold, event: Event) -> Vec<Effect> { step(hold, event).into_iter().collect() } + +#[test] +fn a_lost_release_while_dragging_gives_the_press_up_once_where_the_button_rose() { + let mut hold = Hold::default(); + let now = crate::time::now(); + step(&mut hold, DOWN); + step(&mut hold, Event::Dispatched { down: true }); + assert!(step(&mut hold, sample(true, now, (40.0, 40.0))).is_empty(), "the drag is under way"); + assert!(matches!(hold, Hold::Pressed { .. })); + step(&mut hold, sample(false, now, (50.0, 50.0))); + assert!(matches!(hold, Hold::Releasing { .. })); + assert_eq!(hold.deadline(), Some(now + UNSEEN_UP_GRACE)); + assert!(step(&mut hold, sample(false, now + Duration::from_millis(99), (60.0, 60.0))).is_empty()); + assert!(hold.captured()); + assert_eq!(effects(&mut hold, sample(false, now + UNSEEN_UP_GRACE, (70.0, 70.0))), [Effect::ReleaseLost((50.0, 50.0))]); + assert_eq!(hold, Hold::default()); + assert_eq!(hold.deadline(), None); + assert!(step(&mut hold, sample(false, now + Duration::from_secs(1), (80.0, 80.0))).is_empty(), "lost once"); +} + +#[test] +fn a_quick_press_queued_before_the_release_reaches_the_runtime_stays_held() { + let mut hold = Hold::default(); + step(&mut hold, DOWN); + step(&mut hold, UP); + assert_eq!(effects(&mut hold, Event::Dispatched { down: true }), [Effect::Deliver((20.0, 20.0))]); + assert!(step(&mut hold, DOWN).is_empty(), "an Up is queued ahead of it, so nothing was lost"); + assert_eq!(effects(&mut hold, Event::Dispatched { down: false }), [Effect::Deliver((100.0, 100.0))]); + step(&mut hold, Event::Released); + assert!(hold.captured(), "the queued press owns the pointer"); + assert_eq!(effects(&mut hold, Event::Dispatched { down: true }), [Effect::Deliver((20.0, 20.0))]); + step(&mut hold, UP); + assert_eq!(effects(&mut hold, Event::Dispatched { down: false }), [Effect::Deliver((100.0, 100.0))]); + step(&mut hold, Event::Released); + assert_eq!(hold, Hold::default()); +} + +#[test] +fn two_queued_presses_with_no_up_between_end_the_first_between_them() { + let mut hold = Hold::default(); + let now = crate::time::now(); + step(&mut hold, DOWN); + step(&mut hold, sample(false, now, (50.0, 50.0))); + assert!(step(&mut hold, DOWN).is_empty()); + assert!(matches!(hold, Hold::Pressed { .. })); + assert_eq!(effects(&mut hold, Event::Dispatched { down: true }), [Effect::Deliver((20.0, 20.0))]); + assert_eq!(effects(&mut hold, Event::Dispatched { down: true }), [Effect::ReleaseLost((50.0, 50.0)), Effect::Deliver((20.0, 20.0))]); + step(&mut hold, UP); + assert_eq!(effects(&mut hold, Event::Dispatched { down: false }), [Effect::Deliver((100.0, 100.0))], "the second press ends normally"); + step(&mut hold, Event::Released); + assert_eq!(hold, Hold::default()); +} + +#[test] +fn a_press_that_beats_the_grace_ends_the_dispatched_press_where_the_button_rose() { + let mut hold = Hold::default(); + let now = crate::time::now(); + step(&mut hold, DOWN); + step(&mut hold, Event::Dispatched { down: true }); + step(&mut hold, sample(false, now, (50.0, 50.0))); + assert!(step(&mut hold, DOWN).is_empty()); + assert!(matches!(hold, Hold::Pressed { .. }), "the new press holds"); + assert_eq!(hold.deadline(), None); + assert_eq!(effects(&mut hold, Event::Dispatched { down: true }), [Effect::ReleaseLost((50.0, 50.0)), Effect::Deliver((20.0, 20.0))]); +} + +#[test] +fn a_sample_that_beats_the_next_press_keeps_the_release_point() { + let mut hold = Hold::default(); + let now = crate::time::now(); + step(&mut hold, DOWN); + step(&mut hold, Event::Dispatched { down: true }); + step(&mut hold, sample(false, now, (50.0, 50.0))); + assert!(step(&mut hold, sample(true, now, (55.0, 55.0))).is_empty()); // the sample beat the Down's event + assert_eq!(hold.deadline(), None, "the grace rests while the button reads down"); + step(&mut hold, DOWN); + assert_eq!(effects(&mut hold, Event::Dispatched { down: true }), [Effect::ReleaseLost((50.0, 50.0)), Effect::Deliver((20.0, 20.0))]); +} + +#[test] +fn a_rebounding_button_gives_up_where_it_first_rose_after_a_fresh_grace() { + let mut hold = Hold::default(); + let now = crate::time::now(); + step(&mut hold, DOWN); + step(&mut hold, Event::Dispatched { down: true }); + step(&mut hold, sample(false, now, (50.0, 50.0))); + step(&mut hold, sample(true, now, (55.0, 55.0))); + let later = now + Duration::from_secs(1); + step(&mut hold, sample(false, later, (60.0, 60.0))); + assert_eq!(hold.deadline(), Some(later + UNSEEN_UP_GRACE)); + assert_eq!(effects(&mut hold, sample(false, later + UNSEEN_UP_GRACE, (70.0, 70.0))), [Effect::ReleaseLost((50.0, 50.0))]); +} + +#[test] +fn acknowledging_an_older_up_keeps_the_queued_presss_release() { + let mut hold = Hold::default(); + let now = crate::time::now(); + step(&mut hold, DOWN); + step(&mut hold, Event::Dispatched { down: true }); + step(&mut hold, UP); + step(&mut hold, DOWN); + step(&mut hold, sample(false, now, (50.0, 50.0))); + step(&mut hold, Event::Dispatched { down: false }); + step(&mut hold, Event::Released); + step(&mut hold, sample(false, now, (70.0, 70.0))); + step(&mut hold, Event::Dispatched { down: true }); + assert_eq!(hold.deadline(), Some(now + UNSEEN_UP_GRACE), "the grace keeps running"); + assert_eq!(effects(&mut hold, sample(false, now + UNSEEN_UP_GRACE, (80.0, 80.0))), [Effect::ReleaseLost((50.0, 50.0))]); +} + +#[test] +fn a_position_ends_the_press_before_the_front_click_without_taking_it() { + let mut hold = Hold::default(); + step(&mut hold, DOWN); + step(&mut hold, Event::Seen { down: true, at: (30.0, 30.0), over: true }); + assert!(step(&mut hold, Event::Positioning).is_empty(), "the front press is the first: nothing before it to end"); + assert_eq!(effects(&mut hold, Event::Dispatched { down: true }), [Effect::Deliver((20.0, 20.0))]); + assert_eq!(effects(&mut hold, Event::Positioning), [Effect::ReleaseLost((20.0, 20.0))], "its own Down, never the new press's point"); + assert_eq!(effects(&mut hold, Event::Dispatched { down: true }), [Effect::Deliver((30.0, 30.0))], "landed once"); +} + +#[test] +fn with_no_rise_read_a_press_ends_where_it_was_last_read_down() { + let mut hold = Hold::default(); + let now = crate::time::now(); + step(&mut hold, sample(false, now, (5.0, 5.0))); // a hover older than the press + step(&mut hold, DOWN); + step(&mut hold, Event::Dispatched { down: true }); + step(&mut hold, sample(true, now, (25.0, 25.0))); + step(&mut hold, Event::Seen { down: true, at: (30.0, 30.0), over: true }); + assert_eq!(effects(&mut hold, Event::Dispatched { down: true }), [Effect::ReleaseLost((25.0, 25.0)), Effect::Deliver((30.0, 30.0))]); +} + +#[test] +fn a_press_after_a_lost_release_starts_a_new_hold() { + let mut hold = Hold::default(); + let now = crate::time::now(); + step(&mut hold, DOWN); + step(&mut hold, sample(false, now, (50.0, 50.0))); + assert_eq!(effects(&mut hold, sample(false, now + UNSEEN_UP_GRACE, (50.0, 50.0))), [Effect::ReleaseLost((50.0, 50.0))]); + step(&mut hold, DOWN); + assert!(hold.captured()); + assert!(step(&mut hold, sample(true, now + Duration::from_secs(1), (50.0, 50.0))).is_empty(), "the old release is spent"); +} + +#[test] +fn a_queued_up_gets_the_longer_grace() { + let mut hold = Hold::default(); + let now = crate::time::now(); + step(&mut hold, DOWN); + step(&mut hold, UP); + step(&mut hold, sample(false, now, (20.0, 20.0))); + assert_eq!(hold.deadline(), Some(now + QUEUED_UP_GRACE)); + assert!(step(&mut hold, sample(false, now + Duration::from_millis(1999), (20.0, 20.0))).is_empty()); + assert_eq!(effects(&mut hold, sample(false, now + QUEUED_UP_GRACE, (30.0, 30.0))), [Effect::ReleaseLost((20.0, 20.0))]); +} + +#[test] +fn an_up_with_no_seen_press_stays_free_and_still_dispatches() { + let mut hold = Hold::default(); + step(&mut hold, UP); + assert!(!hold.captured()); + assert_eq!(effects(&mut hold, Event::Dispatched { down: true }), []); + assert_eq!(effects(&mut hold, Event::Dispatched { down: false }), [Effect::Deliver((100.0, 100.0))]); +} + +#[test] +fn losing_the_view_gives_up_where_the_pointer_was_and_hiding_stays_silent() { + let mut hold = Hold::default(); + step(&mut hold, DOWN); + step(&mut hold, sample(true, crate::time::now(), (25.0, 15.0))); + assert_eq!(effects(&mut hold, Event::ViewLost { last: Some((5.0, 5.0)) }), [Effect::ReleaseLost((25.0, 15.0))], "not a reading older than the press"); + assert_eq!(effects(&mut hold, Event::ViewLost { last: Some((25.0, 15.0)) }), [Effect::ReleaseLost((25.0, 15.0))], "no press seen: the last reading"); + assert_eq!(hold, Hold::default()); + step(&mut hold, DOWN); + assert!(step(&mut hold, Event::Stopped).is_empty()); + assert_eq!(hold, Hold::default()); +} + +#[test] +fn the_button_is_known_up_once_a_sample_or_the_monitor_says_so() { + let mut hold = Hold::default(); + let now = crate::time::now(); + assert!(!hold.button_up()); + step(&mut hold, DOWN); + assert!(!hold.button_up(), "the press itself is still on its way"); + step(&mut hold, Event::Dispatched { down: true }); + assert!(!hold.button_up(), "held"); + step(&mut hold, UP); + assert!(hold.button_up(), "the monitor saw the Up"); + step(&mut hold, Event::Dispatched { down: false }); + step(&mut hold, Event::Released); + step(&mut hold, DOWN); + step(&mut hold, Event::Dispatched { down: true }); + step(&mut hold, sample(false, now, (30.0, 30.0))); + assert!(hold.button_up(), "a sample read it rise"); + step(&mut hold, sample(true, now, (30.0, 30.0))); + assert!(hold.button_up(), "rebounding: the held press's own Up is still missing"); + step(&mut hold, DOWN); + assert!(!hold.button_up(), "a new press is on its way"); +} diff --git a/app/vendor/rune/crates/rune/src/platform/macos/panel_bridge.rs b/app/vendor/rune/crates/rune/src/platform/macos/panel_bridge.rs new file mode 100644 index 0000000..dd9a8bf --- /dev/null +++ b/app/vendor/rune/crates/rune/src/platform/macos/panel_bridge.rs @@ -0,0 +1,383 @@ +//! winit 0.30 keeps its original NSWindow in the view/delegate. Forward the handful of +//! readbacks that must describe the adopted panel. +//! +//! The forwards are added once to winit's own classes rather than to a per-window subclass: +//! winit observes `effectiveAppearance`, so its window's isa is KVO's `NSKVONotifying_` +//! class, and KVO's `-class`, `-dealloc` and observer bookkeeping read state stored on that +//! exact class. A subclass of it makes `-class` return nil. Objects Rune hasn't bridged, and +//! calls off the main thread, fall through to AppKit. + +#![allow(unsafe_code)] + +use std::{cell::RefCell, collections::{HashMap, HashSet}, ffi::{c_char, c_void}, sync::{Mutex, OnceLock, atomic::{AtomicUsize, Ordering}}}; +use objc2::{msg_send, sel, runtime::{AnyClass, AnyObject, Bool, Sel}}; +use objc2_app_kit::{NSPanel, NSView, NSWindow}; +use objc2_foundation::{NSPoint, NSRect, NSSize}; +use std::rc::Rc; + +unsafe extern "C" { + fn object_getClass(object: *const AnyObject) -> *const AnyClass; + fn class_getSuperclass(class: *const AnyClass) -> *const AnyClass; + fn class_getInstanceMethod(class: *const AnyClass, selector: Sel) -> *const c_void; + fn method_getTypeEncoding(method: *const c_void) -> *const c_char; + fn class_addMethod(class: *const AnyClass, selector: Sel, imp: *const c_void, types: *const c_char) -> Bool; + fn dladdr(address: *const c_void, info: *mut DlInfo) -> i32; + fn getsegmentdata(header: *const c_void, segment: *const c_char, size: *mut std::ffi::c_ulong) -> *const u8; +} + +#[repr(C)] +struct DlInfo { fname: *const c_char, fbase: *mut c_void, sname: *const c_char, saddr: *mut c_void } + +#[derive(Clone, Copy)] +struct Source { view: usize, panel: usize, ordinary: bool } + +thread_local! { + static WINDOWS: RefCell<HashMap<usize, Source>> = RefCell::default(); + static VIEWS: RefCell<HashMap<usize, Rc<crate::platform::macos::PointerState>>> = RefCell::default(); + /// Panels `reattach` has returned a view to, until their owner notices. + static LOST: RefCell<HashSet<usize>> = RefCell::default(); +} +static REATTACHED: AtomicUsize = AtomicUsize::new(0); +/// (class, its superclass) for every class Rune added methods to. +static INSTALLED: Mutex<Vec<(usize, usize)>> = Mutex::new(Vec::new()); + +fn source(window: &AnyObject) -> Option<Source> { + WINDOWS.try_with(|windows| windows.borrow().get(&(window as *const _ as usize)).copied()).ok().flatten() +} +fn panel(window: &AnyObject, ordinary_only: bool) -> Option<*mut AnyObject> { + source(window).filter(|s| s.ordinary || !ordinary_only).map(|s| s.panel as *mut AnyObject) +} +/// The superclass of the class Rune installed into, which is what an unbridged object (or a +/// KVO subclass of it) would have reached without Rune. +fn base(object: &AnyObject) -> &'static AnyClass { + let installed = INSTALLED.lock().unwrap_or_else(|e| e.into_inner()); + // SAFETY: `object` is a valid live ObjC instance reference passed from an IMP. + let mut class = unsafe { object_getClass(object) }; + while !class.is_null() { + if let Some((_, parent)) = installed.iter().find(|(c, _)| *c == class as usize) { + // SAFETY: `parent` came from `class_getSuperclass` during `install` and ObjC class objects live for the process. + return unsafe { &*(*parent as *const AnyClass) }; + } + // SAFETY: `class` is non-null by the loop condition and points to a registered ObjC class. + class = unsafe { class_getSuperclass(class) }; + } + unreachable!("Rune's forwards only run on classes it installed them into") +} + +macro_rules! forward { + ($name:ident, $ordinary_only:expr, ($($arg:ident: $ty:ty),*) -> $ret:ty, $($message:tt)+) => { + extern "C" fn $name(window: &AnyObject, _: Sel $(, $arg: $ty)*) -> $ret { + // SAFETY: runs as an ObjC IMP on `window`; `panel(...)` returns a live `NSPanel` owned by `Panel` + // while bridged, and `base(window)` is the original superclass matching this selector's signature. + unsafe { match panel(window, $ordinary_only) { + Some(panel) => msg_send![panel, $($message)+], + None => msg_send![super(window, base(window)), $($message)+], + } } + } + }; +} +forward!(visible, false, () -> Bool, isVisible); +forward!(occlusion, false, () -> usize, occlusionState); +forward!(scale, false, () -> f64, backingScaleFactor); +forward!(screen, false, () -> *mut AnyObject, screen); +// winit's `set_cursor` invalidates the view's cursor rects in its own (hidden) window. +forward!(invalidate_cursor_rects, false, (view: *mut AnyObject) -> (), invalidateCursorRectsForView: view); +// Ordinary panel hosts retain winit's geometry/appearance API. Only their source window +// gets these forwards; overlay placement continues to manage both native frames itself. +forward!(frame, true, () -> NSRect, frame); +forward!(key, true, () -> Bool, isKeyWindow); +forward!(live_resize, true, () -> Bool, inLiveResize); +/// The title also stays on the source, where winit's `title()` reads it back. +extern "C" fn set_title(window: &AnyObject, _: Sel, title: *mut AnyObject) { + // SAFETY: runs as the `setTitle:` IMP on `window`; `panel(...)` returns a live `NSPanel` while bridged, + // `title` is the `NSString` argument from AppKit, and `base(window)` is the original superclass. + unsafe { + if let Some(panel) = panel(window, true) { let _: () = msg_send![panel, setTitle: title]; } + msg_send![super(window, base(window)), setTitle: title] + } +} + +/// A mutating forward that only winit's calls take. AppKit restyling the source recomputes +/// and sets the source's own frame, which must not move or resize the panel. The trampoline +/// passes the sender's return address as the argument after the message's own: `$arm` and +/// `$x86` name that register for the message's integer arguments. +macro_rules! gated { + ($name:ident, $from:ident, ($($arg:ident: $ty:ty),*), $arm:literal, $x86:literal, $($message:tt)+) => { + #[unsafe(naked)] + extern "C" fn $name(_: &AnyObject, _: Sel $(, _: $ty)*) { + #[cfg(target_arch = "aarch64")] + core::arch::naked_asm!($arm, "b {}", sym $from); + #[cfg(target_arch = "x86_64")] + core::arch::naked_asm!($x86, "jmp {}", sym $from); + } + extern "C" fn $from(window: &AnyObject, _: Sel $(, $arg: $ty)*, caller: usize) { + // SAFETY: invoked from the naked trampoline with the IMP's `window` and arguments; `panel(...)` + // returns a live `NSPanel` while bridged, and `base(window)` is the original superclass. + unsafe { match panel(window, true).filter(|_| from_rune(caller)) { + Some(panel) => msg_send![panel, $($message)+], + None => msg_send![super(window, base(window)), $($message)+], + } } + } + }; +} +// NSRect, NSPoint and NSSize are all doubles, so they take float registers and leave the +// integer ones alone (on x86_64 an NSRect goes on the stack, which the tail jump keeps). +gated!(set_frame, set_frame_from, (rect: NSRect, display: Bool), "mov x3, x30", "mov rcx, [rsp]", setFrame: rect, display: display); +gated!(set_origin, set_origin_from, (point: NSPoint), "mov x2, x30", "mov rdx, [rsp]", setFrameOrigin: point); +gated!(set_size, set_size_from, (size: NSSize), "mov x2, x30", "mov rdx, [rsp]", setContentSize: size); +gated!(set_level, set_level_from, (level: isize), "mov x3, x30", "mov rcx, [rsp]", setLevel: level); +gated!(set_hit, set_hit_from, (ignore: Bool), "mov x3, x30", "mov rcx, [rsp]", setIgnoresMouseEvents: ignore); + +/// `-contentView`. AppKit restyles a window by removing `[self contentView]` from its +/// superview (`setStyleMask:`, `setContentView:`, toolbars), and other frameworks restyle the +/// first window in `NSApp.windows`, which is the hidden source (ReplayKit does when a +/// ScreenCaptureKit stream starts). Handing them the view that now lives in the panel would +/// pull it out of the panel. So only Rune and winit get the moved view (`from_rune`); +/// everyone else sees the source's real, empty content. +#[unsafe(naked)] +extern "C" fn content_view(_window: &AnyObject, _selector: Sel) -> *mut AnyObject { + // objc_msgSend tail-calls the IMP, so the return address still points into the sender. + #[cfg(target_arch = "aarch64")] + core::arch::naked_asm!("mov x2, x30", "b {}", sym content_view_from); + #[cfg(target_arch = "x86_64")] + core::arch::naked_asm!("mov rdx, [rsp]", "jmp {}", sym content_view_from); +} +extern "C" fn content_view_from(window: &AnyObject, _: Sel, caller: usize) -> *mut AnyObject { + if let Some(source) = source(window) && from_rune(caller) { return source.view as *mut AnyObject; } + // SAFETY: `window` is the live ObjC receiver and `base(window)` is its original superclass implementing `contentView`. + unsafe { msg_send![super(window, base(window)), contentView] } +} +/// The `__TEXT` range of the image holding `address`. +fn text(address: usize) -> Option<(usize, usize)> { + let mut info = DlInfo { fname: std::ptr::null(), fbase: std::ptr::null_mut(), sname: std::ptr::null(), saddr: std::ptr::null_mut() }; + // SAFETY: `dladdr` accepts any pointer value and writes into the valid local `DlInfo`. + if unsafe { dladdr(address as *const c_void, &mut info) } == 0 { return None; } + let mut size = 0; + // SAFETY: `dladdr` succeeded so `info.fbase` is a valid Mach-O header, `"__TEXT"` is NUL-terminated, and `&mut size` is a valid out-pointer. + let start = unsafe { getsegmentdata(info.fbase, c"__TEXT".as_ptr(), &mut size) }; + (!start.is_null()).then(|| (start as usize, start as usize + size as usize)) +} +/// Whether a message came from Rune, winit or the objc2 crates they send through. Linked +/// statically, that's all one image. Linked dynamically (`prefer-dynamic`), winit's +/// `contentView()` and frame setters are objc2-app-kit's methods, sending through objc2's +/// generics. A static library inside a Swift or Objective-C app shares the host's image, +/// which is fine: the host's AppKit calls still come from AppKit. +fn from_rune(caller: usize) -> bool { + static IMAGES: OnceLock<Vec<(usize, usize)>> = OnceLock::new(); + IMAGES.get_or_init(|| { + let anchors = [ + content_view_from as *const () as usize, + NSWindow::contentView as *const () as usize, + AnyClass::get as *const () as usize, + ]; + let mut images: Vec<_> = anchors.into_iter().filter_map(text).collect(); + images.dedup(); + images + }).iter().any(|(start, end)| (*start..*end).contains(&caller)) +} + +extern "C" fn hit_test(view: &AnyObject, _: Sel, point: NSPoint) -> *mut AnyObject { + let state = VIEWS.try_with(|views| views.borrow().get(&(view as *const _ as usize)).cloned()).ok().flatten(); + // SAFETY: runs as the `hitTest:` IMP on a live `NSView` on the main thread; all selectors match + // `NSView`'s ObjC signatures and `base(view)` is the original superclass. + unsafe { + if let Some(state) = state { + let parent: *mut AnyObject = msg_send![view, superview]; + let local: NSPoint = msg_send![view, convertPoint: point, fromView: parent]; + let bounds: NSRect = msg_send![view, bounds]; + let flipped: Bool = msg_send![view, isFlipped]; + let y = if flipped.as_bool() { local.y - bounds.origin.y } else { bounds.origin.y + bounds.size.height - local.y }; + if !state.hit((local.x - bounds.origin.x) as f32, y as f32) { return std::ptr::null_mut(); } + } + msg_send![super(view, base(view)), hitTest: point] + } +} + +/// Adds `methods` to `class` once. Refuses AppKit's own classes, whose instances Rune doesn't +/// own, and any class that already implements one of them, since the fallback is its superclass. +fn install(class: &AnyClass, appkit: &AnyClass, methods: &[(Sel, *const c_void)]) -> bool { + let mut installed = INSTALLED.lock().unwrap_or_else(|e| e.into_inner()); + let key = class as *const AnyClass as usize; + if installed.iter().any(|(c, _)| *c == key) { return true; } + if std::ptr::eq(class, appkit) { return false; } + // SAFETY: `class` is a registered ObjC class, `INSTALLED` serializes installation, and each added + // IMP's ABI matches the inherited method's type encoding copied from `class_getInstanceMethod`. + unsafe { + let parent = class_getSuperclass(class); + if parent.is_null() { return false; } + for (selector, _) in methods { + let method = class_getInstanceMethod(class, *selector); + if method.is_null() || method != class_getInstanceMethod(parent, *selector) { return false; } + } + // Recorded first: a forward that did get added always finds its fallback. + installed.push((key, parent as usize)); + methods.iter().all(|(selector, implementation)| { + let types = method_getTypeEncoding(class_getInstanceMethod(class, *selector)); + class_addMethod(class, *selector, *implementation, types).as_bool() + }) + } +} + +/// Returns `view` to `panel` if anything took it, and reports whether it had to. Runs inside +/// `sendEvent:`, so it never panics. +pub(crate) fn reattach(panel: &NSPanel) -> bool { + let key = panel as *const NSPanel as usize; + let found = WINDOWS.try_with(|w| w.borrow().iter().find(|(_, s)| s.panel == key).map(|(k, s)| (*k, *s))).ok().flatten(); + let Some((source, entry)) = found else { return false }; + let view = entry.view as *mut AnyObject; + // SAFETY: main-thread AppKit calls; `WINDOWS` only contains entries while `Panel` retains `source`, + // `panel`, and `view`, and `base(&*source)` is `source`'s original superclass. + unsafe { + let content: *mut AnyObject = msg_send![panel, contentView]; + let window: *mut AnyObject = msg_send![view, window]; + if content == view && window == key as *mut AnyObject { return false; } + let source = source as *mut AnyObject; + // A foreign setContentView: may have installed the view in the source itself. AppKit + // can also leave it in the source's frame view without making it the content view. + let real: *mut AnyObject = msg_send![super(&*source, base(&*source)), contentView]; + if real == view { let _: () = msg_send![source, setContentView: std::ptr::null_mut::<AnyObject>()]; } + let _: () = msg_send![view, removeFromSuperview]; + // The panel would ignore its own stale content view. + if content == view { let _: () = msg_send![panel, setContentView: std::ptr::null_mut::<AnyObject>()]; } + let _: () = msg_send![panel, setContentView: view]; + let key_window: Bool = msg_send![panel, isKeyWindow]; + if key_window.as_bool() { let _: Bool = msg_send![panel, makeFirstResponder: view]; } + } + REATTACHED.fetch_add(1, Ordering::Relaxed); + LOST.try_with(|lost| lost.borrow_mut().insert(key)).ok(); + true +} + +/// Whether `reattach` returned `panel`'s view since the last call. +pub(crate) fn take_reattached(panel: &NSPanel) -> bool { + LOST.try_with(|lost| lost.borrow_mut().remove(&(panel as *const NSPanel as usize))).unwrap_or(false) +} + +/// How many times a panel has had to take its view back. Tests assert the view was never taken. +#[doc(hidden)] +pub fn reattach_count() -> usize { REATTACHED.load(Ordering::Relaxed) } + +fn window_forwards() -> [(Sel, *const c_void); 15] { + [ + (sel!(contentView), content_view as *const c_void), + (sel!(isVisible), visible as *const c_void), + (sel!(occlusionState), occlusion as *const c_void), + (sel!(backingScaleFactor), scale as *const c_void), + (sel!(screen), screen as *const c_void), + (sel!(invalidateCursorRectsForView:), invalidate_cursor_rects as *const c_void), + (sel!(frame), frame as *const c_void), + (sel!(isKeyWindow), key as *const c_void), + (sel!(inLiveResize), live_resize as *const c_void), + (sel!(setFrame:display:), set_frame as *const c_void), + (sel!(setFrameOrigin:), set_origin as *const c_void), + (sel!(setContentSize:), set_size as *const c_void), + (sel!(setTitle:), set_title as *const c_void), + (sel!(setLevel:), set_level as *const c_void), + (sel!(setIgnoresMouseEvents:), set_hit as *const c_void), + ] +} + +pub(crate) struct Bridge { source: usize, view: Option<usize> } +impl Bridge { + /// Main-thread only. The owner retains all three objects until after this bridge drops. + pub fn new(source: &NSWindow, panel: &NSPanel, view: &NSView, filter: Option<Rc<crate::platform::macos::PointerState>>) -> Option<Self> { + Self::new_kind(source, panel, view, filter, false) + } + pub fn new_window(source: &NSWindow, panel: &NSPanel, view: &NSView) -> Option<Self> { + Self::new_kind(source, panel, view, None, true) + } + fn new_kind(source: &NSWindow, panel: &NSPanel, view: &NSView, filter: Option<Rc<crate::platform::macos::PointerState>>, ordinary: bool) -> Option<Self> { + use objc2::ClassType; + // `-class` is the class winit declared, below any KVO subclass. + // SAFETY: `source` is a live `NSWindow` on the main thread; `-class` returns a non-null static `AnyClass`. + let class: &AnyClass = unsafe { msg_send![source, class] }; + if !install(class, NSWindow::class(), &window_forwards()) { return None; } + if filter.is_some() { + // SAFETY: `view` is a live `NSView` on the main thread; `-class` returns a non-null static `AnyClass`. + let view_class: &AnyClass = unsafe { msg_send![view, class] }; + if !install(view_class, NSView::class(), &[(sel!(hitTest:), hit_test as *const c_void)]) { return None; } + } + let source = source as *const NSWindow as usize; + WINDOWS.with(|w| w.borrow_mut().insert(source, Source { view: view as *const NSView as usize, panel: panel as *const NSPanel as usize, ordinary })); + let view = filter.map(|filter| { + let view = view as *const NSView as usize; + VIEWS.with(|v| v.borrow_mut().insert(view, filter)); + view + }); + Some(Self { source, view }) + } +} +impl Drop for Bridge { + fn drop(&mut self) { + if let Some(entry) = WINDOWS.with(|w| w.borrow_mut().remove(&self.source)) { LOST.with(|lost| lost.borrow_mut().remove(&entry.panel)); } + if let Some(view) = self.view { VIEWS.with(|v| v.borrow_mut().remove(&view)); } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use objc2::{class, runtime::ClassBuilder}; + + thread_local! { static RECEIVED: RefCell<Vec<String>> = RefCell::default(); } + fn received(message: String) { RECEIVED.with(|r| r.borrow_mut().push(message)); } + extern "C" fn got_frame(_: *mut AnyObject, _: Sel, rect: NSRect, display: Bool) { + received(format!("frame {} {} {} {} {}", rect.origin.x, rect.origin.y, rect.size.width, rect.size.height, display.as_bool())); + } + extern "C" fn got_origin(_: *mut AnyObject, _: Sel, point: NSPoint) { received(format!("origin {} {}", point.x, point.y)); } + extern "C" fn got_size(_: *mut AnyObject, _: Sel, size: NSSize) { received(format!("size {} {}", size.width, size.height)); } + extern "C" fn got_level(_: *mut AnyObject, _: Sel, level: isize) { received(format!("level {level}")); } + extern "C" fn got_hit(_: *mut AnyObject, _: Sel, ignore: Bool) { received(format!("ignore {}", ignore.as_bool())); } + extern "C" fn got_live_resize(_: *mut AnyObject, _: Sel) -> Bool { Bool::YES } + + /// The trampolines on this architecture: each hands its own arguments and the sender's + /// return address to the Rust side. A wrong register would read garbage as the caller and + /// send the message on to the (uninitialized) window instead of the panel. + #[test] + fn trampolines_pass_the_arguments_and_the_sender() { + use objc2::ClassType; + let window_class = ClassBuilder::new(c"RuneBridgeTestWindow", NSWindow::class()).unwrap().register(); + assert!(install(window_class, NSWindow::class(), &window_forwards())); + let mut panel_class = ClassBuilder::new(c"RuneBridgeTestPanel", class!(NSObject)).unwrap(); + // SAFETY: each test handler's C ABI matches the corresponding `NSWindow` selector. + unsafe { + panel_class.add_method(sel!(setFrame:display:), got_frame as extern "C" fn(*mut AnyObject, Sel, NSRect, Bool)); + panel_class.add_method(sel!(setFrameOrigin:), got_origin as extern "C" fn(*mut AnyObject, Sel, NSPoint)); + panel_class.add_method(sel!(setContentSize:), got_size as extern "C" fn(*mut AnyObject, Sel, NSSize)); + panel_class.add_method(sel!(setLevel:), got_level as extern "C" fn(*mut AnyObject, Sel, isize)); + panel_class.add_method(sel!(setIgnoresMouseEvents:), got_hit as extern "C" fn(*mut AnyObject, Sel, Bool)); + panel_class.add_method(sel!(inLiveResize), got_live_resize as extern "C" fn(*mut AnyObject, Sel) -> Bool); + } + let panel_class = panel_class.register(); + // A real NSWindow needs the window server, so the source is only allocated. All leak. + // SAFETY: `window_class`, `panel_class`, and `NSObject` are registered ObjC classes whose `alloc`/`new` return valid instances. + let (window, panel, view): (*mut AnyObject, *mut AnyObject, *mut AnyObject) = unsafe { + (msg_send![window_class, alloc], msg_send![panel_class, new], msg_send![class!(NSObject), new]) + }; + WINDOWS.with(|w| w.borrow_mut().insert(window as usize, Source { view: view as usize, panel: panel as usize, ordinary: true })); + // SAFETY: `window`, `panel`, and `view` are live ObjC instances registered in `WINDOWS`, and + // every message and `NSInvocation` return buffer (`&mut foreign`) matches its selector's signature. + unsafe { + let content: *mut AnyObject = msg_send![window, contentView]; + assert_eq!(content, view, "Rune's call gets the moved view"); + // NSInvocation calls the method from CoreFoundation, as AppKit would. + let signature: *mut AnyObject = msg_send![window, methodSignatureForSelector: sel!(contentView)]; + let invocation: *mut AnyObject = msg_send![class!(NSInvocation), invocationWithMethodSignature: signature]; + let _: () = msg_send![invocation, setSelector: sel!(contentView)]; + let _: () = msg_send![invocation, invokeWithTarget: window]; + let mut foreign: *mut AnyObject = view; + let _: () = msg_send![invocation, getReturnValue: &mut foreign as *mut *mut AnyObject as *mut c_void]; + assert!(foreign.is_null(), "a framework's call gets the window's own, empty content"); + + let live: Bool = msg_send![window, inLiveResize]; + assert!(live.as_bool(), "ordinary panel forwards inLiveResize"); + let _: () = msg_send![window, setFrame: NSRect::new(NSPoint::new(1.5, 2.5), NSSize::new(300.0, 200.0)), display: Bool::YES]; + let _: () = msg_send![window, setFrameOrigin: NSPoint::new(7.0, 8.0)]; + let _: () = msg_send![window, setContentSize: NSSize::new(40.0, 50.0)]; + let _: () = msg_send![window, setLevel: 3isize]; + let _: () = msg_send![window, setIgnoresMouseEvents: Bool::YES]; + } + WINDOWS.with(|w| w.borrow_mut().remove(&(window as usize))); + assert_eq!(RECEIVED.with(|r| r.take()), ["frame 1.5 2.5 300 200 true", "origin 7 8", "size 40 50", "level 3", "ignore true"]); + } +} diff --git a/app/vendor/rune/crates/rune/src/platform/macos/pointer.rs b/app/vendor/rune/crates/rune/src/platform/macos/pointer.rs new file mode 100644 index 0000000..aaa38ed --- /dev/null +++ b/app/vendor/rune/crates/rune/src/platform/macos/pointer.rs @@ -0,0 +1,290 @@ +//! Overlay pointer sampling, hit testing, and native mouse monitors. + +use std::{cell::{Cell, RefCell}, time::{Duration, Instant}}; +use objc2::{ClassType, MainThreadMarker, msg_send, rc::Retained}; +use objc2_app_kit::{NSEvent, NSPanel, NSScreen, NSWindow}; +use objc2_foundation::{NSObject, NSPoint}; +use crate::{OverlayInput, OverlaySupport}; +use super::{Panel, cursor::set_ns_cursor, geometry::{contains_pointer, screen_id}, hold::{self, Effect, Event, Hold, Point}}; + +#[derive(Default)] +pub(crate) struct PointerState { + input: Cell<OverlayInput>, + regions: RefCell<Vec<[f32; 4]>>, + pending: Cell<Option<(f32, f32)>>, + hold: RefCell<Hold>, + /// The last press winit dispatched was the only click the hold had queued, so what the hold + /// learns about the button after it is about the press the runtime holds. With anything else + /// queued, a stale click could be taken for it, so the hold claims nothing. + matched: Cell<bool>, + last: Cell<Option<(f32, f32)>>, + inside: Cell<bool>, + display: Cell<Option<u32>>, + follow: Cell<bool>, + /// A lost release the host hasn't given the runtime yet. + recovered_release: Cell<Option<(f32, f32)>>, + /// The cursor the overlay shows while the pointer is over its hit area. + cursor: Cell<Option<crate::el::Cursor>>, +} + +impl PointerState { + pub(crate) fn new(input: OverlayInput, follow: bool) -> Self { + Self { input: Cell::new(input), follow: Cell::new(follow), ..Default::default() } + } + + #[allow(unsafe_code)] + fn trace(&self, panel: &NSPanel, source: &str, event: Option<&NSEvent>) { + static ENABLED: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + if !*ENABLED.get_or_init(|| std::env::var_os("RUNE_OVERLAY_TRACE_INPUT").is_some()) { return; } + let cursor = NSEvent::mouseLocation(); + let frame = panel.frame(); + let local = (cursor.x - frame.origin.x, frame.origin.y + frame.size.height - cursor.y); + // SAFETY: `event` is a live `NSEvent` on the main thread; `type` returns `NSEventType` (`usize`). + let kind: usize = event.map_or(0, |event| unsafe { msg_send![event, type] }); + // SAFETY: `event` is a live `NSEvent` on the main thread; `locationInWindow` returns `NSPoint`. + let event_point: NSPoint = event.map_or(NSPoint::new(0.0, 0.0), |event| unsafe { msg_send![event, locationInWindow] }); + // SAFETY: class property read on `NSEvent` on the main thread; returns a bitmask (`usize`). + let buttons: usize = unsafe { msg_send![NSEvent::class(), pressedMouseButtons] }; + eprintln!("overlay-input source={source} window={} kind={kind} event={event_point:?} cursor={cursor:?} local={local:?} frame={frame:?} input={:?} buttons={buttons} captured={} ignore={} regions={:?}", + panel.windowNumber(), self.input.get(), self.captured(), panel.ignoresMouseEvents(), self.regions.borrow()); + } + /// Carries a transition out; the point of a click winit dispatched. + fn step(&self, event: Event) -> Option<Point> { + let mut delivered = None; + for effect in hold::step(&mut self.hold.borrow_mut(), event) { + match effect { + Effect::Deliver(at) => delivered = Some(at), + // The first is the press the runtime holds; later ones have nothing left to end. + Effect::ReleaseLost(at) => if self.recovered_release.get().is_none() { self.recovered_release.set(Some(at)); }, + } + } + delivered + } + pub(crate) fn captured(&self) -> bool { self.hold.borrow().captured() } + /// When the loop must sample next. Covered, the recurring `poll` rests; a lost release's + /// one-shot deadline doesn't, or nothing would end its press. + pub(crate) fn deadline(&self, poll: Option<Instant>, occluded: bool) -> Option<Instant> { + poll.filter(|_| !occluded).into_iter().chain(self.hold.borrow().deadline()).min() + } + fn over(&self, x: f32, y: f32) -> bool { + match self.input.get() { + OverlayInput::All => true, + OverlayInput::Regions => self.regions.borrow().iter().any(|r| crate::overlay::options::contains(*r, x, y)), + _ => false, + } + } + pub(crate) fn hit(&self, x: f32, y: f32) -> bool { self.captured() || self.over(x, y) } + pub(crate) fn record_click(&self, down: bool, x: f32, y: f32) { + self.step(Event::Seen { down, at: (x, y), over: self.over(x, y) }); + } + /// winit dispatched a press or release: a lost release to land before it, and its point. + pub(crate) fn take_edge(&self, down: bool) -> (Option<Point>, Option<Point>) { + let point = self.step(Event::Dispatched { down }); + if down { self.matched.set(point.is_some() && !self.hold.borrow().queued()); } + (self.recovered_release.take(), point) + } + /// A lost release to land before a position winit or a sample is about to report. + pub(crate) fn take_lost_before_position(&self) -> Option<Point> { + self.step(Event::Positioning); + self.recovered_release.take() + } + /// The sampled position to report, unless a click it's newer than is still on its way. + pub(crate) fn take_position(&self) -> Option<Point> { + if self.hold.borrow().ahead_of_clicks() { None } else { self.pending.take() } + } + /// One reading of the button and pointer. True if the position is new. + pub(crate) fn read(&self, buttons: usize, now: Instant, at: Point, inside: bool, display_changed: bool) -> bool { + self.observe_release(buttons, now, at); + let was_inside = self.inside.replace(inside); + if !(inside || was_inside || self.captured() || display_changed) || self.last.replace(Some(at)) == Some(at) { return false; } + self.pending.set(Some(at)); + true + } + pub(crate) fn released(&self) { self.step(Event::Released); } + /// Whether the button is known to be up for the press the runtime holds. Not for a press the + /// hold didn't match: a stale Up ahead of it in the queue belongs to an earlier press. + pub(crate) fn button_up(&self) -> bool { self.matched.get() && self.hold.borrow().button_up() } + fn observe_release(&self, buttons: usize, now: Instant, at: (f32, f32)) { + self.step(Event::Sampled { button_down: buttons & 1 != 0, now, at }); + } + /// winit's view was out of the panel, so the clicks recorded meanwhile never reached it. + pub(crate) fn view_lost(&self) { self.step(Event::ViewLost { last: self.last.get() }); } + /// Sets the cursor again after a mouse event, which may have let another window's cursor + /// rects replace it. The arrow once the pointer is off the hit area. + fn reapply_cursor(&self, panel: &NSPanel) { + let Some(cursor) = self.cursor.get() else { return }; + let pointer = NSEvent::mouseLocation(); + let frame = panel.frame(); + let (x, y) = ((pointer.x - frame.origin.x) as f32, (frame.origin.y + frame.size.height - pointer.y) as f32); + let inside = x >= 0.0 && y >= 0.0 && x < frame.size.width as f32 && y < frame.size.height as f32; + if inside && self.hit(x, y) { set_ns_cursor(cursor); } + else { self.cursor.set(None); set_ns_cursor(crate::el::Cursor::Default); } + } + /// Whether a sample can tell the overlay anything: one passing every click through, holding + /// no press, showing no cursor and following nothing never reads the pointer. + fn wanted(&self) -> bool { + self.input.get() != OverlayInput::None || self.follow.get() || self.captured() || self.cursor.get().is_some() + } + #[allow(unsafe_code)] + pub(super) fn observe(&self, panel: &NSPanel, wake: Option<&crate::Waker>) { + let pointer = NSEvent::mouseLocation(); + // SAFETY: class property read on `NSEvent` on AppKit's main thread; returns a bitmask (`usize`). + let buttons: usize = unsafe { msg_send![NSEvent::class(), pressedMouseButtons] }; + let frame = panel.frame(); + let (x, y) = ((pointer.x - frame.origin.x) as f32, (frame.origin.y + frame.size.height - pointer.y) as f32); + let inside = x >= 0.0 && y >= 0.0 && x < frame.size.width as f32 && y < frame.size.height as f32; + let display_changed = self.follow.get() && MainThreadMarker::new().is_some_and(|mtm| { + NSScreen::screens(mtm).iter().find(|s| contains_pointer(s, pointer)) + .is_some_and(|s| self.display.replace(Some(screen_id(&s))) != Some(screen_id(&s))) + }); + let moved = self.read(buttons, crate::time::now(), (x, y), inside, display_changed); + let ignore = !self.hit(x, y); + if panel.ignoresMouseEvents() != ignore { + panel.setIgnoresMouseEvents(ignore); + self.trace(panel, "flip", None); + } + if moved && let Some(wake) = wake { wake(); } + } +} + +pub(super) struct MouseMonitors { tokens: Vec<Retained<NSObject>> } + +impl Drop for MouseMonitors { + #[allow(unsafe_code)] + fn drop(&mut self) { + for token in &self.tokens { + // SAFETY: each token was returned by NSEvent and is removed exactly once on main. + unsafe { let _: () = msg_send![NSEvent::class(), removeMonitor: &**token]; } + } + } +} + +impl Panel { + pub fn global_pointer(&self) -> OverlaySupport { + if (self.follow_pointer.get() || self.pointer.input.get() == OverlayInput::Regions) + && self.monitors.borrow().as_ref().is_none_or(|m| m.tokens.len() != 2) { OverlaySupport::Failed } + else { OverlaySupport::Supported } + } + pub(crate) fn pointer_state(&self) -> std::rc::Rc<PointerState> { self.pointer.clone() } + pub fn pointer_captured(&self) -> bool { self.pointer.captured() } + pub fn pointer_released(&self) { + self.pointer.released(); + self.refresh_monitors(); + if self.presence.get().visible() { self.pointer.observe(&self.panel, self.wake.as_ref()); } + } + pub fn pointer_deadline(&self, occluded: bool) -> Option<Instant> { self.pointer.deadline(self.pointer_poll.get(), occluded) } + /// Samples the pointer if its poll is due; true if it did. + fn poll_pointer(&self, now: Instant) -> bool { + if self.pointer_poll.get().is_some_and(|at| at <= now) { + self.pointer_poll.set(Some(now + Duration::from_secs_f64(1.0 / 120.0))); + self.pointer.trace(&self.panel, "poll", None); + self.pointer.observe(&self.panel, None); + return true; + } + false + } + /// Once per event-loop turn: keeps the view (it hosts the layer the overlay draws into) and + /// samples the pointer, through the timed poll when it is due and `poll` allows it. + pub fn observe_pointer(&self, now: Instant, poll: bool) { + self.keep_view(); + if self.presence.get().visible() && self.pointer.wanted() && !(poll && self.poll_pointer(now)) { self.pointer.observe(&self.panel, None); } + } + pub fn set_input(&self, input: OverlayInput) { + self.pointer.input.set(input); + self.refresh_monitors(); + if self.presence.get().visible() { self.pointer.observe(&self.panel, self.wake.as_ref()); } + } + /// AppKit applies cursor rects (winit's cursor) only in the key window, and an overlay is + /// rarely key. While the pointer is over its hit area (`Some`), set the cursor directly and + /// again on every mouse event; set the arrow once when it leaves (`None`). + pub fn set_cursor(&self, cursor: Option<crate::el::Cursor>) { + let was = self.pointer.cursor.replace(cursor); + match cursor { + Some(cursor) => set_ns_cursor(cursor), + None if was.is_some() => set_ns_cursor(crate::el::Cursor::Default), + None => {} + } + if was.is_some() != cursor.is_some() { self.refresh_monitors(); } + } + pub fn set_follow_pointer(&self, follow: bool) { self.follow_pointer.set(follow); self.pointer.follow.set(follow); self.refresh_monitors(); } + pub(super) fn refresh_monitors(&self) { + if !self.presence.get().visible() { return; } + if self.pointer.input.get() == OverlayInput::Regions { + if self.pointer_poll.get().is_none() { self.pointer_poll.set(Some(crate::time::now())); } + } else { self.pointer_poll.set(None); } + if self.needs_monitors() { self.start_monitors(); } + else { self.monitors.borrow_mut().take(); } + } + pub fn set_regions(&self, regions: &[[f32; 4]]) { + if self.pointer.regions.borrow().as_slice() == regions { return; } + *self.pointer.regions.borrow_mut() = regions.to_vec(); + self.pointer.trace(&self.panel, "regions", None); + if self.presence.get().visible() { self.pointer.observe(&self.panel, None); } + } + + fn needs_monitors(&self) -> bool { + self.follow_pointer.get() || self.pointer.input.get() == OverlayInput::Regions || self.pointer.captured() + || self.pointer.cursor.get().is_some() + } + + #[allow(unsafe_code)] + fn start_monitors(&self) { + if self.monitors.borrow().is_some() || !self.needs_monitors() { return; } + // Monitors wake the loop; position/button state is sampled there. A local down + // owns its drag until winit has delivered Up, including outside the hit region. + let movement = (1usize << 5) | (1 << 6) | (1 << 7) | (1 << 27); + let mask = movement | (1 << 1) | (1 << 2); + let (pointer, panel, wake) = (self.pointer.clone(), self.panel.clone(), self.wake.clone()); + let global = block2::RcBlock::new(move |event: *mut NSEvent| { + // SAFETY: AppKit passes a valid `NSEvent` pointer (or null) for the monitor callback on the main thread. + pointer.trace(&panel, "global", unsafe { event.as_ref() }); + pointer.reapply_cursor(&panel); + if let Some(wake) = &wake { wake(); } + }); + let (pointer, panel, wake) = (self.pointer.clone(), self.panel.clone(), self.wake.clone()); + let local = block2::RcBlock::new(move |event: *mut NSEvent| -> *mut NSEvent { + // SAFETY: AppKit passes a valid `NSEvent` pointer (or null) for the monitor callback on the main thread. + pointer.trace(&panel, "local", unsafe { event.as_ref() }); + pointer.reapply_cursor(&panel); + // SAFETY: `event` is a live `NSEvent` on AppKit's main thread; `type`, `window`, and `locationInWindow` match `NSEvent`'s signatures. + unsafe { + let kind: usize = msg_send![event, type]; + let window: *mut NSWindow = msg_send![event, window]; + if (kind == 1 || kind == 2) && window == (&*panel as *const NSPanel).cast_mut().cast() { + let point: NSPoint = msg_send![event, locationInWindow]; + let frame = panel.frame(); + let (x, y) = (point.x as f32, (frame.size.height - point.y) as f32); + pointer.record_click(kind == 1, x, y); + } + } + if let Some(wake) = &wake { wake(); } + event + }); + let mut tokens = Vec::new(); + // SAFETY: main-thread AppKit calls; `global` and `local` are valid `RcBlock`s copied by AppKit, + // and the returned monitor tokens are removed in `MouseMonitors::drop`. + unsafe { + let token: Option<Retained<NSObject>> = msg_send![NSEvent::class(), addGlobalMonitorForEventsMatchingMask: mask, handler: &*global]; + tokens.extend(token); + let token: Option<Retained<NSObject>> = msg_send![NSEvent::class(), addLocalMonitorForEventsMatchingMask: mask, handler: &*local]; + tokens.extend(token); + } + *self.monitors.borrow_mut() = Some(MouseMonitors { tokens }); + self.pointer.observe(&self.panel, self.wake.as_ref()); + } + + pub(super) fn stop_pointer(&self) { + self.pointer_poll.set(None); + self.monitors.borrow_mut().take(); + self.pointer.step(Event::Stopped); + self.pointer.pending.set(None); + self.pointer.last.set(None); + self.pointer.inside.set(false); + self.pointer.recovered_release.set(None); + self.set_cursor(None); + } +} + +#[cfg(test)] +#[path = "pointer_tests.rs"] +mod tests; diff --git a/app/vendor/rune/crates/rune/src/platform/macos/pointer_tests.rs b/app/vendor/rune/crates/rune/src/platform/macos/pointer_tests.rs new file mode 100644 index 0000000..5667516 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/platform/macos/pointer_tests.rs @@ -0,0 +1,199 @@ +use super::*; +use std::collections::VecDeque; +use super::super::hold::Click; + +/// winit dispatches the click at the front of the queue. +fn dispatch(pointer: &PointerState, down: bool) -> Option<Point> { pointer.step(Event::Dispatched { down }) } +fn queued(pointer: &PointerState) -> VecDeque<Click> { pointer.hold.borrow().clone().into_clicks() } + +#[test] +fn overlay_handlerless_hit_releases_native_ownership_in_every_input_mode() { + fn view(_: &(), _: &mut crate::Cx<()>) -> crate::El { + crate::el().child(crate::el().absolute(10.0, 10.0).size(20.0, 20.0).hit()) + } + for mode in [OverlayInput::Regions, OverlayInput::None] { + let mut rt = crate::Runtime::new((), view, (100.0, 100.0), crate::Env::default()); + rt.host.native_overlay = true; + rt.frame(0.0); + let pointer = PointerState { input: Cell::new(OverlayInput::Regions), ..Default::default() }; + pointer.regions.borrow_mut().extend_from_slice(rt.hit_regions()); + pointer.record_click(true, 20.0, 20.0); + dispatch(&pointer, true); + rt.pointer_down(20.0, 20.0); + assert!(!rt.pointer_captured(), "a handlerless hit owns only the native press"); + assert!(pointer.captured()); + pointer.record_click(false, 50.0, 50.0); + pointer.input.set(mode); + dispatch(&pointer, false); + pointer.released(); // acknowledged even when Runtime input is disabled + assert!(!pointer.captured(), "native release cannot depend on Runtime capture or mode"); + assert!(!pointer.hit(50.0, 50.0)); + } +} + +#[test] +fn a_click_through_overlay_that_follows_nothing_never_samples_the_pointer() { + let pointer = PointerState { input: Cell::new(OverlayInput::None), ..Default::default() }; + assert!(!pointer.wanted()); + pointer.follow.set(true); + assert!(pointer.wanted(), "following the pointer reads it"); + pointer.follow.set(false); + pointer.step(Event::Seen { down: true, at: (0.0, 0.0), over: true }); + assert!(pointer.wanted(), "a press it holds still needs its release"); + pointer.step(Event::Stopped); + for input in [OverlayInput::Regions, OverlayInput::All] { + pointer.input.set(input); + assert!(pointer.wanted()); + } +} + +#[test] +fn overlay_lost_up_recovers_once_after_grace_using_release_position() { + let pointer = PointerState { input: Cell::new(OverlayInput::Regions), ..Default::default() }; + pointer.regions.borrow_mut().push([10.0, 10.0, 30.0, 30.0]); + pointer.record_click(true, 20.0, 20.0); + let now = crate::time::now(); + pointer.observe_release(1, now, (40.0, 40.0)); + pointer.observe_release(0, now, (50.0, 50.0)); + pointer.observe_release(0, now + Duration::from_millis(99), (60.0, 60.0)); + assert!(pointer.captured()); + pointer.observe_release(0, now + Duration::from_millis(100), (70.0, 70.0)); + assert!(!pointer.captured()); + assert!(queued(&pointer).is_empty()); + assert_eq!(pointer.recovered_release.take(), Some((50.0, 50.0))); + pointer.observe_release(0, now + Duration::from_secs(1), (80.0, 80.0)); + assert_eq!(pointer.recovered_release.take(), None); +} +#[test] +fn overlay_queued_up_and_next_down_keep_their_ownership_until_dispatched() { + let pointer = PointerState { input: Cell::new(OverlayInput::Regions), ..Default::default() }; + pointer.regions.borrow_mut().push([10.0, 10.0, 30.0, 30.0]); + pointer.record_click(true, 20.0, 20.0); + pointer.record_click(false, 100.0, 100.0); + pointer.observe_release(0, crate::time::now(), (100.0, 100.0)); + pointer.observe_release(0, crate::time::now() + Duration::from_secs(1), (100.0, 100.0)); + assert!(pointer.captured()); + assert_eq!(pointer.recovered_release.get(), None); + pointer.record_click(true, 20.0, 20.0); // next native Down queued behind the Up + dispatch(&pointer, true); + dispatch(&pointer, false); + pointer.released(); + assert_eq!(pointer.recovered_release.get(), None); + assert!(pointer.captured()); + dispatch(&pointer, true); + pointer.released(); + assert!(!pointer.captured()); +} +#[test] +fn overlay_undelivered_click_releases_capture_after_stall() { + // The local monitor saw a click that never reached winit, so neither entry dispatches. + let pointer = PointerState { input: Cell::new(OverlayInput::Regions), ..Default::default() }; + pointer.regions.borrow_mut().push([10.0, 10.0, 30.0, 30.0]); + pointer.record_click(true, 20.0, 20.0); + pointer.record_click(false, 20.0, 20.0); + let now = crate::time::now(); + pointer.observe_release(0, now, (20.0, 20.0)); + pointer.observe_release(0, now + Duration::from_millis(1999), (20.0, 20.0)); + assert!(pointer.captured(), "a briefly queued Up still belongs to winit"); + pointer.observe_release(0, now + Duration::from_secs(2), (20.0, 20.0)); + assert!(!pointer.captured()); + assert!(queued(&pointer).is_empty()); + assert!(!pointer.hit(50.0, 50.0), "outside the regions passes through again"); +} +#[test] +fn overlay_lost_view_releases_capture_where_the_pointer_was() { + let pointer = PointerState { input: Cell::new(OverlayInput::Regions), ..Default::default() }; + pointer.regions.borrow_mut().push([10.0, 10.0, 30.0, 30.0]); + pointer.record_click(true, 20.0, 20.0); + pointer.read(1, crate::time::now(), (25.0, 15.0), true, false); + pointer.view_lost(); + assert!(!pointer.captured()); + assert!(queued(&pointer).is_empty()); + assert_eq!(pointer.recovered_release.take(), Some((25.0, 15.0)), "the runtime's press is released"); +} +#[test] +fn overlay_rejected_down_cannot_poison_later_click_and_owned_up_survives_exit() { + let pointer = PointerState { input: Cell::new(OverlayInput::Regions), ..Default::default() }; + pointer.regions.borrow_mut().push([10.0, 10.0, 30.0, 30.0]); + pointer.record_click(true, 1.0, 1.0); + pointer.record_click(true, 20.0, 20.0); + pointer.record_click(false, 100.0, 100.0); + assert_eq!(queued(&pointer), VecDeque::from([Click { down: true, at: (20.0, 20.0), ends: None }, Click { down: false, at: (100.0, 100.0), ends: None }])); + // Physical Up must not turn off native hit testing before winit dispatches it. + assert!(pointer.hit(100.0, 100.0)); + pointer.step(Event::Stopped); + assert!(!pointer.hit(100.0, 100.0)); +} +#[test] +fn a_covered_overlay_rests_its_poll_but_keeps_a_lost_releases_deadline() { + let pointer = PointerState { input: Cell::new(OverlayInput::All), ..Default::default() }; + let now = crate::time::now(); + let poll = Some(now + Duration::from_millis(8)); + assert_eq!(pointer.deadline(poll, false), poll); + assert_eq!(pointer.deadline(poll, true), None, "covered, the poll rests"); + pointer.record_click(true, 20.0, 20.0); + dispatch(&pointer, true); + assert_eq!(pointer.deadline(poll, true), None, "a press with the button down waits for nothing"); + pointer.observe_release(0, now, (20.0, 20.0)); + let due = now + Duration::from_millis(100); + assert_eq!(pointer.deadline(poll, true), Some(due), "covered, the grace still wakes the loop"); + assert_eq!(pointer.deadline(poll, false), poll, "the sooner of the two"); + pointer.observe_release(0, due, (20.0, 20.0)); + assert_eq!(pointer.deadline(poll, true), None, "once: it does not restart the poll"); +} +#[test] +fn a_queued_press_hands_over_the_release_lost_before_it() { + let pointer = PointerState { input: Cell::new(OverlayInput::All), ..Default::default() }; + pointer.record_click(true, 20.0, 20.0); + pointer.observe_release(0, crate::time::now(), (50.0, 50.0)); + pointer.record_click(true, 30.0, 30.0); + assert_eq!(pointer.take_edge(true), (None, Some((20.0, 20.0)))); + assert_eq!(pointer.take_edge(true), (Some((50.0, 50.0)), Some((30.0, 30.0))), "landing before the second press"); +} + +#[test] +fn a_sample_beating_the_next_press_cancels_the_old_drag_where_the_button_rose() { + type State = Vec<(crate::Phase, bool, f32)>; + fn view(_: &State, _: &mut crate::Cx<State>) -> crate::El { + crate::el().size(100.0, 100.0).on_drag(|s: &mut State, d, _| s.push((d.phase, d.cancelled(), d.x))) + } + let mut rt = crate::Runtime::new(Vec::new(), view, (100.0, 100.0), crate::Env::default()); + rt.frame(0.0); + let pointer = PointerState { input: Cell::new(OverlayInput::All), ..Default::default() }; + let now = crate::time::now(); + pointer.record_click(true, 10.0, 10.0); + pointer.take_edge(true); + rt.pointer_down(10.0, 10.0); + pointer.observe_release(0, now, (50.0, 50.0)); + pointer.observe_release(1, now, (70.0, 70.0)); + pointer.record_click(true, 70.0, 70.0); + let (lost, _) = pointer.take_edge(true); + let (x, y) = lost.expect("the old press lost its release"); + rt.pointer_release_lost(x, y); + rt.frame(0.0); + assert_eq!(rt.state.last(), Some(&(crate::Phase::Up, true, 50.0))); +} + +#[test] +fn a_press_lost_before_any_sample_cancels_at_its_own_down_and_keeps_the_run() { + type State = Vec<(crate::Phase, bool, f32, u32)>; + fn view(_: &State, _: &mut crate::Cx<State>) -> crate::El { + crate::el().size(100.0, 100.0).on_drag(|s: &mut State, d, _| s.push((d.phase, d.cancelled(), d.x, d.clicks))) + } + let mut rt = crate::Runtime::new(Vec::new(), view, (100.0, 100.0), crate::Env::default()); + rt.frame(0.0); + let pointer = PointerState { input: Cell::new(OverlayInput::All), ..Default::default() }; + pointer.read(0, crate::time::now(), (5.0, 5.0), true, false); // a hover older than the press + pointer.record_click(true, 50.0, 10.0); + let (_, down) = pointer.take_edge(true); + let (x, y) = down.unwrap(); + rt.pointer_down(x, y); + pointer.record_click(true, 51.0, 10.0); + let (lost, down) = pointer.take_edge(true); + let (x, y) = lost.expect("the first press lost its release"); + rt.pointer_release_lost(x, y); + let (x, y) = down.unwrap(); + rt.pointer_down(x, y); + rt.frame(0.0); + assert_eq!(rt.state, [(crate::Phase::Down, false, 50.0, 1), (crate::Phase::Up, true, 50.0, 1), (crate::Phase::Down, false, 51.0, 2)]); +} diff --git a/app/vendor/rune/crates/rune/src/platform/macos/presence.rs b/app/vendor/rune/crates/rune/src/platform/macos/presence.rs new file mode 100644 index 0000000..63f0c5a --- /dev/null +++ b/app/vendor/rune/crates/rune/src/platform/macos/presence.rs @@ -0,0 +1,200 @@ +//! Whether a panel belongs on screen, and whether its capture exclusion is applied. +//! +//! Panels join every Space. An excluded window can blank Mission Control's thumbnails even at +//! alpha zero, and sharing readbacks can remain stale after a reset. +//! Every hidden panel therefore orders out, including prewarmed panels. Its view, surface and +//! cached pixels stay alive. Exclusion holds from show until the hide's fade finishes; ordering +//! out precedes restoring sharing. A show or hide during a fade replaces it, and the replaced +//! fade's completion, which AppKit still delivers, no longer matches the phase's fence. + +use std::time::Duration; +use crate::machine::{Attempt, Effects, Seq}; + +/// Where a panel is between hidden and shown. A prewarm guard lasts one draw and doesn't depend +/// on show or hide, so any phase can hold one: `Prewarmed` is that guard with no show behind it, +/// and `warming` is the same guard over a phase that has one. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +enum Phase { + #[default] + OrderedOut, + /// Ordered in at alpha zero for one surface acquisition. + Prewarmed, + Shown { warming: bool }, + FadingIn { fence: Attempt, warming: bool }, + /// `seen`: it was on screen when the hide started. A panel that wasn't still runs the fade, + /// but holds no place on screen and no exclusion meanwhile. + FadingOut { fence: Attempt, seen: bool, warming: bool }, +} + +impl Phase { + fn at_rest(warming: bool) -> Self { if warming { Self::Prewarmed } else { Self::OrderedOut } } + + fn warming(self) -> bool { + match self { + Self::OrderedOut => false, + Self::Prewarmed => true, + Self::Shown { warming } | Self::FadingIn { warming, .. } | Self::FadingOut { warming, .. } => warming, + } + } + + fn with_warming(self, warming: bool) -> Self { + match self { + Self::OrderedOut | Self::Prewarmed => Self::at_rest(warming), + Self::Shown { .. } => Self::Shown { warming }, + Self::FadingIn { fence, .. } => Self::FadingIn { fence, warming }, + Self::FadingOut { fence, seen, .. } => Self::FadingOut { fence, seen, warming }, + } + } +} + +#[derive(Clone, Copy, Debug)] +pub(crate) enum Event { + /// A show starts, fading in over `fade` (at once when zero). + Show { fade: Duration }, + /// A hide starts, fading out over `fade` (at once when zero). + Hide { fade: Duration }, + PrewarmBegins, + PrewarmEnds, + /// AppKit finished the fade started under `fence`. + FadeEnded { fence: Attempt }, + /// The app asked for capture exclusion on or off. + Request { exclude: bool }, +} + +/// What a transition asks of AppKit, in order. +#[derive(Clone, Copy, Debug, PartialEq)] +pub(crate) enum Effect { + /// `sharingType` none when true, read-only when false. + SetSharing(bool), + /// Puts a panel that joins every Space back on all of them. May order it out. + RejoinSpaces, + /// Orders in if AppKit doesn't have it in, dropping its alpha to zero first if asked. + OrderIn { clear_alpha: bool }, + OrderOut, + SetAlpha(f64), + IgnoreMouse, + /// Switches what `occlusionState` answers (`Presence::draws_occluded`). + DrawOccluded(bool), + /// Takes the alpha to `alpha`, replacing any fade in flight: over a length, answering with + /// `Event::FadeEnded` under its fence, or at once. + Fade { alpha: f64, over: Option<(Duration, Attempt)> }, + ResignKey, +} + +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub(crate) struct Presence { + phase: Phase, + /// Issues every show's and hide's fence, so a finished fade acts only if nothing came after. + fences: Seq, + requested: bool, + /// What `occlusionState` answers. It trails the phase on purpose: an observer inside + /// `orderFrontRegardless` reads it, and must see an alpha-zero panel as occluded until a + /// fade starts or a prewarm has ordered in. + draws_occluded: bool, +} + +impl Presence { + pub(crate) fn new(requested: bool) -> Self { Self { requested, ..Self::default() } } + + /// What the app asked for, shown or not. + pub(crate) fn requested(self) -> bool { self.requested } + + /// Whether `sharingType` should be none now; read-only otherwise. + pub(crate) fn excluded(self) -> bool { self.requested && self.ordered() } + + /// Outside a scoped prewarm acquisition, only a shown or fading-out panel is ordered in. + pub(crate) fn ordered(self) -> bool { + match self.phase { + Phase::OrderedOut | Phase::Prewarmed => false, + Phase::Shown { .. } | Phase::FadingIn { .. } => true, + Phase::FadingOut { seen, .. } => seen, + } + } + + /// Whether the app wants it seen: from a show until the next hide, so not during a fade-out. + pub(crate) fn visible(self) -> bool { matches!(self.phase, Phase::Shown { .. } | Phase::FadingIn { .. }) } + + /// Whether `occlusionState` reports the panel visible, so it may draw though AppKit calls + /// it occluded while its alpha is near zero. + pub(crate) fn draws_occluded(self) -> bool { self.draws_occluded } + + pub(crate) fn with_draws_occluded(self, draws_occluded: bool) -> Self { Self { draws_occluded, ..self } } + + /// What `draws_occluded` settles on in this phase: a prewarm acquisition or a fade. + fn wants_draw_occluded(self) -> bool { + self.phase.warming() || matches!(self.phase, Phase::FadingIn { .. } | Phase::FadingOut { .. }) + } + + pub(crate) fn step(&mut self, event: Event) -> Effects<Effect> { + match event { + Event::Show { fade } => self.show(fade), + Event::Hide { fade } => self.hide(fade), + Event::PrewarmBegins => { + self.phase = self.phase.with_warming(true); + Effects::Many(vec![Effect::SetAlpha(0.0), Effect::IgnoreMouse, Effect::OrderIn { clear_alpha: false }, Effect::DrawOccluded(true)]) + } + Event::PrewarmEnds => { + self.phase = self.phase.with_warming(false); + let mut effects = Effects::one(Effect::DrawOccluded(self.wants_draw_occluded())); + if !self.ordered() { effects.push(Effect::OrderOut); } + effects + } + Event::FadeEnded { fence } => self.fade_ended(fence), + Event::Request { exclude } => { + self.requested = exclude; + Effects::one(Effect::SetSharing(self.excluded())) + } + } + } + + /// Excluded before any of it can be seen: before it orders in or its alpha rises. + fn show(&mut self, fade: Duration) -> Effects<Effect> { + let (fence, warming, fading) = (self.fences.next(), self.phase.warming(), !fade.is_zero()); + self.phase = if fading { Phase::FadingIn { fence, warming } } else { Phase::Shown { warming } }; + Effects::Many(vec![ + Effect::SetSharing(self.excluded()), + Effect::RejoinSpaces, + Effect::OrderIn { clear_alpha: fading }, + Effect::DrawOccluded(self.wants_draw_occluded()), + Effect::Fade { alpha: 1.0, over: fading.then_some((fade, fence)) }, + ]) + } + + /// Clicks and scrolls go to the window below for the whole fade. Shown until the fade-out + /// finishes, so the exclusion holds while it can still be seen. A fade it replaces stops + /// counting as drawing during the setup, and its own starts counting with its alpha. + fn hide(&mut self, fade: Duration) -> Effects<Effect> { + let (fence, warming, fading, seen) = (self.fences.next(), self.phase.warming(), !fade.is_zero(), self.ordered()); + self.phase = if fading { Phase::FadingOut { fence, seen, warming } } else { Phase::at_rest(warming) }; + let mut effects = Effects::Many(vec![ + Effect::DrawOccluded(warming), + Effect::IgnoreMouse, + Effect::DrawOccluded(self.wants_draw_occluded()), + Effect::Fade { alpha: 0.0, over: fading.then_some((fade, fence)) }, + ]); + if !fading { effects.push(Effect::OrderOut); } + effects.push(Effect::ResignKey); + effects.push(Effect::SetSharing(self.excluded())); + effects + } + + /// A fade-out's end orders out before restoring sharing. A fence the phase doesn't hold + /// belongs to a fade a later show or hide replaced. + fn fade_ended(&mut self, ended: Attempt) -> Effects<Effect> { + match self.phase { + Phase::FadingIn { fence, warming } if fence == ended => { + self.phase = Phase::Shown { warming }; + Effects::one(Effect::DrawOccluded(warming)) + } + Phase::FadingOut { fence, warming, .. } if fence == ended => { + self.phase = Phase::at_rest(warming); + Effects::Many(vec![Effect::DrawOccluded(warming), Effect::OrderOut, Effect::SetSharing(self.excluded())]) + } + _ => Effects::none(), + } + } +} + +#[cfg(test)] +#[path = "presence_tests.rs"] +mod tests; diff --git a/app/vendor/rune/crates/rune/src/platform/macos/presence_tests.rs b/app/vendor/rune/crates/rune/src/platform/macos/presence_tests.rs new file mode 100644 index 0000000..0fc6c4b --- /dev/null +++ b/app/vendor/rune/crates/rune/src/platform/macos/presence_tests.rs @@ -0,0 +1,428 @@ +use std::time::Duration; +use crate::machine::Attempt; +use super::{Effect, Event, Presence}; + +const FADE: Duration = Duration::from_millis(200); +const NOW: Duration = Duration::ZERO; + +/// Carries out one effect's part in the state, as `carry_out` does. +fn apply(p: &mut Presence, effect: Effect) { + if let Effect::DrawOccluded(on) = effect { *p = p.with_draws_occluded(on); } +} + +/// Each effect in order, with what `occlusionState` answers while AppKit carries it out. +fn carried(p: &mut Presence, event: Event) -> Vec<(Effect, bool)> { + p.step(event).into_iter().map(|effect| { + let answer = p.draws_occluded(); + apply(p, effect); + (effect, answer) + }).collect() +} + +fn step(p: &mut Presence, event: Event) -> Vec<Effect> { carried(p, event).into_iter().map(|(effect, _)| effect).collect() } + +/// What `occlusionState` answers during the first effect `is` picks out. +fn answer_during(carried: &[(Effect, bool)], is: impl Fn(&Effect) -> bool) -> bool { + carried.iter().find(|(effect, _)| is(effect)).expect("the effect").1 +} + +fn is_order_in(effect: &Effect) -> bool { matches!(effect, Effect::OrderIn { .. }) } +fn is_fade(effect: &Effect) -> bool { matches!(effect, Effect::Fade { .. }) } +fn position(effects: &[Effect], is: impl Fn(&Effect) -> bool) -> usize { effects.iter().position(is).expect("the effect") } + +/// Starts a fade and returns its fence. +fn fence_of(p: &mut Presence, event: Event) -> Attempt { + step(p, event).into_iter().find_map(|effect| match effect { + Effect::Fade { over: Some((_, fence)), .. } => Some(fence), + _ => None, + }).expect("a fade with a length") +} + +fn show_fading(p: &mut Presence) -> Attempt { fence_of(p, Event::Show { fade: FADE }) } +fn hide_fading(p: &mut Presence) -> Attempt { fence_of(p, Event::Hide { fade: FADE }) } +fn show_now(p: &mut Presence) { step(p, Event::Show { fade: NOW }); } +fn hide_now(p: &mut Presence) { step(p, Event::Hide { fade: NOW }); } + +/// The fade's completion is stale: nothing is asked and nothing moves. +fn assert_stale(p: &mut Presence, fence: Attempt) { + let before = *p; + assert_eq!(step(p, Event::FadeEnded { fence }), vec![]); + assert_eq!(*p, before); +} + +#[test] +fn a_show_excludes_before_it_orders_in_and_its_alpha_rises() { + let mut p = Presence::new(true); + let fence = Attempt(1); + assert_eq!(step(&mut p, Event::Show { fade: FADE }), vec![ + Effect::SetSharing(true), + Effect::RejoinSpaces, + Effect::OrderIn { clear_alpha: true }, + Effect::DrawOccluded(true), + Effect::Fade { alpha: 1.0, over: Some((FADE, fence)) }, + ]); +} + +#[test] +fn a_show_without_a_fade_keeps_its_alpha_until_it_lands() { + let mut p = Presence::new(false); + assert_eq!(step(&mut p, Event::Show { fade: NOW }), vec![ + Effect::SetSharing(false), + Effect::RejoinSpaces, + Effect::OrderIn { clear_alpha: false }, + Effect::DrawOccluded(false), + Effect::Fade { alpha: 1.0, over: None }, + ]); + assert!(p.visible() && !p.draws_occluded()); +} + +#[test] +fn a_hide_stops_input_first_and_a_fade_keeps_the_panel_ordered() { + let mut p = Presence::new(true); + show_now(&mut p); + assert_eq!(step(&mut p, Event::Hide { fade: FADE }), vec![ + Effect::DrawOccluded(false), + Effect::IgnoreMouse, + Effect::DrawOccluded(true), + Effect::Fade { alpha: 0.0, over: Some((FADE, Attempt(2))) }, + Effect::ResignKey, + Effect::SetSharing(true), + ], "the fade-out is still on screen, so it stays excluded and ordered"); +} + +#[test] +fn a_hide_without_a_fade_orders_out_before_restoring_sharing() { + let mut p = Presence::new(true); + show_now(&mut p); + assert_eq!(step(&mut p, Event::Hide { fade: NOW }), vec![ + Effect::DrawOccluded(false), + Effect::IgnoreMouse, + Effect::DrawOccluded(false), + Effect::Fade { alpha: 0.0, over: None }, + Effect::OrderOut, + Effect::ResignKey, + Effect::SetSharing(false), + ]); + assert!(!p.ordered(), "resetting sharing alone cannot remove a panel from Spaces"); + assert!(!p.excluded() && p.requested()); +} + +#[test] +fn a_fade_out_ends_by_ordering_out_then_restoring_sharing() { + let mut p = Presence::new(true); + show_now(&mut p); + let out = hide_fading(&mut p); + assert!(p.ordered() && p.excluded() && !p.visible()); + assert!(p.draws_occluded(), "a fading-out overlay still draws its exit"); + assert_eq!(step(&mut p, Event::FadeEnded { fence: out }), vec![Effect::DrawOccluded(false), Effect::OrderOut, Effect::SetSharing(false)]); + assert!(!p.ordered() && !p.excluded() && !p.draws_occluded()); +} + +#[test] +fn a_fade_in_ends_shown_and_asks_for_nothing() { + let mut p = Presence::new(true); + let fence = show_fading(&mut p); + assert!(p.visible() && p.draws_occluded()); + assert_eq!(step(&mut p, Event::FadeEnded { fence }), vec![Effect::DrawOccluded(false)]); + assert!(p.visible() && p.excluded() && !p.draws_occluded()); +} + +#[test] +fn a_hide_during_a_fade_in_replaces_it() { + let mut p = Presence::new(true); + let shown = show_fading(&mut p); + let out = hide_fading(&mut p); + assert!(!p.visible() && p.ordered() && p.draws_occluded()); + assert_stale(&mut p, shown); + assert!(p.ordered(), "the replaced fade-in must not finish the fade-out"); + assert_eq!(step(&mut p, Event::FadeEnded { fence: out }), vec![Effect::DrawOccluded(false), Effect::OrderOut, Effect::SetSharing(false)]); + + let mut p = Presence::new(true); + let shown = show_fading(&mut p); + hide_now(&mut p); + assert!(!p.ordered() && !p.draws_occluded()); + assert_stale(&mut p, shown); + assert!(!p.excluded(), "a stale fade-in must not bring the panel back"); +} + +#[test] +fn a_show_during_a_fade_out_wins() { + let mut p = Presence::new(true); + show_now(&mut p); + let out = hide_fading(&mut p); + let back = show_fading(&mut p); + assert_stale(&mut p, out); + assert!(p.ordered() && p.visible(), "a stale completion must not order out the new show"); + assert!(p.draws_occluded(), "the fade back in is still running"); + assert_eq!(step(&mut p, Event::FadeEnded { fence: back }), vec![Effect::DrawOccluded(false)]); + assert!(p.excluded() && !p.draws_occluded()); + + let mut p = Presence::new(true); + show_now(&mut p); + let out = hide_fading(&mut p); + show_now(&mut p); + assert!(!p.draws_occluded(), "an immediate show ends the fade"); + assert_stale(&mut p, out); + assert!(p.ordered() && p.excluded()); +} + +#[test] +fn a_second_hide_during_a_fade_out_replaces_it() { + let mut p = Presence::new(true); + show_now(&mut p); + let first = hide_fading(&mut p); + let second = hide_fading(&mut p); + assert_stale(&mut p, first); + assert!(p.ordered(), "the panel fades until the second hide finishes"); + assert_eq!(step(&mut p, Event::FadeEnded { fence: second }), vec![Effect::DrawOccluded(false), Effect::OrderOut, Effect::SetSharing(false)]); +} + +#[test] +fn a_prewarmed_panel_is_not_excluded_until_it_shows() { + let mut p = Presence::new(true); + assert_eq!(step(&mut p, Event::PrewarmBegins), vec![Effect::SetAlpha(0.0), Effect::IgnoreMouse, Effect::OrderIn { clear_alpha: false }, Effect::DrawOccluded(true)]); + assert!(!p.ordered() && !p.visible() && p.draws_occluded()); + assert!(p.requested() && !p.excluded(), "a hidden prewarmed panel would blank every Space's thumbnail"); + assert_eq!(step(&mut p, Event::PrewarmEnds), vec![Effect::DrawOccluded(false), Effect::OrderOut], "prewarm keeps the surface, not window ordering"); + assert!(!p.draws_occluded()); + show_now(&mut p); + assert!(p.excluded(), "applied before the alpha starts rising"); +} + +#[test] +fn a_hide_during_a_prewarm_orders_out_and_the_guard_orders_out_again() { + let mut p = Presence::new(true); + step(&mut p, Event::PrewarmBegins); + assert!(step(&mut p, Event::Hide { fade: NOW }).contains(&Effect::OrderOut)); + assert!(p.draws_occluded(), "the acquisition still runs until its guard ends"); + assert_eq!(step(&mut p, Event::PrewarmEnds), vec![Effect::DrawOccluded(false), Effect::OrderOut]); + assert!(!p.draws_occluded() && !p.ordered()); +} + +#[test] +fn a_fading_hide_of_a_prewarmed_panel_holds_no_place_on_screen() { + let mut p = Presence::new(true); + step(&mut p, Event::PrewarmBegins); + let out = hide_fading(&mut p); + assert!(!p.ordered() && !p.excluded(), "it was never shown"); + assert_eq!(step(&mut p, Event::PrewarmEnds), vec![Effect::DrawOccluded(true), Effect::OrderOut]); + assert!(p.draws_occluded(), "the fade outlives the guard"); + assert_eq!(step(&mut p, Event::FadeEnded { fence: out }), vec![Effect::DrawOccluded(false), Effect::OrderOut, Effect::SetSharing(false)]); + assert!(!p.draws_occluded()); +} + +#[test] +fn a_hide_after_a_prewarm_before_any_show_still_runs_its_fade() { + let mut p = Presence::new(true); + step(&mut p, Event::PrewarmBegins); + step(&mut p, Event::PrewarmEnds); + let out = hide_fading(&mut p); + assert!(!p.ordered() && !p.excluded() && p.draws_occluded()); + assert_eq!(step(&mut p, Event::FadeEnded { fence: out }), vec![Effect::DrawOccluded(false), Effect::OrderOut, Effect::SetSharing(false)]); + assert!(!p.draws_occluded()); +} + +#[test] +fn a_show_during_a_prewarm_survives_the_guard() { + let mut p = Presence::new(true); + step(&mut p, Event::PrewarmBegins); + let fence = show_fading(&mut p); + assert_eq!(step(&mut p, Event::PrewarmEnds), vec![Effect::DrawOccluded(true)], "the show keeps it ordered in"); + assert!(p.ordered() && p.excluded() && p.draws_occluded()); + step(&mut p, Event::FadeEnded { fence }); + assert!(!p.draws_occluded()); +} + +#[test] +fn a_prewarm_during_a_fade_out_leaves_its_fence_alone() { + let mut p = Presence::new(true); + show_now(&mut p); + let out = hide_fading(&mut p); + step(&mut p, Event::PrewarmBegins); + assert_eq!(step(&mut p, Event::PrewarmEnds), vec![Effect::DrawOccluded(true)], "still fading, so still ordered in"); + assert!(p.draws_occluded()); + assert_eq!(step(&mut p, Event::FadeEnded { fence: out }), vec![Effect::DrawOccluded(false), Effect::OrderOut, Effect::SetSharing(false)]); +} + +#[test] +fn a_fade_out_ending_inside_a_prewarm_keeps_the_acquisition_readable() { + let mut p = Presence::new(true); + show_now(&mut p); + let out = hide_fading(&mut p); + step(&mut p, Event::PrewarmBegins); + step(&mut p, Event::FadeEnded { fence: out }); + assert!(!p.ordered() && p.draws_occluded()); + assert_eq!(step(&mut p, Event::PrewarmEnds), vec![Effect::DrawOccluded(false), Effect::OrderOut]); + assert!(!p.draws_occluded()); +} + +#[test] +fn a_show_switches_the_occlusion_override_after_ordering_in_and_at_its_fade() { + let mut p = Presence::new(false); + let show = carried(&mut p, Event::Show { fade: FADE }); + assert!(!answer_during(&show, is_order_in), "an observer inside orderFrontRegardless sees an alpha-zero panel as occluded"); + assert!(answer_during(&show, is_fade), "on before the alpha starts rising"); + let effects: Vec<Effect> = show.iter().map(|(effect, _)| *effect).collect(); + let (ordered, switched, faded) = (position(&effects, is_order_in), position(&effects, |e| matches!(e, Effect::DrawOccluded(_))), position(&effects, is_fade)); + assert!(ordered < switched && switched < faded, "{effects:?}"); +} + +#[test] +fn a_show_during_a_fade_keeps_the_prior_override_while_it_orders_in() { + let mut p = Presence::new(false); + show_now(&mut p); + hide_fading(&mut p); + let show = carried(&mut p, Event::Show { fade: NOW }); + assert!(answer_during(&show, is_order_in), "the fade it replaces still counts until its own starts"); + assert!(!answer_during(&show, is_fade)); +} + +#[test] +fn a_prewarm_switches_the_occlusion_override_only_after_ordering_in() { + let mut p = Presence::new(false); + let warm = carried(&mut p, Event::PrewarmBegins); + assert!(!answer_during(&warm, is_order_in), "an observer inside orderFrontRegardless sees an alpha-zero panel as occluded"); + let effects: Vec<Effect> = warm.iter().map(|(effect, _)| *effect).collect(); + assert!(position(&effects, is_order_in) < position(&effects, |e| matches!(e, Effect::DrawOccluded(true))), "{effects:?}"); + assert!(p.draws_occluded()); +} + +#[test] +fn a_hide_clears_a_replaced_fades_override_during_its_setup() { + let mut p = Presence::new(false); + show_fading(&mut p); + let hide = carried(&mut p, Event::Hide { fade: FADE }); + assert!(!answer_during(&hide, |e| matches!(e, Effect::IgnoreMouse))); + assert!(answer_during(&hide, is_fade), "its own fade counts from the start"); +} + +#[test] +fn a_toggle_while_hidden_waits_for_the_next_show() { + let mut p = Presence::new(false); + assert_eq!(step(&mut p, Event::Request { exclude: true }), vec![Effect::SetSharing(false)]); + assert!(p.requested() && !p.excluded()); + show_now(&mut p); + assert!(p.excluded()); + assert_eq!(step(&mut p, Event::Request { exclude: false }), vec![Effect::SetSharing(false)], "a toggle while shown applies at once"); + hide_now(&mut p); + step(&mut p, Event::Request { exclude: true }); + step(&mut p, Event::Request { exclude: false }); + show_now(&mut p); + assert!(!p.excluded(), "the last request wins"); +} + +/// The flags and generation `Panel` kept before `Phase`, written out call by call, as the +/// reference for what `step` must ask of AppKit. +#[derive(Clone, Copy, Debug, Default)] +struct Flags { generation: u32, shown: bool, requested: bool, visible: bool, revealing: bool, warming: bool } + +impl Flags { + fn answer(self) -> bool { self.warming || self.revealing } + + fn fade_to(&mut self, alpha: f64, length: Duration, out: &mut Vec<Effect>) { + let fading = !length.is_zero(); + self.revealing = fading; + out.push(Effect::DrawOccluded(self.answer())); + out.push(Effect::Fade { alpha, over: fading.then_some((length, Attempt(self.generation))) }); + if !fading && !self.shown { out.push(Effect::OrderOut); } + } + + fn show(&mut self, fade: Duration) -> Vec<Effect> { + let mut out = vec![]; + self.visible = true; + self.shown = true; + self.generation += 1; + out.push(Effect::SetSharing(self.requested && self.shown)); + out.push(Effect::RejoinSpaces); + out.push(Effect::OrderIn { clear_alpha: !fade.is_zero() }); + self.fade_to(1.0, fade, &mut out); + out + } + + fn hide(&mut self, fade: Duration) -> Vec<Effect> { + let mut out = vec![]; + self.visible = false; + self.revealing = false; + out.push(Effect::DrawOccluded(self.answer())); + out.push(Effect::IgnoreMouse); + if fade.is_zero() { self.shown = false; } + self.generation += 1; + let excluded = self.requested && self.shown; + self.fade_to(0.0, fade, &mut out); + out.push(Effect::ResignKey); + out.push(Effect::SetSharing(excluded)); + out + } + + fn prewarm(&mut self) -> Vec<Effect> { + self.warming = true; + vec![Effect::SetAlpha(0.0), Effect::IgnoreMouse, Effect::OrderIn { clear_alpha: false }, Effect::DrawOccluded(self.answer())] + } + + fn prewarm_ends(&mut self) -> Vec<Effect> { + self.warming = false; + let mut out = vec![Effect::DrawOccluded(self.answer())]; + if !self.shown { out.push(Effect::OrderOut); } + out + } + + fn fade_done(&mut self, generation: u32, hiding: bool) -> Vec<Effect> { + if generation != self.generation { return vec![]; } + if hiding { self.shown = false; } + self.revealing = false; + let mut out = vec![Effect::DrawOccluded(self.answer())]; + if !self.shown { out.push(Effect::OrderOut); } + if hiding { out.push(Effect::SetSharing(self.requested && self.shown)); } + out + } +} + +#[derive(Clone, Copy, Debug)] +enum Step { Show(Duration), Hide(Duration), Prewarm, PrewarmEnds, Toggle, EndOldest, EndNewest } + +const STEPS: [Step; 9] = [Step::Show(FADE), Step::Show(NOW), Step::Hide(FADE), Step::Hide(NOW), Step::Prewarm, Step::PrewarmEnds, Step::Toggle, Step::EndOldest, Step::EndNewest]; + +/// Every path from this state, comparing `step` with the flags after each event. AppKit delivers +/// each fade's completion once, in any order, however long after it was replaced. +fn walk(p: Presence, flags: Flags, fades: &[(u32, bool)], depth: usize, trail: &mut Vec<Step>) { + if depth == 0 { return; } + for step in STEPS { + let (mut p, mut flags, mut fades) = (p, flags, fades.to_vec()); + trail.push(step); + let (asked, expected) = match step { + Step::Show(fade) => (p.step(Event::Show { fade }), flags.show(fade)), + Step::Hide(fade) => (p.step(Event::Hide { fade }), flags.hide(fade)), + Step::Prewarm => (p.step(Event::PrewarmBegins), flags.prewarm()), + Step::PrewarmEnds => (p.step(Event::PrewarmEnds), flags.prewarm_ends()), + Step::Toggle => { + flags.requested = !flags.requested; + (p.step(Event::Request { exclude: flags.requested }), vec![Effect::SetSharing(flags.requested && flags.shown)]) + } + Step::EndOldest | Step::EndNewest => { + if fades.is_empty() { trail.pop(); continue; } + let (generation, hiding) = fades.remove(if matches!(step, Step::EndOldest) { 0 } else { fades.len() - 1 }); + (p.step(Event::FadeEnded { fence: Attempt(generation) }), flags.fade_done(generation, hiding)) + } + }; + let asked: Vec<Effect> = asked.into_iter().collect(); + assert_eq!(asked, expected, "{trail:?}"); + for effect in &asked { + apply(&mut p, *effect); + if let Effect::Fade { alpha, over: Some((_, fence)) } = effect { fades.push((fence.0, *alpha == 0.0)); } + } + assert_eq!(p.visible(), flags.visible, "{trail:?}"); + assert_eq!(p.ordered(), flags.shown, "hidden panels must leave Spaces regardless of their sharing history: {trail:?}"); + assert_eq!(p.excluded(), flags.requested && flags.shown, "{trail:?}"); + assert_eq!(p.requested(), flags.requested, "{trail:?}"); + assert_eq!(p.draws_occluded(), flags.answer(), "{trail:?}"); + walk(p, flags, &fades, depth - 1, trail); + trail.pop(); + } +} + +#[test] +fn every_sequence_asks_appkit_for_what_the_flags_did() { + for requested in [false, true] { + walk(Presence::new(requested), Flags { requested, ..Flags::default() }, &[], 6, &mut vec![]); + } +} diff --git a/app/vendor/rune/crates/rune/src/platform/macos/presentation.rs b/app/vendor/rune/crates/rune/src/platform/macos/presentation.rs new file mode 100644 index 0000000..a6b3612 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/platform/macos/presentation.rs @@ -0,0 +1,127 @@ +//! Native panel presentation: prewarm, sharing, and fenced fades. `Presence` decides; this +//! carries out what it asks of AppKit. + +use std::{cell::Cell, rc::Rc, time::Duration}; +use objc2::{msg_send, rc::Retained}; +use objc2_app_kit::NSPanel; +use crate::machine::{Attempt, Effects}; +use super::{Panel, set_sharing}; +use super::presence::{Effect, Event, Presence}; + +pub(crate) struct Prewarm { + presence: Rc<Cell<Presence>>, + panel: Retained<NSPanel>, +} +impl Drop for Prewarm { + fn drop(&mut self) { + let effects = step(&self.presence, Event::PrewarmEnds); + carry_out(&self.panel, &self.presence, effects); + } +} + +/// Copied out and back, so nothing is held while AppKit runs: a fade's completion can step it +/// from inside `carry_out`. +fn step(presence: &Cell<Presence>, event: Event) -> Effects<Effect> { + let mut now = presence.get(); + let effects = now.step(event); + presence.set(now); + effects +} + +fn carry_out(panel: &Retained<NSPanel>, presence: &Rc<Cell<Presence>>, effects: Effects<Effect>) { + for effect in effects { + match effect { + Effect::SetSharing(exclude) => set_sharing(panel, exclude), + Effect::RejoinSpaces => rejoin_spaces(panel), + Effect::OrderIn { clear_alpha } => if !panel.isVisible() { + if clear_alpha { panel.setAlphaValue(0.0); } + panel.orderFrontRegardless(); + }, + Effect::OrderOut => panel.orderOut(None), + Effect::SetAlpha(alpha) => panel.setAlphaValue(alpha), + Effect::IgnoreMouse => panel.setIgnoresMouseEvents(true), + Effect::DrawOccluded(on) => presence.set(presence.get().with_draws_occluded(on)), + Effect::Fade { alpha, over } => fade(panel, presence, alpha, over), + Effect::ResignKey => panel.resignKeyWindow(), + } + } +} + +/// Puts a panel that joins every Space back on all of them before it orders in. After the +/// app's activation policy changes (its Dock icon shown or hidden), the window server can +/// tie such a panel to one Space while AppKit still reports the old mask, and setting the +/// same mask again changes nothing. Clearing it and setting it back makes the window +/// server apply it again. A panel still shown on another Space orders out first, so `show` +/// orders it back in on this one. +fn rejoin_spaces(panel: &NSPanel) { + use objc2_app_kit::NSWindowCollectionBehavior as Behavior; + let behavior = panel.collectionBehavior(); + if !behavior.contains(Behavior::CanJoinAllSpaces) { return; } + if panel.isVisible() { + if panel.isOnActiveSpace() { return; } + panel.orderOut(None); + } + panel.setCollectionBehavior(Behavior::Default); + panel.setCollectionBehavior(behavior); +} + +/// Animates the panel's alpha to `alpha`, replacing any fade in flight. Over a length, its +/// completion reports back under the fence; with none, it lands at once. +#[allow(unsafe_code)] +fn fade(panel: &Retained<NSPanel>, presence: &Rc<Cell<Presence>>, alpha: f64, over: Option<(Duration, Attempt)>) { + use objc2::runtime::{AnyClass, AnyObject}; + // SAFETY: AppKit calls on the main thread; the completion handler runs there too. + unsafe { + if let Some(context) = AnyClass::get(c"NSAnimationContext") { + let _: () = msg_send![context, beginGrouping]; + let current: *mut AnyObject = msg_send![context, currentContext]; + let _: () = msg_send![current, setDuration: over.map_or(0.0, |(length, _)| length.as_secs_f64())]; + if let Some((_, fence)) = over { + let (panel, presence) = (panel.clone(), presence.clone()); + let done = block2::RcBlock::new(move || { + let effects = step(&presence, Event::FadeEnded { fence }); + carry_out(&panel, &presence, effects); + }); + let _: () = msg_send![current, setCompletionHandler: &*done]; + } + let animator: *mut AnyObject = msg_send![&**panel, animator]; + let _: () = msg_send![animator, setAlphaValue: alpha]; + let _: () = msg_send![context, endGrouping]; + } + if over.is_none() { panel.setAlphaValue(alpha); } + } +} + +impl Panel { + /// Reveals the panel, fading its alpha in over `fade` (instantly when zero). + pub fn show(&self, fade: Duration) { + self.keep_view(); + let effects = step(&self.presence, Event::Show { fade }); + self.refresh_monitors(); + self.pointer.observe(&self.panel, self.wake.as_ref()); + carry_out(&self.panel, &self.presence, effects); + } + + pub fn prewarm(&self) -> Prewarm { + debug_assert!(self.options.prewarm); + let effects = step(&self.presence, Event::PrewarmBegins); + carry_out(&self.panel, &self.presence, effects); + Prewarm { presence: self.presence.clone(), panel: self.panel.clone() } + } + + /// Hides the panel, fading its alpha out over `fade` (instantly when zero). Input stops at + /// once; `show` restores hit-testing through `pointer.observe`. + pub fn hide(&self, fade: Duration) { + let effects = step(&self.presence, Event::Hide { fade }); + self.stop_pointer(); + carry_out(&self.panel, &self.presence, effects); + } + + /// `sharingType` none while shown, or read-only so recorders see the panel again. Hidden, + /// the panel stays read-only and the request applies at its next show. + pub fn set_capture_exclusion(&self, exclude: bool) -> crate::OverlaySupport { + let effects = step(&self.presence, Event::Request { exclude }); + carry_out(&self.panel, &self.presence, effects); + self.capture_exclusion() + } +} diff --git a/app/vendor/rune/crates/rune/src/platform/macos/surface.rs b/app/vendor/rune/crates/rune/src/platform/macos/surface.rs new file mode 100644 index 0000000..4356623 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/platform/macos/surface.rs @@ -0,0 +1,159 @@ +//! Metal layer presentation and drawable visibility. + +#![allow(unsafe_code)] + +use objc2::msg_send; +use objc2_app_kit::NSWindow; +use super::ns_window; + +/// Presents the surface's drawables inside the current Core Animation transaction, so a +/// window frame change and the frame drawn for it reach the screen together. Costs a +/// wait for the GPU to schedule each frame, so it is on only while a frame moves. +pub(crate) fn present_with_transaction(surface: &wgpu::Surface, on: bool) { + use objc2::runtime::Bool; + // SAFETY: a live CAMetalLayer, on the main thread, between frames. + crate::gpu::with_layer(surface, |layer| unsafe { let _: () = msg_send![layer, setPresentsWithTransaction: Bool::new(on)]; }); +} + +#[link(name = "QuartzCore", kind = "framework")] +unsafe extern "C" { + static kCAGravityTopLeft: &'static objc2::runtime::AnyObject; + static kCAGravityBottomLeft: &'static objc2::runtime::AnyObject; +} + +/// The gravity that keeps a layer's contents at the window's top left. Core Animation names its +/// gravities for unflipped contents; under a flipped view (winit's is) "bottom" is the top. +fn top_left_gravity(contents_flipped: bool) -> &'static objc2::runtime::AnyObject { + // SAFETY: QuartzCore's constant strings. + unsafe { if contents_flipped { kCAGravityBottomLeft } else { kCAGravityTopLeft } } +} + +/// Pins the Metal layer's contents to the window's top left at their own size. A drawable that +/// doesn't match the layer yet (a frame that isn't drawn in time for a resize) is clipped or +/// leaves a strip, rather than stretched to the new size and snapped back a frame later. +/// Also tags the contents sRGB, as AppKit's own drawing is, so the compositor colour-matches +/// them to the display (untagged, a wide-gamut display shows them oversaturated). Either +/// surface format holds sRGB-encoded values; wgpu's reconfigures keep the tag. +pub(crate) fn pin_contents_top_left(surface: &wgpu::Surface) { + use objc2::runtime::Bool; + use objc2_core_graphics::{CGColorSpace, kCGColorSpaceSRGB}; + // SAFETY: a live CAMetalLayer, on the main thread, under wgpu's lock. + crate::gpu::with_layer(surface, |layer| unsafe { + let flipped: Bool = msg_send![layer, contentsAreFlipped]; + let _: () = msg_send![layer, setContentsGravity: top_left_gravity(flipped.as_bool())]; + let Some(srgb) = CGColorSpace::with_name(Some(kCGColorSpaceSRGB)) else { return }; + let _: () = msg_send![layer, setColorspace: &*srgb]; + }); +} + +/// Whether none of `window` is on screen: covered, or its displays asleep. AppKit keeps the +/// state from the window server's notifications, so reading it costs one message send. wgpu +/// declines a drawable on the same check. +pub(crate) fn window_occluded(window: &winit::window::Window) -> bool { + ns_window(window).is_some_and(|window| occlusion_hidden(&window)) +} + +/// Whether wgpu will decline this surface a drawable as occluded. It reads the window hosting +/// the layer: the first delegate up the layer tree is the backing view, and its window's +/// occlusion state is checked before `nextDrawable`. Asking wgpu anyway costs a texture id that +/// wgpu-core 30.0.1 never frees, so `acquire` asks this first. +pub(crate) fn surface_occluded(surface: &wgpu::Surface<'_>) -> bool { + // SAFETY: only reads the layer wgpu presents into, a CALayer, under wgpu's own lock. + crate::gpu::with_layer(surface, |layer| unsafe { layer_occluded(layer) }).unwrap_or(false) +} + +/// `surface_occluded` for a layer: the same walk as wgpu-hal's `hosting_window`. +/// +/// # Safety +/// `layer` is a CALayer. +pub(crate) unsafe fn layer_occluded(layer: &objc2::runtime::AnyObject) -> bool { + use objc2::runtime::AnyObject; + let mut current: *const AnyObject = layer; + // SAFETY: CALayer and NSView property reads; each pointer is live while its layer is. + unsafe { + while let Some(layer) = current.as_ref() { + let delegate: *const AnyObject = msg_send![layer, delegate]; + if let Some(delegate) = delegate.as_ref() { + let window: *const AnyObject = msg_send![delegate, window]; + let Some(window) = window.as_ref() else { return false }; + let state: usize = msg_send![window, occlusionState]; + return state & OCCLUSION_VISIBLE == 0; + } + current = msg_send![layer, superlayer]; + } + } + false +} + +const OCCLUSION_VISIBLE: usize = 1 << 1; + +objc2::define_class!( + /// The window `PresumeShown` puts in front of a layer: always on screen. + #[unsafe(super(objc2::runtime::NSObject))] + #[name = "RuneShownWindow"] + struct ShownWindow; + + impl ShownWindow { + #[unsafe(method(window))] + fn window(&self) -> *const Self { self } + + #[unsafe(method(occlusionState))] + fn occlusion_state(&self) -> usize { OCCLUSION_VISIBLE } + + #[unsafe(method(actionForLayer:forKey:))] + fn action_for_layer( + &self, + _: *const objc2::runtime::AnyObject, + _: *const objc2::runtime::AnyObject, + ) -> *const objc2::runtime::AnyObject { + let Some(null) = objc2::runtime::AnyClass::get(c"NSNull") else { return std::ptr::null() }; + // SAFETY: `NSNull` is a Foundation class whose `+null` returns the process-lifetime singleton pointer. + unsafe { msg_send![null, null] } + } + } +); + +/// While alive, a surface's window reads as on screen to wgpu's occlusion check and +/// `surface_occluded`: the layer's delegate, the first up the tree, is a stand-in that is its own +/// visible window. For a window's first frame, drawn while AppKit orders the window in and before +/// the window server reports it visible. A new layer's drawables are all free, so `nextDrawable` +/// can't stall the way it does for a covered window with frames still queued. +pub(crate) struct PresumeShown { + layer: objc2::rc::Retained<objc2::runtime::AnyObject>, + previous: Option<objc2::rc::Retained<objc2::runtime::AnyObject>>, + _stand_in: objc2::rc::Retained<ShownWindow>, +} + +impl PresumeShown { + /// `None` off Metal. + pub(crate) fn new(surface: &wgpu::Surface<'_>) -> Option<PresumeShown> { + use objc2::{ClassType, Message, rc::Retained, runtime::AnyObject}; + // The layer is retained here and the lock released, so wgpu can take it to acquire. Only + // messages every CALayer answers are sent to it. + let layer: Retained<AnyObject> = crate::gpu::with_layer(surface, |layer| layer.retain())?; + // SAFETY: CALayer delegate reads and writes on the main thread (window creation). + unsafe { + let previous: Option<Retained<AnyObject>> = msg_send![&*layer, delegate]; + let stand_in: Retained<ShownWindow> = msg_send![ShownWindow::class(), new]; + let _: () = msg_send![&*layer, setDelegate: &*stand_in]; + Some(PresumeShown { layer, previous, _stand_in: stand_in }) + } + } +} + +impl Drop for PresumeShown { + fn drop(&mut self) { + // SAFETY: as in `new`; restores the delegate the layer had. + unsafe { let _: () = msg_send![&*self.layer, setDelegate: self.previous.as_deref()]; } + } +} + +pub(super) fn occlusion_hidden(window: &NSWindow) -> bool { + // SAFETY: a property read on the main thread. + let state: usize = unsafe { msg_send![window, occlusionState] }; + state & OCCLUSION_VISIBLE == 0 +} + +#[cfg(test)] +#[path = "surface_tests.rs"] +mod tests; diff --git a/app/vendor/rune/crates/rune/src/platform/macos/surface_tests.rs b/app/vendor/rune/crates/rune/src/platform/macos/surface_tests.rs new file mode 100644 index 0000000..2c14b0a --- /dev/null +++ b/app/vendor/rune/crates/rune/src/platform/macos/surface_tests.rs @@ -0,0 +1,35 @@ +#![allow(unsafe_code)] + +use super::*; +use objc2::rc::Retained; + +/// A late drawable stays at the window's top left at its own size, rather than stretching +/// to a resized window: under winit's flipped view, and under an unflipped one. +#[test] +fn a_metal_layer_pins_its_contents_to_the_window_top_left() { + use objc2::runtime::{AnyClass, AnyObject, Bool}; + for flipped in [true, false] { + // SAFETY: new layers, used on this thread only. + let (parent, layer): (Retained<AnyObject>, Retained<AnyObject>) = unsafe { + (msg_send![AnyClass::get(c"CALayer").unwrap(), new], msg_send![AnyClass::get(c"CAMetalLayer").expect("QuartzCore"), new]) + }; + // SAFETY: `parent` and `layer` are valid retained `CALayer`/`CAMetalLayer` objects owned by this test. + unsafe { + let _: () = msg_send![&*parent, setGeometryFlipped: Bool::new(flipped)]; + let _: () = msg_send![&*parent, addSublayer: &*layer]; + } + let target = wgpu::SurfaceTargetUnsafe::CoreAnimationLayer(Retained::as_ptr(&layer) as *mut std::ffi::c_void); + // SAFETY: the layer outlives the surface. + let surface = unsafe { crate::render::Gpu::instance().create_surface_unsafe(target) }.expect("a Metal layer surface"); + pin_contents_top_left(&surface); + // SAFETY: `layer` is a live `CAMetalLayer`; `contentsGravity` returns a non-null `NSString`. + let gravity: Retained<objc2_foundation::NSString> = unsafe { msg_send![&*layer, contentsGravity] }; + assert_eq!(gravity.to_string(), if flipped { "bottomLeft" } else { "topLeft" }, "flipped: {flipped}"); + // SAFETY: `layer` is a live `CAMetalLayer`; `colorspace` returns a borrowed `CGColorSpaceRef` or null. + let space: *mut objc2_core_graphics::CGColorSpace = unsafe { msg_send![&*layer, colorspace] }; + // SAFETY: `space` is either null or the `CGColorSpace` borrowed from `layer`, which stays alive across the call. + let name = objc2_core_graphics::CGColorSpace::name(unsafe { space.as_ref() }).map(|n| n.to_string()); + assert_eq!(name.as_deref(), Some("kCGColorSpaceSRGB"), "the layer's contents are tagged sRGB"); + drop(surface); + } +} diff --git a/app/vendor/rune/crates/rune/src/platform/macos/traffic_lights.rs b/app/vendor/rune/crates/rune/src/platform/macos/traffic_lights.rs new file mode 100644 index 0000000..494d1bf --- /dev/null +++ b/app/vendor/rune/crates/rune/src/platform/macos/traffic_lights.rs @@ -0,0 +1,132 @@ +//! The traffic lights at the app's own spot (`Chrome::traffic_lights`). +//! +//! Since macOS 26, AppKit puts the buttons back at (9, 9) and the titlebar container back to +//! its own height whenever it lays the titlebar out again, which it does on its own (a title +//! or appearance change, a zoom), not only on the resizes the shell sees. So the container and +//! the buttons' own superview each get a subclass, for that instance only, whose `-layout` runs +//! AppKit's and then puts the buttons back. + +#![allow(unsafe_code)] + +use std::cell::{Cell, RefCell}; +use std::collections::HashMap; + +use objc2::rc::Retained; +use objc2::runtime::{AnyClass, AnyObject, ClassBuilder, Sel}; +use objc2::{msg_send, sel}; +use objc2_app_kit::{NSView, NSWindow, NSWindowButton, NSWindowStyleMask}; +use objc2_foundation::NSPoint; +use winit::window::Window; + +use crate::platform::macos::ns_window; + +thread_local! { + /// Each window's spot, by its `NSWindow` pointer, for the layout hook. + static SPOTS: RefCell<HashMap<usize, (f64, f64)>> = RefCell::new(HashMap::new()); + /// Set while the hook places, so the frames it sets don't place again. + static PLACING: Cell<bool> = const { Cell::new(false) }; +} + +/// Drops its window's spot when the window goes, so a later window at the same address +/// doesn't inherit it. +pub(crate) struct Spot(usize); + +impl Spot { + pub(crate) fn new(window: &Window) -> Spot { + Spot(ns_window(window).map_or(0, |w| Retained::as_ptr(&w) as usize)) + } +} + +impl Drop for Spot { + fn drop(&mut self) { + SPOTS.try_with(|s| s.borrow_mut().remove(&self.0)).ok(); + } +} + +/// Electron's `trafficLightPosition`: the titlebar container grows to the buttons' height +/// plus twice `y`, and the buttons sit `x, y` from the top-left at AppKit's own pitch. +pub(crate) fn place(window: &Window, (x, y): (f32, f32)) { + let Some(win) = ns_window(window) else { return }; + let spot = (f64::from(x), f64::from(y)); + SPOTS.with(|s| s.borrow_mut().insert(Retained::as_ptr(&win) as usize, spot)); + place_in(&win, spot); +} + +fn place_in(win: &NSWindow, (x, y): (f64, f64)) { + if win.styleMask().contains(NSWindowStyleMask::FullScreen) { + return; + } + let buttons = [NSWindowButton::CloseButton, NSWindowButton::MiniaturizeButton, NSWindowButton::ZoomButton] + .map(|b| win.standardWindowButton(b)); + let [Some(close), Some(mini), Some(zoom)] = buttons else { return }; + // SAFETY: AppKit's own view hierarchy, on the main thread. + let Some(parent) = (unsafe { close.superview() }) else { return }; + // SAFETY: `parent` is a live `NSView` in AppKit's window hierarchy on the main thread. + let Some(container) = (unsafe { parent.superview() }) else { return }; + // SAFETY: live views on the main thread. + unsafe { + hold(&parent); + hold(&container); + } + if PLACING.with(|p| p.replace(true)) { + return; + } + // A right-to-left app's titlebar lays out from the right (`labels::set_direction`), as AppKit + // lays out a right-to-left localization's: `x` in from the right edge, Close outermost (on macOS + // 27 a native window's Close sits at 687-701 of 720 points, against 19-33 left to right). AppKit's + // own `windowTitlebarLayoutDirection` follows the localization and has no setter, so Rune places + // them, as it does the spot. + let rtl = crate::labels::rtl(); + let pitch = (mini.frame().origin.x - close.frame().origin.x).abs(); + let mut frame = container.frame(); + frame.size.height = close.frame().size.height + 2.0 * y; + frame.origin.y = win.frame().size.height - frame.size.height; + let width = parent.frame().size.width; + container.setFrame(frame); + for (i, b) in [close, mini, zoom].iter().enumerate() { + let at = x + i as f64 * pitch; + let at = if rtl { width - at - b.frame().size.width } else { at }; + b.setFrameOrigin(NSPoint::new(at, y)); + } + PLACING.with(|p| p.set(false)); +} + +/// Runs AppKit's `-layout` for the view's real class, then puts the buttons back. +unsafe extern "C" fn layout(view: &NSView, _: Sel) { + // Not `view.class()`'s superclass: entering full screen, AppKit observes the container and + // KVO puts its own subclass above Rune's, whose superclass is Rune's again. + let base = held_class(view).and_then(AnyClass::superclass).expect("Rune traffic-light view has a superclass"); + // SAFETY: `base` is the class this instance had before `hold`, which implements -layout. + let _: () = unsafe { msg_send![super(view, base), layout] }; + if PLACING.with(Cell::get) { + return; + } + let Some(win) = view.window() else { return }; + let Some(spot) = SPOTS.with(|s| s.borrow().get(&(Retained::as_ptr(&win) as usize)).copied()) else { return }; + place_in(&win, spot); +} + +/// Gives this one view a subclass of its own class whose `-layout` places the buttons again. +unsafe fn hold(view: &NSView) { + if held_class(view).is_some() { + return; + } + let base = view.class(); + let Ok(name) = std::ffi::CString::new(format!("RuneTrafficLights_{}", base.name().to_string_lossy())) else { return }; + let class = match ClassBuilder::new(&name, base) { + Some(mut builder) => { + // SAFETY: the signature matches -[NSView layout]. + unsafe { builder.add_method(sel!(layout), layout as unsafe extern "C" fn(_, _)) }; + builder.register() + } + None => AnyClass::get(&name).expect("register Rune traffic-light view"), + }; + // SAFETY: a live view on the main thread. Only its isa changes, to a subclass without + // ivars; the original class is never modified. + unsafe { AnyObject::set_class(view, class) }; +} + +/// The subclass `hold` gave this view, wherever it sits in the view's class chain. +fn held_class(view: &NSView) -> Option<&'static AnyClass> { + std::iter::successors(Some(view.class()), |c| c.superclass()).find(|c| c.name().to_bytes().starts_with(b"RuneTrafficLights_")) +} diff --git a/app/vendor/rune/crates/rune/src/platform/macos/window_shape.rs b/app/vendor/rune/crates/rune/src/platform/macos/window_shape.rs new file mode 100644 index 0000000..8347cc5 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/platform/macos/window_shape.rs @@ -0,0 +1,141 @@ +//! Rounded corners and shadow re-sampling for transparent macOS windows. +//! +//! A transparent, borderless window has no frame to round it, so +//! `MacWindowOptions::corner_radius` rounds the content view's layer. wgpu's CAMetalLayer and +//! the native material views are its sublayers, so `masksToBounds` clips them all. +//! +//! The window server draws a transparent window's shadow from the window's pixels. It samples +//! them when the window orders in or changes size, usually before Rune's frame for that state +//! has landed, and keeps the outline of an empty or older frame. `-[NSWindow invalidateShadow]` +//! asks it to sample again. [`Resample`] decides when: once, after the first frame presented +//! since a show, resize, scale change or launcher prewarm has reached the screen, as Metal's +//! presented handler reports it (`present_time::metal`). Calling earlier would sample the old +//! pixels again; ordinary frames never call it. + +use crate::frame::present_time::metal::{wake_main, Log}; +use objc2::msg_send; +use objc2::rc::Retained; +use objc2::runtime::AnyObject; +use objc2_app_kit::NSWindow; +use std::cell::Cell; +use std::sync::Arc; + +#[link(name = "QuartzCore", kind = "framework")] +#[allow(unsafe_code)] +unsafe extern "C" { + static kCACornerCurveContinuous: &'static AnyObject; + static kCACornerCurveCircular: &'static AnyObject; +} + +/// Rounds the window's content layer when the options ask for it and the window is +/// transparent and borderless. Runs on each native creation, after wgpu adds its layer. +#[allow(unsafe_code)] +pub(crate) fn apply_corners(window: &winit::window::Window, options: &crate::MacWindowOptions, transparent: bool, borderless: bool) { + let Some(radius) = options.corner_radius.filter(|_| transparent && borderless) else { return }; + let Some(view) = crate::platform::macos::content_view(window) else { return }; + // SAFETY: AppKit and Core Animation calls on the main thread; the layer is the view's own. + unsafe { + let layer: *mut AnyObject = msg_send![&*view, layer]; + let Some(layer) = layer.as_ref() else { return }; + let curve = if options.corner_curve_circular { kCACornerCurveCircular } else { kCACornerCurveContinuous }; + let _: () = msg_send![layer, setCornerRadius: f64::from(radius)]; + let _: () = msg_send![layer, setCornerCurve: curve]; + let _: () = msg_send![layer, setMasksToBounds: true]; + } +} + +/// When to re-sample a transparent window's shadow. Drawables are numbered by [`Log`]. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(crate) enum Resample { + #[default] + Idle, + /// Once the next frame presents. + NextFrame, + /// Once drawable `n` is on screen. + OnScreen(u64), +} + +impl Resample { + /// Ordered in or revealed. The last presented drawable (0 for none) will do, since a + /// reveal of cached pixels draws nothing new. A frame already awaited stays awaited. + pub(crate) fn shown(&mut self, last: u64) { + if *self == Resample::Idle { *self = if last > 0 { Resample::OnScreen(last) } else { Resample::NextFrame }; } + } + + /// Resized, rescaled or prewarmed: only a frame drawn for the new state will do. + pub(crate) fn redraw(&mut self) { *self = Resample::NextFrame; } + + /// Drawable `n` was presented. + pub(crate) fn presented(&mut self, n: u64) { + if *self == Resample::NextFrame { *self = Resample::OnScreen(n); } + } + + pub(crate) fn hidden(&mut self) { *self = Resample::Idle; } + + /// A run loop turn, with the newest drawable on screen. True once: re-sample now. + pub(crate) fn turn(&mut self, on_screen: u64) -> bool { + let due = self.due(on_screen); + if due { *self = Resample::Idle; } + due + } + + /// Whether the drawable it awaits is already on screen. + fn due(self, on_screen: u64) -> bool { matches!(self, Resample::OnScreen(n) if on_screen >= n) } +} + +/// Whether a window re-samples its shadow: transparent, with the system shadow on. +pub(crate) fn resamples(window: &winit::window::Window, transparent: bool) -> bool { + transparent && crate::platform::macos::ns_window(window).is_some_and(|w| w.hasShadow()) +} + +/// One window's shadow re-sampling, fed by its hooked layer's [`Log`]. +pub(crate) struct Shadow { + window: Retained<NSWindow>, + log: Arc<Log>, + state: Cell<Resample>, + /// The drawable the last frame presented. + last: Cell<u64>, +} + +impl Shadow { + /// `first`: the window is on screen (or prewarming) and its first frame is coming. + pub(crate) fn new(window: &winit::window::Window, log: Arc<Log>, first: bool) -> Option<Self> { + let shadow = Shadow { window: crate::platform::macos::ns_window(window)?, log, state: Cell::default(), last: Cell::new(0) }; + if first { shadow.update(Resample::redraw); } + Some(shadow) + } + + pub(crate) fn shown(&self) { let last = self.last.get(); self.update(|r| r.shown(last)); } + pub(crate) fn redraw(&self) { self.update(Resample::redraw); } + pub(crate) fn hidden(&self) { self.update(Resample::hidden); } + + pub(crate) fn presented(&self) { + let n = self.log.last_acquired(); + self.last.set(n); + self.update(|r| r.presented(n)); + } + + /// At the start of each run loop turn. + pub(crate) fn turn(&self) { + let mut state = self.state.get(); + if state == Resample::Idle { return; } + if state.turn(self.log.on_screen()) { + self.window.invalidateShadow(); + } + self.state.set(state); + self.log.watch(state != Resample::Idle); + } + + fn update(&self, f: impl FnOnce(&mut Resample)) { + let mut state = self.state.get(); + f(&mut state); + self.state.set(state); + self.log.watch(state != Resample::Idle); + // Its drawable already landed, so no presented handler will wake the next turn. + if state.due(self.log.on_screen()) { wake_main(); } + } +} + +#[cfg(test)] +#[path = "window_shape_tests.rs"] +mod tests; diff --git a/app/vendor/rune/crates/rune/src/platform/macos/window_shape_tests.rs b/app/vendor/rune/crates/rune/src/platform/macos/window_shape_tests.rs new file mode 100644 index 0000000..96ddc61 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/platform/macos/window_shape_tests.rs @@ -0,0 +1,132 @@ +use super::Resample; + +/// A window's drawables: presents number them, Metal reports them on screen later. +#[derive(Default)] +struct Sim { state: Resample, acquired: u64, on_screen: u64, resamples: usize } + +impl Sim { + fn present(&mut self) -> u64 { self.acquired += 1; self.state.presented(self.acquired); self.acquired } + fn land(&mut self, n: u64) { self.on_screen = self.on_screen.max(n); } + fn turn(&mut self) { if self.state.turn(self.on_screen) { self.resamples += 1; } } + /// Present a frame, let a turn pass before it lands, then land it and turn again. + fn frame(&mut self) { + let n = self.present(); + self.turn(); + self.land(n); + self.turn(); + } +} + +#[test] +fn first_show_resamples_once_its_first_frame_is_on_screen() { + let mut sim = Sim::default(); + sim.state.shown(0); + sim.turn(); + assert_eq!(sim.resamples, 0, "nothing presented yet"); + let n = sim.present(); + sim.turn(); + assert_eq!(sim.resamples, 0, "presented but not on screen: the old pixels would be sampled"); + sim.land(n); + sim.turn(); + assert_eq!(sim.resamples, 1); + sim.turn(); + assert_eq!(sim.resamples, 1, "once per show"); +} + +#[test] +fn ordinary_frames_never_resample() { + let mut sim = Sim::default(); + for _ in 0..20 { sim.frame(); } + assert_eq!(sim.resamples, 0); + sim.state.shown(sim.acquired); + sim.turn(); + assert_eq!(sim.resamples, 1); + for _ in 0..20 { sim.frame(); } + assert_eq!(sim.resamples, 1, "frames after the resample don't repeat it"); +} + +#[test] +fn resize_and_scale_wait_for_a_frame_drawn_after_them() { + for change in ["resize", "scale"] { + let mut sim = Sim::default(); + sim.state.shown(0); + sim.frame(); + assert_eq!(sim.resamples, 1); + // A frame from before the change lands after it: not good enough. + let stale = sim.present(); + sim.state.redraw(); + sim.land(stale); + sim.turn(); + assert_eq!(sim.resamples, 1, "{change}: a frame presented before it is the old shape"); + sim.frame(); + assert_eq!(sim.resamples, 2, "{change}: the first frame after it"); + sim.frame(); + assert_eq!(sim.resamples, 2, "{change}: once"); + } +} + +#[test] +fn a_live_resize_resamples_after_it_settles() { + let mut sim = Sim::default(); + for _ in 0..10 { + sim.state.redraw(); + let n = sim.present(); + sim.turn(); + // The next resize arrives before this frame lands. + sim.state.redraw(); + sim.land(n); + sim.turn(); + } + assert_eq!(sim.resamples, 0, "each frame was already stale when it landed"); + sim.frame(); + assert_eq!(sim.resamples, 1); +} + +#[test] +fn prewarm_resamples_after_its_hidden_frame_and_reveal_after_the_cached_one() { + let mut sim = Sim::default(); + // The launcher's prewarm: its first frame draws at alpha zero. + sim.state.redraw(); + sim.frame(); + assert_eq!(sim.resamples, 1, "after the prewarm frame lands"); + // Hidden refreshes change the cached pixels without a resample. + sim.frame(); + sim.frame(); + assert_eq!(sim.resamples, 1); + // Revealing cached pixels draws nothing new; the last frame is already on screen. + sim.state.shown(sim.acquired); + sim.turn(); + assert_eq!(sim.resamples, 2, "the reveal resamples on the next turn"); + sim.state.hidden(); + // A reveal right after a hidden refresh waits for that frame to land. + let n = sim.present(); + sim.state.shown(n); + sim.turn(); + assert_eq!(sim.resamples, 2); + sim.land(n); + sim.turn(); + assert_eq!(sim.resamples, 3); +} + +#[test] +fn hiding_cancels_a_pending_resample() { + let mut sim = Sim::default(); + sim.state.shown(0); + let n = sim.present(); + sim.state.hidden(); + sim.land(n); + sim.turn(); + assert_eq!(sim.resamples, 0); +} + +#[test] +fn a_show_keeps_waiting_for_the_frame_a_resize_asked_for() { + let mut sim = Sim::default(); + sim.frame(); + sim.state.redraw(); + sim.state.shown(sim.acquired); + sim.turn(); + assert_eq!(sim.resamples, 0, "the frame on screen predates the resize"); + sim.frame(); + assert_eq!(sim.resamples, 1); +} diff --git a/app/vendor/rune/crates/rune/src/platform/portal.rs b/app/vendor/rune/crates/rune/src/platform/portal.rs new file mode 100644 index 0000000..e362255 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/platform/portal.rs @@ -0,0 +1,243 @@ +//! Shared XDG desktop portal helpers for Linux D-Bus clients (`portal_appearance`, +//! `shortcuts::wayland`, `file_dialog::portal`): monotonic request tokens, Request object path +//! construction, portal availability classification, subscribe-before-call Request/Response +//! round-trips, and a shared background worker runtime for one-shot portal calls. + +use std::sync::atomic::{AtomicU64, Ordering}; + +pub(crate) const PATH: &str = "/org/freedesktop/portal/desktop"; + +static NEXT_TOKEN: AtomicU64 = AtomicU64::new(1); + +/// Returns a process-unique XDG portal `handle_token` / `session_handle_token` so repeated or +/// concurrent portal requests never collide on `/org/freedesktop/portal/desktop/request/...`. +pub(crate) fn next_token(prefix: &str) -> String { + let n = NEXT_TOKEN.fetch_add(1, Ordering::Relaxed); + format!("rune_{prefix}_{n}") +} + +/// Builds the `org.freedesktop.portal.Request` object path from the D-Bus connection's unique +/// name (`:1.42`) and a request `token`. Returns `None` if either component is empty or contains +/// characters outside `[A-Za-z0-9_]` after sanitizing the sender name. +pub(crate) fn request_path(unique_name: &str, token: &str) -> Option<String> { + let sender = unique_name.trim_start_matches(':'); + if sender.is_empty() + || token.is_empty() + || !token.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_') + { + return None; + } + let sender = sender.replace('.', "_"); + if !sender.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_') { + return None; + } + Some(format!("{PATH}/request/{sender}/{token}")) +} + +/// Whether the Settings portal watcher should keep its thread alive listening for +/// `SettingChanged`: keep watching when the initial read succeeded or failed for a reason other +/// than the portal being absent; exit cleanly when the portal service itself is unavailable. +pub(crate) fn should_watch_settings(read_ok: bool, unavailable: bool) -> bool { + read_ok || !unavailable +} + +#[cfg(all(target_os = "linux", feature = "dbus"))] +mod dbus { + use std::collections::HashMap; + use std::future::Future; + use std::pin::{Pin, pin}; + use std::sync::OnceLock; + use std::time::Duration; + + use async_executor::LocalExecutor; + use async_io::Timer; + use futures_lite::{FutureExt, StreamExt}; + use zbus::{ + Connection, Proxy, fdo, + zvariant::{OwnedObjectPath, OwnedValue, Type}, + }; + + use super::request_path; + + pub(crate) const DEST: &str = "org.freedesktop.portal.Desktop"; + + /// Timeouts for an XDG portal `Request`/`Response` round-trip. + pub(crate) struct RequestTimeouts { + pub(crate) rpc: Duration, + pub(crate) response: Option<Duration>, + } + + /// Failure from [`request`]. + pub(crate) enum RequestError { + Dbus(zbus::Error), + Unavailable, + TimedOut, + Disconnected, + Cancelled, + } + + /// Awaits `future`, returning `None` if `limit` elapses first. + pub(crate) async fn timeout<T>(limit: Duration, future: impl Future<Output = T>) -> Option<T> { + async { Some(future.await) } + .or(async { + Timer::after(limit).await; + None + }) + .await + } + + async fn or_cancel<T, C: Future<Output = ()>>( + cancel: Pin<&mut C>, + future: impl Future<Output = Result<T, RequestError>>, + ) -> Result<T, RequestError> { + async { + cancel.await; + Err(RequestError::Cancelled) + } + .or(future) + .await + } + + /// Whether `e` indicates that the XDG desktop portal service or interface is absent or + /// failed D-Bus activation on this desktop. + pub(crate) fn is_unavailable(e: &zbus::Error) -> bool { + matches!( + e, + zbus::Error::FDO(fdo) + if matches!( + **fdo, + fdo::Error::ServiceUnknown(_) + | fdo::Error::NameHasNoOwner(_) + | fdo::Error::UnknownInterface(_) + | fdo::Error::UnknownMethod(_) + | fdo::Error::UnknownObject(_) + | fdo::Error::SpawnExecFailed(_) + | fdo::Error::SpawnForkFailed(_) + | fdo::Error::SpawnChildExited(_) + | fdo::Error::SpawnChildSignaled(_) + | fdo::Error::SpawnFailed(_) + | fdo::Error::SpawnServiceNotFound(_) + ) + ) + } + + /// Runs a standard XDG portal `Request`/`Response` round-trip: subscribes to the predicted + /// `org.freedesktop.portal.Request::Response` signal before invoking `method`, falls back to + /// the returned path on pre-`handle_token` portals, honours `cancel` at every step, and calls + /// `Request::Close` on cancellation or timeout. + pub(crate) async fn request<B, C>( + conn: &Connection, + portal: &Proxy<'_>, + token: &str, + method: &str, + body: &B, + timeouts: RequestTimeouts, + cancel: C, + ) -> Result<(u32, HashMap<String, OwnedValue>), RequestError> + where + B: serde::Serialize + Type, + C: Future<Output = ()>, + { + let mut cancel = pin!(cancel); + let unique = conn.unique_name().ok_or(RequestError::Unavailable)?; + let path = request_path(unique.as_str(), token).ok_or(RequestError::Unavailable)?; + let (request, mut responses) = timeout(timeouts.rpc, async { + let mut request = Proxy::new(conn, DEST, path.clone(), "org.freedesktop.portal.Request") + .await + .map_err(RequestError::Dbus)?; + // Subscribe before calling: a portal can emit `Response` before the method returns. + let mut responses = or_cancel(cancel.as_mut(), async { + request.receive_signal("Response").await.map_err(RequestError::Dbus) + }) + .await?; + let handle: OwnedObjectPath = match or_cancel(cancel.as_mut(), async { + portal.call::<_, _, OwnedObjectPath>(method, body).await.map_err(RequestError::Dbus) + }) + .await + { + Ok(handle) => handle, + Err(RequestError::Cancelled) => { + let _ = timeout(timeouts.rpc, request.call::<_, _, ()>("Close", &())).await; + return Err(RequestError::Cancelled); + } + Err(e) => return Err(e), + }; + if handle.as_str() != path { + // Portals older than `handle_token` support pick their own request object path. + request = Proxy::new(conn, DEST, handle.as_str().to_owned(), "org.freedesktop.portal.Request") + .await + .map_err(RequestError::Dbus)?; + responses = match or_cancel(cancel.as_mut(), async { + request.receive_signal("Response").await.map_err(RequestError::Dbus) + }) + .await + { + Ok(responses) => responses, + Err(RequestError::Cancelled) => { + let _ = timeout(timeouts.rpc, request.call::<_, _, ()>("Close", &())).await; + return Err(RequestError::Cancelled); + } + Err(e) => return Err(e), + }; + } + Ok::<_, RequestError>((request, responses)) + }) + .await + .unwrap_or(Err(RequestError::TimedOut))?; + + let wait = or_cancel(cancel.as_mut(), async { + match responses.next().await { + Some(message) => message + .body() + .deserialize::<(u32, HashMap<String, OwnedValue>)>() + .map_err(RequestError::Dbus), + None => Err(RequestError::Disconnected), + } + }); + let result = match timeouts.response { + Some(limit) => timeout(limit, wait).await.unwrap_or(Err(RequestError::TimedOut)), + None => wait.await, + }; + if result.is_err() { + let _ = timeout(timeouts.rpc, request.call::<_, _, ()>("Close", &())).await; + } + result + } + + /// Runs a one-shot portal future on a single lazily-started background `LocalExecutor` + /// thread instead of spawning an unjoined thread per call. + pub(crate) fn spawn<F, Fut>(make: F) -> Result<(), String> + where + F: FnOnce() -> Fut + Send + 'static, + Fut: Future<Output = ()> + 'static, + { + type Job = Box<dyn FnOnce() -> Pin<Box<dyn Future<Output = ()>>> + Send>; + static WORKER: OnceLock<Result<async_channel::Sender<Job>, String>> = OnceLock::new(); + let tx = WORKER + .get_or_init(|| { + let (tx, rx) = async_channel::unbounded::<Job>(); + std::thread::Builder::new() + .name("rune-portal-worker".into()) + .spawn(move || { + let local = LocalExecutor::new(); + async_io::block_on(local.run(async { + while let Ok(job) = rx.recv().await { + local.spawn(job()).detach(); + } + })); + }) + .map_err(|e| e.to_string())?; + Ok(tx) + }) + .as_ref() + .map_err(Clone::clone)?; + tx.try_send(Box::new(move || Box::pin(make()))).map_err(|_| "portal worker stopped".to_owned()) + } +} + +#[cfg(all(target_os = "linux", feature = "dbus"))] +pub(crate) use dbus::{DEST, RequestError, RequestTimeouts, is_unavailable, request, spawn, timeout}; + +#[cfg(test)] +#[path = "portal_tests.rs"] +mod tests; diff --git a/app/vendor/rune/crates/rune/src/platform/portal_appearance.rs b/app/vendor/rune/crates/rune/src/platform/portal_appearance.rs new file mode 100644 index 0000000..9e286c1 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/platform/portal_appearance.rs @@ -0,0 +1,107 @@ +//! The desktop's light or dark preference on Linux, from the XDG desktop portal +//! (`org.freedesktop.appearance` `color-scheme`). winit reports no theme on Wayland unless the +//! app set one, so hosts ask here before falling back to dark. A worker thread reads the setting +//! once and follows `SettingChanged`; a change asks every window to redraw, which rereads it. + +use futures_lite::StreamExt; +use std::{sync::{Arc, Mutex, OnceLock, Weak, atomic::{AtomicU8, Ordering}, mpsc}, time::Duration}; +use winit::window::Window; +use zbus::{Connection, Proxy, zvariant::{OwnedValue, Value}}; + +use super::portal::{self, DEST, PATH}; + +const INTERFACE: &str = "org.freedesktop.portal.Settings"; +const NAMESPACE: &str = "org.freedesktop.appearance"; +const KEY: &str = "color-scheme"; +/// How long the first window waits for the portal's first answer, as sctk-adwaita does for its +/// frame; a slower answer redraws the windows when it arrives. +const FIRST_ANSWER: Duration = Duration::from_millis(100); +/// Connecting, D-Bus activation of the portal and the first read. +const RPC_TIMEOUT: Duration = Duration::from_secs(10); + +/// The portal's numbering: 0 no preference (or not known yet), 1 dark, 2 light. +static SCHEME: AtomicU8 = AtomicU8::new(0); +static WATCH: OnceLock<()> = OnceLock::new(); +static WINDOWS: Mutex<Vec<Weak<Window>>> = Mutex::new(Vec::new()); + +/// Some(true) when the desktop prefers dark, Some(false) light, None when it has no preference +/// or no portal answers. +pub(crate) fn dark() -> Option<bool> { + WATCH.get_or_init(start); + scheme_dark(SCHEME.load(Ordering::Relaxed).into()) +} + +/// Redraws `window` whenever the preference changes; its redraw rereads [`dark`]. +pub(crate) fn follow(window: &Arc<Window>) { + let mut windows = WINDOWS.lock().unwrap_or_else(|e| e.into_inner()); + windows.retain(|w| w.strong_count() > 0); + windows.push(Arc::downgrade(window)); +} + +fn scheme_dark(scheme: u32) -> Option<bool> { + match scheme { + 1 => Some(true), + 2 => Some(false), + _ => None, + } +} + +/// `color-scheme` as a `u32`. Portals answer `v`, and `Read` (before `ReadOne`) wraps it twice. +fn scheme(value: &Value<'_>) -> Option<u32> { + match value { + Value::U32(x) => Some(*x), + Value::Value(inner) => scheme(inner), + _ => None, + } +} + +fn store(value: &Value<'_>) { + let Some(scheme) = scheme(value) else { return }; + let scheme = if scheme <= 2 { scheme as u8 } else { 0 }; + if SCHEME.swap(scheme, Ordering::Relaxed) == scheme { return; } + for window in WINDOWS.lock().unwrap_or_else(|e| e.into_inner()).iter().filter_map(Weak::upgrade) { + window.request_redraw(); + } +} + +fn start() { + let (ready, first) = mpsc::sync_channel(1); + let worker = std::thread::Builder::new().name("rune-appearance-portal".into()).spawn(move || { + async_io::block_on(watch(ready)); + }); + if worker.is_ok() { first.recv_timeout(FIRST_ANSWER).ok(); } +} + +async fn watch(ready: mpsc::SyncSender<()>) { + let setup = portal::timeout(RPC_TIMEOUT, async { + let conn = Connection::session().await.ok()?; + let portal = Proxy::new(&conn, DEST, PATH, INTERFACE).await.ok()?; + // Subscribe first, so a change between the read and the subscription isn't lost. + let changes = portal.receive_signal("SettingChanged").await.ok()?; + let (read_ok, unavailable) = match portal.call::<_, _, OwnedValue>("ReadOne", &(NAMESPACE, KEY)).await { + Ok(v) => { store(&v); (true, false) } + Err(first) => match portal.call::<_, _, OwnedValue>("Read", &(NAMESPACE, KEY)).await { + Ok(v) => { store(&v); (true, false) } + Err(second) => (false, portal::is_unavailable(&first) && portal::is_unavailable(&second)), + }, + }; + if !portal::should_watch_settings(read_ok, unavailable) { + conn.close().await.ok(); + return None; + } + Some((conn, changes)) + }).await.flatten(); + ready.send(()).ok(); + let Some((_conn, mut changes)) = setup else { return }; + while let Some(message) = changes.next().await { + if let Ok((namespace, key, value)) = message.body().deserialize::<(String, String, OwnedValue)>() + && namespace == NAMESPACE && key == KEY + { + store(&value); + } + } +} + +#[cfg(test)] +#[path = "portal_appearance_tests.rs"] +mod tests; diff --git a/app/vendor/rune/crates/rune/src/platform/portal_appearance_tests.rs b/app/vendor/rune/crates/rune/src/platform/portal_appearance_tests.rs new file mode 100644 index 0000000..d82fdf4 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/platform/portal_appearance_tests.rs @@ -0,0 +1,17 @@ +use super::*; + +#[test] +fn only_an_explicit_preference_picks_an_appearance() { + assert_eq!(scheme_dark(1), Some(true)); + assert_eq!(scheme_dark(2), Some(false)); + assert_eq!(scheme_dark(0), None); + assert_eq!(scheme_dark(7), None); +} + +#[test] +fn reads_the_scheme_however_deeply_the_portal_wraps_it() { + assert_eq!(scheme(&Value::U32(2)), Some(2)); + assert_eq!(scheme(&Value::Value(Box::new(Value::U32(1)))), Some(1)); + assert_eq!(scheme(&Value::Value(Box::new(Value::Value(Box::new(Value::U32(2)))))), Some(2)); + assert_eq!(scheme(&Value::Str("prefer-dark".into())), None); +} diff --git a/app/vendor/rune/crates/rune/src/platform/portal_tests.rs b/app/vendor/rune/crates/rune/src/platform/portal_tests.rs new file mode 100644 index 0000000..974b3b0 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/platform/portal_tests.rs @@ -0,0 +1,36 @@ +use super::*; + +#[test] +fn portal_tokens_are_monotonic_and_never_collide() { + let a = next_token("shortcuts_create"); + let b = next_token("shortcuts_create"); + let c = next_token("file_dialog"); + assert_ne!(a, b, "repeated requests for the same prefix must get distinct tokens"); + assert_ne!(b, c); + assert!(a.starts_with("rune_shortcuts_create_")); + assert!(c.starts_with("rune_file_dialog_")); +} + +#[test] +fn portal_request_path_sanitizes_sender_and_rejects_invalid_inputs() { + assert_eq!( + request_path(":1.42", "rune_shortcuts_1").as_deref(), + Some("/org/freedesktop/portal/desktop/request/1_42/rune_shortcuts_1") + ); + assert_eq!( + request_path("1.99", "tok_2").as_deref(), + Some("/org/freedesktop/portal/desktop/request/1_99/tok_2") + ); + assert_eq!(request_path("", "tok"), None); + assert_eq!(request_path(":", "tok"), None); + assert_eq!(request_path(":1.42", ""), None); + assert_eq!(request_path(":1.42", "bad-token"), None, "XDG request tokens must be [A-Za-z0-9_]"); + assert_eq!(request_path(":1.42", "bad/token"), None); +} + +#[test] +fn settings_portal_watcher_exits_when_portal_is_absent() { + assert!(should_watch_settings(true, false)); + assert!(should_watch_settings(false, false), "live portal with unset key still watches changes"); + assert!(!should_watch_settings(false, true), "absent portal must not keep watcher thread alive forever"); +} diff --git a/app/vendor/rune/crates/rune/src/platform/preferences.rs b/app/vendor/rune/crates/rune/src/platform/preferences.rs new file mode 100644 index 0000000..6e975ca --- /dev/null +++ b/app/vendor/rune/crates/rune/src/platform/preferences.rs @@ -0,0 +1,208 @@ +//! Native accessibility and appearance preferences, sampled when a host is created or focused +//! (appearance also on each redraw, which a change asks for). +//! Headless runtimes use their explicit Env instead. + +#![allow(unsafe_code)] + +#[cfg(target_os = "macos")] +pub(crate) fn reduced_motion() -> bool { + use objc2::{class, msg_send}; + // SAFETY: NSWorkspace's shared instance lives for the process; these selectors return + // an object pointer and Objective-C BOOL respectively. Native hosts call on the UI thread. + unsafe { + let workspace: *mut objc2::runtime::AnyObject = msg_send![class!(NSWorkspace), sharedWorkspace]; + let reduced: objc2::runtime::Bool = msg_send![workspace, accessibilityDisplayShouldReduceMotion]; + reduced.as_bool() + } +} + +#[cfg(target_os = "windows")] +pub(crate) fn reduced_motion() -> bool { + use windows_sys::Win32::UI::WindowsAndMessaging::{SystemParametersInfoW, SPI_GETCLIENTAREAANIMATION}; + let mut animations: i32 = 1; + // SAFETY: this SPI writes one BOOL to a valid, aligned local variable. + unsafe { SystemParametersInfoW(SPI_GETCLIENTAREAANIMATION, 0, (&mut animations as *mut i32).cast(), 0) != 0 && animations == 0 } +} + +#[cfg(target_os = "linux")] +pub(crate) fn reduced_motion() -> bool { + // KDE exposes animation duration in kdeglobals; zero disables animation. + let config = std::env::var_os("XDG_CONFIG_HOME").map(std::path::PathBuf::from) + .or_else(|| std::env::var_os("HOME").map(|h| std::path::PathBuf::from(h).join(".config"))); + if rune_core::env::var("XDG_CURRENT_DESKTOP").unwrap_or_default().split(':').any(|d| d.eq_ignore_ascii_case("KDE")) + && let Some(config) = config + && let Ok(contents) = std::fs::read_to_string(config.join("kdeglobals")) + && let Some(factor) = contents.lines().filter_map(|line| line.trim().split_once('=')) + .find_map(|(k, v)| (k.trim() == "AnimationDurationFactor").then(|| v.trim().parse::<f64>().ok()).flatten()) + { return factor == 0.0; } + // Optional GNOME GSettings, with schema lookup before constructing settings (missing + // schemas otherwise abort GLib). No subprocess or required GNOME dependency. + // SAFETY: `gnome_animations` dynamically resolves GIO symbols, checks every pointer for null, + // and releases each GLib object before returning. + unsafe { gnome_animations().is_some_and(|enabled| !enabled) } +} + +#[cfg(target_os = "linux")] +unsafe fn gnome_animations() -> Option<bool> { + use std::ffi::{c_char, c_void}; + type Ptr = *mut c_void; + // SAFETY: signatures match GIO/GLib's public C API; every reference is released while + // the library is loaded. Null source/schema/settings are handled before use. + unsafe { + static GIO: std::sync::OnceLock<Option<libloading::Library>> = std::sync::OnceLock::new(); + let gio = GIO.get_or_init(|| libloading::Library::new("libgio-2.0.so.0").ok()).as_ref()?; + let default = gio.get::<unsafe extern "C" fn() -> Ptr>(b"g_settings_schema_source_get_default\0").ok()?; + let lookup = gio.get::<unsafe extern "C" fn(Ptr, *const c_char, i32) -> Ptr>(b"g_settings_schema_source_lookup\0").ok()?; + let has_key = gio.get::<unsafe extern "C" fn(Ptr, *const c_char) -> i32>(b"g_settings_schema_has_key\0").ok()?; + let new = gio.get::<unsafe extern "C" fn(Ptr, Ptr, *const c_char) -> Ptr>(b"g_settings_new_full\0").ok()?; + let get = gio.get::<unsafe extern "C" fn(Ptr, *const c_char) -> i32>(b"g_settings_get_boolean\0").ok()?; + let schema_unref = gio.get::<unsafe extern "C" fn(Ptr)>(b"g_settings_schema_unref\0").ok()?; + let unref = gio.get::<unsafe extern "C" fn(Ptr)>(b"g_object_unref\0").ok()?; + let source = default(); + if source.is_null() { return None; } + let schema = lookup(source, c"org.gnome.desktop.interface".as_ptr(), 1); + if schema.is_null() { return None; } + if has_key(schema, c"enable-animations".as_ptr()) == 0 { schema_unref(schema); return None; } + let settings = new(schema, std::ptr::null_mut(), std::ptr::null()); + schema_unref(schema); + if settings.is_null() { return None; } + let enabled = get(settings, c"enable-animations".as_ptr()) != 0; + unref(settings); + // The static library stays loaded for GLib's retained backend callbacks. + Some(enabled) + } +} + +#[cfg(not(any(target_os = "macos", target_os = "windows", target_os = "linux")))] +pub(crate) fn reduced_motion() -> bool { false } + +/// `RUNE_INCREASE_CONTRAST=1`: [`increased_contrast`] on, for captures and checks. +pub(crate) fn increased_contrast_preset() -> bool { + std::env::var_os("RUNE_INCREASE_CONTRAST").is_some_and(|v| v == "1") +} + +/// Whether the system asks apps for more contrast: macOS's Increase Contrast (Accessibility > +/// Display), or a Windows contrast theme. `RUNE_INCREASE_CONTRAST=1` reports it on, for captures +/// and checks, without turning it on for the whole machine. Read as [`reduced_motion`] is, and on +/// macOS again when the display options change (`a11y/macos.rs`). +pub(crate) fn increased_contrast() -> bool { + if increased_contrast_preset() { return true; } + #[cfg(target_os = "macos")] + { + use objc2::{class, msg_send}; + // SAFETY: NSWorkspace's shared instance lives for the process; the selector returns an + // Objective-C BOOL. Native hosts call on the UI thread. + unsafe { + let workspace: *mut objc2::runtime::AnyObject = msg_send![class!(NSWorkspace), sharedWorkspace]; + let more: objc2::runtime::Bool = msg_send![workspace, accessibilityDisplayShouldIncreaseContrast]; + more.as_bool() + } + } + #[cfg(target_os = "windows")] + { contrast().is_some() } + #[cfg(not(any(target_os = "macos", target_os = "windows")))] + { false } +} + +/// The colours a system contrast theme asks every app to paint with (Windows' Contrast themes, +/// CSS `forced-colors`' system colours), in linear sRGB as Rune's colours are. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct SystemContrast { + /// A window's ground (`Canvas`, `COLOR_WINDOW`). + pub window: crate::Color, + /// Text on it (`CanvasText`, `COLOR_WINDOWTEXT`). + pub text: crate::Color, + /// A selection, a focus ring, a checked control (`Highlight`, `COLOR_HIGHLIGHT`). + pub highlight: crate::Color, + /// Text on [`Self::highlight`] (`HighlightText`, `COLOR_HIGHLIGHTTEXT`). + pub highlight_text: crate::Color, + /// Disabled text (`GrayText`, `COLOR_GRAYTEXT`). + pub disabled: crate::Color, + /// A button's face and text (`ButtonFace`, `ButtonText`). + pub button: crate::Color, + pub button_text: crate::Color, + /// A link (`LinkText`, `COLOR_HOTLIGHT`). + pub link: crate::Color, +} + +/// The system's contrast theme, when one is on (Windows: Settings > Accessibility > Contrast +/// themes). Read when a window opens and when Windows says its settings or colours changed. +#[cfg(target_os = "windows")] +pub(crate) fn contrast() -> Option<SystemContrast> { + if let Some(preset) = contrast_preset() { return Some(preset); } + use windows_sys::Win32::Graphics::Gdi::GetSysColor; + use windows_sys::Win32::UI::Accessibility::{HCF_HIGHCONTRASTON, HIGHCONTRASTW}; + use windows_sys::Win32::UI::WindowsAndMessaging::{SPI_GETHIGHCONTRAST, SystemParametersInfoW}; + let mut hc = HIGHCONTRASTW { cbSize: std::mem::size_of::<HIGHCONTRASTW>() as u32, dwFlags: 0, lpszDefaultScheme: std::ptr::null_mut() }; + // SAFETY: SPI_GETHIGHCONTRAST fills a HIGHCONTRASTW whose size it is told. + let read = unsafe { SystemParametersInfoW(SPI_GETHIGHCONTRAST, hc.cbSize, (&mut hc as *mut HIGHCONTRASTW).cast(), 0) } != 0; + if !read || hc.dwFlags & HCF_HIGHCONTRASTON == 0 { return None; } + let sys = |index: i32| { + // SAFETY: `GetSysColor` is a read-only Win32 query; callers pass standard `COLOR_*` indices. + let c = unsafe { GetSysColor(index) }; + let d = |v: u32| crate::color::srgb_decode((v & 0xff) as f32 / 255.0); + crate::Color { r: d(c), g: d(c >> 8), b: d(c >> 16), a: 1.0 } + }; + // COLOR_WINDOW 5, WINDOWTEXT 8, HIGHLIGHT 13, HIGHLIGHTTEXT 14, BTNFACE 15, GRAYTEXT 17, + // BTNTEXT 18, HOTLIGHT 26. + Some(SystemContrast { window: sys(5), text: sys(8), highlight: sys(13), highlight_text: sys(14), disabled: sys(17), button: sys(15), button_text: sys(18), link: sys(26) }) +} + +#[cfg(not(target_os = "windows"))] +pub(crate) fn contrast() -> Option<SystemContrast> { contrast_preset() } + +/// `RUNE_CONTRAST=aquatic|desert|dusk|night-sky`: Windows 11's contrast theme of that name, as +/// its system colours are, without turning it on for the whole machine: for captures and checks +/// of an app in each. +pub(crate) fn contrast_preset() -> Option<SystemContrast> { + let name = rune_core::env::var("RUNE_CONTRAST")?; + let [window, text, highlight, highlight_text, disabled, link] = match name.to_ascii_lowercase().as_str() { + "aquatic" => ["#202020", "#ffffff", "#8ee3f0", "#263b50", "#a6a6a6", "#75e9fc"], + "desert" => ["#fffaef", "#3d3d3d", "#903909", "#fff5e3", "#6d6d6d", "#1c5e75"], + "dusk" => ["#2d3236", "#ffffff", "#a1bfde", "#212d3b", "#a6a6a6", "#70ebde"], + "night-sky" | "nightsky" => ["#000000", "#ffffff", "#d6b4fd", "#2b2b2b", "#a6a6a6", "#8080ff"], + _ => return None, + }.map(|h| crate::color::hex(h).unwrap_or(crate::Color::BLACK)); + Some(SystemContrast { window, text, highlight, highlight_text, disabled, button: window, button_text: text, link }) +} +/// The desktop's light or dark preference where winit reports none (Linux: the XDG desktop +/// portal's `color-scheme`). None leaves the host's own default. +#[cfg(all(target_os = "linux", feature = "dbus"))] +pub(crate) fn dark() -> Option<bool> { crate::platform::portal_appearance::dark() } + +#[cfg(not(all(target_os = "linux", feature = "dbus")))] +pub(crate) fn dark() -> Option<bool> { None } + +/// [`dark`] for a window winit gives no theme; None leaves the window's appearance as it is. +pub(crate) fn desktop_dark(window: &winit::window::Window) -> Option<bool> { + dark().filter(|_| window.theme().is_none()) +} + +/// A new window's appearance: `--theme` when given, else winit's theme, else [`desktop_dark`], +/// else dark. On Linux a change of the desktop's preference redraws the window, which rereads it. +pub(crate) fn window_dark(window: &std::sync::Arc<winit::window::Window>, theme: Option<&str>) -> bool { + #[cfg(all(target_os = "linux", feature = "dbus"))] + crate::platform::portal_appearance::follow(window); + match theme { + Some("light") => false, + Some("dark") => true, + _ => window.theme().map_or_else(|| desktop_dark(window).unwrap_or(true), |t| t == winit::window::Theme::Dark), + } +} + +/// macOS "Keyboard navigation" (Full Keyboard Access): when off, Tab visits only text fields +/// and lists, as in AppKit. Windows and Linux always Tab through every control. +#[cfg(target_os = "macos")] +pub(crate) fn full_keyboard_access() -> bool { + use objc2::{class, msg_send}; + // SAFETY: NSApplication's shared instance lives for the process; the selector returns an + // Objective-C BOOL. Native hosts call on the UI thread. + unsafe { + let app: *mut objc2::runtime::AnyObject = msg_send![class!(NSApplication), sharedApplication]; + let enabled: objc2::runtime::Bool = msg_send![app, isFullKeyboardAccessEnabled]; + enabled.as_bool() + } +} + +#[cfg(not(target_os = "macos"))] +pub(crate) fn full_keyboard_access() -> bool { true } diff --git a/app/vendor/rune/crates/rune/src/platform/ready_signal.rs b/app/vendor/rune/crates/rune/src/platform/ready_signal.rs new file mode 100644 index 0000000..9efa6d0 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/platform/ready_signal.rs @@ -0,0 +1,133 @@ +//! A launcher can wait for readiness. With `RUNE_READY_DIR` set, the process writes +//! `$RUNE_READY_DIR/<bundle id>.<pid>` once its first window's `on_ready` has returned (or would +//! have, with none), and removes it when it exits normally. The file is one line of JSON: +//! `{"pid":123,"bundle_id":"com.example.app","ready_ms":412,"rune":"0.1.0"}`, where `ready_ms` +//! counts from the process's start (from `run` where that's unknown). The bundle id is the main +//! bundle's on macOS, else the executable's name. A process killed outright leaves its file +//! behind, so a reader treats one whose PID is no longer running as stale. + +use std::ffi::OsStr; +use std::io::Write; +use std::path::{Path, PathBuf}; +use std::sync::{Mutex, OnceLock}; +use std::time::Instant; + +const VAR: &str = "RUNE_READY_DIR"; + +static RUN: OnceLock<Instant> = OnceLock::new(); +static WRITTEN: Mutex<Written> = Mutex::new(Written::NotYet); + +/// The readiness file, as far as this process goes. +#[derive(Debug, PartialEq)] +enum Written { + /// No window's `on_ready` has returned yet. + NotYet, + /// Ready, with no file to show for it (no `RUNE_READY_DIR`, a failed write), or the file + /// has been removed. + NoFile, + At(PathBuf), +} + +/// `run` starts the event loop. +pub(crate) fn run_starts() { RUN.get_or_init(crate::time::now); } + +/// A window's `on_ready` returned. Only the process's first writes the file. +pub(crate) fn ready() { ready_in(std::env::var_os(VAR).as_deref()) } + +fn ready_in(dir: Option<&OsStr>) { + let mut written = WRITTEN.lock().unwrap_or_else(|e| e.into_inner()); + if *written != Written::NotYet { return; } + let Some(dir) = dir.filter(|dir| !dir.is_empty()) else { *written = Written::NoFile; return }; + let ready_ms = crate::tooling::perf_warn::launch::process_age().or_else(|| RUN.get().map(Instant::elapsed)).map_or(0, |age| age.as_millis() as u64); + let signal = Signal { pid: std::process::id(), bundle_id: bundle_id(), ready_ms }; + *written = match signal.write_in(Some(dir)) { + Some(Ok(path)) => { + on_exit(); + Written::At(path) + } + Some(Err(error)) => { + #[cfg(debug_assertions)] + eprintln!("rune: couldn't write the {VAR} readiness file: {error}"); + let _ = error; + Written::NoFile + } + None => Written::NoFile, + }; +} + +/// Removes the file, if this process wrote one. Runs as the event loop returns and at exit. +pub(crate) fn clear() { + // At exit, another thread may hold the lock; leaving the file then is what a kill does. + let Ok(mut written) = WRITTEN.try_lock() else { return }; + if let Written::At(path) = &*written { + std::fs::remove_file(path).ok(); + *written = Written::NoFile; + } +} + +/// What the file says. +struct Signal { pid: u32, bundle_id: String, ready_ms: u64 } + +impl Signal { + fn json(&self) -> String { + let id = serde_json::to_string(&self.bundle_id).unwrap_or_else(|_| "\"\"".into()); + format!(r#"{{"pid":{},"bundle_id":{id},"ready_ms":{},"rune":"{}"}}"#, self.pid, self.ready_ms, env!("CARGO_PKG_VERSION")) + } + + /// Writes the file into `dir`, made 0700 if it's missing, through a temporary file renamed + /// over it. Nothing without a `dir`. + fn write_in(&self, dir: Option<&OsStr>) -> Option<std::io::Result<PathBuf>> { + let dir = Path::new(dir.filter(|dir| !dir.is_empty())?); + Some((|| { + let mut builder = std::fs::DirBuilder::new(); + builder.recursive(true); + #[cfg(unix)] + std::os::unix::fs::DirBuilderExt::mode(&mut builder, 0o700); + builder.create(dir)?; + let name = format!("{}.{}", self.bundle_id.replace(['/', '\\'], "_"), self.pid); + let path = dir.join(&name); + let temp = dir.join(format!(".{name}.tmp")); + let mut file = std::fs::File::create(&temp)?; + file.write_all(format!("{}\n", self.json()).as_bytes())?; + drop(file); + std::fs::rename(&temp, &path).inspect_err(|_| { std::fs::remove_file(&temp).ok(); })?; + Ok(path) + })()) + } +} + +/// The main bundle's identifier on macOS, else the executable's name. +fn bundle_id() -> String { + #[cfg(target_os = "macos")] + if let Some(id) = main_bundle_id() { return id; } + std::env::current_exe().ok().and_then(|exe| exe.file_name().map(|name| name.to_string_lossy().into_owned())) + .unwrap_or_else(|| "rune-app".into()) +} + +#[cfg(target_os = "macos")] +#[allow(unsafe_code)] +fn main_bundle_id() -> Option<String> { + use objc2_foundation::NSString; + use objc2::{class, msg_send, rc::Retained, runtime::AnyObject}; + // SAFETY: NSBundle reads, which are thread-safe. + unsafe { + let bundle: Option<Retained<AnyObject>> = msg_send![class!(NSBundle), mainBundle]; + let id: Option<Retained<NSString>> = msg_send![&*bundle?, bundleIdentifier]; + id.map(|id| id.to_string()).filter(|id| !id.is_empty()) + } +} + +/// Removes the file when the process exits through `exit`, as AppKit's Quit does. +#[allow(unsafe_code)] +fn on_exit() { + #[cfg(unix)] + { + extern "C" fn at_exit() { clear() } + // SAFETY: registers a plain function with no captured state. + unsafe { libc::atexit(at_exit) }; + } +} + +#[cfg(test)] +#[path = "ready_signal_tests.rs"] +mod tests; diff --git a/app/vendor/rune/crates/rune/src/platform/ready_signal_tests.rs b/app/vendor/rune/crates/rune/src/platform/ready_signal_tests.rs new file mode 100644 index 0000000..cd38a05 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/platform/ready_signal_tests.rs @@ -0,0 +1,45 @@ +use super::*; + +fn scratch(name: &str) -> PathBuf { + let nanos = crate::time::system_now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos(); + std::env::temp_dir().join(format!("rune-{name}-{}-{nanos}", std::process::id())) +} + +/// The first `on_ready` writes `<bundle id>.<pid>` as one line of JSON into a directory it +/// makes private; later ones write nothing; exiting removes it. +#[test] +fn a_launcher_can_wait_for_the_ready_file() { + let root = scratch("ready"); + let dir = root.join("ready"); + ready_in(Some(dir.as_os_str())); + let path = dir.join(format!("{}.{}", bundle_id(), std::process::id())); + let text = std::fs::read_to_string(&path).expect("the ready file"); + assert!(text.ends_with('\n') && text.lines().count() == 1, "{text:?}"); + let json: serde_json::Value = serde_json::from_str(&text).unwrap(); + assert_eq!(json["pid"], std::process::id()); + assert_eq!(json["bundle_id"], bundle_id()); + assert_eq!(json["rune"], env!("CARGO_PKG_VERSION")); + assert!(json["ready_ms"].is_u64()); + assert_eq!(std::fs::read_dir(&dir).unwrap().count(), 1, "no temporary file is left"); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + assert_eq!(std::fs::metadata(&dir).unwrap().permissions().mode() & 0o777, 0o700); + } + + let other = root.join("other"); + ready_in(Some(other.as_os_str())); + assert!(!other.exists(), "once per process: another window's on_ready writes nothing"); + + clear(); + assert!(!path.exists(), "exiting removes it"); + std::fs::remove_dir_all(&root).ok(); +} + +#[test] +fn without_the_variable_nothing_is_written() { + let signal = Signal { pid: 7, bundle_id: "com.example.app".into(), ready_ms: 412 }; + assert!(signal.write_in(None).is_none()); + assert!(signal.write_in(Some(OsStr::new(""))).is_none()); + assert_eq!(signal.json(), format!(r#"{{"pid":7,"bundle_id":"com.example.app","ready_ms":412,"rune":"{}"}}"#, env!("CARGO_PKG_VERSION"))); +} diff --git a/app/vendor/rune/crates/rune/src/platform/reopen.rs b/app/vendor/rune/crates/rune/src/platform/reopen.rs new file mode 100644 index 0000000..01ec1fc --- /dev/null +++ b/app/vendor/rune/crates/rune/src/platform/reopen.rs @@ -0,0 +1,197 @@ +//! Reopening a running app: on macOS, a click on its Dock icon, or opening it again from Finder, +//! Spotlight or `open` while it runs. Without this an app whose windows Rune hid (⌘W with +//! `keep_running`, `hide`) stays invisible, because AppKit only brings back minimized windows. +//! +//! AppKit answers the reopen Apple event itself and asks the app delegate +//! `applicationShouldHandleReopen:hasVisibleWindows:`. winit's delegate doesn't implement it, +//! so Rune adds the method to the delegate's class once (`install`). The method only sends an +//! event to the loop; `App::on_reopen` hooks and the default (`target`) run from it, like any +//! other wake, never inside the AppKit callback. + +use std::sync::atomic::{AtomicU64, Ordering}; + +/// One window as reopening sees it. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub(crate) struct Candidate { + /// An app window that still exists and can come back: not a launcher or other + /// nonactivating panel, an overlay, or a window that closed for good. + pub reopenable: bool, + /// On screen and not minimized. + pub visible: bool, + pub minimized: bool, + /// When Rune last hid it (a close with `keep_running`, `hide`), as `stamp` counted. + pub hidden_at: Option<u64>, + /// A window of the app itself, not one `App::window` added. + pub main: bool, +} + +/// Whether any window reopening could bring back already shows. +pub(crate) fn has_visible(windows: &[Candidate]) -> bool { + windows.iter().any(|w| w.reopenable && w.visible) +} + +/// The window the default reopen shows, when none shows: a minimized one, as AppKit restores +/// them; else the one Rune hid last; else the first main window, which may never have shown. +pub(crate) fn target(windows: &[Candidate]) -> Option<usize> { + if has_visible(windows) { return None; } + let ok = |w: &&Candidate| w.reopenable; + let indexed = || windows.iter().enumerate().filter(|(_, w)| ok(w)); + indexed().find(|(_, w)| w.minimized).map(|(i, _)| i) + .or_else(|| indexed().filter_map(|(i, w)| Some((w.hidden_at?, i))).max().map(|(_, i)| i)) + .or_else(|| indexed().find(|(_, w)| w.main).map(|(i, _)| i)) +} + +static HIDES: AtomicU64 = AtomicU64::new(0); + +/// A number larger than every earlier one, for the order windows hid in. +pub(crate) fn stamp() -> u64 { HIDES.fetch_add(1, Ordering::Relaxed) + 1 } + +/// What the reopen method answers AppKit: whether AppKit should run its own reopen handling. +/// When AppKit sees a visible window its handling changes nothing, and the activation that +/// came with the reopen already brought the app forward, to the window's Space; so it goes +/// ahead. Otherwise Rune brings the window back itself, unless the event never reached Rune's +/// loop (it has exited), when AppKit still restores what it can. +#[cfg_attr(not(target_os = "macos"), allow(dead_code))] +pub(crate) fn appkit_handles(sent: bool, appkit_sees_visible: bool) -> bool { !sent || appkit_sees_visible } + +#[cfg(target_os = "macos")] +pub(crate) use mac::{accessory, front, install, unhide}; + +#[cfg(target_os = "macos")] +#[allow(unsafe_code)] +mod mac { + use std::cell::{Cell, RefCell}; + use std::ffi::{c_char, c_void}; + use objc2::{MainThreadMarker, msg_send, sel}; + use objc2::runtime::{AnyClass, AnyObject, Bool, Sel}; + use objc2_app_kit::{NSApplication, NSApplicationActivationPolicy}; + + thread_local! { + /// Sends the reopen to Rune's loop; false once the loop is gone. + static REOPEN: RefCell<Option<Box<dyn Fn() -> bool>>> = const { RefCell::new(None) }; + /// The delegate class Rune added the method to. + static HOOKED: Cell<*const AnyClass> = const { Cell::new(std::ptr::null()) }; + } + + unsafe extern "C" { + fn class_addMethod(class: *const AnyClass, selector: Sel, implementation: *const c_void, types: *const c_char) -> Bool; + } + + extern "C" fn should_handle_reopen(_: *mut AnyObject, _: Sel, _: *mut AnyObject, visible: Bool) -> Bool { + let sent = std::panic::catch_unwind(|| { + REOPEN.with(|reopen| reopen.try_borrow().ok().and_then(|f| f.as_ref().map(|f| f())).unwrap_or(false)) + }).unwrap_or_else(|_| { eprintln!("rune: reopen callback panicked"); false }); + Bool::new(super::appkit_handles(sent, visible.as_bool())) + } + + /// Calls `reopen` on the main thread each time the app is reopened; it returns whether the + /// event reached Rune's loop. Adds the reopen method to the app delegate's class unless the + /// class already answers it (a later winit, or an app's own delegate), in which case + /// reopening stays with that delegate. Main thread only; a later call replaces `reopen`. + pub(crate) fn install(reopen: impl Fn() -> bool + 'static) { + let Some(mtm) = MainThreadMarker::new() else { return }; + let app = NSApplication::sharedApplication(mtm); + let selector = sel!(applicationShouldHandleReopen:hasVisibleWindows:); + // SAFETY: AppKit calls and runtime changes on the main thread. The added function has + // the selector's ABI (`types`: BOOL is `bool` on Apple silicon, `signed char` on Intel), + // and adding a method the class lacks leaves its other methods and instances alone. + unsafe { + let delegate: *mut AnyObject = msg_send![&app, delegate]; + let Some(delegate) = delegate.as_ref() else { return }; + let class = delegate.class(); + if !HOOKED.with(|hooked| std::ptr::eq(hooked.get(), class)) { + let answers: bool = msg_send![delegate, respondsToSelector: selector]; + if answers { return; } + let types = if cfg!(target_arch = "aarch64") { c"B@:@B" } else { c"c@:@c" }; + let imp = should_handle_reopen as extern "C" fn(*mut AnyObject, Sel, *mut AnyObject, Bool) -> Bool; + if !class_addMethod(class, selector, imp as *const c_void, types.as_ptr()).as_bool() { + eprintln!("rune: could not add the reopen method to the app delegate"); + return; + } + HOOKED.with(|hooked| hooked.set(class)); + // AppKit caches which optional methods its delegate answers when it is set. + let _: () = msg_send![&app, setDelegate: delegate]; + } + } + REOPEN.with(|r| if let Ok(mut r) = r.try_borrow_mut() { *r = Some(Box::new(reopen)); }); + } + + /// The app has no Dock icon now (`App::accessory`, `AppHandle::set_dock_icon(false)`). + pub(crate) fn accessory() -> bool { + let Some(mtm) = MainThreadMarker::new() else { return false }; + NSApplication::sharedApplication(mtm).activationPolicy() != NSApplicationActivationPolicy::Regular + } + + /// Unhides the app if it is hidden (⌘H, Hide Others), which also activates it. + pub(crate) fn unhide() { + let Some(mtm) = MainThreadMarker::new() else { return }; + let app = NSApplication::sharedApplication(mtm); + if app.isHidden() { app.unhide(None); } + } + + /// Activates the app with `window` key and in front. Unlike winit's `focus_window`, this + /// also works while the window is still deminiaturizing. + pub(crate) fn front(window: &winit::window::Window) { + let Some(mtm) = MainThreadMarker::new() else { return }; + #[allow(deprecated)] + NSApplication::sharedApplication(mtm).activateIgnoringOtherApps(true); + if let Some(window) = crate::platform::macos::ns_window(window) { window.makeKeyAndOrderFront(None); } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn window(visible: bool, hidden_at: Option<u64>) -> Candidate { + Candidate { reopenable: true, visible, minimized: false, hidden_at, main: false } + } + + #[test] + fn reopening_shows_the_window_hidden_last() { + let windows = [Candidate { main: true, ..window(false, Some(1)) }, window(false, Some(3)), window(false, Some(2))]; + assert!(!has_visible(&windows)); + assert_eq!(target(&windows), Some(1)); + } + + #[test] + fn a_visible_window_leaves_reopening_alone() { + let windows = [window(true, None), window(false, Some(5))]; + assert!(has_visible(&windows)); + assert_eq!(target(&windows), None); + } + + #[test] + fn a_minimized_window_comes_back_first() { + let windows = [window(false, Some(9)), Candidate { minimized: true, ..window(false, None) }]; + assert_eq!(target(&windows), Some(1)); + } + + #[test] + fn without_a_hidden_window_the_main_window_shows() { + let windows = [window(false, None), Candidate { main: true, ..window(false, None) }]; + assert_eq!(target(&windows), Some(1)); + } + + #[test] + fn panels_and_closed_windows_never_come_back_or_count_as_visible() { + let panel = Candidate { reopenable: false, ..window(true, Some(7)) }; + let closed = Candidate { reopenable: false, main: true, ..window(false, Some(8)) }; + assert!(!has_visible(&[panel, closed])); + assert_eq!(target(&[panel, closed]), None); + assert_eq!(target(&[panel, closed, window(false, Some(1))]), Some(2)); + } + + #[test] + fn appkit_handles_a_reopen_unless_rune_brings_a_window_back() { + assert!(appkit_handles(true, true), "a window shows: AppKit's handling, which changes nothing"); + assert!(!appkit_handles(true, false), "none shows: Rune's"); + assert!(appkit_handles(false, false), "the loop is gone: AppKit's"); + } + + #[test] + fn stamps_count_up() { + let (a, b) = (stamp(), stamp()); + assert!(b > a); + } +} diff --git a/app/vendor/rune/crates/rune/src/platform/scroll_bars.rs b/app/vendor/rune/crates/rune/src/platform/scroll_bars.rs new file mode 100644 index 0000000..67d42e0 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/platform/scroll_bars.rs @@ -0,0 +1,266 @@ +//! The user's "Show scroll bars" and "Click in the scroll bar to" preferences, and the +//! pointing-device scroller style. +//! +//! macOS reads `AppleShowScrollBars`, `AppleScrollerPagingBehavior` and +//! `NSScroller.preferredScrollerStyle`, and follows +//! `NSPreferredScrollerStyleDidChangeNotification` while windows are open; iOS always uses +//! overlay scroll bars; other platforms and headless runs default to [`ScrollBars::WhenScrolling`]. + +/// The system's "Show scroll bars" preference (System Settings › Appearance on macOS). +/// +/// Read it with [`system_scroll_bars`], or in a view with [`Cx::scroll_bars`](crate::Cx::scroll_bars) +/// and [`Cx::overlay_scroll_bars`](crate::Cx::overlay_scroll_bars), which re-run the view and its +/// memos when the preference or connected pointing device changes. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] +pub enum ScrollBars { + /// Follow the connected pointing device (`NSScroller.preferredScrollerStyle` on macOS): + /// overlay with a trackpad or touch surface, always shown with a mouse. + Automatic, + /// Overlay over the content while scrolling and fade out after a short rest. + #[default] + WhenScrolling, + /// Show whenever content overflows. + Always, +} + +impl ScrollBars { + /// Whether scroll bars overlay and fade out at rest, given whether the pointing device prefers + /// overlay scrollers (`NSScroller.preferredScrollerStyle == .overlay` on macOS). iOS always + /// uses overlay scroll bars. + pub const fn is_overlay(self, scroller_overlay: bool) -> bool { + #[cfg(target_os = "ios")] + { + let _ = scroller_overlay; + return true; + } + #[cfg(not(target_os = "ios"))] + match self { + Self::Automatic => scroller_overlay, + Self::WhenScrolling => true, + Self::Always => false, + } + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub(crate) struct SystemScrollBars { + pub bars: ScrollBars, + pub scroller_overlay: bool, + /// A click in the track jumps to the spot clicked instead of paging toward it. + pub jump_to_click: bool, +} + +impl SystemScrollBars { + pub const DEFAULT: Self = Self { bars: ScrollBars::WhenScrolling, scroller_overlay: true, jump_to_click: false }; + + pub const fn is_overlay(self) -> bool { + self.bars.is_overlay(self.scroller_overlay) + } + + pub const fn with_override(self, bars: Option<ScrollBars>) -> Self { + match bars { + Some(bars) => Self { bars, ..self }, + None => self, + } + } +} + +impl Default for SystemScrollBars { + fn default() -> Self { + Self::DEFAULT + } +} + +#[cfg(any(target_os = "macos", test))] +fn parse_show_scroll_bars(raw: Option<&str>) -> ScrollBars { + match raw { + Some("Always") => ScrollBars::Always, + Some("WhenScrolling") => ScrollBars::WhenScrolling, + _ => ScrollBars::Automatic, + } +} + +thread_local! { + static VIEW_SCOPE: std::cell::Cell<Option<(SystemScrollBars, u64)>> = const { std::cell::Cell::new(None) }; +} + +/// Holds a runtime's scroll-bar preference and id for [`system_scroll_bars`] during a view build. +#[must_use] +pub(crate) struct Scope(Option<(SystemScrollBars, u64)>); + +pub(crate) fn scope(bars: SystemScrollBars, runtime_id: u64) -> Scope { + Scope(VIEW_SCOPE.with(|c| c.replace(Some((bars, runtime_id))))) +} + +impl Drop for Scope { + fn drop(&mut self) { + VIEW_SCOPE.with(|c| c.set(self.0)); + } +} + +pub(crate) fn scoped() -> Option<SystemScrollBars> { + VIEW_SCOPE.with(std::cell::Cell::get).map(|(bars, _)| bars) +} + +#[doc(hidden)] +pub fn current_runtime_id() -> u64 { + VIEW_SCOPE.with(std::cell::Cell::get).map_or(0, |(_, id)| id) +} + +/// The user's "Show scroll bars" preference: the building window's setting inside a view, or the +/// host setting outside one (`AppleShowScrollBars` on macOS, [`ScrollBars::WhenScrolling`] +/// elsewhere and headless). +pub fn system_scroll_bars() -> ScrollBars { + scoped().unwrap_or_else(current).bars +} + +/// Whether the connected pointing device prefers overlay scroll bars: the building window's +/// setting inside a view, or `NSScroller.preferredScrollerStyle == .overlay` on macOS (`true` +/// elsewhere and headless). +pub fn system_scroller_overlay() -> bool { + scoped().unwrap_or_else(current).scroller_overlay +} + +/// Whether a click in a scroll bar's track jumps to the spot clicked rather than paging toward +/// it (System Settings › Appearance › "Click in the scroll bar to"): the building window's setting +/// inside a view, or `AppleScrollerPagingBehavior` on macOS (`false`, paging, elsewhere and +/// headless). Option-click does the other. +pub fn system_scroller_jumps() -> bool { + scoped().unwrap_or_else(current).jump_to_click +} + +pub(crate) fn current() -> SystemScrollBars { + #[cfg(target_os = "macos")] + return mac::current(); + #[cfg(not(target_os = "macos"))] + SystemScrollBars::DEFAULT +} + +pub(crate) fn reread() -> SystemScrollBars { + #[cfg(target_os = "macos")] + return mac::reread(); + #[cfg(not(target_os = "macos"))] + SystemScrollBars::DEFAULT +} + +/// Starts following scroller-style changes (`NSPreferredScrollerStyleDidChangeNotification`), once +/// per process: each change rereads the preference and asks every window to redraw, which hands it +/// to its runtime. Main thread. +pub(crate) fn watch() { + #[cfg(target_os = "macos")] + mac::watch(); +} + +#[cfg(target_os = "macos")] +#[allow(unsafe_code)] +mod mac { + use super::{SystemScrollBars, parse_show_scroll_bars}; + use objc2::{MainThreadMarker, class, msg_send, rc::Retained, runtime::{AnyObject, Bool}}; + use objc2_foundation::{NSString, NSUserDefaults}; + use std::{cell::Cell, sync::Mutex}; + + const OVERLAY_STYLE: isize = 1; + + static CURRENT: Mutex<Option<SystemScrollBars>> = Mutex::new(None); + + pub(super) fn current() -> SystemScrollBars { + let mut cur = CURRENT.lock().unwrap_or_else(|e| e.into_inner()); + if cur.is_none() && MainThreadMarker::new().is_some() { + *cur = Some(read()); + } + cur.unwrap_or_default() + } + + pub(super) fn reread() -> SystemScrollBars { + let mut cur = CURRENT.lock().unwrap_or_else(|e| e.into_inner()); + if MainThreadMarker::new().is_some() { + *cur = Some(read()); + } + cur.unwrap_or_default() + } + + fn read() -> SystemScrollBars { + // SAFETY: main thread (`MainThreadMarker` checked by callers); `standardUserDefaults` + // returns a valid shared instance and `NSScroller.preferredScrollerStyle` returns NSInteger. + unsafe { + let pref = NSUserDefaults::standardUserDefaults() + .stringForKey(&NSString::from_str("AppleShowScrollBars")) + .map(|s| s.to_string()); + let style: isize = msg_send![class!(NSScroller), preferredScrollerStyle]; + let jump_to_click = NSUserDefaults::standardUserDefaults() + .boolForKey(&NSString::from_str("AppleScrollerPagingBehavior")); + SystemScrollBars { + bars: parse_show_scroll_bars(pref.as_deref()), + scroller_overlay: style == OVERLAY_STYLE, + jump_to_click, + } + } + } + + pub(super) fn watch() { + thread_local! { static WATCHING: Cell<bool> = const { Cell::new(false) }; } + if MainThreadMarker::new().is_none() || WATCHING.replace(true) { + return; + } + *CURRENT.lock().unwrap_or_else(|e| e.into_inner()) = Some(read()); + let block = block2::RcBlock::new(|_: *mut AnyObject| { + *CURRENT.lock().unwrap_or_else(|e| e.into_inner()) = Some(read()); + // SAFETY: main thread (the observer has no queue, and AppKit posts this there); + // `windows` is an NSArray of NSWindow, each with a content view or nil. + unsafe { + let app: *mut AnyObject = msg_send![class!(NSApplication), sharedApplication]; + let windows: *mut AnyObject = msg_send![app, windows]; + let count: usize = msg_send![windows, count]; + for i in 0..count { + let window: *mut AnyObject = msg_send![windows, objectAtIndex: i]; + let view: *mut AnyObject = msg_send![window, contentView]; + if !view.is_null() { + let _: () = msg_send![view, setNeedsDisplay: Bool::YES]; + } + } + } + }); + // SAFETY: main thread; the observer lives for the process, so its token is leaked. + unsafe { + let center: Retained<AnyObject> = msg_send![class!(NSNotificationCenter), defaultCenter]; + let name = NSString::from_str("NSPreferredScrollerStyleDidChangeNotification"); + let token: Option<Retained<AnyObject>> = msg_send![ + &*center, + addObserverForName: &*name, + object: std::ptr::null::<AnyObject>(), + queue: std::ptr::null::<AnyObject>(), + usingBlock: &*block + ]; + std::mem::forget(token); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn defaults_and_resolution_match_system_modes() { + assert_eq!(ScrollBars::default(), ScrollBars::WhenScrolling); + assert!(SystemScrollBars::DEFAULT.is_overlay()); + assert!(ScrollBars::WhenScrolling.is_overlay(false)); + assert!(ScrollBars::WhenScrolling.is_overlay(true)); + #[cfg(not(target_os = "ios"))] + { + assert!(!ScrollBars::Always.is_overlay(true)); + assert!(!ScrollBars::Always.is_overlay(false)); + assert!(ScrollBars::Automatic.is_overlay(true)); + assert!(!ScrollBars::Automatic.is_overlay(false)); + } + } + + #[test] + fn parses_macos_show_scroll_bars_values() { + assert_eq!(parse_show_scroll_bars(None), ScrollBars::Automatic); + assert_eq!(parse_show_scroll_bars(Some("Automatic")), ScrollBars::Automatic); + assert_eq!(parse_show_scroll_bars(Some("WhenScrolling")), ScrollBars::WhenScrolling); + assert_eq!(parse_show_scroll_bars(Some("Always")), ScrollBars::Always); + assert_eq!(parse_show_scroll_bars(Some("Unexpected")), ScrollBars::Automatic); + } +} diff --git a/app/vendor/rune/crates/rune/src/platform/web.rs b/app/vendor/rune/crates/rune/src/platform/web.rs new file mode 100644 index 0000000..25cd343 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/platform/web.rs @@ -0,0 +1,594 @@ +//! Single-threaded browser shell. GPU initialization yields to the browser; winit owns +//! demand-driven rAF and its device-pixel-content-box ResizeObserver (with DPR fallback). +use std::{cell::RefCell, rc::Rc, sync::{Arc, atomic::Ordering}, time::Duration}; +use wasm_bindgen::JsCast; +use winit::{application::ApplicationHandler, event::WindowEvent, event_loop::{ActiveEventLoop, ControlFlow, EventLoop, EventLoopProxy}, + platform::web::{EventLoopExtWebSys, WindowAttributesExtWebSys, WindowExtWebSys}, window::{Window, WindowId}}; +use crate::{App, Env, app::SharedCore, render::Gpu, time::Instant}; +use super::web_math; +use app::{PendingApp, TypedWebApp, WebApp}; +use gpu::Draw; + +mod app; +mod cpu_canvas; +mod frame; +mod full_faces; +mod gpu; +mod handover; +pub(crate) mod health; +mod input; +mod page; +mod page_fonts; +mod pipelines; +pub(crate) mod platform; +pub(crate) use rune_text::segmenter; + +thread_local! { + static INSETS: std::cell::Cell<[f32; 4]> = const { std::cell::Cell::new([0.0; 4]) }; + /// The largest viewport's height in CSS points (`100lvh`): a page's band is sized from it so + /// a phone's toolbar coming and going never changes the band. + static LARGE_VIEWPORT: std::cell::Cell<f32> = const { std::cell::Cell::new(0.0) }; + /// The page's primary pointer can't hover (CSS `(hover: none)`): a phone's or tablet's touch screen. + static PRIMARY_POINTER: std::cell::Cell<PrimaryPointer> = const { std::cell::Cell::new(PrimaryPointer::Hover) }; +} + +pub(crate) fn safe_area() -> [f32; 4] { INSETS.get() } + +/// The largest viewport's height in CSS points, or 0 before the browser has reported one. +pub(crate) fn large_viewport() -> f32 { LARGE_VIEWPORT.get() } + +#[derive(Clone, Copy, PartialEq, Eq)] +enum PrimaryPointer { Hover, NoHover, Touch } + +pub(crate) fn hover_none() -> bool { PRIMARY_POINTER.get() != PrimaryPointer::Hover } +pub(crate) fn touch_controls() -> bool { PRIMARY_POINTER.get() == PrimaryPointer::Touch } + +/// Fetches the font at `url` now, for something about to draw in it (a terminal's face, say), +/// as `App::font_url_later` fetches its fonts after the first frame: every window takes it up +/// on its next frame once it arrives; until then text in its family sets in the slot's fallback. +/// Asked before the first frame, it waits for it. Each URL loads once. +pub fn font_url_now(url: &str) { + full_faces::now(url); +} + +/// Open an HTTP(S) or mail link in a new browser tab. Call from a user input handler; +/// browser popup policy applies. The new page receives no opener or referrer. +pub fn open_url(url: &str) -> Result<(), String> { + let url = crate::open_url::check(url).map_err(|e| e.to_string())?; + platform::open_link(&url).map_err(|e| format!("{e:?}")) +} + +/// Open a link in this tab, as `Tx::open_url_same_tab` does: a link on the page's origin goes +/// to the app's `App::same_tab_router` first, and the browser loads it with `location.assign` +/// unless the router handled it. A link without a scheme (`/notes/42`) is relative to the page. +pub fn open_url_same_tab(url: &str) -> Result<(), String> { + let url = crate::open_url::check_same_tab(url).map_err(|e| e.to_string())?; + let resolved = platform::resolve_link(&url).map_err(|e| format!("{e:?}"))?; + let href = resolved.get(0).as_string().unwrap_or_default(); + if resolved.get(1).is_truthy() && page::route(&href) { return Ok(()); } + platform::assign_link(&href).map_err(|e| format!("{e:?}")) +} + +#[derive(Clone, Copy)] +enum Wake { + /// The app's `font_url` fonts are in: the app starts (on the CPU, or with the GPU). + Start, + /// The GPU came, or couldn't. + Ready, + /// Time to see whether the page is quiet enough to start the GPU (`Browser::maybe_start_gpu`). + StartGpu, + App, +} + +/// How a page's frames start: on the CPU until WebGPU takes over (a full-window app, the +/// default, with or without a compositor), or on the GPU from the first frame (a page that is +/// the document or is inline). `globalThis.RUNE_CPU_FIRST` set to `"off"` starts every app on the +/// GPU; `"only"` keeps it on the CPU for good. +#[derive(Clone, Copy, PartialEq, Eq)] +enum Start { + GpuFirst, + CpuFirst, + CpuOnly, +} + +fn cpu_first_asked() -> Option<String> { + js_sys::Reflect::get(&js_sys::global(), &"RUNE_CPU_FIRST".into()).ok().and_then(|v| v.as_string()) +} + +pub(crate) fn run<S: 'static>(app: App<S>) -> Result<(), String> { + run_pending(TypedWebApp::pending(app)?) +} + +fn run_pending(app: PendingApp) -> Result<(), String> { + console_error_panic_hook::set_once(); + segmenter::install(); + text_probe(); + page::start(quitting(&app.shared), Box::new(move || spawn(app))) +} + +/// For a measuring harness that sets `globalThis.__runeTextProbe` before the module runs: +/// `globalThis.__runeLines(text, size, weight, width)` gives the UTF-16 offsets where Rune starts +/// each line of `text` in the sans family (points), to compare with the browser's own lines. +fn text_probe() { + let global = js_sys::global(); + if !js_sys::Reflect::get(&global, &"__runeTextProbe".into()).is_ok_and(|v| v.is_truthy()) { return; } + let lines = wasm_bindgen::closure::Closure::<dyn Fn(String, f32, f32, f32) -> Vec<u32>>::new(|text: String, size: f32, weight: f32, width: f32| { + crate::text::line_starts(&text, size, weight, width).into_iter().map(|b| text[..b].encode_utf16().count() as u32).collect::<Vec<u32>>() + }); + js_sys::Reflect::set(&global, &"__runeLines".into(), lines.as_ref()).ok(); + lines.forget(); +} + +fn quitting(shared: &Arc<SharedCore>) -> Box<dyn Fn() -> bool> { + let shared = shared.clone(); + Box::new(move || shared.quitting.load(Ordering::Acquire)) +} + +fn spawn(mut app: PendingApp) -> Result<(), String> { + if app.shared.quitting.load(Ordering::Acquire) { return Ok(()); } + let event_loop = EventLoop::<Wake>::with_user_event().build().map_err(|e| e.to_string())?; + event_loop.set_control_flow(ControlFlow::Wait); + let proxy = event_loop.create_proxy(); + let shared = app.shared.clone(); + let wake = proxy.clone(); + shared.connect(Arc::new(move || { wake.send_event(Wake::App).ok(); })); + page::occupy(quitting(&shared), app.same_tab_router.take()); + event_loop.spawn_app(Browser { app: Some(app), shared, proxy, window: None, embedded: false, document: false, owns_canvas: true, + borrowed: page::Borrowed::default(), start: Start::GpuFirst, fonts: Rc::default(), pending: Rc::default(), warmed: Rc::default(), running: Rc::default(), + lost: Rc::default(), webgl_watch: None, webgl_restored: Rc::default(), webgl_restoring: false, waiting: None, first_at: None, drawn_at: None, gpu_asked: false }); + Ok(()) +} + +fn warn_native_window(requests: &crate::app::WindowRequests) { + if requests.window.as_ref().is_some_and(|r| !matches!(r, crate::app::WindowRequest::Open(_) | crate::app::WindowRequest::Show)) + || requests.position.is_some() || requests.place.is_some() || requests.activation == Some(crate::app::Activation::Minimize) { + web_sys::console::warn_1(&"Native window management is ignored on web.".into()); + } +} + +struct Browser { + app: Option<PendingApp>, + shared: Arc<SharedCore>, + proxy: EventLoopProxy<Wake>, + window: Option<Arc<Window>>, + /// Inline in the page at its parent's width, rather than covering the viewport. + embedded: bool, + /// The app is the page (`App::web_document`): the browser scrolls it. + document: bool, + /// Rune made the canvas (no `App::canvas_id`), so it removes it when the app ends. + owns_canvas: bool, + borrowed: page::Borrowed, + start: Start, + /// The bytes of `App::font_url`'s fonts that loaded, once all have answered. + fonts: Rc<RefCell<Option<Vec<Vec<u8>>>>>, + /// The GPU, once the browser answered for it. + pending: Rc<RefCell<Option<Result<(Gpu, wgpu::Surface<'static>), String>>>>, + /// The pipelines compiled ahead for that GPU (`pipelines::warm`), kept until its renderer is made. + warmed: Rc<RefCell<Option<pipelines::Warmed>>>, + running: Rc<RefCell<Option<Running>>>, + /// Why the browser lost the GPU device or WebGL2 context, until `lost_device` handles it. + lost: Rc<RefCell<Option<gpu::Loss>>>, + /// Active `webglcontextlost` / `webglcontextrestored` listeners once WebGL2 has run on the canvas. + webgl_watch: Option<health::WebglWatch>, + /// Set by `webglcontextrestored` until `maybe_restore_webgl` spawns a WebGL2 rebuild. + webgl_restored: Rc<std::cell::Cell<bool>>, + /// True while a WebGL2 rebuild after `webglcontextrestored` is in flight. + webgl_restoring: bool, + /// The deadline the event loop was last told to wait for (`None`: none). winit schedules a + /// browser task for each new control flow and aborts the last one's, so the same deadline + /// isn't set again. + waiting: Option<u64>, + /// For a page that starts on the CPU: when its first frame was presented, when it last drew + /// one that changed more than an ambient loop (a spinner's step), and whether the GPU was + /// asked for. + first_at: Option<Instant>, + drawn_at: Option<Instant>, + gpu_asked: bool, +} + +struct Running { + draw: Draw, + app: Box<dyn WebApp>, + shared: Arc<SharedCore>, + clock: crate::frame::clock::FrameClock, + suspended: bool, + /// An input or app event can share a redraw with the animation timer. In that case the + /// timer must not consume the redraw as a stand-alone paint. + full_redraw: bool, + embedded: bool, + document: bool, + /// The first frame is on screen. + presented: bool, + /// `App::on_ready`, which runs once that first frame is presented, as a window's does. + on_ready: Option<crate::app::OnWindow>, + /// `App::font_url_later`'s fonts, fetched once that first frame is presented. + late_fonts: Vec<String>, + /// The app's fonts, which the page takes as its own once that first frame is presented + /// (`page_fonts`). + fonts: &'static [&'static [u8]], + /// Where the canvas was last put in the document (a page's band top), in points. + band: Option<f32>, + /// The canvas's size in physical pixels: the CPU paints at it, the GPU's surface is it. + size: (u32, u32), + cursor: crate::cursor::os::OsCursor, + _menus: crate::native_menu::MenuGuard, + shortcuts: crate::shortcuts::Guard, + input: input::Bridge, + clipboard: crate::clipboard::Client, +} + +impl Running { + /// Ends the app: listeners off the page, then the GPU device, which the WebGPU backend + /// doesn't destroy on drop. + fn close(self) { + self.shared.set_visible(false); + let device = self.draw.gpu().map(|side| side.gpu.device.clone()); + drop(self); + if let Some(device) = device { device.destroy(); } + } +} + +/// Reports `message` to the console, and on screen unless the app is the page: a document's +/// static HTML is a working page, and an opaque overlay would cover the page a reader can still +/// read and scroll. Ending the app leaves that page as the browser found it. +fn error(message: &str, target: Option<&web_sys::HtmlCanvasElement>, embedded: bool, document: bool) { + web_sys::console::error_1(&message.into()); + let Some(doc) = web_sys::window().and_then(|w| w.document()) else { return }; + if document && doc.query_selector("[data-rune-static]").ok().flatten().is_some() { return; } + if let Ok(label) = doc.create_element("pre") { + label.set_text_content(Some(message)); + if embedded && let Some(canvas) = target && let Some(parent) = canvas.parent_element() { + label.set_attribute("style", "margin:0;padding:16px;white-space:pre-wrap;background:Canvas;color:CanvasText;border:1px solid #444;border-radius:8px").ok(); + parent.insert_before(&label, Some(canvas)).ok(); + return; + } + if let Some(body) = doc.body() { + label.set_attribute("style", "position:fixed;inset:0;z-index:1;padding:24px;white-space:pre-wrap;background:Canvas;color:CanvasText").ok(); + body.append_child(&label).ok(); + } + } +} + +impl Browser { + fn end(&self, event_loop: &ActiveEventLoop) { + self.shared.quitting.store(true, Ordering::Release); + event_loop.exit(); + } + + /// Makes the running app once its fonts are in, and for a page that starts on the GPU its + /// GPU too: the runtime, the input bridge and what draws its first frame. + fn start_app(&mut self, event_loop: &ActiveEventLoop) { + if self.running.borrow().is_some() || self.app.is_none() { return; } + let Some(window) = self.window.clone() else { return }; + if self.fonts.borrow().is_none() { return; } + let gpu_first = self.start == Start::GpuFirst; + if gpu_first && self.pending.borrow().is_none() { return; } + let fonts = self.fonts.borrow_mut().take().unwrap_or_default(); + let gpu = if gpu_first { + match self.pending.borrow_mut().take() { + Some(Ok(gpu)) => Some(gpu), + Some(Err(e)) => { + self.shared.set_window_error(Some(e.clone())); + error(&e, window.canvas().as_ref(), self.embedded, self.document); + self.end(event_loop); + return; + } + None => return, + } + } else { + None + }; + let mut pending = self.app.take().expect("one canvas initialization"); + let fit_height = pending.fit_height; + let spec_size = pending.size; + let on_ready = pending.on_ready.take(); + let late_fonts = std::mem::take(&mut pending.late_font_urls); + let scale = window.scale_factor() as f32; + let document = self.document; + let max_dim = gpu.as_ref().map_or(frame::CPU_MAX_DIM, |(gpu, _)| gpu.device.limits().max_texture_dimension_2d.max(1)); + // A page's canvas is its band: the visible height plus a skirt of overscan, sized + // before the box is measured so the first frame is that tall. + let band = if document { + let (view, band) = frame::band_css(&window, scale, max_dim); + frame::set_band_height(&window, band); + Some((view, band)) + } else { + None + }; + // Both sides from the canvas's own box: a browser that reports the box in CSS pixels + // (Chromium's emulated device scale) would otherwise leave the height at the CSS + // height, which its style stretches back over the screen: a 2× vertical stretch. + let inner = window.inner_size(); + let css = window.canvas().map_or((0.0, 0.0), |c| (c.client_width().max(0) as f32, c.client_height().max(0) as f32)); + let fixed = web_math::fix_canvas_size(css, (inner.width, inner.height), spec_size, scale, fit_height); + let mut size = winit::dpi::PhysicalSize::new(fixed.0, fixed.1); + let dark = web_sys::window().and_then(|w| w.match_media("(prefers-color-scheme: dark)").ok().flatten()).is_some_and(|q| q.matches()); + let proxy = self.proxy.clone(); + let wake: crate::Waker = Arc::new(move || { proxy.send_event(Wake::App).ok(); }); + let app::StartedWebApp { mut app, menus, shortcuts, fonts: spec_fonts } = pending.start( + fonts, + (size.width as f32 / scale, size.height as f32 / scale), + Env::new(dark, scale), + wake.clone(), + ); + // A page brings its own fonts for its mirror; an app's are the page's (`page_fonts`). + let page_fonts = if document { &[][..] } else { spec_fonts }; + if let Some((view, band)) = band { + let rt = app.rt_mut(); + rt.page_mode(); + rt.set_band(band, view); + rt.set_viewport((size.width as f32 / scale, band), scale); + } else if fit_height { + let w = (size.width as f32 / scale).max(1.0); + { + let rt = app.rt_mut(); + rt.host.fit_height = true; + rt.set_viewport((w, spec_size.1), scale); + } + let h = app.content_height(); + app.rt_mut().set_viewport((w, h), scale); + size.height = (h * scale).round().max(1.0) as u32; + if let Some(canvas) = window.canvas() { + canvas.style().set_property("height", &format!("{h}px")).ok(); + } + } + let now = Instant::now(); + { + let rt = app.rt_mut(); + rt.set_os_drag(false); + rt.wall_start = Some(now); + rt.host.open_urls_natively = true; + rt.frame.set_record_events(false); + } + let mut clipboard = crate::clipboard::Client::default(); + clipboard.connect(wake); + self.shared.set_visible(true); + let physical = (size.width.clamp(1, max_dim), size.height.clamp(1, max_dim)); + let mut started_webgl = false; + let draw = match gpu { + Some((gpu, surface)) => { + match gpu::gpu_side(gpu, surface, physical, app.rt_mut(), self.lost.clone(), self.proxy.clone()) { + Ok(side) => { + started_webgl = side.backend == wgpu::Backend::Gl; + Draw::Gpu(side) + } + Err(e) => { error(&e, window.canvas().as_ref(), self.embedded, self.document); self.end(event_loop); return; } + } + } + None => { + let Some(canvas) = window.canvas() else { return }; + let Some(cpu) = cpu_canvas::CpuCanvas::under(&canvas) else { + error("This page couldn't make a canvas to draw in.", Some(&canvas), self.embedded, self.document); + self.end(event_loop); + return; + }; + // The first frame's glyphs queue fills for the CPU painter. + crate::render::cpu_boot::attach_text(&mut app.rt_mut().text.atlas); + Draw::Cpu { cpu, failed: self.start == Start::CpuOnly } + } + }; + if started_webgl { self.ensure_webgl_watch(); } + let cursor = crate::cursor::os::OsCursor::new(); + let input = input::Bridge::new(&window.canvas().unwrap(), Rc::downgrade(&self.running), window.clone(), + input::Mode { embedded: self.embedded, fit_height, document }); + *self.running.borrow_mut() = Some(Running { draw, app, shared: self.shared.clone(), input, clipboard, + clock: crate::frame::clock::FrameClock::new(now), suspended: false, full_redraw: true, embedded: self.embedded, + document, presented: false, band: None, size: physical, on_ready, late_fonts, fonts: page_fonts, + cursor, _menus: menus, shortcuts }); + crate::marks::mark("web.started"); + window.request_redraw(); + } +} + +impl ApplicationHandler<Wake> for Browser { + fn resumed(&mut self, event_loop: &ActiveEventLoop) { + if self.window.is_some() { return; } + let app = self.app.as_ref().expect("app before canvas"); + self.document = app.document; + self.embedded = app.embedded; + let existing = match &app.canvas_id { + Some(id) => { + let Some(el) = web_sys::window().and_then(|w| w.document()).and_then(|d| d.get_element_by_id(id)) else { + error(&format!("canvas #{id} not found in document"), None, true, self.document); + self.end(event_loop); + return; + }; + match el.dyn_into::<web_sys::HtmlCanvasElement>() { + Ok(canvas) => Some(canvas), + Err(_) => { + error(&format!("element #{id} is not a <canvas>"), None, true, self.document); + self.end(event_loop); + return; + } + } + } + None => None, + }; + self.owns_canvas = existing.is_none(); + if let Some(canvas) = &existing { self.borrowed.canvas(canvas); } + // Not `active`: winit would focus the canvas before it's styled, and a browser scrolls a + // focused element into view, so a page landed at its foot. The bridge focuses a + // full-window canvas itself, without scrolling. + let mut attrs = Window::default_attributes().with_title(app.title).with_prevent_default(false).with_active(false); + attrs = match &existing { + Some(c) => attrs.with_canvas(Some(c.clone())).with_append(false), + None => attrs.with_append(true), + }; + let window = match event_loop.create_window(attrs) { + Ok(window) => Arc::new(window), + Err(e) => { error(&e.to_string(), existing.as_ref(), self.embedded, self.document); self.end(event_loop); return; } + }; + let canvas = window.canvas().expect("winit web canvas"); + if !canvas.has_attribute("tabindex") { + canvas.set_attribute("tabindex", "0").ok(); + } + if self.document { + // The browser scrolls the page over a canvas that is part of the document, not fixed + // to the screen: the compositor moves the pixels Rune drew at the display's own rate, + // and a frame is only drawn when the window nears the band's edge. Rune puts it in a + // clipper as tall as the page (the bridge) and translates it to `page.top`. + canvas.set_attribute("tabindex", "-1").ok(); + canvas.style().set_css_text("position:absolute;left:0;top:0;width:100%;display:block;transform:translate3d(0,0,0);will-change:transform;pointer-events:auto;touch-action:pan-y pinch-zoom;outline:none;user-select:none;-webkit-user-select:none"); + if let Some(document) = web_sys::window().and_then(|w| w.document()) { + self.borrowed.viewport(&document); + document.set_title(app.title); + if let Some(body) = document.body() { body.style().set_property("margin", "0").ok(); } + } + } else if self.embedded { + let touch = if app.fit_height { "pan-y" } else { "none" }; + canvas.style().set_css_text(&format!( + "display:block;width:100%;touch-action:{touch};outline:none;user-select:none;-webkit-user-select:none" + )); + } else { + // No border/padding: winit's physical input and resize coordinates must match pixels. + canvas.style().set_css_text("position:fixed;inset:0;width:100%;height:100%;display:block;touch-action:none;outline:none;user-select:none;-webkit-user-select:none"); + if let Some(document) = web_sys::window().and_then(|w| w.document()) { + self.borrowed.viewport(&document); + document.set_title(app.title); + if let Some(body) = document.body() { + let style = body.style(); + for (name, value) in [("margin", "0"), ("overflow", "hidden"), ("overscroll-behavior", "none")] { + style.set_property(name, value).ok(); + } + } + } + } + // A full-window app starts on the CPU, under the GPU's canvas, which stays see-through + // (and takes the input) until the GPU's first frame is done; one with a compositor too: + // its effect slots draw from the hand-over on, and never where the browser has no GPU + // (starting on the GPU would leave such a page with nothing at all). A page that is the + // document or sits inline starts on the GPU. + let asked = cpu_first_asked(); + self.start = if self.document || self.embedded || asked.as_deref() == Some("off") { + Start::GpuFirst + } else if asked.as_deref() == Some("only") { + Start::CpuOnly + } else { + Start::CpuFirst + }; + if self.start != Start::GpuFirst { canvas.style().set_property("opacity", "0").ok(); } + // The fonts download while the GPU starts; the CPU's first frame needs only them. + let fonts: Vec<_> = app.font_urls.iter().map(|url| (url.clone(), platform::fetch_bytes(url))).collect(); + self.window = Some(window); + let (slot, proxy) = (self.fonts.clone(), self.proxy.clone()); + wasm_bindgen_futures::spawn_local(async move { + let mut loaded = Vec::new(); + for (url, font) in fonts { + match wasm_bindgen_futures::JsFuture::from(font).await { + Ok(bytes) => loaded.push(js_sys::Uint8Array::new(&bytes).to_vec()), + Err(e) => web_sys::console::warn_2(&format!("rune: font {url} did not load:").into(), &e), + } + } + *slot.borrow_mut() = Some(loaded); + proxy.send_event(Wake::Start).ok(); + }); + // A page that starts on the CPU asks for the GPU once its first frames are up and it's + // quiet (`maybe_start_gpu`): asked at once, the browser's GPU process makes the adapter + // and compiles the renderer's pipelines while the first frame waits on it to show. + if self.start == Start::GpuFirst { self.ask_gpu(); } + } + + fn user_event(&mut self, event_loop: &ActiveEventLoop, event: Wake) { + if self.shared.quitting.load(Ordering::Acquire) { self.end(event_loop); return; } + if self.lost_device(event_loop) { return; } + if self.window.is_none() { return; } + self.maybe_restore_webgl(); + match event { + Wake::Start | Wake::Ready => { + self.start_app(event_loop); + self.gpu_came(); + } + Wake::StartGpu => self.maybe_start_gpu(), + Wake::App => self.hand_over_if_done(), + } + let Some(window) = self.window.as_ref() else { return }; + if let Some(r) = &mut *self.running.borrow_mut() { + r.full_redraw = true; + r.shortcuts.drain(); + r.clipboard.receive_core(r.app.rt_mut()); + let requests = self.shared.take_window(); + if requests.quit.is_some() { self.end(event_loop); return; } + warn_native_window(&requests); + let had_updates = { + let _receiving = r.shortcuts.receiving(); + r.app.drain_updates() + }; + if !had_updates { r.app.rt_mut().invalidate(); } + window.request_redraw(); + } + } + + fn window_event(&mut self, event_loop: &ActiveEventLoop, _: WindowId, event: WindowEvent) { + if matches!(event, WindowEvent::Focused(_)) { return; } + if self.lost_device(event_loop) { return; } + if matches!(event, WindowEvent::RedrawRequested) { return self.redraw(event_loop); } + let mut running = self.running.borrow_mut(); + let (Some(window), Some(r)) = (&self.window, &mut *running) else { return }; + let _input = crate::input::time::arrived(&event); + r.full_redraw = true; + if r.window_input(&event, window) { window.request_redraw(); return; } + match event { + WindowEvent::Resized(size) => { + r.resize_surface(window, size, window.scale_factor() as f32); + window.request_redraw(); + } + WindowEvent::ScaleFactorChanged { scale_factor, .. } => { + r.resize_surface(window, window.inner_size(), scale_factor as f32); + window.request_redraw(); + } + WindowEvent::ThemeChanged(theme) => { r.app.rt_mut().set_system_dark(theme == winit::window::Theme::Dark); window.request_redraw(); } + _ => {} + } + } + + fn about_to_wait(&mut self, event_loop: &ActiveEventLoop) { + crate::cursor::os::make_pending(event_loop); + // Channels the app serves with `task::serve` get their turn after the handlers that fed them. + crate::task::pump(); + let Ok(running) = self.running.try_borrow() else { return }; + let Some(r) = &*running else { return }; + let rt = r.app.rt(); + let (flow, waiting) = match rt.wake_deadline() { + Some(deadline) if deadline <= rt.wall_start.unwrap().elapsed().as_secs_f64() => { + if let Some(window) = &self.window { window.request_redraw(); } + (ControlFlow::Wait, None) + } + Some(deadline) => (ControlFlow::WaitUntil(crate::time::for_winit(rt.wall_start.unwrap() + Duration::from_secs_f64(deadline.max(0.0)))), Some(deadline.to_bits())), + None => (ControlFlow::Wait, None), + }; + drop(running); + if self.waiting != waiting || waiting.is_none() && !matches!(event_loop.control_flow(), ControlFlow::Wait) { + self.waiting = waiting; + event_loop.set_control_flow(flow); + } + } + + fn new_events(&mut self, _: &ActiveEventLoop, cause: winit::event::StartCause) { + if matches!(cause, winit::event::StartCause::ResumeTimeReached { .. }) { + if let Some(window) = &self.window { window.request_redraw(); } + } + } + + fn exiting(&mut self, _: &ActiveEventLoop) { + self.shared.quitting.store(true, Ordering::Release); + self.webgl_watch = None; + let running = self.running.borrow_mut().take(); + if let Some(r) = running { r.close(); } + self.warmed.borrow_mut().take(); + if let Some(Ok((gpu, _))) = self.pending.borrow_mut().take() { gpu.device.destroy(); } + if let Some(window) = self.window.take() && self.owns_canvas && let Some(canvas) = window.canvas() { canvas.remove(); } + std::mem::take(&mut self.borrowed).give_back(); + INSETS.set([0.0; 4]); + LARGE_VIEWPORT.set(0.0); + PRIMARY_POINTER.set(PrimaryPointer::Hover); + page::vacate(); + } +} + +/// Runs `f` once `delay` has passed, from the page's timer. +fn after(delay: Duration, f: impl FnOnce() + 'static) { + let callback = wasm_bindgen::closure::Closure::once_into_js(f); + if let Some(window) = web_sys::window() { + window.set_timeout_with_callback_and_timeout_and_arguments_0(callback.unchecked_ref(), delay.as_millis().min(i32::MAX as u128) as i32).ok(); + } +} diff --git a/app/vendor/rune/crates/rune/src/platform/web/app.rs b/app/vendor/rune/crates/rune/src/platform/web/app.rs new file mode 100644 index 0000000..1350c51 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/platform/web/app.rs @@ -0,0 +1,295 @@ +//! Non-generic boundary between the web host (`Browser`, `Running`) and the typed `App<S>`, +//! `Runtime<S>`, `Shared<S>` and `Compositor<S>`. + +use std::sync::Arc; + +use wasm_bindgen::JsValue; + +use crate::app::{OnWindow, Shared, SharedCore}; +use crate::compose::{Compositor, Frame}; +use crate::frame::clock::FrameClock; +use crate::render::Renderer; +use crate::runtime::{AppDriver, Runtime, RuntimeCore}; +use crate::time::Instant; +use crate::{App, Env, Waker}; + +/// Non-generic arguments passed to [`WebApp::render_compositor`], which constructs +/// [`Frame<'_, S>`] in place. +pub(super) struct CompositorFrame<'a> { + pub device: &'a wgpu::Device, + pub queue: &'a wgpu::Queue, + pub encoder: &'a mut wgpu::CommandEncoder, + pub target: &'a wgpu::TextureView, + pub format: wgpu::TextureFormat, + pub size: (u32, u32), + pub dt: f64, + pub update_ms: f64, + pub ui: &'a mut Renderer, +} + +/// What [`PendingApp::start`] produces once fonts (and any initial GPU) are ready. +pub(super) struct StartedWebApp { + pub(super) app: Box<dyn WebApp>, + pub(super) menus: crate::native_menu::MenuGuard, + pub(super) shortcuts: crate::shortcuts::Guard, + pub(super) fonts: &'static [&'static [u8]], +} + +type StartFn = Box<dyn FnOnce(Vec<Vec<u8>>, (f32, f32), Env, Waker) -> StartedWebApp>; + +/// Everything `Browser` holds of an `App<S>` before `start_app` constructs its `Runtime<S>`. +pub(super) struct PendingApp { + pub(super) title: &'static str, + pub(super) size: (f32, f32), + pub(super) canvas_id: Option<String>, + pub(super) embedded: bool, + pub(super) document: bool, + pub(super) fit_height: bool, + pub(super) font_urls: Vec<String>, + pub(super) late_font_urls: Vec<String>, + pub(super) on_ready: Option<OnWindow>, + pub(super) same_tab_router: Option<Box<dyn Fn(&str) -> bool>>, + pub(super) compositor_features: wgpu::Features, + pub(super) shared: Arc<SharedCore>, + start: StartFn, +} + +impl PendingApp { + fn check(has_extra_windows: bool, unsupported_window_mode: bool) -> Result<(), String> { + if has_extra_windows { + return Err("web supports one canvas; overlays and multiple windows are unsupported".into()); + } + if unsupported_window_mode { + return Err("web does not support windowless apps or native window hooks".into()); + } + Ok(()) + } + + pub(super) fn start(self, fonts: Vec<Vec<u8>>, viewport: (f32, f32), env: Env, wake: Waker) -> StartedWebApp { + (self.start)(fonts, viewport, env, wake) + } +} + +fn with_fonts(mut fonts: &'static [&'static [u8]], extra: Vec<Vec<u8>>) -> &'static [&'static [u8]] { + for bytes in extra { + fonts = crate::app::with_font(fonts, bytes); + } + fonts +} + +/// Everything the non-generic web host needs of its typed app state `S`. +pub(super) trait WebApp { + fn rt(&self) -> &RuntimeCore; + fn rt_mut(&mut self) -> &mut RuntimeCore; + fn with_driver(&mut self, f: &mut dyn FnMut(&mut RuntimeCore, &mut dyn AppDriver)); + + fn drain_updates(&mut self) -> bool; + fn has_compositor(&self) -> bool; + fn compositor_features(&self) -> wgpu::Features; + fn compositor_animating(&self) -> bool; + fn compositor_draws_own(&self) -> bool; + fn render_compositor(&mut self, args: CompositorFrame<'_>) -> bool; + fn paste_event(&mut self, clipboard: &crate::clipboard::Client, content: crate::ClipboardContent, image: Option<&JsValue>); +} + +impl dyn WebApp + '_ { + fn driver<R>(&mut self, f: impl FnOnce(&mut RuntimeCore, &mut dyn AppDriver) -> R) -> R { + let mut f = Some(f); + let mut out = None; + self.with_driver(&mut |core, app| { + out = Some(f.take().unwrap()(core, app)); + }); + out.unwrap() + } + + pub(super) fn frame(&mut self, dt: f64) -> bool { + self.driver(|rt, app| rt.frame(app, dt)) + } + + pub(super) fn covered_wake(&mut self) { + self.driver(|rt, app| { rt.covered_wake(app); }); + } + + pub(super) fn clock_advance(&mut self, clock: &mut FrameClock, at: Instant, compositing: bool) -> (bool, f64) { + self.driver(|rt, app| clock.advance_core(rt, app, at, compositing)) + } + + pub(super) fn content_height(&mut self) -> f32 { + self.driver(|rt, app| rt.content_height(app)) + } + + pub(super) fn copy_text(&mut self) -> Option<String> { + self.driver(|rt, app| rt.copy_text(app)) + } + + pub(super) fn window_focus(&mut self, focused: bool) { + self.driver(|rt, app| rt.window_focus(app, focused)); + } + + pub(super) fn resolve_popup(&mut self, picked: Option<&str>) -> Result<(), crate::PopupMenuError> { + self.driver(|rt, app| rt.resolve_popup(app, picked)) + } + + pub(super) fn pointer_move(&mut self, x: f32, y: f32) { + self.driver(|rt, app| rt.pointer_move(app, x, y)); + } + + pub(super) fn mouse_button( + &mut self, + input: crate::input::host_events::MouseButtonInput, + control_click: &mut bool, + ) -> crate::input::host_events::ButtonAction { + self.driver(|rt, app| crate::input::host_events::mouse_button_core(rt, app, input, control_click)) + } + + pub(super) fn sync_modifiers(&mut self, mods: &mut winit::keyboard::ModifiersState, next: winit::keyboard::ModifiersState) -> bool { + self.driver(|rt, app| crate::input::host_events::sync_modifiers(rt, app, mods, next)) + } + + pub(super) fn keyboard( + &mut self, + clipboard: &crate::clipboard::Client, + event: &winit::event::KeyEvent, + mods: winit::keyboard::ModifiersState, + ) -> bool { + self.driver(|rt, app| crate::input::host_events::keyboard(rt, app, clipboard, event, mods, None)) + } + + pub(super) fn touch(&mut self, touch: &winit::event::Touch) { + self.driver(|rt, app| crate::window::touch_core(rt, app, touch)); + } + + pub(super) fn web_focus_field(&mut self) -> bool { + self.driver(|rt, app| rt.web_focus_field(app)) + } + + pub(super) fn web_edit_context(&mut self, mirror: &mut crate::runtime::web_runtime::Mirror) -> Option<bool> { + self.driver(|rt, app| rt.web_edit_context(app, mirror)) + } + + pub(super) fn web_key(&mut self, event: &serde_json::Value) -> bool { + self.driver(|rt, app| rt.web_key(app, event)) + } + + pub(super) fn web_edit(&mut self, event: &serde_json::Value) { + self.driver(|rt, app| rt.web_edit(app, event)); + } +} + +fn pasted_image_fn(handle: &JsValue) -> impl FnOnce() -> js_sys::Promise + '_ { + move || super::input::pasted_image_promise(handle) +} + +/// The only per-state-type structure owned by a running web host. +pub(super) struct TypedWebApp<S: 'static> { + rt: Runtime<S>, + shared: Arc<Shared<S>>, + compositor: Option<Box<dyn Compositor<S>>>, +} + +impl<S: 'static> TypedWebApp<S> { + pub(super) fn pending(mut app: App<S>) -> Result<PendingApp, String> { + PendingApp::check(!app.overlays.is_empty() || !app.windows.is_empty(), !app.open || app.on_window.is_some())?; + let document = app.web_document; + let embedded = app.web_inline() && !document; + let title = app.spec.title; + let size = app.spec.size; + let canvas_id = app.canvas_id.take(); + let fit_height = app.fit_content_height; + let font_urls = std::mem::take(&mut app.font_urls); + let late_font_urls = std::mem::take(&mut app.late_font_urls); + let on_ready = app.on_ready.take(); + let same_tab_router = app.same_tab_router.take(); + let compositor_features = app.compositor.as_ref().map_or(wgpu::Features::empty(), |c| c.features()); + let shared = app.shared.core.clone(); + let start: StartFn = Box::new(move |fonts, viewport, env, wake| { + app.spec.fonts = with_fonts(app.spec.fonts, fonts); + let compositor = app.compositor.take(); + let (playground, attach_playground) = (app.playground.take(), app.attach_playground); + let spec_fonts = app.spec.fonts; + let (spec, state, shared, runtime) = app.into_parts(None); + let mut rt = crate::tooling::runtime_for(&spec, state, viewport, env, wake.clone()); + if let Some(attach) = attach_playground { attach(&mut rt, playground, &spec, None, None, true); } + rt.configure(runtime); + let menus = crate::native_menu::MenuGuard::attach(&shared, false); + let shortcuts = crate::shortcuts::Guard::attach(&shared, wake, false, false); + StartedWebApp { + app: Box::new(TypedWebApp { rt, shared, compositor }), + menus, + shortcuts, + fonts: spec_fonts, + } + }); + Ok(PendingApp { + title, + size, + canvas_id, + embedded, + document, + fit_height, + font_urls, + late_font_urls, + on_ready, + same_tab_router, + compositor_features, + shared, + start, + }) + } +} + +impl<S: 'static> WebApp for TypedWebApp<S> { + fn rt(&self) -> &RuntimeCore { self.rt.core() } + + fn rt_mut(&mut self) -> &mut RuntimeCore { self.rt.core_mut() } + + fn with_driver(&mut self, f: &mut dyn FnMut(&mut RuntimeCore, &mut dyn AppDriver)) { + let (core, mut driver) = self.rt.split_mut(); + f(core, &mut driver); + } + + fn drain_updates(&mut self) -> bool { + let updates = self.shared.take_updates(); + let had_updates = !updates.is_empty(); + for update in updates { + self.rt.update_if(update); + } + had_updates + } + + fn has_compositor(&self) -> bool { self.compositor.is_some() } + + fn compositor_features(&self) -> wgpu::Features { + self.compositor.as_ref().map_or(wgpu::Features::empty(), |c| c.features()) + } + + fn compositor_animating(&self) -> bool { + self.compositor.as_ref().is_some_and(|c| c.animating()) + } + + fn compositor_draws_own(&self) -> bool { + self.compositor.as_ref().is_some_and(|c| c.draws_own()) + } + + fn render_compositor(&mut self, args: CompositorFrame<'_>) -> bool { + let Some(c) = self.compositor.as_mut() else { return false }; + let mut f = Frame { + device: args.device, + queue: args.queue, + encoder: args.encoder, + target: args.target, + format: args.format, + size: args.size, + dt: args.dt, + update_ms: args.update_ms, + rt: &mut self.rt, + ui: args.ui, + }; + c.render(&mut f); + c.animating() + } + + fn paste_event(&mut self, clipboard: &crate::clipboard::Client, content: crate::ClipboardContent, image: Option<&JsValue>) { + clipboard.paste_event(&mut self.rt, content, image.map(pasted_image_fn)); + } +} diff --git a/app/vendor/rune/crates/rune/src/platform/web/bridge.js b/app/vendor/rune/crates/rune/src/platform/web/bridge.js new file mode 100644 index 0000000..d27eb30 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/platform/web/bridge.js @@ -0,0 +1,1105 @@ +// Browser text services and semantic DOM accessibility mirror. +const MAC = /Mac|iP/.test(navigator.platform); +const coarse = () => matchMedia('(pointer: coarse)').matches; +export function isMac() { return MAC; } +const high = n => n >= 0xd800 && n <= 0xdbff; +const low = n => n >= 0xdc00 && n <= 0xdfff; +function boundary(text, at, forward) { + if (at > 0 && at < text.length && high(text.charCodeAt(at - 1)) && low(text.charCodeAt(at))) at += forward ? 1 : -1; + return at; +} + +function replacement(old, next, composition, caret) { + let start = 0; + while (start < old.length && start < next.length && old[start] === next[start]) start++; + start = boundary(old, start, false); + let end = old.length, nextEnd = next.length; + while (end > start && nextEnd > start && old[end - 1] === next[nextEnd - 1]) { end--; nextEnd--; } + const adjusted = boundary(old, end, true) - end; + end += adjusted; nextEnd += adjusted; + if (composition && caret >= composition.length && next.slice(caret - composition.length, caret) === composition) { + const from = caret - composition.length; + const to = caret + old.length - next.length; + if (from <= to && to <= old.length) { + if (old === next) { start = from; end = to; nextEnd = caret; } + else { start = Math.min(start, from); end = Math.max(end, to); nextEnd = end + next.length - old.length; } + } + } + return { start, end, text: next.slice(start, nextEnd) }; +} + +function browserShortcut(event) { + const chord = (event.metaKey || event.ctrlKey) && !event.getModifierState?.('AltGraph'); + if (event.key === 'F5' || event.key === 'F12') return true; + if (!chord) return false; + const k = event.key.toLowerCase(); + // With Alt only the developer tools' chords are the browser's: Ctrl+Alt+W and the like are + // the app's (its Close tab, where the browser keeps Ctrl+W). + if (event.altKey) return ['i', 'j', 'u'].includes(k); + // An installed app's window gives the page every key first (Chromium: "In Apps mode, no keys + // are reserved"), and closes itself on a Ctrl+W the page lets through: there the tab, window + // and new-session keys are the app's, as in its desktop build. + if (['t', 'w', 'n'].includes(k) && appWindow()) return false; + // Leave copy ('c') un-prevented too so the browser fires its synchronous `copy` event. + return ['c', 'r', 'l', 't', 'w', 'n', 'f', 'g', '=', '+', '-', '0'].includes(k); +} + +function appWindow() { + return navigator.standalone === true + || matchMedia('(display-mode: standalone), (display-mode: window-controls-overlay), (display-mode: minimal-ui)').matches; +} + +// Keys that scroll a page when nothing in Rune has focus. +const SCROLL_KEYS = [' ', 'PageUp', 'PageDown', 'Home', 'End', 'ArrowUp', 'ArrowDown']; + +// What a page's mirror needs: focus rings on its links and buttons, and a selection highlight +// over its transparent text. The page can restyle both. +const PAGE_CSS = `[data-rune-a11y] :focus-visible{outline:2px solid var(--rune-focus,Highlight);outline-offset:2px;border-radius:4px} +[data-rune-a11y] ::selection{background:var(--rune-selection,rgba(80,150,255,.35));color:transparent} +[data-rune-a11y] a,[data-rune-a11y] button{color:transparent;-webkit-tap-highlight-color:transparent} +[data-rune-a11y] [data-rune-scroll-x]::-webkit-scrollbar{display:none}`; + +export function mount(canvas, callback, embedded, fitHeight, page) { + const textarea = document.createElement('textarea'); + textarea.setAttribute('aria-label', 'Text input'); + textarea.setAttribute('autocapitalize', 'sentences'); + // It is 1 px wide: wrapped, its every character would be a line to a screen reader reading by + // line. Unwrapped, a line is what a line break ends. + textarea.wrap = 'off'; + const password = document.createElement('input'); + password.type = 'password'; + password.setAttribute('aria-label', 'Password input'); + password.autocomplete = 'off'; + password.setAttribute('autocorrect', 'off'); + password.setAttribute('autocapitalize', 'off'); + password.spellcheck = false; + for (const field of [textarea, password]) { + field.style.cssText = 'position:fixed;left:0;top:0;width:1px;height:1px;padding:0;border:0;opacity:0;font-size:16px;resize:none;pointer-events:none;'; + field.tabIndex = -1; + field.inputMode = coarse() ? 'none' : 'text'; + document.body.append(field); + } + // The mirror's text is transparent over the canvas. `forced-color-adjust:none` keeps it so in + // Windows' contrast themes, which would otherwise paint it, on backplates, over what Rune drew. + const a11y = document.createElement('div'); + a11y.setAttribute('data-rune-a11y', ''); + a11y.setAttribute('role', 'document'); + let band = null; + if (page) { + // The canvas is a band of the page, not a window fixed to the screen: clipped to the + // page's own height, in the document's flow, so the browser's compositor scrolls the + // pixels Rune drew rather than moving a fixed layer at a frame's delay. + band = document.createElement('div'); + band.setAttribute('data-rune-band', ''); + band.style.cssText = 'position:absolute;left:0;top:0;width:100%;height:0;overflow:hidden;overflow:clip;pointer-events:none;'; + canvas.replaceWith(band); + band.append(canvas); + a11y.style.cssText = 'position:absolute;left:0;top:0;width:100%;height:0;overflow-x:clip;pointer-events:none;z-index:1;color:transparent;forced-color-adjust:none;touch-action:pan-y pinch-zoom;'; + const style = document.createElement('style'); + style.textContent = PAGE_CSS; + a11y.append(style); + document.body.append(a11y); + } else if (embedded && canvas.parentElement) { + if (getComputedStyle(canvas.parentElement).position === 'static') canvas.parentElement.style.position = 'relative'; + a11y.style.cssText = 'position:absolute;inset:0;overflow:hidden;pointer-events:none;z-index:1;color:transparent;forced-color-adjust:none;'; + canvas.after(a11y); + } else { + a11y.style.cssText = 'position:fixed;inset:0;overflow:hidden;pointer-events:none;z-index:1;color:transparent;forced-color-adjust:none;'; + document.body.append(a11y); + } + const h = { canvas, textarea, password, a11y, a11yNodes: new Map(), field: textarea, key: '', base: 0, value: '', + copyText: '', composing: false, composition: '', shift: false, modBits: 0, listeners: [], syncing: false, disposed: false, + embedded, fitHeight, page, focused: false, presented: false, swapped: false, touchDown: false, + lastScrollAt: 0, staticTimer: 0, scrollEls: new Map(), band }; + const send = event => { + const message = JSON.stringify(event); + if (h.syncing) queueMicrotask(() => { if (!h.disposed) callback(message); }); + else if (!h.disposed) callback(message); + }; + h.send = send; + const listen = (target, name, handler, options) => { + target.addEventListener(name, handler, options); + h.listeners.push(() => target.removeEventListener(name, handler, options)); + }; + const MOD_KEYS = ['Shift', 'Control', 'Alt', 'Meta', 'AltGraph']; + const ownsTarget = target => target === canvas || target === textarea || target === password || (target instanceof Node && a11y.contains(target)); + const syncMods = event => { + const bits = (event.shiftKey ? 1 : 0) | (event.ctrlKey ? 2 : 0) | (event.altKey ? 4 : 0) | (event.metaKey ? 8 : 0); + if (bits === h.modBits) return; + h.modBits = bits; + send({ kind: 'mods', shift: !!(bits & 1), ctrl: !!(bits & 2), alt: !!(bits & 4), meta: !!(bits & 8) }); + }; + // Refresh modifiers from DOM events before winit's canvas listeners run: winit suppresses + // ModifiersChanged on pointer/wheel when the canvas lacks focus (e.g. while a text field is + // focused or in document mode) and emits KeyboardInput before ModifiersChanged. + for (const name of ['pointerdown', 'pointermove', 'pointerup', 'pointerover', 'pointerout', 'wheel', 'keydown']) { + listen(window, name, event => { if (ownsTarget(event.target)) syncMods(event); }, { capture: true, passive: true }); + } + listen(window, 'keyup', event => { + if (ownsTarget(event.target) && !(event.target === canvas && MOD_KEYS.includes(event.key))) syncMods(event); + }, { capture: true, passive: true }); + // Let winit deliver a modifier key's own release on the canvas before clearing its flag so + // on_physical_input handlers see the key-up first. + listen(window, 'keyup', event => { + if (event.target === canvas && MOD_KEYS.includes(event.key)) syncMods(event); + }, { passive: true }); + listen(window, 'blur', () => { h.modBits = 0; }); + listen(document, 'visibilitychange', () => { if (document.hidden) h.modBits = 0; }); + function changed(preedit = false) { + const backward = textarea.selectionDirection === 'backward'; + send({ kind: preedit ? 'preedit' : 'edit', key: h.key, base: h.base, expected: h.value, + ...replacement(h.value, textarea.value, preedit ? h.composition : '', textarea.selectionEnd), + anchor: backward ? textarea.selectionEnd : textarea.selectionStart, + focus: backward ? textarea.selectionStart : textarea.selectionEnd }); + } + const key = (name, event = {}) => send({ kind: 'key', key: name, code: event.code ?? '', shift: !!event.shiftKey, + ctrl: !!event.ctrlKey, alt: !!event.altKey, meta: !!event.metaKey, repeat: !!event.repeat }); + listen(textarea, 'input', event => { + // No Rune field has the keyboard: nothing to edit, so the field stays empty. + if (!h.key) { textarea.value = ''; return; } + changed(h.composing || event.isComposing); + }); + listen(textarea, 'compositionstart', () => { h.composing = true; h.composition = ''; }); + listen(textarea, 'compositionupdate', event => { + h.composition = event.data ?? ''; + queueMicrotask(() => { if (!h.disposed && h.composing) changed(true); }); + }); + listen(textarea, 'compositionend', () => { + changed(); + h.composing = false; h.composition = ''; + send({ kind: 'sync' }); + }); + listen(password, 'input', () => { + const text = password.value; + password.value = ''; + if (text) send({ kind: 'secure', key: h.key, text }); + }); + for (const field of [textarea, password]) { + listen(field, 'paste', event => { + // Only a paste into a Rune field is Rune's; the browser keeps the rest. + if (!h.key) return; + event.preventDefault(); + const data = event.clipboardData; + h.image = field === textarea ? [...(data?.items ?? [])].find(i => i.kind === 'file' && i.type === 'image/png')?.getAsFile() ?? undefined : undefined; + try { + send({ kind: 'paste', text: data?.getData('text/plain') ?? '', html: field === textarea ? data?.getData('text/html') ?? '' : '', image: !!h.image }); + } finally { + if (h.syncing) queueMicrotask(() => { h.image = undefined; }); + else h.image = undefined; + } + }); + listen(field, 'beforeinput', event => { + if (event.inputType === 'insertLineBreak' || event.inputType === 'insertParagraph') { + event.preventDefault(); + if (!h.composing && !event.isComposing) key('Enter', { shiftKey: h.shift, code: 'Enter' }); + } else if (field === password && event.inputType.startsWith('delete')) { + event.preventDefault(); + const forward = event.inputType.endsWith('Forward'); + key(forward ? 'Delete' : 'Backspace', + { altKey: event.inputType.includes('Word'), code: forward ? 'Delete' : 'Backspace' }); + } + }); + listen(field, 'keydown', event => { + h.shift = event.shiftKey; + if (event.isComposing || h.composing || event.keyCode === 229) return; + // On Windows European layouts AltGr sets both ctrlKey and altKey; let those characters type. + const chord = (event.metaKey || event.ctrlKey) && !event.getModifierState?.('AltGraph'); + const editing = ['Enter', 'Tab', 'Escape', 'ArrowLeft', 'ArrowRight', 'ArrowUp', 'ArrowDown', 'Home', 'End', 'PageUp', 'PageDown']; + if (field === password) editing.push('Backspace', 'Delete'); + if (!chord && !editing.includes(event.key)) return; + if (chord && event.key.toLowerCase() === 'v') return; + event.preventDefault(); + key(event.key, event); + }); + listen(field, 'keyup', event => { h.shift = event.shiftKey; }); + listen(field, 'blur', () => { h.shift = false; }); + } + listen(textarea, 'select', () => { + if (h.syncing || h.composing || document.activeElement !== textarea) return; + const backward = textarea.selectionDirection === 'backward'; + send({ kind: 'selection', key: h.key, base: h.base, expected: h.value, + anchor: backward ? textarea.selectionEnd : textarea.selectionStart, + focus: backward ? textarea.selectionStart : textarea.selectionEnd }); + }); + // Synchronous copy support for read-only `El::selectable` selections (`Edit › Copy` / ⌘C). + listen(document, 'copy', event => { + const active = document.activeElement; + if (!h.key && h.copyText && event.clipboardData && (active === canvas || active === document.body)) { + event.preventDefault(); + event.clipboardData.setData('text/plain', h.copyText); + } + }); + // A file dropped while a Rune field has the keyboard is pasted into it, as a page's field + // takes a drop: an image as a pasted image, text as text. Elsewhere a drop does nothing (the + // browser would open the file in place of the app). + listen(canvas, 'dragover', event => { + if (!event.dataTransfer?.types.includes('Files')) return; + event.preventDefault(); + event.dataTransfer.dropEffect = h.key ? 'copy' : 'none'; + }); + listen(canvas, 'drop', async event => { + const file = event.dataTransfer?.files?.[0]; + if (!file) return; + event.preventDefault(); + if (!h.key) return; + if (file.type === 'image/png') { + h.image = file; + send({ kind: 'paste', text: '', html: '', image: true }); + return; + } + if (file.type.startsWith('text/') || file.size < 1048576 && !file.type) send({ kind: 'paste', text: await file.text(), html: '', image: false }); + }); + listen(canvas, 'pointerdown', event => event.preventDefault(), { capture: true }); + // winit's web backend ignores pointercancel for mouse/pen and does not listen to + // lostpointercapture; forward non-touch cancellations so held presses and drags never stick. + listen(canvas, 'pointercancel', event => { + if (event.pointerType !== 'touch') send({ kind: 'pointer_cancel', lost_capture: false }); + }, { passive: true }); + listen(canvas, 'lostpointercapture', event => { + if (event.pointerType !== 'touch') send({ kind: 'pointer_cancel', lost_capture: true }); + }, { passive: true }); + listen(a11y, 'pointerleave', event => { + if (event.pointerType !== 'touch' && event.relatedTarget !== canvas) send({ kind: 'leave' }); + }, { passive: true }); + listen(canvas, 'keydown', event => { + if (page && !h.focused && SCROLL_KEYS.includes(event.key) && !event.metaKey && !event.ctrlKey) return; + if (!browserShortcut(event)) event.preventDefault(); + }); + if (page) { + const scrolled = () => { h.lastScrollAt = performance.now(); send({ kind: 'scroll', y: window.scrollY }); }; + listen(window, 'scroll', scrolled, { passive: true }); + // A finger down or a page still coasting moves the export's layout under the reader; the + // swap to the live mirror waits for it (see `dropStatic`). + listen(window, 'touchstart', () => { h.touchDown = true; deferStatic(h); }, { passive: true }); + listen(window, 'touchend', () => { h.touchDown = false; deferStatic(h); }, { passive: true }); + listen(window, 'touchcancel', () => { h.touchDown = false; deferStatic(h); }, { passive: true }); + // Mirrored text and links take the pointer from the canvas; hover still reaches Rune. + listen(a11y, 'pointermove', event => { + if (event.pointerType !== 'touch') send({ kind: 'hover', x: event.clientX, y: event.clientY }); + }, { passive: true }); + queueMicrotask(() => { if (!h.disposed) scrolled(); }); + } + // winit's web backend drops WheelEvent.DOM_DELTA_PAGE (deltaMode === 2); forward page + // deltas to Rune before checking wheelUsed / preventDefault. + const forwardPageWheel = event => { + if (event.deltaMode !== 2) return; + send({ + kind: 'wheel_page', + dx: -event.deltaX, + dy: -event.deltaY, + shift: event.shiftKey, + ctrl: event.ctrlKey, + alt: event.altKey, + meta: event.metaKey, + }); + }; + if (!fitHeight) { + // Ctrl+wheel (a touchpad's pinch) is the browser's zoom unless Rune pinched something with + // it: Rune hears the wheel first (winit's listener is older) and says so (`syncWheel`). + listen(canvas, 'wheel', event => { + forwardPageWheel(event); + const used = h.wheelUsed; + h.wheelUsed = false; + if (event.ctrlKey && !used) return; + event.preventDefault(); + }, { passive: false }); + listen(document, 'gesturestart', event => event.preventDefault(), { passive: false }); + } else { + listen(canvas, 'wheel', forwardPageWheel, { passive: true }); + } + if (!page && !embedded) { + // Printing prints what's on screen (the canvas, and the mirror's text over it, which the + // PDF keeps selectable), fitted to the paper's width rather than cut off at its edge. + const style = document.createElement('style'); + style.textContent = '@media print{canvas,[data-rune-a11y]{transform:scale(var(--rune-print-scale,1));transform-origin:0 0}}'; + document.head.append(style); + listen(window, 'beforeprint', () => { + // An A4 or Letter page's printable width at the browser's default margins, in CSS pixels. + document.documentElement.style.setProperty('--rune-print-scale', String(Math.min(1, 718 / innerWidth))); + }); + h.listeners.push(() => style.remove()); + } + if (!page) { + // A web link takes the pointer while it's over it, as a page's would: the status bar + // shows where it goes, and middle-click, Ctrl+click and its own menu open it. + listen(canvas, 'pointermove', event => { + if (event.pointerType === 'touch' || event.buttons) return; + const a = linkAt(h, event.clientX, event.clientY); + if (a && a !== h.hoverLink) armLink(h, a); + }, { passive: true }); + // The pointer over a link (or anything else of the mirror's that took it) still hovers Rune. + listen(a11y, 'pointermove', event => { + if (event.pointerType !== 'touch') { + const r = canvas.getBoundingClientRect(); + send({ kind: 'hover', x: event.clientX - r.left, y: event.clientY - r.top }); + } + }, { passive: true }); + } + // Right-click (and Ctrl+click on macOS): Rune draws an element's own menu; anywhere else the + // browser opens its own over what a page would have there (the selection, a link, text, a text + // field), never the canvas's image menu; Shift+right-click always opens the browser's. Armed + // before the menu's event, which on Windows and Linux follows the release; macOS's follows the + // press, which Rune has just heard (`syncSecondary`). + const isSecondaryPress = event => event.button === 2 || (MAC && event.button === 0 && event.ctrlKey); + const armAt = event => { + if (!isSecondaryPress(event) || event.pointerType === 'touch' || event.target !== canvas) return; + if (armMenu(h, event.clientX, event.clientY, event.shiftKey)) send({ kind: 'secondary_browser' }); + }; + if (MAC) listen(canvas, 'pointerdown', armAt); + else listen(window, 'pointerup', armAt, { capture: true }); + listen(document, 'contextmenu', event => { + if (h.menu === 'rune' || event.target === canvas) event.preventDefault(); + if (h.menu === 'rune') h.menu = ''; + }, { capture: true }); + for (const name of ['pointerdown', 'keydown', 'wheel']) { + listen(window, name, event => { if (name !== 'pointerdown' || !isSecondaryPress(event)) disarmMenu(h); }, { capture: true, passive: true }); + } + queueMicrotask(() => { + if (!h.disposed && !embedded && !page && document.activeElement === document.body) canvas.focus({ preventScroll: true }); + }); + return h; +} + +export function sync(h, key, text, base, anchor, focus, secure) { + if (h.composing && key === h.key) return; + h.composing = false; + h.syncing = true; + const editing = document.activeElement === h.textarea || document.activeElement === h.password; + h.key = key; h.base = base; h.value = text; + h.password.value = ''; + h.field = secure ? h.password : h.textarea; + if (!key) { + h.textarea.value = ''; + if (editing) h.canvas.focus({ preventScroll: true }); + h.textarea.inputMode = h.password.inputMode = coarse() ? 'none' : 'text'; + } else { + if (h.textarea.value !== text) h.textarea.value = text; + if (!secure) { + const start = Math.min(anchor, focus), end = Math.max(anchor, focus); + const direction = anchor > focus ? 'backward' : 'forward'; + if (h.textarea.selectionStart !== start || h.textarea.selectionEnd !== end || h.textarea.selectionDirection !== direction) { + h.textarea.setSelectionRange(start, end, direction); + } + } + if (editing && document.activeElement !== h.field) activate(h); + } + h.syncing = false; +} + +// Drops browser composition tracking after Rune finished/cancelled composition (e.g. on blur or hide). +export function cancelIme(h) { + h.composing = false; + h.composition = ''; +} + +export function syncCopy(h, text) { + h.copyText = text; +} + +// What the right-click Rune just heard is on: 'app' (an element's menu, which Rune draws), +// 'field', 'text' or '' (`Runtime::secondary_claim`). +export function syncSecondary(h, claim) { + h.secondary = claim; +} + +// The sans and mono slots' families (CSS lists): the mirror's text sets in them (`family`). +export function syncFamilies(h, sans, mono) { + const css = (list, generic) => list.split(',').map(n => n.trim()).filter(Boolean).map(n => `"${n.replace(/["\\]/g, '')}"`).concat(generic).join(','); + h.a11y.style.setProperty('--rune-sans', css(sans, 'sans-serif')); + h.a11y.style.setProperty('--rune-mono', css(mono, 'monospace')); +} + +// A pop-up menu (`Tx::popup_menu`, a field's menu with its spelling suggestions, selected +// text's Copy) as the page's own elements: `role="menu"` with keyboard, pointer and screen +// reader use, top-left at window point (x, y) of the canvas, at least `minWidth` wide, light or +// dark as the window draws. A pick or a dismissal is sent once: `{ kind: 'menu', id }`, `id` +// null when dismissed. +export function showMenu(h, json, x, y, minWidth, dark) { + closeMenu(h, false); + const spec = JSON.parse(json); + const box = h.canvas.getBoundingClientRect(); + const colors = dark + ? { bg: '#2b2b2b', fg: '#f2f2f2', muted: '#8f8f8f', line: '#454545', hover: '#3d3d3d' } + : { bg: '#ffffff', fg: '#1a1a1a', muted: '#8c8c8c', line: '#e0e0e0', hover: '#ebebeb' }; + const menus = []; + let answered = false; + const answer = (id) => { + if (answered) return; + answered = true; + closeMenu(h, true); + h.send({ kind: 'menu', id }); + }; + const open = (spec, left, top, min, parentItem) => { + const menu = document.createElement('div'); + menu.setAttribute('data-rune-menu', ''); + menu.setAttribute('role', 'menu'); + menu.tabIndex = -1; + menu.style.cssText = `position:fixed;left:0;top:0;z-index:2147483647;box-sizing:border-box;min-width:${Math.max(min, 160)}px;max-height:calc(100vh - 8px);overflow-y:auto;padding:4px;margin:0;background:${colors.bg};color:${colors.fg};border:1px solid ${colors.line};border-radius:8px;box-shadow:0 4px 16px rgba(0,0,0,.18);font:13px/18px system-ui,sans-serif;user-select:none;-webkit-user-select:none;outline:none`; + const rows = []; + for (const entry of spec.items) { + if (entry.separator) { + const sep = document.createElement('div'); + sep.setAttribute('role', 'separator'); + sep.style.cssText = `height:1px;margin:4px 0;background:${colors.line}`; + menu.append(sep); + continue; + } + const row = document.createElement('div'); + const sub = entry.menu; + const enabled = entry.enabled !== false; + row.setAttribute('role', entry.checked ? 'menuitemcheckbox' : 'menuitem'); + if (entry.checked !== undefined && !sub) row.setAttribute('aria-checked', String(!!entry.checked)); + if (!enabled) row.setAttribute('aria-disabled', 'true'); + if (sub) row.setAttribute('aria-haspopup', 'menu'); + row.tabIndex = -1; + row.style.cssText = `display:flex;align-items:center;gap:16px;padding:4px 10px 4px 26px;border-radius:4px;position:relative;cursor:default;white-space:nowrap;color:${enabled ? colors.fg : colors.muted};outline:none`; + const title = document.createElement('span'); + title.style.flex = '1'; + title.textContent = sub ? entry.submenu : entry.title; + row.append(title); + if (entry.checked) { + const tick = document.createElement('span'); + tick.textContent = '✓'; + tick.setAttribute('aria-hidden', 'true'); + tick.style.cssText = 'position:absolute;left:9px'; + row.append(tick); + } + if (entry.keyEquivalent || sub) { + const hint = document.createElement('span'); + hint.setAttribute('aria-hidden', 'true'); + hint.textContent = sub ? '›' : entry.keyEquivalent.replace(/^mod\+/i, navigator.platform.startsWith('Mac') ? '⌘' : 'Ctrl+'); + hint.style.color = colors.muted; + row.append(hint); + } + const item = { row, enabled, sub, id: entry.id }; + rows.push(item); + row.addEventListener('pointerenter', () => focusRow(item, true)); + row.addEventListener('click', (event) => { + event.preventDefault(); + if (!enabled) return; + if (sub) { openSub(item); return; } + answer(entry.id); + }); + menu.append(row); + } + document.body.append(menu); + // Inside the viewport: flipped left of the parent item, or up, where it would overflow. + const r = menu.getBoundingClientRect(); + let l = left, t = top; + if (l + r.width > innerWidth - 4) l = parentItem ? parentItem.row.getBoundingClientRect().left - r.width + 4 : innerWidth - 4 - r.width; + // A menu at a point opens upward from it where it would run off the bottom, as a context + // menu does; a submenu moves up. + if (t + r.height > innerHeight - 4) t = Math.max(4, parentItem || top - r.height < 4 ? innerHeight - 4 - r.height : top - r.height); + menu.style.left = `${Math.max(4, l)}px`; + menu.style.top = `${Math.max(4, t)}px`; + const level = { menu, rows, active: null, child: null, parentItem }; + menus.push(level); + const focusRow = (item, fromPointer) => { + for (const m of menus) if (m.rows.includes(item)) { + if (m.active) m.active.row.style.background = ''; + m.active = item; + if (item.enabled) item.row.style.background = colors.hover; + item.row.focus({ preventScroll: true }); + // Leaving a submenu's item for another closes the submenu. + if (m.child && m.child.parentItem !== item) closeFrom(menus.indexOf(m) + 1); + if (fromPointer && item.sub && item.enabled) openSub(item); + } + }; + level.focusRow = focusRow; + return level; + }; + const closeFrom = (k) => { + while (menus.length > k) { + const m = menus.pop(); + m.menu.remove(); + if (menus.length) menus[menus.length - 1].child = null; + } + }; + const openSub = (item) => { + const parent = menus.find(m => m.rows.includes(item)); + if (!parent || parent.child?.parentItem === item) return parent?.child; + closeFrom(menus.indexOf(parent) + 1); + const r = item.row.getBoundingClientRect(); + const child = open(item.sub, r.right - 4, r.top - 5, 0, item); + parent.child = child; + return child; + }; + const top = open(spec, box.left + x, box.top + y, minWidth, null); + const selected = spec.selected && top.rows.find(r => r.id === spec.selected); + // A positioned menu puts its selected item over the point, as a pop-up button opens. + if (selected) { + const dy = selected.row.getBoundingClientRect().top - top.menu.getBoundingClientRect().top; + top.menu.style.top = `${Math.max(4, box.top + y - dy)}px`; + } + top.menu.focus({ preventScroll: true }); + if (selected) top.focusRow(selected, false); + const step = (level, by) => { + const live = level.rows.filter(r => r.enabled); + if (!live.length) return; + const at = live.indexOf(level.active); + level.focusRow(live[(at + by + live.length) % live.length], false); + }; + const onKey = (event) => { + const level = menus[menus.length - 1]; + const k = event.key; + if (k === 'Escape' || k === 'Tab') { + if (menus.length > 1 && k === 'Escape') { closeFrom(menus.length - 1); menus[menus.length - 1].active?.row.focus(); } + else answer(null); + } else if (k === 'ArrowDown') step(level, 1); + else if (k === 'ArrowUp') step(level, -1); + else if (k === 'Home') { level.active = null; step(level, 1); } + else if (k === 'End') { level.active = null; step(level, -1); } + else if (k === 'ArrowRight' && level.active?.sub) { const child = openSub(level.active); if (child) step(child, 1); } + else if (k === 'ArrowLeft' && menus.length > 1) { closeFrom(menus.length - 1); menus[menus.length - 1].active?.row.focus(); } + else if ((k === 'Enter' || k === ' ') && level.active?.enabled) { + if (level.active.sub) { const child = openSub(level.active); if (child) step(child, 1); } + else answer(level.active.id); + } else if (k.length === 1 && /\S/.test(k)) { + const live = level.rows.filter(r => r.enabled); + const from = live.indexOf(level.active); + const hit = [...live.slice(from + 1), ...live.slice(0, from + 1)].find(r => r.row.textContent.trim().toLowerCase().startsWith(k.toLowerCase())); + if (hit) level.focusRow(hit, false); + } else return; + event.preventDefault(); + event.stopPropagation(); + }; + const onDown = (event) => { + if (!menus.some(m => m.menu.contains(event.target))) answer(null); + }; + const onBlur = () => answer(null); + document.addEventListener('keydown', onKey, true); + document.addEventListener('pointerdown', onDown, true); + window.addEventListener('blur', onBlur); + window.addEventListener('resize', onBlur); + h.menu = { menus, done: () => { + document.removeEventListener('keydown', onKey, true); + document.removeEventListener('pointerdown', onDown, true); + window.removeEventListener('blur', onBlur); + window.removeEventListener('resize', onBlur); + for (const m of menus) m.menu.remove(); + menus.length = 0; + } }; +} + +// Takes the menu down; `refocus` gives the canvas its focus back, as a closing menu does. +function closeMenu(h, refocus) { + if (!h.menu) return; + const menu = h.menu; + h.menu = null; + menu.done(); + if (refocus) h.canvas.focus({ preventScroll: true }); +} + +// The app went away or the menu was answered by Rune itself: no answer is sent. +export function hideMenu(h) { + closeMenu(h, false); +} + +// Whether Rune pinched something with the Ctrl+wheel it just heard. +export function syncWheel(h, used) { + h.wheelUsed = used; +} + +// The focused field's IME area in window points: the page's own text field sits there, so an +// input method's candidate window opens beside the caret, not in the page's corner. +export function syncCaret(h, x, y, w, height) { + h.caret = [x, y, Math.max(1, w), Math.max(1, height)]; + if (h.fieldArmed) return; + for (const field of [h.textarea, h.password]) placeField(field, h.caret); +} + +function placeField(field, [x, y, w, height]) { + Object.assign(field.style, { left: `${x}px`, top: `${y}px`, width: `${w}px`, height: `${height}px`, pointerEvents: 'none' }); +} + +// The mirror's web link under (x, y), if any. +function linkAt(h, x, y) { + for (const a of h.a11y.querySelectorAll('a[target="_blank"]')) { + for (const r of a.getClientRects()) if (x >= r.left && x < r.right && y >= r.top && y < r.bottom) return a; + } + return null; +} + +function armLink(h, a) { + disarmLink(h); + h.hoverLink = a; + a.style.pointerEvents = 'auto'; + a.style.cursor = 'pointer'; + a.addEventListener('pointerleave', () => disarmLink(h), { once: true }); +} + +function disarmLink(h) { + if (!h.hoverLink) return; + h.hoverLink.style.pointerEvents = 'none'; + h.hoverLink = null; +} + +// Readies the browser's own menu for a right-click at (x, y), unless Rune's takes it. True when +// the browser's will open. +function armMenu(h, x, y, browser) { + disarmMenu(h); + const claim = h.secondary === 'app' && browser ? 'text' : h.secondary; + h.secondary = ''; + if (claim === 'app') { h.menu = 'rune'; return false; } + h.menu = 'browser'; + if (claim === 'field' && h.key) { + // The page's field holds the Rune field's text and selection: its menu's Cut, Copy, Paste + // and Select all edit them, as a page's text field's would. + h.fieldArmed = true; + placeField(h.field, [x - 2, y - 2, 4, 4]); + h.field.style.pointerEvents = 'auto'; + return true; + } + if (h.copyText) { + // The selection, as a page's: in a node under the pointer, selected, so the menu offers + // Copy and a search for it. + if (!h.pick) { + h.pick = document.createElement('div'); + h.pick.setAttribute('data-rune-selection', ''); + const style = document.createElement('style'); + style.textContent = '[data-rune-selection]::selection{background:transparent;color:transparent}'; + document.head.append(style); + document.body.append(h.pick); + } + h.pick.textContent = h.copyText; + h.pick.style.cssText = `position:fixed;left:${x - 4}px;top:${y - 4}px;width:8px;height:8px;overflow:hidden;white-space:pre;color:transparent;forced-color-adjust:none;z-index:2;user-select:text;-webkit-user-select:text;`; + const range = document.createRange(); + range.selectNodeContents(h.pick); + const selection = getSelection(); + selection.removeAllRanges(); + selection.addRange(range); + return true; + } + // A link, the text under the pointer, or the page itself (Back, Reload, Print, Inspect). + const el = linkAt(h, x, y) ?? textAt(h, x, y) ?? h.a11y; + h.armed = [el, el.style.pointerEvents]; + el.style.pointerEvents = 'auto'; + return true; +} + +function textAt(h, x, y) { + let hit = null; + for (const el of h.a11y.querySelectorAll('p, li, h1, h2, h3, h4, h5, h6')) { + const r = el.getBoundingClientRect(); + if (x >= r.left && x < r.right && y >= r.top && y < r.bottom) hit = el; + } + return hit; +} + +function disarmMenu(h) { + if (h.armed) { + const [el, before] = h.armed; + el.style.pointerEvents = before; + h.armed = null; + } + if (h.pick?.textContent) { + const selection = getSelection(); + if (selection.anchorNode && h.pick.contains(selection.anchorNode)) selection.removeAllRanges(); + h.pick.textContent = ''; + h.pick.style.left = '-10000px'; + } + if (h.fieldArmed) { + h.fieldArmed = false; + if (h.caret) placeField(h.field, h.caret); + else Object.assign(h.field.style, { left: '0px', top: '0px', width: '1px', height: '1px', pointerEvents: 'none' }); + } + if (h.menu === 'browser') h.menu = ''; +} + +function webLink(url) { + return url.startsWith('https://') || url.startsWith('http://') || url.startsWith('mailto:'); +} + +const TAGS = { heading: null, button: 'button', link: 'a', image: 'div', text: 'p', scroll_x: 'div' }; + +function family(name) { + if (name === 'sans') return 'var(--rune-sans,sans-serif)'; + if (name === 'mono') return 'var(--rune-mono,monospace)'; + return `"${name.replace(/["\\]/g, '')}",var(--rune-sans,sans-serif)`; +} + +// The mirror's first item element, after its stylesheet. +function firstItem(el) { + let c = el.firstElementChild; + while (c && c.tagName === 'STYLE') c = c.nextElementSibling; + return c; +} + +function runs(h, el, item) { + for (const run of item.u) { + if (!run.h) { el.append(document.createTextNode(run.t)); continue; } + const a = document.createElement('a'); + a.textContent = run.t; + a.style.cssText = `color:transparent;text-decoration:none;pointer-events:${h.page ? 'auto' : 'none'};`; + if (webLink(run.h)) { + a.href = run.h; + a.target = '_blank'; + a.rel = 'noopener noreferrer'; + } else { + a.href = '#'; + a.addEventListener('click', ev => { + ev.preventDefault(); + h.send({ kind: 'a11y_link', path: run.p, link: run.i }); + }); + } + el.append(a); + } +} + +function itemStyle(h, item, origin) { + const [x, y, w, bh] = item.r; + let css = `position:absolute;left:${x - origin[0]}px;top:${y - origin[1]}px;width:${w}px;height:${bh}px;margin:0;padding:0;border:0;background:transparent;color:transparent;`; + if (item.k === 'group') return css + 'overflow:visible;list-style:none;pointer-events:none;'; + // A page's horizontal scroller: the browser scrolls it natively, so a flick inside a code + // block scrolls the block at the compositor's rate while a vertical drag still scrolls the + // page. + if (item.k === 'scroll_x') return css + 'overflow-x:auto;overflow-y:hidden;pointer-events:auto;touch-action:pan-x pan-y pinch-zoom;scrollbar-width:none;'; + if (item.k === 'link') return css + 'display:block;overflow:hidden;text-decoration:none;cursor:pointer;pointer-events:auto;font:14px/1.25 sans-serif;'; + if (item.k === 'image' || item.k === 'button') return css + 'overflow:hidden;pointer-events:none;font:14px/1.25 sans-serif;'; + const fs = item.s || 14; + if (!item.f) return css + `font:${fs}px/1.25 sans-serif;overflow:hidden;white-space:pre-wrap;pointer-events:none;`; + const [fam, weight, lh, tracking, italic, align] = item.f; + css += `font:${italic ? 'italic ' : ''}${weight} ${fs}px/${lh}px ${family(fam)};letter-spacing:${tracking}px;text-align:${align};white-space:pre-wrap;overflow-wrap:break-word;overflow:visible;`; + return css + (item.e ? 'pointer-events:auto;user-select:text;-webkit-user-select:text;cursor:text;' : 'pointer-events:none;user-select:none;-webkit-user-select:none;'); +} + +export function syncA11y(h, json) { + if (h.disposed) return; + const items = JSON.parse(json); + const seen = new Set(); + const els = []; + const cursors = new Map([[h.a11y, firstItem(h.a11y)]]); + for (const item of items) { + const tag = item.k === 'group' ? item.g : item.k === 'heading' ? `h${item.l || 2}` : TAGS[item.k] ?? 'p'; + const key = `${tag}:${item.p}`; + seen.add(key); + let el = h.a11yNodes.get(key); + if (!el) { + el = document.createElement(tag); + if (tag === 'button') { + el.type = 'button'; + el.tabIndex = h.page ? 0 : -1; + el.addEventListener('click', ev => { + ev.preventDefault(); + h.send({ kind: 'a11y_press', path: item.p }); + }); + } + if (item.k === 'image') el.setAttribute('role', 'img'); + if (item.k === 'scroll_x') { + el.setAttribute('data-rune-scroll-x', ''); + // The browser scrolls this container itself; Rune draws the content where the + // container says it is. + el.addEventListener('scroll', () => { + const path = el._path; + if (path && !h.disposed) h.send({ kind: 'scroll_x', path, x: readScrollX(el) }); + }, { passive: true }); + } + h.a11yNodes.set(key, el); + } + const parent = item.a === undefined ? null : items[item.a]; + const parentEl = item.a === undefined ? h.a11y : els[item.a]; + // Writing `cssText` invalidates the node's style and its layout: only do it when the + // mirror's item actually moved or changed, so one animating element never rewrites a whole + // page's worth of nodes mid-scroll. + const css = itemStyle(h, item, parent ? parent.r : [0, 0]); + if (el._css !== css) { el._css = css; el.style.cssText = css; } + if (item.i) el.id = item.i; else el.removeAttribute('id'); + // `El::description` and `El::described_by`'s words: what a reader says after the name. + if (item.d) el.setAttribute('aria-description', item.d); else el.removeAttribute('aria-description'); + // A table's parts: the role says what the div is (`aria_role`). + if ((el.getAttribute('role') ?? undefined) !== item.o && item.k === 'group') { + if (item.o) el.setAttribute('role', item.o); else el.removeAttribute('role'); + } + if (tag === 'button') { + if (item.x === true || item.x === false) el.setAttribute('aria-expanded', String(item.x)); + else el.removeAttribute('aria-expanded'); + // A control's role and states (a palette's option, a tab, a switch): `control_role`. + const states = [['role', item.o], ['aria-selected', item.se === undefined ? undefined : String(item.se)], ['aria-checked', item.c], + ['aria-posinset', item.n ? String(item.n[0]) : undefined], ['aria-setsize', item.n ? String(item.n[1]) : undefined]]; + for (const [name, value] of states) { + if (value === undefined) el.removeAttribute(name); + else if (el.getAttribute(name) !== value) el.setAttribute(name, value); + } + } + if (item.k === 'group' || item.k === 'image') { + if (item.t) el.setAttribute('aria-label', item.t); else el.removeAttribute('aria-label'); + } else if (item.k === 'link') { + el.href = item.h; + if (!h.page && webLink(item.h)) { el.target = '_blank'; el.rel = 'noopener noreferrer'; } + } + const container = item.k === 'group' || item.k === 'scroll_x'; + if (item.k === 'scroll_x' && el._path !== item.p) { el._path = item.p; h.scrollEls.set(item.p, el); } + const sig = container || item.k === 'image' ? '' : item.u?.length ? JSON.stringify(item.u) : item.t ?? ''; + if (!container && el._sig !== sig) { + el._sig = sig; + el.replaceChildren(); + if (item.u?.length) runs(h, el, item); + else if (item.k !== 'image') el.textContent = item.t ?? ''; + } + els.push(el); + if (container && !cursors.has(el)) cursors.set(el, el.firstElementChild); + const cursor = cursors.get(parentEl) ?? null; + if (cursor !== el) parentEl.insertBefore(el, cursor); + else cursors.set(parentEl, cursor.nextElementSibling); + } + for (const [key, el] of h.a11yNodes) { + if (!seen.has(key)) { + if (el._path && h.scrollEls.get(el._path) === el) h.scrollEls.delete(el._path); + el.remove(); + h.a11yNodes.delete(key); + } + } +} + +// An app's focus (`Runtime::web_a11y_focus`), for a reader: the browser's own focus stays on the +// canvas (where keys go) or its text field, so the canvas is an `application` whose active +// descendant is a proxy in its fallback content saying the focused element's role, name and +// states. Two proxies, taking turns, so every move is a change of active descendant a reader +// follows, even between two elements alike. A text field's name goes on the field the browser +// edits. +export function focusA11y(h, json) { + if (h.disposed || h.page) return; + const f = json ? JSON.parse(json) : null; + if (!h.focusProxies) { + h.focusProxies = [0, 1].map(n => { + const el = document.createElement('div'); + el.id = `rune-focus-${n}`; + el.tabIndex = -1; + h.canvas.append(el); + return el; + }); + h.focusTurn = 0; + h.canvas.setAttribute('role', 'application'); + if (document.title) h.canvas.setAttribute('aria-label', document.title); + } + if (!f) { + h.canvas.removeAttribute('aria-activedescendant'); + return; + } + if (f.o === 'textbox') h.textarea.setAttribute('aria-label', f.t || 'Text input'); + if (f.f) h.textarea.setAttribute('aria-label', f.f); + h.focusTurn ^= 1; + const el = h.focusProxies[h.focusTurn]; + for (const a of [...el.attributes]) if (a.name === 'role' || a.name.startsWith('aria-')) el.removeAttribute(a.name); + el.setAttribute('role', f.o); + el.setAttribute('aria-label', f.t ?? ''); + if (f.d) el.setAttribute('aria-description', f.d); + if (f.c) el.setAttribute('aria-checked', f.c); + if (f.s !== undefined) el.setAttribute('aria-selected', String(f.s)); + if (f.x !== undefined) el.setAttribute('aria-expanded', String(f.x)); + if (f.n) { el.setAttribute('aria-posinset', String(f.n[0])); el.setAttribute('aria-setsize', String(f.n[1])); } + if (f.l) el.setAttribute('aria-level', String(f.l)); + h.canvas.setAttribute('aria-activedescendant', el.id); + // Typing in a field whose highlighted row this is (the palette): the field says it too. + if (f.o !== 'textbox') h.textarea.setAttribute('aria-activedescendant', el.id); + else h.textarea.removeAttribute('aria-activedescendant'); +} + +// `Tx::announce`: two live regions in the mirror, polite and assertive, made the first time +// something is said (a region must be in the page before its text changes for a reader to say +// it). The words go in on the next frame, after the region is emptied, so the same words said +// twice are said twice. +export function announceA11y(h, text, assertive) { + if (h.disposed) return; + h.live ??= {}; + const kind = assertive ? 'assertive' : 'polite'; + let el = h.live[kind]; + if (!el) { + el = document.createElement('div'); + el.setAttribute('aria-live', kind); + el.setAttribute('aria-atomic', 'true'); + if (!assertive) el.setAttribute('role', 'status'); + el.style.cssText = 'position:absolute;width:1px;height:1px;margin:-1px;overflow:hidden;clip-path:inset(50%);white-space:nowrap;'; + h.a11y.parentNode.insertBefore(el, h.a11y); + h.live[kind] = el; + } + el.textContent = ''; + requestAnimationFrame(() => { if (!h.disposed) el.textContent = text; }); +} + +// Rune skipped rebuilding the mirror while it scrolls: it asks again once the scroll has rested. +// The mirror's first build, in the page's idle time (its first frame's input goes first). +export function scheduleA11yIdle(h) { + const due = () => { if (!h.disposed) h.send({ kind: 'a11y_due' }); }; + if (globalThis.requestIdleCallback) requestIdleCallback(due, { timeout: 100 }); else setTimeout(due, 0); +} + +export function scheduleA11y(h) { + clearTimeout(h.a11yTimer); + h.a11yTimer = setTimeout(() => { h.a11yTimer = 0; if (!h.disposed) h.send({ kind: 'a11y_due' }); }, 160); +} + +// A page's height and whether a Rune control has the keyboard (scroll keys are the page's +// when none has). +export function syncPage(h, height, focused) { + h.focused = focused; + h.a11y.style.height = `${height}px`; + // The clipper is as tall as the page, so the band's overscan past the document's end is + // clipped instead of making the page scrollable past its foot. + if (h.band && h.band.style.height !== `${height}px`) h.band.style.height = `${height}px`; +} + +// Detects how this browser represents `Element.scrollLeft` on a `direction: rtl` container: +// - 'negative': 0 at the right (start) edge, -(scrollWidth - clientWidth) at the left (end) edge +// (CSSOM View standard: Chromium >= 85, Firefox, Safari >= 15.4). +// - 'reverse': 0 at the right (start) edge, +(scrollWidth - clientWidth) at the left (end) edge +// (legacy Edge / IE). +// - 'default': +(scrollWidth - clientWidth) at the right (start) edge, 0 at the left (end) edge +// (legacy Blink / WebKit). +let rtlScrollType = null; +function detectRtlScrollType() { + if (rtlScrollType) return rtlScrollType; + const host = document.body ?? document.documentElement; + if (!host) return 'negative'; + const outer = document.createElement('div'); + outer.dir = 'rtl'; + outer.style.cssText = 'position:fixed;top:-9999px;left:-9999px;width:40px;height:40px;overflow-x:scroll;overflow-y:hidden;scrollbar-width:none;visibility:hidden;pointer-events:none;'; + const inner = document.createElement('div'); + inner.style.cssText = 'width:80px;height:1px;'; + outer.append(inner); + host.append(outer); + let type = 'negative'; + if (outer.scrollWidth > outer.clientWidth) { + if (outer.scrollLeft > 0) { + type = 'default'; + } else { + outer.scrollLeft = 1; + type = outer.scrollLeft === 0 ? 'negative' : 'reverse'; + } + rtlScrollType = type; + } + outer.remove(); + return type; +} + +function isRtl(el) { + if (el.dir === 'rtl') return true; + if (el.dir === 'ltr') return false; + return getComputedStyle(el).direction === 'rtl'; +} + +// Normalizes `el.scrollLeft` into Rune's logical horizontal scroll offset (0 at the inline-start +// edge, growing toward the inline-end edge up to `scrollWidth - clientWidth`). +function readScrollX(el) { + const raw = el.scrollLeft; + if (!Number.isFinite(raw)) return 0; + const max = Math.max(0, el.scrollWidth - el.clientWidth); + if (!isRtl(el)) return Math.min(Math.max(raw, 0), max); + const type = detectRtlScrollType(); + const logical = type === 'negative' ? -raw : type === 'default' ? max - raw : raw; + return Math.min(Math.max(logical, 0), max); +} + +// Converts Rune's logical horizontal scroll offset (`0..=max`) into the DOM `scrollLeft` value +// expected by `el`'s direction and browser RTL scroll model. +function domScrollLeft(el, x) { + if (!Number.isFinite(x)) return 0; + const max = Math.max(0, el.scrollWidth - el.clientWidth); + const clamped = Math.min(Math.max(x, 0), max); + if (!isRtl(el)) return clamped; + const type = detectRtlScrollType(); + if (type === 'negative') return clamped === 0 ? 0 : -clamped; + if (type === 'default') return max - clamped; + return clamped; +} + +// A horizontal viewport Rune scrolled itself (a wheel, a key): move the mirror's container to +// match, so the two stay the same text. The container's own scroll event echoes back the same +// offset, which Rune ignores. +export function syncScrollX(h, path, x, rtl) { + const el = h.scrollEls.get(path); + if (!el) return; + if (rtl !== undefined) { + const dir = rtl ? 'rtl' : 'ltr'; + if (el.dir !== dir) el.dir = dir; + } + const target = domScrollLeft(el, x); + if (Math.abs(el.scrollLeft - target) > 0.5) el.scrollLeft = target; +} + +// Rune's first frame is on screen: the canvas announces `runepresent`, and a page swaps its +// static export (`[data-rune-static]`) for the live mirror, keeping the section that was at +// the top of the window where it was. The export is hidden, not removed: removing the +// element a browser counted as the largest contentful paint takes the metric away. It goes +// two frames later (the canvas covers it by then), as a phone may not have painted the page +// before Rune's first frame, and content never painted can't count at all. +export function presented(h) { + if (h.disposed || h.presented) return; + h.presented = true; + h.canvas.dispatchEvent(new CustomEvent('runepresent', { bubbles: true })); + if (h.page) requestAnimationFrame(() => requestAnimationFrame(() => { if (!h.disposed) dropStatic(h); })); +} + +function dropStatic(h) { + if (h.disposed || h.swapped) return; + const parts = [...document.querySelectorAll('[data-rune-static]')]; + const exported = parts.find((el) => el.tagName !== 'STYLE'); + if (!exported) { h.swapped = true; return; } + // A finger is down, or the page is still coasting: hiding the export would take it out of the + // page's flow under a scroll that is under way, and iOS stops momentum dead when the scroll + // position moves underneath it. The touchend or the next scroll arms the retry. + if (h.touchDown) return; + if (performance.now() - h.lastScrollAt < 120) { deferStatic(h); return; } + h.swapped = true; + let anchor = null, offset = 0; + if (window.scrollY > 0) { + for (const el of exported.querySelectorAll('[id]')) { + const r = el.getBoundingClientRect(); + if (r.bottom > 0) { anchor = el.id; offset = r.top; break; } + } + } + for (const el of parts) { + if (el.tagName === 'STYLE') { el.remove(); continue; } + // Out of the page's flow, find, focus and accessibility tree, its ids the mirror's. + el.style.cssText = 'position:absolute;top:0;left:0;width:0;height:0;overflow:hidden;visibility:hidden;'; + el.inert = true; + el.setAttribute('aria-hidden', 'true'); + el.removeAttribute('id'); + for (const named of el.querySelectorAll('[id]')) named.removeAttribute('id'); + el.removeAttribute('data-rune-static'); + el.setAttribute('data-rune-static-hidden', ''); + } + const live = anchor && h.a11y.querySelector(`#${CSS.escape(anchor)}`); + if (live) { + const delta = live.getBoundingClientRect().top - offset; + // The export's CSS and the live layout differ by a pixel or two here and there; taking the + // page's scroll for that would stop a flick for nothing. + if (Math.abs(delta) > 2) window.scrollTo({ top: window.scrollY + delta, behavior: 'instant' }); + } +} + +// Swaps once the page has settled. Only a scroll or a touch arms it, so a still page doesn't poll. +function deferStatic(h) { + if (h.staticTimer || h.swapped || !h.presented || h.disposed) return; + h.staticTimer = setTimeout(() => { h.staticTimer = 0; if (!h.disposed) dropStatic(h); }, 150); +} + +export function activate(h) { + // A page's canvas is `tabindex="-1"`: focusing it on a tap would only drop the reader's text + // selection or a link's focus. An input that took the keyboard still gets it. + if (h.page && !h.key) return; + const field = h.key ? h.field : h.canvas; + if (h.key) field.inputMode = 'text'; + if (document.activeElement !== field) field.focus({ preventScroll: true }); +} + +export async function pastedImage(h, max) { + const file = h.image; + h.image = undefined; + return file && file.size <= max ? new Uint8Array(await file.arrayBuffer()) : undefined; +} + +export function destroy(h) { + closeMenu(h, false); + h.disposed = true; + h.image = undefined; + clearTimeout(h.staticTimer); + clearTimeout(h.a11yTimer); + for (const remove of h.listeners) remove(); + h.password.value = ''; h.textarea.value = ''; h.copyText = ''; + h.a11yNodes.clear(); + h.scrollEls.clear(); + h.a11y.remove(); + h.band?.remove(); + h.password.remove(); h.textarea.remove(); +} diff --git a/app/vendor/rune/crates/rune/src/platform/web/cpu_canvas.rs b/app/vendor/rune/crates/rune/src/platform/web/cpu_canvas.rs new file mode 100644 index 0000000..b67a421 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/platform/web/cpu_canvas.rs @@ -0,0 +1,180 @@ +//! A page's frames painted on the CPU (`render::cpu_boot`), from the module's first frame until +//! WebGPU takes over, and for good where it never does. The painter keeps a BGRA buffer of the +//! frame it painted last and says which rectangles changed; those go to a 2D canvas under the +//! GPU's, turned into RGBA on the way. The GPU's canvas lies over it, see-through until the +//! GPU's first frame is done (`web.rs`), and takes the page's input all along. + +use std::cell::Cell; + +use wasm_bindgen::{JsCast, JsValue}; + +use crate::render::cpu_boot::{CpuPainter, HalfRounding, NeedsGpu, Scene, Target}; +use crate::runtime::RuntimeCore; + +pub(super) struct CpuCanvas { + canvas: web_sys::HtmlCanvasElement, + ctx: web_sys::CanvasRenderingContext2d, + painter: CpuPainter, + /// The frame painted last, `size.0 * 4` bytes a row, B, G, R, A. + buffer: Vec<u8>, + size: (u32, u32), + /// One row of a rectangle in RGBA, on its way to `staged`. + rows: Vec<u8>, + /// The rectangle's rows in the page's own memory: an image made over the module's memory takes the + /// browser tens of milliseconds to put (all of it, for a full frame), one over this a few + /// hundred microseconds. + staged: js_sys::Uint8ClampedArray, + /// How the GPU that takes over rounds half floats: once it exists, its own. + pub(super) half: HalfRounding, +} + +/// What a CPU frame cost, for a page that asks (`globalThis.__runeCpuFrames`, an array a +/// measuring harness sets): microseconds painting and putting, and pixels put. +#[derive(Default)] +pub(super) struct Cost { + /// Filling the frame's new glyph masks. + pub fill_us: f64, + /// Binning, hashing tiles and painting the changed ones. + pub paint_us: f64, + /// Of that, painting. + pub raster_us: f64, + /// Turning the changed rectangles into RGBA and putting them on the canvas. + pub put_us: f64, + /// Of that, turning them into RGBA. + pub swizzle_us: f64, + pub put_px: u64, +} + +thread_local! { + /// Whether the page asked for each frame's cost, read once. + static STATS: Cell<Option<bool>> = const { Cell::new(None) }; +} + +impl CpuCanvas { + /// A 2D canvas laid out exactly as `over` (the GPU's), drawn under it and taking no input. + pub(super) fn under(over: &web_sys::HtmlCanvasElement) -> Option<CpuCanvas> { + let document = over.owner_document()?; + let canvas: web_sys::HtmlCanvasElement = document.create_element("canvas").ok()?.dyn_into().ok()?; + let css = over.style().css_text(); + // The GPU's canvas starts see-through: this one shows. + canvas.style().set_css_text(&format!("{css};pointer-events:none;opacity:1")); + canvas.set_attribute("aria-hidden", "true").ok(); + over.parent_node()?.insert_before(&canvas, Some(over)).ok()?; + let options = js_sys::Object::new(); + js_sys::Reflect::set(&options, &"alpha".into(), &JsValue::FALSE).ok(); + let ctx = canvas.get_context_with_context_options("2d", &options).ok()??.dyn_into().ok()?; + Some(CpuCanvas { canvas, ctx, painter: CpuPainter::new(1), buffer: Vec::new(), size: (0, 0), rows: Vec::new(), staged: js_sys::Uint8ClampedArray::new_with_length(0), half: HalfRounding::default() }) + } + + /// Paints the runtime's last frame at `size` physical pixels and puts what changed on the + /// canvas. A frame only the GPU can draw (`Scene::needs_gpu`) leaves the last one up. + pub(super) fn paint(&mut self, rt: &mut RuntimeCore, size: (u32, u32)) -> Result<Cost, NeedsGpu> { + let (w, h) = (size.0.max(1), size.1.max(1)); + if self.size != (w, h) { + // A new size clears the canvas, and the buffer starts again: every tile paints. + self.canvas.set_width(w); + self.canvas.set_height(h); + self.buffer.clear(); + self.buffer.resize(w as usize * h as usize * 4, 0); + self.painter.forget(); + self.size = (w, h); + } + let start = crate::time::Instant::now(); + self.painter.fill_masks(&mut rt.text.atlas); + let filled = crate::time::Instant::now(); + let scene = Scene::new(&rt.instances, &rt.text.atlas, &rt.images, (w, h), rt.clear_color()) + .srgb_blend(rt.srgb_blend()) + .fade_stops(rt.fade_stops()) + .native_surfaces(!rt.surfaces.is_empty()) + .half_rounding(self.half) + .font_smoothing(rt.font_smoothing()); + let painted = self.painter.paint(&scene, &mut Target::new(&mut self.buffer, w, h))?; + let put = crate::time::Instant::now(); + let mut px = 0u64; + let mut swizzle = std::time::Duration::ZERO; + for &[x0, y0, x1, y1] in &painted.rects { + let (rw, rh) = (x1.saturating_sub(x0), y1.saturating_sub(y0)); + if rw == 0 || rh == 0 { continue; } + let began = crate::time::Instant::now(); + let line = rw as usize * 4; + let len = line * rh as usize; + if (self.staged.length() as usize) < len { + self.staged = js_sys::Uint8ClampedArray::new_with_length((w as usize * h as usize * 4).max(len) as u32); + } + // A row at a time through one row's buffer: a whole frame's RGBA copy in the module's + // memory (4 MB at 1280x800) would stay in its high-water mark for good. + self.rows.resize(line, 0); + for (i, y) in (y0..y1).enumerate() { + let at = (y as usize * w as usize + x0 as usize) * 4; + rgba(&self.buffer[at..at + line], &mut self.rows); + self.staged.subarray((i * line) as u32, ((i + 1) * line) as u32).copy_from(&self.rows); + } + swizzle += began.elapsed(); + let staged = self.staged.subarray(0, len as u32); + if let Ok(image) = web_sys::ImageData::new_with_js_u8_clamped_array_and_sh(&staged, rw, rh) { + self.ctx.put_image_data(&image, f64::from(x0), f64::from(y0)).ok(); + } + px += u64::from(rw) * u64::from(rh); + } + let end = crate::time::Instant::now(); + let us = |d: std::time::Duration| d.as_secs_f64() * 1e6; + let cost = Cost { fill_us: us(filled - start), paint_us: us(put - filled), raster_us: painted.report.raster_ns as f64 / 1e3, put_us: us(end - put), swizzle_us: us(swizzle), put_px: px }; + report(&cost); + Ok(cost) + } + + /// The frame painted last: B, G, R, A, `size.0 * 4` bytes a row. + pub(super) fn pixels(&self) -> &[u8] { &self.buffer } + + /// The canvas goes: the GPU's frames are on screen in its place. Its pixels go now (a 0x0 + /// canvas has none), not when the page next collects garbage: 15.6 MB at 1280x800 until then. + pub(super) fn remove(self) { + self.canvas.set_width(0); + self.canvas.set_height(0); + self.canvas.remove(); + } +} + +/// `bgra`'s pixels as R, G, B, A, into `out` (as long). +#[allow(unsafe_code)] +fn rgba(bgra: &[u8], out: &mut [u8]) { + let swap = |v: u32| (v & 0xff00_ff00) | ((v >> 16) & 0xff) | ((v & 0xff) << 16); + // Whole pixels as words where both sides line up (they do: rows start on whole pixels of + // buffers the allocator aligns). + let (Ok(dm), Ok(sm)) = (bytemuck::try_cast_slice_mut::<u8, u32>(out), bytemuck::try_cast_slice::<u8, u32>(bgra)) else { + for (d, s) in out.chunks_exact_mut(4).zip(bgra.chunks_exact(4)) { + d.copy_from_slice(&[s[2], s[1], s[0], s[3]]); + } + return; + }; + #[cfg(target_feature = "simd128")] + { + use core::arch::wasm32::{i8x16, u8x16_swizzle, v128, v128_load, v128_store}; + // Four pixels at a time: B, G, R, A to R, G, B, A. + const ORDER: v128 = i8x16(2, 1, 0, 3, 6, 5, 4, 7, 10, 9, 8, 11, 14, 13, 12, 15); + let whole = dm.len() / 4 * 4; + let (dq, dr) = dm.split_at_mut(whole); + let (sq, sr) = sm.split_at(whole); + for (d, s) in dq.chunks_exact_mut(4).zip(sq.chunks_exact(4)) { + // SAFETY: each chunk is four u32s, 16 bytes; v128 loads and stores need no alignment. + unsafe { v128_store(d.as_mut_ptr().cast(), u8x16_swizzle(v128_load(s.as_ptr().cast()), ORDER)) } + } + for (d, s) in dr.iter_mut().zip(sr) { *d = swap(*s); } + } + #[cfg(not(target_feature = "simd128"))] + for (d, s) in dm.iter_mut().zip(sm) { *d = swap(*s); } +} +/// Appends a frame's cost to `globalThis.__runeCpuFrames`, when the page made that array. +fn report(cost: &Cost) { + let wanted = STATS.get().unwrap_or_else(|| { + let on = js_sys::Reflect::get(&js_sys::global(), &"__runeCpuFrames".into()).is_ok_and(|v| js_sys::Array::is_array(&v)); + STATS.set(Some(on)); + on + }); + if !wanted { return; } + let Ok(list) = js_sys::Reflect::get(&js_sys::global(), &"__runeCpuFrames".into()) else { return }; + let list: js_sys::Array = list.unchecked_into(); + let row = js_sys::Array::new(); + for v in [cost.fill_us, cost.paint_us, cost.raster_us, cost.put_us, cost.swizzle_us, cost.put_px as f64] { row.push(&v.into()); } + list.push(&row); +} diff --git a/app/vendor/rune/crates/rune/src/platform/web/frame.rs b/app/vendor/rune/crates/rune/src/platform/web/frame.rs new file mode 100644 index 0000000..ba89dfb --- /dev/null +++ b/app/vendor/rune/crates/rune/src/platform/web/frame.rs @@ -0,0 +1,452 @@ +//! Per-frame redraw loop, document band sizing, canvas surface resize, and frame requests. + +use std::{sync::Arc, time::Duration}; +use winit::{event_loop::{ActiveEventLoop, EventLoopProxy}, platform::web::WindowExtWebSys, window::Window}; +use crate::frame::clock::FrameClock; +use crate::frame::host_step::{self, Acquire, FrameHost, Gate, PostStepCheck, ReacquireReason, RenderPrep, StepInfo}; +use crate::runtime::RuntimeCore; +use crate::time::Instant; +use crate::window::Missed; +use super::{Browser, Running, Wake, after, error, full_faces, gpu::{self, Draw, FINISH_LIMIT}, handover::QUIET, large_viewport, page_fonts, pipelines, web_math}; + +/// The overscan a page's canvas carries above and below the window, in CSS points: the distance +/// the browser's compositor can scroll before Rune has to draw a new band. +const SKIRT: f32 = 256.0; + +/// The largest texture side a canvas may have before a GPU says: WebGPU's default limit. +pub(super) const CPU_MAX_DIM: u32 = 8192; + +impl Running { + fn max_dim(&self) -> u32 { + self.draw.gpu().map_or(CPU_MAX_DIM, |side| side.gpu.device.limits().max_texture_dimension_2d.max(1)) + } + + pub(super) fn resize_surface(&mut self, window: &Window, size: winit::dpi::PhysicalSize<u32>, scale: f32) { + let max_dim = self.max_dim(); + if self.document { + // The canvas covers a band of the page: size it before the box is measured. + let (view, band) = band_css(window, scale, max_dim); + set_band_height(window, band); + self.app.rt_mut().set_band(band, view); + } + let size = window.canvas().map_or(size, |c| canvas_physical(&c, size, scale)); + self.suspended = size.width == 0 || size.height == 0; + if self.suspended { return; } + let next = (size.width.min(max_dim), size.height.min(max_dim)); + let document = self.document; + if let Some(side) = self.draw.gpu_mut() { + let (kept, reconfigure) = web_math::should_reconfigure_surface((side.config.width, side.config.height), next, document); + if reconfigure { + side.config.width = kept.0; + side.config.height = kept.1; + side.surface.configure(&side.gpu.device, &side.config); + } + self.size = (side.config.width, side.config.height); + } else { + self.size = next; + } + self.app.rt_mut().set_viewport((next.0 as f32 / scale, next.1 as f32 / scale), scale); + } + + /// Puts a page's canvas where the band it just drew starts in the document. The browser's + /// compositor scrolls those pixels itself, at its own rate, until the window nears the band's + /// edge and the next frame draws a new one. + fn sync_band(&mut self, window: &Window) { + if !self.document { return; } + let top = self.app.rt().page_offset(); + if self.band == Some(top) { return; } + self.band = Some(top); + if let Some(canvas) = window.canvas() { + canvas.style().set_property("transform", &format!("translate3d(0,{top}px,0)")).ok(); + } + } + + pub(super) fn apply_frame_requests(&mut self, window: &Window) { + let rt = self.app.rt_mut(); + if !self.embedded + && let Some(title) = rt.host.window_title.take_change() + && let Some(doc) = web_sys::window().and_then(|w| w.document()) + { + doc.set_title(title); + } + // A page's height is the mirror's, which `sync_input` keeps; the canvas stays the band. + if self.document { + rt.host.window_frame = None; + } else if let Some(req) = rt.host.window_frame.take() + && let Some((_, h)) = req.size + && let Some(canvas) = window.canvas() + { + canvas.style().set_property("height", &format!("{h}px")).ok(); + } + } +} + +/// A page's band in CSS points: `view`, how much of the document the window shows at once, and +/// `band`, the canvas that covers it. The view height is the *largest* viewport (`100lvh`), so a +/// phone's toolbar coming and going never changes the band. The skirt is clamped so the texture +/// stays inside the device's limit; a viewport already at the limit has no skirt. +pub(super) fn band_css(window: &Window, scale: f32, max_dim: u32) -> (f32, f32) { + let scale = scale.max(1e-3); + let reported = large_viewport(); + let view = if reported > 0.0 { reported } else { window.inner_size().height as f32 / scale }; + let max = max_dim as f32 / scale; + let band = (view + 2.0 * SKIRT).min(max.max(view)); + (view, band) +} + +/// The canvas's CSS height is its band, in points. +pub(super) fn set_band_height(window: &Window, band: f32) { + if let Some(canvas) = window.canvas() { + let height = format!("{band}px"); + if canvas.style().get_property_value("height").unwrap_or_default() != height { + canvas.style().set_property("height", &height).ok(); + } + } +} + +/// The canvas's size in device pixels: its CSS box times `scale` when the browser's own +/// `devicePixelContentBoxSize` (what winit reports) disagrees, as Chromium's emulated device +/// scale does by reporting CSS pixels. Trusting it would lay out at a fraction of the box. +fn canvas_physical(canvas: &web_sys::HtmlCanvasElement, reported: winit::dpi::PhysicalSize<u32>, scale: f32) -> winit::dpi::PhysicalSize<u32> { + let rect = canvas.get_bounding_client_rect(); + let (w, h) = (rect.width() as f32, rect.height() as f32); + if w <= 0.0 || h <= 0.0 { return reported; } + let fix = |got: u32, css: f32| { let want = (css * scale).round().max(1.0); if (got as f32 - want).abs() > scale.ceil() + 1.0 { want as u32 } else { got } }; + winit::dpi::PhysicalSize::new(fix(reported.width, w), fix(reported.height, h)) +} + +enum WebDrawable { + Cpu, + Gpu(wgpu::SurfaceTexture), +} + +enum PreparedWeb { + Cpu, + HandingOver { gpu: Option<gpu::PreparedGpu> }, + Gpu(gpu::PreparedGpu), +} + +struct WebFrameHost<'a> { + r: &'a mut Running, + window: &'a Arc<Window>, + proxy: &'a EventLoopProxy<Wake>, + first_at: &'a mut Option<Instant>, + drawn_at: &'a mut Option<Instant>, + now: Option<Instant>, + commits: u64, + had_input: bool, + tick: bool, + reblend_tried: Option<bool>, + drawn: bool, + fatal_error: Option<String>, + should_end: bool, + try_gpu_came: bool, +} + +impl FrameHost for WebFrameHost<'_> { + type Drawable = WebDrawable; + type Prepared = PreparedWeb; + + fn gate(&mut self) -> Gate { + web_math::web_frame_gate(self.r.suspended, self.r.draw.kind()) + } + + fn needs_reblend(&self) -> bool { + matches!(&self.r.draw, Draw::Gpu(side) if side.renderer.srgb_blend() != self.r.app.rt().srgb_blend()) + } + + fn reblend(&mut self) -> bool { + let target = self.r.app.rt().srgb_blend(); + self.reblend_tried = Some(target); + if let Draw::Gpu(side) = &mut self.r.draw { + gpu::reblend(side, self.r.app.rt_mut()); + } + true + } + + fn acquire(&mut self) -> Acquire<WebDrawable> { + match &mut self.r.draw { + Draw::Gpu(side) => match gpu::acquire_texture(side) { + Ok(frame) => Acquire::Ready(WebDrawable::Gpu(frame)), + Err(missed) => Acquire::Missed(missed), + }, + Draw::Cpu { .. } | Draw::HandingOver { .. } => Acquire::Ready(WebDrawable::Cpu), + Draw::ContextLost | Draw::Moving => Acquire::Missed(Missed::Unconfigured), + } + } + + fn step_runtime(&mut self) -> StepInfo { + let now = Instant::now(); + self.now = Some(now); + let (commits, had_input) = { + let rt = self.r.app.rt(); + (rt.stats.commits, rt.has_pending_input()) + }; + self.commits = commits; + self.had_input = had_input; + let tick = !std::mem::take(&mut self.r.full_redraw) + && matches!(&self.r.draw, Draw::Gpu(side) if !side.renderer.checking_gpu()) + && !self.r.app.compositor_animating() + && !self.r.app.compositor_draws_own() + && self.r.app.rt_mut().paint_cycle_tick(); + self.tick = tick; + let (animating, dt) = if tick { + let dt = now.saturating_duration_since(self.r.clock.last()).as_secs_f64(); + self.r.clock.hold(now); + (false, dt) + } else { + let compositing = self.r.app.compositor_animating(); + self.r.app.clock_advance(&mut self.r.clock, now, compositing) + }; + StepInfo { runtime_animating: animating, animating, dt, update_ms: 0.0, presents_at: None } + } + + fn post_step_check(&mut self, _info: &mut StepInfo) -> PostStepCheck { + if let Draw::Gpu(side) = &self.r.draw + && web_math::should_post_step_reblend( + side.renderer.srgb_blend(), + self.r.app.rt().srgb_blend(), + self.reblend_tried, + ) + { + PostStepCheck::Reacquire(ReacquireReason::Reblend) + } else { + PostStepCheck::Keep + } + } + + fn prepare_reacquire(&mut self, reason: ReacquireReason, _info: &mut StepInfo) -> bool { + match reason { + ReacquireReason::Reblend => self.reblend(), + } + } + + fn on_missed(&mut self, missed: Missed, stepped: bool) { + match web_math::web_miss_action(missed) { + web_math::WebMissAction::Fatal => { + self.fatal_error = Some("WebGPU canvas acquisition failed".into()); + } + web_math::WebMissAction::CoveredOnly => { + if !stepped { + self.r.app.covered_wake(); + self.r.clipboard.flush_core(self.r.app.rt_mut()); + } + } + web_math::WebMissAction::RetryNextFrame => { + if !stepped { + self.r.app.covered_wake(); + self.r.clipboard.flush_core(self.r.app.rt_mut()); + } + self.window.request_redraw(); + } + } + } + + fn sync_after_step(&mut self, info: &mut StepInfo) { + let now = self.now.unwrap_or_else(Instant::now); + info.update_ms = now.elapsed().as_secs_f64() * 1000.0; + self.r.apply_frame_requests(self.window); + self.r.clipboard.flush_core(self.r.app.rt_mut()); + // A menu asked for opens as the page's own elements (bridge.js `showMenu`), once the frame + // that asked has laid out what it anchors to. + if !self.r.app.rt().popup_waits_for_layout() { + match self.r.app.rt_mut().take_popup() { + Some(Some(show)) => { + let rt = self.r.app.rt(); + self.r.input.show_menu(&show, rt.backdrop_dark().unwrap_or(rt.env.system_dark)); + } + Some(None) => { self.r.app.resolve_popup(None).ok(); } + None => {} + } + } + self.r.app.rt_mut().refuse_file_dialog("native file dialogs are unsupported on web"); + if !self.tick { self.r.sync_input(false); } + let rt = self.r.app.rt(); + self.r.cursor.apply(self.window, rt.cursor(), rt.pointer().is_some()); + if !rt.surfaces.is_empty() { + self.fatal_error = Some("native video surfaces are unsupported on web".into()); + } + } + + fn prepare_render(&mut self, drawable: WebDrawable, _info: &mut StepInfo) -> RenderPrep<PreparedWeb> { + if self.fatal_error.is_some() { + return RenderPrep::Abort; + } + match (&mut self.r.draw, drawable) { + (Draw::Cpu { .. }, WebDrawable::Cpu) => RenderPrep::Ready(PreparedWeb::Cpu), + (Draw::HandingOver { side, built, .. }, WebDrawable::Cpu) => { + let gpu = if built.get() { + let rt = self.r.app.rt_mut(); + gpu::reblend(side, rt); + match gpu::acquire_texture(side) { + Ok(frame) => Some(gpu::prepare_gpu_frame(side, rt, frame, gpu::drift_wanted(), false)), + Err(missed) => { + web_sys::console::warn_1( + &format!("rune: the GPU's hand-over frame wasn't drawn ({missed:?})").into(), + ); + None + } + } + } else { + None + }; + RenderPrep::Ready(PreparedWeb::HandingOver { gpu }) + } + (Draw::Gpu(side), WebDrawable::Gpu(frame)) => { + let prepared = gpu::prepare_gpu_frame(side, self.r.app.rt_mut(), frame, false, self.tick); + RenderPrep::Ready(PreparedWeb::Gpu(prepared)) + } + _ => RenderPrep::Abort, + } + } + + fn render(&mut self, prepared: &mut PreparedWeb, info: &StepInfo) -> bool { + let size = self.r.size; + match (&mut self.r.draw, prepared) { + // A frame only the GPU draws (`Scene::needs_gpu`) leaves the last one up. + (Draw::Cpu { cpu, .. }, PreparedWeb::Cpu) => { + self.drawn = cpu.paint(self.r.app.rt_mut(), size).is_ok(); + false + } + (Draw::HandingOver { cpu, side, .. }, PreparedWeb::HandingOver { gpu }) => { + self.drawn = cpu.paint(self.r.app.rt_mut(), size).is_ok(); + // Both renderers draw this frame once the browser has compiled the GPU's + // pipelines; the GPU's canvas stays see-through until its frame is done. + match gpu.as_mut() { + Some(prepared_gpu) => { + gpu::encode_gpu_frame(side, &mut *self.r.app, prepared_gpu, info.dt, info.update_ms) + } + None => false, + } + } + (Draw::Gpu(side), PreparedWeb::Gpu(prepared_gpu)) => { + gpu::encode_gpu_frame(side, &mut *self.r.app, prepared_gpu, info.dt, info.update_ms) + } + _ => false, + } + } + + fn submit_and_present(&mut self, prepared: PreparedWeb, _info: &StepInfo) -> Instant { + match (&mut self.r.draw, prepared) { + (Draw::Cpu { .. }, PreparedWeb::Cpu) => {} + (Draw::HandingOver { cpu, side, done, since, .. }, PreparedWeb::HandingOver { gpu }) => { + if let Some(prepared_gpu) = gpu { + let copy = gpu::submit_gpu_frame(side, prepared_gpu, || {}); + // That frame made pipelines its draw needed and drew a fallback for each + // while the browser checks it (the renderer hears the answers as it + // draws): frames go on drawing into the see-through canvas, and the + // first one drawn with every check answered is the hand-over frame. + if side.renderer.checking_gpu() { + crate::marks::mark("web.handover.warming"); + } else { + if let Some(copy) = copy { copy.count(cpu.pixels().to_vec()); } + *done = Some(gpu::when_done(side, self.proxy)); + *since = Instant::now(); + let proxy = self.proxy.clone(); + after(FINISH_LIMIT + Duration::from_millis(50), move || { proxy.send_event(Wake::App).ok(); }); + crate::marks::mark("web.handover.drawn"); + } + } + } + (Draw::Gpu(side), PreparedWeb::Gpu(prepared_gpu)) => { + let window = self.window; + let _ = gpu::submit_gpu_frame(side, prepared_gpu, || window.pre_present_notify()); + self.drawn = true; + } + _ => {} + } + Instant::now() + } + + fn present_targets(&mut self) -> (Option<&mut FrameClock>, &mut RuntimeCore) { + (Some(&mut self.r.clock), self.r.app.rt_mut()) + } + + fn settle(&mut self, submitted: Instant, info: &StepInfo) { + let now = self.now.unwrap_or(submitted); + // In the same commit as the frame: the canvas moves to where this frame drew it. + self.r.sync_band(self.window); + // Only an ambient loop's step (a frame its wake asked for, no commit, nothing else moving). + let ambient = { + let rt = self.r.app.rt(); + !self.had_input && !info.runtime_animating && rt.stats.commits == self.commits && rt.ambient.is_some() + }; + if self.drawn && !ambient { *self.drawn_at = Some(now); } + if self.drawn && !self.r.presented { + self.r.presented = true; + *self.first_at = Some(now); + let proxy = self.proxy.clone(); + // A browser that compiles pipelines asynchronously is asked in the task after this + // frame: nothing waits for quiet there (`maybe_start_gpu`). + let first_look = if pipelines::browser_compiles_async() { Duration::ZERO } else { QUIET }; + after(first_look, move || { proxy.send_event(Wake::StartGpu).ok(); }); + crate::marks::mark("web.first.presented"); + self.r.input.presented(); + // In a task of its own: a click or key that came with the first frame is handled + // first, not after what the app starts once it shows (about 9 ms in OpenCode's). + if let Some(mut ready) = self.r.on_ready.take() { after(Duration::ZERO, move || ready(&crate::WindowHandle::new("main"))); } + page_fonts::share_later(self.r.fonts); + let proxy = self.proxy.clone(); + full_faces::fetch(std::mem::take(&mut self.r.late_fonts), !self.r.document, move || { proxy.send_event(Wake::App).ok(); }); + } + if self.r.app.rt_mut().shell_request.take().is_some() { + self.should_end = true; + return; + } + // A frame that drew a fallback while the browser checks a pipeline is drawn again once it + // answers, and so is a hand-over waiting on that check. + let checking = self.r.draw.gpu().is_some_and(|side| side.renderer.checking_gpu()); + let handing = matches!(self.r.draw, Draw::HandingOver { done: None, .. }); + let wants_frame = { + let rt = self.r.app.rt(); + info.animating || rt.has_pending_input() || rt.live_pending() || self.r.app.compositor_animating() || checking + }; + if wants_frame { + self.window.request_redraw(); + } + self.try_gpu_came = self.r.presented && !handing; + } +} + +impl Browser { + /// Draws a frame through the shared [`host_step::run`] frame sequencer: the runtime steps, + /// then the CPU paints it, the GPU draws it, or both while handing over. + pub(super) fn redraw(&mut self, event_loop: &ActiveEventLoop) { + if self.lost_device(event_loop) { return; } + self.maybe_restore_webgl(); + self.hand_over_if_done(); + let (fatal_error, should_end, try_gpu_came, embedded, document) = { + let mut running = self.running.borrow_mut(); + let (Some(window), Some(r)) = (&self.window, &mut *running) else { return }; + let mut host = WebFrameHost { + r, + window, + proxy: &self.proxy, + first_at: &mut self.first_at, + drawn_at: &mut self.drawn_at, + now: None, + commits: 0, + had_input: false, + tick: false, + reblend_tried: None, + drawn: false, + fatal_error: None, + should_end: false, + try_gpu_came: false, + }; + host_step::run(&mut host); + (host.fatal_error, host.should_end, host.try_gpu_came, host.r.embedded, host.r.document) + }; + if let Some(msg) = fatal_error { + error(&msg, self.window.as_ref().and_then(|w| w.canvas()).as_ref(), embedded, document); + self.end(event_loop); + return; + } + if should_end { + self.end(event_loop); + return; + } + // A GPU that came before the first frame is taken up after it. + if try_gpu_came { self.gpu_came(); } + } +} diff --git a/app/vendor/rune/crates/rune/src/platform/web/full_faces.rs b/app/vendor/rune/crates/rune/src/platform/web/full_faces.rs new file mode 100644 index 0000000..353db59 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/platform/web/full_faces.rs @@ -0,0 +1,104 @@ +//! Fetches the faces a page adds once its first frame is up (see `text::full_faces`): the full +//! Inter faces when the app sets text in the embedded Inter, and `App::font_url_later`'s fonts. + +use std::cell::RefCell; +use std::rc::Rc; +use std::sync::atomic::{AtomicBool, Ordering}; + +#[cfg(feature = "embedded-fonts")] +use wasm_bindgen::prelude::*; + +#[cfg(feature = "embedded-fonts")] +#[wasm_bindgen] +extern "C" { + /// The URL of the app's `app.js`, which a web build serves the faces beside. + #[wasm_bindgen(thread_local_v2, js_namespace = ["import", "meta"], js_name = url)] + static MODULE_URL: String; +} + +static STARTED: AtomicBool = AtomicBool::new(false); + +/// Starts the fetches, once per page; `wake` runs as each set arrives. The full Inter faces +/// are one set, as a page that fetches only some would set text in two cuts; the app's late +/// fonts are another, each skipped alone if it fails. +/// `share` adds the late fonts to the page's own too (`page_fonts`). +pub(super) fn fetch(late: Vec<String>, share: bool, wake: impl Fn() + Clone + 'static) { + if STARTED.swap(true, Ordering::AcqRel) { + return; + } + #[cfg(feature = "embedded-fonts")] + if crate::text::full_faces::embedded_inter() { + let base = MODULE_URL.with(String::clone); + let urls = crate::text::full_faces::FILES.iter().map(|file| super::platform::resolve_url(file, &base)).collect(); + load(urls, true, false, wake.clone()); + } + let wake: Rc<dyn Fn()> = Rc::new(wake); + let later = LATER.with_borrow_mut(|later| { + later.ready = Some((share, wake.clone())); + later.seen.extend(late.iter().cloned()); + std::mem::take(&mut later.asked) + }); + let late: Vec<String> = late.into_iter().chain(later).collect(); + if !late.is_empty() { + load(late, false, share, move || wake()); + } +} + +/// [`now`]'s fonts, and, once the first frame is up, how [`fetch`] loads them. +#[derive(Default)] +struct Later { + /// Asked for before the first frame: they go with the app's late fonts. + asked: Vec<String>, + /// Every URL asked for, so each loads once. + seen: Vec<String>, + ready: Option<(bool, Rc<dyn Fn()>)>, +} + +thread_local! { + static LATER: RefCell<Later> = RefCell::default(); +} + +/// Fetches `url`'s font now, as `App::font_url_later`'s fonts are fetched: added to the app's +/// fonts when it arrives (every window takes it up on its next frame), reported and skipped if +/// it fails. Asked before the first frame, it waits for it. Each URL loads once. +pub(super) fn now(url: &str) { + let ready = LATER.with_borrow_mut(|later| { + if later.seen.iter().any(|u| u == url) { + return None; + } + later.seen.push(url.to_owned()); + if later.ready.is_none() { + later.asked.push(url.to_owned()); + } + later.ready.clone() + }); + if let Some((share, wake)) = ready { + load(vec![url.to_owned()], false, share, move || wake()); + } +} +fn load(urls: Vec<String>, all_or_none: bool, share: bool, wake: impl FnOnce() + 'static) { + let files: Vec<_> = urls.into_iter().map(|url| { + let bytes = super::platform::fetch_bytes(&url); + (url, bytes) + }).collect(); + wasm_bindgen_futures::spawn_local(async move { + let mut faces = Vec::new(); + for (url, bytes) in files { + match wasm_bindgen_futures::JsFuture::from(bytes).await { + Ok(bytes) => faces.push(js_sys::Uint8Array::new(&bytes).to_vec()), + Err(e) if all_or_none => { + let note = format!("rune: {url} did not load, so text outside Latin, Greek and Cyrillic draws in fallback fonts:"); + web_sys::console::warn_2(&note.into(), &e); + return; + } + Err(e) => web_sys::console::warn_2(&format!("rune: font {url} did not load:").into(), &e), + } + } + if faces.is_empty() { + return; + } + if share { super::page_fonts::share(faces.iter().map(Vec::as_slice)); } + crate::text::full_faces::arrive(faces); + wake(); + }); +} diff --git a/app/vendor/rune/crates/rune/src/platform/web/gpu.rs b/app/vendor/rune/crates/rune/src/platform/web/gpu.rs new file mode 100644 index 0000000..38b475f --- /dev/null +++ b/app/vendor/rune/crates/rune/src/platform/web/gpu.rs @@ -0,0 +1,482 @@ +//! WebGPU and WebGL2 backend setup, canvas surface configuration, GPU frame submission, and +//! hand-over pixel readback. + +use std::{cell::{Cell, RefCell}, rc::Rc, time::Duration}; +use wasm_bindgen::JsCast; +use winit::event_loop::EventLoopProxy; +use crate::{render::{Gpu, Renderer}, runtime::RuntimeCore, time::Instant}; +use super::{Wake, app::{CompositorFrame, WebApp}, cpu_canvas, health}; + +/// The GPU's side of the page: its device, the canvas's surface and Rune's renderer. +pub(super) struct GpuSide { + pub(super) gpu: Gpu, + pub(super) surface: wgpu::Surface<'static>, + pub(super) config: wgpu::SurfaceConfiguration, + pub(super) renderer: Renderer, + pub(super) backend: wgpu::Backend, +} + +/// A GPU device or WebGL2 context loss waiting for `Browser::lost_device` to handle. +pub(super) enum Loss { + WebGpu(String), + WebGl(String), +} + +impl Loss { + pub(super) fn is_webgl(&self) -> bool { + matches!(self, Loss::WebGl(_)) + } + + pub(super) fn reason(&self) -> &str { + match self { + Loss::WebGpu(why) | Loss::WebGl(why) => why, + } + } +} + +/// Who draws the page's frames, and how far the GPU is (the native CPU-first window's +/// `SurfaceMode`, with two canvases for its two surfaces). +pub(super) enum Draw { + /// The CPU paints into its canvas under the GPU's, which stays see-through and takes the + /// input. `failed`: the GPU won't come automatically (no WebGPU, or it was lost until restore). + Cpu { cpu: cpu_canvas::CpuCanvas, failed: bool }, + /// The GPU is made and its canvas configured, still see-through. `built` turns true once + /// the queue has answered a submit made after the renderer's pipelines, so the browser has + /// compiled them; the CPU paints on meanwhile. Then one frame is drawn by both from the same + /// instances, and nothing new until the GPU's is done (`done`): its canvas then shows over + /// the CPU's, which goes. + HandingOver { cpu: cpu_canvas::CpuCanvas, side: GpuSide, built: Rc<Cell<bool>>, done: Option<Rc<Cell<bool>>>, since: Instant }, + Gpu(GpuSide), + /// WebGL2 context lost on a GPU-first inline or document page that cannot overlay a CPU + /// canvas; redraws pause until `webglcontextrestored` rebuilds `GpuSide`. + ContextLost, + /// Only while one state is taken apart for the next: no frame sees it. + Moving, +} + +impl Draw { + pub(super) fn gpu(&self) -> Option<&GpuSide> { + match self { + Draw::HandingOver { side, .. } | Draw::Gpu(side) => Some(side), + Draw::Cpu { .. } | Draw::ContextLost | Draw::Moving => None, + } + } + + pub(super) fn gpu_mut(&mut self) -> Option<&mut GpuSide> { + match self { + Draw::HandingOver { side, .. } | Draw::Gpu(side) => Some(side), + Draw::Cpu { .. } | Draw::ContextLost | Draw::Moving => None, + } + } + + /// The GPU's hand-over frame is drawn and not finished: nothing new is drawn until it is. + pub(super) fn waiting_for_gpu(&self) -> bool { + matches!(self, Draw::HandingOver { done: Some(done), .. } if !done.get()) + } + + pub(super) fn kind(&self) -> super::web_math::WebDrawKind { + use super::web_math::WebDrawKind; + match self { + Draw::Cpu { .. } => WebDrawKind::Cpu, + Draw::HandingOver { .. } => WebDrawKind::HandingOver { waiting_for_gpu: self.waiting_for_gpu() }, + Draw::Gpu(_) => WebDrawKind::Gpu, + Draw::ContextLost => WebDrawKind::ContextLost, + Draw::Moving => WebDrawKind::Moving, + } + } +} + +/// Probes WebGPU for an adapter and device before touching `canvas`. +/// +/// Calling `canvas.getContext("webgpu")` permanently locks the canvas to WebGPU even if +/// `requestAdapter` or `requestDevice` then fails, blocking any WebGL2 fallback on the same +/// canvas. wgpu's WebGPU backend does not need a surface to request an adapter or device, so +/// the canvas surface is created only after both succeed. +async fn try_webgpu(canvas: &web_sys::HtmlCanvasElement, features: wgpu::Features) + -> Result<(Gpu, wgpu::Surface<'static>), String> { + let mut descriptor = wgpu::InstanceDescriptor::new_without_display_handle(); + descriptor.backends = wgpu::Backends::BROWSER_WEBGPU; + let instance = wgpu::Instance::new(descriptor); + let adapter = instance.request_adapter(&wgpu::RequestAdapterOptions { + power_preference: wgpu::PowerPreference::LowPower, compatible_surface: None, + force_fallback_adapter: false, apply_limit_buckets: false, + }).await.map_err(|e| e.to_string())?; + let required_limits = wgpu::Limits::default().using_resolution(adapter.limits()); + let (device, queue) = adapter.request_device(&wgpu::DeviceDescriptor { + label: Some("rune web"), required_features: adapter.features() & features, + required_limits, experimental_features: Default::default(), + memory_hints: Default::default(), trace: Default::default(), + }).await.map_err(|e| format!("GPU device: {e}"))?; + let surface = match instance.create_surface(wgpu::SurfaceTarget::Canvas(canvas.clone())) { + Ok(surface) => surface, + Err(e) => { + device.destroy(); + return Err(e.to_string()); + } + }; + Ok((Gpu::from_device(instance, adapter, device, queue), surface)) +} + +/// Creates a WebGL2 surface and device on `canvas`. Unlike WebGPU, `wgpu-hal`'s WebGL2 backend +/// discovers its adapter from the surface's `WebGL2RenderingContext`, so the surface comes first. +#[cfg(feature = "webgl")] +pub(super) async fn try_webgl2(canvas: &web_sys::HtmlCanvasElement, features: wgpu::Features) + -> Result<(Gpu, wgpu::Surface<'static>), String> { + let mut descriptor = wgpu::InstanceDescriptor::new_without_display_handle(); + descriptor.backends = wgpu::Backends::GL; + let instance = wgpu::Instance::new(descriptor); + let surface = instance.create_surface(wgpu::SurfaceTarget::Canvas(canvas.clone())).map_err(|e| e.to_string())?; + let adapter = instance.request_adapter(&wgpu::RequestAdapterOptions { + power_preference: wgpu::PowerPreference::LowPower, compatible_surface: Some(&surface), + force_fallback_adapter: false, apply_limit_buckets: false, + }).await.map_err(|e| e.to_string())?; + let adapter_limits = adapter.limits(); + let required_limits = wgpu::Limits::downlevel_webgl2_defaults() + .using_resolution(adapter_limits.clone()) + .using_alignment(adapter_limits); + let (device, queue) = adapter.request_device(&wgpu::DeviceDescriptor { + label: Some("rune web"), required_features: adapter.features() & features, + required_limits, experimental_features: Default::default(), + memory_hints: Default::default(), trace: Default::default(), + }).await.map_err(|e| format!("GPU device: {e}"))?; + Ok((Gpu::from_device(instance, adapter, device, queue), surface)) +} + +pub(super) async fn gpu(canvas: web_sys::HtmlCanvasElement, features: wgpu::Features) -> Result<(Gpu, wgpu::Surface<'static>), String> { + let mut webgpu_err = None; + for &backend in super::web_math::backend_order(health::has_navigator_gpu(), cfg!(feature = "webgl")) { + match backend { + super::web_math::WebBackend::WebGpu => match try_webgpu(&canvas, features).await { + Ok(pair) => return Ok(pair), + Err(err) => webgpu_err = Some(err), + }, + super::web_math::WebBackend::WebGl2 => { + #[cfg(feature = "webgl")] + match try_webgl2(&canvas, features).await { + Ok(pair) => return Ok(pair), + Err(gl_err) => { + let webgpu = webgpu_err.as_deref().unwrap_or("navigator.gpu unavailable"); + return Err(format!("WebGPU ({webgpu}) and WebGL2 ({gl_err}) unavailable")); + } + } + } + } + } + let why = webgpu_err.unwrap_or_else(|| "navigator.gpu unavailable".into()); + Err(format!("WebGPU adapter unavailable (HTTPS and WebGPU are required): {why}")) +} + +/// The GPU's side for a canvas of `size`: the surface configured, the renderer made, and the +/// text system told its masks are the renderer's to fill from now on. `lost` records the reason +/// and wakes `proxy` if the device is lost. +pub(super) fn gpu_side(gpu: Gpu, surface: wgpu::Surface<'static>, size: (u32, u32), rt: &mut RuntimeCore, lost: Rc<RefCell<Option<Loss>>>, proxy: EventLoopProxy<Wake>) -> Result<GpuSide, String> { + let Some((config, format)) = canvas_config(&gpu, &surface, size, rt.srgb_blend()) else { + return Err("WebGPU canvas has no supported configuration".into()); + }; + let backend = gpu.adapter.get_info().backend; + let is_gl = backend == wgpu::Backend::Gl; + surface.configure(&gpu.device, &config); + health::watch(&gpu.device, move |why| { + *lost.borrow_mut() = Some(if is_gl { Loss::WebGl(why) } else { Loss::WebGpu(why) }); + proxy.send_event(Wake::App).ok(); + }); + let mut renderer = Renderer::new(&gpu.device, format); + renderer.set_srgb_blend(!format.is_srgb()); + renderer.attach_text(&mut rt.text.atlas); + // Re-upload every placed glyph row and outline record on a fresh renderer (for example after + // a WebGL2 context restore, where a previous renderer had already cleared `atlas.dirty`). + rt.text.atlas.invalidate(); + Ok(GpuSide { gpu, surface, config, renderer, backend }) +} + +/// The canvas's configuration for `size`, and the format the renderer draws in: the canvas's, +/// or its sRGB twin directly (when supported, as on WebGL2) or as a view format (on WebGPU) for +/// the blend `srgb_blend` asks. +pub(super) fn canvas_config(gpu: &Gpu, surface: &wgpu::Surface<'static>, size: (u32, u32), srgb_blend: bool) -> Option<(wgpu::SurfaceConfiguration, wgpu::TextureFormat)> { + let max_dim = gpu.device.limits().max_texture_dimension_2d.max(1); + let mut config = surface.get_default_config(&gpu.adapter, size.0.clamp(1, max_dim), size.1.clamp(1, max_dim))?; + config.present_mode = wgpu::PresentMode::Fifo; + let caps = surface.get_capabilities(&gpu.adapter); + let backend = gpu.adapter.get_info().backend; + config.usage = super::web_math::surface_usage(caps.usages, backend, drift_wanted()); + let chosen = super::web_math::select_surface_formats(config.format, &caps.formats, backend, srgb_blend); + config.format = chosen.surface; + if let Some(view) = chosen.view_format { + config.view_formats.push(view); + } + Some((config, chosen.render)) +} + +/// Reconfigures the canvas surface and rebuilds the renderer when `rt.srgb_blend()` differs from +/// the renderer's current blend mode. +pub(super) fn reblend(side: &mut GpuSide, rt: &mut RuntimeCore) { + if side.renderer.srgb_blend() == rt.srgb_blend() { return; } + let caps = side.surface.get_capabilities(&side.gpu.adapter); + let backend = side.gpu.adapter.get_info().backend; + let chosen = super::web_math::select_surface_formats(side.config.format, &caps.formats, backend, rt.srgb_blend()); + let mut reconfigure = side.config.format != chosen.surface; + side.config.format = chosen.surface; + if let Some(view) = chosen.view_format { + if !side.config.view_formats.contains(&view) { + side.config.view_formats.push(view); + reconfigure = true; + } + } else if !side.config.view_formats.is_empty() { + side.config.view_formats.clear(); + reconfigure = true; + } + if reconfigure { + side.surface.configure(&side.gpu.device, &side.config); + } + if side.renderer.format() != chosen.render { + crate::window::rebuild_renderer_core(&side.gpu.device, &mut side.renderer, chosen.render, rt); + } + side.renderer.set_srgb_blend(chosen.srgb_blend()); +} + +/// Acquires the next canvas texture, reconfiguring and retrying once on `Outdated`/`Lost`. +pub(super) fn acquire_texture(side: &mut GpuSide) -> Result<wgpu::SurfaceTexture, crate::window::Missed> { + use super::web_math::{WebAcquireAction, WebAcquireStatus, web_acquire_action}; + let mut retries = 1u8; + loop { + let (frame, status) = match side.surface.get_current_texture() { + wgpu::CurrentSurfaceTexture::Success(frame) | wgpu::CurrentSurfaceTexture::Suboptimal(frame) => { + (Some(frame), WebAcquireStatus::Ready) + } + wgpu::CurrentSurfaceTexture::Timeout => (None, WebAcquireStatus::Timeout), + wgpu::CurrentSurfaceTexture::Occluded => (None, WebAcquireStatus::Occluded), + wgpu::CurrentSurfaceTexture::Outdated | wgpu::CurrentSurfaceTexture::Lost => { + (None, WebAcquireStatus::OutdatedOrLost) + } + wgpu::CurrentSurfaceTexture::Validation => (None, WebAcquireStatus::Validation), + }; + match web_acquire_action(status, retries) { + WebAcquireAction::UseTexture => return Ok(frame.expect("ready acquisition carries texture")), + WebAcquireAction::ReconfigureAndRetry => { + side.surface.configure(&side.gpu.device, &side.config); + retries -= 1; + } + WebAcquireAction::Miss(missed) => return Err(missed), + } + } +} + +/// GPU frame resources prepared before encoding and submission. +pub(super) struct PreparedGpu { + frame: wgpu::SurfaceTexture, + encoder: wgpu::CommandEncoder, + size: (u32, u32), + armed: bool, + readback: bool, + copy: Option<Readback>, +} + +/// Uploads dirty images, registers the renderer's frame wake, arms a cycle-only frame when `tick` +/// applies, and opens the command encoder. +pub(super) fn prepare_gpu_frame( + side: &mut GpuSide, + rt: &mut RuntimeCore, + frame: wgpu::SurfaceTexture, + readback: bool, + tick: bool, +) -> PreparedGpu { + let size = (side.config.width, side.config.height); + side.renderer.upload_images(&side.gpu.device, &side.gpu.queue, &mut rt.images); + side.renderer.set_frame_wake(rt.live_wake()); + // A loop-only step (`runtime/paint/cycle.rs`) writes only the dots it changed, and redraws + // only where they are, into the last frame the renderer keeps, which is copied to the canvas. + let (paint, slots) = rt.cycle_paint(); + let armed = tick && side.config.usage.contains(wgpu::TextureUsages::COPY_DST) + && side.renderer.arm_cycle(&side.gpu.device, &side.gpu.queue, paint, &rt.instances, &slots, rt.clear_color(), size, side.config.format).is_ok(); + side.renderer.next_instances(paint, tick.then_some(slots)); + let encoder = side.gpu.device.create_command_encoder(&Default::default()); + PreparedGpu { frame, encoder, size, armed, readback, copy: None } +} + +/// Encodes the UI or custom compositor pass (plus optional hand-over drift readback copy) into +/// `prepared.encoder`. Returns `true` when a custom compositor reported it is still animating. +pub(super) fn encode_gpu_frame( + side: &mut GpuSide, + app: &mut dyn WebApp, + prepared: &mut PreparedGpu, + dt: f64, + update_ms: f64, +) -> bool { + let comp_animating = if prepared.armed { + // Rune's default frame (a compositor that drew its own would have kept this a whole one): + // nothing draws into the canvas but the copy of the kept frame. + let rt = app.rt_mut(); + side.renderer.set_fade_stops(rt.fade_stops()); + side.renderer.prepare_ui(&side.gpu.device, &side.gpu.queue, &mut rt.text.atlas, &rt.instances, prepared.size); + side.renderer.draw_armed(&mut prepared.encoder, &prepared.frame.texture); + false + } else if app.has_compositor() { + let target = prepared.frame.texture.create_view(&wgpu::TextureViewDescriptor { format: Some(side.renderer.format()), ..Default::default() }); + app.render_compositor(CompositorFrame { + device: &side.gpu.device, + queue: &side.gpu.queue, + encoder: &mut prepared.encoder, + target: &target, + format: side.renderer.format(), + size: prepared.size, + dt, + update_ms, + ui: &mut side.renderer, + }) + } else { + let target = prepared.frame.texture.create_view(&wgpu::TextureViewDescriptor { format: Some(side.renderer.format()), ..Default::default() }); + let rt = app.rt_mut(); + let clear = rt.clear_color(); + crate::frame::host_step::draw_ui(&mut side.renderer, &side.gpu, &mut prepared.encoder, &target, rt, prepared.size, clear); + false + }; + // A copy of the frame for counting how many of its pixels the CPU's differ in (drift). + if prepared.readback && side.config.usage.contains(wgpu::TextureUsages::COPY_SRC) { + let (width, height) = (side.config.width, side.config.height); + let row = (width * 4).div_ceil(wgpu::COPY_BYTES_PER_ROW_ALIGNMENT) * wgpu::COPY_BYTES_PER_ROW_ALIGNMENT; + let buffer = side.gpu.device.create_buffer(&wgpu::BufferDescriptor { + label: Some("rune hand-over readback"), + size: u64::from(row) * u64::from(height), + usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ, + mapped_at_creation: false, + }); + prepared.encoder.copy_texture_to_buffer( + prepared.frame.texture.as_image_copy(), + wgpu::TexelCopyBufferInfo { + buffer: &buffer, + layout: wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(row), rows_per_image: Some(height) }, + }, + wgpu::Extent3d { width, height, depth_or_array_layers: 1 }, + ); + let poll_device = super::web_math::needs_device_poll(side.backend).then(|| side.gpu.device.clone()); + prepared.copy = Some(Readback { + buffer, + row, + size: (width, height), + rgba: matches!(side.config.format, wgpu::TextureFormat::Rgba8Unorm | wgpu::TextureFormat::Rgba8UnormSrgb), + poll_device, + }); + } + // Every frame: one drawn whole leaves the kept frame behind. + side.renderer.damage_drawn().ok(); + comp_animating +} + +/// Submits the encoded GPU commands, runs `before_present` (e.g. `pre_present_notify`), and +/// presents the canvas texture. +pub(super) fn submit_gpu_frame( + side: &mut GpuSide, + prepared: PreparedGpu, + before_present: impl FnOnce(), +) -> Option<Readback> { + side.renderer.submit(&side.gpu.queue, prepared.encoder); + before_present(); + side.gpu.queue.present(prepared.frame); + prepared.copy +} + +/// The GPU's hand-over frame, copied where the CPU can read it. +pub(super) struct Readback { + buffer: wgpu::Buffer, + row: u32, + size: (u32, u32), + /// The canvas's format is RGBA (the CPU paints BGRA). + rgba: bool, + /// Present only on backends whose `map_async` needs explicit `Device::poll` (WebGL2). + poll_device: Option<wgpu::Device>, +} + +impl Readback { + /// Counts the pixels of `cpu` (BGRA, `size.0 * 4` bytes a row) this frame drew otherwise, and + /// appends `[differing, of, max]` to `globalThis.__runeDrift` once the copy is mapped. + pub(super) fn count(self, cpu: Vec<u8>) { + let Readback { buffer, row, size: (w, h), rgba, poll_device } = self; + let buffer = Rc::new(buffer); + let mapped = buffer.clone(); + let done = Rc::new(Cell::new(false)); + let mark_done = done.clone(); + buffer.slice(..).map_async(wgpu::MapMode::Read, move |result| { + mark_done.set(true); + if result.is_err() { return; } + let (mut differing, mut max) = (0u32, 0u8); + let mut bbox = [u32::MAX, u32::MAX, 0u32, 0u32]; + let mut worst = [0u32; 8]; + { + let Ok(gpu) = mapped.slice(..).get_mapped_range() else { return }; + for y in 0..h as usize { + let g = &gpu[y * row as usize..y * row as usize + w as usize * 4]; + let c = &cpu[y * w as usize * 4..(y + 1) * w as usize * 4]; + for (x, (p, q)) in c.chunks_exact(4).zip(g.chunks_exact(4)).enumerate() { + let q = if rgba { [q[2], q[1], q[0]] } else { [q[0], q[1], q[2]] }; + let d = p[..3].iter().zip(&q).map(|(x, y)| x.abs_diff(*y)).max().unwrap_or(0); + if d > 1 { + let (x, y) = (x as u32, y as u32); + bbox = [bbox[0].min(x), bbox[1].min(y), bbox[2].max(x + 1), bbox[3].max(y + 1)]; + } + if d > max { worst = [x as u32, y as u32, u32::from(p[2]), u32::from(p[1]), u32::from(p[0]), u32::from(q[2]), u32::from(q[1]), u32::from(q[0])]; } + if d > 0 { differing += 1; max = max.max(d); } + } + } + } + mapped.unmap(); + let Ok(list) = js_sys::Reflect::get(&js_sys::global(), &"__runeDrift".into()) else { return }; + if !js_sys::Array::is_array(&list) { return; } + let list: js_sys::Array = list.unchecked_into(); + let row = js_sys::Array::of3(&differing.into(), &(w * h).into(), &max.into()); + for v in bbox.into_iter().chain(worst) { row.push(&v.into()); } + list.push(&row); + }); + if let Some(device) = poll_device { + poll_until_done(device, &done, Instant::now() + FINISH_LIMIT); + } + } +} + +/// Whether the page asked for the hand-over's drift (`globalThis.__runeDrift`, an array). +pub(super) fn drift_wanted() -> bool { + js_sys::Reflect::get(&js_sys::global(), &"__runeDrift".into()).is_ok_and(|v| js_sys::Array::is_array(&v)) +} + +/// A flag the GPU's queue sets once the work submitted so far is done, waking the loop. +/// On WebGL2 (`wgpu-core`), schedules lightweight non-blocking `Device::poll` ticks until the +/// callback fires or `FINISH_LIMIT` passes; on WebGPU the browser resolves it from its task queue. +pub(super) fn when_done(side: &GpuSide, proxy: &EventLoopProxy<Wake>) -> Rc<Cell<bool>> { + let flag = Rc::new(Cell::new(false)); + let set = PageOnly((flag.clone(), proxy.clone())); + side.gpu.queue.on_submitted_work_done(move || { + let PageOnly((flag, proxy)) = &set; + flag.set(true); + proxy.send_event(Wake::App).ok(); + }); + if super::web_math::needs_device_poll(side.backend) { + poll_until_done(side.gpu.device.clone(), &flag, Instant::now() + FINISH_LIMIT); + } + flag +} + +/// Interval between WebGL2 `Device::poll` checks while an async wgpu callback is pending. +const POLL_INTERVAL: Duration = Duration::from_millis(8); + +/// Drives `wgpu-core` callbacks on WebGL2 after yielding to the browser event loop (WebGL2 sync +/// objects only transition to `SIGNALED` across turns). Stops as soon as `flag` flips, is dropped, +/// the device reports an error, or `deadline` passes. +fn poll_until_done(device: wgpu::Device, flag: &Rc<Cell<bool>>, deadline: Instant) { + fn step(device: wgpu::Device, weak: std::rc::Weak<Cell<bool>>, deadline: Instant) { + let Some(flag) = weak.upgrade() else { return }; + if flag.get() || Instant::now() >= deadline { return; } + if device.poll(wgpu::PollType::Poll).is_err() || flag.get() { return; } + super::after(POLL_INTERVAL, move || step(device, weak, deadline)); + } + let weak = Rc::downgrade(flag); + super::after(Duration::ZERO, move || step(device, weak, deadline)); +} + +/// A value moved into a callback wgpu wants `Send`. In a page that callback runs on the page's +/// one thread, from a promise. +struct PageOnly<T>(T); +// SAFETY: wasm32 without threads: there is one thread, and every callback runs on it. +#[allow(unsafe_code)] +unsafe impl<T> Send for PageOnly<T> {} + +/// How long the GPU's hand-over frame may take to finish before the page stays on the CPU. +pub(super) const FINISH_LIMIT: Duration = Duration::from_secs(5); diff --git a/app/vendor/rune/crates/rune/src/platform/web/handover.rs b/app/vendor/rune/crates/rune/src/platform/web/handover.rs new file mode 100644 index 0000000..e5d24da --- /dev/null +++ b/app/vendor/rune/crates/rune/src/platform/web/handover.rs @@ -0,0 +1,280 @@ +//! CPU-first GPU acquisition, hand-over from the CPU canvas to WebGPU/WebGL2, and device/context +//! loss and restore recovery. + +use std::time::Duration; +use winit::{event_loop::ActiveEventLoop, platform::web::WindowExtWebSys}; +use crate::time::Instant; +use super::{ + Browser, Start, Wake, after, cpu_canvas, error, + gpu::{self, Draw, FINISH_LIMIT, Loss}, + health, pipelines, web_math, +}; + +/// How long a page that starts on the CPU draws nothing before it asks for the GPU, and the +/// longest after its first frame that it waits for that. +pub(super) const QUIET: Duration = Duration::from_millis(250); +const QUIET_LIMIT: Duration = Duration::from_secs(3); + +impl Browser { + /// Installs `webglcontextlost` / `webglcontextrestored` listeners on the page's canvas once + /// WebGL2 has attached to it. Lives on `Browser` so restore events still arrive after a lost + /// `GpuSide` has been dropped. + pub(super) fn ensure_webgl_watch(&mut self) { + if self.webgl_watch.is_some() { return; } + let Some(canvas) = self.window.as_ref().and_then(|w| w.canvas()) else { return }; + let (lost, restored_lost, restored_ok, proxy_lost, proxy_restored) = ( + self.lost.clone(), + self.webgl_restored.clone(), + self.webgl_restored.clone(), + self.proxy.clone(), + self.proxy.clone(), + ); + self.webgl_watch = Some(health::WebglWatch::new( + &canvas, + move |why| { + restored_lost.set(false); + *lost.borrow_mut() = Some(Loss::WebGl(why)); + proxy_lost.send_event(Wake::App).ok(); + }, + move || { + restored_ok.set(true); + proxy_restored.send_event(Wake::App).ok(); + }, + )); + } + + /// The browser lost the GPU device or WebGL2 context. WebGPU loss keeps the existing policy + /// (CPU fallback on CPU-first pages, fatal on GPU-first pages). WebGL2 context loss falls back + /// to the CPU canvas on full-window pages or pauses inline/document pages without exiting, so + /// a later `webglcontextrestored` brings WebGL2 back. True when the app ended. + pub(super) fn lost_device(&mut self, event_loop: &ActiveEventLoop) -> bool { + let mut loss = self.lost.borrow_mut().take(); + if loss.is_none() + && self.webgl_watch.as_ref().is_some_and(health::WebglWatch::is_lost) + && self.running.borrow().as_ref().is_some_and(|r| r.draw.gpu().is_some_and(|s| s.backend == wgpu::Backend::Gl)) + { + loss = Some(Loss::WebGl("WebGL2 context lost".into())); + } + let Some(loss) = loss else { return false }; + let Some(window) = self.window.clone() else { return false }; + let canvas = window.canvas(); + let why = loss.reason(); + match web_math::loss_action(loss.is_webgl(), self.start == Start::GpuFirst, self.embedded, self.document) { + web_math::LossAction::Fatal => { + error(&format!("The GPU device was lost ({why}). Reload the page to draw again."), canvas.as_ref(), self.embedded, self.document); + self.end(event_loop); + return true; + } + web_math::LossAction::PauseForRestore => { + let mut running = self.running.borrow_mut(); + let Some(r) = &mut *running else { return false }; + let side = match std::mem::replace(&mut r.draw, Draw::Moving) { + Draw::Gpu(side) => { r.draw = Draw::ContextLost; side } + other => { r.draw = other; return false; } + }; + self.webgl_restoring = false; + web_sys::console::warn_1(&format!("rune: the WebGL2 context was lost ({why}); waiting for restore").into()); + crate::marks::mark("web.gpu.lost"); + side.gpu.device.destroy(); + drop(side); + return false; + } + web_math::LossAction::FallbackToCpu { .. } => {} + } + let mut running = self.running.borrow_mut(); + let Some(r) = &mut *running else { return false }; + let side = match std::mem::replace(&mut r.draw, Draw::Moving) { + Draw::Gpu(side) => match canvas.as_ref().and_then(cpu_canvas::CpuCanvas::under) { + Some(cpu) => { r.draw = Draw::Cpu { cpu, failed: true }; side } + None => { + r.draw = Draw::Gpu(side); + drop(running); + error(&format!("The GPU device was lost ({why}). Reload the page to draw again."), canvas.as_ref(), self.embedded, self.document); + self.end(event_loop); + return true; + } + }, + // Mid hand-over: the CPU's canvas is still up, and stays. + Draw::HandingOver { cpu, side, .. } => { r.draw = Draw::Cpu { cpu, failed: true }; side } + other => { r.draw = other; return false; } + }; + self.webgl_restoring = false; + web_sys::console::warn_1(&format!("rune: the GPU device was lost ({why}); the page draws on the CPU").into()); + crate::marks::mark("web.gpu.lost"); + side.gpu.device.destroy(); + drop(side); + let atlas = &mut r.app.rt_mut().text.atlas; + crate::render::cpu_boot::attach_text(atlas); + atlas.refill_gpu_masks(); + if let Some(c) = &canvas { c.style().set_property("opacity", "0").ok(); } + window.request_redraw(); + false + } + + /// Rebuilds the WebGL2 `GpuSide` after `webglcontextrestored` fires on the canvas. + pub(super) fn maybe_restore_webgl(&mut self) { + if !self.webgl_restored.get() || self.webgl_restoring { return; } + if self.webgl_watch.as_ref().is_some_and(health::WebglWatch::is_lost) { return; } + let features = { + let running = self.running.borrow(); + let Some(r) = &*running else { return }; + if !matches!(r.draw, Draw::Cpu { failed: true, .. } | Draw::ContextLost) { + self.webgl_restored.set(false); + return; + } + r.app.compositor_features() + }; + let Some(canvas) = self.window.as_ref().and_then(|w| w.canvas()) else { return }; + self.webgl_restored.set(false); + #[cfg(feature = "webgl")] + { + self.webgl_restoring = true; + let (pending, proxy) = (self.pending.clone(), self.proxy.clone()); + wasm_bindgen_futures::spawn_local(async move { + let result = gpu::try_webgl2(&canvas, features).await; + if proxy.send_event(Wake::Ready).is_err() { + if let Ok((gpu, _)) = result { gpu.device.destroy(); } + return; + } + *pending.borrow_mut() = Some(result); + }); + } + #[cfg(not(feature = "webgl"))] + let _ = (canvas, features); + } + + /// The GPU answered while the page draws on the CPU (initial CPU-first hand-over) or after + /// `webglcontextrestored`: its side is made and either handed over from the CPU canvas or + /// installed directly for inline/document pages waiting in `Draw::ContextLost`. + pub(super) fn gpu_came(&mut self) { + let watch_webgl = { + let mut running = self.running.borrow_mut(); + let Some(r) = &mut *running else { return }; + let can_take = r.presented && ( + (self.start == Start::CpuFirst && matches!(r.draw, Draw::Cpu { failed: false, .. })) + || (self.webgl_restoring && matches!(r.draw, Draw::Cpu { .. } | Draw::ContextLost)) + ); + if !can_take { return; } + let Some(made) = self.pending.borrow_mut().take() else { return }; + let restoring = std::mem::take(&mut self.webgl_restoring); + let side = made.and_then(|(gpu, surface)| { + gpu::gpu_side(gpu, surface, r.size, r.app.rt_mut(), self.lost.clone(), self.proxy.clone()) + }); + // The renderer is made: the pipelines compiled ahead for it can go. + self.warmed.borrow_mut().take(); + let side = match side { + Ok(side) => side, + Err(why) => { + web_sys::console::warn_1(&format!("rune: the page draws on the CPU ({why})").into()); + crate::marks::mark("web.gpu.failed"); + if let Draw::Cpu { failed, .. } = &mut r.draw { *failed = true; } + return; + } + }; + let is_gl = side.backend == wgpu::Backend::Gl; + if matches!(r.draw, Draw::ContextLost) { + r.draw = Draw::Gpu(side); + r.app.rt_mut().invalidate(); + crate::marks::mark("web.gpu.restored"); + if let Some(window) = &self.window { window.request_redraw(); } + } else { + // The browser compiles the renderer's pipelines in its GPU process, in order: a submit + // made after them is answered once they're built. + side.gpu.queue.submit([]); + let built = gpu::when_done(&side, &self.proxy); + let Draw::Cpu { mut cpu, .. } = std::mem::replace(&mut r.draw, Draw::Moving) else { unreachable!("checked above") }; + cpu.half = crate::render::cpu_boot::HalfRounding::of_vendor(side.gpu.adapter.get_info().vendor); + r.draw = Draw::HandingOver { cpu, side, built, done: None, since: Instant::now() }; + if restoring { crate::marks::mark("web.gpu.restored"); } + crate::marks::mark("web.gpu.ready"); + } + is_gl + }; + if watch_webgl { self.ensure_webgl_watch(); } + } + + /// While handing over: once the GPU's frame is done, its canvas shows and the CPU's goes, in + /// one turn, so the next composition has the GPU's frame where the CPU's was. A frame that + /// doesn't finish in `FINISH_LIMIT` leaves the page on the CPU. + pub(super) fn hand_over_if_done(&mut self) { + let mut running = self.running.borrow_mut(); + let Some(r) = &mut *running else { return }; + let Draw::HandingOver { done: Some(done), since, .. } = &r.draw else { return }; + let (finished, late) = (done.get(), since.elapsed() > FINISH_LIMIT); + if !finished && !late { return; } + let Draw::HandingOver { cpu, side, .. } = std::mem::replace(&mut r.draw, Draw::Moving) else { unreachable!("checked above") }; + let canvas = self.window.as_ref().and_then(|w| w.canvas()); + if !finished { + web_sys::console::warn_1(&"rune: the GPU didn't finish its first frame; the page draws on the CPU".into()); + crate::marks::mark("web.handover.failed"); + side.gpu.device.destroy(); + let atlas = &mut r.app.rt_mut().text.atlas; + crate::render::cpu_boot::attach_text(atlas); + atlas.refill_gpu_masks(); + r.draw = Draw::Cpu { cpu, failed: true }; + return; + } + if let Some(c) = &canvas { c.style().remove_property("opacity").ok(); } + cpu.remove(); + // A harness checking the way back to the CPU (`globalThis.RUNE_LOSE_GPU_AFTER`, in ms) + // has the device count as lost that long after the hand-over, as the browser reports it. + if let Some(ms) = js_sys::Reflect::get(&js_sys::global(), &"RUNE_LOSE_GPU_AFTER".into()).ok().and_then(|v| v.as_f64()) { + let (lost, proxy) = (self.lost.clone(), self.proxy.clone()); + after(Duration::from_millis(ms as u64), move || { + *lost.borrow_mut() = Some(Loss::WebGpu("RUNE_LOSE_GPU_AFTER".into())); + proxy.send_event(Wake::App).ok(); + }); + } + r.draw = Draw::Gpu(side); + crate::marks::mark("web.handover.done"); + if let Some(window) = &self.window { window.request_redraw(); } + } + + /// Asks the browser for the GPU, once. + pub(super) fn ask_gpu(&mut self) { + if self.gpu_asked || self.start == Start::CpuOnly { return; } + let Some(canvas) = self.window.as_ref().and_then(|w| w.canvas()) else { return }; + self.gpu_asked = true; + crate::marks::mark("web.gpu.asked"); + // A page that started on the CPU asks after its first frame, when the running app holds the compositor. + let features = match &self.app { + Some(app) => app.compositor_features, + None => self.running.borrow().as_ref().map_or(wgpu::Features::empty(), |r| r.app.compositor_features()), + }; + // The renderer's pipelines are compiled ahead for the running app's canvas and blend, so + // making its renderer at the hand-over finds them built (`pipelines::warm`). + let canvas_now = self.running.borrow().as_ref().map(|r| (r.size, r.app.rt().srgb_blend())); + let (pending, warmed, proxy) = (self.pending.clone(), self.warmed.clone(), self.proxy.clone()); + wasm_bindgen_futures::spawn_local(async move { + let result = gpu::gpu(canvas, features).await; + crate::marks::mark("web.gpu.answered"); + let format = result.as_ref().ok().zip(canvas_now).and_then(|((gpu, surface), (size, srgb))| gpu::canvas_config(gpu, surface, size, srgb)).map(|(_, format)| format); + if let (Ok((gpu, _)), Some(format)) = (&result, format) && let Some(w) = pipelines::warm(&gpu.device, format).await { + crate::marks::mark("web.gpu.warmed"); + *warmed.borrow_mut() = Some(w); + } + // A loop that has closed was quit while the GPU started. + if proxy.send_event(Wake::Ready).is_err() { + warmed.borrow_mut().take(); + if let Ok((gpu, _)) = result { gpu.device.destroy(); } + return; + } + *pending.borrow_mut() = Some(result); + }); + } + + /// After the first frame of a page that starts on the CPU: the GPU is asked for once the page + /// has drawn nothing but ambient loops for `QUIET` (its first reads in and shown; a spinner on + /// screen would otherwise hold the page on the CPU, painting each of its steps there), or `QUIET_LIMIT` after that + /// frame at the latest; until then this looks again every `QUIET`. A browser that compiles + /// pipelines asynchronously is asked at the first look: its pipelines build off the thread + /// that presents the CPU's frames (`pipelines::warm`), so nothing waits for quiet. + pub(super) fn maybe_start_gpu(&mut self) { + if self.gpu_asked || self.start != Start::CpuFirst { return; } + let Some(first) = self.first_at else { return }; + let quiet = self.drawn_at.is_none_or(|at| at.elapsed() >= QUIET); + if quiet || first.elapsed() >= QUIET_LIMIT || pipelines::browser_compiles_async() { return self.ask_gpu(); } + let proxy = self.proxy.clone(); + after(QUIET, move || { proxy.send_event(Wake::StartGpu).ok(); }); + } +} diff --git a/app/vendor/rune/crates/rune/src/platform/web/health.js b/app/vendor/rune/crates/rune/src/platform/web/health.js new file mode 100644 index 0000000..3c52a54 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/platform/web/health.js @@ -0,0 +1,84 @@ +// A WebGPU device's errors and loss, read from the JS device itself. wgpu's own handlers turn a +// GPUInternalError into a panic (an `unreachable` trap that ends the app), so Rune never asks +// wgpu for them on the web. + +// Whether `navigator.gpu` is exposed on this page (false on insecure origins or when WebGPU is +// disabled by flag, even when `canvas.getContext('webgpu')` still returns a context). +export function hasNavigatorGpu() { + return typeof globalThis.navigator?.gpu === 'object' && globalThis.navigator.gpu !== null; +} + +// The adapter a device runs on, as far as the browser says: vendor, architecture, device and +// description (each may be empty), whether it is a fallback adapter, and its texture limit. +export function gpuSummary(device) { + const info = device.adapterInfo ?? {}; + const parts = [info.vendor, info.architecture, info.device, info.description].filter(Boolean); + if (info.isFallbackAdapter) parts.push('fallback adapter'); + parts.push(`max texture ${device.limits.maxTextureDimension2D}`); + return parts.join(', '); +} + +// Calls `onError(kind, message)` for each uncaptured error and keeps it out of the browser's own +// log (`onError` logs what's worth logging), and `onLost(reason, message)` once if the device is +// lost for any reason but being destroyed. +export function watchGpu(device, onError, onLost) { + device.addEventListener('uncapturederror', (event) => { + event.preventDefault(); + onError(event.error?.constructor?.name ?? 'GPUError', event.error?.message ?? ''); + }); + device.lost.then((info) => { + if (info.reason !== 'destroyed') onLost(info.reason ?? 'unknown', info.message ?? ''); + }); +} + +export function pushScopes(device) { + device.pushErrorScope('validation'); + device.pushErrorScope('out-of-memory'); + device.pushErrorScope('internal'); +} + +// Pops `pushScopes`'s scopes now, and resolves to the first error they caught as `kind: +// message`, or null. +export function popScopes(device) { + const caught = [device.popErrorScope(), device.popErrorScope(), device.popErrorScope()]; + return Promise.all(caught).then((errors) => { + const error = errors.find(Boolean); + return error ? `${error.constructor?.name ?? 'GPUError'}: ${error.message}` : null; + }); +} + +// Watches `canvas` for WebGL2 context loss and restore. Calls `event.preventDefault()` on loss +// so the browser can restore the context, and caches the existing context handle once so +// `webglWatchLost` checks `isContextLost()` without calling `getContext` on every frame. +export function watchWebglContext(canvas, onLost, onRestored) { + let gl = canvas.getContext('webgl2'); + let lost = !gl || gl.isContextLost(); + const handleLost = (event) => { + event.preventDefault(); + lost = true; + const detail = event.statusMessage ? `: ${event.statusMessage}` : ''; + onLost(`WebGL2 context lost${detail}`); + }; + const handleRestored = () => { + lost = false; + gl = canvas.getContext('webgl2'); + onRestored(); + }; + canvas.addEventListener('webglcontextlost', handleLost); + canvas.addEventListener('webglcontextrestored', handleRestored); + return { + isLost() { return lost || !gl || gl.isContextLost(); }, + dispose() { + canvas.removeEventListener('webglcontextlost', handleLost); + canvas.removeEventListener('webglcontextrestored', handleRestored); + }, + }; +} + +export function webglWatchLost(handle) { + return !!handle?.isLost?.(); +} + +export function disposeWebglWatch(handle) { + handle?.dispose?.(); +} diff --git a/app/vendor/rune/crates/rune/src/platform/web/health.rs b/app/vendor/rune/crates/rune/src/platform/web/health.rs new file mode 100644 index 0000000..b3b813a --- /dev/null +++ b/app/vendor/rune/crates/rune/src/platform/web/health.rs @@ -0,0 +1,158 @@ +//! The page's watch on its GPU device (health.js and WebGL2 `wgpu-core` / DOM context events): +//! uncaptured errors logged as `gpu::health::ErrorLog` says, with the adapter they happened on, +//! and the device's or WebGL2 context's loss and restore. The error scopes the renderer checks +//! its lazily built pipelines in (`render::breaker`) are the JS device's on WebGPU (avoiding +//! wgpu's panic on a `GPUInternalError`) and `wgpu-core`'s synchronous scopes on WebGL2. + +use std::{cell::RefCell, sync::{Arc, Mutex}}; +use wasm_bindgen::{JsCast, prelude::*}; +use crate::gpu::health::{ErrorLog, Note}; + +#[wasm_bindgen(module = "/src/platform/web/health.js")] +extern "C" { + #[wasm_bindgen(js_name = hasNavigatorGpu)] + fn has_navigator_gpu_js() -> bool; + #[wasm_bindgen(js_name = gpuSummary)] + fn gpu_summary(device: &JsValue) -> String; + #[wasm_bindgen(js_name = watchGpu)] + fn watch_gpu(device: &JsValue, on_error: &js_sys::Function, on_lost: &js_sys::Function); + #[wasm_bindgen(js_name = pushScopes)] + fn push_scopes(device: &JsValue); + /// Resolves to the first error the scopes caught, as `kind: message`, or null. + #[wasm_bindgen(js_name = popScopes)] + fn pop_scopes(device: &JsValue) -> js_sys::Promise; + #[wasm_bindgen(js_name = watchWebglContext)] + fn watch_webgl_context(canvas: &web_sys::HtmlCanvasElement, on_lost: &js_sys::Function, on_restored: &js_sys::Function) -> JsValue; + #[wasm_bindgen(js_name = webglWatchLost)] + fn webgl_watch_lost(handle: &JsValue) -> bool; + #[wasm_bindgen(js_name = disposeWebglWatch)] + fn dispose_webgl_watch(handle: &JsValue); +} + +/// Whether `navigator.gpu` is exposed on this page. +pub(super) fn has_navigator_gpu() -> bool { + has_navigator_gpu_js() +} + +/// The JS `GPUDevice` under `device`; none on WebGL2. +fn js_device(device: &wgpu::Device) -> Option<&JsValue> { + device.as_webgpu().map(|d| d.as_ref()) +} + +/// The adapter under `device`, as the browser describes it. +pub(crate) fn summary(device: &wgpu::Device) -> String { + js_device(device).map_or_else(|| "WebGL2".into(), gpu_summary) +} + +/// Validation, out-of-memory and internal error scopes on the JS device. +pub(crate) struct Scopes<'d>(&'d JsValue); + +impl<'d> Scopes<'d> { + /// None on WebGL2, which uses `wgpu-core` scopes instead of a JS `GPUDevice`. + pub(crate) fn push(device: &'d wgpu::Device) -> Option<Self> { + let js = js_device(device)?; + push_scopes(js); + Some(Self(js)) + } + + /// Pops the scopes now, and calls `answer` with what they caught when the browser says. + pub(crate) fn pop(self, answer: impl FnOnce(Option<String>) + 'static) { + let caught = wasm_bindgen_futures::JsFuture::from(pop_scopes(self.0)); + wasm_bindgen_futures::spawn_local(async move { + let error = match caught.await { + Ok(value) => value.as_string(), + Err(e) => Some(format!("{e:?}")), + }; + answer(error); + }); + } +} + +fn log_error_line(log: &mut ErrorLog, adapter: &str, kind: &str, message: &str) { + let line = match log.note(message) { + Note::First => format!("rune: GPU error on {adapter}: {kind}: {message}"), + Note::New => format!("rune: GPU error: {kind}: {message}"), + Note::Mute => format!("rune: GPU error: {kind}: {message}\n(further GPU errors on this device aren't logged)"), + Note::Quiet => return, + }; + web_sys::console::error_1(&line.into()); +} + +/// Logs `device`'s uncaptured errors, and calls `lost` with why and on what adapter if the +/// browser loses it. Handles both WebGPU (through `health.js`) and WebGL2 (through `wgpu-core` +/// callbacks logged to `console.error`). +pub(super) fn watch(device: &wgpu::Device, lost: impl FnOnce(String) + 'static) { + if let Some(js) = js_device(device) { + let adapter = gpu_summary(js); + let log = RefCell::new(ErrorLog::default()); + let on_error = { + let adapter = adapter.clone(); + Closure::<dyn FnMut(String, String)>::new(move |kind: String, message: String| { + log_error_line(&mut log.borrow_mut(), &adapter, &kind, &message); + }) + }; + let on_lost = Closure::once_into_js(move |reason: String, message: String| { + lost(format!("{reason}: {message}, on {adapter}")); + }); + watch_gpu(js, on_error.as_ref().unchecked_ref(), on_lost.unchecked_ref()); + on_error.forget(); + return; + } + let log = Mutex::new(ErrorLog::default()); + device.on_uncaptured_error(Arc::new(move |error: wgpu::Error| { + let kind = match &error { + wgpu::Error::Validation { .. } => "GPUValidationError", + wgpu::Error::OutOfMemory { .. } => "GPUOutOfMemoryError", + wgpu::Error::Internal { .. } => "GPUInternalError", + }; + let message = error.to_string(); + log_error_line(&mut log.lock().unwrap_or_else(|e| e.into_inner()), "WebGL2", kind, &message); + })); + let lost = PageOnly(RefCell::new(Some(lost))); + device.set_device_lost_callback(move |reason, message| { + if reason == wgpu::DeviceLostReason::Destroyed { return; } + let PageOnly(slot) = &lost; + if let Some(lost) = slot.borrow_mut().take() { + lost(format!("{reason:?}: {message}, on WebGL2")); + } + }); +} + +/// Active `webglcontextlost` / `webglcontextrestored` DOM listeners on a canvas; removed on drop. +pub(super) struct WebglWatch { + handle: JsValue, + _on_lost: Closure<dyn FnMut(String)>, + _on_restored: Closure<dyn FnMut()>, +} + +impl WebglWatch { + pub(super) fn new( + canvas: &web_sys::HtmlCanvasElement, + on_lost: impl FnMut(String) + 'static, + on_restored: impl FnMut() + 'static, + ) -> Self { + let on_lost = Closure::<dyn FnMut(String)>::new(on_lost); + let on_restored = Closure::<dyn FnMut()>::new(on_restored); + let handle = watch_webgl_context( + canvas, + on_lost.as_ref().unchecked_ref(), + on_restored.as_ref().unchecked_ref(), + ); + Self { handle, _on_lost: on_lost, _on_restored: on_restored } + } + + pub(super) fn is_lost(&self) -> bool { + webgl_watch_lost(&self.handle) + } +} + +impl Drop for WebglWatch { + fn drop(&mut self) { + dispose_webgl_watch(&self.handle); + } +} + +struct PageOnly<T>(T); +// SAFETY: wasm32 without threads: there is one thread, and every callback runs on it. +#[allow(unsafe_code)] +unsafe impl<T> Send for PageOnly<T> {} diff --git a/app/vendor/rune/crates/rune/src/platform/web/input.rs b/app/vendor/rune/crates/rune/src/platform/web/input.rs new file mode 100644 index 0000000..839d1e5 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/platform/web/input.rs @@ -0,0 +1,580 @@ +use super::*; +use wasm_bindgen::{JsCast, JsValue, prelude::*}; +use winit::event::{ElementState, TouchPhase}; +use winit::keyboard::ModifiersState; + +#[wasm_bindgen(module = "/src/platform/web/bridge.js")] +extern "C" { + #[wasm_bindgen(js_name = isMac)] + fn is_mac() -> bool; + fn mount(canvas: &web_sys::HtmlCanvasElement, callback: &js_sys::Function, embedded: bool, fit_height: bool, document: bool) -> JsValue; + fn sync(handle: &JsValue, key: &str, text: &str, base: usize, anchor: u32, focus: u32, secure: bool); + #[wasm_bindgen(js_name = syncCopy)] + fn sync_copy(handle: &JsValue, text: &str); + #[wasm_bindgen(js_name = syncA11y)] + fn sync_a11y(handle: &JsValue, json: &str); + #[wasm_bindgen(js_name = syncScrollX)] + fn sync_scroll_x(handle: &JsValue, path: &str, x: f32, rtl: bool); + fn activate(handle: &JsValue); + #[wasm_bindgen(js_name = syncPage)] + fn sync_page(handle: &JsValue, height: f32, focused: bool); + #[wasm_bindgen(js_name = presented)] + fn presented_js(handle: &JsValue); + fn destroy(handle: &JsValue); + #[wasm_bindgen(js_name = pastedImage)] + fn pasted_image(handle: &JsValue, max: u32) -> js_sys::Promise; + #[wasm_bindgen(js_name = announceA11y)] + fn announce_a11y(handle: &JsValue, text: &str, assertive: bool); + #[wasm_bindgen(js_name = focusA11y)] + fn focus_a11y(handle: &JsValue, json: &str); + #[wasm_bindgen(js_name = scheduleA11y)] + fn schedule_a11y(handle: &JsValue); + #[wasm_bindgen(js_name = scheduleA11yIdle)] + fn schedule_a11y_idle(handle: &JsValue); + #[wasm_bindgen(js_name = syncSecondary)] + fn sync_secondary(handle: &JsValue, claim: &str); + #[wasm_bindgen(js_name = syncWheel)] + fn sync_wheel(handle: &JsValue, used: bool); + #[wasm_bindgen(js_name = syncCaret)] + fn sync_caret(handle: &JsValue, x: f32, y: f32, w: f32, h: f32); + #[wasm_bindgen(js_name = cancelIme)] + fn cancel_ime(handle: &JsValue); + #[wasm_bindgen(js_name = syncFamilies)] + fn sync_families(handle: &JsValue, sans: &str, mono: &str); + #[wasm_bindgen(js_name = showMenu)] + fn show_menu(handle: &JsValue, json: &str, x: f32, y: f32, min_width: f32, dark: bool); + #[wasm_bindgen(js_name = hideMenu)] + fn hide_menu(handle: &JsValue); +} + +/// How the canvas sits in the page. +#[derive(Clone, Copy)] +pub(super) struct Mode { + /// Inline at its parent's width. + pub embedded: bool, + /// As tall as its content: vertical wheel and pans belong to the page. + pub fit_height: bool, + /// The app is the page (`App::web_document`). + pub document: bool, +} + +pub(super) struct Bridge { + handle: JsValue, + _callback: Closure<dyn FnMut(String)>, + dispose_viewport: js_sys::Function, + mods: ModifiersState, + is_mac: bool, + control_click: bool, + mirror: crate::runtime::web_runtime::Mirror, + a11y: crate::runtime::web_a11y::A11yMirror, + copy_cache: String, + fit_height: bool, + document: bool, + /// The page height and control focus the page last heard. + page: Option<(f32, bool)>, + /// The horizontal offsets and RTL flags the mirror's containers were last set to. + scroll_x: Vec<(String, f32, bool)>, + /// The IME area the page's text field was last put at. + caret: Option<[f32; 4]>, + /// When the mirror was last rebuilt, for the scroll throttle (`sync_input`). + a11y_at: Option<crate::time::Instant>, + /// `Tx::announce`'s calls the page's live regions have said. + announced: u32, + /// The mirror's first build (`sync_input`): not yet asked for, waiting for idle time, built. + a11y_first: First, + /// The slot families the mirror's text was last set in. + families: (String, String), +} + +/// Reads the pasted image bytes from the page's clipboard bridge. +pub(super) fn pasted_image_promise(handle: &JsValue) -> js_sys::Promise { + pasted_image(handle, crate::clipboard::MAX_IMAGE_BYTES as u32) +} + +impl Bridge { + pub(super) fn new(canvas: &web_sys::HtmlCanvasElement, + running: std::rc::Weak<RefCell<Option<Running>>>, window: Arc<Window>, + mode: Mode) -> Self { + let Mode { embedded, fit_height, document } = mode; + let callback = Closure::new(move |event: String| { + let Some(running) = running.upgrade() else { return }; + let event = zeroize::Zeroizing::new(event); + if let Ok(mut event) = serde_json::from_str(&event) { + // A DOM event fired synchronously by page JavaScript Rune called mid-frame (a + // same-tab router tearing the route down) is dropped rather than re-entering. + let Ok(mut running) = running.try_borrow_mut() else { return }; + if let Some(r) = &mut *running && r.input_event(&mut event, &window) { window.request_redraw(); } + } + }); + // A page's canvas is sized by its style and reports no safe area: the page lays out + // around the notch itself. + let dispose_viewport = platform::viewport(canvas, callback.as_ref().unchecked_ref(), embedded || document); + let handle = mount(canvas, callback.as_ref().unchecked_ref(), embedded, fit_height, document); + Self { handle, _callback: callback, dispose_viewport, mods: ModifiersState::empty(), is_mac: is_mac(), control_click: false, + mirror: Default::default(), a11y: Default::default(), + copy_cache: String::new(), fit_height, document, page: None, scroll_x: Vec::new(), caret: None, a11y_at: None, announced: 0, a11y_first: First::Unasked, families: Default::default() } + } + + /// The first frame is on screen: a page swaps its static export for the live mirror. + pub(super) fn presented(&self) { presented_js(&self.handle); } + + /// Opens `show` as the page's own menu, its top-left at its window point. + pub(super) fn show_menu(&self, show: &crate::popup_menu::Show, dark: bool) { + show_menu(&self.handle, &show.menu.to_json().to_string(), show.at.0, show.at.1, show.min_width, dark); + } +} +impl Drop for Bridge { + fn drop(&mut self) { + self.dispose_viewport.call0(&JsValue::NULL).ok(); + destroy(&self.handle); + } +} + +impl Running { + pub(super) fn sync_input(&mut self, focus: bool) { + let (reset, caret) = crate::input::host_events::ime_sync_state(self.app.rt_mut()); + if reset { + cancel_ime(&self.input.handle); + } + if self.app.rt().web_context(&mut self.input.mirror) || reset { + let m = &self.input.mirror; + sync(&self.input.handle, &m.key, &m.text, m.base, m.anchor, m.focus, m.secure); + } + let next_copy = self.app.copy_text().unwrap_or_default(); + if self.input.copy_cache != next_copy { + self.input.copy_cache = next_copy; + sync_copy(&self.input.handle, &self.input.copy_cache); + } + let rt = self.app.rt(); + // The page's text field sits at the caret in window points, so an input method's + // candidates open beside it at any zoom. + if self.input.caret != caret { + self.input.caret = caret; + if let Some([x, y, w, h]) = self.input.caret { sync_caret(&self.input.handle, x, y, w, h); } + } + let (sans, mono) = rt.font_families(); + if !self.input.document && (self.input.families.0 != sans || self.input.families.1 != mono) { + self.input.families = (sans.to_owned(), mono.to_owned()); + sync_families(&self.input.handle, sans, mono); + } + // While the app scrolls, the mirror follows at most every 150 ms (and once when it stops), + // not every frame: rebuilding and restyling every item each frame was most of a scroll + // frame's JavaScript. A page's mirror is in document coordinates and doesn't move. + let now = crate::time::Instant::now(); + // An app's first mirror is every item a new element the browser lays out (13 ms of layout + // on OpenCode's Home): it waits for the page's idle time, so a click or key that came + // with the first frame is handled first. A page's mirror is its document, so it doesn't. + if !self.input.document && self.input.a11y_first != First::Built { + if self.input.a11y_first == First::Unasked { + self.input.a11y_first = First::Waiting; + schedule_a11y_idle(&self.input.handle); + } + } else if !self.input.document && rt.web_a11y_scrolled_only(&self.input.a11y) + && self.input.a11y_at.is_some_and(|at| now.duration_since(at).as_secs_f64() < 0.15) + { + schedule_a11y(&self.input.handle); + } else if let Some(json) = rt.web_a11y(&mut self.input.a11y) { + sync_a11y(&self.input.handle, json); + self.input.a11y_at = Some(now); + } + // An app's focus, for a reader: the browser's focus stays on the canvas or its text field. + if !self.input.document && let Some(focus) = rt.web_a11y_focus(&mut self.input.a11y) { + focus_a11y(&self.input.handle, focus); + } + // `Tx::announce`: the page's own live regions say it, as the native tree's announcer does. + if rt.host.announcement.said() != self.input.announced { + self.input.announced = rt.host.announcement.said(); + if let Some((words, how)) = rt.host.announcement.words() { + announce_a11y(&self.input.handle, &words, how == crate::LiveRegion::Assertive); + } + } + if self.input.document { + let page = (rt.page_height().ceil(), rt.has_focus()); + if self.input.page != Some(page) { + self.input.page = Some(page); + sync_page(&self.input.handle, page.0, page.1); + } + // A horizontal viewport Rune scrolled (a wheel or a key on desktop) moves the mirror's + // container to match; one the browser scrolled already says where it is. + let handle = &self.input.handle; + let mut nodes = rt.tree.nodes.iter(); + let next: Vec<_> = rt.page_scroll_x().into_iter().map(|(path, x)| { + let rtl = nodes.find(|n| n.path == path).is_some_and(|n| n.flow == crate::el::Flow::Rtl); + (path, x, rtl) + }).collect(); + for (path, x, rtl) in &next { + let known = self.input.scroll_x.iter().find(|(p, _, _)| p == path).map(|(_, x, rtl)| (*x, *rtl)); + if known.is_none_or(|(kx, krtl)| (kx - x).abs() > 0.5 || krtl != *rtl) { + sync_scroll_x(handle, path, *x, *rtl); + } + } + self.input.scroll_x = next; + } + if focus { activate(&self.input.handle); } + } + + /// The page's field takes the focused field's context from the model now (web_edit_context); + /// false when a whole frame has to run inside this event instead. + fn sync_live_edit(&mut self) -> bool { + let Some(changed) = self.app.web_edit_context(&mut self.input.mirror) else { return false }; + if changed { + let m = &self.input.mirror; + sync(&self.input.handle, &m.key, &m.text, m.base, m.anchor, m.focus, m.secure); + } + true + } + + /// Handles one DOM event. Returns whether a frame must be drawn: a page's scroll only draws + /// when it moves the band (the browser's compositor scrolls the pixels Rune already drew). + pub(super) fn input_event(&mut self, event: &mut serde_json::Value, window: &Arc<Window>) -> bool { + if event["kind"].as_str() == Some("mods") { + let next = crate::input::host_events::modifiers_from_flags( + event["shift"].as_bool().unwrap_or(false), + event["ctrl"].as_bool().unwrap_or(false), + event["alt"].as_bool().unwrap_or(false), + event["meta"].as_bool().unwrap_or(false), + ); + let redraw = self.app.sync_modifiers(&mut self.input.mods, next); + if redraw { self.full_redraw = true; } + return redraw; + } + if event["kind"].as_str() == Some("pointer_cancel") { + let lost_capture = event["lost_capture"].as_bool().unwrap_or(false); + if !crate::input::host_events::pointer_cancel( + self.app.rt_mut(), + &mut self.input.control_click, + lost_capture, + ) { + return false; + } + self.full_redraw = true; + self.cursor.apply(window, crate::el::Cursor::Default, false); + self.app.frame(0.0); + self.apply_frame_requests(window); + self.clipboard.flush_core(self.app.rt_mut()); + self.sync_input(false); + return true; + } + self.full_redraw = true; + let mut activate = false; + // What a person typed or pressed through the page's own elements is input too, for + // `rune::last_input` (an app holds background work while someone types). + if matches!(event["kind"].as_str(), Some("edit" | "preedit" | "selection" | "key" | "paste" | "a11y_press" | "a11y_link")) { + crate::input::time::typed(); + } + match event["kind"].as_str() { + Some("viewport") => { + let insets = std::array::from_fn(|i| event["insets"][i].as_f64().unwrap_or(0.0).max(0.0) as f32); + let h = event["h"].as_f64().unwrap_or(0.0).max(0.0) as f32; + // A phone reports the visual viewport on every scroll frame as its toolbar moves; + // when neither the safe area nor the largest viewport moved, there's nothing to do. + let moved = LARGE_VIEWPORT.replace(h) != h; + if INSETS.replace(insets) == insets && !moved { return false; } + if moved { self.resize_surface(window, window.inner_size(), window.scale_factor() as f32); } + self.app.rt_mut().invalidate(); + } + Some("dpr") => { + let size = window.inner_size(); + let scale = event["scale"].as_f64().unwrap_or_else(|| window.scale_factor()).max(0.5) as f32; + self.resize_surface(window, size, scale); + } + Some("motion") => self.app.rt_mut().set_system_reduced_motion(event["reduced"].as_bool().unwrap_or(false)), + // The primary pointer can or can't hover (a mouse or a touch screen), read by views + // through `Cx::hover_none`. + Some("primary_pointer") => { + let pointer = match (event["hover"].as_bool(), event["coarse"].as_bool()) { + (Some(false), Some(true)) => PrimaryPointer::Touch, + (Some(false), _) => PrimaryPointer::NoHover, + _ => PrimaryPointer::Hover, + }; + if PRIMARY_POINTER.replace(pointer) == pointer { return false; } + self.app.rt_mut().invalidate(); + } + // The browser's `forced-colors` (a contrast theme) and its system colours, as sRGB bytes: + // Canvas, CanvasText, Highlight, HighlightText, GrayText, ButtonFace, ButtonText, LinkText. + Some("contrast") => { + let colors: Option<Vec<crate::Color>> = event["colors"].as_array().map(|list| list.iter().map(|c| { + let d = |i: usize| crate::color::srgb_decode(c[i].as_f64().unwrap_or(0.0) as f32 / 255.0); + crate::Color { r: d(0), g: d(1), b: d(2), a: 1.0 } + }).collect()); + let contrast = colors.filter(|c| c.len() == 8).map(|c| crate::SystemContrast { + window: c[0], text: c[1], highlight: c[2], highlight_text: c[3], disabled: c[4], button: c[5], button_text: c[6], link: c[7], + }); + self.app.rt_mut().set_system_contrast(contrast); + } + Some("focus") => { + let focused = event["focused"].as_bool().unwrap_or(false); + self.app.window_focus(focused); + if !focused { + self.input.mods = ModifiersState::empty(); + self.input.control_click = false; + self.cursor.apply(window, crate::el::Cursor::Default, false); + } + } + Some("visibility") => { + let visible = event["visible"].as_bool().unwrap_or(false); + self.shared.set_visible(visible); + if !visible { + crate::input::host_events::hide_reset( + self.app.rt_mut(), + &mut self.input.mods, + &mut self.input.control_click, + ); + hide_menu(&self.input.handle); + self.app.resolve_popup(None).ok(); + self.cursor.apply(window, crate::el::Cursor::Default, false); + // Commit cancellation, FocusLost, FinishIme and poll now: browsers pause rAF + // while the tab is hidden. + self.app.frame(0.0); + self.apply_frame_requests(window); + self.clipboard.flush_core(self.app.rt_mut()); + self.sync_input(false); + return false; + } + if event["focused"].as_bool().unwrap_or(false) { + self.app.window_focus(true); + } + return true; + } + Some("leave") => { + if self.app.rt().touching() { return false; } + self.app.rt_mut().pointer_leave(); + self.cursor.apply(window, crate::el::Cursor::Default, false); + return true; + } + Some(kind @ ("edit" | "selection" | "preedit")) => { + self.app.web_edit(event); + // A typed edit is in the model and the page's field: the display's next frame + // draws it, one frame for every key and press that came before it. + if kind == "edit" && self.sync_live_edit() { return true; } + } + Some("sync") => self.input.mirror.key.clear(), // Composition's final sync was deferred by the DOM. + Some("paste") => { + let mut content = crate::ClipboardContent::new(event["text"].as_str().unwrap_or_default()); + if let Some(html) = event["html"].as_str().filter(|html| !html.is_empty()) { content = content.with_html(html); } + let image = (event["image"].as_bool() == Some(true)).then_some(&self.input.handle); + self.app.paste_event(&self.clipboard, content, image); + } + Some("secure") => { + if let serde_json::Value::String(text) = event["text"].take() { + self.app.rt_mut().web_secure(event["key"].as_str().unwrap_or_default(), text); + } + } + Some("key") => activate = self.app.web_key(event), + Some("a11y_press" | "a11y_link") => { let _ = self.app.rt_mut().web_a11y_action(event); } + // The page's menu (`showMenu`) was picked from or dismissed. + Some("menu") => { + if self.app.resolve_popup(event["id"].as_str()).is_err() { self.app.resolve_popup(None).ok(); } + } + // The browser's menu takes this right-click (bridge.js): its release opens none of Rune's. + Some("secondary_browser") => { self.app.rt_mut().secondary_abandon(); return false; } + // The scroll throttle's last word: the mirror where the scroll stopped. + Some("a11y_due") => { + self.input.a11y_first = First::Built; + self.input.a11y_at = None; + self.sync_input(false); + return false; + } + // The page scrolled: draw the band in view, and hover what is now under the pointer. + // The redraw that follows the event draws it; nothing commits. + Some("scroll") => { + let (moved, hover) = { + let rt = self.app.rt_mut(); + let before = rt.page_scroll_y(); + let moved = rt.set_page_scroll(event["y"].as_f64().unwrap_or(0.0) as f32); + // The pointer keeps its place on screen while the band moves under it. + let turned = rt.page_scroll_y() - before; + let hover = (turned != 0.0).then(|| rt.pointer().filter(|_| !rt.touching()).map(|(x, y)| (x, y + turned))).flatten(); + (moved, hover) + }; + if let Some((x, y)) = hover { + self.app.pointer_move(x, y); + } + return moved; + } + // A page's horizontal viewport scrolled natively, by the browser's own compositor. + Some("scroll_x") => { + let path = event["path"].as_str().unwrap_or_default(); + let x = event["x"].as_f64().unwrap_or(0.0) as f32; + return self.app.rt_mut().set_page_scroll_x(path, x); + } + // `WheelEvent.DOM_DELTA_PAGE` (deltaMode === 2), which winit's web backend drops. + Some("wheel_page") => { + let mods = crate::input::key_table::web_mods( + event["shift"].as_bool().unwrap_or(false), + event["ctrl"].as_bool().unwrap_or(false), + event["alt"].as_bool().unwrap_or(false), + event["meta"].as_bool().unwrap_or(false), + ); + let dx_pages = event["dx"].as_f64().unwrap_or(0.0) as f32; + let dy_pages = event["dy"].as_f64().unwrap_or(0.0) as f32; + let shift = !self.input.is_mac && mods.shift; + let (dx, dy) = crate::input::host_events::wheel_page_delta(self.app.rt(), dx_pages, dy_pages, shift); + let (redraw, wheel_used) = crate::input::host_events::web_wheel( + self.app.rt_mut(), + dx, + dy, + mods, + crate::GesturePhase::Moved, + false, + self.input.document, + self.input.fit_height, + ); + if let Some(used) = wheel_used { sync_wheel(&self.input.handle, used); } + return redraw; + } + // The pointer is over mirrored text or a link, which takes it from the canvas. + Some("hover") => { + let (x, y, offset) = { + let rt = self.app.rt(); + if rt.touching() { return false; } + let (x, y) = crate::input::host_events::window_point( + rt, + event["x"].as_f64().unwrap_or(0.0) as f32, + event["y"].as_f64().unwrap_or(0.0) as f32, + ); + (x, y, rt.page_window().0) + }; + // The mirror's pointer is in window points; the canvas draws the band. + self.app.pointer_move(x, y + offset); + return true; + } + _ => {} + } + // Commit within the DOM event: clipboard, link and soft-keyboard APIs need activation. + self.app.frame(0.0); + self.apply_frame_requests(window); + self.clipboard.flush_core(self.app.rt_mut()); + self.sync_input(activate); + true + } + + pub(super) fn window_input(&mut self, event: &WindowEvent, window: &Arc<Window>) -> bool { + let scale = window.scale_factor() as f32; + let mut activate = false; + let mut immediate = false; + match event { + WindowEvent::ModifiersChanged(mods) => { + return self.app.sync_modifiers(&mut self.input.mods, mods.state()); + } + WindowEvent::CursorMoved { position, .. } if !self.app.rt().touching() => { + let (x, y) = crate::input::host_events::physical_point(self.app.rt(), position.x, position.y); + self.app.pointer_move(x, y); + self.cursor.apply(window, self.app.rt().cursor(), true); + } + WindowEvent::CursorLeft { .. } if !self.app.rt().touching() => { + self.app.rt_mut().pointer_leave(); + self.cursor.apply(window, crate::el::Cursor::Default, false); + } + WindowEvent::MouseInput { button, state, .. } if !self.app.rt().touching() => { + immediate = true; + let Some((x, y)) = self.app.rt().pointer() else { return false }; + let mods = crate::window::map_mods(self.input.mods); + let action = self.app.mouse_button( + crate::input::host_events::MouseButtonInput { + x, + y, + button: crate::window::pointer_button(*button), + pressed: *state == ElementState::Pressed, + mods, + ctrl_click_is_secondary: self.input.is_mac, + // Queued after `web_focus_field` below so the text-field fast path still + // sees `Action::Focus` as its sole activation-sensitive action. + queue_mods_on_primary_down: false, + }, + &mut self.input.control_click, + ); + match action { + crate::input::host_events::ButtonAction::PrimaryDown => { + activate = true; + // A press into a text field: the field takes focus now (a key may follow + // before the next frame, and a phone's keyboard opens only inside the + // press); the frame waits for the display's. + if self.app.web_focus_field() && self.sync_live_edit() { + self.app.rt_mut().physical_input(crate::PhysicalInput::Modifiers(mods)); + super::input::activate(&self.input.handle); + return true; + } + self.app.rt_mut().physical_input(crate::PhysicalInput::Modifiers(mods)); + } + crate::input::host_events::ButtonAction::PrimaryUp => { + // Only a release with a handler runs its frame inside the event. A field's + // own selection step (a move while held) runs as a press into it does. + immediate = self.app.rt().web_release_needs_frame() && !(self.app.web_focus_field() && self.sync_live_edit()); + } + crate::input::host_events::ButtonAction::SecondaryDown => { + // The browser's own menu opens where Rune's doesn't (bridge.js). + sync_secondary(&self.input.handle, self.app.rt().secondary_claim()); + } + crate::input::host_events::ButtonAction::SecondaryUp + | crate::input::host_events::ButtonAction::OtherDown(_) + | crate::input::host_events::ButtonAction::OtherUp(_) => {} + } + } + WindowEvent::MouseWheel { delta, phase, .. } => { + // On macOS, AppKit swaps Shift+mouse-wheel before the browser sees it while + // leaving Shift+trackpad vertical. Elsewhere, browsers that keep deltaX == 0 + // rely on wheel_delta to swap vertical into horizontal (it never double-swaps + // when dx != 0). + let shift = !self.input.is_mac && self.input.mods.shift_key(); + let (dx, dy) = crate::runtime::wheel_delta(*delta, scale, shift, crate::runtime::LINE_POINTS); + let precise = matches!(delta, winit::event::MouseScrollDelta::PixelDelta(_)); + // Browsers give WheelEvent no gesture phase (always Moved), matching unphased + // desktop mouse wheels so WheelLock uses its idle timeout. + let phase = crate::input::host_events::gesture_phase(*phase); + let (redraw, wheel_used) = crate::input::host_events::web_wheel( + self.app.rt_mut(), + dx, + dy, + crate::window::map_mods(self.input.mods), + phase, + precise, + self.input.document, + self.input.fit_height, + ); + if let Some(used) = wheel_used { sync_wheel(&self.input.handle, used); } + if !redraw { return false; } + } + // A page's Tab is the browser's, through the mirror's links and buttons. + WindowEvent::KeyboardInput { event, .. } + if self.input.document && event.logical_key == winit::keyboard::Key::Named(winit::keyboard::NamedKey::Tab) => return false, + WindowEvent::KeyboardInput { event, is_synthetic: false, .. } => { + // Browsers expose no synchronous layout key_without_modifiers, so `Tx::key_base` + // stays `None` on web by design; physical US positions arrive in `physical_key`. + if !self.app.keyboard(&self.clipboard, event, self.input.mods) { return false; } + immediate = true; + // Any key that puts Rune's focus in a field (Tab, or a shortcut such as the + // prompt's) hands the page's own field the browser's focus, so a screen reader is + // in a real text field with its text, not on the canvas's stand-in for it. + activate = event.state == ElementState::Pressed; + } + // On a canvas as tall as its content the browser takes vertical pans and cancels the + // touch; taps and horizontal drags stay Rune's. + WindowEvent::Touch(touch) => { + self.app.touch(touch); + // A tap is a user activation: links, the clipboard and focus act before the handler + // returns. In a page only a tap that left something focused needs it; anything else + // would focus the canvas and drop the reader's selection. + if matches!(touch.phase, TouchPhase::Ended) { + activate = !self.input.document || self.app.rt().has_focus(); + immediate = true; + } + } + _ => return false, + } + // Moves and wheels are coalesced by rAF. Only activation-sensitive input must + // commit before the DOM handler returns (clipboard, links and keyboard focus). + if immediate { + self.app.frame(0.0); + self.apply_frame_requests(window); + self.clipboard.flush_core(self.app.rt_mut()); + self.sync_input(activate); + let rt = self.app.rt(); + self.cursor.apply(window, rt.cursor(), rt.pointer().is_some()); + } + true + } +} + +#[derive(Clone, Copy, PartialEq, Eq)] +enum First { Unasked, Waiting, Built } diff --git a/app/vendor/rune/crates/rune/src/platform/web/page.rs b/app/vendor/rune/crates/rune/src/platform/web/page.rs new file mode 100644 index 0000000..c18eff6 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/platform/web/page.rs @@ -0,0 +1,95 @@ +//! What a web app holds of the page while it runs, and gives back when it ends: the event loop +//! (winit allows one at a time), a canvas the page passed in, the body's style and the +//! document title. An app started while the running one is quitting starts once it has gone, +//! so a route can unmount Rune and mount it again in the same tick. +use std::cell::RefCell; + +type Quitting = Box<dyn Fn() -> bool>; +type Start = Box<dyn FnOnce() -> Result<(), String>>; + +#[derive(Default)] +struct Page { + /// The running app's "a quit is on its way". + live: Option<Quitting>, + /// The app to start once the running one has gone. + next: Option<(Quitting, Start)>, + router: Option<std::rc::Rc<dyn Fn(&str) -> bool>>, +} + +thread_local! { static PAGE: RefCell<Page> = RefCell::default(); } + +const BUSY: &str = "a Rune app is already running on this page; call its AppHandle::quit before starting another"; + +/// Starts an app now if the page is free, or once the running app (asked to quit) has gone. +/// `quitting` reports whether the new app was itself asked to quit before it started. +pub(super) fn start(quitting: Quitting, start: Start) -> Result<(), String> { + let now = PAGE.with_borrow_mut(|page| { + // The app this one would follow: one already waiting, else the running one. + let ahead = page.next.as_ref().map(|(quitting, _)| quitting).or(page.live.as_ref()).map(|quitting| quitting()); + match ahead { + None => Ok(Some(start)), + Some(true) => { page.next = Some((quitting, start)); Ok(None) } + Some(false) => Err(BUSY.to_owned()), + } + })?; + now.map_or(Ok(()), |start| start()) +} + +/// The event loop for `quitting`'s app started. +pub(super) fn occupy(quitting: Quitting, router: Option<Box<dyn Fn(&str) -> bool>>) { + PAGE.with_borrow_mut(|page| { page.live = Some(quitting); page.router = router.map(Into::into); }); +} + +/// The running app's event loop is ending. A queued app starts after this turn, once winit +/// has let go of its loop. +pub(super) fn vacate() { + let next = PAGE.with_borrow_mut(|page| { page.live = None; page.router = None; page.next.take() }); + if let Some((_, start)) = next { + wasm_bindgen_futures::spawn_local(async move { + if let Err(e) = start() { super::error(&e, None, false, false); } + }); + } +} + +/// The running app's `App::same_tab_router`, which routed `href` when it returns true. +pub(super) fn route(href: &str) -> bool { + let router = PAGE.with_borrow(|page| page.router.clone()); + router.is_some_and(|route| route(href)) +} + +/// What Rune changed on the page, to put back when the app ends. +#[derive(Default)] +pub(super) struct Borrowed { + canvas: Option<(web_sys::HtmlCanvasElement, String, Vec<(&'static str, Option<String>)>)>, + body: Option<String>, + title: Option<String>, +} + +/// The attributes Rune and winit set on a canvas. +const CANVAS_ATTRIBUTES: [&str; 4] = ["tabindex", "alt", "width", "height"]; + +impl Borrowed { + /// Remembers a canvas the page owns, before Rune styles it. + pub(super) fn canvas(&mut self, canvas: &web_sys::HtmlCanvasElement) { + let attributes = CANVAS_ATTRIBUTES.iter().map(|&name| (name, canvas.get_attribute(name))).collect(); + self.canvas = Some((canvas.clone(), canvas.style().css_text(), attributes)); + } + + /// Remembers the body's inline style and the title, before Rune takes over the viewport. + pub(super) fn viewport(&mut self, document: &web_sys::Document) { + self.body = document.body().map(|body| body.style().css_text()); + self.title = Some(document.title()); + } + + pub(super) fn give_back(self) { + if let Some((canvas, css, attributes)) = self.canvas { + canvas.style().set_css_text(&css); + for (name, value) in attributes { + match value { Some(value) => canvas.set_attribute(name, &value).ok(), None => canvas.remove_attribute(name).ok() }; + } + } + let Some(document) = web_sys::window().and_then(|w| w.document()) else { return }; + if let (Some(css), Some(body)) = (self.body, document.body()) { body.style().set_css_text(&css); } + if let Some(title) = self.title { document.set_title(&title); } + } +} diff --git a/app/vendor/rune/crates/rune/src/platform/web/page_fonts.rs b/app/vendor/rune/crates/rune/src/platform/web/page_fonts.rs new file mode 100644 index 0000000..9f27055 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/platform/web/page_fonts.rs @@ -0,0 +1,48 @@ +//! The app's fonts as the page's own (`FontFace`s in `document.fonts`), so the semantic mirror's +//! text lays out in the faces Rune draws: the browser's Find highlight lands on the glyphs, and a +//! link the pointer is over is where it's drawn. Shared once the first frame is up, from the +//! bytes Rune already has: nothing downloads twice. + +use std::sync::Arc; + +use parley::fontique::{Blob, Collection, CollectionOptions, FontStyle}; +use wasm_bindgen::prelude::*; + +#[wasm_bindgen(module = "/src/platform/web/platform.js")] +extern "C" { + #[wasm_bindgen(js_name = addFontFace)] + fn add_font_face(family: &str, bytes: &[u8], weight: &str, style: &str); +} + +/// [`share`] one font file at a time in the page's idle time (1 s at the latest each), so the +/// frames and reads that follow the first one aren't held behind it: shared at once, a page's +/// fonts held its first reads' answers back 34 ms. +pub(super) fn share_later(fonts: &'static [&'static [u8]]) { + if fonts.is_empty() { + return; + } + wasm_bindgen_futures::spawn_local(async move { + for &font in fonts { + wasm_bindgen_futures::JsFuture::from(super::platform::next_idle(1000)).await.ok(); + share([font]); + } + }); +} + +/// Adds each font file's faces to the page under the family names Rune knows them by. +pub(super) fn share<'a>(fonts: impl IntoIterator<Item = &'a [u8]>) { + let mut collection = Collection::new(CollectionOptions { shared: false, system_fonts: false }); + for bytes in fonts { + for (id, faces) in collection.register_fonts(Blob::new(Arc::new(bytes.to_vec())), None) { + let Some(family) = collection.family_name(id).map(str::to_owned) else { continue }; + // A collection file's later faces would need their own file; its first is the one. + for face in faces.iter().filter(|f| f.index() == 0) { + let declared = crate::text::face_weights::declared(&family, face.weight().value()).map(|r| format!("{} {}", r.0, r.1)); + let weight = declared.or_else(|| face.axes().iter().find(|a| a.tag.to_string() == "wght").map(|a| format!("{} {}", a.min, a.max))) + .unwrap_or_else(|| face.weight().value().to_string()); + let style = match face.style() { FontStyle::Normal => "normal", FontStyle::Italic => "italic", FontStyle::Oblique(_) => "oblique" }; + add_font_face(&family, bytes, &weight, style); + } + } + } +} diff --git a/app/vendor/rune/crates/rune/src/platform/web/pipelines.js b/app/vendor/rune/crates/rune/src/platform/web/pipelines.js new file mode 100644 index 0000000..772847b --- /dev/null +++ b/app/vendor/rune/crates/rune/src/platform/web/pipelines.js @@ -0,0 +1,45 @@ +// The renderer's pipelines compiled off the browser's GPU thread before the renderer is made. +// While diverted, the device's createRenderPipeline starts createRenderPipelineAsync with the +// same descriptor and answers at once with a small stand-in, so a renderer made meanwhile costs +// nothing to compile and is thrown away. Once the async pipelines are in, the real renderer's +// identical descriptors find them in the browser's pipeline cache (Dawn keeps one pipeline per +// descriptor while one is alive), so the hand-over no longer holds the GPU thread that also +// presents the CPU canvas's frames. + +// Whether this browser's WebGPU has an async pipeline compile, before there's a device. +// Requires `navigator.gpu`: when WebGPU is disabled by flag, `GPUDevice` may still exist while +// the page falls back to WebGL2 (which compiles pipelines synchronously). +export function compilesAsync() { + return typeof globalThis.navigator?.gpu === 'object' + && globalThis.navigator.gpu !== null + && typeof globalThis.GPUDevice?.prototype?.createRenderPipelineAsync === 'function'; +} + +// Whether `device` compiles pipelines asynchronously. +export function canDivert(device) { + return typeof device?.createRenderPipelineAsync === 'function'; +} + +// Starts diverting `device`'s createRenderPipeline; `settle` ends it. +export function divert(device) { + const started = []; + let standIn = null; + device.createRenderPipeline = (descriptor) => { + started.push(device.createRenderPipelineAsync(descriptor).catch(() => null)); + standIn ??= GPUDevice.prototype.createRenderPipeline.call(device, standInDescriptor(device)); + return standIn; + }; + return { device, started }; +} + +// Ends the diversion, and resolves to the compiled pipelines (to keep alive until the real +// renderer has made its own) once all of them are in. +export function settle(diverted) { + delete diverted.device.createRenderPipeline; + return Promise.all(diverted.started); +} + +function standInDescriptor(device) { + const module = device.createShaderModule({ code: '@vertex fn v() -> @builtin(position) vec4f { return vec4f(); } @fragment fn f() -> @location(0) vec4f { return vec4f(); }' }); + return { layout: 'auto', vertex: { module, entryPoint: 'v' }, fragment: { module, entryPoint: 'f', targets: [{ format: 'rgba8unorm' }] } }; +} diff --git a/app/vendor/rune/crates/rune/src/platform/web/pipelines.rs b/app/vendor/rune/crates/rune/src/platform/web/pipelines.rs new file mode 100644 index 0000000..9a827f2 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/platform/web/pipelines.rs @@ -0,0 +1,39 @@ +//! The renderer's pipelines compiled ahead, off the browser's GPU thread (pipelines.js), where +//! the browser compiles pipelines asynchronously. A stand-in renderer is made while the device's +//! pipeline creation is diverted to `createRenderPipelineAsync`; the real one, made once those +//! are in, finds them compiled. + +use wasm_bindgen::prelude::*; +use crate::render::Renderer; + +#[wasm_bindgen(module = "/src/platform/web/pipelines.js")] +extern "C" { + #[wasm_bindgen(js_name = compilesAsync)] + fn compiles_async() -> bool; + #[wasm_bindgen(js_name = canDivert)] + fn can_divert(device: &JsValue) -> bool; + fn divert(device: &JsValue) -> JsValue; + fn settle(diverted: &JsValue) -> js_sys::Promise; +} + +/// Kept until the real renderer is made: the stand-in renderer and the compiled pipelines, which +/// the browser's cache holds only while they live. +pub(super) struct Warmed { + _renderer: Renderer, + _pipelines: JsValue, +} + +/// Whether this browser's WebGPU compiles pipelines asynchronously, so asking for the GPU early +/// doesn't hold the page's frames. +pub(super) fn browser_compiles_async() -> bool { compiles_async() } + +/// A renderer for `format` made with the device's pipeline creation diverted, once the browser +/// has compiled every pipeline it asked for. None where it can't (WebGL2, no async compile). +pub(super) async fn warm(device: &wgpu::Device, format: wgpu::TextureFormat) -> Option<Warmed> { + let js: &JsValue = device.as_webgpu()?.as_ref(); + if !can_divert(js) { return None; } + let diverted = divert(js); + let renderer = Renderer::new(device, format); + let pipelines = wasm_bindgen_futures::JsFuture::from(settle(&diverted)).await.ok()?; + Some(Warmed { _renderer: renderer, _pipelines: pipelines }) +} diff --git a/app/vendor/rune/crates/rune/src/platform/web/platform.js b/app/vendor/rune/crates/rune/src/platform/web/platform.js new file mode 100644 index 0000000..4b15bfe --- /dev/null +++ b/app/vendor/rune/crates/rune/src/platform/web/platform.js @@ -0,0 +1,183 @@ +// Plain text, with HTML and a PNG image (a Uint8Array) beside it when there are some (`html` +// is '' and `png` empty otherwise). Empty text isn't written beside another form. +export async function writeClipboard(text, html, png) { + const clipboard = navigator.clipboard; + if (!clipboard) throw new Error('Clipboard requires HTTPS.'); + if ((!html && !png.length) || typeof ClipboardItem === 'undefined') return clipboard.writeText(text); + const forms = {}; + if (text) forms['text/plain'] = new Blob([text], { type: 'text/plain' }); + if (html) forms['text/html'] = new Blob([html], { type: 'text/html' }); + if (png.length) forms['image/png'] = new Blob([png], { type: 'image/png' }); + return clipboard.write([new ClipboardItem(forms)]); +} + +// `{ text, html, png }`, each undefined when the clipboard lacks it; `html` only when `rich`, +// and `png` (a Uint8Array of at most `maxImage` bytes) only when `image`. `read()` starts +// before the first await, inside the input handler; where it fails, plain `readText()` is the +// fallback. +export async function readClipboard(rich, image, maxImage) { + const clipboard = navigator.clipboard; + if (!clipboard) throw new Error('Clipboard requires HTTPS.'); + if (rich && clipboard.read) { + try { + let text, html, png; + for (const item of await clipboard.read()) { + if (text === undefined && item.types.includes('text/plain')) text = await (await item.getType('text/plain')).text(); + if (html === undefined && item.types.includes('text/html')) html = await (await item.getType('text/html')).text(); + if (image && png === undefined && item.types.includes('image/png')) png = await pngBytes(await item.getType('image/png'), maxImage); + } + return { text, html, png }; + } catch {} + } + return { text: await clipboard.readText() }; +} + +// A PNG blob's bytes, or undefined when it's larger than `max`. +export async function pngBytes(blob, max) { + return blob && blob.size <= max ? new Uint8Array(await blob.arrayBuffer()) : undefined; +} + +export function openLink(url) { + const parsed = new URL(url); + if (!['https:', 'http:', 'mailto:'].includes(parsed.protocol)) throw new Error('Unsupported link scheme.'); + window.open(parsed.href, '_blank', 'noopener,noreferrer'); +} + +// `url` resolved against the page, and whether it stays on the page's origin. +export function resolveLink(url) { + const parsed = new URL(url, document.baseURI); + if (!['https:', 'http:', 'mailto:'].includes(parsed.protocol)) throw new Error('Unsupported link scheme.'); + return [parsed.href, parsed.origin === location.origin]; +} + +export function assignLink(href) { + location.assign(href); +} + +export function objectUrl(bytes, type) { + return URL.createObjectURL(new Blob([bytes], { type })); +} + +export function revokeUrl(url) { + URL.revokeObjectURL(url); +} + +// Sets `canvas`'s CSS cursor, or clears it when `css` is empty. Safari reads `image-set()` in a +// cursor only with its `-webkit-` prefix. +export function setCursor(canvas, css) { + if (!css) return void canvas.style.removeProperty('cursor'); + canvas.style.cursor = css; + if (!canvas.style.cursor) canvas.style.cursor = `-webkit-${css}`; +} + +// Resolves in the page's next idle time, or after `timeout` ms at the latest. +export function nextIdle(timeout) { + return new Promise((resolve) => globalThis.requestIdleCallback ? requestIdleCallback(() => resolve(), { timeout }) : setTimeout(resolve, timeout)); +} + +export async function fetchBytes(url) { + const response = await fetch(new URL(url, document.baseURI)); + if (!response.ok) throw new Error(`HTTP ${response.status}`); + return new Uint8Array(await response.arrayBuffer()); +} + +export function resolveUrl(url, base) { + return new URL(url, base).href; +} + +export function viewport(canvas, callback, embedded) { + const probe = document.createElement('div'); + probe.style.cssText = 'position:fixed;visibility:hidden;pointer-events:none;padding:env(safe-area-inset-top) env(safe-area-inset-right) env(safe-area-inset-bottom) env(safe-area-inset-left)'; + document.body.append(probe); + // The largest viewport: on iOS Safari `100lvh` is the viewport with the toolbar collapsed, so + // a canvas or band sized from it doesn't change as the toolbar comes and goes mid-scroll. + const largest = document.createElement('div'); + largest.style.cssText = 'position:fixed;top:0;left:0;width:0;height:100lvh;visibility:hidden;pointer-events:none'; + document.body.append(largest); + const update = () => { + if (!embedded) { + const v = window.visualViewport; + canvas.style.width = `${v?.width ?? innerWidth}px`; + canvas.style.height = `${v?.height ?? innerHeight}px`; + canvas.style.left = `${v?.offsetLeft ?? 0}px`; + canvas.style.top = `${v?.offsetTop ?? 0}px`; + } + const s = getComputedStyle(probe); + callback(JSON.stringify({ kind: 'viewport', h: largest.offsetHeight || innerHeight, + insets: embedded ? [0, 0, 0, 0] : [s.paddingTop, s.paddingRight, s.paddingBottom, s.paddingLeft].map(parseFloat) })); + }; + const motion = matchMedia('(prefers-reduced-motion: reduce)'); + const reduced = () => callback(JSON.stringify({ kind: 'motion', reduced: motion.matches })); + // A primary pointer that can't hover (a touch screen): `Cx::hover_none`. + const hoverNone = matchMedia('(hover: none)'); + const coarse = matchMedia('(pointer: coarse)'); + const pointer = () => callback(JSON.stringify({ kind: 'primary_pointer', hover: !hoverNone.matches, coarse: coarse.matches })); + // A contrast theme (Windows' Contrast themes): `forced-colors`, and its system colours read + // off a probe, as sRGB bytes, for `Cx::system_contrast`. + const forced = matchMedia('(forced-colors: active)'); + const contrast = () => { + if (!forced.matches) { callback(JSON.stringify({ kind: 'contrast', colors: null })); return; } + const swatch = document.createElement('span'); + swatch.style.cssText = 'position:fixed;visibility:hidden;forced-color-adjust:none'; + document.body.append(swatch); + const colors = ['Canvas', 'CanvasText', 'Highlight', 'HighlightText', 'GrayText', 'ButtonFace', 'ButtonText', 'LinkText'].map((name) => { + swatch.style.color = name; + return (getComputedStyle(swatch).color.match(/\d+(\.\d+)?/g) ?? ['0', '0', '0']).slice(0, 3).map(Number); + }); + swatch.remove(); + callback(JSON.stringify({ kind: 'contrast', colors })); + }; + const focus = () => callback(JSON.stringify({ kind: 'focus', focused: document.hasFocus() })); + const visibility = () => callback(JSON.stringify({ kind: 'visibility', visible: !document.hidden, focused: document.hasFocus() })); + let dprMedia = null; + const watchDpr = () => { + dprMedia?.removeEventListener('change', onDpr); + dprMedia = matchMedia(`(resolution: ${window.devicePixelRatio || 1}dppx)`); + dprMedia.addEventListener('change', onDpr); + }; + function onDpr() { + watchDpr(); + callback(JSON.stringify({ kind: 'dpr', scale: window.devicePixelRatio || 1 })); + } + watchDpr(); + window.visualViewport?.addEventListener('resize', update); + window.visualViewport?.addEventListener('scroll', update); + window.addEventListener('resize', update); + // The safe area can change with no resize (Safari settles nv() after a rotation's resize; + // a Home Screen app's status bar): the probe's padding is the insets, so its border box follows + // them (its content box is always empty, which is what an observer watches by default). + const insets = new ResizeObserver(update); + insets.observe(probe, { box: 'border-box' }); + motion.addEventListener('change', reduced); + hoverNone.addEventListener('change', pointer); + coarse.addEventListener('change', pointer); + forced.addEventListener('change', contrast); + window.addEventListener('focus', focus); + window.addEventListener('blur', focus); + document.addEventListener('visibilitychange', visibility); + // Mount is called while Rust is installing the shell; enter it only after installation. + queueMicrotask(() => { update(); reduced(); pointer(); contrast(); focus(); visibility(); }); + return () => { + dprMedia?.removeEventListener('change', onDpr); + window.visualViewport?.removeEventListener('resize', update); + window.visualViewport?.removeEventListener('scroll', update); + window.removeEventListener('resize', update); + insets.disconnect(); + motion.removeEventListener('change', reduced); + hoverNone.removeEventListener('change', pointer); + coarse.removeEventListener('change', pointer); + forced.removeEventListener('change', contrast); + window.removeEventListener('focus', focus); + window.removeEventListener('blur', focus); + document.removeEventListener('visibilitychange', visibility); + probe.remove(); + largest.remove(); + }; +} + +// One face of an app font as the page's own, so the semantic mirror's text sets in it. +export function addFontFace(family, bytes, weight, style) { + const face = new FontFace(family, bytes.slice(), { weight, style }); + document.fonts.add(face); + face.load().catch(() => {}); +} diff --git a/app/vendor/rune/crates/rune/src/platform/web/platform.rs b/app/vendor/rune/crates/rune/src/platform/web/platform.rs new file mode 100644 index 0000000..147de65 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/platform/web/platform.rs @@ -0,0 +1,32 @@ +use wasm_bindgen::prelude::*; + +#[wasm_bindgen(module = "/src/platform/web/platform.js")] +extern "C" { + #[wasm_bindgen(js_name = writeClipboard)] + pub(crate) fn write_clipboard(text: &str, html: &str, png: &[u8]) -> js_sys::Promise; + #[wasm_bindgen(js_name = readClipboard)] + pub(crate) fn read_clipboard(rich: bool, image: bool, max_image: u32) -> js_sys::Promise; + #[wasm_bindgen(catch, js_name = openLink)] + pub(crate) fn open_link(url: &str) -> Result<(), JsValue>; + /// `[absolute href, on this page's origin]`. + #[wasm_bindgen(catch, js_name = resolveLink)] + pub(crate) fn resolve_link(url: &str) -> Result<js_sys::Array, JsValue>; + #[wasm_bindgen(catch, js_name = assignLink)] + pub(crate) fn assign_link(href: &str) -> Result<(), JsValue>; + /// Resolves to the `Uint8Array` body of `url`, relative to the page. + #[wasm_bindgen(js_name = fetchBytes)] + pub(crate) fn fetch_bytes(url: &str) -> js_sys::Promise; + /// `url` resolved against `base`. + #[wasm_bindgen(js_name = resolveUrl)] + pub(crate) fn resolve_url(url: &str, base: &str) -> String; + #[wasm_bindgen(js_name = objectUrl)] + pub(crate) fn object_url(bytes: &[u8], kind: &str) -> String; + #[wasm_bindgen(js_name = revokeUrl)] + pub(crate) fn revoke_url(url: &str); + /// Sets the canvas's CSS `cursor`, or clears it when `css` is empty. + #[wasm_bindgen(js_name = setCursor)] + pub(crate) fn set_cursor(canvas: &web_sys::HtmlCanvasElement, css: &str); + #[wasm_bindgen(js_name = nextIdle)] + pub(crate) fn next_idle(timeout: u32) -> js_sys::Promise; + pub(super) fn viewport(canvas: &web_sys::HtmlCanvasElement, callback: &js_sys::Function, embedded: bool) -> js_sys::Function; +} diff --git a/app/vendor/rune/crates/rune/src/platform/web_math.rs b/app/vendor/rune/crates/rune/src/platform/web_math.rs new file mode 100644 index 0000000..f27030f --- /dev/null +++ b/app/vendor/rune/crates/rune/src/platform/web_math.rs @@ -0,0 +1,332 @@ +//! The arithmetic behind the browser shell: the canvas's size in device pixels, when a resize +//! needs the surface configured again, and the band a page's canvas covers. Kept out of +//! `platform/web.rs`, which only builds on `wasm32`, so the tests run headless. +#![cfg_attr(not(test), allow(dead_code))] + +/// The canvas's size in device pixels. `css` is the canvas's CSS box and `reported` what winit +/// reported for it. A canvas reports pixels, but an emulated device scale reports CSS pixels, so +/// where a side disagrees with the canvas's own box the box wins. A window that fits its content +/// (`fit_height`) keeps the reported height: the app measures its content and sets the height +/// itself, so the box is only as tall as the last frame's content. +pub(crate) fn fix_canvas_size(css: (f32, f32), reported: (u32, u32), spec: (f32, f32), scale: f32, fit_height: bool) -> (u32, u32) { + let scale = scale.max(1e-3); + let want = |css: f32| (css * scale).round().max(1.0) as u32; + // Within a pixel of the box the browser's own number is the box's: it knows the device + // grid, and a fractional CSS box rounds by a fraction of a pixel either way. + let fixed = |got: u32, css: f32| { + if css > 0.0 && (got as f32 - want(css) as f32).abs() > scale.ceil() + 1.0 { want(css) } else { got } + }; + let (w, h) = css; + let mut size = reported; + if w > 0.0 { size.0 = fixed(size.0, w); } + if !fit_height && h > 0.0 { size.1 = fixed(size.1, h); } + if size.0 == 0 { size.0 = if w > 0.0 { want(w) } else { want(spec.0) }; } + if size.1 == 0 { size.1 = if !fit_height && h > 0.0 { want(h) } else { want(spec.1) }; } + size +} + +/// The surface's next size and whether it needs configuring again. `current` is the size it is +/// configured at. A page (`document`) never shrinks its surface: a phone's toolbar expanding +/// shrinks the viewport for a moment mid-scroll, and a web surface configured again destroys and +/// reallocates its swapchain textures in the GPU process right then. +pub(crate) fn should_reconfigure_surface(current: (u32, u32), next: (u32, u32), document: bool) -> ((u32, u32), bool) { + if next.0 == 0 || next.1 == 0 || next == current { return (current, false); } + if document && next.0 == current.0 && next.1 < current.1 { return (current, false); } + (next, true) +} + +/// The surface format, optional `view_formats` entry, and render-target format for a web canvas. +/// +/// Mirrors native `window::surface::surface_config`: +/// - `srgb_blend == true`: wants a non-sRGB render target (`remove_srgb_suffix`) so the target +/// writes and blends already sRGB-encoded values without encoding a second time. +/// - `srgb_blend == false`: wants an `*Srgb` render target (`add_srgb_suffix`) so the target +/// encodes linear shader outputs once on write. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct SurfaceFormats { + pub surface: wgpu::TextureFormat, + pub view_format: Option<wgpu::TextureFormat>, + pub render: wgpu::TextureFormat, +} + +impl SurfaceFormats { + /// Whether the renderer must encode sampled sRGB images in the shader (non-sRGB target). + pub(crate) fn srgb_blend(self) -> bool { + !self.render.is_srgb() + } +} + +/// Chooses the canvas configuration format and render target format for `srgb_blend`. +/// +/// Prefers configuring the surface directly in the wanted format when `supported` lists it +/// (e.g. WebGL2 exposes both `Rgba8UnormSrgb` and `Rgba8Unorm`). Otherwise keeps `preferred` +/// and exposes the wanted twin via `view_format` on backends that support view-format aliasing +/// (WebGPU canvases configure only non-sRGB formats and accept sRGB view formats). +pub(crate) fn select_surface_formats( + preferred: wgpu::TextureFormat, + supported: &[wgpu::TextureFormat], + backend: wgpu::Backend, + srgb_blend: bool, +) -> SurfaceFormats { + let wanted = if srgb_blend { + preferred.remove_srgb_suffix() + } else { + preferred.add_srgb_suffix() + }; + if wanted == preferred { + return SurfaceFormats { surface: preferred, view_format: None, render: preferred }; + } + if supported.contains(&wanted) { + return SurfaceFormats { surface: wanted, view_format: None, render: wanted }; + } + if backend != wgpu::Backend::Gl { + return SurfaceFormats { surface: preferred, view_format: Some(wanted), render: wanted }; + } + SurfaceFormats { surface: preferred, view_format: None, render: preferred } +} + +/// Surface texture usages for a web canvas. +/// +/// WebGPU canvases accept `COPY_DST` (for retained loop-only frames) and `COPY_SRC` (for drift +/// readback) even though wgpu's capabilities report only `RENDER_ATTACHMENT`. WebGL2 runs through +/// `wgpu-core`, which rejects any usage absent from `caps_usages`. +pub(crate) fn surface_usage( + caps_usages: wgpu::TextureUsages, + backend: wgpu::Backend, + drift: bool, +) -> wgpu::TextureUsages { + let mut usage = wgpu::TextureUsages::RENDER_ATTACHMENT + | (caps_usages & wgpu::TextureUsages::COPY_SRC); + if backend == wgpu::Backend::BrowserWebGpu { + usage |= wgpu::TextureUsages::COPY_DST; + if drift { + usage |= wgpu::TextureUsages::COPY_SRC; + } + } + usage +} + +/// Whether `backend` requires explicit `Device::poll` calls to deliver `on_submitted_work_done` +/// and `map_async` callbacks. WebGPU delivers them from browser promises (and `Device::poll` is a +/// no-op there); `wgpu-core`'s WebGL2 backend only fires them when polled. +pub(crate) fn needs_device_poll(backend: wgpu::Backend) -> bool { + backend != wgpu::Backend::BrowserWebGpu +} + +/// GPU backends the web host can attempt for a canvas. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum WebBackend { + WebGpu, + WebGl2, +} + +/// Backends to attempt in order, given whether `navigator.gpu` is exposed and whether the +/// `webgl` cargo feature is enabled. +/// +/// When `navigator.gpu` is absent (insecure origin, WebGPU disabled by flag while +/// `canvas.getContext("webgpu")` still exists, or a browser without WebGPU), WebGPU is skipped +/// so the canvas is never locked to a `"webgpu"` context before WebGL2 runs. When `navigator.gpu` +/// is present, WebGPU probes for an adapter and device before creating a canvas surface, leaving +/// the canvas free for WebGL2 if either fails. +pub(crate) fn backend_order(has_navigator_gpu: bool, webgl_enabled: bool) -> &'static [WebBackend] { + match (has_navigator_gpu, webgl_enabled) { + (true, true) => &[WebBackend::WebGpu, WebBackend::WebGl2], + (true, false) => &[WebBackend::WebGpu], + (false, true) => &[WebBackend::WebGl2], + (false, false) => &[], + } +} + +/// How the web host handles a lost GPU device or WebGL2 context. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum LossAction { + /// Fall back to the CPU 2D canvas under the GPU canvas. `recoverable` is true for WebGL2 + /// context loss, where a later `webglcontextrestored` hands back over to WebGL2. + FallbackToCpu { recoverable: bool }, + /// Drop the lost GPU side and pause rendering until `webglcontextrestored` rebuilds it. + PauseForRestore, + /// Show the fatal GPU-lost message and exit the loop. + Fatal, +} + +/// Decides how the web host responds when the GPU device or WebGL2 context is lost. +/// +/// WebGPU loss preserves the existing policy: permanent CPU fallback on CPU-first pages and +/// fatal on GPU-first pages. WebGL2 context loss is recoverable when `webglcontextrestored` +/// fires: full-window pages (`!embedded && !document`) fall back to the CPU canvas immediately so +/// they are never blank while waiting (or if restore never arrives), while inline and document +/// pages pause in place until restore. +pub(crate) fn loss_action(is_webgl: bool, gpu_first: bool, embedded: bool, document: bool) -> LossAction { + if is_webgl { + if !embedded && !document { + LossAction::FallbackToCpu { recoverable: true } + } else { + LossAction::PauseForRestore + } + } else if gpu_first { + LossAction::Fatal + } else { + LossAction::FallbackToCpu { recoverable: false } + } +} + +/// Web draw state reduced to the facts `WebFrameHost::gate` needs to decide whether a frame runs. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum WebDrawKind { + Cpu, + HandingOver { waiting_for_gpu: bool }, + Gpu, + ContextLost, + Moving, +} + +/// Decides whether a web frame proceeds into [`crate::frame::host_step::run`] or skips. +pub(crate) fn web_frame_gate(suspended: bool, draw: WebDrawKind) -> crate::frame::host_step::Gate { + if suspended + || matches!( + draw, + WebDrawKind::HandingOver { waiting_for_gpu: true } + | WebDrawKind::ContextLost + | WebDrawKind::Moving + ) + { + crate::frame::host_step::Gate::Skip + } else { + crate::frame::host_step::Gate::Draw + } +} + +/// Outcome of one `wgpu::Surface::get_current_texture` call without the texture payload, so +/// acquisition policy can be tested off `wasm32`. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum WebAcquireStatus { + Ready, + Timeout, + Occluded, + OutdatedOrLost, + Validation, +} + +/// Action taken after `get_current_texture` returns [`WebAcquireStatus`]. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum WebAcquireAction { + UseTexture, + ReconfigureAndRetry, + Miss(crate::window::Missed), +} + +/// Maps a canvas texture acquisition status and remaining reconfigure retries to an action. +/// +/// Transient `Timeout` and `Occluded` statuses return missed frames instead of terminating the +/// app; `Outdated` and `Lost` reconfigure once before becoming fatal `Missed::Unconfigured`. +pub(crate) fn web_acquire_action(status: WebAcquireStatus, retries_left: u8) -> WebAcquireAction { + use crate::window::Missed; + match status { + WebAcquireStatus::Ready => WebAcquireAction::UseTexture, + WebAcquireStatus::Timeout => WebAcquireAction::Miss(Missed::Timeout), + WebAcquireStatus::Occluded => WebAcquireAction::Miss(Missed::Occluded), + WebAcquireStatus::OutdatedOrLost if retries_left > 0 => WebAcquireAction::ReconfigureAndRetry, + WebAcquireStatus::OutdatedOrLost | WebAcquireStatus::Validation => { + WebAcquireAction::Miss(Missed::Unconfigured) + } + } +} + +/// How the web host responds inside `FrameHost::on_missed`. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum WebMissAction { + /// Canvas acquisition failed fatally: report the error and end the event loop. + Fatal, + /// Surface is occluded: step covered work if unstepped, without requesting another rAF. + CoveredOnly, + /// Transient miss: step covered work if unstepped and request a redraw on the next rAF. + RetryNextFrame, +} + +/// Classifies a missed web frame for `WebFrameHost::on_missed`. +pub(crate) fn web_miss_action(missed: crate::window::Missed) -> WebMissAction { + use crate::window::Missed; + match missed { + Missed::Unconfigured => WebMissAction::Fatal, + Missed::Occluded => WebMissAction::CoveredOnly, + Missed::Timeout | Missed::Outdated => WebMissAction::RetryNextFrame, + } +} + +/// Whether `WebFrameHost::post_step_check` should drop the acquired drawable and reblend. +/// +/// Skips re-acquiring when this frame already tried reblending for `rt_srgb` (for example on a +/// WebGL2 surface without an sRGB twin where the chosen format cannot match `rt_srgb`). +pub(crate) fn should_post_step_reblend( + renderer_srgb: bool, + rt_srgb: bool, + reblend_tried: Option<bool>, +) -> bool { + renderer_srgb != rt_srgb && reblend_tried != Some(rt_srgb) +} + +/// How a browser represents `Element.scrollLeft` on a `direction: rtl` container. +/// +/// Matches `detectRtlScrollType()` in `platform/web/bridge.js`: +/// - `Negative` (CSSOM View standard: Chromium >= 85, Firefox, Safari >= 15.4): `0` at the right +/// (start) edge, `-max` at the left (end) edge. +/// - `Reverse` (legacy Edge/IE): `0` at the right (start) edge, `+max` at the left (end) edge. +/// - `Default` (legacy Blink/WebKit): `+max` at the right (start) edge, `0` at the left (end) edge. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum RtlScrollModel { + Negative, + Reverse, + Default, +} + +/// Converts a DOM `Element.scrollLeft` reading into Rune's logical horizontal scroll offset +/// (`0..=max_scroll`, measuring distance from the inline-start edge). +pub(crate) fn scroll_x_from_dom( + scroll_left: f32, + max_scroll: f32, + rtl: bool, + model: RtlScrollModel, +) -> f32 { + if !scroll_left.is_finite() || !max_scroll.is_finite() { + return 0.0; + } + let max = max_scroll.max(0.0); + let logical = if !rtl { + scroll_left + } else { + match model { + RtlScrollModel::Negative => -scroll_left, + RtlScrollModel::Reverse => scroll_left, + RtlScrollModel::Default => max - scroll_left, + } + }; + logical.clamp(0.0, max) +} + +/// Converts Rune's logical horizontal scroll offset (`0..=max_scroll`) into the DOM +/// `Element.scrollLeft` value expected by the browser's RTL scroll model. +pub(crate) fn scroll_x_to_dom( + offset: f32, + max_scroll: f32, + rtl: bool, + model: RtlScrollModel, +) -> f32 { + if !offset.is_finite() || !max_scroll.is_finite() { + return 0.0; + } + let max = max_scroll.max(0.0); + let clamped = offset.clamp(0.0, max); + if !rtl { + clamped + } else { + match model { + RtlScrollModel::Negative => if clamped == 0.0 { 0.0 } else { -clamped }, + RtlScrollModel::Reverse => clamped, + RtlScrollModel::Default => max - clamped, + } + } +} + +#[cfg(test)] +#[path = "web_math_tests.rs"] +mod tests; diff --git a/app/vendor/rune/crates/rune/src/platform/web_math_tests.rs b/app/vendor/rune/crates/rune/src/platform/web_math_tests.rs new file mode 100644 index 0000000..58f8dbb --- /dev/null +++ b/app/vendor/rune/crates/rune/src/platform/web_math_tests.rs @@ -0,0 +1,672 @@ +use super::*; + +#[test] +fn a_phone_canvas_reported_in_css_pixels_gets_its_device_height() { + // Chromium's emulated device scale reports the CSS box: 390 × 844 at 2× used to take the + // width's fix and leave the height at 844, stretching the canvas 2× vertically. + assert_eq!(fix_canvas_size((390.0, 844.0), (390, 844), (1200.0, 900.0), 2.0, false), (780, 1688)); +} + +#[test] +fn a_canvas_still_at_its_intrinsic_size_is_sized_to_its_box() { + // The canvas exists at the HTML default 300 × 150 until `resumed` styles it; a frame that + // races the browser's first ResizeObserver sees that size. + assert_eq!(fix_canvas_size((393.0, 852.0), (300, 150), (1200.0, 900.0), 3.0, false), (1179, 2556)); +} + +#[test] +fn a_window_that_fits_its_content_keeps_the_height_it_measured() { + // `fit_content_height`: the canvas is exactly its content, and the app set that height. + assert_eq!(fix_canvas_size((600.0, 640.0), (600, 640), (1200.0, 900.0), 2.0, true).1, 640); + assert_eq!(fix_canvas_size((600.0, 640.0), (300, 150), (1200.0, 900.0), 2.0, true).1, 150); +} + +#[test] +fn a_canvas_with_no_box_yet_falls_back_to_the_spec() { + assert_eq!(fix_canvas_size((0.0, 0.0), (0, 0), (1200.0, 900.0), 2.0, false), (2400, 1800)); + assert_eq!(fix_canvas_size((0.0, 0.0), (0, 0), (1200.0, 900.0), 1.0, true), (1200, 900)); +} + +#[test] +fn a_size_the_box_agrees_with_is_left_alone() { + // The box's fractional width at 1.5× rounds to a pixel the browser may report ±1. + assert_eq!(fix_canvas_size((1001.0, 700.0), (1502, 1050), (1200.0, 900.0), 1.5, false), (1502, 1050)); +} + +#[test] +fn a_page_surface_never_shrinks_for_a_toolbar() { + let phone = (1179, 2556); + // Safari's toolbar expanding shrinks the viewport while the page is scrolling. + assert_eq!(should_reconfigure_surface(phone, (1179, 2400), true), (phone, false)); + // Collapsing again lands on the size it already has. + assert_eq!(should_reconfigure_surface(phone, phone, true), (phone, false)); + // A rotation has a new width, and does reconfigure. + assert_eq!(should_reconfigure_surface(phone, (2556, 1179), true), ((2556, 1179), true)); +} + +#[test] +fn other_windows_reconfigure_on_every_size_change() { + assert_eq!(should_reconfigure_surface((800, 600), (800, 500), false), ((800, 500), true)); + assert_eq!(should_reconfigure_surface((800, 600), (800, 600), false), ((800, 600), false)); + // A window hidden to nothing keeps its surface until it has a size again. + assert_eq!(should_reconfigure_surface((800, 600), (0, 0), false), ((800, 600), false)); +} + +#[test] +fn webgl_picks_non_srgb_surface_format_directly_for_srgb_blend() { + use wgpu::{Backend, TextureFormat}; + // wgpu-core sorts sRGB formats first, so WebGL2's default config prefers Rgba8UnormSrgb + // while advertising both Rgba8UnormSrgb and Rgba8Unorm. + let caps = [TextureFormat::Rgba8UnormSrgb, TextureFormat::Rgba8Unorm]; + let srgb_on = select_surface_formats(TextureFormat::Rgba8UnormSrgb, &caps, Backend::Gl, true); + assert_eq!(srgb_on, SurfaceFormats { + surface: TextureFormat::Rgba8Unorm, + view_format: None, + render: TextureFormat::Rgba8Unorm, + }); + assert!(srgb_on.srgb_blend()); + + // Switching back to linear blending (srgb_blend == false) selects Rgba8UnormSrgb directly. + let srgb_off = select_surface_formats(TextureFormat::Rgba8Unorm, &caps, Backend::Gl, false); + assert_eq!(srgb_off, SurfaceFormats { + surface: TextureFormat::Rgba8UnormSrgb, + view_format: None, + render: TextureFormat::Rgba8UnormSrgb, + }); + assert!(!srgb_off.srgb_blend()); +} + +#[test] +fn webgpu_uses_view_format_for_linear_blend_and_direct_for_srgb_blend() { + use wgpu::{Backend, TextureFormat}; + let caps = [TextureFormat::Bgra8Unorm, TextureFormat::Rgba8Unorm]; + let srgb_on = select_surface_formats(TextureFormat::Bgra8Unorm, &caps, Backend::BrowserWebGpu, true); + assert_eq!(srgb_on, SurfaceFormats { + surface: TextureFormat::Bgra8Unorm, + view_format: None, + render: TextureFormat::Bgra8Unorm, + }); + assert!(srgb_on.srgb_blend()); + + let srgb_off = select_surface_formats(TextureFormat::Bgra8Unorm, &caps, Backend::BrowserWebGpu, false); + assert_eq!(srgb_off, SurfaceFormats { + surface: TextureFormat::Bgra8Unorm, + view_format: Some(TextureFormat::Bgra8UnormSrgb), + render: TextureFormat::Bgra8UnormSrgb, + }); + assert!(!srgb_off.srgb_blend()); +} + +#[test] +fn webgl_without_srgb_twin_keeps_supported_format_without_view_formats() { + use wgpu::{Backend, TextureFormat}; + let caps = [TextureFormat::Rgba8Unorm]; + let linear_asked = select_surface_formats(TextureFormat::Rgba8Unorm, &caps, Backend::Gl, false); + assert_eq!(linear_asked, SurfaceFormats { + surface: TextureFormat::Rgba8Unorm, + view_format: None, + render: TextureFormat::Rgba8Unorm, + }); + assert!(linear_asked.srgb_blend()); +} + +#[test] +fn webgl_surface_usage_never_adds_unsupported_copy_flags() { + use wgpu::{Backend, TextureUsages}; + let render_only = TextureUsages::RENDER_ATTACHMENT; + assert_eq!(surface_usage(render_only, Backend::Gl, false), TextureUsages::RENDER_ATTACHMENT); + assert_eq!(surface_usage(render_only, Backend::Gl, true), TextureUsages::RENDER_ATTACHMENT); + assert_eq!( + surface_usage(render_only, Backend::BrowserWebGpu, false), + TextureUsages::RENDER_ATTACHMENT | TextureUsages::COPY_DST, + ); + assert_eq!( + surface_usage(render_only, Backend::BrowserWebGpu, true), + TextureUsages::RENDER_ATTACHMENT | TextureUsages::COPY_DST | TextureUsages::COPY_SRC, + ); + assert_eq!( + surface_usage(render_only | TextureUsages::COPY_SRC, Backend::Gl, false), + TextureUsages::RENDER_ATTACHMENT | TextureUsages::COPY_SRC, + ); +} + +#[test] +fn only_non_webgpu_backends_need_device_polling() { + use wgpu::Backend; + assert!(!needs_device_poll(Backend::BrowserWebGpu)); + assert!(needs_device_poll(Backend::Gl)); +} + +#[test] +fn backend_order_skips_webgpu_when_navigator_gpu_is_absent() { + assert_eq!(backend_order(true, true), &[WebBackend::WebGpu, WebBackend::WebGl2]); + assert_eq!(backend_order(true, false), &[WebBackend::WebGpu]); + assert_eq!(backend_order(false, true), &[WebBackend::WebGl2]); + assert_eq!(backend_order(false, false), &[]); +} + +#[test] +fn webgl_context_loss_recovers_instead_of_terminating_the_app() { + // WebGL2 full-window (CPU-first or ?cpu-first=off): immediate CPU fallback, recoverable on restore. + assert_eq!(loss_action(true, false, false, false), LossAction::FallbackToCpu { recoverable: true }); + assert_eq!(loss_action(true, true, false, false), LossAction::FallbackToCpu { recoverable: true }); + // WebGL2 inline or document: pause until webglcontextrestored instead of showing a fatal overlay. + assert_eq!(loss_action(true, true, true, false), LossAction::PauseForRestore); + assert_eq!(loss_action(true, true, false, true), LossAction::PauseForRestore); + // WebGPU keeps its existing policy: permanent CPU fallback on CPU-first, fatal on GPU-first. + assert_eq!(loss_action(false, false, false, false), LossAction::FallbackToCpu { recoverable: false }); + assert_eq!(loss_action(false, true, false, false), LossAction::Fatal); + assert_eq!(loss_action(false, true, true, false), LossAction::Fatal); +} + +#[test] +fn web_gate_skips_suspended_waiting_context_lost_and_moving() { + use crate::frame::host_step::Gate; + assert!(matches!(web_frame_gate(true, WebDrawKind::Gpu), Gate::Skip)); + assert!(matches!(web_frame_gate(true, WebDrawKind::Cpu), Gate::Skip)); + assert!(matches!(web_frame_gate(false, WebDrawKind::ContextLost), Gate::Skip)); + assert!(matches!(web_frame_gate(false, WebDrawKind::Moving), Gate::Skip)); + assert!(matches!(web_frame_gate(false, WebDrawKind::HandingOver { waiting_for_gpu: true }), Gate::Skip)); + assert!(matches!(web_frame_gate(false, WebDrawKind::HandingOver { waiting_for_gpu: false }), Gate::Draw)); + assert!(matches!(web_frame_gate(false, WebDrawKind::Cpu), Gate::Draw)); + assert!(matches!(web_frame_gate(false, WebDrawKind::Gpu), Gate::Draw)); +} + +#[test] +fn web_acquire_and_miss_policies_distinguish_transient_from_fatal() { + use crate::window::Missed; + assert_eq!(web_acquire_action(WebAcquireStatus::Ready, 1), WebAcquireAction::UseTexture); + assert_eq!(web_acquire_action(WebAcquireStatus::Timeout, 1), WebAcquireAction::Miss(Missed::Timeout)); + assert_eq!(web_acquire_action(WebAcquireStatus::Occluded, 1), WebAcquireAction::Miss(Missed::Occluded)); + assert_eq!(web_acquire_action(WebAcquireStatus::OutdatedOrLost, 1), WebAcquireAction::ReconfigureAndRetry); + assert_eq!(web_acquire_action(WebAcquireStatus::OutdatedOrLost, 0), WebAcquireAction::Miss(Missed::Unconfigured)); + assert_eq!(web_acquire_action(WebAcquireStatus::Validation, 1), WebAcquireAction::Miss(Missed::Unconfigured)); + + assert_eq!(web_miss_action(Missed::Unconfigured), WebMissAction::Fatal); + assert_eq!(web_miss_action(Missed::Occluded), WebMissAction::CoveredOnly); + assert_eq!(web_miss_action(Missed::Timeout), WebMissAction::RetryNextFrame); + assert_eq!(web_miss_action(Missed::Outdated), WebMissAction::RetryNextFrame); +} + +#[test] +fn rtl_scroll_x_normalizes_all_browser_models_and_round_trips() { + let max = 400.0; + // LTR: identity clamped to [0, max]. + for model in [RtlScrollModel::Negative, RtlScrollModel::Reverse, RtlScrollModel::Default] { + assert_eq!(scroll_x_from_dom(0.0, max, false, model), 0.0); + assert_eq!(scroll_x_from_dom(120.0, max, false, model), 120.0); + assert_eq!(scroll_x_from_dom(400.0, max, false, model), 400.0); + assert_eq!(scroll_x_from_dom(-25.0, max, false, model), 0.0, "LTR rubber-band past start clamps to 0"); + assert_eq!(scroll_x_from_dom(430.0, max, false, model), 400.0, "LTR overscroll past end clamps to max"); + assert_eq!(scroll_x_to_dom(120.0, max, false, model), 120.0); + } + + // RTL Negative (CSSOM View standard: modern Chrome/Firefox/Safari): 0 at start, -max at end. + assert_eq!(scroll_x_from_dom(0.0, max, true, RtlScrollModel::Negative), 0.0); + assert_eq!(scroll_x_from_dom(-80.0, max, true, RtlScrollModel::Negative), 80.0); + assert_eq!(scroll_x_from_dom(-400.0, max, true, RtlScrollModel::Negative), 400.0); + assert_eq!(scroll_x_from_dom(20.0, max, true, RtlScrollModel::Negative), 0.0, "RTL negative rubber-band past start"); + assert_eq!(scroll_x_from_dom(-425.0, max, true, RtlScrollModel::Negative), 400.0, "RTL negative rubber-band past end"); + let dom_zero = scroll_x_to_dom(0.0, max, true, RtlScrollModel::Negative); + assert_eq!(dom_zero, 0.0); + assert!(!dom_zero.is_sign_negative(), "start offset writes +0.0, not -0.0"); + assert_eq!(scroll_x_to_dom(80.0, max, true, RtlScrollModel::Negative), -80.0); + assert_eq!(scroll_x_to_dom(400.0, max, true, RtlScrollModel::Negative), -400.0); + + // RTL Reverse (legacy Edge/IE): 0 at start, +max at end. + assert_eq!(scroll_x_from_dom(0.0, max, true, RtlScrollModel::Reverse), 0.0); + assert_eq!(scroll_x_from_dom(80.0, max, true, RtlScrollModel::Reverse), 80.0); + assert_eq!(scroll_x_from_dom(400.0, max, true, RtlScrollModel::Reverse), 400.0); + assert_eq!(scroll_x_from_dom(-15.0, max, true, RtlScrollModel::Reverse), 0.0); + assert_eq!(scroll_x_from_dom(420.0, max, true, RtlScrollModel::Reverse), 400.0); + assert_eq!(scroll_x_to_dom(0.0, max, true, RtlScrollModel::Reverse), 0.0); + assert_eq!(scroll_x_to_dom(80.0, max, true, RtlScrollModel::Reverse), 80.0); + assert_eq!(scroll_x_to_dom(400.0, max, true, RtlScrollModel::Reverse), 400.0); + + // RTL Default (legacy Blink/WebKit): +max at start, 0 at end. + assert_eq!(scroll_x_from_dom(400.0, max, true, RtlScrollModel::Default), 0.0); + assert_eq!(scroll_x_from_dom(320.0, max, true, RtlScrollModel::Default), 80.0); + assert_eq!(scroll_x_from_dom(0.0, max, true, RtlScrollModel::Default), 400.0); + assert_eq!(scroll_x_from_dom(430.0, max, true, RtlScrollModel::Default), 0.0, "RTL default rubber-band past start"); + assert_eq!(scroll_x_from_dom(-20.0, max, true, RtlScrollModel::Default), 400.0, "RTL default rubber-band past end"); + assert_eq!(scroll_x_to_dom(0.0, max, true, RtlScrollModel::Default), 400.0); + assert_eq!(scroll_x_to_dom(80.0, max, true, RtlScrollModel::Default), 320.0); + assert_eq!(scroll_x_to_dom(400.0, max, true, RtlScrollModel::Default), 0.0); + + // Round-trip invariant across every model, direction, and edge value. + for rtl in [false, true] { + for model in [RtlScrollModel::Negative, RtlScrollModel::Reverse, RtlScrollModel::Default] { + for offset in [0.0, 0.5, 80.0, 199.75, 400.0] { + let dom = scroll_x_to_dom(offset, max, rtl, model); + let back = scroll_x_from_dom(dom, max, rtl, model); + assert!((back - offset).abs() < 1e-4, "round-trip mismatch for rtl={rtl} model={model:?} offset={offset}: dom={dom} -> {back}"); + } + assert_eq!(scroll_x_from_dom(f32::NAN, max, rtl, model), 0.0); + assert_eq!(scroll_x_from_dom(f32::INFINITY, max, rtl, model), 0.0); + assert_eq!(scroll_x_to_dom(f32::NAN, max, rtl, model), 0.0); + assert_eq!(scroll_x_to_dom(100.0, 0.0, rtl, model), 0.0); + assert_eq!(scroll_x_from_dom(-100.0, 0.0, rtl, model), 0.0); + } + } +} + +mod web_frame_host_tests { + use std::collections::VecDeque; + use std::time::Duration; + + use super::*; + use crate::frame::clock::FrameClock; + use crate::frame::host_step::{ + self, Acquire, FrameHost, Gate, Outcome, PostStepCheck, ReacquireReason, RenderPrep, StepInfo, + }; + use crate::runtime::RuntimeCore; + use crate::time::Instant; + use crate::window::Missed; + use crate::{Cx, El, Env, Runtime, Tx, el}; + + #[derive(Default)] + struct MockState { + width: f32, + polls: u32, + switch_blend_to: Option<bool>, + } + + fn view(s: &MockState, _: &mut Cx<MockState>) -> El { + el().child(el().key("bar").size(s.width + 12.0, 8.0)) + } + + fn poll(s: &mut MockState, _: f64, tx: &mut Tx) -> bool { + s.polls += 1; + if let Some(next) = s.switch_blend_to.take() { + tx.set_srgb_blend(next); + } + false + } + + #[derive(Clone, Copy, Debug, PartialEq, Eq)] + enum MockDrawable { + Cpu, + Gpu(u32), + } + + #[derive(Clone, Copy, Debug, PartialEq, Eq)] + enum MockPrepared { + Cpu, + HandingOver { gpu: Option<u32> }, + Gpu(u32), + } + + /// Browser-free stand-in for `platform::web::frame::WebFrameHost` sharing the exact + /// `web_math` gate/acquire/miss/reblend decisions through `frame::host_step::run`. + struct MockWebHost { + rt: Runtime<MockState>, + clock: FrameClock, + suspended: bool, + draw: WebDrawKind, + handover_built: bool, + full_redraw: bool, + force_cycle_tick: bool, + renderer_srgb: bool, + reblend_supports_linear: bool, + acquires: VecDeque<WebAcquireStatus>, + next_tex: u32, + step_at: Instant, + submit_at: Instant, + reblend_tried: Option<bool>, + tick: bool, + simulate_native_surface: bool, + fatal_error: Option<&'static str>, + redraw_requested: u32, + reconfigures: u32, + handover_gpu_acquired: u32, + log: Vec<&'static str>, + } + + impl MockWebHost { + fn new(start: Instant, draw: WebDrawKind) -> Self { + let mut rt = Runtime::new(MockState::default(), view, (300.0, 40.0), Env::default()); + rt.poll = Some(poll); + rt.set_system_reduced_motion(false); + rt.wall_start = Some(start); + rt.set_srgb_blend(true); + Self { + rt, + clock: FrameClock::new(start), + suspended: false, + draw, + handover_built: false, + full_redraw: true, + force_cycle_tick: false, + renderer_srgb: true, + reblend_supports_linear: true, + acquires: VecDeque::new(), + next_tex: 1, + step_at: start, + submit_at: start, + reblend_tried: None, + tick: false, + simulate_native_surface: false, + fatal_error: None, + redraw_requested: 0, + reconfigures: 0, + handover_gpu_acquired: 0, + log: Vec::new(), + } + } + + fn acquire_gpu_tex(&mut self) -> Result<u32, Missed> { + let mut retries = 1u8; + loop { + let status = self.acquires.pop_front().unwrap_or(WebAcquireStatus::Ready); + match web_acquire_action(status, retries) { + WebAcquireAction::UseTexture => { + let id = self.next_tex; + self.next_tex += 1; + return Ok(id); + } + WebAcquireAction::ReconfigureAndRetry => { + self.reconfigures += 1; + self.log.push("reconfigure"); + retries -= 1; + } + WebAcquireAction::Miss(missed) => return Err(missed), + } + } + } + } + + impl FrameHost for MockWebHost { + type Drawable = MockDrawable; + type Prepared = MockPrepared; + + fn gate(&mut self) -> Gate { + self.reblend_tried = None; + self.tick = false; + self.fatal_error = None; + let gate = web_frame_gate(self.suspended, self.draw); + self.log.push(if matches!(gate, Gate::Skip) { "gate:skip" } else { "gate:draw" }); + gate + } + + fn needs_reblend(&self) -> bool { + self.draw == WebDrawKind::Gpu && self.renderer_srgb != self.rt.srgb_blend() + } + + fn reblend(&mut self) -> bool { + let target = self.rt.srgb_blend(); + self.reblend_tried = Some(target); + self.log.push("reblend"); + self.renderer_srgb = if target || self.reblend_supports_linear { target } else { true }; + true + } + + fn acquire(&mut self) -> Acquire<MockDrawable> { + match self.draw { + WebDrawKind::Gpu => match self.acquire_gpu_tex() { + Ok(id) => { + self.log.push("acquire:gpu"); + Acquire::Ready(MockDrawable::Gpu(id)) + } + Err(missed) => { + self.log.push("acquire:missed"); + Acquire::Missed(missed) + } + }, + WebDrawKind::Cpu | WebDrawKind::HandingOver { .. } => { + self.log.push("acquire:cpu"); + Acquire::Ready(MockDrawable::Cpu) + } + WebDrawKind::ContextLost | WebDrawKind::Moving => Acquire::Missed(Missed::Unconfigured), + } + } + + fn step_runtime(&mut self) -> StepInfo { + self.log.push("step"); + let full = std::mem::take(&mut self.full_redraw); + let tick = !full && self.draw == WebDrawKind::Gpu && self.force_cycle_tick; + self.tick = tick; + let (animating, dt) = if tick { + self.log.push("step:cycle_tick"); + let dt = self.step_at.saturating_duration_since(self.clock.last()).as_secs_f64(); + self.clock.hold(self.step_at); + (false, dt) + } else { + let (core, mut app) = self.rt.split_mut(); + self.clock.advance_core(core, &mut app, self.step_at, false) + }; + StepInfo { runtime_animating: animating, animating, dt, update_ms: 0.0, presents_at: None } + } + + fn post_step_check(&mut self, _info: &mut StepInfo) -> PostStepCheck { + if self.draw == WebDrawKind::Gpu + && should_post_step_reblend(self.renderer_srgb, self.rt.srgb_blend(), self.reblend_tried) + { + self.log.push("post:reblend"); + PostStepCheck::Reacquire(ReacquireReason::Reblend) + } else { + PostStepCheck::Keep + } + } + + fn prepare_reacquire(&mut self, reason: ReacquireReason, _info: &mut StepInfo) -> bool { + match reason { + ReacquireReason::Reblend => self.reblend(), + ReacquireReason::NativeMaterials => true, + } + } + + fn on_missed(&mut self, missed: Missed, stepped: bool) { + match web_miss_action(missed) { + WebMissAction::Fatal => { + self.log.push("missed:fatal"); + self.fatal_error = Some("WebGPU canvas acquisition failed"); + } + WebMissAction::CoveredOnly => { + self.log.push("missed:occluded"); + if !stepped { self.rt.covered_wake(); } + } + WebMissAction::RetryNextFrame => { + self.log.push("missed:retry"); + if !stepped { self.rt.covered_wake(); } + self.redraw_requested += 1; + } + } + } + + fn sync_after_step(&mut self, _info: &mut StepInfo) { + self.log.push("sync"); + if self.simulate_native_surface { + self.fatal_error = Some("native video surfaces are unsupported on web"); + } + } + + fn prepare_render(&mut self, drawable: MockDrawable, _info: &mut StepInfo) -> RenderPrep<MockPrepared> { + if self.fatal_error.is_some() { + self.log.push("prepare:abort"); + return RenderPrep::Abort; + } + match (self.draw, drawable) { + (WebDrawKind::Cpu, MockDrawable::Cpu) => { + self.log.push("prepare:cpu"); + RenderPrep::Ready(MockPrepared::Cpu) + } + (WebDrawKind::HandingOver { .. }, MockDrawable::Cpu) => { + let gpu = if self.handover_built { + self.handover_gpu_acquired += 1; + self.acquire_gpu_tex().ok() + } else { + None + }; + self.log.push(if gpu.is_some() { "prepare:handover_gpu" } else { "prepare:handover_cpu" }); + RenderPrep::Ready(MockPrepared::HandingOver { gpu }) + } + (WebDrawKind::Gpu, MockDrawable::Gpu(id)) => { + self.log.push("prepare:gpu"); + RenderPrep::Ready(MockPrepared::Gpu(id)) + } + _ => RenderPrep::Abort, + } + } + + fn render(&mut self, _prepared: &mut MockPrepared, _info: &StepInfo) -> bool { + self.log.push("render"); + false + } + + fn submit_and_present(&mut self, _prepared: MockPrepared, _info: &StepInfo) -> Instant { + self.log.push("present"); + self.submit_at + } + + fn present_targets(&mut self) -> (Option<&mut FrameClock>, &mut RuntimeCore) { + (Some(&mut self.clock), self.rt.core_mut()) + } + + fn settle(&mut self, _submitted: Instant, _info: &StepInfo) { + self.log.push("settle"); + } + } + + #[test] + fn gpu_frame_acquires_before_step_and_delays_overrun_on_clock() { + let start = crate::time::now(); + let frame = Duration::from_micros(16_667); + let overrun = Duration::from_millis(50); + let mut host = MockWebHost::new(start, WebDrawKind::Gpu); + + assert_eq!(host_step::run(&mut host), Outcome::Presented); + assert_eq!(host.log, ["gate:draw", "acquire:gpu", "step", "sync", "prepare:gpu", "render", "present", "settle"]); + + // Start a spring on an overrunning frame: host_step::run calls clock.presented_core. + host.rt.update(|s, _| s.width = 200.0); + let f1 = start + frame; + host.step_at = f1; + host.submit_at = f1 + overrun; + assert_eq!(host_step::run(&mut host), Outcome::Presented); + let w1 = host.rt.presented("bar").unwrap().0[2]; + + let f2 = f1 + overrun + frame; + host.step_at = f2; + host.submit_at = f2; + assert_eq!(host_step::run(&mut host), Outcome::Presented); + let w2 = host.rt.presented("bar").unwrap().0[2]; + + // Reference without clock.presented_core: would jump ahead by the 50 ms overrun. + let mut plain_clock = FrameClock::new(start); + let mut plain = Runtime::new(MockState::default(), view, (300.0, 40.0), Env::default()); + plain.set_system_reduced_motion(false); + plain.wall_start = Some(start); + plain_clock.advance(&mut plain, start, false); + plain.update(|s, _| s.width = 200.0); + plain_clock.advance(&mut plain, f1, false); + plain_clock.advance(&mut plain, f2, false); + let undelayed_w2 = plain.presented("bar").unwrap().0[2]; + + assert!(w2 > w1); + assert!(undelayed_w2 - w2 > 5.0, "web host_step must record presentation on clock: w2={w2}, undelayed={undelayed_w2}"); + } + + #[test] + fn gpu_transient_and_outdated_acquire_follow_web_recovery_policy() { + let start = crate::time::now(); + let mut host = MockWebHost::new(start, WebDrawKind::Gpu); + // Transient Timeout: missed before step -> runs covered_wake once, requests redraw, not fatal. + host.acquires = VecDeque::from([WebAcquireStatus::Timeout]); + let polls0 = host.rt.state.polls; + assert_eq!(host_step::run(&mut host), Outcome::Missed); + assert_eq!(host.rt.state.polls, polls0 + 1); + assert_eq!(host.redraw_requested, 1); + assert!(host.fatal_error.is_none()); + assert!(host.full_redraw, "missed acquire before step preserves full_redraw"); + + // Transient Occluded: covered_wake runs, no redraw requested, not fatal. + host.acquires = VecDeque::from([WebAcquireStatus::Occluded]); + assert_eq!(host_step::run(&mut host), Outcome::Missed); + assert_eq!(host.redraw_requested, 1); + assert!(host.fatal_error.is_none()); + + // Single Outdated -> reconfigures and retries once, then presents. + host.log.clear(); + host.acquires = VecDeque::from([WebAcquireStatus::OutdatedOrLost, WebAcquireStatus::Ready]); + assert_eq!(host_step::run(&mut host), Outcome::Presented); + assert_eq!(host.reconfigures, 1); + assert!(host.fatal_error.is_none()); + + // Persistent Lost after reconfigure retry -> fatal error. + host.acquires = VecDeque::from([WebAcquireStatus::OutdatedOrLost, WebAcquireStatus::OutdatedOrLost]); + assert_eq!(host_step::run(&mut host), Outcome::Missed); + assert_eq!(host.reconfigures, 2); + assert_eq!(host.fatal_error, Some("WebGPU canvas acquisition failed")); + } + + #[test] + fn post_step_reblend_reacquires_once_and_does_not_loop_without_srgb_twin() { + let start = crate::time::now(); + let mut host = MockWebHost::new(start, WebDrawKind::Gpu); + // Handler flips srgb_blend during step: drops old drawable, reblends, reacquires once. + host.rt.state.switch_blend_to = Some(false); + assert_eq!(host_step::run(&mut host), Outcome::Presented); + assert_eq!( + host.log, + ["gate:draw", "acquire:gpu", "step", "post:reblend", "reblend", "acquire:gpu", "sync", "prepare:gpu", "render", "present", "settle"] + ); + + // WebGL2 without sRGB twin: renderer stays srgb_blend=true while rt wants false. + // Pre-step reblend tries once; post_step_check must NOT loop re-acquiring. + host.log.clear(); + host.renderer_srgb = true; + host.reblend_supports_linear = false; + assert_eq!(host_step::run(&mut host), Outcome::Presented); + assert_eq!( + host.log, + ["gate:draw", "reblend", "acquire:gpu", "step", "sync", "prepare:gpu", "render", "present", "settle"] + ); + } + + #[test] + fn cycle_tick_handover_and_native_surface_abort_follow_host_step() { + let start = crate::time::now(); + // Cycle tick holds clock without advancing runtime poll. + let mut gpu_host = MockWebHost::new(start, WebDrawKind::Gpu); + assert_eq!(host_step::run(&mut gpu_host), Outcome::Presented); + let polls_after_first = gpu_host.rt.state.polls; + gpu_host.log.clear(); + gpu_host.force_cycle_tick = true; + gpu_host.step_at = start + Duration::from_millis(16); + gpu_host.submit_at = gpu_host.step_at; + assert_eq!(host_step::run(&mut gpu_host), Outcome::Presented); + assert_eq!(gpu_host.rt.state.polls, polls_after_first, "paint_cycle_tick skips full runtime step"); + assert!(gpu_host.log.contains(&"step:cycle_tick")); + assert_eq!(gpu_host.clock.last(), gpu_host.step_at); + + // HandingOver acquires GPU texture only during prepare_render when `built` is true. + let mut handover = MockWebHost::new(start, WebDrawKind::HandingOver { waiting_for_gpu: false }); + assert_eq!(host_step::run(&mut handover), Outcome::Presented); + assert_eq!(handover.handover_gpu_acquired, 0); + assert!(handover.log.contains(&"prepare:handover_cpu")); + + handover.log.clear(); + handover.handover_built = true; + assert_eq!(host_step::run(&mut handover), Outcome::Presented); + assert_eq!(handover.handover_gpu_acquired, 1); + assert_eq!(handover.log, ["gate:draw", "acquire:cpu", "step", "sync", "prepare:handover_gpu", "render", "present", "settle"]); + + // Waiting on GPU handover or ContextLost skips at gate without stepping. + handover.log.clear(); + handover.draw = WebDrawKind::HandingOver { waiting_for_gpu: true }; + assert_eq!(host_step::run(&mut handover), Outcome::Skipped); + assert_eq!(handover.log, ["gate:skip"]); + + handover.log.clear(); + handover.draw = WebDrawKind::ContextLost; + assert_eq!(host_step::run(&mut handover), Outcome::Skipped); + assert_eq!(handover.log, ["gate:skip"]); + + // Native video surface aborts in prepare_render without presenting or settling. + let mut cpu = MockWebHost::new(start, WebDrawKind::Cpu); + cpu.simulate_native_surface = true; + assert_eq!(host_step::run(&mut cpu), Outcome::Aborted); + assert_eq!(cpu.fatal_error, Some("native video surfaces are unsupported on web")); + assert_eq!(cpu.log, ["gate:draw", "acquire:cpu", "step", "sync", "prepare:abort"]); + } +} diff --git a/app/vendor/rune/crates/rune/src/platform/win32.rs b/app/vendor/rune/crates/rune/src/platform/win32.rs new file mode 100644 index 0000000..da3820b --- /dev/null +++ b/app/vendor/rune/crates/rune/src/platform/win32.rs @@ -0,0 +1,547 @@ +//! Win32 pieces winit 0.30 doesn't expose, for overlays. + +use winit::raw_window_handle::{HasWindowHandle, RawWindowHandle}; +use windows_sys::Win32::Foundation::HWND; +use windows_sys::Win32::Foundation::{LPARAM, LRESULT, POINT, WPARAM}; +use windows_sys::Win32::UI::Shell::{DefSubclassProc, RemoveWindowSubclass, SetWindowSubclass}; +use windows_sys::Win32::UI::WindowsAndMessaging::*; +use std::{cell::{Cell, RefCell}, collections::VecDeque, rc::Rc}; +use crate::{OverlayInput, OverlayLevel, OverlayOptions, OverlaySupport}; +use windows_sys::Win32::UI::WindowsAndMessaging::{ + GWL_EXSTYLE, GetWindowLongPtrW, HWND_TOPMOST, SW_HIDE, SW_SHOWNOACTIVATE, SWP_NOACTIVATE, SWP_NOMOVE, SWP_NOSIZE, + SetWindowLongPtrW, SetWindowPos, ShowWindow, WS_EX_LAYERED, WS_EX_NOACTIVATE, WS_EX_TOOLWINDOW, WS_EX_TOPMOST, + WS_EX_TRANSPARENT, +}; + +mod cloak; +pub(crate) mod dark_mode; +pub(crate) mod dcomp_handover; +pub(crate) mod dib; +mod dpi_drag; +pub(crate) mod drop_target; +mod frame; +pub(crate) mod jump_list; +pub(crate) mod occlusion; +mod placement; +pub(crate) mod press_point; +mod pointer; +#[cfg(not(feature = "segmenter-dictionaries"))] +pub(crate) use rune_text::segmenter; +pub(crate) mod session_lock; +pub(crate) mod taskbar; + +pub(crate) use cloak::Cloak; +pub(crate) use dpi_drag::follow_suggested_rect; +pub(crate) use dpi_drag::in_size_move; +pub(crate) use frame::CustomFrame; +pub(crate) use frame::has_window_menu; +pub(crate) use frame::request_inner_size; +pub(crate) use frame::window_menu; +pub(crate) use placement::restore_frame; + +/// Loads a Windows system DLL from System32 only, never from the application directory or CWD. +/// Rejects names containing path separators or drive prefixes. +#[allow(unsafe_code)] +pub(crate) fn load_system_dll(name: &str) -> windows_sys::Win32::Foundation::HMODULE { + use windows_sys::Win32::System::LibraryLoader::{LOAD_LIBRARY_SEARCH_SYSTEM32, LoadLibraryExW}; + if name.is_empty() || name.contains(['\\', '/', ':']) { + return std::ptr::null_mut(); + } + let wide: Vec<u16> = name.encode_utf16().chain(Some(0)).collect(); + // SAFETY: `wide` is NUL-terminated and `LOAD_LIBRARY_SEARCH_SYSTEM32` restricts the search + // path to System32. + unsafe { LoadLibraryExW(wide.as_ptr(), std::ptr::null_mut(), LOAD_LIBRARY_SEARCH_SYSTEM32) } +} + +pub(crate) fn hwnd(window: &winit::window::Window) -> Option<HWND> { + let RawWindowHandle::Win32(h) = window.window_handle().ok()?.as_raw() else { return None }; + Some(h.hwnd.get() as HWND) +} + +/// When the display shows its next refresh after `now`, from DWM's timing (`now` plus a 60 Hz +/// frame when DWM won't say). +#[allow(unsafe_code)] +pub(crate) fn next_vblank(now: std::time::Instant) -> std::time::Instant { + use windows_sys::Win32::Graphics::Dwm::{DWM_TIMING_INFO, DwmGetCompositionTimingInfo}; + // The first ask comes from the window's first frame, as DWM shows the window: the query then + // waits on DWM for 2-2.5 ms, in front of the first input. A refresh from now does for that one. + static ASKED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + if !ASKED.swap(true, std::sync::atomic::Ordering::Relaxed) { + return now + std::time::Duration::from_micros(16_667); + } + use windows_sys::Win32::System::Performance::{QueryPerformanceCounter, QueryPerformanceFrequency}; + // SAFETY: plain out-parameters. + unsafe { + let mut t: DWM_TIMING_INFO = std::mem::zeroed(); + t.cbSize = size_of::<DWM_TIMING_INFO>() as u32; + let (mut qpc, mut freq) = (0i64, 0i64); + if DwmGetCompositionTimingInfo(std::ptr::null_mut(), &mut t) < 0 || t.qpcRefreshPeriod == 0 + || QueryPerformanceCounter(&mut qpc) == 0 || QueryPerformanceFrequency(&mut freq) == 0 || freq <= 0 { + return now + std::time::Duration::from_micros(16_667); + } + let (period, last) = (t.qpcRefreshPeriod as i64, t.qpcVBlank as i64); + let next = last + ((qpc - last) / period + 1) * period; + now + std::time::Duration::from_nanos(((next - qpc).max(0) as i128 * 1_000_000_000 / freq as i128) as u64) + } +} + +/// Whether a screen reader is running (`SPI_GETSCREENREADER`). +#[allow(unsafe_code)] +pub(crate) fn screen_reader() -> bool { + let mut on = 0i32; + // SAFETY: SPI_GETSCREENREADER writes one BOOL. + unsafe { SystemParametersInfoW(SPI_GETSCREENREADER, 0, (&raw mut on).cast(), 0) != 0 && on != 0 } +} + +/// Whether the system asks `window` to paint part of itself again (an update region): it threw +/// away what the window showed, as when a window covered whole comes back. +#[allow(unsafe_code)] +pub(crate) fn repaint_owed(window: &winit::window::Window) -> bool { + use windows_sys::Win32::Graphics::Gdi::GetUpdateRect; + let Some(hwnd) = hwnd(window) else { return false }; + // SAFETY: a live window this thread owns; no rectangle asked for. + unsafe { GetUpdateRect(hwnd, std::ptr::null_mut(), 0) != 0 } +} + +/// Raises D3D12's "D3D Background Thread"s, once, from idle priority to below normal, on a thread of +/// its own. D3D12 starts them at idle priority (base 1) for the driver's shader work, and a thread +/// has to run to end: on a busy machine they sat Ready, never scheduled, after the process was +/// ended (a kill, the uninstaller closing running copies), keeping it alive for seconds, once +/// 106 s. Called once a first GPU frame is done; a second pass 2 s later takes any D3D12 started +/// since. Returns how many it raised. +pub(crate) fn unidle_d3d_threads_soon() { + static ONCE: std::sync::Once = std::sync::Once::new(); + ONCE.call_once(|| { std::thread::Builder::new().name("rune-unidle".into()).spawn(|| { unidle_d3d_threads(); std::thread::sleep(std::time::Duration::from_secs(2)); unidle_d3d_threads(); }).ok(); }); +} + +/// This process's threads by name and priority, counted (`name (priority) xN`, unnamed ones as +/// `?`), for saying what a quit waits on. +#[allow(unsafe_code)] +pub(crate) fn threads_summary() -> String { + let mut seen: Vec<(String, i32, usize)> = Vec::new(); + for_each_own_thread(|thread| { + let name = thread_name(thread).filter(|n| !n.is_empty()).unwrap_or_else(|| "?".into()); + // SAFETY: a thread handle `for_each_own_thread` opened for querying. + let priority = unsafe { windows_sys::Win32::System::Threading::GetThreadPriority(thread) }; + match seen.iter_mut().find(|(n, p, _)| *n == name && *p == priority) { + Some(s) => s.2 += 1, + None => seen.push((name, priority, 1)), + } + }); + seen.iter().map(|(n, p, c)| if *c > 1 { format!("{n} ({p}) x{c}") } else { format!("{n} ({p})") }).collect::<Vec<_>>().join(", ") +} + +/// Raises this process's threads whose name passes `named` and whose priority is under `floor` to +/// `floor` (a `THREAD_PRIORITY_*`); returns how many. Walks only this process's threads. +#[allow(unsafe_code)] +pub fn raise_threads(named: impl Fn(&str) -> bool, floor: i32) -> usize { + use windows_sys::Win32::System::Threading::{GetThreadPriority, SetThreadPriority}; + let mut raised = 0; + for_each_own_thread(|thread| { + // SAFETY: a thread handle `for_each_own_thread` opened for querying and setting. + unsafe { + if GetThreadPriority(thread) < floor && thread_name(thread).is_some_and(|n| named(&n)) && SetThreadPriority(thread, floor) != 0 { + raised += 1; + } + } + }); + raised +} + +fn unidle_d3d_threads() -> usize { + raise_threads(|name| name.starts_with("D3D Background Thread"), windows_sys::Win32::System::Threading::THREAD_PRIORITY_BELOW_NORMAL) +} + +/// Calls `f` with a handle to each of this process's threads, open for querying and setting its +/// priority, walking this process's own thread list (`NtGetNextThread`). A Toolhelp snapshot lists +/// every thread on the machine: 67-75 ms a walk on a busy one, twice per launch. +#[allow(unsafe_code)] +fn for_each_own_thread(mut f: impl FnMut(windows_sys::Win32::Foundation::HANDLE)) { + use windows_sys::Win32::Foundation::{CloseHandle, HANDLE}; + use windows_sys::Win32::System::LibraryLoader::{GetModuleHandleW, GetProcAddress}; + use windows_sys::Win32::System::Threading::{GetCurrentProcess, THREAD_QUERY_LIMITED_INFORMATION, THREAD_SET_INFORMATION}; + type NextThread = unsafe extern "system" fn(HANDLE, HANDLE, u32, u32, u32, *mut HANDLE) -> i32; + static NEXT: std::sync::OnceLock<Option<NextThread>> = std::sync::OnceLock::new(); + // SAFETY: ntdll is loaded in every process; NtGetNextThread has this signature since Vista. + let next = *NEXT.get_or_init(|| unsafe { + let ntdll = GetModuleHandleW("ntdll.dll\0".encode_utf16().collect::<Vec<_>>().as_ptr()); + if ntdll.is_null() { return None; } + GetProcAddress(ntdll, c"NtGetNextThread".as_ptr().cast()).map(|p| std::mem::transmute::<_, NextThread>(p)) + }); + let Some(next) = next else { return }; + let mut prev: HANDLE = std::ptr::null_mut(); + loop { + let mut thread: HANDLE = std::ptr::null_mut(); + // SAFETY: this process's pseudo-handle and the last thread handle it returned (or none); + // each handle it returns is closed once the next is taken. + let status = unsafe { next(GetCurrentProcess(), prev, THREAD_QUERY_LIMITED_INFORMATION | THREAD_SET_INFORMATION, 0, 0, &mut thread) }; + // SAFETY: `prev` is a non-null thread handle returned by the prior `NtGetNextThread` call and is closed once here. + if !prev.is_null() { unsafe { CloseHandle(prev) }; } + if status < 0 || thread.is_null() { return; } + f(thread); + prev = thread; + } +} + +/// A thread's description (`SetThreadDescription`), if it has one. +#[allow(unsafe_code)] +fn thread_name(thread: windows_sys::Win32::Foundation::HANDLE) -> Option<String> { + use windows_sys::Win32::Foundation::LocalFree; + use windows_sys::Win32::System::Threading::GetThreadDescription; + let mut desc = std::ptr::null_mut(); + // SAFETY: a live thread handle; the description is read to its NUL and freed with LocalFree. + unsafe { + if GetThreadDescription(thread, &mut desc) < 0 || desc.is_null() { return None; } + let len = (0..).take_while(|&i| *desc.add(i) != 0).count(); + let name = String::from_utf16_lossy(std::slice::from_raw_parts(desc, len)); + LocalFree(desc.cast()); + Some(name) + } +} + +/// Drops the paint the system still owes `window`, which the loop just painted itself. +#[allow(unsafe_code)] +pub(crate) fn drop_paint(window: &winit::window::Window) { + use windows_sys::Win32::Graphics::Gdi::{RDW_NOINTERNALPAINT, RedrawWindow}; + let Some(hwnd) = hwnd(window) else { return }; + // SAFETY: a live window this thread owns; no region or rectangle. + unsafe { RedrawWindow(hwnd, std::ptr::null(), std::ptr::null_mut(), RDW_NOINTERNALPAINT) }; +} + +#[allow(unsafe_code)] +pub(crate) fn pointer_position() -> Option<(i32, i32)> { + let mut p = POINT { x: 0, y: 0 }; + // SAFETY: `p` is a valid, aligned local `POINT` out-parameter. + (unsafe { GetCursorPos(&mut p) } != 0).then_some((p.x, p.y)) +} + +struct Input { + hwnd: HWND, + regions: RefCell<Vec<[f32; 4]>>, + scale: Cell<f32>, + clicks: RefCell<VecDeque<(bool, (f32, f32))>>, + captured: Cell<bool>, + visible: Cell<bool>, + input: Cell<OverlayInput>, + follow: Cell<bool>, + level: OverlayLevel, + /// Fading out (`OverlayWindow::fade`): every click goes through. + fading: Cell<bool>, +} +impl Input { + fn track(&self) -> bool { self.input.get() == OverlayInput::Regions || self.follow.get() } + #[allow(unsafe_code)] + fn local(&self, mut point: POINT) -> (f32, f32) { + // SAFETY: `self.hwnd` is a live window owned by this thread and `point` is a valid local `POINT`. + unsafe { windows_sys::Win32::Graphics::Gdi::ScreenToClient(self.hwnd, &mut point); } + (point.x as f32 / self.scale.get(), point.y as f32 / self.scale.get()) + } + fn hit(&self, point: (f32, f32)) -> bool { + !self.fading.get() && (self.captured.get() || match self.input.get() { + OverlayInput::All => true, + OverlayInput::Regions => self.regions.borrow().iter().any(|r| crate::overlay::options::contains(*r, point.0, point.1)), + _ => false, + }) + } + #[allow(unsafe_code)] + fn observe(&self, point: POINT) { + if !self.visible.get() { return; } + let local = self.local(point); + { + // SAFETY: `self.hwnd` is a live window owned by this thread; `GWL_EXSTYLE` toggles `WS_EX_TRANSPARENT`. + unsafe { + let style = GetWindowLongPtrW(self.hwnd, GWL_EXSTYLE) as u32; + let next = if self.hit(local) { style & !WS_EX_TRANSPARENT } else { style | WS_EX_TRANSPARENT }; + if next != style { SetWindowLongPtrW(self.hwnd, GWL_EXSTYLE, next as isize); } + } + } + } +} + +thread_local! { + static INPUTS: RefCell<Vec<Rc<Input>>> = const { RefCell::new(Vec::new()) }; +} + +#[allow(unsafe_code)] +unsafe extern "system" fn subclass(hwnd: HWND, message: u32, wparam: WPARAM, lparam: LPARAM, _: usize, data: usize) -> LRESULT { + let ptr = data as *const Input; + if message == WM_NCDESTROY { + // SAFETY: removes this subclass; if it was still installed, reclaims the ref `new` gave it. + unsafe { + if RemoveWindowSubclass(hwnd, Some(subclass), 0x52554e45) != 0 { + drop(Rc::from_raw(ptr)); + } + return DefSubclassProc(hwnd, message, wparam, lparam); + } + } + // Hold a strong ref across `DefSubclassProc` so dropping `OverlayWindow` re-entrantly + // cannot free `Input` while this frame is still on the stack. + // SAFETY: `ptr` is the live `Rc<Input>` owned by the subclass until removal. + let input: Rc<Input> = unsafe { + Rc::increment_strong_count(ptr); + Rc::from_raw(ptr) + }; + match message { + WM_NCHITTEST => { + let p = POINT { x: lparam as i16 as i32, y: (lparam >> 16) as i16 as i32 }; + return if input.hit(input.local(p)) { HTCLIENT as LRESULT } else { HTTRANSPARENT as LRESULT }; + } + WM_LBUTTONDOWN | WM_LBUTTONDBLCLK | WM_LBUTTONUP => { + let down = message != WM_LBUTTONUP; + input.captured.set(down); + let point = (lparam as i16 as f32 / input.scale.get(), (lparam >> 16) as i16 as f32 / input.scale.get()); + input.clicks.borrow_mut().push_back((down, point)); + } + WM_CAPTURECHANGED => input.captured.set(false), + _ => {} + } + // SAFETY: forwards the unhandled message to the next procedure in this window's subclass chain. + unsafe { DefSubclassProc(hwnd, message, wparam, lparam) } +} + +/// Per-window input owner; the shared low-level hook observes but never consumes events. +pub(crate) struct OverlayWindow { + watch: Option<crate::platform::win32::pointer::MouseWatch>, + wake: Option<crate::Waker>, + input: Rc<Input>, + observing: bool, + exclusion: OverlaySupport, + keys: crate::KeyPolicy, +} +impl OverlayWindow { + #[allow(unsafe_code)] + pub fn new(window: &winit::window::Window, interactive: bool, options: &OverlayOptions, wake: Option<crate::Waker>) -> Result<Self, String> { + let hwnd = hwnd(window).ok_or("the overlay window has no Win32 handle")?; + let mode = options.input.resolved(interactive); + overlay_styles(hwnd, mode, options.keys)?; + let exclusion = if options.exclude_from_capture { + // SAFETY: `hwnd` is a live window owned by this thread; `WDA_EXCLUDEFROMCAPTURE` is a valid display affinity flag. + if unsafe { SetWindowDisplayAffinity(hwnd, WDA_EXCLUDEFROMCAPTURE) } != 0 { OverlaySupport::Requested } else { OverlaySupport::Failed } + } else { OverlaySupport::Unknown }; + let input = Rc::new(Input { hwnd, regions: RefCell::default(), scale: Cell::new(window.scale_factor() as f32), clicks: RefCell::default(), captured: Cell::new(false), visible: Cell::new(false), input: Cell::new(mode), follow: Cell::new(options.follow_pointer), level: options.level, fading: Cell::new(false) }); + let data = Rc::into_raw(input.clone()); + // SAFETY: `data` is reclaimed exactly once, either by `Drop` or by `WM_NCDESTROY`, + // whichever succeeds in removing the subclass. + if unsafe { SetWindowSubclass(hwnd, Some(subclass), 0x52554e45, data as usize) } == 0 { + // SAFETY: `SetWindowSubclass` failed, so no subclass took ownership of `data`; reclaim the `Rc` created by `into_raw` above. + unsafe { drop(Rc::from_raw(data)); } + return Err(format!("SetWindowSubclass failed: {}", last_error())); + } + Ok(Self { input, observing: false, exclusion, watch: None, wake, keys: options.keys }) + } + pub fn capture_exclusion(&self) -> OverlaySupport { self.exclusion } + #[allow(unsafe_code)] + pub fn set_capture_exclusion(&mut self, exclude: bool) -> OverlaySupport { + let affinity = if exclude { WDA_EXCLUDEFROMCAPTURE } else { WDA_NONE }; + // SAFETY: `self.input.hwnd` is a live window owned by this thread and `affinity` is a valid `WDA_*` constant. + let applied = unsafe { SetWindowDisplayAffinity(self.input.hwnd, affinity) } != 0; + self.exclusion = match (exclude, applied) { (true, true) => OverlaySupport::Requested, (true, false) => OverlaySupport::Failed, (false, _) => OverlaySupport::Unknown }; + self.exclusion + } + pub fn global_pointer(&self) -> OverlaySupport { + if self.input.track() && self.watch.as_ref().is_none_or(|w| !w.supported()) { OverlaySupport::Failed } + else { OverlaySupport::Supported } + } + pub fn take_pointer(&self) -> Option<(f32, f32)> { + let (x, y) = self.watch.as_ref()?.take()?; + self.input.observe(POINT { x, y }); + Some(self.input.local(POINT { x, y })) + } + pub fn set_input(&mut self, input: OverlayInput) { + self.input.input.set(input); + self.refresh_watch(); + if let Some((x, y)) = pointer_position() { self.input.observe(POINT { x, y }); } + } + pub fn set_follow_pointer(&mut self, follow: bool) { self.input.follow.set(follow); self.refresh_watch(); } + + fn refresh_watch(&mut self) { + if self.input.visible.get() && self.input.track() { + if self.watch.is_none() { self.watch = Some(crate::platform::win32::pointer::MouseWatch::new(self.wake.clone())); } + if let Some(watch) = &self.watch { watch.geometry(self.input.hwnd, self.input.follow.get()); } + } else { self.watch.take(); } + } + pub fn take_click(&self, down: bool) -> Option<(f32, f32)> { + self.input.clicks.borrow_mut().pop_front().filter(|(pressed, _)| *pressed == down).map(|(_, point)| point) + } + pub fn set_regions(&self, regions: &[[f32; 4]], scale: f32) { + self.input.scale.set(scale); + if self.input.regions.borrow().as_slice() != regions { *self.input.regions.borrow_mut() = regions.to_vec(); } + if let Some(watch) = &self.watch { watch.geometry(self.input.hwnd, self.input.follow.get()); } + if let Some((x, y)) = pointer_position() { + self.input.observe(POINT { x, y }); + if let Some(watch) = &self.watch { watch.observe((x, y)); } + } + } + /// Puts the window on screen without activating it, above other topmost windows. Rune shows + /// and hides overlays with Win32 calls alone: winit never sees either, and a winit + /// visibility change would also reset these styles. Errs when Windows leaves it hidden. + #[allow(unsafe_code)] + pub fn show(&mut self) -> Result<(), String> { + let hwnd = self.input.hwnd; + // Opaque again, after any fade-out. + self.input.fading.set(false); + overlay_styles(hwnd, self.input.input.get(), self.keys)?; + // SAFETY: Win32 calls on a live window owned by this thread. + let visible = unsafe { + ShowWindow(hwnd, SW_SHOWNOACTIVATE); + SetWindowPos(hwnd, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE); + IsWindowVisible(hwnd) != 0 + }; + if !visible { return Err("ShowWindow left the overlay window hidden".into()); } + let mut cloaked = 0u32; + // SAFETY: DWMWA_CLOAKED writes one u32 into `cloaked`. + let read = unsafe { + windows_sys::Win32::Graphics::Dwm::DwmGetWindowAttribute(hwnd, windows_sys::Win32::Graphics::Dwm::DWMWA_CLOAKED as u32, (&raw mut cloaked).cast(), 4) + }; + if read >= 0 && cloaked != 0 { return Err(format!("Windows cloaked the overlay window (DWMWA_CLOAKED {cloaked:#x})")); } + self.input.visible.set(true); + raise_levels(); + if self.observing { return Ok(()); } + INPUTS.with(|inputs| inputs.borrow_mut().push(self.input.clone())); + self.refresh_watch(); + self.observing = true; + if let Some((x, y)) = pointer_position() { self.input.observe(POINT { x, y }); } + Ok(()) + } + /// Gives the shown window the foreground and the keys, for `request_keys`, when Windows lets + /// this process take the foreground (it just had the user's input, or was given the right); + /// otherwise the window stays as it is and takes the keys when clicked. False when its policy + /// takes no keys or this process may not take the foreground. + pub fn request_keys(&self) -> bool { + self.input.visible.get() && crate::overlay::keys::can_take_keys(self.keys) && cloak::take_foreground(self.input.hwnd) + } + /// Keeps the shown window up at `alpha` (255 opaque) while it fades out, taking no clicks. + #[allow(unsafe_code)] + pub fn fade(&self, alpha: u8) { + if !self.input.fading.replace(true) && let Some((x, y)) = pointer_position() { + self.input.observe(POINT { x, y }); + } + // SAFETY: a Win32 call on a live layered window owned by this thread. + unsafe { SetLayeredWindowAttributes(self.input.hwnd, 0, alpha, LWA_ALPHA); } + } + #[allow(unsafe_code)] + pub fn hide(&mut self) { + // SAFETY: a Win32 call on a live window owned by this thread. + unsafe { ShowWindow(self.input.hwnd, SW_HIDE); } + self.input.visible.set(false); + self.input.captured.set(false); + self.watch.take(); + self.input.clicks.borrow_mut().clear(); + if !self.observing { return; } + INPUTS.with(|inputs| inputs.borrow_mut().retain(|i| !Rc::ptr_eq(i, &self.input))); + self.observing = false; + } +} +impl Drop for OverlayWindow { + #[allow(unsafe_code)] + fn drop(&mut self) { + self.hide(); + // SAFETY: removes the subclass installed in `new`; if it was still installed (not already + // removed by `WM_NCDESTROY`), reclaims the `Rc` reference owned by the subclass. + unsafe { + if RemoveWindowSubclass(self.input.hwnd, Some(subclass), 0x52554e45) != 0 { + drop(Rc::from_raw(Rc::as_ptr(&self.input))); + } + } + } +} + +/// A layered, topmost tool window that never activates, unless its policy takes keys +/// (`KeyPolicy::OnDemand`: a click or `request_keys` activates it); unless `mode` takes every +/// click, every click goes through (`Input::observe` lifts that over input regions). Windows composes a +/// layered window, its DirectComposition content included, only once it has layered +/// attributes: without them it stays invisible however often it is shown (#510 in Hex). +/// Opaque attributes leave the content's own alpha as the only transparency. +#[allow(unsafe_code)] +fn overlay_styles(hwnd: HWND, mode: OverlayInput, keys: crate::KeyPolicy) -> Result<(), String> { + let through = if mode == OverlayInput::All { 0 } else { WS_EX_TRANSPARENT }; + let no_activate = if crate::overlay::keys::can_take_keys(keys) { 0 } else { WS_EX_NOACTIVATE }; + // SAFETY: style changes on a live window owned by this thread. + unsafe { + let style = GetWindowLongPtrW(hwnd, GWL_EXSTYLE) as u32; + let next = style | WS_EX_LAYERED | no_activate | WS_EX_TOOLWINDOW | WS_EX_TOPMOST | through; + if next != style { SetWindowLongPtrW(hwnd, GWL_EXSTYLE, next as isize); } + if SetLayeredWindowAttributes(hwnd, 0, 255, LWA_ALPHA) == 0 { + return Err(format!("SetLayeredWindowAttributes failed: {}", last_error())); + } + } + Ok(()) +} + +#[allow(unsafe_code)] +fn last_error() -> String { + // SAFETY: reads this thread's last Win32 error. + let code = unsafe { windows_sys::Win32::Foundation::GetLastError() }; + format!("Win32 error {code}") +} + +/// Whether `hwnd` is a shown overlay's window, whatever its `KeyPolicy`. +pub(crate) fn is_overlay(hwnd: HWND) -> bool { + INPUTS.with(|inputs| inputs.borrow().iter().any(|input| input.hwnd == hwnd)) +} + +/// Keeps shown overlays above one another by level. +#[allow(unsafe_code)] +fn raise_levels() { + let inputs = INPUTS.with(|inputs| inputs.borrow().clone()); + for level in [OverlayLevel::Status, OverlayLevel::AboveStatus, OverlayLevel::AboveOverlays] { + for input in &inputs { + if input.visible.get() && input.level == level { + // SAFETY: a Win32 call on a live window owned by this thread. + unsafe { SetWindowPos(input.hwnd, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE); } + } + } + } +} + +/// `monitor`'s work area (without its taskbar and app bars) as top and bottom, in physical +/// desktop pixels. +#[allow(unsafe_code)] +pub(crate) fn work_area(monitor: &winit::monitor::MonitorHandle) -> Option<(i32, i32)> { + use winit::platform::windows::MonitorHandleExtWindows; + use windows_sys::Win32::Graphics::Gdi::{GetMonitorInfoW, MONITORINFO}; + // SAFETY: MONITORINFO is plain data; all zeros is valid before cbSize is set. + let mut info: MONITORINFO = unsafe { std::mem::zeroed() }; + info.cbSize = std::mem::size_of::<MONITORINFO>() as u32; + // SAFETY: GetMonitorInfoW fills `info`, whose cbSize says which struct it is. + (unsafe { GetMonitorInfoW(monitor.hmonitor() as _, &mut info) } != 0).then_some((info.rcWork.top, info.rcWork.bottom)) +} + +/// Destroys this thread's windows at once, for a fast exit: each gets the default window procedure +/// first, so neither winit's nor a subclass runs while the process is ending. +#[allow(unsafe_code)] +pub(crate) fn destroy_own_windows() { + use windows_sys::Win32::Foundation::{HWND, LPARAM, TRUE}; + use windows_sys::Win32::System::Threading::GetCurrentThreadId; + use windows_sys::Win32::UI::WindowsAndMessaging::EnumThreadWindows; + use windows_sys::core::BOOL; + unsafe extern "system" fn add(hwnd: HWND, list: LPARAM) -> BOOL { + // SAFETY: `list` is the Vec `destroy_own_windows` passes, alive for the enumeration. + unsafe { (*(list as *mut Vec<HWND>)).push(hwnd) }; + TRUE + } + let mut windows: Vec<HWND> = Vec::new(); + // SAFETY: this thread's own top-level windows; each is destroyed by the thread that made it. + unsafe { + EnumThreadWindows(GetCurrentThreadId(), Some(add), (&raw mut windows) as LPARAM); + } + for hwnd in windows { destroy(hwnd); } +} + +/// Destroys `window` at once, for the last window of an app that ends fast (`Host::close`): +/// what's left of the quit runs without it. +pub(crate) fn destroy_window_now(window: &winit::window::Window) { + if let Some(hwnd) = hwnd(window) { destroy(hwnd); } +} + +/// Destroys `hwnd` with the default window procedure in place, so neither winit's nor a subclass +/// runs while the process is ending. +#[allow(unsafe_code)] +fn destroy(hwnd: windows_sys::Win32::Foundation::HWND) { + use windows_sys::Win32::UI::WindowsAndMessaging::{DefWindowProcW, DestroyWindow, GWLP_WNDPROC, SetWindowLongPtrW}; + // SAFETY: a window of this thread's; nothing of this process's uses it after. + unsafe { + SetWindowLongPtrW(hwnd, GWLP_WNDPROC, DefWindowProcW as *const () as usize as isize); + DestroyWindow(hwnd); + } +} \ No newline at end of file diff --git a/app/vendor/rune/crates/rune/src/platform/win32/cloak.rs b/app/vendor/rune/crates/rune/src/platform/win32/cloak.rs new file mode 100644 index 0000000..e6b1c39 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/platform/win32/cloak.rs @@ -0,0 +1,169 @@ +//! Keeps a window off screen until its first frame lands. Windows shows a window before +//! anything presents into it, and DWM fills that empty client area white for a frame or more +//! (Hex #850). Cloaked, DWM composes the window and it takes paints and presents, but nothing +//! of it reaches the screen. As OpenCode Desktop's windows stay hidden until their content is +//! ready, or a timeout shows them anyway (`packages/desktop/src/main/windows/reveal-machine.ts`). +//! +//! A window that should take the focus doesn't take it as it shows: activating it starts the +//! thread's text services (TSF), about 7,500 µs on the UI thread, and that would come before the +//! frame. It shows without activating and activates as the cloak lifts, once its frame is up. + +#![allow(unsafe_code)] + +use std::cell::Cell; +use std::time::Instant; + +use windows_sys::Win32::Graphics::Dwm::{DWMWA_CLOAK, DwmSetWindowAttribute}; + +/// Whether DWM keeps the window off screen. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(crate) enum CloakState { + /// On screen (or hidden the ordinary way). + #[default] + Lifted, + /// Cloaked until its frame lands, or `until` at the latest; `activate` when it takes the + /// focus as it comes on screen. + Held { until: Instant, activate: bool }, +} + +pub(crate) enum CloakEvent { + /// Shown before its frame: cloak until `until` at the latest, then activate it if asked. + Hold { until: Instant, activate: bool }, + /// Making the GPU took part of the wait: give up at `until` instead. + Extend { until: Instant }, + /// Its frame landed. + Lift, + /// It hid: off without taking the focus. + Hidden, + /// The loop turned at `now`. + Tick { now: Instant }, +} + +/// What a cloak transition asks DWM for. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum CloakEffect { + None, + Cloak, + /// Uncloak, and activate the window when the cloak was asked to. + Uncloak { activate: bool }, +} + +impl CloakState { + pub(crate) fn step(self, event: CloakEvent) -> (CloakState, CloakEffect) { + match (self, event) { + (CloakState::Lifted, CloakEvent::Hold { until, activate }) => (CloakState::Held { until, activate }, CloakEffect::Cloak), + (CloakState::Held { activate: was, .. }, CloakEvent::Hold { until, activate }) => (CloakState::Held { until, activate: was || activate }, CloakEffect::None), + (CloakState::Held { activate, .. }, CloakEvent::Extend { until }) => (CloakState::Held { until, activate }, CloakEffect::None), + (CloakState::Held { activate, .. }, CloakEvent::Lift) => (CloakState::Lifted, CloakEffect::Uncloak { activate }), + (CloakState::Held { .. }, CloakEvent::Hidden) => (CloakState::Lifted, CloakEffect::Uncloak { activate: false }), + (CloakState::Held { until, activate }, CloakEvent::Tick { now }) if until <= now => (CloakState::Lifted, CloakEffect::Uncloak { activate }), + (state, _) => (state, CloakEffect::None), + } + } +} + +/// A window's cloak. +#[derive(Default)] +pub(crate) struct Cloak { + state: Cell<CloakState>, +} + +impl Cloak { + /// Cloaks the window until `lift`, or `until` at the latest; with `activate` it takes + /// the focus as the cloak lifts. + pub(crate) fn hold(&self, window: &winit::window::Window, until: Instant, activate: bool) { self.apply(window, CloakEvent::Hold { until, activate }); } + + pub(crate) fn held(&self) -> bool { self.state.get() != CloakState::Lifted } + + /// Moves a held cloak's deadline, as when making the GPU took part of it. + pub(crate) fn extend(&self, until: Instant) { + self.state.set(self.state.get().step(CloakEvent::Extend { until }).0); + } + + /// When the cloak gives up on a frame. + pub(crate) fn deadline(&self) -> Option<Instant> { + match self.state.get() { + CloakState::Held { until, .. } => Some(until), + CloakState::Lifted => None, + } + } + + /// Uncloaks: its frame landed. + pub(crate) fn lift(&self, window: &winit::window::Window) { self.apply(window, CloakEvent::Lift); } + + /// Uncloaks a window that hid, without activating it. + pub(crate) fn hidden(&self, window: &winit::window::Window) { self.apply(window, CloakEvent::Hidden); } + + /// Uncloaks once `now` is past the deadline. + pub(crate) fn lift_if_due(&self, window: &winit::window::Window, now: Instant) { self.apply(window, CloakEvent::Tick { now }); } + + fn apply(&self, window: &winit::window::Window, event: CloakEvent) { + let (next, effect) = self.state.get().step(event); + match effect { + CloakEffect::None => self.state.set(next), + // A window DWM won't cloak shows as it is: nothing is held, and it activates now. + CloakEffect::Cloak => { + if set(window, true) { self.state.set(next) } else { + self.state.set(CloakState::Lifted); + if matches!(next, CloakState::Held { activate: true, .. }) { activate(window); } + } + } + CloakEffect::Uncloak { activate: then } => { + self.state.set(next); + set(window, false); + crate::marks::mark("window.uncloaked"); + if then { activate(window); } + } + } + } +} + +fn set(window: &winit::window::Window, cloaked: bool) -> bool { + let Some(hwnd) = super::hwnd(window) else { return false }; + let value = i32::from(cloaked); + // SAFETY: DWMWA_CLOAK reads one BOOL from `value` for a window this thread owns. + unsafe { DwmSetWindowAttribute(hwnd, DWMWA_CLOAK as u32, (&raw const value).cast(), 4) >= 0 } +} + +/// Brings the window to the foreground and gives it the focus, as a show that activates would, +/// when this process may take the foreground (a launch by the user). Otherwise it stays where a +/// show without the foreground puts it, below the foreground window: a `SetForegroundWindow` that +/// Windows refuses also holds the window under the foreground window from then on, so another +/// process's `HWND_TOPMOST` (PowerToys' Always On Top) succeeds and changes nothing. +/// `AllowSetForegroundWindow` for this process fails exactly when this process can't take it. +/// The launch's first window doesn't take the foreground when whoever started the process asked +/// for a show without activation (`STARTUPINFO`'s `SW_SHOWNOACTIVATE`, `SW_SHOWNA`, a minimized +/// show), as Windows applies that to a first `ShowWindow`: a script or a test that starts the app +/// in the background keeps the user's window in front. +fn activate(window: &winit::window::Window) { + let Some(hwnd) = super::hwnd(window) else { return }; + if launch_asks_no_activation() || !take_foreground(hwnd) { return; } + crate::marks::mark("window.activated"); +} + +/// Brings `hwnd` to the foreground and gives it the focus when this process may take the +/// foreground, and otherwise leaves it where it is (see `activate`). False when it may not. +pub(super) fn take_foreground(hwnd: windows_sys::Win32::Foundation::HWND) -> bool { + // SAFETY: plain calls on this process's id and a window this thread owns. + unsafe { + if windows_sys::Win32::UI::WindowsAndMessaging::AllowSetForegroundWindow(windows_sys::Win32::System::Threading::GetCurrentProcessId()) == 0 { return false; } + windows_sys::Win32::UI::WindowsAndMessaging::SetForegroundWindow(hwnd); + } + true +} + +/// Whether this is the launch's first activation and the launch asked for none (see `activate`). +fn launch_asks_no_activation() -> bool { + use windows_sys::Win32::System::Threading::{GetStartupInfoW, STARTF_USESHOWWINDOW, STARTUPINFOW}; + use windows_sys::Win32::UI::WindowsAndMessaging::{SW_MINIMIZE, SW_SHOWMINNOACTIVE, SW_SHOWNA, SW_SHOWNOACTIVATE}; + static FIRST: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(true); + if !FIRST.swap(false, std::sync::atomic::Ordering::Relaxed) { return false; } + // SAFETY: GetStartupInfoW fills the struct whose size it's given. + let info = unsafe { + let mut info: STARTUPINFOW = std::mem::zeroed(); + info.cb = std::mem::size_of::<STARTUPINFOW>() as u32; + GetStartupInfoW(&mut info); + info + }; + info.dwFlags & STARTF_USESHOWWINDOW != 0 && [SW_SHOWNOACTIVATE, SW_SHOWNA, SW_SHOWMINNOACTIVE, SW_MINIMIZE].contains(&i32::from(info.wShowWindow)) +} diff --git a/app/vendor/rune/crates/rune/src/platform/win32/dark_mode.rs b/app/vendor/rune/crates/rune/src/platform/win32/dark_mode.rs new file mode 100644 index 0000000..9baa845 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/platform/win32/dark_mode.rs @@ -0,0 +1,89 @@ +//! Dark native menus. Windows draws pop-up, context, window and tray menus light unless the +//! process asks for the dark theme through two functions uxtheme exports by ordinal only: +//! `SetPreferredAppMode` (135) and `FlushMenuThemes` (136). Both have kept their ordinals since +//! Windows 10 1903 (build 18362); earlier builds export something else there, so they're left +//! alone and menus stay light. + +#![allow(unsafe_code)] + +use std::sync::{OnceLock, atomic::{AtomicU8, Ordering}}; + +use windows_sys::Win32::System::LibraryLoader::{GetModuleHandleW, GetProcAddress, LOAD_LIBRARY_SEARCH_SYSTEM32, LoadLibraryExW}; + +/// `PreferredAppMode`: follow the system's app mode, or force one. +const ALLOW_DARK: i32 = 1; +const FORCE_DARK: i32 = 2; +const FORCE_LIGHT: i32 = 3; + +const FIRST_BUILD: u32 = 18362; + +struct Uxtheme { + set_preferred_app_mode: unsafe extern "system" fn(i32) -> i32, + flush_menu_themes: unsafe extern "system" fn(), +} + +/// The mode last asked for, so a frame that doesn't change it costs nothing. +static APPLIED: AtomicU8 = AtomicU8::new(0); + +/// Menus follow the system's dark or light app mode until a window says what it draws. +pub(crate) fn follow_system() { apply(ALLOW_DARK); } + +/// Menus from now on are dark or light, whatever the system's app mode. +pub(crate) fn menus(dark: bool) { apply(if dark { FORCE_DARK } else { FORCE_LIGHT }); } + +fn apply(mode: i32) { + let Some(uxtheme) = uxtheme() else { return }; + if APPLIED.swap(mode as u8, Ordering::Relaxed) == mode as u8 { return; } + // SAFETY: both are uxtheme's own exports on a build that has them with these signatures. + unsafe { + (uxtheme.set_preferred_app_mode)(mode); + (uxtheme.flush_menu_themes)(); + } +} + +fn uxtheme() -> Option<&'static Uxtheme> { + static UXTHEME: OnceLock<Option<Uxtheme>> = OnceLock::new(); + UXTHEME.get_or_init(|| { + if build()? < FIRST_BUILD { return None; } + // SAFETY: loads a system DLL from System32 and looks up two exports by ordinal (a + // pointer value below 0x10000). The module stays loaded for the process. + unsafe { + let module = LoadLibraryExW(wide("uxtheme.dll").as_ptr(), std::ptr::null_mut(), LOAD_LIBRARY_SEARCH_SYSTEM32); + if module.is_null() { return None; } + let set = GetProcAddress(module, 135 as *const u8)?; + let flush = GetProcAddress(module, 136 as *const u8)?; + Some(Uxtheme { + set_preferred_app_mode: std::mem::transmute::<unsafe extern "system" fn() -> isize, unsafe extern "system" fn(i32) -> i32>(set), + flush_menu_themes: std::mem::transmute::<unsafe extern "system" fn() -> isize, unsafe extern "system" fn()>(flush), + }) + } + }).as_ref() +} + +/// `OSVERSIONINFOW`, as `RtlGetVersion` fills it. +#[repr(C)] +struct VersionInfo { + size: u32, + major: u32, + minor: u32, + build: u32, + platform: u32, + service_pack: [u16; 128], +} + +/// The Windows build number. `RtlGetVersion` reports it whatever the app's manifest says, which +/// `GetVersionEx` doesn't. +fn build() -> Option<u32> { + // SAFETY: ntdll is loaded in every process; RtlGetVersion fills the struct whose size it is + // given and returns an NTSTATUS. + unsafe { + let ntdll = GetModuleHandleW(wide("ntdll.dll").as_ptr()); + if ntdll.is_null() { return None; } + let get = GetProcAddress(ntdll, c"RtlGetVersion".as_ptr().cast())?; + let get = std::mem::transmute::<unsafe extern "system" fn() -> isize, unsafe extern "system" fn(*mut VersionInfo) -> i32>(get); + let mut info = VersionInfo { size: size_of::<VersionInfo>() as u32, major: 0, minor: 0, build: 0, platform: 0, service_pack: [0; 128] }; + (get(&mut info) == 0).then_some(info.build) + } +} + +fn wide(s: &str) -> Vec<u16> { s.encode_utf16().chain(Some(0)).collect() } diff --git a/app/vendor/rune/crates/rune/src/platform/win32/dcomp_handover.rs b/app/vendor/rune/crates/rune/src/platform/win32/dcomp_handover.rs new file mode 100644 index 0000000..a2afaec --- /dev/null +++ b/app/vendor/rune/crates/rune/src/platform/win32/dcomp_handover.rs @@ -0,0 +1,110 @@ +//! The DirectComposition target a window's GPU swap chain shows through once the CPU renderer +//! hands it over. Made uncommitted: DWM keeps composing the window's GDI redirection surface (the +//! CPU's frames) under a visual that has a swap chain and no frame yet, for as many refreshes as +//! the GPU takes. Committing after the GPU's first frame is presented and done makes DWM switch +//! to it within one composition. wgpu's own `VisualFromWndHandle` commits inside +//! `Surface::configure`, before anything is presented (an already visible window would show an +//! empty swap chain for a refresh); a surface on a caller's visual +//! (`SurfaceTargetUnsafe::CompositionVisual`) only sets the visual's content. +//! +//! `dcomp.dll` loads here, when the GPU is ready, not at launch. + +#![allow(unsafe_code)] + +use windows::Win32::Graphics::DirectComposition::{IDCompositionDevice, IDCompositionTarget, IDCompositionVisual}; +use windows::core::{GUID, HRESULT, Interface}; + +pub(crate) struct Handover { + device: IDCompositionDevice, + _target: IDCompositionTarget, + /// The target's root: no content of its own; the UI's visual and, under it, any clip's layer. + root: IDCompositionVisual, + /// The UI's visual, which the wgpu surface goes on. + visual: IDCompositionVisual, +} + +// SAFETY: DirectComposition objects can be used from any thread one at a time; a `Handover` is +// made on the GPU thread and then used only by the window's thread. +unsafe impl Send for Handover {} + +impl Handover { + /// A device, a target for `hwnd` below its child windows, and a root visual holding the UI's, + /// uncommitted. + pub(crate) fn new(hwnd: isize) -> Result<Handover, String> { + let device = create_device()?; + // SAFETY: COM calls on objects made here, for a window of this process. + unsafe { + let target = device.CreateTargetForHwnd(windows::Win32::Foundation::HWND(hwnd as *mut _), false).map_err(|e| format!("CreateTargetForHwnd: {e}"))?; + let root = device.CreateVisual().map_err(|e| format!("CreateVisual: {e}"))?; + let visual = device.CreateVisual().map_err(|e| format!("CreateVisual: {e}"))?; + root.AddVisual(&visual, true, None).map_err(|e| format!("AddVisual: {e}"))?; + target.SetRoot(&root).map_err(|e| format!("SetRoot: {e}"))?; + Ok(Handover { device, _target: target, root, visual }) + } + } + + /// The visual a wgpu surface goes on (`SurfaceTargetUnsafe::CompositionVisual`). + pub(crate) fn visual(&self) -> *mut std::ffi::c_void { self.visual.as_raw() } + + /// The visual's swap chain, with the frame it presented, replaces the window's own content + /// at DWM's next composition. + pub(crate) fn commit(&self) -> Result<(), String> { + // SAFETY: a COM call on our device. + unsafe { self.device.Commit() }.map_err(|e| format!("IDCompositionDevice::Commit: {e}")) + } + + /// A visual under the UI's that shows the DirectComposition surface `handle` (a playing clip's + /// own layer, `video::windows::layer`), uncommitted. + pub(crate) fn add_under(&self, handle: usize) -> Result<IDCompositionVisual, String> { + // SAFETY: COM calls on our device and visuals; the handle is a live composition surface + // handle its owner keeps open while the visual shows it. + unsafe { + let surface = self.device.CreateSurfaceFromHandle(windows::Win32::Foundation::HANDLE(handle as *mut _)).map_err(|e| format!("CreateSurfaceFromHandle: {e}"))?; + let visual = self.device.CreateVisual().map_err(|e| format!("CreateVisual: {e}"))?; + visual.SetContent(&surface).map_err(|e| format!("SetContent: {e}"))?; + self.root.AddVisual(&visual, false, &self.visual).map_err(|e| format!("AddVisual: {e}"))?; + Ok(visual) + } + } + + /// Takes a visual `add_under` made out of the tree, uncommitted. + pub(crate) fn remove(&self, visual: &IDCompositionVisual) { + // SAFETY: a COM call on our root visual. + unsafe { self.root.RemoveVisual(visual) }.ok(); + } + + /// Commits, and returns once DWM has taken the commit: a frame presented after this shows + /// over what it committed. + pub(crate) fn commit_and_wait(&self) -> Result<(), String> { + self.commit()?; + // SAFETY: a COM call on our device. + unsafe { self.device.WaitForCommitCompletion() }.map_err(|e| format!("IDCompositionDevice::WaitForCommitCompletion: {e}")) + } + +} + +fn load_dll(name: &str) -> windows_sys::Win32::Foundation::HMODULE { + super::load_system_dll(name) +} + +/// `DCompositionCreateDevice2(NULL, ...)`, from `dcomp.dll` loaded now rather than imported. +fn create_device() -> Result<IDCompositionDevice, String> { + type Create = unsafe extern "system" fn(*mut std::ffi::c_void, *const GUID, *mut *mut std::ffi::c_void) -> HRESULT; + // SAFETY: a system DLL by name; the entry point has the signature dcomp.h declares, and the + // pointer it writes is an owned reference to the interface asked for. + unsafe { + let lib = load_dll("dcomp.dll"); + if lib.is_null() { return Err("dcomp.dll did not load".into()); } + let Some(create) = windows_sys::Win32::System::LibraryLoader::GetProcAddress(lib, c"DCompositionCreateDevice2".as_ptr().cast()) else { + return Err("dcomp.dll has no DCompositionCreateDevice2".into()); + }; + let create: Create = std::mem::transmute(create); + let mut raw = std::ptr::null_mut(); + create(std::ptr::null_mut(), &IDCompositionDevice::IID, &mut raw).ok().map_err(|e| format!("DCompositionCreateDevice2: {e}"))?; + Ok(IDCompositionDevice::from_raw(raw)) + } +} + +#[cfg(test)] +#[path = "dcomp_handover_tests.rs"] +mod tests; diff --git a/app/vendor/rune/crates/rune/src/platform/win32/dcomp_handover_tests.rs b/app/vendor/rune/crates/rune/src/platform/win32/dcomp_handover_tests.rs new file mode 100644 index 0000000..7fe3552 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/platform/win32/dcomp_handover_tests.rs @@ -0,0 +1,58 @@ +#![allow(unsafe_code)] + +use std::path::PathBuf; + +use windows_sys::Win32::Foundation::FreeLibrary; +use windows_sys::Win32::System::LibraryLoader::GetModuleFileNameW; + +use super::load_dll; + +struct TempDll { + path: PathBuf, + loaded: windows_sys::Win32::Foundation::HMODULE, +} + +impl Drop for TempDll { + fn drop(&mut self) { + if !self.loaded.is_null() { + // SAFETY: module handle returned by `load_dll` in this test. + unsafe { FreeLibrary(self.loaded); } + } + std::fs::remove_file(&self.path).ok(); + } +} + +fn module_path(module: windows_sys::Win32::Foundation::HMODULE) -> PathBuf { + let mut buf = [0u16; 260]; + // SAFETY: `module` is a loaded HMODULE and `buf` holds up to 260 UTF-16 code units. + let len = unsafe { GetModuleFileNameW(module, buf.as_mut_ptr(), buf.len() as u32) } as usize; + assert!(len > 0 && len < buf.len()); + PathBuf::from(String::from_utf16_lossy(&buf[..len])) +} + +#[test] +fn system_dll_loader_refuses_app_directory_hijack_and_loads_from_system32() { + let dcomp = load_dll("dcomp.dll"); + assert!(!dcomp.is_null(), "dcomp.dll should load from System32"); + let dcomp_path = module_path(dcomp); + let system32 = dcomp_path.parent().expect("dcomp parent dir"); + assert!( + system32.file_name().and_then(|s| s.to_str()).is_some_and(|s| s.eq_ignore_ascii_case("system32")), + "expected dcomp.dll from System32, got {dcomp_path:?}" + ); + // SAFETY: releases the reference acquired above. + unsafe { FreeLibrary(dcomp); } + + let exe_dir = std::env::current_exe().unwrap().parent().unwrap().to_path_buf(); + let probe_name = format!("rune_system32_probe_{}.dll", std::process::id()); + let probe_path = exe_dir.join(&probe_name); + // Copy a small harmless System32 DLL beside the test executable under a unique name. + std::fs::copy(system32.join("version.dll"), &probe_path).expect("copy probe dll"); + let mut guard = TempDll { path: probe_path, loaded: std::ptr::null_mut() }; + + let loaded = load_dll(&probe_name); + guard.loaded = loaded; + assert!(loaded.is_null(), "system DLL loader must not load a DLL from the application directory"); + assert!(load_dll("..\\dcomp.dll").is_null(), "relative paths are rejected"); + assert!(load_dll(&dcomp_path.to_string_lossy()).is_null(), "full paths are rejected"); +} diff --git a/app/vendor/rune/crates/rune/src/platform/win32/dib.rs b/app/vendor/rune/crates/rune/src/platform/win32/dib.rs new file mode 100644 index 0000000..f766b10 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/platform/win32/dib.rs @@ -0,0 +1,165 @@ +//! A window's CPU frame buffer: a top-down 32-bit DIB section the CPU renderer +//! (`render::cpu_boot`) paints in place, and the window's GDI redirection surface it's copied to, +//! one `BitBlt` a frame (`Blit`). Measured against every other way of getting CPU bytes +//! composed on Windows (layered windows, a WARP swap chain on the window or on a DirectComposition +//! visual, a DirectComposition surface), this is the cheapest correct one: no DLL beyond user32 +//! and gdi32, about 90 µs to set up, one copy of what changed per frame, and nothing per frame that +//! allocates. The buffer keeps the last frame, which the renderer's damage tracking relies on, and +//! it's made once at the largest size the window is likely to reach (its display's), with one row +//! length: a resize then repaints only what moved and touches no new memory. + +#![allow(unsafe_code)] + +use windows_sys::Win32::Foundation::HWND; +use windows_sys::Win32::Graphics::Gdi::{ + BI_RGB, BITMAPINFO, BITMAPINFOHEADER, BitBlt, CreateCompatibleDC, CreateDIBSection, DIB_RGB_COLORS, DeleteDC, DeleteObject, GetDC, HBITMAP, + HDC, HGDIOBJ, RGBQUAD, ReleaseDC, SRCCOPY, SelectObject, +}; + +/// A DIB section and the memory DC it's selected into. +pub(crate) struct Dib { + bitmap: HBITMAP, + dc: HDC, + old: HGDIOBJ, + bits: *mut u8, + width: u32, + height: u32, +} + +impl Dib { + /// A `width` x `height` buffer: B, G, R, A bytes, `width * 4` per row (`stride`), top row + /// first; the window's client area is its top-left part. Its pages are untouched until + /// something writes them. None when GDI refuses (out of memory). + pub(crate) fn new(width: u32, height: u32) -> Option<Dib> { + let (width, height) = (width.max(1), height.max(1)); + let info = BITMAPINFO { + bmiHeader: BITMAPINFOHEADER { + biSize: size_of::<BITMAPINFOHEADER>() as u32, + biWidth: width as i32, + biHeight: -(height as i32), + biPlanes: 1, + biBitCount: 32, + biCompression: BI_RGB, + biSizeImage: 0, + biXPelsPerMeter: 0, + biYPelsPerMeter: 0, + biClrUsed: 0, + biClrImportant: 0, + }, + bmiColors: [RGBQUAD { rgbBlue: 0, rgbGreen: 0, rgbRed: 0, rgbReserved: 0 }], + }; + let mut bits = std::ptr::null_mut(); + // SAFETY: `info` describes a 32 bpp top-down DIB; GDI writes the bits pointer. + unsafe { + let bitmap = CreateDIBSection(std::ptr::null_mut(), &info, DIB_RGB_COLORS, &mut bits, std::ptr::null_mut(), 0); + if bitmap.is_null() || bits.is_null() { return None; } + let dc = CreateCompatibleDC(std::ptr::null_mut()); + if dc.is_null() { + DeleteObject(bitmap); + return None; + } + let old = SelectObject(dc, bitmap); + Some(Dib { bitmap, dc, old, bits: bits.cast(), width, height }) + } + } + + /// Whether a client area of `size` fits in it. + pub(crate) fn fits(&self, size: (u32, u32)) -> bool { size.0 <= self.width && size.1 <= self.height } + + /// Bytes from one row to the next. + pub(crate) fn stride(&self) -> usize { self.width as usize * 4 } + + /// The pixels, for the renderer to paint into. + pub(crate) fn bytes(&mut self) -> &mut [u8] { + // SAFETY: the section holds width * height * 4 bytes for as long as `self` lives, and + // `&mut self` keeps any other access out. + unsafe { std::slice::from_raw_parts_mut(self.bits, self.width as usize * self.height as usize * 4) } + } + + /// Writes every page of the first `rows` rows once, so the first frame's paint doesn't take a + /// fault per 4 KiB. Meant for a worker while the frame is laid out (`Prefault`). + fn touch(&self, rows: u32) { + let len = self.stride() * rows.min(self.height) as usize; + let mut at = 0; + while at < len { + // SAFETY: inside the section; a volatile write of the byte already there. + unsafe { std::ptr::write_volatile(self.bits.add(at), std::ptr::read_volatile(self.bits.add(at))) }; + at += 4096; + } + } + + /// Copies what `blit` says of the buffer to the window's client area of `client` pixels, at + /// the same place. + pub(crate) fn present(&self, hwnd: HWND, client: (u32, u32), blit: Blit<'_>) { + let (width, height) = (client.0.min(self.width), client.1.min(self.height)); + let clip = |r: &[u32; 4]| { + let (x0, y0, x1, y1) = (r[0].min(width), r[1].min(height), r[2].min(width), r[3].min(height)); + (x1 > x0 && y1 > y0).then_some((x0 as i32, y0 as i32, (x1 - x0) as i32, (y1 - y0) as i32)) + }; + let bounds = |rects: &[[u32; 4]]| rects.iter().fold([u32::MAX, u32::MAX, 0, 0], |u, r| [u[0].min(r[0]), u[1].min(r[1]), u[2].max(r[2]), u[3].max(r[3])]); + let copies: Vec<_> = match blit { + Blit::Bounds([]) => Vec::new(), + Blit::Bounds(rects) => clip(&bounds(rects)).into_iter().collect(), + Blit::All => clip(&[0, 0, width, height]).into_iter().collect(), + }; + if copies.is_empty() { return; } + // SAFETY: a window this thread owns; the DC goes back before returning. + unsafe { + let window = GetDC(hwnd); + if window.is_null() { return; } + for (x, y, w, h) in copies { BitBlt(window, x, y, w, h, self.dc, x, y, SRCCOPY); } + ReleaseDC(hwnd, window); + } + } +} + +/// What a frame copies to the window (`Dib::present`). +pub(crate) enum Blit<'a> { + /// The rects' bounding box, in one copy; nothing when there are none (an unchanged frame). + /// DWM can compose between two `BitBlt`s: on the visible desktop one copy per rect showed + /// 1-15 torn frames in 600, one per frame none. + Bounds(&'a [[u32; 4]]), + /// The whole client area: the window changed size, and its redirection surface with it. + All, +} + +impl Drop for Dib { + fn drop(&mut self) { + // SAFETY: the DC and bitmap are ours; the bitmap leaves the DC before both go. + unsafe { + SelectObject(self.dc, self.old); + DeleteDC(self.dc); + DeleteObject(self.bitmap); + } + } +} + +// SAFETY: a DIB section and a memory DC aren't tied to the thread that made them; the buffer moves +// to a worker to be touched (`Prefault`) or freed, never used from two threads at once. +unsafe impl Send for Dib {} + +/// A new buffer's pages written on a worker while the first frame is laid out: painting into +/// never-touched memory costs a page fault per 4 KiB (20.7 MB at 2880 x 1800, about 8,000 µs on +/// one thread). `take` waits for the worker; None if no worker could start, when the caller makes +/// another buffer and the frame takes the faults. +pub(crate) struct Prefault(Option<std::thread::JoinHandle<Dib>>); + +impl Prefault { + /// Touches the first `rows` rows, the ones the first frame paints. + pub(crate) fn start(dib: Dib, rows: u32) -> Prefault { + let worker = std::thread::Builder::new().name("rune-dib-touch".into()).spawn(move || { dib.touch(rows); dib }); + if let Err(error) = &worker { eprintln!("rune: could not start the frame buffer's worker: {error}"); } + Prefault(worker.ok()) + } + + pub(crate) fn take(self) -> Option<Dib> { + self.0.and_then(|w| w.join().ok()) + } +} + +/// Frees a buffer on a worker (`VirtualFree` of up to tens of MB), off the UI thread. +pub(crate) fn free_later(dib: Dib) { + if let Err(error) = std::thread::Builder::new().name("rune-dib-free".into()).spawn(move || drop(dib)) { + eprintln!("rune: could not free the frame buffer on a worker: {error}"); + } +} diff --git a/app/vendor/rune/crates/rune/src/platform/win32/dpi_drag.rs b/app/vendor/rune/crates/rune/src/platform/win32/dpi_drag.rs new file mode 100644 index 0000000..bd3caaf --- /dev/null +++ b/app/vendor/rune/crates/rune/src/platform/win32/dpi_drag.rs @@ -0,0 +1,73 @@ +//! Dragging a window between displays with different scaling. Windows sends `WM_DPICHANGED` +//! with a rect it worked out for the new scale, and expects the window to take it. winit sizes +//! the window itself, keeps the pointer's place along the title bar, then nudges the window +//! until most of it is on the new display. Mid-drag that nudge moves the window out from +//! under the pointer; the move loop puts it back under the pointer, mostly on the old display, +//! which changes the scale back, and the window grows and shrinks at the boundary instead of +//! crossing it (hex#1355). While the user moves or sizes the window, it takes Windows' rect +//! after winit has handled the message, so winit still learns the new scale. A window with a +//! custom frame (`frame`) lands on Windows' rect in winit's own move, so it needs no second. +//! +//! The move or size loop is also when a resize draws its frame at once (`in_size_move`). + +#![allow(unsafe_code)] + +use std::cell::RefCell; + +use windows_sys::Win32::Foundation::{HWND, LPARAM, LRESULT, RECT, WPARAM}; +use windows_sys::Win32::UI::Shell::{DefSubclassProc, RemoveWindowSubclass, SetWindowSubclass}; +use windows_sys::Win32::UI::WindowsAndMessaging::{ + IsWindow, SWP_NOACTIVATE, SWP_NOZORDER, SetWindowPos, WM_DPICHANGED, WM_ENTERSIZEMOVE, WM_EXITSIZEMOVE, WM_NCDESTROY, +}; + +const SUBCLASS: usize = 0x5255_4e44; + +thread_local! { + /// The windows on this thread inside a move or size loop. + static MOVING: RefCell<Vec<usize>> = const { RefCell::new(Vec::new()) }; +} + +/// Makes `window` take the rect Windows suggests when its scale changes during a move or size. +pub(crate) fn follow_suggested_rect(window: &winit::window::Window) { + let Some(hwnd) = super::hwnd(window) else { return }; + // SAFETY: the subclass reads no data, and goes at WM_NCDESTROY. + unsafe { SetWindowSubclass(hwnd, Some(subclass), SUBCLASS, 0); } +} + +/// Whether the user is moving or sizing `window` by its frame (`WM_ENTERSIZEMOVE` until +/// `WM_EXITSIZEMOVE`), in the system's modal loop. +pub(crate) fn in_size_move(window: &winit::window::Window) -> bool { + super::hwnd(window).is_some_and(moving) +} + +fn moving(hwnd: HWND) -> bool { + MOVING.with(|m| m.borrow().contains(&(hwnd as usize))) +} + +unsafe extern "system" fn subclass(hwnd: HWND, message: u32, wparam: WPARAM, lparam: LPARAM, _: usize, _: usize) -> LRESULT { + match message { + WM_ENTERSIZEMOVE => MOVING.with(|m| { + let mut m = m.borrow_mut(); + if !m.contains(&(hwnd as usize)) { m.push(hwnd as usize); } + }), + WM_EXITSIZEMOVE => MOVING.with(|m| m.borrow_mut().retain(|&h| h != hwnd as usize)), + // SAFETY: WM_DPICHANGED's lparam points to the suggested RECT. + WM_DPICHANGED if moving(hwnd) && !super::frame::installed(hwnd) => unsafe { + let suggested = *(lparam as *const RECT); + let result = DefSubclassProc(hwnd, message, wparam, lparam); + if IsWindow(hwnd) != 0 { + let RECT { left, top, right, bottom } = suggested; + SetWindowPos(hwnd, std::ptr::null_mut(), left, top, right - left, bottom - top, SWP_NOZORDER | SWP_NOACTIVATE); + } + return result; + }, + WM_NCDESTROY => { + MOVING.with(|m| m.borrow_mut().retain(|&h| h != hwnd as usize)); + // SAFETY: removes this subclass from the window it's on. + unsafe { RemoveWindowSubclass(hwnd, Some(subclass), SUBCLASS); } + } + _ => {} + } + // SAFETY: forwards to the next window procedure. + unsafe { DefSubclassProc(hwnd, message, wparam, lparam) } +} diff --git a/app/vendor/rune/crates/rune/src/platform/win32/drop_target.rs b/app/vendor/rune/crates/rune/src/platform/win32/drop_target.rs new file mode 100644 index 0000000..ca6d780 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/platform/win32/drop_target.rs @@ -0,0 +1,184 @@ +//! Files dragged in from other apps, through Rune's own OLE drop target. winit's (its +//! `with_drag_and_drop`) initialises OLE and registers its target inside `CreateWindowExW`, which +//! costs a new window about 8,400 µs and six shell DLLs before its first frame; Rune creates +//! windows without it and registers this target once the window has shown (`install`), so a +//! drag can only start after a frame a person has seen anyway. The steps reach the host as +//! macOS's do (`platform::macos::drop`): with the pointer's place in window points, drained each +//! turn by `Host::flush_files`. + +#![allow(unsafe_code)] + +use std::cell::RefCell; +use std::collections::HashMap; +use std::path::PathBuf; + +use windows::Win32::Foundation::{HWND, POINTL}; +use windows::Win32::System::Com::{DVASPECT_CONTENT, FORMATETC, IDataObject, TYMED_HGLOBAL}; +use windows::Win32::System::Ole::{CF_HDROP, DROPEFFECT, DROPEFFECT_COPY, DROPEFFECT_NONE, IDropTarget, IDropTarget_Impl, OleInitialize, RegisterDragDrop, ReleaseStgMedium}; +use windows::Win32::System::SystemServices::MODIFIERKEYS_FLAGS; +use windows::core::{Ref, implement}; +use winit::raw_window_handle::{HasWindowHandle, RawWindowHandle}; + +use crate::window::FileStep; + +/// What each window's target has seen since its host last looked, and whether it's registered. +#[derive(Default)] +struct Dest { + installed: bool, + steps: Vec<FileStep>, + /// The drag over it carries files, so it may drop them. + files: bool, +} + +thread_local! { + /// By HWND: drop targets live on the UI thread that registered them, as OLE calls them there. + static DESTS: RefCell<HashMap<isize, Dest>> = RefCell::new(HashMap::new()); + /// A drag out of this app runs that its windows don't take (`DragItem::within_app` off). + static MUTED: std::cell::Cell<bool> = const { std::cell::Cell::new(false) }; +} + +/// While a drag out of the app runs, its windows refuse it, as they refuse it on macOS, so a +/// drag let go over the app ends cancelled instead of handing the app its own files. +pub(crate) fn mute(on: bool) { + MUTED.with(|m| m.set(on)); +} + +fn hwnd(window: &winit::window::Window) -> Option<HWND> { + match window.window_handle().ok()?.as_raw() { + RawWindowHandle::Win32(h) => Some(HWND(h.hwnd.get() as *mut _)), + _ => None, + } +} + +/// Registers the window's drop target, once; after its first frame has shown. +pub(crate) fn install(window: &winit::window::Window) { + let Some(hwnd) = hwnd(window) else { return }; + let fresh = DESTS.with(|d| { + let mut d = d.borrow_mut(); + let dest = d.entry(hwnd.0 as isize).or_default(); + !std::mem::replace(&mut dest.installed, true) + }); + if !fresh { + return; + } + // SAFETY: the UI thread, which winit leaves without COM (drag and drop off), becomes OLE's + // single-threaded apartment; the target lives as long as the window (OLE holds a reference + // until the window is destroyed and revokes it then). + unsafe { + if OleInitialize(None).is_err() { + return; + } + let target: IDropTarget = Target { hwnd: hwnd.0 as isize }.into(); + RegisterDragDrop(hwnd, &target).ok(); + } +} + +/// What the window's target saw since the last call. +pub(crate) fn take(window: &winit::window::Window) -> Vec<FileStep> { + let Some(hwnd) = hwnd(window) else { return Vec::new() }; + DESTS.with(|d| d.borrow_mut().get_mut(&(hwnd.0 as isize)).map(|d| std::mem::take(&mut d.steps)).unwrap_or_default()) +} + +fn push(hwnd: isize, step: FileStep) { + DESTS.with(|d| d.borrow_mut().entry(hwnd).or_default().steps.push(step)); + // Turns the loop, whose `about_to_wait` drains the step (`Host::flush_files`). + // SAFETY: a message with no meaning to a window we own. + unsafe { + windows_sys::Win32::UI::WindowsAndMessaging::PostMessageW(hwnd as _, windows_sys::Win32::UI::WindowsAndMessaging::WM_NULL, 0, 0); + } +} + +#[implement(IDropTarget)] +struct Target { + hwnd: isize, +} + +impl Target { + /// `pt` (screen pixels) in the window's points. + fn at(&self, pt: &POINTL) -> (f32, f32) { + let hwnd = self.hwnd as windows_sys::Win32::Foundation::HWND; + let mut p = windows_sys::Win32::Foundation::POINT { x: pt.x, y: pt.y }; + // SAFETY: our own window, on its thread. + let scale = unsafe { + windows_sys::Win32::Graphics::Gdi::ScreenToClient(hwnd, &mut p); + windows_sys::Win32::UI::HiDpi::GetDpiForWindow(hwnd) as f32 / 96.0 + }; + let scale = if scale > 0.0 { scale } else { 1.0 }; + (p.x as f32 / scale, p.y as f32 / scale) + } + + fn set_files(&self, files: bool) { + DESTS.with(|d| d.borrow_mut().entry(self.hwnd).or_default().files = files); + } + + fn files(&self) -> bool { + DESTS.with(|d| d.borrow().get(&self.hwnd).is_some_and(|d| d.files)) + } +} + +/// The paths `data` carries as a shell file list (`CF_HDROP`); none for any other drag, or +/// while the app's own drag is muted. +fn paths(data: Option<&IDataObject>) -> Vec<PathBuf> { + let Some(data) = data.filter(|_| !MUTED.with(|m| m.get())) else { return Vec::new() }; + let format = FORMATETC { cfFormat: CF_HDROP.0, ptd: std::ptr::null_mut(), dwAspect: DVASPECT_CONTENT.0, lindex: -1, tymed: TYMED_HGLOBAL.0 as u32 }; + // SAFETY: a `CF_HDROP` medium holds an HDROP in its HGLOBAL, read and released here. + unsafe { + let Ok(mut medium) = data.GetData(&format) else { return Vec::new() }; + use windows_sys::Win32::UI::Shell::DragQueryFileW; + let drop = medium.u.hGlobal.0 as windows_sys::Win32::UI::Shell::HDROP; + let count = DragQueryFileW(drop, u32::MAX, std::ptr::null_mut(), 0); + let out = (0..count).filter_map(|i| { + let len = DragQueryFileW(drop, i, std::ptr::null_mut(), 0) as usize; + let mut buf = vec![0u16; len + 1]; + (DragQueryFileW(drop, i, buf.as_mut_ptr(), buf.len() as u32) as usize == len).then(|| PathBuf::from(String::from_utf16_lossy(&buf[..len]))) + }).collect(); + ReleaseStgMedium(&mut medium); + out + } +} + +fn effect(out: *mut DROPEFFECT, files: bool) { + if !out.is_null() { + // SAFETY: OLE's out parameter for the effect the target offers. + unsafe { *out = if files { DROPEFFECT_COPY } else { DROPEFFECT_NONE } }; + } +} + +impl IDropTarget_Impl for Target_Impl { + fn DragEnter(&self, data: Ref<IDataObject>, _: MODIFIERKEYS_FLAGS, pt: &POINTL, out: *mut DROPEFFECT) -> windows::core::Result<()> { + let files = paths(data.as_ref()); + self.set_files(!files.is_empty()); + effect(out, !files.is_empty()); + if !files.is_empty() { + push(self.hwnd, FileStep::Enter(files, Some(self.at(pt)))); + } + Ok(()) + } + + fn DragOver(&self, _: MODIFIERKEYS_FLAGS, pt: &POINTL, out: *mut DROPEFFECT) -> windows::core::Result<()> { + let files = self.files(); + effect(out, files); + if files { + push(self.hwnd, FileStep::Move(self.at(pt))); + } + Ok(()) + } + + fn DragLeave(&self) -> windows::core::Result<()> { + if self.files() { + self.set_files(false); + push(self.hwnd, FileStep::Leave); + } + Ok(()) + } + + fn Drop(&self, data: Ref<IDataObject>, _: MODIFIERKEYS_FLAGS, pt: &POINTL, out: *mut DROPEFFECT) -> windows::core::Result<()> { + let files = paths(data.as_ref()); + self.set_files(false); + effect(out, !files.is_empty()); + if !files.is_empty() { + push(self.hwnd, FileStep::Drop(files, Some(self.at(pt)))); + } + Ok(()) + } +} diff --git a/app/vendor/rune/crates/rune/src/platform/win32/frame.rs b/app/vendor/rune/crates/rune/src/platform/win32/frame.rs new file mode 100644 index 0000000..3071da2 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/platform/win32/frame.rs @@ -0,0 +1,541 @@ +//! A custom frame for a window whose app draws its own titlebar (`App::titlebar`). +//! +//! The window keeps its standard styles (caption, sizing border, system menu, minimize and +//! maximize boxes), so Windows still gives it resize edges, Aero Snap, the snap layouts +//! flyout, the window menu and its animations; only the title bar goes. `WM_NCCALCSIZE` +//! hands the caption's band to the client area and keeps the side and bottom borders, which +//! Windows 10 and 11 draw invisibly outside the window, as resize edges. The top resize edge +//! is then a band inside the client area that `WM_NCHITTEST` reports as `HTTOP`. Windows 11 +//! draws the window's 1 px border over the client area; Windows 10 draws it only around +//! non-client pixels, so there a restored window keeps a 1 px non-client row at the top. +//! +//! Rune draws the caption buttons as elements (`titlebar::caption`), and this procedure answers +//! hit tests over them as `HTMINBUTTON`, `HTMAXBUTTON` and `HTCLOSE`. Windows 11 shows its snap +//! layouts flyout over a window's `HTMAXBUTTON`, so they have to be non-client hits; the +//! pointer over them then arrives as non-client messages, which this procedure turns into the +//! buttons' `CaptionState` and their actions (`WM_SYSCOMMAND`), never letting the default +//! procedure draw classic buttons over them. A press captures the mouse until its release, as +//! a native caption button does: dragging off cancels, dragging back resumes, and a release +//! anywhere ends it. A window without a minimize or maximize box gets no hit for that button, +//! so no flyout and no action. +//! +//! winit sizes the window from its client size with `AdjustWindowRectEx`, which counts the +//! title bar this frame removed: the minimum and maximum track sizes, the size for a new scale +//! (`WM_GETDPISCALEDSIZE`, which Windows' `WM_DPICHANGED` rect then follows) and +//! `request_inner_size` are corrected here to the frame's borders. + +#![allow(unsafe_code)] + +use std::cell::Cell; +use std::rc::Rc; +use std::sync::OnceLock; + +use windows_sys::Win32::Foundation::{HWND, LPARAM, LRESULT, POINT, RECT, SIZE, WPARAM}; +use windows_sys::Win32::Graphics::Gdi::{ClientToScreen, GetMonitorInfoW, InvalidateRect, MONITOR_DEFAULTTONEAREST, MONITORINFO, MonitorFromRect, ScreenToClient}; +use windows_sys::Win32::System::LibraryLoader::{GetModuleHandleW, GetProcAddress}; +use windows_sys::Win32::UI::HiDpi::{AdjustWindowRectExForDpi, GetDpiForWindow, GetSystemMetricsForDpi}; +use windows_sys::Win32::UI::Input::KeyboardAndMouse::{ReleaseCapture, SetCapture, TME_LEAVE, TME_NONCLIENT, TRACKMOUSEEVENT, TrackMouseEvent}; +use windows_sys::Win32::UI::Shell::{ABE_BOTTOM, ABE_LEFT, ABE_RIGHT, ABE_TOP, ABM_GETAUTOHIDEBAREX, APPBARDATA, DefSubclassProc, RemoveWindowSubclass, SHAppBarMessage, SetWindowSubclass}; +use windows_sys::Win32::UI::WindowsAndMessaging::*; + +use crate::runtime::WindowMenu; +use crate::titlebar::{Caption, CaptionButton, CaptionState}; + +const SUBCLASS: usize = 0x5255_4e46; +/// `WM_MOUSEMOVE`'s flag for the (logical) left button held. +const MK_LBUTTON: WPARAM = 0x0001; + +/// A window's custom frame: installed for its life, removed as the window is destroyed. +pub(crate) struct CustomFrame { + state: Rc<State>, +} + +struct State { + /// The titlebar's height in points, which the caption buttons take. + height: Cell<f32>, + caption: Cell<CaptionState>, + /// Windows' rect for the new scale while `WM_DPICHANGED` runs: winit's own `SetWindowPos` + /// lands on it (`WM_WINDOWPOSCHANGING`), so the window moves and resizes once. + dpi_rect: Cell<Option<RECT>>, +} + +impl CustomFrame { + /// Takes the title bar off `window`, keeping its client size. + pub(crate) fn install(window: &winit::window::Window, height: f32) -> Option<Self> { + let hwnd = super::hwnd(window)?; + let state = Rc::new(State { height: Cell::new(height), caption: Cell::new(CaptionState::Idle), dpi_rect: Cell::new(None) }); + let data = Rc::into_raw(state.clone()); + // SAFETY: `data` stays alive until WM_NCDESTROY, where the subclass that reads it goes. + if unsafe { SetWindowSubclass(hwnd, Some(subclass), SUBCLASS, data as usize) } == 0 { + // SAFETY: never handed to Windows. + drop(unsafe { Rc::from_raw(data) }); + return None; + } + FRAMED.with(|f| f.borrow_mut().push(hwnd as usize)); + let before = client_size(hwnd); + // SAFETY: Win32 calls on a live window this thread owns. + unsafe { + SetWindowPos(hwnd, std::ptr::null_mut(), 0, 0, 0, 0, SWP_FRAMECHANGED | SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE | SWP_NOOWNERZORDER); + let grown = client_size(hwnd).1 - before.1; + let mut r = RECT { left: 0, top: 0, right: 0, bottom: 0 }; + if grown != 0 && IsZoomed(hwnd) == 0 && GetWindowRect(hwnd, &mut r) != 0 { + SetWindowPos(hwnd, std::ptr::null_mut(), 0, 0, r.right - r.left, r.bottom - r.top - grown, SWP_NOMOVE | SWP_NOZORDER | SWP_NOACTIVATE | SWP_NOOWNERZORDER); + } + } + Some(Self { state }) + } + + /// The caption buttons as they are now. + pub(crate) fn caption(&self, window: &winit::window::Window) -> Caption { + match super::hwnd(window) { + Some(hwnd) => self.state.caption(hwnd), + None => Caption::new(self.state.height.get()), + } + } + + /// A new titlebar height (`Cx::titlebar_height`): the buttons and the band they hit-test. + pub(crate) fn set_height(&self, height: f32) { + self.state.height.set(height); + } +} + +/// Sizes `window`'s client area to `size` points, as `request_inner_size` would for a window +/// with this frame. False when it has none, for winit to do it. +pub(crate) fn request_inner_size(window: &winit::window::Window, size: (f32, f32)) -> bool { + let Some(hwnd) = super::hwnd(window).filter(|&h| installed(h)) else { return false }; + let scale = window.scale_factor(); + let (w, h) = ((f64::from(size.0) * scale).round() as i32, (f64::from(size.1) * scale).round() as i32); + // SAFETY: Win32 calls on a live window this thread owns. + unsafe { + if IsZoomed(hwnd) != 0 { ShowWindow(hwnd, SW_RESTORE); } + let b = borders(hwnd, GetDpiForWindow(hwnd)); + SetWindowPos(hwnd, std::ptr::null_mut(), 0, 0, w + b.left + b.right, h + top_border(hwnd) + b.bottom, SWP_NOMOVE | SWP_NOZORDER | SWP_NOACTIVATE | SWP_NOOWNERZORDER); + } + true +} + +/// Whether the window has a window menu (`WS_SYSMENU`) for Alt+Space to open. +pub(crate) fn has_window_menu(window: &winit::window::Window) -> bool { + // SAFETY: reads the style of a live window. + super::hwnd(window).is_some_and(|hwnd| unsafe { GetWindowLongPtrW(hwnd, GWL_STYLE) } as u32 & WS_SYSMENU != 0) +} + +/// Opens the window menu and carries out what the user picks: at `at` (the click), as a right-click +/// on a native title bar does, or from the keyboard, as Alt+Space does. Both are posted, so the +/// menu's modal loop runs from the message loop rather than inside the event loop's handler, +/// where neither a quit (`crate::quit`) nor the windows' timers could run until it closed. +pub(crate) fn window_menu(window: &winit::window::Window, menu: WindowMenu, at: Option<(i32, i32)>) { + let Some(hwnd) = super::hwnd(window) else { return }; + if menu == WindowMenu::Keyboard { + // SAFETY: posts to a live window this thread owns. + unsafe { PostMessageW(hwnd, WM_SYSCOMMAND, SC_KEYMENU as WPARAM, LPARAM::from(b' ')); } + return; + } + // Where the click was, in desktop pixels; the pointer may have moved since. + let Some((x, y)) = at.or_else(super::pointer_position) else { return }; + let id = NEXT_MENU.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + // Screen points fit 16 bits each, as in every mouse message's. + let point = ((y as u16 as u32) << 16 | x as u16 as u32) as usize; + // SAFETY: Win32 calls on a live window this thread owns; the subclass keeps no pointer. + unsafe { + if SetWindowSubclass(hwnd, Some(menu_procedure), id, point) == 0 { return; } + if PostMessageW(hwnd, menu_message(), id, 0) == 0 { + RemoveWindowSubclass(hwnd, Some(menu_procedure), id); + } + } +} + +/// The top right corner of `hwnd`'s client area, in desktop pixels. +fn client_top_right(hwnd: HWND) -> Option<(i32, i32)> { + let mut r = RECT { left: 0, top: 0, right: 0, bottom: 0 }; + // SAFETY: plain queries on a live window this thread owns. + unsafe { + if GetClientRect(hwnd, &mut r) == 0 { return None; } + let mut p = POINT { x: r.right, y: r.top }; + (ClientToScreen(hwnd, &mut p) != 0).then_some((p.x, p.y)) + } +} + +/// Each posted window menu's subclass id, named in its message. +static NEXT_MENU: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(1); + +fn menu_message() -> u32 { + static MESSAGE: OnceLock<u32> = OnceLock::new(); + // SAFETY: the name is NUL-terminated. + *MESSAGE.get_or_init(|| unsafe { RegisterWindowMessageW("Rune::WindowMenu\0".encode_utf16().collect::<Vec<u16>>().as_ptr()) }) +} + +unsafe extern "system" fn menu_procedure(hwnd: HWND, message: u32, w: WPARAM, l: LPARAM, id: usize, point: usize) -> LRESULT { + if (message == menu_message() && w == id) || message == WM_NCDESTROY { + // SAFETY: removes this subclass, on the window it was set on. + unsafe { RemoveWindowSubclass(hwnd, Some(menu_procedure), id) }; + if message != WM_NCDESTROY { + let (x, y) = ((point & 0xffff) as u16 as i16 as i32, (point >> 16 & 0xffff) as u16 as i16 as i32); + std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| track_window_menu(hwnd, x, y))).ok(); + return 0; + } + } + // SAFETY: passes every other message on. + unsafe { DefSubclassProc(hwnd, message, w, l) } +} + +/// Shows the window menu at screen point (`x`, `y`) until it closes, and carries out the pick. +fn track_window_menu(hwnd: HWND, x: i32, y: i32) { + let Some(_modal) = crate::popup_menu::enter_menu_loop() else { return }; + // SAFETY: `IsWindow` safely validates whether `hwnd` still refers to a live window. + if unsafe { IsWindow(hwnd) == 0 } { return; } + let _turns = crate::popup_menu::turns(hwnd); + // SAFETY: Win32 calls on a live window this thread owns and its own system menu. + unsafe { + let menu = GetSystemMenu(hwnd, 0); + if menu.is_null() { return; } + let zoomed = IsZoomed(hwnd) != 0; + let style = GetWindowLongPtrW(hwnd, GWL_STYLE) as u32; + let enable = |item: u32, on: bool| { EnableMenuItem(menu, item, MF_BYCOMMAND | if on { MF_ENABLED } else { MF_GRAYED }); }; + enable(SC_RESTORE, zoomed); + enable(SC_MOVE, !zoomed); + enable(SC_SIZE, !zoomed && style & WS_THICKFRAME != 0); + enable(SC_MINIMIZE, style & WS_MINIMIZEBOX != 0); + enable(SC_MAXIMIZE, !zoomed && style & WS_MAXIMIZEBOX != 0); + enable(SC_CLOSE, true); + SetMenuDefaultItem(menu, SC_CLOSE, 0); + let picked = TrackPopupMenu(menu, TPM_RETURNCMD | TPM_RIGHTBUTTON | crate::popup_menu::layout(), x, y, 0, hwnd, std::ptr::null()); + if picked != 0 && IsWindow(hwnd) != 0 { PostMessageW(hwnd, WM_SYSCOMMAND, picked as WPARAM, 0); } + } +} + +thread_local! { + /// The windows on this thread with a custom frame. (`GetWindowSubclass` would say, but the + /// system's version 5 comctl32 exports it only by ordinal.) + static FRAMED: std::cell::RefCell<Vec<usize>> = const { std::cell::RefCell::new(Vec::new()) }; +} + +pub(super) fn installed(hwnd: HWND) -> bool { + FRAMED.with(|f| f.borrow().contains(&(hwnd as usize))) +} + +unsafe extern "system" fn subclass(hwnd: HWND, message: u32, wparam: WPARAM, lparam: LPARAM, _: usize, data: usize) -> LRESULT { + let ptr = data as *const State; + if message == WM_NCDESTROY { + FRAMED.with(|f| f.borrow_mut().retain(|&h| h != hwnd as usize)); + // SAFETY: removes this subclass; if it was still installed, reclaims the ref `install` gave it. + unsafe { + if RemoveWindowSubclass(hwnd, Some(subclass), SUBCLASS) != 0 { + drop(Rc::from_raw(ptr)); + } + return DefSubclassProc(hwnd, message, wparam, lparam); + } + } + // Hold our own strong reference for the duration of this callback so a re-entrant + // `WM_NCDESTROY` during `DefSubclassProc` or a modal menu loop cannot free `State` while + // this stack frame still uses it. + // SAFETY: `ptr` is the live `Rc<State>` owned by the subclass until `WM_NCDESTROY`. + let state: Rc<State> = unsafe { + Rc::increment_strong_count(ptr); + Rc::from_raw(ptr) + }; + let state: &State = &state; + if !framed(hwnd) { + // Full screen: no frame to adjust. + // SAFETY: forwards to the next window procedure. + return unsafe { DefSubclassProc(hwnd, message, wparam, lparam) }; + } + // SAFETY: each arm reads the message's own parameters as Windows documents them, on a + // live window this thread owns. + unsafe { + match message { + WM_NCCALCSIZE if wparam != 0 => { + let params = &mut *(lparam as *mut NCCALCSIZE_PARAMS); + let outer = params.rgrc[0]; + DefSubclassProc(hwnd, message, wparam, lparam); + params.rgrc[0].top = outer.top + top_border(hwnd); + if IsZoomed(hwnd) != 0 { fit_maximized(hwnd, &outer, &mut params.rgrc[0]); } + return 0; + } + WM_NCHITTEST => { + let hit = DefSubclassProc(hwnd, message, wparam, lparam); + if hit != HTCLIENT as LRESULT { return hit; } + return hit_test(state, hwnd, POINT { x: lparam as i16 as i32, y: (lparam >> 16) as i16 as i32 }) as LRESULT; + } + // The default procedure would paint the classic frame's background first. + WM_ERASEBKGND => return 1, + WM_NCMOUSEMOVE => { + let button = caption_button(wparam); + // A press keeps the mouse; a move here means it lost it (WM_CAPTURECHANGED). + if !matches!(state.caption.get(), CaptionState::Pressed { .. }) { + state.set(hwnd, button.map_or(CaptionState::Idle, CaptionState::Hovered)); + } + if button.is_some() { + let mut track = TRACKMOUSEEVENT { cbSize: size_of::<TRACKMOUSEEVENT>() as u32, dwFlags: TME_LEAVE | TME_NONCLIENT, hwndTrack: hwnd, dwHoverTime: 0 }; + TrackMouseEvent(&mut track); + return 0; + } + } + WM_NCMOUSELEAVE if matches!(state.caption.get(), CaptionState::Hovered(_)) => state.set(hwnd, CaptionState::Idle), + // Captured by a press: the pointer moves on or off its button, wherever it goes, and + // never hovers another. The view never sees these moves. + WM_MOUSEMOVE if let CaptionState::Pressed { button, .. } = state.caption.get() => { + if wparam & MK_LBUTTON == 0 { + // The button went up where no release reached the window. + state.release(hwnd, button, false); + } else { + let over = caption_hit(state, hwnd, client_point(lparam)) == Some(button); + state.set(hwnd, CaptionState::Pressed { button, over }); + } + return 0; + } + WM_MOUSEMOVE if matches!(state.caption.get(), CaptionState::Hovered(_)) => state.set(hwnd, CaptionState::Idle), + WM_NCLBUTTONDOWN | WM_NCLBUTTONDBLCLK if let Some(button) = caption_button(wparam) => { + state.set(hwnd, CaptionState::Pressed { button, over: true }); + SetCapture(hwnd); + return 0; + } + WM_LBUTTONUP if let CaptionState::Pressed { button, .. } = state.caption.get() => { + state.release(hwnd, button, caption_hit(state, hwnd, client_point(lparam)) == Some(button)); + return 0; + } + WM_NCLBUTTONUP => { + if let CaptionState::Pressed { button, .. } = state.caption.get() { + state.release(hwnd, button, caption_button(wparam) == Some(button)); + return 0; + } + if caption_button(wparam).is_some() { return 0; } + } + // Another window took the mouse, or a menu or drag loop cancelled the press. + WM_CAPTURECHANGED | WM_CANCELMODE if matches!(state.caption.get(), CaptionState::Pressed { .. }) => { + state.set(hwnd, CaptionState::Idle); + if message == WM_CANCELMODE { ReleaseCapture(); } + } + // Alt+Space right to left: the window menu at the window's top right corner, laid + // out right to left, where a right-to-left window's opens; Windows' own keyboard + // menu would open left to right at the top left. + WM_SYSCOMMAND if wparam & 0xFFF0 == SC_KEYMENU as WPARAM && lparam == LPARAM::from(b' ') && crate::labels::rtl() => { + if let Some((x, y)) = client_top_right(hwnd) { track_window_menu(hwnd, x, y); } + return 0; + } + WM_NCRBUTTONDOWN | WM_NCRBUTTONUP | WM_NCRBUTTONDBLCLK if caption_button(wparam).is_some() => return 0, + // The default would repaint a title bar this window doesn't have. + WM_NCACTIVATE => return DefSubclassProc(hwnd, message, wparam, -1), + WM_GETMINMAXINFO => { + let info = &mut *(lparam as *mut MINMAXINFO); + let (min, max) = (info.ptMinTrackSize.y, info.ptMaxTrackSize.y); + let result = DefSubclassProc(hwnd, message, wparam, lparam); + // winit sized them for a title bar: take it back off what it set. + let top = borders(hwnd, GetDpiForWindow(hwnd)).top - top_border(hwnd); + if info.ptMinTrackSize.y != min { info.ptMinTrackSize.y = (info.ptMinTrackSize.y - top).max(1); } + if info.ptMaxTrackSize.y != max { info.ptMaxTrackSize.y = (info.ptMaxTrackSize.y - top).max(1); } + return result; + } + WM_GETDPISCALEDSIZE if IsZoomed(hwnd) == 0 => { + let dpi = wparam as u32; + let (w, h) = client_size(hwnd); + let ratio = f64::from(dpi) / f64::from(GetDpiForWindow(hwnd).max(1)); + let b = borders(hwnd, dpi); + let out = &mut *(lparam as *mut SIZE); + out.cx = (f64::from(w) * ratio).round() as i32 + b.left + b.right; + out.cy = (f64::from(h) * ratio).round() as i32 + top_border(hwnd) + b.bottom; + return 1; + } + // winit sizes the window for a title bar; Windows' rect (from WM_GETDPISCALEDSIZE) + // is right. A maximized window keeps its size. + WM_DPICHANGED => { + if IsZoomed(hwnd) == 0 { state.dpi_rect.set(Some(*(lparam as *const RECT))); } + let result = DefSubclassProc(hwnd, message, wparam, lparam); + state.dpi_rect.set(None); + return result; + } + WM_WINDOWPOSCHANGING if let Some(r) = state.dpi_rect.get() => { + let pos = &mut *(lparam as *mut WINDOWPOS); + if pos.flags & SWP_NOMOVE == 0 { (pos.x, pos.y) = (r.left, r.top); } + if pos.flags & SWP_NOSIZE == 0 { (pos.cx, pos.cy) = (r.right - r.left, r.bottom - r.top); } + } + _ => {} + } + DefSubclassProc(hwnd, message, wparam, lparam) + } +} + +impl State { + fn set(&self, hwnd: HWND, caption: CaptionState) { + if self.caption.replace(caption) != caption { invalidate(hwnd); } + } + + /// Ends a press on `button`: it acts when released `over` it. + fn release(&self, hwnd: HWND, button: CaptionButton, over: bool) { + // Idle first: releasing the capture sends WM_CAPTURECHANGED. + self.set(hwnd, CaptionState::Idle); + // SAFETY: Win32 calls on a live window this thread owns. + unsafe { + ReleaseCapture(); + if !over { return; } + let command = match button { + CaptionButton::Minimize => SC_MINIMIZE, + CaptionButton::Maximize if IsZoomed(hwnd) != 0 => SC_RESTORE, + CaptionButton::Maximize => SC_MAXIMIZE, + CaptionButton::Close => SC_CLOSE, + }; + PostMessageW(hwnd, WM_SYSCOMMAND, command as WPARAM, 0); + } + } + + /// The caption buttons as the window is now: which it has, and the pointer's state. + fn caption(&self, hwnd: HWND) -> Caption { + // SAFETY: reads a live window's state and style. + let (zoomed, style) = unsafe { (IsZoomed(hwnd) != 0, GetWindowLongPtrW(hwnd, GWL_STYLE) as u32) }; + Caption { + height: self.height.get(), + state: self.caption.get(), + maximized: zoomed, + minimizable: style & WS_MINIMIZEBOX != 0, + maximizable: style & WS_MAXIMIZEBOX != 0, + hidden: !framed(hwnd), + mirrored: crate::labels::rtl(), + } + } +} + +/// The caption buttons draw with the next frame: winit turns the paint into a redraw. +fn invalidate(hwnd: HWND) { + // SAFETY: a Win32 call on a live window this thread owns. + unsafe { InvalidateRect(hwnd, std::ptr::null(), 0); } +} + +/// A window with a title bar style, so not full screen. +fn framed(hwnd: HWND) -> bool { + // SAFETY: reads the style of a live window. + let style = unsafe { GetWindowLongPtrW(hwnd, GWL_STYLE) } as u32; + style & WS_CAPTION == WS_CAPTION +} + +fn caption_button(hit: WPARAM) -> Option<CaptionButton> { + match hit as u32 { + HTMINBUTTON => Some(CaptionButton::Minimize), + HTMAXBUTTON => Some(CaptionButton::Maximize), + HTCLOSE => Some(CaptionButton::Close), + _ => None, + } +} + +fn client_point(lparam: LPARAM) -> POINT { + POINT { x: lparam as i16 as i32, y: (lparam >> 16) as i16 as i32 } +} + +/// What a point (screen pixels) in the client area hits: the top resize edge, an enabled +/// caption button, or the client. +fn hit_test(state: &State, hwnd: HWND, mut point: POINT) -> u32 { + // SAFETY: Win32 calls on a live window this thread owns. + let (dpi, zoomed, resizable) = unsafe { + ScreenToClient(hwnd, &mut point); + let style = GetWindowLongPtrW(hwnd, GWL_STYLE) as u32; + (GetDpiForWindow(hwnd), IsZoomed(hwnd) != 0, style & WS_THICKFRAME != 0) + }; + let edge = frame_thickness(dpi); + let client_width = client_size(hwnd).0; + if !zoomed && resizable && point.y >= 0 && point.y < edge { + return if point.x < edge { HTTOPLEFT } else if point.x >= client_width - edge { HTTOPRIGHT } else { HTTOP }; + } + match caption_hit(state, hwnd, point) { + Some(CaptionButton::Minimize) => HTMINBUTTON, + Some(CaptionButton::Maximize) => HTMAXBUTTON, + Some(CaptionButton::Close) => HTCLOSE, + None => HTCLIENT, + } +} + +/// The enabled caption button under a point in client pixels. +fn caption_hit(state: &State, hwnd: HWND, point: POINT) -> Option<CaptionButton> { + // SAFETY: reads a live window's scale. + let scale = unsafe { GetDpiForWindow(hwnd) } as f32 / 96.0; + let width = client_size(hwnd).0 as f32 / scale; + state.caption(hwnd).hit(width, scale, (point.x as f32 / scale, point.y as f32 / scale)) +} + +/// The sizing border's thickness: the top resize edge, and how far a maximized window's top +/// hangs off the display. +fn frame_thickness(dpi: u32) -> i32 { + // SAFETY: reads system metrics. + unsafe { GetSystemMetricsForDpi(SM_CYFRAME, dpi) + GetSystemMetricsForDpi(SM_CXPADDEDBORDER, dpi) } +} + +/// The non-client pixels left at the top: Windows 10 draws a restored window's top border only +/// over non-client pixels. +fn top_border(hwnd: HWND) -> i32 { + // SAFETY: reads a live window's state. + i32::from(windows_10() && unsafe { IsZoomed(hwnd) } == 0) +} + +/// Windows before 11 (build 22000). `RtlGetVersion` reports the real build, whatever the +/// executable's manifest says. +fn windows_10() -> bool { + static BEFORE_11: OnceLock<bool> = OnceLock::new(); + *BEFORE_11.get_or_init(|| { + #[repr(C)] + struct Version { size: u32, major: u32, minor: u32, build: u32, platform: u32, service_pack: [u16; 128] } + let mut v = Version { size: size_of::<Version>() as u32, major: 0, minor: 0, build: 0, platform: 0, service_pack: [0; 128] }; + let ntdll: Vec<u16> = "ntdll.dll\0".encode_utf16().collect(); + // SAFETY: ntdll is loaded in every process; RtlGetVersion fills the OSVERSIONINFOW + // `Version` mirrors, whose size field says which struct it is. + unsafe { + let Some(get) = GetProcAddress(GetModuleHandleW(ntdll.as_ptr()), c"RtlGetVersion".as_ptr().cast()) else { return false }; + let get: unsafe extern "system" fn(*mut Version) -> i32 = std::mem::transmute(get); + get(&mut v) == 0 && v.major == 10 && v.build < 22000 + } + }) +} + +/// What the window's frame adds around its client area while it is restored, at `dpi`, each +/// edge as a positive width: a custom frame keeps the standard frame's sides and bottom, and at +/// the top only Windows 10's non-client row. +pub(super) fn restored_borders(hwnd: HWND, dpi: u32) -> RECT { + let b = borders(hwnd, dpi); + if !installed(hwnd) || !framed(hwnd) { return b; } + RECT { top: i32::from(windows_10()), ..b } +} + +/// What a standard frame adds around the client area at `dpi`, each edge as a positive width. +fn borders(hwnd: HWND, dpi: u32) -> RECT { + let mut r = RECT { left: 0, top: 0, right: 0, bottom: 0 }; + // SAFETY: reads a live window's styles, and fills `r`. + unsafe { + let style = GetWindowLongPtrW(hwnd, GWL_STYLE) as u32; + let ex = GetWindowLongPtrW(hwnd, GWL_EXSTYLE) as u32; + AdjustWindowRectExForDpi(&mut r, style, 0, ex, dpi); + } + RECT { left: -r.left, top: -r.top, right: r.right, bottom: r.bottom } +} + +/// A maximized window hangs its frame off the display: the client area starts below the top +/// that hangs off, and leaves a pixel at an edge with an auto-hiding taskbar so the pointer +/// can still bring it up. `outer` is the window's new rect, on the display it maximizes on, +/// which may not be the one it is on yet. +fn fit_maximized(hwnd: HWND, outer: &RECT, client: &mut RECT) { + // SAFETY: Win32 calls on a live window, its monitor and the shell's app bars. + unsafe { + client.top += frame_thickness(GetDpiForWindow(hwnd)); + let monitor = MonitorFromRect(outer, MONITOR_DEFAULTTONEAREST); + let mut info: MONITORINFO = std::mem::zeroed(); + info.cbSize = size_of::<MONITORINFO>() as u32; + if GetMonitorInfoW(monitor, &mut info) == 0 { return; } + for edge in [ABE_TOP, ABE_LEFT, ABE_BOTTOM, ABE_RIGHT] { + let mut bar: APPBARDATA = std::mem::zeroed(); + bar.cbSize = size_of::<APPBARDATA>() as u32; + bar.uEdge = edge; + bar.rc = info.rcMonitor; + let found = SHAppBarMessage(ABM_GETAUTOHIDEBAREX, &mut bar) as HWND; + if found.is_null() || IsWindow(found) == 0 { continue; } + match edge { + ABE_TOP => client.top += 1, + ABE_LEFT => client.left += 1, + ABE_BOTTOM => client.bottom -= 1, + _ => client.right -= 1, + } + } + } +} + +fn client_size(hwnd: HWND) -> (i32, i32) { + let mut r = RECT { left: 0, top: 0, right: 0, bottom: 0 }; + // SAFETY: fills `r` for a live window. + unsafe { GetClientRect(hwnd, &mut r); } + (r.right - r.left, r.bottom - r.top) +} diff --git a/app/vendor/rune/crates/rune/src/platform/win32/jump_list.rs b/app/vendor/rune/crates/rune/src/platform/win32/jump_list.rs new file mode 100644 index 0000000..6b74e60 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/platform/win32/jump_list.rs @@ -0,0 +1,128 @@ +//! The taskbar's jump list (`crate::jump_list`), through the shell's `ICustomDestinationList`, on +//! a thread of its own: made on the first list, asleep on its channel in between, its own COM +//! apartment. Each entry is a shell link to this executable with the entry's argument. + +#![allow(unsafe_code)] + +use std::collections::HashSet; +use std::sync::mpsc::{Receiver, Sender, channel}; +use std::sync::{Mutex, OnceLock}; + +use windows::Win32::Foundation::PROPERTYKEY; +use windows::Win32::System::Com::StructuredStorage::PROPVARIANT; +use windows::Win32::System::Com::{CLSCTX_INPROC_SERVER, COINIT_APARTMENTTHREADED, CoCreateInstance, CoInitializeEx}; +use windows::Win32::UI::Shell::Common::{IObjectArray, IObjectCollection}; +use windows::Win32::UI::Shell::PropertiesSystem::IPropertyStore; +use windows::Win32::UI::Shell::{DestinationList, EnumerableObjectCollection, ICustomDestinationList, IShellLinkW, ShellLink}; +use windows::core::{HSTRING, Interface}; + +use crate::jump_list::{JumpItem, JumpList}; + +/// `PKEY_Title`: an entry's title (a shell link's own name is its target's). +const TITLE: PROPERTYKEY = PROPERTYKEY { fmtid: windows::core::GUID::from_u128(0xf29f85e0_4ff9_1068_ab91_08002b27b3d9), pid: 2 }; + +struct Worker { + to: Sender<JumpList>, + last: Option<JumpList>, +} + +static WORKER: OnceLock<Mutex<Worker>> = OnceLock::new(); + +pub(crate) fn set(list: JumpList) { + let worker = WORKER.get_or_init(|| { + let (to, from) = channel(); + let spawned = std::thread::Builder::new().name("rune-jump-list".into()).spawn(move || run(from)); + if let Err(e) = spawned { eprintln!("rune: jump list: {e}"); } + Mutex::new(Worker { to, last: None }) + }); + let mut w = worker.lock().unwrap_or_else(|e| e.into_inner()); + if w.last.as_ref() == Some(&list) { return; } + w.last = Some(list.clone()); + w.to.send(list).ok(); +} + +fn run(from: Receiver<JumpList>) { + // SAFETY: this thread's own single-threaded apartment, for the shell's objects. + if unsafe { CoInitializeEx(None, COINIT_APARTMENTTHREADED) }.is_err() { return; } + let Some(exe) = std::env::current_exe().ok() else { return }; + let exe = HSTRING::from(exe.as_os_str()); + while let Ok(mut list) = from.recv() { + // Only the newest of lists sent meanwhile. + while let Ok(newer) = from.try_recv() { list = newer; } + let started = crate::time::now(); + // SAFETY: shell COM calls in this thread's apartment. + match unsafe { commit(&list, &exe) } { + Ok(n) => eprintln!("rune: jump list: {n} entries committed in {} µs off the UI thread", started.elapsed().as_micros()), + Err(e) => eprintln!("rune: jump list: {e}"), + } + } +} + +unsafe fn commit(list: &JumpList, exe: &HSTRING) -> windows::core::Result<usize> { + // SAFETY: shell COM calls in this thread's apartment, on objects made here. + unsafe { + let dest: ICustomDestinationList = CoCreateInstance(&DestinationList, None, CLSCTX_INPROC_SERVER)?; + let mut slots = 0u32; + let removed: IObjectArray = dest.BeginList(&mut slots)?; + let removed = removed_arguments(&removed); + let mut n = 0; + if !list.tasks.is_empty() { + let tasks = collection(&list.tasks, list.lead.as_deref(), exe, &HashSet::new())?; + dest.AddUserTasks(&tasks)?; + n += list.tasks.len(); + } + for (name, items) in &list.categories { + let kept: Vec<&JumpItem> = items.iter().filter(|i| !removed.contains(&i.argument)).collect(); + if kept.is_empty() { continue; } + let entries = collection(items, list.lead.as_deref(), exe, &removed)?; + // A category the person removed entries from, or that policy hides, is skipped. + if dest.AppendCategory(&HSTRING::from(name.as_str()), &entries).is_ok() { n += kept.len(); } + } + dest.CommitList()?; + Ok(n) + } +} + +/// The arguments of the entries the person removed: Windows refuses a list that adds them back. +unsafe fn removed_arguments(removed: &IObjectArray) -> HashSet<String> { + // SAFETY: reads the shell's array of links. + unsafe { + let count = removed.GetCount().unwrap_or(0); + (0..count).filter_map(|i| { + let link: IShellLinkW = removed.GetAt(i).ok()?; + let mut buf = [0u16; 2048]; + link.GetArguments(&mut buf).ok()?; + let len = buf.iter().position(|&c| c == 0).unwrap_or(buf.len()); + Some(last_argument(&String::from_utf16_lossy(&buf[..len]))) + }).collect() + } +} + +unsafe fn collection(items: &[JumpItem], lead: Option<&str>, exe: &HSTRING, removed: &HashSet<String>) -> windows::core::Result<IObjectArray> { + // SAFETY: shell COM calls on objects made here. + unsafe { + let all: IObjectCollection = CoCreateInstance(&EnumerableObjectCollection, None, CLSCTX_INPROC_SERVER)?; + for item in items.iter().filter(|i| !removed.contains(&i.argument)) { + let link: IShellLinkW = CoCreateInstance(&ShellLink, None, CLSCTX_INPROC_SERVER)?; + link.SetPath(exe)?; + let arguments = match lead { Some(lead) => format!("\"{lead}\" \"{}\"", item.argument), None => format!("\"{}\"", item.argument) }; + link.SetArguments(&HSTRING::from(arguments))?; + link.SetIconLocation(exe, 0)?; + if !item.description.is_empty() { link.SetDescription(&HSTRING::from(item.description.as_str()))?; } + let props: IPropertyStore = link.cast()?; + props.SetValue(&TITLE, &PROPVARIANT::from(item.title.as_str()))?; + props.Commit()?; + all.AddObject(&link)?; + } + all.cast() + } +} + +/// An entry's own argument: the last one on its link's command line, after any `lead`. +fn last_argument(s: &str) -> String { + let s = s.trim(); + match s.strip_suffix('"').and_then(|rest| rest.rfind('"').map(|at| &rest[at + 1..])) { + Some(quoted) => quoted.to_owned(), + None => s.rsplit(' ').next().unwrap_or_default().to_owned(), + } +} diff --git a/app/vendor/rune/crates/rune/src/platform/win32/occlusion.rs b/app/vendor/rune/crates/rune/src/platform/win32/occlusion.rs new file mode 100644 index 0000000..13249e0 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/platform/win32/occlusion.rs @@ -0,0 +1,201 @@ +//! Whether a window can be seen, asked when it's about to draw a frame (`window::look`), never +//! listened for. Nothing in the process hears other apps' windows: a window that draws nothing +//! costs nothing whatever the rest of the desktop does, and one that draws pays one walk of the +//! z-order a quarter second at most. +//! +//! The walk is Chromium's `WindowOcclusionCalculator`'s: from the top of the z-order down, what's +//! left of the screens shrinks by each opaque window, and the window shows if any of what's left +//! is in its rect when the walk reaches it. Minimised, on another virtual desktop (DWM cloaks it) +//! or behind the lock screen, it's covered too. +//! +//! Only on the desktop the user sees. A window on another one (a capture harness's hidden +//! desktop, which several apps share) is never covered, so it keeps drawing for whoever reads +//! its pixels. + +#![allow(unsafe_code)] + +use windows_sys::Win32::Foundation::{HWND, LPARAM, RECT, TRUE}; +use windows_sys::core::BOOL; +use windows_sys::Win32::Graphics::Dwm::{DWM_CLOAKED_SHELL, DWMWA_CLOAKED, DWMWA_EXTENDED_FRAME_BOUNDS, DwmGetWindowAttribute}; +use windows_sys::Win32::Graphics::Gdi::{ + COMPLEXREGION, CombineRgn, CreateRectRgn, DeleteObject, EnumDisplayMonitors, GetMonitorInfoW, GetWindowRgn, HDC, HMONITOR, HRGN, + MONITOR_DEFAULTTONEAREST, MONITORINFO, MonitorFromWindow, RGN_DIFF, RGN_OR, RectInRegion, +}; +use windows_sys::Win32::System::StationsAndDesktops::{CloseDesktop, DESKTOP_READOBJECTS, GetThreadDesktop, GetUserObjectInformationW, HDESK, OpenInputDesktop, UOI_NAME}; +use windows_sys::Win32::System::Threading::GetCurrentThreadId; +use windows_sys::Win32::UI::WindowsAndMessaging::{ + EnumWindows, GWL_EXSTYLE, GWL_STYLE, GetClassNameW, GetLayeredWindowAttributes, GetWindowLongW, GetWindowPlacement, IsIconic, IsWindowVisible, + LWA_ALPHA, LWA_COLORKEY, SW_MAXIMIZE, WINDOWPLACEMENT, WS_EX_LAYERED, WS_EX_TOOLWINDOW, WS_EX_TRANSPARENT, WS_POPUP, +}; + +/// What a look found. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum Found { + Seen, + Covered, +} + +/// Whether `window` can be seen now. +pub(crate) fn look(window: &winit::window::Window) -> Found { + let Some(hwnd) = super::hwnd(window) else { return Found::Seen }; + match desktop() { + Desktop::Other => return Found::Seen, + Desktop::Locked => return Found::Covered, + Desktop::Shown => {} + } + // SAFETY: plain queries on a live top-level window. + unsafe { + if IsWindowVisible(hwnd) == 0 { return Found::Seen; } + if IsIconic(hwnd) != 0 || cloaked(hwnd).is_some_and(|c| c & DWM_CLOAKED_SHELL != 0) { return Found::Covered; } + } + walk(hwnd) +} + +/// Where this thread's desktop is, against the one the user sees. +enum Desktop { + /// It's the one the user sees. + Shown, + /// The user's, behind the lock screen or a secure desktop (the input desktop can't be read). + Locked, + /// Another one (a harness's hidden desktop): nothing covers it. + Other, +} + +fn desktop() -> Desktop { + // SAFETY: desktop handles this function opens it closes; the thread's own isn't closed. + unsafe { + let ours = desktop_name(GetThreadDesktop(GetCurrentThreadId())); + let input = OpenInputDesktop(0, 0, DESKTOP_READOBJECTS); + if input.is_null() { + return if ours.as_deref() == Some(DEFAULT) { Desktop::Locked } else { Desktop::Other }; + } + let same = desktop_name(input).is_some_and(|name| ours == Some(name)); + CloseDesktop(input); + if same { Desktop::Shown } else if ours.as_deref() == Some(DEFAULT) { Desktop::Locked } else { Desktop::Other } + } +} + +/// The interactive desktop's name ("Default"). +const DEFAULT: &[u16] = &[0x44, 0x65, 0x66, 0x61, 0x75, 0x6C, 0x74]; + +fn desktop_name(desktop: HDESK) -> Option<Vec<u16>> { + if desktop.is_null() { return None; } + let mut name = [0u16; 256]; + let mut needed = 0u32; + // SAFETY: `name` holds 512 bytes, as passed. + let ok = unsafe { GetUserObjectInformationW(desktop, UOI_NAME, name.as_mut_ptr().cast(), std::mem::size_of_val(&name) as u32, &mut needed) }; + if ok == 0 { return None; } + Some(name.iter().copied().take_while(|&c| c != 0).collect()) +} + +/// One walk down the z-order to `target`. +fn walk(target: HWND) -> Found { + struct Walk { + target: HWND, + left: HRGN, + found: Option<Found>, + } + unsafe extern "system" fn monitor(_m: HMONITOR, _dc: HDC, rect: *mut RECT, data: LPARAM) -> BOOL { + // SAFETY: `data` is the walk's region; `rect` the monitor's, from the system. + unsafe { + let left = data as HRGN; + let r = &*rect; + let screen = CreateRectRgn(r.left, r.top, r.right, r.bottom); + CombineRgn(left, left, screen, RGN_OR); + DeleteObject(screen); + } + TRUE + } + unsafe extern "system" fn window(hwnd: HWND, data: LPARAM) -> BOOL { + // SAFETY: `data` is the `Walk` `walk` passes, alive for the enumeration. + let walk = unsafe { &mut *(data as *mut Walk) }; + if hwnd == walk.target { + // SAFETY: a live top-level window and the walk's region. + let shows = bounds(hwnd).is_none_or(|r| unsafe { RectInRegion(walk.left, &r) } != 0); + walk.found = Some(if shows { Found::Seen } else { Found::Covered }); + return 0; + } + if let Some(r) = opaque_rect(hwnd) { + // SAFETY: regions this walk owns. + unsafe { + let rgn = CreateRectRgn(r.left, r.top, r.right, r.bottom); + CombineRgn(walk.left, walk.left, rgn, RGN_DIFF); + DeleteObject(rgn); + } + } + TRUE + } + // SAFETY: the region is this walk's, deleted below; the callbacks get valid pointers. + unsafe { + let left = CreateRectRgn(0, 0, 0, 0); + EnumDisplayMonitors(std::ptr::null_mut(), std::ptr::null(), Some(monitor), left as LPARAM); + let mut walk = Walk { target, left, found: None }; + EnumWindows(Some(window), (&raw mut walk) as LPARAM); + DeleteObject(left); + // Not reached (destroyed meanwhile): nothing to hold back. + walk.found.unwrap_or(Found::Seen) + } +} + +/// The rect an opaque window covers, or None for one that may let what's under it show, as +/// Chromium's `IsWindowVisibleAndFullyOpaque` decides. +fn opaque_rect(hwnd: HWND) -> Option<RECT> { + // SAFETY: plain queries on a window `EnumWindows` handed over. + unsafe { + if IsWindowVisible(hwnd) == 0 || IsIconic(hwnd) != 0 { return None; } + let ex = GetWindowLongW(hwnd, GWL_EXSTYLE) as u32; + // Clicks fall through it. + if ex & WS_EX_TRANSPARENT != 0 { return None; } + // Floating windows can be larger than what they draw; the taskbar isn't. + if (ex & WS_EX_TOOLWINDOW != 0 || GetWindowLongW(hwnd, GWL_STYLE) as u32 & WS_POPUP != 0) && !taskbar(hwnd) { return None; } + if ex & WS_EX_LAYERED != 0 { + let (mut key, mut alpha, mut flags) = (0u32, 0u8, 0u32); + // Fails for a window drawn with UpdateLayeredWindow: per-pixel alpha. + if GetLayeredWindowAttributes(hwnd, &mut key, &mut alpha, &mut flags) == 0 { return None; } + if flags & LWA_COLORKEY != 0 || (flags & LWA_ALPHA != 0 && alpha < 255) { return None; } + } + let rgn = CreateRectRgn(0, 0, 0, 0); + let shape = GetWindowRgn(hwnd, rgn); + DeleteObject(rgn); + if shape == COMPLEXREGION { return None; } + // Shown to no one: on another virtual desktop, or a shell window kept for later. + if cloaked(hwnd).is_some_and(|c| c != 0) { return None; } + let mut r = bounds(hwnd)?; + if r.right <= r.left || r.bottom <= r.top { return None; } + let mut placement: WINDOWPLACEMENT = std::mem::zeroed(); + placement.length = std::mem::size_of::<WINDOWPLACEMENT>() as u32; + if GetWindowPlacement(hwnd, &mut placement) != 0 && placement.showCmd == SW_MAXIMIZE as u32 { + let mut info: MONITORINFO = std::mem::zeroed(); + info.cbSize = std::mem::size_of::<MONITORINFO>() as u32; + if GetMonitorInfoW(MonitorFromWindow(hwnd, MONITOR_DEFAULTTONEAREST), &mut info) != 0 { + let w = info.rcWork; + r = RECT { left: r.left.max(w.left), top: r.top.max(w.top), right: r.right.min(w.right), bottom: r.bottom.min(w.bottom) }; + } + } + Some(r) + } +} + +/// The rect DWM draws a window in, without its invisible resize borders. +fn bounds(hwnd: HWND) -> Option<RECT> { + let mut r = RECT { left: 0, top: 0, right: 0, bottom: 0 }; + // SAFETY: `r` is a RECT, as the attribute's size says. + let hr = unsafe { DwmGetWindowAttribute(hwnd, DWMWA_EXTENDED_FRAME_BOUNDS as u32, (&raw mut r).cast(), std::mem::size_of::<RECT>() as u32) }; + (hr >= 0).then_some(r) +} + +/// Why DWM keeps a window off screen, if it does: `DWM_CLOAKED_SHELL` for another virtual +/// desktop, `DWM_CLOAKED_APP` for its app's own cloak. +fn cloaked(hwnd: HWND) -> Option<u32> { + let mut why = 0u32; + // SAFETY: `why` is a u32, as the attribute's size says. + let hr = unsafe { DwmGetWindowAttribute(hwnd, DWMWA_CLOAKED as u32, (&raw mut why).cast(), 4) }; + (hr >= 0).then_some(why) +} + +fn taskbar(hwnd: HWND) -> bool { + let mut class = [0u16; 32]; + // SAFETY: `class` holds 32 characters, as passed. + let n = unsafe { GetClassNameW(hwnd, class.as_mut_ptr(), class.len() as i32) }; + n > 0 && String::from_utf16_lossy(&class[..n as usize]) == "Shell_TrayWnd" +} diff --git a/app/vendor/rune/crates/rune/src/platform/win32/placement.rs b/app/vendor/rune/crates/rune/src/platform/win32/placement.rs new file mode 100644 index 0000000..f78e71a --- /dev/null +++ b/app/vendor/rune/crates/rune/src/platform/win32/placement.rs @@ -0,0 +1,38 @@ +//! Where a maximized or minimized window goes back to (`WindowPlacement::restore`), as Windows +//! keeps it. Windows moves that frame with the window: Win+Shift+Arrow takes a maximized window +//! to another display and its restored frame with it, which reading the window's frame while it +//! is restored can never see. + +#![allow(unsafe_code)] + +use windows_sys::Win32::Graphics::Gdi::{GetMonitorInfoW, MONITOR_DEFAULTTONEAREST, MONITORINFO, MonitorFromRect}; +use windows_sys::Win32::UI::HiDpi::GetDpiForWindow; +use windows_sys::Win32::UI::WindowsAndMessaging::{GWL_EXSTYLE, GetWindowLongPtrW, GetWindowPlacement, WINDOWPLACEMENT, WS_EX_TOOLWINDOW}; + +/// The frame restoring `window` returns to: its top-left in desktop pixels and its content +/// size, the space `WindowOptions::position` and `physical_size` take. +pub(crate) fn restore_frame(window: &winit::window::Window) -> Option<((i32, i32), (u32, u32))> { + let hwnd = super::hwnd(window)?; + // SAFETY: plain queries on a live window this thread owns; each struct carries its size. + unsafe { + let mut p: WINDOWPLACEMENT = std::mem::zeroed(); + p.length = size_of::<WINDOWPLACEMENT>() as u32; + if GetWindowPlacement(hwnd, &mut p) == 0 { return None; } + let mut r = p.rcNormalPosition; + // Workspace coordinates, whose origin is the top-left of the work area of the display + // the frame is on (a taskbar on the left or top moves it); a tool window's are the + // screen's. Chromium converts them the same way (`HWNDMessageHandler::GetWindowPlacement`). + if GetWindowLongPtrW(hwnd, GWL_EXSTYLE) as u32 & WS_EX_TOOLWINDOW == 0 { + let mut info: MONITORINFO = std::mem::zeroed(); + info.cbSize = size_of::<MONITORINFO>() as u32; + if GetMonitorInfoW(MonitorFromRect(&r, MONITOR_DEFAULTTONEAREST), &mut info) != 0 { + let (dx, dy) = (info.rcWork.left - info.rcMonitor.left, info.rcWork.top - info.rcMonitor.top); + (r.left, r.top, r.right, r.bottom) = (r.left + dx, r.top + dy, r.right + dx, r.bottom + dy); + } + } + let b = super::frame::restored_borders(hwnd, GetDpiForWindow(hwnd)); + let width = (r.right - r.left - b.left - b.right).max(1) as u32; + let height = (r.bottom - r.top - b.top - b.bottom).max(1) as u32; + Some(((r.left, r.top), (width, height))) + } +} diff --git a/app/vendor/rune/crates/rune/src/platform/win32/pointer.rs b/app/vendor/rune/crates/rune/src/platform/win32/pointer.rs new file mode 100644 index 0000000..d768e33 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/platform/win32/pointer.rs @@ -0,0 +1,105 @@ +//! The low-level mouse hook never runs on the rendering/event thread. Its message loop +//! records positions and wakes interested overlays; window styles are changed by the owner. + +#![allow(unsafe_code)] + +use std::sync::{Arc, Mutex, OnceLock, atomic::{AtomicBool, Ordering}}; +use windows_sys::Win32::{Foundation::{LPARAM, LRESULT, POINT, RECT, WPARAM}, UI::WindowsAndMessaging::*}; +use crate::input::pointer_observer::Observer; + +type Observers = Arc<Mutex<Vec<Arc<Observer>>>>; +#[derive(Default)] +struct Service { + observers: Observers, + running: Arc<AtomicBool>, + thread: Option<(u32, std::thread::JoinHandle<()>)>, +} +fn service() -> &'static Mutex<Service> { static SERVICE: OnceLock<Mutex<Service>> = OnceLock::new(); SERVICE.get_or_init(Mutex::default) } +thread_local! { static OBSERVERS: std::cell::RefCell<Option<Observers>> = const { std::cell::RefCell::new(None) }; } + +unsafe extern "system" fn hook(code: i32, kind: WPARAM, data: LPARAM) -> LRESULT { + if code >= 0 && kind as u32 == WM_MOUSEMOVE { + // SAFETY: for `WH_MOUSE_LL` with `code >= 0`, Windows passes a valid `MSLLHOOKSTRUCT` pointer in `data`. + let point = unsafe { (*(data as *const MSLLHOOKSTRUCT)).pt }; + let observers = OBSERVERS.with(|s| s.borrow().as_ref().map(|s| s.lock().unwrap().clone())).unwrap_or_default(); + for observer in observers { observer.observe((point.x, point.y)); } + } + // SAFETY: forwards the hook parameters unchanged to the next hook in the `WH_MOUSE_LL` chain. + unsafe { CallNextHookEx(std::ptr::null_mut(), code, kind, data) } +} + +pub(crate) struct MouseWatch { observer: Arc<Observer>, running: Arc<AtomicBool> } +impl MouseWatch { + pub fn new(wake: Option<crate::Waker>) -> Self { + let observer = Arc::new(Observer::new(wake)); + let mut s = service().lock().unwrap(); + s.observers.lock().unwrap().push(observer.clone()); + if s.thread.is_none() { + let (observers, running) = (s.observers.clone(), s.running.clone()); + let (ready, started) = std::sync::mpsc::sync_channel(1); + // SAFETY: initializes this thread's message queue, installs a `WH_MOUSE_LL` hook with + // this module's handle, pumps messages into a valid local `MSG`, and unhooks before exit. + let thread = std::thread::spawn(move || unsafe { + OBSERVERS.with(|s| *s.borrow_mut() = Some(observers)); + let mut message = std::mem::zeroed(); + PeekMessageW(&mut message, std::ptr::null_mut(), 0, 0, PM_NOREMOVE); + let id = windows_sys::Win32::System::Threading::GetCurrentThreadId(); + let hook = SetWindowsHookExW(WH_MOUSE_LL, Some(hook), windows_sys::Win32::System::LibraryLoader::GetModuleHandleW(std::ptr::null()), 0); + running.store(!hook.is_null(), Ordering::Release); + ready.send(id).ok(); + if !hook.is_null() { + while GetMessageW(&mut message, std::ptr::null_mut(), 0, 0) > 0 { + TranslateMessage(&message); + DispatchMessageW(&message); + } + UnhookWindowsHookEx(hook); + } + running.store(false, Ordering::Release); + OBSERVERS.with(|s| s.borrow_mut().take()); + }); + s.thread = Some((started.recv().unwrap_or(0), thread)); + } + Self { observer, running: s.running.clone() } + } + + pub fn supported(&self) -> bool { self.running.load(Ordering::Acquire) } + pub fn take(&self) -> Option<(i32, i32)> { self.observer.take() } + pub fn observe(&self, point: (i32, i32)) { self.observer.observe(point); } + + /// Main-thread snapshot. The hook reads no HWND, application state, or renderer locks. + pub fn geometry(&self, hwnd: windows_sys::Win32::Foundation::HWND, follow: bool) { + use windows_sys::Win32::Graphics::Gdi::{ClientToScreen, EnumDisplayMonitors}; + // SAFETY: `RECT` is a plain Win32 C struct for which all-zeros is a valid initial value. + let mut rect: RECT = unsafe { std::mem::zeroed() }; + let mut origin = POINT { x: 0, y: 0 }; + // SAFETY: `hwnd` is a live window on the main thread; `rect` and `origin` are valid local out-parameters. + if unsafe { GetClientRect(hwnd, &mut rect) } == 0 || unsafe { ClientToScreen(hwnd, &mut origin) } == 0 { return; } + let canvas = [origin.x, origin.y, origin.x + rect.right, origin.y + rect.bottom]; + if !self.observer.needs_geometry(canvas, follow) { return; } + let mut displays: Vec<[i32; 4]> = Vec::new(); + unsafe extern "system" fn monitor(_: windows_sys::Win32::Graphics::Gdi::HMONITOR, _: windows_sys::Win32::Graphics::Gdi::HDC, rect: *mut RECT, data: LPARAM) -> i32 { + // SAFETY: `EnumDisplayMonitors` passes a valid `RECT` pointer and the `&mut Vec<[i32; 4]>` + // passed as `data`, which stays alive for the synchronous enumeration. + let (r, displays) = unsafe { (&*rect, &mut *(data as *mut Vec<[i32; 4]>)) }; + displays.push([r.left, r.top, r.right, r.bottom]); + 1 + } + // SAFETY: `EnumDisplayMonitors` synchronously invokes `monitor` on this thread while `displays` is exclusively borrowed and alive. + if follow { unsafe { EnumDisplayMonitors(std::ptr::null_mut(), std::ptr::null(), Some(monitor), (&mut displays as *mut Vec<[i32; 4]>) as LPARAM); } } + self.observer.configure(canvas, displays, follow); + } +} +impl Drop for MouseWatch { + fn drop(&mut self) { + let thread = { + let mut s = service().lock().unwrap(); + s.observers.lock().unwrap().retain(|o| !Arc::ptr_eq(o, &self.observer)); + if s.observers.lock().unwrap().is_empty() { s.thread.take() } else { None } + }; + if let Some((id, thread)) = thread { + // SAFETY: `id` is the non-zero Win32 thread ID of the still-unjoined hook thread whose message queue was created before `id` was sent. + if id != 0 { unsafe { PostThreadMessageW(id, WM_QUIT, 0, 0); } } + thread.join().ok(); + } + } +} diff --git a/app/vendor/rune/crates/rune/src/platform/win32/press_point.rs b/app/vendor/rune/crates/rune/src/platform/win32/press_point.rs new file mode 100644 index 0000000..04bbe1d --- /dev/null +++ b/app/vendor/rune/crates/rune/src/platform/win32/press_point.rs @@ -0,0 +1,55 @@ +//! Where the mouse button message being handled says the button went down or up. winit drops +//! the point a button message carries and reports only that the button changed, so the press +//! lands wherever the last move left the pointer. Input that isn't the real mouse (window +//! messages posted by an automation driver) has no real cursor over the window: Windows' leave +//! tracking ends the pointer between the move and the press, and the system cursor is +//! elsewhere, or unreadable on a desktop no one sees. The message's own point is the truth. + +#![allow(unsafe_code)] + +use std::cell::Cell; + +use windows_sys::Win32::Foundation::{HWND, LPARAM, LRESULT, WPARAM}; +use windows_sys::Win32::UI::Shell::{DefSubclassProc, RemoveWindowSubclass, SetWindowSubclass}; +use windows_sys::Win32::UI::WindowsAndMessaging::{WM_LBUTTONDOWN, WM_MOUSEWHEEL, WM_NCDESTROY, WM_XBUTTONDBLCLK}; + +const SUBCLASS: usize = 0x5255_4e50; + +thread_local! { + /// The window and client point of the button message this thread is handling. + static CURRENT: Cell<Option<(usize, i32, i32)>> = const { Cell::new(None) }; +} + +/// Records the point of each button message `window` receives while its handlers run. +pub(crate) fn install(window: &winit::window::Window) { + let Some(hwnd) = super::hwnd(window) else { return }; + // SAFETY: the subclass reads no data, and goes at WM_NCDESTROY. + unsafe { SetWindowSubclass(hwnd, Some(subclass), SUBCLASS, 0); } +} + +/// The client point, in physical pixels, of the button message `window` is handling now. +pub(crate) fn current(window: &winit::window::Window) -> Option<(i32, i32)> { + let hwnd = super::hwnd(window)? as usize; + CURRENT.get().filter(|c| c.0 == hwnd).map(|c| (c.1, c.2)) +} + +fn button_message(message: u32) -> bool { + (WM_LBUTTONDOWN..=WM_XBUTTONDBLCLK).contains(&message) && message != WM_MOUSEWHEEL +} + +unsafe extern "system" fn subclass(hwnd: HWND, message: u32, wparam: WPARAM, lparam: LPARAM, _: usize, _: usize) -> LRESULT { + if button_message(message) { + let (x, y) = (i32::from(lparam as u16 as i16), i32::from((lparam >> 16) as u16 as i16)); + let outer = CURRENT.replace(Some((hwnd as usize, x, y))); + // SAFETY: forwards to the next window procedure. + let result = unsafe { DefSubclassProc(hwnd, message, wparam, lparam) }; + CURRENT.set(outer); + return result; + } + if message == WM_NCDESTROY { + // SAFETY: removes this subclass from the window it's on. + unsafe { RemoveWindowSubclass(hwnd, Some(subclass), SUBCLASS); } + } + // SAFETY: forwards to the next window procedure. + unsafe { DefSubclassProc(hwnd, message, wparam, lparam) } +} \ No newline at end of file diff --git a/app/vendor/rune/crates/rune/src/platform/win32/session_lock.rs b/app/vendor/rune/crates/rune/src/platform/win32/session_lock.rs new file mode 100644 index 0000000..7c975ca --- /dev/null +++ b/app/vendor/rune/crates/rune/src/platform/win32/session_lock.rs @@ -0,0 +1,61 @@ +//! Locking the session (Win+L) wipes the secret Rune copied last, if the clipboard still holds it, +//! as `Tx::clear_secret_clipboard` does: a token copied and left there doesn't wait for its +//! countdown while the desk is empty. Each window asks for session notifications once, after its +//! first frame (`wtsapi32.dll` loads then, not with the process); the system posts +//! `WM_WTSSESSION_CHANGE` only when the session changes, so it costs nothing while idle. + +#![allow(unsafe_code)] + +use windows_sys::Win32::Foundation::HWND; +use windows_sys::Win32::System::LibraryLoader::{GetProcAddress, LOAD_LIBRARY_SEARCH_SYSTEM32, LoadLibraryExW}; +use windows_sys::Win32::UI::Shell::{DefSubclassProc, RemoveWindowSubclass, SetWindowSubclass}; +use windows_sys::Win32::UI::WindowsAndMessaging::{WM_NCDESTROY, WM_WTSSESSION_CHANGE}; + +const SUBCLASS: usize = 0x5255_4e4c; +/// `WTS_SESSION_LOCK`. +const SESSION_LOCK: usize = 0x7; +/// `NOTIFY_FOR_THIS_SESSION`. +const THIS_SESSION: u32 = 0; + +type Register = unsafe extern "system" fn(HWND, u32) -> i32; +type Unregister = unsafe extern "system" fn(HWND) -> i32; + +/// Asks for `window`'s session notifications. Call it once, after the first frame. +pub(crate) fn install(window: &winit::window::Window) { + let Some(hwnd) = super::hwnd(window) else { return }; + let Some(register) = proc::<Register>(c"WTSRegisterSessionNotification") else { return }; + // SAFETY: the subclass keeps no pointer and goes at WM_NCDESTROY; registering for a live + // window this thread owns. + unsafe { + if SetWindowSubclass(hwnd, Some(procedure), SUBCLASS, 0) == 0 { return; } + register(hwnd, THIS_SESSION); + } +} + +/// An export of `wtsapi32.dll`, loaded from System32 the first time. +fn proc<F: Copy>(name: &std::ffi::CStr) -> Option<F> { + // SAFETY: a NUL-terminated name from System32; the function's type is the caller's, which + // names its documented signature. + unsafe { + let module = LoadLibraryExW(windows_sys::core::w!("wtsapi32.dll"), std::ptr::null_mut(), LOAD_LIBRARY_SEARCH_SYSTEM32); + if module.is_null() { return None; } + let f = GetProcAddress(module, name.as_ptr().cast())?; + Some(std::mem::transmute_copy(&f)) + } +} + +unsafe extern "system" fn procedure(hwnd: HWND, msg: u32, w: usize, l: isize, _: usize, _: usize) -> isize { + if msg == WM_WTSSESSION_CHANGE && w == SESSION_LOCK { + crate::clipboard::clear_secret_now(); + } + if msg == WM_NCDESTROY { + if let Some(unregister) = proc::<Unregister>(c"WTSUnRegisterSessionNotification") { + // SAFETY: the window is still alive during WM_NCDESTROY. + unsafe { unregister(hwnd); } + } + // SAFETY: removes this subclass from the window it was set on. + unsafe { RemoveWindowSubclass(hwnd, Some(procedure), SUBCLASS) }; + } + // SAFETY: passes every message on. + unsafe { DefSubclassProc(hwnd, msg, w, l) } +} diff --git a/app/vendor/rune/crates/rune/src/platform/win32/taskbar.rs b/app/vendor/rune/crates/rune/src/platform/win32/taskbar.rs new file mode 100644 index 0000000..7f7ac73 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/platform/win32/taskbar.rs @@ -0,0 +1,220 @@ +//! The taskbar button's progress, overlay badge and flash (`crate::taskbar`), through the +//! shell's `ITaskbarList3`. The UI thread only compares and hands the state on: a thread of its +//! own (made on the first state that shows something, asleep on its channel in between) makes +//! the shell's object, which loads the shell's taskbar DLLs, draws the badges and makes the +//! calls, which go to Explorer. +//! +//! The badge is an icon drawn here with GDI at the taskbar's small-icon size for the window's +//! scale: a red disc with the count in white, anti-aliased, kept per count and size for the +//! run. A button Explorer makes again (it restarted) announces itself with +//! `TaskbarButtonCreated`; each window's subclass hears it and sends its state again. + +#![allow(unsafe_code)] + +use std::cell::RefCell; +use std::collections::HashMap; +use std::sync::OnceLock; +use std::sync::mpsc::{Receiver, Sender, channel}; + +use windows::Win32::Foundation::HWND; +use windows::Win32::System::Com::{CLSCTX_INPROC_SERVER, COINIT_APARTMENTTHREADED, CoCreateInstance, CoInitializeEx}; +use windows::Win32::UI::Shell::{ITaskbarList3, TBPF_ERROR, TBPF_INDETERMINATE, TBPF_NOPROGRESS, TBPF_PAUSED, TBPFLAG, TaskbarList}; +use windows::Win32::UI::WindowsAndMessaging::HICON; +use windows::core::PCWSTR; + +use crate::taskbar::{Taskbar, TaskbarProgress}; + +const SUBCLASS: usize = 0x5255_4e54; +/// The badge's disc: Windows 11's critical red. +const DISC: [u8; 3] = [0xC4, 0x2B, 0x1C]; + +/// One state for the worker to show: the window, what it showed, what it shows now. +struct Job { + hwnd: isize, + before: Taskbar, + state: Taskbar, +} + +thread_local! { + /// What each window shows, to skip a call that changes nothing and to send again to a new button. + static SHOWN: RefCell<HashMap<isize, Taskbar>> = RefCell::new(HashMap::new()); +} + +fn worker() -> &'static std::sync::Mutex<Sender<Job>> { + static WORKER: OnceLock<std::sync::Mutex<Sender<Job>>> = OnceLock::new(); + WORKER.get_or_init(|| { + let (to, from) = channel(); + if let Err(e) = std::thread::Builder::new().name("rune-taskbar".into()).spawn(move || run(from)) { eprintln!("rune: taskbar: {e}"); } + std::sync::Mutex::new(to) + }) +} + +/// Shows `state` on `window`'s taskbar button. Call it on the UI thread. +pub(crate) fn set(window: &winit::window::Window, state: Taskbar) { + let Some(hwnd) = super::hwnd(window) else { return }; + let key = hwnd as isize; + let before = SHOWN.with_borrow(|s| s.get(&key).cloned()); + if before.as_ref().unwrap_or(&Taskbar::default()) == &state { return; } + if before.is_none() { + // SAFETY: the subclass keeps no pointer and goes at WM_NCDESTROY. + unsafe { windows_sys::Win32::UI::Shell::SetWindowSubclass(hwnd, Some(procedure), SUBCLASS, 0); } + } + SHOWN.with_borrow_mut(|s| s.insert(key, state.clone())); + send(Job { hwnd: key, before: before.unwrap_or_default(), state }); +} + +fn send(job: Job) { + worker().lock().unwrap_or_else(|e| e.into_inner()).send(job).ok(); +} + +fn run(from: Receiver<Job>) { + // SAFETY: this thread's own single-threaded apartment, for the shell's object. + if unsafe { CoInitializeEx(None, COINIT_APARTMENTTHREADED) }.is_err() { return; } + let started = crate::time::now(); + let Some(list) = list() else { return }; + eprintln!("rune: taskbar: the shell's object in {} µs off the UI thread", started.elapsed().as_micros()); + let mut icons = HashMap::new(); + while let Ok(job) = from.recv() { + apply(&list, &mut icons, HWND(job.hwnd as *mut _), &job.before, &job.state); + } +} +/// Flashes `window`'s taskbar button twice and leaves it lit until the window comes forward, +/// or stops it (`on` false). Nothing flashes while Focus Assist (Do not disturb) holds +/// notifications back, or for a window in front. +pub(crate) fn flash(window: &winit::window::Window, on: bool) { + use windows_sys::Win32::UI::WindowsAndMessaging::{FLASHW_STOP, FLASHW_TRAY, FLASHWINFO, FlashWindowEx, GetForegroundWindow}; + let Some(hwnd) = super::hwnd(window) else { return }; + // SAFETY: plain calls on a live window this thread owns. + unsafe { + if on && (GetForegroundWindow() == hwnd || !accepts_notifications()) { return; } + let info = FLASHWINFO { cbSize: size_of::<FLASHWINFO>() as u32, hwnd, dwFlags: if on { FLASHW_TRAY } else { FLASHW_STOP }, uCount: if on { 2 } else { 0 }, dwTimeout: 0 }; + FlashWindowEx(&info); + } +} + +/// Whether the person takes notifications now: not in Focus Assist, a full-screen app, a +/// presentation or the first hour after setup (`SHQueryUserNotificationState`). +fn accepts_notifications() -> bool { + use windows_sys::Win32::UI::Shell::{QUNS_ACCEPTS_NOTIFICATIONS, SHQueryUserNotificationState}; + let mut state = 0; + // SAFETY: fills `state`. + unsafe { SHQueryUserNotificationState(&mut state) >= 0 && state == QUNS_ACCEPTS_NOTIFICATIONS } +} + +fn list() -> Option<ITaskbarList3> { + // SAFETY: the shell's taskbar object in this thread's apartment, initialised before use as + // its contract asks. + unsafe { + let list: ITaskbarList3 = CoCreateInstance(&TaskbarList, None, CLSCTX_INPROC_SERVER).ok()?; + list.HrInit().ok()?; + Some(list) + } +} + +fn apply(list: &ITaskbarList3, icons: &mut HashMap<(u32, i32), isize>, hwnd: HWND, before: &Taskbar, state: &Taskbar) { + // SAFETY: shell calls about a window of this process (gone, they fail harmlessly). + unsafe { + if before.progress != state.progress { + let flag: TBPFLAG = match state.progress { + TaskbarProgress::None => TBPF_NOPROGRESS, + TaskbarProgress::Busy => TBPF_INDETERMINATE, + TaskbarProgress::Paused => TBPF_PAUSED, + TaskbarProgress::Error => TBPF_ERROR, + }; + // A paused or failed bar shows its value: full. + if matches!(state.progress, TaskbarProgress::Paused | TaskbarProgress::Error) { list.SetProgressValue(hwnd, 1, 1).ok(); } + list.SetProgressState(hwnd, flag).ok(); + } + if before.badge != state.badge { + let (count, description) = &state.badge; + let icon = if *count == 0 { HICON::default() } else { HICON(badge_icon(icons, hwnd, *count) as *mut _) }; + let description: Vec<u16> = description.encode_utf16().chain([0]).collect(); + list.SetOverlayIcon(hwnd, icon, PCWSTR(description.as_ptr())).ok(); + } + } +} + +fn button_created() -> u32 { + static MESSAGE: OnceLock<u32> = OnceLock::new(); + // SAFETY: the name is NUL-terminated. + *MESSAGE.get_or_init(|| unsafe { windows_sys::Win32::UI::WindowsAndMessaging::RegisterWindowMessageW("TaskbarButtonCreated\0".encode_utf16().collect::<Vec<u16>>().as_ptr()) }) +} + +unsafe extern "system" fn procedure(hwnd: windows_sys::Win32::Foundation::HWND, msg: u32, w: usize, l: isize, _: usize, _: usize) -> isize { + use windows_sys::Win32::UI::Shell::{DefSubclassProc, RemoveWindowSubclass}; + use windows_sys::Win32::UI::WindowsAndMessaging::WM_NCDESTROY; + if msg == WM_NCDESTROY { + SHOWN.with(|s| s.try_borrow_mut().map(|mut s| s.remove(&(hwnd as isize))).ok()); + // SAFETY: removes this subclass from the window it was set on. + unsafe { RemoveWindowSubclass(hwnd, Some(procedure), SUBCLASS) }; + } else if msg == button_created() { + // A new button (Explorer restarted): it shows nothing until told again. + if let Some(state) = SHOWN.with(|s| s.try_borrow().ok().and_then(|s| s.get(&(hwnd as isize)).cloned())) { + send(Job { hwnd: hwnd as isize, before: Taskbar::default(), state }); + } + } + // SAFETY: passes every message on. + unsafe { DefSubclassProc(hwnd, msg, w, l) } +} + +/// The overlay icon for `count` at the taskbar's small-icon size for `hwnd`'s scale. +fn badge_icon(icons: &mut HashMap<(u32, i32), isize>, hwnd: HWND, count: u32) -> isize { + use windows_sys::Win32::UI::HiDpi::{GetDpiForWindow, GetSystemMetricsForDpi}; + use windows_sys::Win32::UI::WindowsAndMessaging::SM_CXSMICON; + // SAFETY: reads the window's scale and a system metric. + let size = unsafe { GetSystemMetricsForDpi(SM_CXSMICON, GetDpiForWindow(hwnd.0).max(96)) }.max(16); + let count = count.min(10); + *icons.entry((count, size)).or_insert_with(|| draw_badge(count, size)) +} + +/// A `size` square icon: the disc, and `count` (10 reads "9+") in white, its glyphs' coverage +/// from GDI's grayscale anti-aliasing. +fn draw_badge(count: u32, size: i32) -> isize { + use windows_sys::Win32::Graphics::Gdi::*; + use windows_sys::Win32::UI::WindowsAndMessaging::{CreateIconIndirect, ICONINFO}; + let label: Vec<u16> = (if count >= 10 { "9+".to_owned() } else { count.to_string() }).encode_utf16().collect(); + // SAFETY: a plain C struct, all zeroes valid. + let mut info: BITMAPINFO = unsafe { std::mem::zeroed() }; + info.bmiHeader = BITMAPINFOHEADER { biSize: size_of::<BITMAPINFOHEADER>() as u32, biWidth: size, biHeight: -size, biPlanes: 1, biBitCount: 32, biCompression: BI_RGB, biSizeImage: 0, biXPelsPerMeter: 0, biYPelsPerMeter: 0, biClrUsed: 0, biClrImportant: 0 }; + let n = (size * size) as usize; + // SAFETY: GDI objects made, used and deleted here; each DIB section holds `n` 32-bit pixels. + unsafe { + let dc = CreateCompatibleDC(std::ptr::null_mut()); + let mut text_bits = std::ptr::null_mut(); + let text = CreateDIBSection(dc, &info, DIB_RGB_COLORS, &mut text_bits, std::ptr::null_mut(), 0); + let old = SelectObject(dc, text); + let height = -(f64::from(size) * if label.len() > 1 { 0.62 } else { 0.78 }).round() as i32; + let face: Vec<u16> = "Segoe UI\0".encode_utf16().collect(); + let font = CreateFontW(height, 0, 0, 0, FW_BOLD as i32, 0, 0, 0, DEFAULT_CHARSET as u32, OUT_DEFAULT_PRECIS as u32, CLIP_DEFAULT_PRECIS as u32, ANTIALIASED_QUALITY as u32, DEFAULT_PITCH as u32, face.as_ptr()); + let old_font = SelectObject(dc, font); + SetBkMode(dc, TRANSPARENT as i32); + SetTextColor(dc, 0x00FF_FFFF); + let mut rect = windows_sys::Win32::Foundation::RECT { left: 0, top: 0, right: size, bottom: size }; + let mut label = label; + DrawTextW(dc, label.as_mut_ptr(), label.len() as i32, &mut rect, DT_CENTER | DT_VCENTER | DT_SINGLELINE | DT_NOPREFIX); + GdiFlush(); + let coverage: Vec<u8> = std::slice::from_raw_parts(text_bits.cast::<u8>(), n * 4).chunks_exact(4).map(|p| p[1]).collect(); + SelectObject(dc, old_font); + DeleteObject(font); + SelectObject(dc, old); + DeleteObject(text); + let mut bits = std::ptr::null_mut(); + let color = CreateDIBSection(dc, &info, DIB_RGB_COLORS, &mut bits, std::ptr::null_mut(), 0); + let out = std::slice::from_raw_parts_mut(bits.cast::<u8>(), n * 4); + let r = f64::from(size) / 2.0; + for (i, p) in out.chunks_exact_mut(4).enumerate() { + let (x, y) = ((i % size as usize) as f64 + 0.5 - r, (i / size as usize) as f64 + 0.5 - r); + let a = (r - (x * x + y * y).sqrt()).clamp(0.0, 1.0); + let t = f64::from(coverage[i]) / 255.0; + let mix = |disc: u8| (f64::from(disc) * (1.0 - t) + 255.0 * t) * a; + // Premultiplied BGRA. + p.copy_from_slice(&[mix(DISC[2]).round() as u8, mix(DISC[1]).round() as u8, mix(DISC[0]).round() as u8, (a * 255.0).round() as u8]); + } + let mask = CreateBitmap(size, size, 1, 1, std::ptr::null()); + let icon = CreateIconIndirect(&ICONINFO { fIcon: 1, xHotspot: 0, yHotspot: 0, hbmMask: mask, hbmColor: color }); + DeleteObject(mask); + DeleteObject(color); + DeleteDC(dc); + icon as isize + } +} diff --git a/app/vendor/rune/crates/rune/src/platform/x11.rs b/app/vendor/rune/crates/rune/src/platform/x11.rs new file mode 100644 index 0000000..a726f39 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/platform/x11.rs @@ -0,0 +1,3 @@ +pub(crate) mod overlay; +pub(crate) mod pointer; +pub(crate) mod xwayland; diff --git a/app/vendor/rune/crates/rune/src/platform/x11/overlay.rs b/app/vendor/rune/crates/rune/src/platform/x11/overlay.rs new file mode 100644 index 0000000..8f6fe1e --- /dev/null +++ b/app/vendor/rune/crates/rune/src/platform/x11/overlay.rs @@ -0,0 +1,130 @@ +//! X11 input SHAPE regions. The visual surface stays intact; only pointer ownership changes. +//! An override-redirect window gets no focus from the window manager, so an overlay that may take +//! keys (`KeyPolicy::OnDemand`) sets the input focus itself. + +use x11rb::{connection::Connection, protocol::{shape::{ConnectionExt as _, SK, SO}, xproto::{ConnectionExt as _, ClipOrdering, ConfigureWindowAux, InputFocus, Rectangle, StackMode}}, rust_connection::RustConnection}; +use winit::raw_window_handle::{HasWindowHandle, RawWindowHandle}; + +thread_local! { + static SHOWN: std::cell::RefCell<Vec<(u32, crate::OverlayLevel)>> = const { std::cell::RefCell::new(Vec::new()) }; +} + +pub(crate) struct InputWindow { + watch: std::cell::RefCell<Option<crate::platform::x11::pointer::MouseWatch>>, + wake: Option<crate::Waker>, + visible: std::cell::Cell<bool>, + follow: std::cell::Cell<bool>, + input: std::cell::Cell<crate::OverlayInput>, + keys: crate::KeyPolicy, + connection: RustConnection, + root: u32, + window: u32, + last: Option<Vec<Rectangle>>, +} + +impl InputWindow { + pub fn show(&self, level: crate::OverlayLevel) { + self.visible.set(true); + self.refresh_watch(); + let windows = SHOWN.with(|shown| { + let mut shown = shown.borrow_mut(); + shown.retain(|(id, _)| *id != self.window); + shown.push((self.window, level)); + shown.clone() + }); + for level in [crate::OverlayLevel::Status, crate::OverlayLevel::AboveStatus, crate::OverlayLevel::AboveOverlays] { + for (id, at) in &windows { + if *at == level { self.connection.configure_window(*id, &ConfigureWindowAux::new().stack_mode(StackMode::ABOVE)).ok(); } + } + } + self.connection.flush().ok(); + } + pub fn hide(&self) { self.visible.set(false); self.watch.borrow_mut().take(); SHOWN.with(|shown| shown.borrow_mut().retain(|(id, _)| *id != self.window)); } + pub fn new(window: &winit::window::Window, wake: Option<crate::Waker>, input: crate::OverlayInput, follow: bool, keys: crate::KeyPolicy) -> Option<Self> { + let id = match window.window_handle().ok()?.as_raw() { + RawWindowHandle::Xlib(w) => u32::try_from(w.window).ok()?, + RawWindowHandle::Xcb(w) => w.window.get(), + _ => return None, + }; + let (connection, screen) = x11rb::connect(None).ok()?; + let version = connection.shape_query_version().ok()?.reply().ok()?; + if (version.major_version, version.minor_version) < (1, 1) { return None; } + let root = connection.setup().roots.get(screen)?.root; + Some(Self { connection, root, window: id, last: None, watch: std::cell::RefCell::default(), wake, visible: std::cell::Cell::new(false), follow: std::cell::Cell::new(follow), input: std::cell::Cell::new(input), keys }) + } + /// Gives the shown window the keyboard focus, for `request_keys` or a click, as the macOS + /// panel takes it. Focus reverts to the root window when it hides, for the window manager to + /// hand on. False when its policy takes no keys or the server refused (not yet mapped). + pub fn request_keys(&self) -> bool { + if !self.visible.get() || !crate::overlay::keys::can_take_keys(self.keys) { return false; } + self.connection.set_input_focus(InputFocus::PARENT, self.window, x11rb::CURRENT_TIME).ok().and_then(|r| r.check().ok()).is_some() + } + pub fn global_pointer(&self) -> crate::OverlaySupport { + if self.input.get() != crate::OverlayInput::Regions && !self.follow.get() { return crate::OverlaySupport::Supported; } + if self.watch.borrow().as_ref().is_some_and(|w| w.supported()) { crate::OverlaySupport::Supported } else { crate::OverlaySupport::Failed } + } + pub fn set_follow_pointer(&self, follow: bool) { self.follow.set(follow); self.refresh_watch(); } + fn refresh_watch(&self) { + if self.visible.get() && (self.input.get() == crate::OverlayInput::Regions || self.follow.get()) { + if self.watch.borrow().is_none() { *self.watch.borrow_mut() = crate::platform::x11::pointer::MouseWatch::new(self.wake.clone()); } + self.update_geometry(); + } else { self.watch.borrow_mut().take(); } + } + pub fn update_geometry(&self) { + let watch = self.watch.borrow(); + let Some(watch) = watch.as_ref() else { return }; + if let Some(p) = self.connection.translate_coordinates(self.window, self.root, 0, 0).ok().and_then(|r| r.reply().ok()) + && let Some(g) = self.connection.get_geometry(self.window).ok().and_then(|r| r.reply().ok()) { + watch.geometry([i32::from(p.dst_x), i32::from(p.dst_y), i32::from(p.dst_x) + i32::from(g.width), i32::from(p.dst_y) + i32::from(g.height)], self.follow.get()); + } + } + pub fn set_input(&mut self, input: crate::OverlayInput) { + self.input.set(input); + self.refresh_watch(); + self.last = None; + match input { + crate::OverlayInput::All => { let _ = self.connection.shape_mask(SO::SET, SK::INPUT, self.window, 0, 0, x11rb::NONE).ok().and_then(|r| r.check().ok()); } + crate::OverlayInput::None => self.regions(&[], 1.0), + _ => {} + } + } + pub fn take_pointer(&self, scale: f32) -> Option<((f32, f32), (i32, i32))> { + let desktop = self.watch.borrow().as_ref()?.take()?; + let p = self.connection.translate_coordinates(self.window, self.root, 0, 0).ok()?.reply().ok()?; + Some((((desktop.0 - i32::from(p.dst_x)) as f32 / scale, (desktop.1 - i32::from(p.dst_y)) as f32 / scale), desktop)) + } + pub fn regions(&mut self, rects: &[[f32; 4]], scale: f32) { + let rects: Vec<_> = rects.iter().filter_map(|r| { + let x = (r[0] * scale).floor().max(0.0).min(i16::MAX as f32) as i16; + let y = (r[1] * scale).floor().max(0.0).min(i16::MAX as f32) as i16; + let width = ((r[2] * scale).ceil() - f32::from(x)).clamp(0.0, u16::MAX as f32) as u16; + let height = ((r[3] * scale).ceil() - f32::from(y)).clamp(0.0, u16::MAX as f32) as u16; + (width > 0 && height > 0).then_some(Rectangle { x, y, width, height }) + }).collect(); + if self.last.as_ref().is_some_and(|last| last.len() == rects.len() && last.iter().zip(&rects).all(|(a, b)| + (a.x, a.y, a.width, a.height) == (b.x, b.y, b.width, b.height))) { return; } + // X11 retains its implicit button grab through release even if input shape changes. + if self.connection.shape_rectangles(SO::SET, SK::INPUT, ClipOrdering::UNSORTED, self.window, 0, 0, &rects) + .ok().and_then(|request| request.check().ok()).is_some() { + // This connection is separate from wgpu's. Wait for the shape to be applied + // before presenting pixels, rather than racing two independent X11 streams. + self.last = Some(rects); + } + } +} + +impl Drop for InputWindow { fn drop(&mut self) { self.hide(); } } + +pub(crate) fn pointer_position() -> Option<(i32, i32)> { + let (connection, screen) = x11rb::connect(None).ok()?; + let root = connection.setup().roots.get(screen)?.root; + let p = connection.query_pointer(root).ok()?.reply().ok()?; + p.same_screen.then_some((i32::from(p.root_x), i32::from(p.root_y))) +} + +pub(crate) fn output_crtc(output: u32) -> Option<u32> { + use x11rb::protocol::randr::ConnectionExt as _; + let (connection, _) = x11rb::connect(None).ok()?; + let crtc = connection.randr_get_output_info(output, x11rb::CURRENT_TIME).ok()?.reply().ok()?.crtc; + (crtc != 0).then_some(crtc) +} diff --git a/app/vendor/rune/crates/rune/src/platform/x11/pointer.rs b/app/vendor/rune/crates/rune/src/platform/x11/pointer.rs new file mode 100644 index 0000000..5fb5c90 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/platform/x11/pointer.rs @@ -0,0 +1,62 @@ +//! XI2 raw motion on a private connection. Idle overlays have no polling deadline. + +#![allow(unsafe_code)] + +use std::sync::{Arc, atomic::{AtomicBool, Ordering}}; +use x11rb::{connection::Connection, protocol::{Event, xinput::{ConnectionExt as _, Device, EventMask, XIEventMask}, randr::ConnectionExt as _, xproto::ConnectionExt as _}, rust_connection::RustConnection}; + +pub(crate) struct MouseWatch { + connection: Arc<RustConnection>, + observer: Arc<crate::input::pointer_observer::Observer>, + running: Arc<AtomicBool>, + thread: Option<std::thread::JoinHandle<()>>, + root: u32, +} +impl MouseWatch { + pub fn new(wake: Option<crate::Waker>) -> Option<Self> { + let (connection, screen) = x11rb::connect(None).ok()?; + let root = connection.setup().roots.get(screen)?.root; + connection.xinput_xi_query_version(2, 0).ok()?.reply().ok()?; + connection.xinput_xi_select_events(root, &[EventMask { deviceid: Device::ALL_MASTER.into(), mask: vec![XIEventMask::RAW_MOTION] }]).ok()?.check().ok()?; + connection.flush().ok()?; + let connection = Arc::new(connection); + let observer = Arc::new(crate::input::pointer_observer::Observer::new(wake)); + let running = Arc::new(AtomicBool::new(true)); + let (reader, sample, active) = (connection.clone(), observer.clone(), running.clone()); + let thread = std::thread::spawn(move || { + while let Ok(event) = reader.wait_for_event() { + if matches!(event, Event::XinputRawMotion(_)) + && let Ok(cookie) = reader.query_pointer(root) && let Ok(p) = cookie.reply() && p.same_screen { + sample.observe((i32::from(p.root_x), i32::from(p.root_y))); + } + } + active.store(false, Ordering::Release); + }); + Some(Self { connection, observer, running, thread: Some(thread), root }) + } + pub fn supported(&self) -> bool { self.running.load(Ordering::Acquire) } + pub fn take(&self) -> Option<(i32, i32)> { self.observer.take() } + pub fn geometry(&self, canvas: [i32; 4], follow: bool) { + if !self.observer.needs_geometry(canvas, follow) { return; } + let displays = if follow { + self.connection.randr_get_monitors(self.root, true).ok().and_then(|r| r.reply().ok()).map(|r| { + r.monitors.iter().map(|m| [i32::from(m.x), i32::from(m.y), i32::from(m.x) + i32::from(m.width), i32::from(m.y) + i32::from(m.height)]).collect() + }).unwrap_or_default() + } else { Vec::new() }; + self.observer.configure(canvas, displays, follow); + if let Ok(cookie) = self.connection.query_pointer(self.root) && let Ok(p) = cookie.reply() && p.same_screen { + self.observer.observe((i32::from(p.root_x), i32::from(p.root_y))); + } + } +} +impl Drop for MouseWatch { + fn drop(&mut self) { + use std::os::fd::AsRawFd; + unsafe extern "C" { fn shutdown(fd: std::ffi::c_int, how: std::ffi::c_int) -> std::ffi::c_int; } + // This private connection stays owned here until the reader exits. Shutdown wakes + // wait_for_event without touching winit's display or waiting for another input event. + // SAFETY: `self.connection` owns a live open socket FD until `Drop` finishes (`SHUT_RDWR == 2`). + unsafe { shutdown(self.connection.stream().as_raw_fd(), 2); } + if let Some(thread) = self.thread.take() { thread.join().ok(); } + } +} diff --git a/app/vendor/rune/crates/rune/src/platform/x11/xwayland.rs b/app/vendor/rune/crates/rune/src/platform/x11/xwayland.rs new file mode 100644 index 0000000..d9f2410 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/platform/x11/xwayland.rs @@ -0,0 +1,234 @@ +//! An overlay on XWayland, for a Wayland compositor without layer-shell (GNOME's Mutter): an +//! override-redirect ARGB window of the notification type on its own libxcb connection. Like a +//! layer surface it is mapped while it lives and destroyed when hidden. An overlay that takes no +//! input gets an empty input shape, so it never takes a click. One whose host set +//! `OverlayOptions::xwayland_input` takes the pointer in its input shape (all of it, or its hit +//! regions) and reads its own events; being override-redirect, it never takes keyboard focus. +//! The rest of the app stays on Wayland. + +use std::num::NonZeroU32; +use std::os::fd::AsRawFd; +use std::ptr::NonNull; + +use winit::raw_window_handle::{RawDisplayHandle, RawWindowHandle, XcbDisplayHandle, XcbWindowHandle}; +use x11rb::connection::Connection; +use x11rb::protocol::randr::ConnectionExt as _; +use x11rb::protocol::shape::{ConnectionExt as _, SK, SO}; +use x11rb::protocol::Event; +use x11rb::protocol::xproto::{ + AtomEnum, ChangeWindowAttributesAux, ClipOrdering, ColormapAlloc, ConfigureWindowAux, ConnectionExt as _, CreateWindowAux, + EventMask, KeyButMask, PropMode, Rectangle, StackMode, VisualClass, WindowClass, +}; +use x11rb::wrapper::ConnectionExt as _; +use x11rb::xcb_ffi::XCBConnection; + +use crate::overlay::Placement; +use crate::platform::layer_shell::{Input, Watch}; +use crate::runtime::Waker; +use crate::{DisplayTarget, OverlayInput, OverlayOptions}; + +/// The events a window that takes input asks for; one that takes none asks for nothing. +fn events(input: OverlayInput) -> EventMask { + if input == OverlayInput::None { return EventMask::NO_EVENT; } + EventMask::BUTTON_PRESS | EventMask::BUTTON_RELEASE | EventMask::POINTER_MOTION | EventMask::ENTER_WINDOW | EventMask::LEAVE_WINDOW +} + +pub(crate) struct XwaylandSurface { + /// Dropped first: its thread stops polling the connection's socket within one timeout. + watch: Option<Watch>, + connection: XCBConnection, + screen: usize, + root: u32, + window: u32, + colormap: u32, + scale: f32, + input: OverlayInput, + /// The input shape's rectangles (pixels) last set for `OverlayInput::Regions`. + regions: Option<Vec<(i16, i16, u16, u16)>>, + size: (u16, u16), +} + +impl XwaylandSurface { + /// `None` without an X server (`DISPLAY`), a 32-bit visual, or the SHAPE extension the + /// input region needs. `input` is the overlay's resolved input; anything but `None` asks + /// for pointer events, and `wake` turns the event loop when they arrive. + pub fn new(name: &str, at: Placement, options: &OverlayOptions, input: OverlayInput, wake: Option<Waker>) -> Option<Self> { + std::env::var_os("DISPLAY").filter(|display| !display.is_empty())?; + let (connection, screen) = XCBConnection::connect(None).ok()?; + let version = connection.shape_query_version().ok()?.reply().ok()?; + if (version.major_version, version.minor_version) < (1, 1) { return None; } + let root_screen = connection.setup().roots.get(screen)?; + let root = root_screen.root; + let visual = root_screen.allowed_depths.iter().filter(|d| d.depth == 32) + .flat_map(|d| d.visuals.iter()).find(|v| v.class == VisualClass::TRUE_COLOR)?.visual_id; + let scale = xft_scale(&connection, root); + let colormap = connection.generate_id().ok()?; + connection.create_colormap(ColormapAlloc::NONE, colormap, root, visual).ok()?.check().ok()?; + let window = connection.generate_id().ok()?; + let mut this = Self { watch: None, connection, screen, root, window: 0, colormap, scale, input: OverlayInput::None, regions: None, size: (1, 1) }; + let (x, y, w, h) = this.rect(at, options)?; + this.size = (w, h); + let aux = CreateWindowAux::new().override_redirect(1).background_pixel(0).border_pixel(0).colormap(colormap) + .event_mask(events(input)); + this.connection.create_window(32, window, root, x, y, w, h, 0, WindowClass::INPUT_OUTPUT, visual, &aux).ok()?.check().ok()?; + this.window = window; + let atom = |name: &[u8]| Some(this.connection.intern_atom(false, name).ok()?.reply().ok()?.atom); + let (kind, notification) = (atom(b"_NET_WM_WINDOW_TYPE")?, atom(b"_NET_WM_WINDOW_TYPE_NOTIFICATION")?); + let c = &this.connection; + c.change_property32(PropMode::REPLACE, window, kind, AtomEnum::ATOM, &[notification]).ok()?; + c.change_property8(PropMode::REPLACE, window, AtomEnum::WM_NAME, AtomEnum::STRING, name.as_bytes()).ok()?; + let id = crate::tooling::app_id().unwrap_or(name); + let class = [id.as_bytes(), b"\0", id.as_bytes(), b"\0"].concat(); + c.change_property8(PropMode::REPLACE, window, AtomEnum::WM_CLASS, AtomEnum::STRING, &class).ok()?; + this.shape(input)?; + let c = &this.connection; + c.map_window(window).ok()?; + c.configure_window(window, &ConfigureWindowAux::new().stack_mode(StackMode::ABOVE)).ok()?; + c.flush().ok()?; + this.input = input; + if input != OverlayInput::None { this.watch = wake.map(|wake| Watch::spawn(this.connection.as_raw_fd(), wake)); } + Some(this) + } + + /// The input shape for `input`: the whole window, nothing, or (for regions) nothing until + /// `regions` sets them. + fn shape(&mut self, input: OverlayInput) -> Option<()> { + self.regions = None; + let c = &self.connection; + match input { + OverlayInput::All => c.shape_mask(SO::SET, SK::INPUT, self.window, 0, 0, x11rb::NONE).ok()?.check().ok(), + _ => c.shape_rectangles(SO::SET, SK::INPUT, ClipOrdering::UNSORTED, self.window, 0, 0, &[]).ok()?.check().ok(), + } + } + + /// Changes what the window takes. Turning input on needs a watch made with the surface, so + /// an overlay made without input stays click-through until it is made again. + pub fn set_input(&mut self, input: OverlayInput) { + let input = if self.watch.is_none() { OverlayInput::None } else { input }; + if input == self.input { return; } + self.input = input; + self.connection.change_window_attributes(self.window, &ChangeWindowAttributesAux::new().event_mask(events(input))).ok(); + let _ = self.shape(input); + self.connection.flush().ok(); + } + + /// Sets the input shape to the overlay's hit regions (points) while it takes input in + /// regions; checked, so the shape applies before the frame's pixels present. + pub fn regions(&mut self, rects: &[[f32; 4]]) { + if self.input != OverlayInput::Regions { return; } + let scale = self.scale; + let rects: Vec<_> = rects.iter().filter_map(|r| { + let x = (r[0] * scale).floor().clamp(0.0, f32::from(i16::MAX)) as i16; + let y = (r[1] * scale).floor().clamp(0.0, f32::from(i16::MAX)) as i16; + let width = ((r[2] * scale).ceil() - f32::from(x)).clamp(0.0, f32::from(u16::MAX)) as u16; + let height = ((r[3] * scale).ceil() - f32::from(y)).clamp(0.0, f32::from(u16::MAX)) as u16; + (width > 0 && height > 0).then_some(Rectangle { x, y, width, height }) + }).collect(); + let key: Vec<_> = rects.iter().map(|r| (r.x, r.y, r.width, r.height)).collect(); + if self.regions.as_ref() == Some(&key) { return; } + if self.connection.shape_rectangles(SO::SET, SK::INPUT, ClipOrdering::UNSORTED, self.window, 0, 0, &rects) + .ok().and_then(|request| request.check().ok()).is_some() { + self.regions = Some(key); + } + } + + /// The desktop's scale (`Xft.dpi` / 96), which XWayland's native scaling sets. + pub fn scale(&self) -> f32 { self.scale } + + pub fn place(&mut self, at: Placement, options: &OverlayOptions) { + let Some((x, y, w, h)) = self.rect(at, options) else { return }; + self.size = (w, h); + let aux = ConfigureWindowAux::new().x(i32::from(x)).y(i32::from(y)).width(u32::from(w)).height(u32::from(h)).stack_mode(StackMode::ABOVE); + self.connection.configure_window(self.window, &aux).ok(); + self.connection.flush().ok(); + } + + /// What the server sent since the last call, as overlay input in points. A window that + /// takes no input asks for no events, so only errors arrive and are dropped. + pub fn dispatch(&mut self) -> Vec<Input> { + let mut input = Vec::new(); + while let Ok(Some(event)) = self.connection.poll_for_event() { + if self.input != OverlayInput::None { pointer_input(event, self.scale, self.size, &mut input); } + } + if let Some(watch) = &self.watch { watch.turned(); } + input + } + + pub fn raw_handles(&self) -> Option<(RawDisplayHandle, RawWindowHandle)> { + let display = XcbDisplayHandle::new(NonNull::new(self.connection.get_raw_xcb_connection()), i32::try_from(self.screen).ok()?); + let window = XcbWindowHandle::new(NonZeroU32::new(self.window)?); + Some((RawDisplayHandle::Xcb(display), RawWindowHandle::Xcb(window))) + } + + /// The window's pixels on the target monitor: the primary unless the pointer's is asked for. + fn rect(&self, at: Placement, options: &OverlayOptions) -> Option<(i16, i16, u16, u16)> { + let monitors = self.connection.randr_get_monitors(self.root, true).ok()?.reply().ok()?.monitors; + let bounds: Vec<_> = monitors.iter().map(|m| { + let (x, y) = (f64::from(m.x), f64::from(m.y)); + [x, y, x + f64::from(m.width), y + f64::from(m.height)] + }).collect(); + let primary = monitors.iter().position(|m| m.primary); + let pointer = (options.display == DisplayTarget::UnderPointer).then(|| { + let p = self.connection.query_pointer(self.root).ok()?.reply().ok()?; + p.same_screen.then_some((f64::from(p.root_x), f64::from(p.root_y))) + }).flatten(); + let monitor = &monitors[crate::overlay::options::choose_display(&bounds, primary, None, pointer)?]; + let scale = self.scale; + let area = (f32::from(monitor.width) / scale, f32::from(monitor.height) / scale); + let r = crate::overlay::options::local_rect(at, options.placement, area); + let px = |v: f32| (v * scale).round(); + let x = (f32::from(monitor.x) + px(r[0])).clamp(f32::from(i16::MIN), f32::from(i16::MAX)) as i16; + let y = (f32::from(monitor.y) + px(r[1])).clamp(f32::from(i16::MIN), f32::from(i16::MAX)) as i16; + let size = |v: f32| px(v).clamp(1.0, f32::from(u16::MAX)) as u16; + Some((x, y, size(r[2]), size(r[3]))) + } +} + +impl Drop for XwaylandSurface { + fn drop(&mut self) { + if self.window != 0 { self.connection.destroy_window(self.window).ok(); } + self.connection.free_colormap(self.colormap).ok(); + self.connection.flush().ok(); + } +} + +/// One X event as overlay input: positions in points, the primary button as `Button` and the +/// secondary as `Secondary`. While a button is held the window keeps the pointer (X11's +/// implicit grab), so leaving then is ignored and a release outside the window leaves. +fn pointer_input(event: Event, scale: f32, size: (u16, u16), input: &mut Vec<Input>) { + let at = |x: i16, y: i16| Input::Move(f32::from(x) / scale, f32::from(y) / scale); + let (e, down) = match event { + Event::MotionNotify(e) => return input.push(at(e.event_x, e.event_y)), + Event::EnterNotify(e) => return input.push(at(e.event_x, e.event_y)), + Event::LeaveNotify(e) => { + let held = KeyButMask::BUTTON1 | KeyButMask::BUTTON2 | KeyButMask::BUTTON3; + if !e.state.intersects(held) { input.push(Input::Leave); } + return; + } + Event::ButtonPress(e) => (e, true), + Event::ButtonRelease(e) => (e, false), + _ => return, + }; + let button = match e.detail { + 1 => Input::Button(down), + 3 => Input::Secondary(down), + _ => return, + }; + input.push(at(e.event_x, e.event_y)); + input.push(button); + let inside = (0..i32::from(size.0)).contains(&i32::from(e.event_x)) && (0..i32::from(size.1)).contains(&i32::from(e.event_y)); + if !down && !inside { input.push(Input::Leave); } +} + +/// `Xft.dpi` from the root window's resource database, as a scale; 1 when unset. +fn xft_scale(connection: &XCBConnection, root: u32) -> f32 { + let Some(reply) = connection.get_property(false, root, AtomEnum::RESOURCE_MANAGER, AtomEnum::STRING, 0, 1 << 16) + .ok().and_then(|cookie| cookie.reply().ok()) else { return 1.0 }; + String::from_utf8_lossy(&reply.value).lines() + .find_map(|line| line.strip_prefix("Xft.dpi:")?.trim().parse::<f32>().ok()) + .map_or(1.0, |dpi| (dpi / 96.0).clamp(1.0, 4.0)) +} + +#[cfg(test)] +#[path = "xwayland_tests.rs"] +mod tests; diff --git a/app/vendor/rune/crates/rune/src/platform/x11/xwayland_tests.rs b/app/vendor/rune/crates/rune/src/platform/x11/xwayland_tests.rs new file mode 100644 index 0000000..74ab6bd --- /dev/null +++ b/app/vendor/rune/crates/rune/src/platform/x11/xwayland_tests.rs @@ -0,0 +1,34 @@ +use super::*; +use x11rb::protocol::xproto::{ButtonPressEvent, LeaveNotifyEvent, MotionNotifyEvent}; + +fn read(event: Event) -> Vec<String> { + let mut input = Vec::new(); + pointer_input(event, 2.0, (200, 100), &mut input); + input.iter().map(|i| match i { + Input::Move(x, y) => format!("move {x} {y}"), + Input::Leave => "leave".into(), + Input::Button(down) => format!("button {down}"), + Input::Secondary(down) => format!("secondary {down}"), + _ => "other".into(), + }).collect() +} + +fn button(detail: u8, x: i16, y: i16) -> ButtonPressEvent { + ButtonPressEvent { detail, event_x: x, event_y: y, ..Default::default() } +} + +#[test] +fn pixels_become_points_and_buttons_follow_a_move() { + assert_eq!(read(Event::MotionNotify(MotionNotifyEvent { event_x: 40, event_y: 20, ..Default::default() })), ["move 20 10"]); + assert_eq!(read(Event::ButtonPress(button(1, 40, 20))), ["move 20 10", "button true"]); + assert_eq!(read(Event::ButtonRelease(button(3, 40, 20))), ["move 20 10", "secondary false"]); + assert!(read(Event::ButtonPress(button(4, 40, 20))).is_empty(), "scrolling isn't a click"); +} + +#[test] +fn a_held_button_keeps_the_pointer_until_its_release() { + let held = LeaveNotifyEvent { state: KeyButMask::BUTTON1, ..Default::default() }; + assert!(read(Event::LeaveNotify(held)).is_empty()); + assert_eq!(read(Event::LeaveNotify(LeaveNotifyEvent::default())), ["leave"]); + assert_eq!(read(Event::ButtonRelease(button(1, 260, 20))), ["move 130 10", "button false", "leave"]); +} diff --git a/app/vendor/rune/crates/rune/src/playground.rs b/app/vendor/rune/crates/rune/src/playground.rs new file mode 100644 index 0000000..e01b1ea --- /dev/null +++ b/app/vendor/rune/crates/rune/src/playground.rs @@ -0,0 +1,463 @@ +//! [`App::playground`](crate::App::playground): a storybook built into the window (⌘⇧D). Its +//! stories, grouped by type, are the app's scenes and its own [`Story`]s and pages. One shows +//! at a time on a plain stage, live and interactive, with a column beside it for that story's +//! triggers and controls. Nothing touches the app's real state. +//! +//! While it's open, handlers in the stage act on the stage's state: a fresh scene state, a +//! story's own state, or the real state for a [`Playground::page`]. Its own controls act on +//! [`Controls`], beside it, through [`crate::states::States`]. The real state keeps polling +//! throughout and is back, untouched, after Back. + +use std::any::Any; +use std::rc::Rc; +use std::time::Duration; + +use crate::states::{States, StatesRef}; +use crate::tok::{self, Theme, radius, type_}; +use crate::{Color, Cx, El, Icon, Key, KeyEvent, OverlaySpec, ScrollSpec, Shortcut, Tx, col, el, icon, row, spacer, text, text_input}; + +/// The bar's height when the playground is closed, hairline included. +pub(crate) const BAR: f32 = 26.0; +const SIDEBAR: f32 = 200.0; +const SIDE: f32 = 264.0; +const HEADER: f32 = 38.0; +const BAND: f32 = 28.0; +const ROW: f32 = 28.0; +const CONTROL: f32 = 24.0; +/// The story list's filter field. +pub(crate) const FILTER: &str = "playground-filter"; +/// How far each level of the story list indents. +const INDENT: f32 = 12.0; + +mod folds; +mod list; +mod live; +mod nav; +mod open; +mod region; +mod stage; +mod story; +mod testing; +mod tree; +mod variants; +mod view; +mod widths; + +pub(crate) use live::{Live, LiveCore}; +use live::{SceneOps, TypedStage}; +use folds::Folds; +use widths::Widths; +pub use open::slug; +pub(crate) use region::{Keyboard, Moved, Region}; +pub(crate) use stage::call; +pub use stage::{Play, Stage, Step}; +use stage::{SCROLL_MARGIN, Staged, Trigger, View, trigger, trigger_tx}; +pub use story::Story; +use story::OwnStory; +pub(crate) use testing::stage_element; +use tree::Row; + +/// A storybook for one window, given to [`App::playground`](crate::App::playground): +/// +/// ```ignore +/// App::new(spec).playground( +/// Playground::<State>::new() +/// .page("Lists/Live devices", devices) +/// .trigger("Lists/Many devices", 'a', "Add device", |s, _| s.devices.push("New")) +/// .story(Story::new("Progress/Upload", Upload::new, upload).trigger('r', "Run", run)) +/// .sizes(&[("Compact", (360.0, 240.0)), ("Wide", (900.0, 600.0))]), +/// ) +/// ``` +/// +/// Name the app's state, as `Playground::<State>::new()`, when a closure comes before anything +/// that does: `Playground::new().trigger(.., |s, _| ..)` can't infer it (E0282). +/// +/// Its stories are the window's `AppSpec::scenes`, then its pages and [`Story`]s, listed under +/// their groups: a `"Group/Name"` name puts a story in a group, and each further `/` nests a +/// group inside it (`"Sidebar/Filter buttons/Compact"`), indented a step, as deep as the path +/// goes. Groups and stories keep the order they first appear in, scenes first, unless +/// [`Playground::group_order`] names the top-level groups to list first; +/// [`Playground::start_folded`] starts them folded. Scenes without a group list under +/// "Scenes", pages and stories under "Pages". A filter field above the list (/ or a click +/// focuses it) narrows it to the stories whose path has every word typed, with their groups +/// unfolded: ↓ goes down into the matches, Return opens the first, and Esc clears it, then +/// leaves. +/// +/// A scene opens as a fresh `AppSpec::init` with the scene fn applied (`App::init`'s closure +/// isn't used), polled by `AppSpec::poll` but never given `AppSpec::setup`, so it gets no +/// waker and starts nothing; with [`Playground::fresh`] it starts from the real state instead. Back drops every stage state and returns to the real one. +/// +/// Keys, while it's open, go to one column at a time: the story list, the stage or the side +/// column. Its selection takes the accent (a ring for the stage), and the hint under the side +/// column lists its keys. A click in a column gives it the keyboard. +/// +/// - **The list** (where it starts): ↑↓ move along it, group headers included, and J K between +/// stories (⌘↑ ⌘↓ to the first and last). On a header ← folds its group, or goes to the group +/// around it once folded, → unfolds it or steps in, and ↵ toggles it, as a click on it does; +/// ← on a story goes to its group. Groups stay folded while the app runs (see +/// [`Playground::folds`] to keep them longer). R replays the story from the start and a +/// trigger's letter runs it. → on a story, or Tab, moves to the side column, ⇧Tab to the +/// stage, and Esc or ⌘⇧D go back to the app. +/// - **The side column**: ↑↓ move between its controls, 1 to 9 pick the story's variant, a +/// trigger's letter runs it, and ←, Tab or Esc go back to the list. Side controls from +/// `side_keys` get every key first, and only Tab and Esc leave them. +/// - **The stage**: every key is the story's, through its focused element or the stage's +/// `AppSpec::on_key`, and Esc it leaves goes back to the list. +/// +/// Keys the list and side column leave, ⌘-chords and digits included, go to the stage's +/// `on_key` too, so a story's shortcuts work wherever the keyboard is. From the list, Esc goes +/// to it first, and [`Playground::typing`] gives it every key first. A focused text field +/// keeps all its keys. +pub struct Playground<S: 'static> { + pages: Vec<Page<S>>, + triggers: Vec<(&'static str, Trigger<S>)>, + sides: Vec<(&'static str, Side<S>)>, + stages: Vec<(&'static str, Stage)>, + sizes: Vec<(&'static str, (f32, f32))>, + shortcut: Option<Shortcut>, + bar: bool, + enabled: bool, + scenes: Option<fn(&str) -> bool>, + fresh: Option<fn(&S) -> S>, + keep: Option<fn(&S, &mut S)>, + variants: Vec<(&'static str, &'static str, Variant<S>)>, + typing: Option<fn(&S) -> bool>, + dark: Option<fn(&S) -> bool>, + folds: Folds, + widths: Widths, + group_order: Vec<&'static str>, +} + +impl<S: 'static> Default for Playground<S> { + fn default() -> Self { + Self::new() + } +} + +impl<S: 'static> Playground<S> { + /// No pages, a bar, ⌘⇧D (Ctrl+Shift+D off macOS), and enabled in debug builds only. + pub fn new() -> Self { + let shortcut = if cfg!(target_os = "macos") { "Shift+Cmd+D" } else { "Ctrl+Shift+D" }; + Playground { + pages: Vec::new(), + triggers: Vec::new(), + sides: Vec::new(), + stages: Vec::new(), + sizes: Vec::new(), + shortcut: shortcut.parse().ok(), + bar: true, + enabled: cfg!(debug_assertions), + scenes: None, + fresh: None, + keep: None, + variants: Vec::new(), + typing: None, + dark: None, + folds: Folds::default(), + widths: Widths::default(), + group_order: Vec::new(), + } + } + + /// A page drawn by `view` from the app's live state. Its handlers change the real state, + /// and it has no triggers or replay. + pub fn page(mut self, name: &'static str, view: impl Fn(&S, &mut Cx<S>) -> El + 'static) -> Self { + self.pages.push(Page { name, kind: Kind::Live(stage::view(view)) }); + self + } + + /// A story with its own state: see [`Story`]. + pub fn story<P: 'static>(mut self, story: Story<P>) -> Self { + assert!(story.real().is_none_or(|t| t == std::any::TypeId::of::<S>()), "Story::from_real({:?}) derives from another app state than this playground's", story.name); + self.pages.push(Page { name: story.name, kind: Kind::Own(Box::new(story)) }); + self + } + + /// A trigger for the scene named `scene` (its path, or just its name): `key` runs `run` on the scene's stage state, as + /// its button in the side column does. An `'r'` trigger runs when the scene is chosen and on + /// each replay, so its motion plays at once. See + /// [`Story::trigger`]. + pub fn trigger(mut self, scene: &'static str, key: char, label: &'static str, run: impl Fn(&mut S, &mut Play<'_, S>) + 'static) -> Self { + self.triggers.push((scene, trigger(key, label, run))); + self + } + + /// [`Playground::trigger`] with a step that takes just the [`Tx`]. See [`Story::trigger_tx`]. + pub fn trigger_tx(mut self, scene: &'static str, key: char, label: &'static str, run: impl Fn(&mut S, &mut Tx) + 'static) -> Self { + self.triggers.push((scene, trigger_tx(key, label, run))); + self + } + + /// The app's own controls for the scene named `scene` (its path, or just its name), at the + /// top of the side column, drawn from and acting on the scene's stage state: knobs, say. + /// See [`Story::side`]. + pub fn side(mut self, scene: &'static str, view: impl Fn(&S, &mut Cx<S>) -> El + 'static) -> Self { + self.sides.push((scene, Side::Stage(stage::view(view)))); + self + } + + /// A variant of the scene named `scene` (its path, or just its name): `apply` runs on its + /// state after the scene fn. See [`Story::variant`]. + pub fn variant(mut self, scene: &'static str, name: &'static str, apply: impl Fn(&mut S) + 'static) -> Self { + self.variants.push((scene, name, Box::new(apply))); + self + } + + /// [`Playground::side`], drawn from the stage and the real state both: to mark the app's + /// own choice beside the one the stage previews, say, with a control that calls + /// [`Tx::keep_playground`] to write the preview back through [`Playground::keep`]. + pub fn side_real(mut self, scene: &'static str, view: impl Fn(&S, &S, &mut Cx<S>) -> El + 'static) -> Self { + self.sides.push((scene, Side::Real(Box::new(view)))); + self + } + + /// [`Playground::side`] for controls that take keys, for the scene named `scene`. See + /// [`Story::side_keys`]. + pub fn side_keys(mut self, scene: &'static str, view: impl Fn(&S, bool, &mut Cx<S>) -> El + 'static, key: impl Fn(&mut S, &KeyEvent, &mut Tx) -> bool + 'static) -> Self { + self.sides.push((scene, Side::Keys(Box::new(view), Box::new(key)))); + self + } + + /// How the stage lays out the scene named `scene` (its path, or just its name). See + /// [`Story::stage`]. + pub fn stage(mut self, scene: &'static str, stage: Stage) -> Self { + self.stages.push((scene, stage)); + self + } + + /// Which of `AppSpec::scenes` the list shows, by name: `|name| name.contains('/')` keeps + /// ungrouped scenes to `--scene`. By default, all of them. + pub fn scenes(mut self, show: fn(&str) -> bool) -> Self { + self.scenes = Some(show); + self + } + + /// Scenes start from `fresh(&real)` rather than `AppSpec::init`, then their scene fn applies: + /// `|real| real.clone()` previews them on a copy of the app as it is, its waker and handles + /// included: a wake from another thread polls the stage. + pub fn fresh(mut self, fresh: fn(&S) -> S) -> Self { + self.fresh = Some(fresh); + self + } + + /// Runs before a scene's stage goes, on R, another story or Back, with the stage and the + /// real state: what it copies over stays in the app, and the next [`Playground::fresh`] + /// starts from it, so tuning in the side column sticks. + pub fn keep(mut self, keep: fn(&S, &mut S)) -> Self { + self.keep = Some(keep); + self + } + + /// While `typing` is true of the stage's state (a scene's, or the real state on a page), + /// `AppSpec::on_key` gets every key before the playground and focused fields do, letters + /// and arrows included, and what it refuses goes on as usual: for a view that takes text + /// itself. A focused Rune field needs none of this; it keeps its keys anyway. + pub fn typing(mut self, typing: fn(&S) -> bool) -> Self { + self.typing = Some(typing); + self + } + + /// Whether the app is dark, read from its real state, for the playground's bar and chrome + /// and the stage's appearance until the switch beside it changes it: for an app with its own + /// light and dark setting. By default, the system's. + pub fn dark(mut self, dark: fn(&S) -> bool) -> Self { + self.dark = Some(dark); + self + } + + /// Stage sizes offered beside "Window" (the stage fills what the playground leaves). + pub fn sizes(mut self, sizes: &[(&'static str, (f32, f32))]) -> Self { + self.sizes = sizes.to_vec(); + self + } + + /// The shortcut that opens and closes the playground, or `None` for none: by default ⌘⇧D, + /// Ctrl+Shift+D off macOS. On macOS it's the View menu's Playground item's. + pub fn shortcut(mut self, shortcut: Option<Shortcut>) -> Self { + self.shortcut = shortcut; + self + } + + /// The bar along the window's bottom edge that opens the playground. With it, the app lays + /// out 26 points shorter, as in a window that much shorter. Without it the app's layout is + /// untouched and the playground opens from its shortcut, the View menu's Playground item, + /// or [`Tx::open_playground`]. + pub fn bar(mut self, on: bool) -> Self { + self.bar = on; + self + } + + /// Whether the window offers the playground at all; by default only in debug builds. + pub fn enabled(mut self, on: bool) -> Self { + self.enabled = on; + self + } + + pub(crate) fn is_enabled(&self) -> bool { + self.enabled + } + + pub(crate) fn shortcut_key(&self) -> Option<&Shortcut> { + self.shortcut.as_ref() + } +} + +/// A scene's side column view, from [`Playground::side`], [`Playground::side_real`] or +/// [`Playground::side_keys`]. +enum Side<S: 'static> { + Stage(View<S>), + Real(Box<dyn Fn(&S, &S, &mut Cx<S>) -> El>), + Keys(SideView<S>, SideKey<S>), +} + +/// A variant's setup, run on a new stage state. +type Variant<X> = Box<dyn Fn(&mut X)>; + +/// A side column view that takes keys, told whether the keyboard is on it. +type SideView<X> = Box<dyn Fn(&X, bool, &mut Cx<X>) -> El>; +/// Its keys: true when it took one. +type SideKey<X> = Box<dyn Fn(&mut X, &KeyEvent, &mut Tx) -> bool>; + +struct Page<S: 'static> { + name: &'static str, + kind: Kind<S>, +} + +enum Kind<S: 'static> { + Live(View<S>), + Own(Box<dyn OwnStory>), +} + +/// A story's group and name, from its path: everything before the last `/` names its group +/// (`"Sidebar/Filter buttons"`, a group inside "Sidebar"), the rest the story. +fn split(path: &'static str, default: &'static str) -> (&'static str, &'static str) { + path.rsplit_once('/').unwrap_or((default, path)) +} + +/// What a handler asks of the playground (`Tx::open_playground`, its keys and its controls), +/// applied at the start of the next commit, before the view runs against the new stage. +#[derive(Clone, Debug, PartialEq)] +pub(crate) enum Request { + Open(Option<String>), + /// [`Tx::open_playground_at`]: a story by path, name or slug, and a variant. + OpenAt(String, Option<String>), + Close, + Toggle, + Select(usize), + /// R: the stage's state made again, then its `'r'` trigger. + Replay, + /// [`Tx::keep_playground`]. + Keep, + /// A digit: the open story's variant, by index, made as R makes it. + Variant(usize), + Trigger(char), + Dark(bool), + Size(usize), + ReduceMotion(bool), + /// A group's header becomes the list's selection; the stage keeps its story. + Header(&'static str), + /// Folds a group (`Some(true)`), unfolds it, or toggles it (`None`). + Fold(&'static str, Option<bool>), +} + +impl Request { + /// Whether this one changes the stage's state, so handlers built for the old one must go. + fn swaps_stage(&self) -> bool { + matches!(self, Request::Open(_) | Request::OpenAt(..) | Request::Close | Request::Toggle | Request::Select(_) | Request::Replay | Request::Variant(_)) + } +} + +/// What a key does in the open playground, for the runtime to carry out. +pub(crate) enum Nav { + Pass, + /// The playground's key, which does nothing here. + Stay, + Request(Request), + /// Focus the side column's first control. + IntoSide, + /// The stage takes the keyboard. + IntoStage, + /// Focus the story list's filter field. + Filter, + /// Focus leaves the side column. + OutOfSide, + /// Focus moves this many controls along the side column. + SideStep(isize), +} + +/// The playground's own controls' state: the story list's filter field and column widths. Its +/// other controls change the playground through requests. +pub(crate) struct Controls { + pub(crate) filter: crate::TextEdit, + pub(super) sidebar_w: f32, + pub(super) side_w: f32, + pub(super) save_widths: Option<Rc<dyn Fn(f32, f32)>>, +} + +impl Default for Controls { + fn default() -> Self { + Self { filter: Default::default(), sidebar_w: SIDEBAR, side_w: SIDE, save_widths: None } + } +} + +/// `attach`'s signature, for `App::attach_playground`. +pub(crate) type Attach<S> = fn(&mut crate::Runtime<S>, Option<Playground<S>>, &crate::AppSpec<S>, Option<Option<String>>, Option<String>, bool); + +/// Shows `playground` in `rt`'s window when this run offers it: an enabled playground, in a +/// window unless `RUNE_PLAYGROUND=0`, or wherever `--playground` asks for it, headless included, +/// opened at the story it names, on the variant `--variant` names. +pub(crate) fn attach<S: 'static>(rt: &mut crate::Runtime<S>, playground: Option<Playground<S>>, spec: &crate::AppSpec<S>, open: Option<Option<String>>, variant: Option<String>, windowed: bool) { + let Some(mut playground) = playground.filter(Playground::is_enabled) else { return }; + if open.is_none() && (!windowed || hidden_by_env()) { return; } + playground.widths.attach_prefs(windowed, spec.title); + let mut live = Live::new(playground, spec, windowed && cfg!(target_os = "macos")); + live.core.queue_launch(open, variant); + rt.attach_playground(live); +} + +/// `--playground [NAME]`'s optional story name, taking it when the next argument isn't a flag. +pub(crate) fn arg(argv: &[String], i: &mut usize) -> Option<String> { + let name = argv.get(*i + 1).filter(|v| !v.starts_with("--")).cloned(); + if name.is_some() { *i += 1; } + name +} + +fn hidden_by_env() -> bool { + rune_core::env::var("RUNE_PLAYGROUND").is_some_and(|v| v == "0") +} + +pub(crate) fn offered_by_env() -> bool { + !hidden_by_env() +} + +impl Tx { + /// Show [`App::playground`](crate::App::playground) in this window. Without one, or in a + /// run that doesn't show it (a release build, `RUNE_PLAYGROUND=0`, a headless render + /// without `--playground`), nothing happens. + pub fn open_playground(&mut self) { + self.playground.push(Request::Open(None)); + } + + /// Back to the app from the playground, as its Back button does. + pub fn close_playground(&mut self) { + self.playground.push(Request::Close); + } + + /// Runs [`Playground::keep`] now, with the open scene's stage and the real state, as a + /// switch would before the stage goes. The stage stays. + pub fn keep_playground(&mut self) { + self.playground.push(Request::Keep); + } + + pub fn toggle_playground(&mut self) { + self.playground.push(Request::Toggle); + } +} + +/// Whether `key` is the stage's, around the story's root. +pub(crate) fn is_stage(key: &str) -> bool { + key.strip_prefix("playground-stage-").is_some_and(|g| g.parse::<u32>().is_ok()) +} + +#[cfg(test)] +mod tests; diff --git a/app/vendor/rune/crates/rune/src/playground/chrome_tests.rs b/app/vendor/rune/crates/rune/src/playground/chrome_tests.rs new file mode 100644 index 0000000..193ac36 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/playground/chrome_tests.rs @@ -0,0 +1,25 @@ +use super::*; + +fn fill(rt: &Runtime<Real>, key: &str) -> Color { + find(rt, key).unwrap_or_else(|| panic!("no {key}")).fill +} + +#[test] +fn the_chrome_follows_the_apps_own_dark_setting() { + let mut rt = runtime_with(base().dark(|s| s.count >= 100), Some(Some("Fade".into())), true); + assert_eq!(fill(&rt, "playground"), tok::theme(false).bg, "the real state says light"); + rt.state.count = 100; + rt.update(|_, _| {}); + for _ in 0..60 { rt.frame(DT); } + assert_eq!(fill(&rt, "playground"), tok::theme(true).bg, "though the system is light"); + assert_eq!(find(&rt, "playground-theme").and_then(|e| e.label).as_deref(), Some("Dark appearance"), "and the stage starts dark with it"); +} + +#[test] +fn without_it_the_chrome_follows_the_system() { + let mut rt = runtime(Some(Some("Fade".into()))); + rt.state.count = 100; + rt.update(|_, _| {}); + for _ in 0..60 { rt.frame(DT); } + assert_eq!(fill(&rt, "playground"), tok::theme(false).bg); +} diff --git a/app/vendor/rune/crates/rune/src/playground/folds.rs b/app/vendor/rune/crates/rune/src/playground/folds.rs new file mode 100644 index 0000000..28b2b6b --- /dev/null +++ b/app/vendor/rune/crates/rune/src/playground/folds.rs @@ -0,0 +1,67 @@ +//! Which groups the list folds, at any level: kept while the app runs, and through +//! [`Playground::folds`]' hooks from one run to the next. + +use super::*; + +/// [`Playground::folds`]' hooks, and [`Playground::start_folded`]. `load` runs once, when the +/// playground first applies a request. +#[derive(Default)] +pub(super) struct Folds { + load: Option<Box<dyn FnOnce() -> Vec<String>>>, + save: Option<Box<dyn Fn(&[String])>>, + pub(super) start: bool, +} + +impl<S: 'static> Playground<S> { + /// Every group starts folded, at every level, but the ones around the open story: each + /// time the playground opens, the open story's groups unfold, so a link through + /// [`Tx::open_playground_at`] at launch shows its story. Off by default, where every group + /// starts open and a folded one stays folded until it's unfolded. Worth it for a long, + /// deep list. + pub fn start_folded(mut self, on: bool) -> Self { + self.folds.start = on; + self + } + + /// Keeps the folded groups from one run to the next. Without it, folds last while the app + /// runs, closing and opening the playground included. A group is named by its path, + /// `"Sidebar"` or `"Sidebar/Filter buttons"` for one inside it. `load` gives the names + /// saved last time, once, as the playground first opens; names it no longer has are + /// dropped. `save` gets the names each time a group folds or unfolds: the folded groups, + /// or with [`Playground::start_folded`] the unfolded ones, so a group added since starts + /// as the rest do. With [`Prefs`](crate::prefs::Prefs): + /// + /// ```ignore + /// .folds( + /// || Prefs::open(APP_ID).get("playground_folds").unwrap_or_default(), + /// |groups| { Prefs::open(APP_ID).set("playground_folds", &groups).ok(); }, + /// ) + /// ``` + pub fn folds(mut self, load: impl Fn() -> Vec<String> + 'static, save: impl Fn(&[String]) + 'static) -> Self { + self.folds = Folds { load: Some(Box::new(load)), save: Some(Box::new(save)), start: self.folds.start }; + self + } +} + +impl LiveCore { + /// Folds the groups [`Playground::folds`]' `load` names, the first time it's called. + pub(super) fn load_folds(&mut self) { + let Some(load) = self.folds.load.take() else { return }; + let names = load(); + let start = self.folds.start; + self.folded = self.all_groups().into_iter().filter(|g| names.iter().any(|n| n == g) != start).collect(); + } + + /// Changes which groups are folded, and saves them if that changed them. + pub(super) fn refold(&mut self, change: impl FnOnce(&mut Vec<&'static str>)) { + let before = self.folded.clone(); + change(&mut self.folded); + if self.folded == before { return; } + let Some(save) = &self.folds.save else { return }; + let names: Vec<String> = match self.folds.start { + true => self.all_groups().into_iter().filter(|g| !self.folded.contains(g)).map(str::to_owned).collect(), + false => self.folded.iter().map(|g| (*g).to_owned()).collect(), + }; + save(&names); + } +} diff --git a/app/vendor/rune/crates/rune/src/playground/groups_tests.rs b/app/vendor/rune/crates/rune/src/playground/groups_tests.rs new file mode 100644 index 0000000..8e7d5d2 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/playground/groups_tests.rs @@ -0,0 +1,61 @@ +use super::*; + +fn shown(rt: &Runtime<Real>, i: usize) -> bool { + find(rt, &format!("playground-item-{i}")).is_some() +} + +#[test] +fn a_click_on_a_header_folds_its_group_and_another_unfolds_it() { + let mut rt = runtime(Some(Some("big".into()))); + assert!(shown(&rt, 2) && shown(&rt, 5)); + tap(&mut rt, "playground-group-2"); + assert!(!shown(&rt, 2) && !shown(&rt, 5), "Motion's stories are hidden"); + assert!(shown(&rt, 3), "other groups aren't"); + assert_eq!((header(&rt), selected(&rt)), (Some("Motion"), 0), "the header is the selection; the stage keeps its story"); + tap(&mut rt, "playground-group-2"); + assert!(shown(&rt, 2) && shown(&rt, 5)); +} + +#[test] +fn left_right_and_return_fold_the_selected_header() { + let mut rt = runtime(Some(Some("Still".into()))); + press(&mut rt, Key::Up); + assert_eq!(header(&rt), Some("Motion")); + press(&mut rt, Key::Left); + assert!(!shown(&rt, 2)); + press(&mut rt, Key::Down); + assert_eq!(header(&rt), Some("Live"), "↓ skips the folded stories"); + press(&mut rt, Key::Up); + press(&mut rt, Key::Right); + assert!(shown(&rt, 2)); + press(&mut rt, Key::Enter); + assert!(!shown(&rt, 2)); + press(&mut rt, Key::Enter); + assert!(shown(&rt, 2)); + assert_eq!(selected(&rt), 2, "the stage never changed story"); +} + +#[test] +fn folding_the_open_storys_group_selects_its_header_and_stays_folded_after_close() { + let mut rt = runtime(Some(Some("Fade".into()))); + tap(&mut rt, "playground-group-2"); + assert_eq!((header(&rt), selected(&rt)), (Some("Motion"), 5)); + letter(&mut rt, "r"); + assert_eq!(header(&rt), Some("Motion"), "a replay keeps the list as it is"); + assert!(!shown(&rt, 5)); + escape(&mut rt); + rt.update(|_, tx| tx.open_playground()); + rt.frame(DT); + assert!(!shown(&rt, 2) && !shown(&rt, 5), "reopened, the group is still folded"); + assert_eq!((header(&rt), selected(&rt)), (Some("Motion"), 5), "and its header stands in for the story"); +} + +#[test] +fn choosing_a_story_by_name_unfolds_its_group() { + let mut rt = runtime(Some(Some("big".into()))); + tap(&mut rt, "playground-group-2"); + rt.update(|_, tx| tx.playground.push(Request::Open(Some("Fade".into())))); + rt.frame(DT); + assert!(shown(&rt, 5)); + assert_eq!((header(&rt), selected(&rt)), (None, 5)); +} diff --git a/app/vendor/rune/crates/rune/src/playground/keys_tests.rs b/app/vendor/rune/crates/rune/src/playground/keys_tests.rs new file mode 100644 index 0000000..4574565 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/playground/keys_tests.rs @@ -0,0 +1,29 @@ +use super::*; + +fn typing() -> Playground<Real> { + base().typing(|s| s.typing).trigger("big", 't', "Type", |s, _| s.typing = true) +} + +fn typed(rt: &Runtime<Real>) -> String { + rt.hooks.playground.as_ref().and_then(|p| p.scene()).map(|s| s.state.typed.clone()).unwrap_or_default() +} + +#[test] +fn while_the_stage_is_typing_its_on_key_gets_keys_before_the_playground() { + let mut rt = runtime_with(typing(), Some(Some("big".into())), true); + letter(&mut rt, "t"); + rt.frame(DT); + for c in ["j", "r", "t", "2"] { letter(&mut rt, c); } + assert_eq!((typed(&rt), selected(&rt)), ("jrt2".into(), 0), "letters, R and triggers are the stage's"); + press(&mut rt, Key::Down); + assert_eq!(selected(&rt), 1, "what on_key refuses still reaches the playground"); +} + +#[test] +fn without_typing_the_playground_keeps_its_keys() { + let mut rt = runtime_with(base().trigger("big", 't', "Type", |s, _| s.typing = true), Some(Some("big".into())), true); + letter(&mut rt, "t"); + rt.frame(DT); + letter(&mut rt, "j"); + assert_eq!(selected(&rt), 1); +} diff --git a/app/vendor/rune/crates/rune/src/playground/list.rs b/app/vendor/rune/crates/rune/src/playground/list.rs new file mode 100644 index 0000000..238e59f --- /dev/null +++ b/app/vendor/rune/crates/rune/src/playground/list.rs @@ -0,0 +1,117 @@ +//! The sidebar: Back, the filter field, the story list as an indented tree, and the stage's +//! controls along its foot. + +use super::view::{CHEVRON_DOWN, CHEVRON_LEFT, CHEVRON_RIGHT, MOTION, selected, tertiary}; +use super::*; + +/// The filter field's row: the field and the gap under it. +const FIELD: f32 = 32.0; + +impl LiveCore { + pub(super) fn sidebar(&self, t: Theme, dark: bool, accent: Color, inset: f32, sidebar_w: f32, height: f32) -> El { + let back = row().key("playground-back").h(CONTROL).pl(4.0).pr(8.0).gap(2.0).center_y().radius(radius::SM) + .hover(t.hover).press(t.press) + .child(icon(&CHEVRON_LEFT, 16.0).color(t.text_secondary)) + .child(text("Back").font(type_::LABEL).color(t.text)) + .role("button").label("Back to the app") + .on_press_tx(|_: &mut Controls, tx: &mut Tx| tx.close_playground()); + // Back sits at the list's text inset; where the window's own controls take the corner, + // it goes in the row under them. + let band = if inset > 0.0 { BAND } else { 0.0 }; + let header = row().w(sidebar_w).h(HEADER).pl(8.0).center_y().child(back); + let drag = (band > 0.0).then(|| el().w(sidebar_w).h(band).window_drag()); + // The list's selection takes the accent while the list has the keyboard. + let on_fill = if self.region() == Region::List { focused(accent) } else { selected(t, dark) }; + // A scroll measures its first child, so the rows go in one content column. + let mut list = col().key("playground-rows").w_full(); + let rows = self.rows(); + for (n, entry) in rows.iter().copied().enumerate() { + list = list.child(match entry { + Row::Header(group, first, depth) => self.header_row(t, on_fill, group, first, depth, n == 0), + Row::Story(i, depth) => self.story_row(t, on_fill, i, depth), + }); + } + if rows.is_empty() { + let empty = if self.order.is_empty() { "No stories" } else { "No matches" }; + list = list.child(text(empty).font(type_::BODY).color(t.text_secondary).px(8.0).pt(4.0)); + } + let list = col().key("playground-list").w(sidebar_w).h(height - 2.0 * HEADER - FIELD - band).px(8.0).pb(8.0) + .scroll(ScrollSpec { stick_bottom: false }).child(list); + col().w(sidebar_w).h(height) + .children(drag) + .child(header) + .child(self.filter_field(t, sidebar_w)) + .child(list) + .child(self.stage_controls(t, dark, sidebar_w)) + } + + /// Narrows the list to the stories whose path has every word typed; / focuses it. + fn filter_field(&self, t: Theme, sidebar_w: f32) -> El { + let field = text_input(&self.controls.filter, type_::LABEL).key(FILTER) + .single_line() + .color(t.text) + .caret(t.text, t.text.alpha(0.2)) + .placeholder("Filter", tertiary(t)) + .grow(1.0) + .min_w(0.0) + .label("Filter stories") + .on_edit(|c: &mut Controls| &mut c.filter); + row().w(sidebar_w).h(FIELD).px(8.0).pb(8.0).child( + row().w_full().h(FIELD - 8.0).px(8.0).center_y().radius(radius::MD).fill(t.card).outline(1.0, 0.0, t.card_border).child(field), + ) + } + + /// A story's row, indented a step for each group it's in. + fn story_row(&self, t: Theme, on_fill: Color, i: usize, depth: usize) -> El { + let on = i == self.selected && self.header.is_none(); + let name = self.name(i); + // Stories with triggers move, so a quiet mark tells them apart. + let mark = self.has_triggers(i).then(|| [ + spacer(), + icon(&MOTION, 12.0).key(format!("playground-motion-{i}")).color(tertiary(t)).ml(6.0), + ]); + row().key(format!("playground-item-{i}")).w_full().h(ROW).pl(indent(depth)).pr(8.0).center_y().radius(radius::MD) + .fill(if on { on_fill } else { Color::TRANSPARENT }) + .hover(if on { on_fill } else { t.hover }) + .child(text(name).font(type_::BODY).color(if on || i == self.selected { t.text } else { t.text_secondary }).truncate()) + .children(mark.into_iter().flatten()) + .role("button").label(name) + .on_press_tx(move |_: &mut Controls, tx: &mut Tx| tx.playground.push(Request::Select(i))) + } + + /// A group's header, keyed by its first story and depth: a disclosure chevron, its name a + /// step bolder than a story's, and how many stories it holds. A press selects it and folds + /// or unfolds it. + fn header_row(&self, t: Theme, on_fill: Color, group: &'static str, first: usize, depth: usize, top: bool) -> El { + let on = self.header == Some(group); + let folded = self.is_folded(group); + let name = Self::parent(group).map_or(group, |up| &group[up.len() + 1..]); + // A top group reads in full text colour, the groups inside it a step quieter. + let ink = if on || depth == 0 { t.text } else { t.text_secondary }; + let row = row().key(Row::header_key(first, depth)).w_full().h(24.0).pl(indent(depth)).pr(8.0).center_y().radius(radius::MD) + .fill(if on { on_fill } else { Color::TRANSPARENT }) + .hover(if on { on_fill } else { t.hover }) + .child(row().w(INDENT).h(24.0).center().child(icon(if folded { &CHEVRON_RIGHT } else { &CHEVRON_DOWN }, 12.0).color(tertiary(t)))) + .child(text(name).font(type_::SECTION).color(ink).truncate()) + .child(spacer()) + .child(text(self.count_in(group).to_string()).key(Row::header_key(first, depth).replace("group", "count")).font(type_::LABEL).color(tertiary(t)).ml(6.0)) + .role("button").label(if folded { format!("Show {name}") } else { format!("Hide {name}") }) + .on_press_tx(move |_: &mut Controls, tx: &mut Tx| { + tx.playground.push(Request::Header(group)); + tx.playground.push(Request::Fold(group, None)); + }); + // Top groups stand apart; the groups inside them sit closer. + let above = match (top, depth) { (true, _) => 2.0, (_, 0) => 10.0, _ => 4.0 }; + col().w_full().pt(above).pb(2.0).child(row) + } +} + +/// A row's left inset at `depth`: its text lines up with its group's name. +fn indent(depth: usize) -> f32 { + 8.0 + INDENT * depth as f32 +} + +/// A selection's fill in the column that has the keyboard: the accent, softly. +pub(super) fn focused(accent: Color) -> Color { + accent.alpha(0.2) +} diff --git a/app/vendor/rune/crates/rune/src/playground/live.rs b/app/vendor/rune/crates/rune/src/playground/live.rs new file mode 100644 index 0000000..cd7ab4d --- /dev/null +++ b/app/vendor/rune/crates/rune/src/playground/live.rs @@ -0,0 +1,639 @@ +//! [`Live`] and [`LiveCore`]: a window's playground while it runs, and the requests that move it. + +use super::*; + +/// An own-state story (`Story<P>`, type-erased) together with its live stage while open. +pub(super) struct OwnedStory { + pub(super) story: Box<dyn OwnStory>, + pub(super) stage: Option<Box<dyn Any>>, +} + +/// Precomputed `S`-independent story metadata used by the list, side column, navigation and +/// layout without touching the app's state type. +pub(super) struct StoryMeta { + pub(super) path: &'static str, + pub(super) group: &'static str, + pub(super) name: &'static str, + pub(super) layout: Stage, + pub(super) frame: Option<(f32, f32)>, + pub(super) has_triggers: bool, + pub(super) triggers: Vec<(char, &'static str)>, + pub(super) variants: Vec<&'static str>, + pub(super) side_keys: bool, + pub(super) is_live_page: bool, +} + +/// Inputs [`Live::new`] extracts from a typed `Playground<S>` and `AppSpec<S>` to build +/// [`LiveCore`] once, non-generically. +pub(super) struct LiveInit { + pub(super) scenes: Vec<&'static str>, + pub(super) pages: Vec<(&'static str, Option<Box<dyn OwnStory>>)>, + pub(super) triggers: Vec<(usize, char, &'static str)>, + pub(super) side_keys: Vec<usize>, + pub(super) stages: Vec<(usize, Stage)>, + pub(super) variants: Vec<(usize, &'static str)>, + pub(super) sizes: Vec<(&'static str, (f32, f32))>, + pub(super) shortcut: Option<Shortcut>, + pub(super) menu: bool, + pub(super) bar: bool, + pub(super) show: Option<fn(&str) -> bool>, + pub(super) folds: Folds, + pub(super) widths: Widths, + pub(super) group_order: Vec<&'static str>, +} + +/// Narrow boundary through which non-generic [`LiveCore`] request handling reaches the typed +/// scene state and real app state `S`. +pub(super) trait SceneOps { + fn real(&self) -> &dyn Any; + fn keep(&mut self); + fn clear_scene(&mut self); + fn build_scene(&mut self, selected: usize, variant: usize, clock: crate::SceneClock); + fn trigger_scene(&mut self, selected: usize, key: char, now: f64); +} + +static REPLAY_ONLY: &[(char, &str)] = &[('r', "Replay")]; + +fn order_triggers(mut keys: Vec<(char, &'static str)>) -> Vec<(char, &'static str)> { + let replay = keys.iter().position(|(k, _)| *k == 'r').map_or(('r', "Replay"), |i| keys.remove(i)); + keys.insert(0, replay); + keys +} + +/// Non-generic playground UI state, story metadata, navigation, chrome and own-state stages. +/// +/// Compiled once in `librune` instead of per app state type `S`; [`Live<S>`] wraps this beside +/// the typed scene/page hooks. +pub(crate) struct LiveCore { + pub(super) scene_count: usize, + pub(super) stories: Vec<StoryMeta>, + /// Each story's variant, by its index into scenes then pages, until the playground closes. + pub(super) variant: Vec<usize>, + pub(super) sizes: Vec<(&'static str, (f32, f32))>, + pub(super) shortcut: Option<Shortcut>, + /// The View menu's item takes the shortcut, so keys here leave it alone. + pub(super) menu: bool, + pub(super) bar: bool, + /// Stories, as indices into scenes then pages, in the order the list shows them. + pub(super) order: Vec<usize>, + /// Into scenes then pages. + pub(super) selected: usize, + /// A group header is the list's selection rather than `selected`'s row. + pub(super) header: Option<&'static str>, + /// Groups whose stories the list hides, until the playground closes. + pub(super) folded: Vec<&'static str>, + /// [`Playground::folds`]. + pub(super) folds: Folds, + /// [`Playground::widths`]. + pub(super) widths: Widths, + /// The column that has the keyboard. + pub(super) keyboard: Keyboard, + /// Whether the playground is showing. While closed, `Live::stage.scene` is `None`. + pub(super) open: bool, + /// Own-state stories by page index (`i - scene_count`); `None` for live pages. + pub(super) owned: Vec<Option<OwnedStory>>, + pub(super) controls: Controls, + pub(super) dark: Option<bool>, + pub(super) size: usize, + pub(super) reduce_motion: bool, + pub(super) pending: Vec<Request>, + /// Keys the stage's steps pressed with [`Play::press`], until the runtime routes them. + pub(super) pressed: Vec<KeyEvent>, + /// A key a step pressed is being routed: only the stage pages. + pub(crate) pressing: bool, + /// How many keys steps have pressed, which a motion gate's run reads as input. + pub(crate) played: u64, + /// The clock at the last commit or poll, which triggers start from. + pub(super) now: f64, + /// Bumped by every select and replay, so the new stage's elements start fresh: scroll + /// offsets, focus and animations don't carry over from the last one. + pub(super) generation: u32, + /// The time scale the app had when the playground opened, which every new stage starts + /// from and Back restores. + pub(crate) app_time_scale: f32, +} + +impl LiveCore { + pub(super) fn new(init: LiveInit) -> Self { + let LiveInit { scenes, pages, triggers, side_keys, stages, variants, sizes, shortcut, menu, bar, show, folds, mut widths, group_order } = init; + let scene_count = scenes.len(); + let mut stories = Vec::with_capacity(scene_count + pages.len()); + for (i, path) in scenes.into_iter().enumerate() { + let (group, name) = split(path, "Scenes"); + let layout = stages.iter().rev().find(|(s, _)| *s == i).map_or(Stage::Center, |(_, stage)| *stage); + let keys: Vec<(char, &'static str)> = triggers.iter().filter(|(s, _, _)| *s == i).map(|(_, k, l)| (*k, *l)).collect(); + let has_triggers = !keys.is_empty(); + stories.push(StoryMeta { + path, + group, + name, + layout, + frame: None, + has_triggers, + triggers: order_triggers(keys), + variants: variants.iter().filter(|(s, _)| *s == i).map(|(_, label)| *label).collect(), + side_keys: side_keys.contains(&i), + is_live_page: false, + }); + } + let mut owned = Vec::with_capacity(pages.len()); + for (path, own) in pages { + let (group, name) = split(path, "Pages"); + match own { + Some(story) => { + let keys = story.triggers(); + let has_triggers = !keys.is_empty(); + stories.push(StoryMeta { + path, + group, + name, + layout: story.layout(), + frame: story.frame(), + has_triggers, + triggers: order_triggers(keys), + variants: story.variants(), + side_keys: story.side_keys(), + is_live_page: false, + }); + owned.push(Some(OwnedStory { story, stage: None })); + } + None => { + stories.push(StoryMeta { + path, + group, + name, + layout: Stage::Center, + frame: None, + has_triggers: false, + triggers: Vec::new(), + variants: Vec::new(), + side_keys: false, + is_live_page: true, + }); + owned.push(None); + } + } + } + let controls = Controls { save_widths: widths.save.take(), ..Controls::default() }; + let count = stories.len(); + let mut core = LiveCore { + scene_count, + stories, + variant: vec![0; count], + sizes, + shortcut, + menu, + bar, + order: Vec::new(), + selected: 0, + header: None, + folded: Vec::new(), + folds, + widths, + keyboard: Keyboard::default(), + open: false, + owned, + controls, + dark: None, + size: 0, + reduce_motion: false, + pending: Vec::new(), + pressed: Vec::new(), + pressing: false, + played: 0, + now: 0.0, + generation: 0, + app_time_scale: 1.0, + }; + let listed: Vec<usize> = (0..count).filter(|&i| i >= scene_count || show.is_none_or(|show| show(core.path(i)))).collect(); + core.order = core.tree_order(&listed, &group_order); + core.selected = core.order.first().copied().unwrap_or(0); + if core.folds.start { core.folded = core.all_groups(); } + core.load_widths(); + core + } + + pub(crate) fn is_open(&self) -> bool { + self.open + } + + pub(super) fn count(&self) -> usize { + self.stories.len() + } + + pub(super) fn path(&self, i: usize) -> &'static str { + self.stories[i].path + } + + pub(super) fn group(&self, i: usize) -> &'static str { + self.stories[i].group + } + + pub(super) fn name(&self, i: usize) -> &'static str { + self.stories[i].name + } + + pub(super) fn own(&self) -> Option<(&dyn OwnStory, &dyn Any)> { + let i = self.selected.checked_sub(self.scene_count)?; + let own = self.owned.get(i)?.as_ref()?; + Some((own.story.as_ref(), own.stage.as_deref()?)) + } + + pub(super) fn own_slot_mut(&mut self, i: usize) -> Option<&mut OwnedStory> { + let page = i.checked_sub(self.scene_count)?; + self.owned.get_mut(page)?.as_mut() + } + + pub(super) fn is_live_page(&self) -> bool { + self.stories.get(self.selected).is_some_and(|s| s.is_live_page) + } + + #[inline(always)] + pub(super) fn is_own_page(&self) -> bool { + self.selected.checked_sub(self.scene_count).and_then(|i| self.owned.get(i)).is_some_and(Option::is_some) + } + + /// How the stage lays out the open story. + pub(super) fn layout(&self) -> Stage { + self.stories.get(self.selected).map_or(Stage::Center, |s| s.layout) + } + + /// An overlay story's dashed frame size, if the open story has one. + pub(super) fn frame(&self) -> Option<(f32, f32)> { + self.stories.get(self.selected).and_then(|s| s.frame) + } + + /// Whether story `i` has triggers of its own, beside R, which the list marks. + pub(super) fn has_triggers(&self, i: usize) -> bool { + self.stories.get(i).is_some_and(|s| s.has_triggers) + } + + /// The open story's triggers, R's first. + pub(super) fn triggers(&self) -> &[(char, &'static str)] { + match self.stories.get(self.selected) { + Some(story) => &story.triggers, + None => REPLAY_ONLY, + } + } + + pub(crate) fn request(&mut self, requests: Vec<Request>) { + self.pending.extend(requests); + } + + pub(crate) fn has_pending(&self) -> bool { + !self.pending.is_empty() + } + + pub(crate) fn pending_swaps_stage(&self) -> bool { + self.pending.iter().any(Request::swaps_stage) + } + + /// Whether the only requests that swap the stage are replays, which keep its story. + pub(crate) fn pending_replays_only(&self) -> bool { + self.pending.iter().filter(|r| r.swaps_stage()).all(|r| matches!(r, Request::Replay | Request::Variant(_))) + } + + pub(super) fn apply_requests(&mut self, clock: f64, ops: &mut dyn SceneOps) -> bool { + self.now = clock; + self.load_folds(); + self.load_widths(); + let mut changed = false; + for request in std::mem::take(&mut self.pending) { + changed = true; + match request { + Request::Open(name) => self.open_story(name.as_deref(), ops), + Request::OpenAt(name, variant) => { + let name = self.resolve(&name, variant.as_deref()); + self.open_story(name.as_deref(), ops); + } + Request::Close => self.close(ops), + Request::Toggle if self.open => self.close(ops), + Request::Toggle => { + self.open = true; + if self.folds.start { self.reveal(self.selected); } + self.select(self.selected, ops); + } + Request::Select(i) => { + self.reveal(i); + self.select(i, ops); + } + Request::Replay => self.replay(ops), + Request::Variant(n) if n < self.variants().len() => { + self.variant[self.selected] = n; + self.replay(ops); + } + Request::Variant(_) => {} + Request::Keep => ops.keep(), + Request::Trigger(key) => self.trigger(key, ops), + Request::Dark(dark) => self.dark = Some(dark), + Request::Size(i) => self.size = i, + Request::ReduceMotion(on) => self.reduce_motion = on, + Request::Header(group) => self.header = Some(group), + Request::Fold(group, fold) => self.fold(group, fold), + } + } + // Opened on a story whose group is folded, the header stands in for its row. + self.settle(); + changed + } + + /// Folds a group, unfolds it, or toggles it. A filter shows every match, so folds wait + /// until it's cleared. A selection whose row goes moves to the header that hid it. + pub(super) fn fold(&mut self, group: &'static str, fold: Option<bool>) { + if !self.query().is_empty() { return; } + let folded = self.folded.contains(&group); + match fold.unwrap_or(!folded) { + true if !folded => self.refold(|f| f.push(group)), + false => self.refold(|f| f.retain(|g| *g != group)), + true => {} + } + self.settle(); + } + + /// Story `i`'s row becomes the list's selection, its groups unfolded. + pub(super) fn reveal(&mut self, i: usize) { + self.header = None; + if i < self.count() { + let groups = self.groups_of(i); + self.refold(|f| f.retain(|g| !groups.contains(g))); + } + } + + /// The open story's stage made again, then its `'r'` trigger. + pub(super) fn replay(&mut self, ops: &mut dyn SceneOps) { + if self.is_live_page() { return; } + if let Some(own) = self.own_slot_mut(self.selected) { own.stage = None; } + self.select(self.selected, ops); + } + + pub(super) fn close(&mut self, ops: &mut dyn SceneOps) { + ops.keep(); + ops.clear_scene(); + self.open = false; + self.header = None; + self.moved(Moved::Closed); + self.controls.filter = crate::TextEdit::default(); + self.variant.iter_mut().for_each(|v| *v = 0); + for own in self.owned.iter_mut().flatten() { own.stage = None; } + } + + /// Shows story `i`. A stage made new, as a scene's always is, runs its `'r'` trigger. + /// Closed, only the selection moves: nothing is staged until the playground opens. + pub(super) fn select(&mut self, i: usize, ops: &mut dyn SceneOps) { + ops.keep(); + if let Some(own) = self.own_slot_mut(self.selected) + && let Some(stage) = own.stage.as_mut() + { + own.story.stop(stage.as_mut()); + } + self.selected = i.min(self.count().saturating_sub(1)); + if !self.open { return; } + ops.clear_scene(); + self.generation += 1; + let scene_clock = crate::SceneClock { now: self.now, dt: 1.0 / 60.0 }; + if self.selected < self.scene_count { + ops.build_scene(self.selected, self.variant_at(), scene_clock); + } else { + let variant = self.variant_at(); + let Some(own) = self.own_slot_mut(self.selected) else { return }; + if own.stage.is_some() { return; } + let stage = crate::with_scene_clock(scene_clock, || own.story.init(ops.real(), variant)); + own.stage = Some(stage); + } + self.trigger('r', ops); + } + + /// Queues the open story's trigger on `key`, to run at the next poll from now. + pub(super) fn trigger(&mut self, key: char, ops: &mut dyn SceneOps) { + if !self.open { return; } + let now = self.now; + if self.selected < self.scene_count { + ops.trigger_scene(self.selected, key, now); + return; + } + if let Some(own) = self.own_slot_mut(self.selected) + && let Some(stage) = own.stage.as_mut() + { + own.story.trigger(stage.as_mut(), key, now); + } + } + + /// Whether `ev` is the shortcut that opens and closes the playground, where no menu item + /// takes it first. + pub(crate) fn is_shortcut(&self, ev: &KeyEvent) -> bool { + !self.menu && self.shortcut.as_ref().is_some_and(|s| s.matches_key(ev)) + } +} + +/// The `S`-dependent scene hooks, live page views and active scene stage owned beside [`LiveCore`]. +pub(super) struct TypedStage<S: 'static> { + /// Live-page views by page index (`i - scene_count`); `None` for own-state stories. + pub(super) live_pages: Vec<Option<View<S>>>, + /// By the scene they're for. + pub(super) triggers: Vec<(usize, Trigger<S>)>, + pub(super) sides: Vec<(usize, Side<S>)>, + pub(super) variants: Vec<(usize, Variant<S>)>, + pub(super) init: fn() -> S, + pub(super) fresh: Option<fn(&S) -> S>, + pub(super) keep: Option<fn(&S, &mut S)>, + pub(super) typing: Option<fn(&S) -> bool>, + /// [`Playground::dark`]. + pub(super) app_dark: Option<fn(&S) -> bool>, + pub(super) scenes: &'static [(&'static str, fn(&mut S))], + pub(super) poll: Option<fn(&mut S, f64, &mut Tx) -> bool>, + /// The open scene's stage; always `None` while closed or showing a page. + pub(super) scene: Option<Box<Staged<S>>>, +} + +struct SceneSession<'a, S: 'static> { + stage: &'a mut TypedStage<S>, + real: &'a mut S, +} + +impl<S: 'static> SceneOps for SceneSession<'_, S> { + fn real(&self) -> &dyn Any { self.real } + + fn keep(&mut self) { + if let (Some(keep), Some(scene)) = (self.stage.keep, self.stage.scene.as_deref()) { + keep(&scene.state, self.real); + } + } + + fn clear_scene(&mut self) { + self.stage.scene = None; + } + + fn build_scene(&mut self, selected: usize, variant: usize, clock: crate::SceneClock) { + let (_, f) = self.stage.scenes[selected]; + let (init, fresh) = (self.stage.init, self.stage.fresh); + let variant = self.stage.scene_variant(selected, variant); + let state = crate::with_scene_clock(clock, || { + let mut s = fresh.map_or_else(init, |fresh| fresh(self.real)); + f(&mut s); + if let Some(variant) = variant { variant(&mut s); } + s + }); + self.stage.scene = Some(Box::new(Staged::new(state))); + } + + fn trigger_scene(&mut self, selected: usize, key: char, now: f64) { + if let Some(scene) = &mut self.stage.scene + && let Some((_, t)) = self.stage.triggers.iter().find(|(s, t)| *s == selected && t.key == key) + { + scene.script.push((now, t.queued())); + } + } +} + +/// A window's playground while it runs. +pub(crate) struct Live<S: 'static> { + pub(super) core: LiveCore, + pub(super) stage: TypedStage<S>, + /// `compose` and `apply_requests`, which the runtime reaches through these so that only an app + /// that makes a playground (`Live::new`) links the playground's views and requests. + compose: fn(&Self, &S, fn(&S, &mut Cx<S>) -> El, &mut Cx<S>, (f32, f32)) -> El, + apply_requests: fn(&mut Self, f64, &mut S) -> bool, + /// Trait-object casts initialized only in `Live::new`, keeping `Live<S>: PlaygroundDriver` + /// dead-code-eliminated for apps without a playground. + as_driver: fn(&Self) -> &dyn crate::runtime::driver::PlaygroundDriver, + as_driver_mut: fn(&mut Self) -> &mut dyn crate::runtime::driver::PlaygroundDriver, +} + +impl<S: 'static> std::ops::Deref for Live<S> { + type Target = LiveCore; + #[inline(always)] + fn deref(&self) -> &LiveCore { &self.core } +} + +impl<S: 'static> Live<S> { + pub(super) fn new(playground: Playground<S>, spec: &crate::AppSpec<S>, menu: bool) -> Self { + let Playground { pages, triggers, sides, stages, sizes, shortcut, bar, enabled: _, scenes: show, fresh, keep, variants, typing, dark: app_dark, folds, widths, group_order } = playground; + let scene_names: Vec<&'static str> = spec.scenes.iter().map(|(name, _)| *name).collect(); + let mut live_pages = Vec::with_capacity(pages.len()); + let mut page_specs = Vec::with_capacity(pages.len()); + for Page { name, kind } in pages { + match kind { + Kind::Live(view) => { live_pages.push(Some(view)); page_specs.push((name, None)); } + Kind::Own(own) => { live_pages.push(None); page_specs.push((name, Some(own))); } + } + } + let mut typed_triggers = Vec::new(); + let mut trigger_meta = Vec::new(); + for (name, t) in triggers { + if let Some(s) = open::resolve_scene(&scene_names, name) { + trigger_meta.push((s, t.key, t.label)); + typed_triggers.push((s, t)); + } + } + let mut typed_sides = Vec::new(); + let mut side_keys = Vec::new(); + for (name, side) in sides { + if let Some(s) = open::resolve_scene(&scene_names, name) { + if matches!(side, Side::Keys(..)) { side_keys.push(s); } + typed_sides.push((s, side)); + } + } + let stages = stages.into_iter().filter_map(|(name, stage)| Some((open::resolve_scene(&scene_names, name)?, stage))).collect(); + let mut typed_variants = Vec::new(); + let mut variant_meta = Vec::new(); + for (name, label, apply) in variants { + if let Some(s) = open::resolve_scene(&scene_names, name) { + variant_meta.push((s, label)); + typed_variants.push((s, apply)); + } + } + let core = LiveCore::new(LiveInit { + scenes: scene_names, + pages: page_specs, + triggers: trigger_meta, + side_keys, + stages, + variants: variant_meta, + sizes, + shortcut, + menu, + bar, + show, + folds, + widths, + group_order, + }); + Live { + core, + stage: TypedStage { + live_pages, + triggers: typed_triggers, + sides: typed_sides, + variants: typed_variants, + init: spec.init, + fresh, + keep, + typing, + app_dark, + scenes: spec.scenes, + poll: spec.poll, + scene: None, + }, + compose: Self::compose, + apply_requests: Self::apply_requests, + as_driver: |live| live, + as_driver_mut: |live| live, + } + } + + /// The open scene's stage. + pub(super) fn scene(&self) -> Option<&Staged<S>> { + self.stage.scene.as_deref() + } + + pub(super) fn live_page(&self) -> Option<&View<S>> { + let i = self.core.selected.checked_sub(self.core.scene_count)?; + self.stage.live_pages.get(i)?.as_ref() + } + + /// The window's root: the app's view above the bar, or the playground around its stage. + pub(crate) fn view(&self, app: &S, view: fn(&S, &mut Cx<S>) -> El, cx: &mut Cx<S>, viewport: (f32, f32)) -> El { + (self.compose)(self, app, view, cx, viewport) + } + + /// Applies the requests handlers made since the last commit; true when anything changed. + pub(crate) fn apply(&mut self, clock: f64, real: &mut S) -> bool { (self.apply_requests)(self, clock, real) } + + fn apply_requests(&mut self, clock: f64, real: &mut S) -> bool { + let mut ops = SceneSession { stage: &mut self.stage, real }; + self.core.apply_requests(clock, &mut ops) + } + + pub(crate) fn driver(&self) -> &dyn crate::runtime::driver::PlaygroundDriver { + (self.as_driver)(self) + } + + pub(crate) fn driver_mut(&mut self) -> &mut dyn crate::runtime::driver::PlaygroundDriver { + (self.as_driver_mut)(self) + } +} + +impl<S: 'static> crate::runtime::driver::PlaygroundDriver for Live<S> { + fn is_open(&self) -> bool { self.core.is_open() } + fn is_shortcut(&self, ev: &KeyEvent) -> bool { self.core.is_shortcut(ev) } + fn request(&mut self, requests: Vec<Request>) { self.core.request(requests); } + fn has_pending(&self) -> bool { self.core.has_pending() } + fn pending_swaps_stage(&self) -> bool { self.core.pending_swaps_stage() } + fn pending_replays_only(&self) -> bool { self.core.pending_replays_only() } + fn polls(&self) -> bool { Live::polls(self) } + fn poll_stage(&mut self, clock: f64, tx: &mut Tx) -> bool { Live::poll_stage(self, clock, tx) } + fn take_pressed(&mut self) -> Vec<KeyEvent> { self.core.take_pressed() } + fn pressing(&self) -> bool { self.core.pressing } + fn set_pressing(&mut self, pressing: bool) { self.core.pressing = pressing; } + fn app_time_scale(&self) -> f32 { self.core.app_time_scale } + fn set_app_time_scale(&mut self, scale: f32) { self.core.app_time_scale = scale; } + fn region(&self) -> Region { self.core.region() } + fn region_at(&self, x: f32, width: f32) -> Region { self.core.region_at(x, width) } + fn saw_focus(&self, focus: Option<&str>) -> bool { self.core.saw_focus(focus) } + fn moved(&mut self, moved: Moved) -> bool { self.core.moved(moved) } + fn nav(&self, ev: &KeyEvent, region: Region) -> Nav { self.core.nav(ev, region) } + fn side_key(&mut self, ev: &KeyEvent, tx: &mut Tx) -> bool { Live::side_key(self, ev, tx) } + fn clear_filter(&mut self) -> bool { self.core.clear_filter() } + fn first_shown(&self) -> Option<usize> { self.core.first_shown() } + fn first_match(&self) -> Option<usize> { self.core.first_match() } +} diff --git a/app/vendor/rune/crates/rune/src/playground/nav.rs b/app/vendor/rune/crates/rune/src/playground/nav.rs new file mode 100644 index 0000000..53fd1c0 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/playground/nav.rs @@ -0,0 +1,140 @@ +//! The open playground's keys. + +use super::*; + +impl LiveCore { + /// What `ev` does in the open playground, with the keyboard in `region`. The stage's keys + /// are its own, so it only gets here from the list or the side column. + pub(crate) fn nav(&self, ev: &KeyEvent, region: Region) -> Nav { + let m = ev.mods; + // Control on macOS, the Windows key elsewhere: never the playground's. + let other = m.alt || (cfg!(target_os = "macos") && m.ctrl) || (cfg!(not(target_os = "macos")) && m.logo); + if !self.is_open() || other || region == Region::Stage { return Nav::Pass; } + let letter = match &ev.key { + Key::Text(t) if !m.cmd => t.chars().next().filter(|_| t.chars().count() == 1).map(|c| c.to_ascii_lowercase()), + _ => None, + }; + let in_side = region == Region::Side; + if in_side { + match ev.key { + Key::Tab | Key::Escape | Key::Left => return Nav::OutOfSide, + Key::Up if !m.cmd => return Nav::SideStep(-1), + Key::Down if !m.cmd => return Nav::SideStep(1), + _ => {} + } + // Digits pick a variant only here, where the keyboard is on the story's controls. + if let Some(request) = letter.and_then(|c| self.variant_key(c)) { return Nav::Request(request); } + } + // In the side column, Space presses the focused control. + if let Some(c) = letter && !(in_side && c == ' ') && let Some(request) = self.trigger_request(c) { + return Nav::Request(request); + } + if in_side { return Nav::Pass; } + if letter == Some('/') { return Nav::Filter; } + match self.list_nav(ev, letter) { + // The list's arrows and Return, even where they do nothing. Every other key it + // leaves, ⌘-chords and digits included, is the stage's. + Nav::Pass if !m.cmd && matches!(ev.key, Key::Up | Key::Down | Key::Left | Key::Right | Key::Enter) => Nav::Stay, + nav => nav, + } + } + + /// Keys in the story list: along it, into and out of groups, and on to the other columns. + fn list_nav(&self, ev: &KeyEvent, letter: Option<char>) -> Nav { + let m = ev.mods; + match ev.key { + Key::Tab if m.shift => return Nav::IntoStage, + Key::Tab => return Nav::IntoSide, + _ => {} + } + let rows = self.rows(); + let is_story = |r: &Row| matches!(r, Row::Story(..)); + let Some(&last) = rows.iter().rev().find(|r| is_story(r)) else { return Nav::Pass }; + let at = rows.iter().position(|r| match (*r, self.header) { + (Row::Header(g, ..), Some(h)) => g == h, + (Row::Story(i, _), None) => i == self.selected, + _ => false, + }); + let n = rows.len(); + let first = rows.iter().position(is_story).unwrap_or(0); + let to = match (&ev.key, letter, self.header) { + // Filtering, ↑ from the first match goes back up to the field. + (Key::Up, _, _) if !m.cmd && !self.query().is_empty() && at.is_none_or(|a| a <= first) => return Nav::Filter, + (Key::Up, _, _) if m.cmd => rows.iter().copied().find(is_story).unwrap_or(last), + (Key::Down, _, _) if m.cmd => last, + (_, _, _) if m.cmd => return Nav::Pass, + (Key::Up, _, _) => rows[at.map_or(0, |a| (a + n - 1) % n)], + (Key::Down, _, _) => rows[at.map_or(0, |a| (a + 1) % n)], + // J and K skip the headers. + (_, Some(c @ ('j' | 'k')), _) => { + let step = if c == 'j' { 1 } else { n - 1 }; + let from = at.unwrap_or(0); + (1..=n).map(|k| rows[(from + k * step) % n]).find(is_story).unwrap_or(last) + } + // ← folds an open group, else goes up to the group around. + (Key::Left, _, Some(g)) if !self.is_folded(g) && self.query().is_empty() => return Nav::Request(Request::Fold(g, Some(true))), + (Key::Left, _, Some(g)) => match Self::parent(g) { + Some(up) => return Nav::Request(Request::Header(up)), + None => return Nav::Pass, + }, + (Key::Left, _, None) if self.selected < self.count() => return Nav::Request(Request::Header(self.group(self.selected))), + // → opens a folded group, else steps into it. + (Key::Right, _, Some(g)) if !m.shift && self.is_folded(g) => return Nav::Request(Request::Fold(g, Some(false))), + (Key::Right, _, Some(_)) if !m.shift => match at.and_then(|a| rows.get(a + 1)) { + Some(&next) if !matches!(next, Row::Header(_, _, d) if d == 0) => next, + _ => return Nav::Pass, + }, + (Key::Enter, _, Some(g)) => return Nav::Request(Request::Fold(g, None)), + (Key::Right, _, None) if !m.shift => return Nav::IntoSide, + _ => return Nav::Pass, + }; + Nav::Request(match to { + Row::Header(g, ..) => Request::Header(g), + Row::Story(i, _) => Request::Select(i), + }) + } + + /// Whether the open story's side controls take keys: `Story::side_keys`, or + /// `Playground::side_keys` for a scene. + pub(super) fn side_keys(&self) -> bool { + self.open && self.stories.get(self.selected).is_some_and(|s| s.side_keys) + } + + /// Keys while the keyboard is on an own-state story's side controls that take keys. + pub(super) fn side_key_own(&mut self, ev: &KeyEvent, tx: &mut Tx) -> bool { + let took = self.own_slot_mut(self.selected) + .and_then(|own| Some((own.story.as_ref(), own.stage.as_mut()?))) + .is_some_and(|(story, stage)| story.side_key(stage.as_mut(), ev, tx)); + took || ev.key == Key::Left + } + + /// What the open story's trigger on `c` asks for, as its letter does: R replays. + pub(super) fn trigger_request(&self, c: char) -> Option<Request> { + self.triggers().iter().any(|(k, _)| *k == c).then_some(if c == 'r' { Request::Replay } else { Request::Trigger(c) }) + } + + /// [`Self::trigger_request`] for tests, panicking with the story's triggers when missing. + pub(super) fn require_trigger(&self, key: char) -> Request { + assert!(self.open, "the playground isn't open: call Runtime::open_playground first"); + self.trigger_request(key).unwrap_or_else(|| { + let keys: Vec<String> = self.triggers().iter().map(|(k, label)| format!("{k:?} ({label})")).collect(); + panic!("{:?} has no trigger on {key:?}; it has: {}", self.path(self.selected), keys.join(", ")); + }) + } +} + +impl<S: 'static> Live<S> { + /// Keys while the keyboard is on the open story's side controls that take keys: true when + /// the story's hook took `ev`, or it's ←, which stays rather than leaving. + pub(crate) fn side_key(&mut self, ev: &KeyEvent, tx: &mut Tx) -> bool { + if !self.core.open { return false; } + if let Some(scene) = &mut self.stage.scene { + let key = self.stage.sides.iter().find_map(|(s, side)| match side { + Side::Keys(_, key) if *s == self.core.selected => Some(key), + _ => None, + }); + return key.is_some_and(|key| key(&mut scene.state, ev, tx)) || ev.key == Key::Left; + } + self.core.side_key_own(ev, tx) + } +} diff --git a/app/vendor/rune/crates/rune/src/playground/open.rs b/app/vendor/rune/crates/rune/src/playground/open.rs new file mode 100644 index 0000000..a6c5d3c --- /dev/null +++ b/app/vendor/rune/crates/rune/src/playground/open.rs @@ -0,0 +1,116 @@ +//! Finding a story by its path, name or slug, and opening the playground on it: one lookup for +//! `--playground NAME --variant V`, [`Tx::open_playground_at`] and `Runtime::open_playground`. + +use super::*; + +/// A story's path as a link takes it: lowercased, with each run of characters that aren't +/// letters or digits (the `/` between group and name, spaces, punctuation) made one `-`, and +/// none at either end. `"Timeline/Send"` is `"timeline-send"` and `"Lists/Many devices"` is +/// `"lists-many-devices"`. Letters outside ASCII are kept, lowercased. The rule won't change, +/// so a link stays good while the story keeps its path. Every lookup by name accepts a slug: +/// `--playground timeline-send`, [`Tx::open_playground_at`] and `Runtime::open_playground`. +pub fn slug(path: &str) -> String { + let mut out = String::with_capacity(path.len()); + for c in path.chars() { + if c.is_alphanumeric() { + out.extend(c.to_lowercase()); + } else if !out.is_empty() && !out.ends_with('-') { + out.push('-'); + } + } + if out.ends_with('-') { out.pop(); } + out +} + +/// Matches `name` against `scenes` as [`LiveCore::find`] does, logging if none matches. +pub(super) fn resolve_scene(scenes: &[&'static str], name: &str) -> Option<usize> { + let exact = |i: &usize| scenes[*i] == name || split(scenes[*i], "").1 == name; + let loose = |i: &usize| scenes[*i].eq_ignore_ascii_case(name) || split(scenes[*i], "").1.eq_ignore_ascii_case(name); + let slugged = |i: &usize| slug(scenes[*i]) == name; + let at = (0..scenes.len()).find(exact).or_else(|| (0..scenes.len()).find(loose)).or_else(|| (0..scenes.len()).find(slugged)); + if at.is_none() { eprintln!("rune: the playground has a trigger, side column or stage for {name:?}, which isn't one of AppSpec::scenes"); } + at +} + +impl LiveCore { + /// The listed story called `name`: its path or just its name, matching case only if need + /// be, or its path's [`slug`]. Where two match, the first in the list. + pub(super) fn find(&self, name: &str) -> Option<usize> { + self.find_in(name, &self.order) + } + + /// [`LiveCore::find`] among `ids`, in order. + pub(super) fn find_in(&self, name: &str, ids: &[usize]) -> Option<usize> { + let exact = |i: &&usize| self.path(**i) == name || self.name(**i) == name; + let loose = |i: &&usize| self.path(**i).eq_ignore_ascii_case(name) || self.name(**i).eq_ignore_ascii_case(name); + let slugged = |i: &&usize| slug(self.path(**i)) == name; + ids.iter().find(exact).or_else(|| ids.iter().find(loose)).or_else(|| ids.iter().find(slugged)).copied() + } + + /// Checks that story `name` (else the one selected) is there, and picks `variant` of it. + pub(super) fn open_at(&mut self, name: Option<&str>, variant: Option<&str>) -> Result<(), String> { + if let Some(name) = name && self.find(name).is_none() { + let names: Vec<_> = self.order.iter().map(|&i| self.path(i)).collect(); + return Err(format!("no story {name:?} in the playground; it has: {}", names.join(", "))); + } + match variant { + Some(variant) => self.pick(name, variant), + None => Ok(()), + } + } + + /// Validates `--playground`/`--variant` at launch and queues the initial open request. + pub(super) fn queue_launch(&mut self, open: Option<Option<String>>, variant: Option<String>) { + if let Some(name) = open { + self.open_at(name.as_deref(), variant.as_deref()).unwrap_or_else(|e| crate::tooling::die(&e)); + self.pending.push(Request::Open(name)); + } + } + + /// [`Tx::open_playground_at`]'s story, once checked. An app can't stop over a bad link, so + /// what's wrong is logged: an unknown story opens the list where it was, and a story's + /// unknown variant opens the story on the variant it was on. + pub(super) fn resolve(&mut self, name: &str, variant: Option<&str>) -> Option<String> { + let Err(e) = self.open_at(Some(name), variant) else { return Some(name.to_owned()) }; + eprintln!("rune: Tx::open_playground_at: {e}"); + self.find(name).map(|_| name.to_owned()) + } + + /// Opens the playground, on story `name` if it's there; open already, it moves there. + pub(super) fn open_story(&mut self, name: Option<&str>, ops: &mut dyn SceneOps) { + let at = name.and_then(|n| self.find(n)); + if !self.open || at.is_some() { + // Open already on a scene, `select` keeps its stage before replacing it. + if !self.open { self.open = true; } + if let Some(i) = at.or(self.folds.start.then_some(self.selected)) { self.reveal(i); } + self.select(at.unwrap_or(self.selected), ops); + } + } +} + +impl Tx { + /// Shows [`App::playground`](crate::App::playground) on `story` (its `"Group/Name"` path, + /// its name, or its path's [`slug`]), on `variant` (by number from 1, or by name) if given, + /// as `--playground NAME --variant V` does. From `App::on_open_url` a link opens straight + /// onto the story, at launch too: the hook runs before the first frame, which then shows + /// the story with no frame of the app first. A story it doesn't have is logged and opens the + /// list instead; an unknown variant is logged and the story opens as it would without one. + /// Where the playground doesn't show, nothing happens, as with [`Tx::open_playground`]. + pub fn open_playground_at(&mut self, story: &str, variant: Option<&str>) { + self.playground.push(Request::OpenAt(story.to_owned(), variant.map(str::to_owned))); + } + + /// Makes the open story's stage again and runs its `'r'` trigger, as R does. After + /// [`Tx::open_playground_at`] in the same handler it applies to the story that opens. + /// With the playground closed, nothing happens. + pub fn replay_playground(&mut self) { + self.playground.push(Request::Replay); + } + + /// Runs the open story's trigger on `key`, as its letter or its side-column button does; + /// `'r'` is [`Tx::replay_playground`]. A key the story has no trigger on does nothing. + pub fn playground_trigger(&mut self, key: char) { + let key = key.to_ascii_lowercase(); + self.playground.push(if key == 'r' { Request::Replay } else { Request::Trigger(key) }); + } +} diff --git a/app/vendor/rune/crates/rune/src/playground/press_tests.rs b/app/vendor/rune/crates/rune/src/playground/press_tests.rs new file mode 100644 index 0000000..29a4c9b --- /dev/null +++ b/app/vendor/rune/crates/rune/src/playground/press_tests.rs @@ -0,0 +1,125 @@ +//! Steps that press keys with [`Play::press`]. +use super::*; +use crate::motion_gate::Run; +use crate::{App, AppSpec, Env, Mods, Runtime}; + +const SIZE: (f32, f32) = (1200.0, 700.0); + +/// A list whose selection ↓ moves, scrolling the new row in. +#[derive(Default)] +struct List { + selected: usize, + keys: Vec<(Key, Mods)>, +} + +static SCENES: &[(&str, fn(&mut List))] = &[("Keys/Pressed", |_| {}), ("Keys/Stepped", |_| {})]; + +fn list(s: &List, _: &mut Cx<List>) -> El { + let rows = (0..30).map(|i| el().key(format!("row{i}")).w_full().h(40.0).fill(if i == s.selected { Color::WHITE } else { Color::BLACK })); + col().w_full().h_full().child(col().key("list").w_full().h(200.0).scroll(ScrollSpec { stick_bottom: false }).child(col().key("rows").w_full().children(rows))) +} + +/// Selects the next row and puts it at the list's bottom: from row 4, a 40 pt scroll that +/// brings row 5 into view. +fn down(s: &mut List, tx: &mut Tx) { + s.selected += 1; + tx.scroll_key_to(format!("row{}", s.selected), 160.0); +} + +fn runtime(scene: &str) -> Runtime<List> { + let mut spec = AppSpec::new("press", SIZE, || List { selected: 4, ..List::default() }, list); + spec.scenes = SCENES; + spec.on_key = Some(|s, ev, tx| { + s.keys.push((ev.key.clone(), ev.mods)); + if ev.key != Key::Down { return false; } + down(s, tx); + true + }); + let playground = Playground::new() + .enabled(true) + .trigger("Keys/Pressed", 'r', "Press ↓", |_, play| play.after(0.5, |_, play| play.press(Key::Down))) + .trigger("Keys/Pressed", 's', "Press ⇧↓", |_, play| play.press(KeyEvent { key: Key::Down, mods: Mods { shift: true, ..Mods::default() } })) + .trigger("Keys/Stepped", 'r', "Step down", |_, play| play.after(0.5, |s, play| down(s, play))); + let mut rt = App::new(spec).playground(playground).headless_runtime(SIZE, Env::new(false, 1.0)); + rt.frame(0.0); + rt.open_playground(scene, None); + rt +} + +fn focused(rt: &Runtime<List>) -> Option<String> { + rt.elements().into_iter().find(|e| e.focused).and_then(|e| e.key) +} + +fn stage(rt: &Runtime<List>) -> &List { + rt.playground_state().expect("the scene's state") +} + +#[test] +fn a_step_presses_a_key_the_stage_hears_as_input() { + let mut r = Run::new(runtime("Keys/Pressed"), 120.0); + let story = r.rt.hooks.playground.as_ref().unwrap().selected; + // The list's filter has the keyboard, so a person's ↓ would go to the list. + r.rt.key(Key::Text("/".into()).into()); + r.step(); + assert_eq!(focused(&r.rt).as_deref(), Some(FILTER)); + while stage(&r.rt).keys.is_empty() { + assert!(r.rec.frames < 120, "the step never pressed"); + r.step(); + } + assert_eq!(stage(&r.rt).keys, [(Key::Down, Mods::default())], "the scene's on_key hears it"); + assert_eq!(stage(&r.rt).selected, 5); + let frame = r.rec.frames - 1; + assert_eq!(r.rec.inputs.last().map(|i| i.0), Some(frame), "the frame it lands on is input"); + assert_eq!(focused(&r.rt).as_deref(), Some(FILTER), "the filter keeps the keyboard"); + let p = r.rt.hooks.playground.as_ref().unwrap(); + assert_eq!((p.selected, p.controls.filter.text.as_str()), (story, ""), "neither the list nor its filter took it"); + r.rt.playground_trigger('s'); + assert_eq!(stage(&r.rt).keys[1], (Key::Down, Mods { shift: true, ..Mods::default() }), "with its modifiers, on the step's own frame"); +} + +/// The jumps the gate finds in the list when `scene`'s replay moves its selection. +fn jumps(scene: &str) -> Vec<String> { + let mut r = Run::new(runtime(scene), 120.0); + r.idle(0.25); + r.step(); + r.play(1.0); + assert_eq!(stage(&r.rt).selected, 5, "the replay ran"); + r.finish().into_iter().filter(|f| ["jump", "offset-jump", "jerk"].contains(&f.kind) && f.element.contains("row")).map(|f| f.to_string()).collect() +} + +#[test] +fn a_scroll_a_pressed_key_asks_for_isnt_reported_as_input_less() { + let stepped = jumps("Keys/Stepped"); + assert!(stepped.iter().any(|f| f.starts_with("offset-jump") && f.contains("list/rows")), "a step that scrolls on its own teleports the rows: {stepped:#?}"); + let pressed = jumps("Keys/Pressed"); + assert!(pressed.is_empty(), "{pressed:#?}"); +} + +#[derive(Default)] +struct Long; + +fn long(_: &Long, _: &mut Cx<Long>) -> El { + let rows = (0..40).map(|i| el().key(format!("line{i}")).w_full().h(40.0)); + col().w_full().h_full().child(col().key("page").w_full().h(300.0).scroll(ScrollSpec { stick_bottom: false }).child(col().w_full().children(rows))) +} + +/// How far the scroll view keyed `key` has carried its content, from its first child. +fn scrolled(rt: &Runtime<List>, key: &str) -> f32 { + let all = rt.elements(); + let at = all.iter().position(|e| e.key.as_deref() == Some(key)).unwrap_or_else(|| panic!("no {key}")); + all.iter().find(|e| e.parent == Some(at)).expect("its content").scrolled[1] +} + +#[test] +fn a_pressed_page_key_pages_the_stage_not_the_story_list() { + let story = Story::new("Pages/Long", Long::default, long).trigger('r', "Page down", |_, play| play.after(0.1, |_, play| play.press(Key::PageDown))); + // Enough stories that the list overflows too, and comes first in the tree. + let playground = (0..60).fold(Playground::new().enabled(true), |p, i| p.story(Story::new(Box::leak(format!("Filler/Story {i}").into_boxed_str()), Long::default, long))).story(story); + let mut rt = App::new(AppSpec::new("press", SIZE, List::default, list)).playground(playground).headless_runtime(SIZE, Env::new(false, 1.0)); + rt.frame(0.0); + rt.open_playground("Pages/Long", None); + let list_at = scrolled(&rt, "playground-list"); + for _ in 0..30 { rt.frame(1.0 / 60.0); } + assert_eq!(scrolled(&rt, "page"), 270.0, "a page is 90% of the stage's view"); + assert_eq!(scrolled(&rt, "playground-list"), list_at, "the story list stays put"); +} diff --git a/app/vendor/rune/crates/rune/src/playground/real_tests.rs b/app/vendor/rune/crates/rune/src/playground/real_tests.rs new file mode 100644 index 0000000..9ac3265 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/playground/real_tests.rs @@ -0,0 +1,148 @@ +use super::*; + +fn open(rt: &mut Runtime<Real>, name: &str) { + let name = name.to_string(); + rt.update(move |_, tx| tx.playground.push(Request::Open(Some(name)))); + rt.frame(DT); +} + +fn copy(real: &Real) -> Real { + Real { count: real.count, ..Real::default() } +} + +#[test] +fn fresh_scenes_start_from_the_real_state_on_each_choice_and_replay() { + let mut rt = runtime_with(base().fresh(copy), None, true); + rt.state.count = 7; + open(&mut rt, "holding"); + assert_eq!(shows(&rt, "count"), "count 7", "from the real state, then the scene fn"); + open(&mut rt, "big"); + assert_eq!(shows(&rt, "count"), "count 100", "the scene fn still applies"); + rt.state.count = 9; + open(&mut rt, "holding"); + assert_eq!(shows(&rt, "count"), "count 9"); + rt.state.count = 11; + letter(&mut rt, "r"); + assert_eq!(shows(&rt, "count"), "count 11", "R starts from it again"); + assert_eq!(rt.state.count, 11, "and never writes to it"); +} + +#[test] +fn a_story_from_real_derives_its_state_when_it_shows_and_on_replay() { + let story = Story::from_real("Lab/Derived", |r: &Real| Lab { ticks: r.count, presses: 0 }, lab); + let mut rt = runtime_with(base().story(story), None, true); + rt.state.count = 3; + open(&mut rt, "Derived"); + assert_eq!(shows(&rt, "lab"), "ticks 3 presses 0"); + rt.state.count = 4; + letter(&mut rt, "j"); + letter(&mut rt, "k"); + assert_eq!(shows(&rt, "lab"), "ticks 3 presses 0", "kept while the playground's open"); + letter(&mut rt, "r"); + assert_eq!(shows(&rt, "lab"), "ticks 4 presses 0", "derived again on R"); +} + +#[test] +#[should_panic(expected = "derives from another app state")] +fn a_story_from_another_apps_state_is_refused() { + let _ = base().story(Story::from_real("Lab/Other", |l: &Lab| Lab { ticks: l.ticks, presses: 0 }, lab)); +} + +#[test] +fn keep_copies_the_stage_back_before_a_replay_a_switch_and_back() { + let keep = base().fresh(copy).keep(|stage, real| real.count = stage.count); + let mut rt = runtime_with(keep, None, true); + rt.state.count = 5; + open(&mut rt, "Still"); + tap(&mut rt, "inc"); + assert_eq!((shows(&rt, "count"), rt.state.count), ("count 6".into(), 5), "tuned on the stage only"); + escape(&mut rt); + letter(&mut rt, "r"); + assert_eq!((shows(&rt, "count"), rt.state.count), ("count 6".into(), 6), "kept, and the replay starts from it"); + tap(&mut rt, "inc"); + escape(&mut rt); + letter(&mut rt, "j"); + assert_eq!(rt.state.count, 7, "kept on a switch"); + letter(&mut rt, "k"); + assert_eq!(shows(&rt, "count"), "count 7", "which the next scene starts from"); + tap(&mut rt, "inc"); + escape(&mut rt); + escape(&mut rt); + assert_eq!(rt.state.count, 8, "and on Back"); + assert_eq!(shows(&rt, "count"), "count 8"); +} + +#[test] +fn a_fresh_stage_shares_the_real_waker_and_a_wake_from_another_thread_reaches_its_poll() { + use std::sync::atomic::{AtomicUsize, Ordering}; + let mut spec = AppSpec::new("playground", (800.0, 500.0), Real::default, view); + spec.scenes = SCENES; + spec.setup = Some(|s, waker| { + s.waker = Some(waker); + s.inbox = Some(Arc::default()); + }); + spec.poll = Some(|s, _, _| { + let got: Vec<u32> = s.inbox.as_ref().map(|i| i.lock().unwrap().drain(..).collect()).unwrap_or_default(); + s.count += got.iter().sum::<u32>(); + !got.is_empty() + }); + // The stage keeps the real waker and makes its own inbox, as a worker it starts would. + let fresh = base().fresh(|real| Real { waker: real.waker.clone(), inbox: Some(Arc::default()), ..Real::default() }); + let wakes = Arc::new(AtomicUsize::new(0)); + let counted = wakes.clone(); + let mut rt = crate::tooling::runtime_for(&spec, (spec.init)(), spec.size, Env::new(false, 1.0), Arc::new(move || { counted.fetch_add(1, Ordering::SeqCst); })); + attach(&mut rt, Some(fresh), &spec, Some(Some("Still".into())), None, false); + rt.frame(0.0); + rt.frame(DT); + let stage = &rt.hooks.playground.as_ref().unwrap().scene().expect("a scene's stage").state; + let (waker, inbox) = (stage.waker.clone().expect("the real waker"), stage.inbox.clone().unwrap()); + let before = wakes.load(Ordering::SeqCst); + std::thread::spawn(move || { + inbox.lock().unwrap().push(41); + waker(); + }) + .join() + .unwrap(); + assert_eq!(wakes.load(Ordering::SeqCst), before + 1, "the wake reached the window's waker"); + rt.frame(DT); + assert_eq!(shows(&rt, "count"), "count 41", "and the next frame's poll of the stage took it"); + assert_eq!(rt.state.count, 0, "the real state's inbox is its own"); +} + +fn compare(stage: &Real, real: &Real, _: &mut Cx<Real>) -> El { + col() + .child(text(format!("stage {} real {}", stage.count, real.count)).key("compare")) + .child(el().key("keep").size(40.0, 20.0).on_press_tx(|_: &mut Real, tx: &mut Tx| tx.keep_playground())) +} + +#[test] +fn a_side_view_reads_the_real_state_and_keep_writes_the_preview_back() { + let playground = base().fresh(copy).keep(|stage, real| real.count = stage.count).side_real("Still", compare); + let mut rt = runtime_with(playground, None, true); + rt.state.count = 3; + open(&mut rt, "Still"); + assert_eq!(shows(&rt, "compare"), "stage 3 real 3"); + tap(&mut rt, "inc"); + assert_eq!(shows(&rt, "compare"), "stage 4 real 3", "the stage previews; the app's own choice shows beside it"); + let generation = rt.hooks.playground.as_ref().unwrap().generation; + tap(&mut rt, "keep"); + assert_eq!(shows(&rt, "compare"), "stage 4 real 4"); + assert_eq!((rt.state.count, rt.hooks.playground.as_ref().unwrap().generation), (4, generation), "kept, and the stage stays"); +} + +#[test] +fn a_replay_while_closed_makes_no_stage_for_the_next_open_to_keep() { + let keep = base().fresh(copy).keep(|stage, real| real.count = stage.count); + let mut rt = runtime_with(keep, None, true); + open(&mut rt, "big"); + rt.update(|_, tx| tx.close_playground()); + rt.frame(DT); + rt.state.count = 5; + rt.update(|_, tx| tx.replay_playground()); + rt.frame(DT); + assert!(rt.hooks.playground.as_ref().unwrap().scene().is_none(), "closed, a replay does nothing"); + rt.update(|_, tx| tx.toggle_playground()); + rt.frame(DT); + assert_eq!(rt.state.count, 5, "opening keeps nothing back from a stage nobody saw"); + assert_eq!(shows(&rt, "count"), "count 100", "and the story opens fresh"); +} diff --git a/app/vendor/rune/crates/rune/src/playground/region.rs b/app/vendor/rune/crates/rune/src/playground/region.rs new file mode 100644 index 0000000..9c9bd0e --- /dev/null +++ b/app/vendor/rune/crates/rune/src/playground/region.rs @@ -0,0 +1,126 @@ +//! Which of the playground's three columns has the keyboard: the story list, the stage or the +//! side column. One at a time, and only it gets keys: the list its arrows, letters and triggers, +//! the side column its controls, variants' digits and `side_keys` hook, the stage the story's +//! own keys. A click in a column, or focus moving into one, gives it the keyboard. +//! +//! [`Keyboard`] is the one place that remembers it: the column, whether focus is on the slot +//! that takes the story's keys, and the focus it last took. + +use super::*; + +/// A column of the open playground, as the keyboard sees it. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(crate) enum Region { + #[default] + List, + Stage, + Side, +} + +/// What gives a column the keyboard. +pub(crate) enum Moved { + /// A press, or a key that asks for a column: `region` takes the keyboard, and `seen` is the + /// focus it was made with (`None` when nothing is focused), so the column holds until focus + /// moves again. + Give { region: Region, seen: Option<String> }, + /// A key the stage's steps pressed holds `region` for its route. Focus was set aside for + /// it, so the focus it last saw stays as it was. + Hold(Region), + /// The route is over: `region` takes the keyboard again, and `back` is the focus it puts + /// back. `None` when the key left focus where its handler chose: the next look at focus + /// gives the keyboard to the column it landed in. + Resume { region: Region, back: Option<String> }, + /// Focus moved to `focus`, into `region`: none when it left every column or only a hover + /// moved it, which takes no keys. + Focus { focus: Option<String>, region: Option<Region> }, + /// Focus moved onto the open story's slot (`true`) or off it. + Slot(bool), + /// The playground closed: the list has the keyboard. + Closed, +} + +/// Which column has the keyboard, whether focus is on the open story's slot, and the focus it +/// last took as a move: one that only a hover moved (a row under the pointer) is passed over +/// rather than taken as one. The slot goes by focus alone: a click elsewhere that leaves focus +/// on it, as a link's does, leaves it its keys and its mark. +#[derive(Clone, Default)] +pub(crate) struct Keyboard { + region: Region, + slot_focused: bool, + seen: Option<String>, +} + +impl Keyboard { + pub(crate) fn region(&self) -> Region { + self.region + } + + /// Whether focus is on the open story's slot, whose view marks what its keys move. + pub(crate) fn slot_focused(&self) -> bool { + self.slot_focused + } + + /// Whether `focus` is the focus it last took, so a look at it has nothing to do. + pub(crate) fn saw(&self, focus: Option<&str>) -> bool { + self.seen.as_deref() == focus + } + + /// Applies `moved`; true when the column or the slot changed. + pub(crate) fn step(&mut self, moved: Moved) -> bool { + let before = (self.region, self.slot_focused); + match moved { + Moved::Give { region, seen } => { + self.region = region; + self.seen = seen; + } + Moved::Hold(region) => self.region = region, + Moved::Resume { region, back } => { + self.region = region; + if back.is_some() { self.seen = back; } + } + // Focus leaving every column keeps the one that has the keyboard, and a hover takes + // no keys: neither moves a column. + Moved::Focus { focus, region } if self.seen != focus => { + self.seen = focus; + if let Some(region) = region { self.region = region; } + } + Moved::Focus { .. } => {} + Moved::Slot(slot) => self.slot_focused = slot, + Moved::Closed => self.region = Region::List, + } + (self.region, self.slot_focused) != before + } +} + +impl LiveCore { + pub(crate) fn region(&self) -> Region { + self.keyboard.region() + } + + /// Whether the keyboard is on the side column's slot, whose view marks what its keys move. + pub(super) fn side_active(&self) -> bool { + self.keyboard.slot_focused() + } + + /// Whether `focus` is the focus the keyboard last took. + pub(crate) fn saw_focus(&self, focus: Option<&str>) -> bool { + self.keyboard.saw(focus) + } + + /// Moves the keyboard; true when that changed what the columns draw. + pub(crate) fn moved(&mut self, moved: Moved) -> bool { + self.keyboard.step(moved) + } + + /// The column at window point `x`, in a window `width` wide. + pub(crate) fn region_at(&self, x: f32, width: f32) -> Region { + let (sidebar_w, side_w) = self.widths(width); + if x < sidebar_w + 1.0 { + Region::List + } else if x >= width - side_w { + Region::Side + } else { + Region::Stage + } + } +} diff --git a/app/vendor/rune/crates/rune/src/playground/region_tests.rs b/app/vendor/rune/crates/rune/src/playground/region_tests.rs new file mode 100644 index 0000000..bbf19ad --- /dev/null +++ b/app/vendor/rune/crates/rune/src/playground/region_tests.rs @@ -0,0 +1,371 @@ +use super::*; + +/// The column as the old code kept it. Its own type, so the reference shares nothing with the +/// conversions it checks. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum OldRegion { + List, + Stage, + Side, +} + +/// The caches this replaced, transcribed from the old code: the column, `side_active` beside +/// it, and `region_seen`. It calls nothing in production. +#[derive(Clone, Debug)] +struct Old { + region: OldRegion, + side_active: bool, + region_seen: Option<&'static str>, +} + +impl Old { + fn set_region(&mut self, region: OldRegion) -> bool { + std::mem::replace(&mut self.region, region) != region + } + + fn see_focus(&mut self, focused: Option<&'static str>) -> bool { + if self.region_seen == focused { return false; } + self.region_seen = focused; + true + } + + fn set_side_active(&mut self, active: bool) -> bool { + std::mem::replace(&mut self.side_active, active) != active + } + + /// `give_region`. + fn give_region(&mut self, region: OldRegion, focused: Option<&'static str>) { + self.see_focus(focused); + self.set_region(region); + } + + /// `sync_region`, `at` being the column of the focused element when there is one. + fn sync_region(&mut self, focused: Option<&'static str>, hover: bool, at: Option<OldRegion>) { + if !self.see_focus(focused) || hover { return; } + let Some(region) = at else { return }; + self.set_region(region); + } + + /// `Live::close`. + fn close(&mut self) { + self.region = OldRegion::List; + } +} + +/// A focusable element: its column, whether it's the side column's slot, and whether the pointer +/// can light it. The slot has no `focus_highlight`, so a hover never lands on it. +#[derive(Clone, Copy, Debug, PartialEq)] +struct Node { + path: &'static str, + column: OldRegion, + slot: bool, + highlight: bool, +} + +const LIST_ROW: Node = Node { path: "list/row", column: OldRegion::List, slot: false, highlight: true }; +const SIDE_ROW: Node = Node { path: "side/row", column: OldRegion::Side, slot: false, highlight: true }; +const SLOT: Node = Node { path: "side/slot", column: OldRegion::Side, slot: true, highlight: false }; +const FIELD: Node = Node { path: "stage/field", column: OldRegion::Stage, slot: false, highlight: false }; + +/// An event as the runtime meets it. +#[derive(Clone, Copy, Debug)] +enum Feed { + /// `set_focus`, which reports the slot. + Focus(Option<Node>), + /// The pointer lights or leaves the focused row, which reports nothing. + Hover(bool), + /// `sync_region`, as a commit or a key looks at focus. + Look, + /// A press in a column, or a key that asks for one. It leaves focus where it is. + Press(OldRegion), + /// The playground closes. + Close, + /// A step's key starts its route, setting aside focus outside the stage. + RouteStart, + /// Its route ends, putting focus back if the key left none. + RouteEnd, +} + +const FEEDS: [Feed; 14] = [ + Feed::Focus(None), + Feed::Focus(Some(LIST_ROW)), + Feed::Focus(Some(SIDE_ROW)), + Feed::Focus(Some(SLOT)), + Feed::Focus(Some(FIELD)), + Feed::Hover(true), + Feed::Hover(false), + Feed::Look, + Feed::Press(OldRegion::List), + Feed::Press(OldRegion::Stage), + Feed::Press(OldRegion::Side), + Feed::Close, + Feed::RouteStart, + Feed::RouteEnd, +]; + +/// What a route remembers while it runs, for each side. +#[derive(Clone, Copy)] +struct Route { + old: OldRegion, + new: Region, + aside: Option<(Node, bool)>, +} + +/// How many of the sequences the walk has to reach it reached. +#[derive(Default)] +struct Reached { + retained_clicks: u64, + restored_unseen: u64, + routes_moving_focus: u64, + closes_on_the_slot: u64, +} + +/// The focus both sides read, the keyboard, and the old caches. +#[derive(Clone)] +struct Sim { + keys: Keyboard, + old: Old, + focus: Option<Node>, + hovered: bool, + route: Option<Route>, + /// A route blurred the focus it had set aside and then put it back, which reports nothing: + /// the old flag stayed false with focus on the slot, whose keys it still took. + old_flag_stale: bool, +} + +fn new_region(region: OldRegion) -> Region { + match region { + OldRegion::List => Region::List, + OldRegion::Stage => Region::Stage, + OldRegion::Side => Region::Side, + } +} + +impl Sim { + fn new() -> Self { + Self { + keys: Keyboard::default(), + old: Old { region: OldRegion::List, side_active: false, region_seen: None }, + focus: None, + hovered: false, + route: None, + old_flag_stale: false, + } + } + + fn path(&self) -> Option<&'static str> { + self.focus.map(|n| n.path) + } + + /// `on_side_keys`. + fn on_slot(&self) -> bool { + !self.hovered && self.focus.is_some_and(|n| n.slot) + } + + /// Whether the runtime can meet `feed` now. A route runs inside one key, so the pointer and + /// a close wait for it. + fn allows(&self, feed: Feed) -> bool { + let routing = self.route.is_some(); + match feed { + Feed::Focus(_) | Feed::Look => true, + Feed::Hover(lit) => !routing && self.hovered != lit && self.focus.is_some_and(|n| n.highlight), + Feed::Press(_) => true, + Feed::Close | Feed::RouteStart => !routing, + Feed::RouteEnd => routing, + } + } + + /// Feeds `feed` to both sides; true when the keyboard says its region changed. + fn feed(&mut self, feed: Feed, reached: &mut Reached) -> bool { + match feed { + Feed::Focus(next) => { + if self.path() != next.map(|n| n.path) { self.hovered = false; } + self.focus = next; + self.old_flag_stale = false; + let slot = self.on_slot(); + self.old.set_side_active(slot); + self.keys.step(Moved::Slot(slot)) + } + Feed::Hover(lit) => { + self.hovered = lit; + false + } + Feed::Look => { + let at = if self.hovered { None } else { self.focus }; + self.old.sync_region(self.path(), self.hovered, self.focus.map(|n| n.column)); + if self.keys.saw(self.path()) { return false; } + self.keys.step(Moved::Focus { + focus: self.path().map(str::to_owned), + region: at.map(|n| new_region(n.column)), + }) + } + Feed::Press(region) => { + if region == OldRegion::Stage && self.focus == Some(SLOT) { reached.retained_clicks += 1; } + self.old.give_region(region, self.path()); + self.keys.step(Moved::Give { region: new_region(region), seen: self.path().map(str::to_owned) }) + } + Feed::Close => { + if self.focus == Some(SLOT) { reached.closes_on_the_slot += 1; } + self.old.close(); + self.keys.step(Moved::Closed) + } + Feed::RouteStart => { + let aside = self.focus.filter(|n| n.column != OldRegion::Stage).map(|n| (n, self.hovered)); + self.route = Some(Route { old: self.old.region, new: self.keys.region(), aside }); + if aside.is_some() { + self.focus = None; + self.hovered = false; + } + self.old.set_region(OldRegion::Stage); + self.keys.step(Moved::Hold(Region::Stage)) + } + Feed::RouteEnd => { + let route = self.route.take().expect("a route is running"); + let back = route.aside.filter(|_| self.focus.is_none()); + if route.aside.is_some() && back.is_none() { reached.routes_moving_focus += 1; } + if back.is_some_and(|(n, _)| self.old.region_seen != Some(n.path)) { reached.restored_unseen += 1; } + self.old.set_region(route.old); + if let Some((node, _)) = back { self.old.see_focus(Some(node.path)); } + let mut changed = self.keys.step(Moved::Resume { region: route.new, back: back.map(|(n, _)| n.path.to_owned()) }); + if let Some((node, hovered)) = back { + self.focus = Some(node); + self.hovered = hovered; + self.old_flag_stale = self.old.side_active != self.on_slot(); + assert!(!self.old_flag_stale || self.on_slot(), "the one difference keeps a mark, never drops one"); + changed |= self.keys.step(Moved::Slot(self.on_slot())); + } + changed + } + } + } + + /// The keyboard against the old caches, by hand so no production conversion checks itself. + /// They differ in one approved way: the mark on a slot a route blurred and put back. + fn check(&self, trail: &[Feed]) { + let region = match self.keys.region() { + Region::List => OldRegion::List, + Region::Stage => OldRegion::Stage, + Region::Side => OldRegion::Side, + }; + assert_eq!(region, self.old.region, "{trail:?}: the column"); + assert_eq!(self.keys.slot_focused(), self.old.side_active || self.old_flag_stale, "{trail:?}: what looks active"); + assert!(self.keys.saw(self.old.region_seen), "{trail:?}: the focus last taken, {:?}", self.old.region_seen); + } +} + +fn walk(sim: &Sim, depth: usize, trail: &mut Vec<Feed>, reached: &mut Reached) -> u64 { + let mut checked = 0; + for feed in FEEDS { + if !sim.allows(feed) { continue; } + let mut next = sim.clone(); + let before = (next.keys.region(), next.keys.slot_focused()); + let changed = next.feed(feed, reached); + trail.push(feed); + assert_eq!(changed, before != (next.keys.region(), next.keys.slot_focused()), "{trail:?}: says whether it changed"); + next.check(trail); + checked += 1; + if depth > 1 { checked += walk(&next, depth - 1, trail, reached); } + trail.pop(); + } + checked +} + +#[test] +fn any_order_of_keyboard_events_leaves_the_column_slot_and_seen_focus_the_old_caches_did() { + let mut reached = Reached::default(); + let checked = walk(&Sim::new(), 7, &mut Vec::new(), &mut reached); + assert!(checked > 1_000_000, "walked {checked}"); + assert!(reached.retained_clicks > 0, "a stage click that keeps the slot's focus"); + assert!(reached.restored_unseen > 0, "a route restoring a focus the keyboard hadn't seen"); + assert!(reached.routes_moving_focus > 0, "a route whose key moved focus"); + assert!(reached.closes_on_the_slot > 0, "a close with focus on the slot"); +} + +#[test] +fn a_look_at_focus_it_already_took_has_nothing_to_do() { + let mut keys = Keyboard::default(); + assert!(keys.saw(None)); + keys.step(Moved::Focus { focus: Some("side/row".into()), region: None }); + assert!(keys.saw(Some("side/row")), "a hover is taken as seen too, so it isn't looked at again"); + assert!(!keys.saw(None)); +} + +#[test] +fn a_clicked_column_keeps_the_keyboard_until_focus_moves() { + let mut keys = Keyboard::default(); + keys.step(Moved::Give { region: Region::Stage, seen: None }); + // A frame's look at focus, which nothing has: the stage keeps the keyboard. + keys.step(Moved::Focus { focus: None, region: None }); + assert_eq!(keys.region(), Region::Stage); + keys.step(Moved::Focus { focus: Some("list/story".into()), region: Some(Region::List) }); + assert_eq!(keys.region(), Region::List); +} + +#[test] +fn a_stage_click_that_keeps_the_slots_focus_keeps_its_mark() { + let mut keys = Keyboard::default(); + keys.step(Moved::Slot(true)); + keys.step(Moved::Give { region: Region::Side, seen: Some("side/slot".into()) }); + keys.step(Moved::Give { region: Region::Stage, seen: Some("side/slot".into()) }); + keys.step(Moved::Focus { focus: Some("side/slot".into()), region: Some(Region::Side) }); + assert_eq!(keys.region(), Region::Stage, "focus didn't move, so the click stands"); + assert!(keys.slot_focused(), "and the slot it left focused stays marked"); +} + +#[test] +fn the_slot_goes_by_focus_whatever_the_column() { + let mut keys = Keyboard::default(); + keys.step(Moved::Give { region: Region::Stage, seen: None }); + assert!(keys.step(Moved::Slot(true)), "a change redraws its view"); + assert_eq!(keys.region(), Region::Stage, "and moves no column"); + assert!(keys.step(Moved::Slot(false))); + assert!(!keys.slot_focused()); +} + +#[test] +fn a_route_that_moves_focus_gives_the_column_it_landed_in_the_keyboard() { + let mut keys = Keyboard::default(); + keys.step(Moved::Give { region: Region::List, seen: Some("list/story".into()) }); + // A key a step pressed holds the stage, then gives the list back: focus was set aside, so + // nothing new is seen. + keys.step(Moved::Hold(Region::Stage)); + keys.step(Moved::Resume { region: Region::List, back: None }); + assert_eq!(keys.region(), Region::List); + // The stage's key focused a control in the side column: the next look at focus gives it the + // keyboard, because the route restored nothing. + keys.step(Moved::Focus { focus: Some("side/variant".into()), region: Some(Region::Side) }); + assert_eq!(keys.region(), Region::Side, "focus where the route left it takes the keyboard"); +} + +#[test] +fn a_route_that_puts_focus_back_keeps_the_column_it_had() { + let mut keys = Keyboard::default(); + keys.step(Moved::Give { region: Region::Stage, seen: Some("stage/old".into()) }); + keys.step(Moved::Hold(Region::Stage)); + keys.step(Moved::Resume { region: Region::Stage, back: Some("stage/field".into()) }); + assert!(keys.saw(Some("stage/field")), "the focus it put back is the one it has seen"); + // The focus that came back isn't a move. + keys.step(Moved::Focus { focus: Some("stage/field".into()), region: Some(Region::List) }); + assert_eq!(keys.region(), Region::Stage); +} + +#[test] +fn closing_gives_the_list_the_keyboard_and_keeps_the_focus_it_saw() { + let mut keys = Keyboard::default(); + keys.step(Moved::Give { region: Region::Side, seen: Some("side/slot".into()) }); + assert!(keys.step(Moved::Closed)); + assert_eq!(keys.region(), Region::List); + assert!(keys.saw(Some("side/slot"))); +} + +#[test] +fn a_route_that_blurs_the_focus_it_puts_back_keeps_the_slots_mark() { + let mut sim = Sim::new(); + let mut reached = Reached::default(); + for feed in [Feed::Focus(Some(SLOT)), Feed::Press(OldRegion::Side), Feed::RouteStart, Feed::Focus(None), Feed::RouteEnd] { + sim.feed(feed, &mut reached); + } + assert_eq!(sim.focus, Some(SLOT)); + assert!(!sim.old.side_active, "the old flag stayed off with the slot focused"); + assert!(sim.keys.slot_focused(), "the keyboard follows focus"); +} diff --git a/app/vendor/rune/crates/rune/src/playground/scenes_tests.rs b/app/vendor/rune/crates/rune/src/playground/scenes_tests.rs new file mode 100644 index 0000000..4e944ba --- /dev/null +++ b/app/vendor/rune/crates/rune/src/playground/scenes_tests.rs @@ -0,0 +1,68 @@ +use super::*; + +#[test] +fn unwinding_a_scene_restores_the_enclosing_clock() { + use crate::{SceneClock, scene_clock, with_scene_clock}; + + let outer = SceneClock { now: 4.0, dt: 0.1 }; + with_scene_clock(outer, || { + let inner = SceneClock { now: 12.0, dt: 0.5 }; + let result = std::panic::catch_unwind(|| with_scene_clock(inner, || panic!("scene failed"))); + assert!(result.is_err()); + assert_eq!(scene_clock(), outer); + }); + assert_eq!(scene_clock(), SceneClock::default()); +} + +#[test] +fn the_scene_filter_lists_only_the_scenes_it_keeps() { + let mut rt = runtime_with(base().scenes(|name| name.contains('/')), Some(None), true); + assert!(find(&rt, "playground-item-0").is_none() && find(&rt, "playground-item-1").is_none()); + assert!(find(&rt, "playground-item-2").is_some(), "Motion/Still stays"); + assert_eq!(selected(&rt), 2, "the list starts at its first listed story"); + let live = rt.hooks.playground.as_ref().unwrap(); + assert_eq!(live.find("big"), None, "a hidden scene can't be chosen by name"); + assert_eq!(live.find("Still"), Some(2)); + letter(&mut rt, "k"); + assert_eq!(selected(&rt), 4, "K wraps past the hidden scenes"); +} + +fn count_up() -> Playground<Real> { + base().trigger("Still", 'r', "Count up", |s, play| { + s.count = 1; + play.after(0.5, |s, _| s.count = 2); + }) +} + +fn run_for(rt: &mut Runtime<Real>, secs: f64) { + for _ in 0..(secs * 60.0).round() as usize { rt.frame(1.0 / 60.0); } +} + +#[test] +fn choosing_a_scene_runs_its_r_trigger() { + let mut rt = runtime_with(count_up(), Some(Some("Still".into())), false); + rt.frame(DT); + assert_eq!(shows(&rt, "count"), "count 1", "it ran as the scene opened, headless included"); + run_for(&mut rt, 0.6); + assert_eq!(shows(&rt, "count"), "count 2", "and its steps follow on the clock"); + letter(&mut rt, "j"); + letter(&mut rt, "k"); + rt.frame(DT); + assert_eq!(shows(&rt, "count"), "count 1", "a scene starts afresh every time it's chosen"); +} + +#[test] +fn a_story_runs_its_r_trigger_when_its_state_is_made_not_when_it_comes_back() { + let mut rt = runtime(Some(Some("Fade".into()))); + rt.frame(DT); + assert_eq!(shows(&rt, "fade"), "[\"start\"]"); + run_for(&mut rt, 1.0); + assert_eq!(shows(&rt, "fade"), "[\"start\", \"half\", \"end\"]"); + letter(&mut rt, "j"); + letter(&mut rt, "k"); + run_for(&mut rt, 1.0); + assert_eq!(shows(&rt, "fade"), "[\"start\", \"half\", \"end\"]", "the kept state isn't played again"); + letter(&mut rt, "r"); + rt.frame(DT); + assert_eq!(shows(&rt, "fade"), "[\"start\"]", "R plays it once, not twice"); +} diff --git a/app/vendor/rune/crates/rune/src/playground/stage.rs b/app/vendor/rune/crates/rune/src/playground/stage.rs new file mode 100644 index 0000000..4d08185 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/playground/stage.rs @@ -0,0 +1,271 @@ +//! The stage: triggers and their steps on the logical clock, and the state handlers, keys and +//! polls reach while the playground is open. + +use super::*; + +/// A step a trigger runs, now or later on the logical clock, as a fn: see [`Play::after`]. +/// Triggers and `Play::after` take closures too. +pub type Step<X> = fn(&mut X, &mut Play<'_, X>); + +/// How the stage lays a story out, from [`Story::stage`] or [`Playground::stage`]. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +#[non_exhaustive] +pub enum Stage { + /// Sized as a window sizes its root, to the stage or the size picked beside it, in the + /// stage's middle. + #[default] + Center, + /// For content taller than the stage: laid out at the stage's width inside a 24 pt margin, + /// at its own height, from the top, and the stage scrolls. + Scroll, + /// Edge to edge across the whole stage, whatever size is picked beside it: for a story the + /// size of a window. + Fill, +} + +/// [`Stage::Scroll`]'s margin. +pub(super) const SCROLL_MARGIN: f32 = 24.0; + +/// A step queued on a stage, which runs once. +pub(super) type Queued<X> = Box<dyn FnOnce(&mut X, &mut Play<'_, X>)>; + +/// A story's view, or a scene's side view, of state `X`. +pub(super) type View<X> = Box<dyn Fn(&X, &mut Cx<X>) -> El>; + +/// What a trigger's steps get beside their state: the frame's [`Tx`] (`Play` derefs to it), +/// [`Play::after`] for the steps that follow and [`Play::press`] for keys. +pub struct Play<'a, X> { + tx: &'a mut Tx, + script: &'a mut Vec<(f64, Queued<X>)>, + pressed: &'a mut Vec<KeyEvent>, + now: f64, +} + +impl<X> Play<'_, X> { + /// Runs `step` `secs` after this one, on the runtime's logical clock. Times count from when + /// this step was due, not from the frame that ran it, so a replay runs the same every time, + /// headless runs included. + pub fn after(&mut self, secs: f64, step: impl FnOnce(&mut X, &mut Play<'_, X>) + 'static) { + self.script.push((self.now + secs.max(0.0), Box::new(step))); + } + + /// Drops every step still queued on this stage, a loop's next one included, so a trigger + /// can take over from a running one; steps queued after it in this step still run. The + /// stage's state and its running animations are left alone. + pub fn clear(&mut self) { + self.script.clear(); + } + + /// When this step was due, on the runtime's clock. + pub fn now(&self) -> f64 { + self.now + } + + /// Presses `key` on the stage, as a person would with the stage holding the keyboard: it + /// goes the way a real key does, through focus, `on_key` handlers and shortcuts, on the + /// frame this step runs, after the step's own changes. That frame counts as input, so a + /// scroll the key asks for moves as one under a hand does. Pass a [`Key`] for a plain key, + /// or a [`KeyEvent`] for one with modifiers. It stands in for a person's key in the app, so + /// a letter reaches the app and not the story's triggers: a step that wants another + /// trigger's behaviour calls that code directly. + pub fn press(&mut self, key: impl Into<KeyEvent>) { + self.pressed.push(key.into()); + } +} + +impl<X> std::ops::Deref for Play<'_, X> { + type Target = Tx; + fn deref(&self) -> &Tx { + self.tx + } +} + +impl<X> std::ops::DerefMut for Play<'_, X> { + fn deref_mut(&mut self) -> &mut Tx { + self.tx + } +} + +/// A trigger: a step on a single-letter key, shown as a button in the side column. +pub(super) struct Trigger<X> { + pub(super) key: char, + pub(super) label: &'static str, + pub(super) run: Rc<dyn Fn(&mut X, &mut Play<'_, X>)>, +} + +impl<X: 'static> Trigger<X> { + /// Its step, to queue. + pub(super) fn queued(&self) -> Queued<X> { + let run = self.run.clone(); + Box::new(move |x, play| { + // The trigger is input even though its step runs in the next frame's poll. + play.tx.asked_motion = true; + run(x, play); + }) + } +} + +/// Runs `view`, through the hot-patch table in a hot build, unless the frame is rebuilding from +/// the startup code after a patched view panicked. +pub(crate) fn call<X: 'static>(view: fn(&X, &mut Cx<X>) -> El, state: &X, cx: &mut Cx<X>) -> El { + #[cfg(feature = "hot")] + if !crate::hot::originals_only() { return subsecond::HotFn::current(view).call((state, cx)); } + view(state, cx) +} + +/// `view` as the playground keeps it: called through the hot-patch table in a hot build when +/// it's a fn or a closure that captures nothing, as [`call`] does. A closure that captures +/// runs as built: subsecond would take a pointer-sized one's captures for code. +pub(super) fn view<X: 'static>(view: impl Fn(&X, &mut Cx<X>) -> El + 'static) -> View<X> { + Box::new(move |x, cx| hot_view(&view, x, cx)) +} + +#[allow(unsafe_code)] +fn hot_view<X: 'static, F: Fn(&X, &mut Cx<X>) -> El + 'static>(view: &F, state: &X, cx: &mut Cx<X>) -> El { + #[cfg(feature = "hot")] + if !crate::hot::originals_only() { + if let Some(f) = (view as &dyn Any).downcast_ref::<fn(&X, &mut Cx<X>) -> El>() { return call(*f, state, cx); } + if size_of::<F>() == 0 { + // SAFETY: a zero-sized `F` has no bytes to copy; the copy is forgotten, not dropped. + let mut hot = subsecond::HotFn::current(unsafe { std::ptr::read(view) }); + let root = hot.call((state, cx)); + std::mem::forget(hot); + return root; + } + } + view(state, cx) +} + +pub(super) fn trigger<X>(key: char, label: &'static str, run: impl Fn(&mut X, &mut Play<'_, X>) + 'static) -> Trigger<X> { + let key = key.to_ascii_lowercase(); + assert!(!matches!(key, 'j' | 'k'), "J and K move between stories; give the {label:?} trigger another key"); + Trigger { key, label, run: Rc::new(run) } +} + +/// A trigger whose step takes just the [`Tx`]. +pub(super) fn trigger_tx<X>(key: char, label: &'static str, run: impl Fn(&mut X, &mut Tx) + 'static) -> Trigger<X> { + trigger(key, label, move |x: &mut X, play: &mut Play<'_, X>| run(x, play)) +} + +/// How far past the clock a step can be due and still run on this frame, in seconds. +const DUE_SLACK: f64 = 1e-6; + +/// A stage's state and its triggers' queued steps. +pub(super) struct Staged<X> { + pub(super) state: X, + pub(super) script: Vec<(f64, Queued<X>)>, +} + +impl<X> Staged<X> { + pub(super) fn new(state: X) -> Self { + Staged { state, script: Vec::new() } + } + + /// Runs the steps due by `t`, earliest first, each seeing the time it was due, adding the + /// keys they press to `pressed`. Asks for a frame when the next one is due. + pub(super) fn run(&mut self, t: f64, tx: &mut Tx, pressed: &mut Vec<KeyEvent>) -> bool { + // The clock is a running sum of frame times, so a step due on a frame can sit a rounding + // error past it; without the slack a replay later in the clock lands a frame late. + let t = t + DUE_SLACK; + let mut ran = false; + // Bounded, in case steps keep queueing more with no delay. + for _ in 0..64 { + let due = self.script.iter().enumerate().filter(|(_, (at, _))| *at <= t).min_by(|a, b| a.1.0.total_cmp(&b.1.0)).map(|(i, _)| i); + let Some(i) = due else { break }; + let (at, step) = self.script.remove(i); + step(&mut self.state, &mut Play { tx: &mut *tx, script: &mut self.script, pressed: &mut *pressed, now: at }); + ran = true; + } + if let Some(next) = self.script.iter().map(|(at, _)| *at).min_by(f64::total_cmp) { + tx.wake_after(Duration::from_secs_f64((next - t).max(0.0))); + } + ran + } +} + +impl LiveCore { + /// The keys this frame's steps pressed, to route to the stage, counting them in `played`. + pub(crate) fn take_pressed(&mut self) -> Vec<KeyEvent> { + self.played += self.pressed.len() as u64; + std::mem::take(&mut self.pressed) + } + + pub(super) fn own_polls(&self) -> bool { + self.own().is_some_and(|(own, stage)| own.polls(stage)) + } + + pub(super) fn poll_own(&mut self, t: f64, tx: &mut Tx) -> bool { + let Some(i) = self.selected.checked_sub(self.scene_count) else { return false }; + let Some(Some(own)) = self.owned.get_mut(i) else { return false }; + let Some(stage) = own.stage.as_mut() else { return false }; + own.story.poll(stage.as_mut(), t, tx, &mut self.pressed) + } +} + +impl<S: 'static> Live<S> { + /// What one handler call can reach: the stage's state, or the app's while closed (or on a + /// live page), and the playground's controls. + pub(crate) fn states<'a>(&'a mut self, app: &'a mut S) -> States<'a> { + let app = crate::runtime::handler_state(app); + if !self.core.open { return States::two(app, &mut self.core.controls); } + if let Some(scene) = &mut self.stage.scene { return States::two(&mut scene.state, &mut self.core.controls); } + let stage = self.core.selected.checked_sub(self.core.scene_count) + .and_then(|i| self.core.owned.get_mut(i)?.as_mut()) + .and_then(|own| Some(own.story.state(own.stage.as_mut()?.as_mut()))); + States::two(stage.unwrap_or(app), &mut self.core.controls) + } + + pub(crate) fn states_ref<'a>(&'a self, app: &'a S) -> StatesRef<'a> { + let app = crate::runtime::handler_state_ref(app); + if !self.core.open { return StatesRef::two(app, &self.core.controls); } + if let Some(scene) = &self.stage.scene { return StatesRef::two(&scene.state, &self.core.controls); } + let stage = self.core.selected.checked_sub(self.core.scene_count) + .and_then(|i| self.core.owned.get(i)?.as_ref()) + .and_then(|own| Some(own.story.state_ref(own.stage.as_deref()?))); + StatesRef::two(stage.unwrap_or(app), &self.core.controls) + } + + /// Whether the stage's `App::on_ime` hears the input method now: only while its column has + /// the keyboard, unless [`Playground::typing`] asks for every key: in the list, a letter may + /// be J, K or a trigger's. + pub(crate) fn stage_hears(&self, app: &S) -> bool { + !self.core.open || self.core.keyboard.region() == Region::Stage || self.typing(app) + } + + /// The state `AppSpec::on_key` gets: the stage's when it's an app state, none on a story + /// with its own. + pub(crate) fn key_state<'a>(&'a mut self, app: &'a mut S) -> Option<&'a mut S> { + if !self.core.open { return Some(app); } + if self.core.is_own_page() { return None; } + match &mut self.stage.scene { + Some(scene) => Some(&mut scene.state), + None => Some(app), + } + } + + /// Whether [`Playground::typing`] gives the stage's `on_key` every key first. + pub(crate) fn typing(&self, app: &S) -> bool { + let Some(typing) = self.stage.typing.filter(|_| self.core.open) else { return false }; + if let Some(scene) = &self.stage.scene { return typing(&scene.state); } + if self.core.is_own_page() { return false; } + typing(app) + } + + pub(crate) fn polls(&self) -> bool { + if !self.core.open { return false; } + if let Some(scene) = &self.stage.scene { return self.stage.poll.is_some() || !scene.script.is_empty(); } + self.core.own_polls() + } + + /// Polls the stage's state after the app's own poll: its due steps, then `AppSpec::poll` + /// for a scene or the story's own. The keys the steps press wait in [`LiveCore::take_pressed`]. + pub(crate) fn poll_stage(&mut self, t: f64, tx: &mut Tx) -> bool { + self.core.now = t; + if !self.core.open { return false; } + if let Some(scene) = &mut self.stage.scene { + let ran = scene.run(t, tx, &mut self.core.pressed); + return self.stage.poll.is_some_and(|poll| poll(&mut scene.state, t, tx)) || ran; + } + self.core.poll_own(t, tx) + } +} diff --git a/app/vendor/rune/crates/rune/src/playground/stage_tests.rs b/app/vendor/rune/crates/rune/src/playground/stage_tests.rs new file mode 100644 index 0000000..1d2ad4a --- /dev/null +++ b/app/vendor/rune/crates/rune/src/playground/stage_tests.rs @@ -0,0 +1,69 @@ +//! How each stage layout takes the size picked beside the stage. +use super::*; +use crate::{App, AppSpec, Env, Runtime}; + +const SIZE: (f32, f32) = (1200.0, 700.0); + +#[derive(Default)] +struct Real; + +fn real(_: &Real, _: &mut Cx<Real>) -> El { + text("the app") +} + +#[derive(Default)] +struct Card; + +fn plain(_: &Card, _: &mut Cx<Card>) -> El { + el().key("plain") +} + +fn tall(_: &Card, _: &mut Cx<Card>) -> El { + col().key("tall").w_full().children((0..40).map(|_| el().h(40.0))) +} + +fn screen(_: &Card, _: &mut Cx<Card>) -> El { + el().key("screen") +} + +fn runtime() -> Runtime<Real> { + let playground = Playground::<Real>::new() + .story(Story::new("Cards/Plain", Card::default, plain)) + .story(Story::new("Cards/Tall", Card::default, tall).stage(Stage::Scroll)) + .story(Story::new("Screens/Window", Card::default, screen).stage(Stage::Fill)) + .sizes(&[("Small", (300.0, 200.0))]); + App::new(AppSpec::new("stage", SIZE, Real::default, real)).playground(playground).headless_runtime(SIZE, Env::new(false, 1.0)) +} + +/// Opens `story` at the "Small" size; the width and height of the element keyed `key`. +fn size_at_small(story: &str, key: &str) -> (f32, f32) { + let mut rt = runtime(); + rt.open_playground(story, None); + rt.update(|_, tx| tx.playground.push(Request::Size(1))); + rt.frame(1.0 / 60.0); + let e = rt.elements().into_iter().find(|e| e.key.as_deref() == Some(key)).unwrap_or_else(|| panic!("no {key}")); + (e.rect[2], e.rect[3]) +} + +#[test] +fn a_centred_story_takes_the_picked_size() { + assert_eq!(size_at_small("Cards/Plain", "plain"), (300.0, 200.0)); +} + +#[test] +fn a_scrolling_story_takes_its_width_inside_the_margin() { + assert_eq!(size_at_small("Cards/Tall", "tall"), (300.0 - 2.0 * SCROLL_MARGIN, 1600.0)); +} + +#[test] +fn a_scrolling_story_keeps_the_root_handlers() { + let mut rt = runtime(); + rt.open_playground("Cards/Tall", None); + let root = rt.tree.app_root(); + assert_eq!(rt.tree.nodes[root].key.as_deref(), Some("tall"), "the story's root, not the margin around it"); +} + +#[test] +fn a_fill_story_keeps_the_whole_stage() { + assert_eq!(size_at_small("Screens/Window", "screen"), (SIZE.0 - SIDEBAR - SIDE - 2.0, SIZE.1)); +} diff --git a/app/vendor/rune/crates/rune/src/playground/story.rs b/app/vendor/rune/crates/rune/src/playground/story.rs new file mode 100644 index 0000000..7b05b5c --- /dev/null +++ b/app/vendor/rune/crates/rune/src/playground/story.rs @@ -0,0 +1,231 @@ +//! [`Story`], and [`OwnStory`], which erases its state type so the playground holds stories +//! of any. + +use super::*; + +/// A story with its own state, made by `init` when it first shows and kept, timers and +/// animations included, until the playground closes. R makes it again. Handlers built for `P` +/// change it. +/// +/// ```ignore +/// Story::new("Progress/Upload", Upload::new, upload_view) +/// .poll(Upload::tick) +/// .trigger('r', "Run", |u, play| play.after(0.5, |u, _| u.done = true)) +/// .trigger('f', "Finish", |u, _| u.done = true) +/// .side(upload_knobs) +/// ``` +pub struct Story<P: 'static> { + pub(super) name: &'static str, + init: Init<P>, + view: View<P>, + poll: Option<Box<dyn Fn(&mut P, f64, &mut Tx) -> bool>>, + frame: Option<(f32, f32)>, + stage: Stage, + triggers: Vec<Trigger<P>>, + /// Its view, told whether the keyboard is on it. + side: Option<SideView<P>>, + side_key: Option<SideKey<P>>, + variants: Vec<(&'static str, Variant<P>)>, +} + +impl<P: 'static> Story<P> { + /// `name` may be a `"Group/Name"` path. `init` and `view` may be closures, so a story + /// table can make its stories in a loop, each capturing its row. + pub fn new(name: &'static str, init: impl Fn() -> P + 'static, view: impl Fn(&P, &mut Cx<P>) -> El + 'static) -> Self { + Story { name, init: Init::New(Box::new(init)), view: stage::view(view), poll: None, frame: None, stage: Stage::Center, triggers: Vec::new(), side: None, side_key: None, variants: Vec::new() } + } + + /// A story whose state `derive` makes from the app's real state, each time it's made: when + /// it first shows, and on R. `S` is the playground's app state. + pub fn from_real<S: 'static>(name: &'static str, derive: impl Fn(&S) -> P + 'static, view: impl Fn(&P, &mut Cx<P>) -> El + 'static) -> Self { + let init = Init::Real(std::any::TypeId::of::<S>(), Box::new(move |real: &dyn Any| derive(real.downcast_ref().expect("checked by Playground::story")))); + Story { init, ..Story::new(name, || unreachable!(), view) } + } + + /// An overlay's view at its size, in a dashed frame over the stage (the overlay's clear + /// parts stay clear), with a state made by `init`. + pub fn overlay(name: &'static str, spec: &OverlaySpec<P>, init: impl Fn() -> P + 'static) -> Self { + Story { frame: Some(spec.size), ..Story::new(name, init, spec.view) } + } + + /// Called every frame while the story shows, as `AppSpec::poll` is, after its due steps: + /// true when it changed the state. + pub fn poll(mut self, poll: impl Fn(&mut P, f64, &mut Tx) -> bool + 'static) -> Self { + self.poll = Some(Box::new(poll)); + self + } + + /// A trigger: `key` (a letter, or `' '` for Space) runs `run` on the story's state, as its + /// button in the side column does. [`Play::after`] queues the steps that follow, on the + /// logical clock. An `'r'` trigger runs whenever the state is made: when the story first + /// shows, and on R, which always replays. J and K are taken. + pub fn trigger(mut self, key: char, label: &'static str, run: impl Fn(&mut P, &mut Play<'_, P>) + 'static) -> Self { + self.triggers.push(trigger(key, label, run)); + self + } + + /// [`Story::trigger`] with a step that takes just the [`Tx`], for a handler the app already + /// has: `.trigger_tx('s', "Send", Chat::send)` for `fn send(&mut Chat, &mut Tx)`. + pub fn trigger_tx(mut self, key: char, label: &'static str, run: impl Fn(&mut P, &mut Tx) + 'static) -> Self { + self.triggers.push(trigger_tx(key, label, run)); + self + } + + /// The app's own controls for this story, at the top of the side column, drawn from and + /// acting on its state: knobs, say. + pub fn side(mut self, view: impl Fn(&P, &mut Cx<P>) -> El + 'static) -> Self { + let view = stage::view(view); + self.side = Some(Box::new(move |p, _, cx| view(p, cx))); + self.side_key = None; + self + } + + /// [`Story::side`] for controls that take keys: knobs, say. → or Tab puts the keyboard on + /// them, and `view` gets `true` while it's there, to mark what the keys move. `key` gets + /// each key first, and returns true when it took it. Esc and Tab always leave, and ← + /// doesn't. Keys it leaves do what they do anywhere in the side column: ↑ and ↓ move on to + /// the controls below, and letters run triggers. + /// + /// ```ignore + /// .side_keys( + /// |s, active, cx| rune_knobs::inline(&s.knobs, GROUPS, style(cx), |s: &mut State| &mut s.knobs, active), + /// rune_knobs::side_key(GROUPS, |s: &mut State| &mut s.knobs), + /// ) + /// ``` + pub fn side_keys(mut self, view: impl Fn(&P, bool, &mut Cx<P>) -> El + 'static, key: impl Fn(&mut P, &KeyEvent, &mut Tx) -> bool + 'static) -> Self { + self.side = Some(Box::new(view)); + self.side_key = Some(Box::new(key)); + self + } + + /// How the stage lays it out: in its middle at the size picked beside it, by default; + /// [`Stage::Scroll`] for a page taller than the stage, or [`Stage::Fill`] for a story the + /// size of a window. + /// + /// ```ignore + /// Story::new("Settings/All", Settings::default, settings).stage(Stage::Scroll) + /// ``` + pub fn stage(mut self, stage: Stage) -> Self { + self.stage = stage; + self + } + + /// The app state `init` derives from, for [`Story::from_real`]. + pub(super) fn real(&self) -> Option<std::any::TypeId> { + match &self.init { + Init::New(_) => None, + Init::Real(t, _) => Some(*t), + } + } + + /// A variant: `apply` runs on the state after `init`. Keys 1 to 9, or its row in the side + /// column, switch between them, making the state again as R does. A story with variants + /// starts on its first. + pub fn variant(mut self, name: &'static str, apply: impl Fn(&mut P) + 'static) -> Self { + self.variants.push((name, Box::new(apply))); + self + } + + fn staged(stage: &dyn Any) -> &Staged<P> { + stage.downcast_ref().expect("a story's stage is its own") + } + + fn staged_mut(stage: &mut dyn Any) -> &mut Staged<P> { + stage.downcast_mut().expect("a story's stage is its own") + } +} + +/// How a story makes its state: from nothing, or from the real state, of the type named. +enum Init<P> { + New(Box<dyn Fn() -> P>), + Real(std::any::TypeId, Box<dyn Fn(&dyn Any) -> P>), +} + +/// A [`Story`] with its state type erased. Its stage is a `Staged<P>`. +pub(super) trait OwnStory { + /// A new stage, from the app's real state if the story derives from it. + fn init(&self, real: &dyn Any, variant: usize) -> Box<dyn Any>; + fn state<'a>(&self, stage: &'a mut dyn Any) -> &'a mut dyn Any; + fn state_ref<'a>(&self, stage: &'a dyn Any) -> &'a dyn Any; + fn view(&self, stage: &dyn Any, cx: &mut Cx<()>) -> El; + /// `active`: the keyboard is on it. + fn side(&self, stage: &dyn Any, active: bool, cx: &mut Cx<()>) -> Option<El>; + /// Whether its side controls take keys. + fn side_keys(&self) -> bool; + /// Offers `ev` to its side controls; true when they took it. + fn side_key(&self, stage: &mut dyn Any, ev: &KeyEvent, tx: &mut Tx) -> bool; + fn poll(&self, stage: &mut dyn Any, t: f64, tx: &mut Tx, pressed: &mut Vec<KeyEvent>) -> bool; + fn polls(&self, stage: &dyn Any) -> bool; + /// Queues the trigger on `key` at `now`; false when there's none. + fn trigger(&self, stage: &mut dyn Any, key: char, now: f64) -> bool; + /// Drops the steps still queued, so a story left part way doesn't burst on return. + fn stop(&self, stage: &mut dyn Any); + fn triggers(&self) -> Vec<(char, &'static str)>; + fn variants(&self) -> Vec<&'static str>; + fn frame(&self) -> Option<(f32, f32)>; + fn layout(&self) -> Stage; +} + +impl<P: 'static> OwnStory for Story<P> { + fn init(&self, real: &dyn Any, variant: usize) -> Box<dyn Any> { + let mut state = match &self.init { + Init::New(init) => init(), + Init::Real(_, derive) => derive(real), + }; + if let Some((_, apply)) = self.variants.get(variant) { apply(&mut state); } + Box::new(Staged::new(state)) + } + fn state<'a>(&self, stage: &'a mut dyn Any) -> &'a mut dyn Any { + &mut Self::staged_mut(stage).state + } + fn state_ref<'a>(&self, stage: &'a dyn Any) -> &'a dyn Any { + &Self::staged(stage).state + } + fn view(&self, stage: &dyn Any, cx: &mut Cx<()>) -> El { + let mut own = cx.retype::<P>(); + let root = (self.view)(&Self::staged(stage).state, &mut own); + cx.absorb(own); + root + } + fn side(&self, stage: &dyn Any, active: bool, cx: &mut Cx<()>) -> Option<El> { + let side = self.side.as_ref()?; + let mut own = cx.retype::<P>(); + let root = side(&Self::staged(stage).state, active, &mut own); + cx.absorb(own); + Some(root) + } + fn side_keys(&self) -> bool { + self.side_key.is_some() + } + fn side_key(&self, stage: &mut dyn Any, ev: &KeyEvent, tx: &mut Tx) -> bool { + self.side_key.as_ref().is_some_and(|key| key(&mut Self::staged_mut(stage).state, ev, tx)) + } + fn poll(&self, stage: &mut dyn Any, t: f64, tx: &mut Tx, pressed: &mut Vec<KeyEvent>) -> bool { + let stage = Self::staged_mut(stage); + let ran = stage.run(t, tx, pressed); + self.poll.as_ref().is_some_and(|poll| poll(&mut stage.state, t, tx)) || ran + } + fn polls(&self, stage: &dyn Any) -> bool { + self.poll.is_some() || !Self::staged(stage).script.is_empty() + } + fn trigger(&self, stage: &mut dyn Any, key: char, now: f64) -> bool { + let Some(t) = self.triggers.iter().find(|t| t.key == key) else { return false }; + Self::staged_mut(stage).script.push((now, t.queued())); + true + } + fn stop(&self, stage: &mut dyn Any) { + Self::staged_mut(stage).script.clear(); + } + fn triggers(&self) -> Vec<(char, &'static str)> { + self.triggers.iter().map(|t| (t.key, t.label)).collect() + } + fn variants(&self) -> Vec<&'static str> { + self.variants.iter().map(|(name, _)| *name).collect() + } + fn frame(&self) -> Option<(f32, f32)> { + self.frame + } + fn layout(&self) -> Stage { + self.stage + } +} diff --git a/app/vendor/rune/crates/rune/src/playground/testing.rs b/app/vendor/rune/crates/rune/src/playground/testing.rs new file mode 100644 index 0000000..5df1393 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/playground/testing.rs @@ -0,0 +1,99 @@ +//! The playground in an app's tests: [`App::headless_runtime`] attaches it, and +//! [`Runtime::open_playground`] opens a story the way `--playground NAME --variant V` does. + +use super::*; +use crate::{App, ElementInfo, Env, Runtime}; + +impl<S: 'static> App<S> { + /// A runtime for this app with no window, as a headless render builds it: the state from + /// `AppSpec::init` (or [`App::init`]'s closure), `AppSpec::setup` given a waker that does + /// nothing, the app's fonts, `poll` and `on_key`, and its [`App::playground`] attached, + /// closed, if it's enabled (by default, in debug builds, so in `cargo test`). Nothing is + /// read from the command line. Call [`Runtime::frame`] to build the first frame. + pub fn headless_runtime(mut self, size: (f32, f32), env: Env) -> Runtime<S> { + let playground = self.playground.take(); + let (chrome, titlebar, borderless) = (self.chrome, self.titlebar, self.window_options.borderless); + let (spec, state, _, runtime) = self.into_parts(None); + let mut rt = crate::tooling::runtime_for(&spec, state, size, env, std::sync::Arc::new(|| {})); + if let Some(playground) = playground.filter(Playground::is_enabled) { + rt.attach_playground(Live::new(playground, &spec, false)); + } + rt.headless_chrome(chrome, titlebar, borderless); + rt.configure(runtime); + rt + } +} + +impl<S: 'static> Runtime<S> { + /// Opens the playground at `story` (its `"Group/Name"` path, its name, or its path's + /// [`slug`](crate::playground::slug)), on `variant` (by number from 1, or by name) if given, + /// as `--playground NAME --variant V` and [`Tx::open_playground_at`] do. Like a handler's + /// [`Tx::open_playground`], it applies on a frame; this one takes + /// two that advance no time, so on return the stage is made and the steps its `'r'` + /// trigger runs at once have run. Steps queued with [`Play::after`] run as later frames + /// reach them. Opening the story already open makes a scene's stage again, and a story's + /// only with a variant. + /// + /// Panics without a playground (see [`App::headless_runtime`]), or when it has no such + /// story or variant, listing those it has. + pub fn open_playground(&mut self, story: &str, variant: Option<&str>) { + let live = self.hooks.playground.as_mut().expect(NO_PLAYGROUND); + live.core.open_at(Some(story), variant).unwrap_or_else(|e| panic!("{e}")); + self.settle_playground(Request::Open(Some(story.to_owned()))); + } + + /// Runs the open story's trigger on `key`, as its letter or its button in the side column + /// does: `'r'` makes the stage again and replays. As with [`Runtime::open_playground`], + /// its first step has run on return, and its [`Play::after`] steps wait for their frames. + /// + /// Panics when the playground isn't open, or its story has no trigger on `key`. + pub fn playground_trigger(&mut self, key: char) { + let live = self.hooks.playground.as_ref().expect("the playground isn't open: call Runtime::open_playground first"); + let request = live.core.require_trigger(key); + self.settle_playground(request); + } + + /// Queues `request` as a handler does, then takes two frames that advance no time: the + /// first applies it, the second runs the steps it made due now. + fn settle_playground(&mut self, request: Request) { + self.update(move |_, tx| tx.playground.push(request)); + self.frame(0.0); + self.frame(0.0); + } + + /// The open story's stage state: a scene's `S`, or a [`Story`]'s own state. `None` while + /// the playground is closed, on a [`Playground::page`] (whose stage is the real state, + /// `self.state`), or when `P` isn't the stage's type. `self.state` stays the app's real + /// state throughout. + pub fn playground_state<P: 'static>(&self) -> Option<&P> { + self.hooks.playground.as_ref()?.stage_state()?.downcast_ref() + } + + /// The element keyed or pathed `key` on the open story's stage, as of the last frame: its + /// rect, text, role and the rest. The playground's list and side column aren't searched; + /// [`Runtime::find`] and [`Runtime::elements`] see the whole window. + pub fn playground_element(&self, key: &str) -> Option<ElementInfo> { + if !self.hooks.playground.as_ref().is_some_and(|p| p.is_open()) { return None; } + let all = self.elements(); + let i = stage_element(&all, key)?; + all.into_iter().nth(i) + } +} + +const NO_PLAYGROUND: &str = "this runtime has no playground: build it with App::headless_runtime from an App whose App::playground is enabled"; + +/// The index in `all` of the element keyed or pathed `key` on the stage, not exiting. +pub(crate) fn stage_element(all: &[ElementInfo], key: &str) -> Option<usize> { + let named = |i: &usize| !all[*i].exiting && (all[*i].key.as_deref() == Some(key) || all[*i].path == key); + let in_stage = |i: &usize| std::iter::successors(Some(*i), |&j| all[j].parent).any(|j| all[j].key.as_deref().is_some_and(is_stage)); + (0..all.len()).filter(named).find(in_stage) +} + +impl<S: 'static> Live<S> { + /// The open stage's own state: a scene's, or a story's. + fn stage_state(&self) -> Option<&dyn Any> { + if !self.core.open { return None; } + if let Some(scene) = self.scene() { return Some(&scene.state); } + self.core.own().map(|(own, stage)| own.state_ref(stage)) + } +} diff --git a/app/vendor/rune/crates/rune/src/playground/tests.rs b/app/vendor/rune/crates/rune/src/playground/tests.rs new file mode 100644 index 0000000..f088dc5 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/playground/tests.rs @@ -0,0 +1,640 @@ +use std::sync::Arc; +use std::time::Duration; + +use super::*; +use crate::{AppSpec, Env, Key, KeyEvent, Mods, Runtime, TextEdit, TextStyle, Transition, text_input}; + +#[derive(Default)] +struct Real { + count: u32, + polls: u32, + holds_escape: bool, + field: TextEdit, + pastes: Vec<String>, + drops: usize, + focus: Vec<bool>, + waker: Option<crate::Waker>, + inbox: Option<Arc<std::sync::Mutex<Vec<u32>>>>, + typing: bool, + typed: String, +} + +fn view(s: &Real, _: &mut Cx<Real>) -> El { + col().w_full().h_full() + .on_paste(|s: &mut Real, text: &str, _| s.pastes.push(text.into())) + .on_drop_files(|s: &mut Real, files: &[std::path::PathBuf], _| s.drops += files.len()) + .on_window_focus(|s: &mut Real, focused, _| s.focus.push(focused)) + .child(text(format!("count {}", s.count)).key("count")) + .child(el().key("inc").size(40.0, 20.0).on_press(|s: &mut Real| s.count += 1)) + .child(text_input(&s.field, TextStyle::new(14.0, 400.0)).key("field").size(200.0, 24.0).on_edit(|s: &mut Real| &mut s.field)) +} + +static SCENES: &[(&str, fn(&mut Real))] = &[("big", |s| s.count = 100), ("holding", |s| s.holds_escape = true), ("Motion/Still", |_| {})]; + +#[derive(Default)] +struct Lab { + ticks: u32, + presses: u32, +} + +fn lab(p: &Lab, _: &mut Cx<Lab>) -> El { + col().w_full().h_full() + .child(text(format!("ticks {} presses {}", p.ticks, p.presses)).key("lab")) + .child(el().key("bump").size(40.0, 20.0).on_press(|p: &mut Lab| p.presses += 1)) +} + +/// A timer: one tick a second, by `wake_after` and the page's poll. +fn lab_poll(p: &mut Lab, t: f64, tx: &mut Tx) -> bool { + tx.wake_after(Duration::from_secs(1)); + let due = t.floor() as u32; + let changed = due != p.ticks; + p.ticks = due; + changed +} + +fn activity(s: &Real, _: &mut Cx<Real>) -> El { + text(format!("live {}", s.count)).key("activity") +} + +/// A story whose replay runs timed steps, logging when each was due after the first. +#[derive(Default)] +struct Fade { + t0: f64, + log: Vec<(&'static str, f64)>, +} + +fn fade(p: &Fade, _: &mut Cx<Fade>) -> El { + text(format!("{:?}", p.log.iter().map(|(n, _)| *n).collect::<Vec<_>>())).key("fade") +} + +fn fade_story() -> Story<Fade> { + Story::new("Motion/Fade", Fade::default, fade) + .trigger('r', "Fade in", |p, play| { + p.t0 = play.now(); + p.log.push(("start", 0.0)); + play.after(0.5, |p, play| { + p.log.push(("half", play.now() - p.t0)); + play.after(0.25, |p, play| p.log.push(("end", play.now() - p.t0))); + }); + }) + .trigger('f', "Finish", |p, _| p.log.push(("finish", 0.0))) +} + +fn base() -> Playground<Real> { + Playground::new() + .enabled(true) + .page("Live/Activity", activity) + .story(Story::new("Lab", Lab::default, lab).poll(lab_poll)) + .story(fade_story()) + .trigger("big", 'd', "Double", |s, _| s.count *= 2) +} + +fn runtime_in(open: Option<Option<String>>, windowed: bool) -> Runtime<Real> { + runtime_with(base(), open, windowed) +} + +fn runtime_with(playground: Playground<Real>, open: Option<Option<String>>, windowed: bool) -> Runtime<Real> { + let mut spec = AppSpec::new("playground", (800.0, 500.0), Real::default, view); + spec.scenes = SCENES; + spec.poll = Some(|s, _, _| { s.polls += 1; false }); + spec.on_key = Some(|s, ev, _| match &ev.key { + Key::Text(t) if s.typing => { + s.typed.push_str(t); + true + } + key => s.holds_escape && *key == Key::Escape, + }); + let mut rt = crate::tooling::runtime_for(&spec, (spec.init)(), spec.size, Env::new(false, 1.0), Arc::new(|| {})); + attach(&mut rt, Some(playground), &spec, open, None, windowed); + rt.frame(0.0); + rt +} + +fn runtime(open: Option<Option<String>>) -> Runtime<Real> { + runtime_in(open, true) +} + +#[test] +fn replacing_stage_cancels_titlebar_press() { + fn bar(_: &Real, _: &mut Cx<Real>) -> El { el().key("bar").size(120.0, 50.0).window_drag() } + let mut rt = runtime_with(base().page("First", bar).page("Second", bar), None, true); + rt.set_caption(Some(crate::titlebar::Caption::new(28.0))); + rt.open_playground("First", None); + let (x, y) = center(&rt, "bar"); + rt.secondary_down(x, y); + rt.open_playground("Second", None); + let (x, y) = center(&rt, "bar"); + rt.secondary_up(x, y); + assert_eq!(rt.take_window_menu(), None); + rt.secondary_down(x, y); + rt.secondary_up(x, y); + assert!(rt.take_window_menu().is_some(), "a fresh click opens the menu"); +} + +fn press_with(rt: &mut Runtime<Real>, key: Key, mods: Mods) { + rt.key(KeyEvent { key, mods }); + rt.frame(1.0 / 60.0); +} + +fn press(rt: &mut Runtime<Real>, key: Key) { + press_with(rt, key, Mods::default()); +} + +fn letter(rt: &mut Runtime<Real>, c: &str) { + press(rt, Key::Text(c.into())); +} + +fn selected(rt: &Runtime<Real>) -> usize { + rt.hooks.playground.as_ref().map_or(usize::MAX, |p| p.selected) +} + +fn header(rt: &Runtime<Real>) -> Option<&'static str> { + rt.hooks.playground.as_ref().and_then(|p| p.header) +} + +fn focused(rt: &Runtime<Real>) -> Option<String> { + rt.elements().into_iter().find(|e| e.focused).and_then(|e| e.key) +} + +fn find(rt: &Runtime<Real>, key: &str) -> Option<crate::ElementInfo> { + rt.elements().into_iter().find(|e| e.key.as_deref() == Some(key) && !e.exiting) +} + +fn shows(rt: &Runtime<Real>, key: &str) -> String { + find(rt, key).and_then(|e| e.text).unwrap_or_else(|| panic!("no {key}")) +} + +fn tap(rt: &mut Runtime<Real>, key: &str) { + let r = find(rt, key).unwrap_or_else(|| panic!("no {key}")).rect; + let (x, y) = (r[0] + r[2] * 0.5, r[1] + r[3] * 0.5); + rt.pointer_down(x, y); + rt.pointer_up(x, y); + rt.frame(1.0 / 60.0); +} + +fn escape(rt: &mut Runtime<Real>) { + rt.key(KeyEvent { key: Key::Escape, mods: Mods::default() }); + rt.frame(1.0 / 60.0); +} + +fn region(rt: &Runtime<Real>) -> Region { + rt.hooks.playground.as_ref().map_or(Region::List, |p| p.region()) +} + +fn is_open(rt: &Runtime<Real>) -> bool { + rt.hooks.playground.as_ref().is_some_and(|p| p.is_open()) +} + +#[test] +fn the_bar_shortens_the_app_and_opens_the_playground() { + let mut rt = runtime(None); + assert!(find(&rt, "playground-open").is_some()); + let bar = find(&rt, "playground-open").unwrap().rect; + assert!(bar[1] >= 500.0 - BAR, "the bar sits along the bottom edge"); + tap(&mut rt, "inc"); + assert_eq!(rt.state.count, 1); + tap(&mut rt, "playground-open"); + assert!(is_open(&rt)); + assert_eq!(shows(&rt, "count"), "count 100", "the first scene, from a fresh init"); +} + +#[test] +fn a_scene_gets_a_fresh_state_and_back_restores_the_real_one() { + let mut rt = runtime(None); + tap(&mut rt, "inc"); + rt.update(|_, tx| tx.open_playground()); + rt.frame(1.0 / 60.0); + tap(&mut rt, "inc"); + assert_eq!(shows(&rt, "count"), "count 101"); + tap(&mut rt, "playground-trigger-d"); + rt.frame(1.0 / 60.0); + assert_eq!(shows(&rt, "count"), "count 202", "triggers act on the stage"); + assert_eq!(rt.state.count, 1, "the real state is untouched"); + tap(&mut rt, "playground-back"); + assert!(!is_open(&rt)); + assert_eq!(shows(&rt, "count"), "count 1"); + assert!(find(&rt, "playground-trigger-d").is_none()); +} + +#[test] +fn the_stage_takes_escape_first() { + let mut rt = runtime(Some(Some("holding".into()))); + assert!(is_open(&rt)); + escape(&mut rt); + assert!(is_open(&rt), "the scene's on_key took Escape"); + tap(&mut rt, "playground-item-0"); + tap(&mut rt, "field"); + assert_eq!(rt.elements().into_iter().find(|e| e.focused).and_then(|e| e.key).as_deref(), Some("field")); + escape(&mut rt); + assert!(is_open(&rt), "the focused field took Escape"); + escape(&mut rt); + assert!(is_open(&rt) && region(&rt) == Region::List, "unhandled in the stage, Escape gives the list the keyboard"); + escape(&mut rt); + assert!(!is_open(&rt), "and from the list goes back"); + assert!(!rt.state.holds_escape); +} + +#[test] +fn a_page_keeps_its_own_state_and_timer_while_open() { + let mut rt = runtime(Some(Some("lab".into()))); + tap(&mut rt, "bump"); + tap(&mut rt, "bump"); + for _ in 0..70 { rt.frame(1.0 / 60.0); } + assert_eq!(shows(&rt, "lab"), "ticks 1 presses 2"); + tap(&mut rt, "playground-item-0"); + tap(&mut rt, "playground-item-4"); + assert_eq!(shows(&rt, "lab"), "ticks 1 presses 2", "kept across selections"); + tap(&mut rt, "playground-trigger-r"); + assert_eq!(rt.wake_deadline(), Some(rt.clock), "a new stage state asks for its first poll"); + rt.frame(1.0 / 60.0); + assert_eq!(shows(&rt, "lab"), "ticks 1 presses 0", "restart makes it again, polled at once"); + tap(&mut rt, "bump"); + escape(&mut rt); + escape(&mut rt); + rt.update(|_, tx| tx.open_playground()); + rt.frame(1.0 / 60.0); + assert!(shows(&rt, "lab").ends_with("presses 0"), "closing drops it"); +} + +#[test] +fn a_live_page_draws_and_changes_the_real_state() { + let mut rt = runtime(Some(Some("Activity".into()))); + assert_eq!(shows(&rt, "activity"), "live 0"); + rt.update(|s, _| s.count = 7); + rt.frame(1.0 / 60.0); + assert_eq!(shows(&rt, "activity"), "live 7"); +} + +#[test] +fn the_real_state_keeps_polling_while_open() { + let mut rt = runtime(Some(None)); + let before = rt.state.polls; + for _ in 0..5 { rt.frame(1.0 / 60.0); } + assert!(rt.state.polls >= before + 5); + let scene = rt.hooks.playground.as_ref().and_then(|p| p.scene()).map(|s| s.state.polls); + assert!(scene.is_some_and(|n| n >= 5), "the scene polls too"); +} + +#[test] +fn without_the_bar_the_app_lays_out_untouched() { + let spec = AppSpec::new("playground", (800.0, 500.0), Real::default, view); + let mut rt = crate::tooling::runtime_for(&spec, (spec.init)(), spec.size, Env::new(false, 1.0), Arc::new(|| {})); + rt.frame(0.0); + let plain: Vec<_> = rt.elements().into_iter().map(|e| (e.path, e.rect)).collect(); + let mut rt = crate::tooling::runtime_for(&spec, (spec.init)(), spec.size, Env::new(false, 1.0), Arc::new(|| {})); + attach(&mut rt, Some(Playground::new().enabled(true).bar(false)), &spec, None, None, true); + rt.frame(0.0); + let barless: Vec<_> = rt.elements().into_iter().map(|e| (e.path, e.rect)).collect(); + assert_eq!(plain, barless); +} + +#[test] +fn keys_walk_the_stories_in_their_groups_order() { + let mut rt = runtime(Some(None)); + // Scenes: big, holding; Motion: Still (a scene), Fade; Live: Activity; Pages: Lab. + for (i, group) in [(0, true), (1, false), (2, true), (5, false), (3, true), (4, true)] { + assert_eq!(find(&rt, &format!("playground-group-{i}")).is_some(), group, "story {i}"); + } + // Headers are rows too; on one, the stage keeps its story. + let walk = [(Key::Down, 1, None), (Key::Down, 1, Some("Motion")), (Key::Down, 2, None), (Key::Down, 5, None), (Key::Down, 5, Some("Live")), (Key::Down, 3, None), (Key::Up, 3, Some("Live")), (Key::Up, 5, None)]; + for (key, at, on) in walk { + press(&mut rt, key); + assert_eq!((selected(&rt), header(&rt)), (at, on)); + } + letter(&mut rt, "j"); + assert_eq!((selected(&rt), header(&rt)), (3, None), "J skips headers"); + letter(&mut rt, "k"); + assert_eq!((selected(&rt), header(&rt)), (5, None)); + let cmd = Mods { cmd: true, ..Mods::default() }; + press_with(&mut rt, Key::Down, cmd); + assert_eq!(selected(&rt), 4, "⌘↓ goes to the last story"); + press_with(&mut rt, Key::Up, cmd); + assert_eq!(selected(&rt), 0, "⌘↑ to the first"); + press(&mut rt, Key::Up); + assert_eq!(header(&rt), Some("Scenes")); + press(&mut rt, Key::Up); + assert_eq!(selected(&rt), 4, "and ↑ wraps"); +} + +#[test] +fn a_replay_runs_its_steps_on_the_logical_clock_the_same_every_time() { + let mut logs = Vec::new(); + for (start, dt) in [(0.0, 1.0 / 60.0), (3.3, 1.0 / 24.0)] { + let mut rt = runtime(Some(Some("fade".into()))); + rt.frame(start); + letter(&mut rt, "f"); + rt.frame(dt); + letter(&mut rt, "r"); + // A second R part way starts over rather than queueing another run. + for _ in 0..4 { rt.frame(dt); } + letter(&mut rt, "r"); + rt.frame(dt); + assert_eq!(shows(&rt, "fade"), "[\"start\"]", "the replay made the state again"); + for _ in 0..(1.0 / dt) as usize { rt.frame(dt); } + let log = rt.hooks.playground.as_ref().and_then(|p| p.own()).map(|(own, stage)| { + own.state_ref(stage).downcast_ref::<Fade>().unwrap().log.iter().map(|(n, t)| (*n, (t * 1e6).round() as i64)).collect::<Vec<_>>() + }); + logs.push(log.unwrap()); + } + assert_eq!(logs[0], [("start", 0), ("half", 500_000), ("end", 750_000)]); + assert_eq!(logs[0], logs[1], "whatever the frame rate or start time"); +} + +#[test] +fn right_goes_into_the_side_column_and_tab_or_left_comes_back() { + let mut rt = runtime(Some(Some("Fade".into()))); + press(&mut rt, Key::Right); + assert_eq!(focused(&rt).as_deref(), Some("playground-trigger-r")); + press(&mut rt, Key::Down); + assert_eq!(focused(&rt).as_deref(), Some("playground-trigger-f")); + press(&mut rt, Key::Down); + assert_eq!(focused(&rt).as_deref(), Some("playground-trigger-r"), "↑↓ wrap inside it"); + letter(&mut rt, "j"); + assert_eq!(selected(&rt), 5, "J doesn't leave the story from the side column"); + press(&mut rt, Key::Tab); + assert_eq!(focused(&rt), None); + press(&mut rt, Key::Right); + press(&mut rt, Key::Left); + assert_eq!((focused(&rt), selected(&rt)), (None, 5), "← comes back too, to the same story"); + press(&mut rt, Key::Down); + press(&mut rt, Key::Down); + assert_eq!(selected(&rt), 3); + press(&mut rt, Key::Right); + assert_eq!(focused(&rt), None, "a live page has no triggers to go into"); +} + +#[test] +fn the_shortcut_opens_and_closes_it_without_a_menu() { + let mut rt = runtime_in(Some(None), false); + let chord = Mods { cmd: true, shift: true, ctrl: cfg!(not(target_os = "macos")), ..Mods::default() }; + assert!(is_open(&rt)); + press_with(&mut rt, Key::Command('d'), chord); + assert!(!is_open(&rt)); + press_with(&mut rt, Key::Command('d'), chord); + assert!(is_open(&rt)); + let mut rt = runtime(Some(None)); + let menu = cfg!(target_os = "macos"); + press_with(&mut rt, Key::Command('d'), chord); + assert_eq!(is_open(&rt), menu, "the View menu's item has it in a Mac window"); +} + +#[test] +fn leaving_a_story_part_way_drops_its_queued_steps() { + let mut rt = runtime(Some(Some("Fade".into()))); + letter(&mut rt, "r"); + letter(&mut rt, "j"); + for _ in 0..60 { rt.frame(1.0 / 60.0); } + letter(&mut rt, "k"); + for _ in 0..60 { rt.frame(1.0 / 60.0); } + assert_eq!(shows(&rt, "fade"), "[\"start\"]", "no burst of overdue steps on return"); +} + +const DT: f64 = 1.0 / 60.0; + +fn center(rt: &Runtime<Real>, key: &str) -> (f32, f32) { + let r = find(rt, key).unwrap_or_else(|| panic!("no {key}")).rect; + (r[0] + r[2] * 0.5, r[1] + r[3] * 0.5) +} + +fn own_state<P: 'static>(rt: &Runtime<Real>) -> &P { + let (own, stage) = rt.hooks.playground.as_ref().and_then(|p| p.own()).expect("a story with its own state"); + own.state_ref(stage).downcast_ref().unwrap() +} + +fn scene_state(rt: &Runtime<Real>) -> &Real { + &rt.hooks.playground.as_ref().and_then(|p| p.scene()).expect("a scene").state +} + +#[cfg(feature = "hot")] +#[test] +fn a_view_that_panics_falls_back_to_the_open_story() { + thread_local! { static PANICS: std::cell::Cell<u32> = const { std::cell::Cell::new(0) }; } + fn flaky(_: &Lab, _: &mut Cx<Lab>) -> El { + if PANICS.replace(PANICS.get().saturating_sub(1)) > 0 { panic!("a patched view panicked"); } + text("steady").key("flaky") + } + let mut rt = runtime_with(base().story(Story::new("Fixes/Flaky", Lab::default, flaky)), Some(Some("Flaky".into())), true); + assert_eq!(shows(&rt, "flaky"), "steady"); + PANICS.set(1); + rt.update(|s, _| s.count += 1); + rt.frame(DT); + assert_eq!(shows(&rt, "flaky"), "steady", "the fallback builds the story, not the app"); + assert!(find(&rt, "count").is_none()); +} + +#[derive(Default)] +struct Tip { + hidden: bool, +} + +fn tip(p: &Tip, _: &mut Cx<Tip>) -> El { + let tip = (!p.hidden).then(|| el().key("tip").size(120.0, 120.0).transition(Transition::opacity()).on_hover_change(|_: &mut Tip, _, _| {})); + col().w_full().h_full().children(tip) +} + +#[test] +fn a_new_stage_ends_the_old_ones_exits() { + let story = Story::new("Fixes/Tip", Tip::default, tip).trigger('h', "Hide", |p, _| p.hidden = true); + let mut rt = runtime_with(base().story(story), Some(Some("Tip".into())), true); + let (x, y) = center(&rt, "tip"); + rt.pointer_move(x, y); + rt.frame(DT); + letter(&mut rt, "h"); + rt.frame(DT); + let exiting = |rt: &Runtime<Real>| rt.elements().into_iter().any(|e| e.key.as_deref() == Some("tip") && e.exiting); + assert!(exiting(&rt), "the tip fades out"); + letter(&mut rt, "j"); + assert!(!exiting(&rt), "gone with the state its handlers were built for"); + rt.pointer_move(x + 300.0, y); + rt.frame(DT); + rt.pointer_move(x, y); + rt.frame(DT); +} + +#[test] +fn root_handlers_reach_the_app_above_the_bar_and_the_stage() { + let mut rt = runtime(None); + rt.paste("hi"); + rt.frame(DT); + rt.drop_files(vec!["a.txt".into()], None); + rt.frame(DT); + rt.window_focus(false); + rt.frame(DT); + assert_eq!((rt.state.pastes.as_slice(), rt.state.drops, rt.state.focus.last()), (&["hi".to_owned()][..], 1, Some(&false))); + rt.update(|_, tx| tx.open_playground()); + rt.frame(DT); + rt.paste("staged"); + rt.frame(DT); + rt.drop_files(vec!["b.txt".into(), "c.txt".into()], None); + rt.frame(DT); + rt.window_focus(true); + rt.frame(DT); + let scene = scene_state(&rt); + assert_eq!((scene.pastes.as_slice(), scene.drops, scene.focus.as_slice()), (&["staged".to_owned()][..], 2, &[true][..])); + assert_eq!((rt.state.pastes.len(), rt.state.drops), (1, 1), "the real state is untouched"); +} + +#[test] +fn a_key_after_a_press_that_opens_the_playground_reaches_it() { + let mut rt = runtime(None); + let (x, y) = center(&rt, "playground-open"); + rt.pointer_down(x, y); + rt.pointer_up(x, y); + rt.key(KeyEvent { key: Key::Down, mods: Mods::default() }); + rt.frame(DT); + assert!(is_open(&rt)); + assert_eq!(selected(&rt), 1, "the open landed before the key"); +} + +#[derive(Default)] +struct Tray { + hovering: bool, +} + +fn tray(_: &Tray, _: &mut Cx<Tray>) -> El { + el().key("tray").w_full().h_full().on_drop_files(|_: &mut Tray, _, _| {}).on_drop_hover(|p: &mut Tray, on, _| p.hovering = on) +} + +#[test] +fn a_new_stage_forgets_what_the_pointer_held_in_the_old_one() { + let mut rt = runtime_with(base().story(Story::new("Fixes/Tray", Tray::default, tray)), Some(Some("Tray".into())), true); + let at = center(&rt, "tray"); + rt.drag_files(vec!["a.txt".into()], Some(at)); + rt.frame(DT); + assert!(own_state::<Tray>(&rt).hovering); + rt.pointer_down(at.0, at.1); + press(&mut rt, Key::Escape); + letter(&mut rt, "j"); + assert_eq!(selected(&rt), 0); + rt.drag_files_leave(); + rt.frame(DT); + rt.pointer_move(at.0 + 10.0, at.1); + rt.pointer_up(at.0 + 10.0, at.1); + rt.frame(DT); + assert_eq!(rt.drop_hovered(), None); +} + +fn slow(_: &Lab, cx: &mut Cx<Lab>) -> El { + cx.time_scale(0.25); + text("slow").key("slow") +} + +#[test] +fn a_storys_time_scale_stays_with_it() { + let mut rt = runtime_with(base().story(Story::new("Fixes/Slow", Lab::default, slow)), Some(Some("Slow".into())), true); + assert_eq!(rt.time_scale, 0.25); + letter(&mut rt, "j"); + assert_eq!(rt.time_scale, 1.0, "the next story starts at the app's"); + letter(&mut rt, "k"); + assert_eq!(rt.time_scale, 0.25); + escape(&mut rt); + assert!(!is_open(&rt)); + assert_eq!(rt.time_scale, 1.0, "Back restores the app's"); +} + +#[derive(Default)] +struct Knob { + value: i32, +} + +fn knob(k: &Knob, _: &mut Cx<Knob>) -> El { + col().w_full().h_full() + .child(text(format!("value {}", k.value)).key("value")) + .child(el().key("knob").size(60.0, 20.0).on_step(|k: &mut Knob, by, _| k.value += by)) +} + +#[test] +fn an_element_focused_in_the_stage_keeps_its_keys_until_escape() { + let mut rt = runtime_with(base().story(Story::new("Fixes/Knob", Knob::default, knob)), Some(Some("Knob".into())), true); + let at = selected(&rt); + tap(&mut rt, "knob"); + assert_eq!(focused(&rt).as_deref(), Some("knob")); + press(&mut rt, Key::Down); + press(&mut rt, Key::Up); + press(&mut rt, Key::Up); + assert_eq!((shows(&rt, "value"), selected(&rt)), ("value 1".to_owned(), at)); + escape(&mut rt); + assert!(is_open(&rt) && focused(&rt).is_none(), "Escape leaves the knob"); + letter(&mut rt, "j"); + assert_ne!(selected(&rt), at); +} + +#[test] +fn a_replay_from_the_side_column_keeps_the_keyboard_there() { + let mut rt = runtime(Some(Some("Fade".into()))); + press(&mut rt, Key::Right); + press(&mut rt, Key::Down); + assert_eq!(focused(&rt).as_deref(), Some("playground-trigger-f")); + letter(&mut rt, "r"); + rt.frame(DT); + assert_eq!(shows(&rt, "fade"), "[\"start\"]"); + assert_eq!(focused(&rt).as_deref(), Some("playground-trigger-f")); + press(&mut rt, Key::Up); + assert_eq!(focused(&rt).as_deref(), Some("playground-trigger-r")); +} + +#[test] +fn scene_triggers_and_sides_take_names_as_find_does() { + let playground = base() + .trigger("still", 'q', "Add four", |s, _| s.count += 4) + .side("STILL", |s, _| text(format!("side {}", s.count)).key("still-side")); + let mut rt = runtime_with(playground, Some(Some("Motion/Still".into())), true); + assert_eq!(shows(&rt, "still-side"), "side 0"); + letter(&mut rt, "q"); + rt.frame(DT); + assert_eq!(shows(&rt, "still-side"), "side 4"); +} + +#[test] +fn a_long_story_list_scrolls_and_reaches_what_was_off_screen() { + let mut p = base(); + for n in 0..30 { + let name: &'static str = Box::leak(format!("Many/Story {n}").into_boxed_str()); + p = p.story(Story::new(name, Lab::default, lab)); + } + let mut rt = runtime_with(p, Some(None), true); + rt.frame(DT); + let last = rt.hooks.playground.as_ref().unwrap().order.last().copied().unwrap(); + let item = format!("playground-item-{last}"); + let (_, y) = center(&rt, &item); + assert!(y > 500.0, "the last story starts below the window"); + let list = find(&rt, "playground-list").expect("list").rect; + + rt.wheel(list[0] + 20.0, list[1] + 100.0, -4000.0); + rt.frame(DT); + rt.frame(DT); + let (x2, y2) = center(&rt, &item); + assert!(y2 < y && y2 < 500.0, "the wheel scrolled the list up to the last story"); + let hit = rt.element_at(x2, y2).and_then(|p| p.key().map(str::to_owned)); + assert!(hit.is_some_and(|k| k == item || find(&rt, &k).is_some_and(|e| e.rect[1] >= y2 - 28.0)), "the last story is hittable"); +} + +#[path = "groups_tests.rs"] +mod groups; + +#[path = "scenes_tests.rs"] +mod scenes; + +#[path = "real_tests.rs"] +mod real; + +#[path = "variants_tests.rs"] +mod variants; + +#[path = "keys_tests.rs"] +mod keys; + +#[path = "region_tests.rs"] +mod region; + +#[path = "chrome_tests.rs"] +mod chrome; + +#[path = "stage_tests.rs"] +mod stage_layout; + +#[path = "press_tests.rs"] +mod press; + +#[path = "widths_tests.rs"] +mod widths_tests; diff --git a/app/vendor/rune/crates/rune/src/playground/tree.rs b/app/vendor/rune/crates/rune/src/playground/tree.rs new file mode 100644 index 0000000..7c998cc --- /dev/null +++ b/app/vendor/rune/crates/rune/src/playground/tree.rs @@ -0,0 +1,185 @@ +//! The story list as a tree: a story's path names its groups, one per `/`, so +//! `"Sidebar/Filter buttons/Compact"` lists "Compact" in "Filter buttons", inside "Sidebar". +//! A group is known by its path prefix (`"Sidebar/Filter buttons"`), which folds keep, and +//! every level folds. + +use super::*; + +impl<S: 'static> Playground<S> { + /// Lists these top-level groups first, in this order, then the rest in the order they first + /// appear. Scenes and stories are alike here: `&["Prototypes", "Scenes"]` lists the + /// "Prototypes" stories above the scenes. Inside a group, stories keep the order they're + /// declared in. A name that isn't a group is passed over (and logged in debug builds). + pub fn group_order(mut self, groups: &[&'static str]) -> Self { + self.group_order = groups.to_vec(); + self + } +} + +impl LiveCore { + /// Story `i`'s groups, outermost first, each by its path prefix: `"Sidebar"`, then + /// `"Sidebar/Filter buttons"`. + pub(super) fn groups_of(&self, i: usize) -> Vec<&'static str> { + let group = self.group(i); + group.match_indices('/').map(|(at, _)| &group[..at]).chain(std::iter::once(group)).collect() + } + + /// Stories in list order: each group gathered where its first story is, at every level, and + /// stories and groups inside one kept in the order they first appear, except that the + /// top-level groups `first` names come first, in its order ([`Playground::group_order`]). + pub(super) fn tree_order(&self, listed: &[usize], first: &[&'static str]) -> Vec<usize> { + if cfg!(debug_assertions) { + for name in first.iter().filter(|&&name| !listed.iter().any(|&i| self.groups_of(i)[0] == name)) { + eprintln!("rune: Playground::group_order names {name:?}, which isn't a group in the list"); + } + } + let mut out = Vec::with_capacity(listed.len()); + self.gather(listed, 0, first, &mut out); + out + } + + fn gather(&self, items: &[usize], depth: usize, first: &[&'static str], out: &mut Vec<usize>) { + // A story here, or a group's stories, in the order they first appear. + let mut runs: Vec<(Option<&'static str>, Vec<usize>)> = Vec::new(); + for &i in items { + match self.groups_of(i).get(depth).copied() { + Some(group) => match runs.iter_mut().find(|(g, _)| *g == Some(group)) { + Some((_, inside)) => inside.push(i), + None => runs.push((Some(group), vec![i])), + }, + None => runs.push((None, vec![i])), + } + } + if depth == 0 { runs.sort_by_key(|(g, _)| g.and_then(|g| first.iter().position(|&f| f == g)).unwrap_or(usize::MAX)); } + for (group, inside) in runs { + match group { + Some(_) => self.gather(&inside, depth + 1, first, out), + None => out.extend(inside), + } + } + } + + /// What the filter field holds, trimmed. + pub(super) fn query(&self) -> &str { + self.controls.filter.text.trim() + } + + /// Empties the filter field; true when it held something. + pub(crate) fn clear_filter(&mut self) -> bool { + if self.controls.filter.text.is_empty() { return false; } + self.controls.filter.replace_text(String::new()); + true + } + + /// The first story the filter keeps, unless the selected one is among them. + pub(crate) fn first_match(&self) -> Option<usize> { + if self.header.is_none() && self.selected < self.count() && self.matches(self.selected) { return None; } + self.order.iter().copied().find(|&i| self.matches(i)) + } + + /// The first story the list shows, which ↓ from the filter goes to. + pub(crate) fn first_shown(&self) -> Option<usize> { + self.rows().into_iter().find_map(|r| match r { + Row::Story(i, _) => Some(i), + Row::Header(..) => None, + }) + } + + /// Whether story `i` matches the filter: each word somewhere in its path, ignoring case. + pub(super) fn matches(&self, i: usize) -> bool { + let query = self.query(); + if query.is_empty() { return true; } + let path = self.path(i).to_lowercase(); + query.to_lowercase().split_whitespace().all(|word| path.contains(word)) + } + + /// Whether `group` is folded, as the list shows it: a filter shows every match. + pub(super) fn is_folded(&self, group: &str) -> bool { + self.query().is_empty() && self.folded.contains(&group) + } + + /// Whether story `i` is in `group`, directly or in a group inside it. + pub(super) fn is_in(&self, i: usize, group: &str) -> bool { + let own = self.group(i); + own == group || own.strip_prefix(group).is_some_and(|rest| rest.starts_with('/')) + } + + /// The stories in `group` that the filter keeps, which its header counts. + pub(super) fn count_in(&self, group: &str) -> usize { + self.order.iter().filter(|&&i| self.is_in(i, group) && self.matches(i)).count() + } + + /// The first story in `group`, filter or not, which keys its header. + fn first_in(&self, group: &str) -> usize { + self.order.iter().copied().find(|&i| self.is_in(i, group)).unwrap_or(0) + } + + /// The group around `group`, if it's not at the top. + pub(super) fn parent(group: &'static str) -> Option<&'static str> { + group.rfind('/').map(|at| &group[..at]) + } + + /// The list's rows: each group's header, then what's in it unless it, or a group around it, + /// is folded. A filter keeps its matches and the headers above them. + pub(super) fn rows(&self) -> Vec<Row> { + let mut rows = Vec::new(); + let mut open: Vec<&'static str> = Vec::new(); + for &i in self.order.iter().filter(|&&i| self.matches(i)) { + let groups = self.groups_of(i); + let same = open.iter().zip(&groups).take_while(|(a, b)| a == b).count(); + open.truncate(same); + for depth in same..groups.len() { + if !groups[..depth].iter().any(|g| self.is_folded(g)) { rows.push(Row::Header(groups[depth], self.first_in(groups[depth]), depth)); } + open.push(groups[depth]); + } + if !groups.iter().any(|g| self.is_folded(g)) { rows.push(Row::Story(i, groups.len())); } + } + rows + } + + /// The outermost folded group that hides story `i`'s row, or `group`'s header, if one does. + fn hidden_by(&self, groups: &[&'static str]) -> Option<&'static str> { + groups.iter().copied().find(|g| self.is_folded(g)) + } + + /// After folds change: a selection whose row a fold hid moves to the header that hides it. + pub(super) fn settle(&mut self) { + if !self.is_open() { return; } + let hider = match self.header { + Some(h) => { + let mut around: Vec<&'static str> = std::iter::successors(Self::parent(h), |g| Self::parent(g)).collect(); + around.reverse(); + self.hidden_by(&around) + } + None if self.selected < self.count() => self.hidden_by(&self.groups_of(self.selected)), + None => None, + }; + if let Some(g) = hider { self.header = Some(g); } + } + + /// Every group in the list, outermost first, as folds name them. + pub(super) fn all_groups(&self) -> Vec<&'static str> { + let mut out: Vec<&'static str> = Vec::new(); + for &i in &self.order { + for g in self.groups_of(i) { + if !out.contains(&g) { out.push(g); } + } + } + out + } +} + +/// A row of the story list. A header carries its first story, which keys it, and its depth; +/// a story its depth, the number of groups it's in. +#[derive(Clone, Copy, Debug, PartialEq)] +pub(super) enum Row { + Header(&'static str, usize, usize), + Story(usize, usize), +} + +impl Row { + /// A header's element key: by its first story, with its depth below the top. + pub(super) fn header_key(first: usize, depth: usize) -> String { + if depth == 0 { format!("playground-group-{first}") } else { format!("playground-group-{first}-{depth}") } + } +} diff --git a/app/vendor/rune/crates/rune/src/playground/variants.rs b/app/vendor/rune/crates/rune/src/playground/variants.rs new file mode 100644 index 0000000..efb0645 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/playground/variants.rs @@ -0,0 +1,49 @@ +//! Variants: a story's state made with one of its named tweaks, picked by 1 to 9. + +use super::*; + +impl LiveCore { + /// The open story's variants' names, in key order. + pub(super) fn variants(&self) -> &[&'static str] { + self.variants_of(self.selected) + } + + fn variants_of(&self, i: usize) -> &[&'static str] { + self.stories.get(i).map_or(&[], |s| &s.variants) + } + + /// `--variant`: story `name` (else the first) opens on the variant `variant` names, by + /// number from 1 or by name. + pub(super) fn pick(&mut self, name: Option<&str>, variant: &str) -> Result<(), String> { + let i = name.and_then(|n| self.find(n)).unwrap_or(self.selected); + let names = self.variants_of(i); + let by_number = variant.parse::<usize>().ok().filter(|n| (1..=names.len()).contains(n)).map(|n| n - 1); + let by_name = || names.iter().position(|n| *n == variant).or_else(|| names.iter().position(|n| n.eq_ignore_ascii_case(variant))); + match by_number.or_else(by_name) { + Some(n) => self.variant[i] = n, + None if names.is_empty() => return Err(format!("{:?} has no variants", self.path(i))), + None => return Err(format!("no variant {variant:?} of {:?}; it has: {}", self.path(i), names.join(", "))), + } + // A story's stage outlives a switch away; made again, it takes the variant. + if let Some(own) = self.own_slot_mut(i) { own.stage = None; } + Ok(()) + } + + /// The open story's variant, by index, of those it has. + pub(super) fn variant_at(&self) -> usize { + self.variant.get(self.selected).copied().unwrap_or(0) + } + + /// What a digit key does: the open story's variant it names, if it has that many. + pub(super) fn variant_key(&self, c: char) -> Option<Request> { + let n = c.to_digit(10).filter(|d| (1..=9).contains(d))? as usize; + (n <= self.variants().len()).then_some(Request::Variant(n - 1)) + } +} + +impl<S: 'static> TypedStage<S> { + /// Scene `selected`'s variant fn at `at`, if it has variants. + pub(super) fn scene_variant(&self, selected: usize, at: usize) -> Option<&dyn Fn(&mut S)> { + self.variants.iter().filter(|(s, _)| *s == selected).nth(at).map(|(_, apply)| apply.as_ref()) + } +} diff --git a/app/vendor/rune/crates/rune/src/playground/variants_tests.rs b/app/vendor/rune/crates/rune/src/playground/variants_tests.rs new file mode 100644 index 0000000..eb49810 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/playground/variants_tests.rs @@ -0,0 +1,75 @@ +use super::*; + +fn lab_variants() -> Playground<Real> { + let story = Story::new("Variants/Pressed", Lab::default, lab) + .variant("Few", |p| p.presses = 5) + .variant("Many", |p| p.presses = 50) + .trigger('x', "Clear", |p, _| p.presses = 0); + base().story(story) +} + +#[test] +fn digits_switch_a_storys_variant_and_r_remakes_the_one_its_on() { + let mut rt = runtime_with(lab_variants(), Some(Some("Pressed".into())), true); + assert_eq!(shows(&rt, "lab"), "ticks 0 presses 5", "a story with variants starts on its first"); + assert!(find(&rt, "playground-variant-0").is_some() && find(&rt, "playground-variant-1").is_some(), "the side column lists them"); + assert_eq!(shows(&rt, "playground-hint").replace('\u{a0}', " "), "↑↓ stories · ←→ groups · / filter · Tab controls · Esc back"); + let (hint, side) = (find(&rt, "playground-hint").unwrap().rect, find(&rt, "playground-side").unwrap().rect); + let (one_line, line) = rt.text.measure(&shows(&rt, "playground-hint"), crate::tok::type_::SECTION, 1.0); + assert!(hint[0] + hint[2] <= side[0] + side[2], "{hint:?} in {side:?}"); + assert!(one_line <= hint[2] - 8.0 || hint[3] > 1.5 * line, "a hint too long for one line wraps: {one_line} wide, {hint:?}"); + let all = rt.elements(); + let caps: Vec<_> = all.iter().filter(|e| e.parent.is_some_and(|p| all[p].key.as_deref() == Some("cap"))).filter_map(|e| e.text.clone()).collect(); + assert_eq!(caps, ["1", "2", "R", "X"], "each variant's and trigger's key, by its row"); + letter(&mut rt, "2"); + assert_eq!(shows(&rt, "lab"), "ticks 0 presses 5", "from the list, a digit isn't a variant"); + press(&mut rt, Key::Tab); + assert_eq!(shows(&rt, "playground-hint").replace('\u{a0}', " "), "↑↓ controls · 1–2 variants · Esc stories"); + letter(&mut rt, "2"); + assert_eq!(shows(&rt, "lab"), "ticks 0 presses 50"); + tap(&mut rt, "bump"); + escape(&mut rt); + letter(&mut rt, "r"); + assert_eq!(shows(&rt, "lab"), "ticks 0 presses 50", "R makes the variant again"); + press(&mut rt, Key::Tab); + letter(&mut rt, "3"); + assert_eq!(shows(&rt, "lab"), "ticks 0 presses 50", "there's no third"); + letter(&mut rt, "x"); + rt.frame(DT); + assert_eq!(shows(&rt, "lab"), "ticks 0 presses 0", "triggers still run"); + tap(&mut rt, "playground-variant-0"); + assert_eq!(shows(&rt, "lab"), "ticks 0 presses 5", "a row picks one too"); + letter(&mut rt, "2"); + escape(&mut rt); + letter(&mut rt, "k"); + letter(&mut rt, "j"); + assert_eq!(shows(&rt, "lab"), "ticks 0 presses 50", "J and K still move, and the variant stays with its story"); + escape(&mut rt); + rt.update(|_, tx| tx.open_playground()); + rt.frame(DT); + assert_eq!(shows(&rt, "lab"), "ticks 0 presses 5", "reopened, it's back on its first"); +} + +#[test] +fn a_scene_has_variants_too_applied_after_its_scene_fn() { + let scenes = base() + .variant("Still", "Ten", |s| s.count = 10) + .variant("Still", "Twenty", |s| s.count = 20) + .trigger("Still", 'd', "Double", |s, _| s.count *= 2); + let mut rt = runtime_with(scenes, Some(Some("Still".into())), true); + assert_eq!(shows(&rt, "count"), "count 10"); + press(&mut rt, Key::Tab); + letter(&mut rt, "2"); + assert_eq!(shows(&rt, "count"), "count 20"); + letter(&mut rt, "d"); + rt.frame(DT); + assert_eq!(shows(&rt, "count"), "count 40"); + letter(&mut rt, "r"); + assert_eq!(shows(&rt, "count"), "count 20"); + escape(&mut rt); + letter(&mut rt, "k"); + assert!(find(&rt, "playground-variant-0").is_none(), "another scene has none"); + press(&mut rt, Key::Tab); + letter(&mut rt, "1"); + assert_eq!(shows(&rt, "count"), "count 0", "and a digit isn't the playground's there"); +} diff --git a/app/vendor/rune/crates/rune/src/playground/view.rs b/app/vendor/rune/crates/rune/src/playground/view.rs new file mode 100644 index 0000000..df5f2f7 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/playground/view.rs @@ -0,0 +1,379 @@ +//! The playground's window: the bar, the sidebar of stories, the stage and the side column. + +use super::*; + +impl<S: 'static> Live<S> { + /// The window's root: the app's view above the bar, or the playground around its stage. + /// Reached through `Live::view`. + pub(super) fn compose(&self, app: &S, view: fn(&S, &mut Cx<S>) -> El, cx: &mut Cx<S>, viewport: (f32, f32)) -> El { + let dark = self.stage.app_dark.map_or_else(|| cx.system_dark(), |dark| dark(app)); + if !self.core.open { + if !self.core.bar { return call(view, app, cx); } + let root = call(view, app, cx); + return self.core.closed_view(root, dark, viewport); + } + let env = self.core.stage_env(cx.env(), dark); + let content = self.stage_content(app, view, cx, env); + let side_slot = self.side_slot(app, cx); + let chrome = Chrome { + accent: cx.accent(), + focus_color: cx.focus_color(), + titlebar_inset: cx.titlebar_inset(), + chrome_insets: cx.chrome_insets(), + }; + self.core.open_view(content, side_slot, chrome, dark, viewport) + } + + fn stage_content(&self, app: &S, view: fn(&S, &mut Cx<S>) -> El, cx: &mut Cx<S>, env: crate::Env) -> Option<El> { + if let Some(scene) = self.scene() { + return Some(self.nested(cx, env, |c| call(view, &scene.state, c))); + } + if let Some(page) = self.live_page() { + return Some(self.nested(cx, env, |c| page(app, c))); + } + if self.core.own().is_some() { + let mut unit = cx.retype::<()>(); + let root = self.core.own_stage_view(env, &mut unit); + cx.absorb(unit); + return root; + } + None + } + + /// The app's controls for the open story, from `Playground::side` or `Story::side` (or + /// their `side_keys`), acting on its stage state. + fn side_slot(&self, app: &S, cx: &mut Cx<S>) -> Option<El> { + if let Some(scene) = self.scene() { + let (_, view) = self.stage.sides.iter().find(|(s, _)| *s == self.core.selected)?; + let mut stage = cx.retype::<S>(); + let root = match view { + Side::Stage(view) => view(&scene.state, &mut stage), + Side::Real(view) => view(&scene.state, app, &mut stage), + Side::Keys(view, _) => view(&scene.state, self.core.side_active(), &mut stage), + }; + cx.absorb(stage); + return Some(root); + } + if self.core.own().is_some() { + let mut unit = cx.retype::<()>(); + let root = self.core.own_side_view(&mut unit); + cx.absorb(unit); + return root; + } + None + } + + /// Runs a stage view of the app's own type with the stage's appearance and motion. + fn nested(&self, cx: &mut Cx<S>, env: crate::Env, f: impl FnOnce(&mut Cx<S>) -> El) -> El { + let mut stage = cx.retype::<S>(); + stage.set_env(env); + stage.clear_chrome(); + if self.core.reduce_motion { stage.reduced_motion(true); } + let root = f(&mut stage); + cx.absorb(stage); + root + } +} + +/// Window chrome metrics read from `Cx` for building the non-generic playground UI. +#[derive(Clone, Copy)] +pub(super) struct Chrome { + accent: Color, + focus_color: Color, + titlebar_inset: f32, + chrome_insets: crate::ChromeInsets, +} + +impl LiveCore { + pub(super) fn closed_view(&self, root: El, dark: bool, viewport: (f32, f32)) -> El { + let t = tok::theme(dark); + // Laid out as the root of a window BAR shorter, as the runtime sizes a root. The + // runtime finds the root's handlers on it here (`Runtime::app_root`). + col().key("playground-closed").w(viewport.0).h(viewport.1) + .child(root.w(viewport.0).h((viewport.1 - BAR).max(0.0))) + .child(self.bar_view(t)) + } + + pub(super) fn stage_env(&self, mut env: crate::Env, dark: bool) -> crate::Env { + env.system_dark = self.dark.unwrap_or(dark); + env + } + + pub(super) fn own_stage_view(&self, env: crate::Env, unit: &mut Cx<()>) -> Option<El> { + let (own, stage) = self.own()?; + unit.set_env(env); + unit.clear_chrome(); + if self.reduce_motion { unit.reduced_motion(true); } + Some(own.view(stage, unit)) + } + + pub(super) fn own_side_view(&self, unit: &mut Cx<()>) -> Option<El> { + let (own, stage) = self.own()?; + own.side(stage, self.side_active(), unit) + } + + pub(super) fn open_view(&self, content: Option<El>, side_slot: Option<El>, chrome: Chrome, dark: bool, viewport: (f32, f32)) -> El { + let t = tok::theme(dark); + let (sidebar_w, side_w) = self.widths(viewport.0); + let stage_w = (viewport.0 - sidebar_w - side_w - 2.0).max(0.0); + let stage = self.stage_frame(content, (stage_w, viewport.1), t, dark); + let stage = match self.region() { + // The stage has no selection to colour, so a ring inside its edge shows it has the + // keyboard. It takes no input, so presses reach the story under it. + Region::Stage => stage.child(el().key("playground-stage-ring").pin(Some(0.0), Some(0.0), Some(0.0), Some(0.0)).border(2.0, chrome.focus_color)), + _ => stage, + }; + let side = self.side(side_slot, chrome, t, dark, side_w, viewport.1); + row().key("playground").w(viewport.0).h(viewport.1).fill(t.bg) + .child(self.sidebar(t, dark, chrome.accent, chrome.titlebar_inset, sidebar_w, viewport.1)) + .child(el().w(1.0).h(viewport.1).fill(t.separator)) + .child(stage) + .child(el().w(1.0).h(viewport.1).fill(t.separator)) + .child(side) + .child(self.sidebar_edge(sidebar_w, viewport)) + .child(self.side_edge(side_w, viewport)) + } + + fn bar_view(&self, t: Theme) -> El { + let stories = match self.order.len() { 0 => String::new(), 1 => "1 story".into(), n => format!("{n} stories") }; + let hint = self.shortcut.as_ref().map(keycaps); + let summary = [Some(stories).filter(|s| !s.is_empty()), hint].into_iter().flatten().collect::<Vec<_>>().join(" · "); + let open = row().key("playground-open").h(20.0).ml(4.0).px(6.0).gap(6.0).center_y().radius(radius::SM - 1.0) + .hover(t.hover).press(t.press) + .child(icon(&GRID, 12.0).color(t.text_secondary)) + .child(text("Playground").font(type_::LABEL).color(t.text_secondary)) + .role("button").label("Open the playground") + .on_press_tx(|_: &mut Controls, tx: &mut Tx| tx.open_playground()); + col().w_full().h(BAR).fill(t.bg) + .child(el().w_full().h(1.0).fill(t.separator)) + .child( + row().w_full().h(BAR - 1.0).center_y().justify_between() + .child(open) + .child(text(summary).font(type_::LABEL).color(t.text_secondary).pr(10.0)), + ) + } + + /// Along the sidebar's foot: the stage's size, motion and appearance. + pub(super) fn stage_controls(&self, t: Theme, window_dark: bool, sidebar_w: f32) -> El { + let dark = self.dark.unwrap_or(window_dark); + let (glyph, appearance) = if dark { (&MOON, "Dark appearance") } else { (&SUN, "Light appearance") }; + let theme = icon_button(t, "playground-theme", glyph, appearance, false, window_dark, Request::Dark(!dark)); + let reduce = icon_button(t, "playground-reduce-motion", &MOTION, "Reduce Motion", self.reduce_motion, window_dark, Request::ReduceMotion(!self.reduce_motion)); + let sizes = (!self.sizes.is_empty()).then(|| self.size_menu(t)); + row().key("playground-stage-controls").w(sidebar_w).h(HEADER).px(8.0).gap(2.0).center_y() + .children(sizes) + .child(spacer()) + .child(reduce) + .child(theme) + } + + /// The stage's size: the window's room or a preset, from a pop-up menu (a press steps + /// through them where there's no native one). + fn size_menu(&self, t: Theme) -> El { + let current = self.size.checked_sub(1).and_then(|i| self.sizes.get(i)).map_or("Window", |(n, _)| *n); + let options: Vec<(String, String)> = std::iter::once(("0".to_owned(), "Window".to_owned())) + .chain(self.sizes.iter().enumerate().map(|(i, (n, (w, h)))| ((i + 1).to_string(), format!("{n} {w}×{h}")))) + .collect(); + let (size, count) = (self.size, self.sizes.len() + 1); + row().key("playground-size").h(CONTROL).pl(8.0).pr(4.0).gap(2.0).center_y().radius(radius::SM) + .hover(t.hover).press(t.press) + .child(text(current).font(type_::LABEL).color(t.text)) + .child(icon(&CHEVRON_DOWN, 16.0).color(t.text_secondary)) + .role("button").label("Stage size") + .on_press_tx(move |_: &mut Controls, tx: &mut Tx| { + if !crate::popup_menu_supported() { + tx.playground.push(Request::Size((size + 1) % count)); + return; + } + let menu = crate::PopupMenu::picker(options.clone(), &size.to_string()); + tx.popup_menu(menu, "playground-size", |_: &mut Controls, picked, tx| { + if let Some(i) = picked.and_then(|id| id.parse().ok()) { tx.playground.push(Request::Size(i)); } + }); + }) + } + + /// The column right of the stage: the story's group and name, the app's controls for it, + /// its triggers, and a key hint. + fn side(&self, side_slot: Option<El>, chrome: Chrome, t: Theme, dark: bool, side_w: f32, height: f32) -> El { + let i = self.selected; + let title = (i < self.count()).then(|| { + col().key("playground-title").px(4.0).gap(2.0) + .child(text(self.group(i).replace('/', " › ")).font(type_::SECTION).color(t.text_secondary).truncate()) + .child(text(self.name(i)).font(type_::TITLE).color(t.text).truncate()) + }); + // Keyed by story, not generation, so a replay keeps the keyboard on the control it's on. + let slot = side_slot.map(|slot| { + let slot = el().key(format!("playground-slot-{i}")).w_full().child(slot); + // Its view marks what the keys move, so no ring. + if self.side_keys() { slot.focusable(true).no_focus_ring() } else { slot } + }); + let variants = self.variants(); + let at = self.variant_at(); + // The control the keyboard is on takes the accent, as the list's selection does while + // the list has it; the picked variant stays grey. + let on_fill = super::list::focused(chrome.accent); + let picker = (!variants.is_empty()).then(|| { + col().key("playground-variants").w_full().padding(4.0).gap(2.0).radius(radius::LG).fill(t.card).outline(1.0, 0.0, t.card_border) + .children(variants.iter().enumerate().take(9).map(|(n, &name)| { + let on = n == at; + row().key(format!("playground-variant-{n}")).w_full().h(ROW).px(4.0).gap(8.0).center_y().radius(radius::MD) + .fill(if on { selected(t, dark) } else { Color::TRANSPARENT }) + .focusable(true).focus_highlight(on_fill).press(t.press) + .child(keycap(t, &(n + 1).to_string())) + .child(text(name).font(type_::BODY).color(if on { t.text } else { t.text_secondary }).truncate()) + .role("button").label(name) + .on_press_tx(move |_: &mut Controls, tx: &mut Tx| tx.playground.push(Request::Variant(n))) + })) + }); + let triggers = self.triggers(); + let card = (!triggers.is_empty()).then(|| { + col().key("playground-triggers").w_full().padding(4.0).gap(2.0).radius(radius::LG).fill(t.card).outline(1.0, 0.0, t.card_border) + .children(triggers.iter().map(|&(key, label)| { + let request = if key == 'r' { Request::Replay } else { Request::Trigger(key) }; + row().key(format!("playground-trigger-{key}")).w_full().h(ROW).px(4.0).gap(8.0).center_y().radius(radius::MD) + .focusable(true).focus_highlight(on_fill).press(t.press) + .child(keycap(t, &cap(key))) + .child(text(label).font(type_::BODY).color(t.text).truncate()) + .role("button").label(label) + .on_press_tx(move |_: &mut Controls, tx: &mut Tx| tx.playground.push(request.clone())) + })) + }); + let hint = self.hint(variants.len(), slot.is_some() || !variants.is_empty() || !triggers.is_empty()); + // The Windows caption buttons sit over the column's top. + let insets = chrome.chrome_insets; + let under_caption = if insets.trailing > 0.0 { insets.height } else { 0.0 }; + col().key("playground-side").w(side_w).h(height).px(12.0).pt(12.0 + under_caption).pb(12.0).gap(12.0) + .children(title) + .children(slot) + .children(picker) + .children(card) + .child(spacer()) + .child(text(hint).key("playground-hint").font(type_::SECTION).color(t.text_secondary).px(4.0).wrap()) + } + + /// The keys of the column that has the keyboard, under the side column. + fn hint(&self, variants: usize, controls: bool) -> String { + let variants = match variants.min(9) { 0 => None, 1 => Some("1\u{a0}variant".into()), n => Some(format!("1–{n}\u{a0}variants")) }; + let parts: Vec<Option<String>> = match self.region() { + Region::List => vec![ + Some("↑↓\u{a0}stories".into()), + Some("←→\u{a0}groups".into()), + Some("/\u{a0}filter".into()), + controls.then(|| "Tab\u{a0}controls".into()), + Some("Esc\u{a0}back".into()), + ], + Region::Side => vec![Some("↑↓\u{a0}controls".into()), variants, Some("Esc\u{a0}stories".into())], + Region::Stage => vec![Some("Keys go to the story".into()), Some("Esc\u{a0}stories".into())], + }; + // No-break spaces keep each part whole when the hint wraps. + parts.into_iter().flatten().collect::<Vec<_>>().join("\u{a0}· ") + } + + fn stage_frame(&self, content: Option<El>, area: (f32, f32), t: Theme, dark: bool) -> El { + let stage_dark = self.dark.unwrap_or(dark); + let frame = self.frame(); + let preset = self.size.checked_sub(1).and_then(|i| self.sizes.get(i)).map(|(_, size)| *size); + let layout = self.layout(); + let (w, h) = if layout == Stage::Fill { area } else { frame.or(preset).unwrap_or(area) }; + let inner = tok::theme(stage_dark); + let content = content.unwrap_or_else(|| { + col().center().child(text("Add scenes to AppSpec::scenes, or stories to the playground").font(type_::BODY).color(inner.text_secondary)) + }); + let key = format!("playground-stage-{}", self.generation); + let stage = match layout { + // A scroll measures its first child, so the margin goes on a column around the content. + Stage::Scroll => col().key(key).w(w).h(h).scroll(ScrollSpec { stick_bottom: false }) + .child(col().key("playground-margin").w(w).padding(SCROLL_MARGIN).child(content.w((w - 2.0 * SCROLL_MARGIN).max(0.0)))), + // Sized as a window sizes its root. + _ => el().key(key).w(w).h(h).child(content.w(w).h(h)), + }; + let stage = match (layout, frame, preset) { + (Stage::Fill, _, _) => stage, + // An overlay's clear parts stay clear. + (_, Some(_), _) => stage.border(1.0, t.text_secondary.alpha(0.35)).border_dash(4.0, 3.0), + (_, None, Some(_)) => stage.outline(1.0, 0.0, inner.separator), + (_, None, None) => stage, + }; + col().w(area.0).h(area.1).center().fill(inner.bg).clip_rounded(0.0).child(stage) + } +} + +/// A selected row's fill, a step stronger in dark mode where the track is faint. +pub(super) fn selected(t: Theme, dark: bool) -> Color { + if dark { t.control_off } else { t.control_track } +} + +/// Text a step quieter than secondary: the list's counts and motion marks. +pub(super) fn tertiary(t: Theme) -> Color { + t.text_secondary.mix(t.bg, 0.45) +} + +/// A key's cap beside its control in the side column. +fn keycap(t: Theme, key: &str) -> El { + row().key("cap").h(20.0).min_w(22.0).px(6.0).center().radius(radius::SM - 2.0).fill(t.control_track) + .child(text(key.to_owned()).font(type_::LABEL).color(t.text)) +} + +/// A trigger's key as its cap shows it. +fn cap(key: char) -> String { + if key == ' ' { "Space".into() } else { key.to_ascii_uppercase().to_string() } +} + +/// A shortcut as the bar shows it: "⇧⌘D", or "Ctrl+Shift+D" off macOS. Its menu item and the +/// window both match the character, so this is the key on every layout. +fn keycaps(shortcut: &Shortcut) -> String { + shortcut.menu_keycaps().join(if cfg!(target_os = "macos") { "" } else { "+" }) +} + +/// A quiet square button showing `glyph`, named by `label` in its tooltip; `on` fills it as the +/// list's selection is filled. +fn icon_button(t: Theme, key: &str, glyph: &'static Icon, label: &str, on: bool, dark: bool, request: Request) -> El { + row().key(key.to_owned()).size(CONTROL, CONTROL).center().radius(radius::SM) + .fill(if on { selected(t, dark) } else { Color::TRANSPARENT }) + .hover(if on { selected(t, dark) } else { t.hover }).press(t.press) + .child(icon(glyph, 16.0).color(if on { t.text } else { t.text_secondary })) + .role("button").label(label.to_owned()).help(label.to_owned()) + .on_press_tx(move |_: &mut Controls, tx: &mut Tx| tx.playground.push(request.clone())) +} + +pub(super) static CHEVRON_LEFT: Icon = Icon { + name: "playground-chevron-left", + view: 16.0, + body: r#"<path d="M9.5 4L5.5 8L9.5 12" stroke="currentColor" stroke-width="1.5" fill="none" stroke-linecap="round" stroke-linejoin="round"/>"#, +}; + +static GRID: Icon = Icon { + name: "playground-grid", + view: 12.0, + body: r#"<rect x="1" y="1" width="4" height="4" rx="1" fill="currentColor"/><rect x="7" y="1" width="4" height="4" rx="1" fill="currentColor"/><rect x="1" y="7" width="4" height="4" rx="1" fill="currentColor"/><rect x="7" y="7" width="4" height="4" rx="1" fill="currentColor"/>"#, +}; + +pub(super) static CHEVRON_RIGHT: Icon = Icon { + name: "playground-chevron-right", + view: 16.0, + body: r#"<path d="M6.75 5L9.75 8L6.75 11" stroke="currentColor" stroke-width="1.5" fill="none" stroke-linecap="round" stroke-linejoin="round"/>"#, +}; + +pub(super) static CHEVRON_DOWN: Icon = Icon { + name: "playground-chevron-down", + view: 16.0, + body: r#"<path d="M5 6.75L8 9.75L11 6.75" stroke="currentColor" stroke-width="1.5" fill="none" stroke-linecap="round" stroke-linejoin="round"/>"#, +}; + +static SUN: Icon = Icon { + name: "playground-sun", + view: 16.0, + body: r#"<circle cx="8" cy="8" r="2.75" stroke="currentColor" stroke-width="1.5" fill="none"/><path d="M8 1.75V3M8 13V14.25M1.75 8H3M13 8H14.25M3.6 3.6L4.45 4.45M11.55 11.55L12.4 12.4M3.6 12.4L4.45 11.55M11.55 4.45L12.4 3.6" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"/>"#, +}; + +static MOON: Icon = Icon { + name: "playground-moon", + view: 16.0, + body: r#"<path d="M13.25 9.5A5.5 5.5 0 0 1 6.5 2.75A5.5 5.5 0 1 0 13.25 9.5Z" stroke="currentColor" stroke-width="1.5" fill="none" stroke-linejoin="round"/>"#, +}; + +pub(super) static MOTION: Icon = Icon { + name: "playground-motion", + view: 16.0, + body: r#"<circle cx="10" cy="8" r="3.25" stroke="currentColor" stroke-width="1.5" fill="none"/><path d="M1.75 5.5H4.5M1.25 8H4M1.75 10.5H4.5" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"/>"#, +}; diff --git a/app/vendor/rune/crates/rune/src/playground/widths.rs b/app/vendor/rune/crates/rune/src/playground/widths.rs new file mode 100644 index 0000000..00a3bd2 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/playground/widths.rs @@ -0,0 +1,154 @@ +//! Resizable widths for the playground's story list and right-hand column: dragged by their +//! separator edges, reset by double-clicking, and remembered across launches. + +use super::*; +use crate::prefs::Prefs; +use crate::{Cursor, Drag, Phase}; + +pub(super) const SIDEBAR_MIN: f32 = 150.0; +pub(super) const SIDEBAR_MAX: f32 = 520.0; +pub(super) const SIDE_MIN: f32 = 180.0; +pub(super) const SIDE_MAX: f32 = 560.0; +pub(super) const STAGE_MIN: f32 = 200.0; + +const PREF_SIDEBAR: &str = "playground_sidebar_w"; +const PREF_SIDE: &str = "playground_side_w"; + +#[derive(Default)] +pub(super) struct Widths { + pub(super) load: Option<Box<dyn FnOnce() -> (f32, f32)>>, + pub(super) save: Option<Rc<dyn Fn(f32, f32)>>, +} + +impl Widths { + pub(super) fn attach_prefs(&mut self, windowed: bool, title: &'static str) { + if windowed && !cfg!(test) && self.load.is_none() && self.save.is_none() { + *self = Self::prefs(crate::tooling::app_id().unwrap_or(title)); + } + } + + pub(super) fn prefs(app_id: &str) -> Self { + let load_id = app_id.to_owned(); + let save_id = app_id.to_owned(); + Self { + load: Some(Box::new(move || { + let p = Prefs::open(&load_id); + (p.get(PREF_SIDEBAR).unwrap_or(SIDEBAR), p.get(PREF_SIDE).unwrap_or(SIDE)) + })), + save: Some(Rc::new(move |sidebar, side| { + let mut p = Prefs::open(&save_id); + if (sidebar - SIDEBAR).abs() < 0.5 { + p.remove(PREF_SIDEBAR).ok(); + } else { + p.set(PREF_SIDEBAR, &sidebar).ok(); + } + if (side - SIDE).abs() < 0.5 { + p.remove(PREF_SIDE).ok(); + } else { + p.set(PREF_SIDE, &side).ok(); + } + })), + } + } +} + +impl<S: 'static> Playground<S> { + /// Keeps the story list's and side column's widths from one run to the next. Windowed apps + /// that don't set this store them in [`Prefs`] automatically. + pub fn widths(mut self, load: impl FnOnce() -> (f32, f32) + 'static, save: impl Fn(f32, f32) + 'static) -> Self { + self.widths = Widths { load: Some(Box::new(load)), save: Some(Rc::new(save)) }; + self + } +} + +pub(super) fn clamp_pair(sidebar: f32, side: f32, viewport_w: f32) -> (f32, f32) { + let side = side.clamp(SIDE_MIN, SIDE_MAX.min((viewport_w - SIDEBAR_MIN - STAGE_MIN - 2.0).max(SIDE_MIN))); + let sidebar = sidebar.clamp(SIDEBAR_MIN, SIDEBAR_MAX.min((viewport_w - side - STAGE_MIN - 2.0).max(SIDEBAR_MIN))); + (sidebar, side) +} + +impl Controls { + pub(super) fn set_widths(&mut self, sidebar: f32, side: f32) { + if sidebar.is_finite() && sidebar > 0.0 { + self.sidebar_w = sidebar.clamp(SIDEBAR_MIN, SIDEBAR_MAX).round(); + } + if side.is_finite() && side > 0.0 { + self.side_w = side.clamp(SIDE_MIN, SIDE_MAX).round(); + } + } + + pub(super) fn save_widths(&self) { + if let Some(save) = &self.save_widths { + save(self.sidebar_w, self.side_w); + } + } +} + +impl LiveCore { + pub(super) fn load_widths(&mut self) { + if let Some(load) = self.widths.load.take() { + let (sidebar, side) = load(); + self.controls.set_widths(sidebar, side); + } + } + + pub(super) fn widths(&self, viewport_w: f32) -> (f32, f32) { + clamp_pair(self.controls.sidebar_w, self.controls.side_w, viewport_w) + } + + pub(super) fn sidebar_edge(&self, sidebar_w: f32, viewport: (f32, f32)) -> El { + let vw = viewport.0; + el().key("playground-sidebar-edge") + .absolute(sidebar_w - 3.0, 0.0) + .w(7.0) + .h(viewport.1) + .cursor(Cursor::ResizeColumn) + .help("Drag to resize; double-click for the default width") + .on_drag(move |c: &mut Controls, d: &mut Drag, tx: &mut Tx| { + tx.instant(); + match d.phase { + Phase::Down => d.data = clamp_pair(c.sidebar_w, c.side_w, vw).0, + Phase::Move => { + let (_, side_w) = clamp_pair(c.sidebar_w, c.side_w, vw); + let max = SIDEBAR_MAX.min((vw - side_w - STAGE_MIN - 2.0).max(SIDEBAR_MIN)); + c.sidebar_w = (d.data + d.dx).clamp(SIDEBAR_MIN, max).round(); + } + Phase::Up if d.cancelled() => c.sidebar_w = d.data, + Phase::Up => c.save_widths(), + } + }) + .on_double_press_tx(|c: &mut Controls, tx: &mut Tx| { + tx.instant(); + c.sidebar_w = SIDEBAR; + c.save_widths(); + }) + } + + pub(super) fn side_edge(&self, side_w: f32, viewport: (f32, f32)) -> El { + let vw = viewport.0; + el().key("playground-side-edge") + .absolute(vw - side_w - 4.0, 0.0) + .w(7.0) + .h(viewport.1) + .cursor(Cursor::ResizeColumn) + .help("Drag to resize; double-click for the default width") + .on_drag(move |c: &mut Controls, d: &mut Drag, tx: &mut Tx| { + tx.instant(); + match d.phase { + Phase::Down => d.data = clamp_pair(c.sidebar_w, c.side_w, vw).1, + Phase::Move => { + let (sidebar_w, _) = clamp_pair(c.sidebar_w, c.side_w, vw); + let max = SIDE_MAX.min((vw - sidebar_w - STAGE_MIN - 2.0).max(SIDE_MIN)); + c.side_w = (d.data - d.dx).clamp(SIDE_MIN, max).round(); + } + Phase::Up if d.cancelled() => c.side_w = d.data, + Phase::Up => c.save_widths(), + } + }) + .on_double_press_tx(|c: &mut Controls, tx: &mut Tx| { + tx.instant(); + c.side_w = SIDE; + c.save_widths(); + }) + } +} diff --git a/app/vendor/rune/crates/rune/src/playground/widths_tests.rs b/app/vendor/rune/crates/rune/src/playground/widths_tests.rs new file mode 100644 index 0000000..45c2312 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/playground/widths_tests.rs @@ -0,0 +1,66 @@ +use std::cell::Cell; +use std::rc::Rc; + +use super::*; +use crate::App; + +fn size_rt(playground: Playground<Real>) -> Runtime<Real> { + let mut spec = AppSpec::new("playground", (1200.0, 700.0), Real::default, view); + spec.scenes = SCENES; + let mut rt = App::new(spec).playground(playground).headless_runtime((1200.0, 700.0), Env::new(false, 1.0)); + rt.open_playground("Fade", None); + rt.frame(DT); + rt +} + +#[test] +fn dragging_both_column_edges_resizes_them_and_double_click_restores_defaults() { + let saved = Rc::new(Cell::new((0.0_f32, 0.0_f32))); + let saved_out = saved.clone(); + let p = base().widths(|| (240.0, 310.0), move |a, b| saved_out.set((a, b))); + let mut rt = size_rt(p); + + assert_eq!(find(&rt, "playground-list").unwrap().rect[2], 240.0, "loaded sidebar width"); + assert_eq!(find(&rt, "playground-side").unwrap().rect[2], 310.0, "loaded side width"); + + let left = find(&rt, "playground-sidebar-edge").unwrap().rect; + let (lx, ly) = (left[0] + left[2] * 0.5, left[1] + 200.0); + rt.pointer_down(lx, ly); + rt.pointer_move(lx + 60.0, ly); + rt.frame(DT); + assert_eq!(find(&rt, "playground-list").unwrap().rect[2], 300.0, "sidebar widened live"); + rt.pointer_up(lx + 60.0, ly); + rt.frame(DT); + assert_eq!(saved.get().0, 300.0, "saved on release"); + + let right = find(&rt, "playground-side-edge").unwrap().rect; + let (rx, ry) = (right[0] + right[2] * 0.5, right[1] + 200.0); + rt.pointer_down(rx, ry); + rt.pointer_move(rx - 50.0, ry); + rt.frame(DT); + assert_eq!(find(&rt, "playground-side").unwrap().rect[2], 360.0, "side column widened live"); + rt.pointer_up(rx - 50.0, ry); + rt.frame(DT); + assert_eq!(saved.get(), (300.0, 360.0)); + + // Double-click each edge restores its default width. + let left = find(&rt, "playground-sidebar-edge").unwrap().rect; + let (lx, ly) = (left[0] + left[2] * 0.5, left[1] + 200.0); + rt.pointer_down(lx, ly); + rt.pointer_up(lx, ly); + rt.pointer_down(lx, ly); + rt.pointer_up(lx, ly); + rt.frame(DT); + assert_eq!(find(&rt, "playground-list").unwrap().rect[2], SIDEBAR); + assert_eq!(saved.get(), (SIDEBAR, 360.0)); + + let right = find(&rt, "playground-side-edge").unwrap().rect; + let (rx, ry) = (right[0] + right[2] * 0.5, right[1] + 200.0); + rt.pointer_down(rx, ry); + rt.pointer_up(rx, ry); + rt.pointer_down(rx, ry); + rt.pointer_up(rx, ry); + rt.frame(DT); + assert_eq!(find(&rt, "playground-side").unwrap().rect[2], SIDE); + assert_eq!(saved.get(), (SIDEBAR, SIDE)); +} diff --git a/app/vendor/rune/crates/rune/src/popup_menu/macos.rs b/app/vendor/rune/crates/rune/src/popup_menu/macos.rs new file mode 100644 index 0000000..14c76ac --- /dev/null +++ b/app/vendor/rune/crates/rune/src/popup_menu/macos.rs @@ -0,0 +1,205 @@ +//! AppKit pop-up menus. winit panics if its handler re-enters, and a menu's tracking loop run +//! inside a handler would hold every Rune frame until it closed. So the menu opens from a +//! run-loop block, after the handler returns: while it tracks, winit's observers (registered +//! for the common modes, which include the tracking mode) keep delivering redraws, display +//! ticks and wakes. + +#![allow(unsafe_code)] + +use std::{cell::{Cell, RefCell}, ffi::c_void, rc::Rc, sync::Arc}; + +use block2::{Block, RcBlock}; +use objc2::{DefinedClass, MainThreadMarker, MainThreadOnly, define_class, msg_send, sel, rc::Retained, + runtime::{AnyClass, AnyObject}}; +use objc2_app_kit::{NSMenu, NSMenuItem}; +use objc2_foundation::{NSObject, NSPoint, NSString}; +use winit::window::Window; + +use super::{Entry, PopupMenu, Session, Show}; +use crate::runtime::Waker; + +pub(super) const SUPPORTED: bool = true; + +/// The menu while it tracks, to cancel it. +pub(super) type Tracking = Retained<NSMenu>; + +/// Stops the menu's tracking. +pub(super) fn stop(menu: Tracking) { + menu.cancelTrackingWithoutAnimation(); +} + +/// An `NSMenu` takes its appearance from the view it pops up in. +pub(super) fn scheme(_dark: bool) {} + +/// winit's run-loop observers keep running while a menu tracks, so nothing asks for turns. +pub(super) fn start(_turn: Waker) {} + +/// Every item's id, by tag, and the one picked. +struct Picks { ids: Vec<String>, picked: RefCell<Option<String>> } + +define_class!( + #[unsafe(super(NSObject))] + #[thread_kind = MainThreadOnly] + #[name = "RunePopupMenuTarget"] + #[ivars = Picks] + struct Target; + + impl Target { + #[unsafe(method(runePopupPick:))] + fn pick(&self, sender: &NSMenuItem) { + let tag = sender.tag(); + if let Some(id) = usize::try_from(tag).ok().and_then(|i| self.ivars().ids.get(i)) { + *self.ivars().picked.borrow_mut() = Some(id.clone()); + } + } + } +); + +/// Opens `show` over `window` once the current winit handler returns. The answer lands in +/// `session` and `wake` brings the host to read it. False when the window has no AppKit view. +/// A session cancelled before then never opens; one whose window was hidden by then answers +/// `None`. +pub(super) fn show(window: &Arc<Window>, show: Show, session: Rc<Session>, wake: Option<Waker>) -> bool { + let Some(mtm) = MainThreadMarker::new() else { return false }; + let Some(view) = crate::platform::macos::content_view(window) else { return false }; + let mut ids = Vec::new(); + collect_ids(&show.menu, &mut ids); + // SAFETY: NSObject initialization follows set_ivars, on the main thread. + let target: Retained<Target> = unsafe { msg_send![super(mtm.alloc().set_ivars(Picks { ids, picked: RefCell::default() })), init] }; + let mut positioned = None; + let menu = build(mtm, &show.menu, &target, &mut 0, show.positioned.as_deref(), &mut positioned); + menu.setMinimumWidth(show.min_width.max(0.0) as f64); + // AppKit puts the menu's (or its positioned item's) top left at the point. Right to left it + // opens leftward from a point and lines up with its anchor's right edge, as a right-to-left + // localization's menus do. + let x = match (crate::labels::rtl(), show.element) { + (false, _) => show.at.0 as f64, + (true, Some([x, _, w, _])) => (x + w) as f64 - menu.size().width, + (true, None) => show.at.0 as f64 - menu.size().width, + }; + let at = NSPoint::new(x, show.at.1 as f64); + run_later(move || { + if !session.begin() { return; } + // A close or hide in the same turn as the request, after the host handed it over. + let picked = if view.window().is_some_and(|w| w.isVisible()) { + session.tracking(Some(menu.clone())); + // winit's view is flipped, so `at` is in window points from the top-left, the + // coordinates Rune lays out in; AppKit maps them through the view to the screen at + // its backing scale. + let chose = menu.popUpMenuPositioningItem_atLocation_inView(positioned.as_deref(), at, Some(&view)); + session.tracking(None); + let picked = target.ivars().picked.borrow_mut().take(); + if chose && picked.is_none() { eprintln!("rune: pop-up menu reported a pick without its action"); } + picked + } else { None }; + clear_targets(&menu); + drop((menu, target)); + if session.resolve(picked, None) && let Some(wake) = wake { wake(); } + }); + true +} + +fn collect_ids(menu: &PopupMenu, ids: &mut Vec<String>) { + for entry in &menu.entries { + match entry { + Entry::Item(item) => ids.push(item.id.clone()), + Entry::Submenu(_, menu, _) => collect_ids(menu, ids), + Entry::Separator => {} + } + } +} + +/// Builds the menu in `collect_ids` order, so an item's tag indexes its id. +fn build(mtm: MainThreadMarker, menu: &PopupMenu, target: &Target, tag: &mut isize, positioned: Option<&str>, + found: &mut Option<Retained<NSMenuItem>>) -> Retained<NSMenu> { + let ns_menu = NSMenu::new(mtm); + let object: &AnyObject = target; + // SAFETY: main-thread AppKit objects this function owns. Items don't retain their target; + // `show` keeps it alive until the menu closes and clears it then. + unsafe { + ns_menu.setAutoenablesItems(false); + crate::native_menu::set_layout_direction(&ns_menu); + for entry in &menu.entries { + match entry { + Entry::Item(item) => { + let ns_item = NSMenuItem::initWithTitle_action_keyEquivalent(mtm.alloc(), + &NSString::from_str(&item.title), Some(sel!(runePopupPick:)), &NSString::from_str("")); + ns_item.setTarget(Some(object)); + ns_item.setTag(*tag); + *tag += 1; + ns_item.setEnabled(item.enabled); + ns_item.setState(if item.checked { 1 } else { 0 }); + crate::native_menu::set_key_equivalent(&ns_item, item.key_equivalent.as_ref()); + if let Some(symbol) = &item.symbol { set_symbol(&ns_item, symbol); } + if positioned == Some(item.id.as_str()) { *found = Some(ns_item.clone()); } + ns_menu.addItem(&ns_item); + } + Entry::Separator => ns_menu.addItem(&NSMenuItem::separatorItem(mtm)), + Entry::Submenu(title, menu, enabled) => { + let title = NSString::from_str(title); + let submenu = build(mtm, menu, target, tag, None, found); + submenu.setTitle(&title); + let ns_item = NSMenuItem::new(mtm); + ns_item.setTitle(&title); + ns_item.setSubmenu(Some(&submenu)); + ns_item.setEnabled(*enabled); + ns_menu.addItem(&ns_item); + } + } + } + } + ns_menu +} + +/// An SF Symbol image, on macOS 11 and later. +fn set_symbol(item: &NSMenuItem, name: &str) { + let Some(class) = AnyClass::get(c"NSImage") else { return }; + let selector = sel!(imageWithSystemSymbolName:accessibilityDescription:); + if class.class_method(selector).is_none() { return; } + // SAFETY: the class responds to this selector, which takes (NSString*, NSString* nullable) + // and returns an autoreleased NSImage* or nil; setImage: retains it. + unsafe { + let image: Option<Retained<AnyObject>> = msg_send![class, imageWithSystemSymbolName: &*NSString::from_str(name), + accessibilityDescription: std::ptr::null::<NSString>()]; + if let Some(image) = image { let _: () = msg_send![item, setImage: &*image]; } + } +} + +/// AppKit may keep a closed menu's items alive (autoreleased) after the target is gone. +fn clear_targets(menu: &NSMenu) { + // SAFETY: main-thread items, indices bounded by the item count. + unsafe { + for i in 0..menu.numberOfItems() { + let Some(item) = menu.itemAtIndex(i) else { continue }; + item.setTarget(None); + item.setAction(None); + if let Some(submenu) = item.submenu() { clear_targets(&submenu); } + } + } +} + +#[link(name = "CoreFoundation", kind = "framework")] +unsafe extern "C" { + static kCFRunLoopDefaultMode: *const c_void; + fn CFRunLoopGetMain() -> *mut c_void; + fn CFRunLoopPerformBlock(run_loop: *mut c_void, mode: *const c_void, block: &Block<dyn Fn()>); + fn CFRunLoopWakeUp(run_loop: *mut c_void); +} + +/// Runs `f` on the main run loop after the current callout returns, in the default mode, as +/// winit queues its own deferred work. +fn run_later(f: impl FnOnce() + 'static) { + let f = Cell::new(Some(f)); + let block = RcBlock::new(move || { + if let Some(f) = f.take() && std::panic::catch_unwind(std::panic::AssertUnwindSafe(f)).is_err() { + eprintln!("rune: pop-up menu panicked"); + } + }); + // SAFETY: the main run loop is valid for the process, the mode is a CFStringRef, and + // CFRunLoopPerformBlock copies the block. + unsafe { + let run_loop = CFRunLoopGetMain(); + CFRunLoopPerformBlock(run_loop, kCFRunLoopDefaultMode, &block); + CFRunLoopWakeUp(run_loop); + } +} diff --git a/app/vendor/rune/crates/rune/src/popup_menu/mod.rs b/app/vendor/rune/crates/rune/src/popup_menu/mod.rs new file mode 100644 index 0000000..ac12aae --- /dev/null +++ b/app/vendor/rune/crates/rune/src/popup_menu/mod.rs @@ -0,0 +1,474 @@ +//! Native pop-up and context menus. A handler asks with [`Tx::popup_menu`]; once the handler's +//! frame is done the window opens the menu, and the callback runs with the picked item's id, or +//! `None` when the menu is dismissed. The answer goes through the same path as +//! [`Runtime::update`], so it commits on the next frame. +//! +//! - macOS: an `NSMenu` popped up in the window's view, overlays included. Rune keeps drawing +//! while the menu tracks: frames, display-link pacing and animations keep running. +//! - Windows: a `TrackPopupMenuEx` menu owned by the window, light or dark as the window's +//! content is. It drops down below an element anchor, as Windows menus do, and Rune keeps +//! drawing while it tracks: frames, wakes, timers and overlays. +//! - Other platforms: [`popup_menu_supported`] is false and the callback gets `None` at once. +//! - Headless runs: the menu stays open in `--tree` (`popupMenu`) until a script's +//! `{"type": "menu-pick", "id": "dark"}` or `{"type": "menu-cancel"}` answers it. + +use std::cell::RefCell; +use std::rc::Rc; +use std::sync::Arc; + +use serde_json::{Value, json}; +use winit::window::Window; + +use crate::runtime::Waker; +#[cfg(test)] +use crate::Runtime; +use crate::{PointerPress, Shortcut, Tx}; + +#[cfg(target_os = "macos")] +mod macos; +#[cfg(target_os = "macos")] +use macos as host; +#[cfg(target_os = "windows")] +mod win32; +#[cfg(target_os = "windows")] +use win32 as host; +#[cfg(target_os = "windows")] +pub(crate) use win32::{enter_menu_loop, layout, turns}; + +/// Platforms without native menus: nothing opens, so every request answers `None` at once. +#[cfg(not(any(target_os = "macos", target_os = "windows")))] +mod host { + use super::{Arc, Rc, Session, Show, Waker, Window}; + pub(super) const SUPPORTED: bool = false; + pub(super) type Tracking = (); + pub(super) fn show(_: &Arc<Window>, _: Show, _: Rc<Session>, _: Option<Waker>) -> bool { false } + pub(super) fn stop(_: Tracking) {} + pub(super) fn scheme(_: bool) {} + pub(super) fn start(_: Waker) {} +} + +/// Whether this platform shows native pop-up menus (macOS and Windows). Where it doesn't, +/// [`Tx::popup_menu`] calls back with `None` straight away, so an app can draw its own menu +/// instead. +pub fn popup_menu_supported() -> bool { host::SUPPORTED } + +/// The event loop starts. `turn` runs its idle turn (due timers, overlays), for a platform whose +/// menus hold the event loop in a modal loop of their own while they track. +pub(crate) fn start(turn: Waker) { host::start(turn); } + +/// One choice in a [`PopupMenu`]: enabled and unchecked unless set. +#[derive(Clone, Debug, PartialEq)] +pub struct PopupItem { + pub(crate) id: String, + pub(crate) title: String, + pub(crate) enabled: bool, + pub(crate) checked: bool, + pub(crate) key_equivalent: Option<Shortcut>, + pub(crate) symbol: Option<String>, +} + +impl PopupItem { + pub fn new(id: impl Into<String>, title: impl Into<String>) -> Self { + Self { id: id.into(), title: title.into(), enabled: true, checked: false, key_equivalent: None, symbol: None } + } + pub fn enabled(mut self, enabled: bool) -> Self { self.enabled = enabled; self } + /// A checkmark beside the title, as a picker shows its current value. + pub fn checked(mut self, checked: bool) -> Self { self.checked = checked; self } + /// The shortcut shown beside the title. It is a hint: the menu doesn't register it. + pub fn key_equivalent(mut self, shortcut: Shortcut) -> Self { self.key_equivalent = Some(shortcut); self } + /// An SF Symbol shown before the title on macOS 11 and later, e.g. `"moon"`. Windows shows + /// no symbol. + pub fn symbol(mut self, name: impl Into<String>) -> Self { self.symbol = Some(name.into()); self } + + pub fn id(&self) -> &str { &self.id } + pub fn title(&self) -> &str { &self.title } + pub fn is_enabled(&self) -> bool { self.enabled } + pub fn is_checked(&self) -> bool { self.checked } +} + +#[derive(Clone, Debug, PartialEq)] +pub(crate) enum Entry { + Item(PopupItem), + Separator, + /// A titled submenu, and whether it opens. + Submenu(String, PopupMenu, bool), +} + +/// The items of a native pop-up or context menu. Ids must be unique across the menu and its +/// submenus. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct PopupMenu { + pub(crate) entries: Vec<Entry>, + pub(crate) selected: Option<String>, +} + +impl PopupMenu { + pub fn new() -> Self { Self::default() } + + /// A picker's menu: one item per `(id, title)`, with `selected` checked and placed over the + /// anchor, as a SwiftUI menu-style `Picker` opens. + pub fn picker<I, T>(options: impl IntoIterator<Item = (I, T)>, selected: &str) -> Self + where I: Into<String>, T: Into<String> { + let items = options.into_iter().map(|(id, title)| { + let id = id.into(); + let checked = id == selected; + PopupItem::new(id, title).checked(checked) + }); + Self::new().items(items).selected(selected) + } + + pub fn item(mut self, item: PopupItem) -> Self { self.entries.push(Entry::Item(item)); self } + pub fn items(mut self, items: impl IntoIterator<Item = PopupItem>) -> Self { + self.entries.extend(items.into_iter().map(Entry::Item)); + self + } + pub fn separator(mut self) -> Self { self.entries.push(Entry::Separator); self } + pub fn submenu(mut self, title: impl Into<String>, menu: PopupMenu) -> Self { + self.entries.push(Entry::Submenu(title.into(), menu, true)); + self + } + /// A submenu shown greyed out and closed unless nabled. + pub fn submenu_enabled(mut self, title: impl Into<String>, menu: PopupMenu, enabled: bool) -> Self { + self.entries.push(Entry::Submenu(title.into(), menu, enabled)); + self + } + /// The top-level item that opens over an element anchor, like a pop-up button's current + /// value. Without one, a menu anchored to an element drops down below it. Over a point + /// anchor, this item opens under the point instead of the menu's top-left corner. + pub fn selected(mut self, id: impl Into<String>) -> Self { self.selected = Some(id.into()); self } + + /// The item with this id, in this menu or a submenu. + pub fn find(&self, id: &str) -> Option<&PopupItem> { + self.entries.iter().find_map(|entry| match entry { + Entry::Item(item) if item.id == id => Some(item), + Entry::Submenu(_, menu, _) => menu.find(id), + _ => None, + }) + } + + /// The selected id when it names a top-level item, the only kind AppKit can position. + pub(crate) fn positioned(&self) -> Option<&str> { + let selected = self.selected.as_deref()?; + self.entries.iter().any(|e| matches!(e, Entry::Item(item) if item.id == selected)).then_some(selected) + } + + fn validate(&self, ids: &mut std::collections::HashSet<String>) -> Result<(), String> { + for entry in &self.entries { + match entry { + Entry::Item(item) => { + if item.id.is_empty() { return Err("an item has an empty id".into()); } + if !ids.insert(item.id.clone()) { return Err(format!("duplicate item id {:?}", item.id)); } + } + Entry::Submenu(_, menu, _) => menu.validate(ids)?, + Entry::Separator => {} + } + } + Ok(()) + } + + pub(crate) fn to_json(&self) -> Value { + let entries: Vec<Value> = self.entries.iter().map(|entry| match entry { + Entry::Item(item) => { + let mut v = json!({ "id": item.id, "title": item.title, "enabled": item.enabled, "checked": item.checked }); + if let Some(shortcut) = &item.key_equivalent { v["keyEquivalent"] = shortcut.to_string().into(); } + if let Some(symbol) = &item.symbol { v["symbol"] = symbol.clone().into(); } + v + } + Entry::Separator => json!({ "separator": true }), + Entry::Submenu(title, menu, true) => json!({ "submenu": title, "menu": menu.to_json() }), + Entry::Submenu(title, menu, false) => json!({ "submenu": title, "enabled": false, "menu": menu.to_json() }), + }).collect(); + let mut v = json!({ "items": entries }); + if let Some(selected) = &self.selected { v["selected"] = selected.clone().into(); } + v + } +} + +/// Where a menu opens: over an element (by key, or a key path like `row-3/more`), or at a +/// point in window points, such as a context menu's [`PointerPress`]. +#[derive(Clone, Debug, PartialEq)] +pub enum PopupAnchor { + Key(String), + Point(f32, f32), +} + +impl From<&str> for PopupAnchor { fn from(key: &str) -> Self { Self::Key(key.into()) } } +impl From<String> for PopupAnchor { fn from(key: String) -> Self { Self::Key(key) } } +impl From<&String> for PopupAnchor { fn from(key: &String) -> Self { Self::Key(key.clone()) } } +impl From<PointerPress> for PopupAnchor { fn from(p: PointerPress) -> Self { Self::Point(p.x, p.y) } } +impl From<(f32, f32)> for PopupAnchor { fn from((x, y): (f32, f32)) -> Self { Self::Point(x, y) } } + +/// Why [`Runtime::resolve_popup`] could not answer a menu. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum PopupMenuError { + NotOpen, + UnknownItem(String), + Disabled(String), +} + +impl std::fmt::Display for PopupMenuError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::NotOpen => f.write_str("no pop-up menu is open"), + Self::UnknownItem(id) => write!(f, "the pop-up menu has no item {id:?}"), + Self::Disabled(id) => write!(f, "pop-up menu item {id:?} is disabled"), + } + } +} +impl std::error::Error for PopupMenuError {} + +pub(crate) type PickFn = Box<dyn FnOnce(crate::states::States<'_>, Option<&str>, &mut Tx)>; + +pub(crate) struct Request { + pub menu: PopupMenu, + pub anchor: PopupAnchor, + pub on_pick: PickFn, + /// A text field's own menu, whose picks the runtime acts on. + pub field: Option<Box<crate::runtime::field_menu::FieldMenu>>, +} + +impl Request { + pub(crate) fn validate(&self) -> Result<(), String> { self.menu.validate(&mut Default::default()) } +} + +/// A `Tx`'s menu request. `Tx` is `Clone`; clones share the request and the runtime takes it once. +#[derive(Clone)] +pub(crate) struct Call(Rc<RefCell<Option<Request>>>); + +impl Call { + pub(crate) fn take(&self) -> Option<Request> { self.0.borrow_mut().take() } +} + +impl std::fmt::Debug for Call { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + let menu = self.0.borrow(); + f.debug_tuple("PopupMenuCall").field(&menu.as_ref().map(|r| (&r.menu, &r.anchor))).finish() + } +} + +impl Tx { + /// Open a native pop-up menu once this handler's frame is done. `on_pick` runs, as an + /// update would, with the picked item's id after the menu closes, or `None` when it's + /// dismissed or this platform has no native menu ([`popup_menu_supported`]). Exactly one + /// call per request. A menu asked for while another is open opens after it closes. + /// + /// ```ignore + /// .on_press_tx(|_: &mut Settings, tx: &mut Tx| { + /// let menu = PopupMenu::picker([("system", "System"), ("light", "Light"), ("dark", "Dark")], "system"); + /// tx.popup_menu(menu, "theme-button", |s: &mut Settings, picked, _| { + /// if let Some(id) = picked { s.theme = id.into(); } + /// }); + /// }) + /// ``` + pub fn popup_menu<S: 'static>( + &mut self, + menu: PopupMenu, + anchor: impl Into<PopupAnchor>, + on_pick: impl FnOnce(&mut S, Option<&str>, &mut Tx) + 'static, + ) { + let on_pick: PickFn = Box::new(move |s, picked, tx| { + // None once the playground has dropped the stage that asked. + if let Some(s) = s.cast::<S>() { on_pick(s, picked, tx); } + }); + let request = Request { menu, anchor: anchor.into(), on_pick, field: None }; + self.popups.push(Call(Rc::new(RefCell::new(Some(request))))); + } +} + +/// What a host opens: the menu, where its positioned item (or its top-left corner) goes, in +/// window points, and the narrowest it may be. `element` is the anchor element's rect, for a +/// host that places menus its platform's way. +#[derive(Clone, Debug, PartialEq)] +pub(crate) struct Show { + pub menu: PopupMenu, + pub at: (f32, f32), + pub positioned: Option<String>, + pub min_width: f32, + #[cfg_attr(not(any(target_os = "windows", target_os = "macos")), allow(dead_code))] + pub element: Option<[f32; 4]>, +} + +impl Show { + /// Over an element with a selected item, that item covers the element's top-left, as a + /// pop-up button opens; without one, the menu drops down from the element's bottom-left. + /// Either way it is at least as wide as the element. At a point, the menu (or its selected + /// item) opens with its top-left corner there. + pub(crate) fn new(menu: PopupMenu, anchor: &PopupAnchor, rect: [f32; 4]) -> Self { + let positioned = menu.positioned().map(str::to_owned); + let [x, y, w, h] = rect; + let (at, min_width) = match anchor { + PopupAnchor::Key(_) if positioned.is_some() => ((x, y), w), + PopupAnchor::Key(_) => ((x, y + h), w), + PopupAnchor::Point(..) => ((x, y), 0.0), + }; + let element = matches!(anchor, PopupAnchor::Key(_)).then_some(rect); + Self { menu, at, positioned, min_width, element } + } +} + +/// Where one native menu is. The presenter holds no session while it's closed; a handed-over +/// menu is `Opening` until the platform puts it up, `Open` while it tracks, and ends +/// `Resolved` with its answer, or `Cancelled` when its window goes away first. A cancelled +/// menu never opens (or stops tracking), and its answer is dropped. +#[derive(Default)] +#[cfg_attr(not(any(target_os = "macos", target_os = "windows")), allow(dead_code))] +pub(crate) enum Phase { + #[default] + Opening, + /// Up. `tracking` is the platform's hold on the menu while its loop runs, to stop it. + Open { tracking: Option<host::Tracking> }, + /// Closed with `picked`. `pointer`: where the pointer was over the window as it closed, in + /// window points, for a platform that sends no pointer move until the pointer moves again. + Resolved { picked: Option<String>, pointer: Option<(f32, f32)> }, + Cancelled, +} + +/// One native menu, from the host handing it over until its answer is read. +#[derive(Default)] +pub(crate) struct Session { + phase: RefCell<Phase>, +} + +// Only macOS and Windows open menus; elsewhere every request answers `None` before a session. +#[cfg_attr(not(any(target_os = "macos", target_os = "windows")), allow(dead_code))] +impl Session { + /// `Opening` → `Open`, as the menu comes up. False when it was cancelled first. + pub(crate) fn begin(&self) -> bool { + let mut phase = self.phase.borrow_mut(); + if !matches!(*phase, Phase::Opening) { return false; } + *phase = Phase::Open { tracking: None }; + true + } + + /// The menu's tracking loop starts (`Some`) or returns (`None`). + pub(crate) fn tracking(&self, menu: Option<host::Tracking>) { + if let Phase::Open { tracking } = &mut *self.phase.borrow_mut() { *tracking = menu; } + } + + /// `Opening` or `Open` → `Resolved`: the menu closed with `picked`, the pointer at + /// `pointer`. False, and the answer dropped, when it was cancelled first. + pub(crate) fn resolve(&self, picked: Option<String>, pointer: Option<(f32, f32)>) -> bool { + let mut phase = self.phase.borrow_mut(); + if !matches!(*phase, Phase::Opening | Phase::Open { .. }) { return false; } + *phase = Phase::Resolved { picked, pointer }; + true + } + + /// Any phase → `Cancelled`. The menu to stop, when its loop was tracking. + pub(crate) fn cancel(&self) -> Option<host::Tracking> { + match self.phase.replace(Phase::Cancelled) { + Phase::Open { tracking } => tracking, + _ => None, + } + } + + #[cfg(test)] + pub(crate) fn is_cancelled(&self) -> bool { matches!(*self.phase.borrow(), Phase::Cancelled) } + + /// The answer of a `Resolved` menu, and where the pointer was, once: the session is + /// `Cancelled` after. + fn take_answer(&self) -> Option<(Option<String>, Option<(f32, f32)>)> { + let mut phase = self.phase.borrow_mut(); + match std::mem::replace(&mut *phase, Phase::Cancelled) { + Phase::Resolved { picked, pointer } => Some((picked, pointer)), + other => { + *phase = other; + None + } + } + } +} + +/// One window's native menu: opens what its runtime asks for, and hands the answer back after +/// `wake` brings the host to its inbox. +#[derive(Default)] +pub(crate) struct Presenter { + session: Option<Rc<Session>>, + wake: Option<Waker>, +} + +impl Presenter { + pub(crate) fn new(wake: Waker) -> Self { Self { session: None, wake: Some(wake) } } + + pub(crate) fn connect(&mut self, wake: Waker) { self.wake = Some(wake); } + + /// Runs the callback of a menu that closed since the last event. True when one ran. The + /// pointer the menu released is back where the menu left it, so a click that doesn't move + /// it first still lands. + #[cfg(test)] + #[inline(always)] + pub(crate) fn answer<S: 'static>(&mut self, rt: &mut Runtime<S>) -> bool { + let (core, mut app) = rt.split_mut(); + self.answer_core(core, &mut app) + } + + pub(crate) fn answer_core(&mut self, rt: &mut crate::runtime::RuntimeCore, app: &mut dyn crate::runtime::AppDriver) -> bool { + let Some((picked, pointer)) = self.session.as_ref().and_then(|s| s.take_answer()) else { return false }; + self.session = None; + if let Err(error) = rt.resolve_popup(app, picked.as_deref()) { + eprintln!("rune: {error}"); + rt.resolve_popup(app, None).ok(); + } + // In window points; the view's are over its zoom. + if let Some((x, y)) = pointer && rt.pointer().is_none() { rt.pointer_move(app, x / rt.zoom(), y / rt.zoom()); } + true + } + + /// Opens the runtime's next menu over `window`. Without a shown window or native menus the + /// callback gets `None` at once. With `paints`, a menu anchored to an element waits while + /// the runtime has changes to commit, so the next frame places it from the new layout. + /// True when the window should draw: a callback ran, the pointer was released, or a menu + /// waits for that frame. + #[cfg(test)] + #[inline(always)] + pub(crate) fn open<S: 'static>(&mut self, rt: &mut Runtime<S>, window: Option<&Arc<Window>>, paints: bool) -> bool { + let (core, mut app) = rt.split_mut(); + self.open_core(core, &mut app, window, paints) + } + + pub(crate) fn open_core(&mut self, rt: &mut crate::runtime::RuntimeCore, app: &mut dyn crate::runtime::AppDriver, window: Option<&Arc<Window>>, paints: bool) -> bool { + let mut redraw = false; + loop { + if window.is_some() && paints && rt.popup_waits_for_layout() { return true; } + let Some(show) = rt.take_popup() else { return redraw }; + redraw = true; + if let (Some(show), Some(window)) = (show, window) { + // As dark as what the window draws, which may not be the system's appearance. + host::scheme(rt.backdrop_dark().unwrap_or(rt.env.system_dark)); + let session = Rc::new(Session::default()); + if host::show(window, show, session.clone(), self.wake.clone()) { + self.session = Some(session); + return true; + } + } + rt.resolve_popup(app, None).ok(); + } + } + + /// The window is going away (hidden, closed or quitting): the open menu stops tracking and + /// every request still waiting is answered `None`, while its state is alive. An answer the + /// cancelled menu gives later is dropped. + #[cfg(test)] + #[inline(always)] + pub(crate) fn cancel<S: 'static>(&mut self, rt: &mut Runtime<S>) { + let (core, mut app) = rt.split_mut(); + self.cancel_core(core, &mut app); + } + + pub(crate) fn cancel_core(&mut self, rt: &mut crate::runtime::RuntimeCore, app: &mut dyn crate::runtime::AppDriver) { + self.stop(); + rt.cancel_popups(app); + } + + fn stop(&mut self) { + let Some(session) = self.session.take() else { return }; + if let Some(menu) = session.cancel() { host::stop(menu); } + } +} + +impl Drop for Presenter { + fn drop(&mut self) { self.stop(); } +} + +#[cfg(test)] +mod tests; diff --git a/app/vendor/rune/crates/rune/src/popup_menu/tests.rs b/app/vendor/rune/crates/rune/src/popup_menu/tests.rs new file mode 100644 index 0000000..2589eeb --- /dev/null +++ b/app/vendor/rune/crates/rune/src/popup_menu/tests.rs @@ -0,0 +1,281 @@ +use super::*; +use crate::{Cx, El, Env, el}; + +#[derive(Default)] +struct State { theme: String, picks: Vec<Option<String>>, anchor: Option<PopupAnchor>, hovers: Vec<bool>, extra: bool } + +fn theme_menu(selected: &str) -> PopupMenu { + PopupMenu::picker([("system", "System"), ("light", "Light"), ("dark", "Dark")], selected) +} + +fn record(s: &mut State, picked: Option<&str>, _: &mut Tx) { + s.picks.push(picked.map(str::to_owned)); + if let Some(id) = picked { s.theme = id.into(); } +} + +fn view(s: &State, _: &mut Cx<State>) -> El { + el() + .child(el().key("theme").size(80.0, 20.0).pin(Some(40.0), Some(30.0), None, None) + .on_hover_change(|s: &mut State, inside: bool, _: &mut Tx| s.hovers.push(inside)) + .on_press_tx(|s: &mut State, tx: &mut Tx| { + let anchor = s.anchor.clone().unwrap_or_else(|| "theme".into()); + tx.popup_menu(theme_menu(&s.theme), anchor, record); + })) + .children(s.extra.then(|| el().key("extra").size(30.0, 10.0).pin(Some(150.0), Some(5.0), None, None))) + .child(el().key("canvas").size(100.0, 40.0).pin(Some(0.0), Some(60.0), None, None) + .on_secondary_press(|_: &mut State, press: PointerPress, tx: &mut Tx| { + let menu = PopupMenu::new().item(PopupItem::new("copy", "Copy")).separator() + .item(PopupItem::new("paste", "Paste").enabled(false)) + .submenu("More", PopupMenu::new().item(PopupItem::new("share", "Share"))); + tx.popup_menu(menu, press, record); + })) +} + +fn runtime() -> Runtime<State> { + let mut rt = Runtime::new(State { theme: "system".into(), ..State::default() }, view, (200.0, 120.0), Env::new(true, 1.0)); + rt.frame(0.0); + rt +} + +fn click(rt: &mut Runtime<State>, key: &str) { + let (x, y) = rt.find(key).unwrap(); + rt.pointer_down(x, y); + rt.pointer_up(x, y); + rt.frame(0.0); +} + +#[test] +fn a_press_handler_asks_for_a_menu_that_opens_over_its_anchor() { + let mut rt = runtime(); + click(&mut rt, "theme"); + assert_eq!(rt.popup_menu(), Some(&theme_menu("system"))); + let show = rt.take_popup().unwrap().unwrap(); + assert_eq!(show.positioned.as_deref(), Some("system")); + assert_eq!((show.at, show.min_width), ((40.0, 30.0), 80.0), "the current value covers the button, at least as wide"); + assert_eq!(rt.take_popup(), None, "one menu at a time"); + + rt.resolve_popup(Some("dark")).unwrap(); + assert_eq!(rt.state.picks, [Some("dark".to_owned())]); + assert_eq!(rt.popup_menu(), None); + rt.frame(0.0); + assert_eq!(rt.state.theme, "dark"); +} + +#[test] +fn a_menu_without_a_selection_drops_down_below_its_element() { + let mut rt = runtime(); + rt.update(|_, tx| tx.popup_menu(PopupMenu::new().item(PopupItem::new("a", "A")), "theme", record)); + let show = rt.take_popup().unwrap().unwrap(); + assert_eq!((show.at, show.positioned, show.min_width), ((40.0, 50.0), None, 80.0)); +} + +#[test] +fn a_context_menu_opens_at_the_press() { + let mut rt = runtime(); + rt.secondary_down(30.0, 70.0); + rt.secondary_up(30.0, 70.0); + rt.frame(0.0); + let show = rt.take_popup().unwrap().unwrap(); + assert_eq!((show.at, show.positioned, show.min_width), ((30.0, 70.0), None, 0.0)); + assert_eq!(rt.resolve_popup(Some("paste")), Err(PopupMenuError::Disabled("paste".into()))); + assert_eq!(rt.resolve_popup(Some("nope")), Err(PopupMenuError::UnknownItem("nope".into()))); + assert!(rt.popup_menu().is_some(), "a refused answer leaves the menu open"); + rt.resolve_popup(Some("share")).unwrap(); + assert_eq!(rt.state.picks, [Some("share".to_owned())], "submenu items answer too"); + assert_eq!(rt.resolve_popup(None), Err(PopupMenuError::NotOpen)); +} + +#[test] +fn a_point_anchor_with_a_selection_puts_that_item_under_the_point() { + let mut rt = runtime(); + rt.state.anchor = Some((5.0, 6.0).into()); + click(&mut rt, "theme"); + let show = rt.take_popup().unwrap().unwrap(); + assert_eq!((show.at, show.positioned.as_deref(), show.min_width), ((5.0, 6.0), Some("system"), 0.0)); +} + +#[test] +fn a_menu_that_cannot_open_answers_none() { + let mut rt = runtime(); + rt.update(|_, tx| tx.popup_menu(theme_menu("system"), "missing", record)); + rt.update(|_, tx| tx.popup_menu(PopupMenu::new().item(PopupItem::new("a", "A")).item(PopupItem::new("a", "B")), "theme", record)); + rt.update(|_, tx| tx.popup_menu(PopupMenu::new().item(PopupItem::new("", "Blank")), "theme", record)); + rt.update(|_, tx| tx.popup_menu(theme_menu("light"), "theme", record)); + rt.open_popup_headless(); + assert_eq!(rt.state.picks, [None, None, None], "a missing anchor, a repeated id and an empty id each answer None"); + assert_eq!(rt.popup_menu(), Some(&theme_menu("light")), "the next valid menu opens"); + assert!(rt.host.popup_is_open()); +} + +#[test] +fn menus_asked_for_together_open_one_after_another() { + let mut rt = runtime(); + rt.update(|_, tx| { + tx.popup_menu(theme_menu("system"), "theme", record); + tx.popup_menu(theme_menu("dark"), "theme", record); + }); + rt.open_popup_headless(); + rt.resolve_popup(None).unwrap(); + assert_eq!(rt.popup_menu(), Some(&theme_menu("dark"))); + assert!(!rt.host.popup_is_open(), "the next waits for the host to open it"); + rt.open_popup_headless(); + rt.resolve_popup(Some("light")).unwrap(); + assert_eq!(rt.state.picks, [None, Some("light".to_owned())]); +} + +#[test] +fn a_pick_can_ask_for_the_next_menu() { + let mut rt = runtime(); + rt.update(|_, tx| tx.popup_menu(theme_menu("system"), "theme", |s: &mut State, picked, tx: &mut Tx| { + record(s, picked, tx); + tx.popup_menu(theme_menu("dark"), "theme", record); + })); + rt.open_popup_headless(); + rt.resolve_popup(Some("dark")).unwrap(); + assert_eq!(rt.popup_menu(), Some(&theme_menu("dark"))); +} + +#[test] +fn clones_of_a_tx_share_one_request() { + let mut tx = Tx::default(); + tx.popup_menu(theme_menu("system"), "theme", record); + let clone = tx.clone(); + assert!(clone.popups[0].take().is_some()); + assert!(tx.popups[0].take().is_none(), "taken once, whichever clone the runtime reads"); +} + +#[test] +fn the_tree_shows_the_open_menu() { + let mut rt = runtime(); + assert!(crate::tooling::tree_json(&rt, 0.0).get("popupMenu").is_none()); + rt.update(|_, tx| tx.popup_menu(PopupMenu::new().item(PopupItem::new("copy", "Copy").checked(true).symbol("doc.on.doc") + .key_equivalent("super+c".parse().unwrap())).separator(), (3.0, 4.0), record)); + rt.update(|_, tx| tx.popup_menu(theme_menu("system"), "theme", record)); + rt.open_popup_headless(); + let tree = crate::tooling::tree_json(&rt, 0.0); + let menu = &tree["popupMenu"]; + assert_eq!(menu["open"], true); + assert_eq!(menu["queued"], 1); + assert_eq!(menu["anchor"], json!({ "x": 3.0, "y": 4.0 })); + assert_eq!(menu["items"][0]["id"], "copy"); + assert_eq!(menu["items"][0]["checked"], true); + assert_eq!(menu["items"][0]["symbol"], "doc.on.doc"); + assert!(menu["items"][0]["keyEquivalent"].is_string()); + assert_eq!(menu["items"][1], json!({ "separator": true })); +} + +#[test] +fn a_window_going_away_answers_every_waiting_menu_none_once() { + let mut rt = runtime(); + let mut presenter = Presenter::default(); + rt.update(|_, tx| { + tx.popup_menu(theme_menu("system"), "theme", record); + // A dismissal that asks again is answered too. + tx.popup_menu(theme_menu("dark"), "theme", |s: &mut State, picked, tx: &mut Tx| { + record(s, picked, tx); + tx.popup_menu(theme_menu("light"), "theme", record); + }); + }); + rt.open_popup_headless(); + // The menu that was showing gives its answer only after the window went away. + let showing = Rc::new(Session::default()); + presenter.session = Some(showing.clone()); + presenter.cancel(&mut rt); + assert_eq!(rt.state.picks, [None, None, None]); + assert_eq!(rt.popup_menu(), None); + assert!(!rt.host.popup_is_open()); + assert!(showing.is_cancelled(), "a tracking menu stops, and one not yet up never opens"); + + showing.resolve(Some("dark".into()), None); + assert!(!presenter.answer(&mut rt), "a late answer doesn't call back a second time"); + presenter.cancel(&mut rt); + assert_eq!(rt.state.picks, [None, None, None]); +} + +#[test] +fn a_callback_that_always_asks_again_cannot_hold_a_closing_window() { + fn again(s: &mut State, picked: Option<&str>, tx: &mut Tx) { + record(s, picked, tx); + tx.popup_menu(theme_menu("system"), "theme", again); + } + let mut rt = runtime(); + rt.update(|_, tx| tx.popup_menu(theme_menu("system"), "theme", again)); + rt.cancel_popups(); + assert_eq!(rt.state.picks.len(), 64); + assert_eq!(rt.popup_menu(), None); +} + +#[test] +fn a_menu_from_a_press_ends_the_hover_in_that_frame() { + let mut rt = runtime(); + let (x, y) = rt.find("theme").unwrap(); + rt.pointer_move(x, y); + rt.frame(0.0); + assert_eq!(rt.state.hovers, [true]); + rt.pointer_down(x, y); + rt.pointer_up(x, y); + rt.frame(0.0); + assert!(rt.popup_menu().is_some()); + assert_eq!(rt.state.hovers, [true, false], "the hover ends with the frame that asked for the menu"); + assert_eq!((rt.pointer(), rt.pressing()), (None, false), "nothing draws hovered or pressed under the menu"); +} + +#[test] +fn a_menu_from_an_update_ends_the_hover_when_it_opens() { + let mut rt = runtime(); + let (x, y) = rt.find("theme").unwrap(); + rt.pointer_move(x, y); + rt.frame(0.0); + rt.update(|_, tx| tx.popup_menu(theme_menu("system"), (x, y), record)); + rt.open_popup_headless(); + assert_eq!(rt.pointer(), None); + rt.frame(0.0); + assert_eq!(rt.state.hovers, [true, false]); +} + +#[test] +fn a_menu_a_pick_asks_for_waits_for_the_element_the_pick_mounts() { + let mut rt = runtime(); + rt.update(|_, tx| tx.popup_menu(theme_menu("system"), "theme", |s: &mut State, picked, tx: &mut Tx| { + record(s, picked, tx); + s.extra = true; + tx.popup_menu(theme_menu("dark"), "extra", record); + })); + rt.frame(0.0); + assert!(!rt.popup_waits_for_layout(), "the frame committed"); + rt.open_popup_headless(); + rt.resolve_popup(Some("dark")).unwrap(); + assert!(rt.popup_waits_for_layout(), "\"extra\" mounts with the next commit"); + rt.frame(0.0); + assert!(!rt.popup_waits_for_layout()); + let show = rt.take_popup().unwrap().unwrap(); + assert_eq!((show.at, show.min_width), ((150.0, 5.0), 30.0)); + assert_eq!(rt.state.picks, [Some("dark".to_owned())]); +} + +#[test] +fn support_is_macos_and_windows() { + assert_eq!(popup_menu_supported(), cfg!(any(target_os = "macos", target_os = "windows"))); +} + +#[test] +fn a_session_cancelled_before_it_opens_never_opens_or_answers() { + let session = Session::default(); + assert!(session.cancel().is_none(), "nothing tracks yet, so nothing stops"); + assert!(!session.begin(), "a cancelled menu never comes up"); + assert!(!session.resolve(Some("dark".into()), Some((1.0, 2.0))), "its late answer is dropped"); + assert!(session.take_answer().is_none()); +} + +#[test] +fn a_resolved_session_hands_over_its_answer_and_pointer_once() { + let session = Session::default(); + assert!(session.begin()); + assert!(!session.begin(), "it comes up once"); + session.tracking(None); + assert!(session.resolve(Some("dark".into()), Some((3.0, 4.0)))); + assert!(!session.resolve(None, None), "the first answer stands"); + assert_eq!(session.take_answer(), Some((Some("dark".into()), Some((3.0, 4.0))))); + assert!(session.take_answer().is_none() && session.is_cancelled()); + assert!(session.cancel().is_none(), "a closed menu has nothing to stop"); +} diff --git a/app/vendor/rune/crates/rune/src/popup_menu/win32.rs b/app/vendor/rune/crates/rune/src/popup_menu/win32.rs new file mode 100644 index 0000000..1cfff6a --- /dev/null +++ b/app/vendor/rune/crates/rune/src/popup_menu/win32.rs @@ -0,0 +1,359 @@ +//! Win32 pop-up menus. `TrackPopupMenuEx` runs its own modal loop until the menu closes. Run +//! inside a winit handler, that loop would hold every Rune frame: winit buffers the events it +//! dispatches while its handler is busy. So the menu opens from a message posted to the window, +//! which winit's loop dispatches after the handler returns. While the menu tracks, its loop +//! hands the window's paints and wakes to winit as usual, so Rune keeps drawing. winit's own +//! idle turn (`AboutToWait`, resting timers) runs only between its message loops, so a timer +//! asks for that turn while the menu tracks (`start`). +//! +//! The menu drops down below an element anchor and opens with its top-left corner at a point, +//! as Windows menus do. A plain Win32 menu can't put an item under the pointer or take a +//! minimum width, so `Show::positioned` and `Show::min_width` don't apply. Keyboard navigation +//! (arrows, Enter, Esc, first letters, submenus), screen-edge flipping and dismissal by a click +//! outside are the system's. Menus are light or dark as the window's content is (`scheme`). + +#![allow(unsafe_code)] + +use std::{cell::{Cell, RefCell}, rc::Rc, sync::{Arc, OnceLock, atomic::{AtomicUsize, Ordering}}}; + +use windows_sys::Win32::Foundation::{HWND, LPARAM, LRESULT, POINT, RECT, WPARAM}; +use windows_sys::Win32::Graphics::Gdi::{ClientToScreen, ScreenToClient}; +use windows_sys::Win32::UI::HiDpi::GetDpiForWindow; +use windows_sys::Win32::UI::Shell::{DefSubclassProc, RemoveWindowSubclass, SetWindowSubclass}; +use windows_sys::Win32::UI::WindowsAndMessaging::{ + AppendMenuW, CreatePopupMenu, DestroyMenu, EndMenu, GetClientRect, GetCursorPos, GetForegroundWindow, HMENU, + IsWindow, IsWindowVisible, KillTimer, MF_CHECKED, MF_GRAYED, MF_POPUP, MF_SEPARATOR, MF_STRING, PostMessageW, + RegisterWindowMessageW, SetForegroundWindow, SetTimer, TPM_LAYOUTRTL, TPM_LEFTALIGN, TPM_NONOTIFY, TPM_RETURNCMD, + TPM_RIGHTALIGN, TPM_RIGHTBUTTON, TPM_TOPALIGN, TPM_VERTICAL, TPMPARAMS, TRACK_POPUP_MENU_FLAGS, TrackPopupMenuEx, + WM_NCDESTROY, WM_NULL, WindowFromPoint, +}; +use winit::window::Window; + +use super::{Entry, PopupItem, PopupMenu, Session, Show}; +use crate::runtime::Waker; + +pub(super) const SUPPORTED: bool = true; + +/// The menu's owner while `TrackPopupMenuEx` runs, so `EndMenu` (which ends whatever menu this +/// thread tracks) only ends this one. +pub(super) type Tracking = HWND; + +/// The next menu's subclass id. `GetWindowSubclass` would find an earlier one by a fixed id, +/// but the comctl32 an app without a v6 manifest loads exports it by ordinal only. +static NEXT: AtomicUsize = AtomicUsize::new(1); + +/// The timer asking for the event loop's idle turn while a menu tracks, about once a frame. +/// Each active `Turns` gets its own timer id so nested modal loops never cancel each other's timer. +static NEXT_TIMER: AtomicUsize = AtomicUsize::new(0x5255_4e50); +const TURN_MS: u32 = 16; + +/// Whether this thread is currently inside a Win32 modal menu loop or turn timer trampoline. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +enum ModalPhase { + #[default] + Idle, + Active, +} + +thread_local! { + static TURN: RefCell<Option<Waker>> = const { RefCell::new(None) }; + static IN_TURN: Cell<ModalPhase> = const { Cell::new(ModalPhase::Idle) }; + static IN_MENU: Cell<ModalPhase> = const { Cell::new(ModalPhase::Idle) }; +} + +/// Guard preventing re-entrant Win32 modal menu loops (`TrackPopupMenu` / `TrackPopupMenuEx`) on +/// the same thread. +pub(crate) struct MenuLoopGuard; + +impl Drop for MenuLoopGuard { + fn drop(&mut self) { + IN_MENU.with(|phase| phase.set(ModalPhase::Idle)); + } +} + +/// Enters a Win32 modal menu loop on this thread, returning `None` if one is already active. +pub(crate) fn enter_menu_loop() -> Option<MenuLoopGuard> { + IN_MENU.with(|phase| { + if phase.get() != ModalPhase::Idle { + return None; + } + phase.set(ModalPhase::Active); + Some(MenuLoopGuard) + }) +} + +struct TurnGuard; + +impl Drop for TurnGuard { + fn drop(&mut self) { + IN_TURN.with(|phase| phase.set(ModalPhase::Idle)); + } +} + +/// A menu handed over and waiting for its posted message. +struct Pending { show: Show, session: Rc<Session>, wake: Option<Waker> } + +/// A menu this thread created, destroyed with its submenus when dropped. +struct OwnedMenu(HMENU); + +impl Drop for OwnedMenu { + fn drop(&mut self) { + // SAFETY: a menu this thread created and still owns. + unsafe { DestroyMenu(self.0) }; + } +} + +/// Posts `show` to `window`, to open once the current winit handler returns. The answer lands +/// in `session` and `wake` brings the host to read it. False when the window has no Win32 +/// handle. A session cancelled before then never opens; one whose window was hidden by then +/// answers `None`. +pub(super) fn show(window: &Arc<Window>, show: Show, session: Rc<Session>, wake: Option<Waker>) -> bool { + let Some(hwnd) = crate::platform::win32::hwnd(window) else { return false }; + // Each menu has its own subclass, named in its message: one handed over earlier whose + // message hasn't come yet was cancelled, and goes when that message comes. + let id = NEXT.fetch_add(1, Ordering::Relaxed); + // SAFETY: Win32 calls on a live window owned by this thread; a subclass's data is the + // `Pending` boxed here, taken back exactly once, by whoever removes the subclass. + unsafe { + let pending = Box::into_raw(Box::new(Pending { show, session, wake })); + if SetWindowSubclass(hwnd, Some(procedure), id, pending as usize) == 0 { + drop(Box::from_raw(pending)); + return false; + } + if PostMessageW(hwnd, open_message(), id, 0) == 0 { + RemoveWindowSubclass(hwnd, Some(procedure), id); + drop(Box::from_raw(pending)); + return false; + } + } + true +} + +/// Stops the menu tracking on this thread. Its `TrackPopupMenuEx` returns once the handler that +/// asked returns. +pub(super) fn stop(_: Tracking) { + // SAFETY: ends this thread's active menu, which is this session's. + unsafe { EndMenu() }; +} + +/// Menus from now on are dark or light, whatever the system's appearance. +pub(super) fn scheme(dark: bool) { crate::platform::win32::dark_mode::menus(dark); } + +/// The event loop starts on this thread: menus follow the system's app mode until a window +/// says what it draws, and ask for `turn` while they track. +pub(super) fn start(turn: Waker) { + crate::platform::win32::dark_mode::follow_system(); + TURN.with(|t| *t.borrow_mut() = Some(turn)); +} + +fn open_message() -> u32 { + static MESSAGE: OnceLock<u32> = OnceLock::new(); + // SAFETY: the name is NUL-terminated. + *MESSAGE.get_or_init(|| unsafe { RegisterWindowMessageW(wide("Rune::PopupMenu").as_ptr()) }) +} + +unsafe extern "system" fn procedure(hwnd: HWND, message: u32, w: WPARAM, l: LPARAM, id: usize, data: usize) -> LRESULT { + if (message == open_message() && w == id) || message == WM_NCDESTROY { + // SAFETY: `data` is the `Pending` `show` boxed for this subclass, taken back once, here, + // as the subclass goes. A window destroyed first answers `None`. + let pending = unsafe { + RemoveWindowSubclass(hwnd, Some(procedure), id); + Box::from_raw(data as *mut Pending) + }; + let opens = message != WM_NCDESTROY; + let mut pointer = None; + let picked = if opens { std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| track(hwnd, &pending, &mut pointer))) } else { Ok(None) }; + let picked = picked.unwrap_or_else(|_| { + eprintln!("rune: pop-up menu panicked"); + None + }); + if pending.session.resolve(picked, pointer) && let Some(wake) = &pending.wake { wake(); } + if opens { return 0; } + } + // SAFETY: passes every other message on to winit's window procedure. + unsafe { DefSubclassProc(hwnd, message, w, l) } +} + +unsafe extern "system" fn turn(_: HWND, _: u32, _: usize, _: u32) { + let entered = IN_TURN.with(|phase| { + if phase.get() != ModalPhase::Idle { + return false; + } + phase.set(ModalPhase::Active); + true + }); + if !entered { + return; + } + let _guard = TurnGuard; + // Clone before invoking so the `RefCell` borrow is released before user code runs. + let waker = TURN.with(|t| t.borrow().clone()); + if let Some(waker) = waker { + std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| waker())).ok(); + } +} + +/// Asks for the event loop's idle turn about once a frame while a modal loop over `hwnd` runs +/// (a menu's), until it drops. +pub(crate) struct Turns { + hwnd: HWND, + id: usize, + armed: bool, +} + +pub(crate) fn turns(hwnd: HWND) -> Turns { + let id = NEXT_TIMER.fetch_add(1, Ordering::Relaxed); + // SAFETY: a timer on this thread's live window, killed when the guard drops. + let armed = unsafe { IsWindow(hwnd) != 0 && SetTimer(hwnd, id, TURN_MS, Some(turn)) != 0 }; + Turns { hwnd, id, armed } +} + +impl Drop for Turns { + fn drop(&mut self) { + // SAFETY: `IsWindow` safely validates `self.hwnd` on this thread before killing the timer. + if self.armed && unsafe { IsWindow(self.hwnd) != 0 } { + // SAFETY: `self.hwnd` was just confirmed live and `self.id` is the timer `turns` armed on it. + unsafe { KillTimer(self.hwnd, self.id) }; + } + } +} + +/// Shows the menu over `hwnd` until it closes. The picked item's id, or `None` when it was +/// dismissed, cancelled or couldn't open. Leaves where the pointer is in `pointer`. +fn track(hwnd: HWND, pending: &Pending, pointer: &mut Option<(f32, f32)>) -> Option<String> { + let _modal = enter_menu_loop()?; + if !pending.session.begin() { return None; } + // SAFETY: Win32 calls on this thread's live window. The menu is built, tracked and + // destroyed here. + unsafe { + // A close or hide in the same turn as the request, after the host handed it over. + if IsWindow(hwnd) == 0 || IsWindowVisible(hwnd) == 0 { return None; } + let mut ids = Vec::new(); + let menu = build(&pending.show.menu, &mut ids)?; + let (x, y, params) = placement(hwnd, &pending.show); + // A menu closes on a click elsewhere, and gets the keyboard, only while its owner is + // the foreground window. An overlay takes the foreground for its menu, and hands it back + // after (`hands_back`). + let previous = GetForegroundWindow(); + if previous != hwnd { SetForegroundWindow(hwnd); } + let flags = TPM_RETURNCMD | TPM_NONOTIFY | TPM_RIGHTBUTTON | TPM_TOPALIGN | layout() + | if params.is_some() { TPM_VERTICAL } else { 0 }; + let params_ptr = params.as_ref().map_or(std::ptr::null(), |p| p as *const TPMPARAMS); + let turns = turns(hwnd); + pending.session.tracking(Some(hwnd)); + let command = TrackPopupMenuEx(menu.0, flags, x, y, hwnd, params_ptr); + pending.session.tracking(None); + drop(turns); + if IsWindow(hwnd) != 0 { + // The menu's loop lets go of the foreground state once the owner gets a message. + PostMessageW(hwnd, WM_NULL, 0, 0); + if hands_back(crate::platform::win32::is_overlay(hwnd), previous, hwnd, GetForegroundWindow()) { + SetForegroundWindow(previous); + } + // winit sends no pointer move until the pointer leaves the pixel it's on. + *pointer = client_pointer(hwnd); + } + usize::try_from(command).ok()?.checked_sub(1).and_then(|i| ids.get(i)).cloned() + } +} + +/// Whether the menu's `owner` gives the foreground back to `previous` once the menu closes: an +/// overlay, whatever its `KeyPolicy`, that took the foreground only for the menu and still has +/// it. One that had the foreground before (an `OnDemand` overlay the user clicked) keeps it. +fn hands_back(overlay: bool, previous: HWND, owner: HWND, foreground: HWND) -> bool { + overlay && !previous.is_null() && previous != owner && foreground == owner +} + +/// Where the pointer is over `hwnd`'s content, in points, unless another window covers it. +fn client_pointer(hwnd: HWND) -> Option<(f32, f32)> { + // SAFETY: plain queries on this thread's live window. + unsafe { + let mut point = POINT { x: 0, y: 0 }; + if GetCursorPos(&mut point) == 0 || WindowFromPoint(point) != hwnd { return None; } + let mut client = RECT { left: 0, top: 0, right: 0, bottom: 0 }; + if ScreenToClient(hwnd, &mut point) == 0 || GetClientRect(hwnd, &mut client) == 0 { return None; } + if point.x < client.left || point.y < client.top || point.x >= client.right || point.y >= client.bottom { return None; } + let scale = scale(hwnd); + Some((point.x as f32 / scale, point.y as f32 / scale)) + } +} + +/// How a menu lays out in the app's language ([`crate::labels::set_direction`]): from its left +/// edge, or right to left from its right edge, mirrored, as a right-to-left Windows lays out its +/// menus. +pub(crate) fn layout() -> TRACK_POPUP_MENU_FLAGS { + if crate::labels::rtl() { TPM_LAYOUTRTL | TPM_RIGHTALIGN } else { TPM_LEFTALIGN } +} + +/// Where the menu opens, in screen pixels: below an element anchor (from its left edge, or its +/// right right to left), keeping clear of it when it has to flip up, or with its top-left corner +/// (top-right right to left) at a point. +fn placement(hwnd: HWND, show: &Show) -> (i32, i32, Option<TPMPARAMS>) { + let scale = scale(hwnd); + let mut origin = POINT { x: 0, y: 0 }; + // SAFETY: a plain query on this thread's live window. + unsafe { ClientToScreen(hwnd, &mut origin) }; + let px = |v: f32, o: i32| o.saturating_add((v * scale).round() as i32); + let Some([x, y, w, h]) = show.element else { return (px(show.at.0, origin.x), px(show.at.1, origin.y), None) }; + let element = RECT { left: px(x, origin.x), top: px(y, origin.y), right: px(x + w, origin.x), bottom: px(y + h, origin.y) }; + let params = TPMPARAMS { cbSize: size_of::<TPMPARAMS>() as u32, rcExclude: element }; + (if crate::labels::rtl() { element.right } else { element.left }, element.bottom, Some(params)) +} + +/// Physical pixels per point on `hwnd`'s monitor. +fn scale(hwnd: HWND) -> f32 { + // SAFETY: a plain query on this thread's live window. + let dpi = unsafe { GetDpiForWindow(hwnd) }; + if dpi == 0 { 1.0 } else { dpi as f32 / 96.0 } +} + +/// The menu's items, numbered from 1 in order (`ids[n - 1]` is item `n`'s id). `None` when +/// Windows has no menu to give. Win32 command ids are 16-bit: items past the 65,535th are left +/// out. +unsafe fn build(menu: &PopupMenu, ids: &mut Vec<String>) -> Option<OwnedMenu> { + // SAFETY: the caller's thread owns the new menu; every string is NUL-terminated and copied. + // A submenu the menu took is the menu's to destroy; one it refused drops here. + unsafe { + let hmenu = OwnedMenu(CreatePopupMenu()); + if hmenu.0.is_null() { return None; } + for entry in &menu.entries { + match entry { + Entry::Item(item) => { + let Ok(command) = u16::try_from(ids.len() + 1) else { break }; + let flags = MF_STRING | if item.enabled { 0 } else { MF_GRAYED } | if item.checked { MF_CHECKED } else { 0 }; + if AppendMenuW(hmenu.0, flags, usize::from(command), wide(&label(item)).as_ptr()) != 0 { + ids.push(item.id.clone()); + } + } + Entry::Separator => { AppendMenuW(hmenu.0, MF_SEPARATOR, 0, std::ptr::null()); } + Entry::Submenu(title, menu, enabled) => { + let Some(submenu) = build(menu, ids) else { continue }; + let flags = MF_STRING | MF_POPUP | if *enabled { 0 } else { MF_GRAYED }; + if AppendMenuW(hmenu.0, flags, submenu.0 as usize, wide(&escape(title)).as_ptr()) != 0 { + std::mem::forget(submenu); + } + } + } + } + Some(hmenu) + } +} + +/// An item's title, with its shortcut hint right-aligned after a tab, as Windows draws it. +fn label(item: &PopupItem) -> String { + let title = escape(&item.title); + match &item.key_equivalent { + Some(shortcut) => format!("{title}\t{}", shortcut.menu_keycaps().join("+")), + None => title, + } +} + +/// A title as Windows shows it literally: `&` would underline the next letter, and a tab would +/// start the shortcut column. +fn escape(title: &str) -> String { title.replace('&', "&&").replace('\t', " ") } + +fn wide(s: &str) -> Vec<u16> { s.encode_utf16().chain(Some(0)).collect() } + +#[cfg(test)] +#[path = "win32_tests.rs"] +mod tests; diff --git a/app/vendor/rune/crates/rune/src/popup_menu/win32_tests.rs b/app/vendor/rune/crates/rune/src/popup_menu/win32_tests.rs new file mode 100644 index 0000000..132c864 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/popup_menu/win32_tests.rs @@ -0,0 +1,114 @@ +#![allow(unsafe_code)] + +use std::sync::{Arc, atomic::{AtomicUsize, Ordering}}; + +use windows_sys::Win32::Foundation::{HWND, LPARAM, LRESULT, WPARAM}; +use windows_sys::Win32::System::LibraryLoader::GetModuleHandleW; +use windows_sys::Win32::UI::WindowsAndMessaging::{ + CreateWindowExW, DefWindowProcW, DestroyWindow, DispatchMessageW, HWND_MESSAGE, MSG, + PM_REMOVE, PeekMessageW, RegisterClassW, WNDCLASSW, +}; + +use super::{hands_back, start, turn, turns, wide}; + +unsafe extern "system" fn test_wndproc(hwnd: HWND, msg: u32, w: WPARAM, l: LPARAM) -> LRESULT { + // SAFETY: plain default window procedure for a test message-only window. + unsafe { DefWindowProcW(hwnd, msg, w, l) } +} + +fn message_window() -> HWND { + let class = wide("RuneModalLoopTest"); + // SAFETY: registers a simple message-only window class on this thread and creates one window. + unsafe { + let instance = GetModuleHandleW(std::ptr::null()); + let wc = WNDCLASSW { + lpfnWndProc: Some(test_wndproc), + hInstance: instance, + lpszClassName: class.as_ptr(), + ..std::mem::zeroed() + }; + RegisterClassW(&wc); + let hwnd = CreateWindowExW( + 0, class.as_ptr(), std::ptr::null(), 0, 0, 0, 0, 0, + HWND_MESSAGE, std::ptr::null_mut(), instance, std::ptr::null(), + ); + assert!(!hwnd.is_null(), "CreateWindowExW failed"); + hwnd + } +} + +#[test] +fn modal_turn_trampoline_blocks_reentrancy_and_keeps_outer_timer_alive() { + let hwnd = message_window(); + + // 1. Re-entrancy: a turn callback firing while a turn is already on the stack must be ignored + // (and must not panic if `start` is called or if `turn` re-enters). + let calls = Arc::new(AtomicUsize::new(0)); + let calls_inner = calls.clone(); + let raw_hwnd = hwnd as usize; + start(Arc::new(move || { + let n = calls_inner.fetch_add(1, Ordering::SeqCst); + if n == 0 { + // Simulate a nested WM_TIMER firing `turn` while the first turn is still running. + // SAFETY: invoking the Win32 TIMERPROC with benign test arguments on this thread. + unsafe { turn(raw_hwnd as HWND, 0, 0, 0); } + } + })); + // SAFETY: invoking the Win32 TIMERPROC on this thread. + unsafe { turn(hwnd, 0, 0, 0); } + assert_eq!(calls.load(Ordering::SeqCst), 1, "re-entrant timer trampoline must not nest"); + + // 2. Nested `Turns` on the same HWND: dropping the inner guard must not kill the outer timer. + let fired = Arc::new(AtomicUsize::new(0)); + let fired_inner = fired.clone(); + start(Arc::new(move || { fired_inner.fetch_add(1, Ordering::SeqCst); })); + let outer = turns(hwnd); + let inner = turns(hwnd); + drop(inner); + + let deadline = crate::time::now() + std::time::Duration::from_millis(250); + while fired.load(Ordering::SeqCst) == 0 && crate::time::now() < deadline { + std::thread::sleep(std::time::Duration::from_millis(10)); + // SAFETY: pumps messages for this thread's test window. + unsafe { + let mut msg: MSG = std::mem::zeroed(); + while PeekMessageW(&mut msg, hwnd, 0, 0, PM_REMOVE) != 0 { + DispatchMessageW(&msg); + } + } + } + let count = fired.load(Ordering::SeqCst); + drop(outer); + // SAFETY: destroys the message-only window created in this test. + unsafe { DestroyWindow(hwnd); } + assert!(count > 0, "dropping an inner Turns guard must not kill the outer modal timer"); +} + +#[test] +fn modal_menu_guard_prevents_reentrant_menu_loops_and_turns_handles_destroyed_hwnd() { + let outer = super::enter_menu_loop(); + assert!(outer.is_some()); + assert!(super::enter_menu_loop().is_none(), "nested modal menu loop must be refused"); + drop(outer); + assert!(super::enter_menu_loop().is_some(), "next modal menu loop succeeds once the previous ends"); + + let hwnd = message_window(); + let guard = turns(hwnd); + // Destroy the window while the modal timer guard is still alive; dropping must not fail or + // touch a dead window handle. + // SAFETY: destroys the message-only window created above. + unsafe { DestroyWindow(hwnd); } + drop(guard); +} + +/// An overlay's menu gives the foreground back to the window that had it, whatever the overlay's +/// `KeyPolicy`: the decision reads only whether the owner is an overlay, not its styles. +#[test] +fn an_overlay_menu_hands_the_foreground_back() { + let (owner, other, third): (HWND, HWND, HWND) = (std::ptr::without_provenance_mut(1), std::ptr::without_provenance_mut(2), std::ptr::without_provenance_mut(3)); + assert!(hands_back(true, other, owner, owner), "took it for the menu"); + assert!(!hands_back(false, other, owner, owner), "an ordinary window keeps what it took"); + assert!(!hands_back(true, owner, owner, owner), "had it before the menu (an OnDemand overlay the user clicked)"); + assert!(!hands_back(true, std::ptr::null_mut(), owner, owner), "nothing to give it back to"); + assert!(!hands_back(true, other, owner, third), "the foreground moved on meanwhile"); +} diff --git a/app/vendor/rune/crates/rune/src/quit.rs b/app/vendor/rune/crates/rune/src/quit.rs new file mode 100644 index 0000000..2372421 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/quit.rs @@ -0,0 +1,278 @@ +//! The app quitting, as one signal whatever starts it: `Tx::quit` or `AppHandle::quit` from any +//! window, the last window closing, macOS Quit (?Q, the Dock, logout and shutdown, which AppKit +//! asks the app delegate about with `applicationShouldTerminate:`), and a Windows logoff or +//! shutdown (`WM_QUERYENDSESSION`, then `WM_ENDSESSION`). Every open window's `App::on_quit` +//! runs once when it starts, before any window closes for it, and [`quitting`] holds from then +//! on, so a window's `on_close` can tell the app ending from the user closing that one window. +//! +//! One machine ([`State`], [`step`]) holds where the quit is: running, quitting (the windows' +//! hooks owed, then run, and whether the app starts again after, `Tx::relaunch`), done. The hooks run in the event loop (`Windows`, which carries out +//! the effects). Windows sends its session messages to a window and waits for the answer, and +//! may end the process once every `WM_ENDSESSION` has returned, so the session window (`win32`) +//! wakes the loop and runs it until the hooks have run before it answers; when it comes while +//! a loop handler runs (a modal loop inside one), it can only end that loop and let the hooks +//! run once the handler returns. + +use std::sync::Mutex; + +#[cfg(target_os = "macos")] +mod mac; +pub(crate) mod relaunch; +#[cfg(target_os = "windows")] +mod win32; + +/// Where the app's quit is. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum State { + /// The app runs. + Running, + /// A quit started; the windows' hooks are owed or ran, and what follows the exit. + Quitting(Hooks, After), + /// The session ends now (a logoff): the windows closed as their close buttons would, and + /// the loop is ending. + Closed, + /// The loop ended. + Done, +} + +/// The windows' `App::on_quit` hooks, for a quit. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum Hooks { + /// Not run yet. + Owed, + /// Every open window ran its hook. + Ran, +} + +/// What follows a quit's exit: nothing, or the app starting again (`Tx::relaunch`). A relaunch +/// asked during a quit outranks the plain exit. +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)] +pub(crate) enum After { + Exit, + Relaunch, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum Event { + /// Something asks to quit: `Tx::quit` or `Tx::relaunch`, the last window closing, macOS + /// terminating, a Windows session query (`ending: false`) or its end (`ending: true`). + Start { ending: bool, after: After }, + /// The loop ran every window's hook. + HooksRan, + /// The loop closed the windows for the session's end (`Effect::CloseAndExit`). + WindowsClosed, + /// The system took the quit back (another app refused a logoff): the app runs on. + Cancel, + /// The event loop ended. + Exited, +} + +/// What the loop does for a step, in order. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum Effect { + /// Every open window runs `App::on_quit`, then the loop sends `Event::HooksRan`. + RunHooks, + /// Every open window closes as its close button would, the loop sends + /// `Event::WindowsClosed` and ends. + CloseAndExit, + /// The loop ended for a relaunch: start the app again (`crate::relaunch`). + Relaunch, +} + +pub(crate) fn step(state: State, event: Event) -> (State, Vec<Effect>) { + use {Effect::*, Event::*, State::*}; + let close = |ending: bool| if ending { vec![CloseAndExit] } else { vec![] }; + match (state, event) { + (Done, _) => (Done, vec![]), + (Quitting(_, After::Relaunch), Exited) => (Done, vec![Relaunch]), + (_, Exited) => (Done, vec![]), + // A session ending closed the windows: the system ends the app, and nothing restarts it. + (Closed, _) => (Closed, vec![]), + (Running, Start { ending, after }) => (Quitting(Hooks::Owed, after), [vec![RunHooks], close(ending)].concat()), + (Quitting(Hooks::Owed, was), Start { ending, after }) => (Quitting(Hooks::Owed, was.max(after)), [vec![RunHooks], close(ending)].concat()), + (Quitting(Hooks::Ran, was), Start { ending, after }) => (Quitting(Hooks::Ran, was.max(after)), close(ending)), + (Quitting(_, after), HooksRan) => (Quitting(Hooks::Ran, after), vec![]), + (Quitting(..), WindowsClosed) => (Closed, vec![]), + (Running | Quitting(..), Cancel) => (Running, vec![]), + (Running, HooksRan | WindowsClosed) => (Running, vec![]), + } +} + +static STATE: Mutex<State> = Mutex::new(State::Running); +static FAST_EXIT: std::sync::OnceLock<fn()> = std::sync::OnceLock::new(); + +/// How a quitting app ends: fast, unless it asked for an orderly exit (`orderly_exit`). +static ORDERLY: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + +/// What a fast exit runs last: once the app has quit, every window has hidden (as the quit +/// started) and run its `App::on_quit`, the clipboard has handed over what it holds, tray icons +/// have left the notification area and a relaunch has started, `last` runs (the app's final +/// durable write, a trace) and the process ends at once. Windows, GPU devices, threads and memory +/// aren't dropped: the OS takes them back, which on Windows skips tens to hundreds of milliseconds +/// of destructors and graphics-driver `DllMain` detach, and a window is gone the moment its quit +/// is done. Every app ends this way unless it calls [`orderly_exit`]; `fast_exit` only adds +/// `last`. Nothing after the event loop returns runs, so whatever the app does there belongs in +/// `last` or its quit hooks. Set it once, before the app runs; a later call does nothing. On the +/// web the page's own lifetime applies instead. +pub fn fast_exit(last: fn()) { + FAST_EXIT.set(last).ok(); +} + +/// Tears the process down in order when the app quits instead of ending it at once (the default, +/// [`fast_exit`]): windows, GPU devices and threads are dropped and `run` returns, for an app with +/// work after `run` or destructors that must run. Call it before the app runs. +pub fn orderly_exit() { + ORDERLY.store(true, std::sync::atomic::Ordering::Relaxed); +} + +/// The app's last step before a fast exit: its `fast_exit`, or nothing; none for an orderly exit. +#[cfg(not(target_arch = "wasm32"))] +pub(crate) fn fast_exit_hook() -> Option<fn()> { + if ORDERLY.load(std::sync::atomic::Ordering::Relaxed) { return None; } + Some(FAST_EXIT.get().copied().unwrap_or(|| {})) +} +/// A fast exit, once the windows' hooks ran and the loop is ending: what must leave the system +/// tidy goes in order (the clipboard's hand-over, tray icons, a relaunch), then the app's +/// `last`, then the process ends without dropping a window, a device or an allocation. +#[cfg(not(target_arch = "wasm32"))] +pub(crate) fn end_fast(last: fn()) -> ! { + // The windows go now, not when the process's threads are torn down. + #[cfg(target_os = "windows")] + crate::platform::win32::destroy_own_windows(); + // What the loop's end does for an orderly exit (`event_loop::run_configured`). + crate::tooling::interaction::flush(); + crate::platform::ready_signal::clear(); + crate::clipboard::shutdown(); + crate::tray::remove_all(); + if send(Event::Exited).contains(&Effect::Relaunch) { + relaunch::spawn(); + } + #[cfg(any(target_os = "windows", target_os = "linux"))] + crate::open_url::instance::exited(); + crate::marks::mark("quit.last"); + last(); + end_process() +} + +/// Ends this process now with exit code 0 (3 when `RUNE_LOOP_CHECK=2` found a differing picture, +/// `render::pixel_check`): no destructors, no `atexit`, no DLL detach. +#[cfg(not(target_arch = "wasm32"))] +#[allow(unsafe_code)] +fn end_process() -> ! { + crate::marks::mark("quit.end"); + let code = if crate::render::loop_pixel_check_failed() { 3 } else { 0 }; + // A process ends once each of its threads has run to its end: an idle-priority one (D3D12's + // shader threads) on a busy machine can hold it for seconds. + #[cfg(target_os = "windows")] + crate::platform::win32::raise_threads(|_| true, windows_sys::Win32::System::Threading::THREAD_PRIORITY_NORMAL); + #[cfg(target_os = "windows")] + // SAFETY: the pseudo-handle names this process; TerminateProcess on it doesn't return. + unsafe { + use windows_sys::Win32::System::Threading::{GetCurrentProcess, TerminateProcess}; + TerminateProcess(GetCurrentProcess(), code as u32); + } + #[cfg(unix)] + // SAFETY: `_exit` ends the process without running anything of this process's. + unsafe { libc::_exit(code) } + #[allow(unreachable_code)] + std::process::exit(code) +} + +/// Steps the app's quit, returning what the loop must do. +pub(crate) fn send(event: Event) -> Vec<Effect> { + let mut state = STATE.lock().unwrap_or_else(|e| e.into_inner()); + let (next, effects) = step(*state, event); + if *state == State::Running && matches!(next, State::Quitting(..)) { + crate::marks::mark("quit.start"); + #[cfg(not(target_arch = "wasm32"))] + watch_quit(); + } + *state = next; + effects +} + +/// A quit still running this long after it started says where it is on stderr, and again as long +/// as it runs: the last step it reached and, on Windows, the threads still alive. +#[cfg(not(target_arch = "wasm32"))] +const QUIT_REPORT_EVERY: std::time::Duration = std::time::Duration::from_secs(3); + +#[cfg(not(target_arch = "wasm32"))] +fn watch_quit() { + let started = crate::time::now(); + std::thread::Builder::new().name("rune-quit-watch".into()).spawn(move || loop { + std::thread::sleep(QUIT_REPORT_EVERY); + eprintln!("rune: still quitting {} ms after the quit started: {}", started.elapsed().as_millis(), where_the_quit_is()); + }).ok(); +} + +/// Ends the process `after` from now if it's still alive then, saying on stderr what it was +/// waiting for (the last step it reached, the threads still alive) and marking `quit.deadline`. +/// For an app to call once nothing of its own is left to lose, after its storage has closed, so +/// that a quit always ends. +#[cfg(not(target_arch = "wasm32"))] +pub fn exit_deadline(after: std::time::Duration) { + std::thread::Builder::new().name("rune-exit-deadline".into()).spawn(move || { + std::thread::sleep(after); + eprintln!("rune: the quit didn't end within {} ms of the app's last step, so the process ends itself: {}", after.as_millis(), where_the_quit_is()); + crate::marks::mark("quit.deadline"); + end_process(); + }).ok(); +} + +/// The quit's last step reached and how long ago, and the process's threads. +#[cfg(not(target_arch = "wasm32"))] +fn where_the_quit_is() -> String { + let last = crate::marks::marks().into_iter().last().map_or_else(|| "no step".to_owned(), |(name, at)| format!("last step {name}, {} ms ago", at.elapsed().as_millis())); + #[cfg(target_os = "windows")] + return format!("{last}; threads: {}", crate::platform::win32::threads_summary()); + #[cfg(not(target_os = "windows"))] + last +} + +pub(crate) fn state() -> State { *STATE.lock().unwrap_or_else(|e| e.into_inner()) } + +/// Whether the app is quitting: a quit started and the system didn't cancel it. A window's +/// `on_close` that runs while this holds closes because the app ends, so it keeps what it would +/// forget when the user closes it alone (an app reopening its windows next launch keeps that +/// window's place in the list). False while the app runs, including when its last window +/// closes, whose `on_close` runs before the quit starts. +pub fn quitting() -> bool { + !matches!(state(), State::Running) +} + +/// Hooks the system's quit requests into the loop: `send` delivers a quit (`true` when the +/// session ends now and the windows must close) to `Windows`. Once per process, on the UI thread. +#[cfg_attr(target_arch = "wasm32", allow(dead_code))] +pub(crate) fn install(send: impl Fn(bool) -> bool + 'static) { + #[cfg(target_os = "windows")] + win32::install(send); + #[cfg(target_os = "macos")] + { let _ = send; mac::install(); } + #[cfg(not(any(target_os = "windows", target_os = "macos")))] + let _ = send; +} + +/// Whether the event loop is inside one of its handlers, on the UI thread: a session message +/// that arrives then (from a modal loop the handler runs) can't run the windows' hooks. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum Loop { + Idle, + Handling, +} + +thread_local! { + static LOOP: std::cell::Cell<Loop> = const { std::cell::Cell::new(Loop::Idle) }; +} + +/// Marks the loop handling an event until the guard drops. +#[cfg_attr(target_arch = "wasm32", allow(dead_code))] +pub(crate) fn handling() -> Handling { Handling(LOOP.replace(Loop::Handling)) } + +#[cfg_attr(not(target_os = "windows"), allow(dead_code))] +pub(crate) fn loop_state() -> Loop { LOOP.get() } + +pub(crate) struct Handling(Loop); + +impl Drop for Handling { + fn drop(&mut self) { LOOP.set(self.0); } +} diff --git a/app/vendor/rune/crates/rune/src/quit/mac.rs b/app/vendor/rune/crates/rune/src/quit/mac.rs new file mode 100644 index 0000000..bd08e48 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/quit/mac.rs @@ -0,0 +1,63 @@ +//! AppKit asks the app delegate `applicationShouldTerminate:` before every quit: ⌘Q, the Dock's +//! Quit, logout, restart and shutdown. winit's delegate doesn't implement it, so Rune adds the +//! method to the delegate's class once (as `platform::reopen` does for reopening). It marks the +//! app quitting and lets the quit go ahead; `applicationWillTerminate:` follows at once, where +//! winit ends the loop and `Windows::exiting` runs every window's `App::on_quit`, then its +//! `on_close`. + +#![allow(unsafe_code)] + +use std::cell::Cell; +use std::ffi::{c_char, c_void}; + +use objc2::runtime::{AnyClass, AnyObject, Bool, Sel}; +use objc2::{MainThreadMarker, msg_send, sel}; +use objc2_app_kit::NSApplication; + +thread_local! { + /// The delegate class Rune added the method to. + static HOOKED: Cell<*const AnyClass> = const { Cell::new(std::ptr::null()) }; +} + +unsafe extern "C" { + fn class_addMethod(class: *const AnyClass, selector: Sel, implementation: *const c_void, types: *const c_char) -> Bool; +} + +/// `NSTerminateNow`. +const TERMINATE_NOW: usize = 1; + +extern "C" fn should_terminate(_: *mut AnyObject, _: Sel, _: *mut AnyObject) -> usize { + // Windows::exiting carries out the quit's effects. + let _ = super::send(super::Event::Start { ending: false, after: super::After::Exit }); + TERMINATE_NOW +} + +pub(super) fn install() { + let Some(mtm) = MainThreadMarker::new() else { return }; + let app = NSApplication::sharedApplication(mtm); + let selector = sel!(applicationShouldTerminate:); + // SAFETY: AppKit calls and runtime changes on the main thread. The added function has the + // selector's ABI (`NSApplicationTerminateReply` is an `NSUInteger`, `Q` on 64-bit), and + // adding a method the class lacks leaves its other methods and instances alone. + unsafe { + let delegate: *mut AnyObject = msg_send![&app, delegate]; + let Some(delegate) = delegate.as_ref() else { return }; + let class = delegate.class(); + if HOOKED.with(|hooked| std::ptr::eq(hooked.get(), class)) { + return; + } + // A later winit, or an app's own delegate, decides itself. + let answers: bool = msg_send![delegate, respondsToSelector: selector]; + if answers { + return; + } + let imp = should_terminate as extern "C" fn(*mut AnyObject, Sel, *mut AnyObject) -> usize; + if !class_addMethod(class, selector, imp as *const c_void, c"Q@:@".as_ptr()).as_bool() { + eprintln!("rune: could not add the terminate method to the app delegate"); + return; + } + HOOKED.with(|hooked| hooked.set(class)); + // AppKit caches which optional methods its delegate answers when it is set. + let _: () = msg_send![&app, setDelegate: delegate]; + } +} diff --git a/app/vendor/rune/crates/rune/src/quit/relaunch.rs b/app/vendor/rune/crates/rune/src/quit/relaunch.rs new file mode 100644 index 0000000..8bcbb2f --- /dev/null +++ b/app/vendor/rune/crates/rune/src/quit/relaunch.rs @@ -0,0 +1,173 @@ +//! Starting the app again after it quits (`Tx::relaunch`, `AppHandle::relaunch`), as Electron's +//! `app.relaunch()` does. Once the event loop has ended for a relaunch (`crate::quit`), this +//! process starts its own executable again with its arguments and working folder, and the new +//! process waits for this one to exit before it goes on ([`wait_for_previous`], from +//! [`single_instance`](crate::single_instance) and the event loop's start), so it finds the +//! app's single-instance claim, files and windows free, as Electron's relauncher waits for the +//! old process. macOS starts an app bundle again through Launch Services (`open -n`), as the +//! Finder does, so it comes forward as a launch does. + +/// The variable that tells a relaunched process the pid it waits for. +const AFTER: &str = "RUNE_RELAUNCH_AFTER"; +/// The variable that tells a launch handed on by a quitting process (`spawn_with`) that process's +/// pid: it claims the instance once that one lets go of it, not once it has exited. +#[cfg(any(target_os = "windows", target_os = "linux"))] +const HANDED: &str = "RUNE_INSTANCE_HANDED"; +/// The longest a relaunched process waits for the previous one. +const WAIT: std::time::Duration = std::time::Duration::from_secs(10); + +/// Starts this app again, to go on once this process has exited. Errors are logged: the app +/// is quitting either way. +pub(crate) fn spawn() { + #[cfg(not(target_arch = "wasm32"))] + if let Err(e) = start(std::env::args_os().skip(1).collect(), AFTER) { + eprintln!("rune: couldn't start the app again: {e}"); + } +} + +/// Starts this app with another launch's arguments: a launch that reached this process while it +/// quits (`single_instance`). The new process claims the instance as soon as this one lets go of +/// it (`release_instance`), and starts meanwhile. +#[cfg(any(target_os = "windows", target_os = "linux"))] +pub(crate) fn spawn_with(args: Vec<String>) { + if let Err(e) = start(args.into_iter().map(Into::into).collect(), HANDED) { + eprintln!("rune: couldn't start the app for a launch that came while it quit: {e}"); + } +} + +/// The quitting process that handed this launch on (`spawn_with`), once. +#[cfg(any(target_os = "windows", target_os = "linux"))] +pub(crate) fn handed_from() -> Option<u32> { + std::env::var_os(HANDED).and_then(|v| v.to_str().and_then(|v| v.parse::<u32>().ok())).filter(|pid| *pid != std::process::id()) +} + +#[cfg(not(target_arch = "wasm32"))] +fn start(args: Vec<std::ffi::OsString>, wait_var: &str) -> std::io::Result<()> { + use std::process::{Command, Stdio}; + let exe = std::env::current_exe()?; + let pid = std::process::id().to_string(); + #[cfg(target_os = "macos")] + if let Some(bundle) = bundle_of(&exe) { + let status = Command::new("/usr/bin/open").arg("-n").arg(&bundle).arg("--env").arg(format!("{wait_var}={pid}")).arg("--args").args(&args).status()?; + return if status.success() { Ok(()) } else { Err(std::io::Error::other(format!("open -n exited with {status}"))) }; + } + let mut cmd = Command::new(&exe); + // Only this launch's wait goes to the new process, not one this process was started with. + cmd.args(&args).env_remove(AFTER); + #[cfg(any(target_os = "windows", target_os = "linux"))] + cmd.env_remove(HANDED); + cmd.env(wait_var, &pid).stdin(Stdio::null()).stdout(Stdio::null()).stderr(Stdio::null()); + if let Ok(dir) = std::env::current_dir() { cmd.current_dir(dir); } + #[cfg(target_os = "windows")] + { + use std::os::windows::process::CommandExt; + const DETACHED_PROCESS: u32 = 0x0000_0008; + const CREATE_NEW_PROCESS_GROUP: u32 = 0x0000_0200; + const CREATE_BREAKAWAY_FROM_JOB: u32 = 0x0100_0000; + // Out of any job this process runs in, so the new one outlives it; a job that refuses + // the breakaway still starts it inside. + let flags = DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP; + if cmd.creation_flags(flags | CREATE_BREAKAWAY_FROM_JOB).spawn().is_ok() { return Ok(()); } + cmd.creation_flags(flags); + } + cmd.spawn().map(drop) +} + +/// The `.app` an executable in `Contents/MacOS` belongs to. +#[cfg(target_os = "macos")] +fn bundle_of(exe: &std::path::Path) -> Option<std::path::PathBuf> { + let macos = exe.parent().filter(|p| p.file_name().is_some_and(|n| n == "MacOS"))?; + let bundle = macos.parent().filter(|p| p.file_name().is_some_and(|n| n == "Contents"))?.parent()?; + bundle.extension().is_some_and(|e| e == "app").then(|| bundle.to_path_buf()) +} + +/// A relaunched process waits here, once, for the process that started it to exit, for at most +/// ten seconds. Any other launch goes straight on. +pub(crate) fn wait_for_previous() { + #[cfg(not(target_arch = "wasm32"))] + { + static ONCE: std::sync::Once = std::sync::Once::new(); + ONCE.call_once(|| { + let Some(pid) = std::env::var_os(AFTER).and_then(|v| v.to_str().and_then(|v| v.parse::<u32>().ok())) else { return }; + if pid != std::process::id() { wait(pid); } + }); + } +} + +#[cfg(target_os = "windows")] +#[allow(unsafe_code)] +fn wait(pid: u32) { + use windows_sys::Win32::Foundation::CloseHandle; + use windows_sys::Win32::System::Threading::{OpenProcess, PROCESS_SYNCHRONIZE, WaitForSingleObject}; + // SAFETY: a plain handle request; a process that already exited answers null. The handle is + // closed once. + unsafe { + let handle = OpenProcess(PROCESS_SYNCHRONIZE, 0, pid); + if handle.is_null() { return; } + WaitForSingleObject(handle, WAIT.as_millis() as u32); + CloseHandle(handle); + } +} + +/// Whether process `pid` still holds what it holds: its process object isn't signalled yet. A +/// process that was terminated has its exit code at once, but it is signalled only after the +/// kernel has closed its handles (its instance pipe, its file locks), which can take a while: a +/// process in between is still here, and is [`ending`]. +#[cfg(target_os = "windows")] +pub(crate) fn alive(pid: u32) -> bool { + process(pid).is_some_and(|(signalled, _)| !signalled) +} + +/// Whether process `pid` has an exit code but hasn't closed its handles yet: a launch that finds +/// its pipe waits for the name to come free rather than taking another. +#[cfg(target_os = "windows")] +pub(crate) fn ending(pid: u32) -> bool { + process(pid).is_some_and(|(signalled, running)| !signalled && !running) +} + +/// `pid`'s process object: whether it is signalled, and whether its exit code is still +/// `STILL_ACTIVE`. None when it is gone (or can't be opened). +#[cfg(target_os = "windows")] +#[allow(unsafe_code)] +fn process(pid: u32) -> Option<(bool, bool)> { + use windows_sys::Win32::Foundation::{CloseHandle, STILL_ACTIVE, WAIT_TIMEOUT}; + use windows_sys::Win32::System::Threading::{GetExitCodeProcess, OpenProcess, PROCESS_QUERY_LIMITED_INFORMATION, PROCESS_SYNCHRONIZE, WaitForSingleObject}; + // SAFETY: a plain handle request; a process that already exited answers null. The handle is + // closed once; the exit code is written into `code`. + unsafe { + let handle = OpenProcess(PROCESS_SYNCHRONIZE | PROCESS_QUERY_LIMITED_INFORMATION, 0, pid); + if handle.is_null() { + return None; + } + let signalled = WaitForSingleObject(handle, 0) != WAIT_TIMEOUT; + let mut code = 0; + let running = GetExitCodeProcess(handle, &mut code) != 0 && code == STILL_ACTIVE as u32; + CloseHandle(handle); + Some((signalled, running)) + } +} + +#[cfg(all(not(target_os = "windows"), not(target_arch = "wasm32")))] +fn wait(pid: u32) { + let deadline = crate::time::now() + WAIT; + while alive(pid) && crate::time::now() < deadline { + std::thread::sleep(std::time::Duration::from_millis(25)); + } +} + +#[cfg(all(unix, not(target_os = "linux")))] +#[allow(unsafe_code)] +fn alive(pid: u32) -> bool { + // SAFETY: signal 0 only checks that the process exists. + unsafe { libc::kill(pid as libc::pid_t, 0) == 0 } +} + +#[cfg(target_os = "linux")] +pub(crate) fn alive(pid: u32) -> bool { + std::path::Path::new(&format!("/proc/{pid}")).exists() +} + +#[cfg(not(any(unix, target_os = "windows")))] +fn alive(_pid: u32) -> bool { + false +} diff --git a/app/vendor/rune/crates/rune/src/quit/win32.rs b/app/vendor/rune/crates/rune/src/quit/win32.rs new file mode 100644 index 0000000..9b1c57a --- /dev/null +++ b/app/vendor/rune/crates/rune/src/quit/win32.rs @@ -0,0 +1,144 @@ +//! A hidden top-level window that hears a Windows logoff or shutdown. Windows asks every +//! top-level window whether the session may end (`WM_QUERYENDSESSION`), then tells each +//! whether it does (`WM_ENDSESSION`); a message-only window hears neither, and the app's own +//! windows come and go. Restart Manager's requests to close the app (`ENDSESSION_CLOSEAPP`, an +//! installer or an update) arrive the same way. +//! +//! Neither message waits in the queue: Windows sends it and waits for the answer, and once every +//! window answered `WM_ENDSESSION` it may end the process at any moment. So the window starts +//! the quit (`quitting` holds from then on), wakes the loop and runs it here, as a modal loop +//! does, until `Windows` has run the hooks, for at most `WAIT`. +//! +//! A message can also come while one of the loop's handlers runs, from a modal loop inside it +//! or a synchronous send. winit then holds the wake until the handler returns, and a paint run +//! from here would re-enter it, so the window runs no loop: it ends a tracking menu (the usual +//! modal loop) and answers, and the hooks run as the handler returns, before `WM_ENDSESSION`. + +#![allow(unsafe_code)] + +use std::cell::RefCell; +use std::time::Duration; + +use windows_sys::Win32::Foundation::{HWND, LPARAM, LRESULT, TRUE, WPARAM}; +use windows_sys::Win32::System::LibraryLoader::GetModuleHandleW; +use windows_sys::Win32::UI::WindowsAndMessaging::{ + CreateWindowExW, DefWindowProcW, DispatchMessageW, EndMenu, MSG, MsgWaitForMultipleObjects, PM_REMOVE, PeekMessageW, + PostQuitMessage, QS_ALLINPUT, RegisterClassW, TranslateMessage, WM_ENDSESSION, WM_QUERYENDSESSION, WM_QUIT, WNDCLASSW, + WS_EX_TOOLWINDOW, +}; + +use super::{Event, Hooks, Loop, State}; + +/// How long the window runs the loop for the hooks before it answers anyway: Windows shows +/// that the app is preventing shutdown after five seconds. +const WAIT: Duration = Duration::from_secs(3); + +type Deliver = Box<dyn Fn(bool) -> bool>; + +thread_local! { + /// Sends a quit to the loop (`true`: the session ends now); false once the loop is gone. + static DELIVER: RefCell<Option<Deliver>> = const { RefCell::new(None) }; + static WINDOW: std::cell::Cell<HWND> = const { std::cell::Cell::new(std::ptr::null_mut()) }; +} + +pub(super) fn install(deliver: impl Fn(bool) -> bool + 'static) { + DELIVER.with(|d| *d.borrow_mut() = Some(Box::new(deliver))); + if !WINDOW.get().is_null() { + return; + } + let class: Vec<u16> = "RuneSession\0".encode_utf16().collect(); + // SAFETY: the class name is NUL-terminated and outlives both calls; the window lives as + // long as the process, on this (the UI) thread, and keeps no pointer to Rust state. + let window = unsafe { + let instance = GetModuleHandleW(std::ptr::null()); + let wc = WNDCLASSW { lpfnWndProc: Some(procedure), hInstance: instance, lpszClassName: class.as_ptr(), ..std::mem::zeroed() }; + RegisterClassW(&wc); + // Never shown, and a tool window, so nothing lists it: not the taskbar, Alt+Tab or a + // relaunch looking for the app's front window. + CreateWindowExW(WS_EX_TOOLWINDOW, class.as_ptr(), std::ptr::null(), 0, 0, 0, 0, 0, std::ptr::null_mut(), std::ptr::null_mut(), instance, std::ptr::null()) + }; + if window.is_null() { + eprintln!("rune: could not create the session window; a logoff won't run App::on_quit"); + } + WINDOW.set(window); +} + +unsafe extern "system" fn procedure(hwnd: HWND, message: u32, w: WPARAM, l: LPARAM) -> LRESULT { + match message { + WM_QUERYENDSESSION => { + answer(false); + TRUE as LRESULT + } + WM_ENDSESSION => { + if w != 0 { + answer(true); + } else { + // Another app refused, or the user cancelled: the app runs on. + super::send(Event::Cancel); + } + 0 + } + // SAFETY: the parameters are the ones Windows passed. + _ => unsafe { DefWindowProcW(hwnd, message, w, l) }, + } +} + +/// Starts the quit and has the loop run the hooks, before the answer when the loop can run. +fn answer(ending: bool) { + // The loop carries out the effects when the quit reaches it. + let _ = super::send(Event::Start { ending, after: super::After::Exit }); + let sent = DELIVER.with(|d| d.try_borrow().ok().and_then(|d| d.as_ref().map(|d| d(ending)))).unwrap_or(false); + match super::loop_state() { + Loop::Handling => { + // SAFETY: ends whatever menu this thread tracks; nothing when none does. + unsafe { EndMenu() }; + if ending && !answered(ending) { + eprintln!("rune: the session ended inside a loop handler, before the windows' App::on_quit ran"); + } + } + Loop::Idle if sent => run_loop(ending), + Loop::Idle => {} + } +} + +/// The loop did what the message asks: ran the hooks, and when the session ends now, closed the +/// windows too. A cancelled or finished quit asks nothing more. +fn answered(ending: bool) -> bool { + match super::state() { + State::Quitting(Hooks::Ran, _) => !ending, + State::Quitting(Hooks::Owed, _) => false, + State::Running | State::Closed | State::Done => true, + } +} + +/// Runs the loop's messages until `Windows` answered the message, for at most `WAIT`. +fn run_loop(ending: bool) { + let ran = std::panic::catch_unwind(|| { + let deadline = crate::time::now() + WAIT; + while !answered(ending) { + let left = deadline.saturating_duration_since(crate::time::now()); + if left.is_zero() { + eprintln!("rune: the session ends before the windows' App::on_quit ran"); + break; + } + // SAFETY: `msg` is written by PeekMessageW before it is read; dispatching on the + // thread that owns the windows is what its own loop does. + unsafe { + let mut msg: MSG = std::mem::zeroed(); + if PeekMessageW(&mut msg, std::ptr::null_mut(), 0, 0, PM_REMOVE) == 0 { + MsgWaitForMultipleObjects(0, std::ptr::null(), 0, left.as_millis() as u32, QS_ALLINPUT); + continue; + } + if msg.message == WM_QUIT { + PostQuitMessage(msg.wParam as i32); + break; + } + TranslateMessage(&msg); + DispatchMessageW(&msg); + } + } + }); + if ran.is_err() { + eprintln!("rune: a quit hook panicked during a logoff"); + } +} diff --git a/app/vendor/rune/crates/rune/src/render.rs b/app/vendor/rune/crates/rune/src/render.rs new file mode 100644 index 0000000..8780e5c --- /dev/null +++ b/app/vendor/rune/crates/rune/src/render.rs @@ -0,0 +1,696 @@ +//! The instanced wgpu renderer, with lazy bounded group layers and offscreen readback. + +use crate::pixels::ImageAtlas; +use crate::text::{ATLAS_SIZE, Atlas}; + +mod backdrop_blur; +mod breaker; +#[cfg(any(target_os = "windows", target_arch = "wasm32"))] +mod damaged; +mod device; +mod dxbc; +mod fill; +mod first_use; +mod gpu_loss; +mod instance; +mod layers; +mod metallib; +mod offscreen; +mod outlines; +mod pass; +mod pipelines; +// The kept frame it checks exists only where partial frames do (`damaged`). +#[cfg(any(target_os = "windows", target_arch = "wasm32"))] +mod pixel_check; +#[cfg(target_os = "macos")] +mod prewarm; +#[cfg(not(any(target_os = "macos", target_arch = "wasm32")))] +#[path = "render/warm.rs"] +mod prewarm; +#[cfg(target_arch = "wasm32")] +mod prewarm { + pub(super) fn start() {} + pub(super) fn take() -> Option<(super::Gpu, super::Renderer)> { None } + pub(super) fn discard() {} +} +mod uber_wgsl; +mod upload; +mod variant; +mod warmup; +#[cfg(target_os = "macos")] +mod windfoil_metallib; + +pub(crate) mod csd_corners; +pub(crate) mod gpu_events; +pub(crate) mod layer_blur; +pub(crate) mod surface_alpha; +pub(crate) mod translucency; + +pub mod cpu_boot; + +#[cfg(test)] +mod abi_tests; +#[cfg(test)] +mod backdrop_tests; +#[cfg(test)] +mod image_tests; +#[cfg(test)] +#[path = "render/native_surface_tests.rs"] +mod native_surface; +#[cfg(test)] +mod prewarm_tests; +#[cfg(test)] +#[path = "render/warm_tests.rs"] +mod warm_tests; + +use pass::{ActivePass, Backdrop}; + +#[cfg(target_os = "windows")] +pub(crate) use damaged::MAX_RECTS; +pub(crate) use device::choose_gpu_backend; +pub(crate) use device::discard_prewarm; +pub(crate) use instance::Globals; +pub(crate) use instance::INSTANCE_WORDS; +pub(crate) use instance::effect_mark; +pub(crate) use instance::end_layer; +pub(crate) use instance::pack_u64_f32; +pub(crate) use instance::turned_bounds; +pub(crate) use instance::unpack_u64_f32; +pub(crate) use instance::word; +pub(crate) use warmup::park_gpu; +pub(crate) use warmup::surface_gpu; + +pub use backdrop_blur::MAX_BACKDROP_BLURS; +pub use device::Gpu; +pub use device::prewarm_gpu; +pub use device::prewarm_gpu_on; +#[doc(hidden)] +pub use fill::FillDrift; +pub use first_use::make_layer_blur; +pub use first_use::make_straight_alpha; +pub use first_use::precompiled_misses; +pub use instance::Instance; +pub use instance::KIND_BACKDROP_BLUR; +pub use instance::KIND_DASHED; +pub use instance::KIND_EFFECT; +pub use instance::KIND_GLYPH; +pub use instance::KIND_GRADIENT; +pub use instance::KIND_IMAGE; +pub use instance::KIND_INSET; +pub use instance::KIND_LAYER; +pub use instance::KIND_LAYER_END; +pub use instance::KIND_RADIAL; +pub use instance::KIND_RECT; +pub use instance::KIND_SEGMENT; +pub use instance::KIND_SHADOW; +pub use instance::KIND_TRIANGLE; +pub use instance::Kind; +pub use instance::NO_CLIP; +pub(crate) use instance::STOP_FADE_BIAS; +pub use instance::pack_clip_radii; +pub use instance::pack_fade; +pub use instance::unpack_clip_radii; +pub use instance::unpack_fade; +pub use layers::LayerStats; +pub use offscreen::OFFSCREEN_FORMAT; +pub use offscreen::Offscreen; +pub use offscreen::write_png; +pub use rune_core::Blend; +pub use warmup::warm_gpu; +pub use warmup::warm_gpu_with; + +/// Rows the first glyph atlas page's texture starts with: a window that shows a few labels holds +/// 512 KiB of it, not 4 MiB. It doubles as its shelves fill, up to `ATLAS_SIZE` (`prepare`). +pub(crate) const ATLAS_START_ROWS: u32 = 256; + +/// `RUNE_LOOP_CHECK=2` found a picture that differed from the whole frame's (`pixel_check`), so the +/// process's exit code is 3. Never on macOS and Linux, which have no loop-only frames. +pub(crate) fn loop_pixel_check_failed() -> bool { + #[cfg(any(target_os = "windows", target_arch = "wasm32"))] + return pixel_check::failed(); + #[cfg(not(any(target_os = "windows", target_arch = "wasm32")))] + false +} + +/// The kinds the frame pass has a pipeline of its own for (`regen_dxbc` compiles each). +#[doc(hidden)] +pub const PINNED_KINDS: [u32; 3] = variant::PINNED; + +/// BLAKE3 of the WGSL the frame pass's pipeline pinned to `kind` compiles from (`variant::pinned_wgsl`, `\r\n` read as +/// `\n`): what `regen_dxbc` records beside each pinned fragment and `dxbc::uber_pinned` checks before using one. +#[doc(hidden)] +pub fn pinned_wgsl_blake3(kind: u32) -> Option<String> { + variant::pinned_wgsl(kind).map(|wgsl| blake3::hash(wgsl.replace("\r\n", "\n").as_bytes()).to_hex().to_string()) +} + +pub(crate) fn blend_state(blend: Blend) -> wgpu::BlendState { + match blend { + Blend::SourceOver => wgpu::BlendState::PREMULTIPLIED_ALPHA_BLENDING, + Blend::PlusLighter => { + let add = wgpu::BlendComponent { src_factor: wgpu::BlendFactor::One, + dst_factor: wgpu::BlendFactor::One, operation: wgpu::BlendOperation::Add }; + wgpu::BlendState { color: add, alpha: add } + } + } +} + +/// Composition properties of an isolated subtree. Filters can extend this contract without +/// changing painter-stream scopes or the target pool. +#[derive(Clone, Copy, Debug)] +pub struct LayerSpec { + pub opacity: f32, + pub blend: Blend, + /// Gaussian standard deviation in device pixels, clamped to 64. Zero bypasses filtering. + pub blur: f32, + /// Radius of the rounded `clip` rectangle, in device pixels; zero is rectangular and a + /// negative radius rounds with continuous corners (`El::continuous_corners`). Applied to + /// the completed layer after filtering. The caller supplies finite clip edges. + pub clip_radius: f32, +} + +impl Default for LayerSpec { + fn default() -> Self { Self { opacity: 1.0, blend: Blend::SourceOver, blur: 0.0, clip_radius: 0.0 } } +} + +/// WGSL for clipping like Rune does: `sd_rounded`, `ramp` and `clip_alpha(p, clip, fade)`. `p` is +/// a window device-pixel position, `clip` an instance's `clip` and `fade` (`vec4<u32>`) its packed +/// soft edges and rounded-clip radius, so a compositor shader cuts its effect with the same +/// rectangle, feathers and circular or continuous corners as the primitives around it. Prepend it +/// to the shader source. +pub const CLIP_WGSL: &str = include_str!("shaders/clip.wgsl"); + +/// The WGSL the precompiled DX12 bytecode is compiled from (Windfoil's, CRLF read as LF), its +/// BLAKE3 and the hash of its pipeline layout, as the bytecode records them; +/// `examples/regen_dxbc.rs` regenerates that bytecode from them. +#[cfg(target_os = "windows")] +#[doc(hidden)] +pub fn uber_shader_identity() -> (&'static str, &'static str, u64) { + (variant::windfoil_wgsl(), uber_wgsl::WINDFOIL_BLAKE3, variant::windfoil_abi_hash()) +} + +/// Where a compositor is asked to draw an effect slot (`Renderer::draw_range_with`). +pub struct EffectSite<'a> { + /// The slot's position in the painter stream. + pub index: u32, + /// The slot's record (`KIND_EFFECT`): rect, radii, clip and fade. + pub instance: &'a Instance, + /// The slot's `El::effect` tag, so a compositor can find the resources it keeps for it. + pub mark: u32, + /// The slot's `El::effect_data` payload, as the element was last built. A slot playing its + /// exit transition keeps the payload it had when it was removed. + pub data: [f32; 4], + /// Device pixels per point at this slot (`instance.params[3]`: `Env::scale` times any + /// element or ancestor `scale` / `live_scale`). + pub scale: f32, + /// Format of the pass being recorded. + pub format: wgpu::TextureFormat, + /// Window device-pixel position of this pass's top-left pixel: zero in the frame target, + /// the layer's bounds origin inside an isolated layer. Subtract it from window coordinates. + pub origin: [f32; 2], + /// Size of this pass's target in device pixels. + pub size: [u32; 2], + /// True inside an isolated layer: the pass is that layer's offscreen target. + pub in_layer: bool, + /// Whether colours are sRGB-encoded for blending (`Renderer::srgb_blend`). Choose a + /// pipeline's encoding from this: encode the shader's output when it's true, write linear + /// values when it's false. Don't use `format.is_srgb()`: an isolated layer's `Rgba16Float` + /// target is neither, and holds whichever encoding the frame uses. + pub srgb_blend: bool, + /// Viewport-sized copy of the pass's target up to this slot when the slot asked for a + /// backdrop (`El::effect_backdrop(true)`, `instance.params[0] != 0.0`) and the pass was run + /// with a command encoder (`Renderer::draw_with`, `Renderer::draw_with_backdrop`, + /// `Renderer::draw_target_range_with`, or `Renderer::encode_layers_with`). Has the same + /// `format` as the pass (`*Srgb` / `Rgba16Float` in linear frames, non-sRGB / `Rgba16Float` + /// holding sRGB-encoded premultiplied values when `srgb_blend` is true; pass it directly to + /// `FxRenderer::blur_backdrop` or `FxRenderer::set_layer_backdrop`). Inside an isolated layer + /// (`in_layer: true`), holds that layer's offscreen target copied at `origin` in window + /// coordinates. + pub backdrop: Option<&'a wgpu::TextureView>, + /// Packed explicit scroll-fade stops (`Runtime::fade_stops`) for this frame, matching + /// `clip_alpha_stops` in `CLIP_WGSL` (`[0.0, 0.0]` when no scroller uses `ScrollFade::stops`). + pub fade_stops: [f32; 2], +} + +/// Called at each effect slot, with the pass open and everything painted before the slot already +/// recorded, and the scissor set to the slot's clip rectangle (a slot clipped away entirely is +/// skipped). Soft edges and rounded corners on a slot outside a layer are the hook's to apply +/// (`CLIP_WGSL`). It may record draws; the viewport and scissor are reset to the full target after. +pub type EffectHook<'h> = dyn FnMut(&mut wgpu::RenderPass<'_>, &EffectSite<'_>) + 'h; + +/// Phase of an effect slot callback in `Renderer::draw_with_backdrop`, +/// `Renderer::encode_layers_with_backdrop`, and `Renderer::draw_target_range_with`. +pub enum EffectPhase<'a, 'p> { + /// Outside the render pass, right after the target up to a backdrop slot + /// (`El::effect_backdrop(true)`) was copied into `site.backdrop` and before the pass re-opens + /// with `LoadOp::Load` (e.g. for `FxRenderer::blur_backdrop`). + Backdrop(&'a mut wgpu::CommandEncoder), + /// Inside the open render pass at the slot's painter position, with the scissor set to the + /// slot's clip rectangle. + Draw(&'a mut wgpu::RenderPass<'p>), +} + +/// Called at each effect slot: first with `EffectPhase::Backdrop(encoder)` while the pass is +/// closed if the slot requested a backdrop (`El::effect_backdrop(true)`), then with +/// `EffectPhase::Draw(pass)` inside the open pass. +pub type EffectBackdropHook<'h> = dyn FnMut(EffectPhase<'_, '_>, &EffectSite<'_>) + 'h; + +#[derive(Clone, Copy, PartialEq, Eq)] +enum BatchBind { + /// Glyph atlas page 0 with image atlas page `usize`. + Image(usize), + /// Secondary glyph atlas page `usize` (index in `atlas_pages`, i.e. glyph page - 1). + Glyph(usize), +} + +pub struct Renderer { + surfaces: Option<crate::native_surface::SurfaceRenderer>, + /// The native surface renderer while its pipeline compiles (`build_surfaces`). + surfaces_building: Option<crate::native_surface::Building>, + pipeline: wgpu::RenderPipeline, + format: wgpu::TextureFormat, + shader: dxbc::Shaders, + layout: wgpu::PipelineLayout, + vertex_entry: &'static str, + /// Pipelines for other target formats a compositor draws into (`add_format`). + extra: Vec<(wgpu::TextureFormat, wgpu::RenderPipeline)>, + bind_group: wgpu::BindGroup, + bind_layout: wgpu::BindGroupLayout, + globals: wgpu::Buffer, + atlas: wgpu::Texture, + /// Which uber shader draws (`variant::Uber`), with the outline store's texture under Windfoil. + uber: variant::Uber, + /// Windfoil's subpixel pipeline for the window (`variant::Lcd`), and whether this frame's + /// text draws subpixel masks. + lcd: variant::Lcd, + /// The frame pass's pipelines pinned to one kind each (`variant::PINNED`), once their thread has made them + /// (`variant::start_pinned`); empty where there's no bytecode for them, None until they arrive. + pinned: Option<Vec<Option<wgpu::RenderPipeline>>>, + /// Those of the formats `extra` keeps a frame pipeline for, so a switch back makes none. + pinned_extra: Vec<(wgpu::TextureFormat, Vec<Option<wgpu::RenderPipeline>>)>, + /// The pinned pipelines being made on their thread (`variant::start_pinned`), for this format. + #[cfg_attr(not(target_os = "windows"), allow(dead_code))] + pinned_building: Option<(wgpu::TextureFormat, std::sync::mpsc::Receiver<Vec<Option<wgpu::RenderPipeline>>>)>, + /// Each instance's kind (`params[1]`), as batched: where a run of one kind starts and ends. + kinds: Vec<Option<Kind>>, + lcd_frame: bool, + /// The window's wake, for work a frame starts on another thread (set_frame_wake). + frame_wake: Option<std::sync::Arc<crate::live::Wake>>, + /// The 1×1 image the base bind group holds until the first image page. + stand_in: wgpu::Texture, + /// Secondary glyph atlas pages (`1..`). + atlas_pages: Vec<(wgpu::Texture, wgpu::BindGroup)>, + /// Stable image pages; the initial bind group uses a 1×1 stand-in. + images: Vec<Option<(wgpu::Texture, wgpu::BindGroup)>>, + image_batches: Vec<(std::ops::Range<u32>, BatchBind)>, + instances: rune_staging::GrowBuffer, + count: u32, + springs: Option<crate::gpu::springs::Bindings>, + spring_instances: usize, + layers: layers::Layers, + srgb_blend: bool, + fade_stops: [f32; 2], + /// Effect slots of the uploaded instances, by index. + effects: Vec<(u32, Instance)>, + /// Pooled viewport-sized backdrop copies, allocated only when a slot sets `effect_backdrop` + /// or an element sets `backdrop_blur`. + backdrops: Vec<Backdrop>, + /// The last prepared frame had an effect reading the backdrop: a rest keeps the copies. + backdrop_used: bool, + /// Pipelines and pyramid for backdrop blur records, built on the first one. + backdrop_blur: Option<backdrop_blur::BackdropBlur>, + /// Which lazily built pipelines the device took (`breaker`). + breakers: breaker::Breakers, + uploads: upload::Uploads, + /// Atlas fills `prepare` staged, recorded into the frame's encoder with the uploads. + fills: std::sync::Mutex<Option<fill::PendingFills>>, + /// Unique to this renderer, so to the device it was made on (`Frame::device_key`). + device_key: crate::compose::DeviceKey, + /// The device's largest 2D texture, read once: in a browser each `Device::limits` reads every + /// limit from JavaScript (about 35 µs), which a frame's layers used to pay. + max_texture_dim: u32, + /// The one instance per rectangle that clears a damaged one (`arm_damage`), made on first use. + #[cfg(any(target_os = "windows", target_arch = "wasm32"))] + clear_quad: std::sync::OnceLock<wgpu::Buffer>, + /// The kept frame and the rectangles the next `draw` may redraw alone (`damaged`). + #[cfg(any(target_os = "windows", target_arch = "wasm32"))] + damage: std::sync::Mutex<damaged::DamageState>, +} + +impl Renderer { + /// `Frame::device_key`: a renderer belongs to one device, and a new device gets a new one. + pub fn device_key(&self) -> crate::compose::DeviceKey { + self.device_key + } + + pub fn new(device: &wgpu::Device, format: wgpu::TextureFormat) -> Renderer { + Self::create(device, format, None, cfg!(target_os = "macos")) + } + + pub fn set_srgb_blend(&mut self, enabled: bool) { + self.srgb_blend = enabled; + if let Some(s) = &mut self.surfaces { + s.set_srgb_blend(enabled); + } + } + + pub fn set_fade_stops(&mut self, stops: [f32; 2]) { + self.fade_stops = stops; + } + + pub fn fade_stops(&self) -> [f32; 2] { + self.fade_stops + } + + /// Opt-in retained geometry. IDs map instances to shared translation/opacity nodes. + /// Upload geometry once with `prepare`, then use `present_at` without rebuilding instances. + pub fn with_springs(device: &wgpu::Device, format: wgpu::TextureFormat, nodes: &[crate::gpu::springs::Node], ids: &[u32]) -> Renderer { + Self::create(device, format, Some((nodes, ids)), true) + } + + /// A renderer that starts with the Classic uber shader, as on macOS, and builds Windfoil when + /// text first draws from outlines (render/variant.rs); for checking that path elsewhere. + #[doc(hidden)] + pub fn new_classic(device: &wgpu::Device, format: wgpu::TextureFormat) -> Renderer { + Self::create(device, format, None, true) + } + + /// Draws uploaded instances `range` into a pass whose target has `format` (the renderer's + /// own, or one added with `add_format`). Call `encode_layers` before opening the pass. + /// Scopes are atomic: list/range boundaries must not bisect a layer. + pub fn draw_range(&self, pass: &mut wgpu::RenderPass<'_>, format: wgpu::TextureFormat, range: std::ops::Range<u32>) { + if range.is_empty() && range.end != self.count { return; } + self.submit_uploads(); + self.validate_layer_range(&range); + let mut active = ActivePass::borrowed(pass); + self.draw_layer_range(&mut active, format, range, None, &mut |_, _| {}); + } + + /// `draw_range` that stops at each effect slot (`El::effect`) in `range` and calls `hook` + /// there, in painter order. Effects inside an isolated layer are reached through + /// `encode_layers_with`, which draws that layer's pass; scopes nest as in `draw_range`. + /// Because `pass` is already open, `EffectSite::backdrop` is `None`; use `draw_with`, + /// `draw_with_backdrop`, or `draw_target_range_with` when slots request a backdrop copy. + pub fn draw_range_with(&self, pass: &mut wgpu::RenderPass<'_>, format: wgpu::TextureFormat, range: std::ops::Range<u32>, hook: &mut EffectHook<'_>) { + if range.is_empty() && range.end != self.count { return; } + self.submit_uploads(); + self.validate_layer_range(&range); + let mut active = ActivePass::borrowed(pass); + self.draw_layer_range(&mut active, format, range, None, &mut |phase, site| { + if let EffectPhase::Draw(pass) = phase { hook(pass, site); } + }); + } + + /// Encodes isolated layers and draws the frame into `view` (cleared to `clear`), calling + /// `hook` at each effect slot (`El::effect`) in painter order. At slots with + /// `El::effect_backdrop(true)`, ends the current pass, copies the target up to that slot into + /// a pooled backdrop texture, re-opens the pass with `LoadOp::Load`, and hands the backdrop + /// view in `EffectSite::backdrop`. + pub fn draw_with(&self, encoder: &mut wgpu::CommandEncoder, view: &wgpu::TextureView, clear: [f32; 4], hook: &mut EffectHook<'_>) { + self.draw_with_backdrop(encoder, view, clear, &mut |phase, site| { + if let EffectPhase::Draw(pass) = phase { hook(pass, site); } + }); + } + + /// Like `draw_with`, also calling `hook(EffectPhase::Backdrop(encoder), site)` while the + /// render pass is closed at each backdrop slot (`El::effect_backdrop(true)`) so the compositor + /// can blur or pre-process `site.backdrop` (e.g. `FxRenderer::blur_backdrop`) before the pass + /// re-opens for `EffectPhase::Draw(pass)`. + pub fn draw_with_backdrop( + &self, + encoder: &mut wgpu::CommandEncoder, + view: &wgpu::TextureView, + clear: [f32; 4], + hook: &mut EffectBackdropHook<'_>, + ) { + self.encode_layers_with_backdrop(encoder, hook); + let clear = wgpu::Color { r: clear[0] as f64, g: clear[1] as f64, b: clear[2] as f64, a: clear[3] as f64 }; + self.draw_target_range_with(encoder, view, self.format, wgpu::LoadOp::Clear(clear), 0..self.count, hook); + } + + /// Draws `range` into `view` (opening the pass with `load`), splitting the pass on `encoder` + /// only at backdrop slots (`El::effect_backdrop(true)`) in `range` to copy `view` into + /// `EffectSite::backdrop` and run `EffectPhase::Backdrop(encoder)` before re-opening with + /// `LoadOp::Load`. Call `encode_layers_with` / `encode_layers_with_backdrop` before drawing + /// the first range. + /// `view` must be a single-sample, full-size, mip-zero 2D target; backdrop slots require + /// its texture to have `COPY_SRC` usage. These owned passes have no depth/stencil or resolve + /// attachment. Use `draw_range_with` for a caller-owned pass instead (no backdrop copies). + pub fn draw_target_range_with( + &self, + encoder: &mut wgpu::CommandEncoder, + view: &wgpu::TextureView, + format: wgpu::TextureFormat, + load: wgpu::LoadOp<wgpu::Color>, + range: std::ops::Range<u32>, + hook: &mut EffectBackdropHook<'_>, + ) { + if range.is_empty() && range.end != self.count { return; } + self.validate_layer_range(&range); + self.flush_uploads(encoder); + let pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { + label: Some("frame"), + color_attachments: &[Some(wgpu::RenderPassColorAttachment { + view, + depth_slice: None, + resolve_target: None, + ops: wgpu::Operations { load, store: wgpu::StoreOp::Store }, + })], + depth_stencil_attachment: None, + timestamp_writes: None, + occlusion_query_set: None, + multiview_mask: None, + }).forget_lifetime(); + let mut active = ActivePass::owned(pass, encoder, view); + self.draw_layer_range(&mut active, format, range, None, hook); + } + + /// `draw_instances`, split after each effect slot in `range` so `hook` runs at its place. + fn draw_with_effects(&self, pass: &mut ActivePass<'_, '_>, format: wgpu::TextureFormat, range: std::ops::Range<u32>, target: Option<usize>, hook: &mut EffectBackdropHook<'_>) { + let first = self.effects.partition_point(|(at, _)| *at < range.start); + let mut cursor = range.start; + for (at, instance) in self.effects[first..].iter().take_while(|(at, _)| *at < range.end) { + self.draw_instances(pass, format, cursor..*at + 1, target); + cursor = *at + 1; + if instance.kind() == Some(Kind::BackdropBlur) { + self.draw_backdrop_blur(pass, format, *at, instance, target); + continue; + } + let (origin, size) = self.target_frame(target); + // Scissor to the slot's clip rectangle, so a compositor that ignores `clip` still + // stays inside its scroll view or clipped ancestor. + let c = instance.clip; + let edge = |v: f32, o: f32, max: u32| (v - o).clamp(0.0, max as f32) as u32; + let (x0, y0) = (edge(c[0].floor(), origin[0], size[0]), edge(c[1].floor(), origin[1], size[1])); + let (x1, y1) = (edge(c[2].ceil(), origin[0], size[0]), edge(c[3].ceil(), origin[1], size[1])); + if x1 <= x0 || y1 <= y0 { continue; } + let backdrop = if instance.params[0] != 0.0 { + pass.split_for_backdrop(self, *at, instance, format, origin, size, target.is_some(), hook) + } else { + None + }; + pass.set_scissor_rect(x0, y0, x1 - x0, y1 - y0); + hook(EffectPhase::Draw(pass), &EffectSite { index: *at, instance, mark: effect_mark(instance), data: instance.uv, scale: instance.params[3], + format, origin, size, in_layer: target.is_some(), srgb_blend: self.srgb_blend, backdrop, fade_stops: self.fade_stops }); + pass.set_viewport(0.0, 0.0, size[0] as f32, size[1] as f32, 0.0, 1.0); + pass.set_scissor(pass.scissor(), size); + } + self.draw_instances(pass, format, cursor..range.end, target); + } + + fn draw_instances(&self, pass: &mut wgpu::RenderPass<'_>, format: wgpu::TextureFormat, range: std::ops::Range<u32>, target: Option<usize>) { + if range.is_empty() { + return; + } + let frame_pipeline = self.draw_pipeline(format, target); + pass.set_pipeline(frame_pipeline); + // The pinned pipelines draw the frame pass's runs of one kind (`variant::PINNED`), in paint order: + // only where the frame's own pipeline would draw (not a layer target, an additive layer or subpixel text). + let pinned = self.pinned.as_deref().filter(|p| p.iter().any(Option::is_some) && std::ptr::eq(frame_pipeline, &self.pipeline) && target.is_none() && format == self.format); + // Frame-profile builds: `RUNE_PINNED=off` draws every span with the general shader, `all` splits every span + // whatever its runs; the screen comparison runs both against the general build. + #[cfg(feature = "frame-profile")] + let pinned = pinned.filter(|_| pinned_forced() != Some(false)); + let mut bound = frame_pipeline; + if let Some(properties) = &self.springs { pass.set_bind_group(1, &properties.group, &[]); } + pass.set_vertex_buffer(0, self.instances.slice(..)); + let start = self.image_batches.partition_point(|(batch, _)| batch.end <= range.start); + for (batch, bind_kind) in self.image_batches[start..].iter().take_while(|(batch, _)| batch.start < range.end) { + let bind = match (*bind_kind, target) { + (BatchBind::Image(page), Some(index)) => { + let t = self.layers.targets[index].as_ref().unwrap(); + t.images.get(page).and_then(Option::as_ref).unwrap_or(&t.base) + } + (BatchBind::Image(page), None) => { + self.images.get(page).and_then(Option::as_ref).map_or(&self.bind_group, |(_, bind)| bind) + } + (BatchBind::Glyph(page), Some(index)) => { + let t = self.layers.targets[index].as_ref().unwrap(); + t.glyphs.get(page).unwrap_or(&t.base) + } + (BatchBind::Glyph(page), None) => { + self.atlas_pages.get(page).map_or(&self.bind_group, |(_, bind)| bind) + } + }; + pass.set_bind_group(0, bind, &[]); + let span = batch.start.max(range.start)..batch.end.min(range.end); + // A span whose kinds alternate (a chip behind each token, a terminal's cell backgrounds between its + // glyphs) draws in one call with the general shader: a draw and a pipeline switch per run cost more + // than the smaller shader saves. + #[cfg(not(feature = "frame-profile"))] + let split = pinned.filter(|_| few_runs(&self.kinds, span.clone())); + #[cfg(feature = "frame-profile")] + let split = pinned.filter(|_| pinned_forced() == Some(true) || few_runs(&self.kinds, span.clone())); + #[cfg(feature = "frame-profile")] + PINNED_DRAWN[usize::from(split.is_some())].fetch_add(u64::from(span.end - span.start), std::sync::atomic::Ordering::Relaxed); + let Some(pinned) = split else { + if !std::ptr::eq(bound, frame_pipeline) { pass.set_pipeline(frame_pipeline); bound = frame_pipeline; } + pass.draw(0..4, span); + continue; + }; + for run in kind_runs(&self.kinds, span) { + let kind = self.kinds[run.start as usize]; + let pipeline = kind + .and_then(|k| variant::PINNED.iter().position(|&p| p == k.as_u32())) + .and_then(|at| pinned[at].as_ref()) + .unwrap_or(&self.pipeline); + if !std::ptr::eq(pipeline, bound) { pass.set_pipeline(pipeline); bound = pipeline; } + pass.draw(0..4, run); + } + } + } + + /// The format of the target the renderer was built for (`draw_range` with this format). + pub fn format(&self) -> wgpu::TextureFormat { self.format } + + /// True when colours are sRGB-encoded for blending: the target is a non-sRGB view and every + /// pass, offscreen layers included, holds encoded premultiplied values. False means linear + /// premultiplied values, encoded by the `*Srgb` target on write. + pub fn srgb_blend(&self) -> bool { self.srgb_blend } + + pub fn submit(&self, queue: &wgpu::Queue, mut encoder: wgpu::CommandEncoder) -> wgpu::SubmissionIndex { + self.before_submit(&mut encoder); + if let Some(s) = &self.surfaces { s.submit(queue, encoder) } else { queue.submit([encoder.finish()]) } + } + + /// Whether `submit` is `queue.submit` after `before_submit` and nothing more: no native video + /// surface waits on the frame's submission, so another thread may make it. + #[cfg(target_os = "macos")] + pub(crate) fn submits_plainly(&self) -> bool { + self.surfaces.as_ref().is_none_or(|s| s.draws_nothing()) + } + + pub fn draw(&self, encoder: &mut wgpu::CommandEncoder, view: &wgpu::TextureView, clear: [f32; 4]) { + #[cfg(any(target_os = "windows", target_arch = "wasm32"))] + if self.armed() && self.draw_armed(encoder, &view.texture()) { return; } + self.draw_timed(encoder, view, clear, None); + } + + /// Constant-time scheduler check. Present the terminal frame, then stop the display link. + /// Deadlines are recomputed only on commits, so no per-node CPU sampling occurs on ticks. + pub fn springs_animating(&self, time: f64) -> bool { + self.springs.as_ref().is_some_and(|p| time < p.settle_at) + } + + /// Draws over what `view` already holds instead of clearing it (headless overlays). + pub(crate) fn draw_over(&self, encoder: &mut wgpu::CommandEncoder, view: &wgpu::TextureView) { + self.draw_load(encoder, view, wgpu::LoadOp::Load, None); + } + + pub fn draw_timed(&self, encoder: &mut wgpu::CommandEncoder, view: &wgpu::TextureView, clear: [f32; 4], timestamps: Option<wgpu::RenderPassTimestampWrites<'_>>) { + let clear = wgpu::Color { r: clear[0] as f64, g: clear[1] as f64, b: clear[2] as f64, a: clear[3] as f64 }; + self.draw_load(encoder, view, wgpu::LoadOp::Clear(clear), timestamps); + } + + fn draw_load(&self, encoder: &mut wgpu::CommandEncoder, view: &wgpu::TextureView, load: wgpu::LoadOp<wgpu::Color>, timestamps: Option<wgpu::RenderPassTimestampWrites<'_>>) { + let timestamps = timestamps.or_else(|| self.surfaces.as_ref().and_then(|s| s.timestamp_writes())); + self.encode_layers_timed(encoder, timestamps.as_ref(), &mut |_, _| {}); + let timestamps = timestamps.map(|mut t| { + if self.layer_stats().extra_passes > 0 { t.beginning_of_pass_write_index = None; } + t + }); + let blurs = self.has_backdrop_blur(); + let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { + label: Some("frame"), + color_attachments: &[Some(wgpu::RenderPassColorAttachment { + view, + depth_slice: None, + resolve_target: None, + ops: wgpu::Operations { load, store: wgpu::StoreOp::Store }, + })], + depth_stencil_attachment: None, + timestamp_writes: timestamps.clone(), + occlusion_query_set: None, + multiview_mask: None, + }); + if !blurs { + self.draw_range(&mut pass, self.format, 0..self.count); + return; + } + // Backdrop blurs split the frame pass, which needs it owned along with the encoder. + let pass = pass.forget_lifetime(); + let mut active = ActivePass::owned_timed(pass, encoder, view, timestamps); + self.draw_layer_range(&mut active, self.format, 0..self.count, None, &mut |_, _| {}); + } +} + +/// How far a corner of radius `radius` reaches along each edge. Radii are signed: a negative +/// radius draws Apple's continuous corner, whose curve starts `CONTINUOUS_K` times the radius from +/// the corner (`CONTINUOUS_K` in clip.wgsl). +pub(crate) fn corner_extent(radius: f32) -> f32 { + if radius < 0.0 { -radius * CONTINUOUS_K } else { radius } +} + +pub(crate) const CONTINUOUS_K: f32 = instance::shader_consts::CONTINUOUS_K; + +/// Frame-profile builds: `RUNE_PINNED` forcing the split on (`all`) or off (`off`), and the instances drawn +/// unsplit and split since the last report (`report_pinned`). +#[cfg(feature = "frame-profile")] +pub(super) fn pinned_forced() -> Option<bool> { + static FORCED: std::sync::OnceLock<Option<bool>> = std::sync::OnceLock::new(); + *FORCED.get_or_init(|| match rune_core::env::var("RUNE_PINNED").as_deref() { Some("all") => Some(true), Some("off") => Some(false), _ => None }) +} + +#[cfg(feature = "frame-profile")] +static PINNED_DRAWN: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2]; + +/// Frame-profile builds with `RUNE_PINNED` set: every 60th frame, how many instances of the window's pass the +/// pinned pipelines drew and how many went unsplit, so a comparison shows it exercised the pinned path. +#[cfg(feature = "frame-profile")] +pub(crate) fn report_pinned() { + static FRAMES: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + let frame = FRAMES.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + if std::env::var_os("RUNE_PINNED").is_none() || frame % 60 != 0 { return; } + let [whole, split] = [0, 1].map(|i| PINNED_DRAWN[i].swap(0, std::sync::atomic::Ordering::Relaxed)); + eprintln!("rune-pinned: {split} instances split into runs, {whole} drawn unsplit (frame {frame})"); +} + +/// Most runs a span is split into (`few_runs`), and fewest instances a run has on average. +const MAX_RUNS: usize = 64; +const MIN_RUN: usize = 8; + +/// Whether `span` splits into few enough runs of one kind to draw them with the pinned pipelines: one run, +/// or at most `MAX_RUNS` of `MIN_RUN` instances or more on average. +fn few_runs(kinds: &[Option<Kind>], span: std::ops::Range<u32>) -> bool { + let len = span.len(); + let runs = kind_runs(kinds, span).take(MAX_RUNS + 1).count(); + runs <= 1 || (runs <= MAX_RUNS && runs * MIN_RUN <= len) +} + +/// `span` split into runs of instances of one kind (`kinds` by instance). +fn kind_runs(kinds: &[Option<Kind>], span: std::ops::Range<u32>) -> impl Iterator<Item = std::ops::Range<u32>> + '_ { + let mut at = span.start as usize; + let end = span.end as usize; + let slice = &kinds[..end.min(kinds.len())]; + std::iter::from_fn(move || { + if at >= end { return None; } + let start = at; + let Some(&first) = slice.get(at) else { + at = end; + return Some(start as u32..end as u32); + }; + let mut cur = at + 1; + while let Some(&k) = slice.get(cur) && k == first { cur += 1; } + at = cur; + Some(start as u32..cur as u32) + }) +} diff --git a/app/vendor/rune/crates/rune/src/render/abi_tests.rs b/app/vendor/rune/crates/rune/src/render/abi_tests.rs new file mode 100644 index 0000000..0f069ad --- /dev/null +++ b/app/vendor/rune/crates/rune/src/render/abi_tests.rs @@ -0,0 +1,958 @@ +use std::mem::{offset_of, size_of}; + +use bytemuck::Zeroable; + +use super::*; + +#[test] +fn kind_enum_round_trips_and_rejects_invalid_floats() { + assert_eq!(size_of::<Option<Kind>>(), 1); + let all = [ + (Kind::Rect, KIND_RECT, 0u8), + (Kind::Shadow, KIND_SHADOW, 1), + (Kind::Glyph, KIND_GLYPH, 2), + (Kind::Inset, KIND_INSET, 3), + (Kind::Gradient, KIND_GRADIENT, 4), + (Kind::Segment, KIND_SEGMENT, 5), + (Kind::Triangle, KIND_TRIANGLE, 6), + (Kind::Image, KIND_IMAGE, 7), + (Kind::Layer, KIND_LAYER, 8), + (Kind::LayerEnd, KIND_LAYER_END, 9), + (Kind::Dashed, KIND_DASHED, 10), + (Kind::Radial, KIND_RADIAL, 11), + (Kind::Effect, KIND_EFFECT, 12), + (Kind::BackdropBlur, KIND_BACKDROP_BLUR, 13), + ]; + assert_eq!(all.len(), Kind::COUNT); + for (kind, constant, num) in all { + assert_eq!(kind.as_u8(), num); + assert_eq!(kind.as_u32(), u32::from(num)); + assert_eq!(kind.as_f32(), constant); + assert_eq!(constant, f32::from(num)); + assert_eq!(Kind::from_u8(num), Some(kind)); + assert_eq!(Kind::from_f32(constant), Some(kind)); + let mut inst = Instance::zeroed(); + inst.params[1] = constant; + assert_eq!(inst.kind(), Some(kind)); + } + assert_eq!(Kind::from_f32(-0.0), Some(Kind::Rect)); + assert_eq!(Kind::from_u8(14), None); + for bad in [-1.0, -0.5, 0.5, 1.5, 8.5, 9.5, 11.5, 13.5, 14.0, 255.0, f32::NAN, f32::INFINITY, f32::NEG_INFINITY] { + assert_eq!(Kind::from_f32(bad), None, "expected None for {bad:?}"); + } +} + +#[test] +fn instance_word_indices_match_field_offsets() { + assert_eq!(INSTANCE_WORDS, 32); + assert_eq!(word::RECT * 4, offset_of!(Instance, rect)); + assert_eq!(word::RECT_Y, 1); + assert_eq!(word::FILL, 8..12); + assert_eq!(word::FILL.start * 4, offset_of!(Instance, fill)); + assert_eq!(word::BORDER, 12..16); + assert_eq!(word::BORDER.start * 4, offset_of!(Instance, border)); + assert_eq!(word::PARAMS * 4, offset_of!(Instance, params)); + assert_eq!(word::PARAMS_W, 19); + assert_eq!(word::CLIP * 4, offset_of!(Instance, clip)); + assert_eq!(word::CLIP_Y0, 25); + assert_eq!(word::CLIP_Y1, 27); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn wgsl_uniform_and_storage_layouts_match_rust() { + use crate::gpu::springs; + use wgpu::naga::{Module, TypeInner, front::wgsl, proc::Layouter, valid::{Capabilities, ValidationFlags, Validator}}; + + let parse = |label: &str, source: &str| -> (Module, Layouter) { + let module = wgsl::parse_str(source).unwrap_or_else(|e| panic!("{label}: {}", e.emit_to_string(source))); + Validator::new(ValidationFlags::all(), Capabilities::default() | Capabilities::SHADER_FLOAT16_IN_FLOAT32) + .validate(&module) + .unwrap_or_else(|e| panic!("{label}: {e}")); + let mut layouter = Layouter::default(); + layouter.update(module.to_ctx()).unwrap_or_else(|e| panic!("{label}: {e}")); + (module, layouter) + }; + + let check_struct = |label: &str, module: &Module, layouter: &Layouter, name: &str, size: usize, expected: &[(&str, usize)]| { + let (handle, ty) = module + .types + .iter() + .find(|(_, t)| t.name.as_deref() == Some(name)) + .unwrap_or_else(|| panic!("{label}: WGSL struct {name} not found")); + assert_eq!(layouter[handle].size as usize, size, "{label} {name} size"); + let TypeInner::Struct { members, span } = &ty.inner else { panic!("{label}: {name} is not a struct") }; + assert_eq!(*span as usize, size, "{label} {name} span"); + assert_eq!(members.len(), expected.len(), "{label} {name} member count"); + for (member, &(field, offset)) in members.iter().zip(expected) { + assert_eq!(member.name.as_deref(), Some(field), "{label} {name}.{field} name"); + assert_eq!(member.offset as usize, offset, "{label} {name}.{field} offset"); + } + }; + + let globals_fields: &[(&str, usize)] = &[ + ("viewport", offset_of!(Globals, viewport)), + ("pad", offset_of!(Globals, pad)), + ("flags", offset_of!(Globals, flags)), + ]; + let level_fields: &[(&str, usize)] = &[ + ("w", offset_of!(backdrop_blur::Level, w)), + ("region", offset_of!(backdrop_blur::Level, region)), + ("map", offset_of!(backdrop_blur::Level, map)), + ("place", offset_of!(backdrop_blur::Level, place)), + ]; + let layer_blur_fields: &[(&str, usize)] = &[ + ("config", offset_of!(layer_blur::Uniforms, meta)), + ("mapping", offset_of!(layer_blur::Uniforms, mapping)), + ("taps", offset_of!(layer_blur::Uniforms, taps)), + ]; + + let (classic, classic_layout) = parse("uber_wgsl::CLASSIC", uber_wgsl::CLASSIC); + check_struct("CLASSIC", &classic, &classic_layout, "Globals", size_of::<Globals>(), globals_fields); + + // Also confirm Instance's vertex attributes agree with `struct In` locations and `offset_of!`. + let expected_attrs = [ + (0u32, offset_of!(Instance, rect) as u64, wgpu::VertexFormat::Float32x4), + (1, offset_of!(Instance, radii) as u64, wgpu::VertexFormat::Float32x4), + (2, offset_of!(Instance, fill) as u64, wgpu::VertexFormat::Float32x4), + (3, offset_of!(Instance, border) as u64, wgpu::VertexFormat::Float32x4), + (4, offset_of!(Instance, params) as u64, wgpu::VertexFormat::Float32x4), + (5, offset_of!(Instance, uv) as u64, wgpu::VertexFormat::Float32x4), + (6, offset_of!(Instance, clip) as u64, wgpu::VertexFormat::Float32x4), + (7, offset_of!(Instance, fade) as u64, wgpu::VertexFormat::Uint32x4), + ]; + let vlayout = metallib::uber_vertex_layout(); + assert_eq!(vlayout.array_stride, size_of::<Instance>() as u64); + assert_eq!(vlayout.attributes.len(), expected_attrs.len()); + for (attr, &(loc, off, fmt)) in vlayout.attributes.iter().zip(&expected_attrs) { + assert_eq!((attr.shader_location, attr.offset, attr.format), (loc, off, fmt)); + } + + let (windfoil, windfoil_layout) = parse("uber_wgsl::WINDFOIL", uber_wgsl::WINDFOIL); + check_struct("WINDFOIL", &windfoil, &windfoil_layout, "Globals", size_of::<Globals>(), globals_fields); + + let (bd_blur, bd_blur_layout) = parse("backdrop_blur.wgsl", backdrop_blur::BLUR_WGSL); + check_struct("backdrop_blur.wgsl", &bd_blur, &bd_blur_layout, "Level", size_of::<backdrop_blur::Level>(), level_fields); + + let composite_src = backdrop_blur::composite_wgsl(); + let (bd_comp, bd_comp_layout) = parse("backdrop_composite.wgsl", &composite_src); + check_struct("backdrop_composite.wgsl", &bd_comp, &bd_comp_layout, "Globals", size_of::<Globals>(), globals_fields); + check_struct("backdrop_composite.wgsl", &bd_comp, &bd_comp_layout, "Level", size_of::<backdrop_blur::Level>(), level_fields); + + let (lb, lb_layout) = parse("layer_blur.wgsl", layer_blur::WGSL); + check_struct("layer_blur.wgsl", &lb, &lb_layout, "Uniforms", size_of::<layer_blur::Uniforms>(), layer_blur_fields); + + let springs_src = format!("{}\n{}", uber_wgsl::CLASSIC, springs::SHADER); + let (sp, sp_layout) = parse("CLASSIC+springs.wgsl", &springs_src); + check_struct("CLASSIC+springs.wgsl", &sp, &sp_layout, "Globals", size_of::<Globals>(), globals_fields); + check_struct( + "CLASSIC+springs.wgsl", + &sp, + &sp_layout, + "SpringNode", + size_of::<springs::Node>(), + &[ + ("x", offset_of!(springs::Node, x)), + ("y", offset_of!(springs::Node, y)), + ("opacity", offset_of!(springs::Node, opacity)), + ], + ); +} + +/// Exact `shader.wgsl` `base_vs` quad corners -> pixel centres `[x0, y0, x1, y1)` inside clip & target. +fn shader_exact_pixels(i: &Instance, w: i32, h: i32) -> [i32; 4] { + let kind = i.params[1]; + if kind > 11.5 || kind == KIND_LAYER_END { + return [0; 4]; + } + let mut grow = 1.0 + i.params[2] * 2.0; + if kind > 0.5 && kind < 1.5 { + grow = i.params[2] * 3.0 + 1.0; + } else if kind > 1.5 && kind < 2.5 { + grow = 0.0; + } else if (kind > 2.5 && kind < 3.5) || (kind > 4.5 && kind < 9.5) { + grow = 1.0; + } + let mut lo = [i.rect[0] - grow, i.rect[1] - grow]; + let mut hi = [lo[0] + i.rect[2] + 2.0 * grow, lo[1] + i.rect[3] + 2.0 * grow]; + if kind < 1.5 && i.uv[2] < 0.0 { + lo = [lo[0].max(i.rect[0] + i.uv[0]), lo[1].max(i.rect[1] + i.uv[1])]; + hi = [hi[0].min(i.rect[0] - i.uv[2]).max(lo[0]), hi[1].min(i.rect[1] + i.uv[3]).max(lo[1])]; + } + let mut min_x = f32::INFINITY; + let mut min_y = f32::INFINITY; + let mut max_x = f32::NEG_INFINITY; + let mut max_y = f32::NEG_INFINITY; + for vi in 0..4u32 { + let p = [if vi & 1 != 0 { hi[0] } else { lo[0] }, if vi >> 1 != 0 { hi[1] } else { lo[1] }]; + let mut screen = p; + if kind > 1.5 && kind < 2.5 && i.params[0] != 0.0 { + let center = [i.rect[0] + i.rect[2] * 0.5, i.rect[1] + i.rect[3] * 0.5]; + let q = [p[0] - center[0], p[1] - center[1]]; + let (s, c) = i.params[0].sin_cos(); + screen = [center[0] + c * q[0] - s * q[1], center[1] + s * q[0] + c * q[1]]; + } + if kind > 7.5 && kind < 8.5 && i.border[1] != 0.0 { + let q = [p[0] - i.border[2], p[1] - i.border[3]]; + let (s, c) = i.border[1].sin_cos(); + screen = [i.border[2] + c * q[0] - s * q[1], i.border[3] + s * q[0] + c * q[1]]; + } + min_x = min_x.min(screen[0]); + min_y = min_y.min(screen[1]); + max_x = max_x.max(screen[0]); + max_y = max_y.max(screen[1]); + } + let first = |v: f32| (v - 0.5).ceil(); + let c = i.clip; + // Exact `clip_alpha > 0` reach for hard clip edges (`ramp(d, 0) = clamp(d + 0.5, 0, 1)`): + // pixel `x` has centre `x + 0.5`, so `(x + 0.5 - c0) + 0.5 > 0` <=> `x >= c0.floor()`, + // and `(c2 - (x + 0.5)) + 0.5 > 0` <=> `x < c2.ceil()`. + let x0 = first(min_x).max(c[0].floor()).max(0.0); + let y0 = first(min_y).max(c[1].floor()).max(0.0); + let x1 = first(max_x).min(c[2].ceil()).min(w as f32); + let y1 = first(max_y).min(c[3].ceil()).min(h as f32); + if !(x1 > x0 && y1 > y0) { + return [0; 4]; + } + [x0 as i32, y0 as i32, x1 as i32, y1 as i32] +} + +fn contains(outer: [i32; 4], inner: [i32; 4]) -> bool { + if inner[2] <= inner[0] || inner[3] <= inner[1] { + return true; + } + outer[2] > outer[0] + && outer[3] > outer[1] + && outer[0] <= inner[0] + && outer[1] <= inner[1] + && outer[2] >= inner[2] + && outer[3] >= inner[3] +} + +fn area_i32(r: [i32; 4]) -> i64 { + i64::from((r[2] - r[0]).max(0)) * i64::from((r[3] - r[1]).max(0)) +} + +fn old_layer_bounds(i: &Instance) -> [f32; 4] { + let mut rect = i.rect; + if i.params[1] == KIND_GLYPH && i.params[0] != 0.0 { + let (sin, cos) = i.params[0].sin_cos(); + let width = cos.abs() * rect[2] + sin.abs() * rect[3]; + let height = sin.abs() * rect[2] + cos.abs() * rect[3]; + rect = [rect[0] + (rect[2] - width) * 0.5, rect[1] + (rect[3] - height) * 0.5, width, height]; + } + let grow = match i.params[1] { + KIND_GLYPH => 0.0, + KIND_SHADOW => i.params[2] * 3.0 + 1.0, + KIND_EFFECT => i.params[2] + 1.0, + KIND_RECT | KIND_GRADIENT | KIND_DASHED | KIND_RADIAL => 1.0 + i.params[2] * 2.0, + _ => 1.0, + }; + [ + (rect[0] - grow).max(i.clip[0]), + (rect[1] - grow).max(i.clip[1]), + (rect[0] + rect[2] + grow).min(i.clip[2]), + (rect[1] + rect[3] + grow).min(i.clip[3]), + ] +} + +#[test] +fn instance_bounds_contain_exact_drawn_pixels_across_all_kinds() { + let (w, h) = (256i32, 256i32); + let mut atlas = crate::text::Atlas::new(); + atlas.data.resize((crate::text::ATLAS_SIZE * crate::text::ATLAS_SIZE) as usize, 0); + // Put a solid 16×16 glyph mask at (0, 0) on page 0 so CPU rasterization paints every glyph pixel. + for y in 0..16usize { + for x in 0..16usize { + atlas.data[y * crate::text::ATLAS_SIZE as usize + x] = 255; + } + } + let mut images = crate::pixels::ImageAtlas::default(); + let px = crate::Pixels::new(); + px.set(16, 16, vec![255u8; 16 * 16 * 4]); + let placed = images.place(&px, [16.0, 16.0]).expect("place test image"); + + let base = |kind: Kind, rect: [f32; 4]| Instance { + rect, + fill: [1.0, 0.4, 0.2, 1.0], + border: [0.2, 0.8, 1.0, 1.0], + params: [0.0, kind.as_f32(), 0.0, 1.0], + clip: NO_CLIP, + ..Instance::zeroed() + }; + + let mut cases: Vec<(&str, Instance, bool)> = vec![ + // (name, instance, cpu_paintable) + ("rect_plain", base(Kind::Rect, [30.3, 40.7, 50.0, 30.0]), true), + ("rect_border_soft", Instance { params: [3.0, KIND_RECT, 2.0, 1.0], radii: [8.0; 4], ..base(Kind::Rect, [40.0, 40.0, 60.0, 40.0]) }, true), + ("rect_clipped", Instance { clip: [45.2, 48.6, 82.4, 70.1], ..base(Kind::Rect, [30.0, 40.0, 80.0, 50.0]) }, true), + // Banded border ring (top band via uv.z < 0). + ("rect_banded", Instance { params: [2.0, KIND_RECT, 0.0, 1.0], uv: [-1.0, -1.0, -101.0, 6.0], ..base(Kind::Rect, [50.0, 60.0, 100.0, 80.0]) }, true), + ("shadow_plain", Instance { params: [0.0, KIND_SHADOW, 6.0, 1.0], radii: [8.0; 4], ..base(Kind::Shadow, [60.0, 60.0, 80.0, 50.0]) }, true), + ("shadow_hole", Instance { params: [0.0, KIND_SHADOW, 5.0, 1.0], uv: [10.0, 10.0, 40.0, 20.0], ..base(Kind::Shadow, [60.0, 60.0, 80.0, 50.0]) }, true), + // Banded shadow (right strip via uv.z < 0). + ("shadow_banded", Instance { params: [0.0, KIND_SHADOW, 6.0, 1.0], uv: [90.0, -19.0, -119.0, 99.0], ..base(Kind::Shadow, [40.0, 50.0, 100.0, 80.0]) }, true), + ("glyph_upright", Instance { uv: [0.0, 0.0, 0.0, 0.0], ..base(Kind::Glyph, [70.0, 70.0, 16.0, 16.0]) }, true), + ("glyph_scaled", Instance { uv: [0.0, 0.0, 16.0, 16.0], ..base(Kind::Glyph, [70.2, 70.8, 32.0, 12.0]) }, true), + ("inset_sharp", Instance { params: [3.0, KIND_INSET, 0.0, 1.0], ..base(Kind::Inset, [50.0, 50.0, 60.0, 40.0]) }, true), + ("inset_blur", Instance { params: [2.0, KIND_INSET, 4.0, 1.0], uv: [2.0, 2.0, 0.0, 0.0], ..base(Kind::Inset, [50.0, 50.0, 60.0, 40.0]) }, true), + ("gradient_fill", Instance { uv: [0.1, 0.2, 0.9, 1.0], params: [0.0, KIND_GRADIENT, 1.5, 1.0], ..base(Kind::Gradient, [30.0, 30.0, 50.0, 50.0]) }, true), + ("segment_round", Instance { radii: [40.0, 40.0, 110.0, 85.0], params: [3.0, KIND_SEGMENT, 1.0, 1.0], ..base(Kind::Segment, [36.0, 36.0, 78.0, 53.0]) }, true), + ("triangle", Instance { radii: [50.0, 40.0, 120.0, 60.0], uv: [70.0, 110.0, 0.0, 0.0], params: [7.0, KIND_TRIANGLE, 0.0, 1.0], ..base(Kind::Triangle, [50.0, 40.0, 70.0, 70.0]) }, true), + ("image", Instance { params: [placed.page as f32, KIND_IMAGE, 0.0, 1.0], uv: [placed.rect[0] as f32, placed.rect[1] as f32, placed.rect[2] as f32, placed.rect[3] as f32], ..base(Kind::Image, [80.0, 80.0, 24.0, 24.0]) }, true), + ("dashed", Instance { params: [3.0, KIND_DASHED, 0.5, 1.0], uv: [6.0, 4.0, 0.0, 0.0], ..base(Kind::Dashed, [40.0, 40.0, 80.0, 60.0]) }, true), + ("radial", Instance { params: [0.0, KIND_RADIAL, 1.0, 1.0], uv: [40.0, 30.0, 40.0, 30.0], ..base(Kind::Radial, [40.0, 40.0, 80.0, 60.0]) }, true), + ("linear_angle", Instance { params: [0.0, KIND_RADIAL, 1.0, 1.0], uv: [0.01, 0.005, 0.0, 0.0], ..base(Kind::Radial, [40.0, 40.0, 80.0, 60.0]) }, true), + ("layer_plain", Instance::begin_layer([40.0, 50.0, 80.0, 60.0], NO_CLIP, LayerSpec::default()), false), + ("layer_turned", Instance::begin_layer([60.0, 60.0, 80.0, 40.0], NO_CLIP, LayerSpec::default()).turned(0.6, [100.0, 80.0]), false), + ("layer_end", Instance::end_layer(), false), + ("effect_bleed0", Instance { params: [0.0, KIND_EFFECT, 0.0, 1.0], ..base(Kind::Effect, [60.0, 60.0, 40.0, 30.0]) }, false), + ("effect_bleed16", Instance { params: [0.0, KIND_EFFECT, 16.0, 1.0], ..base(Kind::Effect, [60.0, 60.0, 40.0, 30.0]) }, false), + ("backdrop_blur", Instance { params: [12.0, KIND_BACKDROP_BLUR, 0.0, 1.0], ..base(Kind::BackdropBlur, [50.0, 50.0, 70.0, 50.0]) }, false), + ]; + + // Spread of rotated glyphs across angles and aspect ratios. + for &(label, rect, angle) in &[ + ("glyph_rot_small", [80.0, 80.0, 40.0, 12.0], 0.05f32), + ("glyph_rot_15deg", [80.0, 80.0, 40.0, 12.0], 0.26), + ("glyph_rot_45deg", [80.0, 80.0, 40.0, 12.0], std::f32::consts::FRAC_PI_4), + ("glyph_rot_90deg", [80.0, 80.0, 40.0, 12.0], std::f32::consts::FRAC_PI_2), + ("glyph_rot_tall", [80.0, 80.0, 12.0, 40.0], 1.1), + ("glyph_rot_clipped", [80.0, 80.0, 40.0, 12.0], 0.4), + ] { + let mut inst = Instance { params: [angle, KIND_GLYPH, 0.0, 1.0], uv: [0.0, 0.0, 16.0, 16.0], ..base(Kind::Glyph, rect) }; + if label == "glyph_rot_clipped" { + inst.clip = [85.0, 75.0, 115.0, 98.0]; + } + cases.push((label, inst, true)); + } + + let mut tighter_layer_sites = Vec::new(); + + for (name, inst, paintable) in &cases { + let exact_vs = shader_exact_pixels(inst, w, h); + let pb = inst.pixel_bounds(w, h); + assert!(contains(pb, exact_vs), "{name}: pixel_bounds {pb:?} missed base_vs exact {exact_vs:?}"); + assert_eq!(cpu_boot::bin::pixel_bounds(inst, w, h), pb, "{name}: bin::pixel_bounds delegates to Instance::pixel_bounds"); + + // Ground truth from actual CPU rasterized pixels. + let mut painted_box = [0i32; 4]; + if *paintable { + let mut buf = vec![0u8; (w * h * 4) as usize]; + let scene = cpu_boot::Scene::new(std::slice::from_ref(inst), &atlas, &images, (w as u32, h as u32), [0.0; 4]); + cpu_boot::paint(&scene, &mut cpu_boot::Target::new(&mut buf, w as u32, h as u32), 1) + .unwrap_or_else(|e| panic!("{name}: cpu_boot::paint failed: {e:?}")); + let (mut x0, mut y0, mut x1, mut y1) = (w, h, 0, 0); + for y in 0..h { + for x in 0..w { + let at = ((y * w + x) * 4) as usize; + if buf[at..at + 4] != [0, 0, 0, 0] { + x0 = x0.min(x); + y0 = y0.min(y); + x1 = x1.max(x + 1); + y1 = y1.max(y + 1); + } + } + } + if x1 > x0 && y1 > y0 { + painted_box = [x0, y0, x1, y1]; + } + assert!(contains(pb, painted_box), "{name}: pixel_bounds {pb:?} missed CPU-painted pixels {painted_box:?}"); + } + + // Layer bounds (non-scope records only, as `prepare_layers` calls it). + if !matches!(inst.kind(), Some(Kind::Layer | Kind::LayerEnd)) { + let lb = inst.layer_bounds(); + let lb_px = [ + lb[0].max(0.0).floor() as i32, + lb[1].max(0.0).floor() as i32, + lb[2].min(w as f32).ceil() as i32, + lb[3].min(h as f32).ceil() as i32, + ]; + let target_exact = match inst.kind() { + Some(Kind::Effect) => { + let g = inst.params[2] + 1.0; + [(inst.rect[0] - g).max(inst.clip[0]).max(0.0).floor() as i32, + (inst.rect[1] - g).max(inst.clip[1]).max(0.0).floor() as i32, + (inst.rect[0] + inst.rect[2] + g).min(inst.clip[2]).min(w as f32).ceil() as i32, + (inst.rect[1] + inst.rect[3] + g).min(inst.clip[3]).min(h as f32).ceil() as i32] + } + Some(Kind::BackdropBlur) => [ + (inst.rect[0] - 1.0).max(inst.clip[0]).max(0.0).floor() as i32, + (inst.rect[1] - 1.0).max(inst.clip[1]).max(0.0).floor() as i32, + (inst.rect[0] + inst.rect[2] + 1.0).min(inst.clip[2]).min(w as f32).ceil() as i32, + (inst.rect[1] + inst.rect[3] + 1.0).min(inst.clip[3]).min(h as f32).ceil() as i32, + ], + _ => exact_vs, + }; + assert!(contains(lb_px, target_exact), "{name}: layer_bounds {lb_px:?} missed exact {target_exact:?}"); + assert!(contains(lb_px, painted_box), "{name}: layer_bounds {lb_px:?} missed CPU-painted {painted_box:?}"); + + // CPU boot's layer planner (`cpu_boot::bin::plan_layers`) must agree with + // `Instance::layer_bounds` and contain every exact and painted pixel. + let seed = [lb[0], lb[1], 0.0, 0.0]; + let stream = [ + Instance::begin_layer(seed, NO_CLIP, LayerSpec { opacity: 0.5, ..Default::default() }), + *inst, + Instance::end_layer(), + ]; + let (plans, _) = cpu_boot::bin::plan_layers(&stream, (w as u32, h as u32)); + assert_eq!(plans.len(), 1, "{name}: one planned layer"); + assert_eq!(plans[0].bounds, lb_px, "{name}: cpu_boot plan_layers bounds match Instance::layer_bounds"); + assert!(contains(plans[0].bounds, target_exact), "{name}: cpu_boot plan_layers {:?} missed exact {target_exact:?}", plans[0].bounds); + assert!(contains(plans[0].bounds, painted_box), "{name}: cpu_boot plan_layers {:?} missed CPU-painted {painted_box:?}", plans[0].bounds); + + let old_lb = old_layer_bounds(inst); + let old_px = [ + old_lb[0].max(0.0).floor() as i32, + old_lb[1].max(0.0).floor() as i32, + old_lb[2].min(w as f32).ceil() as i32, + old_lb[3].min(h as f32).ceil() as i32, + ]; + if area_i32(lb_px) < area_i32(old_px) { + assert!(contains(old_px, lb_px), "{name}: tighter layer_bounds must be subset of old"); + tighter_layer_sites.push(*name); + } + } + } + + assert!(tighter_layer_sites.contains(&"rect_banded"), "expected tighter layer bounds on banded rect: {tighter_layer_sites:?}"); + assert!(tighter_layer_sites.contains(&"shadow_banded"), "expected tighter layer bounds on banded shadow: {tighter_layer_sites:?}"); + + // A clipped-away child inside an isolated layer must not pull `plan_layers` bounds outward. + let clipped_away = Instance { clip: [200.0, 200.0, 220.0, 220.0], ..base(Kind::Rect, [10.0, 10.0, 20.0, 20.0]) }; + let stream = [ + Instance::begin_layer([100.0, 100.0, 20.0, 20.0], NO_CLIP, LayerSpec { opacity: 0.5, ..Default::default() }), + clipped_away, + Instance::end_layer(), + ]; + let (plans, _) = cpu_boot::bin::plan_layers(&stream, (w as u32, h as u32)); + assert_eq!(plans[0].bounds, [100, 100, 120, 120], "clipped-away child must not bloat layer bounds"); +} + +#[test] +fn from_f32_and_bounds_handle_edge_floats_and_nans() { + let reference_from_f32 = |v: f32| -> Option<Kind> { + if v.is_nan() || v.fract() != 0.0 || !(0.0..=13.0).contains(&v) { + return None; + } + Kind::from_u8(v as u8) + }; + + // Every 1/8 step in [-2, 18], plus bit perturbations of every valid kind, subnormals, inf, NaN. + let mut probe = vec![ + -0.0f32, + 0.0, + f32::MIN_POSITIVE, + f32::from_bits(1), + f32::from_bits(0x8000_0001), + 11.5f32, + f32::from_bits(11.5f32.to_bits() + 1), + f32::from_bits(11.5f32.to_bits() - 1), + f32::INFINITY, + f32::NEG_INFINITY, + f32::NAN, + f32::from_bits(0x7fc0_0001), + f32::from_bits(0xffc0_0001), + f32::from_bits(0x7f80_0001), + f32::MAX, + f32::MIN, + ]; + for step in -16..=144 { + probe.push(step as f32 * 0.125); + } + for k in 0..Kind::COUNT { + let bits = Kind::from_u8(k as u8).unwrap().as_f32().to_bits(); + probe.push(f32::from_bits(bits)); + probe.push(f32::from_bits(bits.wrapping_add(1))); + probe.push(f32::from_bits(bits.wrapping_sub(1))); + probe.push(f32::from_bits(bits | 0x8000_0000)); + } + + for v in probe { + assert_eq!(Kind::from_f32(v), reference_from_f32(v), "from_f32({v:?}, bits={:#010x})", v.to_bits()); + let inst = Instance { + rect: [20.0, 30.0, 40.0, 25.0], + params: [0.0, v, 2.0, 1.0], + clip: NO_CLIP, + ..Instance::zeroed() + }; + let qb = inst.quad_bounds(); + let expected_none = matches!(Kind::from_f32(v), Some(Kind::LayerEnd | Kind::Effect | Kind::BackdropBlur)) + || (Kind::from_f32(v).is_none() && v > 11.5); + assert_eq!(qb.is_none(), expected_none, "quad_bounds none mismatch for {v:?}"); + if Kind::from_f32(v).is_none() { + let lb = inst.layer_bounds(); + assert_eq!(lb, [19.0, 29.0, 61.0, 56.0], "layer_bounds fallback for {v:?}"); + } + } + + // Kinds whose growth does not depend on `params[2]` ignore non-finite `params[2]`. + for kind in [Kind::Glyph, Kind::Inset, Kind::Segment, Kind::Triangle, Kind::Image, Kind::Layer] { + let inst = Instance { + rect: [10.0, 12.0, 20.0, 15.0], + params: [0.0, kind.as_f32(), f32::NAN, 1.0], + clip: NO_CLIP, + ..Instance::zeroed() + }; + let b = inst.quad_bounds().expect("valid quad"); + assert!(b.iter().all(|v| v.is_finite()), "{kind:?} quad_bounds leaked NaN p2: {b:?}"); + } + + // Verify `pixel_bounds` matches the un-simplified 8-round reference across clip edge cases. + let ref_pixel_bounds = |i: &Instance, w: i32, h: i32| -> [i32; 4] { + let Some([mut x0, mut y0, mut x1, mut y1]) = i.quad_bounds() else { return [0; 4] }; + if i.kind() == Some(Kind::Glyph) && i.params[0] != 0.0 { + x0 -= 1.0; y0 -= 1.0; x1 += 1.0; y1 += 1.0; + } + let first = |v: f32| (v - 0.5).ceil(); + let c = i.clip; + let px0 = first(x0).max((c[0] - 0.5).floor()).max(0.0); + let py0 = first(y0).max((c[1] - 0.5).floor()).max(0.0); + let px1 = first(x1).min((c[2] + 0.5).ceil()).min(w as f32); + let py1 = first(y1).min((c[3] + 0.5).ceil()).min(h as f32); + if !(px1 > px0 && py1 > py0) { return [0; 4]; } + [px0 as i32, py0 as i32, px1 as i32, py1 as i32] + }; + + let clips = [ + NO_CLIP, + [0.0, 0.0, 256.0, 256.0], + [0.4, 0.5, 100.2, 80.7], + [15.2, 18.8, 45.6, 55.1], + [40.0, 40.0, 40.0, 40.0], + [-5.0, 0.51, 200.5, 120.49], + [f32::NAN, 10.0, 100.0, f32::NAN], + ]; + for clip in clips { + for rect in [[10.3, 12.7, 30.0, 20.0], [0.2, 0.3, 10.0, 10.0], [35.0, 35.0, 50.0, 40.0], [f32::NAN, 10.0, 20.0, 20.0]] { + for kind in [KIND_RECT, KIND_SHADOW, KIND_GLYPH, KIND_LAYER, KIND_LAYER_END, KIND_EFFECT, 14.0, -1.0] { + let inst = Instance { rect, clip, params: [0.0, kind, 2.0, 1.0], ..Instance::zeroed() }; + assert_eq!(inst.pixel_bounds(256, 256), ref_pixel_bounds(&inst, 256, 256), "clip={clip:?} rect={rect:?} kind={kind}"); + } + } + } +} + +#[test] +fn kind_runs_matches_reference_across_valid_none_and_out_of_bounds_spans() { + let reference = |kinds: &[Option<Kind>], span: std::ops::Range<u32>| -> Vec<std::ops::Range<u32>> { + let mut at = span.start; + let mut out = Vec::new(); + while at < span.end { + let kind = kinds.get(at as usize).copied(); + let start = at; + while at < span.end && kinds.get(at as usize).copied() == kind { at += 1; } + out.push(start..at); + } + out + }; + let kinds = [ + Some(Kind::Rect), Some(Kind::Rect), Some(Kind::Glyph), None, None, + Some(Kind::Shadow), Some(Kind::Rect), None, + ]; + for span in [0..0, 0..1, 0..8, 2..6, 3..5, 6..12, 8..12, 10..10] { + let got: Vec<_> = kind_runs(&kinds, span.clone()).collect(); + assert_eq!(got, reference(&kinds, span.clone()), "span {span:?}"); + } +} + +#[test] +fn gpu_spring_opacity_folding_matches_cpu_across_all_kinds() { + use crate::gpu::springs::{Node, Track}; + + let (w, h) = (192u32, 128u32); + let mut atlas = crate::text::Atlas::new(); + atlas.data.resize((crate::text::ATLAS_SIZE * crate::text::ATLAS_SIZE) as usize, 0); + for y in 0..16usize { + for x in 0..16usize { + atlas.data[y * crate::text::ATLAS_SIZE as usize + x] = ((x * 15 + y * 9) & 0xff) as u8; + } + } + atlas.dirty = Some((0, 16)); + + let mut images = crate::pixels::ImageAtlas::default(); + let px = crate::Pixels::new(); + px.set( + 4, + 4, + (0..16u8).flat_map(|i| [220, i.wrapping_mul(15), 80, 255]).collect(), + ); + let placed = images.place(&px, [24.0, 24.0]).expect("place test image"); + + // Non-overlapping grid covering every primitive kind a GPU spring can drive. + let base_instances = vec![ + // (8..44, 8..40): KIND_RECT, opaque fill + opaque border, rounded (checks border_over hide + shrink) + Instance { + rect: [8.0, 8.0, 36.0, 32.0], + radii: [8.0; 4], + fill: [0.15, 0.35, 0.85, 1.0], + border: [0.9, 0.12, 0.1, 1.0], + params: [4.0, KIND_RECT, 0.0, 1.0], + uv: [0.0; 4], + clip: NO_CLIP, + fade: [0; 4], + }, + // (52..88, 8..40): KIND_RECT, translucent fill + translucent border (border.a = 0.6) + Instance { + rect: [52.0, 8.0, 36.0, 32.0], + radii: [6.0; 4], + fill: [0.12, 0.56, 0.24, 0.8], + border: [0.54, 0.06, 0.48, 0.6], + params: [4.0, KIND_RECT, 0.0, 1.0], + uv: [0.0; 4], + clip: NO_CLIP, + fade: [0; 4], + }, + // (96..132, 8..40): KIND_RECT, pre-dimmed (o = 0.6) with per-side border widths + Instance { + rect: [96.0, 8.0, 36.0, 32.0], + radii: [4.0; 4], + fill: [0.12, 0.24, 0.48, 0.6], + border: [0.54, 0.42, 0.06, 0.6], + params: [5.0, KIND_RECT, 0.0, 0.6], + uv: [3.0, 5.0, 4.0, 2.0], + clip: NO_CLIP, + fade: [0; 4], + }, + // (140..176, 8..40): KIND_GRADIENT with gradient border (bw = 4.0, border top -> uv bottom) + Instance { + rect: [140.0, 8.0, 36.0, 32.0], + radii: [6.0; 4], + fill: [0.1, 0.2, 0.7, 1.0], + border: [0.95, 0.2, 0.1, 1.0], + params: [4.0, KIND_GRADIENT, 0.0, 1.0], + uv: [0.1, 0.85, 0.3, 1.0], + clip: NO_CLIP, + fade: [0; 4], + }, + // (8..44, 48..80): KIND_GRADIENT fill-only (bw = 0.0, fill top -> uv bottom) + Instance { + rect: [8.0, 48.0, 36.0, 32.0], + radii: [6.0; 4], + fill: [0.8, 0.2, 0.1, 1.0], + border: [0.0; 4], + params: [0.0, KIND_GRADIENT, 0.0, 1.0], + uv: [0.1, 0.3, 0.9, 1.0], + clip: NO_CLIP, + fade: [0; 4], + }, + // (52..88, 48..80): KIND_SHADOW + Instance { + rect: [56.0, 52.0, 28.0, 24.0], + radii: [6.0; 4], + fill: [0.0, 0.0, 0.0, 0.6], + border: [0.0; 4], + params: [0.0, KIND_SHADOW, 4.0, 1.0], + uv: [0.0; 4], + clip: NO_CLIP, + fade: [0; 4], + }, + // (96..132, 48..80): KIND_INSET + Instance { + rect: [96.0, 48.0, 36.0, 32.0], + radii: [6.0; 4], + fill: [0.05, 0.05, 0.15, 0.7], + border: [0.0; 4], + params: [2.0, KIND_INSET, 3.0, 1.0], + uv: [1.0, 2.0, 0.0, 0.0], + clip: NO_CLIP, + fade: [0; 4], + }, + // (140..176, 48..80): KIND_DASHED + Instance { + rect: [140.0, 48.0, 36.0, 32.0], + radii: [6.0; 4], + fill: [0.9, 0.7, 0.1, 1.0], + border: [0.2, 0.8, 0.9, 1.0], + params: [3.0, KIND_DASHED, 0.0, 1.0], + uv: [6.0, 4.0, 0.0, 0.0], + clip: NO_CLIP, + fade: [0; 4], + }, + // (8..44, 88..120): KIND_RADIAL + Instance { + rect: [8.0, 88.0, 36.0, 32.0], + radii: [6.0; 4], + fill: [0.9, 0.3, 0.2, 1.0], + border: [0.1, 0.4, 0.9, 0.8], + params: [0.0, KIND_RADIAL, 0.0, 1.0], + uv: [18.0, 16.0, 18.0, 16.0], + clip: NO_CLIP, + fade: [0; 4], + }, + // (52..88, 88..120): KIND_SEGMENT + KIND_TRIANGLE + Instance { + rect: [52.0, 88.0, 36.0, 32.0], + radii: [56.0, 92.0, 84.0, 114.0], + fill: [0.95, 0.55, 0.15, 1.0], + border: [0.0; 4], + params: [2.5, KIND_SEGMENT, 1.0, 1.0], + uv: [0.0; 4], + clip: NO_CLIP, + fade: [0; 4], + }, + Instance { + rect: [96.0, 88.0, 36.0, 32.0], + radii: [100.0, 116.0, 114.0, 92.0], + fill: [0.55, 0.3, 0.9, 0.9], + border: [0.0; 4], + params: [7.0, KIND_TRIANGLE, 0.0, 1.0], + uv: [128.0, 116.0, 0.0, 0.0], + clip: NO_CLIP, + fade: [0; 4], + }, + // (140..156, 92..108): KIND_GLYPH + (160..184, 92..116): KIND_IMAGE + Instance { + rect: [140.0, 92.0, 16.0, 16.0], + radii: [0.0; 4], + fill: [0.95, 0.95, 0.85, 1.0], + border: [0.0; 4], + params: [0.0, KIND_GLYPH, 0.0, 1.45], + uv: [0.0, 0.0, 16.0, 16.0], + clip: NO_CLIP, + fade: [0; 4], + }, + Instance { + rect: [160.0, 92.0, 24.0, 24.0], + radii: [4.0; 4], + fill: [0.0, 0.0, 0.0, 0.9], + border: [0.0; 4], + params: [placed.page as f32, KIND_IMAGE, 0.0, 1.0], + uv: placed.rect.map(|v| v as f32), + clip: NO_CLIP, + fade: [0; 4], + }, + ]; + + let gpu = Gpu::headless(); + let clear = [0.06, 0.08, 0.12, 1.0]; + + for alpha in [0.5f32, 0.25] { + // Canonical CPU opacity fold via `instance::end_layer`, applied to each primitive. + let cpu_folded: Vec<Instance> = base_instances + .iter() + .map(|&inst| { + let mut list = vec![ + Instance::begin_layer(inst.rect, NO_CLIP, LayerSpec { opacity: alpha, ..Default::default() }), + inst, + ]; + let mut marks = Vec::new(); + end_layer(&mut list, &mut [], &mut marks, 0, 0); + assert_eq!(list.len(), 1, "single primitive must fold opacity directly"); + list[0] + }) + .collect(); + + for (format, srgb_blend) in [(OFFSCREEN_FORMAT, false), (wgpu::TextureFormat::Bgra8Unorm, true)] { + atlas.dirty = Some((0, 16)); + let mut r_cpu = Renderer::new(&gpu.device, format); + r_cpu.set_srgb_blend(srgb_blend); + r_cpu.upload_images(&gpu.device, &gpu.queue, &mut images); + r_cpu.prepare(&gpu.device, &gpu.queue, &mut atlas, &cpu_folded, (w, h)); + let t_cpu = Offscreen::with_format(&gpu.device, w, h, format); + let mut enc = gpu.device.create_command_encoder(&Default::default()); + r_cpu.draw(&mut enc, &t_cpu.view, clear); + t_cpu.copy(&mut enc); + r_cpu.submit(&gpu.queue, enc); + let px_cpu = t_cpu.read(&gpu.device); + + atlas.dirty = Some((0, 16)); + let zero = Track::constant(0.0); + let node = Node { x: zero, y: zero, opacity: Track::constant(alpha) }; + let ids = vec![0u32; base_instances.len()]; + let mut r_spring = Renderer::with_springs(&gpu.device, format, &[node], &ids); + r_spring.set_srgb_blend(srgb_blend); + r_spring.upload_images(&gpu.device, &gpu.queue, &mut images); + r_spring.prepare(&gpu.device, &gpu.queue, &mut atlas, &base_instances, (w, h)); + let t_spring = Offscreen::with_format(&gpu.device, w, h, format); + let mut enc = gpu.device.create_command_encoder(&Default::default()); + r_spring.draw(&mut enc, &t_spring.view, clear); + t_spring.copy(&mut enc); + r_spring.submit(&gpu.queue, enc); + let px_spring = t_spring.read(&gpu.device); + + let mut max_diff = 0u8; + let mut worst = None; + for y in 0..h { + for x in 0..w { + let i = ((y * w + x) * 4) as usize; + let a = [px_cpu[i], px_cpu[i + 1], px_cpu[i + 2], px_cpu[i + 3]]; + let b = [px_spring[i], px_spring[i + 1], px_spring[i + 2], px_spring[i + 3]]; + let d = (0..4).map(|k| a[k].abs_diff(b[k])).max().unwrap(); + if d > max_diff { + max_diff = d; + worst = Some((x, y, a, b)); + } + } + } + assert!( + max_diff <= 1, + "GPU spring opacity={alpha} format={format:?} drifted from CPU fold: max_diff={max_diff} worst={worst:?}" + ); + + if srgb_blend { + let half = cpu_boot::HalfRounding::of_vendor(gpu.adapter.get_info().vendor); + let scene = cpu_boot::Scene::new(&cpu_folded, &atlas, &images, (w, h), clear) + .srgb_blend(true) + .half_rounding(half); + let mut boot = vec![0u8; (w * h * 4) as usize]; + cpu_boot::paint(&scene, &mut cpu_boot::Target::new(&mut boot, w, h), 1).expect("cpu_boot paints"); + let d = cpu_boot::drift( + cpu_boot::Pixels::bgra(&boot, w, h, w as usize * 4), + cpu_boot::Pixels::bgra(&px_spring, w, h, w as usize * 4), + ); + assert!(d.max <= 1, "GPU spring opacity={alpha} drifted from cpu_boot: {d:?}"); + } + } + } +} + +#[test] +fn shader_consts_and_clip_radii_invariants() { + use super::instance::shader_consts as sc; + + // Generated Kind discriminants and uber threshold match Rust's Kind enum. + assert_eq!(Kind::Rect.as_u8(), sc::KIND_RECT_U8); + assert_eq!(Kind::Shadow.as_u8(), sc::KIND_SHADOW_U8); + assert_eq!(Kind::Glyph.as_u8(), sc::KIND_GLYPH_U8); + assert_eq!(Kind::Inset.as_u8(), sc::KIND_INSET_U8); + assert_eq!(Kind::Gradient.as_u8(), sc::KIND_GRADIENT_U8); + assert_eq!(Kind::Segment.as_u8(), sc::KIND_SEGMENT_U8); + assert_eq!(Kind::Triangle.as_u8(), sc::KIND_TRIANGLE_U8); + assert_eq!(Kind::Image.as_u8(), sc::KIND_IMAGE_U8); + assert_eq!(Kind::Layer.as_u8(), sc::KIND_LAYER_U8); + assert_eq!(Kind::LayerEnd.as_u8(), sc::KIND_LAYER_END_U8); + assert_eq!(Kind::Dashed.as_u8(), sc::KIND_DASHED_U8); + assert_eq!(Kind::Radial.as_u8(), sc::KIND_RADIAL_U8); + assert!(Kind::Radial.as_f32() < sc::UBER_MAX_KIND_THRESHOLD); + assert!(Kind::Effect.as_f32() > sc::UBER_MAX_KIND_THRESHOLD); + assert!(Kind::BackdropBlur.as_f32() > sc::UBER_MAX_KIND_THRESHOLD); + + // Analytic checks on WGSL math constants mirrored into Rust. + assert_eq!(CONTINUOUS_K.to_bits(), sc::CONTINUOUS_K.to_bits()); + assert_eq!(sc::CONTINUOUS_PI.to_bits(), std::f32::consts::PI.to_bits()); + let unit_g = |x: f32| (-0.5 * x * x).exp() / (2.0 * std::f32::consts::PI).sqrt(); + let expected_shadow_inside = 3.0 * (unit_g(0.75) + unit_g(2.25)); + assert!((sc::SHADOW_INSIDE - expected_shadow_inside).abs() < 1e-6); + assert_eq!(sc::OUTLINE_TEX_WIDTH, crate::text::outline::WIDTH); + + // `variant::LCD_MEAN_EPSILON` matches the threshold literal in `variant::DUAL_ENTRY`. + let eps_start = variant::DUAL_ENTRY.find("mean < ").expect("DUAL_ENTRY mean threshold") + "mean < ".len(); + let eps_end = eps_start + variant::DUAL_ENTRY[eps_start..].find(')').expect("DUAL_ENTRY threshold paren"); + let dual_eps: f32 = variant::DUAL_ENTRY[eps_start..eps_end].trim().parse().expect("parse DUAL_ENTRY epsilon"); + assert_eq!(dual_eps.to_bits(), variant::LCD_MEAN_EPSILON.to_bits()); + + // `pack_clip_radii` / `unpack_clip_radii` agree on fine, coarse, uniform and continuous corners. + let big = [0.0, 0.0, 1000.0, 1000.0]; + let fine_max = sc::CLIP_RADII_LANE_MASK as f32 * sc::CLIP_RADII_FINE_STEP; + let coarse_max = sc::CLIP_RADII_LANE_MASK as f32 * sc::CLIP_RADII_COARSE_STEP; + for radii in [ + [0.0; 4], + [12.0; 4], + [-18.5; 4], + [4.0, 8.5, 0.0, fine_max], + [-4.0, -8.5, 0.0, -fine_max], + [0.0, 64.0, 128.0, coarse_max], + [-2.0, -66.0, 0.0, -coarse_max], + ] { + let packed = pack_clip_radii(big, radii); + assert_eq!(unpack_clip_radii(packed), radii, "clip radii round-trip for {radii:?}"); + } + + // `crate::color::srgb_encode` agrees with `shader.wgsl`'s IEC 61966-2-1 transfer function. + for byte in 0..=255u8 { + let v = (byte as f32 / 255.0).clamp(0.0, 1.0); + let wgsl = if v <= 0.0031308 { v * 12.92 } else { 1.055 * v.powf(1.0 / 2.4) - 0.055 }; + assert!((crate::color::srgb_encode(v) - wgsl).abs() < 1e-6, "srgb_encode mismatch at {byte}"); + } +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn wgsl_generated_constants_match_naga_ir() { + use super::instance::shader_consts as sc; + use wgpu::naga::{ArraySize, Binding, Expression, Handle, Literal, Module, TypeInner, UnaryOperator, front::wgsl}; + + let eval_f32 = |m: &Module, mut h: Handle<Expression>| -> f32 { + let mut neg = false; + loop { + match &m.global_expressions[h] { + Expression::Unary { op: UnaryOperator::Negate, expr } => { neg = !neg; h = *expr; } + Expression::Literal(Literal::F32(v)) => return if neg { -*v } else { *v }, + Expression::Literal(Literal::AbstractFloat(v)) => return if neg { -(*v as f32) } else { *v as f32 }, + other => panic!("unexpected f32 const expr: {other:?}"), + } + } + }; + let eval_u32 = |m: &Module, h: Handle<Expression>| -> u32 { + match &m.global_expressions[h] { + Expression::Literal(Literal::U32(v)) => *v, + Expression::Literal(Literal::AbstractInt(v)) => u32::try_from(*v).unwrap(), + other => panic!("unexpected u32 const expr: {other:?}"), + } + }; + let eval_bool = |m: &Module, h: Handle<Expression>| -> bool { + match &m.global_expressions[h] { + Expression::Literal(Literal::Bool(v)) => *v, + other => panic!("unexpected bool const expr: {other:?}"), + } + }; + let const_expr = |m: &Module, name: &str| { + m.constants.iter().find(|(_, c)| c.name.as_deref() == Some(name)) + .unwrap_or_else(|| panic!("WGSL const `{name}` not found")).1.init + }; + let override_expr = |m: &Module, name: &str| { + m.overrides.iter().find(|(_, o)| o.name.as_deref() == Some(name)) + .unwrap_or_else(|| panic!("WGSL override `{name}` not found")).1.init + .unwrap_or_else(|| panic!("WGSL override `{name}` has no default")) + }; + + let classic = wgsl::parse_str(uber_wgsl::CLASSIC).expect("parse CLASSIC"); + assert_eq!(eval_f32(&classic, const_expr(&classic, "CONTINUOUS_K")).to_bits(), sc::CONTINUOUS_K.to_bits()); + assert_eq!(eval_f32(&classic, const_expr(&classic, "SHADOW_INSIDE")).to_bits(), sc::SHADOW_INSIDE.to_bits()); + assert_eq!(eval_f32(&classic, const_expr(&classic, "PINNED_KIND")).to_bits(), sc::PINNED_KIND.to_bits()); + + let windfoil = wgsl::parse_str(uber_wgsl::WINDFOIL).expect("parse WINDFOIL"); + assert_eq!(eval_f32(&windfoil, const_expr(&windfoil, "OUTLINE_HINT_REACH")).to_bits(), sc::OUTLINE_HINT_REACH.to_bits()); + assert_eq!(eval_bool(&windfoil, const_expr(&windfoil, "OUTLINE_SUBPIXEL")), sc::OUTLINE_SUBPIXEL); + + // Every pinned variant and the dual-source variant resolve their substituted constants in Naga. + for &kind in &variant::PINNED { + let src = variant::pinned_wgsl(kind).expect("pinned_wgsl"); + let m = wgsl::parse_str(&src).expect("parse pinned WGSL"); + assert_eq!(eval_f32(&m, const_expr(&m, "PINNED_KIND")), kind as f32); + } + let dual = wgsl::parse_str(&variant::dual_wgsl().expect("dual_wgsl")).expect("parse dual WGSL"); + assert!(eval_bool(&dual, const_expr(&dual, "OUTLINE_SUBPIXEL"))); + + // `layer_blur.wgsl` overrides and `Uniforms.taps` array length. + let lb = wgsl::parse_str(layer_blur::WGSL).expect("parse layer_blur.wgsl"); + assert_eq!(eval_u32(&lb, override_expr(&lb, sc::LAYER_BLUR_OVERRIDE_MODE)), sc::LAYER_BLUR_MODE_BLUR); + assert!(!eval_bool(&lb, override_expr(&lb, sc::LAYER_BLUR_OVERRIDE_ADDITIVE))); + let (_, uniforms) = lb.types.iter().find(|(_, t)| t.name.as_deref() == Some("Uniforms")).expect("Uniforms"); + let TypeInner::Struct { members, .. } = &uniforms.inner else { panic!("Uniforms is not a struct") }; + let taps = members.iter().find(|m| m.name.as_deref() == Some("taps")).expect("Uniforms.taps"); + let TypeInner::Array { size: ArraySize::Constant(n), .. } = lb.types[taps.ty].inner else { panic!("taps not fixed array") }; + assert_eq!(n.get() as usize, sc::LAYER_BLUR_TAPS); + + // Vertex input `@location(N)` bindings in Naga agree with `shader_consts` for uber and backdrop_composite. + let check_locs = |label: &str, m: &Module, expected: &[(&str, u32)]| { + let (_, ty) = m.types.iter().find(|(_, t)| t.name.as_deref() == Some("In")).unwrap_or_else(|| panic!("{label}: no In")); + let TypeInner::Struct { members, .. } = &ty.inner else { panic!("{label}: In not struct") }; + for &(field, loc) in expected { + let member = members.iter().find(|m| m.name.as_deref() == Some(field)).unwrap_or_else(|| panic!("{label}: In.{field}")); + assert!(matches!(member.binding, Some(Binding::Location { location, .. }) if location == loc), + "{label}: In.{field} expected @location({loc}), got {:?}", member.binding); + } + }; + check_locs("CLASSIC", &classic, &[ + ("rect", sc::ATTR_RECT_LOC), ("radii", sc::ATTR_RADII_LOC), ("fill", sc::ATTR_FILL_LOC), ("border", sc::ATTR_BORDER_LOC), + ("params", sc::ATTR_PARAMS_LOC), ("uv", sc::ATTR_UV_LOC), ("clip", sc::ATTR_CLIP_LOC), ("fade", sc::ATTR_FADE_LOC), + ]); + let bc = wgsl::parse_str(&backdrop_blur::composite_wgsl()).expect("parse backdrop_composite.wgsl"); + check_locs("backdrop_composite", &bc, &[ + ("rect", sc::ATTR_RECT_LOC), ("radii", sc::ATTR_RADII_LOC), ("fill", sc::ATTR_FILL_LOC), + ("clip", sc::ATTR_CLIP_LOC), ("fade", sc::ATTR_FADE_LOC), + ]); +} diff --git a/app/vendor/rune/crates/rune/src/render/backdrop_blur.rs b/app/vendor/rune/crates/rune/src/render/backdrop_blur.rs new file mode 100644 index 0000000..f7acbbc --- /dev/null +++ b/app/vendor/rune/crates/rune/src/render/backdrop_blur.rs @@ -0,0 +1,522 @@ +//! In-window backdrop blur (`El::backdrop_blur`, `KIND_BACKDROP_BLUR` records). At each record +//! the pass splits (`ActivePass::split`) and copies what is below into the pooled backdrop, a +//! dual-filter pyramid blurs it at half resolution inside the record's rect plus the blur's reach, +//! and a composite quad draws the result inside the record's rounded rect and clip. The pyramid +//! covers only that region, not the window, and grows to the largest one seen. Built on the +//! first record; frames without one never touch it. +use bytemuck::{Pod, Zeroable}; + +use super::*; + +/// Backdrop-blurred elements per frame. Elements past this many draw only their fill. +pub const MAX_BACKDROP_BLURS: usize = 4; + +/// Pyramid levels below the backdrop, the first at half resolution. +pub(in crate::render) const MIPS: u32 = 7; +/// Uniform slot stride: the largest `min_uniform_buffer_offset_alignment` WebGPU allows. +const SLOT: u64 = 256; +/// Uniform slots per record: one per level for passes that read the pyramid, then the first +/// down pass, which reads the backdrop. +const SLOTS: usize = MIPS as usize + 1; +/// Pyramid sizes are multiples of this many half-resolution texels, so every level halves +/// exactly and small changes in a region's size don't reallocate. +pub(in crate::render) const STEP: u32 = 1 << (MIPS - 1); +/// Standard deviation in device pixels of the pyramid's blur when its up chain starts at level +/// `n` at full weight (`n = 0`: the half-resolution downsample alone). Measured from the +/// filters' line spread; each level doubles it, and a crossfade mixes variances linearly. +pub(in crate::render) const SIGMAS: [f32; MIPS as usize] = [1.58, 4.53, 9.62, 19.51, 39.15, 78.36, 156.2]; + +#[repr(C)] +#[derive(Clone, Copy, Pod, Zeroable)] +pub(super) struct Level { + /// x: share of the coarser level in an up pass. + pub(super) w: [f32; 4], + /// The region's bounds in the source's uv, clamping every tap. + pub(super) region: [f32; 4], + /// Source uv from target uv: `uv * xy + zw`. + pub(super) map: [f32; 4], + /// Where the pyramid sits, in window device pixels: origin xy, extent zw. Level 0 of each + /// slot carries it for the composite. + pub(super) place: [f32; 4], +} + +const _: () = { + assert!(std::mem::size_of::<Level>() == 64); + assert!(std::mem::offset_of!(Level, w) == 0); + assert!(std::mem::offset_of!(Level, region) == 16); + assert!(std::mem::offset_of!(Level, map) == 32); + assert!(std::mem::offset_of!(Level, place) == 48); +}; + +/// Planned pyramid geometry for one `KIND_BACKDROP_BLUR` record, shared with `cpu_boot::backdrop`. +#[derive(Clone, Copy, Debug)] +pub(in crate::render) struct Plan { + /// The up chain starts at this level (at least 1), mixing `share` of it with the finer level. + pub levels: usize, + pub share: f32, + /// Window device pixels blurred: the rect plus the blur's reach, inside the viewport. + pub region: [f32; 4], + /// The pyramid's window origin, aligned to a texel of level `levels`. + pub origin: [f32; 2], + /// Minimum level-0 pyramid size in half-resolution texels (a positive multiple of `STEP`). + pub size: [u32; 2], +} + +/// Plans one backdrop blur record's region, aligned origin, start level and minimum pyramid size, +/// or returns `None` when its region is empty. +pub(in crate::render) fn plan_region(i: &Instance, viewport: (u32, u32)) -> Option<Plan> { + let sigma = i.params[0]; + let (n, share) = levels(sigma, MIPS as usize - 1); + let reach = sigma.min(SIGMAS[n]) * 3.0 + 2.0; + let v = [viewport.0 as f32, viewport.1 as f32]; + let region = [ + (i.rect[0] - reach).max(0.0), + (i.rect[1] - reach).max(0.0), + (i.rect[0] + i.rect[2] + reach).min(v[0]), + (i.rect[1] + i.rect[3] + reach).min(v[1]), + ]; + if region[2] <= region[0] || region[3] <= region[1] { return None; } + // On level n's texel grid, so the blur stays put while content scrolls under it. + let align = (2u32 << n) as f32; + let origin = [(region[0] / align).floor() * align, (region[1] / align).floor() * align]; + let size = [0, 1].map(|k| ((((region[k + 2] - origin[k]) / 2.0).ceil() as u32).next_multiple_of(STEP)).max(STEP)); + Some(Plan { levels: n, share, region, origin, size }) +} + +/// Inclusive-start, exclusive-end texel bounds `(x0, y0, x1, y1)` of pyramid level `m` covering +/// `region` plus two texels on each side (the reach of its taps into the next level), clamped to +/// the level's dimensions. +pub(in crate::render) fn level_scissor(region: [f32; 4], origin: [f32; 2], pyramid: [u32; 2], m: usize) -> (u32, u32, u32, u32) { + let k = (2u32 << m) as f32; + let (w, h) = ((pyramid[0] >> m).max(1), (pyramid[1] >> m).max(1)); + let x = (((region[0] - origin[0]) / k).floor() as u32).saturating_sub(2).min(w - 1); + let y = (((region[1] - origin[1]) / k).floor() as u32).saturating_sub(2).min(h - 1); + let r = (((region[2] - origin[0]) / k).ceil() as u32 + 2).min(w); + let b = (((region[3] - origin[1]) / k).ceil() as u32 + 2).min(h); + (x, y, r.max(x + 1), b.max(y + 1)) +} + +/// One record's pyramid run, prepared with its uniforms. +#[derive(Clone, Copy)] +struct Record { + at: u32, + slot: usize, + /// The up chain starts at this level (at least 1). + levels: usize, + /// Window device pixels blurred: the rect plus the blur's reach, inside the viewport. + region: [f32; 4], + /// The pyramid's window origin, aligned to a texel of level `levels`. + origin: [f32; 2], +} + +struct Pyramid { + /// Level 0 in texels; level m is `size >> m`. + size: [u32; 2], + down: Vec<wgpu::TextureView>, + up: Vec<wgpu::TextureView>, + /// The down pass into level m + 1 reads level m. + down_binds: Vec<wgpu::BindGroup>, + /// The up pass into level m reads down level m + 1 (where the chain starts) or up level m + 1. + up_binds: Vec<(wgpu::BindGroup, Option<wgpu::BindGroup>)>, + /// Up level 0, what the composite samples. + result: wgpu::BindGroup, +} + +/// The down and up passes' shader (`backdrop_blur.wgsl`). +pub(crate) const BLUR_WGSL: &str = include_str!("../shaders/backdrop_blur.wgsl"); + +/// The composite's shader: the clip helpers, then `backdrop_composite.wgsl`. +pub(crate) fn composite_wgsl() -> String { format!("{CLIP_WGSL}\n{}", include_str!("../shaders/backdrop_composite.wgsl")) } + +fn composite_from_wgsl(device: &wgpu::Device, wgsl: &str) -> super::dxbc::Shaders { + super::dxbc::Shaders::one(device.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some("backdrop blur composite"), source: wgpu::ShaderSource::Wgsl(wgsl.into()) })) +} + +pub(super) struct BackdropBlur { + down: wgpu::RenderPipeline, + up: wgpu::RenderPipeline, + level_layout: wgpu::BindGroupLayout, + result_layout: wgpu::BindGroupLayout, + composite_layout: wgpu::PipelineLayout, + /// The composite's stages: precompiled (`composite_precompiled`) or from WGSL. + composite: super::dxbc::Shaders, + composite_precompiled: bool, + composites: Vec<(wgpu::TextureFormat, wgpu::RenderPipeline)>, + sampler: wgpu::Sampler, + dummy: wgpu::TextureView, + uniforms: wgpu::Buffer, + pyramid: Option<Pyramid>, + /// The down pass into level 0, reading the pooled backdrop of each format. + first: Vec<(wgpu::TextureFormat, wgpu::BindGroup)>, + records: Vec<Record>, +} + +/// The up chain's start level `n` (1..=top) and the share of level `n` that gives `sigma`. +pub(in crate::render) fn levels(sigma: f32, top: usize) -> (usize, f32) { + let top = top.clamp(1, SIGMAS.len() - 1); + let sigma = sigma.clamp(SIGMAS[0], SIGMAS[top]); + let n = (1..=top).find(|&n| sigma <= SIGMAS[n]).unwrap_or(top); + let (a, b) = (SIGMAS[n - 1], SIGMAS[n]); + (n, ((sigma * sigma - a * a) / (b * b - a * a)).clamp(0.0, 1.0)) +} + +impl BackdropBlur { + pub(super) fn new(device: &wgpu::Device, uber: &wgpu::BindGroupLayout) -> Self { + let texture = |binding| wgpu::BindGroupLayoutEntry { + binding, + visibility: wgpu::ShaderStages::FRAGMENT, + ty: wgpu::BindingType::Texture { + sample_type: wgpu::TextureSampleType::Float { filterable: true }, + view_dimension: wgpu::TextureViewDimension::D2, + multisampled: false, + }, + count: None, + }; + let sampler_entry = |binding| wgpu::BindGroupLayoutEntry { + binding, + visibility: wgpu::ShaderStages::FRAGMENT, + ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering), + count: None, + }; + let levels_entry = |binding, visibility| wgpu::BindGroupLayoutEntry { + binding, + visibility, + ty: wgpu::BindingType::Buffer { + ty: wgpu::BufferBindingType::Uniform, + has_dynamic_offset: true, + min_binding_size: wgpu::BufferSize::new(std::mem::size_of::<Level>() as u64), + }, + count: None, + }; + let level_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + label: Some("backdrop blur level"), + entries: &[texture(0), texture(1), sampler_entry(2), levels_entry(3, wgpu::ShaderStages::FRAGMENT)], + }); + let result_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + label: Some("backdrop blur result"), + entries: &[texture(0), sampler_entry(1), levels_entry(2, wgpu::ShaderStages::FRAGMENT)], + }); + let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + label: Some("backdrop blur"), + bind_group_layouts: &[Some(&level_layout)], + immediate_size: 0, + }); + let pass = |vertex: &wgpu::ShaderModule, fragment: &wgpu::ShaderModule, entry| device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { + label: Some("backdrop blur"), + layout: Some(&layout), + vertex: wgpu::VertexState { module: vertex, entry_point: Some("vs"), compilation_options: Default::default(), buffers: &[] }, + primitive: Default::default(), + depth_stencil: None, + multisample: Default::default(), + fragment: Some(wgpu::FragmentState { + module: fragment, + entry_point: Some(entry), + compilation_options: Default::default(), + targets: &[Some(wgpu::ColorTargetState { format: layers::FORMAT, blend: None, write_mask: wgpu::ColorWrites::ALL })], + }), + multiview_mask: None, + cache: None, + }); + // DX12 takes the bytecode regen_dxbc compiled from this WGSL; elsewhere, or when it's stale or + // refused, the WGSL compiles here. + #[cfg(target_os = "windows")] + let precompiled = super::dxbc::backdrop_blur(device, BLUR_WGSL, |m| (pass(&m[0], &m[1], "fs_down"), pass(&m[0], &m[2], "fs_up"))); + #[cfg(not(target_os = "windows"))] + let precompiled = None; + let (down, up) = precompiled.unwrap_or_else(|| { + let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some("backdrop blur"), source: wgpu::ShaderSource::Wgsl(BLUR_WGSL.into()) }); + (pass(&shader, &shader, "fs_down"), pass(&shader, &shader, "fs_up")) + }); + let composite_wgsl = composite_wgsl(); + #[cfg(target_os = "windows")] + let composite = super::dxbc::backdrop_composite(device, &composite_wgsl); + #[cfg(not(target_os = "windows"))] + let composite = None; + let composite_precompiled = composite.is_some(); + let composite = composite.unwrap_or_else(|| composite_from_wgsl(device, &composite_wgsl)); + let composite_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + label: Some("backdrop blur composite"), + bind_group_layouts: &[Some(uber), Some(&result_layout)], + immediate_size: 0, + }); + let sampler = device.create_sampler(&wgpu::SamplerDescriptor { + label: Some("backdrop blur"), + mag_filter: wgpu::FilterMode::Linear, + min_filter: wgpu::FilterMode::Linear, + ..Default::default() + }); + let dummy = device.create_texture(&wgpu::TextureDescriptor { + label: Some("backdrop blur stand-in"), + size: wgpu::Extent3d { width: 1, height: 1, depth_or_array_layers: 1 }, + mip_level_count: 1, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + format: layers::FORMAT, + usage: wgpu::TextureUsages::TEXTURE_BINDING, + view_formats: &[], + }).create_view(&Default::default()); + let uniforms = device.create_buffer(&wgpu::BufferDescriptor { + label: Some("backdrop blur levels"), + size: (MAX_BACKDROP_BLURS * SLOTS) as u64 * SLOT, + usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + }); + BackdropBlur { + down, up, level_layout, result_layout, composite_layout, composite, composite_precompiled, + composites: Vec::new(), sampler, dummy, uniforms, pyramid: None, first: Vec::new(), records: Vec::new(), + } + } + + fn levels_binding(&self) -> wgpu::BindingResource<'_> { + wgpu::BindingResource::Buffer(wgpu::BufferBinding { + buffer: &self.uniforms, + offset: 0, + size: wgpu::BufferSize::new(std::mem::size_of::<Level>() as u64), + }) + } + + fn level_bind(&self, device: &wgpu::Device, src: &wgpu::TextureView, fine: &wgpu::TextureView) -> wgpu::BindGroup { + device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("backdrop blur level"), + layout: &self.level_layout, + entries: &[ + wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::TextureView(src) }, + wgpu::BindGroupEntry { binding: 1, resource: wgpu::BindingResource::TextureView(fine) }, + wgpu::BindGroupEntry { binding: 2, resource: wgpu::BindingResource::Sampler(&self.sampler) }, + wgpu::BindGroupEntry { binding: 3, resource: self.levels_binding() }, + ], + }) + } + + /// Points the first down pass at the pooled backdrop of `format` (new or resized). + /// Drops the pyramid and the bindings of the pooled backdrops, which `Renderer::give_back` + /// drops; the next blurred frame makes them again. + pub(super) fn give_back(&mut self) { + self.pyramid = None; + self.first.clear(); + } + + pub(super) fn bind_backdrop(&mut self, device: &wgpu::Device, format: wgpu::TextureFormat, view: &wgpu::TextureView) { + let bind = self.level_bind(device, view, &self.dummy); + match self.first.iter_mut().find(|(f, _)| *f == format) { + Some(slot) => slot.1 = bind, + None => self.first.push((format, bind)), + } + } + + pub(super) fn ensure_composite(&mut self, device: &wgpu::Device, format: wgpu::TextureFormat) { + if self.composites.iter().any(|(f, _)| *f == format) { return; } + let make = |shaders: &super::dxbc::Shaders| device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { + label: Some("backdrop blur composite"), + layout: Some(&self.composite_layout), + vertex: wgpu::VertexState { + module: &shaders.vertex, + entry_point: Some("vs"), + compilation_options: Default::default(), + buffers: &[Some(metallib::uber_vertex_layout())], + }, + primitive: metallib::uber_primitive(), + depth_stencil: None, + multisample: Default::default(), + fragment: Some(wgpu::FragmentState { + module: &shaders.fragment, + entry_point: Some("fs"), + compilation_options: Default::default(), + targets: &[Some(wgpu::ColorTargetState { + format, + blend: Some(super::blend_state(Blend::SourceOver)), + write_mask: wgpu::ColorWrites::ALL, + })], + }), + multiview_mask: None, + cache: None, + }); + #[cfg(target_os = "windows")] + if self.composite_precompiled { + if let Some(pipeline) = super::dxbc::checked(device, "backdrop blur composite", "compiling WGSL", || make(&self.composite)) { + self.composites.push((format, pipeline)); + return; + } + self.composite = composite_from_wgsl(device, &composite_wgsl()); + self.composite_precompiled = false; + } + let pipeline = make(&self.composite); + self.composites.push((format, pipeline)); + } + + /// Makes the pyramid's level 0 at least `need` texels, grown in `STEP`s and never past `cap`. + fn ensure_pyramid(&mut self, device: &wgpu::Device, need: [u32; 2], cap: [u32; 2]) { + let have = self.pyramid.as_ref().map_or([0; 2], |p| p.size); + let size = [0, 1].map(|k| have[k].min(cap[k]).max(need[k])); + if size == have { return; } + let mips = MIPS; + let chain = |label| { + let t = device.create_texture(&wgpu::TextureDescriptor { + label: Some(label), + size: wgpu::Extent3d { width: size[0], height: size[1], depth_or_array_layers: 1 }, + mip_level_count: mips, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + format: layers::FORMAT, + usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING, + view_formats: &[], + }); + (0..mips) + .map(|m| t.create_view(&wgpu::TextureViewDescriptor { base_mip_level: m, mip_level_count: Some(1), ..Default::default() })) + .collect::<Vec<_>>() + }; + let (down, up) = (chain("backdrop blur down"), chain("backdrop blur up")); + let m = down.len(); + let down_binds = (1..m).map(|k| self.level_bind(device, &down[k - 1], &self.dummy)).collect(); + let up_binds = (0..m.saturating_sub(1)) + .map(|k| (self.level_bind(device, &down[k + 1], &down[k]), (k + 2 < m).then(|| self.level_bind(device, &up[k + 1], &down[k])))) + .collect(); + let result = device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("backdrop blur result"), + layout: &self.result_layout, + entries: &[ + wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::TextureView(&up[0]) }, + wgpu::BindGroupEntry { binding: 1, resource: wgpu::BindingResource::Sampler(&self.sampler) }, + wgpu::BindGroupEntry { binding: 2, resource: self.levels_binding() }, + ], + }); + self.pyramid = Some(Pyramid { size, down, up, down_binds, up_binds, result }); + } + + /// Records the pyramid passes for `record`, reading the backdrop of `format`. + fn encode(&self, encoder: &mut wgpu::CommandEncoder, format: wgpu::TextureFormat, record: &Record) { + let (Some(pyramid), Some((_, first))) = (&self.pyramid, self.first.iter().find(|(f, _)| *f == format)) else { return }; + let scissor = |m: usize| { + let (x, y, r, b) = level_scissor(record.region, record.origin, pyramid.size, m); + (x, y, r - x, b - y) + }; + let mut run = |pipeline: &wgpu::RenderPipeline, dst: &wgpu::TextureView, bind: &wgpu::BindGroup, m: usize, uniform: usize| { + let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { + label: Some("backdrop blur"), + color_attachments: &[Some(wgpu::RenderPassColorAttachment { + view: dst, + depth_slice: None, + resolve_target: None, + // Taps never read past the scissor, so nothing outside it needs loading. + ops: wgpu::Operations { load: wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT), store: wgpu::StoreOp::Store }, + })], + depth_stencil_attachment: None, + timestamp_writes: None, + occlusion_query_set: None, + multiview_mask: None, + }); + let (x, y, w, h) = scissor(m); + pass.set_scissor_rect(x, y, w, h); + pass.set_pipeline(pipeline); + pass.set_bind_group(0, bind, &[((record.slot * SLOTS + uniform) as u64 * SLOT) as u32]); + pass.draw(0..3, 0..1); + }; + let n = record.levels; + for m in 0..=n { + if m == 0 { run(&self.down, &pyramid.down[0], first, 0, MIPS as usize) } else { run(&self.down, &pyramid.down[m], &pyramid.down_binds[m - 1], m, m) } + } + for m in (0..n).rev() { + let (from_down, from_up) = &pyramid.up_binds[m]; + run(&self.up, &pyramid.up[m], if m + 1 == n { from_down } else { from_up.as_ref().unwrap() }, m, m); + } + } +} + +impl Renderer { + pub(super) fn has_backdrop_blur(&self) -> bool { + self.backdrop_blur.as_ref().is_some_and(|b| !b.records.is_empty()) + } + + /// Builds what this frame's backdrop blur records need and writes their pyramid uniforms. + pub(super) fn prepare_backdrop_blur(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, (vw, vh): (u32, u32)) { + let any = self.effects.iter().any(|(_, i)| i.kind() == Some(Kind::BackdropBlur)); + if let Some(b) = &mut self.backdrop_blur { b.records.clear(); } + if !any || vw == 0 || vh == 0 { return; } + let staging = self.uploads.staging(device, queue); + if self.backdrop_blur.is_none() { + let mut blur = BackdropBlur::new(device, &self.bind_layout); + for bd in &self.backdrops { blur.bind_backdrop(device, bd.format, &bd.view); } + self.backdrop_blur = Some(blur); + } + let Some(blur) = &mut self.backdrop_blur else { return }; + blur.ensure_composite(device, self.format); + for (format, _) in &self.extra { blur.ensure_composite(device, *format); } + if self.layers.targets.iter().any(Option::is_some) { blur.ensure_composite(device, layers::FORMAT); } + let viewport = [vw as f32, vh as f32]; + let mut placed = Vec::new(); + let mut need = [STEP; 2]; + let records = self.effects.iter().filter(|(_, i)| i.kind() == Some(Kind::BackdropBlur)).take(MAX_BACKDROP_BLURS); + for (at, i) in records { + let Some(plan) = plan_region(i, (vw, vh)) else { continue }; + for k in 0..2 { need[k] = need[k].max(plan.size[k]); } + placed.push((*at, plan.levels, plan.share, plan.region, plan.origin)); + } + if placed.is_empty() { return; } + // The window plus the most an aligned origin can sit before it. + let cap = [vw, vh].map(|v| (v.div_ceil(2) + STEP).next_multiple_of(STEP)); + blur.ensure_pyramid(device, need, cap); + let Some(pyramid) = &blur.pyramid else { return }; + let extent = [pyramid.size[0] as f32 * 2.0, pyramid.size[1] as f32 * 2.0]; + let mut levels_data = vec![0u8; MAX_BACKDROP_BLURS * SLOTS * SLOT as usize]; + for (slot, (at, n, share, region, origin)) in placed.into_iter().enumerate() { + let inside = [(region[0] - origin[0]) / extent[0], (region[1] - origin[1]) / extent[1], + (region[2] - origin[0]) / extent[0], (region[3] - origin[1]) / extent[1]]; + let place = [origin[0], origin[1], extent[0], extent[1]]; + for m in 0..SLOTS { + // The first down pass reads the window-sized backdrop; the rest read the pyramid. + let (region, map) = if m == MIPS as usize { + ([region[0] / viewport[0], region[1] / viewport[1], region[2] / viewport[0], region[3] / viewport[1]], + [extent[0] / viewport[0], extent[1] / viewport[1], origin[0] / viewport[0], origin[1] / viewport[1]]) + } else { + (inside, [1.0, 1.0, 0.0, 0.0]) + }; + let level = Level { w: [if m + 1 == n { share } else { 1.0 }, 0.0, 0.0, 0.0], region, map, place }; + let at = (slot * SLOTS + m) * SLOT as usize; + levels_data[at..at + std::mem::size_of::<Level>()].copy_from_slice(bytemuck::bytes_of(&level)); + } + blur.records.push(Record { at, slot, levels: n, region, origin }); + } + let used = blur.records.last().map_or(0, |r| (r.slot + 1) * SLOTS * SLOT as usize); + staging.write_buffer(&blur.uniforms, 0, &levels_data[..used]); + } + + /// Draws the backdrop blur record at `at`: splits the pass to copy and blur what is below, + /// then composites the blur inside the record's rounded rect and clip. Draws nothing (the + /// element shows only its fill) when the pass can't be split or the record wasn't prepared. + pub(super) fn draw_backdrop_blur(&self, pass: &mut ActivePass<'_, '_>, format: wgpu::TextureFormat, at: u32, instance: &Instance, target: Option<usize>) { + let Some(blur) = &self.backdrop_blur else { return }; + let Ok(k) = blur.records.binary_search_by_key(&at, |r| r.at) else { return }; + let record = &blur.records[k]; + let (Some((_, composite)), Some(pyramid)) = (blur.composites.iter().find(|(f, _)| *f == format), &blur.pyramid) else { return }; + let (origin, size) = self.target_frame(target); + let (r, c) = (instance.rect, instance.clip); + let edge = |v: f32, o: f32, max: u32| (v - o).clamp(0.0, max as f32) as u32; + let (x0, y0) = (edge(r[0].max(c[0]).floor(), origin[0], size[0]), edge(r[1].max(c[1]).floor(), origin[1], size[1])); + let (x1, y1) = (edge((r[0] + r[2]).min(c[2]).ceil(), origin[0], size[0]), edge((r[1] + r[3]).min(c[3]).ceil(), origin[1], size[1])); + if x1 <= x0 || y1 <= y0 { return; } + let split = pass.split(self, format, origin, size, target.is_some(), Some(record.region), |encoder, backdrop| { + blur.encode(encoder, backdrop.format, record); + }); + if split.is_none() { return; } + let scope = pass.scissor(); + let [sx, sy, sw, sh] = scope.unwrap_or([0, 0, size[0], size[1]]); + let (x0, y0, x1, y1) = (x0.max(sx), y0.max(sy), x1.min(sx + sw), y1.min(sy + sh)); + if x1 > x0 && y1 > y0 { + let bind = match target { + Some(index) => &self.layers.targets[index].as_ref().unwrap().base, + None => &self.bind_group, + }; + pass.set_scissor_rect(x0, y0, x1 - x0, y1 - y0); + pass.set_pipeline(composite); + pass.set_bind_group(0, bind, &[]); + pass.set_bind_group(1, &pyramid.result, &[(record.slot * SLOTS) as u32 * SLOT as u32]); + pass.set_vertex_buffer(0, self.instances.slice(..)); + pass.draw(0..4, at..at + 1); + } + pass.set_scissor(scope, size); + } +} + +#[cfg(test)] +#[path = "backdrop_blur_tests.rs"] +mod tests; diff --git a/app/vendor/rune/crates/rune/src/render/backdrop_blur_tests.rs b/app/vendor/rune/crates/rune/src/render/backdrop_blur_tests.rs new file mode 100644 index 0000000..e876e92 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/render/backdrop_blur_tests.rs @@ -0,0 +1,18 @@ +use super::{SIGMAS, levels}; + +#[test] +fn levels_cover_the_range_continuously() { + let top = SIGMAS.len() - 1; + assert_eq!(levels(0.0, top), (1, 0.0)); + assert_eq!(levels(SIGMAS[top] * 4.0, top), (top, 1.0)); + let mut last = 0.0; + for k in 1..400 { + let sigma = k as f32 * 0.5; + let (n, share) = levels(sigma, top); + let (a, b) = (SIGMAS[n - 1], SIGMAS[n]); + let got = (a * a + share * (b * b - a * a)).sqrt(); + assert!((got - sigma.clamp(SIGMAS[0], SIGMAS[top])).abs() < 1e-3, "sigma {sigma}: {got}"); + assert!(got >= last); + last = got; + } +} diff --git a/app/vendor/rune/crates/rune/src/render/backdrop_tests.rs b/app/vendor/rune/crates/rune/src/render/backdrop_tests.rs new file mode 100644 index 0000000..e73f127 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/render/backdrop_tests.rs @@ -0,0 +1,110 @@ +use super::*; + +fn rect(rect: [f32; 4], fill: [f32; 4]) -> Instance { + Instance { rect, fill, clip: NO_CLIP, ..bytemuck::Zeroable::zeroed() } +} + +#[test] +fn backdrop_pool_is_lazy_reused_resized_and_follows_live_formats() { + let gpu = Gpu::headless(); + let (device, queue) = (&gpu.device, &gpu.queue); + let mut renderer = Renderer::new(device, OFFSCREEN_FORMAT); + let mut text = crate::text::TextSystem::new(&[], ("Inter", "Inter")); + let mut slot = rect([0.0, 0.0, 16.0, 16.0], [0.0, 0.0, 0.0, 1.0]); + slot.params = [0.0, KIND_EFFECT, 0.0, 1.0]; + for instances in [&[][..], &[slot][..]] { + renderer.prepare(device, queue, &mut text.atlas, instances, (32, 32)); + assert!(renderer.backdrops.is_empty(), "ordinary slots allocate no backdrops"); + } + slot.params[0] = 1.0; + renderer.prepare(device, queue, &mut text.atlas, &[slot], (32, 32)); + let original = renderer.backdrops[0].view.clone(); + renderer.prepare(device, queue, &mut text.atlas, &[slot], (32, 32)); + assert_eq!(renderer.backdrops[0].view, original); + + // Switching after prepare is legal: the next draw must already have the new format's pool. + let format = OFFSCREEN_FORMAT.remove_srgb_suffix(); + renderer.set_format(device, format); + assert!(renderer.backdrops.iter().any(|b| b.format == format)); + for (format, size) in [(format, (48, 24)), (OFFSCREEN_FORMAT, (24, 48)), (format, (32, 32))] { + renderer.set_format(device, format); + renderer.prepare(device, queue, &mut text.atlas, &[slot, slot], size); + let target = Offscreen::with_format(device, size.0, size.1, format); + let mut encoder = device.create_command_encoder(&Default::default()); + let mut backdrops = Vec::new(); + renderer.draw_with_backdrop(&mut encoder, &target.view, [0.0; 4], &mut |phase, site| { + if let EffectPhase::Backdrop(_) = phase { + let view = site.backdrop.unwrap(); + assert_eq!((view.texture().width(), view.texture().height()), size); + assert_eq!(view.texture().format(), format); + backdrops.push(view.clone()); + } + }); + queue.submit([encoder.finish()]); + assert_eq!(backdrops.len(), 2); + assert_eq!(backdrops[0], backdrops[1], "same-format slots share a texture"); + assert_eq!(renderer.backdrops.len(), 2); + } +} + +#[test] +fn split_resets_the_hook_viewport_and_scissor_for_later_primitives() { + let gpu = Gpu::headless(); + let (device, queue) = (&gpu.device, &gpu.queue); + let mut renderer = Renderer::new(device, OFFSCREEN_FORMAT); + let mut text = crate::text::TextSystem::new(&[], ("Inter", "Inter")); + let mut slot = rect([0.0, 0.0, 16.0, 16.0], [0.0, 0.0, 0.0, 1.0]); + slot.params = [1.0, KIND_EFFECT, 0.0, 1.0]; + slot.clip = [0.0, 0.0, 16.0, 16.0]; + let instances = [rect([0.0, 0.0, 32.0, 32.0], [1.0, 0.0, 0.0, 1.0]), slot, + rect([16.0, 0.0, 16.0, 32.0], [0.0, 1.0, 0.0, 1.0])]; + renderer.prepare(device, queue, &mut text.atlas, &instances, (32, 32)); + let target = Offscreen::new(device, 32, 32); + let mut encoder = device.create_command_encoder(&Default::default()); + renderer.draw_with(&mut encoder, &target.view, [0.0; 4], &mut |pass, site| { + assert!(site.backdrop.is_some()); + pass.set_viewport(0.0, 0.0, 1.0, 1.0, 0.0, 1.0); + pass.set_scissor_rect(0, 0, 1, 1); + }); + target.copy(&mut encoder); + queue.submit([encoder.finish()]); + let pixels = target.read(device); + for (x, color) in [(8, [255, 0, 0, 255]), (24, [0, 255, 0, 255])] { + let at = (24 * 32 + x) * 4; + assert_eq!(&pixels[at..at + 4], &color); + } +} + +#[test] +fn backdrop_slot_degrades_when_the_target_cannot_be_copied() { + let gpu = Gpu::headless(); + let (device, queue) = (&gpu.device, &gpu.queue); + let mut renderer = Renderer::new(device, OFFSCREEN_FORMAT); + let mut text = crate::text::TextSystem::new(&[], ("Inter", "Inter")); + let mut slot = rect([0.0, 0.0, 16.0, 16.0], [0.0, 0.0, 0.0, 1.0]); + slot.params = [1.0, KIND_EFFECT, 0.0, 1.0]; + slot.clip = [0.0, 0.0, 16.0, 16.0]; + renderer.prepare(device, queue, &mut text.atlas, &[slot], (32, 32)); + let texture = device.create_texture(&wgpu::TextureDescriptor { + label: Some("no copy src"), + size: wgpu::Extent3d { width: 32, height: 32, depth_or_array_layers: 1 }, + mip_level_count: 1, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + format: OFFSCREEN_FORMAT, + usage: wgpu::TextureUsages::RENDER_ATTACHMENT, + view_formats: &[], + }); + let view = texture.create_view(&Default::default()); + let scope = device.push_error_scope(wgpu::ErrorFilter::Validation); + let mut encoder = device.create_command_encoder(&Default::default()); + let mut draws = 0; + renderer.draw_with(&mut encoder, &view, [0.0; 4], &mut |_, site| { + assert!(site.backdrop.is_none()); + draws += 1; + }); + queue.submit([encoder.finish()]); + let error = pollster::block_on(scope.pop()); + assert!(error.is_none(), "{error:?}"); + assert_eq!(draws, 1); +} diff --git a/app/vendor/rune/crates/rune/src/render/breaker.rs b/app/vendor/rune/crates/rune/src/render/breaker.rs new file mode 100644 index 0000000..8010222 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/render/breaker.rs @@ -0,0 +1,283 @@ +//! Circuit breakers for the pipelines a renderer builds the first time a frame needs them: an +//! isolated layer's (its `Rgba16Float` target's and the composites), `Blend::PlusLighter`'s, and +//! the layer blur's. A pipeline the device refused poisons the command encoder that sets it, +//! and with it the whole frame, so each is built inside error scopes and used only once the +//! device has taken it. One it refused is dropped and not built again, and frames draw without +//! it: an isolated group straight into its parent, a dissolve as source-over, a blur unblurred. +//! +//! A native device answers at once. A browser's error scopes answer a little later, so on the +//! web a frame or two draw that fallback while the answer comes (`Renderer::checking_gpu`). + +use std::sync::{Arc, Mutex}; +use crate::machine::{Attempt, Effects, Seq}; +use super::{Blend, Renderer, layer_blur, layers::FORMAT}; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum Feature { + /// Isolated layers: the uber pipeline for their `Rgba16Float` targets and the composites. + Isolation, + /// `Blend::PlusLighter` layers' pipelines. + PlusLighter, + /// The layer blur's pipelines. + LayerBlur, +} + +/// A browser's answer to a check, once it comes: the error it caught, or none. +pub(super) type Answer = Arc<Mutex<Option<Option<String>>>>; + +/// What the device said about a build. +pub(super) enum Verdict { + /// It answered at once: the error it caught, or none. + Now(Option<String>), + /// It will answer here. + #[cfg_attr(not(target_arch = "wasm32"), allow(dead_code))] + Later(Answer), +} + +#[derive(Default)] +pub(super) enum Health { + /// Not built. + #[default] + Untried, + /// Built; waiting on the browser to say whether the device took it. + Checking { attempt: Attempt, answer: Answer }, + /// The device took it. + Working, + /// The device refused it: dropped, and not built again for this shader. + Broken, +} + +pub(super) enum Event { + /// A frame needs it. + Wanted, + /// It was built, with what the device said. + Built(Verdict), + /// The browser answered the check `attempt`. + Answered { attempt: Attempt, error: Option<String> }, + /// The uber shader changed (`variant::Uber`); what was built from the old one goes. + ShaderChanged, +} + +#[derive(Debug, PartialEq)] +pub(super) enum Effect { + /// Build it in error scopes and send `Built`. + Build, + /// Drop what was built. + Drop, + /// Say once that it can't draw here, and why. + Report(String), +} + +impl Health { + pub(super) fn step(&mut self, seq: &mut Seq, event: Event) -> Effects<Effect> { + match (&*self, event) { + (Health::Untried, Event::Wanted) => Effects::one(Effect::Build), + (Health::Untried, Event::Built(Verdict::Later(answer))) => { + *self = Health::Checking { attempt: seq.next(), answer }; + Effects::none() + } + (Health::Untried, Event::Built(Verdict::Now(error))) => self.settle(error), + (Health::Checking { attempt, .. }, Event::Answered { attempt: answered, error }) if *attempt == answered => self.settle(error), + (Health::Untried, Event::ShaderChanged) => Effects::none(), + (_, Event::ShaderChanged) => { + *self = Health::Untried; + Effects::one(Effect::Drop) + } + _ => Effects::none(), + } + } + + fn settle(&mut self, error: Option<String>) -> Effects<Effect> { + match error { + None => { *self = Health::Working; Effects::none() } + Some(why) => { *self = Health::Broken; Effects::two(Effect::Drop, Effect::Report(why)) } + } + } + + pub(super) fn working(&self) -> bool { matches!(self, Health::Working) } + + /// The browser's answer to the check under way, if it has come. + fn answered(&self) -> Option<Event> { + let Health::Checking { attempt, answer } = self else { return None }; + let error = answer.lock().unwrap_or_else(|e| e.into_inner()).take()?; + Some(Event::Answered { attempt: *attempt, error }) + } +} + +/// The renderer's breakers, one per lazily built feature. +#[derive(Default)] +pub(super) struct Breakers { + seq: Seq, + isolation: Health, + plus_lighter: Health, + layer_blur: Health, + /// Tests: build this feature's pipelines broken, as a device that refuses them would. + #[cfg(test)] + pub refuse: Option<Feature>, +} + +impl Breakers { + pub(super) fn health(&self, feature: Feature) -> &Health { + match feature { + Feature::Isolation => &self.isolation, + Feature::PlusLighter => &self.plus_lighter, + Feature::LayerBlur => &self.layer_blur, + } + } + + fn step(&mut self, feature: Feature, event: Event) -> Effects<Effect> { + let health = match feature { + Feature::Isolation => &mut self.isolation, + Feature::PlusLighter => &mut self.plus_lighter, + Feature::LayerBlur => &mut self.layer_blur, + }; + health.step(&mut self.seq, event) + } + + /// Whether a check is waiting on the browser, which a later frame picks up. + pub(super) fn checking(&self) -> bool { + [&self.isolation, &self.plus_lighter, &self.layer_blur].iter().any(|h| matches!(h, Health::Checking { .. })) + } +} + +const FEATURES: [Feature; 3] = [Feature::Isolation, Feature::PlusLighter, Feature::LayerBlur]; + +impl Renderer { + /// Whether a frame drew a fallback while the browser checks a pipeline; draw another soon, and + /// it draws with the pipeline if the device took it. + #[cfg_attr(not(target_arch = "wasm32"), allow(dead_code))] + pub(crate) fn checking_gpu(&self) -> bool { self.breakers.checking() } + + /// Takes the answers that came since the last frame, then builds what `wanted` needs. + pub(super) fn check_features(&mut self, device: &wgpu::Device, wanted: impl Fn(Feature) -> bool) { + for feature in FEATURES { + if let Some(answer) = self.breakers.health(feature).answered() { self.run_breaker(device, feature, answer); } + if wanted(feature) { self.run_breaker(device, feature, Event::Wanted); } + } + } + + /// The uber shader changed: the features built from it are built again, and checked again, + /// when a frame next needs them. + pub(super) fn shader_changed(&mut self, device: &wgpu::Device) { + for feature in [Feature::Isolation, Feature::PlusLighter] { self.run_breaker(device, feature, Event::ShaderChanged); } + } + + /// Steps `feature`'s breaker on `event` and carries out what it asks, until nothing is left. + fn run_breaker(&mut self, device: &wgpu::Device, feature: Feature, event: Event) { + let mut queue: std::collections::VecDeque<Effect> = self.breakers.step(feature, event).into_iter().collect(); + while let Some(effect) = queue.pop_front() { + match effect { + Effect::Build => { + let verdict = checked(device, || self.build_feature(device, feature)); + queue.extend(self.breakers.step(feature, Event::Built(verdict))); + } + Effect::Drop => self.drop_feature(feature), + Effect::Report(why) => report(device, feature, &why), + } + } + } + + fn build_feature(&mut self, device: &wgpu::Device, feature: Feature) { + // `Rgba8Snorm` never allows `RENDER_ATTACHMENT`, so every pipeline fails validation + // regardless of blend state or passthrough bytecode. + #[cfg(test)] + let format = if self.breakers.refuse == Some(feature) { wgpu::TextureFormat::Rgba8Snorm } else { FORMAT }; + #[cfg(not(test))] + let format = FORMAT; + match feature { + Feature::Isolation => { + if !self.extra.iter().any(|(f, _)| *f == FORMAT) { + let pipeline = Self::pipeline(device, &self.layout, &self.shader, format, self.vertex_entry, Blend::SourceOver); + self.extra.push((FORMAT, pipeline)); + } + let formats: Vec<_> = [self.format].into_iter().chain(self.extra.iter().map(|(f, _)| *f)).collect(); + for format in formats { self.add_layer_format(device, format); } + } + Feature::PlusLighter => { + self.layers.additive = Some(( + Self::pipeline(device, &self.layout, &self.shader, format, self.vertex_entry, Blend::PlusLighter), + Self::pipeline(device, &self.layout, &self.shader, format, "vs", Blend::PlusLighter))); + } + Feature::LayerBlur => self.layers.blur = Some(layer_blur::Pipeline::new(device, format)), + } + } + + fn drop_feature(&mut self, feature: Feature) { + match feature { + Feature::Isolation => { + self.extra.retain(|(f, _)| *f != FORMAT); + let broken = matches!(self.breakers.isolation, Health::Broken); + self.drop_layer_pipelines(broken); + } + Feature::PlusLighter => self.layers.additive = None, + Feature::LayerBlur => self.drop_layer_blur(), + } + } +} + +/// Runs `build` inside error scopes for validation, out-of-memory and internal errors. +#[cfg(not(target_arch = "wasm32"))] +fn checked(device: &wgpu::Device, build: impl FnOnce()) -> Verdict { + let validation = device.push_error_scope(wgpu::ErrorFilter::Validation); + let memory = device.push_error_scope(wgpu::ErrorFilter::OutOfMemory); + let internal = device.push_error_scope(wgpu::ErrorFilter::Internal); + build(); + let errors = [internal.pop(), memory.pop(), validation.pop()].map(pollster::block_on); + Verdict::Now(errors.into_iter().flatten().next().map(|e| e.to_string())) +} + +/// Runs `build` inside the browser's error scopes, which answer later. wgpu's own scopes would +/// panic on an internal error (`platform::web::health`). On WebGL2 (`wgpu-core`, no JS +/// `GPUDevice`), wgpu's thread-local scopes resolve synchronously so refused optional pipelines +/// (such as `Rgba16Float` layers where half-float render targets are absent) still fall back. +#[cfg(target_arch = "wasm32")] +fn checked(device: &wgpu::Device, build: impl FnOnce()) -> Verdict { + let Some(scopes) = crate::platform::web::health::Scopes::push(device) else { + return checked_wgpu_core(device, build); + }; + build(); + let answer = Answer::default(); + let to = answer.clone(); + scopes.pop(move |error| *to.lock().unwrap_or_else(|e| e.into_inner()) = Some(error)); + Verdict::Later(answer) +} + +#[cfg(target_arch = "wasm32")] +fn checked_wgpu_core(device: &wgpu::Device, build: impl FnOnce()) -> Verdict { + use std::future::Future; + use std::task::{Context, Poll, Waker}; + fn poll_now<F: Future<Output = Option<wgpu::Error>>>(fut: F) -> Option<wgpu::Error> { + let mut cx = Context::from_waker(Waker::noop()); + match std::pin::pin!(fut).poll(&mut cx) { + Poll::Ready(err) => err, + Poll::Pending => None, + } + } + let validation = device.push_error_scope(wgpu::ErrorFilter::Validation); + let memory = device.push_error_scope(wgpu::ErrorFilter::OutOfMemory); + let internal = device.push_error_scope(wgpu::ErrorFilter::Internal); + build(); + let error = poll_now(internal.pop()) + .or_else(|| poll_now(memory.pop())) + .or_else(|| poll_now(validation.pop())); + Verdict::Now(error.map(|e| e.to_string())) +} + +fn report(device: &wgpu::Device, feature: Feature, why: &str) { + let fallback = match feature { + Feature::Isolation => "isolated layers draw straight into their parent, without their opacity, blur, clip or turn", + Feature::PlusLighter => "plus-lighter layers draw source-over", + Feature::LayerBlur => "layers draw unblurred", + }; + #[cfg(target_arch = "wasm32")] + web_sys::console::error_1(&format!("rune: a pipeline the GPU refused ({why}) on {}; {fallback}", crate::platform::web::health::summary(device)).into()); + #[cfg(not(target_arch = "wasm32"))] + { + let _ = device; + eprintln!("rune: a pipeline the GPU refused ({why}); {fallback}"); + } +} + +#[cfg(test)] +#[path = "breaker_tests.rs"] +mod tests; diff --git a/app/vendor/rune/crates/rune/src/render/breaker_tests.rs b/app/vendor/rune/crates/rune/src/render/breaker_tests.rs new file mode 100644 index 0000000..dfd8ed9 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/render/breaker_tests.rs @@ -0,0 +1,109 @@ +use super::*; +use crate::render::{Gpu, Instance, KIND_RECT, LayerSpec, NO_CLIP, OFFSCREEN_FORMAT, Offscreen}; +use bytemuck::Zeroable; + +fn step(health: &mut Health, seq: &mut Seq, event: Event) -> Vec<Effect> { + health.step(seq, event).into_iter().collect() +} + +#[test] +fn a_build_the_device_takes_works_and_one_it_refuses_is_dropped_for_good() { + let mut seq = Seq::default(); + let mut health = Health::Untried; + assert_eq!(step(&mut health, &mut seq, Event::Wanted), [Effect::Build]); + assert!(step(&mut health, &mut seq, Event::Built(Verdict::Now(None))).is_empty()); + assert!(health.working()); + assert!(step(&mut health, &mut seq, Event::Wanted).is_empty(), "built once"); + + let mut health = Health::Untried; + let effects = step(&mut health, &mut seq, Event::Built(Verdict::Now(Some("invalid".into())))); + assert_eq!(effects, [Effect::Drop, Effect::Report("invalid".into())]); + assert!(matches!(health, Health::Broken)); + assert!(step(&mut health, &mut seq, Event::Wanted).is_empty(), "never built again"); + // A new shader gets one more try. + assert_eq!(step(&mut health, &mut seq, Event::ShaderChanged), [Effect::Drop]); + assert_eq!(step(&mut health, &mut seq, Event::Wanted), [Effect::Build]); +} + +/// The web's answer comes later; until it does the pipeline isn't used, and an answer to a check +/// the state no longer holds changes nothing. +#[test] +fn a_late_answer_settles_only_its_own_check() { + let mut seq = Seq::default(); + let mut health = Health::Untried; + let answer = Answer::default(); + assert!(step(&mut health, &mut seq, Event::Built(Verdict::Later(answer.clone()))).is_empty()); + assert!(!health.working()); + assert!(health.answered().is_none(), "no answer yet"); + *answer.lock().unwrap() = Some(Some("GPUInternalError: compile failed".into())); + let Some(Event::Answered { attempt, error }) = health.answered() else { panic!("the answer") }; + + assert_eq!(step(&mut health, &mut seq, Event::ShaderChanged), [Effect::Drop]); + assert!(step(&mut health, &mut seq, Event::Answered { attempt, error: error.clone() }).is_empty(), "stale"); + assert!(matches!(health, Health::Untried)); + + let answer = Answer::default(); + step(&mut health, &mut seq, Event::Built(Verdict::Later(answer.clone()))); + *answer.lock().unwrap() = Some(error); + let answered = health.answered().expect("the answer"); + assert_eq!(step(&mut health, &mut seq, answered), [Effect::Drop, Effect::Report("GPUInternalError: compile failed".into())]); + assert!(matches!(health, Health::Broken)); +} + +fn rect(bounds: [f32; 4]) -> Instance { + Instance { rect: bounds, fill: [1.0; 4], clip: NO_CLIP, params: [0.0, KIND_RECT, 0.0, 1.0], ..Instance::zeroed() } +} + +fn group(spec: LayerSpec) -> Vec<Instance> { + let bounds = [4.0, 4.0, 24.0, 8.0]; + vec![Instance::begin_layer(bounds, NO_CLIP, spec), rect(bounds), Instance::end_layer()] +} + +/// Draws three frames of `instances` with `feature`'s pipelines built broken, and checks that no +/// frame set an invalid pipeline; the pixel at the group's centre. +fn draw_refusing(feature: Feature, instances: &[Instance]) -> (Renderer, [u8; 4]) { + let gpu = Gpu::headless_wgpu(); + let mut renderer = Renderer::new(&gpu.device, OFFSCREEN_FORMAT); + renderer.breakers.refuse = Some(feature); + let target = Offscreen::new(&gpu.device, 32, 16); + let mut atlas = crate::text::TextSystem::default().atlas; + let mut out = Vec::new(); + for _ in 0..3 { + let scope = gpu.device.push_error_scope(wgpu::ErrorFilter::Validation); + renderer.prepare(&gpu.device, &gpu.queue, &mut atlas, instances, (32, 16)); + let mut encoder = gpu.device.create_command_encoder(&Default::default()); + renderer.draw(&mut encoder, &target.view, [0.0; 4]); + target.copy(&mut encoder); + renderer.submit(&gpu.queue, encoder); + out = target.read(&gpu.device); + let error = pollster::block_on(scope.pop()); + assert!(error.is_none(), "a frame set a pipeline the device refused: {error:?}"); + } + assert!(!matches!(renderer.breakers.health(feature), Health::Working | Health::Untried)); + let at = (8 * 32 + 16) * 4; + (renderer, [out[at], out[at + 1], out[at + 2], out[at + 3]]) +} + +/// A half-faded group whose layer pipeline the device refused draws its contents straight into +/// the frame, at full opacity, rather than leaving the frame blank. +#[test] +fn a_refused_layer_pipeline_draws_the_group_in_its_parent() { + let (renderer, pixel) = draw_refusing(Feature::Isolation, &group(LayerSpec { opacity: 0.5, ..Default::default() })); + assert_eq!(pixel, [255; 4]); + assert_eq!(renderer.layer_stats().targets, 0); + assert!(!renderer.extra.iter().any(|(f, _)| *f == FORMAT), "the refused pipeline isn't kept"); +} + +#[test] +fn a_refused_plus_lighter_pipeline_draws_source_over() { + let (renderer, pixel) = draw_refusing(Feature::PlusLighter, &group(LayerSpec { opacity: 0.5, blend: Blend::PlusLighter, ..Default::default() })); + let want = [188, 188, 188, 128]; + assert!(pixel.iter().zip(want).all(|(&a, b)| a.abs_diff(b) <= 1), "half white, isolated, source-over: {pixel:?}"); + assert!(renderer.layers.additive.is_none()); +} + +#[test] +fn a_refused_blur_pipeline_draws_unblurred() { + let (_, pixel) = draw_refusing(Feature::LayerBlur, &group(LayerSpec { blur: 4.0, ..Default::default() })); + assert_eq!(pixel, [255; 4]); +} diff --git a/app/vendor/rune/crates/rune/src/render/continuous_corner_tests.rs b/app/vendor/rune/crates/rune/src/render/continuous_corner_tests.rs new file mode 100644 index 0000000..97df003 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/render/continuous_corner_tests.rs @@ -0,0 +1,90 @@ +use super::*; +use super::tests::{pixels, rect}; + +// Apple's continuous corner for r = 1, corner at the origin: three cubics from (0, K) to (K, 0), +// as Core Animation and SwiftUI draw it. +const CURVE: [[f32; 2]; 10] = [ + [0.0, 1.528_664_8], [0.0, 1.088_493_2], [0.0, 0.868_407], [0.074_911_41, 0.631_494], + [0.169_06, 0.372_824], [0.372_824, 0.169_06], [0.631_494, 0.074_911_41], + [0.868_407, 0.0], [1.088_493_2, 0.0], [1.528_664_8, 0.0], +]; + +fn polyline(r: f32) -> Vec<[f32; 2]> { + let mut points = Vec::new(); + for c in CURVE[..].windows(4).step_by(3) { + for k in 0..64 { + let t = k as f32 / 64.0; + let b = [(1.0 - t).powi(3), 3.0 * t * (1.0 - t).powi(2), 3.0 * t * t * (1.0 - t), t.powi(3)]; + points.push(std::array::from_fn(|a| (0..4).map(|j| b[j] * c[j][a]).sum::<f32>() * r)); + } + } + points.push(CURVE[9].map(|v| v * r)); + points +} + +/// Signed distance (negative inside) from `p`, relative to the corner, to the curve, extended +/// along both edges. +fn oracle(p: [f32; 2], line: &[[f32; 2]]) -> f32 { + let e = line[line.len() - 1][0]; + if p[0] >= e || p[1] >= e { return (-p[0]).max(-p[1]); } + let mut best = (f32::MAX, 0.0); + for s in line.windows(2) { + let (a, b) = (s[0], s[1]); + let ab = [b[0] - a[0], b[1] - a[1]]; + let ap = [p[0] - a[0], p[1] - a[1]]; + let t = ((ap[0] * ab[0] + ap[1] * ab[1]) / (ab[0] * ab[0] + ab[1] * ab[1])).clamp(0.0, 1.0); + let d = (ap[0] - ab[0] * t).hypot(ap[1] - ab[1] * t); + if d < best.0 { best = (d, ab[0] * ap[1] - ab[1] * ap[0]); } + } + if best.1 > 0.0 { -best.0 } else { best.0 } +} + +#[test] +fn continuous_corners_follow_apples_curve_in_fills_and_clips() { + let gpu = Gpu::headless(); + let mut renderer = Renderer::new(&gpu.device, OFFSCREEN_FORMAT); + let target = Offscreen::new(&gpu.device, 96, 80); + let mut atlas = crate::text::TextSystem::default().atlas; + let (bounds, r) = ([8.0, 8.0, 72.0, 56.0], 14.0); + let line = polyline(r); + let mut fill = rect(bounds, [1.0; 4]); + fill.radii = [-r; 4]; + let mut clipped = rect([0.0, 0.0, 96.0, 80.0], [1.0; 4]); + clipped.clip = [8.0, 8.0, 80.0, 64.0]; + clipped.round_clip(-r); + for instance in [fill, clipped] { + renderer.prepare(&gpu.device, &gpu.queue, &mut atlas, &[instance], (96, 80)); + let out = pixels(&gpu, &renderer, &target); + let mut worst = 0.0f32; + for y in 0..80 { + for x in 0..96 { + // Fold each pixel centre into its own corner's frame. + let c = [x as f32 + 0.5, y as f32 + 0.5]; + let p = [(c[0] - 8.0).min(80.0 - c[0]), (c[1] - 8.0).min(64.0 - c[1])]; + let want = (0.5 - oracle(p, &line)).clamp(0.0, 1.0); + let got = out[(y * 96 + x) * 4 + 3] as f32 / 255.0; + worst = worst.max((got - want).abs()); + } + } + assert!(worst < 0.04, "coverage off the curve by {worst}"); + } +} + +// Past half the shorter side, Core Animation still draws each corner's whole curve, folded +// into its own quadrant; the shape stays inside the rect and covers its centre. +#[test] +fn continuous_corners_at_half_the_shorter_side_stay_closed() { + let gpu = Gpu::headless(); + let mut renderer = Renderer::new(&gpu.device, OFFSCREEN_FORMAT); + let target = Offscreen::new(&gpu.device, 64, 32); + let mut atlas = crate::text::TextSystem::default().atlas; + let mut capsule = rect([0.0, 0.0, 64.0, 32.0], [1.0; 4]); + capsule.radii = [-100.0; 4]; + renderer.prepare(&gpu.device, &gpu.queue, &mut atlas, &[capsule], (64, 32)); + let out = pixels(&gpu, &renderer, &target); + let alpha = |x: usize, y: usize| out[(y * 64 + x) * 4 + 3]; + assert_eq!(alpha(32, 16), 255); + assert_eq!(alpha(32, 0), 255, "the top edge's centre is flat"); + assert_eq!(alpha(0, 0), 0); + assert!(alpha(0, 16) > 64 && alpha(0, 16) < 255, "the end reaches the rect's side"); +} diff --git a/app/vendor/rune/crates/rune/src/render/cpu_boot.rs b/app/vendor/rune/crates/rune/src/render/cpu_boot.rs new file mode 100644 index 0000000..86940b8 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/render/cpu_boot.rs @@ -0,0 +1,313 @@ +//! A window's first frame painted on the CPU, for the moment before any GPU device exists. +//! +//! `paint` takes the same draw data the renderer consumes for a frame (the instance list after +//! layout, the glyph atlas pages and the image atlas pages) and fills a `Bgra8` buffer with the +//! bytes the GPU would write to a `Bgra8Unorm` swap chain for it: tiles of 64 × 32 pixels run +//! across threads, each instance blended into the 8-bit target in sRGB encoding as the GPU +//! blends (`Renderer::srgb_blend`), with the uber shader's coverage for each kind (`shade.rs` +//! mirrors shader.wgsl function for function). +//! +//! Text comes from the same masks the GPU samples. With [`attach_text`] the text system queues +//! Windfoil masks as it does for a renderer that fills them, and [`fill_masks`] fills them across +//! threads with the coverage function the GPU fill's shader runs (`text::outline::coverage`). +//! Those masks then belong to the CPU copy of the atlas: the GPU's first frame uploads and +//! samples the same texels, so text doesn't change at the hand-over. +//! +//! What it doesn't draw it doesn't guess at: [`Scene::needs_gpu`] names the first thing in a +//! frame that only the GPU can draw (a blurred or isolated layer, a backdrop blur, a compositor's +//! effect slot, a native surface, a glyph drawn from its outline), and `paint` refuses that frame +//! with the same answer. The supported set is the list in `NeedsGpu`'s negation, kept small on +//! purpose: a second renderer that drifts from the first shows as a flicker at the hand-over, so +//! [`drift`] counts how many pixels the GPU's frame changed when it took over. +//! +//! Nothing here runs or allocates until it's called: no statics to initialise, no tables. + +use super::{Instance, Kind}; +use crate::pixels::ImageAtlas; +use crate::text::{Atlas, FontSmoothing}; + +mod backdrop; +pub(super) mod bin; +mod blend; +mod damage; +mod drift; +mod fill; +mod painter; +mod pool; +mod raster; +mod scroll; +#[doc(hidden)] +pub mod record; +mod shade; +pub(crate) mod tool; + +#[cfg(test)] +mod tests; + +pub use drift::{Drift, Pixels, drift, drift_wanted, last_drift}; +pub use fill::{FillReport, attach_text, fill_masks}; +pub use painter::{CpuPainter, Painted}; + +/// One frame's draw data, borrowed from the runtime that built it. +pub struct Scene<'a> { + instances: &'a [Instance], + glyph_pages: Vec<&'a [u8]>, + /// The outline store, for glyphs drawn from their outlines (text whose scale moves). + outlines: Option<&'a crate::text::outline::OutlineStore>, + images: Vec<Image<'a>>, + size: (u32, u32), + clear: [f32; 4], + /// The frame's text draws subpixel masks blended by channel (`Atlas::lcd`). + lcd: bool, + srgb_blend: bool, + native_surfaces: bool, + compositor: bool, + smoothing: Option<FontSmoothing>, + /// How many times the atlas has evicted a page (`Atlas::resets`): a glyph at the same place + /// may be another mask after one. + atlas_resets: u64, + /// How the GPU that takes over rounds into half floats (layers, blur levels). + half: HalfRounding, + /// Packed explicit scroll-fade stops (`Runtime::fade_stops`), matching `Globals::flags[2..4]`. + fade_stops: [f32; 2], +} + +/// How a GPU stores a float into an `Rgba16Float` target. Vendors differ, and a layer's pixels +/// come out a step apart when the CPU guesses wrong, so the painter follows the adapter the +/// window will use (`gpu::pick`, known before any device exists). +/// +/// Measured on D3D12 (a mid-animation layer frame at 2880×1800 against each GPU's own frame of +/// the same draw data): Intel Iris Xe and NVIDIA RTX 3080 Ti both store toward zero (rounded to +/// nearest, 9% of that frame's pixels come out a step off; toward zero, 0.13–0.27%). D3D lets a +/// float target's conversion round either way, so a vendor not measured takes toward zero too; +/// if it rounds to nearest instead, layer pixels can come out a step off (two inside a nested +/// layer), and the drift count at the hand-over says so. +#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)] +pub enum HalfRounding { + #[default] + TowardZero, + /// To nearest, ties to even (IEEE's default). + NearestEven, +} + +/// PCI vendor IDs whose half-float rounding was measured. +const MEASURED: [(u32, HalfRounding); 2] = [(0x8086, HalfRounding::TowardZero), (0x10de, HalfRounding::TowardZero)]; + +impl HalfRounding { + /// The rounding of the GPU with PCI vendor ID `vendor`: measured for Intel and NVIDIA, + /// assumed (toward zero) for any other, AMD (0x1002) among them. + pub fn of_vendor(vendor: u32) -> HalfRounding { + MEASURED.iter().find(|m| m.0 == vendor).map_or(HalfRounding::TowardZero, |m| m.1) + } +} + +/// A scene's switches (`Scene::flags`). +#[derive(Clone, Copy, PartialEq, Debug)] +struct Flags { + srgb_blend: bool, + native_surfaces: bool, + compositor: bool, + lcd: bool, + smoothing: Option<FontSmoothing>, + half: HalfRounding, + fade_stops: [u32; 2], +} + +/// An image atlas page: RGBA8 texels, `width * 4` bytes a row. +#[derive(Clone, Copy)] +pub struct Image<'a> { + width: u32, + data: &'a [u8], + /// Rows written since the renderer last uploaded the page (`ImagePage::dirty`). + dirty: Option<(u32, u32)>, +} + +impl<'a> Scene<'a> { + /// The frame `instances` draws with `atlas`'s glyph masks and `images`' pages into a + /// `size` (device pixels) target cleared to `clear` (`Runtime::clear_color`), blending in + /// sRGB encoding as windows do by default. + pub fn new(instances: &'a [Instance], atlas: &'a Atlas, images: &'a ImageAtlas, size: (u32, u32), clear: [f32; 4]) -> Self { + let glyph_pages = (0..atlas.page_count()).filter_map(|p| atlas.page_data(p)).collect(); + let images = images.pages.iter().map(|p| Image { width: p.width, data: &p.data, dirty: p.dirty }).collect(); + Scene { instances, glyph_pages, outlines: Some(&atlas.outlines), images, size, clear, lcd: atlas.lcd, srgb_blend: true, native_surfaces: false, compositor: false, smoothing: None, atlas_resets: atlas.resets(), half: HalfRounding::default(), fade_stops: [0.0; 2] } + } + + /// Packed explicit scroll-fade stops (`Runtime::fade_stops`). + pub fn fade_stops(mut self, stops: [f32; 2]) -> Self { + self.fade_stops = stops; + self + } + + /// Whether the frame blends in sRGB encoding (`Runtime::srgb_blend`). Linear blending needs + /// the GPU's sRGB target. + pub fn srgb_blend(mut self, on: bool) -> Self { + self.srgb_blend = on; + self + } + + /// Whether the frame shows native surfaces (`Runtime::surfaces`: video, an embedded browser). + pub fn native_surfaces(mut self, any: bool) -> Self { + self.native_surfaces = any; + self + } + + /// Whether the window has a compositor (`App::compositor`), which draws into effect slots. + /// Without one an effect slot draws nothing. + pub fn compositor(mut self, has: bool) -> Self { + self.compositor = has; + self + } + + /// Whether subpixel text blends by channel, as the GPU's subpixel pipeline does; it does when + /// the atlas says so, unless the GPU couldn't (no dual-source blending). + pub fn lcd(mut self, on: bool) -> Self { + self.lcd = on; + self + } + + /// The scene-wide switches, which a frame that only recolours keeps. + fn flags(&self) -> Flags { + Flags { srgb_blend: self.srgb_blend, native_surfaces: self.native_surfaces, compositor: self.compositor, lcd: self.lcd, smoothing: self.smoothing, half: self.half, fade_stops: [self.fade_stops[0].to_bits(), self.fade_stops[1].to_bits()] } + } + + /// How the GPU that will take over rounds half floats (`HalfRounding::of_vendor`). + pub fn half_rounding(mut self, r: HalfRounding) -> Self { + self.half = r; + self + } + + /// The text's font smoothing (`Runtime::font_smoothing`): Slug's coverage has no CPU form. + pub fn font_smoothing(mut self, mode: FontSmoothing) -> Self { + self.smoothing = Some(mode); + self + } + + /// The first thing in this frame only the GPU can draw, or None when `paint` draws all of it. + pub fn needs_gpu(&self) -> Option<NeedsGpu> { + if !self.srgb_blend { return Some(NeedsGpu::LinearBlend); } + if self.native_surfaces { return Some(NeedsGpu::NativeSurface); } + if self.smoothing == Some(FontSmoothing::Slug) { return Some(NeedsGpu::SlugText); } + // How many layer scopes are open: a backdrop blur inside one reads that layer's target. + let mut depth = 0u32; + self.instances.iter().find_map(|i| match i.kind() { + Some(Kind::Layer) if i.params[2] != 0.0 => Some(NeedsGpu::LayerBlur), + Some(Kind::Layer) if i.border[1] != 0.0 => Some(NeedsGpu::TurnedLayer), + Some(Kind::Layer) => { depth += 1; None } + Some(Kind::LayerEnd) => { depth = depth.saturating_sub(1); None } + Some(Kind::BackdropBlur) if depth > 0 => Some(NeedsGpu::BackdropBlur), + Some(Kind::Effect) if self.compositor => Some(NeedsGpu::Effect), + // Slug's rays (coverage 1) have no CPU form; Windfoil's box does (outline::coverage). + Some(Kind::Glyph) if i.radii[3] > 0.0 && (self.outlines.is_none() || i.border[3] == super::instance::shader_consts::OUTLINE_MODE_SLUG as f32) => Some(NeedsGpu::OutlineGlyph), + Some( + Kind::Rect | Kind::Shadow | Kind::Glyph | Kind::Inset | Kind::Gradient + | Kind::Segment | Kind::Triangle | Kind::Image | Kind::Dashed | Kind::Radial + | Kind::Effect | Kind::BackdropBlur, + ) => None, + None => Some(NeedsGpu::UnknownKind), + }) + } +} + +/// Why a frame needs the GPU. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum NeedsGpu { + /// The frame blends in linear light (`App::srgb_blend(false)`). + LinearBlend, + /// It shows a native surface. + NativeSurface, + /// Its text uses Slug's coverage. + SlugText, + /// A layer blurred as a whole (`El::blur`). + LayerBlur, + /// A layer turned as a whole (`Instance::turned`). + TurnedLayer, + /// A backdrop blur inside a layer (it blurs that layer's target). + BackdropBlur, + /// An effect slot a compositor draws into. + Effect, + /// A glyph drawn from its outline with Slug's coverage, or with no outline store at hand. + OutlineGlyph, + /// An instance kind this painter doesn't know. + UnknownKind, + /// The target isn't the scene's size, or its buffer is too small. + Target, +} + +/// Where `paint` writes: `width × height` pixels, four bytes each in memory order B, G, R, A, +/// `stride` bytes from one row's start to the next, row 0 at the top. +pub struct Target<'a> { + pixels: &'a mut [u8], + width: u32, + height: u32, + stride: usize, +} + +impl<'a> Target<'a> { + /// Tightly packed rows (`width * 4` bytes), as a top-down 32-bit DIB section lays them out. + pub fn new(pixels: &'a mut [u8], width: u32, height: u32) -> Self { + Target { pixels, width, height, stride: width as usize * 4 } + } + + /// Rows `stride` bytes apart. + pub fn with_stride(pixels: &'a mut [u8], width: u32, height: u32, stride: usize) -> Self { + Target { pixels, width, height, stride } + } +} + +/// How a `paint` went: each stage's time and what it drew. +#[derive(Clone, Debug, Default)] +pub struct Report { + pub threads: usize, + /// Binning instances into tiles, on the calling thread. + pub bin_ns: u64, + /// Painting every tile, all threads, wall clock. + pub raster_ns: u64, + pub total_ns: u64, + pub tiles: usize, + /// Instance-tile pairs painted, and those a later opaque instance covering the whole tile + /// made unnecessary. + pub binned: usize, + pub culled: usize, + /// Tiles cleared to the clear colour (the rest begin under an opaque instance). + pub cleared: usize, + /// Pixels written by each path: constant spans, per-pixel shading, glyph texels. + pub span_px: u64, + pub shaded_px: u64, + pub glyph_px: u64, + /// The longest one tile took: no thread count paints faster. + pub slowest_tile_ns: u64, + /// Taking backdrop blurs, on the calling thread between phases. + pub blur_ns: u64, +} + +/// Paints `scene` into `target` on `threads` threads (the calling one among them), or says why +/// only the GPU can. +pub fn paint(scene: &Scene<'_>, target: &mut Target<'_>, threads: usize) -> Result<Report, NeedsGpu> { + if let Some(why) = scene.needs_gpu() { return Err(why); } + check_target(scene, target)?; + let start = crate::time::now(); + let bins = bin::Bins::of(scene); + let binned = crate::time::now(); + let tiles: Vec<u32> = (0..bins.tile_count() as u32).collect(); + let mut report = raster::run(scene, &bins, target, &tiles, &raster::Spawn(threads.max(1)), &raster::Spawn(threads.max(1))); + let done = crate::time::now(); + report.bin_ns = ns(binned - start); + report.raster_ns = ns(done - binned); + report.total_ns = ns(done - start); + report.tiles = bins.tile_count(); + report.binned = bins.len(); + report.culled = bins.culled; + Ok(report) +} + +/// Whether `target` is `scene`'s size, with rows at least a row of pixels apart. +fn check_target(scene: &Scene<'_>, target: &Target<'_>) -> Result<(), NeedsGpu> { + let (w, h) = scene.size; + let fits = target.width == w && target.height == h && target.stride >= w as usize * 4 + && target.pixels.len() >= target.stride * h.saturating_sub(1) as usize + w as usize * 4; + if fits { Ok(()) } else { Err(NeedsGpu::Target) } +} + +fn ns(d: std::time::Duration) -> u64 { + u64::try_from(d.as_nanos()).unwrap_or(u64::MAX) +} diff --git a/app/vendor/rune/crates/rune/src/render/cpu_boot/backdrop.rs b/app/vendor/rune/crates/rune/src/render/cpu_boot/backdrop.rs new file mode 100644 index 0000000..6f80b6b --- /dev/null +++ b/app/vendor/rune/crates/rune/src/render/cpu_boot/backdrop.rs @@ -0,0 +1,245 @@ +//! `KIND_BACKDROP_BLUR` on the CPU: `render/backdrop_blur.rs`'s dual-filter pyramid over what is +//! painted below the record, pass for pass. Down passes (backdrop_blur.wgsl's `fs_down`, 13 taps) +//! from the window's pixels at half resolution through the levels the blur's width needs, up passes +//! (`fs_up`, a 9-tap tent mixed with the finer level) back to half resolution, each level stored as +//! `Rgba16Float` holds it, then the composite (backdrop_composite.wgsl) inside the record's rounded +//! rect and clip. Only the record's region is blurred, as on the GPU. + +use std::sync::Mutex; + +use super::raster::{Exec, f16}; +use super::shade::{Clip, sd_rounded}; +use crate::render::Instance; +use crate::render::backdrop_blur::level_scissor; +pub(super) use crate::render::backdrop_blur::{Plan as Record, plan_region as plan}; +use crate::render::instance::shader_consts; + +/// The composite's pixels: the rect inside its clip, by whole pixels (the GPU's scissor). +pub(super) fn bounds(i: &Instance, viewport: (u32, u32)) -> [i32; 4] { + let (r, c) = (i.rect, i.clip); + let x0 = r[0].max(c[0]).floor().clamp(0.0, viewport.0 as f32); + let y0 = r[1].max(c[1]).floor().clamp(0.0, viewport.1 as f32); + let x1 = (r[0] + r[2]).min(c[2]).ceil().clamp(0.0, viewport.0 as f32); + let y1 = (r[1] + r[3]).min(c[3]).ceil().clamp(0.0, viewport.1 as f32); + if x1 <= x0 || y1 <= y0 { return [0; 4]; } + [x0 as i32, y0 as i32, x1 as i32, y1 as i32] +} + +/// A level: `w × h` texels of premultiplied RGBA, as `Rgba16Float` keeps them. +struct Level { + w: u32, + h: u32, + px: Vec<[f32; 4]>, +} + +impl Level { + fn new(w: u32, h: u32) -> Level { Level { w, h, px: vec![[0.0; 4]; (w * h) as usize] } } + + /// A linear-filtered sample at `uv`, clamped to the edge, as the pyramid's sampler takes it. + fn sample(&self, uv: [f32; 2]) -> [f32; 4] { + bilinear(uv, self.w, self.h, |x, y| self.px[(y * self.w + x) as usize]) + } +} + +/// One axis of a linear-filtered sample at `u` (0..=1) over `n` texels, clamped to the edge: +/// the two texels and the weight of the second, as `bilinear` takes them. +#[derive(Clone, Copy)] +struct Axis { + i0: u32, + i1: u32, + f: f32, +} + +fn axis(u: f32, n: u32) -> Axis { + let x = u * n as f32 - 0.5; + let x0 = x.floor(); + let i = |v: f32| (v as i32).clamp(0, n as i32 - 1) as u32; + Axis { i0: i(x0), i1: i(x0 + 1.0), f: x - x0 } +} + +/// `bilinear` from its two axes. +#[inline] +fn tap(x: &Axis, y: &Axis, texel: impl Fn(u32, u32) -> [f32; 4]) -> [f32; 4] { + let mix = |a: [f32; 4], b: [f32; 4], t: f32| -> [f32; 4] { std::array::from_fn(|c| a[c] * (1.0 - t) + b[c] * t) }; + mix(mix(texel(x.i0, y.i0), texel(x.i1, y.i0), x.f), mix(texel(x.i0, y.i1), texel(x.i1, y.i1), x.f), y.f) +} + +fn bilinear(uv: [f32; 2], w: u32, h: u32, texel: impl Fn(u32, u32) -> [f32; 4]) -> [f32; 4] { + let (x, y) = (uv[0] * w as f32 - 0.5, uv[1] * h as f32 - 0.5); + let (fx0, fy0) = (x.floor(), y.floor()); + let (fx, fy) = (x - fx0, y - fy0); + let ix = |v: f32| (v as i32).clamp(0, w as i32 - 1) as u32; + let iy = |v: f32| (v as i32).clamp(0, h as i32 - 1) as u32; + let (x0, x1, y0, y1) = (ix(fx0), ix(fx0 + 1.0), iy(fy0), iy(fy0 + 1.0)); + let mix = |a: [f32; 4], b: [f32; 4], t: f32| -> [f32; 4] { std::array::from_fn(|c| a[c] * (1.0 - t) + b[c] * t) }; + mix(mix(texel(x0, y0), texel(x1, y0), fx), mix(texel(x0, y1), texel(x1, y1), fx), fy) +} + +/// Runs `row(y, texels)` for rows `y0..y1` of `out`, in disjoint horizontal bands on `exec`'s +/// threads. +fn rows(exec: &dyn Exec, out: &mut Level, y0: u32, y1: u32, row: &(dyn Fn(u32, &mut [[f32; 4]]) + Sync)) { + if y1 <= y0 || out.w == 0 { return; } + let w = out.w as usize; + let slice = &mut out.px[y0 as usize * w..y1 as usize * w]; + let total = (y1 - y0) as usize; + let threads = exec.threads().max(1); + if threads == 1 || total == 1 { + for (i, texels) in slice.chunks_exact_mut(w).enumerate() { + row(y0 + i as u32, texels); + } + return; + } + let band = (total / (threads * 4)).max(1); + let work = Mutex::new((y0, slice.chunks_mut(band * w))); + exec.run(&|| loop { + let next = { + let mut guard = work.lock().unwrap_or_else(|e| e.into_inner()); + guard.1.next().map(|chunk| { + let y = guard.0; + guard.0 += (chunk.len() / w) as u32; + (y, chunk) + }) + }; + let Some((y_start, chunk)) = next else { break }; + for (i, texels) in chunk.chunks_exact_mut(w).enumerate() { + row(y_start + i as u32, texels); + } + }); +} + +/// A record's blurred result, level 0 of the up chain, and where it sits. +pub(super) struct Blurred { + up: Level, + place: [f32; 4], +} + +/// Blurs the window's pixels under `rec`: `window(x, y)` reads pixel `(x, y)` as the target +/// holds it, R, G, B, A in 0..=1. +pub(super) fn blur(rec: &Record, viewport: (u32, u32), half: super::HalfRounding, exec: &dyn Exec, window: impl Fn(u32, u32) -> [f32; 4] + Sync) -> Blurred { + let [pw, ph] = rec.size; + let extent = [pw as f32 * 2.0, ph as f32 * 2.0]; + let v = [viewport.0 as f32, viewport.1 as f32]; + let inside = [(rec.region[0] - rec.origin[0]) / extent[0], (rec.region[1] - rec.origin[1]) / extent[1], + (rec.region[2] - rec.origin[0]) / extent[0], (rec.region[3] - rec.origin[1]) / extent[1]]; + let dims = |m: usize| ((pw >> m).max(1), (ph >> m).max(1)); + let scissor = |m: usize| level_scissor(rec.region, rec.origin, rec.size, m); + let window_region = [rec.region[0] / v[0], rec.region[1] / v[1], rec.region[2] / v[0], rec.region[3] / v[1]]; + let window_map = [extent[0] / v[0], extent[1] / v[1], rec.origin[0] / v[0], rec.origin[1] / v[1]]; + // The region's pixels as floats, once: the first pass reads each a few dozen times. A + // bilinear read at the region's edge reaches one pixel past it. + let (cx0, cy0) = ((rec.region[0].floor() as u32).saturating_sub(1), (rec.region[1].floor() as u32).saturating_sub(1)); + let (cx1, cy1) = (((rec.region[2].ceil() as u32) + 1).min(viewport.0), ((rec.region[3].ceil() as u32) + 1).min(viewport.1)); + let cw = cx1 - cx0; + let cache: Vec<[f32; 4]> = (cy0..cy1).flat_map(|y| (cx0..cx1).map(move |x| (x, y))).map(|(x, y)| window(x, y)).collect(); + let window = |x: u32, y: u32| if x >= cx0 && x < cx1 && y >= cy0 && y < cy1 { cache[((y - cy0) * cw + (x - cx0)) as usize] } else { window(x, y) }; + // Every tap's place along x depends on the texel's x alone, and along y on its y: each + // pass takes them once a column and once a row (the same expressions as a tap would), then + // filters with them. + let mut down: Vec<Level> = Vec::with_capacity(rec.levels + 1); + for m in 0..=rec.levels { + let (w, h) = dims(m); + let mut out = Level::new(w, h); + let (sx0, sy0, sx1, sy1) = scissor(m); + let offsets = [-2.0f32, -1.0, 0.0, 1.0, 2.0]; + if m == 0 { + let t = [1.0 / v[0], 1.0 / v[1]]; + let xs: Vec<[Axis; 5]> = (sx0..sx1).map(|tx| { + let u = (tx as f32 + 0.5) / w as f32; + offsets.map(|o| axis((u * window_map[0] + window_map[2] + t[0] * o).clamp(window_region[0], window_region[2]), viewport.0)) + }).collect(); + let ys: Vec<[Axis; 5]> = (sy0..sy1).map(|ty| { + let u = (ty as f32 + 0.5) / h as f32; + offsets.map(|o| axis((u * window_map[1] + window_map[3] + t[1] * o).clamp(window_region[1], window_region[3]), viewport.1)) + }).collect(); + rows(exec, &mut out, sy0, sy1, &|ty, row| { + let ay = &ys[(ty - sy0) as usize]; + for (tx, ax) in (sx0..sx1).zip(&xs) { + row[tx as usize] = down13(|o| tap(&ax[(o[0] + 2.0) as usize], &ay[(o[1] + 2.0) as usize], &window)).map(|v| f16(v, half)); + } + }); + } else { + let src = &down[m - 1]; + let t = [1.0 / src.w as f32, 1.0 / src.h as f32]; + let xs: Vec<[Axis; 5]> = (sx0..sx1).map(|tx| { + let u = (tx as f32 + 0.5) / w as f32; + offsets.map(|o| axis((u + t[0] * o).clamp(inside[0], inside[2]), src.w)) + }).collect(); + let ys: Vec<[Axis; 5]> = (sy0..sy1).map(|ty| { + let u = (ty as f32 + 0.5) / h as f32; + offsets.map(|o| axis((u + t[1] * o).clamp(inside[1], inside[3]), src.h)) + }).collect(); + let texel = |x: u32, y: u32| src.px[(y * src.w + x) as usize]; + rows(exec, &mut out, sy0, sy1, &|ty, row| { + let ay = &ys[(ty - sy0) as usize]; + for (tx, ax) in (sx0..sx1).zip(&xs) { + row[tx as usize] = down13(|o| tap(&ax[(o[0] + 2.0) as usize], &ay[(o[1] + 2.0) as usize], &texel)).map(|v| f16(v, half)); + } + }); + } + down.push(out); + } + let mut coarse: Option<Level> = None; + for m in (0..rec.levels).rev() { + let (w, h) = dims(m); + let mut out = Level::new(w, h); + let src = coarse.as_ref().unwrap_or(&down[rec.levels]); + let fine = &down[m]; + let weight = if m + 1 == rec.levels { rec.share } else { 1.0 }; + let t = [1.0 / src.w as f32, 1.0 / src.h as f32]; + let (sx0, sy0, sx1, sy1) = scissor(m); + // Per column: the coarse level's three taps (−t, 0, +t) and the fine level's one. + let xs: Vec<([Axis; 3], Axis)> = (sx0..sx1).map(|tx| { + let u = (tx as f32 + 0.5) / w as f32; + ([-t[0], 0.0, t[0]].map(|o| axis((u + o).clamp(inside[0], inside[2]), src.w)), axis(u.clamp(inside[0], inside[2]), fine.w)) + }).collect(); + let ys: Vec<([Axis; 3], Axis)> = (sy0..sy1).map(|ty| { + let u = (ty as f32 + 0.5) / h as f32; + ([-t[1], 0.0, t[1]].map(|o| axis((u + o).clamp(inside[1], inside[3]), src.h)), axis(u.clamp(inside[1], inside[3]), fine.h)) + }).collect(); + let coarse_texel = |x: u32, y: u32| src.px[(y * src.w + x) as usize]; + let fine_texel = |x: u32, y: u32| fine.px[(y * fine.w + x) as usize]; + rows(exec, &mut out, sy0, sy1, &|ty, row| { + let ay = &ys[(ty - sy0) as usize]; + for (tx, ax) in (sx0..sx1).zip(&xs) { + // `s(dx, dy)`: the coarse level at offset (dx, dy) texels, each −1, 0 or 1. + let s = |dx: usize, dy: usize| tap(&ax.0[dx], &ay.0[dy], &coarse_texel); + let add = |a: [f32; 4], b: [f32; 4]| -> [f32; 4] { std::array::from_fn(|c| a[c] + b[c]) }; + let scale = |a: [f32; 4], k: f32| a.map(|v| v * k); + // `fs_up`'s sums, in its order. + let mut c = scale(s(1, 1), shader_consts::BACKDROP_UP_CENTER_WEIGHT); + c = add(c, scale(add(add(add(s(2, 1), s(0, 1)), s(1, 2)), s(1, 0)), shader_consts::BACKDROP_UP_AXIAL_WEIGHT)); + c = add(c, add(add(add(s(2, 2), s(0, 0)), s(2, 0)), s(0, 2))); + let c = c.map(|v| v / shader_consts::BACKDROP_UP_DIVISOR); + let f = tap(&ax.1, &ay.1, &fine_texel); + row[tx as usize] = std::array::from_fn(|ch| f16(f[ch] * (1.0 - weight) + c[ch] * weight, half)); + } + }); + coarse = Some(out); + } Blurred { up: coarse.unwrap_or_else(|| down.swap_remove(0)), place: [rec.origin[0], rec.origin[1], extent[0], extent[1]] } +} + +/// `fs_down`'s 13 taps, `s` sampling at a texel offset, summed in its order. +fn down13(s: impl Fn([f32; 2]) -> [f32; 4]) -> [f32; 4] { + let (a, b, c) = (s([-2.0, -2.0]), s([0.0, -2.0]), s([2.0, -2.0])); + let (d, e) = (s([-1.0, -1.0]), s([1.0, -1.0])); + let (f, g, h) = (s([-2.0, 0.0]), s([0.0, 0.0]), s([2.0, 0.0])); + let (i, j) = (s([-1.0, 1.0]), s([1.0, 1.0])); + let (k, l, m) = (s([-2.0, 2.0]), s([0.0, 2.0]), s([2.0, 2.0])); + std::array::from_fn(|ch| { + (d[ch] + e[ch] + i[ch] + j[ch]) * shader_consts::BACKDROP_DOWN_INNER_WEIGHT + + (a[ch] + b[ch] + g[ch] + f[ch]) * shader_consts::BACKDROP_DOWN_OUTER_WEIGHT + + (b[ch] + c[ch] + h[ch] + g[ch]) * shader_consts::BACKDROP_DOWN_OUTER_WEIGHT + + (f[ch] + g[ch] + l[ch] + k[ch]) * shader_consts::BACKDROP_DOWN_OUTER_WEIGHT + + (g[ch] + h[ch] + m[ch] + l[ch]) * shader_consts::BACKDROP_DOWN_OUTER_WEIGHT + }) +} + +/// The composite at pixel centre `p`: the blur inside the rounded rect, cut by the clip, at the +/// record's opacity. +pub(super) fn composite(b: &Blurred, i: &Instance, clip: &Clip, p: [f32; 2]) -> [f32; 4] { + let half = [i.rect[2] * 0.5, i.rect[3] * 0.5]; + let d = sd_rounded([p[0] - i.rect[0] - half[0], p[1] - i.rect[1] - half[1]], half, i.radii); + let cov = (0.5 - d).clamp(0.0, 1.0) * clip.alpha(p) * i.fill[3]; + let col = b.up.sample([(p[0] - b.place[0]) / b.place[2], (p[1] - b.place[1]) / b.place[3]]); + col.map(|v| v * cov) +} diff --git a/app/vendor/rune/crates/rune/src/render/cpu_boot/bin.rs b/app/vendor/rune/crates/rune/src/render/cpu_boot/bin.rs new file mode 100644 index 0000000..cc3fafc --- /dev/null +++ b/app/vendor/rune/crates/rune/src/render/cpu_boot/bin.rs @@ -0,0 +1,347 @@ +//! Binning: which instances touch which tile, in painter order, from the quad the vertex shader +//! would rasterise for each, cut to its clip's reach. An opaque box that covers a whole tile +//! starts that tile over: nothing before it there can show. + +use std::collections::HashMap; + +use super::Scene; +use super::shade::{Clip, has_sides, sides_inner}; +use crate::render::instance::shader_consts; +use crate::render::layers::is_scissor_clip; +use crate::render::{Instance, Kind, MAX_BACKDROP_BLURS, NO_CLIP, corner_extent}; + +pub(super) const TILE_W: u32 = 64; +/// `Bins::within` for an instance that draws straight into the window. +pub(super) const TOP: u32 = u32::MAX; +pub(super) const TILE_H: u32 = 32; + +/// Instances by tile: tile `t`'s are `index[start[t]..start[t + 1]]`. +pub(super) struct Bins { + pub cols: u32, + pub rows: u32, + start: Vec<u32>, + index: Vec<u32>, + /// Each instance's pixel bounds `[x0, y0, x1, y1)`. + pub bounds: Vec<[i32; 4]>, + /// Per tile, whether it begins under an opaque instance (no clear needed). + pub covered: Vec<bool>, + /// The layer each instance draws into: the plan of the innermost layer with a target of its + /// own around it, or `TOP` for the window's pixels. + pub within: Vec<u32>, + /// The frame's backdrop blurs (all outside layers, `Scene::needs_gpu`), in painter order: + /// each must see everything before it painted in its region first. + pub blurs: Vec<(u32, super::backdrop::Record)>, + /// Tiles a blur reads: no later box stands in for what's under it there. + pub quiet: Vec<bool>, + pub culled: usize, + /// Each layer scope as the renderer plans it (`layers.rs`), and which plan each scope's + /// `KIND_LAYER` and `KIND_LAYER_END` belong to. + pub layers: Vec<Layer>, + pub scope: HashMap<u32, u32>, +} + +/// How a layer scope draws, as `Renderer::prepare_layers` decides. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub(in crate::render) enum Show { + /// Fully transparent, empty, or inside one that is: none of it draws. + Hidden, + /// Opaque and unclipped: its contents draw straight into the parent. + Flat, + /// Into its own `Rgba16Float` target, composited at its end. + Render, +} + +#[derive(Clone, Copy, Debug)] +pub(in crate::render) struct Layer { + pub begin: u32, + pub end: u32, + pub show: Show, + /// The target's pixels, `[x0, y0, x1, y1)`: the composite draws nothing outside them. + pub bounds: [i32; 4], + pub additive: bool, + /// The round hole its composite cuts (`El::cutout_circle`). + pub hole: [f32; 4], +} + +/// `Renderer::prepare_layers`' planning walk, for the layers this painter draws (no blur, no +/// turn): each scope's bounds from what it holds, cut to its clip and its ancestors', and whether +/// it draws at all, straight into its parent or into a target of its own. +#[inline(never)] +pub(in crate::render) fn plan_layers(instances: &[Instance], viewport: (u32, u32)) -> (Vec<Layer>, HashMap<u32, u32>) { + struct Open { at: usize, edges: [f32; 4], clip: [f32; 4], limit: [f32; 4], cache: bool } + let mut plans: Vec<Layer> = Vec::new(); + let mut scope = HashMap::new(); + let mut open: Vec<Open> = Vec::new(); + let union = |e: &mut [f32; 4], x0: f32, y0: f32, x1: f32, y1: f32| { + if x1 <= x0 || y1 <= y0 { return; } + e[0] = e[0].min(x0); + e[1] = e[1].min(y0); + e[2] = e[2].max(x1); + e[3] = e[3].max(y1); + }; + for (index, i) in instances.iter().enumerate() { + if i.kind() == Some(Kind::Layer) { + let parent = open.last().map(|o| o.at); + let limit = open.last().map_or(NO_CLIP, |p| [p.clip[0].max(p.limit[0]), p.clip[1].max(p.limit[1]), p.clip[2].min(p.limit[2]), p.clip[3].min(p.limit[3])]); + let opacity = i.fill[3].clamp(0.0, 1.0); + let hidden = opacity == 0.0 || parent.is_some_and(|p| plans[p].show == Show::Hidden); + let cache = i.params[3] == 1.0; + let additive = i.params[0] == shader_consts::LAYER_ADDITIVE_PARAM; + let additive_parent = parent.is_some_and(|p| plans[p].additive); + let hole = if cache { [0.0; 4] } else { i.radii }; + let flat = !cache && opacity == 1.0 && !additive && !additive_parent && i.fade[3] == 0 + && is_scissor_clip(i.clip, i.fade) && hole[3] == 0.0; + let show = if hidden { Show::Hidden } else if flat { Show::Flat } else { Show::Render }; + scope.insert(index as u32, plans.len() as u32); + open.push(Open { at: plans.len(), edges: [i.rect[0], i.rect[1], i.rect[0] + i.rect[2], i.rect[1] + i.rect[3]], clip: i.clip, limit, cache }); + plans.push(Layer { begin: index as u32, end: 0, show, bounds: [0; 4], additive, hole }); + } else if i.kind() == Some(Kind::LayerEnd) { + let Some(o) = open.pop() else { continue }; + scope.insert(index as u32, o.at as u32); + let e = o.edges; + let vis = [(e[0]).max(o.clip[0].max(o.limit[0])).max(0.0).floor(), e[1].max(o.clip[1].max(o.limit[1])).max(0.0).floor(), + e[2].min(o.clip[2].min(o.limit[2])).min(viewport.0 as f32).ceil(), e[3].min(o.clip[3].min(o.limit[3])).min(viewport.1 as f32).ceil()]; + let edges = if o.cache { [e[0].floor(), e[1].floor(), e[2].ceil(), e[3].ceil()] } else { vis }; + let l = &mut plans[o.at]; + l.end = index as u32; + // A cached scope's target holds all of it; the window shows the part inside it. + let shown = [edges[0].max(0.0), edges[1].max(0.0), edges[2].min(viewport.0 as f32), edges[3].min(viewport.1 as f32)]; + l.bounds = [shown[0] as i32, shown[1] as i32, shown[2] as i32, shown[3] as i32]; + if edges[2] <= edges[0] || edges[3] <= edges[1] || (o.cache && (vis[2] <= vis[0] || vis[3] <= vis[1])) { l.show = Show::Hidden; } + if let Some(p) = open.last_mut().filter(|p| !p.cache) { union(&mut p.edges, edges[0], edges[1], edges[2], edges[3]); } + } else if let Some(o) = open.last_mut() { + if o.cache { continue; } + let (x0, y0, x1, y1) = i.layer_bounds_non_scope(); + union(&mut o.edges, x0, y0, x1, y1); + } + } + // A layer that was never closed draws nothing. + for o in open { plans[o.at].show = Show::Hidden; } + (plans, scope) +} + +/// The tiles holding any of `reg`'s pixels (`[x0, y0, x1, y1)`, device px). +pub(super) fn region_tiles(reg: [f32; 4], cols: u32, rows: u32) -> impl Iterator<Item = usize> { + let (tx0, tx1) = (reg[0] as u32 / TILE_W, (reg[2].ceil() as u32).div_ceil(TILE_W).min(cols)); + ((reg[1] as u32 / TILE_H)..(reg[3].ceil() as u32).div_ceil(TILE_H).min(rows)).flat_map(move |ty| (tx0..tx1).map(move |tx| (ty * cols + tx) as usize)) +} + +pub(super) fn cut(a: [i32; 4], b: [i32; 4]) -> [i32; 4] { + let r = [a[0].max(b[0]), a[1].max(b[1]), a[2].min(b[2]), a[3].min(b[3])]; + if r[2] > r[0] && r[3] > r[1] { r } else { [0; 4] } +} + +impl Bins { + pub(super) fn of(scene: &Scene<'_>) -> Bins { + let (w, h) = scene.size; + let (cols, rows) = (w.div_ceil(TILE_W), h.div_ceil(TILE_H)); + let tiles = (cols * rows) as usize; + let mut bounds: Vec<[i32; 4]> = scene.instances.iter().map(|i| pixel_bounds(i, w as i32, h as i32)).collect(); + let (layers, scope) = plan_layers(scene.instances, (w, h)); + // Within a layer drawn to its own target or scissored flat, nothing reaches past its + // bounds; inside a target of its own, nothing stands in for what's under the layer. + let mut within = vec![TOP; scene.instances.len()]; + let mut stack: Vec<([i32; 4], u32)> = Vec::new(); + let mut n = 0; + while n < scene.instances.len() { + let inside = stack.last().map(|s| s.0); + within[n] = stack.last().map_or(TOP, |s| s.1); + if let Some(&p) = scope.get(&(n as u32)) { + let l = &layers[p as usize]; + if scene.instances[n].kind() == Some(Kind::Layer) { + match l.show { + Show::Hidden => { + for b in &mut bounds[n..=l.end as usize] { *b = [0; 4]; } + n = l.end as usize + 1; + continue; + } + Show::Flat => { + bounds[n] = [0; 4]; + let i = &scene.instances[n]; + let scissor = if i.clip == NO_CLIP { + inside.unwrap_or([0, 0, w as i32, h as i32]) + } else { + let s = [ + i.clip[0].floor().clamp(0.0, w as f32) as i32, + i.clip[1].floor().clamp(0.0, h as f32) as i32, + i.clip[2].ceil().clamp(0.0, w as f32) as i32, + i.clip[3].ceil().clamp(0.0, h as f32) as i32, + ]; + let s = if s[2] > s[0] && s[3] > s[1] { s } else { [0; 4] }; + inside.map_or(s, |o| cut(s, o)) + }; + stack.push((scissor, within[n])); + } + Show::Render => { + bounds[n] = inside.map_or(l.bounds, |o| cut(l.bounds, o)); + stack.push((bounds[n], p)); + } + } + } else { + let popped = stack.pop(); + bounds[n] = if l.show == Show::Render { popped.map_or([0; 4], |s| s.0) } else { [0; 4] }; + within[n] = stack.last().map_or(TOP, |s| s.1); + } + } else if let Some(o) = inside { + bounds[n] = cut(bounds[n], o); + } + n += 1; + } + let mut blurs = Vec::new(); + let mut quiet = vec![false; tiles]; + for (n, i) in scene.instances.iter().enumerate().filter(|(_, i)| i.kind() == Some(Kind::BackdropBlur)).take(MAX_BACKDROP_BLURS) { + bounds[n] = super::backdrop::bounds(i, (w, h)); + let Some(rec) = super::backdrop::plan(i, (w, h)) else { continue }; + for t in region_tiles(rec.region, cols, rows) { quiet[t] = true; } + blurs.push((n as u32, rec)); + } + // The last opaque instance covering each tile whole, plus one (0: none). + let mut first = vec![0u32; tiles]; + for (n, i) in scene.instances.iter().enumerate() { + let b = bounds[n]; + if b[2] <= b[0] || b[3] <= b[1] || within[n] != TOP { continue; } + if let Some(solid) = opaque_box(i) { + let clip = Clip::of(i); + let (tx0, ty0) = ((b[0] as u32).div_ceil(TILE_W), (b[1] as u32).div_ceil(TILE_H)); + let (tx1, ty1) = ((b[2] as u32 / TILE_W).min(cols), (b[3] as u32 / TILE_H).min(rows)); + for ty in ty0..ty1 { + let (y0, y1) = ((ty * TILE_H) as f32 + 0.5, ((ty + 1) * TILE_H).min(h) as f32 - 0.5); + let span = |y: f32| intersect(solid.span(y), clip_span(&clip, y)); + let (top, bottom) = (span(y0), span(y1)); + for tx in tx0..tx1 { + let (x0, x1) = ((tx * TILE_W) as f32 + 0.5, ((tx + 1) * TILE_W).min(w) as f32 - 0.5); + if top.0 <= x0 && top.1 >= x1 && bottom.0 <= x0 && bottom.1 >= x1 && !quiet[(ty * cols + tx) as usize] { + first[(ty * cols + tx) as usize] = n as u32 + 1; + } + } + } + } + } + let mut count = vec![0u32; tiles + 1]; + let mut culled = 0; + let each = |n: usize, f: &mut dyn FnMut(usize)| { + let b = bounds[n]; + if b[2] <= b[0] || b[3] <= b[1] { return; } + for ty in b[1] as u32 / TILE_H..(b[3] as u32).div_ceil(TILE_H) { + for tx in b[0] as u32 / TILE_W..(b[2] as u32).div_ceil(TILE_W) { + f((ty * cols + tx) as usize); + } + } + }; + for n in 0..scene.instances.len() { + each(n, &mut |t| if n as u32 + 1 >= first[t] { count[t + 1] += 1 } else { culled += 1 }); + } + for t in 0..tiles { count[t + 1] += count[t]; } + let mut index = vec![0u32; count[tiles] as usize]; + let mut at = count.clone(); + for n in 0..scene.instances.len() { + each(n, &mut |t| if n as u32 + 1 >= first[t] { + index[at[t] as usize] = n as u32; + at[t] += 1; + }); + } + Bins { cols, rows, start: count, index, bounds, covered: first.iter().map(|&f| f > 0).collect(), culled, layers, scope, within, blurs, quiet } + } + + pub(super) fn tile(&self, t: usize) -> &[u32] { + &self.index[self.start[t] as usize..self.start[t + 1] as usize] + } + + pub(super) fn tile_count(&self) -> usize { (self.cols * self.rows) as usize } + + pub(super) fn len(&self) -> usize { self.index.len() } +} + +/// The pixels whose centres lie in the quad the vertex shader draws for `i` (`base_vs`), within +/// the reach of its clip and the target. Empty for what rasterises nothing. +#[inline] +pub(in crate::render) fn pixel_bounds(i: &Instance, w: i32, h: i32) -> [i32; 4] { + i.pixel_bounds(w, h) +} + +/// A rounded box and how far inside its edge a pixel centre must be to be whole: the region of +/// pixels a box kind paints in one colour. +#[derive(Clone, Copy, PartialEq)] +pub(super) struct Solid { + pub edges: [f32; 4], + pub radii: [f32; 4], + pub inset: f32, +} + +impl Solid { + /// How far in from its top and bottom edges the span stops narrowing for the corners. + pub(super) fn bands(&self) -> (f32, f32) { + let [x0, y0, x1, y1] = self.edges; + let m = ((x1 - x0) * 0.5).min((y1 - y0) * 0.5); + let reach = |r: f32| if r < 0.0 { corner_extent(-(-r).min(m)) } else { r.min(m) }; + let r = self.radii.map(reach); + (r[0].max(r[1]).max(self.inset), r[3].max(r[2]).max(self.inset)) + } + + /// The pixel centres `[a, b]` on the row with centre `y` that lie at least `inset` inside the + /// box (its signed distance at most `-inset`), conservatively near rounded corners. + pub(super) fn span(&self, y: f32) -> (f32, f32) { + let [x0, y0, x1, y1] = self.edges; + let (top, bottom) = (y - y0, y1 - y); + let t = self.inset; + if top < t || bottom < t { return EMPTY; } + let m = ((x1 - x0) * 0.5).min((y1 - y0) * 0.5); + let reach = |r: f32| if r < 0.0 { corner_extent(-(-r).min(m)) } else { r.min(m) }; + let upper = y < (y0 + y1) * 0.5; + let (rl, rr) = if upper { (reach(self.radii[0]), reach(self.radii[1])) } else { (reach(self.radii[3]), reach(self.radii[2])) }; + let near = top.min(bottom); + let a = x0 + if near < rl { rl.max(t) } else { t }; + let b = x1 - if near < rr { rr.max(t) } else { t }; + (a, b) + } +} + +pub(super) const EMPTY: (f32, f32) = (f32::INFINITY, f32::NEG_INFINITY); + +pub(super) fn intersect(a: (f32, f32), b: (f32, f32)) -> (f32, f32) { + (a.0.max(b.0), a.1.min(b.1)) +} + +/// Where on row `y` the clip is whole (`clip_alpha` is 1). +pub(super) fn clip_span(clip: &Clip, y: f32) -> (f32, f32) { + let c = clip.rect; + let inset = clip.inset(); + if y < c[1] + inset[1] || y > c[3] - inset[3] { return EMPTY; } + let edges = (c[0] + inset[0], c[2] - inset[2]); + match clip.radii { + None => edges, + Some(radii) => intersect(edges, Solid { edges: c, radii, inset: 0.5 }.span(y)), + } +} + +/// The region a box kind paints in one colour, if it's opaque there: the interior of a +/// `KIND_RECT` (inside its border, when it has one) whose colour there has alpha 1. +pub(super) fn opaque_box(i: &Instance) -> Option<Solid> { + if i.kind() != Some(Kind::Rect) || i.fill[3] < 1.0 { return None; } + interior(i) +} + +/// Where a `KIND_RECT` or `KIND_GRADIENT` paints its fill whole, over nothing of its border. +pub(super) fn interior(i: &Instance) -> Option<Solid> { + let edges = [i.rect[0], i.rect[1], i.rect[0] + i.rect[2], i.rect[1] + i.rect[3]]; + let soft = i.params[2].max(shader_consts::SOFT_MIN); + let bw = i.params[0]; + if bw <= 0.0 { return Some(Solid { edges, radii: i.radii, inset: soft }); } + if i.kind() == Some(Kind::Rect) && has_sides(i) { + // The per-side inner box is inside the outer one, which is whole wherever it is. + let half = [i.rect[2] * 0.5, i.rect[3] * 0.5]; + let (c, ih, radii) = sides_inner(i, [i.rect[0] + half[0], i.rect[1] + half[1]], half); + return Some(Solid { edges: [c[0] - ih[0], c[1] - ih[1], c[0] + ih[0], c[1] + ih[1]], radii, inset: soft }); + } + Some(Solid { edges, radii: i.radii, inset: soft + bw }) +} + +/// Whether every pixel centre of `r` is inside `solid` (if given) where `clip` is whole: true at +/// its first and last rows means true between (both regions are convex). +pub(super) fn covers(solid: Option<&Solid>, clip: &Clip, r: [f32; 4]) -> bool { + let (x0, x1) = (r[0] + 0.5, r[2] - 0.5); + [r[1] + 0.5, r[3] - 0.5].iter().all(|&y| { + let span = solid.map_or(clip_span(clip, y), |s| intersect(s.span(y), clip_span(clip, y))); + span.0 <= x0 && span.1 >= x1 + }) +} diff --git a/app/vendor/rune/crates/rune/src/render/cpu_boot/blend.rs b/app/vendor/rune/crates/rune/src/render/cpu_boot/blend.rs new file mode 100644 index 0000000..acf7374 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/render/cpu_boot/blend.rs @@ -0,0 +1,185 @@ +//! The GPU's premultiplied source-over on a `Bgra8Unorm` target, byte for byte: the fragment's +//! colour converted to the target's 8-bit steps first (round to nearest, ties to even), then +//! `src + dst × (1 − src.a)`, rounded the same way. On x86-64 one pixel's four channels go through +//! SSE2 at once; elsewhere the same operations run a channel at a time, in the same order, so +//! both produce the same bits. + +#![allow(unsafe_code)] + +/// Adding 1.5 × 2²³ to a float in [0, 255] rounds it to an integer, ties to even, in the default +/// rounding mode, and leaves that integer in the low mantissa bits. +const MAGIC: f32 = 12_582_912.0; + +/// A float in 0..=255 to the byte the GPU stores. +#[inline] +pub(super) fn q(v: f32) -> u8 { + (v.clamp(0.0, 255.0) + MAGIC).to_bits() as u8 +} + +/// `v` (0..=1) in the target's 8-bit steps, as a float in 0..=255. +#[inline] +fn steps(v: f32) -> f32 { + ((v * 255.0).clamp(0.0, 255.0) + MAGIC) - MAGIC +} + +/// Premultiplied RGBA `c` (0..=1) as the blender takes it for a B, G, R, A pixel: in 8-bit steps, +/// with the destination's weight `1 − a`. +#[derive(Clone, Copy)] +pub(super) struct Src { + bgra: [f32; 4], + keep: f32, +} + +impl Src { + #[inline] + pub(super) fn new(c: [f32; 4]) -> Src { + let bgra = [steps(c[2]), steps(c[1]), steps(c[0]), steps(c[3])]; + Src { bgra, keep: 1.0 - bgra[3] / 255.0 } + } + + /// The pixel it writes over anything when it's opaque. + #[inline] + pub(super) fn opaque(&self) -> Option<[u8; 4]> { + (self.keep == 0.0).then(|| self.bgra.map(|v| v as u8)) + } +} + +/// Blends `s` over B, G, R, A pixel `p`. +#[inline] +pub(super) fn over(p: &mut [u8], s: &Src) { + #[cfg(target_arch = "x86_64")] + // SAFETY: SSE2 is part of x86-64; `p` holds at least four bytes (checked). + unsafe { + use std::arch::x86_64::*; + assert!(p.len() >= 4); + let zero = _mm_setzero_si128(); + let px = _mm_cvtsi32_si128(i32::from_ne_bytes([p[0], p[1], p[2], p[3]])); + let d = _mm_cvtepi32_ps(_mm_unpacklo_epi16(_mm_unpacklo_epi8(px, zero), zero)); + let src = _mm_loadu_ps(s.bgra.as_ptr()); + let r = _mm_add_ps(src, _mm_mul_ps(d, _mm_set1_ps(s.keep))); + let r = _mm_add_ps(_mm_min_ps(_mm_max_ps(r, _mm_setzero_ps()), _mm_set1_ps(255.0)), _mm_set1_ps(MAGIC)); + let bytes = _mm_and_si128(_mm_castps_si128(r), _mm_set1_epi32(0xff)); + let packed = _mm_packus_epi16(_mm_packs_epi32(bytes, zero), zero); + p[..4].copy_from_slice(&_mm_cvtsi128_si32(packed).to_ne_bytes()); + } + #[cfg(not(target_arch = "x86_64"))] + for ch in 0..4 { + p[ch] = q(s.bgra[ch] + p[ch] as f32 * s.keep); + } +} + +/// Blends premultiplied RGBA `c` (0..=1) over B, G, R, A pixel `p`: `over(p, &Src::new(c))` in +/// one go. +#[inline] +pub(super) fn over_rgba(p: &mut [u8], c: [f32; 4]) { + #[cfg(target_arch = "x86_64")] + // SAFETY: SSE2 is part of x86-64; `p` holds at least four bytes (checked). + unsafe { + use std::arch::x86_64::*; + assert!(p.len() >= 4); + let zero = _mm_setzero_si128(); + let (lo, hi, magic) = (_mm_setzero_ps(), _mm_set1_ps(255.0), _mm_set1_ps(MAGIC)); + // R, G, B, A to B, G, R, A, then `steps`: × 255, clamped, rounded. + let c = _mm_loadu_ps(c.as_ptr()); + let c = _mm_shuffle_ps::<0b11_00_01_10>(c, c); + let s = _mm_sub_ps(_mm_add_ps(_mm_min_ps(_mm_max_ps(_mm_mul_ps(c, hi), lo), hi), magic), magic); + let a = _mm_shuffle_ps::<0b11_11_11_11>(s, s); + let keep = _mm_sub_ps(_mm_set1_ps(1.0), _mm_div_ps(a, hi)); + let px = _mm_cvtsi32_si128(i32::from_ne_bytes([p[0], p[1], p[2], p[3]])); + let d = _mm_cvtepi32_ps(_mm_unpacklo_epi16(_mm_unpacklo_epi8(px, zero), zero)); + let r = _mm_add_ps(_mm_min_ps(_mm_max_ps(_mm_add_ps(s, _mm_mul_ps(d, keep)), lo), hi), magic); + let bytes = _mm_and_si128(_mm_castps_si128(r), _mm_set1_epi32(0xff)); + let packed = _mm_packus_epi16(_mm_packs_epi32(bytes, zero), zero); + p[..4].copy_from_slice(&_mm_cvtsi128_si32(packed).to_ne_bytes()); + } + #[cfg(not(target_arch = "x86_64"))] + over(p, &Src::new(c)); +} + +/// The B, G, R, A bytes an opaque premultiplied RGBA `c` (`c[3] == 1`) writes over any pixel. +#[inline] +pub(super) fn opaque(c: [f32; 4]) -> [u8; 4] { + [q(c[2] * 255.0), q(c[1] * 255.0), q(c[0] * 255.0), q(c[3] * 255.0)] +} + +/// A layer's row composited whole (inside its clip, no hole) over B, G, R, A pixels: each texel +/// by `opacity`, then `over_rgba`. An opaque texel at opacity 1 comes out as `opaque`, a clear +/// one leaves the pixel, so neither needs its own case. +#[inline] +pub(super) fn composite_row(row: &mut [u8], src: &[[f32; 4]]) { + composite_row_by(row, src, 1.0) +} + +/// `composite_row` for a layer of any opacity. On x86-64 four pixels go at once, a channel to a +/// register, through `over_rgba`'s operations in its order, so the bytes are the same. +#[inline] +pub(super) fn composite_row_by(row: &mut [u8], src: &[[f32; 4]], opacity: f32) { + let n = (row.len() / 4).min(src.len()); + #[cfg(target_arch = "x86_64")] + let done = { + let quads = n / 4; + // SAFETY: SSE2 is part of x86-64; `quads * 4` pixels and texels are in bounds. + unsafe { over4(&mut row[..quads * 16], &src[..quads * 4], opacity) }; + quads * 4 + }; + #[cfg(not(target_arch = "x86_64"))] + let done = 0; + for (p, s) in row[done * 4..n * 4].chunks_exact_mut(4).zip(&src[done..n]) { + over_rgba(p, s.map(|v| v * opacity)); + } +} + +/// Four texels at a time over four B, G, R, A pixels: `over_rgba` on each, by lanes. +#[cfg(target_arch = "x86_64")] +unsafe fn over4(row: &mut [u8], src: &[[f32; 4]], opacity: f32) { + use std::arch::x86_64::*; + // SAFETY: SSE2 is baseline on x86-64; every load and store is inside `row` (16 bytes a step) + // and `src` (four texels a step). + unsafe { + let (lo, hi, magic, one) = (_mm_setzero_ps(), _mm_set1_ps(255.0), _mm_set1_ps(MAGIC), _mm_set1_ps(1.0)); + let k = _mm_set1_ps(opacity); + let byte = _mm_set1_epi32(0xff); + for (p, s) in row.chunks_exact_mut(16).zip(src.chunks_exact(4)) { + let mut t0 = _mm_mul_ps(_mm_loadu_ps(s[0].as_ptr()), k); + let mut t1 = _mm_mul_ps(_mm_loadu_ps(s[1].as_ptr()), k); + let mut t2 = _mm_mul_ps(_mm_loadu_ps(s[2].as_ptr()), k); + let mut t3 = _mm_mul_ps(_mm_loadu_ps(s[3].as_ptr()), k); + _MM_TRANSPOSE4_PS(&mut t0, &mut t1, &mut t2, &mut t3); + // t0..t3: R, G, B, A of the four texels. `steps`: × 255, clamped, rounded. + let steps = |v: __m128| _mm_sub_ps(_mm_add_ps(_mm_min_ps(_mm_max_ps(_mm_mul_ps(v, hi), lo), hi), magic), magic); + let (r, g, b, a) = (steps(t0), steps(t1), steps(t2), steps(t3)); + let keep = _mm_sub_ps(one, _mm_div_ps(a, hi)); + let px = _mm_loadu_si128(p.as_ptr() as *const __m128i); + let ch = |shift: i32| _mm_cvtepi32_ps(_mm_and_si128(_mm_srl_epi32(px, _mm_cvtsi32_si128(shift)), byte)); + let out = |s: __m128, d: __m128| _mm_and_si128(_mm_castps_si128(_mm_add_ps(_mm_min_ps(_mm_max_ps(_mm_add_ps(s, _mm_mul_ps(d, keep)), lo), hi), magic)), byte); + let (ob, og, or, oa) = (out(b, ch(0)), out(g, ch(8)), out(r, ch(16)), out(a, ch(24))); + let packed = _mm_or_si128(_mm_or_si128(ob, _mm_slli_epi32::<8>(og)), _mm_or_si128(_mm_slli_epi32::<16>(or), _mm_slli_epi32::<24>(oa))); + _mm_storeu_si128(p.as_mut_ptr() as *mut __m128i, packed); + } + } +} +/// Blends `s` over every pixel of `row`. +#[inline] +pub(super) fn over_row(row: &mut [u8], s: &Src) { + if let Some(px) = s.opaque() { return fill_row(row, px); } + if s.bgra == [0.0; 4] { return; } + for p in row.chunks_exact_mut(4) { over(p, s); } +} + +/// The dual-source blend of subpixel text: each colour channel kept by its own `1 − k`, where +/// `k` (0..=1, red to blue) is the second output, in 8-bit steps like the first. +#[inline] +pub(super) fn over_lcd(p: &mut [u8], c: [f32; 4], k: [f32; 3]) { + let s = [steps(c[2]), steps(c[1]), steps(c[0]), steps(c[3])]; + let keep = [1.0 - steps(k[2]) / 255.0, 1.0 - steps(k[1]) / 255.0, 1.0 - steps(k[0]) / 255.0, 1.0 - s[3] / 255.0]; + for ch in 0..4 { p[ch] = q(s[ch] + p[ch] as f32 * keep[ch]); } +} + +/// Writes pixel `px` over every pixel of `row`, as words when the row is word aligned. +#[inline] +pub(super) fn fill_row(row: &mut [u8], px: [u8; 4]) { + match bytemuck::try_cast_slice_mut::<u8, u32>(row) { + Ok(words) => words.fill(u32::from_ne_bytes(px)), + Err(_) => for p in row.chunks_exact_mut(4) { p.copy_from_slice(&px) }, + } +} diff --git a/app/vendor/rune/crates/rune/src/render/cpu_boot/damage.rs b/app/vendor/rune/crates/rune/src/render/cpu_boot/damage.rs new file mode 100644 index 0000000..192654e --- /dev/null +++ b/app/vendor/rune/crates/rune/src/render/cpu_boot/damage.rs @@ -0,0 +1,171 @@ +//! Damage by tile hash: a tile whose painting inputs hash the same as last frame's holds the +//! same pixels, since the window's buffer keeps them between frames. A tile's inputs are what +//! it draws (`Bins::tile`, culled to what can show): each instance's 128 bytes in order, the +//! layer plans its scope records stand for, whether it starts cleared or covered and the clear +//! colour, the atlas generation for glyphs and the image texels images sample. + +use super::Scene; +use super::bin::{Bins, Solid, TILE_H, TILE_W, covers, interior}; +use super::shade::Clip; +use crate::render::{INSTANCE_WORDS, Kind}; + +/// FxHash's step, word by word. +#[inline] +fn mix(h: u64, w: u64) -> u64 { (h.rotate_left(5) ^ w).wrapping_mul(0x517c_c1b7_2722_0a95) } + +/// Each tile's hash into `out`, from each instance's hash, made once into `each`. +pub(super) fn hashes(scene: &Scene<'_>, bins: &Bins, each: &mut Vec<u64>, out: &mut Vec<u64>) { + each.clear(); + each.extend((0..scene.instances.len()).map(|n| instance(scene, bins, n))); + let flat: Vec<(u32, Flat)> = (0..scene.instances.len()).filter_map(|n| flat(&scene.instances[n]).map(|f| (n as u32, f))).collect(); + out.clear(); + out.extend((0..bins.tile_count()).map(|t| tile(scene, bins, each, t, |n| flat.binary_search_by_key(&n, |f| f.0).ok().map(|k| &flat[k].1)))); +} + +/// Tile `t`'s hash again, after instances in it changed (`each` already holds theirs). +pub(super) fn rehash(scene: &Scene<'_>, bins: &Bins, each: &[u64], t: usize) -> u64 { + let flats: Vec<(u32, Flat)> = bins.tile(t).iter().filter_map(|&n| flat(&scene.instances[n as usize]).map(|f| (n, f))).collect(); + tile(scene, bins, each, t, |n| flats.iter().find(|f| f.0 == n).map(|f| &f.1)) +} + +/// One instance's inputs: its bytes, and what they stand for elsewhere (a layer's plan, the +/// atlas's evictions for a glyph, an image's texels). +pub(super) fn instance(scene: &Scene<'_>, bins: &Bins, n: usize) -> u64 { + let i = &scene.instances[n]; + let words: &[u32; INSTANCE_WORDS] = bytemuck::cast_ref(i); + let mut h = 0; + for w in words.chunks_exact(2) { h = mix(h, u64::from(w[0]) | u64::from(w[1]) << 32); } + let b = bins.bounds[n]; + h = mix(mix(h, (b[0] as u32 as u64) | (b[1] as u32 as u64) << 32), (b[2] as u32 as u64) | (b[3] as u32 as u64) << 32); + match i.kind() { + Some(Kind::Layer | Kind::LayerEnd) => { + if let Some(&p) = bins.scope.get(&(n as u32)) { + let l = &bins.layers[p as usize]; + let b = l.bounds; + h = mix(mix(h, (b[0] as u32 as u64) | (b[1] as u32 as u64) << 32), (b[2] as u32 as u64) | (b[3] as u32 as u64) << 32); + h = mix(h, l.show as u64); + } + } + Some(Kind::Glyph) => { h = mix(h, scene.atlas_resets); } + Some(Kind::Image) => { h = image(scene, i, h); } + Some( + Kind::Rect | Kind::Shadow | Kind::Inset | Kind::Gradient | Kind::Segment + | Kind::Triangle | Kind::Dashed | Kind::Radial | Kind::Effect | Kind::BackdropBlur, + ) | None => {} + } + h +} + +/// A box whose one colour fills a whole tile draws only that colour there, wherever its edges +/// are: a tile it fills takes its colour, not its bytes, so a panel that grows or a window card +/// that resizes leaves the tiles inside it clean. Boxes big enough to fill a tile; each with the +/// rect its corners and its clip's edges can't reach (a tile inside that is filled without +/// asking). +pub(super) struct Flat { + solid: Solid, + clip: Clip, + token: u64, + sure: [f32; 4], +} + +fn flat(i: &crate::render::Instance) -> Option<Flat> { + if i.kind() != Some(Kind::Rect) || i.rect[2] < TILE_W as f32 || i.rect[3] < TILE_H as f32 { return None; } + let solid = interior(i)?; + let clip = Clip::of(i); + let fill: &[u32; 4] = bytemuck::cast_ref(&i.fill); + let m = solid.radii.iter().fold(0.0f32, |a, r| a.max(r.abs())) + solid.inset + 1.0; + let e = solid.edges; + let inset = clip.inset(); + let cm = clip.radii.map_or(0.0, |r| r.iter().fold(0.0f32, |a, v| a.max(v.abs()))) + 1.0; + let c = clip.rect; + let sure = [(e[0] + m).max(c[0] + inset[0] + cm), (e[1] + m).max(c[1] + inset[1] + cm), (e[2] - m).min(c[2] - inset[2] - cm), (e[3] - m).min(c[3] - inset[3] - cm)]; + let token = mix(mix(0x5a5a, u64::from(fill[0]) | u64::from(fill[1]) << 32), u64::from(fill[2]) | u64::from(fill[3]) << 32); + Some(Flat { solid, clip, token, sure }) +} + +/// Tile `t`'s hash: how it starts, then each instance it draws, by its colour where it fills the +/// tile (`flat_of`), else by its inputs. +fn tile<'f>(scene: &Scene<'_>, bins: &Bins, each: &[u64], t: usize, flat_of: impl Fn(u32) -> Option<&'f Flat>) -> u64 { + let clear = scene.clear.map(f32::to_bits); + let base = mix(mix(0, u64::from(clear[0]) | u64::from(clear[1]) << 32), u64::from(clear[2]) | u64::from(clear[3]) << 32); + let (w, h) = scene.size; + let mut hash = mix(mix(base, u64::from(bins.covered[t])), u64::from(bins.quiet[t])); + let (tx, ty) = (t as u32 % bins.cols, t as u32 / bins.cols); + let r = [(tx * TILE_W) as f32, (ty * TILE_H) as f32, ((tx + 1) * TILE_W).min(w) as f32, ((ty + 1) * TILE_H).min(h) as f32]; + for &n in bins.tile(t) { + let token = match flat_of(n) { + Some(f) if bounds_cover(bins.bounds[n as usize], r) && (inside(r, f.sure) || covers(Some(&f.solid), &f.clip, r)) => f.token, + _ => each[n as usize], + }; + hash = mix(hash, token); + } + hash +} + +fn bounds_cover(b: [i32; 4], r: [f32; 4]) -> bool { + (b[0] as f32) <= r[0] && (b[1] as f32) <= r[1] && (b[2] as f32) >= r[2] && (b[3] as f32) >= r[3] +} + +fn inside(r: [f32; 4], o: [f32; 4]) -> bool { r[0] >= o[0] && r[1] >= o[1] && r[2] <= o[2] && r[3] <= o[3] } +/// The texels an image instance samples, hashed: an animated image writes its next frame into +/// the same place. +fn image(scene: &Scene<'_>, i: &crate::render::Instance, mut h: u64) -> u64 { + let Some(page) = scene.images.get(i.params[0] as usize) else { return h }; + let w = page.width as usize; + let (x0, y0) = (i.uv[0].max(0.0) as usize, i.uv[1].max(0.0) as usize); + let (x1, y1) = (x0 + i.uv[2].max(0.0) as usize, y0 + i.uv[3].max(0.0) as usize); + for y in y0..y1 { + let Some(row) = page.data.get((y * w + x0) * 4..(y * w + x1) * 4) else { break }; + for c in row.chunks(8) { + let mut b = [0u8; 8]; + b[..c.len()].copy_from_slice(c); + h = mix(h, u64::from_le_bytes(b)); + } + } + h +} + +/// Adds `r` to `rects`, merging the closest pair while there are more than `max`. +pub(super) fn add(rects: &mut Vec<[u32; 4]>, r: [u32; 4], max: usize) { + rects.push(r); + merge(rects, max); +} + +/// Dirty tiles as at most `max` rectangles of pixels `[x0, y0, x1, y1)`: runs along each tile row, +/// stacked where consecutive rows have the same run, then merged into their bounding boxes +/// pairwise (the closest first) until few enough. +pub(super) fn rects(dirty: &[u32], cols: u32, size: (u32, u32), max: usize) -> Vec<[u32; 4]> { + let mut runs: Vec<[u32; 4]> = Vec::new(); + let mut k = 0; + while k < dirty.len() { + let (t0, row) = (dirty[k], dirty[k] / cols); + let mut t1 = t0; + while k + 1 < dirty.len() && dirty[k + 1] == t1 + 1 && dirty[k + 1] / cols == row { k += 1; t1 += 1; } + k += 1; + let r = [(t0 % cols) * TILE_W, row * TILE_H, ((t1 % cols + 1) * TILE_W).min(size.0), ((row + 1) * TILE_H).min(size.1)]; + match runs.iter_mut().find(|p| p[0] == r[0] && p[2] == r[2] && p[3] == r[1]) { + Some(p) => p[3] = r[3], + None => runs.push(r), + } + } + merge(&mut runs, max); + runs +} + +/// Merges rectangles into their bounding boxes pairwise, the pair that wastes least first, until +/// at most `max` are left. +fn merge(runs: &mut Vec<[u32; 4]>, max: usize) { + while runs.len() > max { + let area = |r: &[u32; 4]| u64::from(r[2] - r[0]) * u64::from(r[3] - r[1]); + let union = |a: &[u32; 4], b: &[u32; 4]| [a[0].min(b[0]), a[1].min(b[1]), a[2].max(b[2]), a[3].max(b[3])]; + let mut best = (0, 1, u64::MAX); + for a in 0..runs.len() { + for b in a + 1..runs.len() { + let waste = area(&union(&runs[a], &runs[b])).saturating_sub(area(&runs[a]) + area(&runs[b])); + if waste < best.2 { best = (a, b, waste); } + } + } + let b = runs.swap_remove(best.1); + runs[best.0] = union(&runs[best.0], &b); + } +} diff --git a/app/vendor/rune/crates/rune/src/render/cpu_boot/drift.rs b/app/vendor/rune/crates/rune/src/render/cpu_boot/drift.rs new file mode 100644 index 0000000..b0afe80 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/render/cpu_boot/drift.rs @@ -0,0 +1,71 @@ +//! The hand-over's drift: how many pixels the GPU's first frame changed from the CPU frame it +//! replaced. A window that took over from `paint` reads its first GPU frame back and calls +//! [`drift`] when [`drift_wanted`] (`RUNE_CPU_BOOT_DRIFT=1`), so the day the two renderers start +//! to disagree shows as a count in the log and in [`last_drift`], not as a flicker nobody traces. + +use std::sync::Mutex; + +/// What the GPU's frame changed: pixels compared, pixels with any channel different, pixels with +/// a channel more than 2 apart, and the largest channel difference. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct Drift { + pub pixels: u64, + pub differ: u64, + pub over_two: u64, + pub max: u8, +} + +/// A frame's pixels: `width × height`, `stride` bytes a row, four bytes a pixel in memory order +/// B, G, R, A (the swap chain's and `paint`'s) or R, G, B, A (an offscreen readback's). +#[derive(Clone, Copy)] +pub struct Pixels<'a> { + data: &'a [u8], + width: u32, + height: u32, + stride: usize, + rgba: bool, +} + +impl<'a> Pixels<'a> { + pub fn bgra(data: &'a [u8], width: u32, height: u32, stride: usize) -> Self { Pixels { data, width, height, stride, rgba: false } } + + pub fn rgba(data: &'a [u8], width: u32, height: u32, stride: usize) -> Self { Pixels { data, width, height, stride, rgba: true } } + + /// Pixel `(x, y)` as B, G, R, A. + fn bgra_at(&self, x: u32, y: u32) -> [u8; 4] { + let at = y as usize * self.stride + x as usize * 4; + let p = &self.data[at..at + 4]; + if self.rgba { [p[2], p[1], p[0], p[3]] } else { [p[0], p[1], p[2], p[3]] } + } +} + +static LAST: Mutex<Option<Drift>> = Mutex::new(None); + +/// Whether the hand-over should measure its drift (`RUNE_CPU_BOOT_DRIFT` set and not `0`). +pub fn drift_wanted() -> bool { + std::env::var_os("RUNE_CPU_BOOT_DRIFT").is_some_and(|v| v != "0") +} + +/// Compares the CPU frame with the GPU frame that replaced it over their common area, keeps the +/// result for [`last_drift`] and logs it. +pub fn drift(cpu: Pixels<'_>, gpu: Pixels<'_>) -> Drift { + let (w, h) = (cpu.width.min(gpu.width), cpu.height.min(gpu.height)); + let mut d = Drift { pixels: u64::from(w) * u64::from(h), ..Drift::default() }; + for y in 0..h { + for x in 0..w { + let (a, b) = (cpu.bgra_at(x, y), gpu.bgra_at(x, y)); + let m = (0..4).map(|c| a[c].abs_diff(b[c])).max().unwrap_or(0); + if m > 0 { d.differ += 1; } + if m > 2 { d.over_two += 1; } + d.max = d.max.max(m); + } + } + *LAST.lock().unwrap_or_else(|e| e.into_inner()) = Some(d); + eprintln!("rune: cpu boot drift: {} of {} px differ from the GPU's first frame, {} by more than 2 (max {})", d.differ, d.pixels, d.over_two, d.max); + d +} + +/// The drift the last hand-over measured, if one did. +pub fn last_drift() -> Option<Drift> { + *LAST.lock().unwrap_or_else(|e| e.into_inner()) +} diff --git a/app/vendor/rune/crates/rune/src/render/cpu_boot/fill.rs b/app/vendor/rune/crates/rune/src/render/cpu_boot/fill.rs new file mode 100644 index 0000000..1e0abc1 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/render/cpu_boot/fill.rs @@ -0,0 +1,87 @@ +//! Windfoil's atlas masks filled on the CPU, across threads, before any renderer exists: the +//! fills the text system queued for the GPU (`text::atlas_fill`), each mask the bytes the fill's +//! shader writes for it (`outline.wgsl`'s `outline_glyph`, through `text::outline::fill_shared`, +//! its CPU form). +//! +//! A filled mask becomes one the CPU drew (`Residency::Uploaded`) and its rows are marked for +//! upload: a renderer that arrives later uploads these texels and samples them, never filling +//! them again, so text at the hand-over is the same texels on both sides. + +use std::sync::Mutex; +use std::sync::atomic::{AtomicUsize, Ordering}; + +use crate::text::{ATLAS_SIZE, Atlas, QueuedFill, outline}; + +/// Tells the text system its masks will be filled from outlines, as a Windfoil renderer's +/// `attach_text` does, so the first frame's glyphs queue fills for [`fill_masks`] instead of +/// filling them one by one on the thread that lays the frame out. +pub fn attach_text(atlas: &mut Atlas) { + atlas.outlines.set_support(outline::Support::Drawn); +} + +/// How a `fill_masks` went. +#[derive(Clone, Debug, Default)] +pub struct FillReport { + pub threads: usize, + pub masks: usize, + pub texels: u64, + /// Computing every texel's coverage, all threads, wall clock. + pub cover_ns: u64, + /// Copying the masks into their pages. + pub copy_ns: u64, +} + +/// Fills every mask the text system queued for the GPU (`attach_text`), on `threads` threads. +pub fn fill_masks(atlas: &mut Atlas, threads: usize) -> FillReport { + fill_with(atlas, &|n| super::raster::Spawn(n.min(threads.max(1)))) +} + +/// Texels a thread fills before another is worth waking: about 50 µs of work (a parked pool +/// thread wakes in a few µs; one made for the job costs tens). +pub(super) const TEXELS_PER_THREAD: u64 = 1_500; + +/// `fill_masks` on the threads `exec` gives for this many. +pub(super) fn fill_with<E: super::raster::Exec>(atlas: &mut Atlas, exec: &dyn Fn(usize) -> E) -> FillReport { + let started = crate::time::now(); + let fills: Vec<(usize, QueuedFill)> = atlas.take_cpu_fills().into_iter().flat_map(|(page, f)| f.into_iter().map(move |q| (page, q))).collect(); + let queued: Vec<QueuedFill> = fills.iter().map(|f| f.1).collect(); + // Masks of one glyph at several x phases share their rows (`outline::share_rows`): a group is + // one piece of work. The biggest first, so the last ones a thread picks up are small. + let mut groups = outline::share_rows(&queued); + let size = |g: &Vec<u32>| g.iter().map(|&i| u64::from(queued[i as usize].rect[2] * queued[i as usize].rect[3])).sum::<u64>(); + groups.sort_by_key(|g| std::cmp::Reverse(size(g))); + let texels: u64 = groups.iter().map(size).sum(); + let next = AtomicUsize::new(0); + let done: Vec<Mutex<Vec<Vec<u8>>>> = groups.iter().map(|_| Mutex::new(Vec::new())).collect(); + let store = &atlas.outlines; + let worker = || loop { + let k = next.fetch_add(1, Ordering::Relaxed); + let Some(group) = groups.get(k) else { break }; + let mut masks: Vec<Vec<u8>> = group.iter().map(|&i| Vec::with_capacity((queued[i as usize].rect[2] * queued[i as usize].rect[3]) as usize)).collect(); + outline::fill_shared::<outline::F4>(store, &queued, group, &mut masks, None); + *done[k].lock().unwrap_or_else(|e| e.into_inner()) = masks; + }; + let exec = exec(texels.div_ceil(TEXELS_PER_THREAD).max(1) as usize); + let threads = exec.threads(); + if !fills.is_empty() { exec.run(&worker); } + let covered = crate::time::now(); + for (group, masks) in groups.iter().zip(done) { + for (&i, mask) in group.iter().zip(masks.into_inner().unwrap_or_else(|e| e.into_inner())) { + let (page, q) = &fills[i as usize]; + let (data, dirty) = if *page == 0 { (&mut atlas.data, &mut atlas.dirty) } else { + let Some(p) = atlas.pages.get_mut(page - 1) else { continue }; + (&mut p.data, &mut p.dirty) + }; + let [x, y, w, h] = q.rect; + for row in 0..h { + let at = ((y + row) * ATLAS_SIZE + x) as usize; + data[at..at + w as usize].copy_from_slice(&mask[(row * w) as usize..((row + 1) * w) as usize]); + } + let rows = (y - 1, y + h + 1); + let d = dirty.get_or_insert(rows); + *d = (d.0.min(rows.0), d.1.max(rows.1)); + } + } + let end = crate::time::now(); + FillReport { threads, masks: fills.len(), texels, cover_ns: super::ns(covered - started), copy_ns: super::ns(end - covered) } +} \ No newline at end of file diff --git a/app/vendor/rune/crates/rune/src/render/cpu_boot/painter.rs b/app/vendor/rune/crates/rune/src/render/cpu_boot/painter.rs new file mode 100644 index 0000000..4e329aa --- /dev/null +++ b/app/vendor/rune/crates/rune/src/render/cpu_boot/painter.rs @@ -0,0 +1,442 @@ +//! The live CPU renderer: paints each frame into the same window buffer, repainting only the +//! tiles whose inputs changed since the frame before (`damage.rs`), on a pool of threads kept +//! between frames, and says which rectangles of the buffer changed so the window copies only +//! those to the screen. + +use crate::time::Instant; + +use super::bin::{Bins, TILE_H, TILE_W}; +use crate::render::{INSTANCE_WORDS, Instance, Kind, word}; +use super::pool::Pool; +use super::{NeedsGpu, Report, Scene, Target, damage, raster, scroll}; + +/// Rectangles a frame's damage is merged into at most. +const MAX_RECTS: usize = 8; +/// Dirty tiles per extra thread: a handful of tiles paints faster on the calling thread than it +/// takes to wake another. +const TILES_PER_THREAD: usize = 24; +/// Tiles a frame must change before it's checked for a scroll. +const MIN_SCROLL_TILES: usize = 16; + +/// Paints frames into one retained buffer. +pub struct CpuPainter { + pool: Pool, + /// Each tile's inputs last frame, for a buffer of `size`; empty when the buffer's pixels + /// aren't known (`forget`). + hashes: Vec<u64>, + next: Vec<u64>, + each: Vec<u64>, + size: (u32, u32), + /// The buffer's row pitch last frame, in bytes. + stride: usize, + dirty: Vec<u32>, + /// The last frame's instances and bins, for telling a scroll (`scroll.rs`) and for a frame + /// that only recolours (`recoloured`). + prev: Option<scroll::Prev>, + /// The atlas's evictions last frame (`Atlas::resets`). + resets: u64, + /// The last frame's scene-wide switches (`Scene::flags`), from a frame the CPU could draw. + flags: Option<super::Flags>, + /// Scratch for `recoloured`: the instances that changed, and which tiles they mark. + changed: Vec<u32>, + marked: Vec<bool>, +} + +/// Instances a frame may recolour and still take `recoloured`. +const RECOLOURED_MAX: usize = 256; + +/// What a frame painted. +#[derive(Clone, Debug, Default)] +pub struct Painted { + pub report: Report, + /// Tiles repainted, of all of them. + pub dirty_tiles: usize, + pub tiles: usize, + /// The buffer's changed pixels, `[x0, y0, x1, y1)`, at most eight rectangles. + pub rects: Vec<[u32; 4]>, + /// Rows of the buffer moved by `dy` (down when positive) before the dirty tiles painted: + /// a window can scroll its own copy by as much and copy only the rest. + pub scrolled: Option<([u32; 4], i32)>, + /// Hashing tiles, on the calling thread, with telling a scroll and moving its rows. + pub hash_ns: u64, + /// Of that, telling whether the frame scrolled (`scroll.rs`), and moving the rows. + pub plan_ns: u64, + pub move_ns: u64, +} + +impl CpuPainter { + /// A painter running on `threads` threads, the caller among them (the others are made now, + /// and park between frames). + pub fn new(threads: usize) -> CpuPainter { + CpuPainter { pool: Pool::new(threads), hashes: Vec::new(), next: Vec::new(), each: Vec::new(), size: (0, 0), stride: 0, dirty: Vec::new(), prev: None, resets: 0, flags: None, changed: Vec::new(), marked: Vec::new() } + } + + /// The buffer's pixels are no longer the last frame's (a new buffer): the next frame paints + /// every tile. A buffer that keeps its row pitch when the window resizes needn't: tiles + /// whole in both sizes keep what they held, and only those that changed paint. + pub fn forget(&mut self) { + self.hashes.clear(); + self.prev = None; + self.flags = None; + } + + /// Fills the masks the text system queued (`fill_masks`) on this painter's threads. + pub fn fill_masks(&self, atlas: &mut crate::text::Atlas) -> super::FillReport { + super::fill::fill_with(atlas, &|threads| Threads { pool: &self.pool, extra: (threads - 1).min(self.pool.threads() - 1) }) + } + + /// Paints `scene` into `target`, which holds the frame this painter painted last unless + /// `forget` was called since. + pub fn paint(&mut self, scene: &Scene<'_>, target: &mut Target<'_>) -> Result<Painted, NeedsGpu> { + super::check_target(scene, target)?; + let start = crate::time::now(); + // A recoloured frame draws what the last one did, so whatever it needed it still does. + if self.flags == Some(scene.flags()) && let Some(p) = self.recoloured(scene, target, start) { return Ok(p); } + if let Some(why) = scene.needs_gpu() { return Err(why); } + self.flags = Some(scene.flags()); + let bins = Bins::of(scene); + let binned = crate::time::now(); + damage::hashes(scene, &bins, &mut self.each, &mut self.next); + // Pixels stay where they were only in rows as far apart as before. + if self.stride != target.stride { self.hashes.clear(); } + self.dirty.clear(); + let all = self.hashes.is_empty(); + let resized = self.size != scene.size; + // A tile's hash last frame. After a resize, a tile keeps its place (the buffer's rows + // don't move), so one whole in both sizes compares with itself; one cut by either + // edge holds pixels that were never painted. + let (old, ocols) = (self.size, self.size.0.div_ceil(super::bin::TILE_W)); + let whole = |tx: u32, ty: u32, (w, h): (u32, u32)| (tx + 1) * super::bin::TILE_W <= w && (ty + 1) * super::bin::TILE_H <= h; + let before = |t: usize| -> Option<u64> { + if all { return None; } + if !resized { return Some(self.hashes[t]); } + let (tx, ty) = (t as u32 % bins.cols, t as u32 / bins.cols); + (whole(tx, ty, old) && whole(tx, ty, scene.size)).then(|| self.hashes[(ty * ocols + tx) as usize]) + }; + let hash_changed = |t: usize| before(t) != Some(self.next[t]); + // A backdrop blur reads every pixel of its region: when any tile there changed, the + // whole region paints again (what's under the blur first, then the blur). + let mut redo = vec![false; self.next.len()]; + for (_, rec) in &bins.blurs { + if all || super::bin::region_tiles(rec.region, bins.cols, bins.rows).any(hash_changed) { + for t in super::bin::region_tiles(rec.region, bins.cols, bins.rows) { redo[t] = true; } + } + } + let changed = |t: usize| redo[t] || hash_changed(t); + let by_hash = (0..self.next.len()).filter(|&t| changed(t)).count(); + // Only a frame that changed many tiles can be a scroll; and a move is kept only when it + // leaves fewer tiles to paint than the hashes alone do. + let planning = crate::time::now(); + let shift = if all || resized || by_hash < MIN_SCROLL_TILES { None } else { self.prev.as_ref().and_then(|p| scroll::plan(p, scene, &bins, &Threads { pool: &self.pool, extra: self.pool.threads() - 1 })) }; + let touched = |s: &scroll::Shift, t: usize| { + let (tx, ty) = (t as u32 % bins.cols, t as u32 / bins.cols); + tx * super::bin::TILE_W < s.rect[2] && (tx + 1) * super::bin::TILE_W > s.rect[0] && ty * super::bin::TILE_H < s.rect[3] && (ty + 1) * super::bin::TILE_H > s.rect[1] + }; + // A tile the move touched holds the right pixels only if it moved whole. + let dirty = |s: Option<&scroll::Shift>, t: usize| match s { + Some(s) if touched(s, t) => bins.quiet[t] || !s.clean[t], + _ => changed(t), + }; + let shift = shift.filter(|s| (0..self.next.len()).filter(|&t| dirty(Some(s), t)).count() < by_hash); + let moving = crate::time::now(); + if let Some(s) = &shift { + let movers = (s.clean.iter().filter(|&&c| c).count() / TILES_PER_THREAD).min(self.pool.threads() - 1); + move_tiles(&Threads { pool: &self.pool, extra: movers }, target, scene.size, bins.cols, &s.clean, s.dy); + } + let moved = crate::time::now(); + self.dirty.extend((0..self.next.len() as u32).filter(|&t| dirty(shift.as_ref(), t as usize))); + std::mem::swap(&mut self.hashes, &mut self.next); + self.size = scene.size; + self.stride = target.stride; + self.resets = scene.atlas_resets; + let hashed = crate::time::now(); + let extra = (self.dirty.len() / TILES_PER_THREAD).min(self.pool.threads() - 1); + let mut report = raster::run(scene, &bins, target, &self.dirty, &Threads { pool: &self.pool, extra }, &Threads { pool: &self.pool, extra: self.pool.threads() - 1 }); + let done = crate::time::now(); + report.bin_ns = super::ns(binned - start); + report.raster_ns = super::ns(done - hashed); + report.total_ns = super::ns(done - start); + report.tiles = bins.tile_count(); + report.binned = bins.len(); + report.culled = bins.culled; + let mut rects = damage::rects(&self.dirty, bins.cols, scene.size, MAX_RECTS); + if let Some(s) = &shift { damage::add(&mut rects, s.rect, MAX_RECTS); } + let scrolled = shift.as_ref().map(|s| (s.rect, s.dy)); + self.prev = Some(scroll::Prev { instances: scene.instances.to_vec(), bins }); + Ok(Painted { dirty_tiles: self.dirty.len(), tiles: report.tiles, rects, scrolled, hash_ns: super::ns(hashed - binned), plan_ns: super::ns(moving - planning), move_ns: super::ns(moved - moving), report }) + } +} + +impl CpuPainter { + /// A frame that draws the last frame's instances, some of them in other colours (a spinner's + /// dots, a caret's blink, a hover's fill) or with new texels (an animated image): the bins + /// still hold, so it skips binning and hashing every tile, repaints only the tiles the + /// changed instances reach, and rehashes only those. With nothing changed it touches + /// nothing: no tile, no rect, nothing to present. None when the frame needs the full path. + fn recoloured(&mut self, scene: &Scene<'_>, target: &mut Target<'_>, start: Instant) -> Option<Painted> { + let prev = self.prev.as_mut()?; + if self.hashes.is_empty() || self.size != scene.size || self.stride != target.stride || prev.instances.len() != scene.instances.len() || self.resets != scene.atlas_resets { + return None; + } + // The whole list at memcmp's speed first: most frames that get here changed nothing. + let images = scene.images.iter().any(|p| p.dirty.is_some()); + if !images && bytemuck::cast_slice::<Instance, u8>(scene.instances) == bytemuck::cast_slice::<Instance, u8>(&prev.instances) { + let mut report = Report { total_ns: super::ns(start.elapsed()), tiles: prev.bins.tile_count(), ..Report::default() }; + report.raster_ns = 0; + return Some(Painted { tiles: report.tiles, hash_ns: report.total_ns, report, ..Painted::default() }); + } + self.changed.clear(); + for (n, (new, old)) in scene.instances.iter().zip(&prev.instances).enumerate() { + let same = bytemuck::bytes_of(new) == bytemuck::bytes_of(old) + && !(new.kind() == Some(Kind::Image) && image_written(scene, new) && damage::instance(scene, &prev.bins, n) != self.each[n]); + if same { continue; } + if self.changed.len() == RECOLOURED_MAX || !recolour(new, old) { return None; } + self.changed.push(n as u32); + } + let bins = &prev.bins; + let tiles = bins.tile_count(); + self.marked.clear(); + self.marked.resize(tiles, false); + for &n in &self.changed { + let b = bins.bounds[n as usize]; + if b[2] <= b[0] || b[3] <= b[1] { continue; } + let (tx0, tx1) = (b[0] as u32 / TILE_W, (b[2] as u32).div_ceil(TILE_W).min(bins.cols)); + for ty in b[1] as u32 / TILE_H..(b[3] as u32).div_ceil(TILE_H).min(bins.rows) { + for tx in tx0..tx1 { self.marked[(ty * bins.cols + tx) as usize] = true; } + } + } + // A blur under a changed tile is taken again: its whole region paints. + for (_, rec) in &bins.blurs { + if super::bin::region_tiles(rec.region, bins.cols, bins.rows).any(|t| self.marked[t]) { + for t in super::bin::region_tiles(rec.region, bins.cols, bins.rows) { self.marked[t] = true; } + } + } + self.dirty.clear(); + self.dirty.extend((0..tiles as u32).filter(|&t| self.marked[t as usize])); + for &n in &self.changed { + self.each[n as usize] = damage::instance(scene, bins, n as usize); + prev.instances[n as usize] = scene.instances[n as usize]; + } + for &t in &self.dirty { + self.hashes[t as usize] = damage::rehash(scene, bins, &self.each, t as usize); + } + let hashed = crate::time::now(); + let extra = (self.dirty.len() / TILES_PER_THREAD).min(self.pool.threads() - 1); + let mut report = if self.dirty.is_empty() { Report::default() } else { raster::run(scene, bins, target, &self.dirty, &Threads { pool: &self.pool, extra }, &Threads { pool: &self.pool, extra: self.pool.threads() - 1 }) }; + let done = crate::time::now(); + report.raster_ns = super::ns(done - hashed); + report.total_ns = super::ns(done - start); + report.tiles = tiles; + let rects = damage::rects(&self.dirty, bins.cols, scene.size, MAX_RECTS); + Some(Painted { dirty_tiles: self.dirty.len(), tiles, rects, scrolled: None, hash_ns: super::ns(hashed - start), plan_ns: 0, move_ns: 0, report }) + } +} + +/// Whether `new` is `old` in other colours: every word the same but its fill, a box's border and +/// `params.w` (an opacity, a text gamma), which no bin, bound or layer plan reads outside layers, +/// and opaque exactly where it was (the occluders and the tiles it covers whole stay). Layer scopes and blurs (whose opacity plans a layer) don't count. +fn recolour(new: &Instance, old: &Instance) -> bool { + let (a, b): (&[u32; INSTANCE_WORDS], &[u32; INSTANCE_WORDS]) = (bytemuck::cast_ref(new), bytemuck::cast_ref(old)); + // The border is a colour only for boxes and gradients (a glyph's names its outline). + let (border, shading_w) = match new.kind() { + Some(Kind::Layer | Kind::LayerEnd | Kind::BackdropBlur | Kind::Effect) | None => return false, + Some(Kind::Rect) => (true, true), + Some(Kind::Glyph) => (false, true), + Some(Kind::Gradient | Kind::Dashed | Kind::Radial) => (true, false), + Some(Kind::Shadow | Kind::Inset | Kind::Segment | Kind::Triangle | Kind::Image) => (false, false), + }; + (0..INSTANCE_WORDS).all(|k| { + word::FILL.contains(&k) + || (word::BORDER.contains(&k) && border) + || (k == word::PARAMS_W && shading_w) + || a[k] == b[k] + }) && super::bin::opaque_box(new) == super::bin::opaque_box(old) +} + +/// Whether rows `new` samples were written into its image page since the renderer last took it. +fn image_written(scene: &Scene<'_>, i: &Instance) -> bool { + let Some(page) = scene.images.get(i.params[0] as usize) else { return false }; + let (y0, y1) = (i.uv[1].max(0.0) as u32, (i.uv[1] + i.uv[3]).max(0.0).ceil() as u32); + page.dirty.is_some_and(|(a, b)| a < y1 && b > y0) +} + +/// Minimum vertical shift (in rows) before `move_tiles` splits work into parallel row waves. +/// Smaller shifts copy sequentially with merged row spans so rows stay hot in cache without +/// paying per-wave thread-pool barriers. +const MIN_WAVE_ROWS: u32 = TILE_H * 2; + +struct MoveGrid<'a> { + size: (u32, u32), + stride: usize, + cols: u32, + clean: &'a [bool], +} + +impl MoveGrid<'_> { + fn row_clean(&self, ty: u32) -> &[bool] { + let a = (ty * self.cols) as usize; + &self.clean[a..a + self.cols as usize] + } + + fn any_clean_in_rows(&self, y0: u32, y1: u32) -> bool { + let a = ((y0 / TILE_H) * self.cols) as usize; + let b = (y1.div_ceil(TILE_H) * self.cols) as usize; + self.clean[a..b].iter().any(|&c| c) + } + + /// Copies every contiguous run of clean tiles in tile-row `ty` from `src_row` to `dst_row`. + fn copy_spans(&self, dst_row: &mut [u8], src_row: &[u8], ty: u32) { + let row_clean = self.row_clean(ty); + let mut tx = 0u32; + while tx < self.cols { + if !row_clean[tx as usize] { + tx += 1; + continue; + } + let start = tx; + while tx < self.cols && row_clean[tx as usize] { + tx += 1; + } + let x0 = (start * TILE_W) as usize * 4; + let x1 = (tx * TILE_W).min(self.size.0) as usize * 4; + dst_row[x0..x1].copy_from_slice(&src_row[x0..x1]); + } + } + + /// Copies one disjoint wave of destination rows starting at `dst_start` from `src_buf` (whose + /// first byte is row `src_origin`) across `exec`'s threads. + fn copy_wave( + &self, + exec: &dyn raster::Exec, + dst_buf: &mut [u8], + src_buf: &[u8], + dst_start: u32, + src_origin: u32, + dy: i32, + ) { + use std::sync::Mutex; + let stride = self.stride; + let row_bytes = self.size.0 as usize * 4; + let shift = dy.unsigned_abs(); + let total = dst_buf.len().div_ceil(stride); + let workers = exec.threads().max(1); + let band = (total / (workers * 2)).max(8).min(total.max(1)); + let work = Mutex::new((dst_start, dst_buf.chunks_mut(band * stride))); + exec.run(&|| loop { + let next = { + let mut guard = work.lock().unwrap_or_else(|e| e.into_inner()); + guard.1.next().map(|chunk| { + let y = guard.0; + guard.0 += chunk.len().div_ceil(stride) as u32; + (y, chunk) + }) + }; + let Some((y_start, chunk)) = next else { break }; + for (i, dst_row) in chunk.chunks_mut(stride).enumerate() { + let y = y_start + i as u32; + let ty = y / TILE_H; + if !self.row_clean(ty).iter().any(|&c| c) { continue; } + let src_y = if dy > 0 { y - shift } else { y + shift }; + let src_at = (src_y - src_origin) as usize * stride; + let src_row = &src_buf[src_at..src_at + row_bytes]; + self.copy_spans(dst_row, src_row, ty); + } + }); + } + + /// Copies clean tile runs row by row in-place via `copy_within`, merging adjacent clean tiles + /// into contiguous horizontal spans. + fn move_sequential(&self, pixels: &mut [u8], dy: i32) { + let tile_rows = self.size.1.div_ceil(TILE_H); + let shift = dy.unsigned_abs(); + let copy_row = |pixels: &mut [u8], ty: u32, y: u32, src_y: u32| { + let row_clean = self.row_clean(ty); + let dst_row = y as usize * self.stride; + let src_row = src_y as usize * self.stride; + let mut tx = 0u32; + while tx < self.cols { + if !row_clean[tx as usize] { + tx += 1; + continue; + } + let start = tx; + while tx < self.cols && row_clean[tx as usize] { + tx += 1; + } + let x0 = (start * TILE_W) as usize * 4; + let x1 = (tx * TILE_W).min(self.size.0) as usize * 4; + pixels.copy_within(src_row + x0..src_row + x1, dst_row + x0); + } + }; + if dy > 0 { + for ty in (0..tile_rows).rev() { + if !self.row_clean(ty).iter().any(|&c| c) { continue; } + let (a, b) = (ty * TILE_H, ((ty + 1) * TILE_H).min(self.size.1)); + for y in (a..b).rev() { + copy_row(pixels, ty, y, y - shift); + } + } + } else { + for ty in 0..tile_rows { + if !self.row_clean(ty).iter().any(|&c| c) { continue; } + let (a, b) = (ty * TILE_H, ((ty + 1) * TILE_H).min(self.size.1)); + for y in a..b { + copy_row(pixels, ty, y, y + shift); + } + } + } + } +} + +/// Moves the tiles the scroll left clean `dy` rows (down when positive): each takes what was +/// `dy` rows back. Adjacent clean tiles on a row copy together as one contiguous span. Larger +/// shifts (`|dy| >= MIN_WAVE_ROWS`) split into disjoint `|dy|`-row waves whose source and +/// destination slices don't overlap, running each wave across `threads`'s workers in row order +/// that reads every row before it is written (bottom up for a move down); smaller shifts copy +/// sequentially in place. The rest repaint, so they aren't moved. +pub(super) fn move_tiles(threads: &dyn raster::Exec, target: &mut Target<'_>, size: (u32, u32), cols: u32, clean: &[bool], dy: i32) { + let shift = dy.unsigned_abs(); + if shift == 0 || shift >= size.1 || size.0 == 0 { return; } + let grid = MoveGrid { size, stride: target.stride, cols, clean }; + if threads.threads() <= 1 || shift < MIN_WAVE_ROWS { + grid.move_sequential(target.pixels, dy); + return; + } + if dy > 0 { + let mut dst_end = size.1; + while dst_end > shift { + let dst_start = dst_end.saturating_sub(shift).max(shift); + if grid.any_clean_in_rows(dst_start, dst_end) { + let split = dst_start as usize * grid.stride; + let (src_buf, dst_rest) = target.pixels.split_at_mut(split); + let wave_bytes = ((dst_end - dst_start) as usize * grid.stride).min(dst_rest.len()); + grid.copy_wave(threads, &mut dst_rest[..wave_bytes], src_buf, dst_start, 0, dy); + } + dst_end = dst_start; + } + } else { + let limit = size.1 - shift; + let mut dst_start = 0u32; + while dst_start < limit { + let dst_end = (dst_start + shift).min(limit); + if grid.any_clean_in_rows(dst_start, dst_end) { + let split = dst_end as usize * grid.stride; + let (dst_all, src_buf) = target.pixels.split_at_mut(split); + let dst_buf = &mut dst_all[dst_start as usize * grid.stride..]; + grid.copy_wave(threads, dst_buf, src_buf, dst_start, dst_end, dy); + } + dst_start = dst_end; + } + } +} +/// The pool, with as many of its workers as the frame's damage pays for. +struct Threads<'p> { + pool: &'p Pool, + extra: usize, +} + +impl raster::Exec for Threads<'_> { + fn threads(&self) -> usize { self.extra + 1 } + + fn run(&self, job: &(dyn Fn() + Sync)) { self.pool.run(self.extra, job); } +} diff --git a/app/vendor/rune/crates/rune/src/render/cpu_boot/pool.rs b/app/vendor/rune/crates/rune/src/render/cpu_boot/pool.rs new file mode 100644 index 0000000..2f1a904 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/render/cpu_boot/pool.rs @@ -0,0 +1,116 @@ +//! A small persistent pool of painting threads: parked between frames, woken together for one +//! job, which the calling thread runs too, and joined before `run` returns, so a job may borrow +//! the frame. Spawning threads per frame costs tens of microseconds each on Windows; waking a +//! parked one costs a few. + +#![allow(unsafe_code)] + +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::{Arc, Condvar, Mutex}; + +/// A job: run by every thread of the pool and by the caller. +type Job = dyn Fn() + Sync; + +struct Shared { + state: Mutex<State>, + wake: Condvar, + done: Condvar, + /// Workers still running the current job. + running: AtomicUsize, +} + +/// What the workers see, as one state: parked, a job to run (and which one, so a worker runs each +/// once), or told to leave. +enum State { + Idle { round: u64 }, + Working { round: u64, job: JobRef, wanted: usize }, + Leaving, +} + +/// A job borrowed for one `run`: `run` waits until every worker that took it is done, so the +/// reference never outlives what it points at. +#[derive(Clone, Copy)] +struct JobRef(*const Job); + +// SAFETY: the job is `Sync`; the pointer is only dereferenced while `run` keeps it alive. +unsafe impl Send for JobRef {} + +pub struct Pool { + shared: Arc<Shared>, + workers: Vec<std::thread::JoinHandle<()>>, +} + +impl Pool { + /// A pool that runs jobs on `threads` threads in all: the caller and `threads - 1` workers. + pub fn new(threads: usize) -> Pool { + let shared = Arc::new(Shared { state: Mutex::new(State::Idle { round: 0 }), wake: Condvar::new(), done: Condvar::new(), running: AtomicUsize::new(0) }); + let workers = (1..threads.max(1)).map(|k| { + let shared = shared.clone(); + std::thread::Builder::new().name(format!("rune-cpu-paint-{k}")).spawn(move || work(&shared, k)).expect("a painting thread") + }).collect(); + Pool { shared, workers } + } + + /// Threads a job runs on, the caller included. + pub fn threads(&self) -> usize { self.workers.len() + 1 } + + /// Runs `job` on the caller and on `extra` workers (at most all of them), returning once all + /// have finished it. + pub fn run(&self, extra: usize, job: &(dyn Fn() + Sync + '_)) { + let extra = extra.min(self.workers.len()); + if extra == 0 { return job(); } + // SAFETY: only the lifetime is erased; `run` doesn't return before `running` is back to + // zero, so no worker holds the pointer past this call. + let erased: *const Job = unsafe { std::mem::transmute::<&(dyn Fn() + Sync + '_), &'static Job>(job) }; + { + let mut s = self.shared.state.lock().unwrap_or_else(|e| e.into_inner()); + let round = match *s { State::Idle { round } => round + 1, _ => return job() }; + self.shared.running.store(extra, Ordering::Release); + *s = State::Working { round, job: JobRef(erased), wanted: extra }; + } + self.shared.wake.notify_all(); + job(); + let mut s = self.shared.state.lock().unwrap_or_else(|e| e.into_inner()); + while self.shared.running.load(Ordering::Acquire) > 0 { + s = self.shared.done.wait(s).unwrap_or_else(|e| e.into_inner()); + } + if let State::Working { round, .. } = *s { *s = State::Idle { round }; } + } +} + +/// A worker: waits for a round it hasn't run, runs it if it's among those wanted, reports done. +fn work(shared: &Shared, k: usize) { + let mut last = 0; + loop { + let job = { + let mut s = shared.state.lock().unwrap_or_else(|e| e.into_inner()); + loop { + match *s { + State::Leaving => return, + State::Working { round, job, wanted } if round != last => { + last = round; + if k <= wanted { break job; } + } + _ => {} + } + s = shared.wake.wait(s).unwrap_or_else(|e| e.into_inner()); + } + }; + // SAFETY: `run` keeps the job alive until `running` reaches zero, which this decrement + // can only do after the call returns. + // A panic in a job is the caller's to see; the count must still go down. + std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| unsafe { (*job.0)() })).ok(); + if shared.running.fetch_sub(1, Ordering::AcqRel) == 1 { + let _guard = shared.state.lock().unwrap_or_else(|e| e.into_inner()); + shared.done.notify_all(); + } + } +} + +impl Drop for Pool { + fn drop(&mut self) { + *self.shared.state.lock().unwrap_or_else(|e| e.into_inner()) = State::Leaving; + self.shared.wake.notify_all(); + for w in self.workers.drain(..) { w.join().ok(); } + } +} diff --git a/app/vendor/rune/crates/rune/src/render/cpu_boot/raster.rs b/app/vendor/rune/crates/rune/src/render/cpu_boot/raster.rs new file mode 100644 index 0000000..7421a02 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/render/cpu_boot/raster.rs @@ -0,0 +1,541 @@ +//! Painting tiles: each thread takes the next tile, and draws its instances in painter order +//! straight into the 8-bit target, blending each as the GPU's +//! premultiplied source-over does on a `Bgra8Unorm` target: the destination read as stored, the +//! result rounded back to 8 bits after every instance. A layer drawn to its own target draws into +//! a scratch tile holding what an `Rgba16Float` texel holds, composited at its end. + +mod glyph; +mod segments; + +use std::sync::Mutex; +use std::sync::atomic::{AtomicUsize, Ordering}; + +use glyph::Pow; +use segments::{Occluder, Segment, centres}; + +use super::bin::{Bins, Show, Solid, TILE_H, TILE_W, interior, intersect}; +use super::backdrop; +use super::blend::{self, Src, q}; +use super::shade::{self, Clip}; +use super::{HalfRounding, Report, Scene, Target}; +use crate::render::instance::shader_consts; +use crate::render::{Instance, Kind}; + +const TILE_PX: usize = (TILE_W * TILE_H) as usize; + +/// Paints iles on xec's threads; backdrop blurs, taken between phases, go on wide's. +pub(super) fn run(scene: &Scene<'_>, bins: &Bins, target: &mut Target<'_>, tiles: &[u32], exec: &dyn Exec, wide: &dyn Exec) -> Report { + let surface = Surface { base: target.pixels.as_mut_ptr(), len: target.pixels.len(), stride: target.stride }; + let clear = scene.clear.map(|c| c.clamp(0.0, 1.0) * 255.0); + let clear = [q(clear[2]), q(clear[1]), q(clear[0]), q(clear[3])]; + let mut report = Report { threads: exec.threads(), ..Report::default() }; + if tiles.is_empty() { return report; } + // Each record's blur, or None when no tile painted this frame shows it. + let mut blurred: Vec<Option<backdrop::Blurred>> = Vec::with_capacity(bins.blurs.len()); + // A backdrop blur splits the frame: what's under it is painted everywhere first. + let cuts: Vec<u32> = bins.blurs.iter().map(|(n, _)| *n).chain([u32::MAX]).collect(); + let mut from = 0; + for (phase, &until) in cuts.iter().enumerate() { + let next = AtomicUsize::new(0); + let done = &blurred; + let sums = Mutex::new(Report::default()); + let worker = || { + let mut stats = Report::default(); + let mut pow = Pow::default(); + let mut layers: Vec<Scratch> = Vec::new(); + let mut occ: Vec<Occluder> = Vec::new(); + let mut painter = Painter { scene, bins, surface, stats: &mut stats, pow: &mut pow, layers: &mut layers, depth: 0, tile: [0; 4], + occ: &mut occ, n: 0, breaks: Vec::new(), segs: Vec::new(), blurred: done }; + // A big frame goes out a page-wide run of tiles at a time (16 tiles: 1,024 pixels of + // each row, about a page), so threads fault in pages of their own rather than all + // queuing on the same ones (a fresh buffer: 12,969 to 9,992 µs); a small one tile at + // a time, so a thread that drew cheap tiles takes more. + let chunk = if tiles.len() > 512 { 16 } else { 1 }; + loop { + let at = next.fetch_add(chunk, Ordering::Relaxed); + if at >= tiles.len() { break; } + for &t in &tiles[at..(at + chunk).min(tiles.len())] { + let t = t as usize; + let began = crate::time::now(); + painter.tile = painter.tile_rect(t as u32 % bins.cols, t as u32 / bins.cols); + if phase == 0 && !bins.covered[t] { + painter.surface.fill(painter.tile, clear); + painter.stats.cleared += 1; + } + let list = bins.tile(t); + let (a, b) = (list.partition_point(|&n| n < from), list.partition_point(|&n| n < until)); + painter.occluders(&list[a..b]); + for &n in &list[a..b] { + let b = bins.bounds[n as usize]; + let tile = painter.tile; + let r = [(b[0] as u32).max(tile[0]), (b[1] as u32).max(tile[1]), (b[2] as u32).min(tile[2]), (b[3] as u32).min(tile[3])]; + if r[2] > r[0] && r[3] > r[1] { painter.draw(n, r); } + } + painter.depth = 0; + painter.stats.slowest_tile_ns = painter.stats.slowest_tile_ns.max(super::ns(began.elapsed())); + } + } + drop(painter); + let mut s = sums.lock().unwrap_or_else(|e| e.into_inner()); + s.span_px += stats.span_px; + s.shaded_px += stats.shaded_px; + s.glyph_px += stats.glyph_px; + s.cleared += stats.cleared; + s.slowest_tile_ns = s.slowest_tile_ns.max(stats.slowest_tile_ns); + }; + exec.run(&worker); + let s = sums.into_inner().unwrap_or_else(|e| e.into_inner()); + report.span_px += s.span_px; + report.shaded_px += s.shaded_px; + report.glyph_px += s.glyph_px; + report.cleared += s.cleared; + report.slowest_tile_ns = report.slowest_tile_ns.max(s.slowest_tile_ns); + if let Some((n, rec)) = bins.blurs.get(phase) { + let px: &[u8] = &*target.pixels; + let stride = target.stride; + let b = bins.bounds[*n as usize]; + let shown = tiles.iter().any(|&t| { + let (tx, ty) = (t % bins.cols, t / bins.cols); + ((tx * TILE_W) as i32) < b[2] && (((tx + 1) * TILE_W) as i32) > b[0] && ((ty * TILE_H) as i32) < b[3] && (((ty + 1) * TILE_H) as i32) > b[1] + }); + let began = crate::time::now(); + blurred.push(shown.then(|| backdrop::blur(rec, scene.size, scene.half, wide, |x, y| { + let at = y as usize * stride + x as usize * 4; + [px[at + 2] as f32 / 255.0, px[at + 1] as f32 / 255.0, px[at] as f32 / 255.0, px[at + 3] as f32 / 255.0] + }))); + report.blur_ns += super::ns(began.elapsed()); + } + from = until; + } + report +} +/// Runs a painting job on some threads at once, the caller among them, and returns when all are +/// done. +pub(super) trait Exec { + fn threads(&self) -> usize; + fn run(&self, job: &(dyn Fn() + Sync)); +} + +/// Threads made for the one job (`paint`), joined at its end. +pub(super) struct Spawn(pub usize); + +impl Exec for Spawn { + fn threads(&self) -> usize { self.0.max(1) } + + fn run(&self, job: &(dyn Fn() + Sync)) { + std::thread::scope(|s| { + for _ in 1..self.0 { s.spawn(job); } + job(); + }); + } +} + +/// What an `Rgba16Float` texel keeps of `v` on the GPU that takes over (`HalfRounding`). Colours +/// here stay far below half's largest value. +#[inline] +pub(super) fn f16(v: f32, r: HalfRounding) -> f32 { + let b = v.to_bits(); + if v.abs() >= 6.103_515_6e-5 { + // 10 of f32's 23 mantissa bits stay; to nearest, add half of what goes (and one more + // when what stays is odd) first. + let up = match r { HalfRounding::TowardZero => 0, HalfRounding::NearestEven => 0x0fff + ((b >> 13) & 1) }; + return f32::from_bits((b + up) & 0xffff_e000); + } + // Subnormal halves are whole multiples of 2^-24. + const M: f32 = 16_777_216.0; + match r { + HalfRounding::TowardZero => (v * M).trunc() / M, + HalfRounding::NearestEven => ((v * M + 12_582_912.0) - 12_582_912.0) / M, + } +} + +/// `f16` on four values at once: F16C's conversion where the CPU has it. +#[inline] +#[allow(unsafe_code)] +pub(super) fn f16x4(v: [f32; 4], r: HalfRounding) -> [f32; 4] { + #[cfg(target_arch = "x86_64")] + if std::arch::is_x86_feature_detected!("f16c") { + // SAFETY: the CPU has F16C (checked). + return unsafe { f16x4_f16c(v, r) }; + } + v.map(|x| f16(x, r)) +} + +#[cfg(target_arch = "x86_64")] +#[target_feature(enable = "f16c")] +#[allow(unsafe_code)] +unsafe fn f16x4_f16c(v: [f32; 4], r: HalfRounding) -> [f32; 4] { + use std::arch::x86_64::*; + let mut out = [0.0f32; 4]; + // SAFETY: both arrays hold four floats. + unsafe { + let x = _mm_loadu_ps(v.as_ptr()); + let h = match r { + HalfRounding::TowardZero => _mm_cvtps_ph::<_MM_FROUND_TO_ZERO>(x), + HalfRounding::NearestEven => _mm_cvtps_ph::<_MM_FROUND_TO_NEAREST_INT>(x), + }; + _mm_storeu_ps(out.as_mut_ptr(), _mm_cvtph_ps(h)); + } + out +} +/// The target's pixels, shared by the threads: each writes only the tile it holds, and tiles +/// don't overlap. +#[derive(Clone, Copy)] +struct Surface { + base: *mut u8, + len: usize, + stride: usize, +} + +// SAFETY: `run` hands each tile to one thread; a thread writes only pixels of its tile, and the +// target outlives the scope its threads run in. +#[allow(unsafe_code)] +unsafe impl Send for Surface {} +// SAFETY: as above; `run` partitions the target into disjoint tiles across threads and joins +// before the target borrow ends. +#[allow(unsafe_code)] +unsafe impl Sync for Surface {} + +impl Surface { + #[inline] + fn at(&self, x: u32, y: u32) -> usize { y as usize * self.stride + x as usize * 4 } + + /// `n` pixels of row `y` from `x`, all inside the target and the caller's tile. + #[inline] + #[allow(unsafe_code)] + fn row(&mut self, x: u32, y: u32, n: u32) -> &mut [u8] { + let at = self.at(x, y); + let len = n as usize * 4; + assert!(at + len <= self.len); + // SAFETY: in bounds (checked), and only this tile's thread touches these bytes. + unsafe { std::slice::from_raw_parts_mut(self.base.add(at), len) } + } + /// Writes `px` over `r`. + fn fill(&mut self, r: [u32; 4], px: [u8; 4]) { + for y in r[1]..r[3] { blend::fill_row(self.row(r[0], y, r[2] - r[0]), px); } + } + + /// Blends premultiplied RGBA `c` (0..=1) over pixels `x0..x1` of row `y`. + #[inline] + fn span(&mut self, x0: u32, x1: u32, y: u32, c: [f32; 4]) { + blend::over_row(self.row(x0, y, x1 - x0), &Src::new(c)); + } + + #[inline] + fn blend(&mut self, x: u32, y: u32, c: [f32; 4]) { + blend::over_rgba(self.row(x, y, 1), c); + } + + #[inline] + fn blend_lcd(&mut self, x: u32, y: u32, c: [f32; 4], k: [f32; 3]) { + blend::over_lcd(self.row(x, y, 1), c, k); + } +} +/// A layer's target over one tile: premultiplied RGBA as `Rgba16Float` holds it, cleared to +/// zero, and how it blends what's drawn into it. +struct Scratch { + px: Vec<[f32; 4]>, + additive: bool, + /// The plan it draws (`Bins::layers`). + plan: usize, +} + +struct Painter<'p, 's> { + scene: &'p Scene<'s>, + bins: &'p Bins, + surface: Surface, + stats: &'p mut Report, + pow: &'p mut Pow, + /// The thread's scratch tiles, reused; the first `depth` are open layers, innermost last. + layers: &'p mut Vec<Scratch>, + depth: usize, + /// The tile being drawn, `[x0, y0, x1, y1)`. + tile: [u32; 4], + /// The opaque boxes in this tile that draw straight into the window: a pixel one of them + /// paints whole needs nothing drawn under it. + occ: &'p mut Vec<Occluder>, + /// The instance being drawn. + n: u32, + /// Scratch for `segments`, kept between instances. + breaks: Vec<u32>, + segs: Vec<Segment>, + /// The blurs of the frame's backdrop blur records painted so far, in order. + blurred: &'p [Option<backdrop::Blurred>], +} + +impl Painter<'_, '_> { + /// Tile `tx`'s pixels `[x0, y0, x1, y1)` in the target. + fn tile_rect(&self, tx: u32, ty: u32) -> [u32; 4] { + let (w, h) = self.scene.size; + [tx * TILE_W, ty * TILE_H, ((tx + 1) * TILE_W).min(w), ((ty + 1) * TILE_H).min(h)] + } + + #[inline] + fn slot(&self, x: u32, y: u32) -> usize { ((y - self.tile[1]) * TILE_W + (x - self.tile[0])) as usize } + + /// Blends premultiplied `c` into pixel `(x, y)` of whatever is being drawn into. + #[inline] + fn put(&mut self, x: u32, y: u32, c: [f32; 4]) { + if self.depth == 0 { + // Under half a step in every channel it rounds to nothing and leaves the pixel as is: + // a shadow's tail, a glyph's faintest edge. + if c[0].max(c[1]).max(c[2]).max(c[3]) * 255.0 <= 0.5 { return; } + return self.surface.blend(x, y, c); + } + let s = self.slot(x, y); + let top = &mut self.layers[self.depth - 1]; + let d = &mut top.px[s]; + let half = self.scene.half; + let c = f16x4(c, half); + let k = if top.additive { 1.0 } else { 1.0 - c[3] }; + *d = f16x4(std::array::from_fn(|ch| c[ch] + d[ch] * k), half); + } + + fn put_span(&mut self, x0: u32, x1: u32, y: u32, c: [f32; 4]) { + if x1 <= x0 { return; } + self.stats.span_px += u64::from(x1 - x0); + if self.depth == 0 { return self.surface.span(x0, x1, y, c); } + let half = self.scene.half; + let c16 = f16x4(c, half); + let top = &mut self.layers[self.depth - 1]; + let (row, x0t) = (((y - self.tile[1]) * TILE_W) as usize, self.tile[0]); + let px = &mut top.px[row + (x0 - x0t) as usize..row + (x1 - x0t) as usize]; + // Opaque over anything is itself: `c + d × 0`. + if c16[3] == 1.0 && !top.additive { return px.fill(c16); } + let k = if top.additive { 1.0 } else { 1.0 - c16[3] }; + for d in px { *d = f16x4(std::array::from_fn(|ch| c16[ch] + d[ch] * k), half); } + } + + /// Draws instance `n` over pixels `r` (inside its bounds and this tile). + fn draw(&mut self, n: u32, r: [u32; 4]) { + let i = &self.scene.instances[n as usize]; + self.n = n; + match i.kind() { + Some(Kind::Layer) => self.open(n), + Some(Kind::LayerEnd) => self.close(i, r), + Some(Kind::Glyph) => { let clip = Clip::of_stops(i, self.scene.fade_stops); self.glyph(i, r, &clip); } + Some(Kind::Image) => { let clip = Clip::of_stops(i, self.scene.fade_stops); self.image(i, r, &clip); } + Some(kind @ (Kind::Rect | Kind::Gradient)) => { let clip = Clip::of_stops(i, self.scene.fade_stops); self.shaded(i, kind, r, &clip, interior(i)); } + Some(Kind::Shadow) => { let clip = Clip::of_stops(i, self.scene.fade_stops); self.shadow(i, r, &clip); } + Some(Kind::Radial) => { + let clip = Clip::of_stops(i, self.scene.fade_stops); + let solid = Solid { + edges: [i.rect[0], i.rect[1], i.rect[0] + i.rect[2], i.rect[1] + i.rect[3]], + radii: i.radii, + inset: i.params[2].max(shader_consts::SOFT_MIN), + }; + self.shaded(i, Kind::Radial, r, &clip, Some(solid)); + } + Some(kind @ (Kind::Inset | Kind::Segment | Kind::Triangle | Kind::Dashed)) => { + let clip = Clip::of_stops(i, self.scene.fade_stops); + self.shaded(i, kind, r, &clip, None); + } + Some(Kind::BackdropBlur) => { let clip = Clip::of_stops(i, self.scene.fade_stops); self.backdrop(i, r, &clip); } + Some(Kind::Effect) | None => {} + } + } + + /// A layer drawn to its own target begins: a cleared scratch tile. + fn open(&mut self, n: u32) { + let Some(&plan) = self.bins.scope.get(&n) else { return }; + let l = &self.bins.layers[plan as usize]; + if l.show != Show::Render { return; } + if self.layers.len() == self.depth { self.layers.push(Scratch { px: vec![[0.0; 4]; TILE_PX], additive: false, plan: 0 }); } + let s = &mut self.layers[self.depth]; + s.px.fill([0.0; 4]); + s.additive = l.additive; + s.plan = plan as usize; + self.depth += 1; + } + + /// The innermost layer ends: its tile composited over pixels `r` of its parent, by its + /// opacity, clip and hole (shader.wgsl's `KIND_LAYER` branch). + fn close(&mut self, end: &Instance, r: [u32; 4]) { + let _ = end; + if self.depth == 0 { return; } + self.depth -= 1; + let plan = self.layers[self.depth].plan; + let l = self.bins.layers[plan]; + let begin = &self.scene.instances[l.begin as usize]; + let clip = Clip::of_stops(begin, self.scene.fade_stops); + let opacity = begin.fill[3]; + let segs = self.segments(r, None, &clip); + let mut k = 0; + for y in r[1]..r[3] { + let py = y as f32 + 0.5; + while segs[k].y1 <= y { k += 1; } + let (whole, vis) = (segs[k].whole, segs[k].vis); + // Where the clip is whole and there's no hole, the composite is each texel by the + // opacity: a row at a time, into the window or the parent layer. + let (fa, fb) = if !l.additive && l.hole[3] <= 0.0 { centres(whole, r[0], r[2]) } else { (r[2], r[2]) }; + for (va, vb) in vis.iter() { + let (a, b) = (fa.max(va), fb.min(vb)); + if b <= a { continue; } + let at = self.slot(a, y); + let n = (b - a) as usize; + if self.depth == 0 { + let src = &self.layers[0].px[at..at + n]; + if opacity == 1.0 { blend::composite_row(self.surface.row(a, y, b - a), src) } else { blend::composite_row_by(self.surface.row(a, y, b - a), src, opacity) } + continue; + } + let (outer, inner) = self.layers.split_at_mut(self.depth); + let parent = &mut outer[self.depth - 1]; + for (d, s) in parent.px[at..at + n].iter_mut().zip(&inner[0].px[at..at + n]) { + if *s == [0.0; 4] { continue; } + let c = if opacity == 1.0 { *s } else { s.map(|v| v * opacity) }; + // Opaque over anything is itself (a texel is already in half precision). + if c[3] == 1.0 && !parent.additive && opacity == 1.0 { *d = c; continue; } + if c == [0.0; 4] { continue; } + let c = f16x4(c, self.scene.half); + let k = if parent.additive { 1.0 } else { 1.0 - c[3] }; + *d = f16x4(std::array::from_fn(|ch| c[ch] + d[ch] * k), self.scene.half); + } + } + for x in vis.iter().flat_map(|(a, b)| a..b).filter(|&x| x < fa || x >= fb) { + let s = self.layers[self.depth].px[self.slot(x, y)]; + if s == [0.0; 4] { continue; } + let px = x as f32 + 0.5; + let s = if l.additive { s.map(|v| v.clamp(0.0, 1.0)) } else { s }; + let a = if px >= whole.0 && px <= whole.1 { 1.0 } else { clip.alpha([px, py]) }; + let h = hole_alpha([px, py], l.hole); + // Whole and opaque over the window: the texel itself, in 8-bit steps. + if self.depth == 0 && s[3] == 1.0 && opacity == 1.0 && a == 1.0 && h == 1.0 { + self.surface.row(x, y, 1).copy_from_slice(&blend::opaque(s)); + continue; + } + let c = s.map(|v| v * opacity * a * h); + if c != [0.0; 4] { self.put(x, y, c); } + } + } + self.segs = segs; + } + + /// A box kind pixel by pixel through `shade::boxes`, with `solid`'s interior in one colour per + /// row where the clip is whole. + fn shaded(&mut self, i: &Instance, kind: Kind, r: [u32; 4], clip: &Clip, solid: Option<Solid>) { + let gradient_row = kind == Kind::Gradient && i.params[0] <= 0.0; + let segs = self.segments(r, solid, clip); + let mut k = 0; + for y in r[1]..r[3] { + let py = y as f32 + 0.5; + while segs[k].y1 <= y { k += 1; } + let (whole, (ia, ib)) = (segs[k].whole, segs[k].solid); + let c = if gradient_row { + let t = ((py - i.rect[1]) / i.rect[3].max(1.0)).clamp(0.0, 1.0); + std::array::from_fn(|ch| i.fill[ch] * (1.0 - t) + i.uv[ch] * t) + } else { i.fill }; + if kind == Kind::Radial && shade::linear_row_outside(i, py, r[0] as f32 + 0.5, r[2] as f32 - 0.5) { continue; } + for (va, vb) in segs[k].vis.iter() { + for x in va..ia.clamp(va, vb) { self.pixel(i, kind, clip, whole, x, y); } + if kind == Kind::Radial { + // A gradient's colour moves along the span; only its coverage is whole there. + for x in ia.max(va)..ib.min(vb) { + let c = shade::radial(i, [x as f32 + 0.5, py], true); + if c != [0.0; 4] { self.put(x, y, c); } + } + } else { + self.put_span(ia.max(va), ib.min(vb), y, c); + } + for x in ib.clamp(va, vb)..vb { self.pixel(i, kind, clip, whole, x, y); } + } + } + self.segs = segs; + } + + /// A `KIND_SHADOW`, its y samples taken once a row and each column's sum once for every row + /// that samples the same (all but the rows near its corners), so a pixel costs a blend. + fn shadow(&mut self, i: &Instance, r: [u32; 4], clip: &Clip) { + let mut key = None; + let mut sums = [f32::NAN; TILE_W as usize]; + let cx = i.rect[0] + i.rect[2] * 0.5; + let segs = self.segments(r, None, clip); + let mut k = 0; + for y in r[1]..r[3] { + let py = y as f32 + 0.5; + while segs[k].y1 <= y { k += 1; } + let (whole, vis) = (segs[k].whole, segs[k].vis); + let row = shade::shadow_row(i, py); + if key != Some(row.key()) { + key = Some(row.key()); + sums = [f32::NAN; TILE_W as usize]; + } + // Where the row's colour is one value, it's a span; a pixel short of each end, so + // rounding in `px - cx` can't put an end pixel on the wrong side. + let (fa, fb, flat) = match row.flat().filter(|_| i.uv[2] <= 0.0) { + Some((reach, cov)) => { + let (a, b) = centres(intersect((cx - reach, cx + reach), whole), r[0], r[2]); + (a + 1, b.saturating_sub(1).max(a + 1), i.fill.map(|v| v * cov)) + } + None => (r[2], r[2], [0.0; 4]), + }; + for (va, vb) in vis.iter() { + if fb > fa { self.put_span(fa.max(va), fb.min(vb), y, flat); } + } + for x in vis.iter().flat_map(|(a, b)| a..b).filter(|&x| x < fa || x >= fb) { + let px = x as f32 + 0.5; + let dx = px - cx; + let cov = if row.inside(dx) { shade::SHADOW_INSIDE } else { + let s = &mut sums[(x - self.tile[0]) as usize]; + if s.is_nan() { *s = row.sum(dx); } + *s + }; + let c = shade::shadow_cov(i, &row, px, cov); + if c == [0.0; 4] { continue; } + let a = if px >= whole.0 && px <= whole.1 { 1.0 } else { clip.alpha([px, py]) }; + self.stats.shaded_px += 1; + if a > 0.0 { self.put(x, y, c.map(|v| v * a)); } + } + } + self.segs = segs; + } + + #[inline] + fn pixel(&mut self, i: &Instance, kind: Kind, clip: &Clip, whole: (f32, f32), x: u32, y: u32) { + let p = [x as f32 + 0.5, y as f32 + 0.5]; + let c = shade::boxes(i, kind, p); + if c == [0.0; 4] { return; } + let a = if p[0] >= whole.0 && p[0] <= whole.1 { 1.0 } else { clip.alpha(p) }; + self.stats.shaded_px += 1; + if a > 0.0 { self.put(x, y, c.map(|v| v * a)); } + } + + /// A `KIND_BACKDROP_BLUR`'s composite, from the blur painted before it. + fn backdrop(&mut self, i: &Instance, r: [u32; 4], clip: &Clip) { + let Some(at) = self.bins.blurs.iter().position(|(n, _)| *n == self.n) else { return }; + let Some(Some(b)) = self.blurred.get(at) else { return }; + for y in r[1]..r[3] { + for x in r[0]..r[2] { + let c = backdrop::composite(b, i, clip, [x as f32 + 0.5, y as f32 + 0.5]); + if c != [0.0; 4] { self.put(x, y, c); } + } + } + } + + /// A `KIND_IMAGE` from its image page. + fn image(&mut self, i: &Instance, r: [u32; 4], clip: &Clip) { + let Some(&page) = self.scene.images.get(i.params[0] as usize) else { return }; + let segs = self.segments(r, None, clip); + let mut k = 0; + for y in r[1]..r[3] { + let py = y as f32 + 0.5; + while segs[k].y1 <= y { k += 1; } + let (whole, vis) = (segs[k].whole, segs[k].vis); + for x in vis.iter().flat_map(|(a, b)| a..b) { + let p = [x as f32 + 0.5, py]; + let c = shade::image(i, &page, p); + if c == [0.0; 4] { continue; } + let a = if p[0] >= whole.0 && p[0] <= whole.1 { 1.0 } else { clip.alpha(p) }; + self.stats.shaded_px += 1; + self.put(x, y, c.map(|v| v * a)); + } + } + self.segs = segs; + } +} + +/// `hole_alpha`: a layer composite's round hole (`El::cutout_circle`). +fn hole_alpha(p: [f32; 2], h: [f32; 4]) -> f32 { + if h[3] <= 0.0 { return 1.0; } + let (dx, dy) = (p[0] - h[0], p[1] - h[1]); + (((dx * dx + dy * dy).sqrt() - (h[2] + h[3]) * 0.5) / (h[3] - h[2]).max(1.0) + 0.5).clamp(0.0, 1.0) +} diff --git a/app/vendor/rune/crates/rune/src/render/cpu_boot/raster/glyph.rs b/app/vendor/rune/crates/rune/src/render/cpu_boot/raster/glyph.rs new file mode 100644 index 0000000..a40bd60 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/render/cpu_boot/raster/glyph.rs @@ -0,0 +1,166 @@ +use super::Painter; +use super::super::shade::Clip; +use crate::render::Instance; +use crate::render::instance::shader_consts; +use crate::render::variant::LCD_MEAN_EPSILON; + +/// `pow(cov / 255, e)` for each coverage byte, per exponent: Skia's text gamma keys a handful of +/// exponents by the text's luminance, and a frame's text alternates between them (syntax colours), +/// so the last `POW_TABLES` stay. +#[derive(Default)] +pub(super) struct Pow { + tables: Vec<(u32, [f32; 256])>, +} + +const POW_TABLES: usize = 16; + +impl Pow { + fn index(&mut self, e: f32) -> usize { + let bits = e.to_bits(); + let at = match self.tables.iter().position(|(k, _)| *k == bits) { + Some(at) => at, + None => { + if self.tables.len() == POW_TABLES { self.tables.remove(0); } + self.tables.push((bits, std::array::from_fn(|c| if e == 1.0 { c as f32 / 255.0 } else { (c as f32 / 255.0).powf(e) }))); + self.tables.len() - 1 + } + }; + at + } +} + +impl Painter<'_, '_> { + /// A `KIND_GLYPH` from its atlas mask: whole texels at rest, bilinear when its quad is + /// scaled (`uv.z > 0`) or turned (`params.x`), a subpixel mask's three texels a pixel + /// (`radii.x`). + pub(super) fn glyph(&mut self, i: &Instance, r: [u32; 4], clip: &Clip) { + if i.radii[3] > 0.0 { return self.outline(i, r, clip); } + let Some(&mask) = self.scene.glyph_pages.get(i.params[2] as usize) else { return }; + let side = crate::text::ATLAS_SIZE as i32; + let load = |x: i32, y: i32| -> u8 { if x < 0 || y < 0 || x >= side || y >= side { 0 } else { mask[(y * side + x) as usize] } }; + let e = i.params[3]; + let turn = i.params[0]; + let rotated = turn != 0.0; + let filtered = i.uv[2] > 0.0 || rotated; + let lcd = i.radii[0] > shader_consts::FLAG_ON_THRESHOLD && !filtered; + // Subpixel text blends by channel over the window; inside layers it draws grayscale. + let by_channel = lcd && self.scene.lcd && self.depth == 0; + let (sin, cos) = turn.sin_cos(); + let centre = [i.rect[0] + i.rect[2] * 0.5, i.rect[1] + i.rect[3] * 0.5]; + let span = if i.uv[2] > 0.0 { [i.uv[2], i.uv[3]] } else { [i.rect[2], i.rect[3]] }; + let table = self.pow.index(e); + let mut count = 0; + let segs = self.segments(r, None, clip); + let mut k = 0; + for y in r[1]..r[3] { + let py = y as f32 + 0.5; + while segs[k].y1 <= y { k += 1; } + let (whole, vis) = (segs[k].whole, segs[k].vis); + let ty = i.uv[1] as i32 + (py - i.rect[1]).floor() as i32; + if !lcd && !filtered { + // A mask at rest: one texel a pixel, a row of them per row. + if ty < 0 || ty >= side { continue; } + let row = &mask[(ty * side) as usize..((ty + 1) * side) as usize]; + let t0 = i.uv[0] as i32 + (r[0] as f32 + 0.5 - i.rect[0]).floor() as i32 - r[0] as i32; + for x in vis.iter().flat_map(|(a, b)| a..b) { + let Some(&v) = row.get((t0 + x as i32).max(0) as usize).filter(|_| t0 + x as i32 >= 0) else { continue }; + if v == 0 { continue; } + count += 1; + let px = x as f32 + 0.5; + let a = if px >= whole.0 && px <= whole.1 { 1.0 } else { clip.alpha([px, py]) }; + let cov = self.pow.tables[table].1[v as usize]; + self.put(x, y, i.fill.map(|f| f * cov * a)); + } + continue; + } + for x in vis.iter().flat_map(|(a, b)| a..b) { + let px = x as f32 + 0.5; + let alpha = || if px >= whole.0 && px <= whole.1 { 1.0 } else { clip.alpha([px, py]) }; + if lcd { + let tx = i.uv[0] as i32 + (px - i.rect[0]).floor() as i32 * shader_consts::OUTLINE_SUBPIXEL_STRIDE as i32; + let c3 = [load(tx, ty), load(tx + 1, ty), load(tx + 2, ty)]; + if c3 == [0; 3] { continue; } + count += 1; + let a = alpha(); + let mean = ((c3[0] as f32 + c3[1] as f32 + c3[2] as f32) / shader_consts::OUTLINE_SUBPIXEL_STRIDE / 255.0).powf(e); + if by_channel { + if mean < LCD_MEAN_EPSILON { continue; } + let kc = c3.map(|v| self.pow.tables[table].1[v as usize]); + let f = i.fill.map(|v| v * a); + self.surface.blend_lcd(x, y, [f[0] * kc[0], f[1] * kc[1], f[2] * kc[2], f[3] * mean], kc.map(|v| f[3] * v)); + } else { + self.put(x, y, i.fill.map(|v| v * mean * a)); + } + continue; + } + let cov = if filtered { + // A turned icon samples at its unturned point; outside its quad is outside. + let p = if rotated { + let d = [px - centre[0], py - centre[1]]; + [centre[0] + cos * d[0] + sin * d[1], centre[1] - sin * d[0] + cos * d[1]] + } else { [px, py] }; + if rotated && (p[0] < i.rect[0] || p[1] < i.rect[1] || p[0] >= i.rect[0] + i.rect[2] || p[1] >= i.rect[1] + i.rect[3]) { continue; } + let local = [(p[0] - i.rect[0]) * span[0] / i.rect[2] - 0.5, (p[1] - i.rect[1]) * span[1] / i.rect[3] - 0.5]; + let base = [local[0].floor(), local[1].floor()]; + let f = [local[0] - base[0], local[1] - base[1]]; + let t = [(i.uv[0] + base[0]) as i32, (i.uv[1] + base[1]) as i32]; + let s = |dx: i32, dy: i32| load(t[0] + dx, t[1] + dy) as f32 / 255.0; + let mix = |a: f32, b: f32, t: f32| a * (1.0 - t) + b * t; + let c = mix(mix(s(0, 0), s(1, 0), f[0]), mix(s(0, 1), s(1, 1), f[0]), f[1]); + if c <= 0.0 { continue; } + if e == 1.0 { c } else { c.powf(e) } + } else { + let v = load(i.uv[0] as i32 + (px - i.rect[0]).floor() as i32, ty); + if v == 0 { continue; } + self.pow.tables[table].1[v as usize] + }; + count += 1; + let a = alpha(); + self.put(x, y, i.fill.map(|v| v * cov * a)); + } + } + self.stats.glyph_px += count; + self.segs = segs; + } + + /// A glyph drawn from its outline (text whose scale moves): outline.wgsl's `outline_glyph`, + /// Windfoil's box (coverage 0), or one box about each subpixel (2), blended by channel + /// over the window where the frame's text is subpixel. + fn outline(&mut self, i: &Instance, r: [u32; 4], clip: &Clip) { + let Some(store) = self.scene.outlines else { return }; + let z = i.radii[3]; + let (rec, hint, radius, mode) = (i.border[0] as u32, i.border[1] as u32, i.border[2], (i.border[3] + 0.5) as u32); + let hw = 0.5 / z; + let across = if mode == shader_consts::OUTLINE_MODE_SUBPIXEL_MASK { shader_consts::OUTLINE_SUBPIXEL_STRIDE } else { 1.0 }; + let e = i.params[3]; + let rgb = mode == shader_consts::OUTLINE_MODE_RGB && self.scene.lcd && self.depth == 0; + let cover = |local: [f32; 2]| crate::text::outline::coverage(store, rec, hint, local, i.radii[2], radius, hw); + let segs = self.segments(r, None, clip); + let mut k = 0; + for y in r[1]..r[3] { + let py = y as f32 + 0.5; + while segs[k].y1 <= y { k += 1; } + let (whole, vis) = (segs[k].whole, segs[k].vis); + for x in vis.iter().flat_map(|(a, b)| a..b) { + let px = x as f32 + 0.5; + let local = [(px - i.radii[0]) / across / z, (i.radii[1] - py) / z]; + let a = if px >= whole.0 && px <= whole.1 { 1.0 } else { clip.alpha([px, py]) }; + if rgb { + let third = 2.0 * hw / shader_consts::OUTLINE_SUBPIXEL_STRIDE; + let c3 = [cover([local[0] - third, local[1]]), cover(local), cover([local[0] + third, local[1]])]; + let mean = ((c3[0] + c3[1] + c3[2]) / shader_consts::OUTLINE_SUBPIXEL_STRIDE).powf(e); + if mean < LCD_MEAN_EPSILON { continue; } + let kc = c3.map(|v| v.powf(e)); + let f = i.fill.map(|v| v * a); + self.surface.blend_lcd(x, y, [f[0] * kc[0], f[1] * kc[1], f[2] * kc[2], f[3] * mean], kc.map(|v| f[3] * v)); + continue; + } + let cov = cover(local); + if cov <= 0.0 { continue; } + self.stats.glyph_px += 1; + self.put(x, y, i.fill.map(|v| v * cov.powf(e) * a)); + } + } + self.segs = segs; + } +} diff --git a/app/vendor/rune/crates/rune/src/render/cpu_boot/raster/segments.rs b/app/vendor/rune/crates/rune/src/render/cpu_boot/raster/segments.rs new file mode 100644 index 0000000..fe1319f --- /dev/null +++ b/app/vendor/rune/crates/rune/src/render/cpu_boot/raster/segments.rs @@ -0,0 +1,145 @@ +use super::Painter; +use super::super::bin::{EMPTY, Solid, TOP, clip_span, intersect, opaque_box}; +use super::super::shade::Clip; + +#[derive(Clone, Copy)] +pub(super) struct Occluder { + n: u32, + /// The layer it draws into (`Bins::within`): it stands in only for what's under it there. + within: u32, + solid: Solid, + clip: Clip, + r: [u32; 4], +} + +/// The parts of a row left to draw: at most `RANGES` runs of pixels `[a, b)`. +#[derive(Clone, Copy)] +pub(super) struct Ranges { + runs: [(u32, u32); RANGES], + len: usize, +} + +const RANGES: usize = 8; + +impl Ranges { + pub(super) fn iter(&self) -> impl Iterator<Item = (u32, u32)> + '_ { self.runs[..self.len].iter().copied() } + + /// Takes pixels `[a, b)` out. Past `RANGES` runs it leaves them in: drawing under the box + /// too is only wasted work. + fn cut(&mut self, a: u32, b: u32) { + let mut next = Ranges { runs: [(0, 0); RANGES], len: 0 }; + for (x0, x1) in self.iter() { + for piece in [(x0, x1.min(a)), (x0.max(b), x1)] { + if piece.1 <= piece.0 { continue; } + if next.len == RANGES { return; } + next.runs[next.len] = piece; + next.len += 1; + } + } + *self = next; + } +} + +/// A run of rows ending before `y1` of one instance in one tile, and what holds on each of them: the +/// pixels its interior paints in one colour (`[a, b)`), where its clip is whole, and the runs no +/// later opaque box covers. +#[derive(Clone, Copy)] +pub(super) struct Segment { + pub(super) y1: u32, + pub(super) solid: (u32, u32), + pub(super) whole: (f32, f32), + pub(super) vis: Ranges, +} + +/// The first row (by index) whose centre is at least `v`, and the first past those at most `v`. +fn row_from(v: f32) -> u32 { (v - 0.5).ceil().max(0.0) as u32 } +fn row_past(v: f32) -> u32 { ((v - 0.5).floor() + 1.0).max(0.0) as u32 } + +/// Where a `Solid`'s span changes: its top and bottom `inset`, and its corner bands. +fn solid_breaks(s: &Solid, out: &mut Vec<u32>) { + let [_, y0, _, y1] = s.edges; + let (top, bottom) = s.bands(); + out.extend([row_from(y0 + s.inset), row_from(y0 + top), row_past(y1 - bottom), row_past(y1 - s.inset)]); +} + +/// Where a clip's whole span changes. +fn clip_breaks(c: &Clip, out: &mut Vec<u32>) { + let inset = c.inset(); + out.extend([row_from(c.rect[1] + inset[1]), row_past(c.rect[3] - inset[3])]); + if let Some(radii) = c.radii { + let (top, bottom) = Solid { edges: c.rect, radii, inset: 0.5 }.bands(); + out.extend([row_from(c.rect[1] + top), row_past(c.rect[3] - bottom)]); + } +} + +/// Pixel indices `[ia, ib)` whose centres lie in `[a, b]`, within `x0..x1`. +pub(super) fn centres(span: (f32, f32), x0: u32, x1: u32) -> (u32, u32) { + if span.0 > span.1 { return (x1, x1); } + let a = (span.0 - 0.5).ceil().clamp(x0 as f32, x1 as f32) as u32; + let b = ((span.1 - 0.5).floor() + 1.0).clamp(a as f32, x1 as f32) as u32; + (a, b) +} + +impl Painter<'_, '_> { + /// The occluders among `list` (a tile's instances in one phase), in painter order. A box + /// past a backdrop blur's record never stands in for what that blur reads: phases end at + /// each record, and occluders come from this phase only. + pub(super) fn occluders(&mut self, list: &[u32]) { + self.occ.clear(); + for &n in list { + let within = self.bins.within[n as usize]; + // Inside a PlusLighter layer every primitive adds to what came before it; an opaque + // box never hides an earlier sibling. + if within != TOP && self.bins.layers[within as usize].additive { continue; } + let i = &self.scene.instances[n as usize]; + let Some(solid) = opaque_box(i) else { continue }; + let (b, tile) = (self.bins.bounds[n as usize], self.tile); + let r = [(b[0] as u32).max(tile[0]), (b[1] as u32).max(tile[1]), (b[2] as u32).min(tile[2]), (b[3] as u32).min(tile[3])]; + if r[2] > r[0] && r[3] > r[1] { self.occ.push(Occluder { n, within, solid, clip: Clip::of_stops(i, self.scene.fade_stops), r }); } + } + } + + /// Splits rows `r[1]..r[3]` of `r` where anything this instance's drawing depends on changes + /// (its interior's corner bands, its clip's, a later opaque box's), and for each run of rows + /// takes what holds on its first and last row: those regions are convex, so it holds on every + /// row between. A pixel outside these (smaller than exact) regions is shaded one by one, + /// which gives it the same bytes. + pub(super) fn segments(&mut self, r: [u32; 4], solid: Option<Solid>, clip: &Clip) -> Vec<Segment> { + let mut breaks = std::mem::take(&mut self.breaks); + breaks.clear(); + breaks.extend([r[1], r[3]]); + if let Some(s) = &solid { solid_breaks(s, &mut breaks); } + clip_breaks(clip, &mut breaks); + // Occluders are in painter order: only those after this instance count. + let later = self.occ.partition_point(|o| o.n <= self.n); + let within = self.bins.within[self.n as usize]; + let occ: Vec<&Occluder> = self.occ[later..].iter().filter(|o| o.within == within && o.r[1] < r[3] && o.r[3] > r[1] && o.r[0] < r[2] && o.r[2] > r[0]).collect(); + for o in &occ { + breaks.extend([o.r[1], o.r[3]]); + solid_breaks(&o.solid, &mut breaks); + clip_breaks(&o.clip, &mut breaks); + } + breaks.retain(|&b| b >= r[1] && b <= r[3]); + breaks.sort_unstable(); + breaks.dedup(); + let mut out = std::mem::take(&mut self.segs); + out.clear(); + for w in breaks.windows(2) { + let (ya, yb) = (w[0], w[1]); + let (pa, pb) = (ya as f32 + 0.5, (yb - 1) as f32 + 0.5); + let whole = intersect(clip_span(clip, pa), clip_span(clip, pb)); + let inside = solid.map_or(EMPTY, |s| intersect(intersect(s.span(pa), s.span(pb)), whole)); + let mut vis = Ranges { runs: [(0, 0); RANGES], len: 1 }; + vis.runs[0] = (r[0], r[2]); + for o in occ.iter().filter(|o| o.r[1] <= ya && o.r[3] >= yb) { + let covered = intersect(intersect(o.solid.span(pa), o.solid.span(pb)), intersect(clip_span(&o.clip, pa), clip_span(&o.clip, pb))); + let (ca, cb) = centres(covered, o.r[0], o.r[2]); + if cb > ca { vis.cut(ca, cb); } + if vis.len == 0 { break; } + } + out.push(Segment { y1: yb, solid: centres(inside, r[0], r[2]), whole, vis }); + } + self.breaks = breaks; + out + } +} diff --git a/app/vendor/rune/crates/rune/src/render/cpu_boot/record.rs b/app/vendor/rune/crates/rune/src/render/cpu_boot/record.rs new file mode 100644 index 0000000..f39f2db --- /dev/null +++ b/app/vendor/rune/crates/rune/src/render/cpu_boot/record.rs @@ -0,0 +1,103 @@ +//! A frame's draw data as bytes (`--cpu-boot`): what `paint` reads, so a tool can paint it again +//! away from the app. Little-endian: `RCB1`, width, height, clear (4 × f32), flags (bit 0 lcd), +//! the instance count and instances, the glyph page count and pages (`ATLAS_SIZE`² bytes each), +//! then the image page count and each page's width, height and RGBA bytes. + +use super::{Image, Scene}; +use crate::render::Instance; +use crate::text::ATLAS_SIZE; + +const MAGIC: &[u8; 4] = b"RCB1"; + +/// A decoded frame, owning what its [`Scene`] borrows. +pub struct Recording { + instances: Vec<Instance>, + glyph_pages: Vec<Vec<u8>>, + images: Vec<(u32, Vec<u8>)>, + size: (u32, u32), + clear: [f32; 4], + lcd: bool, +} + +/// `scene` as bytes. +pub fn encode(scene: &Scene<'_>) -> Vec<u8> { + let mut out = Vec::new(); + out.extend_from_slice(MAGIC); + for v in [scene.size.0, scene.size.1] { out.extend_from_slice(&v.to_le_bytes()); } + for c in scene.clear { out.extend_from_slice(&c.to_le_bytes()); } + out.extend_from_slice(&u32::from(scene.lcd).to_le_bytes()); + out.extend_from_slice(&(scene.instances.len() as u32).to_le_bytes()); + out.extend_from_slice(bytemuck::cast_slice(scene.instances)); + out.extend_from_slice(&(scene.glyph_pages.len() as u32).to_le_bytes()); + for page in &scene.glyph_pages { out.extend_from_slice(page); } + out.extend_from_slice(&(scene.images.len() as u32).to_le_bytes()); + for image in &scene.images { + let height = image.data.len() as u32 / (image.width * 4).max(1); + for v in [image.width, height] { out.extend_from_slice(&v.to_le_bytes()); } + out.extend_from_slice(image.data); + } + out +} + +impl Recording { + pub fn decode(bytes: &[u8]) -> Option<Recording> { + let mut r = Reader { bytes, at: 0 }; + if r.take(4)? != MAGIC { return None; } + let size = (r.u32()?, r.u32()?); + let clear = [f32::from_bits(r.u32()?), f32::from_bits(r.u32()?), f32::from_bits(r.u32()?), f32::from_bits(r.u32()?)]; + let lcd = r.u32()? & 1 != 0; + let count = r.u32()? as usize; + let instances = bytemuck::pod_collect_to_vec(r.take(count * std::mem::size_of::<Instance>())?); + let pages = r.u32()? as usize; + let side = (ATLAS_SIZE * ATLAS_SIZE) as usize; + let glyph_pages = (0..pages).map(|_| r.take(side).map(<[u8]>::to_vec)).collect::<Option<Vec<_>>>()?; + let count = r.u32()? as usize; + let mut images = Vec::with_capacity(count); + for _ in 0..count { + let (w, h) = (r.u32()?, r.u32()?); + images.push((w, r.take((w * h * 4) as usize)?.to_vec())); + } + Some(Recording { instances, glyph_pages, images, size, clear, lcd }) + } + + /// The frame, ready for `paint`. + pub fn scene(&self) -> Scene<'_> { + Scene { + instances: &self.instances, + glyph_pages: self.glyph_pages.iter().map(Vec::as_slice).collect(), + outlines: None, + images: self.images.iter().map(|(width, data)| Image { width: *width, data, dirty: None }).collect(), + size: self.size, + clear: self.clear, + lcd: self.lcd, + srgb_blend: true, + native_surfaces: false, + compositor: false, + smoothing: None, + atlas_resets: 0, + half: super::HalfRounding::default(), + fade_stops: [0.0; 2], + } + } + + pub fn instances(&self) -> &[Instance] { &self.instances } + + pub fn size(&self) -> (u32, u32) { self.size } +} + +struct Reader<'b> { + bytes: &'b [u8], + at: usize, +} + +impl<'b> Reader<'b> { + fn take(&mut self, n: usize) -> Option<&'b [u8]> { + let s = self.bytes.get(self.at..self.at.checked_add(n)?)?; + self.at += n; + Some(s) + } + + fn u32(&mut self) -> Option<u32> { + Some(u32::from_le_bytes(self.take(4)?.try_into().ok()?)) + } +} diff --git a/app/vendor/rune/crates/rune/src/render/cpu_boot/scroll.rs b/app/vendor/rune/crates/rune/src/render/cpu_boot/scroll.rs new file mode 100644 index 0000000..2590d48 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/render/cpu_boot/scroll.rs @@ -0,0 +1,230 @@ +//! Scrolling by moving pixels: when a frame's content moved by a whole number of pixels inside a +//! clip that stayed put (a scroll view), the rows of the buffer that hold it are moved by that +//! much, and only the tiles that came out different repaint (the strip that scrolled in, and +//! anything that didn't move with the content). +//! +//! A tile counts as moved only if what draws there is, instance for instance and in order, +//! what drew `dy` rows away last frame: each the same bytes but for its rect's y moved by `dy` +//! (and its clip's, or a clip that stayed put and is whole over both places), or the same bytes +//! where it paints one colour over both places. Every position the shading reads is relative to +//! the instance's rect, so those draw the same pixels `dy` rows away. + +use std::sync::atomic::{AtomicBool, AtomicU32, Ordering}; + +use super::Scene; +use super::bin::{Bins, Show, Solid, TILE_H, TILE_W, covers, cut, interior}; +use super::shade::{Clip, has_sides}; +use crate::render::instance::shader_consts; +use crate::render::{INSTANCE_WORDS, Instance, Kind, word}; + +/// What the last frame drew, kept for the next frame's comparison. +pub(super) struct Prev { + pub instances: Vec<Instance>, + pub bins: Bins, +} + +/// Rows `rect` of the new frame come from `dy` rows up of the old buffer (down when negative); +/// `clean[t]` says tile `t` needs nothing more. +pub(super) struct Shift { + pub rect: [u32; 4], + pub dy: i32, + pub clean: Vec<bool>, +} + +fn words(i: &Instance) -> &[u32; INSTANCE_WORDS] { bytemuck::cast_ref(i) } + +/// An instance's bytes with what moves with it left out. +fn key(i: &Instance) -> u64 { + let mut h = 0u64; + for (k, &w) in words(i).iter().enumerate() { + if k == word::RECT_Y || k == word::CLIP_Y0 || k == word::CLIP_Y1 { continue; } + h = (h.rotate_left(5) ^ u64::from(w)).wrapping_mul(0x517c_c1b7_2722_0a95); + } + h +} + +/// Kinds whose every position is relative to their rect (segments and triangles hold absolute +/// points, so they never count as moved). +fn movable(kind: Option<Kind>) -> bool { + match kind { + Some( + Kind::Rect | Kind::Shadow | Kind::Glyph | Kind::Inset | Kind::Gradient + | Kind::Image | Kind::Layer | Kind::LayerEnd | Kind::Dashed | Kind::Radial, + ) => true, + Some(Kind::Segment | Kind::Triangle | Kind::Effect | Kind::BackdropBlur) | None => false, + } +} + +/// The shift that explains this frame, if one does: the whole-pixel `dy` most of the moved +/// instances agree on, inside the clip they share. +pub(super) fn plan(prev: &Prev, scene: &Scene<'_>, bins: &Bins, exec: &dyn super::raster::Exec) -> Option<Shift> { + let old = &prev.instances; + let voter = |i: &Instance| matches!(i.kind(), Some(Kind::Glyph | Kind::Rect)); + // The old voters by key, sorted: those with one key are a run. + let mut by_key: Vec<(u64, u32)> = old.iter().enumerate().filter(|(_, i)| voter(i)).map(|(m, i)| (key(i), m as u32)).collect(); + by_key.sort_unstable(); + // Votes for (dy, the clip the content stayed inside); a frame has a handful of each. + let mut votes: Vec<((i32, [u32; 4]), u32)> = Vec::new(); + for i in scene.instances.iter().filter(|i| voter(i)) { + let k = key(i); + let at = by_key.partition_point(|e| e.0 < k); + // One vote each, for the smallest move that explains it: repeated glyphs (a column of + // the same letter in code) match other lines too, and staying put (0) beats them. + let dy = by_key[at..].iter().take_while(|e| e.0 == k).map(|e| &old[e.1 as usize]).filter(|o| i.clip == o.clip).map(|o| i.rect[1] - o.rect[1]) + .filter(|dy| dy.fract() == 0.0 && dy.abs() < scene.size.1 as f32).min_by(|a, b| a.abs().total_cmp(&b.abs())); + let Some(dy) = dy else { continue }; + let vote = (dy as i32, i.clip.map(f32::to_bits)); + match votes.iter_mut().find(|v| v.0 == vote) { + Some(v) => v.1 += 1, + None => votes.push((vote, 1)), + } + } + // The move most agree on, if more in its clip moved by it than stayed put. + let &((dy, clip_bits), count) = votes.iter().filter(|v| v.0.0 != 0).max_by_key(|v| v.1)?; + if count < 8 || votes.iter().any(|v| v.0 == (0, clip_bits) && v.1 >= count) { return None; } + let clip = clip_bits.map(f32::from_bits); + // Rows whose centres are where the clip is whole, now and `dy` rows back. + let c = Clip::of(&Instance { clip, ..bytemuck::Zeroable::zeroed() }); + let inset = c.inset(); + let (w, h) = (scene.size.0 as f32, scene.size.1 as f32); + let whole = [(clip[0] + inset[0]).max(0.0), (clip[1] + inset[1]).max(0.0), (clip[2] - inset[2]).min(w), (clip[3] - inset[3]).min(h)]; + let y0 = whole[1].max(whole[1] + dy as f32); + let y1 = whole[3].min(whole[3] + dy as f32); + let rect = [(whole[0] - 0.5).ceil().max(0.0) as u32, (y0 - 0.5).ceil().max(0.0) as u32, ((whole[2] - 0.5).floor() + 1.0).max(0.0) as u32, ((y1 - 0.5).floor() + 1.0).max(0.0) as u32]; + if rect[2] <= rect[0] || rect[3] <= rect[1] { return None; } + // A backdrop blur's pixels never move: its record is in place in the old tiles that held it, + // so no tile drawn from them counts as moved. + if prev.bins.cols != bins.cols { return None; } + // Any tile may have moved whole: instance for instance is the test, not the rect. Tile rows + // go to threads. + let clean: Vec<AtomicBool> = (0..bins.tile_count()).map(|_| AtomicBool::new(false)).collect(); + let next = AtomicU32::new(0); + exec.run(&|| loop { + let ty = next.fetch_add(1, Ordering::Relaxed); + if ty >= bins.rows { break; } + for tx in 0..bins.cols { + let t = (ty * bins.cols + tx) as usize; + let r = [tx * TILE_W, ty * TILE_H, ((tx + 1) * TILE_W).min(scene.size.0), ((ty + 1) * TILE_H).min(scene.size.1)]; + if !bins.quiet[t] && tile_moved(prev, scene, bins, t, r, dy) { clean[t].store(true, Ordering::Relaxed); } + } + }); + Some(Shift { rect, dy, clean: clean.into_iter().map(AtomicBool::into_inner).collect() }) +} + +/// Whether tile `t` (pixels `r`) draws what the old frame drew `dy` rows back. +fn tile_moved(prev: &Prev, scene: &Scene<'_>, bins: &Bins, t: usize, r: [u32; 4], dy: i32) -> bool { + let back = [r[0] as i32, r[1] as i32 - dy, r[2] as i32, r[3] as i32 - dy]; + if back[1] < 0 || back[3] > scene.size.1 as i32 { return false; } + let ob = &prev.bins; + // What drew over the old rows: the old tiles that held them (one, or two when `dy` isn't a + // whole number of tiles), each in painter order, merged, those reaching the rows kept. + let (tx, oty) = (r[0] / TILE_W, back[1] as u32 / TILE_H); + let upper = ob.tile((oty * ob.cols + tx) as usize); + let lower = if (back[3] as u32).div_ceil(TILE_H) > oty + 1 && oty + 1 < ob.rows { ob.tile(((oty + 1) * ob.cols + tx) as usize) } else { &[] }; + let reaches = |m: u32| { + let b = ob.bounds[m as usize]; + b[0] < back[2] && b[2] > back[0] && b[1] < back[3] && b[3] > back[1] + }; + let (mut a, mut b) = (0, 0); + let mut olds = std::iter::from_fn(|| loop { + let m = match (upper.get(a), lower.get(b)) { + (Some(&x), Some(&y)) if x == y => { a += 1; b += 1; x } + (Some(&x), Some(&y)) if x < y => { a += 1; x } + (_, Some(&y)) => { b += 1; y } + (Some(&x), None) => { a += 1; x } + (None, None) => return None, + }; + if reaches(m) { return Some(m); } + }); + let both = [r[0] as f32, r[1].min(back[1] as u32) as f32, r[2] as f32, r[3].max(back[3] as u32) as f32]; + let tile = [r[0] as i32, r[1] as i32, r[2] as i32, r[3] as i32]; + bins.tile(t).iter().all(|&n| { + olds.next().is_some_and(|m| { + let new_r = cut(bins.bounds[n as usize], tile); + let old_r = cut(prev.bins.bounds[m as usize], back); + new_r == [old_r[0], old_r[1] + dy, old_r[2], old_r[3] + dy] && same(scene, bins, prev, n, m, dy, both) + }) + }) && olds.next().is_none() +} + +/// Whether new instance `n` draws over the tile what old instance `m` drew `dy` rows back: +/// moved with the content, or one colour over `both` (the tile and its old place together). +fn same(scene: &Scene<'_>, bins: &Bins, prev: &Prev, n: u32, m: u32, dy: i32, both: [f32; 4]) -> bool { + let (a, b) = (&scene.instances[n as usize], &prev.instances[m as usize]); + let (wa, wb) = (words(a), words(b)); + let kind = a.kind(); + if !movable(kind) { return false; } + let marker = matches!(kind, Some(Kind::Layer | Kind::LayerEnd)); + if wa == wb { + // In place: it must look the same everywhere it reaches over both. + return if marker { layer_same(bins, prev, n, m, 0) && layer_covers(scene, bins, n, both) } else { flat_over(a, both) || rows_alike(a, both) }; + } + let rest = (0..INSTANCE_WORDS).all(|k| k == word::RECT_Y || k == word::CLIP_Y0 || k == word::CLIP_Y1 || wa[k] == wb[k]); + if !rest || a.rect[1] != b.rect[1] + dy as f32 { return false; } + // Its clip moved with it, or stayed put and cuts every row over both places alike. + let clip_moved = a.clip[1] == b.clip[1] + dy as f32 && a.clip[3] == b.clip[3] + dy as f32; + let clip_kept = a.clip[1] == b.clip[1] && a.clip[3] == b.clip[3] && clip_rows_alike(&Clip::of(a), both); + if !clip_moved && !clip_kept { return false; } + !marker || layer_same(bins, prev, n, m, dy) +} + +/// Whether the layer plans of markers `n` (new) and `m` (old) are the same `dy` rows apart. +fn layer_same(bins: &Bins, prev: &Prev, n: u32, m: u32, dy: i32) -> bool { + let (Some(&p), Some(&q)) = (bins.scope.get(&n), prev.bins.scope.get(&m)) else { return false }; + let (l, o) = (&bins.layers[p as usize], &prev.bins.layers[q as usize]); + l.show == o.show && l.additive == o.additive && l.hole == o.hole + && l.bounds == [o.bounds[0], o.bounds[1] + dy, o.bounds[2], o.bounds[3] + dy] +} + +/// Whether a layer in place composites the same over `both`: its target covers them, with no +/// hole and its clip whole there. +fn layer_covers(scene: &Scene<'_>, bins: &Bins, n: u32, both: [f32; 4]) -> bool { + let Some(&p) = bins.scope.get(&n) else { return false }; + let l = &bins.layers[p as usize]; + if l.show != Show::Render { return true; } + let b = l.bounds.map(|v| v as f32); + let begin = &scene.instances[l.begin as usize]; + l.hole[3] <= 0.0 && b[1] <= both[1] && b[3] >= both[3] && clip_rows_alike(&Clip::of(begin), both) +} + +/// Whether an instance in place draws every row of `r` alike: a box or a shadow whose rows +/// there are all in its straight middle, far enough from its top and bottom edges and corners +/// that what it draws depends on x alone, inside a clip that cuts them alike. +fn rows_alike(i: &Instance, r: [f32; 4]) -> bool { + let (top, bottom) = (r[1] + 0.5, r[3] - 0.5); + let middle = |margin: f32| top >= i.rect[1] + margin && bottom <= i.rect[1] + i.rect[3] - margin; + let reach = i.radii.iter().fold(0.0f32, |m, v| m.max(v.abs())); + let alike = match i.kind() { + // `sd_rounded` there is `|x| - half width`, or deep inside past the border's reach. + Some(Kind::Rect) => !has_sides(i) && middle(reach + 4.0 * (i.params[0].max(0.0) + i.params[2].max(shader_consts::SOFT_MIN)) + 4.0), + // `shadow_row`'s samples and its interior test are the same on every row there. + Some(Kind::Shadow) => i.uv[2] <= 0.0 && { + let half = [i.rect[2] * 0.5, i.rect[3] * 0.5]; + let corner = i.radii[0].abs().min(half[0].min(half[1])); + middle(corner + shader_consts::SHADOW_INSIDE_SIGMA * i.params[2].max(shader_consts::SHADOW_MIN_SIGMA) + 1.0) + }, + Some( + Kind::Glyph | Kind::Inset | Kind::Gradient | Kind::Segment | Kind::Triangle + | Kind::Image | Kind::Layer | Kind::LayerEnd | Kind::Dashed | Kind::Radial + | Kind::Effect | Kind::BackdropBlur, + ) | None => false, + }; + alike && clip_rows_alike(&Clip::of(i), r) +} + +/// Whether `clip` cuts every row of `r` alike: they're all where its top and bottom edges, their +/// fades and its corners don't reach. +fn clip_rows_alike(c: &Clip, r: [f32; 4]) -> bool { + let inset = c.inset(); + let (mut top, mut bottom) = (inset[1], inset[3]); + if let Some(radii) = c.radii { + let (t, b) = Solid { edges: c.rect, radii, inset: 0.5 }.bands(); + (top, bottom) = (top.max(t + 1.0), bottom.max(b + 1.0)); + } + r[1] + 0.5 >= c.rect[1] + top && r[3] - 0.5 <= c.rect[3] - bottom +} + +/// Whether a box in place paints one colour over all of `r`. +fn flat_over(i: &Instance, r: [f32; 4]) -> bool { + i.kind() == Some(Kind::Rect) && interior(i).is_some_and(|s| covers(Some(&s), &Clip::of(i), r)) +} diff --git a/app/vendor/rune/crates/rune/src/render/cpu_boot/shade.rs b/app/vendor/rune/crates/rune/src/render/cpu_boot/shade.rs new file mode 100644 index 0000000..e96e19d --- /dev/null +++ b/app/vendor/rune/crates/rune/src/render/cpu_boot/shade.rs @@ -0,0 +1,578 @@ +//! shader.wgsl and clip.wgsl on the CPU, function for function in f32: one pixel's premultiplied +//! colour for each instance kind `cpu_boot` draws. The names are the shader's, so a change there +//! has one obvious place to land here. + +use crate::render::instance::shader_consts; +use crate::render::{CONTINUOUS_K, Instance, Kind, unpack_clip_radii}; + +fn clamp01(x: f32) -> f32 { x.clamp(0.0, 1.0) } + +fn mix4(a: [f32; 4], b: [f32; 4], t: f32) -> [f32; 4] { std::array::from_fn(|c| a[c] * (1.0 - t) + b[c] * t) } + +fn scale4(a: [f32; 4], k: f32) -> [f32; 4] { a.map(|v| v * k) } + +/// `sd_continuous`. +fn sd_continuous(p: [f32; 2], half: [f32; 2], r: f32) -> f32 { + let [c0, c1, c2, c3] = shader_consts::CONTINUOUS_POLY; + let e = CONTINUOUS_K * r; + let q = [half[0] - p[0].abs(), half[1] - p[1].abs()]; + let v = [e - q[0], e - q[1]]; + if v[0] <= 0.0 || v[1] <= 0.0 { return (-q[0]).max(-q[1]); } + let u = v[1].atan2(v[0]) * (4.0 / shader_consts::CONTINUOUS_PI) - 1.0; + let u2 = u * u; + (v[0] * v[0] + v[1] * v[1]).sqrt() - e * (c0 + u2 * (c1 + u2 * (c2 + c3 * u2))) +} + +/// `sd_rounded`: radii top-left, top-right, bottom-right, bottom-left (y down); negative is +/// continuous. +pub(super) fn sd_rounded(p: [f32; 2], half: [f32; 2], radii: [f32; 4]) -> f32 { + let r = if p[0] > 0.0 { if p[1] > 0.0 { radii[2] } else { radii[1] } } else if p[1] > 0.0 { radii[3] } else { radii[0] }; + let m = half[0].min(half[1]); + if r < 0.0 { return sd_continuous(p, half, (-r).min(m)); } + let r = r.min(m); + let q = [p[0].abs() - half[0] + r, p[1].abs() - half[1] + r]; + let (a, b) = (q[0].max(0.0), q[1].max(0.0)); + q[0].max(q[1]).min(0.0) + (a * a + b * b).sqrt() - r +} + +/// `ramp`. +fn ramp(d: f32, fade: f32) -> f32 { + if fade == 0.0 { return clamp01(d + 0.5); } + let x = clamp01(d / fade.abs()); + if fade < 0.0 { x } else { x * x * (3.0 - 2.0 * x) } +} + +/// `ramp_stops`: matches `clip.wgsl`'s `ramp_stops`. +fn ramp_stops(d: f32, fade: f32, ts: [f32; 4], ys: [f32; 4]) -> f32 { + if fade == 0.0 { return clamp01(d + 0.5); } + let w = fade.abs(); + if d >= w { return 1.0; } + if d <= 0.0 { return 0.0; } + let x = d / w; + let (mut px, mut py) = (0.0f32, 0.0f32); + for k in 0..4 { + let (nx, ny) = (ts[k], ys[k]); + if x <= nx { + let span = nx - px; + return if span > 1e-6 { py + (ny - py) * ((x - px) / span) } else { ny }; + } + px = nx; + py = ny; + } + 1.0 +} + +/// An instance's clip, decoded once: `clip_alpha_stops`'s inputs. +#[derive(Clone, Copy)] +pub(super) struct Clip { + pub rect: [f32; 4], + fade: [f32; 4], + offset: [f32; 4], + is_stops: [bool; 4], + ts: [f32; 4], + ys: [f32; 4], + pub radii: Option<[f32; 4]>, +} + +impl Clip { + pub(super) fn of(i: &Instance) -> Clip { + Self::of_stops(i, [0.0; 2]) + } + + pub(super) fn of_stops(i: &Instance, stops: [f32; 2]) -> Clip { + let f = i.fade; + let half = |w: u32, hi: bool| half::f16::from_bits((if hi { w >> 16 } else { w }) as u16).to_f32(); + let (ts, ys) = if (f[2] & 0x8080_8080) != 0 { + let lo = (stops[0] + 0.5) as u32; + let hi = (stops[1] + 0.5) as u32; + ( + [(lo & 0xFF) as f32 * (1.0 / 200.0), ((lo >> 16) & 0xFF) as f32 * (1.0 / 200.0), ((hi >> 8) & 0xFF) as f32 * (1.0 / 200.0), 1.0], + [((lo >> 8) & 0xFF) as f32 * (1.0 / 200.0), (hi & 0xFF) as f32 * (1.0 / 200.0), ((hi >> 16) & 0xFF) as f32 * (1.0 / 200.0), 1.0], + ) + } else { + ([0.0, 0.0, 0.0, 1.0], [0.0, 0.0, 0.0, 1.0]) + }; + Clip { + rect: i.clip, + fade: [half(f[0], false), half(f[0], true), half(f[1], false), half(f[1], true)], + offset: std::array::from_fn(|e| ((f[2] >> (e * 8)) & 0x7f) as f32 / 127.0), + is_stops: std::array::from_fn(|e| ((f[2] >> (e * 8)) & 0x80) != 0), + ts, + ys, + radii: (f[3] != 0).then(|| unpack_clip_radii(f[3])), + } + } + + /// `clip_alpha_stops`. + pub(super) fn alpha(&self, p: [f32; 2]) -> f32 { + let c = self.rect; + let hard = [p[0] - c[0], p[1] - c[1], c[2] - p[0], c[3] - p[1]]; + let mut alpha = 1.0; + for edge in 0..4 { + let (f, o, is_stops) = (self.fade[edge], self.offset[edge], self.is_stops[edge]); + let a = if o >= 1.0 { + ramp(hard[edge], 0.0) + } else if o > 0.0 { + let shifted = hard[edge] + o * f.abs(); + let r = if is_stops { ramp_stops(shifted, f, self.ts, self.ys) } else { ramp(shifted, f) }; + ramp(hard[edge], 0.0).min(r) + } else if is_stops { + ramp_stops(hard[edge], f, self.ts, self.ys) + } else { + ramp(hard[edge], f) + }; + alpha *= a; + } + if let Some(radii) = self.radii { + let half = [(c[2] - c[0]) * 0.5, (c[3] - c[1]) * 0.5]; + alpha *= clamp01(0.5 - sd_rounded([p[0] - c[0] - half[0], p[1] - c[1] - half[1]], half, radii)); + } + alpha + } + + /// How far in from each edge (`[left, top, right, bottom]`) the clip is whole: a hard edge + /// half a pixel, a soft one its whole fade. + pub(super) fn inset(&self) -> [f32; 4] { + std::array::from_fn(|e| if self.offset[e] >= 1.0 || self.fade[e] == 0.0 { 0.5 } else { self.fade[e].abs().max(0.5) }) + } +} + +fn gaussian(x: f32, sigma: f32) -> f32 { + (-(x * x) / (2.0 * sigma * sigma)).exp() / ((2.0 * shader_consts::CONTINUOUS_PI).sqrt() * sigma) +} + +fn erf(x: f32) -> f32 { + let [a1, a2, a3] = shader_consts::ERF_POLY; + let s = if x > 0.0 { 1.0 } else if x < 0.0 { -1.0 } else { 0.0 }; + let a = x.abs(); + // From 5.5 on, `s / r⁴` is under half an ulp of 1: the result is `s` exactly. + if a >= 5.5 { return s; } + let r = 1.0 + (a1 + (a2 + a3 * (a * a)) * a) * a; + let r = r * r; + s - s / (r * r) +} + +fn shadow_x(x: f32, y: f32, sigma: f32, corner: f32, half: [f32; 2]) -> f32 { + let delta = (half[1] - corner - y.abs()).min(0.0); + let curved = half[0] - corner + (corner * corner - delta * delta).max(0.0).sqrt(); + let k = 0.5f32.sqrt() / sigma; + (0.5 + 0.5 * erf((x + curved) * k)) - (0.5 + 0.5 * erf((x - curved) * k)) +} + +/// shader.wgsl's `SHADOW_INSIDE`. +pub(super) use shader_consts::SHADOW_INSIDE; + +/// `shadow`. +fn shadow(p: [f32; 2], half: [f32; 2], sigma: f32, corner: f32) -> f32 { + if p[0].abs() <= half[0] - shader_consts::SHADOW_INSIDE_SIGMA * sigma + && p[1].abs() <= half[1] - corner - shader_consts::SHADOW_INSIDE_SIGMA * sigma + { + return SHADOW_INSIDE; + } + let (lo, hi) = (p[1] - half[1], p[1] + half[1]); + let start = (-shader_consts::SHADOW_WINDOW_SIGMA * sigma).clamp(lo, hi); + let end = (shader_consts::SHADOW_WINDOW_SIGMA * sigma).clamp(lo, hi); + let step = (end - start) / shader_consts::SHADOW_SAMPLES as f32; + let mut y = start + step * 0.5; + let mut v = 0.0; + for _ in 0..shader_consts::SHADOW_SAMPLES { + v += shadow_x(p[0], p[1] - y, sigma, corner, half) * gaussian(y, sigma) * step; + y += step; + } + v +} + +/// `shadow` for one row of a `KIND_SHADOW`: what its four y samples take from the row alone +/// (each sample's curved half width and Gaussian weight), so a pixel costs only its erf pairs. +/// The arithmetic and its order are `shadow`'s. +pub(super) struct ShadowRow { + /// The row's centre relative to the shadow's centre. + y: f32, + py: f32, + samples: [(f32, f32); shader_consts::SHADOW_SAMPLES], + step: f32, + half: [f32; 2], + sigma: f32, + corner: f32, + k: f32, + /// Within `|x| <= mid.0` every sample's erf pair is exactly `1 - 0`: the row's value there is + /// `mid.1` whatever `x` is. + pub mid: (f32, f32), +} + +impl ShadowRow { + /// What a pixel's sum depends on besides its `x`: rows that share it share every column's. + pub(super) fn key(&self) -> [u32; shader_consts::SHADOW_SAMPLES * 2 + 1] { + let mut k = [self.step.to_bits(); shader_consts::SHADOW_SAMPLES * 2 + 1]; + for (n, (c, g)) in self.samples.iter().enumerate() { k[n * 2] = c.to_bits(); k[n * 2 + 1] = g.to_bits(); } + k + } + + /// Whether `x` (from the shadow's centre) is in the interior `shadow` returns + /// `SHADOW_INSIDE` for. + pub(super) fn inside(&self, x: f32) -> bool { + x.abs() <= self.half[0] - shader_consts::SHADOW_INSIDE_SIGMA * self.sigma + && self.y.abs() <= self.half[1] - self.corner - shader_consts::SHADOW_INSIDE_SIGMA * self.sigma + } + + /// The run of `x` (from the shadow's centre, `|x| <= reach`) where this row's colour doesn't + /// change, and its blur there: the interior, on a row that crosses it, else the middle. + pub(super) fn flat(&self) -> Option<(f32, f32)> { + if self.y.abs() <= self.half[1] - self.corner - shader_consts::SHADOW_INSIDE_SIGMA * self.sigma { + return Some((self.half[0] - shader_consts::SHADOW_INSIDE_SIGMA * self.sigma, SHADOW_INSIDE)); + } + (self.mid.0 > 0.0).then_some(self.mid) + } + + /// The erf sum at `x` (from the shadow's centre), outside the interior. + pub(super) fn sum(&self, x: f32) -> f32 { + if x.abs() <= self.mid.0 { return self.mid.1; } + let mut v = 0.0; + for &(curved, g) in &self.samples { + let sx = (0.5 + 0.5 * erf((x + curved) * self.k)) - (0.5 + 0.5 * erf((x - curved) * self.k)); + v += sx * g * self.step; + } + v + } +} + +pub(super) fn shadow_row(i: &Instance, py: f32) -> ShadowRow { + let half = [i.rect[2] * 0.5, i.rect[3] * 0.5]; + let y = py - (i.rect[1] + half[1]); + let sigma = i.params[2].max(shader_consts::SHADOW_MIN_SIGMA); + let corner = i.radii[0].abs().min(half[0].min(half[1])); + let (lo, hi) = (y - half[1], y + half[1]); + let start = (-shader_consts::SHADOW_WINDOW_SIGMA * sigma).clamp(lo, hi); + let end = (shader_consts::SHADOW_WINDOW_SIGMA * sigma).clamp(lo, hi); + let step = (end - start) / shader_consts::SHADOW_SAMPLES as f32; + let mut s = start + step * 0.5; + let samples = std::array::from_fn(|_| { + let at = s; + s += step; + let delta = (half[1] - corner - (y - at).abs()).min(0.0); + (half[0] - corner + (corner * corner - delta * delta).max(0.0).sqrt(), gaussian(at, sigma)) + }); + let k = 0.5f32.sqrt() / sigma; + // `erf` is exactly ±1 from 5.5 out; `(x ± curved) * k` must reach it for every sample. + let reach = samples.iter().map(|s| s.0).fold(f32::INFINITY, f32::min) - 5.5 / k; + let mut v = 0.0; + for &(_, g) in &samples { v += 1.0 * g * step; } + // Shrunk by a part in a million, so rounding in `x ± curved` can't land a pixel short of 5.5. + let mid = (reach - reach.abs() * 1e-6 - 1e-3, v); + ShadowRow { y, py, samples, step, half, sigma, corner, k, mid } +} + + +/// `KIND_SHADOW`'s colour at `px` given its blur `cov` there: cut by its hole, if it has one. +pub(super) fn shadow_cov(i: &Instance, row: &ShadowRow, px: f32, mut cov: f32) -> [f32; 4] { + if i.uv[2] > 0.0 { + let hole = [i.uv[2] * 0.5, i.uv[3] * 0.5]; + let at = [px - (i.rect[0] + i.uv[0] + hole[0]), row.py - (i.rect[1] + i.uv[1] + hole[1])]; + cov *= clamp01(0.5 + sd_rounded(at, hole, [i.radii[3]; 4])); + } + scale4(i.fill, cov) +} + +/// `segment`. +fn segment(p: [f32; 2], a: [f32; 2], b: [f32; 2], hw: f32, round: bool) -> f32 { + let w = hw.max(0.5); + let weight = (hw * 2.0).min(1.0); + let ab = [b[0] - a[0], b[1] - a[1]]; + let len = (ab[0] * ab[0] + ab[1] * ab[1]).sqrt(); + let ap = [p[0] - a[0], p[1] - a[1]]; + let d = if len < shader_consts::SEGMENT_MIN_LEN { + if !round { return 0.0; } + (ap[0] * ap[0] + ap[1] * ap[1]).sqrt() - w + } else { + let dir = [ab[0] / len, ab[1] / len]; + let along = ap[0] * dir[0] + ap[1] * dir[1]; + if round { + let t = along.clamp(0.0, len); + let (dx, dy) = (ap[0] - dir[0] * t, ap[1] - dir[1] * t); + (dx * dx + dy * dy).sqrt() - w + } else { + let across = (dir[0] * ap[1] - dir[1] * ap[0]).abs(); + let q = [(along - len * 0.5).abs() - len * 0.5, across - w]; + let (mx, my) = (q[0].max(0.0), q[1].max(0.0)); + q[0].max(q[1]).min(0.0) + (mx * mx + my * my).sqrt() + } + }; + clamp01(0.5 - d) * weight +} + +fn edge(p: [f32; 2], a: [f32; 2], b: [f32; 2], c: [f32; 2]) -> f32 { + let e = [b[0] - a[0], b[1] - a[1]]; + let l = (e[0] * e[0] + e[1] * e[1]).sqrt().max(shader_consts::EDGE_EPSILON); + let n = [-e[1] / l, e[0] / l]; + let s = if (c[0] - a[0]) * n[0] + (c[1] - a[1]) * n[1] >= 0.0 { 1.0 } else { -1.0 }; + ((p[0] - a[0]) * n[0] + (p[1] - a[1]) * n[1]) * s +} + +fn owns(p: [f32; 2], a: [f32; 2], b: [f32; 2], c: [f32; 2]) -> bool { + let swap = a[0] > b[0] || (a[0] == b[0] && a[1] > b[1]); + let (lo, hi) = if swap { (b, a) } else { (a, b) }; + let e = [hi[0] - lo[0], hi[1] - lo[1]]; + let side = e[0] * (c[1] - lo[1]) - e[1] * (c[0] - lo[0]); + let v = e[0] * (p[1] - lo[1]) - e[1] * (p[0] - lo[0]); + if side > 0.0 { v >= 0.0 } else { v < 0.0 } +} + +fn soft(p: [f32; 2], a: [f32; 2], b: [f32; 2], c: [f32; 2]) -> f32 { + let d = edge(p, a, b, c); + let e = [b[0] - a[0], b[1] - a[1]]; + let t = ((p[0] - a[0]) * e[0] + (p[1] - a[1]) * e[1]) / (e[0] * e[0] + e[1] * e[1]).max(shader_consts::EDGE_EPSILON); + if !(0.0..=1.0).contains(&t) { return if d >= 0.0 { 1.0 } else { 0.0 }; } + clamp01(d + 0.5) +} + +/// `triangle`. +fn triangle(p: [f32; 2], a: [f32; 2], b: [f32; 2], c: [f32; 2], aa: u32) -> f32 { + let mut cov = 1.0; + for (bit, (u, v, w)) in [ + (shader_consts::TRIANGLE_AA_AB, (a, b, c)), + (shader_consts::TRIANGLE_AA_BC, (b, c, a)), + (shader_consts::TRIANGLE_AA_CA, (c, a, b)), + ] { + if aa & bit != 0 { cov *= soft(p, u, v, w); } else if !owns(p, u, v, w) { return 0.0; } + } + cov +} + +/// `ring_arc`. +fn ring_arc(p: [f32; 2], size: [f32; 2], radii: [f32; 4], bw: f32) -> (f32, f32) { + let h = bw * 0.5; + let half = [size[0] * 0.5, size[1] * 0.5]; + let m = half[0].min(half[1]); + let rc = radii.map(|r| (r.abs().min(m) - h).max(0.0)); + let e = rc.map(|r| r + h); + let arc = rc.map(|r| r * shader_consts::QUARTER_TURN); + let s_tr = (size[0] - bw - rc[0] - rc[1]).max(0.0); + let s_right = s_tr + arc[1]; + let s_br = s_right + (size[1] - bw - rc[1] - rc[2]).max(0.0); + let s_bottom = s_br + arc[2]; + let s_bl = s_bottom + (size[0] - bw - rc[2] - rc[3]).max(0.0); + let s_left = s_bl + arc[3]; + let s_tl = s_left + (size[1] - bw - rc[3] - rc[0]).max(0.0); + let top = p[0] - e[0]; + let right = s_right + p[1] - e[1]; + let bottom = s_bottom + size[0] - e[2] - p[0]; + let left = s_left + size[1] - e[3] - p[1]; + let s = if p[0] > half[0] { + if p[1] > half[1] { + let v = [p[0] - (size[0] - e[2]), p[1] - (size[1] - e[2])]; + if v[0] > 0.0 && v[1] > 0.0 { s_br + v[1].atan2(v[0]) * rc[2] } else if size[0] - p[0] < size[1] - p[1] { right } else { bottom } + } else { + let v = [p[0] - (size[0] - e[1]), p[1] - e[1]]; + if v[0] > 0.0 && v[1] < 0.0 { s_tr + v[0].atan2(-v[1]) * rc[1] } else if size[0] - p[0] < p[1] { right } else { top } + } + } else if p[1] > half[1] { + let v = [p[0] - e[3], p[1] - (size[1] - e[3])]; + if v[0] < 0.0 && v[1] > 0.0 { s_bl + (-v[0]).atan2(v[1]) * rc[3] } else if p[0] < size[1] - p[1] { left } else { bottom } + } else { + let v = [p[0] - e[0], p[1] - e[0]]; + if v[0] < 0.0 && v[1] < 0.0 { s_tl + (-v[1]).atan2(-v[0]) * rc[0] } else if p[0] < p[1] { left } else { top } + }; + (s, s_tl + arc[0]) +} + +/// `dash_cov`. +fn dash_cov(s: f32, total: f32, d: [f32; 3]) -> f32 { + let nominal = d[0] + d[1]; + let k = total.max(shader_consts::DASH_MIN_TOTAL) / ((total / nominal + 0.5).floor().max(1.0) * nominal); + let period = nominal * k; + let dash = d[0] * k; + let a = s + d[2] * k - dash * 0.5; + let m = a - period * (a / period + 0.5).floor(); + clamp01(dash * 0.5 - m.abs() + 0.5) +} + +/// `border_over`. +#[allow(clippy::too_many_arguments)] +fn border_over(fill: [f32; 4], edge: [f32; 4], d: f32, inner_d: f32, soft: f32, bw: f32, opacity: f32, shrink: bool) -> [f32; 4] { + let cov = clamp01(0.5 - d / (soft * 2.0)); + let ring = (cov - clamp01(0.5 - inner_d / (soft * 2.0))).max(0.0); + let hide = clamp01(edge[3] / opacity.clamp(shader_consts::OPACITY_EPSILON, 1.0)); + let under = clamp01( + 0.5 - (d + if shrink && hide > shader_consts::OPAQUE_HIDE_THRESHOLD { bw * 0.5 } else { 0.0 }) / (soft * 2.0), + ); + std::array::from_fn(|c| edge[c] * ring + fill[c] * (under * (1.0 - hide * ring))) +} + +/// `box_cov`. +fn box_cov(p: [f32; 2], half: [f32; 2], radii: [f32; 4]) -> f32 { + let r = if p[0] > 0.0 { if p[1] > 0.0 { radii[2] } else { radii[1] } } else if p[1] > 0.0 { radii[3] } else { radii[0] }; + if r == 0.0 { + let e = |a: usize| clamp01(half[a].min(p[a] + 0.5) - (-half[a]).max(p[a] - 0.5)); + return e(0) * e(1); + } + clamp01(0.5 - sd_rounded(p, half, radii)) +} + +/// The per-side widths' inner box of a `KIND_RECT` border: its centre, half size and radii. +pub(super) fn sides_inner(i: &Instance, center: [f32; 2], half: [f32; 2]) -> ([f32; 2], [f32; 2], [f32; 4]) { + let w = i.uv; + let ih = [(half[0] - (w[1] + w[3]) * 0.5).max(0.0), (half[1] - (w[0] + w[2]) * 0.5).max(0.0)]; + let ic = [center[0] + (w[3] - w[1]) * 0.5, center[1] + (w[0] - w[2]) * 0.5]; + let cut = [w[0].max(w[3]), w[0].max(w[1]), w[2].max(w[1]), w[2].max(w[3])]; + let r = i.radii; + (ic, ih, std::array::from_fn(|n| (r[n].abs() - cut[n]).max(0.0).copysign(r[n]))) +} + +/// Whether a `KIND_RECT` border has per-side widths. +pub(super) fn has_sides(i: &Instance) -> bool { + i.uv[2] >= 0.0 && i.uv != [0.0; 4] +} + +/// The colour (premultiplied, before the clip) of one of the box kinds (`KIND_RECT`, +/// `KIND_SHADOW`, `KIND_INSET`, `KIND_GRADIENT`, `KIND_SEGMENT`, `KIND_TRIANGLE`, `KIND_DASHED`, +/// `KIND_RADIAL`) at pixel centre `p`: the `fs` branch for its kind. +pub(super) fn boxes(i: &Instance, kind: Kind, p: [f32; 2]) -> [f32; 4] { + let half = [i.rect[2] * 0.5, i.rect[3] * 0.5]; + let center = [i.rect[0] + half[0], i.rect[1] + half[1]]; + let q = [p[0] - center[0], p[1] - center[1]]; + let soft = i.params[2].max(shader_consts::SOFT_MIN); + let t_y = || clamp01((p[1] - i.rect[1]) / i.rect[3].max(1.0)); + match kind { + Kind::Rect => { + let d = sd_rounded(q, half, i.radii); + let bw = i.params[0]; + if bw <= 0.0 { return scale4(i.fill, clamp01(0.5 - d / (soft * 2.0))); } + let sides = has_sides(i); + let inner_d = if sides { + let (ic, ih, ir) = sides_inner(i, center, half); + sd_rounded([p[0] - ic[0], p[1] - ic[1]], ih, ir) + } else { + d + bw + }; + border_over(i.fill, i.border, d, inner_d, soft, bw, i.params[3], !sides && i.radii != [0.0; 4]) + } + Kind::Shadow => { + let sigma = i.params[2].max(shader_consts::SHADOW_MIN_SIGMA); + let corner = i.radii[0].abs().min(half[0].min(half[1])); + let mut cov = shadow(q, half, sigma, corner); + if i.uv[2] > 0.0 { + let hole = [i.uv[2] * 0.5, i.uv[3] * 0.5]; + let at = [p[0] - (i.rect[0] + i.uv[0] + hole[0]), p[1] - (i.rect[1] + i.uv[1] + hole[1])]; + cov *= clamp01(0.5 + sd_rounded(at, hole, [i.radii[3]; 4])); + } + scale4(i.fill, cov) + } + Kind::Inset => { + let spread = i.params[0]; + let ih = half.map(|v| (v - spread).max(0.0)); + let qs = [q[0] - i.uv[0], q[1] - i.uv[1]]; + let lit = if i.params[2] < shader_consts::INSET_SHARP_SIGMA { + box_cov(qs, ih, i.radii.map(|r| (r.abs() - spread).max(0.0).copysign(r))) + } else { + shadow(qs, ih, i.params[2], (i.radii[0].abs() - spread).min(ih[0].min(ih[1])).max(0.0)) + }; + scale4(i.fill, box_cov(q, half, i.radii) * (1.0 - clamp01(lit))) + } + Kind::Gradient => { + let d = sd_rounded(q, half, i.radii); + let t = t_y(); + let bw = i.params[0]; + if bw > 0.0 { + border_over(i.fill, mix4(i.border, i.uv, t), d, d + bw, soft, bw, i.params[3], i.radii != [0.0; 4]) + } else { + scale4(mix4(i.fill, i.uv, t), clamp01(0.5 - d / (soft * 2.0))) + } + } + Kind::Segment => scale4(i.fill, segment(p, [i.radii[0], i.radii[1]], [i.radii[2], i.radii[3]], i.params[0], i.params[2] > shader_consts::FLAG_ON_THRESHOLD)), + Kind::Triangle => scale4(i.fill, triangle(p, [i.radii[0], i.radii[1]], [i.radii[2], i.radii[3]], [i.uv[0], i.uv[1]], (i.params[0] + 0.5) as u32)), + Kind::Dashed => { + let d = sd_rounded(q, half, i.radii); + let bw = i.params[0]; + let ring = clamp01(0.5 - d / (soft * 2.0)) - clamp01(0.5 - (d + bw) / (soft * 2.0)); + let (s, total) = ring_arc([p[0] - i.rect[0], p[1] - i.rect[1]], [i.rect[2], i.rect[3]], i.radii, bw); + scale4(mix4(i.fill, i.border, t_y()), ring * dash_cov(s, total, [i.uv[0], i.uv[1], i.uv[2]])) + } + Kind::Radial => radial(i, p, false), + Kind::Glyph | Kind::Image | Kind::Layer | Kind::LayerEnd | Kind::Effect | Kind::BackdropBlur => [0.0; 4], + } +} + +/// `KIND_RADIAL` at `p`: a radial or angled linear stop segment. `inside` says `p` is where the +/// rounded rect covers the pixel whole, so its distance needn't be taken (its coverage is 1). +pub(super) fn radial(i: &Instance, p: [f32; 2], inside: bool) -> [f32; 4] { + let half = [i.rect[2] * 0.5, i.rect[3] * 0.5]; + let q = [p[0] - (i.rect[0] + half[0]), p[1] - (i.rect[1] + half[1])]; + let soft = i.params[2].max(shader_consts::SOFT_MIN); + let (t0_raw, t1_raw) = (i.params[0], i.params[3]); + let (lower_open, upper_open) = ( + t0_raw >= shader_consts::RADIAL_OPEN_THRESHOLD, + t1_raw >= shader_consts::RADIAL_OPEN_THRESHOLD, + ); + let t0 = if lower_open { t0_raw - shader_consts::RADIAL_OPEN_OFFSET } else { t0_raw }; + let t1 = if upper_open { t1_raw - shader_consts::RADIAL_OPEN_OFFSET } else { t1_raw }; + let t = if i.uv[2] > 0.0 { + let (dx, dy) = ((p[0] - i.rect[0] - i.uv[0]) / i.uv[2], (p[1] - i.rect[1] - i.uv[1]) / i.uv[3]); + (dx * dx + dy * dy).sqrt() + } else { + 0.5 + (q[0] * i.uv[0] + q[1] * i.uv[1]) + }; + // Outside its stops a segment draws nothing, whatever its coverage: decided first. + if (lower_open && t < t0) || (upper_open && t >= t1) { return [0.0; 4]; } + let cov = if inside { 1.0 } else { clamp01(0.5 - sd_rounded(q, half, i.radii) / (soft * 2.0)) }; + let u = if t1 <= t0 + shader_consts::RADIAL_STOP_EPSILON { if t >= t0 { 1.0 } else { 0.0 } } else { clamp01((t - t0) / (t1 - t0)) }; + scale4(mix4(i.fill, i.border, u), cov) +} + +/// Whether row `py`, from pixel centre `x0` to `x1`, is all outside a linear `KIND_RADIAL` +/// segment's open stops: `t` is linear along the row, so both ends on one side means every +/// pixel between is. +pub(super) fn linear_row_outside(i: &Instance, py: f32, x0: f32, x1: f32) -> bool { + if i.uv[2] > 0.0 { return false; } + let (cx, cy) = (i.rect[0] + i.rect[2] * 0.5, i.rect[1] + i.rect[3] * 0.5); + let t = |px: f32| 0.5 + ((px - cx) * i.uv[0] + (py - cy) * i.uv[1]); + let (ta, tb) = (t(x0), t(x1)); + let (t0_raw, t1_raw) = (i.params[0], i.params[3]); + let (thr, off) = (shader_consts::RADIAL_OPEN_THRESHOLD, shader_consts::RADIAL_OPEN_OFFSET); + (t0_raw >= thr && ta < t0_raw - off && tb < t0_raw - off) || (t1_raw >= thr && ta >= t1_raw - off && tb >= t1_raw - off) +} + +/// `image_texel` in an sRGB-blending frame: one texel of an `Rgba8UnormSrgb` image page, +/// premultiplied in sRGB encoding. The page holds straight alpha unless `premultiplied`. +pub(super) fn image_texel(page: &super::Image<'_>, t: [i32; 2], premultiplied: bool) -> [f32; 4] { + let at = (t[1] as usize * page.width as usize + t[0] as usize) * 4; + let Some(c) = page.data.get(at..at + 4) else { return [0.0; 4] }; + let a = c[3] as f32 / 255.0; + if a <= 0.0 { return [0.0; 4]; } + let (decoded, round_trip) = srgb_tables(); + if !premultiplied { + // The texture decodes sRGB to linear and the shader encodes it back: a round trip per + // byte value, taken from a table. + return [round_trip[c[0] as usize] * a, round_trip[c[1] as usize] * a, round_trip[c[2] as usize] * a, a]; + } + // Opaque, the texel divides by exactly 1: the round trip again. + if c[3] == 255 { return [round_trip[c[0] as usize], round_trip[c[1] as usize], round_trip[c[2] as usize], 1.0]; } + let e = |v: u8| crate::color::srgb_encode(decoded[v as usize] / a) * a; + [e(c[0]), e(c[1]), e(c[2]), a] +} + +/// Each byte's sRGB decode (what an `Rgba8UnormSrgb` texel reads as) and its encode back, built +/// the first time an image draws. +fn srgb_tables() -> &'static ([f32; 256], [f32; 256]) { + static TABLES: std::sync::OnceLock<([f32; 256], [f32; 256])> = std::sync::OnceLock::new(); + TABLES.get_or_init(|| { + let decoded: [f32; 256] = std::array::from_fn(|v| crate::color::srgb_decode(v as f32 / 255.0)); + (decoded, decoded.map(crate::color::srgb_encode)) + }) +} + +/// `KIND_IMAGE` at pixel centre `p`: bilinear, clamped to the image's own texels. +pub(super) fn image(i: &Instance, page: &super::Image<'_>, p: [f32; 2]) -> [f32; 4] { + let half = [i.rect[2] * 0.5, i.rect[3] * 0.5]; + let d = sd_rounded([p[0] - i.rect[0] - half[0], p[1] - i.rect[1] - half[1]], half, i.radii); + let local = [(p[0] - i.rect[0]) * i.uv[2] / i.rect[2] - 0.5, (p[1] - i.rect[1]) * i.uv[3] / i.rect[3] - 0.5]; + let lo = [i.uv[0] as i32, i.uv[1] as i32]; + let hi = [lo[0] + i.uv[2] as i32 - 1, lo[1] + i.uv[3] as i32 - 1]; + let base = [local[0].floor(), local[1].floor()]; + let f = [local[0] - base[0], local[1] - base[1]]; + let t0 = [(lo[0] + base[0] as i32).clamp(lo[0], hi[0]), (lo[1] + base[1] as i32).clamp(lo[1], hi[1])]; + let t1 = [(lo[0] + base[0] as i32 + 1).clamp(lo[0], hi[0]), (lo[1] + base[1] as i32 + 1).clamp(lo[1], hi[1])]; + let pm = i.params[2] > shader_consts::FLAG_ON_THRESHOLD; + let top = mix4(image_texel(page, t0, pm), image_texel(page, [t1[0], t0[1]], pm), f[0]); + let bottom = mix4(image_texel(page, [t0[0], t1[1]], pm), image_texel(page, t1, pm), f[0]); + scale4(mix4(top, bottom, f[1]), i.fill[3] * clamp01(0.5 - d)) +} diff --git a/app/vendor/rune/crates/rune/src/render/cpu_boot/tests.rs b/app/vendor/rune/crates/rune/src/render/cpu_boot/tests.rs new file mode 100644 index 0000000..afaf5dc --- /dev/null +++ b/app/vendor/rune/crates/rune/src/render/cpu_boot/tests.rs @@ -0,0 +1,417 @@ +use super::bin::{Bins, Show}; +use super::{CpuPainter, HalfRounding, Pixels, Scene, Target, drift, paint}; +use crate::color::Color; +use crate::pixels::ImageAtlas; +use crate::render::{ + Gpu, Instance, KIND_BACKDROP_BLUR, KIND_RECT, LayerSpec, MAX_BACKDROP_BLURS, NO_CLIP, Offscreen, + Renderer, pack_clip_radii, pack_fade, +}; +use crate::text::Atlas; + +fn rect(bounds: [f32; 4], fill: [f32; 4], clip: [f32; 4]) -> Instance { + Instance { + rect: bounds, + radii: [0.0; 4], + fill, + border: [0.0; 4], + params: [0.0, KIND_RECT, 0.0, 1.0], + uv: [0.0; 4], + clip, + fade: [0; 4], + } +} + +fn render_gpu_bgra(gpu: &Gpu, instances: &[Instance], size: (u32, u32), clear: [f32; 4]) -> Vec<u8> { + let format = wgpu::TextureFormat::Bgra8Unorm; + let mut renderer = Renderer::new(&gpu.device, format); + renderer.set_srgb_blend(true); + let mut atlas = Atlas::new(); + renderer.prepare_ui(&gpu.device, &gpu.queue, &mut atlas, instances, size); + let target = Offscreen::with_format(&gpu.device, size.0, size.1, format); + let mut enc = gpu.device.create_command_encoder(&Default::default()); + renderer.draw(&mut enc, &target.view, clear); + target.copy(&mut enc); + renderer.submit(&gpu.queue, enc); + target.read(&gpu.device) +} + +#[test] +fn backdrop_blur_cap_matches_gpu() { + let (w, h) = (256u32, 64u32); + let clear = Color { r: 0.05, g: 0.08, b: 0.12, a: 1.0 }.premul_srgb(1.0); + let mut instances = Vec::new(); + // High-contrast vertical stripes so blurring vs not blurring produces a clear pixel delta. + for x in (0..w).step_by(8) { + let color = if (x / 8) % 2 == 0 { + Color { r: 0.9, g: 0.15, b: 0.1, a: 1.0 }.premul_srgb(1.0) + } else { + Color { r: 0.1, g: 0.85, b: 0.25, a: 1.0 }.premul_srgb(1.0) + }; + instances.push(rect([x as f32, 0.0, 8.0, h as f32], color, NO_CLIP)); + } + // Emit MAX_BACKDROP_BLURS + 2 backdrop blurs; the GPU caps at MAX_BACKDROP_BLURS. + for k in 0..(MAX_BACKDROP_BLURS + 2) { + let x = 4.0 + k as f32 * 40.0; + instances.push(Instance { + rect: [x, 8.0, 32.0, 48.0], + radii: [4.0; 4], + fill: [0.0, 0.0, 0.0, 1.0], + border: [0.0; 4], + params: [8.0, KIND_BACKDROP_BLUR, 0.0, 1.0], + uv: [0.0; 4], + clip: NO_CLIP, + fade: [0; 4], + }); + } + + let atlas = Atlas::new(); + let images = ImageAtlas::default(); + let gpu = Gpu::headless(); + let half = HalfRounding::of_vendor(gpu.adapter.get_info().vendor); + let scene = Scene::new(&instances, &atlas, &images, (w, h), clear).srgb_blend(true).half_rounding(half); + let bins = Bins::of(&scene); + assert_eq!(bins.blurs.len(), MAX_BACKDROP_BLURS, "CPU boot must cap backdrop blurs at MAX_BACKDROP_BLURS"); + + let mut cpu_px = vec![0u8; (w * h * 4) as usize]; + paint(&scene, &mut Target::new(&mut cpu_px, w, h), 1).expect("CPU paints backdrop blurs"); + let gpu_px = render_gpu_bgra(&gpu, &instances, (w, h), clear); + let d = drift( + Pixels::bgra(&cpu_px, w, h, w as usize * 4), + Pixels::bgra(&gpu_px, w, h, w as usize * 4), + ); + assert_eq!(d.over_two, 0, "CPU and GPU backdrop blur frames drifted: {d:?}"); +} + +#[test] +fn scissor_clipped_layer_flattens_and_matches_gpu() { + let (w, h) = (128u32, 64u32); + let clear = Color { r: 0.08, g: 0.1, b: 0.14, a: 1.0 }.premul_srgb(1.0); + let atlas = Atlas::new(); + let images = ImageAtlas::default(); + + // 1. Planning rules match GPU `layers/plan.rs` `is_scissor_clip`: + // - integer-aligned square clip with zero fade flattens (`Show::Flat`) + // - fractional clip isolates (`Show::Render`) + // - soft-faded or rounded clip isolates (`Show::Render`) + let child = rect([0.0, 0.0, 128.0, 64.0], Color { r: 0.8, g: 0.25, b: 0.15, a: 1.0 }.premul_srgb(1.0), NO_CLIP); + let int_clip = [16.0, 16.0, 80.0, 48.0]; + let mut soft_layer = Instance::begin_layer([0.0, 0.0, 128.0, 64.0], int_clip, LayerSpec::default()); + soft_layer.fade = pack_fade([8.0, 0.0, 0.0, 0.0], int_clip, int_clip); + let mut rounded_layer = Instance::begin_layer([0.0, 0.0, 128.0, 64.0], int_clip, LayerSpec::default()); + rounded_layer.fade[3] = pack_clip_radii(int_clip, [6.0; 4]); + let plan_instances = [ + Instance::begin_layer([0.0, 0.0, 128.0, 64.0], int_clip, LayerSpec::default()), + child, + Instance::end_layer(), + Instance::begin_layer([0.0, 0.0, 128.0, 64.0], [16.5, 16.0, 80.0, 48.0], LayerSpec::default()), + child, + Instance::end_layer(), + soft_layer, + child, + Instance::end_layer(), + rounded_layer, + child, + Instance::end_layer(), + ]; + let plan_scene = Scene::new(&plan_instances, &atlas, &images, (w, h), clear).srgb_blend(true); + let plan_bins = Bins::of(&plan_scene); + assert_eq!(plan_bins.layers[0].show, Show::Flat, "integer square clip with no fade must flatten"); + assert_eq!(plan_bins.layers[1].show, Show::Render, "fractional clip must isolate"); + assert_eq!(plan_bins.layers[2].show, Show::Render, "soft-faded clip must isolate"); + assert_eq!(plan_bins.layers[3].show, Show::Render, "rounded clip must isolate"); + + // 2. Flattened scissor-clipped layers (including nested) clip children accurately and match GPU. + let instances = [ + // Outer scissor-clipped flat layer: [16, 16, 80, 48] + Instance::begin_layer([0.0, 0.0, 128.0, 64.0], [16.0, 16.0, 80.0, 48.0], LayerSpec::default()), + // Unclipped child larger than the layer's clip: must stay strictly inside [16, 16, 80, 48]. + rect([0.0, 0.0, 128.0, 64.0], Color { r: 0.75, g: 0.2, b: 0.15, a: 0.8 }.premul_srgb(1.0), NO_CLIP), + // Nested scissor-clipped flat layer: [32, 8, 96, 40] -> effective intersection [32, 16, 80, 40]. + Instance::begin_layer([0.0, 0.0, 128.0, 64.0], [32.0, 8.0, 96.0, 40.0], LayerSpec::default()), + rect([0.0, 0.0, 128.0, 64.0], Color { r: 0.15, g: 0.7, b: 0.9, a: 0.65 }.premul_srgb(1.0), NO_CLIP), + Instance::end_layer(), + Instance::end_layer(), + ]; + let gpu = Gpu::headless(); + let half = HalfRounding::of_vendor(gpu.adapter.get_info().vendor); + let scene = Scene::new(&instances, &atlas, &images, (w, h), clear).srgb_blend(true).half_rounding(half); + let mut cpu_px = vec![0u8; (w * h * 4) as usize]; + paint(&scene, &mut Target::new(&mut cpu_px, w, h), 1).expect("CPU paints flat scissor layers"); + let gpu_px = render_gpu_bgra(&gpu, &instances, (w, h), clear); + let d = drift( + Pixels::bgra(&cpu_px, w, h, w as usize * 4), + Pixels::bgra(&gpu_px, w, h, w as usize * 4), + ); + assert_eq!(d.over_two, 0, "CPU and GPU scissor-clipped flat layers drifted: {d:?}"); + // Pixel (4, 4) is outside the outer scissor: must keep the clear colour. + let at = |buf: &[u8], x: u32, y: u32| -> [u8; 4] { + let i = ((y * w + x) * 4) as usize; + [buf[i], buf[i + 1], buf[i + 2], buf[i + 3]] + }; + let bg_px = at(&cpu_px, 4, 4); + assert_eq!(bg_px, at(&gpu_px, 4, 4)); + // Pixel (85, 30) is outside outer [16..80] even though inside nested [32..96]: must be clear. + assert_eq!(at(&cpu_px, 85, 30), bg_px, "outer scissor must clip nested flat layer"); + // Pixel (40, 24) is inside both clips: must differ from clear. + assert_ne!(at(&cpu_px, 40, 24), bg_px); + + // 3. Incremental `CpuPainter` repaints tiles when a flattened layer's scissor shrinks even if + // the child instance itself didn't change. + let mut painter = CpuPainter::new(1); + let mut retained = vec![0u8; (w * h * 4) as usize]; + let frame1 = [ + Instance::begin_layer([0.0, 0.0, 128.0, 64.0], [16.0, 16.0, 80.0, 48.0], LayerSpec::default()), + child, + Instance::end_layer(), + ]; + let frame2 = [ + Instance::begin_layer([0.0, 0.0, 128.0, 64.0], [16.0, 16.0, 48.0, 48.0], LayerSpec::default()), + child, + Instance::end_layer(), + ]; + painter.paint(&Scene::new(&frame1, &atlas, &images, (w, h), clear).srgb_blend(true), &mut Target::new(&mut retained, w, h)).unwrap(); + assert_ne!(at(&retained, 60, 30), bg_px, "frame 1 paints inside [16..80]"); + painter.paint(&Scene::new(&frame2, &atlas, &images, (w, h), clear).srgb_blend(true), &mut Target::new(&mut retained, w, h)).unwrap(); + assert_eq!(at(&retained, 60, 30), bg_px, "frame 2 must repaint pixel exposed when flat scissor shrinks"); +} + +#[test] +fn plus_lighter_overlapping_opaque_rects_match_gpu() { + use crate::render::Blend; + + let (w, h) = (64u32, 48u32); + let clear = Color { r: 0.04, g: 0.06, b: 0.1, a: 1.0 }.premul_srgb(1.0); + let instances = [ + rect([0.0, 0.0, w as f32, h as f32], [0.05, 0.1, 0.2, 1.0], NO_CLIP), + Instance::begin_layer( + [4.0, 4.0, 56.0, 40.0], + NO_CLIP, + LayerSpec { opacity: 0.7, blend: Blend::PlusLighter, ..Default::default() }, + ), + // Two overlapping opaque primaries inside a PlusLighter layer: red + blue must sum to + // magenta [1, 0, 1, 2] -> clamped [1, 0, 1, 1], never let the second rect occlude the first. + rect([8.0, 8.0, 28.0, 24.0], [1.0, 0.0, 0.0, 1.0], NO_CLIP), + rect([20.0, 12.0, 28.0, 24.0], [0.0, 0.0, 1.0, 1.0], NO_CLIP), + // Two overlapping translucent bright rects whose sum saturates past 1.0. + rect([10.0, 28.0, 24.0, 12.0], [0.8, 0.25, 0.0, 0.8], NO_CLIP), + rect([18.0, 28.0, 24.0, 12.0], [0.8, 0.25, 0.0, 0.8], NO_CLIP), + Instance::end_layer(), + ]; + + let atlas = Atlas::new(); + let images = ImageAtlas::default(); + let gpu = Gpu::headless(); + let half = HalfRounding::of_vendor(gpu.adapter.get_info().vendor); + let scene = Scene::new(&instances, &atlas, &images, (w, h), clear).srgb_blend(true).half_rounding(half); + let mut cpu_px = vec![0u8; (w * h * 4) as usize]; + paint(&scene, &mut Target::new(&mut cpu_px, w, h), 1).expect("CPU paints PlusLighter layers"); + let gpu_px = render_gpu_bgra(&gpu, &instances, (w, h), clear); + + let at = |buf: &[u8], x: u32, y: u32| -> [u8; 4] { + let i = ((y * w + x) * 4) as usize; + [buf[i], buf[i + 1], buf[i + 2], buf[i + 3]] + }; + let mut max_diff = 0u8; + let mut worst = None; + for y in 0..h { + for x in 0..w { + let (c, g) = (at(&cpu_px, x, y), at(&gpu_px, x, y)); + let d = (0..4).map(|k| c[k].abs_diff(g[k])).max().unwrap(); + if d > max_diff { + max_diff = d; + worst = Some((x, y, c, g)); + } + } + } + assert!( + max_diff <= 1, + "CPU boot and GPU drifted on PlusLighter layer: max_diff={max_diff} worst={worst:?} (overlap (24,20) cpu={:?} gpu={:?})", + at(&cpu_px, 24, 20), + at(&gpu_px, 24, 20), + ); +} + +#[test] +fn plus_lighter_turned_and_scaled_layers_saturate_before_interpolation() { + use crate::render::{Blend, OFFSCREEN_FORMAT, pack_u64_f32}; + + let (w, h) = (64u32, 48u32); + let gpu = Gpu::headless(); + let render = |renderer: &mut Renderer, instances: &[Instance]| -> Vec<u8> { + let mut atlas = Atlas::new(); + renderer.prepare(&gpu.device, &gpu.queue, &mut atlas, instances, (w, h)); + let target = Offscreen::with_format(&gpu.device, w, h, OFFSCREEN_FORMAT); + let mut enc = gpu.device.create_command_encoder(&Default::default()); + renderer.draw(&mut enc, &target.view, [0.0; 4]); + target.copy(&mut enc); + renderer.submit(&gpu.queue, enc); + target.read(&gpu.device) + }; + let max_diff = |a: &[u8], b: &[u8]| -> (u8, Option<(u32, u32, [u8; 4], [u8; 4])>) { + let mut max_d = 0u8; + let mut worst = None; + for y in 0..h { + for x in 0..w { + let i = ((y * w + x) * 4) as usize; + let pa = [a[i], a[i + 1], a[i + 2], a[i + 3]]; + let pb = [b[i], b[i + 1], b[i + 2], b[i + 3]]; + let d = (0..4).map(|k| pa[k].abs_diff(pb[k])).max().unwrap(); + if d > max_d { + max_d = d; + worst = Some((x, y, pa, pb)); + } + } + } + (max_d, worst) + }; + + // 1. Turned PlusLighter layer: two overlapping [0.8, 0.2, 0.0, 0.8] rects saturate to + // [1.0, 0.4, 0.0, 1.0], so rotating the layer must match a single [1.0, 0.4, 0.0, 1.0] rect. + let box_rect = [16.0, 12.0, 24.0, 24.0]; + let turned_open = Instance::begin_layer( + box_rect, + NO_CLIP, + LayerSpec { opacity: 0.8, blend: Blend::PlusLighter, ..Default::default() }, + ) + .turned(0.4, [28.0, 24.0]); + let single_turned = [turned_open, rect(box_rect, [1.0, 0.4, 0.0, 1.0], NO_CLIP), Instance::end_layer()]; + let doubled_turned = [ + turned_open, + rect(box_rect, [0.8, 0.2, 0.0, 0.8], NO_CLIP), + rect(box_rect, [0.8, 0.2, 0.0, 0.8], NO_CLIP), + Instance::end_layer(), + ]; + let mut renderer = Renderer::new(&gpu.device, OFFSCREEN_FORMAT); + let a = render(&mut renderer, &single_turned); + let b = render(&mut renderer, &doubled_turned); + let (diff_turned, worst_turned) = max_diff(&a, &b); + + // 2. Scaled cached PlusLighter layer (`uv.z > 0`): frame 1 renders a 20x20 cache with a 12x12 + // inner saturated shape and transparent border; frame 2 composites the cached target scaled + // to 36x36 so bilinear resampling crosses the shape's boundary. + let cache_frame = |node: u64, bounds: [f32; 4], children: &[Instance]| -> Vec<Instance> { + let mut open = Instance::begin_layer( + bounds, + NO_CLIP, + LayerSpec { opacity: 0.8, blend: Blend::PlusLighter, ..Default::default() }, + ); + open.params[3] = 1.0; + open.radii = pack_u64_f32(node); + open.uv = pack_u64_f32(1); + let mut out = vec![open]; + out.extend_from_slice(children); + out.push(Instance::end_layer()); + out + }; + let inner = [12.0, 12.0, 12.0, 12.0]; + let base_bounds = [8.0, 8.0, 20.0, 20.0]; + let scaled_bounds = [8.0, 8.0, 36.0, 36.0]; + let mut r_single = Renderer::new(&gpu.device, OFFSCREEN_FORMAT); + let _ = render(&mut r_single, &cache_frame(1, base_bounds, &[rect(inner, [1.0, 0.4, 0.0, 1.0], NO_CLIP)])); + let scaled_single = render(&mut r_single, &cache_frame(1, scaled_bounds, &[])); + + let mut r_doubled = Renderer::new(&gpu.device, OFFSCREEN_FORMAT); + let _ = render( + &mut r_doubled, + &cache_frame( + 2, + base_bounds, + &[rect(inner, [0.8, 0.2, 0.0, 0.8], NO_CLIP), rect(inner, [0.8, 0.2, 0.0, 0.8], NO_CLIP)], + ), + ); + let scaled_doubled = render(&mut r_doubled, &cache_frame(2, scaled_bounds, &[])); + let (diff_scaled, worst_scaled) = max_diff(&scaled_single, &scaled_doubled); + assert!( + diff_turned <= 1 && diff_scaled <= 1, + "PlusLighter layer interpolated unclamped texels: turned max={diff_turned} worst={worst_turned:?}; scaled max={diff_scaled} worst={worst_scaled:?}", + ); +} + +#[test] +fn backdrop_blur_multithreaded_matches_single_thread() { + let (w, h) = (320u32, 173u32); + let clear = Color { r: 0.05, g: 0.08, b: 0.12, a: 1.0 }.premul_srgb(1.0); + let mut instances = Vec::new(); + for y in (0..h).step_by(12) { + for x in (0..w).step_by(12) { + let color = if ((x / 12) + (y / 12)) % 2 == 0 { + Color { r: 0.9, g: 0.2, b: 0.1, a: 1.0 }.premul_srgb(1.0) + } else { + Color { r: 0.1, g: 0.75, b: 0.85, a: 1.0 }.premul_srgb(1.0) + }; + instances.push(rect([x as f32, y as f32, 12.0, 12.0], color, NO_CLIP)); + } + } + for (k, sigma) in [2.5f32, 8.0, 24.0].into_iter().enumerate() { + let x = 10.0 + k as f32 * 96.0; + instances.push(Instance { + rect: [x, 12.0, 84.0, 149.0], + radii: [6.0; 4], + fill: [0.0, 0.0, 0.0, 1.0], + border: [0.0; 4], + params: [sigma, KIND_BACKDROP_BLUR, 0.0, 1.0], + uv: [0.0; 4], + clip: NO_CLIP, + fade: [0; 4], + }); + } + let atlas = Atlas::new(); + let images = ImageAtlas::default(); + let scene = Scene::new(&instances, &atlas, &images, (w, h), clear).srgb_blend(true); + let mut single = vec![0u8; (w * h * 4) as usize]; + let mut multi = vec![0u8; (w * h * 4) as usize]; + paint(&scene, &mut Target::new(&mut single, w, h), 1).expect("single-thread paint"); + paint(&scene, &mut Target::new(&mut multi, w, h), 4).expect("multi-thread paint"); + assert_eq!(single, multi, "multi-threaded backdrop blur must match single-threaded pixels bit-for-bit"); +} + +#[test] +fn move_tiles_matches_reference_across_shifts_strides_and_threads() { + use super::bin::{TILE_H, TILE_W}; + let size = (275u32, 210u32); + let cols = size.0.div_ceil(TILE_W); + let tile_rows = size.1.div_ceil(TILE_H); + let row_bytes = size.0 as usize * 4; + + for (stride, extra_tail) in [(row_bytes, 0usize), (row_bytes + 48, 0usize), (row_bytes + 48, (row_bytes + 48) * 3 + 12)] { + let buf_len = stride * (size.1 as usize - 1) + row_bytes + extra_tail; + let initial: Vec<u8> = (0..buf_len).map(|i| ((i.wrapping_mul(131) ^ (i >> 5)) & 0xff) as u8).collect(); + for dy in [-130i32, -64, -33, -12, -1, 1, 12, 33, 64, 130] { + let mut clean = vec![false; (cols * tile_rows) as usize]; + for ty in 0..tile_rows { + let y0 = ty * TILE_H; + let y1 = ((ty + 1) * TILE_H).min(size.1); + let in_bounds = y0 as i32 - dy >= 0 && y1 as i32 - dy <= size.1 as i32; + if !in_bounds { continue; } + for tx in 0..cols { + // Mix gaps (static sidebar at tx=0, dirty tile at tx=2 on odd rows) with contiguous runs. + if tx > 0 && !(tx == 2 && ty % 2 == 1) { + clean[(ty * cols + tx) as usize] = true; + } + } + } + let mut expected = initial.clone(); + for ty in 0..tile_rows { + let y0 = ty * TILE_H; + let y1 = ((ty + 1) * TILE_H).min(size.1); + for tx in 0..cols { + if !clean[(ty * cols + tx) as usize] { continue; } + let x0 = (tx * TILE_W) as usize * 4; + let x1 = ((tx + 1) * TILE_W).min(size.0) as usize * 4; + for y in y0..y1 { + let src_y = (y as i32 - dy) as usize; + let dst_y = y as usize; + expected[dst_y * stride + x0..dst_y * stride + x1] + .copy_from_slice(&initial[src_y * stride + x0..src_y * stride + x1]); + } + } + } + for threads in [1usize, 4] { + let mut actual = initial.clone(); + let mut target = Target::with_stride(&mut actual, size.0, size.1, stride); + super::painter::move_tiles(&super::raster::Spawn(threads), &mut target, size, cols, &clean, dy); + assert_eq!(actual, expected, "mismatch for stride={stride} tail={extra_tail} dy={dy} threads={threads}"); + } + } + } +} diff --git a/app/vendor/rune/crates/rune/src/render/cpu_boot/tool.rs b/app/vendor/rune/crates/rune/src/render/cpu_boot/tool.rs new file mode 100644 index 0000000..3317ae6 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/render/cpu_boot/tool.rs @@ -0,0 +1,101 @@ +//! `--cpu-boot DIR`: a headless run that also draws every frame on the CPU, as a window does +//! before its GPU: the live painter (`CpuPainter`) repaints the damaged tiles of one retained +//! buffer, after filling the frame's queued masks (which the GPU then uploads and samples, as +//! after a hand-over). Each frame's stage times and damage go to `DIR/frames.jsonl`. At the +//! snapshot frame it writes the draw data (`draw.bin`, `record.rs`), the CPU's frame (`cpu.png`) +//! and the GPU's (`gpu.png`), and prints `rune-cpu-boot {json}` with that frame's numbers and the +//! drift between the two. + +use std::io::Write; +use std::path::PathBuf; + +use serde_json::json; + +use super::{CpuPainter, Pixels, Scene, Target}; +use crate::runtime::RuntimeCore; + +pub(crate) struct Tool { + dir: PathBuf, + painter: CpuPainter, + threads: usize, + /// The retained buffer, B, G, R, A, rows `stride` bytes apart, as large as the largest frame + /// so far, as a window keeps its bitmap across a live resize; and the frame's size in it. + buf: Vec<u8>, + stride: usize, + size: (u32, u32), + vendor: u32, + log: Option<std::io::BufWriter<std::fs::File>>, + /// The snapshot frame and what the run said about it, until the GPU's arrives. + painted: Option<(Vec<u8>, serde_json::Value)>, +} + +impl Tool { + /// A run whose GPU has PCI vendor ID endor, the one whose rounding the CPU follows. + pub(crate) fn new(dir: PathBuf, threads: usize, vendor: u32) -> Tool { + std::fs::create_dir_all(&dir).ok(); + let log = std::fs::File::create(dir.join("frames.jsonl")).ok().map(std::io::BufWriter::new); + Tool { dir, painter: CpuPainter::new(threads), threads: threads.max(1), buf: Vec::new(), stride: 0, size: (0, 0), vendor, log, painted: None } + } + + /// Before the renderer prepares frame `k`, which `rt` laid out in `update_ns`: fills its + /// queued masks and paints it, and at the snapshot frame records it. + pub(crate) fn frame(&mut self, rt: &mut RuntimeCore, size: (u32, u32), k: usize, update_ns: u64, snap: bool) { + let started = crate::time::now(); + let fills = self.painter.fill_masks(&mut rt.text.atlas); + let scene = Scene::new(&rt.instances, &rt.text.atlas, &rt.images, size, rt.clear_color()) + .srgb_blend(rt.srgb_blend()) + .fade_stops(rt.fade_stops()) + .native_surfaces(!rt.surfaces.is_empty()) + .font_smoothing(rt.font_smoothing()) + .half_rounding(super::HalfRounding::of_vendor(self.vendor)); + // Outgrown, the bitmap is made again at the new size: every pixel paints. + if size.0 as usize * 4 > self.stride || self.buf.len() < self.stride * size.1 as usize { + let rows = if self.stride == 0 { 0 } else { self.buf.len() / self.stride }; + self.stride = self.stride.max(size.0 as usize * 4); + self.buf = vec![0u8; self.stride * rows.max(size.1 as usize)]; + self.painter.forget(); + } + self.size = size; + let painted = self.painter.paint(&scene, &mut Target::with_stride(&mut self.buf, size.0, size.1, self.stride)); + let total = super::ns(started.elapsed()); + let mut out = json!({ "k": k, "vendor": self.vendor, "update_ns": update_ns, "cpu_ns": total, "instances": rt.instances.len(), "threads": self.threads, + "fill": { "masks": fills.masks, "texels": fills.texels, "cover_ns": fills.cover_ns, "copy_ns": fills.copy_ns } }); + match &painted { + Ok(p) => out["paint"] = json!({ + "bin_ns": p.report.bin_ns, "hash_ns": p.hash_ns, "plan_ns": p.plan_ns, "move_ns": p.move_ns, "scrolled": p.scrolled, "slowest_tile_ns": p.report.slowest_tile_ns, "blur_ns": p.report.blur_ns, "raster_ns": p.report.raster_ns, "total_ns": p.report.total_ns, "threads": p.report.threads, + "dirty_tiles": p.dirty_tiles, "tiles": p.tiles, "rects": p.rects, "span_px": p.report.span_px, "shaded_px": p.report.shaded_px, "glyph_px": p.report.glyph_px, + "dirty_px": p.rects.iter().map(|r| u64::from(r[2] - r[0]) * u64::from(r[3] - r[1])).sum::<u64>(), + }), + Err(why) => out["needs_gpu"] = json!(format!("{why:?}")), + } + if let Some(log) = self.log.as_mut() { writeln!(log, "{out}").ok(); } + if !snap { return; } + let mut kinds = [0u32; 16]; + for i in &rt.instances { + let slot = match i.kind() { + Some(k) => k.as_u8() as usize, + None => (i.params[1].max(0.0) as usize).min(15), + }; + kinds[slot] += 1; + } + out["kinds"] = json!(kinds); + std::fs::write(self.dir.join("draw.bin"), super::record::encode(&scene)).ok(); + // The frame's rows, tightly packed. + let bgra: Vec<u8> = self.buf.chunks(self.stride).take(size.1 as usize).flat_map(|row| &row[..size.0 as usize * 4]).copied().collect(); + let rgba: Vec<u8> = bgra.chunks_exact(4).flat_map(|p| [p[2], p[1], p[0], p[3]]).collect(); + crate::render::write_png(&self.dir.join("cpu.png"), size.0, size.1, &rgba).ok(); + self.painted = Some((bgra, out)); + } + + /// The GPU's snapshot frame, R, G, B, A, tightly packed. + pub(crate) fn gpu(&mut self, rgba: &[u8], size: (u32, u32)) { + let Some((cpu, mut out)) = self.painted.take() else { return }; + if let Some(log) = self.log.as_mut() { log.flush().ok(); } + crate::render::write_png(&self.dir.join("gpu.png"), size.0, size.1, rgba).ok(); + if self.size == size { + let d = super::drift(Pixels::bgra(&cpu, size.0, size.1, size.0 as usize * 4), Pixels::rgba(rgba, size.0, size.1, size.0 as usize * 4)); + out["drift"] = json!({ "pixels": d.pixels, "differ": d.differ, "over_two": d.over_two, "max": d.max }); + } + println!("rune-cpu-boot {out}"); + } +} diff --git a/app/vendor/rune/crates/rune/src/render/csd_corners.rs b/app/vendor/rune/crates/rune/src/render/csd_corners.rs new file mode 100644 index 0000000..f6b0539 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/render/csd_corners.rs @@ -0,0 +1,189 @@ +//! Clearing the corners a Wayland client-side frame leaves outside its rounded window. +//! +//! Under `sctk-adwaita` the frame draws the window's shadow and its one-point visible border on +//! subsurfaces around the content, and rounds the window's corners while it floats +//! (`vendor/sctk-adwaita`). The content's own surface is a rectangle, so its square corners would +//! show past that border. This fades the pixels outside the arc at the two bottom corners, which +//! the frame's border covers, so the surface composites them fully transparent. The top corners +//! need nothing: the headerbar's own surface covers the content's top edge. +//! +//! The fade multiplies whatever the app drew there, so it assumes the content is opaque in the two +//! corner squares: Rune's root fill is (an app's window is opaque unless it asked to be +//! translucent, and then its own alpha fades with the corners rather than behind them). A pixel the +//! arc crosses keeps its colour and loses the same share of its alpha, which is the frame's ring's +//! own antialiasing, so the two meet without a seam. On the sRGB view `srgb_blend(false)` draws +//! into, the one-pixel fade's encoded colour can sit a step above what its alpha alone would say: +//! the blend is linear while the stored value is encoded, the same rounding Rune's own blending +//! takes there. + +/// A pipeline that fades out what is outside a rounded corner's arc, and leaves everything inside +/// it. It multiplies the target by the arc's coverage, so a pixel the arc crosses keeps exactly its +/// share of the frame's antialiased ring: no jagged seam between them. Only each corner's square is +/// drawn at all, and every other pixel of the target keeps what it had. +/// +/// The multiply is a blend, and a blend into an sRGB view happens in linear light — the hardware +/// decodes the stored pixels, blends, and encodes the result — which is the space Rune's own +/// blending there works in. The linear view `srgb_blend(true)` draws into needs no conversion at +/// all, so the fade is the same on both; a fully faded pixel is clear either way. +pub(crate) struct CsdCorners { + pipeline: wgpu::RenderPipeline, + format: wgpu::TextureFormat, + vertices: wgpu::Buffer, + /// The radius, in device pixels, and target size `vertices` were written for. + prepared: Option<(f32, (u32, u32))>, +} + +impl CsdCorners { + pub fn new(device: &wgpu::Device, format: wgpu::TextureFormat) -> Self { + let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor { + label: Some("rounded corners"), + source: wgpu::ShaderSource::Wgsl( + r#" +// `centre` is the corner arc's centre in device pixels, flat across the corner's square, and +// `radius` is the arc's radius in device pixels, so the fade is one pixel wide whatever the scale. +// Measuring from `@builtin(position).xy` uses the rasterizer's exact pixel centre instead of an +// interpolated quad coordinate that can drift by subpixel ULPs on D3D12. +struct Vertex { + @builtin(position) at: vec4<f32>, + @location(0) @interpolate(flat) centre: vec2<f32>, + @location(1) @interpolate(flat) radius: f32, +}; + +@vertex fn vs(@location(0) at: vec2<f32>, @location(1) centre: vec2<f32>, @location(2) radius: f32) -> Vertex { + return Vertex(vec4(at, 0.0, 1.0), centre, radius); +} + +@fragment fn fs(frag: Vertex) -> @location(0) vec4<f32> { + // How much of this pixel the arc leaves: one inside the content's corner, none outside it, and + // a pixel's width of fade across the arc itself. `a` is what is cleared, so the target is + // multiplied by `1 - a`. + let distance = length(frag.at.xy - frag.centre); + let outside = smoothstep(frag.radius - 0.5, frag.radius + 0.5, distance); + if outside <= 0.0 { + discard; + } + return vec4(0.0, 0.0, 0.0, outside); +} +"# + .into(), + ), + }); + // A vertex is its clip-space position, its corner arc's centre in device pixels, and the + // arc's radius. + let vertex = std::mem::size_of::<f32>() as wgpu::BufferAddress; + let stride = 5 * vertex; + let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { + label: Some("rounded corners"), + layout: None, + vertex: wgpu::VertexState { + module: &shader, + entry_point: Some("vs"), + compilation_options: Default::default(), + buffers: &[Some(wgpu::VertexBufferLayout { + array_stride: stride, + step_mode: wgpu::VertexStepMode::Vertex, + attributes: &[ + wgpu::VertexAttribute { format: wgpu::VertexFormat::Float32x2, offset: 0, shader_location: 0 }, + wgpu::VertexAttribute { format: wgpu::VertexFormat::Float32x2, offset: 2 * vertex, shader_location: 1 }, + wgpu::VertexAttribute { format: wgpu::VertexFormat::Float32, offset: 4 * vertex, shader_location: 2 }, + ], + })], + }, + primitive: Default::default(), + depth_stencil: None, + multisample: Default::default(), + fragment: Some(wgpu::FragmentState { + module: &shader, + entry_point: Some("fs"), + compilation_options: Default::default(), + targets: &[Some(wgpu::ColorTargetState { + format, + // The target's colour and alpha both times the arc's coverage: what the + // fragment keeps, and nothing where it is outside the arc. + blend: Some(wgpu::BlendState { + color: wgpu::BlendComponent { + src_factor: wgpu::BlendFactor::Zero, + dst_factor: wgpu::BlendFactor::OneMinusSrcAlpha, + operation: wgpu::BlendOperation::Add, + }, + alpha: wgpu::BlendComponent { + src_factor: wgpu::BlendFactor::Zero, + dst_factor: wgpu::BlendFactor::OneMinusSrcAlpha, + operation: wgpu::BlendOperation::Add, + }, + }), + write_mask: wgpu::ColorWrites::ALL, + })], + }), + multiview_mask: None, + cache: None, + }); + let vertices = device.create_buffer(&wgpu::BufferDescriptor { + label: Some("rounded corners"), + // Two corners, two triangles each, five values a vertex. + size: 12 * stride, + usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + }); + Self { pipeline, format, vertices, prepared: None } + } + + /// The format it draws into: a surface that changed its format needs another pass. + pub fn format(&self) -> wgpu::TextureFormat { self.format } + + /// Whether it already clears `size` with arcs of `radius` device pixels. + pub fn is_prepared_for(&self, size: (u32, u32), radius: f32) -> bool { self.prepared == Some((radius, size)) } + + /// Writes the two bottom corner squares of a `size` target, whose arcs have `radius` device + /// pixels. A radius of zero draws nothing: production never asks for one (`window::surface::corners`). + pub fn prepare(&mut self, queue: &wgpu::Queue, size: (u32, u32), radius: f32) { + if self.is_prepared_for(size, radius) || radius <= 0. { return; } + let (width, height) = (size.0.max(1) as f32, size.1.max(1) as f32); + let mut vertices: Vec<f32> = Vec::with_capacity(12 * 5); + // Each corner's square runs from the arc's centre out to the window's edges, a radius + // either way; the bottom two sit a radius in from the foot's sides and off its edge, one + // reaching left and the other right. + for (centre, side) in [((radius, height - radius), -1.), ((width - radius, height - radius), 1.)] { + for (u, v) in [(0., 0.), (1., 0.), (0., 1.), (1., 0.), (1., 1.), (0., 1.)] { + let (x, y) = (centre.0 + side * u * radius, centre.1 + v * radius); + vertices.extend_from_slice(&[ + x / width * 2.0 - 1.0, + 1.0 - y / height * 2.0, + centre.0, + centre.1, + radius, + ]); + } + } + queue.write_buffer(&self.vertices, 0, bytemuck::cast_slice(&vertices)); + self.prepared = Some((radius, size)); + } + + /// Fades out what lies outside the arcs, leaving every other pixel of `target` as it was + /// drawn: it is a premultiplied composition, before a straight-alpha surface converts it. + pub fn draw(&self, encoder: &mut wgpu::CommandEncoder, target: &wgpu::TextureView) { + if self.prepared.is_none() { + return; + } + let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { + label: Some("rounded corners"), + color_attachments: &[Some(wgpu::RenderPassColorAttachment { + view: target, + depth_slice: None, + resolve_target: None, + ops: wgpu::Operations { load: wgpu::LoadOp::Load, store: wgpu::StoreOp::Store }, + })], + depth_stencil_attachment: None, + timestamp_writes: None, + occlusion_query_set: None, + multiview_mask: None, + }); + pass.set_pipeline(&self.pipeline); + pass.set_vertex_buffer(0, self.vertices.slice(..)); + pass.draw(0..12, 0..1); + } +} + +#[cfg(test)] +#[path = "csd_corners_tests.rs"] +mod tests; diff --git a/app/vendor/rune/crates/rune/src/render/csd_corners_tests.rs b/app/vendor/rune/crates/rune/src/render/csd_corners_tests.rs new file mode 100644 index 0000000..fc35a7b --- /dev/null +++ b/app/vendor/rune/crates/rune/src/render/csd_corners_tests.rs @@ -0,0 +1,146 @@ +//! Clearing a window's rounded bottom corners on the GPU: what stays, and what goes. + +use super::CsdCorners; +use crate::render::{Gpu, Offscreen, OFFSCREEN_FORMAT}; + +/// A target of opaque red, its corners faded at `radius` device pixels. +fn cleared(gpu: &Gpu, size: (u32, u32), radius: f32) -> Vec<u8> { + cleared_with(gpu, size, radius, OFFSCREEN_FORMAT) +} + +/// [`cleared`] into a target of `format`. +fn cleared_with(gpu: &Gpu, size: (u32, u32), radius: f32, format: wgpu::TextureFormat) -> Vec<u8> { + let target = Offscreen::with_format(&gpu.device, size.0, size.1, format); + let mut pass = CsdCorners::new(&gpu.device, format); + let mut enc = gpu.device.create_command_encoder(&Default::default()); + { + let _clear = enc.begin_render_pass(&wgpu::RenderPassDescriptor { + label: None, + color_attachments: &[Some(wgpu::RenderPassColorAttachment { + view: &target.view, + depth_slice: None, + resolve_target: None, + ops: wgpu::Operations { + load: wgpu::LoadOp::Clear(wgpu::Color::RED), + store: wgpu::StoreOp::Store, + }, + })], + depth_stencil_attachment: None, + timestamp_writes: None, + occlusion_query_set: None, + multiview_mask: None, + }); + } + pass.prepare(&gpu.queue, (size.0, size.1), radius); + pass.draw(&mut enc, &target.view); + target.copy(&mut enc); + gpu.queue.submit([enc.finish()]); + target.read(&gpu.device) +} + +/// The target's pixel at `(x, y)`, as RGBA. +fn at(pixels: &[u8], width: u32, (x, y): (u32, u32)) -> [u8; 4] { + let start = ((y * width + x) * 4) as usize; + pixels[start..start + 4].try_into().expect("four channels") +} + +#[test] +fn the_bottom_corners_clear_and_nothing_else() { + let gpu = Gpu::new(Gpu::instance(), None); + let (width, height) = (40, 30); + let radius = 6.; + let pixels = cleared(&gpu, (width, height), radius); + let red = at(&pixels, width, (0, 0)); + assert_eq!(red[3], 255, "the top left corner keeps its pixel: {red:?}"); + assert_eq!(at(&pixels, width, (0, height - 1))[3], 0, "the bottom left corner clears"); + assert_eq!(at(&pixels, width, (width - 1, height - 1))[3], 0, "the bottom right corner clears"); + // Along the foot, the arc is gone only past where it meets the window's edge. The pixels a + // pixel in from it are inside the fade's inside edge, so they keep all of their coverage. + assert_eq!(at(&pixels, width, (radius as u32, height - 2))[3], 255, "inside the arc stays"); + assert_eq!(at(&pixels, width, (width - 1 - radius as u32, height - 2))[3], 255, "inside the arc stays"); + // Above the corners' own squares nothing changed, at either side. + assert_eq!(at(&pixels, width, (0, height - 1 - radius as u32))[3], 255, "above the arc's centre stays"); + assert_eq!(at(&pixels, width, (width - 1, height - 1 - radius as u32))[3], 255, "above the arc's centre stays"); + // The top two corners are the headerbar's business. + assert_eq!(at(&pixels, width, (width - 1, 0))[3], 255, "the top right corner keeps its pixel"); +} + +/// The arcs follow the radius: a wider one takes more of the corner. +#[test] +fn a_wider_radius_clears_more_of_the_corner() { + let gpu = Gpu::new(Gpu::instance(), None); + let size = (40, 30); + let narrow = cleared(&gpu, size, 4.); + let wide = cleared(&gpu, size, 9.); + // A pixel above the bottom left, on the window's edge: outside a radius-9 arc (9.9 from its + // centre) but above a radius-4 one's corner square altogether, which only starts four in from + // the foot. + let corner = (0, 25); + assert_eq!(at(&narrow, size.0, corner)[3], 255, "outside the narrow corner's square"); + assert_eq!(at(&wide, size.0, corner)[3], 0, "outside the wide corner's arc"); +} + +/// A square window (maximized, tiled or fullscreen) draws nothing: nothing is prepared for a +/// radius of zero, and the pass draws nothing when nothing was prepared for it. `Host::draw` skips +/// it outright for that radius (`window::tests`). +#[test] +fn a_square_window_draws_nothing() { + let gpu = Gpu::new(Gpu::instance(), None); + let size = (40, 30); + let target = Offscreen::new(&gpu.device, size.0, size.1); + let mut enc = gpu.device.create_command_encoder(&Default::default()); + { + let _clear = enc.begin_render_pass(&wgpu::RenderPassDescriptor { + label: None, + color_attachments: &[Some(wgpu::RenderPassColorAttachment { + view: &target.view, + depth_slice: None, + resolve_target: None, + ops: wgpu::Operations { load: wgpu::LoadOp::Clear(wgpu::Color::RED), store: wgpu::StoreOp::Store }, + })], + depth_stencil_attachment: None, + timestamp_writes: None, + occlusion_query_set: None, + multiview_mask: None, + }); + } + let mut pass = CsdCorners::new(&gpu.device, OFFSCREEN_FORMAT); + pass.prepare(&gpu.queue, size, 0.); + assert!(!pass.is_prepared_for(size, 0.), "a square window prepares no pass"); + // And the pass draws nothing when nothing was prepared for it. + pass.draw(&mut enc, &target.view); + target.copy(&mut enc); + gpu.queue.submit([enc.finish()]); + let pixels = target.read(&gpu.device); + for y in 0..size.1 { + for x in 0..size.0 { + assert_eq!(at(&pixels, size.0, (x, y))[3], 255, "({x}, {y}) faded with no radius"); + } + } +} + +/// The fade holds in both views the renderer makes: the sRGB one `srgb_blend(false)` draws into and +/// the linear one it makes for `srgb_blend(true)`, which the frame is drawn through in either case. +#[test] +fn both_target_views_fade_the_corners() { + let gpu = Gpu::new(Gpu::instance(), None); + let size = (40, 30); + for format in [OFFSCREEN_FORMAT, OFFSCREEN_FORMAT.remove_srgb_suffix()] { + let pixels = cleared_with(&gpu, size, 6., format); + assert_eq!(at(&pixels, size.0, (0, 0))[3], 255, "{format:?}: the top left keeps its pixel"); + assert_eq!(at(&pixels, size.0, (0, size.1 - 1))[3], 0, "{format:?}: the bottom corner fades"); + assert_eq!(at(&pixels, size.0, (6, 27))[3], 255, "{format:?}: inside the arc stays"); + // A pixel the arc crosses keeps part of its colour and of its alpha alike: the fade is a + // multiply in linear light, so the red the target was cleared to scales with the coverage + // (encoded, on an sRGB view). + let across = at(&pixels, size.0, (1, 28)); + assert!(across[3] > 0 && across[3] < 255, "{format:?}: the arc's edge fades ({across:?})"); + let coverage = across[3] as f32 / 255.; + let want = if format.is_srgb() { (crate::color::srgb_encode(coverage) * 255.).round() as u8 } else { across[3] }; + assert!( + across[0].abs_diff(want) <= 2, + "{format:?}: the faded red is {} where the coverage says {want}", + across[0], + ); + } +} diff --git a/app/vendor/rune/crates/rune/src/render/damaged.rs b/app/vendor/rune/crates/rune/src/render/damaged.rs new file mode 100644 index 0000000..aae3216 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/render/damaged.rs @@ -0,0 +1,365 @@ +//! Redrawing part of a frame: the renderer keeps the window's last frame in a texture of its own +//! (`Retained`), redraws only the rectangles that changed into it, and copies it to the +//! drawable. wgpu treats a drawable as holding nothing when it's acquired (a `LoadOp::Load` into +//! it loads zeros), so the frame can't be drawn over the drawable itself; the copy costs the GPU +//! a few hundred microseconds where the whole frame's raster costs milliseconds. +//! +//! The window arms the rectangles before the frame draws (`arm_damage`); `draw` (and so a +//! compositor's `Frame::draw_ui`) redraws only them when nothing but the instances draws there, +//! and the window reads back whether it did (`damage_drawn`), every frame: any frame drawn +//! another way leaves the kept texture behind, and the next armed one draws it whole. Every +//! instance still goes through the pass, each scissor kept inside the rectangle +//! (`ActivePass::borrowed_within`), so what lands there is exactly what a whole frame draws there. + +use super::*; + +/// Rectangles a frame redraws at most. +pub(crate) const MAX_RECTS: usize = 4; + +/// What the armed rectangles came to. +pub(super) type Drawn = Result<(), &'static str>; + +/// The window's last frame, and whether it's current. +pub(super) struct Retained { + texture: wgpu::Texture, + view: wgpu::TextureView, + current: bool, +} + +/// The renderer's side of a partial frame. +#[derive(Default)] +pub(super) struct DamageState { + retained: Option<Retained>, + armed: Vec<[u32; 4]>, + /// For each armed rectangle, the instances whose quads reach it (`arm_cycle`), when only + /// those are drawn there; empty: every instance is. + runs: Vec<Vec<std::ops::Range<u32>>>, + /// The paint and target size `arm_cycle` last found its rectangles and runs for, and them. + #[cfg_attr(not(target_arch = "wasm32"), allow(dead_code))] + cycle: Option<((u64, (u32, u32)), Result<Cull, &'static str>)>, + /// The paint and target size `arm_loop` last found the units of, and them. + loop_units: Option<((u64, (u32, u32)), Result<std::sync::Arc<Units>, &'static str>)>, + /// Whether a run of the armed rectangles holds a layer's scope. + layers_reached: bool, + clear: [f32; 4], + drawn: Option<Drawn>, + /// The armed rectangles are a loop-only frame's (`arm_loop`), for `RUNE_LOOP_CHECK=2`. + pub(super) looped: bool, + pub(super) pixel: Option<super::pixel_check::Check>, +} + +impl Renderer { + /// The next `draw` may redraw only `rects` (`[x, y, width, height]` each, target pixels, at + /// most `MAX_RECTS`) of a `size` drawable of `format`, cleared to `clear`. + pub(crate) fn arm_damage(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, rects: &[[u32; 4]], clear: [f32; 4], size: (u32, u32), format: wgpu::TextureFormat) { + let mut d = self.damage.lock().unwrap(); + if d.retained.as_ref().is_none_or(|r| (r.texture.width(), r.texture.height()) != size || r.texture.format() != format) { + let texture = device.create_texture(&wgpu::TextureDescriptor { + label: Some("last frame"), + size: wgpu::Extent3d { width: size.0, height: size.1, depth_or_array_layers: 1 }, + mip_level_count: 1, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + format, + usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC, + view_formats: &[self.format], + }); + let view = texture.create_view(&wgpu::TextureViewDescriptor { format: Some(self.format), ..Default::default() }); + d.retained = Some(Retained { texture, view, current: false }); + } + let fills: Vec<Instance> = rects.iter().take(MAX_RECTS).map(|&[x, y, w, h]| Instance { + rect: [x as f32, y as f32, w as f32, h as f32], + radii: [0.0; 4], + fill: clear, + border: [0.0; 4], + params: [0.0; 4], + uv: [0.0; 4], + clip: [x as f32, y as f32, (x + w) as f32, (y + h) as f32], + fade: [0; 4], + }).collect(); + let quads = self.clear_quad.get_or_init(|| device.create_buffer(&wgpu::BufferDescriptor { + label: Some("damage clear"), + size: (std::mem::size_of::<Instance>() * MAX_RECTS) as u64, + usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + })); + // Through the renderer's staging, as a layer's quad: `Queue::write_buffer` makes a buffer each call. + if !fills.is_empty() { self.uploads.staging(device, queue).write_buffer(quads, 0, bytemuck::cast_slice(&fills)); } + d.armed = rects.iter().take(MAX_RECTS).copied().collect(); + d.runs.clear(); + d.clear = clear; + d.drawn = Some(Err("drawn by the compositor")); + } + + /// A loop-only frame (`runtime/paint/cycle.rs`): only the instances at `slots` changed since + /// the frame the kept texture holds, and only in colour. Arms the rectangles they draw in, + /// each with only the instances whose quads reach it (what the rest drew there stays as + /// drawn). `Err` says why this frame draws whole. + #[cfg_attr(not(target_arch = "wasm32"), allow(dead_code))] + pub(crate) fn arm_cycle(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, paint: u64, instances: &[Instance], slots: &[u32], clear: [f32; 4], size: (u32, u32), format: wgpu::TextureFormat) -> Result<(), &'static str> { + // The clearing quad blends: only an opaque clear stands for `LoadOp::Clear`. + if clear[3] != 1.0 { return Err("clear"); } + if slots.is_empty() { return Err("no slots"); } + self.redraws_in_place()?; + let key = (paint, size); + let cached = self.damage.lock().unwrap().cycle.as_ref().filter(|c| c.0 == key).map(|c| c.1.clone()); + let (rects, runs, layers) = match cached { + Some(c) => c?, + None => { + let c = cycle_cull(instances, slots, size); + self.damage.lock().unwrap().cycle = Some((key, c.clone())); + c? + } + }; + self.arm_damage(device, queue, &rects, clear, size, format); + let mut d = self.damage.lock().unwrap(); + d.runs = runs; + d.layers_reached = layers; + Ok(()) + } + + /// A window's loop-only frame (`Runtime::loop_step`): only the instances at `patched` + /// (ascending) changed since the frame the kept texture and the instance buffer hold, both + /// paint `paint`'s. Arms the pixels they drew on and draw on now, each with only the instances + /// that reach it (what the rest drew there stays as drawn). Returns those rectangles (x0, y0, + /// x1, y1) to present, or why this frame draws whole. + #[allow(clippy::too_many_arguments)] + pub(crate) fn arm_loop(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, paint: u64, instances: &[Instance], patched: &[u32], clear: [f32; 4], size: (u32, u32), format: wgpu::TextureFormat) -> Result<Vec<[i32; 4]>, &'static str> { + // The clearing quad blends: only an opaque clear stands for `LoadOp::Clear`. + if clear[3] != 1.0 { return Err("clear"); } + self.redraws_in_place()?; + let held = self.held_instances(paint, instances.len()).ok_or("buffer")?; + let at = |i: &u32| *i as usize; + // Only what differs from what the buffer holds, which is what the last frame drew (a + // frame that missed its drawable uploaded nothing): a stepped spinner's dots between their + // steps, while the shine drives frames, aren't redrawn; a dot a missed frame stepped is. + let patched: Vec<u32> = patched.iter().copied().filter(|&i| bytemuck::bytes_of(&held[i as usize]) != bytemuck::bytes_of(&instances[i as usize])).collect(); + let patched = &patched[..]; + let mut rects = gather(patched.iter().map(at).flat_map(|i| [&held[i], &instances[i]]), size); + // Nothing on screen changed: one pixel keeps the present, which DWM composes again as is. + if rects.is_empty() { rects.push([0, 0, 1, 1]); } + let key = (paint, size); + let cached = self.damage.lock().unwrap().loop_units.as_ref().filter(|c| c.0 == key).map(|c| c.1.clone()); + let units = match cached { + Some(units) => units?, + None => { + let units = units(instances, size).map(std::sync::Arc::new); + self.damage.lock().unwrap().loop_units = Some((key, units.clone())); + units? + } + }; + let (draw, runs, layers) = cull_runs(instances, &units, &rects, patched); + self.arm_damage(device, queue, &draw, clear, size, format); + if super::pixel_check::on() { self.pixel_check_arm(device, size, format); } + let mut d = self.damage.lock().unwrap(); + d.runs = runs; + d.layers_reached = layers; + Ok(rects) + } + + /// The armed frame redraws its rectangles over a current kept frame, and no layer is among + /// what it draws there: `prepare` leaves the layers as the last frame planned and drew them. + pub(super) fn cycle_leaves_layers(&self) -> bool { + let d = self.damage.lock().unwrap(); + !d.armed.is_empty() && !d.runs.is_empty() && !d.layers_reached && d.retained.as_ref().is_some_and(|r| r.current) + } + + /// After every frame: whether it redrew only the armed rectangles, or why not. A frame that + /// drew any other way leaves the kept frame behind. + pub(crate) fn damage_drawn(&self) -> Drawn { + let mut d = self.damage.lock().unwrap(); + d.armed.clear(); + d.looped = false; + if let Some(c) = d.pixel.as_mut() { c.frame_ended(); } + let drawn = d.drawn.take().unwrap_or(Err("not armed")); + if drawn.is_err() && let Some(r) = d.retained.as_mut() { r.current = false; } + drawn + } + + /// Whether this frame can redraw only part of its target: nothing draws there but its own + /// instances (no turned or blurred layer, effect slot, backdrop blur, native surface or GPU + /// spring moves pixels the instances don't say). + pub(super) fn redraws_in_place(&self) -> Drawn { + if !self.effects.is_empty() { return Err("effect"); } + if self.has_backdrop_blur() { return Err("backdrop blur"); } + if self.springs.is_some() { return Err("springs"); } + if !self.layers.in_place() { return Err("layer"); } + if self.surfaces.as_ref().is_some_and(|s| !s.draws_nothing()) { return Err("surface"); } + Ok(()) + } + + /// Rectangles are armed for the next `draw` (asked before it looks up its target's texture). + pub(super) fn armed(&self) -> bool { + !self.damage.lock().unwrap().armed.is_empty() + } + + /// `draw`'s part, when armed: redraws the armed rectangles into the kept frame (all of it + /// when it's behind) and copies it to `dst`. False when `draw` should draw whole. + pub(crate) fn draw_armed(&self, encoder: &mut wgpu::CommandEncoder, dst: &wgpu::Texture) -> bool { + let mut guard = self.damage.lock().unwrap(); + let d = &mut *guard; + let looped = std::mem::take(&mut d.looped); + if d.armed.is_empty() { return false; } + if let Err(why) = self.redraws_in_place() { + d.drawn = Some(Err(why)); + return false; + } + let rects = std::mem::take(&mut d.armed); + let runs = std::mem::take(&mut d.runs); + let layers_reached = d.layers_reached; + let clear = d.clear; + let (Some(quads), Some(kept)) = (self.clear_quad.get(), d.retained.as_mut()) else { return false }; + if (dst.width(), dst.height()) != (kept.texture.width(), kept.texture.height()) { + d.drawn = Some(Err("size")); + return false; + } + let partial = kept.current; + if kept.current { + // No layer reaches the rectangles: their targets aren't drawn from, nor made again. + // The uploads go into this encoder ahead of the pass either way (`encode_layers_timed` + // flushes them too), not in a submission of their own: a submit costs the CPU about as + // much as the rest of a loop-only frame. + if runs.is_empty() || layers_reached { self.encode_layers_timed(encoder, None, &mut |_, _| {}); } else { self.flush_uploads(encoder); } + self.submit_uploads(); + let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { + label: Some("frame (damage)"), + color_attachments: &[Some(wgpu::RenderPassColorAttachment { + view: &kept.view, + depth_slice: None, + resolve_target: None, + ops: wgpu::Operations { load: wgpu::LoadOp::Load, store: wgpu::StoreOp::Store }, + })], + depth_stencil_attachment: None, + timestamp_writes: None, + occlusion_query_set: None, + multiview_mask: None, + }); + let size = [dst.width(), dst.height()]; + // frame-profile, `RUNE_LOOP_CHECK_SPOIL=1`: a loop-only frame skips its redraw, so the kept + // picture goes stale and `RUNE_LOOP_CHECK=2` must find it (its failing row). + #[cfg(feature = "frame-profile")] + let spoil = looped && super::pixel_check::spoiled(); + #[cfg(not(feature = "frame-profile"))] + let spoil = false; + for (n, &rect) in rects.iter().enumerate().filter(|_| !spoil) { + let [x, y, w, h] = rect; + pass.set_scissor_rect(x, y, w, h); + pass.set_pipeline(self.draw_pipeline(self.format, None)); + pass.set_bind_group(0, &self.bind_group, &[]); + pass.set_vertex_buffer(0, quads.slice(..)); + pass.draw(0..4, n as u32..n as u32 + 1); + let mut active = ActivePass::borrowed_within(&mut pass, rect); + active.set_scissor(None, size); + match runs.get(n) { + // Only what reaches the rectangle (`arm_cycle`): none of the rest draws there. + Some(runs) => for run in runs { self.draw_layer_range(&mut active, self.format, run.clone(), None, &mut |_, _| {}); }, + None => self.draw_layer_range(&mut active, self.format, 0..self.count, None, &mut |_, _| {}), + } + } + } else { + // Behind: this frame draws whole, into the kept frame. + self.draw_timed(encoder, &kept.view, clear, None); + kept.current = true; + } + // `RUNE_LOOP_CHECK=2`: this loop-only frame's picture, and the whole frame's beside it. + if looped && partial && let Some(c) = d.pixel.as_mut() { self.pixel_check_encode(encoder, c, &kept.texture, clear, &rects); } + let whole = wgpu::Extent3d { width: dst.width(), height: dst.height(), depth_or_array_layers: 1 }; + encoder.copy_texture_to_texture(kept.texture.as_image_copy(), dst.as_image_copy(), whole); + d.drawn = Some(Ok(())); + true + } +} + +/// A loop-only frame's rectangles, the runs drawn in each, and whether a layer is among them. +type Cull = (Vec<[u32; 4]>, Vec<Vec<std::ops::Range<u32>>>, bool); + +/// The rectangles a loop-only frame redraws (each slot's quad 2 px wider, merged with those it +/// comes within 8 px of, `MAX_RECTS` at most) and, for each, runs of what reaches it, a pixel +/// wider still: an instance, or a layer's whole scope (its own bounds and all it holds), which +/// `draw_layer_range` draws as one. +#[cfg_attr(not(target_arch = "wasm32"), allow(dead_code))] +fn cycle_cull(instances: &[Instance], slots: &[u32], size: (u32, u32)) -> Result<Cull, &'static str> { + let quads = slots.iter().map(|&s| instances.get(s as usize).ok_or("slot")).collect::<Result<Vec<_>, _>>()?; + let rects = gather(quads.into_iter(), size); + if rects.is_empty() { return Err("nothing drawn"); } + let units = units(instances, size)?; + Ok(cull_runs(instances, &units, &rects, &[])) +} + +/// The pixels `quads` draw on, each 2 px wider, merged with those it comes within 8 px of, +/// `MAX_RECTS` at most (x0, y0, x1, y1). +fn gather<'a>(quads: impl Iterator<Item = &'a Instance>, size: (u32, u32)) -> Vec<[i32; 4]> { + let (w, h) = (size.0 as i32, size.1 as i32); + let empty = |b: &[i32; 4]| b[2] <= b[0] || b[3] <= b[1]; + let near = |a: &[i32; 4], b: &[i32; 4]| a[0] <= b[2] + 8 && b[0] <= a[2] + 8 && a[1] <= b[3] + 8 && b[1] <= a[3] + 8; + let union = |a: [i32; 4], b: [i32; 4]| if empty(&a) { b } else if empty(&b) { a } else { [a[0].min(b[0]), a[1].min(b[1]), a[2].max(b[2]), a[3].max(b[3])] }; + let mut rects: Vec<[i32; 4]> = Vec::new(); + for q in quads { + let b = q.pixel_bounds(w, h); + if empty(&b) { continue; } + let mut b = [(b[0] - 2).max(0), (b[1] - 2).max(0), (b[2] + 2).min(w), (b[3] + 2).min(h)]; + while let Some(k) = rects.iter().position(|r| near(r, &b)) { b = union(b, rects.swap_remove(k)); } + rects.push(b); + } + while rects.len() > MAX_RECTS { + let (Some(a), Some(b)) = (rects.pop(), rects.pop()) else { break }; + rects.push(union(a, b)); + } + rects +} + +/// What a frame draws, in units: an instance, or a layer's whole scope (its own bounds and all it +/// holds), which `draw_layer_range` draws as one, each with its pixel bounds. +type Units = Vec<(std::ops::Range<u32>, [i32; 4])>; + +fn units(instances: &[Instance], size: (u32, u32)) -> Result<Units, &'static str> { + let (w, h) = (size.0 as i32, size.1 as i32); + let bounds = |i: &Instance| i.pixel_bounds(w, h); + let empty = |b: &[i32; 4]| b[2] <= b[0] || b[3] <= b[1]; + let union = |a: [i32; 4], b: [i32; 4]| if empty(&a) { b } else if empty(&b) { a } else { [a[0].min(b[0]), a[1].min(b[1]), a[2].max(b[2]), a[3].max(b[3])] }; + let mut units: Units = Vec::new(); + let mut n = 0; + while n < instances.len() { + let start = n; + let mut b = bounds(&instances[n]); + if instances[n].kind() == Some(Kind::Layer) { + let mut depth = 1; + while depth > 0 { + n += 1; + let i = instances.get(n).ok_or("open layer")?; + b = union(b, bounds(i)); + match i.kind() { + Some(Kind::Layer) => depth += 1, + Some(Kind::LayerEnd) => depth -= 1, + _ => {} + } + } + } + n += 1; + units.push((start as u32..n as u32, b)); + } + Ok(units) +} + +/// For each of `rects`, runs of the units that reach it, a pixel wider still, and of any unit +/// holding one of `always` (ascending): instances whose bounds were found before they moved. +fn cull_runs(instances: &[Instance], units: &Units, rects: &[[i32; 4]], always: &[u32]) -> Cull { + let empty = |b: &[i32; 4]| b[2] <= b[0] || b[3] <= b[1]; + let holds = |u: &std::ops::Range<u32>| always.get(always.partition_point(|&a| a < u.start)).is_some_and(|&a| a < u.end); + let runs: Vec<Vec<std::ops::Range<u32>>> = rects.iter().map(|r| { + let mut runs: Vec<std::ops::Range<u32>> = Vec::new(); + for (unit, b) in units { + let reaches = !empty(b) && b[0] - 1 < r[2] && r[0] < b[2] + 1 && b[1] - 1 < r[3] && r[1] < b[3] + 1; + if !reaches && !holds(unit) { continue; } + // A short gap is drawn through: what's in it doesn't reach the rectangle, and one + // draw costs less than two. + match runs.last_mut() { + Some(run) if unit.start - run.end <= 16 => run.end = unit.end, + _ => runs.push(unit.clone()), + } + } + runs + }).collect(); + let layers = units.iter().any(|(u, _)| instances[u.start as usize].kind() == Some(Kind::Layer) && runs.iter().flatten().any(|r| r.start <= u.start && u.end <= r.end)); + (rects.iter().map(|r| [r[0] as u32, r[1] as u32, (r[2] - r[0]) as u32, (r[3] - r[1]) as u32]).collect(), runs, layers) +} \ No newline at end of file diff --git a/app/vendor/rune/crates/rune/src/render/device.rs b/app/vendor/rune/crates/rune/src/render/device.rs new file mode 100644 index 0000000..8bf7aee --- /dev/null +++ b/app/vendor/rune/crates/rune/src/render/device.rs @@ -0,0 +1,381 @@ +//! GPU instance, adapter and device creation, prewarming, and allocation reporting. + +use std::sync::{Arc, atomic::AtomicBool}; + +use super::{Renderer, gpu_events, prewarm}; + +pub struct Gpu { + pub instance: wgpu::Instance, + pub adapter: wgpu::Adapter, + pub device: wgpu::Device, + pub queue: wgpu::Queue, + /// Set by the device's lost callback: a device that went away (a driver reset, a GPU removed, + /// Windows' Modern Standby) can't configure a surface, and wgpu drops that error, so nothing + /// else would report it. See `is_lost`. + pub(super) lost: Arc<AtomicBool>, + /// D3D12 removes a device before wgpu hears of it (`Gpu::is_lost`). + pub(super) removal: rune_gpu::health::Removal, +} + +/// The most views and buffers a device binds at once (`Limits::max_non_sampler_bindings`). +/// D3D12 sizes its shader-visible heap from it and can't grow it: each layer target holds about +/// five of these, so 4,096 ran out at 1,024 layers in one frame. +const MAX_VIEWS: u32 = 65_536; + +/// Vulkan loaders crash when two threads create instances or devices at once (seen with +/// parallel GPU tests on lavapipe), so Rune creates them one at a time. +static GPU_INIT: std::sync::Mutex<()> = std::sync::Mutex::new(()); + +impl Gpu { + /// Panics without a usable adapter or device; windows use `try_new`. + pub fn new(instance: wgpu::Instance, surface: Option<&wgpu::Surface<'_>>) -> Gpu { + Self::try_new(instance, surface).unwrap_or_else(|error| panic!("{error}")) + } + + pub fn try_new(instance: wgpu::Instance, surface: Option<&wgpu::Surface<'_>>) -> Result<Gpu, String> { + Self::try_with_features(instance, surface, wgpu::Features::empty()) + } + + /// Like `try_new`, also enabling whichever of `wanted` the adapter supports. + #[cfg(not(target_arch = "wasm32"))] + pub fn try_with_features(instance: wgpu::Instance, surface: Option<&wgpu::Surface<'_>>, wanted: wgpu::Features) -> Result<Gpu, String> { + Self::try_for(instance, surface, wanted, false) + } + + /// Like `try_with_features`, preferring for a `translucent` surface `translucency::prefer`'s adapter. + #[cfg(not(target_arch = "wasm32"))] + fn try_for(instance: wgpu::Instance, surface: Option<&wgpu::Surface<'_>>, wanted: wgpu::Features, translucent: bool) -> Result<Gpu, String> { + Self::try_picked(instance, surface, wanted, translucent, false) + } + + /// A device for a surface not made yet (`warm_gpu`): on the adapter a surface would get. + #[cfg(not(any(target_arch = "wasm32", target_os = "macos")))] + pub(super) fn try_for_display(instance: wgpu::Instance, wanted: wgpu::Features) -> Result<Gpu, String> { + Self::try_picked(instance, None, wanted, false, true) + } + + #[cfg(not(target_arch = "wasm32"))] + fn try_picked(instance: wgpu::Instance, surface: Option<&wgpu::Surface<'_>>, wanted: wgpu::Features, translucent: bool, presented: bool) -> Result<Gpu, String> { + let _serial = GPU_INIT.lock().unwrap_or_else(|e| e.into_inner()); + // D3D12 keeps one device per adapter in a process: while a removed one is still held, a + // new device on that adapter is the removed one again. + crate::native_surface::release_removed_device(); + let pick = crate::gpu::pick::pick(&instance, surface, presented)?; + let named = pick.reason == crate::gpu::pick::Reason::EnvName; + crate::marks::mark("gpu.adapter"); + if !crate::marks::noted("adapter") { crate::marks::note("adapter", Box::leak(pick.adapter.get_info().name.into_boxed_str())); } + let adapter = match surface { + Some(s) if translucent && !pick.from_env() => crate::render::translucency::prefer(&instance, s, &pick), + _ => pick.adapter, + }; + match Self::device_on(&adapter, wanted) { + Ok((device, queue)) => { + crate::marks::mark("gpu.device"); + crate::native_surface::note_device(&device, surface.is_some() || presented); + Ok(Gpu::made(instance, adapter, device, queue, surface.is_some() || presented)) + } + // A named adapter (`WGPU_ADAPTER_NAME`) never falls through to another GPU. + Err(error) if named => Err(error), + // A driver that can't make a device (a broken integrated GPU on a hybrid laptop) + // leaves the window to the next adapter that presents to its surface. + Err(error) => { + let first = adapter.get_info(); + let others = pollster::block_on(instance.enumerate_adapters(wgpu::Backends::all())) + .into_iter() + .filter(|other| { + let info = other.get_info(); + (info.name != first.name || info.backend != first.backend) + && surface.is_none_or(|s| other.is_surface_supported(s)) + && (!translucent || surface.is_none_or(|s| crate::render::translucency::mode(s, other).is_some())) + }); + for other in others { + if let Ok((device, queue)) = Self::device_on(&other, wanted) { + eprintln!("rune: {} ({:?}) made no device ({error}); using {}", first.name, first.backend, other.get_info().name); + crate::native_surface::note_device(&device, surface.is_some() || presented); + return Ok(Gpu::made(instance, other, device, queue, surface.is_some() || presented)); + } + } + Err(error) + } + } + } + + #[cfg(not(target_arch = "wasm32"))] + fn device_on(adapter: &wgpu::Adapter, wanted: wgpu::Features) -> Result<(wgpu::Device, wgpu::Queue), String> { + // Dual-source blending is for subpixel text (`FontSmoothing::WindfoilRgb`, `ClearType`). + let optional_features = wgpu::Features::TIMESTAMP_QUERY | wgpu::Features::DUAL_SOURCE_BLENDING | wanted | crate::gpu::backend::free_features(adapter); + // Precompiled uber shaders: a metallib on macOS, DXBC on Windows. + #[cfg(any(target_os = "macos", target_os = "windows"))] + let optional_features = optional_features | wgpu::Features::PASSTHROUGH_SHADERS; + let required_features = adapter.features() & optional_features; + // A compositor that asks for immediates (`Compositor::features`) gets all the adapter has. + let max_immediate_size = if required_features.contains(wgpu::Features::IMMEDIATES) { adapter.limits().max_immediate_size } else { 0 }; + let adapter_limits = adapter.limits(); + // Views and buffers bound at once (D3D12's shader-visible descriptor heap, which wgpu sizes from + // this limit when it makes the device). wgpu's default, a million, is a 32-64 MB heap on + // Windows; 65,536 is far more than Rune binds and keeps it to a few MB (a bare wgpu window: + // 82.0 MB private bytes with a million, 24.8 MB with 65,536; a bare D3D12 window, 14.1 MB). + let views = MAX_VIEWS.min(adapter_limits.max_non_sampler_bindings); + let required_limits = if adapter_limits.max_inter_stage_shader_variables < wgpu::Limits::default().max_inter_stage_shader_variables + || adapter_limits.max_color_attachments < wgpu::Limits::default().max_color_attachments + || adapter_limits.max_compute_workgroup_storage_size < wgpu::Limits::default().max_compute_workgroup_storage_size + { + wgpu::Limits { + max_immediate_size, + max_non_sampler_bindings: views, + ..wgpu::Limits::downlevel_defaults() + .using_resolution(adapter_limits.clone()) + .using_alignment(adapter_limits) + } + } else { + wgpu::Limits { + max_immediate_size, + max_non_sampler_bindings: views, + ..wgpu::Limits::default() + .using_resolution(adapter_limits.clone()) + .using_alignment(adapter_limits) + } + }; + let made = pollster::block_on(adapter.request_device(&wgpu::DeviceDescriptor { + label: Some("rune"), + required_features, + required_limits, + experimental_features: Default::default(), + // `Performance` suballocates from 128 MB device and 64 MB host blocks, so a device + // that holds a few atlases commits about 190 MB more than it uses: process memory on + // an integrated GPU, and on Windows on a discrete one too. Rune keeps and reuses its + // buffers and textures, so the smaller blocks only cost a few more heaps. + memory_hints: wgpu::MemoryHints::MemoryUsage, + trace: Default::default(), + })) + .map_err(|error| format!("no GPU device: {error}")); + #[cfg(feature = "alloc-sites")] + if let Ok((device, _)) = &made { + report_gpu_allocations(device.clone()); + } + made + } + + #[cfg(target_arch = "wasm32")] + pub fn try_with_features(_: wgpu::Instance, _: Option<&wgpu::Surface<'_>>, _: wgpu::Features) -> Result<Gpu, String> { + Err("synchronous GPU initialization is unsupported on web; use App::run".into()) + } + + #[cfg(target_arch = "wasm32")] + fn try_for(i: wgpu::Instance, s: Option<&wgpu::Surface<'_>>, w: wgpu::Features, _: bool) -> Result<Gpu, String> { Self::try_with_features(i, s, w) } + + pub fn headless() -> Gpu { + Self::new(Self::instance(), None) + } + + /// A headless GPU on wgpu's backends, for tests of what needs wgpu-hal. + #[cfg(test)] + pub(crate) fn headless_wgpu() -> Gpu { + Self::new(Self::wgpu_instance(), None) + } + + /// Without `VALIDATION_INDIRECT_CALL`: Rune issues no indirect draws or dispatches, and the + /// validation pipeline wgpu would build for them costs every device a shader compile (about + /// 40 ms on a Mac's first launch after an install or update). Indirect draws a compositor + /// records on Rune's device still work; wgpu just doesn't check their argument buffers. + pub fn instance() -> wgpu::Instance { + #[cfg(all(target_vendor = "apple", feature = "metal-backend"))] + if crate::gpu::metal::enabled() { return crate::gpu::metal::instance(); } + Self::wgpu_instance() + } + + /// `instance`, or wgpu's when the native Metal backend is only the default and lacks one of + /// the features a compositor wants (`Compositor::features`). + pub(crate) fn instance_for(wanted: wgpu::Features) -> wgpu::Instance { + if crate::gpu::backend::wgpu_for(wanted) { Self::wgpu_instance() } else { Self::instance() } + } + + /// wgpu's own backends, whatever `RUNE_GPU_BACKEND` says: DX12 alone on Windows. It's the + /// backend that composites transparent surfaces, and a Vulkan instance loads every GPU's Vulkan + /// driver, where a broken one (Intel's, on a hybrid laptop) crashed the process before its first + /// window (Hex #662). A machine without a hardware D3D12 adapter gets WARP, D3D12's software + /// adapter, from the same instance. + #[cfg(target_os = "windows")] + fn wgpu_instance() -> wgpu::Instance { + let _serial = GPU_INIT.lock().unwrap_or_else(|e| e.into_inner()); + let instance = Self::wgpu_instance_on(wgpu::Backends::DX12); + crate::marks::mark("gpu.instance"); + instance + } + + /// wgpu's own backends, whatever `RUNE_GPU_BACKEND` says. + #[cfg(not(target_os = "windows"))] + fn wgpu_instance() -> wgpu::Instance { + let _serial = GPU_INIT.lock().unwrap_or_else(|e| e.into_inner()); + Self::wgpu_instance_on(wgpu::Backends::all()) + } + + /// One instance per set of backends for the whole process: a new one per device was a new + /// DXGI factory and adapter list each time a window or overlay made a device (hex#1268). + fn wgpu_instance_on(backends: wgpu::Backends) -> wgpu::Instance { + #[cfg(not(target_arch = "wasm32"))] + { + static MADE: std::sync::Mutex<Vec<(wgpu::Backends, wgpu::Instance)>> = std::sync::Mutex::new(Vec::new()); + let mut made = MADE.lock().unwrap_or_else(|e| e.into_inner()); + if let Some((_, instance)) = made.iter().find(|(made, _)| *made == backends) { return instance.clone(); } + let instance = Self::new_wgpu_instance(backends); + made.push((backends, instance.clone())); + instance + } + #[cfg(target_arch = "wasm32")] + { + // With `wgpu/webgl`, wgpu's wasm handles are single-threaded (`!Send + !Sync`), so + // keep the per-backend instance cache in thread-local storage. + thread_local! { + static MADE: std::cell::RefCell<Vec<(wgpu::Backends, wgpu::Instance)>> = const { std::cell::RefCell::new(Vec::new()) }; + } + MADE.with(|made| { + let mut made = made.borrow_mut(); + if let Some((_, instance)) = made.iter().find(|(made, _)| *made == backends) { return instance.clone(); } + let instance = Self::new_wgpu_instance(backends); + made.push((backends, instance.clone())); + instance + }) + } + } + + fn new_wgpu_instance(backends: wgpu::Backends) -> wgpu::Instance { + let mut descriptor = wgpu::InstanceDescriptor::new_without_display_handle(); + descriptor.backends = backends; + descriptor.flags.remove(wgpu::InstanceFlags::VALIDATION_INDIRECT_CALL); + // An HWND's DXGI swapchain is opaque only; DirectComposition composites alpha on every GPU. + descriptor.backend_options.dx12.presentation_system = wgpu::Dx12SwapchainKind::DxgiFromVisual; + // A window waits for room in its swap chain itself, in the loop rather than in + // `acquire` (`window::slot`). + descriptor.backend_options.dx12.latency_waitable_object = wgpu::Dx12UseFrameLatencyWaitableObject::DontWait; + // FXC ships with Windows (d3dcompiler_47.dll in System32). wgpu's default looks for + // dxcompiler.dll on PATH, where another app's incompatible copy crashes the first + // shader compile (Hex #587). + descriptor.backend_options.dx12.shader_compiler = wgpu::Dx12Compiler::Fxc; + wgpu::Instance::new(descriptor) + } + + /// The GPU for a window's first surface, which `surface` makes from the instance: + /// `prewarm_gpu`'s device, with the renderer it made, when its adapter presents to that + /// surface and has `wanted`'s features; otherwise a new device on the same instance, so the + /// window never gets a second surface. + /// A `translucent` surface gets an adapter that composites translucent pixels when any can. + #[cfg_attr(target_arch = "wasm32", allow(dead_code))] + pub(crate) fn for_surface<'w>(wanted: wgpu::Features, translucent: bool, + surface: impl FnOnce(&wgpu::Instance) -> Result<wgpu::Surface<'w>, String>) -> Result<(Gpu, wgpu::Surface<'w>, Option<Renderer>), String> { + Self::for_surface_from(prewarm::take(), wanted, translucent, surface) + } + + #[cfg_attr(target_arch = "wasm32", allow(dead_code))] + pub(super) fn for_surface_from<'w>(early: Option<(Gpu, Renderer)>, wanted: wgpu::Features, translucent: bool, + surface: impl FnOnce(&wgpu::Instance) -> Result<wgpu::Surface<'w>, String>) -> Result<(Gpu, wgpu::Surface<'w>, Option<Renderer>), String> { + let made = Self::surface_gpu_from(early, wanted, translucent, surface)?; + if std::env::var_os("RUNE_GPU_LOG").is_some_and(|v| v != "0") { + eprintln!("rune: a surface draws with {}", crate::gpu::backend::describe(&made.0.device)); + } + Ok(made) + } + + #[cfg_attr(target_arch = "wasm32", allow(dead_code))] + fn surface_gpu_from<'w>(early: Option<(Gpu, Renderer)>, wanted: wgpu::Features, translucent: bool, + surface: impl FnOnce(&wgpu::Instance) -> Result<wgpu::Surface<'w>, String>) -> Result<(Gpu, wgpu::Surface<'w>, Option<Renderer>), String> { + // A prewarmed native Metal GPU lacking a wanted feature, or one that died since it was + // made, is dropped before it makes a surface. + let Some((early, renderer)) = early.filter(|(gpu, _)| !gpu.is_lost() && crate::gpu::backend::serves(&gpu.device, wanted)) else { + let instance = Self::instance_for(wanted); + let surface = surface(&instance)?; + gpu_events::starting(); + return Ok((Self::try_for(instance, Some(&surface), wanted, translucent)?, surface, None)); + }; + let surface = surface(&early.instance)?; + if crate::render::translucency::serves(&early, &surface, wanted, translucent) { + return Ok((early, surface, Some(renderer))); + } + let instance = early.instance.clone(); + drop((renderer, early)); + gpu_events::starting(); + Ok((Self::try_for(instance, Some(&surface), wanted, translucent)?, surface, None)) + } +} + +/// Starts the GPU device and Rune's render pipeline on a thread, so they're ready when the first +/// window opens instead of being made after AppKit starts, which is most of a first launch after +/// an install or update (when Metal compiles the shaders). Call it first thing in `main`; Rune's +/// run functions call it too, but only once they start the event loop. +/// +/// A window or overlay opened at launch picks the result up, waiting for the thread if it's still working; +/// if none opens, it's dropped. Calling again does nothing. Only on macOS, where any Metal adapter +/// presents to any window; elsewhere the window's surface decides the adapter, and this does +/// nothing. +/// +/// It starts on the backend the app draws with when nothing chose one: Rune's native Metal +/// backend with the `metal-backend` feature (on by default), wgpu without it. An app that opts +/// out with `GpuBackend::Wgpu` should call `prewarm_gpu_on(GpuBackend::Wgpu)` instead, so the +/// thread starts on wgpu rather than on the native backend and starting over. +pub fn prewarm_gpu() { + prewarm::start(); +} + +/// Chooses `backend` (as `App::gpu_backend` does), then starts `prewarm_gpu`'s thread on it, so an +/// app that picks a backend other than the default never prewarms on the default and restarts. +/// `App::gpu_backend` with the same backend afterwards changes nothing. On iOS it only chooses: call +/// it before the first `embed::LayerHost` (and `embed::prewarm`). Elsewhere, or without +/// `metal-backend`, it is `prewarm_gpu`. +pub fn prewarm_gpu_on(backend: crate::GpuBackend) { + choose_then_start(backend, choose_gpu_backend, prewarm::start); +} + +/// `choose` before `start`: a thread started first would run on the old backend. +pub(super) fn choose_then_start(backend: crate::GpuBackend, choose: impl FnOnce(crate::GpuBackend), start: impl FnOnce()) { + choose(backend); + start(); +} + +/// Makes GPUs from now on with `backend`, process-wide, and restarts a `prewarm_gpu` thread +/// running on the old backend. +pub(crate) fn choose_gpu_backend(backend: crate::GpuBackend) { + let changed = crate::gpu::backend::choose(backend); + #[cfg(all(target_os = "macos", feature = "metal-backend"))] + if changed { + prewarm::restart(); + } + #[cfg(not(all(target_os = "macos", feature = "metal-backend")))] + let _ = changed; +} + +/// Drops what `prewarm_gpu` made if no window took it. +pub(crate) fn discard_prewarm() { + #[cfg(not(test))] + prewarm::discard(); +} + +/// With `alloc-sites` (a measuring build), every heap dump also lists what the device holds by kind +/// (`textures <count> <bytes>`, `buffers <count> <bytes>`, views, bind groups, pipelines, command +/// encoders, shader modules, memory allocations) and its suballocator's allocations by label. +#[cfg(all(feature = "alloc-sites", not(target_arch = "wasm32")))] +fn report_gpu_allocations(device: wgpu::Device) { + procwatch::alloc::sites::contribute("gpu", move || { + // What the device holds, by kind (wgpu's counters: committed resources count here too). + let c = device.get_internal_counters().hal; + let mut out = format!( + "textures {} {}\nbuffers {} {}\nviews {}\nbind_groups {}\npipelines {}\nencoders {}\nshader_modules {}\nallocations {}\n", + c.textures.read(), + c.texture_memory.read(), + c.buffers.read(), + c.buffer_memory.read(), + c.texture_views.read(), + c.bind_groups.read(), + c.render_pipelines.read(), + c.command_encoders.read(), + c.shader_modules.read(), + c.memory_allocations.read() + ); + if let Some(r) = device.generate_allocator_report() { + out.push_str(&format!("gpu {} {} {}\n", r.total_allocated_bytes, r.total_reserved_bytes, r.blocks.len())); + for a in &r.allocations { + out.push_str(&format!("alloc {} {}\n", a.size, a.name)); + } + } + out + }); +} diff --git a/app/vendor/rune/crates/rune/src/render/dxbc.rs b/app/vendor/rune/crates/rune/src/render/dxbc.rs new file mode 100644 index 0000000..00c0ec7 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/render/dxbc.rs @@ -0,0 +1,325 @@ +//! Precompiled DX12 bytecode for Rune's uber shader on Windows. +//! +//! wgpu 30's DX12 backend translates `shader.wgsl` through Naga to HLSL and compiles it with +//! FXC each time a device makes the uber pipeline: about 250 ms on a desktop CPU, the largest +//! part of a first surface's cost, and paid again by every new device. Rune ships the bytecode +//! FXC makes from that HLSL for the Windfoil variant (render/variant.rs), the one Windows renderers +//! draw with (`uber.vs.dxbc`, `uber.fs.dxbc`), and loads it with +//! `Device::create_shader_module_passthrough`; the pipeline then takes about 2 ms, as the +//! driver caches its own compile across launches. D3D12 takes FXC's DXBC as it takes DXIL. +//! +//! The bytecode must be what wgpu itself would compile: the same HLSL, whose register +//! assignments wgpu's root signature for the uber layout expects. `uber_dxbc_is_fresh` +//! (Windows) compares the HLSL wgpu generates now with the HLSL the general and subpixel bytecode +//! came from, and `cargo run -p rune --example regen_dxbc` rewrites everything, the pinned fragments +//! (`uber.fs-k0/k1/k2.dxbc`) and the hash of the WGSL each came from included: no other path writes +//! those, and a pinned fragment is used only while the build finds that WGSL and those files (`PINNED_FRESH`). The +//! bytecode is used only while the WGSL hashes as it did when it was compiled, which the build +//! knows (`build.rs` hashes the WGSL with `\r\n` read as `\n`, so a CRLF checkout matches too, and +//! warns when it doesn't match), and while the layout hashes the same. A launch that can't use it +//! says why once; a pipeline the driver refuses falls back to WGSL. + +#[cfg(target_os = "windows")] +include!("uber/dxbc_hash.rs"); +#[cfg(target_os = "windows")] +include!("uber/dxbc_pinned_hash.rs"); + +#[cfg(target_os = "windows")] +const VERTEX: &[u8] = include_bytes!("../../shaders/dxbc/uber.vs.dxbc"); +#[cfg(target_os = "windows")] +const FRAGMENT: &[u8] = include_bytes!("../../shaders/dxbc/uber.fs.dxbc"); +/// The subpixel variant's stages (render/variant.rs `dual_wgsl`), whose fragment blends by a +/// second output. FXC takes about a minute for it, so a window drawing subpixel text froze that +/// long compiling it. +#[cfg(target_os = "windows")] +const VERTEX_DUAL: &[u8] = include_bytes!("../../shaders/dxbc/uber.vs-dual.dxbc"); +#[cfg(target_os = "windows")] +const FRAGMENT_DUAL: &[u8] = include_bytes!("../../shaders/dxbc/uber.fs-dual.dxbc"); +/// The fragment stage pinned to one kind each (render/variant.rs `pinned_wgsl`, `PINNED`), beside the +/// shared vertex stage: the frame pass's pipelines for rects, shadows and glyphs. +#[cfg(target_os = "windows")] +const FRAGMENT_PINNED: [&[u8]; 3] = [ + include_bytes!("../../shaders/dxbc/uber.fs-k0.dxbc"), + include_bytes!("../../shaders/dxbc/uber.fs-k1.dxbc"), + include_bytes!("../../shaders/dxbc/uber.fs-k2.dxbc"), +]; +// `FRAGMENT_PINNED` is in `PINNED`'s order and its files are named by kind: the two must agree. +#[cfg(target_os = "windows")] +const _: () = assert!(super::variant::PINNED[0] == 0 && super::variant::PINNED[1] == 1 && super::variant::PINNED[2] == 2, + "render/variant.rs PINNED changed: name FRAGMENT_PINNED's files after it and run regen_dxbc"); + +// The built-in passes besides the uber shader, compiled by regen_dxbc from their WGSL as wgpu +// would, and the BLAKE3 of the WGSL each came from (`uber/pass_dxbc_hash.rs`). +#[cfg(target_os = "windows")] +include!("uber/pass_dxbc_hash.rs"); +#[cfg(target_os = "windows")] +const ALPHA_VERTEX: &[u8] = include_bytes!("../../shaders/dxbc/alpha.vs.dxbc"); +#[cfg(target_os = "windows")] +const ALPHA_FRAGMENT: &[u8] = include_bytes!("../../shaders/dxbc/alpha.fs.dxbc"); +#[cfg(target_os = "windows")] +const LAYER_BLUR_VERTEX: &[u8] = include_bytes!("../../shaders/dxbc/layer_blur.vs.dxbc"); +#[cfg(target_os = "windows")] +const BACKDROP_BLUR: [&[u8]; 3] = [ + include_bytes!("../../shaders/dxbc/backdrop_blur.vs.dxbc"), + include_bytes!("../../shaders/dxbc/backdrop_blur.fs_down.dxbc"), + include_bytes!("../../shaders/dxbc/backdrop_blur.fs_up.dxbc"), +]; +#[cfg(target_os = "windows")] +const BACKDROP_COMPOSITE: [&[u8]; 2] = [ + include_bytes!("../../shaders/dxbc/backdrop_composite.vs.dxbc"), + include_bytes!("../../shaders/dxbc/backdrop_composite.fs.dxbc"), +]; +#[cfg(target_os = "windows")] +const LAYER_BLUR_FRAGMENTS: [&[u8]; 5] = [ + include_bytes!("../../shaders/dxbc/layer_blur.fs0.dxbc"), + include_bytes!("../../shaders/dxbc/layer_blur.fs1.dxbc"), + include_bytes!("../../shaders/dxbc/layer_blur.fs2.dxbc"), + include_bytes!("../../shaders/dxbc/layer_blur.fs3.dxbc"), + include_bytes!("../../shaders/dxbc/layer_blur.fs4.dxbc"), +]; + +/// The uber shader's modules: one WGSL (or metallib) module for both stages, or one +/// precompiled module per stage. +#[derive(Clone)] +pub(crate) struct Shaders { + pub vertex: wgpu::ShaderModule, + pub fragment: wgpu::ShaderModule, +} + +impl Shaders { + pub(crate) fn one(module: wgpu::ShaderModule) -> Self { + Self { vertex: module.clone(), fragment: module } + } +} + +/// What a caller does when its precompiled shader is refused: makes it from WGSL. +#[cfg(target_os = "windows")] +const WGSL: &str = "compiling WGSL"; + +/// Whether the bytecode was compiled from the WGSL this build joined (render/uber_wgsl.rs). +#[cfg(target_os = "windows")] +const WGSL_MATCHES: bool = super::uber_wgsl::same(super::uber_wgsl::WINDFOIL_BLAKE3, UBER_DXBC_WGSL_BLAKE3); + +/// Whether it was compiled for Windfoil's pipeline layout as this build has it. +#[cfg(target_os = "windows")] +const ABI_MATCHES: bool = super::variant::windfoil_abi_hash() == UBER_DXBC_ABI_FNV64; + +// A build whose layout isn't the bytecode's warns, as build.rs does for the WGSL. +#[cfg(target_os = "windows")] +const _: () = Layout::<ABI_MATCHES>::check(); + +#[cfg(target_os = "windows")] +struct Layout<const MATCHES: bool>; + +#[cfg(target_os = "windows")] +#[allow(dead_code)] +impl Layout<true> { + const fn check() {} +} + +#[cfg(target_os = "windows")] +#[allow(dead_code)] +impl Layout<false> { + #[deprecated(note = "the precompiled DX12 uber shader was compiled for another pipeline layout, so it isn't used: \ + run `cargo run -p rune --example regen_dxbc` on Windows")] + const fn check() {} +} + +/// The precompiled Windfoil uber shader and its pipeline on a DX12 device, when the bytecode +/// matches Windfoil's WGSL and layout and the driver takes it. +#[cfg(target_os = "windows")] +pub(super) fn uber<T>(device: &wgpu::Device, make_pipeline: impl FnOnce(&Shaders) -> T) -> Option<(Shaders, T)> { + load(device, (VERTEX, FRAGMENT), "uber", uber_fresh, WGSL, make_pipeline) +} + +/// [`uber`] for the subpixel variant. +#[cfg(target_os = "windows")] +pub(super) fn uber_dual<T>(device: &wgpu::Device, make_pipeline: impl FnOnce(&Shaders) -> T) -> Option<(Shaders, T)> { + load(device, (VERTEX_DUAL, FRAGMENT_DUAL), "subpixel uber", uber_fresh, WGSL, make_pipeline) +} + +/// [`uber`] pinned to `KIND_*` `kind` (render/variant.rs `PINNED`): the shared vertex stage and that kind's fragment, +/// only while that fragment was compiled from the WGSL `pinned_wgsl(kind)` gives now (`pinned_fresh`). A stale one +/// isn't used: the general shader draws the kind. +#[cfg(target_os = "windows")] +pub(super) fn uber_pinned<T>(device: &wgpu::Device, kind: u32, make_pipeline: impl FnOnce(&Shaders) -> T) -> Option<(Shaders, T)> { + let at = super::variant::PINNED.iter().position(|&k| k == kind)?; + let fragment = Some(FRAGMENT_PINNED[at]).filter(|f| !f.is_empty())?; + load(device, (VERTEX, fragment), "pinned uber", || uber_fresh() && pinned_fresh(at, kind), "the general shader draws that kind", make_pipeline) +} + +/// Whether each pinned fragment (`PINNED` order) is the one `regen_dxbc` compiled from this build's WGSL beside this +/// build's vertex stage: the WGSL hash and both files' BLAKE3 that build.rs takes (render/uber_wgsl.rs) against what +/// `regen_dxbc` recorded with them (`uber/dxbc_pinned_hash.rs`). Settled at compile time, so nothing is hashed at run +/// time. A fragment left by another shader or beside a regenerated vertex stage (which is how a wgpu or Naga upgrade +/// shows), a hand-edited hash or a swapped file all fail it, and the general shader draws that kind. +#[cfg(target_os = "windows")] +const PINNED_FRESH: [bool; 3] = { + use super::uber_wgsl::same; + let mut fresh = [false; 3]; + let mut at = 0; + while at < 3 { + fresh[at] = same(super::uber_wgsl::PINNED_WGSL_BLAKE3[at], UBER_DXBC_PINNED_WGSL_BLAKE3[at]) + && same(super::uber_wgsl::PINNED_FS_BLAKE3[at], UBER_DXBC_PINNED_FS_BLAKE3[at]) + && same(super::uber_wgsl::PINNED_VS_BLAKE3, UBER_DXBC_PINNED_VS_BLAKE3); + at += 1; + } + fresh +}; + +/// [`PINNED_FRESH`] for the fragment at `at`; says once for each stale kind (build.rs warns too). +#[cfg(target_os = "windows")] +fn pinned_fresh(at: usize, kind: u32) -> bool { + if !PINNED_FRESH[at] { + static STALE: std::sync::Mutex<Vec<u32>> = std::sync::Mutex::new(Vec::new()); + let mut said = STALE.lock().unwrap_or_else(|e| e.into_inner()); + if !said.contains(&kind) { + said.push(kind); + eprintln!("rune: the precompiled DX12 fragment pinned to kind {kind} (uber.fs-k{kind}.dxbc) wasn't compiled from this shader beside this vertex stage, so the general shader draws that kind (scrolling on the slow path); rebuild it with `cargo run -p rune --example regen_dxbc` on Windows"); + } + } + PINNED_FRESH[at] +} +/// The straight-alpha pass (render/surface_alpha.rs) from its precompiled stages, when they were +/// compiled from `wgsl` and the driver takes them. +#[cfg(target_os = "windows")] +pub(super) fn surface_alpha<T>(device: &wgpu::Device, wgsl: &str, make_pipeline: impl FnOnce(&Shaders) -> T) -> Option<(Shaders, T)> { + load(device, (ALPHA_VERTEX, ALPHA_FRAGMENT), "straight alpha", || compiled_from(wgsl, ALPHA_DXBC_WGSL_BLAKE3, "straight alpha"), WGSL, make_pipeline) +} + +/// Whether a pass's bytecode came from `wgsl` (its `\r\n` read as `\n`, as build.rs reads the +/// uber shader's); says so when it didn't. +#[cfg(target_os = "windows")] +fn compiled_from(wgsl: &str, recorded: &str, what: &str) -> bool { + let now = blake3::hash(wgsl.replace("\r\n", "\n").as_bytes()).to_hex(); + if now.as_str() == recorded { return true; } + eprintln!("rune: the precompiled DX12 {what} shader was built from other WGSL (blake3 {recorded}, now {now}); compiling WGSL. Rebuild it with `cargo run -p rune --example regen_dxbc` on Windows"); + false +} + +#[cfg(target_os = "windows")] +fn load<T>(device: &wgpu::Device, (vertex, fragment): (&'static [u8], &'static [u8]), what: &str, fresh: impl FnOnce() -> bool, otherwise: &str, + make_pipeline: impl FnOnce(&Shaders) -> T) -> Option<(Shaders, T)> { + load_modules(device, &[(vertex, "vs"), (fragment, "fs")], what, fresh, otherwise, |modules| { + let shaders = Shaders { vertex: modules[0].clone(), fragment: modules[1].clone() }; + let pipeline = make_pipeline(&shaders); + (shaders, pipeline) + }) +} + +/// Makes a passthrough module from each `(bytecode, entry point)` and hands them to +/// `make_pipelines`, when this is a DX12 device that takes bytecode and `fresh` says it's this +/// build's; `None` (so the caller does `otherwise`, which a refusal names) when not, or when the driver refuses it. +#[cfg(target_os = "windows")] +#[allow(unsafe_code)] +fn load_modules<T>(device: &wgpu::Device, blobs: &[(&'static [u8], &'static str)], what: &str, fresh: impl FnOnce() -> bool, otherwise: &str, + make_pipelines: impl FnOnce(&[wgpu::ShaderModule]) -> T) -> Option<T> { + if device.adapter_info().backend != wgpu::Backend::Dx12 || !device.features().contains(wgpu::Features::PASSTHROUGH_SHADERS) || !enabled() { + return None; + } + if !fresh() { return None; } + let module = |blob: &'static [u8], entry: &'static str| { + // SAFETY: the bytecode is FXC's compile of the HLSL wgpu generates for this pass's WGSL with + // its layout (regen_dxbc; `fresh` checked it's that WGSL), so it binds what the layout declares. + unsafe { + device.create_shader_module_passthrough(wgpu::ShaderModuleDescriptorPassthrough { + label: Some(what), + entry_points: std::borrow::Cow::Owned(vec![wgpu::PassthroughShaderEntryPoint { name: entry.into(), workgroup_size: (0, 0, 0) }]), + dxil: Some(std::borrow::Cow::Borrowed(blob)), + ..Default::default() + }) + } + }; + let modules: Vec<wgpu::ShaderModule> = blobs.iter().map(|&(blob, entry)| module(blob, entry)).collect(); + checked(device, what, otherwise, || make_pipelines(&modules)) +} + +/// `make`'s pipelines from precompiled modules, or `None` (said once on stderr, with what the +/// caller does `otherwise`) when the driver refuses them. +#[cfg(target_os = "windows")] +pub(super) fn checked<T>(device: &wgpu::Device, what: &str, otherwise: &str, make: impl FnOnce() -> T) -> Option<T> { + let validation = device.push_error_scope(wgpu::ErrorFilter::Validation); + let internal = device.push_error_scope(wgpu::ErrorFilter::Internal); + let made = make(); + let refused = pollster::block_on(internal.pop()).or(pollster::block_on(validation.pop())); + match refused { + None => Some(made), + Some(error) => { + eprintln!("rune: the precompiled {what} shader was refused ({error}); {otherwise}"); + None + } + } +} + +/// The backdrop blur's down and up passes (render/backdrop_blur.rs): its vertex stage and its +/// `fs_down` and `fs_up` fragment stages, when they were compiled from `wgsl`. +#[cfg(target_os = "windows")] +pub(super) fn backdrop_blur<T>(device: &wgpu::Device, wgsl: &str, make_pipelines: impl FnOnce(&[wgpu::ShaderModule]) -> T) -> Option<T> { + let blobs = [(BACKDROP_BLUR[0], "vs"), (BACKDROP_BLUR[1], "fs_down"), (BACKDROP_BLUR[2], "fs_up")]; + load_modules(device, &blobs, "backdrop blur", || compiled_from(wgsl, BACKDROP_BLUR_DXBC_WGSL_BLAKE3, "backdrop blur"), WGSL, make_pipelines) +} + +/// The backdrop blur's composite stages, which bind the uber shader's group 0: when they were +/// compiled from `wgsl` and for this build's uber layout. Its pipelines are made per target format +/// later, each through [`checked`]. +#[cfg(target_os = "windows")] +pub(super) fn backdrop_composite(device: &wgpu::Device, wgsl: &str) -> Option<Shaders> { + let fresh = || ABI_MATCHES && compiled_from(wgsl, BACKDROP_COMPOSITE_DXBC_WGSL_BLAKE3, "backdrop blur composite"); + load_modules(device, &[(BACKDROP_COMPOSITE[0], "vs"), (BACKDROP_COMPOSITE[1], "fs")], "backdrop blur composite", fresh, WGSL, + |m| Shaders { vertex: m[0].clone(), fragment: m[1].clone() }) +} + +/// The layer blur's vertex stage and its five fragment variants (render/layer_blur.rs `MODES`, the +/// WGSL's `MODE` and `ADDITIVE` overrides each compiled in), when they were compiled from `wgsl`. +#[cfg(target_os = "windows")] +pub(super) fn layer_blur<T>(device: &wgpu::Device, wgsl: &str, make_pipelines: impl FnOnce(&[wgpu::ShaderModule]) -> T) -> Option<T> { + let blobs = [(LAYER_BLUR_VERTEX, "vs"), (LAYER_BLUR_FRAGMENTS[0], "fs"), (LAYER_BLUR_FRAGMENTS[1], "fs"), (LAYER_BLUR_FRAGMENTS[2], "fs"), + (LAYER_BLUR_FRAGMENTS[3], "fs"), (LAYER_BLUR_FRAGMENTS[4], "fs")]; + load_modules(device, &blobs, "layer gaussian", || compiled_from(wgsl, LAYER_BLUR_DXBC_WGSL_BLAKE3, "layer gaussian"), WGSL, make_pipelines) +} +/// Whether the uber bytecode matches this build's Windfoil WGSL and layout; says why once when not. +#[cfg(target_os = "windows")] +fn uber_fresh() -> bool { + if !WGSL_MATCHES || !ABI_MATCHES { stale(); } + WGSL_MATCHES && ABI_MATCHES +} + +/// Says once why the shipped bytecode can't be used, and how to rebuild it. +#[cfg(target_os = "windows")] +fn stale() { + static ONCE: std::sync::Once = std::sync::Once::new(); + ONCE.call_once(|| { + let why = if WGSL_MATCHES { + format!("the uber pipeline layout changed (it hashes {:#018x}; the bytecode's was {UBER_DXBC_ABI_FNV64:#018x})", super::variant::windfoil_abi_hash()) + } else { + format!("the WGSL changed (blake3 {}; the bytecode's was {UBER_DXBC_WGSL_BLAKE3})", super::uber_wgsl::WINDFOIL_BLAKE3) + }; + eprintln!("rune: the precompiled DX12 uber shader doesn't match this build: {why}. FXC compiles the WGSL instead, \ + which takes seconds on every launch; rebuild the bytecode with `cargo run -p rune --example regen_dxbc` on Windows"); + }); +} + +#[cfg(target_os = "windows")] +std::thread_local! { + static FORCE: std::cell::Cell<Option<bool>> = const { std::cell::Cell::new(None) }; +} + +/// `RUNE_DISABLE_DXBC=1` compiles the WGSL instead, as before. +#[cfg(target_os = "windows")] +fn enabled() -> bool { + FORCE.with(std::cell::Cell::get).unwrap_or_else(|| !rune_core::env::flag("RUNE_DISABLE_DXBC")) +} + +#[cfg(all(test, target_os = "windows"))] +pub(super) fn with_dxbc_enabled<R>(enabled: bool, f: impl FnOnce() -> R) -> R { + struct Restore(Option<bool>); + impl Drop for Restore { + fn drop(&mut self) { FORCE.with(|c| c.set(self.0)); } + } + let _restore = Restore(FORCE.with(|c| c.replace(Some(enabled)))); + f() +} + +#[cfg(all(test, target_os = "windows"))] +#[path = "dxbc_tests.rs"] +mod tests; diff --git a/app/vendor/rune/crates/rune/src/render/dxbc_tests.rs b/app/vendor/rune/crates/rune/src/render/dxbc_tests.rs new file mode 100644 index 0000000..ddb745f --- /dev/null +++ b/app/vendor/rune/crates/rune/src/render/dxbc_tests.rs @@ -0,0 +1,193 @@ +//! The precompiled DX12 shaders are FXC's compile of the HLSL wgpu generates today. Run +//! `cargo run -p rune --example regen_dxbc` on Windows to rewrite all bytecode and hashes after +//! the WGSL, the uber layout or wgpu changes. + +#![allow(unsafe_code)] + +use std::sync::{Mutex, OnceLock}; + +/// HLSL wgpu-hal logged at debug level, with the thread that logged it. +static HLSL: Mutex<Vec<(std::thread::ThreadId, String)>> = Mutex::new(Vec::new()); + +struct Capture; + +impl log::Log for Capture { + fn enabled(&self, metadata: &log::Metadata) -> bool { metadata.target().starts_with("wgpu_hal") } + fn log(&self, record: &log::Record) { + let text = record.args().to_string(); + if text.starts_with("Naga generated shader for") { + HLSL.lock().unwrap().push((std::thread::current().id(), text)); + } + } + fn flush(&self) {} +} + +fn capture() { + static INSTALLED: OnceLock<()> = OnceLock::new(); + INSTALLED.get_or_init(|| { + log::set_logger(&Capture).expect("no other test installs a logger"); + log::set_max_level(log::LevelFilter::Debug); + }); +} + +#[link(name = "d3dcompiler")] +unsafe extern "system" { + fn D3DCompile(source: *const u8, len: usize, name: *const i8, defines: *const u8, include: *mut u8, + entry: *const i8, target: *const i8, flags1: u32, flags2: u32, code: *mut *mut Blob, errors: *mut *mut Blob) -> i32; +} + +#[repr(C)] +struct Blob { vtbl: *const BlobVtbl } + +#[repr(C)] +struct BlobVtbl { + _query_interface: usize, + _add_ref: usize, + release: unsafe extern "system" fn(*mut Blob) -> u32, + pointer: unsafe extern "system" fn(*mut Blob) -> *const u8, + size: unsafe extern "system" fn(*mut Blob) -> usize, +} + +/// FXC as wgpu-hal calls it: strictness only, shader model 5.1. +fn fxc(source: &str, entry: &str, target: &str) -> Vec<u8> { + const D3DCOMPILE_ENABLE_STRICTNESS: u32 = 1 << 11; + let entry = std::ffi::CString::new(entry).unwrap(); + let target = std::ffi::CString::new(target).unwrap(); + let (mut code, mut errors) = (std::ptr::null_mut(), std::ptr::null_mut()); + // SAFETY: D3DCompile reads `source` and fills two COM blobs, each read and released once. + unsafe { + let hr = D3DCompile(source.as_ptr(), source.len(), std::ptr::null(), std::ptr::null(), std::ptr::null_mut(), + entry.as_ptr(), target.as_ptr(), D3DCOMPILE_ENABLE_STRICTNESS, 0, &mut code, &mut errors); + let read = |blob: *mut Blob| { + let bytes = std::slice::from_raw_parts(((*(*blob).vtbl).pointer)(blob), ((*(*blob).vtbl).size)(blob)).to_vec(); + ((*(*blob).vtbl).release)(blob); + bytes + }; + if hr < 0 { + panic!("FXC failed ({hr:#x}): {}", String::from_utf8_lossy(&read(errors))); + } + if !errors.is_null() { read(errors); } + read(code) + } +} + +fn logged_here() -> Vec<String> { + let me = std::thread::current().id(); + HLSL.lock().unwrap().iter().filter(|(thread, _)| *thread == me).map(|(_, text)| text.clone()).collect() +} + +fn stage(logged: &[String], name: &str) -> String { + let prefix = format!("Naga generated shader for \"{name}\""); + let text = logged.iter().rev().find(|text| text.starts_with(&prefix)) + .unwrap_or_else(|| panic!("wgpu logged no HLSL for {name}: is the device DX12 with FXC?")); + text.split_once(":\n").unwrap().1.to_owned() +} + +fn stages(logged: &[String], name: &str) -> Vec<String> { + let prefix = format!("Naga generated shader for \"{name}\""); + logged.iter().filter(|text| text.starts_with(&prefix)).map(|text| text.split_once(":\n").unwrap().1.to_owned()).collect() +} + +fn hlsl_hash(vertex: &str, fragment: &str) -> String { + blake3::hash(format!("{vertex}\0{fragment}").as_bytes()).to_hex().to_string() +} + +fn wgsl_hash(wgsl: &str) -> String { + blake3::hash(wgsl.replace("\r\n", "\n").as_bytes()).to_hex().to_string() +} + +const STALE: &str = "precompiled DX12 shaders are stale: run `cargo run -p rune --example regen_dxbc` on Windows"; + +#[test] +fn uber_dxbc_is_fresh() { + capture(); + let gpu = crate::render::Gpu::headless(); + let start = logged_here().len(); + let mut renderer = super::with_dxbc_enabled(false, || crate::render::Renderer::new(&gpu.device, wgpu::TextureFormat::Bgra8Unorm)); + let uber_end = logged_here().len(); + renderer.compile_subpixel_now(&gpu.device).expect("the subpixel pipeline compiles"); + let dual_end = logged_here().len(); + let mut pinned_spans = Vec::new(); + for &kind in &crate::render::PINNED_KINDS { + let from = logged_here().len(); + renderer.compile_pinned_now(&gpu.device, kind).expect("the pinned pipeline compiles"); + pinned_spans.push((kind, from, logged_here().len())); + } + let logged = logged_here(); + let (vertex, fragment) = (stage(&logged[start..uber_end], "vs"), stage(&logged[start..uber_end], "fs")); + let (dual_vertex, dual_fragment) = (stage(&logged[uber_end..dual_end], "vs"), stage(&logged[uber_end..dual_end], "fs")); + let (vs, fs) = (fxc(&vertex, "vs", "vs_5_1"), fxc(&fragment, "fs", "ps_5_1")); + let (vs_dual, fs_dual) = (fxc(&dual_vertex, "vs", "vs_5_1"), fxc(&dual_fragment, "fs", "ps_5_1")); + let (_, wgsl, abi) = crate::render::uber_shader_identity(); + let hlsl = hlsl_hash(&vertex, &fragment); + let dual = hlsl_hash(&dual_vertex, &dual_fragment); + assert_eq!(wgsl, super::UBER_DXBC_WGSL_BLAKE3, "{STALE}"); + assert_eq!(abi, super::UBER_DXBC_ABI_FNV64, "{STALE}"); + assert_eq!(hlsl, super::UBER_DXBC_HLSL_BLAKE3, "{STALE}"); + assert_eq!(dual, super::UBER_DXBC_DUAL_HLSL_BLAKE3, "{STALE}"); + assert!(vs == super::VERTEX && fs == super::FRAGMENT && vs_dual == super::VERTEX_DUAL && fs_dual == super::FRAGMENT_DUAL, "{STALE}"); + assert_eq!(super::PINNED_FRESH, [true; 3], "{STALE}"); + assert_eq!(blake3::hash(&vs).to_hex().as_str(), super::UBER_DXBC_PINNED_VS_BLAKE3, "{STALE}"); + for (at, &(kind, from, to)) in pinned_spans.iter().enumerate() { + let fs_pinned = fxc(&stage(&logged[from..to], "fs"), "fs", "ps_5_1"); + assert_eq!(crate::render::pinned_wgsl_blake3(kind).as_deref(), Some(super::UBER_DXBC_PINNED_WGSL_BLAKE3[at]), "pinned kind {kind}: {STALE}"); + assert_eq!(blake3::hash(&fs_pinned).to_hex().as_str(), super::UBER_DXBC_PINNED_FS_BLAKE3[at], "pinned kind {kind}: {STALE}"); + assert!(fs_pinned == super::FRAGMENT_PINNED[at], "uber.fs-k{kind}.dxbc: {STALE}"); + } +} + +#[test] +fn pass_dxbc_is_fresh() { + capture(); + let gpu = crate::render::Gpu::headless(); + + assert_eq!(wgsl_hash(crate::render::surface_alpha::WGSL), super::ALPHA_DXBC_WGSL_BLAKE3, "surface_alpha: {STALE}"); + let start = logged_here().len(); + super::with_dxbc_enabled(false, || crate::render::make_straight_alpha(&gpu.device, wgpu::TextureFormat::Bgra8Unorm)); + let logged = logged_here(); + let (alpha_vs, alpha_fs) = (fxc(&stage(&logged[start..], "vs"), "vs", "vs_5_1"), fxc(&stage(&logged[start..], "fs"), "fs", "ps_5_1")); + assert!(alpha_vs == super::ALPHA_VERTEX && alpha_fs == super::ALPHA_FRAGMENT, "alpha.dxbc: {STALE}"); + + assert_eq!(wgsl_hash(crate::render::layer_blur::WGSL), super::LAYER_BLUR_DXBC_WGSL_BLAKE3, "layer_blur: {STALE}"); + let start = logged_here().len(); + super::with_dxbc_enabled(false, || crate::render::make_layer_blur(&gpu.device)); + let logged = logged_here(); + let blur_vs = fxc(&stage(&logged[start..], "vs"), "vs", "vs_5_1"); + let blur_fragments = stages(&logged[start..], "fs"); + assert_eq!(blur_fragments.len(), super::LAYER_BLUR_FRAGMENTS.len(), "layer_blur pipelines: {STALE}"); + assert!(blur_vs == super::LAYER_BLUR_VERTEX, "layer_blur.vs.dxbc: {STALE}"); + for (i, hlsl) in blur_fragments.iter().enumerate() { + assert!(fxc(hlsl, "fs", "ps_5_1") == super::LAYER_BLUR_FRAGMENTS[i], "layer_blur.fs{i}.dxbc: {STALE}"); + } + + assert_eq!(wgsl_hash(crate::render::backdrop_blur::BLUR_WGSL), super::BACKDROP_BLUR_DXBC_WGSL_BLAKE3, "backdrop_blur: {STALE}"); + assert_eq!(wgsl_hash(&crate::render::backdrop_blur::composite_wgsl()), super::BACKDROP_COMPOSITE_DXBC_WGSL_BLAKE3, "backdrop_composite: {STALE}"); + let renderer = crate::render::Renderer::new(&gpu.device, wgpu::TextureFormat::Bgra8Unorm); + let start = logged_here().len(); + super::with_dxbc_enabled(false, || renderer.make_backdrop_blur(&gpu.device)); + let logged = logged_here(); + let (vertices, down, up, fragments) = (stages(&logged[start..], "vs"), stages(&logged[start..], "fs_down"), stages(&logged[start..], "fs_up"), stages(&logged[start..], "fs")); + assert!(vertices.len() >= 2 && down.len() == 1 && up.len() == 1 && fragments.len() == 1); + assert!(fxc(&vertices[0], "vs", "vs_5_1") == super::BACKDROP_BLUR[0], "backdrop_blur.vs.dxbc: {STALE}"); + assert!(fxc(&down[0], "fs_down", "ps_5_1") == super::BACKDROP_BLUR[1], "backdrop_blur.fs_down.dxbc: {STALE}"); + assert!(fxc(&up[0], "fs_up", "ps_5_1") == super::BACKDROP_BLUR[2], "backdrop_blur.fs_up.dxbc: {STALE}"); + assert!(fxc(vertices.last().unwrap(), "vs", "vs_5_1") == super::BACKDROP_COMPOSITE[0], "backdrop_composite.vs.dxbc: {STALE}"); + assert!(fxc(&fragments[0], "fs", "ps_5_1") == super::BACKDROP_COMPOSITE[1], "backdrop_composite.fs.dxbc: {STALE}"); +} + +/// A DX12 device loads every precompiled shader (general uber, pinned kinds and built-in passes), +/// and without the passthrough path compiles the WGSL. +#[test] +fn renderers_load_the_precompiled_uber_shader() { + let gpu = crate::render::Gpu::headless(); + assert!(super::uber(&gpu.device, |_| ()).is_some(), "a DX12 device takes the uber bytecode"); + for &kind in &crate::render::PINNED_KINDS { + assert!(super::uber_pinned(&gpu.device, kind, |_| ()).is_some(), "pinned kind {kind} loads"); + } + assert!(super::surface_alpha(&gpu.device, crate::render::surface_alpha::WGSL, |_| ()).is_some(), "straight alpha loads"); + assert!(super::layer_blur(&gpu.device, crate::render::layer_blur::WGSL, |_| ()).is_some(), "layer blur loads"); + assert!(super::backdrop_blur(&gpu.device, crate::render::backdrop_blur::BLUR_WGSL, |_| ()).is_some(), "backdrop blur loads"); + assert!(super::backdrop_composite(&gpu.device, &crate::render::backdrop_blur::composite_wgsl()).is_some(), "backdrop composite loads"); + assert!(super::with_dxbc_enabled(false, || super::uber(&gpu.device, |_| ())).is_none()); + drop(crate::render::Renderer::new(&gpu.device, wgpu::TextureFormat::Bgra8Unorm)); +} diff --git a/app/vendor/rune/crates/rune/src/render/fill.rs b/app/vendor/rune/crates/rune/src/render/fill.rs new file mode 100644 index 0000000..1c49dbd --- /dev/null +++ b/app/vendor/rune/crates/rune/src/render/fill.rs @@ -0,0 +1,271 @@ +//! Filling atlas masks on the GPU (`text::atlas_fill`): each queued mask is a Windfoil glyph +//! instance drawn into its page, R8, replacing what was there, by the uber shader that draws +//! moving text from outlines, so a mask and its glyph in motion share one coverage function. + +use super::*; +use crate::text::QueuedFill; + +/// The fill pass's pipeline and what it draws with: the outline store, stand-ins for the atlas +/// and images (a page can't be read while it's drawn into), and a page-sized projection. +pub(super) struct FillPass { + pipeline: wgpu::RenderPipeline, + projection: wgpu::Buffer, + /// `projection` for each page height, copied in before each page's pass. + projections: wgpu::Buffer, + bind: wgpu::BindGroup, + instances: rune_staging::GrowBuffer, +} + +/// What a fill pass binds besides its own buffers. +pub(super) struct FillBindings<'a> { + pub layout: &'a wgpu::BindGroupLayout, + pub globals: &'a wgpu::Buffer, + pub outlines: &'a wgpu::Texture, + pub stand_in: &'a wgpu::Texture, +} + +impl FillPass { + pub(super) fn new(device: &wgpu::Device, layout: &wgpu::PipelineLayout, shader: &dxbc::Shaders, bindings: FillBindings<'_>) -> FillPass { + let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { + label: Some("atlas fill"), + layout: Some(layout), + vertex: wgpu::VertexState { + module: &shader.vertex, + entry_point: Some("vs"), + compilation_options: Default::default(), + buffers: &[Some(metallib::uber_vertex_layout())], + }, + primitive: metallib::uber_primitive(), + depth_stencil: None, + multisample: Default::default(), + fragment: Some(wgpu::FragmentState { + module: &shader.fragment, + entry_point: Some("fs"), + compilation_options: Default::default(), + targets: &[Some(wgpu::ColorTargetState { format: wgpu::TextureFormat::R8Unorm, blend: None, write_mask: wgpu::ColorWrites::ALL })], + }), + multiview_mask: None, + cache: None, + }); + let projection = device.create_buffer(&wgpu::BufferDescriptor { + label: Some("atlas fill projection"), size: 16, usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, mapped_at_creation: false, + }); + // One projection per page height a page can have (`ATLAS_START_ROWS` doubling up to + // `ATLAS_SIZE`): each pass copies its page's into `projection` first. + let heights: Vec<f32> = std::iter::successors(Some(ATLAS_START_ROWS), |h| (*h < ATLAS_SIZE).then_some(h * 2)).map(|h| h as f32).collect(); + let projections = device.create_buffer(&wgpu::BufferDescriptor { + label: Some("atlas fill projections"), size: 16 * heights.len() as u64, usage: wgpu::BufferUsages::COPY_SRC, mapped_at_creation: true, + }); + if let Ok(mut range) = projections.slice(..).get_mapped_range_mut() { + let all: Vec<f32> = heights.iter().flat_map(|h| [0.0, 0.0, ATLAS_SIZE as f32, *h]).collect(); + range.copy_from_slice(bytemuck::cast_slice(&all)); + } + projections.unmap(); + let bind = Self::bind(device, &bindings, &projection); + let instances = rune_staging::GrowBuffer::new( + device, + "instances", + wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST, + std::mem::size_of::<Instance>(), + 64, + 0, + ); + FillPass { pipeline, projection, projections, bind, instances } + } + + fn bind(device: &wgpu::Device, b: &FillBindings<'_>, projection: &wgpu::Buffer) -> wgpu::BindGroup { + Renderer::bind_group(device, b.layout, b.globals, Some(b.outlines), b.stand_in, b.stand_in, Some(projection)) + } + + /// Binds a new outline texture. + pub(super) fn rebind(&mut self, device: &wgpu::Device, bindings: FillBindings<'_>) { + self.bind = Self::bind(device, &bindings, &self.projection); + } + + /// Writes the instances of `pages`' fills through `staging`, for [`FillPass::encode`]: the + /// instance range each page draws. + fn stage(&mut self, device: &wgpu::Device, staging: &rune_staging::Staging, pages: &[(usize, Vec<QueuedFill>)]) -> Vec<(usize, std::ops::Range<u32>)> { + let count: usize = pages.iter().map(|(_, f)| f.len()).sum(); + self.instances.ensure(device, count); + let instances: Vec<Instance> = pages.iter().flat_map(|(_, fills)| fills.iter().map(instance)).collect(); + staging.write_buffer(self.instances.buffer(), 0, bytemuck::cast_slice(&instances)); + let mut first = 0u32; + pages.iter().map(|(page, fills)| { + let last = first + fills.len() as u32; + let range = first..last; + first = last; + (*page, range) + }).collect() + } + + /// Records the fills `stage` wrote into `encoder`: one pass a page, each drawing into it. + fn encode(&self, encoder: &mut wgpu::CommandEncoder, pages: &[(&wgpu::Texture, std::ops::Range<u32>)]) { + for (texture, range) in pages { + let at = u64::from((texture.height() / ATLAS_START_ROWS).max(1).ilog2()) * 16; + encoder.copy_buffer_to_buffer(&self.projections, at, &self.projection, 0, 16); + let view = texture.create_view(&Default::default()); + let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { + label: Some("atlas fill"), + color_attachments: &[Some(wgpu::RenderPassColorAttachment { + view: &view, + depth_slice: None, + resolve_target: None, + ops: wgpu::Operations { load: wgpu::LoadOp::Load, store: wgpu::StoreOp::Store }, + })], + depth_stencil_attachment: None, + timestamp_writes: None, + occlusion_query_set: None, + multiview_mask: None, + }); + pass.set_pipeline(&self.pipeline); + pass.set_bind_group(0, &self.bind, &[]); + pass.set_vertex_buffer(0, self.instances.slice(..)); + pass.draw(0..4, range.clone()); + } + } +} + +/// Fills staged by `prepare` and not yet recorded: recorded into the frame's encoder where it +/// first records the renderer's uploads (`flush_uploads`), so a frame that places new glyphs +/// submits once, as any frame does; or submitted on their own ahead of a caller's pass +/// (`submit_uploads`). The device and queue are for that. +pub(super) struct PendingFills { + device: wgpu::Device, + queue: wgpu::Queue, + pages: Vec<(usize, std::ops::Range<u32>)>, +} +/// A queued fill as the Windfoil glyph instance that draws it, over its mask and one-texel border +/// (which comes out clear), at zoom 1 with no clip. +fn instance(q: &QueuedFill) -> Instance { + let [x, y, w, h] = q.rect.map(|v| v as f32); + let f = q.fill; + Instance { + rect: [x - 1.0, y - 1.0, w + 2.0, h + 2.0], + radii: [x + f.pen[0], y + f.pen[1], f.scale, 1.0], + fill: [1.0; 4], + border: [f.record as f32, f.hint as f32, f.radius, f.coverage as f32], + // A negative exponent marks a fill: the shader rounds the coverage as fill_mask does. + params: [0.0, KIND_GLYPH, 0.0, -1.0], + uv: [0.0; 4], + clip: NO_CLIP, + fade: [0; 4], + } +} + +impl Renderer { + /// A glyph atlas page; a Windfoil renderer also draws into its pages (`FillPass`). + /// A glyph atlas page `rows` texels tall (`ATLAS_SIZE` wide): the first starts at + /// `ATLAS_START_ROWS` and grows with what its shelves hold (`prepare`). + pub(super) fn atlas_texture(device: &wgpu::Device, filled: bool, rows: u32) -> wgpu::Texture { + // A page the GPU fills can be read back to compare its fills with the CPU's (`fill_drift`). + let render = if filled { wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC } else { wgpu::TextureUsages::empty() }; + device.create_texture(&wgpu::TextureDescriptor { + label: Some("glyph atlas"), + size: wgpu::Extent3d { width: ATLAS_SIZE, height: rows, depth_or_array_layers: 1 }, + mip_level_count: 1, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + format: wgpu::TextureFormat::R8Unorm, + usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST | render, + view_formats: &[], + }) + } + + /// Stages the atlas's queued fills (after this frame's row uploads, which they draw over), to + /// be recorded into the frame's encoder after those uploads (`encode_fills`). + pub(super) fn fill_atlas(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, staging: &rune_staging::Staging, atlas: &mut Atlas) { + if !matches!(self.uber, variant::Uber::Windfoil { .. }) { return; } + let fills = atlas.take_fills(); + if cfg!(debug_assertions) && std::env::var_os("RUNE_FILL_STATS").is_some() && fills.iter().any(|(_, f)| !f.is_empty()) { + let masks: usize = fills.iter().map(|(_, f)| f.len()).sum(); + let texels: u64 = fills.iter().flat_map(|(_, f)| f.iter().map(|q| u64::from(q.rect[2] * q.rect[3]))).sum(); + eprintln!("rune: fill stats: {masks} masks, {texels} texels this frame"); + } + let fills: Vec<(usize, Vec<QueuedFill>)> = fills.into_iter().filter(|(page, f)| !f.is_empty() && *page <= self.atlas_pages.len()).collect(); + if fills.is_empty() { + return; + } + // A prepare whose fills no draw recorded: they go now, before their instances are + // written over. + self.submit_fills(); + let variant::Uber::Windfoil { fill, .. } = &mut self.uber else { return }; + let pages = fill.stage(device, staging, &fills); + *self.fills.lock().unwrap_or_else(|e| e.into_inner()) = Some(PendingFills { device: device.clone(), queue: queue.clone(), pages }); + } + + /// Records the fills `prepare` staged into `encoder`, after the uploads already recorded there. + pub(super) fn encode_fills(&self, encoder: &mut wgpu::CommandEncoder) { + let Some(pending) = self.fills.lock().unwrap_or_else(|e| e.into_inner()).take() else { return }; + let variant::Uber::Windfoil { fill, .. } = &self.uber else { return }; + let pages: Vec<(&wgpu::Texture, std::ops::Range<u32>)> = pending.pages.iter().filter_map(|(page, range)| { + let texture = if *page == 0 { Some(&self.atlas) } else { self.atlas_pages.get(page - 1).map(|p| &p.0) }; + texture.map(|t| (t, range.clone())) + }).collect(); + fill.encode(encoder, &pages); + } + + /// Submits the fills `prepare` staged on their own, the uploads ahead of them, for a draw + /// into a pass its caller opened (`draw_range`), or a prepare no draw followed. + pub(super) fn submit_fills(&self) { + let (device, queue) = match &*self.fills.lock().unwrap_or_else(|e| e.into_inner()) { + Some(p) => (p.device.clone(), p.queue.clone()), + None => return, + }; + let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("atlas fill") }); + self.flush_uploads(&mut encoder); + queue.submit([encoder.finish()]); + } +} +/// How far the GPU's atlas fills are from the CPU's (`Renderer::fill_drift`): texels compared, +/// and how many differ by 1, 2, and 3 or more. +#[doc(hidden)] +#[derive(Clone, Copy, Debug, Default)] +pub struct FillDrift { + pub masks: usize, + pub texels: u64, + pub off_by: [u64; 3], + pub max: u8, +} + +impl Renderer { + /// Reads every atlas page back and compares each mask the GPU filled with what + /// `text::outline::fill_mask` gives for it, byte for byte. A diagnostic: it blocks on the GPU. + #[doc(hidden)] + #[cfg(not(target_arch = "wasm32"))] + pub fn fill_drift(&self, device: &wgpu::Device, queue: &wgpu::Queue, atlas: &crate::text::Atlas) -> FillDrift { + self.submit_uploads(); + let pages: Vec<&wgpu::Texture> = std::iter::once(&self.atlas).chain(self.atlas_pages.iter().map(|(t, _)| t)).collect(); + let read = |texture: &wgpu::Texture| -> Vec<u8> { + let buffer = device.create_buffer(&wgpu::BufferDescriptor { label: Some("fill drift"), size: u64::from(ATLAS_SIZE * ATLAS_SIZE), usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ, mapped_at_creation: false }); + let rows = texture.height(); + let mut encoder = device.create_command_encoder(&Default::default()); + encoder.copy_texture_to_buffer(texture.as_image_copy(), wgpu::TexelCopyBufferInfo { buffer: &buffer, layout: wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(ATLAS_SIZE), rows_per_image: Some(rows) } }, wgpu::Extent3d { width: ATLAS_SIZE, height: rows, depth_or_array_layers: 1 }); + queue.submit([encoder.finish()]); + // A callback never panics: one that did while a failed wait unwinds (wgpu aborts the map + // then) would abort the process. A failed map shows as `get_mapped_range`'s error. + let slice = buffer.slice(..); + slice.map_async(wgpu::MapMode::Read, |_| {}); + rune_gpu::health::poll(device, wgpu::PollType::wait_indefinitely()).expect("poll"); + let out = slice.get_mapped_range().expect("mapped").to_vec(); + buffer.unmap(); + out + }; + let data: Vec<Vec<u8>> = pages.iter().map(|t| read(t)).collect(); + let mut d = FillDrift::default(); + for (page, [x, y, w, h], cpu) in atlas.gpu_fills() { + let Some(gpu) = data.get(page as usize) else { continue }; + d.masks += 1; + for row in 0..h { + for col in 0..w { + let g = gpu[((y + row) * ATLAS_SIZE + x + col) as usize]; + let c = cpu[(row * w + col) as usize]; + let off = g.abs_diff(c); + d.texels += 1; + d.max = d.max.max(off); + if off > 0 { d.off_by[usize::from(off.min(3)) - 1] += 1; } + } + } + } + d + } +} diff --git a/app/vendor/rune/crates/rune/src/render/first_use.rs b/app/vendor/rune/crates/rune/src/render/first_use.rs new file mode 100644 index 0000000..0c9c452 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/render/first_use.rs @@ -0,0 +1,59 @@ +//! What Rune's pipelines other than the uber shader cost the first time a process makes them, +//! for rune-light's `shader_first_use` example and `builtin_shaders` test, which between them +//! build every pipeline Rune and its effect crates ship. + + +use super::{Renderer, backdrop_blur::BackdropBlur, layer_blur, surface_alpha::AlphaSurface}; + +impl Renderer { + /// Makes and drops a backdrop blur with its composite for this renderer's format, for regen_dxbc. + #[doc(hidden)] + pub fn make_backdrop_blur(&self, device: &wgpu::Device) { + BackdropBlur::new(device, &self.bind_layout).ensure_composite(device, self.format); + } + + /// Makes, times and drops what a first backdrop blur, layer blur, video frame, transparent + /// window and spring-driven renderer build, in milliseconds each. + #[doc(hidden)] + pub fn first_use_ms(&self, device: &wgpu::Device) -> Vec<(&'static str, f64)> { + fn ms(f: impl FnOnce()) -> f64 { + let start = crate::time::now(); + f(); + start.elapsed().as_secs_f64() * 1e3 + } + use crate::gpu::springs::{Node, Track}; + let node = Node { x: Track::constant(0.0), y: Track::constant(0.0), opacity: Track::constant(1.0) }; + vec![ + ("backdrop_blur", ms(|| BackdropBlur::new(device, &self.bind_layout).ensure_composite(device, self.format))), + ("layer_blur", ms(|| drop(layer_blur::Pipeline::new(device, super::layers::FORMAT)))), + ("video", ms(|| drop(crate::native_surface::SurfaceRenderer::new(device, self.format)))), + ("alpha", ms(|| drop(AlphaSurface::new(device, self.format, (16, 16))))), + ("springs", ms(|| drop(Renderer::with_springs(device, self.format, &[node], &[0])))), + ] + } +} + +/// Makes and drops the straight-alpha pass from its WGSL, for regen_dxbc to take the HLSL wgpu +/// generates for it. +#[doc(hidden)] +pub fn make_straight_alpha(device: &wgpu::Device, format: wgpu::TextureFormat) { + drop(AlphaSurface::new(device, format, (16, 16))); +} + +/// Makes and drops the layer blur's pipelines from their WGSL, for regen_dxbc. +#[doc(hidden)] +pub fn make_layer_blur(device: &wgpu::Device) { + drop(layer_blur::Pipeline::new(device, super::layers::FORMAT)); +} + +/// How many pipelines Rune's Metal backend compiled at runtime because its precompiled library +/// lacked them; `None` on any other backend. +#[doc(hidden)] +pub fn precompiled_misses(device: &wgpu::Device) -> Option<usize> { + #[cfg(all(target_vendor = "apple", feature = "metal-backend"))] + if crate::gpu::metal::raw_device(device).is_some() { + return Some(crate::gpu::metal::builtin_misses()); + } + let _ = device; + None +} diff --git a/app/vendor/rune/crates/rune/src/render/gpu_events.rs b/app/vendor/rune/crates/rune/src/render/gpu_events.rs new file mode 100644 index 0000000..162486c --- /dev/null +++ b/app/vendor/rune/crates/rune/src/render/gpu_events.rs @@ -0,0 +1,65 @@ +//! `on_gpu`: when Rune makes a GPU device for a window or overlay, and when a frame first +//! presents on it, for an app that guards its launches against a GPU driver that crashes. + +use std::sync::OnceLock; +use std::sync::atomic::{AtomicBool, Ordering}; + +/// What `on_gpu`'s hook hears. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum GpuEvent { + /// Rune is about to make a GPU device: for the first window or overlay that draws, or for + /// one that draws after the last device went with its surfaces. + Starting, + /// The first frame since the last `Starting` drew: a window's or overlay's present, or the + /// pass `warm_gpu` runs on the device it makes. + Drew, +} + +type Hook = Box<dyn Fn(GpuEvent) + Send + Sync>; + +static HOOK: OnceLock<Hook> = OnceLock::new(); +/// A device was made and nothing has presented on it yet. +static WAITING: AtomicBool = AtomicBool::new(false); + +/// Calls `f` on the thread that makes a GPU device (`GpuEvent::Starting`) and on the thread that +/// presents its first frame (`GpuEvent::Drew`). A tray app whose windows and overlays wait +/// hidden makes no device until one shows, so a launch that never draws hears nothing. Set it +/// once, before the app runs; later calls do nothing. Headless renders and `Gpu::headless` +/// don't report. +pub fn on_gpu(f: impl Fn(GpuEvent) + Send + Sync + 'static) { + HOOK.set(Box::new(f)).ok(); +} + +pub(crate) fn starting() { + WAITING.store(true, Ordering::Release); + if let Some(hook) = HOOK.get() { hook(GpuEvent::Starting); } +} + +/// After every present; reports only the first after a `starting`. +pub(crate) fn presented() { + if WAITING.load(Ordering::Relaxed) && WAITING.swap(false, Ordering::AcqRel) && let Some(hook) = HOOK.get() { + hook(GpuEvent::Drew); + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::sync::Mutex; + + /// One `Drew` per `Starting`, however many frames present. + #[test] + fn the_first_present_after_a_device_starts_reports_drew() { + static HEARD: Mutex<Vec<GpuEvent>> = Mutex::new(Vec::new()); + on_gpu(|event| HEARD.lock().unwrap().push(event)); + presented(); + starting(); + presented(); + presented(); + starting(); + presented(); + // No other unit test makes a surface's device or presents a frame. + use GpuEvent::*; + assert_eq!(*HEARD.lock().unwrap(), [Starting, Drew, Starting, Drew]); + } +} diff --git a/app/vendor/rune/crates/rune/src/render/gpu_loss.rs b/app/vendor/rune/crates/rune/src/render/gpu_loss.rs new file mode 100644 index 0000000..21ee2ee --- /dev/null +++ b/app/vendor/rune/crates/rune/src/render/gpu_loss.rs @@ -0,0 +1,98 @@ +//! Device loss: the callback that tells Rune a device went away, and what a surface does about +//! it (`window/host/create.rs::Host::reattach`). wgpu reports a dead device only through +//! `Device::set_device_lost_callback`; `Surface::configure`'s `DeviceLost` is dropped, so a lost +//! device would otherwise surface as a panic on the surface's next drawable. +//! +//! The native Metal backend's `set_device_lost_callback` is a no-op +//! (`gpu/metal/device.rs`), so there `is_lost` never becomes true: a Metal device reports its +//! loss through the command buffer's error instead. + +use super::Gpu; +#[cfg(not(target_arch = "wasm32"))] +use std::sync::Mutex; +use std::sync::{Arc, atomic::{AtomicBool, Ordering}}; + +/// The distinct messages `Gpu::made` has printed, bounded: an error inside the frame would +/// otherwise print on every frame. +#[cfg(not(target_arch = "wasm32"))] +const PRINTED: usize = 16; + +impl Gpu { + /// A GPU over a device made elsewhere (`device_on`, a native backend, an example): Rune + /// watches it for loss, and on a surface device logs its uncaptured errors rather than + /// letting wgpu's default handler panic the app. That handler replaces any handler set on + /// the device before it was handed over. + pub fn from_device(instance: wgpu::Instance, adapter: wgpu::Adapter, device: wgpu::Device, queue: wgpu::Queue) -> Gpu { + Self::made(instance, adapter, device, queue, true) + } + + /// `from_device`, saying whether this device draws surfaces (`Host::try_create`, + /// `Overlay::attach`): only those log uncaptured errors. A headless device is usually a + /// test's or an offscreen render's, where a validation error should still fail loudly, and + /// under `cfg(test)` nothing logs so Rune's own tests see wgpu's panic. + pub(crate) fn made(instance: wgpu::Instance, adapter: wgpu::Adapter, device: wgpu::Device, queue: wgpu::Queue, + draws_surfaces: bool) -> Gpu { + let lost = Arc::new(AtomicBool::new(false)); + let lost_by_callback = lost.clone(); + device.set_device_lost_callback(move |reason, message| { + // Before anything reads it: a lost device's surface can't be configured, and wgpu + // reports that failure nowhere (`is_lost`). + lost_by_callback.store(true, Ordering::Release); + // No panic here, in tests either: wgpu calls this inside its own work (a submission, + // a queue's drop) and a panic there could abort the process. A test fails at its + // next wait instead (`rune_gpu::health::poll` returns `Lost`). + #[cfg(not(target_arch = "wasm32"))] + eprintln!("rune: the GPU device was lost ({reason:?}): {message}"); + #[cfg(target_arch = "wasm32")] + let _ = (reason, message); + }); + // On wasm32, `platform::web::health::watch` owns uncaptured error logging for both WebGPU + // (through JS, avoiding wgpu's panic on `GPUInternalError`) and WebGL2 (to `console.error`, + // where `eprintln!` is silent). + #[cfg(not(target_arch = "wasm32"))] + if draws_surfaces && !cfg!(test) { log_uncaptured(&device); } + #[cfg(target_arch = "wasm32")] + let _ = draws_surfaces; + let removal = rune_gpu::health::Removal::watch(&device); + Gpu { instance, adapter, device, queue, lost, removal } + } + + /// Whether the device went away: a driver reset, a GPU removed, a resume from Modern Standby. + /// Nothing can be drawn with it, and its surfaces can't be configured, so its owner makes a + /// new GPU and surface instead (`Host::reattach`). + /// On D3D12 the device is asked too: wgpu hears of a removal only at the next submission. + pub fn is_lost(&self) -> bool { self.lost.load(Ordering::Acquire) || self.removal.removed() } +} + +/// What `log_uncaptured` has printed: each distinct message once, up to `PRINTED`, then one +/// line saying the rest are silent. +#[cfg(not(target_arch = "wasm32"))] +#[derive(Default)] +struct Printed { + seen: Vec<String>, + silenced: bool, +} + +/// Prints each uncaptured error once, up to `PRINTED` distinct messages, then one line saying +/// further ones are not shown. A scoped error (a `push_error_scope`, as `window::configure` +/// uses) still goes to its scope first; this is the fallback for errors nothing else caught. +#[cfg(not(target_arch = "wasm32"))] +fn log_uncaptured(device: &wgpu::Device) { + let printed: Arc<Mutex<Printed>> = Arc::default(); + device.on_uncaptured_error(Arc::new(move |error: wgpu::Error| { + let message = error.to_string(); + let line = { + let mut printed = printed.lock().unwrap_or_else(|e| e.into_inner()); + if printed.silenced || printed.seen.contains(&message) { + None + } else if printed.seen.len() < PRINTED { + printed.seen.push(message.clone()); + Some(format!("rune: a GPU error went uncaptured: {message}")) + } else { + printed.silenced = true; + Some(format!("rune: {PRINTED} distinct GPU errors went uncaptured; further uncaptured GPU errors are not shown")) + } + }; + if let Some(line) = line { eprintln!("{line}"); } + })); +} diff --git a/app/vendor/rune/crates/rune/src/render/image_tests.rs b/app/vendor/rune/crates/rune/src/render/image_tests.rs new file mode 100644 index 0000000..866f287 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/render/image_tests.rs @@ -0,0 +1,261 @@ +use std::sync::Arc; + +use crate::pixels::Pixels; + +#[test] +fn gpu_pages_interleave_with_video_and_retained_springs() { + use crate::native_surface::{ByteFrame, ColorInfo, Format, NativeSurface, SurfaceFit}; + use crate::render::{Gpu, OFFSCREEN_FORMAT, Offscreen, Renderer}; + use crate::{Cx, El, Env, Runtime, el}; + type State = ([Pixels; 3], NativeSurface); + fn view(s: &State, _: &mut Cx<State>) -> El { + el().size(8.0, 8.0).pixels(&s.0[0]).child( + el().size(6.0, 6.0).pin(Some(1.0), Some(1.0), None, None).native_surface(&s.1, SurfaceFit::Fill) + .child(el().size(2.0, 2.0).pin(Some(1.0), Some(1.0), None, None).pixels(&s.0[1])) + .child(el().size(1.0, 1.0).pin(Some(4.0), Some(4.0), None, None).pixels(&s.0[2])), + ) + } + let pixels = [Pixels::new(), Pixels::new(), Pixels::new()]; + pixels[0].set(8, 8, [255, 0, 0, 255].repeat(64)); + pixels[1].set(2, 2, [0, 255, 0, 255].repeat(4)); + pixels[2].set(1024, 1024, [255; 4].repeat(1024 * 1024)); + let surface = NativeSurface::new(); + surface.push_bytes(ByteFrame { + width: 6, + height: 6, + format: Format::Bgra, + color: ColorInfo::default(), + planes: [[255, 0, 0, 255].repeat(36), vec![]], + }, 1).unwrap(); + let mut rt = Runtime::new((pixels, surface), view, (8.0, 8.0), Env::new(true, 1.0)); + rt.frame(0.0); + assert_eq!(rt.images.pages.len(), 2); + let gpu = Gpu::headless(); + let zero = crate::gpu::springs::Track::constant(0.0); + let node = crate::gpu::springs::Node { x: zero, y: zero, opacity: crate::gpu::springs::Track::constant(1.0) }; + let mut renderer = Renderer::with_springs(&gpu.device, OFFSCREEN_FORMAT, &[node], &vec![0; rt.instances.len()]); + renderer.prepare(&gpu.device, &gpu.queue, &mut rt.text.atlas, &rt.instances, (8, 8)); + renderer.upload_images(&gpu.device, &gpu.queue, &mut rt.images); + renderer.prepare_surfaces(&gpu.device, &gpu.queue, &rt.surfaces, (8, 8)); + let target = Offscreen::new(&gpu.device, 8, 8); + let mut encoder = gpu.device.create_command_encoder(&Default::default()); + renderer.draw(&mut encoder, &target.view, [0.0; 4]); + target.copy(&mut encoder); + renderer.submit(&gpu.queue, encoder); + let out = target.read(&gpu.device); + for (x, y, want) in [(0, 0, [255, 0, 0, 255]), (1, 1, [0, 0, 255, 255]), (2, 2, [0, 255, 0, 255]), (5, 5, [255; 4])] { + assert_eq!(&out[(y * 8 + x) * 4..(y * 8 + x + 1) * 4], &want, "at {x},{y}"); + } +} + +/// An emoji in a text element reaches the screen in colour, from the image atlas. +#[test] +fn gpu_emoji_in_text_draws_in_colour() { + use crate::render::{Gpu, OFFSCREEN_FORMAT, Offscreen, Renderer}; + use crate::{Color, Cx, El, Env, Runtime, TextStyle, el, text}; + fn view(_: &(), _: &mut Cx<()>) -> El { + el().size(80.0, 24.0).fill(Color::BLACK).child(text("Hi 🎉").font(TextStyle::new(16.0, 400.0)).color(Color::WHITE)) + } + let mut rt = Runtime::new((), view, (80.0, 24.0), Env::new(true, 2.0)); + rt.frame(0.0); + if rt.images.pages.is_empty() { + eprintln!("skipping: no colour emoji font installed"); + return; + } + let (w, h) = (160, 48); + let gpu = Gpu::headless(); + let mut renderer = Renderer::new(&gpu.device, OFFSCREEN_FORMAT); + renderer.prepare(&gpu.device, &gpu.queue, &mut rt.text.atlas, &rt.instances, (w, h)); + renderer.upload_images(&gpu.device, &gpu.queue, &mut rt.images); + let target = Offscreen::new(&gpu.device, w, h); + let mut enc = gpu.device.create_command_encoder(&Default::default()); + renderer.draw(&mut enc, &target.view, [0.0, 0.0, 0.0, 1.0]); + target.copy(&mut enc); + gpu.queue.submit([enc.finish()]); + let out = target.read(&gpu.device); + if let Some(path) = std::env::var_os("RUNE_EMOJI_PNG") { + crate::render::write_png(std::path::Path::new(&path), w, h, &out).unwrap(); + } + let coloured = out.chunks(4).filter(|p| p[0].abs_diff(p[1]) > 60 || p[1].abs_diff(p[2]) > 60).count(); + assert!(coloured > 100, "only {coloured} coloured pixels"); +} + +#[test] +fn an_image_over_its_fill_fades_into_a_soft_edge_like_a_flat_fill() { + use crate::color::hex; + use crate::render::{Gpu, OFFSCREEN_FORMAT, Offscreen, Renderer}; + use crate::{Cx, El, Env, Runtime, ScrollSpec, col, el, image::ImageCache, row}; + // A dark image on a lighter placeholder with a border, as a chat thumbnail, beside a + // flat fill of the image's colour, under a scroll's 16 pt top fade. + fn view(s: &Pixels, _: &mut Cx<Pixels>) -> El { + let thumb = el().size(40.0, 60.0).radius(8.0).fill(hex("#5a5a5a").unwrap()) + .border(0.5, hex("#ffffff33").unwrap()).pixels_fit(s, crate::SurfaceFit::Fill); + el().size(100.0, 60.0).fill(hex("#141414").unwrap()).child( + col().w_full().h_full().scroll(ScrollSpec { stick_bottom: false }).clip_fade(0.0, 16.0, 0.0, 8.0) + .child(row().gap(10.0).child(thumb).child(el().size(40.0, 60.0).fill(hex("#282828").unwrap()))) + .child(el().size(4.0, 200.0)), + ) + } + let cache = ImageCache::new(Arc::new(|| {})); + let image = cache.rgba(80, 120, [40u8, 40, 40, 255].repeat(80 * 120)); + image.wait().unwrap(); + let gpu = Gpu::headless(); + let mut renderer = Renderer::new(&gpu.device, OFFSCREEN_FORMAT); + let target = Offscreen::new(&gpu.device, 100, 60); + let mut rt = Runtime::new(image.pixels().clone(), view, (100.0, 60.0), Env::new(true, 1.0)); + rt.frame(0.0); + renderer.prepare(&gpu.device, &gpu.queue, &mut rt.text.atlas, &rt.instances, (100, 60)); + renderer.upload_images(&gpu.device, &gpu.queue, &mut rt.images); + let mut enc = gpu.device.create_command_encoder(&Default::default()); + renderer.draw(&mut enc, &target.view, [0.0, 0.0, 0.0, 1.0]); + target.copy(&mut enc); + gpu.queue.submit([enc.finish()]); + let out = target.read(&gpu.device); + let px = |x: usize, y: usize| out[(y * 100 + x) * 4]; + let (image, flat): (Vec<u8>, Vec<u8>) = (0..24).map(|y| (px(20, y), px(70, y))).unzip(); + assert!(flat[0] < flat[20], "the band fades: {flat:?}"); + assert!(image.iter().zip(&flat).all(|(a, b)| a.abs_diff(*b) <= 1), "the image fades like the fill\nimage {image:?}\nflat {flat:?}"); +} + +#[test] +fn gpu_static_mips_alpha_clip_and_page_order_match_pixels() { + use crate::render::{Gpu, OFFSCREEN_FORMAT, Offscreen, Renderer}; + use crate::{Cx, El, Env, Runtime, el, image::ImageCache}; + type State = (Pixels, Pixels, bool); + fn view(s: &State, _: &mut Cx<State>) -> El { + let base = el().size(8.0, 8.0).pixels(&s.0); + if s.2 { + base.child(el().size(4.0, 4.0).pin(Some(2.0), Some(2.0), None, None).pixels(&s.1)) + } else { + base.radius(4.0).clip_fade(2.0, 0.0, 0.0, 0.0) + } + } + let cache = ImageCache::new(Arc::new(|| {})); + let checker: Vec<_> = (0..64 * 64).flat_map(|i| { + let v = if (i % 64 + i / 64) % 2 == 0 { 0 } else { 255 }; + [v, v, v, 255] + }).collect(); + let image = cache.rgba(64, 64, checker); + image.wait().unwrap(); + let gpu = Gpu::headless(); + let mut renderer = Renderer::new(&gpu.device, OFFSCREEN_FORMAT); + let target = Offscreen::new(&gpu.device, 8, 8); + let mut rt = Runtime::new((image.pixels().clone(), Pixels::new(), false), view, (8.0, 8.0), Env::new(true, 1.0)); + let mut draw = |rt: &mut Runtime<State>| { + rt.frame(0.0); + renderer.prepare(&gpu.device, &gpu.queue, &mut rt.text.atlas, &rt.instances, (8, 8)); + renderer.upload_images(&gpu.device, &gpu.queue, &mut rt.images); + let mut enc = gpu.device.create_command_encoder(&Default::default()); + renderer.draw(&mut enc, &target.view, [0.0, 0.0, 1.0, 1.0]); + target.copy(&mut enc); + gpu.queue.submit([enc.finish()]); + target.read(&gpu.device) + }; + let pixel = |out: &[u8], x: usize, y: usize| <[u8; 4]>::try_from(&out[(y * 8 + x) * 4..(y * 8 + x + 1) * 4]).unwrap(); + let near = |got: [u8; 4], want: [u8; 4]| assert!(got.iter().zip(want).all(|(a, b)| a.abs_diff(b) <= 2), "{got:?} != {want:?}"); + let out = draw(&mut rt); + near(pixel(&out, 4, 4), [188, 188, 188, 255]); + near(pixel(&out, 0, 0), [0, 0, 255, 255]); + assert!(pixel(&out, 0, 4)[0] < pixel(&out, 3, 4)[0], "edge fade clips the image"); + assert!(rt.images.has_slot(image.pixels(), 3), "64px source uses its 8px mip"); + let alpha: Vec<_> = (0..64 * 64).flat_map(|i| if i % 2 == 0 { [255, 0, 0, 128] } else { [0, 255, 0, 0] }).collect(); + let transparent = cache.rgba(64, 64, alpha); + transparent.wait().unwrap(); + rt.state.0 = transparent.pixels().clone(); + rt.invalidate(); + let out = draw(&mut rt); + near(pixel(&out, 4, 4), [137, 0, 224, 255]); + let big = Pixels::new(); + big.set(2048, 1, [255, 0, 0, 255].repeat(2048)); + let full = Pixels::new(); + full.set(1024, 1024, [0, 255, 0, 255].repeat(1024 * 1024)); + rt.state = (big, full, true); + rt.invalidate(); + rt.settle_all(); + let out = draw(&mut rt); + near(pixel(&out, 0, 0), [255, 0, 0, 255]); + near(pixel(&out, 4, 4), [0, 255, 0, 255]); + assert!(rt.images.pages.len() >= 2, "large images and full pages share painter order"); + rt.state.0.set(2, 1, vec![255, 0, 0, 255, 0, 0, 255, 255]); + let out = draw(&mut rt); + near(pixel(&out, 0, 0), [255, 0, 0, 255]); + near(pixel(&out, 7, 0), [0, 0, 255, 255]); + assert!(rt.images.pages.iter().any(|p| p.data.is_empty()), "the old large page is released between live pages"); +} + +#[test] +fn gpu_draws_pixels_texel_for_texel_and_follows_new_frames() { + use crate::el::{El, el}; + use crate::render::{Gpu, OFFSCREEN_FORMAT, Offscreen, Renderer}; + use crate::runtime::{Cx, Env, Runtime}; + fn view(px: &Pixels, _: &mut Cx<Pixels>) -> El { + el().size(4.0, 4.0).pixels(px) + } + let px = Pixels::new(); + let mut rgba = Vec::new(); + for i in 0..16u8 { + rgba.extend_from_slice(&[i * 16, 255 - i * 16, 40, 255]); + } + px.set(4, 4, rgba.clone()); + let mut rt = Runtime::new(px.clone(), view, (4.0, 4.0), Env::new(true, 1.0)); + let gpu = Gpu::new(Gpu::instance(), None); + let mut renderer = Renderer::new(&gpu.device, OFFSCREEN_FORMAT); + let target = Offscreen::new(&gpu.device, 4, 4); + let mut draw = |rt: &mut Runtime<Pixels>| { + rt.frame(1.0 / 60.0); + renderer.prepare(&gpu.device, &gpu.queue, &mut rt.text.atlas, &rt.instances, (4, 4)); + renderer.upload_images(&gpu.device, &gpu.queue, &mut rt.images); + let mut enc = gpu.device.create_command_encoder(&Default::default()); + renderer.draw(&mut enc, &target.view, [0.0, 0.0, 0.0, 1.0]); + target.copy(&mut enc); + gpu.queue.submit([enc.finish()]); + target.read(&gpu.device) + }; + let out = draw(&mut rt); + for (got, want) in out.chunks_exact(4).zip(rgba.chunks_exact(4)) { + assert!(got.iter().zip(want).all(|(a, b)| a.abs_diff(*b) <= 1), "drew {got:?}, image {want:?}"); + } + px.set(4, 4, [10, 20, 30, 255].repeat(16)); + let out = draw(&mut rt); + assert!(out.chunks_exact(4).all(|p| p.iter().zip([10u8, 20, 30, 255]).all(|(a, b)| a.abs_diff(b) <= 1)), "a new frame shows without re-running the view: {:?}", &out[..4]); +} + +#[test] +fn gpu_pixels_fit_letterboxes_and_fill_crops() { + use crate::el::{El, el}; + use crate::render::{Gpu, OFFSCREEN_FORMAT, Offscreen, Renderer}; + use crate::runtime::{Cx, Env, Runtime}; + type State = (Pixels, crate::SurfaceFit); + fn view(s: &State, _: &mut Cx<State>) -> El { el().size(4.0, 4.0).pixels_fit(&s.0, s.1) } + // Four columns, red green blue white, two rows tall. + let px = Pixels::new(); + px.set(4, 2, [[255, 0, 0, 255], [0, 255, 0, 255], [0, 0, 255, 255], [255; 4]].concat().repeat(2)); + let gpu = Gpu::headless(); + let mut renderer = Renderer::new(&gpu.device, OFFSCREEN_FORMAT); + let target = Offscreen::new(&gpu.device, 4, 4); + let mut draw = |fit| { + let mut rt = Runtime::new((px.clone(), fit), view, (4.0, 4.0), Env::new(true, 1.0)); + rt.frame(0.0); + renderer.prepare(&gpu.device, &gpu.queue, &mut rt.text.atlas, &rt.instances, (4, 4)); + renderer.upload_images(&gpu.device, &gpu.queue, &mut rt.images); + let mut enc = gpu.device.create_command_encoder(&Default::default()); + renderer.draw(&mut enc, &target.view, [0.0, 0.0, 0.0, 1.0]); + target.copy(&mut enc); + gpu.queue.submit([enc.finish()]); + target.read(&gpu.device) + }; + let at = |out: &[u8], x: usize, y: usize| <[u8; 4]>::try_from(&out[(y * 4 + x) * 4..(y * 4 + x + 1) * 4]).unwrap(); + let out = draw(crate::SurfaceFit::Fit); + for x in 0..4 { + assert_eq!(at(&out, x, 0), [0, 0, 0, 255], "letterbox above column {x}"); + assert_eq!(at(&out, x, 3), [0, 0, 0, 255], "letterbox below column {x}"); + } + assert_eq!([at(&out, 0, 1), at(&out, 1, 2), at(&out, 2, 1), at(&out, 3, 2)], + [[255, 0, 0, 255], [0, 255, 0, 255], [0, 0, 255, 255], [255; 4]], "the image draws texel for texel"); + let out = draw(crate::SurfaceFit::Fill); + for y in 0..4 { + assert_eq!(at(&out, 0, y), [0, 255, 0, 255], "row {y} starts on green"); + assert_eq!(at(&out, 3, y), [0, 0, 255, 255], "row {y} ends on blue"); + } + assert!(out.as_chunks::<4>().0.iter().all(|p| p[0] < 200), "red and white columns are cropped"); +} diff --git a/app/vendor/rune/crates/rune/src/render/instance.rs b/app/vendor/rune/crates/rune/src/render/instance.rs new file mode 100644 index 0000000..d16355b --- /dev/null +++ b/app/vendor/rune/crates/rune/src/render/instance.rs @@ -0,0 +1,796 @@ +//! The per-instance and per-frame GPU ABI shared by the uber shader, layer planner, CPU +//! boot painter and Windows damage planner. + +use std::mem::{offset_of, size_of}; + +use bytemuck::{Pod, Zeroable}; + +use super::{Blend, LayerSpec, layer_blur}; + +/// Constants and ABI parameters parsed directly from `crates/rune/src/shaders/*.wgsl` by `build.rs`. +pub(crate) mod shader_consts { + include!(concat!(env!("OUT_DIR"), "/shader_consts.rs")); +} + +/// Primitive kind stored in [`Instance::params`]`[1]`. +/// +/// The `KIND_*` float constants derive from these discriminants so every Rust consumer shares one +/// numeric table with `shader.wgsl`. +#[repr(u8)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum Kind { + /// Rounded rect in `fill` with a `params.x`-wide `border` ring over it (`KIND_RECT`). + Rect = shader_consts::KIND_RECT_U8, + /// Analytic Gaussian rounded-rect shadow (`KIND_SHADOW`). + Shadow = shader_consts::KIND_SHADOW_U8, + /// Glyph-atlas or outline text (`KIND_GLYPH`). + Glyph = shader_consts::KIND_GLYPH_U8, + /// Inset shadow inside a rounded rect (`KIND_INSET`). + Inset = shader_consts::KIND_INSET_U8, + /// Rounded rect or border with a vertical gradient (`KIND_GRADIENT`). + Gradient = shader_consts::KIND_GRADIENT_U8, + /// Antialiased stroke segment (`KIND_SEGMENT`). + Segment = shader_consts::KIND_SEGMENT_U8, + /// Filled triangle (`KIND_TRIANGLE`). + Triangle = shader_consts::KIND_TRIANGLE_U8, + /// RGBA image from the image atlas (`KIND_IMAGE`). + Image = shader_consts::KIND_IMAGE_U8, + /// Isolated layer scope open / composite quad (`KIND_LAYER`). + Layer = shader_consts::KIND_LAYER_U8, + /// Isolated layer scope close (`KIND_LAYER_END`). + LayerEnd = shader_consts::KIND_LAYER_END_U8, + /// Dashed border ring (`KIND_DASHED`). + Dashed = shader_consts::KIND_DASHED_U8, + /// Radial or angled linear gradient stop segment (`KIND_RADIAL`). + Radial = shader_consts::KIND_RADIAL_U8, + /// Compositor effect slot (`KIND_EFFECT`). + Effect = 12, + /// In-window backdrop blur (`KIND_BACKDROP_BLUR`). + BackdropBlur = 13, +} + +const _: () = { + assert!(size_of::<Option<Kind>>() == 1); + assert!(Kind::Radial.as_f32() < shader_consts::UBER_MAX_KIND_THRESHOLD); + assert!(Kind::Effect.as_f32() > shader_consts::UBER_MAX_KIND_THRESHOLD); + assert!(Kind::BackdropBlur.as_f32() > shader_consts::UBER_MAX_KIND_THRESHOLD); + assert!(shader_consts::OUTLINE_TEX_WIDTH == crate::text::outline::WIDTH); + assert!(shader_consts::OUTLINE_HINT_REACH > 0.0); +}; + +impl Kind { + /// Number of defined primitive kinds. + pub const COUNT: usize = 14; + + #[inline] + pub const fn as_u8(self) -> u8 { + self as u8 + } + + #[inline] + pub const fn as_u32(self) -> u32 { + self as u32 + } + + #[inline] + pub const fn as_f32(self) -> f32 { + self as u8 as f32 + } + + #[inline] + pub const fn from_u8(v: u8) -> Option<Kind> { + match v { + shader_consts::KIND_RECT_U8 => Some(Kind::Rect), + shader_consts::KIND_SHADOW_U8 => Some(Kind::Shadow), + shader_consts::KIND_GLYPH_U8 => Some(Kind::Glyph), + shader_consts::KIND_INSET_U8 => Some(Kind::Inset), + shader_consts::KIND_GRADIENT_U8 => Some(Kind::Gradient), + shader_consts::KIND_SEGMENT_U8 => Some(Kind::Segment), + shader_consts::KIND_TRIANGLE_U8 => Some(Kind::Triangle), + shader_consts::KIND_IMAGE_U8 => Some(Kind::Image), + shader_consts::KIND_LAYER_U8 => Some(Kind::Layer), + shader_consts::KIND_LAYER_END_U8 => Some(Kind::LayerEnd), + shader_consts::KIND_DASHED_U8 => Some(Kind::Dashed), + shader_consts::KIND_RADIAL_U8 => Some(Kind::Radial), + 12 => Some(Kind::Effect), + 13 => Some(Kind::BackdropBlur), + _ => None, + } + } + + /// Lossless conversion from the `f32` stored in `Instance::params[1]`. + /// + /// Matches IEEE-754 bit patterns directly so per-instance loops compile to integer ops with + /// no float-to-int saturating cast, and non-integer or out-of-range values return `None`. + /// All non-zero kinds (`1.0..=13.0`) have zero low 20 bits and span `0..=29` after + /// `(bits - 1.0_f32.to_bits()).rotate_left(12)`, letting LLVM lower full matches to a dense + /// lookup/jump table while still folding single-kind checks to one immediate compare. + #[inline(always)] + pub const fn from_f32(v: f32) -> Option<Kind> { + const ONE: u32 = KIND_SHADOW.to_bits(); + const fn slot(k: Kind) -> u32 { + k.as_f32().to_bits().wrapping_sub(ONE).rotate_left(12) + } + const SHADOW: u32 = slot(Kind::Shadow); + const GLYPH: u32 = slot(Kind::Glyph); + const INSET: u32 = slot(Kind::Inset); + const GRADIENT: u32 = slot(Kind::Gradient); + const SEGMENT: u32 = slot(Kind::Segment); + const TRIANGLE: u32 = slot(Kind::Triangle); + const IMAGE: u32 = slot(Kind::Image); + const LAYER: u32 = slot(Kind::Layer); + const LAYER_END: u32 = slot(Kind::LayerEnd); + const DASHED: u32 = slot(Kind::Dashed); + const RADIAL: u32 = slot(Kind::Radial); + const EFFECT: u32 = slot(Kind::Effect); + const BACKDROP_BLUR: u32 = slot(Kind::BackdropBlur); + let bits = v.to_bits(); + if (bits << 1) == 0 { + return Some(Kind::Rect); + } + match bits.wrapping_sub(ONE).rotate_left(12) { + SHADOW => Some(Kind::Shadow), + GLYPH => Some(Kind::Glyph), + INSET => Some(Kind::Inset), + GRADIENT => Some(Kind::Gradient), + SEGMENT => Some(Kind::Segment), + TRIANGLE => Some(Kind::Triangle), + IMAGE => Some(Kind::Image), + LAYER => Some(Kind::Layer), + LAYER_END => Some(Kind::LayerEnd), + DASHED => Some(Kind::Dashed), + RADIAL => Some(Kind::Radial), + EFFECT => Some(Kind::Effect), + BACKDROP_BLUR => Some(Kind::BackdropBlur), + _ => None, + } + } +} + +/// Rounded rect in `fill` with a `params.x`-wide `border` ring drawn over it, as CSS paints a +/// border over its background. `params.w` is the opacity the colours already carry (1 when not +/// faded), so the ring hides the fill by `border.a / params.w`. Non-zero `uv` (with `uv.z >= 0`) +/// gives per-side widths `[top, right, bottom, left]`; `params.x` is then the widest. +pub const KIND_RECT: f32 = Kind::Rect.as_f32(); +pub const KIND_SHADOW: f32 = Kind::Shadow.as_f32(); +pub const KIND_GLYPH: f32 = Kind::Glyph.as_f32(); +/// Inset shadow inside a rounded rect: `params.x` spread, `params.z` sigma, `uv.xy` offset. +pub const KIND_INSET: f32 = Kind::Inset.as_f32(); +/// Rounded rect with a vertical gradient: `fill` at the top, `uv` (premultiplied) at the bottom. +/// With a border width in `params.x` it is a `KIND_RECT` whose ring runs from `border` to `uv`, +/// over the fill, with the same `params.w`. +pub const KIND_GRADIENT: f32 = Kind::Gradient.as_f32(); +/// A stroke segment: `radii` = x0, y0, x1, y1; `params.x` half width, `params.z` 1 for round caps. +pub const KIND_SEGMENT: f32 = Kind::Segment.as_f32(); +/// A filled triangle: `radii` = ax, ay, bx, by; `uv.xy` = cx, cy; `params.x` the antialiased-edge +/// mask (a→b, b→c, c→a as bits 0, 1, 2; other edges are hard so neighbours meet without seams). +pub const KIND_TRIANGLE: f32 = Kind::Triangle.as_f32(); +/// An RGBA image (`El::pixels`): `uv.xy` its origin in the image atlas, `uv.zw` its size in +/// texels, drawn scaled into `rect` with the element's corner `radii`; `fill.a` is the opacity. +pub const KIND_IMAGE: f32 = Kind::Image.as_f32(); +/// Balanced scope records in the painter stream. They occupy instance indices but are never +/// rasterized as ordinary quads. Keep scopes intact when partitioning compositor lists. +pub const KIND_LAYER: f32 = Kind::Layer.as_f32(); +pub const KIND_LAYER_END: f32 = Kind::LayerEnd.as_f32(); +/// A dashed border ring (`El::border_dash`), `params.x` wide inside the rounded rect, drawn +/// alone (the fill is its own instance, showing through the gaps). Its colour runs from `fill` +/// at the top to `border` at the bottom; `uv.xyz` = dash, gap, phase in device pixels. +pub const KIND_DASHED: f32 = Kind::Dashed.as_f32(); +/// A radial (`uv.z > 0`: `uv` = `[cx, cy, rx, ry]` in rect-local device pixels) or angled linear +/// (`uv.z == 0`: `uv.xy` = gradient vector per device pixel) stop segment from `fill` at `t0` +/// (`params.x`) to `border` at `t1` (`params.w`), with `+ 2.0` marking an open interior stop edge. +pub const KIND_RADIAL: f32 = Kind::Radial.as_f32(); +/// An effect slot (`El::effect`). It rasterizes no pixels but keeps its place in the painter +/// stream, so `Renderer::draw_range_with` or `Renderer::draw_with` can hand the compositor the pass +/// at exactly this point, inside the enclosing isolated layer if there is one. `rect` is the +/// element, `clip`/`fade` (and the rounded-clip radius in `fade[3]`) its clip, `params.x` `1.0` +/// when the slot requests a backdrop copy (`El::effect_backdrop(true)`), `params.z` the bleed past +/// `rect` in device pixels and `params.w` the slot's scale in device pixels per point (`Env::scale` +/// times any element or ancestor `scale` / `live_scale`). `fill[3]` is always 1: a faded slot is +/// drawn in an isolated layer that applies its opacity. `border[0]` and `border[1]` hold the low +/// and high 16 bits of its `El::effect` tag as exact floats (`EffectSite::mark`), and `uv` its +/// `El::effect_data` payload, bit for bit (`EffectSite::data`). +pub const KIND_EFFECT: f32 = Kind::Effect.as_f32(); +/// A backdrop blur (`El::backdrop_blur`). Like an effect slot it rasterizes nothing itself in +/// the uber shader; the renderer stops there, copies and blurs what is below, and draws the blur +/// inside `rect` with signed corner `radii`, cut by `clip`/`fade`, at opacity `fill[3]`. +/// `params.x` is the blur's standard deviation in device pixels and `params.w` the scale in +/// device pixels per point. +pub const KIND_BACKDROP_BLUR: f32 = Kind::BackdropBlur.as_f32(); + +/// Uniform block bound at `@group(0) @binding(0)` by `shader.wgsl` and `backdrop_composite.wgsl`. +#[repr(C)] +#[derive(Clone, Copy, Debug, Pod, Zeroable)] +pub(crate) struct Globals { + pub viewport: [f32; 2], + /// Split presentation timestamp `[t_hi, t_lo]` for GPU springs (`springs.wgsl`). + pub pad: [f32; 2], + /// `[srgb_blend, byte_source, 0.0, 0.0]`. + pub flags: [f32; 4], +} + +const _: () = { + assert!(size_of::<Globals>() == 32); + assert!(offset_of!(Globals, viewport) == 0); + assert!(offset_of!(Globals, pad) == 8); + assert!(offset_of!(Globals, flags) == 16); +}; + +/// One instance, in device pixels. +#[repr(C)] +#[derive(Clone, Copy, Debug, Pod, Zeroable)] +pub struct Instance { + pub rect: [f32; 4], + pub radii: [f32; 4], + pub fill: [f32; 4], + pub border: [f32; 4], + /// border width, kind, shadow sigma, glyph coverage exponent + pub params: [f32; 4], + pub uv: [f32; 4], + /// x0, y0, x1, y1 + pub clip: [f32; 4], + /// Attribute 7 is Uint32x4; the instance ABI stays 128 bytes (8 × vec4). + /// [0] = pack2x16float(left, top), [1] = pack2x16float(right, bottom) widths; a negative + /// width ramps linearly, a positive one on smoothstep. + /// [2] = pack4x8unorm(clamp(inward origin→clip distance / width, 0, 1)), LTRB. + /// [3] = signed uniform f32 clip-radius bits or tagged mixed radii (`pack_clip_radii`). + /// The rounded rectangle is `clip`; fade widths never occupy this word. + /// Layer records may leave all four words zero. See `pack_fade`. + pub fade: [u32; 4], +} + +const _: () = assert!(size_of::<Instance>() == 128); + +/// Word count of [`Instance`] when viewed as `[u32; INSTANCE_WORDS]`. +pub(crate) const INSTANCE_WORDS: usize = size_of::<Instance>() / 4; + +const fn word_of(byte_offset: usize) -> usize { + assert!(byte_offset.is_multiple_of(4), "Instance field offset must be a multiple of 4 bytes"); + byte_offset / 4 +} + +/// 32-bit word indices into [`Instance`] (viewed as `[u32; INSTANCE_WORDS]`), derived from +/// `offset_of!` so word-level comparisons cannot drift from the struct layout. +pub(crate) mod word { + use std::mem::{offset_of, size_of}; + use std::ops::Range; + + use super::{Instance, shader_consts, word_of}; + + const _: () = { + assert!(size_of::<Instance>() == shader_consts::UBER_ATTR_COUNT * 16); + assert!(word_of(offset_of!(Instance, rect)) == shader_consts::ATTR_RECT_LOC as usize * 4); + assert!(word_of(offset_of!(Instance, radii)) == shader_consts::ATTR_RADII_LOC as usize * 4); + assert!(word_of(offset_of!(Instance, fill)) == shader_consts::ATTR_FILL_LOC as usize * 4); + assert!(word_of(offset_of!(Instance, border)) == shader_consts::ATTR_BORDER_LOC as usize * 4); + assert!(word_of(offset_of!(Instance, params)) == shader_consts::ATTR_PARAMS_LOC as usize * 4); + assert!(word_of(offset_of!(Instance, uv)) == shader_consts::ATTR_UV_LOC as usize * 4); + assert!(word_of(offset_of!(Instance, clip)) == shader_consts::ATTR_CLIP_LOC as usize * 4); + assert!(word_of(offset_of!(Instance, fade)) == shader_consts::ATTR_FADE_LOC as usize * 4); + }; + + pub(crate) const RECT: usize = word_of(offset_of!(Instance, rect)); + pub(crate) const RECT_Y: usize = RECT + 1; + pub(crate) const FILL: Range<usize> = word_of(offset_of!(Instance, fill))..word_of(offset_of!(Instance, fill)) + 4; + pub(crate) const BORDER: Range<usize> = word_of(offset_of!(Instance, border))..word_of(offset_of!(Instance, border)) + 4; + pub(crate) const PARAMS: usize = word_of(offset_of!(Instance, params)); + pub(crate) const PARAMS_W: usize = PARAMS + 3; + pub(crate) const CLIP: usize = word_of(offset_of!(Instance, clip)); + pub(crate) const CLIP_Y0: usize = CLIP + 1; + pub(crate) const CLIP_Y1: usize = CLIP + 3; +} + +/// Bias added to a fade width in `Inh::fade` / `pack_fade` to tag an edge as using the frame's +/// piecewise-linear explicit stops (`ScrollFade::stops`) rather than smoothstep or pure linear. +/// Strictly above `f16::MAX` (`65504.0`) so any normal smoothstep width passes through untouched. +pub(crate) const STOP_FADE_BIAS: f32 = 131_072.0; + +pub fn pack_fade(width: [f32; 4], origin: [f32; 4], clip: [f32; 4]) -> [u32; 4] { + // A negative width is a linear ramp (`El::clip_fade_linear`); `width > STOP_FADE_BIAS` tags + // an edge using explicit piecewise-linear stops (`ScrollFade::stops`, bit 7 of its offset byte). + let mut halves = [0u32; 4]; + let mut offsets = 0u32; + for edge in 0..4 { + let is_stops = width[edge] > STOP_FADE_BIAS; + let raw_w = if is_stops { width[edge] - STOP_FADE_BIAS } else { width[edge] }; + halves[edge] = half::f16::from_f32(raw_w.clamp(-65504.0, 65504.0)).to_bits() as u32; + let distance = if edge < 2 { clip[edge] - origin[edge] } else { origin[edge] - clip[edge] }; + let w = raw_w.abs(); + let offset = if w > 0.0 { (distance / w).clamp(0.0, 1.0) } else { 0.0 }; + let byte = ((offset * 127.0 + 0.5) as u32).min(127) | if is_stops { 0x80 } else { 0 }; + offsets |= byte << (edge * 8); + } + [halves[0] | (halves[1] << 16), halves[2] | (halves[3] << 16), offsets, 0] +} + +/// Decode widths and normalized origin offsets for tools inspecting the instance stream. A +/// negative width is a linear ramp. +pub fn unpack_fade(fade: [u32; 4]) -> ([f32; 4], [f32; 4]) { + (std::array::from_fn(|e| half::f16::from_bits((fade[e / 2] >> ((e % 2) * 16)) as u16).to_f32()), + std::array::from_fn(|e| ((fade[2] >> (e * 8)) & 0x7f) as f32 / 127.0)) +} + +pub const NO_CLIP: [f32; 4] = [-1e6, -1e6, 1e6, 1e6]; + +/// Pack per-corner signed clip radii `[tl, tr, br, bl]` (negative = continuous corners) +/// into `Instance::fade[3]`, clamping each corner to half the shorter `clip` side. +/// Uniform corners stay an exact IEEE-754 `f32`; mixed corners use the `0x6000_0000` +/// high-exponent tag (`|r| >= 2^65` in IEEE-754) with 4 × 7-bit magnitudes. +/// Mixed radii round to 0.5 px through 63.5 px, otherwise 2 px, saturating at 254 px. +/// All nonzero radii must have the same sign (one curve style per clip). Uniform radii +/// saturate just below the tag's exponent range, far beyond device-pixel coordinates. +pub fn pack_clip_radii(clip: [f32; 4], radii: [f32; 4]) -> u32 { + const UNIFORM_MAX: f32 = f32::from_bits(shader_consts::CLIP_RADII_MIXED_TAG - 1); + const LANE_MAX: f32 = shader_consts::CLIP_RADII_LANE_MASK as f32; + const FINE_MAX: f32 = LANE_MAX * shader_consts::CLIP_RADII_FINE_STEP; + const INV_COARSE: f32 = 1.0 / shader_consts::CLIP_RADII_COARSE_STEP; + const INV_FINE: f32 = 1.0 / shader_consts::CLIP_RADII_FINE_STEP; + let half = ((clip[2] - clip[0]).min(clip[3] - clip[1]) * 0.5).max(0.0); + let clamped = radii.map(|radius| { + let r = radius.abs().min(half).min(UNIFORM_MAX); + if radius < 0.0 && r > 0.0 { -r } else { r } + }); + if clamped[0] == clamped[1] && clamped[1] == clamped[2] && clamped[2] == clamped[3] { + return if clamped[0] == 0.0 { 0 } else { clamped[0].to_bits() }; + } + let continuous = clamped.iter().any(|&r| r < 0.0); + let max_r = clamped.iter().fold(0.0f32, |m, r| m.max(r.abs())); + let coarse = max_r > FINE_MAX; + let inv_step = if coarse { INV_COARSE } else { INV_FINE }; + let mut bits = shader_consts::CLIP_RADII_MIXED_TAG + | if continuous { shader_consts::CLIP_RADII_CONTINUOUS_BIT } else { 0 } + | if coarse { shader_consts::CLIP_RADII_COARSE_BIT } else { 0 }; + for (idx, r) in clamped.into_iter().enumerate() { + let q = (r.abs() * inv_step).round().clamp(0.0, LANE_MAX) as u32; + bits |= q << (idx as u32 * shader_consts::CLIP_RADII_LANE_BITS); + } + bits +} + +/// Decode `Instance::fade[3]` into four signed corner radii `[tl, tr, br, bl]`. +pub fn unpack_clip_radii(w: u32) -> [f32; 4] { + if w == 0 { + return [0.0; 4]; + } + if (w & shader_consts::CLIP_RADII_MIXED_TAG) != shader_consts::CLIP_RADII_MIXED_TAG { + return [f32::from_bits(w); 4]; + } + let step = if (w & shader_consts::CLIP_RADII_COARSE_BIT) != 0 { + shader_consts::CLIP_RADII_COARSE_STEP + } else { + shader_consts::CLIP_RADII_FINE_STEP + }; + let sign = if (w & shader_consts::CLIP_RADII_CONTINUOUS_BIT) != 0 { -1.0 } else { 1.0 }; + std::array::from_fn(|idx| { + let q = (w >> (idx as u32 * shader_consts::CLIP_RADII_LANE_BITS)) & shader_consts::CLIP_RADII_LANE_MASK; + if q == 0 { 0.0 } else { q as f32 * step * sign } + }) +} + +/// Sentinel index for `None` (invalid `params[1]` with `<= 11.5` or NaN) in the 15-entry `Kind` +/// tables. Every `KIND_NONE` entry inside `KIND_SLOT_LUT[0..30]` sits at `slot <= 23` (`<= 7.5`), +/// so any `None` with `params[1] > 11.5` always falls outside `0..30`. +const KIND_NONE: usize = Kind::COUNT; + +/// Maps `(bits - 1.0_f32.to_bits()).rotate_left(12)` in `0..30` to `Kind as u8` (`0..14`) or +/// `KIND_NONE` (`14`). Derived solely from [`Kind::from_u8`] and [`Kind::as_f32`]. +const KIND_SLOT_LUT: [u8; 30] = { + const ONE: u32 = KIND_SHADOW.to_bits(); + let mut table = [KIND_NONE as u8; 30]; + let mut k = 1u8; + while (k as usize) < Kind::COUNT { + let Some(kind) = Kind::from_u8(k) else { panic!("dense Kind discriminants") }; + let slot = kind.as_f32().to_bits().wrapping_sub(ONE).rotate_left(12) as usize; + assert!(slot < 30); + table[slot] = k; + k += 1; + } + table +}; + +/// Decodes non-zero `Instance::params[1]` bits to a dense index `0..=Kind::COUNT` +/// (`Kind::COUNT` = `None`). Caller has already handled `±0.0` (`Kind::Rect`). +#[inline(always)] +const fn kind_index_nonzero(bits: u32) -> usize { + const ONE: u32 = KIND_SHADOW.to_bits(); + let slot = bits.wrapping_sub(ONE).rotate_left(12); + if slot < 30 { + KIND_SLOT_LUT[slot as usize] as usize + } else { + KIND_NONE + } +} + +/// Bit-exact integer predicate for `f32::from_bits(bits) > UBER_MAX_KIND_THRESHOLD` (positive +/// finite floats above the threshold and `+inf`; false for negatives, `<=` threshold, and `NaN`). +/// Keeps `bounds_core` purely in integer registers with no XMM-to-GPR transfer. +#[inline(always)] +const fn bits_gt_uber_max(bits: u32) -> bool { + const LIMIT: u32 = shader_consts::UBER_MAX_KIND_THRESHOLD.to_bits(); + const INF: u32 = f32::INFINITY.to_bits(); + bits > LIMIT && bits <= INF +} + +/// Bitmask of `Kind` indices (`0..=Kind::COUNT`) that draw no uber-shader quad (`quad_bounds` is +/// `None`, except `KIND_NONE` which only skips when `params[1] > UBER_MAX_KIND_THRESHOLD`). +const NO_UBER_QUAD_MASK: u32 = + (1 << Kind::LayerEnd.as_u8()) | (1 << Kind::Effect.as_u8()) | (1 << Kind::BackdropBlur.as_u8()); + +#[derive(Clone, Copy)] +enum GrowMode { + Quad, + Layer, + Damage, +} + +const fn grow_spec(kind: Option<Kind>, mode: GrowMode) -> (f32, f32) { + match (mode, kind) { + (GrowMode::Layer | GrowMode::Damage, Some(Kind::Effect)) => (shader_consts::GROW_FLAT, 1.0), + (GrowMode::Layer, Some(Kind::BackdropBlur) | None) => (shader_consts::BACKDROP_COMPOSITE_GROW, 0.0), + (GrowMode::Damage, Some(Kind::BackdropBlur)) => (shader_consts::BACKDROP_COMPOSITE_GROW, 0.0), + (_, Some(Kind::Shadow)) => (shader_consts::GROW_SHADOW_PAD, shader_consts::GROW_SHADOW_SIGMA), + (_, Some(Kind::Glyph)) => (shader_consts::GROW_GLYPH, 0.0), + (_, Some(Kind::Inset | Kind::Segment | Kind::Triangle | Kind::Image | Kind::Layer)) => (shader_consts::GROW_FLAT, 0.0), + (_, Some(Kind::Rect | Kind::Gradient | Kind::Dashed | Kind::Radial) | None) => { + (shader_consts::GROW_RECT_PAD, shader_consts::GROW_RECT_SOFT) + } + (_, Some(Kind::LayerEnd | Kind::Effect | Kind::BackdropBlur)) => (0.0, 0.0), + } +} + +struct GrowTable { + base: [f32; Kind::COUNT + 1], + scale: [f32; Kind::COUNT + 1], + /// Bit `k` is set when `scale[k] != 0.0`, so `params[2]` is masked to `0.0` for other kinds + /// (preserving exact IEEE-754 results even if `params[2]` were NaN or infinite). + uses_p2: u32, +} + +const fn build_grow_table(mode: GrowMode) -> GrowTable { + let mut base = [0.0f32; Kind::COUNT + 1]; + let mut scale = [0.0f32; Kind::COUNT + 1]; + let mut uses_p2 = 0u32; + let mut k = 0usize; + while k <= Kind::COUNT { + let (b, s) = grow_spec(Kind::from_u8(k as u8), mode); + base[k] = b; + scale[k] = s; + if s != 0.0 { + uses_p2 |= 1u32 << k; + } + k += 1; + } + GrowTable { base, scale, uses_p2 } +} + +const QUAD_GROW: GrowTable = build_grow_table(GrowMode::Quad); +const LAYER_GROW: GrowTable = build_grow_table(GrowMode::Layer); +const DAMAGE_GROW: GrowTable = build_grow_table(GrowMode::Damage); + +/// The upright bounds of edges `r` (`[x0, y0, x1, y1]`) turned `angle` radians clockwise about `p`. +#[cold] +#[inline(never)] +pub(crate) fn turned_bounds(r: [f32; 4], angle: f32, p: [f32; 2]) -> [f32; 4] { + let (sn, c) = angle.sin_cos(); + let mut out = [f32::INFINITY, f32::INFINITY, f32::NEG_INFINITY, f32::NEG_INFINITY]; + for (x, y) in [(r[0], r[1]), (r[2], r[1]), (r[0], r[3]), (r[2], r[3])] { + let (dx, dy) = (x - p[0], y - p[1]); + let (qx, qy) = (p[0] + c * dx - sn * dy, p[1] + sn * dx + c * dy); + out = [out[0].min(qx), out[1].min(qy), out[2].max(qx), out[3].max(qy)]; + } + out +} + +/// The upright bounds of a glyph rect `[x, y, w, h]` turned `angle` radians about its centre. +#[cold] +#[inline(never)] +fn turned_glyph_bounds(rect: [f32; 4], angle: f32) -> [f32; 4] { + let (sin, cos) = angle.sin_cos(); + let (w, h) = (cos.abs() * rect[2] + sin.abs() * rect[3], sin.abs() * rect[2] + cos.abs() * rect[3]); + let lo = [rect[0] + (rect[2] - w) * 0.5, rect[1] + (rect[3] - h) * 0.5]; + [lo[0], lo[1], lo[0] + w, lo[1] + h] +} + +/// Band window clamp for a big shadow or border ring (`runtime/bands.rs`, `uv[2] < 0`). +/// Kept inline: it makes no calls (no extra XMM spills) and fires on banded rects/shadows. +#[inline(always)] +fn clamp_band(rect: [f32; 4], uv: [f32; 4], lo0: f32, lo1: f32, hi0: f32, hi1: f32) -> (f32, f32, f32, f32) { + let lo0 = lo0.max(rect[0] + uv[0]); + let lo1 = lo1.max(rect[1] + uv[1]); + let hi0 = hi0.min(rect[0] - uv[2]).max(lo0); + let hi1 = hi1.min(rect[1] + uv[3]).max(lo1); + (lo0, lo1, hi0, hi1) +} + +impl Instance { + /// Decodes the primitive kind stored in `params[1]`. + #[inline(always)] + pub const fn kind(&self) -> Option<Kind> { + Kind::from_f32(self.params[1]) + } + + #[inline(always)] + fn grow_from(table: &GrowTable, k: usize, p2: f32) -> f32 { + let p2 = if ((table.uses_p2 >> k) & 1) != 0 { p2 } else { 0.0 }; + table.base[k] + p2 * table.scale[k] + } + + #[inline(always)] + fn bounds_core<const DAMAGE: bool>(&self, glyph_rot_pad: f32) -> Option<(f32, f32, f32, f32)> { + let bits = self.params[1].to_bits(); + // Fast path for the two dominant kinds (`Rect` and `Glyph`): pure integer tests, no LUT + // load, no `uv` load for glyphs, and zero extra kind checks. + if (bits & 0x7FFF_FFFF) == 0 { + let grow = shader_consts::GROW_RECT_PAD + self.params[2] * shader_consts::GROW_RECT_SOFT; + let lo0 = self.rect[0] - grow; + let lo1 = self.rect[1] - grow; + let (hi0, hi1) = if DAMAGE { + (self.rect[0] + self.rect[2] + grow, self.rect[1] + self.rect[3] + grow) + } else { + (lo0 + self.rect[2] + 2.0 * grow, lo1 + self.rect[3] + 2.0 * grow) + }; + return Some(if self.uv[2] < 0.0 { + clamp_band(self.rect, self.uv, lo0, lo1, hi0, hi1) + } else { + (lo0, lo1, hi0, hi1) + }); + } + if bits == KIND_GLYPH.to_bits() { + if self.params[0] != 0.0 { + let [x0, y0, x1, y1] = turned_glyph_bounds(self.rect, self.params[0]); + return Some((x0 - glyph_rot_pad, y0 - glyph_rot_pad, x1 + glyph_rot_pad, y1 + glyph_rot_pad)); + } + return Some((self.rect[0], self.rect[1], self.rect[0] + self.rect[2], self.rect[1] + self.rect[3])); + } + + // Remaining kinds (`1.0..=13.0` and invalid): branchless 30-entry LUT + affine grow table. + const ONE: u32 = KIND_SHADOW.to_bits(); + let slot = bits.wrapping_sub(ONE).rotate_left(12); + let k = if slot < 30 { + KIND_SLOT_LUT[slot as usize] as usize + } else if bits_gt_uber_max(bits) { + return None; + } else { + KIND_NONE + }; + + if !DAMAGE && ((NO_UBER_QUAD_MASK >> k) & 1) != 0 { + return None; + } + if DAMAGE && k == Kind::LayerEnd.as_u8() as usize { + return None; + } + + let p2 = if DAMAGE && k == Kind::Effect.as_u8() as usize { + self.params[2].max(0.0) + } else { + self.params[2] + }; + let table = if DAMAGE { &DAMAGE_GROW } else { &QUAD_GROW }; + let grow = Self::grow_from(table, k, p2); + let lo0 = self.rect[0] - grow; + let lo1 = self.rect[1] - grow; + let (hi0, hi1) = if DAMAGE { + (self.rect[0] + self.rect[2] + grow, self.rect[1] + self.rect[3] + grow) + } else { + (lo0 + self.rect[2] + 2.0 * grow, lo1 + self.rect[3] + 2.0 * grow) + }; + // A band of a big shadow draws only its window (`runtime/bands.rs`; Rect handled above). + if k == Kind::Shadow.as_u8() as usize && self.uv[2] < 0.0 { + return Some(clamp_band(self.rect, self.uv, lo0, lo1, hi0, hi1)); + } + // A turned layer composite (`Instance::turned`) turns about `border[2..4]`. + if k == Kind::Layer.as_u8() as usize && self.border[1] != 0.0 { + let [x0, y0, x1, y1] = turned_bounds([lo0, lo1, hi0, hi1], self.border[1], [self.border[2], self.border[3]]); + return Some((x0, y0, x1, y1)); + } + Some((lo0, lo1, hi0, hi1)) + } + + /// Axis-aligned device-pixel bounds `[x0, y0, x1, y1]` of the quad the uber vertex shader + /// (`shader.wgsl` `base_vs`) emits for this instance, before clipping. + /// + /// Returns `None` for records that rasterize no uber-shader quad (`Kind::LayerEnd`, + /// `Kind::Effect`, `Kind::BackdropBlur`, and out-of-range values with `params[1] > 11.5`). + #[inline] + pub fn quad_bounds(&self) -> Option<[f32; 4]> { + let (x0, y0, x1, y1) = self.bounds_core::<false>(0.0)?; + Some([x0, y0, x1, y1]) + } + + /// Pre-clip bounds for Windows damage (`window/win32/damage.rs`): `quad_bounds` plus + /// `Kind::Effect` (`params[2].max(0) + 1`) and `Kind::BackdropBlur` (`1`). + #[cfg(target_os = "windows")] + #[inline(always)] + pub(crate) fn damage_quad_bounds(&self) -> Option<(f32, f32, f32, f32)> { + self.bounds_core::<true>(0.0) + } + + /// [`Self::layer_bounds`] when the caller has already ruled out `Kind::Layer` and + /// `Kind::LayerEnd` (`render/layers.rs`, `render/cpu_boot/bin.rs`). Fast-paths the two + /// dominant kinds (`Glyph` and `Rect`) without LUT loads or `uv` reads on glyphs. + #[inline(always)] + pub(crate) fn layer_bounds_non_scope(&self) -> (f32, f32, f32, f32) { + let bits = self.params[1].to_bits(); + if bits == KIND_GLYPH.to_bits() { + let (x0, y0, x1, y1) = if self.params[0] != 0.0 { + let [a, b, c, d] = turned_glyph_bounds(self.rect, self.params[0]); + (a, b, c, d) + } else { + (self.rect[0], self.rect[1], self.rect[0] + self.rect[2], self.rect[1] + self.rect[3]) + }; + return (x0.max(self.clip[0]), y0.max(self.clip[1]), x1.min(self.clip[2]), y1.min(self.clip[3])); + } + if (bits & 0x7FFF_FFFF) == 0 { + let grow = shader_consts::GROW_RECT_PAD + self.params[2] * shader_consts::GROW_RECT_SOFT; + let lo0 = self.rect[0] - grow; + let lo1 = self.rect[1] - grow; + let hi0 = self.rect[0] + self.rect[2] + grow; + let hi1 = self.rect[1] + self.rect[3] + grow; + let (x0, y0, x1, y1) = if self.uv[2] < 0.0 { + clamp_band(self.rect, self.uv, lo0, lo1, hi0, hi1) + } else { + (lo0, lo1, hi0, hi1) + }; + return (x0.max(self.clip[0]), y0.max(self.clip[1]), x1.min(self.clip[2]), y1.min(self.clip[3])); + } + let k = kind_index_nonzero(bits); + let grow = Self::grow_from(&LAYER_GROW, k, self.params[2]); + let lo0 = self.rect[0] - grow; + let lo1 = self.rect[1] - grow; + let hi0 = self.rect[0] + self.rect[2] + grow; + let hi1 = self.rect[1] + self.rect[3] + grow; + let (x0, y0, x1, y1) = if k == Kind::Shadow.as_u8() as usize && self.uv[2] < 0.0 { + clamp_band(self.rect, self.uv, lo0, lo1, hi0, hi1) + } else { + (lo0, lo1, hi0, hi1) + }; + (x0.max(self.clip[0]), y0.max(self.clip[1]), x1.min(self.clip[2]), y1.min(self.clip[3])) + } + + /// Device-pixel bounds `[x0, y0, x1, y1]` this instance contributes to an enclosing isolated + /// layer (`render/layers.rs`), intersected with `self.clip`. Includes non-uber records painted + /// in the layer pass (`Kind::Effect` with bleed `params[2] + 1`, `Kind::BackdropBlur` with `1`). + #[inline] + pub fn layer_bounds(&self) -> [f32; 4] { + if matches!(self.kind(), Some(Kind::Layer | Kind::LayerEnd)) { + return [0.0; 4]; + } + let (x0, y0, x1, y1) = self.layer_bounds_non_scope(); + [x0, y0, x1, y1] + } + + /// The pixels `[x0, y0, x1, y1)` whose centres lie in the quad `shader.wgsl` (`base_vs`) draws + /// for this instance, within the reach of its clip and a `w × h` target. Empty (`[0; 4]`) for + /// records that rasterize nothing in the uber shader. + pub(crate) fn pixel_bounds(&self, w: i32, h: i32) -> [i32; 4] { + // A rotated glyph gets a 1 px margin for trig rounding between CPU and GPU. + let Some((x0, y0, x1, y1)) = self.bounds_core::<false>(1.0) else { return [0; 4] }; + // Centres in [lo, hi): the rasterizer's top-left rule. + // `ceil(a).min(ceil(b)) == ceil(a.min(b))` for all floats (including NaN), and when + // `x0 >= c[0]` or `c[0] <= 0.5` the clip floor cannot exceed `ceil(x0 - 0.5).max(0.0)`. + let c = self.clip; + let x0_ceil = (x0 - 0.5).ceil(); + let y0_ceil = (y0 - 0.5).ceil(); + let px0 = if x0 >= c[0] || c[0] <= 0.5 { x0_ceil } else { x0_ceil.max((c[0] - 0.5).floor()) }.max(0.0); + let py0 = if y0 >= c[1] || c[1] <= 0.5 { y0_ceil } else { y0_ceil.max((c[1] - 0.5).floor()) }.max(0.0); + let px1 = (x1 - 0.5).min(c[2] + 0.5).ceil().min(w as f32); + let py1 = (y1 - 0.5).min(c[3] + 0.5).ceil().min(h as f32); + if !(px1 > px0 && py1 > py0) { + return [0; 4]; + } + [px0 as i32, py0 as i32, px1 as i32, py1 as i32] + } + + /// Rounded clipping shares the packed fade ABI across primitives and layer composites. + /// A negative radius keeps its sign: continuous corners (`corner_extent`). + pub(crate) fn round_clip(&mut self, radius: f32) { + self.round_clip_corners([radius; 4]); + } + + pub(crate) fn round_clip_corners(&mut self, radii: [f32; 4]) { + self.fade[3] = pack_clip_radii(self.clip, radii); + } + + /// Begin an isolated scope. `bounds` is a device-pixel [x,y,w,h] content bound, including + /// native surfaces. Primitive bounds (including shadow support) expand it during prepare. + pub fn begin_layer(bounds: [f32; 4], clip: [f32; 4], spec: LayerSpec) -> Self { + let mut instance = Self { rect: bounds, clip, fill: [0.0, 0.0, 0.0, spec.opacity.clamp(0.0, 1.0)], + params: [if spec.blend == Blend::PlusLighter { shader_consts::LAYER_ADDITIVE_PARAM } else { 0.0 }, KIND_LAYER, + layer_blur::sigma(spec.blur), 0.0], ..Self::zeroed() }; + instance.round_clip(spec.clip_radius); + instance + } + + /// Turn this scope's composite `angle` radians clockwise about `pivot` (device pixels). + /// The contents draw upright; the layer's clip applies after the turn. Layer records keep + /// it in `border[1..4]` as `[angle, pivot.x, pivot.y]`. + pub fn turned(mut self, angle: f32, pivot: [f32; 2]) -> Self { + self.border = [0.0, angle, pivot[0], pivot[1]]; + self + } + + pub fn end_layer() -> Self { + Self { params: [0.0, KIND_LAYER_END, 0.0, 0.0], ..Self::zeroed() } + } +} + +/// An effect slot's `El::effect` tag, from the two exact 16-bit floats in `border` (`KIND_EFFECT`). +pub(crate) fn effect_mark(i: &Instance) -> u32 { + (i.border[0] as u32 & 0xFFFF) | (i.border[1] as u32 & 0xFFFF) << 16 +} + +/// Pack a 64-bit integer into four exact non-negative 16-bit integer floats (`0.0..=65535.0`). +pub(crate) fn pack_u64_f32(v: u64) -> [f32; 4] { + [ + (v & 0xFFFF) as f32, + ((v >> 16) & 0xFFFF) as f32, + ((v >> 32) & 0xFFFF) as f32, + ((v >> 48) & 0xFFFF) as f32, + ] +} + +/// Unpack a 64-bit integer from [`pack_u64_f32`]. +pub(crate) fn unpack_u64_f32(a: [f32; 4]) -> u64 { + (a[0] as u64 & 0xFFFF) + | ((a[1] as u64 & 0xFFFF) << 16) + | ((a[2] as u64 & 0xFFFF) << 32) + | ((a[3] as u64 & 0xFFFF) << 48) +} + +/// Close a runtime scope, folding empty/single-draw groups back into the direct path. Only the +/// last one or two records move, so video insertions before this scope keep their indices. +pub(crate) fn end_layer(instances: &mut Vec<Instance>, surfaces: &mut [crate::native_surface::SurfaceDraw], marks: &mut Vec<u32>, start: usize, surface_start: usize) { + let primitives = instances.len() - start - 1; + let videos = surfaces.len() - surface_start; + let scope = instances[start]; + let unmasked = if primitives == 1 { + instances[start + 1].clip == NO_CLIP && instances[start + 1].fade == [0; 4] + } else if videos == 1 { + surfaces[surface_start].clip == NO_CLIP && surfaces[surface_start].fade == [0; 4] + } else { true }; + let transfer_clip = scope.fade[3] == 0 && unmasked; + // A lone effect slot keeps a faded scope: the compositor's paint can't take the opacity. + let faded_effect = primitives == 1 && instances[start + 1].kind() == Some(Kind::Effect) && scope.fill[3] != 1.0; + // A layer's `radii` hold its hole (`El::cutout_circle`), which only its composite can cut. + if !faded_effect && primitives + videos <= 1 && (primitives + videos == 0 || (scope.border[1] == 0.0 && scope.radii == [0.0; 4])) && scope.params[0] == 0.0 && scope.params[2] == 0.0 && scope.params[3] == 0.0 + && (transfer_clip || (scope.clip == NO_CLIP && scope.fade == [0; 4])) { + let opacity = scope.fill[3]; + if primitives == 1 { + let i = &mut instances[start + 1]; + if transfer_clip { i.clip = scope.clip; i.fade = scope.fade; } + i.fill = i.fill.map(|v| v * opacity); + // A glyph's `border` holds no colour (an outline glyph's names its record). + // A box's `params.w` is the opacity its colours carry (shader.wgsl `border_over`). + match i.kind() { + Some(Kind::Glyph) => {} + Some(Kind::Rect) => { + i.border = i.border.map(|v| v * opacity); + i.params[3] *= opacity; + } + Some(Kind::Gradient) => { + i.border = i.border.map(|v| v * opacity); + i.uv = i.uv.map(|v| v * opacity); + i.params[3] *= opacity; + } + Some( + Kind::Shadow | Kind::Inset | Kind::Segment | Kind::Triangle | Kind::Image + | Kind::Layer | Kind::LayerEnd | Kind::Dashed | Kind::Radial + | Kind::Effect | Kind::BackdropBlur, + ) | None => { + i.border = i.border.map(|v| v * opacity); + } + } + } + if videos == 1 { + if transfer_clip { surfaces[surface_start].clip = scope.clip; surfaces[surface_start].fade = scope.fade; } + surfaces[surface_start].opacity *= opacity; + surfaces[surface_start].before_instance -= 1; + } + instances.remove(start); + if marks.len() > start { marks.remove(start); } + } else { + instances.push(Instance::end_layer()); + if let Some(&mark) = marks.get(start) { marks.push(mark); } + } +} diff --git a/app/vendor/rune/crates/rune/src/render/layer_blur.rs b/app/vendor/rune/crates/rune/src/render/layer_blur.rs new file mode 100644 index 0000000..c4e26cd --- /dev/null +++ b/app/vendor/rune/crates/rune/src/render/layer_blur.rs @@ -0,0 +1,277 @@ +//! Separable premultiplied Gaussian. Wider kernels use continuously scaled intermediate +//! resolution; the final reconstruction returns to the layer so composite bindings stay stable. +use bytemuck::{Pod, Zeroable}; + +use super::instance::shader_consts; + +pub(crate) const MAX_SIGMA: f32 = 64.0; +pub(crate) fn sigma(value: f32) -> f32 { value.max(0.0).min(MAX_SIGMA) } +const TAPS: usize = shader_consts::LAYER_BLUR_TAPS; // centre + ceil(3 * MAX_SIGMA / 2) pairs; padded for Pod arrays + +#[repr(C)] +#[derive(Clone, Copy, Pod, Zeroable)] +pub(super) struct Uniforms { + pub(super) meta: [f32; 4], // used width, height, axis (0 horizontal), tap count + pub(super) mapping: [f32; 4], // output->input scale xy + pub(super) taps: [[f32; 4]; TAPS], // offset, weight; vec4 stride matches WGSL uniform arrays +} + +const _: () = { + assert!(std::mem::size_of::<Uniforms>() == 2080); + assert!(std::mem::offset_of!(Uniforms, meta) == 0); + assert!(std::mem::offset_of!(Uniforms, mapping) == 16); + assert!(std::mem::offset_of!(Uniforms, taps) == 32); +}; + +pub(super) struct Pipeline { + pipelines: [wgpu::RenderPipeline; 5], + layout: wgpu::BindGroupLayout, + sampler: wgpu::Sampler, +} + +pub(super) struct Scratch { + texture: wgpu::Texture, + view: wgpu::TextureView, + /// The reduced work target, allocated the first time a blur needs one and kept after. + work: Option<(wgpu::Texture, wgpu::TextureView, wgpu::BindGroup)>, + uniforms: [wgpu::Buffer; 4], + bindings: [wgpu::BindGroup; 4], + additive: bool, + mode: Mode, + /// Set by `forget_uniforms`: the next `prepare` writes even when nothing changed. + stale: bool, + #[cfg(test)] + pub uniform_writes: usize, +} + +/// How a blur runs, and the inputs its uniforms were written for. +#[derive(Clone, Copy)] +enum Mode { + /// Nothing prepared yet: the next `prepare` writes whatever it is given. + Unprepared, + /// Two passes: horizontal into `view`, vertical into the destination, at `size`. + Direct { size: [f32; 2], sigma: f32 }, + /// Four passes through `reduced`: downsample, blur, blur back up, then reconstruct at `size`. + Reduced { size: [f32; 2], reduced: [f32; 2], sigma: f32 }, +} + +impl Mode { + /// Whether `prepare` can leave the uniforms this mode wrote alone. + fn matches(&self, size: [f32; 2], sigma: f32) -> bool { + match self { + Mode::Unprepared => false, + Mode::Direct { size: s, sigma: g } | Mode::Reduced { size: s, sigma: g, .. } => *s == size && *g == sigma, + } + } + + fn passes(&self) -> usize { if matches!(self, Mode::Reduced { .. }) { 4 } else { 2 } } +} + +/// The pass's shader (`layer_blur.wgsl`). +pub(crate) const WGSL: &str = include_str!("../shaders/layer_blur.wgsl"); + +/// Each pipeline's `MODE` and `ADDITIVE` overrides, in `Pipeline::pipelines`' order. +pub(crate) const MODES: [(f64, f64); 5] = [ + (shader_consts::LAYER_BLUR_MODE_BLUR as f64, 0.0), + (shader_consts::LAYER_BLUR_MODE_BLUR as f64, 1.0), + (shader_consts::LAYER_BLUR_MODE_PREFILTER as f64, 0.0), + (shader_consts::LAYER_BLUR_MODE_PREFILTER as f64, 1.0), + (shader_consts::LAYER_BLUR_MODE_RECONSTRUCT as f64, 0.0), +]; + +impl Pipeline { + /// The pipelines for layers of `format` (`layers::FORMAT`). + pub fn new(device: &wgpu::Device, format: wgpu::TextureFormat) -> Self { + let layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + label: Some("gaussian inputs"), entries: &[ + wgpu::BindGroupLayoutEntry { binding: 0, visibility: wgpu::ShaderStages::FRAGMENT, + ty: wgpu::BindingType::Texture { sample_type: wgpu::TextureSampleType::Float { filterable: true }, + view_dimension: wgpu::TextureViewDimension::D2, multisampled: false }, count: None }, + wgpu::BindGroupLayoutEntry { binding: 1, visibility: wgpu::ShaderStages::FRAGMENT, + ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering), count: None }, + wgpu::BindGroupLayoutEntry { binding: 2, visibility: wgpu::ShaderStages::FRAGMENT, + ty: wgpu::BindingType::Buffer { ty: wgpu::BufferBindingType::Uniform, has_dynamic_offset: false, min_binding_size: None }, count: None }, + ], + }); + let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + label: Some("gaussian"), bind_group_layouts: &[Some(&layout)], immediate_size: 0, + }); + // One pipeline per `MODES` entry: from WGSL, its `MODE` and `ADDITIVE` overrides set here; from + // DX12 bytecode (`fragments[i]`), compiled in by regen_dxbc. + let make = |vertex: &wgpu::ShaderModule, fragments: &[&wgpu::ShaderModule; 5], overrides: bool| std::array::from_fn(|i| { + let (mode, additive) = MODES[i]; + let constants = [(shader_consts::LAYER_BLUR_OVERRIDE_MODE, mode), (shader_consts::LAYER_BLUR_OVERRIDE_ADDITIVE, additive)]; + device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { + label: Some("layer gaussian"), layout: Some(&pipeline_layout), + vertex: wgpu::VertexState { module: vertex, entry_point: Some("vs"), compilation_options: Default::default(), buffers: &[] }, + primitive: Default::default(), depth_stencil: None, multisample: Default::default(), + fragment: Some(wgpu::FragmentState { module: fragments[i], entry_point: Some("fs"), + compilation_options: wgpu::PipelineCompilationOptions { constants: if overrides { &constants } else { &[] }, ..Default::default() }, + targets: &[Some(wgpu::ColorTargetState { format, blend: None, write_mask: wgpu::ColorWrites::ALL })] }), + multiview_mask: None, cache: None, + }) + }); + #[cfg(target_os = "windows")] + let precompiled = super::dxbc::layer_blur(device, WGSL, |m| make(&m[0], &[&m[1], &m[2], &m[3], &m[4], &m[5]], false)); + #[cfg(not(target_os = "windows"))] + let precompiled = None; + let pipelines = precompiled.unwrap_or_else(|| { + let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some("layer gaussian"), source: wgpu::ShaderSource::Wgsl(WGSL.into()) }); + make(&shader, &[&shader; 5], true) + }); + let sampler = device.create_sampler(&wgpu::SamplerDescriptor { + label: Some("gaussian linear taps"), mag_filter: wgpu::FilterMode::Linear, min_filter: wgpu::FilterMode::Linear, + ..Default::default() + }); + Self { pipelines, layout, sampler } + } + + pub fn scratch(&self, device: &wgpu::Device, source: &wgpu::Texture) -> Scratch { + let texture = device.create_texture(&wgpu::TextureDescriptor { + label: Some("layer gaussian scratch"), size: source.size(), mip_level_count: 1, sample_count: 1, + dimension: wgpu::TextureDimension::D2, format: super::layers::FORMAT, + usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING, view_formats: &[], + }); + let view = texture.create_view(&Default::default()); + let input = source.create_view(&Default::default()); + let uniforms = std::array::from_fn(|_| device.create_buffer(&wgpu::BufferDescriptor { + label: Some("gaussian taps"), size: std::mem::size_of::<Uniforms>() as u64, + usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, mapped_at_creation: false, + })); + let bindings = std::array::from_fn(|axis| device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("gaussian input"), layout: &self.layout, + entries: &[ + wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::TextureView(if axis == 0 { &input } else { &view }) }, + wgpu::BindGroupEntry { binding: 1, resource: wgpu::BindingResource::Sampler(&self.sampler) }, + wgpu::BindGroupEntry { binding: 2, resource: uniforms[axis].as_entire_binding() }, + ], + })); + Scratch { texture, view, uniforms, bindings, work: None, additive: false, mode: Mode::Unprepared, + stale: false, #[cfg(test)] uniform_writes: 0 } + } + + pub fn encode(&self, encoder: &mut wgpu::CommandEncoder, scratch: &Scratch, destination: &wgpu::TextureView) { + let (size, reduced) = match scratch.mode { + Mode::Unprepared => return, + Mode::Direct { size, .. } => (size, None), + Mode::Reduced { size, reduced, .. } => (size, Some(reduced)), + }; + let work = reduced.map(|_| scratch.work.as_ref().expect("a reduced blur allocates its work target")); + for axis in 0..if reduced.is_some() { 4 } else { 2 } { + let (view, bind, at) = match (reduced, work) { + (Some(reduced), Some((_, work, bind))) => match axis { + 0 => (&scratch.view, &scratch.bindings[0], reduced), + 1 => (work, &scratch.bindings[1], reduced), + 2 => (&scratch.view, bind, reduced), + _ => (destination, &scratch.bindings[3], size), + }, + _ => (if axis == 0 { &scratch.view } else { destination }, &scratch.bindings[axis], size), + }; + let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { + label: Some("layer gaussian axis"), + color_attachments: &[Some(wgpu::RenderPassColorAttachment { view, depth_slice: None, resolve_target: None, + ops: wgpu::Operations { load: wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT), store: wgpu::StoreOp::Store } })], + ..Default::default() + }); + pass.set_viewport(0.0, 0.0, at[0], at[1], 0.0, 1.0); + let pipeline = match (reduced.is_some(), axis) { + (true, 3) => 4, + (true, 0) => 2 + usize::from(scratch.additive), + _ => usize::from(axis == 0 && scratch.additive), + }; + pass.set_pipeline(&self.pipelines[pipeline]); + pass.set_bind_group(0, bind, &[]); + pass.draw(0..3, 0..1); + } + } +} + +impl Scratch { + pub fn bytes(&self) -> u64 { + u64::from(self.texture.width()) * u64::from(self.texture.height()) * 8 + + self.work.as_ref().map_or(0, |(t, _, _)| u64::from(t.width()) * u64::from(t.height()) * 8) + } + pub fn passes(&self) -> usize { self.mode.passes() } + + /// Makes the next `prepare` write the uniforms again. + pub fn forget_uniforms(&mut self) { self.stale = true; } + + pub fn prepare(&mut self, device: &wgpu::Device, pipeline: &Pipeline, staging: &rune_staging::Staging, size: [f32; 2], sigma: f32, additive: bool) -> bool { + let sigma = sigma.clamp(0.001, MAX_SIGMA); + if !self.stale && self.additive == additive && self.mode.matches(size, sigma) { return false; } + let reduction = (sigma / 3.0).clamp(1.0, 8.0); + let reduced = size.map(|v| (v / reduction).ceil()); + let next = if reduced != size { + Mode::Reduced { size, reduced, sigma } + } else { + Mode::Direct { size, sigma } + }; + let allocated = matches!(next, Mode::Reduced { .. }) && self.work.is_none(); + self.mode = next; + self.additive = additive; + self.stale = false; + if allocated { + // Allocate against the stable primary bucket, not each animated reduced size. + let texture = device.create_texture(&wgpu::TextureDescriptor { + label: Some("gaussian reduced work"), size: self.texture.size(), mip_level_count: 1, sample_count: 1, + dimension: wgpu::TextureDimension::D2, format: super::layers::FORMAT, + usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING, view_formats: &[], + }); + let view = texture.create_view(&Default::default()); + let bind = device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("gaussian reduced input"), layout: &pipeline.layout, entries: &[ + wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::TextureView(&view) }, + wgpu::BindGroupEntry { binding: 1, resource: wgpu::BindingResource::Sampler(&pipeline.sampler) }, + wgpu::BindGroupEntry { binding: 2, resource: self.uniforms[2].as_entire_binding() }, + ], + }); + self.work = Some((texture, view, bind)); + } + let (passes, reduced) = match self.mode { + Mode::Reduced { reduced, .. } => (4, reduced), + _ => (2, size), + }; + let scale = [size[0] / reduced[0], size[1] / reduced[1]]; + for pass in 0usize..passes { + let axis = if passes == 4 { pass.saturating_sub(1).min(1) } else { pass }; + let input = if passes == 2 || pass == 0 { size } else { reduced }; + let mode = if passes == 2 { + axis as u32 + } else { + [shader_consts::LAYER_BLUR_MODE_PREFILTER, 0, 1, shader_consts::LAYER_BLUR_MODE_RECONSTRUCT][pass] + }; + // Subtract the box prefilter + linear reconstruction variance from the Gaussian. + let variance = (scale[axis] * scale[axis] - 1.0) * 0.25; + let mut u = kernel((sigma * sigma - variance).sqrt() / scale[axis]); + u.meta = [input[0], input[1], mode as f32, u.meta[3]]; + u.mapping = match mode { + shader_consts::LAYER_BLUR_MODE_PREFILTER => [scale[0], scale[1], 0.0, 0.0], + shader_consts::LAYER_BLUR_MODE_RECONSTRUCT => [1.0 / scale[0], 1.0 / scale[1], 0.0, 0.0], + _ => [1.0, 1.0, 0.0, 0.0], + }; + staging.write_buffer(&self.uniforms[pass], 0, bytemuck::bytes_of(&u)); + #[cfg(test)] { self.uniform_writes += 1; } + } + allocated + } +} + +fn kernel(sigma: f32) -> Uniforms { + let radius = (3.0 * sigma).ceil() as usize; + let weight = |x: usize| (-0.5 * (x as f32 / sigma).powi(2)).exp(); + let sum = 1.0 + 2.0 * (1..=radius).map(weight).sum::<f32>(); + let mut u = Uniforms::zeroed(); + u.taps[0][1] = 1.0 / sum; + let mut count = 1; + for x in (1..=radius).step_by(2) { + let a = weight(x); + let b = if x < radius { weight(x + 1) } else { 0.0 }; + let w = a + b; + if w > 0.0 { + u.taps[count] = [x as f32 + b / w, w / sum, 0.0, 0.0]; + count += 1; + } + } + u.meta[3] = count as f32; + u +} diff --git a/app/vendor/rune/crates/rune/src/render/layer_filter_tests.rs b/app/vendor/rune/crates/rune/src/render/layer_filter_tests.rs new file mode 100644 index 0000000..fea5279 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/render/layer_filter_tests.rs @@ -0,0 +1,449 @@ +use super::*; +use super::tests::{rect, pixels, rgba, near}; +use crate::{Color, Cx, El, Env, Live, Runtime, el}; + +fn filtered(bounds: [f32; 4], sigma: f32) -> Vec<Instance> { + vec![Instance::begin_layer(bounds, NO_CLIP, LayerSpec { blur: sigma, ..Default::default() }), + rect(bounds, [1.0; 4]), Instance::end_layer()] +} + +// Independent discrete Gaussian oracle (no paired taps, no renderer bounds/pooling logic). +fn coverage(x: i32, start: i32, end: i32, sigma: f32) -> f32 { + let radius = (3.0 * sigma).ceil() as i32; + let weight = |d: i32| (-0.5 * (d as f32 / sigma).powi(2)).exp(); + let total: f32 = (-radius..=radius).map(weight).sum(); + (-radius..=radius).filter(|d| (start..end).contains(&(x + d))).map(weight).sum::<f32>() / total +} + +#[test] +fn gaussian_pixels_support_offscreen_saturation_and_pooling() { + let gpu = Gpu::headless(); + let mut renderer = Renderer::new(&gpu.device, OFFSCREEN_FORMAT); + let target = Offscreen::new(&gpu.device, 64, 48); + let mut atlas = crate::text::TextSystem::default().atlas; + // Negative origin tests retained source outside the destination viewport. The duplicate + // additive shape must saturate BEFORE blur (clamping after convolution doubles the halo). + for (left, top, sigma, additive) in [(12, 10, 2.0, false), (-6, -4, 3.0, false), (12, 10, 2.0, true)] { + let bounds = [left as f32, top as f32, 20.0, 16.0]; + let mut content = filtered(bounds, sigma); + if additive { content[0].params[0] = 1.0; content.insert(2, rect(bounds, [1.0; 4])); } + renderer.prepare(&gpu.device, &gpu.queue, &mut atlas, &content, (64, 48)); + assert_eq!(renderer.layer_stats().extra_passes, 3); + let out = pixels(&gpu, &renderer, &target); + for y in 0..48 { for x in 0..64 { + let c = coverage(x, left, left + 20, sigma) * coverage(y, top, top + 16, sigma); + let at = ((y * 64 + x) * 4) as usize; + near(&out[at..at + 4], rgba([c; 4])); + } } + } + let allocations = renderer.layer_stats().allocations; + for sigma in [2.1, 2.4, 2.0] { + renderer.prepare(&gpu.device, &gpu.queue, &mut atlas, &filtered([12.0, 10.0, 20.0, 16.0], sigma), (64, 48)); + assert_eq!(renderer.layer_stats().allocations, allocations); + } + for sigma in [0.0, -1.0, f32::NAN] { + renderer.prepare(&gpu.device, &gpu.queue, &mut atlas, &filtered([12.0, 10.0, 20.0, 16.0], sigma), (64, 48)); + assert_eq!(renderer.layer_stats().targets, 0); + assert_eq!(renderer.layer_stats().extra_passes, 0); + } +} + +#[test] +fn cached_blur_only_counts_passes_when_it_draws_the_layer() { + fn view(_: &(), _: &mut Cx<()>) -> El { + el().size(20.0, 16.0).fill(Color::WHITE).blur(2.0).cache() + } + let gpu = Gpu::headless(); + let mut renderer = Renderer::new(&gpu.device, OFFSCREEN_FORMAT); + let mut rt = Runtime::new((), view, (32.0, 32.0), Env::new(true, 1.0)); + let target = Offscreen::new(&gpu.device, 32, 32); + for expected in [3, 0] { + rt.frame(1.0 / 60.0); + renderer.prepare(&gpu.device, &gpu.queue, &mut rt.text.atlas, &rt.instances, (32, 32)); + let _ = pixels(&gpu, &renderer, &target); + assert_eq!(renderer.layer_stats().extra_passes, expected); + } +} + +#[test] +fn blur_live_springs_curves_and_zero_bypass() { + fn view(value: &Live<f32>, _: &mut Cx<Live<f32>>) -> El { + el().size(20.0, 16.0).fill(Color::WHITE).live_blur(value) + } + let mut rt = Runtime::new(Live::new(0.0), view, (64.0, 48.0), Env { scale: 2.0, system_dark: true }); + rt.frame(0.0); + assert_eq!(rt.instances.len(), 1); + let commits = rt.stats.commits; + rt.state.set(2.0); rt.frame(0.0); + assert_eq!(rt.instances[0].params[1], KIND_LAYER); + assert_eq!(rt.instances[0].params[2], 4.0); + assert_eq!(rt.instances[1].params[2], 0.0, "do not also blur each primitive"); + rt.state.set(0.0); rt.frame(0.0); + assert_eq!(rt.instances.len(), 1); + assert_eq!(rt.stats.commits, commits); + + fn smooth(value: &Live<f32>, _: &mut Cx<Live<f32>>) -> El { + el().size(20.0, 16.0).fill(Color::WHITE).live_blur(value.smooth(crate::Spring::new(0.3, 0.0))) + } + let mut rt = Runtime::new(Live::new(0.0), smooth, (64.0, 48.0), Env { scale: 1.0, system_dark: true }); + rt.frame(0.0); rt.state.set(4.0); rt.frame(0.05); + let first = rt.instances[0].params[2]; + assert!(first > 0.0 && first < 4.0); + rt.frame(0.05); + assert!(rt.instances[0].params[2] > first); + + fn curve(value: &f32, _: &mut Cx<f32>) -> El { + el().size(20.0, 16.0).fill(Color::WHITE).blur(*value) + .blur_motion(rune_motion::Curve::ease_in_out(0.2)) + } + let mut rt = Runtime::new(4.0, curve, (64.0, 48.0), Env { scale: 1.0, system_dark: true }); + rt.frame(0.0); rt.state = 0.0; rt.invalidate(); rt.frame(0.0); rt.frame(0.05); + assert!(rt.instances[0].params[2] > 0.0 && rt.instances[0].params[2] < 4.0); + for _ in 0..30 { rt.frame(1.0 / 60.0); } + assert_eq!(rt.instances.len(), 1); +} + +#[test] +fn runtime_keeps_offscreen_blur_sources_and_presence_transitions() { + fn offscreen(_: &(), _: &mut Cx<()>) -> El { + el().child(el().size(6.0, 12.0).absolute(-8.0, 12.0).fill(Color::WHITE).blur(4.0)) + } + let gpu = Gpu::headless(); + let mut renderer = Renderer::new(&gpu.device, OFFSCREEN_FORMAT); + let target = Offscreen::new(&gpu.device, 64, 48); + let mut rt = Runtime::new((), offscreen, (64.0, 48.0), Env { scale: 1.0, system_dark: true }); + rt.frame(0.0); + assert!(rt.instances.iter().any(|i| i.params[1] == KIND_RECT && i.rect[0] < 0.0)); + renderer.prepare(&gpu.device, &gpu.queue, &mut rt.text.atlas, &rt.instances, (64, 48)); + let out = pixels(&gpu, &renderer, &target); + assert!(out[(18 * 64) * 4 + 3] > 0, "offscreen paint contributes to the visible halo"); + + fn presence(show: &bool, _: &mut Cx<bool>) -> El { + el().children(show.then(|| el().key("state").size(20.0, 16.0).fill(Color::WHITE) + .transition(rune_motion::Transition::blur(4.0)))) + } + let mut rt = Runtime::new(false, presence, (64.0, 48.0), Env { scale: 1.0, system_dark: true }); + rt.frame(0.0); rt.state = true; rt.invalidate(); rt.frame(0.0); rt.frame(0.05); + assert!(rt.instances.iter().any(|i| i.params[1] == KIND_LAYER && i.params[2] > 0.0)); + assert!(rt.instances.iter().filter(|i| i.params[1] == KIND_RECT).all(|i| i.params[2] == 0.0)); + for _ in 0..120 { rt.frame(1.0 / 120.0); } + assert!(rt.instances.iter().all(|i| i.params[1] != KIND_LAYER)); +} + +#[test] +fn later_live_blur_binding_replaces_the_earlier_source() { + type State = (Live<f32>, Live<f32>); + fn view(s: &State, _: &mut Cx<State>) -> El { + el().size(20.0, 16.0).fill(Color::WHITE).live_blur(&s.0).live_blur(&s.1) + } + let mut rt = Runtime::new((Live::new(1.0), Live::new(2.0)), view, (64.0, 48.0), Env { scale: 1.0, system_dark: true }); + rt.frame(0.0); + rt.state.0.set(4.0); rt.frame(0.0); + assert_eq!(rt.instances[0].params[2], 2.0); +} + +#[test] +fn nested_blur_and_capsule_mask_apply_to_completed_output() { + let gpu = Gpu::headless(); + let mut renderer = Renderer::new(&gpu.device, OFFSCREEN_FORMAT); + let target = Offscreen::new(&gpu.device, 64, 48); + let mut atlas = crate::text::TextSystem::default().atlas; + let clip = [8.0, 8.0, 56.0, 40.0]; + // The source covers the capsule plus filter support; mask AFTER filtering must preserve + // unit coverage in the middle of its straight edges and transparent corner exteriors. + let mut outer = Instance::begin_layer([0.0, 0.0, 64.0, 48.0], clip, + LayerSpec { blur: 2.0, clip_radius: 16.0, opacity: 0.5, ..Default::default() }); + let mut all = vec![outer]; + all.extend(filtered([0.0, 0.0, 64.0, 48.0], 2.0)); + all.push(Instance::end_layer()); + renderer.prepare(&gpu.device, &gpu.queue, &mut atlas, &all, (64, 48)); + assert_eq!(renderer.layer_stats().extra_passes, 6); + let out = pixels(&gpu, &renderer, &target); + for (x, y, c) in [(8, 8, 0.0), (55, 39, 0.0), (32, 24, 0.5), (32, 9, 0.5), (4, 24, 0.0)] { + let at = (y * 64 + x) * 4; + near(&out[at..at + 4], rgba([c; 4])); + } + // An intersecting rectangular ancestor must not recenter the child's rounded rectangle. + outer = Instance::begin_layer([0.0, 0.0, 64.0, 48.0], [24.0, 0.0, 64.0, 48.0], + LayerSpec { opacity: 0.5, ..Default::default() }); + all = vec![outer, Instance::begin_layer([0.0, 0.0, 64.0, 48.0], clip, + LayerSpec { clip_radius: 16.0, ..Default::default() }), rect([0.0, 0.0, 64.0, 48.0], [1.0; 4]), + Instance::end_layer(), Instance::end_layer()]; + renderer.prepare(&gpu.device, &gpu.queue, &mut atlas, &all, (64, 48)); + let out = pixels(&gpu, &renderer, &target); + near(&out[(8 * 64 + 24) * 4..(8 * 64 + 25) * 4], rgba([0.5; 4])); + near(&out[(24 * 64 + 20) * 4..(24 * 64 + 21) * 4], [0; 4]); +} + +#[test] +fn nested_targets_bound_ancestor_support_without_losing_halos() { + let gpu = Gpu::headless(); + let mut renderer = Renderer::new(&gpu.device, OFFSCREEN_FORMAT); + let target = Offscreen::new(&gpu.device, 512, 512); + let mut atlas = crate::text::TextSystem::default().atlas; + let clip = [240.0, 240.0, 272.0, 272.0]; + let mut content = vec![Instance::begin_layer([0.0, 0.0, 512.0, 512.0], NO_CLIP, + LayerSpec { blur: 3.0, ..Default::default() })]; + content.push(Instance::begin_layer([0.0, 0.0, 512.0, 512.0], NO_CLIP, + LayerSpec { blur: 2.0, ..Default::default() })); + content.extend(filtered([232.0, 246.0, 6.0, 20.0], 1.0)); + content.extend([Instance::end_layer(), Instance::end_layer()]); + renderer.prepare(&gpu.device, &gpu.queue, &mut atlas, &content, (512, 512)); + let reference = pixels(&gpu, &renderer, &target); + content[0].clip = clip; + renderer.prepare(&gpu.device, &gpu.queue, &mut atlas, &content, (512, 512)); + for t in renderer.layers.targets.iter().flatten() { + assert!(t.texture.width() <= 64 && t.texture.height() <= 64, "bound every nested texture"); + } + let out = pixels(&gpu, &renderer, &target); + let mut halo = false; + for y in 0..512 { for x in 0..512 { + let at = (y * 512 + x) * 4 + 3; + let inside = (240..272).contains(&x) && (240..272).contains(&y); + let want = if inside { reference[at] } else { 0 }; + assert!(out[at].abs_diff(want) <= 1, "({x},{y})"); + halo |= inside && out[at] > 0; + } } + assert!(halo, "off-wall source still contributes through all ancestor filters"); +} + +#[test] +fn unchanged_blur_reuses_uniforms_and_changed_inputs_refresh_them() { + let gpu = Gpu::headless(); + let mut renderer = Renderer::new(&gpu.device, OFFSCREEN_FORMAT); + let mut atlas = crate::text::TextSystem::default().atlas; + let mut writes = 0; + for (width, sigma, additive, changed) in [(20.0, 2.0, false, true), (20.0, 2.0, false, false), + (20.0, 2.5, false, true), (22.0, 2.5, false, true), (22.0, 2.5, true, true), + (22.0, 4.0, true, true), (22.0, 4.0, true, false), (22.0, 2.0, true, true)] { + let mut content = filtered([12.0, 10.0, width, 16.0], sigma); + content[0].params[0] = if additive { 1.0 } else { 0.0 }; + renderer.prepare(&gpu.device, &gpu.queue, &mut atlas, &content, (64, 48)); + let blur = renderer.layers.targets[0].as_ref().unwrap().blur.as_ref().unwrap(); + let expected = writes + if changed { blur.passes() } else { 0 }; + assert_eq!(blur.uniform_writes, expected); + writes = expected; + } +} + +#[test] +fn filtered_video_and_image_page_match_primitive_source() { + use crate::native_surface::{ByteFrame, ColorInfo, Format, NativeSurface, SurfaceDraw, SurfaceFit}; + use crate::pixels::{Pixels, ImageAtlas}; + let gpu = Gpu::headless(); + let mut renderer = Renderer::new(&gpu.device, OFFSCREEN_FORMAT); + let target = Offscreen::new(&gpu.device, 64, 48); + let mut atlas = crate::text::TextSystem::default().atlas; + let bounds = [12.0, 10.0, 20.0, 16.0]; + let mut content = filtered(bounds, 2.0); + renderer.prepare(&gpu.device, &gpu.queue, &mut atlas, &content, (64, 48)); + let reference = pixels(&gpu, &renderer, &target); + let mut images = ImageAtlas::default(); + let full = Pixels::new(); full.set(1024, 1024, vec![255; 1024 * 1024 * 4]); + images.place(&full, [1024.0; 2]).unwrap(); + let white = Pixels::new(); white.set(1, 1, vec![255; 4]); + let image = images.place(&white, [20.0, 16.0]).unwrap(); + assert_eq!(image.page, 1); + content[1] = Instance { rect: bounds, fill: [0.0, 0.0, 0.0, 1.0], clip: NO_CLIP, + uv: image.rect.map(|v| v as f32), params: [image.page as f32, KIND_IMAGE, 0.0, 1.0], ..Instance::zeroed() }; + renderer.prepare(&gpu.device, &gpu.queue, &mut atlas, &content, (64, 48)); + renderer.upload_images(&gpu.device, &gpu.queue, &mut images); + assert_eq!(pixels(&gpu, &renderer, &target), reference); + content.remove(1); + renderer.prepare(&gpu.device, &gpu.queue, &mut atlas, &content, (64, 48)); + let surface = NativeSurface::new(); + surface.push_bytes(ByteFrame { width: 1, height: 1, format: Format::Bgra, color: ColorInfo::default(), + planes: [vec![255; 4], vec![]] }, 1).unwrap(); + renderer.prepare_surfaces(&gpu.device, &gpu.queue, &[SurfaceDraw { surface: surface.clone(), fit: SurfaceFit::Fill, + before_instance: 1, rect: bounds, radii: [0.0; 4], clip: NO_CLIP, fade: [0; 4], opacity: 1.0 }], (64, 48)); + assert_eq!(pixels(&gpu, &renderer, &target), reference); + surface.push_bytes(ByteFrame { width: 1, height: 1, format: Format::Bgra, color: ColorInfo::default(), + planes: [vec![0, 0, 0, 255], vec![]] }, 2).unwrap(); + renderer.prepare_surfaces(&gpu.device, &gpu.queue, &[SurfaceDraw { surface, fit: SurfaceFit::Fill, + before_instance: 1, rect: bounds, radii: [0.0; 4], clip: NO_CLIP, fade: [0; 4], opacity: 1.0 }], (64, 48)); + let black = pixels(&gpu, &renderer, &target); + assert_eq!(black[(18 * 64 + 22) * 4], 0, "new video frame is never cached"); + assert_eq!(black[(18 * 64 + 22) * 4 + 3], reference[(18 * 64 + 22) * 4 + 3]); +} + +pub(super) fn gpu_time(gpu: &Gpu, mut draw: impl FnMut(&mut wgpu::CommandEncoder, wgpu::RenderPassTimestampWrites<'_>)) -> (f64, f64) { + const N: u32 = 68; + let queries = gpu.device.create_query_set(&wgpu::QuerySetDescriptor { label: None, ty: wgpu::QueryType::Timestamp, count: N * 2 }); + let resolve = gpu.device.create_buffer(&wgpu::BufferDescriptor { label: None, size: u64::from(N) * 16, + usage: wgpu::BufferUsages::QUERY_RESOLVE | wgpu::BufferUsages::COPY_SRC, mapped_at_creation: false }); + let read = gpu.device.create_buffer(&wgpu::BufferDescriptor { label: None, size: u64::from(N) * 16, + usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ, mapped_at_creation: false }); + for i in 0..N { + let mut enc = gpu.device.create_command_encoder(&Default::default()); + draw(&mut enc, wgpu::RenderPassTimestampWrites { query_set: &queries, + beginning_of_pass_write_index: Some(i * 2), end_of_pass_write_index: Some(i * 2 + 1) }); + gpu.queue.submit([enc.finish()]); + gpu.device.poll(wgpu::PollType::wait_indefinitely()).unwrap(); + } + let mut enc = gpu.device.create_command_encoder(&Default::default()); + enc.resolve_query_set(&queries, 0..N * 2, &resolve, 0); + enc.copy_buffer_to_buffer(&resolve, 0, &read, 0, u64::from(N) * 16); + gpu.queue.submit([enc.finish()]); + read.slice(..).map_async(wgpu::MapMode::Read, |_| {}); + gpu.device.poll(wgpu::PollType::wait_indefinitely()).unwrap(); + let bytes = read.slice(..).get_mapped_range().unwrap(); + let mut ms: Vec<f64> = bytes.chunks_exact(16).skip(8).map(|b| { + let a = u64::from_le_bytes(b[..8].try_into().unwrap()); + let z = u64::from_le_bytes(b[8..].try_into().unwrap()); + assert!(z >= a && z != 0); + (z - a) as f64 * f64::from(gpu.queue.get_timestamp_period()) / 1e6 + }).collect(); + ms.sort_by(f64::total_cmp); + (ms[30], ms[56]) +} + +#[test] +#[ignore = "manual 400x40pt pill and oversized 400x120pt stress fixture at 2x"] +fn pill_blur_gpu_cost() { + let gpu = Gpu::headless(); + eprintln!("adapter: {:?}", gpu.adapter.get_info()); + let mut renderer = Renderer::new(&gpu.device, OFFSCREEN_FORMAT); + let target = Offscreen::new(&gpu.device, 1024, 512); + let mut atlas = crate::text::TextSystem::default().atlas; + for height in [80.0, 240.0] { + let mut baseline = 0.0; + for sigma in [0.0, 3.0, 8.0, 16.0] { + let mut all = filtered([112.0, 136.0, 800.0, height], sigma); + all[0].fill[3] = 0.5; // already-isolated crossfade, measure incremental filter cost + all[1].radii = [height * 0.5; 4]; + renderer.prepare(&gpu.device, &gpu.queue, &mut atlas, &all, (1024, 512)); + let (median, p95) = gpu_time(&gpu, |enc, writes| renderer.draw_timed(enc, &target.view, [0.0; 4], Some(writes))); + if sigma == 0.0 { baseline = median; } + eprintln!("pill height={height}px sigma={sigma}px: median={median:.6}ms p95={p95:.6}ms added={:.6}ms {:?}", median - baseline, renderer.layer_stats()); + } + } +} + +#[test] +fn reduced_gaussian_accuracy_and_resolution_boundary_continuity() { + let gpu = Gpu::headless(); + let format = wgpu::TextureFormat::Rgba8Unorm; + let mut renderer = Renderer::new(&gpu.device, format); + let target = Offscreen::with_format(&gpu.device, 128, 96, format); + let mut atlas = crate::text::TextSystem::default().atlas; + let mut previous: Option<Vec<u8>> = None; + for sigma in [2.999, 3.001, 4.0, 8.0, 16.0, 64.0] { + renderer.prepare(&gpu.device, &gpu.queue, &mut atlas, &filtered([24.0, 24.0, 80.0, 48.0], sigma), (128, 96)); + let out = pixels(&gpu, &renderer, &target); + let mut worst = 0; + for y in 0..96 { for x in 0..128 { + let c = coverage(x, 24, 104, sigma) * coverage(y, 24, 72, sigma); + worst = worst.max(out[((y * 128 + x) * 4 + 3) as usize].abs_diff((c * 255.0).round() as u8)); + } } + eprintln!("sigma={sigma} max alpha error versus full Gaussian={worst}/255"); + assert!(worst <= 3, "sigma={sigma} error={worst}"); + if sigma == 3.001 { + let before = previous.as_ref().unwrap(); + assert!(out.iter().zip(before).all(|(a,b)| a.abs_diff(*b) <= 1), "resolution boundary must be continuous"); + } + previous = Some(out); + } +} + +#[test] +#[ignore = "manual legacy/4pt/equivalent/capped presence-blur comparison and list GPU cost"] +fn blur_replace_cost_and_appearance() { + struct State { rows: usize, alpha: f32, sigma: f32, scale: Live<f32> } + fn view(s: &State, _: &mut Cx<State>) -> El { + el().fill(Color { r: 0.012, g: 0.012, b: 0.016, a: 1.0 }).children((0..s.rows).map(|i| { + el().size(300.0, 36.0).absolute(12.0, 12.0 + i as f32 * 48.0) + .radius(8.0).fill(Color { r: 0.055, g: 0.07, b: 0.10, a: 1.0 }) + .opacity(s.alpha).blur(s.sigma).live_scale(&s.scale) + .child(el().size(16.0, 16.0).absolute(10.0, 10.0).radius(8.0) + .fill(Color { r: 0.08, g: 0.45, b: 0.8, a: 1.0 })) + .child(crate::text("Replace this row").absolute(36.0, 8.0).color(Color::WHITE)) + })) + } + let gpu = Gpu::headless(); + eprintln!("adapter: {:?}", gpu.adapter.get_info()); + let modes = [("legacy-radius4", 4.0), ("sigma4", 4.0), ("equivalent", 4.0 / 3.0f32.sqrt()), + ("capped", rune_motion::Transition::blur_replace().insertion.blur)]; + let mut sheet = vec![0u8; 648 * 120 * 4 * modes.len()]; + for rows in [1, 12] { + let size = (648, (rows as u32 * 48 + 12) * 2); + let target = Offscreen::new(&gpu.device, size.0, size.1); + for alpha in [0.25, 0.5, 0.75] { + let mut renderers = Vec::new(); + for (mode, (_, peak)) in modes.into_iter().enumerate() { + let mut renderer = Renderer::new(&gpu.device, OFFSCREEN_FORMAT); + let mut rt = Runtime::new(State { rows, alpha, sigma: peak * (1.0 - alpha), + scale: Live::new(0.96 + 0.04 * alpha) }, view, + (size.0 as f32 / 2.0, size.1 as f32 / 2.0), Env { scale: 2.0, system_dark: true }); + rt.frame(0.0); + if mode == 0 { + // Reconstruct pre-b3 emission: opacity scopes already existed; radius was + // a linear SDF ramp on rects, half-radius added to shadows, no glyph blur. + let mut depth = 0; + for i in &mut rt.instances { + match i.params[1] { + KIND_LAYER => { depth += 1; i.params[2] = 0.0; } + KIND_LAYER_END => depth -= 1, + KIND_RECT if depth > 0 => i.params[2] = 4.0 * (1.0 - alpha) * 2.0, + KIND_SHADOW if depth > 0 => i.params[2] += 4.0 * (1.0 - alpha), + _ => {}, + } + } + } + renderer.prepare(&gpu.device, &gpu.queue, &mut rt.text.atlas, &rt.instances, size); + if rows == 1 && alpha == 0.5 { + let out = pixels(&gpu, &renderer, &target); + let start = mode * out.len(); + sheet[start..start + out.len()].copy_from_slice(&out); + } + renderers.push(renderer); + } + let samples = interleaved_gpu_times(&gpu, &renderers, &target); + for (mode, (name, _)) in modes.into_iter().enumerate() { + let mut times = samples[mode].clone(); + let mut deltas: Vec<_> = times.iter().zip(&samples[0]).map(|(a,b)| a-b).collect(); + times.sort_by(f64::total_cmp); deltas.sort_by(f64::total_cmp); + eprintln!("blur_replace rows={rows} alpha={alpha} {name}: median={:.6}ms p95={:.6}ms paired-added={:.6}ms per-row={:.6}ms {:?}", + times[30], times[56], deltas[30], deltas[30] / rows as f64, renderers[mode].layer_stats()); + } + } + } + if let Some(path) = std::env::var_os("RUNE_TRANSITION_PROOF") { + write_png(&std::path::PathBuf::from(path), 648, 480, &sheet).unwrap(); + } +} + +// Rotate order every sample to avoid attributing a changing shared-worker load to a variant. +fn interleaved_gpu_times(gpu: &Gpu, renderers: &[Renderer], target: &Offscreen) -> Vec<Vec<f64>> { + let count = 68 * renderers.len() as u32; + let queries = gpu.device.create_query_set(&wgpu::QuerySetDescriptor { label: None, ty: wgpu::QueryType::Timestamp, count: count * 2 }); + let resolve = gpu.device.create_buffer(&wgpu::BufferDescriptor { label: None, size: u64::from(count) * 16, + usage: wgpu::BufferUsages::QUERY_RESOLVE | wgpu::BufferUsages::COPY_SRC, mapped_at_creation: false }); + let read = gpu.device.create_buffer(&wgpu::BufferDescriptor { label: None, size: u64::from(count) * 16, + usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ, mapped_at_creation: false }); + for sample in 0..68 { + for j in 0..renderers.len() { + let mode = (j + sample) % renderers.len(); + let index = (sample * renderers.len() + mode) as u32; + let mut enc = gpu.device.create_command_encoder(&Default::default()); + renderers[mode].draw_timed(&mut enc, &target.view, [0.0; 4], Some(wgpu::RenderPassTimestampWrites { + query_set: &queries, beginning_of_pass_write_index: Some(index * 2), end_of_pass_write_index: Some(index * 2 + 1) })); + gpu.queue.submit([enc.finish()]); + gpu.device.poll(wgpu::PollType::wait_indefinitely()).unwrap(); + } + } + let mut enc = gpu.device.create_command_encoder(&Default::default()); + enc.resolve_query_set(&queries, 0..count * 2, &resolve, 0); + enc.copy_buffer_to_buffer(&resolve, 0, &read, 0, u64::from(count) * 16); + gpu.queue.submit([enc.finish()]); + read.slice(..).map_async(wgpu::MapMode::Read, |_| {}); + gpu.device.poll(wgpu::PollType::wait_indefinitely()).unwrap(); + let bytes = read.slice(..).get_mapped_range().unwrap(); + let mut samples = vec![Vec::new(); renderers.len()]; + for (index, b) in bytes.chunks_exact(16).enumerate().skip(8 * renderers.len()) { + let a = u64::from_le_bytes(b[..8].try_into().unwrap()); + let z = u64::from_le_bytes(b[8..].try_into().unwrap()); + assert!(z >= a && z != 0); + samples[index % renderers.len()].push((z - a) as f64 * f64::from(gpu.queue.get_timestamp_period()) / 1e6); + } + samples +} diff --git a/app/vendor/rune/crates/rune/src/render/layer_rebind_tests.rs b/app/vendor/rune/crates/rune/src/render/layer_rebind_tests.rs new file mode 100644 index 0000000..2186975 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/render/layer_rebind_tests.rs @@ -0,0 +1,97 @@ +//! Which atlas and outline texture a pool target's base bind group is made against: a target +//! waiting in the spares binds the current one only when a layer takes it back. +use super::tests::rect; +use super::*; +use crate::text::outline::{OutlineStore, WIDTH}; + +/// A group that needs a target of its own: half-opaque, so it isolates. +fn group(bounds: [f32; 4]) -> Vec<Instance> { + vec![Instance::begin_layer(bounds, NO_CLIP, LayerSpec { opacity: 0.5, ..Default::default() }), + rect(bounds, [1.0; 4]), Instance::end_layer()] +} + +/// `count` groups in a row, each with a target of its own. +fn groups(count: usize) -> Vec<Instance> { + (0..count).flat_map(|index| group([index as f32 * 8.0, 4.0, 8.0, 8.0])).collect() +} + +/// An outline store of `rows` rows holding a record, so text asks the renderer for Windfoil. +fn store(rows: usize) -> OutlineStore { + OutlineStore::from_texels(vec![[0; 4]; WIDTH as usize * rows]) +} + +/// A target is parked when its text leaves, and the outline store can grow while it waits. Taking +/// it back for text that needs the new rows must bind the taller texture before it draws. +/// +/// differs from dev: dev's `rebind_layers` walked the slots and the retained caches only, so a +/// parked target kept binding the outline texture it was made against. +#[test] +fn a_parked_target_binds_the_outline_texture_when_it_is_taken_back() { + let gpu = Gpu::headless(); + let mut renderer = Renderer::new(&gpu.device, OFFSCREEN_FORMAT); + let mut atlas = crate::text::TextSystem::default().atlas; + let text = group([8.0, 8.0, 32.0, 16.0]); + // Text has drawn from outlines: Windfoil and its minimum-height outline texture exist. + atlas.outlines = store(1); + renderer.prepare(&gpu.device, &gpu.queue, &mut atlas, &text, (64, 64)); + let short = renderer.uber.outlines().expect("text asked for Windfoil").height(); + assert_eq!(short, crate::render::outlines::MIN_ROWS, "the store starts at its minimum"); + assert_eq!(renderer.layers.targets[0].as_ref().unwrap().outline_rows, short); + + // The text leaves: its target waits in the spares. + renderer.prepare(&gpu.device, &gpu.queue, &mut atlas, &[], (64, 64)); + let parked = renderer.layers.spare[0].identity; + + // The store grows past the texture while the target waits: nothing binds it yet. + atlas.outlines = store(crate::render::outlines::MIN_ROWS as usize * 2); + renderer.prepare(&gpu.device, &gpu.queue, &mut atlas, &[], (64, 64)); + let tall = renderer.uber.outlines().expect("Windfoil stays built").height(); + assert!(tall > short, "the outline texture grew"); + assert_eq!(renderer.layers.spare[0].outline_rows, short, "a parked target waits unbound"); + + // Text needing the new rows takes that same target back, and it binds before it draws. + renderer.prepare(&gpu.device, &gpu.queue, &mut atlas, &text, (64, 64)); + let slot = renderer.layers.targets[0].as_ref().expect("the layer has its target"); + assert_eq!(slot.identity, parked, "the layer took the parked target back"); + assert_eq!(slot.outline_rows, tall, "and draws through the taller outline store"); + assert_eq!(slot.binding, renderer.layers.bindings, "bound in this frame's generation"); +} + +/// Switching the outline on a layerless frame (text's first records build Windfoil) rebinds the +/// slots and retained caches, and must leave every parked target unbound: each one binds once, when +/// a layer takes it, and one no layer takes again costs nothing. +#[test] +fn a_texture_switch_binds_no_parked_target_until_one_returns() { + let gpu = Gpu::headless(); + let mut renderer = Renderer::new_classic(&gpu.device, OFFSCREEN_FORMAT); + let mut atlas = crate::text::TextSystem::default().atlas; + // Nothing has asked for outlines: the renderer is Classic, and four half-opaque groups make + // four targets. + let quad = groups(4); + renderer.prepare(&gpu.device, &gpu.queue, &mut atlas, &quad, (64, 64)); + assert!(renderer.uber.outlines().is_none(), "no outline store yet"); + renderer.prepare(&gpu.device, &gpu.queue, &mut atlas, &[], (64, 64)); + assert_eq!(renderer.layers.spare.len(), 4, "the four targets are parked"); + let binds = renderer.layers.binds; + + // A layerless frame whose atlas grew outline records: the renderer switches to Windfoil and + // makes its atlas pages again, rebinding every live target twice. + atlas.outlines = store(1); + renderer.prepare(&gpu.device, &gpu.queue, &mut atlas, &[], (64, 64)); + assert!(renderer.uber.outlines().is_some(), "the frame switched to Windfoil"); + assert_eq!(renderer.layers.binds, binds, "a parked target makes no bind group"); + let generation = renderer.layers.bindings; + assert!(renderer.layers.spare.iter().all(|t| t.binding < generation), "every spare waits stale"); + + // One layer comes back and takes one of them: that target binds, once, and only it. + renderer.prepare(&gpu.device, &gpu.queue, &mut atlas, &quad[..3], (64, 64)); + assert_eq!(renderer.layers.binds, binds + 1, "one target returned, so one bind group"); + let slot = renderer.layers.targets[0].as_ref().expect("the layer has its target"); + assert_eq!(slot.binding, generation, "and it binds the frame's atlas and outline texture"); + assert!(renderer.layers.spare.iter().all(|t| t.binding < generation), "the others still wait"); + assert_eq!(renderer.layers.spare.len(), 3); + + // A frame that keeps that layer takes no new target and binds nothing. + renderer.prepare(&gpu.device, &gpu.queue, &mut atlas, &quad[..3], (64, 64)); + assert_eq!(renderer.layers.binds, binds + 1, "a steady frame binds nothing"); +} diff --git a/app/vendor/rune/crates/rune/src/render/layer_show_tests.rs b/app/vendor/rune/crates/rune/src/render/layer_show_tests.rs new file mode 100644 index 0000000..214e29a --- /dev/null +++ b/app/vendor/rune/crates/rune/src/render/layer_show_tests.rs @@ -0,0 +1,79 @@ +//! How a layer draws (`Disposition`) when the frame finds out more about its parent than the +//! planning walk knew at the layer's start. +use super::*; +use super::tests::{near, pixels, rgba}; + +fn rect(bounds: [f32; 4]) -> Instance { + Instance { rect: bounds, fill: [1.0; 4], clip: NO_CLIP, params: [0.0, KIND_RECT, 0.0, 1.0], ..Instance::zeroed() } +} + +/// A cached scope (`El::cache`, node 7) holding a half-faded group of two overlapping rects. +fn cached_card(bounds: [f32; 4]) -> Vec<Instance> { + let mut cache = Instance::begin_layer(bounds, NO_CLIP, LayerSpec::default()); + cache.params[3] = 1.0; + cache.radii = pack_u64_f32(7); + cache.uv = pack_u64_f32(1); + let inner = [bounds[0] + 4.0, bounds[1] + 2.0, bounds[2] - 8.0, bounds[3] - 4.0]; + vec![cache, Instance::begin_layer(inner, NO_CLIP, LayerSpec { opacity: 0.5, ..Default::default() }), + rect(inner), rect([inner[0] + 4.0, inner[1], inner[2] - 8.0, inner[3]]), Instance::end_layer(), Instance::end_layer()] +} + +/// A cache hit composites from a texture the miss drew upright, so it must carry the same turn the +/// miss did: an unturned hit snaps the scope back to where its bounds sit. +#[test] +fn a_cache_hit_composites_with_its_layer_turn() { + let gpu = Gpu::headless(); + let mut renderer = Renderer::new(&gpu.device, OFFSCREEN_FORMAT); + let target = Offscreen::new(&gpu.device, 64, 64); + let mut atlas = crate::text::TextSystem::default().atlas; + // A wide scope holding ink in its left third, turned about its centre: the turn moves it. + let bounds = [16.0, 22.0, 32.0, 12.0]; + let turned = |angle: Option<f32>| { + let mut cache = Instance::begin_layer(bounds, NO_CLIP, LayerSpec::default()); + if let Some(angle) = angle { cache = cache.turned(angle, [32.0, 28.0]); } + cache.params[3] = 1.0; + cache.radii = pack_u64_f32(31); + cache.uv = pack_u64_f32(1); + vec![cache, rect([bounds[0] + 2.0, bounds[1] + 2.0, 8.0, 6.0]), Instance::end_layer()] + }; + // The miss draws the turned scope into its target and composites it turned. + let instances = turned(Some(0.6)); + renderer.prepare(&gpu.device, &gpu.queue, &mut atlas, &instances, (64, 64)); + assert!(matches!(renderer.layers.planner.dispositions[0], Disposition::Render { .. }), "the first frame draws it"); + let miss = pixels(&gpu, &renderer, &target); + // The hit composites the texture it kept, and must land the same pixels. + renderer.prepare(&gpu.device, &gpu.queue, &mut atlas, &instances, (64, 64)); + assert!(matches!(renderer.layers.planner.dispositions[0], Disposition::Cached { .. }), "the second frame hits"); + let hit = pixels(&gpu, &renderer, &target); + let differing = hit.iter().zip(&miss).filter(|(hit, miss)| hit != miss).count(); + assert_eq!(differing, 0, "a hit composites the turned quad the miss drew"); + // And the turn is what moves them: the same scope upright draws elsewhere. + let upright = turned(None); + for _ in 0..2 { renderer.prepare(&gpu.device, &gpu.queue, &mut atlas, &upright, (64, 64)); } + assert_ne!(pixels(&gpu, &renderer, &target), hit, "the turn is in the composite, not only the render"); +} + +/// The planning walk takes a kept cache to be a hit and covers what's inside it; when the cache +/// then doesn't fit the budget, the scope draws as a plain group, and its faded child with it. +#[test] +fn a_layer_inside_a_cache_that_misses_its_budget_still_draws() { + let gpu = Gpu::headless(); + let mut renderer = Renderer::new(&gpu.device, OFFSCREEN_FORMAT); + let target = Offscreen::new(&gpu.device, 32, 16); + let mut atlas = crate::text::TextSystem::default().atlas; + let instances = cached_card([4.0, 2.0, 24.0, 12.0]); + let at = (8 * 32 + 16) * 4; + renderer.prepare(&gpu.device, &gpu.queue, &mut atlas, &instances, (32, 16)); + near(&pixels(&gpu, &renderer, &target)[at..at + 4], rgba([0.5; 4])); + assert!(matches!(renderer.layers.planner.dispositions[1], Disposition::Render { .. })); + + renderer.prepare(&gpu.device, &gpu.queue, &mut atlas, &instances, (32, 16)); + assert!(matches!(renderer.layers.planner.dispositions[0], Disposition::Cached { .. })); + assert_eq!(renderer.layers.planner.dispositions[1], Disposition::Skip); + + // The kept texture no longer fits, but stays in the pool for this frame's walk to find. + renderer.layers.cache_budget = 1; + renderer.prepare(&gpu.device, &gpu.queue, &mut atlas, &instances, (32, 16)); + near(&pixels(&gpu, &renderer, &target)[at..at + 4], rgba([0.5; 4])); + assert!(matches!(renderer.layers.planner.dispositions[1], Disposition::Render { .. })); +} diff --git a/app/vendor/rune/crates/rune/src/render/layers.rs b/app/vendor/rune/crates/rune/src/render/layers.rs new file mode 100644 index 0000000..858cd87 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/render/layers.rs @@ -0,0 +1,878 @@ +//! Bounded painter scopes. The ordinary path retains its instance buffer, batches and pass; +//! only scopes requiring isolation acquire a target. Scope records are also compositor fences. +use super::*; +#[cfg(test)] +use bytemuck::Zeroable; +use std::ops::Range; + +mod plan; +pub(super) use plan::is_scissor_clip; +use plan::{Describe, Disposition, Held, Kept, Layer, Move, Planned, Planner, Pools}; + +// Linear premultiplied intermediates preserve HDR colours and avoid accumulating 8-bit +// quantization through nested layers. The destination format is applied only at composition. +pub(super) const FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Rgba16Float; +/// Default offscreen texture budget for [`El::cache`](crate::El::cache) subtrees (64 MiB). +pub const DEFAULT_CACHE_BUDGET: u64 = 64 * 1024 * 1024; +/// What spare layer targets may hold (Layers::spare): a full-window layer at 2880x1800 or two menus' worth. +const SPARE_BYTES: u64 = 32 * 1024 * 1024; +/// Maximum width or height of a cached subtree's offscreen texture in device pixels. +const MAX_CACHE_DIM: u32 = 4096; + +#[cfg(test)] +#[path = "layers/plan_frame_tests.rs"] +mod plan_frame_tests; +#[cfg(test)] +#[path = "../runtime/layer_tests.rs"] +mod tests; +#[cfg(test)] +#[path = "../runtime/layer_cache_tests.rs"] +mod cache_tests; +#[cfg(test)] +#[path = "layer_filter_tests.rs"] +mod filter_tests; +#[cfg(test)] +#[path = "../runtime/rounded_clip_tests.rs"] +mod rounded_clip_tests; +#[cfg(test)] +#[path = "continuous_corner_tests.rs"] +mod continuous_corner_tests; +#[cfg(test)] +#[path = "layer_show_tests.rs"] +mod show_tests; +#[cfg(test)] +#[path = "layer_rebind_tests.rs"] +mod rebind_tests; + +pub(super) struct Layers { + plan: Vec<Layer>, + /// What each layer does this frame, and the moves the target pools take to get there. + planner: Planner, + pub targets: Vec<Option<Target>>, + retained: Vec<Target>, + /// Targets no layer drew into this frame (a menu closed, a layer's place in the plan moved), + /// kept for the next layer of their size: opening a menu or a popover again makes no texture. + spare: Vec<Target>, + stack: Vec<usize>, + pipelines: Vec<(wgpu::TextureFormat, wgpu::RenderPipeline)>, + pub additive: Option<(wgpu::RenderPipeline, wgpu::RenderPipeline)>, + pub blur: Option<layer_blur::Pipeline>, + viewport: (u32, u32), + image_generation: u64, + allocations: u64, + /// The atlas and outline texture generation: every target's base bind group names the + /// generation it was made against, and a parked target is bound again only when a layer takes + /// it in a later one. + bindings: u64, + cache_budget: u64, + frame_stamp: u64, + /// Test-only: the most bytes of live targets and their blur scratches a frame has held at once. + #[cfg(test)] + peak: u64, + /// Test-only: how many times a target's base bind group has been made again. + #[cfg(test)] + pub(super) binds: u64, +} + +impl Layers { + /// Whether every group of the frame lands where its instances say: drawn straight into its + /// parent's pass, or into a target composited back at its own place, neither turned nor + /// blurred, so a changed instance changes only the pixels its bounds cover + /// (`Renderer::redraws_in_place`). + #[cfg(any(target_os = "windows", target_arch = "wasm32"))] + pub(super) fn in_place(&self) -> bool { + self.plan.iter().enumerate().all(|(i, l)| match self.planner.dispositions.get(i) { + Some(Disposition::Inline | Disposition::Skip) | None => true, + Some(Disposition::Render { .. } | Disposition::Cached { .. }) => l.turn.is_none() && !l.free && l.blur == 0.0, + }) + } + + /// Kept textures get the budget left after this frame's visible caches. + fn trim_retained(&mut self, active_bytes: u64) { + let available = self.cache_budget.saturating_sub(active_bytes); + let mut bytes: u64 = self.retained.iter().map(Renderer::target_bytes).sum(); + while bytes > available { + let oldest = self.retained.iter().enumerate().min_by_key(|(_, t)| t.last_used).unwrap().0; + let evicted = self.retained.swap_remove(oldest); + bytes -= Renderer::target_bytes(&evicted); + } + } + + /// Keeps `t` for a later layer of its size, within `SPARE_BYTES`; the least recently used go. + fn park(&mut self, mut t: Target) { + t.cache = None; + self.spare.push(t); + self.trim_spare(SPARE_BYTES); + } + + /// Drops the least recently used spare targets until they hold at most `limit` bytes. + fn trim_spare(&mut self, limit: u64) { + let mut bytes: u64 = self.spare.iter().map(Renderer::target_bytes).sum(); + while bytes > limit { + let oldest = self.spare.iter().enumerate().min_by_key(|(_, t)| t.last_used).unwrap().0; + bytes -= Renderer::target_bytes(&self.spare.swap_remove(oldest)); + } + } + + /// Test-only: notes the peak of the bytes this frame holds live, targets and blur scratches + /// alike, so a test can pin it against the peak dev held. + #[cfg(test)] + fn watch_peak(&mut self) { + let bytes: u64 = self.targets.iter().flatten().chain(&self.retained).chain(&self.spare) + .map(Renderer::target_bytes).sum(); + self.peak = self.peak.max(bytes); + } + + /// Test-only: the most live target bytes the last frame held at once. + #[cfg(test)] + pub(super) fn peak_bytes(&self) -> u64 { self.peak } + + /// Makes every blurred layer write its blur uniforms again on its next prepare. + pub(super) fn forget_blur_uniforms(&mut self) { + let targets = self.targets.iter_mut().flatten().chain(&mut self.retained).chain(&mut self.spare); + for blur in targets.filter_map(|t| t.blur.as_mut()) { blur.forget_uniforms(); } + } +} + +impl Default for Layers { + fn default() -> Self { + Self { + plan: Vec::new(), + planner: Planner::default(), + targets: Vec::new(), + retained: Vec::new(), + spare: Vec::new(), + stack: Vec::new(), + pipelines: Vec::new(), + additive: None, + blur: None, + viewport: (0, 0), + image_generation: 0, + allocations: 0, + bindings: 0, + cache_budget: DEFAULT_CACHE_BUDGET, + frame_stamp: 0, + #[cfg(test)] + peak: 0, + #[cfg(test)] + binds: 0, + } + } +} + +pub(super) struct Target { + identity: u64, + composite_parent: Option<u64>, + texture: wgpu::Texture, + view: wgpu::TextureView, + projection: wgpu::Buffer, + quad: wgpu::Buffer, + composite: wgpu::BindGroup, + pub base: wgpu::BindGroup, + pub images: Vec<Option<wgpu::BindGroup>>, + pub glyphs: Vec<wgpu::BindGroup>, + image_generation: u64, + blur: Option<layer_blur::Scratch>, + /// The node and signature of the cached content, if this target is kept. + cache: Option<(u64, u64)>, + last_used: u64, + content_size: [f32; 2], + /// The `Layers::bindings` generation the base bind group was made against. + binding: u64, + /// Test-only: the outline texture's height the base bind group was made against. + #[cfg(test)] + outline_rows: u32, +} + +impl Describe for Target { + /// What the plan reads about it: its size, what it keeps and what it costs, with no handle. + fn held(&self) -> Held { + Held { + size: [self.texture.width(), self.texture.height()], + bytes: Renderer::target_bytes(self), + cache: self.cache, + last_used: self.last_used, + content: self.content_size, + } + } +} + +/// Binds `t` to the frame's atlas and outline texture, and to `generation`: its base bind group +/// here, its composite and image and glyph pages at the next `prepare_layers`. +fn rebind_target(device: &wgpu::Device, layout: &wgpu::BindGroupLayout, globals: &wgpu::Buffer, + outlines: Option<&wgpu::Texture>, atlas: &wgpu::Texture, t: &mut Target, generation: u64) { + t.base = Renderer::bind_group(device, layout, globals, outlines, atlas, atlas, Some(&t.projection)); + // No target's identity is 0, so the composite is made again. + t.composite_parent = Some(0); + t.image_generation = u64::MAX; + t.binding = generation; + #[cfg(test)] + { t.outline_rows = outlines.map_or(0, wgpu::Texture::height); } +} + +/// Resource/pass counters for diagnostics. The ordinary path creates no layer resources. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct LayerStats { + pub targets: usize, + pub bytes: u64, + pub extra_passes: usize, + pub allocations: u64, +} + +fn union(a: &mut [f32; 4], b: [f32; 4]) { + if b[2] <= b[0] || b[3] <= b[1] { return; } + a[0] = a[0].min(b[0]); a[1] = a[1].min(b[1]); + a[2] = a[2].max(b[2]); a[3] = a[3].max(b[3]); +} + +impl Renderer { + fn target_bytes(t: &Target) -> u64 { + let mut bytes = u64::from(t.texture.width()) * u64::from(t.texture.height()) + * u64::from(FORMAT.block_copy_size(None).unwrap()); + if let Some(blur) = &t.blur { + bytes += blur.bytes(); + } + bytes + } + + /// Maximum bytes of offscreen textures retained for [`El::cache`](crate::El::cache) subtrees + /// before least-recently-used entries are evicted. Defaults to 64 MiB. + pub fn set_cache_budget(&mut self, bytes: u64) { + self.layers.cache_budget = bytes; + self.layers.trim_retained(0); + } + + /// Current [`El::cache`](crate::El::cache) texture memory budget in bytes. + pub fn cache_budget(&self) -> u64 { + self.layers.cache_budget + } + + /// With `alloc-sites` (a measuring build), the heap dump's `rune-gpu` section lists what this + /// renderer's pools hold after its latest frame or rest, as `<pool> <count> <bytes>`. + #[cfg(all(feature = "alloc-sites", not(target_arch = "wasm32")))] + pub(super) fn report_pools(&self) { + static POOLS: std::sync::Mutex<String> = std::sync::Mutex::new(String::new()); + static ONCE: std::sync::Once = std::sync::Once::new(); + fn texture_bytes(t: &wgpu::Texture) -> u64 { + let block = u64::from(t.format().block_copy_size(None).unwrap_or(4)); + (0..t.mip_level_count()).map(|m| u64::from((t.width() >> m).max(1)) * u64::from((t.height() >> m).max(1)) * block).sum() + } + let pool = |name: &str, ts: &mut dyn Iterator<Item = u64>| { + let (n, bytes) = ts.fold((0, 0), |(n, b), x| (n + 1, b + x)); + format!("{name} {n} {bytes}\n") + }; + let l = &self.layers; + let out = [ + pool("layer-live", &mut l.targets.iter().flatten().filter(|t| t.cache.is_none()).map(Self::target_bytes)), + pool("layer-cache-live", &mut l.targets.iter().flatten().filter(|t| t.cache.is_some()).map(Self::target_bytes)), + pool("layer-retained", &mut l.retained.iter().map(Self::target_bytes)), + pool("layer-spare", &mut l.spare.iter().map(Self::target_bytes)), + pool("backdrops", &mut self.backdrops.iter().map(|b| texture_bytes(&b.texture))), + pool("glyph-atlas", &mut std::iter::once(&self.atlas).chain(self.atlas_pages.iter().map(|p| &p.0)).map(texture_bytes)), + pool("image-pages", &mut self.images.iter().flatten().map(|p| texture_bytes(&p.0))), + ].concat(); + *POOLS.lock().unwrap_or_else(|e| e.into_inner()) = out; + ONCE.call_once(|| procwatch::alloc::sites::contribute("rune-gpu", || POOLS.lock().unwrap_or_else(|e| e.into_inner()).clone())); + } + + /// What a window at rest gives back (`window::rest`): every spare target (the first menu, + /// hover or session after it makes its own again, within a frame's run-to-run spread on an + /// Iris Xe), cache textures no layer drew last frame, and the backdrop copies and blur pyramid + /// when the last frame read none. With `all`, also the scratch targets of this screen's + /// layers and its backdrop copies, which its next frame makes again (a few ms on an integrated GPU). It keeps the + /// textures of caches on screen, which the last frame's instances name instead of their + /// contents, and takes the ones it drops out of `resident`, so their next frame paints them. + /// What no submission still uses is freed here; the rest when the device next polls. + pub(crate) fn give_back(&mut self, all: bool, resident: &mut std::collections::HashMap<u64, u64>) { + for t in self.layers.retained.drain(..) { + if let Some((node, _)) = t.cache { resident.remove(&node); } + } + self.layers.trim_spare(0); + if all { + for slot in &mut self.layers.targets { + if slot.as_ref().is_some_and(|t| t.cache.is_none()) { *slot = None; } + } + } + // The backdrop copies (one full-window texture per target format) and the blur pyramid: + // out of sight, or when the last frame read none (a session's jump button had blurred + // what was under it, and Home doesn't). + if all || !self.backdrop_used { + self.backdrops.clear(); + if let Some(blur) = &mut self.backdrop_blur { blur.give_back(); } + } + #[cfg(all(feature = "alloc-sites", not(target_arch = "wasm32")))] + self.report_pools(); + } + + /// Frees the staging chunks kept for reuse (`window::rest`, out of sight only: the next + /// frame's uploads would make new ones). + pub(crate) fn trim_uploads(&self) { + self.uploads.trim(); + } + + pub(super) fn sync_resident_caches(&self, out: &mut std::collections::HashMap<u64, u64>) { + if !out.is_empty() { + out.clear(); + } + for t in self.layers.targets.iter().flatten().chain(self.layers.retained.iter()) { + if let Some((node, sig)) = t.cache { + out.insert(node, sig); + } + } + } + + pub fn layer_stats(&self) -> LayerStats { + let mut stats = LayerStats { allocations: self.layers.allocations, ..Default::default() }; + for (index, t) in self.layers.targets.iter().enumerate() { + let Some(t) = t else { continue }; + stats.targets += 1; + stats.bytes += Self::target_bytes(t); + if matches!(self.layers.planner.dispositions.get(index), Some(Disposition::Render { .. })) { + stats.extra_passes += 1 + t.blur.as_ref().map_or(0, layer_blur::Scratch::passes); + } + } + for t in &self.layers.retained { + stats.targets += 1; + stats.bytes += Self::target_bytes(t); + } + stats + } + + pub(super) fn prepare_layers(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, instances: &[Instance], viewport: (u32, u32)) { + let staging = self.uploads.staging(device, queue); + self.layers.viewport = viewport; + #[cfg(test)] + { self.layers.peak = 0; } + let before = self.layers.plan.len(); + for slot in &mut self.layers.targets { + if slot.as_ref().is_some_and(|t| t.cache.is_some()) { + self.layers.retained.push(slot.take().unwrap()); + } + } + self.layers.plan.clear(); + self.layers.stack.clear(); + for (index, i) in instances.iter().enumerate() { + if i.kind() == Some(Kind::Layer) { + let parent = self.layers.stack.last().copied(); + let parent_cached_hit = parent.is_some_and(|p| { + self.layers.plan[p].cache.is_some_and(|key| { + self.layers.retained.iter().any(|t| t.cache == Some(key)) + }) + }); + let opacity = i.fill[3].clamp(0.0, 1.0); + let planned = match parent.map(|p| self.layers.plan[p].planned) { + _ if opacity == 0.0 => Planned::Hidden, + Some(Planned::Hidden) => Planned::Hidden, + Some(Planned::Covered) => Planned::Covered, + _ if parent_cached_hit => Planned::Covered, + _ => Planned::Inline, + }; + // Bound storage by the ancestor's required input, including filter support. + // Keep the actual clip separate so rounded corners never move. + let limit = parent.map_or(NO_CLIP, |p| { + let p = &self.layers.plan[p]; + let grow = (3.0 * p.blur).ceil(); + [p.clip[0].max(p.limit[0]) - grow, p.clip[1].max(p.limit[1]) - grow, + p.clip[2].min(p.limit[2]) + grow, p.clip[3].min(p.limit[3]) + grow] + }); + let blur = layer_blur::sigma(i.params[2]); + let cache = (i.params[3] == 1.0).then(|| (unpack_u64_f32(i.radii), unpack_u64_f32(i.uv))); + let turn = (i.border[1] != 0.0).then_some((i.border[1], [i.border[2], i.border[3]])); + let parent_free = parent.is_some_and(|p| self.layers.plan[p].free); + let free = turn.is_some() || parent_free; + let frame = if free { + let outer = match parent { + Some(p) if parent_free => self.layers.plan[p].frame, + _ => { + let support = parent.map_or(0.0, |p| self.layers.plan[p].support); + [-support, -support, viewport.0 as f32 + support, viewport.1 as f32 + support] + } + }; + let shown = [outer[0].max(i.clip[0]), outer[1].max(i.clip[1]), outer[2].min(i.clip[2]), outer[3].min(i.clip[3])]; + match turn { + Some((angle, pivot)) if shown[2] > shown[0] && shown[3] > shown[1] => turned_bounds(shown, -angle, pivot), + _ => shown, + } + } else { [0.0; 4] }; + let limit = if parent_free { NO_CLIP } else { limit }; + self.layers.stack.push(self.layers.plan.len()); + self.layers.plan.push(Layer { + begin: index as u32, end: 0, parent, + edges: [i.rect[0], i.rect[1], i.rect[0] + i.rect[2], i.rect[1] + i.rect[3]], + vis: [0.0; 4], + clip: i.clip, + limit, + fade: i.fade, + opacity, + blend: if i.params[0] == 1.0 { Blend::PlusLighter } else { Blend::SourceOver }, + blur, + support: parent.map_or(0.0, |p| self.layers.plan[p].support) + (3.0 * blur).ceil(), + cache, + planned, + turn, + free, + frame, + // A cached scope's `radii` name its node instead. + hole: if cache.is_some() { [0.0; 4] } else { i.radii }, + }); + } else if i.kind() == Some(Kind::LayerEnd) { + let at = self.layers.stack.pop().expect("unbalanced layer end"); + let l = &mut self.layers.plan[at]; + l.end = index as u32; + let grow = (3.0 * l.blur).ceil(); + // Retain off-viewport sources that can contribute through this or an ancestor's + // filter. Clipping to the destination viewport before filtering loses those taps. + let e = l.edges; + let vis = if l.free { + [(e[0] - grow).max(l.frame[0] - grow).floor(), (e[1] - grow).max(l.frame[1] - grow).floor(), + (e[2] + grow).min(l.frame[2] + grow).ceil(), (e[3] + grow).min(l.frame[3] + grow).ceil()] + } else { + [(e[0] - grow).max(l.clip[0].max(l.limit[0]) - grow).max(-l.support).floor(), + (e[1] - grow).max(l.clip[1].max(l.limit[1]) - grow).max(-l.support).floor(), + (e[2] + grow).min(l.clip[2].min(l.limit[2]) + grow).min(viewport.0 as f32 + l.support).ceil(), + (e[3] + grow).min(l.clip[3].min(l.limit[3]) + grow).min(viewport.1 as f32 + l.support).ceil()] + }; + l.vis = vis; + if l.cache.is_some() { + if vis[2] <= vis[0] || vis[3] <= vis[1] { + l.planned = Planned::Hidden; + } + l.edges = [e[0].floor(), e[1].floor(), e[2].ceil(), e[3].ceil()]; + } else { + l.edges = vis; + } + let edges = match l.turn { + Some((angle, pivot)) if l.edges[2] > l.edges[0] && l.edges[3] > l.edges[1] => turned_bounds(l.edges, angle, pivot), + _ => l.edges, + }; + if let Some(parent) = l.parent.filter(|&p| self.layers.plan[p].cache.is_none()) { + union(&mut self.layers.plan[parent].edges, edges); + } + } else if let Some(&at) = self.layers.stack.last() { + if self.layers.plan[at].cache.is_some() { continue; } + let (x0, y0, x1, y1) = i.layer_bounds_non_scope(); + union(&mut self.layers.plan[at].edges, [x0, y0, x1, y1]); + } + } + assert!(self.layers.stack.is_empty(), "unclosed layer scope"); + let isolate = self.check_layer_features(device); + while self.layers.targets.len() > self.layers.plan.len() { + if let Some(t) = self.layers.targets.pop().flatten() { self.layers.park(t); } + } + self.layers.targets.resize_with(self.layers.plan.len(), || None); + if !self.layers.plan.is_empty() || !self.layers.retained.is_empty() { + self.layers.frame_stamp += 1; + } + let max_dim = self.max_texture_dim.min(MAX_CACHE_DIM); + if self.layers.plan.is_empty() { + // No layers to plan: what closed at the last frame's end is all this frame keeps or + // drops, exactly as dev trimmed the pool. Nothing here reads a target's size. + self.layers.trim_retained(0); + } else { + // One disposition per layer, and every change to the target pools it needs, decided on + // the pools as they are: `commit` then carries the moves out and `paint_layers` draws them. + let layers = &mut self.layers; + let pools = Pools { slots: &layers.targets, retained: &layers.retained, spare: &layers.spare }; + layers.planner.decide(&layers.plan, &pools, layers.cache_budget, isolate, max_dim); + self.commit(device); + self.paint_layers(device, &staging); + } + // A frame whose layers fell gives back what a burst grew the plan's scratch to; a frame + // that keeps its layers, or stays empty, leaves it alone. + if self.layers.plan.len() < before { + let layers = &mut self.layers; + layers.planner.settle(layers.plan.len(), layers.retained.len(), layers.spare.len()); + } + // Rebind child composites to their nearest materialized parent (opaque scopes flatten). + for index in 0..self.layers.plan.len() { + if self.layers.targets[index].is_none() { continue; } + let parent = self.layer_target(self.layers.plan[index].parent); + let t = self.layers.targets[index].as_ref().unwrap(); + let parent_identity = parent.map(|p| self.layers.targets[p].as_ref().unwrap().identity); + if t.composite_parent == parent_identity { continue; } + let composite = Self::bind_group(device, &self.bind_layout, &self.globals, self.uber.outlines(), &self.atlas, &t.texture, + parent.map(|p| &self.layers.targets[p].as_ref().unwrap().projection)); + let t = self.layers.targets[index].as_mut().unwrap(); + t.composite = composite; + t.composite_parent = parent_identity; + } + if self.layers.targets.iter().any(Option::is_some) { + self.add_format(device, FORMAT); + self.add_layer_format(device, self.format); + for index in 0..self.extra.len() { self.add_layer_format(device, self.extra[index].0); } + } + if self.layers.plan.iter().any(|l| l.blend == Blend::PlusLighter) && let Some(s) = &mut self.surfaces { + s.add_plus_lighter(device, FORMAT); + } + debug_assert!(self.layers.planner.dispositions.iter().zip(&self.layers.targets) + .all(|(d, t)| t.is_some() == matches!(d, Disposition::Render { .. } | Disposition::Cached { .. })), + "only Render and Cached layers hold a target"); + self.refresh_layer_bindings(device); + if before > 0 || !self.layers.plan.is_empty() { self.position_layer_surfaces(queue); } + } + + /// Carries out the moves the plan decided, in its order: the one place a target changes pool. + fn commit(&mut self, device: &wgpu::Device) { + for i in 0..self.layers.planner.moves.len() { + match self.layers.planner.moves[i] { + Move::Park(slot) => { + // The plan's `Drop`s trim the spares; nothing trims here. + if let Some(mut t) = self.layers.targets[slot].take() { t.cache = None; self.layers.spare.push(t); } + } + Move::Set { slot, from } => { + let mut t = match from { + Kept::Retained(at) => self.layers.retained.swap_remove(at), + Kept::Spare(at) => self.layers.spare.swap_remove(at), + }; + // A target parked before the atlas or outline texture changed binds it now, + // once; a spare no layer takes again never makes a bind group at all. + self.rebind_if_stale(device, &mut t); + self.layers.targets[slot] = Some(t); + } + Move::Create { slot, size } => self.layers.targets[slot] = Some(self.make_target(device, size)), + Move::Unblur(slot) => { + if let Some(t) = self.layers.targets[slot].as_mut() { t.blur = None; } + } + Move::Drop(Kept::Retained(at)) => { self.layers.retained.swap_remove(at); } + Move::Drop(Kept::Spare(at)) => { self.layers.spare.swap_remove(at); } + } + #[cfg(test)] + self.layers.watch_peak(); + } + } + + /// A target of `size`, with the buffers and bind groups a layer draws into it through. + fn make_target(&mut self, device: &wgpu::Device, size: [u32; 2]) -> Target { + let (width, height) = (size[0], size[1]); + let texture = device.create_texture(&wgpu::TextureDescriptor { + label: Some("isolated group"), size: wgpu::Extent3d { width, height, depth_or_array_layers: 1 }, + mip_level_count: 1, sample_count: 1, dimension: wgpu::TextureDimension::D2, + format: FORMAT, usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_SRC, + view_formats: &[], + }); + let view = texture.create_view(&Default::default()); + let projection = device.create_buffer(&wgpu::BufferDescriptor { + label: Some("layer projection"), size: 16, usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + }); + let base = Self::bind_group(device, &self.bind_layout, &self.globals, self.uber.outlines(), &self.atlas, &self.atlas, Some(&projection)); + let composite = Self::bind_group(device, &self.bind_layout, &self.globals, self.uber.outlines(), &self.atlas, &texture, None); + self.layers.allocations += 1; + Target { texture, view, projection, + identity: self.layers.allocations, composite_parent: None, + quad: Self::instance_buffer(device, 1), base, composite, images: Vec::new(), glyphs: Vec::new(), image_generation: u64::MAX, blur: None, + cache: None, last_used: 0, content_size: [0.0; 2], binding: self.layers.bindings, + #[cfg(test)] + outline_rows: self.uber.outlines().map_or(0, wgpu::Texture::height) } + } + + /// Draws what each layer's disposition says: its target's descriptor, its blur, and the quad + /// that composites it. + fn paint_layers(&mut self, device: &wgpu::Device, staging: &rune_staging::Staging) { + let stamp = self.layers.frame_stamp; + for index in 0..self.layers.plan.len() { + let l = self.layers.plan[index]; + match self.layers.planner.dispositions[index] { + Disposition::Skip | Disposition::Inline => {} + Disposition::Cached { rect, cache } => { + let t = self.layers.targets[index].as_mut().expect("a claimed cache has its target"); + t.cache = cache; + if cache.is_some() { t.last_used = stamp; } + let mut quad = Instance::begin_layer(rect, l.clip, LayerSpec { + opacity: l.opacity, blend: l.blend, ..Default::default() }); + // A hit composites the same turned quad a miss drew: the turn belongs to the + // scope, not to the pass that filled its texture. + if let Some((angle, pivot)) = l.turn { quad = quad.turned(angle, pivot); } + quad.fade = l.fade; + if (t.content_size[0] - rect[2]).abs() > 0.5 || (t.content_size[1] - rect[3]).abs() > 0.5 { + quad.uv = [0.0, 0.0, t.content_size[0], t.content_size[1]]; + } + staging.write_buffer(&t.quad, 0, bytemuck::bytes_of(&quad)); + } + Disposition::Render { rect, cache } => { + let t = self.layers.targets[index].as_mut().expect("a rendering layer has its target"); + t.cache = cache; + t.last_used = stamp; + t.content_size = [rect[2], rect[3]]; + // A scratch the layer no longer wants was dropped by `Move::Unblur`, before any + // later layer's texture existed. + if l.blur > 0.0 { + let pipeline = self.layers.blur.as_ref().expect("prepared layer blur"); + if t.blur.is_none() { + t.blur = Some(pipeline.scratch(device, &t.texture)); + self.layers.allocations += 1; + } + if t.blur.as_mut().unwrap().prepare(device, pipeline, staging, + [rect[2], rect[3]], l.blur, l.blend == Blend::PlusLighter) { + self.layers.allocations += 1; + } + } + staging.write_buffer(&t.projection, 0, bytemuck::cast_slice(&rect)); + let mut quad = Instance::begin_layer(rect, l.clip, LayerSpec { + opacity: l.opacity, blend: l.blend, ..Default::default() }); + if let Some((angle, pivot)) = l.turn { quad = quad.turned(angle, pivot); } + quad.fade = l.fade; + quad.radii = l.hole; + staging.write_buffer(&t.quad, 0, bytemuck::bytes_of(&quad)); + } + } + #[cfg(test)] + self.layers.watch_peak(); + } + } + + /// Builds and checks the pipelines this frame's layers need (`breaker`), and plans the frame + /// without the ones the device refused or hasn't taken yet: a dissolve as source-over, a blur + /// unblurred. Whether layers can isolate; when they can't, each group draws in its parent. + fn check_layer_features(&mut self, device: &wgpu::Device) -> bool { + // A layer a cache covers counts: the cache can still miss and draw it this frame. + let shown = || self.layers.plan.iter().enumerate().filter(|(_, l)| l.planned != Planned::Hidden); + let isolation = shown().any(|(index, _)| self.isolates(index)); + let plus_lighter = shown().any(|(_, l)| l.blend == Blend::PlusLighter); + let blur = shown().any(|(_, l)| l.blur > 0.0); + if !isolation && !plus_lighter && !blur && !self.breakers.checking() { return false; } + self.check_features(device, |feature| match feature { + breaker::Feature::Isolation => isolation, + breaker::Feature::PlusLighter => plus_lighter, + breaker::Feature::LayerBlur => blur, + }); + let working = |feature| self.breakers.health(feature).working(); + let (isolate, add, blur) = (working(breaker::Feature::Isolation), working(breaker::Feature::PlusLighter), working(breaker::Feature::LayerBlur)); + for l in &mut self.layers.plan { + if !add { l.blend = Blend::SourceOver; } + if !blur { l.blur = 0.0; } + } + isolate + } + + /// Whether layer `index` needs a target of its own to draw as asked, while planning. + fn isolates(&self, index: usize) -> bool { + let l = &self.layers.plan[index]; + let additive_parent = l.parent.is_some_and(|p| self.layers.plan[p].blend == Blend::PlusLighter); + l.cache.is_some() || l.opacity != 1.0 || l.blend != Blend::SourceOver || additive_parent + || l.blur != 0.0 || l.fade[3] != 0 || l.clip != NO_CLIP || l.turn.is_some() || l.hole[3] != 0.0 + } + + /// Drops the composite pipelines (`breaker`), and with `targets` every target, which no + /// frame will draw into again. + pub(super) fn drop_layer_pipelines(&mut self, targets: bool) { + self.layers.pipelines.clear(); + if targets { + self.layers.targets.clear(); + self.layers.retained.clear(); + self.layers.spare.clear(); + } + } + + /// Drops the layer blur's pipelines and every target's blur scratch (`breaker`). + pub(super) fn drop_layer_blur(&mut self) { + self.layers.blur = None; + for t in self.layers.targets.iter_mut().flatten().chain(&mut self.layers.retained).chain(&mut self.layers.spare) { t.blur = None; } + } + + pub(super) fn add_layer_format(&mut self, device: &wgpu::Device, format: wgpu::TextureFormat) { + if !self.layers.pipelines.iter().any(|(f, _)| *f == format) { + self.layers.pipelines.push((format, Self::pipeline(device, &self.layout, &self.shader, format, "vs", Blend::SourceOver))); + } + } + + fn layer_target(&self, mut layer: Option<usize>) -> Option<usize> { + while let Some(index) = layer { + if self.layers.targets[index].is_some() { return Some(index); } + layer = self.layers.plan[index].parent; + } + None + } + + pub(super) fn layer_blend(&self, target: Option<usize>) -> Blend { + target.map_or(Blend::SourceOver, |p| self.layers.plan[p].blend) + } + + pub(super) fn images_changed(&mut self) { self.layers.image_generation += 1; } + + /// Makes every live target's bind groups again (a new atlas or outline texture), and starts a + /// generation: the slots and retained caches bind it here, a parked target binds it when a + /// layer takes it back, and a spare no layer takes again makes nothing. + pub(super) fn rebind_layers(&mut self, device: &wgpu::Device) { + self.layers.bindings += 1; + let generation = self.layers.bindings; + let (layout, globals, outlines, atlas) = (&self.bind_layout, &self.globals, self.uber.outlines(), &self.atlas); + for t in self.layers.targets.iter_mut().flatten().chain(&mut self.layers.retained) { + rebind_target(device, layout, globals, outlines, atlas, t, generation); + #[cfg(test)] + { self.layers.binds += 1; } + } + } + + /// Binds `t` to the atlas and outline texture this frame draws with, if it was made or parked + /// against an earlier generation. + fn rebind_if_stale(&mut self, device: &wgpu::Device, t: &mut Target) { + let generation = self.layers.bindings; + if t.binding == generation { return; } + rebind_target(device, &self.bind_layout, &self.globals, self.uber.outlines(), &self.atlas, t, generation); + #[cfg(test)] + { self.layers.binds += 1; } + } + + pub(super) fn refresh_layer_bindings(&mut self, device: &wgpu::Device) { + for t in self.layers.targets.iter_mut().flatten() { + if t.image_generation == self.layers.image_generation { continue; } + t.images.clear(); + t.images.extend(self.images.iter().map(|page| page.as_ref().map(|(texture, _)| + Self::bind_group(device, &self.bind_layout, &self.globals, self.uber.outlines(), &self.atlas, texture, Some(&t.projection))))); + t.glyphs.clear(); + t.glyphs.extend(self.atlas_pages.iter().map(|(texture, _)| + Self::bind_group(device, &self.bind_layout, &self.globals, self.uber.outlines(), texture, texture, Some(&t.projection)))); + t.image_generation = self.layers.image_generation; + } + } + + pub(super) fn position_layer_surfaces(&self, queue: &wgpu::Queue) { + let Some(s) = &self.surfaces else { return }; + for index in 0..s.len() { + let before = s.before_instance(index); + let layer = self.layers.plan.iter().rposition(|l| before > l.begin && before <= l.end); + let bounds = self.layer_target(layer).map_or( + [0.0, 0.0, self.layers.viewport.0 as f32, self.layers.viewport.1 as f32], + |p| self.layers.planner.dispositions.get(p).map_or([0.0; 4], |d| d.rect())); + // prepare_surfaces may precede prepare on the first frame. + if bounds[2] > 0.0 && bounds[3] > 0.0 { s.target(queue, index, bounds); } + } + } + + /// Encode isolated scopes before opening a compositor render pass that calls `draw_range`. + /// `draw`/`draw_timed` do this automatically. Contents are redrawn each presentation so GPU + /// springs and newly latched native surfaces stay live; textures, not content, are pooled. + pub fn encode_layers(&self, encoder: &mut wgpu::CommandEncoder) { + self.encode_layers_timed(encoder, None, &mut |_, _| {}); + } + + /// `encode_layers` that calls `hook` at each effect slot inside an isolated layer, in painter + /// order within that layer's pass. The layer's opacity, blur, dissolve and clip then apply to + /// whatever the hook drew when the layer composites. Slots outside any layer are reached by + /// `draw_range_with` or `draw_with`. + pub fn encode_layers_with(&self, encoder: &mut wgpu::CommandEncoder, hook: &mut EffectHook<'_>) { + self.encode_layers_timed(encoder, None, &mut |phase, site| { + if let EffectPhase::Draw(pass) = phase { hook(pass, site); } + }); + } + + /// `encode_layers_with` that also calls `hook(EffectPhase::Backdrop(encoder), site)` outside + /// the render pass at each backdrop slot (`El::effect_backdrop(true)`) inside an isolated + /// layer, right after copying the layer's target up to that slot into `EffectSite::backdrop` + /// and before re-opening the layer's pass for `EffectPhase::Draw(pass)`. + pub fn encode_layers_with_backdrop(&self, encoder: &mut wgpu::CommandEncoder, hook: &mut EffectBackdropHook<'_>) { + self.encode_layers_timed(encoder, None, hook); + } + + /// Origin and size of a pass's target: a layer's bounds, or the frame viewport. + pub(super) fn target_frame(&self, target: Option<usize>) -> ([f32; 2], [u32; 2]) { + match target { + Some(index) => { + let b = self.layers.planner.dispositions.get(index).map_or([0.0; 4], |d| d.rect()); + ([b[0], b[1]], [b[2] as u32, b[3] as u32]) + } + None => ([0.0, 0.0], [self.layers.viewport.0, self.layers.viewport.1]), + } + } + + pub(super) fn encode_layers_timed(&self, encoder: &mut wgpu::CommandEncoder, timestamps: Option<&wgpu::RenderPassTimestampWrites<'_>>, hook: &mut EffectBackdropHook<'_>) { + self.flush_uploads(encoder); + let mut first = true; + for (index, l) in self.layers.plan.iter().enumerate().rev() { + let disposition = self.layers.planner.dispositions.get(index).copied().unwrap_or(Disposition::Skip); + if !matches!(disposition, Disposition::Render { .. }) { continue; } + let Some(target) = &self.layers.targets[index] else { continue }; + let rect = disposition.rect(); + let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { + label: Some("isolated group"), + color_attachments: &[Some(wgpu::RenderPassColorAttachment { + view: &target.view, depth_slice: None, resolve_target: None, + ops: wgpu::Operations { load: wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT), store: wgpu::StoreOp::Store }, + })], depth_stencil_attachment: None, + timestamp_writes: if first { timestamps.map(|t| wgpu::RenderPassTimestampWrites { + query_set: t.query_set, beginning_of_pass_write_index: t.beginning_of_pass_write_index, + end_of_pass_write_index: None, + }) } else { None }, + occlusion_query_set: None, multiview_mask: None, + }).forget_lifetime(); + first = false; + pass.set_viewport(0.0, 0.0, rect[2], rect[3], 0.0, 1.0); + let mut active = ActivePass::owned(pass, encoder, &target.view); + self.draw_layer_range(&mut active, FORMAT, l.begin + 1..l.end, Some(index), hook); + drop(active); + if let Some(blur) = &target.blur { + self.layers.blur.as_ref().unwrap().encode(encoder, blur, &target.view); + } + } + } + + pub(super) fn draw_layer_range(&self, pass: &mut ActivePass<'_, '_>, format: wgpu::TextureFormat, range: Range<u32>, target: Option<usize>, hook: &mut EffectBackdropHook<'_>) { + let mut cursor = range.start; + for (index, l) in self.layers.plan.iter().enumerate() { + if l.begin < cursor || l.begin >= range.end { continue; } + assert!(l.end < range.end, "draw_range must not split a layer scope"); + self.draw_plain(pass, format, cursor..l.begin, target, true, hook); + let disposition = self.layers.planner.dispositions.get(index).copied().unwrap_or(Disposition::Skip); + if let (Disposition::Render { .. } | Disposition::Cached { .. }, Some(t)) = (disposition, &self.layers.targets[index]) { + let pipeline = if self.layer_blend(target) == Blend::PlusLighter { + &self.layers.additive.as_ref().expect("prepared dissolve").1 + } else { &self.layers.pipelines.iter().find(|(f, _)| *f == format).expect("Renderer::add_format first").1 }; + pass.set_pipeline(pipeline); + if let Some(properties) = &self.springs { pass.set_bind_group(1, &properties.group, &[]); } + pass.set_bind_group(0, &t.composite, &[]); + pass.set_vertex_buffer(0, t.quad.slice(..)); + pass.draw(0..4, 0..1); + } else if disposition == Disposition::Inline { + // An opaque group that needs no target, or any group while layers can't isolate + // (`breaker`). + if l.clip != NO_CLIP { + let (origin, size) = self.target_frame(target); + let edge = |v: f32, o: f32, max: u32| (v - o).clamp(0.0, max as f32) as u32; + let (mut x0, mut y0) = (edge(l.clip[0].floor(), origin[0], size[0]), edge(l.clip[1].floor(), origin[1], size[1])); + let (mut x1, mut y1) = (edge(l.clip[2].ceil(), origin[0], size[0]), edge(l.clip[3].ceil(), origin[1], size[1])); + // Inside an enclosing inline clip: both apply. + let outer = pass.scissor(); + if let Some([ox, oy, ow, oh]) = outer { + (x0, y0, x1, y1) = (x0.max(ox), y0.max(oy), x1.min(ox + ow), y1.min(oy + oh)); + } + if x1 > x0 && y1 > y0 { + pass.set_scissor(Some([x0, y0, x1 - x0, y1 - y0]), size); + self.draw_layer_range(pass, format, l.begin + 1..l.end, target, hook); + pass.set_scissor(outer, size); + } + } else { + self.draw_layer_range(pass, format, l.begin + 1..l.end, target, hook); + } + } + cursor = l.end + 1; + } + let include_end = range.end == self.count || self.layers.plan.iter().any(|l| l.end == range.end); + self.draw_plain(pass, format, cursor..range.end, target, include_end, hook); + } + + pub(super) fn validate_layer_range(&self, range: &Range<u32>) { + for l in &self.layers.plan { + assert!(!(l.begin < range.start && range.start <= l.end) + && !(l.begin < range.end && range.end <= l.end), "draw_range must not split a layer scope"); + } + } + + fn draw_plain(&self, pass: &mut ActivePass<'_, '_>, format: wgpu::TextureFormat, range: Range<u32>, target: Option<usize>, include_end: bool, hook: &mut EffectBackdropHook<'_>) { + let mut cursor = range.start; + if let Some(s) = &self.surfaces { + for index in 0..s.len() { + let before = s.before_instance(index); + if before < range.start || before > range.end || (before == range.end && !include_end) { continue; } + self.draw_with_effects(pass, format, cursor..before, target, hook); + // Only the window's own pass can punch a video's place out for its layer. + match target { + None => s.draw_main(pass, index, format, self.layer_blend(target)), + Some(_) => s.draw_isolated(pass, index, format, self.layer_blend(target)), + } + cursor = before; + } + } + self.draw_with_effects(pass, format, cursor..range.end, target, hook); + } +} diff --git a/app/vendor/rune/crates/rune/src/render/layers/plan.rs b/app/vendor/rune/crates/rune/src/render/layers/plan.rs new file mode 100644 index 0000000..9fbaf31 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/render/layers/plan.rs @@ -0,0 +1,470 @@ +//! The layer plan: the record the planning walk leaves for each layer, and the one decision that +//! turns it into what the layer does this frame. Deciding on plain data means everything after it +//! only carries the plan out: no layer's verdict and no target's place in a pool changes under a +//! later pass, which is what a rewrite mid-prepare used to do. +use super::*; + +#[cfg(test)] +#[path = "plan_tests.rs"] +mod tests; + +/// A layer's scope, as the planning walk recorded it. +#[derive(Clone, Copy, Debug)] +pub(super) struct Layer { + pub(super) begin: u32, + pub(super) end: u32, + pub(super) parent: Option<usize>, + /// The edges of what it draws, `[x0, y0, x1, y1]`, while planning. + pub(super) edges: [f32; 4], + /// The part of `edges` that can show, which a cache that doesn't fit falls back to. + pub(super) vis: [f32; 4], + pub(super) clip: [f32; 4], + pub(super) limit: [f32; 4], // ancestor output needed by their filters; never a replacement rounded clip + pub(super) fade: [u32; 4], + pub(super) opacity: f32, + pub(super) blend: Blend, + pub(super) blur: f32, + pub(super) support: f32, + /// The node and signature `El::cache` asked to keep it under. + pub(super) cache: Option<(u64, u64)>, + pub(super) planned: Planned, + /// `Instance::turned`: the composite turns `angle` radians about `pivot`. + pub(super) turn: Option<(f32, [f32; 2])>, + /// Turned, or inside a turned layer: the window, clips and filter limits above don't line + /// up with this layer's pixels, so `frame` bounds it instead. + pub(super) free: bool, + /// For a free layer, the edges of its contents that can reach the window. + pub(super) frame: [f32; 4], + /// The round hole its composite cuts (`El::cutout_circle`): centre, then the radii it's clear + /// within and whole from, in window device pixels; zeros for none. + pub(super) hole: [f32; 4], +} + +/// What the planning walk knew when it reached a layer, before the frame settles it into a +/// [`Disposition`]. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum Planned { + /// Nothing to draw: transparent, empty, or inside a transparent layer. + Hidden, + /// Inside a cache that composites from its texture, so not drawn on its own. + Covered, + /// Drawn straight into its parent's pass, unless a cache covers it. + Inline, +} + +/// What a layer does this frame, and the one place it draws into: decided once, by +/// [`Planner::decide`], so nothing that follows can change its mind. +#[derive(Clone, Copy, Debug, PartialEq)] +pub(super) enum Disposition { + /// Nothing to draw: transparent, empty, or inside a cache that composites from its texture. + Skip, + /// Drawn straight into its parent's pass. + Inline, + /// Drawn into a target of its own, then composited. The target keeps `cache` for the next frame. + Render { rect: [f32; 4], cache: Option<(u64, u64)> }, + /// Composited from the texture its cache kept, without drawing into it. `cache` is `None` when + /// the budget only let this frame borrow the texture. + Cached { rect: [f32; 4], cache: Option<(u64, u64)> }, +} + +impl Disposition { + /// The place of the layer's target in the window, for the two that have one. + pub(super) fn rect(self) -> [f32; 4] { + match self { + Self::Render { rect, .. } | Self::Cached { rect, .. } => rect, + Self::Skip | Self::Inline => [0.0; 4], + } + } +} + +/// A target as the plan sees it: its size, what it holds and what it costs, with no handle, so +/// [`Planner::decide`] needs no device and a walk can drive it. +#[derive(Clone, Copy, Debug, PartialEq)] +pub(super) struct Held { + pub(super) size: [u32; 2], + pub(super) bytes: u64, + pub(super) cache: Option<(u64, u64)>, + pub(super) last_used: u64, + pub(super) content: [f32; 2], +} + +impl Held { + /// What a target of `size` costs, and holds, before anything draws into it. + fn new(size: [u32; 2], bpp: u64) -> Self { + Self { size, bytes: u64::from(size[0]) * u64::from(size[1]) * bpp, cache: None, last_used: 0, content: [0.0; 2] } + } +} + +/// Which pool a kept target is in. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum Kept { + Retained(usize), + Spare(usize), +} + +/// One change to the target pools, in the order the plan decided it. `Renderer::commit` is the +/// only place a target changes pool. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum Move { + /// Parks a slot's target for a later layer of its size. + Park(usize), + /// Puts a kept target in a slot, dropping whatever it held. + Set { slot: usize, from: Kept }, + /// Makes a target of `size` for a slot. + Create { slot: usize, size: [u32; 2] }, + /// Drops a slot target's blur scratch: the layer draws unblurred from now on, and the scratch + /// must go before a later layer makes a texture of its own (dev dropped it in the same place). + Unblur(usize), + /// Drops a kept target. + Drop(Kept), +} + +/// Whether a layer's clip can be applied as a hardware scissor without isolating into an +/// offscreen target: unclipped, or an integer-aligned square rectangle with no fade. +pub(in crate::render) fn is_scissor_clip(clip: [f32; 4], fade: [u32; 4]) -> bool { + clip == NO_CLIP || (fade == [0; 4] && clip.iter().all(|v| (v - v.round()).abs() < 1e-3)) +} + +/// A layer's bounds, from the edges of what it draws. +pub(super) fn rect_of(edges: [f32; 4]) -> [f32; 4] { + [edges[0], edges[1], (edges[2] - edges[0]).max(0.0), (edges[3] - edges[1]).max(0.0)] +} + +/// A target's texture size for `bounds`: whole 64-pixel buckets, beside the size it was asked for. +fn bucket_of(bounds: [f32; 4]) -> ([u32; 2], u32, u32) { + let (width, height) = (bounds[2] as u32, bounds[3] as u32); + ([width.div_ceil(64) * 64, height.div_ceil(64) * 64], width, height) +} + +/// What a texel of a layer target costs. +fn bpp() -> u64 { + u64::from(FORMAT.block_copy_size(None).unwrap()) +} + +/// Where a target the plan has placed is before the frame's moves: in a layer's slot, at a place +/// in a pool, or not yet made. The plan reads its [`Held`] there, in place. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum Source { + Slot(usize), + Retained(usize), + Spare(usize), + New([u32; 2]), +} + +/// A target that can say what it is to the plan, without a device. +pub(super) trait Describe { + fn held(&self) -> Held; +} + +/// The target pools as the frame starts. The plan reads them where they are and moves nothing. +pub(super) struct Pools<'a, T> { + pub(super) slots: &'a [Option<T>], + pub(super) retained: &'a [T], + pub(super) spare: &'a [T], +} + +impl<T: Describe> Pools<'_, T> { + fn held(&self, source: Source) -> Held { + match source { + Source::Slot(index) => self.slots[index].as_ref().expect("the plan places only targets that exist").held(), + Source::Retained(at) => self.retained[at].held(), + Source::Spare(at) => self.spare[at].held(), + Source::New(size) => Held::new(size, bpp()), + } + } +} + +/// A pool as the plan has rearranged it so far. Until the plan first moves a target in or out, it +/// is the pool itself, read in place; from then on `order` says where each place's target is. +#[derive(Clone)] +pub(super) struct View { + own: fn(usize) -> Source, + len: usize, + moved: bool, + order: Vec<Source>, + /// Test-only: every place the plan has read or copied, over every frame. + #[cfg(test)] + pub(super) visits: u64, +} + +impl View { + fn new(own: fn(usize) -> Source) -> Self { + Self { own, len: 0, moved: false, order: Vec::new(), #[cfg(test)] visits: 0 } + } + + /// Starts a frame on a pool of `len` targets. + fn reset(&mut self, len: usize) { + self.len = len; + self.moved = false; + self.order.clear(); + } + + /// The target at `place`. + fn held<T: Describe>(&mut self, place: usize, pools: &Pools<'_, T>) -> Held { + #[cfg(test)] + { self.visits += 1; } + pools.held(self.source(place)) + } + + /// Where the target at `place` is before the frame's moves. + fn source(&self, place: usize) -> Source { + if self.moved { self.order[place] } else { (self.own)(place) } + } + + /// The first place whose target passes `test`. + fn position<T: Describe>(&mut self, pools: &Pools<'_, T>, test: impl Fn(&Held) -> bool) -> Option<usize> { + (0..self.len).find(|&place| test(&self.held(place, pools))) + } + + /// What every target in it costs. + fn bytes<T: Describe>(&mut self, pools: &Pools<'_, T>) -> u64 { + (0..self.len).map(|place| self.held(place, pools).bytes).sum() + } + + /// The place of the least recently used target, the first of equals. + fn oldest<T: Describe>(&mut self, pools: &Pools<'_, T>) -> usize { + (0..self.len).min_by_key(|&place| self.held(place, pools).last_used).unwrap() + } + + /// Takes the target at `place` out, the last one taking its place, as `Vec::swap_remove` does. + fn swap_remove(&mut self, place: usize) -> Source { + self.own_order(); + self.len -= 1; + self.order.swap_remove(place) + } + + fn push(&mut self, source: Source) { + self.own_order(); + self.len += 1; + self.order.push(source); + } + + /// From the first move on, the plan keeps the pool's order itself. + fn own_order(&mut self) { + if self.moved { return; } + #[cfg(test)] + { self.visits += self.len as u64; } + let own = self.own; + self.order.extend((0..self.len).map(own)); + self.moved = true; + } +} + +/// What the plan's scratch keeps between frames, in entries: an ordinary frame's layers, so a menu +/// that opens and closes allocates nothing. +const WARM: usize = 64; + +/// Gives back what a burst grew `scratch` to, beyond twice what `keep` entries need. +fn shrink<T>(scratch: &mut Vec<T>, keep: usize) { + if scratch.capacity() > 2 * keep { scratch.shrink_to(keep); } +} + +/// The plan of a frame's layers, and the scratch it is decided in, kept warm between frames. +#[derive(Clone)] +pub(super) struct Planner { + /// What each layer does this frame, one per layer: `decide` fills it, and only its two + /// targetted variants carry the place their target draws. + pub(super) dispositions: Vec<Disposition>, + /// The changes to the target pools, in the order `Renderer::commit` carries them out. + pub(super) moves: Vec<Move>, + /// Where the target in each layer's slot is before the moves. + slots: Vec<Option<Source>>, + pub(super) kept: View, + pub(super) parked: View, + /// Test-only: how many frames have given scratch back. + #[cfg(test)] + pub(super) settles: u64, +} + +impl Default for Planner { + fn default() -> Self { + Self { + dispositions: Vec::new(), + moves: Vec::new(), + slots: Vec::new(), + kept: View::new(Source::Retained), + parked: View::new(Source::Spare), + #[cfg(test)] + settles: 0, + } + } +} + +impl Planner { + /// Decides what every layer of `plan` does this frame, and every change to the target pools it + /// takes. It reads each target where `pools` holds it, and only where dev's passes read one: a + /// layer whose slot fits reads no spare. It moves nothing and needs no device, so a walk of + /// frames drives it. + pub(super) fn decide<T: Describe>(&mut self, plan: &[Layer], pools: &Pools<'_, T>, budget: u64, isolate: bool, max_dim: u32) { + let bpp = bpp(); + self.dispositions.clear(); + self.dispositions.resize(plan.len(), Disposition::Skip); + self.slots.clear(); + self.slots.extend(pools.slots.iter().enumerate().map(|(index, t)| t.is_some().then_some(Source::Slot(index)))); + self.moves.clear(); + self.kept.reset(pools.retained.len()); + self.parked.reset(pools.spare.len()); + let mut active = 0u64; + // First claim resident cache hits, so caches already on screen never thrash under a tight + // budget. + for (index, layer) in plan.iter().enumerate() { + let rect = rect_of(layer.edges); + if rect[2] == 0.0 || rect[3] == 0.0 || !isolate || layer.planned != Planned::Inline { continue; } + let Some(cache) = layer.cache else { continue }; + let Some(at) = self.kept.position(pools, |t| t.cache == Some(cache)) else { continue }; + let bytes = self.kept.held(at, pools).bytes; + let over = active + bytes > budget; + // A cache with contents keeps its place under the budget: it can't be made again cheaply. + if over && layer.begin + 1 < layer.end { continue; } + if !over { active += bytes; } + self.dispositions[index] = Disposition::Cached { rect, cache: (!over).then_some(cache) }; + self.slots[index] = Some(self.kept.swap_remove(at)); + self.moves.push(Move::Set { slot: index, from: Kept::Retained(at) }); + } + for (index, layer) in plan.iter().enumerate() { + if matches!(self.dispositions[index], Disposition::Cached { .. }) { continue; } + let rect = rect_of(layer.edges); + let parent = layer.parent.map(|p| self.dispositions[p]); + // A layer inside a cache that composites from its texture, or inside a transparent one, + // draws nothing: what a cache kept comes from its texture. + if layer.planned == Planned::Hidden || rect[2] == 0.0 || rect[3] == 0.0 + || matches!(parent, Some(Disposition::Skip | Disposition::Cached { .. })) { + self.dispositions[index] = Disposition::Skip; + self.park_slot(index, pools); + continue; + } + if !isolate { + // Without isolation (`breaker`), every group draws straight into its parent. + self.dispositions[index] = Disposition::Inline; + self.park_slot(index, pools); + continue; + } + let mut bounds = rect; + let (mut bucket, mut width, mut height) = bucket_of(bounds); + let mut cache = None; + if let Some((node, sig)) = layer.cache { + let previous = self.kept.position(pools, |t| t.cache.is_some_and(|(n, _)| n == node)); + let needed = u64::from(bucket[0]) * u64::from(bucket[1]) * bpp; + if bucket[0] <= max_dim && bucket[1] <= max_dim && active + needed <= budget { + active += needed; + cache = Some((node, sig)); + match previous { + // Take the target this node kept: the new bounds may only be smaller. + Some(at) => { + self.park_slot(index, pools); + self.slots[index] = Some(self.kept.swap_remove(at)); + self.moves.push(Move::Set { slot: index, from: Kept::Retained(at) }); + } + None => self.trim(active, budget, pools), + } + } else { + if let Some(at) = previous { + self.kept.swap_remove(at); + self.moves.push(Move::Drop(Kept::Retained(at))); + } + // Drawn like an uncached group, it only needs the part that shows. + bounds = rect_of(layer.vis); + (bucket, width, height) = bucket_of(bounds); + } + } + let additive_parent = layer.parent.is_some_and(|p| plan[p].blend == Blend::PlusLighter); + // A clip of whole pixels with square corners and no fade is a scissor, exactly: such a + // group draws straight into its parent too (`Renderer::draw_layer_range`). That keeps a + // clipped pane's video in the window's own pass, where its own layer can show it. + let scissor_clip = is_scissor_clip(layer.clip, layer.fade); + if cache.is_none() && layer.opacity == 1.0 && layer.blend == Blend::SourceOver && !additive_parent + && layer.blur == 0.0 && layer.fade[3] == 0 && scissor_clip + && layer.turn.is_none() && layer.hole[3] == 0.0 { + self.dispositions[index] = Disposition::Inline; + self.park_slot(index, pools); + continue; + } + self.dispositions[index] = Disposition::Render { rect: bounds, cache }; + let fits = self.slots[index].is_some_and(|source| { + let size = pools.held(source).size; + // The minimum bucket is unavoidable for tiny controls. Do not recreate that + // same bucket every frame when rounding alone exceeds the 2x area limit. + size[0] >= width && size[1] >= height && (size == bucket + || u64::from(size[0]) * u64::from(size[1]) <= 2 * u64::from(width) * u64::from(height)) + }); + if !fits { + self.park_slot(index, pools); + let spare = self.parked.position(pools, |t| { + let size = t.size; + size[0] >= width && size[1] >= height + && u64::from(size[0]) * u64::from(size[1]) <= 2 * u64::from(width.max(64)) * u64::from(height.max(64)) + }); + match spare { + Some(at) => { + self.slots[index] = Some(self.parked.swap_remove(at)); + self.moves.push(Move::Set { slot: index, from: Kept::Spare(at) }); + } + None => { + self.slots[index] = Some(Source::New(bucket)); + self.moves.push(Move::Create { slot: index, size: bucket }); + } + } + } + // The scratch a blur left behind goes before the next layer makes its own texture. + if layer.blur == 0.0 { self.moves.push(Move::Unblur(index)); } + } + self.trim(active, budget, pools); + } + + /// After a frame whose layers fell to `len`: forgets the plan when no layer is left, and gives + /// back what a burst grew the scratch to. The per-layer buffers keep what `len` layers need; a + /// pool's order keeps what the `retained` or `spare` targets left in that pool need, since the + /// next frame to move one copies the whole pool's order. A frame that keeps its layers, or + /// stays empty, never comes here, so it touches nothing. + pub(super) fn settle(&mut self, len: usize, retained: usize, spare: usize) { + #[cfg(test)] + { self.settles += 1; } + // The moves are carried out and the views read; only the dispositions outlive the frame. + self.moves.clear(); + self.slots.clear(); + self.kept.reset(0); + self.parked.reset(0); + if len == 0 { self.dispositions.clear(); } + let keep = len.max(WARM); + shrink(&mut self.dispositions, keep); + shrink(&mut self.moves, keep); + shrink(&mut self.slots, keep); + shrink(&mut self.kept.order, retained.max(WARM)); + shrink(&mut self.parked.order, spare.max(WARM)); + } + + /// Test-only: the scratch's capacities, which a warm frame never changes. + #[cfg(test)] + pub(super) fn capacities(&self) -> [usize; 5] { + [self.dispositions.capacity(), self.moves.capacity(), self.slots.capacity(), + self.kept.order.capacity(), self.parked.order.capacity()] + } + + /// Parks slot `index`'s target for a later layer of its size: what `spare` stops holding once + /// it passes `SPARE_BYTES`, least recently used first, goes. + fn park_slot<T: Describe>(&mut self, index: usize, pools: &Pools<'_, T>) { + let Some(source) = self.slots[index].take() else { return }; + self.moves.push(Move::Park(index)); + self.parked.push(source); + let mut bytes = self.parked.bytes(pools); + while bytes > SPARE_BYTES { + let oldest = self.parked.oldest(pools); + bytes -= self.parked.held(oldest, pools).bytes; + self.parked.swap_remove(oldest); + self.moves.push(Move::Drop(Kept::Spare(oldest))); + } + } + + /// Drops the least recently used kept targets until the budget left after this frame's `active` + /// cache bytes holds them. + fn trim<T: Describe>(&mut self, active: u64, budget: u64, pools: &Pools<'_, T>) { + let available = budget.saturating_sub(active); + let mut bytes = self.kept.bytes(pools); + while bytes > available { + let oldest = self.kept.oldest(pools); + bytes -= self.kept.held(oldest, pools).bytes; + self.kept.swap_remove(oldest); + self.moves.push(Move::Drop(Kept::Retained(oldest))); + } + } +} diff --git a/app/vendor/rune/crates/rune/src/render/layers/plan_frame_tests.rs b/app/vendor/rune/crates/rune/src/render/layers/plan_frame_tests.rs new file mode 100644 index 0000000..9cc6f6d --- /dev/null +++ b/app/vendor/rune/crates/rune/src/render/layers/plan_frame_tests.rs @@ -0,0 +1,174 @@ +//! What a frame costs the plan: a frame with no layers plans nothing at all, a frame reads no spare +//! target dev didn't, the plan's scratch stays warm without keeping a burst's size, and the scratch +//! a layer stops needing goes before a later layer makes a texture, so the frame's peak is dev's. +use super::tests::rect; +use super::*; + +/// A group that needs a target of its own: half-opaque, and blurred when `sigma` is not zero. +fn group(bounds: [f32; 4], sigma: f32) -> Vec<Instance> { + vec![Instance::begin_layer(bounds, NO_CLIP, LayerSpec { opacity: 0.5, blur: sigma, ..Default::default() }), + rect(bounds, [1.0; 4]), Instance::end_layer()] +} + +/// 1,024 small groups, each with a target of its own. +fn burst() -> Vec<Instance> { + (0..1024).flat_map(|index| group([(index % 32) as f32 * 8.0, (index / 32) as f32 * 8.0, 8.0, 8.0], 0.0)).collect() +} + +/// Whether every one of the plan's scratch buffers holds no more than an ordinary frame keeps. +fn warm_sized(renderer: &Renderer) -> bool { + renderer.layers.planner.capacities().iter().all(|&capacity| capacity <= 64) +} + +/// A frame with no layers draws nothing, so it must plan nothing: dev walked no target and no layer +/// there, and neither may the plan, however many layers closed on the frame before. +#[test] +fn a_layerless_frame_plans_nothing() { + let gpu = Gpu::headless(); + let mut renderer = Renderer::new(&gpu.device, OFFSCREEN_FORMAT); + let mut atlas = crate::text::TextSystem::default().atlas; + renderer.prepare(&gpu.device, &gpu.queue, &mut atlas, &burst(), (256, 256)); + assert_eq!(renderer.layer_stats().targets, 1024, "a frame's worth of layers, every one with a target"); + + // They close: their targets stay parked for the next layer of their size, and the plan's own + // buffers must not be left behind at a burst's size for every frame after them. + renderer.prepare(&gpu.device, &gpu.queue, &mut atlas, &[], (256, 256)); + let stats = renderer.layer_stats(); + assert_eq!((stats.targets, stats.bytes, stats.extra_passes), (0, 0, 0), "nothing is drawn"); + assert!(renderer.layers.planner.dispositions.is_empty()); + assert!(renderer.layers.planner.moves.is_empty()); + assert!(warm_sized(&renderer), "a burst's planning buffers go with it"); +} + +/// One layer left of a burst keeps its own target, which still fits: dev never looked at the spare +/// pool again, and neither may the plan, frame after frame. +#[test] +fn one_layer_left_of_a_burst_reads_no_spare() { + let gpu = Gpu::headless(); + let mut renderer = Renderer::new(&gpu.device, OFFSCREEN_FORMAT); + let mut atlas = crate::text::TextSystem::default().atlas; + let burst = burst(); + renderer.prepare(&gpu.device, &gpu.queue, &mut atlas, &burst, (256, 256)); + let visits = renderer.layers.planner.parked.visits; + for frame in 0..4 { + renderer.prepare(&gpu.device, &gpu.queue, &mut atlas, &burst[..3], (256, 256)); + assert_eq!(renderer.layers.spare.len(), 1023, "the burst's other targets are parked"); + assert_eq!(renderer.layers.planner.parked.visits, visits, "frame {frame} read a spare"); + assert!(warm_sized(&renderer), "a burst's planning buffers go once it ends"); + } +} + +/// A menu that opens and closes again and again: once warm, neither the plan's scratch nor a +/// target is made again, as dev reused its vectors and the target it parked. +#[test] +fn a_warm_menu_opens_and_closes_without_allocating() { + let gpu = Gpu::headless(); + let mut renderer = Renderer::new(&gpu.device, OFFSCREEN_FORMAT); + let mut atlas = crate::text::TextSystem::default().atlas; + let menu = group([4.0, 4.0, 40.0, 24.0], 0.0); + // The first opening makes the target; the second takes it back from the spares. + for instances in [&menu[..], &[], &menu[..]] { + renderer.prepare(&gpu.device, &gpu.queue, &mut atlas, instances, (64, 64)); + } + let (warm, allocations) = (renderer.layers.planner.capacities(), renderer.layer_stats().allocations); + for toggle in 0..4 { + renderer.prepare(&gpu.device, &gpu.queue, &mut atlas, &[], (64, 64)); + assert_eq!(renderer.layers.planner.capacities(), warm, "closing {toggle}"); + renderer.prepare(&gpu.device, &gpu.queue, &mut atlas, &menu, (64, 64)); + assert_eq!(renderer.layers.planner.capacities(), warm, "opening {toggle}"); + assert_eq!(renderer.layer_stats().allocations, allocations, "opening {toggle} made a target"); + } +} + +/// A list's cached rows (`El::cache`, one node a row), 64×16 each, the first `count` of them. +fn rows(count: u64) -> Vec<Instance> { + (0..count).flat_map(|row| { + let bounds = [0.0, row as f32 * 16.0, 64.0, 16.0]; + let mut scope = Instance::begin_layer(bounds, NO_CLIP, LayerSpec::default()); + scope.params[3] = 1.0; + scope.radii = pack_u64_f32(row); + scope.uv = pack_u64_f32(1); + [scope, rect(bounds, [1.0; 4]), Instance::end_layer()] + }).collect() +} + +/// A list of 160 cached rows, 13 and then 12 of them showing by turns: the pool keeps every row, +/// so the plan's copy of the pool's order stays at the pool's size, as dev reused its pool. +#[test] +fn a_list_showing_twelve_and_thirteen_cached_rows_by_turns_allocates_nothing() { + let gpu = Gpu::headless(); + let mut renderer = Renderer::new(&gpu.device, OFFSCREEN_FORMAT); + let mut atlas = crate::text::TextSystem::default().atlas; + let (all, twelve, thirteen) = (rows(160), rows(12), rows(13)); + for instances in [&all, &thirteen, &twelve, &thirteen, &twelve] { + renderer.prepare(&gpu.device, &gpu.queue, &mut atlas, instances, (64, 2560)); + } + assert_eq!(renderer.layers.retained.len(), 148, "every row the list doesn't show is kept"); + let (warm, allocations) = (renderer.layers.planner.capacities(), renderer.layer_stats().allocations); + for turn in 0..4 { + renderer.prepare(&gpu.device, &gpu.queue, &mut atlas, &thirteen, (64, 2560)); + assert!(matches!(renderer.layers.planner.dispositions[12], Disposition::Cached { .. }), "the thirteenth row is a hit"); + assert_eq!(renderer.layers.planner.capacities(), warm, "thirteen rows, turn {turn}"); + renderer.prepare(&gpu.device, &gpu.queue, &mut atlas, &twelve, (64, 2560)); + assert_eq!(renderer.layers.planner.capacities(), warm, "twelve rows, turn {turn}"); + assert_eq!(renderer.layer_stats().allocations, allocations, "turn {turn} made a target"); + } +} + +/// After a burst parks 1,024 targets, a menu that opens takes one back and copies the spare pool's +/// order to do it: closing again must not give that copy back while the pool is still that large. +#[test] +fn a_menu_after_a_burst_opens_and_closes_without_allocating() { + let gpu = Gpu::headless(); + let mut renderer = Renderer::new(&gpu.device, OFFSCREEN_FORMAT); + let mut atlas = crate::text::TextSystem::default().atlas; + let burst = burst(); + let menu = &burst[..3]; + for instances in [&burst[..], &[], menu, &[], menu] { + renderer.prepare(&gpu.device, &gpu.queue, &mut atlas, instances, (256, 256)); + } + let (warm, allocations) = (renderer.layers.planner.capacities(), renderer.layer_stats().allocations); + for toggle in 0..4 { + renderer.prepare(&gpu.device, &gpu.queue, &mut atlas, &[], (256, 256)); + assert_eq!(renderer.layers.spare.len(), 1024, "the burst's targets are all parked"); + assert_eq!(renderer.layers.planner.capacities(), warm, "closing {toggle}"); + renderer.prepare(&gpu.device, &gpu.queue, &mut atlas, menu, (256, 256)); + assert_eq!(renderer.layers.planner.capacities(), warm, "opening {toggle}"); + assert_eq!(renderer.layer_stats().allocations, allocations, "opening {toggle} made a target"); + } +} + +/// The frame a menu closes on forgets its plan; the empty frames after it have nothing to forget. +#[test] +fn an_empty_frame_after_an_empty_frame_does_nothing() { + let gpu = Gpu::headless(); + let mut renderer = Renderer::new(&gpu.device, OFFSCREEN_FORMAT); + let mut atlas = crate::text::TextSystem::default().atlas; + renderer.prepare(&gpu.device, &gpu.queue, &mut atlas, &group([4.0, 4.0, 40.0, 24.0], 0.0), (64, 64)); + renderer.prepare(&gpu.device, &gpu.queue, &mut atlas, &[], (64, 64)); + assert_eq!(renderer.layers.planner.settles, 1, "the frame the menu closed on"); + for frame in 0..3 { + renderer.prepare(&gpu.device, &gpu.queue, &mut atlas, &[], (64, 64)); + assert_eq!(renderer.layers.planner.settles, 1, "empty frame {frame} tidied the plan"); + } +} + +/// Two viewport-sized half-opaque siblings each fill a 2,048 bucket: 32 MiB of texture. The first +/// blurs at sigma 1, whose scratch is one more texture at the same size, and dev dropped that +/// scratch before the sibling's texture existed: at most 64 MiB is ever live at once. +#[test] +fn a_frame_never_holds_more_layer_textures_than_dev() { + let gpu = Gpu::headless(); + let mut renderer = Renderer::new(&gpu.device, OFFSCREEN_FORMAT); + let mut atlas = crate::text::TextSystem::default().atlas; + let (one, two) = ([4.0, 4.0, 2000.0, 2000.0], [8.0, 8.0, 2000.0, 2000.0]); + renderer.prepare(&gpu.device, &gpu.queue, &mut atlas, &group(one, 1.0), (2048, 2048)); + assert_eq!(renderer.layers.peak_bytes(), 64 << 20, "the layer's texture and its blur scratch"); + + // It stops blurring while a sibling appears: its scratch is released before the sibling's + // texture is made, as dev released it in the same layer's own step. + let mut instances = group(one, 0.0); + instances.extend(group(two, 0.0)); + renderer.prepare(&gpu.device, &gpu.queue, &mut atlas, &instances, (2048, 2048)); + assert_eq!(renderer.layers.peak_bytes(), 64 << 20, "two textures, with the scratch already gone"); +} diff --git a/app/vendor/rune/crates/rune/src/render/layers/plan_tests.rs b/app/vendor/rune/crates/rune/src/render/layers/plan_tests.rs new file mode 100644 index 0000000..bc4da41 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/render/layers/plan_tests.rs @@ -0,0 +1,572 @@ +//! A walk of every frame sequence through the plan, checked against origin/dev's planning passes +//! transcribed over plain records: what each layer draws, and what becomes of the target pools. +//! +//! The reference is dev's code as it was, not a cleaned-up version of it: the claim pass, the settle +//! pass and the allocate pass, each with the pools it reads and rewrites in the order it rewrote +//! them, its target writes where it made them, and what a blur scratch costs. The side under test +//! is the real `Planner::decide`, whose moves are carried out by `apply` (a transcription of +//! `commit`) and whose target descriptors are written by `finish` (a transcription of +//! `paint_layers`), so a move in the wrong order, at the wrong index, or with a disposition changed, +//! fails the walk. +use super::*; + +/// A layer of a frame's scene, as the planning walk would record it. +#[derive(Clone, Copy, Debug)] +struct Spec { + parent: Option<usize>, + edges: [f32; 4], + vis: [f32; 4], + cache: Option<(u64, u64)>, + opacity: f32, + blend: Blend, + /// The blur's sigma, as `layer_blur::sigma` would have it. + blur: f32, + fade: u32, + clip: [f32; 4], + turn: Option<(f32, [f32; 2])>, + hole: [f32; 4], + /// The ordinary draws its scope opens with, before any child layer's. + draws: u32, +} + +impl Spec { + fn plain(edges: [f32; 4], vis: [f32; 4]) -> Self { + Self { parent: None, edges, vis, cache: None, opacity: 1.0, blend: Blend::SourceOver, blur: 0.0, + fade: 0, clip: NO_CLIP, turn: None, hole: [0.0; 4], draws: 0 } + } + + fn cached(edges: [f32; 4], vis: [f32; 4], cache: (u64, u64)) -> Self { + Self { cache: Some(cache), ..Self::plain(edges, vis) } + } + + fn child(parent: usize, edges: [f32; 4], vis: [f32; 4]) -> Self { + Self { parent: Some(parent), ..Self::plain(edges, vis) } + } +} + +/// The walk's scenes: what a frame's instance stream holds. +fn scenes() -> Vec<Vec<Spec>> { + let window = [0.0, 0.0, 32.0, 16.0]; + vec![ + // A cached card with a half-faded child (`layer_show_tests`' scene). + vec![Spec::cached([4.0, 2.0, 24.0, 12.0], window, (7, 1)), + Spec { opacity: 0.5, ..Spec::child(0, [8.0, 4.0, 16.0, 6.0], window) }], + // Two sibling caches, so one budget can hold one and not the other. + vec![Spec::cached([0.0, 0.0, 16.0, 8.0], window, (11, 1)), + Spec::cached([16.0, 8.0, 32.0, 16.0], window, (12, 3))], + // A cache inside a cache, and a child of the inner one: the outer scope has contents. + vec![Spec::cached([2.0, 1.0, 28.0, 14.0], window, (21, 2)), + Spec { parent: Some(0), ..Spec::cached([4.0, 2.0, 12.0, 8.0], window, (22, 5)) }, + Spec { opacity: 0.75, ..Spec::child(1, [6.0, 3.0, 8.0, 4.0], window) }], + // Something that flattens, a clip off whole pixels that isolates, a blur, a dissolve, and a + // clip of whole pixels that's a scissor and flattens. + vec![Spec::plain([0.0, 0.0, 8.0, 8.0], window), + Spec { clip: [4.5, 2.0, 20.0, 10.0], ..Spec::child(0, [4.0, 2.0, 16.0, 8.0], window) }, + Spec { blur: 2.0, ..Spec::plain([8.0, 0.0, 16.0, 8.0], window) }, + Spec { blend: Blend::PlusLighter, ..Spec::plain([12.0, 4.0, 8.0, 8.0], window) }, + Spec { clip: [8.0, 4.0, 24.0, 12.0], ..Spec::child(0, [8.0, 4.0, 16.0, 8.0], window) }], + // The cached card grown, so the target it kept no longer fits its bucket. + vec![Spec::cached([4.0, 2.0, 26.0, 13.0], window, (7, 1)), + Spec { opacity: 0.5, ..Spec::child(0, [8.0, 4.0, 18.0, 7.0], window) }], + // A turned cache, whose hit writes the same turned composite as its miss, and a fade that + // isolates without a target of its own. + vec![Spec { turn: Some((0.3, [16.0, 8.0])), ..Spec::cached([8.0, 4.0, 16.0, 8.0], window, (31, 4)) }, + Spec { fade: 1200, hole: [16.0, 8.0, 6.0, 8.0], ..Spec::plain([6.0, 2.0, 12.0, 12.0], window) }], + // A cached card that blurs widely: its target and the scratch's own work target are three + // 64×64 textures, more than the budget below will keep. + vec![Spec { blur: 12.0, ..Spec::cached([4.0, 2.0, 68.0, 66.0], window, (41, 1)) }, + Spec { opacity: 0.5, ..Spec::child(0, [8.0, 4.0, 16.0, 6.0], window) }], + // Two cached leaves side by side: the first draws a rect, a cache with contents and no + // child layer; the second draws nothing at all. + vec![Spec { draws: 1, ..Spec::cached([0.0, 0.0, 16.0, 8.0], window, (11, 1)) }, + Spec::cached([16.0, 8.0, 32.0, 16.0], window, (12, 3))], + ] +} + +/// Where each layer's scope opens and closes in the instance stream: a layer is a `KIND_LAYER` and a +/// `KIND_LAYER_END`, with its draws and then its child layers between them, so a cache with contents +/// of either kind has `begin + 1 < end` and one with none doesn't. +fn marks(scene: &[Spec]) -> (Vec<u32>, Vec<u32>) { + let mut at = 0u32; + let (mut begin, mut end) = (vec![0u32; scene.len()], vec![0u32; scene.len()]); + fn visit(scene: &[Spec], index: usize, at: &mut u32, begin: &mut [u32], end: &mut [u32]) { + begin[index] = *at; + *at += 1 + scene[index].draws; + for (child, spec) in scene.iter().enumerate() { + if spec.parent == Some(index) { visit(scene, child, at, begin, end); } + } + end[index] = *at; + *at += 1; + } + for (index, spec) in scene.iter().enumerate() { + if spec.parent.is_none() { visit(scene, index, &mut at, &mut begin, &mut end); } + } + (begin, end) +} + +/// A scene's layers, with the scopes their instance stream nests into and the walk's verdict on +/// each: a layer inside a cache the pool holds is covered, a transparent one is hidden. +fn plan_of(scene: &[Spec], held: &[Held]) -> Vec<Layer> { + let (begin, end) = marks(scene); + let mut planned = Vec::new(); + scene.iter().enumerate().map(|(index, spec)| { + let above = spec.parent.map(|p| planned[p]); + let covered = spec.parent.is_some_and(|p| scene[p].cache.is_some_and(|key| held.iter().any(|t| t.cache == Some(key)))); + planned.push(match above { + _ if spec.opacity == 0.0 => Planned::Hidden, + Some(Planned::Hidden) => Planned::Hidden, + Some(Planned::Covered) => Planned::Covered, + _ if covered => Planned::Covered, + _ => Planned::Inline, + }); + Layer { + begin: begin[index], end: end[index], parent: spec.parent, + edges: spec.edges, vis: spec.vis, clip: spec.clip, limit: NO_CLIP, + fade: [0, 0, 0, spec.fade], opacity: spec.opacity, blend: spec.blend, blur: spec.blur, + support: 0.0, cache: spec.cache, planned: planned[index], turn: spec.turn, + free: spec.turn.is_some(), frame: spec.edges, hole: spec.hole, + } + }).collect() +} + +#[derive(Clone, Copy, Debug, PartialEq)] +enum OldShow { Hidden, Covered, Inline, Render, Cached } + +/// A layer as origin/dev's `Layer` held it, with the fields its passes read and wrote. +#[derive(Clone, Copy, Debug)] +struct OldLayer { + begin: u32, end: u32, parent: Option<usize>, + edges: [f32; 4], vis: [f32; 4], rect: [f32; 4], + cache: Option<(u64, u64)>, cache_target: Option<(u64, u64)>, + opacity: f32, blend: Blend, blur: f32, fade: [u32; 4], clip: [f32; 4], + turn: Option<(f32, [f32; 2])>, hole: [f32; 4], + show: OldShow, +} + +impl From<&Layer> for OldLayer { + fn from(l: &Layer) -> Self { + Self { + begin: l.begin, end: l.end, parent: l.parent, edges: l.edges, vis: l.vis, rect: [0.0; 4], + cache: l.cache, cache_target: None, opacity: l.opacity, blend: l.blend, blur: l.blur, + fade: l.fade, clip: l.clip, turn: l.turn, hole: l.hole, + show: match l.planned { + Planned::Hidden => OldShow::Hidden, + Planned::Covered => OldShow::Covered, + Planned::Inline => OldShow::Inline, + }, + } + } +} + +/// The reference's layers: dev's instance walk opened and closed each scope where the scene's +/// stream does, and the pass's own records carry the rest. +fn old_layers(scene: &[Spec], plan: &[Layer]) -> Vec<OldLayer> { + let (begin, end) = marks(scene); + plan.iter().enumerate().map(|(index, l)| OldLayer { begin: begin[index], end: end[index], ..OldLayer::from(l) }).collect() +} + +/// Dev's blur scratch on a target: its own texture at the target's size, and the reduced work target +/// `prepare` makes once a sigma wide enough asks for one. +#[derive(Clone, Copy, Debug, PartialEq)] +struct OldScratch { work: bool } + +/// A target as dev's pools held it, and what dev's `target_bytes` counts for it. +#[derive(Clone, Copy, Debug, PartialEq)] +struct OldHeld { + size: [u32; 2], + cache: Option<(u64, u64)>, + last_used: u64, + content: [f32; 2], + blur: Option<OldScratch>, + /// The turn the composite quad was written with. + quad: Option<(f32, [f32; 2])>, +} + +impl OldHeld { + fn new(size: [u32; 2]) -> Self { + Self { size, cache: None, last_used: 0, content: [0.0; 2], blur: None, quad: None } + } + + /// The texture, and the scratch's own texture plus its work target when it has one. + fn bytes(&self) -> u64 { + let texture = u64::from(self.size[0]) * u64::from(self.size[1]) * 8; + let scratch = self.blur.map_or(0, |b| if b.work { 2 * texture } else { texture }); + texture + scratch + } + + /// What dev's `prepare` did to the scratch this frame: make one if there is none, and make the + /// work target when the sigma needs an intermediate resolution. + fn blur(&mut self, sigma: f32, content: [f32; 2]) { + let scratch = self.blur.get_or_insert(OldScratch { work: false }); + let reduction = (sigma / 3.0).clamp(1.0, 8.0); + let reduced = [content[0] / reduction, content[1] / reduction].map(f32::ceil); + if reduced != content { scratch.work = true; } + } +} + +impl From<&OldHeld> for Held { + fn from(h: &OldHeld) -> Self { + Self { size: h.size, bytes: h.bytes(), cache: h.cache, last_used: h.last_used, content: h.content } + } +} + +/// The plan reads a walk's targets where they are, as it reads a frame's. +impl Describe for OldHeld { + fn held(&self) -> Held { Held::from(self) } +} + +/// Dev's target pools, and the three passes that read them. +#[derive(Clone, Default, Debug, PartialEq)] +struct Old { retained: Vec<OldHeld>, spare: Vec<OldHeld>, slots: Vec<Option<OldHeld>> } + +impl Old { + fn park(&mut self, mut t: OldHeld) { + t.cache = None; + self.spare.push(t); + let mut bytes: u64 = self.spare.iter().map(OldHeld::bytes).sum(); + while bytes > SPARE_BYTES { + let oldest = self.spare.iter().enumerate().min_by_key(|(_, t)| t.last_used).unwrap().0; + bytes -= self.spare.swap_remove(oldest).bytes(); + } + } + + fn release(&mut self, index: usize) { + if let Some(t) = self.slots[index].take() { self.park(t); } + } + + fn trim_retained(&mut self, active_bytes: u64, budget: u64) { + let available = budget.saturating_sub(active_bytes); + let mut bytes: u64 = self.retained.iter().map(OldHeld::bytes).sum(); + while bytes > available { + let oldest = self.retained.iter().enumerate().min_by_key(|(_, t)| t.last_used).unwrap().0; + bytes -= self.retained.swap_remove(oldest).bytes(); + } + } + + fn take_spare(&mut self, width: u32, height: u32) -> Option<OldHeld> { + let fits = |t: &OldHeld| { + let size = (t.size[0], t.size[1]); + size.0 >= width && size.1 >= height && u64::from(size.0) * u64::from(size.1) <= 2 * u64::from(width.max(64)) * u64::from(height.max(64)) + }; + let at = self.spare.iter().position(fits)?; + Some(self.spare.swap_remove(at)) + } + + /// Dev's `prepare_layers`: the claim pass, the settle pass and the allocate pass as they were. + fn passes(&mut self, plan: &mut [OldLayer], isolate: bool, max_dim: u32, budget: u64, stamp: u64) { + let bpp = u64::from(FORMAT.block_copy_size(None).unwrap()); + let mut active_cache_bytes = 0u64; + // First claim resident cache hits so existing on-screen caches never thrash under a tight budget. + for index in 0..plan.len() { + let l = &mut plan[index]; + let e = l.edges; + l.rect = [e[0], e[1], (e[2] - e[0]).max(0.0), (e[3] - e[1]).max(0.0)]; + if l.rect[2] == 0.0 || l.rect[3] == 0.0 { l.show = OldShow::Hidden; } + if !isolate || l.show != OldShow::Inline { continue; } + let Some(key) = l.cache else { continue }; + let Some(pos) = self.retained.iter().position(|t| t.cache == Some(key)) else { continue }; + let t_bytes = self.retained[pos].bytes(); + let over_budget = active_cache_bytes + t_bytes > budget; + if over_budget && l.begin + 1 < l.end { continue; } + let mut t = self.retained.swap_remove(pos); + if over_budget { + t.cache = None; + } else { + t.last_used = stamp; + active_cache_bytes += t_bytes; + } + // differs from dev: dev wrote the hit's composite quad upright, so a turned cache drew + // its content where it stood on the miss and snapped back on the hit. + t.quad = l.turn; + l.show = OldShow::Cached; + l.cache_target = t.cache; + self.slots[index] = Some(t); + } + // Settle what the planning walk couldn't know at a layer's start. + for index in 0..plan.len() { + let parent = plan[index].parent.map(|p| plan[p].show); + let l = &mut plan[index]; + l.show = match (l.show, parent) { + (OldShow::Cached, _) => OldShow::Cached, + (_, Some(OldShow::Hidden)) => OldShow::Hidden, + (OldShow::Covered, Some(OldShow::Covered | OldShow::Cached)) => OldShow::Covered, + (OldShow::Covered, _) => OldShow::Inline, + (show, _) => show, + }; + } + for index in 0..plan.len() { + match plan[index].show { + OldShow::Inline => {} + OldShow::Cached | OldShow::Render => continue, + OldShow::Hidden | OldShow::Covered => { self.release(index); continue; } + } + let additive_parent = plan[index].parent.is_some_and(|p| plan[p].blend == Blend::PlusLighter); + let l = &mut plan[index]; + if !isolate { self.release(index); continue; } + let mut bounds = l.rect; + let (mut width, mut height) = (bounds[2] as u32, bounds[3] as u32); + let mut bucket = (width.div_ceil(64) * 64, height.div_ceil(64) * 64); + let mut cache_target = None; + if let Some((node_id, sig)) = l.cache { + let previous = self.retained.iter().position(|t| t.cache.is_some_and(|(n, _)| n == node_id)); + let needed_bytes = u64::from(bucket.0) * u64::from(bucket.1) * bpp; + if bucket.0 <= max_dim && bucket.1 <= max_dim && active_cache_bytes + needed_bytes <= budget { + active_cache_bytes += needed_bytes; + cache_target = Some((node_id, sig)); + if let Some(pos) = previous { + self.release(index); + self.slots[index] = Some(self.retained.swap_remove(pos)); + } else { + self.trim_retained(active_cache_bytes, budget); + } + } else { + if let Some(pos) = previous { + self.retained.swap_remove(pos); + } + let v = l.vis; + bounds = [v[0], v[1], (v[2] - v[0]).max(0.0), (v[3] - v[1]).max(0.0)]; + l.rect = bounds; + (width, height) = (bounds[2] as u32, bounds[3] as u32); + bucket = (width.div_ceil(64) * 64, height.div_ceil(64) * 64); + } + } + let l = &mut plan[index]; + if cache_target.is_none() && l.opacity == 1.0 && l.blend == Blend::SourceOver && !additive_parent + && l.blur == 0.0 && l.fade[3] == 0 && l.turn.is_none() && l.hole[3] == 0.0 + && (l.clip == NO_CLIP || (l.fade == [0; 4] && l.clip.iter().all(|v| (v - v.round()).abs() < 1e-3))) { + self.release(index); + continue; + } + l.show = OldShow::Render; + l.cache_target = cache_target; + if self.slots[index].as_ref().is_none_or(|t| { + let size = (t.size[0], t.size[1]); + size.0 < width || size.1 < height || (size != bucket + && u64::from(size.0) * u64::from(size.1) > 2 * u64::from(width) * u64::from(height)) + }) && let Some(spare) = { self.release(index); self.take_spare(width, height) } { + self.slots[index] = Some(spare); + } + if self.slots[index].is_none() { + let (width, height) = bucket; + self.slots[index] = Some(OldHeld::new([width, height])); + } + let sigma = plan[index].blur; + let bounds = plan[index].rect; + let t = self.slots[index].as_mut().unwrap(); + t.cache = cache_target; + t.last_used = stamp; + t.content = [bounds[2], bounds[3]]; + t.quad = plan[index].turn; + if sigma > 0.0 { + t.blur(sigma, [bounds[2], bounds[3]]); + } else { + t.blur = None; + } + } + self.trim_retained(active_cache_bytes, budget); + } +} + +/// `Renderer::commit`, transcribed: the moves the plan decided, in its order. +fn apply(pools: &mut Old, moves: &[Move]) { + for &m in moves { + match m { + Move::Park(slot) => { + if let Some(mut t) = pools.slots[slot].take() { t.cache = None; pools.spare.push(t); } + } + Move::Set { slot, from } => { + pools.slots[slot] = Some(match from { + Kept::Retained(at) => pools.retained.swap_remove(at), + Kept::Spare(at) => pools.spare.swap_remove(at), + }); + } + Move::Create { slot, size } => pools.slots[slot] = Some(OldHeld::new(size)), + Move::Unblur(slot) => { + if let Some(t) = pools.slots[slot].as_mut() { t.blur = None; } + } + Move::Drop(Kept::Retained(at)) => { pools.retained.swap_remove(at); } + Move::Drop(Kept::Spare(at)) => { pools.spare.swap_remove(at); } + } + } +} + +/// `Renderer::paint_layers`, transcribed: what a target learned about the frame it drew. +fn finish(pools: &mut Old, plan: &[Layer], dispositions: &[Disposition], stamp: u64) { + for (index, disposition) in dispositions.iter().enumerate() { + let Some(t) = pools.slots[index].as_mut() else { continue }; + match *disposition { + Disposition::Cached { cache, .. } => { + t.cache = cache; + if cache.is_some() { t.last_used = stamp; } + t.quad = plan[index].turn; + } + Disposition::Render { rect, cache } => { + t.cache = cache; + t.last_used = stamp; + t.content = [rect[2], rect[3]]; + t.quad = plan[index].turn; + // The plan dropped a scratch the layer no longer wants (`Move::Unblur`). + if plan[index].blur > 0.0 { t.blur(plan[index].blur, [rect[2], rect[3]]); } + } + Disposition::Skip | Disposition::Inline => {} + } + } +} + +/// One frame: the plan decides from the pools as they are, both sides, and every verdict and every +/// pool is compared. `planner` is the same one frame after frame, warm with what the last left in +/// it. Returns what the frame decided for each layer. +fn frame(planner: &mut Planner, pools: &Old, old_pools: &mut Old, scene: &[Spec], isolate: bool, budget: u64, stamp: u64) -> Vec<Disposition> { + // `prepare_layers`' prelude, in its order: a slot that still keeps a cache gives it back to the + // pool first, then the slots a shorter plan no longer has are parked, then the slots shrink. + let previous = pools.slots.len(); + let mut before = pools.clone(); + for slot in &mut before.slots { + if slot.as_ref().is_some_and(|t| t.cache.is_some()) { before.retained.push(slot.take().unwrap()); } + } + while before.slots.len() > scene.len() { + if let Some(t) = before.slots.pop().flatten() { before.park(t); } + } + before.slots.resize(scene.len(), None); + + let layers = plan_of(scene, &before.retained.iter().map(Held::from).collect::<Vec<_>>()); + old_pools.clone_from(&before); + let mut plan: Vec<OldLayer> = old_layers(scene, &layers); + old_pools.passes(&mut plan, isolate, 4096, budget, stamp); + + let mut decisions = Vec::new(); + if scene.is_empty() { + // A layerless frame plans nothing: dev's only work is the trim its passes end with. + before.trim_retained(0, budget); + } else { + let pools = Pools { slots: &before.slots, retained: &before.retained, spare: &before.spare }; + planner.decide(&layers, &pools, budget, isolate, 4096); + for (index, old) in plan.iter().enumerate() { + let got = planner.dispositions[index]; + match (old.show, got) { + (OldShow::Hidden | OldShow::Covered, Disposition::Skip) + | (OldShow::Inline, Disposition::Inline) => {} + (OldShow::Render, Disposition::Render { rect, cache }) + | (OldShow::Cached, Disposition::Cached { rect, cache }) => { + assert_eq!((rect, cache), (old.rect, old.cache_target), "layer {index} at {stamp}"); + } + (show, got) => panic!("layer {index} at {stamp}: dev says {show:?}, the plan says {got:?}"), + } + } + apply(&mut before, &planner.moves); + finish(&mut before, &layers, &planner.dispositions, stamp); + decisions = planner.dispositions.clone(); + } + assert_eq!(before, *old_pools, "the pools at {stamp}, from {:?}: {:?}", planner.moves, planner.dispositions); + // `prepare_layers`' tail: a frame whose layers fell gives the plan's scratch back. + if scene.len() < previous { planner.settle(scene.len(), before.retained.len(), before.spare.len()); } + decisions +} + +#[test] +fn every_frame_walk_matches_dev() { + let scenes = scenes(); + const TIGHT: u64 = 40_000; + // Each event is a scene the next frame draws, the budget it has, and whether layers can isolate. + let events: Vec<(usize, u64, bool)> = vec![ + (0, DEFAULT_CACHE_BUDGET, true), (1, DEFAULT_CACHE_BUDGET, true), (1, TIGHT, true), + (0, 1, true), (2, DEFAULT_CACHE_BUDGET, true), (3, DEFAULT_CACHE_BUDGET, true), + (6, TIGHT, true), (4, DEFAULT_CACHE_BUDGET, true), (5, DEFAULT_CACHE_BUDGET, true), + (0, TIGHT, true), (1, DEFAULT_CACHE_BUDGET, false), + (7, DEFAULT_CACHE_BUDGET, true), (7, 1, true), + ]; + fn walk(scenes: &[Vec<Spec>], events: &[(usize, u64, bool)], pools: &Old, planner: &Planner, stamp: u64, depth: u32) -> bool { + if depth == 0 { return false; } + let mut saw_split_budget = false; + for &(scene, budget, isolate) in events { + let (mut after, mut planner) = (Old::default(), planner.clone()); + let next = stamp + 1; + let decisions = frame(&mut planner, pools, &mut after, &scenes[scene], isolate, budget, next); + // Both siblings hit, but the budget keeps only the first for another frame. + saw_split_budget |= scene == 1 && budget == TIGHT && matches!(decisions.as_slice(), [ + Disposition::Cached { cache: Some((11, 1)), .. }, Disposition::Cached { cache: None, .. }, + ]); + saw_split_budget |= walk(scenes, events, &after, &planner, next, depth - 1); + // Nothing is left for a later frame to find: every scene closes what it opened. + assert!(after.slots.len() <= scenes[scene].len()); + } + saw_split_budget + } + // An empty scene closes the frame's layers and shows what a layerless frame does to the pools. + let empty = scenes.len(); + let mut scenes = scenes; + scenes.push(Vec::new()); + let events: Vec<(usize, u64, bool)> = events.into_iter().chain([(empty, DEFAULT_CACHE_BUDGET, true)]).collect(); + assert!(walk(&scenes, &events, &Old::default(), &Planner::default(), 0, 5), + "the tight budget never kept one sibling cache while borrowing the other"); +} + +/// What dev's `target_bytes` counts for a kept target: its own texture, plus the blur scratch's +/// texture and the reduced work target a wide sigma adds at the same size. +#[test] +fn a_kept_target_costs_its_texture_and_its_blur() { + let (mut direct, mut reduced) = (OldHeld::new([64, 64]), OldHeld::new([64, 64])); + direct.blur(1.0, [64.0, 64.0]); + reduced.blur(12.0, [64.0, 64.0]); + assert_eq!(direct.bytes(), 65_536, "64×64 at eight bytes, and a direct scratch beside it"); + assert_eq!(reduced.bytes(), 98_304, "and the work target a wide sigma adds"); +} + +/// A cache whose layers close keeps its texture for the next frame of its node: dev gave every slot +/// that still kept a cache back to the pool *before* it shrank the slots, so a menu that closes and +/// opens again makes no texture. +#[test] +fn a_closed_cache_is_still_kept_when_its_layers_come_back() { + let scenes = scenes(); + let (mut pools, mut after, mut planner) = (Old::default(), Old::default(), Planner::default()); + frame(&mut planner, &pools, &mut after, &scenes[0], true, DEFAULT_CACHE_BUDGET, 1); + std::mem::swap(&mut pools, &mut after); + frame(&mut planner, &pools, &mut after, &[], true, DEFAULT_CACHE_BUDGET, 2); + std::mem::swap(&mut pools, &mut after); + assert!(pools.retained.iter().any(|t| t.cache == Some((7, 1))), "a closed cache is kept for its node"); + let decisions = frame(&mut planner, &pools, &mut after, &scenes[0], true, DEFAULT_CACHE_BUDGET, 3); + assert!(matches!(decisions[0], Disposition::Cached { .. }), "the frame that closes and opens again hits it"); +} + +/// The plan reads a pool in place until it first moves a target, and after that through its own +/// order: every sequence of parks and takes, from pools of every small size, leaves the places +/// where `Vec::push` and `Vec::swap_remove` would, which is what `commit` replays on the pool. +#[test] +fn a_pool_view_moves_its_targets_as_a_vec_does() { + fn walk(view: &View, model: &[Source], fresh: usize, depth: u32) { + assert_eq!(view.len, model.len()); + for (place, &source) in model.iter().enumerate() { assert_eq!(view.source(place), source, "{model:?}"); } + if depth == 0 { return; } + let (mut parked, mut pushed) = (view.clone(), model.to_vec()); + parked.push(Source::Slot(fresh)); + pushed.push(Source::Slot(fresh)); + walk(&parked, &pushed, fresh + 1, depth - 1); + for at in 0..model.len() { + let (mut view, mut model) = (view.clone(), model.to_vec()); + assert_eq!(view.swap_remove(at), model.swap_remove(at)); + walk(&view, &model, fresh + 1, depth - 1); + } + } + for len in 0..4 { + let mut view = View::new(Source::Spare); + view.reset(len); + let model: Vec<Source> = (0..len).map(Source::Spare).collect(); + walk(&view, &model, 0, 6); + } +} + +/// A cached leaf that draws something can't be made again cheaply, so over budget dev let its kept +/// texture go rather than borrow it; a leaf that draws nothing borrows it. Neither has a child layer. +#[test] +fn a_cached_leaf_with_a_draw_keeps_its_place_under_the_budget() { + let scenes = scenes(); + let (mut pools, mut after, mut planner) = (Old::default(), Old::default(), Planner::default()); + frame(&mut planner, &pools, &mut after, &scenes[7], true, DEFAULT_CACHE_BUDGET, 1); + std::mem::swap(&mut pools, &mut after); + let (begin, end) = marks(&scenes[7]); + assert_eq!((end[0] - begin[0], end[1] - begin[1]), (2, 1), "the first leaf draws a rect, the second nothing"); + let decisions = frame(&mut planner, &pools, &mut after, &scenes[7], true, 1, 2); + assert_eq!(decisions[0], Disposition::Inline, "the leaf with a draw draws again, straight into the window"); + assert!(!after.retained.iter().chain(after.slots.iter().flatten()).any(|t| t.cache == Some((11, 1))), "and its texture goes"); + assert!(matches!(decisions[1], Disposition::Cached { cache: None, .. }), "the empty leaf borrows its texture: {decisions:?}"); +} diff --git a/app/vendor/rune/crates/rune/src/render/metallib.rs b/app/vendor/rune/crates/rune/src/render/metallib.rs new file mode 100644 index 0000000..030ea33 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/render/metallib.rs @@ -0,0 +1,498 @@ +//! Precompiled Metal library (`.metallib`) for Rune's uber shader on macOS. +//! +//! `wgpu` 30's Metal backend otherwise translates `shader.wgsl` through Naga to MSL and calls +//! `[MTLDevice newLibraryWithSource:options:error:]` on the XPC `MTLCompilerService` during +//! `Renderer::new`. Loading precompiled AIR bytecode via `Device::create_shader_module_passthrough` +//! skips WGSL parsing, validation, MSL codegen, and the Metal front-end compile on every launch. +//! +//! On wgpu's backend, other shaders stay on WGSL (Rune's own backend precompiles them too, in +//! `gpu/metal/builtin.rs`): +//! - `Renderer::with_springs`, `rune-fx`, and `rune-light` bind runtime-sized `var<storage>` +//! arrays (`_mslBufferSizes`), and `wgpu-hal` 30's `ShaderModuleSource::Passthrough` leaves +//! `CompiledShader::sized_bindings` empty. +//! - `layer_blur` specializes WGSL `override` constants (`MODE`, `ADDITIVE`) per pipeline, which +//! `ShaderModuleSource::Passthrough` does not evaluate. +//! - iOS (`target_os = "ios"`) uses a distinct `MTLB` platform tag (`ios` vs `ios-simulator` vs +//! `macos`) and stays on WGSL for now. +//! +//! Note on `MTLBinaryArchive`: `wgpu-hal` 30's Metal `PipelineCache` implementation is a no-op, so +//! precompiling `.metallib` eliminates front-end MSL->AIR compilation while the final AIR->GPU ISA +//! step in `newRenderPipelineStateWithDescriptor` remains cached by the macOS Metal shader cache. +//! Supporting `MTLBinaryArchive` without forking `wgpu` would require `wgpu-hal` to wire +//! `MTLRenderPipelineDescriptor.binaryArchives` through `RenderPipelineDescriptor::cache`. +//! +//! Rune's own Metal backend (`metal-backend`) loads `uber_native.metallib` instead: the MSL that +//! backend emits (vertex descriptors rather than wgpu-hal's vertex pulling), in MSL 3.0. + +include!("uber/metallib_hash.rs"); + +#[cfg(any(test, target_os = "macos"))] +const UBER_METALLIB: &[u8] = include_bytes!("../shaders/uber.metallib"); +#[cfg(all(target_os = "macos", feature = "metal-backend"))] +const UBER_NATIVE_METALLIB: &[u8] = include_bytes!("../shaders/uber_native.metallib"); + +pub(super) const UBER_VERTEX_ATTRS: [wgpu::VertexAttribute; 8] = wgpu::vertex_attr_array![ + 0 => Float32x4, 1 => Float32x4, 2 => Float32x4, 3 => Float32x4, + 4 => Float32x4, 5 => Float32x4, 6 => Float32x4, 7 => Uint32x4 +]; + +#[cfg(all(test, target_os = "macos"))] +pub(super) const METAL_COMPILE_FLAGS: &str = + "-std=macos-metal2.3 -mmacosx-version-min=11.0 -fpreserve-invariance -Wno-unused-const-variable -O2"; + +/// Rune's Metal backend picks MSL 3.0 or later, so needs macOS 13. +#[cfg(all(test, target_os = "macos", feature = "metal-backend"))] +pub(super) const NATIVE_METAL_COMPILE_FLAGS: &str = + "-std=metal3.0 -mmacosx-version-min=13.0 -fpreserve-invariance -Wno-unused-const-variable -O2"; +#[cfg(all(test, target_os = "macos", feature = "metal-backend"))] +const NATIVE_MSL_VERSION: (u8, u8) = (3, 0); + +#[cfg(target_os = "macos")] +std::thread_local! { + static FORCE_METALLIB: std::cell::Cell<Option<bool>> = const { std::cell::Cell::new(None) }; + static METALLIB_LOADS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) }; +} + +/// clip.wgsl and shader.wgsl, joined when Rune builds (render/uber_wgsl.rs). +pub(super) fn uber_wgsl() -> &'static str { + super::uber_wgsl::CLASSIC +} + +#[cfg(test)] +pub(super) fn uber_wgsl_hash(wgsl: &str) -> blake3::Hash { + blake3::hash(wgsl.as_bytes()) +} + +pub(super) const fn uber_bind_entries() -> [wgpu::BindGroupLayoutEntry; 4] { + let uniform = wgpu::BindingType::Buffer { + ty: wgpu::BufferBindingType::Uniform, + has_dynamic_offset: false, + min_binding_size: None, + }; + let texture = wgpu::BindingType::Texture { + sample_type: wgpu::TextureSampleType::Float { filterable: false }, + view_dimension: wgpu::TextureViewDimension::D2, + multisampled: false, + }; + [ + wgpu::BindGroupLayoutEntry { binding: 0, visibility: wgpu::ShaderStages::VERTEX_FRAGMENT, ty: uniform, count: None }, + wgpu::BindGroupLayoutEntry { binding: 1, visibility: wgpu::ShaderStages::FRAGMENT, ty: texture, count: None }, + wgpu::BindGroupLayoutEntry { binding: 2, visibility: wgpu::ShaderStages::FRAGMENT, ty: texture, count: None }, + wgpu::BindGroupLayoutEntry { binding: 3, visibility: wgpu::ShaderStages::VERTEX_FRAGMENT, ty: uniform, count: None }, + ] +} + +pub(super) fn uber_pipeline_layout<'a>(layouts: &'a [Option<&'a wgpu::BindGroupLayout>; 2], springs: bool) -> wgpu::PipelineLayoutDescriptor<'a> { + wgpu::PipelineLayoutDescriptor { + label: None, + bind_group_layouts: &layouts[..if springs { 2 } else { 1 }], + immediate_size: 0, + } +} + +pub(super) const fn uber_vertex_layout() -> wgpu::VertexBufferLayout<'static> { + wgpu::VertexBufferLayout { + array_stride: std::mem::size_of::<super::Instance>() as u64, + step_mode: wgpu::VertexStepMode::Instance, + attributes: &UBER_VERTEX_ATTRS, + } +} + +pub(super) const fn uber_primitive() -> wgpu::PrimitiveState { + wgpu::PrimitiveState { + topology: wgpu::PrimitiveTopology::TriangleStrip, + strip_index_format: None, + front_face: wgpu::FrontFace::Ccw, + cull_mode: None, + unclipped_depth: false, + polygon_mode: wgpu::PolygonMode::Fill, + conservative: false, + } +} + +// Descriptor values shared with Renderer::create, not their source spelling or labels. +// WGSL, generated MSL, and the actual Naga options have separate fingerprints below. +#[cfg(any(test, target_os = "macos"))] +pub(super) const fn uber_abi_hash() -> u64 { + layout_hash(&uber_bind_entries(), &uber_vertex_layout(), uber_primitive()) +} + +/// [`uber_abi_hash`] for another set of uber bindings (the Windfoil variant's). +#[cfg(any(test, target_os = "macos", target_os = "windows"))] +pub(super) const fn abi_hash_of(entries: &[wgpu::BindGroupLayoutEntry]) -> u64 { + layout_hash(entries, &uber_vertex_layout(), uber_primitive()) +} + +#[cfg(any(test, target_os = "macos", target_os = "windows"))] +const fn layout_hash(entries: &[wgpu::BindGroupLayoutEntry], vertex: &wgpu::VertexBufferLayout<'_>, primitive: wgpu::PrimitiveState) -> u64 { + // The normal uber pipeline has one group and no immediates; the springs pipeline has a + // second group and never uses the precompiled shaders. + descriptor_hash(entries, vertex, primitive, 1, 0) +} + +/// FNV-1a of every value of the bindings, vertex layout, primitive state, group count and +/// immediate size that decides what a precompiled uber shader binds. A `const fn`: the build +/// knows the layout's hash, so a launch compares nothing. Destructured whole, so a field wgpu +/// adds doesn't compile until it's hashed too. +#[cfg(any(test, target_os = "macos", target_os = "windows"))] +const fn descriptor_hash(entries: &[wgpu::BindGroupLayoutEntry], vertex: &wgpu::VertexBufferLayout<'_>, primitive: wgpu::PrimitiveState, groups: usize, immediate_size: u32) -> u64 { + let mut h = Fnv(0xcbf29ce484222325).word(entries.len() as u64); + let mut i = 0; + while i < entries.len() { + let wgpu::BindGroupLayoutEntry { binding, visibility, ty, count } = entries[i]; + h = h.word(binding as u64).word(visibility.bits() as u64).word(match count { Some(n) => n.get() as u64, None => 0 }); + h = match ty { + wgpu::BindingType::Buffer { ty, has_dynamic_offset, min_binding_size } => h.word(1) + .word(match ty { wgpu::BufferBindingType::Uniform => 0, wgpu::BufferBindingType::Storage { read_only } => 1 + read_only as u64 }) + .word(has_dynamic_offset as u64).word(match min_binding_size { Some(n) => n.get(), None => 0 }), + wgpu::BindingType::Texture { sample_type, view_dimension, multisampled } => h.word(2) + .word(match sample_type { + wgpu::TextureSampleType::Float { filterable } => filterable as u64, + wgpu::TextureSampleType::Depth => 2, + wgpu::TextureSampleType::Sint => 3, + wgpu::TextureSampleType::Uint => 4, + }) + .word(view_dimension as u64).word(multisampled as u64), + _ => panic!("audit a new uber binding type before precompiling a shader for it"), + }; + i += 1; + } + let wgpu::VertexBufferLayout { array_stride, step_mode, attributes } = *vertex; + h = h.word(array_stride).word(step_mode as u64).word(attributes.len() as u64); + let mut i = 0; + while i < attributes.len() { + let wgpu::VertexAttribute { format, offset, shader_location } = attributes[i]; + h = h.word(format as u64).word(offset).word(shader_location as u64); + i += 1; + } + let wgpu::PrimitiveState { topology, strip_index_format, front_face, cull_mode, unclipped_depth, polygon_mode, conservative } = primitive; + h.word(topology as u64).word(match strip_index_format { Some(f) => 1 + f as u64, None => 0 }).word(front_face as u64) + .word(match cull_mode { Some(f) => 1 + f as u64, None => 0 }).word(unclipped_depth as u64).word(polygon_mode as u64) + .word(conservative as u64).word(groups as u64).word(immediate_size as u64).0 +} + +/// FNV-1a, a word at a time, for constants. +#[cfg(any(test, target_os = "macos", target_os = "windows"))] +struct Fnv(u64); + +#[cfg(any(test, target_os = "macos", target_os = "windows"))] +impl Fnv { + const fn word(self, value: u64) -> Fnv { + let (mut h, mut i) = (self.0, 0); + while i < 8 { + h = (h ^ ((value >> (8 * i)) & 0xff)).wrapping_mul(0x100000001b3); + i += 1; + } + Fnv(h) + } +} + +#[cfg(test)] +fn fnv1a64(bytes: &[u8]) -> u64 { + let mut h = 0xcbf29ce484222325u64; + for &b in bytes { + h = (h ^ u64::from(b)).wrapping_mul(0x100000001b3); + } + h +} + +fn wgsl_shader(device: &wgpu::Device, wgsl: &str) -> wgpu::ShaderModule { + device.create_shader_module(wgpu::ShaderModuleDescriptor { + label: Some("uber"), + source: wgpu::ShaderSource::Wgsl(wgsl.into()), + }) +} + +pub(super) fn uber_shader_and_pipeline( + device: &wgpu::Device, + mut make_pipeline: impl FnMut(&super::dxbc::Shaders) -> wgpu::RenderPipeline, +) -> (super::dxbc::Shaders, wgpu::RenderPipeline) { + #[cfg(target_os = "macos")] + if metallib_enabled() + && let Some((shader, pipeline)) = try_uber_metallib(device, uber_metallib(device), UBER_WGSL_BLAKE3, |shader| make_pipeline(&super::dxbc::Shaders::one(shader.clone()))) + { + METALLIB_LOADS.with(|n| n.set(n.get() + 1)); + return (super::dxbc::Shaders::one(shader), pipeline); + } + // Windows ships bytecode for Windfoil alone (render/dxbc.rs): Classic compiles its WGSL there. + let shaders = super::dxbc::Shaders::one(wgsl_shader(device, uber_wgsl())); + let pipeline = make_pipeline(&shaders); + (shaders, pipeline) +} + +#[cfg(target_os = "macos")] +pub(super) fn metallib_enabled() -> bool { + if let Some(forced) = FORCE_METALLIB.with(std::cell::Cell::get) { + return forced; + } + !rune_core::env::flag("RUNE_DISABLE_METALLIB") +} + +#[cfg(all(test, target_os = "macos"))] +pub(super) fn thread_loads() -> usize { + METALLIB_LOADS.with(std::cell::Cell::get) +} + +/// Whether `device` is Rune's own Metal backend's. +#[cfg(target_os = "macos")] +fn native(device: &wgpu::Device) -> bool { + #[cfg(feature = "metal-backend")] + { crate::gpu::metal::raw_device(device).is_some() } + #[cfg(not(feature = "metal-backend"))] + { let _ = device; false } +} + +/// The library built for `device`'s backend. +#[cfg(target_os = "macos")] +fn uber_metallib(device: &wgpu::Device) -> &'static [u8] { + #[cfg(feature = "metal-backend")] + if native(device) { return UBER_NATIVE_METALLIB; } + #[cfg(not(feature = "metal-backend"))] + let _ = device; + UBER_METALLIB +} + +/// Whether the libraries were built for this build's uber layout. +#[cfg(target_os = "macos")] +const ABI_MATCHES: bool = uber_abi_hash() == UBER_ABI_FNV64; + +#[cfg(target_os = "macos")] +#[allow(unsafe_code)] +fn try_uber_metallib<T>( + device: &wgpu::Device, + metallib: &[u8], + expected_wgsl_hash: &str, + make_pipeline: impl FnOnce(&wgpu::ShaderModule) -> T, +) -> Option<(wgpu::ShaderModule, T)> { + // Rune's backend takes a metallib without the feature, which promises arbitrary passthrough. + if !native(device) && !device.features().contains(wgpu::Features::PASSTHROUGH_SHADERS) { + return None; + } + if metallib != uber_metallib(device) || !ABI_MATCHES { + return None; + } + // The build hashed the WGSL it joined (render/uber_wgsl.rs), so nothing is hashed here. + if !super::uber_wgsl::same(super::uber_wgsl::CLASSIC_BLAKE3, expected_wgsl_hash) { + return None; + } + let validation_scope = device.push_error_scope(wgpu::ErrorFilter::Validation); + let internal_scope = device.push_error_scope(wgpu::ErrorFilter::Internal); + // SAFETY: only our embedded macOS library is accepted, never caller-provided shader code. + // Its validated Naga MSL retains bounds checks and loop bounding; the ABI fingerprint above + // covers the renderer's bindings, immediates and vertex/primitive layout. Freshness tests + // cover the generator's actual MSL/options; pixel equivalence guards backend patch updates. + // Vertex pulling uses buffer(30), and Metal supplies its sizes even for passthrough. + // No storage/workgroup arrays or specialization constants are used (HAL cannot reflect those + // from passthrough). Unsupported OS/GPU libraries and pipeline linkage failures are caught + // before any draw. Pixel equivalence and regeneration tests check the committed artifact. + let shader = unsafe { + device.create_shader_module_passthrough(wgpu::ShaderModuleDescriptorPassthrough { + label: Some("uber"), + entry_points: std::borrow::Cow::Borrowed(&[ + wgpu::PassthroughShaderEntryPoint { + name: std::borrow::Cow::Borrowed("vs"), + workgroup_size: (0, 0, 0), + }, + wgpu::PassthroughShaderEntryPoint { + name: std::borrow::Cow::Borrowed("fs"), + workgroup_size: (0, 0, 0), + }, + ]), + metallib: Some(std::borrow::Cow::Borrowed(metallib)), + ..Default::default() + }) + }; + // Rune's backend reports no errors to scopes, so check it loaded and has both functions. + #[cfg(feature = "metal-backend")] + if native(device) && !crate::gpu::metal::module_ready(&shader) { + let _ = (pollster::block_on(internal_scope.pop()), pollster::block_on(validation_scope.pop())); + return None; + } + // Metal may load the library but reject an entry point or its AIR at pipeline creation. + // Keep both scopes active through that operation, before retaining the shader for later use. + let pipeline = make_pipeline(&shader); + let internal_err = pollster::block_on(internal_scope.pop()); + let validation_err = pollster::block_on(validation_scope.pop()); + if internal_err.is_some() || validation_err.is_some() { + return None; + } + Some((shader, pipeline)) +} + +#[cfg(all(test, target_os = "macos"))] +pub(super) fn with_metallib_enabled<R>(enabled: bool, f: impl FnOnce() -> R) -> R { + struct Guard(Option<bool>); + impl Drop for Guard { + fn drop(&mut self) { + FORCE_METALLIB.with(|c| c.set(self.0)); + } + } + let prev = FORCE_METALLIB.with(|c| c.replace(Some(enabled))); + let _guard = Guard(prev); + f() +} + +/// Translates `uber_wgsl()` to MSL for the `vs` and `fs` entry points with the exact resource +/// bindings, vertex-pulling transform (`buffer(30)`), and runtime check policies that `wgpu-hal` +/// uses on Metal for `Renderer::new`. +#[cfg(all(test, target_os = "macos"))] +fn uber_msl(wgsl_src: &str, attrs: &[wgpu::VertexAttribute], stride: u32) -> (String, String, u64) { + uber_msl_with(wgsl_src, &uber_bind_entries(), attrs, stride) +} + +/// [`uber_msl`] for another uber variant's bindings (render/variant.rs). +#[cfg(all(test, target_os = "macos"))] +fn uber_msl_with(wgsl_src: &str, bind_entries: &[wgpu::BindGroupLayoutEntry], attrs: &[wgpu::VertexAttribute], stride: u32) -> (String, String, u64) { + use wgpu::naga::{ + self, + back::{msl, pipeline_constants::process_overrides}, + front::wgsl, + proc::{BoundsCheckPolicies, BoundsCheckPolicy}, + valid::{Capabilities, SubgroupOperationSet, ValidationFlags, Validator}, + }; + + let module = wgsl::parse_str(wgsl_src).expect("parse uber WGSL"); + let info = Validator::new( + ValidationFlags::all(), + Capabilities::default() | Capabilities::SHADER_FLOAT16_IN_FLOAT32, + ) + .subgroup_stages(naga::valid::ShaderStages::all()) + .subgroup_operations(SubgroupOperationSet::all()) + .validate(&module) + .expect("validate uber WGSL"); + + // Follow HAL's per-stage allocation, using the renderer's actual entries. Fail closed if + // the shader gains storage/arrays: passthrough cannot provide their sized-binding metadata. + let resources = |stage: wgpu::ShaderStages| { + let groups = [None, None]; + let layout = uber_pipeline_layout(&groups, false); + assert_eq!(layout.immediate_size, 0, "audit Metal immediate-data mapping before precompiling"); + let mut result = msl::EntryPointResources::default(); + let (mut buffer, mut texture) = (0, 0); + let mut entries = bind_entries.to_vec(); + entries.sort_by_key(|entry| entry.binding); + for entry in entries { + if !entry.visibility.contains(stage) { continue; } + assert!(entry.count.is_none(), "passthrough binding arrays need an audit"); + let mut target = msl::BindTarget::default(); + match entry.ty { + wgpu::BindingType::Buffer { ty: wgpu::BufferBindingType::Uniform, .. } => { + target.buffer = Some(buffer); + buffer += 1; + } + wgpu::BindingType::Texture { .. } => { + target.texture = Some(texture); + texture += 1; + } + _ => panic!("audit new uber binding type before precompiling"), + } + result.resources.insert(naga::ResourceBinding { group: 0, binding: entry.binding }, target); + } + if stage == wgpu::ShaderStages::VERTEX { result.sizes_buffer = Some(buffer); } + result + }; + let vs_resources = resources(wgpu::ShaderStages::VERTEX); + let fs_resources = resources(wgpu::ShaderStages::FRAGMENT); + + let attributes = attrs + .iter() + .map(|attr| msl::AttributeMapping { + shader_location: attr.shader_location, + offset: attr.offset as u32, + format: attr.format, + }) + .collect(); + let vbm = msl::VertexBufferMapping { + id: 30, + stride, + step_mode: match uber_vertex_layout().step_mode { + wgpu::VertexStepMode::Instance => msl::VertexBufferStepMode::ByInstance, + wgpu::VertexStepMode::Vertex => msl::VertexBufferStepMode::ByVertex, + }, + attributes, + }; + + let limits = wgpu::Limits::default(); + let translate = |stage: naga::ShaderStage, + ep: &str, + resources: msl::EntryPointResources, + vertex_buffer_mappings: Vec<msl::VertexBufferMapping>| { + let (ep_module, ep_info) = + process_overrides(&module, &info, Some((stage, ep)), &Default::default()) + .expect("process overrides"); + let options = msl::Options { + lang_version: (2, 3), + inline_samplers: Default::default(), + spirv_cross_compatibility: false, + fake_missing_bindings: false, + per_entry_point_map: msl::EntryPointResourceMap::from([(ep.to_owned(), resources)]), + bounds_check_policies: BoundsCheckPolicies { + index: BoundsCheckPolicy::Restrict, + buffer: BoundsCheckPolicy::Restrict, + image_load: BoundsCheckPolicy::Restrict, + binding_array: BoundsCheckPolicy::Unchecked, + }, + zero_initialize_workgroup_memory: true, + force_loop_bounding: true, + task_dispatch_limits: Some(naga::back::TaskDispatchLimits { + max_mesh_workgroups_per_dim: limits.max_mesh_workgroups_per_dimension, + max_mesh_workgroups_total: limits.max_mesh_workgroup_total_count, + }), + mesh_shader_primitive_indices_clamp: true, + emit_int_div_checks: true, + ray_query_initialization_tracking: true, + }; + let pipeline_options = msl::PipelineOptions { + entry_point: Some((stage, ep.to_owned())), + allow_and_force_point_size: uber_primitive().topology == wgpu::PrimitiveTopology::PointList, + vertex_pulling_transform: true, + vertex_buffer_mappings, + binding_array_length_map: Default::default(), + }; + let (msl, translation_info) = + msl::write_string(&ep_module, &ep_info, &options, &pipeline_options) + .expect("translate uber WGSL to MSL"); + assert_eq!( + translation_info.entry_point_names[0].as_deref(), + Ok(ep), + "MSL entry point name must match WGSL entry point" + ); + // Resource maps are ordered; the binding-array map is empty (arrays rejected above). + (msl, format!("{options:?}\n{pipeline_options:?}")) + }; + + let (vs_msl, vs_options) = translate(naga::ShaderStage::Vertex, "vs", vs_resources, vec![vbm]); + let (fs_msl, fs_options) = translate(naga::ShaderStage::Fragment, "fs", fs_resources, Vec::new()); + (vs_msl, fs_msl, fnv1a64(format!("{vs_options}\n{fs_options}").as_bytes())) +} + +#[cfg(all(test, target_os = "macos"))] +fn uber_msl_hash(vs_msl: &str, fs_msl: &str) -> blake3::Hash { + let mut hasher = blake3::Hasher::new(); + hasher.update(METAL_COMPILE_FLAGS.as_bytes()); + hasher.update(&[0]); + hasher.update(vs_msl.as_bytes()); + hasher.update(&[0]); + hasher.update(fs_msl.as_bytes()); + hasher.finalize() +} + +/// The MSL Rune's Metal backend compiles the uber shader to, which `uber_native.metallib` holds. +#[cfg(all(test, target_os = "macos", feature = "metal-backend"))] +fn native_uber_msl(wgsl: &str) -> [String; 2] { + crate::gpu::metal::render_msl(wgsl, &uber_bind_entries(), NATIVE_MSL_VERSION) +} + +#[cfg(all(test, target_os = "macos", feature = "metal-backend"))] +fn native_uber_msl_hash([vs, fs]: &[String; 2]) -> blake3::Hash { + let mut hasher = blake3::Hasher::new(); + for part in [NATIVE_METAL_COMPILE_FLAGS, vs, fs] { + hasher.update(part.as_bytes()); + hasher.update(&[0]); + } + hasher.finalize() +} + +#[cfg(test)] +#[path = "metallib_tests.rs"] +mod tests; diff --git a/app/vendor/rune/crates/rune/src/render/metallib_tests.rs b/app/vendor/rune/crates/rune/src/render/metallib_tests.rs new file mode 100644 index 0000000..dd70bc8 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/render/metallib_tests.rs @@ -0,0 +1,461 @@ +use super::*; + +/// Called by `scripts/precompile-metal-shaders.sh` (`--ignored --exact --nocapture`) to emit +/// the Naga-translated MSL and BLAKE3 digests for the current `shader.wgsl` + `clip.wgsl`. +#[cfg(target_os = "macos")] +#[test] +#[ignore] +fn dump_uber_msl() { + let wgsl = uber_wgsl(); + let wgsl_hash = uber_wgsl_hash(&wgsl); + let (vs_msl, fs_msl, options_hash) = + uber_msl(&wgsl, &UBER_VERTEX_ATTRS, std::mem::size_of::<super::super::Instance>() as u32); + let msl_hash = uber_msl_hash(&vs_msl, &fs_msl); + println!("---BEGIN_WGSL_BLAKE3---\n{}\n---END_WGSL_BLAKE3---", wgsl_hash.to_hex()); + println!("---BEGIN_MSL_BLAKE3---\n{}\n---END_MSL_BLAKE3---", msl_hash.to_hex()); + println!("---BEGIN_METAL_FLAGS---\n{METAL_COMPILE_FLAGS}\n---END_METAL_FLAGS---"); + println!("---BEGIN_ABI_FNV64---\n{:016x}\n---END_ABI_FNV64---", uber_abi_hash()); + println!("---BEGIN_OPTIONS_FNV64---\n{options_hash:016x}\n---END_OPTIONS_FNV64---"); + println!("---BEGIN_VS_MSL---\n{vs_msl}---END_VS_MSL---"); + println!("---BEGIN_FS_MSL---\n{fs_msl}---END_FS_MSL---"); + #[cfg(feature = "metal-backend")] + { + let native = native_uber_msl(&wgsl); + println!("---BEGIN_NATIVE_MSL_BLAKE3---\n{}\n---END_NATIVE_MSL_BLAKE3---", native_uber_msl_hash(&native).to_hex()); + println!("---BEGIN_NATIVE_METAL_FLAGS---\n{NATIVE_METAL_COMPILE_FLAGS}\n---END_NATIVE_METAL_FLAGS---"); + println!("---BEGIN_NATIVE_VS_MSL---\n{}---END_NATIVE_VS_MSL---", native[0]); + println!("---BEGIN_NATIVE_FS_MSL---\n{}---END_NATIVE_FS_MSL---", native[1]); + } + // The Windfoil variant (render/variant.rs), for uber_windfoil{,_native}.metallib. + let windfoil = super::super::variant::windfoil_wgsl(); + let entries = super::super::variant::windfoil_bind_entries(); + let (vs_msl, fs_msl, _) = uber_msl_with(&windfoil, &entries, &UBER_VERTEX_ATTRS, std::mem::size_of::<super::super::Instance>() as u32); + println!("---BEGIN_WINDFOIL_WGSL_BLAKE3---\n{}\n---END_WINDFOIL_WGSL_BLAKE3---", uber_wgsl_hash(&windfoil).to_hex()); + println!("---BEGIN_WINDFOIL_ABI_FNV64---\n{:016x}\n---END_WINDFOIL_ABI_FNV64---", super::super::variant::windfoil_abi_hash()); + println!("---BEGIN_WINDFOIL_VS_MSL---\n{vs_msl}---END_WINDFOIL_VS_MSL---"); + println!("---BEGIN_WINDFOIL_FS_MSL---\n{fs_msl}---END_WINDFOIL_FS_MSL---"); + #[cfg(feature = "metal-backend")] + { + let native = crate::gpu::metal::render_msl(&windfoil, &entries, NATIVE_MSL_VERSION); + println!("---BEGIN_WINDFOIL_NATIVE_VS_MSL---\n{}---END_WINDFOIL_NATIVE_VS_MSL---", native[0]); + println!("---BEGIN_WINDFOIL_NATIVE_FS_MSL---\n{}---END_WINDFOIL_NATIVE_FS_MSL---", native[1]); + } +} + +#[test] +fn precompiled_uber_metallib_is_fresh() { + let wgsl = uber_wgsl(); + #[cfg(not(target_os = "macos"))] + assert_eq!( + uber_wgsl_hash(&wgsl).to_hex().as_str(), + UBER_WGSL_BLAKE3, + "WGSL changed; run this freshness test on macOS to check whether MSL needs regeneration" + ); + assert!( + UBER_METALLIB.starts_with(b"MTLB") && UBER_METALLIB.len() > 1024, + "uber.metallib must be a valid Metal library binary" + ); + assert_eq!( + fnv1a64(UBER_METALLIB), + UBER_METALLIB_FNV64, + "crates/rune/src/shaders/uber.metallib does not match recorded hash; run scripts/precompile-metal-shaders.sh" + ); + + #[cfg(target_os = "macos")] + { + let stride = std::mem::size_of::<super::super::Instance>() as u32; + let (vs_msl, fs_msl, options_hash) = uber_msl(&wgsl, &UBER_VERTEX_ATTRS, stride); + assert_eq!( + uber_msl_hash(&vs_msl, &fs_msl).to_hex().as_str(), + UBER_MSL_BLAKE3, + "generated MSL or Metal compile flags changed; run scripts/precompile-metal-shaders.sh" + ); + + let wgsl_hash = uber_wgsl_hash(&wgsl).to_hex().to_string(); + assert!(uber_abi_hash() == UBER_ABI_FNV64 + && options_hash == UBER_MSL_OPTIONS_FNV64 + && wgsl_hash == UBER_WGSL_BLAKE3, + "MSL is byte-identical; no Xcode or metallib regeneration needed. Paste these lines into crates/rune/src/render/uber/metallib_hash.rs:\n\ +pub(super) const UBER_ABI_FNV64: u64 = 0x{:016x};\n\ +pub(super) const UBER_MSL_OPTIONS_FNV64: u64 = 0x{options_hash:016x};\n\ +pub(super) const UBER_WGSL_BLAKE3: &str = \"{wgsl_hash}\";", uber_abi_hash()); + + // Perturbing WGSL or vertex layout must change the hash so staleness cannot hide. + let mut altered_wgsl = wgsl.to_owned(); + altered_wgsl.push_str("\n// perturbed\n"); + assert_ne!(uber_wgsl_hash(&altered_wgsl).to_hex().as_str(), UBER_WGSL_BLAKE3); + + let (vs_stride_changed, _, changed_options) = uber_msl(&wgsl, &UBER_VERTEX_ATTRS, stride + 16); + assert_ne!(changed_options, options_hash); + assert_ne!( + uber_msl_hash(&vs_stride_changed, &fs_msl).to_hex().as_str(), + UBER_MSL_BLAKE3 + ); + } + #[cfg(all(target_os = "macos", feature = "metal-backend"))] + { + assert!(UBER_NATIVE_METALLIB.starts_with(b"MTLB") && UBER_NATIVE_METALLIB.len() > 1024); + assert_eq!(fnv1a64(UBER_NATIVE_METALLIB), UBER_NATIVE_METALLIB_FNV64, + "crates/rune/src/shaders/uber_native.metallib does not match recorded hash; run scripts/precompile-metal-shaders.sh"); + assert_eq!(native_uber_msl_hash(&native_uber_msl(&wgsl)).to_hex().as_str(), UBER_NATIVE_MSL_BLAKE3, + "the Metal backend's MSL or its compile flags changed; run scripts/precompile-metal-shaders.sh"); + } + #[cfg(not(target_os = "macos"))] + assert_eq!(uber_abi_hash(), UBER_ABI_FNV64, + "descriptor fingerprint changed; run this test on macOS for exact replacement hash lines (no Xcode if MSL is unchanged)"); +} + +#[test] +fn semantic_fingerprint_tracks_descriptors_not_source_text() { + let entries = uber_bind_entries(); + let vertex = uber_vertex_layout(); + let primitive = uber_primitive(); + let baseline = layout_hash(&entries, &vertex, primitive); + let mut changed = entries; + changed[0].visibility = wgpu::ShaderStages::VERTEX; + assert_ne!(layout_hash(&changed, &vertex, primitive), baseline); + changed = entries; + changed[0].binding = 4; + assert_ne!(layout_hash(&changed, &vertex, primitive), baseline); + let mut changed_vertex = uber_vertex_layout(); + changed_vertex.array_stride += 16; + assert_ne!(layout_hash(&entries, &changed_vertex, primitive), baseline); + changed_vertex = uber_vertex_layout(); + changed_vertex.step_mode = wgpu::VertexStepMode::Vertex; + assert_ne!(layout_hash(&entries, &changed_vertex, primitive), baseline); + let mut attrs = UBER_VERTEX_ATTRS; + attrs[0].offset += 4; + changed_vertex = uber_vertex_layout(); + changed_vertex.attributes = &attrs; + assert_ne!(layout_hash(&entries, &changed_vertex, primitive), baseline); + let mut changed_primitive = primitive; + changed_primitive.strip_index_format = Some(wgpu::IndexFormat::Uint32); + assert_ne!(layout_hash(&entries, &vertex, changed_primitive), baseline); + changed_primitive = primitive; + changed_primitive.topology = wgpu::PrimitiveTopology::TriangleList; + assert_ne!(layout_hash(&entries, &vertex, changed_primitive), baseline); + let groups = [None, None]; + let mut layout = uber_pipeline_layout(&groups, false); + layout.immediate_size = 16; + assert_ne!(descriptor_hash(&entries, &vertex, primitive, layout.bind_group_layouts.len(), layout.immediate_size), baseline); + let layout = uber_pipeline_layout(&groups, true); + assert_ne!(descriptor_hash(&entries, &vertex, primitive, layout.bind_group_layouts.len(), layout.immediate_size), baseline); + // Labels, comments, and unrelated Rust source are deliberately not inputs. + assert_eq!(layout_hash(&entries, &vertex, primitive), baseline); + #[cfg(target_os = "macos")] + { + let wgsl = uber_wgsl(); + let stride = vertex.array_stride as u32; + let original = uber_msl(&wgsl, vertex.attributes, stride); + let comment_only = uber_msl(&format!("{wgsl}\n// unrelated comment\n"), vertex.attributes, stride); + assert_eq!(original, comment_only, "comment edits must not require a Metal compiler"); + } +} + +#[cfg(target_os = "macos")] +#[test] +fn uber_shader_loads_precompiled_metallib_and_falls_back_cleanly() { + use super::super::{Gpu, OFFSCREEN_FORMAT, Renderer}; + + let gpu = Gpu::headless_wgpu(); + assert!( + gpu.device.features().contains(wgpu::Features::PASSTHROUGH_SHADERS), + "Metal device must enable PASSTHROUGH_SHADERS" + ); + + let before = METALLIB_LOADS.with(std::cell::Cell::get); + let _r_on = with_metallib_enabled(true, || Renderer::new(&gpu.device, OFFSCREEN_FORMAT)); + let after_on = METALLIB_LOADS.with(std::cell::Cell::get); + assert_eq!(after_on, before + 1, "Renderer::new must load precompiled uber.metallib on macOS"); + + let _r_off = with_metallib_enabled(false, || Renderer::new(&gpu.device, OFFSCREEN_FORMAT)); + let after_off = METALLIB_LOADS.with(std::cell::Cell::get); + assert_eq!(after_off, after_on, "disabled metallib must fall back to WGSL"); + + assert!( + try_uber_metallib(&gpu.device, UBER_METALLIB, "stale-hash", |_| ()).is_none(), + "hash mismatch must fall back" + ); + assert!( + try_uber_metallib(&gpu.device, b"not-mtlb", UBER_WGSL_BLAKE3, |_| ()).is_none(), + "missing MTLB magic must fall back" + ); + assert!( + try_uber_metallib(&gpu.device, b"MTLBcorrupt-payload", UBER_WGSL_BLAKE3, |_| ()).is_none(), + "foreign or corrupt metallib must be rejected before passing bytes to the driver" + ); + + // Device created without PASSTHROUGH_SHADERS must fall back cleanly to WGSL. + let (no_pt_device, _no_pt_queue) = pollster::block_on(gpu.adapter.request_device( + &wgpu::DeviceDescriptor { + label: Some("no-passthrough"), + required_features: wgpu::Features::empty(), + required_limits: wgpu::Limits::default(), + experimental_features: Default::default(), + memory_hints: wgpu::MemoryHints::Performance, + trace: Default::default(), + }, + )) + .expect("device without passthrough"); + assert!( + try_uber_metallib(&no_pt_device, UBER_METALLIB, UBER_WGSL_BLAKE3, |_| ()).is_none(), + "device without PASSTHROUGH_SHADERS must fall back" + ); + let _r_fallback = Renderer::new(&no_pt_device, OFFSCREEN_FORMAT); +} + +#[cfg(all(target_os = "macos", feature = "metal-backend"))] +#[test] +#[allow(unsafe_code)] +fn native_backend_loads_its_metallib_and_falls_back_cleanly() { + use super::super::{Gpu, OFFSCREEN_FORMAT, Renderer}; + + let gpu = Gpu::new(crate::gpu::metal::instance(), None); + let before = METALLIB_LOADS.with(std::cell::Cell::get); + let _on = with_metallib_enabled(true, || Renderer::new(&gpu.device, OFFSCREEN_FORMAT)); + assert_eq!(METALLIB_LOADS.with(std::cell::Cell::get), before + 1, "Renderer::new must load uber_native.metallib"); + + assert!(try_uber_metallib(&gpu.device, UBER_METALLIB, UBER_WGSL_BLAKE3, |_| ()).is_none(), + "wgpu-hal's vertex-pulling library must not load on Rune's backend"); + let module = |bytes: &'static [u8], names: &'static [&'static str]| { + let entry_points: Vec<_> = names.iter() + .map(|n| wgpu::PassthroughShaderEntryPoint { name: std::borrow::Cow::Borrowed(*n), workgroup_size: (0, 0, 0) }) + .collect(); + // SAFETY: the backend only hands the bytes to Metal, which checks them. + let module = unsafe { + gpu.device.create_shader_module_passthrough(wgpu::ShaderModuleDescriptorPassthrough { + entry_points: entry_points.into(), + metallib: Some(std::borrow::Cow::Borrowed(bytes)), + ..Default::default() + }) + }; + crate::gpu::metal::module_ready(&module) + }; + assert!(module(UBER_NATIVE_METALLIB, &["vs", "fs"])); + assert!(!module(UBER_NATIVE_METALLIB, &["vs", "missing"]), "a missing function must fall back"); + assert!(!module(b"MTLBcorrupt-payload", &["vs", "fs"]), "a library Metal refuses must fall back"); +} + +#[cfg(target_os = "macos")] +#[test] +fn pipeline_linkage_failure_retries_wgsl_without_uncaptured_error() { + use super::super::{Blend, Gpu, OFFSCREEN_FORMAT, Renderer}; + + let gpu = Gpu::headless_wgpu(); + let renderer = with_metallib_enabled(false, || Renderer::new(&gpu.device, OFFSCREEN_FORMAT)); + let before = METALLIB_LOADS.with(std::cell::Cell::get); + let mut attempts = 0; + let (_shader, _pipeline) = with_metallib_enabled(true, || { + uber_shader_and_pipeline(&gpu.device, |shader| { + attempts += 1; + // Loading the library succeeds; resolving this function fails in HAL's + // load_shader at pipeline creation. The default uncaptured handler panics + // if the pipeline is outside the fallback's error scopes. + let entry = if attempts == 1 { "missing_vertex_entry" } else { "vs" }; + Renderer::pipeline(&gpu.device, &renderer.layout, shader, OFFSCREEN_FORMAT, + entry, Blend::SourceOver) + }) + }); + assert_eq!(attempts, 2, "a loaded library can still fail at pipeline creation"); + assert_eq!(METALLIB_LOADS.with(std::cell::Cell::get), before, + "a failed pipeline must not retain the passthrough shader"); +} + +/// The precompiled uber shader (a metallib on macOS, DXBC on Windows) and WGSL draw the same pixels. +#[cfg(any(target_os = "macos", target_os = "windows"))] +#[test] +fn metallib_and_wgsl_render_identical_pixels() { + #[cfg(target_os = "macos")] + use super::with_metallib_enabled as with_precompiled; + #[cfg(target_os = "windows")] + use super::super::dxbc::with_dxbc_enabled as with_precompiled; + use super::super::{ + Blend, Gpu, Instance, KIND_GLYPH, KIND_GRADIENT, KIND_IMAGE, KIND_INSET, KIND_RECT, + KIND_SEGMENT, KIND_SHADOW, KIND_TRIANGLE, LayerSpec, NO_CLIP, OFFSCREEN_FORMAT, + Offscreen, Renderer, pack_fade, + }; + use crate::{ + pixels::ImageAtlas, + text::{ATLAS_SIZE, TextSystem}, + }; + use bytemuck::Zeroable; + + let gpu = Gpu::headless_wgpu(); + #[cfg(all(target_os = "macos", feature = "metal-backend"))] + let native = Gpu::new(crate::gpu::metal::instance(), None); + let (width, height) = (160u32, 120u32); + + let render_scene = |gpu: &Gpu, use_metallib: bool, format: wgpu::TextureFormat, srgb_blend: bool| { + with_precompiled(use_metallib, || { + let mut renderer = Renderer::new(&gpu.device, format); + renderer.set_srgb_blend(srgb_blend); + + let mut text = TextSystem::default(); + text.atlas.data.resize((ATLAS_SIZE * ATLAS_SIZE) as usize, 0); + for y in 0..16u32 { + for x in 0..16u32 { + text.atlas.data[(y * ATLAS_SIZE + x) as usize] = + ((x * 15 + y * 9) & 0xff) as u8; + } + } + text.atlas.dirty = Some((0, 16)); + + let mut images = ImageAtlas::default(); + let px = crate::pixels::Pixels::new(); + px.set( + 4, + 4, + (0..16) + .flat_map(|i| [200u8, (i * 12) as u8, 90, 255]) + .collect(), + ); + let placed = images.place(&px, [24.0, 24.0]).expect("place test pixels"); + renderer.upload_images(&gpu.device, &gpu.queue, &mut images); + + let mut instances = vec![ + // Rounded rect with border + Instance { + rect: [8.0, 8.0, 44.0, 32.0], + radii: [8.0, 8.0, 8.0, 8.0], + fill: [0.2, 0.45, 0.85, 1.0], + border: [0.9, 0.95, 1.0, 1.0], + params: [2.0, KIND_RECT, 0.0, 0.0], + clip: NO_CLIP, + ..Instance::zeroed() + }, + // Continuous-corner rect (negative radii) with edge fade + Instance { + rect: [60.0, 8.0, 44.0, 32.0], + radii: [-10.0; 4], + fill: [0.85, 0.3, 0.4, 0.9], + params: [0.0, KIND_RECT, 0.0, 0.0], + clip: [58.0, 6.0, 106.0, 42.0], + fade: pack_fade([6.0, 6.0, 6.0, 6.0], [58.0, 6.0, 106.0, 42.0], [58.0, 6.0, 106.0, 42.0]), + ..Instance::zeroed() + }, + // Drop shadow + inset shadow + Instance { + rect: [112.0, 10.0, 36.0, 28.0], + radii: [6.0; 4], + fill: [0.0, 0.0, 0.0, 0.55], + params: [0.0, KIND_SHADOW, 6.0, 0.0], + clip: NO_CLIP, + ..Instance::zeroed() + }, + Instance { + rect: [112.0, 10.0, 36.0, 28.0], + radii: [6.0; 4], + fill: [0.1, 0.1, 0.15, 0.5], + params: [2.0, KIND_INSET, 4.0, 0.0], + uv: [1.0, 2.0, 0.0, 0.0], + clip: NO_CLIP, + ..Instance::zeroed() + }, + // Vertical gradient + Instance { + rect: [8.0, 48.0, 44.0, 30.0], + radii: [6.0; 4], + fill: [0.15, 0.7, 0.55, 1.0], + border: [0.8, 0.8, 0.2, 1.0], + params: [1.5, KIND_GRADIENT, 0.0, 0.0], + uv: [0.05, 0.2, 0.35, 1.0], + clip: NO_CLIP, + ..Instance::zeroed() + }, + // Stroke segment (round caps) + triangle + Instance { + rect: [56.0, 48.0, 48.0, 30.0], + radii: [60.0, 52.0, 100.0, 74.0], + fill: [0.95, 0.6, 0.2, 1.0], + params: [2.5, KIND_SEGMENT, 1.0, 0.0], + clip: NO_CLIP, + ..Instance::zeroed() + }, + Instance { + rect: [108.0, 48.0, 44.0, 30.0], + radii: [112.0, 74.0, 130.0, 50.0], + fill: [0.6, 0.35, 0.9, 0.95], + params: [7.0, KIND_TRIANGLE, 0.0, 0.0], + uv: [148.0, 74.0, 0.0, 0.0], + clip: NO_CLIP, + ..Instance::zeroed() + }, + // Glyph + image + Instance { + rect: [12.0, 86.0, 16.0, 16.0], + fill: [1.0, 1.0, 1.0, 1.0], + params: [0.0, KIND_GLYPH, 0.0, 1.45], + uv: [0.0, 0.0, 16.0, 16.0], + clip: NO_CLIP, + ..Instance::zeroed() + }, + Instance { + rect: [36.0, 84.0, 24.0, 24.0], + radii: [4.0; 4], + fill: [0.0, 0.0, 0.0, 0.9], + params: [placed.page as f32, KIND_IMAGE, 0.0, 0.0], + uv: placed.rect.map(|v| v as f32), + clip: NO_CLIP, + ..Instance::zeroed() + }, + ]; + + // Isolated layer with PlusLighter blend and rounded clip + instances.push(Instance::begin_layer( + [70.0, 82.0, 76.0, 30.0], + [70.0, 82.0, 146.0, 112.0], + LayerSpec { + opacity: 0.8, + blend: Blend::PlusLighter, + blur: 0.0, + clip_radius: 6.0, + }, + )); + instances.push(Instance { + rect: [74.0, 86.0, 40.0, 22.0], + radii: [5.0; 4], + fill: [0.3, 0.5, 0.7, 0.85], + params: [0.0, KIND_RECT, 0.0, 0.0], + clip: NO_CLIP, + ..Instance::zeroed() + }); + instances.push(Instance { + rect: [96.0, 86.0, 40.0, 22.0], + radii: [5.0; 4], + fill: [0.7, 0.3, 0.4, 0.85], + params: [0.0, KIND_RECT, 0.0, 0.0], + clip: NO_CLIP, + ..Instance::zeroed() + }); + instances.push(Instance::end_layer()); + + renderer.prepare(&gpu.device, &gpu.queue, &mut text.atlas, &instances, (width, height)); + let target = Offscreen::with_format(&gpu.device, width, height, format); + let mut encoder = gpu.device.create_command_encoder(&Default::default()); + renderer.draw(&mut encoder, &target.view, [0.08, 0.09, 0.12, 1.0]); + target.copy(&mut encoder); + renderer.submit(&gpu.queue, encoder); + target.read(&gpu.device) + }) + }; + + for (format, srgb_blend) in [ + (OFFSCREEN_FORMAT, false), + (wgpu::TextureFormat::Bgra8UnormSrgb, false), + (wgpu::TextureFormat::Rgba8Unorm, true), + ] { + let metallib_pixels = render_scene(&gpu, true, format, srgb_blend); + let wgsl_pixels = render_scene(&gpu, false, format, srgb_blend); + assert_eq!( + metallib_pixels, wgsl_pixels, + "metallib and WGSL pixel output differed for format={format:?} srgb_blend={srgb_blend}" + ); + #[cfg(all(target_os = "macos", feature = "metal-backend"))] + for use_metallib in [true, false] { + assert!( + render_scene(&native, use_metallib, format, srgb_blend) == wgsl_pixels, + "Rune's Metal backend and wgpu's differed for format={format:?} srgb_blend={srgb_blend} metallib={use_metallib}" + ); + } + } +} diff --git a/app/vendor/rune/crates/rune/src/render/native_surface_tests.rs b/app/vendor/rune/crates/rune/src/render/native_surface_tests.rs new file mode 100644 index 0000000..4bd0d0a --- /dev/null +++ b/app/vendor/rune/crates/rune/src/render/native_surface_tests.rs @@ -0,0 +1,264 @@ +use std::sync::Arc; + +use crate::el::{Align, El, el}; +use crate::native_surface::place::SurfacePlace; +use crate::native_surface::{ByteFrame, ColorInfo, Format, NativeSurface, SurfaceFit}; +use crate::render::{Gpu, OFFSCREEN_FORMAT, Offscreen, Renderer}; +use crate::runtime::{Cx, Env, Runtime}; + +const TOP_LEFT_1X: SurfacePlace = SurfacePlace { anchor: [Align::Start; 2], unscaled: true }; + +macro_rules! on_each_backend { + ($wgpu:ident, $metal:ident, $body:ident) => { + #[test] + fn $wgpu() { + $body(Gpu::headless_wgpu()); + } + #[cfg(all(target_vendor = "apple", feature = "metal-backend"))] + #[test] + fn $metal() { + $body(Gpu::new(crate::gpu::metal::instance(), None)); + } + }; +} + +#[test] +fn the_element_carries_its_placement_to_the_draw() { + type State = (NativeSurface, bool); + fn view(s: &State, _: &mut Cx<State>) -> El { + let e = el().size(80.0, 60.0).native_surface(&s.0, SurfaceFit::Fill); + if s.1 { e.surface_anchor(Align::Start, Align::Start).surface_unscaled(true) } else { e } + } + let surface = NativeSurface::new(); + surface + .push_bytes( + ByteFrame { width: 4, height: 2, format: Format::Bgra, color: ColorInfo::default(), planes: [vec![0; 32], vec![]] }, + 1, + ) + .unwrap(); + for (anchored, want) in [(false, SurfacePlace::CENTRED), (true, TOP_LEFT_1X)] { + let mut rt = Runtime::new((surface.clone(), anchored), view, (80.0, 60.0), Env::new(true, 1.0)); + rt.frame(0.0); + assert_eq!(rt.surfaces.len(), 1); + assert_eq!(rt.surfaces[0].surface.place(), want); + assert_eq!(rt.surfaces[0].surface.key(), surface.key(), "same frames"); + } +} + +on_each_backend!( + video_interleaves_with_renderer_springs_and_external_timing, + video_interleaves_with_renderer_springs_and_external_timing_on_metal, + video_interleaves_with_renderer_springs_and_external_timing_on +); +fn video_interleaves_with_renderer_springs_and_external_timing_on(gpu: Gpu) { + let surface = NativeSurface::new(); + surface + .push_bytes( + ByteFrame { + width: 16, + height: 8, + format: Format::Bgra, + color: ColorInfo::default(), + planes: [vec![255; 16 * 8 * 4], vec![]], + }, + 1001, + ) + .unwrap(); + + fn view(s: &NativeSurface, _: &mut Cx<NativeSurface>) -> El { + el() + .w(8.0) + .h(4.0) + .fill(crate::Color::BLACK) + .native_surface(s, SurfaceFit::Fit) + .border(1.0, crate::Color::BLACK) + // 3x3 pt (6x6 px at 2x) puts the probed pixel (3, 3) clear of both the 2 px border + // and the child's outer anti-aliasing boundary. + .child(el().w(3.0).h(3.0).fill(crate::Color::BLACK)) + } + let mut rt = Runtime::new(surface.clone(), view, (8.0, 4.0), Env::new(true, 2.0)); + rt.frame(0.0); + assert_eq!(rt.surfaces[0].rect, [0.0, 0.0, 16.0, 8.0]); + let mut renderer = Renderer::new(&gpu.device, OFFSCREEN_FORMAT); + renderer.prepare(&gpu.device, &gpu.queue, &mut rt.text.atlas, &rt.instances, (16, 8)); + renderer.prepare_surfaces(&gpu.device, &gpu.queue, &rt.surfaces, (16, 8)); + let target = Offscreen::new(&gpu.device, 16, 8); + let mut encoder = gpu.device.create_command_encoder(&Default::default()); + renderer.draw(&mut encoder, &target.view, [0.0; 4]); + target.copy(&mut encoder); + renderer.submit(&gpu.queue, encoder); + let p = target.read(&gpu.device); + assert_eq!(&p[0..4], &[0, 0, 0, 255], "border must paint over video"); + assert_eq!(&p[(3 * 16 + 3) * 4..(3 * 16 + 3) * 4 + 4], &[0, 0, 0, 255], "child must paint over video"); + assert_eq!(&p[(4 * 16 + 10) * 4..(4 * 16 + 10) * 4 + 4], &[255; 4], "video must paint over background"); + + // A video pipeline switch must also restore the retained-springs bind group before + // painting the border and child. Identity tracks should exactly match ordinary rendering. + let zero = crate::gpu::springs::Track::constant(0.0); + let node = crate::gpu::springs::Node { x: zero, y: zero, opacity: crate::gpu::springs::Track::constant(1.0) }; + let mut sprung = Renderer::with_springs(&gpu.device, OFFSCREEN_FORMAT, &[node], &vec![0; rt.instances.len()]); + sprung.prepare(&gpu.device, &gpu.queue, &mut rt.text.atlas, &rt.instances, (16, 8)); + sprung.prepare_surfaces(&gpu.device, &gpu.queue, &rt.surfaces, (16, 8)); + let mut encoder = gpu.device.create_command_encoder(&Default::default()); + sprung.draw(&mut encoder, &target.view, [0.0; 4]); + target.copy(&mut encoder); + sprung.submit(&gpu.queue, encoder); + assert_eq!(target.read(&gpu.device), p, "retained-springs binding must survive the video draw"); + + // A custom compositor can omit video. Preparing it alone must not report a submission. + let submitted = surface.counts().0; + renderer.prepare_surfaces(&gpu.device, &gpu.queue, &rt.surfaces, (16, 8)); + renderer.submit(&gpu.queue, gpu.device.create_command_encoder(&Default::default())); + assert_eq!(surface.counts().0, submitted, "undrawn video must not report submission"); + + // External pass timing takes precedence without resolving NativeSurface's unwritten + // query set. Frame completion still arrives, with no native GPU timestamps. + if gpu.device.features().contains(wgpu::Features::TIMESTAMP_QUERY) { + let external = gpu.device.create_query_set(&wgpu::QuerySetDescriptor { + label: Some("external UI timing"), + ty: wgpu::QueryType::Timestamp, + count: 2, + }); + let (done, completion) = std::sync::mpsc::channel(); + surface.set_observer(Arc::new(move |t| { + if t.completed_at.is_some() { + done.send(t).ok(); + } + })); + renderer.prepare_surfaces(&gpu.device, &gpu.queue, &rt.surfaces, (16, 8)); + let mut encoder = gpu.device.create_command_encoder(&Default::default()); + renderer.draw_timed( + &mut encoder, + &target.view, + [0.0; 4], + Some(wgpu::RenderPassTimestampWrites { + query_set: &external, + beginning_of_pass_write_index: Some(0), + end_of_pass_write_index: Some(1), + }), + ); + renderer.submit(&gpu.queue, encoder); + // The preceding render's callback may still arrive; consume until this submission. + let submission = surface.timing().unwrap().submitted_at; + loop { + let t = completion.recv_timeout(std::time::Duration::from_secs(10)).expect("externally timed frame completion"); + if t.submitted_at != submission { + continue; + } + assert_eq!(t.gpu_start_seconds, None); + assert_eq!(t.gpu_end_seconds, None); + break; + } + } +} + +#[test] +fn video_continuous_corners_match_uber_shader() { + use crate::render::{Instance, KIND_RECT, NO_CLIP, pack_clip_radii}; + + let gpu = Gpu::headless(); + let (w, h) = (96u32, 80u32); + let surface = NativeSurface::new(); + surface + .push_bytes( + ByteFrame { + width: 80, + height: 64, + format: Format::Bgra, + color: ColorInfo::default(), + planes: [vec![255; 80 * 64 * 4], vec![]], + }, + 1, + ) + .unwrap(); + + let cases: [(&str, [f32; 4], [f32; 4], [f32; 4], Option<[f32; 4]>); 3] = [ + ("uniform-continuous", [8.0, 8.0, 80.0, 64.0], [-20.0; 4], NO_CLIP, None), + ("mixed-continuous", [8.0, 8.0, 80.0, 64.0], [-20.0, 12.0, -10.0, 0.0], NO_CLIP, None), + ( + "continuous-clip", + [8.0, 8.0, 80.0, 64.0], + [0.0; 4], + [12.0, 12.0, 84.0, 68.0], + Some([-16.0, -10.0, -16.0, 0.0]), + ), + ]; + + for (name, box_rect, radii, clip, clip_radii) in cases { + let mut fade = [0u32; 4]; + if let Some(cr) = clip_radii { + fade[3] = pack_clip_radii(clip, cr); + } + + // Reference: uber shader (`shader.wgsl`) solid white KIND_RECT with the same geometry. + let inst = Instance { + rect: box_rect, + radii, + fill: [1.0; 4], + border: [0.0; 4], + params: [0.0, KIND_RECT, 0.0, 1.0], + uv: [0.0; 4], + clip, + fade, + }; + let mut atlas = crate::text::Atlas::new(); + let mut uber = Renderer::new(&gpu.device, OFFSCREEN_FORMAT); + uber.prepare(&gpu.device, &gpu.queue, &mut atlas, &[inst], (w, h)); + let uber_target = Offscreen::new(&gpu.device, w, h); + let mut enc = gpu.device.create_command_encoder(&Default::default()); + uber.draw(&mut enc, &uber_target.view, [0.0; 4]); + uber_target.copy(&mut enc); + uber.submit(&gpu.queue, enc); + let uber_px = uber_target.read(&gpu.device); + + // Video shader (`video.wgsl`) with a solid white frame and the exact same rect/radii/clip/fade. + let draw = crate::native_surface::SurfaceDraw { + surface: surface.clone(), + fit: SurfaceFit::Fill, + before_instance: 0, + rect: box_rect, + radii, + clip, + fade, + opacity: 1.0, + }; + let mut video = Renderer::new(&gpu.device, OFFSCREEN_FORMAT); + video.prepare(&gpu.device, &gpu.queue, &mut atlas, &[], (w, h)); + video.prepare_surfaces(&gpu.device, &gpu.queue, &[draw], (w, h)); + let video_target = Offscreen::new(&gpu.device, w, h); + let mut enc = gpu.device.create_command_encoder(&Default::default()); + video.draw(&mut enc, &video_target.view, [0.0; 4]); + video_target.copy(&mut enc); + video.submit(&gpu.queue, enc); + let video_px = video_target.read(&gpu.device); + + let mut max_diff = 0u8; + let mut worst = None; + let (x0, y0, x1, y1) = ( + box_rect[0] as u32, + box_rect[1] as u32, + (box_rect[0] + box_rect[2]) as u32, + (box_rect[1] + box_rect[3]) as u32, + ); + for y in 0..h { + for x in 0..w { + let i = ((y * w + x) * 4) as usize; + let u = [uber_px[i], uber_px[i + 1], uber_px[i + 2], uber_px[i + 3]]; + let v = [video_px[i], video_px[i + 1], video_px[i + 2], video_px[i + 3]]; + if x < x0 || x >= x1 || y < y0 || y >= y1 { + assert_eq!(v, [0, 0, 0, 0], "{name}: video drew outside its rect at ({x},{y}): {v:?}"); + continue; + } + let d = (0..4).map(|k| u[k].abs_diff(v[k])).max().unwrap(); + if d > max_diff { + max_diff = d; + worst = Some((x, y, u, v)); + } + } + } + assert!( + max_diff <= 1, + "{name}: video.wgsl drifted from shader.wgsl: max_diff={max_diff} worst={worst:?}" + ); + } +} diff --git a/app/vendor/rune/crates/rune/src/render/offscreen.rs b/app/vendor/rune/crates/rune/src/render/offscreen.rs new file mode 100644 index 0000000..f7dde94 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/render/offscreen.rs @@ -0,0 +1,70 @@ +//! Offscreen render targets with CPU readback and PNG writing. + +/// An offscreen sRGB target with CPU readback. +pub struct Offscreen { + texture: wgpu::Texture, + pub view: wgpu::TextureView, + readback: rune_staging::Readback, + pub width: u32, + pub height: u32, +} + +pub const OFFSCREEN_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Rgba8UnormSrgb; + +impl Offscreen { + pub fn new(device: &wgpu::Device, width: u32, height: u32) -> Offscreen { + Self::with_format(device, width, height, OFFSCREEN_FORMAT) + } + + pub fn with_format(device: &wgpu::Device, width: u32, height: u32, format: wgpu::TextureFormat) -> Offscreen { + let texture = device.create_texture(&wgpu::TextureDescriptor { + label: Some("offscreen"), + size: wgpu::Extent3d { width, height, depth_or_array_layers: 1 }, + mip_level_count: 1, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + format, + usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC, + view_formats: &[], + }); + let view = texture.create_view(&Default::default()); + let readback = rune_staging::Readback::new(device, "readback", width, height, 4); + Offscreen { texture, view, readback, width, height } + } + + pub fn copy(&self, encoder: &mut wgpu::CommandEncoder) { + self.readback.copy_from(encoder, &self.texture); + } + + /// Underlying offscreen texture, for readback rings (`tooling::record`). + pub(crate) fn texture(&self) -> &wgpu::Texture { &self.texture } + + /// Tightly packed sRGB RGBA8 after `copy` was submitted. + #[cfg(not(target_arch = "wasm32"))] + pub fn read(&self, device: &wgpu::Device) -> Vec<u8> { + // A callback never panics: one that did while a failed wait unwinds (wgpu aborts the map + // then) would abort the process. A failed map shows as `take_mapped`'s panic. + self.readback.buffer().slice(..).map_async(wgpu::MapMode::Read, |_| {}); + rune_gpu::health::poll(device, wgpu::PollType::wait_indefinitely()).expect("poll"); + self.readback.take_mapped() + } + + #[cfg(target_arch = "wasm32")] + pub fn read(&self, _: &wgpu::Device) -> Vec<u8> { + panic!("blocking GPU readback is unsupported on web") + } +} + +pub fn write_png(path: &std::path::Path, width: u32, height: u32, rgba: &[u8]) -> std::io::Result<()> { + if let Some(dir) = path.parent() { + std::fs::create_dir_all(dir)?; + } + let file = std::io::BufWriter::new(std::fs::File::create(path)?); + let mut enc = png::Encoder::new(file, width, height); + enc.set_color(png::ColorType::Rgba); + enc.set_depth(png::BitDepth::Eight); + enc.set_source_srgb(png::SrgbRenderingIntent::Perceptual); + let mut w = enc.write_header().map_err(std::io::Error::other)?; + w.write_image_data(rgba).map_err(std::io::Error::other)?; + Ok(()) +} diff --git a/app/vendor/rune/crates/rune/src/render/outlines.rs b/app/vendor/rune/crates/rune/src/render/outlines.rs new file mode 100644 index 0000000..8f15032 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/render/outlines.rs @@ -0,0 +1,51 @@ +//! The outline store's texture (`text::OutlineStore`, binding 4 of the Windfoil shader): its +//! changed rows go up with each frame's uploads, and when the store outgrows it a taller one +//! replaces it and every bind group is made again. + +use rune_staging::Staging; + +use super::*; + +/// Rows the texture starts with (256 KB). +pub(super) const MIN_ROWS: u32 = 16; + +impl Renderer { + pub(super) fn outline_texture(device: &wgpu::Device, rows: u32) -> wgpu::Texture { + Self::texture(device, "glyph outlines", wgpu::TextureFormat::Rgba32Uint, crate::text::outline::WIDTH, rows) + } + + /// Hands text's new outline records to the GPU, growing the texture first if they don't fit. + pub(super) fn upload_outlines(&mut self, device: &wgpu::Device, staging: &Staging, atlas: &mut Atlas) { + let store = &mut atlas.outlines; + let variant::Uber::Windfoil { outlines, .. } = &mut self.uber else { return }; + if store.rows() > outlines.height() { + *outlines = Self::outline_texture(device, store.rows().next_power_of_two()); + store.invalidate(); + self.rebind_all(device); + } + let variant::Uber::Windfoil { outlines, .. } = &self.uber else { return }; + if let Some((y, rows)) = store.take_dirty() { + staging.write_texture_rows(outlines, y, rows); + } + } + + /// Every bind group again, for a new shader or outline texture. + pub(super) fn rebind_all(&mut self, device: &wgpu::Device) { + let outlines = self.uber.outlines(); + self.bind_group = Self::bind_group(device, &self.bind_layout, &self.globals, outlines, &self.atlas, &self.stand_in, None); + for page in 0..self.atlas_pages.len() { + let texture = &self.atlas_pages[page].0; + let bind = Self::bind_group(device, &self.bind_layout, &self.globals, outlines, texture, texture, None); + self.atlas_pages[page].1 = bind; + } + for page in 0..self.images.len() { + let Some((texture, _)) = &self.images[page] else { continue }; + let bind = Self::bind_group(device, &self.bind_layout, &self.globals, outlines, &self.atlas, texture, None); + if let Some(slot) = &mut self.images[page] { slot.1 = bind; } + } + self.rebind_layers(device); + if let variant::Uber::Windfoil { outlines, fill, .. } = &mut self.uber { + fill.rebind(device, fill::FillBindings { layout: &self.bind_layout, globals: &self.globals, outlines, stand_in: &self.stand_in }); + } + } +} diff --git a/app/vendor/rune/crates/rune/src/render/pass.rs b/app/vendor/rune/crates/rune/src/render/pass.rs new file mode 100644 index 0000000..9e50eeb --- /dev/null +++ b/app/vendor/rune/crates/rune/src/render/pass.rs @@ -0,0 +1,292 @@ +//! The frame pass a renderer records into, and how it splits at a backdrop slot: the pass +//! ends, its target is copied into a pooled texture, and a new pass re-opens with `LoadOp::Load`. +use super::*; + +pub(super) struct Backdrop { + pub(super) format: wgpu::TextureFormat, + pub(super) texture: wgpu::Texture, + pub(super) view: wgpu::TextureView, +} + +/// The pass a frame records into. Only a pass the renderer opened itself can end mid-frame +/// (`split`): the caller's own `draw_range` pass has no encoder to copy its target and re-open it. +pub(super) enum ActivePass<'a, 'p> { + /// A pass the caller opened and will end: it carries no encoder. + Borrowed { + pass: &'a mut wgpu::RenderPass<'p>, + /// The scissor a scope set (`None`: the whole target), restored after a nested scope. + scissor: Option<[u32; 4]>, + /// What every scissor stays inside: the part of the target a frame redraws + /// (`Renderer::draw_damaged`). + bound: Option<[u32; 4]>, + }, + /// A pass this renderer opened along with its encoder and target. + Owned(OpenPass<'a, 'p>), + /// Held only between `split` ending the pass and re-opening it, while the encoder copies the + /// target and runs the hook. + Parked, +} + +/// An owned pass, with everything a re-opened pass restores. +pub(super) struct OpenPass<'a, 'p> { + pass: wgpu::RenderPass<'p>, + encoder: &'a mut wgpu::CommandEncoder, + view: &'a wgpu::TextureView, + /// The scissor a scope set (`None`: the whole target), restored when the pass re-opens. + scissor: Option<[u32; 4]>, + /// The frame pass's timestamp writes: a re-opened pass writes the end index again. + timestamps: Option<wgpu::RenderPassTimestampWrites<'a>>, +} + +impl<'a, 'p> ActivePass<'a, 'p> { + pub(super) fn borrowed(pass: &'a mut wgpu::RenderPass<'p>) -> Self { + ActivePass::Borrowed { pass, scissor: None, bound: None } + } + + /// A caller's pass whose scissors all stay inside `bound` (`[x, y, width, height]`). + pub(super) fn borrowed_within(pass: &'a mut wgpu::RenderPass<'p>, bound: [u32; 4]) -> Self { + ActivePass::Borrowed { pass, scissor: None, bound: Some(bound) } + } + + pub(super) fn owned( + pass: wgpu::RenderPass<'p>, + encoder: &'a mut wgpu::CommandEncoder, + view: &'a wgpu::TextureView, + ) -> Self { + Self::owned_timed(pass, encoder, view, None) + } + + pub(super) fn owned_timed( + pass: wgpu::RenderPass<'p>, + encoder: &'a mut wgpu::CommandEncoder, + view: &'a wgpu::TextureView, + timestamps: Option<wgpu::RenderPassTimestampWrites<'a>>, + ) -> Self { + ActivePass::Owned(OpenPass { pass, encoder, view, scissor: None, timestamps }) + } + + /// Sets the scissor to `rect` (`[x, y, width, height]`), or to the whole `size` target. + pub(super) fn set_scissor(&mut self, rect: Option<[u32; 4]>, size: [u32; 2]) { + let bound = match self { + ActivePass::Borrowed { scissor, bound, .. } => { *scissor = rect; *bound } + ActivePass::Owned(owned) => { owned.scissor = rect; None } + ActivePass::Parked => None, + }; + let [x, y, w, h] = rect.unwrap_or([0, 0, size[0], size[1]]); + let [x, y, w, h] = match bound { + Some([bx, by, bw, bh]) => { + let (x0, y0) = (x.max(bx), y.max(by)); + let (x1, y1) = ((x + w).min(bx + bw).max(x0), (y + h).min(by + bh).max(y0)); + [x0, y0, x1 - x0, y1 - y0] + } + None => [x, y, w, h], + }; + self.set_scissor_rect(x, y, w, h); + } + + pub(super) fn scissor(&self) -> Option<[u32; 4]> { + match self { + ActivePass::Borrowed { scissor, .. } => *scissor, + ActivePass::Owned(owned) => owned.scissor, + ActivePass::Parked => None, + } + } + + /// Whether this pass has an encoder and a target that can be copied, so `split` can end it. + fn splittable(&self) -> bool { + match self { + ActivePass::Owned(owned) => owned.view.texture().usage().contains(wgpu::TextureUsages::COPY_SRC), + ActivePass::Borrowed { .. } | ActivePass::Parked => false, + } + } + + /// Takes the owned pass out of `self`, leaving it `Parked`; puts a borrowed pass back and + /// returns `None` for it. + fn take(&mut self) -> Option<OpenPass<'a, 'p>> { + match std::mem::replace(self, ActivePass::Parked) { + ActivePass::Owned(owned) => Some(owned), + other => { + *self = other; + None + } + } + } + + pub(super) fn split_for_backdrop<'r>( + &mut self, + renderer: &'r Renderer, + at: u32, + instance: &Instance, + format: wgpu::TextureFormat, + origin: [f32; 2], + size: [u32; 2], + in_layer: bool, + hook: &mut EffectBackdropHook<'_>, + ) -> Option<&'r wgpu::TextureView> { + let bd = self.split(renderer, format, origin, size, in_layer, None, |encoder, bd| { + let site = EffectSite { + index: at, + instance, + mark: super::effect_mark(instance), + data: instance.uv, + scale: instance.params[3], + format, + origin, + size, + in_layer, + srgb_blend: renderer.srgb_blend, + backdrop: Some(&bd.view), + fade_stops: renderer.fade_stops, + }; + hook(EffectPhase::Backdrop(encoder), &site); + })?; + Some(&bd.view) + } + + /// Ends the pass, copies its target into the pooled backdrop of `format` (all of it, or + /// only `copy`, a window device-pixel rect `[x0, y0, x1, y1]`), runs `then` on the encoder, + /// and re-opens the pass with `LoadOp::Load`. `None` when the pass is borrowed, its target + /// lacks `COPY_SRC`, or no backdrop of `format` is pooled. + pub(super) fn split<'r>( + &mut self, + renderer: &'r Renderer, + format: wgpu::TextureFormat, + origin: [f32; 2], + size: [u32; 2], + in_layer: bool, + copy: Option<[f32; 4]>, + then: impl FnOnce(&mut wgpu::CommandEncoder, &'r Backdrop), + ) -> Option<&'r Backdrop> { + if !self.splittable() { return None; } + let bd = renderer.backdrops.iter().find(|b| b.format == format)?; + let OpenPass { pass, encoder, view, scissor, timestamps } = self.take()?; + // The pass ends here: the encoder is free until it re-opens below. + drop(pass); + let (vw, vh) = (bd.texture.width(), bd.texture.height()); + if in_layer { + let _clear = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { + label: Some("backdrop clear"), + color_attachments: &[Some(wgpu::RenderPassColorAttachment { + view: &bd.view, + depth_slice: None, + resolve_target: None, + ops: wgpu::Operations { load: wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT), store: wgpu::StoreOp::Store }, + })], + depth_stencil_attachment: None, + timestamp_writes: None, + occlusion_query_set: None, + multiview_mask: None, + }); + } + let src_tex = view.texture(); + let (src_x, src_y, dst_x, dst_y, copy_w, copy_h) = match copy { + None => { + let src_x = (-origin[0]).max(0.0) as u32; + let src_y = (-origin[1]).max(0.0) as u32; + let dst_x = origin[0].max(0.0) as u32; + let dst_y = origin[1].max(0.0) as u32; + let copy_w = size[0].min(src_tex.width()).saturating_sub(src_x).min(vw.saturating_sub(dst_x)); + let copy_h = size[1].min(src_tex.height()).saturating_sub(src_y).min(vh.saturating_sub(dst_y)); + (src_x, src_y, dst_x, dst_y, copy_w, copy_h) + } + Some(r) => { + let span = |lo: f32, hi: f32, o: f32, src: u32, dst: u32| { + let lo = lo.floor().max(o.ceil()).max(0.0); + let hi = hi.ceil().min(o + src as f32).min(dst as f32); + (lo, (hi - lo).max(0.0) as u32) + }; + let (x, w) = span(r[0], r[2], origin[0], size[0].min(src_tex.width()), vw); + let (y, h) = span(r[1], r[3], origin[1], size[1].min(src_tex.height()), vh); + ((x - origin[0].ceil()) as u32, (y - origin[1].ceil()) as u32, x as u32, y as u32, w, h) + } + }; + if copy_w > 0 && copy_h > 0 { + encoder.copy_texture_to_texture( + wgpu::TexelCopyTextureInfo { + texture: src_tex, + mip_level: 0, + origin: wgpu::Origin3d { x: src_x, y: src_y, z: 0 }, + aspect: wgpu::TextureAspect::All, + }, + wgpu::TexelCopyTextureInfo { + texture: &bd.texture, + mip_level: 0, + origin: wgpu::Origin3d { x: dst_x, y: dst_y, z: 0 }, + aspect: wgpu::TextureAspect::All, + }, + wgpu::Extent3d { width: copy_w, height: copy_h, depth_or_array_layers: 1 }, + ); + } + then(&mut *encoder, bd); + let mut next = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { + label: Some(if in_layer { "isolated group" } else { "frame" }), + color_attachments: &[Some(wgpu::RenderPassColorAttachment { + view, + depth_slice: None, + resolve_target: None, + ops: wgpu::Operations { load: wgpu::LoadOp::Load, store: wgpu::StoreOp::Store }, + })], + depth_stencil_attachment: None, + timestamp_writes: timestamps.as_ref().filter(|t| t.end_of_pass_write_index.is_some()).map(|t| wgpu::RenderPassTimestampWrites { + query_set: t.query_set, + beginning_of_pass_write_index: None, + end_of_pass_write_index: t.end_of_pass_write_index, + }), + occlusion_query_set: None, + multiview_mask: None, + }).forget_lifetime(); + next.set_viewport(0.0, 0.0, size[0] as f32, size[1] as f32, 0.0, 1.0); + if let Some([x, y, w, h]) = scissor { next.set_scissor_rect(x, y, w, h); } + *self = ActivePass::Owned(OpenPass { pass: next, encoder, view, scissor, timestamps }); + Some(bd) + } +} + +impl<'p> std::ops::Deref for ActivePass<'_, 'p> { + type Target = wgpu::RenderPass<'p>; + fn deref(&self) -> &Self::Target { + match self { + ActivePass::Borrowed { pass, .. } => &**pass, + ActivePass::Owned(owned) => &owned.pass, + ActivePass::Parked => panic!("no active pass: split ended the pass"), + } + } +} + +impl<'p> std::ops::DerefMut for ActivePass<'_, 'p> { + fn deref_mut(&mut self) -> &mut Self::Target { + match self { + ActivePass::Borrowed { pass, .. } => &mut **pass, + ActivePass::Owned(owned) => &mut owned.pass, + ActivePass::Parked => panic!("no active pass: split ended the pass"), + } + } +} + +impl Renderer { + pub(super) fn ensure_backdrop(&mut self, device: &wgpu::Device, format: wgpu::TextureFormat, (width, height): (u32, u32)) { + let (width, height) = (width.max(1), height.max(1)); + if let Some(b) = self.backdrops.iter().find(|b| b.format == format) + && b.texture.width() == width && b.texture.height() == height + { + return; + } + let texture = device.create_texture(&wgpu::TextureDescriptor { + label: Some("effect backdrop"), + size: wgpu::Extent3d { width, height, depth_or_array_layers: 1 }, + mip_level_count: 1, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + format, + usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST | wgpu::TextureUsages::RENDER_ATTACHMENT, + view_formats: &[], + }); + let view = texture.create_view(&Default::default()); + if let Some(blur) = &mut self.backdrop_blur { blur.bind_backdrop(device, format, &view); } + if let Some(b) = self.backdrops.iter_mut().find(|b| b.format == format) { + *b = Backdrop { format, texture, view }; + } else { + self.backdrops.push(Backdrop { format, texture, view }); + } + } +} diff --git a/app/vendor/rune/crates/rune/src/render/pipelines.rs b/app/vendor/rune/crates/rune/src/render/pipelines.rs new file mode 100644 index 0000000..34badc9 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/render/pipelines.rs @@ -0,0 +1,261 @@ +//! Building the renderer and its uber pipelines: the pipeline for each target format and blend, +//! the sampled textures the CPU fills, and the bind group the uber shader reads. + +use super::{ATLAS_START_ROWS, Blend, CLIP_WGSL, Globals, Instance, Renderer, dxbc, metallib, variant, warmup::WarmRenderer}; + +impl Renderer { + #[cfg(not(target_arch = "wasm32"))] + pub(super) fn new_warm(device: &wgpu::Device, format: wgpu::TextureFormat) -> WarmRenderer { + Self::create_warm(device, format, None, cfg!(target_os = "macos")) + } + + pub(super) fn create(device: &wgpu::Device, format: wgpu::TextureFormat, properties: Option<(&[crate::gpu::springs::Node], &[u32])>, classic: bool) -> Renderer { + Self::from_warm(Self::create_warm(device, format, properties, classic)) + } + + fn create_warm(device: &wgpu::Device, format: wgpu::TextureFormat, properties: Option<(&[crate::gpu::springs::Node], &[u32])>, classic: bool) -> WarmRenderer { + let spring_shader = if properties.is_some() { + let source = format!("{CLIP_WGSL}\n{}\n{}", include_str!("../shaders/shader.wgsl"), crate::gpu::springs::SHADER); + Some(device.create_shader_module(wgpu::ShaderModuleDescriptor { + label: Some("uber"), + source: wgpu::ShaderSource::Wgsl(source.into()), + })) + } else { + None + }; + let globals = device.create_buffer(&wgpu::BufferDescriptor { + label: None, + size: u64::from(device.limits().min_uniform_buffer_offset_alignment).max(std::mem::size_of::<Globals>() as u64) + 16, + usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + }); + let stand_in = Self::image_texture(device, 1, 1); + // Subpixel text waits for the subpixel pipeline (`lcd_ready`), not just the feature. + if !device.features().contains(wgpu::Features::DUAL_SOURCE_BLENDING) { crate::text::note_dual_source(false); } + let spring_layout = properties.map(|_| crate::gpu::springs::Bindings::layout(device)); + let vertex_entry = if properties.is_some() { "vs_springs" } else { "vs" }; + // The shader machine starts Classic; everywhere but macOS (whose default text keeps the + // Classic shader it always drew) and GPU springs, it asks for Windfoil at once. + let (uber, windfoil) = if classic { + (variant::Uber::Classic, None) + } else { + Self::start_windfoil(device, &variant::BuildContext { format, vertex_entry, globals: &globals, stand_in: &stand_in }) + }; + let atlas = Self::atlas_texture(device, windfoil.is_some(), ATLAS_START_ROWS); + let (bgl, layout, shader, pipeline) = match windfoil { + Some(built) => (built.bind_layout, built.layout, built.shader, built.pipeline), + None => { + let bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + label: None, + entries: &metallib::uber_bind_entries(), + }); + let layouts = [Some(&bgl), spring_layout.as_ref()]; + let layout = device.create_pipeline_layout(&metallib::uber_pipeline_layout( + &layouts, properties.is_some(), + )); + let make_pipeline = |shader: &dxbc::Shaders| Self::pipeline(device, &layout, shader, format, vertex_entry, Blend::SourceOver); + let (shader, pipeline) = match spring_shader { + Some(shader) => { let shader = dxbc::Shaders::one(shader); let pipeline = make_pipeline(&shader); (shader, pipeline) } + None => metallib::uber_shader_and_pipeline(device, make_pipeline), + }; + (bgl, layout, shader, pipeline) + } + }; + let bind_group = Self::bind_group(device, &bgl, &globals, uber.outlines(), &atlas, &stand_in, None); + let instances = rune_staging::GrowBuffer::new( + device, + "instances", + wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST, + std::mem::size_of::<Instance>(), + 256, + 0, + ); + let spring_instances = properties.map_or(0, |(_, ids)| ids.len()); + let springs = properties.map(|(nodes, ids)| crate::gpu::springs::Bindings::new(device, spring_layout.as_ref().unwrap(), nodes, ids)); + WarmRenderer { + surfaces_building: None, + pipeline, + format, + shader, + layout, + vertex_entry, + extra: Vec::new(), + bind_group, + bind_layout: bgl, + globals, + atlas, + uber, + lcd: variant::Lcd::Unbuilt, + pinned: None, + pinned_extra: Vec::new(), + pinned_building: None, + kinds: Vec::new(), + lcd_frame: false, + frame_wake: None, + stand_in, + atlas_pages: Vec::new(), + images: Vec::new(), + image_batches: Vec::new(), + instances, + count: 0, + springs, + spring_instances, + layers: Default::default(), + srgb_blend: false, + effects: Vec::new(), + backdrops: Vec::new(), + backdrop_used: false, + backdrop_blur: None, + breakers: Default::default(), + uploads: Default::default(), + fills: Default::default(), + device_key: crate::compose::DeviceKey::next(), + max_texture_dim: device.limits().max_texture_dimension_2d, + #[cfg(any(target_os = "windows", target_arch = "wasm32"))] + clear_quad: std::sync::OnceLock::new(), + #[cfg(any(target_os = "windows", target_arch = "wasm32"))] + damage: Default::default(), + } + } + + pub(super) fn pipeline( + device: &wgpu::Device, + layout: &wgpu::PipelineLayout, + shader: &dxbc::Shaders, + format: wgpu::TextureFormat, + vertex_entry: &str, + blend: Blend, + ) -> wgpu::RenderPipeline { + device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { + label: Some("uber"), + layout: Some(layout), + vertex: wgpu::VertexState { + module: &shader.vertex, + entry_point: Some(vertex_entry), + compilation_options: Default::default(), + buffers: &[Some(metallib::uber_vertex_layout())], + }, + primitive: metallib::uber_primitive(), + depth_stencil: None, + multisample: Default::default(), + fragment: Some(wgpu::FragmentState { + module: &shader.fragment, + entry_point: Some("fs"), + compilation_options: Default::default(), + targets: &[Some(wgpu::ColorTargetState { + format, + blend: Some(super::blend_state(blend)), + write_mask: wgpu::ColorWrites::ALL, + })], + }), + multiview_mask: None, + cache: None, + }) + } + + pub(super) fn image_texture(device: &wgpu::Device, width: u32, height: u32) -> wgpu::Texture { + Self::texture(device, "image atlas", wgpu::TextureFormat::Rgba8UnormSrgb, width, height) + } + + /// A sampled texture the CPU fills with `write_rows`. + pub(super) fn texture(device: &wgpu::Device, label: &str, format: wgpu::TextureFormat, width: u32, height: u32) -> wgpu::Texture { + device.create_texture(&wgpu::TextureDescriptor { + label: Some(label), + size: wgpu::Extent3d { width, height, depth_or_array_layers: 1 }, + mip_level_count: 1, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + format, + usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST, + view_formats: &[], + }) + } + + pub(super) fn bind_group( + device: &wgpu::Device, + layout: &wgpu::BindGroupLayout, + globals: &wgpu::Buffer, + outlines: Option<&wgpu::Texture>, + atlas: &wgpu::Texture, + images: &wgpu::Texture, + target: Option<&wgpu::Buffer>, + ) -> wgpu::BindGroup { + let atlas_view = atlas.create_view(&Default::default()); + let image_view = images.create_view(&Default::default()); + let outline_view = outlines.map(|t| t.create_view(&Default::default())); + let mut entries = vec![ + wgpu::BindGroupEntry { binding: 0, resource: globals.as_entire_binding() }, + wgpu::BindGroupEntry { binding: 1, resource: wgpu::BindingResource::TextureView(&atlas_view) }, + wgpu::BindGroupEntry { binding: 2, resource: wgpu::BindingResource::TextureView(&image_view) }, + wgpu::BindGroupEntry { binding: 3, resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding { + buffer: target.unwrap_or(globals), + offset: if target.is_some() { 0 } else { u64::from(device.limits().min_uniform_buffer_offset_alignment).max(std::mem::size_of::<Globals>() as u64) }, + size: std::num::NonZeroU64::new(16), + }) }, + ]; + // The Windfoil shader's outline store (render/variant.rs); Classic has no binding 4. + if let Some(view) = &outline_view { + entries.push(wgpu::BindGroupEntry { binding: 4, resource: wgpu::BindingResource::TextureView(view) }); + } + device.create_bind_group(&wgpu::BindGroupDescriptor { label: None, layout, entries: &entries }) + } + + /// The pipeline that draws into a `format` target: the layer's additive one inside a + /// `Blend::PlusLighter` layer, else the frame's or the `add_format` one. + pub(super) fn draw_pipeline(&self, format: wgpu::TextureFormat, target: Option<usize>) -> &wgpu::RenderPipeline { + if self.layer_blend(target) == Blend::PlusLighter { + &self.layers.additive.as_ref().expect("prepared dissolve").0 + } else if let (variant::Lcd::Built(lcd), true, None) = (&self.lcd, self.lcd_frame && format == self.format, target) { + // Subpixel text blends by channel over the window; inside layers it draws grayscale. + lcd + } else if format == self.format { + &self.pipeline + } else { + &self.extra.iter().find(|(f, _)| *f == format).expect("Renderer::add_format first").1 + } + } + + /// Builds the pipeline for another target format (e.g. an `Rgba16Float` layer), once. + pub fn add_format(&mut self, device: &wgpu::Device, format: wgpu::TextureFormat) { + if format != self.format && !self.extra.iter().any(|(f, _)| *f == format) { + let p = Self::pipeline(device, &self.layout, &self.shader, format, self.vertex_entry, Blend::SourceOver); + self.extra.push((format, p)); + } + if self.layer_stats().targets > 0 { self.add_layer_format(device, format); } + let [vw, vh] = self.target_frame(None).1; + if !self.backdrops.is_empty() && vw > 0 && vh > 0 { + self.ensure_backdrop(device, format, (vw, vh)); + } + if let Some(s) = &mut self.surfaces { s.add_format(device, format); } + } + + /// Switches the frame pass's target format (`!format.is_srgb()` turns `srgb_blend` on), + /// keeping the glyph and image atlases, offscreen layer targets and `extra` pipelines. + pub fn set_format(&mut self, device: &wgpu::Device, format: wgpu::TextureFormat) { + if self.format == format { return; } + let next = match self.extra.iter().position(|(f, _)| *f == format) { + Some(i) => self.extra.swap_remove(i).1, + None => Self::pipeline(device, &self.layout, &self.shader, format, self.vertex_entry, Blend::SourceOver), + }; + let old = std::mem::replace(&mut self.pipeline, next); + self.extra.push((self.format, old)); + // The pinned pipelines go with the frame pipeline: kept for the old format, made on their thread for a new one. + if let Some(pinned) = self.pinned.take() { self.pinned_extra.push((self.format, pinned)); } + self.format = format; + self.lcd = variant::Lcd::Unbuilt; + match self.pinned_extra.iter().position(|(f, _)| *f == format) { + Some(i) => self.pinned = Some(self.pinned_extra.swap_remove(i).1), + None => self.start_pinned(device), + } + self.srgb_blend = !format.is_srgb(); + if self.layer_stats().targets > 0 { self.add_layer_format(device, format); } + let [vw, vh] = self.target_frame(None).1; + if !self.backdrops.is_empty() && vw > 0 && vh > 0 { + self.ensure_backdrop(device, format, (vw, vh)); + } + if let Some(s) = &mut self.surfaces { + s.set_srgb_blend(self.srgb_blend); + s.add_format(device, format); + } + } +} diff --git a/app/vendor/rune/crates/rune/src/render/pixel_check.rs b/app/vendor/rune/crates/rune/src/render/pixel_check.rs new file mode 100644 index 0000000..b7f2123 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/render/pixel_check.rs @@ -0,0 +1,152 @@ +//! `RUNE_LOOP_CHECK=2` (Windows): a loop-only frame's picture against the whole frame's. After a +//! loop-only frame redraws its rectangles into the kept texture (`draw_armed`), the same instances +//! are drawn whole into a scratch texture in the same encoder and both are copied out; the next +//! frame of any kind (`damage_drawn`, once the encoding frame was submitted), or the next loop-only +//! frame (`arm_loop`), or the renderer going away, reads them back and compares every pixel, so the +//! last check of a run is compared too. This reaches what the +//! instance comparison (`RUNE_LOOP_CHECK=1`) can't: `arm_loop`'s rectangles, the culled redraw +//! inside them, and so the present rectangles, which are the same rectangles. Stalls on the +//! readback; a diagnostic only. Unset, it costs one `OnceLock` read per loop-only frame. +//! +//! Each check prints a line when any pixel differs (how many, by more than 2 of 255 in a channel, +//! their bounds, and the frame's rectangles), and every 240 checks a running count. A differing check +//! is noted for the whole process (`failed`): the process then ends with exit code 3, whether it +//! exits fast or in order (`quit::end_process`, `event_loop::run_configured`). + +use super::*; + +/// A check found a differing picture, in any window, at any time in this process. +static FAILED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + +/// `RUNE_LOOP_CHECK=2` is set and a check found a differing picture: the process's exit code is 3. +pub(crate) fn failed() -> bool { on() && FAILED.load(std::sync::atomic::Ordering::Relaxed) } + +/// frame-profile, `RUNE_LOOP_CHECK_SPOIL=1`: loop-only frames skip their redraw (`draw_armed`). +#[cfg(feature = "frame-profile")] +pub(super) fn spoiled() -> bool { + static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("RUNE_LOOP_CHECK_SPOIL").is_some_and(|v| v == "1")) +} + +pub(super) fn on() -> bool { + static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("RUNE_LOOP_CHECK").is_some_and(|v| v == "2")) +} + +/// The scratch target, the two readback buffers, and what the last encode left in them. +pub(super) struct Check { + device: wgpu::Device, + size: (u32, u32), + format: wgpu::TextureFormat, + texture: wgpu::Texture, + view: wgpu::TextureView, + kept: rune_staging::Readback, + whole: rune_staging::Readback, + /// The rectangles of the frame whose pictures the buffers hold, and how many frames have ended + /// since it encoded them (1: its own, not yet submitted; 2: submitted). + pending: Option<(Vec<[u32; 4]>, u8)>, + checks: u64, + differ: u64, +} + +impl Check { + fn new(device: &wgpu::Device, size: (u32, u32), format: wgpu::TextureFormat, view_format: wgpu::TextureFormat) -> Check { + let texture = device.create_texture(&wgpu::TextureDescriptor { + label: Some("loop pixel check"), + size: wgpu::Extent3d { width: size.0, height: size.1, depth_or_array_layers: 1 }, + mip_level_count: 1, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + format, + usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC, + view_formats: &[view_format], + }); + let view = texture.create_view(&wgpu::TextureViewDescriptor { format: Some(view_format), ..Default::default() }); + let kept = rune_staging::Readback::new(device, "loop pixel check: kept", size.0, size.1, 4); + let whole = rune_staging::Readback::new(device, "loop pixel check: whole", size.0, size.1, 4); + Check { device: device.clone(), size, format, texture, view, kept, whole, pending: None, checks: 0, differ: 0 } + } + + /// Reads back and compares what the last loop-only frame left, if anything. + fn resolve(&mut self) { + let Some((rects, _)) = self.pending.take() else { return }; + let device = self.device.clone(); + let (a, b) = (self.kept.buffer().slice(..), self.whole.buffer().slice(..)); + a.map_async(wgpu::MapMode::Read, |_| {}); + b.map_async(wgpu::MapMode::Read, |_| {}); + if rune_gpu::health::poll(&device, wgpu::PollType::wait_indefinitely()).is_err() { return; } + let row = self.kept.padded_row(); + let row_bytes = self.kept.row_bytes(); + let (mut any, mut far, mut bounds) = (0u64, 0u64, [u32::MAX, u32::MAX, 0, 0]); + { + let (Ok(ka), Ok(wb)) = (a.get_mapped_range(), b.get_mapped_range()) else { + self.kept.buffer().unmap(); + self.whole.buffer().unmap(); + return; + }; + for y in 0..self.size.1 { + let at = (y * row) as usize; + let (kr, wr) = (&ka[at..at + row_bytes], &wb[at..at + row_bytes]); + if kr == wr { continue; } + for x in 0..self.size.0 as usize { + let (p, q) = (&kr[x * 4..x * 4 + 4], &wr[x * 4..x * 4 + 4]); + if p == q { continue; } + any += 1; + if p.iter().zip(q).any(|(u, v)| u.abs_diff(*v) > 2) { + far += 1; + let x = x as u32; + bounds = [bounds[0].min(x), bounds[1].min(y), bounds[2].max(x + 1), bounds[3].max(y + 1)]; + } + } + } + } + self.kept.buffer().unmap(); + self.whole.buffer().unmap(); + self.checks += 1; + if any > 0 { + self.differ += 1; + FAILED.store(true, std::sync::atomic::Ordering::Relaxed); + eprintln!("rune: loop pixel check: {any} pixels differ from the whole frame, {far} by more than 2/255{}; the frame's rectangles {rects:?}", + if far > 0 { format!(" within {bounds:?}") } else { String::new() }); + } + if self.checks % 240 == 0 { eprintln!("rune: loop pixel check: {} loop-only frames compared with whole frames, {} differ", self.checks, self.differ); } + } +} + +impl Check { + /// A frame ended (`damage_drawn`, before its submit): the pictures the frame before it copied + /// out are on the GPU's queue by now, and are compared. + pub(super) fn frame_ended(&mut self) { + let Some((_, age)) = self.pending.as_mut() else { return }; + *age += 1; + if *age >= 2 { self.resolve(); } + } +} + +impl Drop for Check { + fn drop(&mut self) { + self.resolve(); + if self.checks > 0 { eprintln!("rune: loop pixel check: {} loop-only frames compared with whole frames, {} differ (at the end)", self.checks, self.differ); } + } +} + +impl Renderer { + /// `arm_loop`'s part: compares the last loop-only frame's pictures, and has a scratch target + /// for this frame's. + pub(super) fn pixel_check_arm(&self, device: &wgpu::Device, size: (u32, u32), format: wgpu::TextureFormat) { + let mut d = self.damage.lock().unwrap(); + if let Some(c) = d.pixel.as_mut() { c.resolve(); } + if d.pixel.as_ref().is_none_or(|c| c.size != size || c.format != format) { d.pixel = Some(Check::new(device, size, format, self.format)); } + d.looped = true; + } + + /// `draw_armed`'s part, after a loop-only frame redrew `kept`: the whole frame into the scratch + /// target, and both copied out for the next `pixel_check_arm`. + pub(super) fn pixel_check_encode(&self, encoder: &mut wgpu::CommandEncoder, c: &mut Check, kept: &wgpu::Texture, clear: [f32; 4], rects: &[[u32; 4]]) { + if (kept.width(), kept.height()) != c.size { return; } + self.draw_timed(encoder, &c.view, clear, None); + c.kept.copy_from(encoder, kept); + c.whole.copy_from(encoder, &c.texture); + c.pending = Some((rects.to_vec(), 0)); + } +} diff --git a/app/vendor/rune/crates/rune/src/render/prewarm.rs b/app/vendor/rune/crates/rune/src/render/prewarm.rs new file mode 100644 index 0000000..9cd511b --- /dev/null +++ b/app/vendor/rune/crates/rune/src/render/prewarm.rs @@ -0,0 +1,81 @@ +//! `prewarm_gpu`'s thread and the slot a window takes its result from. + +use super::{Gpu, Renderer, warmup::WarmRenderer}; +use std::sync::Mutex; +use std::thread::JoinHandle; + +/// A Mac window's target format (`surface_config`), which blends in sRGB space unless the +/// app turns that off, so the window renders with the pipeline compiled here. +const FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Bgra8Unorm; + +struct Prewarmed(Gpu, WarmRenderer); + +#[derive(Default)] +enum State { + #[default] + Idle, + Running(JoinHandle<Option<Prewarmed>>), + Done, +} + +pub(super) struct Slot(Mutex<State>); + +impl Slot { + pub(super) const fn new() -> Self { + Self(Mutex::new(State::Idle)) + } + + pub(super) fn start(&self) { + let mut state = self.0.lock().unwrap_or_else(|e| e.into_inner()); + if !matches!(*state, State::Idle) { return; } + let thread = std::thread::Builder::new().name("rune-gpu-prewarm".into()).spawn(|| { + objc2::rc::autoreleasepool(|_| { + super::gpu_events::starting(); + let gpu = Gpu::try_new(Gpu::instance(), None).ok()?; + #[cfg(test)] + let loads_before = super::metallib::thread_loads(); + let renderer = Renderer::new_warm(&gpu.device, FORMAT); + #[cfg(test)] + if super::metallib::metallib_enabled() { + assert_eq!(super::metallib::thread_loads(), loads_before + 1, "prewarm_gpu loads the precompiled metallib"); + } + Some(Prewarmed(gpu, renderer)) + }) + }); + *state = match thread { + Ok(thread) => State::Running(thread), + Err(_) => State::Done, + }; + } + + pub(super) fn take(&self) -> Option<(Gpu, Renderer)> { + let state = std::mem::replace(&mut *self.0.lock().unwrap_or_else(|e| e.into_inner()), State::Done); + let State::Running(thread) = state else { return None }; + thread.join().ok().flatten().map(|Prewarmed(gpu, renderer)| (gpu, Renderer::from_warm(renderer))) + } + + /// Starts a new thread if one is working; that one drops its result when it finishes. + #[cfg_attr(not(feature = "metal-backend"), allow(dead_code))] + pub(super) fn restart(&self) { + let mut state = self.0.lock().unwrap_or_else(|e| e.into_inner()); + if !matches!(*state, State::Running(_)) { return; } + *state = State::Idle; + drop(state); + self.start(); + } + + /// The thread, if still working, drops its result when it finishes. + pub(super) fn discard(&self) { + let state = std::mem::replace(&mut *self.0.lock().unwrap_or_else(|e| e.into_inner()), State::Done); + drop(state); + } +} + +static GLOBAL: Slot = Slot::new(); + +pub(super) fn start() { GLOBAL.start(); } +pub(super) fn take() -> Option<(Gpu, Renderer)> { GLOBAL.take() } +#[cfg(feature = "metal-backend")] +pub(super) fn restart() { GLOBAL.restart(); } +#[cfg_attr(test, allow(dead_code))] +pub(super) fn discard() { GLOBAL.discard(); } diff --git a/app/vendor/rune/crates/rune/src/render/prewarm_tests.rs b/app/vendor/rune/crates/rune/src/render/prewarm_tests.rs new file mode 100644 index 0000000..989c04d --- /dev/null +++ b/app/vendor/rune/crates/rune/src/render/prewarm_tests.rs @@ -0,0 +1,144 @@ +//! `prewarm_gpu` ordering and macOS Metal prewarm tests. + +#[test] +fn prewarm_gpu_on_chooses_before_it_starts() { + let log = std::cell::RefCell::new(Vec::new()); + super::device::choose_then_start(crate::GpuBackend::Metal, |b| log.borrow_mut().push(format!("choose {b:?}")), || log.borrow_mut().push("start".into())); + assert_eq!(*log.borrow(), ["choose Metal", "start"]); +} + +/// `prewarm_gpu` and how a window picks it up, on a bare Metal layer (no window server needed). +#[cfg(target_os = "macos")] +#[allow(unsafe_code)] +mod macos { + use super::super::{Gpu, Renderer}; + use objc2::{rc::Retained, runtime::{AnyClass, AnyObject}, msg_send}; + + fn layer() -> Retained<AnyObject> { + // SAFETY: `+[CAMetalLayer new]` allocates and returns a retained `CAMetalLayer`. + unsafe { msg_send![AnyClass::get(c"CAMetalLayer").expect("QuartzCore"), new] } + } + + fn surface<'w>(instance: &wgpu::Instance, layer: &Retained<AnyObject>) -> Result<wgpu::Surface<'w>, String> { + let target = wgpu::SurfaceTargetUnsafe::CoreAnimationLayer(Retained::as_ptr(layer) as *mut std::ffi::c_void); + // SAFETY: the layer outlives the surface in each test. + unsafe { instance.create_surface_unsafe(target) }.map_err(|e| e.to_string()) + } + + /// The window gets the thread's device and its compiled pipeline, once, in the Mac window format. + #[test] + fn a_window_takes_the_prewarmed_gpu_and_renderer_once() { + crate::prewarm_gpu(); + crate::prewarm_gpu(); + let layer = layer(); + let (gpu, _surface, renderer) = match Gpu::for_surface(wgpu::Features::empty(), false, |i| surface(i, &layer)) { + Ok(taken) => taken, + Err(error) => return eprintln!("skipped: {error}"), + }; + let Some(renderer) = renderer else { return eprintln!("skipped: no GPU for the prewarm thread") }; + // Rune's Metal backend loads its metallib without advertising passthrough. + #[cfg(feature = "metal-backend")] + let native = crate::gpu::metal::raw_device(&gpu.device).is_some(); + #[cfg(not(feature = "metal-backend"))] + let native = false; + assert!(native || gpu.device.features().contains(wgpu::Features::PASSTHROUGH_SHADERS)); + assert_eq!(renderer.format, wgpu::TextureFormat::Bgra8Unorm); + drop((renderer, gpu)); + let (_, _surface, again) = Gpu::for_surface(wgpu::Features::empty(), false, |i| surface(i, &layer)).expect("a second GPU"); + assert!(again.is_none(), "the prewarmed GPU goes to one window"); + + // A slot that already took or discarded a GPU ignores a later `start`, so a late + // `prewarm_gpu()` call cannot leave an unclaimed GPU in memory. + let taken = super::super::prewarm::Slot::new(); + assert!(taken.take().is_none()); + taken.start(); + assert!(taken.take().is_none()); + + let discarded = super::super::prewarm::Slot::new(); + discarded.start(); + discarded.discard(); + assert!(discarded.take().is_none()); + discarded.start(); + assert!(discarded.take().is_none()); + + // `restart` replaces a working thread and leaves an idle or finished slot alone. + let restarted = super::super::prewarm::Slot::new(); + restarted.restart(); + restarted.start(); + restarted.restart(); + assert!(restarted.take().is_some(), "the new thread's GPU"); + restarted.restart(); + assert!(restarted.take().is_none(), "a taken slot stays taken"); + } + + /// A prewarmed device without a feature the window wants (and the adapter has) is replaced on + /// the same instance, with the surface made once: a second surface would add a second layer. + #[test] + fn a_prewarmed_gpu_missing_wanted_features_is_redone_on_its_instance() { + let Ok(early) = Gpu::try_new(Gpu::instance(), None) else { return eprintln!("skipped: no GPU") }; + let plain = wgpu::Features::FLOAT32_FILTERABLE | wgpu::Features::DEPTH32FLOAT_STENCIL8 | wgpu::Features::TEXTURE_FORMAT_16BIT_NORM; + let missing = (early.adapter.features() - early.device.features()) & plain; + let Some(wanted) = missing.iter().next() else { return eprintln!("skipped: the adapter has none of the test's features") }; + let renderer = Renderer::new(&early.device, wgpu::TextureFormat::Bgra8UnormSrgb); + let layer = layer(); + let mut made = 0; + let (gpu, _surface, renderer) = Gpu::for_surface_from(Some((early, renderer)), wanted, false, |i| { made += 1; surface(i, &layer) }) + .expect("a GPU with the wanted feature"); + assert_eq!(made, 1); + assert!(renderer.is_none(), "the prewarmed renderer belongs to the dropped device"); + assert!(gpu.device.features().contains(wanted)); + + let Ok(early) = Gpu::try_new(Gpu::instance(), None) else { return }; + let renderer = Renderer::new(&early.device, wgpu::TextureFormat::Bgra8UnormSrgb); + let (_, _surface, kept) = Gpu::for_surface_from(Some((early, renderer)), wgpu::Features::empty(), false, |i| surface(i, &layer)).expect("a GPU"); + assert!(kept.is_some(), "a suitable prewarmed device keeps its renderer"); + } + + /// A compositor wanting a feature the native Metal backend lacks gets wgpu's device, when + /// Metal is only the default, with the prewarmed native GPU dropped before any surface. + #[cfg(feature = "metal-backend")] + #[test] + fn a_compositor_wanting_what_the_native_backend_lacks_draws_with_wgpu() { + if !crate::gpu::metal::enabled() || std::env::var_os("RUNE_GPU_BACKEND").is_some() { + return eprintln!("skipped: the native backend isn't the default here"); + } + let early = Gpu::headless(); + assert!(crate::gpu::metal::raw_device(&early.device).is_some()); + let renderer = Renderer::new(&early.device, wgpu::TextureFormat::Bgra8UnormSrgb); + let layer = layer(); + let mut made = 0; + let wanted = wgpu::Features::POLYGON_MODE_LINE; + let (gpu, _surface, renderer) = Gpu::for_surface_from(Some((early, renderer)), wanted, false, |i| { made += 1; surface(i, &layer) }) + .expect("a wgpu GPU"); + assert_eq!(made, 1); + assert!(renderer.is_none()); + assert!(crate::gpu::metal::raw_device(&gpu.device).is_none(), "wgpu's device"); + assert!(gpu.device.features().contains(wanted)); + let described = crate::gpu::backend::describe(&gpu.device); + assert!(described.starts_with("wgpu Metal on ") && described.contains("which Rune's Metal backend lacks"), "{described}"); + assert!(crate::gpu::backend::describe(&Gpu::headless().device).ends_with("(the default)")); + assert!(!crate::gpu::backend::serves(&Gpu::headless().device, wanted)); + assert!(crate::gpu::backend::serves(&Gpu::headless().device, wgpu::Features::TIMESTAMP_QUERY)); + } + + /// A compositor wanting immediates keeps the native backend and the prewarmed device, which + /// has them whether or not anything asked, with the adapter's immediate size. + #[cfg(feature = "metal-backend")] + #[test] + fn a_compositor_wanting_immediates_keeps_the_native_backend_and_the_prewarmed_gpu() { + if !crate::gpu::metal::enabled() || std::env::var_os("RUNE_GPU_BACKEND").is_some() { + return eprintln!("skipped: the native backend isn't the default here"); + } + let early = Gpu::headless(); + let renderer = Renderer::new(&early.device, wgpu::TextureFormat::Bgra8UnormSrgb); + let layer = layer(); + let wanted = wgpu::Features::IMMEDIATES; + let (gpu, _surface, kept) = Gpu::for_surface_from(Some((early, renderer)), wanted, false, |i| surface(i, &layer)).expect("a GPU"); + assert!(kept.is_some(), "the prewarmed renderer"); + assert!(crate::gpu::metal::raw_device(&gpu.device).is_some(), "the native backend's device"); + assert!(gpu.device.features().contains(wanted)); + assert_eq!(gpu.device.limits().max_immediate_size, 4096); + let described = crate::gpu::backend::describe(&gpu.device); + assert!(described.starts_with("Rune's Metal backend on ") && described.ends_with("(the default)"), "{described}"); + } +} diff --git a/app/vendor/rune/crates/rune/src/render/surface_alpha.rs b/app/vendor/rune/crates/rune/src/render/surface_alpha.rs new file mode 100644 index 0000000..6093cd9 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/render/surface_alpha.rs @@ -0,0 +1,130 @@ +//! Convert Rune's premultiplied composition to the straight alpha required by +//! wgpu's straight-alpha surfaces and PNG exports. Metal's CAMetalLayer stays premultiplied. +/// The pass's shader (`surface_alpha.wgsl`). +pub(crate) const WGSL: &str = include_str!("../shaders/surface_alpha.wgsl"); + +/// Render targets of `*Srgb` formats hold sRGB-encoded premultiplied linear colour. PNG uses +/// straight sRGB colour, so un-premultiply in linear light, not in the encoded byte domain. +pub(crate) fn straight_alpha(pixels: &mut [u8]) { + for pixel in pixels.chunks_exact_mut(4) { + let alpha = f32::from(pixel[3]) / 255.0; + if alpha == 0.0 { + pixel[..3].fill(0); + } else if alpha < 1.0 { + for c in &mut pixel[..3] { + *c = (crate::color::srgb_encode((crate::color::srgb_decode(f32::from(*c) / 255.0) / alpha).clamp(0.0, 1.0)) * 255.0).round() as u8; + } + } + } +} + +pub(crate) struct AlphaSurface { + pub view: wgpu::TextureView, + texture: wgpu::Texture, + pipeline: wgpu::RenderPipeline, + layout: wgpu::BindGroupLayout, + bind: wgpu::BindGroup, + format: wgpu::TextureFormat, +} + +#[cfg(test)] +mod tests { + #[test] + fn gpu_straight_alpha_matches_cpu_reference() { + use crate::render::{Gpu, Offscreen, OFFSCREEN_FORMAT}; + let gpu = Gpu::new(Gpu::instance(), None); + let alpha = super::AlphaSurface::new(&gpu.device, OFFSCREEN_FORMAT, (4, 4)); + let target = Offscreen::new(&gpu.device, 4, 4); + for color in [[0.125_f32, 0.25, 0.375, 0.5], [0.0; 4], [0.4, 0.6, 0.1, 1.0]] { + let mut enc = gpu.device.create_command_encoder(&Default::default()); + { + let _pass = enc.begin_render_pass(&wgpu::RenderPassDescriptor { + label: None, color_attachments: &[Some(wgpu::RenderPassColorAttachment { + view: &alpha.view, depth_slice: None, resolve_target: None, + ops: wgpu::Operations { load: wgpu::LoadOp::Clear(wgpu::Color { + r: color[0] as f64, g: color[1] as f64, b: color[2] as f64, a: color[3] as f64, + }), store: wgpu::StoreOp::Store }, + })], depth_stencil_attachment: None, timestamp_writes: None, + occlusion_query_set: None, multiview_mask: None, + }); + } + alpha.draw(&mut enc, &target.view); + target.copy(&mut enc); + gpu.queue.submit([enc.finish()]); + let pixels = target.read(&gpu.device); + let mut reference = [0_u8; 4]; + for i in 0..3 { reference[i] = (crate::color::srgb_encode(color[i]) * 255.0).round() as u8; } + reference[3] = (color[3] * 255.0).round() as u8; + crate::tooling::straight_alpha(&mut reference); + for pixel in pixels.chunks_exact(4) { + assert!(pixel.iter().zip(reference).all(|(a, b)| a.abs_diff(b) <= 1), "GPU {pixel:?}, CPU {reference:?}"); + } + } + } +} +impl AlphaSurface { + pub fn new(device: &wgpu::Device, format: wgpu::TextureFormat, size: (u32, u32)) -> Self { + let layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + label: Some("alpha source"), entries: &[wgpu::BindGroupLayoutEntry { + binding: 0, visibility: wgpu::ShaderStages::FRAGMENT, + ty: wgpu::BindingType::Texture { sample_type: wgpu::TextureSampleType::Float { filterable: false }, + view_dimension: wgpu::TextureViewDimension::D2, multisampled: false }, count: None, + }], + }); + let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + label: Some("alpha conversion"), bind_group_layouts: &[Some(&layout)], immediate_size: 0, + }); + let make = |shaders: &super::dxbc::Shaders| device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { + label: Some("straight alpha"), layout: Some(&pipeline_layout), + vertex: wgpu::VertexState { module: &shaders.vertex, entry_point: Some("vs"), compilation_options: Default::default(), buffers: &[] }, + primitive: Default::default(), depth_stencil: None, multisample: Default::default(), + fragment: Some(wgpu::FragmentState { module: &shaders.fragment, entry_point: Some("fs"), compilation_options: Default::default(), + targets: &[Some(wgpu::ColorTargetState { format, blend: None, write_mask: wgpu::ColorWrites::ALL })] }), + multiview_mask: None, cache: None, + }); + // DX12 takes the bytecode regen_dxbc compiled from this WGSL; elsewhere, or when it's stale + // or refused, the WGSL compiles here. + #[cfg(target_os = "windows")] + let precompiled = super::dxbc::surface_alpha(device, WGSL, &make); + #[cfg(not(target_os = "windows"))] + let precompiled: Option<(super::dxbc::Shaders, wgpu::RenderPipeline)> = None; + let pipeline = precompiled.map_or_else(|| { + let module = device.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some("straight alpha"), source: wgpu::ShaderSource::Wgsl(WGSL.into()) }); + make(&super::dxbc::Shaders::one(module)) + }, |(_, pipeline)| pipeline); + let (texture, view, bind) = Self::target(device, &layout, format, size); + Self { texture, view, bind, pipeline, layout, format } + } + fn target(device: &wgpu::Device, layout: &wgpu::BindGroupLayout, format: wgpu::TextureFormat, size: (u32, u32)) + -> (wgpu::Texture, wgpu::TextureView, wgpu::BindGroup) { + let texture = device.create_texture(&wgpu::TextureDescriptor { + label: Some("premultiplied composition"), + size: wgpu::Extent3d { width: size.0.max(1), height: size.1.max(1), depth_or_array_layers: 1 }, + mip_level_count: 1, sample_count: 1, dimension: wgpu::TextureDimension::D2, + format, usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_SRC, view_formats: &[], + }); + let view = texture.create_view(&Default::default()); + let bind = device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("alpha source"), layout, + entries: &[wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::TextureView(&view) }], + }); + (texture, view, bind) + } + pub fn resize(&mut self, device: &wgpu::Device, size: (u32, u32)) { + if (self.texture.width(), self.texture.height()) == (size.0.max(1), size.1.max(1)) { return; } + (self.texture, self.view, self.bind) = Self::target(device, &self.layout, self.format, size); + } + pub fn draw(&self, encoder: &mut wgpu::CommandEncoder, target: &wgpu::TextureView) { + let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { + label: Some("straight alpha"), + color_attachments: &[Some(wgpu::RenderPassColorAttachment { + view: target, depth_slice: None, resolve_target: None, + ops: wgpu::Operations { load: wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT), store: wgpu::StoreOp::Store }, + })], depth_stencil_attachment: None, timestamp_writes: None, occlusion_query_set: None, + multiview_mask: None, + }); + pass.set_pipeline(&self.pipeline); + pass.set_bind_group(0, &self.bind, &[]); + pass.draw(0..3, 0..1); + } +} diff --git a/app/vendor/rune/crates/rune/src/render/translucency.rs b/app/vendor/rune/crates/rune/src/render/translucency.rs new file mode 100644 index 0000000..50e3764 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/render/translucency.rs @@ -0,0 +1,82 @@ +//! Picking a GPU that composites translucent pixels on a surface. Some surfaces are opaque only: +//! a Win32 Vulkan surface on AMD's integrated GPUs, and any DXGI swapchain made from an HWND. A +//! transparent window or overlay drawn there shows black where it should be clear. Rune makes +//! DX12 surfaces through DirectComposition (`Gpu::instance`), which composites alpha on every +//! GPU, and gives a translucent surface the lowest-power adapter that composites it. +//! +//! On Windows only that DirectComposition swapchain composites alpha. A Vulkan surface there is +//! a swapchain on the HWND, whatever alpha modes its driver reports: a transparent window, +//! which has no redirection bitmap, shows it black or not at all (Hex #499, #510, on hybrid +//! laptops whose integrated GPU's Vulkan driver claimed premultiplied alpha). + +/// The alpha mode that composites translucent pixels on `surface` through `adapter`, if any. +pub(crate) fn mode(surface: &wgpu::Surface<'_>, adapter: &wgpu::Adapter) -> Option<wgpu::CompositeAlphaMode> { + if cfg!(target_os = "windows") && adapter.get_info().backend != wgpu::Backend::Dx12 { return None; } + let caps = surface.get_capabilities(adapter); + [wgpu::CompositeAlphaMode::PreMultiplied, wgpu::CompositeAlphaMode::PostMultiplied, wgpu::CompositeAlphaMode::Inherit] + .into_iter() + .find(|mode| caps.alpha_modes.contains(mode)) +} + +/// Whether `gpu` can draw `surface` with `wanted`'s features its adapter supports, and, for a +/// `translucent` surface, composite translucent pixels on it. +pub(crate) fn serves(gpu: &crate::render::Gpu, surface: &wgpu::Surface<'_>, wanted: wgpu::Features, translucent: bool) -> bool { + gpu.adapter.is_surface_supported(surface) + && gpu.device.features().contains(wanted & gpu.adapter.features()) + && crate::gpu::backend::serves(&gpu.device, wanted) + && (!translucent || mode(surface, &gpu.adapter).is_some()) +} + +/// `pick`'s adapter when it composites translucent pixels on `surface`; otherwise the adapter +/// on `instance` that does on the compositor's GPU (`gpu_pick`), then the lowest-power one that +/// does, or `pick`'s adapter when none can. When the compositor named its GPU, adapters on +/// others are never candidates, however their drivers answer: on GNOME with an NVIDIA card, whose +/// XWayland surfaces are opaque only, RADV and lavapipe claim premultiplied alpha for an overlay's +/// XWayland window but can't make its swapchain (hex#979, #982). It draws opaque there instead. +/// A software adapter never replaces a hardware one: on X11 with NVIDIA, whose surfaces are +/// opaque only, lavapipe claims premultiplied alpha, but its swapchain sends DRI3 requests +/// NVIDIA's Xorg refuses, and the X error lands in whichever window is next (hex#1216). The +/// hardware adapter draws opaque there, and an X compositor still blends its ARGB window. +#[cfg(not(target_arch = "wasm32"))] +pub(crate) fn prefer(instance: &wgpu::Instance, surface: &wgpu::Surface<'_>, pick: &crate::gpu::pick::Pick) -> wgpu::Adapter { + if mode(surface, &pick.adapter).is_some() { + return pick.adapter.clone(); + } + let mut able: Vec<_> = pollster::block_on(instance.enumerate_adapters(wgpu::Backends::all())) + .into_iter() + .filter(|candidate| { + let info = candidate.get_info(); + pick.shows(&info) && takes_over(pick.adapter.get_info().device_type, info.device_type) + && candidate.is_surface_supported(surface) && mode(surface, candidate).is_some() + }) + .collect(); + able.sort_by_key(|candidate| { + let info = candidate.get_info(); + (!pick.on_compositor_device(&info), crate::gpu::pick::power_rank(info.device_type)) + }); + able.into_iter().next().unwrap_or_else(|| pick.adapter.clone()) +} + +/// Whether an adapter of type `candidate` may draw a translucent surface in place of `pick`'s: +/// any but a software adapter, which may only stand in for another. +#[cfg(not(target_arch = "wasm32"))] +fn takes_over(pick: wgpu::DeviceType, candidate: wgpu::DeviceType) -> bool { + candidate != wgpu::DeviceType::Cpu || pick == wgpu::DeviceType::Cpu +} + +#[cfg(test)] +mod tests { + /// lavapipe never takes a translucent overlay from a hardware adapter (hex#1216), but a + /// hardware adapter may still take one from software, and GPUs from each other. + #[test] + fn software_never_takes_over_from_hardware() { + use super::takes_over; + use wgpu::DeviceType::*; + for hardware in [DiscreteGpu, IntegratedGpu, VirtualGpu, Other] { + assert!(!takes_over(hardware, Cpu), "{hardware:?}"); + assert!(takes_over(Cpu, hardware), "{hardware:?}"); + } + assert!(takes_over(DiscreteGpu, IntegratedGpu)); + assert!(takes_over(Cpu, Cpu)); + } +} diff --git a/app/vendor/rune/crates/rune/src/render/uber/dxbc_hash.rs b/app/vendor/rune/crates/rune/src/render/uber/dxbc_hash.rs new file mode 100644 index 0000000..eed94a1 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/render/uber/dxbc_hash.rs @@ -0,0 +1,8 @@ +// Written by `cargo run -p rune --example regen_dxbc` on Windows, the one way to regenerate the uber bytecode: +// it also writes the pinned fragments and their hashes (dxbc_pinned_hash.rs), which nothing else updates. +pub(super) const UBER_DXBC_WGSL_BLAKE3: &str = "54888f45682dd582361a4b0783101cdb88f5d7f4c7c6f315c8dedc406a188f4b"; +pub(super) const UBER_DXBC_ABI_FNV64: u64 = 0x6b9932e7795ec011; +#[cfg(test)] +pub(super) const UBER_DXBC_HLSL_BLAKE3: &str = "b9e32c1aa2b9a47c8a2fac7fb3aa86ba73bbe4ed2e719784a6ac27a628979fd1"; +#[cfg(test)] +pub(super) const UBER_DXBC_DUAL_HLSL_BLAKE3: &str = "dc7867c147533433b91d1d8358d15388fd2e8d4975c0cab7820a3bdd3312b2ec"; diff --git a/app/vendor/rune/crates/rune/src/render/uber/dxbc_pinned_hash.rs b/app/vendor/rune/crates/rune/src/render/uber/dxbc_pinned_hash.rs new file mode 100644 index 0000000..b924d86 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/render/uber/dxbc_pinned_hash.rs @@ -0,0 +1,6 @@ +// Written by `cargo run -p rune --example regen_dxbc` on Windows with uber.fs-k0/k1/k2.dxbc; nothing else writes them. +/// BLAKE3 of the WGSL each pinned fragment was compiled from (render/variant.rs `pinned_wgsl`, `PINNED` order). +pub(super) const UBER_DXBC_PINNED_WGSL_BLAKE3: [&str; 3] = ["1167292b3c2b91cdbf76e2f72971eda7922f3983c571a54eb1d3534526e24d9a", "6ccb754d19b24a58a1ae12bca1eb148e5264370d19f77f0fa63e516b44dda2f3", "5b804b75ff560e9da89f98214577fb1d651f3114c6f9c2866d0e1045e84f1077"]; +/// BLAKE3 of each pinned fragment's file, and of the `uber.vs.dxbc` it was compiled beside. +pub(super) const UBER_DXBC_PINNED_FS_BLAKE3: [&str; 3] = ["27f1ae9dc85c8a789d573fe175966fb8533e847a80b37ad7f592adb5409abf2a", "daaf0d13c697b270b4d22942414d2624146069b95752962ff8b4b5a4a8219feb", "c5bfbb288a39e79a59bc037d6e3e76f8e29dfbf5513460b6356ebf01e96fc923"]; +pub(super) const UBER_DXBC_PINNED_VS_BLAKE3: &str = "e6a25a34357594d88ffdbe2f8f6e242ee9b42aa46005cc71d067b4891bbdd42c"; diff --git a/app/vendor/rune/crates/rune/src/render/uber/metallib_hash.rs b/app/vendor/rune/crates/rune/src/render/uber/metallib_hash.rs new file mode 100644 index 0000000..c2ddc69 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/render/uber/metallib_hash.rs @@ -0,0 +1,15 @@ +// Generated by scripts/precompile-metal-shaders.sh, or refreshed from the freshness test when MSL is unchanged. +#[cfg(any(test, target_os = "macos"))] +pub(super) const UBER_WGSL_BLAKE3: &str = "321953684c57f92a08e8d125167db30e150c6c442886a49679c60c21fbcd8db8"; +#[cfg(any(test, target_os = "macos"))] +pub(super) const UBER_ABI_FNV64: u64 = 0xb462b40a6abf4cf1; +#[cfg(all(test, target_os = "macos"))] +pub(super) const UBER_MSL_OPTIONS_FNV64: u64 = 0x0eaa2a2ef8dcd514; +#[cfg(test)] +pub(super) const UBER_MSL_BLAKE3: &str = "9bd2e984b0be6622d77cbf6cb59676a701aa15351c12c760e84699857ba7b38c"; +#[cfg(test)] +pub(super) const UBER_METALLIB_FNV64: u64 = 0xa8e4d14d8a7c9f26; +#[cfg(all(test, target_os = "macos", feature = "metal-backend"))] +pub(super) const UBER_NATIVE_MSL_BLAKE3: &str = "5264d0cc6c71d1bf7a4bb78661261737c558d2ae87f81290ed77cf326bd270df"; +#[cfg(all(test, target_os = "macos", feature = "metal-backend"))] +pub(super) const UBER_NATIVE_METALLIB_FNV64: u64 = 0x582783c6850f4a17; diff --git a/app/vendor/rune/crates/rune/src/render/uber/pass_dxbc_hash.rs b/app/vendor/rune/crates/rune/src/render/uber/pass_dxbc_hash.rs new file mode 100644 index 0000000..3d0bda3 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/render/uber/pass_dxbc_hash.rs @@ -0,0 +1,5 @@ +// Written by `cargo run -p rune --example regen_dxbc` on Windows. +pub(super) const ALPHA_DXBC_WGSL_BLAKE3: &str = "5a5c19095cfb20f0b1281ffe424e89feb625a70015cd7629c46f9f432874309b"; +pub(super) const LAYER_BLUR_DXBC_WGSL_BLAKE3: &str = "aa3c4f0be11b22d24ba3cd91ff70168eb1520fc76dc323d51cab3ed5dd0048aa"; +pub(super) const BACKDROP_BLUR_DXBC_WGSL_BLAKE3: &str = "71d5e66fff21415bedc5d5bbc68554e20d95a8f5d3d57f9e1718fb063267b362"; +pub(super) const BACKDROP_COMPOSITE_DXBC_WGSL_BLAKE3: &str = "3d1630fc09197c719a90cf96ffcd4cc19c0444d6e433bf16899bd60da4fe9dd3"; diff --git a/app/vendor/rune/crates/rune/src/render/uber/windfoil_hash.rs b/app/vendor/rune/crates/rune/src/render/uber/windfoil_hash.rs new file mode 100644 index 0000000..49f2b28 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/render/uber/windfoil_hash.rs @@ -0,0 +1,3 @@ +// Generated by scripts/precompile-metal-shaders.sh. Empty until a Mac has built uber_windfoil.metallib. +pub(super) const WINDFOIL_WGSL_BLAKE3: &str = "54888f45682dd582361a4b0783101cdb88f5d7f4c7c6f315c8dedc406a188f4b"; +pub(super) const WINDFOIL_ABI_FNV64: u64 = 0x6b9932e7795ec011; diff --git a/app/vendor/rune/crates/rune/src/render/uber_wgsl.rs b/app/vendor/rune/crates/rune/src/render/uber_wgsl.rs new file mode 100644 index 0000000..9e1c367 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/render/uber_wgsl.rs @@ -0,0 +1,18 @@ +//! The uber shader's WGSL, Classic and Windfoil, joined when Rune builds (`build.rs`) with every +//! `\r\n` read as `\n`, and the BLAKE3 of each: the precompiled shaders are used when the hash +//! recorded beside them is this one, which the build knows, so a launch hashes nothing. + +include!(concat!(env!("OUT_DIR"), "/uber_wgsl.rs")); + +/// Whether two strings are equal, for constants. +#[cfg(any(target_os = "macos", target_os = "windows"))] +pub(super) const fn same(a: &str, b: &str) -> bool { + let (a, b) = (a.as_bytes(), b.as_bytes()); + if a.len() != b.len() { return false; } + let mut i = 0; + while i < a.len() { + if a[i] != b[i] { return false; } + i += 1; + } + true +} diff --git a/app/vendor/rune/crates/rune/src/render/upload.rs b/app/vendor/rune/crates/rune/src/render/upload.rs new file mode 100644 index 0000000..3ca9184 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/render/upload.rs @@ -0,0 +1,543 @@ +//! Per-frame uploads: instances, globals, glyph and image atlas rows, and GPU spring nodes. +//! +//! Writes go through the renderer's `Staging`, so a steady frame allocates no buffers. They are +//! recorded into the frame's encoder where the renderer first uses it (`flush_uploads`, at the +//! start of `encode_layers*` and `draw_target_range_with`), or submitted ahead of a draw into a +//! caller's pass (`draw_range*`) and of `Renderer::submit`. Globals are written only when they +//! change, and instances only in the spans that changed. + +use std::sync::atomic::{AtomicU64, Ordering}; + +use bytemuck::Zeroable; +use rune_staging::Staging; + +use super::*; + +/// Upload state: the staging, and what the instance and globals buffers hold. +pub(super) struct Uploads { + /// Made on the first upload, which brings the queue. + staging: Option<Staging>, + /// A compositor's `Frame::write_buffer`s, recorded into the frame's encoder as they come and + /// sealed when it's submitted. Apart from `staging`, whose `submit` would seal them early. + frame_writes: Option<Staging>, + /// The instance buffer's contents, so a frame writes only the span that changed. + instances: Vec<Instance>, + /// Whether `image_batches`, `effects` and `has_layers` were made from `instances`: false + /// once the list's length or an instance's `params` change, which can move a batch. + batched: bool, + /// Whether `instances` holds a layer. + has_layers: bool, + /// The viewport last written to globals (`width << 32 | height`, `u64::MAX` before any). + viewport: AtomicU64, + /// Gamma-space blend, byte-source, and packed scroll-fade stops last written to globals. + srgb: Option<(bool, bool, [u32; 2])>, + /// `Staging::lost` as last seen by `prepare` and by `upload_images`. + lost: (u64, u64), + /// The paint the next `prepare`'s instances come from, and which of them alone changed + /// since the last `prepare` of that paint (`Renderer::next_instances`). + next: Option<(u64, Option<Vec<u32>>)>, + /// The paint `instances` came from, when the last `prepare` was told it. + held_paint: Option<u64>, + /// The last `prepare` wrote only a loop-only frame's slots. + patched: bool, + #[cfg(test)] + pub(super) globals_writes: u64, + #[cfg(test)] + pub(super) batch_runs: u64, +} + +impl Default for Uploads { + fn default() -> Uploads { + Uploads { staging: None, frame_writes: None, instances: Vec::new(), batched: false, has_layers: false, viewport: AtomicU64::new(u64::MAX), srgb: None, lost: (0, 0), next: None, held_paint: None, patched: false, + #[cfg(test)] globals_writes: 0, #[cfg(test)] batch_runs: 0 } + } +} + +impl Uploads { + /// Forgets what the instance buffer holds, so the next frame writes and batches it all. + fn forget_instances(&mut self) { + self.instances.clear(); + self.batched = false; + self.held_paint = None; + } + + pub(super) fn staging(&mut self, device: &wgpu::Device, queue: &wgpu::Queue) -> Staging { + self.staging.get_or_insert_with(|| Staging::new(device, queue)).clone() + } + + /// Frees the staging chunks kept for reuse (`Renderer::give_back`). + pub(super) fn trim(&self) { + if let Some(staging) = &self.staging { staging.trim(); } + } + + #[cfg(test)] + pub(super) fn stats(&self) -> rune_staging::Stats { + self.staging.as_ref().map(Staging::stats).unwrap_or_default() + } + + #[cfg(all(test, feature = "test-gpu-counters"))] + pub(super) fn frame_write_stats(&self) -> rune_staging::Stats { + self.frame_writes.as_ref().map(Staging::stats).unwrap_or_default() + } +} + +/// Instances `write_instances` compares at once. +const BLOCK: usize = 64; + +/// Whether two equally long instance lists hold the same bytes. Folds over words into one +/// accumulator per word of an instance, which vectorizes, at about half the cost of a `memcmp`. +/// Words are `u32`, `Instance`'s own alignment, so any list casts. +fn same(a: &[Instance], b: &[Instance]) -> bool { + let words = |l| bytemuck::cast_slice::<Instance, [u32; INSTANCE_WORDS]>(l); + let mut acc = [0u32; INSTANCE_WORDS]; + for (x, y) in words(a).iter().zip(words(b)) { + for j in 0..INSTANCE_WORDS { acc[j] |= x[j] ^ y[j]; } + } + acc.iter().fold(0, |s, w| s | w) == 0 +} + +fn pack((w, h): (u32, u32)) -> u64 { u64::from(w) << 32 | u64::from(h) } + +impl Renderer { + /// Records pending uploads into `encoder`, ahead of the renderer's commands in it, and the + /// atlas fills staged after them. + pub(super) fn flush_uploads(&self, encoder: &mut wgpu::CommandEncoder) { + if let Some(s) = &self.uploads.staging { s.flush(encoder); } + self.encode_fills(encoder); + } + + /// Submits pending uploads (and atlas fills) ahead of commands already recorded. + pub(super) fn submit_uploads(&self) { + if self.fills.lock().unwrap_or_else(|e| e.into_inner()).is_some() { return self.submit_fills(); } + if let Some(s) = &self.uploads.staging { s.submit(); } + } + + /// Readies the frame's `encoder` for submission: submits pending uploads ahead of it, and + /// seals the compositor's writes recorded into it. + pub(crate) fn before_submit(&self, encoder: &mut wgpu::CommandEncoder) { + self.submit_uploads(); + if let Some(s) = &self.uploads.frame_writes { s.flush(encoder); } + } + + /// `Queue::write_buffer` through staging chunks, recorded into `encoder` here: ahead of the + /// commands recorded after it (`Frame::write_buffer`). A frame's writes share a chunk, which + /// `before_submit` hands back to the GPU. + pub(crate) fn write_buffer(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, encoder: &mut wgpu::CommandEncoder, + buffer: &wgpu::Buffer, offset: u64, data: &[u8]) { + let staging = self.uploads.frame_writes.get_or_insert_with(|| Staging::new(device, queue)); + staging.write_buffer(buffer, offset, data); + staging.record(encoder); + } + + /// Writes rows `y0..y1` of `texture` from its tightly packed CPU copy `data`. + fn write_rows(staging: &Staging, texture: &wgpu::Texture, data: &[u8], (y0, y1): (u32, u32)) { + if y1 <= y0 { return; } + let row = texture.width() * texture.format().block_copy_size(None).unwrap(); + staging.write_texture_rows(texture, y0, &data[(y0 * row) as usize..(y1 * row) as usize]); + } + + /// Uploads changed rows of the runtime's image atlas (`El::pixels`), creating its texture on + /// first use. + pub fn upload_images(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, images: &mut ImageAtlas) { + if images.pages.is_empty() && self.images.is_empty() { return self.refresh_layer_bindings(device); } + let staging = self.uploads.staging(device, queue); + if staging.lost() != self.uploads.lost.1 { + self.uploads.lost.1 = staging.lost(); + for page in &mut images.pages { page.dirty = Some((0, page.height)); } + } + let mut changed = self.images.len() != images.pages.len(); + self.images.resize_with(images.pages.len(), || None); + for (index, page) in images.pages.iter_mut().enumerate() { + if page.data.is_empty() { changed |= self.images[index].is_some(); self.images[index] = None; continue; } + if self.images[index].as_ref().is_none_or(|(t, _)| t.width() != page.width || t.height() != page.height) { + let texture = Self::image_texture(device, page.width, page.height); + let bind = Self::bind_group(device, &self.bind_layout, &self.globals, self.uber.outlines(), &self.atlas, &texture, None); + self.images[index] = Some((texture, bind)); + changed = true; + page.dirty = Some((0, page.height)); + } + let Some(rows) = page.dirty.take() else { continue }; + Self::write_rows(&staging, &self.images[index].as_ref().unwrap().0, &page.data, rows); + } + if changed { self.images_changed(); } + self.refresh_layer_bindings(device); + } + + /// Uploads several instance lists back to back (one buffer, one glyph upload) and returns + /// each list's instance range for `draw_range`. A compositor's version of `prepare`. + pub fn prepare_lists( + &mut self, + device: &wgpu::Device, + queue: &wgpu::Queue, + atlas: &mut Atlas, + lists: &[&[Instance]], + viewport: (u32, u32), + ) -> Vec<std::ops::Range<u32>> { + let mut all = Vec::with_capacity(lists.iter().map(|l| l.len()).sum()); + let mut ranges = Vec::with_capacity(lists.len()); + for l in lists { + let a = all.len() as u32; + all.extend_from_slice(l); + ranges.push(a..all.len() as u32); + } + self.prepare(device, queue, atlas, &all, viewport); + ranges + } + + pub(super) fn instance_buffer(device: &wgpu::Device, capacity: usize) -> wgpu::Buffer { + device.create_buffer(&wgpu::BufferDescriptor { + label: Some("instances"), + size: (capacity * std::mem::size_of::<Instance>()) as u64, + usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + }) + } + + /// Uploads instances, globals and any new glyphs. They land ahead of the renderer's next draw: + /// recorded into the encoder it draws into, which must then be submitted, or submitted ahead + /// of a `draw_range` and of `submit`. + pub fn prepare( + &mut self, + device: &wgpu::Device, + queue: &wgpu::Queue, + atlas: &mut Atlas, + instances: &[Instance], + viewport: (u32, u32), + ) { + // A caller may draw these lists into several different formats with draw_range. + self.prepare_with_precision(device, queue, atlas, instances, viewport, false); + } + + /// The default UI pass draws the root into one known target. Its float intermediate layers + /// have their own projection and keep their source precision in the shader. + pub(crate) fn prepare_ui(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, atlas: &mut Atlas, + instances: &[Instance], viewport: (u32, u32)) { + let bytes = self.srgb_blend && matches!(self.format, wgpu::TextureFormat::Bgra8Unorm | wgpu::TextureFormat::Rgba8Unorm); + self.prepare_with_precision(device, queue, atlas, instances, viewport, bytes); + } + + fn prepare_with_precision(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, atlas: &mut Atlas, + instances: &[Instance], viewport: (u32, u32), byte_source: bool) { + if self.springs.is_some() { assert_eq!(instances.len(), self.spring_instances); } + // The pinned pipelines (`variant::start_pinned`): asked for at the first prepare, taken once their thread has them. + if self.pinned.is_none() && self.pinned_building.is_none() { self.start_pinned(device); } + self.take_pinned(); + #[cfg(feature = "frame-profile")] + super::report_pinned(); + let staging = self.uploads.staging(device, queue); + if staging.lost() != self.uploads.lost.0 { + self.uploads.lost.0 = staging.lost(); + self.resend_uploads(atlas); + } + // The Windfoil shader, built the first time text draws from outlines (render/variant.rs), + // fills atlas pages on the GPU, so the pages are made again as ones it can draw into. + if atlas.outlines.has_records() && self.select(device, variant::Event::OutlinesWanted) { + self.atlas = Self::atlas_texture(device, true, self.atlas.height()); + for page in &mut self.atlas_pages { page.0 = Self::atlas_texture(device, true, ATLAS_SIZE); } + self.rebind_all(device); + atlas.invalidate(); + } + // The first page's texture grows with what its shelves hold (or explicit dirty rows); a + // new one starts empty, so every placed row goes up again and every GPU-filled mask is + // filled again (`invalidate`). + let dirty_rows = atlas.dirty; + let rows = atlas.page_rows(0).max(dirty_rows.map_or(0, |(_, y1)| y1)); + if rows > self.atlas.height() { + let height = rows.next_power_of_two().clamp(ATLAS_START_ROWS, ATLAS_SIZE); + self.atlas = Self::atlas_texture(device, self.uber.outlines().is_some(), height); + self.rebind_all(device); + atlas.invalidate(); + if let Some((a, b)) = dirty_rows { + atlas.dirty = Some(atlas.dirty.map_or((a, b), |(c, d)| (a.min(c), b.max(d)))); + } + } + atlas.outlines.set_support(self.uber.support()); + self.lcd_frame = self.lcd_ready(device, atlas.lcd_wanted) && atlas.lcd; + if let Some(rows) = atlas.dirty.take() { + atlas.rows_uploaded(0, rows); + Self::write_rows(&staging, &self.atlas, &atlas.data, rows); + } + let mut atlas_changed = self.atlas_pages.len() > atlas.pages.len(); + self.atlas_pages.truncate(atlas.pages.len()); + let filled = self.uber.outlines().is_some(); + for index in 0..atlas.pages.len() { + if index >= self.atlas_pages.len() { + let texture = Self::atlas_texture(device, filled, ATLAS_SIZE); + let bind = Self::bind_group(device, &self.bind_layout, &self.globals, self.uber.outlines(), &texture, &texture, None); + self.atlas_pages.push((texture, bind)); + atlas_changed = true; + } + if let Some(rows) = atlas.pages[index].dirty.take() { + atlas.rows_uploaded(index + 1, rows); + Self::write_rows(&staging, &self.atlas_pages[index].0, &atlas.pages[index].data, rows); + } + } + if atlas_changed { self.images_changed(); } + self.upload_outlines(device, &staging, atlas); + self.fill_atlas(device, queue, &staging, atlas); + if self.instances.ensure(device, instances.len()) { + self.uploads.forget_instances(); + } + self.write_instances(&staging, instances); + // Geometry uploads must preserve a presentation timestamp already latched this frame. + if self.uploads.viewport.swap(pack(viewport), Ordering::Relaxed) != pack(viewport) { + staging.write_buffer(&self.globals, std::mem::offset_of!(Globals, viewport) as u64, bytemuck::cast_slice(&[viewport.0 as f32, viewport.1 as f32])); + #[cfg(test)] { self.uploads.globals_writes += 1; } + } + let mode = (self.srgb_blend, byte_source, [self.fade_stops[0].to_bits(), self.fade_stops[1].to_bits()]); + if self.uploads.srgb.replace(mode) != Some(mode) { + let flags: [f32; 4] = [self.srgb_blend as u8 as f32, byte_source as u8 as f32, self.fade_stops[0], self.fade_stops[1]]; + staging.write_buffer(&self.globals, std::mem::offset_of!(Globals, flags) as u64, bytemuck::cast_slice(&flags)); + #[cfg(test)] { self.uploads.globals_writes += 1; } + } + self.count = instances.len() as u32; + if !self.uploads.batched { + self.batch(instances); + } else { + // Same batches: only the effects' copies of their instances can be out of date. + for (at, effect) in &mut self.effects { *effect = instances[*at as usize]; } + } + let has_layers = self.uploads.has_layers; + // A loop-only frame that draws no layer leaves them as the last frame drew them. + #[cfg(any(target_os = "windows", target_arch = "wasm32"))] + let layers_kept = self.uploads.patched && self.cycle_leaves_layers(); + #[cfg(not(any(target_os = "windows", target_arch = "wasm32")))] + let layers_kept = false; + if !layers_kept { self.prepare_layers(device, queue, if has_layers { instances } else { &[] }, viewport); } + self.sync_resident_caches(&mut atlas.resident_caches); + self.backdrop_used = self.effects.iter().any(|(_, i)| i.params[0] != 0.0 || i.kind() == Some(Kind::BackdropBlur)); + if self.backdrop_used { + self.ensure_backdrop(device, self.format, viewport); + for index in 0..self.extra.len() { + self.ensure_backdrop(device, self.extra[index].0, viewport); + } + if self.layers.targets.iter().any(Option::is_some) { + self.ensure_backdrop(device, layers::FORMAT, viewport); + } + } + self.prepare_backdrop_blur(device, queue, viewport); + #[cfg(all(feature = "alloc-sites", not(target_arch = "wasm32")))] + self.report_pools(); + } + + /// A window's or overlay's first native surface: its renderer's pipeline compiles on a thread + /// of its own, and `done` runs once it's ready (the window's live wake, so the next frame + /// draws it). Until then `prepare_surfaces` draws no surface: a clip that's opening has no + /// picture yet anyway. Without this call, `prepare_surfaces` compiles in place. + pub(crate) fn build_surfaces(&mut self, device: &wgpu::Device, draws: &[crate::native_surface::SurfaceDraw], done: impl FnOnce() + Send + 'static) { + if draws.is_empty() || self.surfaces.is_some() || self.surfaces_building.is_some() { return; } + self.surfaces_building = Some(crate::native_surface::SurfaceRenderer::build(device, self.format, Box::new(done))); + } + + /// Punches these native surfaces' places out of the window's pixels from the next + /// `prepare_surfaces` on, for clips shown on their own layer underneath (Windows). + #[cfg(target_os = "windows")] + pub(crate) fn set_punched_surfaces(&mut self, keys: Vec<usize>) { + if let Some(s) = &mut self.surfaces { s.set_punched(keys); } + } + + /// The punch pipeline has compiled (`set_punched_surfaces`). + #[cfg(target_os = "windows")] + pub(crate) fn surface_punch_ready(&mut self) -> bool { + self.surfaces.as_mut().is_some_and(crate::native_surface::SurfaceRenderer::punch_ready) + } + + /// Whether the last frame drew surface `key` inside an isolated layer; None when it didn't + /// draw it. + #[cfg(target_os = "windows")] + pub(crate) fn surface_drew_isolated(&self, key: usize) -> Option<bool> { + self.surfaces.as_ref().and_then(|s| s.drew_isolated(key)) + } + + pub fn prepare_surfaces(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, draws: &[crate::native_surface::SurfaceDraw], viewport: (u32,u32)) { + let built = match &self.surfaces_building { + Some(building) => crate::native_surface::SurfaceRenderer::finish(device, building), + None => None, + }; + if built.is_some() { self.surfaces_building = None; } + if self.surfaces.is_none() && self.surfaces_building.is_some() { return; } + if (!draws.is_empty() || built.is_some()) && self.surfaces.is_none() { + let mut surfaces = built.unwrap_or_else(|| crate::native_surface::SurfaceRenderer::new(device, self.format)); + surfaces.set_srgb_blend(self.srgb_blend); + surfaces.set_staging(self.uploads.staging(device, queue)); + for (format, _) in &self.extra { surfaces.add_format(device, *format); } + self.surfaces = Some(surfaces); + } + if let Some(s) = &mut self.surfaces { + s.set_srgb_blend(self.srgb_blend); + if self.layers.additive.is_some() { s.add_plus_lighter(device, layers::FORMAT); } + s.prepare(device,queue,draws,viewport); + } + if self.layer_stats().targets > 0 { self.position_layer_surfaces(queue); } + } + + /// One uniform write per presentation-only frame; use the display's target time. + pub fn present_at(&self, queue: &wgpu::Queue, viewport: (u32, u32), time: f64) { + const _: () = assert!(std::mem::offset_of!(Globals, viewport) == 0 && std::mem::offset_of!(Globals, pad) == 8); + let t = crate::gpu::springs::split_time(time); + let data = [viewport.0 as f32, viewport.1 as f32, t[0], t[1]]; + self.uploads.viewport.store(pack(viewport), Ordering::Relaxed); + let offset = std::mem::offset_of!(Globals, viewport) as u64; + match &self.uploads.staging { + Some(s) => s.write_buffer(&self.globals, offset, bytemuck::cast_slice(&data)), + None => queue.write_buffer(&self.globals, offset, bytemuck::cast_slice(&data)), + } + } + + /// A retarget touches one node record; caller computes inherited position/velocity on CPU. + pub fn write_spring_node(&mut self, queue: &wgpu::Queue, id: usize, node: &crate::gpu::springs::Node) { + let properties = self.springs.as_mut().expect("renderer has no GPU springs"); + assert!(id < properties.deadlines.len()); + properties.deadlines[id] = node.settle_at(); + properties.settle_at = properties.deadlines.iter().copied().fold(0.0, f64::max); + let offset = (id * std::mem::size_of::<crate::gpu::springs::Node>()) as u64; + match &self.uploads.staging { + Some(s) => s.write_buffer(&properties.nodes, offset, bytemuck::bytes_of(node)), + None => queue.write_buffer(&properties.nodes, offset, bytemuck::bytes_of(node)), + } + } + + /// Splits the instances into runs that bind the same atlas pages, and notes their effects + /// and whether they hold a layer. + fn batch(&mut self, instances: &[Instance]) { + self.image_batches.clear(); + self.kinds.clear(); + self.kinds.extend(instances.iter().map(Instance::kind)); + let (mut start, mut bind) = (0, BatchBind::Image(0)); + let mut has_layers = false; + self.effects.clear(); + for (i, instance) in instances.iter().enumerate() { + let Some(kind) = instance.kind() else { continue }; + let next_bind = match kind { + Kind::Rect | Kind::Shadow | Kind::Inset | Kind::Gradient | Kind::Segment + | Kind::Triangle | Kind::LayerEnd | Kind::Dashed | Kind::Radial => continue, + Kind::Layer => { has_layers = true; continue; } + Kind::Effect | Kind::BackdropBlur => { self.effects.push((i as u32, *instance)); continue; } + Kind::Image => Some(BatchBind::Image(instance.params[0] as usize)), + Kind::Glyph => { + let g = instance.params[2] as usize; + if g == 0 { + match bind { + BatchBind::Image(_) => None, + BatchBind::Glyph(_) => Some(BatchBind::Image(0)), + } + } else { + Some(BatchBind::Glyph(g - 1)) + } + } + }; + if let Some(next) = next_bind && next != bind { + if start < i as u32 { self.image_batches.push((start..i as u32, bind)); } + start = i as u32; + bind = next; + } + } + if start < instances.len() as u32 { self.image_batches.push((start..instances.len() as u32, bind)); } + self.uploads.has_layers = has_layers; + self.uploads.batched = true; + #[cfg(test)] { self.uploads.batch_runs += 1; } + } + + /// Writes the spans of instances that differ from what the buffer holds, comparing a block + /// at a time. Spans less than a block apart merge, so a scroll writes one span and a frame + /// where a few instances move writes only those. A span whose `params` changed asks `prepare` + /// to batch again. + fn write_instances(&mut self, staging: &Staging, instances: &[Instance]) { + let next = self.uploads.next.take(); + self.uploads.patched = false; + if let Some((paint, Some(patched))) = &next && self.uploads.held_paint == Some(*paint) && instances.len() == self.uploads.instances.len() { + self.uploads.patched = true; + return self.write_patched(staging, instances, patched); + } + self.uploads.held_paint = next.map(|n| n.0); + let held = &mut self.uploads.instances; + let shared = instances.len().min(held.len()); + let mut rebatch = instances.len() != held.len(); + held.resize(instances.len(), Instance::zeroed()); + let mut open: Option<std::ops::Range<usize>> = None; + for start in (0..shared).step_by(BLOCK) { + let end = (start + BLOCK).min(shared); + let differs = |i: &usize| !same(&instances[*i..=*i], &held[*i..=*i]); + // The first instance alone, so a block that all moved costs one compare to find. + let first = if differs(&start) { start } else if same(&instances[start..end], &held[start..end]) { continue } else { + (start + 1..end).find(differs).unwrap_or(start) + }; + let last = (first..end).rfind(differs).map_or(end, |i| i + 1); + rebatch |= Self::join(self.instances.buffer(), held, staging, instances, &mut open, first..last); + } + if instances.len() > shared { rebatch |= Self::join(self.instances.buffer(), held, staging, instances, &mut open, shared..instances.len()); } + if let Some(span) = open { rebatch |= Self::write_span(self.instances.buffer(), held, staging, instances, span); } + self.uploads.batched &= !rebatch; + } + + /// Writes only `patched` (ascending): the instances a loop-only frame changed (a dot's colour, + /// a sliding window's clip) since the buffer was written from the same paint, so nothing else + /// needs comparing. Batches split on the image, kind and atlas page (`params` 0 to 2): only a + /// change there can move one. + fn write_patched(&mut self, staging: &Staging, instances: &[Instance], patched: &[u32]) { + let held = &mut self.uploads.instances; + debug_assert!(held.iter().zip(instances).enumerate().all(|(n, (h, i))| patched.binary_search(&(n as u32)).is_ok() || same(std::slice::from_ref(h), std::slice::from_ref(i))), + "a loop-only frame changed an instance that isn't one of its slots"); + let mut rebatch = false; + let mut k = 0; + while k < patched.len() { + let start = patched[k] as usize; + let mut end = start + 1; + while k + 1 < patched.len() && patched[k + 1] as usize == end { k += 1; end += 1; } + k += 1; + if end > instances.len() || same(&instances[start..end], &held[start..end]) { continue; } + rebatch |= held[start..end].iter().zip(&instances[start..end]).any(|(h, i)| h.params[..3] != i.params[..3]); + held[start..end].copy_from_slice(&instances[start..end]); + let offset = (start * std::mem::size_of::<Instance>()) as u64; + staging.write_buffer(self.instances.buffer(), offset, bytemuck::cast_slice(&instances[start..end])); + } + self.uploads.batched &= !rebatch; + } + + /// The instances the buffer holds, when they are paint `paint`'s and `len` of them. + #[cfg_attr(not(any(target_os = "windows", target_arch = "wasm32")), allow(dead_code))] + pub(super) fn held_instances(&self, paint: u64, len: usize) -> Option<&[Instance]> { + (self.uploads.held_paint == Some(paint) && self.uploads.instances.len() == len).then_some(&self.uploads.instances[..]) + } + + /// The next `prepare`'s instances are paint `paint`'s (`runtime/paint/cycle.rs`). With + /// `patched`, only those instances changed since the last `prepare` of the same paint. + pub(crate) fn next_instances(&mut self, paint: u64, patched: Option<Vec<u32>>) { + self.uploads.next = Some((paint, patched)); + } + + /// Adds `span` to the open span if it is less than a block past it, or writes the open span + /// and opens `span`. True if it wrote a span whose `params` changed. + fn join(buffer: &wgpu::Buffer, held: &mut [Instance], staging: &Staging, instances: &[Instance], + open: &mut Option<std::ops::Range<usize>>, span: std::ops::Range<usize>) -> bool { + match open { + Some(o) if span.start <= o.end + BLOCK => { o.end = span.end; false } + _ => open.replace(span).is_some_and(|o| Self::write_span(buffer, held, staging, instances, o)), + } + } + + /// Writes `span`, and says whether any of its instances' `params`, which pick their batch, + /// changed. + fn write_span(buffer: &wgpu::Buffer, held: &mut [Instance], staging: &Staging, instances: &[Instance], span: std::ops::Range<usize>) -> bool { + let params = |i: &Instance| bytemuck::cast::<[f32; 4], u128>(i.params); + let rebatch = held[span.clone()].iter().zip(&instances[span.clone()]).any(|(h, i)| params(h) != params(i)); + held[span.clone()].copy_from_slice(&instances[span.clone()]); + let offset = (span.start * std::mem::size_of::<Instance>()) as u64; + staging.write_buffer(buffer, offset, bytemuck::cast_slice(&instances[span])); + rebatch + } + + /// The staging lost writes (an encoder holding them was dropped unsubmitted): forget what + /// the buffers are thought to hold, so this frame writes it all again. + fn resend_uploads(&mut self, atlas: &mut Atlas) { + self.uploads.forget_instances(); + self.uploads.viewport.store(u64::MAX, Ordering::Relaxed); + self.uploads.srgb = None; + atlas.resend_rows(); + atlas.outlines.invalidate(); + self.layers.forget_blur_uniforms(); + } +} + +#[cfg(test)] +mod tests; diff --git a/app/vendor/rune/crates/rune/src/render/upload/tests.rs b/app/vendor/rune/crates/rune/src/render/upload/tests.rs new file mode 100644 index 0000000..cbe6193 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/render/upload/tests.rs @@ -0,0 +1,354 @@ +use super::*; + +const SIZE: (u32, u32) = (64, 32); +const RED: [u8; 4] = [255, 0, 0, 255]; +const CLEAR: [u8; 4] = [0, 0, 0, 0]; + +fn square(x: f32, y: f32) -> Instance { + Instance { rect: [x, y, 8.0, 8.0], fill: [1.0, 0.0, 0.0, 1.0], clip: NO_CLIP, ..Zeroable::zeroed() } +} + +/// A moving square over a still grid of small ones. +fn scene(frame: usize) -> Vec<Instance> { + let grid = (0..48).map(|i| Instance { rect: [(i % 16) as f32 * 4.0, (i / 16) as f32 * 4.0, 1.0, 1.0], ..square(0.0, 0.0) }); + std::iter::once(square(frame as f32, 20.0)).chain(grid).collect() +} + +#[cfg(feature = "test-gpu-counters")] +fn live_buffers(device: &wgpu::Device) -> isize { + device.get_internal_counters().hal.buffers.read() +} + +fn pixel(pixels: &[u8], x: u32, y: u32) -> [u8; 4] { + let at = ((y * SIZE.0 + x) * 4) as usize; + pixels[at..at + 4].try_into().unwrap() +} + +#[cfg(feature = "test-gpu-counters")] +#[test] +fn a_steady_animating_frame_creates_no_buffers_and_skips_unchanged_globals() { + let gpu = Gpu::headless(); + let (device, queue) = (&gpu.device, &gpu.queue); + let mut renderer = Renderer::new(device, OFFSCREEN_FORMAT); + let mut text = crate::text::TextSystem::new(&[], ("Inter", "Inter")); + let target = Offscreen::new(device, SIZE.0, SIZE.1); + let mut pixels = Vec::new(); + for frame in 0..24 { + let (buffers, globals, stats) = (live_buffers(device), renderer.uploads.globals_writes, renderer.uploads.stats()); + renderer.prepare(device, queue, &mut text.atlas, &scene(frame), SIZE); + let mut encoder = device.create_command_encoder(&Default::default()); + renderer.draw(&mut encoder, &target.view, [0.0; 4]); + // Before the submit, while a queue write's staging buffer would still be alive. + let created = live_buffers(device) - buffers; + if frame == 23 { target.copy(&mut encoder); } + renderer.submit(queue, encoder); + device.poll(wgpu::PollType::wait_indefinitely()).unwrap(); + if frame < 4 { continue; } + let now = renderer.uploads.stats(); + assert_eq!(created, 0, "frame {frame} created buffers"); + assert_eq!(now.chunks, stats.chunks, "frame {frame} made a staging chunk"); + assert_eq!(renderer.uploads.globals_writes, globals, "frame {frame} rewrote unchanged globals"); + assert_eq!((now.writes - stats.writes, now.bytes - stats.bytes), (1, size_of::<Instance>() as u64), + "frame {frame} writes only the instance that moved"); + // Written in place where the backend can (`rune_staging::set_direct`), else staged. + let staged = u64::from(now.direct == stats.direct); + assert_eq!((now.flushes - stats.flushes, now.submits - stats.submits), (staged, 0), "recorded into the frame"); + } + pixels.extend(target.read(device)); + assert_eq!(pixel(&pixels, 27, 24), RED, "the square reached its last position"); + assert_eq!(pixel(&pixels, 2, 24), CLEAR, "and left its first"); +} + +/// Instances that moved far apart are written alone, ones close together as one span, and every +/// write lands: the frame draws each square where it is now. +#[test] +fn instances_are_written_in_the_spans_that_changed() { + let gpu = Gpu::headless(); + let (device, queue) = (&gpu.device, &gpu.queue); + let mut renderer = Renderer::new(device, OFFSCREEN_FORMAT); + let mut text = crate::text::TextSystem::new(&[], ("Inter", "Inter")); + let target = Offscreen::new(device, SIZE.0, SIZE.1); + let hidden = square(-100.0, -100.0); + // Two short of a power of two, so the instances added below fit the buffer. + let (far, last) = (2 * BLOCK + 10, 4 * BLOCK - 3); + let mut instances = vec![hidden; last + 1]; + let mut frame = |instances: &[Instance]| { + let stats = renderer.uploads.stats(); + renderer.prepare(device, queue, &mut text.atlas, instances, SIZE); + let mut encoder = device.create_command_encoder(&Default::default()); + renderer.draw(&mut encoder, &target.view, [0.0; 4]); + target.copy(&mut encoder); + renderer.submit(queue, encoder); + let now = renderer.uploads.stats(); + ((now.writes - stats.writes, (now.bytes - stats.bytes) / size_of::<Instance>() as u64), target.read(device)) + }; + frame(&instances); + (instances[3], instances[far], instances[last]) = (square(0.0, 0.0), square(20.0, 0.0), square(40.0, 0.0)); + let (written, pixels) = frame(&instances); + assert_eq!(written, (3, 3), "three far apart instances, written alone"); + for x in [4, 24, 44] { assert_eq!(pixel(&pixels, x, 4), RED, "the square at {x} landed"); } + (instances[far], instances[far + 10], instances[far + 25]) = (hidden, square(20.0, 20.0), square(40.0, 20.0)); + let (written, pixels) = frame(&instances); + assert_eq!(written, (1, 26), "close together, one span from the first to the last"); + assert_eq!(pixel(&pixels, 24, 4), CLEAR, "the square that left"); + for x in [24, 44] { assert_eq!(pixel(&pixels, x, 24), RED, "the square at {x}, 24 landed"); } + instances.extend([square(56.0, 0.0), hidden]); + let (written, pixels) = frame(&instances); + assert_eq!(written, (1, 2), "added instances"); + assert_eq!(pixel(&pixels, 60, 4), RED); + instances.iter_mut().for_each(|i| i.rect[1] += 1.0); + assert_eq!(frame(&instances).0, (1, last as u64 + 3), "everything moved: one span"); +} + +/// The upload has no encoder to go into when the first draw is into a caller's pass, and a +/// caller may submit without `Renderer::submit`. +#[test] +fn uploads_land_before_a_draw_into_a_callers_pass() { + let gpu = Gpu::headless(); + let (device, queue) = (&gpu.device, &gpu.queue); + let mut renderer = Renderer::new(device, OFFSCREEN_FORMAT); + let mut text = crate::text::TextSystem::new(&[], ("Inter", "Inter")); + let target = Offscreen::new(device, SIZE.0, SIZE.1); + for x in [0.0, 30.0] { + renderer.prepare(device, queue, &mut text.atlas, &[square(x, 4.0)], SIZE); + let mut encoder = device.create_command_encoder(&Default::default()); + { + let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { + label: None, + color_attachments: &[Some(wgpu::RenderPassColorAttachment { + view: &target.view, depth_slice: None, resolve_target: None, + ops: wgpu::Operations { load: wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT), store: wgpu::StoreOp::Store }, + })], + depth_stencil_attachment: None, timestamp_writes: None, occlusion_query_set: None, multiview_mask: None, + }); + renderer.draw_range(&mut pass, OFFSCREEN_FORMAT, 0..1); + } + target.copy(&mut encoder); + queue.submit([encoder.finish()]); + let pixels = target.read(device); + assert_eq!(pixel(&pixels, x as u32 + 4, 8), RED); + } +} + +/// Writes recorded into an encoder that is then dropped never land; the next frame sends what +/// it would otherwise skip as unchanged. +#[test] +fn a_dropped_encoder_makes_the_next_frame_resend_everything() { + let gpu = Gpu::headless(); + let (device, queue) = (&gpu.device, &gpu.queue); + let mut renderer = Renderer::new(device, OFFSCREEN_FORMAT); + let mut text = crate::text::TextSystem::new(&[], ("Inter", "Inter")); + let target = Offscreen::new(device, SIZE.0, SIZE.1); + let instances = [square(10.0, 10.0)]; + renderer.prepare(device, queue, &mut text.atlas, &instances, SIZE); + let mut encoder = device.create_command_encoder(&Default::default()); + renderer.draw(&mut encoder, &target.view, [0.0; 4]); + drop(encoder); + renderer.prepare(device, queue, &mut text.atlas, &instances, SIZE); + let mut encoder = device.create_command_encoder(&Default::default()); + renderer.draw(&mut encoder, &target.view, [0.0; 4]); + target.copy(&mut encoder); + renderer.submit(queue, encoder); + assert_eq!(pixel(&target.read(device), 14, 14), RED); +} + +/// `Frame::write_buffer`: each write lands ahead of the commands recorded after it, and a frame's +/// writes share one reused staging chunk rather than making a buffer each, as a queue write would. +#[cfg(feature = "test-gpu-counters")] +#[test] +fn compositor_buffer_writes_land_in_order_and_reuse_staging() { + let gpu = Gpu::headless(); + let (device, queue) = (&gpu.device, &gpu.queue); + let mut renderer = Renderer::new(device, OFFSCREEN_FORMAT); + let uniforms = device.create_buffer(&wgpu::BufferDescriptor { + label: None, size: 16, usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::COPY_SRC, mapped_at_creation: false, + }); + let readback = device.create_buffer(&wgpu::BufferDescriptor { + label: None, size: 32, usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ, mapped_at_creation: false, + }); + for frame in 0..12u32 { + let buffers = live_buffers(device); + let mut encoder = device.create_command_encoder(&Default::default()); + let allocs = crate::tooling::test_alloc::allocs(); + renderer.write_buffer(device, queue, &mut encoder, &uniforms, 0, bytemuck::cast_slice(&[frame; 4])); + let first = crate::tooling::test_alloc::allocs() - allocs; + encoder.copy_buffer_to_buffer(&uniforms, 0, &readback, 0, 16); + let allocs = crate::tooling::test_alloc::allocs(); + renderer.write_buffer(device, queue, &mut encoder, &uniforms, 0, bytemuck::cast_slice(&[frame + 100; 4])); + let second = crate::tooling::test_alloc::allocs() - allocs; + encoder.copy_buffer_to_buffer(&uniforms, 0, &readback, 16, 16); + let created = live_buffers(device) - buffers; + renderer.submit(queue, encoder); + let slice = readback.slice(..); + slice.map_async(wgpu::MapMode::Read, |_| {}); + device.poll(wgpu::PollType::wait_indefinitely()).unwrap(); + let words: Vec<u32> = bytemuck::cast_slice(&slice.get_mapped_range().unwrap()).to_vec(); + readback.unmap(); + assert_eq!(words, [[frame; 4], [frame + 100; 4]].concat(), "frame {frame}: each write before the copy after it"); + let stats = renderer.uploads.frame_write_stats(); + let staged = u64::from(stats.direct == 0); + assert_eq!(stats.chunks, staged, "frame {frame}: the writes share one chunk, reused once the GPU is done"); + if frame >= 2 { + assert_eq!(created, 0, "frame {frame} created buffers"); + // A queue write allocates 6 or 7 times; the first command in a new encoder grows its list once. + assert!(first <= 1 && second == 0, "frame {frame}: the writes allocated {first} and {second} times"); + } + } +} + +#[test] +fn a_frame_with_nothing_to_upload_never_touches_the_staging() { + let gpu = Gpu::headless(); + let (device, queue) = (&gpu.device, &gpu.queue); + let mut renderer = Renderer::new(device, OFFSCREEN_FORMAT); + renderer.upload_images(device, queue, &mut ImageAtlas::default()); + assert!(renderer.uploads.staging.is_none(), "no images, no staging"); + let uniforms = device.create_buffer(&wgpu::BufferDescriptor { + label: None, size: 16, usage: wgpu::BufferUsages::COPY_DST, mapped_at_creation: false, + }); + let mut encoder = device.create_command_encoder(&Default::default()); + renderer.write_buffer(device, queue, &mut encoder, &uniforms, 0, bytemuck::cast_slice(&[1u32; 4])); + let writes = renderer.uploads.frame_writes.clone().unwrap(); + assert!(writes.busy() || writes.stats().direct == 1, "recorded, its chunk still mapped, or written in place"); + renderer.before_submit(&mut encoder); + assert!(!writes.busy(), "sealed into the frame"); + let flushes = writes.stats().flushes; + renderer.before_submit(&mut encoder); + assert_eq!(writes.stats().flushes, flushes); + queue.submit([encoder.finish()]); +} + +/// A compositor asking for `IMMEDIATES` gets the adapter's immediate size and can colour a +/// draw with `set_immediates`, no buffer written. +#[test] +fn a_device_asked_for_immediates_draws_with_them() { + let Ok(gpu) = Gpu::try_with_features(Gpu::instance(), None, wgpu::Features::IMMEDIATES) else { return }; + let device = &gpu.device; + if !device.features().contains(wgpu::Features::IMMEDIATES) { return; } + assert!(device.limits().max_immediate_size >= 16, "the limit came with the feature"); + let plain = Gpu::headless(); + if crate::gpu::backend::native(&plain.device) { + assert!(plain.device.features().contains(wgpu::Features::IMMEDIATES), "free on the native backend, so always there"); + } else { + assert_eq!(plain.device.limits().max_immediate_size, 0, "only when asked"); + } + let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor { + label: None, + source: wgpu::ShaderSource::Wgsl(" + // A struct: naga's HLSL output has no immediates of other types (wgpu#5683). + struct Fill { colour: vec4<f32> } + var<immediate> fill: Fill; + @vertex fn vs(@builtin(vertex_index) i: u32) -> @builtin(position) vec4<f32> { + return vec4<f32>(vec2<f32>(f32((i << 1u) & 2u), f32(i & 2u)) * 2.0 - 1.0, 0.0, 1.0); + } + @fragment fn fs() -> @location(0) vec4<f32> { return fill.colour; } + ".into()), + }); + let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { label: None, bind_group_layouts: &[], immediate_size: 16 }); + let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { + label: None, layout: Some(&layout), + vertex: wgpu::VertexState { module: &shader, entry_point: Some("vs"), compilation_options: Default::default(), buffers: &[] }, + fragment: Some(wgpu::FragmentState { + module: &shader, entry_point: Some("fs"), compilation_options: Default::default(), + targets: &[Some(OFFSCREEN_FORMAT.into())], + }), + primitive: Default::default(), depth_stencil: None, multisample: Default::default(), multiview_mask: None, cache: None, + }); + let target = Offscreen::new(device, SIZE.0, SIZE.1); + let mut encoder = device.create_command_encoder(&Default::default()); + { + let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { + label: None, + color_attachments: &[Some(wgpu::RenderPassColorAttachment { + view: &target.view, resolve_target: None, depth_slice: None, + ops: wgpu::Operations { load: wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT), store: wgpu::StoreOp::Store }, + })], + ..Default::default() + }); + pass.set_pipeline(&pipeline); + pass.set_immediates(0, bytemuck::cast_slice(&[1.0f32, 0.0, 0.0, 1.0])); + pass.draw(0..3, 0..1); + } + target.copy(&mut encoder); + gpu.queue.submit([encoder.finish()]); + assert_eq!(pixel(&target.read(device), 10, 10), RED); +} + +#[test] +fn same_finds_one_changed_bit_in_any_word() { + let a = scene(0); + assert!(same(&a, &a.clone())); + for word in 0..size_of::<Instance>() / 4 { + let mut b = a.clone(); + let words: &mut [u32] = bytemuck::cast_slice_mut(&mut b[a.len() - 1..]); + words[word] ^= 1 << 31; + assert!(!same(&a, &b), "missed a change in word {word}"); + } +} + +/// Lists at any 4-byte offset compare, not only 8-aligned ones: a stack array or a Vec may land +/// either way. +#[test] +fn same_takes_lists_at_any_word_offset() { + let n = size_of::<Instance>() / 4; + let words: Vec<u32> = (0..3 * n as u32 + 1).collect(); + let mut other = words.clone(); + for skip in [0, 1] { + let a: &[Instance] = bytemuck::cast_slice(&words[skip..skip + 3 * n]); + assert!(same(a, a), "offset {skip}"); + other[skip + 2 * n] ^= 1; + assert!(!same(a, bytemuck::cast_slice(&other[skip..skip + 3 * n])), "offset {skip}"); + other[skip + 2 * n] ^= 1; + } +} + +/// Plain rects between images and glyphs keep the batch they're in; only image and glyph pages +/// start one. +#[test] +fn batches_break_only_where_the_bound_page_changes() { + let gpu = Gpu::headless(); + let (device, queue) = (&gpu.device, &gpu.queue); + let mut renderer = Renderer::new(device, OFFSCREEN_FORMAT); + let mut text = crate::text::TextSystem::new(&[], ("Inter", "Inter")); + let with = |kind: f32, page: f32| Instance { params: [page, kind, 0.0, 0.0], ..square(0.0, 0.0) }; + let glyph = |page: f32| Instance { params: [0.0, KIND_GLYPH, page, 0.0], ..square(0.0, 0.0) }; + let instances = [ + square(0.0, 0.0), with(KIND_IMAGE, 1.0), square(0.0, 0.0), with(KIND_SHADOW, 0.0), + glyph(2.0), with(KIND_GRADIENT, 0.0), glyph(0.0), square(0.0, 0.0), with(KIND_IMAGE, 1.0), + ]; + renderer.prepare(device, queue, &mut text.atlas, &instances, SIZE); + let batches: Vec<_> = renderer.image_batches.iter().map(|(range, bind)| (range.clone(), match bind { + BatchBind::Image(page) => ('i', *page), + BatchBind::Glyph(page) => ('g', *page), + })).collect(); + assert_eq!(batches, [(0..1, ('i', 0)), (1..4, ('i', 1)), (4..6, ('g', 1)), (6..8, ('i', 0)), (8..9, ('i', 1))]); +} + +/// Frames whose instances only move keep their batches, and their effects see where they moved; +/// a changed `params`, a longer list or a lost staging batches again. +#[test] +fn only_a_changed_params_or_length_batches_again() { + let gpu = Gpu::headless(); + let (device, queue) = (&gpu.device, &gpu.queue); + let mut renderer = Renderer::new(device, OFFSCREEN_FORMAT); + let mut text = crate::text::TextSystem::new(&[], ("Inter", "Inter")); + let frame = |x: f32, page: f32, extra: usize| { + let mut list = vec![square(x, 0.0), Instance { params: [page, KIND_IMAGE, 0.0, 0.0], ..square(x, 8.0) }, + Instance { params: [0.0, KIND_EFFECT, 0.0, 0.0], ..square(x, 16.0) }]; + list.extend((0..extra).map(|i| square(i as f32, 24.0))); + list + }; + let mut prepare = |renderer: &mut Renderer, list: &[Instance]| { + let runs = renderer.uploads.batch_runs; + renderer.prepare(device, queue, &mut text.atlas, list, SIZE); + let pages: Vec<_> = renderer.image_batches.iter().map(|(r, b)| (r.clone(), matches!(b, BatchBind::Image(1)))).collect(); + (renderer.uploads.batch_runs - runs, pages, renderer.effects.iter().map(|(at, i)| (*at, i.rect[0])).collect::<Vec<_>>()) + }; + assert_eq!(prepare(&mut renderer, &frame(0.0, 1.0, 0)), (1, vec![(0..1, false), (1..3, true)], vec![(2, 0.0)])); + assert_eq!(prepare(&mut renderer, &frame(5.0, 1.0, 0)), (0, vec![(0..1, false), (1..3, true)], vec![(2, 5.0)]), "moved only"); + assert_eq!(prepare(&mut renderer, &frame(5.0, 0.0, 0)), (1, vec![(0..3, false)], vec![(2, 5.0)]), "image page changed"); + assert_eq!(prepare(&mut renderer, &frame(5.0, 0.0, 2)).0, 1, "longer"); + renderer.uploads.forget_instances(); + assert_eq!(prepare(&mut renderer, &frame(5.0, 0.0, 2)).0, 1, "forgotten"); + assert_eq!(prepare(&mut renderer, &[]), (1, vec![], vec![]), "emptied"); +} diff --git a/app/vendor/rune/crates/rune/src/render/variant.rs b/app/vendor/rune/crates/rune/src/render/variant.rs new file mode 100644 index 0000000..6d375f6 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/render/variant.rs @@ -0,0 +1,525 @@ +//! Which uber shader a renderer draws with, as a state machine ([`Uber`]). +//! +//! `Classic` is shader.wgsl alone, the shader every renderer drew before glyphs could draw from +//! their outlines: its WGSL, layout and precompiled libraries are unchanged, so a Mac that keeps +//! the default text path draws exactly what it drew before. `Windfoil` is shader.wgsl with +//! outline.wgsl, whose glyphs can also draw from the outline store (binding 4). Renderers start +//! with Windfoil except on macOS (and with GPU springs, which keep Classic); a Classic renderer +//! builds Windfoil the first time text asks for outlines. A Windfoil that can't be built leaves +//! the renderer Classic for good (`Unavailable`), and text falls back to its other rasterisers. + +use super::instance::shader_consts; +use super::*; +use crate::machine::Effects; + +const _: () = { + assert!(shader_consts::PINNED_KIND < 0.0); + assert!(!shader_consts::OUTLINE_SUBPIXEL); +}; + +/// Windfoil's WGSL: shader.wgsl with outline.wgsl's glyph branch, joined when Rune builds +/// (`build.rs`, render/uber_wgsl.rs). +pub(crate) fn windfoil_wgsl() -> &'static str { + super::uber_wgsl::WINDFOIL +} + +/// Windfoil's fragment entry, which the subpixel variant renames for its own entry to call. +const FS_ENTRY: &str = shader_consts::FS_ENTRY_DECL; +/// Mean subpixel coverage floor below which dual-source text emits zero (`DUAL_ENTRY`). +pub(super) const LCD_MEAN_EPSILON: f32 = 1.0e-5; +pub(super) const DUAL_ENTRY: &str = r#" +struct DualOut { + @location(0) @blend_src(0) color: vec4<f32>, + @location(0) @blend_src(1) blend: vec4<f32>, +} + +// Windfoil's fragment, with each colour channel blended by its own coverage where the glyph +// drawn set one (`lcd_cov`): subpixel text. Everything else blends as premultiplied alpha. +@fragment +fn fs(i: Out) -> DualOut { + let c = fs_premul(i); + if (lcd_cov.w == 0.0) { + return DualOut(c, vec4<f32>(c.a)); + } + let e = i.params.w; + let mean = pow((lcd_cov.x + lcd_cov.y + lcd_cov.z) / 3.0, e); + if (mean < 1.0e-5) { + return DualOut(vec4<f32>(0.0), vec4<f32>(0.0)); + } + let k = pow(lcd_cov.xyz, vec3<f32>(e)) / mean; + return DualOut(vec4<f32>(c.rgb * k, c.a), vec4<f32>(c.a * k, c.a)); +} +"#; + +/// The kinds the frame pass has a pipeline of its own for (`KIND_RECT`, `KIND_SHADOW`, `KIND_GLYPH`): +/// what most of a frame's fragments draw. +pub(crate) const PINNED: [u32; 3] = [Kind::Rect.as_u32(), Kind::Shadow.as_u32(), Kind::Glyph.as_u32()]; + +/// shader.wgsl's marker for the kind a fragment draws: -1, every kind. +const PINNED_OFF: &str = shader_consts::PINNED_KIND_OFF_DECL; + +/// Windfoil's WGSL with its fragment entry pinned to `kind` (shader.wgsl `fragment_kind`): the +/// compiler drops every other kind's code. The vertex stage is unchanged. +pub(crate) fn pinned_wgsl(kind: u32) -> Option<String> { + let windfoil = windfoil_wgsl(); + (windfoil.matches(PINNED_OFF).count() == 1).then(|| windfoil.replacen(PINNED_OFF, &format!("const PINNED_KIND: f32 = {kind}.0;"), 1)) +} + +/// outline.wgsl's switch for subpixel outline glyphs, off but in the subpixel variant. +const SUBPIXEL_OFF: &str = shader_consts::OUTLINE_SUBPIXEL_OFF_DECL; + +/// The subpixel variant's WGSL: Windfoil's, with subpixel outline coverage and its fragment +/// entry blending by a second output. Only this variant pays for the three coverages. +pub(super) fn dual_wgsl() -> Option<String> { + let windfoil = windfoil_wgsl(); + let marked = windfoil.matches(FS_ENTRY).count() == 1 && windfoil.matches(SUBPIXEL_OFF).count() == 1; + marked.then(|| { + let body = windfoil.replacen(FS_ENTRY, "fn fs_premul(i: Out) -> vec4<f32> {", 1) + .replacen(SUBPIXEL_OFF, "const OUTLINE_SUBPIXEL: bool = true;", 1); + format!("enable dual_source_blending;\n{body}\n{DUAL_ENTRY}") + }) +} + +/// Windfoil's subpixel pipeline for the window, built the first frame text draws subpixel masks +/// (`FontSmoothing::WindfoilRgb`, `ClearType`) on a Windfoil renderer whose device blends by a +/// second output. Layers keep the plain pipeline, so text in them draws grayscale. +pub(super) enum Lcd { + Unbuilt, + /// No shipped bytecode takes it here, so its WGSL compiles on a thread of its own (FXC takes + /// about a minute for it on a Windows laptop) and subpixel text draws grayscale meanwhile. + Building(std::sync::mpsc::Receiver<Result<wgpu::RenderPipeline, String>>), + Built(wgpu::RenderPipeline), + /// It can't be built here: subpixel text draws grayscale from now on. + Refused, +} + +/// Classic's bindings and the outline store's. +pub(crate) const fn windfoil_bind_entries() -> [wgpu::BindGroupLayoutEntry; 5] { + let [a, b, c, d] = metallib::uber_bind_entries(); + let outlines = wgpu::BindingType::Texture { + sample_type: wgpu::TextureSampleType::Uint, + view_dimension: wgpu::TextureViewDimension::D2, + multisampled: false, + }; + [a, b, c, d, wgpu::BindGroupLayoutEntry { binding: 4, visibility: wgpu::ShaderStages::FRAGMENT, ty: outlines, count: None }] +} + +/// Windfoil's pipeline ABI, as `metallib::uber_abi_hash` hashes Classic's. +#[cfg(any(target_os = "macos", target_os = "windows"))] +pub(crate) const fn windfoil_abi_hash() -> u64 { + metallib::abi_hash_of(&windfoil_bind_entries()) +} + +/// Where a Windfoil shader came from. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum Source { + /// The bytecode Rune ships for it (DXBC on Windows, a metallib on macOS). + #[cfg_attr(not(any(target_os = "macos", target_os = "windows")), allow(dead_code))] + Precompiled, + /// Its WGSL, compiled at run time. + Compiled, +} + +pub(super) enum Uber { + /// shader.wgsl alone, and no outline store. + Classic, + /// shader.wgsl and outline.wgsl, with the outline store's texture and the atlas fill pass. + Windfoil { source: Source, outlines: wgpu::Texture, fill: fill::FillPass }, + /// Windfoil was asked for and couldn't be built: Classic from now on. + Unavailable, +} + +pub(super) enum Event { + /// Text drew glyphs from outlines. + OutlinesWanted, + /// Windfoil's pipeline was built. + Built { source: Source, outlines: wgpu::Texture, fill: fill::FillPass }, + /// Windfoil's pipeline couldn't be built, and why. + Refused(String), +} + +#[derive(Debug, PartialEq)] +pub(super) enum Effect { + /// Build Windfoil's pipeline, and send `Built` or `Refused`. + Build, + /// Say why text falls back from outlines. + Fallback(String), +} + +impl Uber { + pub(super) fn step(&mut self, event: Event) -> Effects<Effect> { + match (&*self, event) { + (Uber::Classic, Event::OutlinesWanted) => Effects::one(Effect::Build), + (Uber::Classic, Event::Built { source, outlines, fill }) => { + *self = Uber::Windfoil { source, outlines, fill }; + Effects::none() + } + (Uber::Classic, Event::Refused(why)) => { + *self = Uber::Unavailable; + Effects::one(Effect::Fallback(why)) + } + _ => Effects::none(), + } + } + + /// The outline store's texture, which Windfoil's bind groups hold. + pub(super) fn outlines(&self) -> Option<&wgpu::Texture> { + match self { + Uber::Windfoil { outlines, .. } => Some(outlines), + Uber::Classic | Uber::Unavailable => None, + } + } + + /// What text can expect of outlines from this renderer. + pub(super) fn support(&self) -> crate::text::outline::Support { + match self { + Uber::Classic => crate::text::outline::Support::Untried, + Uber::Windfoil { .. } => crate::text::outline::Support::Drawn, + Uber::Unavailable => crate::text::outline::Support::Unavailable, + } + } +} + +/// What building Windfoil needs from its renderer. +pub(super) struct BuildContext<'a> { + pub format: wgpu::TextureFormat, + pub vertex_entry: &'static str, + pub globals: &'a wgpu::Buffer, + pub stand_in: &'a wgpu::Texture, +} + +/// A built Windfoil: its layouts, shader and frame pipeline. +pub(super) struct Built { + pub bind_layout: wgpu::BindGroupLayout, + pub layout: wgpu::PipelineLayout, + pub shader: dxbc::Shaders, + pub pipeline: wgpu::RenderPipeline, + pub source: Source, +} + +impl Renderer { + /// Which uber shader draws, for diagnostics: `classic`, `windfoil (precompiled)`, + /// `windfoil (compiled)` or `unavailable` (Windfoil couldn't be built). + #[doc(hidden)] + pub fn uber_shader(&self) -> &'static str { + match self.uber { + Uber::Classic => "classic", + Uber::Windfoil { source: Source::Precompiled, .. } => "windfoil (precompiled)", + Uber::Windfoil { source: Source::Compiled, .. } => "windfoil (compiled)", + Uber::Unavailable => "unavailable", + } + } + + /// Tells `atlas` what this renderer does with outlines (`text::outline::Support`) before it + /// first draws, so the first frame's glyph masks are queued for the GPU fill rather than + /// filled on the CPU. `prepare` tells it again every frame. + pub fn attach_text(&self, atlas: &mut Atlas) { + atlas.outlines.set_support(self.uber.support()); + } + + /// Steps the shader machine `state` on `event`, carrying out each effect (building Windfoil + /// feeds `Built` or `Refused` back in) until none is left; with the Windfoil pipeline it + /// built on the way, if it built one. + fn run(device: &wgpu::Device, cx: &BuildContext<'_>, state: &mut Uber, event: Event) -> Option<Built> { + let mut built = None; + let mut queue: Vec<Effect> = state.step(event).into_iter().collect(); + while let Some(effect) = queue.pop() { + match effect { + Effect::Build => { + let next = match Self::build_windfoil(device, cx.format, cx.vertex_entry) { + Ok(b) => { + let outlines = Self::outline_texture(device, outlines::MIN_ROWS); + let fill = fill::FillPass::new(device, &b.layout, &b.shader, fill::FillBindings { + layout: &b.bind_layout, globals: cx.globals, outlines: &outlines, stand_in: cx.stand_in }); + let event = Event::Built { source: b.source, outlines, fill }; + built = Some(b); + event + } + Err(why) => Event::Refused(why), + }; + queue.extend(state.step(next)); + } + Effect::Fallback(why) => eprintln!("rune: glyphs can't draw from outlines here ({why}); text draws from the atlas alone"), + } + } + built + } + /// A new renderer's shader machine, asked for Windfoil at once. + pub(super) fn start_windfoil(device: &wgpu::Device, cx: &BuildContext<'_>) -> (Uber, Option<Built>) { + let mut state = Uber::Classic; + let built = Self::run(device, cx, &mut state, Event::OutlinesWanted); + (state, built) + } + + /// Steps this renderer's shader machine on `event`, taking any Windfoil pipeline it builds; + /// whether it took one (the caller then makes its atlas pages ones the GPU can fill). + pub(super) fn select(&mut self, device: &wgpu::Device, event: Event) -> bool { + let cx = BuildContext { format: self.format, vertex_entry: self.vertex_entry, globals: &self.globals, stand_in: &self.stand_in }; + if let Some(built) = Self::run(device, &cx, &mut self.uber, event) { + self.adopt(device, built); + self.rebind_all(device); + return true; + } + false + } + + /// Windfoil's layouts, shader and pipeline for `format`, from the shipped bytecode where it + /// matches, else from WGSL; an error where neither builds. + pub(super) fn build_windfoil(device: &wgpu::Device, format: wgpu::TextureFormat, vertex_entry: &'static str) -> Result<Built, String> { + if vertex_entry != "vs" { + return Err("GPU springs draw the classic shader".into()); + } + let bind_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { label: None, entries: &windfoil_bind_entries() }); + let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { label: None, bind_group_layouts: &[Some(&bind_layout)], immediate_size: 0 }); + let make_pipeline = |shader: &dxbc::Shaders| Self::pipeline(device, &layout, shader, format, vertex_entry, Blend::SourceOver); + #[cfg(target_os = "windows")] + if let Some((shader, pipeline)) = dxbc::uber(device, make_pipeline) { + return Ok(Built { bind_layout, layout, shader, pipeline, source: Source::Precompiled }); + } + #[cfg(target_os = "macos")] + if let Some((shader, pipeline)) = windfoil_metallib::load(device, make_pipeline) { + return Ok(Built { bind_layout, layout, shader: dxbc::Shaders::one(shader), pipeline, source: Source::Precompiled }); + } + let (shader, pipeline) = compile(device, windfoil_wgsl(), make_pipeline)?; + Ok(Built { bind_layout, layout, shader, pipeline, source: Source::Compiled }) + } + + /// Whether this frame's subpixel text can blend by channel, starting the pipeline the first + /// time it's asked: from the shipped bytecode at once where it matches, else compiled on a + /// thread, which `frame_wake` tells when it's done. Until then subpixel text draws grayscale. + /// `want`: this frame's text draws subpixel masks. A compile already running is collected + /// either way, since text draws grayscale while it runs. + pub(super) fn lcd_ready(&mut self, device: &wgpu::Device, want: bool) -> bool { + if want && matches!(self.lcd, Lcd::Unbuilt) && self.uber.outlines().is_some() { + self.lcd = match self.start_lcd(device) { + Ok(lcd) => lcd, + Err(why) => Self::refuse_lcd(&why), + }; + if matches!(self.lcd, Lcd::Built(_)) { self.lcd_built(); } + } + if let Lcd::Building(done) = &self.lcd { + match done.try_recv() { + Ok(Ok(pipeline)) => { + self.lcd = Lcd::Built(pipeline); + self.lcd_built(); + } + Ok(Err(why)) => self.lcd = Self::refuse_lcd(&why), + Err(std::sync::mpsc::TryRecvError::Disconnected) => self.lcd = Self::refuse_lcd("its compile ended without a pipeline"), + Err(std::sync::mpsc::TryRecvError::Empty) => {} + } + } + want && matches!(self.lcd, Lcd::Built(_)) + } + + /// Subpixel text can blend by channel from now on: it switches at its next frame, on the CPU + /// and the GPU together, which the window is asked for. + fn lcd_built(&self) { + crate::text::note_dual_source(true); + if let Some(wake) = &self.frame_wake { wake.notify(); } + } + + fn refuse_lcd(why: &str) -> Lcd { + eprintln!("rune: subpixel text can't blend by channel here ({why}); it draws grayscale"); + crate::text::note_dual_source(false); + Lcd::Refused + } + + fn start_lcd(&self, device: &wgpu::Device) -> Result<Lcd, String> { + if !device.features().contains(wgpu::Features::DUAL_SOURCE_BLENDING) { + return Err("the device has no dual-source blending".into()); + } + let wgsl = dual_wgsl().ok_or("shader.wgsl's fragment entry moved")?; + let (layout, format, entry) = (self.layout.clone(), self.format, self.vertex_entry); + #[cfg(target_os = "windows")] + if let Some((_, pipeline)) = dxbc::uber_dual(device, |shader| lcd_pipeline(device, &layout, format, entry, shader)) { + return Ok(Lcd::Built(pipeline)); + } + #[cfg(target_arch = "wasm32")] + return compile(device, &wgsl, |shader| lcd_pipeline(device, &layout, format, entry, shader)).map(|(_, pipeline)| Lcd::Built(pipeline)); + #[cfg(not(target_arch = "wasm32"))] + { + let (sent, done) = std::sync::mpsc::channel(); + let (device, wake) = (device.clone(), self.frame_wake.clone()); + std::thread::Builder::new() + .name("rune-subpixel-shader".into()) + .spawn(move || { + // A renderer dropped meanwhile has no receiver: nothing to tell. + sent.send(compile(&device, &wgsl, |shader| lcd_pipeline(&device, &layout, format, entry, shader)).map(|(_, pipeline)| pipeline)).ok(); + if let Some(wake) = wake { wake.notify(); } + }) + .map_err(|e| format!("no thread to compile it on: {e}"))?; + Ok(Lcd::Building(done)) + } + } + + /// The window's wake, which a subpixel pipeline compiled off this thread tells when it's + /// ready, so a window that rests meanwhile still draws its next frame with it. + pub(crate) fn set_frame_wake(&mut self, wake: &std::sync::Arc<crate::live::Wake>) { + if !self.frame_wake.as_ref().is_some_and(|w| std::sync::Arc::ptr_eq(w, wake)) { + self.frame_wake = Some(wake.clone()); + } + } + + #[cfg(test)] + pub(crate) fn has_frame_wake(&self) -> bool { + self.frame_wake.is_some() + } + + /// The subpixel pipeline compiled from WGSL now, on this thread, for the tools that capture + /// its HLSL (`regen_dxbc`): it bypasses the shipped bytecode. + #[doc(hidden)] + pub fn compile_subpixel_now(&mut self, device: &wgpu::Device) -> Result<(), String> { + let wgsl = dual_wgsl().ok_or("shader.wgsl's fragment entry moved")?; + let (layout, format, entry) = (self.layout.clone(), self.format, self.vertex_entry); + let (_, pipeline) = compile(device, &wgsl, |shader| lcd_pipeline(device, &layout, format, entry, shader))?; + self.lcd = Lcd::Built(pipeline); + Ok(()) + } + + /// Compiles the pipeline pinned to `KIND_*` `kind` (`pinned_wgsl`) from WGSL now, so wgpu logs + /// its HLSL (`regen_dxbc`): it bypasses the shipped bytecode. + #[doc(hidden)] + pub fn compile_pinned_now(&mut self, device: &wgpu::Device, kind: u32) -> Result<(), String> { + let wgsl = pinned_wgsl(kind).ok_or("shader.wgsl's PINNED_KIND moved")?; + let (layout, format, entry) = (self.layout.clone(), self.format, self.vertex_entry); + compile(device, &wgsl, |shader| Self::pipeline(device, &layout, shader, format, entry, Blend::SourceOver))?; + Ok(()) + } + + /// Starts making the frame pass's pipelines pinned to one kind each (`PINNED`) from the shipped bytecode, on a + /// thread of their own, for Windows renderers drawing Windfoil from its precompiled shader: on a cold driver cache + /// (the first launch after an install or a driver update) the driver takes about 150 ms for the three, which no + /// frame should wait for. The general shader draws every kind until they arrive (`take_pinned`), the same picture. + /// Anywhere else, or when the bytecode doesn't match, none: every kind draws with the one shader, as before. + /// Never from WGSL, which takes FXC tens of seconds each. + #[allow(unsafe_code)] + pub(super) fn start_pinned(&mut self, device: &wgpu::Device) { + self.pinned = None; + self.pinned_building = None; + #[cfg(target_os = "windows")] + if matches!(self.uber, Uber::Windfoil { source: Source::Precompiled, .. }) && self.vertex_entry == "vs" { + let (sent, done) = std::sync::mpsc::channel(); + let (device, layout, format) = (device.clone(), self.layout.clone(), self.format); + let spawned = std::thread::Builder::new() + .name("rune-pinned-pipelines".into()) + // A renderer dropped meanwhile has no receiver: nothing to tell. + .spawn(move || { + // Below normal, as the CPU frame's helpers are: on a two-core machine a cold driver cache makes this a + // 150 ms compile, which mustn't compete with the first input. + // SAFETY: this thread's pseudo-handle. + unsafe { windows_sys::Win32::System::Threading::SetThreadPriority(windows_sys::Win32::System::Threading::GetCurrentThread(), windows_sys::Win32::System::Threading::THREAD_PRIORITY_BELOW_NORMAL) }; + sent.send(make_pinned(&device, &layout, format)).ok(); + }); + if spawned.is_ok() { + self.pinned_building = Some((format, done)); + return; + } + } + let _ = device; + self.pinned = Some(Vec::new()); + } + + /// Takes the pinned pipelines once their thread has made them for this format (one made for a format the + /// renderer has since left is dropped, and that format's next use starts again). + pub(super) fn take_pinned(&mut self) { + let Some((format, done)) = &self.pinned_building else { return }; + // Frame-profile builds with `RUNE_PINNED=all` wait for them, so a capture's every frame draws pinned (the + // screen comparison forces the split on); every other build never waits. + #[cfg(feature = "frame-profile")] + let got = if super::pinned_forced() == Some(true) { done.recv().map_err(|_| std::sync::mpsc::TryRecvError::Disconnected) } else { done.try_recv() }; + #[cfg(not(feature = "frame-profile"))] + let got = done.try_recv(); + match got { + Ok(pinned) => { + if *format == self.format { self.pinned = Some(pinned); } + self.pinned_building = None; + } + Err(std::sync::mpsc::TryRecvError::Disconnected) => { + self.pinned = Some(Vec::new()); + self.pinned_building = None; + } + Err(std::sync::mpsc::TryRecvError::Empty) => {} + } + } + /// Takes `built` as the renderer's shader: every pipeline again from it. Bind groups follow + /// once the outline texture exists (`rebind_all`). + fn adopt(&mut self, device: &wgpu::Device, built: Built) { + self.bind_layout = built.bind_layout; + self.layout = built.layout; + self.shader = built.shader; + self.pipeline = built.pipeline; + for index in 0..self.extra.len() { + let format = self.extra[index].0; + self.extra[index].1 = Self::pipeline(device, &self.layout, &self.shader, format, self.vertex_entry, Blend::SourceOver); + } + self.shader_changed(device); + // Built on the old bind layout; made again at the next backdrop blur and subpixel frame. + self.backdrop_blur = None; + self.lcd = Lcd::Unbuilt; + // The pinned pipelines again from the new shader, on their thread: the general shader draws until they're in. + self.pinned_extra.clear(); + self.start_pinned(device); + } +} + +/// The subpixel pipeline from `shader`'s stages: Windfoil's, blending each channel by the +/// fragment's second output. +fn lcd_pipeline(device: &wgpu::Device, layout: &wgpu::PipelineLayout, format: wgpu::TextureFormat, vertex_entry: &'static str, shader: &dxbc::Shaders) -> wgpu::RenderPipeline { + let blend = wgpu::BlendState { + color: wgpu::BlendComponent { src_factor: wgpu::BlendFactor::One, dst_factor: wgpu::BlendFactor::OneMinusSrc1, operation: wgpu::BlendOperation::Add }, + alpha: wgpu::BlendComponent { src_factor: wgpu::BlendFactor::One, dst_factor: wgpu::BlendFactor::OneMinusSrcAlpha, operation: wgpu::BlendOperation::Add }, + }; + device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { + label: Some("uber subpixel"), + layout: Some(layout), + vertex: wgpu::VertexState { + module: &shader.vertex, + entry_point: Some(vertex_entry), + compilation_options: Default::default(), + buffers: &[Some(metallib::uber_vertex_layout())], + }, + primitive: metallib::uber_primitive(), + depth_stencil: None, + multisample: Default::default(), + fragment: Some(wgpu::FragmentState { + module: &shader.fragment, + entry_point: Some("fs"), + compilation_options: Default::default(), + targets: &[Some(wgpu::ColorTargetState { format, blend: Some(blend), write_mask: wgpu::ColorWrites::ALL })], + }), + multiview_mask: None, + cache: None, + }) +} + +/// `wgsl`'s module and pipeline, compiled now, or the error the device reported. +fn compile(device: &wgpu::Device, wgsl: &str, make_pipeline: impl FnOnce(&dxbc::Shaders) -> wgpu::RenderPipeline) -> Result<(dxbc::Shaders, wgpu::RenderPipeline), String> { + #[cfg(not(target_arch = "wasm32"))] + let scopes = (device.push_error_scope(wgpu::ErrorFilter::Validation), device.push_error_scope(wgpu::ErrorFilter::Internal)); + let shader = dxbc::Shaders::one(device.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some("uber"), source: wgpu::ShaderSource::Wgsl(wgsl.into()) })); + let pipeline = make_pipeline(&shader); + #[cfg(not(target_arch = "wasm32"))] + if let Some(error) = pollster::block_on(scopes.1.pop()).or(pollster::block_on(scopes.0.pop())) { + return Err(error.to_string()); + } + Ok((shader, pipeline)) +} + +/// The pinned pipelines for `format` (`Renderer::start_pinned`'s thread): none taken (refused, or every fragment +/// stale) is none at all, so nothing is split. +#[cfg(target_os = "windows")] +fn make_pinned(device: &wgpu::Device, layout: &wgpu::PipelineLayout, format: wgpu::TextureFormat) -> Vec<Option<wgpu::RenderPipeline>> { + #[cfg(feature = "frame-profile")] + let started = crate::time::now(); + let pinned: Vec<_> = PINNED.iter().map(|&kind| dxbc::uber_pinned(device, kind, |shader| Renderer::pipeline(device, layout, shader, format, "vs", Blend::SourceOver)).map(|(_, p)| p)).collect(); + // Frame-profile builds: what making them costs, and what the run-time freshness check before `PINNED_FRESH` + // cost (three `pinned_wgsl` and their hashes). + #[cfg(feature = "frame-profile")] + { + let made = started.elapsed(); + let checked = crate::time::now(); + let old: usize = PINNED.iter().filter_map(|&kind| super::pinned_wgsl_blake3(kind)).map(|h| h.len()).sum(); + eprintln!("rune-warm pinned pipelines: {:.0} us to make {} of 3 on their thread (the run-time check they replace: {:.0} us, {old} hex)", made.as_secs_f64() * 1e6, pinned.iter().filter(|p| p.is_some()).count(), checked.elapsed().as_secs_f64() * 1e6); + } + if pinned.iter().any(Option::is_some) { pinned } else { Vec::new() } +} \ No newline at end of file diff --git a/app/vendor/rune/crates/rune/src/render/warm.rs b/app/vendor/rune/crates/rune/src/render/warm.rs new file mode 100644 index 0000000..7fd1059 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/render/warm.rs @@ -0,0 +1,172 @@ +//! `warm_gpu` away from macOS: a GPU device and Rune's renderer made on a thread ahead of a +//! surface that may show soon, and the slot the next surface takes them from (`Gpu::for_surface`). +//! Unclaimed, they go after `LINGER`, so an app that warms on a hint and then shows nothing +//! holds no device for long. A hidden overlay that gives its surface back parks its device and +//! renderer here too (`park`), for `PARKED` rather than `LINGER`: an overlay shown for each +//! dictation takes the same device every time instead of making one per show (hex#1268). + +use super::{Gpu, Renderer, warmup::WarmRenderer}; +use std::sync::{Arc, Condvar, Mutex, Weak}; +use std::time::Duration; + +use crate::time::Instant; + +/// How long a warmed device waits for a surface, from the last `warm_gpu`. +pub(super) const LINGER: Duration = Duration::from_secs(30); + +/// How long a parked device waits for the next surface. +pub(crate) const PARKED: Duration = Duration::from_secs(5 * 60); + +/// The format overlays and windows draw in on Windows and Linux (`surface_config`, after +/// `srgb_blend` drops the sRGB suffix); a surface in another one rebuilds the pipeline. +const FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Bgra8Unorm; + +struct Warmed(Gpu, WarmRenderer); + +#[derive(Default)] +enum State { + #[default] + Idle, + Making { until: Instant }, + Ready { warmed: Warmed, until: Instant }, +} + +struct Slot { + state: Mutex<State>, + changed: Condvar, + /// The device a window's or overlay's surface draws with, while one does. + live: Mutex<Weak<Gpu>>, +} + +static SLOT: Slot = Slot { state: Mutex::new(State::Idle), changed: Condvar::new(), live: Mutex::new(Weak::new()) }; + +fn lock<T>(mutex: &Mutex<T>) -> std::sync::MutexGuard<'_, T> { + mutex.lock().unwrap_or_else(|e| e.into_inner()) +} + +/// Some surface draws with `gpu`: a warm-up while it lives would make a second device. +pub(crate) fn surface_gpu(gpu: &Arc<Gpu>) { + *lock(&SLOT.live) = Arc::downgrade(gpu); +} + +/// The device a surface draws with now, if any. A lost one is no device to share, so it reads as +/// none and `warm` makes another. +pub(super) fn live() -> Option<Arc<Gpu>> { + lock(&SLOT.live).upgrade().filter(|gpu| !gpu.is_lost()) +} + +/// Starts making a device with `features` (whichever the adapter has) and the renderer, +/// unless a surface's device lives or one is being made or waits; either way the warmed one +/// waits `LINGER` from now. `prepare` runs on the warming thread with the new device, or the +/// live one, so an app can make its own pipelines off the UI thread. +pub(super) fn warm(features: wgpu::Features, prepare: Option<Box<dyn FnOnce(&wgpu::Device) + Send>>) { + if let Some(gpu) = live() { + if let Some(prepare) = prepare { + std::thread::Builder::new().name("rune-gpu-warm".into()).spawn(move || prepare(&gpu.device)).ok(); + } + return; + } + let mut state = lock(&SLOT.state); + let until = crate::time::now() + LINGER; + match &mut *state { + State::Making { until: at } | State::Ready { until: at, .. } => { *at = (*at).max(until); return; } + State::Idle => *state = State::Making { until }, + } + drop(state); + let spawned = std::thread::Builder::new().name("rune-gpu-warm".into()).spawn(move || { + let made = make(features); + // Before the slot says ready, so a surface waiting for it gets the app's pipelines too; + // outside the lock, so `warm` never waits on them. + if let (Some(warmed), Some(prepare)) = (&made, prepare) { prepare(&warmed.0.device); } + let mut state = lock(&SLOT.state); + let (Some(warmed), State::Making { until }) = (made, &*state) else { + *state = State::Idle; + SLOT.changed.notify_all(); + return; + }; + let until = *until; + *state = State::Ready { warmed, until }; + SLOT.changed.notify_all(); + wait_for_surface(state); + }); + if spawned.is_err() { *lock(&SLOT.state) = State::Idle; } +} + +/// Keeps what's ready for a surface to take, or lets it go once nothing asked for it by its +/// time (which `warm` may push back). +fn wait_for_surface(mut state: std::sync::MutexGuard<'_, State>) { + loop { + let State::Ready { until, .. } = &*state else { return }; + let now = crate::time::now(); + if now >= *until { break; } + let wait = *until - now; + state = SLOT.changed.wait_timeout(state, wait).unwrap_or_else(|e| e.into_inner()).0; + } + let expired = std::mem::take(&mut *state); + drop(state); + drop(expired); +} + +/// A hidden overlay's device and renderer, its surface already dropped, for the next surface to +/// take within `linger`. The device first finishes its work, so what the dropped surface and +/// its swapchain left is freed now rather than whenever the device next runs. When something +/// already waits in the slot, this one goes; so does a device that died while it was hidden. +pub(crate) fn park(gpu: Gpu, renderer: Renderer, linger: Duration) { + if gpu.is_lost() { return; } + rune_gpu::health::poll(&gpu.device, wgpu::PollType::wait_indefinitely()).ok(); + let Some(renderer) = renderer.into_warm() else { return }; + let mut state = lock(&SLOT.state); + if !matches!(*state, State::Idle) { return; } + *state = State::Ready { warmed: Warmed(gpu, renderer), until: crate::time::now() + linger }; + SLOT.changed.notify_all(); + drop(state); + let spawned = std::thread::Builder::new().name("rune-gpu-parked".into()).spawn(|| wait_for_surface(lock(&SLOT.state))); + if spawned.is_err() { discard(); } +} + +/// A device for a future surface on a GPU that drives a display, with the renderer, and one +/// pass run offscreen, so the device has drawn (`GpuEvent::Drew`). +fn make(features: wgpu::Features) -> Option<Warmed> { + super::gpu_events::starting(); + let gpu = Gpu::try_for_display(Gpu::instance_for(features), features).ok()?; + let renderer = Renderer::new_warm(&gpu.device, FORMAT); + let target = super::Offscreen::with_format(&gpu.device, 8, 8, FORMAT); + let mut encoder = gpu.device.create_command_encoder(&Default::default()); + drop(encoder.begin_render_pass(&wgpu::RenderPassDescriptor { + label: Some("rune warm-up"), + color_attachments: &[Some(wgpu::RenderPassColorAttachment { + view: &target.view, depth_slice: None, resolve_target: None, + ops: wgpu::Operations { load: wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT), store: wgpu::StoreOp::Store }, + })], + ..Default::default() + })); + gpu.queue.submit([encoder.finish()]); + rune_gpu::health::poll(&gpu.device, wgpu::PollType::wait_indefinitely()).ok(); + super::gpu_events::presented(); + Some(Warmed(gpu, renderer)) +} + +/// What `warm` made, waiting for it if it's still making it. A device that died while it waited +/// is dropped: its surface's owner makes a new one. +pub(super) fn take() -> Option<(Gpu, Renderer)> { + let mut state = lock(&SLOT.state); + while matches!(*state, State::Making { .. }) { + state = SLOT.changed.wait(state).unwrap_or_else(|e| e.into_inner()); + } + let State::Ready { warmed: Warmed(gpu, renderer), .. } = std::mem::take(&mut *state) else { return None }; + SLOT.changed.notify_all(); + if gpu.is_lost() { return None; } + Some((gpu, Renderer::from_warm(renderer))) +} + +/// `prewarm_gpu` is macOS's; elsewhere the surface decides the adapter. +pub(super) fn start() {} + +/// What's warmed goes; a thread still making it lets it go when it's done. +#[cfg_attr(test, allow(dead_code))] +pub(super) fn discard() { + let mut state = lock(&SLOT.state); + if let State::Ready { .. } = &*state { drop(std::mem::take(&mut *state)); } + else if let State::Making { until } = &mut *state { *until = crate::time::now(); } + SLOT.changed.notify_all(); +} diff --git a/app/vendor/rune/crates/rune/src/render/warm_tests.rs b/app/vendor/rune/crates/rune/src/render/warm_tests.rs new file mode 100644 index 0000000..bae59cf --- /dev/null +++ b/app/vendor/rune/crates/rune/src/render/warm_tests.rs @@ -0,0 +1,70 @@ +//! A device that died while it waited for a surface (Windows' Modern Standby, a driver reset) is +//! not handed to the next one: a lost device configures nothing, and wgpu panics on the drawable +//! its surface is asked for. + +#[cfg(all(target_os = "linux", feature = "test-gpu-noop"))] +mod lost { + use crate::render::prewarm::{PARKED, discard, park, take}; + use crate::render::{Gpu, Renderer}; + + /// A GPU on wgpu's noop backend: it takes anything and draws nothing. + fn noop_gpu() -> Gpu { + let mut descriptor = wgpu::InstanceDescriptor::new_without_display_handle(); + descriptor.backends = wgpu::Backends::NOOP; + descriptor.backend_options.noop.enable = true; + let instance = wgpu::Instance::new(descriptor); + let adapter = pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions::default())).unwrap(); + let (device, queue) = pollster::block_on(adapter.request_device(&wgpu::DeviceDescriptor::default())).unwrap(); + Gpu::from_device(instance, adapter, device, queue) + } + + #[test] + fn a_parked_device_that_died_is_not_handed_to_the_next_surface() { + discard(); + let gpu = noop_gpu(); + let renderer = Renderer::new(&gpu.device, wgpu::TextureFormat::Bgra8Unorm); + assert!(!gpu.is_lost()); + gpu.device.destroy(); + // wgpu loses a destroyed device once its queues drain, when the device next maintains itself. + gpu.device.poll(wgpu::PollType::wait_indefinitely()).ok(); + assert!(gpu.is_lost(), "the device's lost callback marks it"); + park(gpu, renderer, PARKED); + assert!(take().is_none(), "a lost device waits for no surface"); + } +} + +#[cfg(not(target_arch = "wasm32"))] +mod warm_renderer { + use crate::render::{Gpu, Renderer}; + + #[test] + fn warm_renderer_transfers_across_threads_and_rejects_surfaces() { + let Ok(gpu) = Gpu::try_new(Gpu::instance(), None) else { return eprintln!("skipped: no GPU") }; + let device = gpu.device.clone(); + let warm = std::thread::spawn(move || Renderer::new_warm(&device, wgpu::TextureFormat::Bgra8Unorm)) + .join() + .expect("warm thread"); + let renderer = Renderer::from_warm(warm); + assert_eq!(renderer.format(), wgpu::TextureFormat::Bgra8Unorm); + + #[cfg(not(target_os = "macos"))] + { + let warm = renderer.into_warm().expect("new renderer has no native surface renderer"); + let mut renderer = std::thread::spawn(move || Renderer::from_warm(warm)) + .join() + .expect("attach thread"); + let draw = crate::native_surface::SurfaceDraw { + surface: crate::native_surface::NativeSurface::new(), + fit: crate::native_surface::SurfaceFit::Fill, + before_instance: 0, + rect: [0.0, 0.0, 16.0, 16.0], + radii: [0.0; 4], + clip: crate::render::NO_CLIP, + fade: [0; 4], + opacity: 1.0, + }; + renderer.prepare_surfaces(&gpu.device, &gpu.queue, &[draw], (16, 16)); + assert!(renderer.into_warm().is_none(), "renderer with native surfaces must not convert to WarmRenderer"); + } + } +} diff --git a/app/vendor/rune/crates/rune/src/render/warmup.rs b/app/vendor/rune/crates/rune/src/render/warmup.rs new file mode 100644 index 0000000..4f1f566 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/render/warmup.rs @@ -0,0 +1,303 @@ +//! Making a GPU device ahead of a surface (`warm_gpu`), so a first surface waits less for its +//! device. + +use super::{ + BatchBind, Instance, Kind, Renderer, backdrop_blur, breaker, dxbc, fill, layers, pass::Backdrop, + upload, variant, +}; + +#[cfg(any(target_os = "windows", target_arch = "wasm32"))] +use super::damaged; + +/// The `Send` state of a [`Renderer`]: every field except `surfaces` (the lazy native surface +/// renderer, which holds `!Send` platform handles such as macOS's `CVMetalTextureCache`). +/// Prewarm and warm-up threads construct and transfer a `WarmRenderer` directly so `Send` is +/// proved by the compiler without `unsafe`, then attach it via [`Renderer::from_warm`]. +pub(super) struct WarmRenderer { + pub(super) surfaces_building: Option<crate::native_surface::Building>, + pub(super) pipeline: wgpu::RenderPipeline, + pub(super) format: wgpu::TextureFormat, + pub(super) shader: dxbc::Shaders, + pub(super) layout: wgpu::PipelineLayout, + pub(super) vertex_entry: &'static str, + pub(super) extra: Vec<(wgpu::TextureFormat, wgpu::RenderPipeline)>, + pub(super) bind_group: wgpu::BindGroup, + pub(super) bind_layout: wgpu::BindGroupLayout, + pub(super) globals: wgpu::Buffer, + pub(super) atlas: wgpu::Texture, + pub(super) uber: variant::Uber, + pub(super) lcd: variant::Lcd, + pub(super) pinned: Option<Vec<Option<wgpu::RenderPipeline>>>, + pub(super) pinned_extra: Vec<(wgpu::TextureFormat, Vec<Option<wgpu::RenderPipeline>>)>, + pub(super) pinned_building: Option<(wgpu::TextureFormat, std::sync::mpsc::Receiver<Vec<Option<wgpu::RenderPipeline>>>)>, + pub(super) kinds: Vec<Option<Kind>>, + pub(super) lcd_frame: bool, + pub(super) frame_wake: Option<std::sync::Arc<crate::live::Wake>>, + pub(super) stand_in: wgpu::Texture, + pub(super) atlas_pages: Vec<(wgpu::Texture, wgpu::BindGroup)>, + pub(super) images: Vec<Option<(wgpu::Texture, wgpu::BindGroup)>>, + pub(super) image_batches: Vec<(std::ops::Range<u32>, BatchBind)>, + pub(super) instances: rune_staging::GrowBuffer, + pub(super) count: u32, + pub(super) springs: Option<crate::gpu::springs::Bindings>, + pub(super) spring_instances: usize, + pub(super) layers: layers::Layers, + pub(super) srgb_blend: bool, + pub(super) effects: Vec<(u32, Instance)>, + pub(super) backdrops: Vec<Backdrop>, + pub(super) backdrop_used: bool, + pub(super) backdrop_blur: Option<backdrop_blur::BackdropBlur>, + pub(super) breakers: breaker::Breakers, + pub(super) uploads: upload::Uploads, + pub(super) fills: std::sync::Mutex<Option<fill::PendingFills>>, + pub(super) device_key: crate::compose::DeviceKey, + pub(super) max_texture_dim: u32, + #[cfg(any(target_os = "windows", target_arch = "wasm32"))] + pub(super) clear_quad: std::sync::OnceLock<wgpu::Buffer>, + #[cfg(any(target_os = "windows", target_arch = "wasm32"))] + pub(super) damage: std::sync::Mutex<damaged::DamageState>, +} + +#[cfg(not(target_arch = "wasm32"))] +const _: fn() = || { + fn assert_send<T: Send>() {} + assert_send::<super::Gpu>(); + assert_send::<WarmRenderer>(); +}; + +impl Renderer { + /// Attaches a `WarmRenderer` as a `Renderer` with no native surface renderer. + pub(super) fn from_warm(warm: WarmRenderer) -> Renderer { + let WarmRenderer { + surfaces_building, + pipeline, + format, + shader, + layout, + vertex_entry, + extra, + bind_group, + bind_layout, + globals, + atlas, + uber, + lcd, + pinned, + pinned_extra, + pinned_building, + kinds, + lcd_frame, + frame_wake, + stand_in, + atlas_pages, + images, + image_batches, + instances, + count, + springs, + spring_instances, + layers, + srgb_blend, + effects, + backdrops, + backdrop_used, + backdrop_blur, + breakers, + uploads, + fills, + device_key, + max_texture_dim, + #[cfg(any(target_os = "windows", target_arch = "wasm32"))] + clear_quad, + #[cfg(any(target_os = "windows", target_arch = "wasm32"))] + damage, + } = warm; + Renderer { + surfaces: None, + fade_stops: [0.0; 2], + surfaces_building, + pipeline, + format, + shader, + layout, + vertex_entry, + extra, + bind_group, + bind_layout, + globals, + atlas, + uber, + lcd, + pinned, + pinned_extra, + pinned_building, + kinds, + lcd_frame, + frame_wake, + stand_in, + atlas_pages, + images, + image_batches, + instances, + count, + springs, + spring_instances, + layers, + srgb_blend, + effects, + backdrops, + backdrop_used, + backdrop_blur, + breakers, + uploads, + fills, + device_key, + max_texture_dim, + #[cfg(any(target_os = "windows", target_arch = "wasm32"))] + clear_quad, + #[cfg(any(target_os = "windows", target_arch = "wasm32"))] + damage, + } + } + + /// Extracts the `Send` core when no native surface renderer has been created; drops `self` on + /// the calling thread and returns `None` otherwise. + #[cfg(not(any(target_os = "macos", target_arch = "wasm32")))] + pub(super) fn into_warm(self) -> Option<WarmRenderer> { + if self.surfaces.is_some() { + return None; + } + let Renderer { + surfaces: _, + fade_stops: _, + surfaces_building, + pipeline, + format, + shader, + layout, + vertex_entry, + extra, + bind_group, + bind_layout, + globals, + atlas, + uber, + lcd, + pinned, + pinned_extra, + pinned_building, + kinds, + lcd_frame, + frame_wake, + stand_in, + atlas_pages, + images, + image_batches, + instances, + count, + springs, + spring_instances, + layers, + srgb_blend, + effects, + backdrops, + backdrop_used, + backdrop_blur, + breakers, + uploads, + fills, + device_key, + max_texture_dim, + #[cfg(any(target_os = "windows", target_arch = "wasm32"))] + clear_quad, + #[cfg(any(target_os = "windows", target_arch = "wasm32"))] + damage, + } = self; + Some(WarmRenderer { + surfaces_building, + pipeline, + format, + shader, + layout, + vertex_entry, + extra, + bind_group, + bind_layout, + globals, + atlas, + uber, + lcd, + pinned, + pinned_extra, + pinned_building, + kinds, + lcd_frame, + frame_wake, + stand_in, + atlas_pages, + images, + image_batches, + instances, + count, + springs, + spring_instances, + layers, + srgb_blend, + effects, + backdrops, + backdrop_used, + backdrop_blur, + breakers, + uploads, + fills, + device_key, + max_texture_dim, + #[cfg(any(target_os = "windows", target_arch = "wasm32"))] + clear_quad, + #[cfg(any(target_os = "windows", target_arch = "wasm32"))] + damage, + }) + } +} + +/// A window's or overlay's surface draws with `gpu`, which `warm_gpu` then leaves alone. +pub(crate) fn surface_gpu(gpu: &std::sync::Arc<super::Gpu>) { + #[cfg(not(any(target_os = "macos", target_arch = "wasm32")))] + super::prewarm::surface_gpu(gpu); + #[cfg(any(target_os = "macos", target_arch = "wasm32"))] + let _ = gpu; +} + +/// A hidden overlay's device and renderer, its surface dropped, for the next window's or +/// overlay's surface to take (`warm::park`). macOS drops them: its prewarmed panels keep theirs. +pub(crate) fn park_gpu(gpu: super::Gpu, renderer: super::Renderer) { + #[cfg(not(any(target_os = "macos", target_arch = "wasm32")))] + super::prewarm::park(gpu, renderer, super::prewarm::PARKED); + #[cfg(any(target_os = "macos", target_arch = "wasm32"))] + drop((renderer, gpu)); +} + +/// Starts making, on a thread, the GPU device and Rune's renderer the next window or overlay +/// surface would make, so a show soon after (a tray app's HUD, on its shortcut's first key) +/// doesn't wait for them on the UI thread. That surface takes them, waiting for the thread if +/// it's still working; unclaimed, they go half a minute after the last call. Does nothing while a +/// surface's device lives. `features` are the ones that surface's compositor asks for +/// (`Compositor::features`); a device without them isn't taken. Windows and Linux; on macOS +/// use `prewarm_gpu`. On Windows, the first call in a process also makes the DX12-or-Vulkan +/// choice on its thread. Cheap to call often, from any thread. +pub fn warm_gpu(features: wgpu::Features) { + #[cfg(not(any(target_os = "macos", target_arch = "wasm32")))] + super::prewarm::warm(features, None); + #[cfg(any(target_os = "macos", target_arch = "wasm32"))] + let _ = features; +} + +/// `warm_gpu`, then `prepare` on that thread with the device, new or the one a surface draws +/// with: an app makes its own pipelines there, off the UI thread, for its compositor to find. +/// On Windows, its first call in a process also makes the DX12-or-Vulkan choice on that thread. +pub fn warm_gpu_with(features: wgpu::Features, prepare: impl FnOnce(&wgpu::Device) + Send + 'static) { + #[cfg(not(any(target_os = "macos", target_arch = "wasm32")))] + super::prewarm::warm(features, Some(Box::new(prepare))); + #[cfg(any(target_os = "macos", target_arch = "wasm32"))] + let _ = (features, prepare); +} diff --git a/app/vendor/rune/crates/rune/src/render/windfoil_metallib.rs b/app/vendor/rune/crates/rune/src/render/windfoil_metallib.rs new file mode 100644 index 0000000..6f1d8cb --- /dev/null +++ b/app/vendor/rune/crates/rune/src/render/windfoil_metallib.rs @@ -0,0 +1,71 @@ +//! macOS: the Windfoil uber shader's precompiled libraries (render/variant.rs), which +//! `scripts/precompile-metal-shaders.sh` builds beside Classic's: `uber_windfoil.metallib` for +//! wgpu's Metal backend and `uber_windfoil_native.metallib` for Rune's. Only a Windfoil renderer +//! loads them, so they never touch Classic, the Mac's default. One that's missing or stale (its +//! WGSL or layout hash differs) is skipped with a log line, and Windfoil compiles from WGSL. + +include!("uber/windfoil_hash.rs"); + +const LIBRARY: &[u8] = include_bytes!("../shaders/uber_windfoil.metallib"); +#[cfg(feature = "metal-backend")] +const NATIVE_LIBRARY: &[u8] = include_bytes!("../shaders/uber_windfoil_native.metallib"); + +/// Whether the libraries were built from the WGSL this build joined (render/uber_wgsl.rs). +const WGSL_MATCHES: bool = super::uber_wgsl::same(super::uber_wgsl::WINDFOIL_BLAKE3, WINDFOIL_WGSL_BLAKE3); +/// Whether they were built for Windfoil's layout as this build has it. +const ABI_MATCHES: bool = super::variant::windfoil_abi_hash() == WINDFOIL_ABI_FNV64; + +/// The Windfoil shader from the library for `device`'s backend and its pipeline, when the +/// library matches Windfoil's WGSL and layout and the device takes it. +#[allow(unsafe_code)] +pub(super) fn load<T>(device: &wgpu::Device, make_pipeline: impl FnOnce(&super::dxbc::Shaders) -> T) -> Option<(wgpu::ShaderModule, T)> { + #[cfg(feature = "metal-backend")] + let native = crate::gpu::metal::raw_device(device).is_some(); + #[cfg(not(feature = "metal-backend"))] + let native = false; + #[cfg(feature = "metal-backend")] + let library = if native { NATIVE_LIBRARY } else { LIBRARY }; + #[cfg(not(feature = "metal-backend"))] + let library = LIBRARY; + if !super::metallib::metallib_enabled() { + return None; + } + if library.is_empty() || !WGSL_MATCHES || !ABI_MATCHES { + static STALE: std::sync::Once = std::sync::Once::new(); + STALE.call_once(|| eprintln!("rune: uber_windfoil.metallib is missing or stale, so Windfoil text compiles its shader from WGSL; \ + run scripts/precompile-metal-shaders.sh on a Mac to rebuild it")); + return None; + } + // Rune's backend takes a library without the feature, which promises arbitrary passthrough. + if !native && !device.features().contains(wgpu::Features::PASSTHROUGH_SHADERS) { + return None; + } + let validation = device.push_error_scope(wgpu::ErrorFilter::Validation); + let internal = device.push_error_scope(wgpu::ErrorFilter::Internal); + // SAFETY: only the embedded library is loaded, built by the script from Windfoil's WGSL + // (checked by its hash) with the bindings its layout hash covers, as Classic's `uber.metallib` is. + let shader = unsafe { + device.create_shader_module_passthrough(wgpu::ShaderModuleDescriptorPassthrough { + label: Some("uber"), + entry_points: std::borrow::Cow::Borrowed(&[ + wgpu::PassthroughShaderEntryPoint { name: std::borrow::Cow::Borrowed("vs"), workgroup_size: (0, 0, 0) }, + wgpu::PassthroughShaderEntryPoint { name: std::borrow::Cow::Borrowed("fs"), workgroup_size: (0, 0, 0) }, + ]), + metallib: Some(std::borrow::Cow::Borrowed(library)), + ..Default::default() + }) + }; + // Rune's backend reports no errors to scopes, so check it loaded and has both functions. + #[cfg(feature = "metal-backend")] + if native && !crate::gpu::metal::module_ready(&shader) { + let _ = (pollster::block_on(internal.pop()), pollster::block_on(validation.pop())); + eprintln!("rune: uber_windfoil_native.metallib didn't load; Windfoil text compiles its shader from WGSL"); + return None; + } + let pipeline = make_pipeline(&super::dxbc::Shaders::one(shader.clone())); + if let Some(error) = pollster::block_on(internal.pop()).or(pollster::block_on(validation.pop())) { + eprintln!("rune: uber_windfoil.metallib was refused ({error}); Windfoil text compiles its shader from WGSL"); + return None; + } + Some((shader, pipeline)) +} diff --git a/app/vendor/rune/crates/rune/src/rewind/bundle.rs b/app/vendor/rune/crates/rune/src/rewind/bundle.rs new file mode 100644 index 0000000..3aabda9 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/rewind/bundle.rs @@ -0,0 +1,220 @@ +//! A stretch of a clip as a folder someone else can read: `trace.jsonl` (motion-lint's format), +//! `contact.png` (a contact sheet drawn from the recorded rects) and `summary.md`. + +use std::fmt::Write as _; +use std::io::Write as _; +use std::ops::Range; +use std::path::{Path, PathBuf}; + +use super::clip::{Change, Clip, Shot}; + +/// What [`Clip::write_bundle`] wrote. +#[derive(Clone, Debug)] +pub struct Bundle { + dir: PathBuf, + summary: String, + frames: Range<usize>, +} + +impl Bundle { + /// The folder. + pub fn dir(&self) -> &Path { &self.dir } + /// `summary.md`'s text: the note, the stretch, the jumps and what moved most. + pub fn summary(&self) -> &str { &self.summary } + /// The frames it holds. + pub fn frames(&self) -> Range<usize> { self.frames.clone() } + /// The files in it. + pub fn files(&self) -> [PathBuf; 3] { + ["summary.md", "trace.jsonl", "contact.png"].map(|f| self.dir.join(f)) + } +} + +const TILE_W: u32 = 320; +const TILES: usize = 12; +const COLS: usize = 4; + +impl Clip { + /// Writes frames `range` (clamped to the clip) into `dir`, created if missing, with `note` + /// at the top of the summary. + pub fn write_bundle(&self, dir: &Path, range: Range<usize>, note: &str) -> std::io::Result<Bundle> { + let end = range.end.min(self.len()); + let range = range.start.min(end.saturating_sub(1))..end.max(1).min(self.len()); + std::fs::create_dir_all(dir)?; + let changes: Vec<Vec<Change>> = range.clone().map(|k| self.changes(k)).collect(); + self.write_trace(&dir.join("trace.jsonl"), range.clone())?; + let tiles = self.pick_tiles(range.clone()); + self.write_contact(&dir.join("contact.png"), &tiles)?; + let summary = self.summary_text(range.clone(), note, &changes, &tiles); + std::fs::write(dir.join("summary.md"), &summary)?; + Ok(Bundle { dir: dir.to_owned(), summary, frames: range }) + } + + fn write_trace(&self, path: &Path, range: Range<usize>) -> std::io::Result<()> { + let mut out = std::io::BufWriter::new(std::fs::File::create(path)?); + let hz = (1.0 / self.frame_interval()).round(); + writeln!(out, r#"{{"type":"header","launch":"rune-rewind","width":{},"height":{},"hz":{hz},"scale":1,"platform":"rune","units":"pt","clock":"wall"}}"#, + self.viewport.0, self.viewport.1)?; + let mut described = vec![false; self.names.len()]; + let start_t = self.time(range.start); + let first = range.start; + let mut last: Vec<Option<Shot>> = vec![None; self.names.len()]; + let mut state: Vec<Option<Shot>> = vec![None; self.names.len()]; + for (id, shot) in self.before(first) { + state[id as usize] = Some(shot); + } + for k in range { + for c in self.changes(k) { state[c.id as usize] = c.after; } + let mut line = String::new(); + write!(line, r#"{{"t":{:.3},"n":1"#, (self.time(k) - start_t) * 1000.0).ok(); + let (mut metas, mut elems, mut gone) = (Vec::new(), Vec::new(), Vec::new()); + for (i, now) in state.iter().enumerate() { + if *now == last[i] { continue; } + match now { + Some(s) => { + if !described[i] { + described[i] = true; + metas.push(format!(r#"{{"id":{},"cls":"rune","nm":{},"host":"rune"}}"#, i + 1, json_str(&self.names[i]))); + } + let [x, y, w, h] = s.rect; + elems.push(format!("[{},{x},{y},{w},{h},{},0,0]", i + 1, s.opacity)); + } + None => gone.push((i + 1).to_string()), + } + last[i] = *now; + } + if !metas.is_empty() { write!(line, r#","m":[{}]"#, metas.join(",")).ok(); } + if !elems.is_empty() { write!(line, r#","e":[{}]"#, elems.join(",")).ok(); } + if !gone.is_empty() { write!(line, r#","g":[{}]"#, gone.join(",")).ok(); } + line.push('}'); + writeln!(out, "{line}")?; + } + out.flush() + } + + /// Up to `TILES` frames: every jump first, then the busiest of the rest, in order. + fn pick_tiles(&self, range: Range<usize>) -> Vec<usize> { + let mut picked: Vec<usize> = range.clone().filter(|&k| self.has_jump(k)).take(TILES).collect(); + let mut rest: Vec<usize> = range.clone().filter(|&k| !self.has_jump(k) && self.activity(k) > 0.0).collect(); + rest.sort_by(|a, b| self.activity(*b).total_cmp(&self.activity(*a))); + picked.extend(rest.into_iter().take(TILES.saturating_sub(picked.len()))); + if picked.is_empty() { picked.push(range.end.saturating_sub(1)); } + picked.sort_unstable(); + picked + } + + fn write_contact(&self, path: &Path, tiles: &[usize]) -> std::io::Result<()> { + let (vw, vh) = (self.viewport.0.max(1.0), self.viewport.1.max(1.0)); + let scale = TILE_W as f32 / vw; + let tile_h = ((vh * scale).round() as u32).max(1); + let cols = COLS.min(tiles.len()).max(1); + let rows = tiles.len().div_ceil(cols); + let gap = 8; + let (w, h) = (cols as u32 * (TILE_W + gap) + gap, rows as u32 * (tile_h + gap) + gap); + let mut px = vec![0u8; (w * h * 4) as usize]; + for p in px.chunks_exact_mut(4) { p.copy_from_slice(&[10, 10, 12, 255]); } + let mut canvas = Canvas { px: &mut px, w, h }; + for (n, &k) in tiles.iter().enumerate() { + let (ox, oy) = ((n % cols) as u32 * (TILE_W + gap) + gap, (n / cols) as u32 * (tile_h + gap) + gap); + canvas.fill(ox, oy, TILE_W, tile_h, [24, 24, 28]); + let at = |r: [f32; 4]| [ox as f32 + r[0] * scale, oy as f32 + r[1] * scale, r[2] * scale, r[3] * scale]; + let clip = [ox as f32, oy as f32, TILE_W as f32, tile_h as f32]; + for (_, s) in self.frame(k) { + let grey = (40.0 + 80.0 * s.opacity.clamp(0.0, 1.0)) as u8; + canvas.outline(at(s.rect), clip, [grey, grey, grey + 6]); + } + for c in self.changes(k).iter().rev() { + let Some(s) = c.after.or(c.before) else { continue }; + let color = if c.jump { [255, 84, 84] } else { [255, 204, 64] }; + if let Some(b) = c.before.filter(|_| c.after.is_some()) { canvas.outline(at(b.rect), clip, [110, 90, 40]); } + canvas.outline(at(s.rect), clip, color); + } + } + crate::render::write_png(path, w, h, &px) + } + + fn summary_text(&self, range: Range<usize>, note: &str, changes: &[Vec<Change>], tiles: &[usize]) -> String { + let mut s = String::from("# Rewind clip\n\n"); + if !note.trim().is_empty() { writeln!(s, "> {}\n", note.trim().replace('\n', "\n> ")).ok(); } + let hz = (1.0 / self.frame_interval()).round(); + writeln!(s, "Frames {}–{} of {} ({:.2} s to {:.2} s before the freeze, {} frames at {hz} Hz), window {}×{} pt.\n", + range.start, range.end.saturating_sub(1), self.len(), self.time(range.start), self.time(range.end.saturating_sub(1)), + range.len(), self.viewport.0, self.viewport.1).ok(); + let jumps: Vec<String> = range.clone().zip(changes).flat_map(|(k, cs)| { + cs.iter().filter(|c| c.jump).map(move |c| format!("- frame {k} ({:.2} s): {}", self.time(k), c.label())) + }).collect(); + if !jumps.is_empty() { + writeln!(s, "## Jumps\n\nMoved much further in one frame than in the frames either side.\n\n{}\n", jumps.join("\n")).ok(); + } + // Per element: how many frames it changed in, and its largest single-frame move. + let mut most: Vec<(u32, usize, f32, usize, String)> = Vec::new(); + for (k, cs) in range.clone().zip(changes) { + for c in cs { + let d = c.distance(); + match most.iter_mut().find(|m| m.0 == c.id) { + Some(m) => { m.1 += 1; if d > m.2 { (m.2, m.3, m.4) = (d, k, c.label()); } } + None => most.push((c.id, 1, d, k, c.label())), + } + } + } + most.sort_by(|a, b| b.2.total_cmp(&a.2)); + if !most.is_empty() { + writeln!(s, "## Moved most\n").ok(); + for (_, n, _, k, label) in most.iter().take(12) { + writeln!(s, "- {label} at frame {k} (changed in {n} frames)").ok(); + } + writeln!(s).ok(); + } + writeln!(s, "## Files\n\n- `trace.jsonl`: every element's rect and opacity per frame, motion-lint's format (`motion-lint analyze trace.jsonl`).\n- `contact.png`: frames {} drawn from the recorded rects, left to right. Grey: on screen. Yellow: changed in that frame, its old place dimmer. Red: jumped.", + tiles.iter().map(usize::to_string).collect::<Vec<_>>().join(", ")).ok(); + s + } +} + +struct Canvas<'a> { + px: &'a mut [u8], + w: u32, + h: u32, +} + +impl Canvas<'_> { + fn put(&mut self, x: i64, y: i64, c: [u8; 3]) { + if x < 0 || y < 0 || x >= self.w as i64 || y >= self.h as i64 { return; } + let i = ((y as u32 * self.w + x as u32) * 4) as usize; + self.px[i..i + 3].copy_from_slice(&c); + } + + fn fill(&mut self, x: u32, y: u32, w: u32, h: u32, c: [u8; 3]) { + for yy in y..(y + h).min(self.h) { for xx in x..(x + w).min(self.w) { self.put(xx as i64, yy as i64, c); } } + } + + /// A one-pixel outline of `r`, cut to `clip`. + fn outline(&mut self, r: [f32; 4], clip: [f32; 4], c: [u8; 3]) { + let (x0, y0) = (r[0].max(clip[0]), r[1].max(clip[1])); + let (x1, y1) = ((r[0] + r[2]).min(clip[0] + clip[2] - 1.0), (r[1] + r[3]).min(clip[1] + clip[3] - 1.0)); + if x1 < x0 || y1 < y0 { return; } + let (ax, ay, bx, by) = (x0.round() as i64, y0.round() as i64, x1.round() as i64, y1.round() as i64); + for x in ax..=bx { + if r[1] >= clip[1] { self.put(x, ay, c); } + if r[1] + r[3] <= clip[1] + clip[3] { self.put(x, by, c); } + } + for y in ay..=by { + if r[0] >= clip[0] { self.put(ax, y, c); } + if r[0] + r[2] <= clip[0] + clip[2] { self.put(bx, y, c); } + } + } +} + +fn json_str(s: &str) -> String { + let mut out = String::with_capacity(s.len() + 2); + out.push('"'); + for c in s.chars() { + match c { + '"' => out.push_str("\\\""), + '\\' => out.push_str("\\\\"), + c if (c as u32) < 0x20 => { write!(out, "\\u{:04x}", c as u32).ok(); } + c => out.push(c), + } + } + out.push('"'); + out +} diff --git a/app/vendor/rune/crates/rune/src/rewind/clip.rs b/app/vendor/rune/crates/rune/src/rewind/clip.rs new file mode 100644 index 0000000..db2fd40 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/rewind/clip.rs @@ -0,0 +1,262 @@ +//! A frozen copy of the recording, for scrubbing: any frame's elements, what changed in it, how +//! much moved, and where one element went over time. + +use super::tape::{FIELDS, Q, Tape}; + +/// Checkpoints every this many frames, so rebuilding a frame replays at most this many. +const STRIDE: usize = 64; + +/// One element as a frame presented it: `[x, y, w, h]` in points and opacity. +#[derive(Clone, Copy, Debug, PartialEq)] +#[non_exhaustive] +pub struct Shot { + pub rect: [f32; 4], + pub opacity: f32, +} + +impl Shot { + pub(crate) fn of(q: &Q) -> Shot { + Shot { rect: [q[0], q[1], q[2], q[3]].map(|v| v as f32 / 100.0), opacity: q[4] as f32 / 1000.0 } + } + + /// The largest change of an edge or side from `other`, in points. + pub fn distance(&self, other: &Shot) -> f32 { + let (a, b) = (self.rect, other.rect); + let edges = |r: [f32; 4]| [r[0], r[1], r[0] + r[2], r[1] + r[3]]; + edges(a).iter().zip(edges(b)).map(|(x, y)| (x - y).abs()).fold(0.0, f32::max) + } +} + +/// An element whose rect or opacity changed in a frame. +#[derive(Clone, Debug, PartialEq)] +#[non_exhaustive] +pub struct Change { + /// The element's id in this clip (stable for its whole run). + pub id: u32, + pub name: String, + /// None: it appeared in this frame. + pub before: Option<Shot>, + /// None: it went away in this frame. + pub after: Option<Shot>, + /// It moved much further in this frame than in the frames either side: a likely glitch. + pub jump: bool, +} + +impl Change { + /// Points it moved (its largest edge change); 0 when it appeared or went. + pub fn distance(&self) -> f32 { + match (self.before, self.after) { + (Some(a), Some(b)) => a.distance(&b), + _ => 0.0, + } + } + + /// A short label: `title ↓7.9 pt`, `card w +12 pt`, `toast 0.40→1.00`, `row appears`. + pub fn label(&self) -> String { + let (Some(a), Some(b)) = (self.before, self.after) else { + return format!("{} {}", self.name, if self.after.is_some() { "appears" } else { "goes" }); + }; + let mut parts = Vec::new(); + let d = |x: f32| if x.abs() >= 10.0 { format!("{:.0}", x.abs()) } else { format!("{:.1}", x.abs()) }; + let (dx, dy) = (b.rect[0] - a.rect[0], b.rect[1] - a.rect[1]); + let (dw, dh) = (b.rect[2] - a.rect[2], b.rect[3] - a.rect[3]); + if dy.abs() >= 0.05 { parts.push(format!("{}{}", if dy > 0.0 { "↓" } else { "↑" }, d(dy))); } + if dx.abs() >= 0.05 { parts.push(format!("{}{}", if dx > 0.0 { "→" } else { "←" }, d(dx))); } + if dw.abs() >= 0.05 { parts.push(format!("w {}{}", if dw > 0.0 { "+" } else { "−" }, d(dw))); } + if dh.abs() >= 0.05 { parts.push(format!("h {}{}", if dh > 0.0 { "+" } else { "−" }, d(dh))); } + let mut label = self.name.clone(); + if !parts.is_empty() { label = format!("{label} {} pt", parts.join(" ")); } + if (b.opacity - a.opacity).abs() >= 0.005 { label = format!("{label} {:.2}→{:.2}", a.opacity, b.opacity); } + label + } +} + +/// The last stretch of a window's frames, frozen by [`Rewind::freeze`](super::Rewind::freeze). +pub struct Clip { + pub(crate) names: Vec<String>, + pub(crate) viewport: (f32, f32), + times: Vec<f64>, + starts: Vec<usize>, + words: Vec<u32>, + checkpoints: Vec<Vec<(u32, Q)>>, + activity: Vec<f32>, + jumps: Vec<Vec<u32>>, +} + +impl Clip { + pub(crate) fn from_tape(tape: &Tape) -> Clip { + let words: Vec<u32> = tape.words.iter().copied().collect(); + let mut starts = Vec::with_capacity(tape.frames.len() + 1); + let mut times = Vec::with_capacity(tape.frames.len()); + let mut at = 0; + for m in &tape.frames { + starts.push(at); + times.push(m.t); + at += m.len as usize; + } + starts.push(at); + let mut clip = Clip { + names: tape.names.clone(), viewport: tape.viewport, times, starts, words, + checkpoints: Vec::new(), activity: Vec::new(), jumps: Vec::new(), + }; + clip.index(&tape.base); + clip + } + + /// One pass over every frame: checkpoints, how far things moved, and jumps. + fn index(&mut self, base: &[Option<Q>]) { + let n = self.len(); + let mut state: Vec<Option<Q>> = base.to_vec(); + state.resize(self.names.len(), None); + // Per frame: each element that moved, how far, and where it was before and after. + let mut moved: Vec<Vec<(u32, f32, Shot, Shot)>> = Vec::with_capacity(n); + self.activity = Vec::with_capacity(n); + for k in 0..n { + if k % STRIDE == 0 { + self.checkpoints.push(state.iter().enumerate().filter_map(|(i, q)| q.map(|q| (i as u32, q))).collect()); + } + let mut frame = Vec::new(); + let mut most = 0.0f32; + let mut faded = false; + Tape::decode(&self.words[self.starts[k]..self.starts[k + 1]], |id, mask, values| { + let i = id as usize; + if mask == 0 { state[i] = None; return; } + let before = state[i]; + let mut q = before.unwrap_or([0; FIELDS]); + for f in 0..FIELDS { if mask & (1 << f) != 0 { q[f] = values[f]; } } + state[i] = Some(q); + if let Some(b) = before { + let d = Shot::of(&b).distance(&Shot::of(&q)); + if d > 0.0 { frame.push((id, d, Shot::of(&b), Shot::of(&q))); most = most.max(d); } + faded |= b[4] != q[4]; + } + }); + // An opacity change alone still shows on the track, faintly. + self.activity.push(if most == 0.0 && faded { 0.25 } else { most }); + moved.push(frame); + } + let find = |k: usize, id: u32| moved.get(k).and_then(|f| f.iter().find(|m| m.0 == id)); + self.jumps = (0..n).map(|k| { + moved[k].iter().filter(|&&(id, d, was, _)| { + let near = k.checked_sub(1).and_then(|p| find(p, id)).map_or(0.0, |m| m.1).max(find(k + 1, id).map_or(0.0, |m| m.1)); + // A blip: out in this frame and straight back in the next. + let back = find(k + 1, id).is_some_and(|m| m.3.distance(&was) < 0.5); + d >= 4.0 && (d > 2.5 * near || back) + }).map(|m| m.0).collect() + }).collect(); + } + + /// Frames in the clip. + pub fn len(&self) -> usize { self.times.len() } + + pub fn is_empty(&self) -> bool { self.times.is_empty() } + + /// The window's size in points when the last frame was recorded. + pub fn viewport(&self) -> (f32, f32) { self.viewport } + + /// Seconds from the last frame to frame `k` (0 for the last, negative before it). + pub fn time(&self, k: usize) -> f64 { + match (self.times.get(k), self.times.last()) { + (Some(t), Some(last)) => t - last, + _ => 0.0, + } + } + + /// Seconds the clip covers. + pub fn duration(&self) -> f64 { -self.time(0) } + + /// The largest move of any element in frame `k`, in points (0.25 when only opacity changed). + pub fn activity(&self, k: usize) -> f32 { self.activity.get(k).copied().unwrap_or(0.0) } + + /// Frame `k` has an element that jumped (see [`Change::jump`]). + pub fn has_jump(&self, k: usize) -> bool { self.jumps.get(k).is_some_and(|j| !j.is_empty()) } + + /// An element's name: its trace name, key or path. + pub fn name(&self, id: u32) -> &str { self.names.get(id as usize).map_or("", String::as_str) } + + /// Every element on screen after frame `k`. + pub fn frame(&self, k: usize) -> Vec<(u32, Shot)> { + self.state(k).iter().enumerate().filter_map(|(i, q)| q.map(|q| (i as u32, Shot::of(&q)))).collect() + } + + /// Every element on screen just before frame `k`. + pub(crate) fn before(&self, k: usize) -> Vec<(u32, Shot)> { + let state = if k == 0 { self.checkpoint_state(0) } else { self.state(k - 1) }; + state.iter().enumerate().filter_map(|(i, q)| q.map(|q| (i as u32, Shot::of(&q)))).collect() + } + + /// The elements whose rect or opacity changed in frame `k`, furthest moved first. + pub fn changes(&self, k: usize) -> Vec<Change> { + if k >= self.len() { return Vec::new(); } + let before = if k == 0 { self.checkpoint_state(0) } else { self.state(k - 1) }; + let mut out = Vec::new(); + Tape::decode(&self.words[self.starts[k]..self.starts[k + 1]], |id, mask, values| { + let b = before.get(id as usize).copied().flatten(); + let after = (mask != 0).then(|| { + let mut q = b.unwrap_or([0; FIELDS]); + for f in 0..FIELDS { if mask & (1 << f) != 0 { q[f] = values[f]; } } + Shot::of(&q) + }); + let jump = self.jumps[k].contains(&id); + out.push(Change { id, name: self.name(id).to_owned(), before: b.map(|q| Shot::of(&q)), after, jump }); + }); + out.sort_by(|a, b| b.jump.cmp(&a.jump).then(b.distance().total_cmp(&a.distance()))); + out + } + + /// Where element `id` was in each frame of `range` it was on screen. + pub fn path(&self, id: u32, range: std::ops::Range<usize>) -> Vec<(usize, Shot)> { + let range = range.start.min(self.len())..range.end.min(self.len()); + let mut state = if range.start == 0 { self.checkpoint_state(0) } else { self.state(range.start - 1) }; + let mut out = Vec::new(); + for k in range { + self.apply(k, &mut state); + if let Some(q) = state.get(id as usize).copied().flatten() { out.push((k, Shot::of(&q))); } + } + out + } + + /// The next frame from `k` in direction `step` (±1) where anything moved. + pub fn next_active(&self, k: usize, step: isize) -> Option<usize> { + let mut i = k as isize + step; + while i >= 0 && (i as usize) < self.len() { + if self.activity(i as usize) > 0.0 { return Some(i as usize); } + i += step; + } + None + } + + fn checkpoint_state(&self, c: usize) -> Vec<Option<Q>> { + let mut state = vec![None; self.names.len()]; + for &(id, q) in self.checkpoints.get(c).map_or(&[][..], Vec::as_slice) { state[id as usize] = Some(q); } + state + } + + fn apply(&self, k: usize, state: &mut [Option<Q>]) { + Tape::decode(&self.words[self.starts[k]..self.starts[k + 1]], |id, mask, values| { + let i = id as usize; + if mask == 0 { state[i] = None; return; } + let mut q = state[i].unwrap_or([0; FIELDS]); + for f in 0..FIELDS { if mask & (1 << f) != 0 { q[f] = values[f]; } } + state[i] = Some(q); + }); + } + + /// Every element's state after frame `k`. + pub(crate) fn state(&self, k: usize) -> Vec<Option<Q>> { + let k = k.min(self.len().saturating_sub(1)); + let c = k / STRIDE; + let mut state = self.checkpoint_state(c); + if self.is_empty() { return state; } + for f in c * STRIDE..=k { self.apply(f, &mut state); } + state + } + + /// Seconds between frames, the median. + pub(crate) fn frame_interval(&self) -> f64 { + let mut dts: Vec<f64> = self.times.windows(2).map(|w| w[1] - w[0]).filter(|d| *d > 0.0).collect(); + if dts.is_empty() { return 1.0 / 60.0; } + dts.sort_by(f64::total_cmp); + dts[dts.len() / 2] + } +} diff --git a/app/vendor/rune/crates/rune/src/rewind/mod.rs b/app/vendor/rune/crates/rune/src/rewind/mod.rs new file mode 100644 index 0000000..84e8f95 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/rewind/mod.rs @@ -0,0 +1,103 @@ +//! Rewind: an opt-in recorder of the last minute of what a window presented, and a scrubber to +//! step back through it and hand a stretch to someone. +//! +//! Attach a [`Rewind`] with [`Tx::record_rewind`](crate::Tx::record_rewind) and every presented +//! frame records the rect and opacity of each keyed or trace-named element that changed, delta +//! encoded, in a ring that keeps the last 60 seconds (or less, within a byte budget). Nothing is +//! attached by default, and then a frame does nothing more than check for it. +//! +//! [`Rewind::freeze`] pauses recording and hands back a [`Clip`]: any frame's elements, what +//! changed in each frame and by how much, and an element's path over time. [`Scrub`] is a +//! ready-made scrubber over a clip: the view lays [`Scrub::view`] over its own, with its own +//! subtree's clock paused (`El::time_scale(0.0)`), and Send gives the app the selected +//! stretch, which [`Clip::write_bundle`] turns into a folder (a motion-lint trace, a contact +//! sheet and a summary). +//! +//! ```ignore +//! // Start recording (a setting turned on): +//! tx.record_rewind(Some(&s.rewind)); +//! // A shortcut freezes it: +//! s.scrub.open(&s.rewind); +//! // The view, always wrapped the same way so the app's elements keep their paths: +//! el().child(app_view.time_scale(if s.scrub.is_open() { 0.0 } else { 1.0 })) +//! .child(s.scrub.view(|s: &mut App| &mut s.scrub, |s, sent, tx| { ... })) +//! ``` + +mod bundle; +mod clip; +mod scrub; +mod tape; +mod track; + +#[cfg(test)] +mod tests; + +pub use bundle::Bundle; +pub use clip::{Change, Clip, Shot}; +pub use scrub::{Keyed, Scrub, Sent}; + +pub(crate) use tape::quantize; + +use std::sync::{Arc, Mutex, MutexGuard, PoisonError}; + +/// A recorder handle: cheap to clone, shared by the app and the window it's attached to. +#[derive(Clone)] +pub struct Rewind { + tape: Arc<Mutex<tape::Tape>>, +} + +impl Default for Rewind { + fn default() -> Self { Self::new() } +} + +impl std::fmt::Debug for Rewind { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("Rewind").field("frames", &self.frames()).field("bytes", &self.bytes()).finish() + } +} + +impl Rewind { + /// Keeps the last 60 seconds, within 24 MB. + pub fn new() -> Self { + Rewind { tape: Arc::new(Mutex::new(tape::Tape::new(60.0, 24 << 20))) } + } + + /// Keep the last `seconds` (at least one frame is always kept). + pub fn seconds(self, seconds: f64) -> Self { + self.lock().window = seconds.max(0.0); + self + } + + /// Drop the oldest frames once the recording holds more than `bytes`. + pub fn max_bytes(self, bytes: usize) -> Self { + self.lock().max_bytes = bytes; + self + } + + /// Pauses recording and copies out what it holds. [`Rewind::resume`] carries on. + pub fn freeze(&self) -> Arc<Clip> { + let mut tape = self.lock(); + tape.paused = true; + Arc::new(Clip::from_tape(&tape)) + } + + /// Records again after [`Rewind::freeze`], from where it left off. + pub fn resume(&self) { + self.lock().paused = false; + } + + pub fn is_paused(&self) -> bool { self.lock().paused } + + /// Frames held. + pub fn frames(&self) -> usize { self.lock().frames.len() } + + /// Bytes the recording holds, roughly. + pub fn bytes(&self) -> usize { self.lock().bytes() } + + /// A window at rest (`window::rest`): what the recording no longer refers to goes. + pub(crate) fn rest(&self) { self.lock().rest(); } + + pub(crate) fn lock(&self) -> MutexGuard<'_, tape::Tape> { + self.tape.lock().unwrap_or_else(PoisonError::into_inner) + } +} diff --git a/app/vendor/rune/crates/rune/src/rewind/scrub.rs b/app/vendor/rune/crates/rune/src/rewind/scrub.rs new file mode 100644 index 0000000..445771b --- /dev/null +++ b/app/vendor/rune/crates/rune/src/rewind/scrub.rs @@ -0,0 +1,297 @@ +//! The scrubber: a frozen clip's frames over the window, one at a time, with the elements that +//! moved outlined and labelled, a track along the bottom that lights up where things moved, and +//! Send for the selected stretch. + +use std::ops::Range; +use std::sync::Arc; + +use crate::edit::{Key, KeyEvent}; +use crate::tok::{self, type_}; +use crate::{Color, El, Tx, col, el, row, spacer, text, text_input}; + +use super::bundle::Bundle; +use super::clip::{Change, Clip, Shot}; +use super::Rewind; + +/// The bar along the window's foot, in points. +pub(crate) const BAR_H: f32 = 92.0; +pub(crate) const TRACK_H: f32 = 34.0; +pub(crate) const PAD: f32 = 12.0; +/// Frames of an element's path shown either side of the playhead when nothing is selected. +const PATH_SPAN: usize = 90; +/// Narrower than this, the bar drops its key hints. +const HINT_MIN_W: f32 = 760.0; + +pub(crate) fn moved_color() -> Color { crate::oklch(0.86, 0.15, 85.0) } +pub(crate) fn jump_color() -> Color { crate::oklch(0.68, 0.2, 25.0) } + +/// The scrubber's state; keep one in the app's state. +#[derive(Default)] +pub struct Scrub { + showing: Showing, + frame: usize, + anchor: Option<usize>, + picked: Option<u32>, + note: crate::TextEdit, +} + +#[derive(Default)] +enum Showing { + #[default] + Closed, + /// `clip` over the window; `held` is the recorder it froze, which closing resumes. + Open { clip: Arc<Clip>, held: Option<Rewind> }, +} + +/// What a press of a key did ([`Scrub::key`]). +#[derive(Debug)] +#[non_exhaustive] +pub enum Keyed { + /// Not the scrubber's key. + Ignored, + Handled, + /// Escape: the scrubber closed and recording resumed. + Closed, + /// Return: send the selected stretch. + Send(Sent), +} + +/// A stretch of frames to hand on, with the note typed for it. +#[derive(Clone)] +pub struct Sent { + clip: Arc<Clip>, + frames: Range<usize>, + note: String, +} + +impl std::fmt::Debug for Sent { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("Sent").field("frames", &self.frames).field("note", &self.note).finish() + } +} + +impl Sent { + pub fn clip(&self) -> &Arc<Clip> { &self.clip } + pub fn frames(&self) -> Range<usize> { self.frames.clone() } + pub fn note(&self) -> &str { &self.note } + /// [`Clip::write_bundle`] for this stretch and note. + pub fn write(&self, dir: &std::path::Path) -> std::io::Result<Bundle> { + self.clip.write_bundle(dir, self.frames.clone(), &self.note) + } +} + +impl Scrub { + /// Freezes `rewind` and shows its clip at the last frame anything moved in. A recorder an + /// earlier `open` froze records again. + pub fn open(&mut self, rewind: &Rewind) { + self.close(); + let clip = rewind.freeze(); + self.show_from(clip, Some(rewind.clone())); + } + + /// Shows `clip` without a recorder behind it (a story, a saved clip). A recorder an + /// earlier `open` froze stays frozen until [`close`](Self::close). + pub fn show(&mut self, clip: Arc<Clip>) { + let held = match std::mem::take(&mut self.showing) { + Showing::Open { held, .. } => held, + Showing::Closed => None, + }; + self.show_from(clip, held); + } + + fn show_from(&mut self, clip: Arc<Clip>, held: Option<Rewind>) { + let last = clip.len().saturating_sub(1); + self.frame = if clip.activity(last) > 0.0 { last } else { clip.next_active(last, -1).unwrap_or(last) }; + self.showing = Showing::Open { clip, held }; + self.anchor = None; + self.picked = None; + self.note = crate::TextEdit::default(); + } + + /// Hides the scrubber and resumes recording. + pub fn close(&mut self) { + if let Showing::Open { held: Some(rewind), .. } = std::mem::take(&mut self.showing) { rewind.resume(); } + } + + pub fn is_open(&self) -> bool { self.clip().is_some() } + + pub fn clip(&self) -> Option<&Arc<Clip>> { + match &self.showing { + Showing::Open { clip, .. } => Some(clip), + Showing::Closed => None, + } + } + + /// The frame showing. + pub fn frame(&self) -> usize { self.frame } + + /// The selected frames: from the anchor ⇧ set to the playhead, or the playhead alone. + pub fn selection(&self) -> Range<usize> { + let a = self.anchor.unwrap_or(self.frame); + a.min(self.frame)..a.max(self.frame) + 1 + } + + /// Shows frame `k`; with `extend`, selects from where the selection started to it. + pub fn seek(&mut self, k: usize, extend: bool) { + let Some(len) = self.clip().map(|clip| clip.len()) else { return }; + let k = k.min(len.saturating_sub(1)); + if extend { self.anchor.get_or_insert(self.frame); } else { self.anchor = None; } + self.frame = k; + } + + /// Shows element `id`'s path over time (None hides it). + pub fn pick(&mut self, id: Option<u32>) { self.picked = id; } + + /// The note typed so far. + pub fn note(&self) -> &str { &self.note.text } + + pub fn set_note(&mut self, note: &str) { + self.note = crate::TextEdit::default(); + self.note.insert(note); + } + + /// What Send would hand on now. + pub fn sent(&self) -> Option<Sent> { + Some(Sent { clip: self.clip()?.clone(), frames: self.selection(), note: self.note.text.clone() }) + } + + /// ←/→ step a frame (⇧ selects, ⌥ jumps to the next frame anything moved in), Home/End go + /// to the ends, Return sends and Escape closes. Route the app's unhandled keys here while + /// [`Scrub::is_open`]. + pub fn key(&mut self, ev: &KeyEvent) -> Keyed { + let Some(clip) = self.clip().cloned() else { return Keyed::Ignored }; + let extend = ev.mods.shift; + let step = |dir: isize| if ev.mods.alt { clip.next_active(self.frame, dir) } else { self.frame.checked_add_signed(dir) }; + match ev.key { + Key::Left => { if let Some(k) = step(-1) { self.seek(k, extend); } } + Key::Right => { if let Some(k) = step(1) { self.seek(k, extend); } } + Key::Home => self.seek(0, extend), + Key::End => self.seek(clip.len(), extend), + Key::Escape => { self.close(); return Keyed::Closed; } + Key::Enter => return self.sent().map_or(Keyed::Handled, Keyed::Send), + _ => return Keyed::Ignored, + } + Keyed::Handled + } + + /// The scrubber over the whole window, or nothing while closed. Lay it over the app's view; + /// it lines its outlines up with the window wherever it sits, so a story can show it on a + /// stage. Pause the app's subtree (`El::time_scale(0.0)`) while it shows, not the window's + /// clock: the scrubber itself still animates. `lens` finds this state in the app's; Send + /// (the button, or Return in the note) calls `on_send`. + #[inline] + pub fn view<S: 'static>(&self, lens: fn(&mut S) -> &mut Scrub, on_send: fn(&mut S, Sent, &mut Tx)) -> El { + self.view_inner(&ScrubActions { + clear_pick: &|e| e.on_press(move |s: &mut S| lens(s).picked = None), + toggle_pick: &|e, id| e.on_press(move |s: &mut S| { + let scrub = lens(s); + scrub.picked = if scrub.picked == Some(id) { None } else { Some(id) }; + }), + send: &|e| e.on_press_tx(move |s: &mut S, tx: &mut Tx| if let Some(sent) = lens(s).sent() { on_send(s, sent, tx); }), + note: &|e| e + .on_edit(move |s: &mut S| &mut lens(s).note) + .on_submit(move |s: &mut S, tx: &mut Tx| if let Some(sent) = lens(s).sent() { on_send(s, sent, tx); }), + track_drag: &|e| e.on_drag(move |s: &mut S, d: &mut crate::Drag, tx: &mut Tx| super::track::drag(lens(s), d, tx)), + }) + } + + fn view_inner(&self, actions: &ScrubActions<'_>) -> El { + let Some(clip) = self.clip() else { return el() }; + let (vw, vh) = clip.viewport(); + let [ox, oy, w, _] = crate::memo::layout_with("rewind", |r| r.map(|v| (v * 2.0).round() / 2.0)).unwrap_or([0.0, 0.0, vw, vh]); + let changes = clip.changes(self.frame); + // The live view under it keeps changing; dimmed, the recorded frame reads over it. + let dim = (actions.clear_pick)(el().key("rewind-dim").pin(Some(0.0), Some(0.0), Some(0.0), Some(0.0)).fill(Color::BLACK.alpha(0.55))); + let layer = el().key("rewind").pin(Some(0.0), Some(0.0), Some(0.0), Some(0.0)).child(dim); + // Recorded frames: they land where they were, never springing between steps. + let mut marks = el().key("rewind-marks").absolute(-ox, -oy).size(vw, vh).motion(crate::Spring::NONE); + for (id, shot) in clip.frame(self.frame) { + if changes.iter().any(|c| c.id == id) { continue; } + let r = shot.rect; + marks = marks.child(el().key(format!("rewind-el-{id}")).absolute(r[0], r[1]).size(r[2].max(1.0), r[3].max(1.0)) + .border(0.5, Color::WHITE.alpha(0.08 + 0.14 * shot.opacity.clamp(0.0, 1.0)))); + } + if let Some(id) = self.picked { marks = marks.children(self.path_view(clip, id)); } + for c in changes.iter().rev() { marks = marks.children(outline(c, actions.toggle_pick)); } + if let Some(id) = self.picked.filter(|id| !changes.iter().any(|c| c.id == *id)) + && let Some((_, s)) = clip.frame(self.frame).into_iter().find(|(i, _)| *i == id) + { + marks = marks.child(el().key("rewind-picked").absolute(s.rect[0], s.rect[1]).size(s.rect[2].max(1.0), s.rect[3].max(1.0)).border(1.0, Color::WHITE.alpha(0.7))); + } + layer.child(marks).child(self.bar(clip, w, &changes, actions)) + } + + fn path_view(&self, clip: &Clip, id: u32) -> Vec<El> { + let sel = self.selection(); + let range = if sel.len() > 1 { sel } else { self.frame.saturating_sub(PATH_SPAN)..(self.frame + PATH_SPAN + 1).min(clip.len()) }; + let path = clip.path(id, range); + let mut last: Option<Shot> = None; + path.into_iter().filter_map(|(k, s)| { + let moved = last.is_none_or(|l| l != s); + last = Some(s); + if !moved && k != self.frame { return None; } + let (cx, cy) = (s.rect[0] + s.rect[2] / 2.0, s.rect[1] + s.rect[3] / 2.0); + let r = if k == self.frame { 3.5 } else { 1.5 }; + let c = if clip.has_jump(k) { jump_color() } else { Color::WHITE.alpha(if k == self.frame { 1.0 } else { 0.55 }) }; + Some(el().key(format!("rewind-path-{k}")).absolute(cx - r, cy - r).size(r * 2.0, r * 2.0).radius(r).fill(c)) + }).collect() + } + + fn bar(&self, clip: &Clip, w: f32, changes: &[Change], actions: &ScrubActions<'_>) -> El { + let t = tok::theme(true); + let sel = self.selection(); + let moved = changes.iter().filter(|c| c.before.is_some() && c.after.is_some()).count(); + let mut facts = vec![format!("{:+.2} s", clip.time(self.frame)), format!("frame {} of {}", self.frame + 1, clip.len())]; + if moved > 0 { facts.push(format!("{moved} moved")); } + if sel.len() > 1 { facts.push(format!("{} frames selected", sel.len())); } + let track_w = (w - PAD * 2.0).max(1.0); + let send = (actions.send)(row().key("rewind-send").h(24.0).px(10.0).center_y().radius(tok::radius::SM).fill(t.card) + .border(0.5, t.card_border).hover(t.hover).press(t.press) + .role("button").label("Send these frames") + .child(text("Send").font(type_::LABEL).color(t.text))); + let note = (actions.note)(text_input(&self.note, type_::BODY).key("rewind-note").single_line().grow(1.0) + .placeholder("What's wrong here?", t.text_secondary)); + let mut controls = row().w_full().h(24.0).gap(12.0).center_y() + .child(text(facts.join(" · ")).font(type_::MONO_CAPTION.mono()).color(t.text_secondary)) + .child(note); + if w >= HINT_MIN_W { + controls = controls.child(text("←→ step ⇧ select ⌥ next move esc resume").font(type_::LABEL).color(t.text_secondary)); + } + col().key("rewind-bar").pin(Some(0.0), None, Some(0.0), Some(0.0)).h(BAR_H).px(PAD).pt(8.0).gap(8.0) + .fill(t.bg.alpha(0.96)).border(0.5, t.separator) + .child(super::track::view(clip, self.frame, sel, track_w, actions.track_drag)) + .child(controls.child(send)) + .child(spacer()) + } +} + +/// Type-erased handler binders passed from [`Scrub::view`] into the non-generic view builders. +struct ScrubActions<'a> { + clear_pick: &'a dyn Fn(El) -> El, + toggle_pick: &'a dyn Fn(El, u32) -> El, + send: &'a dyn Fn(El) -> El, + note: &'a dyn Fn(El) -> El, + track_drag: &'a dyn Fn(El) -> El, +} + +/// An element that changed this frame: its old place dim, its new place outlined, and a label. +fn outline(c: &Change, toggle_pick: &dyn Fn(El, u32) -> El) -> Vec<El> { + let Some(now) = c.after.or(c.before) else { return Vec::new() }; + let color = if c.jump { jump_color() } else { moved_color() }; + let id = c.id; + let mut out = Vec::new(); + if let (Some(b), Some(_)) = (c.before, c.after) { + out.push(el().key(format!("rewind-was-{id}")).absolute(b.rect[0], b.rect[1]).size(b.rect[2].max(1.0), b.rect[3].max(1.0)).border(1.0, color.alpha(0.35))); + } + let r = now.rect; + out.push(toggle_pick( + el().key(format!("rewind-box-{id}")).absolute(r[0], r[1]).size(r[2].max(1.0), r[3].max(1.0)) + .border(if c.after.is_some() { 1.5 } else { 1.0 }, color.alpha(if c.after.is_some() { 1.0 } else { 0.5 })) + .role("button").label(format!("Show {}'s path", c.name)), + id, + )); + let above = r[1] >= 20.0; + out.push(row().key(format!("rewind-label-{id}")).absolute(r[0], if above { r[1] - 19.0 } else { r[1] + r[3] + 2.0 }).h(17.0).px(5.0).center_y() + .radius(3.0).fill(color).child(text(c.label()).font(type_::LABEL).color(Color::BLACK))); + out +} diff --git a/app/vendor/rune/crates/rune/src/rewind/tape.rs b/app/vendor/rune/crates/rune/src/rewind/tape.rs new file mode 100644 index 0000000..ec73e5d --- /dev/null +++ b/app/vendor/rune/crates/rune/src/rewind/tape.rs @@ -0,0 +1,218 @@ +//! The recording: one entry per presented frame, each the elements whose rect or opacity changed +//! since the frame before, in a ring that drops frames older than the window (or over its byte +//! budget) into a base state, so any kept frame can be rebuilt. + +use std::collections::VecDeque; + +use crate::runtime::HashMap; + +/// An element's presented state, quantized: x, y, w, h in hundredths of a point and opacity in +/// thousandths. +pub(crate) type Q = [i32; 5]; + +pub(crate) const FIELDS: usize = 5; +/// The delta header's low bits: which fields follow. Zero says the element went away. +const MASK_BITS: u32 = 5; +/// Elements known before the first compaction (`Tape::compact`). +const COMPACT_AT: usize = 4096; + +pub(crate) fn quantize(rect: [f32; 4], opacity: f32) -> Q { + let q = |v: f32, k: f32| (v * k).round().clamp(i32::MIN as f32, i32::MAX as f32) as i32; + [q(rect[0], 100.0), q(rect[1], 100.0), q(rect[2], 100.0), q(rect[3], 100.0), q(opacity, 1000.0)] +} + +#[derive(Clone, Copy, Debug)] +pub(crate) struct Mark { + /// Seconds on the window's clock. + pub t: f64, + /// Words this frame's deltas take in `words`. + pub len: u32, +} + +pub(crate) struct Tape { + pub window: f64, + pub max_bytes: usize, + pub paused: bool, + pub viewport: (f32, f32), + ids: HashMap<u64, u32>, + pub names: Vec<String>, + name_bytes: usize, + /// Per id: its state as last recorded, and the frame serial it was last seen in. + last: Vec<Q>, + seen: Vec<u32>, + present: Vec<u32>, + next_present: Vec<u32>, + serial: u32, + open: Option<(f64, usize)>, + pub frames: VecDeque<Mark>, + pub words: VecDeque<u32>, + /// Each id's state just before the oldest kept frame (None: not on screen). + pub base: Vec<Option<Q>>, + /// Known elements past which the next frame's end forgets those nothing kept refers to. + compact_at: usize, +} + +impl Tape { + pub(crate) fn new(window: f64, max_bytes: usize) -> Tape { + Tape { + window, max_bytes, paused: false, viewport: (0.0, 0.0), + ids: HashMap::default(), names: Vec::new(), name_bytes: 0, + last: Vec::new(), seen: Vec::new(), present: Vec::new(), next_present: Vec::new(), serial: 0, + open: None, frames: VecDeque::new(), words: VecDeque::new(), base: Vec::new(), compact_at: COMPACT_AT, + } + } + + /// Starts a frame presented at `t` seconds. + pub(crate) fn begin(&mut self, t: f64, viewport: (f32, f32)) { + self.serial = self.serial.wrapping_add(1).max(1); + self.viewport = viewport; + self.open = Some((t, self.words.len())); + self.next_present.clear(); + } + + /// One element as this frame presents it. `name` runs only the first time `node` is seen. + #[inline] + pub(crate) fn sample(&mut self, node: u64, q: Q, name: impl FnOnce() -> String) { + let id = match self.ids.get(&node) { + Some(&id) => id, + None => self.intern(node, name()), + }; + self.record_sample(id, q); + } + + fn intern(&mut self, node: u64, name: String) -> u32 { + let id = self.names.len() as u32; + self.name_bytes += name.len(); + self.names.push(name); + self.ids.insert(node, id); + self.last.push([i32::MIN; FIELDS]); + self.seen.push(0); + self.base.push(None); + id + } + + fn record_sample(&mut self, id: u32, q: Q) { + let i = id as usize; + if self.seen[i] == self.serial { return; } + // On screen last frame: sampled in the frame before this one. + let was = self.seen[i] != 0 && self.seen[i] == self.serial.wrapping_sub(1); + self.seen[i] = self.serial; + self.next_present.push(id); + let old = self.last[i]; + let mut mask = 0u32; + for f in 0..FIELDS { + if !was || old[f] != q[f] { mask |= 1 << f; } + } + if mask == 0 { return; } + self.words.push_back(id << MASK_BITS | mask); + for f in 0..FIELDS { + if mask & (1 << f) != 0 { self.words.push_back(q[f] as u32); } + } + self.last[i] = q; + } + + /// Ends the frame: elements on screen last frame and not this one went away. + pub(crate) fn end(&mut self) { + let Some((t, start)) = self.open.take() else { return }; + for &id in &self.present { + if self.seen[id as usize] != self.serial { + self.words.push_back(id << MASK_BITS); + } + } + std::mem::swap(&mut self.present, &mut self.next_present); + let len = (self.words.len() - start) as u32; + self.frames.push_back(Mark { t, len }); + self.evict(t); + if self.names.len() >= self.compact_at { + self.compact(); + self.compact_at = (self.names.len() * 2).max(COMPACT_AT); + } + } + + /// A window at rest: forgets the elements nothing kept refers to now, not at the next + /// `compact_at` (each session or terminal opened and closed adds its own, and frames past + /// the window have gone into the base since), and gives back the space the ring grew to. + pub(crate) fn rest(&mut self) { + if self.paused { return; } + self.compact(); + self.compact_at = (self.names.len() * 2).max(COMPACT_AT); + self.ids.shrink_to_fit(); + self.words.shrink_to_fit(); + self.frames.shrink_to_fit(); + self.present.shrink_to_fit(); + self.next_present.shrink_to_fit(); + } + + /// Forgets the elements nothing kept refers to: not on screen, with no state before the + /// oldest kept frame, and in no kept frame. Without it every element a window ever showed + /// keeps its name and state for good (each session opened and closed adds its own), and + /// past `max_bytes` those alone evict every frame. The rest are numbered afresh. + fn compact(&mut self) { + let mut keep = vec![false; self.names.len()]; + for &id in &self.present { keep[id as usize] = true; } + for (k, b) in keep.iter_mut().zip(&self.base) { *k |= b.is_some(); } + Tape::decode(self.words.make_contiguous(), |id, _, _| keep[id as usize] = true); + let mut map = vec![u32::MAX; keep.len()]; + let mut next = 0u32; + for (m, k) in map.iter_mut().zip(&keep) { + if *k { *m = next; next += 1; } + } + let kept = |i: &usize| keep[*i]; + let names = std::mem::take(&mut self.names); + self.names = names.into_iter().enumerate().filter(|(i, _)| kept(i)).map(|(_, n)| n).collect(); + self.name_bytes = self.names.iter().map(String::len).sum(); + self.last = self.last.iter().enumerate().filter(|(i, _)| kept(i)).map(|(_, q)| *q).collect(); + self.seen = self.seen.iter().enumerate().filter(|(i, _)| kept(i)).map(|(_, s)| *s).collect(); + self.base = self.base.iter().enumerate().filter(|(i, _)| kept(i)).map(|(_, b)| *b).collect(); + self.ids.retain(|_, id| { *id = map[*id as usize]; *id != u32::MAX }); + for id in &mut self.present { *id = map[*id as usize]; } + self.next_present.clear(); + let words = self.words.make_contiguous(); + let mut k = 0; + while k < words.len() { + let mask = words[k] & ((1 << MASK_BITS) - 1); + words[k] = map[(words[k] >> MASK_BITS) as usize] << MASK_BITS | mask; + k += 1 + mask.count_ones() as usize; + } + } + + fn evict(&mut self, now: f64) { + while self.frames.len() > 1 && (self.frames[0].t < now - self.window || self.bytes() > self.max_bytes) { + let mark = self.frames.pop_front().expect("a frame"); + let mut k = 0; + while k < mark.len as usize { + let head = self.words[k]; + let (id, mask) = ((head >> MASK_BITS) as usize, head & ((1 << MASK_BITS) - 1)); + k += 1; + if mask == 0 { self.base[id] = None; continue; } + let mut q = self.base[id].unwrap_or([0; FIELDS]); + for (f, v) in q.iter_mut().enumerate() { + if mask & (1 << f) != 0 { *v = self.words[k] as i32; k += 1; } + } + self.base[id] = Some(q); + } + self.words.drain(..mark.len as usize); + } + } + + /// What the recording holds, roughly: deltas, frame marks, names and per-element state. + pub(crate) fn bytes(&self) -> usize { + self.words.len() * 4 + self.frames.len() * std::mem::size_of::<Mark>() + self.name_bytes + + self.names.len() * (std::mem::size_of::<String>() + 2 * std::mem::size_of::<Q>() + 16) + } + + /// Decodes a frame's words into `(id, mask, values)` deltas. + pub(crate) fn decode(words: &[u32], mut each: impl FnMut(u32, u32, &Q)) { + let mut k = 0; + while k < words.len() { + let head = words[k]; + let (id, mask) = (head >> MASK_BITS, head & ((1 << MASK_BITS) - 1)); + k += 1; + let mut q = [0; FIELDS]; + for (f, v) in q.iter_mut().enumerate() { + if mask & (1 << f) != 0 { *v = words[k] as i32; k += 1; } + } + each(id, mask, &q); + } + } +} diff --git a/app/vendor/rune/crates/rune/src/rewind/tests.rs b/app/vendor/rune/crates/rune/src/rewind/tests.rs new file mode 100644 index 0000000..d84ef30 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/rewind/tests.rs @@ -0,0 +1,272 @@ +use super::*; +use crate::edit::{Key, KeyEvent}; +use crate::{Cx, El, Env, Mods, Runtime, Tx, el}; + +struct S { + y: f32, + rewind: Rewind, + scrub: Scrub, + sent: Vec<Sent>, + /// Where the scrubber's stage sits in the window. + inset: f32, +} + +fn view(s: &S, _: &mut Cx<S>) -> El { + let app = el().size(400.0, 300.0) + .child(el().key("title").absolute(10.0, s.y).size(100.0, 20.0).fill(crate::Color::WHITE)) + .child(el().key("still").absolute(200.0, 200.0).size(40.0, 40.0).fill(crate::Color::WHITE)); + el().size(400.0, 300.0) + .child(app.time_scale(if s.scrub.is_open() { 0.0 } else { 1.0 })) + .child(el().absolute(s.inset, s.inset).size(400.0 - s.inset, 300.0 - s.inset) + .child(s.scrub.view(|s: &mut S| &mut s.scrub, |s: &mut S, sent: Sent, _: &mut Tx| s.sent.push(sent)))) +} + +fn app(rewind: Rewind) -> Runtime<S> { + let state = S { y: 0.0, rewind, scrub: Scrub::default(), sent: Vec::new(), inset: 0.0 }; + let mut rt = Runtime::new(state, view, (400.0, 300.0), Env::new(true, 1.0)); + rt.frame(0.0); + rt +} + +fn record(rt: &mut Runtime<S>) { + rt.update(|s, tx| tx.record_rewind(Some(&s.rewind))); + rt.frame(1.0 / 60.0); +} + +/// Moves the title to `y` at once. +fn jump(rt: &mut Runtime<S>, y: f32) { + rt.update(|s, tx| { s.y = y; tx.instant(); }); +} + +fn frames(rt: &mut Runtime<S>, n: usize) { + for _ in 0..n { rt.frame(1.0 / 60.0); } +} + +fn press(key: Key, shift: bool) -> KeyEvent { + KeyEvent { key, mods: Mods { shift, ..Mods::default() } } +} + +#[test] +fn nothing_records_or_allocates_until_a_recorder_is_attached() { + let mut rt = app(Rewind::new()); + frames(&mut rt, 5); + assert!(rt.rewind().is_none()); + assert_eq!(rt.state.rewind.frames(), 0); + let before = crate::tooling::test_alloc::allocs(); + for _ in 0..100 { rt.record_rewind(); } + assert_eq!(crate::tooling::test_alloc::allocs(), before, "an unattached recorder costs a branch"); +} + +#[test] +fn a_poll_can_attach_the_recorder() { + let mut rt = app(Rewind::new()); + rt.poll = Some(|s, _, tx| { if s.y == 0.0 { s.y = 1.0; tx.record_rewind(Some(&s.rewind)); true } else { false } }); + frames(&mut rt, 3); + assert!(rt.rewind().is_some()); + assert!(rt.state.rewind.frames() > 0); +} + +#[test] +fn records_each_frame_and_stops_when_detached() { + let mut rt = app(Rewind::new()); + record(&mut rt); + frames(&mut rt, 9); + let n = rt.state.rewind.frames(); + assert!(n >= 10, "{n} frames"); + rt.update(|_, tx| tx.record_rewind(None)); + frames(&mut rt, 5); + assert_eq!(rt.state.rewind.frames(), n, "nothing records once detached"); +} + +#[test] +fn the_ring_keeps_only_its_window_and_rebuilds_old_frames() { + let mut rt = app(Rewind::new().seconds(1.0)); + record(&mut rt); + frames(&mut rt, 30); + jump(&mut rt, 40.0); + frames(&mut rt, 300); + let held = rt.state.rewind.frames(); + assert!((59..=62).contains(&held), "a second at 60 Hz, held {held}"); + // The frames that put both elements on screen are long gone; the base still has them. + let clip = rt.state.rewind.freeze(); + let first = clip.frame(0); + assert_eq!(first.len(), 2, "{first:?}"); + let title = first.iter().find(|(id, _)| clip.name(*id) == "title").unwrap().1; + assert_eq!(title.rect, [10.0, 40.0, 100.0, 20.0]); +} + +#[test] +fn the_ring_stays_within_its_byte_budget() { + let budget = 4096; + let mut rt = app(Rewind::new().max_bytes(budget)); + record(&mut rt); + for k in 0..400 { jump(&mut rt, (k % 50) as f32); rt.frame(1.0 / 60.0); } + assert!(rt.state.rewind.bytes() <= budget, "{} bytes", rt.state.rewind.bytes()); + assert!(rt.state.rewind.frames() > 10); +} + +#[test] +fn a_one_frame_jump_is_found_and_labelled() { + let mut rt = app(Rewind::new()); + record(&mut rt); + frames(&mut rt, 10); + jump(&mut rt, 7.5); + frames(&mut rt, 10); + let clip = rt.state.rewind.freeze(); + let k = (0..clip.len()).find(|&k| clip.has_jump(k)).expect("a jump"); + let changes = clip.changes(k); + assert_eq!(changes.len(), 1, "{changes:?}"); + assert!(changes[0].jump); + assert_eq!(changes[0].label(), "title ↓7.5 pt"); + assert!((clip.activity(k) - 7.5).abs() < 0.01); + assert_eq!(clip.activity(k + 1), 0.0, "nothing moves after"); + let path = clip.path(changes[0].id, 0..clip.len()); + assert_eq!(path.first().unwrap().1.rect[1], 0.0); + assert_eq!(path.last().unwrap().1.rect[1], 7.5); +} + +#[test] +fn a_one_frame_blip_out_and_back_is_a_jump() { + let mut rt = app(Rewind::new()); + record(&mut rt); + frames(&mut rt, 10); + jump(&mut rt, 9.0); + rt.frame(1.0 / 60.0); + jump(&mut rt, 0.0); + frames(&mut rt, 10); + let clip = rt.state.rewind.freeze(); + let jumps: Vec<usize> = (0..clip.len()).filter(|&k| clip.has_jump(k)).collect(); + assert_eq!(jumps.len(), 1, "only the frame it went out in: {jumps:?}"); + assert_eq!(clip.changes(jumps[0])[0].label(), "title ↓9.0 pt"); +} + +#[test] +fn smooth_motion_is_not_a_jump() { + let mut rt = app(Rewind::new()); + record(&mut rt); + for k in 1..=30 { jump(&mut rt, k as f32 * 3.0); rt.frame(1.0 / 60.0); } + let clip = rt.state.rewind.freeze(); + assert!((0..clip.len()).all(|k| !clip.has_jump(k))); + assert!((0..clip.len()).filter(|&k| clip.activity(k) > 0.0).count() >= 29); +} + +#[test] +fn freezing_pauses_recording_and_the_keys_step_select_and_resume() { + let mut rt = app(Rewind::new()); + record(&mut rt); + frames(&mut rt, 10); + jump(&mut rt, 20.0); + frames(&mut rt, 10); + let rewind = rt.state.rewind.clone(); + rt.state.scrub.open(&rewind); + let scrub = &mut rt.state.scrub; + assert!(scrub.is_open() && rewind.is_paused()); + let held = rewind.frames(); + let clip = scrub.clip().unwrap().clone(); + // It opens on the last frame anything moved in: the jump. + let k = scrub.frame(); + assert!(clip.has_jump(k)); + assert!(matches!(scrub.key(&press(Key::Left, false)), Keyed::Handled)); + assert_eq!(scrub.frame(), k - 1); + scrub.key(&press(Key::Right, true)); + scrub.key(&press(Key::Right, true)); + assert_eq!(scrub.selection(), k - 1..k + 2); + let Keyed::Send(sent) = scrub.key(&press(Key::Enter, false)) else { panic!("Return sends") }; + assert_eq!(sent.frames(), k - 1..k + 2); + frames(&mut rt, 5); + assert_eq!(rewind.frames(), held, "nothing records while frozen"); + assert!(matches!(rt.state.scrub.key(&press(Key::Escape, false)), Keyed::Closed)); + assert!(!rt.state.scrub.is_open() && !rewind.is_paused()); + frames(&mut rt, 5); + assert_eq!(rewind.frames(), held + 5); +} + +#[test] +fn the_scrubber_draws_the_moved_element_and_sends_from_its_button() { + let mut rt = app(Rewind::new()); + record(&mut rt); + frames(&mut rt, 5); + jump(&mut rt, 30.0); + frames(&mut rt, 5); + rt.update(|s, _| { let r = s.rewind.clone(); s.scrub.open(&r); s.scrub.set_note("title jumps"); }); + rt.frame(1.0 / 60.0); + let els = rt.elements(); + let find = |key: &str| els.iter().find(|e| e.key.as_deref() == Some(key)).unwrap_or_else(|| panic!("no {key}")).rect; + let id = rt.state.scrub.clip().unwrap().changes(rt.state.scrub.frame())[0].id; + assert_eq!(find(&format!("rewind-box-{id}")), [10.0, 30.0, 100.0, 20.0]); + assert_eq!(find(&format!("rewind-was-{id}")), [10.0, 0.0, 100.0, 20.0]); + assert!(els.iter().any(|e| e.key.as_deref().is_some_and(|k| k.starts_with("rewind-bin-"))), "the track lights up"); + let (x, y) = rt.find("rewind-send").unwrap(); + rt.pointer_down(x, y); + rt.pointer_up(x, y); + rt.frame(1.0 / 60.0); + assert_eq!(rt.state.sent.len(), 1, "send at {x},{y}: {:?}", rt.elements().iter().filter(|e| e.key.as_deref().is_some_and(|k| k.starts_with("rewind-"))).map(|e| (e.key.clone(), e.rect)).collect::<Vec<_>>()); + assert_eq!(rt.state.sent[0].note(), "title jumps"); +} + +#[test] +fn a_scrubber_on_an_inset_stage_still_outlines_where_the_window_drew() { + let mut rt = app(Rewind::new()); + rt.update(|s, tx| { s.inset = 50.0; tx.instant(); }); + record(&mut rt); + frames(&mut rt, 5); + jump(&mut rt, 30.0); + frames(&mut rt, 5); + rt.update(|s, _| { let r = s.rewind.clone(); s.scrub.open(&r); }); + frames(&mut rt, 2); + let id = rt.state.scrub.clip().unwrap().changes(rt.state.scrub.frame())[0].id; + let rect = rt.elements().iter().find(|e| e.key.as_deref() == Some(&format!("rewind-box-{id}"))).unwrap().rect; + assert_eq!(rect, [10.0, 30.0, 100.0, 20.0]); + let bar = rt.elements().iter().find(|e| e.key.as_deref() == Some("rewind-bar")).map(|e| e.rect); + assert!(bar.is_none_or(|b| b[0] >= 50.0), "the bar stays on the stage: {bar:?}"); +} + +#[test] +fn a_bundle_holds_a_trace_a_contact_sheet_and_a_summary() { + let mut rt = app(Rewind::new()); + record(&mut rt); + frames(&mut rt, 10); + jump(&mut rt, 7.5); + frames(&mut rt, 10); + let clip = rt.state.rewind.freeze(); + let dir = std::env::temp_dir().join(format!("rune-rewind-{}", std::process::id())); + std::fs::remove_dir_all(&dir).ok(); + let bundle = clip.write_bundle(&dir, 0..clip.len(), "the title hops").unwrap(); + let trace = std::fs::read_to_string(dir.join("trace.jsonl")).unwrap(); + let mut lines = trace.lines(); + assert!(lines.next().unwrap().contains(r#""type":"header""#)); + let first = lines.next().unwrap(); + assert!(first.contains(r#""nm":"title""#) && first.contains(r#""nm":"still""#), "{first}"); + assert_eq!(trace.lines().count(), clip.len() + 1); + assert!(trace.contains(",10,7.5,100,20,1,0,0]"), "the jump frame: {trace}"); + let png = std::fs::read(dir.join("contact.png")).unwrap(); + assert_eq!(&png[1..4], b"PNG"); + let summary = std::fs::read_to_string(dir.join("summary.md")).unwrap(); + assert_eq!(summary, bundle.summary()); + assert!(summary.contains("> the title hops")); + assert!(summary.contains("## Jumps") && summary.contains("title ↓7.5 pt"), "{summary}"); + std::fs::remove_dir_all(&dir).ok(); +} + +/// Opening the scrubber over another recorder resumes the one it froze before; showing a saved +/// clip keeps the frozen one until the scrubber closes. +#[test] +fn opening_over_an_open_scrubber_resumes_the_recorder_it_froze() { + let (first, second) = (Rewind::new(), Rewind::new()); + let mut scrub = Scrub::default(); + scrub.open(&first); + scrub.open(&second); + assert!(!first.is_paused(), "the first recorder records again"); + assert!(second.is_paused()); + scrub.show(first.freeze()); + first.resume(); + assert!(second.is_paused(), "a story over it keeps it frozen"); + scrub.close(); + assert!(!scrub.is_open() && !second.is_paused()); + // Reopening the same recorder leaves it frozen. + scrub.open(&first); + scrub.open(&first); + assert!(first.is_paused()); + scrub.close(); + assert!(!first.is_paused()); +} diff --git a/app/vendor/rune/crates/rune/src/rewind/track.rs b/app/vendor/rune/crates/rune/src/rewind/track.rs new file mode 100644 index 0000000..fc59012 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/rewind/track.rs @@ -0,0 +1,53 @@ +//! The scrub bar's track: one bar per few frames, as tall and bright as the most anything moved +//! in them (red where something jumped), the selection behind and the playhead over it. Dragging +//! scrubs; ⇧-dragging selects. + +use std::ops::Range; + +use crate::el::Phase; +use crate::{Color, El, Tx, el}; + +use super::clip::Clip; +use super::scrub::{Scrub, TRACK_H, jump_color, moved_color}; + +/// Points per bar, gap included. +const BAR_PITCH: f32 = 3.0; +/// A move this many points tall fills the track. +const FULL: f32 = 40.0; + +/// Which frames bar `b` of `bins` covers. +pub(crate) fn bin(len: usize, bins: usize, b: usize) -> Range<usize> { + (b * len / bins)..((b + 1) * len / bins).max(b * len / bins + 1) +} + +pub(crate) fn drag(scrub: &mut Scrub, d: &mut crate::Drag, tx: &mut Tx) { + if d.phase == Phase::Up { return; } + let Some(len) = scrub.clip().map(|c| c.len()) else { return }; + let k = ((d.x / d.w.max(1.0)).clamp(0.0, 1.0) * len as f32) as usize; + scrub.seek(k, tx.mods().shift); +} + +pub(crate) fn view(clip: &Clip, frame: usize, sel: Range<usize>, w: f32, bind_drag: &dyn Fn(El) -> El) -> El { + let len = clip.len().max(1); + let bins = ((w / BAR_PITCH) as usize).clamp(1, len); + let pitch = w / bins as f32; + let x_of = |k: usize| k as f32 / len as f32 * w; + let mut track = bind_drag(el().key("rewind-track").w(w).h(TRACK_H).radius(4.0).fill(Color::WHITE.alpha(0.04)) + .role("slider").label("Frame")); + if sel.len() > 1 { + track = track.child(el().key("rewind-selection").absolute(x_of(sel.start), 0.0).size((x_of(sel.end) - x_of(sel.start)).max(1.0), TRACK_H) + .fill(Color::WHITE.alpha(0.1))); + } + for b in 0..bins { + let frames = bin(len, bins, b); + let most = frames.clone().map(|k| clip.activity(k)).fold(0.0f32, f32::max); + if most <= 0.0 { continue; } + let jump = frames.clone().any(|k| clip.has_jump(k)); + let level = ((1.0 + most).ln() / (1.0 + FULL).ln()).clamp(0.08, 1.0); + let h = 3.0 + (TRACK_H - 6.0) * level; + let color = if jump { jump_color() } else { moved_color().alpha(0.35 + 0.65 * level) }; + track = track.child(el().key(format!("rewind-bin-{b}")).absolute(b as f32 * pitch, TRACK_H - 3.0 - h).size((pitch - 1.0).max(1.0), h) + .radius(1.0).fill(color)); + } + track.child(el().key("rewind-playhead").absolute((x_of(frame) + x_of(frame + 1)) / 2.0 - 1.0, 0.0).size(2.0, TRACK_H).fill(Color::WHITE)) +} diff --git a/app/vendor/rune/crates/rune/src/runtime.rs b/app/vendor/rune/crates/rune/src/runtime.rs new file mode 100644 index 0000000..3f54ad5 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime.rs @@ -0,0 +1,626 @@ +//! The retained tree: view → keyed nodes → Taffy layout at the target state → `rune-motion` Scene. +//! Animation samples tracks at frame time; it never re-runs view functions. +//! +//! Beside Scene's tracks the runtime owns four render-side behaviours that never touch app code: +//! scroll viewports (offset, momentum, follow-the-end), growth stacks (row heights on a capped +//! spring, positions derived), streaming word reveals, and text-field carets. Each frame: +//! queued input → (commit if state changed) → Scene → growth → scroll → reveals → build. + +use std::any::Any; +// The runtime's maps hash node ids and paths every commit; SipHash's DoS resistance buys nothing here. +pub(crate) use rune_core::{HashMap, HashSet}; +use std::marker::PhantomData; +use std::rc::Rc; +use std::sync::Arc; + +use parley::Layout; +use parley::editing::Cursor; +use parley::layout::Affinity; +use rune_motion::{ + Anim, Corners, LayoutAnim, Mount, NodeId, NodeSpec, Phase as PresencePhase, Prop, PropClass, Rect as MRect, Scene, + Spring, Transition, prop, snap::grid, +}; +use rune_taffy::prelude::*; + +use crate::color::{Color, over, srgb_encode}; +use crate::edit::{EditOutcome, Ime, KeyEvent}; +use crate::el::{Align, Commit, Drag, El, GrowthSpec, InputSpec, MotionSource, Phase, PointerEvent, ScrollSpec, Shell, TextSpec, Tx, Visual}; +use crate::growth::GrowTrack; +// Half-open, like overlays, NSPointInRect and PtInRect: a shared edge belongs to one side. +use crate::overlay::options::contains; +use crate::flight::{TextFlight, transformed}; +use crate::render::{Instance, KIND_DASHED, KIND_EFFECT, KIND_GLYPH, KIND_GRADIENT, KIND_IMAGE, KIND_INSET, KIND_RADIAL, KIND_RECT, KIND_SEGMENT, KIND_SHADOW, KIND_TRIANGLE, NO_CLIP}; +use crate::shape::{LineCap, Op, Shape}; +use crate::text::{Deco, PaintedDeco, GlyphQuad, Ink, TextFlow, TextLayout, TextSystem}; +use event_log::log_event; + +#[inline(always)] +pub(crate) fn handler_state<S: 'static>(state: &mut S) -> &mut dyn Any { + #[cfg(feature = "hot")] + if std::any::TypeId::of::<S>() == std::any::TypeId::of::<crate::hot::HostState>() { + return (state as &mut dyn Any).downcast_mut::<crate::hot::HostState>().unwrap().value.as_mut(); + } + state +} + +/// Calls an app's `poll` or `on_key`. With `rune/hot` it goes through subsecond's jump table, +/// so a patched body runs instead of the pointer captured at startup, and a panicking patch +/// falls back to that pointer. +macro_rules! app_call { + ($f:expr, $($arg:expr),* $(,)?) => {{ + #[cfg(feature = "hot")] + let called = crate::hot::patched_or_original!("callback", $f, $($arg),*); + #[cfg(not(feature = "hot"))] + let called = ($f)($($arg),*); + called + }}; +} + +#[inline(always)] +pub(crate) fn handler_state_ref<S: 'static>(state: &S) -> &dyn Any { + #[cfg(feature = "hot")] + if std::any::TypeId::of::<S>() == std::any::TypeId::of::<crate::hot::HostState>() { + return (state as &dyn Any).downcast_ref::<crate::hot::HostState>().unwrap().value.as_ref(); + } + state +} + +pub(crate) mod driver; +pub(crate) use driver::{AppDriver, AppRef, AppRefMut, RuntimeHooks, ViewDriver}; + +mod anchor; +mod api; +mod commit; +mod cx; +mod drag_out_host; +mod elements; +pub(crate) mod event_log; +mod font_families; +mod frame; +#[cfg(feature = "hot")] +mod hot_state; +mod init; +mod input; +mod interaction; +mod key_index; +pub(crate) mod layout_read; +mod motion; +mod node_index; +use node_index::NodeIndex; +mod paint; +mod paint_probe; +mod playground; +mod scroll; +mod selection; +mod system_settings; +mod text_fill; +mod turn; +mod types; +mod virtual_list; +mod visible; +mod web; +mod window_requests; +mod zoom; + +pub(crate) use commit::memo_reuse; +pub(crate) use commit::text_layout::{caret_index, text_width}; +pub(crate) use commit::why::CommitWhy; +#[cfg(all(test, debug_assertions))] +use commit::layout_diagnostics; +#[cfg(test)] +use commit::{prune, relayout, text_layout}; +use commit::{Measured, Measurement, flatten, measure}; +use commit::flatten::*; +use commit::text_layout::*; + +#[cfg(test)] +pub(crate) use input::action; +pub(crate) use input::field_menu; +pub use input::help_look::HelpLook; +#[cfg_attr(not(any(target_os = "macos", target_os = "windows")), allow(unused_imports))] +pub(crate) use input::physical::Unhandled; +pub(crate) use input::titlebar::WindowMenu; +pub use input::touch::TouchPhase; +#[cfg(target_os = "linux")] +use input::primary_selection; +use input::{ + app_ime, autoscroll, capture, drop as drop_dispatch, focus, focus_machine, + gesture as gesture_dispatch, help, hit, hover, hover_delay, key_releases, modal_focus, + modifier_keys, physical as physical_dispatch, popup as popup_dispatch, press_repeat, press_run, + titlebar, touch as touch_input, +}; +use input::action::*; +use input::pointer::CLICK_SLOP; + +pub(crate) use motion::live_check::fold_live; +pub use motion::motion_elements::MotionElement; +#[cfg(test)] +use motion::live_check; +use motion::{content_slide, flights, growth_runs, timer_wake, tracks}; +use motion::props::*; +use motion::reveal_phase::{Arrival, RevealChain, RevealEffect, RevealEvent, RevealPhase}; +use motion::tracks::{SCROLL_DECAY, mark_ancestors, scroll_offsets}; + +pub(crate) use paint::blend::{apron_key, glyph, icon_inst, premul}; +use paint::{ + border as border_paint, content as paint_content, exit_mask, keep as paint_keep, pixel_snap, + raster_check, shadow as shadow_paint, slots as paint_slots, state as paint_state, + tracks as paint_tracks, +}; +use paint::cache_layer::{ActiveCache, AnotherFrame, NodeCache, RasterPass, RasterPhase, ScaleSettle}; +use paint::helpers::*; +use paint::shape::push_shape; +use paint::soft_edges::{in_fade, inherit_fade}; + +pub(crate) use scroll::offset::{ScrollAnchor, ScrollRequest}; +pub(crate) use scroll::reveal::ScrollReveal; +#[doc(hidden)] +pub use scroll::watch::scroll_watch_state; +#[cfg(not(target_os = "windows"))] +pub(crate) use scroll::x::LINE_POINTS; +pub(crate) use scroll::x::{SHIFT_TURNS_WHEEL, wheel_delta}; +use scroll::{ + bottom as scroll_bottom, edge as scroll_edge, mode as scroll_mode, nudge as scroll_nudge, + offset as scroll_offset, requests, sticky, touch as scroll_touch, watch as scroll_watch, + wheel as scroll_wheel, x as scroll_x, +}; +use scroll::drawn::PixelHold; +use scroll::mode::ScrollMode; + +pub(crate) use selection::links::origin as text_origin; +pub(crate) use selection::selectable; +pub use selection::selectable::{SelectedText, SelectionChange, TextSelection}; +pub use selection::text_marks::TextMark; +use selection::{caret, click as input_click, links, select_all, text_marks}; + +use virtual_list::{fill as virtual_fill, row_reorder}; + +pub(crate) use web::{a11y as web_a11y, export as web_export, page as web_page}; +#[cfg(any(test, target_arch = "wasm32"))] +pub(crate) use web::runtime as web_runtime; + +pub(crate) use anchor::anchor_position; +use anchor::{anchor_index, anchor_index_live, step_up}; +pub use cx::{Cx, Env, Waker, commit_generation}; +pub(crate) use cx::caret_of; +use cx::COMMITS; +pub use elements::{ElementInfo, Pick, Picked, Pose}; +#[cfg(debug_assertions)] +pub(crate) use layout_read::window_read_key; +pub(crate) use turn::intersect; +use turn::{Turn, compose_turn, open_turned_layer, screen_clip_of}; +pub(crate) use types::{AnimSource, Node}; +pub use types::{FrameStats, TitlebarAction}; +use types::{AxisScroll, GlideTo, Inh, NodeCold, RowLayout, ScaleMotion, ScrollState, Stack, WidthHold, XMotion}; +pub(crate) use window_requests::HostState; + +#[cfg(test)] +mod timer_wake_tests; +#[cfg(test)] +mod grid_tests; +#[cfg(test)] +mod truncate_tests; +#[cfg(test)] +mod truncate_fade_tests; +#[cfg(test)] +mod line_clamp_tests; +#[cfg(test)] +mod aspect_fit_tests; +#[cfg(test)] +mod anchor_fit_tests; +#[cfg(test)] +mod drop_tests; +#[cfg(test)] +mod on_key_tests; +#[cfg(test)] +mod live_only_tests; +#[cfg(test)] +mod live_check_tests; +#[cfg(test)] +mod virtual_store_tests; +#[cfg(test)] +mod select_all_tests; +#[cfg(test)] +mod selection_api_tests; +#[cfg(test)] +mod anchored_grow_tests; +#[cfg(test)] +mod pixel_snap_tests; +#[cfg(test)] +mod recorder_tests; +#[cfg(test)] +mod size_tests; +#[cfg(test)] +mod video_tests; + +/// Zero-sized alignment barrier terminating `RuntimeCore` and the identical `#[repr(C)]` +/// prefix of `Runtime<S>`, ensuring `Runtime<S>::state` always sits at or past +/// `size_of::<RuntimeCore>()`. +#[repr(align(16))] +pub(crate) struct CoreEnd; + +macro_rules! runtime_core_fields { + ( + $( + $(#[doc = $doc:expr])* + $(#[cfg($($cfg:tt)*)])* + $vis:vis $name:ident : $ty:ty + ),* $(,)? + ) => { + /// Non-generic retained tree, layout, scene, input, scroll, selection, and paint state + /// forming the exact `#[repr(C)]` prefix of [`Runtime<S>`]. + #[repr(C)] + pub(crate) struct RuntimeCore { + $( + $(#[doc = $doc])* + $(#[cfg($($cfg)*)])* + $vis $name: $ty, + )* + pub(crate) _core_end: CoreEnd, + } + + #[repr(C)] + pub struct Runtime<S: 'static> { + $( + $(#[doc = $doc])* + $(#[cfg($($cfg)*)])* + $vis $name: $ty, + )* + pub(crate) _core_end: CoreEnd, + pub state: S, + /// Called at the start of every frame with the clock; return true when state changed (new data). + pub poll: Option<fn(&mut S, f64, &mut Tx) -> bool>, + /// Called for keys unhandled by the focused control; return true to consume it. + pub on_key: Option<fn(&mut S, &KeyEvent, &mut Tx) -> bool>, + pub(crate) hooks: RuntimeHooks<S>, + } + + impl<S: 'static> Runtime<S> { + /// Builds a `Runtime<S>` from an initialized `RuntimeCore` and its `S`-dependent tail + /// fields. Generated from the shared field list as an exhaustive struct literal so + /// adding any field without initializing it is a compile error. + pub(crate) fn from_core(core: RuntimeCore, state: S, view: fn(&S, &mut Cx<S>) -> El) -> Self { + assert_prefix_layout::<S>(); + let hooks = RuntimeHooks::new(view); + Self { + $( + $(#[cfg($($cfg)*)])* + $name: core.$name, + )* + _core_end: core._core_end, + state, + poll: None, + on_key: None, + hooks, + } + } + } + + #[inline(always)] + const fn assert_prefix_layout<S: 'static>() { + const { + assert!(std::mem::size_of::<CoreEnd>() == 0); + assert!(std::mem::align_of::<RuntimeCore>() <= 16); + $( + $(#[cfg($($cfg)*)])* + assert!(std::mem::offset_of!(Runtime<S>, $name) == std::mem::offset_of!(RuntimeCore, $name)); + )* + assert!(std::mem::offset_of!(Runtime<S>, _core_end) == std::mem::offset_of!(RuntimeCore, _core_end)); + assert!(std::mem::size_of::<RuntimeCore>() == std::mem::offset_of!(RuntimeCore, _core_end)); + assert!(std::mem::offset_of!(Runtime<S>, state) >= std::mem::size_of::<RuntimeCore>()); + assert!(std::mem::offset_of!(Runtime<S>, poll) >= std::mem::size_of::<RuntimeCore>()); + assert!(std::mem::offset_of!(Runtime<S>, on_key) >= std::mem::size_of::<RuntimeCore>()); + assert!(std::mem::offset_of!(Runtime<S>, hooks) >= std::mem::size_of::<RuntimeCore>()); + assert!(std::mem::align_of::<Runtime<S>>() >= std::mem::align_of::<RuntimeCore>()); + } + } + }; +} + +// Field order is load-bearing under `#[repr(C)]`: the leading `Env`/clock scalars, `tree`, +// `instances`/`marks`, `hit`, `paint`, `motion`, `scroll`, `scene`, `frame` and `commit` are read +// per node or per frame during paint, commit and idle walks, so they are kept together and first +// ahead of colder input, text and host state. +runtime_core_fields! { + pub env: Env, + /// Viewport in points: the view's, the window's over the zoom. + pub viewport: (f32, f32), + /// Animation time (seconds, scaled by the time scale). + pub t: f64, + /// Seconds since the first frame, unscaled (virtual when headless). + pub clock: f64, + pub ime_area: Option<[f32; 4]>, + pub time_scale: f32, + pub reduced_motion: bool, + pub track_marks: bool, + pub animating: bool, + /// This frame's commit landed every track (`Tx::settle`): a deliberate cut. + pub settled: bool, + /// Transparent native surfaces/headless exports clear to transparent black. + pub transparent: bool, + + /// Retained node tree, id/key lookup tables and per-commit capability flags. + pub(crate) tree: types::TreeState, + /// Seconds until the next frame while only [`Cycle`](crate::el::Cycle)s move on screen + /// (the shell sleeps until then instead of drawing every display frame). + pub ambient: Option<f32>, + pub instances: Vec<Instance>, + /// Per instance, the `El::mark` of its nearest marked node (0 for none). Filled only while + /// `track_marks` is set (a compositor is attached). + pub marks: Vec<u32>, + + /// Per-frame hit-test lists built in paint order. + hit: hit::HitState, + /// Two presses closer than this (seconds) are a double press: the system setting on macOS + /// and Windows, 0.5 elsewhere and headless. + pub double_click_interval: f64, + + /// Paint scratch buffers, reuse record, layer caches, text quads and paint outputs. + pub(crate) paint: paint_state::PaintState, + /// Render-side growth stacks, reveals, flights, loops and rewind capture. + pub(crate) motion: tracks::MotionState, + /// Scroll viewports, wheel axis locking, scroll requests and sticky headers. + pub(crate) scroll: requests::ScrollTables, + pub scene: Scene, + /// Action queue, pending `Tx`, wake deadlines, live latch, tracing and hot reload. + pub(crate) frame: timer_wake::FrameState, + /// View commit, Taffy layout, memo cache, virtual lists and layout callback state. + pub(crate) commit: commit::CommitState, + /// Pointer position, capture, hover/tooltip tracking, touch, autoscroll and file/OS drags. + pointer: capture::PointerState, + /// Keyboard focus, modal focus/scope, type-select, held keys and modifier tracking. + pub(crate) kbd: focus_machine::KeyboardState, + + pub surfaces: Vec<crate::native_surface::SurfaceDraw>, + /// RGBA images elements show (`El::pixels`), uploaded by the renderer. + pub images: crate::pixels::ImageAtlas, + pub text: TextSystem, + + /// Selectable text, links, field click/scroll, caret, IME, spellcheck and clipboard state. + pub(crate) edit: caret::TextInputState, + /// Window/host settings, zoom, titlebar, window requests, popups, dialogs, a11y and web page. + pub(crate) host: window_requests::HostState, + + /// Text the focused field asked to copy (the shell writes it to the clipboard). + pub copy_request: Option<crate::ClipboardWrite>, + /// A handler or `update` asked to close the window or quit (the shell takes it). + pub shell_request: Option<Shell>, + /// Windowed runs read the clock from the wall instead of summing frame steps. + pub wall_start: Option<crate::time::Instant>, + /// Input markers for traces and headless tests, at most `event_log::CAP` of them unread. + pub events: Vec<String>, + /// Counters for perf gates. + pub stats: FrameStats, + /// How long (seconds) the pointer rests on an `El::help` element before its tooltip shows: + /// the system's hover time on Windows, 0.5 elsewhere and headless. macOS windows use + /// AppKit's own tooltips, unless the view sets its own look (`Cx::help_look`), whose delay + /// may replace this one. + pub help_delay: f64, +} + +// Moving a non-Copy field out fails with E0509 if `RuntimeCore` or `Runtime<S>` ever implements `Drop`. +const _: () = { + fn check<S: 'static>(core: RuntimeCore, rt: Runtime<S>) -> (Vec<Node>, Vec<Node>) { + (core.tree.nodes, rt.tree.nodes) + } + let _ = check::<()>; +}; + +impl<S: 'static> Runtime<S> { + pub fn new(state: S, view: fn(&S, &mut Cx<S>) -> El, viewport: (f32, f32), env: Env) -> Self { + Self::with_text(state, view, viewport, env, TextSystem::default()) + } + + pub fn with_text(state: S, view: fn(&S, &mut Cx<S>) -> El, viewport: (f32, f32), env: Env, text: TextSystem) -> Self { + Self::from_core(RuntimeCore::new(viewport, env, text), state, view) + } + + #[inline(always)] + #[allow(unsafe_code)] + pub(crate) fn core(&self) -> &RuntimeCore { + assert_prefix_layout::<S>(); + // SAFETY: `Runtime<S>` and `RuntimeCore` are `#[repr(C)]` with an identical field prefix + // ending at zero-sized `_core_end: CoreEnd`, and neither implements custom `Drop` (guarded + // at compile time above). `assert_prefix_layout::<S>()` proves `size_of::<CoreEnd>() == 0`, + // identical `_core_end` offsets equal to `size_of::<RuntimeCore>()`, and + // `align_of::<Runtime<S>>() >= align_of::<RuntimeCore>()`. + unsafe { &*std::ptr::from_ref(self).cast::<RuntimeCore>() } + } + + /// Mutable view of the shared non-generic prefix. + /// + /// Mutate fields through the returned reference only; never replace the whole value + /// (`std::mem::swap`, `std::mem::replace`, `*core = ...`), which would pair this + /// `Runtime<S>`'s tail fields with another runtime's core. + #[inline(always)] + #[allow(unsafe_code)] + pub(crate) fn core_mut(&mut self) -> &mut RuntimeCore { + assert_prefix_layout::<S>(); + // SAFETY: `Runtime<S>` and `RuntimeCore` are `#[repr(C)]` with an identical field prefix + // ending at zero-sized `_core_end: CoreEnd`, and neither implements custom `Drop` (guarded + // at compile time above). `assert_prefix_layout::<S>()` proves `size_of::<CoreEnd>() == 0`, + // identical `_core_end` offsets equal to `size_of::<RuntimeCore>()`, and + // `align_of::<Runtime<S>>() >= align_of::<RuntimeCore>()`. + unsafe { &mut *std::ptr::from_mut(self).cast::<RuntimeCore>() } + } + + #[inline(always)] + #[allow(unsafe_code)] + pub(crate) fn split(&self) -> (&RuntimeCore, AppRef<'_, S>) { + assert_prefix_layout::<S>(); + let ptr = std::ptr::from_ref(self); + // SAFETY: `Runtime<S>` and `RuntimeCore` share an identical `#[repr(C)]` prefix ending at + // zero-sized `_core_end: CoreEnd`, and neither implements custom `Drop`. `assert_prefix_layout::<S>()` + // proves `state` and `hooks` sit at offsets `>= size_of::<RuntimeCore>()`, so shared + // references to the prefix (preserving any interior `UnsafeCell` bytes at identical offsets) + // and the trailing fields may coexist. + unsafe { + let core = &*ptr.cast::<RuntimeCore>(); + let app = AppRef { + state: &(*ptr).state, + hooks: &(*ptr).hooks, + }; + (core, app) + } + } + + /// Disjoint mutable borrow of the shared prefix and the `S`-dependent tail. + /// + /// As with [`Self::core_mut`], mutate fields on the returned `&mut RuntimeCore` rather than + /// replacing the whole value. + #[inline(always)] + #[allow(unsafe_code)] + pub(crate) fn split_mut(&mut self) -> (&mut RuntimeCore, AppRefMut<'_, S>) { + assert_prefix_layout::<S>(); + let ptr = std::ptr::from_mut(self); + // SAFETY: `Runtime<S>` and `RuntimeCore` share an identical `#[repr(C)]` prefix ending + // at zero-sized `_core_end: CoreEnd`, and neither implements custom `Drop`. + // `assert_prefix_layout::<S>()` proves at compile time that `size_of::<CoreEnd>() == 0`, + // `size_of::<RuntimeCore>() == offset_of!(RuntimeCore, _core_end)`, + // `align_of::<Runtime<S>>() >= align_of::<RuntimeCore>()`, and every tail field (`state`, + // `poll`, `on_key`, `hooks`) sits at an offset `>= size_of::<RuntimeCore>()`. Every + // projection below derives from `ptr` and covers strictly disjoint byte ranges: + // `[0..size_of::<RuntimeCore>())` for `core` and distinct tail fields at offsets + // `>= size_of::<RuntimeCore>()` for `app`. + unsafe { + let poll = *std::ptr::addr_of!((*ptr).poll); + let on_key = *std::ptr::addr_of!((*ptr).on_key); + let state = &mut *std::ptr::addr_of_mut!((*ptr).state); + let hooks = &mut *std::ptr::addr_of_mut!((*ptr).hooks); + let core = &mut *ptr.cast::<RuntimeCore>(); + (core, AppRefMut { state, poll, on_key, hooks }) + } + } + + /// Attaches a live playground to this runtime and keeps `has_playground` in sync. + pub(crate) fn attach_playground(&mut self, live: crate::playground::Live<S>) { + self.hooks.playground = Some(Box::new(live)); + self.tree.attach_playground(); + } +} + +#[cfg(test)] +mod prefix_layout_tests { + use std::cell::Cell; + use std::rc::Rc; + + use super::*; + + #[repr(align(64))] + struct OverAligned(u8); + + struct ZeroSized; + + struct DropCounter(Rc<Cell<usize>>); + + impl Drop for DropCounter { + fn drop(&mut self) { + self.0.set(self.0.get() + 1); + } + } + + fn empty_view<S: 'static>(_: &S, _: &mut Cx<S>) -> El { + crate::el() + } + + fn verify_layout<S: 'static>(state: S, bump: impl FnOnce(&mut S), check: impl FnOnce(&S)) { + assert_prefix_layout::<S>(); + assert_eq!(std::mem::size_of::<CoreEnd>(), 0); + assert_eq!(std::mem::offset_of!(Runtime<S>, tree), std::mem::offset_of!(RuntimeCore, tree)); + assert_eq!(std::mem::offset_of!(Runtime<S>, hit), std::mem::offset_of!(RuntimeCore, hit)); + assert_eq!(std::mem::offset_of!(Runtime<S>, motion), std::mem::offset_of!(RuntimeCore, motion)); + assert_eq!(std::mem::offset_of!(Runtime<S>, scroll), std::mem::offset_of!(RuntimeCore, scroll)); + assert_eq!(std::mem::offset_of!(Runtime<S>, paint), std::mem::offset_of!(RuntimeCore, paint)); + assert_eq!(std::mem::offset_of!(Runtime<S>, pointer), std::mem::offset_of!(RuntimeCore, pointer)); + assert_eq!(std::mem::offset_of!(Runtime<S>, kbd), std::mem::offset_of!(RuntimeCore, kbd)); + assert_eq!(std::mem::offset_of!(Runtime<S>, commit), std::mem::offset_of!(RuntimeCore, commit)); + assert_eq!(std::mem::offset_of!(Runtime<S>, edit), std::mem::offset_of!(RuntimeCore, edit)); + assert_eq!(std::mem::offset_of!(Runtime<S>, frame), std::mem::offset_of!(RuntimeCore, frame)); + assert_eq!(std::mem::offset_of!(Runtime<S>, host), std::mem::offset_of!(RuntimeCore, host)); + assert!(std::mem::offset_of!(Runtime<S>, state) >= std::mem::size_of::<RuntimeCore>()); + assert!(std::mem::offset_of!(Runtime<S>, poll) >= std::mem::size_of::<RuntimeCore>()); + assert!(std::mem::offset_of!(Runtime<S>, on_key) >= std::mem::size_of::<RuntimeCore>()); + assert!(std::mem::offset_of!(Runtime<S>, hooks) >= std::mem::size_of::<RuntimeCore>()); + assert!(std::mem::align_of::<Runtime<S>>() >= std::mem::align_of::<RuntimeCore>()); + + let mut rt = Runtime::new(state, empty_view::<S>, (320.0, 240.0), Env::new(true, 2.0)); + assert_eq!(rt.core().viewport, (320.0, 240.0)); + assert_eq!(rt.core().env.scale, 2.0); + assert_eq!(rt.core().tree.next_id, 1); + assert!(rt.core().commit.dirty); + + rt.core_mut().viewport = (400.0, 300.0); + assert_eq!(rt.viewport, (400.0, 300.0)); + assert_eq!(rt.core().viewport, (400.0, 300.0)); + + { + let (core, app) = rt.split_mut(); + core.viewport = (640.0, 480.0); + core.t = 1.5; + bump(app.state); + } + assert_eq!(rt.viewport, (640.0, 480.0)); + assert_eq!(rt.t, 1.5); + + { + let (core, app) = rt.split(); + assert_eq!(core.viewport, (640.0, 480.0)); + assert_eq!(core.t, 1.5); + check(app.state); + } + + // Reading through `split()` while an interior `RefCell` field of the core is mutably + // borrowed must preserve `UnsafeCell` aliasing semantics. + { + let mut scratch = rt.motion.motion_scratch.borrow_mut(); + scratch.push((7, 3, true)); + let (core, app) = rt.split(); + assert_eq!(core.viewport, (640.0, 480.0)); + assert!(core.motion.motion_scratch.try_borrow().is_err()); + let _ptr = std::ptr::from_ref(app.state); + } + assert_eq!(rt.core().motion.motion_scratch.borrow().as_slice(), &[(7, 3, true)]); + } + + #[test] + fn shared_prefix_layout_holds_across_state_alignments() { + verify_layout((), |_| {}, |_| {}); + + let mut seen_u8 = 0u8; + verify_layout( + 1u8, + |s| { *s = 7; seen_u8 = *s; }, + |s| assert_eq!(*s, 7), + ); + assert_eq!(seen_u8, 7); + + let mut seen_u128 = 0u128; + verify_layout( + 1u128, + |s| { *s = 0x1234_5678_9abc_def0; seen_u128 = *s; }, + |s| assert_eq!(*s, 0x1234_5678_9abc_def0), + ); + assert_eq!(seen_u128, 0x1234_5678_9abc_def0); + + let mut seen_over = 0u8; + verify_layout( + OverAligned(3), + |s| { s.0 = 42; seen_over = s.0; }, + |s| assert_eq!(s.0, 42), + ); + assert_eq!(seen_over, 42); + + verify_layout(ZeroSized, |_| {}, |_| {}); + + let drops = Rc::new(Cell::new(0)); + verify_layout( + DropCounter(drops.clone()), + |s| assert_eq!(s.0.get(), 0), + |s| assert_eq!(s.0.get(), 0), + ); + assert_eq!(drops.get(), 1, "state with Drop must drop exactly once"); + } +} + +#[cfg(test)] +mod tests; diff --git a/app/vendor/rune/crates/rune/src/runtime/anchor.rs b/app/vendor/rune/crates/rune/src/runtime/anchor.rs new file mode 100644 index 0000000..5e38f63 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/anchor.rs @@ -0,0 +1,299 @@ +//! Where `El::anchored` overlays go, how long an `El::anchored_fit` one may be, and the zoom +//! one inherits from its anchor. +use super::*; +use crate::el::{Anchor, Flow, Pin, Side}; + +/// The node an `El::above` anchor `a` names, among the `before` nodes ahead of its element. +pub(super) fn anchor_index(nodes: &[Node], before: usize, a: &Anchor) -> Option<usize> { + nodes[..before].iter().position(|n| n.key.as_ref() == Some(&a.key)) +} + +/// Like [`anchor_index`], preferring a live (non-exiting) anchor when both a live and an exiting +/// node share the key. +pub(super) fn anchor_index_live(nodes: &[Node], before: usize, a: &Anchor, exiting: impl Fn(usize) -> bool) -> Option<usize> { + let mut fallback = None; + for (idx, n) in nodes[..before].iter().enumerate() { + if n.key.as_ref() != Some(&a.key) { continue; } + if !exiting(idx) { return Some(idx); } + fallback.get_or_insert(idx); + } + fallback +} + +/// Where a walk from node `i` goes next: the node it is anchored above, else its parent. +pub(super) fn step_up(nodes: &[Node], i: usize) -> Option<usize> { + nodes[i].above.as_ref().and_then(|a| anchor_index(nodes, i, a)).or(nodes[i].parent) +} + +/// How far an anchored overlay stays inside the window. +const MARGIN: f32 = 8.0; + +/// Where an anchored overlay of `size` goes next to `t` (x0, y0, x1, y1), flipped to the +/// opposite side when it doesn't fit, then kept 8 points inside the viewport. +pub(crate) fn anchor_position(a: &Anchor, t: [f32; 4], size: (f32, f32), vp: (f32, f32)) -> (f32, f32) { + debug_assert!(t.iter().all(|v| v.is_finite()), "anchor_position called with non-finite target {t:?}"); + let (w, h) = size; + let margin = MARGIN; + let along = |lo: f32, hi: f32, len: f32| match a.align { + Align::Start => lo, + Align::Center => (lo + hi - len) * 0.5, + Align::End => hi - len, + }; + let (mut x, mut y) = match a.side { + Side::Top => (along(t[0], t[2], w), t[1] - h - a.gap), + Side::Bottom => (along(t[0], t[2], w), t[3] + a.gap), + Side::Left => (t[0] - w - a.gap, along(t[1], t[3], h)), + Side::Right => (t[2] + a.gap, along(t[1], t[3], h)), + }; + // Flip the side when the other one fits (Floating UI's `flip`). + match a.side { + Side::Bottom if y + h > vp.1 - margin && t[1] - h - a.gap >= margin => y = t[1] - h - a.gap, + Side::Top if y < margin && t[3] + a.gap + h <= vp.1 - margin => y = t[3] + a.gap, + Side::Right if x + w > vp.0 - margin && t[0] - w - a.gap >= margin => x = t[0] - w - a.gap, + Side::Left if x < margin && t[2] + a.gap + w <= vp.0 - margin => x = t[2] + a.gap, + _ => {} + } + // Flip the alignment when it overflows and the other end fits, then shift along the side. + let vertical = matches!(a.side, Side::Top | Side::Bottom); + let (pos, lo, hi, len, room) = if vertical { (&mut x, t[0], t[2], w, vp.0) } else { (&mut y, t[1], t[3], h, vp.1) }; + match a.align { + Align::End if *pos < margin && lo + len <= room - margin => *pos = lo, + Align::Start if *pos + len > room - margin && hi - len >= margin => *pos = hi - len, + _ => {} + } + *pos = pos.clamp(margin, (room - len - margin).max(margin)); + // Along the main axis only keep the start edge inside; a long list may run off the far end + // (`El::anchored_fit` bounds it instead). + if vertical { y = y.max(margin) } else { x = x.max(margin) } + if a.round { + // `Math.round`: halves go up. + return ((x + 0.5).floor(), (y + 0.5).floor()); + } + (x, y) +} + +/// The longest an `anchored_fit` overlay `len` long may be next to `t`, or `None` when it fits +/// on its side or the other one as it is. The bound is the larger room (its own side's on a +/// tie), a little short of it so [`anchor_position`] puts the bounded overlay on that side. +fn fit_bound(a: &Anchor, t: [f32; 4], len: f32, vp: (f32, f32)) -> Option<f32> { + let (before, after) = match a.side { + Side::Top | Side::Bottom => (t[1] - a.gap - MARGIN, vp.1 - MARGIN - (t[3] + a.gap)), + Side::Left | Side::Right => (t[0] - a.gap - MARGIN, vp.0 - MARGIN - (t[2] + a.gap)), + }; + let (own, other) = if matches!(a.side, Side::Top | Side::Left) { (before, after) } else { (after, before) }; + if len <= own || len <= other { + return None; + } + Some((own.max(other) - 0.5).floor().max(0.0)) +} + +impl Measurement<'_> { + /// Places every node from `taffy`'s layout: ids, local and window rects, insets, and + /// anchored overlays beside their anchors. + pub(super) fn place(&mut self, taffy: &LayoutEngine, nodes: &mut [Node]) { + self.node_index.rebuild(nodes.len()); + for i in 0..nodes.len() { + let id = if nodes[i].id != NodeId(0) { + debug_assert_eq!(self.path_ids.get(&nodes[i].path).copied(), Some(nodes[i].id)); + nodes[i].id + } else { + self.node_id(&nodes[i].path) + }; + nodes[i].id = id; + self.node_index.insert(id, i); + let mut l = taffy.box_layout(nodes[i].taffy); + // Right to left: laid out left to right, then mirrored inside the parent (`El::dir`). + if let Some(p) = nodes[i].parent.filter(|&p| nodes[p].flow == Flow::Rtl && nodes[i].pin == Pin::Flowing) { + l.x = nodes[p].local.w - l.x - l.w; + } + if nodes[i].flow == Flow::Rtl { + l.inset.swap(0, 2); + } + nodes[i].local = MRect::new(l.x, l.y, l.w, l.h); + let (px, py) = nodes[i].parent.map_or((0.0, 0.0), |p| (nodes[p].target[0], nodes[p].target[1])); + let mut x = px + l.x; + let mut y = py + l.y; + let mut resolved = true; + if let Some(a) = &nodes[i].above { + if let Some(j) = anchor_index(&nodes, i, a) { + // Anchors inside scroll viewports sit where they are scrolled (and stuck) to. + let target = sticky::anchored_target(nodes, self.scrolls, j, self.viewport); + (x, y) = anchor_position(a, target, (l.w, l.h), self.viewport); + nodes[i].local.x = x - px; + nodes[i].local.y = y - py; + } else { + // Never leave an unresolved anchored overlay at (0, 0) of the window. + nodes[i].local.x = 0.0; + nodes[i].local.y = 0.0; + resolved = false; + } + } + nodes[i].target = if resolved { [x, y, x + l.w, y + l.h] } else { [0.0; 4] }; + nodes[i].inset = l.inset; + } + } + + /// Bounds each placed `anchored_fit` overlay that fits on neither side of its anchor to the + /// larger room, through its style. True when any changed, so layout runs again. + pub(super) fn fit_anchored(&self, taffy: &mut LayoutEngine, nodes: &[Node]) -> bool { + let mut changed = false; + for (i, n) in nodes.iter().enumerate() { + let Some(a) = n.above.as_ref().filter(|a| a.fit) else { continue }; + let Some(j) = anchor_index(&nodes, i, a) else { continue }; + let target = sticky::anchored_target(nodes, self.scrolls, j, self.viewport); + // It draws `k` times its layout size beside where the anchor draws. + let k = inherited_zoom(nodes, i, &|m: &Node| m.static_scale).max(MIN_ZOOM); + let target = if k == 1.0 { target } else { zoomed_rect(nodes, self.scrolls, j, target, self.viewport) }; + let zoomed; + let a = if k == 1.0 { a } else { zoomed = zoomed_gap(a, k); &zoomed }; + let vertical = matches!(a.side, Side::Top | Side::Bottom); + let len = if vertical { n.local.h } else { n.local.w }; + let Some(bound) = fit_bound(a, target, len * k, self.viewport) else { continue }; + let mut style = taffy.style(n.taffy).clone(); + if vertical { + style.set_max_height(length(bound / k)); + } else { + style.set_max_width(length(bound / k)); + } + taffy.set_style_and_mark_ancestors( + n.taffy, + style, + std::iter::successors(n.parent, |&p| nodes[p].parent).map(|p| nodes[p].taffy), + ); + changed = true; + } + changed + } +} + +#[cfg(test)] +#[path = "anchor_zoom_tests.rs"] +mod zoom_tests; +#[cfg(test)] +#[path = "anchor_zoom_motion_tests.rs"] +mod zoom_motion_tests; + +/// The smallest zoom an anchored overlay is placed at, so placing it never divides by zero. +const MIN_ZOOM: f32 = 1e-3; + +/// The zoom anchored overlay `i` draws at: its anchor's, the product of the `El::scale`s on the +/// anchor's ancestors (through any anchored overlay the anchor is in). It is 1 when the overlay +/// opts out with `El::anchored_unscaled`, or scales itself with `El::scale`, as an app that +/// already zooms its popovers by hand does. `own` reads a node's own `El::scale`. +pub(super) fn inherited_zoom(nodes: &[Node], i: usize, own: &impl Fn(&Node) -> f32) -> f32 { + let n = &nodes[i]; + let Some(a) = n.above.as_ref().filter(|a| !a.unscaled) else { return 1.0 }; + if n.scale_track || n.static_scale != 1.0 { + return 1.0; + } + let Some(j) = anchor_index(&nodes, i, a) else { return 1.0 }; + let mut k = 1.0; + let mut at = nodes[j].parent; + while let Some(p) = at { + k *= own(&nodes[p]); + if nodes[p].above.is_some() { + return k * inherited_zoom(nodes, p, own); + } + at = nodes[p].parent; + } + k +} + +/// `t`, node `j`'s layout rect, where its ancestors' `El::scale`s draw it at rest. An anchored +/// ancestor zooms about its own top-left corner. +fn zoomed_rect(nodes: &[Node], scrolls: &HashMap<NodeId, ScrollState>, j: usize, t: [f32; 4], vp: (f32, f32)) -> [f32; 4] { + let chain: Vec<usize> = std::iter::successors(nodes[j].parent, |&p| nodes[p].parent).collect(); + // A point `x` draws at `to + (x - from) * k`, as `Inh` composes scales down the tree. + let (mut k, mut from, mut to) = (1.0f32, [0.0f32; 2], [0.0f32; 2]); + for &p in chain.iter().rev() { + let n = &nodes[p]; + if n.above.is_some() { + // An overlay drops its ancestors' scales. + (k, from, to) = (1.0, [0.0; 2], [0.0; 2]); + } + let own = n.static_scale * inherited_zoom(nodes, p, &|m: &Node| m.static_scale); + if (own - 1.0).abs() <= 1e-5 { + continue; + } + let r = sticky::anchored_target(nodes, scrolls, p, vp); + let [ox, oy] = match (n.above.is_some(), n.vis.origin) { + (true, _) => [0.0, 0.0], + (false, Some(o)) => o, + (false, None) => [0.5, 0.5], + }; + let pivot = [r[0] + ox * (r[2] - r[0]), r[1] + oy * (r[3] - r[1])]; + to = [to[0] + (pivot[0] - from[0]) * k, to[1] + (pivot[1] - from[1]) * k]; + from = pivot; + k *= own; + } + [to[0] + (t[0] - from[0]) * k, to[1] + (t[1] - from[1]) * k, to[0] + (t[2] - from[0]) * k, to[1] + (t[3] - from[1]) * k] +} + +/// `a` with its gap at zoom `k`; the window margin stays in window points. +fn zoomed_gap(a: &Anchor, k: f32) -> Anchor { + Anchor { gap: a.gap * k, ..a.clone() } +} + +/// The point on drawn box `d` that touches its anchor `t`: the middle of the edge facing the +/// anchor, moved along it to the end `a.align` names. The overlay zooms about it, so it grows +/// away from its anchor. +fn attach_point(a: &Anchor, t: [f32; 4], d: [f32; 4]) -> [f32; 2] { + let along = |lo: f32, hi: f32| match a.align { + Align::Start => lo, + Align::Center => (lo + hi) * 0.5, + Align::End => hi, + }; + let facing = |lo: f32, hi: f32, t_lo: f32, t_hi: f32| if lo + hi > t_lo + t_hi { lo } else { hi }; + match a.side { + Side::Top | Side::Bottom => [along(d[0], d[2]), facing(d[1], d[3], t[1], t[3])], + Side::Left | Side::Right => [facing(d[0], d[2], t[0], t[2]), along(d[1], d[3])], + } +} + +impl RuntimeCore { + /// Sets up anchored overlay `i`'s inherited paint state beside anchor `j`: at the anchor's + /// zoom (see [`inherited_zoom`]), placed and flipped by its zoomed size where the anchor was + /// drawn, and zooming about the point it attaches at. Its own `prop::OFFSET` and transition + /// still apply on top; its ancestors' positions and scales don't. Returns `(target, zoom)` + /// so an exiting overlay can hold its last valid position if its anchor unmounts. + pub(super) fn anchored_inh(&self, i: usize, j: usize, a: &Anchor, p: &rune_motion::Presented, pinh: &mut Inh) -> ([f32; 4], f32) { + let tracked = |m: &Node| if m.scale_track { self.scene.get(m.id, P_SCALE).unwrap_or(m.static_scale) } else { m.static_scale }; + let k = inherited_zoom(&self.tree.nodes, i, &tracked).max(MIN_ZOOM); + let d = self.paint.drawn[j]; + let target = if d != [0.0; 4] { [d[0], d[1], d[0] + d[2], d[1] + d[3]] } else { + let t = sticky::anchored_target(&self.tree.nodes, &self.scroll.scrolls, j, self.viewport); + if k == 1.0 { t } else { zoomed_rect(&self.tree.nodes, &self.scroll.scrolls, j, t, self.viewport) } + }; + let motion = self.tree.nodes[j].parent.and_then(|jp| self.paint.inh_scratch.get(jp)).map_or(ScaleMotion::Still, |h| h.scale_motion); + self.anchored_inh_at(i, a, target, k, motion, p, pinh); + (target, k) + } + + /// Places anchored overlay `i` against a resolved `(target, k)` rect and zoom. + pub(super) fn anchored_inh_at(&self, i: usize, a: &Anchor, target: [f32; 4], k: f32, motion: ScaleMotion, p: &rune_motion::Presented, pinh: &mut Inh) { + let zoomed; + let a = if k == 1.0 { a } else { zoomed = zoomed_gap(a, k); &zoomed }; + let (w, h) = (p.rect.w * k, p.rect.h * k); + let (ax, ay) = anchor_position(a, target, (w, h), self.viewport); + let pivot = attach_point(a, target, [ax, ay, ax + w, ay + h]); + // Placed from the presented size and anchor, so drop the scene's own layout position + // (this node's `prop::FRAME` x/y and its ancestors' origins) while keeping this node's + // own `prop::OFFSET` and transition offset: with the frame position spring left in, an + // End-aligned box growing in width would start from its old x and its end edge would + // swing out and back. Zoomed about `pivot`, the box's top-left lands on (ax, ay). + let world = self.scene.world(self.tree.nodes[i].id).unwrap_or(p.rect); + (pinh.snap.rigid, pinh.snap.steady, pinh.snap.layer) = ([0.0; 2], [0.0; 2], 0); + if k == 1.0 { + (pinh.dx, pinh.dy) = (ax - world.x, ay - world.y); + (pinh.scale, pinh.anchor, pinh.anchor_to) = (1.0, [0.0; 2], [0.0; 2]); + pinh.still = (1.0, [0.0; 2], [0.0; 2]); + return; + } + pinh.dx = pivot[0] + (ax - pivot[0]) / k - world.x; + pinh.dy = pivot[1] + (ay - pivot[1]) / k - world.y; + (pinh.scale, pinh.anchor, pinh.anchor_to) = (k, pivot, pivot); + // Text rasterizes as the anchor's does: crisp at the zoom once it rests. + pinh.scale_motion = pinh.scale_motion.max(motion); + pinh.still = if pinh.scale_motion == ScaleMotion::Still { (k, pivot, pivot) } else { (1.0, [0.0; 2], [0.0; 2]) }; + } +} diff --git a/app/vendor/rune/crates/rune/src/runtime/anchor_fit_tests.rs b/app/vendor/rune/crates/rune/src/runtime/anchor_fit_tests.rs new file mode 100644 index 0000000..d746802 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/anchor_fit_tests.rs @@ -0,0 +1,62 @@ +//! `El::anchored_fit`: an overlay that fits on neither side of its anchor goes to the side +//! with more room and is at most that room long, so the list in it scrolls. +use super::*; +use crate::el::{Align, ScrollSpec, Side}; +use crate::{Cx, El, Env, col, el}; + +#[derive(Clone, Copy)] +struct S { + /// The anchor's top edge. + top: f32, + rows: usize, + fit: bool, +} + +fn view(s: &S, _: &mut Cx<S>) -> El { + let rows = col().key("rows").children((0..s.rows).map(|i| el().key(format!("row{i}")).w(100.0).h(20.0))); + let list = col().key("scroll").shrink().min_h(0.0).scroll(ScrollSpec { stick_bottom: false }).child(rows); + let menu = col().key("menu").w(100.0).child(list); + let menu = if s.fit { + menu.anchored_fit("target", Side::Bottom, Align::Start, 4.0) + } else { + menu.anchored("target", Side::Bottom, Align::Start, 4.0) + }; + col().size(400.0, 300.0).child(el().key("target").absolute(20.0, s.top).size(100.0, 30.0)).child(menu) +} + +fn menu(s: S) -> [f32; 4] { + let mut rt = Runtime::new(s, view, (400.0, 300.0), Env::new(true, 1.0)); + rt.frame(0.0); + for _ in 0..120 { rt.frame(1.0 / 120.0); } + rt.presented("menu").unwrap().0 +} + +#[test] +fn a_list_that_fits_below_is_left_alone() { + let r = menu(S { top: 20.0, rows: 5, fit: true }); + assert_eq!((r[1], r[3]), (54.0, 100.0)); +} + +#[test] +fn a_list_that_fits_above_flips_whole() { + let r = menu(S { top: 200.0, rows: 8, fit: true }); + assert_eq!((r[1], r[3]), (36.0, 160.0)); +} + +#[test] +fn a_long_list_takes_the_larger_room_and_scrolls() { + // Below has 300 - 8 - 234 = 58 points, above 200 - 4 - 8 = 188. + let r = menu(S { top: 200.0, rows: 40, fit: true }); + assert_eq!(r[3], 187.0, "bounded to the room above"); + assert!(r[1] >= 8.0 && r[1] + r[3] <= 196.0, "above the anchor, inside the window: {r:?}"); + // Without fit it stays below and runs off the window. + let r = menu(S { top: 200.0, rows: 40, fit: false }); + assert_eq!((r[1], r[3]), (234.0, 800.0)); +} + +#[test] +fn a_long_list_with_more_room_below_stays_below() { + // Below has 300 - 8 - 84 = 208 points, above 50 - 4 - 8 = 38. + let r = menu(S { top: 50.0, rows: 40, fit: true }); + assert_eq!((r[1], r[3]), (84.0, 207.0)); +} diff --git a/app/vendor/rune/crates/rune/src/runtime/anchor_zoom_motion_tests.rs b/app/vendor/rune/crates/rune/src/runtime/anchor_zoom_motion_tests.rs new file mode 100644 index 0000000..49e6987 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/anchor_zoom_motion_tests.rs @@ -0,0 +1,51 @@ +//! Motion gate for `El::anchored` at its anchor's zoom: an open popover follows the page's zoom +//! spring, and one entering or leaving a zoomed page plays its transition there. +use super::*; +use crate::el::{Align, Side}; +use crate::motion_gate::{self, Allow, Job, Recording, Run}; +use crate::{Cx, El, Env, TextStyle, Transition, col, el, text}; + +#[derive(Clone, Copy)] +struct S { + zoom: f32, + open: bool, +} + +fn view(s: &S, _: &mut Cx<S>) -> El { + // Small enough that the page's own scale spring stays under the `jerk` threshold. + let page = col().key("page").size(300.0, 200.0).scale(s.zoom).origin(0.0, 0.0) + .child(el().key("target").absolute(100.0, 100.0).size(80.0, 20.0).fill(crate::Color::WHITE)); + let root = col().size(800.0, 600.0).child(page); + if !s.open { + return root; + } + let pop = col().key("pop").w(120.0).padding(10.0).fill(crate::Color::WHITE) + .child(text("Rename").key("label").font(TextStyle::new(13.0, 400.0))) + .transition(Transition::scale(0.95).combined(Transition::opacity())) + .anchored("target", Side::Bottom, Align::Start, 5.0); + root.child(pop) +} + +fn cell(start: S, what: &'static str, change: fn(&mut S)) -> Recording { + let mut r = Run::new(Runtime::new(start, view, (800.0, 600.0), Env::new(true, 2.0)), 120.0); + r.idle(1.0); + r.step(); + r.act(what, |rt| rt.update(|s, _| change(s))); + r.play(1.2); + r.quiet(); + r.play(0.3); + r.rec +} + +const ALLOW: &[Allow] = &[]; + +#[test] +fn anchored_zoom_motion_gate() { + let cells: Vec<(String, Job)> = vec![ + ("anchored-zoom/zoom-while-open".into(), Box::new(|| cell(S { zoom: 1.0, open: true }, "zoom to 1.6", |s| s.zoom = 1.6))), + ("anchored-zoom/unzoom-while-open".into(), Box::new(|| cell(S { zoom: 1.6, open: true }, "zoom to 1.0", |s| s.zoom = 1.0))), + ("anchored-zoom/enter-zoomed".into(), Box::new(|| cell(S { zoom: 1.6, open: false }, "open", |s| s.open = true))), + ("anchored-zoom/exit-zoomed".into(), Box::new(|| cell(S { zoom: 1.6, open: true }, "close", |s| s.open = false))), + ]; + motion_gate::gate(cells, ALLOW); +} diff --git a/app/vendor/rune/crates/rune/src/runtime/anchor_zoom_tests.rs b/app/vendor/rune/crates/rune/src/runtime/anchor_zoom_tests.rs new file mode 100644 index 0000000..22b5111 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/anchor_zoom_tests.rs @@ -0,0 +1,125 @@ +//! `El::anchored` inside a zoomed page: the overlay draws at its anchor's zoom, beside where the +//! anchor draws, flips by its zoomed size, and hits where it draws. +use super::*; +use crate::el::{Align, Side}; +use crate::{Cx, El, Env, TextStyle, col, el, text}; + +#[derive(Clone, Copy, Default)] +struct S { + zoom: f32, + /// The anchor's top edge in the page. + top: f32, + /// How the overlay takes the zoom. + mode: Mode, + presses: u32, +} + +#[derive(Clone, Copy, Default, PartialEq)] +enum Mode { + #[default] + Inherit, + /// Scales itself, as an app that zooms its popovers by hand does. + OwnScale, + Unscaled, +} + +fn view(s: &S, _: &mut Cx<S>) -> El { + let page = col().key("page").size(800.0, 600.0).scale(s.zoom).origin(0.0, 0.0) + .child(el().key("target").absolute(100.0, s.top).size(80.0, 20.0)); + let pop = col().key("pop").w(120.0).h(60.0).padding(10.0) + .child(el().key("btn").size(100.0, 30.0).on_press(|s: &mut S| s.presses += 1) + .child(text("Rename").key("label").font(TextStyle::new(13.0, 400.0)))) + .anchored("target", Side::Bottom, Align::Start, 5.0); + let pop = match s.mode { + Mode::Inherit => pop, + Mode::OwnScale => pop.scale(s.zoom).origin(0.0, 0.0), + Mode::Unscaled => pop.anchored_unscaled(), + }; + col().size(800.0, 600.0).child(page).child(pop) +} + +fn run(s: S) -> Runtime<S> { + let mut rt = Runtime::new(s, view, (800.0, 600.0), Env::new(true, 2.0)); + rt.frame(0.0); + for _ in 0..120 { rt.frame(1.0 / 120.0); } + rt +} + +fn rect(rt: &Runtime<S>, key: &str) -> [f32; 4] { rt.presented(key).unwrap().0 } + +#[test] +fn at_zoom_one_the_overlay_sits_below_its_anchor_at_its_own_size() { + let rt = run(S { zoom: 1.0, top: 100.0, ..S::default() }); + assert_eq!(rect(&rt, "target"), [100.0, 100.0, 80.0, 20.0]); + assert_eq!(rect(&rt, "pop"), [100.0, 125.0, 120.0, 60.0]); + assert_eq!(rect(&rt, "btn"), [110.0, 135.0, 100.0, 30.0]); +} + +#[test] +fn at_zoom_one_point_six_the_overlay_draws_at_the_zoom_beside_the_drawn_anchor() { + let rt = run(S { zoom: 1.6, top: 100.0, ..S::default() }); + assert_eq!(rect(&rt, "target"), [160.0, 160.0, 128.0, 32.0]); + // The gap zooms too: 5 points at 1.6 is 8. + assert_eq!(rect(&rt, "pop"), [160.0, 200.0, 192.0, 96.0]); + assert_eq!(rect(&rt, "btn"), [176.0, 216.0, 160.0, 48.0]); + // Its text rasterizes at the zoom, as the page's does. + let label = rt.tree.nodes.iter().position(|n| n.key.as_deref() == Some("label")).unwrap(); + assert!(rt.paint.inh_scratch[label].scale == 1.6 && rt.paint.inh_scratch[label].scale_motion == ScaleMotion::Still); +} + +#[test] +fn at_zoom_one_point_six_it_flips_by_its_zoomed_size() { + // At 1.0 the 60 point overlay fits below an anchor ending at 320. + let rt = run(S { zoom: 1.0, top: 300.0, ..S::default() }); + assert_eq!(rect(&rt, "pop")[1], 325.0); + // At 1.6 the anchor ends at 512 and the 96 point overlay would end at 616, past the window, + // so it goes above: 480 - 8 - 96. + let rt = run(S { zoom: 1.6, top: 300.0, ..S::default() }); + assert_eq!(rect(&rt, "target"), [160.0, 480.0, 128.0, 32.0]); + assert_eq!(rect(&rt, "pop"), [160.0, 376.0, 192.0, 96.0]); +} + +#[test] +fn at_zoom_one_point_six_a_button_in_the_overlay_hits_where_it_draws() { + let mut rt = run(S { zoom: 1.6, top: 100.0, ..S::default() }); + // Inside the zoomed button (176..336, 216..264), outside where it would sit unzoomed. + rt.pointer_down(320.0, 255.0); + rt.pointer_up(320.0, 255.0); + rt.frame(1.0 / 120.0); + assert_eq!(rt.state.presses, 1); + assert_eq!(rt.element_at(320.0, 255.0).as_ref().and_then(|e| e.key()), Some("btn")); +} + +#[test] +fn an_overlay_that_scales_itself_is_not_zoomed_twice() { + let rt = run(S { zoom: 1.6, top: 100.0, mode: Mode::OwnScale, ..S::default() }); + assert_eq!(rect(&rt, "pop")[2..], [192.0, 96.0]); +} + +#[test] +fn an_unscaled_overlay_stays_at_window_scale_beside_the_drawn_anchor() { + let rt = run(S { zoom: 1.6, top: 100.0, mode: Mode::Unscaled, ..S::default() }); + assert_eq!(rect(&rt, "pop"), [160.0, 197.0, 120.0, 60.0]); +} + +fn long_list(zoom: &f32, _: &mut Cx<f32>) -> El { + let rows = col().key("rows").children((0..40).map(|i| el().key(format!("row{i}")).w(100.0).h(20.0))); + let list = col().key("scroll").shrink().min_h(0.0).scroll(crate::ScrollSpec { stick_bottom: false }).child(rows); + let page = col().size(800.0, 600.0).scale(*zoom).origin(0.0, 0.0) + .child(el().key("target").absolute(100.0, 100.0).size(80.0, 20.0)); + col().size(800.0, 600.0).child(page) + .child(col().key("menu").w(100.0).child(list).anchored_fit("target", Side::Bottom, Align::Start, 5.0)) +} + +#[test] +fn at_zoom_one_point_six_a_fitted_list_fits_the_room_it_draws_in() { + let mut rt = Runtime::new(1.6, long_list, (800.0, 600.0), Env::new(true, 2.0)); + rt.frame(0.0); + for _ in 0..120 { rt.frame(1.0 / 120.0); } + // The anchor draws down to 192 and the gap is 8, so 600 - 8 - 200 = 392 points are left. + let r = rect_of(&rt, "menu"); + assert_eq!(r[1], 200.0); + assert!(r[3] <= 392.0 && r[3] > 390.0, "drawn within the room below: {r:?}"); +} + +fn rect_of<T>(rt: &Runtime<T>, key: &str) -> [f32; 4] { rt.presented(key).unwrap().0 } diff --git a/app/vendor/rune/crates/rune/src/runtime/anchored_grow_tests.rs b/app/vendor/rune/crates/rune/src/runtime/anchored_grow_tests.rs new file mode 100644 index 0000000..36b54c0 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/anchored_grow_tests.rs @@ -0,0 +1,299 @@ +//! `El::anchored`: while an anchored box's size springs, the edge facing the anchor stays a gap +//! away from it, the edge its alignment names stays on it (End keeps its end, Center its centre, +//! Start its start), and the box follows an anchor that moves without trailing on a spring of its own. +use super::*; +use crate::el::{Align, Side}; +use crate::{Cx, El, Env, col, el, row, text}; + +#[derive(Clone, Copy)] +struct S { + label: &'static str, + side: Side, + align: Align, + /// The anchor's width. + w: f32, + /// The height of a box beside the anchor (`Side::Left` / `Side::Right`). + h: f32, + /// A 40 point box this deep away from the anchor, on any side, instead. + depth: Option<f32>, +} + +const SHORT: &str = "1 subagent"; +const LONG: &str = "2 subagents and 1 shell"; + +fn view(s: &S, _: &mut Cx<S>) -> El { + let vertical = matches!(s.side, Side::Top | Side::Bottom); + let cap = if let Some(d) = s.depth { + if vertical { el().key("cap").w(40.0).h(d) } else { el().key("cap").w(d).h(40.0) } + } else if vertical { + row().key("cap").h(28.0).pl(10.0).pr(10.0).items_center().child(text(s.label)) + } else { + el().key("cap").w(40.0).h(s.h) + }; + col().size(800.0, 600.0).items_center().justify_center() + .child(el().key("target").size(s.w, 100.0)) + .child(cap.anchored("target", s.side, s.align, 10.0)) +} + +fn run(side: Side, align: Align) -> Runtime<S> { + start(S { label: SHORT, side, align, w: 600.0, h: 40.0, depth: None }) +} + +fn start(s: S) -> Runtime<S> { + let mut rt = Runtime::new(s, view, (800.0, 600.0), Env::new(true, 1.0)); + rt.frame(0.0); + for _ in 0..240 { rt.frame(1.0 / 120.0); } + rt +} + +fn rect(rt: &Runtime<S>, key: &str) -> [f32; 4] { rt.presented(key).unwrap().0 } + +/// Steps 1/120 s frames until the box settles, checking `held` (the aligned edge, expected) +/// each frame, and returns the box's size along the aligned axis per frame. +fn spring(rt: &mut Runtime<S>, vertical: bool, held: impl Fn(&Runtime<S>) -> (f32, f32)) -> Vec<f32> { + let mut sizes = Vec::new(); + for frame in 0..240 { + rt.frame(1.0 / 120.0); + let (got, want) = held(rt); + assert!((got - want).abs() < 0.5, "frame {frame}: the aligned edge is at {got}, wanted {want}"); + let r = rect(rt, "cap"); + sizes.push(if vertical { r[3] } else { r[2] }); + } + sizes +} + +/// No frame steps more than a tenth of the whole change, as a spring at 120 Hz doesn't. +fn assert_smooth(sizes: &[f32], from: f32, to: f32) { + let step = (to - from).abs() * 0.1; + for pair in sizes.windows(2) { + assert!((pair[1] - pair[0]).abs() < step, "size stepped {} -> {}", pair[0], pair[1]); + } + assert!((sizes[0] - from).abs() < step, "first frame size {} is near {from}", sizes[0]); + assert!((sizes.last().unwrap() - to).abs() < 0.5, "settles at {to}, not {}", sizes.last().unwrap()); + let mid = (from + to) * 0.5; + assert!(sizes.iter().any(|w| (w - mid).abs() < (to - from).abs() * 0.25), "the size springs through {mid}: {sizes:?}"); +} + +#[test] +fn an_end_aligned_box_keeps_its_end_edge_while_its_width_springs() { + let mut rt = run(Side::Top, Align::End); + let [x, _, w, _] = rect(&rt, "cap"); + assert!((x + w - 700.0).abs() < 0.5, "settled at the anchor's right edge: {x} + {w}"); + let short = w; + rt.update(|s, _| s.label = LONG); + let right = |rt: &Runtime<S>| { let r = rect(rt, "cap"); (r[0] + r[2], 700.0) }; + let grow = spring(&mut rt, false, right); + let long = *grow.last().unwrap(); + assert!(long > short + 40.0, "{long} grows from {short}"); + assert_smooth(&grow, short, long); + + rt.update(|s, _| s.label = SHORT); + let shrink = spring(&mut rt, false, right); + assert_smooth(&shrink, long, short); +} + +#[test] +fn a_centred_box_keeps_its_centre_and_a_start_aligned_box_its_start() { + let mut rt = run(Side::Bottom, Align::Center); + rt.update(|s, _| s.label = LONG); + spring(&mut rt, false, |rt| { let r = rect(rt, "cap"); (r[0] + r[2] * 0.5, 400.0) }); + + let mut rt = run(Side::Top, Align::Start); + rt.update(|s, _| s.label = LONG); + spring(&mut rt, false, |rt| (rect(rt, "cap")[0], 100.0)); +} + +#[test] +fn a_box_beside_its_anchor_keeps_its_vertical_alignment_while_its_height_springs() { + for (side, align, held) in [(Side::Right, Align::End, 1.0), (Side::Left, Align::Center, 0.5), (Side::Right, Align::Start, 0.0)] { + let mut rt = run(side, align); + rt.update(|s, _| s.h = 90.0); + let edge = move |rt: &Runtime<S>| { let r = rect(rt, "cap"); (r[1] + r[3] * held, 250.0 + 100.0 * held) }; + let sizes = spring(&mut rt, true, edge); + assert_smooth(&sizes, 40.0, 90.0); + rt.update(|s, _| s.h = 20.0); + let sizes = spring(&mut rt, true, edge); + assert_smooth(&sizes, 90.0, 20.0); + } +} + +#[test] +fn an_anchored_box_follows_its_resizing_anchor_frame_by_frame() { + let mut rt = run(Side::Top, Align::End); + rt.update(|s, _| s.w = 400.0); + let mut moved = false; + for frame in 0..240 { + rt.frame(1.0 / 120.0); + let (cap, target) = (rect(&rt, "cap"), rect(&rt, "target")); + moved |= (target[0] + target[2] - 700.0).abs() > 1.0 && (target[0] + target[2] - 600.0).abs() > 1.0; + assert!((cap[0] + cap[2] - (target[0] + target[2])).abs() < 0.5, + "frame {frame}: box ends at {}, its anchor at {}", cap[0] + cap[2], target[0] + target[2]); + } + assert!(moved, "the anchor springs to its new width"); + assert!((rect(&rt, "cap")[0] + rect(&rt, "cap")[2] - 600.0).abs() < 0.5); +} + +#[test] +fn the_edge_facing_the_anchor_holds_while_the_box_springs_away_from_it() { + // A 300 by 100 anchor spans x 250..550 and y 250..350; each box sits 10 points off it. + let near = |side: Side, r: [f32; 4]| match side { + Side::Top => (r[1] + r[3], 240.0), + Side::Bottom => (r[1], 360.0), + Side::Left => (r[0] + r[2], 240.0), + Side::Right => (r[0], 560.0), + }; + for side in [Side::Top, Side::Bottom, Side::Left, Side::Right] { + let vertical = matches!(side, Side::Top | Side::Bottom); + let mut rt = start(S { label: SHORT, side, align: Align::Start, w: 300.0, h: 40.0, depth: Some(180.0) }); + let held = move |rt: &Runtime<S>| near(side, rect(rt, "cap")); + let (got, want) = held(&rt); + assert!((got - want).abs() < 0.5, "{side:?} settles {want}, not {got}"); + rt.update(|s, _| s.depth = Some(57.0)); + let sizes = spring(&mut rt, vertical, held); + assert_smooth(&sizes, 180.0, 57.0); + rt.update(|s, _| s.depth = Some(180.0)); + let sizes = spring(&mut rt, vertical, held); + assert_smooth(&sizes, 57.0, 180.0); + } +} + +#[test] +fn an_anchored_box_inside_a_moving_or_offset_parent_holds_its_anchor_gap() { + // A bottom-docked composer wrapper rises when the composer grows; a pill inside that + // wrapper anchored above the composer must rise with the composer's drawn top edge on + // every frame rather than double-counting the wrapper's own spring or offset. + #[derive(Clone, Copy)] + struct Dock { + composer_h: f32, + cap_w: f32, + open: bool, + } + fn dock_view(s: &Dock, _: &mut Cx<Dock>) -> El { + let mut wrap = col().key("wrap").w(600.0).offset(15.0, -8.0) + .child(el().key("composer").w_full().h(s.composer_h)); + if s.open { + wrap = wrap.child( + el().key("pill") + .size(s.cap_w, 28.0) + .offset(6.0, -4.0) + .transition( + rune_motion::Transition::offset(0.0, 10.0) + .combined(rune_motion::Transition::scale_anchor(0.8, rune_motion::Vec2::new(1.0, 1.0))), + ) + .raise() + .on_press(|s: &mut Dock| s.cap_w = 180.0) + .anchored("composer", Side::Top, Align::End, 10.0), + ); + } + col().size(800.0, 600.0).items_center() + .child(el().w_full().grow(1.0)) + .child(wrap) + } + let mut rt = Runtime::new(Dock { composer_h: 40.0, cap_w: 100.0, open: false }, dock_view, (800.0, 600.0), Env::new(true, 1.0)); + rt.frame(0.0); + for _ in 0..240 { rt.frame(1.0 / 120.0); } + + // Mount with transition (scale_anchor + offset) and El::offset on the anchored box. + rt.update(|s, _| s.open = true); + rt.frame(1.0 / 120.0); + let comp0 = rt.presented("composer").unwrap().0; + let pill0 = rt.presented("pill").unwrap().0; + assert!(pill0[2] < 98.0 && pill0[2] > 75.0, "entering pill scales from 0.8: {:?}", pill0); + assert!(pill0[1] + pill0[3] > comp0[1] - 10.0 - 4.0 + 2.0, "entering pill starts shifted down by transition offset: {:?}", pill0); + for _ in 0..240 { rt.frame(1.0 / 120.0); } + let comp = rt.presented("composer").unwrap().0; + let pill = rt.presented("pill").unwrap().0; + assert!((pill[0] + pill[2] - (comp[0] + comp[2] + 6.0)).abs() < 0.5, "settled x includes pill's own offset(6): {pill:?} vs {comp:?}"); + assert!((pill[1] + pill[3] - (comp[1] - 10.0 - 4.0)).abs() < 0.5, "settled y includes pill's own offset(-4): {pill:?} vs {comp:?}"); + + // Press hits the raised, offset anchored box and widens it; grow the composer at the same time + // so the parent wrapper springs upward while the pill widens. + let cx = pill[0] + pill[2] * 0.5; + let cy = pill[1] + pill[3] * 0.5; + rt.pointer_down(cx, cy); + rt.pointer_up(cx, cy); + rt.update(|s, _| s.composer_h = 100.0); + for frame in 0..240 { + rt.frame(1.0 / 120.0); + let comp = rt.presented("composer").unwrap().0; + let pill = rt.presented("pill").unwrap().0; + let info = rt.elements().into_iter().find(|e| e.key.as_deref() == Some("pill")).unwrap(); + assert_eq!(info.rect, pill, "frame {frame}: elements() agrees with presented()"); + assert!((pill[0] + pill[2] - (comp[0] + comp[2] + 6.0)).abs() < 0.5, + "frame {frame}: pill right {} stays aligned to composer right + 6 ({})", pill[0] + pill[2], comp[0] + comp[2] + 6.0); + assert!((pill[1] + pill[3] - (comp[1] - 10.0 - 4.0)).abs() < 0.5, + "frame {frame}: pill bottom {} stays 14pt above composer top {}", pill[1] + pill[3], comp[1]); + } + assert!((rt.presented("pill").unwrap().0[2] - 180.0).abs() < 0.5); +} + +#[test] +fn animate_layout_and_scrolled_sticky_subtree_agree_across_paint_caret_and_layout() { + use crate::el::{GrowthSpec, ScrollSpec}; + use crate::{TextEdit, TextStyle, text_input}; + struct Sub { + pop_size: (f32, f32), + edit: TextEdit, + seen_layout: Option<[f32; 4]>, + } + fn sub_view(s: &Sub, cx: &mut Cx<Sub>) -> El { + let seen = cx.layout("pop"); + let mut input = text_input(&s.edit, TextStyle::new(13.0, 400.0)).key("field").size(s.pop_size.0, 22.0).on_edit(|s: &mut Sub| &mut s.edit); + if let Some(r) = seen { + input = input.label(format!("{:.0},{:.0}", r[0], r[1])); + } + col().size(400.0, 300.0) + .child( + col().key("scroll").size(400.0, 300.0).scroll(ScrollSpec { stick_bottom: false }).scroll_xy() + .child( + col().w(900.0).growth(GrowthSpec::default()) + .child( + row().key("hdr").w(900.0).h(40.0).sticky_top(0.0) + .child(el().key("anchor").size(100.0, 30.0).sticky_left(0.0)) + .child( + col().key("pop").size(s.pop_size.0, s.pop_size.1).animate_layout() + .on_layout(|s: &mut Sub, r| s.seen_layout = Some(r)) + .child(input) + .anchored("anchor", Side::Bottom, Align::End, 6.0), + ), + ) + .child(el().size(900.0, 800.0)), + ), + ) + } + let mut edit = TextEdit::new("hi"); + edit.focused = true; + let mut rt = Runtime::new(Sub { pop_size: (120.0, 50.0), edit, seen_layout: None }, sub_view, (400.0, 300.0), Env::new(true, 1.0)); + rt.frame(0.0); + for _ in 0..120 { rt.frame(1.0 / 120.0); } + + // Scroll both axes so the header sticks at (0, 0); the anchored popover and its focused field + // inside the sticky/scrolled subtree must not double-apply scroll or sticky offsets. + rt.wheel_xy(200.0, 150.0, -200.0, -120.0); + for _ in 0..60 { rt.frame(1.0 / 120.0); } + let anc = rt.presented("anchor").unwrap().0; + let pop = rt.presented("pop").unwrap().0; + assert!((anc[0]).abs() < 0.5 && (anc[1]).abs() < 0.5, "anchor stuck at top-left: {anc:?}"); + assert!((pop[0] - 8.0).abs() < 0.5 && (pop[1] - 36.0).abs() < 0.5, "popover sits below stuck anchor (clamped to 8pt left margin): {pop:?}"); + let field_el = rt.elements().into_iter().find(|e| e.key.as_deref() == Some("field")).unwrap(); + let caret = field_el.caret.expect("focused field inside anchored popover has caret"); + assert!(caret[0] >= pop[0] && caret[0] <= pop[0] + pop[2] && (caret[1] - pop[1]).abs() < 8.0, + "caret {caret:?} sits inside drawn popover {pop:?}"); + let laid = rt.state.seen_layout.expect("on_layout reported"); + assert!((laid[0] - pop[0]).abs() < 0.5 && (laid[1] - pop[1]).abs() < 0.5, + "on_layout {laid:?} agrees with drawn popover {pop:?}"); + + // Inside a growth row, `animate_layout` on the anchored box springs both width and height. + rt.update(|s, _| s.pop_size = (180.0, 90.0)); + let mut heights = Vec::new(); + let mut widths = Vec::new(); + for _ in 0..240 { + rt.frame(1.0 / 120.0); + let p = rt.presented("pop").unwrap().0; + widths.push(p[2]); + heights.push(p[3]); + assert!((p[1] - 36.0).abs() < 0.5, "top edge holds at 36 while height springs: {p:?}"); + } + assert_smooth(&widths, 120.0, 180.0); + assert_smooth(&heights, 50.0, 90.0); +} diff --git a/app/vendor/rune/crates/rune/src/runtime/api.rs b/app/vendor/rune/crates/rune/src/runtime/api.rs new file mode 100644 index 0000000..784fb50 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/api.rs @@ -0,0 +1,690 @@ +//! Thin `#[inline(always)]` public and crate-internal forwarders on [`Runtime<S>`] delegating +//! to non-generic [`RuntimeCore`] (frame, lifecycle, settings, layout, elements, motion, a11y, +//! and web). Input, scroll, and selection forwarders live in `runtime/input/api.rs`. + +use super::*; + +#[allow(dead_code)] +impl<S: 'static> Runtime<S> { + // ── Update ───────────────────────────────────────────────────────────────────────────────── + + /// Changes the state from outside any handler, for data another thread delivered + /// (`AppHandle::update`). Runs now, so it works while no window shows; the next frame commits + /// it with the motion `f` asked for. + #[inline(always)] + pub fn update(&mut self, f: impl FnOnce(&mut S, &mut Tx)) { + let (core, mut app) = self.split_mut(); + let (mut one, stall) = core.begin_update(&app); + f(app.state, &mut one); + core.finish_update(&mut app, stall, one, true, false); + } + + /// `update` for a change that may be no change: `f` returns whether it changed state the + /// view reads, as `poll` does. Returns whether the last frame went out of date. + #[inline(always)] + pub fn update_if(&mut self, f: impl FnOnce(&mut S, &mut Tx) -> bool) -> bool { + self.update_inner(f, false).0 + } + + /// `update_if` for an update a window drain runs, returning `(stale, minimize_order)`. + #[inline(always)] + pub(crate) fn update_if_ordered(&mut self, f: impl FnOnce(&mut S, &mut Tx) -> bool) -> (bool, Option<std::num::NonZeroU64>) { + self.update_inner(f, true) + } + + #[inline(always)] + fn update_inner(&mut self, f: impl FnOnce(&mut S, &mut Tx) -> bool, ordered: bool) -> (bool, Option<std::num::NonZeroU64>) { + let (core, mut app) = self.split_mut(); + let (mut one, stall) = core.begin_update(&app); + let changed = f(app.state, &mut one); + core.finish_update(&mut app, stall, one, changed, ordered) + } + + // ── Frame & lifecycle ────────────────────────────────────────────────────────────────────── + + /// Advances animation time by `dt` real seconds, runs queued handlers, re-runs the view only + /// if state changed, steps `Scene`, growth, scroll and reveals, and builds this frame's + /// instances. + #[inline(always)] + pub fn frame(&mut self, dt: f64) -> bool { + let (core, mut app) = self.split_mut(); + core.frame(&mut app, dt) + } + + #[inline(always)] + pub(crate) fn frame_split(&mut self, catch_up: f64, dt: f64) -> bool { + let (core, mut app) = self.split_mut(); + core.frame_split(&mut app, catch_up, dt) + } + + #[inline(always)] + pub(crate) fn hidden_timer_frame(&mut self) { + let (core, mut app) = self.split_mut(); + core.hidden_timer_frame(&mut app); + } + + #[inline(always)] + pub(crate) fn build_for_show(&mut self) -> bool { + let (core, mut app) = self.split_mut(); + core.build_for_show(&mut app) + } + + #[inline(always)] + pub(crate) fn hidden_wake(&mut self) -> bool { + let (core, mut app) = self.split_mut(); + core.hidden_wake(&mut app) + } + + #[inline(always)] + pub(crate) fn covered_wake(&mut self) -> bool { + let (core, mut app) = self.split_mut(); + core.covered_wake(&mut app) + } + + /// Queue a native focus transition. Repeated notifications do not repeat the callback. + #[inline(always)] + pub fn window_focus(&mut self, focused: bool) { + let (core, mut app) = self.split_mut(); + core.window_focus(&mut app, focused); + } + + #[inline(always)] + pub(crate) fn keys_lost(&mut self) { self.core_mut().keys_lost(); } + #[inline(always)] + pub(crate) fn keys_queued(&self) -> bool { self.core().keys_queued() } + #[inline(always)] + pub(crate) fn needs_commit(&self) -> bool { self.core().needs_commit() } + #[inline(always)] + pub(crate) fn stale(&self) -> bool { self.core().stale() } + #[inline(always)] + pub(crate) fn patch_pending(&self) -> bool { self.core().patch_pending() } + + /// Marks app state changed outside a handler (the next frame re-runs the view). + #[inline(always)] + pub fn invalidate(&mut self) { self.core_mut().invalidate(); } + + /// Lands every track before the next frame: growth, reveals and follow-the-end. + #[inline(always)] + pub fn settle_all(&mut self) { self.core_mut().settle_all(); } + + #[inline(always)] + pub(crate) fn ignore_minimize(&mut self, what: &str) { self.core_mut().ignore_minimize(what); } + #[inline(always)] + pub(crate) fn minimize_step(&mut self, event: crate::window::MinimizeEvent) -> bool { self.core_mut().minimize_step(event) } + #[inline(always)] + pub(crate) fn schedule_pending_wakes(&mut self) { self.core_mut().schedule_pending_wakes(); } + + /// Next requested wake on the unscaled app clock. None lets the shell sleep indefinitely. + #[inline(always)] + pub fn wake_deadline(&self) -> Option<f64> { self.core().wake_deadline() } + + /// The native window or overlay's frame counts; `None` headless. + #[inline(always)] + pub fn surface_stats(&self) -> Option<crate::SurfaceStats> { self.core().surface_stats() } + + #[cfg(any(test, feature = "frame-profile"))] + #[inline(always)] + pub(crate) fn polled_at(&self) -> f64 { self.core().polled_at() } + #[cfg(feature = "frame-profile")] + #[inline(always)] + pub(crate) fn poll_wake_deadline(&self) -> Option<f64> { self.core().poll_wake_deadline() } + #[cfg(feature = "frame-profile")] + #[inline(always)] + pub(crate) fn motion_wake_deadline(&self) -> Option<f64> { self.core().motion_wake_deadline() } + + #[inline(always)] + pub fn tracing(&self) -> bool { self.core().tracing() } + + /// A scalar from the actual draw path (e.g. `shell.width`). + #[inline(always)] + pub fn trace_channel(&mut self, name: &'static str, kind: &'static str, value: f32) { + self.core_mut().trace_channel(name, kind, value); + } + + /// Queues an app marker once for each attached writer. Formatting is skipped when off. + #[inline(always)] + pub fn trace_event(&mut self, event: impl std::fmt::Display) { + self.core_mut().trace_event_dyn(&event); + } + + #[cfg(feature = "frame-profile")] + #[inline(always)] + pub(crate) fn fp_loops(&self) -> Vec<String> { self.core().fp_loops() } + + #[cfg_attr(not(target_os = "windows"), allow(dead_code))] + #[inline(always)] + pub(crate) fn loops_shown(&self) -> bool { self.core().loops_shown() } + + // ── Viewport, zoom & window requests ─────────────────────────────────────────────────────── + + /// The window's size in its points and its scale. + #[inline(always)] + pub fn set_viewport(&mut self, viewport: (f32, f32), scale: f32) { + self.core_mut().set_viewport(viewport, scale); + } + + #[inline(always)] + pub(crate) fn step_viewport(&mut self, viewport: (f32, f32), scale: f32) { + self.core_mut().step_viewport(viewport, scale); + } + + /// The view's UI zoom from the last commit (`Cx::zoom`), 1 when unzoomed. + #[inline(always)] + pub fn zoom(&self) -> f32 { self.core().host.zoom() } + + /// The window's size in its own points, before the view's zoom. + #[inline(always)] + pub fn window_viewport(&self) -> (f32, f32) { self.core().host.window_viewport() } + + /// The window's scale, before the view's zoom. + #[inline(always)] + pub fn window_scale(&self) -> f32 { self.core().host.window_scale() } + + /// Physical pixels per view point: what a host divides physical pointer coordinates by. + #[inline(always)] + pub fn input_scale(&self) -> f32 { self.core().input_scale() } + + /// A rect `[x, y, w, h]` from view points to window points. + #[inline(always)] + pub fn to_window(&self, r: [f32; 4]) -> [f32; 4] { self.core().host.to_window(r) } + + /// The root's natural height at the current width, in window points. + #[inline(always)] + pub fn content_height(&mut self) -> f32 { + let (core, app) = self.split_mut(); + core.content_height(&app) + } + + #[inline(always)] + pub(crate) fn set_window_origin(&mut self, origin: (f32, f32)) -> bool { + self.core_mut().set_window_origin(origin) + } + + // ── System settings, fonts & blend ───────────────────────────────────────────────────────── + + #[inline(always)] + pub fn set_system_dark(&mut self, dark: bool) { self.core_mut().set_system_dark(dark); } + #[inline(always)] + pub fn set_titlebar_inset(&mut self, points: f32) { self.core_mut().set_titlebar_inset(points); } + #[inline(always)] + pub(crate) fn system_accent(&self) -> crate::SystemAccent { self.core().system_accent() } + #[inline(always)] + pub fn set_system_accent(&mut self, accent: crate::SystemAccent) { self.core_mut().set_system_accent(accent); } + #[inline(always)] + pub fn set_full_keyboard_access(&mut self, on: bool) { self.core_mut().set_full_keyboard_access(on); } + #[inline(always)] + pub fn set_tab_visits_controls(&mut self, on: bool) { self.core_mut().set_tab_visits_controls(on); } + #[inline(always)] + pub fn set_system_contrast(&mut self, contrast: Option<crate::SystemContrast>) { self.core_mut().set_system_contrast(contrast); } + #[inline(always)] + pub fn set_system_increased_contrast(&mut self, on: bool) { self.core_mut().set_system_increased_contrast(on); } + #[inline(always)] + pub fn set_system_reduced_motion(&mut self, reduced: bool) { self.core_mut().set_system_reduced_motion(reduced); } + #[inline(always)] + pub fn system_reduced_motion(&self) -> bool { self.core().host.system_reduced_motion() } + #[inline(always)] + pub(crate) fn system_scroll_bars_state(&self) -> crate::platform::scroll_bars::SystemScrollBars { self.core().system_scroll_bars_state() } + #[inline(always)] + pub(crate) fn set_system_scroll_bars_state(&mut self, next: crate::platform::scroll_bars::SystemScrollBars) { self.core_mut().set_system_scroll_bars_state(next); } + #[inline(always)] + pub fn set_system_scroll_bars(&mut self, bars: crate::ScrollBars) { self.core_mut().set_system_scroll_bars(bars); } + #[inline(always)] + pub fn system_scroll_bars(&self) -> crate::ScrollBars { self.core().host.system_scroll_bars() } + #[inline(always)] + pub fn set_system_scroller_overlay(&mut self, overlay: bool) { self.core_mut().set_system_scroller_overlay(overlay); } + #[inline(always)] + pub fn system_scroller_overlay(&self) -> bool { self.core().host.system_scroller_overlay() } + #[inline(always)] + pub fn set_system_scroller_jumps(&mut self, jumps: bool) { self.core_mut().set_system_scroller_jumps(jumps); } + #[inline(always)] + pub fn system_scroller_jumps(&self) -> bool { self.core().host.system_scroller_jumps() } + #[inline(always)] + pub fn overlay_scroll_bars(&self) -> bool { self.core().host.overlay_scroll_bars() } + + #[inline(always)] + pub fn set_font_families(&mut self, sans: &str, mono: &str) { self.core_mut().set_font_families(sans, mono); } + #[inline(always)] + pub fn font_families(&self) -> (&str, &str) { self.core().font_families() } + #[inline(always)] + pub(crate) fn follow_font_families(&mut self) -> bool { self.core_mut().follow_font_families() } + + #[inline(always)] + pub fn set_srgb_blend(&mut self, enabled: bool) { self.core_mut().set_srgb_blend(enabled); } + #[inline(always)] + pub fn srgb_blend(&self) -> bool { self.core().srgb_blend() } + #[inline(always)] + pub fn fade_stops(&self) -> [f32; 2] { self.core().fade_stops() } + #[inline(always)] + pub fn set_font_smoothing(&mut self, mode: crate::FontSmoothing) { self.core_mut().set_font_smoothing(mode); } + #[inline(always)] + pub fn font_smoothing(&self) -> crate::FontSmoothing { self.core().font_smoothing() } + #[inline(always)] + pub fn clear_color(&self) -> [f32; 4] { self.core().clear_color() } + + // ── Elements & inspection ────────────────────────────────────────────────────────────────── + + #[inline(always)] + pub fn element_is_secure(&self, path: &str) -> bool { self.core().tree.element_is_secure(path) } + #[inline(always)] + pub fn elements(&self) -> Vec<ElementInfo> { self.core().elements() } + #[inline(always)] + pub fn find(&self, key: &str) -> Option<(f32, f32)> { self.core().find(key) } + #[inline(always)] + pub fn presented(&self, key: &str) -> Option<([f32; 4], f32)> { self.core().presented(key) } + #[inline(always)] + pub fn element_at(&self, x: f32, y: f32) -> Option<Picked> { self.core().element_at(x, y) } + #[inline(always)] + pub fn element_at_with(&self, x: f32, y: f32, pick: Pick) -> Option<Picked> { self.core().element_at_with(x, y, pick) } + #[inline(always)] + pub fn element_at_in(&self, within: &str, x: f32, y: f32) -> Option<Picked> { self.core().element_at_in(within, x, y) } + #[inline(always)] + pub fn element_at_in_with(&self, within: &str, x: f32, y: f32, pick: Pick) -> Option<Picked> { self.core().element_at_in_with(within, x, y, pick) } + #[inline(always)] + pub fn contains(&self, key: &str, x: f32, y: f32) -> bool { self.core().contains(key, x, y) } + #[inline(always)] + pub fn contains_with(&self, key: &str, x: f32, y: f32, pick: Pick) -> bool { self.core().contains_with(key, x, y, pick) } + #[inline(always)] + pub fn presented_pose(&self, key: &str) -> Option<Pose> { self.core().presented_pose(key) } + + #[inline(always)] + pub(crate) fn backdrop_dark(&self) -> Option<bool> { self.core().backdrop_dark() } + + // ── Motion, live, timers, paint, clipboard, memo & URLs ──────────────────────────────────── + + #[inline(always)] + pub fn live_only_events(&self) -> u64 { self.core().live_only_events() } + #[inline(always)] + pub fn check_live_only(&mut self, on: bool) { self.core_mut().check_live_only(on); } + #[inline(always)] + pub fn live_only_warnings(&self) -> &[String] { self.core().live_only_warnings() } + + #[inline(always)] + pub(crate) fn live_wake(&self) -> &Arc<crate::live::Wake> { self.core().live_wake() } + #[inline(always)] + pub fn set_live_waker(&mut self, waker: Waker) { self.core_mut().set_live_waker(waker); } + #[inline(always)] + pub fn set_live_visible(&mut self, visible: bool) { + let (core, mut app) = self.split_mut(); + core.set_live_visible(&mut app, visible); + } + #[inline(always)] + pub(crate) fn live_notifier(&self) -> impl FnOnce() + Send + 'static { self.core().live_notifier() } + #[inline(always)] + pub(crate) fn live_visible(&self) -> bool { self.core().live_visible() } + #[inline(always)] + pub fn live_pending(&self) -> bool { self.core().live_pending() } + + #[inline(always)] + pub fn motion_elements(&self, out: &mut Vec<MotionElement>) { self.core().motion_elements(out); } + #[inline(always)] + pub fn element_path(&self, id: NodeId) -> Option<(&str, Option<&str>)> { self.core().element_path(id) } + #[inline(always)] + pub fn rewind(&self) -> Option<&crate::rewind::Rewind> { self.core().motion.rewind() } + + #[inline(always)] + pub(crate) fn poll_hidden(&mut self) -> bool { + let (core, mut app) = self.split_mut(); + core.poll_hidden(&mut app) + } + #[inline(always)] + pub(crate) fn resting_wake(&mut self) -> Option<bool> { + let (core, mut app) = self.split_mut(); + core.resting_wake(&mut app) + } + #[inline(always)] + pub(crate) fn resting_wake_frame(&mut self, frame: bool) { self.core_mut().resting_wake_frame(frame); } + #[inline(always)] + pub(crate) fn cancel_timer_frame(&mut self) { self.core_mut().cancel_timer_frame(); } + #[inline(always)] + pub(crate) fn rests(&self) -> bool { self.core().rests() } + + #[cfg_attr(not(target_arch = "wasm32"), allow(dead_code))] + #[inline(always)] + pub(crate) fn cycle_paint(&self) -> (u64, Vec<u32>) { self.core().cycle_paint() } + #[inline(always)] + pub(crate) fn paint_count(&self) -> u64 { self.core().paint_count() } + #[cfg_attr(not(target_arch = "wasm32"), allow(dead_code))] + #[inline(always)] + pub(crate) fn paint_cycle_tick(&mut self) -> bool { self.core_mut().paint_cycle_tick() } + #[inline(always)] + pub(crate) fn loop_step(&mut self, dt: f64) -> Result<Vec<u32>, &'static str> { self.core_mut().loop_step(dt) } + #[inline(always)] + pub(crate) fn loop_check_on(&self) -> bool { self.core().loop_check_on() } + #[inline(always)] + pub(crate) fn loop_checked(&mut self) -> Option<(usize, f32)> { self.core_mut().loop_checked() } + #[cfg(test)] + #[inline(always)] + pub(crate) fn paints(&self) -> HashMap<(String, bool), crate::motion_gate::check::paint::Paint> { self.core().paints() } + #[inline(always)] + pub(crate) fn played_keys(&self) -> u64 { + match self.hooks.playground.as_deref() { + Some(p) => p.played, + None => 0, + } + } + #[inline(always)] + pub(crate) fn interaction_presented(&mut self, submitted: crate::time::Instant, presents_at: Option<crate::time::Instant>) { + self.core_mut().interaction_presented(submitted, presents_at); + } + #[inline(always)] + pub(crate) fn interaction_flush(&mut self) { self.core_mut().interaction_flush(); } + + /// Use a shared in-memory clipboard (`clipboard::memory()`) instead of the OS one. + #[inline(always)] + pub fn use_clipboard(&mut self, clipboard: &crate::clipboard::MemoryClipboard) { + self.core_mut().use_clipboard(clipboard); + } + + /// Drops this window's cached subtrees whose memo id starts with `prefix`, then re-runs the view. + #[inline(always)] + pub fn invalidate_memos_by_prefix(&mut self, prefix: &str) { + self.core_mut().invalidate_memos_by_prefix(prefix); + } + + /// Takes the links handlers asked to open that this runtime didn't open. + #[inline(always)] + pub fn take_url_requests(&mut self) -> Vec<String> { self.core_mut().host.take_url_requests() } + + #[cfg(feature = "hot")] + #[inline(always)] + pub(crate) fn hot_scrolls(&self) -> Vec<(String, f64)> { self.core().hot_scrolls() } + #[cfg(feature = "hot")] + #[inline(always)] + pub(crate) fn hot_motion(&self) -> Vec<(String, [f32; 4], [f32; 4])> { self.core().tree.hot_motion(&self.core().scene) } + + // ── Accessibility & web ──────────────────────────────────────────────────────────────────── + + #[cfg(test)] + #[inline(always)] + pub(crate) fn a11y_action(&mut self, request: &accesskit::ActionRequest) -> bool { self.core_mut().a11y_action(request) } + #[inline(always)] + pub fn accessibility_action(&mut self, key: &str, action: accesskit::Action, data: Option<accesskit::ActionData>) -> bool { + self.core_mut().accessibility_action(key, action, data) + } + #[cfg(test)] + #[inline(always)] + pub(crate) fn a11y_activate(&mut self, name: &str) { self.core_mut().a11y_activate(name); } + #[cfg(test)] + #[inline(always)] + pub(crate) fn a11y_deactivate(&mut self) { self.core_mut().a11y_deactivate(); } + #[cfg(test)] + #[inline(always)] + pub(crate) fn a11y_changes(&self) -> crate::a11y::tree::Changes { self.core().a11y_changes() } + #[cfg(test)] + #[inline(always)] + pub(crate) fn a11y_update(&mut self) -> Option<accesskit::TreeUpdate> { self.core_mut().a11y_update() } + #[inline(always)] + pub fn accessibility_tree(&self) -> accesskit::TreeUpdate { self.core().accessibility_tree() } + #[inline(always)] + pub fn accessibility_json(&self) -> serde_json::Value { self.core().accessibility_json() } + #[inline(always)] + pub fn a11y_json(&self) -> String { self.core().a11y_json() } + + #[cfg(test)] + #[inline(always)] + pub(crate) fn web_a11y_items(&self) -> Vec<web_a11y::A11yItem> { self.core().web_a11y_items() } + #[cfg(target_arch = "wasm32")] + #[inline(always)] + pub(crate) fn page_scroll_x(&self) -> Vec<(String, f32)> { self.core().page_scroll_x() } + #[cfg_attr(not(target_arch = "wasm32"), allow(dead_code))] + #[inline(always)] + pub(crate) fn web_a11y_scrolled_only(&self, mirror: &web_a11y::A11yMirror) -> bool { self.core().web_a11y_scrolled_only(mirror) } + #[cfg(any(test, target_arch = "wasm32"))] + #[inline(always)] + pub(crate) fn web_a11y<'a>(&self, mirror: &'a mut web_a11y::A11yMirror) -> Option<&'a str> { self.core().web_a11y(mirror) } + #[cfg(target_arch = "wasm32")] + #[inline(always)] + pub(crate) fn web_a11y_focus<'a>(&self, mirror: &'a mut web_a11y::A11yMirror) -> Option<&'a str> { self.core().web_a11y_focus(mirror) } + #[cfg(any(test, target_arch = "wasm32"))] + #[inline(always)] + pub(crate) fn web_a11y_action(&mut self, event: &serde_json::Value) -> bool { self.core_mut().web_a11y_action(event) } + #[inline(always)] + pub(crate) fn export_nodes(&self) -> Vec<web_export::ExportNode> { self.core().export_nodes() } + + #[inline(always)] + pub(crate) fn page_mode(&mut self) { self.core_mut().page_mode(); } + #[cfg_attr(not(target_arch = "wasm32"), allow(dead_code))] + #[inline(always)] + pub(crate) fn page_height(&self) -> f32 { self.core().page_height() } + #[cfg_attr(not(target_arch = "wasm32"), allow(dead_code))] + #[inline(always)] + pub(crate) fn set_band(&mut self, band: f32, view: f32) -> bool { self.core_mut().set_band(band, view) } + #[cfg_attr(not(target_arch = "wasm32"), allow(dead_code))] + #[inline(always)] + pub(crate) fn set_page_scroll(&mut self, y: f32) -> bool { self.core_mut().set_page_scroll(y) } + #[cfg_attr(not(target_arch = "wasm32"), allow(dead_code))] + #[inline(always)] + pub(crate) fn page_scroll_y(&self) -> f32 { self.core().page_scroll_y() } + #[cfg(any(test, target_arch = "wasm32"))] + #[inline(always)] + pub(crate) fn page_window(&self) -> (f32, f32) { self.core().page_window() } + #[cfg_attr(not(target_arch = "wasm32"), allow(dead_code))] + #[inline(always)] + pub(crate) fn set_page_scroll_x(&mut self, path: &str, x: f32) -> bool { self.core_mut().set_page_scroll_x(path, x) } + #[cfg(any(test, target_arch = "wasm32"))] + #[inline(always)] + pub(crate) fn page_offset(&self) -> f32 { self.core().page_offset() } + + #[cfg(target_arch = "wasm32")] + #[inline(always)] + pub(crate) fn web_release_needs_frame(&self) -> bool { self.core().web_release_needs_frame() } + #[cfg(target_arch = "wasm32")] + #[inline(always)] + pub(crate) fn web_focus_field(&mut self) -> bool { + let (core, mut app) = self.split_mut(); + core.web_focus_field(&mut app) + } + #[cfg(target_arch = "wasm32")] + #[inline(always)] + pub(crate) fn web_edit_context(&mut self, mirror: &mut web_runtime::Mirror) -> Option<bool> { + let (core, mut app) = self.split_mut(); + core.web_edit_context(&mut app, mirror) + } + #[cfg(target_arch = "wasm32")] + #[inline(always)] + pub(crate) fn web_context(&self, mirror: &mut web_runtime::Mirror) -> bool { self.core().web_context(mirror) } + #[cfg(any(test, target_arch = "wasm32"))] + #[inline(always)] + pub(crate) fn web_key(&mut self, event: &serde_json::Value) -> bool { + let (core, mut app) = self.split_mut(); + core.web_key(&mut app, event) + } + #[cfg(target_arch = "wasm32")] + #[inline(always)] + pub(crate) fn web_secure(&mut self, key: &str, text: String) { self.core_mut().web_secure(key, text); } + #[cfg(any(test, target_arch = "wasm32"))] + #[inline(always)] + pub(crate) fn web_edit(&mut self, event: &serde_json::Value) { + let (core, mut app) = self.split_mut(); + core.web_edit(&mut app, event); + } + + // ── Test-only helpers called directly on `Runtime<S>` inside unit tests ─────────────────── + + #[cfg(test)] + #[inline(always)] + pub(super) fn set_focus(&mut self, path: Option<String>, keyboard: bool) -> bool { + let (core, mut app) = self.split_mut(); + core.set_focus(&mut app, path, keyboard) + } + + #[cfg(test)] + #[inline(always)] + pub(super) fn transaction(&self) -> Tx { + let (core, app) = self.split(); + core.transaction(&app) + } + + #[cfg(test)] + #[inline(always)] + pub(super) fn commit(&mut self, tx: &Tx) { + let (core, mut app) = self.split_mut(); + core.commit(&mut app, tx); + } + + #[cfg(test)] + #[inline(always)] + pub(super) fn apply(&mut self, measured: Measured, tx: &Tx) { + let (core, mut app) = self.split_mut(); + core.apply(&mut app, measured, tx); + } + + #[cfg(test)] + #[inline(always)] + pub(super) fn measure(&mut self, tx: &Tx) -> Measured { + let (core, app) = self.split_mut(); + core.measure(&app, tx) + } + + #[cfg(test)] + #[inline(always)] + pub(super) fn commit_kind(&self, tx: &Tx) -> relayout::CommitKind { self.core().commit_kind(tx) } + + #[cfg(test)] + #[inline(always)] + pub(super) fn build(&mut self) -> bool { self.core_mut().build() } + + #[cfg(test)] + #[inline(always)] + pub(super) fn capture_text_flight(&mut self, source: String, target: String) { + let c = self.core_mut(); + c.motion.capture_text_flight(&c.tree.nodes, &mut c.paint, &mut c.text, c.env.scale, c.viewport, c.t, source, target); + } + + #[cfg(test)] + #[inline(always)] + pub(super) fn color(&self, id: NodeId, prop: Prop<Color>, rest: Color) -> Color { self.core().color(id, prop, rest) } + + #[cfg(test)] + #[inline(always)] + pub(super) fn drawn_box(&self, i: usize) -> [f32; 4] { self.core().drawn_box(i) } + + #[cfg(test)] + #[inline(always)] + pub(super) fn focused_key(&self) -> Option<String> { self.core().focused_key() } + + #[cfg(test)] + #[inline(always)] + pub(super) fn focused_layout(&mut self) -> Option<TextLayout> { self.core_mut().focused_layout() } + + #[cfg(test)] + #[inline(always)] + pub(super) fn highlight_visible(&self, i: usize) -> bool { self.core().highlight_visible(i) } + + #[cfg(test)] + #[inline(always)] + pub(crate) fn interaction_tracker(&mut self) -> &mut crate::tooling::interaction::Tracker { self.core_mut().interaction_tracker() } + + #[cfg(test)] + #[inline(always)] + pub(super) fn is_exiting(&self, id: NodeId) -> bool { self.core().is_exiting(id) } + + #[cfg(test)] + #[inline(always)] + pub(super) fn is_selectable(&self, i: usize) -> bool { self.core().is_selectable(i) } + + #[cfg(test)] + #[inline(always)] + pub(super) fn link_boxes(&self, i: usize, rect: [f32; 4]) -> Vec<(usize, [f32; 4])> { self.core().link_boxes(i, rect) } + + #[cfg(test)] + #[inline(always)] + pub(super) fn node(&self, path: &str) -> Option<&Node> { self.core().node(path) } + + #[cfg(test)] + #[inline(always)] + pub(super) fn page_to(&mut self, i: usize, to: impl FnOnce(f64, f64, f64) -> f64) -> bool { self.core_mut().page_to(i, to) } + + #[cfg(test)] + #[inline(always)] + pub(super) fn pointer_event(&self, i: usize, x: f32, y: f32) -> PointerEvent { self.core().pointer_event(i, x, y) } + + #[cfg(test)] + #[inline(always)] + pub(super) fn prune_exited(&mut self) { self.core_mut().prune_exited(); } + + #[cfg(test)] + #[inline(always)] + pub(crate) fn record_rewind(&mut self) { + let c = self.core(); + c.motion.record_rewind(c.clock, c.viewport, &c.tree.nodes, &c.paint); + } + + #[cfg(test)] + #[inline(always)] + pub(super) fn route_key_up(&mut self, ev: &KeyEvent, tx: &mut Tx) -> bool { + let (core, mut app) = self.split_mut(); + core.route_key_up(&mut app, ev, tx) + } + + #[cfg(test)] + #[inline(always)] + pub(super) fn schedule_wakes_from(&mut self, now: f64, wakes: impl IntoIterator<Item = std::time::Duration>) { + self.core_mut().schedule_wakes_from(now, wakes); + } + + #[cfg(test)] + #[inline(always)] + pub(super) fn scroll_at(&self, x: f32, y: f32) -> Option<NodeId> { self.core().scroll_at(x, y) } + + #[cfg(test)] + #[inline(always)] + pub(super) fn scroll_at_axis(&self, x: f32, y: f32, horizontal: bool) -> Option<NodeId> { self.core().scroll_at_axis(x, y, horizontal) } + + #[cfg(test)] + #[inline(always)] + pub(super) fn scroll_viewport(&self, key: &str) -> Option<usize> { self.core().scroll_viewport(key) } + + #[cfg(test)] + #[inline(always)] + pub(super) fn secondary_target(&self, x: f32, y: f32) -> Option<&str> { self.core().secondary_target(x, y) } + + #[cfg(test)] + #[inline(always)] + pub(super) fn selection_menu(&mut self, path: &str, x: f32, y: f32) -> bool { + let (core, app) = self.split_mut(); + core.selection_menu(&app, path, x, y) + } + + #[cfg(test)] + #[inline(always)] + pub(crate) fn sync_selection_pins(&mut self) { self.core_mut().sync_selection_pins(); } + + #[cfg(test)] + #[inline(always)] + pub(super) fn touch_scroll_start(&mut self, x: f32, y: f32) -> Option<NodeId> { self.core_mut().touch_scroll_start(x, y) } + + #[cfg(test)] + #[inline(always)] + pub(super) fn touch_scroll_pan(&mut self, x: f32, y: f32, horizontal: bool, vertical: Option<NodeId>) -> (Option<NodeId>, bool) { + self.core_mut().touch_scroll_pan(x, y, horizontal, vertical) + } + + #[cfg(test)] + #[inline(always)] + pub(super) fn touch_scroll_move(&mut self, id: NodeId, d: f32) { self.core_mut().touch_scroll_move(id, d); } + + #[cfg(test)] + #[inline(always)] + pub(super) fn touch_scroll_end(&mut self, id: Option<NodeId>, velocity: f32) { self.core_mut().touch_scroll_end(id, velocity); } + + #[cfg(test)] + #[inline(always)] + pub(super) fn update_interaction(&mut self, held: Option<bool>) -> bool { self.core_mut().update_interaction(held) } + + #[cfg(all(test, debug_assertions))] + #[inline(always)] + pub(super) fn view_print(&self) -> live_check::ViewPrint { self.core().view_print() } + + #[cfg(test)] + #[inline(always)] + pub(super) fn wheel_lost(&mut self) { self.core_mut().wheel_lost(); } + + #[cfg(all(test, target_os = "macos"))] + #[inline(always)] + pub(crate) fn take_queued_pointer(&mut self) -> Vec<Option<Drag>> { self.core_mut().take_queued_pointer() } + + #[cfg(all(test, target_os = "macos"))] + #[inline(always)] + pub(crate) fn end_click_run(&mut self) { self.core_mut().end_click_run(); } +} diff --git a/app/vendor/rune/crates/rune/src/runtime/aspect_fit_tests.rs b/app/vendor/rune/crates/rune/src/runtime/aspect_fit_tests.rs new file mode 100644 index 0000000..6c5b678 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/aspect_fit_tests.rs @@ -0,0 +1,84 @@ +//! `El::aspect_fit`: the element takes the largest box at its ratio inside the room its parent +//! gives it, so siblings such as a caption sit against the fitted box, not the room. +use super::*; +use crate::{Cx, El, Env, col, el, row, text}; + +/// A 300 by 200 cell, its picture and a 20 pt caption centred in a column. +fn cell(ratio: f32) -> El { + col().size(300.0, 200.0).items_center() + .child(el().key("pic").aspect_fit(ratio)) + .child(text("caption").key("cap").h(20.0)) +} + +fn rects(rt: &Runtime<f32>, keys: &[&str]) -> Vec<[f32; 4]> { + let all = rt.elements(); + keys.iter().map(|k| all.iter().find(|e| e.key.as_deref() == Some(*k)).unwrap().target).collect() +} + +fn run(ratio: f32, view: fn(&f32, &mut Cx<f32>) -> El) -> Runtime<f32> { + let mut rt = Runtime::new(ratio, view, (800.0, 600.0), Env::new(true, 1.0)); + rt.frame(0.0); + rt +} + +#[test] +fn a_picture_fits_its_cell_less_the_caption() { + fn view(r: &f32, _: &mut Cx<f32>) -> El { col().child(cell(*r)) } + let rt = run(2.0, view); + let [pic, cap] = rects(&rt, &["pic", "cap"])[..] else { unreachable!() }; + assert_eq!(pic, [0.0, 0.0, 300.0, 150.0], "a wide picture takes the cell's width"); + assert_eq!(cap[1], 150.0, "the caption sits under the picture"); + let rt = run(0.5, view); + assert_eq!(rects(&rt, &["pic", "cap"])[0], [105.0, 0.0, 90.0, 180.0], + "a tall one takes the height the caption leaves, centred by the column"); +} + +#[test] +fn a_new_ratio_or_room_refits() { + fn view(r: &f32, _: &mut Cx<f32>) -> El { col().w_full().h_full().items_center().child(el().key("pic").aspect_fit(*r)) } + let mut rt = run(2.0, view); + assert_eq!(rects(&rt, &["pic"])[0][2..], [800.0, 400.0]); + rt.update(|r, _| *r = 0.5); + rt.frame(1.0); + assert_eq!(rects(&rt, &["pic"])[0][2..], [300.0, 600.0]); + rt.set_viewport((400.0, 400.0), 1.0); + rt.frame(2.0); + assert_eq!(rects(&rt, &["pic"])[0][2..], [200.0, 400.0]); +} + +#[test] +fn cells_in_a_row_each_fit_their_own() { + fn view(r: &f32, _: &mut Cx<f32>) -> El { + let cell = |k: &'static str, r: f32| col().grow(1.0).h_full().items_center().child(el().key(k).aspect_fit(r)); + col().child(row().size(610.0, 200.0).gap(10.0).child(cell("a", *r)).child(cell("b", 0.5))) + } + let rt = run(3.0, view); + assert_eq!(rects(&rt, &["a", "b"]), [[0.0, 0.0, 300.0, 100.0], [410.0, 0.0, 100.0, 200.0]]); +} + +#[test] +fn max_sizes_bound_it_where_nothing_else_does() { + fn view(r: &f32, _: &mut Cx<f32>) -> El { + col().child(col().w(300.0).child(el().key("pic").max_h(80.0).aspect_fit(*r)).child(text("caption").key("cap").h(20.0))) + } + let rt = run(2.0, view); + let [pic, cap] = rects(&rt, &["pic", "cap"])[..] else { unreachable!() }; + assert_eq!(pic, [0.0, 0.0, 160.0, 80.0], "an auto-height column has no free space, so max_h sets the room's height"); + assert_eq!(cap[1], 80.0); +} + +#[test] +fn grow_and_content_do_not_size_the_fitted_box() { + fn view(r: &f32, _: &mut Cx<f32>) -> El { + col() + .child(col().size(300.0, 200.0).child(el().key("grown").grow(1.0).aspect_fit(*r))) + .child(row().size(600.0, 200.0) + .child(el().key("a").aspect_fit(*r).child(el().w(200.0).h(10.0))) + .child(el().key("b").aspect_fit(*r))) + } + let rt = run(2.0, view); + let [grown, a, b] = rects(&rt, &["grown", "a", "b"])[..] else { unreachable!() }; + assert_eq!(grown[2..], [300.0, 150.0], "its own grow doesn't stretch it back to the room"); + assert_eq!((a[2..].to_vec(), b[2..].to_vec()), (vec![300.0, 150.0], vec![300.0, 150.0]), + "a 200 pt child doesn't take its cell a bigger share of the row"); +} diff --git a/app/vendor/rune/crates/rune/src/runtime/bands_tests.rs b/app/vendor/rune/crates/rune/src/runtime/bands_tests.rs new file mode 100644 index 0000000..ddaf41f --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/bands_tests.rs @@ -0,0 +1,69 @@ +use super::*; +use crate::render::{KIND_RECT, KIND_SHADOW, NO_CLIP}; + +fn shadow(rect: [f32; 4], sigma: f32) -> Instance { + Instance { rect, radii: [16.0; 4], fill: [0.0, 0.0, 0.0, 0.3], border: [0.0; 4], params: [0.0, KIND_SHADOW, sigma, 1.0], uv: [0.0; 4], clip: NO_CLIP, fade: [0; 4] } +} + +/// Each band's window in absolute device px, as `base_vs` clamps the grown quad to it. +fn windows(out: &[Instance], grow: f32) -> Vec<[f32; 4]> { + out.iter().map(|i| { + let [x, y, w, h] = i.rect; + let [u0, v0, u1, v1] = i.uv; + assert!(u1 < 0.0, "every band carries the mark"); + [(x - grow).max(x + u0), (y - grow).max(y + v0), (x + w + grow).min(x - u1), (y + h + grow).min(y + v1)] + }).collect() +} + +fn area(r: [f32; 4]) -> f32 { + (r[2] - r[0]).max(0.0) * (r[3] - r[1]).max(0.0) +} + +#[test] +fn a_big_shadow_draws_as_four_bands_around_the_box() { + let mut out = Vec::new(); + let caster = [100.0, 100.0, 1000.0, 600.0]; + push_shadow(&mut out, shadow([100.0, 104.0, 1000.0, 600.0], 4.0), caster, [16.0; 4]); + assert_eq!(out.len(), 4); + let grow = 4.0 * 3.0 + 1.0; + let bands = windows(&out, grow); + let quad = [100.0 - grow, 104.0 - grow, 1100.0 + grow, 704.0 + grow]; + let hole = [117.0, 117.0, 1083.0, 683.0]; + let total: f32 = bands.iter().map(|&b| area(b)).sum(); + assert_eq!(total, area(quad) - area(hole), "the bands tile the quad around the hole"); + for (a, b) in bands.iter().enumerate().flat_map(|(k, a)| bands[k + 1..].iter().map(move |b| (a, b))) { + assert_eq!(area([a[0].max(b[0]), a[1].max(b[1]), a[2].min(b[2]), a[3].min(b[3])]), 0.0, "bands never overlap"); + } + let whole = shadow([100.0, 104.0, 1000.0, 600.0], 4.0); + assert!(out.iter().all(|i| (i.rect, i.radii, i.fill, i.params, i.clip) == (whole.rect, whole.radii, whole.fill, whole.params, whole.clip)), "each band shades as the whole did"); +} + +#[test] +fn a_small_shadow_stays_one_quad() { + let mut out = Vec::new(); + push_shadow(&mut out, shadow([0.0, 2.0, 120.0, 80.0], 4.0), [0.0, 0.0, 120.0, 80.0], [8.0; 4]); + assert_eq!(out.len(), 1); + assert_eq!(out[0].uv, [0.0; 4]); +} + +#[test] +fn a_shadow_with_a_hole_already_stays_one_quad() { + let mut out = Vec::new(); + let inst = Instance { uv: [0.0, 0.0, 1000.0, 600.0], ..shadow([0.0, 0.0, 1000.0, 600.0], 4.0) }; + push_shadow(&mut out, inst, [0.0, 0.0, 1000.0, 600.0], [8.0; 4]); + assert_eq!(out.len(), 1); +} + +#[test] +fn a_big_border_ring_draws_as_bands_and_a_filled_box_never_asks() { + let mut out = Vec::new(); + let ring = Instance { rect: [10.0, 10.0, 800.0, 500.0], radii: [-16.0; 4], fill: [0.0; 4], border: [1.0; 4], params: [1.0, KIND_RECT, 0.0, 1.0], uv: [0.0; 4], clip: NO_CLIP, fade: [0; 4] }; + push_ring(&mut out, ring); + assert_eq!(out.len(), 4); + let bands = windows(&out, 1.0); + // Continuous corners reach K times their radius along each edge. + let e = 16.0 * crate::render::CONTINUOUS_K + 1.0 + 0.5 + 1.0; + let hole = [10.0 + e, 10.0 + e, 810.0 - e, 510.0 - e]; + let total: f32 = bands.iter().map(|&b| area(b)).sum(); + assert!((total - (area([9.0, 9.0, 811.0, 511.0]) - area(hole))).abs() < 1.0); +} diff --git a/app/vendor/rune/crates/rune/src/runtime/commit.rs b/app/vendor/rune/crates/rune/src/runtime/commit.rs new file mode 100644 index 0000000..b7ecfb8 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/commit.rs @@ -0,0 +1,500 @@ +//! View-to-scene commit orchestration (`Runtime::commit`, `Measurement`, `Measured`). +use super::*; + +mod prepare; +pub(super) mod apply; +pub(super) mod apply_scratch; +mod device; +pub(super) mod flatten; +#[cfg(debug_assertions)] +pub(super) mod layout_diagnostics; +pub(super) mod measure; +pub(crate) mod memo_reuse; +pub(super) mod prune; +#[cfg(test)] +mod prune_tests; +pub(super) mod relayout; +pub(super) mod remount; +pub(super) mod text_layout; +pub(super) mod watch; +pub(super) mod why; + +/// View commit, Taffy layout, memoization, virtual list windows and layout/visibility callback +/// tracking owned by [`RuntimeCore`]. Ordered hot-first under `#[repr(C)]` so per-frame flags +/// (`dirty`, `relayout`, `settle`) sit directly adjacent to [`FrameState`]'s `queue`/`live`. +#[repr(C)] +pub(crate) struct CommitState { + pub(crate) dirty: bool, + pub(in crate::runtime) relayout: bool, + /// Every viewport change since the last commit came from the window's own resize + /// animation (`step_viewport`), not the user or the system. + viewport_stepped: bool, + settle: bool, + /// True when the commit in flight is for scroll/layout only (`self.state` wasn't mutated). + state_unchanged: bool, + /// Why this frame committed, as [`commit_why::CommitWhy`] bits, until the frame log takes them. + commit_why: u16, + pub(crate) commits: u64, + commit_gen: u64, + /// The memo pass the current commit's first view build was. Memos none of its builds used + /// go once it applies. + memo_since: u64, + /// The clock at the last commit. + last_commit_clock: f64, + /// The last view's `Cx::foreground` and `Cx::focus_ring`, for rows built after it and the + /// rings painted until the next. + pub(in crate::runtime) defaults: cx::ViewDefaults, + reuse: relayout::Reuse, + pub(in crate::runtime) layout: LayoutEngine, + memo: crate::memo::MemoCache, + apply_scratch: apply_scratch::ApplyScratch, + pub(in crate::runtime) watch: crate::tooling::perf_warn::Watch, + /// Opt-in tooling checks. None keeps release commits free of key traversal/allocation. + key_warnings: Option<Vec<String>>, + pub(crate) virtuals: HashMap<String, crate::el::virtual_list::VirtualList>, + virtual_culled: HashSet<String>, + /// Fresh view accessors for focused text fields omitted by virtualization. + pub(in crate::runtime) virtual_inputs: HashMap<String, Box<InputSpec>>, + /// Whether an index-built list still fills its overscan, and for how many frames. + pub(in crate::runtime) virtual_fill: virtual_fill::Fill, + /// Keys the last view read with `Cx::layout` or `Cx::layout_size`, and what each resolved to. + pub(in crate::runtime) layout_seen: layout_read::LayoutSeen, + /// Rect last sent to each element's `El::on_layout`. + layout_fired: HashMap<NodeId, [f32; 4]>, + /// Rect last sent to each element's `El::on_screen_layout`. + screen_fired: HashMap<NodeId, [f32; 4]>, + /// (Drawn rect, laid-out rect) last sent to each element's `El::on_drawn_layout`. + drawn_fired: HashMap<NodeId, ([f32; 4], [f32; 4])>, + /// Whether each element with `El::on_visible` was last on screen. + visible_fired: HashMap<NodeId, bool>, + /// Whether layout feedback may still cause a commit (see `layout_read`). + feedback: layout_read::Feedback, +} + +impl CommitState { + // Single-caller constructor for `RuntimeCore::new`; inlined so it stays in its caller's + // codegen unit instead of shifting partitioning and dropping inlining in the paint walk. + #[inline] + pub(in crate::runtime) fn new() -> Self { + Self { + layout: LayoutEngine::new(), + memo: Default::default(), + memo_since: 0, + apply_scratch: Default::default(), + commits: 0, + commit_gen: 0, + dirty: true, + relayout: false, + viewport_stepped: false, + settle: false, + state_unchanged: false, + reuse: Default::default(), + commit_why: 0, + watch: Default::default(), + key_warnings: None, + defaults: Default::default(), + virtuals: HashMap::default(), + virtual_culled: HashSet::default(), + virtual_inputs: HashMap::default(), + virtual_fill: virtual_fill::Fill::default(), + layout_seen: Default::default(), + layout_fired: HashMap::default(), + screen_fired: HashMap::default(), + drawn_fired: HashMap::default(), + visible_fired: HashMap::default(), + feedback: Default::default(), + last_commit_clock: f64::NEG_INFINITY, + } + } + + #[inline] + pub(in crate::runtime) fn is_viewport_stepped(&self) -> bool { + self.viewport_stepped + } + + #[inline] + pub(in crate::runtime) fn set_viewport_stepped(&mut self, stepped: bool) { + self.viewport_stepped = stepped; + } + + #[inline] + pub(in crate::runtime) fn is_settling(&self) -> bool { + self.settle + } + + #[inline] + pub(in crate::runtime) fn request_settle(&mut self) { + self.settle = true; + } + + #[inline] + pub(in crate::runtime) fn set_state_unchanged(&mut self, unchanged: bool) { + self.state_unchanged = unchanged; + } + + #[inline] + pub(crate) fn take_commit_why(&mut self) -> u16 { + std::mem::take(&mut self.commit_why) + } + + #[inline] + pub(crate) fn clear_commit_why(&mut self) { + self.commit_why = 0; + } + + #[cfg(test)] + #[inline] + pub(in crate::runtime) fn commit_why(&self) -> u16 { + self.commit_why + } + + #[inline] + pub(in crate::runtime) fn commit_gen(&self) -> u64 { + self.commit_gen + } + + #[cfg(test)] + #[inline] + pub(in crate::runtime) fn set_commit_gen(&mut self, generation: u64) { + self.commit_gen = generation; + } + + #[inline] + pub(in crate::runtime) fn last_commit_clock(&self) -> f64 { + self.last_commit_clock + } + + #[inline] + pub(in crate::runtime) fn set_read_moved(&mut self, moved: bool) { + self.reuse.read_moved = moved; + } + + #[cfg(test)] + #[inline] + pub(in crate::runtime) fn set_reuse_scale(&mut self, scale: f32) { + self.reuse.scale = scale; + } + + #[inline] + pub(crate) fn clear_memo(&mut self) { + self.memo.clear(); + } + + #[inline] + pub(crate) fn evict_memo_prefix(&mut self, prefix: &str) { + self.memo.evict_prefix(prefix); + } + + #[cfg(test)] + #[inline] + pub(in crate::runtime) fn memo_builds(&self) -> usize { + self.memo.builds + } + + #[cfg(test)] + #[inline] + pub(in crate::runtime) fn memo_len(&self) -> usize { + self.memo.len() + } + + #[inline] + pub(crate) fn enable_key_warnings(&mut self) { + self.key_warnings = Some(Vec::new()); + } + + #[inline] + pub(crate) fn key_warnings(&self) -> Option<&[String]> { + self.key_warnings.as_deref() + } + + #[inline] + pub(in crate::runtime) fn push_key_warning(&mut self, msg: impl FnOnce() -> String) { + if let Some(warnings) = self.key_warnings.as_mut() { + warnings.push(msg()); + } + } + + #[cfg(test)] + #[inline] + pub(crate) fn virtuals(&self) -> &HashMap<String, crate::el::virtual_list::VirtualList> { + &self.virtuals + } + + #[cfg(test)] + #[inline] + pub(crate) fn virtual_culled(&self) -> &HashSet<String> { + &self.virtual_culled + } + + #[inline] + pub(in crate::runtime) fn take_layout_fired(&mut self, screen: bool) -> HashMap<NodeId, [f32; 4]> { + std::mem::take(if screen { &mut self.screen_fired } else { &mut self.layout_fired }) + } + + #[inline] + pub(in crate::runtime) fn set_layout_fired(&mut self, screen: bool, fired: HashMap<NodeId, [f32; 4]>) { + *(if screen { &mut self.screen_fired } else { &mut self.layout_fired }) = fired; + } + + #[inline] + pub(in crate::runtime) fn drawn_fired_empty(&self) -> bool { + self.drawn_fired.is_empty() + } + + #[inline] + pub(in crate::runtime) fn take_drawn_fired(&mut self) -> HashMap<NodeId, ([f32; 4], [f32; 4])> { + std::mem::take(&mut self.drawn_fired) + } + + #[inline] + pub(in crate::runtime) fn set_drawn_fired(&mut self, fired: HashMap<NodeId, ([f32; 4], [f32; 4])>) { + self.drawn_fired = fired; + } + + #[inline] + pub(in crate::runtime) fn visible_fired_empty(&self) -> bool { + self.visible_fired.is_empty() + } + + #[inline] + pub(in crate::runtime) fn take_visible_fired(&mut self) -> HashMap<NodeId, bool> { + std::mem::take(&mut self.visible_fired) + } + + #[inline] + pub(in crate::runtime) fn set_visible_fired(&mut self, seen: HashMap<NodeId, bool>) { + self.visible_fired = seen; + } + + #[inline] + pub(in crate::runtime) fn feedback_open(&self) -> bool { + self.feedback.open() + } + + #[inline] + pub(in crate::runtime) fn step_feedback(&mut self, event: layout_read::FeedbackEvent) { + self.feedback = self.feedback.step(event); + } + + /// Restores any nodes moved out of `old_nodes` and recycles `measured`'s buffers before a + /// commit pass re-measures. + pub(in crate::runtime) fn discard_measured( + &mut self, + old_nodes: &mut [Node], + spare_nodes: &mut Vec<Node>, + mut measured: Measured, + ) { + memo_reuse::restore_moved_nodes(old_nodes, &mut measured.nodes, &measured.memo_reused, &measured.taken_paths); + measured.nodes.clear(); + *spare_nodes = measured.nodes; + if let Some(mut pending) = measured.memo_flattened { + pending.clear(); + self.memo.pending_scratch = pending; + } + measured.memo_reused.clear(); + self.memo.reused_scratch = measured.memo_reused; + measured.taken_paths.clear(); + self.memo.taken_paths_scratch = measured.taken_paths; + self.layout = measured.layout; + } +} + +/// Which measurement pass a commit is on. The first pass trusts the last commit's geometry; a +/// retry measures again because a virtual window fell short; past eight retries the pass is +/// forced, mounting every row so a degenerate transcript can't loop forever. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum Pass { + First, + Retry { n: u8 }, + Forced, +} + +impl Pass { + /// The pass number `finish_from` counts to. + pub(super) fn of(passes: usize) -> Self { + match passes { + 0 | 1 => Self::First, + n if n > 8 => Self::Forced, + n => Self::Retry { n: u8::try_from(n).unwrap_or(u8::MAX) }, + } + } + + /// The last commit's measured viewport still stands; a retry keeps the one the last pass found. + pub(super) fn trusts_estimates(self) -> bool { + matches!(self, Self::First) + } + + /// Newly mounted rows may spread over the next frames. A retry builds what the viewport + /// needs now, and keeps the rows a live-only check already has mounted. + pub(super) fn spreads_rows(self) -> bool { + matches!(self, Self::First) + } + + /// A newly selected row may be revealed. A retry would only fight the estimate it is fixing. + pub(super) fn reveals(self) -> bool { + matches!(self, Self::First) + } + + /// Every row mounts, whatever the window says. + pub(super) fn forced(self) -> bool { + matches!(self, Self::Forced) + } +} + +/// Measurement capabilities: text/layout caches and virtual geometry only. In particular this +/// type has no Scene, growth tracks, reveal tracks, draw instances, or mutable app state. +pub(super) struct Measurement<'a> { + pub(super) app: &'a dyn ViewDriver, + pub(super) env: Env, + pub(super) viewport: (f32, f32), + pub(super) fit_height: bool, + pub(super) system_reduced_motion: bool, + pub(super) titlebar_inset: f32, + pub(super) chrome: crate::ChromeInsets, + /// Caption buttons drawn over the view's root. + pub(super) caption: Option<crate::titlebar::Caption>, + pub(super) system_accent: crate::SystemAccent, + pub(super) system_contrast: Option<crate::SystemContrast>, + pub(super) system_increased_contrast: bool, + pub(super) system_scroll_bars: crate::platform::scroll_bars::SystemScrollBars, + pub(super) reduced_motion: bool, + pub(super) time_scale: f32, + /// The window's zoom, then the one the view asked for (`Cx::zoom`) once it returns. + pub(super) zoom: f32, + /// `Cx::foreground` and `Cx::focus_ring`: the last view's, then this one's once it returns. + pub(super) defaults: cx::ViewDefaults, + /// `Cx::set_titlebar` and `Cx::titlebar_height`, as the view sets them. + pub(super) titlebar: crate::titlebar::TitlebarSet, + pub(super) commits: u64, + /// The last commit's nodes. A pass that commits drops the text layouts of the ones it keeps. + pub(super) nodes: &'a mut [Node], + pub(super) committing: bool, + pub(super) spare_nodes: &'a mut Vec<Node>, + pub(super) layout: &'a mut LayoutEngine, + pub(super) node_index: &'a mut NodeIndex, + pub(super) path_ids: &'a mut HashMap<String, NodeId>, + pub(super) memo: &'a mut crate::memo::MemoCache, + pub(super) next_id: &'a mut u64, + pub(super) scrolls: &'a mut HashMap<NodeId, ScrollState>, + pub(super) virtuals: &'a mut HashMap<String, crate::el::virtual_list::VirtualList>, + pub(super) virtual_culled: &'a mut HashSet<String>, + pub(super) virtual_inputs: &'a mut HashMap<String, Box<InputSpec>>, + pub(super) stats: &'a mut FrameStats, + pub(super) key_warnings: &'a mut Option<Vec<String>>, + /// The focused element's path, so an index-built row holding it is still built. + pub(super) focused: Option<&'a str>, + /// True when `self.state` was not mutated since the previous commit. + pub(super) state_unchanged: bool, + /// Which pass this is: the first, a retry after estimates left part of a viewport blank, or + /// the forced full measurement that ends a runaway retry. + pub(super) pass: Pass, + /// This commit is a live-only check's: virtual lists keep the rows they mount now. + pub(super) hold_windows: bool, + /// Windows picked for lists in a memo that `keeps_windows` then expanded, by list path. + pub(super) windowed: HashMap<String, super::measure::Window>, + /// Lists kept with their memo this pass, and which of their mounted rows mount quietly. + pub(super) kept_lists: Vec<(String, Vec<bool>)>, + pub(super) caret: Option<(String, [f32; 4])>, + pub(super) caret_read: bool, + pub(super) layout_seen: layout_read::LayoutRects, + pub(super) layout_reads: layout_read::LayoutReads, +} + +/// Owned result of completed measurement. Scene mutation consumes this once; retries never +/// return it. Keeping this separate from El makes unmeasured views invalid commit inputs. +pub(super) struct Measured { + pub(super) layout: LayoutEngine, + pub(super) nodes: Vec<Node>, + pub(super) reduced_motion: bool, + pub(super) time_scale: f32, + pub(super) zoom: f32, + pub(super) defaults: cx::ViewDefaults, + pub(super) titlebar: crate::titlebar::TitlebarSet, + pub(super) caret_read: bool, + pub(super) layout_reads: layout_read::LayoutReads, + pub(super) memo_flattened: Option<Vec<memo_reuse::PendingFlat>>, + pub(super) memo_reused: Vec<memo_reuse::ReusedSpan>, + pub(super) taken_paths: Vec<(u32, u32)>, + /// The selection as the measure began, before reused `memo` subtrees left the last + /// commit's nodes. + pub(super) selection: Vec<layout_read::SelectedRange>, +} + +impl RuntimeCore { + pub(super) fn commit(&mut self, app: &mut dyn AppDriver, tx: &Tx) { + let _commit_time = crate::frame::profile::Scope::new(crate::frame::profile::Phase::Commit); + let _first_view = crate::tooling::perf_warn::launch::FirstView::start(self.commit.commits == 0); + let budget = crate::tooling::perf_warn::budget::Commit::start(); + self.apply_playground(app); + let _history = crate::memo::snapshot::enter(); + COMMITS.set(COMMITS.get() + 1); + self.commit.last_commit_clock = self.clock; + self.commit.memo_since = self.commit.memo.next_pass(); + for r in self.scroll.requests.reveals() { + if r.at_end && let Some(&id) = self.tree.path_ids.get(&r.viewport) + && let Some(scroll) = self.scroll.scrolls.get_mut(&id) + { + scroll.pin(); + } + } + self.note_drawn_rows(); + let mut measured = self.measure_commit(app, tx); + // A new zoom lays the view out again at the scale and size it gives, in this commit. + if self.apply_zoom(measured.zoom) { + self.discard_measured(measured); + measured = self.measure_commit(app, tx); + } + self.kbd.focus_before_commit = self.kbd.focus.owned(); + // Settle layout reads first so a field that mounts once a rect is known is in `nodes`. + measured = self.settle_layout_reads(app, measured, tx); + if self.sync_requested_focus(app, &mut measured.nodes) { + self.discard_measured(measured); + measured = self.measure(app, tx); + measured = self.settle_layout_reads(app, measured, tx); + } + if measured.caret_read && self.caret_moved(Some(&measured.nodes)) { + self.discard_measured(measured); + measured = self.measure(app, tx); + measured = self.settle_layout_reads(app, measured, tx); + } + self.apply(app, measured, tx); + self.scene.keep_flights(false); + self.commit.memo.keep_since(self.commit.memo_since); + self.track_focused_rows(); + #[cfg(debug_assertions)] + if COMMITS.get() % 16 == 1 { self.a11y_warn_nameless(); } + self.prune_text_selection(); + budget.end(self.commit.watch.cause); + } + + /// A frame's commit for `why` (`CommitWhy` bits). + pub(in crate::runtime) fn commit_for(&mut self, app: &mut dyn AppDriver, tx: &Tx, why: u16) { + self.commit.begin_watch(why); + self.commit(app, tx); + self.commit.end_watch(); + } + + /// Restores any nodes moved out of `self.nodes` and recycles `measured`'s buffers before a + /// commit pass re-measures. + #[inline] + pub(super) fn discard_measured(&mut self, measured: Measured) { + self.commit.discard_measured(&mut self.tree.nodes, &mut self.tree.spare_nodes, measured); + } +} + +/// A horizontal scroll viewport's content without a width of its own, or one filling the +/// viewport (`w_full`), takes its natural one, unwrapped, and at least the viewport's (CSS +/// `width: max-content; min-width: 100%`). Any other width stays as set, narrower than the +/// viewport too. The content never shrinks. The viewport lays it out as a row, where taffy +/// measures a max-content main size unwrapped (a column measures its height wrapped at the +/// viewport's width). With vertical scrolling too it keeps its natural height instead of +/// stretching to the viewport's. +pub(super) fn unwrapped_width(style: &mut CompactStyle, vertical: bool) { + let w = style.size().width; + if w.is_auto() || w == Dimension::percent(1.0) { + style.set_width(Dimension::max_content()); + if style.min_size().width.is_auto() { style.set_min_width(percent(1.0)); } + } + style.set_flex_shrink(0.0); + if vertical && style.align_self().is_none() { style.set_align_self(Some(AlignSelf::FLEX_START)); } +} diff --git a/app/vendor/rune/crates/rune/src/runtime/commit/apply.rs b/app/vendor/rune/crates/rune/src/runtime/commit/apply.rs new file mode 100644 index 0000000..8d1ca68 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/commit/apply.rs @@ -0,0 +1,567 @@ +//! Applying a completed measurement pass to `Scene`, growth stacks, reveals, scroll viewports, +//! live bindings and retained exits. +use super::*; + +mod exits; +mod growth; + +impl RuntimeCore { + /// The mutation phase cannot accept an El or an unfinished measurement pass. + pub(in crate::runtime) fn apply(&mut self, app: &mut dyn AppDriver, measured: Measured, tx: &Tx) { + let _apply_time = crate::frame::profile::Scope::new(crate::frame::profile::Phase::Apply); + let Measured { layout: mut taffy, mut nodes, reduced_motion, time_scale, defaults, titlebar, caret_read, memo_flattened, memo_reused, taken_paths, .. } = measured; + self.commit.defaults = defaults; + if crate::tooling::interaction::active() { self.interaction_reused(&memo_reused); } + let mut scratch = std::mem::take(&mut self.commit.apply_scratch); + self.edit.caret_watch = caret_read; + let reduced_motion_unchanged = reduced_motion == self.reduced_motion; + if !reduced_motion_unchanged { + self.reduced_motion = reduced_motion; + self.scene.set_reduced_motion(reduced_motion); + } + self.time_scale = time_scale; + if tx.commit.lands() { self.motion.clear_flights(); } + let scale = self.env.scale; + // Culling is not a model removal. Retire offscreen scene/growth state immediately; + // re-entering historical rows mount settled and don't replay streaming words. + if !self.commit.virtual_culled.is_empty() { + scratch.culled.clear(); + scratch.culled.resize(self.tree.nodes.len(), false); + for (i, n) in self.tree.nodes.iter().enumerate() { + if self.commit.virtual_culled.contains(&n.path) || n.parent.is_some_and(|p| scratch.culled[p]) { + scratch.culled[i] = true; + self.scene.unmount(n.id); + self.motion.grows.remove(&n.id); + } + } + for path in &self.commit.virtual_culled { + if let Some(id) = self.tree.path_ids.get(path) { + self.scene.unmount(*id); + self.motion.grows.remove(id); + } + } + } + for v in self.commit.virtuals.values_mut() { + v.shown = v.keys[v.range.clone()].iter().cloned().collect(); + v.mounted = v.indexed.then(|| crate::el::virtual_list::Mounted::of(v)); + } + // A row scrolled into view mounts settled with its subtree. Content added later under a + // row already on screen is a live change and keeps its own entrance. + // Parents precede children, so a remounting row passes its flag down its whole subtree. + for i in 0..nodes.len() { + if let Some(p) = nodes[i].parent { + nodes[i].virtual_mount |= nodes[p].virtual_mount && !self.scene.contains(nodes[p].id); + } + } + let first = self.commit.commits == 0; + self.commit.commits += 1; + self.stats.commits = self.commit.commits; + // Concealing is a security boundary: old geometry must not disclose the revealed + // line count through a height spring, displaced siblings, or a lingering scroll glide. + let revealed: HashSet<_> = self.tree.nodes.iter() + .filter(|n| { + n.input.as_ref().is_some_and(|input| input.edit.masking() == crate::edit::Masking::Shown) + || (n.input.is_none() && n.text.as_ref().is_some_and(|t| t.redacted && t.cold.secure_revealed)) + }) + .map(|n| n.id).collect(); + let mut concealed = std::mem::take(&mut scratch.concealed); + concealed.clear(); + let concealing = if !revealed.is_empty() { + concealed.resize(nodes.len(), false); + for (i, n) in nodes.iter().enumerate() { + let hidden_now = n.input.as_ref().is_some_and(|input| input.edit.is_hidden_multiline()) + || (n.input.is_none() && n.text.as_ref().is_some_and(|t| t.redacted && !t.cold.secure_revealed)); + if hidden_now && revealed.contains(&n.id) { + concealed[i] = true; + } + } + mark_ancestors(&nodes, &mut concealed); + concealed.iter().any(|&hidden| hidden) + } else { + false + }; + let instant = tx.commit.snaps() || first || concealing; + // What this commit mounts or unmounts, and rows new to a growth stack, appear and go at + // once when no input caused it (`Tx::unprompted`); what stays keeps its motion. + let cut = instant || tx.unprompted; + if tx.commit.snaps() && !first { self.commit.commit_why |= crate::runtime::CommitWhy::INSTANT; } + // An instant change lands what it changes; motion an earlier change set going keeps on. + let keeps_flights = tx.commit.snaps() && !tx.commit.lands() && !first && !concealing; + self.scene.keep_flights(keeps_flights); + let now = self.t; + if self.host.fit_height && let Some(root) = nodes.first() { self.fit_window(root.local.h, tx, first); } + let mut held = std::mem::take(&mut scratch.held); + let holds = self.motion.landing_holds(&nodes, &self.tree.nodes, self.paint.seen(), &self.scene, !instant && !tx.relayout && !tx.window_step, self.reduced_motion, &mut held); + + // What drew nothing last frame has no exit to show (`unseen_presence.rs`). + let any_gone = self.tree.nodes.iter().any(|o| !self.tree.node_index.contains_key(&o.id)); + let any_replaced = self.commit.virtuals.values().any(crate::el::virtual_list::VirtualList::replaced_view); + let drew_nothing = if any_gone || any_replaced { self.drew_nothing() } else { Vec::new() }; + let unseen_ids: HashSet<NodeId> = if self.commit.virtuals.is_empty() || drew_nothing.is_empty() { HashSet::default() } else { + self.tree.nodes.iter().zip(&drew_nothing).filter(|&(_, &u)| u).map(|(n, _)| n.id).collect() + }; + + let mut live_by_id = HashMap::default(); + // Growth stacks: rows of a stack that existed before grow; a new stack mounts settled. + if let Some(start) = nodes.iter().position(|n| n.cold.get().is_some_and(|nd| nd.growth.is_some())) { + self.apply_growth_stacks( + start, &nodes, &taffy, tx, &mut scratch, &held, &unseen_ids, + first, concealing, instant, cut, now, scale, &mut live_by_id, + ); + } + + // Put nodes on their subtree's clock before this commit animates them. + let time_scaled = self.motion.time_scaled() || nodes.iter().any(|n| n.time_scale != 1.0); + let mut time_scales = std::mem::take(&mut scratch.time_scales); + time_scales.clear(); + if time_scaled { self.motion.sync_time_scales(&mut self.scene, &nodes, &mut time_scales, false); } + + let can_skip_apply = !first && !tx.commit.lands() && !concealing && reduced_motion_unchanged && !self.scene.tracing(); + let mut skip_spans = std::mem::take(&mut self.commit.memo.skip_scratch); + self.commit.clean_apply_spans(&self.tree, &self.scene, &self.motion, &nodes, &memo_reused, can_skip_apply, |i| self.reorder_jump(&nodes, i), &mut skip_spans); + let unseen = self.unseen_before_and_after(&nodes, &skip_spans); + // `El::matched` elements of this tree: (id, index, newly mounted). + let mut arrivals = std::mem::take(&mut scratch.arrivals); + arrivals.clear(); + let mut mounted = std::mem::take(&mut scratch.mounted); + mounted.clear(); + // A flight this commit would re-aim that has as good as landed lands instead and rides + // its parent, rather than set off again on a path that doesn't. + let landing = if self.motion.flying.is_empty() { Vec::new() } else { self.motion.landing_flights(&self.scene, self.env.scale) }; + let mut landed = false; + // Nodes this commit slid from where they were drawn, or under an ancestor that slid. + let mut slid = std::mem::take(&mut scratch.slid); + slid.clear(); + // How far the top of each node's contents moved down in its growth row (drawn less new). + let mut top_moved = std::mem::take(&mut scratch.top_moved); + top_moved.clear(); + let has_virtuals = !self.commit.virtuals.is_empty(); + let mut last = paint_tracks::Finder::default(); + let mut skip_cursor = 0usize; + // A crossing carries its paint and exits; a resizing row carries its inset. Its + // stationary neighbour only rounds a changed corner, not its opacity or contents. + let mut live_row = None; + let mut exit_parents = HashSet::default(); + let mut i = 0usize; + while i < nodes.len() { + while skip_cursor < skip_spans.len() && skip_spans[skip_cursor].new_start + skip_spans[skip_cursor].len <= i { + skip_cursor += 1; + } + if let Some(span) = skip_spans.get(skip_cursor).filter(|s| s.new_start == i) { + for k in 0..span.len { + nodes[span.new_start + k].scale_track = self.tree.nodes[span.old_start + k].scale_track; + } + last.advance(span.old_start + span.len); + i += span.len; + continue; + } + let cur_i = i; + i += 1; + let i = cur_i; + if live_row.is_some_and(|(root, _)| nodes[i].parent.is_none_or(|p| p < root)) { live_row = None; } + let id = nodes[i].id; + let mut scene_rect = nodes[i].local; + let parent_virtual = if has_virtuals { + nodes[i].parent.and_then(|p| self.commit.virtuals.get(&nodes[p].path)) + } else { + None + }; + if let Some(v) = parent_virtual { + scene_rect.y -= v.before; + } + if !live_by_id.is_empty() && let Some(&row) = live_by_id.get(&id) { live_row = Some((i, row)); } + let shift = live_row.and_then(|(_, row)| row.shift); + let riding = live_row.is_some_and(|(_, row)| row.ink && row.shift.is_some_and(|jump| jump != 0.0)) && !nodes[i].instant_changes; + if riding && nodes[i].vis.child_exit.is_some() { exit_parents.insert(id); } + let old = last.find(&self.tree.nodes, id); + if can_skip_apply + && slid.is_empty() + && top_moved.is_empty() + && paint_tracks::unchanged_node_resting(&self.tree, &self.scene, &self.motion, &nodes, i, old, scene_rect, parent_virtual, || self.reorder_jump(&nodes, i)) + { + continue; + } + let is_virtual = has_virtuals && self.commit.virtuals.contains_key(&nodes[i].path); + let parent_id = nodes[i].parent.map(|p| nodes[p].id); + let (spring_l, anim_l) = tx.motion.map_or_else( + || { let spring = nodes[i].motion; (spring, spring.into()) }, + |m| (m.spring(), m.anim()), + ); + let spring_c = tx.color_motion.unwrap_or(nodes[i].motion); + // Text leads its background so theme crossfades never dip through zero contrast; a + // colour change asked to land at once lands at once on text too. + let spring_tc = if spring_c == Spring::NONE { spring_c } else { Spring::new((spring_c.duration * 0.5).max(0.1), spring_c.bounce) }; + let row_like = nodes[i].in_row == RowLayout::Snaps || nodes[i].parent.is_some_and(|p| nodes[p].growth.is_some()); + // An `El::instant_changes` element lands its changes, and those of what it holds; + // its own entrance and exit, and colours, stay with the commit, as do the entrances of + // an `El::animated_changes` subtree inside it. + let enters_at_once = cut || (nodes[i].parent.is_some_and(|p| nodes[p].instant_changes) && nodes[i].instant_changes); + let lands = instant || nodes[i].instant_changes; + let layout_instant = lands || row_like || tx.relayout || is_virtual + || (!self.tree.aspect_snap.is_empty() && self.tree.aspect_snap.contains(&id)); + + let was_present = self.scene.contains(id); + let was_exiting = self.is_exiting(id); + if was_present && !was_exiting && !enters_at_once && !unseen_ids.is_empty() { self.reenter_unseen_row(&nodes, i, &unseen_ids); } + if let Some((key, _)) = &nodes[i].matched { + arrivals.push((key.clone(), i, !was_present || was_exiting)); + } + if !was_present || was_exiting { + // Presence belongs to the transition. Layout tuning must not replace + // the caller's enter/exit springs when this node mounts or revives. + let tr = nodes[i].transition.as_deref().copied().unwrap_or_else(Transition::opacity); + // Revive presence first, then let this transaction own the layout retarget. + // Scene::insert otherwise starts its default .4 s reflow before our .25 s + // menu curve; the equal target makes the intended retarget a no-op. + let mount_rect = if was_exiting { + self.scene.store().target(id, prop::FRAME).unwrap_or(scene_rect) + } else { scene_rect }; + let mut spec = NodeSpec::new(mount_rect) + .opacity(nodes[i].vis.opacity) + .radius(Corners(nodes[i].vis.radii())) + .transition(tr); + if let Some(pid) = parent_id { + spec = spec.parent(pid); + } + // Growth carries a row's entrance; an explicit transition adds to it. Under + // `animate_layout`, contents new to a row already in place enter on their own. + if !was_present { + if mounted.is_empty() { mounted.resize(nodes.len(), false); } + mounted[i] = true; + } + let rides_row = row_like || (nodes[i].in_row == RowLayout::Horizontal && nodes[i].parent.is_some_and(|p| mounted.get(p).copied().unwrap_or(false))); + let quiet_row = rides_row + && nodes[i].transition.as_ref().is_none_or(|t| t.insertion == rune_motion::Effect::IDENTITY) + && !was_exiting + && !self.reduced_motion; + let mount = if enters_at_once || nodes[i].virtual_mount || quiet_row || self.enters_unseen(&nodes, &unseen, i) { Mount::Initial } else { Mount::Animated }; + self.scene.insert_delayed(id, spec, mount, nodes[i].vis.enter_delay); + } else if tx.commit.lands() { self.scene.land_waiting(id); } + self.scene.set_ride_trailing(id, nodes[i].vis_flags.ride_trailing()); + // How far a growth or virtual row's place jumps in this commit (drawn minus new). + let (mut row_jump, mut reorder_jump) = (0.0, 0.0); + if was_present && !was_exiting && !lands + && landing.contains(&id) + && self.motion.flying.iter().any(|f| f.0 == id && (f.1 != nodes[i].local || nodes[i].parent.is_some_and(|p| slid.get(p).copied().unwrap_or(false)))) + { + self.motion.land_flight(&mut self.scene, id); + landed = true; + } + if was_present { + // As in SwiftUI, a node leaves with the transition of its last render. + if !was_exiting { + self.scene.set_transition(id, nodes[i].transition.as_deref().copied().unwrap_or_else(Transition::opacity)); + } + let stack_row = nodes[i].parent.is_some_and(|p| nodes[p].growth.is_some()) || is_virtual + || (nodes[i].in_row == RowLayout::Horizontal && (self.tree.aspect_snap.is_empty() || !self.tree.aspect_snap.contains(&id))); + // A window's own resize step moves content at rest with the window; motion + // already running retargets on its spring. + let follows_window = tx.window_step && !self.motion.flying.iter().any(|f| f.0 == id) + && !self.scene.store().is_animating(id, prop::FRAME); + // Out of sight before and after: nobody would see it move. + let out_of_sight = unseen.get(i).copied().unwrap_or(false) && nodes[i].matched.is_none() + && !self.motion.flying.iter().any(|f| f.0 == id); + if !out_of_sight && !nodes[i].instant_changes && live_row.is_some_and(|(root, _)| root == i) { + reorder_jump = shift.unwrap_or(0.0); + } + let layout_anim = if out_of_sight || held.get(i).copied().unwrap_or(false) { + LayoutAnim::INSTANT + } else if stack_row && !lands && !tx.relayout && !follows_window { + // Growth and virtual windows own a row's vertical place; its horizontal place + // still springs, or a re-centred column jumps against its moving parent. So + // do `animate_layout` contents inside the row. + // A flying row's path restarts from where it is drawn, with no slide on top. + if !self.motion.flying.iter().any(|f| f.0 == id) { + if let Some(drawn) = self.scene.get(id, prop::FRAME) { row_jump = drawn.y - scene_rect.y; } + reorder_jump = self.reorder_jump(&nodes, i); + } + let mut la = LayoutAnim::axes(anim_l, Anim::INSTANT); + if tx.motion.is_none() && nodes[i].width_leads { + la = la.width_leads(); + } + la + } else if layout_instant || follows_window { + LayoutAnim::INSTANT + } else { + let mut la = LayoutAnim::new(anim_l); + if tx.motion.is_none() { + if let Some((lead, trail)) = nodes[i].lead { + la = la.lead(lead, trail); + } else if nodes[i].width_leads { + la = la.width_leads(); + } + } + la + }; + // An instant change that leaves a flying node's own layout as it was (a click + // placing a caret elsewhere, say) keeps its flight on its path, as it keeps + // other motion an earlier change set going. + let flying = if self.motion.flying.is_empty() { None } + else if lands { self.motion.flying.iter().position(|f| f.0 == id && f.1 == nodes[i].local).filter(|_| keeps_flights && !nodes[i].instant_changes) } + else { self.motion.flying.iter().position(|f| f.0 == id) }; + // A growth row lays out its contents at once. When the top of a parent's contents + // moves in it (a padding, gap or margin above its first child changed), they all + // slide from where they were drawn; a sibling's new size still moves the ones + // under it at once, as the row's growth reveals it. + if nodes[i].in_row == RowLayout::Snaps && !stack_row && (!lands || (shift.is_some() && !nodes[i].instant_changes)) && !tx.relayout && !follows_window && !out_of_sight + && let Some(p) = nodes[i].parent + { + if i == p + 1 && flying.is_none() && let Some(drawn) = self.scene.get(id, prop::FRAME) { + let dy = drawn.y - scene_rect.y; + if dy.abs() > 1.0 / 64.0 { + if top_moved.is_empty() { top_moved.resize(nodes.len(), 0.0); } + top_moved[p] = dy; + } + } + let tm = top_moved.get(p).copied().unwrap_or(0.0); + if tm.abs() > 1.0 / 64.0 && flying.is_none() { + let left = self.motion.slide_with_row(&nodes, p, id, tm); + (row_jump, reorder_jump) = (left, left); + // Sliding with its row, it still slid: a flight under it lands or re-aims. + if left == 0.0 { + if slid.is_empty() { slid.resize(nodes.len(), false); } + slid[i] = true; + } + } + } + if let Some(f) = flying { + // Keep a matched flight on its one screen path, even where a growth row + // owns its place; retarget it only if its layout moved, or an ancestor's + // under a slide its path doesn't ride, so an unrelated commit doesn't re-time it. + if self.motion.flying[f].1 != nodes[i].local || nodes[i].parent.is_some_and(|p| slid.get(p).copied().unwrap_or(false)) { + self.motion.flying[f].1 = nodes[i].local; + // A growth row's instant vertical place would land the whole flight. + let la = if layout_anim.x == Anim::INSTANT || layout_anim.y == Anim::INSTANT { LayoutAnim::new(spring_l) } else { layout_anim }; + let [drawn, speed] = self.motion.launches_mut().restart(&self.scene, id); + self.scene.retarget_drawn(id, scene_rect, la.screen(), drawn, speed); + } + } else if !nodes[i].live.iter().any(|b| b.property == crate::live::Property::Rect) { + // Springing to a new place, it slides from where it was drawn: a flight + // under it, headed for its target, lands or re-aims. + let was = self.scene.store().target(id, prop::FRAME).or_else(|| self.scene.get(id, prop::FRAME)); + if was.is_some_and(|r| (layout_anim.x != Anim::INSTANT && r.x != scene_rect.x) || (layout_anim.y != Anim::INSTANT && r.y != scene_rect.y)) { + if slid.is_empty() { slid.resize(nodes.len(), false); } + slid[i] = true; + } + self.scene.set_frame(id, scene_rect, layout_anim); + } + let quiet = (lands && !riding) || out_of_sight; + let joins = live_row.is_some_and(|(_, row)| row.joins) && !nodes[i].instant_changes; + self.set_or_anim(id, prop::RADIUS, Corners(nodes[i].vis.radii()), spring_l, (lands && !riding && !joins) || out_of_sight); + if nodes[i].live.iter().any(|b| b.property == crate::live::Property::Opacity) { + // The live source owns this property, including across unrelated commits. + } else if !quiet && let Some(&anim) = nodes[i].opacity_motion.as_deref() { + // Only a new target: an anim with its own velocity would restart each commit, + // and would run on an element that mounted where it rests. + let rest = self.scene.store().target(id, prop::OPACITY).or_else(|| self.scene.get(id, prop::OPACITY)); + if rest != Some(nodes[i].vis.opacity) { + self.scene.animate(id, prop::OPACITY, nodes[i].vis.opacity, anim); + } + } else { + self.set_or_anim(id, prop::OPACITY, nodes[i].vis.opacity, spring_l, quiet); + } + } + let rest_quiet = (lands && !riding) || !was_present || was_exiting || self.reduced_motion; + let shift = nodes[i].vis.offset; + if !slid.is_empty() && nodes[i].parent.is_some_and(|p| slid[p]) { slid[i] = true; } + if nodes[i].looping.is_none() && !nodes[i].live.iter().any(|b| b.property == crate::live::Property::Offset) + && (shift != [0.0; 2] || reorder_jump != 0.0 || self.scene.store().has(id, prop::OFFSET)) + { + let to = rune_motion::Vec2::new(shift[0], shift[1]); + if rest_quiet && reorder_jump == 0.0 { + self.scene.set(id, prop::OFFSET, to); + } else if self.scene.store().target(id, prop::OFFSET).unwrap_or(rune_motion::Vec2::ZERO) != to { + if row_jump != 0.0 { + // The row starts from where it was drawn: a reordered row that drops its + // offset slides into its new place. + let now = self.scene.get(id, prop::OFFSET).unwrap_or(rune_motion::Vec2::ZERO); + self.scene.set(id, prop::OFFSET, rune_motion::Vec2::new(now.x, now.y + row_jump)); + if slid.is_empty() { slid.resize(nodes.len(), false); } + slid[i] = true; + } + self.scene.animate(id, prop::OFFSET, to, nodes[i].vis.offset_motion.as_deref().copied().unwrap_or_else(|| spring_l.into())); + } else if reorder_jump != 0.0 { + self.slide_reordered(id, reorder_jump, to, anim_l); + if slid.is_empty() { slid.resize(nodes.len(), false); } + slid[i] = true; + } + } + // Held at its landing width, it starts where its anchor child was drawn. + if let Some(&(_, dx)) = holds.iter().find(|h| h.0 == i) + && nodes[i].looping.is_none() + && !nodes[i].live.iter().any(|b| b.property == crate::live::Property::Offset) + { + let now = self.scene.get(id, prop::OFFSET).unwrap_or(rune_motion::Vec2::ZERO); + self.scene.set(id, prop::OFFSET, rune_motion::Vec2::new(now.x + dx, now.y)); + self.scene.animate(id, prop::OFFSET, rune_motion::Vec2::new(shift[0], shift[1]), nodes[i].vis.offset_motion.as_deref().copied().unwrap_or_else(|| spring_l.into())); + if slid.is_empty() { slid.resize(nodes.len(), false); } + slid[i] = true; + } + nodes[i].group_fade = set_group_rest(&mut self.scene, id, nodes[i].vis.group_opacity, nodes[i].opacity_motion.as_deref().copied(), spring_l, rest_quiet); + let k = nodes[i].static_scale; + nodes[i].scale_track = k != 1.0 || self.scene.store().has(id, P_SCALE); + if nodes[i].scale_track { + self.snap_or_animate(id, P_SCALE, k, rest_quiet, 1.0, nodes[i].vis.scale_motion.as_deref().copied(), spring_l); + } + let turn = nodes[i].vis.rotate; + if turn != 0.0 || self.scene.store().has(id, prop::ROTATION) { + self.snap_or_animate(id, prop::ROTATION, turn, rest_quiet, 0.0, nodes[i].vis.rotate_motion.as_deref().copied(), spring_l); + } + let (instant, vis) = ((instant && !riding) || self.enters_unseen(&nodes, &unseen, i), &nodes[i].vis); + if !nodes[i].live.iter().any(|b| b.property == crate::live::Property::Blur) + && (vis.blur != 0.0 || self.scene.store().has(id, prop::BLUR)) + { + if !instant && was_present && let Some(&anim) = vis.blur_motion.as_deref() { + self.scene.animate(id, prop::BLUR, vis.blur, anim); + } else { self.set_or_anim(id, prop::BLUR, vis.blur, spring_l, instant || !was_present); } + } + let live_colors = paint_tracks::live_colors(&nodes[i]); + if !live_colors.fill { + paint_tracks::commit_paint(&mut self.scene, id, P_FILL, paint_tracks::prev_node(&self.tree.nodes, &nodes, old, i).map(|o| o.vis.fill), vis.fill, spring_c, instant); + } + if vis.border_width() > 0.0 { + let had_bottom = self.scene.store().has(id, P_BORDER_BOTTOM); + if vis.border_bottom.is_some() && !had_bottom + && let Some(c) = self.scene.get(id, P_BORDER).or(paint_tracks::prev_node(&self.tree.nodes, &nodes, old, i).map(|o| o.vis.border())) + { + // A solid border's bottom springs into the gradient rather than jumping. + self.scene.set(id, P_BORDER_BOTTOM, c); + } + if !live_colors.border { + paint_tracks::commit_paint(&mut self.scene, id, P_BORDER, paint_tracks::prev_node(&self.tree.nodes, &nodes, old, i).map(|o| o.vis.border()), vis.border(), spring_c, instant); + } + if vis.border_bottom.is_some() || had_bottom { + self.set_or_anim(id, P_BORDER_BOTTOM, vis.border_bottom.unwrap_or(vis.border()), spring_c, instant); + } + } + if !live_colors.text && let Some(c) = paint_tracks::text_color(&nodes[i]) { + paint_tracks::commit_paint(&mut self.scene, id, P_TEXT, paint_tracks::prev_node(&self.tree.nodes, &nodes, old, i).and_then(paint_tracks::text_color), c, spring_tc, instant); + } + if nodes[i].vis.icon.is_some() && (nodes[i].vis.icon_turn != 0.0 || self.scene.store().has(id, P_ICON_TURN)) { + if was_present && !self.scene.store().has(id, P_ICON_TURN) { + self.scene.set(id, P_ICON_TURN, 0.0); + } + self.set_or_anim(id, P_ICON_TURN, nodes[i].vis.icon_turn, spring_l, instant || !was_present); + } + if vis.hover().a > 0.0 || self.scene.store().has(id, P_HOVER_C) { + paint_tracks::commit_paint(&mut self.scene, id, P_HOVER_C, paint_tracks::prev_node(&self.tree.nodes, &nodes, old, i).map(|o| o.vis.hover()), vis.hover(), spring_c, instant); + } + if vis.press().a > 0.0 || self.scene.store().has(id, P_PRESS_C) { + paint_tracks::commit_paint(&mut self.scene, id, P_PRESS_C, paint_tracks::prev_node(&self.tree.nodes, &nodes, old, i).map(|o| o.vis.press()), vis.press(), spring_c, instant); + } + if !vis.cold.is_empty() || paint_tracks::prev_node(&self.tree.nodes, &nodes, old, i).is_some_and(|o| !o.vis.cold.is_empty()) { + paint_tracks::commit_cold_paint(&mut self.scene, &self.tree.nodes, id, vis, old, live_colors, spring_c, spring_l, instant); + } + + // Streaming word reveal. + if let Some(spec) = &nodes[i].text + && spec.reveal >= 0.0 + { + let content = spec.content.as_str(); + let now = if time_scaled { self.scene.store().node_time(id) } else { now }; + let fade = if self.reduced_motion { 0.15 } else { spec.reveal }; + self.motion.commit_reveal(id, content, fade, now, time_scaled, was_present, instant, tx.unprompted, nodes[i].virtual_mount, self.reduced_motion); + } + } + + if !arrivals.is_empty() || self.motion.has_matched() { + self.motion.match_elements(&self.tree, &self.paint, &mut self.scene, &mut self.commit, &nodes, &arrivals, tx, instant, self.reduced_motion); + } + arrivals.clear(); + if self.motion.launches().pending() { + self.motion.launch_elements(&self.tree, &self.paint, &mut self.scene, &nodes, tx, instant, self.env.scale, self.reduced_motion); + } + + // Scroll viewports: a new sticky viewport opens at the end. + for (i, n) in nodes.iter().enumerate() { + if let Some(sp) = n.cold.get().and_then(|c| c.scroll) { + let e = self.scroll.scrolls.entry(n.id).or_insert(ScrollState { mode: if sp.stick_bottom { ScrollMode::following() } else { ScrollMode::rest() }, ..ScrollState::default() }); + e.x.flow = n.flow; + if concealed.get(i).copied().unwrap_or(false) { + e.offset = 0.0; + e.halt(); + e.max = 0.0; + e.held = false; + e.still(); + e.slack = scroll_bottom::Slack::landed(self.viewport); + e.x = AxisScroll::default(); + } + if tx.commit.lands() && sp.stick_bottom { + e.pin(); + } + // A window resize, a settle or an instant change lands the slack: the rows go + // straight to the bottom, not on a glide a moment later. + if tx.commit.lands() || tx.commit.snaps() || e.slack.window != self.viewport { e.slack = scroll_bottom::Slack::landed(self.viewport); } + if tx.follow_edge && sp.stick_bottom && !tx.commit.snaps() { e.slack.follow = true; } + } + } + + // Removed nodes stay mounted in `Scene` until their exit transition settles at opacity 0. + let present_len = nodes.len(); + let mut old_nodes = std::mem::take(&mut self.tree.nodes); + exits::carry_live_bindings(&self.tree.node_index, &mut self.scene, &mut nodes, &old_nodes, tx); + if !any_gone { + old_nodes = apply_scratch::clear_old_nodes(old_nodes, &memo_reused, &mut scratch.moved_spans); + } else { + let mut pruned = Vec::new(); + exits::retire_removed_nodes( + &mut self.tree.node_index, &mut self.scene, &self.motion.flying, &mut self.text, self.env.scale, + &mut nodes, &mut old_nodes, present_len, tx, instant, &drew_nothing, &exit_parents, &mut scratch, &mut pruned, + ); + for old in &pruned { self.hover_pruned(old); } + } + self.tree.spare_nodes = old_nodes; + + if time_scaled { + // Exits keep following their present ancestors' scale, so one under a frozen subtree + // finishes once it resumes. + self.motion.sync_time_scales(&mut self.scene, &nodes, &mut time_scales, true); + self.motion.set_time_scaled(time_scales.iter().any(|&k| k != 1.0)); + } + scratch.concealed = concealed; + scratch.time_scales = time_scales; + scratch.arrivals = arrivals; + scratch.mounted = mounted; + scratch.slid = slid; + scratch.top_moved = top_moved; + scratch.held = held; + self.commit.apply_scratch = scratch; + self.tree.nodes = nodes; + self.commit.memo.commit_flattened(&self.tree.nodes, present_len, memo_flattened, memo_reused, taken_paths); + skip_spans.clear(); + self.commit.memo.skip_scratch = skip_spans; + self.find_app_root(); + self.commit.commit_gen = self.commit.commit_gen.wrapping_add(1); + let any_loop = self.prune_detached_tables(true); + if self.tree.nodes.len() > present_len || !self.motion.flying.is_empty() || landed || self.tree.has_sticky || self.tree.has_raise || self.tree.has_paint_order { self.update_layer_paint_order(); } + else { self.paint.clear_layer_paint_order(); } + self.tree.built = false; + self.subscribe_live(); + self.sync_modals(app); + self.sync_follows(app); + self.motion.sync_loops(&self.tree.nodes, &self.scene, self.t, self.clock, self.time_scale, time_scaled, any_loop, tx.commit.lands() || self.reduced_motion); + taffy.compact_if_sparse(|me, slot| self.tree.nodes[me as usize].taffy = slot); + self.commit.layout = taffy; + self.commit.reuse.built(self.env.scale, self.paint.srgb_blend()); + self.text.end_commit(); + self.commit.dirty = false; + self.commit.relayout = false; + self.tree.aspect_snap.clear(); + self.commit.viewport_stepped = false; + self.commit.settle = false; + // After the commit: a new height changes the insets, which the next frame's view reads. + self.set_titlebar(titlebar); + } + + /// Sets `prop` to `to` when `quiet`, or animates it from `identity` when its target changed. + fn snap_or_animate<T: rune_motion::Animatable + PartialEq>( + &mut self, id: NodeId, prop: Prop<T>, to: T, quiet: bool, identity: T, motion: Option<Anim>, spring: Spring, + ) { + if quiet { + self.scene.set(id, prop, to); + } else if self.scene.store().target(id, prop) != Some(to) { + if !self.scene.store().has(id, prop) { self.scene.set(id, prop, identity); } + self.scene.animate(id, prop, to, motion.unwrap_or_else(|| spring.into())); + } + } +} diff --git a/app/vendor/rune/crates/rune/src/runtime/commit/apply/exits.rs b/app/vendor/rune/crates/rune/src/runtime/commit/apply/exits.rs new file mode 100644 index 0000000..d79fa67 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/commit/apply/exits.rs @@ -0,0 +1,143 @@ +//! Live-binding handoff and retiring/concealing removed nodes during `RuntimeCore::apply`. +use super::*; + +// Kept inlined into `RuntimeCore::apply` so the common path with no live bindings stays a +// tight scan without an extra call frame. +#[inline] +pub(super) fn carry_live_bindings( + node_index: &NodeIndex, + scene: &mut Scene, + nodes: &mut [Node], + old_nodes: &[Node], + tx: &Tx, +) { + // A node reused from the last commit keeps its bindings' latches, which a commit that + // lands drops as a rebuilt node's are (below). + if tx.commit.lands() { + for n in nodes.iter_mut().filter(|n| n.cold.get().is_some_and(|c| !c.live.is_empty())) { + if let Some(cold) = n.cold.get_mut_if_some() { cold.live.iter_mut().for_each(|b| b.seen = None); } + } + } + for old in old_nodes { + if old.cold.get().is_none_or(|c| c.live.is_empty()) { continue; } + if let Some(&i) = node_index.get(&old.id) { + let mut kept = paint_tracks::LiveColors::default(); + if let Some(cold) = nodes[i].cold.get_mut_if_some() { + for bound in &mut cold.live { + if let Some(previous) = old.live.iter().find(|b| b.property == bound.property && Arc::ptr_eq(&b.source, &bound.source)) { + bound.seen = if tx.commit.lands() { None } else { previous.seen }; + kept.add(bound.property); + } + } + } + // A kept colour binding keeps the colour it last latched until it publishes again. + kept.carry(old, &mut nodes[i]); + // Removing a binding restores the normal property, including transform defaults. + for previous in &old.live { + if !nodes[i].live.iter().any(|b| b.property == previous.property) { + match previous.property { + crate::live::Property::Offset => scene.set(old.id, prop::OFFSET, rune_motion::Vec2::ZERO), + crate::live::Property::Scale => scene.set(old.id, prop::SCALE, 1.0), + crate::live::Property::Trim => { scene.store_mut().remove(old.id, P_TRIM); } + _ => {} + } + } + } + } + } +} + +#[allow(clippy::too_many_arguments)] +pub(super) fn retire_removed_nodes( + node_index: &mut NodeIndex, + scene: &mut Scene, + flying: &[(NodeId, MRect)], + text: &mut TextSystem, + scale: f32, + nodes: &mut Vec<Node>, + old_nodes: &mut Vec<Node>, + present_len: usize, + tx: &Tx, + instant: bool, + drew_nothing: &[bool], + exit_parents: &HashSet<NodeId>, + scratch: &mut apply_scratch::ApplyScratch, + pruned: &mut Vec<Node>, +) { + scratch.old_ids.clear(); + scratch.old_ids.extend(old_nodes.iter().map(|n| n.id)); + let old_ids = &scratch.old_ids; + // Only the nodes that left are moved out; the rest drop where they are. + for (oi, mut old) in old_nodes.drain(..).enumerate() { + if old.is_moved_stub() { + std::mem::forget(old); + continue; + } + if node_index.contains_key(&old.id) { + continue; + } + if !scene.contains(old.id) { + pruned.push(old); + continue; + } + let old_parent_id = old.parent.and_then(|p| old_ids.get(p).copied()); + let parent_remained_present = + old_parent_id.is_none_or(|pid| node_index.get(&pid).is_some_and(|&i| i < present_len)); + if parent_remained_present { + let instant = instant || (old.instant_changes && old_parent_id.and_then(|pid| node_index.get(&pid)).is_some_and(|&p| nodes[p].instant_changes)); + let rides_parent = old_parent_id.is_some_and(|p| exit_parents.contains(&p)); + let is_exiting = matches!(scene.phase(old.id), Some(PresencePhase::Exiting { .. })); + if tx.commit.lands() || ((instant || tx.unprompted) && !rides_parent && !is_exiting) || drew_nothing.get(oi).copied().unwrap_or(false) { + scene.unmount(old.id); + } else { + if let Some(t) = old_parent_id.and_then(|pid| node_index.get(&pid)).and_then(|&p| nodes[p].vis.child_exit.as_deref().copied()) { + scene.set_transition(old.id, t); + } + scene.remove(old.id); + } + } else if !tx.commit.lands() && flying.iter().any(|f| f.0 == old.id) { + // A flight paints outside its ancestors, so it can't fade with an exiting one. + scene.remove(old.id); + } + old.parent = old_parent_id.and_then(|pid| node_index.get(&pid).copied()); + if let Some(cold) = old.cold.get_mut_if_some() { cold.live.clear(); } + // Exit visuals outlive their model. Never call an accessor captured by + // a deleted row while normalizing a later focus change. + if let Some(input) = &mut old.input { + let was_revealed = input.edit.masking() == crate::edit::Masking::Shown; + input.access = None; + input.key = None; + input.change = None; + input.edit.focused = false; + input.edit.cancel_composition(); + input.edit.conceal(); + if was_revealed && let Some(spec) = &mut old.text { + spec.replace_content(input.edit.display().0); + if input.edit.is_hidden_multiline() { spec.wrap = false; } + let w = (old.local.w - old.inset[0] - old.inset[2]).max(0.0); + let wrap = spec.wrap.then_some(w * scale); + old.text_layout = Some(TextLayout::Single(text.layout_for_spec(&spec.as_text_input(scale, false), scale, wrap, line_alignment(spec)))); + old.elided = None; + } + } else if let Some(spec) = &mut old.text + && spec.redacted + && spec.cold.secure_revealed + { + spec.conceal(); + let w = (old.local.w - old.inset[0] - old.inset[2]).max(0.0); + let wrap = spec.wrap.then_some(w * scale); + let mut layout = text.layout_for_spec(&spec.as_text_input(scale, false), scale, wrap, line_alignment(spec)); + let mut elided = None; + if spec.truncate && layout.full_width() > w * scale + 0.5 { + let (cut, e) = truncated(text, spec, scale, w * scale); + (layout, elided) = (cut, Some(e)); + } + old.text_layout = Some(TextLayout::Single(layout)); + old.elided = elided; + } + // A resize that laid the tree out again took the text layouts before the view ran. + if old.text_layout.is_none() { relayout::lay_out_text_in_place(text, &mut old, scale); } + node_index.insert(old.id, nodes.len()); + nodes.push(old); + } +} diff --git a/app/vendor/rune/crates/rune/src/runtime/commit/apply/growth.rs b/app/vendor/rune/crates/rune/src/runtime/commit/apply/growth.rs new file mode 100644 index 0000000..63cee0c --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/commit/apply/growth.rs @@ -0,0 +1,252 @@ +//! Growth stack reconciliation during `RuntimeCore::apply`: merging row order, retargeting +//! `GrowTrack`s, closing/reopening folds, reorder jumps and live-growth row tracking. +use super::*; + +impl RuntimeCore { + pub(super) fn apply_growth_stacks( + &mut self, + start: usize, + nodes: &[Node], + taffy: &LayoutEngine, + tx: &Tx, + scratch: &mut apply_scratch::ApplyScratch, + held: &[bool], + unseen_ids: &HashSet<NodeId>, + first: bool, + concealing: bool, + instant: bool, + cut: bool, + now: f64, + scale: f32, + live_by_id: &mut HashMap<NodeId, row_reorder::LiveRow>, + ) { + for c in start..nodes.len() { + if nodes[c].cold.get().is_none_or(|nd| nd.growth.is_none()) { continue } + self.apply_growth_stack( + c, nodes, taffy, tx, scratch, held, unseen_ids, + first, concealing, instant, cut, now, scale, live_by_id, + ); + } + } + + fn apply_growth_stack( + &mut self, + c: usize, + nodes: &[Node], + taffy: &LayoutEngine, + tx: &Tx, + scratch: &mut apply_scratch::ApplyScratch, + held: &[bool], + unseen_ids: &HashSet<NodeId>, + first: bool, + concealing: bool, + instant: bool, + cut: bool, + now: f64, + scale: f32, + live_by_id: &mut HashMap<NodeId, row_reorder::LiveRow>, + ) { + let cid = nodes[c].id; + let instant = instant || nodes[c].instant_changes; + let cut = cut || nodes[c].instant_changes; + // A reader away from the tail is anchored using measured row heights. Land those + // heights with the anchor correction, unless `keep_on_screen` or `scroll_into_view` + // is driving this viewport across the commit. A reveal left from an earlier commit + // keeps only rows already growing on their spring: new rows land, or under a parent + // whose size springs too, the two springs carry them past their slots. + // So does a reveal in this commit for rows new to the stack: rows inserted above an + // anchored first row and revealed at once land whole instead of growing from zero. + let revealing = self.commit.virtuals.get(&nodes[c].path) + .is_some_and(|v| self.scroll.requests.reveals().any(|r| r.viewport == v.scroll_path)); + let revealed_now = self.commit.virtuals.get(&nodes[c].path).is_some_and(|v| { + tx.scroll_to.iter().any(|r| { + nodes.iter().enumerate().find(|(_, n)| n.named(&r.key) + && n.parent.is_none_or(|p| in_scope(&nodes[p].path, r.scope.as_deref()))) + .is_some_and(|(i, _)| { + std::iter::successors(nodes[i].parent, |&p| nodes[p].parent) + .find(|&p| nodes[p].scroll.is_some() && nodes[p].scroll_axes.y()) + .is_some_and(|p| nodes[p].path == v.scroll_path) + }) + }) + }); + let reader = self.commit.virtuals.get(&nodes[c].path) + .filter(|v| !self.scroll.requests.keeps().any(|k| k.viewport == v.scroll_path)) + .and_then(|v| self.tree.path_ids.get(&v.scroll_path)) + .and_then(|id| self.scroll.scrolls.get(id)).is_some_and(|s| !s.pinned()); + let reading = reader && !revealed_now; + scratch.rows.clear(); + scratch.rows.extend((c + 1..nodes.len()).filter(|&j| nodes[j].parent == Some(c))); + let rows = &scratch.rows; + let existed = self.motion.stacks.contains_key(&cid) && !tx.commit.lands(); + let mut stack = self.motion.stacks.remove(&cid).unwrap_or_default(); + scratch.new_ids.clear(); + scratch.new_ids.extend(rows.iter().map(|&j| nodes[j].id)); + let new_ids = &scratch.new_ids; + scratch.new_set.clear(); + scratch.new_set.extend(new_ids.iter().copied()); + let new_set = &scratch.new_set; + // Merge: keep leaving rows where they stood. In a virtual list, a row that drew + // nothing, or any row when the change keeps none the reader could see (a filter), + // leaves no space to close: the list's anchor already holds what shows (`set_keys`), + // and the space would only push the rows the change brings in down, out of view. + let list = self.commit.virtuals.get(&nodes[c].path); + let is_virtual = list.is_some(); + let replaced = list.is_some_and(crate::el::virtual_list::VirtualList::replaced_view); + let (mut opened, mut shut) = (Vec::new(), Vec::new()); + let mut order = std::mem::take(&mut scratch.order); + order.clear(); + order.reserve(new_ids.len() + 4); + let mut ni = 0; + for &old in &stack.order { + if new_set.contains(&old) { + while ni < new_ids.len() && new_ids[ni] != old { + if !order.contains(&new_ids[ni]) { + order.push(new_ids[ni]); + } + ni += 1; + } + if !order.contains(&old) { + order.push(old); + } + ni += 1; + } else if let Some(g) = self.motion.grows.get(&old).filter(|g| g.h > 0.01) && existed && !cut && !replaced && !(is_virtual && unseen_ids.contains(&old)) { + // A row fades in place before its space closes, except a fold, which shuts + // at once on its own spring under its feather, as it would fold shut in place. + let hold = if g.glide().is_some() { 0.0 } else { 0.15 }; + if g.glide().is_some() && !stack.closing.contains_key(&old) { shut.push(old); } + stack.closing.entry(old).or_insert(now + hold); + order.push(old); + } else { + self.motion.grows.remove(&old); + stack.closing.remove(&old); + } + } + for &id in &new_ids[ni.min(new_ids.len())..] { + if !order.contains(&id) { + order.push(id); + } + } + let ctop = nodes[c].target[1]; + let width = nodes[c].local.w; + let revealing_moving = revealing && rows.iter().any(|&j| { + let id = nodes[j].id; + self.motion.grows.get(&id).is_some_and(|g| g.moving()) || stack.pending_heights.contains_key(&id) + }); + // A person resizing the window holds the content: rewrapped rows land in the frame, + // so a pinned tail stays where it is instead of sliding back after the drag. A + // streaming row still waits for the width to settle, then eases. A stack held at its + // landing width (`El::hold_landing_width`) lands its rewrapped rows the same way. + let resized = existed && (stack.window != self.viewport || held.get(c).copied().unwrap_or(false)); + stack.window = self.viewport; + if first || !existed || tx.commit.lands() || self.reduced_motion || (reading && !revealing_moving) { + stack.width_hold = WidthHold::Off; + stack.pending_heights.clear(); + } else if (width - stack.width).abs() > 0.25 { + stack.width_hold = WidthHold::rewrap(now); + } + let live_rows = if existed && !first && !resized && !concealing && !self.reduced_motion && !tx.live_growth.is_empty() && !stack.width_hold.defers(now) { + self.live_tail(nodes, c, tx, &mut stack) + } else { None }; + stack.viewport_height = list.map_or(0.0, |v| v.viewport); + stack.width = width; + stack.pending_heights.retain(|id, _| new_set.contains(id)); + stack.gap = crate::el::virtual_list::gap_y(taffy.style(nodes[c].taffy)); + // With every row gone, the leaving rows still stand below the stack's top padding. + let pad_top = rows.first().map_or(stack.pad_top, |&j| nodes[j].target[1] - ctop); + stack.pad_bottom = rows.last().map_or(nodes[c].target[3] - ctop - pad_top, |&j| nodes[c].target[3] - nodes[j].target[3]); + stack.pad_top = pad_top; + let (mut hidden_cut, mut reopened, mut held_folds) = (0.0, Vec::new(), Vec::new()); + for &j in rows { + let id = nodes[j].id; + let mut h = nodes[j].target[3] - nodes[j].target[1]; + stack.closing.remove(&id); + stack.tops.insert(id, nodes[j].target[1] - ctop); + let streaming = nodes[j].streaming; + let whole = nodes[j].whole && !streaming; + let g_moving = self.motion.grows.get(&id).is_some_and(|g| g.moving()) || stack.pending_heights.contains_key(&id); + let entering = revealed_now && reader && !self.motion.grows.contains_key(&id); + let row_reading = (reading && !(revealing && g_moving)) || entering; + let live = !row_reading && live_rows.as_ref().is_some_and(|range| { + nodes[j].key.as_deref().and_then(|key| list?.index_of(key)).is_some_and(|index| range.contains(&index)) + }); + if streaming && existed && !tx.commit.lands() && !first && !self.reduced_motion && !row_reading { + // Measure the final wrapped text before mutating the growth track. Targets + // retain full layout height; only the presented stack extent lags the fill. + let mut end = j + 1; + while end < nodes.len() && nodes[end].parent.is_some_and(|p| p >= j) { end += 1; } + if let Some(n) = nodes[j..end].iter().rev().find(|n| n.text.as_ref().is_some_and(|t| t.wrap && t.reveal >= 0.0)) + && let Some(laid) = &n.text_layout + { + let width = (n.target[2] - n.target[0] - n.inset[0] - n.inset[2]) * scale; + h = (h - laid.view().stream_height_lag(width, scale)).max(0.0); + } + } + let (duration, glide) = (tx.motion.map_or(0.0, |m| m.spring().duration * 1.15), nodes[j].glide.map(|s| (s, self.fold_limit(id)))); + let hidden = if glide.is_some() { self.fold_hidden_above(nodes, j, h) } else { None }; + if existed && !cut && !nodes[j].virtual_mount && nodes[j].glide.is_some() && !self.motion.grows.contains_key(&id) { opened.push(id); } + let g = self.motion.grows.entry(id).or_insert_with(|| { + if existed && (!cut || live) && !nodes[j].virtual_mount { GrowTrack::settled(0.0).with_duration(duration) } else { GrowTrack::settled(h) } + }); + g.set_kind(streaming, whole, glide); + let snap_change = ((instant && !live) || resized) && !streaming && (h - g.target).abs() > 1e-4; + if tx.commit.lands() || !existed || first || self.reduced_motion || snap_change || row_reading { + *g = g.restarted(h); + stack.pending_heights.remove(&id); + stack.slides.land(id); + } else { + // Only a width/scale rewrap may shrink an active streaming row, including + // when fresh text arrives in the same frame as the resize. + let t = if streaming && !self.commit.relayout && stack.width_hold.may_shrink(now) { h.max(g.h.min(g.target)) } else { h }; + if stack.width_hold.defers(now) { + stack.pending_heights.insert(id, t); + } else { + stack.pending_heights.remove(&id); + if (t - g.target).abs() > 1e-4 { g.duration = duration; g.linear_edge = live; } + let shutting = t < g.target - 1e-4; + // A fold opening again while its contents draw lifted, or opening from + // rest (not one mounting): `ride_from_end` grows it from its bottom where + // its viewport follows its end, and leaves the rest alone. + if t > g.target + 1e-4 && (g.lift() > 0.0 || (g.glide().is_some() && g.target > 1e-4)) { reopened.push((j, g.give.is_some())); } + let before = g.h; + g.retarget(t); + if let Some((above, header)) = hidden.filter(|_| shutting && g.shutting_fold()) { + held_folds.push((id, before - g.h)); + hidden_cut += g.hide_above(above); + self.motion.insert_fold_header(id, header); + } + } + } + } + if !tx.commit.lands() && !first && !self.reduced_motion { self.motion.link_growth_runs(&mut stack, &order, &opened, &shut); } else { stack.runs.clear(); } + if hidden_cut > 0.0 { self.scroll_by_cut(nodes, c, hidden_cut); } + if !held_folds.is_empty() { self.give_way(nodes, c, &std::mem::take(&mut held_folds)); } + for (j, giving) in reopened.drain(..) { self.ride_from_end(nodes, c, j, giving); } + if let Some(&last) = rows.last() + && !self.scene.contains(nodes[last].id) + && let Some(s) = std::iter::successors(nodes[c].parent, |&p| nodes[p].parent) + .find(|&p| nodes[p].scroll.is_some() && nodes[p].scroll_axes.y()) + { + self.scroll.requests.step(requests::Event::NewTail { viewport: &nodes[s].path, key: &nodes[last].path }); + } + stack.growing = !stack.pending_heights.is_empty() + || order.iter().any(|r| self.motion.grows.get(r).is_some_and(|g| g.target > g.h + 1.0 / 128.0)); + stack.moving = stack.growing + || order.iter().any(|r| self.motion.grows.get(r).is_some_and(|g| g.moving())); + // Order holds the rows this commit brought and the ones still closing; no others. + stack.tops.retain(|id, _| new_set.contains(id) || stack.closing.contains_key(id)); + let animates = existed && (!instant || live_rows.is_some()) && !tx.relayout && !self.reduced_motion; + stack.reorder.measure(animates, &stack.order, &order, stack.gap, |id| self.motion.grows.get(&id).map(|g| g.h)); + if first || self.reduced_motion || concealing || resized || reader || nodes[c].instant_changes || tx.commit.lands() || (stack.order != order && live_rows.is_none()) { stack.seams.clear(); } + if let Some(range) = live_rows && let Some(v) = self.commit.virtuals.get(&nodes[c].path) && stack.order != order { + self.join_live_rows(&mut stack, nodes, rows, v, &range); + let ink = tx.live_growth.iter().any(|(key, ink)| *ink && nodes[c].named(key)); + live_by_id.extend(rows.iter().enumerate().filter_map(|(k, &j)| { + let moves = |&n: &usize| stack.reorder.jump(nodes[n].id) != 0.0; + let joins = ink && (rows.get(k.wrapping_sub(1)).is_some_and(moves) || rows.get(k + 1).is_some_and(moves)); + self.live_row(&nodes[j], &stack.reorder, ink, joins, v, &range) + })); + } + scratch.order = std::mem::replace(&mut stack.order, order); + self.motion.stacks.insert(cid, stack); + } +} diff --git a/app/vendor/rune/crates/rune/src/runtime/commit/apply_scratch.rs b/app/vendor/rune/crates/rune/src/runtime/commit/apply_scratch.rs new file mode 100644 index 0000000..48a00d5 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/commit/apply_scratch.rs @@ -0,0 +1,87 @@ +//! Reusable per-commit scratch buffers for `apply` and `prune_exited`, plus fast clearing of the +//! previous commit's `Node` buffer without walking `moved` memo spans. +use super::*; + +#[derive(Default)] +pub(crate) struct ApplyScratch { + pub(in crate::runtime) culled: Vec<bool>, + pub(in crate::runtime) concealed: Vec<bool>, + pub(in crate::runtime) rows: Vec<usize>, + pub(in crate::runtime) new_ids: Vec<NodeId>, + pub(in crate::runtime) new_set: HashSet<NodeId>, + pub(in crate::runtime) order: Vec<NodeId>, + pub(in crate::runtime) time_scales: Vec<f32>, + pub(in crate::runtime) arrivals: Vec<(Rc<str>, usize, bool)>, + pub(in crate::runtime) mounted: Vec<bool>, + pub(in crate::runtime) slid: Vec<bool>, + pub(in crate::runtime) top_moved: Vec<f32>, + /// Per node: held at its landing width this commit (`El::hold_landing_width`). + pub(in crate::runtime) held: Vec<bool>, + pub(in crate::runtime) old_ids: Vec<NodeId>, + pub(in crate::runtime) moved_spans: Vec<(usize, usize)>, + pub(in crate::runtime) remap: Vec<Option<usize>>, +} + +/// Drops the un-moved `Node`s in `old_nodes` and returns the empty `Vec<Node>` allocation for the +/// next commit's `flatten`, skipping `moved` memo spans whose placeholders own nothing. +#[allow(unsafe_code)] +pub(in crate::runtime) fn clear_old_nodes( + mut old_nodes: Vec<Node>, + reused: &[memo_reuse::ReusedSpan], + spans_scratch: &mut Vec<(usize, usize)>, +) -> Vec<Node> { + let len = old_nodes.len(); + if len == 0 { + return old_nodes; + } + spans_scratch.clear(); + spans_scratch.extend(reused.iter().filter(|s| s.moved && s.len > 0).map(|s| (s.old_start, s.len))); + if spans_scratch.is_empty() { + old_nodes.clear(); + return old_nodes; + } + if !spans_scratch.windows(2).all(|w| w[0].0 + w[0].1 <= w[1].0) { + spans_scratch.sort_unstable_by_key(|s| s.0); + } + let ptr = old_nodes.as_mut_ptr(); + // SAFETY: `0..len` was initialized; every slot inside a `moved` span holds a `Node::moved_stub` + // with zero heap allocations or reference counts (asserted in debug builds), and every slot + // outside those spans is dropped once via `drop_in_place` after `set_len(0)` prevents unwinds + // from double-dropping. + unsafe { + old_nodes.set_len(0); + let mut cur = 0usize; + for &(start, slen) in spans_scratch.iter() { + let s = start.min(len); + while cur < s { + std::ptr::drop_in_place(ptr.add(cur)); + cur += 1; + } + let end = (start + slen).min(len); + #[cfg(debug_assertions)] + for k in s..end { + let stub = &*ptr.add(k); + debug_assert!( + stub.is_moved_stub() + && stub.path.capacity() == 0 + && stub.key.is_none() + && stub.text.is_none() + && stub.text_layout.is_none() + && stub.input.is_none() + && stub.focus.is_empty() + && stub.handlers.is_empty() + && stub.cold.is_empty() + && stub.vis.cold.is_empty() + ); + } + if end > cur { + cur = end; + } + } + while cur < len { + std::ptr::drop_in_place(ptr.add(cur)); + cur += 1; + } + } + old_nodes +} diff --git a/app/vendor/rune/crates/rune/src/runtime/commit/device.rs b/app/vendor/rune/crates/rune/src/runtime/commit/device.rs new file mode 100644 index 0000000..409bca7 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/commit/device.rs @@ -0,0 +1,20 @@ +//! CSS boxes whose authored dimensions resolve to whole device pixels at layout time. +use super::*; + +pub(super) fn border(style: &mut CompactStyle, vis: &Visual, scale: f32) { + let sides = vis.border_sides.unwrap_or([vis.border_width(); 4]); + style.set_border(sides.map(|w| crate::runtime::pixel_snap::line_width(w * scale) / scale)); +} + +pub(super) fn disc(style: &mut CompactStyle, [ascent, descent, line]: [f32; 3], scale: f32) { + let a = (ascent * scale).round(); + let two_thirds = (a * 2.0 / 3.0).floor(); + let diameter = ((two_thirds + 1.0) * 0.5).floor(); + let leading = ((line * scale - a - (descent * scale).round()) * 0.5).floor(); + let top = leading + (1.5 * (a - two_thirds)).floor(); + // Blink's outside margin_start = -offset - 8; the drawing starts 1 px into that box. + let end = two_thirds + 7.0 - diameter; + style.set_width(length(diameter / scale)); + style.set_height(length(diameter / scale)); + style.set_absolute_inset(Rect { left: auto(), right: length(end / scale), top: length(top / scale), bottom: auto() }); +} diff --git a/app/vendor/rune/crates/rune/src/runtime/commit/flatten.rs b/app/vendor/rune/crates/rune/src/runtime/commit/flatten.rs new file mode 100644 index 0000000..412e40c --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/commit/flatten.rs @@ -0,0 +1,788 @@ +use std::borrow::Cow; +use crate::el::ElFlags; + +use super::*; + +/// An `aspect_fit` element's first layout: it takes the free space along its parent's main axis +/// and the whole cross side, within its max sizes, as the room its fitted box must fit. Its +/// content never sizes the room: with no max along the main axis it starts from 0 and grows. +pub(in crate::runtime) fn fit_room(own: &CompactStyle, parent_row: bool) -> CompactStyle { + let raw = own.to_style(); + let zero = |d: LengthPercentageAuto| if d.is_auto() { length(0.0) } else { d }; + let main_max = if parent_row { raw.max_size.width } else { raw.max_size.height }; + CompactStyle::from_style(Style { + size: raw.max_size.map(Into::into), + min_size: Size { width: zero(raw.min_size.width), height: zero(raw.min_size.height) }, + flex_grow: 1.0, + flex_shrink: 1.0, + flex_basis: if main_max.is_auto() { length(0.0) } else { auto() }, + align_self: Some(AlignSelf::STRETCH), + aspect_ratio: None, + ..raw + }) +} + +/// The largest box at `ratio` inside `room`, as the fixed size an `aspect_fit` element lays +/// out at once its room is known. +pub(in crate::runtime) fn fitted(ratio: f32, own: &CompactStyle, room: Size<f32>) -> CompactStyle { + let w = room.width.min(room.height * ratio).max(0.0); + CompactStyle::from_style(Style { + size: Size { width: length(w), height: length(w / ratio) }, + flex_grow: 0.0, + flex_shrink: 0.0, + flex_basis: auto(), + aspect_ratio: None, + ..own.to_style() + }) +} + +/// Width over height of the image in `pixels`, or 0 while it's empty. +pub(in crate::runtime) fn pixel_ratio(pixels: &crate::Pixels) -> f32 { + let (w, h) = pixels.size(); + if w > 0 && h > 0 { w as f32 / h as f32 } else { 0.0 } +} + +/// How a picture that takes one side from its image's ratio gets the other. Taffy carries an +/// aspect ratio over from the preferred size before min and max clamp it (`w_full().max_w(176.0)` +/// at 4.4:1 in a 696-point column came out 176 wide yet reserved 158 tall), so a side in points +/// is clamped here first. A percentage under a min or max can't be: that picture measures +/// instead (`Picture::Measured`), its other side from the side it gets, as a browser sizes an +/// image. +fn picture_side(style: &mut CompactStyle) -> Picture { + use taffy::util::MaybeResolve; + let size = style.size(); + let tall = size.height.is_auto(); + let (min, max) = (style.min_size(), style.max_size()); + let (set, min, max) = if tall { (size.width, min.width, max.width) } else { (size.height, min.height, max.height) }; + if min.is_auto() && max.is_auto() { return Picture::Styled; } + let points = |l: LengthPercentageAuto| l.maybe_resolve(None, |_, _| 0.0); + let limits_in_points = (min.is_auto() || points(min).is_some()) && (max.is_auto() || points(max).is_some()); + let Some(v) = set.maybe_resolve(None, |_, _| 0.0).filter(|_| limits_in_points) else { return Picture::Measured }; + let v = points(max).map_or(v, |m| v.min(m)); + let v = points(min).map_or(v, |m| v.max(m)); + let side = taffy::Dimension::length(v); + style.set_size(if tall { Size { width: side, height: size.height } } else { Size { width: size.width, height: side } }); + Picture::Styled +} + +/// How a picture's ratio reaches layout. +#[derive(Clone, Copy, PartialEq, Eq)] +enum Picture { + /// As the style's aspect ratio. + Styled, + /// As its leaf's measure (`text_layout::compute_layout`), keyed by the ratio. + Measured, +} + +/// A measured picture's measure key: its ratio, so a new one measures again. +fn picture_key(ratio: f32) -> u64 { 0x7069_6300_0000_0000 | u64::from(ratio.to_bits()) } + +// Build the owned path directly, without cloning a key or formatting an index into a +// temporary segment first. Measurement and flattening must use the same identity rule. +/// Whether `path` lies inside an element keyed `scope` (always, without one). +pub(crate) fn in_scope(path: &str, scope: Option<&str>) -> bool { + scope.is_none_or(|s| path.split('/').any(|seg| seg == s)) +} + +pub(in crate::runtime) fn node_path(parent: &str, key: Option<&str>, index: usize) -> String { + match (parent.is_empty(), key) { + (true, Some(key)) => key.to_owned(), + (true, None) => format!("#{index}"), + // Sized up front: `format!` guesses short and reallocates every deep path, twice a + // commit per element. + (false, Some(key)) => { + let mut path = String::with_capacity(parent.len() + 1 + key.len()); + path.push_str(parent); + path.push('/'); + path.push_str(key); + path + } + (false, None) => { + use std::fmt::Write; + let mut path = String::with_capacity(parent.len() + 22); + path.push_str(parent); + write!(path, "/#{index}").ok(); + path + } + } +} + +#[inline(always)] +fn push_usize(buf: &mut String, mut n: usize) { + if n < 10 { + buf.push((b'0' + n as u8) as char); + return; + } + let mut digits = [0u8; 20]; + let mut i = digits.len(); + while n > 0 { + i -= 1; + digits[i] = b'0' + (n % 10) as u8; + n /= 10; + } + if let Ok(s) = std::str::from_utf8(&digits[i..]) { + buf.push_str(s); + } +} + +fn push_segment(path: &mut String, key: Option<&str>, index: usize) { + if !path.is_empty() { + path.push('/'); + } + match key { + Some(k) => path.push_str(k), + None => { + path.push('#'); + push_usize(path, index); + } + } +} + +#[inline] +fn can_take_old_path(old: &Node, path_buf: &str) -> bool { + !path_buf.is_empty() + && !old.is_moved_stub() + && old.path == path_buf + && old.input.is_none() + && old.focus.get().is_none_or(|f| f.return_to.is_none()) +} + +#[inline] +fn resolve_path_and_id( + path_buf: &str, + new_idx: usize, + memo_ctx: &mut memo_reuse::MemoFlattenCtx<'_>, +) -> (String, NodeId) { + let old_limit = memo_ctx.old_present_len.min(memo_ctx.old_nodes.len()); + if memo_ctx.committing && memo_ctx.old_cursor < old_limit { + let oi = memo_ctx.old_cursor; + if can_take_old_path(&memo_ctx.old_nodes[oi], path_buf) { + let old = &mut memo_ctx.old_nodes[oi]; + let id = old.id; + let path = std::mem::take(&mut old.path); + memo_ctx.taken_paths.push((oi as u32, new_idx as u32)); + memo_ctx.old_cursor = oi + 1; + return (path, id); + } + } + if let Some(&id) = memo_ctx.path_ids.get(path_buf) { + if memo_ctx.committing + && let Some(&oi) = memo_ctx.old_node_index.get(&id) + && oi < old_limit + && memo_ctx.old_nodes[oi].id == id + && can_take_old_path(&memo_ctx.old_nodes[oi], path_buf) + { + let old = &mut memo_ctx.old_nodes[oi]; + let path = std::mem::take(&mut old.path); + memo_ctx.taken_paths.push((oi as u32, new_idx as u32)); + memo_ctx.old_cursor = oi + 1; + return (path, id); + } + return (path_buf.to_owned(), id); + } + let path = path_buf.to_owned(); + let id = NodeId(*memo_ctx.next_id); + *memo_ctx.next_id += 1; + memo_ctx.path_ids.insert(path.clone(), id); + (path, id) +} + +#[derive(Clone, Copy)] +enum ScrollXChild { + Single { vertical: bool }, + Many { vertical: bool }, +} + +fn apply_scroll_x_child(style: &mut CompactStyle, sx: ScrollXChild) { + match sx { + ScrollXChild::Single { vertical } => unwrapped_width(style, vertical), + ScrollXChild::Many { vertical } => { + let w = style.size().width; + let w_full = w == Dimension::percent(1.0); + if w.is_auto() || w_full { + style.set_width(Dimension::max_content()); + if w_full && style.min_size().width.is_auto() { + style.set_min_width(percent(1.0)); + } + } + style.set_flex_shrink(0.0); + if vertical && style.align_self().is_none() { + style.set_align_self(Some(AlignSelf::FLEX_START)); + } + } + } +} + +fn prepare_text( + text: &mut Option<crate::cold::SharedBox<TextSpec>>, + input: Option<&InputSpec>, + scale: f32, + flow: Option<crate::el::Flow>, +) -> (Option<u64>, bool) { + if let Some(t) = text + && let dir = crate::el::step_text_dir(t.dir, crate::el::TextDirEvent::Flatten(flow)) + // A field Ctrl+Shift set reads that way, every line of it. + && let dir = input.and_then(|i| i.edit.forced_dir()).map_or(dir, crate::el::TextDir::Fixed) + && t.dir != dir + { + t.dir = dir; + t.shape = None; + } + if let Some(t) = text && t.redacted { + // Rich links carry URLs and can expose them through hover, copy and tree children. + use zeroize::Zeroize; + let t: &mut TextSpec = t; + t.selectable = false; + if let Some(cold) = t.cold.get_mut_if_some() { + for link in &mut cold.links { + link.id.zeroize(); + if let Some(label) = &mut link.label { label.zeroize(); } + if let Some(help) = &mut link.help { help.zeroize(); } + } + cold.links.clear(); + cold.rings.clear(); + cold.advance_in = None; + cold.live = None; + } + } + if input.is_some_and(|i| i.edit.is_hidden_multiline()) && let Some(t) = text { + // The fixed mask stays one line even in a field narrower than twelve bullets. + if t.wrap { t.wrap = false; } + } else if input.is_none() + && let Some(t) = text + && t.redacted + { + t.case = None; + if !t.cold.secure_revealed { + t.conceal(); + } + } + if let Some(t) = text && t.cold.live.is_some() { + assert!(input.is_none() && !t.redacted && !t.wrap && t.spans.is_empty() && t.reveal < 0.0 && !t.truncate, + "live_text requires plain single-line text; use truncate_fade for overflow"); + } + if input.is_none() + && text.as_ref().is_some_and(|t| !t.cold.isolates.is_empty() || !t.cold.pills.is_empty()) + && let Some(t) = text + { + t.apply_isolates(); + } + if input.is_none() + && text.as_ref().is_some_and(|t| t.redacted || t.case.is_some() || !t.cold.rings.is_empty()) + && let Some(t) = text + { + t.apply_case(); + } + if text.as_ref().is_some_and(|t| t.redacted || t.shape.is_none_or(|s| s.0 != scale.to_bits())) + && let Some(t) = text + { + t.key_shape(scale); + } + let measure = text.as_ref().map(|t| t.shape.map_or(0, |s| s.1) ^ u64::from(t.wrap) ^ (u64::from(t.truncate || t.truncate_fade) << 1) + ^ ((t.max_lines as u64) << 2) + ^ (u64::from(input.is_some_and(|i| i.edit.is_revealed()) || t.cold.secure_revealed) << 3) + ^ (u64::from(t.wrap_anywhere) << 4) ^ (u64::from(t.greedy) << 5) ^ (u64::from(t.by_line) << 6) + ^ t.cold.advance_in.as_ref().map_or(0, |(run, at)| run.hash.rotate_left(3) ^ (*at as u64).wrapping_mul(0x9e37_79b9_7f4a_7c15))); + // Secure leaves remeasure without retaining a content-derived dictionary oracle. + let secure_measure = text.as_ref().is_some_and(|t| t.redacted); + let measure = if secure_measure { Some(0) } else { measure }; + (measure, secure_measure) +} + +/// Text, an icon, and a text field's placeholder, caret and selection that weren't given a +/// colour take the window's foreground ([`Cx::foreground`]), as CSS text takes `color`. +fn take_foreground( + text: &mut Option<crate::cold::SharedBox<TextSpec>>, + input: Option<&mut InputSpec>, + vis: &mut Visual, + foreground: Option<Color>, +) { + let Some(fg) = foreground else { return }; + if let Some(t) = text && !t.inked && t.color != fg { + t.color = fg; + } + if let Some(i) = input { + if !i.placeholder_inked { + i.placeholder_color = fg.alpha(0.4); + } + if !i.caret_inked { + i.caret = fg; + if i.selection == crate::el::DEFAULT_SELECTION { + i.selection = fg.alpha(0.2); + } + } + } + if !vis.icon_inked && vis.icon.is_some_and(|(_, c)| c != fg) && let Some((_, c)) = &mut vis.cold_mut().icon { + *c = fg; + } +} + +/// The `El::hover_motion_within` pair a node goes by: its own, else its anchor's, else its +/// parent's. +#[inline(always)] +fn inherit_hover_within( + vis: &Visual, + above: Option<&crate::el::Anchor>, + parent: Option<usize>, + nodes: &[Node], +) -> Option<Rc<(Anim, Anim)>> { + if vis.hover_within.is_none() && above.is_none() && parent.is_none_or(|p| nodes[p].hover_within.is_none()) { + return None; + } + inherit_hover_within_slow(vis, above, parent, nodes) +} + +#[inline(never)] +fn inherit_hover_within_slow( + vis: &Visual, + above: Option<&crate::el::Anchor>, + parent: Option<usize>, + nodes: &[Node], +) -> Option<Rc<(Anim, Anim)>> { + vis.hover_within.clone().or_else(|| { + above + .and_then(|a| nodes.iter().position(|n| n.key.as_ref() == Some(&a.key))) + .and_then(|j| nodes[j].hover_within.clone()) + .or_else(|| parent.and_then(|p| nodes[p].hover_within.clone())) + }) +} + +#[inline(always)] +fn needs_node_cold(c: &crate::el::ElCold, meta: &ColdMeta) -> bool { + let base = meta.trace_namespace.is_some() || meta.pixel_aspect.is_some() || meta.aspect_fit.is_some() + || c.label.is_some() || c.help.is_some() || c.transition.is_some() + || !c.live.is_empty() || c.scroll.is_some() || c.matched.is_some() + || c.wheel_scrolls.is_some() + || c.above.is_some() || c.growth.is_some() || c.sticky.is_some() + || c.trace_name.is_some() || c.looping.is_some() || c.opacity_motion.is_some() + || c.lead.is_some() || c.glide.is_some() || c.material.is_some() + || c.help_cut || c.help_side.is_some() || c.help_open + || c.scroll_axes != crate::el::ScrollAxes::Y + || c.scroll_edges != crate::el::ScrollEdges::default() + || c.a11y != crate::el::A11y::default(); + #[cfg(debug_assertions)] + let base = base || c.scroll_source.is_some(); + base +} + +#[inline(always)] +fn node_cold_meta_only(meta: ColdMeta) -> NodeCold { + NodeCold { + trace_name: None, trace_namespace: meta.trace_namespace, label: None, live: Vec::new(), + run_layout: None, live_text_seen: None, looping: None, opacity_motion: None, lead: None, + transition: None, matched: None, above: None, scroll: None, scroll_axes: crate::el::ScrollAxes::Y, + scroll_edges: crate::el::ScrollEdges::default(), wheel_scrolls: None, sticky: None, growth: None, glide: None, + a11y: crate::el::A11y::EMPTY, pixel_aspect: meta.pixel_aspect, aspect_fit: meta.aspect_fit, + material: None, help: None, help_cut: false, help_side: None, help_open: false, + #[cfg(debug_assertions)] + scroll_source: None, + } +} + +#[cold] +#[inline(never)] +fn take_cold_input(cold: &mut crate::cold::Cold<crate::el::ElCold>) -> Option<Box<InputSpec>> { + cold.get_mut_if_some().and_then(|c| c.input.take()) +} + +mod sealed { + pub trait Sealed {} + impl Sealed for super::El {} + impl Sealed for &super::El {} +} + +trait StyleBuf { + fn as_ref(&self) -> &CompactStyle; + fn into_owned(self) -> CompactStyle; +} + +impl StyleBuf for CompactStyle { + #[inline(always)] fn as_ref(&self) -> &CompactStyle { self } + #[inline(always)] fn into_owned(self) -> CompactStyle { self } +} + +impl StyleBuf for Cow<'_, CompactStyle> { + #[inline(always)] fn as_ref(&self) -> &CompactStyle { self } + #[inline(always)] fn into_owned(self) -> CompactStyle { + match self { Cow::Borrowed(s) => s.clone(), Cow::Owned(s) => s } + } +} + +#[derive(Clone, Copy)] +struct ChildEnv { me: usize, motion: Spring, in_row: RowLayout, row: bool, sx: Option<ScrollXChild> } + +struct RefScratch<'a> { + style: Cow<'a, CompactStyle>, + vis: Visual, + text: Option<crate::cold::SharedBox<TextSpec>>, +} + +struct ColdMeta { + trace_namespace: Option<(&'static str, &'static str)>, + mirror: bool, + pixel_aspect: Option<f32>, + aspect_fit: Option<Box<(f32, CompactStyle)>>, +} + +macro_rules! take_field { + (move, $e:expr) => { $e }; + (clone, $e:expr) => { $e.clone() }; +} + +macro_rules! node_cold_from { + ($mode:ident, $c:ident, $m:ident) => {{ + let mut above = take_field!($mode, $c.above); + if $m.mirror && let Some(a) = &mut above { crate::el::mirror_anchor(a); } + let matched = take_field!($mode, $c.matched).map(|id| (id, $c.motion)); + let help_side = if $m.mirror { $c.help_side.map(crate::el::mirror_side) } else { $c.help_side }; + NodeCold { + trace_name: $c.trace_name, trace_namespace: $m.trace_namespace, + label: take_field!($mode, $c.label), live: take_field!($mode, $c.live), + run_layout: None, live_text_seen: None, + looping: take_field!($mode, $c.looping), opacity_motion: take_field!($mode, $c.opacity_motion), + lead: $c.lead, transition: take_field!($mode, $c.transition), matched, above, + scroll: $c.scroll, scroll_axes: $c.scroll_axes, scroll_edges: $c.scroll_edges, + wheel_scrolls: take_field!($mode, $c.wheel_scrolls), + sticky: take_field!($mode, $c.sticky), growth: take_field!($mode, $c.growth), + glide: $c.glide, a11y: take_field!($mode, $c.a11y), + pixel_aspect: $m.pixel_aspect, aspect_fit: $m.aspect_fit, material: $c.material, + help: take_field!($mode, $c.help), help_cut: $c.help_cut, help_side, help_open: $c.help_open, + #[cfg(debug_assertions)] + scroll_source: $c.scroll_source, + } + }}; +} + +#[inline(never)] +fn pack_cold_owned(cold: crate::cold::Cold<crate::el::ElCold>, meta: ColdMeta) -> crate::cold::Cold<NodeCold> { + let Some(c_ref) = cold.get() else { return crate::cold::Cold::from_owned(node_cold_meta_only(meta)); }; + if !needs_node_cold(c_ref, &meta) { return crate::cold::Cold::default(); } + let c = cold.into_owned(); + crate::cold::Cold::from_owned(node_cold_from!(move, c, meta)) +} + +#[inline(never)] +fn pack_cold_ref(c: Option<&crate::el::ElCold>, meta: ColdMeta) -> crate::cold::Cold<NodeCold> { + let Some(c) = c else { return crate::cold::Cold::from_owned(node_cold_meta_only(meta)); }; + if !needs_node_cold(c, &meta) { return crate::cold::Cold::default(); } + crate::cold::Cold::from_owned(node_cold_from!(clone, c, meta)) +} + +type FinishedWork<S, C, K> = ( + Option<String>, + crate::cold::Cold<crate::el::Handlers>, + Option<crate::cold::SharedBox<TextSpec>>, + Visual, + C, + S, + K, +); + +trait FlattenEl: sealed::Sealed { + type Scratch; + type Style: StyleBuf; + type Cold; + type Children; + + fn as_el(&self) -> &El; + fn new_scratch(&mut self) -> (Self::Scratch, Option<Box<InputSpec>>); + fn style<'a>(&'a self, s: &'a Self::Scratch) -> &'a CompactStyle; + fn style_mut<'a>(&'a mut self, s: &'a mut Self::Scratch) -> &'a mut CompactStyle; + fn replace_style(&mut self, s: &mut Self::Scratch, style: CompactStyle) -> CompactStyle; + fn vis<'a>(&'a self, s: &'a Self::Scratch) -> &'a Visual; + fn vis_mut<'a>(&'a mut self, s: &'a mut Self::Scratch) -> &'a mut Visual; + fn text_mut<'a>(&'a mut self, s: &'a mut Self::Scratch) -> &'a mut Option<crate::cold::SharedBox<TextSpec>>; + fn text_and_vis_mut<'a>(&'a mut self, s: &'a mut Self::Scratch) -> (&'a mut Option<crate::cold::SharedBox<TextSpec>>, &'a mut Visual); + fn style_mut_and_vis<'a>(&'a mut self, s: &'a mut Self::Scratch) -> (&'a mut CompactStyle, &'a Visual); + fn finish(self, s: Self::Scratch) -> FinishedWork<Self::Style, Self::Cold, Self::Children>; + fn cold_is_empty(cold: &Self::Cold) -> bool; + fn pack_cold(cold: Self::Cold, meta: ColdMeta) -> crate::cold::Cold<NodeCold>; + #[allow(clippy::too_many_arguments)] + fn flatten_children( + children: Self::Children, env: ChildEnv, path_buf: &mut String, + taffy: &mut LayoutEngine, nodes: &mut Vec<Node>, scale: f32, + memo_ctx: &mut memo_reuse::MemoFlattenCtx<'_>, + ) -> bool; +} + +impl FlattenEl for El { + type Scratch = (); + type Style = CompactStyle; + type Cold = crate::cold::Cold<crate::el::ElCold>; + type Children = (Option<Rc<crate::memo::Built>>, Vec<El>); + + #[inline(always)] fn as_el(&self) -> &El { self } + #[inline(always)] fn new_scratch(&mut self) -> ((), Option<Box<InputSpec>>) { + // Only a text field's element has to own its cold fields here; a memo placeholder shares them. + let input = if self.cold.input.is_some() { take_cold_input(&mut self.cold) } else { None }; + ((), input) + } + #[inline(always)] fn style<'a>(&'a self, _: &'a ()) -> &'a CompactStyle { &self.style } + #[inline(always)] fn style_mut<'a>(&'a mut self, _: &'a mut ()) -> &'a mut CompactStyle { &mut self.style } + #[inline(always)] fn replace_style(&mut self, _: &mut (), style: CompactStyle) -> CompactStyle { std::mem::replace(&mut self.style, style) } + #[inline(always)] fn vis<'a>(&'a self, _: &'a ()) -> &'a Visual { &self.vis } + #[inline(always)] fn vis_mut<'a>(&'a mut self, _: &'a mut ()) -> &'a mut Visual { &mut self.vis } + #[inline(always)] fn text_mut<'a>(&'a mut self, _: &'a mut ()) -> &'a mut Option<crate::cold::SharedBox<TextSpec>> { &mut self.text } + #[inline(always)] fn text_and_vis_mut<'a>(&'a mut self, _: &'a mut ()) -> (&'a mut Option<crate::cold::SharedBox<TextSpec>>, &'a mut Visual) { (&mut self.text, &mut self.vis) } + #[inline(always)] fn style_mut_and_vis<'a>(&'a mut self, _: &'a mut ()) -> (&'a mut CompactStyle, &'a Visual) { (&mut self.style, &self.vis) } + #[inline(always)] fn finish(self, _: ()) -> FinishedWork<Self::Style, Self::Cold, Self::Children> { + let El { key, handlers, text, vis, cold, style, memo, children, .. } = self; + (key, handlers, text, vis, cold, style, (memo, children)) + } + #[inline(always)] fn cold_is_empty(cold: &Self::Cold) -> bool { cold.is_empty() } + #[inline(always)] fn pack_cold(cold: Self::Cold, meta: ColdMeta) -> crate::cold::Cold<NodeCold> { pack_cold_owned(cold, meta) } + + #[inline(always)] + #[allow(clippy::too_many_arguments)] + fn flatten_children( + (memo, children): Self::Children, env: ChildEnv, path_buf: &mut String, + taffy: &mut LayoutEngine, nodes: &mut Vec<Node>, scale: f32, + memo_ctx: &mut memo_reuse::MemoFlattenCtx<'_>, + ) -> bool { + let mut children_dirty = false; + let shared_len = memo.as_ref().map_or(0, |b| b.children.children.len()); + if let Some(built) = &memo { + for (i, c) in built.children.children.iter().enumerate() { + let (kid, kid_dirty) = flatten_ref(c, Some(env.me), path_buf, i, env.motion, env.in_row, env.row, env.sx, taffy, nodes, scale, memo_ctx); + taffy.push_child(kid); + children_dirty |= kid_dirty; + } + } + for (j, c) in children.into_iter().enumerate() { + let (kid, kid_dirty) = flatten_owned(c, Some(env.me), path_buf, shared_len + j, env.motion, env.in_row, env.row, env.sx, taffy, nodes, scale, memo_ctx); + taffy.push_child(kid); + children_dirty |= kid_dirty; + } + children_dirty + } +} + +impl<'e> FlattenEl for &'e El { + type Scratch = RefScratch<'e>; + type Style = Cow<'e, CompactStyle>; + type Cold = Option<&'e crate::el::ElCold>; + type Children = &'e El; + + #[inline(always)] fn as_el(&self) -> &El { self } + #[inline(always)] fn new_scratch(&mut self) -> (RefScratch<'e>, Option<Box<InputSpec>>) { + let input = self.cold.input.clone(); + (RefScratch { style: Cow::Borrowed(&self.style), vis: self.vis.clone(), text: self.text.clone() }, input) + } + #[inline(always)] fn style<'a>(&'a self, s: &'a RefScratch<'e>) -> &'a CompactStyle { &s.style } + #[inline(always)] fn style_mut<'a>(&'a mut self, s: &'a mut RefScratch<'e>) -> &'a mut CompactStyle { s.style.to_mut() } + #[inline(always)] fn replace_style(&mut self, s: &mut RefScratch<'e>, style: CompactStyle) -> CompactStyle { + std::mem::replace(&mut s.style, Cow::Owned(style)).into_owned() + } + #[inline(always)] fn vis<'a>(&'a self, s: &'a RefScratch<'e>) -> &'a Visual { &s.vis } + #[inline(always)] fn vis_mut<'a>(&'a mut self, s: &'a mut RefScratch<'e>) -> &'a mut Visual { &mut s.vis } + #[inline(always)] fn text_mut<'a>(&'a mut self, s: &'a mut RefScratch<'e>) -> &'a mut Option<crate::cold::SharedBox<TextSpec>> { &mut s.text } + #[inline(always)] fn text_and_vis_mut<'a>(&'a mut self, s: &'a mut RefScratch<'e>) -> (&'a mut Option<crate::cold::SharedBox<TextSpec>>, &'a mut Visual) { (&mut s.text, &mut s.vis) } + #[inline(always)] fn style_mut_and_vis<'a>(&'a mut self, s: &'a mut RefScratch<'e>) -> (&'a mut CompactStyle, &'a Visual) { (s.style.to_mut(), &s.vis) } + #[inline(always)] fn finish(self, s: RefScratch<'e>) -> FinishedWork<Self::Style, Self::Cold, Self::Children> { + (self.key.clone(), self.handlers.clone(), s.text, s.vis, self.cold.get(), s.style, self) + } + #[inline(always)] fn cold_is_empty(cold: &Self::Cold) -> bool { cold.is_none() } + #[inline(always)] fn pack_cold(cold: Self::Cold, meta: ColdMeta) -> crate::cold::Cold<NodeCold> { pack_cold_ref(cold, meta) } + + #[inline(always)] + #[allow(clippy::too_many_arguments)] + fn flatten_children( + el: Self::Children, env: ChildEnv, path_buf: &mut String, + taffy: &mut LayoutEngine, nodes: &mut Vec<Node>, scale: f32, + memo_ctx: &mut memo_reuse::MemoFlattenCtx<'_>, + ) -> bool { + let mut children_dirty = false; + for (i, c) in el.all_children().enumerate() { + let (kid, kid_dirty) = flatten_ref(c, Some(env.me), path_buf, i, env.motion, env.in_row, env.row, env.sx, taffy, nodes, scale, memo_ctx); + taffy.push_child(kid); + children_dirty |= kid_dirty; + } + children_dirty + } +} + +#[allow(clippy::too_many_arguments)] +pub(in crate::runtime) fn flatten_with_buf( + el: El, parent: Option<usize>, path_buf: &mut String, index: usize, motion: Spring, + in_row: RowLayout, + // The parent lays its children out in a row (its main axis is horizontal). + parent_row: bool, + taffy: &mut LayoutEngine, nodes: &mut Vec<Node>, scale: f32, + memo_ctx: &mut memo_reuse::MemoFlattenCtx<'_>, +) -> (SlotId, bool) { + if path_buf.capacity() < path_buf.len() + 128 { path_buf.reserve(128); } + flatten_owned(el, parent, path_buf, index, motion, in_row, parent_row, None, taffy, nodes, scale, memo_ctx) +} + +// Keep both monomorphizations in this module's codegen unit alongside its private helpers +// (`push_segment`, `prepare_text`, `take_foreground`, `inherit_hover_within`, `pack_cold_*`) +// so LLVM retains intra-CGU attributes and layout under `codegen-units = 16, lto = false`. +#[inline(never)] +#[allow(clippy::too_many_arguments)] +fn flatten_owned( + el: El, parent: Option<usize>, path_buf: &mut String, index: usize, motion: Spring, + in_row: RowLayout, parent_row: bool, parent_sx: Option<ScrollXChild>, + taffy: &mut LayoutEngine, nodes: &mut Vec<Node>, scale: f32, + memo_ctx: &mut memo_reuse::MemoFlattenCtx<'_>, +) -> (SlotId, bool) { + flatten_node(el, parent, path_buf, index, motion, in_row, parent_row, parent_sx, taffy, nodes, scale, memo_ctx) +} + +#[inline(never)] +#[allow(clippy::too_many_arguments)] +fn flatten_ref( + el: &El, parent: Option<usize>, path_buf: &mut String, index: usize, motion: Spring, + in_row: RowLayout, parent_row: bool, parent_sx: Option<ScrollXChild>, + taffy: &mut LayoutEngine, nodes: &mut Vec<Node>, scale: f32, + memo_ctx: &mut memo_reuse::MemoFlattenCtx<'_>, +) -> (SlotId, bool) { + flatten_node(el, parent, path_buf, index, motion, in_row, parent_row, parent_sx, taffy, nodes, scale, memo_ctx) +} + +#[inline(always)] +#[allow(clippy::too_many_arguments)] +fn flatten_node<E: FlattenEl>( + mut el: E, parent: Option<usize>, path_buf: &mut String, index: usize, motion: Spring, + in_row: RowLayout, parent_row: bool, parent_sx: Option<ScrollXChild>, + taffy: &mut LayoutEngine, nodes: &mut Vec<Node>, scale: f32, + memo_ctx: &mut memo_reuse::MemoFlattenCtx<'_>, +) -> (SlotId, bool) { + let el_ref = el.as_el(); + if parent_sx.is_none() + && let Some(slot) = memo_reuse::try_reuse_memo(el_ref, parent, path_buf, index, motion, in_row, scale, taffy, nodes, memo_ctx) + { + return (slot, false); + } + let record_built = parent_sx.is_none().then(|| { + let built = el_ref.memo_built().filter(|b| b.reusable && memo_reuse::same_root_el(el_ref, b, false)) + .or_else(|| el_ref.cold.expanded_memo.as_ref().filter(|b| b.reusable && memo_reuse::same_root_el(el_ref, b, true)))?; + let (inherited, hover_within) = memo_reuse::inherited_for(parent, nodes, motion, in_row, scale, memo_ctx.foreground); + Some((built.id, inherited, hover_within)) + }).flatten(); + let prev_len = path_buf.len(); + push_segment(path_buf, el_ref.key.as_deref(), index); + let me = nodes.len(); + let (path, id) = resolve_path_and_id(path_buf, me, memo_ctx); + let motion = el_ref.cold.motion.unwrap_or(motion); + let parent_is_stack = parent.is_some_and(|p| nodes[p].growth.is_some()); + let flags = el_ref.flags; + let animate_layout = flags.has(ElFlags::ANIMATE_LAYOUT); + let in_row = if el_ref.cold.above.is_some() && (animate_layout || in_row == RowLayout::Horizontal) { + RowLayout::Free + } else if animate_layout && in_row == RowLayout::Snaps { + RowLayout::Horizontal + } else { + in_row + }; + let instant_changes = flags.has(ElFlags::INSTANT_CHANGES) || (parent.is_some_and(|p| nodes[p].instant_changes) && !el_ref.cold.animated_changes); + let trace_namespace = el_ref.cold.trace_namespace.or_else(|| parent.and_then(|p| nodes[p].trace_namespace)); + let parent_flow = parent.map_or(crate::el::Flow::Ltr, |p| nodes[p].flow); + let (flow, dir_effect) = crate::el::step_direction(parent_flow, crate::el::DirEvent::of(el_ref)); + let directed = flags.dir().is_some() || parent.is_some_and(|p| nodes[p].directed); + let inert = flags.has(ElFlags::INERT) || parent.is_some_and(|p| nodes[p].inert); + let mirror = dir_effect == crate::el::DirEffect::Mirror; + let (mut s, mut input) = el.new_scratch(); + if let Some(sx) = parent_sx { apply_scroll_x_child(el.style_mut(&mut s), sx); } + let (measure, secure_measure) = { + let text = el.text_mut(&mut s); + if text.is_some() { prepare_text(text, input.as_deref(), scale, directed.then_some(flow)) } else { (None, false) } + }; + if memo_ctx.foreground.is_some() { + let (text_m, vis_m) = el.text_and_vis_mut(&mut s); + take_foreground(text_m, input.as_deref_mut(), vis_m, memo_ctx.foreground); + } + if el.vis(&s).border_layout { + let (style, vis) = el.style_mut_and_vis(&mut s); + device::border(style, vis, scale); + } + if let Some(metrics) = el.as_el().cold.list_disc { device::disc(el.style_mut(&mut s), metrics, scale); } + if mirror { crate::el::mirror_visual(el.vis_mut(&mut s)); } + let hover_within = inherit_hover_within(el.vis(&s), el.as_el().cold.above.as_ref(), parent, nodes); + let pixel_aspect = el.vis(&s).pixels.as_ref() + .filter(|_| { + let st = el.style(&s); + let sz = st.size(); + st.aspect_ratio().is_none() && sz.width.is_auto() != sz.height.is_auto() + }) + .map(pixel_ratio); + let picture = pixel_aspect.filter(|&r| r > 0.0).map(|ratio| (ratio, picture_side(el.style_mut(&mut s)))); + if let Some((ratio, Picture::Styled)) = picture { el.style_mut(&mut s).set_aspect_ratio(Some(ratio)); } + let measure = measure.or(picture.filter(|p| p.1 == Picture::Measured).map(|p| picture_key(p.0))); + let aspect_fit = { + let af = el.as_el().cold.aspect_fit; + (af > 0.0).then(|| { + let room = fit_room(el.style(&s), parent_row); + Box::new((af, el.replace_style(&mut s, room))) + }) + }; + let child_sx = { + let r = el.as_el(); + let c = &*r.cold; + if c.scroll.is_some() && c.scroll_axes.x() { + let scroll_axes = c.scroll_axes; + let total_children = r.memo.as_ref().map_or(0, |b| b.children.children.len()) + r.children.len(); + if total_children == 1 { + el.style_mut(&mut s).set_flex_direction(FlexDirection::Row); + Some(ScrollXChild::Single { vertical: scroll_axes.y() }) + } else { + if !scroll_axes.y() { el.style_mut(&mut s).set_flex_direction(FlexDirection::Row); } + Some(ScrollXChild::Many { vertical: scroll_axes.y() }) + } + } else { + None + } + }; + let el_r = el.as_el(); + let role = el_r.role_name(); + let pin = crate::el::Pin::of(el_r); + let vis_flags = el_r.vis_flags; + let static_scale = el_r.scale; + let time_scale = el_r.cold.time_scale; + let option_as_alt = el_r.cold.option_as_alt; + let focus = el_r.cold.focus.clone(); + let (key, handlers, text, vis, cold, style, children) = el.finish(s); + let cold = if E::cold_is_empty(&cold) && trace_namespace.is_none() && pixel_aspect.is_none() && aspect_fit.is_none() { + crate::cold::Cold::default() + } else { + E::pack_cold(cold, ColdMeta { trace_namespace, mirror, pixel_aspect, aspect_fit }) + }; + nodes.push(Node { + id, path, key, role, parent, taffy: SlotId(0), text, text_layout: None, elided: None, + input, focus, handlers, cold, vis, vis_flags, hover_within, + target: [0.0; 4], local: MRect::ZERO, inset: [0.0; 4], + motion, static_scale, time_scale, in_row, + width_leads: flags.has(ElFlags::WIDTH_LEADS), + instant_changes, + streaming: flags.has(ElFlags::STREAMING), + whole: flags.has(ElFlags::WHOLE), + inert, flow, directed, pin, scale_track: false, group_fade: false, + virtual_mount: flags.has(ElFlags::VIRTUAL_MOUNT), + selection_group: flags.has(ElFlags::SELECTION_GROUP), + window_drag: flags.window_drag(), + ime_cursor: flags.has(ElFlags::IME_CURSOR), + ime_option_as_alt: option_as_alt, + moved_stub: false, + epoch: crate::runtime::paint_keep::next_epoch(), + }); + let child_in_row = match in_row { + RowLayout::Free if parent_is_stack => if animate_layout { RowLayout::Horizontal } else { RowLayout::Snaps }, + r => r, + }; + let row = matches!(style.as_ref().flex_direction(), FlexDirection::Row | FlexDirection::RowReverse); + let child_mark = taffy.begin_children(); + let env = ChildEnv { me, motion, in_row: child_in_row, row, sx: child_sx }; + let children_dirty = E::flatten_children(children, env, path_buf, taffy, nodes, scale, memo_ctx); + path_buf.truncate(prev_len); + let (slot, dirty) = taffy.sync_node(id.0, me as u32, style.into_owned(), measure, secure_measure, child_mark, children_dirty); + nodes[me].taffy = slot; + if let Some((built_id, inherited, hover_within)) = record_built { + memo_ctx.pending.push(memo_reuse::PendingFlat { + built_id, start: me, len: nodes.len() - me, inherited, hover_within, + }); + } + (slot, dirty) +} + +#[cfg(test)] +#[path = "flatten_tests.rs"] +mod flatten_tests; diff --git a/app/vendor/rune/crates/rune/src/runtime/commit/flatten_tests.rs b/app/vendor/rune/crates/rune/src/runtime/commit/flatten_tests.rs new file mode 100644 index 0000000..e0d0f2f --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/commit/flatten_tests.rs @@ -0,0 +1,200 @@ +use super::*; +use crate::{Align, Color, Direction, Env, GrowthSpec, Pixels, Side, TextEdit, TextStyle, col, el, memo, row, text, text_input}; + +fn sample_pixels() -> Pixels { + let px = Pixels::new(); + px.set(4, 2, vec![255; 4 * 2 * 4]); + px +} + +fn sample_tree(edit: &TextEdit, px: &Pixels) -> El { + let hover = Anim::from(Spring::new(0.2, 0.0)); + col().key("root").size(320.0, 240.0) + .trace_namespace("test", "flatten") + .hover_motion_within(hover, hover) + .child( + col().key("stack").w_full().growth(GrowthSpec::default()) + .child(el().key("row-snap").w_full().h(20.0).child(text("snap"))) + .child( + el().key("row-anim").w_full().animate_layout() + .child(text("anim")) + .child(el().key("pop").size(30.0, 12.0).anchored("row-snap", Side::Left, Align::Start, 4.0)), + ), + ) + .child( + row().key("rtl").dir(Direction::Rtl).instant_changes().scale(1.25).time_scale(0.5) + .border(1.0, Color { r: 1.0, g: 0.0, b: 0.0, a: 1.0 }).border_layout().corners([2.0, 4.0, 6.0, 8.0]) + .child(el().key("anchor-target").size(40.0, 20.0).animated_changes().matched("m1").help("tip")) + .child(el().key("rtl-pop").size(24.0, 12.0).anchored("anchor-target", Side::Left, Align::Start, 6.0)) + .child(el().key("inert-box").inert().child(text("muted"))), + ) + .child(el().key("pic-styled").w(40.0).max_w(30.0).pixels(px)) + .child(el().key("pic-measured").w_full().max_w(80.0).pixels(px)) + .child(el().key("fit").w(100.0).h(80.0).aspect_fit(2.0)) + .child(el().key("sx-one").w(120.0).h(30.0).scroll_x().child(el().key("only").w_full().h(20.0))) + .child( + el().key("sx-many").w(120.0).h(30.0).scroll_x() + .child(el().key("a").w_full().h(20.0)) + .child(el().key("b").w(50.0).h(20.0)), + ) + .child(text_input(edit, TextStyle::new(14.0, 400.0)).key("field").w(100.0).h(24.0)) +} + +fn run_flatten<E: FlattenEl>(el: E, foreground: Option<Color>) -> (Vec<Node>, LayoutEngine) { + let mut taffy = LayoutEngine::with_capacity(32); + taffy.begin_commit(); + let mut nodes = Vec::new(); + let mut path_buf = String::new(); + let mut old_nodes = Vec::new(); + let old_index = NodeIndex::default(); + let committed = HashMap::default(); + let mut path_ids = HashMap::default(); + let mut next_id = 1u64; + let mut memo_ctx = memo_reuse::MemoFlattenCtx { + old_nodes: &mut old_nodes, + old_present_len: 0, + old_node_index: &old_index, + old_cursor: 0, + committing: true, + committed: &committed, + pending: Vec::new(), + reused: Vec::new(), + taken_paths: Vec::new(), + path_ids: &mut path_ids, + next_id: &mut next_id, + foreground, + }; + let _ = flatten_node(el, None, &mut path_buf, 0, crate::tok::motion::DEFAULT, RowLayout::Free, true, None, &mut taffy, &mut nodes, 2.0, &mut memo_ctx); + taffy.finish_flatten(); + (nodes, taffy) +} + +fn assert_nodes_match(owned: &[Node], borrowed: &[Node], taffy_owned: Option<&LayoutEngine>, taffy_borrowed: Option<&LayoutEngine>) { + assert_eq!(owned.len(), borrowed.len(), "node count"); + for (i, (a, b)) in owned.iter().zip(borrowed.iter()).enumerate() { + assert_eq!(a.id, b.id, "node {i} id"); + assert_eq!(a.path, b.path, "node {i} path"); + assert_eq!(a.key, b.key, "node {i} key"); + assert_eq!(a.role, b.role, "node {i} role"); + assert_eq!(a.parent, b.parent, "node {i} parent"); + assert_eq!(a.text.as_ref().map(|t| (&t.content, t.color, t.dir, t.shape)), b.text.as_ref().map(|t| (&t.content, t.color, t.dir, t.shape)), "node {i} text"); + assert_eq!(a.input.as_ref().map(|x| (x.placeholder_color, x.caret, x.selection)), b.input.as_ref().map(|x| (x.placeholder_color, x.caret, x.selection)), "node {i} input"); + assert_eq!(a.vis.radii(), b.vis.radii(), "node {i} radii"); + assert_eq!(a.vis.border_width(), b.vis.border_width(), "node {i} border_width"); + assert_eq!(a.vis_flags, b.vis_flags, "node {i} vis_flags"); + assert_eq!(a.hover_within.as_deref(), b.hover_within.as_deref(), "node {i} hover_within"); + assert_eq!(a.motion, b.motion, "node {i} motion"); + assert_eq!(a.static_scale, b.static_scale, "node {i} static_scale"); + assert_eq!(a.time_scale, b.time_scale, "node {i} time_scale"); + assert_eq!(a.in_row, b.in_row, "node {i} in_row"); + assert_eq!(a.width_leads, b.width_leads, "node {i} width_leads"); + assert_eq!(a.instant_changes, b.instant_changes, "node {i} instant_changes"); + assert_eq!(a.streaming, b.streaming, "node {i} streaming"); + assert_eq!(a.whole, b.whole, "node {i} whole"); + assert_eq!(a.inert, b.inert, "node {i} inert"); + assert_eq!(a.flow, b.flow, "node {i} flow"); + assert_eq!(a.directed, b.directed, "node {i} directed"); + assert_eq!(a.pin, b.pin, "node {i} pin"); + assert_eq!(a.ime_option_as_alt, b.ime_option_as_alt, "node {i} ime_option_as_alt"); + assert_eq!(a.cold.is_empty(), b.cold.is_empty(), "node {i} cold empty"); + assert_eq!(a.trace_namespace, b.trace_namespace, "node {i} trace_namespace"); + assert_eq!(a.above.as_ref().map(|x| (&x.key, x.side, x.align, x.gap)), b.above.as_ref().map(|x| (&x.key, x.side, x.align, x.gap)), "node {i} above"); + assert_eq!(a.matched, b.matched, "node {i} matched"); + assert_eq!(a.pixel_aspect, b.pixel_aspect, "node {i} pixel_aspect"); + assert_eq!(a.aspect_fit.as_ref().map(|x| (x.0, &x.1)), b.aspect_fit.as_ref().map(|x| (x.0, &x.1)), "node {i} aspect_fit"); + assert_eq!(a.help, b.help, "node {i} help"); + assert_eq!(a.scroll_axes, b.scroll_axes, "node {i} scroll_axes"); + if let (Some(ta), Some(tb)) = (taffy_owned, taffy_borrowed) { + assert_eq!(ta.style(a.taffy), tb.style(b.taffy), "node {i} style"); + } else { + assert_eq!(a.local, b.local, "node {i} local"); + assert_eq!(a.target, b.target, "node {i} target"); + } + } +} + +#[test] +fn owned_and_borrowed_flatten_produce_identical_nodes() { + let edit = TextEdit::new("hello"); + let px = sample_pixels(); + let tree = sample_tree(&edit, &px); + let fg = Some(Color { r: 0.2, g: 0.4, b: 0.6, a: 1.0 }); + let (borrowed, taffy_borrowed) = run_flatten(&tree, fg); + let (owned, taffy_owned) = run_flatten(tree, fg); + assert_nodes_match(&owned, &borrowed, Some(&taffy_owned), Some(&taffy_borrowed)); + // Verify RTL actually mirrored the anchor on both paths. + let pop = owned.iter().find(|n| n.key.as_deref() == Some("rtl-pop")).unwrap(); + assert_eq!(pop.above.as_ref().unwrap().side, Side::Right); + assert_eq!(pop.above.as_ref().unwrap().align, Align::Start); +} + +#[test] +fn memo_children_and_plain_children_flatten_to_matching_node_tables() { + struct S { + edit: TextEdit, + px: Pixels, + use_memo: bool, + } + fn view(s: &S, cx: &mut Cx<S>) -> El { + cx.foreground(Color { r: 0.2, g: 0.4, b: 0.6, a: 1.0 }); + if s.use_memo { + let extra = el().key("tail").size(20.0, 10.0).child(text("extra")); + memo("root", 1u32, || sample_tree(&s.edit, &s.px)).child(extra) + } else { + sample_tree(&s.edit, &s.px).child(el().key("tail").size(20.0, 10.0).child(text("extra"))) + } + } + let env = Env::new(true, 2.0); + let mut plain = Runtime::new(S { edit: TextEdit::new("hello"), px: sample_pixels(), use_memo: false }, view, (320.0, 240.0), env); + let mut memoed = Runtime::new(S { edit: TextEdit::new("hello"), px: sample_pixels(), use_memo: true }, view, (320.0, 240.0), env); + plain.frame(0.0); + memoed.frame(0.0); + assert_nodes_match(&plain.tree.nodes, &memoed.tree.nodes, None, None); +} + +#[test] +fn cold_packing_handles_el_only_cold_meta_only_and_shared_clones() { + let px = sample_pixels(); + let own_spring = Spring::new(0.15, 0.0); + let tree = col().key("root").size(200.0, 120.0) + // Plain node: empty ElCold, no metadata -> empty NodeCold. + .child(el().key("plain").size(20.0, 20.0)) + // Non-empty ElCold containing only fields that do not live in NodeCold -> still empty NodeCold. + .child(el().key("el-only").size(20.0, 20.0).motion(own_spring).animated_changes().time_scale(0.5).focusable(true).ime_option_as_alt(true)) + // Empty ElCold with pixel_aspect metadata only -> packs NodeCold from metadata alone. + .child(el().key("pic-only").w(40.0).pixels(&px)) + // Matched element with its own motion override -> preserves (id, Some(own_spring)). + .child(el().key("matched-motion").size(20.0, 20.0).motion(own_spring).matched("card").label("Card").help("Open card")); + + let cloned = tree.clone(); + let (borrowed, taffy_borrowed) = run_flatten(&tree, None); + let (owned_shared, taffy_shared) = run_flatten(cloned, None); + let (owned_unique, taffy_unique) = run_flatten(tree, None); + + assert_nodes_match(&owned_shared, &borrowed, Some(&taffy_shared), Some(&taffy_borrowed)); + assert_nodes_match(&owned_unique, &borrowed, Some(&taffy_unique), Some(&taffy_borrowed)); + + fn by_key<'a>(nodes: &'a [Node], k: &str) -> &'a Node { + nodes.iter().find(|n| n.key.as_deref() == Some(k)).unwrap() + } + assert!(by_key(&owned_unique, "plain").cold.is_empty()); + assert!(by_key(&owned_unique, "el-only").cold.is_empty()); + assert_eq!(by_key(&owned_unique, "el-only").motion, own_spring); + assert_eq!(by_key(&owned_unique, "el-only").time_scale, 0.5); + assert!(by_key(&owned_unique, "el-only").ime_option_as_alt); + assert!(!by_key(&owned_unique, "pic-only").cold.is_empty()); + assert_eq!(by_key(&owned_unique, "pic-only").pixel_aspect, Some(2.0)); + let matched = by_key(&owned_unique, "matched-motion"); + assert_eq!(matched.matched.as_ref().map(|(id, m)| (&**id, *m)), Some(("card", Some(own_spring)))); + assert_eq!(matched.label.as_deref(), Some("Card")); + assert_eq!(matched.help.as_deref(), Some("Open card")); +} + +#[test] +fn push_usize_formats_single_and_multi_digit_indices() { + for n in [0usize, 1, 9, 10, 42, 999, 1_234_567, usize::MAX] { + let mut buf = String::from("root/#"); + push_usize(&mut buf, n); + assert_eq!(buf, format!("root/#{n}")); + } +} diff --git a/app/vendor/rune/crates/rune/src/runtime/commit/layout_diagnostics.rs b/app/vendor/rune/crates/rune/src/runtime/commit/layout_diagnostics.rs new file mode 100644 index 0000000..46dbb9b --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/commit/layout_diagnostics.rs @@ -0,0 +1,167 @@ +//! Debug-only layout warnings for mistakes that lay out without error but look broken. +use std::collections::BTreeSet; +use std::sync::Mutex; + +use rune_taffy::prelude::*; + +use super::Node; + +/// A scroll viewport that resolved to 0 pt inside a `.grow()` container while its content has +/// height: `.grow()` sets flex-basis 0, so with no bounded ancestor there is nothing to grow +/// into. Warns once per `.scroll(..)` call site. +static WARNED: Mutex<BTreeSet<String>> = Mutex::new(BTreeSet::new()); + +#[cfg(test)] +thread_local! { + static SCOPED_WARNED: std::cell::RefCell<Option<BTreeSet<String>>> = const { std::cell::RefCell::new(None) }; +} + +fn mark_warned(key: String) -> bool { + #[cfg(test)] + if let Some(inserted) = SCOPED_WARNED.with(|slot| slot.borrow_mut().as_mut().map(|set| set.insert(key.clone()))) { + return inserted; + } + WARNED.lock().unwrap().insert(key) +} + +pub(in crate::runtime) fn collapsed_scrolls(taffy: &LayoutEngine, nodes: &[Node]) { + let height = |i: usize| taffy.box_layout(nodes[i].taffy).h; + let bottom = |i: usize| { + let l = taffy.box_layout(nodes[i].taffy); + l.y + l.h + }; + let grown = |i: usize| { + let s = taffy.style(nodes[i].taffy); + s.flex_grow() > 0.0 && s.flex_basis() == length(0.0) + }; + for (i, n) in nodes.iter().enumerate() { + let s = taffy.style(n.taffy); + if s.whole_rows() && !s.whole_rows_column() && mark_warned(format!("whole-rows-dir:{}", n.path)) { + eprintln!( + "rune: El::whole_rows on {:?} is ignored because its container is not a \ + non-wrapping flex column (Display::Flex, FlexDirection::Column, FlexWrap::NoWrap). (debug builds only)", + n.path, + ); + } + if n.scroll.is_none() { continue; } + let direct = || (i + 1..nodes.len()).take_while(|&j| nodes[j].parent >= Some(i)).filter(|&j| nodes[j].parent == Some(i)); + if n.growth.is_some() { + let site = n.scroll_source.map_or_else(|| n.path.clone(), |s| s.to_string()); + if mark_warned(format!("growth:{site}")) { + eprintln!( + "rune: scroll viewport {:?} (.scroll at {site}) also sets .growth(..); \ + put .growth(..) on a child column inside .scroll(..) so the viewport box \ + does not take the stack's presented height. (debug builds only)", + n.path, + ); + } + } + let mut kids = direct(); + if let Some(g) = kids.find(|&j| nodes[j].growth.is_some()) + && kids.next().is_some() + { + let site = n.scroll_source.map_or_else(|| n.path.clone(), |s| s.to_string()); + if mark_warned(format!("growth-sibling:{site}")) { + eprintln!( + "rune: growth stack {:?} inside scroll viewport {:?} (.scroll at {site}) \ + has sibling elements after it; a growth stack must be the last (or only) \ + child of its scroll viewport so nothing below it overlaps its growing rows. (debug builds only)", + nodes[g].path, n.path, + ); + } + } + if !n.scroll_axes.y() || height(i) >= 0.5 { continue; } + let content = direct().map(bottom).fold(0.0_f32, f32::max); + if content < 0.5 { continue; } + let mut up = Some(i); + let mut collapsed = false; + while let Some(j) = up { + if grown(j) && height(j) < 0.5 { collapsed = true; break; } + up = nodes[j].parent; + } + if !collapsed { continue; } + let site = n.scroll_source.map_or_else(|| n.path.clone(), |s| s.to_string()); + if !mark_warned(site.clone()) { continue; } + eprintln!( + "rune: scroll viewport {:?} (.scroll at {site}) is 0 pt tall inside a .grow() container \ + while its content is {content} pt. .grow() sets flex-basis 0, so it only fills space a \ + bounded parent leaves: bound an ancestor's height (.h(..), .h_full()) or set .min_h(..), \ + and put .min_h(0.0) on nested flex columns. (debug builds only)", + n.path, + ); + } +} + +/// Isolates layout warn-once tracking on the current thread for the duration of a test so +/// warnings emitted by earlier or concurrent tests do not leak into assertions. +#[cfg(test)] +pub(in crate::runtime) struct WarningScope(Option<BTreeSet<String>>); + +#[cfg(test)] +impl Drop for WarningScope { + fn drop(&mut self) { + SCOPED_WARNED.with(|slot| *slot.borrow_mut() = self.0.take()); + } +} + +#[cfg(test)] +pub(in crate::runtime) fn scope() -> WarningScope { + WarningScope(SCOPED_WARNED.with(|slot| slot.borrow_mut().replace(BTreeSet::new()))) +} + +#[cfg(test)] +pub(in crate::runtime) fn warned_at(needle: &str) -> bool { + if let Some(found) = SCOPED_WARNED.with(|slot| slot.borrow().as_ref().map(|set| set.iter().any(|site| site.contains(needle)))) { + return found; + } + WARNED.lock().unwrap().iter().any(|site| site.contains(needle)) +} + +#[cfg(test)] +mod tests { + use crate::{Env, GrowthSpec, Runtime, ScrollSpec, col, el}; + + fn view(bounded: &bool, _: &mut crate::Cx<bool>) -> crate::El { + let list = col().key("list").scroll(ScrollSpec { stick_bottom: false }).grow(1.0) + .child(col().key("rows").child(el().h(400.0))); + let page = col().key("page").child(list); + col().child(if *bounded { page.h_full() } else { page }) + } + + #[test] + fn a_grown_scroll_in_an_auto_height_column_warns_and_keeps_its_layout() { + let _warnings = super::scope(); + for bounded in [true, false] { + let mut rt = Runtime::new(bounded, view, (200.0, 200.0), Env::new(true, 1.0)); + rt.frame(0.0); + let list = rt.elements().into_iter().find(|e| e.key.as_deref() == Some("list")).unwrap(); + assert_eq!(list.rect[3], if bounded { 200.0 } else { 0.0 }, "layout is unchanged"); + assert_eq!(super::warned_at("layout_diagnostics.rs"), !bounded); + } + } + + #[test] + fn warning_scope_isolates_tests_from_prior_process_warnings() { + fn bad_growth_sibling(_: &(), _: &mut crate::Cx<()>) -> crate::El { + col().key("scroll").size(200.0, 200.0).scroll(ScrollSpec { stick_bottom: false }) + .child(col().key("stack").w_full().growth(GrowthSpec::default()).child(el().h(40.0))) + .child(el().key("after").w_full().h(40.0)) + } + // Pollute the process-global set outside any test scope. + let mut prior = Runtime::new((), bad_growth_sibling, (200.0, 200.0), Env::new(true, 1.0)); + prior.frame(0.0); + assert!(super::warned_at("growth-sibling:")); + + { + let _warnings = super::scope(); + assert!(!super::warned_at("growth-sibling:")); + let mut rt = Runtime::new((), bad_growth_sibling, (200.0, 200.0), Env::new(true, 1.0)); + rt.frame(0.0); + assert!(super::warned_at("growth-sibling:")); + } + { + let _warnings = super::scope(); + assert!(!super::warned_at("growth-sibling:")); + } + } +} diff --git a/app/vendor/rune/crates/rune/src/runtime/commit/measure.rs b/app/vendor/rune/crates/rune/src/runtime/commit/measure.rs new file mode 100644 index 0000000..d59fd53 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/commit/measure.rs @@ -0,0 +1,743 @@ +use super::*; +use crate::el::ElFlags; + +pub(in crate::runtime) fn collect_virtual_inputs(el: &El, parent: &str, index: usize, inert: bool, inputs: &mut HashMap<String, Box<InputSpec>>) { + // Most offscreen rows hold no focused field; find that out before building any paths. + if !crate::memo::has_focused_input(el) { + return; + } + let inert = inert || el.flags.has(ElFlags::INERT); + let input = el.cold.input.as_ref().filter(|i| i.edit.focused && i.access.is_some()); + // A memo's shared children are skipped whole when none is a focused field. + let skip = el.memo_children().filter(|m| !m.focused_input).map_or(0, |m| m.children.len()); + if input.is_none() && el.children.is_empty() && skip == el.memo_children().map_or(0, |m| m.children.len()) { + return; + } + let segment = el.key.clone().unwrap_or_else(|| format!("#{index}")); + let path = format!("{parent}/{segment}"); + if let Some(input) = input { + let mut input = input.clone(); + if inert { input.edit.focused = false; } + inputs.insert(path.clone(), input); + } + for (i, child) in el.all_children().enumerate().skip(skip) { + collect_virtual_inputs(child, &path, i, inert, inputs); + } +} + +impl RuntimeCore { + pub(in crate::runtime) fn measure(&mut self, app: &dyn ViewDriver, tx: &Tx) -> Measured { + self.measure_pass(app, tx, true) + } + + pub(in crate::runtime) fn measure_retry(&mut self, app: &dyn ViewDriver, tx: &Tx) -> Measured { + let _blend = crate::theme::scope(self.paint.srgb_blend()); + let _bars = crate::platform::scroll_bars::scope(self.host.scroll_bars.state, self.host.scroll_bars.runtime_id); + let selection = self.selection_by_path(); + let (m, text) = self.measurement(app, true); + Measured { selection, ..m.finish_from(text, tx, 1) } + } + + /// `committing` when the result is applied, so the last commit's text layouts can go. + pub(in crate::runtime) fn measure_pass(&mut self, app: &dyn ViewDriver, tx: &Tx, committing: bool) -> Measured { + let _blend = crate::theme::scope(self.paint.srgb_blend()); + let _bars = crate::platform::scroll_bars::scope(self.host.scroll_bars.state, self.host.scroll_bars.runtime_id); + let selection = self.selection_by_path(); + let (m, text) = self.measurement(app, committing); + Measured { selection, ..m.finish(text, tx) } + } + + pub(in crate::runtime) fn measurement<'a>(&'a mut self, app: &'a dyn ViewDriver, committing: bool) -> (Measurement<'a>, &'a mut TextSystem) { + let hold_windows = self.checking_live_only(); + let m = Measurement { + app, + env: self.env, + viewport: self.viewport, + fit_height: self.host.fit_height, + system_reduced_motion: self.host.system_reduced_motion, + // The window's controls are in its points; the view's are over the zoom. + titlebar_inset: self.host.titlebar_inset / self.host.zoom.k, + chrome: self.host.titlebar.insets.zoomed(self.host.zoom.k), + caption: self.host.titlebar.caption, + system_accent: self.host.system_accent, + system_contrast: self.host.system_contrast, + system_increased_contrast: self.host.system_increased_contrast, + system_scroll_bars: self.host.scroll_bars.state, + reduced_motion: self.reduced_motion, + time_scale: self.time_scale, + zoom: self.host.zoom.k, + defaults: self.commit.defaults.clone(), + titlebar: self.titlebar_set(), + caret: self.edit.caret.clone(), + caret_read: false, + layout_seen: self.commit.layout_seen.rects.clone(), + layout_reads: Vec::new(), + commits: self.commit.commits, + nodes: &mut self.tree.nodes, + committing, + spare_nodes: &mut self.tree.spare_nodes, + layout: &mut self.commit.layout, + node_index: &mut self.tree.node_index, + path_ids: &mut self.tree.path_ids, + memo: &mut self.commit.memo, + next_id: &mut self.tree.next_id, + scrolls: &mut self.scroll.scrolls, + virtuals: &mut self.commit.virtuals, + virtual_culled: &mut self.commit.virtual_culled, + virtual_inputs: &mut self.commit.virtual_inputs, + stats: &mut self.stats, + key_warnings: &mut self.commit.key_warnings, + focused: self.kbd.focus.path(), + state_unchanged: std::mem::take(&mut self.commit.state_unchanged), + pass: Pass::First, + hold_windows, + windowed: HashMap::default(), + kept_lists: Vec::new(), + }; + (m, &mut self.text) + } +} + +impl Measurement<'_> { + pub(in crate::runtime) fn node_id(&mut self, path: &str) -> NodeId { + if let Some(&id) = self.path_ids.get(path) { return id; } + let id = NodeId(*self.next_id); + *self.next_id += 1; + self.path_ids.insert(path.to_owned(), id); + id + } + + /// Finishes all row measurements before scene/growth mutation. Newly measured estimates + /// above the viewport adjust the scroll offset by exactly the same amount. + pub(in crate::runtime) fn measure_virtuals(&mut self, nodes: &[Node], settle: bool) -> bool { + let mut retry = false; + for (path, v) in self.virtuals.iter_mut() { + let Some((ci, _)) = nodes.iter().enumerate().find(|(_, n)| n.path == *path) else { continue }; + for n in nodes.iter().filter(|n| n.parent == Some(ci)) { + v.set_height(n.key.as_deref().unwrap(), n.local.h); + } + let Some((si, scroll)) = nodes.iter().enumerate().find(|(_, n)| n.path == v.scroll_path) else { continue }; + v.viewport = scroll.local.h; + v.top = (nodes[ci].target[1] - scroll.target[1]).max(0.0); + if v.nested { + // What the viewport's content holds under the list, for its window while the + // viewport holds its end. + let bottom = nodes.iter().filter(|n| n.parent == Some(si)).map(|n| n.target[1] + n.local.h).fold(0.0f32, f32::max); + v.tail = (bottom - nodes[ci].target[1] - nodes[ci].local.h).max(0.0); + } + let st = self.scrolls.get_mut(&scroll.id); + let sticky = scroll.scroll.unwrap().stick_bottom; + let held = (settle && sticky) || st.as_ref().map_or(sticky, |s| s.pinned()); + let offset = if let Some(st) = st { + if !held { st.offset = (st.offset + f64::from(v.anchor_delta())).max(0.0); } + st.offset as f32 + } else { 0.0 }; + // Rows that shrank or went leave the offset past the end until scrolling clamps it; + // what shows then is the end. + let (offset, pinned) = v.locate(offset, held); + let offset = offset.min(v.max_offset()); + let end = v.row_end(v.range.end); + let mounted_height = (end - v.before).max(0.0); + // Never present a blank caused by an estimate. Expand and measure again first. + retry |= if pinned { + v.range.start > 0 && mounted_height < v.viewport + } else { + (v.range.start > 0 && offset < v.pad_top + v.before) + || (v.range.end < v.keys.len() && offset + v.viewport > v.pad_top + end) + }; + } + retry + } + + /// Checks the view's keys and builds the virtual windows, index-built rows included. + pub(in crate::runtime) fn build_tree(&mut self, mut root: El, tx: &Tx, force_all: bool) -> El { + // Two siblings with one key would share a layout node, which Taffy panics on. Rename the + // later ones so every build, debug or release, lays out; --tree still lists them. + let duplicates = crate::input::key_diagnostics::repair(&mut root); + match self.key_warnings.as_mut() { + Some(warnings) => *warnings = duplicates.into_iter().map(|d| d.message).collect(), + None => crate::input::key_diagnostics::warn_once(&duplicates), + } + // Index-built rows build here, so memos inside them share the view's cache. A window that + // fits its content lays its root out at its natural height, which nothing bounds. + let bound = if self.fit_height { f32::INFINITY } else { self.viewport.1 }; + self.window_tree(&mut root, "", 0, None, tx, force_all, bound, false, None); + root + } + + /// The app's view, or with the playground attached, the view it composes (the bar, or the + /// playground around its stage). + fn root_view(&self, cx: cx::CxCore) -> (El, cx::CxCore) { + let (root, cx) = self.app.view(cx, self.viewport); + // The Windows caption buttons go over everything the view drew, in a frame around it. + let Some(caption) = &self.caption else { return (root, cx) }; + let symbol = cx.caption_color.unwrap_or(if self.env.system_dark { Color::WHITE } else { Color::BLACK }); + // At the height this run sets (`Cx::titlebar_height`, a zoom's), in this commit: the + // window's frame takes it after, and drawing the old one first would spring the buttons + // to the new one, at launch and on every zoom step. + let height = cx.titlebar.height.or(cx.titlebar.titlebar.map(|t| t.height())).unwrap_or(caption.height); + let caption = crate::titlebar::Caption { height, ..*caption }; + (crate::titlebar::frame(root, &caption, symbol, (self.env.scale, self.zoom), self.fit_height), cx) + } + + /// What a memo scope hashes of the window's controls (`Cx::titlebar_inset`, + /// `Cx::chrome_insets`), so memos that read them rebuild when they change. + pub(in crate::runtime) fn chrome_bits(&self) -> [u32; 4] { + let [leading, trailing, height] = self.chrome.bits(); + [self.titlebar_inset.to_bits(), leading, trailing, height] + } + + pub(in crate::runtime) fn finish(self, text: &mut TextSystem, tx: &Tx) -> Measured { + self.finish_from(text, tx, 0) + } + + pub(in crate::runtime) fn finish_from(mut self, text: &mut TextSystem, tx: &Tx, mut passes: usize) -> Measured { + let (layout, nodes, memo_pending, memo_reused, taken_paths) = loop { + passes += 1; + self.pass = Pass::of(passes); + self.virtual_culled.clear(); + self.virtual_inputs.clear(); + self.windowed.clear(); + // Degenerate zero-height runs fall back to a full measurement instead of + // an unbounded retry loop. Normal transcripts need one pass. + let (layout, mut nodes, pending, mut reused, mut taken) = self.measure_view(text, tx, self.pass.forced()); + if !self.measure_virtuals(&nodes, tx.commit.lands()) { break (layout, nodes, pending, reused, taken); } + memo_reuse::restore_moved_nodes(self.nodes, &mut nodes, &reused, &taken); + nodes.clear(); + *self.spare_nodes = nodes; + reused.clear(); + taken.clear(); + self.memo.pending_scratch = pending; + self.memo.reused_scratch = reused; + self.memo.taken_paths_scratch = taken; + *self.layout = layout; + }; + // Exiting virtual subtrees still use their origin and measured extent while + // fading. Runtime prunes this metadata with the retained scene nodes. + Measured { + layout, + nodes, + reduced_motion: self.reduced_motion, + time_scale: self.time_scale, + zoom: self.zoom, + defaults: self.defaults.clone(), + titlebar: self.titlebar, + caret_read: self.caret_read, + layout_reads: self.layout_reads, + memo_flattened: Some(memo_pending), + memo_reused, + taken_paths, + selection: Vec::new(), + } + } + + /// The last commit's node at `path`. + fn committed_node(&self, path: &str) -> Option<usize> { + // The index can describe a retried pass's nodes rather than the last commit's: check. + let id = *self.path_ids.get(path)?; + let at = self.node_index.get(&id).copied().filter(|&i| self.nodes.get(i).is_some_and(|n| n.id == id)); + at.or_else(|| self.nodes.iter().position(|n| n.path == path)) + } + + /// `bound` is the most `el` can be tall (see [`crate::el::virtual_list::height_bound`]); `scroll` + /// is the scroll viewport `el` is the content of, whether it sticks to the bottom, and its bound. + #[allow(clippy::too_many_arguments)] + fn window_tree(&mut self, el: &mut El, parent: &str, index: usize, scroll: Option<(&str, bool, f32)>, tx: &Tx, force_all: bool, bound: f32, inert: bool, group: Option<&str>) { + if !el.flags.has(ElFlags::HAS_VIRTUAL) { + return; + } + let path = node_path(parent, el.key.as_deref(), index); + // A memo reused whole whose lists mount what the last commit did stays a placeholder, + // so flattening reuses its nodes, rows included. + if self.keeps_windows(el, &path, scroll, tx, force_all, bound) { + return; + } + el.expand_memo(); + let inert = inert || el.flags.has(ElFlags::INERT); + let bound = crate::el::virtual_list::height_bound(&el.style, bound); + if let Some(estimate) = el.cold.virtual_estimate { + let w = match self.windowed.remove(&path) { + Some(w) => w, + None => self.window(el, &path, estimate, scroll, tx, force_all), + }; + let source = el.cold.get_mut_if_some().and_then(|c| c.virtual_rows.take()); + for (i, key) in w.renamed { + el.children[i].key = Some(key); + } + el.style.set_pad_top(w.pad_top); + el.style.set_pad_bottom(w.pad_bottom); + self.populate_virtual_children(el, &path, source, inert, group); + } + let bounds = crate::el::virtual_list::child_bounds(&el.style, el.cold.scroll.is_some(), bound, &el.children); + // A virtual stack windows against the nearest scroll viewport around it, its rows' lists + // included: a list in a row windows against the same viewport (`VirtualList::nested`). + let scroll = match el.cold.scroll { + Some(s) => Some((path.as_str(), s.stick_bottom, bound)), + None => scroll, + }; + let child_group = if el.flags.has(ElFlags::SELECTION_GROUP) { Some(path.as_str()) } else { group }; + for (i, child) in el.children.iter_mut().enumerate() { + if !child.flags.has(ElFlags::HAS_VIRTUAL) { continue; } + let bound = bounds.of(child); + self.window_tree(child, &path, i, scroll, tx, force_all, bound, inert, child_group); + } + } + + /// Picks the rows virtual list `el` at `path` mounts, updating its `VirtualList`, the scroll + /// offset its anchor keeps and the rows it culls. Reads `el` only: the caller applies the + /// padding, the renamed keys and the rows. + fn window(&mut self, el: &El, path: &str, estimate: f32, scroll: Option<(&str, bool, f32)>, tx: &Tx, force_all: bool) -> Window { + assert!(el.cold.growth.is_some(), "`.virtualize(..)` at {path:?} needs `.growth(GrowthSpec)` on the same element"); + let (scroll_path, sticky, scroll_bound) = scroll.expect("virtual stack must be inside a scroll viewport"); + let old_scroll = self.path_ids.get(scroll_path).and_then(|id| self.scrolls.get(id)); + let pinned = (tx.commit.lands() && sticky) || old_scroll.map_or(sticky, |s| s.pinned()); + let mut offset = old_scroll.map_or(0.0, |s| s.offset as f32); + // A new viewport has no height yet: its bound from the tree, else the window's. + let first = if scroll_bound.is_finite() { scroll_bound } else { self.viewport.1 }; + let height = self.committed_node(scroll_path).map_or(first, |i| { + let old = self.nodes[i].local.h; + // A viewport filling the old window follows its new bound on resize. Picking + // rows for the old height first can require running the entire view twice. + if tx.relayout && old == self.nodes[0].local.h { first } else { old } + }); + let padding = |p: LengthPercentage| match p.expand() { + taffy::style::ExpandedLengthPercentage::Length(x) => x, + _ => panic!("virtual stack padding must be in points"), + }; + let list = self.committed_node(path); + // A list in a row of another list windows against that list's viewport too. + let nested = self.virtuals.keys().any(|p| p.starts_with(scroll_path) && path.strip_prefix(p.as_str()).is_some_and(|r| r.starts_with('/'))); + let v = self.virtuals.entry(path.to_owned()).or_default(); + v.set_estimate(if el.style.whole_rows_column() { (estimate + 0.5).floor() } else { estimate }); + v.scroll_path = scroll_path.to_owned(); + // A retry keeps the viewport the last pass measured; `self.nodes` is the last commit's. + if self.pass.trusts_estimates() { v.viewport = height; } + let el_pad = el.style.padding(); + v.pad_top = padding(el_pad.top); + v.pad_bottom = padding(el_pad.bottom); + v.set_gap(crate::el::virtual_list::gap_y(&el.style)); + v.nested = nested; + // The viewport's own pin moves its offset; the list windows where that leaves it. + let held = pinned; + let (list_offset, pinned) = v.locate(offset, held); + offset = list_offset; + let source = el.cold.virtual_rows.as_ref(); + let state = self.app.states_ref(); + if source.is_some() { + assert!(el.children.is_empty(), "`.virtual_rows(..)` at {path:?} builds its own rows; it takes no children"); + } + v.indexed = source.is_some(); + let version = el.cold.virtual_rows_version.filter(|_| source.is_some()); + let same = match source { + Some(rows) => rows.count == v.keys.len() + && (self.state_unchanged || (version.is_some() && version == v.keys_version) || (0..rows.count).all(|i| (rows.key)(state, i) == v.keys[i])), + None => v.same_keys(el.children.iter().map(|c| c.key.as_deref())), + }; + v.keys_version = version; + let mut renamed_children = Vec::new(); + // Most commits keep the same rows; only a change pays for sets of every key. + let anchor = if same { + if pinned || v.passed() { None } else { v.first_visible(offset, |_| true) } + } else { + let mut keys: Vec<_> = match source { + Some(rows) => (0..rows.count).map(|i| (rows.key)(state, i).into_owned()).collect(), + None => el.children.iter().map(|c| c.key.clone().expect("virtual rows require stable keys")).collect(), + }; + // Rows sharing a key would share a height and a node: rename the later ones, as + // the view's siblings are, so the list still lays out. + let renamed = crate::input::key_diagnostics::rename_duplicates(keys.iter_mut()); + if !renamed.is_empty() { + let duplicates: Vec<_> = renamed.iter().map(|(_, key)| { + let key = key.clone(); + let message = format!("duplicate virtual row key {key:?} under {path:?}; give rows unique keys"); + crate::input::key_diagnostics::Duplicate { key, message } + }).collect(); + if source.is_none() { + renamed_children = renamed.iter().map(|(i, _)| (*i, keys[*i].clone())).collect(); + } + match self.key_warnings.as_mut() { + Some(out) => out.extend(duplicates.into_iter().map(|d| d.message)), + None => crate::input::key_diagnostics::warn_once(&duplicates), + } + } + // A reorder keeps each row where it was drawn, by its offset or by sliding it + // (`row_reorder.rs`). Anchoring to the formerly first row as it changes slots + // would scroll the entire list a second time. Inserts/removals still preserve + // the reader's anchor, and so does a reorder that lands at once. + let slides = !tx.commit.snaps() && !tx.commit.lands() && !tx.relayout && !self.reduced_motion; + let reorder = keys.len() == v.keys.len() && keys.iter().all(|key| v.has(key)) + && (slides || list.is_some_and(|list| self.nodes.iter().any(|n| n.vis.offset != [0.0; 2] && n.parent == Some(list)))); + v.set_keys(keys, self.commits, (!pinned && !reorder && !v.passed()).then_some(offset)) + }; + v.anchor = anchor; + let delta = v.anchor_delta(); + offset = (offset + delta).max(0.0); + if let Some(st) = self.path_ids.get(scroll_path).and_then(|id| self.scrolls.get_mut(id)) { + if !held { st.offset = (st.offset + f64::from(delta)).max(0.0); } + } + // Rows new since the last commit spread over frames, unless this pass is a retry to + // fill the viewport or a settle. A list's first showing is all new rows: it mounts + // its viewport and a budget of overscan, and the rest fills over the next frames. + let budget = v.indexed && self.pass.spreads_rows() && !tx.commit.lands(); + let shown = std::mem::take(&mut v.shown); + // A live-only check's commit keeps the rows mounted now while they still cover the + // viewport, as skipping the commit would: re-picking the overscan for a viewport that + // changed since would build rows the handler had nothing to do with. + if self.hold_windows && same && self.pass.spreads_rows() && !force_all && !v.needs_window(offset, pinned) { + v.hold(offset, pinned); + } else { + v.select(offset, pinned, budget.then_some(&shown)); + } + if force_all { v.range = 0..v.keys.len(); v.before = 0.0; v.after = 0.0; } + // Keys are unique, so a key is mounted when its row's index is in the range. + for key in shown.iter().filter(|k| v.index_of(k).is_some_and(|i| !v.range.contains(&i))) { + self.virtual_culled.insert(format!("{path}/{key}")); + } + v.shown = shown; + Window { same, renamed: renamed_children, pad_top: v.pad_top + v.before, pad_bottom: v.pad_bottom + v.after } + } + + /// Whether memo placeholder `el` at `path` can stay one: a region's, flattened by the last + /// commit, whose virtual lists are index-built and mount the rows, at the padding, that commit + /// did (`VirtualList::mounted`), with what their rows read unchanged (`VirtualList::row_reads`) + /// and no focused or selected row built off screen. Its lists are windowed either way, once: + /// when it can't stay, `window_tree` applies these windows to the expanded subtree. + #[allow(clippy::too_many_arguments)] + fn keeps_windows(&mut self, el: &El, path: &str, scroll: Option<(&str, bool, f32)>, tx: &Tx, force_all: bool, bound: f32) -> bool { + let Some(built) = el.memo_built() else { return false }; + if !built.region || !built.reusable || force_all || !matches!(self.pass, Pass::First) || !crate::memo::flattened(built.id) { + return false; + } + let mut lists = Vec::new(); + if !windowed_lists(el, path, scroll, bound, &mut lists) { + return false; + } + let prefix = format!("{path}/"); + let under = self.virtuals.keys().filter(|k| k.starts_with(&prefix) || *k == path).count(); + // An outer memo that couldn't stay windowed these lists already: they apply as picked. + if under != lists.len() || lists.iter().any(|(p, ..)| self.windowed.contains_key(p)) { + return false; + } + let mut keeps = true; + let mut quiet = Vec::with_capacity(lists.len()); + for (list_path, list_el, list_scroll) in lists { + let Some(estimate) = list_el.cold.virtual_estimate else { return false }; + let held = self.virtuals.get(&list_path).is_some_and(|v| { + v.mounted.is_some() && v.focused_row.is_none() && v.selection.pins.rows().is_empty() && v.row_reads.hold() + }); + let w = self.window(list_el, &list_path, estimate, list_scroll.as_ref().map(|(p, s, b)| (p.as_str(), *s, *b)), tx, force_all); + let v = self.virtuals.get_mut(&list_path).expect("windowed"); + let same = held && w.same && v.mounted == Some(crate::el::virtual_list::Mounted::of(v)); + if same { + let commits = self.commits; + quiet.push((list_path.clone(), v.range.clone().map(|i| v.mounts_quietly(i, commits)).collect::<Vec<_>>())); + } + keeps &= same; + self.windowed.insert(list_path, w); + } + if !keeps { + return false; + } + for (list_path, _) in &quiet { + self.windowed.remove(list_path); + let v = &self.virtuals[list_path]; + v.row_reads.replay(); + crate::memo::keep_rows(v.keys[v.range.clone()].iter().map(|key| crate::memo::virtual_row_tag(list_path, key))); + } + self.kept_lists.extend(quiet); + true + } + fn measure_view(&mut self, text: &mut TextSystem, tx: &Tx, force_all: bool) -> (LayoutEngine, Vec<Node>, Vec<memo_reuse::PendingFlat>, Vec<memo_reuse::ReusedSpan>, Vec<(u32, u32)>) { + let scale = self.env.scale; + let fresh_cx = |this: &Self| cx::CxCore { + env: this.env, + titlebar_inset: this.titlebar_inset, + chrome: this.chrome, + caption_color: None, + titlebar: Default::default(), + system_accent: this.system_accent, + system_contrast: this.system_contrast, + system_increased_contrast: this.system_increased_contrast, + system_scroll_bars: this.system_scroll_bars, + system_reduced_motion: this.system_reduced_motion, + reduced_motion: this.system_reduced_motion, + time_scale: this.time_scale, + zoom: 1.0, + defaults: Default::default(), + caret: this.caret.clone(), + caret_read: std::cell::Cell::new(false), + layout: this.layout_seen.clone(), + layout_reads: Default::default(), + }; + let cx = fresh_cx(self); + #[cfg(feature = "hot")] + let emptied = self.memo.emptied(); + let memo = crate::memo::enter(std::mem::take(self.memo), self.env, self.system_accent, self.system_reduced_motion, crate::theme::blends_srgb(), self.chrome_bits(), cx.caret.clone(), cx.layout.clone()); + let view_time = crate::frame::profile::Scope::new(crate::frame::profile::Phase::View); + // The view and the rows it builds measure text with the window's own text system. + #[cfg(not(feature = "hot"))] + let (mut root, cx) = crate::text::lend(&mut *text, || { + let (root, cx) = self.root_view(cx); + (self.build_tree(root, tx, force_all), cx) + }); + // Index-built rows run the app's closures in `build_tree`, so a patch's panic there + // falls back like one in the view. + #[cfg(feature = "hot")] + let (mut root, cx, memo) = { + match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| crate::text::lend(&mut *text, || { + let (root, cx) = self.root_view(cx); + (self.build_tree(root, tx, force_all), cx) + }))) { + Ok((root, cx)) => (root, cx, memo), + Err(_) => { + eprintln!("rune-hot: view panicked; rendering the original view"); + // The failed build's memo scope, cache and context writes go; the startup + // view builds from scratch against the retained state. + drop(memo); + self.virtual_culled.clear(); + self.virtual_inputs.clear(); + let cx = fresh_cx(self); + let memo = crate::memo::enter(emptied, self.env, self.system_accent, self.system_reduced_motion, crate::theme::blends_srgb(), self.chrome_bits(), cx.caret.clone(), cx.layout.clone()); + let (root, cx) = crate::hot::original_only(|| self.root_view(cx)); + (crate::hot::original_only(|| self.build_tree(root, tx, force_all)), cx, memo) + } + } + }; + // Both paths finish the memo here, after the rows are built. + let (memo, replayed) = memo.finish(); + drop(view_time); + *self.memo = memo; + self.reduced_motion = cx.reduced_motion; + self.time_scale = cx.time_scale; + self.zoom = cx.zoom; + self.defaults = cx.defaults; + self.titlebar = cx.titlebar; + // Reads made by memos this build reused count as made again. + self.caret_read = cx.caret_read.get() || replayed.caret; + self.layout_reads = cx.layout_reads.take(); + for read in replayed.layout { layout_read::note_read_at(&mut self.layout_reads, &read.key, read.same, read.at); } + + let mut taffy = std::mem::replace(self.layout, LayoutEngine::with_capacity(0)); + taffy.begin_commit(); + let mut nodes = std::mem::take(self.spare_nodes); + nodes.clear(); + nodes.reserve(self.nodes.len().max(32)); + // Root constraints are part of the retained style, not a dirty write after flattening. + // A window that fits its content lays the root out at its natural height. + root.style.set_size(relayout::root_size(self.viewport, self.fit_height)); + let (pending, reused, taken_paths, root_id) = { + let mut pending = std::mem::take(&mut self.memo.pending_scratch); + pending.clear(); + let mut reused = std::mem::take(&mut self.memo.reused_scratch); + reused.clear(); + let mut taken_paths = std::mem::take(&mut self.memo.taken_paths_scratch); + taken_paths.clear(); + let mut path_buf = std::mem::take(&mut self.memo.path_scratch); + path_buf.clear(); + let mut memo_ctx = memo_reuse::MemoFlattenCtx { + old_nodes: &mut *self.nodes, + old_present_len: self.memo.present_len, + old_node_index: &*self.node_index, + old_cursor: 0, + committing: self.committing, + committed: &self.memo.flattened, + pending, + reused, + taken_paths, + path_ids: &mut *self.path_ids, + next_id: &mut *self.next_id, + foreground: self.defaults.foreground, + }; + let (root_id, _) = flatten_with_buf(root, None, &mut path_buf, 0, crate::tok::motion::DEFAULT, RowLayout::Free, true, &mut taffy, &mut nodes, scale, &mut memo_ctx); + let (pending, reused, taken_paths) = (memo_ctx.pending, memo_ctx.reused, memo_ctx.taken_paths); + path_buf.clear(); + self.memo.path_scratch = path_buf; + (pending, reused, taken_paths, root_id) + }; + // Rows of a list kept with its memo came from the last commit's nodes: mark which mount + // quietly, as `populate_virtual_children` marks a list's rows. + for (path, quiet) in self.kept_lists.drain(..) { + let Some(list) = nodes.iter().position(|n| n.path == path) else { continue }; + for (n, quiet) in nodes[list + 1..].iter_mut().filter(|n| n.parent == Some(list)).zip(quiet) { + n.virtual_mount = quiet; + } + } + if self.committing { release_kept_layouts(self.nodes, &mut nodes, &taffy, text, &reused); } + taffy.finish_flatten(); + let (taffy, nodes) = self.solve(text, taffy, root_id, nodes); + (taffy, nodes, pending, reused, taken_paths) + } + + pub(in crate::runtime) fn populate_virtual_children( + &mut self, + el: &mut El, + path: &str, + source: Option<Rc<crate::el::virtual_rows::RowSource>>, + inert: bool, + group: Option<&str>, + ) { + let state = self.app.states_ref(); + let v = self.virtuals.get_mut(path).unwrap(); + let list_group = if el.flags.has(ElFlags::SELECTION_GROUP) { Some(path.to_owned()) } else { group.map(str::to_owned) }; + v.selection.scope = selectable::virtual_selection::Scope { group_path: list_group.clone(), inert }; + // Refill the kept rows' texts in place, so the vectors' allocations carry over and a + // builder that panics partway leaves what it already collected. + v.selection.pins.clear_texts(); + // Dev's order: the rows kept from the last commit go before any builder runs, so a row + // holding a resource doesn't keep it through building its replacement. + v.selection.stored.clear(); + if let Some(rows) = source { + // What the rows read, so a memo holding the list can keep them while it holds. + let ((), reads) = crate::memo::recording(|| { + let quiet: Vec<bool> = v.range.clone().map(|i| v.mounts_quietly(i, self.commits)).collect(); + let key_warnings = &mut *self.key_warnings; + let keys = &v.keys; + let mut build = |i: usize| { + let key = &keys[i]; + let tag = crate::memo::virtual_row_tag(path, key); + let mut row = crate::memo::in_virtual_row(tag, || (rows.build)(state, i)).key(key.clone()); + // The view's key repair ran before these rows existed. + if crate::input::key_diagnostics::clean(&row) { return row; } + let duplicates = crate::input::key_diagnostics::repair_at(&mut row, &format!("{path}/{key}")); + match key_warnings.as_mut() { + Some(out) => out.extend(duplicates.into_iter().map(|d| d.message)), + None => crate::input::key_diagnostics::warn_once(&duplicates), + } + row + }; + // A focused field's row and a selection's pinned end rows are built unmounted. + let under = |f: &str| f.strip_prefix(path).is_some_and(|rest| rest.starts_with('/')); + let focused = v.focused_row.as_deref().filter(|_| self.focused.is_some_and(under)) + .and_then(|key| v.index_of(key)).filter(|i| !v.range.contains(i)); + let pinned: Vec<usize> = v.selection.pins.rows().iter() + .filter_map(|key| v.index_of(key)) + .filter(|i| !v.range.contains(i)) + .collect(); + if let Some(i) = focused { + let row = build(i); + collect_virtual_inputs(&row, path, i, inert, self.virtual_inputs); + if pinned.contains(&i) { + selectable::virtual_selection::collect_row_into_pins( + &mut v.selection.pins, &row, path, &v.keys[i], i, list_group.as_deref(), inert, + ); + } + } + for i in pinned { + if Some(i) == focused { continue; } + let row = build(i); + selectable::virtual_selection::collect_row_into_pins( + &mut v.selection.pins, &row, path, &v.keys[i], i, list_group.as_deref(), inert, + ); + } + el.children = v.range.clone().zip(quiet).map(|(i, quiet)| { + let mut row = build(i); + row.flags.set(ElFlags::VIRTUAL_MOUNT, quiet); + row + }).collect(); + }); + v.row_reads = reads; + // Rows a pass that doesn't commit built aren't the nodes a memo would keep. + if !self.committing { v.mounted = None; } + v.selection.pins.set_source(selectable::virtual_selection::Source::Rebuild(rows)); + } else { + if self.pass.reveals() && el.cold.focus.reveal_selected { + let selected = el.children.iter().find(|c| c.cold.focus.selected).and_then(|c| c.key.clone()); + if selected != v.selected_row { + v.reveal_selected = selected.clone(); + v.selected_row = selected; + } + } + #[cfg(debug_assertions)] + crate::tooling::perf_warn::overbuilt(path, el.cold.virtual_source, el.children.len(), v.range.len()); + let pinned: Vec<usize> = v.selection.pins.rows().iter() + .filter_map(|key| v.index_of(key)) + .filter(|i| !v.range.contains(i)) + .collect(); + // Dev installs the stored source before the children loop, releasing the old indexed + // builder before the kept rows and copied texts it would overlap with. + v.selection.pins.set_source(selectable::virtual_selection::Source::Stored); + el.children = std::mem::take(&mut el.children).into_iter().enumerate().filter_map(|(i, mut child)| { + if !v.range.contains(&i) { + collect_virtual_inputs(&child, path, i, inert, self.virtual_inputs); + if pinned.contains(&i) { + selectable::virtual_selection::collect_row_into_pins( + &mut v.selection.pins, &child, path, &v.keys[i], i, list_group.as_deref(), inert, + ); + } + v.selection.stored.insert(i, child); + return None; + } + child.flags.set(ElFlags::VIRTUAL_MOUNT, v.mounts_quietly(i, self.commits)); + Some(child) + }).collect(); + } + } +} + +impl RuntimeCore { + /// Records which row of each virtual list holds focus, by key, so the row is still built + /// after it scrolls out. Walks the node tree, since a key may itself contain `/`. + pub(in crate::runtime) fn track_focused_rows(&mut self) { + if self.commit.virtuals.is_empty() { return; } + let focused = self.kbd.focus.path().and_then(|f| self.tree.nodes.iter().position(|n| n.path == f)); + for (path, v) in self.commit.virtuals.iter_mut() { + let Some(rest) = self.kbd.focus.path().and_then(|f| f.strip_prefix(path.as_str())).and_then(|r| r.strip_prefix('/')) else { + v.focused_row = None; + continue; + }; + if let Some(mut i) = focused { + while let Some(p) = self.tree.nodes[i].parent { + if self.tree.nodes[p].path == *path { + v.focused_row = self.tree.nodes[i].key.clone(); + break; + } + i = p; + } + } else { + let matches = |k: &str| rest == k || rest.strip_prefix(k).is_some_and(|t| t.starts_with('/')); + if !v.focused_row.as_deref().is_some_and(matches) { + v.focused_row = v.keys.iter().find(|k| matches(k)).cloned(); + } + } + } + } +} + +/// The `virtual_rows` lists in memo placeholder `el`'s shared subtree at `path`, with the scroll +/// viewport each windows against, as `window_tree` would find them. False when one can't be +/// windowed without expanding: a list built from children, or a memo given extra children. +fn windowed_lists<'e>(el: &'e El, path: &str, scroll: Option<(&str, bool, f32)>, bound: f32, out: &mut Vec<(String, &'e El, Option<(String, bool, f32)>)>) -> bool { + if !el.flags.has(ElFlags::HAS_VIRTUAL) { + return true; + } + let kids: &[El] = match el.memo_children() { + Some(m) if el.children.is_empty() && !el.flags.has(ElFlags::MEMO_EXTENDED) => &m.children, + Some(_) => return false, + None => &el.children, + }; + let bound = crate::el::virtual_list::height_bound(&el.style, bound); + if el.cold.virtual_estimate.is_some() { + if el.cold.virtual_rows.is_none() { + return false; + } + out.push((path.to_owned(), el, scroll.map(|(p, s, b)| (p.to_owned(), s, b)))); + } + let bounds = crate::el::virtual_list::child_bounds(&el.style, el.cold.scroll.is_some(), bound, kids); + let scroll = match el.cold.scroll { + Some(s) => Some((path, s.stick_bottom, bound)), + None => scroll, + }; + kids.iter().enumerate().filter(|(_, c)| c.flags.has(ElFlags::HAS_VIRTUAL)).all(|(i, child)| { + windowed_lists(child, &node_path(path, child.key.as_deref(), i), scroll, bounds.of(child), out) + }) +} + +/// A virtual list's window, picked before its element is expanded (`Measurement::window`). +pub(in crate::runtime) struct Window { + /// The list's keys are the ones it had. + same: bool, + /// Children renamed for a duplicate key: their index and new key. + renamed: Vec<(usize, String)>, + pad_top: f32, + pad_bottom: f32, +} \ No newline at end of file diff --git a/app/vendor/rune/crates/rune/src/runtime/commit/memo_reuse.rs b/app/vendor/rune/crates/rune/src/runtime/commit/memo_reuse.rs new file mode 100644 index 0000000..abbaa4a --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/commit/memo_reuse.rs @@ -0,0 +1,765 @@ +//! Reusing a [`memo`](crate::memo)'s flattened `Node` slice and Taffy `NodeId` subtree across +//! commits when neither the memo's inputs, its root modifiers nor its inherited flatten state +//! changed, rebasing node paths and ids only when its parent path moved. +use super::*; + +#[derive(Clone, Copy, PartialEq)] +pub(crate) struct InheritedFlatten { + pub(in crate::runtime) motion: Spring, + pub(in crate::runtime) in_row: RowLayout, + pub(in crate::runtime) parent_is_stack: bool, + pub(in crate::runtime) instant_changes: bool, + pub(in crate::runtime) inert: bool, + /// The parent's flow (`El::dir`). + pub(in crate::runtime) flow: crate::el::Flow, + pub(in crate::runtime) directed: bool, + pub(in crate::runtime) trace_namespace: Option<(&'static str, &'static str)>, + pub(in crate::runtime) scale_bits: u32, + /// The window's foreground (`Cx::foreground`), which a memo's uncoloured text took. + pub(in crate::runtime) foreground: Option<Color>, +} + +pub(crate) struct FlattenedMemo { + pub(in crate::runtime) start: usize, + pub(in crate::runtime) len: usize, + pub(in crate::runtime) root_id: NodeId, + pub(in crate::runtime) last_id: NodeId, + pub(in crate::runtime) inherited: InheritedFlatten, + pub(in crate::runtime) hover_within: Option<Rc<(Anim, Anim)>>, +} + +pub(crate) struct PendingFlat { + pub(in crate::runtime) built_id: u64, + pub(in crate::runtime) start: usize, + pub(in crate::runtime) len: usize, + pub(in crate::runtime) inherited: InheritedFlatten, + pub(in crate::runtime) hover_within: Option<Rc<(Anim, Anim)>>, +} + +#[derive(Clone, Copy)] +pub(crate) struct ReusedSpan { + pub(in crate::runtime) new_start: usize, + pub(in crate::runtime) old_start: usize, + pub(in crate::runtime) len: usize, + pub(in crate::runtime) same_path: bool, + pub(in crate::runtime) moved: bool, +} + +/// A contiguous sub-range of `nodes` (`new_start .. new_start + len`, from `old_start`) whose +/// per-node `apply` diff is a guaranteed no-op. +#[derive(Clone, Copy)] +pub(crate) struct CleanApplySpan { + pub(in crate::runtime) new_start: usize, + pub(in crate::runtime) old_start: usize, + pub(in crate::runtime) len: usize, +} + +pub(in crate::runtime) fn is_in_clean_spans(spans: &[CleanApplySpan], i: usize) -> bool { + let idx = spans.partition_point(|s| s.new_start <= i); + idx > 0 && { + let s = &spans[idx - 1]; + i < s.new_start + s.len + } +} + +impl CommitState { + fn node_clean_for_apply(tree: &types::TreeState, scene: &Scene, motion: &tracks::MotionState, new_n: &Node, old_n: &Node, any_animating: bool) -> bool { + new_n.id == old_n.id + && new_n.local == old_n.local + && (!any_animating || !scene.store().is_node_animating(new_n.id)) + && scene.phase(new_n.id) == Some(PresencePhase::Present) + && !old_n.group_fade + && new_n.cold.get().is_none_or(|c| c.matched.is_none() && c.looping.is_none()) + && (motion.flying.is_empty() || !motion.flying.iter().any(|f| f.0 == new_n.id)) + && (tree.aspect_snap.is_empty() || !tree.aspect_snap.contains(&new_n.id)) + && new_n.text.as_ref().is_none_or(|t| t.reveal < 0.0 || motion.reveal_caught_up(new_n.id, t.content.len())) + } + + /// Fills `out` with the reused memo slices that can skip `apply`'s per-node diff loop. + #[allow(clippy::too_many_arguments)] + pub(in crate::runtime) fn clean_apply_spans(&self, tree: &types::TreeState, scene: &Scene, motion: &tracks::MotionState, nodes: &[Node], reused: &[ReusedSpan], can_skip: bool, reorder_jump: impl Fn(usize) -> f32, out: &mut Vec<CleanApplySpan>) { + out.clear(); + if !can_skip || reused.is_empty() { return; } + out.reserve(reused.len()); + let any_animating = scene.store().active_len() > 0; + for span in reused { + if !span.same_path || span.len == 0 || span.old_start + span.len > tree.nodes.len() || span.new_start + span.len > nodes.len() { continue; } + let (r_new, r_old) = (&nodes[span.new_start], &tree.nodes[span.old_start]); + if !scene.contains(r_new.id) || matches!(scene.phase(r_new.id), Some(PresencePhase::Exiting { .. })) { continue; } + let mut scene_rect = r_new.local; + if !self.virtuals.is_empty() && let Some(v) = r_new.parent.and_then(|p| self.virtuals.get(&nodes[p].path)) { scene_rect.y -= v.before; } + let parent_top_clean = r_new.in_row != RowLayout::Snaps + || r_new.parent.is_none_or(|p| { + nodes.get(p + 1).is_none_or(|first_sib| { + let mut sr = first_sib.local; + if !self.virtuals.is_empty() && let Some(v) = self.virtuals.get(&nodes[p].path) { sr.y -= v.before; } + scene.get(first_sib.id, prop::FRAME) == Some(sr) + }) + }); + let root_clean = Self::node_clean_for_apply(tree, scene, motion, r_new, r_old, any_animating) + && parent_top_clean + && r_new.parent.map(|p| nodes[p].id) == r_old.parent.map(|p| tree.nodes[p].id) + && (self.virtuals.is_empty() || !self.virtuals.contains_key(&r_new.path)) + && scene.is_resting_at(r_new.id, scene_rect) + && (motion.stacks.is_empty() || reorder_jump(span.new_start) == 0.0) + && (self.virtuals.is_empty() + || !r_new.parent.and_then(|p| self.virtuals.get(&nodes[p].path)).is_some_and(crate::el::virtual_list::VirtualList::replaced_view)); + if !root_clean && !motion.flying.is_empty() { continue; } + let offset = if root_clean { 0 } else { 1 }; + if offset >= span.len { continue; } + let interior_clean = (offset..span.len).all(|k| { + Self::node_clean_for_apply(tree, scene, motion, &nodes[span.new_start + k], &tree.nodes[span.old_start + k], any_animating) + }); + if interior_clean { + let (new_start, old_start, len) = (span.new_start + offset, span.old_start + offset, span.len - offset); + if let Some(last) = out.last_mut() && last.new_start + last.len == new_start && last.old_start + last.len == old_start { + last.len += len; + } else { + out.push(CleanApplySpan { new_start, old_start, len }); + } + } + } + } +} + +pub(in crate::runtime) struct MemoFlattenCtx<'a> { + pub(in crate::runtime) old_nodes: &'a mut [Node], + pub(in crate::runtime) old_present_len: usize, + pub(in crate::runtime) old_node_index: &'a NodeIndex, + pub(in crate::runtime) old_cursor: usize, + pub(in crate::runtime) committing: bool, + pub(in crate::runtime) committed: &'a HashMap<u64, FlattenedMemo>, + pub(in crate::runtime) pending: Vec<PendingFlat>, + pub(in crate::runtime) reused: Vec<ReusedSpan>, + pub(in crate::runtime) taken_paths: Vec<(u32, u32)>, + pub(in crate::runtime) path_ids: &'a mut HashMap<String, NodeId>, + pub(in crate::runtime) next_id: &'a mut u64, + /// What text, icons and text fields without their own colour draw in (`Cx::foreground`). + pub(in crate::runtime) foreground: Option<Color>, +} + +fn opt_rc_eq<T: ?Sized>(a: &Option<Rc<T>>, b: &Option<Rc<T>>) -> bool { + match (a, b) { + (None, None) => true, + (Some(x), Some(y)) => Rc::ptr_eq(x, y), + _ => false, + } +} + +fn opt_box_eq<T: PartialEq>(a: &Option<Box<T>>, b: &Option<Box<T>>) -> bool { + match (a, b) { + (None, None) => true, + (Some(x), Some(y)) => **x == **y, + _ => false, + } +} + +fn same_visual_cold(a: &crate::el::VisualCold, b: &crate::el::VisualCold) -> bool { + let crate::el::VisualCold { + surface, surface_place, border_bottom, border_sides, border_layout, border_dash, border_dash_phase, shadows, blur_motion, + clip, clip_radius, clip_corners, cutout, icon, icon_inked, icon_one_color, gradient, radial, outline, shape, + grid, pixels, pixels_fit, effect, backdrop_blur, hover_motion, hover_within, + group_opacity, group_color, hover_alone, hover_share, icon_turn, cache_key, offset_motion, scale_motion, + origin, rotate_motion, child_exit, enter_delay, motion_intent, instant_motion, clip_to_content, flight_crop, + hold_landing, row_face, press_color, paint_contain, motion_snaps, hairline, offset, paint_alpha, layer_opacity, blur, rotate, mark, mirror_rtl, paint_order, + } = b; + (match (&a.surface, surface) { + (None, None) => true, + (Some((sa, fa)), Some((sb, fb))) => sa.key() == sb.key() && fa == fb, + _ => false, + }) && a.surface_place == *surface_place && a.border_bottom == *border_bottom && a.border_sides == *border_sides && a.border_layout == *border_layout && a.border_dash == *border_dash + && a.border_dash_phase == *border_dash_phase && a.shadows == *shadows + && opt_box_eq(&a.blur_motion, blur_motion) && a.clip == *clip + && a.clip_radius == *clip_radius && a.clip_corners == *clip_corners && a.cutout == *cutout + && match (&a.icon, icon) { + (None, None) => true, + (Some((ia, ca)), Some((ib, cb))) => std::ptr::eq(*ia, *ib) && ca == cb, + _ => false, + } + && a.icon_inked == *icon_inked && a.icon_one_color == *icon_one_color + && opt_box_eq(&a.gradient, gradient) && opt_box_eq(&a.radial, radial) + && a.outline == *outline && opt_rc_eq(&a.shape, shape) + // A grid built again from the same rows is the same grid. + && match (&a.grid, grid) { + (None, None) => true, + (Some(x), Some(y)) => Rc::ptr_eq(x, y) || (x.cols == y.cols && x.cell == y.cell && x.caret == y.caret && x.rows.len() == y.rows.len() && x.rows.iter().zip(&y.rows).all(|(p, q)| Rc::ptr_eq(p, q))), + _ => false, + } + && match (&a.pixels, pixels) { + (None, None) => true, + (Some(pa), Some(pb)) => Arc::ptr_eq(&pa.source, &pb.source), + _ => false, + } + && a.pixels_fit == *pixels_fit && a.effect == *effect && a.backdrop_blur == *backdrop_blur + && opt_rc_eq(&a.hover_motion, hover_motion) && opt_rc_eq(&a.hover_within, hover_within) + && a.group_opacity == *group_opacity && a.group_color == *group_color && a.hover_alone == *hover_alone && a.hover_share == *hover_share + && a.icon_turn == *icon_turn && a.cache_key == *cache_key + && opt_box_eq(&a.offset_motion, offset_motion) && opt_box_eq(&a.scale_motion, scale_motion) + && a.origin == *origin && opt_box_eq(&a.rotate_motion, rotate_motion) + && opt_box_eq(&a.child_exit, child_exit) && a.enter_delay == *enter_delay + && a.motion_intent == *motion_intent && a.instant_motion == *instant_motion + && a.clip_to_content == *clip_to_content + && a.flight_crop == *flight_crop + && a.row_face == *row_face && a.hold_landing == *hold_landing && a.press_color == *press_color && a.paint_contain == *paint_contain && a.motion_snaps == *motion_snaps && a.hairline == *hairline + && a.offset == *offset && a.paint_alpha == *paint_alpha && a.layer_opacity == *layer_opacity + && a.blur == *blur && a.rotate == *rotate && a.mark == *mark && a.mirror_rtl == *mirror_rtl && a.paint_order == *paint_order +} + +pub(in crate::runtime) fn same_visual(a: &Visual, b: &Visual) -> bool { + let Visual { fill, radius, opacity, box_paint, cold } = b; + a.fill == *fill && a.radius.to_bits() == radius.to_bits() && a.opacity == *opacity + && (crate::cold::Cold::ptr_eq(&a.box_paint, box_paint) || *a.box_paint == **box_paint) + && (crate::cold::Cold::ptr_eq(&a.cold, cold) || same_visual_cold(&a.cold, cold)) +} + +fn same_el_cold(a: &crate::el::ElCold, b: &crate::el::ElCold) -> bool { + let crate::el::ElCold { + focus, looping, trace_name, trace_namespace, role, label, live, above, motion, opacity_motion, lead, + animated_changes, option_as_alt, transition, matched, scroll, scroll_axes, sticky, scroll_edges, growth, virtual_estimate, virtual_rows, + virtual_rows_version, glide, input, time_scale, help, help_cut, help_side, help_open, material, aspect_fit, list_disc, a11y, wheel_scrolls, + expanded_memo: _, + #[cfg(debug_assertions)] + scroll_source: _, + #[cfg(debug_assertions)] + virtual_source: _, + } = b; + crate::cold::Cold::ptr_eq(&a.focus, focus) + && opt_box_eq(&a.looping, looping) + && a.trace_name == *trace_name + && a.trace_namespace == *trace_namespace + && a.role == *role + && a.label == *label + && a.live.is_empty() + && live.is_empty() + && a.above == *above + && a.motion == *motion + && opt_box_eq(&a.opacity_motion, opacity_motion) + && a.lead == *lead + && a.animated_changes == *animated_changes + && a.option_as_alt == *option_as_alt + && opt_box_eq(&a.transition, transition) + && a.matched == *matched + && a.scroll == *scroll + && a.scroll_axes == *scroll_axes + && opt_box_eq(&a.sticky, sticky) + && a.scroll_edges == *scroll_edges + && opt_box_eq(&a.growth, growth) + && a.virtual_estimate == *virtual_estimate + && opt_rc_eq(&a.virtual_rows, virtual_rows) + && a.virtual_rows_version == *virtual_rows_version + && a.glide == *glide + && a.input.is_none() + && input.is_none() + && a.time_scale == *time_scale + && a.help == *help + && a.help_cut == *help_cut + && a.help_side == *help_side + && a.help_open == *help_open + && a.list_disc == *list_disc + && a.material == *material + && a.aspect_fit == *aspect_fit + && a.a11y == *a11y + && a.wheel_scrolls == *wheel_scrolls +} + +fn same_gestures( + a: &Option<Box<crate::input::canvas_input::CanvasInput>>, + b: &Option<Box<crate::input::canvas_input::CanvasInput>>, +) -> bool { + match (a, b) { + (None, None) => true, + (Some(x), Some(y)) => { + x.buttons == y.buttons + && opt_rc_eq(&x.wheel, &y.wheel) + && opt_rc_eq(&x.magnify, &y.magnify) + && opt_rc_eq(&x.rotate, &y.rotate) + && opt_rc_eq(&x.smart_magnify, &y.smart_magnify) + } + _ => false, + } +} + +fn same_drop( + a: &Option<Box<crate::el::DropSpec>>, + b: &Option<Box<crate::el::DropSpec>>, +) -> bool { + match (a, b) { + (None, None) => true, + (Some(x), Some(y)) => { + opt_rc_eq(&x.on_drop, &y.on_drop) + && opt_rc_eq(&x.accepts, &y.accepts) + && opt_rc_eq(&x.on_hover, &y.on_hover) + && opt_rc_eq(&x.on_reject, &y.on_reject) + && opt_rc_eq(&x.on_reject_hover, &y.on_reject_hover) + && opt_rc_eq(&x.on_move, &y.on_move) + } + _ => false, + } +} + +fn same_handlers( + a: &crate::cold::Cold<crate::el::Handlers>, + b: &crate::cold::Cold<crate::el::Handlers>, +) -> bool { + if crate::cold::Cold::ptr_eq(a, b) { + return true; + } + let crate::el::Handlers { + on_paste, + on_window_focus, + on_spellcheck, + on_spellcheck_languages, + modal, + on_press, + on_double_press, + on_secondary_press, + on_middle_press, + on_hover, + on_hover_change, + hover_delay, + on_pointer_move, + gestures, + on_drag, + drag_out, + drag_threshold, + touch_at_once, + press_on_down, + on_drag_start, + on_drag_end, + drop, + on_at_bottom, + on_far_from_bottom, + on_visible_rows, + on_layout, + on_screen_layout, + on_drawn_layout, + on_visible, + drawn_rect, + on_scroll_offset, + selection_copy, + on_selection_change, + cursor, + press_scale, + #[cfg(debug_assertions)] + sites: _, + } = &**b; + a.modal.is_none() + && modal.is_none() + && match (&a.on_paste, on_paste) { + (None, None) => true, + (Some(pa), Some(pb)) => pa.rich == pb.rich && Rc::ptr_eq(&pa.call, &pb.call), + _ => false, + } + && opt_rc_eq(&a.on_window_focus, on_window_focus) + && match (&a.on_spellcheck, on_spellcheck) { + (None, None) => true, + (Some((on_a, fa)), Some((on_b, fb))) => on_a == on_b && Rc::ptr_eq(fa, fb), + _ => false, + } + && opt_rc_eq(&a.on_spellcheck_languages, on_spellcheck_languages) + && opt_rc_eq(&a.on_press, on_press) + && opt_rc_eq(&a.on_double_press, on_double_press) + && opt_rc_eq(&a.on_secondary_press, on_secondary_press) + && opt_rc_eq(&a.on_middle_press, on_middle_press) + && opt_rc_eq(&a.on_hover, on_hover) + && opt_rc_eq(&a.on_hover_change, on_hover_change) + && a.hover_delay == *hover_delay + && opt_rc_eq(&a.on_pointer_move, on_pointer_move) + && same_gestures(&a.gestures, gestures) + && opt_rc_eq(&a.on_drag, on_drag) + && opt_rc_eq(&a.drag_out, drag_out) + && a.drag_threshold == *drag_threshold + && a.touch_at_once == *touch_at_once + && a.press_on_down == *press_on_down + && opt_rc_eq(&a.on_drag_start, on_drag_start) + && opt_rc_eq(&a.on_drag_end, on_drag_end) + && same_drop(&a.drop, drop) + && opt_rc_eq(&a.on_at_bottom, on_at_bottom) + && match (&a.on_far_from_bottom, on_far_from_bottom) { + (None, None) => true, + (Some((da, ua, fa)), Some((db, ub, fb))) => da == db && ua == ub && Rc::ptr_eq(fa, fb), + _ => false, + } + && opt_rc_eq(&a.on_visible_rows, on_visible_rows) + && opt_rc_eq(&a.on_layout, on_layout) + && opt_rc_eq(&a.on_screen_layout, on_screen_layout) + && opt_rc_eq(&a.on_drawn_layout, on_drawn_layout) + && opt_rc_eq(&a.on_visible, on_visible) + && match (&a.drawn_rect, drawn_rect) { + (None, None) => true, + (Some(la), Some(lb)) => std::sync::Arc::ptr_eq(&la.source, &lb.source), + _ => false, + } + && opt_rc_eq(&a.on_scroll_offset, on_scroll_offset) + && opt_rc_eq(&a.selection_copy, selection_copy) + && opt_rc_eq(&a.on_selection_change, on_selection_change) + && a.cursor == *cursor + && a.press_scale == *press_scale +} + +/// Exhaustively checks that `el` has not been mutated by builders after `Built::placeholder` +/// returned it (apart from `key` and `virtual_mount`, which flattening handles explicitly). +/// `expanded`: `el` is the placeholder after `El::expand_memo` copied the shared children in. +pub(in crate::runtime) fn same_root_el(el: &El, built: &crate::memo::Built, expanded: bool) -> bool { + let base = &built.root; + let El { + style, + vis, + children: _, + key: _, + text, + handlers, + memo: _, + cold, + scale, + flags, + role, + vis_flags, + #[cfg(debug_assertions)] + key_source: _, + } = base; + // Flags flattening handles itself, or that only describe the children. + let ignored = crate::el::ElFlags::HAS_VIRTUAL | crate::el::ElFlags::MEMO_EXTENDED | crate::el::ElFlags::VIRTUAL_MOUNT; + let mut a = el.flags; + let mut b = *flags; + a.set(ignored, false); + b.set(ignored, false); + + (expanded || (el.children.is_empty() && el.memo_children().is_some_and(|mc| Rc::ptr_eq(mc, &built.children)))) + && el.role == *role + && a == b + && el.vis_flags == *vis_flags + && el.style == *style + && same_visual(&el.vis, vis) + && match (&el.text, text) { + (None, None) => true, + (Some(ta), Some(tb)) => crate::cold::SharedBox::ptr_eq(ta, tb), + _ => false, + } + && same_handlers(&el.handlers, handlers) + && el.scale == *scale + && cold.live.is_empty() + && cold.input.is_none() + && (crate::cold::Cold::ptr_eq(&el.cold, cold) || same_el_cold(&el.cold, cold)) +} + +pub(in crate::runtime) fn inherited_for( + parent: Option<usize>, + nodes: &[Node], + motion: Spring, + in_row: RowLayout, + scale: f32, + foreground: Option<Color>, +) -> (InheritedFlatten, Option<Rc<(Anim, Anim)>>) { + let parent_is_stack = parent.is_some_and(|p| nodes[p].growth.is_some()); + let instant_changes = parent.is_some_and(|p| nodes[p].instant_changes); + let inert = parent.is_some_and(|p| nodes[p].inert); + let trace_namespace = parent.and_then(|p| nodes[p].trace_namespace); + let hover_within = parent.and_then(|p| nodes[p].hover_within.clone()); + ( + InheritedFlatten { + motion, + in_row, + parent_is_stack, + instant_changes, + inert, + flow: parent.map_or(crate::el::Flow::Ltr, |p| nodes[p].flow), + directed: parent.is_some_and(|p| nodes[p].directed), + trace_namespace, + scale_bits: scale.to_bits(), + foreground, + }, + hover_within, + ) +} + +fn path_matches(old_path: &str, parent_path: &str, key: Option<&str>, index: usize) -> bool { + let tail = if parent_path.is_empty() { + old_path + } else { + let Some(rest) = old_path.strip_prefix(parent_path).and_then(|r| r.strip_prefix('/')) else { + return false; + }; + rest + }; + match key { + Some(k) => tail == k, + None => tail.strip_prefix('#').is_some_and(|n| !n.contains('/') && n.parse::<usize>().ok() == Some(index)), + } +} + +#[allow(clippy::too_many_arguments)] +pub(in crate::runtime) fn try_reuse_memo( + el: &El, + parent: Option<usize>, + parent_path: &str, + index: usize, + motion: Spring, + in_row: RowLayout, + scale: f32, + taffy: &mut LayoutEngine, + nodes: &mut Vec<Node>, + ctx: &mut MemoFlattenCtx<'_>, +) -> Option<SlotId> { + let built = el.memo_built()?; + if !built.reusable { + return None; + } + let flat = ctx.committed.get(&built.id)?; + let end = flat.start.checked_add(flat.len)?; + if flat.len == 0 || end > ctx.old_present_len || end > ctx.old_nodes.len() { + return None; + } + let old_slice = &ctx.old_nodes[flat.start..end]; + if old_slice[0].is_moved_stub() || old_slice[0].path.is_empty() || old_slice[0].id != flat.root_id || old_slice[flat.len - 1].id != flat.last_id { + return None; + } + let (inherited, hover_within) = inherited_for(parent, nodes, motion, in_row, scale, ctx.foreground); + // By value: a view that sets `hover_motion_within` above the memo builds a new pair each time. + if flat.inherited != inherited || flat.hover_within.as_deref() != hover_within.as_deref() { + return None; + } + if el.key != old_slice[0].key || !same_root_el(el, built, false) { + return None; + } + if !old_slice.iter().all(|old| !old.is_moved_stub() && !old.path.is_empty() && taffy.can_reuse(old.id.0, old.taffy)) { + return None; + } + // A picture that takes a side from its image's ratio keeps its layout only while the image + // keeps that ratio: one still loading when it was flattened gets its size later. + if !old_slice.iter().all(|old| old.cold.get().and_then(|c| c.pixel_aspect).is_none_or(|r| old.vis.pixels.as_ref().is_some_and(|p| super::flatten::pixel_ratio(p) == r))) { + return None; + } + + let old_root_path = old_slice[0].path.as_str(); + let same_path = path_matches(old_root_path, parent_path, el.key.as_deref(), index); + let new_start = nodes.len(); + let moved = same_path && ctx.committing; + let root_taffy = old_slice[0].taffy; + + if moved { + for k in 0..flat.len { + let new_idx = new_start + k; + let slot = &mut ctx.old_nodes[flat.start + k]; + taffy.reuse_slot(slot.taffy, new_idx as u32); + let stub = Node::moved_stub(slot); + let mut n = std::mem::replace(slot, stub); + n.text_layout = None; + n.elided = None; + n.clear_run_layout(); + n.scale_track = false; + n.group_fade = false; + n.virtual_mount = if k == 0 { el.flags.has(crate::el::ElFlags::VIRTUAL_MOUNT) } else { false }; + n.parent = if k == 0 { parent } else { n.parent.map(|p| new_start + (p - flat.start)) }; + n.target = [0.0; 4]; + n.local = MRect::ZERO; + n.inset = [0.0; 4]; + nodes.push(n); + } + } else if same_path { + for (k, old) in old_slice.iter().enumerate() { + let new_idx = new_start + k; + taffy.reuse_slot(old.taffy, new_idx as u32); + let mut n = Node { + id: old.id, + text_layout: None, + elided: None, + scale_track: false, + group_fade: false, + virtual_mount: if k == 0 { el.flags.has(crate::el::ElFlags::VIRTUAL_MOUNT) } else { false }, + parent: if k == 0 { parent } else { old.parent.map(|p| new_start + (p - flat.start)) }, + target: [0.0; 4], + local: MRect::ZERO, + inset: [0.0; 4], + ..old.clone() + }; + n.clear_run_layout(); + nodes.push(n); + } + } else { + let new_root_path = node_path(parent_path, el.key.as_deref(), index); + let mut rebased = Vec::with_capacity(flat.len); + for (k, old) in old_slice.iter().enumerate() { + let path = if k == 0 { + new_root_path.clone() + } else { + let tail = &old.path[old_root_path.len()..]; + let mut s = String::with_capacity(new_root_path.len() + tail.len()); + s.push_str(&new_root_path); + s.push_str(tail); + s + }; + if ctx.path_ids.get(&path).is_some_and(|id| taffy.is_used_this_commit(id.0)) { + return None; + } + rebased.push(path); + } + let mut new_ids = Vec::with_capacity(flat.len); + for path in &rebased { + let id = match ctx.path_ids.get(path.as_str()) { + Some(&id) => id, + None => { + let id = NodeId(*ctx.next_id); + *ctx.next_id += 1; + ctx.path_ids.insert(path.clone(), id); + id + } + }; + new_ids.push(id); + } + taffy.rekey_and_reuse_batch( + old_slice + .iter() + .zip(new_ids.iter()) + .enumerate() + .map(|(k, (old, new_id))| (old.id.0, new_id.0, old.taffy, (new_start + k) as u32)), + ); + for (k, ((old, path), id)) in old_slice.iter().zip(rebased).zip(new_ids).enumerate() { + let mut n = Node { + id, + path, + text_layout: None, + elided: None, + scale_track: false, + group_fade: false, + virtual_mount: if k == 0 { el.flags.has(crate::el::ElFlags::VIRTUAL_MOUNT) } else { false }, + parent: if k == 0 { parent } else { old.parent.map(|p| new_start + (p - flat.start)) }, + target: [0.0; 4], + local: MRect::ZERO, + inset: [0.0; 4], + ..old.clone() + }; + n.clear_run_layout(); + nodes.push(n); + } + } + + if same_path { + ctx.old_cursor = end; + } + ctx.pending.push(PendingFlat { + built_id: built.id, + start: new_start, + len: flat.len, + inherited, + hover_within, + }); + ctx.reused.push(ReusedSpan { + new_start, + old_start: flat.start, + len: flat.len, + same_path, + moved, + }); + Some(root_taffy) +} + +/// Puts `moved` slices and individually taken paths back into `old_nodes` with their pre-pass +/// geometry and flags before a virtual-window retry or a layout-read, focus or caret re-measure. +pub(in crate::runtime) fn restore_moved_nodes( + old_nodes: &mut [Node], + nodes: &mut [Node], + reused: &[ReusedSpan], + taken_paths: &[(u32, u32)], +) { + for &(oi, ni) in taken_paths { + old_nodes[oi as usize].path = std::mem::take(&mut nodes[ni as usize].path); + } + for span in reused.iter().filter(|s| s.moved) { + for k in 0..span.len { + let stub = &old_nodes[span.old_start + k]; + let n = &mut nodes[span.new_start + k]; + n.parent = stub.parent; + n.target = stub.target; + n.local = stub.local; + n.inset = stub.inset; + n.scale_track = stub.scale_track; + n.group_fade = stub.group_fade; + n.text_layout = None; + n.elided = None; + n.clear_run_layout(); + std::mem::swap(&mut old_nodes[span.old_start + k], n); + } + } +} + +impl crate::memo::MemoCache { + /// Updates flattened subtree spans once `apply` installs `nodes` (`0..present_len`). + /// `None` when `relayout` reused the previous commit's node array in place. + pub(crate) fn commit_flattened( + &mut self, + nodes: &[Node], + present_len: usize, + pending: Option<Vec<PendingFlat>>, + mut reused: Vec<ReusedSpan>, + mut taken_paths: Vec<(u32, u32)>, + ) { + self.present_len = present_len; + taken_paths.clear(); + self.taken_paths_scratch = taken_paths; + let Some(mut pending) = pending else { + reused.clear(); + self.reused_scratch = reused; + return; + }; + // Nested memos inside an outer memo that was reused whole stay live at their rebased index. + if !self.flattened.is_empty() { + self.flattened.retain(|_, flat| { + let Some(span) = reused.iter().find(|s| { + flat.start >= s.old_start && flat.start + flat.len <= s.old_start + s.len + }) else { + return false; + }; + flat.start = span.new_start + (flat.start - span.old_start); + if !span.same_path { + flat.root_id = nodes[flat.start].id; + flat.last_id = nodes[flat.start + flat.len - 1].id; + } + true + }); + } + for p in pending.drain(..) { + if p.len == 0 || p.start + p.len > present_len { + continue; + } + self.flattened.insert( + p.built_id, + FlattenedMemo { + start: p.start, + len: p.len, + root_id: nodes[p.start].id, + last_id: nodes[p.start + p.len - 1].id, + inherited: p.inherited, + hover_within: p.hover_within, + }, + ); + } + reused.clear(); + self.pending_scratch = pending; + self.reused_scratch = reused; + } + + /// Rebases flattened subtree indices after `prune_exited` compacts `self.nodes`. + pub(crate) fn on_prune(&mut self, remap: &[Option<usize>]) { + self.present_len = remap + .get(..self.present_len.min(remap.len())) + .map_or(0, |s| s.iter().filter(|r| r.is_some()).count()); + self.flattened.retain(|_, flat| { + let Some(new_start) = remap.get(flat.start).copied().flatten() else { + return false; + }; + let Some(new_last) = remap.get(flat.start + flat.len - 1).copied().flatten() else { + return false; + }; + if new_last + 1 != new_start + flat.len { + return false; + } + flat.start = new_start; + true + }); + } +} + +#[cfg(test)] +#[path = "../memo_reuse_tests.rs"] +mod tests; diff --git a/app/vendor/rune/crates/rune/src/runtime/commit/prepare.rs b/app/vendor/rune/crates/rune/src/runtime/commit/prepare.rs new file mode 100644 index 0000000..7fd1de9 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/commit/prepare.rs @@ -0,0 +1,112 @@ +//! Text laid out ahead (`Tx::prepare_text`): a view the app names, measured as the window would +//! measure it, into the window's layout cache, without mounting anything. Its nodes, layout tree, +//! ids and memo are the pass's own and go when it ends, so nothing draws, hits, animates or is +//! announced, and no handler or live value sees it. What it shaped stays in the cache until a view +//! shows it (then it is found, not shaped) or the cache lets it go: past [`PREPARE_BYTES`] of +//! prepared layouts the oldest go first, and all of them at the window's next rest. One request is +//! held at a time, the latest; it runs in the window's next idle turn after its first frame, and +//! none while input waits. + +use super::*; + +/// The most prepared layouts no view holds may take in the layout cache, by the cache's own count +/// (`LAYOUT_PER_BYTE`): about one transcript screen. +pub(crate) const PREPARE_BYTES: usize = 1 << 20; + +struct PrepareView<'a, S: 'static> { + state: &'a S, + view: fn(&S, &mut Cx<S>) -> El, +} + +impl<S: 'static> ViewDriver for PrepareView<'_, S> { + fn states_ref(&self) -> crate::states::StatesRef<'_> { + crate::states::StatesRef::one(handler_state_ref(self.state)) + } + + fn view(&self, cx: cx::CxCore, _viewport: (f32, f32)) -> (El, cx::CxCore) { + let mut cx = Cx { core: cx, _s: PhantomData }; + let root = crate::playground::call(self.view, self.state, &mut cx); + (root, cx.core) + } +} + +impl<S: 'static> Runtime<S> { + /// Whether an idle turn has a view to prepare for this window. + pub(crate) fn text_idle_owed(&self) -> bool { + Tx::prepare_owed::<S>() + } + + /// One idle turn's text work: the view asked to be prepared, if any; true while more is owed. + pub(crate) fn text_idle_turn(&mut self) -> bool { + if let Some((view, size)) = Tx::take_prepared::<S>() { + self.prepare_text(view, size.unwrap_or(self.viewport)); + } + self.text_idle_owed() + } + + /// Measures `view` at `size` (points) with this window's text system and scratch everything + /// else, then drops it. Returns the layouts it added. + pub(crate) fn prepare_text(&mut self, view: fn(&S, &mut Cx<S>) -> El, size: (f32, f32)) -> usize { + let (core, app) = self.split_mut(); + let prepare = PrepareView { state: &*app.state, view }; + core.prepare_text_with(&prepare, size) + } +} + +impl RuntimeCore { + pub(super) fn prepare_text_with(&mut self, app: &dyn ViewDriver, size: (f32, f32)) -> usize { + let before = self.text.layout_keys(); + let (mut nodes, mut spare_nodes, mut layout) = (Vec::new(), Vec::new(), LayoutEngine::new()); + let (mut node_index, mut path_ids, mut memo) = (NodeIndex::default(), HashMap::default(), crate::memo::MemoCache::default()); + let (mut next_id, mut scrolls, mut virtuals) = (0u64, HashMap::default(), HashMap::default()); + let (mut virtual_culled, mut virtual_inputs, mut stats, mut key_warnings) = (HashSet::default(), HashMap::default(), FrameStats::default(), None); + let m = Measurement { + app, + env: self.env, + viewport: size, + fit_height: false, + system_reduced_motion: self.host.system_reduced_motion, + titlebar_inset: self.host.titlebar_inset / self.host.zoom.k, + chrome: self.host.titlebar.insets.zoomed(self.host.zoom.k), + caption: self.host.titlebar.caption, + system_accent: self.host.system_accent, + system_contrast: self.host.system_contrast, + system_increased_contrast: self.host.system_increased_contrast, + system_scroll_bars: self.host.scroll_bars.state, + reduced_motion: self.reduced_motion, + time_scale: self.time_scale, + zoom: self.host.zoom.k, + defaults: self.commit.defaults.clone(), + titlebar: self.titlebar_set(), + caret: None, + caret_read: false, + // The rects the window last laid out, as its next frame reads them, so a view that + // measures against them (a header fitting its title) measures here too. + layout_seen: self.commit.layout_seen.rects.clone(), + layout_reads: Vec::new(), + commits: self.commit.commits, + nodes: &mut nodes, + committing: false, + spare_nodes: &mut spare_nodes, + layout: &mut layout, + node_index: &mut node_index, + path_ids: &mut path_ids, + memo: &mut memo, + next_id: &mut next_id, + scrolls: &mut scrolls, + virtuals: &mut virtuals, + virtual_culled: &mut virtual_culled, + virtual_inputs: &mut virtual_inputs, + stats: &mut stats, + key_warnings: &mut key_warnings, + focused: None, + state_unchanged: false, + pass: Pass::First, + hold_windows: false, + windowed: HashMap::default(), + kept_lists: Vec::new(), + }; + drop(m.finish(&mut self.text, &Tx::default())); + self.text.keep_prepared(&before, PREPARE_BYTES) + } +} diff --git a/app/vendor/rune/crates/rune/src/runtime/commit/prune.rs b/app/vendor/rune/crates/rune/src/runtime/commit/prune.rs new file mode 100644 index 0000000..4a07b15 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/commit/prune.rs @@ -0,0 +1,116 @@ +//! Dropping detached nodes and pruning per-node tables across commits and finished exits. + +use super::*; + +/// Reveal states kept for texts that left the tree, newest first: a keyed child that comes back +/// under its old path still shows its words (r349). One that never comes back would otherwise +/// keep its entry, and its path, for the window's life, so only this many stay and the oldest +/// leave. +pub(in crate::runtime) const REVEALS_KEPT: usize = 64; + +impl RuntimeCore { + /// Forgets the ids of paths that left with nothing kept under their id, so a session that + /// mounts many distinct keys (a long virtual list scrolled end to end) doesn't keep them all. + /// A path whose id still holds scroll, growth or reveal state keeps it, so it comes back + /// with that state as before. + pub(in crate::runtime) fn prune_path_ids(&mut self) { + if self.tree.path_ids.len() <= self.tree.node_index.len() { return; } + let Self { tree, scroll, motion, .. } = self; + tree.path_ids.retain(|_, id| { + tree.node_index.contains_key(id) || scroll.scrolls.contains_key(id) || motion.stacks.contains_key(id) || motion.grows.contains_key(id) || motion.has_reveal(*id) + }); + } + + /// Recomputes node-derived presence flags in a single pass over `self.nodes`. + /// Returns whether any node has a loop spec. + pub(in crate::runtime) fn refresh_node_flags(&mut self) -> bool { + let (mut dissolve, mut cache, mut pix, mut drawn_ly, mut key_up, mut sticky, mut raise, mut any_loop) = + (false, false, false, false, false, false, false, false); + let mut ordered = false; + let mut fade_stops: Option<[f32; 2]> = None; + for n in &self.tree.nodes { + dissolve |= n.vis_flags.blend() == crate::render::Blend::PlusLighter; + cache |= n.vis_flags.cache(); + if let Some(c) = n.cold.get() { + pix |= c.pixel_aspect.is_some(); + sticky |= c.sticky.as_ref().is_some_and(|s| s.edge.is_some()); + any_loop |= c.looping.is_some(); + } + drawn_ly |= n.handlers.get().is_some_and(|h| h.on_drawn_layout.is_some() || h.on_visible.is_some() || h.drawn_rect.is_some()); + key_up |= n.focus.get().is_some_and(|f| f.key_up.is_some()); + raise |= n.vis_flags.raise(); + ordered |= n.vis.paint_order != 0; + if let Some(packed) = n.scroll_edges.fade_style.packed_stops() { + debug_assert!( + fade_stops.is_none_or(|prev| prev == packed), + "ScrollFade::stops supports one explicit stop curve per window; got conflicting curves {fade_stops:?} vs {packed:?}" + ); + fade_stops = Some(packed); + } + } + self.tree.has_dissolve = dissolve; + self.tree.has_cache = cache; + self.tree.has_pixel_aspect = pix; + self.tree.has_drawn_layout = drawn_ly; + self.tree.has_key_up = key_up; + self.tree.has_sticky = self.holding() || sticky; + self.tree.has_raise = raise; + self.tree.has_paint_order = ordered; + self.tree.fade_stops = fade_stops.unwrap_or([0.0; 2]); + any_loop + } + + pub(in crate::runtime) fn prune_detached_tables(&mut self, prune_paths: bool) -> bool { + let any_loop = self.refresh_node_flags(); + self.paint.prune_caches(self.tree.has_cache, &self.scene, &mut self.text.atlas.resident_caches); + self.paint.prune_static_scales(&self.scene); + self.motion.prune_detached(&self.scene, &self.tree.node_index, REVEALS_KEPT); + if !self.commit.virtuals.is_empty() { + let Self { commit, tree, .. } = self; + commit.virtuals.retain(|path, _| tree.path_ids.get(path).is_some_and(|id| tree.node_index.contains_key(id))); + } + if prune_paths { + self.prune_path_ids(); + } + self.refresh_modal_index(); + any_loop + } + + pub(in crate::runtime) fn prune_exited(&mut self) { + // Fills last commit's spare buffer and keeps this one as the next spare: a few thousand + // nodes would otherwise grow a fresh Vec, megabytes, on every frame a node exits. + self.nodes_replaced(); + let mut old = std::mem::replace(&mut self.tree.nodes, std::mem::take(&mut self.tree.spare_nodes)); + self.tree.nodes.clear(); + self.tree.nodes.reserve(old.len()); + let mut remap = std::mem::take(&mut self.commit.apply_scratch.remap); + remap.clear(); + remap.resize(old.len(), None); + self.tree.node_index.rebuild(old.len()); + for (old_idx, mut n) in old.drain(..).enumerate() { + if !self.scene.contains(n.id) { + self.hover_pruned(&n); + self.motion.remove_reveal(n.id); + self.scroll.scrolls.remove(&n.id); + continue; + } + n.parent = n.parent.and_then(|p| remap[p]); + let idx = self.tree.nodes.len(); + remap[old_idx] = Some(idx); + self.tree.node_index.insert(n.id, idx); + self.tree.nodes.push(n); + } + self.tree.spare_nodes = old; + self.commit.memo.on_prune(&remap); + remap.clear(); + self.commit.apply_scratch.remap = remap; + self.prune_detached_tables(false); + if !self.paint.layer_paint_order().is_empty() || !self.motion.flying.is_empty() || self.tree.has_sticky || self.tree.has_raise || self.tree.has_paint_order { self.update_layer_paint_order(); } + // A removed element's live sources (a `Pixels` stream) stop waking this window. + if self.frame.has_live_subscriptions() { + let keep = self.frame.live.dirty(); + self.subscribe_live(); + self.frame.live.pruned(keep); + } + } +} diff --git a/app/vendor/rune/crates/rune/src/runtime/commit/prune_tests.rs b/app/vendor/rune/crates/rune/src/runtime/commit/prune_tests.rs new file mode 100644 index 0000000..2a817ff --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/commit/prune_tests.rs @@ -0,0 +1,150 @@ +use super::*; +use super::prune::REVEALS_KEPT; +use crate::{Env, GrowthSpec, ScrollSpec, col, el, text}; + +#[test] +fn static_scales_entry_is_pruned_when_exit_finishes() { + fn view(present: &bool, _: &mut Cx<bool>) -> El { + col().key("root").size(200.0, 200.0).children( + present.then(|| el().key("scaled").size(40.0, 40.0).scale(1.5)), + ) + } + let mut rt = Runtime::new(true, view, (200.0, 200.0), Env::new(true, 1.0)); + rt.frame(0.0); + let id = rt.tree.nodes.iter().find(|n| n.key.as_deref() == Some("scaled")).unwrap().id; + assert!(rt.paint.tracks_static_scale(id), "scaled node is tracked in static_scales"); + + rt.update(|on, _| *on = false); + for _ in 0..180 { + rt.frame(1.0 / 60.0); + if !rt.tree.nodes.iter().any(|n| n.id == id) { break; } + } + assert!(!rt.tree.nodes.iter().any(|n| n.id == id), "scaled node finished exiting"); + assert!(!rt.paint.tracks_static_scale(id), "exited node's static_scales entry must be pruned without waiting for another commit"); +} + +#[test] +fn launch_for_exited_flight_is_dropped_when_exit_finishes() { + #[derive(Default)] + struct S { show_target: bool } + fn view(s: &S, _: &mut Cx<S>) -> El { + col().key("root").size(300.0, 200.0) + .child(text("hello").key("src")) + .children(s.show_target.then(|| { + el().key("dst").absolute(150.0, 120.0).size(80.0, 24.0).child(text("hello")) + })) + } + let mut rt = Runtime::new(S::default(), view, (300.0, 200.0), Env::new(true, 1.0)); + rt.frame(0.0); + rt.update(|s, tx| { + s.show_target = true; + tx.launch("src", "dst"); + }); + rt.frame(1.0 / 60.0); + let dst_id = rt.tree.nodes.iter().find(|n| n.key.as_deref() == Some("dst")).unwrap().id; + assert!(rt.motion.flying.iter().any(|f| f.0 == dst_id), "launched node is flying"); + assert!(rt.motion.launches().flying(dst_id), "launch state tracks airborne flight"); + + // Remove the flying destination with an animated exit while still airborne. + rt.update(|s, _| s.show_target = false); + rt.frame(1.0 / 60.0); + assert!(rt.tree.nodes.iter().any(|n| n.id == dst_id), "destination stays mounted while exiting"); + assert!(rt.motion.flying.iter().any(|f| f.0 == dst_id), "exiting flight stays lifted"); + + // Let the exit finish with no further commit. + for _ in 0..180 { + rt.frame(1.0 / 60.0); + if !rt.tree.nodes.iter().any(|n| n.id == dst_id) { break; } + } + assert!(!rt.tree.nodes.iter().any(|n| n.id == dst_id), "destination finished exiting"); + assert!(!rt.motion.flying.iter().any(|f| f.0 == dst_id), "exited flight left flying"); + assert!(!rt.motion.launches().flying(dst_id), "airborne launch entry must be dropped when its exiting flight is pruned"); +} + +#[test] +fn reveals_stay_bounded_across_instant_unmounts_in_commit_apply() { + #[derive(Default)] + struct S { n: usize, present: bool } + fn view(s: &S, _: &mut Cx<S>) -> El { + col().key("root").w(300.0).children( + s.present.then(|| col().key(format!("p{}", s.n)).child(text("a b c").key("t").w_full().wrap().reveal(0.2))), + ) + } + let mut rt = Runtime::new(S::default(), view, (300.0, 200.0), Env::new(true, 1.0)); + rt.frame(0.0); + let mounted = rt.tree.path_ids.len(); + let mut instant_tx = Tx::default(); + instant_tx.instant(); + let count = REVEALS_KEPT * 2; + for n in 0..count { + rt.state.n = n; + rt.state.present = true; + rt.commit(&Tx::default()); + rt.state.present = false; + rt.commit(&instant_tx); + } + assert_eq!(rt.motion.reveals_map().len(), REVEALS_KEPT, "commit apply must cap orphan reveals even without prune_exited"); + assert!(rt.motion.reveals_kept_len() <= REVEALS_KEPT, "{} orphans tracked", rt.motion.reveals_kept_len()); + // At most the mounted paths, the REVEALS_KEPT orphan reveal paths, and the last unmounted parent still waiting for prune_exited. + assert!(rt.tree.path_ids.len() <= mounted + REVEALS_KEPT + 1, "{} paths kept", rt.tree.path_ids.len()); +} + +#[test] +fn resident_caches_and_node_flags_clear_when_exit_finishes() { + fn view(present: &bool, _: &mut Cx<bool>) -> El { + col().key("root").size(200.0, 200.0).scroll(ScrollSpec { stick_bottom: false }).children( + present.then(|| { + col().key("section").w_full().h(300.0) + .child(el().key("hdr").w_full().h(24.0).sticky_top(0.0).cache()) + }), + ) + } + let mut rt = Runtime::new(true, view, (200.0, 200.0), Env::new(true, 1.0)); + rt.frame(0.0); + let hdr_id = rt.tree.nodes.iter().find(|n| n.key.as_deref() == Some("hdr")).unwrap().id; + assert!(rt.tree.has_sticky, "sticky header sets has_sticky"); + assert!(rt.tree.has_cache, "cached header sets has_cache"); + // Simulate a resident GPU cache entry with no CPU-side node_caches entry. + rt.paint.node_caches.clear(); + rt.text.atlas.resident_caches.insert(hdr_id.0, 42); + + rt.update(|on, _| *on = false); + for _ in 0..180 { + rt.frame(1.0 / 60.0); + if !rt.tree.nodes.iter().any(|n| n.id == hdr_id) { break; } + } + assert!(!rt.tree.nodes.iter().any(|n| n.id == hdr_id), "section finished exiting"); + assert!(!rt.tree.has_sticky, "has_sticky clears when the last sticky node finishes exiting"); + assert!(!rt.tree.has_cache, "has_cache clears when the last cached node finishes exiting"); + assert!(!rt.text.atlas.resident_caches.contains_key(&hdr_id.0), "resident_caches clears even if node_caches was empty"); +} + +#[test] +fn virtual_list_stays_during_exit_and_prunes_when_exit_finishes() { + fn view(present: &bool, _: &mut Cx<bool>) -> El { + col().key("root").size(200.0, 200.0).children( + present.then(|| { + col().key("vp").size(200.0, 120.0).scroll(ScrollSpec { stick_bottom: false }).child( + col().key("list").w_full().growth(GrowthSpec::default()).virtualize(20.0) + .children((0..10).map(|i| el().key(format!("r{i}")).w_full().h(20.0))), + ) + }), + ) + } + let mut rt = Runtime::new(true, view, (200.0, 200.0), Env::new(true, 1.0)); + rt.frame(0.0); + let list_path = "root/vp/list"; + assert!(rt.commit.virtuals.contains_key(list_path), "virtual list registered"); + + rt.update(|on, _| *on = false); + rt.frame(1.0 / 60.0); + assert!(rt.tree.nodes.iter().any(|n| n.path == list_path), "list stays in nodes mid-exit"); + assert!(rt.commit.virtuals.contains_key(list_path), "virtual metadata stays while exiting"); + + for _ in 0..180 { + rt.frame(1.0 / 60.0); + if !rt.tree.nodes.iter().any(|n| n.path == list_path) { break; } + } + assert!(!rt.tree.nodes.iter().any(|n| n.path == list_path), "list finished exiting"); + assert!(rt.commit.virtuals.is_empty(), "virtual metadata pruned when exit finishes"); +} diff --git a/app/vendor/rune/crates/rune/src/runtime/commit/relayout.rs b/app/vendor/rune/crates/rune/src/runtime/commit/relayout.rs new file mode 100644 index 0000000..40ea0d5 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/commit/relayout.rs @@ -0,0 +1,380 @@ +//! Laying a flattened tree out: Taffy, then each node's place and text. +//! +//! A commit that only resized the window lays the last commit's nodes out again at the new +//! size, without running the view or flattening what it returns: with the state, scale and +//! everything else a view can read unchanged, the view would build the same tree. A view that +//! reads layout or the caret still runs when what it read moved. A virtual list keeps its +//! mounted rows, which lay out again like the rest; the view runs only when the list's window +//! has to move to rows it hasn't built. + +use super::*; + +/// What tells a resize whether the last commit's tree still holds. +#[derive(Default)] +pub(in crate::runtime) struct Reuse { + /// The scale the last commit built its view at. + pub(in crate::runtime) scale: f32, + /// A layout read moved this frame, so the view runs to see it. + pub(in crate::runtime) read_moved: bool, + /// The blend mode the last commit built its view in; theme colours resolve per mode. + pub(in crate::runtime) srgb: Option<bool>, +} + +impl Reuse { + /// Records what the commit just applied was built with. + pub(in crate::runtime) fn built(&mut self, scale: f32, srgb: bool) { + self.scale = scale; + self.srgb = Some(srgb); + } +} + +/// The root's size in a viewport; a window that fits its content takes its natural height. +pub(in crate::runtime) fn root_size(viewport: (f32, f32), fit_height: bool) -> Size<Dimension> { + Size { width: length(viewport.0), height: if fit_height { auto() } else { length(viewport.1) } } +} + +/// Whether a commit can lay `n` out again as it is. Layout rewrites the styles of +/// `aspect_fit` elements and fitted anchored overlays, and pictures can change their aspect. +/// Live bindings only own scene properties: moving the node retains their sources, sampled +/// values and exact fill, while `apply` leaves their scene tracks alone. +pub(in crate::runtime) fn reusable(n: &Node) -> bool { + n.cold.get().is_none_or(|c| { + c.aspect_fit.is_none() && c.above.as_ref().is_none_or(|a| !a.fit) && c.pixel_aspect.is_none() + }) +} + +/// How a commit measures, decided once before it starts. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(in crate::runtime) enum CommitKind { + /// Run the view and flatten what it returns. + Rebuild, + /// Only the window resized: lay the last commit's nodes out again at the new size. + Relayout, + /// Only virtual windows moved: keep mounted subtrees and build the rows that enter. + Remount, +} + +impl RuntimeCore { + /// Which way this commit measures. Both shortcuts need everything the view reads to be as + /// the last commit built it, checked here once for both. + pub(in crate::runtime) fn commit_kind(&self, tx: &Tx) -> CommitKind { + let unchanged = self.commit.state_unchanged && !tx.commit.lands() && !self.commit.reuse.read_moved + && self.commit.reuse.scale == self.env.scale && self.commit.reuse.srgb == Some(self.paint.srgb_blend()) + && !self.tree.has_playground && !self.patch_pending() + // Exiting nodes left the layout tree. + && self.commit.layout.live_count() == self.tree.nodes.len(); + if !unchanged { return CommitKind::Rebuild; } + if self.commit.relayout { + // The nodes it built are all there, in the layout tree's order. + return if self.tree.nodes.iter().all(reusable) { CommitKind::Relayout } else { CommitKind::Rebuild }; + } + if self.commit.virtual_only(&self.tree, self.frame.has_hot(), self.checking_live_only()) { CommitKind::Remount } else { CommitKind::Rebuild } + } + + /// Measures a commit: lays the last tree out again when only the viewport changed since it + /// was built, remounts virtual rows alone when only their window moved, else runs the view. + pub(in crate::runtime) fn measure_commit(&mut self, app: &dyn ViewDriver, tx: &Tx) -> Measured { + let kind = self.commit_kind(tx); + if kind == CommitKind::Relayout { + // The view keeps what it last read; `settle_layout_reads` and the caret check run it + // when the new layout moves them. + let reads = self.commit.layout_seen.reads.clone(); + let caret_read = self.edit.caret_watch; + let selection = self.selection_by_path(); + let (mut m, text) = self.measurement(app, true); + m.layout_reads = reads; + m.caret_read = caret_read; + return match m.relayout(text) { + Some(measured) => Measured { selection, ..measured }, + None => { + self.refresh_layout_seen(); + self.measure(app, tx) + } + }; + } + if kind == CommitKind::Remount { + let _blend = crate::theme::scope(self.paint.srgb_blend()); + let _bars = crate::platform::scroll_bars::scope(self.host.scroll_bars.state, self.host.scroll_bars.runtime_id); + let reads = self.commit.layout_seen.reads.clone(); + let caret_read = self.edit.caret_watch; + let selection = self.selection_by_path(); + let (mut m, text) = self.measurement(app, true); + m.layout_reads = reads; + m.caret_read = caret_read; + return match m.remount_virtuals(text) { + commit::remount::RemountOutcome::Measured(measured) => Measured { selection, ..measured }, + commit::remount::RemountOutcome::Retry => { + self.refresh_layout_seen(); + self.measure_retry(app, tx) + } + commit::remount::RemountOutcome::Fallback => { + self.refresh_layout_seen(); + self.measure(app, tx) + } + }; + } + self.refresh_layout_seen(); + self.measure(app, tx) + } +} + +impl Measurement<'_> { + /// Lays the last commit's nodes out again at the viewport, in its layout tree. None when a + /// virtual list's window has to move, which only the view can build. + fn relayout(mut self, text: &mut TextSystem) -> Option<Measured> { + self.anchor_virtuals(); + let len = self.nodes.len(); + let mut taffy = std::mem::replace(self.layout, LayoutEngine::with_capacity(0)); + let mut nodes = std::mem::take(self.spare_nodes); + nodes.clear(); + nodes.reserve(len); + for slot in self.nodes.iter_mut() { + if slot.input.is_some() || slot.is_secure() || slot.text.as_ref().is_some_and(|t| t.by_paragraph(false)) { + // The new nodes lay their text out again; the cache then holds the only reference. + // A by-paragraph field's goes with it, to re-break its paragraphs from. + let kept = slot.text_layout.take().filter(|l| matches!(l, TextLayout::Paragraphs(_))); + let mut copy = Node { elided: None, virtual_mount: false, text_layout: kept, epoch: crate::runtime::paint_keep::next_epoch(), ..slot.clone() }; + copy.clear_run_layout(); + nodes.push(copy); + } else { + let stub = Node::moved_stub(slot); + let mut n = std::mem::replace(slot, stub); + n.text_layout = None; + n.elided = None; + n.clear_run_layout(); + n.virtual_mount = false; + nodes.push(n); + } + } + self.mark_quiet_rows(&mut nodes); + let mut reused = std::mem::take(&mut self.memo.reused_scratch); + let mut split = std::mem::take(&mut self.memo.split_scratch); + build_relayout_spans(self.nodes, &nodes, self.virtuals, self.path_ids, self.node_index, &mut split, &mut reused); + self.memo.split_scratch = split; + let root = nodes[0].taffy; + let mut style = taffy.style(root).clone(); + style.set_size(root_size(self.viewport, self.fit_height)); + taffy.set_style_and_mark_ancestors(root, style, std::iter::empty()); + // As flattening does: secure leaves don't keep a measurement. + for n in nodes.iter().filter(|n| n.text.as_ref().is_some_and(|t| t.redacted)) { + taffy.mark_dirty_and_ancestors( + n.taffy, + std::iter::successors(n.parent, |&p| nodes[p].parent).map(|p| nodes[p].taffy), + ); + } + let (layout, mut nodes) = self.solve(text, taffy, root, nodes); + if self.measure_virtuals(&nodes, false) || self.windows_move() { + memo_reuse::restore_moved_nodes(self.nodes, &mut nodes, &reused, &[]); + reused.clear(); + self.memo.reused_scratch = reused; + nodes.clear(); + *self.spare_nodes = nodes; + *self.layout = layout; + return None; + } + // The mounted rows are the ones shown, so none was culled. + self.virtual_culled.clear(); + Some(Measured { + layout, + nodes, + reduced_motion: self.reduced_motion, + time_scale: self.time_scale, + zoom: self.zoom, + defaults: self.defaults.clone(), + titlebar: self.titlebar, + caret_read: self.caret_read, + layout_reads: self.layout_reads, + memo_flattened: None, + memo_reused: reused, + taken_paths: Vec::new(), + selection: Vec::new(), + }) + } + + /// Anchors each virtual list's reader to the first row in view, as a commit's window pass + /// does, so rows above it that rewrap leave it in place. + fn anchor_virtuals(&mut self) { + for v in self.virtuals.values_mut() { + let scroll = self.path_ids.get(&v.scroll_path).and_then(|id| self.scrolls.get(id)); + let sticky = || self.nodes.iter().find(|n| n.path == v.scroll_path).and_then(|n| n.scroll).is_some_and(|s| s.stick_bottom); + let held = scroll.map_or_else(sticky, |s| s.pinned()); + let (offset, pinned) = v.locate(scroll.map_or(0.0, |s| s.offset as f32), held); + v.anchor = if pinned || v.passed() { None } else { v.first_visible(offset.min(v.max_offset()), |_| true) }; + } + } + + /// Marks which nodes mount quietly, as `populate_virtual_children` marks a virtual list's rows. + fn mark_quiet_rows(&mut self, nodes: &mut [Node]) { + if self.virtuals.is_empty() { + return; + } + for (path, v) in self.virtuals.iter_mut() { + let Some(&list) = self.path_ids.get(path).and_then(|id| self.node_index.get(id)) else { continue }; + for n in nodes.iter_mut().skip(list + 1).filter(|n| n.parent == Some(list)) { + n.virtual_mount = n.key.as_deref().and_then(|k| v.index_of(k)).is_some_and(|row| v.mounts_quietly(row, self.commits)); + } + } + } + + /// Whether a virtual list's viewport came near the edge of its mounted rows, or its rows grew + /// a viewport past the overscan; the view then mounts the window again. + fn windows_move(&self) -> bool { + self.virtuals.values().any(|v| { + self.path_ids.get(&v.scroll_path).and_then(|id| self.scrolls.get(id)).is_some_and(|s| { + let (offset, pinned) = v.at(s.offset as f32, s.pinned()); + v.needs_window(offset, pinned) || v.spare(offset, pinned) > v.viewport + }) + }) + } + + /// Lays `nodes` out from `root_id` at the viewport, places them, and lays out their text. + pub(in crate::runtime) fn solve(&mut self, text: &mut TextSystem, mut taffy: LayoutEngine, root_id: SlotId, mut nodes: Vec<Node>) -> (LayoutEngine, Vec<Node>) { + let scale = self.env.scale; + let room = Size { + width: AvailableSpace::Definite(self.viewport.0), + height: if self.fit_height { AvailableSpace::MaxContent } else { AvailableSpace::Definite(self.viewport.1) }, + }; + { + let _layout_time = crate::frame::profile::Scope::new(crate::frame::profile::Phase::Layout); + compute_layout(&mut taffy, root_id, room, &nodes, text, scale); + // `aspect_fit` elements laid out filling their room; fix each at the largest box + // at its ratio inside it and lay out again, so siblings and alignment follow. + let mut refit = false; + for n in &nodes { + if let Some(fit) = &n.aspect_fit { + let style = fitted(fit.0, &fit.1, taffy.box_layout(n.taffy).size()); + taffy.set_style_and_mark_ancestors( + n.taffy, + style, + std::iter::successors(n.parent, |&p| nodes[p].parent).map(|p| nodes[p].taffy), + ); + refit = true; + } + } + if refit { compute_layout(&mut taffy, root_id, room, &nodes, text, scale); } + } + self.stats.layout_nodes = nodes.len(); + #[cfg(debug_assertions)] + layout_diagnostics::collapsed_scrolls(&taffy, &nodes); + + self.place(&taffy, &mut nodes); + if self.fit_anchored(&mut taffy, &nodes) { + compute_layout(&mut taffy, root_id, room, &nodes, text, scale); + self.place(&taffy, &mut nodes); + } + for n in nodes.iter_mut().filter(|n| n.text.is_some()) { + let w = (taffy.box_layout(n.taffy).w - n.inset[0] - n.inset[2]).max(0.0); + lay_out_text(text, n, w, scale); + } + + (taffy, nodes) + } +} + +/// Partitions the moved nodes of a `relayout` pass into disjoint subtree [`ReusedSpan`]s so +/// `clear_old_nodes` skips dropping every `moved_stub` and `clean_apply_spans` skips unchanged +/// subtrees (such as fixed-width sidebars or blocks that did not rewrap). +fn build_relayout_spans( + old_nodes: &[Node], + nodes: &[Node], + virtuals: &HashMap<String, crate::el::virtual_list::VirtualList>, + path_ids: &HashMap<String, NodeId>, + node_index: &NodeIndex, + split: &mut Vec<bool>, + out: &mut Vec<memo_reuse::ReusedSpan>, +) { + let len = nodes.len(); + out.clear(); + split.clear(); + split.resize(len, false); + let mark_up = |mut cur: Option<usize>, split: &mut [bool]| { + while let Some(p) = cur { + if split[p] { + break; + } + split[p] = true; + cur = nodes[p].parent; + } + }; + for path in virtuals.keys() { + if let Some(&list) = path_ids.get(path).and_then(|id| node_index.get(id)) + && list < len + { + mark_up(Some(list), split); + } + } + for i in 0..len { + if !old_nodes[i].is_moved_stub() { + mark_up(Some(i), split); + continue; + } + let has_children = nodes.get(i + 1).is_some_and(|c| c.parent == Some(i)); + let shallow = i == 0 || nodes[i].parent.is_some_and(|p| p == 0 || nodes[p].parent == Some(0)); + if has_children && shallow { + split[i] = true; + } + } + let mut i = 0usize; + while i < len { + if !old_nodes[i].is_moved_stub() { + i += 1; + continue; + } + let span_len = if split[i] { + 1 + } else { + let mut sub_end = i + 1; + while sub_end < len && nodes[sub_end].parent.is_some_and(|p| p >= i) { + sub_end += 1; + } + sub_end - i + }; + out.push(memo_reuse::ReusedSpan { + new_start: i, + old_start: i, + len: span_len, + same_path: true, + moved: true, + }); + i += span_len; + } +} + +/// Lays `n`'s text out again at the width it was laid out at. +pub(in crate::runtime) fn lay_out_text_in_place(text: &mut TextSystem, n: &mut Node, scale: f32) { + let w = (n.local.w - n.inset[0] - n.inset[2]).max(0.0); + lay_out_text(text, n, w, scale); +} + +/// Lays `n`'s text out at its content width `w`. +pub(in crate::runtime) fn lay_out_text(text: &mut TextSystem, n: &mut Node, w: f32, scale: f32) { + let Some(spec) = &n.text else { return }; + // A cell of a run draws from the run's layout (and keeps it cached) instead of its own. + let run = spec.cold.advance_in.as_ref().map(|(run, at)| (text.run_layout(run, spec.style, scale), *at)); + if let Some((r, _)) = run.filter(|(r, at)| r.x(*at).is_some()) { + n.text_layout = Some(TextLayout::Single(r.layout.clone())); + n.cold_mut().run_layout = Some(r); + return; + } + let wrap = spec.wrap.then_some(w * scale + super::text_layout::FIT_SLACK); + // A by-paragraph field keeps what its last layout (still on it) shares with this one. + let is_input = n.input.is_some(); + let mut layout = match text.layout_text(&spec.as_text_input(scale, is_input), is_input, scale, wrap, line_alignment(spec), n.text_layout.as_ref()) { + TextLayout::Single(l) => l, + TextLayout::Paragraphs(mut p) => { + text.prepare_highlights(&mut p, &spec.cold.highlights); + n.text_layout = Some(TextLayout::Paragraphs(p)); + n.elided = None; + return; + } + }; + let mut elided = None; + if spec.truncate && layout.full_width() > w * scale + 0.5 { + let (cut, e) = truncated(text, spec, scale, w * scale); + (layout, elided) = (cut, Some(e)); + } else if let Some((cut, e)) = clamped(text, spec, scale, w * scale, &layout) { + (layout, elided) = (cut, Some(e)); + } + n.text_layout = Some(TextLayout::Single(layout)); + n.elided = elided; +} diff --git a/app/vendor/rune/crates/rune/src/runtime/commit/remount.rs b/app/vendor/rune/crates/rune/src/runtime/commit/remount.rs new file mode 100644 index 0000000..8cf5931 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/commit/remount.rs @@ -0,0 +1,553 @@ +//! Remounting [`El::virtual_rows`](crate::El::virtual_rows) windows when a commit only shifted a +//! virtual scroll window or filled overscan (`CommitWhy::VIRTUAL`). +//! +//! With app state, scale, blend mode and layout reads unchanged, non-list nodes and rows already +//! mounted stay as they were: they move directly out of `self.nodes` into the new pass's node +//! buffer without running `view` or calling `RowSource::build` on staying rows. Only newly +//! entering rows (and unmounted focused or selection-pinned rows) build and flatten. + +use std::ops::Range; +use std::rc::Rc; + +use super::*; + +pub(in crate::runtime) enum RemountOutcome { + Measured(Measured), + Retry, + Fallback, +} + +struct ListPlan { + path: String, + old_list_idx: usize, + list_subtree_end: usize, + range: Range<usize>, + pad_top: f32, + pad_bottom: f32, + mounted_rows: HashMap<String, (usize, usize)>, + focused: Option<usize>, + pinned: Vec<usize>, + rows: Rc<crate::el::virtual_rows::RowSource>, + list_group: Option<String>, + inert: bool, + quiet: Vec<bool>, + built_rows: Vec<(usize, El)>, +} + +impl CommitState { + /// Whether a commit that resized nothing and changed nothing the view reads + /// ([`Runtime::commit_kind`]) only shifts or fills `virtual_rows` windows, so `view` and + /// already mounted subtrees need not rebuild. + pub(in crate::runtime) fn virtual_only(&self, tree: &types::TreeState, hot: bool, checking_live_only: bool) -> bool { + if hot || checking_live_only || self.virtuals.is_empty() || tree.nodes.is_empty() { + return false; + } + if !tree.nodes.iter().all(|n| { + relayout::reusable(n) && n.text.as_ref().is_none_or(|t| !t.redacted && t.cold.live.is_none()) + }) { + return false; + } + for (path, v) in &self.virtuals { + if !v.indexed || !v.selection.pins.source().and_then(|s| s.rebuild()).is_some_and(|s| s.count == v.keys.len()) { + return false; + } + let Some(&list_id) = tree.path_ids.get(path) else { return false }; + let Some(&list_idx) = tree.node_index.get(&list_id) else { return false }; + if !tree.nodes.get(list_idx).is_some_and(|n| n.id == list_id && n.path == *path && n.growth.is_some()) { + return false; + } + let Some(&scroll_id) = tree.path_ids.get(&v.scroll_path) else { return false }; + let Some(&scroll_idx) = tree.node_index.get(&scroll_id) else { return false }; + if !tree.nodes.get(scroll_idx).is_some_and(|n| { + n.id == scroll_id + && n.path == v.scroll_path + && n.scroll.is_some() + && !n.scroll_axes.x() + && n.growth.is_none() + }) { + return false; + } + if self.virtuals.keys().any(|other| { + other != path && other.strip_prefix(path.as_str()).is_some_and(|r| r.starts_with('/')) + }) { + return false; + } + } + true + } +} + +fn move_slice( + old_nodes: &mut [Node], + range: Range<usize>, + nodes: &mut Vec<Node>, + old_to_new: &mut [u32], + taffy: &mut LayoutEngine, + reused: &mut Vec<memo_reuse::ReusedSpan>, + root_virtual_mount: Option<bool>, +) { + if range.is_empty() { + return; + } + let start = range.start; + let len = range.len(); + let new_start = nodes.len(); + for (k, old_idx) in range.enumerate() { + let new_idx = new_start + k; + old_to_new[old_idx] = new_idx as u32; + let slot = &mut old_nodes[old_idx]; + taffy.reuse_slot(slot.taffy, new_idx as u32); + let old_parent = slot.parent; + let stub = Node::moved_stub(slot); + let mut n = std::mem::replace(slot, stub); + n.text_layout = None; + n.elided = None; + n.clear_run_layout(); + n.scale_track = false; + n.group_fade = false; + n.virtual_mount = if k == 0 { root_virtual_mount.unwrap_or(false) } else { false }; + n.parent = old_parent.map(|p| old_to_new[p] as usize); + n.target = [0.0; 4]; + n.local = MRect::ZERO; + n.inset = [0.0; 4]; + nodes.push(n); + } + reused.push(memo_reuse::ReusedSpan { + new_start, + old_start: start, + len, + same_path: true, + moved: true, + }); +} + +fn build_indexed_row( + rows: &crate::el::virtual_rows::RowSource, + state: crate::states::StatesRef<'_>, + path: &str, + key: &str, + i: usize, + key_warnings: &mut Option<Vec<String>>, +) -> El { + let tag = crate::memo::virtual_row_tag(path, key); + let mut row = crate::memo::in_virtual_row(tag, || (rows.build)(state, i)).key(key.to_owned()); + if crate::input::key_diagnostics::clean(&row) { + return row; + } + let duplicates = crate::input::key_diagnostics::repair_at(&mut row, &format!("{path}/{key}")); + match key_warnings.as_mut() { + Some(out) => out.extend(duplicates.into_iter().map(|d| d.message)), + None => crate::input::key_diagnostics::warn_once(&duplicates), + } + row +} + +impl Measurement<'_> { + pub(in crate::runtime) fn remount_virtuals(mut self, text: &mut TextSystem) -> RemountOutcome { + self.virtual_culled.clear(); + self.virtual_inputs.clear(); + + let mut plans = Vec::with_capacity(self.virtuals.len()); + for (path, v) in self.virtuals.iter_mut() { + let list_id = self.path_ids[path]; + let old_list_idx = self.node_index[&list_id]; + let scroll_id = self.path_ids[&v.scroll_path]; + let scroll_idx = self.node_index[&scroll_id]; + + let mut list_subtree_end = old_list_idx + 1; + while list_subtree_end < self.nodes.len() + && self.nodes[list_subtree_end].parent.is_some_and(|p| p >= old_list_idx) + { + list_subtree_end += 1; + } + let mut mounted_rows = HashMap::default(); + let mut cur = old_list_idx + 1; + while cur < list_subtree_end { + debug_assert_eq!(self.nodes[cur].parent, Some(old_list_idx)); + let mut row_end = cur + 1; + while row_end < list_subtree_end + && self.nodes[row_end].parent.is_some_and(|p| p >= cur) + { + row_end += 1; + } + if let Some(k) = &self.nodes[cur].key { + mounted_rows.insert(k.clone(), (cur, row_end)); + } + cur = row_end; + } + + let sticky = self.nodes[scroll_idx].scroll.unwrap().stick_bottom; + let old_scroll = self.scrolls.get(&scroll_id); + let held = old_scroll.map_or(sticky, |s| s.pinned()); + let offset = old_scroll.map_or(0.0, |s| s.offset as f32); + v.viewport = self.nodes[scroll_idx].local.h; + let (mut offset, pinned) = v.locate(offset, held); + v.anchor = if pinned || v.passed() { None } else { v.first_visible(offset, |_| true) }; + let delta = v.anchor_delta(); + offset = (offset + delta).max(0.0); + if let Some(st) = self.scrolls.get_mut(&scroll_id) && !held { + st.offset = (st.offset + f64::from(delta)).max(0.0); + } + let shown = std::mem::take(&mut v.shown); + v.select(offset, pinned, Some(&shown)); + for key in shown.iter().filter(|k| v.index_of(k).is_some_and(|i| !v.range.contains(&i))) { + self.virtual_culled.insert(format!("{path}/{key}")); + } + v.shown = shown; + + let list_group = v.selection.scope.group_path.clone(); + let inert = v.selection.scope.inert; + // Cleared in place: a later plan that falls back keeps this list's buffers too. + v.selection.pins.clear_texts(); + let rows = v.selection.pins.source().and_then(|s| s.rebuild()) + .expect("an index-built list keeps its row builder").clone(); + + let under = |f: &str| f.strip_prefix(path.as_str()).is_some_and(|rest| rest.starts_with('/')); + let focused = v + .focused_row + .as_deref() + .filter(|_| self.focused.is_some_and(under)) + .and_then(|key| v.index_of(key)) + .filter(|i| !v.range.contains(i)); + let pinned_rows: Vec<usize> = v + .selection + .pins + .rows() + .iter() + .filter_map(|key| v.index_of(key)) + .filter(|i| !v.range.contains(i)) + .collect(); + + plans.push(ListPlan { + path: path.clone(), + old_list_idx, + list_subtree_end, + range: v.range.clone(), + pad_top: v.pad_top + v.before, + pad_bottom: v.pad_bottom + v.after, + mounted_rows, + focused, + pinned: pinned_rows, + rows, + list_group, + inert, + quiet: Vec::new(), + built_rows: Vec::new(), + }); + } + plans.sort_unstable_by_key(|p| p.old_list_idx); + + let mut kept_rows = HashSet::default(); + for plan in &plans { + let keys = &self.virtuals[&plan.path].keys; + for row_i in plan.range.clone() { + let key = &keys[row_i]; + if plan.mounted_rows.contains_key(key) { + kept_rows.insert(crate::memo::virtual_row_tag(&plan.path, key)); + } + } + } + + let memo = crate::memo::enter_partial( + std::mem::take(self.memo), + &kept_rows, + self.env, + self.system_accent, + self.system_reduced_motion, + crate::theme::blends_srgb(), + self.chrome_bits(), + self.caret.clone(), + self.layout_seen.clone(), + ); + let view_time = crate::frame::profile::Scope::new(crate::frame::profile::Phase::View); + let state = self.app.states_ref(); + let mut nested_virtual = false; + for plan in &mut plans { + let v = self.virtuals.get_mut(&plan.path).unwrap(); + if let Some(i) = plan.focused { + let row = build_indexed_row(&plan.rows, state, &plan.path, &v.keys[i], i, self.key_warnings); + measure::collect_virtual_inputs(&row, &plan.path, i, plan.inert, self.virtual_inputs); + if plan.pinned.contains(&i) { + selectable::virtual_selection::collect_row_into_pins( + &mut v.selection.pins, + &row, + &plan.path, + &v.keys[i], + i, + plan.list_group.as_deref(), + plan.inert, + ); + } + } + for &i in &plan.pinned { + if Some(i) == plan.focused { + continue; + } + let row = build_indexed_row(&plan.rows, state, &plan.path, &v.keys[i], i, self.key_warnings); + selectable::virtual_selection::collect_row_into_pins( + &mut v.selection.pins, + &row, + &plan.path, + &v.keys[i], + i, + plan.list_group.as_deref(), + plan.inert, + ); + } + for (pos, row_i) in plan.range.clone().enumerate() { + let key = &v.keys[row_i]; + if !plan.mounted_rows.contains_key(key) { + let row = build_indexed_row(&plan.rows, state, &plan.path, key, row_i, self.key_warnings); + if row.flags.has(crate::el::ElFlags::HAS_VIRTUAL) { + nested_virtual = true; + break; + } + plan.built_rows.push((pos, row)); + } + } + if nested_virtual { + break; + } + } + let (memo, replayed) = memo.finish(); + drop(view_time); + *self.memo = memo; + if nested_virtual { + return RemountOutcome::Fallback; + } + self.caret_read |= replayed.caret; + for read in replayed.layout { + layout_read::note_read_at(&mut self.layout_reads, &read.key, read.same, read.at); + } + + for plan in &mut plans { + let v = self.virtuals.get_mut(&plan.path).unwrap(); + plan.quiet = plan.range.clone().map(|i| v.mounts_quietly(i, self.commits)).collect(); + for (pos, row) in &mut plan.built_rows { + row.flags.set(crate::el::ElFlags::VIRTUAL_MOUNT, plan.quiet[*pos]); + } + } + + let mut on_spine = vec![false; self.nodes.len()]; + for plan in &plans { + on_spine[plan.old_list_idx] = true; + let mut cur = self.nodes[plan.old_list_idx].parent; + while let Some(p) = cur { + if on_spine[p] { + break; + } + on_spine[p] = true; + cur = self.nodes[p].parent; + } + } + + let scale = self.env.scale; + let mut taffy = std::mem::replace(self.layout, LayoutEngine::with_capacity(0)); + taffy.begin_commit(); + let mut nodes = std::mem::take(self.spare_nodes); + nodes.clear(); + nodes.reserve(self.nodes.len().max(32)); + let mut pending = std::mem::take(&mut self.memo.pending_scratch); + pending.clear(); + let mut reused = std::mem::take(&mut self.memo.reused_scratch); + reused.clear(); + let mut path_buf = std::mem::take(&mut self.memo.path_scratch); + path_buf.clear(); + let empty_committed = HashMap::default(); + + let mut old_to_new = vec![u32::MAX; self.nodes.len()]; + let mut plan_iter = plans.into_iter().peekable(); + let mut old_idx = 0usize; + while old_idx < self.nodes.len() { + if plan_iter.peek().is_some_and(|p| p.old_list_idx == old_idx) { + let plan = plan_iter.next().unwrap(); + let new_list_idx = nodes.len(); + old_to_new[old_idx] = new_list_idx as u32; + let (list_id, list_taffy, list_motion, list_in_row) = { + let slot = &mut self.nodes[old_idx]; + let old_parent = slot.parent; + let stub = Node::moved_stub(slot); + let mut n = std::mem::replace(slot, stub); + n.text_layout = None; + n.elided = None; + n.clear_run_layout(); + n.scale_track = false; + n.group_fade = false; + n.virtual_mount = false; + n.parent = old_parent.map(|p| old_to_new[p] as usize); + n.target = [0.0; 4]; + n.local = MRect::ZERO; + n.inset = [0.0; 4]; + let info = (n.id, n.taffy, n.motion, n.in_row); + nodes.push(n); + info + }; + reused.push(memo_reuse::ReusedSpan { + new_start: new_list_idx, + old_start: old_idx, + len: 1, + same_path: true, + moved: true, + }); + + let mut list_style = taffy.style(list_taffy).clone(); + list_style.set_pad_top(plan.pad_top); + list_style.set_pad_bottom(plan.pad_bottom); + let parent_row = matches!( + list_style.flex_direction(), + FlexDirection::Row | FlexDirection::RowReverse + ); + + let mut row_slots = Vec::with_capacity(plan.range.len()); + let mut any_row_dirty = false; + let mut built_iter = plan.built_rows.into_iter().peekable(); + let keys = &self.virtuals[&plan.path].keys; + for (pos, row_i) in plan.range.clone().enumerate() { + if built_iter.peek().is_some_and(|(p, _)| *p == pos) { + let (_, row_el) = built_iter.next().unwrap(); + path_buf.clear(); + path_buf.push_str(&nodes[new_list_idx].path); + let mut memo_ctx = memo_reuse::MemoFlattenCtx { + old_nodes: &mut *self.nodes, + old_present_len: 0, + old_node_index: &*self.node_index, + old_cursor: 0, + committing: self.committing, + committed: &empty_committed, + pending, + reused, + taken_paths: Vec::new(), + path_ids: &mut *self.path_ids, + next_id: &mut *self.next_id, + foreground: self.defaults.foreground, + }; + let (kid_slot, kid_dirty) = flatten_with_buf( + row_el, + Some(new_list_idx), + &mut path_buf, + pos, + list_motion, + list_in_row, + parent_row, + &mut taffy, + &mut nodes, + scale, + &mut memo_ctx, + ); + pending = memo_ctx.pending; + reused = memo_ctx.reused; + row_slots.push(kid_slot); + any_row_dirty |= kid_dirty; + } else { + let &(rs, re) = &plan.mounted_rows[&keys[row_i]]; + let row_taffy = self.nodes[rs].taffy; + move_slice( + self.nodes, + rs..re, + &mut nodes, + &mut old_to_new, + &mut taffy, + &mut reused, + Some(plan.quiet[pos]), + ); + row_slots.push(row_taffy); + } + } + + let child_mark = taffy.begin_children(); + for s in row_slots { + taffy.push_child(s); + } + let (slot, dirty) = taffy.sync_node( + list_id.0, + new_list_idx as u32, + list_style, + None, + false, + child_mark, + any_row_dirty, + ); + debug_assert_eq!(slot, list_taffy); + if dirty { + taffy.mark_dirty_and_ancestors( + list_taffy, + std::iter::successors(nodes[new_list_idx].parent, |&p| nodes[p].parent) + .map(|p| nodes[p].taffy), + ); + } + old_idx = plan.list_subtree_end; + } else if on_spine[old_idx] { + move_slice( + self.nodes, + old_idx..old_idx + 1, + &mut nodes, + &mut old_to_new, + &mut taffy, + &mut reused, + None, + ); + old_idx += 1; + } else { + let mut sub_end = old_idx + 1; + while sub_end < self.nodes.len() + && self.nodes[sub_end].parent.is_some_and(|p| p >= old_idx) + { + sub_end += 1; + } + move_slice( + self.nodes, + old_idx..sub_end, + &mut nodes, + &mut old_to_new, + &mut taffy, + &mut reused, + None, + ); + old_idx = sub_end; + } + } + + path_buf.clear(); + self.memo.path_scratch = path_buf; + taffy.finish_flatten(); + let root_id = nodes[0].taffy; + let (layout, mut nodes) = self.solve(text, taffy, root_id, nodes); + if self.measure_virtuals(&nodes, false) { + memo_reuse::restore_moved_nodes(self.nodes, &mut nodes, &reused, &[]); + nodes.clear(); + *self.spare_nodes = nodes; + pending.clear(); + reused.clear(); + self.memo.pending_scratch = pending; + self.memo.reused_scratch = reused; + *self.layout = layout; + return RemountOutcome::Retry; + } + RemountOutcome::Measured(Measured { + layout, + nodes, + reduced_motion: self.reduced_motion, + time_scale: self.time_scale, + zoom: self.zoom, + defaults: self.defaults.clone(), + titlebar: self.titlebar, + caret_read: self.caret_read, + layout_reads: self.layout_reads, + memo_flattened: Some(pending), + memo_reused: reused, + taken_paths: Vec::new(), + selection: Vec::new(), + }) + } +} + +#[cfg(test)] +impl<S: 'static> Runtime<S> { + /// Runs one remount pass on its own and says whether it fell back, so a test can read what + /// the fallback left in the lists before the full rebuild that follows it fills them again. + pub(in crate::runtime) fn remount_falls_back(&mut self) -> bool { + let (core, app) = self.split_mut(); + let (m, text) = core.measurement(&app, true); + matches!(m.remount_virtuals(text), RemountOutcome::Fallback) + } +} diff --git a/app/vendor/rune/crates/rune/src/runtime/commit/text_layout.rs b/app/vendor/rune/crates/rune/src/runtime/commit/text_layout.rs new file mode 100644 index 0000000..c4cc158 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/commit/text_layout.rs @@ -0,0 +1,495 @@ +use super::*; + +pub(in crate::runtime) trait CeilTo { + fn ceil_to(self, scale: f32) -> f32; +} + +impl CeilTo for f32 { + /// Rounds up to whole device pixels. + fn ceil_to(self, scale: f32) -> f32 { + (self * scale - 1e-3).ceil() / scale + } +} + +pub(crate) use crate::text::text_width; + +/// Device px a text may run past the width it wraps at and still fit: [`text_width`] can round +/// a box up to 1e-3 px under its text, and points to device px and back loses a little more, so +/// a text laid out again in its own shrink-to-fit box would otherwise wrap its last word. Blink +/// compares both in the same `LayoutUnit`s, where they're equal. +pub(crate) const FIT_SLACK: f32 = 1.0 / 256.0; + +/// How far a single-line field's text shifts left (device px) so its caret stays inside +/// `visible` device px. Unfocused fields rest at their start, like a native text field. +pub(in crate::runtime) fn single_line_scroll(scrolls: &mut HashMap<String, f32>, path: &str, inp: &crate::el::InputSpec, content: &str, layout: &Layout<Ink>, s: f32, visible: f32) -> f32 { + if !inp.edit.focused { + scrolls.remove(path); + return 0.0; + } + let scroll = single_line_offset(scrolls.get(path).copied().unwrap_or(0.0), inp, content, layout, s, visible); + scrolls.insert(path.to_owned(), scroll / s); + scroll +} + +/// [`single_line_scroll`] for a focused field, from its previous shift `prev` in points. +pub(in crate::runtime) fn single_line_offset(prev: f32, inp: &crate::el::InputSpec, content: &str, layout: &Layout<Ink>, s: f32, visible: f32) -> f32 { + let caret_w = (1.5 * s).round(); + let caret = Cursor::from_byte_index(layout, caret_index(&inp.edit, content), Affinity::Downstream); + let cx = crate::text::cursor_geometry(&caret, layout, 1.5 * s).x0 as f32; + // A right-to-left field runs from its right edge: measure from there and shift rightward. + let (cx, sign) = match crate::el::Flow::of_layout(layout) { + crate::el::Flow::Ltr => (cx, 1.0), + crate::el::Flow::Rtl => (layout.full_width() - cx, -1.0), + }; + let mut scroll = prev * s * sign; + if cx - scroll > visible - caret_w { + scroll = cx - visible + caret_w; + } + sign * scroll.min(cx).clamp(0.0, (layout.full_width() + caret_w - visible).max(0.0)) +} + +/// The display byte index the caret sits at, inside any IME preedit. +pub(crate) fn caret_index(e: &crate::edit::TextEdit, content: &str) -> usize { + match e.preedit() { + Some((p, Some((_, c)))) => (e.range().0 + c.min(p.len())).min(content.len()), + Some((p, None)) => (e.range().0 + p.len()).min(content.len()), + None => e.display_index(e.focus).min(content.len()), + } +} + +/// Parley line alignment for a text node: only wrapped text aligns per line. +pub(in crate::runtime) fn line_alignment(spec: &TextSpec) -> parley::Alignment { + match spec.align { + _ if spec.wrap && spec.justify => parley::Alignment::Justify, + Align::Center if spec.wrap => parley::Alignment::Center, + Align::End if spec.wrap => parley::Alignment::End, + _ => parley::Alignment::Start, + } +} + +/// The rectangle a text node's laid-out lines cover inside its drawn box `r` (logical points), +/// and the layout origin its glyphs are placed from. Lines aligned inside a wrap width count +/// from their own offsets, so the rect hugs the text rather than the box. +pub(in crate::runtime) fn text_extent(n: &Node, spec: &TextSpec, layout: TextFlow<'_>, r: [f32; 4], scale: f32) -> (MRect, [f32; 2]) { + let (x0, x1) = (r[0] + n.inset[0], r[0] + r[2] - n.inset[2]); + let (lo, hi) = layout.extent().unwrap_or((0.0, layout.full_width())); + let origin = [text_x(spec, x0, x1, layout.full_width() / scale, layout.flow()), r[1] + n.inset[1]]; + let x = origin[0] + lo / scale; + (MRect::new(x, origin[1], ((hi - lo) / scale).min(x1 - x).max(0.0), + (layout.spec_height(spec.style, scale, spec.exact_lines) / scale).min(r[3] - n.inset[1] - n.inset[3])), origin) +} + +/// Where a `width`-wide text line starts between `x0` and `x1`. Wrapped text aligns each line +/// inside the wrap width itself, so it starts at `x0`. A right-to-left paragraph (`flow`, its +/// layout's base level) starts at its right edge; wrapped, its lines already end there. +pub(in crate::runtime) fn text_x(spec: &TextSpec, x0: f32, x1: f32, width: f32, flow: crate::el::Flow) -> f32 { + use crate::el::Flow; + if line_alignment(spec) != parley::Alignment::Start || (flow == Flow::Rtl && spec.wrap) { + return x0; + } + match (spec.align, flow) { + (Align::Start, Flow::Ltr) | (Align::End, Flow::Rtl) => x0, + (Align::Center, _) => x0 + (x1 - x0 - width) * 0.5, + (Align::End, Flow::Ltr) | (Align::Start, Flow::Rtl) => x1 - width, + } +} + +impl Node { + /// Whether the text shows less than its whole content: cut by `El::truncate` or a line + /// clamp, or running past its box under `El::truncate_fade`. A fade keeps the whole + /// content in its layout, so it has no [`Elision`]; it only reads as cut. + pub(crate) fn text_cut(&self, scale: f32) -> bool { + self.elided.is_some() + || self.text.as_ref().is_some_and(|t| t.truncate_fade) && self.run_layout.is_none() + && self.text_layout.as_ref().is_some_and(|l| l.view().full_width() > (self.local.w - self.inset[0] - self.inset[2]).max(0.0) * scale + 0.5) + } +} + +/// Where truncation cut a text: it draws `content[..head]`, "…", then `content[tail..]`. +/// Selections and links stay in content bytes and map through this onto the drawn layout. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct Elision { + pub(crate) head: usize, + pub(crate) tail: usize, +} + +impl Elision { + pub(in crate::runtime) const ELLIPSIS: &str = "…"; + + /// The drawn byte just past the ellipsis. + pub(in crate::runtime) fn after(self) -> usize { self.head + Self::ELLIPSIS.len() } + + /// The content byte at drawn byte `i`. Past the ellipsis is the end of what it hides. + pub(crate) fn content(self, i: usize) -> usize { + if i <= self.head { i } else if i < self.after() { self.tail } else { self.tail + (i - self.after()) } + } + + /// The drawn byte at content byte `i`. A hidden byte lands before the ellipsis, or after it + /// for a range's `end`, so a range reaching into the cut covers the ellipsis. + pub(crate) fn drawn(self, i: usize, end: bool) -> usize { + if i <= self.head { i } else if i < self.tail { if end { self.after() } else { self.head } } else { self.after() + (i - self.tail) } + } + + /// Selected content bytes `a..b` as drawn bytes: a selection reaching into the cut + /// highlights the ellipsis. + pub(crate) fn range(self, a: usize, b: usize) -> (usize, usize) { (self.drawn(a, false), self.drawn(b, true)) } + + /// A span's or link's content bytes `a..b` as drawn bytes. A range wholly inside the cut + /// comes back empty and one crossing an edge keeps its visible side. A link takes the + /// ellipsis only when it shows on both sides of it. A span also takes it when it covers the + /// first byte the cut hides and shows next to it, so "…" wears the style of the text it + /// replaces, as AppKit's truncation draws it. + pub(crate) fn mark(self, a: usize, b: usize, link: bool) -> (usize, usize) { + let (h, t, after) = (self.head, self.tail, self.after()); + if b <= h { return (a, b) } + if a >= t { return (after + a - t, after + b - t) } + let (before, beyond) = (a < h, b > t); + let ellipsis = if link { before && beyond } else { a <= h && (before || beyond) }; + let start = if before { a } else if ellipsis { h } else { after }; + let end = if beyond { after + b - t } else if ellipsis { after } else { h }; + if start < end { (start, end) } else { (start, start) } + } + + /// The drawn string's length for content `len` bytes long. + pub(crate) fn drawn_len(self, len: usize) -> usize { self.drawn(len, true) } + + /// `spans` moved onto the drawn string. + pub(in crate::runtime) fn spans(self, spans: &[crate::text::Span]) -> Vec<crate::text::Span> { + let mut out = Vec::with_capacity(spans.len()); + self.spans_into(spans, &mut out); + out + } + + pub(in crate::runtime) fn spans_into(self, spans: &[crate::text::Span], out: &mut Vec<crate::text::Span>) { + out.clear(); + if spans.is_empty() { + return; + } + out.extend(spans.iter().map(|sp| { + let (start, end) = self.mark(sp.start as usize, sp.end as usize, false); + crate::text::Span { start: start as u32, end: end as u32, ..sp.clone() } + })); + } + + /// `rings` moved onto the drawn string. + pub(in crate::runtime) fn rings(self, rings: &[(u32, u32, Color, f32)]) -> Vec<(u32, u32, Color, f32)> { + rings.iter().filter_map(|&(a, b, c, w)| { + let (start, end) = self.mark(a as usize, b as usize, false); + (start < end).then_some((start as u32, end as u32, c, w)) + }).collect() + } + + /// `strikes` moved onto the drawn string. + pub(in crate::runtime) fn strikes(self, strikes: &[(u32, u32, Option<Color>)]) -> Vec<(u32, u32, Option<Color>)> { + strikes.iter().filter_map(|&(a, b, c)| { + let (start, end) = self.mark(a as usize, b as usize, false); + (start < end).then_some((start as u32, end as u32, c)) + }).collect() + } + + /// `highlights` moved onto the drawn string. + pub(in crate::runtime) fn highlights(self, highlights: &[crate::text::TextHighlight]) -> Vec<crate::text::TextHighlight> { + highlights.iter().filter_map(|h| { + let (start, end) = self.mark(h.start as usize, h.end as usize, false); + (start < end).then(|| crate::text::TextHighlight { start: start as u32, end: end as u32, ..h.clone() }) + }).collect() + } +} + +fn spec_elide_keys(spec: &TextSpec, scale: f32, mode: u8, param: usize, max_w: f32, align: parley::Alignment) -> Option<(u64, u64)> { + if spec.redacted { + return None; + } + let shape = spec.shape_key(scale).unwrap_or_else(|| spec.fresh_shape_key(scale)); + let blocks = spec.cold.blocks.iter().any(|&b| b != crate::edit::Block::Paragraph).then_some(spec.cold.blocks.as_slice()); + Some((shape, crate::text::elide_key(shape, mode, param, max_w, align, blocks))) +} + +/// `spec`'s content cut to fit `max_w` device px with an ellipsis, keeping as many whole +/// graphemes as fit at the start, the end or both ends (half each) as its `elide` says. +/// Whitespace graphemes beside the ellipsis are dropped whole. +pub(in crate::runtime) fn truncated(text: &mut TextSystem, spec: &TextSpec, scale: f32, max_w: f32) -> (Rc<Layout<Ink>>, Elision) { + use unicode_segmentation::UnicodeSegmentation; + let keys = spec_elide_keys(spec, scale, 0, spec.elide as usize, max_w, parley::Alignment::Start); + if let Some((_, key)) = keys + && let Some(hit) = text.get_elision(key) + { + return (hit.layout, Elision { head: hit.head, tail: hit.tail }); + } + let content = spec.content.as_str(); + let bounds: Vec<usize> = content.grapheme_indices(true).map(|(i, _)| i).chain([content.len()]).collect(); + let n = bounds.len() - 1; + let blank = |g: usize| content[bounds[g]..bounds[g + 1]].chars().all(char::is_whitespace); + let cut = |k: usize| { + let (mut head, tail) = match spec.elide { + crate::el::Elide::End => (k, 0), + crate::el::Elide::Middle => (k - k / 2, k / 2), + crate::el::Elide::Head => (0, k), + }; + let mut tail = n - tail; + while head > 0 && blank(head - 1) { head -= 1; } + while tail < n && blank(tail) { tail += 1; } + Elision { head: bounds[head], tail: bounds[tail] } + }; + let mut str_buf = if spec.redacted { String::new() } else { String::with_capacity(content.len() + Elision::ELLIPSIS.len()) }; + let mut span_buf = Vec::new(); + let input = spec.as_text_input(scale, false); + let mut make = |text: &mut TextSystem, e: Elision| { + e.spans_into(&spec.spans, &mut span_buf); + if spec.redacted { + let s = zeroize::Zeroizing::new([&content[..e.head], Elision::ELLIPSIS, &content[e.tail..]].concat()); + text.layout_cut(&input, &s, &span_buf, scale, None, parley::Alignment::Start, false) + } else { + str_buf.clear(); + str_buf.push_str(&content[..e.head]); + str_buf.push_str(Elision::ELLIPSIS); + str_buf.push_str(&content[e.tail..]); + text.layout_cut(&input, &str_buf, &span_buf, scale, None, parley::Alignment::Start, true) + } + }; + let (mut lo, mut hi) = (0usize, n); + let mut best: Option<(usize, Rc<Layout<Ink>>, Elision)> = None; + while lo < hi { + let mid = (lo + hi).div_ceil(2); + let e = cut(mid); + let l = make(text, e); + if l.full_width() <= max_w + 0.5 { + lo = mid; + best = Some((mid, l, e)); + } else { + hi = mid - 1; + } + } + let (layout, e) = match best { + Some((k, l, e)) if k == lo => (l, e), + _ => { + let e = cut(lo); + (make(text, e), e) + } + }; + if let Some((shape, key)) = keys { + text.insert_elision( + key, + shape, + e.drawn_len(content.len()), + crate::text::CachedElision { layout: layout.clone(), head: e.head, tail: e.tail }, + ); + } + (layout, e) +} + +/// Drops the text layouts of the last commit's nodes this pass flattened again (`nodes`, laid +/// out in `taffy`), before measuring, so the layout cache holds the only reference to each and a +/// width change re-breaks it in place rather than copying it. Nodes that leave keep theirs to +/// draw their exit. A text that was edited (typed into, streamed onto) tells the cache its old +/// version's layouts are done; one replaced by unrelated text may be shown again. +pub(in crate::runtime) fn release_kept_layouts( + old: &mut [Node], + nodes: &mut [Node], + taffy: &LayoutEngine, + text: &mut TextSystem, + reused: &[memo_reuse::ReusedSpan], +) { + let mut sorted_buf: Vec<(usize, usize)> = Vec::new(); + let ordered = reused.windows(2).all(|w| w[0].old_start <= w[1].old_start); + if !ordered { + sorted_buf.extend(reused.iter().map(|s| (s.old_start, s.len))); + sorted_buf.sort_unstable_by_key(|s| s.0); + } + let span_len = if ordered { reused.len() } else { sorted_buf.len() }; + let span_at = |k: usize| if ordered { (reused[k].old_start, reused[k].len) } else { sorted_buf[k] }; + let mut ri = 0usize; + let mut oi = 0usize; + while oi < old.len() { + while ri < span_len && { let (s, l) = span_at(ri); s + l <= oi } { + ri += 1; + } + if ri < span_len && { let (s, l) = span_at(ri); oi >= s && oi < s + l } { + let (start, len) = span_at(ri); + let end = (start + len).min(old.len()); + for o in &mut old[oi..end] { + o.text_layout = None; + } + oi = end; + continue; + } + let o = &mut old[oi]; + oi += 1; + let (Some(was), Some(now_idx)) = (o.text.as_deref(), taffy.mounted_node_index(o.id.0)) else { continue }; + let laid = o.text_layout.take(); + let Some(next) = nodes.get_mut(now_idx).filter(|n| n.id == o.id) else { continue }; + // A by-paragraph field lays its next text out from this one, keeping the paragraphs + // they share; measuring reads it there, and laying the text out replaces it. + if next.text_layout.is_none() + && (next.input.is_some() || next.text.as_ref().is_some_and(|t| t.by_paragraph(false))) + && let Some(l @ TextLayout::Paragraphs(_)) = laid + { + next.text_layout = Some(l); + } + if let (Some((_, shape)), Some(now)) = (was.shape, next.text.as_deref()) && now.shape != was.shape && edited(&was.content, &now.content) { + text.supersede(shape); + } + } +} + +/// Whether `now` reads as an edit of `was`: what they share at the start and end is at least +/// half the longer one. +pub(in crate::runtime) fn edited(was: &str, now: &str) -> bool { + let (a, b) = (was.as_bytes(), now.as_bytes()); + // Compared in blocks: a long draft's keystroke compares it in a few dozen memcmps. + let prefix = crate::text::common_start(a, b); + let suffix = crate::text::common_end(a, b).min(a.len().min(b.len()) - prefix); + prefix + suffix < a.len().max(b.len()) && 2 * (prefix + suffix) >= a.len().max(b.len()) +} + +/// Lays out the flattened tree in `room`, measuring text leaves. Not generic over the app state, +/// so Taffy's layout code is instantiated once, not once per `Runtime<S>`. +pub(in crate::runtime) fn compute_layout(taffy: &mut LayoutEngine, root: SlotId, room: Size<AvailableSpace>, nodes: &[Node], text: &mut TextSystem, scale: f32) { + text.forget_diff(); + taffy.compute_layout(root, room, |inputs, ctx, style| { + taffy::compute_leaf_layout(inputs, style, |_, _| 0.0, |known, avail| { + let Some(i) = ctx else { return Size::ZERO }; + let Some(spec) = nodes[i].text.as_ref() else { + return picture_size(known, avail, nodes[i].cold.get().and_then(|c| c.pixel_aspect).unwrap_or(0.0)); + }; + // `known` is the border box; `avail` is already the content box (known or styled + // size, clamped, less padding and border), which is what `lay_out_text` wraps at. + let w = if spec.wrap { + match avail.width { + AvailableSpace::Definite(w) => Some(w.max(0.0)), + AvailableSpace::MinContent => Some(0.0), + AvailableSpace::MaxContent => None, + } + } else { + None + }; + if let Some((run, at)) = &spec.cold.advance_in { + let r = text.run_layout(run, spec.style, scale); + if let Some(w) = r.advance(*at, scale) { + return Size { + width: known.width.unwrap_or(w), + height: known.height.unwrap_or(crate::text::spec_height(&r.layout, spec.style, scale, spec.exact_lines) / scale), + }; + } + } + let is_input = nodes[i].input.is_some(); + let laid = text.layout_text(&spec.as_text_input(scale, is_input), is_input, scale, w.map(|w| w * scale + FIT_SLACK), parley::Alignment::Start, nodes[i].text_layout.as_ref()); + let l = laid.view(); + // Spaces hanging past a wrapped line's end take no room, as in CSS. + let mut lw = text_width(if w.is_some() { l.width() } else { l.full_width() }) / scale; + if (spec.truncate || spec.truncate_fade || spec.max_lines > 0) + && let AvailableSpace::Definite(a) = avail.width + { + lw = lw.min(a); + } + Size { + width: known.width.unwrap_or(lw), + height: known.height.unwrap_or(match laid.single() { + Some(l) => clamped_height(l, spec, scale), + None => l.spec_height(spec.style, scale, spec.exact_lines), + } / scale), + } + }) + }); +} + +/// A measured picture's size (`flatten::Picture::Measured`): the side it's given, and the other +/// from its image's `ratio`; with neither given, as wide as its room. +fn picture_size(known: Size<Option<f32>>, avail: Size<AvailableSpace>, ratio: f32) -> Size<f32> { + if ratio <= 0.0 { return Size { width: known.width.unwrap_or(0.0), height: known.height.unwrap_or(0.0) }; } + let room = match avail.width { + AvailableSpace::Definite(w) => Some(w.max(0.0)), + _ => None, + }; + let width = known.width.or(known.height.map(|h| h * ratio)).or(room).unwrap_or(0.0); + Size { width, height: known.height.unwrap_or(width / ratio) } +} + +/// The height (device px) of `l` as `spec` shows it: its first `max_lines` lines when set. +pub(in crate::runtime) fn clamped_height(l: &Layout<Ink>, spec: &TextSpec, scale: f32) -> f32 { + let full = crate::text::spec_height(l, spec.style, scale, spec.exact_lines); + match spec.max_lines.checked_sub(1).and_then(|last| l.lines().nth(last)).filter(|_| l.len() > spec.max_lines) { + Some(line) => line.metrics().block_max_coord.ceil().min(full), + None => full, + } +} + +/// The advance of the last line `l` shows when clamped to `lines`, in device px. +pub(in crate::runtime) fn last_line_width(l: &Layout<Ink>, lines: usize) -> f32 { + l.lines().take(lines).last().map_or(0.0, |line| line.metrics().advance - line.metrics().hanging_advance) +} + +/// `spec`'s content wrapped at `max_w` device px and cut after `spec.max_lines` lines, "…" +/// ending the last with as many whole graphemes before it as fit within `max_w`, a word that +/// wraps or overflows included. None when `full` (the uncut layout) already fits. +/// Whitespace and line breaks before the ellipsis are dropped. +pub(in crate::runtime) fn clamped(text: &mut TextSystem, spec: &TextSpec, scale: f32, max_w: f32, full: &Layout<Ink>) -> Option<(Rc<Layout<Ink>>, Elision)> { + use unicode_segmentation::UnicodeSegmentation; + let lines = spec.max_lines; + if lines == 0 || full.len() <= lines && last_line_width(full, lines) <= max_w + 0.5 { + return None; + } + let align = line_alignment(spec); + let keys = spec_elide_keys(spec, scale, 1, lines, max_w, align); + if let Some((_, key)) = keys + && let Some(hit) = text.get_elision(key) + { + return Some((hit.layout, Elision { head: hit.head, tail: hit.tail })); + } + let content = spec.content.as_str(); + // The cut falls in the last shown line or the next, whose first word may fill the last. + let start = full.lines().nth(lines.min(full.len()).max(1) - 1)?.text_range().start.min(content.len()); + let end = full.lines().nth(lines).map_or(content.len(), |l| l.text_range().end.min(content.len())); + let bounds: Vec<usize> = content[start..end].grapheme_indices(true).map(|(i, _)| start + i).chain([end]).collect(); + let blank = |g: usize| content[bounds[g]..bounds[g + 1]].chars().all(char::is_whitespace); + let cut = |mut k: usize| { + while k > 0 && blank(k - 1) { k -= 1; } + let head = if k == 0 { content[..start].trim_end().len() } else { bounds[k] }; + Elision { head, tail: content.len() } + }; + let mut str_buf = if spec.redacted { String::new() } else { String::with_capacity(end + Elision::ELLIPSIS.len()) }; + let mut span_buf = Vec::new(); + let input = spec.as_text_input(scale, false); + let mut make = |text: &mut TextSystem, e: Elision| { + e.spans_into(&spec.spans, &mut span_buf); + if spec.redacted { + let s = zeroize::Zeroizing::new([&content[..e.head], Elision::ELLIPSIS].concat()); + text.layout_cut(&input, &s, &span_buf, scale, Some(max_w), align, false) + } else { + str_buf.clear(); + str_buf.push_str(&content[..e.head]); + str_buf.push_str(Elision::ELLIPSIS); + text.layout_cut(&input, &str_buf, &span_buf, scale, Some(max_w), align, true) + } + }; + let fits = |l: &Layout<Ink>| l.len() <= lines && last_line_width(l, lines) <= max_w + 0.5; + let (mut lo, mut hi) = (0usize, bounds.len() - 1); + let mut best: Option<(usize, Rc<Layout<Ink>>, Elision)> = None; + while lo < hi { + let mid = (lo + hi).div_ceil(2); + let e = cut(mid); + let l = make(text, e); + if fits(&l) { + lo = mid; + best = Some((mid, l, e)); + } else { + hi = mid - 1; + } + } + let (layout, e) = match best { + Some((k, l, e)) if k == lo => (l, e), + _ => { + let e = cut(lo); + (make(text, e), e) + } + }; + if let Some((shape, key)) = keys { + text.insert_elision( + key, + shape, + e.drawn_len(content.len()), + crate::text::CachedElision { layout: layout.clone(), head: e.head, tail: e.tail }, + ); + } + Some((layout, e)) +} diff --git a/app/vendor/rune/crates/rune/src/runtime/commit/watch.rs b/app/vendor/rune/crates/rune/src/runtime/commit/watch.rs new file mode 100644 index 0000000..1f5f89d --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/commit/watch.rs @@ -0,0 +1,25 @@ +//! The runtime's side of `perf_warn`'s commit watch: why each of a frame's commits ran, for the +//! frame log and `RUNE_COMMIT_BUDGET_MS`, and what the commit warnings hear once a frame. +use super::*; + +impl CommitState { + #[inline] + pub(super) fn begin_watch(&mut self, why: u16) { + self.commit_why |= why; + if crate::tooling::interaction::on() { self.watch.interaction.committed(why); } + self.watch.cause = why; + } + + #[inline] + pub(super) fn end_watch(&mut self) { + self.watch.cause = 0; + } + + /// After a frame's commits, before its scroll requests run: whether it committed since the + /// `commits0`th commit, while a viewport scrolled; `instant` is the viewport an instant scroll + /// it asked for moves. + #[cfg(debug_assertions)] + pub(in crate::runtime) fn watch_frame(&mut self, commits0: u64, scrolling: bool, instant: Option<&str>) { + self.watch.meter.frame_ends(scrolling, self.commits != commits0, instant); + } +} diff --git a/app/vendor/rune/crates/rune/src/runtime/commit/why.rs b/app/vendor/rune/crates/rune/src/runtime/commit/why.rs new file mode 100644 index 0000000..552a4be --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/commit/why.rs @@ -0,0 +1,34 @@ +//! Why a frame committed, as bits for the frame log (`RUNE_FRAME_LOG`'s `why`). A frame that +//! committed with no bits committed outside `frame_step`'s checks (an update, focus, hot reload). + +/// What made a frame commit. +pub(crate) struct CommitWhy; + +impl CommitWhy { + /// The app's `poll` (or a playground stage's) returned true. + pub const POLL: u16 = 1; + /// A queued event's handler (pointer, hover, key, wheel, selection) returned true without + /// `Tx::live_only`. + pub const INPUT: u16 = 2; + /// An `on_layout`, `on_drawn_layout` or `on_visible_rows` handler returned true. + pub const LAYOUT: u16 = 4; + /// A rect the last view read (`Cx::layout_size`, `Cx::layout_with`) moved. + pub const READ: u16 = 8; + /// State was marked changed outside a handler: an update, a live value, a caret move. + pub const DIRTY: u16 = 16; + /// The viewport, scale or a pixel aspect changed. + pub const RELAYOUT: u16 = 32; + /// A `Tx::settle` is pending. + pub const SETTLE: u16 = 64; + /// A virtual list's mounted window changed. + pub const VIRTUAL: u16 = 128; + /// A key or IME event had to see the state an earlier handler left before routing. + pub const ROUTE: u16 = 256; + /// A commit landed at once (`Tx::instant`): what it changed didn't animate, by design. + pub const INSTANT: u16 = 512; + pub const NAMES: [&'static str; 10] = ["poll", "input", "layout", "read", "dirty", "relayout", "settle", "virtual", "route", "instant"]; + + pub fn names(bits: u16) -> Vec<&'static str> { + Self::NAMES.iter().enumerate().filter(|(i, _)| bits & (1 << i) != 0).map(|(_, n)| *n).collect() + } +} diff --git a/app/vendor/rune/crates/rune/src/runtime/cx.rs b/app/vendor/rune/crates/rune/src/runtime/cx.rs new file mode 100644 index 0000000..0928b5e --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/cx.rs @@ -0,0 +1,362 @@ +//! View environment (`Env`), background wake handle (`Waker`) and view context (`Cx`). +use super::*; + +#[derive(Clone, Copy, Debug)] +pub struct Env { + pub system_dark: bool, + pub scale: f32, +} +impl Env { + pub const fn new(system_dark: bool, scale: f32) -> Self { + Self { system_dark, scale } + } +} +impl Default for Env { + fn default() -> Self { Self::new(true, 1.0) } +} + +/// What a view declares for the elements that don't style themselves. +#[derive(Clone, Debug, Default, PartialEq)] +pub(crate) struct ViewDefaults { + /// [`Cx::foreground`]. + pub(crate) foreground: Option<Color>, + /// [`Cx::focus_ring`]. + pub(crate) focus_ring: Option<crate::el::Outline>, + /// [`Cx::help_look`]. + pub(crate) help: Option<super::HelpLook>, + /// [`Cx::web_focus`]. + pub(crate) web_focus: bool, + /// [`Cx::force_focus_rings`]. + pub(crate) force_focus_rings: bool, + /// [`Cx::mark_texts`]. + pub(crate) marks: Rc<[super::TextMark]>, +} + +pub use rune_core::Waker; + +thread_local! { + pub(super) static COMMITS: std::cell::Cell<u64> = const { std::cell::Cell::new(0) }; +} + +/// How many commits (runs of a view that go on to the screen) have started on this thread, +/// across all its windows; 0 before the first. A cache of what views draw can keep whatever +/// the last commit or two used and evict the rest. +pub fn commit_generation() -> u64 { + COMMITS.get() +} + +/// Type-erased view context owned inside [`Cx<S>`] and constructed by non-generic +/// [`Measurement`](super::commit::Measurement). +#[derive(Clone)] +pub(crate) struct CxCore { + pub(super) env: Env, + pub(super) titlebar_inset: f32, + pub(super) chrome: crate::ChromeInsets, + /// `Cx::caption_color`, read once the view returns. + pub(super) caption_color: Option<Color>, + /// `Cx::foreground` and `Cx::focus_ring`, read once the view returns. + pub(super) defaults: ViewDefaults, + /// `Cx::set_titlebar` and `Cx::titlebar_height`, read once the view returns. + pub(super) titlebar: crate::titlebar::TitlebarSet, + pub(super) system_accent: crate::SystemAccent, + pub(super) system_contrast: Option<crate::SystemContrast>, + pub(super) system_increased_contrast: bool, + pub(super) system_scroll_bars: crate::platform::scroll_bars::SystemScrollBars, + pub(super) system_reduced_motion: bool, + pub(super) reduced_motion: bool, + pub(super) time_scale: f32, + /// [`Cx::zoom`], read once the view returns. + pub(super) zoom: f32, + pub(super) caret: Option<(String, [f32; 4])>, + pub(super) caret_read: std::cell::Cell<bool>, + pub(super) layout: layout_read::LayoutRects, + pub(super) layout_reads: std::cell::RefCell<layout_read::LayoutReads>, +} + +impl CxCore { + pub(super) fn absorb(&mut self, other: CxCore) { + self.reduced_motion = other.reduced_motion; + self.time_scale = other.time_scale; + self.zoom = other.zoom; + self.defaults = other.defaults; + self.caret_read.set(self.caret_read.get() || other.caret_read.get()); + let mut reads = self.layout_reads.borrow_mut(); + for read in other.layout_reads.into_inner() { + layout_read::note_read_at(&mut reads, &read.key, read.same, read.at); + } + } + + pub(crate) fn set_env(&mut self, env: Env) { + self.env = env; + } + + pub(crate) fn clear_chrome(&mut self) { + self.titlebar_inset = 0.0; + self.chrome = crate::ChromeInsets::default(); + } + + #[cfg(feature = "hot")] + pub(crate) fn settings_from(&mut self, other: CxCore) { + self.reduced_motion = other.reduced_motion; + self.time_scale = other.time_scale; + self.zoom = other.zoom; + self.caption_color = other.caption_color; + self.titlebar = other.titlebar; + self.caret_read = other.caret_read; + self.layout_reads = other.layout_reads; + } + + pub(crate) fn env(&self) -> Env { self.env } + pub(crate) fn system_dark(&self) -> bool { self.env.system_dark } + pub(crate) fn titlebar_inset(&self) -> f32 { self.titlebar_inset } + pub(crate) fn chrome_insets(&self) -> crate::ChromeInsets { self.chrome } + pub(crate) fn caption_color(&mut self, color: Color) { self.caption_color = Some(color); } + pub(crate) fn foreground(&mut self, color: Color) { self.defaults.foreground = Some(color); } + pub(crate) fn focus_ring(&mut self, width: f32, offset: f32, color: Color) { + self.defaults.focus_ring = Some(crate::el::Outline { width, offset, color }); + } + pub(crate) fn help_look(&mut self, look: crate::HelpLook) { self.defaults.help = Some(look); } + pub(crate) fn force_focus_rings(&mut self) { self.defaults.force_focus_rings = true; } + pub(crate) fn web_focus(&mut self) { self.defaults.web_focus = true; } + pub(crate) fn titlebar_height(&mut self, points: f32) { self.titlebar.height = Some(points.max(1.0)); } + pub(crate) fn set_titlebar(&mut self, titlebar: crate::Titlebar) { self.titlebar.titlebar = Some(titlebar); } + pub(crate) fn accent(&self) -> Color { self.system_accent.accent(self.env.system_dark) } + pub(crate) fn focus_color(&self) -> Color { self.system_accent.focus(self.env.system_dark) } + pub(crate) fn safe_area(&self) -> [f32; 4] { + #[cfg(target_arch = "wasm32")] + { crate::platform::web::safe_area() } + #[cfg(not(target_arch = "wasm32"))] + { [0.0; 4] } + } + pub(crate) fn hover_none(&self) -> bool { + #[cfg(target_arch = "wasm32")] + { crate::platform::web::hover_none() } + #[cfg(not(target_arch = "wasm32"))] + { false } + } + pub(crate) fn touch_controls(&self) -> bool { + #[cfg(target_arch = "wasm32")] + { crate::platform::web::touch_controls() } + #[cfg(not(target_arch = "wasm32"))] + { false } + } + pub(crate) fn system_contrast(&self) -> Option<crate::SystemContrast> { self.system_contrast } + pub(crate) fn system_increased_contrast(&self) -> bool { self.system_increased_contrast } + pub(crate) fn system_reduced_motion(&self) -> bool { self.system_reduced_motion } + pub(crate) fn scroll_bars(&self) -> crate::ScrollBars { self.system_scroll_bars.bars } + pub(crate) fn overlay_scroll_bars(&self) -> bool { self.system_scroll_bars.is_overlay() } + pub(crate) fn is_reduced_motion(&self) -> bool { self.reduced_motion } + pub(crate) fn reduced_motion(&mut self, on: bool) { self.reduced_motion = on; } + pub(crate) fn time_scale(&mut self, scale: f32) { self.time_scale = scale.clamp(0.0, 8.0); } + pub(crate) fn zoom(&mut self, k: f32) { self.zoom = super::zoom::clamp(k); } + pub(crate) fn caret(&self, key: &str) -> Option<[f32; 4]> { + self.caret_read.set(true); + let rect = caret_of(&self.caret, key); + crate::memo::read_caret(key, rect); + rect + } +} + +/// Passed to view functions: the environment, plus runtime settings a view may declare. +pub struct Cx<S> { + pub(crate) core: CxCore, + pub(super) _s: PhantomData<fn(&S)>, +} + +impl<S> Cx<S> { + /// A copy of this context for a sub-view over another state type, or a scratch run of + /// the same view: environment, settings and the reads made so far. Pass it back with + /// [`Self::absorb`] to keep what the sub-view did, or drop it to discard that, as a host + /// does for a sub-view (a plugin's panel) that panicked partway. + #[inline(always)] + pub fn retype<T>(&self) -> Cx<T> { + Cx { core: self.core.clone(), _s: PhantomData } + } + + /// Takes back a [`Self::retype`]d context a nested view ran with: its overrides, and the + /// caret and layout reads it added. The window's chrome stays the outer view's: a staged + /// story's `caption_color` or titlebar isn't the window's. + #[inline(always)] + pub fn absorb<T>(&mut self, other: Cx<T>) { + self.core.absorb(other.core); + } + + #[inline(always)] + pub(crate) fn set_env(&mut self, env: Env) { + self.core.set_env(env); + } + + /// A nested view on a stage, which no window controls cover. + #[inline(always)] + pub(crate) fn clear_chrome(&mut self) { + self.core.clear_chrome(); + } + + #[cfg(feature = "hot")] + #[inline(always)] + pub(crate) fn settings_from<T>(&mut self, other: Cx<T>) { + self.core.settings_from(other.core); + } + + #[inline(always)] + pub fn env(&self) -> Env { self.core.env() } + #[inline(always)] + pub fn system_dark(&self) -> bool { self.core.system_dark() } + /// Points from the window's leading edge to the trailing edge of the macOS traffic lights + /// drawn over the content, for a top bar's leading inset: 0 when nothing is drawn there (full + /// screen, a titled window whose content starts below its titlebar, other platforms). The + /// view re-runs when it changes, as entering and leaving full screen do. Headless runs report + /// [`Chrome::titlebar_inset`](crate::Chrome::titlebar_inset). A `memo` closure that reads + /// it needs it in its version. + #[inline(always)] + pub fn titlebar_inset(&self) -> f32 { self.core.titlebar_inset() } + /// What the window's own controls take of a titlebar the app draws (`App::titlebar`): + /// the macOS traffic lights at the leading edge, the Windows caption buttons at the + /// trailing edge, and the band's height. Zero where the native frame stays. Keep the + /// titlebar's own controls clear of both ends. Headless runs report what this platform's + /// window would. + #[inline(always)] + pub fn chrome_insets(&self) -> crate::ChromeInsets { self.core.chrome_insets() } + /// The colour of the Windows caption buttons' symbols (Electron's `titleBarOverlay` + /// `symbolColor`), for a titlebar whose colours follow the app's theme rather than the + /// system's light or dark setting: by default black in light mode, white in dark. Their + /// hover and press washes are this colour at 10% and 20%; close turns red either way. + #[inline(always)] + pub fn caption_color(&mut self, color: Color) { self.core.caption_color(color); } + /// The theme's text colour, as CSS `color` on the page: text, icons and text fields that + /// aren't given a colour (`El::color`, `El::placeholder`, `El::caret`) draw in it, the + /// placeholder at 40% and the selection at 20%, so a field left uncoloured stays readable in + /// a light theme. Without it they draw white. Set it on every run of the view; a `memo` + /// whose text takes it rebuilds when it changes. + #[inline(always)] + pub fn foreground(&mut self, color: Color) { self.core.foreground(color); } + /// The keyboard focus ring a focusable element draws when it doesn't set its own + /// ([`El::focus_ring`](crate::El::focus_ring)), in place of AppKit's: `width` points wide, + /// `offset` points outside its border box, following its corner radii, e.g. `2.0, 2.5` for + /// CSS `outline: 2px solid; outline-offset: 2.5px`. It shows only for keyboard focus, as + /// `:focus-visible` does. Set it on every run of the view. + #[inline(always)] + pub fn focus_ring(&mut self, width: f32, offset: f32, color: Color) { self.core.focus_ring(width, offset, color); } + /// How [`El::help`](crate::El::help) tooltips look, where they sit and how long they wait, + /// in place of the system's ([`HelpLook::system`](crate::HelpLook::system)): a design + /// system's own tooltip, as a web page draws one. Rune then draws it on macOS too, instead + /// of AppKit's. Set it on every run of the view. + #[inline(always)] + pub fn help_look(&mut self, look: crate::HelpLook) { self.core.help_look(look); } + /// Every control that can take focus draws its keyboard focus ring (and its focus fill) as + /// if the keyboard had focused it, whether or not it has focus: a developer tool for checking + /// focus styles at a glance, as forcing `:focus` and `:focus-visible` on every focusable + /// element of a web page does (Chrome DevTools' `CSS.forcePseudoState`). Focus itself doesn't + /// move. Set it on every run of the view while the tool is on. + #[inline(always)] + pub fn force_focus_rings(&mut self) { self.core.force_focus_rings(); } + /// Keyboard focus as a web page has it, for a view that ports one: every pressable control + /// (an `on_press` element whose role is button, link, tab, checkbox, switch, radio or + /// combobox) is a Tab stop in document order and takes focus when clicked, as an HTML + /// `<button>` does, unless it says [`El::focusable(false)`](crate::El::focusable) or is + /// disabled. A modal that opens with no [`El::autofocus`](crate::El::autofocus) control and + /// no text field focuses itself, as a web dialog does, so Tab enters it at its first control + /// rather than landing on its close button. Set it on every run of the view. + #[inline(always)] + pub fn web_focus(&mut self) { self.core.web_focus(); } + /// The height of the titlebar the app draws (`App::titlebar`), in window points, in place of + /// `Titlebar::new`'s while the view keeps setting it: a band that scales with the app's UI + /// zoom, as Electron's `setTitleBarOverlay({ height })` does. The Windows caption buttons + /// take it (their width stays), macOS centres the traffic lights in it unless + /// `Titlebar::traffic_lights` or `Chrome::traffic_lights` places them, and + /// [`Self::chrome_insets`] reports it from the next frame on, so the buttons line up with + /// the app's row at every zoom: for a 44 point row, `cx.titlebar_height(44.0 * zoom.max(1.0))` + /// keeps the row 44 points tall zoomed out, as Electron apps size their `titleBarOverlay`. + /// The height is in window points; [`Self::chrome_insets`] reports it in the view's, over + /// [`Self::zoom`]. Over [`Self::set_titlebar`], it sets that titlebar's height. + #[inline(always)] + pub fn titlebar_height(&mut self, points: f32) { self.core.titlebar_height(points); } + /// The titlebar the app draws (`App::titlebar`), in place of the app's while the view keeps + /// setting it: its height and, on macOS, where the traffic lights sit + /// (`Titlebar::traffic_lights`), for a switch between layouts whose titlebars differ. The + /// window moves the traffic lights and resizes the Windows caption buttons to it, and + /// [`Self::chrome_insets`] and [`Self::titlebar_inset`] report the new controls from the + /// next frame on. A window without `App::titlebar` keeps its native frame. + #[inline(always)] + pub fn set_titlebar(&mut self, titlebar: crate::Titlebar) { self.core.set_titlebar(titlebar); } + /// The user's accent colour (System Settings › Appearance on macOS) for this window's + /// appearance, [`SystemAccent::DEFAULT`](crate::SystemAccent::DEFAULT)'s blue elsewhere and + /// headless. The view re-runs, memos included, when the user picks another accent. + #[inline(always)] + pub fn accent(&self) -> Color { self.core.accent() } + /// The keyboard focus ring colour for this window's appearance: AppKit's + /// `keyboardFocusIndicatorColor`, the accent at 50% elsewhere. Elements with no ring of + /// their own draw their default focus ring in it. + #[inline(always)] + pub fn focus_color(&self) -> Color { self.core.focus_color() } + /// Browser safe-area insets in points, in top/right/bottom/left order. Zero on native. + /// Apply these inside a full-canvas root so backgrounds can extend to the screen edges. + #[inline(always)] + pub fn safe_area(&self) -> [f32; 4] { self.core.safe_area() } + /// The primary pointer can't hover: a browser's `(hover: none)`, a phone's or tablet's touch + /// screen. What a mouse would reveal on hover (a code block's Copy, a row's actions) should + /// show without it. False natively. A change re-runs the view. + #[inline(always)] + pub fn hover_none(&self) -> bool { self.core.hover_none() } + /// A page's primary pointer is coarse and can't hover. Use this for a phone or tablet's + /// controls rather than the viewport width: a narrow window can still have a mouse. + #[inline(always)] + pub fn touch_controls(&self) -> bool { self.core.touch_controls() } + /// The system's contrast theme when one is on (Windows' Contrast themes, high contrast): + /// the colours it asks every app to paint with, which a view uses in place of its own + /// (CSS `forced-colors: active`). None otherwise. A change re-runs the view. + #[inline(always)] + pub fn system_contrast(&self) -> Option<crate::SystemContrast> { self.core.system_contrast() } + /// Whether the system asks for more contrast: macOS's Increase Contrast, or a Windows contrast + /// theme (when [`Self::system_contrast`] is also there). A view can draw its stronger edges for + /// it while keeping its own colours. A change re-runs the view. + #[inline(always)] + pub fn system_increased_contrast(&self) -> bool { self.core.system_increased_contrast() } + /// The host's OS accessibility preference, independent of this commit's override. + #[inline(always)] + pub fn system_reduced_motion(&self) -> bool { self.core.system_reduced_motion() } + /// The user's "Show scroll bars" preference (System Settings › Appearance on macOS; + /// [`ScrollBars::WhenScrolling`](crate::ScrollBars::WhenScrolling) elsewhere and headless). + /// The view and its memos re-run when it changes. + #[inline(always)] + pub fn scroll_bars(&self) -> crate::ScrollBars { self.core.scroll_bars() } + /// Whether scroll bars currently overlay and fade out at rest (`true` for + /// [`ScrollBars::WhenScrolling`](crate::ScrollBars::WhenScrolling), `false` for + /// [`ScrollBars::Always`](crate::ScrollBars::Always), and `NSScroller.preferredScrollerStyle` + /// under [`ScrollBars::Automatic`](crate::ScrollBars::Automatic); always `true` on iOS). + #[inline(always)] + pub fn overlay_scroll_bars(&self) -> bool { self.core.overlay_scroll_bars() } + /// Whether this commit reduces motion: the host preference, or the view's override from + /// [`Self::reduced_motion`]. Pass it to builders that pick a different motion under it. + #[inline(always)] + pub fn is_reduced_motion(&self) -> bool { self.core.is_reduced_motion() } + /// Override the host preference for this commit: travel jumps, opacity/colour briefly fade. + #[inline(always)] + pub fn reduced_motion(&mut self, on: bool) { self.core.reduced_motion(on); } + /// Scale the window's animation clock (slow motion below 1, paused at 0). To slow or freeze + /// only part of the window, use [`El::time_scale`](crate::El::time_scale), which multiplies + /// with this. + #[inline(always)] + pub fn time_scale(&mut self, scale: f32) { self.core.time_scale(scale); } + /// The UI zoom, as a browser's page zoom (Electron's `setZoomFactor`): `k` times the size, + /// 1 unzoomed. The view lays out in a window `1 / k` as many points across, drawn at `k` + /// times the window's scale, so borders, icons, text and pixel snapping land on the device + /// grid at every zoom as Chromium's do, and motion runs in the space the layout is in. Set it + /// on every run of the view; a run that doesn't is unzoomed. A change lands at once, in the + /// commit that makes it. [`Self::env`]'s scale, layout reads and pointer positions are in + /// the zoomed view's points; [`Self::chrome_insets`] and [`Self::titlebar_inset`] too. + #[inline(always)] + pub fn zoom(&mut self, k: f32) { self.core.zoom(k); } + /// The focused text field's caret line in window points `[x, y, w, h]`, as last drawn (after + /// scrolling, at the cursor inside an IME composition), when that field is keyed `key` or sits + /// inside an element keyed `key`. A view that reads it re-runs when the caret moves, so a + /// popup placed from it lands the frame after each edit. + #[inline(always)] + pub fn caret(&self, key: &str) -> Option<[f32; 4]> { self.core.caret(key) } +} + +/// [`Cx::caret`] for the caret `caret` (the focused field's path and rect). +pub(crate) fn caret_of(caret: &Option<(String, [f32; 4])>, key: &str) -> Option<[f32; 4]> { + let (path, rect) = caret.as_ref()?; + path.split('/').any(|seg| seg == key).then_some(*rect) +} diff --git a/app/vendor/rune/crates/rune/src/runtime/drag_out_host.rs b/app/vendor/rune/crates/rune/src/runtime/drag_out_host.rs new file mode 100644 index 0000000..b4a8282 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/drag_out_host.rs @@ -0,0 +1,28 @@ +//! The host's side of drag-outs: starting OS drag sessions and reporting how they ended. + +use super::*; + +impl RuntimeCore { + /// A drag-out the pointer move just delivered asked for. The shell must start the OS + /// session before returning from that move event. + /// The drag to start, its rects and press in window points (the view's times its zoom). + pub(crate) fn take_drag_out(&mut self) -> Option<crate::drag_out::DragOutStart> { + let k = self.host.zoom(); + self.pointer.drag_out_request.take().map(|s| crate::drag_out::DragOutStart { + rect: s.rect.map(|v| v * k), + bounds: s.bounds.map(|v| v * k), + press: (s.press.0 * k, s.press.1 * k), + ..s + }) + } + + /// Where the host reports how a drag-out ended; delivered to `on_drag_end` next frame. + pub(crate) fn drag_end_sink(&self) -> crate::drag_out::DragEnds { self.pointer.drag_ends.clone() } + pub(crate) fn drag_ends_pending(&self) -> bool { !self.pointer.drag_ends.borrow().is_empty() } + + /// Whether this host can start OS drags. Without, `drag_out` elements act as if they had + /// none. + pub(crate) fn set_os_drag(&mut self, supported: bool) { self.pointer.os_drag = supported; } + + pub(super) fn drags_out(&self, n: &Node) -> bool { self.pointer.os_drag && n.handlers.get().is_some_and(|h| h.drag_out.is_some()) } +} diff --git a/app/vendor/rune/crates/rune/src/runtime/driver.rs b/app/vendor/rune/crates/rune/src/runtime/driver.rs new file mode 100644 index 0000000..a6562dc --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/driver.rs @@ -0,0 +1,249 @@ +//! Non-generic driver traits erasing the app state type `S` across `RuntimeCore` and `Measurement`. +//! +//! `Runtime<S>` projects its trailing `S`-dependent fields into `AppRef<'_, S>` or +//! `AppRefMut<'_, S>`, which implement `ViewDriver` and `AppDriver`. Every method on +//! `RuntimeCore` and `Measurement` compiles once in `librune.rlib` instead of being +//! monomorphized per app state type. + +use std::marker::PhantomData; + +use super::{Cx, El, Ime, KeyEvent, Tx, cx, handler_state, handler_state_ref}; +use crate::playground::{Moved, Nav, Region, Request}; +use crate::states::{States, StatesRef}; + +/// Non-generic control surface of an attached [`crate::playground::Live<S>`]. +/// +/// The trait-object casts onto this trait live behind function pointers initialized only inside +/// `Live::new`, so an app that never enables a playground never instantiates the `Live<S>` +/// playground vtable or UI code. +pub(crate) trait PlaygroundDriver { + fn is_open(&self) -> bool; + fn is_shortcut(&self, ev: &KeyEvent) -> bool; + fn request(&mut self, requests: Vec<Request>); + fn has_pending(&self) -> bool; + fn pending_swaps_stage(&self) -> bool; + fn pending_replays_only(&self) -> bool; + fn polls(&self) -> bool; + fn poll_stage(&mut self, clock: f64, tx: &mut Tx) -> bool; + fn take_pressed(&mut self) -> Vec<KeyEvent>; + fn pressing(&self) -> bool; + fn set_pressing(&mut self, pressing: bool); + fn app_time_scale(&self) -> f32; + fn set_app_time_scale(&mut self, scale: f32); + fn region(&self) -> Region; + fn region_at(&self, x: f32, width: f32) -> Region; + fn saw_focus(&self, focus: Option<&str>) -> bool; + fn moved(&mut self, moved: Moved) -> bool; + fn nav(&self, ev: &KeyEvent, region: Region) -> Nav; + fn side_key(&mut self, ev: &KeyEvent, tx: &mut Tx) -> bool; + fn clear_filter(&mut self) -> bool; + fn first_shown(&self) -> Option<usize>; + fn first_match(&self) -> Option<usize>; +} + +/// Read-only access to the app's state and view function, sufficient for `Measurement`, +/// virtual-row collection, and drag-out item queries. +pub(crate) trait ViewDriver { + fn states_ref(&self) -> StatesRef<'_>; + fn view(&self, cx: cx::CxCore, viewport: (f32, f32)) -> (El, cx::CxCore); +} + +/// Full app-state and hook driver for `RuntimeCore`'s frame, input, and commit pipelines. +pub(crate) trait AppDriver: ViewDriver { + fn states(&mut self) -> States<'_>; + fn has_poll(&self) -> bool; + fn poll(&mut self, clock: f64, tx: &mut Tx) -> bool; + fn has_on_key(&self) -> bool; + fn on_key(&mut self, ev: &KeyEvent, tx: &mut Tx) -> bool; + fn has_on_focus(&self) -> bool; + fn on_focus(&mut self, focused: bool, tx: &mut Tx); + fn has_on_mods(&self) -> bool; + fn on_mods(&mut self, mods: crate::Mods, tx: &mut Tx) -> bool; + fn has_on_visibility(&self) -> bool; + fn on_visibility(&mut self, visible: bool, tx: &mut Tx); + fn has_on_ime(&self) -> bool; + fn on_ime(&mut self, ev: &Ime, tx: &mut Tx) -> bool; + fn playground(&self) -> Option<&dyn PlaygroundDriver>; + fn playground_mut(&mut self) -> Option<&mut dyn PlaygroundDriver>; + fn playground_apply(&mut self, clock: f64) -> bool; + fn playground_typing(&self) -> bool; + fn playground_played(&self) -> u64; +} + +/// The non-public `S`-dependent hooks owned by [`super::Runtime<S>`] after the shared prefix. +pub(crate) struct RuntimeHooks<S: 'static> { + pub(crate) view: fn(&S, &mut Cx<S>) -> El, + pub(crate) on_focus: Option<fn(&mut S, bool, &mut Tx)>, + pub(crate) on_mods: Option<fn(&mut S, crate::Mods, &mut Tx)>, + pub(crate) on_visibility: Option<fn(&mut S, bool, &mut Tx)>, + pub(crate) on_ime: Option<fn(&mut S, &Ime, &mut Tx) -> bool>, + pub(crate) playground: Option<Box<crate::playground::Live<S>>>, +} + +impl<S: 'static> RuntimeHooks<S> { + pub(crate) fn new(view: fn(&S, &mut Cx<S>) -> El) -> Self { + Self { + view, + on_focus: None, + on_mods: None, + on_visibility: None, + on_ime: None, + playground: None, + } + } +} + +/// Disjoint shared borrow of `Runtime<S>`'s trailing `S`-dependent fields. +pub(crate) struct AppRef<'a, S: 'static> { + pub(crate) state: &'a S, + pub(crate) hooks: &'a RuntimeHooks<S>, +} + +/// Disjoint mutable borrow of `Runtime<S>`'s trailing `S`-dependent fields. +pub(crate) struct AppRefMut<'a, S: 'static> { + pub(crate) state: &'a mut S, + pub(crate) poll: Option<fn(&mut S, f64, &mut Tx) -> bool>, + pub(crate) on_key: Option<fn(&mut S, &KeyEvent, &mut Tx) -> bool>, + pub(crate) hooks: &'a mut RuntimeHooks<S>, +} + +impl<'a, S: 'static> AppRef<'a, S> { + fn states_ref_inner(self) -> StatesRef<'a> { + match self.hooks.playground.as_deref() { + Some(playground) => playground.states_ref(self.state), + None => StatesRef::one(handler_state_ref(self.state)), + } + } + + fn view_inner(self, cx: cx::CxCore, viewport: (f32, f32)) -> (El, cx::CxCore) { + let mut cx = Cx { core: cx, _s: PhantomData }; + let root = match self.hooks.playground.as_deref() { + Some(playground) => playground.view(self.state, self.hooks.view, &mut cx, viewport), + None => crate::playground::call(self.hooks.view, self.state, &mut cx), + }; + (root, cx.core) + } +} + +impl<S: 'static> ViewDriver for AppRef<'_, S> { + fn states_ref(&self) -> StatesRef<'_> { + AppRef { state: self.state, hooks: self.hooks }.states_ref_inner() + } + + fn view(&self, cx: cx::CxCore, viewport: (f32, f32)) -> (El, cx::CxCore) { + AppRef { state: self.state, hooks: self.hooks }.view_inner(cx, viewport) + } +} + +impl<S: 'static> ViewDriver for AppRefMut<'_, S> { + fn states_ref(&self) -> StatesRef<'_> { + AppRef { state: self.state, hooks: self.hooks }.states_ref_inner() + } + + fn view(&self, cx: cx::CxCore, viewport: (f32, f32)) -> (El, cx::CxCore) { + AppRef { state: self.state, hooks: self.hooks }.view_inner(cx, viewport) + } +} + +impl<S: 'static> AppDriver for AppRefMut<'_, S> { + fn states(&mut self) -> States<'_> { + match &mut self.hooks.playground { + Some(playground) => playground.states(self.state), + None => States::one(handler_state(self.state)), + } + } + + fn has_poll(&self) -> bool { + self.poll.is_some() + } + + fn poll(&mut self, clock: f64, tx: &mut Tx) -> bool { + let Some(poll) = self.poll else { return false }; + app_call!(poll, self.state, clock, tx) + } + + fn has_on_key(&self) -> bool { + self.on_key.is_some() + } + + fn on_key(&mut self, ev: &KeyEvent, tx: &mut Tx) -> bool { + let Some(f) = self.on_key else { return false }; + let state = match &mut self.hooks.playground { + Some(playground) => playground.key_state(self.state), + None => Some(&mut *self.state), + }; + state.is_some_and(|state| app_call!(f, state, ev, tx)) + } + + fn has_on_focus(&self) -> bool { + self.hooks.on_focus.is_some() + } + + fn on_focus(&mut self, focused: bool, tx: &mut Tx) { + if let Some(f) = self.hooks.on_focus { + f(self.state, focused, tx); + } + } + + fn has_on_mods(&self) -> bool { + self.hooks.on_mods.is_some() + } + + fn on_mods(&mut self, mods: crate::Mods, tx: &mut Tx) -> bool { + let Some(f) = self.hooks.on_mods else { return false }; + let state = match &mut self.hooks.playground { + Some(playground) => playground.key_state(self.state), + None => Some(&mut *self.state), + }; + let Some(state) = state else { return false }; + f(state, mods, tx); + true + } + + fn has_on_visibility(&self) -> bool { + self.hooks.on_visibility.is_some() + } + + fn on_visibility(&mut self, visible: bool, tx: &mut Tx) { + if let Some(f) = self.hooks.on_visibility { + f(self.state, visible, tx); + } + } + + fn has_on_ime(&self) -> bool { + self.hooks.on_ime.is_some() + } + + fn on_ime(&mut self, ev: &Ime, tx: &mut Tx) -> bool { + let Some(f) = self.hooks.on_ime else { return false }; + let state = match &mut self.hooks.playground { + Some(playground) if !playground.stage_hears(self.state) => None, + Some(playground) => playground.key_state(self.state), + None => Some(&mut *self.state), + }; + state.is_some_and(|state| Tx::took(app_call!(f, state, ev, tx), tx)) + } + + fn playground(&self) -> Option<&dyn PlaygroundDriver> { + self.hooks.playground.as_deref().map(crate::playground::Live::driver) + } + + fn playground_mut(&mut self) -> Option<&mut dyn PlaygroundDriver> { + self.hooks.playground.as_deref_mut().map(crate::playground::Live::driver_mut) + } + + fn playground_apply(&mut self, clock: f64) -> bool { + self.hooks.playground.as_deref_mut().is_some_and(|p| p.apply(clock, self.state)) + } + + fn playground_typing(&self) -> bool { + self.hooks.playground.as_deref().is_some_and(|p| p.typing(self.state)) + } + + fn playground_played(&self) -> u64 { + match self.hooks.playground.as_deref() { + Some(p) => p.played, + None => 0, + } + } +} diff --git a/app/vendor/rune/crates/rune/src/runtime/drop_tests.rs b/app/vendor/rune/crates/rune/src/runtime/drop_tests.rs new file mode 100644 index 0000000..7c9a67d --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/drop_tests.rs @@ -0,0 +1,335 @@ +//! `El::on_drop_files`: files dragged from another app reach the innermost element under the +//! drop that accepts them, in one call, with a drop hover while the drag is over it. +use super::*; +use crate::{Cx, El, Env, col, el}; +use std::path::PathBuf; + +#[derive(Default)] +struct Drops { + /// Each `on_drop_files` call: the target and the files it got. + dropped: Vec<(&'static str, Vec<String>)>, + /// Each `on_drop_hover` call. + hover: Vec<(&'static str, bool)>, + root_takes: bool, + /// The inner zone is gone, and a modal that takes drops is open. + no_inner: bool, + modal: bool, +} + +fn zone(key: &'static str) -> El { + el().key(key) + .on_drop_files(move |s: &mut Drops, files, _| s.dropped.push((key, files.iter().map(|f| f.display().to_string()).collect()))) + .on_drop_hover(move |s: &mut Drops, over, _| s.hover.push((key, over))) +} + +/// An outer zone that takes anything around an inner one that takes pictures, in a 400 by 300 +/// window whose root takes drops when `root_takes`. +fn view(s: &Drops, _: &mut Cx<Drops>) -> El { + let outer = zone("outer").size(200.0, 200.0); + let outer = if s.no_inner { outer } else { outer.child(zone("inner").size(100.0, 100.0).accepts_extensions(&["png", ".JPG"])) }; + let mut root = col().w_full().h_full().child(outer); + if s.modal { + root = root.child(zone("modal").absolute(100.0, 50.0).size(200.0, 200.0).modal(false, |s: &mut Drops| s.modal = false)); + } + if s.root_takes { root.on_drop_files(|s: &mut Drops, files, _| s.dropped.push(("root", files.iter().map(|f| f.display().to_string()).collect()))) } else { root } +} + +fn run(root_takes: bool) -> Runtime<Drops> { + let mut rt = Runtime::new(Drops { root_takes, ..Default::default() }, view, (400.0, 300.0), Env::new(true, 1.0)); + rt.frame(0.0); + rt +} + +fn files(names: &[&str]) -> Vec<PathBuf> { names.iter().map(PathBuf::from).collect() } + +fn drop_at(rt: &mut Runtime<Drops>, names: &[&str], at: (f32, f32)) { + rt.drag_files(files(names), Some(at)); + rt.drop_files(files(names), Some(at)); + rt.frame(1.0 / 60.0); +} + +fn dropped(rt: &Runtime<Drops>) -> Vec<(&'static str, Vec<&str>)> { + rt.state.dropped.iter().map(|(k, f)| (*k, f.iter().map(String::as_str).collect())).collect() +} + +#[test] +fn the_innermost_accepting_target_takes_the_drop() { + let mut rt = run(true); + drop_at(&mut rt, &["a.png"], (50.0, 50.0)); + drop_at(&mut rt, &["b.png"], (150.0, 150.0)); + assert_eq!(dropped(&rt), [("inner", vec!["a.png"]), ("outer", vec!["b.png"])]); +} + +#[test] +fn files_a_target_refuses_pass_to_the_next_that_accepts_them() { + let mut rt = run(true); + drop_at(&mut rt, &["notes.txt"], (50.0, 50.0)); + assert_eq!(dropped(&rt), [("outer", vec!["notes.txt"])], "the inner zone takes only pictures"); + drop_at(&mut rt, &["c.png"], (300.0, 250.0)); + assert_eq!(dropped(&rt)[1], ("root", vec!["c.png"]), "a drop over no zone falls back to the root"); + rt.drop_files(files(&["d.png"]), None); + rt.frame(2.0 / 60.0); + assert_eq!(dropped(&rt)[2], ("root", vec!["d.png"]), "as does a drop with no position"); + + let mut rt = run(false); + drop_at(&mut rt, &["c.png"], (300.0, 250.0)); + assert_eq!(dropped(&rt), [], "with no root handler a drop nothing takes is ignored"); + assert_eq!(rt.state.hover, [], "and shows no hover"); +} + +#[test] +fn the_drop_hover_follows_the_drag_and_ends_when_it_leaves_or_drops() { + let mut rt = run(false); + rt.drag_files(files(&["a.png"]), Some((50.0, 50.0))); + assert!(rt.dragging_files()); + rt.frame(1.0 / 60.0); + assert_eq!(rt.state.hover, [("inner", true)]); + assert_eq!(rt.drop_hovered().as_deref(), Some("inner")); + rt.drag_files_to(Some((150.0, 150.0))); + rt.frame(2.0 / 60.0); + assert_eq!(rt.state.hover[1..], [("inner", false), ("outer", true)], "only the innermost accepting target is hovered"); + rt.drag_files_leave(); + assert!(!rt.dragging_files()); + rt.frame(3.0 / 60.0); + assert_eq!(rt.state.hover[3..], [("outer", false)], "leaving the window ends the hover"); + assert_eq!(rt.drop_hovered(), None); + + rt.state.hover.clear(); + rt.drag_files(files(&["notes.txt"]), Some((50.0, 50.0))); + rt.frame(4.0 / 60.0); + assert_eq!(rt.state.hover, [("outer", true)], "a target that refuses the files isn't hovered"); + rt.drop_files(files(&["notes.txt"]), Some((50.0, 50.0))); + rt.frame(5.0 / 60.0); + assert_eq!(rt.state.hover, [("outer", true), ("outer", false)], "dropping ends the hover"); + assert_eq!(dropped(&rt), [("outer", vec!["notes.txt"])]); +} + +#[test] +fn several_files_arrive_in_one_call() { + let mut rt = run(false); + drop_at(&mut rt, &["a.png", "b.JPG", "c.txt"], (50.0, 50.0)); + assert_eq!(dropped(&rt), [("inner", vec!["a.png", "b.JPG"])], "the target gets the files it accepts, together"); + drop_at(&mut rt, &["a.png", "c.txt"], (150.0, 150.0)); + assert_eq!(dropped(&rt)[1], ("outer", vec!["a.png", "c.txt"])); +} + +#[test] +fn a_covered_window_takes_a_drop_on_the_tree_it_has_now() { + let mut rt = run(true); + rt.set_live_visible(false); + // While covered, the window builds nothing: the inner zone unmounts only in state. + rt.update(|s, _| s.no_inner = true); + rt.drag_files(files(&["a.png"]), Some((50.0, 50.0))); + rt.drop_files(files(&["a.png"]), Some((50.0, 50.0))); + rt.hidden_wake(); + assert_eq!(dropped(&rt), [("outer", vec!["a.png"])], "not the inner zone, which has gone"); + assert_eq!(rt.state.hover, [("outer", true), ("outer", false)]); + + // Nor the zone behind a modal opened while covered (which, still fading in, takes none). + rt.update(|s, _| s.modal = true); + rt.drop_files(files(&["b.png"]), Some((150.0, 150.0))); + rt.hidden_wake(); + assert_eq!(dropped(&rt).len(), 1); +} + +#[test] +fn a_drop_outside_the_window_or_an_open_modal_reaches_nothing() { + let mut rt = run(true); + drop_at(&mut rt, &["a.png"], (450.0, 50.0)); + assert_eq!(dropped(&rt), [], "the root takes drops only inside the window"); + rt.update(|s, _| s.modal = true); + rt.frame(2.0 / 60.0); + rt.drag_files(files(&["a.png"]), Some((50.0, 50.0))); + rt.frame(3.0 / 60.0); + assert_eq!(rt.drop_hovered(), None, "the dimmed window behind a modal takes no drag"); + rt.drop_files(files(&["a.png"]), Some((50.0, 50.0))); + rt.frame(4.0 / 60.0); + assert_eq!(dropped(&rt), []); + drop_at(&mut rt, &["b.png"], (150.0, 150.0)); + assert_eq!(dropped(&rt), [("modal", vec!["b.png"])]); + assert_eq!(rt.state.hover, [("modal", true), ("modal", false)]); +} + +#[test] +fn a_hovered_target_that_unmounts_hears_its_hover_end() { + let mut rt = run(false); + rt.drag_files(files(&["a.png"]), Some((50.0, 50.0))); + rt.frame(1.0 / 60.0); + rt.update(|s, _| s.no_inner = true); + rt.frame(2.0 / 60.0); + // The host samples the pointer while the drag lasts; the target under it has changed. + assert!(rt.drag_files_to(Some((50.0, 50.0)))); + rt.frame(3.0 / 60.0); + assert_eq!(rt.state.hover, [("inner", true), ("inner", false), ("outer", true)]); + assert_eq!(rt.drop_hovered().as_deref(), Some("outer")); +} + +#[test] +fn moving_over_one_target_queues_no_frames() { + let mut rt = run(false); + rt.drag_files(files(&["a.png"]), Some((50.0, 50.0))); + rt.frame(1.0 / 60.0); + for x in 51..90 { + assert!(!rt.drag_files_to(Some((x as f32, 50.0))), "still over the inner zone"); + } + assert!(!rt.has_pending_input(), "so the host draws nothing"); + assert!(rt.drag_files_to(Some((150.0, 150.0))), "onto the outer zone"); + assert!(rt.has_pending_input()); +} + +#[test] +fn a_drop_zone_over_other_elements_leaves_their_menus_and_help() { + #[derive(Default)] + struct S { menus: u32 } + fn view(_: &S, _: &mut Cx<S>) -> El { + el().w_full().h_full() + .child(el().key("row").size(100.0, 40.0).help("Row").on_secondary_press(|s: &mut S, _, _| s.menus += 1)) + .child(el().key("zone").absolute(0.0, 0.0).w_full().h_full().on_drop_files(|_: &mut S, _, _| {})) + } + let mut rt = Runtime::new(S::default(), view, (300.0, 300.0), Env::new(true, 1.0)); + rt.frame(0.0); + rt.secondary_down(10.0, 10.0); + rt.secondary_up(10.0, 10.0); + rt.frame(1.0 / 60.0); + assert_eq!(rt.state.menus, 1, "the row's context menu"); + rt.observe_pointer(10.0, 10.0); + rt.frame(2.0 / 60.0); + rt.frame(rt.help_delay); + assert_eq!(rt.help_tooltip().map(|(t, _)| t), Some("Row")); +} + +#[test] +fn a_covered_window_still_takes_a_drop() { + let mut rt = run(false); + // As the host does for `WindowEvent::Occluded(true)`, then for a drop (`covered_step`). + rt.set_live_visible(false); + rt.drag_files(files(&["a.png"]), Some((50.0, 50.0))); + rt.drop_files(files(&["a.png"]), Some((50.0, 50.0))); + assert!(rt.has_pending_input()); + rt.hidden_wake(); + assert_eq!(dropped(&rt), [("inner", vec!["a.png"])]); + assert_eq!(rt.state.hover, [("inner", true), ("inner", false)]); +} + +#[derive(Default)] +struct Picky { + dropped: Vec<(&'static str, Vec<String>)>, + rejected: Vec<Vec<String>>, + hover: Vec<(&'static str, bool)>, +} + +fn names(files: &[PathBuf]) -> Vec<String> { files.iter().map(|f| f.display().to_string()).collect() } + +/// A zone that takes only exports, and says why it refuses anything else, inside one that takes +/// anything. +fn picky(_: &Picky, _: &mut Cx<Picky>) -> El { + let exports = el().key("exports").size(100.0, 100.0) + .on_drop_files(|s: &mut Picky, files, _| s.dropped.push(("exports", names(files)))) + .accepts_extensions(&["json"]) + .on_drop_hover(|s: &mut Picky, over, _| s.hover.push(("exports", over))) + .on_drop_rejected(|s: &mut Picky, files, _| s.rejected.push(names(files))) + .on_drop_rejected_hover(|s: &mut Picky, over, _| s.hover.push(("exports-rejected", over))); + col().w_full().h_full().child( + el().key("outer").size(200.0, 200.0) + .on_drop_files(|s: &mut Picky, files, _| s.dropped.push(("outer", names(files)))) + .on_drop_hover(|s: &mut Picky, over, _| s.hover.push(("outer", over))) + .child(exports), + ) +} + +#[test] +fn a_target_that_hears_rejected_drops_stops_them_and_shows_its_own_hover() { + let mut rt = Runtime::new(Picky::default(), picky, (400.0, 300.0), Env::new(true, 1.0)); + rt.frame(0.0); + rt.drag_files(files(&["notes.txt"]), Some((50.0, 50.0))); + rt.frame(1.0 / 60.0); + assert_eq!(rt.state.hover, [("exports-rejected", true)], "not the outer zone's hover"); + assert_eq!((rt.drop_rejected_hovered().as_deref(), rt.drop_hovered()), (Some("exports"), None)); + rt.drag_files_to(Some((150.0, 150.0))); + rt.frame(2.0 / 60.0); + assert_eq!(rt.state.hover[1..], [("exports-rejected", false), ("outer", true)]); + assert_eq!((rt.drop_rejected_hovered(), rt.drop_hovered().as_deref()), (None, Some("outer"))); + rt.drag_files_to(Some((50.0, 50.0))); + rt.drop_files(files(&["notes.txt"]), Some((50.0, 50.0))); + rt.frame(3.0 / 60.0); + assert_eq!(rt.state.hover[3..], [("outer", false), ("exports-rejected", true), ("exports-rejected", false)], "dropping ends it"); + assert_eq!((rt.state.rejected.as_slice(), rt.state.dropped.as_slice()), (&[vec!["notes.txt".to_owned()]][..], &[][..])); + + rt.state.hover.clear(); + rt.drag_files(files(&["a.json", "b.txt"]), Some((50.0, 50.0))); + rt.frame(4.0 / 60.0); + assert_eq!(rt.state.hover, [("exports", true)], "a drag carrying an export is accepted"); + rt.drop_files(files(&["a.json", "b.txt"]), Some((50.0, 50.0))); + rt.frame(5.0 / 60.0); + assert_eq!(rt.state.dropped, [("exports", vec!["a.json".to_owned()])]); + assert_eq!(rt.state.rejected[1..], [vec!["b.txt".to_owned()]], "and the rest are rejected"); + + rt.drag_files(files(&["a.json"]), Some((50.0, 50.0))); + rt.frame(6.0 / 60.0); + rt.drag_files_leave(); + rt.drag_files(files(&["c.txt"]), Some((50.0, 50.0))); + rt.frame(7.0 / 60.0); + assert_eq!(rt.state.hover[2..], [("exports", true), ("exports", false), ("exports-rejected", true)], "the same target swaps hovers"); + + rt.drag_files_leave(); + rt.frame(8.0 / 60.0); + rt.state.hover.clear(); + rt.drag_files(Vec::new(), Some((50.0, 50.0))); + rt.drop_files(Vec::new(), Some((50.0, 50.0))); + rt.frame(9.0 / 60.0); + assert!(rt.state.hover.is_empty() && rt.drop_rejected_hovered().is_none(), "an empty drag claims no rejected hover"); +} + +#[test] +fn a_target_that_follows_the_drag_hears_its_point_on_the_element_and_where_it_dropped() { + #[derive(Default)] + struct Caret { seen: Vec<(&'static str, Option<(f32, f32)>)> } + fn view(_: &Caret, _: &mut Cx<Caret>) -> El { + let local = |tx: &crate::Tx| tx.drop_point().map(|p| (p.x, p.y)); + col().w_full().h_full().children([ + el().size(200.0, 20.0), + el().key("doc").size(200.0, 100.0) + .on_drop_files(move |s: &mut Caret, _, tx| s.seen.push(("drop", local(tx)))) + .on_drop_hover(move |s: &mut Caret, over, tx| s.seen.push((if over { "over" } else { "off" }, local(tx)))) + .on_drop_move(|s: &mut Caret, p, tx| { assert_eq!(tx.drop_point(), Some(p)); s.seen.push(("move", Some((p.x, p.y)))) }), + el().key("plain").size(200.0, 100.0).on_drop_files(|_: &mut Caret, _, _| {}), + ]) + } + let mut rt = Runtime::new(Caret::default(), view, (400.0, 300.0), Env::new(true, 1.0)); + rt.frame(0.0); + let take = |rt: &mut Runtime<Caret>| std::mem::take(&mut rt.state.seen); + rt.drag_files(files(&["a.txt"]), Some((30.0, 40.0))); + rt.frame(1.0 / 60.0); + assert_eq!(take(&mut rt), [("over", Some((30.0, 20.0))), ("move", Some((30.0, 20.0)))], "points on the element, below its 20 pt neighbour"); + + assert!(!rt.drag_files_to(Some((30.0, 40.0))), "a drag that didn't move asks for nothing"); + assert!(rt.drag_files_to(Some((50.0, 60.0))), "a move over a target that follows it asks for a frame"); + assert!(!rt.drag_files_to(Some((60.0, 70.0))), "once a frame"); + rt.frame(2.0 / 60.0); + assert_eq!(take(&mut rt), [("move", Some((60.0, 50.0)))], "at the latest point"); + + assert!(rt.drag_files_to(Some((60.0, 150.0))), "onto another target"); + rt.frame(3.0 / 60.0); + assert_eq!(take(&mut rt), [("off", None)]); + assert!(!rt.drag_files_to(Some((70.0, 160.0))), "a target that doesn't follow the drag asks for no frames as it moves"); + + rt.drag_files(files(&["a.txt"]), Some((70.0, 80.0))); + rt.drop_files(files(&["a.txt"]), Some((70.0, 80.0))); + rt.frame(4.0 / 60.0); + assert_eq!(take(&mut rt), [("over", Some((70.0, 60.0))), ("move", Some((70.0, 60.0))), ("off", None), ("drop", Some((70.0, 60.0)))]); +} + +#[test] +fn a_drag_that_left_or_dropped_carries_nothing_into_the_next_sample() { + let mut rt = run(false); + rt.drag_files(files(&["a.png"]), Some((50.0, 50.0))); + rt.drag_files_leave(); + assert!(!rt.drag_files_to(Some((150.0, 150.0))), "no drag: a sample queues nothing"); + rt.frame(1.0 / 60.0); + drop_at(&mut rt, &["a.png"], (50.0, 50.0)); + assert!(!rt.dragging_files() && !rt.drag_files_to(Some((150.0, 150.0)))); + rt.state.hover.clear(); + rt.drag_files(files(&["notes.txt"]), Some((50.0, 50.0))); + rt.frame(3.0 / 60.0); + assert_eq!(rt.state.hover, [("outer", true)], "the next drag starts from its own files, not the last one's"); +} diff --git a/app/vendor/rune/crates/rune/src/runtime/elements.rs b/app/vendor/rune/crates/rune/src/runtime/elements.rs new file mode 100644 index 0000000..3df1970 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/elements.rs @@ -0,0 +1,547 @@ +//! Element inspection (`Runtime::elements`, `presented`, `presented_pose`) and point picking +//! (`Runtime::element_at`, `contains`, `find`). +use super::*; + +/// What tools see of one element. +#[derive(Clone, Debug)] +pub struct ElementInfo { + pub trace_name: Option<&'static str>, + pub trace_namespace: Option<(&'static str, &'static str)>, + pub loop_phase: Option<f64>, + pub focusable: bool, + pub focused: bool, + pub focus_visible: bool, + pub inert: bool, + /// Playing its exit transition, or inside an element that is. Lookups by key treat it + /// as gone; it stays listed so tools can watch the exit. + pub exiting: bool, + pub path: String, + pub key: Option<String>, + pub role: &'static str, + pub label: Option<String>, + /// What a text element shows (none for a secure field). An element of role `"text"` drawn + /// from several texts, such as rune-kit's `RollingText`, gives its label. + pub text: Option<String>, + pub rect: [f32; 4], + pub target: [f32; 4], + pub opacity: f32, + /// Effective uniform scale, including ancestors and the presence transition. + pub scale: f32, + /// Additive blur culling margin in logical points, including scaled ancestor sigmas. + /// Three times this value bounds filter support; it is not the equivalent Gaussian sigma. + pub blur: f32, + pub radius: f32, + pub fill: Color, + pub text_color: Option<Color>, + pub hover: f32, + pub press: f32, + pub moving: bool, + pub parent: Option<usize>, + /// The part of `rect` its ancestors' clips leave visible. + pub visible: [f32; 4], + /// Words of this text are still fading in. + pub revealing: bool, + /// Inside a growth row whose height is moving: its visible part is being revealed. + pub in_growing_row: bool, + /// This node is riding a scroll: a wheel or trackpad, its momentum, or a glide + /// (`Tx::scroll_to`, `scroll_to_with`, `scroll_to_bottom`). + pub scrolling: bool, + /// How far its scroll viewports' offsets carry it this frame, x and y in the window's points + /// (scaled and turned as `rect` is): `rect` sits this much left and up of where it would + /// unscrolled. Motion checks add it back, so they judge an element against the content it + /// scrolls with. + pub scrolled: [f32; 2], + /// Invisible estimated extent of a virtual list, not a drawable surface. + pub virtual_extent: bool, + /// Property-specific intentional cuts for 1:1 live bindings (never smoothed bindings). + pub live_intent: u32, + /// On the focused text field: its caret line in window points (see [`Cx::caret`]). + pub caret: Option<[f32; 4]>, + /// On the focused text field, unless secure: its selection's anchor and focus, UTF-8 bytes + /// of its text (equal for a caret). + pub edit_range: Option<[usize; 2]>, + /// Dragging it starts an OS drag ([`El::drag_out`]). + pub drag_out: bool, + /// Its tooltip and accessibility help ([`El::help`]). + pub help: Option<String>, + /// The part of this [`El::selectable`] text that is selected, as copying would take it. + pub selected: Option<String>, + /// Its outline depth ([`El::level`]). + pub level: Option<u32>, + /// Whether it is open ([`El::expanded`]); `None` when it can't open. + pub expanded: Option<bool>, + /// A selected item of a list, tree, table or group ([`El::focus_selected`]). + pub item_selected: bool, + /// How far [`El::sticky_top`], [`El::sticky_bottom`] or [`El::sticky_left`] moved it from + /// where scrolling put it this frame, in points: down for a stuck header, up for a stuck + /// footer, right for a stuck left element, 0 when it isn't stuck. `rect` already includes it. + pub stuck: f32, +} + +/// An element [`Runtime::element_at`] found. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Picked { + path: String, + key: Option<String>, +} + +/// Options for [`Runtime::element_at_with`] and its siblings. Fields are private, so options can +/// be added without breaking callers; `Pick::default()` is [`Runtime::element_at`]'s behaviour. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct Pick { + transparent: bool, +} + +impl Pick { + pub fn new() -> Self { Self::default() } + + /// Also find elements whose own or inherited opacity is 0, as a design canvas does to + /// select an invisible layer. Exiting elements are skipped either way, and so are hidden + /// or unmounted ones. + pub fn transparent(mut self, on: bool) -> Self { + self.transparent = on; + self + } +} + +impl Picked { + /// Its path in the element tree (as [`ElementInfo::path`]). + pub fn path(&self) -> &str { &self.path } + /// Its key ([`El::key`]), if it has one. + pub fn key(&self) -> Option<&str> { self.key.as_deref() } +} + +/// What an element presents beyond its rect and opacity, as of the last frame +/// ([`Runtime::presented_pose`]). +#[derive(Clone, Debug, PartialEq)] +pub struct Pose { + rotation: f32, + scale: f32, + shadows: Vec<crate::el::Shadow>, + moving: bool, +} + +impl Pose { + /// The element's own presented `El::rotate`, in radians clockwise. Ancestors' turns are not + /// included. + pub fn rotation(&self) -> f32 { self.rotation } + /// Effective uniform scale, ancestors included (as [`ElementInfo::scale`]). + pub fn scale(&self) -> f32 { self.scale } + /// The element's shadows (`El::box_shadow`) at their current sprung geometry and colour. + pub fn shadows(&self) -> &[crate::el::Shadow] { &self.shadows } + /// A spring or decorative loop still moves its rect, scale, rotation, icon turn or shadows, + /// or an ancestor's. An active repeating loop does not settle. + pub fn moving(&self) -> bool { self.moving } +} + +impl types::TreeState { + /// Authored geometry goals, before scroll and spring sampling, in parent space. + pub(crate) fn trace_goals(&self) -> impl Iterator<Item = (&str, [f32; 7])> { + self.nodes.iter().map(|n| (n.path.as_str(), [n.local.x, n.local.y, n.local.w, n.local.h, n.vis.offset[0], n.vis.offset[1], n.static_scale])) + } + + /// Elements that draw nothing and hold nothing: no paint of their own, no text, no field, + /// no focus, no children. Hit and hover zones, spacers. A trace flags them: nobody can see + /// them come, go or move. + pub(crate) fn blank_leaves(&self) -> HashSet<&str> { + let mut parents = vec![false; self.nodes.len()]; + for n in &self.nodes { + if let Some(p) = n.parent { parents[p] = true; } + } + self.nodes.iter().enumerate().filter(|&(i, n)| { + let v = &n.vis; + !parents[i] && n.text.is_none() && n.input.is_none() && !n.focus.enabled && n.material.is_none() + && v.fill.a == 0.0 && (v.border_width() == 0.0 || v.border().a == 0.0 && v.border_bottom.is_none_or(|c| c.a == 0.0)) + && v.shadows.is_empty() && v.surface.is_none() && v.icon.is_none() && v.gradient.is_none() && v.radial.is_none() + && v.outline.is_none() && v.shape.is_none() && v.grid.is_none() && v.pixels.is_none() && v.effect.is_none() + && v.hover().a == 0.0 && v.press().a == 0.0 + }).map(|(_, n)| n.path.as_str()).collect() + } + + /// Video elements' playback state by element path, for `--tree`. + pub(crate) fn videos(&self) -> HashMap<String, crate::video::Snapshot> { + self.nodes.iter() + .filter_map(|n| Some((n.path.clone(), n.vis.surface.as_ref()?.0.video()?.snapshot()))) + .collect() + } + + /// Whether an element path contains secure text, hidden or revealed. Accessibility + /// adapters should use this alongside [`Runtime::elements`] to report protected content. + /// Unknown paths (including synthetic flight/link paths) return false. + pub(crate) fn element_is_secure(&self, path: &str) -> bool { + self.nodes.iter().find(|n| n.path == path).is_some_and(Node::is_secure) + } +} + +impl RuntimeCore { + /// Tracks the last tick sampled, by element path and property name: what spent this + /// frame animating. Tracks of nodes no longer in the tree report their node id. + pub(crate) fn touched_tracks(&self) -> Vec<(String, &'static str, bool)> { + let store = self.scene.store(); + let mut out: Vec<_> = store.touched_tracks().map(|(track, node, p)| { + let path = self.tree.node_by_id(node).map_or_else(|| format!("node:{}", node.0), |n| n.path.clone()); + (path, prop_name(p.0), store.is_active(track)) + }).collect(); + // A growth row's feathered edge (`GrowTrack::mask`) paints as it eases out, after its height + // has landed: it is a track of its own here. + out.extend(self.motion.grows.iter().filter(|(_, g)| g.mask > 0.01).filter_map(|(&id, _)| { + self.tree.node_by_id(id).map(|n| (n.path.clone(), "mask", true)) + })); + out.sort(); + out.dedup(); + out + } + + /// What a move of `v` points inside node `i` (a scroll viewport's offset) comes to in the + /// window: scaled and turned as its children draw. + pub(crate) fn content_to_window(&self, i: usize, v: [f32; 2]) -> [f32; 2] { + let Some(h) = self.paint.inh_scratch.get(i) else { return v }; + let [x, y] = v.map(|c| c * h.scale); + match h.turn.checked_sub(1).and_then(|k| self.paint.turn_scratch.get(k as usize)) { + Some(t) => [t.mat[0] * x + t.mat[1] * y, t.mat[2] * x + t.mat[3] * y], + None => [x, y], + } + } + + pub fn elements(&self) -> Vec<ElementInfo> { + fn intent(n: &Node) -> u32 { + n.live.iter().filter(|b| b.spring.is_none()).fold(0, |bits, b| bits | match b.property { + crate::live::Property::Offset => 1, + crate::live::Property::Scale | crate::live::Property::Rect => 1 | 2, + crate::live::Property::Opacity => 4, + _ => 0, + }) + } + let store = self.scene.store(); + let animating = |id: NodeId| store.is_animating(id, prop::FRAME) || store.is_animating(id, prop::TRAVEL) + || store.is_animating(id, prop::PRESENCE) || store.is_animating(id, prop::OFFSET) || store.is_animating(id, prop::SCALE) || store.is_animating(id, P_PRESS_SCALE) + || store.is_animating(id, P_SCALE) || store.is_animating(id, prop::ROTATION) || paint_pose_springing(store, id) + || (!self.reduced_motion && self.motion.loop_active(id, store.node_time(id))); + let sel_ranges = self.selection_ranges(); + let mut elements: Vec<_> = self.tree.nodes + .iter() + .enumerate() + .filter_map(|(i, n)| { + let p = self.scene.presented(n.id)?; + let exiting = self.subtree_exiting(i); + let flight = self.motion.flights().iter().find(|f| f.lands(&n.path, n.key.as_deref())); + let mut moving = flight.is_some() || animating(n.id) || self.motion.grows.get(&n.id).is_some_and(|g| g.moving()); + let drawn = self.paint.drawn.get(i).copied().unwrap_or([p.rect.x, p.rect.y, p.rect.w, p.rect.h]); + // A flight carries the destination's laid-out text, which can be narrower than + // its box. Report the box carried along with it, so the element lands on its own + // frame instead of jumping out to it when the flight ends. + let rect = flight.map_or(drawn, |f| { + let (d, c) = (f.destination, f.presented); + let (zx, zy) = (c.w / d.w.max(1e-3), c.h / d.h.max(1e-3)); + [c.x + (drawn[0] - d.x) * zx, c.y + (drawn[1] - d.y) * zy, drawn[2] * zx, drawn[3] * zy] + }); + let s = self.env.scale; + let clip = if self.motion.launches().flying(n.id) { NO_CLIP } else { + flight.map_or_else(|| self.screen_clip_of_parent(n.parent), |f| f.clip.map(|v| v * s)) + }; + let (x0, y0) = (rect[0].max(clip[0] / s), rect[1].max(clip[1] / s)); + let (x1, y1) = ((rect[0] + rect[2]).min(clip[2] / s), (rect[1] + rect[3]).min(clip[3] / s)); + let visible = [x0, y0, (x1 - x0).max(0.0), (y1 - y0).max(0.0)]; + let revealing = flight.is_some() || self.motion.reveal_fading(n.id); + let mut in_growing_row = false; + let mut scrolling = false; + let mut scrolled = [0.0; 2]; + let mut live_intent = intent(n); + // Held at its landing width this frame: its re-layout is the design. + if self.motion.holds_landing(n.id) { + live_intent |= 1 | 2; + } + // A group_opacity swap under an instant hover group is a deliberate cut (Beta's + // status/close swap), for it and what it contains: opacity and transition intent. + let up = |from: Option<usize>| std::iter::successors(from, |&pi| self.tree.nodes[pi].parent); + if let Some(gi) = up(Some(i)).find(|&j| self.tree.nodes[j].vis.group_opacity.is_some()) { + let group = up(self.tree.nodes[gi].parent) + .map(|pi| &self.tree.nodes[pi]) + .find(|g| g.vis.hover().a > 0.0 || g.vis_flags.hover_group()); + if group.and_then(|g| g.hover_motion()).is_some_and(|(e, x)| [e, x].iter().any(|a| matches!(a.curve, rune_motion::Curve::Instant))) { + live_intent |= 4 | 16; + } + } + // Offsets are in points inside the scroll viewport; `rect` is in the window, after + // every scale and turn above. Below a lift (a flight or launch drawn over the + // window), the scales holding still above it carry them, unturned. + let mut lifted = None; + let mut j = i; + loop { + let to_window = |at: Option<usize>, v: [f32; 2]| match lifted { + Some(k) => v.map(|c| c * k), + None => at.map_or(v, |at| self.content_to_window(at, v)), + }; + if j != i && let Some(st) = self.scroll.scrolls.get(&self.tree.nodes[j].id) { + let [x, y] = to_window(Some(j), [st.drawn_x, st.drawn.y()]); + scrolled = [scrolled[0] + x, scrolled[1] + y]; + } + // A launch, and what it carries, leaves under the offsets it launched against + // and takes on the scroll's only as it lands. + let id = self.tree.nodes[j].id; + let parent = self.tree.nodes[j].parent; + let fix = self.motion.launches().carried(&self.scene, id); + if fix != [0.0; 2] { + let k = parent.and_then(|p| self.paint.inh_scratch.get(p)).map_or(1.0, |h| h.still.0); + scrolled = [scrolled[0] - fix[0] * k, scrolled[1] - fix[1] * k]; + } + if lifted.is_none() && self.motion.flying.iter().any(|f| f.0 == id) { + lifted = Some(parent.and_then(|p| self.paint.inh_scratch.get(p)).map_or(1.0, |h| h.still.0)); + } + let Some(pi) = step_up(&self.tree.nodes, j) else { break }; + let p = &self.tree.nodes[pi]; + moving |= animating(p.id) + || self.motion.stacks.get(&p.id).is_some_and(|s| s.moving) + || self.scroll.scrolls.get(&p.id).is_some_and(|s| s.slack.moving() || s.glide().is_some()); + live_intent |= intent(p); + scrolling |= self.scroll.scrolls.get(&p.id).is_some_and(ScrollState::moving); + in_growing_row |= self.motion.grows.get(&p.id).is_some_and(|g| g.moving()); + j = pi; + } + let secure = n.is_secure(); + Some(ElementInfo { + trace_name: n.trace_name, + trace_namespace: n.trace_namespace, + loop_phase: self.motion.loop_track(n.id).map(|l| { + if self.reduced_motion && !matches!(n.looping.as_ref().map(|s| s.kind), Some(rune_motion::LoopKind::Sequence(_))) { 0.0 } + else { l.phase(self.scene.store().node_time(n.id)) } + }), + focusable: self.can_focus(i), + focused: self.kbd.focus.path() == Some(&n.path), + focus_visible: self.kbd.focus.keyboard() && self.kbd.focus.path() == Some(&n.path), + inert: !self.allowed(i) || exiting, + exiting, + path: n.path.clone(), + key: n.key.clone(), + role: n.role, + label: n.label.as_deref().map(str::to_owned), + text: match &n.text { + Some(t) => (!secure).then(|| t.source_text().to_owned()), + // A text built from several (a rolling label's glyphs) reads as its label. + None => (!secure).then(|| n.label.as_deref().map(str::to_owned)).flatten().filter(|_| n.role == "text"), + }, + rect, + target: [n.target[0], n.target[1], n.target[2] - n.target[0], n.target[3] - n.target[1]], + opacity: flight.map_or_else(|| self.paint.inh_scratch.get(i).map_or(p.opacity, |h| h.opacity), |f| f.target_alpha), + scale: if flight.is_some() { 1.0 } else { self.paint.inh_scratch.get(i).map_or(p.transform.scale.x, |h| h.scale) }, + blur: if flight.is_some() { 0.0 } else { self.paint.inh_scratch.get(i).map_or(p.blur, |h| h.blur) }, + radius: p.radius.0[0], + fill: self.color(n.id, P_FILL, n.vis.fill), + text_color: paint_tracks::text_color(n) + .map(|c| paint_tracks::group_tint(n, self.color(n.id, P_TEXT, c), self.paint.inh_scratch.get(i).map_or(0.0, |h| h.group))), + hover: if (n.focus.highlight.is_some() && self.highlight_visible(i)) || (n.focus.fill.is_some() && self.focus_ring_visible(i)) { 1.0 } + else { self.scene.get(n.id, P_HOVER).unwrap_or(0.0) }, + press: self.scene.get(n.id, P_PRESS).unwrap_or(0.0), + moving, + parent: n.parent, + visible, + revealing, + in_growing_row, + scrolling, + scrolled, + live_intent, + caret: self.caret_rect(&self.tree.nodes, i), + edit_range: n.input.as_ref().filter(|inp| inp.edit.focused && !inp.edit.is_secure()).map(|inp| [inp.edit.anchor, inp.edit.focus]), + drag_out: n.handlers.drag_out.is_some(), + help: n.help.as_deref().filter(|_| !n.help_cut || n.text_cut(s)).map(|h| crate::el::help_words(h).into_owned()), + selected: n.text.as_ref().filter(|t| t.selectable && !secure).and_then(|t| { + let (a, b) = selectable::range_in(&sel_ranges, i)?; + t.copy_slice(a as u32, b as u32) + }), + level: n.a11y.level, + expanded: n.a11y.expanded, + item_selected: n.focus.selected, + stuck: self.scroll.stuck.get(i).copied().unwrap_or(0.0), + virtual_extent: self.commit.virtuals.contains_key(&n.path) && n.vis.fill.a == 0.0 + && n.vis.border_width() == 0.0 && n.vis.shadows.is_empty() && n.text.is_none() && n.vis.icon.is_none(), + }) + }) + .collect(); + for f in self.motion.flights() { + let r = if self.reduced_motion { f.source } else { f.presented }; + let c = if self.reduced_motion { f.source_clip } else { f.clip }; + let path = format!("flight-source/{}", f.target_key); + let t = f.destination; + elements.push(ElementInfo { + trace_name: None, + trace_namespace: None, + loop_phase: None, + focusable: false, focused: false, focus_visible: false, inert: true, exiting: false, + key: Some(path.clone()), path, role: "text", label: None, text: None, + rect: [r.x, r.y, r.w, r.h], target: [t.x, t.y, t.w, t.h], + opacity: f.source_alpha, scale: 1.0, blur: 0.0, radius: 0.0, fill: Color::TRANSPARENT, text_color: None, + hover: 0.0, press: 0.0, moving: true, parent: None, + visible: [r.x.max(c[0]), r.y.max(c[1]), (r.edges()[2].min(c[2]) - r.x.max(c[0])).max(0.0), + (r.edges()[3].min(c[3]) - r.y.max(c[1])).max(0.0)], + revealing: true, in_growing_row: false, scrolling: false, scrolled: [0.0; 2], virtual_extent: false, live_intent: 0, caret: None, edit_range: None, drag_out: false, + help: None, selected: None, level: None, expanded: None, item_selected: false, stuck: 0.0, + }); + } + self.link_elements(&mut elements); + self.highlight_elements(&mut elements); + elements + } + + /// Index of the first live (non-exiting, mounted) node matching `key` within optional ancestor + /// `scope`. Matches [`Node::named`] (key, full path, or keyed-ancestor suffix such as + /// `slider/knob`) and `/`-separated path suffixes. + pub(crate) fn live_named(&self, scope: Option<&str>, key: &str) -> Option<usize> { + if key.is_empty() { return None; } + let has_slash = key.contains('/'); + (0..self.tree.nodes.len()).find(|&i| { + let n = &self.tree.nodes[i]; + let matched = n.named(key) + || (has_slash && (n.path.strip_suffix(key).is_some_and(|head| head.ends_with('/')) || keyed_suffix(&n.path, key))); + matched && !self.subtree_exiting(i) && !self.subtree_unmounted(i) + && n.parent.is_none_or(|p| in_scope(&self.tree.nodes[p].path, scope)) + }) + } + + /// Centre of the first element whose key is `key`, or whose path ends with `key` when it + /// contains a `/` (e.g. `slider/knob`), in points. Elements without keys between them don't + /// count, so `slider/knob` finds a knob inside unkeyed rows inside the slider. Failing that, + /// the first line box of the link (`El::link`) or highlight (`El::text_highlight`) keyed + /// `key`. Exiting elements and their children are gone here; [`Runtime::presented`] still + /// reads them. + pub fn find(&self, key: &str) -> Option<(f32, f32)> { + let Some(i) = self.live_named(None, key) else { return self.find_link(key).or_else(|| self.find_highlight(key)) }; + let r = self.paint.drawn.get(i).copied()?; + Some((r[0] + r[2] * 0.5, r[1] + r[3] * 0.5)) + } + + /// Drawn rect `[x, y, w, h]` in points and effective opacity (ancestors included) of the + /// element keyed `key`, exiting or not, as of the last frame. + pub fn presented(&self, key: &str) -> Option<([f32; 4], f32)> { + let i = self.tree.index_of_key(key)?; + Some((*self.paint.drawn.get(i)?, self.paint.inh_scratch.get(i)?.opacity)) + } + + /// The topmost element drawn at window point (`x`, `y`) in points, as of the last frame: the + /// point is tested against each element's drawn box the way a press is, through `El::rotate`, + /// `El::scale`, `El::origin`, offsets and scrolling, and inside its ancestors' clips + /// (including a turned ancestor's clip), in paint order (so `El::raise`, sticky and flying + /// elements count). Unlike a press, it also finds elements with no handlers, and it ignores + /// `El::inert` and modals, so a press can land on a different element than this returns. + /// Elements that are exiting or fully transparent are skipped (see [`Runtime::element_at_with`] to include transparent ones). `El::hit`, which marks native + /// overlay input, makes no difference, and overlay panels outside the window are not + /// considered. An element is not cut by its own clip, only by its ancestors'. This is box + /// geometry, not pixel/alpha picking: a box with no fill remains pickable (as an invisible + /// input area does), and rounded corners and soft clip fades do not trim its hit box. + /// Running handlers can use [`Tx::element_at`] without holding a `Runtime`. + pub fn element_at(&self, x: f32, y: f32) -> Option<Picked> { + self.element_at_with(x, y, Pick::default()) + } + + /// [`Runtime::element_at`] with options: [`Pick::transparent`] also finds fully + /// transparent elements (exiting ones stay skipped). + pub fn element_at_with(&self, x: f32, y: f32, pick: Pick) -> Option<Picked> { + self.element_at_within(None, x, y, pick) + } + + pub(super) fn run_pick_reads(&mut self, app: &mut dyn AppDriver, tx: &mut Tx) { + for read in std::mem::take(&mut tx.pick_reads) { + let picked = self.element_at_within(read.within.as_deref(), read.x, read.y, read.pick); + if let Some(f) = read.take() { + f(app.states(), picked, tx); + self.commit.dirty = true; + } + } + // A callback may ask again, but cannot keep this dispatch running indefinitely. + self.frame.pending.pick_reads.append(&mut tx.pick_reads); + } + + /// [`Runtime::element_at`] restricted to an element and its descendants, ignoring other + /// subtrees. `within` accepts a key or key path as [`Cx::layout`] does. + pub fn element_at_in(&self, within: &str, x: f32, y: f32) -> Option<Picked> { + self.element_at_in_with(within, x, y, Pick::default()) + } + + /// [`Runtime::element_at_in`] with options, as [`Runtime::element_at_with`]. + pub fn element_at_in_with(&self, within: &str, x: f32, y: f32, pick: Pick) -> Option<Picked> { + self.element_at_within(Some(within), x, y, pick) + } + + fn element_at_within(&self, within: Option<&str>, x: f32, y: f32, pick: Pick) -> Option<Picked> { + let scope = match within { + Some(key) => Some(self.tree.selects_index(key)?), + None => None, + }; + let n = self.tree.nodes.len(); + let order = self.paint.layer_paint_order(); + let at = |k: usize| if order.is_empty() { k } else { order[k] }; + let count = if order.is_empty() { n } else { order.len() }; + (0..count).rev().map(at).find(|&i| { + scope.is_none_or(|scope| self.tree.is_descendant(i, scope)) + && self.pickable(i, x, y, pick) + }).map(|i| Picked { + path: self.tree.nodes[i].path.clone(), + key: self.tree.nodes[i].key.clone(), + }) + } + + /// Whether window point (`x`, `y`), in points, is inside the drawn, clipped and turned box + /// of the element keyed `key`, whatever is drawn above it and whether or not it has handlers. + /// False when there is no such element, it is exiting or fully transparent. Same geometry + /// as [`Runtime::element_at`]. + pub fn contains(&self, key: &str, x: f32, y: f32) -> bool { + self.contains_with(key, x, y, Pick::default()) + } + + /// [`Runtime::contains`] with options, as [`Runtime::element_at_with`]. + pub fn contains_with(&self, key: &str, x: f32, y: f32, pick: Pick) -> bool { + self.tree.selects_index(key).is_some_and(|i| self.pickable(i, x, y, pick)) + } + + fn pickable(&self, i: usize, x: f32, y: f32, pick: Pick) -> bool { + self.paint.drawn.get(i).is_some() + && self.paint.inh_scratch.get(i).is_some_and(|h| pick.transparent || h.opacity > 0.0) + && !self.subtree_exiting(i) + && self.node_contains(i, x, y) + } + + /// The presented rotation, scale and shadows of the element keyed `key`, exiting or not, as + /// of the last frame, and whether any spring still moves them. It reads the springs on + /// demand: nothing runs per frame for it. This is a driver/headless read: running view + /// functions and handlers do not hold a `Runtime`. + pub fn presented_pose(&self, key: &str) -> Option<Pose> { + let i = self.tree.selects_index(key)?; + let n = &self.tree.nodes[i]; + let store = self.scene.store(); + let shadows = n.vis.shadows.iter().enumerate().map(|(k, sh)| { + let sh = self.shadow_at(n.id, k, sh); + match P_SHADOWS.get(k) { + Some(&p) => crate::el::Shadow { color: self.color(n.id, p, sh.color), ..sh }, + None => sh, + } + }).collect(); + let moving = self.rect_springing(i) + || std::iter::successors(Some(i), |&p| step_up(&self.tree.nodes, p)).any(|p| { + let id = self.tree.nodes[p].id; + paint_pose_springing(store, id) + || (!self.reduced_motion && self.motion.loop_active(id, store.node_time(id))) + }); + Some(Pose { + rotation: self.scene.get(n.id, prop::ROTATION).unwrap_or(n.vis.rotate), + scale: self.paint.inh_scratch.get(i)?.scale, + shadows, + moving, + }) + } + + /// Whether the root's own fill is dark, when it has an opaque one (headless `--keys` caps + /// follow it, so they flip when the app changes theme itself). + pub(crate) fn backdrop_dark(&self) -> Option<bool> { + if self.transparent { return None; } + let n = self.tree.nodes.get(self.tree.app_root())?; + let c = self.color(n.id, P_FILL, n.vis.fill); + (c.a > 0.5).then(|| 0.2126 * c.r + 0.7152 * c.g + 0.0722 * c.b < 0.25) + } +} + +/// Whether `path`'s keyed segments end with `key`'s: `slider/knob` matches +/// `form/#2/slider/#0/knob`, since the `#n` segments stand for elements without keys. +fn keyed_suffix(path: &str, key: &str) -> bool { + let unkeyed = |s: &&str| s.len() > 1 && s.starts_with('#') && s[1..].bytes().all(|b| b.is_ascii_digit()); + let mut keyed = path.rsplit('/').filter(|s| !unkeyed(s)); + key.rsplit('/').all(|want| keyed.next() == Some(want)) +} diff --git a/app/vendor/rune/crates/rune/src/runtime/event_log.rs b/app/vendor/rune/crates/rune/src/runtime/event_log.rs new file mode 100644 index 0000000..a7e2806 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/event_log.rs @@ -0,0 +1,23 @@ +//! `Runtime::events`: input markers for `--trace` and headless inspection. A live window +//! records nothing unless tracing, and every runtime keeps at most `CAP` unread markers. + +/// Unread markers kept before the oldest half is dropped. +pub(crate) const CAP: usize = 512; + +/// Records a formatted marker in `rt.events` when anything reads them (a trace writer, or a +/// headless run: tests, scripts); formats nothing otherwise. Reads fields, not `&self`, so it +/// works while another field is borrowed. +macro_rules! log_event { + ($rt:expr, $($fmt:tt)+) => { + if $rt.frame.record_events() || $rt.frame.tracing_channels() { + let event = format!($($fmt)+); + $crate::runtime::event_log::push(&mut $rt.events, event); + } + }; +} +pub(crate) use log_event; + +pub(crate) fn push(events: &mut Vec<String>, event: String) { + if events.len() >= CAP { events.drain(..CAP / 2); } + events.push(event); +} diff --git a/app/vendor/rune/crates/rune/src/runtime/font_families.rs b/app/vendor/rune/crates/rune/src/runtime/font_families.rs new file mode 100644 index 0000000..38dc76d --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/font_families.rs @@ -0,0 +1,44 @@ +//! Switching the families behind the sans and mono slots while the app runs. + +use super::*; + +impl RuntimeCore { + /// Put `sans` and `mono` behind the `Family::Sans` and `Family::Mono` slots, as + /// `Tx::set_font_families` does from a handler. Every runtime on this thread follows on its + /// next frame (all of an app's windows and overlays), and windows opened later start in + /// them. This one drops what it shaped and measured in the old families now. Asking for the + /// families it already has costs nothing. + pub fn set_font_families(&mut self, sans: &str, mono: &str) { + crate::text::choose_families(sans, mono); + self.follow_font_families(); + } + + /// The sans and mono slots' families. + pub fn font_families(&self) -> (&str, &str) { + self.text.families() + } + + /// Whether `tx` switches the families. + pub(super) fn changes_families(&self, tx: &Tx) -> bool { + tx.font_families.as_ref().is_some_and(|(sans, mono)| self.text.families() != (sans.as_str(), mono.as_str())) + } + + /// Takes up families chosen, or a web app's full faces fetched, since this runtime last + /// looked. On a change, everything sized in the old fonts goes: memoized subtrees, and every + /// measured leaf's layout result. The text system has already dropped its layouts. True + /// when the next frame must build. + pub(crate) fn follow_font_families(&mut self) -> bool { + let chosen = self.text.follow_chosen(); + if !(self.text.follow_full_faces() || chosen) { + return false; + } + for n in &mut self.tree.nodes { + n.text_layout = None; + } + self.commit.clear_memo(); + self.commit.layout.mark_all_dirty(); + self.commit.dirty = true; + self.commit.relayout = true; + true + } +} diff --git a/app/vendor/rune/crates/rune/src/runtime/frame.rs b/app/vendor/rune/crates/rune/src/runtime/frame.rs new file mode 100644 index 0000000..2ddcf6d --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/frame.rs @@ -0,0 +1,477 @@ +//! Frame loop, clocks, wake deadlines, request latching and motion/paint-order stepping. +use super::*; + +mod latch; +mod motion; +mod wakes; + +impl RuntimeCore { + /// The last committed frame is out of date: state changed (an update, poll or handler), or + /// one asked for a scroll or text flight that waits for the next frame. + pub(crate) fn needs_commit(&self) -> bool { + self.commit.dirty || self.frame.pending.frame_work() || self.patch_pending() + } + + /// The last frame no longer shows the window: state, its size or queued input changed since. + pub(crate) fn stale(&self) -> bool { + self.needs_commit() || self.commit.relayout || !self.frame.queue.is_empty() + } + + /// A live-edit patch arrived that the next frame hasn't rebuilt the view with yet. + pub(crate) fn patch_pending(&self) -> bool { + self.frame.hot_pending() + } + + /// Marks app state changed outside a handler (the next frame re-runs the view). + pub fn invalidate(&mut self) { + self.commit.dirty = true; + } + + /// Lands every track before the next frame: growth, reveals and follow-the-end (guarantee 8, + /// for returning to a window or session). + pub fn settle_all(&mut self) { + self.commit.request_settle(); + self.commit.dirty = true; + } + + /// Advances animation time by `dt` real seconds, runs queued handlers, re-runs the view only + /// if state changed, steps `Scene`, growth, scroll and reveals, and builds this frame's + /// instances. + pub(crate) fn frame(&mut self, app: &mut dyn AppDriver, dt: f64) -> bool { + self.frame_split(app, 0.0, dt) + } + + /// A hidden or windowless host's due timer. + pub(crate) fn hidden_timer_frame(&mut self, app: &mut dyn AppDriver) { + self.frame(app, 0.0); + } + + /// Builds what changed while a window that fits its content was hidden, before the host + /// shows it, so the content's height (`window_frame`, a jump) is known before the window + /// is ordered in and its first drawable taken. Lands every track, as showing does. + /// Returns whether it built; the first frame then has nothing left to build. + pub(crate) fn build_for_show(&mut self, app: &mut dyn AppDriver) -> bool { + if !self.host.fit_height || self.commit.commits == 0 || !self.stale() { return false; } + self.settle_all(); + self.hidden_timer_frame(app); + true + } + + /// A hidden or covered host's due timer or wake. `poll` and due timers run now; the view + /// and layout wait, dirty, for the frame that shows the host. Queued input and drag ends take a frame + /// without drawing (`hidden_timer_frame`) so their handlers hear them now. Returns whether + /// the last drawn frame went out of date. + pub(crate) fn hidden_wake(&mut self, app: &mut dyn AppDriver) -> bool { + if self.has_pending_input() || self.drag_ends_pending() { + let commits = self.stats.commits; + self.hidden_timer_frame(app); + // File steps held for that frame's build land in another. + if self.files_held() { self.hidden_timer_frame(app); } + return self.stats.commits != commits; + } + self.poll_hidden(app) + } + + /// [`Runtime::hidden_wake`] for a shown window that can't draw (covered, minimised, on a + /// locked or sleeping display). While an assistive client reads its tree, what changed is + /// built at once, without drawing or motion, so the tree it reads and focus asked of what + /// the change shows (a permission's card) are current whatever the window's motion does. + /// Returns what `hidden_wake` does. + pub(crate) fn covered_wake(&mut self, app: &mut dyn AppDriver) -> bool { + let stale = self.hidden_wake(app); + if self.host.a11y.is_some() && self.needs_commit() { self.hidden_timer_frame(app); } + stale + } + + /// One frame in one pass that steps `catch_up + dt` seconds. Motion already running advances + /// `catch_up` before this frame's handlers and commit, so they retarget it from its pose at + /// the frame's time. Then everything, including what the commit started, steps `dt`. A late + /// frame or a sleeping host's gap belongs to old tracks, never to targets first observed + /// on this frame. + pub(crate) fn frame_split(&mut self, app: &mut dyn AppDriver, catch_up: f64, dt: f64) -> bool { + // Like a native shell: the logical clock follows host time (timers, poll), while + // animations step by the frame's own dt, so idle time never lands on a fresh commit. + let elapsed = catch_up + dt; + // A coarse headless step still polls at its timer deadlines, independent of FPS, as an + // idle window wakes for them. Like a window's timer floor (`window::timer_deadline`), + // a poll comes at most once a frame interval and takes every deadline due by then, so + // wakes that polls keep asking for collapse instead of each adding a poll per frame. + // Input queued for the requested frame stays at that frame's timestamp. The catch-up + // is the earliest part of the step. + let target = self.clock + elapsed; + if self.wall_start.is_none() && self.timer_step(target).is_some() { + let input = std::mem::take(&mut self.frame.queue); + let mut catch_up = catch_up; + while let Some(at) = self.timer_step(target) { + let step = at - self.clock; + let old = step.min(catch_up); + catch_up -= old; + self.frame_step(app, step, old, step - old); + } + self.frame.queue.extend(input); + let step = target - self.clock; + let old = step.min(catch_up); + return self.frame_step(app, step, old, step - old); + } + self.frame_step(app, elapsed, catch_up, dt) + } + + /// When a headless step toward `target` stops early for a timer: the next deadline, but no + /// sooner than a frame interval after the last poll. None when the step's own poll at + /// `target` takes everything due. + pub(super) fn timer_step(&self, target: f64) -> Option<f64> { + let deadline = self.logical_wake_deadline()?; + let at = deadline.max(self.clock + crate::window::TIMER_FRAME.as_secs_f64()); + (at < target).then_some(at) + } + + /// `elapsed` advances the logical clock when no wall clock drives it; `catch_up` steps + /// running motion before the commit and `dt` steps all motion after it. + pub(super) fn frame_step(&mut self, app: &mut dyn AppDriver, elapsed: f64, catch_up: f64, dt: f64) -> bool { + // Each queued action runs with its own input's arrival time; nothing else has one. + let _input = crate::input::time::scope(None); + self.interaction_frame_begins(); + let mut live_woke = self.take_live_wake(); + // Another window may have switched the font families since this one's last frame. + self.follow_font_families(); + for v in self.commit.virtuals.values_mut() { v.frame_begins(); } + #[cfg(feature = "hot")] + if self.frame.hot_changed() { + // Replace handler trait objects before queued input can call an old vtable. + // A regular commit preserves keyed nodes, scrolls and spring velocities. + self.commit.clear_memo(); + self.commit(app, &Tx::default()); + } + let mut tx = std::mem::take(&mut self.frame.pending); + let mut ran = false; + let mut why = if tx.polled_change && self.commit.dirty { CommitWhy::POLL } else { 0 }; + #[cfg(debug_assertions)] + let commits0 = self.commit.commits; + let shaped0 = self.text.shaped; + self.settled = false; + self.motion.clear_landing_holds(); + // `RUNE_LOOP_CHECK=1`: the frame that runs instead of a checked step samples at its clock. + self.clock = self.paint.take_cycle_check_clock().unwrap_or_else(|| self.wall_clock().unwrap_or(self.clock + elapsed)); + if self.wall_start.is_none() { + crate::video::headless_frame(self.clock); + // Fake recorders publish this frame's level to bound meters, drawn this frame. + crate::recorder::headless_frame(self.clock); + live_woke |= self.take_live_wake(); + } + if let Some((deadline, animation_time)) = self.motion.loop_wake() + && !self.animating + { + // Native shells cap dt after idle. Advance the sleeping part of the + // delay before new handlers retarget, without double-stepping manual time. + let elapsed = animation_time - (deadline - self.clock).max(0.0) * self.time_scale as f64; + self.t += (elapsed - self.t - (catch_up + dt) * self.time_scale as f64).max(0.0); + self.scene.set_time(self.t); + if self.clock >= deadline { self.motion.clear_loop_wake(); } + } + // Bring old tracks, growth and scroll to this frame's time before a poll or update + // retargets them. Presenting waits for `step_motion`, so the frame is sampled and + // built once. + if catch_up > 0.0 { self.catch_up_motion(catch_up); } + self.motion.keep_loops_on_clock(&self.scene, self.t, self.clock, self.time_scale, dt); + let (polled, due) = self.frame.begin_frame_poll(self.clock); + self.frame.idle_frame_begins(self.animating, polled || due > 0, live_woke); + self.frame.drain_due_wakes(due); + self.fire_hover_delays(); + self.fire_press_repeat(); + self.fire_edge_scroll(); + self.fire_autoscroll(); + self.fire_touch_hold(app); + // Marks are paint's (`paint::content`), and this frame paints: a pause that ends or words + // the checker brought back show without the view running again. + let (wake, _marked) = crate::spell::pause::tick(&mut self.edit.spell_watch, self.clock); + if let Some(at) = wake { self.schedule_wakes([std::time::Duration::from_secs_f64((at - self.clock).max(0.0))]); } + if !polled && app.has_poll() { + let mut one = self.transaction(app); + one.input_waiting = self.frame.queue.has_input(); + // Scheduling does not imply a model change. + if self.frame.record_poll(crate::tooling::perf_warn::timed("poll", || app.poll(self.clock, &mut one))) { + ran = true; + why |= CommitWhy::POLL; + self.commit.watch.meter.poll(); + } + merge(&mut tx, one); + } + if app.playground().is_some_and(|p| p.polls()) { + let mut one = self.transaction(app); + let clock = self.clock; + if self.poll_playground(app, clock, &mut one) { + ran = true; + why |= CommitWhy::POLL; + } + merge(&mut tx, one); + } + if self.commit.commits == 0 && self.frame.queue.iter().any(|a| matches!(a, Action::WindowFocus(_))) { + self.commit(app, &Tx::default()); + } + let mut ran_layout = false; + self.report_visible_rows(); + // Hosts take a drag-out inside the move that asked for it; by now nothing will. + self.drop_drag_out_request(); + let ended: Vec<_> = self.pointer.drag_ends.borrow_mut().drain(..).collect(); + let queue = order_drag_ends(std::mem::take(&mut self.frame.queue), ended, &mut self.pointer.drags_open); + let queue = self.hold_files(queue, ran || self.commit.dirty); + // A host settle (an uncover, a restore, a shown window) lands the tree the frame began + // with, before this frame's input runs. The input's own commit below then animates, so + // a dialog the first press closes still plays its exit. + if self.commit.is_settling() && queue.has_input_action() { + self.settle_before_input(app, &mut tx, &mut why); + ran = false; + } + // Something besides a checked live-only event wants this frame's commit, so a change + // it makes isn't the live-only handler's. + #[cfg(debug_assertions)] + let mut ran_other = ran; + let mut pointer_hover = false; + for Queued { action, at, input } in queue { + if matches!(action, Action::Key { stage: false, .. } | Action::Physical(crate::PhysicalInput::Key { pressed: true, .. }, _)) { crate::marks::input_handled(true); } + pointer_hover |= matches!(action, Action::Hover(_)); + // The user's own key or press takes over from a `Tx::focus_when_shown` still waiting. + if matches!(action, Action::Key { stage: false, .. } | Action::Physical(crate::PhysicalInput::Key { pressed: true, .. }, _) | Action::Press(..) | Action::Focus(..)) { + self.kbd.focus_owed = None; + } + // State may have requested focus on a newly mounted field. Resolve the + // new tree before routing this frame's text, not after it has gone to + // the previous field. The same boundary covers an earlier handler, and lets a + // file drag find only what is mounted and reachable now (a covered window builds + // nothing until this). + let routed = matches!(&action, Action::Key { .. } | Action::KeyUp(_) | Action::Physical(..) | Action::Ime(_) | Action::FinishIme | Action::Paste(..) | Action::Files(_)); + // So is a playground an earlier handler opened or moved. + if routed { self.latch_playground(app, &mut tx); } + // Both callbacks see ordinary &mut S. After the next mutation a single view + // cannot tell which one introduced a row. Observe the poll's tree now, without + // drawing it or advancing time. A key already needed this same routing boundary. + let split = self.motion.motion_needs_cause() && why & CommitWhy::POLL != 0 && (input || routed); + if split || (ran || self.commit.dirty || !tx.scroll_to.is_empty()) && routed { + if split { + let links = std::mem::take(&mut tx.open_urls); + self.latch_requests(app, &mut tx); + tx.open_urls = links; + } + if ran || self.commit.dirty { + self.motion.capture_flights(&self.tree.nodes, &mut self.paint, &mut self.text, self.env.scale, self.viewport, self.t, &mut tx); + if self.commit.is_settling() { tx.settle(); } + self.settled |= tx.commit.lands(); + #[cfg(debug_assertions)] + if ran_other || self.commit.dirty || ran_layout { self.frame.clear_live_check(); } + self.capture_keeps(&mut tx); + tx.unprompted = self.motion.motion_needs_cause() && why & CommitWhy::INPUT == 0 && !tx.asked_motion; + if split && tx.unprompted { tx.commit = tx.commit.without_input(); } + if routed { why |= CommitWhy::ROUTE; } + if self.commit.dirty { why |= CommitWhy::DIRTY; } + self.commit_for(app, &tx, std::mem::take(&mut why)); + #[cfg(debug_assertions)] + { let check = self.frame.take_live_check(); self.compare_live_check(check); ran_other = false; } + self.apply_keeps(app); + ran = false; + } + if split { + self.finish_scroll_requests(app, &mut tx, false); + // The poll's motion policy belongs to the tree just applied, not to + // the handler about to run. Shell requests and timers still go out once. + tx.commit = Commit::Animate; + tx.unprompted = false; + tx.asked_motion = false; + tx.live_growth.clear(); tx.tail_rooms.clear(); + tx.motion = None; + tx.color_motion = None; + tx.follow_edge = false; + tx.unclipped_flights = false; + ran_layout = false; + } else if !tx.scroll_to.is_empty() { + self.drop_scroll_holds(); + for r in tx.scroll_to.drain(..) { self.reveal_row(app, &r, tx.commit.snaps()); } + } + } + let _input = crate::input::time::scope(at); + // A selection an earlier handler asked for is what this key copies. + if matches!(action, Action::Key { .. } | Action::Physical(..)) && let Some(request) = tx.select.take() { + let from_change = std::mem::take(&mut tx.select_from_change); + self.apply_select_request(app, request, from_change); + } + if matches!(action, Action::Layout(..) | Action::ScreenLayout(..) | Action::DrawnLayout(_, _, false) | Action::VisibleRows(..)) { + ran_layout |= self.run_action(app, action, &mut tx); + } else { + #[cfg(debug_assertions)] + let checks = self.frame.live_checks(); + let r = self.run_action(app, action, &mut tx); + #[cfg(debug_assertions)] + { ran_other |= r && checks == self.frame.live_checks(); } + ran |= r; + if r { why |= if input { CommitWhy::INPUT } else { CommitWhy::DIRTY }; } + } + self.run_pick_reads(app, &mut tx); + } + // Once a frame, however often a drag moved the selection, and in time for this commit. + for action in self.selection_changes(app) { + #[cfg(debug_assertions)] + let checks = self.frame.live_checks(); + let r = self.run_action(app, action, &mut tx); + #[cfg(debug_assertions)] + { ran_other |= r && checks == self.frame.live_checks(); } + if r { ran = true; why |= CommitWhy::DIRTY; } + } + #[cfg(target_os = "linux")] + self.note_primary_selection(app); + let mut open_urls = std::mem::take(&mut tx.open_urls); + self.latch_requests(app, &mut tx); + // A handler asked for a menu: the hover it takes ends in this commit, not a frame later. + if self.release_pointer_for_popup() { + for queued in std::mem::take(&mut self.frame.queue) { + if !matches!(queued.action, Action::HoverChange(..)) { self.frame.queue.push_queued(queued); continue; } + #[cfg(debug_assertions)] + let checks = self.frame.live_checks(); + let r = self.run_action(app, queued.action, &mut tx); + #[cfg(debug_assertions)] + { ran_other |= r && checks == self.frame.live_checks(); } + if r { ran = true; why |= if queued.input { CommitWhy::INPUT } else { CommitWhy::DIRTY }; } + } + open_urls.extend(std::mem::take(&mut tx.open_urls)); + self.latch_requests(app, &mut tx); + } + self.release_files(); + self.schedule_wakes(tx.wakes.drain(..)); + self.motion.capture_flights(&self.tree.nodes, &mut self.paint, &mut self.text, self.env.scale, self.viewport, self.t, &mut tx); + if self.edit.caret_watch && self.caret_moved(None) { self.commit.dirty = true; } + let read_moved = self.layout_reads_moved(); + self.commit.set_read_moved(read_moved); + if self.tree.has_pixel_aspect && self.pixel_aspect_changed() { self.commit.relayout = true; } + let settling = self.commit.is_settling(); + let shifted = !(self.commit.dirty || self.commit.relayout || settling) && self.virtual_window_changed(); + let besides = self.commit.dirty || self.commit.relayout || settling || shifted; + let other = ran || besides; + self.count_layout_echo(ran_layout || read_moved, other); + if other || ran_layout || read_moved { + if self.commit.relayout && !ran && !self.commit.dirty { + if self.commit.is_viewport_stepped() { tx.window_step = true } else { tx.relayout = true } + } + if settling { + tx.commit = Commit::Settle; + } + self.settled = tx.commit.lands(); + self.commit.set_state_unchanged(!ran && !self.commit.dirty && !ran_layout && !settling && self.commit.commits > 0); + #[cfg(debug_assertions)] + if ran_other || besides || ran_layout || read_moved { self.frame.clear_live_check(); } + self.capture_keeps(&mut tx); + let flag = |on: bool, bit: u16| if on { bit } else { 0 }; + // Motion has a cause: the user, in this window. A commit nothing in this frame's + // input asked for shows what it brings in its final state (`Tx::unprompted`). + tx.unprompted = self.motion.motion_needs_cause() && why & CommitWhy::INPUT == 0 && !tx.asked_motion; + // Its layout lands too, as an instant change's does: a container that grows to fit what a + // server brought doesn't ease to its height (motion already running keeps on). + if tx.unprompted { tx.commit = tx.commit.without_input(); } + self.commit_for(app, &tx, why | flag(self.commit.dirty, CommitWhy::DIRTY) | flag(self.commit.relayout, CommitWhy::RELAYOUT) | flag(settling, CommitWhy::SETTLE) + | flag(shifted, CommitWhy::VIRTUAL) | flag(ran_layout, CommitWhy::LAYOUT) | flag(read_moved, CommitWhy::READ)); + #[cfg(debug_assertions)] + { let check = self.frame.take_live_check(); self.compare_live_check(check); } + self.apply_keeps(app); + } + #[cfg(debug_assertions)] + { self.frame.clear_live_check(); } + tx.keep_on_screen.clear(); + for (path, v) in &mut self.commit.virtuals { + if let Some(key) = v.reveal_selected.take() && !pointer_hover { + // Use the keyed ancestor path so identical row keys in other lists do not + // intercept the reveal, including when this row is still virtual. + let scope = path.split('/').filter(|seg| !seg.starts_with('#')).collect::<Vec<_>>().join("/"); + let key = if scope.is_empty() { key } else { format!("{scope}/{key}") }; + tx.scroll_to.push(ScrollReveal::into_view(None, key)); + } + } + #[cfg(debug_assertions)] + { + let scrolling = self.scrolling(); + self.commit.watch_frame(commits0, scrolling, tx.scroll_offsets.iter().find(|r| tx.commit.snaps() || r.glide.is_none()).map(|r| r.key.as_str())); + } + let follow = std::mem::take(&mut self.edit.caret_follow); + self.finish_scroll_requests(app, &mut tx, follow); + // Those scrolls moved the caret after the commit a view placed from it saw. + if self.edit.caret_watch && self.caret_moved(None) { self.commit(app, &Tx { commit: Commit::Instant, ..Tx::default() }); } + if let Some(request) = tx.select.take() { + let from_change = std::mem::take(&mut tx.select_from_change); + self.apply_select_request(app, request, from_change); + } + // What the commit or a `Tx::select_text` changed is heard next frame. + let changes = self.selection_changes(app); + self.frame.queue.extend(changes); + self.update_interaction(None); + #[cfg(test)] + if let Some(publish) = tests::MID_FRAME.with(|hook| hook.borrow_mut().take()) { publish(); } + // Poll and input can publish after the initial wake read without committing. Sample + // those values now, but retain the wake: a picture may still need next frame's layout. + let live_pending = live_woke || self.live_pending(); + let live_animating = self.latch_live(live_pending); + if let Some(trace) = tx.trace.take() { + for event in trace.events { self.trace_event(event); } + for (name, kind, value) in trace.channels { self.trace_channel(name, kind, value); } + } + let dt = if self.fit_frame_holds() { 0.0 } else { dt }; + let instant_scroll = tx.commit.snaps() || self.settled; + let animating = self.step_motion(app, dt, instant_scroll) || live_animating; + self.stats.shaped = self.text.shaped - shaped0; + let filling = self.virtual_filling(); + if live_animating { self.motion.add_anim_sources(AnimSource::LIVE); } + if self.time_scale <= 0.0 { self.motion.set_anim_sources(0); } + if filling { self.motion.add_anim_sources(AnimSource::VIRTUAL_FILL); } + self.animating = (animating && self.time_scale > 0.0) || filling; + #[cfg(debug_assertions)] + { + let clear = self.clear_color(); + let opaque = !self.surfaces.is_empty() || !self.paint.materials().is_empty() || self.paint.videos_active() || self.paint.animated_icons(); + let title = self.host.window_title.current(); + self.frame.idle_frame_ends(self.clock, self.animating, clear, self.viewport, self.env.scale, self.paint.srgb_blend(), self.transparent, self.images.copies, &self.instances, opaque, title); + } + self.interaction_built(); + if !open_urls.is_empty() { self.open_urls(open_urls); } + self.animating + } + + /// Lands a host settle for the tree as it stands before this frame's input, then lets the + /// input's own commit animate what it changes. `apply` clears the settle latch as this + /// commit applies it: the settle is spent here, so nothing is deferred or dropped. + fn settle_before_input(&mut self, app: &mut dyn AppDriver, tx: &mut Tx, why: &mut u16) { + let links = std::mem::take(&mut tx.open_urls); + self.latch_requests(app, tx); + tx.open_urls = links; + self.motion.capture_flights(&self.tree.nodes, &mut self.paint, &mut self.text, self.env.scale, self.viewport, self.t, tx); + tx.settle(); + self.settled |= tx.commit.lands(); + self.capture_keeps(tx); + // `settle_all` marks the tree dirty too, and this commit carries that change. + self.commit_for(app, tx, *why | CommitWhy::SETTLE | CommitWhy::DIRTY); + self.apply_keeps(app); + // Scroll requests queued before the input resolve under the settle, as the poll split's + // do, rather than gliding on the input's own animated commit. + self.finish_scroll_requests(app, tx, false); + // The input below starts from the settled tree, as it would on any other frame. + tx.commit = Commit::Animate; + tx.unprompted = false; + tx.asked_motion = false; + tx.live_growth.clear(); + tx.tail_rooms.clear(); + tx.motion = None; + tx.color_motion = None; + tx.follow_edge = false; + tx.unclipped_flights = false; + *why = 0; + } + + /// A picture sizing a side from its image changed shape (decoded, or a stream resized). + /// The next commit lays those pictures out at once, whatever else it animates. + pub(super) fn pixel_aspect_changed(&mut self) -> bool { + for n in &mut self.tree.nodes { + if let Some(cold) = n.cold.get_mut_if_some() + && let (Some(ratio), Some(pixels)) = (&mut cold.pixel_aspect, &n.vis.pixels) + { + let now = pixel_ratio(pixels); + if now != *ratio { self.tree.aspect_snap.push(n.id); } + *ratio = now; + } + } + !self.tree.aspect_snap.is_empty() + } +} diff --git a/app/vendor/rune/crates/rune/src/runtime/frame/latch.rs b/app/vendor/rune/crates/rune/src/runtime/frame/latch.rs new file mode 100644 index 0000000..0a11102 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/frame/latch.rs @@ -0,0 +1,150 @@ +//! Transactions, `update` lifecycle, `Tx` request latching and tracing hooks. +use super::*; + +impl RuntimeCore { + /// Starts an [`Runtime::update`] transaction with the clock reading now and begins its + /// stall timer right before the app callback runs. + pub(in crate::runtime) fn begin_update(&self, app: &dyn ViewDriver) -> (Tx, crate::tooling::perf_warn::Stall) { + // Its wakes count from now (`schedule_pending_wakes`), so its clock reads now too. + let one = Tx { clock: self.now_clock(), ..self.transaction(app) }; + (one, crate::tooling::perf_warn::Stall::start()) + } + + /// Finishes an [`Runtime::update`] / `update_if` / `update_if_ordered` call after its + /// closure ran against `app.state`. + pub(in crate::runtime) fn finish_update( + &mut self, + app: &mut dyn AppDriver, + stall: crate::tooling::perf_warn::Stall, + mut one: Tx, + changed: bool, + ordered: bool, + ) -> (bool, Option<std::num::NonZeroU64>) { + stall.end_named("an `update` closure"); + let stale = changed || one.frame_work() || one.window_frame.is_some() || one.srgb_blend.is_some_and(|b| b != self.paint.srgb_blend()) || one.font_smoothing.is_some_and(|m| m != self.text.font_smoothing()) + || self.changes_families(&one) + || (one.blur && self.kbd.focus.path().is_some()); + let minimize = if ordered { + let asked = one.minimize_order; + self.run_pick_reads(app, &mut one); + let survived = if asked.is_some() && one.minimize_order == asked { one.minimize_order.take() } else { None }; + self.latch_after_picks(app, &mut one); + survived + } else { + self.latch_requests(app, &mut one); + None + }; + merge(&mut self.frame.pending, one); + self.commit.dirty |= changed; + (stale, minimize) + } + + /// Takes a `Tx::minimize` that `what` can't carry out, saying so in debug builds. + pub(crate) fn ignore_minimize(&mut self, what: &str) { + let field = self.host.minimize.field(); + self.minimize_step(crate::window::MinimizeEvent::Lost); + if field && cfg!(debug_assertions) { + eprintln!("rune: minimize ignored: {what} can't minimize"); + } + } + + /// Latches a Tx's shell and clipboard requests for the shell, so `update`, a hidden poll + /// and `on_close` reach the clipboard without a frame, and applies clipboard requests to a + /// memory clipboard at once. A secret clear drops an earlier secret copy not yet written. + pub(in crate::runtime) fn latch_requests(&mut self, app: &mut dyn AppDriver, tx: &mut Tx) { + self.run_pick_reads(app, tx); + self.latch_after_picks(app, tx); + } + + /// [`Self::latch_requests`] once the pick callbacks have run. + fn latch_after_picks(&mut self, app: &mut dyn AppDriver, tx: &mut Tx) { + self.shell_request = self.shell_request.max(tx.shell.take()); + if tx.minimize_order.take().is_some() { self.minimize_step(crate::window::MinimizeEvent::Asked); } + self.host.titlebar.toggle_maximized |= std::mem::take(&mut tx.toggle_maximized); + self.host.titlebar.toggle_full_screen |= std::mem::take(&mut tx.toggle_full_screen); + for ev in std::mem::take(&mut tx.keys) { self.key(ev); } + self.latch_playground(app, tx); + for prefix in std::mem::take(&mut tx.evict_memos) { self.invalidate_memos_by_prefix(&prefix); } + if !tx.open_urls.is_empty() { self.open_urls(std::mem::take(&mut tx.open_urls)); } + if std::mem::take(&mut tx.clear_secret) { + if self.copy_request.as_ref().is_some_and(crate::ClipboardWrite::is_secret) { self.copy_request = None; } + self.edit.clear_secret_request = true; + self.edit.pill_copy = None; + } + if let Some(copy) = tx.copy.take() { + self.edit.pill_copy = (!copy.is_secret()) + .then(|| copy.content().html()) + .flatten() + .filter(|h| h.contains("<span data-pill=")) + .map(|h| { + let frag = crate::TextEdit::from_html(h); + ( + zeroize::Zeroizing::new(copy.content().text().to_owned()), + frag.pills().map(|(r, id)| (r, id.to_owned())).collect::<Vec<_>>(), + ) + }) + .filter(|(_, pills)| !pills.is_empty()); + self.copy_request = Some(copy); + } + if std::mem::take(&mut tx.paste) { self.edit.paste_request = Some(self.paste_target()); } + for read in tx.clipboard_reads.drain(..).filter_map(|read| read.take()) { + self.edit.next_clipboard_read += 1; + self.edit.clipboard_reads.push((self.edit.next_clipboard_read, read)); + self.edit.read_requests.push(self.edit.next_clipboard_read); + } + self.host.popups.extend(tx.popups.drain(..).filter_map(|call| call.take())); + for request in tx.file_dialogs.drain(..).filter_map(|call| call.take()) { + self.request_file_dialog(request); + } + if let Some(mode) = tx.font_smoothing.take() { self.set_font_smoothing(mode); } + if let Some((sans, mono)) = tx.font_families.take() { self.set_font_families(&sans, &mono); } + if let Some(srgb) = tx.srgb_blend.take() { self.set_srgb_blend(srgb); } + if let Some(rewind) = tx.rewind.take() { self.motion.set_rewind(rewind); } + if std::mem::take(&mut tx.blur) { + if self.kbd.focus.path().is_some() { + self.set_focus(app, None, self.kbd.focus.keyboard()); + self.commit.dirty = true; + } + // An explicit blur is not the temporary pointer-down blur of a scrim, and nothing + // hands focus on from it: only a control the user blurred and then left does. + self.kbd.focus.step(focus_machine::FocusEvent::Dropped); + self.kbd.focus.step(focus_machine::FocusEvent::Settled); + } + if let Some(request) = tx.focus_to.take() { + self.kbd.focus_request = Some(request); + self.commit.dirty = true; + } + if let Some(title) = tx.title.take() { self.host.window_title.set(title); } + if let Some((text, how)) = tx.announce.take() { self.host.announcement.say(text, how); } + if let Some(mut request) = tx.window_frame.take() { + request.spring = (request.animate && !tx.commit.snaps() && !self.reduced_motion).then(|| tx.motion.map_or(crate::tok::motion::DEFAULT, MotionSource::spring)); + self.host.window_frame = Some(self.host.window_frame.unwrap_or_default().merge(request)); + } + crate::clipboard::flush_memory(self); + } + + pub fn tracing(&self) -> bool { self.frame.tracing_channels() || self.scene.tracing() } + + pub(in crate::runtime) fn transaction(&self, app: &dyn ViewDriver) -> Tx { + Tx { trace: self.tracing().then(crate::el::TraceCalls::default), mods: self.kbd.held_mods, selection: self.selection_snapshot(app), + input_time: crate::input::time::current(), clock: self.clock, focus_visible: self.kbd.focus.keyboard(), focused: self.focused_key(), assistive: self.host.a11y.is_some() || cfg!(target_arch = "wasm32"), ..Tx::default() } + } + + /// A scalar from the actual draw path (e.g. `shell.width`). Values hold until resampled. + /// Call before the tooling writer records the frame; scene traces sample in `frame`. + pub fn trace_channel(&mut self, name: &'static str, kind: &'static str, value: f32) { + self.frame.record_trace_channel(name, kind, value); + if let Some(trace) = self.scene.trace_mut() { trace.channel(name, kind, value); } + } + + /// Queues an app marker once for each attached writer. Formatting is skipped when off. + #[inline] + pub fn trace_event(&mut self, event: impl std::fmt::Display) { + self.trace_event_dyn(&event); + } + + pub(crate) fn trace_event_dyn(&mut self, event: &dyn std::fmt::Display) { + if self.frame.tracing_channels() { event_log::push(&mut self.events, event.to_string()); } + if let Some(trace) = self.scene.trace_mut() { trace.event(event); } + } +} diff --git a/app/vendor/rune/crates/rune/src/runtime/frame/motion.rs b/app/vendor/rune/crates/rune/src/runtime/frame/motion.rs new file mode 100644 index 0000000..860463a --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/frame/motion.rs @@ -0,0 +1,162 @@ +//! Per-frame motion stepping, delayed-motion wakes, loop visibility and layer paint order. +use super::*; + +impl RuntimeCore { + /// frame-profile: the paths of drawn nodes whose loop is running, which wake the window. + #[cfg(feature = "frame-profile")] + pub(crate) fn fp_loops(&self) -> Vec<String> { + self.tree.nodes.iter().enumerate() + .filter(|(i, n)| n.looping.is_some() && self.paint.was_seen(*i, false) && self.motion.has_loop(n.id)) + .map(|(_, n)| n.path.clone()).collect() + } + + /// Whether a drawn node's loop runs (a spinner or animated SVG icon): what a window shows + /// would fall behind it while the window draws nothing. + #[cfg_attr(not(target_os = "windows"), allow(dead_code))] + pub(crate) fn loops_shown(&self) -> bool { + (!self.reduced_motion && self.paint.animated_icons_shown()) + || self.tree.nodes.iter().enumerate().any(|(i, n)| n.looping.is_some() && self.paint.was_seen(i, false) && self.motion.has_loop(n.id)) + } + + /// Wakes when a delayed start at animation time `at` comes due, on the loops' wake: the + /// frame then runs at exactly that time, however long the host slept. A hidden window + /// sleeps through it; showing it settles. + fn wake_for_motion(&mut self, at: f64) { + self.paint.note_cycle_other_deadline(); + if !self.frame.live.visible() || self.time_scale <= 0.0 { return; } + let wake = self.clock + (at - self.t).max(0.0) / self.time_scale as f64; + self.motion.arm_loop_wake(wake, at); + } + + /// Wakes for a paced animated SVG icon without marking `cycles.mixed`, so icon-only wakes take + /// the zero-paint-walk `loop_step` / `arm_loop` fast path. + fn wake_for_icon_anim(&mut self, at: f64) { + if !self.frame.live.visible() || self.time_scale <= 0.0 { return; } + let wake = self.clock + (at - self.t).max(0.0) / self.time_scale as f64; + self.motion.arm_loop_wake(wake, at); + } + + /// Wakes for one frame at clock time `due` and draws nothing before it, as a delayed start + /// does: an instant scroll's hover hold asks for the frame it lets go on this way, so a + /// resting window draws no frame while the hold waits. + pub(in crate::runtime) fn wake_for_clock(&mut self, due: f64) { + let at = self.t + (due - self.clock).max(0.0) * self.time_scale as f64; + self.wake_for_motion(at); + } + + pub(in crate::runtime) fn catch_up_motion(&mut self, dt: f64) { + let step = dt * self.time_scale as f64; + self.t += step; + self.scene.set_time(self.t); + self.motion.add_caught_up(step as f32); + self.step_growth(step as f32); + self.step_scroll_by(step as f32, true); + } + + pub(in crate::runtime) fn step_motion(&mut self, app: &dyn ViewDriver, dt: f64, instant_scroll: bool) -> bool { + self.motion.loops_stepped(); + let step = dt * self.time_scale as f64; + self.motion.begin_slack_step(step as f32); + self.frame.set_last_dt(step); + self.t += step; + self.scene.set_time(self.t); + if self.scene.tracing() { + for node in &self.tree.nodes { + self.scene.trace_name(node.id, node.trace_name); + self.scene.trace_namespace(node.id, node.trace_namespace); + } + } + self.motion.step_loops_into_scene(&self.tree.nodes, &self.tree.node_index, &mut self.scene, self.reduced_motion); + self.end_unseen_exits(); + let out = self.scene.frame(); + let (mut animating, exited) = (out.animating, !out.exited.is_empty()); + self.paint.begin_frame(); + // Tracks that only wait for a delayed start (`El::enter_delay`, a delayed `Anim`) + // draw nothing new until it: sleep, and wake for it after the build. + let mut waits = if animating { self.scene.store().waiting_until() } else { None }; + if waits.is_some() { animating = false; } + let mut sources = if animating { AnimSource::TRACKS } else { 0 }; + if exited { + self.prune_exited(); + } + land_group_fades(&mut self.scene, &mut self.tree.nodes, &self.tree.node_index); + if self.motion.prune_landed_flights(&self.scene) { + self.update_layer_paint_order(); + } + let mut source = |on: bool, bit: u16| { if on { sources |= bit; } on }; + animating |= source(self.step_growth(step as f32), AnimSource::GROWTH); + animating |= source(self.step_scroll(step as f32), AnimSource::SCROLL); + // A hold draws nothing while it waits: its wake asks for the one frame that ends it. + let hold_wake = self.step_nudges(); + for stack in self.motion.stacks.values_mut() { stack.grown = 0.0; } + animating |= source(self.motion.reveals_active(&self.scene), AnimSource::REVEAL); + // Values set from `on_scroll_offset` show in the frame that scrolled. + if self.tell_scroll_offsets(instant_scroll) { + let took = self.take_live_wake(); + let live = self.latch_live(took); + if live { sources |= AnimSource::LIVE; } + let running = self.scene.store().running(); + waits = running.then(|| self.scene.store().waiting_until()).flatten(); + if running && waits.is_none() { sources |= AnimSource::TRACKS; } else { sources &= !AnimSource::TRACKS; } + animating = sources != 0; + self.scene.present(); + } + self.paint.record_moved(self.scene.changed().iter().map(|p| p.node)); + if self.fill_text() { animating = true; sources |= AnimSource::TEXT_FILL; } + let mut source = |on: bool, bit: u16| { if on { sources |= bit; } on }; + self.begin_exit_mask(); + animating |= self.build(); + // Compensate drawn motion, leaving unrelated layout and growth springs alone. + for _ in 0..3 { + if !self.follow_keeps() { break; } + animating |= self.build(); + } + self.finish_keeps(); + animating |= self.write_drawn_rects(); + // A selection's edge scroll stepped: it follows the pointer over this layout, and shows. + if self.laid_edge_scroll(app) { animating |= self.build(); } + self.report_at_bottom(); + animating |= self.report_visible_rows(); + self.report_layout(); + // A report waits for the next frame: draw one to deliver it. + animating |= self.report_drawn() | self.report_visible(); + self.end_exit_mask(); + self.motion.record_rewind(self.clock, self.viewport, &self.tree.nodes, &self.paint); + animating |= source(self.motion.loops_active(), AnimSource::LOOP); + animating |= source(self.paint.scale_settling(), AnimSource::SCALE_SETTLE); + animating |= source(self.paint.videos_active(), AnimSource::VIDEO); + animating |= source(self.paint.animated_icons(), AnimSource::ICON_ANIM); + let flights_active = self.paint.draw_text_flights( + self.motion.flights_mut(), &self.tree.nodes, &self.scene, &mut self.text, &mut self.images, + &mut self.instances, self.env.scale, self.t, self.reduced_motion, self.viewport, + ); + animating |= source(flights_active, AnimSource::TEXT_FLIGHT); + animating |= source(self.text_fill_due(), AnimSource::TEXT_FILL); + if !animating && raster_check::on() { + self.check_resting_raster(); + } + if let Some(at) = waits { self.wake_for_motion(at); } + if let Some(at) = self.paint.icon_anim_wake() { self.wake_for_icon_anim(at); } + // An instant scroll's hold draws nothing until it ends: wake for the one frame that + // resolves hover then, taken from the state each frame so a re-arm moves it on. + if let Some(due) = hold_wake { self.wake_for_clock(due); } + self.images.end_frame(); + if self.track_marks { + self.marks.resize(self.instances.len(), 0); + } + self.motion.set_anim_sources(sources); + animating + } + + /// Subtree (preorder) paint order, then each flying element's subtree on top. A sticky + /// element paints after its normal siblings (and before overlay siblings), so it covers the + /// rows it's stuck over. + #[inline] + pub(in crate::runtime) fn update_layer_paint_order(&mut self) { + let Self { paint, tree, motion, scroll, .. } = self; + paint.update_layer_paint_order(tree, &motion.flying, |i| { + (scroll.requests.has_keeps() && scroll.requests.keeps().any(|k| k.hold.as_ref().is_some_and(|h| h.path == tree.nodes[i].path))) + || tree.nodes[i].sticky.as_ref().and_then(|s| s.edge).is_some() + }); + } +} diff --git a/app/vendor/rune/crates/rune/src/runtime/frame/wakes.rs b/app/vendor/rune/crates/rune/src/runtime/frame/wakes.rs new file mode 100644 index 0000000..0e1f7d5 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/frame/wakes.rs @@ -0,0 +1,177 @@ +//! Clocks, timer wake deadlines, viewport updates and native window focus transitions. +use super::*; + +impl RuntimeCore { + /// Clock seconds now: the wall clock in a window (input arrives between frames), the + /// virtual clock headless. + pub(in crate::runtime) fn now_clock(&self) -> f64 { + self.wall_start.map_or(self.clock, |t| t.elapsed().as_secs_f64()) + } + + /// The window's size in its points and its scale. The view lays out in them over its zoom + /// ([`Cx::zoom`]), at the scale times the zoom. + pub fn set_viewport(&mut self, viewport: (f32, f32), scale: f32) { + (self.host.zoom.window, self.host.zoom.window_scale) = (viewport, scale); + let (viewport, scale) = self.host.zoom.view(); + if self.fit_resized(viewport.1) { + self.commit.relayout = true; + self.commit.set_viewport_stepped(false); + } + if self.change_viewport(viewport, scale) { self.commit.set_viewport_stepped(false); } + } + + /// The viewport one frame of the window's own resize animation moved it to. Unlike a + /// user's resize it doesn't land running motion: content at rest follows the window and + /// springs keep going. + pub(crate) fn step_viewport(&mut self, viewport: (f32, f32), scale: f32) { + (self.host.zoom.window, self.host.zoom.window_scale) = (viewport, scale); + let (viewport, scale) = self.host.zoom.view(); + let fresh = !self.commit.relayout; + if self.change_viewport(viewport, scale) && fresh { self.commit.set_viewport_stepped(true); } + } + + /// Whether the change needs a layout. + pub(in crate::runtime) fn change_viewport(&mut self, viewport: (f32, f32), scale: f32) -> bool { + // A window that fits its content lays out the same at any height: its own resize + // mustn't cut short the layout springs it is following. + if self.host.fit_height && viewport.0 == self.viewport.0 && scale == self.env.scale { + self.viewport = viewport; + return false; + } + let changed = viewport != self.viewport || scale != self.env.scale; + if changed { + if scale != self.env.scale { self.motion.clear_flights(); } + self.viewport = viewport; + self.env.scale = scale; + self.scene.set_pixel_scale(scale); + self.commit.relayout = true; + } + changed + } + + /// Queue a native focus transition. Repeated notifications do not repeat the callback. + /// Losing focus is also `keys_lost`. + pub(crate) fn window_focus(&mut self, app: &mut dyn AppDriver, focused: bool) { + // Every focus gain, even one a hide without blur left unreported. + if focused { self.kbd.keys_lost = false; } + if self.host.window_focused != Some(focused) { + // Refocused, the pointer where it was hovers again; blurred, it waits for a move. + if focused && self.host.window_focused == Some(false) { self.pointer.hover_paused = false; } + // A selection takes its active or inactive pair (`El::selection_style`): a focused + // field's, or a selectable text's. + if self.host.window_focused.is_some() + && (self.focused_input().is_some_and(|i| i.selection_style.is_some()) || self.text_selection().is_some_and(|(_, r)| !r.is_empty())) + { + self.commit.dirty = true; + } + // Back to the front: a field's keyboard-entry ring stays off until the keys move focus. + if focused && self.host.window_focused == Some(false) && self.kbd.focus.entered_by_keys() { + self.kbd.focus.step(crate::runtime::input::focus_machine::FocusEvent::WindowReturned); + self.commit.dirty = true; + } + self.host.window_focused = Some(focused); + if app.has_on_focus() { + let (mut one, stall) = self.begin_update(app); + app.on_focus(focused, &mut one); + self.finish_update(app, stall, one, true, false); + } + // Deliver the cancelled Up before FocusLost can commit a view that removes its + // grip (or the focus callback clears the app's drag state). + if !focused { + self.cancel_pointer(); + self.kbd.held = physical_dispatch::Activation::Up; + } + if self.commit.commits == 0 || self.commit.dirty || self.tree.nodes.get(self.app_root()).is_some_and(|n| n.handlers.on_window_focus.is_some()) { + self.frame.queue.push(Action::WindowFocus(focused)); + } + if !focused { + self.finish_composition(); + self.keys_lost(); + // Losing the window ends hover, rather than waiting out an exit grace. A window + // that isn't key still hears the pointer, so its next move starts the wait again. + self.end_hover_delays(); + self.pointer.hover_paused = true; + } + } + if !focused { self.edit.input_click.clear(); self.wheel_lost(); } + } + + /// The window gets no more keys: it lost focus or hid, which may never report a blur. The + /// focused physical handler hears `FocusLost` and held modifier keys are released, once + /// until the window has focus again. A hidden host steps `hidden_timer_frame` while + /// `keys_queued` to deliver them. + pub(crate) fn keys_lost(&mut self) { + if std::mem::replace(&mut self.kbd.keys_lost, true) { return; } + self.physical_input(crate::PhysicalInput::FocusLost); + } + + /// Keyboard input, a focus change, a file drag step or a file dialog answer is queued for the + /// next frame. + pub(crate) fn keys_queued(&self) -> bool { + self.frame.queue.iter().any(|a| matches!(a, Action::Physical(..) | Action::Key { .. } | Action::KeyUp(_) | Action::WindowFocus(_) | Action::Files(_) | Action::FileDialog(..))) + } + + /// Host time on the logical clock. + pub(in crate::runtime) fn wall_clock(&self) -> Option<f64> { + #[cfg(test)] + if let Some(now) = self.frame.test_clock_now() { return Some(now); } + self.wall_start.map(|t0| t0.elapsed().as_secs_f64()) + } + + /// Schedules the `wake_after`s that updates left for a frame, counting from now, when no + /// frame or hidden poll comes to. The clock stays at the last poll, so the frame-interval + /// floor on timers (`window::timer_deadline`) still counts from that poll. + pub(crate) fn schedule_pending_wakes(&mut self) { + let wakes = std::mem::take(&mut self.frame.pending.wakes); + self.schedule_wakes_from(self.now_clock(), wakes); + } + + /// Sorted, de-duplicated deadlines on the logical clock. + pub(in crate::runtime) fn schedule_wakes(&mut self, wakes: impl IntoIterator<Item = std::time::Duration>) { + self.schedule_wakes_from(self.clock, wakes); + } + + /// Wakes for a frame once the clock reaches `due`, as [`Tx::wake_at`] asks from a handler (a + /// deadline already past wakes the next frame), for the runtime's own timers. + #[cfg_attr(feature = "frame-profile", track_caller)] + pub(in crate::runtime) fn wake_at(&mut self, due: f64) { + #[cfg(feature = "frame-profile")] + crate::frame::live_log::waker(std::panic::Location::caller(), std::time::Duration::from_secs_f64((due - self.clock).max(0.0))); + self.schedule_wakes_from(due, [std::time::Duration::ZERO]); + } + + #[inline] + pub(in crate::runtime) fn schedule_wakes_from(&mut self, now: f64, wakes: impl IntoIterator<Item = std::time::Duration>) { + self.frame.schedule_wakes_from(now, wakes); + } + + /// Next requested wake on the unscaled app clock. None lets the shell sleep indefinitely. + pub fn wake_deadline(&self) -> Option<f64> { + self.logical_wake_deadline() + } + + /// The native window or overlay's frame counts; `None` headless. + pub fn surface_stats(&self) -> Option<crate::SurfaceStats> { + self.host.surface_stats.as_deref().map(crate::frame::surface_stats::read) + } + + /// When `poll` last ran, on `wake_deadline`'s clock. + pub(crate) fn polled_at(&self) -> f64 { + self.frame.polled_at(self.clock) + } + + pub(in crate::runtime) fn logical_wake_deadline(&self) -> Option<f64> { + self.frame.next_wake_deadline().into_iter().chain(self.motion.loop_wake().map(|w| w.0)).min_by(f64::total_cmp) + } + + /// The next due timer of `poll`'s, on `wake_deadline`'s clock. + pub(crate) fn poll_wake_deadline(&self) -> Option<f64> { + self.frame.next_wake_deadline() + } + + /// The next frame motion asks for at its own cadence (a loop's next step, a video's next + /// picture), on `wake_deadline`'s clock. + pub(crate) fn motion_wake_deadline(&self) -> Option<f64> { + self.motion.loop_wake().map(|w| w.0) + } +} diff --git a/app/vendor/rune/crates/rune/src/runtime/grid_tests.rs b/app/vendor/rune/crates/rune/src/runtime/grid_tests.rs new file mode 100644 index 0000000..e5ed6f3 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/grid_tests.rs @@ -0,0 +1,56 @@ +use std::rc::Rc; + +use crate::{Color, Cx, El, Env, GridRow, Runtime, Span, TextStyle, col, grid}; + +struct Screen { + rows: Vec<Rc<GridRow>>, +} + +fn view(s: &Screen, _: &mut Cx<Screen>) -> El { + col().w_full().h_full().child(grid(24, 8.0, 18.0, s.rows.clone()).w(192.0).h(18.0 * s.rows.len() as f32)) +} + +fn row(text: &str, k: usize) -> Rc<GridRow> { + let style = TextStyle::new(14.0, 400.0).lh(18.0); + let red = Color { r: 0.8, g: 0.1, b: 0.1, a: 1.0 }; + Rc::new( + GridRow::new(text, vec![Span::new(0, text.len().min(4)).color(red)], style) + .fill(0, 3 + k as u16, Color { r: 0.1, g: 0.2, b: 0.3, a: 1.0 }) + .cell(20, 2, "日", style, Color::WHITE), + ) +} + +fn instances(rt: &Runtime<Screen>) -> Vec<String> { + rt.instances.iter().map(|i| format!("{:?}", (i.rect, i.fill, i.params, i.uv, i.clip))).collect() +} + +/// Where and how each instance draws, not where its mask sits in the atlas: two runtimes fill +/// their atlases in different orders. +fn placed(rt: &Runtime<Screen>) -> Vec<String> { + rt.instances.iter().map(|i| format!("{:?}", (i.rect, i.fill, i.params[1], i.clip))).collect() +} + +#[test] +fn an_unchanged_screen_draws_what_it_drew() { + let rows: Vec<_> = (0..6).map(|k| row(&format!("line {k} of output"), k)).collect(); + let mut rt = Runtime::new(Screen { rows }, view, (240.0, 140.0), Env::new(true, 1.5)); + rt.frame(0.0); + let first = instances(&rt); + assert!(first.len() > 6 * 4, "fills, glyphs and the wide cell of each row"); + rt.invalidate(); + rt.frame(1.0 / 60.0); + assert_eq!(instances(&rt), first, "rows drawn again from what they drew"); +} + +#[test] +fn one_changed_row_draws_as_a_fresh_screen_would() { + let rows: Vec<_> = (0..6).map(|k| row(&format!("line {k} of output"), k)).collect(); + let mut rt = Runtime::new(Screen { rows }, view, (240.0, 140.0), Env::new(true, 1.5)); + rt.frame(0.0); + rt.update(|s, _| s.rows[2] = row("a new third line", 9)); + rt.frame(1.0 / 60.0); + let fresh_rows: Vec<_> = (0..6).map(|k| if k == 2 { row("a new third line", 9) } else { row(&format!("line {k} of output"), k) }).collect(); + let mut fresh = Runtime::new(Screen { rows: fresh_rows }, view, (240.0, 140.0), Env::new(true, 1.5)); + fresh.frame(0.0); + assert_eq!(placed(&rt), placed(&fresh)); +} diff --git a/app/vendor/rune/crates/rune/src/runtime/hot_state.rs b/app/vendor/rune/crates/rune/src/runtime/hot_state.rs new file mode 100644 index 0000000..1a5a705 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/hot_state.rs @@ -0,0 +1,23 @@ +//! What a live-edit reload reports about a running window: its scroll offsets and moving frames. +use super::*; + +impl types::TreeState { + pub(super) fn hot_scrolls(&self, scrolls: &HashMap<NodeId, ScrollState>) -> Vec<(String, f64)> { + self.nodes.iter().filter_map(|n| scrolls.get(&n.id).map(|s| (n.path.clone(), s.offset))).collect() + } + + pub(crate) fn hot_motion(&self, scene: &Scene) -> Vec<(String, [f32; 4], [f32; 4])> { + let store = scene.store(); + self.nodes.iter().filter_map(|n| { + if !store.is_animating(n.id, prop::FRAME) { return None; } + Some((n.path.clone(), store.sample(n.id, prop::FRAME)?.edges(), store.sample_velocity(n.id, prop::FRAME)?.edges())) + }).collect() + } +} + +impl RuntimeCore { + #[inline] + pub(crate) fn hot_scrolls(&self) -> Vec<(String, f64)> { + self.tree.hot_scrolls(&self.scroll.scrolls) + } +} diff --git a/app/vendor/rune/crates/rune/src/runtime/hover_tests.rs b/app/vendor/rune/crates/rune/src/runtime/hover_tests.rs new file mode 100644 index 0000000..46e8288 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/hover_tests.rs @@ -0,0 +1,162 @@ +use super::*; +use crate::{col, el}; + +struct State { custom: bool, growth: bool, rows: usize } + +fn view(s: &State, _: &mut Cx<State>) -> El { + let rows = (0..s.rows).map(|i| { + let row = el().key(format!("row-{i}")).w_full().h(30.0) + .hover(Color::WHITE).on_press(|_: &mut State| {}); + let group = col().key(format!("group-{i}")).w_full().hover_group() + .child(row) + .child(el().key("action").size(10.0, 10.0).fill(Color::WHITE).group_opacity(0.0, 1.0)); + if s.custom { + // Explicit animations take the original, unconditional update path. + group.hover_motion_within(Anim::INSTANT, rune_motion::Curve::tween(0.1, rune_motion::Easing::EASE_OUT)) + } else { group } + }); + let stack = col().key("rows").w_full().children(rows); + let stack = if s.growth { stack.growth(GrowthSpec::default()) } else { stack }; + col().w_full().h_full().child( + col().key("scroll").w_full().h_full().scroll(ScrollSpec { stick_bottom: false }) + .child(stack), + ) +} + +#[test] +fn default_hover_matches_explicit_trajectories_through_scroll_and_reversal() { + for (reduced, growth) in [(false, false), (true, false), (false, true), (true, true)] { + let make = |custom| Runtime::new(State { custom, growth, rows: 30 }, view, (240.0, 150.0), Env::new(true, 2.0)); + let mut fast = make(false); + let mut reference = make(true); + for rt in [&mut fast, &mut reference] { + rt.set_system_reduced_motion(reduced); + rt.frame(0.0); + } + for frame in 0..120 { + for rt in [&mut fast, &mut reference] { + if growth && frame % 12 == 0 { rt.update(|s, _| s.rows += 1); } + if frame == 0 { rt.pointer_move(60.0, 65.0); } + if frame < 60 { rt.wheel(60.0, 65.0, if frame < 30 { -7.0 } else { 7.0 }); } + if frame == 15 { rt.pointer_down(60.0, 65.0); } + if frame == 18 { rt.pointer_up(60.0, 65.0); } + if frame == 65 { rt.pointer_leave(); } + if frame == 67 { rt.pointer_move(60.0, 65.0); } + if frame == 90 { rt.pointer_leave(); } + rt.frame(1.0 / 120.0); + } + assert_eq!(bytemuck::cast_slice::<_, u8>(&fast.instances), bytemuck::cast_slice::<_, u8>(&reference.instances), + "same painted hover at frame {frame}, reduced={reduced}, growth={growth}"); + } + } +} + +#[test] +fn unchanged_default_hover_does_not_dirty_scene_poses() { + for custom in [false, true] { + let mut rt = Runtime::new(State { custom, growth: false, rows: 30 }, view, (240.0, 150.0), Env::new(true, 1.0)); + rt.frame(0.0); + // Drain any requests made by the initial paint's interaction update. + rt.scene.frame(); + rt.update_interaction(Some(false)); + assert_eq!(!rt.scene.frame().changed.is_empty(), custom, + "only explicit animations may dirty poses for unchanged targets"); + } +} + +#[test] +fn inherited_hover_curves_leave_descendants_visuals_shared() { + let mut rt = Runtime::new(State { custom: true, growth: false, rows: 3 }, view, (240.0, 150.0), Env::new(true, 1.0)); + rt.frame(0.0); + rt.update(|s, _| s.rows += 1); + rt.frame(1.0 / 120.0); + let rows: Vec<_> = rt.tree.nodes.iter().filter(|n| n.path.rsplit('/').next().is_some_and(|k| k.starts_with("row-"))).collect(); + assert_eq!(rows.len(), 4); + for n in rows { + assert!(n.hover_motion().is_some(), "{} goes by its group's curves", n.path); + assert!(n.vis.cold.is_empty(), "{} keeps no cold visuals of its own", n.path); + } +} + +/// A face in a hoverable row: on the face only the face shows +/// hover, and the row's wash and its group styles rest; back on the row they light again. +/// The pointer moving between them only paints. +#[test] +fn a_hover_alone_child_keeps_the_row_around_it_unlit() { + struct S; + fn view(_: &S, _: &mut Cx<S>) -> El { + let face = el().key("face").size(20.0, 20.0).hover(Color::WHITE).hover_alone(); + let row = crate::row().key("row").size(200.0, 30.0).hover(Color::WHITE) + .child(el().key("label").size(100.0, 30.0)) + .child(el().key("dot").size(4.0, 4.0).fill(Color::WHITE).group_opacity(0.0, 1.0)) + .child(face); + col().w_full().h_full().child(row) + } + let mut rt = Runtime::new(S, view, (240.0, 100.0), Env::new(true, 1.0)); + rt.frame(0.0); + let id = |rt: &Runtime<S>, key: &str| rt.tree.nodes.iter().find(|n| n.path.rsplit('/').next() == Some(key)).map(|n| n.id).unwrap(); + let lit = |rt: &Runtime<S>, key: &str| rt.scene.store().target(id(rt, key), P_HOVER).unwrap_or(0.0); + let commits = rt.stats.commits; + + rt.pointer_move(50.0, 15.0); + rt.frame(1.0 / 120.0); + assert_eq!((lit(&rt, "row"), lit(&rt, "face")), (1.0, 0.0), "on the label the row lights"); + + rt.pointer_move(114.0, 10.0); + rt.frame(1.0 / 120.0); + assert_eq!((lit(&rt, "row"), lit(&rt, "face")), (0.0, 1.0), "on the face only the face lights"); + + rt.pointer_move(50.0, 15.0); + rt.frame(1.0 / 120.0); + assert_eq!((lit(&rt, "row"), lit(&rt, "face")), (1.0, 0.0), "back on the label the row lights again"); + assert_eq!(rt.stats.commits, commits, "hover between them never commits"); +} + +#[test] +fn a_released_hold_holds_nothing_until_layout_settles() { + let mut h = HoverHold::default(); + h.set_held(true); + assert!(h.held()); + h.release(true); + assert!(h.released() && !h.held(), "the hand let go of the hold while layout moves"); + h.set_held(true); + assert!(h.released() && !h.held(), "released, a pass can't hold hover"); + h.release(true); + assert!(h.released(), "a second move keeps it released"); + h.settled(); + h.set_held(true); + assert!(h.held() && !h.released()); + h.release(false); + assert!(!h.held() && !h.released(), "with layout still, a move just ends the hold"); +} + +#[test] +fn children_of_an_exiting_parent_stop_hovering_and_pressing() { + fn view(show: &bool, _: &mut Cx<bool>) -> El { + let mut root = col().key("root").size(200.0, 100.0); + if *show { + root = root.child( + col().key("panel").size(120.0, 60.0).transition(crate::Transition::opacity()) + .child(el().key("btn").size(80.0, 40.0).hover(Color::WHITE).hover_alone() + .hover_group_shared("shared-exit").on_press(|_: &mut bool| {})), + ); + } + root + } + let mut rt = Runtime::new(true, view, (200.0, 100.0), Env::new(true, 1.0)); + rt.frame(0.0); + rt.update(|show, _| *show = false); + rt.frame(1.0 / 60.0); + + // Move pointer onto the child of the exiting panel while the panel is mid-exit. + let btn_idx = rt.tree.nodes.iter().position(|n| n.key.as_deref() == Some("btn")).expect("child still in exiting subtree"); + assert!(rt.core().subtree_exiting(btn_idx) && !rt.core().is_exiting(rt.tree.nodes[btn_idx].id), "only parent holds Exiting phase"); + rt.pointer_move(20.0, 20.0); + rt.frame(1.0 / 60.0); + + let btn_id = rt.tree.nodes[btn_idx].id; + let target = rt.scene.store().target(btn_id, P_HOVER).unwrap_or(0.0); + assert_eq!(target, 0.0, "child of exiting parent must not light hover"); + assert!(rt.core().hovered_alone().is_none(), "child of exiting parent must not claim hover_alone"); + assert!(rt.core().shared_hovered().is_empty(), "child of exiting parent must not light hover_group_shared"); +} diff --git a/app/vendor/rune/crates/rune/src/runtime/init.rs b/app/vendor/rune/crates/rune/src/runtime/init.rs new file mode 100644 index 0000000..934d883 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/init.rs @@ -0,0 +1,53 @@ +//! Non-generic [`RuntimeCore`] construction, shared by every [`Runtime<S>::with_text`] call. +use super::*; + +impl RuntimeCore { + pub(super) fn new(viewport: (f32, f32), env: Env, text: TextSystem) -> Self { + crate::frame::profile::install_text_hook(); + crate::tooling::perf_warn::warm(); + let mut scene = Scene::new(); + scene.set_pixel_scale(env.scale); + crate::recorder::headless_reset(); + crate::video::headless_reset(); + let host = window_requests::HostState::new(viewport, &env); + RuntimeCore { + env, + viewport, + t: 0.0, + clock: 0.0, + time_scale: 1.0, + reduced_motion: false, + track_marks: false, + animating: false, + settled: false, + transparent: false, + instances: Vec::new(), + marks: Vec::new(), + surfaces: Vec::new(), + tree: types::TreeState::new(), + hit: hit::HitState::new(), + motion: tracks::MotionState::new(), + scroll: requests::ScrollTables::new(), + paint: paint_state::PaintState::new(), + scene, + images: Default::default(), + text, + pointer: capture::PointerState::new(), + kbd: focus_machine::KeyboardState::new(), + commit: commit::CommitState::new(), + edit: caret::TextInputState::new(), + frame: timer_wake::FrameState::new(), + host, + ime_area: None, + copy_request: None, + shell_request: None, + wall_start: None, + events: Vec::new(), + stats: FrameStats::default(), + ambient: None, + double_click_interval: 0.5, + help_delay: 0.5, + _core_end: CoreEnd, + } + } +} diff --git a/app/vendor/rune/crates/rune/src/runtime/input.rs b/app/vendor/rune/crates/rune/src/runtime/input.rs new file mode 100644 index 0000000..34d416e --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/input.rs @@ -0,0 +1,34 @@ +//! Pointer, keyboard, focus, modal, touch, gesture, drag, popup, dialog, IME and hit-test +//! runtime subsystems. +use super::*; + +pub(crate) mod action; +pub(super) mod api; +pub(super) mod app_ime; +pub(super) mod autoscroll; +pub(super) mod capture; +pub(super) mod drop; +pub(crate) mod field_menu; +pub(super) mod file_dialog; +pub(super) mod focus; +pub(super) mod focus_machine; +pub(super) mod gesture; +pub(super) mod help; +pub(super) mod help_look; +pub(super) mod hit; +pub(super) mod hover; +pub(super) mod hover_delay; +pub(super) mod key_releases; +pub(super) mod keys; +pub(super) mod modal_focus; +pub(super) mod modifier_keys; +pub(super) mod physical; +pub(super) mod pointer; +pub(super) mod popup; +pub(super) mod press_repeat; +pub(super) mod press_run; +#[cfg(target_os = "linux")] +pub(super) mod primary_selection; +pub(super) mod secondary; +pub(super) mod titlebar; +pub(super) mod touch; diff --git a/app/vendor/rune/crates/rune/src/runtime/input/action.rs b/app/vendor/rune/crates/rune/src/runtime/input/action.rs new file mode 100644 index 0000000..e2b3e47 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/input/action.rs @@ -0,0 +1,587 @@ +//! The actions input and layout queue for the next frame's handlers, and how a frame runs them. + +use super::*; +use crate::time::Instant; + +pub(in crate::runtime) enum Action { + WindowFocus(bool), + Physical(crate::PhysicalInput, Option<physical_dispatch::Fallback>), + FocusControl(String), + /// The pointer entered a `focus_highlight` row (`Some`) or left every such row. + HoverFocus(Option<String>), + Dismiss(String), + PointerMove(String, PointerEvent), + Hover(String), + HoverChange(String, bool), + /// `El::on_selection_change`. + SelectionChange(String, crate::SelectionChange), + AtBottom(String, bool), + FarFromBottom(String, bool), + VisibleRows(String, std::ops::Range<usize>), + Layout(String, [f32; 4]), + ScreenLayout(String, [f32; 4]), + /// `El::on_drawn_layout`; true when only a live value, scroll or animation moved it. + DrawnLayout(String, [f32; 4], bool), + /// `El::on_visible`: the element came on screen or left it. + Visible(String, bool), + Press(String, crate::PointerButton, bool), // true for a touch tap + DoublePress(String), + /// `El::on_middle_press`. + MiddlePress(String), + /// A text's link and the button that clicked it (the primary or the middle). + Link(String, usize, crate::PointerButton), + /// `El::on_link_secondary`: the text, its link and the press. + LinkSecondary(String, usize, PointerEvent), + SecondaryPress(String, PointerEvent), + Drag(String, Drag, crate::PointerButton), + /// A held press's drag hearing the pointer again (`Tx::drag_repeat_after`). + DragRepeat(String, Drag, crate::PointerButton), + DragStart(String), + DragEnd(String, crate::DragOutcome), + /// A file drag from another app moved, left, or dropped (`drop_dispatch`). + Files(drop_dispatch::FileEvent), + /// `stage`: a playground step pressed it, for the stage (`Play::press`). + Key { ev: KeyEvent, repeat: bool, stage: bool }, + KeyUp(KeyEvent), + /// A wheel delta at window point (x, y) for the `on_wheel` handlers at the pointer, + /// innermost first, with the gesture's own axis policy: whether the platform reported its + /// phases (`runtime/input/gesture.rs`). + Wheel { gesture: crate::machine::Attempt, chain: Vec<String>, ev: crate::WheelEvent, phased: bool }, + Gesture(Vec<String>, gesture_dispatch::Gesture), + Ime(Ime), + /// The window went inactive: an open composition becomes text (`Runtime::finish_composition`). + FinishIme, + Paste(crate::ClipboardContent, Option<Option<String>>), + /// A `Tx::read_clipboard` callback's id and what the clipboard held. + ClipboardRead(u64, crate::ClipboardContent), + /// A `Tx::open_file` or `Tx::save_file` callback's id and the dialog's answer. + FileDialog(u64, crate::file_dialog::FileDialogResult), + Focus(String, f32, f32), + /// A text field's menu: the field, the window point it opens at, and the window point where a + /// press asked for it (none from the keyboard). + FieldMenu(String, (f32, f32), Option<(f32, f32)>), + Blur, + /// What assistive technology asked of an element (`a11y/actions.rs`). + A11y(String, crate::a11y::actions::A11yAct), +} + +/// A queued action and when the input that queued it arrived (`Tx::input_time`): the arrival +/// time its host dispatched the input under (`input_time::scope`), none for what layout, +/// timers, updates and polls queue. +pub(in crate::runtime) struct Queued { + pub(in crate::runtime) action: Action, + pub(in crate::runtime) at: Option<Instant>, + pub(in crate::runtime) input: bool, +} + +/// The actions waiting for the next frame, in order, each with its input's arrival time. +#[derive(Default)] +pub(in crate::runtime) struct ActionQueue(Vec<Queued>); + +impl ActionQueue { + /// Queues `action` stamped with the input being dispatched now, if any. + pub(in crate::runtime) fn push(&mut self, action: Action) { + // A host can dispatch input without a timestamp. Layout and state observers, on the + // other hand, don't become input just because they have a queued callback. + let at = crate::input::time::current(); + let input = !matches!(action, Action::Layout(..) | Action::ScreenLayout(..) | Action::DrawnLayout(..) + | Action::Visible(..) | Action::VisibleRows(..) | Action::AtBottom(..) | Action::FarFromBottom(..) + | Action::WindowFocus(_) | Action::Physical(crate::PhysicalInput::FocusLost, _) | Action::FinishIme + | Action::ClipboardRead(..) | Action::SelectionChange(..)) || at.is_some(); + self.0.push(Queued { action, at, input }); + } + /// A stationary pointer was re-hit after layout; no pointer event asked for that hover. + pub(in crate::runtime) fn observe_since(&mut self, start: usize) { + for q in &mut self.0[start..] { q.input = false; } + } + /// Queues an action again with its own stamp. + pub(in crate::runtime) fn push_queued(&mut self, queued: Queued) { self.0.push(queued); } + /// Puts `queued` ahead of everything queued. + pub(in crate::runtime) fn prepend(&mut self, queued: Vec<Queued>) { self.0.splice(0..0, queued); } + pub(in crate::runtime) fn iter(&self) -> impl Iterator<Item = &Action> { self.0.iter().map(|q| &q.action) } + /// Whether any of them came from the user's input (they carry its arrival time). + pub(in crate::runtime) fn has_input(&self) -> bool { self.0.iter().any(|q| q.at.is_some()) } + /// Whether any of them is the user's input, as the commit's `INPUT` cause counts it: a host + /// may dispatch input without a timestamp. + pub(in crate::runtime) fn has_input_action(&self) -> bool { self.0.iter().any(|q| q.input) } + pub(in crate::runtime) fn len(&self) -> usize { self.0.len() } + pub(in crate::runtime) fn is_empty(&self) -> bool { self.0.is_empty() } + pub(in crate::runtime) fn retain(&mut self, mut keep: impl FnMut(&Action) -> bool) { self.0.retain(|q| keep(&q.action)); } + pub(in crate::runtime) fn remove(&mut self, index: usize) -> Action { self.0.remove(index).action } +} + +impl Extend<Action> for ActionQueue { + fn extend<I: IntoIterator<Item = Action>>(&mut self, actions: I) { + for action in actions { self.push(action); } + } +} + +impl Extend<Queued> for ActionQueue { + fn extend<I: IntoIterator<Item = Queued>>(&mut self, queued: I) { self.0.extend(queued); } +} + +impl FromIterator<Queued> for ActionQueue { + fn from_iter<I: IntoIterator<Item = Queued>>(queued: I) -> Self { Self(queued.into_iter().collect()) } +} + +impl IntoIterator for ActionQueue { + type Item = Queued; + type IntoIter = std::vec::IntoIter<Queued>; + fn into_iter(self) -> Self::IntoIter { self.0.into_iter() } +} + +/// The handler an event goes to, when its `Tx::live_only` can keep the event from committing. +/// Events Rune does its own work for (focus, editing, pastes, file drops) always commit. +pub(in crate::runtime) fn live_only_handler(action: &Action) -> Option<&'static str> { + Some(match action { + Action::WindowFocus(_) => "on_window_focus", + Action::DrawnLayout(..) => "on_drawn_layout_tx", + Action::Visible(..) => "on_visible", + Action::Layout(..) => "on_layout_tx", + Action::PointerMove(..) => "on_pointer_move_local", + Action::Hover(_) => "on_hover", + Action::HoverChange(..) => "on_hover_change", + Action::SelectionChange(..) => "on_selection_change", + Action::Press(..) => "on_press", + Action::DoublePress(_) => "on_double_press", + Action::MiddlePress(_) => "on_middle_press", + Action::Link(..) => "on_link", + Action::LinkSecondary(..) => "on_link_secondary", + Action::SecondaryPress(..) => "on_secondary_press", + Action::Drag(..) | Action::DragRepeat(..) => "on_drag", + Action::DragStart(_) => "on_drag_start", + Action::DragEnd(..) => "on_drag_end", + Action::Key { .. } => "on_key", + Action::KeyUp(_) => "on_key_up", + Action::Wheel { .. } => "on_wheel", + Action::Gesture(_, gesture_dispatch::Gesture::Magnify(_)) => "on_magnify", + Action::Gesture(_, gesture_dispatch::Gesture::Rotate(_)) => "on_rotate", + Action::Gesture(_, gesture_dispatch::Gesture::SmartMagnify(..)) => "on_smart_magnify", + _ => return None, + }) +} + +#[cfg(debug_assertions)] +pub(in crate::runtime) fn action_path(action: &Action) -> Option<&str> { + match action { + Action::PointerMove(path, _) | Action::DrawnLayout(path, ..) | Action::Layout(path, _) | Action::Hover(path) | Action::HoverChange(path, _) | Action::SelectionChange(path, _) | Action::Press(path, ..) | Action::DoublePress(path) | Action::MiddlePress(path) + | Action::Link(path, ..) | Action::LinkSecondary(path, ..) | Action::SecondaryPress(path, _) | Action::Drag(path, ..) | Action::DragRepeat(path, ..) | Action::DragStart(path) + | Action::DragEnd(path, _) | Action::Visible(path, _) => Some(path), + Action::Wheel { chain, .. } | Action::Gesture(chain, _) => chain.first().map(String::as_str), + _ => None, + } +} + +/// The handler an action runs, for the stall warning. +#[cfg(debug_assertions)] +fn handler_name(action: &Action) -> &'static str { + live_only_handler(action).unwrap_or(match action { + Action::Physical(..) => "on_key", + Action::FocusControl(_) | Action::HoverFocus(_) | Action::Focus(..) | Action::Blur => "a focus change", + Action::Dismiss(_) => "a modal's dismiss", + Action::AtBottom(..) => "on_at_bottom", + Action::FarFromBottom(..) => "on_far_from_bottom", + Action::VisibleRows(..) => "on_visible_rows", + Action::ScreenLayout(..) => "on_screen_layout", + Action::Files(_) => "on_drop_files", + Action::Ime(_) | Action::FinishIme => "a text input's edit", + Action::Paste(..) => "on_paste", + Action::ClipboardRead(..) => "a `read_clipboard` callback", + Action::FileDialog(..) => "a file dialog callback", + _ => "a handler", + }) +} + +#[cfg(debug_assertions)] +fn stall_path(action: &Action) -> Option<&str> { + match action { + Action::Dismiss(path) | Action::AtBottom(path, _) | Action::FarFromBottom(path, _) | Action::VisibleRows(path, _) + | Action::Layout(path, _) | Action::ScreenLayout(path, _) | Action::Focus(path, ..) | Action::FocusControl(path) => Some(path), + _ => action_path(action), + } +} + +pub(crate) fn merge(tx: &mut Tx, one: Tx) { + tx.pick_reads.extend(one.pick_reads); + tx.paste |= one.paste; + tx.clipboard_reads.extend(one.clipboard_reads); + if let Some(one) = one.trace { + let trace = tx.trace.get_or_insert_with(Default::default); + trace.events.extend(one.events); + trace.channels.extend(one.channels); + } + tx.scroll_to.extend(one.scroll_to); + tx.scroll_bottom.extend(one.scroll_bottom); + tx.scroll_pages.extend(one.scroll_pages); + tx.scroll_offsets.extend(one.scroll_offsets); + tx.keep_on_screen.extend(one.keep_on_screen); + tx.evict_memos.extend(one.evict_memos); + tx.wakes.extend(one.wakes); + tx.text_flights.extend(one.text_flights); + tx.launches.extend(one.launches); + tx.unclipped_flights |= one.unclipped_flights; + tx.popups.extend(one.popups); + tx.file_dialogs.extend(one.file_dialogs); + if let Some(request) = one.window_frame { tx.window_frame = Some(tx.window_frame.unwrap_or_default().merge(request)); } + if one.clear_secret && tx.copy.as_ref().is_some_and(crate::ClipboardWrite::is_secret) { tx.copy = None; } + tx.clear_secret |= one.clear_secret; + if one.copy.is_some() { tx.copy = one.copy; } + tx.shell = tx.shell.max(one.shell); + tx.minimize_order = tx.minimize_order.max(one.minimize_order); + tx.toggle_maximized |= one.toggle_maximized; + tx.toggle_full_screen |= one.toggle_full_screen; + tx.keys.extend(one.keys); + if one.title.is_some() { tx.title = one.title; } + if one.announce.is_some() { tx.announce = one.announce; } + tx.playground.extend(one.playground); + tx.open_urls.extend(one.open_urls); + tx.srgb_blend = one.srgb_blend.or(tx.srgb_blend); + tx.font_smoothing = one.font_smoothing.or(tx.font_smoothing); + if one.font_families.is_some() { tx.font_families = one.font_families; } + if one.rewind.is_some() { tx.rewind = one.rewind; } + tx.blur |= one.blur; + if one.focus_to.is_some() { tx.focus_to = one.focus_to; } + if one.select.is_some() { + tx.select = one.select; + tx.select_from_change = one.select_from_change; + } + tx.commit = tx.commit.merge(one.commit); + tx.follow_edge |= one.follow_edge; + tx.asked_motion |= one.asked_motion; + for (stack, ink) in one.live_growth { tx.request_live_growth(stack, ink); } + tx.tail_rooms.extend(one.tail_rooms); + tx.motion = one.motion.or(tx.motion); + tx.color_motion = one.color_motion.or(tx.color_motion); +} + +/// Slots the ends hosts reported since the last frame into this frame's actions. One OS drag +/// runs at a time and hosts report ends in order, so each belongs to the oldest open drag: it +/// runs before any later drag's start, and after its own start when both are queued. +pub(in crate::runtime) fn order_drag_ends(queue: ActionQueue, ended: Vec<(String, crate::DragOutcome)>, open: &mut usize) -> ActionQueue { + let mut ended = ended.into_iter().map(|(path, outcome)| Queued { action: Action::DragEnd(path, outcome), at: None, input: true }); + let mut out = Vec::with_capacity(queue.len() + ended.len()); + for queued in queue { + match &queued.action { + Action::DragStart(_) => { + while *open > 0 && let Some(end) = ended.next() { + out.push(end); + *open -= 1; + } + *open += 1; + } + Action::DragEnd(..) => *open = open.saturating_sub(1), + _ => {} + } + out.push(queued); + } + for end in ended { + *open = open.saturating_sub(1); + out.push(end); + } + ActionQueue(out) +} + +impl RuntimeCore { + /// Runs `action`'s handlers; debug builds warn when they block the main thread. + pub(in crate::runtime) fn run_action(&mut self, app: &mut dyn AppDriver, action: Action, tx: &mut Tx) -> bool { + #[cfg(debug_assertions)] + let (name, path, at) = (handler_name(&action), stall_path(&action).map(str::to_owned), self.handler_location(&action)); + let stall = crate::tooling::perf_warn::Stall::start(); + let timed = self.interaction_note(&action).map(|note| (note, crate::time::now())); + let ran = self.dispatch_action(app, action, tx); + if ran && let Some((note, started)) = timed { self.interaction_ran(note, started); } + #[cfg(debug_assertions)] + if ran && name.starts_with("on_") { self.commit.watch.meter.handler(name, path.as_deref(), at); } + #[cfg(debug_assertions)] + stall.end(|| match path { + Some(path) => (crate::tooling::perf_warn::handler_site(name, &path), format!("`{name}` on {path:?}")), + None => (name.to_owned(), format!("`{name}`")), + }); + #[cfg(not(debug_assertions))] + stall.end(|| unreachable!()); + ran + } + + /// Where the app set the handler `action` runs, for the commit warnings. + #[cfg(debug_assertions)] + fn handler_location(&self, action: &Action) -> Option<&'static std::panic::Location<'static>> { + let sites = |path: &str| self.node(path).map(|n| n.handlers.sites); + match action { + Action::Hover(p) => sites(p)?.hover, + Action::HoverChange(p, _) => sites(p)?.hover_change, + Action::PointerMove(p, _) => sites(p)?.pointer_move, + Action::Layout(p, _) => sites(p)?.layout, + Action::DrawnLayout(p, ..) => sites(p)?.drawn_layout, + Action::VisibleRows(p, _) => sites(p)?.visible_rows, + _ => None, + } + } + + fn dispatch_action(&mut self, app: &mut dyn AppDriver, action: Action, tx: &mut Tx) -> bool { + // A caret key or a press reads the field's layout where it lands: a long paste's + // paragraphs still waiting there are shaped first. Typing at the caret needs none. + if !self.paint.text_rows.is_empty() && reads_text_layout(&action) { self.fill_text_near(); } + let mut one = self.transaction(app); + // Debug builds name the element too, for the stale-view warning. + #[cfg(debug_assertions)] + let live_label = live_only_handler(&action).map(|h| match action_path(&action) { + Some(path) => format!("{h} on {path:?}"), + None => h.to_owned(), + }); + #[cfg(not(debug_assertions))] + let live_label = live_only_handler(&action); + let repeat = matches!(action, Action::DragRepeat(..)); + let ran = match action { + Action::WindowFocus(focused) => { + if !focused { self.kbd.clear_held(); } + let Some(f) = self.tree.nodes.get(self.app_root()).and_then(|n| n.handlers.on_window_focus.clone()) else { return false }; + f(app.states(), focused, &mut one); + true + } + Action::Physical(event, fallback) => { + // The window lost key focus (an internal focus move also notifies handlers). + if matches!(event, crate::PhysicalInput::FocusLost) { self.kbd.clear_held(); } + let ran = self.dispatch_physical(app, event, fallback, tx); + let live_only = std::mem::take(&mut tx.live_only); + return if ran && live_only { self.skip_view("a key handler") } else { ran }; + } + Action::FocusControl(path) => { + self.set_focus(app, Some(path), false); + true + } + Action::HoverFocus(path) => match path { + Some(path) => { + self.set_focus(app, Some(path), false); + self.kbd.focus.step(focus_machine::FocusEvent::Hover(true)); + one.commit = one.commit.instant(); + true + } + None => { + let lit = self.kbd.focus.hovered(); + self.kbd.focus.step(focus_machine::FocusEvent::Hover(false)); + lit + } + }, + Action::Dismiss(path) => { + let Some(f) = self.node(&path).and_then(|n| n.handlers.modal.as_ref().map(|m| m.dismiss.clone())) else { return false }; + self.set_focus(app, None, self.kbd.focus.keyboard()); + f(app.states(), &mut one); + true + } + Action::PointerMove(path, point) => { + let Some(f) = self.node(&path).and_then(|n| n.handlers.on_pointer_move.clone()) else { return false }; + f(app.states(), point, &mut one); + true + } + Action::AtBottom(path, at) => { + let Some(f) = self.node(&path).and_then(|n| n.handlers.on_at_bottom.clone()) else { return false }; + f(app.states(), at) + } + Action::FarFromBottom(path, far) => { + let Some((_, _, f)) = self.node(&path).and_then(|n| n.handlers.on_far_from_bottom.clone()) else { return false }; + f(app.states(), far) + } + Action::VisibleRows(path, range) => { + let Some(f) = self.node(&path).and_then(|n| n.handlers.on_visible_rows.clone()) else { return false }; + f(app.states(), range) + } + Action::Layout(path, rect) => { + let Some(f) = self.node(&path).and_then(|n| n.handlers.on_layout.clone()) else { return false }; + f(app.states(), rect, &mut one); + true + } + Action::ScreenLayout(path, rect) => { + let Some(f) = self.node(&path).and_then(|n| n.handlers.on_screen_layout.clone()) else { return false }; + f(app.states(), rect); + true + } + Action::DrawnLayout(path, rect, _) => { + let Some(f) = self.node(&path).and_then(|n| n.handlers.on_drawn_layout.clone()) else { return false }; + f(app.states(), rect, &mut one); + true + } + Action::Visible(path, on) => { + let Some(f) = self.node(&path).and_then(|n| n.handlers.on_visible.clone()) else { return false }; + f(app.states(), on, &mut one); + true + } + Action::Hover(path) => { + let Some(f) = self.node(&path).and_then(|n| n.handlers.on_hover.clone()) else { return false }; + f(app.states(), &mut one); + true + } + Action::HoverChange(path, inside) => { + let gone = self.pointer.take_hover_gone(&path); + // A leave still reaches an element on its way out. + let exiting = || self.tree.nodes.iter().find(|n| !inside && n.path == path).and_then(|n| n.handlers.on_hover_change.clone()); + let Some(f) = self.node(&path).and_then(|n| n.handlers.on_hover_change.clone()).or(gone).or_else(exiting) else { return false }; + f(app.states(), inside, &mut one); + true + } + Action::SelectionChange(path, change) => { + let Some(f) = self.node(&path).and_then(|n| n.handlers.on_selection_change.clone()) else { return false }; + f(app.states(), &change, &mut one); + one.select_from_change = one.select.is_some(); + true + } + Action::Press(path, button, touch) => { + let Some(f) = self.node(&path).and_then(|n| n.handlers.on_press.clone()) else { return false }; + log_event!(self, "press {path}"); + one.button = button; + one.touch_tap = touch; + f(app.states(), &mut one); + true + } + Action::DoublePress(path) => { + let Some(f) = self.node(&path).and_then(|n| n.handlers.on_double_press.clone()) else { return false }; + log_event!(self, "double press {path}"); + f(app.states(), &mut one); + true + } + Action::MiddlePress(path) => { + let Some(f) = self.node(&path).and_then(|n| n.handlers.on_middle_press.clone()) else { return false }; + log_event!(self, "middle press {path}"); + one.button = crate::PointerButton::Middle; + f(app.states(), &mut one); + true + } + Action::Link(path, k, button) => { + one.button = button; + self.press_link(app, &path, k, &mut one) + } + Action::LinkSecondary(path, k, point) => self.secondary_press_link(app, &path, k, point, &mut one), + Action::SecondaryPress(path, point) => { + let Some(n) = self.node(&path).filter(|n| !self.is_exiting(n.id)) else { return false }; + let Some(f) = n.handlers.on_secondary_press.clone() else { return false }; + log_event!(self, "secondary press {path}"); + f(app.states(), point, &mut one); + true + } + Action::Drag(path, mut d, button) | Action::DragRepeat(path, mut d, button) => { + let Some(f) = self.node(&path).and_then(|n| n.handlers.on_drag.clone()) else { return false }; + if d.phase == Phase::Move { + one.commit = one.commit.instant(); + } + one.button = button; + one.drag_repeat = repeat; + d.data = if d.phase == Phase::Down { 0.0 } else { self.pointer.drag_data() }; + f(app.states(), &mut d, &mut one); + self.pointer.set_drag_data(d.data); + if let Some(after) = one.drag_repeat_after.take() { + self.arm_press_repeat(&path, after); + } + if d.phase != Phase::Move { + log_event!(self, "drag {:?} {path}", d.phase); + } + true + } + Action::DragStart(path) => { + let Some(f) = self.node(&path).and_then(|n| n.handlers.on_drag_start.clone()) else { return false }; + f(app.states(), &mut one); + true + } + Action::DragEnd(path, outcome) => { + log_event!(self, "drag-end {outcome:?} {path}"); + let Some(f) = self.node(&path).and_then(|n| n.handlers.on_drag_end.clone()) else { return false }; + f(app.states(), outcome, &mut one); + true + } + Action::Files(event) => self.run_files(app, event, &mut one), + Action::Key { ev, repeat, stage } => { + if self.kbd.held_gate(None, Some(&ev.key), repeat) { return false; } + if ! matches!(ev.key, crate::Key::Modifier { .. }) { self.note_key_down(app, repeat); } + if stage { self.route_stage_key(app, &ev, &mut one) } else { self.route_key(app, &ev, repeat, &mut one) } + } + Action::KeyUp(ev) => self.route_key_up(app, &ev, &mut one), + Action::Wheel { gesture, chain, ev, phased } => self.run_wheel(app, gesture, chain, ev, phased, &mut one), + Action::Gesture(chain, gesture) => self.run_gesture(app, chain, gesture, &mut one), + Action::Ime(ev) => self.run_ime(app, ev, &mut one), + Action::FinishIme => self.finish_ime(app, &mut one), + Action::Paste(content, target) => { + if target.is_some_and(|target| target != self.paste_target()) { return false; } + let hook = self.focused_input().and_then(|i| i.paste.clone()); + let own_pills = if cfg!(not(target_arch = "wasm32")) || self.edit.has_clipboard() { + content.has_own_pills() + } else { + content.html().is_some_and(|h| self.edit.has_pill_copy_matching(content.text(), h)) + }; + let into_field = |mut state: crate::states::States<'_>, access: &crate::el::EditFn, tx: &mut Tx| { + if hook.is_some_and(|hook| hook(state.reborrow(), &content, tx)) { return EditOutcome::default(); } + let edit = access(state); + // A rich field keeps the paste's formatting. The HTML was sanitised when it + // was read, and `from_html` keeps only its own safe subset anyway. + if let Some(html) = content.html() && edit.is_rich() && !edit.is_secure() { + return if own_pills { edit.paste_html_with_pills(html, content.text()) } else { edit.paste_html(html, content.text()) }; + } + if !content.has_plain() { return EditOutcome::default(); } + edit.paste(content.text()) + }; + if self.with_focused_state(app, into_field, &mut one) { + log_event!(self, "paste field"); + true + } else if let Some(f) = self.app_paste_handler() && (f.call)(app.states(), &content, &mut one) { + log_event!(self, "paste window"); + true + } else { false } + } + Action::ClipboardRead(id, content) => { + let Some(f) = self.edit.take_clipboard_read(id) else { return false }; + f(app.states(), &content, &mut one); + true + } + Action::FileDialog(id, result) => self.run_file_dialog(app, id, result, &mut one), + Action::Focus(path, x, y) => self.focus_input(app, path, x, y, &mut one), + Action::FieldMenu(path, at, local) => self.field_menu(app, path, at, local, &mut one), + Action::Blur => { + if self.kbd.focus.path().is_none() { return false; } + self.set_focus(app, None, self.kbd.focus.keyboard()); + true + } + Action::A11y(path, act) => self.run_a11y(app, path, act, &mut one), + }; + let live_only = std::mem::take(&mut one.live_only); + if live_only && live_label.is_some() { + // A handler that asks for no commit cannot change another handler's animation. + one.commit = Commit::Animate; + one.motion = None; + one.follow_edge = false; + one.color_motion = None; + } + merge(tx, one); + if ran && live_only && let Some(label) = live_label { + return self.skip_view(label); + } + ran + } + + pub(crate) fn queue_a11y(&mut self, path: String, act: crate::a11y::actions::A11yAct) { + self.frame.queue.push(Action::A11y(path, act)); + } + pub(crate) fn queue_a11y_press(&mut self, path: String) { + self.frame.queue.push(Action::Press(path, crate::PointerButton::Primary, false)); + } + pub(crate) fn queue_a11y_secondary_press(&mut self, path: String, ev: PointerEvent) { + self.frame.queue.push(Action::SecondaryPress(path, ev)); + } + pub(crate) fn queue_a11y_link(&mut self, path: String, link: usize) { + self.frame.queue.push(Action::Link(path, link, crate::PointerButton::Primary)); + } + pub(crate) fn queue_a11y_link_secondary(&mut self, path: String, link: usize, ev: PointerEvent) { + self.frame.queue.push(Action::LinkSecondary(path, link, ev)); + } +} + +/// Whether `action` reads a text's layout away from its caret: caret movement, a press or a +/// drag. Text typed, deleted or composed at the caret doesn't. +fn reads_text_layout(action: &Action) -> bool { + use crate::Key; + match action { + Action::Key { ev, .. } => match &ev.key { + Key::Text(_) | Key::Backspace | Key::Delete => ev.mods.cmd || ev.mods.ctrl || ev.mods.alt, + Key::Modifier { .. } => false, + _ => true, + }, + Action::Press(..) | Action::DoublePress(..) | Action::MiddlePress(..) | Action::SecondaryPress(..) | Action::Drag(..) | Action::DragStart(..) => true, + _ => false, + } +} diff --git a/app/vendor/rune/crates/rune/src/runtime/input/api.rs b/app/vendor/rune/crates/rune/src/runtime/input/api.rs new file mode 100644 index 0000000..7669e8b --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/input/api.rs @@ -0,0 +1,344 @@ +//! Thin `#[inline(always)]` public and crate-internal forwarders on [`Runtime<S>`] delegating +//! to non-generic [`RuntimeCore`] for pointer, keyboard, gesture, touch, scroll, drop, popup, +//! file dialog, titlebar, help, and text selection. + +use std::path::PathBuf; + +use super::*; +#[cfg(test)] +use crate::file_dialog::FileDialogResult; +use crate::file_dialog::{FileDialogError, FileDialogKind, FileDialogOptions}; +#[cfg(any(test, target_arch = "wasm32"))] +use crate::popup_menu::Show; +use crate::popup_menu::{PopupMenu, PopupMenuError}; +use crate::{MagnifyEvent, PhysicalInput, PointerButton, RotateEvent, WheelEvent}; + +#[allow(dead_code)] +impl<S: 'static> Runtime<S> { + // ── Pointer & secondary ──────────────────────────────────────────────────────────────────── + + #[inline(always)] + pub fn pointer_move(&mut self, x: f32, y: f32) { + let (core, app) = self.split_mut(); + core.pointer_move(&app, x, y); + } + + #[inline(always)] + pub(crate) fn observe_pointer(&mut self, x: f32, y: f32) -> bool { + let (core, app) = self.split_mut(); + core.observe_pointer(&app, x, y) + } + + #[inline(always)] + pub(crate) fn pointer_captured(&self) -> bool { self.core().pointer_captured() } + #[inline(always)] + pub(crate) fn set_window_pixels(&mut self, pixels: Option<(i32, i32)>) { self.core_mut().set_window_pixels(pixels); } + #[inline(always)] + pub(crate) fn window_moved(&mut self, dx: f32, dy: f32) { self.core_mut().window_moved(dx, dy); } + #[inline(always)] + pub(crate) fn cancel_pointer(&mut self) { self.core_mut().cancel_pointer(); } + #[cfg_attr(not(target_os = "macos"), allow(dead_code))] + #[inline(always)] + pub(crate) fn disarm_drag_out(&mut self) { self.core_mut().disarm_drag_out(); } + + #[inline(always)] + pub fn pointer_down(&mut self, x: f32, y: f32) { + let (core, mut app) = self.split_mut(); + core.pointer_down(&mut app, x, y); + } + + #[inline(always)] + pub fn pointer_up(&mut self, x: f32, y: f32) { + let (core, app) = self.split_mut(); + core.pointer_up(&app, x, y); + } + + #[cfg_attr(not(target_os = "macos"), allow(dead_code))] + #[inline(always)] + pub(crate) fn pointer_release_lost(&mut self, x: f32, y: f32) { + let (core, app) = self.split_mut(); + core.pointer_release_lost(&app, x, y); + } + + #[inline(always)] + pub fn pointer_leave(&mut self) { self.core_mut().pointer_leave(); } + #[inline(always)] + pub fn pressing(&self) -> bool { self.core().pressing() } + #[inline(always)] + pub fn pointer(&self) -> Option<(f32, f32)> { self.core().pointer() } + #[inline(always)] + pub fn hit_regions(&self) -> &[[f32; 4]] { self.core().hit_regions() } + #[inline(always)] + pub fn cursor(&self) -> crate::el::Cursor { self.core().cursor() } + #[inline(always)] + pub fn wheel(&mut self, x: f32, y: f32, dy: f32) { self.core_mut().wheel(x, y, dy); } + #[inline(always)] + pub fn set_wheel_glide(&mut self, on: bool) { self.core_mut().scroll.set_wheel_glide(on); } + #[inline(always)] + pub fn fling(&mut self, x: f32, y: f32, velocity: f32) { self.core_mut().fling(x, y, velocity); } + #[inline(always)] + pub fn has_pending_input(&self) -> bool { self.core().has_pending_input() } + + #[inline(always)] + pub fn secondary_down(&mut self, x: f32, y: f32) { self.core_mut().secondary_down(x, y); } + #[cfg_attr(not(target_arch = "wasm32"), allow(dead_code))] + #[inline(always)] + pub(crate) fn secondary_claim(&self) -> &'static str { self.core().secondary_claim() } + #[cfg_attr(not(target_arch = "wasm32"), allow(dead_code))] + #[inline(always)] + pub(crate) fn secondary_abandon(&mut self) { self.core_mut().secondary_abandon(); } + #[inline(always)] + pub fn secondary_up(&mut self, x: f32, y: f32) { + let (core, app) = self.split_mut(); + core.secondary_up(&app, x, y); + } + + // ── Gestures, touch & scroll ─────────────────────────────────────────────────────────────── + + #[inline(always)] + pub fn wheel_event(&mut self, ev: WheelEvent) { self.core_mut().wheel_event(ev); } + #[inline(always)] + pub fn magnify_event(&mut self, ev: MagnifyEvent) { self.core_mut().magnify_event(ev); } + #[inline(always)] + pub fn rotate_event(&mut self, ev: RotateEvent) { self.core_mut().rotate_event(ev); } + #[inline(always)] + pub fn smart_magnify(&mut self, x: f32, y: f32) { self.core_mut().smart_magnify(x, y); } + #[inline(always)] + pub(crate) fn pinch_wheel(&mut self, x: f32, y: f32, dy: f32) -> bool { self.core_mut().pinch_wheel(x, y, dy) } + #[inline(always)] + pub fn button_down(&mut self, x: f32, y: f32, button: PointerButton) { + let (core, mut app) = self.split_mut(); + core.button_down(&mut app, x, y, button); + } + #[inline(always)] + pub fn button_up(&mut self, x: f32, y: f32, button: PointerButton) { + let (core, app) = self.split_mut(); + core.button_up(&app, x, y, button); + } + #[inline(always)] + pub fn key_up(&mut self, ev: KeyEvent) -> bool { + let (core, mut app) = self.split_mut(); + core.key_up(&mut app, ev) + } + #[inline(always)] + pub(crate) fn hears_wheel(&self) -> bool { self.core().hears_wheel() } + #[inline(always)] + pub(crate) fn wants_key_up(&self) -> bool { self.core().wants_key_up() } + + #[inline(always)] + pub fn touch(&mut self, id: u64, phase: TouchPhase, x: f32, y: f32, time: f64) { + let (core, mut app) = self.split_mut(); + core.touch(&mut app, id, phase, x, y, time); + } + #[inline(always)] + pub fn touching(&self) -> bool { self.core().touching() } + + #[inline(always)] + pub fn wheel_xy(&mut self, x: f32, y: f32, dx: f32, dy: f32) { self.core_mut().wheel_xy(x, y, dx, dy); } + #[inline(always)] + pub fn wheel_began(&mut self) { self.core_mut().wheel_began(); } + #[inline(always)] + pub fn wheel_ended(&mut self) { self.core_mut().wheel_ended(); } + #[inline(always)] + pub fn fling_xy(&mut self, x: f32, y: f32, vx: f32, vy: f32) { self.core_mut().fling_xy(x, y, vx, vy); } + #[cfg(target_os = "windows")] + #[inline(always)] + pub(crate) fn windows_wheel_points(&self, delta: winit::event::MouseScrollDelta, shift: bool) -> f32 { + self.core().windows_wheel_points(delta, shift) + } + #[inline(always)] + pub fn scroll_at_bottom(&self, key: &str) -> Option<bool> { self.core().scroll_at_bottom(key) } + + // ── Keys, IME, physical & modifiers ──────────────────────────────────────────────────────── + + #[inline(always)] + pub fn key(&mut self, ev: KeyEvent) { self.core_mut().key(ev); } + #[inline(always)] + pub fn repeat_key(&mut self, ev: KeyEvent) { self.core_mut().repeat_key(ev); } + #[inline(always)] + pub fn ime(&mut self, ev: Ime) { self.core_mut().ime(ev); } + #[inline(always)] + pub fn finish_composition(&mut self) { self.core_mut().finish_composition(); } + #[inline(always)] + pub fn paste(&mut self, text: impl Into<String>) { self.core_mut().paste(text.into()); } + #[inline(always)] + pub fn paste_content(&mut self, content: crate::ClipboardContent) { self.core_mut().paste_content(content); } + #[inline(always)] + pub(crate) fn accepts_paste(&self) -> bool { self.core().accepts_paste() } + #[cfg(test)] + #[inline(always)] + pub(crate) fn paste_target(&self) -> Option<String> { self.core().paste_target() } + #[cfg(test)] + #[inline(always)] + pub(crate) fn paste_forms(&self, target: Option<&str>) -> crate::clipboard::Forms { self.core().paste_forms(target) } + #[cfg(test)] + #[inline(always)] + pub(crate) fn paste_result(&mut self, target: Option<String>, content: crate::ClipboardContent) { self.core_mut().paste_result(target, content); } + #[inline(always)] + pub fn has_secure_focus(&self) -> bool { self.core().has_secure_focus() } + #[inline(always)] + pub fn has_focus(&self) -> bool { self.core().has_focus() } + + #[inline(always)] + pub fn set_modifier_keys(&mut self, enabled: bool) { self.core_mut().set_modifier_keys(enabled); } + #[inline(always)] + pub fn modifier_keys(&self) -> bool { self.core().modifier_keys() } + + #[inline(always)] + pub fn physical_input(&mut self, event: PhysicalInput) { self.core_mut().physical_input(event); } + #[inline(always)] + pub(crate) fn physical_key_input(&mut self, event: PhysicalInput, key: KeyEvent, base: Option<char>) { + let (core, mut app) = self.split_mut(); + core.physical_key_input(&mut app, event, key, base); + } + #[cfg_attr(any(target_os = "windows", target_os = "ios", target_os = "android"), allow(dead_code))] + #[inline(always)] + pub(crate) fn physical_with_fallback(&mut self, event: PhysicalInput, key: Option<KeyEvent>) -> bool { + let (core, mut app) = self.split_mut(); + core.physical_with_fallback(&mut app, event, key) + } + #[inline(always)] + pub(crate) fn physical_then(&mut self, event: PhysicalInput, key: Option<KeyEvent>, base: Option<char>, unhandled: Option<Unhandled>) -> bool { + let (core, mut app) = self.split_mut(); + core.physical_then(&mut app, event, key, base, unhandled) + } + #[inline(always)] + pub(crate) fn physical_observation(&mut self, event: PhysicalInput) -> bool { + let (core, mut app) = self.split_mut(); + core.physical_observation(&mut app, event) + } + + // ── Drag & drop, drag-out, help, titlebar, popup, file dialog & selection ───────────────── + + #[inline(always)] + pub fn drag_files(&mut self, paths: Vec<PathBuf>, at: Option<(f32, f32)>) { self.core_mut().drag_files(paths, at); } + #[inline(always)] + pub fn drag_files_to(&mut self, at: Option<(f32, f32)>) -> bool { self.core_mut().drag_files_to(at) } + #[inline(always)] + pub fn drag_files_leave(&mut self) { self.core_mut().drag_files_leave(); } + #[inline(always)] + pub fn drop_files(&mut self, paths: Vec<PathBuf>, at: Option<(f32, f32)>) { self.core_mut().drop_files(paths, at); } + #[inline(always)] + pub fn dragging_files(&self) -> bool { self.core().dragging_files() } + #[inline(always)] + pub fn drop_hovered(&self) -> Option<String> { self.core().drop_hovered() } + #[inline(always)] + pub fn drop_rejected_hovered(&self) -> Option<String> { self.core().drop_rejected_hovered() } + + #[inline(always)] + pub(crate) fn take_drag_out(&mut self) -> Option<crate::drag_out::DragOutStart> { self.core_mut().take_drag_out() } + #[inline(always)] + pub(crate) fn drag_end_sink(&self) -> crate::drag_out::DragEnds { self.core().drag_end_sink() } + #[inline(always)] + pub(crate) fn drag_ends_pending(&self) -> bool { self.core().drag_ends_pending() } + #[inline(always)] + pub(crate) fn set_os_drag(&mut self, supported: bool) { self.core_mut().set_os_drag(supported); } + + #[cfg(target_os = "macos")] + #[inline(always)] + pub(crate) fn set_native_help(&mut self, on: bool) { self.core_mut().set_native_help(on); } + #[inline(always)] + pub fn help_regions(&self) -> &[([f32; 4], String)] { self.core().help_regions() } + #[inline(always)] + pub fn help_tooltip(&self) -> Option<(&str, [f32; 4])> { self.core().help_tooltip() } + + #[inline(always)] + pub fn set_native_titlebar_band(&mut self, points: f32) { self.core_mut().set_native_titlebar_band(points); } + #[inline(always)] + pub fn take_titlebar_action(&mut self) -> Option<TitlebarAction> { self.core_mut().take_titlebar_action() } + #[inline(always)] + pub fn set_chrome_insets(&mut self, insets: crate::ChromeInsets) { self.core_mut().set_chrome_insets(insets); } + #[inline(always)] + pub fn chrome_insets(&self) -> crate::ChromeInsets { self.core().chrome_insets() } + #[cfg(test)] + #[inline(always)] + pub(crate) fn set_caption(&mut self, caption: Option<crate::titlebar::Caption>) { self.core_mut().set_caption(caption); } + #[inline(always)] + pub(crate) fn headless_chrome(&mut self, chrome: crate::Chrome, titlebar: Option<crate::Titlebar>, borderless: bool) -> crate::Chrome { + self.core_mut().headless_chrome(chrome, titlebar, borderless) + } + #[cfg_attr(target_arch = "wasm32", allow(dead_code))] + #[inline(always)] + pub(crate) fn take_toggle_maximized(&mut self) -> bool { self.core_mut().take_toggle_maximized() } + #[cfg_attr(target_arch = "wasm32", allow(dead_code))] + #[inline(always)] + pub(crate) fn take_toggle_full_screen(&mut self) -> bool { self.core_mut().take_toggle_full_screen() } + #[cfg_attr(target_arch = "wasm32", allow(dead_code))] + #[inline(always)] + pub(crate) fn take_window_menu(&mut self) -> Option<WindowMenu> { self.core_mut().take_window_menu() } + #[inline(always)] + pub(crate) fn titlebar_set(&self) -> crate::titlebar::TitlebarSet { self.core().titlebar_set() } + #[cfg_attr(target_arch = "wasm32", allow(dead_code))] + #[inline(always)] + pub(crate) fn take_titlebar_changed(&mut self) -> bool { self.core_mut().take_titlebar_changed() } + + #[inline(always)] + pub fn popup_menu(&self) -> Option<&PopupMenu> { self.core().popup_menu() } + #[inline(always)] + pub fn resolve_popup(&mut self, picked: Option<&str>) -> Result<(), PopupMenuError> { + let (core, mut app) = self.split_mut(); + core.resolve_popup(&mut app, picked) + } + #[cfg(any(test, target_arch = "wasm32"))] + #[inline(always)] + pub(crate) fn take_popup(&mut self) -> Option<Option<Show>> { self.core_mut().take_popup() } + #[cfg(any(test, target_arch = "wasm32"))] + #[inline(always)] + pub(crate) fn popup_waits_for_layout(&self) -> bool { self.core().popup_waits_for_layout() } + #[inline(always)] + pub(crate) fn cancel_popups(&mut self) { + let (core, mut app) = self.split_mut(); + core.cancel_popups(&mut app); + } + #[inline(always)] + pub(crate) fn open_popup_headless(&mut self) { + let (core, mut app) = self.split_mut(); + core.open_popup_headless(&mut app); + } + + #[inline(always)] + pub fn file_dialog(&self) -> Option<(FileDialogKind, &FileDialogOptions)> { self.core().file_dialog() } + #[inline(always)] + pub fn resolve_file_dialog(&mut self, path: Option<PathBuf>) -> Result<(), FileDialogError> { + self.core_mut().resolve_file_dialog(path) + } + #[cfg(test)] + #[inline(always)] + pub(crate) fn take_file_dialog(&mut self) -> Option<(u64, FileDialogKind, FileDialogOptions)> { + self.core_mut().take_file_dialog() + } + #[cfg(test)] + #[inline(always)] + pub(crate) fn answer_file_dialog(&mut self, id: u64, result: FileDialogResult) { + self.core_mut().answer_file_dialog(id, result); + } + #[inline(always)] + pub(crate) fn refuse_file_dialog(&mut self, why: &str) { self.core_mut().refuse_file_dialog(why); } + #[inline(always)] + pub(crate) fn cancel_file_dialogs(&mut self) { + let (core, mut app) = self.split_mut(); + core.cancel_file_dialogs(&mut app); + } + #[cfg(test)] + #[inline(always)] + pub(crate) fn file_dialog_json(&self) -> Option<serde_json::Value> { self.core().file_dialog_json() } + + #[inline(always)] + pub fn text_selection(&self) -> Option<(&str, std::ops::Range<usize>)> { self.core().text_selection() } + #[inline(always)] + pub fn selected_text(&self) -> Option<String> { + let (core, app) = self.split(); + core.selected_text(&app) + } + #[inline(always)] + pub fn selection(&self) -> Option<TextSelection> { + let (core, app) = self.split(); + core.selection(&app) + } + #[cfg(any(test, target_arch = "wasm32"))] + #[inline(always)] + pub(crate) fn copy_text(&self) -> Option<String> { + let (core, app) = self.split(); + core.copy_text(&app) + } +} diff --git a/app/vendor/rune/crates/rune/src/runtime/input/app_ime.rs b/app/vendor/rune/crates/rune/src/runtime/input/app_ime.rs new file mode 100644 index 0000000..aa3a93a --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/input/app_ime.rs @@ -0,0 +1,91 @@ +//! Input method events for an editor the app draws itself: `App::on_ime` hears them while an +//! `El::ime_cursor` caret has the input method and no text field has focus. +use zeroize::Zeroize; + +use super::*; + +/// What the app's editor was last told the input method shows. +#[derive(Default)] +pub(crate) enum AppComposition { + #[default] + Idle, + Composing(String), +} + +impl AppComposition { + /// Whether an app-level composition is open. + pub(in crate::runtime) fn composing(&self) -> bool { + matches!(self, AppComposition::Composing(_)) + } + + /// Steps the composition with what the app is about to hear. + pub(in crate::runtime) fn step(&mut self, ev: &Ime) { + match ev { + Ime::Preedit(s, ..) => self.replace(if s.is_empty() { AppComposition::Idle } else { AppComposition::Composing(s.clone()) }), + Ime::Commit(_) => self.replace(AppComposition::Idle), + Ime::Select(_) | Ime::Enabled | Ime::Disabled => {} + } + } + + pub(in crate::runtime) fn take_composing(&mut self) -> Option<String> { + match std::mem::take(self) { + AppComposition::Composing(text) => Some(text), + AppComposition::Idle => None, + } + } + + fn replace(&mut self, next: AppComposition) { + if let AppComposition::Composing(old) = self { old.zeroize(); } + *self = next; + } +} + +/// An `El::ime_cursor` element's drawn rect, device pixels, as the window's IME area in points. +pub(in crate::runtime) fn area(r: [f32; 4], s: f32) -> [f32; 4] { + [r[0] / s, r[1] / s, (r[2] - r[0]) / s, (r[3] - r[1]) / s] +} + +impl RuntimeCore { + /// Whether the app's own editor currently holds an open composition. + pub(in crate::runtime) fn app_ime_composing(&self, app: &dyn AppDriver) -> bool { + app.has_on_ime() && self.edit.app_ime_composing() + } + + /// An input method event goes to the focused text field, else to `App::on_ime`. A + /// composition the app has open ends there even after a field took focus, and the input + /// method turning on or off is only the app's to hear. + pub(in crate::runtime) fn run_ime(&mut self, app: &mut dyn AppDriver, ev: Ime, one: &mut Tx) -> bool { + let app_target = self.app_ime_composing(app) || matches!(ev, Ime::Enabled | Ime::Disabled) || self.focused_input().is_none(); + let active = self.composing(app) || matches!(&ev, Ime::Preedit(s, ..) | Ime::Commit(s) if !s.is_empty()); + let ran = if app_target { self.app_ime_event(app, &ev, one) } else { self.with_focused(app, |e| e.ime(&ev), one) }; + // The key that confirmed or cancelled a composition comes back up unheard. + if ran && active { self.kbd.ime_took_key(); } + ran + } + + /// `Runtime::finish_composition`: the focused field's composition becomes its text, or the + /// app's editor hears its last preedit committed. + pub(in crate::runtime) fn finish_ime(&mut self, app: &mut dyn AppDriver, one: &mut Tx) -> bool { + if self.app_ime_composing(app) { + let Some(text) = self.edit.take_app_ime_composing() else { return false }; + return self.app_ime_event(app, &Ime::Commit(text), one); + } + self.finish_field_composition(app, one) + } + + /// The focused field's composition becomes its text, its change handler hearing it, before + /// focus or the caret moves away from it. + pub(in crate::runtime) fn finish_field_composition(&mut self, app: &mut dyn AppDriver, one: &mut Tx) -> bool { + if !self.focused_input().is_some_and(|i| i.access.is_some()) || !self.composing(app) { return false; } + let mut finished = false; + self.with_focused(app, |e| { finished = e.finish_composition(); EditOutcome::default() }, one); + if finished { self.edit.ime_reset = true; } + finished + } + + fn app_ime_event(&mut self, app: &mut dyn AppDriver, ev: &Ime, one: &mut Tx) -> bool { + if !app.has_on_ime() { return false; } + self.edit.step_app_ime(ev); + app.on_ime(ev, one) + } +} diff --git a/app/vendor/rune/crates/rune/src/runtime/input/autoscroll.rs b/app/vendor/rune/crates/rune/src/runtime/input/autoscroll.rs new file mode 100644 index 0000000..aa94da7 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/input/autoscroll.rs @@ -0,0 +1,281 @@ +//! Middle-click autoscroll, as Chromium has it on Windows and Linux (Blink's +//! `AutoscrollController`). A middle press that no element takes (`El::on_middle_press`, a +//! link's `on_link`, `El::pointer_buttons`), over a viewport that can scroll, scrolls toward the +//! pointer: on each axis, the innermost viewport under the press that scrolls on it, at a speed +//! that grows with the pointer's distance from where the press landed: none within [`RADIUS`], +//! then `RATE · d^EXPONENT` points a second (measured on Desktop at a 1x raster: 29 at 20 px, 616 +//! at 80, 4,632 at 200, 11,290 at 300). Released after the pointer has left the radius, it stops; +//! released before, it keeps scrolling until the next press of any button or any key, which it +//! takes and nothing else hears. Wheel scrolls go on as usual meanwhile, and a pointer that leaves +//! the window keeps the speed its last position gave, as Chromium's does. The pointer shows +//! Chromium's pan cursors. A step asks for the next frame only while it moves something, so a +//! pointer resting inside the radius, or a viewport at its end, wakes nothing until it moves. +use crate::machine::{Attempt, Effects, Seq}; +use crate::PointerButton; + +use super::*; + +/// The platforms whose browsers autoscroll on a middle click: Chromium on Windows and Linux. +/// macOS has no such gesture. +pub(in crate::runtime) const ENABLED: bool = cfg!(any(target_os = "windows", target_os = "linux")); +/// Points from where the press landed, per axis, that don't scroll (Blink's +/// `kNoMiddleClickAutoscrollRadius`). +const RADIUS: f32 = 15.0; +/// Speed is `RATE · d^EXPONENT` points a second for a pointer `d` points away on an axis. +const RATE: f32 = 0.04; +const EXPONENT: f32 = 2.2; +/// The longest a step covers, so a late frame doesn't jump. +const MAX_STEP: f64 = 0.05; + +#[derive(Debug, Default)] +pub(in crate::runtime) struct Autoscroll { + seq: Seq, + state: State, +} + +/// The viewports it scrolls: the innermost under the press on each axis (horizontal, vertical). +type Viewports = (Option<NodeId>, Option<NodeId>); + +#[derive(Clone, Copy, Debug, Default, PartialEq)] +enum State { + #[default] + Idle, + /// Scrolling `views` toward the pointer, last seen `at`, from `origin` (window points). + /// `held`: the middle button that started it is still down. `away`: the pointer has left the + /// radius since, so that button's release stops it. `last`: when it last stepped. + /// `attempt`: the step asked for, while one is. + Active { views: Viewports, origin: (f32, f32), at: (f32, f32), held: bool, away: bool, last: f64, attempt: Option<Attempt> }, + /// A press of this button ended it: its release goes nowhere either. + Swallowing(PointerButton), +} + +enum Event { + Down { views: Viewports, origin: (f32, f32), now: f64 }, + Moved { at: (f32, f32), now: f64 }, + /// A frame for the step asked for as `attempt`. + Due { attempt: Attempt, now: f64 }, + /// The step scrolled nothing: the viewports are at their ends that way. + Stuck, + Press(PointerButton), + Release(PointerButton), + Key, + Cancel, +} + +#[derive(Debug, PartialEq)] +enum Effect { + Scroll { views: Viewports, by: (f64, f64) }, + WakeAt(f64), +} + +/// Points a second on one axis for a pointer `d` points from the origin. +fn speed(d: f32) -> f32 { + if d.abs() <= RADIUS { return 0.0; } + RATE * d.abs().powf(EXPONENT) * d.signum() +} + +fn velocity(views: Viewports, origin: (f32, f32), at: (f32, f32)) -> (f32, f32) { + let v = |on: Option<NodeId>, d: f32| if on.is_some() { speed(d) } else { 0.0 }; + (v(views.0, at.0 - origin.0), v(views.1, at.1 - origin.1)) +} + +/// Steps it; true when it took the input. +fn step(seq: &mut Seq, state: &mut State, event: Event) -> (bool, Effects<Effect>) { + match (event, *state) { + (Event::Down { views, origin, now }, State::Idle) => { + *state = State::Active { views, origin, at: origin, held: true, away: false, last: now, attempt: None }; + (true, Effects::none()) + } + (Event::Moved { at, now }, State::Active { views, origin, held, away, last, attempt, .. }) => { + let moving = velocity(views, origin, at) != (0.0, 0.0); + // A pointer back inside the radius stops asking for frames; one that leaves it asks again. + let (attempt, last, effects) = match (moving, attempt) { + (false, _) => (None, last, Effects::none()), + (true, Some(a)) => (Some(a), last, Effects::none()), + (true, None) => (Some(seq.next()), now, Effects::one(Effect::WakeAt(now))), + }; + *state = State::Active { views, origin, at, held, away: away || moving, last, attempt }; + (false, effects) + } + (Event::Due { attempt, now }, State::Active { views, origin, at, held, away, last, attempt: Some(armed) }) if armed == attempt => { + let (vx, vy) = velocity(views, origin, at); + let dt = (now - last).clamp(0.0, MAX_STEP); + *state = State::Active { views, origin, at, held, away, last: now, attempt: Some(seq.next()) }; + let mut effects = Effects::one(Effect::Scroll { views, by: (f64::from(vx) * dt, f64::from(vy) * dt) }); + effects.push(Effect::WakeAt(now)); + (false, effects) + } + (Event::Stuck, State::Active { views, origin, at, held, away, last, .. }) => { + *state = State::Active { views, origin, at, held, away, last, attempt: None }; + (false, Effects::none()) + } + (Event::Release(PointerButton::Middle), State::Active { views, origin, at, held: true, away, last, attempt }) => { + *state = if away { State::Idle } else { State::Active { views, origin, at, held: false, away, last, attempt } }; + (true, Effects::none()) + } + (Event::Press(button), State::Active { .. }) => { + *state = State::Swallowing(button); + (true, Effects::none()) + } + (Event::Release(button), State::Swallowing(held)) if button == held => { + *state = State::Idle; + (true, Effects::none()) + } + (Event::Key, State::Active { .. }) => { + *state = State::Idle; + (true, Effects::none()) + } + (Event::Cancel, _) => { + *state = State::Idle; + (false, Effects::none()) + } + _ => (false, Effects::none()), + } +} + +impl capture::PointerState { + fn autoscroll_step(&mut self, event: Event) -> (bool, Effects<Effect>) { + let a = &mut self.autoscroll; + step(&mut a.seq, &mut a.state, event) + } + + /// Starts autoscrolling `views` from `origin`. + #[inline] + pub(super) fn autoscroll_start(&mut self, views: Viewports, origin: (f32, f32), now: f64) -> bool { + self.autoscroll_step(Event::Down { views, origin, now }).0 + } + + /// A press of `button` while it runs: it ends, and the press goes nowhere. True when it took + /// the press. + #[inline] + pub(super) fn autoscroll_press(&mut self, button: PointerButton) -> bool { + self.autoscroll_step(Event::Press(button)).0 + } + + /// A release of `button`: the middle button that started it (which stops it once the pointer + /// has left the radius), or the press that ended it. True when it took the release. + #[inline] + pub(super) fn autoscroll_release(&mut self, button: PointerButton) -> bool { + self.autoscroll_step(Event::Release(button)).0 + } + + /// A key went down while it runs: it ends, and the key goes nowhere. True when it took it. + #[inline] + pub(super) fn autoscroll_key(&mut self) -> bool { + self.autoscroll_step(Event::Key).0 + } + + /// Updates pointer position while autoscrolling; returns a wake deadline when armed. + #[inline] + pub(super) fn autoscroll_moved(&mut self, at: (f32, f32), now: f64) -> Option<f64> { + if !matches!(self.autoscroll.state, State::Active { .. }) { return None; } + let (_, effects) = self.autoscroll_step(Event::Moved { at, now }); + effects.into_iter().find_map(|e| match e { + Effect::WakeAt(due) => Some(due), + Effect::Scroll { .. } => None, + }) + } + + /// The window lost its focus or the pointer's capture. + #[inline] + pub(super) fn autoscroll_cancel(&mut self) { + let _ = self.autoscroll_step(Event::Cancel); + } + + /// The pan cursor while it runs: which way it scrolls, or the axes it can. + #[inline] + pub(in crate::runtime) fn autoscroll_cursor(&self) -> Option<crate::el::Cursor> { + let State::Active { views, origin, at, .. } = self.autoscroll.state else { return None }; + let v = velocity(views, origin, self.pos.unwrap_or(at)); + Some(crate::el::Cursor::Image(crate::cursor::pan((views.0.is_some(), views.1.is_some()), v))) + } + + fn autoscroll_due(&mut self, has_viewport: impl Fn(NodeId) -> bool, now: f64) -> Effects<Effect> { + let State::Active { views, attempt: Some(attempt), .. } = self.autoscroll.state else { return Effects::none() }; + // The viewports went: nothing to scroll. + if [views.0, views.1].into_iter().flatten().all(|id| !has_viewport(id)) { + self.autoscroll_cancel(); + return Effects::none(); + } + self.autoscroll_step(Event::Due { attempt, now }).1 + } + + fn autoscroll_stuck(&mut self) { + let _ = self.autoscroll_step(Event::Stuck); + } +} + +impl RuntimeCore { + /// A middle press at (x, y) that no element took: autoscroll the viewports there, if one can + /// scroll. True when it started. + pub(in crate::runtime) fn autoscroll_down(&mut self, x: f32, y: f32) -> bool { + if !ENABLED { return false; } + let views = (self.scroll_at_axis(x, y, true), self.scroll_at_axis(x, y, false)); + if views == (None, None) { return false; } + let now = self.now_clock(); + self.pointer.autoscroll_start(views, (x, y), now) + } + + pub(in crate::runtime) fn autoscroll_moved(&mut self, x: f32, y: f32) { + if !matches!(self.pointer.autoscroll.state, State::Active { .. }) { return; } + let now = self.now_clock(); + if let Some(due) = self.pointer.autoscroll_moved((x, y), now) { + self.wake_at(due); + } + } + + /// Takes the step due by this frame. + pub(in crate::runtime) fn fire_autoscroll(&mut self) { + let effects = self.pointer.autoscroll_due(|id| self.scroll.scrolls.contains_key(&id), self.clock); + for effect in effects { + match effect { + // A step of no length (the first, in the frame of the move that armed it) moves + // nothing and says nothing about the ends. + Effect::Scroll { views, by } => { + if by != (0.0, 0.0) && !self.autoscroll_by(views, by) { + self.pointer.autoscroll_stuck(); + } + } + Effect::WakeAt(due) => self.wake_at(due), + } + } + } + + /// The pan cursor while it runs: which way it scrolls, or the axes it can. + #[inline] + pub(in crate::runtime) fn autoscroll_cursor(&self) -> Option<crate::el::Cursor> { + self.pointer.autoscroll_cursor() + } + + /// Scrolls `views` by `by` (horizontal, vertical) points, as the wheel does. True when one + /// moved. + fn autoscroll_by(&mut self, views: Viewports, by: (f64, f64)) -> bool { + let mut moved = false; + if let Some(id) = views.0 + && let Some(st) = self.scroll.scrolls.get_mut(&id) + { + let before = st.x.offset; + st.x.offset = (st.x.offset + st.x.toward(by.0)).clamp(0.0, st.x.max); + st.x.motion = XMotion::Rest; + st.moved(); + if st.x.offset != before { + moved = true; + self.pointer.scroll_cancels_press(&self.tree.nodes, id); + } + } + if let Some(id) = views.1 { + let stick = self.tree.node_index.get(&id).and_then(|&i| self.tree.nodes[i].scroll).is_some_and(|s| s.stick_bottom); + if let Some(st) = self.scroll.scrolls.get_mut(&id) { + let before = st.offset; + st.offset = (st.offset + by.1).clamp(0.0, st.max); + st.moved(); + st.land(stick && by.1 >= 0.0); + if st.offset != before { + moved = true; + self.pointer.scroll_cancels_press(&self.tree.nodes, id); + } + } + } + moved + } +} diff --git a/app/vendor/rune/crates/rune/src/runtime/input/capture.rs b/app/vendor/rune/crates/rune/src/runtime/input/capture.rs new file mode 100644 index 0000000..8e3b59f --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/input/capture.rs @@ -0,0 +1,412 @@ +//! The pointer's hold on an element: the primary (or an extra) button's press from down to up, +//! and the secondary button's beside it. A held press keeps what only it has (where and when it +//! went down, whether it's still inside its element or a scroll cancelled it, whether it +//! travelled past the click slop, whether it's the second of a double press, an armed OS drag, +//! the link it began on), +//! so none of it outlives the release. Between presses only the first click of a possible +//! double press is kept. The input routes in `pointer.rs`, `gesture.rs`, `secondary.rs` and +//! `selection/click.rs` drive it. +use rune_motion::NodeId; + +use crate::PointerButton; +use crate::el::Drag; +use crate::runtime::types::Node; + +/// Where a held press stands against its element: a browser's `:active` while it's inside. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum Hit { + Inside, + /// The pointer moved off the element; back on, it's inside again. + Outside, + /// A scroll under the press let go of it ([`Runtime::scroll_cancels_press`]): the release + /// presses nothing, wherever the pointer is. + Cancelled, +} + +/// The first click of a possible double press: the element, its down time and point. +#[derive(Clone, Debug, PartialEq)] +pub(crate) struct FirstClick { + pub(crate) path: String, + pub(crate) at: f64, + pub(crate) point: (f32, f32), +} + +/// A press the pointer holds on element `path`. +#[derive(Clone, Debug)] +pub(crate) struct Held { + pub(crate) path: String, + /// The `Phase::Down` its drags carry on from. + pub(crate) drag: Drag, + pub(crate) button: PointerButton, + /// Where (window points) and when (`now_clock`) it went down. + pub(crate) at: (f32, f32), + pub(crate) down_at: f64, + pub(crate) hit: Hit, + /// It travelled past the click slop: it isn't a click of a double press. + pub(crate) moved: bool, + /// It's the second press of a double press. + pub(crate) second: bool, + /// It's on a `drag_out` element and hasn't crossed this threshold (points) yet. + pub(crate) drag_out: Option<f32>, + /// The pointer left the window while it held; the leave lands on release. + pub(crate) left: bool, + /// The link of its text it began on: a release on the same link activates it. + pub(crate) link: Option<usize>, + /// It ran its element's `on_press` as it went down (`El::press_on_down`): its release + /// runs nothing. + pub(crate) pressed_on_down: bool, + pub(crate) touch: bool, +} + +impl Held { + /// A press that just went down at `at`, inside its element and still. + pub(crate) fn new(path: String, drag: Drag, button: PointerButton, at: (f32, f32), down_at: f64, second: bool, drag_out: Option<f32>) -> Self { + Self { path, drag, button, at, down_at, hit: Hit::Inside, moved: false, second, drag_out, left: false, link: None, pressed_on_down: false, touch: false } + } + + pub(crate) fn inside(&self) -> bool { self.hit == Hit::Inside } + + /// Began on link `link` of its text. + pub(crate) fn on_link(self, link: Option<usize>) -> Self { Self { link, ..self } } + + /// Ran its element's `on_press` as it went down. + pub(crate) fn pressed_on_down(self, pressed_on_down: bool) -> Self { Self { pressed_on_down, ..self } } +} + +#[derive(Clone, Debug)] +pub(crate) enum Press { + Up { first: Option<FirstClick> }, + Held(Box<Held>), +} + +impl Default for Press { + fn default() -> Self { Self::Up { first: None } } +} + +impl Press { + pub(crate) fn held(&self) -> Option<&Held> { + match self { + Self::Held(h) => Some(h), + Self::Up { .. } => None, + } + } + + pub(crate) fn held_mut(&mut self) -> Option<&mut Held> { + match self { + Self::Held(h) => Some(h), + Self::Up { .. } => None, + } + } + + pub(crate) fn path(&self) -> Option<&str> { self.held().map(|h| h.path.as_str()) } + + pub(crate) fn is_held(&self) -> bool { matches!(self, Self::Held(_)) } + + /// Held, and inside its element. + pub(crate) fn inside(&self) -> bool { self.held().is_some_and(Held::inside) } + + /// Lets go of a held press without a click to pair: a cancel, a drag-out taking the pointer, + /// a modal opening. Returns it. + pub(crate) fn drop_held(&mut self) -> Option<Box<Held>> { + match std::mem::take(self) { + Self::Held(h) => Some(h), + up => { + *self = up; + None + } + } + } + + /// The release: back up, with `first` the click a next press may pair with. Returns the + /// press that was held. + pub(crate) fn release(&mut self, first: Option<FirstClick>) -> Option<Box<Held>> { + let held = self.drop_held()?; + *self = Self::Up { first }; + Some(held) + } + + /// A new press takes the place of whatever came before: the first click it may pair with. + pub(crate) fn take_first(&mut self) -> Option<FirstClick> { + match self { + Self::Up { first } => first.take(), + Self::Held(_) => None, + } + } + + pub(crate) fn hold(&mut self, held: Held) { *self = Self::Held(Box::new(held)); } +} + +/// The secondary button's hold: the element whose menu it opens on release, the link of its +/// text it began on (`on_link_secondary`), and whether the pointer left the window meanwhile. +#[derive(Clone, Debug, Default, PartialEq)] +pub(crate) enum Secondary { + #[default] + Up, + Held { path: String, link: Option<usize>, left: bool }, +} + +/// The middle or secondary button held where the primary isn't: the element it shows pressed +/// ([`El::press`](crate::El::press)) while the pointer is over it, as a browser sets `:active` +/// for a press of any button. It's the element a primary press there would take; it hears +/// nothing, and the release lets go of it. +#[derive(Clone, Debug, Default, PartialEq)] +pub(crate) enum Tint { + #[default] + Up, + Held { path: String, button: PointerButton }, +} + +impl Tint { + pub(crate) fn path(&self) -> Option<&str> { + match self { + Self::Held { path, .. } => Some(path), + Self::Up => None, + } + } + + /// `button` came up: it lets go if it's the one holding. + pub(crate) fn release(&mut self, button: PointerButton) { + if matches!(self, Self::Held { button: b, .. } if *b == button) { *self = Self::Up; } + } +} + +impl Secondary { + pub(crate) fn path(&self) -> Option<&str> { + match self { + Self::Held { path, .. } => Some(path), + Self::Up => None, + } + } + + pub(crate) fn is_held(&self) -> bool { matches!(self, Self::Held { .. }) } +} + +/// Pointer position, button capture, hover/tooltip tracking, touch, autoscroll, file drops and OS +/// drag-out sessions owned by [`crate::runtime::RuntimeCore`]. Ordered hot-first under +/// `#[repr(C)]` so pointer position, press capture and hover state sit together at offset 0. +#[repr(C)] +pub(in crate::runtime) struct PointerState { + pub(in crate::runtime) pos: Option<(f32, f32)>, + /// A press or blur stopped the waits to report an enter; the pointer's next move restarts them. + pub(in crate::runtime) hover_paused: bool, + /// The host starts OS drags, so `drag_out` elements start one (headless tools act as one). + pub(in crate::runtime) os_drag: bool, + pub(in crate::runtime) hovered: Option<String>, + /// Elements with `on_hover_change` that the pointer is inside. + pub(in crate::runtime) hover_within: Vec<String>, + /// Hover waiting out layout motion under a still pointer. + pub(super) hover_hold: crate::runtime::hover::HoverHold, + /// The press the pointer holds, or the click a next press may pair with + /// (`runtime/input/capture.rs`). + pub(super) press: Press, + /// The secondary button's press, held beside it. + secondary: Secondary, + /// The middle or secondary button's pressed look (`capture::Tint`). + tint: Tint, + /// Elements with `hover_delays`: which heard the enter, and which wait out a delay. + pub(in crate::runtime) hover_delays: crate::runtime::hover_delay::HoverDelays, + /// `on_hover_change` handlers of elements that left the tree, owed their queued leave. + hover_gone: Vec<(String, crate::el::WindowFocusFn)>, + /// The presses counted into `Drag::clicks`. + press_clicks: crate::runtime::press_run::PressRun, + /// The held press's drag repeat (`Tx::drag_repeat_after`). + pub(super) press_repeat: crate::runtime::press_repeat::PressRepeat, + drag_data: f32, + /// The middle button's autoscroll (`runtime/input/autoscroll.rs`). + pub(super) autoscroll: crate::runtime::autoscroll::Autoscroll, + /// The finger that is down and the viewport a touch holds (`runtime/input/touch.rs`). + pub(super) touch: crate::runtime::touch_input::Touch, + /// `El::help` tooltips. + pub(super) help: crate::runtime::help::HelpState, + /// Files dragged over the window from another app (`drop_dispatch`). + pub(super) file_drag: crate::runtime::drop_dispatch::FileDrag, + pub(in crate::runtime) drag_out_request: Option<crate::drag_out::DragOutStart>, + /// How OS drags ended, filled by the host's session callbacks between frames. + pub(in crate::runtime) drag_ends: crate::drag_out::DragEnds, + /// Drag-outs whose `on_drag_start` ran and whose `on_drag_end` hasn't yet. + pub(in crate::runtime) drags_open: usize, +} + +impl PointerState { + // Single-caller constructor for `RuntimeCore::new`; inlined so it stays in its caller's + // codegen unit instead of shifting partitioning and dropping inlining in the paint walk. + #[inline] + pub(in crate::runtime) fn new() -> Self { + Self { + pos: None, + press: Default::default(), + secondary: Default::default(), + tint: Default::default(), + press_clicks: Default::default(), + press_repeat: Default::default(), + drag_data: 0.0, + autoscroll: Default::default(), + touch: Default::default(), + hovered: None, + hover_within: Vec::new(), + hover_gone: Vec::new(), + hover_delays: Default::default(), + hover_paused: false, + hover_hold: Default::default(), + help: Default::default(), + file_drag: Default::default(), + os_drag: true, + drag_out_request: None, + drag_ends: Default::default(), + drags_open: 0, + } + } + + #[inline] + pub(in crate::runtime) fn pos(&self) -> Option<(f32, f32)> { self.pos } + + /// A press on an element is held (the hand drives whatever follows it). + #[inline] + pub(in crate::runtime) fn pressing(&self) -> bool { self.press.is_held() } + + /// A button holds the pointer: the OS keeps sending its moves to this window, and a leave + /// waits for the release. + #[inline] + pub(in crate::runtime) fn captured(&self) -> bool { + self.press.is_held() || self.secondary.is_held() || self.tint.path().is_some() + } + + #[inline] + pub(super) fn captured_path(&self) -> Option<&str> { + self.press.path().or(self.secondary.path()) + } + + #[inline] + pub(in crate::runtime) fn press_inside(&self) -> bool { self.press.inside() } + + #[inline] + pub(in crate::runtime) fn press_held(&self) -> Option<&Held> { self.press.held() } + + #[inline] + pub(in crate::runtime) fn hold_press(&mut self, held: Held) { self.press.hold(held); } + + /// The pointer left the window (`true`) or came back (`false`) while a press holds it. + #[inline] + pub(super) fn set_left(&mut self, out: bool) { + if let Some(held) = self.press.held_mut() { held.left = out; } + if let Secondary::Held { left, .. } = &mut self.secondary { *left = out; } + } + + /// The host moved its window by `(dx, dy)` points under a still pointer. + #[inline] + pub(in crate::runtime) fn window_moved(&mut self, dx: f32, dy: f32) { + if let Some((x, y)) = self.pos { self.pos = Some((x - dx, y - dy)); } + if let Some(held) = self.press.held_mut() { held.at = (held.at.0 - dx, held.at.1 - dy); } + } + + /// The button is up, so the held press can no longer start a drag-out; it stays a press. + #[cfg_attr(not(target_os = "macos"), allow(dead_code))] + #[inline] + pub(in crate::runtime) fn disarm_drag_out(&mut self) { + if let Some(held) = self.press.held_mut() { held.drag_out = None; } + } + + #[cfg(all(test, target_os = "macos"))] + #[inline] + pub(in crate::runtime) fn end_click_run(&mut self) { + self.press_clicks.clear(); + self.press.take_first(); + } + + #[inline] + pub(super) fn drag_data(&self) -> f32 { self.drag_data } + + #[inline] + pub(super) fn set_drag_data(&mut self, data: f32) { self.drag_data = data; } + + #[inline] + pub(super) fn tint_path(&self) -> Option<&str> { self.tint.path() } + + #[inline] + pub(super) fn set_tint(&mut self, tint: Tint) { self.tint = tint; } + + #[inline] + pub(super) fn release_tint(&mut self, button: PointerButton) { self.tint.release(button); } + + #[inline] + pub(super) fn clear_tint(&mut self) { self.tint = Tint::Up; } + + #[inline] + pub(super) fn press_click(&mut self, path: &str, now: f64, at: (f32, f32), interval: f64) -> u32 { + self.press_clicks.press(path, now, at, interval) + } + + #[inline] + pub(super) fn clear_press_clicks(&mut self) { self.press_clicks.clear(); } + + #[inline] + pub(super) fn push_hover_gone(&mut self, path: String, f: crate::el::WindowFocusFn) { + self.hover_gone.push((path, f)); + } + + #[inline] + pub(super) fn take_hover_gone(&mut self, path: &str) -> Option<crate::el::WindowFocusFn> { + self.hover_gone.iter().position(|g| g.0 == path).map(|i| self.hover_gone.remove(i).1) + } + + #[inline] + pub(super) fn secondary_held(&self) -> bool { self.secondary.is_held() } + + #[cfg_attr(not(target_arch = "wasm32"), allow(dead_code))] + #[inline] + pub(super) fn secondary(&self) -> &Secondary { &self.secondary } + + #[inline] + pub(super) fn set_secondary(&mut self, secondary: Secondary) { self.secondary = secondary; } + + #[inline] + pub(super) fn clear_secondary(&mut self) { self.secondary = Secondary::Up; } + + #[inline] + pub(super) fn take_secondary(&mut self) -> Secondary { std::mem::take(&mut self.secondary) } + + /// Drops transient pointer, hover, click-run and drop-target state when a playground stage + /// swaps views. + pub(in crate::runtime) fn clear_for_stage(&mut self) { + self.press = Press::default(); + self.secondary = Secondary::Up; + self.hovered = None; + self.hover_gone.clear(); + self.hover_within.clear(); + self.hover_delays.clear(); + self.forget_drop_targets(); + self.press_clicks.clear(); + } + + /// Scrolling viewport `id` under a held press inside it cancels the press, as a UIScrollView + /// cancels its content's touches: the row lets go and the release doesn't press. A drag + /// keeps its capture. + pub(in crate::runtime) fn scroll_cancels_press(&mut self, nodes: &[Node], id: NodeId) { + let Some(path) = self.press.path() else { return }; + let Some(i) = nodes.iter().position(|n| n.path == path) else { return }; + let inside = std::iter::successors(nodes[i].parent, |&p| nodes[p].parent).any(|p| nodes[p].id == id); + if inside && nodes[i].handlers.on_drag.is_none() { + if let Some(held) = self.press.held_mut() { + held.hit = Hit::Cancelled; + held.second = false; + } + } + } + + #[inline] + pub(in crate::runtime) fn touch_scroll_mut(&mut self) -> &mut Option<crate::runtime::scroll_touch::TouchScroll> { + &mut self.touch.scroll + } + + #[cfg(test)] + #[inline] + pub(in crate::runtime) fn touch_scroll(&self) -> Option<crate::runtime::scroll_touch::TouchScroll> { + self.touch.scroll + } + + #[cfg(test)] + #[inline] + pub(in crate::runtime) fn hover_hold(&self) -> &crate::runtime::hover::HoverHold { + &self.hover_hold + } +} diff --git a/app/vendor/rune/crates/rune/src/runtime/input/drop.rs b/app/vendor/rune/crates/rune/src/runtime/input/drop.rs new file mode 100644 index 0000000..cc6ac02 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/input/drop.rs @@ -0,0 +1,307 @@ +//! Files dragged onto a window from another app: `El::on_drop_files`, `El::accepts_files`, +//! `El::on_drop_hover`, `El::on_drop_move`, `El::on_drop_rejected` and +//! `El::on_drop_rejected_hover`. +use super::*; +use crate::el::{DropHoverFn, PointerEvent}; +use crate::el::drop::DropMoveFn; +use std::path::PathBuf; + +/// One step of a file drag over the window, queued for the next frame. +pub(crate) enum FileEvent { + /// The drag entered or moved. A position the platform can't give is `None`. + Hover(Vec<PathBuf>, Option<(f32, f32)>), + /// The drag moved over a target that follows it (`El::on_drop_move`); it runs as a hover + /// at the drag's latest point. + Move, + Drop(Vec<PathBuf>, Option<(f32, f32)>), + Leave, +} + +#[derive(Default)] +pub(crate) struct FileDrag { + /// The drag over the window (set when its step is queued, before it runs). + over: Option<Over>, + /// The drop target notified with `on_drop_hover(true)` (or, rejecting the drag, + /// `on_drop_rejected_hover(true)`), and that callback, which still hears `false` after the + /// element unmounts or starts to exit. + hovered: Option<(Aim, Option<DropHoverFn>)>, + /// File steps waiting for this frame's build (`hold_files`), and whether those leading the + /// queue already waited one. + held: Vec<Queued>, + waited: bool, +} + +/// A file drag over the window. +struct Over { + /// The files it carries, for `drag_files_to`. + paths: Vec<PathBuf>, + /// Where it is now, in window points, when the platform says. + at: Option<(f32, f32)>, + /// The target of the last hover queued or run, so a move that keeps it queues nothing. + aimed: Option<Aim>, + /// A `FileEvent::Move` waits to run. + move_queued: bool, +} + +/// A drop target's path, and whether it takes any of the dragged files (else it stops the drag +/// to reject it). +type Aim = (String, bool); + +/// Where a drag or drop lands: the target, the files it takes and the rest. +struct Target { + i: usize, + files: Vec<PathBuf>, + rejected: Vec<PathBuf>, +} + +impl capture::PointerState { + /// A file drag is over the window. + #[inline] + pub(in crate::runtime) fn dragging_files(&self) -> bool { self.file_drag.over.is_some() } + + /// File steps wait for the next frame (`hold_files`). + #[inline] + pub(in crate::runtime) fn files_held(&self) -> bool { self.file_drag.waited } + + /// Drops the drag's target and the hover callback it would hear `false` on, unheard: their + /// elements went with the state they were built for. + #[inline] + pub(in crate::runtime) fn forget_drop_targets(&mut self) { + if let Some(over) = &mut self.file_drag.over { over.aimed = None; } + self.file_drag.hovered = None; + } + + pub(super) fn drop_hover_key<'a>(&self, node: impl Fn(&str) -> Option<&'a Node>, accepted: bool) -> Option<String> { + let ((path, _), _) = self.file_drag.hovered.as_ref().filter(|((_, a), _)| *a == accepted)?; + Some(node(path).and_then(|n| n.key.clone()).unwrap_or_else(|| path.clone())) + } + + /// Holds file steps for this frame's build when the tree changed since its last build. + pub(in crate::runtime) fn hold_files(&mut self, queue: ActionQueue, stale: bool) -> ActionQueue { + let waited = std::mem::take(&mut self.file_drag.waited); + let aims = |a: &Action| matches!(a, Action::Files(FileEvent::Hover(..) | FileEvent::Move | FileEvent::Drop(..))); + if waited || !stale || !queue.iter().any(aims) { return queue; } + let (files, rest): (_, Vec<_>) = queue.into_iter().partition(|q| matches!(q.action, Action::Files(_))); + self.file_drag.held = files; + rest.into_iter().collect() + } + + #[inline] + pub(super) fn take_held_files(&mut self) -> Option<Vec<Queued>> { + if self.file_drag.held.is_empty() { return None; } + self.file_drag.waited = true; + Some(std::mem::take(&mut self.file_drag.held)) + } +} + +impl RuntimeCore { + /// A file drag from another app entered the window or moved over it, carrying `paths`; `at` + /// is its position in points, or `None` when the platform doesn't say. The innermost + /// [`El::on_drop_files`] under it that accepts the files hears `on_drop_hover(true)` next + /// frame. + pub fn drag_files(&mut self, paths: Vec<PathBuf>, at: Option<(f32, f32)>) { + // A move a lost frame never ran mustn't keep this drag's moves from queueing. + let aimed = self.drop_aim(&paths, at); + self.pointer.file_drag.over = Some(Over { paths: paths.clone(), at, aimed, move_queued: false }); + self.frame.queue.push(Action::Files(FileEvent::Hover(paths, at))); + } + + /// The file drag is at `at`, with the files it entered with. Queues a hover, and returns + /// true, only when that changes the drop target or moves the drag over a target that + /// follows it (`El::on_drop_move`, once a frame), so a host can sample the pointer often and + /// redraw only when something listens. Sampling while still also notices a target that + /// unmounted. + pub fn drag_files_to(&mut self, at: Option<(f32, f32)>) -> bool { + let Some(over) = &self.pointer.file_drag.over else { return false }; + let moved = over.at != at; + let target = self.drop_aim(&over.paths, at); + let same = target == over.aimed; + let follows = same && target.as_ref().is_some_and(|aim| self.drop_move_fn(aim).is_some()); + let Some(over) = &mut self.pointer.file_drag.over else { return false }; + over.at = at; + if same { + if !moved || !follows || std::mem::replace(&mut over.move_queued, true) { return false; } + self.frame.queue.push(Action::Files(FileEvent::Move)); + return true; + } + over.aimed = target; + let paths = over.paths.clone(); + self.frame.queue.push(Action::Files(FileEvent::Hover(paths, at))); + true + } + + /// The file drag left the window, was cancelled, or the window hid. + pub fn drag_files_leave(&mut self) { + if self.pointer.file_drag.over.take().is_none() { return; } + self.frame.queue.push(Action::Files(FileEvent::Leave)); + } + + /// `paths` dropped at `at` (points, or `None` when the platform doesn't say). Next frame the + /// innermost [`El::on_drop_files`] under it that accepts any of them gets those it accepts, + /// in one call, and the drop hover ends. Its [`El::on_drop_rejected`] gets the rest, and a + /// target with one that takes none of them gets them all there. A drop nothing takes is + /// ignored. + pub fn drop_files(&mut self, paths: Vec<PathBuf>, at: Option<(f32, f32)>) { + self.pointer.file_drag.over = None; + self.frame.queue.push(Action::Files(FileEvent::Drop(paths, at))); + } + + /// A file drag is over the window. Hosts whose platform reports no drag positions sample + /// the pointer while this holds. + #[inline] + pub fn dragging_files(&self) -> bool { self.pointer.dragging_files() } + + /// The key (else path) of the element showing the drop hover, for tests and tools. + pub fn drop_hovered(&self) -> Option<String> { self.pointer.drop_hover_key(|p| self.node(p), true) } + + /// The key (else path) of the element showing the rejected drop hover + /// ([`El::on_drop_rejected_hover`]), for tests and tools. + pub fn drop_rejected_hovered(&self) -> Option<String> { self.pointer.drop_hover_key(|p| self.node(p), false) } + + /// A file step that hit-tests (a hover or drop) reaching a tree changed since its last build + /// (`stale`: state changed this frame, or while the window was covered and built nothing) + /// waits for this frame's build, once, so it lands on what is mounted and laid out now. The + /// file steps after it wait too, to keep their order. + #[inline] + pub(in crate::runtime) fn hold_files(&mut self, queue: ActionQueue, stale: bool) -> ActionQueue { + self.pointer.hold_files(queue, stale) + } + + /// The held file steps go first next frame. + pub(in crate::runtime) fn release_files(&mut self) { + if let Some(held) = self.pointer.take_held_files() { + self.frame.queue.prepend(held); + } + } + + /// File steps wait for the next frame (`hold_files`). + #[inline] + pub(in crate::runtime) fn files_held(&self) -> bool { self.pointer.files_held() } + + #[inline] + pub(in crate::runtime) fn clear_drop_hits(&mut self) { self.hit.clear_drop_hits(); } + + /// The target for `paths` at `at` and the files it takes: walking out from the topmost + /// element under the point, the first drop target that accepts any of them or rejects + /// what it doesn't take (`El::on_drop_rejected`), then the root. + /// While a modal is open its root stands in for the window's, and a point outside it + /// reaches nothing, as a drop on the dimmed window behind a sheet does. A point outside the + /// window reaches nothing; a drop without a position goes to the root. + fn drop_target(&self, paths: &[PathBuf], at: Option<(f32, f32)>) -> Option<Target> { + let ok = |id: NodeId| self.tree.node_index.get(&id).copied() + .filter(|&i| i < self.tree.nodes.len() && !self.subtree_exiting(i) && self.allowed(i)); + let start = match at { + None => None, + Some((x, y)) if !self.in_viewport(x, y) => return None, + Some((x, y)) => { + let top = self.hit.top_drop_or_hit(|id, r| self.hit_contains(id, r, x, y), ok); + if top.is_none() && self.active_modal().is_some() { return None; } + top + } + }; + let root = self.active_modal().unwrap_or_else(|| self.app_root()); + std::iter::successors(start, |&i| self.tree.nodes[i].parent) + .chain(std::iter::once(root).filter(|&r| r < self.tree.nodes.len())) + .filter(|&i| self.allowed(i) && !self.subtree_exiting(i)) + .find_map(|i| { + let drop = self.tree.nodes[i].handlers.drop.as_ref()?; + let (files, rejected) = drop.split(paths); + (!files.is_empty() || (!rejected.is_empty() && drop.claims_rejects())).then_some(Target { i, files, rejected }) + }) + } + + fn drop_aim(&self, paths: &[PathBuf], at: Option<(f32, f32)>) -> Option<Aim> { + self.drop_target(paths, at).map(|t| (self.tree.nodes[t.i].path.clone(), !t.files.is_empty())) + } + + fn drop_hover_fn(&self, (path, accepted): &Aim) -> Option<DropHoverFn> { + self.node(path).and_then(|n| n.handlers.drop.as_ref()?.hover_fn(*accepted)) + } + + /// The `El::on_drop_move` of a target that takes the drag. + fn drop_move_fn(&self, (path, accepted): &Aim) -> Option<DropMoveFn> { + self.node(path).filter(|_| *accepted).and_then(|n| n.handlers.drop.as_ref()?.on_move.clone()) + } + + /// `at` on the mounted element `path`, for `Tx::drop_point`. + fn drop_point(&self, path: &str, at: Option<(f32, f32)>) -> Option<PointerEvent> { + let (x, y) = at?; + let i = self.live_index(path)?; + let [lx, ly] = self.to_local(i, x, y); + Some(PointerEvent { x: lx, y: ly, window_x: x, window_y: y }) + } + + /// A hover at `at`: moves the drop hover to the target there, then tells a target that + /// follows the drag where it is. + fn hover_files(&mut self, app: &mut dyn AppDriver, paths: &[PathBuf], at: Option<(f32, f32)>, tx: &mut Tx) -> bool { + let target = self.drop_aim(paths, at); + if let Some(over) = &mut self.pointer.file_drag.over { over.aimed.clone_from(&target); } + let mut ran = self.set_drop_hover(app, target.clone(), at, tx); + if let Some(aim) = target && let Some(f) = self.drop_move_fn(&aim) && let Some(p) = self.drop_point(&aim.0, at) { + self.trace_event(format_args!("drop-move:{}", aim.0)); + tx.drop_point = Some(p); + f(app.states(), p, tx); + tx.drop_point = None; + ran = true; + } + ran + } + + /// Moves the drop hover to `target`, notifying the old and new elements. + fn set_drop_hover(&mut self, app: &mut dyn AppDriver, target: Option<Aim>, at: Option<(f32, f32)>, tx: &mut Tx) -> bool { + if self.pointer.file_drag.hovered.as_ref().map(|(aim, _)| aim) == target.as_ref() { return false; } + let old = self.pointer.file_drag.hovered.take(); + let new = target.map(|aim| { + let f = self.drop_hover_fn(&aim); + (aim, f) + }); + self.pointer.file_drag.hovered.clone_from(&new); + let mut ran = false; + for (hover, over) in [(old, false), (new, true)] { + let Some((aim, kept)) = hover else { continue }; + // The element's current callback, else the one it had if it has gone. + let Some(f) = self.drop_hover_fn(&aim).or(kept) else { continue }; + let (path, accepted) = &aim; + let kind = if *accepted { "drop-hover" } else { "drop-rejected-hover" }; + self.trace_event(format_args!("{kind}:{over}:{path}")); + tx.drop_point = if over { self.drop_point(path, at) } else { None }; + f(app.states(), over, tx); + tx.drop_point = None; + ran = true; + } + ran + } + + pub(in crate::runtime) fn run_files(&mut self, app: &mut dyn AppDriver, event: FileEvent, tx: &mut Tx) -> bool { + match event { + FileEvent::Hover(paths, at) => self.hover_files(app, &paths, at, tx), + FileEvent::Move => { + let Some(over) = &mut self.pointer.file_drag.over else { return false }; + over.move_queued = false; + let (paths, at) = (over.paths.clone(), over.at); + self.hover_files(app, &paths, at, tx) + } + FileEvent::Leave => self.set_drop_hover(app, None, None, tx), + FileEvent::Drop(paths, at) => { + let target = self.drop_target(&paths, at); + let mut ran = self.set_drop_hover(app, None, None, tx); + let Some(Target { i, files, rejected }) = target else { return ran }; + let Some(drop) = self.tree.nodes[i].handlers.drop.as_deref().cloned() else { return ran }; + let path = self.tree.nodes[i].path.clone(); + tx.drop_point = self.drop_point(&path, at); + if !files.is_empty() && let Some(f) = drop.on_drop { + self.trace_event(format_args!("drop-files:{}:{path}", files.len())); + f(app.states(), &files, tx); + ran = true; + } + if !rejected.is_empty() && let Some(f) = drop.on_reject { + self.trace_event(format_args!("drop-rejected:{}:{path}", rejected.len())); + f(app.states(), &rejected, tx); + ran = true; + } + tx.drop_point = None; + ran + } + } + } +} diff --git a/app/vendor/rune/crates/rune/src/runtime/input/field_menu.rs b/app/vendor/rune/crates/rune/src/runtime/input/field_menu.rs new file mode 100644 index 0000000..68cf7e3 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/input/field_menu.rs @@ -0,0 +1,176 @@ +//! A text field's own menu (right-click, macOS control-click, the Menu key and Shift+F10), as a +//! browser's menu over an editable field: a misspelled word's suggestions and Learn Spelling, +//! then Cut, Copy, Paste and, off macOS, Select All, then the app's Spellcheck setting +//! (`El::on_spellcheck`) and, where there are dictionaries to choose, its Spellcheck Languages +//! (`El::on_spellcheck_languages`). A field with its own `on_secondary_press` shows that instead. +//! The items read the app's names for them (`rune::set_labels`) each time the menu opens. +use super::input_click::hit; +use super::*; +use crate::labels::label; +use crate::popup_menu::{PopupAnchor, Request}; +use crate::{Key, Label, Mods, PopupItem, PopupMenu}; + +/// What a field menu's items act on once one is picked. +pub(crate) struct FieldMenu { + path: String, + /// The misspelled word the menu offers suggestions for: its byte range and text. + word: Option<(usize, usize, String)>, + suggestions: Vec<String>, + toggle: Option<(bool, crate::el::WindowFocusFn)>, + /// The dictionaries checking text when the menu opened, and what keeps a new choice. + languages: Option<(Vec<String>, crate::el::LanguagesFn)>, +} + +impl RuntimeCore { + /// Opens field `path`'s menu at window point `at`, pressed at window point `hit_at`, or from + /// the keyboard (`None`). + pub(in crate::runtime) fn field_menu(&mut self, app: &mut dyn AppDriver, path: String, at: (f32, f32), hit_at: Option<(f32, f32)>, one: &mut Tx) -> bool { + let Some(i) = self.live(&path) else { return false }; + let Some(input) = self.tree.nodes[i].input.as_deref() else { return false }; + if let (Some(f), Some((hx, hy))) = (input.on_pill_secondary.clone(), hit_at) + && let Some(pill_id) = self.input_pill_at(i, hx, hy) + && f(app.states(), &pill_id, crate::PointerPress { x: at.0, y: at.1 }, one) + { + return true; + } + let Some(access) = input.access.clone() else { return false }; + let (single, secure) = (input.single_line, input.edit.is_secure()); + let spell = input.spellcheck && !secure; + let layout = self.tree.nodes[i].text_layout.clone(); + let point = hit_at.and_then(|(x, y)| self.input_text_point(i, x, y)); + let s = self.env.scale; + let toggle = std::iter::successors(Some(i), |&j| self.tree.nodes[j].parent).find_map(|j| self.tree.nodes[j].handlers.on_spellcheck.clone()); + let keep = std::iter::successors(Some(i), |&j| self.tree.nodes[j].parent).find_map(|j| self.tree.nodes[j].handlers.on_spellcheck_languages.clone()); + if self.kbd.focus.path() != Some(path.as_str()) { + self.set_focus(app, Some(path.clone()), false); + } + let e = access(app.states()); + e.set_single_line(single); + if let (Some([tx, ty]), Some(l)) = (point, layout.as_ref().map(TextLayout::view)) + && e.preedit().is_none() + { + let caret = hit(e, l, tx, ty, s, single).caret; + let (a, b) = e.range(); + // A press in the selection keeps it for Cut and Copy. Elsewhere it moves the caret + // there, and on a misspelled word selects the word, as Chromium does. + if a == b || caret < a || caret > b { + match spell.then(|| crate::spell::misspelled_at(&e.text, caret)).flatten() { + Some((wa, wb)) => e.set_selection(wa, wb), + None => e.set_caret(caret), + } + } + } + let (a, b) = e.range(); + let word = spell + .then(|| crate::spell::misspelled(&e.text, None)) + .filter(|found| found.contains(&(a, b))) + .map(|_| (a, b, e.text[a..b].to_owned())); + let suggestions = word.as_ref().map(|w| crate::spell::suggest(&w.2)).unwrap_or_default(); + let mut menu = PopupMenu::new(); + if word.is_some() { + if suggestions.is_empty() { + menu = menu.item(PopupItem::new("no-guesses", label(Label::NoGuesses)).enabled(false)); + } + menu = menu.items(suggestions.iter().enumerate().map(|(n, s)| PopupItem::new(format!("suggestion-{n}"), s.clone()))); + menu = menu.separator().item(PopupItem::new("learn-spelling", label(Label::LearnSpelling))).separator(); + } + let selected = a != b && !secure; + menu = menu + .item(PopupItem::new("cut", label(Label::Cut)).enabled(selected)) + .item(PopupItem::new("copy", label(Label::Copy)).enabled(selected)) + .item(PopupItem::new("paste", label(Label::Paste))); + if !cfg!(target_os = "macos") { + menu = menu.item(PopupItem::new("select-all", label(Label::SelectAll))); + } + let mut languages = None; + if let Some((on, _)) = &toggle { + menu = menu.separator().item(PopupItem::new("spellcheck", label(Label::Spellcheck)).checked(*on)); + // Desktop's dictionary picker (spellcheck.ts), where the platform has dictionaries + // to choose: the last one stays, as the Spellcheck item is how to stop checking. + let available = crate::spell::available_languages(); + if let Some(keep) = keep.filter(|_| !available.is_empty()) { + let current = crate::spell::languages(); + let only = |tag: &String| current.len() == 1 && current[0] == *tag; + // Named in the app's language, in the order of those names, as Desktop's + // `nativeLanguageOptions` sorts its `Intl.DisplayNames`. + let locale = crate::labels::locale(); + let name = |tag: &str| { + crate::labels::named(Label::Language(tag)) + .or_else(|| locale.as_deref().and_then(|locale| crate::spell::language_name_in(tag, locale))) + .unwrap_or_else(|| crate::spell::language_name(tag)) + }; + let mut named: Vec<(String, &String)> = available.iter().map(|tag| (name(tag), tag)).collect(); + crate::spell::sort_names_in(&mut named, locale.as_deref().unwrap_or("en")); + let items = named.into_iter().map(|(name, tag)| { + PopupItem::new(format!("language-{tag}"), name).checked(current.contains(tag)).enabled(!only(tag)) + }); + menu = menu.submenu_enabled(label(Label::SpellcheckLanguages), PopupMenu::new().items(items), *on); + languages = Some((current, keep)); + } + } + one.commit = one.commit.instant(); + log_event!(self, "field menu {path}"); + self.host.popups.push_back(Request { + menu, + anchor: PopupAnchor::Point(at.0, at.1), + on_pick: Box::new(|_, _, _| {}), + field: Some(Box::new(FieldMenu { path, word, suggestions, toggle, languages })), + }); + true + } + + /// Does what `picked` in field menu `menu` asks, on its field. + pub(in crate::runtime) fn field_menu_pick(&mut self, app: &mut dyn AppDriver, menu: FieldMenu, picked: &str, one: &mut Tx) { + if self.kbd.focus.path() != Some(menu.path.as_str()) && self.live(&menu.path).is_some() { + self.set_focus(app, Some(menu.path.clone()), false); + } + let command = |c| KeyEvent { key: Key::Command(c), mods: Mods { cmd: true, ctrl: !cfg!(target_os = "macos"), ..Mods::default() } }; + match picked { + "cut" | "copy" | "select-all" => { + let ev = command(match picked { + "cut" => 'x', + "copy" => 'c', + _ => 'a', + }); + let layout = self.focused_layout(); + self.with_focused(app, |e| e.key_in(&ev, layout.as_ref().map(TextLayout::view)), one); + } + "paste" => one.request_paste(), + "learn-spelling" => { + if let Some((_, _, word)) = &menu.word { + crate::spell::learn(word); + self.commit.dirty = true; + } + } + "spellcheck" => { + if let Some((on, f)) = menu.toggle { + f(app.states(), !on, one); + } + } + id if id.starts_with("language-") => { + if let (Some((mut current, keep)), Some(tag)) = (menu.languages, id.strip_prefix("language-")) { + match current.iter().position(|t| t == tag) { + Some(n) => _ = current.remove(n), + None => current.push(tag.to_owned()), + } + crate::spell::set_languages(&current); + keep(app.states(), current, one); + self.commit.dirty = true; + } + } + id => { + let n = id.strip_prefix("suggestion-").and_then(|n| n.parse::<usize>().ok()); + if let (Some((a, b, _)), Some(suggestion)) = (menu.word, n.and_then(|n| menu.suggestions.get(n).cloned())) { + self.with_focused( + app, + |e| { + e.set_selection(a, b); + e.paste(&suggestion) + }, + one, + ); + } + } + } + } +} diff --git a/app/vendor/rune/crates/rune/src/runtime/input/file_dialog.rs b/app/vendor/rune/crates/rune/src/runtime/input/file_dialog.rs new file mode 100644 index 0000000..1d2e00e --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/input/file_dialog.rs @@ -0,0 +1,98 @@ +use super::*; +use crate::file_dialog::{DialogState, FileDialogError, FileDialogKind, FileDialogOptions, FileDialogResult, Pending, Request}; + +impl RuntimeCore { + /// The file dialog showing, or about to show, from [`Tx::open_file`], [`Tx::save_file`] or + /// [`Tx::open_folder`]. + pub fn file_dialog(&self) -> Option<(FileDialogKind, &FileDialogOptions)> { + self.host.file_dialog.pending().map(|d| (d.kind, &d.options)) + } + + /// Answers the file dialog showing as if the user chose `path`, or cancelled with `None`. + /// Its callback runs on the next frame. For tests and headless drivers; native dialogs + /// answer themselves. + pub fn resolve_file_dialog(&mut self, path: Option<std::path::PathBuf>) -> Result<(), FileDialogError> { + let id = self.host.file_dialog.pending().ok_or_else(|| FileDialogError("no file dialog is open".into()))?.id; + self.answer_file_dialog(id, Ok(path)); + Ok(()) + } + + /// Takes a handler's request. One dialog at a time: a request while one is open is + /// answered with an error rather than queued, so a double click opens one dialog. + pub(crate) fn request_file_dialog(&mut self, request: Request) { + self.host.next_file_dialog += 1; + let id = self.host.next_file_dialog; + self.host.file_dialog_answers.push((id, request.on_answer)); + if self.host.native_overlay { + self.trace_event("file-dialog:overlay"); + self.frame.queue.push(Action::FileDialog(id, Err(FileDialogError("overlays cannot open file dialogs".into())))); + return; + } + if self.host.file_dialog.is_open() { + self.trace_event("file-dialog:busy"); + self.frame.queue.push(Action::FileDialog(id, Err(FileDialogError("a file dialog is already open".into())))); + return; + } + self.trace_event(format_args!("file-dialog:open:{:?}", request.kind)); + self.host.file_dialog = DialogState::Requested(Pending { id, kind: request.kind, options: request.options }); + } + + /// The dialog for the host to show, marked shown. Nothing while it shows. + pub(crate) fn take_file_dialog(&mut self) -> Option<(u64, FileDialogKind, FileDialogOptions)> { + let d = self.host.file_dialog.show()?; + Some((d.id, d.kind, d.options.clone())) + } + + /// Queues dialog `id`'s answer for the next frame, closing it. + pub(crate) fn answer_file_dialog(&mut self, id: u64, result: FileDialogResult) { + self.host.file_dialog.answered(id); + self.frame.queue.push(Action::FileDialog(id, result)); + } + + /// Answers a dialog this host can't show with `why`. + pub(crate) fn refuse_file_dialog(&mut self, why: &str) { + if let Some((id, ..)) = self.take_file_dialog() { + self.answer_file_dialog(id, Err(FileDialogError(why.into()))); + } + } + + pub(in crate::runtime) fn run_file_dialog(&mut self, app: &mut dyn AppDriver, id: u64, result: FileDialogResult, one: &mut Tx) -> bool { + let Some(i) = self.host.file_dialog_answers.iter().position(|(dialog, _)| *dialog == id) else { return false }; + let (_, f) = self.host.file_dialog_answers.remove(i); + self.trace_event(format_args!( + "file-dialog:answer:{}", + if result.as_ref().is_ok_and(Option::is_some) { "path" } else if result.is_ok() { "cancel" } else { "error" } + )); + f(app.states(), result, one); + true + } + + /// Answers the open or waiting dialog with `Ok(None)`, and runs any queued file dialog + /// callbacks now while the window's state is still alive. A callback that asks for another + /// dialog is answered too, up to a bound against one that always asks again. + pub(crate) fn cancel_file_dialogs(&mut self, app: &mut dyn AppDriver) { + for _ in 0..64 { + if let Some(d) = self.host.file_dialog.take() { + self.frame.queue.push(Action::FileDialog(d.id, Ok(None))); + } + let Some(pos) = self.frame.queue.iter().position(|a| matches!(a, Action::FileDialog(..))) else { return }; + let Action::FileDialog(id, result) = self.frame.queue.remove(pos) else { unreachable!() }; + let mut one = self.transaction(app); + self.run_file_dialog(app, id, result, &mut one); + self.latch_requests(app, &mut one); + merge(&mut self.frame.pending, one); + self.commit.dirty = true; + } + eprintln!( + "rune: file dialog callbacks kept asking for dialogs while their window went away; dropping {}", + self.host.file_dialog_answers.len() + ); + self.host.file_dialog = DialogState::Closed; + self.host.file_dialog_answers.clear(); + self.frame.queue.retain(|a| !matches!(a, Action::FileDialog(..))); + } + + pub(crate) fn file_dialog_json(&self) -> Option<serde_json::Value> { + self.host.file_dialog.pending().map(Pending::to_json) + } +} diff --git a/app/vendor/rune/crates/rune/src/runtime/input/focus.rs b/app/vendor/rune/crates/rune/src/runtime/input/focus.rs new file mode 100644 index 0000000..76b0cd8 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/input/focus.rs @@ -0,0 +1,884 @@ +//! Focus is keyed retained state. Platform AX can read the same flags as the inspector. +use super::*; +use crate::edit::Key; + +/// Groups whose items stack vertically: only Up and Down move between them. +const VERTICAL_ROLES: [&str; 4] = ["menu", "listbox", "list", "tree"]; +/// Groups that move to the item whose label the user types. +const TYPE_SELECT_ROLES: [&str; 5] = ["menu", "listbox", "list", "tree", "tablist"]; +/// Without Full Keyboard Access, Tab still visits lists inside these groups. +const LIST_ROLES: [&str; 4] = ["listbox", "list", "tree", "grid"]; +/// Groups where Page Up and Page Down move by the items their scroll view shows; elsewhere the +/// keys page the scroll view itself. +const PAGED_ROLES: [&str; 2] = ["menu", "listbox"]; +/// Tables and outlines stop at their ends (NSTableView); menus, popups and segments wrap. +const CLAMPED_ROLES: [&str; 3] = ["list", "tree", "grid"]; +/// Roles whose pressable elements are Tab stops under `Cx::web_focus`, as HTML's buttons, +/// links and form controls are, and the items of trees and grids, which a reader moves through +/// by arrows once their group has focus (`El::focus_group` keeps the group one Tab stop). +/// Roles F6 cycles between, as a browser's and Windows' pane navigation does. +const LANDMARK_ROLES: [&str; 6] = ["banner", "navigation", "main", "complementary", "form", "search"]; +const PRESSABLE_ROLES: [&str; 9] = ["button", "link", "tab", "checkbox", "switch", "radio", "combobox", "treeitem", "gridcell"]; +/// The innermost open modal and the nodes input may reach while it shows: its subtree, the +/// popovers anchored inside it, and the window's caption buttons. +pub(in crate::runtime) struct ModalScope { + index: usize, + members: Vec<bool>, +} + +/// Whether node `i` in `nodes` is not inert and has positive opacity along its ancestor chain. +fn node_visible(nodes: &[Node], i: usize) -> bool { + let n = &nodes[i]; + !n.inert && n.vis.opacity > 0.0 + && std::iter::successors(n.parent, |&p| nodes[p].parent).all(|p| !nodes[p].inert && nodes[p].vis.opacity > 0.0) +} + +/// Whether node `i` in `nodes` has a non-zero laid-out box. +fn node_sized(nodes: &[Node], i: usize) -> bool { + nodes[i].local.w > 0.0 && nodes[i].local.h > 0.0 +} + +/// Whether node `i` in `nodes` is visible and has a non-zero laid-out box. +fn node_shown(nodes: &[Node], i: usize) -> bool { + node_sized(nodes, i) && node_visible(nodes, i) +} + +/// Whether `ev` navigates (Tab, an arrow, Home, End, Page Up or Page Down, unmodified but for +/// Shift), which shows focus from then on, as CSS `:focus-visible` after keyboard navigation. +/// Other keys keep whatever showed: Space on a clicked button, Escape, or typing shows no ring. +/// Type-select shows it when it moves focus. +pub(in crate::runtime) fn navigates(ev: &KeyEvent) -> bool { + !(ev.mods.cmd || ev.mods.ctrl || ev.mods.alt || ev.mods.logo) + && matches!(ev.key, Key::Tab | Key::Up | Key::Down | Key::Left | Key::Right | Key::Home | Key::End | Key::PageUp | Key::PageDown) +} + +/// Pushes focus (and a secure flag) into an input's app-owned editor and mirrors it back. +fn sync_input_focus(input: &mut crate::el::InputSpec, states: crate::states::States<'_>, focused: bool) -> bool { + let Some(access) = &input.access else { + input.edit.focused = focused; + return false; + }; + let edit = access(states); + let mut changed = false; + edit.set_single_line(input.single_line); + if input.edit.is_secure() && !edit.is_secure() { + edit.set_secure(true); + changed = true; + } + if let Some(revealed) = input.revealed_override + && edit.is_revealed() != revealed + { + edit.set_revealed(revealed); + changed = true; + } + if edit.focused != focused || (!focused && edit.is_composing()) { + edit.focused = focused; + if !focused { edit.cancel_composition(); } + edit.break_history_group(); + changed = true; + } + // Into the copy's own buffer: a long draft's field is copied without a new allocation, and + // without wiping the old one. + let mut text = std::mem::take(&mut input.edit.text); + let kept = std::mem::take(&mut edit.text); + input.edit = edit.clone(); + edit.text = kept; + text.clone_from(&edit.text); + input.edit.text = text; + changed +} + +/// Whether node `i` in `nodes` is a landmark F6 cycles between. +fn is_landmark(nodes: &[Node], i: usize) -> bool { + let n = &nodes[i]; + LANDMARK_ROLES.contains(&n.role) || (n.role == "region" && n.label.as_deref().is_some_and(|l| !l.trim().is_empty())) +} + +/// Node `j` is node `i` or inside it. +fn path_inside(nodes: &[Node], j: usize, i: usize) -> bool { + let (p, root) = (nodes[j].path.as_str(), nodes[i].path.as_str()); + p == root || root.is_empty() || (p.len() > root.len() && p.starts_with(root) && p.as_bytes()[root.len()] == b'/') +} + +/// The innermost landmark around node `i`, for F6 to come back to what had focus in it. +fn landmark_of(nodes: &[Node], mut i: usize) -> Option<usize> { + loop { + if is_landmark(nodes, i) { return Some(i); } + i = nodes[i].parent?; + } +} + +impl ModalScope { + fn build(nodes: &[Node], is_exiting: impl Fn(usize) -> bool, is_unmounted: impl Fn(usize) -> bool) -> Option<Self> { + let index = nodes.iter().enumerate().rev() + .find(|(i, n)| n.handlers.get().is_some_and(|h| h.modal.is_some()) && !is_exiting(*i) && !is_unmounted(*i)).map(|(i, _)| i)?; + // The Windows caption buttons are the window's, not the view's: a modal in the view + // leaves them to the pointer and assistive technology, as the native ones are. + let caption = |n: &Node| n.key.as_deref() == Some(crate::titlebar::BUTTONS_KEY) + && n.parent.is_some_and(|p| nodes[p].key.as_deref() == Some(crate::titlebar::FRAME_KEY)); + let mut members: Vec<bool> = nodes.iter().enumerate().map(|(i, n)| i >= index || caption(n)).collect(); + // Portals are root siblings. Follow their anchor ownership, including chained + // popovers, rather than requiring their layout parent to be the modal. + loop { + let mut changed = false; + for (i, n) in nodes.iter().enumerate() { + if members[i] || is_exiting(i) { continue; } + let parent_inside = n.parent.is_some_and(|p| members[p]); + let anchor_inside = n.above.as_ref().is_some_and(|a| nodes.iter().enumerate() + .any(|(j, anchor)| anchor.key.as_deref() == Some(&a.key) && members[j])); + if parent_inside || anchor_inside { members[i] = true; changed = true; } + } + if !changed { break; } + } + Some(Self { index, members }) + } +} + +impl focus_machine::KeyboardState { + #[inline] + pub(in crate::runtime) fn active_modal(&self) -> Option<usize> { + self.modal_scope.as_ref().map(|m| m.index) + } + + /// Node `i` (its subtree ending before `end`) holds the open modal. + #[inline] + pub(in crate::runtime) fn modal_ancestor(&self, i: usize, end: usize) -> bool { + self.modal_scope.as_ref().is_some_and(|m| m.index > i && m.index < end) + } + + /// Node `i` is inside the open modal's scope, or no modal is open. + #[inline] + pub(in crate::runtime) fn modal_member(&self, i: usize) -> bool { + self.modal_scope.as_ref().is_none_or(|m| m.members.get(i).copied().unwrap_or(false)) + } + + /// Input may reach node `i`: it's outside any `El::inert` subtree and not behind a modal. + #[inline] + pub(in crate::runtime) fn allowed(&self, nodes: &[Node], i: usize) -> bool { + !nodes.get(i).is_some_and(|n| n.inert) && self.modal_member(i) + } + + #[inline] + pub(super) fn set_modal_scope(&mut self, scope: Option<ModalScope>) { + self.modal_scope = scope; + } + + pub(super) fn record_unmounted_focused( + &mut self, + old_nodes: &[Node], + new_nodes: &[Node], + virtual_inputs: &HashMap<String, Box<InputSpec>>, + ) { + for old in old_nodes { + if let Some(input) = &old.input + && input.edit.focused + && !new_nodes.iter().any(|n| n.path == old.path || n.input.as_ref().is_some_and(|i| i.edit.same_model(&input.edit))) + && !virtual_inputs.values().any(|i| i.edit.same_model(&input.edit)) + && !self.unmounted_focused.iter().any(|w| input.edit.matches_history(w)) + { + self.unmounted_focused.push(input.edit.weak_history()); + } + } + } + + #[inline] + pub(super) fn was_unmounted_focused(&self, edit: &crate::edit::TextEdit) -> bool { + self.unmounted_focused.iter().any(|w| edit.matches_history(w)) + } + + pub(super) fn prune_unmounted_focused( + &mut self, + new_nodes: &[Node], + virtual_inputs: &HashMap<String, Box<InputSpec>>, + ) { + self.unmounted_focused.retain(|w| { + w.strong_count() > 0 + && !new_nodes.iter().any(|n| n.input.as_ref().is_some_and(|i| i.edit.matches_history(w))) + && !virtual_inputs.values().any(|i| i.edit.matches_history(w)) + }); + } + + /// Type-select: the typed prefix picks the first item whose label starts with it. A + /// repeated letter cycles the items starting with it. The prefix resets after a pause. + pub(super) fn type_select(&mut self, nodes: &[Node], items: &[usize], pos: usize, typed: &str, now: f64) -> Option<usize> { + let buffer = self.type_select_typed(typed, now).to_owned(); + let label = |j: usize| nodes[items[j]].label.as_deref().unwrap_or("").to_lowercase(); + let first = buffer.chars().next()?; + let cycle = buffer.chars().all(|c| c == first); + let order = (0..items.len()).map(|k| if cycle { (pos + 1 + k) % items.len() } else { k }); + let prefix = if cycle { first.to_string() } else { buffer.clone() }; + order.into_iter().find(|&j| label(j).starts_with(&prefix)) + } +} + +impl RuntimeCore { + #[inline] + pub(crate) fn active_modal(&self) -> Option<usize> { + self.kbd.active_modal() + } + /// Node `i` (its subtree ending before `end`) holds the open modal. + #[inline] + pub(crate) fn modal_ancestor(&self, i: usize, end: usize) -> bool { + self.kbd.modal_ancestor(i, end) + } + /// Node `i` is inside the open modal's scope, or no modal is open. + #[inline] + pub(crate) fn modal_member(&self, i: usize) -> bool { + self.kbd.modal_member(i) + } + pub(in crate::runtime) fn refresh_modal_index(&mut self) { + let scope = ModalScope::build(&self.tree.nodes, |i| self.subtree_exiting(i), |i| self.subtree_unmounted(i)); + self.kbd.set_modal_scope(scope); + } + /// Input may reach node `i`: it's outside any `El::inert` subtree and not behind a modal. + #[inline] + pub(crate) fn allowed(&self, i: usize) -> bool { + self.kbd.allowed(&self.tree.nodes, i) + } + /// `El::focusable`, or under `Cx::web_focus` a pressable control that didn't opt out. + pub(crate) fn takes_focus(&self, n: &Node) -> bool { + n.focus.enabled || (self.commit.defaults.web_focus && !n.focus.opt_out && n.handlers.on_press.is_some() && PRESSABLE_ROLES.contains(&n.role)) + } + /// Whether `n` can take keyboard focus itself or is an editable text field. + fn can_take_focus(&self, n: &Node) -> bool { + self.takes_focus(n) || n.input.as_ref().is_some_and(|s| s.access.is_some()) + } + pub(crate) fn can_focus(&self, i: usize) -> bool { + self.can_take_focus(&self.tree.nodes[i]) && self.reachable(i) + } + /// Shown, sized, not exiting and not behind a modal. + fn reachable(&self, i: usize) -> bool { + self.allowed(i) && !self.subtree_exiting(i) && node_shown(&self.tree.nodes, i) + } + /// Whether Return goes to focused element `i` rather than the default button: a focused + /// link, a `focus_highlight` row, or an item of a menu, list, tree or grid group. + /// Under `Cx::web_focus` a focused button presses on Return too, as an HTML one does. + fn takes_return(&self, i: usize) -> bool { + self.edit.link_focused(&self.tree.nodes[i]) || self.tree.nodes[i].focus.highlight.is_some() + || (self.commit.defaults.web_focus && self.tree.nodes[i].handlers.on_press.is_some() && self.takes_focus(&self.tree.nodes[i])) + || self.focus_group(i).is_some_and(|g| LIST_ROLES.contains(&self.tree.nodes[g].role) || VERTICAL_ROLES.contains(&self.tree.nodes[g].role)) + } + /// Return with no modifiers presses the window's default button (`El::default_button`) + /// unless the focused element takes Return itself. Text fields decide in `with_focused`. + pub(in crate::runtime) fn default_button_key(&mut self, app: &mut dyn AppDriver, ev: &KeyEvent, tx: &mut Tx) -> bool { + if ev.key != Key::Enter || ev.mods != crate::Mods::default() { return false; } + if self.focused_input().is_some() || self.focused_index().is_some_and(|i| self.takes_return(i)) { return false; } + self.press_default_button(app, tx) + } + /// Presses the default button, if one is in reach; a held Return presses it once. + pub(in crate::runtime) fn press_default_button(&mut self, app: &mut dyn AppDriver, tx: &mut Tx) -> bool { + let Some(i) = (0..self.tree.nodes.len()).rev() + .find(|&i| self.tree.nodes[i].focus.default && self.tree.nodes[i].handlers.on_press.is_some() && self.reachable(i)) + else { return false }; + if tx.key_repeat { return true; } + let f = self.tree.nodes[i].handlers.on_press.clone().unwrap(); + log_event!(self, "default {}", self.tree.nodes[i].path); + f(app.states(), tx); + true + } + /// In `nodes` (a tree being committed), whether node `j` is a Tab stop: in the Tab order + /// (`El::tab_index` not negative) and not an item of a roving focus group, whatever it can take + /// now (a control just disabled still was one). + fn tab_stop_in(&self, nodes: &[Node], j: usize) -> bool { + if nodes[j].focus.order < 0 { return false; } + let mut p = nodes[j].parent; + while let Some(i) = p { + if nodes[i].focus.group { return false; } + if self.takes_focus(&nodes[i]) { return true; } + p = nodes[i].parent; + } + true + } + /// In `nodes`, the focus group `j` is an item of, as [`Self::focus_group`] finds it in the + /// committed tree. + fn group_in(&self, nodes: &[Node], j: usize) -> Option<usize> { + let mut p = nodes[j].parent; + while let Some(i) = p { + if nodes[i].focus.group { return Some(i); } + if self.takes_focus(&nodes[i]) { return None; } + p = nodes[i].parent; + } + None + } + /// In `nodes`, the nearest roving focus group around `j`: the one it is an item of, or the one + /// whose item holds it (a tab's Close button is in its tab strip's group). + fn roving_home_in(&self, nodes: &[Node], j: usize) -> Option<usize> { + let mut p = nodes[j].parent; + while let Some(i) = p { + if nodes[i].focus.group { return Some(i); } + p = nodes[i].parent; + } + None + } + /// The focus group `i` is an item of. A control inside an item (a tab's close button) is + /// no item: it's a Tab stop of its own, as an HTML button inside a roving `tablist` is. + pub(crate) fn focus_group(&self, i: usize) -> Option<usize> { + let mut p = self.tree.nodes[i].parent; + while let Some(i) = p { + if self.tree.nodes[i].focus.group { return Some(i); } + if self.takes_focus(&self.tree.nodes[i]) { return None; } + p = self.tree.nodes[i].parent; + } + None + } + /// The `focus_highlight` row that `i` (a pointer target) belongs to. + pub(in crate::runtime) fn highlight_row(&self, mut i: usize) -> Option<usize> { + loop { + let n = &self.tree.nodes[i]; + if self.takes_focus(n) { return (n.focus.highlight.is_some() && self.can_focus(i)).then_some(i); } + i = n.parent?; + } + } + #[inline] + pub(in crate::runtime) fn highlight_visible(&self, i: usize) -> bool { + self.kbd.highlight_visible(&self.tree.nodes, i) + } + /// Focus is on node `i` or inside it (CSS `:focus-within`), however it got there. + #[inline] + pub(in crate::runtime) fn focus_within(&self, i: usize) -> bool { + self.kbd.focus_within(&self.tree.nodes, i) + } + pub(in crate::runtime) fn focus_ring_visible(&self, mut i: usize) -> bool { + // `Cx::force_focus_rings`: the ring of whichever control owns node `i`. + if self.commit.defaults.force_focus_rings { + loop { + if self.can_focus(i) { return true; } + let Some(p) = self.tree.nodes[i].parent else { return false }; + i = p; + } + } + if !self.kbd.focus.keyboard() { return false; } + loop { + if self.kbd.focus.is(&self.tree.nodes[i].path) { return true; } + // A nested focusable owns its ring, never inherit another control's focus. + if self.takes_focus(&self.tree.nodes[i]) { return false; } + let Some(p) = self.tree.nodes[i].parent else { return false }; + i = p; + } + } + /// The focused element that draws the default ring, if any (see `El::no_focus_ring`). + pub(in crate::runtime) fn default_ring_owner(&self) -> Option<usize> { + if !self.kbd.focus.keyboard() { return None; } + let i = self.focused_index()?; + let n = &self.tree.nodes[i]; + // A focused link shows its focus with its own hover look. + // A modal that holds focus itself (`Cx::web_focus`) shows none, as a web dialog doesn't. + if n.input.is_some() || n.focus.highlight.is_some() || self.edit.link_focused(n) || !self.can_focus(i) { return None; } + if self.focus_group(i).is_some_and(|g| LIST_ROLES.contains(&self.tree.nodes[g].role) || VERTICAL_ROLES.contains(&self.tree.nodes[g].role)) { + return None; + } + let own = self.tree.nodes.iter().enumerate() + .any(|(j, m)| (m.focus.ring.is_some() || m.focus.ring_off) && self.focus_ring_visible(j)); + (!own).then_some(i) + } + /// Under `Cx::force_focus_rings`, whether node `i` draws the default ring: a control that + /// can take focus and would draw it when focused (see [`Self::default_ring_owner`]), with no + /// ring of its own on it or on a part of it. + pub(in crate::runtime) fn forced_default_ring(&self, i: usize) -> bool { + if !self.commit.defaults.force_focus_rings || !self.can_focus(i) { return false; } + let n = &self.tree.nodes[i]; + if n.input.is_some() || n.focus.highlight.is_some() || links::link_count(n) > 0 { return false; } + if self.focus_group(i).is_some_and(|g| LIST_ROLES.contains(&self.tree.nodes[g].role) || VERTICAL_ROLES.contains(&self.tree.nodes[g].role)) { + return false; + } + // A part's own ring belongs to its nearest focusable ancestor-or-self. + !self.tree.nodes.iter().enumerate().any(|(j, m)| (m.focus.ring.is_some() || m.focus.ring_off) && self.owner_of(j) == Some(i)) + } + /// The nearest node at or above `j` that can take focus. + fn owner_of(&self, mut j: usize) -> Option<usize> { + loop { + if self.can_focus(j) { return Some(j); } + j = self.tree.nodes[j].parent?; + } + } + /// The view's `Cx::focus_ring`, else AppKit's: 3 points just outside the border box. + pub(in crate::runtime) fn default_focus_ring(&self) -> crate::el::Outline { + self.commit.defaults.focus_ring + .unwrap_or(crate::el::Outline { width: 3.0, offset: 0.0, color: self.host.system_accent.focus(self.env.system_dark) }) + } + pub(crate) fn set_focus(&mut self, app: &mut dyn AppDriver, path: Option<String>, keyboard: bool) -> bool { + self.set_focus_entry(app, path, keyboard, false) + } + fn set_focus_entry(&mut self, app: &mut dyn AppDriver, path: Option<String>, keyboard: bool, keep_entry: bool) -> bool { + self.edit.input_click.on_focus_change(path.as_deref()); + let moved = self.kbd.focus.path() != path.as_deref(); + // A field left mid-composition keeps what it showed, as a browser's does (Tab the input + // method let through, a click on another control, `Tx::focus`). + if moved && self.focused_input().is_some() && self.composing(app) { + let mut tx = self.transaction(app); + self.finish_field_composition(app, &mut tx); + self.latch_requests(app, &mut tx); + merge(&mut self.frame.pending, tx); + } + // Tabbing away or into a field takes the selection's keyboard; a hovered row doesn't. + if moved + && let Some(p) = path.as_deref() + && self.text_selection().is_some_and(|(held, _)| held != p) + && (keyboard || self.node(p).is_some_and(|n| n.input.is_some()) || self.commit.virtual_inputs.contains_key(p)) + { + self.clear_text_selection(); + } + let mut changed = moved && self.physical_focus_lost(app); + for n in &mut self.tree.nodes { + if let Some(input) = &mut n.input { + changed |= sync_input_focus(input, app.states(), path.as_deref() == Some(n.path.as_str())); + } + } + for (p, input) in &mut self.commit.virtual_inputs { + changed |= sync_input_focus(input, app.states(), path.as_deref() == Some(p.as_str())); + } + let shown = (self.kbd.focus.keyboard(), self.kbd.focus.shown()); + for effect in self.kbd.focus.step(focus_machine::FocusEvent::Set { path, keyboard, keep_entry }) { + match effect { + focus_machine::FocusEffect::Moved => { + self.ime_area = None; + self.edit.ime_reset = true; + self.edit.blur_links(); + } + } + } + if let Some((mark, at)) = self.focused_index().and_then(|f| landmark_of(&self.tree.nodes, f).map(|m| (m, f))) { + let (mark, at) = (self.tree.nodes[mark].path.clone(), self.tree.nodes[at].path.clone()); + self.kbd.focus.remember_scope(mark, at); + } + self.sync_side_focus(app); + // A hover group keyboard focus enters or leaves hovers or rests now (`El::hover_group`). + // Focus that stayed where it was, shown as it was (every commit's focus pass, most of + // the time), moves no group: the frame's own interaction pass sees the rest. + let regrouped = moved || shown != (self.kbd.focus.keyboard(), self.kbd.focus.shown()); + if regrouped && self.tree.nodes.iter().any(|n| n.vis_flags.hover_group()) { + changed |= self.update_interaction(None); + } + changed + } + pub(in crate::runtime) fn sync_requested_focus(&mut self, app: &mut dyn AppDriver, nodes: &mut Vec<Node>) -> bool { + // A `Tx::focus_when_shown` still owed stands until the user's own input or another ask, + // whatever focus did meanwhile (a closing palette leaves it nowhere, then on the prompt). + let owed = self.kbd.focus_owed.take().map(|(key, ring)| (key, ring, crate::el::FocusAsk::WhenShown)); + let asked = self.kbd.focus_request.take().or(owed); + let waits = asked.as_ref().filter(|(.., ask)| *ask == crate::el::FocusAsk::WhenShown).map(|(key, ring, _)| (key.clone(), *ring)); + self.kbd.record_unmounted_focused(&self.tree.nodes, nodes, &self.commit.virtual_inputs); + let within = |path: &str, root: &str| { + path == root || (path.len() > root.len() && path.starts_with(root) && path.as_bytes()[root.len()] == b'/') + }; + let shown = |idx: usize| node_shown(nodes, idx); + let restore = self.tree.nodes.iter().enumerate().rev().find_map(|(i, old)| { + let key = old.focus.return_to.as_deref()?; + if self.subtree_exiting(i) || nodes.iter().any(|n| n.path == old.path) { return None; } + let focused = self.kbd.focus.now_or_blurred()?; + let has_children = self.tree.nodes.iter().any(|m| m.parent == Some(i)); + let scope = if !has_children && !self.takes_focus(old) && old.input.is_none() + && old.local.w == 0.0 && old.local.h == 0.0 { + let p = self.tree.nodes.get(old.parent?)?; + if p.is_moved_stub() || p.path.is_empty() { + nodes.get(*self.tree.node_index.get(&p.id)?)?.path.as_str() + } else { + p.path.as_str() + } + } else { + old.path.as_str() + }; + if !within(focused, scope) { return None; } + let anchor = nodes.iter().find(|n| n.key.as_deref() == Some(key))?; + let candidates = (0..nodes.len()).filter(|&j| within(&nodes[j].path, &anchor.path) && shown(j) + && self.can_take_focus(&nodes[j])); + candidates.clone().find(|&j| nodes[j].focus.selected) + .or_else(|| candidates.into_iter().next()) + .map(|j| nodes[j].path.clone()) + }); + // `Tx::focus`: the first shown element with the key, or its first focusable child. + let asked = asked.and_then(|(key, ring, ask)| { + let anchor = (0..nodes.len()).find(|&j| nodes[j].key.as_deref() == Some(key.as_str()) && shown(j))?; + (anchor..nodes.len()).take_while(|&j| within(&nodes[j].path, &nodes[anchor].path)) + .find(|&j| shown(j) && self.can_take_focus(&nodes[j])) + .map(|j| (nodes[j].path.clone(), ring, ask)) + }); + let input_focused = self.kbd.focus.path().is_some_and(|p| { + nodes.iter().any(|n| n.path == p && !n.inert && n.input.as_ref().is_some_and(|i| i.edit.focused)) + || self.commit.virtual_inputs.get(p).is_some_and(|i| i.edit.focused) + }); + let was_focused = |edit: &crate::edit::TextEdit, path: &str| { + self.tree.nodes.iter().any(|old| { + old.input.as_ref().is_some_and(|i| i.edit.focused && (old.path == path || i.edit.same_model(edit))) + }) || (input_focused && self.kbd.was_unmounted_focused(edit)) + }; + let virtual_req = || self.commit.virtual_inputs.iter() + .filter(|(_, i)| i.edit.focused) + .map(|(p, i)| (p.as_str(), &i.edit)); + // A newly requested text field wins; a focused control otherwise retains focus. Nothing + // inside an `El::inert` subtree takes or keeps it. + let requested = (0..nodes.len()) + .filter(|&j| shown(j) && nodes[j].input.as_ref().is_some_and(|i| i.edit.focused)) + .map(|j| (nodes[j].path.as_str(), &nodes[j].input.as_ref().unwrap().edit)); + // Hash iteration must not decide between simultaneous offscreen requests. Select + // only the winning path rather than allocating and sorting every focused field. + let newly_requested = |p: &str, edit: &crate::edit::TextEdit| { + !self.kbd.focus.is(p) && !was_focused(edit, p) + }; + let next = requested.clone().find(|&(p, edit)| newly_requested(p, edit)) + .or_else(|| virtual_req().filter(|&(p, edit)| newly_requested(p, edit)).min_by_key(|&(p, _)| p)) + .map(|(p, _)| p.to_owned()) + .or_else(|| asked.as_ref().map(|(p, ..)| p.clone())) + .or(restore) + .or_else(|| self.kbd.focus.owned().filter(|p| (0..nodes.len()).any(|j| &nodes[j].path == p && shown(j) + && (self.takes_focus(&nodes[j]) || nodes[j].input.as_ref().is_some_and(|i| i.edit.focused))) + || self.commit.virtual_inputs.get(p).is_some_and(|i| i.edit.focused))) + .or_else(|| requested.into_iter().next().or_else(|| virtual_req().min_by_key(|&(p, _)| p)).map(|(p, _)| p.to_owned())) + .or_else(|| self.focus_fallback(nodes)); + // State may have deleted a row. Only the new view's accessors are valid now. + // Use the same focus path as input events, then restore the old presentation + // tree so apply can retain its exit visuals. + let explicit = asked.as_ref().filter(|(p, ..)| next.as_deref() == Some(p.as_str())); + let keep_entry = explicit.is_none() && next.as_deref() == self.kbd.focus.path(); + let keyboard = explicit.map_or_else(|| self.kbd.focus.keyboard(), |(_, ring, _)| *ring); + self.kbd.set_focus_returned(matches!(explicit, Some((_, _, crate::el::FocusAsk::Return)))); + if asked.is_none() && let Some(owed) = waits { self.kbd.focus_owed = Some(owed); } + std::mem::swap(&mut self.tree.nodes, nodes); + self.nodes_replaced(); + let changed = self.set_focus_entry(app, next, keyboard, keep_entry); + std::mem::swap(&mut self.tree.nodes, nodes); + self.nodes_replaced(); + if self.edit.input_click.dragging_path().is_some_and(|p| !nodes.iter().any(|n| n.path == p && !n.inert && n.input.is_some())) { + self.edit.input_click.drop_drag(); + } + if !self.pointer.press.is_held() { + self.kbd.focus.step(focus_machine::FocusEvent::Settled); + } + self.kbd.prune_unmounted_focused(nodes, &self.commit.virtual_inputs); + changed + } + /// Where focus goes when the element holding it leaves the tree or can't hold it anymore (a + /// deleted row, a closed tab, a decided prompt, a control disabled while focused, a pane closed + /// under it) and nothing else asked for it. It and [`Self::fallback_in_new`] (a region kept + /// from an earlier commit, or a control rebuilt disabled) share one rule, [`rescue`], looking + /// first inside its nearest container that survived and then further out: + /// - **It was a Tab stop:** the next Tab stop after it in that container, else the one before, + /// else the container itself when it is one, then the same in the next container out; only + /// when no container out to the root has a Tab stop left does focus go to any control. A + /// keyboard user lands where Tab would go, as OpenCode Desktop's focus rescue does + /// (opencode#64909), not on a control Tab never reaches. + /// - **Before either:** focus that was in a roving group (on an item, or on a control inside one, + /// a tab's Close button) goes to another of that group's items, the next, else the previous: + /// the next tab, not the next tab's Close button. + /// - **It wasn't** (an item of a roving group, a control out of the Tab order): the next control + /// after it that can take focus, else the one before, else the container, as a native list + /// hands its selection to the neighbour. + /// + /// Without a rescue focus fell to nothing: a screen reader went back to the window and Tab + /// started over at its top. A modal's own focus is left to the modal machine, which returns + /// it where it was. + fn focus_fallback(&self, nodes: &[Node]) -> Option<String> { + // A field that Escape blurred and that then closed (a comment box cancelled, gone once + // its exit ends) counts as focused: the keyboard was on it, and nothing took focus since. + let gone = self.kbd.focus.path().or_else(|| self.kbd.focus.now_or_blurred().or(self.kbd.focus.tab_start()).filter(|_| self.kbd.focus.keyboard()))?; + // `Tx::blur` says nothing has focus: it hands nothing on, unlike Escape or a deleted row. + if self.kbd.focus.path().is_none() && !self.kbd.focus.handoff() { return None; } + let Some(at) = self.tree.nodes.iter().position(|n| n.path == gone) else { + // An offscreen field had no layout node. Only a moved node lost its path, or one whose + // rebuilt replacement took it over: a control rebuilt disabled (Send as its prompt + // sends) still has to hand focus on, which `fallback_in_new` does from the new tree. + let old = self.tree.nodes.get(*self.tree.node_index.get(self.tree.path_ids.get(gone)?)?)?; + let disabled_here = nodes.iter().any(|n| n.path == gone && !self.can_take_focus(n)); + if !old.is_moved_stub() && !disabled_here { return None; } + return self.fallback_in_new(gone, nodes); + }; + // The control that held it is still in the tree, even when a model cleared its flag or a + // commit hid it: nothing takes its keyboard. One that can't hold focus any more (disabled + // while focused, as a Send button is while its prompt sends) hands it on as if it had left, + // as OpenCode Desktop's focus rescue does (opencode#64909); focus never falls to the window. + if nodes.iter().any(|n| n.path == gone && self.can_take_focus(n)) { return None; } + if self.kbd.focus.path().is_none() && self.tree.nodes[at].input.is_none() { return None; } + if self.active_modal().is_some_and(|m| at >= m && self.modal_member(at)) { return None; } + let new: rustc_hash::FxHashMap<&str, usize> = nodes.iter().enumerate().map(|(j, n)| (n.path.as_str(), j)).collect(); + // Building the new tree hands an old node's path and id to the node that replaces it and + // leaves it without a path, so a control still here can look absent. Resolve those by id. + let at_new = |i: usize| -> Option<usize> { + let n = &self.tree.nodes[i]; + if !n.path.is_empty() { return new.get(n.path.as_str()).copied(); } + self.tree.node_index.get(&n.id).copied() + .filter(|&j| nodes.get(j).is_some_and(|m| m.id == n.id)) + }; + // A node built this commit may have no box yet, and is judged by the size its old node + // had; one laid out keeps its own box, so a collapsed or hidden control takes no focus. + let unlaid = |j: usize| nodes[j].local.w <= 0.0 && nodes[j].local.h <= 0.0; + let survivor = |i: usize| at_new(i) + .filter(|&j| (node_shown(nodes, j) || (unlaid(j) && node_sized(&self.tree.nodes, i) && node_visible(nodes, j))) + && self.can_take_focus(&nodes[j])); + let within = |j: usize, s: usize| { + // Compare in the new tree where both ends are in it; a node that left keeps its old + // path, so the scan still reaches the siblings after it. + let (p, root) = match (at_new(j), at_new(s)) { + (Some(p), Some(r)) => (nodes[p].path.as_str(), nodes[r].path.as_str()), + _ => (self.tree.nodes[j].path.as_str(), self.tree.nodes[s].path.as_str()), + }; + root.is_empty() || (p.len() > root.len() && p.starts_with(root) && p.as_bytes()[root.len()] == b'/') + }; + // Each surviving container, nearest first, with its descendants' span in the old tree. + let mut scopes = Vec::new(); + let mut scope = self.tree.nodes[at].parent; + while let Some(s) = scope { + if at_new(s).is_some() { + scopes.push((s, (s + 1..self.tree.nodes.len()).find(|&j| !within(j, s)).unwrap_or(self.tree.nodes.len()))); + } + scope = self.tree.nodes[s].parent; + } + // The container itself counts after its children, when it takes focus (a list row whose + // comment box closed under it). + // Focus that was in a roving group (on an item, or on a control inside one: a tab's Close + // button) goes first to another item of that group, where the keys move inside it (the + // next tab, not the next tab's Close button). + let home = self.roving_home_in(&self.tree.nodes, at).and_then(at_new); + let item = |i: usize| survivor(i).filter(|&j| home.is_some() && self.group_in(nodes, j) == home); + let tab = |i: usize| survivor(i).filter(|&j| self.tab_stop_in(nodes, j)); + let lost_tab_stop = self.tree.nodes[at].focus.order >= 0 && self.focus_group(at).is_none(); + rescue(lost_tab_stop, at, &scopes, &item, &tab, &survivor).map(|j| nodes[j].path.clone()) + } + /// [`Self::focus_fallback`] when the old tree holds the part that had focus only as a moved + /// stub (a region kept from an earlier commit, a virtual row): the nearest container of it in + /// the new tree takes focus when it can (a diff line whose comment box closed), else its first + /// control. + /// A control still here that can't take focus any more (disabled while focused, inside a + /// region kept from an earlier commit) hands it on as [`Self::focus_fallback`] does: the next + /// control after it in its nearest container that has one, else the one before, else that + /// container. + fn fallback_in_new(&self, gone: &str, nodes: &[Node]) -> Option<String> { + if self.active_modal().is_some() { return None; } + let can = |j: usize| node_shown(nodes, j) && self.can_take_focus(&nodes[j]); + if let Some(at) = nodes.iter().position(|n| n.path == gone) { + if self.can_take_focus(&nodes[at]) { return None; } + let mut scopes = Vec::new(); + let mut p = gone; + while let Some(k) = p.rfind('/') { + p = &p[..k]; + let Some(c) = nodes.iter().position(|n| n.path == p) else { continue }; + let inside = |m: usize| nodes[m].path.len() > p.len() && nodes[m].path.starts_with(p) && nodes[m].path.as_bytes()[p.len()] == b'/'; + scopes.push((c, (c + 1..nodes.len()).find(|&m| !inside(m)).unwrap_or(nodes.len()))); + } + let any = |m: usize| can(m).then_some(m); + let home = self.roving_home_in(nodes, at); + let item = |m: usize| (can(m) && home.is_some() && self.group_in(nodes, m) == home).then_some(m); + let tab = |m: usize| (can(m) && self.tab_stop_in(nodes, m)).then_some(m); + return rescue(self.tab_stop_in(nodes, at), at, &scopes, &item, &tab, &any).map(|m| nodes[m].path.clone()); + } + let mut p = gone; + while let Some(k) = p.rfind('/') { + p = &p[..k]; + let Some(j) = nodes.iter().position(|n| n.path == p) else { continue }; + let inside = |m: usize| nodes[m].path.len() > p.len() && nodes[m].path.starts_with(p) && nodes[m].path.as_bytes()[p.len()] == b'/'; + return std::iter::once(j).chain((j + 1..nodes.len()).take_while(|&m| inside(m))).find(|&m| can(m)).map(|m| nodes[m].path.clone()); + } + None + } + pub(in crate::runtime) fn tab_order(&self) -> Vec<usize> { + let all: Vec<_> = (0..self.tree.nodes.len()).filter(|&i| self.can_focus(i) && self.tree.nodes[i].focus.order >= 0).collect(); + let mut order: Vec<_> = all.iter().copied().filter(|&i| { + let Some(g) = self.focus_group(i) else { return true; }; + let chosen = all.iter().copied().filter(|&j| self.focus_group(j) == Some(g)) + .find(|&j| self.kbd.focus.is(&self.tree.nodes[j].path)) + .or_else(|| all.iter().copied().find(|&j| self.focus_group(j) == Some(g) && self.tree.nodes[j].focus.selected)) + .or_else(|| all.iter().copied().find(|&j| self.focus_group(j) == Some(g))); + chosen == Some(i) + }).collect(); + order.sort_by_key(|&i| { let n = self.tree.nodes[i].focus.order; (if n > 0 { n } else { i32::MAX }, i) }); + order + } + /// F6 (Shift+F6 back): focus moves to the next landmark (`banner`, `navigation`, `main`, + /// `complementary`, `form`, `search`, a labelled `region`) that has a Tab stop, onto the + /// control focused last inside it, else its first Tab stop, as browsers and Windows apps + /// cycle panes. Inside a modal it does nothing: the modal is the only pane. + fn cycle_landmark(&mut self, app: &mut dyn AppDriver, back: bool, tx: &mut Tx) -> bool { + if self.active_modal().is_some() { return false; } + let order = self.tab_order(); + let marks: Vec<(usize, usize)> = (0..self.tree.nodes.len()) + .filter(|&i| is_landmark(&self.tree.nodes, i) && self.allowed(i) && !self.subtree_exiting(i) && self.tree.nodes[i].local.w > 0.0 && self.tree.nodes[i].local.h > 0.0) + .filter_map(|i| order.iter().copied().find(|&j| path_inside(&self.tree.nodes, j, i)).map(|first| (i, first))) + .collect(); + if marks.is_empty() { return false; } + let here = self.focused_index().and_then(|f| marks.iter().rposition(|&(m, _)| path_inside(&self.tree.nodes, f, m))); + let next = match here { + Some(k) if back => (k + marks.len() - 1) % marks.len(), + Some(k) => (k + 1) % marks.len(), + None if back => marks.len() - 1, + None => 0, + }; + let (mark, first) = marks[next]; + let remembered = self.kbd.focus.scope_memory(&self.tree.nodes[mark].path) + .and_then(|p| order.iter().copied().find(|&j| self.tree.nodes[j].path == p)); + let path = self.tree.nodes[remembered.unwrap_or(first)].path.clone(); + self.set_focus(app, Some(path.clone()), true); + tx.scroll_to.push(crate::runtime::ScrollReveal::into_view(None, path)); + true + } + /// `shown`: the focus highlight was visible before this key arrived. + pub(in crate::runtime) fn focus_key(&mut self, app: &mut dyn AppDriver, ev: &KeyEvent, shown: bool, tx: &mut Tx) -> bool { + if ev.mods.cmd || ev.mods.ctrl || ev.mods.alt || ev.mods.logo { return false; } + // Activations (dismiss, press, open) fire once per press. Their repeats are consumed so + // they reach nothing else; navigation below keeps repeating. + let repeat = tx.key_repeat; + if ev.key == Key::Escape && let Some(i) = self.active_modal() { + if repeat { return true; } + let f = self.tree.nodes[i].handlers.modal.as_ref().unwrap().dismiss.clone(); + self.set_focus(app, None, self.kbd.focus.keyboard()); + f(app.states(), tx); + return true; + } + if ev.key == Key::Function(6) { + return self.cycle_landmark(app, ev.mods.shift, tx); + } + if ev.key == Key::Tab { + if self.focused_index().is_some_and(|i| self.edit.link_tab(&self.tree.nodes[i], ev.mods.shift)) { return true; } + let mut order = self.tab_order(); + if !self.kbd.tab_visits_all() { + // A control that owns its keyboard (`El::on_key`) is a list of its own. + order.retain(|&i| self.tree.nodes[i].input.is_some() || self.tree.nodes[i].focus.key.is_some() + || self.focus_group(i).is_some_and(|g| LIST_ROLES.contains(&self.tree.nodes[g].role))); + } + if order.is_empty() { return self.active_modal().is_some(); } + let current = order.iter().position(|&i| self.kbd.focus.is(&self.tree.nodes[i].path)); + // With nothing focused, Tab goes on from where focus was or the pointer pressed last; + // from an element outside the Tab order (`tab_index(-1)`, a region a request focused), + // it goes on from that element's place, as a browser's does. + let from = self.kbd.focus.tab_start().filter(|_| self.commit.defaults.web_focus).and_then(|p| self.tree.nodes.iter().position(|n| n.path == p)) + .or_else(|| self.focused_index().filter(|_| current.is_none())); + let next = match (current, from) { + (Some(i), _) if ev.mods.shift => (i + order.len() - 1) % order.len(), + (Some(i), _) => (i + 1) % order.len(), + (None, Some(k)) if ev.mods.shift => order.iter().rposition(|&j| j < k).unwrap_or(order.len() - 1), + (None, Some(k)) => order.iter().position(|&j| j > k).unwrap_or(0), + (None, None) if ev.mods.shift => order.len() - 1, + (None, None) => 0, + }; + let path = self.tree.nodes[order[next]].path.clone(); + self.set_focus(app, Some(path.clone()), true); + tx.scroll_to.push(crate::runtime::ScrollReveal::into_view(None, path)); + self.edit.enter_links(&self.tree.nodes[order[next]], ev.mods.shift); + return true; + } + let Some(i) = self.focused_index() else { return false; }; + if !self.can_focus(i) { return false; } + // Past Tab, a Shift-modified key navigates and presses nothing: it goes on to the app. + // Typed text still type-selects (Shift-A is "A"). + if ev.mods.shift && !matches!(&ev.key, Key::Text(t) if !t.trim().is_empty()) { return false; } + // A slider's keys come before its group's arrows. + if let Some(step) = self.tree.nodes[i].focus.step.clone() { + // A right-to-left slider runs from its right: Left raises it. + let rtl = self.tree.nodes[i].flow == crate::el::Flow::Rtl; + let delta = match ev.key { + Key::Left => Some(if rtl { 1 } else { -1 }), Key::Right => Some(if rtl { -1 } else { 1 }), + Key::Down => Some(-1), Key::Up => Some(1), + Key::PageDown => Some(-10), Key::PageUp => Some(10), + _ => None, + }; + if let Some(delta) = delta { step(app.states(), delta, tx); return true; } + if matches!(ev.key, Key::Home | Key::End) { + let Some(f) = self.tree.nodes[i].focus.step_limit.clone() else { return false }; + f(app.states(), ev.key == Key::End, tx); + return true; + } + } + // A focused field inside a list row (an inline rename) keeps its letters and arrows. + if self.tree.nodes[i].input.is_none() && let Some(g) = self.focus_group(i) { + let vertical = VERTICAL_ROLES.contains(&self.tree.nodes[g].role); + // A right-to-left row's first item is at its right: Left goes on to the next. + let (back, ahead) = if self.tree.nodes[g].flow == crate::el::Flow::Rtl { (Key::Right, Key::Left) } else { (Key::Left, Key::Right) }; + let backward = matches!(ev.key, Key::Up) || (!vertical && ev.key == back); + let forward = matches!(ev.key, Key::Down) || (!vertical && ev.key == ahead); + let items: Vec<_> = (0..self.tree.nodes.len()).filter(|&j| self.can_focus(j) && self.focus_group(j) == Some(g)).collect(); + let pos = items.iter().position(|&j| j == i).unwrap(); + let page = matches!(ev.key, Key::PageUp | Key::PageDown) && PAGED_ROLES.contains(&self.tree.nodes[g].role); + let next = if backward || forward || page || matches!(ev.key, Key::Home | Key::End) { + self.kbd.reset_type_select(); + Some(match ev.key { + Key::Home => 0, Key::End => items.len() - 1, + Key::PageUp | Key::PageDown => self.page_item(&items, pos, ev.key == Key::PageDown), + // A highlight the user cannot see yet appears where it is (a popup's checked + // item, else the first) before arrows move it; Up from nothing is the last. + _ if self.tree.nodes[i].focus.highlight.is_some() && !shown => + if backward && !self.tree.nodes[i].focus.selected { items.len() - 1 } else { pos }, + _ if CLAMPED_ROLES.contains(&self.tree.nodes[g].role) => + if backward { pos.saturating_sub(1) } else { (pos + 1).min(items.len() - 1) }, + _ if backward => (pos + items.len() - 1) % items.len(), + _ => (pos + 1) % items.len(), + }) + } else if let Key::Text(t) = &ev.key && TYPE_SELECT_ROLES.contains(&self.tree.nodes[g].role) && !t.trim().is_empty() { + let now = self.now_clock(); + self.kbd.type_select(&self.tree.nodes, &items, pos, t, now) + } else { None }; + if let Some(next) = next { + let n = &self.tree.nodes[items[next]]; + let follows = n.role == "radio" || n.role == "tab" || self.tree.nodes[g].focus.follows; + let action = follows.then(|| n.handlers.on_press.clone()).flatten(); + let path = n.path.clone(); + self.set_focus(app, Some(path.clone()), true); + tx.scroll_to.push(crate::runtime::ScrollReveal::into_view(None, path)); + if let Some(f) = action { f(app.states(), tx); } + return true; + } + } else if self.tree.nodes[i].role == "combobox" && self.tree.nodes[i].input.is_none() && matches!(ev.key, Key::Up | Key::Down) { + // A popup button opens on its arrows as well as Space (NSPopUpButton). + if repeat { return true; } + if let Some(f) = self.tree.nodes[i].handlers.on_press.clone() { f(app.states(), tx); } + return true; + } + // Space presses the focused control. Return presses only rows and links; for a button + // it goes on to the default button (`default_button_key`, which ran first) or `on_key`. + let space = ev.key == Key::Text(" ".into()) && !self.scrolls_on_space(i); + if self.tree.nodes[i].input.is_none() && (space || (ev.key == Key::Enter && self.takes_return(i))) { + // A row the user cannot see highlighted (the pointer left it) chooses nothing. + if self.tree.nodes[i].focus.highlight.is_some() && !shown { self.kbd.focus.step(focus_machine::FocusEvent::Pointed); return true; } + if repeat { return true; } + if self.link_key(app, i, tx) { return true; } + if let Some(f) = self.tree.nodes[i].handlers.on_press.clone() { f(app.states(), tx); } + return true; + } + false + } + /// The item Page Down (or Up) moves to from `items[pos]`: the farthest one still inside a + /// viewport's height of it, as a list's highlight pages in AppKit, at least one item on and + /// stopping at the ends. Without a scroll view around it, the last (or first). + fn page_item(&self, items: &[usize], pos: usize, down: bool) -> usize { + let at = &self.tree.nodes[items[pos]]; + let page = std::iter::successors(at.parent, |&p| self.tree.nodes[p].parent) + .find(|&p| self.tree.nodes[p].scroll.is_some()).map_or(f32::INFINITY, |v| self.tree.nodes[v].local.h); + let within = |j: &usize| { + let n = &self.tree.nodes[items[*j]]; + if down { n.target[3] - at.target[1] <= page + 0.5 } else { at.target[3] - n.target[1] <= page + 0.5 } + }; + let far = if down { (pos..items.len()).take_while(within).last() } else { (0..=pos).rev().take_while(within).last() }; + match far.filter(|&j| j != pos) { + Some(j) => j, + None if down => (pos + 1).min(items.len() - 1), + None => pos.saturating_sub(1), + } + } + + /// In a group whose selection follows focus, focus follows selection too: when the app + /// selects another item (a shortcut, say), focus in that group moves to it. + pub(in crate::runtime) fn sync_follows(&mut self, app: &mut dyn AppDriver) { + let Some(i) = self.focused_index() else { return }; + if self.tree.nodes[i].input.is_some() || self.tree.nodes[i].focus.selected { return; } + let Some(g) = self.focus_group(i).filter(|&g| self.tree.nodes[g].focus.follows) else { return }; + let Some(j) = (0..self.tree.nodes.len()) + .find(|&j| self.tree.nodes[j].focus.selected && self.focus_group(j) == Some(g) && self.can_focus(j)) else { return }; + let path = self.tree.nodes[j].path.clone(); + self.set_focus(app, Some(path), self.kbd.focus.keyboard()); + } +} + +/// The rescue's pick for [`RuntimeCore::focus_fallback`] and [`RuntimeCore::fallback_in_new`]: +/// `scopes` are the containers that survived, nearest first, each with the end of its +/// descendants' span (indices in document order; `at` lost focus). In each container, the next +/// control after `at` and then the one before, then the container itself. A Tab stop that lost +/// focus is handed only to Tab stops (`tab`) while any container out to the root has one; only +/// then to any control (`any`). Anything else hands focus to any control. Focus that was in a +/// roving group goes first to another of that group's items (`item`), whatever it was. +fn rescue(lost_tab_stop: bool, at: usize, scopes: &[(usize, usize)], item: &dyn Fn(usize) -> Option<usize>, tab: &dyn Fn(usize) -> Option<usize>, any: &dyn Fn(usize) -> Option<usize>) -> Option<usize> { + let pass = |ok: &dyn Fn(usize) -> Option<usize>| scopes.iter().find_map(|&(s, end)| { + (at + 1..end).find_map(ok).or_else(|| (s + 1..at).rev().find_map(ok)).or_else(|| ok(s)) + }); + pass(item).or_else(|| if lost_tab_stop { pass(tab).or_else(|| pass(any)) } else { pass(any) }) +} + +#[cfg(test)] +#[path = "focus_tests.rs"] +mod tests; diff --git a/app/vendor/rune/crates/rune/src/runtime/input/focus_machine.rs b/app/vendor/rune/crates/rune/src/runtime/input/focus_machine.rs new file mode 100644 index 0000000..ecb3979 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/input/focus_machine.rs @@ -0,0 +1,413 @@ +//! The focus machine: which element has keyboard focus, how focus shows, and where Tab starts +//! while nothing has it. `step` decides; `Runtime::set_focus` and the input routes feed it and +//! carry out what it returns (the IME, links and the inputs' own focus flags follow a move). +//! +//! The pieces it keeps apart, as a browser does: +//! - [`Focus`]: nothing focused, or one element. Only an element the pointer lit as a +//! `focus_highlight` row is `hovered`, and only while nothing is focused is there a starting +//! point for Tab (`from`) or a focus a press just took away (`blurred`). +//! - [`Modality`]: whether focus shows (CSS `:focus-visible`'s heuristic). It outlives a blur, +//! so focus a closing modal hands back shows as it did. +//! - [`TypeSelect`]: a list's typed prefix, which a pause ends. +use crate::machine::Effects; + +/// Whether the keyboard drove focus last: then a focused control shows its ring. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(crate) enum Modality { + #[default] + Pointer, + Keyboard, +} + +/// How focus came to the element that has it: by the keys (a Tab, an arrow in a group, `Tx::focus` +/// with a ring), or otherwise (a press, a hand-over without a ring, nothing focused). A field's +/// keyboard-entry ring follows it, not [`Modality`]: an arrow typed in a field a click focused +/// doesn't make it the keys' (`El::focus_visible_within_ring`). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(crate) enum Entry { + #[default] + Other, + Keys, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) enum Focus { + /// Nothing has focus. Tab starts from `from` (the element last focused, or pressed without + /// taking focus, as a browser's sequential focus navigation starting point). `blurred` is + /// the focus the gesture or commit underway took away: a scrim that blurs on pointer-down + /// and closes its overlay on pointer-up still returns focus through `El::focus_return`. + /// `handoff` is whether that focus may go to a neighbour once its element leaves the tree + /// (the user's Escape or a press): `Tx::blur` says nothing has focus, so it hands nothing on. + None { from: Option<String>, blurred: Option<String>, handoff: bool }, + /// `path` has focus. `hovered`: the pointer lit it as a `focus_highlight` row, so its + /// highlight shows without a key. `from`: a press on content that takes no focus queued a + /// blur, and Tab starts there once it lands. + On { path: String, hovered: bool, from: Option<String> }, +} + +impl Default for Focus { + fn default() -> Self { Self::None { from: None, blurred: None, handoff: false } } +} + +pub(crate) enum FocusEvent { + /// Focus moves to `path`, or nowhere, and shows as `keyboard` says. When `keep_entry` is + /// set (a commit keeping focus on the same element without an explicit `Tx::focus`), [`Entry`] + /// stays as it arrived so an in-field arrow key or window return doesn't light a field's ring. + Set { path: Option<String>, keyboard: bool, keep_entry: bool }, + /// The pointer lit (`true`) or left (`false`) the focused `focus_highlight` row. + Hover(bool), + /// A key that navigates (Tab, an arrow): focus shows from now on. + Navigated, + /// The window came to the front again with focus where it was: that isn't the keys moving + /// focus there. + WindowReturned, + /// A pointer press, or a key on a highlight the user couldn't see: focus stops showing. + Pointed, + /// A press on content that takes no focus: Tab goes on from there. + StartAt(String), + /// `Tx::blur`: the app dropped focus itself, so nothing hands the keyboard on when the + /// element it left goes too, unlike Escape or a press that blurred it. + Dropped, + /// A commit settled with no press held, or `Tx::blur`: a blur it carried is final. + Settled, +} + +#[derive(Debug, PartialEq, Eq)] +pub(crate) enum FocusEffect { + /// Focus left the element it was on (or arrived from nowhere): the IME, links and the + /// selection's keyboard follow. + Moved, +} + +/// The whole focus state the runtime keeps. +#[derive(Clone, Debug, Default, PartialEq)] +pub(crate) struct FocusState { + pub(crate) focus: Focus, + pub(crate) modality: Modality, + pub(crate) entry: Entry, + /// Per landmark (by path), the element focused last inside it, most recent first: where F6 + /// lands when it comes back to that pane. + scopes: Vec<(String, String)>, +} + +/// How many panes F6 remembers a focus for. +const SCOPES: usize = 16; + +impl FocusState { + pub(crate) fn path(&self) -> Option<&str> { + match &self.focus { + Focus::On { path, .. } => Some(path), + Focus::None { .. } => None, + } + } + + pub(crate) fn owned(&self) -> Option<String> { self.path().map(str::to_owned) } + + pub(crate) fn is(&self, path: &str) -> bool { self.path() == Some(path) } + + pub(crate) fn keyboard(&self) -> bool { self.modality == Modality::Keyboard } + + /// The keys put focus where it is. + pub(crate) fn entered_by_keys(&self) -> bool { self.entry == Entry::Keys } + + /// The pointer lit the focused row. + pub(crate) fn hovered(&self) -> bool { matches!(self.focus, Focus::On { hovered: true, .. }) } + + /// Focus shows, by the keyboard or the pointer's light on a row. + pub(crate) fn shown(&self) -> bool { self.keyboard() || self.hovered() } + + /// Notes that `path` has focus inside landmark `scope`. + pub(crate) fn remember_scope(&mut self, scope: String, path: String) { + if self.scopes.first().is_some_and(|(s, p)| *s == scope && *p == path) { return; } + self.scopes.retain(|(s, _)| *s != scope); + self.scopes.insert(0, (scope, path)); + self.scopes.truncate(SCOPES); + } + + /// The element focused last inside landmark `scope`. + pub(crate) fn scope_memory(&self, scope: &str) -> Option<&str> { + self.scopes.iter().find(|(s, _)| s == scope).map(|(_, p)| p.as_str()) + } + + /// Where Tab starts while nothing is focused. + pub(crate) fn tab_start(&self) -> Option<&str> { + match &self.focus { + Focus::None { from, .. } => from.as_deref(), + Focus::On { .. } => None, + } + } + + /// Focus now, else the focus the gesture underway took away. + pub(crate) fn now_or_blurred(&self) -> Option<&str> { + match &self.focus { + Focus::On { path, .. } => Some(path), + Focus::None { blurred, .. } => blurred.as_deref(), + } + } + + /// Whether focus the element lost may move to a neighbour once it leaves the tree. + pub(crate) fn handoff(&self) -> bool { + matches!(self.focus, Focus::None { handoff: true, .. }) + } + + pub(crate) fn step(&mut self, event: FocusEvent) -> Effects<FocusEffect> { + match event { + FocusEvent::Set { path, keyboard, keep_entry } => { + self.modality = if keyboard { Modality::Keyboard } else { Modality::Pointer }; + if !keep_entry { + self.entry = if keyboard && path.is_some() { Entry::Keys } else { Entry::Other }; + } + let moved = self.path() != path.as_deref(); + self.focus = match (std::mem::take(&mut self.focus), path) { + (Focus::On { path: old, hovered, .. }, Some(path)) if old == path => Focus::On { path, hovered, from: None }, + (_, Some(path)) => Focus::On { path, hovered: false, from: None }, + (Focus::On { path: old, from, .. }, None) => Focus::None { from: from.or_else(|| Some(old.clone())), blurred: Some(old), handoff: true }, + (none @ Focus::None { .. }, None) => none, + }; + if moved { Effects::one(FocusEffect::Moved) } else { Effects::none() } + } + FocusEvent::Hover(lit) => { + if let Focus::On { hovered, .. } = &mut self.focus { *hovered = lit; } + Effects::none() + } + FocusEvent::Navigated => { + self.modality = Modality::Keyboard; + Effects::none() + } + FocusEvent::WindowReturned => { + self.entry = Entry::Other; + Effects::none() + } + FocusEvent::Pointed => { + self.modality = Modality::Pointer; + Effects::none() + } + FocusEvent::StartAt(path) => { + match &mut self.focus { + Focus::None { from, .. } | Focus::On { from, .. } => *from = Some(path), + } + Effects::none() + } + FocusEvent::Dropped => { + if let Focus::None { handoff, .. } = &mut self.focus { *handoff = false; } + Effects::none() + } + FocusEvent::Settled => { + if let Focus::None { blurred, .. } = &mut self.focus { *blurred = None; } + Effects::none() + } + } + } + + /// Sets focus aside for a key the playground's stage presses, without a transition: nothing + /// moves, and [`Self::put_back`] restores it if nothing took focus meanwhile. + pub(crate) fn set_aside(&mut self) -> Option<Focus> { + let Focus::On { path, from, .. } = &self.focus else { return None }; + let rest = Focus::None { from: from.clone(), blurred: Some(path.clone()), handoff: false }; + Some(std::mem::replace(&mut self.focus, rest)) + } + + pub(crate) fn put_back(&mut self, aside: Focus) { + if matches!(self.focus, Focus::None { .. }) { self.focus = aside; } + } +} + +/// How long a list waits for the next typed letter before its prefix starts over (AppKit's). +pub(crate) const TYPE_SELECT_PAUSE: f64 = 1.0; + +/// A list's type-select: nothing typed, or a prefix and when its last letter arrived. +#[derive(Clone, Debug, Default, PartialEq)] +pub(crate) enum TypeSelect { + #[default] + Idle, + Typing { prefix: String, at: f64 }, +} + +impl TypeSelect { + /// The prefix after `typed` arrives at `now`: it starts over after a pause. + pub(crate) fn typed(&mut self, typed: &str, now: f64) -> &str { + let prefix = match std::mem::take(self) { + Self::Typing { prefix, at } if now - at <= TYPE_SELECT_PAUSE => prefix, + _ => String::new(), + }; + *self = Self::Typing { prefix: prefix + &typed.to_lowercase(), at: now }; + match self { + Self::Typing { prefix, .. } => prefix, + Self::Idle => "", + } + } + + /// A key that moves by position (an arrow, Home, End) ends the prefix. + pub(crate) fn reset(&mut self) { *self = Self::Idle; } +} + +/// Keyboard focus, modal focus/scope, type-select, held keys and modifier tracking owned by +/// [`crate::runtime::RuntimeCore`]. Ordered hot-first under `#[repr(C)]` so `modal_scope` +/// (checked per interactive node in `register_node_hits`) sits at offset 0. +#[repr(C)] +pub(crate) struct KeyboardState { + /// The innermost open modal this commit shows and what input may reach inside it, worked + /// out from the nodes at each commit; none while no modal shows. + pub(in crate::runtime) modal_scope: Option<crate::runtime::focus::ModalScope>, + /// What has focus, how it shows and where Tab starts (`runtime/input/focus_machine.rs`). + pub(crate) focus: FocusState, + /// Type-select's typed prefix and when its last key arrived (`now_clock`). + type_select: TypeSelect, + /// The activation key (Enter, Escape, Space) held down and the focus it was first pressed + /// on. Its repeats are dropped once focus has moved, so a held key that closed something + /// can't act again on whatever took focus next. + pub(in crate::runtime) held: crate::runtime::physical_dispatch::Activation, + /// Modifier keys down, for `Key::Modifier` (off unless the app opts in). + pub(super) modifier_keys: crate::runtime::modifier_keys::ModifierKeys, + /// Key releases an input method takes, and the focus where the held non-IME key(s) went + /// down, so a release after focus moves still reaches that element first. + key_releases: crate::runtime::key_releases::KeyReleases, + /// The open modals and where focus returns as each closes (`modal_focus`). + pub(super) modal_focus: crate::runtime::modal_focus::ModalFocus, + /// Focus when the running commit began, before a new view's focus request applied: what a + /// modal that opens in this commit returns focus to. + pub(in crate::runtime) focus_before_commit: Option<String>, + /// `Tx::focus`: the key the next commit focuses, and whether its ring shows. + pub(in crate::runtime) focus_request: Option<(String, bool, crate::el::FocusAsk)>, + /// `Tx::focus_when_shown` still waiting for its element: the key and whether its ring shows. + pub(in crate::runtime) focus_owed: Option<(String, bool)>, + /// Focused text fields that unmounted without being blurred: while another field holds focus, + /// remounting one with its old `focused = true` flag does not steal focus back. + pub(super) unmounted_focused: Vec<std::sync::Weak<crate::edit::History>>, + /// The modifiers `App::on_modifiers` last heard. + mods_heard: crate::Mods, + /// Modifier keys held now, as the window last reported them (`Tx::mods`). + pub(in crate::runtime) held_mods: crate::Mods, + /// `keys_lost` queued its `FocusLost` since the window last had focus. + pub(in crate::runtime) keys_lost: bool, + /// Tab visits every control; off, only text fields and lists (macOS Full Keyboard + /// Access off). Native hosts sample the system setting; headless runtimes default on. + pub(in crate::runtime) full_keyboard_access: bool, + /// `App::tab_visits_controls`: Tab visits every control whatever `full_keyboard_access` says. + pub(in crate::runtime) tab_visits_controls: bool, + /// This commit's focus is a `Tx::return_focus` hand-back, which a modal opening in it + /// doesn't take as where focus was. + focus_returned: bool, +} + +impl KeyboardState { + // Single-caller constructor for `RuntimeCore::new`; inlined so it stays in its caller's + // codegen unit instead of shifting partitioning and dropping inlining in the paint walk. + #[inline] + pub(in crate::runtime) fn new() -> Self { + Self { + focus: Default::default(), + type_select: Default::default(), + held: Default::default(), + modifier_keys: Default::default(), + mods_heard: Default::default(), + held_mods: Default::default(), + key_releases: Default::default(), + keys_lost: false, + full_keyboard_access: true, + tab_visits_controls: false, + modal_focus: crate::runtime::modal_focus::ModalFocus::Closed, + focus_before_commit: None, + focus_request: None, + focus_owed: None, + focus_returned: false, + unmounted_focused: Vec::new(), + modal_scope: None, + } + } + + #[inline] + pub(in crate::runtime) fn has_focus(&self) -> bool { + self.focus.path().is_some() + } + + /// The focused element's index. Unlike `RuntimeCore::node`, this finds it while it exits. + #[inline] + pub(in crate::runtime) fn focused_index(&self, nodes: &[crate::runtime::Node]) -> Option<usize> { + let path = self.focus.path()?; + nodes.iter().position(|n| n.path == path) + } + + #[inline] + pub(in crate::runtime) fn highlight_visible(&self, nodes: &[crate::runtime::Node], i: usize) -> bool { + self.focus.shown() && self.focus.is(&nodes[i].path) + } + + /// Focus is on node `i` or inside it (CSS `:focus-within`), however it got there. + #[inline] + pub(in crate::runtime) fn focus_within(&self, nodes: &[crate::runtime::Node], i: usize) -> bool { + let path = nodes[i].path.as_str(); + self.focus.path().is_some_and(|f| f.strip_prefix(path).is_some_and(|rest| rest.is_empty() || rest.starts_with('/'))) + } + + #[inline] + pub(super) fn tab_visits_all(&self) -> bool { + self.full_keyboard_access || self.tab_visits_controls + } + + #[inline] + pub(in crate::runtime) fn ime_took_key(&mut self) { + self.key_releases.ime_took_key(); + } + + #[inline] + pub(super) fn note_key_down(&mut self, composing: bool, repeat: bool) { + let focus = &self.focus; + self.key_releases.down(composing, repeat, || focus.owned()); + } + + #[inline] + pub(super) fn eat_ime_key_up(&mut self, composing: bool) -> bool { + self.key_releases.eat(composing) + } + + #[inline] + pub(super) fn route_key_release(&mut self) -> Option<String> { + self.key_releases.route() + } + + #[inline] + pub(super) fn composing_release(&mut self) { + self.key_releases.composing_release(); + } + + #[inline] + pub(super) fn key_releases_lost(&mut self) { + self.key_releases.lost(); + } + + #[inline] + pub(super) fn type_select_typed(&mut self, typed: &str, now: f64) -> &str { + self.type_select.typed(typed, now) + } + + #[inline] + pub(super) fn reset_type_select(&mut self) { + self.type_select.reset(); + } + + #[cfg(test)] + pub(super) fn age_type_select(&mut self, delta: f64) { + if let TypeSelect::Typing { at, .. } = &mut self.type_select { + *at -= delta; + } + } + + #[inline] + pub(super) fn set_focus_returned(&mut self, returned: bool) { + self.focus_returned = returned; + } + + #[inline] + pub(super) fn take_focus_returned(&mut self) -> bool { + std::mem::take(&mut self.focus_returned) + } + + /// Updates the last-reported modifiers and returns them if they changed. + #[inline] + pub(super) fn take_mods_changed(&mut self) -> Option<crate::Mods> { + if self.held_mods == self.mods_heard { return None; } + self.mods_heard = self.held_mods; + Some(self.mods_heard) + } +} diff --git a/app/vendor/rune/crates/rune/src/runtime/input/focus_tests.rs b/app/vendor/rune/crates/rune/src/runtime/input/focus_tests.rs new file mode 100644 index 0000000..7c0bacb --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/input/focus_tests.rs @@ -0,0 +1,970 @@ +use super::*; +use crate::{col, el, row, Mods}; + +#[derive(Default)] +struct State { open: bool, nested: bool, picks: usize, selected: usize, secondary_picks: usize } +fn button(key: &str) -> El { el().key(key).size(30.0, 30.0).focusable(true).role("button") } +fn view(s: &State, _: &mut Cx<State>) -> El { + let mut root = col().key("root").w_full().h_full() + .on_secondary_press(|s: &mut State, _, _| s.secondary_picks += 1) + .child(button("opener").on_press(|s: &mut State| s.open = true)) + .child(button("early").tab_index(1)) + .child(button("skip").tab_index(-1)) + .child(button("disabled").focusable(false)) + .child(col().key("radios").focus_group() + .children((0..3).map(|i| button(&format!("radio{i}")).role("radio").focus_selected(s.selected == i) + .focusable(i != 1).on_press(move |s: &mut State| { s.selected = i; s.picks += 1; })))); + if s.open { + root = root.child(col().key("modal").absolute(100.0, 0.0).size(100.0, 120.0) + .modal(true, |s: &mut State| s.open = false) + .child(button("one").on_press(|s: &mut State| s.nested = true)) + .child(button("two"))); + } + if s.open && s.nested { + root = root.child(col().key("nested").absolute(200.0, 0.0).size(90.0, 90.0) + .modal(false, |s: &mut State| s.nested = false).child(button("inner"))); + } + root +} +fn runtime() -> Runtime<State> { + let mut rt = Runtime::new(State::default(), view, (300.0, 300.0), Env::new(true, 2.0)); + rt.frame(0.0); rt +} +fn key(rt: &mut Runtime<State>, key: Key, shift: bool) { + rt.key(KeyEvent { key, mods: Mods { shift, ..Default::default() } }); rt.frame(0.0); +} +fn focused<S: 'static>(rt: &Runtime<S>) -> String { + rt.elements().into_iter().find(|e| e.focused).and_then(|e| e.key).unwrap() +} +#[test] +fn state_focus_routes_the_first_same_frame_key_to_a_new_field() { + use crate::{text_input, TextEdit, TextStyle}; + struct Form { first: TextEdit, next: TextEdit, open: bool, hidden: bool } + fn view(s: &Form, _: &mut Cx<Form>) -> El { + col().size(200.0, 100.0) + .child(text_input(&s.first, TextStyle::new(14.0, 400.0)).key("first").size(200.0, 40.0) + .on_edit(|s: &mut Form| &mut s.first)) + .children(s.open.then(|| text_input(&s.next, TextStyle::new(14.0, 400.0)).key("next").size(200.0, 40.0) + .opacity(if s.hidden { 0.0 } else { 1.0 }) + .on_edit(|s: &mut Form| &mut s.next))) + } + let mut first = TextEdit::new(""); first.focused = true; + let mut rt = Runtime::new(Form { first, next: TextEdit::new(""), open: false, hidden: false }, view, + (200.0, 100.0), Env { system_dark: true, scale: 1.0 }); + rt.frame(0.0); + rt.update(|s, _| { s.open = true; s.next.focused = true; }); + rt.key(KeyEvent { key: Key::Text("x".into()), mods: Mods::default() }); + rt.frame(0.0); + assert_eq!(focused(&rt), "next"); + assert_eq!(rt.state.next.text, "x", "the first key must not use the previous frame's focus"); + assert_eq!(rt.state.first.text, ""); + assert!(!rt.state.first.focused && rt.state.next.focused); + assert!(rt.ime_area.is_some()); + rt.update(|s, _| s.hidden = true); rt.frame(0.0); + assert!(rt.ime_area.is_none(), "authored hidden inputs must not enable IME"); +} + +#[test] +fn window_blur_keeps_the_composition_as_text_and_focus() { + fn view(s: &crate::TextEdit, _: &mut Cx<crate::TextEdit>) -> El { + crate::text_input(s, crate::TextStyle::new(14.0, 400.0)).key("field").size(200.0, 40.0) + .on_edit(|s: &mut crate::TextEdit| s) + } + let mut edit = crate::TextEdit::new("committed"); edit.focused = true; + let mut rt = Runtime::new(edit, view, (200.0, 40.0), Env::new(true, 1.0)); + rt.frame(0.0); + rt.ime(crate::Ime::Preedit("pending".into(), None, Vec::new())); rt.frame(0.0); + rt.edit.ime_reset = false; + rt.finish_composition(); rt.frame(0.0); + assert!(rt.state.preedit().is_none() && rt.state.focused && rt.edit.ime_reset); + assert_eq!(rt.state.text, "committedpending"); +} + +#[test] +fn unrealized_virtual_input_keeps_focus_and_does_not_steal_it_back() { + fn view(s: &Vec<crate::TextEdit>, _: &mut Cx<Vec<crate::TextEdit>>) -> El { + col().key("root").size(200.0, 240.0).child(button("other")) + .child(col().key("viewport").size(200.0, 200.0).scroll(ScrollSpec { stick_bottom: false }).clip_soft(0.0) + .child(col().key("rows").w_full().growth(GrowthSpec::default()).virtualize(40.0) + .children(s.iter().enumerate().map(|(i, edit)| { + crate::text_input(edit, crate::TextStyle::new(14.0, 400.0)) + .key(format!("row-{i}")).size(200.0, 40.0) + .on_edit(move |s: &mut Vec<crate::TextEdit>| &mut s[i]) + })))) + } + let mut state: Vec<_> = (0..100).map(|_| crate::TextEdit::new("")).collect(); + state[0].focused = true; + let mut rt = Runtime::new(state, view, (200.0, 240.0), Env::new(true, 1.0)); + rt.frame(0.0); + let path = rt.kbd.focus.owned(); + rt.wheel(100.0, 100.0, -2000.0); rt.frame(0.0); + assert!(rt.node(path.as_deref().unwrap()).is_none()); + assert_eq!(rt.kbd.focus.owned(), path); + rt.key(KeyEvent { key: Key::Text("offscreen".into()), mods: Mods::default() }); rt.frame(0.0); + assert_eq!(rt.state[0].text, "offscreen"); + let (x, y) = rt.find("other").unwrap(); + rt.pointer_down(x, y); rt.pointer_up(x, y); rt.frame(0.0); + assert!(!rt.state[0].focused); + rt.wheel(100.0, 100.0, 2000.0); rt.frame(0.0); + assert_eq!(focused(&rt), "other"); + assert!(rt.elements().iter().any(|e| e.key.as_deref() == Some("row-0"))); +} + +#[test] +fn input_handover_keeps_the_composition_and_keys_bubble_after_the_field() { + use crate::{text_input, TextEdit, TextStyle}; + struct Form { first: TextEdit, search: TextEdit, open: bool, app_keys: usize } + fn view(s: &Form, _: &mut Cx<Form>) -> El { + let mut root = col().size(300.0, 300.0) + .child(text_input(&s.first, TextStyle::new(14.0, 400.0)).key("first").size(200.0, 40.0) + .on_edit(|s: &mut Form| &mut s.first)) + .child(button("open").on_press(|s: &mut Form| { s.open = true; s.search.focused = true; })); + if s.open { + root = root.child(text_input(&s.search, TextStyle::new(14.0, 400.0)).key("search").size(200.0, 40.0) + .on_edit(|s: &mut Form| &mut s.search)); + } + root + } + let mut first = TextEdit::new("hello"); first.focused = true; + let mut rt = Runtime::new(Form { first, search: TextEdit::new(""), open: false, app_keys: 0 }, view, + (300.0, 300.0), Env::new(true, 1.0)); + rt.on_key = Some(|s, _, _| { s.app_keys += 1; true }); + rt.frame(0.0); + rt.ime(crate::Ime::Preedit("pending".into(), None, Vec::new())); rt.frame(0.0); + rt.state.open = true; rt.state.search.focused = true; rt.invalidate(); rt.frame(0.0); + assert!(rt.state.search.focused); + assert!(!rt.state.first.focused); + assert!(rt.state.first.preedit().is_none()); + assert!(rt.edit.ime_reset); + assert!(!rt.kbd.focus.keyboard()); + rt.key(KeyEvent { key: Key::Text("query".into()), mods: Mods::default() }); rt.frame(0.0); + assert_eq!(rt.state.search.text, "query"); + assert_eq!(rt.state.first.text, "hellopending"); + assert_eq!(rt.state.app_keys, 0); + rt.key(KeyEvent { key: Key::Function(5), mods: Mods::default() }); rt.frame(0.0); + assert_eq!(rt.state.app_keys, 1); + rt.ime(crate::Ime::Preedit("pending".into(), None, Vec::new())); rt.frame(0.0); + rt.pointer_down(290.0, 290.0); rt.pointer_up(290.0, 290.0); rt.frame(0.0); + assert!(rt.kbd.focus.path().is_none()); + assert!(!rt.state.search.focused); + assert!(rt.state.search.preedit().is_none()); +} + +#[test] +fn focus_document_order_overrides_roving_and_activation() { + let mut rt = runtime(); + key(&mut rt, Key::Tab, false); assert_eq!(focused(&rt), "early"); + key(&mut rt, Key::Tab, false); assert_eq!(focused(&rt), "opener"); + key(&mut rt, Key::Tab, false); assert_eq!(focused(&rt), "radio0"); + key(&mut rt, Key::Right, false); assert_eq!(focused(&rt), "radio2"); + assert_eq!((rt.state.selected, rt.state.picks), (2, 1)); + key(&mut rt, Key::Text(" ".into()), false); assert_eq!(rt.state.picks, 2); + key(&mut rt, Key::Tab, false); assert_eq!(focused(&rt), "early"); + key(&mut rt, Key::Tab, true); assert_eq!(focused(&rt), "radio2"); + let (x, y) = rt.find("early").unwrap(); + rt.pointer_down(x, y); rt.pointer_up(x, y); rt.frame(0.0); + assert_eq!(focused(&rt), "early"); + assert!(!rt.elements().iter().any(|e| e.focus_visible)); +} +#[test] +fn only_navigation_keys_show_focus_after_a_click() { + let mut rt = runtime(); + let (x, y) = rt.find("radio0").unwrap(); + rt.pointer_down(x, y); rt.pointer_up(x, y); rt.frame(0.0); + assert_eq!(focused(&rt), "radio0"); + for k in [Key::Text(" ".into()), Key::Escape, Key::Text("x".into())] { + key(&mut rt, k.clone(), false); + assert!(!rt.elements().iter().any(|e| e.focus_visible), "{k:?} after a click shows no ring"); + } + key(&mut rt, Key::Right, false); + assert!(rt.elements().iter().any(|e| e.focused && e.focus_visible), "an arrow shows it"); +} +#[test] +fn modal_traps_restores_nested_and_blocks_background() { + let mut rt = runtime(); + key(&mut rt, Key::Tab, false); key(&mut rt, Key::Tab, false); + key(&mut rt, Key::Text(" ".into()), false); assert_eq!(focused(&rt), "one"); + let (x, y) = rt.find("one").unwrap(); + rt.secondary_down(x, y); rt.secondary_up(x, y); rt.frame(0.0); + assert_eq!(rt.state.secondary_picks, 0, "secondary events must not bubble past a modal"); + key(&mut rt, Key::Tab, true); assert_eq!(focused(&rt), "two"); + key(&mut rt, Key::Tab, false); assert_eq!(focused(&rt), "one"); + key(&mut rt, Key::Text(" ".into()), false); assert_eq!(focused(&rt), "inner"); + let (x, y) = rt.find("opener").unwrap(); + rt.pointer_down(x, y); rt.pointer_up(x, y); rt.frame(0.0); + assert!(rt.state.nested); assert_eq!(focused(&rt), "inner"); + key(&mut rt, Key::Escape, false); assert_eq!(focused(&rt), "one"); + key(&mut rt, Key::Escape, false); assert_eq!(focused(&rt), "opener"); + assert!(!rt.state.open); + key(&mut rt, Key::Text(" ".into()), false); + rt.state.nested = false; rt.invalidate(); rt.frame(0.0); + rt.pointer_down(5.0, 280.0); rt.pointer_up(5.0, 280.0); rt.frame(0.0); + assert!(!rt.state.open); assert_eq!(focused(&rt), "opener"); + assert!(!rt.elements().iter().any(|e| e.focus_visible)); +} + +#[test] +fn a_modal_whose_field_opens_focused_returns_focus_to_the_opener() { + use crate::{text_input, TextEdit, TextStyle}; + #[derive(Default)] + struct Form { open: bool, field: TextEdit } + fn view(s: &Form, _: &mut Cx<Form>) -> El { + col().key("root").size(300.0, 300.0) + .child(button("opener").on_press(|s: &mut Form| { s.open = true; s.field.focused = true; })) + .children(s.open.then(|| col().key("sheet").absolute(100.0, 0.0).size(150.0, 100.0) + .modal(true, |s: &mut Form| s.open = false) + .child(text_input(&s.field, TextStyle::new(14.0, 400.0)).key("field").size(120.0, 30.0) + .on_edit(|s: &mut Form| &mut s.field)))) + } + for escape in [false, true] { + let mut rt = Runtime::new(Form::default(), view, (300.0, 300.0), Env::new(true, 1.0)); + rt.frame(0.0); + let (x, y) = rt.find("opener").unwrap(); + rt.pointer_down(x, y); rt.pointer_up(x, y); rt.frame(0.0); + assert!(rt.state.open); + let now = |rt: &Runtime<Form>| rt.elements().into_iter().find(|e| e.focused).and_then(|e| e.key); + assert_eq!(now(&rt).as_deref(), Some("field"), "the field's own focus request wins inside the modal"); + if escape { press(&mut rt, Key::Escape) } else { rt.update(|s, _| s.open = false); rt.frame(0.0); } + assert!(!rt.state.open); + assert_eq!(now(&rt).as_deref(), Some("opener"), "closing (escape: {escape}) returns focus to the opener"); + if escape { assert!(!rt.state.field.focused, "Escape blurs the field before it goes"); } + } +} + +#[test] +fn closing_a_modal_keeps_a_focus_request_outside_it() { + use crate::{text_input, TextEdit, TextStyle}; + #[derive(Default)] + struct Form { open: bool, field: TextEdit, search: TextEdit } + fn view(s: &Form, _: &mut Cx<Form>) -> El { + col().key("root").size(300.0, 300.0) + .child(button("opener").on_press(|s: &mut Form| { s.open = true; s.field.focused = true; })) + .child(text_input(&s.search, TextStyle::new(14.0, 400.0)).key("search").size(120.0, 30.0) + .on_edit(|s: &mut Form| &mut s.search)) + .children(s.open.then(|| col().key("sheet").absolute(100.0, 100.0).size(150.0, 100.0) + .modal(true, |s: &mut Form| s.open = false) + .child(text_input(&s.field, TextStyle::new(14.0, 400.0)).key("field").size(120.0, 30.0) + .on_edit(|s: &mut Form| &mut s.field)))) + } + let mut rt = Runtime::new(Form::default(), view, (300.0, 300.0), Env::new(true, 1.0)); + rt.frame(0.0); + let (x, y) = rt.find("opener").unwrap(); + rt.pointer_down(x, y); rt.pointer_up(x, y); rt.frame(0.0); + assert_eq!(focused(&rt), "field"); + rt.update(|s, _| { s.open = false; s.field.focused = false; s.search.focused = true; }); + rt.frame(0.0); + assert_eq!(focused(&rt), "search", "the handler's focus request outside the modal wins over the opener"); + assert!(rt.state.search.focused); + // The same when the sheet goes in the frame, with no exit. + rt.update(|s, _| { s.search.focused = false; s.open = true; s.field.focused = true; }); + rt.frame(0.0); + let now = |rt: &Runtime<Form>| rt.elements().into_iter().find(|e| e.focused).and_then(|e| e.key); + assert_eq!(now(&rt).as_deref(), Some("field")); + rt.update(|s, tx| { tx.instant(); s.open = false; s.field.focused = false; s.search.focused = true; }); + rt.frame(0.0); + assert_eq!(now(&rt).as_deref(), Some("search"), "an instant close keeps the request too"); + assert!(rt.state.search.focused); +} + +#[test] +fn a_sized_focus_return_leaf_does_not_claim_its_siblings() { + fn view(open: &bool, _: &mut Cx<bool>) -> El { + col().size(300.0, 300.0).child(button("opener")).child(button("sibling")) + .children(open.then(|| el().key("marker").size(10.0, 10.0).focus_return("opener"))) + } + let mut rt = Runtime::new(true, view, (300.0, 300.0), Env::new(true, 1.0)); + rt.frame(0.0); + let (x, y) = rt.find("sibling").unwrap(); + rt.pointer_down(x, y); rt.pointer_up(x, y); rt.frame(0.0); + assert_eq!(focused(&rt), "sibling"); + rt.update(|open, _| *open = false); rt.frame(0.0); + assert_eq!(focused(&rt), "sibling", "only zero-size sentinels use their parent's scope"); +} + +#[test] +fn scrim_return_survives_pointer_down_blur_but_not_explicit_blur() { + struct Popup { open: bool, field: crate::TextEdit } + fn view(s: &Popup, _: &mut Cx<Popup>) -> El { + col().size(300.0, 300.0).child(button("opener")) + .children(s.open.then(|| col().key("popup").focus_return("opener") + .child(crate::text_input(&s.field, crate::TextStyle::new(14.0, 400.0)) + .key("field").size(100.0, 30.0).on_edit(|s: &mut Popup| &mut s.field)))) + .child(el().key("scrim").size(100.0, 30.0).on_press(|s: &mut Popup| s.open = false)) + } + for explicit in [false, true] { + let mut field = crate::TextEdit::new("text"); field.focused = true; + let mut rt = Runtime::new(Popup { open: true, field }, view, (300.0, 300.0), Env::new(true, 1.0)); + rt.frame(0.0); + assert_eq!(focused(&rt), "field"); + let (x, y) = rt.find("scrim").unwrap(); + rt.pointer_down(x, y); rt.frame(0.0); + assert!(rt.kbd.focus.path().is_none(), "pointer-down blurs before pointer-up closes"); + if explicit { rt.update(|_, tx| tx.blur()); rt.frame(0.0); } + rt.pointer_up(x, y); rt.frame(0.0); + assert!(!rt.state.open); + assert_eq!(rt.kbd.focus.path().is_some(), !explicit); + if !explicit { assert_eq!(focused(&rt), "opener"); } + } +} + +/// One state for the key routing tests: each state type builds a whole `Runtime<S>`. +#[derive(Default)] +struct Keys { + pane: usize, seen: Vec<Option<String>>, field: crate::TextEdit, named: crate::TextEdit, + sheet: bool, page: bool, value: i32, steps: Vec<i32>, log: Vec<&'static str>, app: Vec<Key>, +} + +#[derive(Default)] +struct Menu { open: bool, checked: Option<usize>, picks: Vec<usize>, follows: bool, search: bool, field: crate::TextEdit } +const ITEMS: [&str; 4] = ["Alpha", "Beta", "Bravo", "Charlie"]; +fn menu_view(s: &Menu, _: &mut Cx<Menu>) -> El { + let mut root = col().key("root").size(300.0, 300.0) + .child(button("popup").role("combobox").on_press(|s: &mut Menu| s.open = true)) + .child(button("plain")); + if s.open { + let mut list = col().key("menu").role("menu").focus_group(); + if s.follows { list = list.focus_follows(); } + root = root.child(col().key("surface").absolute(100.0, 100.0).focus_return("popup") + .modal(true, |s: &mut Menu| s.open = false) + .children(s.search.then(|| crate::text_input(&s.field, crate::TextStyle::new(14.0, 400.0)) + .key("field").size(80.0, 20.0).on_edit(|s: &mut Menu| &mut s.field))) + .child(list.children(ITEMS.iter().enumerate().map(|(i, label)| { + el().key(*label).label(*label).size(80.0, 20.0).focusable(true) + .focus_selected(s.checked == Some(i)).focus_highlight(crate::Color::WHITE) + .on_press(move |s: &mut Menu| { s.picks.push(i); s.open = s.follows; }) + })))); + } + root +} +fn menu_runtime(state: Menu) -> Runtime<Menu> { + let mut rt = Runtime::new(state, menu_view, (300.0, 300.0), Env::new(true, 1.0)); + rt.frame(0.0); rt +} +fn press<S: 'static>(rt: &mut Runtime<S>, key: Key) { + rt.key(KeyEvent { key, mods: Mods::default() }); rt.frame(0.0); +} +fn highlighted(rt: &Runtime<Menu>) -> Option<String> { + (0..rt.tree.nodes.len()).find(|&i| rt.tree.nodes[i].focus.highlight.is_some() && rt.highlight_visible(i)) + .and_then(|i| rt.tree.nodes[i].key.clone()) +} + +#[test] +fn menu_arrows_wrap_vertically_and_return_focus_on_escape() { + let mut rt = menu_runtime(Menu::default()); + let (x, y) = rt.find("popup").unwrap(); + rt.pointer_down(x, y); rt.pointer_up(x, y); rt.frame(0.0); + assert_eq!(focused(&rt), "Alpha"); + assert_eq!(highlighted(&rt), None, "a pointer-opened menu shows no highlight yet"); + press(&mut rt, Key::Enter); + assert!(rt.state.open && rt.state.picks.is_empty(), "Return chooses no hidden highlight"); + press(&mut rt, Key::Down); + assert_eq!(highlighted(&rt).as_deref(), Some("Alpha"), "the first arrow reveals the highlight"); + press(&mut rt, Key::Down); assert_eq!(focused(&rt), "Beta"); + press(&mut rt, Key::Right); assert_eq!(focused(&rt), "Beta", "Left and Right do not move in a menu"); + press(&mut rt, Key::End); assert_eq!(focused(&rt), "Charlie"); + press(&mut rt, Key::Down); assert_eq!(focused(&rt), "Alpha"); + press(&mut rt, Key::Up); assert_eq!(focused(&rt), "Charlie"); + press(&mut rt, Key::Home); assert_eq!(focused(&rt), "Alpha"); + assert!(rt.state.picks.is_empty(), "moving does not choose"); + press(&mut rt, Key::Escape); + assert!(!rt.state.open); + assert_eq!(focused(&rt), "popup"); +} + +#[test] +fn a_hidden_highlight_appears_on_the_checked_item_or_from_the_end() { + let mut rt = menu_runtime(Menu { open: true, checked: Some(2), ..Default::default() }); + assert_eq!(focused(&rt), "Bravo", "a popup opens on its checked item"); + press(&mut rt, Key::Up); + assert_eq!(focused(&rt), "Bravo"); + let mut rt = menu_runtime(Menu { open: true, ..Default::default() }); + press(&mut rt, Key::Up); + assert_eq!(focused(&rt), "Charlie", "Up into an unchecked menu starts from the bottom"); +} + +#[test] +fn type_select_matches_prefixes_and_cycles_a_repeated_letter() { + let mut rt = menu_runtime(Menu { open: true, ..Default::default() }); + press(&mut rt, Key::Text("b".into())); assert_eq!(focused(&rt), "Beta"); + press(&mut rt, Key::Text("r".into())); assert_eq!(focused(&rt), "Bravo"); + rt.kbd.age_type_select(focus_machine::TYPE_SELECT_PAUSE + 0.1); + press(&mut rt, Key::Text("c".into())); assert_eq!(focused(&rt), "Charlie", "a pause starts a new prefix"); + rt.kbd.age_type_select(focus_machine::TYPE_SELECT_PAUSE + 0.1); + press(&mut rt, Key::Text("b".into())); assert_eq!(focused(&rt), "Beta"); + press(&mut rt, Key::Text("b".into())); assert_eq!(focused(&rt), "Bravo"); + press(&mut rt, Key::Text("b".into())); assert_eq!(focused(&rt), "Beta"); + press(&mut rt, Key::Enter); + assert_eq!(rt.state.picks, [1]); + assert!(!rt.state.open); +} + +#[test] +fn pointer_and_keys_share_one_highlight_but_fields_keep_focus() { + let mut rt = menu_runtime(Menu { open: true, ..Default::default() }); + let (x, y) = rt.find("Bravo").unwrap(); + rt.pointer_move(x, y); rt.frame(0.0); + assert_eq!(highlighted(&rt).as_deref(), Some("Bravo")); + assert!(!rt.elements().iter().any(|e| e.focus_visible), "a pointer highlight is not a focus ring"); + press(&mut rt, Key::Down); assert_eq!(highlighted(&rt).as_deref(), Some("Charlie")); + rt.pointer_move(5.0, 290.0); rt.frame(0.0); + assert_eq!(highlighted(&rt).as_deref(), Some("Charlie"), "leaving rows keeps a keyboard highlight"); + + let mut rt = menu_runtime(Menu { open: true, search: true, ..Default::default() }); + assert_eq!(focused(&rt), "field"); + let (x, y) = rt.find("Beta").unwrap(); + rt.pointer_move(x, y); rt.frame(0.0); + assert_eq!(focused(&rt), "field", "hovering results never takes focus from their search field"); +} + +#[test] +fn follows_presses_as_it_moves_and_popups_open_on_arrows() { + let mut rt = menu_runtime(Menu { follows: true, ..Default::default() }); + press(&mut rt, Key::Tab); assert_eq!(focused(&rt), "popup"); + press(&mut rt, Key::Down); + assert!(rt.state.open, "Down opens a popup button"); + assert_eq!(focused(&rt), "Alpha"); + press(&mut rt, Key::Down); press(&mut rt, Key::Down); + assert_eq!(rt.state.picks, [1, 2], "each move presses the item it reaches"); +} + +#[test] +fn without_full_keyboard_access_tab_visits_only_fields_and_lists() { + use crate::{text_input, TextEdit, TextStyle}; + fn view(s: &TextEdit, _: &mut Cx<TextEdit>) -> El { + col().size(200.0, 200.0) + .child(text_input(s, TextStyle::new(14.0, 400.0)).key("field").size(200.0, 30.0).on_edit(|s: &mut TextEdit| s)) + .child(button("button")) + .child(col().role("list").focus_group().child(button("row0").focus_selected(true)).child(button("row1"))) + } + let mut rt = Runtime::new(TextEdit::new(""), view, (200.0, 200.0), Env::new(true, 1.0)); + rt.frame(0.0); + rt.set_full_keyboard_access(false); + press(&mut rt, Key::Tab); assert_eq!(focused(&rt), "field"); + press(&mut rt, Key::Tab); assert_eq!(focused(&rt), "row0", "buttons are skipped, lists are not"); + press(&mut rt, Key::Tab); assert_eq!(focused(&rt), "field"); + rt.set_full_keyboard_access(true); + press(&mut rt, Key::Tab); assert_eq!(focused(&rt), "button"); + rt.set_full_keyboard_access(false); + rt.set_tab_visits_controls(true); + press(&mut rt, Key::Tab); assert_eq!(focused(&rt), "row0"); + press(&mut rt, Key::Tab); assert_eq!(focused(&rt), "field"); + press(&mut rt, Key::Tab); assert_eq!(focused(&rt), "button", "the app's opt-in wins over the system setting"); +} + +#[test] +fn on_key_tells_a_key_nothing_focused_had_from_one_a_control_passed_on() { + fn view(_: &Keys, _: &mut Cx<Keys>) -> El { + col().size(200.0, 200.0).child(button("switch")).child(el().size(30.0, 30.0).focusable(true)) + } + let mut rt = Runtime::new(Keys::default(), view, (200.0, 200.0), Env::new(true, 1.0)); + rt.on_key = Some(|s, ev, tx| { + s.seen.push(tx.focused().map(str::to_owned)); + // System Settings: plain Down changes the pane only while no control has focus. + if ev.key == Key::Down && tx.focused().is_none() { s.pane += 1; return true; } + false + }); + rt.frame(0.0); + press(&mut rt, Key::Down); + assert_eq!(rt.state.pane, 1); + press(&mut rt, Key::Tab); + assert_eq!(focused(&rt), "switch"); + press(&mut rt, Key::Down); + assert_eq!(rt.state.pane, 1, "Down the focused switch passed on doesn't change the pane"); + press(&mut rt, Key::Tab); + press(&mut rt, Key::Down); + // The first Tab reaches on_key before focus moves; the second never does. + assert_eq!(rt.state.seen, [None, None, Some("switch".into()), Some("#1".into())]); +} + +#[test] +fn a_control_without_a_ring_draws_the_default_one_from_the_keyboard_only() { + fn view(s: &crate::TextEdit, _: &mut Cx<crate::TextEdit>) -> El { + let control = |key: &str| el().key(key).size(40.0, 20.0).radius(6.0).fill(crate::Color::WHITE).focusable(true); + let field = crate::text_input(s, crate::TextStyle::new(14.0, 400.0)).key("field").size(80.0, 20.0) + .on_edit(|s: &mut crate::TextEdit| s); + let menu = col().key("menu").role("menu").focus_group().child(control("item")); + col().padding(20.0).gap(10.0).items_start() + .child(control("plain")) + .child(control("off").no_focus_ring()) + .child(control("own").child(el().key("knob").size(10.0, 10.0).focus_ring(2.0, 1.0, crate::Color::BLACK))) + .child(field) + .child(menu) + } + let mut rt = Runtime::new(crate::TextEdit::new(""), view, (200.0, 300.0), Env::new(true, 1.0)); + rt.set_tab_visits_controls(true); + rt.frame(0.0); + let rings = |rt: &Runtime<crate::TextEdit>| -> Vec<([f32; 4], [f32; 4], f32)> { + rt.instances.iter().filter(|i| i.fill == [0.0; 4] && i.border[3] > 0.0 && i.params[1] == KIND_RECT) + .map(|i| (i.rect, i.border, i.radii[0])).collect() + }; + assert!(rings(&rt).is_empty()); + rt.pointer_down(30.0, 30.0); rt.pointer_up(30.0, 30.0); rt.frame(0.0); + assert_eq!(focused(&rt), "plain"); + assert!(rings(&rt).is_empty(), "a click focuses without a ring"); + let tab_to = |rt: &mut Runtime<crate::TextEdit>, key: &str| { + for _ in 0..10 { press(rt, Key::Tab); if focused(rt) == key { return; } } + panic!("Tab never reached {key}"); + }; + tab_to(&mut rt, "plain"); + let focus = crate::SystemAccent::DEFAULT.focus(true).premul(1.0); + assert_eq!(rings(&rt), [([17.0, 17.0, 46.0, 26.0], focus, 9.0)], "3 points outside, radii grown by 3"); + tab_to(&mut rt, "off"); + assert!(rings(&rt).is_empty(), "no_focus_ring"); + tab_to(&mut rt, "own"); + assert_eq!(rings(&rt).len(), 1, "a child's ring replaces the default one"); + assert_eq!(rings(&rt)[0].1, crate::Color::BLACK.premul(1.0)); + tab_to(&mut rt, "field"); + assert!(rings(&rt).is_empty(), "the caret shows a field's focus"); + tab_to(&mut rt, "item"); + assert!(rings(&rt).is_empty(), "a menu item's highlight shows its focus"); +} + +#[test] +fn return_presses_the_default_button_and_space_the_focused_one() { + fn view(s: &Keys, _: &mut Cx<Keys>) -> El { + let style = crate::TextStyle::new(14.0, 400.0); + let mut root = col().size(300.0, 300.0) + .child(crate::text_input(&s.field, style).key("field").size(100.0, 20.0).on_edit(|s: &mut Keys| &mut s.field)) + .child(crate::text_input(&s.named, style).key("named").size(100.0, 20.0).on_edit(|s: &mut Keys| &mut s.named) + .on_submit(|s: &mut Keys, _| s.log.push("submit"))) + .child(col().key("list").role("listbox").focus_group() + .child(button("row").on_press(|s: &mut Keys| s.log.push("row")))) + .child(button("later").on_press(|s: &mut Keys| s.log.push("later"))) + .child(button("continue").default_button().on_press(|s: &mut Keys| s.log.push("continue"))) + .child(button("hidden").default_button().opacity(0.0).on_press(|s: &mut Keys| s.log.push("hidden"))); + if s.sheet { + root = root.child(col().key("sheet").absolute(150.0, 0.0).size(100.0, 100.0) + .modal(true, |s: &mut Keys| s.sheet = false) + .child(button("cancel").on_press(|s: &mut Keys| s.sheet = false)) + .child(button("done").default_button().on_press(|s: &mut Keys| { s.log.push("done"); s.sheet = false; }))); + } + root + } + let mut rt = Runtime::new(Keys::default(), view, (300.0, 300.0), Env::new(true, 1.0)); + rt.on_key = Some(|s, ev, _| { if ev.key == Key::Enter { s.log.push("on_key"); } false }); + rt.frame(0.0); + let log = |rt: &mut Runtime<Keys>| std::mem::take(&mut rt.state.log); + hold(&mut rt, Key::Enter); + assert_eq!(log(&mut rt), ["continue"], "nothing focused: the default button, once per press"); + let tab_to = |rt: &mut Runtime<Keys>, key: &str| { + for _ in 0..10 { press(rt, Key::Tab); if focused(rt) == key { return; } } + panic!("Tab never reached {key}"); + }; + tab_to(&mut rt, "later"); + press(&mut rt, Key::Enter); + press(&mut rt, Key::Text(" ".into())); + assert_eq!(log(&mut rt), ["continue", "later"], "Return passes a focused button by; Space presses it"); + rt.key(KeyEvent { key: Key::Enter, mods: Mods { shift: true, ..Mods::default() } }); rt.frame(0.0); + assert_eq!(log(&mut rt), ["on_key"], "a modified Return isn't the default button's"); + tab_to(&mut rt, "field"); + press(&mut rt, Key::Enter); + assert_eq!(log(&mut rt), ["continue"], "a field with nothing to submit"); + tab_to(&mut rt, "named"); + press(&mut rt, Key::Enter); + assert_eq!(log(&mut rt), ["submit"]); + tab_to(&mut rt, "row"); + press(&mut rt, Key::Enter); + assert_eq!(log(&mut rt), ["row"], "a list row takes Return"); + rt.state.sheet = true; rt.invalidate(); rt.frame(0.0); + press(&mut rt, Key::Enter); + assert_eq!(log(&mut rt), ["done"], "a modal's default button, not the one behind it"); + assert!(!rt.state.sheet); +} + +#[test] +fn a_focused_slider_steps_on_arrows_and_pages_and_jumps_on_home_and_end() { + fn view(s: &Keys, _: &mut Cx<Keys>) -> El { + let slider = el().key("volume").size(100.0, 20.0) + .on_step(|s: &mut Keys, delta, _| { s.steps.push(delta); s.value = (s.value + delta).clamp(0, 100); }); + let slider = if s.page { slider } else { slider.on_step_limit(|s: &mut Keys, max, _| s.value = if max { 100 } else { 0 }) }; + col().size(200.0, 200.0).child(row().role("toolbar").focus_group().child(button("before")).child(slider)) + } + let mut rt = Runtime::new(Keys { value: 50, ..Keys::default() }, view, (200.0, 200.0), Env::new(true, 1.0)); + rt.on_key = Some(|s, ev, _| { s.app.push(ev.key.clone()); false }); + rt.set_tab_visits_controls(true); + rt.frame(0.0); + assert_eq!(rt.elements().into_iter().find(|e| e.key.as_deref() == Some("volume")).unwrap().role, "slider"); + press(&mut rt, Key::Tab); + assert_eq!(focused(&rt), "before"); + press(&mut rt, Key::Right); + assert_eq!(focused(&rt), "volume", "on_step makes it focusable"); + assert!(rt.state.steps.is_empty()); + for key in [Key::Left, Key::Down, Key::Right, Key::Up, Key::PageDown, Key::PageUp] { press(&mut rt, key); } + assert_eq!(std::mem::take(&mut rt.state.steps), [-1, -1, 1, 1, -10, 10]); + assert_eq!(focused(&rt), "volume", "the toolbar's arrows don't take focus off it"); + hold(&mut rt, Key::Right); + assert_eq!((std::mem::take(&mut rt.state.steps), rt.state.value), (vec![1, 1, 1], 53), "held arrows repeat"); + press(&mut rt, Key::End); + assert_eq!(rt.state.value, 100); + press(&mut rt, Key::Home); + assert_eq!(rt.state.value, 0); + rt.state.page = true; rt.invalidate(); rt.frame(0.0); + rt.state.app.clear(); + rt.state.value = 50; + press(&mut rt, Key::Home); + assert_eq!(rt.state.value, 50, "without on_step_limit Home and End aren't the slider's"); + assert_eq!(focused(&rt), "volume", "nor the toolbar's: they go on to the app"); + rt.key(KeyEvent { key: Key::Right, mods: Mods { shift: true, ..Mods::default() } }); rt.frame(0.0); + assert!(rt.state.steps.is_empty(), "a modified arrow isn't a step"); + assert_eq!(focused(&rt), "volume", "and doesn't move the toolbar's focus"); + assert_eq!(std::mem::take(&mut rt.state.app), [Key::Home, Key::Right]); +} + +#[test] +fn shift_modified_keys_past_tab_go_to_the_app_and_press_nothing() { + fn view(_: &Keys, _: &mut Cx<Keys>) -> El { + col().size(200.0, 200.0) + .child(button("go").on_press(|s: &mut Keys| s.log.push("go"))) + .child(col().key("list").role("listbox").focus_group() + .child(button("apple").label("apple").on_press(|s: &mut Keys| s.log.push("apple"))) + .child(button("banana").label("banana").on_press(|s: &mut Keys| s.log.push("banana")))) + } + let mut rt = Runtime::new(Keys::default(), view, (200.0, 200.0), Env::new(true, 1.0)); + rt.on_key = Some(|s, ev, _| { s.app.push(ev.key.clone()); false }); + rt.set_tab_visits_controls(true); + rt.frame(0.0); + let shifted = |rt: &mut Runtime<Keys>, key: Key| { + rt.key(KeyEvent { key, mods: Mods { shift: true, ..Mods::default() } }); rt.frame(0.0); + }; + press(&mut rt, Key::Tab); + assert_eq!(focused(&rt), "go"); + shifted(&mut rt, Key::Text(" ".into())); + press(&mut rt, Key::Tab); + assert_eq!(focused(&rt), "apple"); + shifted(&mut rt, Key::Enter); + shifted(&mut rt, Key::Down); + assert_eq!(focused(&rt), "apple", "Shift-Down is the app's (to extend a selection, say)"); + assert!(rt.state.log.is_empty(), "Shift-Space and Shift-Return press nothing"); + assert_eq!(rt.state.app, [Key::Tab, Key::Text(" ".into()), Key::Enter, Key::Down], "the first Tab found nothing focused"); + shifted(&mut rt, Key::Text("B".into())); + assert_eq!(focused(&rt), "banana", "a capital still type-selects"); + shifted(&mut rt, Key::Tab); + assert_eq!(focused(&rt), "go", "Shift-Tab still goes back"); +} + +#[test] +fn return_and_escape_confirm_and_cancel_a_composition_and_nothing_else() { + fn view(s: &Keys, _: &mut Cx<Keys>) -> El { + let style = crate::TextStyle::new(14.0, 400.0); + col().size(300.0, 300.0) + .child(crate::text_input(&s.field, style).key("field").size(100.0, 20.0).on_edit(|s: &mut Keys| &mut s.field)) + .child(crate::text_input(&s.named, style).key("named").size(100.0, 20.0).on_edit(|s: &mut Keys| &mut s.named) + .on_submit(|s: &mut Keys, _| s.log.push("submit"))) + .child(button("continue").default_button().on_press(|s: &mut Keys| s.log.push("continue"))) + } + let mut rt = Runtime::new(Keys::default(), view, (300.0, 300.0), Env::new(true, 1.0)); + rt.on_key = Some(|s, ev, _| { if ev.key == Key::Escape { s.log.push("escape"); } false }); + rt.frame(0.0); + for (field, after) in [("field", "continue"), ("named", "submit")] { + for _ in 0..4 { if rt.elements().iter().any(|e| e.focused && e.key.as_deref() == Some(field)) { break; } press(&mut rt, Key::Tab); } + assert_eq!(focused(&rt), field); + rt.ime(crate::Ime::Preedit("ka".into(), None, Vec::new())); rt.frame(0.0); + press(&mut rt, Key::Enter); + press(&mut rt, Key::Escape); + assert!(rt.state.log.is_empty(), "{field}: the composition's Return and Escape: {:?}", rt.state.log); + assert_eq!(focused(&rt), field, "Escape cancels the composition, not the field's focus"); + rt.ime(crate::Ime::Commit("か".into())); rt.frame(0.0); + press(&mut rt, Key::Enter); + assert_eq!(std::mem::take(&mut rt.state.log), [after], "{field}: Return once it's committed"); + } + assert_eq!((rt.state.field.text.as_str(), rt.state.named.text.as_str()), ("か", "か")); +} + +#[test] +fn a_focused_link_draws_no_default_ring_and_is_what_tx_focused_names() { + fn view(_: &Keys, _: &mut Cx<Keys>) -> El { + let text = "see the docs"; + col().size(300.0, 100.0).child(crate::rich(text, Vec::new()).key("para").w(200.0) + .link(crate::Link::new(8..12, "docs")) + .on_link(|_: &mut Keys, _, _| {})) + } + let mut rt = Runtime::new(Keys::default(), view, (300.0, 100.0), Env::new(true, 1.0)); + rt.on_key = Some(|s, _, tx| { s.seen.push(tx.focused().map(str::to_owned)); false }); + rt.set_tab_visits_controls(true); + rt.frame(0.0); + press(&mut rt, Key::Tab); + let link = rt.elements().into_iter().find(|e| e.focused).unwrap(); + assert_eq!(link.key.as_deref(), Some("docs")); + let rings = rt.instances.iter().filter(|i| i.fill == [0.0; 4] && i.border[3] > 0.0 && i.params[1] == KIND_RECT).count(); + assert_eq!(rings, 0, "the link's own look shows its focus, not a ring round the paragraph"); + assert_eq!(rt.state.seen, [None], "Tab with nothing focused"); + press(&mut rt, Key::Text("x".into())); + assert_eq!(rt.state.seen, [None, Some("docs".to_owned())]); +} + +#[test] +fn keyboard_focus_scrolls_into_view() { + fn view(_: &State, _: &mut Cx<State>) -> El { + col().key("root").size(200.0, 200.0).child(button("before")) + .child(col().key("viewport").size(200.0, 100.0).scroll(ScrollSpec { stick_bottom: false }).clip_soft(0.0) + .child(col().role("list").focus_group().children((0..10).map(|i| button(&format!("row{i}")))))) + .child(button("after")) + } + let mut rt = Runtime::new(State::default(), view, (200.0, 200.0), Env::new(true, 1.0)); + rt.frame(0.0); + let visible = |rt: &Runtime<State>, key: &str| { + let (_, y) = rt.find(key).unwrap(); + let (_, top) = rt.find("viewport").unwrap(); + (top - 50.0..=top + 50.0).contains(&y) + }; + assert!(!visible(&rt, "row9")); + key(&mut rt, Key::Tab, false); key(&mut rt, Key::Tab, false); + key(&mut rt, Key::End, false); + assert_eq!(focused(&rt), "row9"); + assert!(visible(&rt, "row9"), "arrows reveal the row they reach"); + key(&mut rt, Key::Tab, false); key(&mut rt, Key::Tab, true); + key(&mut rt, Key::Home, false); + assert!(visible(&rt, "row0")); + rt.wheel(100.0, 100.0, -2000.0); rt.frame(0.0); + key(&mut rt, Key::Tab, true); key(&mut rt, Key::Tab, false); + assert_eq!(focused(&rt), "row0"); + assert!(visible(&rt, "row0"), "Tab reveals the control it reaches"); +} + +#[test] +fn list_arrows_stop_at_the_ends() { + fn view(_: &State, _: &mut Cx<State>) -> El { + col().size(200.0, 200.0) + .child(col().role("list").focus_group().children((0..3).map(|i| button(&format!("row{i}"))))) + } + let mut rt = Runtime::new(State::default(), view, (200.0, 200.0), Env::new(true, 1.0)); + rt.frame(0.0); + key(&mut rt, Key::Tab, false); + assert_eq!(focused(&rt), "row0"); + key(&mut rt, Key::Up, false); + assert_eq!(focused(&rt), "row0", "Up from the first row stays"); + key(&mut rt, Key::End, false); + key(&mut rt, Key::Down, false); + assert_eq!(focused(&rt), "row2", "Down from the last row stays"); + key(&mut rt, Key::Up, false); + assert_eq!(focused(&rt), "row1"); +} + +#[test] +fn focus_follows_an_app_selection_in_a_source_list() { + fn view(s: &State, _: &mut Cx<State>) -> El { + col().size(200.0, 200.0).child(col().role("list").focus_group().focus_follows().children((0..3).map(|i| { + button(&format!("row{i}")).focus_selected(s.selected == i).on_press(move |s: &mut State| s.selected = i) + }))) + } + let mut rt = Runtime::new(State::default(), view, (200.0, 200.0), Env::new(true, 1.0)); + rt.frame(0.0); + key(&mut rt, Key::Tab, false); + assert_eq!(focused(&rt), "row0"); + rt.update(|s, _| s.selected = 2); + rt.frame(0.0); + assert_eq!(focused(&rt), "row2", "a shortcut's selection takes the focus with it"); + assert!(rt.elements().iter().any(|e| e.focused && e.focus_visible), "and keeps the keyboard ring"); + key(&mut rt, Key::Up, false); + assert_eq!((focused(&rt).as_str(), rt.state.selected), ("row1", 1)); +} + +#[derive(Default)] +struct Held { presses: usize, opens: usize, menu: bool, picks: Vec<usize>, modals: u8, submits: usize, app: usize, field: crate::TextEdit } +fn held_view(s: &Held, _: &mut Cx<Held>) -> El { + let mut root = col().key("root").size(300.0, 300.0) + .child(button("press").on_press(|s: &mut Held| s.presses += 1)) + .child(button("popup").role("combobox").on_press(|s: &mut Held| { s.opens += 1; s.menu = !s.menu; })) + .child(crate::text_input(&s.field, crate::TextStyle::new(14.0, 400.0)).single_line().key("field").size(80.0, 20.0) + .on_edit(|s: &mut Held| &mut s.field).on_submit(|s: &mut Held, _| s.submits += 1)) + .child(button("plain")); + if s.menu { + root = root.child(col().key("surface").absolute(100.0, 100.0).focus_return("popup") + .modal(true, |s: &mut Held| s.menu = false) + .child(col().key("menu").role("menu").focus_group().children(ITEMS.iter().enumerate().map(|(i, label)| { + el().key(*label).label(*label).size(80.0, 20.0).focusable(true).focus_highlight(crate::Color::WHITE) + .on_press(move |s: &mut Held| { s.picks.push(i); s.menu = false; }) + })))); + } + if s.modals >= 1 { + root = root.child(col().key("one").absolute(0.0, 150.0).size(100.0, 100.0) + .modal(true, |s: &mut Held| s.modals -= 1).child(button("in-one"))); + } + if s.modals >= 2 { + root = root.child(col().key("two").absolute(150.0, 150.0).size(100.0, 100.0) + .modal(true, |s: &mut Held| s.modals -= 1).child(button("in-two"))); + } + root +} +fn held_runtime(state: Held) -> Runtime<Held> { + let mut rt = Runtime::new(state, held_view, (300.0, 300.0), Env::new(true, 1.0)); + rt.on_key = Some(|s, _, _| { s.app += 1; false }); + rt.frame(0.0); rt +} +/// A first press and two auto-repeats. +fn hold<S: 'static>(rt: &mut Runtime<S>, key: Key) { + rt.key(KeyEvent { key: key.clone(), mods: Mods::default() }); rt.frame(0.0); + for _ in 0..2 { rt.repeat_key(KeyEvent { key: key.clone(), mods: Mods::default() }); rt.frame(0.0); } +} + +#[test] +fn held_activation_keys_fire_once_while_navigation_repeats() { + let mut rt = held_runtime(Held::default()); + press(&mut rt, Key::Tab); assert_eq!(focused(&rt), "press"); + hold(&mut rt, Key::Text(" ".into())); + assert_eq!(rt.state.presses, 1, "Space presses a button once per press"); + hold(&mut rt, Key::Enter); + assert_eq!(rt.state.presses, 1, "Return passes a focused button by"); + press(&mut rt, Key::Tab); assert_eq!(focused(&rt), "popup"); + hold(&mut rt, Key::Down); + assert_eq!(rt.state.opens, 1, "arrows open a popup button once"); + assert!(rt.state.menu); + assert_eq!(focused(&rt), "Bravo", "held arrows keep moving inside the open menu"); + hold(&mut rt, Key::Enter); + assert_eq!(rt.state.picks, [2], "a menu item chooses once"); + assert_eq!(focused(&rt), "popup"); + assert_eq!(rt.state.opens, 1, "the repeat does not reopen the popup that took focus back"); + press(&mut rt, Key::Tab); assert_eq!(focused(&rt), "field"); + hold(&mut rt, Key::Enter); + assert_eq!(rt.state.submits, 1, "a field submits once per press"); + hold(&mut rt, Key::Text("x".into())); + hold(&mut rt, Key::Backspace); + assert_eq!(rt.state.field.text, "", "held keys type and delete"); + let app = rt.state.app; + hold(&mut rt, Key::Escape); + assert!(!rt.has_focus(), "Escape blurs the field"); + assert_eq!(rt.state.app, app, "and its repeats reach nothing once focus has gone"); + rt.state.app = 0; + press(&mut rt, Key::Tab); assert_eq!(focused(&rt), "press"); + hold(&mut rt, Key::Tab); + assert_eq!(focused(&rt), "plain", "held Tab keeps moving focus"); +} + +#[test] +fn held_return_on_a_hidden_highlight_keeps_it_hidden() { + let mut rt = menu_runtime(Menu::default()); + let (x, y) = rt.find("popup").unwrap(); + rt.pointer_down(x, y); rt.pointer_up(x, y); rt.frame(0.0); + assert_eq!(focused(&rt), "Alpha"); + for key in [Key::Enter, Key::Text(" ".into())] { + hold(&mut rt, key); + assert_eq!(highlighted(&rt), None, "a repeat must not reveal the highlight"); + } + assert!(rt.state.open && rt.state.picks.is_empty()); +} + +#[test] +fn held_escape_closes_one_modal_and_its_repeats_reach_nothing_after() { + let mut rt = held_runtime(Held { modals: 2, ..Held::default() }); + assert_eq!(focused(&rt), "in-two"); + hold(&mut rt, Key::Escape); + assert_eq!(rt.state.modals, 1); + assert_eq!(focused(&rt), "in-one"); + hold(&mut rt, Key::Escape); + assert_eq!(rt.state.modals, 0); + assert!(!rt.has_focus()); + assert_eq!(rt.state.app, 0, "repeats never fall through to the app after a dismissal"); +} + +#[test] +fn page_keys_move_a_scrolling_listbox_highlight_by_what_it_shows() { + fn view(_: &(), _: &mut Cx<()>) -> El { + col().size(200.0, 300.0).child(col().key("scroll").w_full().h(100.0).scroll(crate::ScrollSpec { stick_bottom: false }) + .child(col().key("list").role("listbox").focus_group() + .children((0..20).map(|i| el().key(format!("item{i}")).w_full().h(20.0).focusable(true).role("option"))))) + } + let mut rt = Runtime::new((), view, (200.0, 300.0), Env::new(true, 1.0)); + rt.frame(0.0); + rt.set_focus(Some(rt.tree.nodes.iter().find(|n| n.key.as_deref() == Some("item0")).unwrap().path.clone()), true); + rt.frame(0.0); + let shown = |rt: &Runtime<()>, key: &str| { + let e = rt.elements().into_iter().find(|e| e.key.as_deref() == Some(key)).unwrap(); + e.rect[1] >= -0.5 && e.rect[1] + e.rect[3] <= 100.5 + }; + for (key, want) in [(Key::PageDown, "item4"), (Key::PageDown, "item8"), (Key::PageUp, "item4"), (Key::End, "item19"), + (Key::PageDown, "item19"), (Key::PageUp, "item15"), (Key::Home, "item0"), (Key::PageUp, "item0")] { + press(&mut rt, key.clone()); + for _ in 0..30 { rt.frame(1.0 / 60.0); } + assert_eq!(focused(&rt), want, "after {key:?}"); + assert!(shown(&rt, want), "{want} scrolled into view"); + } +} + +#[test] +fn a_blurred_field_that_leaves_hands_focus_to_the_button_after_it() { + struct Form { open: bool, field: crate::TextEdit } + fn view(s: &Form, _: &mut Cx<Form>) -> El { + col().size(200.0, 100.0) + .children(s.open.then(|| crate::text_input(&s.field, crate::TextStyle::new(14.0, 400.0)) + .key("field").size(200.0, 40.0).on_edit(|s: &mut Form| &mut s.field))) + .child(button("next")) + } + let mut rt = Runtime::new(Form { open: true, field: crate::TextEdit::new("") }, view, + (200.0, 100.0), Env::new(true, 1.0)); + rt.set_tab_visits_controls(true); + rt.frame(0.0); + press(&mut rt, Key::Tab); + assert_eq!(focused(&rt), "field"); + press(&mut rt, Key::Escape); + assert!(!rt.has_focus(), "Escape blurs the field"); + rt.update(|s, _| s.open = false); + rt.frame(0.0); + assert_eq!(focused(&rt), "next", "the button after the field takes the keyboard"); +} + +/// Three stacked fields, the first of them removable, for the fallback's guard tests. +struct Fields { open: bool, zero: bool, a: crate::TextEdit, b: crate::TextEdit, c: crate::TextEdit } +fn fields_view(s: &Fields, _: &mut Cx<Fields>) -> El { + let style = || crate::TextStyle::new(14.0, 400.0); + col().size(200.0, 150.0) + .children(s.open.then(|| crate::text_input(&s.a, style()).key("a").size(200.0, 35.0) + .on_edit(|s: &mut Fields| &mut s.a))) + .child(crate::text_input(&s.b, style()).key("b").size(200.0, if s.zero { 0.0 } else { 35.0 }) + .on_edit(|s: &mut Fields| &mut s.b)) + .child(crate::text_input(&s.c, style()).key("c").size(200.0, 35.0).on_edit(|s: &mut Fields| &mut s.c)) +} +fn fields(open: bool) -> Runtime<Fields> { + let mut rt = Runtime::new(Fields { open, zero: false, a: crate::TextEdit::new(""), b: crate::TextEdit::new(""), + c: crate::TextEdit::new("") }, fields_view, (200.0, 150.0), Env::new(true, 1.0)); + rt.set_tab_visits_controls(true); + rt.frame(0.0); + press(&mut rt, Key::Tab); + assert_eq!(focused(&rt), "a"); + rt +} + +#[test] +fn a_field_the_model_blurs_while_it_stays_hands_no_focus_on() { + let mut rt = fields(true); + rt.update(|s, _| s.a.focused = false); + rt.frame(0.0); + assert!(!rt.has_focus(), "the field is still here: clearing its flag focuses nothing else"); + assert!(!rt.state.b.focused && !rt.state.c.focused); +} + +#[test] +fn a_fallback_skips_a_candidate_the_commit_collapsed() { + let mut rt = fields(true); + rt.update(|s, tx| { tx.instant(); s.open = false; s.zero = true; }); + rt.frame(0.0); + assert_eq!(focused(&rt), "c", "a control the commit collapsed to no height takes no focus"); + assert!(!rt.state.b.focused, "the collapsed field has none"); + assert!(rt.state.c.focused); +} + +#[test] +fn an_explicit_blur_hands_no_focus_on_when_its_field_goes() { + let mut rt = fields(true); + let was = rt.kbd.focus.owned(); + rt.update(|s, tx| { tx.blur(); s.open = false; }); + rt.frame(0.0); + assert!(!rt.has_focus(), "Tx::blur says nothing has focus, even as the field leaves"); + assert!(!rt.state.b.focused && !rt.state.c.focused); + assert_eq!(rt.kbd.focus.tab_start(), was.as_deref(), "Tab still starts from where the keyboard was"); +} + +#[test] +fn fallback_in_new_skips_collapsed_zero_size_controls() { + fn view(_: &(), _: &mut Cx<()>) -> El { + col().key("line").size(200.0, 40.0) + .child(el().key("collapsed").size(0.0, 0.0).focusable(true)) + .child(el().key("visible").size(40.0, 20.0).focusable(true)) + } + let mut rt = Runtime::new((), view, (200.0, 40.0), Env::new(true, 1.0)); + rt.frame(0.0); + let line = rt.tree.nodes.iter().find(|n| n.key.as_deref() == Some("line")).unwrap().path.clone(); + let visible = rt.tree.nodes.iter().find(|n| n.key.as_deref() == Some("visible")).unwrap().path.clone(); + let gone = format!("{line}/comment"); + let picked = rt.core().fallback_in_new(&gone, &rt.tree.nodes); + assert_eq!(picked.as_deref(), Some(visible.as_str()), "fallback_in_new must skip collapsed zero-size controls"); +} diff --git a/app/vendor/rune/crates/rune/src/runtime/input/gesture.rs b/app/vendor/rune/crates/rune/src/runtime/input/gesture.rs new file mode 100644 index 0000000..6ebaaa7 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/input/gesture.rs @@ -0,0 +1,363 @@ +//! Routes the canvas input of `canvas_input.rs`: wheel deltas to `on_wheel` before scrolling, +//! pinch, rotation and smart magnify, extra mouse buttons to `on_press` and `on_drag`, and key +//! releases to `on_key_up`. +use super::*; +use crate::input::canvas_input::CanvasInput; +use crate::machine::Attempt; +use crate::runtime::scroll_x::WheelOwner; +use crate::{GesturePhase, MagnifyEvent, PointerButton, RotateEvent, WheelEvent}; + +/// A trackpad gesture at a window point, queued for the handlers under it. +#[derive(Clone, Copy, Debug)] +pub(in crate::runtime) enum Gesture { + Magnify(MagnifyEvent), + Rotate(RotateEvent), + SmartMagnify(f32, f32), +} + +/// Where a wheel delta's chain starts (`Runtime::chain_start`), when it was already found on the +/// way to scrolling, so one delta looks it up once. +#[derive(Clone, Copy, Debug)] +pub(crate) enum WheelStart { + Unknown, + At(Option<usize>), +} + +/// Points of Ctrl + wheel per unit of magnification, where a pinch arrives that way. +const PINCH_WHEEL: f32 = 200.0; + +impl RuntimeCore { + /// A wheel or trackpad scroll at window point (`ev.x`, `ev.y`), with its modifiers and + /// phase. The innermost [`El::on_wheel`] handler there hears it first, up to the nearest + /// scroll view; what none takes scrolls as [`Self::wheel_xy`] does. + pub fn wheel_event(&mut self, ev: WheelEvent) { + if ev.phase == GesturePhase::Began { self.wheel_began(); } + let moved = ev.dx != 0.0 || ev.dy != 0.0; + if moved { + self.dismiss_help(); + let now = self.now_clock(); + let pending = self.wheel_pending(); + self.scroll.wheel_delta(now, ev.dx, ev.dy, pending); + } + // A notch or not is the run's to decide, not each delta's. + let ev = if moved { WheelEvent { notch: self.scroll.wheel_notched(self.now_clock(), ev.notch), ..ev } } else { ev }; + if moved || ev.phase != GesturePhase::Moved { + let ev = WheelEvent { momentum: self.scroll.wheel_momentum(), ..ev }; + let gesture = self.scroll.wheel_gesture(); + let phased = self.scroll.wheel_phased(); + if let Some(start) = self.offer_wheel(gesture, ev) { self.wheel_scroll_for(gesture, ev, phased, start); } + } + if ev.phase == GesturePhase::Ended { self.wheel_ended(); } + } + + /// Queues `ev` for the `on_wheel` handlers it may go to (None), or leaves it to scrolling now, + /// with where its chain starts when that was already found on the way. + fn offer_wheel(&mut self, gesture: Attempt, ev: WheelEvent) -> Option<WheelStart> { + // A delta queued this frame may yet be taken: later ones wait their turn behind it. + let pending = self.wheel_queued(Some(gesture)); + let (scrolls, handled) = match self.scroll.wheel_owner() { + WheelOwner::Vertical | WheelOwner::Horizontal(_) => (true, false), + WheelOwner::Handler(_) => (false, true), + WheelOwner::Unpicked => (false, false), + }; + if scrolls && !pending { return Some(WheelStart::Unknown); } + let start = if handled { WheelStart::Unknown } else { WheelStart::At(self.chain_start(ev.x, ev.y)) }; + let chain = match start { WheelStart::At(s) => self.gesture_chain_from(s, |g| g.wheel.is_some(), true), WheelStart::Unknown => Vec::new() }; + if chain.is_empty() && !handled && !pending { return Some(start); } + let phased = self.scroll.wheel_phased(); + self.frame.queue.push(Action::Wheel { gesture, chain, ev, phased }); + None + } + + /// A queued wheel delta: the handler holding its gesture hears it, else each handler + /// under the pointer until one takes it, else it scrolls. Each queued delta keeps its own + /// gesture's turn and axis policy, so one queued before a newer gesture began still reaches + /// the owner its own gesture picked. + pub(in crate::runtime) fn run_wheel(&mut self, app: &mut dyn AppDriver, gesture: Attempt, chain: Vec<String>, ev: WheelEvent, phased: bool, tx: &mut Tx) -> bool { + self.scroll.sync_wheel_gesture(gesture); + let mut taken = None; + match self.scroll.wheel_owner_of(gesture).cloned() { + Some(WheelOwner::Handler(path)) => { + taken = self.call_wheel(app, &path, ev, tx); + if taken.is_none() { self.scroll.set_wheel_owner(gesture, WheelOwner::Unpicked); } + } + Some(WheelOwner::Unpicked) => { + for path in chain { + if self.call_wheel(app, &path, ev, tx) == Some(true) { + self.scroll.set_wheel_owner(gesture, WheelOwner::Handler(path)); + taken = Some(true); + break; + } + } + } + _ => {} + } + if taken.is_none() { + // Queued from an earlier frame: what lies under the pointer may have moved since. + self.wheel_scroll_for(gesture, ev, phased, WheelStart::Unknown); + } + taken.unwrap_or(false) + } + + /// Element `path`'s `on_wheel` on `ev`, in its own points; None when it's gone. + fn call_wheel(&mut self, app: &mut dyn AppDriver, path: &str, ev: WheelEvent, tx: &mut Tx) -> Option<bool> { + let (i, f) = self.gesture_handler(path, |g| g.wheel.clone())?; + let [x, y] = self.to_local(i, ev.x, ev.y); + Some(Tx::took(f(app.states(), WheelEvent { x, y, ..ev }, tx), tx)) + } + + /// A trackpad pinch at window point (`ev.x`, `ev.y`) for the [`El::on_magnify`] handlers + /// there, innermost first. + pub fn magnify_event(&mut self, ev: MagnifyEvent) { + self.offer_gesture(ev.x, ev.y, |g| g.magnify.is_some(), Gesture::Magnify(ev)); + } + + /// A two-finger rotation at window point (`ev.x`, `ev.y`) for the [`El::on_rotate`] + /// handlers there, innermost first. + pub fn rotate_event(&mut self, ev: RotateEvent) { + self.offer_gesture(ev.x, ev.y, |g| g.rotate.is_some(), Gesture::Rotate(ev)); + } + + /// A two-finger double tap at window point (x, y) for the [`El::on_smart_magnify`] + /// handlers there, innermost first. + pub fn smart_magnify(&mut self, x: f32, y: f32) { + self.offer_gesture(x, y, |g| g.smart_magnify.is_some(), Gesture::SmartMagnify(x, y)); + } + + /// A Ctrl + wheel `dy` at (x, y), which is how a trackpad pinch reaches Windows, Linux and + /// web apps: a pinch when an `on_magnify` handler is there (true), else nothing. + pub(crate) fn pinch_wheel(&mut self, x: f32, y: f32, dy: f32) -> bool { + if dy == 0.0 || self.gesture_chain(x, y, |g| g.magnify.is_some(), false).is_empty() { return false; } + self.magnify_event(MagnifyEvent::new(-dy / PINCH_WHEEL).at(x, y)); + true + } + + fn offer_gesture(&mut self, x: f32, y: f32, has: impl Fn(&CanvasInput) -> bool, gesture: Gesture) { + let chain = self.gesture_chain(x, y, has, false); + if !chain.is_empty() { self.frame.queue.push(Action::Gesture(chain, gesture)); } + } + + pub(in crate::runtime) fn run_gesture(&mut self, app: &mut dyn AppDriver, chain: Vec<String>, gesture: Gesture, tx: &mut Tx) -> bool { + for path in chain { + let taken = match gesture { + Gesture::Magnify(ev) => self.gesture_handler(&path, |g| g.magnify.clone()).map(|(i, f)| { + let [x, y] = self.to_local(i, ev.x, ev.y); + Tx::took(f(app.states(), MagnifyEvent { x, y, ..ev }, tx), tx) + }), + Gesture::Rotate(ev) => self.gesture_handler(&path, |g| g.rotate.clone()).map(|(i, f)| { + let [x, y] = self.to_local(i, ev.x, ev.y); + Tx::took(f(app.states(), RotateEvent { x, y, ..ev }, tx), tx) + }), + Gesture::SmartMagnify(x, y) => self.gesture_handler(&path, |g| g.smart_magnify.clone()).map(|(i, f)| { + let [x, y] = self.to_local(i, x, y); + Tx::took(f(app.states(), x, y, tx), tx) + }), + }; + if taken == Some(true) { return true; } + } + false + } + + /// The elements under window point (x, y) with a handler `has` picks, innermost first: up + /// from the topmost hit, and from a scroll view there inside it. With `stop_at_scroll`, the + /// walk ends at the first scroll view, which scrolls what its handlers leave. + fn gesture_chain(&self, x: f32, y: f32, has: impl Fn(&CanvasInput) -> bool, stop_at_scroll: bool) -> Vec<String> { + self.gesture_chain_from(self.chain_start(x, y), has, stop_at_scroll) + } + + /// [`Self::gesture_chain`] from a start already found. + fn gesture_chain_from(&self, start: Option<usize>, has: impl Fn(&CanvasInput) -> bool, stop_at_scroll: bool) -> Vec<String> { + let mut chain = Vec::new(); + let mut at = start; + while let Some(i) = at { + if self.subtree_exiting(i) || !self.allowed(i) { break; } + let n = &self.tree.nodes[i]; + if n.handlers.gestures.as_deref().is_some_and(&has) { chain.push(n.path.clone()); } + if stop_at_scroll && n.scroll.is_some() { break; } + at = n.parent; + } + chain + } + + /// Where a wheel or gesture at window point (x, y) starts walking up the tree: the topmost of + /// what takes input, the scroll views and the painted surfaces there (`wheel_hits`, in paint + /// order; a row inside a list paints after the list, so it wins). Its ancestors are what + /// Chromium chains a scroll through: a viewport that only lies beneath (the timeline under an + /// open menu, a popover or a raised panel) is never one of them. + pub(in crate::runtime) fn chain_start(&self, x: f32, y: f32) -> Option<usize> { + self.hit.find_wheel_hit(|id, r| { + if !self.hit_contains(id, r, x, y) { return None; } + let i = *self.tree.node_index.get(&id)?; + (!self.subtree_exiting(i) && self.allowed(i)).then_some(i) + }) + } + + /// Element `path` (not exiting or inert) and the handler `pick` takes from its canvas input. + fn gesture_handler<F>(&self, path: &str, pick: impl Fn(&CanvasInput) -> Option<F>) -> Option<(usize, F)> { + let i = self.tree.nodes.iter().enumerate().position(|(i, n)| n.path == path && !self.subtree_exiting(i) && self.allowed(i))?; + Some((i, pick(self.tree.nodes[i].handlers.gestures.as_deref()?)?)) + } + + /// A mouse button went down at (x, y). The primary and secondary buttons do what + /// [`Self::pointer_down`] and [`Self::secondary_down`] do. Another presses the innermost + /// element there that takes it: one that opted in ([`El::pointer_buttons`]), whose `on_drag` + /// and `on_press` follow as for the primary button; for the middle button, also a link of a + /// text with `on_link`, or an element with [`El::on_middle_press`], each clicked when the + /// button comes up over it. + pub(crate) fn button_down(&mut self, app: &mut dyn AppDriver, x: f32, y: f32, button: PointerButton) { + match button { + PointerButton::Primary => return self.pointer_down(app, x, y), + PointerButton::Secondary => return self.secondary_down(x, y), + _ => {} + } + if self.pointer.autoscroll_press(button) { self.pointer.pos = Some((x, y)); return; } + if self.pointer.press.is_held() { return; } + self.pointer.pos = Some((x, y)); + if button == PointerButton::Middle { self.tint_down(x, y, button); } + // On Linux a middle click in a text field pastes the primary selection there. + #[cfg(target_os = "linux")] + if button == PointerButton::Middle && self.primary_paste_down(x, y) { return; } + self.dismiss_help(); + let hit = self.hit.top_hit(|id, r| self.hit_contains(id, r, x, y)).and_then(|id| self.tree.node_index.get(&id).copied()); + let middle = button == PointerButton::Middle; + let target = std::iter::successors(hit, |&i| self.tree.nodes[i].parent) + .take_while(|&i| !self.subtree_exiting(i) && self.allowed(i)) + .find_map(|i| { + let h = &self.tree.nodes[i].handlers; + if self.takes_button(i, button) && (h.on_press.is_some() || h.on_drag.is_some()) { return Some((i, None)); } + if !middle { return None; } + if let Some(k) = self.middle_link_at(i, x, y) { return Some((i, Some(k))); } + h.on_middle_press.is_some().then_some((i, None)) + }); + let Some((i, link)) = target else { + if middle { self.autoscroll_down(x, y); } + return; + }; + let n = &self.tree.nodes[i]; + let r = n.target; + let [lx, ly] = self.to_local(i, x, y); + let d = Drag { phase: Phase::Down, x: lx, y: ly, w: r[2] - r[0], h: r[3] - r[1], start_x: lx, start_y: ly, dx: 0.0, dy: 0.0, data: 0.0, clicks: 1, cancelled: false, window: [x, y], screen: self.screen_at(x, y) }; + let path = n.path.clone(); + if self.drags_with(i, button) { self.frame.queue.push(Action::Drag(path.clone(), d, button)); } + self.pointer.clear_press_clicks(); + let now = self.now_clock(); + self.pointer.press.hold(capture::Held::new(path, d, button, (x, y), now, false, None).on_link(link)); + } + + /// Element `i` opted in to `button` ([`El::pointer_buttons`]); every element takes the + /// primary. + pub(in crate::runtime) fn takes_button(&self, i: usize, button: PointerButton) -> bool { + button == PointerButton::Primary || self.tree.nodes[i].handlers.gestures.as_ref().is_some_and(|g| g.buttons & button.bit() != 0) + } + + /// Element `i`'s `on_drag` hears a press of `button`. + pub(in crate::runtime) fn drags_with(&self, i: usize, button: PointerButton) -> bool { + let n = &self.tree.nodes[i]; + n.handlers.on_drag.is_some() && !self.drags_out(n) && self.takes_button(i, button) + } + + /// The link of text `i` under (x, y) that a middle click opens: one its `on_link` hears. + fn middle_link_at(&self, i: usize, x: f32, y: f32) -> Option<usize> { + self.tree.nodes[i].text.as_ref()?.cold.on_link.as_ref()?; + self.link_at(i, x, y) + } + + /// A mouse button came up at (x, y): the release of [`Self::button_down`]. + pub(crate) fn button_up(&mut self, app: &dyn ViewDriver, x: f32, y: f32, button: PointerButton) { + self.pointer.release_tint(button); + if !matches!(button, PointerButton::Primary | PointerButton::Secondary) && self.pointer.autoscroll_release(button) { self.pointer.pos = Some((x, y)); return; } + match button { + PointerButton::Primary => self.pointer_up(app, x, y), + PointerButton::Secondary => self.secondary_up(app, x, y), + _ if self.pointer.press.held().is_some_and(|h| h.button == button) => self.release_capture(app, x, y), + _ => {} + } + } + + /// A key came up, for the [`El::on_key_up`] handlers: true when one is there to hear it, + /// and a frame is needed. A host with physical keys passes the release's logical key to + /// `physical_then` instead, so the focused `on_physical_input` hears it first. + pub(crate) fn key_up(&mut self, app: &mut dyn AppDriver, ev: KeyEvent) -> bool { + if !self.wants_key_up() { return false; } + if self.frame.queue.is_empty() && !self.commit.dirty && self.eat_ime_key_up(app) { return false; } + self.frame.queue.push(Action::KeyUp(ev)); + true + } + + /// Some reachable element has an `on_wheel` handler. + pub(crate) fn hears_wheel(&self) -> bool { + self.tree.nodes.iter().enumerate().any(|(i, n)| n.handlers.get().is_some_and(|h| h.gestures.as_ref().is_some_and(|g| g.wheel.is_some())) && self.allowed(i)) + } + + /// Some element hears key releases, so a host maps them to logical keys. + pub(crate) fn wants_key_up(&self) -> bool { + self.tree.has_key_up || !self.frame.queue.is_empty() || self.commit.dirty + } + + /// Records a key press for [`Self::route_key_up`]: whether it belongs to an open IME + /// composition, or which focused element should still hear its release if focus moves. + pub(in crate::runtime) fn note_key_down(&mut self, app: &mut dyn AppDriver, repeat: bool) { + let composing = self.composing(app); + self.kbd.note_key_down(composing, repeat); + } + + /// Suppresses key releases that belong to an IME composition (while preedit is open, or + /// the release of the key that confirmed or cancelled it). + pub(in crate::runtime) fn eat_ime_key_up(&mut self, app: &mut dyn AppDriver) -> bool { + let composing = self.composing(app); + self.kbd.eat_ime_key_up(composing) + } + + /// A key release goes to the focused element and up through its ancestors, else to every + /// element with a handler (deepest first), inside the open modal if there is one. If focus moved since the key went down, the element that had + /// focus on the press (and its ancestors) hears the release first. + pub(in crate::runtime) fn route_key_up(&mut self, app: &mut dyn AppDriver, ev: &KeyEvent, tx: &mut Tx) -> bool { + if self.eat_ime_key_up(app) { return false; } + tx.focused = self.focused_key(); + let pressed = self.kbd.route_key_release().and_then(|p| self.live_index(&p)); + let focused = self.kbd.focus.path().and_then(|p| self.live_index(p)); + let secure = [pressed, focused].into_iter().flatten() + .any(|i| self.tree.nodes[i].input.as_ref().is_some_and(|input| input.edit.is_secure())); + let mut chain = Vec::new(); + for start in [pressed, focused].into_iter().flatten() { + let mut at = Some(start); + while let Some(i) = at { + if !self.allowed(i) { break; } + if !chain.contains(&i) { chain.push(i); } + at = self.tree.nodes[i].parent; + } + } + // Nothing is focused, or focus rests on the open modal itself (where it lands on open): + // every element that hears releases is offered this one, the deepest first, confined to + // the modal, not only a handler on the root. + let at_rest = chain.is_empty() || (self.active_modal().is_some() && focused == self.active_modal() && pressed.is_none_or(|p| Some(p) == focused)); + if at_rest { + let rest: Vec<usize> = (0..self.tree.nodes.len()).rev().filter(|&i| !chain.contains(&i) && self.allowed(i) && self.tree.nodes[i].focus.key_up.is_some()).collect(); + chain.extend(rest); + } else if pressed.is_some() && focused.is_some() && pressed != focused { + // Keep shared ancestors (such as the root) after both focused elements. + let mut shared = Vec::new(); + let mut at = focused; + while let Some(i) = at { + shared.push(i); + at = self.tree.nodes[i].parent; + } + chain.sort_by_key(|i| shared.iter().position(|s| s == i).map_or(0, |p| p + 1)); + } + for i in chain { + if let Some(f) = self.tree.nodes[i].focus.key_up.clone() && Tx::took(f(app.states(), ev, tx), tx) { + if secure { log_event!(self, "key-up [redacted]") } else { log_event!(self, "key-up {:?}", ev.key) } + return true; + } + } + false + } +} + +#[cfg(test)] +#[path = "gesture_routing_tests.rs"] +mod tests; + +#[cfg(test)] +#[path = "gesture_tests.rs"] +mod gesture_tests; diff --git a/app/vendor/rune/crates/rune/src/runtime/input/gesture_routing_tests.rs b/app/vendor/rune/crates/rune/src/runtime/input/gesture_routing_tests.rs new file mode 100644 index 0000000..7081d8b --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/input/gesture_routing_tests.rs @@ -0,0 +1,259 @@ +use super::*; +use crate::{Env, Mods, PhysicalInput, PhysicalKeyCode, el}; + +#[derive(Default)] +struct State { ups: Vec<crate::Key>, swallow: bool, zoom: Vec<f32> } + +fn view(_: &State, _: &mut crate::Cx<State>) -> El { + el().w_full().h_full() + .on_key_up(|s: &mut State, e, _| { s.ups.push(e.key.clone()); true }) + .on_magnify(|s: &mut State, e, _| { s.zoom.push(e.delta); true }) + .child(el().key("field").size(40.0, 40.0).focusable(true).on_physical_input(|s: &mut State, _, _| s.swallow)) +} + +#[test] +fn a_physical_release_carries_its_logical_key_to_on_key_up_after_the_focused_handler() { + let mut rt = Runtime::new(State::default(), view, (100.0, 100.0), Env::new(true, 1.0)); + rt.frame(0.0); + assert!(rt.wants_key_up()); + let release = PhysicalInput::Key { key: PhysicalKeyCode::Space, mods: Mods::default(), pressed: false, repeat: false }; + let space = KeyEvent { key: crate::Key::Text(" ".into()), mods: Mods::default() }; + assert!(rt.physical_with_fallback(release, Some(space.clone()))); + rt.frame(0.0); + assert_eq!(rt.state.ups, [space.key.clone()]); + + // A focused `on_physical_input` that takes the release keeps it from `on_key_up`. + let (x, y) = rt.find("field").unwrap(); + rt.pointer_down(x, y); + rt.pointer_up(x, y); + rt.state.swallow = true; + rt.physical_with_fallback(release, Some(space.clone())); + rt.frame(0.0); + assert_eq!(rt.state.ups.len(), 1); + rt.state.swallow = false; + rt.physical_with_fallback(release, Some(space)); + rt.frame(0.0); + assert_eq!(rt.state.ups.len(), 2); +} + +#[derive(Default)] +struct Keys { log: Vec<&'static str> } + +fn stage(s: &Keys, _: &mut crate::Cx<Keys>) -> El { + let _ = s; + el().w_full().h_full() + .child(el().key("stage").size(40.0, 40.0).on_key_up(|s: &mut Keys, _, _| { s.log.push("stage"); true })) + .child(el().key("other").size(40.0, 40.0).focusable(true)) +} + +fn up() -> KeyEvent { KeyEvent { key: crate::Key::Text("a".into()), mods: Mods::default() } } + +#[test] +fn an_unfocused_release_reaches_a_nested_handler() { + let mut rt = Runtime::new(Keys::default(), stage, (100.0, 100.0), Env::new(true, 1.0)); + rt.frame(0.0); + assert!(rt.wants_key_up()); + rt.key_up(up()); + rt.frame(0.0); + assert_eq!(rt.state.log, ["stage"]); +} + +fn pair(_: &Keys, _: &mut crate::Cx<Keys>) -> El { + el().w_full().h_full() + .child(el().key("a").size(40.0, 40.0).focusable(true).on_key_up(|s: &mut Keys, _, _| { s.log.push("a"); true })) + .child(el().key("b").size(40.0, 40.0).focusable(true).on_key_up(|s: &mut Keys, _, _| { s.log.push("b"); true })) +} + +#[test] +fn a_release_goes_to_the_element_focused_at_the_press_even_after_focus_moves() { + let mut rt = Runtime::new(Keys::default(), pair, (100.0, 100.0), Env::new(true, 1.0)); + rt.frame(0.0); + let click = |rt: &mut Runtime<Keys>, k: &str| { let (x, y) = rt.find(k).unwrap(); rt.pointer_down(x, y); rt.pointer_up(x, y); rt.frame(0.0); }; + click(&mut rt, "a"); + rt.key(up()); + rt.frame(0.0); + click(&mut rt, "b"); + rt.key_up(up()); + rt.frame(0.0); + assert_eq!(rt.state.log, ["a"]); +} + +fn modal_view(_: &Keys, _: &mut crate::Cx<Keys>) -> El { + el().w_full().h_full() + .on_key_up(|s: &mut Keys, _, _| { s.log.push("root"); true }) + .child(el().key("under").size(40.0, 40.0).on_key_up(|s: &mut Keys, _, _| { s.log.push("under"); true })) + .child(el().key("sheet").absolute(50.0, 50.0).size(40.0, 40.0).modal(true, |_: &mut Keys| {}) + .child(el().key("inside").size(10.0, 10.0).on_key_up(|s: &mut Keys, _, _| { s.log.push("inside"); true }))) +} + +#[test] +fn an_unfocused_release_in_a_modal_stays_inside_it() { + let mut rt = Runtime::new(Keys::default(), modal_view, (100.0, 100.0), Env::new(true, 1.0)); + rt.frame(0.0); + rt.key_up(up()); + rt.frame(0.0); + assert_eq!(rt.state.log, ["inside"]); +} + +#[test] +fn a_ctrl_wheel_pinches_only_where_a_magnify_handler_is() { + let mut rt = Runtime::new(State::default(), view, (100.0, 100.0), Env::new(true, 1.0)); + rt.frame(0.0); + assert!(rt.pinch_wheel(50.0, 50.0, -20.0)); + rt.frame(0.0); + assert_eq!(rt.state.zoom, [20.0 / PINCH_WHEEL]); + assert!(!rt.pinch_wheel(500.0, 50.0, -20.0), "off the window nothing takes it"); +} + +#[derive(Default)] +struct Wheeled { heard: Vec<f32> } + +fn wheeling(_: &Wheeled, _: &mut crate::Cx<Wheeled>) -> El { + el().w_full().h_full() + .child(el().key("list").w_full().h(300.0).scroll(crate::ScrollSpec { stick_bottom: false }) + .child(el().w_full().h(1000.0) + .child(el().key("takes").absolute(100.0, 40.0).size(40.0, 40.0) + .on_wheel(|s: &mut Wheeled, e: crate::WheelEvent, _: &mut Tx| { s.heard.push(e.x); true })))) +} + +/// Deltas queued before the platform began the next gesture finish with the owner the +/// gesture picked: the one outside the handler still reaches it, rather than scrolling the +/// viewport under the pointer. +#[test] +fn deltas_queued_before_a_new_gesture_began_finish_with_the_gesture_s_owner() { + let mut rt = Runtime::new(Wheeled::default(), wheeling, (300.0, 300.0), Env::default()); + rt.frame(0.0); + rt.frame(1.0 / 60.0); + rt.wheel_event(crate::WheelEvent::new(0.0, -10.0).at(110.0, 50.0)); + rt.wheel_event(crate::WheelEvent::new(0.0, -10.0).at(290.0, 50.0)); + rt.wheel_began(); + rt.frame(1.0 / 60.0); + assert_eq!(rt.state.heard, [10.0, 190.0], "both deltas in the handler's own points"); + let id = rt.tree.nodes.iter().find(|n| n.key.as_deref() == Some("list")).unwrap().id; + assert_eq!(rt.scroll.scrolls[&id].offset, 0.0, "the whole gesture stays with the handler"); +} + +/// A delta queued over the handler, before it has the gesture, still reaches it when a newer +/// gesture scrolls at once outside every handler: the newer one's own delta scrolls once. +#[test] +fn a_queued_delta_picks_its_handler_before_a_newer_gesture_s_scroll() { + let mut rt = Runtime::new(Wheeled::default(), wheeling, (300.0, 300.0), Env::default()); + rt.frame(0.0); + rt.frame(1.0 / 60.0); + rt.wheel_event(crate::WheelEvent::new(0.0, -10.0).at(110.0, 50.0)); + rt.wheel_began(); + rt.wheel_event(crate::WheelEvent::new(0.0, -10.0).at(290.0, 50.0)); + rt.frame(1.0 / 60.0); + assert_eq!(rt.state.heard, [10.0], "the queued delta reaches the handler it was offered to"); + let id = rt.tree.nodes.iter().find(|n| n.key.as_deref() == Some("list")).unwrap().id; + assert_eq!(rt.scroll.scrolls[&id].offset, 10.0, "only the newer gesture's own delta scrolled"); +} + +/// A delta queued for the handler that has the gesture keeps reaching it when the gesture +/// ends and the next one scrolls at once, before the frame drains the queue. +#[test] +fn a_queued_delta_keeps_its_owner_when_the_next_gesture_scrolls_first() { + let mut rt = Runtime::new(Wheeled::default(), wheeling, (300.0, 300.0), Env::default()); + rt.frame(0.0); + rt.frame(1.0 / 60.0); + // The handler takes the gesture. + rt.wheel_event(crate::WheelEvent::new(0.0, -10.0).at(110.0, 50.0)); + rt.frame(1.0 / 60.0); + assert_eq!(rt.state.heard, [10.0]); + // A delta outside it is queued for that owner; the gesture ends, and the next one + // scrolls at once outside every handler. + rt.wheel_event(crate::WheelEvent::new(0.0, -10.0).at(290.0, 50.0)); + rt.wheel_ended(); + rt.wheel_event(crate::WheelEvent::new(0.0, -10.0).at(290.0, 50.0)); + rt.frame(1.0 / 60.0); + assert_eq!(rt.state.heard, [10.0, 190.0], "the queued delta still reaches the gesture's owner"); + let id = rt.tree.nodes.iter().find(|n| n.key.as_deref() == Some("list")).unwrap().id; + assert_eq!(rt.scroll.scrolls[&id].offset, 10.0, "only the newer gesture's own delta scrolled"); +} + +#[derive(Default)] +struct Two { heard: Vec<&'static str> } + +fn two_handlers(_: &Two, _: &mut crate::Cx<Two>) -> El { + el().w_full().h_full() + .child(el().key("list").w_full().h(300.0).scroll(crate::ScrollSpec { stick_bottom: false }) + .child(el().w_full().h(1000.0) + .child(el().key("a").absolute(20.0, 40.0).size(40.0, 40.0) + .on_wheel(|s: &mut Two, _: crate::WheelEvent, _: &mut Tx| { s.heard.push("a"); true })) + .child(el().key("b").absolute(200.0, 40.0).size(40.0, 40.0) + .on_wheel(|s: &mut Two, _: crate::WheelEvent, _: &mut Tx| { s.heard.push("b"); true })))) +} + +/// A gesture whose queued deltas have all run gives its owner's place up: the next gesture's +/// queued delta still reaches that gesture's handler instead of scrolling. +#[test] +fn a_drained_gesture_gives_its_owner_up_to_the_next_queued_one() { + let mut rt = Runtime::new(Two::default(), two_handlers, (300.0, 300.0), Env::default()); + rt.frame(0.0); + rt.frame(1.0 / 60.0); + // A delta over `a`, then a gesture begins and a delta over `b`: each reaches its own. + rt.wheel_event(crate::WheelEvent::new(0.0, -10.0).at(30.0, 50.0)); + rt.wheel_began(); + rt.wheel_event(crate::WheelEvent::new(0.0, -10.0).at(210.0, 50.0)); + rt.frame(1.0 / 60.0); + assert_eq!(rt.state.heard, ["a", "b"]); + // `b` owns the gesture now; a delta outside it is queued for `b`, and the next gesture + // begins before the frame drains it. + rt.wheel_event(crate::WheelEvent::new(0.0, -10.0).at(290.0, 50.0)); + rt.wheel_began(); + rt.frame(1.0 / 60.0); + assert_eq!(rt.state.heard, ["a", "b", "b"], "the queued delta still reaches b"); + let id = rt.tree.nodes.iter().find(|n| n.key.as_deref() == Some("list")).unwrap().id; + assert_eq!(rt.scroll.scrolls[&id].offset, 0.0, "every delta reached a handler"); +} + +/// With a delta queued for a handler under one gesture and another under the next, each +/// reaches its own gesture's handler, however many gestures began before the frame. +#[test] +fn a_delta_queued_for_each_of_two_gestures_reaches_its_own_handler() { + let mut rt = Runtime::new(Two::default(), two_handlers, (300.0, 300.0), Env::default()); + rt.frame(0.0); + rt.frame(1.0 / 60.0); + rt.wheel_event(crate::WheelEvent::new(0.0, -10.0).at(30.0, 50.0)); + rt.wheel_began(); + rt.wheel_event(crate::WheelEvent::new(0.0, -10.0).at(210.0, 50.0)); + rt.wheel_began(); + rt.frame(1.0 / 60.0); + assert_eq!(rt.state.heard, ["a", "b"], "each delta goes to the handler its own gesture found"); +} + +/// Three gestures begin inside one frame, each with a delta queued for the handler under the +/// pointer: each delta reaches its own gesture's handler. +#[test] +fn three_gestures_queued_before_one_frame_each_reach_their_own_handler() { + let mut rt = Runtime::new(Two::default(), two_handlers, (300.0, 300.0), Env::default()); + rt.frame(0.0); + rt.frame(1.0 / 60.0); + rt.wheel_event(crate::WheelEvent::new(0.0, -10.0).at(30.0, 50.0)); + rt.wheel_began(); + rt.wheel_event(crate::WheelEvent::new(0.0, -10.0).at(210.0, 50.0)); + rt.wheel_began(); + rt.wheel_event(crate::WheelEvent::new(0.0, -10.0).at(30.0, 50.0)); + rt.frame(1.0 / 60.0); + assert_eq!(rt.state.heard, ["a", "b", "a"], "each delta goes to the handler its own gesture found"); + let id = rt.tree.nodes.iter().find(|n| n.key.as_deref() == Some("list")).unwrap().id; + assert_eq!(rt.scroll.scrolls[&id].offset, 0.0, "every delta reached a handler"); +} + +/// The third gesture scrolls at once outside every handler: the deltas queued for the first +/// two gestures still reach their own handlers, and only the third scrolls. +#[test] +fn a_third_gesture_scrolling_before_the_frame_keeps_both_queued_owners() { + let mut rt = Runtime::new(Two::default(), two_handlers, (300.0, 300.0), Env::default()); + rt.frame(0.0); + rt.frame(1.0 / 60.0); + rt.wheel_event(crate::WheelEvent::new(0.0, -10.0).at(30.0, 50.0)); + rt.wheel_began(); + rt.wheel_event(crate::WheelEvent::new(0.0, -10.0).at(210.0, 50.0)); + rt.wheel_began(); + rt.wheel_event(crate::WheelEvent::new(0.0, -10.0).at(290.0, 50.0)); + rt.frame(1.0 / 60.0); + assert_eq!(rt.state.heard, ["a", "b"], "the first two gestures' deltas still reach their handlers"); + let id = rt.tree.nodes.iter().find(|n| n.key.as_deref() == Some("list")).unwrap().id; + assert_eq!(rt.scroll.scrolls[&id].offset, 10.0, "only the third gesture's own delta scrolled"); +} diff --git a/app/vendor/rune/crates/rune/src/runtime/input/gesture_tests.rs b/app/vendor/rune/crates/rune/src/runtime/input/gesture_tests.rs new file mode 100644 index 0000000..dbf39e6 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/input/gesture_tests.rs @@ -0,0 +1,173 @@ +//! Wheels over elements that name the viewport they scroll (`El::wheel_scrolls`): a scroll bar +//! drawn beside the viewport it follows, which the chain up the ancestors can't find. +use super::*; + +use crate::{Env, ScrollSpec, col, el}; + +/// The offset of the element at `path`. +fn offset(rt: &Runtime<()>, path: &str) -> f64 { + let id = rt.tree.nodes.iter().find(|n| n.path == path).unwrap_or_else(|| panic!("{path}")).id; + rt.scroll.scrolls[&id].offset +} + +/// A bar beside its viewport, as `rune-kit`'s scroll bar is: in an `area` column with the +/// viewport, drawn after it, so a wheel over the bar hits it and the viewport is a sibling. +/// The named one hands its wheel to the viewport (`El::wheel_scrolls`); the plain one names +/// nothing, as any box taking input does. +fn barred(named: bool) -> El { + let bar = el().key("bar").absolute(286.0, 0.0).size(14.0, 200.0).on_drag(|_: &mut (), _, _| {}); + let bar = if named { bar.wheel_scrolls("area/list") } else { bar }; + el().key("root").w_full().h_full().child( + col().key("area").size(300.0, 200.0) + .child(col().key("list").w_full().h_full().scroll(ScrollSpec { stick_bottom: false }) + .child(el().w_full().h(1000.0))) + .child(bar), + ) +} + +fn named_bar(_: &(), _: &mut crate::Cx<()>) -> El { barred(true) } +fn plain_bar(_: &(), _: &mut crate::Cx<()>) -> El { barred(false) } + +/// A wheel over an element naming the viewport it scrolls (`El::wheel_scrolls`) is that +/// viewport's, though the viewport is its sibling drawn under it: an overlay scroll bar's +/// track beside the viewport it follows. +#[test] +fn a_wheel_over_an_element_that_names_its_viewport_scrolls_that_viewport() { + let mut rt = Runtime::new((), named_bar, (300.0, 200.0), Env::default()); + rt.frame(0.0); + rt.wheel(293.0, 100.0, -30.0); + rt.frame(0.0); + assert_eq!(offset(&rt, "root/area/list"), 30.0, "the wheel over the bar scrolled the list it follows"); + + // Unnamed, the same bar leaves the wheel with what lies above it, as any box taking input + // does: the list is a sibling, not an ancestor, so it never sees the wheel. + let mut plain = Runtime::new((), plain_bar, (300.0, 200.0), Env::default()); + plain.frame(0.0); + plain.wheel(293.0, 100.0, -30.0); + plain.frame(0.0); + assert_eq!(offset(&plain, "root/area/list"), 0.0, "a bar that names nothing scrolls nothing"); +} + +/// A wheel over a bar takes the named viewport before the page around it, and chains on up from +/// that viewport when it has no room, as one over the viewport itself does. +#[test] +fn a_wheel_a_named_viewport_cannot_take_chains_up_from_it() { + fn paged(content: f32) -> El { + el().key("root").w_full().h_full().child( + col().key("page").size(300.0, 200.0).scroll(ScrollSpec { stick_bottom: false }) + .child(el().key("body").w_full().h(1000.0).child( + col().key("area").size(300.0, 200.0) + .child(col().key("list").w_full().h_full().scroll(ScrollSpec { stick_bottom: false }) + .child(el().w_full().h(content))) + .child(el().key("bar").absolute(286.0, 0.0).size(14.0, 200.0) + .on_drag(|_: &mut (), _, _| {}).wheel_scrolls("area/list")), + )), + ) + } + fn page_tall(_:&(), _: &mut crate::Cx<()>) -> El { paged(1000.0) } + fn page_short(_:&(), _: &mut crate::Cx<()>) -> El { paged(100.0) } + + let mut tall = Runtime::new((), page_tall, (300.0, 200.0), Env::default()); + tall.frame(0.0); + tall.wheel(293.0, 100.0, -30.0); + tall.frame(0.0); + assert_eq!(offset(&tall, "root/page/body/area/list"), 30.0, "the named viewport takes the wheel before the page around it"); + assert_eq!(offset(&tall, "root/page"), 0.0, "the page around it stays where it is"); + + let mut short = Runtime::new((), page_short, (300.0, 200.0), Env::default()); + short.frame(0.0); + short.wheel(293.0, 100.0, -30.0); + short.frame(0.0); + assert_eq!(offset(&short, "root/page"), 30.0, "a short list hands the wheel on to the page around it"); + assert_eq!(offset(&short, "root/page/body/area/list"), 0.0, "the list itself never moved"); +} + +/// A raised panel over a bar keeps the wheel from the viewport under it, as #1137 chains a +/// wheel from what takes input or paints above: naming a viewport is how a bar belongs to +/// one, not a way through a panel over it. +#[test] +fn a_raised_panel_over_a_bar_keeps_the_wheel_from_the_viewport_under_it() { + fn panel(_:&(), _: &mut crate::Cx<()>) -> El { + el().key("root").w_full().h_full().child( + col().key("area").size(300.0, 200.0) + .child(col().key("list").w_full().h_full().scroll(ScrollSpec { stick_bottom: false }) + .child(el().w_full().h(1000.0))) + .child(el().key("bar").absolute(286.0, 0.0).size(14.0, 200.0) + .on_drag(|_: &mut (), _, _| {}).wheel_scrolls("area/list")) + .child(el().key("panel").absolute(280.0, 0.0).size(20.0, 100.0).raise()), + ) + } + let mut rt = Runtime::new((), panel, (300.0, 200.0), Env::default()); + rt.frame(0.0); + rt.wheel(293.0, 60.0, -30.0); + rt.frame(0.0); + assert_eq!(offset(&rt, "root/area/list"), 0.0, "the panel over the bar takes the wheel, as it did before"); +} + +/// Two panes keying their list and bar alike, as a chat and a sidebar do: the wheel over the +/// second pane's bar is its own, not the first element keyed `area/list` in the window. +#[test] +fn a_wheel_over_one_pane_s_bar_scrolls_that_pane_when_the_panes_key_alike() { + fn panes(_: &(), _: &mut crate::Cx<()>) -> El { + let pane = |key: &str| col().key(key.to_owned()).w(150.0).h(200.0).child( + col().key("area").w_full().h_full() + .child(col().key("list").w_full().h_full().scroll(ScrollSpec { stick_bottom: false }) + .child(el().w_full().h(1000.0))) + .child(el().key("bar").absolute(136.0, 0.0).size(14.0, 200.0) + .on_drag(|_: &mut (), _, _| {}).wheel_scrolls("area/list")), + ); + crate::row().key("root").w_full().h_full().child(pane("left")).child(pane("right")) + } + let mut rt = Runtime::new((), panes, (300.0, 200.0), Env::default()); + rt.frame(0.0); + assert_eq!((offset(&rt, "root/left/area/list"), offset(&rt, "root/right/area/list")), (0.0, 0.0)); + // The second pane's bar: its strip over the pane's right edge, at x 286..300. + rt.wheel(293.0, 100.0, -30.0); + rt.frame(0.0); + assert_eq!(offset(&rt, "root/right/area/list"), 30.0, "the wheel over the right pane's bar scrolled its own list"); + assert_eq!(offset(&rt, "root/left/area/list"), 0.0, "the left pane, keyed alike, stayed where it was"); +} + +/// A sideways wheel over a bar is the viewport the bar follows too: a two-way pane's vertical +/// track scrolls it across, and a table's horizontal track scrolls the table itself, where a +/// chain up from either track finds no horizontal scroller. +#[test] +fn a_sideways_wheel_over_a_bar_scrolls_the_viewport_it_follows() { + fn both_ways(_: &(), _: &mut crate::Cx<()>) -> El { + el().key("root").w_full().h_full().child( + col().key("area").size(300.0, 200.0) + .child(col().key("list").w_full().h_full().scroll_xy().child(el().size(900.0, 1000.0))) + .child(el().key("bar").absolute(286.0, 0.0).size(14.0, 200.0) + .on_drag(|_: &mut (), _, _| {}).wheel_scrolls("area/list")), + ) + } + fn sideways(_: &(), _: &mut crate::Cx<()>) -> El { + el().key("root").w_full().h_full().child( + col().key("area").size(300.0, 200.0) + .child(col().key("table").w_full().h(100.0).scroll_x().child(el().size(900.0, 100.0))) + .child(el().key("bar").absolute(0.0, 102.0).size(300.0, 8.0) + .on_drag(|_: &mut (), _, _| {}).wheel_scrolls("area/table")), + ) + } + + // A vertical bar over a viewport that scrolls both ways. + let mut across = Runtime::new((), both_ways, (300.0, 200.0), Env::default()); + across.frame(0.0); + across.wheel_xy(293.0, 100.0, -40.0, 0.0); + across.frame(0.0); + { + let id = across.tree.nodes.iter().find(|n| n.path == "root/area/list").unwrap().id; + assert_eq!(across.scroll.scrolls[&id].x.offset, 40.0, "the sideways wheel over the pane's bar scrolled it across"); + assert_eq!(across.scroll.scrolls[&id].offset, 0.0, "and left it where it was down"); + } + + // A horizontal bar under the table it belongs to. + let mut along = Runtime::new((), sideways, (300.0, 200.0), Env::default()); + along.frame(0.0); + along.wheel_xy(150.0, 106.0, -40.0, 0.0); + along.frame(0.0); + { + let id = along.tree.nodes.iter().find(|n| n.path == "root/area/table").unwrap().id; + assert_eq!(along.scroll.scrolls[&id].x.offset, 40.0, "the sideways wheel over the table's own bar scrolled the table"); + } +} diff --git a/app/vendor/rune/crates/rune/src/runtime/input/help.rs b/app/vendor/rune/crates/rune/src/runtime/input/help.rs new file mode 100644 index 0000000..c6de273 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/input/help.rs @@ -0,0 +1,627 @@ +//! Tooltips (`El::help`), as SwiftUI's `.help`. Help elements are hit-tested on their own, so +//! they take no hover or press from anything. The pointer resting on one for `help_delay` +//! shows its tooltip under the element; a press, scroll or key hides it until the pointer +//! leaves the element, as does the pointer leaving. The tooltip draws over everything and +//! follows its element while that moves under the pointer. A text's links can carry their own +//! help (`Link::help`), hit-tested on their glyphs and shown under the link. +//! +//! A macOS window shows AppKit's own tooltips instead (`set_native_help`): the host registers +//! [`Runtime::help_regions`] with its view and AppKit owns the delay, look and hiding, unless +//! the view sets its own look (`Cx::help_look`), which Rune draws everywhere. +//! +//! Where the tooltip is in its life is one [`Tip`], stepped by [`step`] once a frame with what +//! the pointer is over, and on a dismissal; it mirrors `@opencode/ui`'s tooltip machine +//! (`ui/src/overlays/tooltip/machine.ts`) with Kobalte's open and skip delays. A press on the +//! element dismisses its tooltip; a popup or modal over the element suppresses it until +//! the pointer leaves. The look's fade (`HelpLook::fade`) plays as the tooltip opens and +//! closes, the closing one fading out under the next. +use crate::machine::Effects; + +use super::*; + +#[derive(Default)] +pub(in crate::runtime) struct HelpState { + state: Tip, + /// The tooltip showing this frame: its text and box in points. + tip: Option<(String, [f32; 4])>, + /// The open tooltip as it last drew, for its fade out. + drawn: Option<Drawn>, + /// A closed tooltip fading out, and when (clock seconds) it closed. + leaving: Option<(Drawn, f64)>, + /// The host shows system tooltips from `help_regions`. + native: bool, + regions: Vec<([f32; 4], String)>, +} + +/// A help element, or one link of its text, by path. +#[derive(Clone, Debug, PartialEq)] +struct Target { + path: String, + link: Option<usize>, +} + +/// Where the tooltip is in its life. Times are clock seconds. +#[derive(Clone, Debug, Default, PartialEq)] +enum Tip { + /// No help element under the pointer, or a tooltip hid more than the skip delay ago. + #[default] + Idle, + /// A tooltip hid as the pointer left its element: until `until`, the next one opens at once. + Warm { until: f64 }, + /// The pointer has rested on `target` since this clock time. + Waiting { target: Target, since: f64 }, + /// `target`'s tooltip shows, fading in from `since`. + Open { target: Target, since: f64 }, + /// A press, a scroll or key, or a popup over `target` hid its tooltip until the + /// pointer leaves it. + Suppressed { target: Target }, +} + +impl Tip { + fn target(&self) -> Option<&Target> { + match self { + Tip::Waiting { target, .. } | Tip::Open { target, .. } | Tip::Suppressed { target } => Some(target), + Tip::Idle | Tip::Warm { .. } => None, + } + } +} + +/// What the pointer is over as a frame draws. +#[derive(Debug, PartialEq)] +enum Over { + /// No pointer in the window: it left, or a menu took it. + Away, + /// No help element. + Nothing, + Help(Target), + /// A help element, under a popup or modal that the pointer can't reach it through. + Covered(Target), + /// The help element the keyboard focused, with the pointer on no other (`HelpLook::on_focus`). + Focused(Target), + /// A help element held open (`El::help_open`), whatever the pointer does. + Forced(Target), +} + +#[derive(Debug, PartialEq)] +enum Event { + Frame { over: Over, now: f64 }, + /// A press, a scroll or a key. + Dismiss, +} + +#[derive(Debug, PartialEq)] +enum Effect { + /// Wake at this clock time, when a wait ends. + WakeAt(f64), + /// The open tooltip closed: fade it out. + FadeOut, +} + +/// The look's open and skip delays, in seconds. +#[derive(Clone, Copy)] +struct Delays { + open: f64, + skip: f64, +} + +fn step(tip: &mut Tip, event: Event, delays: Delays) -> Effects<Effect> { + let (over, now) = match event { + Event::Dismiss => return suppress(tip), + Event::Frame { over, now } => (over, now), + }; + let effects = match over { + // A menu the element opened took the pointer: the tooltip stays hidden over it after. + Over::Away if matches!(tip, Tip::Suppressed { .. }) => Effects::none(), + Over::Forced(at) if matches!(tip, Tip::Open { target, .. } if *target == at) => Effects::none(), + Over::Forced(at) => open_now(tip, at, now), + Over::Focused(at) if tip.target() == Some(&at) => Effects::none(), + Over::Focused(at) => open_now(tip, at, now), + Over::Covered(at) if tip.target() == Some(&at) => suppress(tip), + Over::Help(at) if tip.target() == Some(&at) => Effects::none(), + Over::Help(at) => leave(tip, Some(at), now, delays), + Over::Away | Over::Nothing | Over::Covered(_) => leave(tip, None, now, delays), + }; + match std::mem::take(tip) { + Tip::Warm { until } if now > until => {} + // The wait is over (or there was none: a zero delay opens in the frame it starts). + Tip::Waiting { target, since } if now + 1e-6 >= since + delays.open => *tip = Tip::Open { target, since: now }, + other => *tip = other, + } + effects +} + +/// The pointer left the tooltip's element for `at` (or nothing): an open tooltip closes, and +/// within the skip delay of one closing the next opens at once. +fn leave(tip: &mut Tip, at: Option<Target>, now: f64, delays: Delays) -> Effects<Effect> { + let open = matches!(tip, Tip::Open { .. }); + let warm = (open && delays.skip > 0.0) || matches!(tip, Tip::Warm { until } if now <= *until); + let mut effects = if open { Effects::one(Effect::FadeOut) } else { Effects::none() }; + *tip = match at { + Some(target) if warm => Tip::Open { target, since: now }, + Some(target) => { + let due = now + delays.open; + effects.push(Effect::WakeAt(due)); + Tip::Waiting { target, since: now } + } + None if open && delays.skip > 0.0 => Tip::Warm { until: now + delays.skip }, + None if warm => std::mem::take(tip), + None => Tip::Idle, + }; + effects +} + +/// `at`'s tooltip shows now, with no wait: the one open closes. +fn open_now(tip: &mut Tip, at: Target, now: f64) -> Effects<Effect> { + let effects = if matches!(tip, Tip::Open { .. }) { Effects::one(Effect::FadeOut) } else { Effects::none() }; + *tip = Tip::Open { target: at, since: now }; + effects +} + +/// Hide the tooltip until the pointer leaves its element. +fn suppress(tip: &mut Tip) -> Effects<Effect> { + match std::mem::take(tip) { + Tip::Open { target, .. } => { + *tip = Tip::Suppressed { target }; + Effects::one(Effect::FadeOut) + } + Tip::Waiting { target, .. } | Tip::Suppressed { target } => { + *tip = Tip::Suppressed { target }; + Effects::none() + } + idle @ (Tip::Idle | Tip::Warm { .. }) => { + *tip = idle; + Effects::none() + } + } +} + +/// A tooltip as drawn: its text, the box it hangs from (window points, x0 y0 x1 y1), the side +/// of that box it asks for (None: under it), and its opacity. +#[derive(Clone, Debug)] +struct Drawn { + text: String, + anchor: [f32; 4], + side: Option<crate::Side>, + alpha: f32, + scale: f32, +} + +/// One row of a tooltip as laid out: its words (when it has any) `tw` by `th` points, its +/// keycaps and their width with the lead before them, and the row's height. +struct TipRow { + words: bool, + layout: std::rc::Rc<parley::Layout<crate::text::Ink>>, + tw: f32, + th: f32, + ch: f32, + caps: Vec<(std::rc::Rc<parley::Layout<crate::text::Ink>>, f32)>, + keys_w: f32, +} + +fn overlaps(a: [f32; 4], b: [f32; 4]) -> bool { + a[0] < b[2] && b[0] < a[2] && a[1] < b[3] && b[1] < a[3] +} + +/// `a` minus `b` (x0 y0 x1 y1), as up to four rects: the bands above and below `b`, then the +/// pieces left and right of it. +fn subtract(a: [f32; 4], b: [f32; 4]) -> Vec<[f32; 4]> { + if !overlaps(a, b) { return vec![a]; } + let (y0, y1) = (b[1].max(a[1]), b[3].min(a[3])); + [[a[0], a[1], a[2], y0], [a[0], y1, a[2], a[3]], [a[0], y0, b[0].max(a[0]), y1], [b[2].min(a[2]), y0, a[2], y1]] + .into_iter().filter(|r| r[2] > r[0] && r[3] > r[1]).collect() +} + +impl capture::PointerState { + /// The host shows AppKit's tooltips: on macOS, while the view keeps the system look. + #[inline] + pub(super) fn native_help(&self, custom_look: bool) -> bool { self.help.native && !custom_look } + + /// The host shows the system's own tooltips for [`Runtime::help_regions`], so Rune draws none. + #[cfg(target_os = "macos")] + #[inline] + pub(in crate::runtime) fn set_native_help(&mut self, on: bool) { self.help.native = on; } + + /// Each visible help element's rect (window points, x0 y0 x1 y1) and text, in paint order, + /// for a host that shows system tooltips. + #[inline] + pub(in crate::runtime) fn help_regions(&self) -> &[([f32; 4], String)] { &self.help.regions } + + /// The tooltip Rune shows now: its text and box (window points, x y w h). + #[inline] + pub(in crate::runtime) fn help_tooltip(&self) -> Option<(&str, [f32; 4])> { + self.help.tip.as_ref().map(|(t, r)| (t.as_str(), *r)) + } + + /// The open tooltip fades in, or a closed one fades out, so frames keep coming. + #[inline] + fn tooltip_fading(&self, clock: f64, fade: [f64; 2]) -> bool { + let opening = matches!(self.help.state, Tip::Open { since, .. } if clock < since + fade[0]); + opening || self.help.leaving.as_ref().is_some_and(|(_, at)| clock < at + fade[1]) + } + + /// A tooltip waits for a frame at or after its delay to draw, or fades in or out. + #[inline] + pub(super) fn tooltip_waiting(&self, clock: f64, open_delay: f64, fade: [f64; 2]) -> bool { + matches!(self.help.state, Tip::Waiting { since, .. } if clock + 1e-6 < since + open_delay) + || self.tooltip_fading(clock, fade) + } + + /// Steps the tooltip's state; returns a wake delay when a wait starts. + fn step_help(&mut self, event: Event, delays: Delays, clock: f64, fade_out: bool) -> Option<std::time::Duration> { + let mut wake = None; + for effect in step(&mut self.help.state, event, delays) { + match effect { + Effect::WakeAt(due) => wake = Some(std::time::Duration::from_secs_f64((due - clock).max(0.0))), + Effect::FadeOut => { + self.help.tip = None; + self.help.leaving = self.help.drawn.take().filter(|_| fade_out).map(|d| (d, clock)); + } + } + } + wake + } +} + +impl RuntimeCore { + /// The look tooltips draw in now: the view's, or the system's for this window. + fn help_look(&self) -> super::HelpLook { + self.commit.defaults.help.unwrap_or_else(|| super::HelpLook::system(self.backdrop_dark().unwrap_or(self.env.system_dark))) + } + + /// The host shows the system's own tooltips for [`Runtime::help_regions`], so Rune draws none. + #[cfg(target_os = "macos")] + #[inline] + pub(crate) fn set_native_help(&mut self, on: bool) { self.pointer.set_native_help(on); } + + /// Each visible help element's rect (window points, x0 y0 x1 y1) and text, in paint order, + /// for a host that shows system tooltips. + #[inline] + pub fn help_regions(&self) -> &[([f32; 4], String)] { self.pointer.help_regions() } + + /// The tooltip Rune shows now: its text and box (window points, x y w h). + #[inline] + pub fn help_tooltip(&self) -> Option<(&str, [f32; 4])> { self.pointer.help_tooltip() } + + /// A tooltip waits for a frame at or after its delay to draw, or fades in or out. + pub(in crate::runtime) fn tooltip_waiting(&self) -> bool { + let look = self.help_look(); + self.pointer.tooltip_waiting(self.clock, look.delay.unwrap_or(self.help_delay), look.fade) + } + + /// The look's delays, the runtime's `help_delay` where it sets none. + fn help_delays(&self) -> Delays { + let look = self.help_look(); + Delays { open: look.delay.unwrap_or(self.help_delay), skip: look.skip } + } + + /// During `build`: the line boxes of node `i`'s links that have help, for border box + /// `rect` and clipped to `clip` (points, x0 y0 x1 y1), after the first `seq` hits. + pub(in crate::runtime) fn push_link_help_hits(&mut self, i: usize, rect: [f32; 4], clip: [f32; 4], seq: usize) { + let Some(t) = self.tree.nodes[i].text.as_ref() else { return }; + if !t.cold.links.iter().any(|l| l.help.is_some()) { return; } + let id = self.tree.nodes[i].id; + for (k, r) in self.link_boxes(i, rect) { + if self.tree.nodes[i].text.as_ref().and_then(|t| t.cold.links.get(k)).is_none_or(|l| l.help.is_none()) { continue; } + let c = [r[0].max(clip[0]), r[1].max(clip[1]), r[2].min(clip[2]), r[3].min(clip[3])]; + self.hit.push_help_hit(id, c, seq, Some(k)); + } + } + + /// The help text of node `i`, or of its link `link`. + fn help_text(&self, i: usize, link: Option<usize>) -> Option<&String> { + match link { + Some(k) => self.tree.nodes[i].text.as_ref()?.cold.links.get(k)?.help.as_ref(), + None => self.tree.nodes[i].help.as_ref(), + } + } + + #[inline] + pub(in crate::runtime) fn clear_help_hits(&mut self) { self.hit.clear_help_hits(); } + + /// A scroll or key: hide the tooltip until the pointer leaves its element. + pub(in crate::runtime) fn dismiss_help(&mut self) { + if self.pointer.help.state.target().is_some() { + let look = self.help_look(); + let delays = Delays { open: look.delay.unwrap_or(self.help_delay), skip: look.skip }; + let fade_out = look.fade[1] > 0.0 && !self.reduced_motion; + if let Some(delay) = self.pointer.step_help(Event::Dismiss, delays, self.clock, fade_out) { + self.schedule_wakes([delay]); + } + } + } + + /// The help element under (x, y): the topmost one, unless something interactive drawn over + /// it (not inside it) is there too. + fn help_at(&self, x: f32, y: f32) -> Option<(usize, Option<usize>)> { + self.help_under(x, y).filter(|u| u.2).map(|(h, link, _)| (h, link)) + } + + /// The topmost help element under (x, y), and whether the pointer reaches it: not behind a + /// modal, and nothing interactive drawn over it (not inside it) is there too. + fn help_under(&self, x: f32, y: f32) -> Option<(usize, Option<usize>, bool)> { + let (id, seq, link) = self.hit.top_help(|id, r| self.hit_contains(id, r, x, y))?; + let h = *self.tree.node_index.get(&id)?; + if self.subtree_exiting(h) { return None; } + let over = self.hit.top_hit_index(|id, r| self.hit_contains(id, r, x, y)); + let covered = over.is_some_and(|(k, top)| { + k >= seq && self.tree.node_index.get(&top).is_some_and(|&t| !std::iter::successors(Some(t), |&p| self.tree.nodes[p].parent).any(|p| p == h)) + }); + Some((h, link, self.allowed(h) && !covered)) + } + + /// Whether moving the pointer to (x, y) changes the help element under it, so a host that + /// skips frames for unchanged pixels still starts or ends a tooltip's wait. + pub(in crate::runtime) fn help_target_changes(&self, x: f32, y: f32) -> bool { + let target = self.pointer.help.state.target(); + if self.pointer.native_help(self.commit.defaults.help.is_some()) || !self.hit.has_help_hits() && target.is_none() { return false; } + let at = self.help_at(x, y).map(|(i, k)| (self.tree.nodes[i].path.as_str(), k)); + at != target.map(|t| (t.path.as_str(), t.link)) + } + + /// What the pointer is over for the tooltip, and the node of a help element it reaches. + fn help_over(&self) -> (Over, Option<usize>) { + let target = |i: usize, link| Target { path: self.tree.nodes[i].path.clone(), link }; + // A tooltip held open shows first (a Copy button's "Copied"). + // Noted as the frame's help hits were pushed (`HitState::help_held`): no walk, and no + // lookup at all when nothing is held open, as almost always. + if let Some(i) = self.hit.help_held.and_then(|id| self.tree.node_index.get(&id).copied()) { return (Over::Forced(target(i, None)), Some(i)); } + let (over, under) = self.pointer_help_over(); + // With the pointer on no help element, the one the keyboard focused shows its own. + if matches!(over, Over::Nothing | Over::Away) && self.help_look().on_focus && self.kbd.focus.keyboard() + && let Some(i) = self.focused_index() + && self.tree.nodes[i].help.is_some() && self.allowed(i) && !self.subtree_exiting(i) + { + return (Over::Focused(target(i, None)), Some(i)); + } + (over, under) + } + + /// What the pointer is over for the tooltip. + fn pointer_help_over(&self) -> (Over, Option<usize>) { + // A menu is up or about to open and has the pointer: the element it came from keeps + // its tooltip hidden. + if !self.host.popups.is_empty() { return (self.pointer.help.state.target().cloned().map_or(Over::Away, Over::Covered), None); } + let Some((x, y)) = self.pointer.pos.filter(|&(x, y)| self.in_viewport(x, y)) else { return (Over::Away, None) }; + let target = |i: usize, link| Target { path: self.tree.nodes[i].path.clone(), link }; + // While moving layout holds hover, the tooltip keeps its element, and nothing sliding + // under the pointer starts a wait. + if self.held_hover().is_some() { + let kept = self.pointer.help.state.target().and_then(|t| Some((self.hover_live(&t.path)?, t.link))); + return kept.map_or((Over::Nothing, None), |(i, k)| (Over::Help(target(i, k)), Some(i))); + } + let Some((i, link, reaches)) = self.help_under(x, y) else { return (Over::Nothing, None) }; + let at = target(i, link); + // A press holds the pointer: a drag across other elements starts no tooltip. + if self.pointer.captured() && self.pointer.help.state.target() != Some(&at) { + return (Over::Nothing, None); + } + if reaches { (Over::Help(at), Some(i)) } else { (Over::Covered(at), None) } + } + + /// The parts of help element `h`'s rect `r` that nothing interactive drawn over it (not + /// inside it), from hit `seq` on, covers. + fn unoccluded(&self, h: usize, r: [f32; 4], seq: usize) -> Vec<[f32; 4]> { + let mut parts = vec![self.hit_screen_rect(self.tree.nodes[h].id, r)]; + for &(id, o) in self.hit.hits_since(seq) { + let o = self.hit_screen_rect(id, o); + if !parts.iter().any(|p| overlaps(*p, o)) { continue; } + let Some(&t) = self.tree.node_index.get(&id) else { continue }; + if std::iter::successors(Some(t), |&p| self.tree.nodes[p].parent).any(|p| p == h) { continue; } + parts = parts.into_iter().flat_map(|p| subtract(p, o)).collect(); + } + parts + } + + /// After `build`'s hits: track the rest, show or hide the tooltip and draw it. + pub(in crate::runtime) fn update_help(&mut self) { + self.pointer.help.regions.clear(); + if self.pointer.native_help(self.commit.defaults.help.is_some()) { + // Nothing behind a modal, and only where nothing else is drawn over the element. + let mut regions = Vec::new(); + for &(id, r, seq, link) in self.hit.help_hits() { + let Some(&i) = self.tree.node_index.get(&id) else { continue }; + let Some(text) = self.help_text(i, link) else { continue }; + if self.subtree_exiting(i) || !self.allowed(i) { continue; } + let words = crate::el::help_words(text); + regions.extend(self.unoccluded(i, r, seq).into_iter().map(|p| (p, words.clone().into_owned()))); + } + self.pointer.help.regions = regions; + self.pointer.help.tip = None; + self.pointer.help.state = Tip::Idle; + self.pointer.help.drawn = None; + self.pointer.help.leaving = None; + return; + } + let (over, under) = self.help_over(); + let look = self.help_look(); + let delays = self.help_delays(); + let fade_out = look.fade[1] > 0.0 && !self.reduced_motion; + if let Some(delay) = self.pointer.step_help(Event::Frame { over, now: self.clock }, delays, self.clock, fade_out) { + self.schedule_wakes([delay]); + } + self.pointer.help.tip = None; + let motion = !self.reduced_motion; + // The closed tooltip fades out first, under the next one. + if let Some((d, at)) = self.pointer.help.leaving.take() { + let t = if motion && look.fade[1] > 0.0 { ((self.clock - at) / look.fade[1]) as f32 } else { 1.0 }; + if t < 1.0 { + let e = rune_motion::Easing::EASE_IN.eval(t); + let scale = d.scale + (look.fade_scale - d.scale) * e; + self.draw_tooltip(&Drawn { alpha: d.alpha * (1.0 - e), scale, ..d.clone() }); + self.pointer.help.leaving = Some((d, at)); + } + } + self.pointer.help.drawn = None; + if let Tip::Open { target, since } = &self.pointer.help.state { + let (link, since) = (target.link, *since); + let node = under.or_else(|| self.hover_live(&target.path)); + if let Some(i) = node && let Some(text) = self.help_text(i, link).cloned() { + let e = self.drawn_box(i); + let anchor = link.and_then(|k| self.link_boxes(i, e).into_iter().filter(|(j, _)| *j == k).map(|(_, r)| r) + .reduce(|u, r| [u[0].min(r[0]), u[1].min(r[1]), u[2].max(r[2]), u[3].max(r[3])])); + let box_rect = anchor.unwrap_or(e); + if box_rect[2] <= box_rect[0] && box_rect[3] <= box_rect[1] { + let path = self.tree.nodes[i].path.clone(); + if self.paint.unresolved_anchor_warnings.insert((path.clone(), "<tooltip>".to_owned())) { + eprintln!("rune: tooltip on {path:?} skipped because its anchor rect is empty (never drawn at origin)"); + } + } else { + let side = link.is_none().then(|| self.tree.nodes[i].cold.get().and_then(|c| c.help_side)).flatten(); + let t = if motion && look.fade[0] > 0.0 { ((self.clock - since) / look.fade[0]) as f32 } else { 1.0 }; + let e_in = rune_motion::Easing::EASE_OUT.eval(t.clamp(0.0, 1.0)); + let d = Drawn { text, anchor: box_rect, side, alpha: e_in, scale: look.fade_scale + (1.0 - look.fade_scale) * e_in }; + let [x, y, w, h] = self.draw_tooltip(&d); + self.pointer.help.tip = Some((crate::el::help_words(&d.text).into_owned(), [x, y, w, h])); + self.pointer.help.drawn = Some(d); + } + } + } + if self.pointer.tooltip_fading(self.clock, look.fade) { self.schedule_wakes([std::time::Duration::ZERO]); } + } + + /// Draws `d`'s text (and its keycaps) in a tooltip in the current look under its box + /// (above it when there's no room below), or on the side it asks for (the opposite one when + /// there's no room there), kept inside the window. Returns the tooltip's box at full size + /// (window points, x y w h); it draws at `d.alpha`, scaled by `d.scale` about the middle + /// of the edge that faces its box. + fn draw_tooltip(&mut self, d: &Drawn) -> [f32; 4] { + let e = d.anchor; + debug_assert!(e[2] > e[0] || e[3] > e[1], "draw_tooltip called with empty anchor rect {e:?}"); + let s = self.env.scale; + let look = self.help_look(); + let key = look.key; + let [pad_x, pad_y] = look.padding; + let (vw, vh) = self.viewport; + let margin = look.margin; + let wrap = look.max_w.unwrap_or(vw - 2.0 * margin - 2.0 * pad_x).max(1.0); + // Each row (`El::help_row`) is its words, then its keycaps. + let mut rows = Vec::new(); + for row in d.text.split(crate::el::HELP_ROW) { + let mut parts = row.split(crate::el::HELP_KEY); + let words = parts.next().unwrap_or_default(); + let caps: Vec<_> = parts.map(|k| { + let k = if key.upper { k.to_uppercase() } else { k.to_owned() }; + let l = self.text.layout_rich(&k, &[], key.font, s, None); + let w = ((l.full_width() / s).ceil() + 2.0 * key.pad_x).max(key.height); + (l, w) + }).collect(); + let keys_w = if caps.is_empty() { 0.0 } else { + caps.iter().map(|(_, w)| w).sum::<f32>() + key.gap * (caps.len() - 1) as f32 + if words.is_empty() { 0.0 } else { key.lead } + }; + let layout = self.text.layout_rich(words, &[], look.font, s, Some((wrap - keys_w).max(1.0) * s)); + let (tw, th) = if words.is_empty() { (0.0, 0.0) } else { ((layout.full_width() / s).ceil(), (layout.height() / s).ceil()) }; + let ch = if caps.is_empty() { th } else { th.max(key.height) }; + rows.push(TipRow { words: !words.is_empty(), layout, tw, th, ch, caps, keys_w }); + } + let gaps = look.row_gap * rows.len().saturating_sub(1) as f32; + let w = rows.iter().map(|r| r.tw + r.keys_w).fold(0.0, f32::max) + 2.0 * pad_x; + let h = rows.iter().map(|r| r.ch).sum::<f32>() + gaps + 2.0 * pad_y; + let [below, over] = look.gap; + let (x, y) = match d.side { + // Beside it, centred down it: right of it unless only the left has room, and the + // other way round (`placement="right"` / `"left"`). + Some(side @ (crate::Side::Left | crate::Side::Right)) => { + let (left, right) = (e[0] - over - w, e[2] + over); + let (fits_left, fits_right) = (left >= margin, right + w <= vw - margin); + let on_left = if side == crate::Side::Left { fits_left || !fits_right } else { fits_left && !fits_right }; + let x = if on_left { left } else { right }; + (x, (e[1] + e[3] - h) * 0.5) + } + side => { + let mut y = e[3] + below; + if side == Some(crate::Side::Top) && e[1] - over - h >= margin { + y = e[1] - over - h; + } else if y + h > vh - margin && e[1] - below - h >= margin { + y = e[1] - below - h; + } + ((e[0] + e[2] - w) * 0.5, y) + } + }; + let x = x.clamp(margin, (vw - w - margin).max(margin)); + let y = y.clamp(margin, (vh - h - margin).max(margin)); + let full = [x * s, y * s, w * s, h * s].map(|v| v.round()); + // Scales about the middle of the edge facing the element (Kobalte's transform origin). + let (k, alpha) = (d.scale, d.alpha); + let pivot = if x >= e[2] { + [full[0], ((e[1] + e[3]) * 0.5 * s).clamp(full[1], full[1] + full[3])] + } else if x + w <= e[0] { + [full[0] + full[2], ((e[1] + e[3]) * 0.5 * s).clamp(full[1], full[1] + full[3])] + } else { + [((e[0] + e[2]) * 0.5 * s).clamp(full[0], full[0] + full[2]), if y >= e[3] { full[1] } else { full[1] + full[3] }] + }; + let at_k = |p: [f32; 2]| [pivot[0] + (p[0] - pivot[0]) * k, pivot[1] + (p[1] - pivot[1]) * k]; + let rect_k = |r: [f32; 4]| { let [x, y] = at_k([r[0], r[1]]); [x, y, r[2] * k, r[3] * k] }; + let r = rect_k(full); + let srgb = self.paint.srgb_blend; + let radii = [look.radius * s * k; 4]; + let cast = super::shadow_paint::Caster { + rect: r, radii, shape: radii, k_px: s, scale: s, opacity: alpha, srgb, clip: NO_CLIP, fade: [0.0; 4], hole: None, + opaque: look.fill.a >= 1.0, + }; + for sh in look.shadows.iter().flatten().filter(|sh| sh.color.a > 0.0) { + super::shadow_paint::push_shadow(&mut self.instances, sh, sh.color, &cast); + } + let (ring_w, ring) = look.ring.map_or((0.0, Color::TRANSPARENT), |(rw, c)| ((rw * s).max(1.0), c)); + self.instances.push(Instance { + rect: r, + radii, + fill: premul(look.fill, alpha, srgb), + border: premul(ring, alpha, srgb), + params: [ring_w, KIND_RECT, 0.0, 1.0], + uv: [0.0; 4], + clip: NO_CLIP, + fade: crate::render::pack_fade([0.0; 4], NO_CLIP, NO_CLIP), + }); + let mut top = full[1] + pad_y * s; + // In a right-to-left app a row reads from the right: its words, then its keycaps to their + // left, as the mirrored tooltip of a browser in Arabic or Hebrew does. + let rtl = crate::labels::rtl(); + for row in &rows { + let mut at = full[0] + pad_x * s; + let words_at = if rtl { full[0] + full[2] - pad_x * s - row.tw * s } else { at }; + if row.words { + // Right-to-left words align to the right of the width they broke at: back into the box. + let shift = if row.layout.is_rtl() { (wrap - row.keys_w).max(1.0) * s - row.layout.full_width() } else { 0.0 }; + self.draw_tip_text(&row.layout, at_k([words_at - shift, top + ((row.ch - row.th) * 0.5 * s).round()]), k, look.ink, alpha); + if !rtl { at += (row.tw + key.lead) * s; } + } + // Right to left, the keycaps end the lead short of the words (`keys_w` holds it). + if rtl { at = words_at - row.keys_w * s; } + for (l, cw) in &row.caps { + let cap = [at, top + ((row.ch - key.height) * 0.5 * s).round(), cw * s, key.height * s].map(|v| v.round()); + self.instances.push(Instance { + rect: rect_k(cap), + radii: [key.radius * s * k; 4], + fill: premul(key.fill, alpha, srgb), + border: [0.0; 4], + params: [0.0, KIND_RECT, 0.0, 1.0], + uv: [0.0; 4], + clip: NO_CLIP, + fade: crate::render::pack_fade([0.0; 4], NO_CLIP, NO_CLIP), + }); + let lw = l.full_width(); + let origin = [cap[0] + ((cap[2] - lw) * 0.5).round(), cap[1] + ((cap[3] - l.height()) * 0.5).round()]; + self.draw_tip_text(l, at_k(origin), k, key.ink, alpha); + at += (cw + key.gap) * s; + } + top += (row.ch + look.row_gap) * s; + } + [x, y, w, h] + } + + /// Draws a tooltip's shaped text with its top left at `origin` (device pixels), scaled by + /// `k` and at `alpha`. + fn draw_tip_text(&mut self, layout: &parley::Layout<crate::text::Ink>, origin: [f32; 2], k: f32, ink: Color, alpha: f32) { + let srgb = self.paint.srgb_blend; + self.paint.glyph_scratch.clear(); + self.text.set_glyph_inks(ink, &[]); + self.text.glyphs_for_layout_scaled(layout, origin, k, false, &mut self.paint.glyph_scratch); + for q in &self.paint.glyph_scratch { + self.instances.extend(glyph_or_image(q, &self.text, &mut self.images, premul(ink, alpha, srgb), NO_CLIP, [0.0; 4])); + } + } +} + +#[cfg(test)] +#[path = "help_tests.rs"] +mod tests; diff --git a/app/vendor/rune/crates/rune/src/runtime/input/help_look.rs b/app/vendor/rune/crates/rune/src/runtime/input/help_look.rs new file mode 100644 index 0000000..e8249de --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/input/help_look.rs @@ -0,0 +1,195 @@ +//! How Rune draws [`El::help`](crate::El::help) tooltips: the system look by default, or an +//! app's own ([`Cx::help_look`](crate::Cx::help_look)), as a web page styles its tooltips. +use crate::el::Shadow; +use crate::{Color, TextStyle}; + +/// The most box shadows a tooltip draws. +const SHADOWS: usize = 4; + +/// A tooltip's surface, type, placement and timing. [`HelpLook::system`] is Rune's own look; +/// each builder overrides one thing, e.g. a design system's compact tooltip: +/// `HelpLook::system(dark).fill(layer).ink(text).radius(4.0).padding(6.0, 5.0).font(small).gap(4.0).delay(0.4)`. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct HelpLook { + pub(crate) fill: Color, + pub(crate) ink: Color, + pub(crate) ring: Option<(f32, Color)>, + pub(crate) radius: f32, + pub(crate) padding: [f32; 2], + pub(crate) font: TextStyle, + pub(crate) max_w: Option<f32>, + /// Points between the element and a tooltip under it, and over it. + pub(crate) gap: [f32; 2], + /// The tooltip keeps this far inside the window. + pub(crate) margin: f32, + /// `None`: the runtime's `help_delay`. + pub(crate) delay: Option<f64>, + pub(crate) skip: f64, + /// The keyboard focusing a help element shows its tooltip at once (`HelpLook::on_focus`). + pub(crate) on_focus: bool, + /// Seconds the tooltip fades in and out (`HelpLook::fade`); 0 shows or hides at once. + pub(crate) fade: [f64; 2], + /// The scale it fades in from and out to. + pub(crate) fade_scale: f32, + pub(crate) shadows: [Option<Shadow>; SHADOWS], + /// [`El::help_keys`](crate::El::help_keys)' keycaps. + pub(crate) key: KeyCap, + /// Points between two rows ([`El::help_row`](crate::El::help_row)). + pub(crate) row_gap: f32, +} + +/// How a tooltip draws its keycaps. +#[derive(Clone, Copy, Debug, PartialEq)] +pub(crate) struct KeyCap { + pub(crate) fill: Color, + pub(crate) ink: Color, + pub(crate) font: TextStyle, + pub(crate) height: f32, + pub(crate) pad_x: f32, + pub(crate) radius: f32, + /// Points between two keycaps. + pub(crate) gap: f32, + /// Points between the text and the first keycap. + pub(crate) lead: f32, + pub(crate) upper: bool, +} + +impl HelpLook { + /// Rune's own tooltip for a light or dark window: a pale or dark grey card with a hairline + /// edge, 12 pt text, under its element 6 pt clear (over it 4 pt clear), after the + /// runtime's `help_delay`. + pub fn system(dark: bool) -> HelpLook { + let grey = |v: f32| Color { r: v, g: v, b: v, a: 1.0 }; + let (fill, ink, edge) = if dark { + (grey(0.17), grey(0.93), Color::WHITE.alpha(0.14)) + } else { + (grey(0.98), grey(0.11), Color::BLACK.alpha(0.16)) + }; + HelpLook { + fill, + ink, + ring: Some((1.0, edge)), + radius: 5.0, + padding: [7.0, 4.0], + font: TextStyle::new(12.0, 400.0).lh(16.0), + max_w: Some(300.0), + gap: [6.0, 4.0], + margin: 4.0, + delay: None, + skip: 0.0, + on_focus: false, + fade: [0.0; 2], + fade_scale: 1.0, + shadows: [None; SHADOWS], + key: KeyCap { + fill: ink.alpha(0.08), + ink: ink.alpha(0.7), + font: TextStyle::new(11.0, 500.0).lh(11.0), + height: 16.0, + pad_x: 4.0, + radius: 3.0, + gap: 2.0, + lead: 6.0, + upper: false, + }, + row_gap: 4.0, + } + } + /// Points between two rows of a tooltip with [`El::help_row`](crate::El::help_row)s. + pub fn row_gap(mut self, gap: f32) -> Self { + self.row_gap = if gap.is_finite() { gap.max(0.0) } else { 0.0 }; + self + } + /// Keycaps ([`El::help_keys`](crate::El::help_keys)) on `fill`, their labels in `font` and + /// `ink`, uppercased when `upper`. + pub fn keycaps(mut self, fill: Color, ink: Color, font: TextStyle, upper: bool) -> Self { + self.key = KeyCap { fill, ink, font, upper, ..self.key }; + self + } + /// A keycap's height, inner padding either side (its least width is its height) and corner + /// radius, `gap` points between two and `lead` points after the text. + pub fn keycap_shape(mut self, height: f32, pad_x: f32, radius: f32, gap: f32, lead: f32) -> Self { + self.key = KeyCap { height: height.max(0.0), pad_x: pad_x.max(0.0), radius: radius.max(0.0), gap: gap.max(0.0), lead: lead.max(0.0), ..self.key }; + self + } + pub fn fill(mut self, c: Color) -> Self { + self.fill = c; + self + } + /// The text colour. + pub fn ink(mut self, c: Color) -> Self { + self.ink = c; + self + } + /// A border `width` points wide inside the edge; 0 removes it. + pub fn ring(mut self, width: f32, c: Color) -> Self { + self.ring = (width > 0.0 && width.is_finite()).then_some((width, c)); + self + } + pub fn radius(mut self, r: f32) -> Self { + self.radius = r.max(0.0); + self + } + /// Horizontal and vertical padding around the text. + pub fn padding(mut self, x: f32, y: f32) -> Self { + self.padding = [x.max(0.0), y.max(0.0)]; + self + } + pub fn font(mut self, f: TextStyle) -> Self { + self.font = f; + self + } + /// The widest the tooltip grows before its text wraps; `None` for the window's width. + pub fn max_width(mut self, w: Option<f32>) -> Self { + self.max_w = w.filter(|w| *w > 0.0); + self + } + /// Points between the element and its tooltip, under it or over it (Kobalte's `gutter`). + pub fn gap(mut self, g: f32) -> Self { + self.gap = [g, g]; + self + } + /// How far the tooltip keeps inside the window's edges (a popper's overflow padding). + pub fn margin(mut self, m: f32) -> Self { + self.margin = m.max(0.0); + self + } + /// Seconds the pointer rests on an element before its tooltip shows, in place of the + /// runtime's `help_delay`. + pub fn delay(mut self, secs: f64) -> Self { + self.delay = Some(secs.max(0.0)); + self + } + /// For this long (seconds) after a tooltip hides, the next element's shows at once, as + /// a web tooltip's `skipDelayDuration` does when the pointer moves along a toolbar. + pub fn skip_delay(mut self, secs: f64) -> Self { + self.skip = secs.max(0.0); + self + } + /// The keyboard moving focus onto a help element (a Tab, an arrow) shows its tooltip at once, + /// with no delay, as a web tooltip opens on `focus`; a press that focuses it doesn't. The + /// pointer resting on another help element shows that one instead. Off by default. + pub fn on_focus(mut self, on: bool) -> Self { + self.on_focus = on; + self + } + /// The tooltip fades in over `enter` seconds (ease-out) and out over `exit` (ease-in), + /// growing from `scale` and shrinking back to it about the middle of the edge that faces + /// its element, as a web tooltip's open and close keyframes do. One closing as the next + /// opens (within the skip delay) fades out under it. 0 shows or hides at once, the + /// default; reduced motion never fades. + pub fn fade(mut self, enter: f64, exit: f64, scale: f32) -> Self { + self.fade = [enter.max(0.0), exit.max(0.0)]; + self.fade_scale = if scale.is_finite() { scale.clamp(0.0, 1.0) } else { 1.0 }; + self + } + /// Box-shadow layers, painted in order (the first four); empty for none. Inset shadows + /// are skipped. + pub fn shadows(mut self, layers: impl IntoIterator<Item = Shadow>) -> Self { + self.shadows = [None; SHADOWS]; + for (slot, s) in self.shadows.iter_mut().zip(layers.into_iter().filter(|s| !s.inset)) { + *slot = Some(s); + } + self + } +} diff --git a/app/vendor/rune/crates/rune/src/runtime/input/help_tests.rs b/app/vendor/rune/crates/rune/src/runtime/input/help_tests.rs new file mode 100644 index 0000000..ce2299d --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/input/help_tests.rs @@ -0,0 +1,105 @@ +use crate::{Cx, El, Env, el, row}; +use super::{Runtime, subtract}; + +#[derive(Default)] +struct S { modal: bool, cover: bool } + +fn view(s: &S, _: &mut Cx<S>) -> El { + let mut root = el().w_full().h_full() + .child(el().key("copy").size(40.0, 20.0).pin(Some(20.0), Some(20.0), None, None).help("Copy")) + .child(el().key("low").size(40.0, 20.0).pin(Some(20.0), Some(200.0), None, None).help("Low")); + if s.cover { + // A popover drawn over the right half of "copy". + root = root.child(el().key("pop").size(100.0, 60.0).pin(Some(40.0), Some(10.0), None, None).on_press(|_: &mut S| {})); + } + if s.modal { + root = root.child(row().key("sheet").size(80.0, 40.0).pin(Some(200.0), Some(200.0), None, None) + .modal(false, |_: &mut S| {}) + .child(el().key("inside").size(30.0, 20.0).help("Inside"))); + } + root +} + +fn runtime(s: S, native: bool) -> Runtime<S> { + let mut rt = Runtime::new(s, view, (300.0, 300.0), Env::new(true, 2.0)); + rt.pointer.help.native = native; + rt.frame(0.0); + rt +} + +fn texts(rt: &Runtime<S>) -> Vec<&str> { rt.help_regions().iter().map(|(_, t)| t.as_str()).collect() } + +#[test] +fn native_regions_skip_what_a_modal_or_popover_covers() { + let rt = runtime(S::default(), true); + assert_eq!(texts(&rt), ["Copy", "Low"]); + let rt = runtime(S { modal: true, ..S::default() }, true); + assert_eq!(texts(&rt), ["Inside"], "behind a modal, nothing registers"); + let rt = runtime(S { cover: true, ..S::default() }, true); + let copy: Vec<[f32; 4]> = rt.help_regions().iter().filter(|(_, t)| t == "Copy").map(|(r, _)| *r).collect(); + assert_eq!(copy, [[20.0, 20.0, 40.0, 40.0]], "only the uncovered half of copy"); +} + +#[test] +fn subtract_leaves_what_is_outside() { + assert_eq!(subtract([0.0, 0.0, 10.0, 10.0], [20.0, 0.0, 30.0, 10.0]), [[0.0, 0.0, 10.0, 10.0]]); + assert_eq!(subtract([0.0, 0.0, 10.0, 10.0], [-1.0, -1.0, 11.0, 11.0]), Vec::<[f32; 4]>::new()); + assert_eq!(subtract([0.0, 0.0, 10.0, 10.0], [4.0, 4.0, 6.0, 6.0]).len(), 4); +} + +#[test] +fn reaching_help_wakes_a_host_that_skips_unchanged_frames() { + // An overlay draws only when observe_pointer says something changed; help that has no + // hover paint of its own must still start its wait. + let mut rt = runtime(S::default(), false); + assert!(!rt.observe_pointer(150.0, 150.0), "nothing there"); + assert!(rt.observe_pointer(30.0, 30.0), "onto help"); + rt.frame(1.0 / 60.0); + assert!(!rt.observe_pointer(31.0, 30.0), "still on it"); + rt.frame(rt.help_delay); + assert!(rt.help_tooltip().is_some()); + assert!(rt.observe_pointer(150.0, 150.0), "off it hides the tooltip"); +} + +fn linked(k: &f32, _: &mut Cx<f32>) -> El { + let label = crate::text("MMMM MMMM") + .font(crate::TextStyle::new(16.0, 400.0)) + .link(crate::Link::new(0..4, "a")) + .link(crate::Link::new(5..9, "b").help("Goes to b")) + .on_link(|_: &mut f32, _, _| {}); + el().w_full().h_full().child(el().pin(Some(10.0), Some(10.0), None, None).scale(*k).child(label)) +} + +/// Rests on (x, y) past the delay and returns the tooltip shown. +fn rest(rt: &mut Runtime<f32>, x: f32, y: f32) -> Option<(String, [f32; 4])> { + rt.pointer_move(x, y); + rt.frame(1.0 / 60.0); + rt.frame(rt.help_delay + 0.1); + rt.help_tooltip().map(|(t, r)| (t.to_owned(), r)) +} + +#[test] +fn a_link_shows_its_own_help_under_its_glyphs() { + for k in [1.0, 1.6] { + let mut rt = Runtime::new(k, linked, (400.0, 300.0), Env::new(true, 2.0)); + rt.frame(0.0); + let i = rt.tree.nodes.iter().position(|n| n.text.is_some()).unwrap(); + let boxes = rt.link_boxes(i, rt.drawn_box(i)); + let b = boxes.iter().find(|(j, _)| *j == 1).unwrap().1; + let a = boxes.iter().find(|(j, _)| *j == 0).unwrap().1; + assert!(rest(&mut rt, (a[0] + a[2]) * 0.5, (a[1] + a[3]) * 0.5).is_none(), "zoom {k}: a link without help shows none"); + let (text, r) = rest(&mut rt, (b[0] + b[2]) * 0.5, (b[1] + b[3]) * 0.5).expect("tip on the link"); + assert_eq!(text, "Goes to b"); + assert!(r[1] >= b[3] && r[0] < b[2] && r[0] + r[2] > b[0], "zoom {k}: tip {r:?} sits under the link {b:?}"); + assert!(rest(&mut rt, 300.0, 250.0).is_none(), "leaving hides it"); + } +} + +#[test] +fn native_regions_carry_a_links_help() { + let mut rt = Runtime::new(1.0, linked, (400.0, 300.0), Env::new(true, 2.0)); + rt.pointer.help.native = true; + rt.frame(0.0); + let texts: Vec<&str> = rt.help_regions().iter().map(|(_, t)| t.as_str()).collect(); + assert_eq!(texts, ["Goes to b"]); +} diff --git a/app/vendor/rune/crates/rune/src/runtime/input/hit.rs b/app/vendor/rune/crates/rune/src/runtime/input/hit.rs new file mode 100644 index 0000000..7c127a9 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/input/hit.rs @@ -0,0 +1,429 @@ +//! Hit-test geometry, turned-layer coordinate mapping, target resolution and per-frame hit +//! registration. +use super::*; + +/// Per-frame hit-test lists built during paint in paint order and queried by pointer, wheel and +/// overlay hit testing. Kept together under `#[repr(C)]` because the per-node paint walk and +/// `keep_swap` read and swap all five lists together. +#[repr(C)] +pub(in crate::runtime) struct HitState { + pub(in crate::runtime) hits: Vec<(NodeId, [f32; 4])>, + /// What a wheel chains up from, in paint order: what takes input, every scroll view and every + /// painted surface (`Runtime::chain_start`). + pub(in crate::runtime) wheel_hits: Vec<(NodeId, [f32; 4])>, + pub(in crate::runtime) overlay_hits: Vec<[f32; 4]>, + /// This frame's help elements: (node, visible rect in points, `hits.len()` before it, the + /// link of its text when the help is that link's). + pub(in crate::runtime) help_hits: Vec<(NodeId, [f32; 4], usize, Option<usize>)>, + /// The first help element this frame that `El::help_open` holds open, noted as its hit is + /// pushed, so the tooltip finds it without walking `help_hits`. + pub(in crate::runtime) help_held: Option<NodeId>, + /// This frame's drop targets: (node, visible rect in points, `hits.len()` before it). Kept + /// apart from `hits`, so a drop zone doesn't cover the context menus and help under it. + pub(in crate::runtime) drop_hits: Vec<(NodeId, [f32; 4], usize)>, +} + +impl HitState { + // Single-caller constructor for `RuntimeCore::new`; inlined so it stays in its caller's + // codegen unit instead of shifting partitioning and dropping inlining in the paint walk. + #[inline] + pub(in crate::runtime) fn new() -> Self { + Self { + hits: Vec::new(), + wheel_hits: Vec::new(), + help_hits: Vec::new(), + help_held: None, + drop_hits: Vec::new(), + overlay_hits: Vec::new(), + } + } + + #[inline] + pub(in crate::runtime) fn overlay_hits(&self) -> &[[f32; 4]] { &self.overlay_hits } + + #[inline] + pub(in crate::runtime) fn hits(&self) -> &[(NodeId, [f32; 4])] { &self.hits } + + #[inline] + pub(in crate::runtime) fn hits_len(&self) -> usize { self.hits.len() } + + #[inline] + pub(in crate::runtime) fn hits_since(&self, seq: usize) -> &[(NodeId, [f32; 4])] { + &self.hits[seq.min(self.hits.len())..] + } + + #[inline] + pub(in crate::runtime) fn help_hits(&self) -> &[(NodeId, [f32; 4], usize, Option<usize>)] { &self.help_hits } + + #[inline] + pub(in crate::runtime) fn has_help_hits(&self) -> bool { !self.help_hits.is_empty() } + + #[inline] + pub(in crate::runtime) fn clear_help_hits(&mut self) { self.help_hits.clear(); self.help_held = None; } + + #[inline] + pub(in crate::runtime) fn clear_drop_hits(&mut self) { self.drop_hits.clear(); } + + #[inline] + pub(in crate::runtime) fn push_hit(&mut self, id: NodeId, rect: [f32; 4]) { + self.hits.push((id, rect)); + } + + #[inline] + pub(in crate::runtime) fn push_wheel_hit(&mut self, id: NodeId, rect: [f32; 4]) { + if rect[2] > rect[0] && rect[3] > rect[1] { + self.wheel_hits.push((id, rect)); + } + } + + #[inline] + pub(in crate::runtime) fn push_overlay_hit(&mut self, rect: [f32; 4]) { + self.overlay_hits.push(rect); + } + + /// During `build`: node `id` (or its `link`) has help and draws visible over `rect` + /// (points, x0 y0 x1 y1), after the first `seq` hits. + #[inline] + pub(in crate::runtime) fn push_help_hit(&mut self, id: NodeId, rect: [f32; 4], seq: usize, link: Option<usize>) { + if rect[2] > rect[0] && rect[3] > rect[1] { + self.help_hits.push((id, rect, seq, link)); + } + } + + /// During `build`: drop target `id` draws visible over `rect`, after the first `seq` hits. + #[inline] + pub(in crate::runtime) fn push_drop_hit(&mut self, id: NodeId, rect: [f32; 4], seq: usize) { + if rect[2] > rect[0] && rect[3] > rect[1] { + self.drop_hits.push((id, rect, seq)); + } + } + + /// Topmost hit whose rect passes `contains`. + #[inline] + pub(in crate::runtime) fn top_hit(&self, mut contains: impl FnMut(NodeId, [f32; 4]) -> bool) -> Option<NodeId> { + self.hits.iter().rev().find(|&&(id, r)| contains(id, r)).map(|&(id, _)| id) + } + + /// Index and node of the topmost hit whose rect passes `contains`. + #[inline] + pub(in crate::runtime) fn top_hit_index(&self, mut contains: impl FnMut(NodeId, [f32; 4]) -> bool) -> Option<(usize, NodeId)> { + self.hits.iter().enumerate().rev().find(|&(_, &(id, r))| contains(id, r)).map(|(k, &(id, _))| (k, id)) + } + + /// Walks hits top-to-bottom and returns the first match from `f`. + #[inline] + pub(in crate::runtime) fn find_hit<T>(&self, mut f: impl FnMut(NodeId, [f32; 4]) -> Option<T>) -> Option<T> { + self.hits.iter().rev().find_map(|&(id, r)| f(id, r)) + } + + /// Walks wheel hits top-to-bottom and returns the first match from `f`. + #[inline] + pub(in crate::runtime) fn find_wheel_hit<T>(&self, mut f: impl FnMut(NodeId, [f32; 4]) -> Option<T>) -> Option<T> { + self.wheel_hits.iter().rev().find_map(|&(id, r)| f(id, r)) + } + + /// Topmost help entry whose rect passes `contains`. + #[inline] + pub(in crate::runtime) fn top_help(&self, mut contains: impl FnMut(NodeId, [f32; 4]) -> bool) -> Option<(NodeId, usize, Option<usize>)> { + self.help_hits.iter().rev().find(|&&(id, r, _, _)| contains(id, r)).map(|&(id, _, seq, link)| (id, seq, link)) + } + + /// Topmost resolved hit or drop zone at the point: whichever painted later wins. + #[inline] + pub(in crate::runtime) fn top_drop_or_hit( + &self, + mut contains: impl FnMut(NodeId, [f32; 4]) -> bool, + mut resolve: impl FnMut(NodeId) -> Option<usize>, + ) -> Option<usize> { + let hit = self.hits.iter().enumerate().rev() + .find_map(|(k, &(id, r))| contains(id, r).then(|| resolve(id)).flatten().map(|i| (k, i))); + let zone = self.drop_hits.iter().rev() + .find_map(|&(id, r, seq)| contains(id, r).then(|| resolve(id)).flatten().map(|i| (seq, i))); + match (hit, zone) { + (Some((k, h)), Some((seq, z))) => Some(if k >= seq { h } else { z }), + (h, z) => h.or(z).map(|(_, i)| i), + } + } + + /// Whether `id` has any hit rects this frame, and if so whether any passes `contains`. + #[inline] + pub(in crate::runtime) fn has_node_hit(&self, id: NodeId, mut contains: impl FnMut(NodeId, [f32; 4]) -> bool) -> Option<bool> { + let mut hits = self.hits.iter().filter(|(hit, _)| *hit == id).peekable(); + hits.peek()?; + Some(hits.any(|&(id, r)| contains(id, r))) + } +} + +impl RuntimeCore { + /// Node `i`'s edges as drawn this frame (points, x0 y0 x1 y1), or its layout box before + /// it draws. + pub(in crate::runtime) fn drawn_edges(&self, i: usize) -> [f32; 4] { + self.paint.drawn.get(i).map_or(self.tree.nodes[i].target, |d| [d[0], d[1], d[0] + d[2], d[1] + d[3]]) + } + + /// Window point (x, y) as node `i`'s handlers see it. + pub(crate) fn pointer_event(&self, i: usize, x: f32, y: f32) -> PointerEvent { + let [lx, ly] = self.to_local(i, x, y); + PointerEvent { x: lx, y: ly, window_x: x, window_y: y } + } + + /// Window point (x, y) in node `i`'s own layout points: from its top-left as drawn, divided + /// by the scale it draws at, so it follows scrolling, `live_offset`, `live_scale`, + /// `El::scale` and `El::rotate`. From its layout box before it draws. + pub(crate) fn to_local(&self, i: usize, x: f32, y: f32) -> [f32; 2] { + let Some(d) = self.paint.drawn.get(i) else { + let t = self.tree.nodes[i].target; + return [x - t[0], y - t[1]]; + }; + let k = self.paint.drawn_scale.get(i).copied().unwrap_or(1.0).max(1e-4); + if self.paint.turn_scratch.is_empty() { + return [(x - d[0]) / k, (y - d[1]) / k]; + } + let (b, ux, uy) = self.unturned_box_and_point(i, x, y); + [(ux - b[0]) / k, (uy - b[1]) / k] + } + + /// The turn node `i` draws inside (`Inh::turn` is 1-based, 0 for none). + pub(in crate::runtime) fn turn_of(&self, i: usize) -> Option<Turn> { + self.paint.inh_scratch.get(i).and_then(|h| h.turn.checked_sub(1)).and_then(|k| self.paint.turn_scratch.get(k as usize)).copied() + } + + /// Node `i`'s unturned border box (points, x0 y0 x1 y1) and window point (x, y) unturned into + /// that layer's points. + pub(in crate::runtime) fn unturned_box_and_point(&self, i: usize, x: f32, y: f32) -> ([f32; 4], f32, f32) { + if let Some(t) = self.turn_of(i) + && let Some(&(b, _)) = self.paint.unturned_drawn.get(i) + { + let s = self.env.scale; + let [ux, uy] = t.unturn([x * s, y * s]).map(|v| v / s); + return (b, ux, uy); + } + (self.drawn_box(i), x, y) + } + + #[inline] + pub(in crate::runtime) fn hit_contains(&self, id: NodeId, r: [f32; 4], x: f32, y: f32) -> bool { + if self.paint.turn_scratch.is_empty() { + return contains(r, x, y); + } + self.hit_contains_turned(id, r, x, y) + } + + #[cold] + #[inline(never)] + fn hit_contains_turned(&self, id: NodeId, r: [f32; 4], x: f32, y: f32) -> bool { + let Some(&i) = self.tree.node_index.get(&id) else { return contains(r, x, y) }; + let Some(t) = self.turn_of(i) else { + return contains(r, x, y); + }; + let s = self.env.scale; + if !contains(t.outer_clip.map(|v| v / s), x, y) { + return false; + } + let [ux, uy] = t.unturn([x * s, y * s]).map(|v| v / s); + contains(r, ux, uy) + } + + pub(in crate::runtime) fn hit_screen_rect(&self, id: NodeId, r: [f32; 4]) -> [f32; 4] { + if self.paint.turn_scratch.is_empty() { + return r; + } + let Some(&i) = self.tree.node_index.get(&id) else { return r }; + let Some(t) = self.turn_of(i) else { + return r; + }; + let s = self.env.scale; + let b = t.bbox(r.map(|v| v * s)).map(|v| v / s); + let c = t.outer_clip.map(|v| v / s); + intersect(b, c) + } + + pub(in crate::runtime) fn node_contains(&self, i: usize, x: f32, y: f32) -> bool { + if !self.paint.turn_scratch.is_empty() + && let Some(turn_k) = self.paint.inh_scratch.get(i).map(|h| h.turn).filter(|&k| k != 0) + && let Some(&t) = self.paint.turn_scratch.get(turn_k as usize - 1) + && let Some(&(b, _)) = self.paint.unturned_drawn.get(i) + { + let s = self.env.scale; + if !contains(t.outer_clip.map(|v| v / s), x, y) { + return false; + } + let lc = self.tree.nodes[i].parent + .filter(|&p| self.paint.inh_scratch.get(p).is_some_and(|h| h.turn == turn_k)) + .and_then(|p| self.paint.unturned_drawn.get(p)) + .map_or(NO_CLIP, |u| u.1) + .map(|v| v / s); + let shown = intersect(b, lc); + let [ux, uy] = t.unturn([x * s, y * s]).map(|v| v / s); + return contains(shown, ux, uy); + } + let r = self.drawn_edges(i); + let c = self.tree.nodes[i].parent.and_then(|p| self.paint.inh_scratch.get(p)).map_or(NO_CLIP, |h| h.clip).map(|v| v / self.env.scale); + let shown = intersect(r, c); + contains(shown, x, y) + } + + pub(in crate::runtime) fn screen_clip_of_parent(&self, parent: Option<usize>) -> [f32; 4] { + screen_clip_of(parent, &self.paint.inh_scratch, &self.paint.turn_scratch) + } + + /// Unmounted in this commit (an instant removal), though still listed until the next. + pub(in crate::runtime) fn subtree_unmounted(&self, mut i: usize) -> bool { + loop { + if !self.scene.contains(self.tree.nodes[i].id) { return true; } + let Some(parent) = self.tree.nodes[i].parent else { return false }; + i = parent; + } + } + + pub(crate) fn is_exiting(&self, id: NodeId) -> bool { + matches!(self.scene.phase(id), Some(PresencePhase::Exiting { .. })) + } + + /// The single reachable editor in a textbox. Only resolve descendants on presses; + /// hover hit testing and cursor updates use the container's role directly. + pub(in crate::runtime) fn textbox_input(&self, i: usize) -> Option<usize> { + if self.tree.nodes[i].input.is_some() { return self.can_focus(i).then_some(i); } + if self.tree.nodes[i].role != "textbox" { return None; } + let mut inputs = (0..self.tree.nodes.len()).filter(|&j| { + self.tree.nodes[j].input.is_some() + && self.can_focus(j) + && std::iter::successors(self.tree.nodes[j].parent, |&p| self.tree.nodes[p].parent).any(|p| p == i) + }); + let first = inputs.next()?; + inputs.next().is_none().then_some(first) + } + + /// The topmost element under (x, y) that takes primary input, selectable text included. + pub(in crate::runtime) fn top_target(&self, x: f32, y: f32) -> Option<usize> { + self.hit.find_hit(|id, r| { + if !self.hit_contains(id, r, x, y) { return None; } + let i = *self.tree.node_index.get(&id)?; + let n = &self.tree.nodes[i]; + // A secondary-only child must not obscure primary input or background blur. + (!self.subtree_exiting(i) && self.allowed(i) && (n.has_primary_handler() || n.input.is_some() || n.role == "textbox" + || (n.role == "button" && n.vis_flags.hit()) || n.window_drag != crate::el::WindowDrag::None || n.focus.enabled || n.handlers.modal.is_some() + || self.is_selectable(i))).then_some(i) + }) + } + + /// The element a press, hover or drag at (x, y) goes to. Selectable text passes them to the + /// nearest ancestor that handles them (a clickable or draggable row), unless the text has + /// its own handlers or the point is on one of its links; selecting goes on beside that + /// (`selectable_at`). + pub(in crate::runtime) fn primary_target(&self, x: f32, y: f32) -> Option<usize> { + let i = self.top_target(x, y)?; + let n = &self.tree.nodes[i]; + if !self.is_selectable(i) || n.has_primary_handler() || self.link_at(i, x, y).is_some() { return Some(i); } + let handles = |n: &Node| n.has_primary_handler() || n.focus.enabled; + let mut p = n.parent; + while let Some(a) = p { + if self.subtree_exiting(a) || !self.allowed(a) || self.tree.nodes[a].handlers.modal.is_some() { break; } + if handles(&self.tree.nodes[a]) { return Some(a); } + p = self.tree.nodes[a].parent; + } + Some(i) + } + + /// A focusable scroll region, which a press on plain content inside it focuses, as a web + /// page focuses a `tabIndex` scroller. + pub(in crate::runtime) fn focuses_on_click(&self, i: usize) -> bool { + self.tree.nodes[i].scroll.is_some() && self.tree.nodes[i].focus.enabled + } + + /// The focusable scroll region a press at (x, y) lands in beneath `layer` + /// (`El::press_focuses_below`): the topmost element there outside the layer, or the nearest + /// region holding it. + pub(in crate::runtime) fn scroll_region_below(&self, layer: usize, x: f32, y: f32) -> Option<usize> { + let in_layer = |i: usize| std::iter::successors(Some(i), |&p| self.tree.nodes[p].parent).any(|p| p == layer); + let under = self.hit.find_hit(|id, r| { + if !self.hit_contains(id, r, x, y) { return None; } + let i = *self.tree.node_index.get(&id)?; + (!in_layer(i) && !self.subtree_exiting(i) && self.allowed(i)).then_some(i) + })?; + std::iter::successors(Some(under), |&p| self.tree.nodes[p].parent).find(|&p| self.focuses_on_click(p) && self.can_focus(p)) + } + + /// The selectable text under (x, y), if it's the topmost thing there that takes input. + pub(in crate::runtime) fn selectable_at(&self, x: f32, y: f32) -> Option<usize> { + self.top_target(x, y).filter(|&i| self.is_selectable(i)) + } + + /// The node at `path`, unless it is on its way out. + pub(crate) fn live_index(&self, path: &str) -> Option<usize> { + self.tree.nodes.iter().enumerate().position(|(i, n)| n.path == path && !self.subtree_exiting(i)) + } + + pub(in crate::runtime) fn in_viewport(&self, x: f32, y: f32) -> bool { + contains([0.0, 0.0, self.viewport.0, self.viewport.1], x, y) + } + + pub(in crate::runtime) fn register_node_hits( + &mut self, + i: usize, + pinh_clip: [f32; 4], + (effective_opacity, visible): (f32, bool), + rect_pt: [f32; 4], + (press_k, press_anchor): (f32, [f32; 2]), + ) { + let s = self.env.scale; + let n = &self.tree.nodes[i]; + let hits_before = self.hit.hits_len(); + if (n.vis_flags.hit() || n.handlers.get().is_some_and(crate::el::Handlers::takes_hit) || n.input.is_some() || n.role == "textbox" || n.window_drag != crate::el::WindowDrag::None || n.focus.get().is_some_and(|f| f.enabled) + || n.text.as_ref().is_some_and(|t| t.selectable)) + && !self.subtree_exiting(i) + && self.allowed(i) && effective_opacity > 0.001 && visible + { + let c = if n.parent.is_some() { pinh_clip } else { self.paint.inh_scratch[0].clip }; + let rect_pt = if (press_k - 1.0).abs() > 1e-5 { + let [ax, ay] = press_anchor; + [ax + (rect_pt[0] - ax) / press_k, ay + (rect_pt[1] - ay) / press_k, + ax + (rect_pt[2] - ax) / press_k, ay + (rect_pt[3] - ay) / press_k] + } else { rect_pt }; + let cr = [ + rect_pt[0].max(c[0] / s), + rect_pt[1].max(c[1] / s), + rect_pt[2].min(c[2] / s), + rect_pt[3].min(c[3] / s), + ]; + let rect = if n.parent.is_some() { cr } else { rect_pt }; + if !self.push_link_hits(i, rect_pt, rect) { self.hit.push_hit(self.tree.nodes[i].id, rect); } + let n = &self.tree.nodes[i]; + if n.vis_flags.hit() && effective_opacity > 0.0 && rect[2] > rect[0] && rect[3] > rect[1] { + let screen_rect = self.hit_screen_rect(n.id, rect); + self.hit.push_overlay_hit(screen_rect); + } + } + // What a wheel chains up from, in the same paint order: what takes input, every scroll + // view, and the roots of what is drawn over others (an anchored overlay, a `raise()`d + // panel, a sticky element), whatever their fill, so a wheel over any of them starts there, + // not on what lies beneath. Other boxes without a handler let the wheel through, as an + // element with `pointer-events: none` does. + let n = &self.tree.nodes[i]; + if (self.hit.hits_len() > hits_before || n.scroll.is_some() || n.above.is_some() || n.vis_flags.raise() || n.sticky.is_some()) + && !self.subtree_exiting(i) && self.allowed(i) && effective_opacity > 0.001 && visible + { + let c = if n.parent.is_some() { pinh_clip } else { self.paint.inh_scratch[0].clip }; + let r = if n.parent.is_some() { + [rect_pt[0].max(c[0] / s), rect_pt[1].max(c[1] / s), rect_pt[2].min(c[2] / s), rect_pt[3].min(c[3] / s)] + } else { rect_pt }; + self.hit.push_wheel_hit(n.id, r); + } + if self.tree.nodes[i].cold.get().is_some_and(|c| c.help.is_some() && (!c.help_cut || self.tree.nodes[i].text_cut(s))) && !self.subtree_exiting(i) && self.allowed(i) && effective_opacity > 0.001 && visible { + let c = if self.tree.nodes[i].parent.is_some() { pinh_clip } else { NO_CLIP }; + let r = [rect_pt[0].max(c[0] / s), rect_pt[1].max(c[1] / s), rect_pt[2].min(c[2] / s), rect_pt[3].min(c[3] / s)]; + self.hit.push_help_hit(self.tree.nodes[i].id, r, hits_before, None); + // The cold block the test above read: a held-open tooltip costs nothing to find later. + if self.hit.help_held.is_none() && r[2] > r[0] && r[3] > r[1] && self.tree.nodes[i].cold.get().is_some_and(|c| c.help_open) { self.hit.help_held = Some(self.tree.nodes[i].id); } + } + if self.tree.nodes[i].text.as_ref().is_some_and(|t| t.cold.links.iter().any(|l| l.help.is_some())) && !self.subtree_exiting(i) && self.allowed(i) && effective_opacity > 0.001 && visible { + let c = if self.tree.nodes[i].parent.is_some() { pinh_clip } else { NO_CLIP }; + self.push_link_help_hits(i, rect_pt, [c[0] / s, c[1] / s, c[2] / s, c[3] / s], hits_before); + } + if self.tree.nodes[i].handlers.get().is_some_and(|h| h.drop.is_some()) && !self.subtree_exiting(i) && self.allowed(i) && effective_opacity > 0.001 && visible { + let c = if self.tree.nodes[i].parent.is_some() { pinh_clip } else { NO_CLIP }; + let r = [rect_pt[0].max(c[0] / s), rect_pt[1].max(c[1] / s), rect_pt[2].min(c[2] / s), rect_pt[3].min(c[3] / s)]; + self.hit.push_drop_hit(self.tree.nodes[i].id, r, hits_before); + } + } +} diff --git a/app/vendor/rune/crates/rune/src/runtime/input/hover.rs b/app/vendor/rune/crates/rune/src/runtime/input/hover.rs new file mode 100644 index 0000000..5b6f088 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/input/hover.rs @@ -0,0 +1,415 @@ +//! Hover and press state: which elements the pointer is over, `on_hover_change` and its +//! delays, and the hover and press tracks hover styles and press scales animate. +use super::*; + +/// Hover under a pointer that hasn't moved while layout carries content under it: a row +/// expanding and the rows below sliding, a growth stack, a flight, a glide the app asked for. +/// As on macOS, where tracking areas enter and exit as the mouse moves and re-sync once layout +/// settles, hover doesn't light each row that passes: it waits for the motion to settle or the +/// pointer to move. What leaves the tree or turns inert lets go at once, and presses are never +/// held. +#[derive(Default)] +pub(in crate::runtime) struct HoverHold { + hold: Hold, + /// Scratch for the hover tracks `update_interaction` would change. + flips: Vec<Flip>, +} + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +enum Hold { + /// Hover follows the pointer, and moving layout may hold it. + #[default] + Free, + /// The last pass held hover: moving layout carried an element whose hover would change. + Held, + /// The pointer moved, pressed or a hand scrolled while layout moved: hover follows the + /// pointer until the motion settles. + Released, +} + +impl HoverHold { + /// The last pass held hover. + pub(in crate::runtime) fn held(&self) -> bool { self.hold == Hold::Held } + + /// Hover follows the pointer until layout settles. + pub(in crate::runtime) fn released(&self) -> bool { self.hold == Hold::Released } + + /// Notes whether this pass held hover. Released, nothing holds it. + fn set_held(&mut self, held: bool) { + if self.hold != Hold::Released { self.hold = if held { Hold::Held } else { Hold::Free }; } + } + + /// The hand moved: with layout `moving`, hover follows the pointer until it settles. + fn release(&mut self, moving: bool) { + if self.hold != Hold::Released { self.hold = if moving { Hold::Released } else { Hold::Free }; } + } + + /// Layout settled: a released hold may hold again. + fn settled(&mut self) { + if self.hold == Hold::Released { self.hold = Hold::Free; } + } +} + +/// Node `i`'s hover track: where it would go, how, whether that changes it, and whether it +/// lands now whatever the hold (a leave from an element turned inert). +#[derive(Clone, Copy)] +struct Flip { i: usize, id: NodeId, on: bool, anim: Anim, changed: bool, now: bool } + +/// What `hover_within` would become: the `on_hover_change` elements the pointer is inside, +/// and those of them entering. +type Within = (Vec<String>, Vec<usize>); + +/// Viewport `s` moves content under a still pointer on its own at `now`: a glide, an app's +/// instant scrolls frame after frame (a glide it steps itself), or slack letting rows down. +fn scroll_carries(s: &ScrollState, now: f64) -> bool { + s.glide().is_some() || s.mode.wheel().is_some() || s.x.carried() || s.hold_at(now) || s.slack.moving() +} + +/// `inner` is `outer` or inside it. +fn holds(outer: &str, inner: &str) -> bool { + inner == outer || inner.len() > outer.len() && inner.starts_with(outer) && inner.as_bytes()[outer.len()] == b'/' +} + +impl capture::PointerState { + /// Hover may wait on moving layout: the pointer is in the window, holds no press, and + /// hasn't moved since the motion started. + #[inline] + pub(super) fn hover_may_hold(&self) -> bool { + self.pos.is_some() && !self.press.is_held() && !self.hover_hold.released() + } + + /// The pointer moved or pressed, or a hand scrolled: hover follows the pointer through the + /// layout moving now, until it settles. + #[inline] + pub(super) fn release_hover_hold(&mut self, layout_moving: impl FnOnce() -> bool) { + let moving = !self.hover_hold.released() && layout_moving(); + self.hover_hold.release(moving); + } + + /// Removes a pruned node from hover tracking; returns true if its leave must still be queued. + pub(super) fn prune_hover(&mut self, n: &Node) -> bool { + let inside = self.hover_within.iter().position(|p| *p == n.path).map(|at| self.hover_within.remove(at)).is_some(); + let shown = self.hover_delays.forget(&n.path); + let heard = if n.handlers.hover_delay == [0.0; 2] { inside } else { shown }; + let Some(f) = n.handlers.on_hover_change.clone().filter(|_| heard) else { return false }; + self.push_hover_gone(n.path.clone(), f); + true + } +} + +impl RuntimeCore { + /// Hover under the pointer at (x, y): what's hovered and what it's inside. Returns whether + /// moving layout holds hover this pass, for the `update_interaction` that follows. + pub(in crate::runtime) fn refresh_hover(&mut self, x: f32, y: f32) -> bool { + if self.pointer.hover_hold.released() && !self.layout_moving() { self.pointer.hover_hold.settled(); } + let hovered = self.primary_target(x, y); + let within = self.within_next(); + let held = self.decide_hold(hovered, within.as_ref(), None); + self.pointer.hover_hold.set_held(held); + if let Some((inside, _)) = within { self.apply_within(inside, held); } + self.apply_hovered(hovered, held); + held + } + + /// Queue `on_hover_change` for elements the pointer entered or left. + pub(in crate::runtime) fn refresh_hover_within(&mut self) { + let Some(within) = self.within_next() else { return }; + let hovered = self.pointer.pos.filter(|_| self.pointer.hover_may_hold()).and_then(|(x, y)| self.primary_target(x, y)); + let held = self.decide_hold(hovered, Some(&within), None); + self.pointer.hover_hold.set_held(held); + self.apply_within(within.0, held); + } + + fn apply_hovered(&mut self, mut hovered: Option<usize>, held: bool) { + // What's hovered stays; one that left the tree or turned inert lets go now. + if held { hovered = self.pointer.hovered.as_deref().and_then(|p| self.hover_live(p)); } + if hovered.map(|i| self.tree.nodes[i].path.as_str()) == self.pointer.hovered.as_deref() { return; } + self.pointer.hovered = hovered.map(|i| self.tree.nodes[i].path.clone()); + if let Some(path) = &self.pointer.hovered { self.frame.queue.push(Action::Hover(path.clone())); } + // A row never takes focus from a text field (a search field above its results). + let row = hovered.and_then(|i| self.highlight_row(i)).filter(|_| self.focused_input().is_none()); + match row { + Some(i) if self.kbd.focus.path() != Some(&self.tree.nodes[i].path) || !self.kbd.focus.hovered() => + self.frame.queue.push(Action::HoverFocus(Some(self.tree.nodes[i].path.clone()))), + None if self.kbd.focus.hovered() => self.frame.queue.push(Action::HoverFocus(None)), + _ => {} + } + } + + /// None when no element tracks `on_hover_change` and none is waiting on a delay. + fn within_next(&self) -> Option<Within> { + if self.pointer.hover_within.is_empty() && self.pointer.hover_delays.is_empty() + && !self.hit.hits().iter().any(|(id, _)| self.tree.node_index.get(id).is_some_and(|&i| self.tree.nodes[i].handlers.get().is_some_and(|h| h.on_hover_change.is_some()))) + { + return None; + } + let mut inside: Vec<String> = Vec::new(); + let mut entering: Vec<usize> = Vec::new(); + if let Some((x, y)) = self.pointer.pos { + for &(id, r) in self.hit.hits() { + if let Some((i, n)) = self.tree.node_index.get(&id).map(|&i| (i, &self.tree.nodes[i])) + && n.handlers.get().is_some_and(|h| h.on_hover_change.is_some()) && self.hit_contains(id, r, x, y) && !inside.contains(&n.path) + { + if !self.pointer.hover_within.contains(&n.path) { entering.push(i); } + inside.push(n.path.clone()); + } + } + } + // A held press stays inside what holds it until it releases. + if let Some(captured) = self.pointer.press.path() { + for path in &self.pointer.hover_within { + if !inside.contains(path) && holds(path, captured) + && self.tree.nodes.iter().enumerate().any(|(i, n)| n.path == *path && self.allowed(i)) + { + inside.push(path.clone()); + } + } + } + Some((inside, entering)) + } + + fn apply_within(&mut self, mut inside: Vec<String>, held: bool) { + // Held, the pointer stays inside what it was until that leaves the tree or turns inert. + if held { inside = self.pointer.hover_within.iter().filter(|p| self.hover_live(p).is_some()).cloned().collect(); } + // An element on its way out keeps its delays: only a shown hover hears its leave. + let delayed = |this: &Self, path: &str| this.tree.nodes.iter().find(|n| n.path == path).map(|n| n.handlers.hover_delay).filter(|d| *d != [0.0; 2]); + for path in &self.pointer.hover_within { + if !inside.contains(path) && delayed(self, path).is_none() { self.frame.queue.push(Action::HoverChange(path.clone(), false)); } + } + for path in &inside { + if !self.pointer.hover_within.contains(path) && delayed(self, path).is_none() { self.frame.queue.push(Action::HoverChange(path.clone(), true)); } + } + self.pointer.hover_within = inside; + self.settle_hover_delays(); + } + + /// Whether moving layout holds hover this pass, decided once before any of its three states + /// change: the pointer may hold, and layout carries an element whose `hovered`, + /// `hover_within` or hover track would change. `flips` are the track changes when known. + fn decide_hold(&self, hovered: Option<usize>, within: Option<&Within>, flips: Option<&[Flip]>) -> bool { + if !self.pointer.hover_may_hold() { return false; } + let carried = |i: usize| self.layout_carries(i); + let was = |p: &str| self.hover_live(p).is_some_and(carried); + if hovered.map(|i| self.tree.nodes[i].path.as_str()) != self.pointer.hovered.as_deref() + && (hovered.is_some_and(carried) || self.pointer.hovered.as_deref().is_some_and(was)) + { + return true; + } + if let Some((inside, entering)) = within + && (entering.iter().any(|&i| carried(i)) || self.pointer.hover_within.iter().any(|p| !inside.contains(p) && was(p))) + { + return true; + } + let held = |f: &Flip| f.changed && !f.now && carried(f.i); + match flips { + Some(flips) => flips.iter().any(held), + None => { + let (captured, alone, shared) = (self.pointer.captured_path(), self.hovered_alone(), self.shared_hovered()); + (0..self.tree.nodes.len()).filter_map(|i| self.hover_flip(i, captured, alone, &shared)).any(|f| held(&f)) + } + } + } + + /// Node `n` leaves the tree: if it heard the pointer enter, its `on_hover_change` still + /// hears the leave, though the handler goes with the node before the action runs. A + /// delayed element heard the enter only once shown; a pending one just stops waiting. + pub(in crate::runtime) fn hover_pruned(&mut self, n: &Node) { + if !self.pointer.prune_hover(n) { return; } + let queued = self.frame.queue.len(); + self.frame.queue.push(Action::HoverChange(n.path.clone(), false)); + self.frame.queue.observe_since(queued); + } + + /// The pointer moved or pressed, or a hand scrolled: hover follows the pointer through the + /// layout moving now, until it settles. + pub(in crate::runtime) fn release_hover_hold(&mut self) { + let moving = !self.pointer.hover_hold.released() && self.layout_moving(); + self.pointer.release_hover_hold(|| moving); + } + + /// Element `i` is carried by moving layout: a frame, offset or flight spring on it or an + /// ancestor, a growth stack moving its rows, or a viewport gliding where the app sent it, + /// stepped by the app frame by frame, or letting rows down. A hand's scroll and live + /// transforms aren't layout motion. Asked only of elements whose hover would change, so a + /// frame at rest walks nothing. + fn layout_carries(&self, i: usize) -> bool { + let store = self.scene.store(); + let mut at = Some(i); + while let Some(k) = at { + let id = self.tree.nodes[k].id; + if store.is_animating(id, prop::FRAME) || store.is_animating(id, prop::OFFSET) || store.is_animating(id, prop::TRAVEL) + || self.motion.stacks.get(&id).is_some_and(|s| s.moving) || self.motion.grows.get(&id).is_some_and(|g| g.moving()) + || self.scroll.scrolls.get(&id).is_some_and(|s| scroll_carries(s, self.clock)) + { + return true; + } + at = self.tree.nodes[k].parent; + } + false + } + + /// Any layout moving at all: the running stacks, growths, glides, flights and spring + /// tracks (started this frame or before), not the tree. Asked only when a hand moves and + /// while hover follows it. + fn layout_moving(&self) -> bool { + let layout = [prop::FRAME.id, prop::OFFSET.id, prop::TRAVEL.id]; + !self.motion.flying.is_empty() + || self.motion.stacks.values().any(|s| s.moving) + || self.motion.grows.values().any(|g| g.moving()) + || self.scroll.scrolls.values().any(|s| scroll_carries(s, self.clock)) + || self.scene.store().active().any(|(_, p)| layout.contains(&p)) + } + + /// While moving layout holds hover, the hovered element, as the cursor and tooltips see + /// it: what the pointer was over, not what slid under it. + pub(crate) fn held_hover(&self) -> Option<Option<usize>> { + (self.pointer.hover_hold.held() && !self.pointer.captured()) + .then(|| self.pointer.hovered.as_deref().and_then(|p| self.hover_live(p))) + } + + /// The element at `path`, while it's in the tree, not leaving it, and not inert. + pub(crate) fn hover_live(&self, path: &str) -> Option<usize> { + (0..self.tree.nodes.len()) + .find(|&i| self.tree.nodes[i].path == path && !self.subtree_exiting(i) && !self.subtree_unmounted(i)) + .filter(|&i| self.allowed(i)) + } + + /// The innermost `hover_alone` element under the pointer: the elements around it show no + /// hover. + fn hovered_alone(&self) -> Option<usize> { + let (x, y) = self.pointer.pos?; + (0..self.tree.nodes.len()) + .filter(|&i| self.tree.nodes[i].vis.hover_alone && !self.subtree_exiting(i) && self.allowed(i) && self.node_contains(i, x, y)) + .max_by_key(|&i| self.tree.nodes[i].path.len()) + } + + /// Keyboard focus shows on node `i` or inside it (CSS `:has(:focus-visible)`): a hover group + /// lights for it as for the pointer, so the controls it reveals (a row's actions, a tab's + /// close button) show when Tab reaches them rather than taking focus unseen. + fn keyboard_within(&self, i: usize) -> bool { + self.kbd.focus.keyboard() && self.focus_within(i) + } + + /// The `hover_group_shared` keys of the elements under the pointer or holding keyboard focus. + fn shared_hovered(&self) -> Vec<Rc<str>> { + let (x, y) = self.pointer.pos.unwrap_or((f32::NAN, f32::NAN)); + (0..self.tree.nodes.len()) + .filter_map(|i| { + let key = self.tree.nodes[i].vis.hover_share.as_ref()?; + (!self.subtree_exiting(i) && self.allowed(i) && (self.node_contains(i, x, y) || self.keyboard_within(i))).then(|| key.clone()) + }) + .collect() + } + + /// Node `i`'s hover track, if it has one and isn't leaving. `alone`: the `hover_alone` + /// element under the pointer, which turns off the tracks of the elements around it. + /// `shared`: the `hover_group_shared` keys the pointer is over. + fn hover_flip(&self, i: usize, captured: Option<&str>, alone: Option<usize>, shared: &[Rc<str>]) -> Option<Flip> { + let n = &self.tree.nodes[i]; + if !(n.vis.hover().a > 0.0 || n.vis_flags.hover_group()) || self.subtree_exiting(i) { return None; } + let inside = self.pointer.pos.is_some_and(|(x, y)| self.node_contains(i, x, y)) + || n.vis.hover_share.as_ref().is_some_and(|k| shared.contains(k)) + || (n.vis_flags.hover_group() && self.keyboard_within(i)); + let capture_inside = if self.pointer.secondary_held() { inside } else { self.pointer.press_inside() }; + let held = captured == Some(n.path.as_str()) && capture_inside; + let allowed = self.allowed(i); + // A held press stays hovered while it's inside, though a press scale shrank the drawn + // rect away from the pointer. A group stays hovered while a descendant holds the press. + let shadowed = alone.is_some_and(|a| a != i && holds(&n.path, &self.tree.nodes[a].path)); + let on = allowed && (inside || held) && !shadowed && captured.is_none_or(|p| holds(&n.path, p)); + // Like a native sidebar or menu: the highlight lands with the pointer and fades + // briefly as it leaves. + let anim = match n.hover_motion() { + Some((enter, exit)) => if on { enter } else { exit }, + None if on => Anim::INSTANT, + None => rune_motion::Curve::tween(0.1, rune_motion::Easing::EASE_OUT).into(), + }; + let changed = self.scene.store().target(n.id, P_HOVER).unwrap_or(0.0) != on as u8 as f32; + Some(Flip { i, id: n.id, on, anim, changed, now: !on && !allowed }) + } + + /// Retargets the hover, press and press-scale tracks. `held` is the hold `refresh_hover` + /// just decided; without it (a commit's pass) this decides it. + pub(in crate::runtime) fn update_interaction(&mut self, held: Option<bool>) -> bool { + // Hit tests read last frame's drawn rects and clips by index. When a commit moved the + // indices (a commit's focus pass runs before the frame is built again), they belong to + // other elements until the build re-evaluates from fresh geometry. + if !self.tree.nodes.iter().map(|n| n.id).eq(self.tree.built_ids.iter().copied()) { + return false; + } + let mut changed = false; + let mut flips = std::mem::take(&mut self.pointer.hover_hold.flips); + let captured = self.pointer.captured_path(); + let alone = self.hovered_alone(); + let shared = self.shared_hovered(); + for i in 0..self.tree.nodes.len() { + let n = &self.tree.nodes[i]; + let press_scale = n.handlers.get().and_then(|h| h.press_scale); + if n.vis.hover().a <= 0.0 && !n.vis_flags.hover_group() && !n.vis.tracks_press() && press_scale.is_none() { continue; } + if self.subtree_exiting(i) { continue; } + match self.hover_flip(i, captured, alone, &shared) { + Some(f) if f.changed => flips.push(f), + // Default hover animations inherit velocity and have no completion token. + // An unchanged target preserves its trajectory in the store already; avoid + // dirtying the scene node for that no-op. Custom animations may carry an + // explicit velocity, decay or token and must still reach the store. + Some(f) if n.hover_motion().is_some() => { + if !self.scene.store().has(f.id, P_HOVER) { self.scene.set(f.id, P_HOVER, 0.0); } + self.scene.animate(f.id, P_HOVER, f.on as u8 as f32, f.anim); + } + Some(_) => {} + None => {} + } + if !n.vis.tracks_press() && press_scale.is_none() { continue; } + let capture_inside = if self.pointer.secondary_held() { + self.pointer.pos.is_some_and(|(x, y)| self.node_contains(i, x, y)) + } else { + self.pointer.press_inside() + }; + // The middle or secondary button shows pressed what it went down on while it's over + // it, as the primary does. + let tinted = self.pointer.tint_path() == Some(n.path.as_str()) && self.pointer.pos.is_some_and(|(x, y)| self.node_contains(i, x, y)); + let down = self.allowed(i) && ((captured == Some(n.path.as_str()) && capture_inside) || tinted); + let pressed = down && n.vis.tracks_press(); + let id = n.id; + changed |= self.scene.store().target(id, P_PRESS).unwrap_or(0.0) != pressed as u8 as f32; + if paint_tracks::ready_from_rest(&mut self.scene, id, P_PRESS, 0.0, pressed as u8 as f32) { + self.scene.animate(id, P_PRESS, pressed as u8 as f32, if pressed { crate::tok::motion::INSTANT } else { crate::tok::motion::SNAPPY }); + } + if let Some(k) = press_scale { + // Down follows the hand; the release springs back with a little life. + let down = down && !self.reduced_motion; + if paint_tracks::ready_from_rest(&mut self.scene, id, P_PRESS_SCALE, 1.0, if down { k } else { 1.0 }) { + self.scene.animate(id, P_PRESS_SCALE, if down { k } else { 1.0 }, if down { crate::tok::motion::INSTANT } else { crate::tok::motion::POP }); + } + } + } + let held = held.unwrap_or_else(|| { + let within = self.within_next(); + let hovered = self.pointer.pos.filter(|_| self.pointer.hover_may_hold()).and_then(|(x, y)| self.primary_target(x, y)); + self.decide_hold(hovered, within.as_ref(), Some(&flips)) + }); + // A leave from an element turned inert lands now; the rest wait while layout holds hover. + // An element that drew nothing (a held hover whose row a glide carried out of view) + // lands it rather than fading where nobody sees. + let mut unseen: Option<Vec<bool>> = None; + for f in flips.drain(..) { + if held && !f.now { continue; } + if paint_tracks::ready_from_rest(&mut self.scene, f.id, P_HOVER, 0.0, f.on as u8 as f32) { + if unseen.get_or_insert_with(|| self.drew_nothing()).get(f.i).copied().unwrap_or(false) { + self.scene.set(f.id, P_HOVER, f.on as u8 as f32); + } else { + self.scene.animate(f.id, P_HOVER, f.on as u8 as f32, f.anim); + } + } + changed = true; + } + self.pointer.hover_hold.flips = flips; + self.pointer.hover_hold.set_held(held); + changed + } +} + +#[cfg(test)] +#[path = "../hover_tests.rs"] +mod tests; diff --git a/app/vendor/rune/crates/rune/src/runtime/input/hover_delay.rs b/app/vendor/rune/crates/rune/src/runtime/input/hover_delay.rs new file mode 100644 index 0000000..d444c0b --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/input/hover_delay.rs @@ -0,0 +1,207 @@ +//! `El::hover_delays`: an `on_hover_change` element that hears the pointer enter only after it +//! rests inside for the enter delay, and leave only after it stays out for the exit delay. Each +//! such element's report is one [`Delayed`], stepped by [`step`]. +use crate::machine::Effects; + +use super::*; + +/// Where a delayed element's report stands. An element with none heard no enter and waits for +/// none. +#[derive(Clone, Copy, Debug, PartialEq)] +pub(in crate::runtime) enum Delayed { + /// The pointer is inside; the enter is reported at `due` (clock seconds). + EnterDue { due: f64 }, + /// It heard the enter. + Shown, + /// It heard the enter and the pointer left; the leave is reported at `due`. + LeaveDue { due: f64 }, +} + +#[derive(Debug, PartialEq)] +pub(in crate::runtime) enum Event { + /// Whether the pointer is inside it now; `may_enter` is false while a held press, or a + /// press or blur the pointer hasn't moved since, keeps an enter from starting its wait. + /// `delay` is its [enter, exit] delay in seconds. + Settle { inside: bool, may_enter: bool, delay: [f32; 2], now: f64 }, + /// A frame at `now`: a wait due by then reports. + Due { now: f64 }, + /// A press: a wait to report an enter stops; the pointer's next move starts it again. + Pressed, + /// It left the tree, or the window lost focus: a shown hover hears its leave now and a + /// wait stops. + Ended, +} + +#[derive(Debug, PartialEq)] +pub(in crate::runtime) enum Effect { + /// Its `on_hover_change` hears this. + Report(bool), + /// Wake at this clock time, when the wait ends. + WakeAt(f64), +} + +pub(in crate::runtime) fn step(state: &mut Option<Delayed>, event: Event) -> Effects<Effect> { + use Delayed::*; + let shown = matches!(state, Some(Shown | LeaveDue { .. })); + match event { + Event::Settle { inside, may_enter, delay, now } => { + let want = inside && (shown || may_enter); + if want == shown { + *state = shown.then_some(Shown); + return Effects::none(); + } + // Already waiting to report `want`. + if matches!(state, Some(EnterDue { .. } | LeaveDue { .. })) { return Effects::none(); } + let d = f64::from(delay[if want { 0 } else { 1 }]); + if d <= 0.0 { + *state = want.then_some(Shown); + return Effects::one(Effect::Report(want)); + } + let due = now + d; + *state = Some(if want { EnterDue { due } } else { LeaveDue { due } }); + Effects::one(Effect::WakeAt(due)) + } + Event::Due { now } => match *state { + Some(EnterDue { due }) if due <= now => { + *state = Some(Shown); + Effects::one(Effect::Report(true)) + } + Some(LeaveDue { due }) if due <= now => { + *state = None; + Effects::one(Effect::Report(false)) + } + _ => Effects::none(), + }, + Event::Pressed => { + if matches!(state, Some(EnterDue { .. })) { *state = None; } + Effects::none() + } + Event::Ended => { + *state = None; + if shown { Effects::one(Effect::Report(false)) } else { Effects::none() } + } + } +} + +/// The delayed elements' reports by path. A state entered again goes to the end, so waits that +/// come due together report in the order they started, and shown hovers in the order they +/// were shown. +#[derive(Default)] +pub(in crate::runtime) struct HoverDelays(Vec<(String, Delayed)>); + +impl HoverDelays { + pub(in crate::runtime) fn is_empty(&self) -> bool { self.0.is_empty() } + + pub(in crate::runtime) fn paths(&self) -> impl Iterator<Item = &str> { self.0.iter().map(|(p, _)| p.as_str()) } + + /// Some wait is running. + pub(in crate::runtime) fn waiting(&self) -> bool { + self.0.iter().any(|(_, d)| matches!(d, Delayed::EnterDue { .. } | Delayed::LeaveDue { .. })) + } + + pub(in crate::runtime) fn clear(&mut self) { self.0.clear(); } + + /// Drops `path`'s report unheard. Returns whether it had heard the enter. + pub(in crate::runtime) fn forget(&mut self, path: &str) -> bool { + let Some(i) = self.0.iter().position(|(p, _)| p == path) else { return false }; + matches!(self.0.remove(i).1, Delayed::Shown | Delayed::LeaveDue { .. }) + } + + /// Steps `path`'s report. + fn step(&mut self, path: &str, event: Event) -> Effects<Effect> { + let at = self.0.iter().position(|(p, _)| p == path); + let mut state = at.map(|i| self.0[i].1); + let effects = step(&mut state, event); + match (at, state) { + (Some(i), Some(s)) if self.0[i].1 == s => {} + (Some(i), s) => { + let (path, _) = self.0.remove(i); + if let Some(s) = s { self.0.push((path, s)); } + } + (None, Some(s)) => self.0.push((path.to_owned(), s)), + (None, None) => {} + } + effects + } +} + +impl capture::PointerState { + /// Steps `path`'s delayed report, pushing any hover change to `queue` and returning a wake deadline. + pub(super) fn step_hover_delay(&mut self, path: &str, event: Event, queue: &mut ActionQueue) -> Option<f64> { + let mut wake = None; + for effect in self.hover_delays.step(path, event) { + match effect { + Effect::Report(inside) => queue.push(Action::HoverChange(path.to_owned(), inside)), + Effect::WakeAt(due) => wake = Some(due), + } + } + wake + } + + /// Reports the delayed hover changes due by `now`. + pub(super) fn fire_hover_delays(&mut self, now: f64, queue: &mut ActionQueue) { + if !self.hover_delays.waiting() { return; } + let paths: Vec<String> = self.hover_delays.paths().map(str::to_owned).collect(); + for path in paths { let _ = self.step_hover_delay(&path, Event::Due { now }, queue); } + } + + /// A press stops the waits to report an enter. + #[inline] + pub(super) fn press_hover_delays(&mut self) { + self.hover_delays.0.retain_mut(|(_, d)| { + let mut state = Some(*d); + let _ = step(&mut state, Event::Pressed); + match state { + Some(next) => { *d = next; true } + None => false, + } + }); + } + + /// The window lost focus: every shown hover hears its leave, and the waits stop. + pub(super) fn end_hover_delays(&mut self, queue: &mut ActionQueue) { + let paths: Vec<String> = self.hover_delays.paths().map(str::to_owned).collect(); + for path in paths { let _ = self.step_hover_delay(&path, Event::Ended, queue); } + } +} + +impl RuntimeCore { + /// Starts or drops the waits of `hover_delays` elements whose inside changed. + pub(in crate::runtime) fn settle_hover_delays(&mut self) { + let mut paths: Vec<String> = self.pointer.hover_delays.paths().map(str::to_owned).collect(); + paths.extend(self.pointer.hover_within.iter().filter(|p| self.node(p).is_some_and(|n| n.handlers.hover_delay != [0.0; 2])).cloned()); + paths.sort(); + paths.dedup(); + let now = self.now_clock(); + // A held button, or a press or blur until the pointer next moves, never starts the + // wait to report an enter. + let may_enter = !self.pointer.press.is_held() && !self.pointer.hover_paused; + for path in paths { + // Gone or on its way out: a shown hover hears its leave now, a pending enter just + // stops waiting. + let event = match self.node(&path).map(|n| n.handlers.hover_delay) { + Some(delay) => Event::Settle { inside: self.pointer.hover_within.contains(&path), may_enter, delay, now }, + None => Event::Ended, + }; + if let Some(due) = self.pointer.step_hover_delay(&path, event, &mut self.frame.queue) { + self.schedule_wakes_from(due, [std::time::Duration::ZERO]); + } + } + } + + /// Reports the delayed hover changes due by this frame. + #[inline] + pub(in crate::runtime) fn fire_hover_delays(&mut self) { + self.pointer.fire_hover_delays(self.clock + 1e-6, &mut self.frame.queue); + } + + /// The window lost focus: every shown hover hears its leave, and the waits stop. + #[inline] + pub(in crate::runtime) fn end_hover_delays(&mut self) { + self.pointer.end_hover_delays(&mut self.frame.queue); + } +} + +#[cfg(test)] +#[path = "hover_delay_tests.rs"] +mod tests; diff --git a/app/vendor/rune/crates/rune/src/runtime/input/hover_delay_tests.rs b/app/vendor/rune/crates/rune/src/runtime/input/hover_delay_tests.rs new file mode 100644 index 0000000..062af44 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/input/hover_delay_tests.rs @@ -0,0 +1,97 @@ +use super::*; + +const DELAY: [f32; 2] = [0.5, 0.25]; + +fn settle(state: &mut Option<Delayed>, inside: bool, now: f64) -> Vec<Effect> { + step(state, Event::Settle { inside, may_enter: true, delay: DELAY, now }).into_iter().collect() +} + +fn due(state: &mut Option<Delayed>, now: f64) -> Vec<Effect> { + step(state, Event::Due { now }).into_iter().collect() +} + +#[test] +fn an_enter_waits_out_its_delay_then_reports() { + let mut s = None; + assert_eq!(settle(&mut s, true, 1.0), [Effect::WakeAt(1.5)]); + assert!(settle(&mut s, true, 1.2).is_empty(), "still inside: the wait runs on"); + assert!(due(&mut s, 1.4).is_empty()); + assert_eq!(due(&mut s, 1.5), [Effect::Report(true)]); + assert_eq!(s, Some(Delayed::Shown)); +} + +#[test] +fn leaving_before_the_enter_is_due_reports_nothing_and_its_wake_is_stale() { + let mut s = None; + settle(&mut s, true, 1.0); + assert!(settle(&mut s, false, 1.1).is_empty()); + assert_eq!(s, None); + // Back in: a new wait, and the first one's wake finds nothing due. + assert_eq!(settle(&mut s, true, 1.3), [Effect::WakeAt(1.8)]); + assert!(due(&mut s, 1.5).is_empty()); + assert_eq!(s, Some(Delayed::EnterDue { due: 1.8 })); +} + +#[test] +fn a_shown_hover_leaves_after_the_exit_delay_unless_the_pointer_comes_back() { + let mut s = Some(Delayed::Shown); + assert_eq!(settle(&mut s, false, 2.0), [Effect::WakeAt(2.25)]); + assert!(settle(&mut s, true, 2.1).is_empty(), "back inside: still shown, no report"); + assert_eq!(s, Some(Delayed::Shown)); + assert!(due(&mut s, 2.25).is_empty()); + settle(&mut s, false, 3.0); + assert_eq!(due(&mut s, 3.25), [Effect::Report(false)]); + assert_eq!(s, None); +} + +#[test] +fn zero_delays_report_at_once() { + let mut s = None; + let now = step(&mut s, Event::Settle { inside: true, may_enter: true, delay: [0.0, 0.0], now: 0.0 }); + assert_eq!(now.into_iter().collect::<Vec<_>>(), [Effect::Report(true)]); + assert_eq!(s, Some(Delayed::Shown)); +} + +#[test] +fn a_press_or_blur_keeps_an_enter_from_starting_but_not_a_shown_hover_from_staying() { + let mut s = None; + assert_eq!(step(&mut s, Event::Settle { inside: true, may_enter: false, delay: DELAY, now: 0.0 }), Effects::none()); + assert_eq!(s, None); + let mut shown = Some(Delayed::Shown); + assert_eq!(step(&mut shown, Event::Settle { inside: true, may_enter: false, delay: DELAY, now: 0.0 }), Effects::none()); + assert_eq!(shown, Some(Delayed::Shown)); +} + +#[test] +fn a_press_stops_an_enter_wait_but_not_a_leave_wait() { + let mut entering = Some(Delayed::EnterDue { due: 1.0 }); + step(&mut entering, Event::Pressed); + assert_eq!(entering, None); + let mut leaving = Some(Delayed::LeaveDue { due: 1.0 }); + step(&mut leaving, Event::Pressed); + assert_eq!(leaving, Some(Delayed::LeaveDue { due: 1.0 })); +} + +#[test] +fn ending_reports_a_leave_only_to_a_hover_that_heard_the_enter() { + for (from, heard) in [(Some(Delayed::Shown), true), (Some(Delayed::LeaveDue { due: 1.0 }), true), (Some(Delayed::EnterDue { due: 1.0 }), false), (None, false)] { + let mut s = from; + let effects: Vec<_> = step(&mut s, Event::Ended).into_iter().collect(); + assert_eq!(effects, if heard { vec![Effect::Report(false)] } else { vec![] }, "from {from:?}"); + assert_eq!(s, None); + } +} + +#[test] +fn the_list_reports_waits_in_the_order_they_started() { + let mut list = HoverDelays::default(); + list.step("a", Event::Settle { inside: true, may_enter: true, delay: [0.0, 0.0], now: 0.0 }); + list.step("b", Event::Settle { inside: true, may_enter: true, delay: DELAY, now: 0.0 }); + // `a` starts its leave after `b` started its enter. + list.step("a", Event::Settle { inside: false, may_enter: true, delay: [0.5, 0.5], now: 0.0 }); + assert_eq!(list.paths().collect::<Vec<_>>(), ["b", "a"]); + assert!(list.waiting()); + assert!(list.forget("a"), "a had heard its enter"); + assert!(!list.forget("b")); + assert!(list.is_empty() && !list.waiting()); +} diff --git a/app/vendor/rune/crates/rune/src/runtime/input/key_releases.rs b/app/vendor/rune/crates/rune/src/runtime/input/key_releases.rs new file mode 100644 index 0000000..72da87c --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/input/key_releases.rs @@ -0,0 +1,91 @@ +//! Where key releases go. Those an input method's composition took come back up unheard; the +//! rest go first to the element that had focus when their key went down, so a release after +//! focus moved still reaches it. +use std::num::NonZeroU32; + +/// Which key releases belong to an input method. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +enum Eat { + #[default] + None, + /// The release of the key that confirmed or cancelled a composition. + One, + /// This many keys went down while a composition was open: their releases are its. + Keys(NonZeroU32), +} + +/// Keys down outside a composition, and the focus where the last of them went down. +#[derive(Clone, Debug, PartialEq, Eq)] +struct Held { + keys: NonZeroU32, + focus: Option<String>, +} + +#[derive(Default)] +pub(in crate::runtime) struct KeyReleases { + eat: Eat, + held: Option<Held>, +} + +impl KeyReleases { + /// A key other than a modifier went down, while a composition is open or not; `focus` is + /// the focus it went down in. + pub(in crate::runtime) fn down(&mut self, composing: bool, repeat: bool, focus: impl FnOnce() -> Option<String>) { + if composing { + self.eat = match (self.eat, repeat) { + (Eat::Keys(n), false) => Eat::Keys(n.saturating_add(1)), + (_, false) => Eat::Keys(NonZeroU32::MIN), + (Eat::None, true) => Eat::One, + (eat, true) => eat, + }; + } else if !repeat { + self.eat = Eat::None; + let keys = self.held.as_ref().map_or(NonZeroU32::MIN, |h| h.keys.saturating_add(1)); + self.held = Some(Held { keys, focus: focus() }); + } + } + + /// The input method took a key: its release comes back up unheard. + pub(in crate::runtime) fn ime_took_key(&mut self) { + if self.eat == Eat::None { self.eat = Eat::One; } + } + + /// A key came up while a composition is open, with no release to route after it. The + /// release of the key that ends the composition is still the input method's. + pub(in crate::runtime) fn composing_release(&mut self) { + if let Eat::Keys(n) = self.eat { self.eat = NonZeroU32::new(n.get() - 1).map_or(Eat::One, Eat::Keys); } + } + + /// A key came up: whether the input method takes its release. + pub(in crate::runtime) fn eat(&mut self, composing: bool) -> bool { + if composing { + self.composing_release(); + return true; + } + match self.eat { + Eat::Keys(n) => self.eat = NonZeroU32::new(n.get() - 1).map_or(Eat::None, Eat::Keys), + Eat::One => self.eat = Eat::None, + Eat::None => return false, + } + true + } + + /// A release the input method didn't take: the focus its key went down in, if a key is + /// held. The last release ends the hold. + pub(in crate::runtime) fn route(&mut self) -> Option<String> { + let held = self.held.as_mut()?; + let focus = held.focus.clone(); + match NonZeroU32::new(held.keys.get() - 1) { + Some(keys) => held.keys = keys, + None => self.held = None, + } + focus + } + + /// The window gets no more keys: nothing is held, and the input method takes nothing. + pub(in crate::runtime) fn lost(&mut self) { *self = Self::default(); } +} + +#[cfg(test)] +#[path = "key_releases_tests.rs"] +mod tests; diff --git a/app/vendor/rune/crates/rune/src/runtime/input/key_releases_tests.rs b/app/vendor/rune/crates/rune/src/runtime/input/key_releases_tests.rs new file mode 100644 index 0000000..ed66a0a --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/input/key_releases_tests.rs @@ -0,0 +1,67 @@ +use super::*; + +fn focus(path: &str) -> impl FnOnce() -> Option<String> + '_ { move || Some(path.to_owned()) } + +#[test] +fn a_release_goes_to_where_its_key_went_down_until_the_last_key_is_up() { + let mut k = KeyReleases::default(); + k.down(false, false, focus("a")); + k.down(false, true, focus("b")); + k.down(false, false, focus("b")); + assert!(!k.eat(false)); + assert_eq!(k.route(), Some("b".into()), "the focus the last key went down in"); + assert!(!k.eat(false)); + assert_eq!(k.route(), Some("b".into())); + assert_eq!(k.route(), None, "both keys are up: nothing is held"); +} + +#[test] +fn every_release_during_a_composition_is_the_input_methods() { + let mut k = KeyReleases::default(); + k.down(true, false, focus("a")); + k.down(true, false, focus("a")); + assert!(k.eat(true) && k.eat(true)); + assert_eq!(k.route(), None, "keys down in a composition hold nothing"); +} + +#[test] +fn the_key_that_ends_a_composition_comes_back_up_unheard_once() { + let mut k = KeyReleases::default(); + // Return goes down while composing and commits it. + k.down(true, false, focus("a")); + k.ime_took_key(); + assert!(k.eat(false), "its release is the input method's"); + assert!(!k.eat(false), "the next one isn't"); + // A commit with no key counted (a click on a candidate) still takes one release. + k.ime_took_key(); + assert!(k.eat(false)); + assert!(!k.eat(false)); +} + +#[test] +fn a_key_outside_the_composition_drops_what_it_would_have_eaten() { + let mut k = KeyReleases::default(); + k.ime_took_key(); + k.down(false, false, focus("a")); + assert!(!k.eat(false)); + assert_eq!(k.route(), Some("a".into())); +} + +#[test] +fn a_physical_release_while_composing_keeps_one_for_the_key_that_ends_it() { + let mut k = KeyReleases::default(); + k.down(true, false, focus("a")); + k.composing_release(); + assert!(k.eat(false), "the last key counted is still the composition's"); + assert!(!k.eat(false)); +} + +#[test] +fn losing_the_window_forgets_everything() { + let mut k = KeyReleases::default(); + k.down(false, false, focus("a")); + k.ime_took_key(); + k.lost(); + assert!(!k.eat(false)); + assert_eq!(k.route(), None); +} diff --git a/app/vendor/rune/crates/rune/src/runtime/input/keys.rs b/app/vendor/rune/crates/rune/src/runtime/input/keys.rs new file mode 100644 index 0000000..691f29c --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/input/keys.rs @@ -0,0 +1,396 @@ +//! Keyboard, IME, focused-field editing and clipboard paste routing. +use super::*; + +impl RuntimeCore { + /// Offer a logical key that already passed `held_gate` to the app, the focused + /// input's handler, focus traversal and the focused editor, in that order. + pub(in crate::runtime) fn route_key(&mut self, app: &mut dyn AppDriver, ev: &KeyEvent, repeat: bool, one: &mut Tx) -> bool { + let physical_key = one.physical_key; + one.by_keys = true; + one.focused = self.focused_key(); + if matches!(ev.key, crate::Key::Modifier { .. }) { return !repeat && self.route_modifier(app, ev, one); } + // Any other key while Ctrl and Shift are down makes them a shortcut, not a direction. + self.kbd.disarm_direction_chord(); + one.key_repeat = repeat; + let shown = self.kbd.focus.keyboard() || self.kbd.focus.hovered(); + if focus::navigates(ev) { self.kbd.focus.step(focus_machine::FocusEvent::Navigated); } + // With no focused element, app-owned navigation (e.g. a toolbar) + // gets first refusal before Rune starts a new Tab traversal. + let app_first = self.kbd.focus.path().is_none(); + // Return and Escape that reach a field mid-composition belong to the input method: they + // confirm or cancel it, and submit, blur and press nothing. + if matches!(ev.key, crate::Key::Enter | crate::Key::Escape) && self.composing(app) { return true; } + if self.element_key(app, ev, one) { return true; } + one.physical_key = None; + if self.default_button_key(app, ev, one) { return true; } + one.physical_key = physical_key; + if self.playground_nav(app, ev, one) { return true; } + if app_first && !app.playground_typing() && app.has_on_key() && Tx::took(app.on_key(ev, one), one) { return true; } + if self.focused_input().is_some() { + self.edit.input_click.clear_last(); + } + if let Some(f) = self.focused_input().and_then(|input| input.key.clone()) + && Tx::took(f(app.states(), ev, one), one) + { + return true; + } + one.physical_key = None; + // Inside a list item or code block, Tab (and Shift+Tab in lists) edits the document by default. + if ev.key == crate::edit::Key::Tab + && !ev.mods.cmd + && !ev.mods.alt + && !ev.mods.ctrl + && self.focused_input().is_some_and(|i| { + !i.single_line + && !i.edit.is_secure() + && (i.edit.selection_in_list() || (!ev.mods.shift && i.edit.active_block() == crate::edit::Block::Code)) + }) + { + let layout = self.focused_layout(); + if self.with_focused(app, |e| e.key_in(ev, layout.as_ref().map(TextLayout::view)), one) { + return true; + } + } + if self.focus_key(app, ev, shown, one) { return true; } + let input_handles = match &ev.key { + crate::edit::Key::Function(_) | crate::edit::Key::ContextMenu | crate::edit::Key::Tab | crate::edit::Key::PageUp | crate::edit::Key::PageDown + | crate::edit::Key::Insert | crate::edit::Key::PrintScreen | crate::edit::Key::ScrollLock | crate::edit::Key::Pause => false, + crate::edit::Key::Command(_) => match ev.edit_command() { + Some('a' | 'c' | 'x' | 'z') => true, + Some('y') => !cfg!(target_os = "macos"), + Some('b' | 'i' | 'u') => self.focused_input().is_some_and(|i| i.edit.format_chord(ev).is_some()), + _ => false, + }, + // Alt+Space is the window menu's, so a field leaves it to the shell. + _ if ev.is_window_menu_chord() => false, + _ => !ev.is_command_chord() || ev.control_binding().is_some(), + }; + if input_handles { + let layout = self.focused_layout(); + // A rich field copies its selection's formatting too, read before a cut removes it. + let mut html = None; + let copies = matches!(ev.edit_command(), Some('c' | 'x')); + let handled = self.with_focused(app, |e| { + if copies && e.is_rich() && !e.is_secure() { + html = Some(e.selected_html()).filter(|h| !h.is_empty()); + } + e.key_in(ev, layout.as_ref().map(TextLayout::view)) + }, one); + if let Some(html) = html + && let Some(text) = one.copy.as_ref().filter(|w| !w.is_secret()).map(|w| w.content().text().to_owned()) + { + one.copy_rich(crate::ClipboardContent::new(text).with_html(html)); + } + if handled { return true; } + } + one.physical_key = physical_key; + if !app_first && !app.playground_typing() && app.has_on_key() && Tx::took(app.on_key(ev, one), one) { + log_event!(self, "key {:?}", ev.key); + return true; + } + one.physical_key = None; + // Selected text takes the Cmd+A and Cmd+C nothing else took, as AppKit's responder chain + // gives a key equivalent to the menu bar before the text view: an app's shortcut wins. + if !repeat && self.selection_key(app, ev, one) { return true; } + if !repeat && self.context_menu_key(app, ev, one) { return true; } + self.page_scroll(app, ev) || self.playground_key(app, ev, one) + } + + /// Page Up and Page Down scroll by most of a viewport, and Home and End to the top and + /// bottom, as an NSScrollView does, when nothing else took the key. The scroll view is the + /// nearest one around the focused element, else around the pointer, else the first in the + /// tree, skipping any whose content fits (nothing to scroll): a chat's short composer passes + /// the keys to the message list beside it. A view that overflows keeps them even at the edge + /// a key moves toward, where it does nothing, as an NSTextView does; an app that wants + /// another view paged there routes the key itself with `Tx::scroll_page`. + pub(in crate::runtime) fn page_scroll(&mut self, app: &dyn AppDriver, ev: &KeyEvent) -> bool { + use crate::Key::*; + if ev.mods.cmd || ev.mods.alt || ev.mods.ctrl { return false; } + // A focused field in a virtual row that scrolled out has no node: page its list. + let focused = self.kbd.focus.path().and_then(|path| { + std::iter::successors(Some(path), |p| p.rsplit_once('/').map(|(head, _)| head)) + .find_map(|p| self.tree.nodes.iter().position(|n| n.path == p)) + }); + if let Some(f) = focused && self.kbd.focus.is(&self.tree.nodes[f].path) && self.pageable(f) && self.scroller_key(f, ev) { return true; } + if !matches!(ev.key, PageUp | PageDown | Home | End) { return false; } + // A step's key (`Play::press`) pages only the stage, never the playground around it. + let staged = app.playground().is_some_and(|p| p.pressing()); + let pageable = |i: usize| self.pageable(i) && (!staged || self.under(i, crate::playground::is_stage)); + let around = |from: usize| std::iter::successors(Some(from), |&i| self.tree.nodes[i].parent).find(|&i| pageable(i)); + let i = focused.and_then(around) + .or_else(|| self.pointer.pos.and_then(|(x, y)| self.scroll_at(x, y)).and_then(|id| self.tree.node_index.get(&id).copied()).and_then(around)) + .or_else(|| (0..self.tree.nodes.len()).find(|&i| pageable(i))); + let Some(i) = i else { return false }; + if !self.page_to(i, |offset, max, page| match ev.key { PageUp => offset - page, PageDown => offset + page, Home => 0.0, _ => max }) { return false; } + log_event!(self, "page {:?}", ev.key); + true + } + + /// Up and Down by a line of 40 points, and Space (Shift+Space back) by a page, on a scroll + /// view that has focus itself, as a browser scrolls a focused scroller (`tabindex` on an + /// `overflow: auto` region) when nothing in it took the key. + fn scroller_key(&mut self, i: usize, ev: &KeyEvent) -> bool { + use crate::Key::*; + const LINE: f64 = 40.0; + let space = ev.key == Text(" ".into()); + if ev.mods.shift && !space { return false; } + let moved = match ev.key { + Up => self.page_to(i, |offset, _, _| offset - LINE), + Down => self.page_to(i, |offset, _, _| offset + LINE), + _ if space && ev.mods.shift => self.page_to(i, |offset, _, page| offset - page), + _ if space => self.page_to(i, |offset, _, page| offset + page), + _ => return false, + }; + if moved { log_event!(self, "scroll {:?}", ev.key); } + moved + } + + /// A focused scroll view that presses nothing passes Space on to scroll itself. + pub(in crate::runtime) fn scrolls_on_space(&self, i: usize) -> bool { + self.tree.nodes[i].handlers.on_press.is_none() && self.pageable(i) + } + + /// Whether node `i` is a live scroll view whose content overflows it. + pub(in crate::runtime) fn pageable(&self, i: usize) -> bool { + self.tree.nodes[i].scroll.is_some() && !self.subtree_exiting(i) && self.allowed(i) + && self.scroll.scrolls.get(&self.tree.nodes[i].id).is_some_and(|st| st.max > 0.5) + } + + /// Moves scroll view `i` to `to(offset, max, page)`, clamped, a page being 90% of its + /// height. The hand moved it: any fling or glide stops, and a `stick_bottom` view that + /// lands on its end follows it again. + #[inline] + pub(in crate::runtime) fn page_to(&mut self, i: usize, to: impl FnOnce(f64, f64, f64) -> f64) -> bool { + let mut to = Some(to); + self.page_to_dyn(i, &mut |offset, max, page| to.take().expect("page_to runs once")(offset, max, page)) + } + + fn page_to_dyn(&mut self, i: usize, to: &mut dyn FnMut(f64, f64, f64) -> f64) -> bool { + self.release_hover_hold(); + self.drop_scroll_holds(); + let (id, page, stick) = (self.tree.nodes[i].id, f64::from(self.tree.nodes[i].local.h * 0.9), self.tree.nodes[i].scroll.is_some_and(|s| s.stick_bottom)); + let Some(st) = self.scroll.scrolls.get_mut(&id) else { return false }; + st.offset = to(st.offset, st.max, page).clamp(0.0, st.max); + st.moved(); + st.land(stick); + true + } + + pub(in crate::runtime) fn focused_layout(&mut self) -> Option<TextLayout> { + let path = self.kbd.focus.owned()?; + let s = self.env.scale; + let n = self.node(&path)?; + // The field shows its edit's display text: the layout it drew is that text's. A secret + // draws its mask, so the keys move through a layout of what it holds. + if let Some(l) = n.text_layout.clone().filter(|_| n.text.as_ref().is_some_and(|t| !t.redacted)) { + return Some(l); + } + let (mut spec, w) = (n.text.clone()?, n.target[2] - n.target[0] - n.inset[0] - n.inset[2]); + spec.replace_content(n.input.as_ref()?.edit.display().0); + Some(TextLayout::Single(self.text.layout_for_spec(&spec.as_text_input(s, false), s, spec.wrap.then_some(w * s), line_alignment(&spec)))) + } + + #[inline] + pub(crate) fn with_focused(&mut self, app: &mut dyn AppDriver, f: impl FnOnce(&mut crate::edit::TextEdit) -> EditOutcome, tx: &mut Tx) -> bool { + let mut f = Some(f); + self.with_focused_state_dyn(app, &mut |state, access, _| f.take().expect("focused edit runs once")(access(state)), tx) + } + + /// [`Self::with_focused`] for an edit that needs the app state (an app's paste hook). + #[inline] + pub(in crate::runtime) fn with_focused_state(&mut self, app: &mut dyn AppDriver, f: impl FnOnce(crate::states::States<'_>, &crate::el::EditFn, &mut Tx) -> EditOutcome, tx: &mut Tx) -> bool { + let mut f = Some(f); + self.with_focused_state_dyn(app, &mut |state, access, tx| f.take().expect("focused edit runs once")(state, access, tx), tx) + } + + fn with_focused_state_dyn( + &mut self, + app: &mut dyn AppDriver, + f: &mut dyn FnMut(crate::states::States<'_>, &crate::el::EditFn, &mut Tx) -> EditOutcome, + tx: &mut Tx, + ) -> bool { + let Some(path) = self.kbd.focus.owned() else { return false }; + let Some((access, submit, change, animate_layout, single_line, secure, revealed_override)) = + self.focused_input().map(|i| (i.access.clone(), i.submit.clone(), i.change.clone(), i.animate_layout, i.single_line, i.edit.is_secure(), i.revealed_override)) + else { + return false; + }; + let Some(access) = access else { return false }; + self.edit.input_click.clear_last(); + { + let edit = access(app.states()); + edit.set_single_line(single_line); + if secure && !edit.is_secure() { edit.set_secure(true); } + if let Some(rev) = revealed_override { edit.set_revealed(rev); } + } + let before = change.as_ref().map(|_| zeroize::Zeroizing::new(access(app.states()).text.clone())); + let mut out = f(app.states(), &access, tx); + // Submit and Escape's blur act once per press; held keys still type, move and delete. + if tx.key_repeat { out.submit = false; out.blur = false; } + // Typing is the user's own hand: no animation. + tx.commit = tx.commit.snap(!animate_layout); + self.edit.caret_follow = true; + if let Some(change) = change + && before.as_ref().map(|s| s.as_str()) != Some(access(app.states()).text.as_str()) + { + change(app.states(), tx); + access(app.states()).mark_edited(); + } + if let Some(c) = out.copy { + tx.copy(c); + } + if out.blur { + self.set_focus(app, None, self.kbd.focus.keyboard()); + } + if out.submit + && let Some(sub) = submit + { + log_event!(self, "submit {path}"); + tx.commit = tx.commit.animated(); + sub(app.states(), tx); + } else if out.submit { + // A field with nothing to submit passes Return to the default button, as in a sheet. + self.press_default_button(app, tx); + } + true + } + + /// Whether the focused field has an input method composition (preedit) open. + pub(in crate::runtime) fn composing(&mut self, app: &mut dyn AppDriver) -> bool { + let Some(access) = self.focused_input().map(|i| i.access.clone()) else { return self.app_ime_composing(app) }; + match access { + Some(access) => access(app.states()).preedit().is_some(), + None => self.focused_input().is_some_and(|i| i.edit.preedit().is_some()), + } + } + + pub(crate) fn node(&self, path: &str) -> Option<&Node> { + self.tree.nodes.iter().enumerate().find(|(i, n)| n.path == path && !self.subtree_exiting(*i) && !self.subtree_unmounted(*i)).map(|(_, n)| n) + } + + /// `El::on_key` handlers on the focused element and its ancestors, innermost first. A + /// focused text field's keys stay its own. + pub(in crate::runtime) fn element_key(&mut self, app: &mut dyn AppDriver, ev: &KeyEvent, tx: &mut Tx) -> bool { + let Some(i) = self.focused_index() else { return false }; + if !self.can_focus(i) || self.focused_input().is_some() { return false; } + let handlers: Vec<_> = std::iter::successors(Some(i), |&j| self.tree.nodes[j].parent) + .take_while(|&j| self.allowed(j) && !self.subtree_exiting(j)) + .filter_map(|j| self.tree.nodes[j].focus.key.clone()) + .collect(); + handlers.into_iter().any(|f| Tx::took(f(app.states(), ev, tx), tx)) + } + + pub(in crate::runtime) fn focused_input(&self) -> Option<&InputSpec> { + let path = self.kbd.focus.path()?; + self.node(path).and_then(|n| n.input.as_deref()).or_else(|| self.commit.virtual_inputs.get(path).map(Box::as_ref)) + } + + /// What [`Tx::focused`] reports: the focused link's id, else the focused element's key, + /// else its path's last segment (a field in a virtual row that scrolled out has no node). + pub(in crate::runtime) fn focused_key(&self) -> Option<String> { + let path = self.kbd.focus.path()?; + if let Some(id) = self.focused_index().and_then(|i| self.edit.focused_link_id(&self.tree.nodes[i])) { return Some(id); } + Some(self.focused_index().and_then(|i| self.tree.nodes[i].key.clone()) + .unwrap_or_else(|| path.rsplit('/').next().unwrap_or(path).to_owned())) + } + + /// The focused element's index. Unlike [`Runtime::node`], this finds it while it exits. + #[inline] + pub(crate) fn focused_index(&self) -> Option<usize> { + self.kbd.focused_index(&self.tree.nodes) + } + + pub fn key(&mut self, ev: KeyEvent) { + self.queue_key(ev, false); + } + + /// [`Runtime::key`]; `stage` routes it to the open playground's stage, for `Play::press`. + pub(in crate::runtime) fn queue_key(&mut self, ev: KeyEvent, stage: bool) { + self.dismiss_help(); + // A key ends a middle-click autoscroll, and does nothing else. + if self.pointer.autoscroll_key() { return; } + // Escape during a drag cancels it and goes no further. + if ev.key == crate::Key::Escape && self.cancel_drag() { return; } + self.frame.queue.push(Action::Key { ev, repeat: false, stage }); + } + + /// Queue an auto-repeat of a held key, as the OS sends after the first press. Handlers see + /// `Tx::key_repeat` true for it. + pub fn repeat_key(&mut self, ev: KeyEvent) { + self.frame.queue.push(Action::Key { ev, repeat: true, stage: false }); + } + + pub fn ime(&mut self, ev: Ime) { + self.frame.queue.push(Action::Ime(ev)); + } + + /// The window went inactive mid-composition: what the composition shows becomes text, in + /// event order, as a browser keeps it, and the field keeps focus. The platform's input + /// method is told to drop its own copy (`ime_reset`), so it doesn't come back in the next + /// field. + pub fn finish_composition(&mut self) { + self.frame.queue.push(Action::FinishIme); + self.edit.ime_reset = true; + } + + pub fn paste(&mut self, text: String) { + self.frame.queue.push(Action::Paste(crate::ClipboardContent::new(text), None)); + } + /// [`Runtime::paste`] with several forms, as from another app's clipboard: its HTML is + /// sanitised as a real paste's is. For tests and scripts. + pub fn paste_content(&mut self, content: crate::ClipboardContent) { + self.frame.queue.push(Action::Paste(content.untrusted(), None)); + } + + pub(in crate::runtime) fn app_paste_handler(&self) -> Option<crate::el::PasteFn> { + self.tree.nodes.get(self.active_modal().unwrap_or_else(|| self.app_root()))?.handlers.on_paste.clone() + } + pub(crate) fn accepts_paste(&self) -> bool { + self.paste_target().is_some() || self.app_paste_handler().is_some() + } + pub(crate) fn paste_target(&self) -> Option<String> { + self.focused_input().filter(|i| i.access.is_some()).and(self.kbd.focus.owned()) + } + /// What the paste target hears: every form, images too, for a field with + /// `on_input_paste` or a root `on_paste_content` handler; text, HTML and RTF for a rich + /// [`TextEdit`](crate::TextEdit); only the clipboard's text for anything else (including a + /// plain field or a plain `on_paste`). + pub(crate) fn paste_forms(&self, target: Option<&str>) -> crate::clipboard::Forms { + use crate::clipboard::Forms; + match target { + Some(path) => match self.node(path).and_then(|n| n.input.as_deref()).or_else(|| self.commit.virtual_inputs.get(path).map(Box::as_ref)) { + Some(input) if input.paste.is_some() => Forms::All, + Some(input) if input.edit.is_rich() && !input.edit.is_secure() => Forms::Rich, + _ => Forms::Text, + }, + None if self.app_paste_handler().is_some_and(|p| p.rich) => Forms::All, + None => Forms::Text, + } + } + pub(crate) fn paste_result(&mut self, target: Option<String>, content: crate::ClipboardContent) { + self.frame.queue.push(Action::Paste(content, Some(target))); + } + pub(crate) fn read_result(&mut self, id: u64, content: crate::ClipboardContent) { + self.frame.queue.push(Action::ClipboardRead(id, content)); + } + + /// The focused field's text around its selection, for the platform's input method. + pub(crate) fn ime_text(&self) -> Option<crate::edit::ImeText> { + self.focused_input().and_then(|i| i.edit.ime_text()) + } + + /// The focused field's open composition and its cursor range, for a script's tree. + pub(crate) fn focused_preedit(&self) -> Option<(&str, Option<(usize, usize)>)> { + self.focused_input().filter(|i| !i.edit.is_secure()).and_then(|i| i.edit.preedit()) + } + + /// Whether the focused editor requires secure native keyboard input. + pub fn has_secure_focus(&self) -> bool { + self.focused_input().is_some_and(|i| i.edit.is_secure()) + } + + #[inline] + pub fn has_focus(&self) -> bool { + self.kbd.has_focus() + } +} diff --git a/app/vendor/rune/crates/rune/src/runtime/input/modal_focus.rs b/app/vendor/rune/crates/rune/src/runtime/input/modal_focus.rs new file mode 100644 index 0000000..d7ade1a --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/input/modal_focus.rs @@ -0,0 +1,174 @@ +//! The modal focus machine: the open modals, innermost last, each holding where focus returns +//! when it closes, as a web dialog stack does (`dialog-machine.ts` in OpenCode's UI: an open +//! entry's `focus` is where focus was before it opened, and only the top layer traps focus and +//! hands it back). `step` decides; `Runtime::sync_modals` feeds it what the commit shows and +//! carries out its effects. A menu or a select's listbox the pointer opened hands focus back +//! without a ring, as Desktop's menu machine does (`ui/src/navigation/menu/machine.ts`, +//! `selectMenuRestoreTriggerWithoutRing`): keys used inside it don't make its trigger ring. +use super::*; + +/// Modal roles that close as Desktop's menus do: a menu, and a select's listbox. +const MENU_ROLES: [&str; 2] = ["menu", "listbox"]; + +/// One open modal: its element, where focus was before it opened, and how it opened. +#[derive(Clone, Debug, PartialEq)] +pub(crate) struct ModalLayer { + path: String, + restore: Option<String>, + opened: Opened, +} + +/// What opened a modal, for how focus shows as it hands focus back. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum Opened { + /// A dialog, or a menu the keyboard opened: focus returns showing as the keys left it. + Dialog, + /// A menu or listbox the pointer opened: focus returns without a ring. + PointerMenu, +} + +#[derive(Clone, Debug, Default, PartialEq)] +pub(crate) enum ModalFocus { + #[default] + Closed, + /// Never empty: the last layer is the top one, which holds the trap. + Open(Vec<ModalLayer>), +} + +pub(crate) enum ModalEvent { + /// A modal mounted; `restore` is the focus it hands back on closing. + Opened { path: String, restore: Option<String>, opened: Opened }, + /// The top modal's element is gone. `kept` is focus the closing change already put outside + /// it (a field the handler focused), which stays. + TopRemoved { kept: bool }, + /// Focus is outside the top modal (nothing focused, or behind it). + FocusOutside, +} + +#[derive(Debug, PartialEq)] +pub(crate) enum ModalEffect { + /// Drop gestures captured before the modal opened. + CancelGestures, + /// Focus what the top modal opens on (`FocusOutside`, which a new modal is in until a field + /// inside it asks for focus): its `autofocus` control, else its field, else itself. + FocusInitial, + /// Focus returns where it was before the closed modal opened; `ring` false keeps it from + /// showing whatever the keys did. + Return { restore: Option<String>, ring: bool }, +} + +impl ModalFocus { + pub(crate) fn top(&self) -> Option<&str> { + match self { + Self::Closed => None, + Self::Open(layers) => layers.last().map(|l| l.path.as_str()), + } + } + + fn holds(&self, path: &str) -> bool { + matches!(self, Self::Open(layers) if layers.iter().any(|l| l.path == path)) + } + + pub(crate) fn step(self, event: ModalEvent) -> (Self, Vec<ModalEffect>) { + match (self, event) { + (state, ModalEvent::Opened { path, .. }) if state.holds(&path) => (state, vec![]), + (Self::Closed, ModalEvent::Opened { path, restore, opened }) => { + (Self::Open(vec![ModalLayer { path, restore, opened }]), vec![ModalEffect::CancelGestures]) + } + (Self::Open(mut layers), ModalEvent::Opened { path, restore, opened }) => { + layers.push(ModalLayer { path, restore, opened }); + (Self::Open(layers), vec![ModalEffect::CancelGestures]) + } + (Self::Open(mut layers), ModalEvent::TopRemoved { kept }) => { + let closed = layers.pop(); + let state = if layers.is_empty() { Self::Closed } else { Self::Open(layers) }; + let effects = closed.filter(|_| !kept) + .map(|l| ModalEffect::Return { restore: l.restore, ring: l.opened == Opened::Dialog }) + .into_iter().collect(); + (state, effects) + } + (state @ Self::Open(_), ModalEvent::FocusOutside) => (state, vec![ModalEffect::FocusInitial]), + (state, _) => (state, vec![]), + } + } +} + +impl focus_machine::KeyboardState { + #[inline] + pub(super) fn modal_top(&self) -> Option<&str> { + self.modal_focus.top() + } + + #[inline] + pub(super) fn step_modal(&mut self, event: ModalEvent) -> Vec<ModalEffect> { + let (state, effects) = std::mem::take(&mut self.modal_focus).step(event); + self.modal_focus = state; + effects + } +} + +impl RuntimeCore { + /// Feeds the modal focus machine what this commit shows: modals that went (innermost first), + /// a modal that opened, and focus that left the top modal. + pub(in crate::runtime) fn sync_modals(&mut self, app: &mut dyn AppDriver) { + let returned = self.kbd.take_focus_returned(); + // Exiting visuals are already inert, so a closing modal counts as gone. + while let Some(top) = self.kbd.modal_top().map(str::to_owned).filter(|p| self.node(p).is_none()) { + let inside = |f: &str| f.strip_prefix(top.as_str()).is_some_and(|rest| rest.is_empty() || rest.starts_with('/')); + let kept = self.kbd.focus.path().is_some_and(|f| !inside(f) && self.node(f).is_some()); + self.modal_step(app, ModalEvent::TopRemoved { kept }); + } + let Some(i) = self.active_modal() else { return }; + let path = self.tree.nodes[i].path.clone(); + // A field in the modal that asked for focus took it earlier in this commit, or a closing + // menu handed focus back to its trigger as its pick opened this modal (`Tx::return_focus`, + // which a web menu does only after the dialog has noted the item): closing returns to + // what had focus before. + let inside = self.focused_index().is_some_and(|j| self.allowed(j)); + let restore = if inside || returned { self.kbd.focus_before_commit.clone() } else { self.kbd.focus.owned() }; + let menu = |j: usize| MENU_ROLES.contains(&self.tree.nodes[j].role); + let is_menu = menu(i) || (i + 1..self.tree.nodes.len()).take_while(|&j| self.tree.nodes[j].parent.is_some_and(|p| p >= i)).any(|j| self.tree.nodes[j].parent == Some(i) && menu(j)); + let opened = if is_menu && !self.kbd.focus.keyboard() { Opened::PointerMenu } else { Opened::Dialog }; + self.modal_step(app, ModalEvent::Opened { path, restore, opened }); + if !self.focused_index().is_some_and(|j| self.allowed(j)) { + self.modal_step(app, ModalEvent::FocusOutside); + } + } + + fn modal_step(&mut self, app: &mut dyn AppDriver, event: ModalEvent) { + let effects = self.kbd.step_modal(event); + for effect in effects { + match effect { + ModalEffect::CancelGestures => { + self.drop_press(); + self.pointer.clear_secondary(); + self.pointer.hovered = None; + } + ModalEffect::FocusInitial => { + if let Some(target) = self.modal_initial_focus() { + self.set_focus(app, Some(target), self.kbd.focus.keyboard()); + } + } + ModalEffect::Return { restore, ring } => { + let restore = restore.filter(|p| self.node(p).is_some()); + self.set_focus(app, restore, ring && self.kbd.focus.keyboard()); + } + } + } + } + + /// What the top modal focuses: its `El::autofocus` control, else under `Cx::web_focus` its + /// first text field and otherwise its first Tab stop, else the modal itself, as a web dialog + /// focuses its content (Kobalte's `onOpenAutoFocus` in OpenCode's `Dialog`). + fn modal_initial_focus(&self) -> Option<String> { + let i = self.active_modal()?; + let inside = |j: usize| self.modal_member(j) && j > i; + let autofocus = (i..self.tree.nodes.len()).find(|&j| inside(j) && self.tree.nodes[j].focus.autofocus && self.can_focus(j)); + let first = if self.commit.defaults.web_focus { + (i..self.tree.nodes.len()).find(|&j| inside(j) && self.tree.nodes[j].input.is_some() && self.can_focus(j)) + } else { + self.tab_order().first().copied() + }; + Some(autofocus.or(first).map_or_else(|| self.tree.nodes[i].path.clone(), |j| self.tree.nodes[j].path.clone())) + } +} diff --git a/app/vendor/rune/crates/rune/src/runtime/input/modifier_keys.rs b/app/vendor/rune/crates/rune/src/runtime/input/modifier_keys.rs new file mode 100644 index 0000000..4be4327 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/input/modifier_keys.rs @@ -0,0 +1,243 @@ +//! Modifier keys pressed and released on their own (`Key::Modifier`), for runtimes that opt in. +//! +//! Hosts already pass every physical key, modifiers included, to `physical_with_fallback`, so +//! the logical event is made here once for windows, overlays, layer surfaces and headless runs. +//! It is made in queue order, once the focused `on_physical_input` handler has declined the +//! physical event, so a shortcut recorder sees modifiers first, as it sees every key. +//! Presses come only from physical keys. A release also comes from a modifier that a +//! `PhysicalInput::Modifiers` turns off while its key is down (a key-up the platform never +//! sent), and every held key is released on `FocusLost`. + +use super::*; +use crate::{Key, Modifier, Mods, PhysicalInput, PhysicalKeyCode as Code}; + +const ALL: [Modifier; 9] = [Modifier::ShiftLeft, Modifier::ShiftRight, Modifier::ControlLeft, Modifier::ControlRight, + Modifier::AltLeft, Modifier::AltRight, Modifier::SuperLeft, Modifier::SuperRight, Modifier::Fn]; + +#[derive(Default)] +pub(in crate::runtime) struct ModifierKeys { + pub(in crate::runtime) enabled: bool, + /// How far Ctrl+Shift's direction chord has gone (`edit::direction_keys`), whatever the + /// app asked for and whoever took the keys. + chord: crate::edit::DirChord, + /// Bit `i` set while `ALL[i]` is down. + held: u16, + /// The last `PhysicalInput::Modifiers`, to see a flag turn off. A flag that was never on + /// says nothing: AltGr (Right Alt on many layouts) is down without `alt` on X11 and Wayland. + last: Mods, +} + +fn modifier(code: Code) -> Option<Modifier> { + Some(match code { + Code::ShiftLeft => Modifier::ShiftLeft, + Code::ShiftRight => Modifier::ShiftRight, + Code::ControlLeft => Modifier::ControlLeft, + Code::ControlRight => Modifier::ControlRight, + Code::AltLeft => Modifier::AltLeft, + Code::AltRight => Modifier::AltRight, + Code::SuperLeft => Modifier::SuperLeft, + Code::SuperRight => Modifier::SuperRight, + Code::Fn => Modifier::Fn, + _ => return None, + }) +} + +fn bit(m: Modifier) -> u16 { 1 << ALL.iter().position(|&a| a == m).unwrap_or(0) } + +/// Both sides of `m`'s modifier. +fn pair(m: Modifier) -> u16 { + use Modifier::*; + match m { + ShiftLeft | ShiftRight => bit(ShiftLeft) | bit(ShiftRight), + ControlLeft | ControlRight => bit(ControlLeft) | bit(ControlRight), + AltLeft | AltRight => bit(AltLeft) | bit(AltRight), + SuperLeft | SuperRight => bit(SuperLeft) | bit(SuperRight), + _ => bit(m), + } +} + +/// Whether `mods` has `m`'s modifier on. Fn has no flag. +fn active(mods: Mods, m: Modifier) -> bool { + use Modifier::*; + match m { + ShiftLeft | ShiftRight => mods.shift, + ControlLeft | ControlRight => mods.ctrl, + AltLeft | AltRight => mods.alt, + SuperLeft | SuperRight => mods.logo, + _ => false, + } +} + +/// `mods` with `m`'s modifier set to `on`, including `cmd` (Command on macOS, Ctrl elsewhere). +fn with(mut mods: Mods, m: Modifier, on: bool) -> Mods { + use Modifier::*; + let mac = cfg!(target_os = "macos"); + match m { + ShiftLeft | ShiftRight => mods.shift = on, + ControlLeft | ControlRight => { mods.ctrl = on; if !mac { mods.cmd = on; } } + AltLeft | AltRight => mods.alt = on, + SuperLeft | SuperRight => { mods.logo = on; if mac { mods.cmd = on; } } + _ => {} + } + mods +} + +/// Windows clears Control and Alt in the flags while AltGr (Right Alt) is down, even with +/// Left Control or Left Alt held. +const ALTGR_CLEARS_FLAGS: bool = cfg!(target_os = "windows"); + +impl ModifierKeys { + fn event(&self, m: Modifier, pressed: bool, mods: Mods) -> KeyEvent { + // Platforms differ on whether a modifier's own key event carries the flags from + // before or after it; report them after, from the keys held. + KeyEvent { key: Key::Modifier { modifier: m, pressed }, mods: with(mods, m, self.held & pair(m) != 0) } + } + + /// The keys `event` presses and releases, without changing anything. A press while held, + /// a release not held and a repeat change nothing. `Modifiers` releases held keys whose + /// flag turns off (Fn has none, so only its key-up or focus loss ends it); `FocusLost` + /// releases them all. + fn changes(&self, event: &PhysicalInput, altgr_clears: bool) -> (u16, u16) { + if !self.enabled { return (0, 0); } + match *event { + PhysicalInput::Key { key, pressed, repeat, .. } => match modifier(key) { + Some(m) if !repeat && (self.held & bit(m) != 0) != pressed => if pressed { (bit(m), 0) } else { (0, bit(m)) }, + _ => (0, 0), + }, + PhysicalInput::Modifiers(now) => { + let altgr = altgr_clears && self.held & bit(Modifier::AltRight) != 0; + let lifted = ALL.into_iter().filter(|&m| { + use Modifier::*; + let cleared = altgr && matches!(m, ControlLeft | ControlRight | AltLeft | AltRight); + self.held & bit(m) != 0 && active(self.last, m) && !active(now, m) && !cleared + }); + (0, lifted.fold(0, |all, m| all | bit(m))) + } + PhysicalInput::FocusLost => (0, self.held), + } + } + + /// Whether `event` presses or releases a modifier key. + fn pending(&self, event: &PhysicalInput) -> bool { self.changes(event, ALTGR_CLEARS_FLAGS) != (0, 0) } + + /// Takes `event` in, with the `Key::Modifier` events it makes. None when a physical handler + /// `consumed` it: a press it took is never held, so its release is never sent either, and a + /// release or focus loss it took ends held keys silently. That is the one way `on_key` sees + /// a press without its release: a handler, such as a shortcut recorder that starts while a + /// modifier is down, takes the key-up. + fn apply(&mut self, event: &PhysicalInput, consumed: bool, altgr_clears: bool) -> Vec<KeyEvent> { + let (pressed, released) = self.changes(event, altgr_clears); + let mods = match *event { + PhysicalInput::Key { mods, .. } => mods, + PhysicalInput::Modifiers(now) => { self.last = now; now } + PhysicalInput::FocusLost => { self.last = Mods::default(); Mods::default() } + }; + let mut out = Vec::new(); + for m in ALL { + if pressed & bit(m) != 0 && !consumed { + self.held |= bit(m); + out.push(self.event(m, true, mods)); + } else if released & bit(m) != 0 { + self.held &= !bit(m); + if !consumed { out.push(self.event(m, false, mods)); } + } + } + out + } +} + +impl focus_machine::KeyboardState { + /// Send `Key::Modifier` presses and releases to `on_key` and the focused input's key + /// handler. Off by default: handlers written before it may act on any key. + #[inline] + pub(in crate::runtime) fn set_modifier_keys(&mut self, enabled: bool) { + if self.modifier_keys.enabled != enabled { self.modifier_keys.held = 0; } + self.modifier_keys.enabled = enabled; + } + + #[inline] + pub(in crate::runtime) fn modifier_keys(&self) -> bool { self.modifier_keys.enabled } + + /// Whether `event` presses or releases a modifier key, which needs a frame to deliver. + #[inline] + pub(super) fn modifier_pending(&self, event: &PhysicalInput) -> bool { self.modifier_keys.pending(event) } + + #[inline] + pub(super) fn disarm_direction_chord(&mut self) { + self.modifier_keys.chord = crate::edit::DirChord::Idle; + } + + /// Steps Ctrl+Shift's direction chord; returns the flow direction when the release completes it. + pub(super) fn step_direction_chord(&mut self, event: &PhysicalInput) -> Option<crate::el::Flow> { + let PhysicalInput::Key { key, mods, pressed, repeat: false } = *event else { return None }; + let Some(m) = modifier(key) else { + if pressed { self.modifier_keys.chord = crate::edit::DirChord::Idle; } + return None; + }; + let after = with(mods, m, pressed); + let (next, set) = crate::edit::step_dir_chord(self.modifier_keys.chord, m, pressed, after.ctrl, after.shift); + self.modifier_keys.chord = next; + set + } + + #[inline] + pub(super) fn apply_modifier_keys(&mut self, event: &PhysicalInput, consumed: bool) -> Vec<KeyEvent> { + self.modifier_keys.apply(event, consumed, ALTGR_CLEARS_FLAGS) + } +} + +impl RuntimeCore { + /// Send `Key::Modifier` presses and releases to `on_key` and the focused input's key + /// handler. Off by default: handlers written before it may act on any key. + #[inline] + pub(crate) fn set_modifier_keys(&mut self, enabled: bool) { self.kbd.set_modifier_keys(enabled); } + + #[inline] + pub(crate) fn modifier_keys(&self) -> bool { self.kbd.modifier_keys() } + + /// Ctrl+Left Shift and Ctrl+Right Shift: every physical key steps the chord (`edit::direction_keys`), + /// and its release sets the focused field's direction. Any other key disarms it. True if it set one. + pub(in crate::runtime) fn direction_chord(&mut self, app: &mut dyn AppDriver, event: &PhysicalInput, tx: &mut Tx) -> bool { + let Some(flow) = self.kbd.step_direction_chord(event).filter(|_| self.focused_input().is_some()) else { return false }; + self.with_focused(app, |e| { e.force_dir(flow); crate::edit::EditOutcome::default() }, tx) + } + + /// After the focused physical handler saw `event` (and `consumed` it or not): route the + /// modifier keys it presses and releases. True if a handler took one. + pub(in crate::runtime) fn modifier_dispatch(&mut self, app: &mut dyn AppDriver, event: &PhysicalInput, consumed: bool, tx: &mut Tx, live: &mut Option<bool>) -> bool { + let mut ran = false; + let code = match *event { PhysicalInput::Key { key, .. } => Some(key), _ => None }; + for ev in self.kbd.apply_modifier_keys(event, consumed) { + let mut one = self.transaction(app); + one.physical_key = code; + let took = self.route_modifier(app, &ev, &mut one); + fold_live(live, took, &one); + ran |= took; + merge(tx, one); + } + ran + } + + /// A modifier key goes to the app and the focused input's key handler, in `route_key`'s + /// order, and to nothing built in: no editing, selection, focus traversal or focus ring. + pub(in crate::runtime) fn route_modifier(&mut self, app: &mut dyn AppDriver, ev: &KeyEvent, one: &mut Tx) -> bool { + if !self.kbd.modifier_keys() { return false; } + one.key_repeat = false; + let app_first = self.kbd.focus.path().is_none(); + if app_first && app.has_on_key() && Tx::took(app.on_key(ev, one), one) { return true; } + if let Some(f) = self.focused_input().and_then(|input| input.key.clone()) + && Tx::took(f(app.states(), ev, one), one) + { + return true; + } + if !app_first && app.has_on_key() && Tx::took(app.on_key(ev, one), one) { + log_event!(self, "key {:?}", ev.key); + return true; + } + matches!(ev.key, Key::Modifier { pressed: false, .. }) && self.route_key_up(app, ev, one) + } +} + +#[cfg(test)] +#[path = "modifier_keys_tests.rs"] +mod tests; diff --git a/app/vendor/rune/crates/rune/src/runtime/input/modifier_keys_tests.rs b/app/vendor/rune/crates/rune/src/runtime/input/modifier_keys_tests.rs new file mode 100644 index 0000000..af63063 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/input/modifier_keys_tests.rs @@ -0,0 +1,279 @@ +use super::*; +use crate::{Cx, El, Env, KeySide, TextEdit, TextStyle, col, el, text_input}; + +#[derive(Default)] +struct Keys { edit: TextEdit, app: Vec<KeyEvent>, field: Vec<KeyEvent>, field_takes: bool, chords: usize, + recording: bool, recorded: Vec<PhysicalInput>, focus_lost: usize } +fn view(s: &Keys, _: &mut Cx<Keys>) -> El { + col().size(300.0, 200.0) + .child(text_input(&s.edit, TextStyle::new(14.0, 400.0)).single_line().key("field").size(200.0, 32.0) + .on_edit(|s: &mut Keys| &mut s.edit) + .on_input_key(|s: &mut Keys, ev, _| { + if !matches!(ev.key, Key::Modifier { .. }) { return false; } + s.field.push(ev.clone()); + s.field_takes + })) + .child(el().key("blank").size(100.0, 40.0)) + // A shortcut recorder: it takes every key while recording. + .child(el().key("recorder").size(100.0, 40.0).focusable(true) + .on_physical_input(|s: &mut Keys, ev, _| { + if matches!(ev, PhysicalInput::FocusLost) { s.focus_lost += 1; } + if s.recording { s.recorded.push(*ev); } + s.recording + })) +} +fn runtime(enabled: bool) -> Runtime<Keys> { + let mut rt = Runtime::new(Keys::default(), view, (300.0, 200.0), Env::new(true, 1.0)); + rt.set_modifier_keys(enabled); + rt.on_key = Some(|s, ev, _| { + // A typical chord binding: Cmd with any key. + if ev.mods.cmd && matches!(ev.key, Key::Text(_) | Key::Command(_)) { s.chords += 1; } + s.app.push(ev.clone()); + true + }); + rt.frame(0.0); + rt +} +fn click(rt: &mut Runtime<Keys>, key: &str) { + let (x, y) = rt.find(key).unwrap(); rt.pointer_down(x, y); rt.pointer_up(x, y); rt.frame(0.0); +} +/// A physical modifier key, as hosts send it: `mods` from before the change, like macOS. +fn modifier(rt: &mut Runtime<Keys>, code: Code, pressed: bool, mods: Mods) -> bool { + let redraw = rt.physical_with_fallback(PhysicalInput::Key { key: code, mods, pressed, repeat: false }, None); + rt.frame(0.0); + redraw +} +fn flags(rt: &mut Runtime<Keys>, mods: Mods) -> bool { + let redraw = rt.physical_with_fallback(PhysicalInput::Modifiers(mods), None); + rt.frame(0.0); + redraw +} +fn modifiers(log: &[KeyEvent]) -> Vec<(Modifier, bool)> { + log.iter().filter_map(|ev| match ev.key { Key::Modifier { modifier, pressed } => Some((modifier, pressed)), _ => None }).collect() +} +const SHIFT: Mods = Mods { shift: true, ctrl: false, alt: false, logo: false, cmd: false }; +const ALT: Mods = Mods { shift: false, ctrl: false, alt: true, logo: false, cmd: false }; + +#[test] +fn shift_alone_sends_press_and_release_with_side_and_mods_after_the_change() { + let mut rt = runtime(true); + assert!(modifier(&mut rt, Code::ShiftLeft, true, Mods::default()), "a press needs a frame"); + assert!(!flags(&mut rt, SHIFT), "the flags of a press already sent add nothing"); + assert!(modifier(&mut rt, Code::ShiftLeft, false, SHIFT)); + assert!(!flags(&mut rt, Mods::default())); + assert_eq!(modifiers(&rt.state.app), [(Modifier::ShiftLeft, true), (Modifier::ShiftLeft, false)]); + assert_eq!((rt.state.app[0].mods, rt.state.app[1].mods), (SHIFT, Mods::default())); + assert_eq!(Modifier::ShiftLeft.side(), Some(KeySide::Left)); + assert!(!rt.kbd.focus.keyboard(), "a modifier tap shows no focus ring"); +} + +#[test] +fn right_option_is_told_apart_from_left_option() { + let mut rt = runtime(true); + modifier(&mut rt, Code::AltRight, true, Mods::default()); + modifier(&mut rt, Code::AltLeft, true, ALT); + modifier(&mut rt, Code::AltRight, false, ALT); + modifier(&mut rt, Code::AltLeft, false, ALT); + assert_eq!(modifiers(&rt.state.app), [(Modifier::AltRight, true), (Modifier::AltLeft, true), + (Modifier::AltRight, false), (Modifier::AltLeft, false)]); + let alt: Vec<bool> = rt.state.app.iter().map(|ev| ev.mods.alt).collect(); + assert_eq!(alt, [true, true, true, false], "Option stays on while the other side is down"); + assert_eq!((Modifier::AltRight.side(), Modifier::Fn.side()), (Some(KeySide::Right), None)); +} + +#[test] +fn a_held_modifier_then_a_letter_is_the_usual_chord() { + let mut rt = runtime(true); + let cmd = Mods { cmd: true, ..Mods::default() }; + let code = if cfg!(target_os = "macos") { Code::SuperLeft } else { Code::ControlLeft }; + modifier(&mut rt, code, true, Mods::default()); + assert_eq!(rt.state.app[0].mods.cmd, true); + assert_eq!(rt.state.chords, 0, "the modifier alone is no chord"); + rt.physical_with_fallback(PhysicalInput::Key { key: Code::KeyK, mods: cmd, pressed: true, repeat: false }, + Some(KeyEvent { key: Key::Command('k'), mods: cmd })); + rt.frame(0.0); + assert_eq!(rt.state.app[1], KeyEvent { key: Key::Command('k'), mods: cmd }); + assert_eq!(rt.state.chords, 1); + // Shift held types capitals in a field as before. + click(&mut rt, "field"); + modifier(&mut rt, Code::ShiftRight, true, Mods::default()); + rt.physical_with_fallback(PhysicalInput::Key { key: Code::KeyA, mods: SHIFT, pressed: true, repeat: false }, + Some(KeyEvent { key: Key::Text("A".into()), mods: SHIFT })); + rt.frame(0.0); + assert_eq!(rt.state.edit.text, "A"); +} + +#[test] +fn modifier_keys_never_fire_chords_insert_text_or_repeat() { + let mut rt = runtime(true); + click(&mut rt, "field"); + rt.state.app.clear(); + for code in [Code::SuperLeft, Code::ControlLeft, Code::AltLeft, Code::ShiftLeft, Code::Fn] { + modifier(&mut rt, code, true, Mods::default()); + rt.physical_with_fallback(PhysicalInput::Key { key: code, mods: Mods::default(), pressed: true, repeat: true }, None); + rt.frame(0.0); + modifier(&mut rt, code, false, Mods::default()); + } + assert_eq!(rt.state.chords, 0); + assert_eq!(rt.state.edit.text, ""); + assert_eq!(rt.state.app.len(), 10, "one press and one release each, no repeats"); + assert!(rt.state.app.iter().all(|ev| matches!(ev.key, Key::Modifier { .. }))); + // A KeyEvent sent straight to a field's editor changes nothing either. + let ev = KeyEvent { key: Key::Modifier { modifier: Modifier::ShiftLeft, pressed: true }, mods: SHIFT }; + assert_eq!(rt.state.edit.key(&ev, None), crate::edit::EditOutcome::default()); +} + +#[test] +fn a_focused_field_hears_modifiers_before_the_window_unless_nothing_is_focused() { + let mut rt = runtime(true); + modifier(&mut rt, Code::ShiftLeft, true, Mods::default()); + assert_eq!((rt.state.app.len(), rt.state.field.len()), (1, 0), "nothing focused: the window's on_key"); + modifier(&mut rt, Code::ShiftLeft, false, SHIFT); + click(&mut rt, "field"); + rt.state.app.clear(); + rt.state.field_takes = true; + modifier(&mut rt, Code::ControlRight, true, Mods::default()); + assert_eq!((rt.state.app.len(), rt.state.field.len()), (0, 1), "the field took it"); + rt.state.field_takes = false; + modifier(&mut rt, Code::ControlRight, false, Mods { ctrl: true, ..Mods::default() }); + assert_eq!((rt.state.app.len(), rt.state.field.len()), (1, 2), "the field passed it on"); + assert_eq!(rt.state.app[0].key, Key::Modifier { modifier: Modifier::ControlRight, pressed: false }); +} + +#[test] +fn off_by_default_existing_handlers_see_no_modifier_keys() { + let mut rt = runtime(false); + assert!(!rt.modifier_keys()); + modifier(&mut rt, Code::ShiftLeft, true, Mods::default()); + assert!(!modifier(&mut rt, Code::ShiftLeft, false, SHIFT), "an unused release needs no frame"); + assert!(!flags(&mut rt, Mods::default())); + rt.physical_input(PhysicalInput::FocusLost); + rt.frame(0.0); + assert!(rt.state.app.is_empty()); +} + +#[test] +fn a_key_up_the_platform_never_sent_comes_from_the_flags_or_focus_loss() { + let mut rt = runtime(true); + let both = Mods { shift: true, alt: true, ..Mods::default() }; + modifier(&mut rt, Code::ShiftLeft, true, Mods::default()); + flags(&mut rt, SHIFT); + modifier(&mut rt, Code::AltRight, true, SHIFT); + flags(&mut rt, both); + modifier(&mut rt, Code::Fn, true, both); + assert!(flags(&mut rt, ALT), "Shift went off without its key-up"); + assert_eq!(modifiers(&rt.state.app)[3..], [(Modifier::ShiftLeft, false)]); + rt.physical_input(PhysicalInput::FocusLost); + rt.frame(0.0); + assert_eq!(modifiers(&rt.state.app)[4..], [(Modifier::AltRight, false), (Modifier::Fn, false)]); + assert!(rt.state.app[4..].iter().all(|ev| ev.mods == Mods::default())); + assert!(!modifier(&mut rt, Code::AltRight, false, Mods::default()), "a late key-up is not sent twice"); + assert_eq!(rt.state.app.len(), 6); +} + +#[test] +fn altgr_held_without_the_alt_flag_stays_down_until_its_key_up() { + // X11 and Wayland report AltGr (Right Alt on many layouts) as Level 3, not `alt`. + let mut rt = runtime(true); + modifier(&mut rt, Code::AltRight, true, Mods::default()); + flags(&mut rt, Mods::default()); + flags(&mut rt, SHIFT); + assert_eq!(modifiers(&rt.state.app), [(Modifier::AltRight, true)]); + modifier(&mut rt, Code::AltRight, false, SHIFT); + assert_eq!(modifiers(&rt.state.app), [(Modifier::AltRight, true), (Modifier::AltRight, false)]); +} + +#[test] +fn a_recorder_takes_modifiers_first_and_on_key_never_hears_half_of_what_it_took() { + let mut rt = runtime(true); + click(&mut rt, "recorder"); + rt.state.recording = true; + // Recording ⌥K: the recorder takes every key, and on_key hears none of it. + modifier(&mut rt, Code::AltLeft, true, Mods::default()); + flags(&mut rt, ALT); + rt.physical_with_fallback(PhysicalInput::Key { key: Code::KeyK, mods: ALT, pressed: true, repeat: false }, + Some(KeyEvent { key: Key::Text("k".into()), mods: ALT })); + rt.frame(0.0); + rt.state.recording = false; + assert!(!flags(&mut rt, Mods::default()), "Option's flag off is no release: its press was taken"); + assert!(!modifier(&mut rt, Code::AltLeft, false, ALT), "nor is its key-up"); + assert_eq!(rt.state.recorded.len(), 3); + assert!(rt.state.app.is_empty()); + // A release the recorder takes ends the key silently, so the next press is heard. + modifier(&mut rt, Code::ShiftLeft, true, Mods::default()); + rt.state.recording = true; + modifier(&mut rt, Code::ShiftLeft, false, SHIFT); + modifier(&mut rt, Code::AltRight, true, Mods::default()); + rt.state.recording = false; + modifier(&mut rt, Code::ShiftLeft, true, Mods::default()); + assert_eq!(modifiers(&rt.state.app), [(Modifier::ShiftLeft, true), (Modifier::ShiftLeft, true)]); + // A focus loss the recorder takes ends held keys silently, releases included. + rt.state.recording = true; + rt.physical_input(PhysicalInput::FocusLost); + rt.frame(0.0); + rt.state.recording = false; + assert!(matches!(rt.state.recorded.last(), Some(PhysicalInput::FocusLost))); + assert_eq!(rt.state.app.len(), 2); + assert!(!modifier(&mut rt, Code::ShiftLeft, false, SHIFT), "Shift was already ended"); + modifier(&mut rt, Code::AltRight, true, Mods::default()); + assert_eq!(modifiers(&rt.state.app)[2..], [(Modifier::AltRight, true)], "a key the recorder took is heard next time"); +} + +#[test] +fn a_blur_or_a_hide_releases_held_keys_once() { + let mut rt = runtime(true); + click(&mut rt, "recorder"); + rt.window_focus(true); + modifier(&mut rt, Code::ShiftLeft, true, Mods::default()); + // How `--desktop` and headless scripts blur a window. + rt.window_focus(false); + rt.frame(0.0); + assert_eq!(modifiers(&rt.state.app), [(Modifier::ShiftLeft, true), (Modifier::ShiftLeft, false)]); + assert_eq!(rt.state.focus_lost, 1, "the recorder hears the blur too"); + // A hide, then the blur it may or may not bring. + rt.window_focus(true); + modifier(&mut rt, Code::AltRight, true, Mods::default()); + rt.keys_lost(); + assert!(rt.keys_queued(), "a hidden host steps a frame to deliver it"); + rt.window_focus(false); + rt.frame(0.0); + assert_eq!(modifiers(&rt.state.app)[2..], [(Modifier::AltRight, true), (Modifier::AltRight, false)]); + assert_eq!(rt.state.focus_lost, 2); + rt.window_focus(true); + rt.keys_lost(); + rt.frame(0.0); + assert_eq!(rt.state.focus_lost, 3, "a hide without a blur, after focus came back"); +} + +#[test] +fn a_focus_move_inside_the_window_keeps_modifiers_held() { + let mut rt = runtime(true); + modifier(&mut rt, Code::ShiftLeft, true, Mods::default()); + click(&mut rt, "recorder"); + click(&mut rt, "field"); + modifier(&mut rt, Code::ShiftLeft, false, SHIFT); + assert_eq!(modifiers(&rt.state.app), [(Modifier::ShiftLeft, true), (Modifier::ShiftLeft, false)]); +} + +#[test] +fn windows_altgr_clearing_control_and_alt_is_no_release() { + let key = |key, pressed, mods| PhysicalInput::Key { key, mods, pressed, repeat: false }; + let ctrl = Mods { ctrl: true, ..Mods::default() }; + let sent = |out: Vec<KeyEvent>| modifiers(&out); + for altgr_clears in [true, false] { + let mut keys = ModifierKeys { enabled: true, ..ModifierKeys::default() }; + keys.apply(&key(Code::ControlLeft, true, Mods::default()), false, altgr_clears); + keys.apply(&PhysicalInput::Modifiers(ctrl), false, altgr_clears); + keys.apply(&key(Code::AltRight, true, ctrl), false, altgr_clears); + // Windows clears both flags while AltGr is down; X11 and Wayland leave Control on. + let cleared = sent(keys.apply(&PhysicalInput::Modifiers(Mods::default()), false, altgr_clears)); + if !altgr_clears { + assert_eq!(cleared, [(Modifier::ControlLeft, false)], "elsewhere a flag off is a key-up"); + continue; + } + assert!(cleared.is_empty(), "Left Control is still down"); + assert_eq!(sent(keys.apply(&key(Code::AltRight, false, Mods::default()), false, true)), [(Modifier::AltRight, false)]); + assert!(sent(keys.apply(&PhysicalInput::Modifiers(ctrl), false, true)).is_empty()); + assert_eq!(sent(keys.apply(&key(Code::ControlLeft, false, ctrl), false, true)), [(Modifier::ControlLeft, false)]); + } +} diff --git a/app/vendor/rune/crates/rune/src/runtime/input/physical.rs b/app/vendor/rune/crates/rune/src/runtime/input/physical.rs new file mode 100644 index 0000000..0370f20 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/input/physical.rs @@ -0,0 +1,240 @@ +use super::*; +use crate::{PhysicalInput, PhysicalKeyCode}; + +pub(in crate::runtime) struct Fallback { key: KeyEvent, base: Option<char>, unhandled: Option<Unhandled> } + +/// What a window does with a logical key no handler took: close or minimize as its title-bar +/// button would, or run a menu item. A standard ⌘W or ⌘M item, or an app's item marked +/// `MenuItem::keys_first`, asks for it, so an app's own binding wins. On Windows, Alt+Space +/// opens the window menu. +#[cfg_attr(not(target_os = "macos"), allow(dead_code))] +#[derive(Clone)] +pub(crate) enum Unhandled { Close, Minimize, Menu(std::sync::Arc<dyn Fn() + Send + Sync>), WindowMenu } + +impl std::fmt::Debug for Unhandled { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(match self { Self::Close => "Close", Self::Minimize => "Minimize", Self::Menu(_) => "Menu", Self::WindowMenu => "WindowMenu" }) + } +} + +/// Whether an activation key (Enter, Escape, Space) is held down: its physical code (native and +/// physical input) or logical key (`Runtime::key`), and the focus its first press landed on. +#[derive(Default)] +pub(in crate::runtime) enum Activation { + #[default] + Up, + Held { physical: Option<PhysicalKeyCode>, key: Option<crate::Key>, focus: Option<String> }, +} + +impl focus_machine::KeyboardState { + /// Remember an activation key's first press and the focus it landed on; true drops a + /// repeat of that same key once focus has moved. Any other first press replaces it. + pub(super) fn held_gate(&mut self, physical: Option<PhysicalKeyCode>, key: Option<&crate::Key>, repeat: bool) -> bool { + use crate::{Key, PhysicalKeyCode as Code}; + if !repeat { + // The OS keeps repeating a held key through modifier presses. + if physical.is_some_and(|c| matches!(c, Code::ShiftLeft | Code::ShiftRight | Code::ControlLeft + | Code::ControlRight | Code::AltLeft | Code::AltRight | Code::SuperLeft | Code::SuperRight + | Code::CapsLock | Code::Fn)) || key.is_some_and(|k| matches!(k, Key::Modifier { .. })) { return false; } + let activation = physical.is_some_and(|c| matches!(c, Code::Enter | Code::NumpadEnter | Code::Escape | Code::Space)) + || key.is_some_and(|k| matches!(k, Key::Enter | Key::Escape) || matches!(k, Key::Text(t) if t == " ")); + self.held = if activation { Activation::Held { physical, key: key.cloned(), focus: self.focus.owned() } } else { Activation::Up }; + return false; + } + let Activation::Held { physical: held, key: held_key, focus } = &self.held else { return false }; + let same = match physical { Some(code) => *held == Some(code), None => held_key.as_ref() == key }; + same && focus.as_deref() != self.focus.path() + } + + #[inline] + pub(super) fn clear_held(&mut self) { + self.held = Activation::Up; + } + + #[inline] + pub(super) fn release_held(&mut self, key: PhysicalKeyCode) { + if matches!(&self.held, Activation::Held { physical, .. } if *physical == Some(key)) { + self.held = Activation::Up; + } + } +} + +impl RuntimeCore { + /// Queue physical input without a logical fallback (also useful for headless drivers). + /// A modifier key still gets its `Key::Modifier` when modifier keys are on. + pub(crate) fn physical_input(&mut self, event: PhysicalInput) { + self.observe_mods(&event); + if self.cancel_drag_key(&event) { return; } + if matches!(event, PhysicalInput::Key { pressed: true, .. }) && self.pointer.autoscroll_key() { return; } + self.frame.queue.push(Action::Physical(event, None)); + } + + fn cancel_drag_key(&mut self, event: &PhysicalInput) -> bool { + matches!(event, PhysicalInput::Key { key: PhysicalKeyCode::Escape, pressed: true, .. }) + && self.cancel_drag() + } + /// Shift held now decides whether the next press extends a text selection, ahead of the + /// queue the press itself skips. A key press hides a tooltip. + fn observe_mods(&mut self, event: &PhysicalInput) { + match event { + PhysicalInput::Modifiers(m) => { self.edit.set_shift(m.shift); self.kbd.held_mods = *m; } + PhysicalInput::FocusLost => { self.edit.set_shift(false); self.kbd.held_mods = Default::default(); self.dismiss_help(); } + PhysicalInput::Key { pressed: true, mods, .. } => { self.kbd.held_mods = *mods; self.dismiss_help(); } + PhysicalInput::Key { mods, .. } => self.kbd.held_mods = *mods, + } + } + /// Queue a key press with its physical code and logical key, as a native host sends them + /// (a script's `{"type": "key", "code": …}`), and its `Tx::key_base`. + pub(crate) fn physical_key_input(&mut self, app: &mut dyn AppDriver, event: PhysicalInput, key: KeyEvent, base: Option<char>) { + self.observe_mods(&event); + self.physical_then(app, event, Some(key), base, None); + } + /// Return whether the native host needs to request a frame for this event. + #[cfg_attr(any(target_os = "windows", target_os = "ios", target_os = "android"), allow(dead_code))] + pub(crate) fn physical_with_fallback(&mut self, app: &mut dyn AppDriver, event: PhysicalInput, key: Option<KeyEvent>) -> bool { + self.physical_then(app, event, key, None, None) + } + /// `physical_with_fallback`, with the key's unmodified character (`Tx::key_base`), and + /// `unhandled` happens when no handler takes the logical key. + pub(crate) fn physical_then(&mut self, app: &mut dyn AppDriver, event: PhysicalInput, key: Option<KeyEvent>, base: Option<char>, unhandled: Option<Unhandled>) -> bool { + if self.cancel_drag_key(&event) { return true; } + // A key ends a middle-click autoscroll, and does nothing else. + if matches!(event, PhysicalInput::Key { pressed: true, .. }) && self.pointer.autoscroll_key() { return true; } + if key.is_none() && matches!(event, PhysicalInput::Modifiers(_) | PhysicalInput::Key { pressed: false, .. }) { + return self.physical_observation(app, event); + } + if !matches!(event, PhysicalInput::Key { pressed: false, .. }) { self.dismiss_help(); } + self.frame.queue.push(Action::Physical(event, key.map(|key| Fallback { key, base, unhandled }))); + true + } + /// Modifier/release events have no logical action. When input is already queued, + /// its requested frame will process this observation in order after clicks/keys. + /// At rest, only a consuming handler invalidates the view and requests a frame. + pub(crate) fn physical_observation(&mut self, app: &mut dyn AppDriver, event: PhysicalInput) -> bool { + let busy = !self.frame.queue.is_empty(); + self.observe_mods(&event); + // The release of a modifier key the app hears needs a frame, in order like a press. + // So does one while state changed since the last frame (a covered window keeps it + // changed until it uncovers): the focused handler is the new view's. + if self.kbd.modifier_pending(&event) || busy || self.commit.dirty { + self.frame.queue.push(Action::Physical(event, None)); + return !busy; + } + let mut tx = Tx::default(); + let consumed = self.dispatch_physical(app, event, None, &mut tx); + let live_only = std::mem::take(&mut tx.live_only); + self.latch_requests(app, &mut tx); + merge(&mut self.frame.pending, tx); + if consumed && live_only { + self.frame.live_only_skips += 1; + self.frame.live.set(); + } else { + self.commit.dirty |= consumed; + } + consumed + } + pub(in crate::runtime) fn dispatch_physical(&mut self, app: &mut dyn AppDriver, event: PhysicalInput, fallback: Option<Fallback>, tx: &mut Tx) -> bool { + tx.by_keys = true; + use crate::PhysicalKeyCode as Code; + let is_mod = |c: Code| matches!(c, Code::ShiftLeft | Code::ShiftRight | Code::ControlLeft + | Code::ControlRight | Code::AltLeft | Code::AltRight | Code::SuperLeft | Code::SuperRight + | Code::CapsLock | Code::Fn); + match event { + PhysicalInput::Key { key, pressed: true, repeat, .. } => { + if self.kbd.held_gate(Some(key), fallback.as_ref().map(|f| &f.key.key), repeat) { return false; } + if !is_mod(key) { self.note_key_down(app, repeat); } + } + PhysicalInput::Key { key, pressed: false, .. } => { + self.kbd.release_held(key); + if fallback.is_none() && !is_mod(key) && self.composing(app) { + self.kbd.composing_release(); + } + } + PhysicalInput::FocusLost => { + self.kbd.key_releases_lost(); + } + PhysicalInput::Modifiers(_) => {} + } + let repeat = matches!(event, PhysicalInput::Key { repeat: true, .. }); + let code = match event { PhysicalInput::Key { key, .. } => Some(key), _ => None }; + // Live-only when every handler that took the event said so (`Tx::live_only`). + let mut live = None; + // Ctrl+Shift's direction chord sees every key, whoever takes it. + let chord = self.direction_chord(app, &event, tx); + // It changes the field, so the view builds again whatever else is live-only. + if chord { live = Some(false); } + let consumed = self.offer_physical(app, &event, tx, &mut live); + let modifier = self.modifier_dispatch(app, &event, consumed, tx, &mut live); + let ran = consumed || chord || modifier | match fallback { + // A release's logical key, for `on_key_up`. + Some(Fallback { key, base, .. }) if matches!(event, PhysicalInput::Key { pressed: false, .. }) => { + let mut one = Tx { physical_key: code, key_base: base, ..self.transaction(app) }; + let ran = self.route_key_up(app, &key, &mut one); + fold_live(&mut live, ran, &one); + merge(tx, one); + ran + } + Some(Fallback { key, base, unhandled }) => { + if key.edit_command() == Some('v') && self.accepts_paste() { + // Capture the target in event order, before another queued click can + // change focus. An empty/image clipboard still consumes the command. + self.edit.paste_request = Some(self.paste_target()); + false + } else { + let mut one = Tx { physical_key: code, key_base: base, ..self.transaction(app) }; + let ran = self.route_key(app, &key, repeat, &mut one); + // A held key repeats a menu item, as AppKit's own equivalents do, but closes once. + let unhandled = unhandled.filter(|u| !ran && (!repeat || matches!(u, Unhandled::Menu(_)))); + let fell = unhandled.is_some(); + match unhandled { + Some(Unhandled::Close) => one.close_window(), + Some(Unhandled::Minimize) => one.minimize(), + Some(Unhandled::Menu(run)) => run(), + Some(Unhandled::WindowMenu) => self.request_window_menu(), + None => {} + } + fold_live(&mut live, ran || fell, &one); + merge(tx, one); + ran || fell + } + } + None => false, + }; + let ran = self.dispatch_mods(app, tx, &mut live) || ran; + tx.live_only = ran && live == Some(true); + ran + } + /// `App::on_modifiers`, when the held modifiers changed since it last heard them. + fn dispatch_mods(&mut self, app: &mut dyn AppDriver, tx: &mut Tx, live: &mut Option<bool>) -> bool { + if !app.has_on_mods() { return false; } + let Some(mods) = self.kbd.take_mods_changed() else { return false }; + let mut one = self.transaction(app); + if !app.on_mods(mods, &mut one) { return false; } + fold_live(live, true, &one); + merge(tx, one); + true + } + /// The focused element's `on_physical_input` handler; true if it consumed `event`. + fn offer_physical(&mut self, app: &mut dyn AppDriver, event: &PhysicalInput, tx: &mut Tx, live: &mut Option<bool>) -> bool { + let Some(handler) = self.kbd.focus.path().and_then(|p| self.node(p)) + .and_then(|n| n.focus.physical.clone()) else { return false }; + let mut one = Tx { key_repeat: matches!(event, PhysicalInput::Key { repeat: true, .. }), ..self.transaction(app) }; + let consumed = Tx::took(handler(app.states(), event, &mut one), &mut one); + fold_live(live, consumed, &one); + merge(tx, one); + consumed + } + /// Focus moving off an element inside the window: its handler hears `FocusLost`, and + /// modifier keys stay held. + pub(in crate::runtime) fn physical_focus_lost(&mut self, app: &mut dyn AppDriver) -> bool { + let mut tx = Tx::default(); + let changed = self.offer_physical(app, &PhysicalInput::FocusLost, &mut tx, &mut None); + self.latch_requests(app, &mut tx); + merge(&mut self.frame.pending, tx); + changed + } +} + +#[cfg(test)] +#[path = "physical_tests.rs"] +mod tests; diff --git a/app/vendor/rune/crates/rune/src/runtime/input/physical_tests.rs b/app/vendor/rune/crates/rune/src/runtime/input/physical_tests.rs new file mode 100644 index 0000000..da23594 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/input/physical_tests.rs @@ -0,0 +1,451 @@ +use super::*; +use crate::{Cx, El, Env, Key, Mods, PhysicalKeyCode, TextEdit, TextStyle, col, el, text_input}; + +#[derive(Default)] +struct State { capture: bool, physical: usize, logical: usize, dismissed: usize, edit: TextEdit, gone: bool } +fn view(s: &State, _: &mut Cx<State>) -> El { + let recorder = el().key("recorder").size(100.0, 40.0).focusable(true) + .on_press(|s: &mut State| s.capture = true) + .on_physical_input(|s: &mut State, _, _| { + if s.capture { s.physical += 1; true } else { false } + }); + col().key("modal").size(300.0, 200.0).modal(false, |s: &mut State| s.dismissed += 1) + .children((!s.gone).then_some(recorder)) + .child(text_input(&s.edit, TextStyle::new(14.0, 400.0)).key("edit").size(200.0, 40.0) + .on_edit(|s: &mut State| &mut s.edit)) +} +#[test] +fn physical_dispatch_precedes_modal_app_and_paste_after_same_frame_click() { + let mut rt = Runtime::new(State::default(), view, (300.0, 200.0), Env { system_dark: true, scale: 1.0 }); + rt.on_key = Some(|s, _, _| { s.logical += 1; true }); + rt.frame(0.0); + let (x, y) = rt.find("recorder").unwrap(); rt.pointer_down(x, y); rt.pointer_up(x, y); + let mods = Mods { cmd: true, ..Mods::default() }; + rt.physical_with_fallback(PhysicalInput::Key { key: PhysicalKeyCode::KeyV, mods, pressed: true, repeat: false }, + Some(KeyEvent { key: Key::Command('v'), mods })); + rt.physical_with_fallback(PhysicalInput::Key { key: PhysicalKeyCode::Escape, mods: Mods::default(), pressed: true, repeat: false }, + Some(KeyEvent { key: Key::Escape, mods: Mods::default() })); + rt.frame(0.0); + assert_eq!((rt.state.physical, rt.state.logical, rt.state.dismissed), (2, 0, 0)); + assert_eq!(rt.state.edit.text, ""); + assert!(rt.edit.paste_request.is_none(), "capture must not read the clipboard"); + rt.state.capture = false; + let (x, y) = rt.find("edit").unwrap(); rt.pointer_down(x, y); rt.pointer_up(x, y); + rt.physical_with_fallback(PhysicalInput::Key { key: PhysicalKeyCode::KeyV, mods, pressed: true, repeat: false }, + Some(KeyEvent { key: Key::Command('v'), mods })); + rt.frame(0.0); + let target = rt.edit.paste_request.take().expect("paste requested"); + rt.paste_result(target, crate::ClipboardContent::new("paste")); + rt.frame(0.0); + assert_eq!(rt.state.edit.text, "paste"); + rt.physical_with_fallback(PhysicalInput::Key { key: PhysicalKeyCode::Escape, mods: Mods::default(), pressed: true, repeat: false }, + Some(KeyEvent { key: Key::Escape, mods: Mods::default() })); + rt.frame(0.0); + assert_eq!(rt.state.dismissed, 1); +} + +#[test] +fn modifier_and_release_redraws_require_consumption_and_keep_queued_focus_order() { + let mut rt = Runtime::new(State::default(), view, (300.0, 200.0), Env::new(true, 1.0)); + rt.frame(0.0); + let modifiers = PhysicalInput::Modifiers(Mods { shift: true, ..Mods::default() }); + let release = PhysicalInput::Key { key: PhysicalKeyCode::ShiftLeft, mods: Mods::default(), pressed: false, repeat: false }; + for event in [modifiers, release] { + assert!(!rt.physical_with_fallback(event, None)); + assert!(rt.frame.queue.is_empty() && !rt.commit.dirty, "unused input must not schedule work"); + } + click(&mut rt, "recorder"); + // The click already requested a frame. Do not deliver modifiers to the old + // focus or request another frame before that queued click starts capture. + assert!(!rt.physical_with_fallback(modifiers, None)); + assert_eq!(rt.state.physical, 0); + rt.frame(0.0); + assert_eq!(rt.state.physical, 1); + for event in [modifiers, release] { + assert!(rt.physical_with_fallback(event, None)); + assert!(rt.commit.dirty, "consumption must commit the handler's state changes"); + rt.frame(0.0); + } + assert_eq!(rt.state.physical, 3); + rt.state.capture = false; + assert!(!rt.physical_with_fallback(release, None), "a declining handler needs no frame"); + rt.state.capture = true; + click(&mut rt, "edit"); + assert!(!rt.physical_with_fallback(modifiers, None)); + rt.frame(0.0); + let delivered = rt.state.physical; // FocusLost may notify the old recorder. + assert!(!rt.physical_with_fallback(release, None)); + assert_eq!(rt.state.physical, delivered); + assert!(rt.frame.queue.is_empty() && !rt.commit.dirty); +} + +/// A modifier change while state changed since the last frame, as a covered window's does +/// until it uncovers, goes to the focused handler of the view that state builds, not the +/// last frame's. +#[test] +fn a_modifier_change_after_an_update_waits_for_the_new_view() { + let mut rt = Runtime::new(State::default(), view, (300.0, 200.0), Env::new(true, 1.0)); + rt.frame(0.0); + click(&mut rt, "recorder"); + rt.frame(0.0); + assert!(rt.state.capture); + let heard = rt.state.physical; + rt.update(|s, _| s.gone = true); + let modifiers = PhysicalInput::Modifiers(Mods { shift: true, ..Mods::default() }); + assert!(rt.physical_with_fallback(modifiers, None), "it asks for the frame that builds the new view"); + assert_eq!(rt.state.physical, heard, "the last frame's recorder doesn't hear it"); + rt.frame(0.0); + assert!(rt.find("recorder").is_none()); + assert_eq!(rt.state.physical, heard, "and the new view has none"); +} + +#[derive(Default)] +struct Fields { first: TextEdit, second: TextEdit, secure: bool, keys: usize, app_keys: usize } +fn fields(s: &Fields, _: &mut Cx<Fields>) -> El { + let first = text_input(&s.first, TextStyle::new(14.0, 400.0)).single_line() + .key("first").size(100.0, 32.0).on_edit(|s: &mut Fields| &mut s.first) + .on_input_key(|s: &mut Fields, _, _| { s.keys += 1; false }); + col().size(300.0, 200.0) + .child(if s.secure { first.secure() } else { first }) + .child(text_input(&s.second, TextStyle::new(14.0, 400.0)).key("second") + .size(100.0, 32.0).on_edit(|s: &mut Fields| &mut s.second)) +} +fn click<S: 'static>(rt: &mut Runtime<S>, key: &str) { + let (x, y) = rt.find(key).unwrap(); rt.pointer_down(x, y); rt.pointer_up(x, y); +} +fn key<S: 'static>(rt: &mut Runtime<S>, physical: PhysicalKeyCode, key: Key) { + let mods = Mods { cmd: matches!(key, Key::Command(_)), ..Mods::default() }; + rt.physical_with_fallback(PhysicalInput::Key { key: physical, mods, pressed: true, repeat: false }, + Some(KeyEvent { key, mods })); +} +fn fields_runtime(secure: bool) -> Runtime<Fields> { + let mut rt = Runtime::new(Fields { secure, ..Fields::default() }, fields, (300.0, 200.0), Env::new(true, 1.0)); + rt.on_key = Some(|s, _, _| { s.app_keys += 1; true }); + rt.frame(0.0); rt +} + +#[test] +fn paste_is_swallowed_without_text_and_target_survives_a_later_queued_click() { + let mut rt = fields_runtime(false); + key(&mut rt, PhysicalKeyCode::KeyV, Key::Command('v')); + rt.frame(0.0); + assert!(rt.edit.paste_request.is_none(), "no focused editor or paste handler: no clipboard read"); + assert_eq!(rt.state.app_keys, 1); + click(&mut rt, "first"); + key(&mut rt, PhysicalKeyCode::KeyV, Key::Command('v')); + rt.frame(0.0); + let first = rt.edit.paste_request.take().unwrap(); + assert!(first.is_some()); + assert_eq!((rt.state.keys, rt.state.app_keys), (0, 1)); + // Image-only clipboard sends no reply. An empty text reply also never falls + // through to either key handler. + rt.paste_result(first.clone(), crate::ClipboardContent::new("")); + rt.frame(0.0); + assert_eq!((rt.state.keys, rt.state.app_keys), (0, 1)); + key(&mut rt, PhysicalKeyCode::KeyV, Key::Command('v')); + click(&mut rt, "second"); + rt.frame(0.0); + let target = rt.edit.paste_request.take().unwrap(); + assert_eq!(target, first, "target captured before the next click, not at worker flush"); + assert_ne!(target, rt.paste_target()); + rt.paste_result(target, crate::ClipboardContent::new("late")); + rt.frame(0.0); + assert!(rt.state.first.text.is_empty() && rt.state.second.text.is_empty()); +} + +#[test] +fn physical_fallback_edits_single_line_and_preserves_secure_copy_protection() { + for secure in [false, true] { + let mut rt = fields_runtime(secure); + click(&mut rt, "first"); + key(&mut rt, PhysicalKeyCode::KeyX, Key::Text("x".into())); + rt.frame(0.0); + assert_eq!(rt.state.first.text, "x"); + assert_eq!(rt.has_secure_focus(), secure); + key(&mut rt, PhysicalKeyCode::KeyA, Key::Command('a')); + key(&mut rt, PhysicalKeyCode::KeyC, Key::Command('c')); + rt.frame(0.0); + assert_eq!(rt.copy_request.is_none(), secure); + key(&mut rt, PhysicalKeyCode::KeyV, Key::Command('v')); + rt.frame(0.0); + let target = rt.edit.paste_request.take().unwrap(); + rt.paste_result(target, crate::ClipboardContent::new("replacement")); + rt.frame(0.0); + assert_eq!(rt.state.first.text, "replacement"); + if secure { + let elements = rt.elements(); + let field = elements.iter().find(|e| e.key.as_deref() == Some("first")).unwrap(); + assert!(field.text.is_none()); + } + } +} + +#[derive(Default)] +struct Held { edit: TextEdit, other: TextEdit, input: Vec<bool>, app: Vec<(Key, bool)> } +fn held(s: &Held, _: &mut Cx<Held>) -> El { + col().size(300.0, 200.0) + .child(text_input(&s.edit, TextStyle::new(14.0, 400.0)).single_line().key("field").size(200.0, 32.0) + .on_edit(|s: &mut Held| &mut s.edit) + .on_input_key(|s: &mut Held, _, tx| { s.input.push(tx.key_repeat()); false })) + .child(text_input(&s.other, TextStyle::new(14.0, 400.0)).single_line().key("other").size(200.0, 32.0) + .on_edit(|s: &mut Held| &mut s.other)) +} +fn focused(rt: &Runtime<Held>) -> Option<String> { + rt.elements().into_iter().find(|e| e.focused).and_then(|e| e.key) +} +fn press<S: 'static>(rt: &mut Runtime<S>, physical: PhysicalKeyCode, key: Key, repeat: bool) { + let mods = Mods::default(); + rt.physical_with_fallback(PhysicalInput::Key { key: physical, mods, pressed: true, repeat }, Some(KeyEvent { key, mods })); + rt.frame(0.0); +} + +#[test] +fn key_handlers_see_a_held_keys_repeats_and_editing_keeps_repeating() { + let mut rt = Runtime::new(Held::default(), held, (300.0, 200.0), Env::new(true, 1.0)); + rt.on_key = Some(|s, ev, tx| { s.app.push((ev.key.clone(), tx.key_repeat())); true }); + rt.frame(0.0); + // No focus: the app handler gets first refusal, so it sees both presses. + press(&mut rt, PhysicalKeyCode::Enter, Key::Enter, false); + press(&mut rt, PhysicalKeyCode::Enter, Key::Enter, true); + assert_eq!(rt.state.app, [(Key::Enter, false), (Key::Enter, true)]); + click(&mut rt, "field"); + rt.frame(0.0); + press(&mut rt, PhysicalKeyCode::KeyX, Key::Text("x".into()), false); + press(&mut rt, PhysicalKeyCode::KeyX, Key::Text("x".into()), true); + press(&mut rt, PhysicalKeyCode::KeyX, Key::Text("x".into()), true); + assert_eq!(rt.state.input, [false, true, true]); + assert_eq!(rt.state.edit.text, "xxx", "a held letter keeps typing"); + // Held Tab keeps moving focus, and Rune consumes it before the app handler. + press(&mut rt, PhysicalKeyCode::Tab, Key::Tab, true); + assert_eq!(focused(&rt).as_deref(), Some("other")); + press(&mut rt, PhysicalKeyCode::Tab, Key::Tab, true); + assert_eq!(focused(&rt).as_deref(), Some("field")); + assert_eq!(rt.state.app.len(), 2); +} + +#[test] +fn a_queued_repeat_reaches_the_app_handler_with_the_flag_set() { + let mut rt = Runtime::new(Held::default(), held, (300.0, 200.0), Env::new(true, 1.0)); + rt.on_key = Some(|s, ev, tx| { s.app.push((ev.key.clone(), tx.key_repeat())); true }); + rt.frame(0.0); + rt.key(KeyEvent { key: Key::Text("s".into()), mods: Mods::default() }); + rt.repeat_key(KeyEvent { key: Key::Text("s".into()), mods: Mods::default() }); + rt.key(KeyEvent { key: Key::Text("s".into()), mods: Mods::default() }); + rt.frame(0.0); + let s = Key::Text("s".into()); + assert_eq!(rt.state.app, [(s.clone(), false), (s.clone(), true), (s, false)]); +} + +#[test] +fn key_handlers_see_the_physical_key_whatever_the_layout_types() { + #[derive(Default)] + struct Codes { + edit: TextEdit, + input: Vec<Option<PhysicalKeyCode>>, + app: Vec<(Key, Option<PhysicalKeyCode>, bool)>, + ups: Vec<Option<PhysicalKeyCode>>, + change: Vec<Option<PhysicalKeyCode>>, + } + let view = |s: &Codes, _: &mut Cx<Codes>| col().size(300.0, 200.0) + .on_key_up(|s: &mut Codes, _, tx| { s.ups.push(tx.physical_key()); true }) + .child(text_input(&s.edit, TextStyle::new(14.0, 400.0)).key("field").size(200.0, 32.0) + .on_edit(|s: &mut Codes| &mut s.edit) + .on_input_change(|s: &mut Codes, tx| s.change.push(tx.physical_key())) + .on_input_key(|s: &mut Codes, _, tx| { s.input.push(tx.physical_key()); false })); + let mut rt = Runtime::new(Codes::default(), view, (300.0, 200.0), Env::new(true, 1.0)); + rt.on_key = Some(|s, ev, tx| { s.app.push((ev.key.clone(), tx.physical_key(), tx.key_repeat())); true }); + rt.frame(0.0); + click(&mut rt, "field"); + rt.frame(0.0); + // ⌘⇧7 on a German layout types '/', on a US one '&'; both are the 7 key (press, repeat, key-up). + let mods = Mods { cmd: true, shift: true, ..Mods::default() }; + for (c, repeat) in [('/', false), ('&', true)] { + rt.physical_with_fallback(PhysicalInput::Key { key: PhysicalKeyCode::Digit7, mods, pressed: true, repeat }, + Some(KeyEvent { key: Key::Command(c), mods })); + rt.physical_with_fallback(PhysicalInput::Key { key: PhysicalKeyCode::Digit7, mods, pressed: false, repeat: false }, + Some(KeyEvent { key: Key::Command(c), mods })); + rt.frame(0.0); + } + let seven = Some(PhysicalKeyCode::Digit7); + assert_eq!(rt.state.input, [seven, seven]); + assert_eq!(rt.state.app, [(Key::Command('/'), seven, false), (Key::Command('&'), seven, true)]); + assert_eq!(rt.state.ups, [seven, seven]); + // A logical key with no physical origin has none, and non-key callbacks (`on_input_change`) + // never inherit the key handler's physical key. + rt.key(KeyEvent { key: Key::Command('&'), mods }); + rt.physical_with_fallback(PhysicalInput::Key { key: PhysicalKeyCode::KeyA, mods: Mods::default(), pressed: true, repeat: false }, + Some(KeyEvent { key: Key::Text("a".into()), mods: Mods::default() })); + rt.frame(0.0); + assert_eq!(rt.state.app.last(), Some(&(Key::Command('&'), None, false))); + assert_eq!(rt.state.change, [None]); +} + +#[test] +fn a_format_chord_the_field_does_not_allow_goes_to_the_app() { + #[derive(Default)] + struct Rich { edit: TextEdit, app: Vec<Key> } + let view = |s: &Rich, _: &mut Cx<Rich>| col().size(300.0, 200.0) + .child(text_input(&s.edit, TextStyle::new(14.0, 400.0)).key("field").size(200.0, 32.0).on_edit(|s: &mut Rich| &mut s.edit)); + let edit = TextEdit::new("ab").rich().allow_marks([crate::Mark::Bold]); + let mut rt = Runtime::new(Rich { edit, app: Vec::new() }, view, (300.0, 200.0), Env::new(true, 1.0)); + rt.on_key = Some(|s, ev, _| { s.app.push(ev.key.clone()); true }); + rt.frame(0.0); + click(&mut rt, "field"); + rt.frame(0.0); + let cmd = |c| KeyEvent { key: Key::Command(c), mods: Mods { cmd: true, ..Mods::default() } }; + for c in ['a', 'u', 'b'] { rt.key(cmd(c)); } + rt.frame(0.0); + assert_eq!(rt.state.app, [Key::Command('u')]); + assert!(rt.state.edit.marks().iter().all(|m| m.mark == crate::Mark::Bold) && !rt.state.edit.marks().is_empty()); +} + +fn release<S: 'static>(rt: &mut Runtime<S>, physical: PhysicalKeyCode) { + rt.physical_with_fallback(PhysicalInput::Key { key: physical, mods: Mods::default(), pressed: false, repeat: false }, None); + rt.frame(0.0); +} + +#[test] +fn a_held_arrow_keeps_repeating_after_an_escape_tap_moves_focus() { + let mut rt = fields_runtime(false); + click(&mut rt, "first"); + press(&mut rt, PhysicalKeyCode::ArrowDown, Key::Down, false); + press(&mut rt, PhysicalKeyCode::Escape, Key::Escape, false); + release(&mut rt, PhysicalKeyCode::Escape); + assert!(!rt.has_focus(), "Escape blurred the field"); + let before = rt.state.app_keys; + press(&mut rt, PhysicalKeyCode::ArrowDown, Key::Down, true); + press(&mut rt, PhysicalKeyCode::ArrowDown, Key::Down, true); + assert_eq!(rt.state.app_keys, before + 2, "the held arrow's repeats still arrive"); + // The same without a release, from a script: only Escape's own repeats are dropped. + click(&mut rt, "first"); + rt.key(KeyEvent { key: Key::Escape, mods: Mods::default() }); rt.frame(0.0); + rt.repeat_key(KeyEvent { key: Key::Down, mods: Mods::default() }); + rt.repeat_key(KeyEvent { key: Key::Escape, mods: Mods::default() }); + rt.frame(0.0); + assert_eq!(rt.state.app_keys, before + 3); +} + +#[test] +fn a_released_key_and_a_pointer_focus_change_leave_later_repeats_alone() { + let mut rt = fields_runtime(false); + click(&mut rt, "second"); + press(&mut rt, PhysicalKeyCode::Enter, Key::Enter, false); + release(&mut rt, PhysicalKeyCode::Enter); + click(&mut rt, "first"); + rt.frame(0.0); + rt.repeat_key(KeyEvent { key: Key::Down, mods: Mods::default() }); + rt.repeat_key(KeyEvent { key: Key::Enter, mods: Mods::default() }); + rt.frame(0.0); + assert_eq!(rt.state.keys, 2, "scripted repeats reach the newly focused field"); +} + +#[derive(Default)] +struct Opener { modal: bool, go_repeats: usize, sink: usize } +fn opener(s: &Opener, _: &mut Cx<Opener>) -> El { + let mut root = col().size(300.0, 200.0) + .child(el().key("go").size(40.0, 30.0).focusable(true).role("button") + .on_press(|s: &mut Opener| s.modal = true) + .on_physical_input(|s: &mut Opener, e, _| { + if matches!(e, PhysicalInput::Key { repeat: true, .. }) { s.go_repeats += 1; } + false + })) + .child(el().key("grab").size(40.0, 30.0).focusable(true) + .on_physical_input(|s: &mut Opener, e, _| match e { + PhysicalInput::Key { key: PhysicalKeyCode::Enter, pressed: true, repeat: false, .. } => { s.modal = true; true } + _ => false, + })); + if s.modal { + root = root.child(col().key("modal").absolute(100.0, 0.0).size(100.0, 100.0) + .modal(true, |s: &mut Opener| s.modal = false) + .child(el().key("sink").size(40.0, 30.0).focusable(true) + .on_physical_input(|s: &mut Opener, e, _| { + if matches!(e, PhysicalInput::Key { pressed: true, .. }) { s.sink += 1; } + true + }))); + } + root +} +fn opener_focused_on(tabs: usize) -> Runtime<Opener> { + let mut rt = Runtime::new(Opener::default(), opener, (300.0, 200.0), Env::new(true, 1.0)); + rt.frame(0.0); + for _ in 0..tabs { rt.key(KeyEvent { key: Key::Tab, mods: Mods::default() }); rt.frame(0.0); } + rt +} +fn focused_key<S: 'static>(rt: &Runtime<S>) -> Option<String> { + rt.elements().into_iter().find(|e| e.focused).and_then(|e| e.key) +} + +#[test] +fn repeats_never_reach_physical_handlers_after_their_key_moved_focus() { + // A built-in press opens the modal: the new focus's physical handler sees no repeat. + let mut rt = opener_focused_on(1); + assert_eq!(focused_key(&rt).as_deref(), Some("go")); + press(&mut rt, PhysicalKeyCode::Space, Key::Text(" ".into()), false); + assert_eq!(focused_key(&rt).as_deref(), Some("sink")); + press(&mut rt, PhysicalKeyCode::Space, Key::Text(" ".into()), true); + press(&mut rt, PhysicalKeyCode::Space, Key::Text(" ".into()), true); + assert_eq!(rt.state.sink, 0); + // A physical handler consumes the first press and opens it: still recorded and dropped. + let mut rt = opener_focused_on(2); + assert_eq!(focused_key(&rt).as_deref(), Some("grab")); + press(&mut rt, PhysicalKeyCode::Enter, Key::Enter, false); + assert_eq!(focused_key(&rt).as_deref(), Some("sink")); + press(&mut rt, PhysicalKeyCode::Enter, Key::Enter, true); + assert_eq!(rt.state.sink, 0); +} + +#[test] +fn a_repeat_queued_in_the_same_frame_sees_the_focus_its_press_moved() { + let mut rt = opener_focused_on(1); + let mods = Mods::default(); + rt.physical_with_fallback(PhysicalInput::Key { key: PhysicalKeyCode::Space, mods, pressed: true, repeat: false }, + Some(KeyEvent { key: Key::Text(" ".into()), mods })); + rt.physical_with_fallback(PhysicalInput::Key { key: PhysicalKeyCode::Space, mods, pressed: true, repeat: true }, + Some(KeyEvent { key: Key::Text(" ".into()), mods })); + rt.frame(0.0); + assert_eq!(focused_key(&rt).as_deref(), Some("sink")); + assert_eq!((rt.state.go_repeats, rt.state.sink), (0, 0), "the repeat went nowhere"); +} + +/// A `keys_first` menu item's key: the focused field, then `on_key`, see it before the item, +/// which runs only when neither takes it (and on each repeat, as a menu equivalent does). +#[test] +fn a_menu_item_handing_over_its_key_runs_only_when_no_handler_takes_it() { + use std::sync::{Arc, atomic::{AtomicUsize, Ordering}}; + let mut rt = fields_runtime(false); + rt.on_key = Some(|s, ev, _| { s.app_keys += 1; ev.is_command(']') }); + let ran = Arc::new(AtomicUsize::new(0)); + let item = { let ran = ran.clone(); Unhandled::Menu(Arc::new(move || { ran.fetch_add(1, Ordering::Relaxed); })) }; + let mods = Mods { cmd: true, ..Mods::default() }; + let chord = |rt: &mut Runtime<Fields>, code, c, repeat| { + rt.physical_then(PhysicalInput::Key { key: code, mods, pressed: true, repeat }, + Some(KeyEvent { key: Key::Command(c), mods }), None, Some(item.clone())); + rt.frame(0.0); + ran.load(Ordering::Relaxed) + }; + assert_eq!(chord(&mut rt, PhysicalKeyCode::BracketRight, ']', false), 0, "the app's on_key took it"); + assert_eq!(chord(&mut rt, PhysicalKeyCode::BracketLeft, '[', false), 1, "nobody took it: the item runs"); + assert_eq!(chord(&mut rt, PhysicalKeyCode::BracketLeft, '[', true), 2, "and repeats"); + assert_eq!(rt.state.app_keys, 3); + // A field that takes the key (⌘A selects all) keeps it from the item and from on_key. + click(&mut rt, "first"); + rt.frame(0.0); + assert_eq!(chord(&mut rt, PhysicalKeyCode::KeyA, 'a', false), 2); + assert_eq!(rt.state.app_keys, 3); +} + +#[test] +fn physical_paste_uses_app_handler_without_a_focused_editor() { + fn view(_: &String, _: &mut Cx<String>) -> El { + el().size(100.0, 100.0).on_paste(|s: &mut String, text, _| *s = text.into()) + } + let mut rt = Runtime::new(String::new(), view, (100.0, 100.0), Env::new(true, 1.0)); + rt.frame(0.0); + key(&mut rt, PhysicalKeyCode::KeyV, Key::Command('v')); + rt.frame(0.0); + assert_eq!(rt.edit.paste_request, Some(None)); + let target = rt.edit.paste_request.take().unwrap(); + rt.paste_result(target, crate::ClipboardContent::new("app")); + rt.frame(0.0); + assert_eq!(rt.state, "app"); +} diff --git a/app/vendor/rune/crates/rune/src/runtime/input/pointer.rs b/app/vendor/rune/crates/rune/src/runtime/input/pointer.rs new file mode 100644 index 0000000..294d84c --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/input/pointer.rs @@ -0,0 +1,680 @@ +//! Pointer press, drag, drag-out, cursor and wheel/fling input entry. +use super::*; + +/// How far (points, per axis) a click may travel and still pair into a double click. +pub(in crate::runtime) const CLICK_SLOP: f32 = 4.0; + +impl RuntimeCore { + pub(crate) fn pointer_move(&mut self, app: &dyn ViewDriver, x: f32, y: f32) { self.move_pointer(app, x, y, true); } + + /// `drag_move` false keeps a held drag from getting a `Phase::Move`: a release at the + /// point the drag last saw has nothing new to report, and its instant transaction would + /// cut short whatever the press started (a tapped slider's knob mid-spring). + pub(in crate::runtime) fn move_pointer(&mut self, app: &dyn ViewDriver, x: f32, y: f32, drag_move: bool) { + let moved = self.pointer.pos != Some((x, y)); + if moved { self.pointer.hover_paused = false; self.release_hover_hold(); } + self.pointer.pos = Some((x, y)); + self.autoscroll_moved(x, y); + if self.in_viewport(x, y) { self.pointer.set_left(false); } + for &(id, rect) in self.hit.hits() { + if self.hit_contains(id, rect, x, y) + && let Some(&i) = self.tree.node_index.get(&id) + && self.tree.nodes[i].handlers.get().is_some_and(|h| h.on_pointer_move.is_some()) + { + let point = self.pointer_event(i, x, y); + self.frame.queue.push(Action::PointerMove(self.tree.nodes[i].path.clone(), point)); + } + } + self.refresh_hover(x, y); + let Some(held) = self.pointer.press.held() else { return }; + let (path, d, at, button) = (held.path.clone(), held.drag, held.at, held.button); + if held.drag_out.is_some_and(|threshold| crate::drag_out::past_threshold(at, (x, y), threshold)) && self.start_drag_out(app, path.clone()) { + return; + } + if let Some(held) = self.pointer.press.held_mut() { + held.moved |= !press_run::within_slop(at, (x, y)); + } + self.selection_drag(x, y); + self.edge_scroll_moved(y); + if self.edit.input_click.captured() { + self.input_drag(x, y, drag_move); + return; + } + let Some(i) = self.live_index(&path) else { return }; + let (id, r, has_drag) = (self.tree.nodes[i].id, self.tree.nodes[i].target, self.drags_with(i, button)); + // A hit rect is where the element was drawn (after scrolling); `target` is its + // unscrolled layout rect, kept only for elements that were never drawn. Only the + // pointer moving decides whether it's still inside: a button that springs out from + // under a still pointer stays pressed, as AppKit only re-tracks on a drag. + if moved && self.pointer.press.held().is_some_and(|h| h.hit != capture::Hit::Cancelled) { + let inside = match self.hit.has_node_hit(id, |id, r| self.hit_contains(id, r, x, y)) { + Some(hit) => hit, + None if self.host.native_overlay => false, + None => contains(r, x, y), + }; + if let Some(held) = self.pointer.press.held_mut() { + held.hit = if inside { capture::Hit::Inside } else { capture::Hit::Outside }; + } + } + if has_drag && drag_move { + let (dx, dy) = (x - at.0, y - at.1); + let [lx, ly] = self.to_local(i, x, y); + let d = Drag { phase: Phase::Move, x: lx, y: ly, dx, dy, window: [x, y], screen: self.screen_at(x, y), ..d }; + self.frame.queue.push(Action::Drag(path, d, button)); + } + } + + /// Overlay observation updates coordinates without presenting unchanged hover pixels. + pub(crate) fn observe_pointer(&mut self, app: &dyn ViewDriver, x: f32, y: f32) -> bool { + if self.pointer.pos == Some((x, y)) { return false; } + let visual_changed = self.tree.nodes.iter().enumerate().any(|(i, n)| { + if n.vis.hover().a <= 0.0 && !n.vis.tracks_press() && n.handlers.get().is_none_or(|h| h.press_scale.is_none()) { return false; } + let inside = |p: Option<(f32, f32)>| p.is_some_and(|(x, y)| self.node_contains(i, x, y)); + inside(self.pointer.pos) != inside(Some((x, y))) + }); + // Reaching or leaving a help element starts or ends its tooltip's wait. + let help_changed = self.help_target_changes(x, y); + let (queued, capture_inside) = (self.frame.queue.len(), self.pointer.press_inside()); + self.pointer_move(app, x, y); + visual_changed || help_changed || self.frame.queue.len() != queued || self.pointer.press_inside() != capture_inside + } + + /// A button holds the pointer: the OS keeps sending its moves to this window, and a leave + /// waits for the release. + #[inline] + pub(crate) fn pointer_captured(&self) -> bool { self.pointer.captured() } + + /// The host's window content top-left in desktop pixels; `None` where it has none. + pub(crate) fn set_window_pixels(&mut self, pixels: Option<(i32, i32)>) { + self.host.window_pixels = pixels; + } + + /// (x, y) window points in desktop pixels (`Drag::screen_point`). + pub(in crate::runtime) fn screen_at(&self, x: f32, y: f32) -> Option<(i32, i32)> { + let s = self.env.scale; + self.host.window_pixels.map(|(px, py)| (px + (x * s).round() as i32, py + (y * s).round() as i32)) + } + + /// The host moved its window by (dx, dy) points under a still pointer. Keep the pointer and + /// a held press's origin in window points, so a drag that moves its own window still reports + /// pointer travel in `Drag::dx`/`dy`. + #[inline] + pub(crate) fn window_moved(&mut self, dx: f32, dy: f32) { + self.pointer.window_moved(dx, dy); + } + + pub(crate) fn cancel_pointer(&mut self) { + // differs from dev: a cancelled press cannot pair with a click after refocusing. + self.host.titlebar.clear(); + self.pointer.autoscroll_cancel(); + self.cancel_drag(); + self.drop_drag_out_request(); + self.edit.input_click.clear(); + self.drop_press(); + self.pointer.clear_secondary(); + self.pointer.clear_tint(); + self.pointer_leave(); + self.drag_files_leave(); + } + + /// End a held drag without a drop: its handler hears `Phase::Up` with [`Drag::cancelled`] + /// and the release that follows does nothing. A press selecting text lets go where the + /// selection stands, without a click. False when no drag is held. + pub(in crate::runtime) fn cancel_drag(&mut self) -> bool { + if self.cancel_drag_at(self.pointer.pos) { return true; } + if !self.edit.selectable.phase.dragging() || !self.pointer.press.is_held() || self.edit.input_click.captured() { return false; } + self.drop_press(); + true + } + + /// Lets go of the held press without a click: a cancel, a drag-out taking the pointer, a + /// modal opening. Every press that ends this way, and every release, ends the selection + /// drag it was making, and with it the list's edge scroll. Returns the press. + pub(in crate::runtime) fn drop_press(&mut self) -> Option<Box<capture::Held>> { + self.select_step(selectable::phase::Event::Release); + self.pointer.press.drop_held() + } + + /// [`Self::cancel_drag`], its last report at `point`, or where the press began. + fn cancel_drag_at(&mut self, point: Option<(f32, f32)>) -> bool { + if self.edit.input_click.captured() { return false; } + let Some(held) = self.pointer.press.held() else { return false }; + let Some(i) = self.live_index(&held.path) else { return false }; + if !self.drags_with(i, held.button) { return false; } + let at = held.at; + let (x, y) = point.unwrap_or(at); + let [lx, ly] = self.to_local(i, x, y); + let (dx, dy) = (x - at.0, y - at.1); + let screen = self.screen_at(x, y); + let Some(held) = self.drop_press() else { return false }; + let d = Drag { phase: Phase::Up, x: lx, y: ly, dx, dy, cancelled: true, window: [x, y], screen, ..held.drag }; + self.frame.queue.push(Action::Drag(held.path, d, held.button)); + self.pointer.end_press_repeat(); + true + } + + /// The button is up, so the held press can no longer start a drag-out; it stays a press. + #[cfg_attr(not(target_os = "macos"), allow(dead_code))] + #[inline] + pub(crate) fn disarm_drag_out(&mut self) { + self.pointer.disarm_drag_out(); + } + + /// The held press crossed the drag threshold on a `drag_out` element: ask the host for an + /// OS drag and hand it the pointer, so nothing stays pressed or hovered after the drop. + /// False when the element offers nothing this time and the press stays a press. + pub(in crate::runtime) fn start_drag_out(&mut self, app: &dyn ViewDriver, path: String) -> bool { + let Some(held) = self.pointer.press.held_mut() else { return false }; + held.drag_out = None; + let press = held.at; + let Some(i) = self.live_index(&path) else { return false }; + let Some(f) = self.tree.nodes[i].handlers.drag_out.clone() else { return false }; + let Some(item) = f(app.states_ref()).filter(|item| !item.is_empty()) else { return false }; + let n = &self.tree.nodes[i]; + let r = self.paint.drawn.get(i).copied().unwrap_or([n.target[0], n.target[1], n.target[2] - n.target[0], n.target[3] - n.target[1]]); + let clip = self.screen_clip_of_parent(n.parent).map(|v| v / self.env.scale); + let (x0, y0) = (r[0].max(clip[0]), r[1].max(clip[1])); + let rect = [x0, y0, ((r[0] + r[2]).min(clip[2]) - x0).max(0.0), ((r[1] + r[3]).min(clip[3]) - y0).max(0.0)]; + log_event!(self, "drag-out {path}"); + self.drop_drag_out_request(); + self.frame.queue.push(Action::DragStart(path.clone())); + self.pointer.drag_out_request = Some(crate::drag_out::DragOutStart { path, item, rect, bounds: r, press }); + self.drop_press(); + self.pointer_leave(); + true + } + + /// A request no host took (headless tools, a cancelled press) ends as `Cancelled`, queued + /// behind its start, so `on_drag_start` is always followed by `on_drag_end`. + pub(in crate::runtime) fn drop_drag_out_request(&mut self) { + if let Some(start) = self.pointer.drag_out_request.take() { + self.frame.queue.push(Action::DragEnd(start.path, crate::DragOutcome::Cancelled)); + } + } + + /// A release outside the window, or after the pointer left during the press, ends the hover. + pub(in crate::runtime) fn leave_after_release(&mut self, left: bool) { + if self.pointer_captured() { return; } + if left || self.pointer.pos.is_some_and(|(x, y)| !self.in_viewport(x, y)) { + self.pointer_leave(); + } + } + + pub(crate) fn pointer_down(&mut self, app: &mut dyn AppDriver, x: f32, y: f32) { + self.press_down(app, x, y, false); + } + + /// A primary press at (x, y); `touch`: a finger's, which never runs `on_press` on the way + /// down (`El::press_on_down` is a mouse's). + pub(in crate::runtime) fn press_down(&mut self, app: &mut dyn AppDriver, x: f32, y: f32, touch: bool) { + // A press ends a middle-click autoscroll, and does nothing else. + if self.pointer.autoscroll_press(crate::PointerButton::Primary) { self.pointer.pos = Some((x, y)); return; } + if self.pointer.press.held().is_some_and(|h| h.button != crate::PointerButton::Primary) { + self.pointer.pos = Some((x, y)); + return; + } + self.drop_drag_out_request(); + // A host that didn't act on the last press's request mustn't get it with this one. + self.host.titlebar.action = None; + self.pointer.pos = Some((x, y)); + // A press is the hand's: hover follows the pointer through moving layout. + self.release_hover_hold(); + self.kbd.focus.step(focus_machine::FocusEvent::Pointed); + self.dismiss_help(); + // A press cancels the waits to report an enter; the next move after it starts them again. + self.pointer.press_hover_delays(); + self.pointer.hover_paused = true; + let target = self.primary_target(x, y); + if target.and_then(|t| self.textbox_input(t)).is_none() { + self.edit.input_click.clear(); + } + if let Some(i) = self.active_modal() + && target.is_none_or(|t| !self.allowed(t)) + { + if self.tree.nodes[i].handlers.modal.as_ref().is_some_and(|m| m.outside) { + self.frame.queue.push(Action::Dismiss(self.tree.nodes[i].path.clone())); + } + return; + } + self.playground_pointer_down(app, x); + self.press_selection(target, x, y); + // Inside a draggable row, dragging drags the row; clicks still select words and lines. + if target.is_some_and(|t| self.tree.nodes[t].handlers.on_drag.is_some() || self.tree.nodes[t].handlers.drag_out.is_some()) { + self.select_step(selectable::phase::Event::Release); + } + let Some(ti) = target else { + let now = self.now_clock(); + self.host.titlebar.press_empty(now, x, y, self.double_click_interval); + if self.kbd.focus.path().is_some() { + self.frame.queue.push(Action::Blur); + } + return; + }; + let link = self.link_at(ti, x, y); + let on_link = link.is_some(); + // Any press breaks a pending pair unless it's the second press of it. + let pending = self.pointer.press.take_first(); + let now = self.now_clock(); + if self.bare_drag_region(ti) { + self.host.titlebar.press_region(now, x, y, self.double_click_interval); + if self.kbd.focus.path().is_some() { + self.frame.queue.push(Action::Blur); + } + return; + } + let n = &self.tree.nodes[ti]; + let clicks = self.pointer.press_click(&n.path, now, (x, y), self.double_click_interval); + let second = n.handlers.on_double_press.is_some() && pending.is_some_and(|first| { + first.path == n.path && press_run::follows(first.at, first.point, now, (x, y), self.double_click_interval) + }); + if let Some(ji) = self.textbox_input(ti) { + self.input_down(ji, x, y, now, second); + return; + } + // Clicking a link leaves focus where it is (a composer keeps typing). Selectable text + // off its links isn't a control: the press blurs, as a click on plain content does. + // Inside a control that owns its keyboard (`El::on_key`), a click on any part of it + // focuses it, as a click on a table view's row focuses the table. + // A `Cx::web_focus` control that keeps the field's focus on a press (`preserve_focus_on_press`) + // doesn't take it, as a button whose mousedown is prevented. + // So does a click on plain content in a focusable scroll region, as a web page focuses a + // `tabIndex` scroller (a `ScrollView`) clicked where nothing inside takes focus; and a + // press on a layer that hands focus below it (`El::press_focuses_below`) focuses the one + // under the pointer. + if n.focus.below && !on_link { + match self.scroll_region_below(ti, x, y) { + Some(r) => self.frame.queue.push(Action::FocusControl(self.tree.nodes[r].path.clone())), + None if self.kbd.focus.path().is_some() => self.frame.queue.push(Action::Blur), + None => {} + } + } + let takes_focus = n.focus.enabled || (self.takes_focus(n) && !self.press_keeps_focus(ti)); + let keyed = (!takes_focus && !self.is_selectable(ti)).then(|| std::iter::successors(n.parent, |&p| self.tree.nodes[p].parent) + .take_while(|&p| self.allowed(p)) + .find(|&p| (self.tree.nodes[p].focus.key.is_some() || self.focuses_on_click(p)) && self.can_focus(p))).flatten(); + let in_textbox = std::iter::successors(n.parent, |&p| self.tree.nodes[p].parent).any(|p| self.textbox_input(p).is_some()); + let (preserve_focus, keeps) = (self.press_keeps_focus(ti), self.press_keeps_selection(ti)); + let below = n.focus.below; + if !below && !on_link && !keeps && takes_focus && !self.is_selectable(ti) { + self.frame.queue.push(Action::FocusControl(n.path.clone())); + } else if !below && !on_link && !keeps && let Some(p) = keyed { + self.frame.queue.push(Action::FocusControl(self.tree.nodes[p].path.clone())); + } else if !below && !on_link && !in_textbox && !preserve_focus { + // Tab goes on from here, as from a browser's click on plain content. + if self.commit.defaults.web_focus { self.kbd.focus.step(focus_machine::FocusEvent::StartAt(n.path.clone())); } + if self.kbd.focus.path().is_some() { self.frame.queue.push(Action::Blur); } + } + let r = n.target; + let [lx, ly] = self.to_local(ti, x, y); + let d = Drag { + phase: Phase::Down, + x: lx, + y: ly, + w: r[2] - r[0], + h: r[3] - r[1], + start_x: lx, + start_y: ly, + dx: 0.0, + dy: 0.0, + data: 0.0, + clicks, + cancelled: false, + window: [x, y], + screen: self.screen_at(x, y), + }; + let path = n.path.clone(); + let drag_out = self.drags_out(n).then(|| n.handlers.drag_threshold.unwrap_or(crate::drag_out::DRAG_THRESHOLD)); + if n.handlers.on_drag.is_some() && drag_out.is_none() { + self.frame.queue.push(Action::Drag(path.clone(), d, crate::PointerButton::Primary)); + } + let on_down = !touch && n.handlers.press_on_down && n.handlers.on_press.is_some(); + if on_down { + self.frame.queue.push(Action::Press(path.clone(), crate::PointerButton::Primary, false)); + } + let mut held = capture::Held::new(path, d, crate::PointerButton::Primary, (x, y), now, second, drag_out).on_link(link).pressed_on_down(on_down); + held.touch = touch; + self.pointer.press.hold(held); + } + + pub(crate) fn pointer_up(&mut self, app: &dyn ViewDriver, x: f32, y: f32) { + if self.pointer.autoscroll_release(crate::PointerButton::Primary) { self.pointer.pos = Some((x, y)); return; } + #[cfg(target_os = "linux")] + self.primary_released(); + if self.pointer.press.held().is_some_and(|h| h.button != crate::PointerButton::Primary) { + self.pointer.pos = Some((x, y)); + return; + } + self.release_capture(app, x, y); + } + + /// The platform lost the release of a held press, so nothing was dropped: a held drag ends + /// cancelled at (x, y), and any other press is released there. + #[cfg_attr(not(target_os = "macos"), allow(dead_code))] + pub(crate) fn pointer_release_lost(&mut self, app: &dyn ViewDriver, x: f32, y: f32) { + let held = self.pointer.press.held().filter(|h| h.button == crate::PointerButton::Primary) + .map(|h| (h.left, h.moved || !press_run::within_slop(h.at, (x, y)))); + if let Some((left, moved)) = held && self.cancel_drag_at(Some((x, y))) { + // As a normal release: a press that dragged ends the run of clicks. + if moved { self.pointer.clear_press_clicks(); } + self.move_pointer(app, x, y, false); + self.leave_after_release(left); + } else { + self.pointer_up(app, x, y); + } + } + + /// What input has queued for handlers, emptied: each drag event, `None` for a press. + #[cfg(all(test, target_os = "macos"))] + pub(crate) fn take_queued_pointer(&mut self) -> Vec<Option<Drag>> { + let heard = self.frame.queue.iter().filter_map(|action| match action { + Action::Drag(_, drag, _) => Some(Some(*drag)), + Action::Press(..) => Some(None), + _ => None, + }).collect(); + self.frame.queue.retain(|_| false); + heard + } + + #[cfg(all(test, target_os = "macos"))] + #[inline] + pub(crate) fn end_click_run(&mut self) { + self.pointer.end_click_run(); + } + + pub(in crate::runtime) fn release_capture(&mut self, app: &dyn ViewDriver, x: f32, y: f32) { + // Hosts release at the last position they saw, which a leave doesn't move. + let left = self.pointer.press.held().is_some_and(|h| h.left); + self.release(app, x, y); + self.leave_after_release(left); + } + + pub(in crate::runtime) fn release(&mut self, app: &dyn ViewDriver, x: f32, y: f32) { + // A release never starts a drag-out: the system session needs the button held. + if let Some(held) = self.pointer.press.held_mut() { held.drag_out = None; } + let moved = self.pointer.pos != Some((x, y)); + self.move_pointer(app, x, y, moved); + // A drag that selected text is a selection, not a press. + let selected = self.selected_by_drag(); + self.select_step(selectable::phase::Event::Release); + let input_capture = self.edit.input_click.end_press(); + self.pointer.end_press_repeat(); + let now = self.now_clock(); + let interval = self.double_click_interval; + let Some(h) = self.pointer.press.held() else { return }; + // Only clicks pair: a press that dragged or was held past the interval is neither half. + let first = (!input_capture && !h.second && h.inside() && !h.moved && now - h.down_at <= interval + && h.button == crate::PointerButton::Primary + && self.live_index(&h.path).is_some_and(|i| self.tree.nodes[i].handlers.on_double_press.is_some())) + .then(|| capture::FirstClick { path: h.path.clone(), at: h.down_at, point: h.at }); + let Some(held) = self.pointer.press.release(first) else { return }; + let inside = held.inside(); + let capture::Held { path, drag: d, button, at, down_at, moved, second: double, link, pressed_on_down, .. } = *held; + self.refresh_hover_within(); + if moved { self.pointer.clear_press_clicks(); } + if input_capture { return; } + let Some(i) = self.live_index(&path) else { return }; + let n = &self.tree.nodes[i]; + // A button the element didn't opt in to is the middle button's click on a link or on + // `on_middle_press`: neither its `on_press` nor its `on_drag` hears it. + let opted = self.takes_button(i, button); + let (has_drag, has_press, has_double) = (self.drags_with(i, button), opted && n.handlers.on_press.is_some(), n.handlers.on_double_press.is_some()); + let middle_press = !opted && link.is_none() && n.handlers.on_middle_press.is_some(); + if has_drag { + let (dx, dy) = (x - at.0, y - at.1); + let [lx, ly] = self.to_local(i, x, y); + self.frame.queue.push(Action::Drag(path.clone(), Drag { phase: Phase::Up, x: lx, y: ly, dx, dy, window: [x, y], screen: self.screen_at(x, y), ..d }, button)); + } + if let Some(k) = link.filter(|_| inside) { self.link_up(&path, k, x, y, button); } + if has_press && inside && !selected && !pressed_on_down { + self.frame.queue.push(Action::Press(path.clone(), button, held.touch)); + } + if middle_press && inside { + self.frame.queue.push(Action::MiddlePress(path.clone())); + } + let click = !moved && now - down_at <= interval; + if has_double && inside && click && button == crate::PointerButton::Primary && double { + self.frame.queue.push(Action::DoublePress(path)); + } + } + + pub fn pointer_leave(&mut self) { + self.wheel_lost(); + if !self.pointer.captured() { + self.pointer.pos = None; + self.pointer.hovered = None; + self.refresh_hover_within(); + } else { + self.pointer.set_left(true); + } + } + + /// A press on an element is held (the hand drives whatever follows it). + #[inline] + pub fn pressing(&self) -> bool { + self.pointer.pressing() + } + #[inline] + pub fn pointer(&self) -> Option<(f32, f32)> { + self.pointer.pos() + } + + /// Native overlay regions from the most recent frame, in logical window points (x0,y0,x1,y1). + #[inline] + pub fn hit_regions(&self) -> &[[f32; 4]] { self.hit.overlay_hits() } + + /// The pointer shape the shell should show: the pressed element's while a gesture holds + /// the pointer, else the one under it in the current frame (the held hover while moving + /// layout holds it), from the nearest ancestor that sets one. The arrow while the pointer is outside the window. + pub fn cursor(&self) -> crate::el::Cursor { + let Some((x, y)) = self.pointer.pos.filter(|&(x, y)| self.in_viewport(x, y)) else { return crate::el::Cursor::Default }; + if let Some(pan) = self.autoscroll_cursor() { return pan; } + // An element on its way out has no cursor: `Cursor::Hidden` ends when it's removed. + // Selectable text shows its I-beam even where its presses go to a row around it. + let target = match self.pointer.press.path() { + Some(_) if self.edit.selectable.phase.dragging() => self.selection_holder(), + Some(p) => self.live_index(p).filter(|&i| self.allowed(i)), + // Moving layout holds hover: the cursor stays with what the pointer was over. + None => self.held_hover().flatten().or_else(|| self.selectable_at(x, y).or_else(|| self.primary_target(x, y))), + }; + let Some(mut i) = target else { + return crate::el::Cursor::Default; + }; + if self.tree.nodes[i].handlers.cursor.is_none() && (self.tree.nodes[i].input.is_some() || self.tree.nodes[i].role == "textbox") { + return crate::el::Cursor::Text; + } + if self.is_selectable(i) && !self.edit.selectable.phase.dragging() && self.link_at(i, x, y).is_some() { + return crate::el::Cursor::Pointer; + } + loop { + if let Some(c) = self.tree.nodes[i].handlers.cursor { + return c; + } + let Some(parent) = self.tree.nodes[i].parent else { return crate::el::Cursor::Default }; + i = parent; + } + } + + /// Whether node `i` is a live, reachable scroll viewport on the horizontal or vertical axis. + pub(in crate::runtime) fn is_scroll_viewport(&self, i: usize, horizontal: bool) -> bool { + let n = &self.tree.nodes[i]; + n.scroll.is_some() && n.scroll_axes.has(horizontal) && !self.subtree_exiting(i) && self.allowed(i) + } + + /// Walks up from `start` through ancestors to the first live, reachable scroll viewport on + /// `horizontal` whose scroll state satisfies `has_room`. + /// + /// An element that names the viewport it scrolls (`El::wheel_scrolls`, an overlay scroll bar's + /// track beside the viewport it follows) hands the wheel to that viewport first, then chains on + /// up from it as a wheel over the viewport itself does. One hand-off, so it can't loop. + fn scroll_in_chain(&self, mut at: Option<usize>, horizontal: bool, has_room: impl Fn(&ScrollState) -> bool) -> Option<NodeId> { + let mut handed = false; + while let Some(i) = at { + if self.is_scroll_viewport(i, horizontal) + && self.scroll.scrolls.get(&self.tree.nodes[i].id).is_some_and(&has_room) + { + return Some(self.tree.nodes[i].id); + } + let hand = (!handed).then(|| self.tree.nodes[i].wheel_scrolls.as_deref()).flatten() + .and_then(|key| self.wheel_scroll_viewport(i, key)).filter(|&j| j != i); + handed |= hand.is_some(); + at = hand.or_else(|| self.tree.nodes[i].parent); + } + None + } + + /// The element keyed `key` that a wheel over element `from` naming it (`El::wheel_scrolls`) + /// scrolls: `key` looked up inside `from` itself, then inside each of its ancestors, innermost + /// first, so a wheel over a bar finds the viewport beside it rather than the first element + /// keyed alike elsewhere (two panes, or every wide markdown table, can key their viewport + /// `scroll`). The first scope that holds one decides: a match on its way out or inert hands + /// the wheel nowhere rather than to another pane's. Named as `Tx::scroll_into_view` names one. + fn wheel_scroll_viewport(&self, from: usize, key: &str) -> Option<usize> { + let mut at = Some(from); + while let Some(a) = at { + let scope = &self.tree.nodes[a].path; + if let Some(i) = self.tree.nodes.iter().position(|n| n.named(key) && within(&n.path, scope)) { + return (!self.subtree_exiting(i) && self.allowed(i)).then_some(i); + } + at = self.tree.nodes[a].parent; + } + None + } + + /// The innermost vertical scroll viewport at (x, y). + pub(in crate::runtime) fn scroll_at(&self, x: f32, y: f32) -> Option<NodeId> { + self.scroll_at_axis(x, y, false) + } + + /// The innermost scroll viewport at (x, y) that moves on the horizontal axis or the vertical, + /// walking up from [`Self::chain_start`] so raised/anchored overlays occlude viewports beneath. + /// One whose content fits on that axis is passed over for the one around it, as Chromium + /// skips a scroller with nothing to scroll: a list of sections, each its own viewport as + /// tall as its rows, scrolls from over any row. + pub(in crate::runtime) fn scroll_at_axis(&self, x: f32, y: f32, horizontal: bool) -> Option<NodeId> { + self.scroll_at_axis_from(x, y, horizontal, crate::runtime::gesture_dispatch::WheelStart::Unknown) + } + + /// [`Self::scroll_at_axis`], with where its chain starts when the caller already found it. + pub(in crate::runtime) fn scroll_at_axis_from(&self, x: f32, y: f32, horizontal: bool, start: crate::runtime::gesture_dispatch::WheelStart) -> Option<NodeId> { + let at = match start { crate::runtime::gesture_dispatch::WheelStart::At(s) => s, crate::runtime::gesture_dispatch::WheelStart::Unknown => self.chain_start(x, y) }; + self.scroll_in_chain(at, horizontal, |st| if horizontal { st.x.max } else { st.max } > 0.0) + } + + /// The vertical viewport a delta `dy` at (x, y) starts a run on: from where a gesture there + /// starts (`Self::chain_start`: the topmost hit, or a scroll view inside it) up its ancestors, + /// the first that can still move that way, as Chromium chains a wheel's scroll. One at its end + /// passes the run to the one around it, so a short region inside a page never traps the wheel; + /// a viewport that only lies beneath (the timeline under an open menu, with or without a list + /// of its own, or under a raised panel) never takes it. A wheel's ease counts from where it heads. + pub(in crate::runtime) fn wheel_target(&self, x: f32, y: f32, dy: f32, start: crate::runtime::gesture_dispatch::WheelStart) -> Option<NodeId> { + let at = match start { crate::runtime::gesture_dispatch::WheelStart::At(s) => s, crate::runtime::gesture_dispatch::WheelStart::Unknown => self.chain_start(x, y) }; + self.scroll_in_chain(at, false, |st| { + let cur = st.mode.wheel().map_or(st.offset, |c| c.target()); + if dy > 0.0 { cur > 0.0 } else { cur < st.max } + }) + } + + /// Wheel or trackpad delta in points (positive `dy` moves content down, like a browser's + /// negative deltaY). Applied 1:1: the platform supplies its own momentum phases. A run of + /// deltas keeps to the viewport it began on (`WheelLock::vertical_run`), even at its end. + pub fn wheel(&mut self, x: f32, y: f32, dy: f32) { + self.wheel_from(x, y, dy, crate::runtime::gesture_dispatch::WheelStart::Unknown); + } + + /// [`Self::wheel`], with where its chain starts when the caller already found it. + pub(in crate::runtime) fn wheel_from(&mut self, x: f32, y: f32, dy: f32, start: crate::runtime::gesture_dispatch::WheelStart) { + self.release_hover_hold(); + self.drop_scroll_holds(); + self.dismiss_help(); + let now = self.now_clock(); + let Some((id, held)) = self.wheel_run(now, x, y, dy, start) else { return }; + let stick = self.tree.node_index.get(&id).and_then(|&i| self.tree.nodes[i].scroll).is_some_and(|s| s.stick_bottom); + let Some(st) = self.scroll.scrolls.get_mut(&id) else { return }; + let before = st.offset; + st.offset = (st.offset - f64::from(dy)).clamp(0.0, st.max); + st.moved(); + st.land(stick); + log_event!(self, "wheel {dy:.1}"); + let moved = st.offset != before; + if moved { self.pointer.scroll_cancels_press(&self.tree.nodes, id); } + self.scroll.ran_wheel_vertical(id, now, x, y, dy, moved, held); + } + + /// The vertical viewport a delta `dy` at (x, y) at `now` scrolls, and whether it continues the + /// run (`WheelLock::vertical_run`) rather than starting one (`Self::wheel_target`). None ends + /// the run. + fn wheel_run(&mut self, now: f64, x: f32, y: f32, dy: f32, start: crate::runtime::gesture_dispatch::WheelStart) -> Option<(NodeId, bool)> { + let held = self.scroll.wheel_vertical_run(now, x, y, dy).filter(|id| { + self.tree.node_index.get(id).is_some_and(|&i| self.is_scroll_viewport(i, false)) + }); + let picked = held.map(|id| (id, true)).or_else(|| self.wheel_target(x, y, dy, start).map(|id| (id, false))); + if picked.is_none() { self.scroll.end_wheel_vertical(); } + picked + } + + /// Whether whole notches of a mouse wheel ease rather than jump: the app hasn't turned it off + /// (`Runtime::set_wheel_glide`), and motion isn't reduced or settled. + #[inline] + pub(in crate::runtime) fn wheel_glides(&self) -> bool { self.scroll.wheel_glides(self.reduced_motion, self.settled) } + + /// Whole notches of a mouse wheel, `dy` points (positive moves content down): the offset + /// eases to where they send it as Chromium's does (`runtime/scroll/wheel.rs`), a notch that + /// comes while it moves sending it on from where it is. A run of notches keeps to the viewport + /// it began on, as `Self::wheel`'s deltas do. With reduced motion, it jumps. + pub(in crate::runtime) fn wheel_notch(&mut self, x: f32, y: f32, dy: f32, start: crate::runtime::gesture_dispatch::WheelStart) { + if !self.wheel_glides() { + self.wheel_from(x, y, dy, start); + return; + } + self.release_hover_hold(); + self.drop_scroll_holds(); + self.dismiss_help(); + let now = self.now_clock(); + let Some((id, held)) = self.wheel_run(now, x, y, dy, start) else { return }; + // The ease's time follows the distance in device pixels, as Chromium measures it. + let scale = f64::from(self.env.scale * self.zoom()); + let stick = self.tree.node_index.get(&id).and_then(|&i| self.tree.nodes[i].scroll).is_some_and(|s| s.stick_bottom); + let Some(st) = self.scroll.scrolls.get_mut(&id) else { return }; + let easing = st.mode.wheel().is_some(); + let mut curve = st.mode.wheel().unwrap_or_else(|| scroll_wheel::WheelCurve::still(st.offset)); + curve.follow(st.offset); + let to = (curve.target() - f64::from(dy)).clamp(0.0, st.max); + let moved = curve.retarget(to, scale); + curve.aimed_at_end(to >= st.max); + if moved { + st.mode = st.mode.to_wheel(curve); + st.moved(); + log_event!(self, "wheel-notch {dy:.1}"); + self.pointer.scroll_cancels_press(&self.tree.nodes, id); + } else if easing { + // Sent back to where it is (a flick back before the next frame): it stays put, as + // Chromium's does, rather than finishing the ease the notch before started. + st.land(stick); + } + self.scroll.ran_wheel_vertical(id, now, x, y, dy, moved, held); + } + + /// Releases a scroll with `velocity` (points per second, positive moves content down); + /// the runtime decays it (for platforms without OS momentum and headless scripts). + pub fn fling(&mut self, x: f32, y: f32, velocity: f32) { + self.release_hover_hold(); + self.drop_scroll_holds(); + self.dismiss_help(); + let Some(id) = self.scroll_at(x, y) else { return }; + if let Some(st) = self.scroll.scrolls.get_mut(&id) { + st.mode = st.mode.to_momentum(-velocity); + log_event!(self, "fling {velocity:.0}"); + if velocity != 0.0 { self.pointer.scroll_cancels_press(&self.tree.nodes, id); } + } + } + + pub fn has_pending_input(&self) -> bool { + !self.frame.queue.is_empty() + } +} + +/// Whether `path` is the element at `scope` or one inside it, by the paths' own segments (so +/// `area/list` isn't inside `area/listx`). +fn within(path: &str, scope: &str) -> bool { + path.strip_prefix(scope).is_some_and(|rest| rest.is_empty() || rest.starts_with('/')) +} diff --git a/app/vendor/rune/crates/rune/src/runtime/input/popup.rs b/app/vendor/rune/crates/rune/src/runtime/input/popup.rs new file mode 100644 index 0000000..c898cd6 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/input/popup.rs @@ -0,0 +1,176 @@ +use super::*; +use crate::popup_menu::{PopupAnchor, PopupMenu, PopupMenuError, Request, Show}; +use std::collections::VecDeque; + +/// The pop-up menus asked for (`Tx::popup_menu`) and not yet answered, oldest first. Menus show +/// one at a time, so only the first can be open, and an open one is always the first. +pub(crate) enum Popups { + /// None is open: the first, if any, waits for the host to open it. + Queued(VecDeque<Request>), + /// `open` is showing (or couldn't, and waits for its `None`); `next` wait behind it. + Showing { open: Request, next: VecDeque<Request> }, +} + +impl Default for Popups { + fn default() -> Self { Popups::Queued(VecDeque::new()) } +} + +impl Popups { + pub(crate) fn front(&self) -> Option<&Request> { + match self { + Popups::Queued(queue) => queue.front(), + Popups::Showing { open, .. } => Some(open), + } + } + pub(crate) fn push_back(&mut self, request: Request) { + match self { + Popups::Queued(queue) | Popups::Showing { next: queue, .. } => queue.push_back(request), + } + } + pub(crate) fn extend(&mut self, requests: impl IntoIterator<Item = Request>) { + for r in requests { self.push_back(r); } + } + pub(crate) fn len(&self) -> usize { + match self { + Popups::Queued(queue) => queue.len(), + Popups::Showing { next, .. } => next.len() + 1, + } + } + pub(crate) fn is_empty(&self) -> bool { self.len() == 0 } + /// The first is showing. + pub(crate) fn is_open(&self) -> bool { matches!(self, Popups::Showing { .. }) } + + /// The host opens the first: it shows from now until it's answered. + fn open_first(&mut self) -> Option<&Request> { + if let Popups::Queued(queue) = self { + let open = queue.pop_front()?; + *self = Popups::Showing { open, next: std::mem::take(queue) }; + } + self.front() + } + + /// The first is answered: it leaves, and the next waits for the host to open it. + fn answer_first(&mut self) -> Option<Request> { + match std::mem::take(self) { + Popups::Queued(mut queue) => { + let first = queue.pop_front(); + *self = Popups::Queued(queue); + first + } + Popups::Showing { open, next } => { + *self = Popups::Queued(next); + Some(open) + } + } + } +} + +impl RuntimeCore { + /// The pop-up menu showing, or the next to show, from [`Tx::popup_menu`]. + pub(crate) fn popup_menu(&self) -> Option<&PopupMenu> { self.host.popups.front().map(|r| &r.menu) } + + /// Answers the pop-up menu showing (or next to show) as if the user picked `picked`, or + /// dismissed it with `None`. Its callback runs now and the next frame commits it, as for + /// [`Runtime::update`]. For tests and headless drivers; native menus answer themselves. + pub(crate) fn resolve_popup(&mut self, app: &mut dyn AppDriver, picked: Option<&str>) -> Result<(), PopupMenuError> { + let request = self.host.popups.front().ok_or(PopupMenuError::NotOpen)?; + if let Some(id) = picked { + let item = request.menu.find(id).ok_or_else(|| PopupMenuError::UnknownItem(id.into()))?; + if !item.enabled { return Err(PopupMenuError::Disabled(id.into())); } + } + let Some(request) = self.host.popups.answer_first() else { return Err(PopupMenuError::NotOpen) }; + match picked { + Some(id) => self.trace_event(format_args!("popup-menu:pick:{id}")), + None => self.trace_event("popup-menu:cancel"), + } + let mut one = self.transaction(app); + if let (Some(field), Some(id)) = (request.field, picked) { + self.field_menu_pick(app, *field, id, &mut one); + } + (request.on_pick)(app.states(), picked, &mut one); + self.latch_requests(app, &mut one); + merge(&mut self.frame.pending, one); + self.commit.dirty = true; + Ok(()) + } + + /// The next menu for the shell to open, marked open. `Some(None)` is a request that can't + /// open (its anchor element is gone, or its ids repeat): answer it with `None`. Nothing while + /// a menu is open, so menus show one at a time. + pub(crate) fn take_popup(&mut self) -> Option<Option<Show>> { + if self.host.popups.is_open() { return None; } + let rect = match &self.host.popups.front()?.anchor { + PopupAnchor::Key(key) => self.anchor_rect(key).ok_or_else(|| format!("no element keyed {key:?} to anchor to")), + &PopupAnchor::Point(x, y) => Ok([x, y, 0.0, 0.0]), + }; + // The host places it in window points: the view's times its zoom. + let rect = rect.map(|r| self.to_window(r)); + let request = self.host.popups.open_first()?; + match request.validate().and(rect) { + Ok(rect) => { + let show = Show::new(request.menu.clone(), &request.anchor, rect); + self.trace_event("popup-menu:open"); + // Asked for outside a frame (an update): the next frame drops the hover. + if self.release_pointer_for_popup() { self.commit.dirty = true; } + Some(Some(show)) + } + Err(problem) => { + eprintln!("rune: pop-up menu: {problem}"); + Some(None) + } + } + } + + /// The next menu anchors to an element and the runtime has changes the next frame commits + /// (a pick that asked for another menu over what it mounted): open it after that frame. + pub(crate) fn popup_waits_for_layout(&self) -> bool { + !self.host.popups.is_open() && (self.commit.dirty || self.commit.relayout) + && self.host.popups.front().is_some_and(|r| matches!(r.anchor, PopupAnchor::Key(_))) + } + + /// A menu is about to take the mouse: press, capture and hover end now, as if the pointer + /// left, rather than when it next moves. True when that changed anything. + pub(crate) fn release_pointer_for_popup(&mut self) -> bool { + if self.host.popups.is_empty() || (self.pointer.pos.is_none() && !self.pointer_captured()) { + return false; + } + self.cancel_pointer(); + true + } + + /// Answers every waiting menu with `None`, as its window goes away. A callback that asks + /// for another menu is answered too, up to a bound against one that always asks again. + pub(crate) fn cancel_popups(&mut self, app: &mut dyn AppDriver) { + for _ in 0..64 { + if self.resolve_popup(app, None).is_err() { return; } + } + eprintln!("rune: pop-up menu callbacks kept asking for menus while their window went away; dropping {}", self.host.popups.len()); + self.host.popups = Popups::default(); + } + + /// A headless run's stand-in for the window's menu: the next menu opens and waits for + /// [`Runtime::resolve_popup`], and one that can't open answers `None` now. + pub(crate) fn open_popup_headless(&mut self, app: &mut dyn AppDriver) { + while let Some(None) = self.take_popup() { + self.resolve_popup(app, None).ok(); + } + } + + /// Drawn rect of the element a menu anchors to, matched as [`Runtime::find`] matches. + fn anchor_rect(&self, key: &str) -> Option<[f32; 4]> { + let i = self.live_named(None, key)?; + self.paint.drawn.get(i).copied().filter(|r| r[2] > 0.0 || r[3] > 0.0) + } + + pub(crate) fn popup_json(&self) -> Option<serde_json::Value> { + let request = self.host.popups.front()?; + let mut v = request.menu.to_json(); + v["open"] = self.host.popups.is_open().into(); + v["anchor"] = match &request.anchor { + PopupAnchor::Key(key) => serde_json::json!({ "key": key }), + PopupAnchor::Point(x, y) => serde_json::json!({ "x": x, "y": y }), + }; + v["queued"] = (self.host.popups.len() - 1).into(); + Some(v) + } +} diff --git a/app/vendor/rune/crates/rune/src/runtime/input/press_repeat.rs b/app/vendor/rune/crates/rune/src/runtime/input/press_repeat.rs new file mode 100644 index 0000000..090e1f2 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/input/press_repeat.rs @@ -0,0 +1,155 @@ +//! A held press whose drag handler asked to hear it again ([`Tx::drag_repeat_after`]): a frame +//! at or after the delay sends the handler the pointer as a `Phase::Move` its `Tx` marks +//! as the repeat. +use crate::machine::{Attempt, Effects, Seq}; + +use super::*; + +/// The held press's repeat: armed for an element at a clock time, as one attempt, so a wake an +/// earlier arm asked for changes nothing. +#[derive(Debug, Default)] +pub(in crate::runtime) struct PressRepeat { + seq: Seq, + state: Repeat, +} + +/// Where the repeat stands. +#[derive(Clone, Debug, Default, PartialEq)] +enum Repeat { + /// No repeat waits. + #[default] + Idle, + /// `path`'s drag hears the pointer again at `due` (clock seconds), as attempt `attempt`. + Armed { attempt: Attempt, path: String, due: f64 }, +} + +impl Repeat { + fn attempt(&self) -> Option<Attempt> { + match self { + Repeat::Armed { attempt, .. } => Some(*attempt), + Repeat::Idle => None, + } + } +} + +pub(in crate::runtime) enum Event<'a> { + /// `path`'s drag handler asked for a repeat due at this clock time. + Arm { path: &'a str, due: f64 }, + /// The release or a cancel ends the repeat. + End, + /// A frame at `now`, carrying the `attempt` its wake was asked for: the repeat fires only + /// if that is still the armed one. + Due { attempt: Attempt, now: f64 }, +} + +#[derive(Debug, PartialEq)] +pub(in crate::runtime) enum Effect { + /// `path`'s drag hears the pointer again. + Fire(String), + /// Wake at this clock time, when the repeat is due. + WakeAt(f64), +} + +pub(in crate::runtime) fn step(seq: &mut Seq, state: &mut Repeat, event: Event) -> Effects<Effect> { + match event { + Event::Arm { path, due } => { + let attempt = seq.next(); + *state = Repeat::Armed { attempt, path: path.to_owned(), due }; + Effects::one(Effect::WakeAt(due)) + } + Event::End => { + *state = Repeat::Idle; + Effects::none() + } + Event::Due { attempt, now } => match state { + Repeat::Armed { attempt: armed, path, due } if *armed == attempt && *due <= now + 1e-6 => { + let path = std::mem::take(path); + *state = Repeat::Idle; + Effects::one(Effect::Fire(path)) + } + _ => Effects::none(), + }, + } +} + +impl PressRepeat { + fn step(&mut self, event: Event) -> Effects<Effect> { + step(&mut self.seq, &mut self.state, event) + } + + /// The attempt a frame's wake for the repeat would carry, while one is armed. + fn attempt(&self) -> Option<Attempt> { self.state.attempt() } + + /// A repeat waits past `now`. + fn waiting(&self, now: f64) -> bool { + matches!(self.state, Repeat::Armed { due, .. } if now + 1e-6 < due) + } +} + +impl capture::PointerState { + /// Arms a drag repeat for `path` at `due`, while `path` holds the press; returns the wake time. + #[inline] + pub(in crate::runtime) fn arm_press_repeat(&mut self, path: &str, due: f64) -> Option<f64> { + if self.press.path() != Some(path) { return None; } + self.press_repeat.step(Event::Arm { path, due }).into_iter().find_map(|e| match e { + Effect::WakeAt(due) => Some(due), + Effect::Fire(_) => None, + }) + } + + /// The release or a cancel ends the repeat. + #[inline] + pub(in crate::runtime) fn end_press_repeat(&mut self) { + let _ = self.press_repeat.step(Event::End); + } + + #[inline] + pub(in crate::runtime) fn press_repeat_waiting(&self, now: f64) -> bool { + self.press_repeat.waiting(now) + } + + /// Consumes and returns the path of any press repeat due by `now`. + pub(super) fn take_due_press_repeat(&mut self, now: f64) -> Option<String> { + let attempt = self.press_repeat.attempt()?; + self.press_repeat.step(Event::Due { attempt, now }).into_iter().find_map(|e| match e { + Effect::Fire(path) => Some(path), + Effect::WakeAt(_) => None, + }) + } +} + +impl RuntimeCore { + /// After `path`'s drag handler asked for a repeat `after` from now: due then, while the + /// press it heard is still held. + pub(in crate::runtime) fn arm_press_repeat(&mut self, path: &str, after: std::time::Duration) { + let due = self.clock + after.as_secs_f64(); + if let Some(due) = self.pointer.arm_press_repeat(path, due) { + self.schedule_wakes_from(due, [std::time::Duration::ZERO]); + } + } + + #[inline] + pub(in crate::runtime) fn press_repeat_waiting(&self) -> bool { self.pointer.press_repeat_waiting(self.clock) } + + /// Sends the repeat due by this frame to the drag still holding its press. + pub(in crate::runtime) fn fire_press_repeat(&mut self) { + if let Some(path) = self.pointer.take_due_press_repeat(self.clock) { + self.send_press_repeat(&path); + } + } + + /// `path`'s drag, if it still holds the press, hears the pointer again. + fn send_press_repeat(&mut self, path: &str) { + let Some(held) = self.pointer.press.held().filter(|h| h.path == path) else { return }; + let (d, at, button) = (held.drag, held.at, held.button); + let Some(i) = self.live_index(path) else { return }; + let (x, y) = self.pointer.pos.unwrap_or(at); + let [lx, ly] = self.to_local(i, x, y); + let (dx, dy) = (x - at.0, y - at.1); + self.frame.queue.push(Action::DragRepeat(path.to_owned(), Drag { phase: Phase::Move, x: lx, y: ly, dx, dy, window: [x, y], screen: self.screen_at(x, y), ..d }, button)); + } +} + +#[cfg(test)] +#[path = "press_repeat_tests.rs"] +mod tests; diff --git a/app/vendor/rune/crates/rune/src/runtime/input/press_repeat_tests.rs b/app/vendor/rune/crates/rune/src/runtime/input/press_repeat_tests.rs new file mode 100644 index 0000000..686cda9 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/input/press_repeat_tests.rs @@ -0,0 +1,67 @@ +use super::*; + +fn armed(seq: &mut Seq, path: &str, due: f64) -> (Repeat, Vec<Effect>) { + let mut state = Repeat::default(); + let effects = step(seq, &mut state, Event::Arm { path, due }).into_iter().collect(); + (state, effects) +} + +#[test] +fn an_arm_keeps_its_attempt_and_wakes_at_its_due_time() { + let mut seq = Seq::default(); + let (state, effects) = armed(&mut seq, "row", 1.5); + let Repeat::Armed { attempt, path, due } = state.clone() else { panic!("{state:?}") }; + assert_eq!((path.as_str(), due), ("row", 1.5)); + assert_eq!(effects, vec![Effect::WakeAt(1.5)]); + assert_eq!(state.attempt(), Some(attempt)); +} + +#[test] +fn a_due_fires_once_at_or_after_its_time() { + let mut seq = Seq::default(); + let (mut state, _) = armed(&mut seq, "row", 1.5); + let attempt = state.attempt().unwrap(); + let early = step(&mut seq, &mut state, Event::Due { attempt, now: 1.0 }); + assert!(early.is_empty(), "before its time"); + assert_eq!(state.attempt(), Some(attempt), "still armed"); + let fired: Vec<Effect> = step(&mut seq, &mut state, Event::Due { attempt, now: 1.5 }).into_iter().collect(); + assert_eq!(fired, vec![Effect::Fire("row".to_owned())]); + assert_eq!(state, Repeat::Idle); + let again = step(&mut seq, &mut state, Event::Due { attempt, now: 9.0 }); + assert!(again.is_empty(), "a spent repeat fires nothing"); +} + +#[test] +fn a_wake_for_an_earlier_arm_changes_nothing() { + let mut seq = Seq::default(); + let (mut state, _) = armed(&mut seq, "row", 1.5); + let first = state.attempt().unwrap(); + // The release and a second arm inside one frame replace the first, with a later due. + step(&mut seq, &mut state, Event::End); + let (state2, _) = armed(&mut seq, "row", 5.0); + state = state2; + let stale = step(&mut seq, &mut state, Event::Due { attempt: first, now: 9.0 }); + assert!(stale.is_empty(), "an earlier arm's wake fires nothing"); + assert!(state.attempt().is_some(), "the later arm still waits"); +} + +#[test] +fn a_release_ends_the_repeat() { + let mut seq = Seq::default(); + let (mut state, _) = armed(&mut seq, "row", 1.5); + let attempt = state.attempt().unwrap(); + step(&mut seq, &mut state, Event::End); + assert_eq!(state, Repeat::Idle); + assert!(step(&mut seq, &mut state, Event::Due { attempt, now: 2.0 }).is_empty()); +} + +#[test] +fn an_arm_for_another_element_is_the_new_one() { + let mut seq = Seq::default(); + let (mut state, _) = armed(&mut seq, "row", 1.5); + let first = state.attempt().unwrap(); + step(&mut seq, &mut state, Event::Arm { path: "cell", due: 2.0 }); + let second = state.attempt().unwrap(); + assert_ne!(first, second, "a new arm is a new attempt"); + assert_eq!(state, Repeat::Armed { attempt: second, path: "cell".to_owned(), due: 2.0 }); +} diff --git a/app/vendor/rune/crates/rune/src/runtime/input/press_run.rs b/app/vendor/rune/crates/rune/src/runtime/input/press_run.rs new file mode 100644 index 0000000..9b5bdba --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/input/press_run.rs @@ -0,0 +1,58 @@ +//! Counting a run of presses, as AppKit's `clickCount` does: one rule for an element's +//! [`Drag::clicks`], a text field's and selectable text's word and line clicks, the titlebar's +//! double click and the first click an `on_double_press` pairs with. +use super::*; + +/// `b` is within the click slop of `a` on each axis. +pub(in crate::runtime) fn within_slop(a: (f32, f32), b: (f32, f32)) -> bool { + (b.0 - a.0).abs() <= CLICK_SLOP && (b.1 - a.1).abs() <= CLICK_SLOP +} + +/// A press at `point` at `now` (clock seconds) carries on a run whose last press went down at +/// `then` at `was`: within `interval` of it and within the click slop. +pub(in crate::runtime) fn follows(then: f64, was: (f32, f32), now: f64, point: (f32, f32), interval: f64) -> bool { + now - then <= interval && within_slop(was, point) +} + +/// The run's last press: its element, time (clock seconds), window point and count. +struct Last { + path: String, + at: f64, + point: (f32, f32), + count: u32, +} + +#[derive(Default)] +pub(in crate::runtime) struct PressRun { + last: Option<Last>, +} + +impl PressRun { + /// Counts a press on `path` at `now`: one more than the last press when that was on the same + /// element and the press [`follows`] it, else 1. + pub(in crate::runtime) fn press(&mut self, path: &str, now: f64, point: (f32, f32), interval: f64) -> u32 { + match &mut self.last { + Some(last) if last.path == path && follows(last.at, last.point, now, point, interval) => { + (last.at, last.point) = (now, point); + last.count += 1; + last.count + } + _ => { + self.last = Some(Last { path: path.to_owned(), at: now, point, count: 1 }); + 1 + } + } + } + + /// A press that dragged, another button's press, a press elsewhere or a reset ends the run. + pub(in crate::runtime) fn clear(&mut self) { self.last = None; } + + /// Ends the run unless its last press was on `path`. + pub(in crate::runtime) fn keep_on(&mut self, path: Option<&str>) { + if self.last.as_ref().is_some_and(|l| Some(l.path.as_str()) != path) { self.last = None; } + } +} + +#[cfg(test)] +#[path = "press_run_tests.rs"] +mod tests; diff --git a/app/vendor/rune/crates/rune/src/runtime/input/press_run_tests.rs b/app/vendor/rune/crates/rune/src/runtime/input/press_run_tests.rs new file mode 100644 index 0000000..fd34f76 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/input/press_run_tests.rs @@ -0,0 +1,30 @@ +use super::*; + +#[test] +fn presses_on_one_element_close_in_time_and_place_count_up() { + let mut run = PressRun::default(); + assert_eq!(run.press("a", 0.0, (10.0, 10.0), 0.5), 1); + assert_eq!(run.press("a", 0.3, (12.0, 9.0), 0.5), 2); + assert_eq!(run.press("a", 0.6, (13.0, 9.0), 0.5), 3, "the interval runs from the last press, not the first"); +} + +#[test] +fn another_element_a_late_press_or_a_far_one_starts_again() { + let mut run = PressRun::default(); + run.press("a", 0.0, (10.0, 10.0), 0.5); + assert_eq!(run.press("b", 0.1, (10.0, 10.0), 0.5), 1); + assert_eq!(run.press("b", 0.7, (10.0, 10.0), 0.5), 1); + assert_eq!(run.press("b", 0.8, (10.0 + CLICK_SLOP + 1.0, 10.0), 0.5), 1); +} + +#[test] +fn clearing_or_moving_away_ends_the_run() { + let mut run = PressRun::default(); + run.press("a", 0.0, (0.0, 0.0), 0.5); + run.keep_on(Some("a")); + assert_eq!(run.press("a", 0.1, (0.0, 0.0), 0.5), 2); + run.keep_on(Some("b")); + assert_eq!(run.press("a", 0.2, (0.0, 0.0), 0.5), 1); + run.clear(); + assert_eq!(run.press("a", 0.3, (0.0, 0.0), 0.5), 1); +} diff --git a/app/vendor/rune/crates/rune/src/runtime/input/primary_selection.rs b/app/vendor/rune/crates/rune/src/runtime/input/primary_selection.rs new file mode 100644 index 0000000..fdf2047 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/input/primary_selection.rs @@ -0,0 +1,57 @@ +//! Linux's primary selection, as Chromium keeps it on X11 and Wayland: the text a pointer +//! selects (a drag, a double or triple click, Shift+click), in selectable text or a text field, +//! goes on the primary selection when the button comes up; a middle click in a text field puts +//! the caret where it landed and pastes the primary selection there. A secure field's text +//! never goes on it. The clipboard's worker beside it writes and reads it +//! (`clipboard/primary.rs`), so Cmd/Ctrl+C and Cmd/Ctrl+V never see it. +use std::hash::BuildHasher; + +use super::*; + +/// What the runtime asks of the primary selection, for the clipboard's flush to take. +#[derive(Default)] +pub(crate) struct PrimarySelection { + /// A primary button came up: after this frame's handlers, what's selected goes on it. + pending: bool, + /// A hash of the text last put on it, so a click that leaves the selection as it was + /// writes nothing. + written: Option<u64>, + /// Text to put on it. + pub(crate) write: Option<String>, + /// The text field a middle click pastes it into. + pub(crate) paste: Option<String>, +} + +impl RuntimeCore { + /// The primary button came up. + pub(in crate::runtime) fn primary_released(&mut self) { + self.edit.primary.pending = true; + } + + /// After a frame's handlers, once the release's caret and selection landed: puts what's + /// selected on the primary selection, if it changed. + pub(in crate::runtime) fn note_primary_selection(&mut self, app: &dyn ViewDriver) { + if !std::mem::take(&mut self.edit.primary.pending) { return; } + let text = match self.focused_input() { + Some(input) if input.edit.is_secure() => None, + Some(input) => Some(input.edit.selected().to_owned()).filter(|t| !t.is_empty()), + None => self.selected_text(app), + }; + let Some(text) = text else { return }; + let hash = std::hash::BuildHasherDefault::<std::hash::DefaultHasher>::default().hash_one(&text); + if self.edit.primary.written == Some(hash) { return; } + self.edit.primary.written = Some(hash); + self.edit.primary.write = Some(text); + } + + /// A middle press at (x, y): on a text field that takes text, it focuses the field with its + /// caret there and asks for the primary selection to paste. True when it did. + pub(in crate::runtime) fn primary_paste_down(&mut self, x: f32, y: f32) -> bool { + let Some(i) = self.primary_target(x, y).filter(|&i| self.allowed(i) && !self.subtree_exiting(i)) else { return false }; + let takes = self.tree.nodes[i].input.as_ref().is_some_and(|input| input.access.is_some() && !input.edit.is_secure()); + if !takes { return false; } + self.place_caret(i, x, y); + self.edit.primary.paste = Some(self.tree.nodes[i].path.clone()); + true + } +} diff --git a/app/vendor/rune/crates/rune/src/runtime/input/secondary.rs b/app/vendor/rune/crates/rune/src/runtime/input/secondary.rs new file mode 100644 index 0000000..f1b2958 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/input/secondary.rs @@ -0,0 +1,176 @@ +//! The secondary gesture (right-click, macOS control-click, the Menu key and Shift+F10): +//! which element's menu it opens. +use super::*; + +impl capture::PointerState { + /// The secondary press went to the browser's own menu: its release opens none of Rune's. + #[cfg_attr(not(target_arch = "wasm32"), allow(dead_code))] + #[inline] + pub(in crate::runtime) fn abandon_secondary(&mut self) { + self.clear_secondary(); + } +} + +impl RuntimeCore { + /// The nearest element with `on_secondary_press` (or a link with `on_link_secondary`) at + /// (x, y), else the selectable text there (its Copy menu): an app's context menu on a row + /// wins over its text's. + pub(in crate::runtime) fn secondary_target(&self, x: f32, y: f32) -> Option<&str> { + let id = self.hit.top_hit(|id, r| self.hit_contains(id, r, x, y))?; + let mut index = *self.tree.node_index.get(&id)?; + let mut text = None; + loop { + let n = &self.tree.nodes[index]; + if self.subtree_exiting(index) || !self.allowed(index) { break; } + if n.handlers.on_secondary_press.is_some() || self.secondary_link_at(index, x, y).is_some() { return Some(&n.path); } + // A text field's own menu (`field_menu`) wins over its ancestors'. + if n.input.as_ref().is_some_and(|i| i.access.is_some()) { return Some(&n.path); } + if text.is_none() && self.is_selectable(index) { text = Some(n.path.as_str()); } + let Some(p) = n.parent else { break }; + index = p; + } + text + } + + /// Capture a secondary gesture without activating primary actions or text selection. + pub fn secondary_down(&mut self, x: f32, y: f32) { + self.pointer.pos = Some((x, y)); + if self.pointer.autoscroll_press(crate::PointerButton::Secondary) { return; } + self.tint_down(x, y, crate::PointerButton::Secondary); + self.release_hover_hold(); + self.kbd.focus.step(focus_machine::FocusEvent::Pointed); + self.dismiss_help(); + let path = self.secondary_target(x, y).map(str::to_owned); + let i = path.as_ref().and_then(|p| self.tree.nodes.iter().position(|n| n.path == *p)); + self.pointer.set_secondary(match path { + Some(path) => capture::Secondary::Held { path, link: i.and_then(|i| self.secondary_link_at(i, x, y)), left: false }, + None => capture::Secondary::Up, + }); + self.secondary_region_down(x, y, self.pointer.secondary_held()); + // Under `Cx::web_focus` a right-click focuses the control it's on, as Chromium's + // mousedown does, so focus is back on it when its menu closes. + if self.commit.defaults.web_focus + && let Some(c) = i.and_then(|i| std::iter::successors(Some(i), |&j| self.tree.nodes[j].parent).find(|&j| self.can_focus(j))) + && self.tree.nodes[c].input.is_none() + { + self.frame.queue.push(Action::FocusControl(self.tree.nodes[c].path.clone())); + } + } + + /// A middle or secondary press at (x, y), with no primary press held: what a primary press + /// there would take shows pressed until the button comes up (`capture::Tint`). + pub(in crate::runtime) fn tint_down(&mut self, x: f32, y: f32, button: crate::PointerButton) { + if self.pointer.press.held().is_some_and(|h| h.button == crate::PointerButton::Primary) { return; } + let path = self.primary_target(x, y).filter(|&i| self.allowed(i) && !self.subtree_exiting(i)).map(|i| self.tree.nodes[i].path.clone()); + self.pointer.set_tint(path.map_or(capture::Tint::Up, |path| capture::Tint::Held { path, button })); + } + + /// What the secondary press being held is on, for a browser that shows its own context + /// menu: `"app"` when an element's menu or a link's takes it (Rune draws that), `"field"` on + /// a text field, `"text"` on selectable text alone, `""` on nothing of Rune's. + #[cfg_attr(not(target_arch = "wasm32"), allow(dead_code))] + pub(crate) fn secondary_claim(&self) -> &'static str { + let capture::Secondary::Held { path, link, .. } = self.pointer.secondary() else { return "" }; + let Some(n) = self.tree.nodes.iter().find(|n| n.path == *path) else { return "" }; + if link.is_some() || n.handlers.on_secondary_press.is_some() { return "app"; } + // On a misspelled word or a pill with a secondary handler, Rune's own menu wins over the browser's. + if let Some(input) = n.input.as_deref() + && input.access.is_some() + { + let on_pill = input.on_pill_secondary.is_some() + && self.pointer.pos.and_then(|(x, y)| self.live(path).and_then(|i| self.input_pill_at(i, x, y))).is_some(); + return if on_pill || self.on_misspelled_word(path) { "app" } else { "field" }; + } + "text" + } + + /// The pointer is over a word field `path`'s spell checker marks. + #[cfg_attr(not(target_arch = "wasm32"), allow(dead_code))] + fn on_misspelled_word(&self, path: &str) -> bool { + let Some(i) = self.live(path) else { return false }; + let n = &self.tree.nodes[i]; + let (Some(input), Some((x, y)), Some(layout)) = (n.input.as_deref(), self.pointer.pos, n.text_layout.as_ref()) else { return false }; + if !input.spellcheck || input.edit.is_secure() { return false; } + let Some([tx, ty]) = self.input_text_point(i, x, y) else { return false }; + let caret = super::input_click::hit(&input.edit, layout.view(), tx, ty, self.env.scale, input.single_line).caret; + crate::spell::misspelled_at(&input.edit.text, caret).is_some() + } + + /// The secondary press went to the browser's own menu: its release opens none of Rune's. + #[cfg_attr(not(target_arch = "wasm32"), allow(dead_code))] + #[inline] + pub(crate) fn secondary_abandon(&mut self) { + self.pointer.abandon_secondary(); + } + + pub(crate) fn secondary_up(&mut self, app: &dyn ViewDriver, x: f32, y: f32) { + self.pointer.pos = Some((x, y)); + self.pointer.release_tint(crate::PointerButton::Secondary); + if self.pointer.autoscroll_release(crate::PointerButton::Secondary) { return; } + self.secondary_region_up(x, y); + let (path, down_link, left) = match self.pointer.take_secondary() { + capture::Secondary::Held { path, link, left } => (Some(path), link, left), + capture::Secondary::Up => (None, None, false), + }; + if let Some(path) = path + && self.secondary_target(x, y) == Some(path.as_str()) + { + let i = self.tree.nodes.iter().position(|n| n.path == path); + let point = i.map_or(PointerEvent { x, y, window_x: x, window_y: y }, |i| self.pointer_event(i, x, y)); + let link = i.and_then(|i| self.secondary_link_at(i, x, y)); + // Like a primary link press, it must end on the link it began on; one that moved + // onto, off or between links opens nothing. + match (link, down_link) { + (Some(k), Some(d)) if k == d => self.frame.queue.push(Action::LinkSecondary(path, k, point)), + (None, None) if !self.selection_menu(app, &path, x, y) && !self.queue_field_menu(&path, x, y) => self.frame.queue.push(Action::SecondaryPress(path, point)), + _ => {} + } + } + self.leave_after_release(left); + } + + /// A secondary press at (x, y) on text field `path` with no `on_secondary_press` of its own: + /// its menu (`field_menu`), queued. + fn queue_field_menu(&mut self, path: &str, x: f32, y: f32) -> bool { + let Some(i) = self.live(path) else { return false }; + let n = &self.tree.nodes[i]; + if n.handlers.on_secondary_press.is_some() || n.input.as_ref().is_none_or(|i| i.access.is_none()) { return false; } + self.frame.queue.push(Action::FieldMenu(path.to_owned(), (x, y), Some((x, y)))); + true + } + + /// The Menu key, or Shift+F10, that nothing before it took: the focused element's context + /// menu. That is its focused link's `on_link_secondary`, else its own or its nearest + /// ancestor's `on_secondary_press`, at the bottom-left of the focused link or element, where + /// a menu opens below it as AppKit's and Windows' keyboard menus do. + pub(in crate::runtime) fn context_menu_key(&mut self, app: &mut dyn AppDriver, ev: &KeyEvent, tx: &mut Tx) -> bool { + let m = ev.mods; + let plain = !m.cmd && !m.ctrl && !m.alt && !m.logo; + let menu_key = match ev.key { + crate::Key::ContextMenu => plain, + crate::Key::Function(10) => plain && m.shift, + _ => false, + }; + let Some(focused) = self.focused_index().filter(|&i| menu_key && self.can_focus(i)) else { return false }; + if self.focused_link_menu(app, focused, tx) { return true; } + let [x, _, _, y] = self.drawn_box(focused); + let n = &self.tree.nodes[focused]; + if n.handlers.on_secondary_press.is_none() && n.input.as_ref().is_some_and(|i| i.access.is_some()) { + return self.field_menu(app, n.path.clone(), (x, y), None, tx); + } + let mut index = focused; + loop { + let n = &self.tree.nodes[index]; + if !self.allowed(index) { return false; } + if let Some(f) = n.handlers.on_secondary_press.clone() { + let path = n.path.clone(); + let point = self.pointer_event(index, x, y); + log_event!(self, "secondary press {path}"); + f(app.states(), point, tx); + return true; + } + let Some(p) = n.parent else { return false }; + index = p; + } + } +} diff --git a/app/vendor/rune/crates/rune/src/runtime/input/titlebar.rs b/app/vendor/rune/crates/rune/src/runtime/input/titlebar.rs new file mode 100644 index 0000000..6a7c774 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/input/titlebar.rs @@ -0,0 +1,321 @@ +//! Presses that move or zoom the window: `.window_drag()` regions, and the titlebar band +//! AppKit drags itself when the app leaves window dragging to it. Also the window's chrome +//! over a custom titlebar (`App::titlebar`): its insets, the Windows caption buttons and the +//! window menu. +use crate::machine::Effects; + +use super::*; + +#[derive(Default)] +pub(in crate::runtime) struct Titlebar { + /// What the press just delivered asks the shell to do, for `take_titlebar_action`. + pub(in crate::runtime) action: Option<TitlebarAction>, + /// The press in flight (`step`). + pub(in crate::runtime) press: TitlebarPress, + /// Window points from the top that AppKit drags natively, over the content (0 elsewhere). + native_band: f32, + /// The window menu the shell opens next. + window_menu: Option<WindowMenu>, + /// What `Cx::chrome_insets` reports. + pub(in crate::runtime) insets: crate::ChromeInsets, + /// The Windows caption buttons the view gets drawn over it, with their state. + pub(in crate::runtime) caption: Option<crate::titlebar::Caption>, + /// `Tx::toggle_maximized`, for the shell. + pub(in crate::runtime) toggle_maximized: bool, + /// `Tx::toggle_full_screen`, for the shell. + pub(in crate::runtime) toggle_full_screen: bool, + /// `Cx::set_titlebar` and `Cx::titlebar_height`, as the last view set them, and whether the + /// shell has yet to see them. + set: crate::titlebar::TitlebarSet, + set_changed: bool, + /// What a run without a window draws for `App::titlebar` (`headless_chrome`), so a new + /// `Cx::set_titlebar` or `Cx::titlebar_height` draws again. + headless: Option<(crate::Chrome, crate::Titlebar)>, +} + +/// The window menu (Restore, Move, Size, Minimize, Maximize, Close) a custom titlebar opens +/// where the native title bar would. +#[cfg_attr(not(target_os = "windows"), allow(dead_code))] +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum WindowMenu { + /// At the pointer: a secondary click on a bare `.window_drag()` region. + Pointer, + /// Under the window's top-left corner, from the keyboard: Alt+Space no handler took. + Keyboard, +} + +/// A press that may pair with the next one: when it went down and where. +#[derive(Clone, Copy, Debug, PartialEq)] +pub(in crate::runtime) struct Pair { + /// Clock seconds it went down at. + pub(in crate::runtime) at: f64, + /// Window points it went down at. + pub(in crate::runtime) point: (f32, f32), +} + +impl Pair { + /// Whether a press at `point` at `now` is this press's second: within the double-click + /// interval and the click slop. + fn second(self, now: f64, point: (f32, f32), interval: f64) -> bool { + press_run::follows(self.at, self.point, now, point, interval) + } +} + +/// The titlebar's press: what the next press can pair with, and whether a secondary press on a +/// bare `.window_drag()` region still owes its release. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub(in crate::runtime) enum TitlebarPress { + /// No press is in flight. + #[default] + Rest, + /// A press went down where a second one means something. + Armed(Pair), + /// A secondary press began on a bare drag region: its release there opens the window menu. + /// `Some` is the primary run it didn't end. + SecondaryOnRegion(Option<Pair>), +} + +impl TitlebarPress { + /// Whether a secondary press `SecondaryDown` began on a bare region owes its release. + pub(in crate::runtime) fn secondary_armed(self) -> bool { matches!(self, TitlebarPress::SecondaryOnRegion(_)) } +} + +/// What the titlebar's press sees. +pub(in crate::runtime) enum Event { + /// A primary press on a bare `.window_drag()` region. + Region { now: f64, point: (f32, f32), interval: f64 }, + /// A primary press that hit nothing; `band` when it is in the native titlebar band, where + /// the system drags the window itself and only the double click is Rune's. + Empty { now: f64, point: (f32, f32), interval: f64, band: bool }, + /// A secondary press; `region` when it landed on a bare drag region of a custom titlebar. + SecondaryDown { region: bool }, + /// A secondary release; `region` when it is over a bare drag region now. + SecondaryUp { region: bool }, + /// Pointer cancellation or stage replacement ends both halves of any pending press. + Clear, +} + +/// What a press asks the window for, in that press event: the shell starts a native drag inside +/// the press, and the window menu opens where the pointer is. +pub(in crate::runtime) enum Request { + /// Move the window, or the titlebar's double-click action. + Action(TitlebarAction), + /// Open the window menu at the pointer. + Menu, +} + +/// The run a `Region` or `Empty` press carries on with or starts, and whether it was a double. +fn pair_of(last: Option<Pair>, now: f64, point: (f32, f32), interval: f64) -> (Option<Pair>, bool) { + match last { + Some(last) if last.second(now, point, interval) => (None, true), + _ => (Some(Pair { at: now, point }), false), + } +} + +/// The press run `state` holds, whatever it is doing with a secondary press. +fn pair(state: &TitlebarPress) -> Option<Pair> { + match *state { + TitlebarPress::Rest => None, + TitlebarPress::Armed(pair) => Some(pair), + TitlebarPress::SecondaryOnRegion(pair) => pair, + } +} + +fn armed(pair: Option<Pair>) -> TitlebarPress { + pair.map_or(TitlebarPress::Rest, TitlebarPress::Armed) +} + +/// The state with its press run replaced, keeping a secondary press that still owes its release. +fn keep_secondary(state: &TitlebarPress, pair: Option<Pair>) -> TitlebarPress { + if state.secondary_armed() { TitlebarPress::SecondaryOnRegion(pair) } else { armed(pair) } +} + +pub(in crate::runtime) fn step(state: &mut TitlebarPress, event: Event) -> Effects<Request> { + match event { + // A press on a drag region always moves the window, unless it is the second of a pair. + Event::Region { now, point, interval } => { + let (next, double) = pair_of(pair(state), now, point, interval); + *state = keep_secondary(state, next); + Effects::one(Request::Action(if double { TitlebarAction::DoubleClick } else { TitlebarAction::Drag })) + } + // AppKit drags the band itself and never sees the double click over the content. + Event::Empty { now, point, interval, band } => { + if !band { return Effects::none(); } + let (next, double) = pair_of(pair(state), now, point, interval); + *state = keep_secondary(state, next); + if double { Effects::one(Request::Action(TitlebarAction::DoubleClick)) } else { Effects::none() } + } + Event::SecondaryDown { region } => { + *state = if region { TitlebarPress::SecondaryOnRegion(pair(state)) } else { armed(pair(state)) }; + Effects::none() + } + Event::SecondaryUp { region } => { + let TitlebarPress::SecondaryOnRegion(pair) = *state else { return Effects::none() }; + *state = armed(pair); + if region { Effects::one(Request::Menu) } else { Effects::none() } + } + Event::Clear => { + // differs from dev: a cancelled secondary down cannot open a menu on release. + *state = TitlebarPress::Rest; + Effects::none() + } + } +} + +impl Titlebar { + /// A press on a `.window_drag()` region: drag, or the double-click action on its second press. + pub(in crate::runtime) fn press_region(&mut self, now: f64, x: f32, y: f32, interval: f64) { + self.act(Event::Region { now, point: (x, y), interval }); + } + + /// A press that hit nothing. In the native band AppKit moves the window itself but doesn't + /// see the double click over the content view, so the second press asks for it here. + pub(in crate::runtime) fn press_empty(&mut self, now: f64, x: f32, y: f32, interval: f64) { + let band = y < self.native_band; + self.act(Event::Empty { now, point: (x, y), interval, band }); + } + + pub(in crate::runtime) fn clear(&mut self) { + self.act(Event::Clear); + } + + /// Steps the press and hands its request to the host, where the shell takes it in that press. + fn act(&mut self, event: Event) { + for request in step(&mut self.press, event) { + match request { + Request::Action(action) => self.action = Some(action), + Request::Menu => self.window_menu = Some(WindowMenu::Pointer), + } + } + } +} + +impl RuntimeCore { + /// The titlebar band, in window points from the top, that the system drags natively while + /// the content view fills it (macOS full-size content without drag regions). Empty presses + /// there take the titlebar double-click action. 0, the default, leaves them alone. + pub fn set_native_titlebar_band(&mut self, points: f32) { + self.host.titlebar.native_band = points; + } + + /// A window drag or titlebar double-click requested by the press just delivered. The shell + /// must act on it before returning from that press event. + pub fn take_titlebar_action(&mut self) -> Option<TitlebarAction> { + self.host.titlebar.action.take() + } + + /// What [`Cx::chrome_insets`] reports. Native windows set it from their controls on every + /// resize, full screen included; a change re-runs the view. + pub fn set_chrome_insets(&mut self, insets: crate::ChromeInsets) { + if insets != self.host.titlebar.insets { + self.host.titlebar.insets = insets; + self.commit.dirty = true; + } + } + + pub fn chrome_insets(&self) -> crate::ChromeInsets { + self.host.titlebar.insets + } + + /// The caption buttons to draw over the view, and their hover and press state; `None` + /// draws none. A change re-runs the view. + pub(crate) fn set_caption(&mut self, caption: Option<crate::titlebar::Caption>) { + if caption == self.host.titlebar.caption { return; } + self.host.titlebar.caption = caption; + self.commit.dirty = true; + } + + /// What a run without a window reports and draws for `App::titlebar` on this platform, as + /// its window would at rest: `Cx::titlebar_inset`, `Cx::chrome_insets` and the caption + /// buttons. Returns the frame the headless traffic-light checks see. + pub(crate) fn headless_chrome(&mut self, chrome: crate::Chrome, titlebar: Option<crate::Titlebar>, borderless: bool) -> crate::Chrome { + let titlebar = titlebar.filter(|_| !borderless); + self.host.titlebar.headless = titlebar.map(|t| (chrome, t)); + let titlebar = titlebar.map(|t| self.host.titlebar.set.over(t)); + let chrome = match titlebar { + Some(t) if cfg!(target_os = "macos") => t.mac_chrome(chrome), + _ => chrome, + }; + let inset = if borderless { 0.0 } else { chrome.titlebar_inset() }; + self.set_titlebar_inset(inset); + let caption = titlebar.filter(|_| cfg!(target_os = "windows")).map(|t| crate::titlebar::Caption::new(t.height())); + let height = titlebar.filter(|_| cfg!(any(target_os = "macos", target_os = "windows"))).map_or(0.0, |t| t.height()); + let leading = if cfg!(target_os = "macos") { inset } else { 0.0 }; + let trailing = caption.map_or(0.0, |c| c.width(self.env.scale)); + self.set_chrome_insets(crate::ChromeInsets::new(leading, trailing, height)); + self.set_caption(caption); + chrome + } + + /// Takes a `Tx::toggle_maximized`, for the shell to carry out. + #[cfg_attr(target_arch = "wasm32", allow(dead_code))] + pub(crate) fn take_toggle_maximized(&mut self) -> bool { + std::mem::take(&mut self.host.titlebar.toggle_maximized) + } + + /// Takes a `Tx::toggle_full_screen`, for the shell to carry out. + #[cfg_attr(target_arch = "wasm32", allow(dead_code))] + pub(crate) fn take_toggle_full_screen(&mut self) -> bool { + std::mem::take(&mut self.host.titlebar.toggle_full_screen) + } + + /// The window menu a secondary click on a drag region or an unclaimed Alt+Space asked for, + /// for the shell to open. + #[cfg_attr(target_arch = "wasm32", allow(dead_code))] + pub(crate) fn take_window_menu(&mut self) -> Option<WindowMenu> { + self.host.titlebar.window_menu.take() + } + + /// Alt+Space no handler took opens the window menu (`Unhandled::WindowMenu`). + pub(in crate::runtime) fn request_window_menu(&mut self) { + self.host.titlebar.window_menu = Some(WindowMenu::Keyboard); + } + + /// `Cx::set_titlebar` and `Cx::titlebar_height`, as the last view set them; empty keeps + /// `App::titlebar`'s. + pub(crate) fn titlebar_set(&self) -> crate::titlebar::TitlebarSet { + self.host.titlebar.set + } + + /// Notes the titlebar a view set. A run without a window draws it at once; a window's shell + /// resizes its frame and moves the traffic lights (`take_titlebar_changed`). + pub(in crate::runtime) fn set_titlebar(&mut self, set: crate::titlebar::TitlebarSet) { + if set == self.host.titlebar.set { return; } + self.host.titlebar.set = set; + self.host.titlebar.set_changed = true; + if let Some((chrome, titlebar)) = self.host.titlebar.headless { + self.headless_chrome(chrome, Some(titlebar), false); + } + } + + /// Whether the titlebar the view set changed since the shell last asked. + #[cfg_attr(target_arch = "wasm32", allow(dead_code))] + pub(crate) fn take_titlebar_changed(&mut self) -> bool { + std::mem::take(&mut self.host.titlebar.set_changed) + } + + /// Notes whether a secondary press at (x, y) landed on a bare `.window_drag()` region of a + /// custom titlebar, where its release opens the window menu. + pub(in crate::runtime) fn secondary_region_down(&mut self, x: f32, y: f32, captured: bool) { + let region = !captured && self.host.titlebar.caption.is_some() + && self.primary_target(x, y).is_some_and(|t| self.bare_drag_region(t)); + self.host.titlebar.act(Event::SecondaryDown { region }); + } + + /// A secondary release that ends the press `secondary_region_down` noted on a drag region + /// asks the shell for the window menu. + pub(in crate::runtime) fn secondary_region_up(&mut self, x: f32, y: f32) { + // A release with no press on a region has nothing to ask for, as `take` returned false. + if !self.host.titlebar.press.secondary_armed() { return; } + let region = self.primary_target(x, y).is_some_and(|t| self.bare_drag_region(t)); + self.host.titlebar.act(Event::SecondaryUp { region }); + } + + /// A `.window_drag()` element with nothing of its own to do with a press: a press there + /// moves the window, and a secondary click opens the window menu. + pub(in crate::runtime) fn bare_drag_region(&self, t: usize) -> bool { + let n = &self.tree.nodes[t]; + n.window_drag == crate::el::WindowDrag::Drag && n.handlers.on_press.is_none() && n.handlers.on_double_press.is_none() && n.handlers.on_drag.is_none() + && n.handlers.drag_out.is_none() && self.textbox_input(t).is_none() + } +} diff --git a/app/vendor/rune/crates/rune/src/runtime/input/touch.rs b/app/vendor/rune/crates/rune/src/runtime/input/touch.rs new file mode 100644 index 0000000..897b08f --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/input/touch.rs @@ -0,0 +1,188 @@ +//! Touchscreen and pen input, as a browser handles it: the first finger is the primary +//! button. It presses where it lands, so a tap clicks; dragging an element that drags +//! (`El::on_drag`: a slider, a scroll bar) drags it; any other drag pans the scroll viewport +//! under the finger (`runtime/scroll/touch.rs`), flinging it on with momentum, and cancels +//! the press. A finger held still for [`LONG_PRESS`] is a secondary click there, as Chromium's +//! long press sends `contextmenu`: the press it began lets go without a click and the menu opens +//! under the finger, which then lifts on nothing. Further fingers are ignored while one is down. +use super::*; + +/// How far (points) a finger travels before its touch is a drag or a pan, not a tap. +const TOUCH_SLOP: f32 = 8.0; +/// A finger held this long (seconds) before lifting throws nothing. +const FLING_HOLD: f64 = 0.1; +/// A finger held still this long (seconds) opens the menu under it (Chromium's +/// `long_press_time_in_ms`). +const LONG_PRESS: f64 = 0.5; + +/// A host's touch phase, as winit reports it. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum TouchPhase { + Started, + Moved, + Ended, + /// The system took the touch (a gesture of its own): nothing it pressed is clicked. + Cancelled, +} + +/// What touches are doing: the finger that is down, and the viewport a touch holds or flung. +#[derive(Default)] +pub(in crate::runtime) struct Touch { + pub(in crate::runtime) scroll: Option<scroll_touch::TouchScroll>, + finger: Option<Finger>, +} + +struct Finger { + id: u64, + origin: (f32, f32), + /// Travel along the pan's axis (vertical until a pan picks horizontal) at the last event, + /// and that event's time. + last: f32, + at: f64, + /// Points per second along the pan's axis. + velocity: f32, + mode: Mode, + /// When (`now_clock`), still pending, it becomes a long press. + hold_due: f64, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Mode { + /// Still within the slop: lifting it here is a tap. `scroll` is the vertical viewport + /// under the finger, held until the pan picks its axis. + Pending { scroll: Option<NodeId> }, + /// It drags the element it pressed. + Drag, + /// It pans viewport `scroll` along one axis. + Pan { scroll: NodeId, horizontal: bool }, + /// A long press opened the menu under it: it lifts on nothing. + Menu, +} + +impl Mode { + /// The viewport the touch holds: the one it pans, or while pending the one under it. + fn scroll(self) -> Option<NodeId> { + match self { + Mode::Pending { scroll } => scroll, + Mode::Pan { scroll, .. } => Some(scroll), + Mode::Drag | Mode::Menu => None, + } + } + + fn horizontal(self) -> bool { matches!(self, Mode::Pan { horizontal: true, .. }) } +} + +impl capture::PointerState { + /// Whether a finger is down: a host ignores the mouse events its system makes up from it. + #[inline] + pub(in crate::runtime) fn touching(&self) -> bool { + self.touch.finger.is_some() + } +} + +impl RuntimeCore { + /// One touch event at (x, y) in window points, `time` in seconds on any steady clock. A + /// host with touches calls this for every one; `id` tells fingers apart. + pub(crate) fn touch(&mut self, app: &mut dyn AppDriver, id: u64, phase: TouchPhase, x: f32, y: f32, time: f64) { + match phase { + TouchPhase::Started => self.touch_down(app, id, x, y, time), + TouchPhase::Moved => self.touch_move(app, id, x, y, time), + TouchPhase::Ended | TouchPhase::Cancelled => self.touch_up(app, id, x, y, time, phase == TouchPhase::Cancelled), + } + } + + /// Whether a finger is down: a host ignores the mouse events its system makes up from it. + #[inline] + pub(crate) fn touching(&self) -> bool { + self.pointer.touching() + } + + fn touch_down(&mut self, app: &mut dyn AppDriver, id: u64, x: f32, y: f32, time: f64) { + if self.pointer.touch.finger.is_some() { return; } + let scroll = self.touch_scroll_start(x, y); + self.pointer_move(app, x, y); + self.press_down(app, x, y, true); + // `El::touch_drags_at_once`: a drag from the first move, and no long press to cut it. + if self.press_drags_at_once() { + self.touch_scroll_end(scroll, 0.0); + self.pointer.touch.finger = Some(Finger { id, origin: (x, y), last: 0.0, at: time, velocity: 0.0, mode: Mode::Drag, hold_due: f64::INFINITY }); + return; + } + let hold_due = self.now_clock() + LONG_PRESS; + self.wake_at(hold_due); + self.pointer.touch.finger = Some(Finger { id, origin: (x, y), last: 0.0, at: time, velocity: 0.0, mode: Mode::Pending { scroll }, hold_due }); + } + + fn touch_move(&mut self, app: &dyn ViewDriver, id: u64, x: f32, y: f32, time: f64) { + let Some(f) = self.pointer.touch.finger.as_ref().filter(|f| f.id == id) else { return }; + let (dx, dy) = (x - f.origin.0, y - f.origin.1); + if let Mode::Pending { scroll } = f.mode && dx.hypot(dy) > TOUCH_SLOP { + let origin = f.origin; + let (scroll, horizontal) = if self.press_drags() { (None, false) } else { self.touch_scroll_pan(origin.0, origin.1, dx.abs() > dy.abs(), scroll) }; + self.pointer.touch.finger.as_mut().unwrap().mode = match scroll { + Some(scroll) => Mode::Pan { scroll, horizontal }, + None => Mode::Drag, + }; + } + let f = self.pointer.touch.finger.as_mut().unwrap(); + let along = if f.mode.horizontal() { dx } else { dy }; + let dt = time - f.at; + if dt > 0.0 { f.velocity = (along - f.last) / dt as f32; } + (f.last, f.at) = (along, time); + match f.mode { + Mode::Pan { scroll, .. } => self.touch_scroll_move(scroll, along), + Mode::Drag => self.pointer_move(app, x, y), + Mode::Pending { .. } | Mode::Menu => {} + } + } + + fn touch_up(&mut self, app: &dyn ViewDriver, id: u64, x: f32, y: f32, time: f64, cancelled: bool) { + let Some(f) = self.pointer.touch.finger.take_if(|f| f.id == id) else { return }; + let pan = matches!(f.mode, Mode::Pan { .. }); + let velocity = if pan && !cancelled && time - f.at < FLING_HOLD { f.velocity } else { 0.0 }; + self.touch_scroll_end(f.mode.scroll(), velocity); + if f.mode == Mode::Menu { + self.pointer_leave(); + return; + } + if cancelled { + self.cancel_pointer(); + return; + } + // A pan cancelled the press, so its release clicks nothing. + let (x, y) = if pan { f.origin } else { (x, y) }; + if f.mode == Mode::Drag { self.pointer_move(app, x, y); } + self.pointer_up(app, x, y); + // No hover is left under a lifted finger. + self.pointer_leave(); + } + + /// A finger still within the slop when its long press is due: the press it began lets go + /// without a click (a drag it started hears a cancelled `Phase::Up`), and a secondary click + /// lands where it went down. + pub(in crate::runtime) fn fire_touch_hold(&mut self, app: &dyn ViewDriver) { + let Some(f) = self.pointer.touch.finger.as_ref().filter(|f| matches!(f.mode, Mode::Pending { .. }) && self.clock >= f.hold_due) else { return }; + let ((x, y), scroll) = (f.origin, f.mode.scroll()); + self.touch_scroll_end(scroll, 0.0); + if !self.cancel_drag() { self.drop_press(); } + self.secondary_down(x, y); + self.secondary_up(app, x, y); + if let Some(f) = self.pointer.touch.finger.as_mut() { f.mode = Mode::Menu; } + } + + /// Whether the held press is on an `El::touch_drags_at_once` element. + fn press_drags_at_once(&self) -> bool { + let Some(path) = self.pointer.press.path() else { return false }; + self.live_index(path).is_some_and(|i| self.tree.nodes[i].handlers.touch_at_once && self.tree.nodes[i].handlers.on_drag.is_some()) + } + + /// Whether the held press is on an element that drags, so a finger drags it, not the page. + fn press_drags(&self) -> bool { + let Some(path) = self.pointer.press.path() else { return false }; + self.live_index(path).is_some_and(|i| self.tree.nodes[i].handlers.on_drag.is_some() && !self.drags_out(&self.tree.nodes[i])) + } +} + +#[cfg(test)] +#[path = "touch_tests.rs"] +mod tests; diff --git a/app/vendor/rune/crates/rune/src/runtime/input/touch_tests.rs b/app/vendor/rune/crates/rune/src/runtime/input/touch_tests.rs new file mode 100644 index 0000000..3a311f7 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/input/touch_tests.rs @@ -0,0 +1,103 @@ +use super::*; +use crate::{ScrollSpec, col, el}; + +#[derive(Default)] +struct S { taps: Vec<usize>, drags: Vec<f32> } + +fn view(_: &S, _: &mut Cx<S>) -> El { + col().size(200.0, 300.0) + .child(el().key("knob").size(200.0, 40.0).on_drag(|s: &mut S, d: &mut Drag, _| s.drags.push(d.dx))) + .child(col().key("list").w_full().h(200.0).scroll(ScrollSpec { stick_bottom: false }) + .children((0..30).map(|i| el().key(format!("row{i}")).w_full().h(40.0).on_press(move |s: &mut S| s.taps.push(i))))) +} + +fn rig() -> Runtime<S> { + let mut rt = Runtime::new(S::default(), view, (200.0, 300.0), Env::default()); + rt.frame(0.0); + rt +} + +fn offset(rt: &Runtime<S>) -> f64 { + let id = rt.tree.nodes.iter().find(|n| n.key.as_deref() == Some("list")).unwrap().id; + rt.scroll.scrolls[&id].offset +} + +/// A finger from (x, y) moving by `dy` over `steps` events 10 ms apart, then lifted. +fn swipe(rt: &mut Runtime<S>, (x, y): (f32, f32), dy: f32, steps: usize) { + rt.touch(1, TouchPhase::Started, x, y, 0.0); + for i in 1..=steps { + rt.touch(1, TouchPhase::Moved, x, y + dy * i as f32 / steps as f32, i as f64 * 0.01); + } + rt.touch(1, TouchPhase::Ended, x, y + dy, steps as f64 * 0.01 + 0.005); + rt.frame(1.0 / 60.0); +} + +#[test] +fn a_tap_clicks_what_it_lands_on_and_leaves_no_hover() { + let mut rt = rig(); + rt.touch(1, TouchPhase::Started, 100.0, 70.0, 0.0); + rt.touch(1, TouchPhase::Moved, 103.0, 72.0, 0.02); + rt.touch(1, TouchPhase::Ended, 103.0, 72.0, 0.05); + rt.frame(1.0 / 60.0); + assert_eq!(rt.state.taps, [0]); + assert_eq!(rt.pointer(), None); + assert!(!rt.touching()); +} + +#[test] +fn a_drag_on_a_list_scrolls_it_without_clicking_and_flings_on() { + let mut rt = rig(); + swipe(&mut rt, (100.0, 200.0), -100.0, 5); + assert!(rt.state.taps.is_empty(), "a pan presses nothing"); + let lifted = offset(&rt); + assert!(lifted >= 90.0, "the list followed the finger: {lifted}"); + for _ in 0..30 { rt.frame(1.0 / 60.0); } + assert!(offset(&rt) > lifted + 50.0, "and coasted on: {} after {lifted}", offset(&rt)); +} + +#[test] +fn a_finger_held_still_before_lifting_throws_nothing() { + let mut rt = rig(); + rt.touch(1, TouchPhase::Started, 100.0, 200.0, 0.0); + rt.touch(1, TouchPhase::Moved, 100.0, 150.0, 0.01); + rt.touch(1, TouchPhase::Ended, 100.0, 150.0, 0.5); + for _ in 0..30 { rt.frame(1.0 / 60.0); } + assert_eq!(offset(&rt), 50.0); +} + +#[test] +fn a_drag_on_an_element_that_drags_drags_it_not_the_page() { + let mut rt = rig(); + rt.touch(1, TouchPhase::Started, 20.0, 20.0, 0.0); + rt.touch(1, TouchPhase::Moved, 60.0, 30.0, 0.01); + rt.touch(1, TouchPhase::Ended, 60.0, 30.0, 0.02); + rt.frame(1.0 / 60.0); + assert_eq!(rt.state.drags.last(), Some(&40.0)); + assert_eq!(offset(&rt), 0.0); +} + +#[test] +fn a_second_finger_is_ignored_and_a_cancelled_touch_clicks_nothing() { + let mut rt = rig(); + rt.touch(1, TouchPhase::Started, 100.0, 70.0, 0.0); + rt.touch(2, TouchPhase::Started, 100.0, 110.0, 0.0); + rt.touch(2, TouchPhase::Ended, 100.0, 110.0, 0.01); + rt.touch(1, TouchPhase::Cancelled, 100.0, 70.0, 0.02); + rt.frame(1.0 / 60.0); + assert!(rt.state.taps.is_empty()); + assert!(!rt.touching()); +} + +#[test] +fn a_finger_past_the_slop_picks_one_mode_with_only_its_own_data() { + let mut rt = rig(); + let list = rt.tree.nodes.iter().find(|n| n.key.as_deref() == Some("list")).unwrap().id; + rt.touch(1, TouchPhase::Started, 100.0, 200.0, 0.0); + assert_eq!(rt.pointer.touch.finger.as_ref().map(|f| f.mode), Some(Mode::Pending { scroll: Some(list) }), "pending, it holds the viewport under it"); + rt.touch(1, TouchPhase::Moved, 100.0, 150.0, 0.01); + assert_eq!(rt.pointer.touch.finger.as_ref().map(|f| f.mode), Some(Mode::Pan { scroll: list, horizontal: false })); + rt.touch(1, TouchPhase::Ended, 100.0, 150.0, 0.02); + rt.touch(2, TouchPhase::Started, 20.0, 20.0, 1.0); + rt.touch(2, TouchPhase::Moved, 60.0, 20.0, 1.01); + assert_eq!(rt.pointer.touch.finger.as_ref().map(|f| f.mode), Some(Mode::Drag), "on an element that drags it holds no viewport"); +} diff --git a/app/vendor/rune/crates/rune/src/runtime/input_click_tests.rs b/app/vendor/rune/crates/rune/src/runtime/input_click_tests.rs new file mode 100644 index 0000000..6073496 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/input_click_tests.rs @@ -0,0 +1,642 @@ +use super::*; +use crate::{Cx, El, Env, Ime, Key, KeyEvent, Mods, PhysicalInput, Runtime, TextEdit, TextStyle, col, text_input}; + +struct Form { + single: TextEdit, + multi: TextEdit, + other: TextEdit, + secret: TextEdit, + secret_multi: TextEdit, + pills: TextEdit, + show_single: bool, + presses: usize, + drags: Vec<Phase>, +} + +fn style() -> TextStyle { + TextStyle::new(14.0, 400.0).lh(20.0) +} + +fn view(s: &Form, _: &mut Cx<Form>) -> El { + let st = style(); + let mut root = col().w_full().h_full().padding(8.0).gap(8.0); + if s.show_single { + root = root.child( + text_input(&s.single, st) + .single_line() + .key("single") + .size(280.0, 24.0) + .on_edit(|s: &mut Form| &mut s.single) + .on_press(|s: &mut Form| s.presses += 1) + .on_drag(|s: &mut Form, d, _| s.drags.push(d.phase)) + .on_input_key(|s: &mut Form, ev, _| { + if ev.key == Key::Function(2) { + s.single.insert("!"); + return true; + } + false + }), + ); + } + root.child( + text_input(&s.multi, st) + .key("multi") + .size(280.0, 80.0) + .on_edit(|s: &mut Form| &mut s.multi), + ) + .child( + text_input(&s.other, st) + .single_line() + .key("other") + .size(280.0, 24.0) + .on_edit(|s: &mut Form| &mut s.other), + ) + .child( + text_input(&s.secret, st) + .single_line() + .secure() + .key("secret") + .size(280.0, 24.0) + .on_edit(|s: &mut Form| &mut s.secret), + ) + .child( + text_input(&s.secret_multi, st) + .secure() + .key("secret-multi") + .size(280.0, 48.0) + .on_edit(|s: &mut Form| &mut s.secret_multi), + ) + .child( + text_input(&s.pills, st) + .single_line() + .key("pills") + .size(280.0, 24.0) + .on_edit(|s: &mut Form| &mut s.pills), + ) +} + +fn runtime() -> Runtime<Form> { + let mut pills = TextEdit::new("").rich(); + pills.insert_pill("u:1", "@maya"); + pills.insert(" hello"); + pills.set_caret(0); + let state = Form { + single: TextEdit::new("make the title smaller"), + multi: TextEdit::new("first line here\nsecond line there\nthird line end"), + other: TextEdit::new("other words"), + secret: TextEdit::new("correct horse battery"), + secret_multi: TextEdit::new("line one secret\nline two secret"), + pills, + show_single: true, + presses: 0, + drags: Vec::new(), + }; + let mut rt = Runtime::new(state, view, (320.0, 300.0), Env::new(true, 1.0)); + rt.frame(0.0); + rt +} + +fn rect_of(rt: &Runtime<Form>, key: &str) -> [f32; 4] { + rt.elements().into_iter().find(|e| e.key.as_deref() == Some(key)).unwrap().rect +} + +/// Window point `(x, y)` at `frac` (`0.0..1.0`) across the glyph cluster at `byte` in `key`. +fn point_in_cluster(rt: &Runtime<Form>, key: &str, byte: usize, frac: f32) -> (f32, f32) { + let n = rt.tree.nodes.iter().find(|n| n.key.as_deref() == Some(key)).unwrap(); + let piece = n.text_layout.as_ref().unwrap().view().piece_at(byte); + let (l, byte) = (piece.layout, piece.shaped(byte)); + let s = rt.env.scale; + let cl = parley::Cluster::from_byte_index(l, byte).unwrap(); + let x0 = cl.visual_offset().unwrap(); + let adv = cl.advance(); + let cur = Cursor::from_byte_index(l, byte, Affinity::Downstream); + let bb = crate::text::cursor_geometry(&cur, l, 1.0); + let r = rect_of(rt, key); + ( + r[0] + n.inset[0] + (x0 + adv * frac) / s, + r[1] + n.inset[1] + (piece.y + ((bb.y0 + bb.y1) * 0.5) as f32) / s, + ) +} + +fn point_at_byte(rt: &Runtime<Form>, key: &str, byte: usize) -> (f32, f32) { + point_in_cluster(rt, key, byte, 0.25) +} + +fn click(rt: &mut Runtime<Form>, (x, y): (f32, f32)) { + rt.pointer_down(x, y); + rt.pointer_up(x, y); + rt.frame(1.0 / 60.0); +} + +#[test] +fn double_and_triple_click_select_word_and_line_in_single_line_input() { + let mut rt = runtime(); + let r = rect_of(&rt, "single"); + let (x, y) = (r[0] + 12.0, r[1] + r[3] * 0.5); + + // Unfocused first press focuses the input and places the caret inside "make". + assert!(!rt.state.single.focused); + rt.pointer_down(x, y); + rt.pointer_up(x, y); + rt.frame(1.0 / 60.0); + assert!(rt.state.single.focused); + assert!(!rt.kbd.focus.keyboard(), "pointer focus does not turn on keyboard focus ring"); + assert_eq!(rt.state.single.anchor, rt.state.single.focus); + assert!(rt.state.single.focus > 0 && rt.state.single.focus < 4); + + // Second press within double_click_interval and CLICK_SLOP selects "make" (0..4). + rt.pointer_down(x, y); + rt.pointer_up(x, y); + rt.frame(1.0 / 60.0); + assert_eq!((rt.state.single.anchor, rt.state.single.focus), (0, 4)); + assert_eq!(rt.state.single.selected(), "make"); + + // Third press selects the whole single-line text; fourth stays at three. + rt.pointer_down(x, y); + rt.pointer_up(x, y); + rt.frame(1.0 / 60.0); + assert_eq!((rt.state.single.anchor, rt.state.single.focus), (0, rt.state.single.text.len())); + rt.pointer_down(x, y); + rt.pointer_up(x, y); + rt.frame(1.0 / 60.0); + assert_eq!((rt.state.single.anchor, rt.state.single.focus), (0, rt.state.single.text.len())); +} + +#[test] +fn triple_click_in_multiline_input_selects_hard_line_paragraph() { + let mut rt = runtime(); + let second = rt.state.multi.text.find("second").unwrap(); + let third = rt.state.multi.text.find("third").unwrap(); + let pt = point_at_byte(&rt, "multi", second + 2); + + click(&mut rt, pt); + click(&mut rt, pt); + assert_eq!((rt.state.multi.anchor, rt.state.multi.focus), (second, second + 6)); + assert_eq!(rt.state.multi.selected(), "second"); + + click(&mut rt, pt); + assert_eq!((rt.state.multi.anchor, rt.state.multi.focus), (second, third)); + assert_eq!(rt.state.multi.selected(), "second line there\n"); + + // Fourth click stays at three. + click(&mut rt, pt); + assert_eq!((rt.state.multi.anchor, rt.state.multi.focus), (second, third)); +} + +#[test] +fn click_drag_double_drag_and_triple_drag_extend_by_unit_in_both_directions() { + let mut rt = runtime(); + let p_the = point_at_byte(&rt, "single", 6); // inside "the" (5..8) + let p_smaller = point_at_byte(&rt, "single", 17); // inside "smaller" (15..22) + let p_make = point_at_byte(&rt, "single", 1); // inside "make" (0..4) + + // Single-click drag selects by characters. + rt.pointer_down(p_the.0, p_the.1); + rt.frame(1.0 / 60.0); + let start = rt.state.single.anchor; + rt.pointer_move(p_smaller.0, p_smaller.1); + rt.pointer_up(p_smaller.0, p_smaller.1); + rt.frame(1.0 / 60.0); + assert_eq!(rt.state.single.anchor, start); + assert!(rt.state.single.focus > 15 && rt.state.single.focus < 22); + + // Wait past double_click_interval, then double-click "the" (5..8) and drag right into "smaller" (15..22). + rt.frame(1.0); + click(&mut rt, p_the); + rt.pointer_down(p_the.0, p_the.1); + rt.frame(1.0 / 60.0); + assert_eq!((rt.state.single.anchor, rt.state.single.focus), (5, 8)); + rt.pointer_move(p_smaller.0, p_smaller.1); + rt.frame(1.0 / 60.0); + assert_eq!((rt.state.single.anchor, rt.state.single.focus), (5, 22)); + assert_eq!(rt.state.single.selected(), "the title smaller"); + + // Dragging back left into "make" (0..4) flips anchor to the far end of "the" (8) and focus to 0. + rt.pointer_move(p_make.0, p_make.1); + rt.pointer_up(p_make.0, p_make.1); + rt.frame(1.0 / 60.0); + assert_eq!((rt.state.single.anchor, rt.state.single.focus), (8, 0)); + assert_eq!(rt.state.single.selected(), "make the"); + + // Triple-click on line 2 of multi ("second line there\n") and drag down to line 3, then up to line 1. + rt.frame(1.0); + let second = rt.state.multi.text.find("second").unwrap(); + let third = rt.state.multi.text.find("third").unwrap(); + let len = rt.state.multi.text.len(); + let l1 = point_at_byte(&rt, "multi", 2); + let l2 = point_at_byte(&rt, "multi", second + 2); + let l3 = point_at_byte(&rt, "multi", third + 2); + + click(&mut rt, l2); + click(&mut rt, l2); + rt.pointer_down(l2.0, l2.1); + rt.frame(1.0 / 60.0); + assert_eq!((rt.state.multi.anchor, rt.state.multi.focus), (second, third)); + rt.pointer_move(l3.0, l3.1); + rt.frame(1.0 / 60.0); + assert_eq!((rt.state.multi.anchor, rt.state.multi.focus), (second, len)); + rt.pointer_move(l1.0, l1.1); + rt.pointer_up(l1.0, l1.1); + rt.frame(1.0 / 60.0); + assert_eq!((rt.state.multi.anchor, rt.state.multi.focus), (third, 0)); +} + +#[test] +fn double_click_drag_extends_by_word_across_paragraphs() { + let mut rt = runtime(); + let text = &rt.state.multi.text; + let line = text.find("line").unwrap(); + let second = text.find("second").unwrap(); + let end = text.find("end").unwrap(); + let start = point_at_byte(&rt, "multi", second + 2); + let forward = point_at_byte(&rt, "multi", end + 1); + let back = point_at_byte(&rt, "multi", line + 1); + + click(&mut rt, start); + rt.pointer_down(start.0, start.1); + rt.frame(1.0 / 60.0); + rt.pointer_move(forward.0, forward.1); + rt.frame(1.0 / 60.0); + assert_eq!((rt.state.multi.anchor, rt.state.multi.focus), (second, end + 3)); + rt.pointer_move(back.0, back.1); + rt.pointer_up(back.0, back.1); + rt.frame(1.0 / 60.0); + assert_eq!((rt.state.multi.anchor, rt.state.multi.focus), (second + 6, line)); +} + +#[test] +fn shift_click_extends_from_anchor_and_does_not_start_multiclick() { + let mut rt = runtime(); + let p_make = point_at_byte(&rt, "single", 2); + let p_title = point_at_byte(&rt, "single", 11); + + click(&mut rt, p_make); + let anchor = rt.state.single.anchor; + assert!(anchor > 0 && anchor < 4); + + // Shift+click at the same point right after a click extends (empty at anchor) instead of double-clicking. + rt.physical_input(PhysicalInput::Modifiers(Mods { shift: true, ..Mods::default() })); + click(&mut rt, p_make); + assert_eq!((rt.state.single.anchor, rt.state.single.focus), (anchor, anchor)); + + // Shift+click further right extends from anchor to the clicked byte. + click(&mut rt, p_title); + rt.physical_input(PhysicalInput::Modifiers(Mods::default())); + assert_eq!(rt.state.single.anchor, anchor); + assert!(rt.state.single.focus >= 9 && rt.state.single.focus <= 14); + + // Immediately clicking at p_title without Shift is a single click, not a double-click. + click(&mut rt, p_title); + assert_eq!(rt.state.single.anchor, rt.state.single.focus); +} + +#[test] +fn secure_inputs_select_all_on_double_and_triple_click_and_stay_pristine() { + let mut rt = runtime(); + assert!(rt.state.secret.is_pristine()); + assert!(rt.state.secret_multi.is_pristine()); + + let r1 = rect_of(&rt, "secret"); + let pt1 = (r1[0] + 12.0, r1[1] + r1[3] * 0.5); + click(&mut rt, pt1); + assert!(rt.state.secret.is_pristine()); + assert_eq!(rt.state.secret.anchor, rt.state.secret.focus); + click(&mut rt, pt1); + assert_eq!((rt.state.secret.anchor, rt.state.secret.focus), (0, rt.state.secret.text.len())); + assert!(rt.state.secret.is_pristine(), "double-click selection must not mark a secure input edited"); + click(&mut rt, pt1); + assert_eq!((rt.state.secret.anchor, rt.state.secret.focus), (0, rt.state.secret.text.len())); + assert!(rt.state.secret.is_pristine()); + + let r2 = rect_of(&rt, "secret-multi"); + let pt2 = (r2[0] + 12.0, r2[1] + 12.0); + click(&mut rt, pt2); + assert_eq!( + (rt.state.secret_multi.anchor, rt.state.secret_multi.focus), + (rt.state.secret_multi.text.len(), rt.state.secret_multi.text.len()), + ); + click(&mut rt, pt2); + assert_eq!((rt.state.secret_multi.anchor, rt.state.secret_multi.focus), (0, rt.state.secret_multi.text.len())); + assert!(rt.state.secret_multi.is_pristine()); + click(&mut rt, pt2); + assert_eq!((rt.state.secret_multi.anchor, rt.state.secret_multi.focus), (0, rt.state.secret_multi.text.len())); + assert!(rt.state.secret_multi.is_pristine()); +} + +#[test] +fn timing_slop_and_target_changes_reset_multiclick_count_and_preedit_ignores_it() { + let mut rt = runtime(); + let r = rect_of(&rt, "single"); + let pt = (r[0] + 12.0, r[1] + r[3] * 0.5); + + // 1. Waiting longer than double_click_interval resets count to 1. + click(&mut rt, pt); + let slow = rt.double_click_interval + 0.05; + rt.frame(slow); + click(&mut rt, pt); + assert_eq!(rt.state.single.anchor, rt.state.single.focus, "press after double_click_interval is a single click"); + + // 2. Moving outside CLICK_SLOP resets count to 1. + rt.frame(1.0); + click(&mut rt, pt); + click(&mut rt, (pt.0 + CLICK_SLOP + 1.0, pt.1)); + assert_eq!(rt.state.single.anchor, rt.state.single.focus, "press outside CLICK_SLOP is a single click"); + + // 3. Pressing another input in between resets count to 1. + rt.frame(1.0); + let r_other = rect_of(&rt, "other"); + let pt_other = (r_other[0] + 12.0, r_other[1] + r_other[3] * 0.5); + click(&mut rt, pt); + click(&mut rt, pt_other); + click(&mut rt, pt); + assert_eq!(rt.state.single.anchor, rt.state.single.focus, "pressing another input resets the click count"); + + // 4. A press mid-composition writes the composition into the text, as a browser's field + // does, and puts the caret where it landed. + rt.frame(1.0); + rt.ime(Ime::Preedit("かん".into(), Some((0, 6)), Vec::new())); + rt.frame(1.0 / 60.0); + click(&mut rt, pt); + assert!(rt.state.single.preedit().is_none()); + assert!(rt.state.single.text.contains("かん")); +} + +#[test] +fn right_half_of_char_and_pill_trailing_padding_select_the_hit_word_and_pill() { + let mut rt = runtime(); + // Byte 3 is the 'e' of "make" in "make the title smaller". Its right half places a single-click + // caret at byte 4, but double-clicking there must still select "make" (0..4), not " " (4..5). + let right_of_e = point_in_cluster(&rt, "single", 3, 0.8); + click(&mut rt, right_of_e); + assert_eq!((rt.state.single.anchor, rt.state.single.focus), (4, 4)); + click(&mut rt, right_of_e); + assert_eq!((rt.state.single.anchor, rt.state.single.focus), (0, 4)); + assert_eq!(rt.state.single.selected(), "make"); + + // In "pills" ("@maya hello" where 0..5 is a pill), find the trailing inline box of "@maya". + let n = rt.tree.nodes.iter().find(|n| n.key.as_deref() == Some("pills")).unwrap(); + let l = n.text_layout.as_ref().and_then(crate::text::TextLayout::single).unwrap(); + let s = rt.env.scale; + let line = l.get(0).unwrap(); + let trail = line + .items() + .find_map(|it| match it { + parley::PositionedLayoutItem::InlineBox(b) if b.id & 1 == 1 => Some(b), + _ => None, + }) + .expect("pill trailing inline box"); + let r = rect_of(&rt, "pills"); + let trail_pt = (r[0] + n.inset[0] + (trail.x + trail.width * 0.5) / s, r[1] + r[3] * 0.5); + + // Single click on trailing pill padding puts caret at pill end (5); double-click selects the pill (0..5). + click(&mut rt, trail_pt); + assert_eq!((rt.state.pills.anchor, rt.state.pills.focus), (5, 5)); + click(&mut rt, trail_pt); + assert_eq!((rt.state.pills.anchor, rt.state.pills.focus), (0, 5)); + assert_eq!(rt.state.pills.selected(), "@maya"); +} + +#[test] +fn input_press_and_drag_selection_do_not_fire_on_press_or_on_drag() { + let mut rt = runtime(); + let p_make = point_at_byte(&rt, "single", 1); + let p_title = point_at_byte(&rt, "single", 11); + + // Plain click on an input with .on_press and .on_drag focuses and places the caret without firing either. + click(&mut rt, p_make); + assert_eq!(rt.state.presses, 0); + assert!(rt.state.drags.is_empty()); + + // Dragging a selection inside the input does not fire .on_press or .on_drag either. + rt.frame(1.0); + rt.pointer_down(p_make.0, p_make.1); + rt.frame(1.0 / 60.0); + rt.pointer_move(p_title.0, p_title.1); + rt.pointer_up(p_title.0, p_title.1); + rt.frame(1.0 / 60.0); + assert!(rt.state.single.anchor < rt.state.single.focus); + assert_eq!(rt.state.presses, 0); + assert!(rt.state.drags.is_empty()); +} + +#[test] +fn focus_loss_and_input_removal_clear_active_drag_and_drop_queued_drag_steps() { + let mut rt = runtime(); + let p_make = point_at_byte(&rt, "single", 1); + let p_the = point_at_byte(&rt, "single", 6); + let p_smaller = point_at_byte(&rt, "single", 18); + + // 1. Shift-click (which leaves `last = None`) + drag move queued, then focus changes before the drag runs. + click(&mut rt, p_make); + let anchor = rt.state.single.anchor; + rt.physical_input(PhysicalInput::Modifiers(Mods { shift: true, ..Mods::default() })); + rt.pointer_down(p_the.0, p_the.1); + rt.frame(1.0 / 60.0); + rt.physical_input(PhysicalInput::Modifiers(Mods::default())); + let after_shift = (rt.state.single.anchor, rt.state.single.focus); + assert_eq!(after_shift.0, anchor); + assert!(rt.edit.input_click.dragging_path().is_some()); + + // Queue a drag move, then lose focus before the frame drains the queue: the queued drag step is dropped. + rt.pointer_move(p_smaller.0, p_smaller.1); + rt. set_focus(None, false); + rt.frame(1.0 / 60.0); + assert!(rt.edit.input_click.dragging_path().is_none()); + assert_eq!((rt.state.single.anchor, rt.state.single.focus), after_shift); + rt.pointer_up(p_smaller.0, p_smaller.1); + rt.frame(1.0 / 60.0); + + // 2. Drag past CLICK_SLOP (clearing `last`), then unmount the input mid-drag and remount it while held. + rt.frame(1.0); + rt.pointer_down(p_make.0, p_make.1); + rt.frame(1.0 / 60.0); + rt.pointer_move(p_the.0, p_the.1); + rt.frame(1.0 / 60.0); + let before_unmount = (rt.state.single.anchor, rt.state.single.focus); + assert!(before_unmount.0 < before_unmount.1); + + rt.update(|s, tx| { + s.show_single = false; + tx.instant(); + }); + rt.frame(1.0 / 60.0); + assert!(rt.edit.input_click.dragging_path().is_none(), "unmounting the dragged input clears dragging"); + + rt.update(|s, tx| { + s.show_single = true; + s.single.focused = true; + tx.instant(); + }); + rt.frame(1.0 / 60.0); + rt.pointer_move(p_smaller.0, p_smaller.1); + rt.pointer_up(p_smaller.0, p_smaller.1); + rt.frame(1.0 / 60.0); + assert_eq!((rt.state.single.anchor, rt.state.single.focus), before_unmount); +} + +#[test] +fn cancel_pointer_and_window_focus_loss_clear_multiclick_history() { + let mut rt = runtime(); + let pt = point_at_byte(&rt, "single", 2); + + // 1. cancel_pointer() between two quick clicks prevents double-click word selection. + click(&mut rt, pt); + assert_eq!(rt.state.single.anchor, rt.state.single.focus); + rt.cancel_pointer(); + click(&mut rt, pt); + assert_eq!(rt.state.single.anchor, rt.state.single.focus); + + // 2. Losing and regaining window focus between two quick clicks prevents double-click word selection. + rt.frame(1.0); + rt.window_focus(true); + rt.frame(1.0 / 60.0); + click(&mut rt, pt); + assert_eq!(rt.state.single.anchor, rt.state.single.focus); + rt.window_focus(false); + rt.window_focus(true); + rt.frame(1.0 / 60.0); + click(&mut rt, pt); + assert_eq!(rt.state.single.anchor, rt.state.single.focus); +} + +#[test] +fn custom_input_on_key_handler_resets_multiclick_history() { + let mut rt = runtime(); + let pt = point_at_byte(&rt, "single", 2); + + click(&mut rt, pt); + assert_eq!(rt.state.single.anchor, rt.state.single.focus); + + // Key::Function(2) is consumed by single's custom `.on_key` handler after inserting "!". + rt.key(KeyEvent { key: Key::Function(2), mods: Mods::default() }); + rt.frame(1.0 / 60.0); + assert!(rt.state.single.text.contains('!')); + + // Clicking again immediately within double_click_interval is a single click, not a word selection. + click(&mut rt, pt); + assert_eq!(rt.state.single.anchor, rt.state.single.focus); +} + +#[test] +fn presses_land_on_targets_inside_a_scrolled_viewport() { + fn view(_: &Vec<usize>, _: &mut Cx<Vec<usize>>) -> El { + let rows = (0..10).map(|i| crate::el().key(format!("row{i}")).w_full().h(50.0).on_press(move |s: &mut Vec<usize>| s.push(i))); + col().size(200.0, 100.0).scroll(crate::ScrollSpec { stick_bottom: false }).child(col().w_full().children(rows)) + } + let mut rt = Runtime::new(Vec::new(), view, (200.0, 100.0), Env { system_dark: true, scale: 1.0 }); + rt.frame(0.0); + rt.pointer_move(100.0, 25.0); + rt.wheel(100.0, 25.0, -200.0); + for _ in 0..240 { + rt.frame(1.0 / 120.0); + } + rt.pointer_move(100.0, 25.0); + rt.pointer_down(100.0, 25.0); + rt.pointer_up(100.0, 25.0); + rt.frame(1.0 / 120.0); + assert_eq!(rt.state, [4]); +} + +#[test] +fn a_field_that_stops_following_its_press_keeps_the_press_until_release() { + let mut c = InputClick::default(); + c.capture = Capture::Held { dragging: Some("field".into()) }; + c.steps.push_back(("field".into(), Step::Drag)); + c.on_focus_change(Some("other")); + assert!(c.captured() && c.dragging_path().is_none(), "focus left: the drag stops, the press stays the field's"); + assert!(matches!(c.steps.front(), Some((_, Step::Cancelled))), "its queued drag step does nothing"); + assert!(c.end_press()); + assert!(!c.captured() && !c.end_press(), "the release ends it once"); +} + +#[test] +fn clicking_centered_end_aligned_rtl_and_multiline_inputs_hits_drawn_glyphs() { + struct AlignForm { + centered: TextEdit, + end: TextEdit, + rtl: TextEdit, + multi: TextEdit, + } + fn align_view(s: &AlignForm, _: &mut Cx<AlignForm>) -> El { + let st = style(); + col().w_full().h_full().padding(10.0).gap(8.0) + .child(text_input(&s.centered, st).single_line().align(crate::Align::Center).px(8.0) + .key("centered").size(300.0, 32.0).on_edit(|s: &mut AlignForm| &mut s.centered)) + .child(text_input(&s.end, st).single_line().align(crate::Align::End).px(8.0) + .key("end").size(300.0, 32.0).on_edit(|s: &mut AlignForm| &mut s.end)) + .child(text_input(&s.rtl, st).single_line().dir(crate::Direction::Rtl).px(8.0) + .key("rtl").size(300.0, 32.0).on_edit(|s: &mut AlignForm| &mut s.rtl)) + .child(text_input(&s.multi, st).px(8.0) + .key("multi").size(300.0, 80.0).on_edit(|s: &mut AlignForm| &mut s.multi)) + } + let rtl_text = "مرحبا بالعالم"; + let mut rt = Runtime::new( + AlignForm { + centered: TextEdit::new("ABCDEFGH"), + end: TextEdit::new("ABCDEFGH"), + rtl: TextEdit::new(rtl_text), + multi: TextEdit::new("Hello world\nSecond line"), + }, + align_view, + (340.0, 260.0), + Env::new(true, 1.0), + ); + rt.frame(0.0); + + // Drawn window coordinates of byte `byte` inside field `key`, computed by the canonical paint rule. + let drawn_byte_pt = |rt: &Runtime<AlignForm>, key: &str, byte: usize| -> (f32, f32) { + let i = rt.tree.nodes.iter().position(|n| n.key.as_deref() == Some(key)).unwrap(); + let n = &rt.tree.nodes[i]; + let spec = n.text.as_ref().unwrap(); + let flow = n.text_layout.as_ref().unwrap().view(); + let s = rt.env.scale; + let rect = rt.drawn_box(i); + let [ox, oy] = links::origin(n, spec, flow, rect, s, 1.0); + let bb = flow.caret(byte, parley::Affinity::Downstream, 1.5 * s); + (ox + bb.x0 as f32 / s + 0.25, oy + ((bb.y0 + bb.y1) * 0.5) as f32 / s) + }; + + // Centered single-line input: click at byte 4. + let pt = drawn_byte_pt(&rt, "centered", 4); + rt.pointer_move(pt.0, pt.1); + rt.pointer_down(pt.0, pt.1); + rt.pointer_up(pt.0, pt.1); + rt.frame(1.0 / 60.0); + assert_eq!(rt.state.centered.focus, 4, "centered single-line click at drawn byte 4"); + + // Secondary click (field_menu) on centered input at byte 2 moves caret to byte 2. + let pt2 = drawn_byte_pt(&rt, "centered", 2); + rt.pointer_move(pt2.0, pt2.1); + rt.secondary_down(pt2.0, pt2.1); + rt.secondary_up(pt2.0, pt2.1); + rt.frame(1.0 / 60.0); + assert_eq!(rt.state.centered.focus, 2, "centered field_menu right-click at drawn byte 2"); + rt.resolve_popup(None).ok(); + + // End-aligned single-line input: click at byte 2. + let pt = drawn_byte_pt(&rt, "end", 2); + rt.pointer_move(pt.0, pt.1); + rt.pointer_down(pt.0, pt.1); + rt.pointer_up(pt.0, pt.1); + rt.frame(1.0 / 60.0); + assert_eq!(rt.state.end.focus, 2, "end-aligned single-line click at drawn byte 2"); + + // RTL single-line input: click at the byte boundary after "مرحبا " (right-aligned from x1). + let rtl_byte = "مرحبا ".len(); + let pt = drawn_byte_pt(&rt, "rtl", rtl_byte); + rt.pointer_move(pt.0, pt.1); + rt.pointer_down(pt.0, pt.1); + rt.pointer_up(pt.0, pt.1); + rt.frame(1.0 / 60.0); + assert_eq!(rt.state.rtl.focus, rtl_byte, "RTL single-line click at drawn byte {rtl_byte}"); + + // Multi-line input ignores any single-line `input_scroll` entry for its path. + let multi_path = rt.tree.nodes.iter().find(|n| n.key.as_deref() == Some("multi")).unwrap().path.clone(); + rt.edit.input_scroll.insert(multi_path, 150.0); + let pt = drawn_byte_pt(&rt, "multi", 2); + rt.pointer_move(pt.0, pt.1); + rt.pointer_down(pt.0, pt.1); + rt.pointer_up(pt.0, pt.1); + rt.frame(1.0 / 60.0); + assert_eq!(rt.state.multi.focus, 2, "multi-line input click must ignore single-line input_scroll"); +} diff --git a/app/vendor/rune/crates/rune/src/runtime/interaction.rs b/app/vendor/rune/crates/rune/src/runtime/interaction.rs new file mode 100644 index 0000000..40b4034 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/interaction.rs @@ -0,0 +1,162 @@ +//! The runtime's side of interaction timing (`tooling::interaction`): naming the route and +//! control each input action reached, and finishing a timed frame once its host submits it. +use std::cmp::Reverse; +use std::sync::Arc; + +use super::*; +use crate::tooling::interaction::{self, Finished, Note, Slow}; + +/// A keyed ancestor covering at least this share of the window is a page. +const PAGE_AREA: f32 = 0.5; + +impl types::TreeState { + /// The innermost keyed element around node `i`, `i` included, that covers a page's share + /// of the window. + fn page_of(&self, mut i: usize, viewport: (f32, f32)) -> Option<usize> { + let area = (viewport.0 * viewport.1 * PAGE_AREA).max(1.0); + loop { + let n = &self.nodes[i]; + let [x0, y0, x1, y1] = n.target; + if n.key.is_some() && (x1 - x0) * (y1 - y0) >= area { return Some(i); } + i = n.parent?; + } + } + + /// The keyed subtrees with the most nodes the last commit rebuilt rather than reused from a + /// `memo`, largest first; each the most specific keyed element holding nearly all of its + /// count. Runs only for a slow interaction. + fn rebuilt_subtrees(&self, reused_spans: &[(usize, usize)], mut label: impl FnMut(&str) -> Arc<str>) -> Vec<(Arc<str>, usize)> { + let n = self.nodes.len(); + let mut reused = vec![false; n]; + for &(start, len) in reused_spans { + for r in reused.iter_mut().skip(start).take(len) { *r = true; } + } + let mut count = vec![0usize; n]; + for i in (0..n).filter(|&i| !reused[i]) { + let mut at = Some(i); + while let Some(j) = at { + if self.nodes[j].key.is_some() { count[j] += 1; } + at = self.nodes[j].parent; + } + } + // The largest count among each keyed element's nearest keyed descendants. + let mut inner = vec![0usize; n]; + for i in (0..n).filter(|&i| count[i] > 0 && self.nodes[i].key.is_some()) { + let mut at = self.nodes[i].parent; + while let Some(j) = at { + if self.nodes[j].key.is_some() { inner[j] = inner[j].max(count[i]); break; } + at = self.nodes[j].parent; + } + } + let mut top: Vec<usize> = (0..n).filter(|&i| count[i] > 0 && self.nodes[i].key.is_some() && (inner[i] as f64) < 0.9 * count[i] as f64).collect(); + top.sort_by_key(|&i| Reverse(count[i])); + top.truncate(3); + top.into_iter().map(|i| (label(&self.nodes[i].path), count[i])).collect() + } +} + +impl RuntimeCore { + /// What `action` was, when timing is on and a person caused it; `None` for everything else + /// (layout reports, timers, clipboard and dialog answers). + pub(super) fn interaction_note(&mut self, action: &Action) -> Option<Note> { + if !interaction::on() { return None; } + let focused = self.kbd.focus.path(); + let editing = || focused.and_then(|p| self.tree.index_of_path(p)).is_some_and(|i| self.tree.nodes[i].input.is_some()); + let (name, rank, path): (&'static str, u8, Option<&str>) = match action { + Action::Press(p, ..) => ("on_press", 3, Some(p)), + Action::DoublePress(p) => ("on_double_press", 3, Some(p)), + Action::SecondaryPress(p, _) => ("on_secondary_press", 3, Some(p)), + Action::MiddlePress(p) => ("on_middle_press", 3, Some(p)), + Action::Link(p, ..) => ("on_link", 3, Some(p)), + Action::LinkSecondary(p, ..) => ("on_link_secondary", 3, Some(p)), + Action::Dismiss(p) => ("dismiss", 3, Some(p)), + Action::Key { .. } | Action::Physical(..) => (if editing() { "key_edit" } else { "key" }, 3, focused), + Action::Ime(_) | Action::FinishIme => ("key_edit", 3, focused), + Action::Paste(..) => ("paste", 3, focused), + Action::Files(_) => ("on_drop_files", 3, None), + Action::DragStart(p) => ("on_drag_start", 2, Some(p)), + Action::Drag(p, ..) | Action::DragRepeat(p, ..) => ("on_drag", 2, Some(p)), + Action::DragEnd(p, _) => ("on_drag_end", 2, Some(p)), + Action::Wheel { chain, .. } => ("on_wheel", 2, chain.first().map(String::as_str)), + Action::Gesture(chain, _) => ("gesture", 2, chain.first().map(String::as_str)), + Action::Hover(p) => ("on_hover", 1, Some(p)), + Action::HoverChange(p, _) => ("on_hover_change", 1, Some(p)), + Action::PointerMove(p, _) => ("on_pointer_move", 1, Some(p)), + _ => return None, + }; + let at = path.and_then(|p| self.tree.index_of_path(p)); + let page = at.and_then(|i| self.tree.page_of(i, self.viewport)).map(|i| self.tree.nodes[i].path.as_str()); + let modal = self.active_modal().map(|i| self.tree.nodes[i].path.as_str()); + let names = &mut self.commit.watch.interaction.names; + let control = match path { + Some(p) => names.control(p), + None => names.fixed("window"), + }; + let route = names.route(page, modal); + let note = Note { route, control, action: name, rank }; + if self.commit.watch.interaction.breached(&note) { interaction::hurry(); } + Some(note) + } + + /// A frame starts. + pub(super) fn interaction_frame_begins(&mut self) { + if !interaction::on() { return; } + let queued = !self.frame.queue.is_empty(); + if let Some(finished) = self.commit.watch.interaction.frame_begins(queued) { self.interaction_finished(finished); } + } + + /// An action that `interaction_note` named ran its handlers from `started`. + pub(super) fn interaction_ran(&mut self, note: Note, started: crate::time::Instant) { + let handler = started.elapsed(); + self.commit.watch.interaction.noted(note, crate::input::time::current(), started, handler); + } + + /// A commit in a timed frame reused `spans` of nodes from `memo`s. + pub(super) fn interaction_reused(&mut self, spans: &[super::memo_reuse::ReusedSpan]) { + let reused = &mut self.commit.watch.interaction.reused; + reused.clear(); + reused.extend(spans.iter().map(|s| (s.new_start, s.len))); + } + + /// The frame is built, ready for its host to draw. + pub(super) fn interaction_built(&mut self) { + if !interaction::on() { return; } + if let Some(frame) = self.commit.watch.interaction.built(self.stats.shaped, self.tree.nodes.len()) { interaction::send_frame(frame); } + } + + /// The host submitted the frame's commands at `submitted`, to show at `presents_at` when a + /// display link paces it. + pub(crate) fn interaction_presented(&mut self, submitted: crate::time::Instant, presents_at: Option<crate::time::Instant>) { + if !interaction::on() { return; } + if let Some(finished) = self.commit.watch.interaction.finish(submitted, presents_at) { self.interaction_finished(finished); } + } + + /// The process is about to exit: sends what's counted and waits briefly for it to go. + pub(crate) fn interaction_flush(&mut self) { + if !interaction::on() { return; } + if let Some(finished) = self.commit.watch.interaction.frame_begins(false) { self.interaction_finished(finished); } + self.commit.watch.interaction.roll(true); + interaction::flush(); + } + + #[cfg(test)] + pub(crate) fn interaction_tracker(&mut self) -> &mut interaction::Tracker { &mut self.commit.watch.interaction } + + fn interaction_finished(&mut self, f: Finished) { + if f.slow { + let interaction = &mut self.commit.watch.interaction; + let rebuilt = self.tree.rebuilt_subtrees(&interaction.reused, |path| interaction.names.control(path).text); + let reused = interaction.reused.iter().map(|r| r.1).sum(); + let Finished { timed, built, phases, shaped, submitted, present, cause, .. } = f; + interaction::send(Slow { + route: timed.note.route.text, control: timed.note.control.text, action: timed.note.action, + arrived: timed.arrived, frame_start: timed.frame_start, built, submitted, present, + handler_ms: timed.handler_ms, phases, why: timed.why, commits: timed.commits, shaped, + nodes: self.tree.nodes.len(), reused, rebuilt, + cpu_ms: f.cpu_ms, cause: cause.unwrap_or(interaction::Cause::Queued), stacks: f.stacks, + }); + } + self.commit.watch.interaction.reused.clear(); + self.commit.watch.interaction.roll(false); + } +} diff --git a/app/vendor/rune/crates/rune/src/runtime/key_index.rs b/app/vendor/rune/crates/rune/src/runtime/key_index.rs new file mode 100644 index 0000000..f6f5f2b --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/key_index.rs @@ -0,0 +1,154 @@ +//! Keys to nodes, so layout reads and highlight lookups find the element or text highlight a +//! key names without scanning the tree. Scroll frames check every layout read against the same +//! nodes, so the index of the current nodes is kept until a commit or a prune replaces them. + +use std::hash::BuildHasher; + +use super::*; + +/// Lookups up to this many scan the nodes rather than index them, unless the same nodes come +/// round again: indexing every key of a large tree costs more than a handful of scans. +pub(super) const SCAN_READS: usize = 8; + +const NONE: u32 = u32::MAX; + +/// Nodes by key and by highlight key, each by the key's hash. A lookup still checks each +/// candidate with [`crate::flight::selects`], so two keys sharing a hash only share a chain. +#[derive(Default)] +pub(super) struct KeyIndex { + /// The nodes the index describes: commit, count and buffer. + built: Option<NodesId>, + /// The nodes the last lookups were for; seeing them again builds the index. + seen: Option<NodesId>, + /// Each key's first node, and the next node with a key of the same hash. + keys: HashMap<u64, u32>, + next_key: Vec<u32>, + /// Each highlight key's first entry, and entries of `(node, next entry)`. + marks: HashMap<u64, u32>, + mark_chain: Vec<(u32, u32)>, +} + +#[derive(Clone, Copy, PartialEq, Eq)] +struct NodesId { + commit: u64, + len: usize, + at: *const Node, +} + +impl NodesId { + fn of(nodes: &[Node], commit: u64) -> Self { + NodesId { commit, len: nodes.len(), at: nodes.as_ptr() } + } +} + +fn hash(key: &str) -> u64 { + rustc_hash::FxBuildHasher.hash_one(key) +} + +/// `selector` and each tail of it after a `/`: the keys a node or highlight it picks can have. +fn tails(selector: &str) -> impl Iterator<Item = &str> { + std::iter::once(selector).chain(selector.match_indices('/').map(|(at, _)| &selector[at + 1..])) +} + +impl KeyIndex { + /// An index of `nodes`, for lookups that won't come round again. + pub(super) fn of(nodes: &[Node]) -> Self { + let mut index = KeyIndex::default(); + index.build(nodes); + index + } + + /// Before `lookups` lookups in `nodes` (the runtime's current nodes as of `commit`): + /// builds the index when there are enough of them, or when the last lookups were for the + /// same nodes. + pub(super) fn prepare(&mut self, nodes: &[Node], commit: u64, lookups: usize) { + let id = NodesId::of(nodes, commit); + if self.built != Some(id) && (lookups > SCAN_READS || self.seen == Some(id)) { + self.build(nodes); + self.built = Some(id); + } + self.seen = Some(id); + } + + /// The index, when it describes `nodes` as of `commit`. + pub(super) fn get(&self, nodes: &[Node], commit: u64) -> Option<&Self> { + (self.built == Some(NodesId::of(nodes, commit))).then_some(self) + } + + /// The nodes changed under the same commit. + pub(super) fn forget(&mut self) { + self.built = None; + self.seen = None; + } + + fn build(&mut self, nodes: &[Node]) { + self.built = None; + self.keys.clear(); + self.next_key.clear(); + self.next_key.resize(nodes.len(), NONE); + self.marks.clear(); + self.mark_chain.clear(); + for (i, n) in nodes.iter().enumerate().rev() { + if let Some(key) = &n.key { + self.next_key[i] = self.keys.insert(hash(key), i as u32).unwrap_or(NONE); + } + let Some(text) = n.text.as_ref() else { continue }; + for key in text.cold.highlights.iter().filter_map(|h| h.key.as_deref()) { + let first = self.marks.entry(hash(key)).or_insert(NONE); + if *first != NONE && self.mark_chain[*first as usize].0 == i as u32 { continue; } + self.mark_chain.push((i as u32, *first)); + *first = (self.mark_chain.len() - 1) as u32; + } + } + } + + /// The first node `selector` picks (see [`crate::flight::selects`]). + pub(super) fn first(&self, nodes: &[Node], selector: &str) -> Option<usize> { + tails(selector).filter_map(|key| { + let mut i = *self.keys.get(&hash(key))?; + while i != NONE { + let n = &nodes[i as usize]; + if crate::flight::selects(selector, &n.path, n.key.as_deref()) { return Some(i as usize); } + i = self.next_key[i as usize]; + } + None + }).min() + } + + /// The nodes holding a highlight `selector` may pick, in order. Each still needs checking. + pub(super) fn marked(&self, selector: &str) -> Vec<usize> { + let mut out = Vec::new(); + for key in tails(selector) { + let Some(&first) = self.marks.get(&hash(key)) else { continue }; + let mut e = first; + while e != NONE { + let (node, next) = self.mark_chain[e as usize]; + out.push(node as usize); + e = next; + } + } + out.sort_unstable(); + out.dedup(); + out + } +} + +/// The first node `selector` picks, by scanning `nodes`. +pub(super) fn scan_first(nodes: &[Node], selector: &str) -> Option<usize> { + nodes.iter().position(|n| n.key.as_deref().is_some_and(|key| tails(selector).any(|t| t == key)) + && crate::flight::selects(selector, &n.path, n.key.as_deref())) +} + +impl RuntimeCore { + /// The kept index, when `nodes` are the current nodes it describes. + #[inline] + pub(super) fn key_index_for(&self, nodes: &[Node]) -> Option<&KeyIndex> { + self.tree.key_index_for(nodes, self.commit.commit_gen()) + } + + /// `self.nodes` changed without a commit: kept per-node answers no longer hold. + #[inline] + pub(super) fn nodes_replaced(&mut self) { + self.tree.nodes_replaced(); + } +} diff --git a/app/vendor/rune/crates/rune/src/runtime/layer_cache_tests.rs b/app/vendor/rune/crates/rune/src/runtime/layer_cache_tests.rs new file mode 100644 index 0000000..a7a9510 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/layer_cache_tests.rs @@ -0,0 +1,901 @@ +use super::*; +use super::tests::{near, pixels, rgba}; +use crate::{Color, Cx, El, Env, Live, Runtime, el}; + +#[test] +fn cache_matches_uncached_at_rest_and_skips_rerasterize_on_ancestor_live_offset() { + type State = (bool, Live<[f32; 2]>); + fn crisp_view(s: &State, _: &mut Cx<State>) -> El { + let mut card = crate::col() + .size(40.0, 28.0) + .padding(4.0) + .gap(2.0) + .fill(Color { r: 0.0, g: 0.0, b: 1.0, a: 1.0 }) + .child(el().size(24.0, 8.0).fill(Color { r: 1.0, g: 0.0, b: 0.0, a: 1.0 })) + .child(el().size(16.0, 8.0).fill(Color::WHITE)); + if s.0 { + card = card.cache(); + } + el().size(64.0, 48.0).padding(6.0).live_offset(&s.1).child(card) + } + fn view(s: &State, _: &mut Cx<State>) -> El { + let mut card = crate::col() + .size(40.0, 28.0) + .padding(4.0) + .gap(2.0) + .fill(Color { r: 0.2, g: 0.35, b: 0.6, a: 1.0 }) + .radius(6.0) + .border(1.0, Color::WHITE) + .child(crate::text("Cached").color(Color::WHITE)) + .child(el().size(24.0, 8.0).fill(Color { r: 0.9, g: 0.3, b: 0.2, a: 1.0 }).radius(3.0)); + if s.0 { + card = card.cache(); + } + el().size(64.0, 48.0) + .padding(6.0) + .live_offset(&s.1) + .child(card) + } + let gpu = Gpu::headless(); + let target = Offscreen::new(&gpu.device, 64, 48); + + // 1. Crisp card is byte-for-byte identical between cached and uncached at rest and under pan. + let mut rt_u = Runtime::new((false, Live::new([0.0, 0.0])), crisp_view, (64.0, 48.0), Env { scale: 1.0, system_dark: true }); + let mut ren_u = Renderer::new(&gpu.device, OFFSCREEN_FORMAT); + rt_u.frame(0.0); + ren_u.prepare(&gpu.device, &gpu.queue, &mut rt_u.text.atlas, &rt_u.instances, (64, 48)); + let mut rt_c = Runtime::new((true, Live::new([0.0, 0.0])), crisp_view, (64.0, 48.0), Env { scale: 1.0, system_dark: true }); + let mut ren_c = Renderer::new(&gpu.device, OFFSCREEN_FORMAT); + rt_c.frame(0.0); + ren_c.prepare(&gpu.device, &gpu.queue, &mut rt_c.text.atlas, &rt_c.instances, (64, 48)); + assert_eq!(pixels(&gpu, &ren_c, &target), pixels(&gpu, &ren_u, &target), "cached vs uncached must be pixel-for-pixel identical at rest"); + + // 2. Rich card with text and antialiased rounded corners under ancestor live_offset pan. + let off_uncached = Live::new([0.0, 0.0]); + let mut rt_uncached = Runtime::new((false, off_uncached.clone()), view, (64.0, 48.0), Env { scale: 1.0, system_dark: true }); + let mut ren_uncached = Renderer::new(&gpu.device, OFFSCREEN_FORMAT); + rt_uncached.frame(0.0); + ren_uncached.prepare(&gpu.device, &gpu.queue, &mut rt_uncached.text.atlas, &rt_uncached.instances, (64, 48)); + let px_uncached = pixels(&gpu, &ren_uncached, &target); + + let off_cached = Live::new([0.0, 0.0]); + let mut rt_cached = Runtime::new((true, off_cached.clone()), view, (64.0, 48.0), Env { scale: 1.0, system_dark: true }); + let mut ren_cached = Renderer::new(&gpu.device, OFFSCREEN_FORMAT); + rt_cached.frame(0.0); + ren_cached.prepare(&gpu.device, &gpu.queue, &mut rt_cached.text.atlas, &rt_cached.instances, (64, 48)); + assert_eq!(ren_cached.layer_stats().targets, 1); + assert_eq!(ren_cached.layer_stats().extra_passes, 1, "initial frame rasterizes the cache"); + let px_cached = pixels(&gpu, &ren_cached, &target); + let max_diff = px_cached.iter().zip(&px_uncached).map(|(a, b)| a.abs_diff(*b)).max().unwrap_or(0); + assert!(max_diff <= 1, "cached vs uncached at rest max_diff={max_diff}"); + assert_eq!(rt_cached.elements().len(), rt_uncached.elements().len(), "elements() unchanged"); + + // Panning via an ancestor's live_offset must elide child instances and not re-rasterize. + for delta in [[4.0, 2.0], [10.0, 6.0], [3.0, 8.0], [0.0, 0.0]] { + off_uncached.set(delta); + rt_uncached.frame(1.0 / 60.0); + ren_uncached.prepare(&gpu.device, &gpu.queue, &mut rt_uncached.text.atlas, &rt_uncached.instances, (64, 48)); + let want = pixels(&gpu, &ren_uncached, &target); + + off_cached.set(delta); + rt_cached.frame(1.0 / 60.0); + assert_eq!(rt_cached.instances.len(), 2, "cached subtree elides to [KIND_LAYER, KIND_LAYER_END]"); + ren_cached.prepare(&gpu.device, &gpu.queue, &mut rt_cached.text.atlas, &rt_cached.instances, (64, 48)); + assert_eq!(ren_cached.layer_stats().extra_passes, 0, "ancestor live_offset must not re-rasterize"); + assert_eq!(ren_cached.layer_stats().allocations, 1); + let got = pixels(&gpu, &ren_cached, &target); + let max_diff = got.iter().zip(&want).map(|(a, b)| a.abs_diff(*b)).max().unwrap_or(0); + assert!(max_diff <= 1, "panned cached output must match uncached at {delta:?} (max_diff={max_diff})"); + if delta == [0.0, 0.0] { + assert_eq!(got, px_cached, "returning to origin is bit-for-bit identical"); + } + } +} + +#[test] +fn cache_invalidates_on_state_and_hover_changes() { + fn view(active: &bool, _: &mut Cx<bool>) -> El { + let fill = if *active { + Color { r: 0.1, g: 0.8, b: 0.2, a: 1.0 } + } else { + Color { r: 0.8, g: 0.1, b: 0.2, a: 1.0 } + }; + el().size(32.0, 32.0).child( + el().size(24.0, 24.0) + .cache() + .child( + el().key("btn") + .size(24.0, 24.0) + .fill(fill) + .hover(Color { r: 0.1, g: 0.2, b: 0.9, a: 1.0 }) + .on_press(|active: &mut bool| *active = !*active), + ), + ) + } + let gpu = Gpu::headless(); + let mut renderer = Renderer::new(&gpu.device, OFFSCREEN_FORMAT); + let target = Offscreen::new(&gpu.device, 32, 32); + let mut rt = Runtime::new(false, view, (32.0, 32.0), Env { scale: 1.0, system_dark: true }); + + // Frame 1: initial rasterize (red). + rt.frame(0.0); + renderer.prepare(&gpu.device, &gpu.queue, &mut rt.text.atlas, &rt.instances, (32, 32)); + assert_eq!(renderer.layer_stats().extra_passes, 1); + let out = pixels(&gpu, &renderer, &target); + near(&out[(12 * 32 + 12) * 4..(12 * 32 + 13) * 4], rgba([0.8, 0.1, 0.2, 1.0])); + + // Frame 2: steady at rest (cache hit). + rt.frame(1.0 / 60.0); + renderer.prepare(&gpu.device, &gpu.queue, &mut rt.text.atlas, &rt.instances, (32, 32)); + assert_eq!(renderer.layer_stats().extra_passes, 0); + + // Frame 3: state change inside cached subtree invalidates and re-renders once settled (green). + rt.state = true; + rt.invalidate(); + rt.frame(1.0); + renderer.prepare(&gpu.device, &gpu.queue, &mut rt.text.atlas, &rt.instances, (32, 32)); + assert_eq!(renderer.layer_stats().extra_passes, 1, "state change must invalidate cache"); + let out = pixels(&gpu, &renderer, &target); + near(&out[(12 * 32 + 12) * 4..(12 * 32 + 13) * 4], rgba([0.1, 0.8, 0.2, 1.0])); + + // Frame 4: hover inside cached subtree invalidates immediately and re-renders (blue hover). + rt.pointer_move(12.0, 12.0); + rt.frame(1.0 / 60.0); + renderer.prepare(&gpu.device, &gpu.queue, &mut rt.text.atlas, &rt.instances, (32, 32)); + assert_eq!(renderer.layer_stats().extra_passes, 1, "hover change must invalidate cache"); + let out = pixels(&gpu, &renderer, &target); + near(&out[(12 * 32 + 12) * 4..(12 * 32 + 13) * 4], rgba([0.1, 0.2, 0.9, 1.0])); + + // Frame 5: settled while hovered hits the cache again. + rt.frame(1.0 / 60.0); + renderer.prepare(&gpu.device, &gpu.queue, &mut rt.text.atlas, &rt.instances, (32, 32)); + assert_eq!(renderer.layer_stats().extra_passes, 0, "settled hover must hit cache"); +} + +#[test] +fn cache_draws_live_while_subtree_animates_and_recaches_when_settled() { + fn view(moved: &bool, _: &mut Cx<bool>) -> El { + let x = if *moved { 16.0 } else { 0.0 }; + el().size(48.0, 24.0).child( + el().size(40.0, 20.0) + .cache() + .child( + el().key("chip") + .size(16.0, 16.0) + .absolute(x, 0.0) + .motion(crate::Spring::DEFAULT) + .fill(Color { r: 1.0, g: 0.0, b: 0.0, a: 1.0 }), + ), + ) + } + let gpu = Gpu::headless(); + let mut renderer = Renderer::new(&gpu.device, OFFSCREEN_FORMAT); + let target = Offscreen::new(&gpu.device, 48, 24); + let mut rt = Runtime::new(false, view, (48.0, 24.0), Env { scale: 1.0, system_dark: true }); + + // Initial rest: cached. + rt.frame(0.0); + renderer.prepare(&gpu.device, &gpu.queue, &mut rt.text.atlas, &rt.instances, (48, 24)); + assert_eq!(renderer.layer_stats().targets, 1); + assert_eq!(renderer.layer_stats().extra_passes, 1); + rt.frame(1.0 / 60.0); + renderer.prepare(&gpu.device, &gpu.queue, &mut rt.text.atlas, &rt.instances, (48, 24)); + assert_eq!(renderer.layer_stats().extra_passes, 0); + + // Start animation inside cached subtree: must bypass cache and draw live without re-rasterizing offscreen targets. + rt.state = true; + rt.invalidate(); + rt.frame(0.0); + for _ in 0..3 { + rt.frame(0.05); + assert!(rt.instances.iter().all(|i| i.params[1] != KIND_LAYER), "must draw live while animating"); + renderer.prepare(&gpu.device, &gpu.queue, &mut rt.text.atlas, &rt.instances, (48, 24)); + assert_eq!(renderer.layer_stats().extra_passes, 0, "no offscreen pass thrash while animating"); + } + + // Advance past animation duration so it settles: re-caches once at the new position, then hits cache. + rt.frame(2.0); + assert!(rt.instances.iter().any(|i| i.params[1] == KIND_LAYER && i.params[3] == 1.0), "re-cached once settled"); + renderer.prepare(&gpu.device, &gpu.queue, &mut rt.text.atlas, &rt.instances, (48, 24)); + assert_eq!(renderer.layer_stats().extra_passes, 1, "rasterize once on settle"); + let out = pixels(&gpu, &renderer, &target); + near(&out[(8 * 48 + 24) * 4..(8 * 48 + 25) * 4], rgba([1.0, 0.0, 0.0, 1.0])); + + rt.frame(1.0 / 60.0); + renderer.prepare(&gpu.device, &gpu.queue, &mut rt.text.atlas, &rt.instances, (48, 24)); + assert_eq!(renderer.layer_stats().extra_passes, 0, "subsequent frame hits settled cache"); +} + +#[test] +fn cache_rerasterizes_at_new_resolution_after_ancestor_scale_settles() { + fn view(scale: &Live<f32>, _: &mut Cx<Live<f32>>) -> El { + el().size(200.0, 200.0) + .padding(60.0) + .live_scale(scale) + .child( + el().size(48.0, 48.0) + .cache() + .fill(Color { r: 0.2, g: 0.5, b: 0.9, a: 1.0 }) + .child(el().size(24.0, 24.0).fill(Color::WHITE)), + ) + } + let gpu = Gpu::headless(); + let mut renderer = Renderer::new(&gpu.device, OFFSCREEN_FORMAT); + let target = Offscreen::new(&gpu.device, 200, 200); + let scale = Live::new(1.0); + let mut rt = Runtime::new(scale.clone(), view, (200.0, 200.0), Env { scale: 1.0, system_dark: true }); + + // Frame 1: rasterize at 1.0x (48x48 -> 64x64 bucket). + rt.frame(0.0); + renderer.prepare(&gpu.device, &gpu.queue, &mut rt.text.atlas, &rt.instances, (200, 200)); + assert_eq!(renderer.layer_stats().extra_passes, 1); + assert_eq!(renderer.layer_stats().bytes, 64 * 64 * 8); + let _ = pixels(&gpu, &renderer, &target); + + // Frame 2: during scale gesture to 2.0x (dt = 0.016 < STATIC_SCALE_SETTLE), composites scaled without re-rasterizing. + scale.set(2.0); + rt.frame(0.016); + renderer.prepare(&gpu.device, &gpu.queue, &mut rt.text.atlas, &rt.instances, (200, 200)); + assert_eq!(renderer.layer_stats().extra_passes, 0, "composite existing texture during scale gesture"); + assert_eq!(renderer.layer_stats().bytes, 64 * 64 * 8, "still 1x texture before settle"); + + // Frame 3: after scale settles (dt = 0.15 >= STATIC_SCALE_SETTLE), re-rasterizes at 2.0x (96x96 -> 128x128 bucket). + rt.frame(0.15); + renderer.prepare(&gpu.device, &gpu.queue, &mut rt.text.atlas, &rt.instances, (200, 200)); + assert_eq!(renderer.layer_stats().extra_passes, 1, "re-rasterize at new resolution once settled"); + assert_eq!(renderer.layer_stats().bytes, 128 * 128 * 8, "upgraded to 2x texture bucket"); + let out = pixels(&gpu, &renderer, &target); + assert_eq!(out[(100 * 200 + 100) * 4 + 3], 255); + + // Frame 4: hits the new 2x cache. + rt.frame(0.016); + renderer.prepare(&gpu.device, &gpu.queue, &mut rt.text.atlas, &rt.instances, (200, 200)); + assert_eq!(renderer.layer_stats().extra_passes, 0); +} + +#[test] +fn cache_lru_eviction_under_small_budget_evicts_oldest_and_recaches_cleanly() { + fn scroll_view(offset: &Live<[f32; 2]>, _: &mut Cx<Live<[f32; 2]>>) -> El { + let card = |key: &str, y: f32, c: Color| { + el().key(key) + .size(24.0, 24.0) + .absolute(4.0, y) + .cache() + .fill(c) + .child(el().size(10.0, 10.0).fill(Color::WHITE)) + }; + el().size(32.0, 32.0).child( + el().size(32.0, 300.0) + .live_offset(offset) + .child(card("a", 0.0, Color { r: 1.0, g: 0.0, b: 0.0, a: 1.0 })) + .child(card("b", 100.0, Color { r: 0.0, g: 1.0, b: 0.0, a: 1.0 })) + .child(card("c", 200.0, Color { r: 0.0, g: 0.0, b: 1.0, a: 1.0 })), + ) + } + let gpu = Gpu::headless(); + let mut renderer = Renderer::new(&gpu.device, OFFSCREEN_FORMAT); + let one_bucket = 64 * 64 * 8; + // Budget fits at most 2 cached 64x64 textures. + renderer.set_cache_budget(one_bucket * 2); + assert_eq!(renderer.cache_budget(), one_bucket * 2); + let target = Offscreen::new(&gpu.device, 32, 32); + let offset = Live::new([0.0, 0.0]); + let mut rt = Runtime::new(offset.clone(), scroll_view, (32.0, 32.0), Env { scale: 1.0, system_dark: true }); + + // Visit card A (y=0): caches A. + rt.frame(0.0); + renderer.prepare(&gpu.device, &gpu.queue, &mut rt.text.atlas, &rt.instances, (32, 32)); + assert_eq!(renderer.layer_stats().extra_passes, 1); + assert!(renderer.layer_stats().bytes <= one_bucket * 2); + let out = pixels(&gpu, &renderer, &target); + near(&out[(16 * 32 + 16) * 4..(16 * 32 + 17) * 4], rgba([1.0, 0.0, 0.0, 1.0])); + + // Visit card B (y=-100): caches B, retains A (2 targets <= budget). + offset.set([0.0, -100.0]); + rt.frame(0.016); + renderer.prepare(&gpu.device, &gpu.queue, &mut rt.text.atlas, &rt.instances, (32, 32)); + assert_eq!(renderer.layer_stats().extra_passes, 1); + assert_eq!(renderer.layer_stats().targets, 2); + assert!(renderer.layer_stats().bytes <= one_bucket * 2); + let out = pixels(&gpu, &renderer, &target); + near(&out[(16 * 32 + 16) * 4..(16 * 32 + 17) * 4], rgba([0.0, 1.0, 0.0, 1.0])); + + // Return to card A (y=0): A is still resident in budget, so extra_passes == 0! + offset.set([0.0, 0.0]); + rt.frame(0.016); + renderer.prepare(&gpu.device, &gpu.queue, &mut rt.text.atlas, &rt.instances, (32, 32)); + assert_eq!(renderer.layer_stats().extra_passes, 0, "A was retained in budget"); + + // Now visit card C (y=-200): A was used most recently, so oldest (B) is evicted! + offset.set([0.0, -200.0]); + rt.frame(0.016); + renderer.prepare(&gpu.device, &gpu.queue, &mut rt.text.atlas, &rt.instances, (32, 32)); + assert_eq!(renderer.layer_stats().extra_passes, 1, "C rasterizes and evicts LRU B"); + assert_eq!(renderer.layer_stats().targets, 2); + assert!(renderer.layer_stats().bytes <= one_bucket * 2); + let out = pixels(&gpu, &renderer, &target); + near(&out[(16 * 32 + 16) * 4..(16 * 32 + 17) * 4], rgba([0.0, 0.0, 1.0, 1.0])); + + // Card A (y=0) is still resident (extra_passes == 0), while card B (y=-100) was evicted and re-caches cleanly! + offset.set([0.0, 0.0]); + rt.frame(0.016); + renderer.prepare(&gpu.device, &gpu.queue, &mut rt.text.atlas, &rt.instances, (32, 32)); + assert_eq!(renderer.layer_stats().extra_passes, 0, "MRU card A stayed resident"); + + offset.set([0.0, -100.0]); + rt.frame(0.016); + renderer.prepare(&gpu.device, &gpu.queue, &mut rt.text.atlas, &rt.instances, (32, 32)); + assert_eq!(renderer.layer_stats().extra_passes, 1, "evicted card B re-caches cleanly"); + let out = pixels(&gpu, &renderer, &target); + near(&out[(16 * 32 + 16) * 4..(16 * 32 + 17) * 4], rgba([0.0, 1.0, 0.0, 1.0])); +} + +/// Drives a cached and an uncached runtime through the same steps (`frames` frames each, 1/60 s +/// apart); the cached one must draw the same pixels after every frame. Returns the cached +/// renderer's stats per frame. +fn same_as_uncached<T: Clone + 'static>(state: T, view: fn(&(bool, T), &mut Cx<(bool, T)>) -> El, size: (u32, u32), + steps: &[(&str, usize, &dyn Fn(&mut Runtime<(bool, T)>))]) -> Vec<(String, LayerStats)> { + let gpu = Gpu::headless(); + let target = Offscreen::new(&gpu.device, size.0, size.1); + let env = Env { scale: 1.0, system_dark: true }; + let viewport = (size.0 as f32, size.1 as f32); + let mut runs: Vec<_> = [false, true].map(|cached| { + (Runtime::new((cached, state.clone()), view, viewport, env), Renderer::new(&gpu.device, OFFSCREEN_FORMAT)) + }).into(); + let mut stats = Vec::new(); + let initial: &dyn Fn(&mut Runtime<(bool, T)>) = &|_| {}; + for (name, frames, step) in [("rest", 2, initial)].into_iter().chain(steps.iter().copied()) { + let mut out = Vec::new(); + for (rt, _) in &mut runs { step(rt); } + for f in 0..frames { + for (rt, renderer) in &mut runs { + rt.frame(1.0 / 60.0); + renderer.prepare(&gpu.device, &gpu.queue, &mut rt.text.atlas, &rt.instances, size); + out.push(pixels(&gpu, renderer, &target)); + } + let (want, got) = (&out[out.len() - 2], &out[out.len() - 1]); + let max_diff = got.iter().zip(want).map(|(a, b)| a.abs_diff(*b)).max().unwrap_or(0); + assert!(max_diff <= 1, "{name} frame {f}: cached differs from uncached (max_diff={max_diff})"); + stats.push((format!("{name}/{f}"), runs[1].1.layer_stats())); + } + } + assert!(runs[1].0.instances.iter().any(|i| i.params[1] == KIND_LAYER && i.params[3] == 1.0), "the subtree stays cached"); + stats +} + +#[test] +fn cache_follows_press_paint_that_lands_without_a_view_run() { + fn view(s: &(bool, ()), _: &mut Cx<(bool, ())>) -> El { + let mut card = el().size(24.0, 24.0).child( + el().size(24.0, 24.0) + .fill(Color { r: 0.8, g: 0.1, b: 0.2, a: 1.0 }) + .press(Color { r: 0.1, g: 0.2, b: 0.9, a: 1.0 }) + .on_press(|_: &mut (bool, ())| {}), + ); + if s.0 { card = card.cache(); } + el().size(32.0, 32.0).child(card) + } + let stats = same_as_uncached((), view, (32, 32), &[ + ("hover", 2, &|rt| rt.pointer_move(12.0, 12.0)), + ("down", 2, &|rt| rt.pointer_down(12.0, 12.0)), + ("up", 40, &|rt| rt.pointer_up(12.0, 12.0)), + ]); + assert_eq!(stats.last().unwrap().1.extra_passes, 0, "the released card hits its cache again"); +} + +#[test] +fn cache_follows_link_hover_moving_between_links_of_one_text() { + fn view(s: &(bool, ()), _: &mut Cx<(bool, ())>) -> El { + let green = crate::LinkPaint::new().bg(Color { r: 0.0, g: 1.0, b: 0.0, a: 1.0 }); + let label = crate::text("MMMM MMMM") + .font(crate::TextStyle::new(16.0, 400.0)) + .color(Color::WHITE) + .link(crate::Link::new(0..4, "a").hover(green)) + .link(crate::Link::new(5..9, "b").hover(green)) + .on_link(|_: &mut (bool, ()), _, _| {}); + let mut card = el().size(150.0, 24.0).child(label); + if s.0 { card = card.cache(); } + el().size(160.0, 32.0).child(card) + } + same_as_uncached((), view, (160, 32), &[ + ("first link", 2, &|rt| rt.pointer_move(16.0, 10.0)), + ("second link", 2, &|rt| rt.pointer_move(90.0, 10.0)), + ]); +} + +#[test] +fn cache_follows_an_outside_hover_group_fading_its_descendants() { + fn view(s: &(bool, ()), _: &mut Cx<(bool, ())>) -> El { + let mut card = el().size(24.0, 24.0).fill(Color { r: 0.0, g: 0.0, b: 1.0, a: 1.0 }).child( + el().size(16.0, 16.0).fill(Color::WHITE).group_opacity(0.2, 1.0), + ); + if s.0 { card = card.cache(); } + el().size(64.0, 32.0).child(crate::row().size(64.0, 32.0).hover_group().child(card)) + } + same_as_uncached((), view, (64, 32), &[ + ("enter", 3, &|rt| rt.pointer_move(48.0, 16.0)), + ("leave", 12, &|rt| rt.pointer_move(200.0, 200.0)), + ]); +} + +#[test] +fn cache_redraws_a_same_length_text_change() { + fn view(s: &(bool, bool), _: &mut Cx<(bool, bool)>) -> El { + let mut card = el().size(60.0, 24.0).child(crate::text(if s.1 { "BBBB" } else { "AAAA" }).color(Color::WHITE)); + if s.0 { card = card.cache(); } + el().size(64.0, 32.0).child(card) + } + let stats = same_as_uncached(false, view, (64, 32), &[ + ("swap", 40, &|rt| { rt.state.1 = true; rt.invalidate(); }), + ]); + let passes: Vec<_> = stats.iter().map(|(_, s)| s.extra_passes).collect(); + assert_eq!(passes[..2], [1, 0]); + assert_eq!(passes[2..].iter().sum::<usize>(), 1, "the new text rasterizes once: {passes:?}"); + assert_eq!(passes.last(), Some(&0)); +} + +#[test] +fn cache_invalidates_the_cached_roots_blur() { + fn view(s: &(bool, bool), _: &mut Cx<(bool, bool)>) -> El { + let mut card = el().size(24.0, 24.0).absolute(16.0, 16.0) + .blur(if s.1 { 3.0 } else { 0.0 }).blur_motion(crate::Anim::INSTANT) + .child(el().size(16.0, 16.0).fill(Color::WHITE)); + if s.0 { card = card.cache(); } + el().size(64.0, 64.0).child(card) + } + same_as_uncached(false, view, (64, 64), &[ + ("blur", 3, &|rt| { rt.state.1 = true; rt.invalidate(); }), + ]); +} + +#[test] +fn clicks_land_inside_a_cached_card_after_a_pan() { + type S = (u32, Live<[f32; 2]>); + fn view(s: &S, _: &mut Cx<S>) -> El { + el().size(96.0, 64.0).child( + el().size(96.0, 64.0).live_offset(&s.1).child( + el().size(32.0, 32.0).cache().fill(Color::WHITE).child( + el().key("button").size(16.0, 16.0).fill(Color { r: 1.0, g: 0.0, b: 0.0, a: 1.0 }) + .on_press(|s: &mut S| s.0 += 1), + ), + ), + ) + } + let gpu = Gpu::headless(); + let mut renderer = Renderer::new(&gpu.device, OFFSCREEN_FORMAT); + let pan = Live::new([0.0, 0.0]); + let mut rt = Runtime::new((0, pan.clone()), view, (96.0, 64.0), Env { scale: 1.0, system_dark: true }); + for _ in 0..2 { + rt.frame(1.0 / 60.0); + renderer.prepare(&gpu.device, &gpu.queue, &mut rt.text.atlas, &rt.instances, (96, 64)); + } + pan.set([50.0, 30.0]); + rt.frame(1.0 / 60.0); + renderer.prepare(&gpu.device, &gpu.queue, &mut rt.text.atlas, &rt.instances, (96, 64)); + assert_eq!(rt.instances.len(), 2, "the panned card is elided to its cached quad"); + for (x, y) in [(8.0, 8.0), (58.0, 38.0)] { + rt.pointer_move(x, y); + rt.pointer_down(x, y); + rt.pointer_up(x, y); + rt.frame(1.0 / 60.0); + renderer.prepare(&gpu.device, &gpu.queue, &mut rt.text.atlas, &rt.instances, (96, 64)); + } + assert_eq!(rt.state.0, 1, "only the click on the button's panned position presses it"); + let b = rt.elements().into_iter().find(|e| e.key.as_deref() == Some("button")).expect("button listed"); + assert_eq!([b.rect[0], b.rect[1]], [50.0, 30.0], "elements() reports the panned rect"); +} + +#[test] +fn cache_updates_same_size_image_pixels_after_the_first_raster() { + fn view(image: &crate::Pixels, _: &mut Cx<crate::Pixels>) -> El { + el().size(32.0, 32.0).child(el().size(24.0, 24.0).cache().pixels(image)) + } + let gpu = Gpu::headless(); + let target = Offscreen::new(&gpu.device, 32, 32); + let mut renderer = Renderer::new(&gpu.device, OFFSCREEN_FORMAT); + let image = crate::Pixels::new(); + let mut rt = Runtime::new(image.clone(), view, (32.0, 32.0), Env::new(true, 1.0)); + for color in [[255, 0, 0, 255], [0, 255, 0, 255]] { + image.set(2, 2, color.repeat(4)); + rt.frame(1.0 / 60.0); + renderer.prepare(&gpu.device, &gpu.queue, &mut rt.text.atlas, &rt.instances, (32, 32)); + renderer.upload_images(&gpu.device, &gpu.queue, &mut rt.images); + let out = pixels(&gpu, &renderer, &target); + assert_eq!(&out[(12 * 32 + 12) * 4..][..4], &color, "same-size image publication must change the output"); + } +} + +#[test] +fn cached_card_stays_elided_during_sixty_live_only_wheel_frames() { + type S = (u32, Live<[f32; 2]>); + fn view(s: &S, _: &mut Cx<S>) -> El { + el().size(160.0, 100.0) + .on_wheel(|s: &mut S, e, tx| { + let p = s.1.get(); s.1.set([p[0] + e.dx, p[1] + e.dy]); + tx.live_only(); true + }) + .child(el().size(160.0, 100.0).live_offset(&s.1) + .child(el().size(32.0, 32.0).cache().fill(Color::WHITE) + .child(el().key("button").size(16.0, 16.0) + .fill(Color { r: 1.0, g: 0.0, b: 0.0, a: 1.0 }) + .on_press(|s: &mut S| s.0 += 1)))) + } + let gpu = Gpu::headless(); + let mut renderer = Renderer::new(&gpu.device, OFFSCREEN_FORMAT); + let target = Offscreen::new(&gpu.device, 160, 100); + let mut rt = Runtime::new((0, Live::new([0.0, 0.0])), view, (160.0, 100.0), Env::new(true, 1.0)); + rt.check_live_only(false); + for _ in 0..3 { + rt.frame(1.0 / 60.0); + renderer.prepare(&gpu.device, &gpu.queue, &mut rt.text.atlas, &rt.instances, (160, 100)); + pixels(&gpu, &renderer, &target); + } + let commits = rt.stats.commits; + for frame in 0..60 { + rt.wheel_event(crate::WheelEvent::new(1.0, 0.5).at(120.0, 80.0)); + rt.frame(1.0 / 60.0); + assert_eq!(rt.stats.commits, commits, "frame {frame} must not rebuild the view"); + assert_eq!(rt.instances.len(), 2, "frame {frame}: child emission stays elided"); + renderer.prepare(&gpu.device, &gpu.queue, &mut rt.text.atlas, &rt.instances, (160, 100)); + let out = pixels(&gpu, &renderer, &target); + if frame == 59 { + near(&out[(38 * 160 + 68) * 4..(38 * 160 + 69) * 4], [255, 0, 0, 255]); + near(&out[(8 * 160 + 8) * 4..(8 * 160 + 9) * 4], [0; 4]); + } + } + let b = rt.elements().into_iter().find(|e| e.key.as_deref() == Some("button")).unwrap(); + assert_eq!([b.rect[0], b.rect[1]], [60.0, 30.0]); + rt.pointer_down(68.0, 38.0); rt.pointer_up(68.0, 38.0); rt.frame(1.0 / 60.0); + assert_eq!(rt.state.0, 1, "the click hits the cached child's moved position"); +} + +#[test] +fn cache_does_not_hide_a_radius_change_during_scale_settling() { + type S = (bool, Live<f32>); + fn view(s: &S, _: &mut Cx<S>) -> El { + el().size(100.0, 100.0).live_scale(&s.1).child( + el().size(32.0, 32.0).cache().child( + el().size(32.0, 32.0).motion(crate::tok::motion::INSTANT).fill(Color::WHITE).radius(if s.0 { 16.0 } else { 0.0 }), + ), + ) + } + let gpu = Gpu::headless(); + let target = Offscreen::new(&gpu.device, 100, 100); + let mut renderer = Renderer::new(&gpu.device, OFFSCREEN_FORMAT); + let scale = Live::new(1.0); + let mut rt = Runtime::new((false, scale.clone()), view, (100.0, 100.0), Env::new(true, 1.0)); + rt.frame(0.0); + renderer.prepare(&gpu.device, &gpu.queue, &mut rt.text.atlas, &rt.instances, (100, 100)); + let _ = pixels(&gpu, &renderer, &target); + scale.set(1.01); + rt.state.0 = true; + rt.invalidate(); + rt.frame(1.0 / 60.0); + renderer.prepare(&gpu.device, &gpu.queue, &mut rt.text.atlas, &rt.instances, (100, 100)); + let out = pixels(&gpu, &renderer, &target); + assert!(out[3] < 32, "the newly rounded corner must not show the stale square (alpha={})", out[3]); +} + +#[test] +fn slow_pinch_composites_until_the_scale_holds_still() { + fn view(scale: &Live<f32>, _: &mut Cx<Live<f32>>) -> El { + el().size(200.0, 200.0).padding(60.0).live_scale(scale).child( + el().size(48.0, 48.0).cache().fill(Color { r: 0.2, g: 0.5, b: 0.9, a: 1.0 }) + .child(el().size(24.0, 24.0).fill(Color::WHITE)), + ) + } + let gpu = Gpu::headless(); + let mut renderer = Renderer::new(&gpu.device, OFFSCREEN_FORMAT); + let scale = Live::new(1.0); + let mut rt = Runtime::new(scale.clone(), view, (200.0, 200.0), Env { scale: 1.0, system_dark: true }); + rt.frame(0.0); + renderer.prepare(&gpu.device, &gpu.queue, &mut rt.text.atlas, &rt.instances, (200, 200)); + assert_eq!(renderer.layer_stats().extra_passes, 1); + for step in 1..=60 { + scale.set(1.0 + step as f32 * 0.01); + rt.frame(1.0 / 60.0); + renderer.prepare(&gpu.device, &gpu.queue, &mut rt.text.atlas, &rt.instances, (200, 200)); + assert_eq!(renderer.layer_stats().extra_passes, 0, "pinch step {step} composites the old texture"); + } + rt.frame(0.15); + renderer.prepare(&gpu.device, &gpu.queue, &mut rt.text.atlas, &rt.instances, (200, 200)); + assert_eq!(renderer.layer_stats().extra_passes, 1, "one raster once the pinch rests"); +} + +#[test] +fn over_budget_cache_falls_back_to_a_viewport_sized_target() { + fn view(_: &(), _: &mut Cx<()>) -> El { + el().size(32.0, 32.0).child( + el().size(300.0, 300.0).cache().clip_rounded(8.0).fill(Color { r: 0.0, g: 0.0, b: 1.0, a: 1.0 }) + .child(el().size(20.0, 20.0).fill(Color::WHITE)), + ) + } + let gpu = Gpu::headless(); + let target = Offscreen::new(&gpu.device, 32, 32); + let mut want = None; + // In budget it caches a 320 px bucket; the fallback draws the same group through the 32 px it shows. + for budget in [DEFAULT_CACHE_BUDGET, 64 * 64 * 8] { + let mut rt = Runtime::new((), view, (32.0, 32.0), Env { scale: 1.0, system_dark: true }); + let mut renderer = Renderer::new(&gpu.device, OFFSCREEN_FORMAT); + renderer.set_cache_budget(budget); + let mut out = Vec::new(); + for _ in 0..3 { + rt.frame(1.0 / 60.0); + renderer.prepare(&gpu.device, &gpu.queue, &mut rt.text.atlas, &rt.instances, (32, 32)); + out = pixels(&gpu, &renderer, &target); + } + match &want { + None => want = Some(out), + Some(w) => { + assert!(renderer.layer_stats().bytes <= 64 * 64 * 8, "over-budget fallback stays viewport-sized: {:?}", renderer.layer_stats()); + assert!(out.iter().zip(w).all(|(a, b)| a.abs_diff(*b) <= 1), "fallback draws like the cache"); + } + } + } +} + +#[test] +fn scale_commits_draw_live_without_repeated_cache_passes() { + fn view(scale: &f32, _: &mut Cx<f32>) -> El { + el().size(200.0, 200.0).scale(*scale).scale_motion(rune_motion::Curve::Instant).child( + el().size(48.0, 48.0).cache().fill(Color::WHITE), + ) + } + let gpu = Gpu::headless(); + let target = Offscreen::new(&gpu.device, 200, 200); + let mut renderer = Renderer::new(&gpu.device, OFFSCREEN_FORMAT); + let mut rt = Runtime::new(1.0, view, (200.0, 200.0), Env::new(true, 1.0)); + rt.frame(0.0); + renderer.prepare(&gpu.device, &gpu.queue, &mut rt.text.atlas, &rt.instances, (200, 200)); + let _ = pixels(&gpu, &renderer, &target); + for step in 1..=30 { + rt.state = 1.0 + step as f32 * 0.01; + rt.invalidate(); + rt.frame(1.0 / 60.0); + renderer.prepare(&gpu.device, &gpu.queue, &mut rt.text.atlas, &rt.instances, (200, 200)); + assert_eq!(renderer.layer_stats().extra_passes, 0, "scale commit {step} must not rasterize another cache"); + let _ = pixels(&gpu, &renderer, &target); + } + rt.frame(0.15); + renderer.prepare(&gpu.device, &gpu.queue, &mut rt.text.atlas, &rt.instances, (200, 200)); + assert_eq!(renderer.layer_stats().extra_passes, 1, "cache once the committed scale settles"); +} + +#[test] +fn glyph_atlas_survives_four_hundred_scales_and_renders_fresh_and_cached_text() { + struct State { + font_size: f32, + banner: &'static str, + card_text: &'static str, + } + fn view(s: &State, _: &mut Cx<State>) -> El { + crate::col() + .size(360.0, 120.0) + .gap(8.0) + .child( + crate::text(s.banner) + .font(crate::TextStyle::new(s.font_size, 400.0)) + .color(Color::WHITE), + ) + .child( + el().size(320.0, 40.0) + .cache() + .child(crate::text(s.card_text).font(crate::TextStyle::new(16.0, 500.0)).color(Color::WHITE)), + ) + } + let gpu = Gpu::headless(); + let target = Offscreen::new(&gpu.device, 360, 120); + let mut renderer = Renderer::new(&gpu.device, OFFSCREEN_FORMAT); + let mut rt = Runtime::new( + State { + font_size: 16.0, + banner: "The quick brown fox jumps over the lazy dog 0123456789", + card_text: "CACHED SUBTREE ALPHA", + }, + view, + (360.0, 120.0), + Env::new(true, 1.0), + ); + rt.frame(0.0); + renderer.prepare(&gpu.device, &gpu.queue, &mut rt.text.atlas, &rt.instances, (360, 120)); + let _ = pixels(&gpu, &renderer, &target); + + for i in 0..400 { + rt.state.font_size = 18.0 + (i as f32) * 0.45; + rt.invalidate(); + rt.frame(1.0 / 60.0); + } + assert!(rt.text.atlas.resets() >= 2, "400 scales must cycle the glyph atlas (resets={})", rt.text.atlas.resets()); + + // Now draw a fresh string at scale 1 (font_size 18.0) and a fresh cached card string. + rt.state.font_size = 18.0; + rt.state.banner = "Sphinx of black quartz, judge my vow!"; + rt.state.card_text = "CACHED SUBTREE OMEGA"; + rt.invalidate(); + rt.frame(1.0); + renderer.prepare(&gpu.device, &gpu.queue, &mut rt.text.atlas, &rt.instances, (360, 120)); + let out = pixels(&gpu, &renderer, &target); + + let glyphs: Vec<_> = rt.instances.iter().filter(|q| q.params[1] == KIND_GLYPH).collect(); + let expected = rt.state.banner.chars().filter(|c| !c.is_whitespace()).count() + + rt.state.card_text.chars().filter(|c| !c.is_whitespace()).count(); + assert_eq!(glyphs.len(), expected, "every glyph in both fresh and cached text must be emitted"); + for (idx, g) in glyphs.iter().enumerate() { + let x0 = (g.rect[0].floor().max(0.0) as u32).min(360); + let y0 = (g.rect[1].floor().max(0.0) as u32).min(120); + let x1 = ((g.rect[0] + g.rect[2]).ceil().max(0.0) as u32).min(360); + let y1 = ((g.rect[1] + g.rect[3]).ceil().max(0.0) as u32).min(120); + let mut lit = 0u32; + for y in y0..y1 { + for x in x0..x1 { + let p = &out[((y * 360 + x) * 4) as usize..][..4]; + if p[0] > 16 || p[1] > 16 || p[2] > 16 { + lit += 1; + } + } + } + assert!(lit > 0, "glyph {idx} at {:?} (page {}) rendered zero ink pixels", g.rect, g.params[2]); + } +} + +#[test] +fn single_frame_spanning_multiple_glyph_atlas_pages_draws_all_pages() { + fn view(_: &(), _: &mut Cx<()>) -> El { + let mut root = el().size(512.0, 512.0); + // 24 overlapping lines of large text inside the viewport overflow page 0 into page 1+. + for i in 0..24 { + root = root.child( + crate::text("ABCDEFGHIJKLMN") + .absolute(4.0, (i * 8) as f32) + .font(crate::TextStyle::new(150.0 + i as f32 * 2.0, 700.0)) + .color(Color::WHITE), + ); + } + root + } + let gpu = Gpu::headless(); + let target = Offscreen::new(&gpu.device, 512, 512); + let mut renderer = Renderer::new(&gpu.device, OFFSCREEN_FORMAT); + let mut rt = Runtime::new((), view, (512.0, 512.0), Env::new(true, 1.0)); + rt.frame(0.0); + assert!(rt.text.atlas.page_count() >= 2, "single frame must allocate >= 2 pages (got {})", rt.text.atlas.page_count()); + assert_eq!(rt.text.atlas.resets(), 0, "single frame must not reset a live page mid-frame"); + assert!(rt.instances.iter().any(|i| i.params[1] == KIND_GLYPH && i.params[2] == 0.0), "has page 0 glyphs"); + assert!(rt.instances.iter().any(|i| i.params[1] == KIND_GLYPH && i.params[2] >= 1.0), "has page 1+ glyphs"); + + renderer.prepare(&gpu.device, &gpu.queue, &mut rt.text.atlas, &rt.instances, (512, 512)); + let out = pixels(&gpu, &renderer, &target); + for page in [0.0f32, 1.0f32] { + let g = rt + .instances + .iter() + .find(|i| i.params[1] == KIND_GLYPH && i.params[2] == page && i.rect[0] >= 0.0 && i.rect[1] >= 0.0 && i.rect[0] + i.rect[2] <= 512.0 && i.rect[1] + i.rect[3] <= 512.0) + .unwrap_or_else(|| panic!("expected in-viewport glyph on page {page}")); + let (x0, y0) = (g.rect[0].floor() as u32, g.rect[1].floor() as u32); + let (x1, y1) = ((g.rect[0] + g.rect[2]).ceil() as u32, (g.rect[1] + g.rect[3]).ceil() as u32); + let mut lit = 0u32; + for y in y0..y1 { + for x in x0..x1 { + if out[((y * 512 + x) * 4) as usize] > 16 { + lit += 1; + } + } + } + assert!(lit > 0, "glyph on page {page} at {:?} must render visible pixels", g.rect); + } +} + +#[test] +fn live_scale_zoom_sweep_buckets_during_motion_and_settles_crisp() { + fn view(zoom: &Live<f32>, _: &mut Cx<Live<f32>>) -> El { + el().size(300.0, 120.0) + .live_scale(zoom) + .child(crate::text("Hamburgefonstiv").font(crate::TextStyle::new(14.0, 400.0)).color(Color::WHITE)) + } + let zoom = Live::new(1.0); + let mut rt = Runtime::new(zoom.clone(), view, (300.0, 120.0), Env::new(true, 2.0)); + rt.frame(0.0); + let per_size = rt.text.atlas.rasterized(); + assert!(per_size >= 10); + + // 10 s zoom sweep at 120 Hz (1,200 frames) across [0.25, 4.0] (4 octaves = 17 quarter-octave buckets). + for frame in 1..=1200 { + let u = frame as f32 / 1200.0; + let k = 0.25 * 16.0f32.powf(u); + zoom.set(k); + rt.frame(1.0 / 120.0); + } + let sweep_rasterized = rt.text.atlas.rasterized(); + let distinct_sizes = sweep_rasterized / per_size; + assert!( + distinct_sizes <= 18, + "10s zoom sweep across [0.25, 4.0] must rasterize at most 17 bucketed sizes (got {distinct_sizes}, total={sweep_rasterized})" + ); + + // Stop at an off-bucket scale (1.13) and let it settle: must re-rasterize crisp at 1.13 and stop animating. + zoom.set(1.13); + rt.frame(1.0 / 120.0); + assert!( + rt.instances.iter().filter(|q| q.params[1] == KIND_GLYPH).any(|q| q.uv[2] > 0.0 || q.radii[3] > 0.0), + "filtered atlas masks or live outlines while moving" + ); + for _ in 0..20 { + rt.frame(1.0 / 120.0); + } + assert!( + rt.instances.iter().filter(|q| q.params[1] == KIND_GLYPH).all(|q| q.uv[2] == 0.0 && q.radii[3] == 0.0), + "crisp 1:1 glyphs once live_scale settles at 1.13" + ); + assert!(!rt.frame(1.0 / 120.0), "nothing keeps animating after live_scale settles"); +} + +#[test] +fn pill_styles_follow_captured_state_through_a_cached_subtree() { + use std::cell::Cell; + use std::rc::Rc; + use crate::{PillStyle, Span, TextEdit, TextStyle}; + static A: crate::Icon = crate::Icon { name: "a", view: 8.0, body: "<rect width=\"8\" height=\"8\"/>" }; + static B: crate::Icon = crate::Icon { name: "b", view: 8.0, body: "<circle cx=\"4\" cy=\"4\" r=\"4\"/>" }; + type S = (TextEdit, bool, Rc<Cell<usize>>); + fn view(s: &S, _: &mut Cx<S>) -> El { + let swap = s.1; + let calls = s.2.clone(); + let field = crate::text_input(&s.0, TextStyle::new(14.0, 400.0)) + .size(200.0, 30.0) + .pill_icon(move |_| Some(&B)) + .pill_style(move |id| { + calls.set(calls.get() + 1); + let first = (id == "p:1") != swap; + if first { + PillStyle::new().bg(Color { r: 1.0, g: 0.0, b: 0.0, a: 1.0 }).icon(&A) + } else { + // Leave icon unset so it falls back to `pill_icon` (&B). + PillStyle::default().bg(Color { r: 0.0, g: 0.0, b: 1.0, a: 1.0 }) + } + }) + .pill_colors(Color { r: 0.0, g: 1.0, b: 0.0, a: 1.0 }, Some(Color::WHITE)) + .color(Color::WHITE) + .decorations([Span::new(0, 1)]); + el().size(200.0, 40.0).child(el().size(190.0, 30.0).child(field).cache()) + } + let mut edit = TextEdit::new(" ").rich(); + edit.set_caret(0); + edit.insert_pill("p:1", "one"); + edit.insert(" "); + edit.insert_pill("p:2", "two"); + let calls = Rc::new(Cell::new(0)); + let mut rt = Runtime::new((edit, false, calls.clone()), view, (200.0, 40.0), Env { scale: 1.0, system_dark: true }); + let gpu = Gpu::headless(); + let target = Offscreen::new(&gpu.device, 200, 40); + let mut renderer = Renderer::new(&gpu.device, OFFSCREEN_FORMAT); + let mut step = |rt: &mut Runtime<S>| { + rt.frame(1.0 / 60.0); + renderer.prepare(&gpu.device, &gpu.queue, &mut rt.text.atlas, &rt.instances, (200, 40)); + (pixels(&gpu, &renderer, &target), renderer.layer_stats().extra_passes) + }; + let chips = |out: &[u8]| { + let first = |hit: &dyn Fn(&[u8]) -> bool| (0..200).find(|&x| (0..40).any(|y| hit(&out[(y * 200 + x) * 4..][..4]))); + let (red, blue) = (first(&|p| p[0] > 120 && p[2] < 60), first(&|p| p[2] > 120 && p[0] < 60)); + (red.expect("red chip"), blue.expect("blue chip")) + }; + let (out, passes) = step(&mut rt); + assert_eq!(calls.get(), 2, "pill_style runs once per pill on build despite later builder calls"); + assert_eq!(passes, 1, "initial frame rasterizes the cached subtree"); + let (red, blue) = chips(&out); + assert!(red < blue, "p:1 draws red then p:2 blue: {red} {blue}"); + assert_eq!(step(&mut rt).1, 0, "steady frame hits the cached layer"); + rt.invalidate(); + assert_eq!(step(&mut rt).1, 0, "rebuilding with unchanged pill styles keeps the cached layer"); + let icons = |rt: &Runtime<S>| rt.tree.nodes.iter().find_map(|n| n.text.as_ref().filter(|t| !t.cold.pills.is_empty())).unwrap().cold.pills.iter().map(|p| p.icon.unwrap().name).collect::<Vec<_>>(); + assert_eq!(icons(&rt), ["a", "b"]); + calls.set(0); + rt.state.1 = true; + rt.invalidate(); + let (out, passes) = step(&mut rt); + assert_eq!(calls.get(), 2, "pill_style runs once per pill when rebuilt"); + assert_eq!(passes, 1, "changed pill styles invalidate the cached layer"); + let (red, blue) = chips(&out); + assert!(blue < red, "after the captured state flips the cached chips restyle: {red} {blue}"); + assert_eq!(icons(&rt), ["b", "a"]); + assert_eq!(step(&mut rt).1, 0, "next frame hits the newly cached layer"); +} diff --git a/app/vendor/rune/crates/rune/src/runtime/layer_tests.rs b/app/vendor/rune/crates/rune/src/runtime/layer_tests.rs new file mode 100644 index 0000000..399a3f8 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/layer_tests.rs @@ -0,0 +1,494 @@ +use super::*; +use crate::{Color, Cx, El, Env, Live, Runtime, el}; + +pub(super) fn rect(bounds: [f32; 4], color: [f32; 4]) -> Instance { + Instance { rect: bounds, fill: color, clip: NO_CLIP, params: [0.0, KIND_RECT, 0.0, 1.0], ..Instance::zeroed() } +} + +fn group(bounds: [f32; 4], opacity: f32, color: [f32; 4]) -> Vec<Instance> { + vec![Instance::begin_layer(bounds, NO_CLIP, LayerSpec { opacity, ..Default::default() }), + rect(bounds, color), rect([bounds[0] + bounds[2] * 0.25, bounds[1], bounds[2] * 0.5, bounds[3]], color), + Instance::end_layer()] +} + +#[test] +fn raised_children_of_cached_clipped_groups_stay_visible_and_clipped() { + fn view(_: &(), _: &mut Cx<()>) -> El { + el().size(32.0, 32.0).child(el().size(16.0, 16.0).clip_rounded(8.0).cache().opacity(0.5) + .child(el().size(24.0, 24.0).raise().fill(Color::WHITE))) + } + let gpu = Gpu::headless(); + let mut renderer = Renderer::new(&gpu.device, OFFSCREEN_FORMAT); + let target = Offscreen::new(&gpu.device, 32, 32); + let mut rt = Runtime::new((), view, (32.0, 32.0), Env::new(true, 1.0)); + for _ in 0..3 { + rt.frame(0.0); + renderer.prepare(&gpu.device, &gpu.queue, &mut rt.text.atlas, &rt.instances, (32, 32)); + let out = pixels(&gpu, &renderer, &target); + near(&out[(8 * 32 + 8) * 4..(8 * 32 + 9) * 4], rgba([0.5; 4])); + near(&out[(8 * 32 + 20) * 4..(8 * 32 + 21) * 4], [0; 4]); + near(&out[0..4], [0; 4]); + } +} + +pub(super) fn pixels(gpu: &Gpu, renderer: &Renderer, target: &Offscreen) -> Vec<u8> { + let mut enc = gpu.device.create_command_encoder(&Default::default()); + renderer.draw(&mut enc, &target.view, [0.0; 4]); + target.copy(&mut enc); + renderer.submit(&gpu.queue, enc); + target.read(&gpu.device) +} + +pub(super) fn rgba(linear: [f32; 4]) -> [u8; 4] { + std::array::from_fn(|i| { + let v = linear[i]; + let v = if i == 3 { v } else if v <= 0.0031308 { v * 12.92 } else { 1.055 * v.powf(1.0 / 2.4) - 0.055 }; + (v.clamp(0.0, 1.0) * 255.0).round() as u8 + }) +} + +pub(super) fn near(got: &[u8], want: [u8; 4]) { + assert!(got.iter().zip(want).all(|(&a,b)| a.abs_diff(b) <= 1), "{got:?} != {want:?}"); +} + +#[test] +fn isolated_layers_match_scalar_overlap_crossfade_and_nesting() { + let gpu = Gpu::headless(); + let mut renderer = Renderer::new(&gpu.device, OFFSCREEN_FORMAT); + let target = Offscreen::new(&gpu.device, 32, 16); + let mut atlas = crate::text::TextSystem::default().atlas; + let bounds = [4.0, 4.0, 24.0, 8.0]; + let mut instances = group(bounds, 0.5, [1.0; 4]); + renderer.prepare(&gpu.device, &gpu.queue, &mut atlas, &instances, (32, 16)); + let out = pixels(&gpu, &renderer, &target); + for x in [6, 16, 26] { near(&out[(8 * 32 + x) * 4..(8 * 32 + x + 1) * 4], rgba([0.5; 4])); } + assert_eq!(renderer.layer_stats().targets, 1); + assert_eq!(renderer.layer_stats().bytes, 64 * 64 * 8, "minimum bucket"); + let allocations = renderer.layer_stats().allocations; + + // Two opaque states, each with internal overlap. Source-over crossfade is B(1-t) over + // A(t): alpha = 1-t+t², NOT 1. Internal child overlap must never alter that oracle. + for t in [0.25, 0.5, 0.75] { + instances = group(bounds, t, [1.0, 0.0, 0.0, 1.0]); + instances.extend(group(bounds, 1.0 - t, [0.0, 0.0, 1.0, 1.0])); + renderer.prepare(&gpu.device, &gpu.queue, &mut atlas, &instances, (32, 16)); + let out = pixels(&gpu, &renderer, &target); + let want = rgba([t * t, 0.0, 1.0 - t, 1.0 - t + t * t]); + for x in [6, 16, 26] { near(&out[(8 * 32 + x) * 4..(8 * 32 + x + 1) * 4], want); } + } + assert_eq!(renderer.layer_stats().allocations, allocations + 1, "reuse targets while opacity changes"); + + instances = vec![Instance::begin_layer(bounds, NO_CLIP, LayerSpec { opacity: 0.5, ..Default::default() })]; + instances.extend(group(bounds, 0.5, [1.0; 4])); + instances.push(Instance::end_layer()); + renderer.prepare(&gpu.device, &gpu.queue, &mut atlas, &instances, (32, 16)); + let out = pixels(&gpu, &renderer, &target); + near(&out[(8 * 32 + 16) * 4..(8 * 32 + 17) * 4], rgba([0.25; 4])); + + instances = group(bounds, 0.5, [1.0; 4]); + for i in &mut instances[..3] { i.clip = [8.0, 5.0, 24.0, 11.0]; } + renderer.prepare(&gpu.device, &gpu.queue, &mut atlas, &instances, (32, 16)); + assert_eq!(renderer.layer_stats().bytes, 64 * 64 * 8, "clip uses the minimum bucket"); + assert_eq!(renderer.layers.planner.dispositions[0].rect(), [8.0, 5.0, 16.0, 6.0]); + let out = pixels(&gpu, &renderer, &target); + near(&out[(8 * 32 + 6) * 4..(8 * 32 + 7) * 4], [0; 4]); + near(&out[(8 * 32 + 16) * 4..(8 * 32 + 17) * 4], rgba([0.5; 4])); + + for alpha in [1.0, 0.0] { + instances = group(bounds, alpha, [1.0; 4]); + renderer.prepare(&gpu.device, &gpu.queue, &mut atlas, &instances, (32, 16)); + let out = pixels(&gpu, &renderer, &target); + near(&out[(8 * 32 + 16) * 4..(8 * 32 + 17) * 4], rgba([alpha; 4])); + assert_eq!(renderer.layer_stats().targets, 0, "release on both endpoints"); + assert_eq!(renderer.layer_stats().extra_passes, 0); + } + // Fully opaque streams allocate no planner storage and issue only the ordinary pass. + let mut ordinary = Renderer::new(&gpu.device, OFFSCREEN_FORMAT); + ordinary.prepare(&gpu.device, &gpu.queue, &mut atlas, &[rect(bounds, [1.0; 4])], (32, 16)); + assert_eq!(ordinary.layer_stats(), LayerStats::default()); + assert_eq!(ordinary.layers.plan.capacity(), 0); + assert_eq!(ordinary.layers.planner.capacities(), [0; 5]); + assert_eq!(ordinary.layers.targets.capacity(), 0); + assert_eq!(ordinary.layers.stack.capacity(), 0); + assert_eq!(ordinary.layers.pipelines.capacity(), 0); +} + +#[test] +fn leaf_dimming_keeps_container_opacity_isolated() { + fn view(alpha: &Live<f32>, _: &mut Cx<Live<f32>>) -> El { + el().size(32.0, 16.0).live_opacity(alpha) + .child(el().size(24.0, 8.0).absolute(4.0, 4.0).fill(Color::WHITE)) + .child(el().size(12.0, 8.0).absolute(10.0, 4.0).fill(Color::WHITE)) + .dim(0.5) + } + let gpu = Gpu::headless(); + let mut renderer = Renderer::new(&gpu.device, OFFSCREEN_FORMAT); + let target = Offscreen::new(&gpu.device, 32, 16); + let mut rt = Runtime::new(Live::new(0.5), view, (32.0, 16.0), Env { scale: 1.0, system_dark: true }); + for (alpha, targets) in [(0.5, 1), (1.0, 0)] { + rt.state.set(alpha); rt.frame(0.0); + renderer.prepare(&gpu.device, &gpu.queue, &mut rt.text.atlas, &rt.instances, (32, 16)); + assert_eq!(renderer.layer_stats().targets, targets); + let out = pixels(&gpu, &renderer, &target); + near(&out[(8*32+6)*4..(8*32+7)*4], rgba([0.5 * alpha; 4])); + near(&out[(8*32+16)*4..(8*32+17)*4], rgba([0.75 * alpha; 4])); + } +} + +#[test] +fn dissolve_keeps_opaque_coverage_and_isolates_each_state() { + type State = (Live<f32>, Live<f32>); + fn view(s: &State, _: &mut Cx<State>) -> El { + let state = |alpha: &Live<f32>, color: Color| { + el().size(24.0, 8.0).absolute(4.0, 4.0).live_opacity(alpha) + .child(el().size(24.0, 8.0).fill(color)) + .child(el().size(12.0, 8.0).absolute(6.0, 0.0).fill(color)) + }; + el().size(32.0, 16.0).dissolve() + .child(state(&s.0, Color { r: 1.0, g: 0.0, b: 0.0, a: 1.0 })) + .child(state(&s.1, Color { r: 0.0, g: 0.0, b: 1.0, a: 1.0 })) + } + let gpu = Gpu::headless(); + // Linear destination makes the exact colour-average assertion independent of sRGB encoding. + let format = wgpu::TextureFormat::Rgba8Unorm; + let mut renderer = Renderer::new(&gpu.device, format); + let target = Offscreen::with_format(&gpu.device, 32, 16, format); + let mut rt = Runtime::new((Live::new(0.5), Live::new(0.5)), view, (32.0, 16.0), Env { scale: 1.0, system_dark: true }); + for t in [0.5, 0.0, 0.25, 0.75, 1.0] { + rt.state.0.set(1.0 - t); rt.state.1.set(t); rt.frame(0.0); + renderer.prepare(&gpu.device, &gpu.queue, &mut rt.text.atlas, &rt.instances, (32, 16)); + if t == 0.0 || t == 1.0 { + assert!(rt.instances.iter().all(|i| i.params[1] != KIND_LAYER), "no dissolve scope at rest"); + assert_eq!(renderer.layer_stats().extra_passes, 0); + } else { + assert!(renderer.layers.targets[0].is_some(), "mid-fade dissolve must isolate"); + } + let out = pixels(&gpu, &renderer, &target); + let want = [((1.0-t)*255.0).round() as u8, 0, (t*255.0).round() as u8, 255]; + for x in [6, 16, 26] { + near(&out[(8*32+x)*4..(8*32+x+1)*4], want); + assert_eq!(out[(8*32+x)*4+3], 255, "opaque coverage at t={t}"); + } + near(&out[..4], [0; 4]); + } + // The first/last isolated frame must not introduce a rasterization jump. These deltas + // are below an output byte but above zero, so they exercise both sides of scope selection. + for (rest, moving) in [(0.0, 0.00001), (1.0, 0.99999)] { + let mut frames = Vec::new(); + for t in [rest, moving] { + rt.state.0.set(1.0 - t); rt.state.1.set(t); rt.frame(0.0); + renderer.prepare(&gpu.device, &gpu.queue, &mut rt.text.atlas, &rt.instances, (32, 16)); + assert_eq!(renderer.layer_stats().targets > 0, t == moving); + frames.push(pixels(&gpu, &renderer, &target)); + } + assert_eq!(frames[0], frames[1], "scope boundary at {rest}"); + } + // A sole multi-draw state at opacity 1 still composites internally with source-over. + // Using translucent primitives distinguishes correct isolation from additive saturation. + let bounds = [4.0, 4.0, 24.0, 8.0]; + let mut all = vec![Instance::begin_layer(bounds, NO_CLIP, LayerSpec { blend: Blend::PlusLighter, ..Default::default() })]; + all.extend(group(bounds, 1.0, [0.5, 0.0, 0.0, 0.5])); + all.push(Instance::end_layer()); + renderer.prepare(&gpu.device, &gpu.queue, &mut rt.text.atlas, &all, (32, 16)); + let out = pixels(&gpu, &renderer, &target); + near(&out[(8*32+6)*4..(8*32+7)*4], [128,0,0,128]); + near(&out[(8*32+16)*4..(8*32+17)*4], [191,0,0,191]); + // Saturate colour as well as alpha, before either the dissolve or enclosing group's fade. + let nested = [Instance::begin_layer(bounds, NO_CLIP, LayerSpec { opacity: 0.5, ..Default::default() }), + Instance::begin_layer(bounds, NO_CLIP, LayerSpec { opacity: 0.5, blend: Blend::PlusLighter, ..Default::default() }), + rect(bounds, [1.0; 4]), rect(bounds, [1.0; 4]), Instance::end_layer(), Instance::end_layer()]; + renderer.prepare(&gpu.device, &gpu.queue, &mut rt.text.atlas, &nested, (32, 16)); + let out = pixels(&gpu, &renderer, &target); + near(&out[(8*32+16)*4..(8*32+17)*4], [64; 4]); +} + +#[test] +fn dissolve_samples_sequence_opacity_before_selecting_scopes() { + fn view(_: &(), _: &mut Cx<()>) -> El { + const OUT: &[crate::Beat] = &[crate::Beat::new(0.0), + crate::Beat::new(1.0).opacity(0.0).easing(crate::Easing::LINEAR)]; + const IN: &[crate::Beat] = &[crate::Beat::new(0.0).opacity(0.0), + crate::Beat::new(1.0).easing(crate::Easing::LINEAR)]; + el().size(32.0, 16.0).dissolve() + .child(el().size(32.0, 16.0).absolute(0.0, 0.0).fill(Color::WHITE).sequence(crate::Sequence::new(OUT))) + .child(el().size(32.0, 16.0).absolute(0.0, 0.0).fill(Color::WHITE).sequence(crate::Sequence::new(IN))) + } + let gpu = Gpu::headless(); + let mut renderer = Renderer::new(&gpu.device, OFFSCREEN_FORMAT); + let target = Offscreen::new(&gpu.device, 32, 16); + let mut rt = Runtime::new((), view, (32.0, 16.0), Env::new(true, 1.0)); + for (dt, active) in [(0.0, false), (0.5, true), (0.5, false)] { + rt.frame(dt); + assert_eq!(rt.instances.iter().any(|i| i.params[1] == KIND_LAYER), active); + renderer.prepare(&gpu.device, &gpu.queue, &mut rt.text.atlas, &rt.instances, (32, 16)); + let out = pixels(&gpu, &renderer, &target); + assert!(out.chunks_exact(4).all(|p| p[3] == 255), "complementary sequences retain opaque coverage"); + } +} + +#[test] +fn dissolve_adds_direct_primitives_and_native_surfaces_then_clamps_before_opacity() { + use crate::native_surface::{ByteFrame, ColorInfo, Format, NativeSurface, SurfaceDraw, SurfaceFit}; + let gpu = Gpu::headless(); + let format = wgpu::TextureFormat::Rgba8Unorm; + let mut renderer = Renderer::new(&gpu.device, format); + let target = Offscreen::with_format(&gpu.device, 32, 16, format); + let mut atlas = crate::text::TextSystem::default().atlas; + let bounds = [4.0, 4.0, 24.0, 8.0]; + let content = [rect([0.0, 0.0, 32.0, 16.0], [0.0, 1.0, 0.0, 1.0]), + Instance::begin_layer(bounds, NO_CLIP, LayerSpec { opacity: 0.5, blend: Blend::PlusLighter, ..Default::default() }), + rect(bounds, [1.0, 0.0, 0.0, 1.0]), Instance::end_layer()]; + renderer.prepare(&gpu.device, &gpu.queue, &mut atlas, &content, (32, 16)); + let surface = NativeSurface::new(); + surface.push_bytes(ByteFrame { width: 1, height: 1, format: Format::Bgra, color: ColorInfo::default(), + planes: [vec![255, 0, 0, 255], vec![]] }, 1).unwrap(); + renderer.prepare_surfaces(&gpu.device, &gpu.queue, &[SurfaceDraw { surface, fit: SurfaceFit::Fill, + before_instance: 3, rect: bounds, radii: [0.0; 4], clip: NO_CLIP, fade: [0; 4], opacity: 1.0 }], (32, 16)); + let out = pixels(&gpu, &renderer, &target); + // Red + blue saturates alpha to 1, then .5 opacity composites over green with source-over. + near(&out[(8*32+16)*4..(8*32+17)*4], [128,128,128,255]); + near(&out[..4], [0,255,0,255]); +} + +#[test] +fn scale_and_fade_reuse_bucket_for_sixty_growing_frames() { + type State = (Live<f32>, Live<f32>); + fn view(s: &State, _: &mut Cx<State>) -> El { + el().size(256.0, 256.0).child(el().size(180.0, 180.0) + .live_scale(&s.0).live_opacity(&s.1) + .child(el().size(180.0, 180.0).fill(Color::WHITE)) + .child(el().size(90.0, 90.0).fill(Color::WHITE))) + } + let gpu = Gpu::headless(); + let mut renderer = Renderer::new(&gpu.device, OFFSCREEN_FORMAT); + let target = Offscreen::new(&gpu.device, 256, 256); + let mut rt = Runtime::new((Live::new(0.9), Live::new(0.1)), view, (256.0, 256.0), Env { scale: 1.0, system_dark: true }); + rt.frame(0.0); + renderer.prepare(&gpu.device, &gpu.queue, &mut rt.text.atlas, &rt.instances, (256, 256)); + let allocations = renderer.layer_stats().allocations; + let first_bounds = renderer.layers.planner.dispositions[0].rect(); + assert_eq!(allocations, 1); + for frame in 1..=60 { + let t = frame as f32 / 60.0; + rt.state.0.set(0.9 + 0.1 * t); + rt.state.1.set(0.1 + 0.8 * t); + rt.frame(1.0 / 60.0); + renderer.prepare(&gpu.device, &gpu.queue, &mut rt.text.atlas, &rt.instances, (256, 256)); + let out = pixels(&gpu, &renderer, &target); + near(&out[(90 * 256 + 90) * 4..(90 * 256 + 91) * 4], rgba([0.1 + 0.8 * t; 4])); + assert_eq!(renderer.layer_stats().allocations, allocations, "frame {frame}"); + } + assert!(renderer.layers.planner.dispositions[0].rect()[2] > first_bounds[2]); + // A genuine shrink drops an oversized allocation, then the tiny minimum bucket stays put. + for size in [20.0, 19.0, 20.0] { + let content = group([4.0, 4.0, size, size], 0.5, [1.0; 4]); + renderer.prepare(&gpu.device, &gpu.queue, &mut rt.text.atlas, &content, (256, 256)); + assert_eq!(renderer.layer_stats().bytes, 64 * 64 * 8); + assert_eq!(renderer.layer_stats().allocations, allocations + 1); + } +} + +#[test] +fn live_group_opacity_changes_scopes_without_view_or_layout_work() { + fn view(alpha: &Live<f32>, _: &mut Cx<Live<f32>>) -> El { + el().size(32.0, 16.0).live_opacity(alpha) + .child(el().size(24.0, 12.0).fill(Color::WHITE)) + .child(el().size(24.0, 12.0).pin(Some(4.0), Some(0.0), None, None).fill(Color::WHITE)) + } + let alpha = Live::new(1.0); + let mut rt = Runtime::new(alpha.clone(), view, (32.0, 16.0), Env { scale: 1.0, system_dark: true }); + rt.frame(0.0); + let commits = rt.stats.commits; + let original = bytemuck::cast_slice::<Instance, u8>(&rt.instances).to_vec(); + alpha.set(0.5); + rt.frame(1.0 / 60.0); + assert_eq!(rt.stats.commits, commits); + assert_eq!(rt.instances.first().unwrap().params[1], KIND_LAYER); + assert_eq!(rt.instances.last().unwrap().params[1], KIND_LAYER_END); + assert_eq!(rt.instances[1].fill[3], 1.0); + alpha.set(0.0); + rt.frame(1.0 / 60.0); + assert!(rt.instances.is_empty()); + alpha.set(0.0009); + rt.frame(1.0 / 60.0); + assert!(rt.instances.is_empty(), "hide sub-threshold tails"); + alpha.set(1.0); + rt.frame(1.0 / 60.0); + assert_eq!(rt.stats.commits, commits); + assert_eq!(bytemuck::cast_slice::<Instance, u8>(&rt.instances), original); +} + +#[test] +fn isolated_exit_descendants_stay_inside_their_fading_parent() { + fn view(show: &bool, _: &mut Cx<bool>) -> El { + let mut fading = el().key("fading").size(24.0, 16.0).opacity(0.5) + .child(el().key("kept").size(16.0, 16.0).fill(Color::WHITE)); + if *show { fading = fading.child(el().key("leaving").size(16.0, 16.0).fill(Color::WHITE)); } + el().size(32.0, 16.0).child(fading) + .child(el().key("sibling").size(8.0, 16.0).pin(Some(24.0), Some(0.0), None, None).fill(Color { r: 0.0, g: 0.0, b: 1.0, a: 1.0 })) + } + let mut rt = Runtime::new(true, view, (32.0, 16.0), Env { scale: 1.0, system_dark: true }); + rt.frame(0.0); + rt.state = false; rt.invalidate(); rt.frame(0.0); + let start = rt.instances.iter().position(|i| i.params[1] == KIND_LAYER).unwrap(); + let end = rt.instances.iter().position(|i| i.params[1] == KIND_LAYER_END).unwrap(); + assert_eq!(end - start, 3, "both retained descendants share the scope"); + assert_eq!(rt.instances[end + 1].fill, [0.0, 0.0, 1.0, 1.0], "sibling paints outside the group"); +} + +#[test] +fn single_leaf_groups_keep_the_direct_path_and_springs_stay_live() { + fn leaf(alpha: &Live<f32>, _: &mut Cx<Live<f32>>) -> El { + el().size(32.0, 16.0).live_opacity(alpha).child(el().size(16.0, 16.0).fill(Color::WHITE)) + } + fn group_view(alpha: &Live<f32>, _: &mut Cx<Live<f32>>) -> El { + el().size(32.0, 16.0).live_opacity(alpha.smooth(crate::Spring::DEFAULT)) + .child(el().size(16.0, 16.0).fill(Color::WHITE)) + .child(el().size(16.0, 16.0).pin(Some(8.0), Some(0.0), None, None).fill(Color::WHITE)) + } + let alpha = Live::new(0.5); + let env = Env { scale: 1.0, system_dark: true }; + let mut rt = Runtime::new(alpha.clone(), leaf, (32.0, 16.0), env); + rt.frame(0.0); + assert_eq!(rt.instances.len(), 1); + assert_eq!(rt.instances[0].fill[3], 0.5); + alpha.set(1.0); + let mut rt = Runtime::new(alpha.clone(), group_view, (32.0, 16.0), env); + rt.frame(0.0); + let commits = rt.stats.commits; + alpha.set(0.5); + rt.frame(1.0 / 60.0); + let a = rt.instances[0].fill[3]; + rt.frame(1.0 / 60.0); + let b = rt.instances[0].fill[3]; + assert_eq!(rt.instances[0].params[1], KIND_LAYER); + assert!(b < a && b > 0.5, "spring samples change the group each presentation: {a} -> {b}"); + assert_eq!(rt.stats.commits, commits); +} + +#[test] +fn clipped_single_draw_fades_do_not_allocate_targets() { + use crate::native_surface::{ByteFrame, ColorInfo, Format, NativeSurface, SurfaceFit}; + type State = (Option<NativeSurface>, u8); + fn view(s: &State, _: &mut Cx<State>) -> El { + let child = el().size(64.0, 48.0).absolute(-8.0, -8.0); + let child = if let Some(surface) = &s.0 { child.native_surface(surface, SurfaceFit::Fill) } + else { child.fill(Color::WHITE) }; + let clip = el().size(48.0, 32.0).absolute(8.0, 8.0); + let clip = match s.1 { + 0 => clip.clip_soft(0.0), + 1 => clip.clip_fade(4.0, 4.0, 4.0, 4.0), + _ => clip.scroll(crate::ScrollSpec { stick_bottom: false }), + }; + el().child(clip.child(el().size(48.0, 32.0).opacity(0.5).child(child))) + } + let gpu = Gpu::headless(); + let mut renderer = Renderer::new(&gpu.device, OFFSCREEN_FORMAT); + let target = Offscreen::new(&gpu.device, 64, 48); + let surface = NativeSurface::new(); + surface.push_bytes(ByteFrame { width: 1, height: 1, format: Format::Bgra, color: ColorInfo::default(), + planes: [vec![255; 4], vec![]] }, 1).unwrap(); + for mode in 0..3 { + let mut frames = Vec::new(); + for video in [false, true] { + let mut rt = Runtime::new((video.then(|| surface.clone()), mode), view, (64.0, 48.0), Env::new(true, 1.0)); + rt.frame(0.0); + assert!(rt.instances.iter().all(|i| i.params[1] != KIND_LAYER)); + renderer.prepare(&gpu.device, &gpu.queue, &mut rt.text.atlas, &rt.instances, (64, 48)); + renderer.prepare_surfaces(&gpu.device, &gpu.queue, &rt.surfaces, (64, 48)); + assert_eq!(renderer.layer_stats().targets, 0, "mode={mode} video={video}"); + let out = pixels(&gpu, &renderer, &target); + // 0.5 * 255 = 127.5 is a rounding tie: D3D12 allows either neighbour (NVIDIA gives 127). + assert!(out[(24 * 64 + 32) * 4 + 3].abs_diff(128) <= 1, "mode={mode} video={video}"); + assert_eq!(out[(24 * 64 + 4) * 4 + 3], 0); + if mode == 1 { assert!(out[(24 * 64 + 8) * 4 + 3] < 32); } + frames.push(out); + } + // On D3D12, `shader.wgsl`'s interpolated `i.p` across a viewport-clipped quad can differ + // from `video.wgsl`'s `@builtin(position)` by a fraction of a thousandth of a pixel along + // a hard clip edge, shifting those boundary pixels by at most 1 LSB. + let max_diff = frames[0].iter().zip(&frames[1]).map(|(a, b)| a.abs_diff(*b)).max().unwrap_or(0); + assert!(max_diff <= 1, "primitive and video inherit identical clips/fades (mode={mode}, max_diff={max_diff})"); + } +} + +#[test] +fn opacity_motion_samples_group_alpha_until_the_terminal_frame() { + fn view(show: &bool, _: &mut Cx<bool>) -> El { + el().size(32.0, 16.0).opacity(if *show { 1.0 } else { 0.0 }) + .opacity_motion(rune_motion::Curve::ease_in_out(0.2)) + .child(el().size(16.0, 16.0).fill(Color::WHITE)) + .child(el().size(16.0, 16.0).pin(Some(8.0), Some(0.0), None, None).fill(Color::WHITE)) + } + let mut rt = Runtime::new(true, view, (32.0, 16.0), Env { scale: 1.0, system_dark: true }); + rt.frame(0.0); + rt.state = false; rt.invalidate(); rt.frame(0.0); + let commits = rt.stats.commits; + rt.frame(0.05); + let first = rt.instances[0].fill[3]; + assert_eq!(rt.instances[0].params[1], KIND_LAYER); + rt.frame(0.05); + assert!(rt.instances[0].fill[3] < first); + assert_eq!(rt.instances[1].fill[3], 1.0); + for _ in 0..24 { rt.frame(1.0 / 60.0); } + assert!(rt.instances.is_empty()); + assert_eq!(rt.stats.commits, commits); +} + +#[test] +fn isolated_layers_preserve_image_video_spring_and_list_order() { + use crate::native_surface::{ByteFrame, ColorInfo, Format, NativeSurface, SurfaceDraw, SurfaceFit}; + use crate::gpu::springs::{Node, Track}; + use crate::pixels::Pixels; + let gpu = Gpu::headless(); + let bounds = [4.0, 4.0, 24.0, 8.0]; + let mut content = group(bounds, 0.5, [1.0, 0.0, 0.0, 1.0]); + // A glyph, a vector and a page-1 image inside the nonzero-origin layer. Absolute spring + // indices differ from local draw indices, so a shifted subrange would use the wrong node. + let mut atlas = crate::text::TextSystem::default().atlas; + atlas.data.resize(crate::text::ATLAS_SIZE.pow(2) as usize, 0); + atlas.data[0] = 255; atlas.dirty = Some((0, 1)); + content.insert(3, Instance { rect: [9.0, 6.0, 1.0, 1.0], fill: [1.0; 4], clip: NO_CLIP, + params: [0.0, KIND_GLYPH, 0.0, 1.0], ..Instance::zeroed() }); + let px = Pixels::new(); px.set(1, 1, vec![0, 255, 0, 255]); + let mut images = crate::pixels::ImageAtlas::default(); + let full_page = Pixels::new(); full_page.set(1024, 1024, vec![255; 1024 * 1024 * 4]); + images.place(&full_page, [1024.0; 2]).unwrap(); + let image = images.place(&px, [2.0, 2.0]).unwrap(); + assert_eq!(image.page, 1); + content.insert(4, Instance { rect: [15.0, 6.0, 2.0, 2.0], fill: [0.0, 0.0, 0.0, 1.0], + params: [image.page as f32, KIND_IMAGE, 0.0, 1.0], uv: image.rect.map(|v| v as f32), clip: NO_CLIP, ..Instance::zeroed() }); + let prefix = [rect([0.0, 0.0, 2.0, 2.0], [1.0; 4])]; + let zero = Track::constant(0.0); + let nodes = [Node { x: zero, y: zero, opacity: Track::constant(1.0) }, + Node { x: Track::constant(1.0), y: zero, opacity: Track::constant(1.0) }]; + let mut ids = vec![0; prefix.len() + content.len()]; + ids[4] = 1; // glyph at absolute index 4, translated from x=9 to x=10 + let mut renderer = Renderer::with_springs(&gpu.device, OFFSCREEN_FORMAT, &nodes, &ids); + let ranges = renderer.prepare_lists(&gpu.device, &gpu.queue, &mut atlas, &[&prefix, &content], (32, 16)); + renderer.upload_images(&gpu.device, &gpu.queue, &mut images); + let surface = NativeSurface::new(); + surface.push_bytes(ByteFrame { width: 2, height: 2, format: Format::Bgra, color: ColorInfo::default(), + planes: [vec![255, 0, 0, 255].repeat(4), vec![]] }, 1).unwrap(); + renderer.prepare_surfaces(&gpu.device, &gpu.queue, &[SurfaceDraw { surface, fit: SurfaceFit::Fill, + before_instance: 4, rect: [22.0, 6.0, 2.0, 2.0], radii: [0.0; 4], clip: NO_CLIP, fade: [0; 4], opacity: 1.0 }], (32, 16)); + let format = wgpu::TextureFormat::Rgba8Unorm; + renderer.add_format(&gpu.device, format); + let target = Offscreen::with_format(&gpu.device, 32, 16, format); + let mut enc = gpu.device.create_command_encoder(&Default::default()); + renderer.encode_layers(&mut enc); + { + let mut pass = enc.begin_render_pass(&wgpu::RenderPassDescriptor { + label: None, color_attachments: &[Some(wgpu::RenderPassColorAttachment { + view: &target.view, depth_slice: None, resolve_target: None, + ops: wgpu::Operations { load: wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT), store: wgpu::StoreOp::Store }, + })], depth_stencil_attachment: None, timestamp_writes: None, occlusion_query_set: None, multiview_mask: None, + }); + for range in ranges { renderer.draw_range(&mut pass, format, range); } + } + target.copy(&mut enc); renderer.submit(&gpu.queue, enc); + let out = target.read(&gpu.device); + for (x, y, want) in [(0,0,[255;4]), (9,6,[128,0,0,128]), (10,6,[128;4]), (15,6,[0,128,0,128]), (22,6,[0,0,128,128])] { + near(&out[(y*32+x)*4..(y*32+x+1)*4], want); + } +} diff --git a/app/vendor/rune/crates/rune/src/runtime/layout_read.rs b/app/vendor/rune/crates/rune/src/runtime/layout_read.rs new file mode 100644 index 0000000..69b4373 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/layout_read.rs @@ -0,0 +1,736 @@ +//! Reading an element's laid-out rect: `Cx::layout` (or only what a view computes from it, +//! `Cx::layout_with` and `Cx::layout_size`) for views, `El::on_layout` for handlers, and +//! `El::on_screen_layout` for handlers in global screen points (the rect plus the window origin +//! its host reports through `Runtime::set_window_origin`). +//! +//! A `layout_with` read keeps its function, and re-runs its view only when the function gives +//! the new rect something other than it gave the old one, so a size read doesn't re-run when +//! the element only moves, and a "scrolled past the top" flag only when it flips. +//! +//! All of them see where layout puts an element, never a frame of its spring, so they don't +//! re-run through animations. View reads see it unscrolled (window points with every viewport +//! at its origin), so scrolling re-runs no view. None of them apply an ancestor's visual +//! transform (`El::scale`): they're layout points. `Cx::window_layout` and +//! `Cx::window_layout_with` read it after scrolling, under a key no element can have +//! ([`window_key`]), and handlers hear it after scrolling. A view reading something its own +//! output resizes (its own size, say) can feed back into itself; that settles instead of +//! looping: +//! - Inside a commit, the view re-runs while what it read moved, at most [`PASSES`] more times. +//! The values it is given next are then the final layout's, so nothing re-runs by itself. +//! - Between commits, only scrolling moves a window read, which re-runs readers next frame. +//! - Commits caused only by layout reads or `on_layout`, with no scroll moving, count up; past +//! [`ECHOES`] in a row, reads and `on_layout` stop causing commits until anything else +//! commits or a scroll moves. Reads get the current rects at the next commit. +//! +//! What a view is given for each key stays what its reads last saw until a read of the key +//! moves or a commit runs the view again, so movement below a read's threshold adds up until +//! it counts. +use std::any::TypeId; +use std::rc::Rc; + +use super::*; +use super::key_index::{self, KeyIndex}; + +#[path = "selection/rects.rs"] +mod selection_rects; +pub(crate) use selection_rects::{SELECTION, SelectedRange, boxes_moved}; + +/// Extra measurements one commit may take while a read moves. +const PASSES: usize = 2; +/// Commits in a row that layout feedback alone may cause. +const ECHOES: u32 = 4; + +/// Whether layout feedback may still cause a commit (see the module docs). Commits that only +/// layout reads or `on_layout` caused count up; past [`ECHOES`] in a row they stop causing +/// commits until anything else commits or a scroll moves. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum Feedback { + /// Feedback may still cause a commit; `run` commits in a row were its alone. + Open { run: u32 }, + /// Too many in a row: reads and `on_layout` cause none until another cause reopens them. + Quiet, +} + +impl Default for Feedback { + fn default() -> Self { Feedback::Open { run: 0 } } +} + +/// What a frame's commits say about layout feedback. +#[derive(Clone, Copy, Debug)] +pub(super) enum FeedbackEvent { + /// A commit: layout reads or `on_layout` caused it (`feedback`), and whether something else + /// did too. + Commit { feedback: bool, other: bool }, + /// A scroll, or the window moving, reopened feedback. + Reopened, +} + +impl Feedback { + /// The state after `event`. + pub(in crate::runtime) fn step(self, event: FeedbackEvent) -> Feedback { + match (self, event) { + (_, FeedbackEvent::Reopened) => Feedback::Open { run: 0 }, + (_, FeedbackEvent::Commit { other: true, .. }) => Feedback::Open { run: 0 }, + (Feedback::Open { run }, FeedbackEvent::Commit { feedback: true, .. }) => { + match run + 1 { + run if run < ECHOES => Feedback::Open { run }, + _ => Feedback::Quiet, + } + } + (state, FeedbackEvent::Commit { .. }) => state, + } + } + + /// Whether feedback may still cause a commit. + pub(in crate::runtime) fn open(self) -> bool { matches!(self, Feedback::Open { .. }) } +} +/// A rect counts as moved when an edge moves more than this (points). +const MOVED: f32 = 0.5; + +type SameFn = dyn Fn([f32; 4], [f32; 4]) -> bool; + +/// Whether two rects give a `Cx::layout_with` read's function the same value. +#[derive(Clone)] +pub(crate) enum Same { + /// A function that captures nothing (`layout_size`'s, say): no allocation, and two reads + /// with the same function are one dependency. + Static(&'static SameFn, TypeId), + /// One that captures something. + Shared(Rc<SameFn>), +} + +impl Same { + pub(crate) fn new<T: PartialEq, F: Fn([f32; 4]) -> T + 'static>(f: F) -> Same { + let same = move |a: [f32; 4], b: [f32; 4]| f(a) == f(b); + if std::mem::size_of_val(&same) == 0 { + // Leaking a zero-sized value allocates and leaks nothing. + Same::Static(Box::leak(Box::new(same)), TypeId::of::<F>()) + } else { + Same::Shared(Rc::new(same)) + } + } + + /// Whether `a` and `b` give the function the same value. + pub(crate) fn holds(&self, a: [f32; 4], b: [f32; 4]) -> bool { + match self { + Same::Static(f, _) => f(a, b), + Same::Shared(f) => f(a, b), + } + } + + /// Whether `self` and `other` are the same function. + pub(crate) fn is(&self, other: &Same) -> bool { + match (self, other) { + (Same::Static(_, a), Same::Static(_, b)) => a == b, + (Same::Shared(a), Same::Shared(b)) => Rc::ptr_eq(a, b), + _ => false, + } + } + + /// Whether the function's value differs between rects `a` and `b`; an element appearing or + /// going counts. + pub(crate) fn moved(&self, a: Option<[f32; 4]>, b: Option<[f32; 4]>) -> bool { + match (a, b) { + (Some(a), Some(b)) => !self.holds(a, b), + (a, b) => a.is_some() != b.is_some(), + } + } +} + +/// One layout read a view made: the element's key, and what of its rect the view depends on. +#[derive(Clone)] +pub(crate) struct LayoutRead { + pub(crate) key: String, + /// The `layout_with` function's check, or `None` for the whole rect (`Cx::layout`). + pub(crate) same: Option<Same>, + /// Where the view called the `Cx` read, for the debug scroll-commit warning. + pub(crate) at: Option<&'static std::panic::Location<'static>>, +} + +impl LayoutRead { + fn moved(&self, a: Option<[f32; 4]>, b: Option<[f32; 4]>) -> bool { + match &self.same { + None => moved(a, b), + Some(same) => same.moved(a, b), + } + } +} + +/// The layout reads a view made. +pub(crate) type LayoutReads = Vec<LayoutRead>; + +/// Counts a read of `key` in `reads`, once per kind: a whole-rect read once, and each +/// `layout_with` function once. A whole-rect read doesn't cover a function's read, since it +/// ignores changes a function may see (a 0.4 pt resize, say). +pub(crate) fn note_read(reads: &mut LayoutReads, key: &str, same: Option<Same>) { + note_read_at(reads, key, same, None); +} + +/// [`note_read`] of a read made at `at`. +pub(crate) fn note_read_at(reads: &mut LayoutReads, key: &str, same: Option<Same>, at: Option<&'static std::panic::Location<'static>>) { + let counted = reads.iter().any(|r| r.key == key && match (&r.same, &same) { + (None, None) => true, + (Some(a), Some(b)) => a.is(b), + _ => false, + }); + if !counted { reads.push(LayoutRead { key: key.to_owned(), same, at }); } +} + +/// What each key a view read resolved to, as last given to the view, and the selection's line +/// boxes when it read them ([`SELECTION`]). +#[derive(Clone, Default)] +pub(crate) struct LayoutRects { + rects: HashMap<String, Option<[f32; 4]>>, + pub(crate) selection: Rc<[[f32; 4]]>, +} + +impl std::ops::Deref for LayoutRects { + type Target = HashMap<String, Option<[f32; 4]>>; + fn deref(&self) -> &Self::Target { &self.rects } +} + +impl std::ops::DerefMut for LayoutRects { + fn deref_mut(&mut self) -> &mut Self::Target { &mut self.rects } +} + +/// The last view's layout reads, and what each key resolved to. +#[derive(Default)] +pub(crate) struct LayoutSeen { + pub(crate) rects: LayoutRects, + pub(super) reads: LayoutReads, +} + +impl LayoutSeen { + pub(crate) fn is_empty(&self) -> bool { + self.reads.is_empty() + } +} + +/// The rect `rects` holds for `key`, when the view read it. +pub(crate) fn seen_rect(rects: &LayoutRects, key: &str) -> Option<[f32; 4]> { + rects.get(key).copied().flatten() +} + +impl cx::CxCore { + #[track_caller] + pub(crate) fn layout(&self, key: &str) -> Option<[f32; 4]> { + note_read_at(&mut self.layout_reads.borrow_mut(), key, None, Some(std::panic::Location::caller())); + let rect = seen_rect(&self.layout, key); + crate::memo::read_layout(key, rect); + rect + } + + #[track_caller] + pub(crate) fn layout_with<T: PartialEq + 'static>(&self, key: &str, f: impl Fn([f32; 4]) -> T + 'static) -> Option<T> { + let rect = seen_rect(&self.layout, key); + let value = rect.map(&f); + let same = Same::new(f); + crate::memo::read_layout_with(key, &same, rect); + note_read_at(&mut self.layout_reads.borrow_mut(), key, Some(same), Some(std::panic::Location::caller())); + value + } + + #[track_caller] + pub(crate) fn layout_size(&self, key: &str) -> Option<[f32; 2]> { + self.layout_with(key, size) + } + + #[track_caller] + pub(crate) fn window_layout(&self, key: &str) -> Option<[f32; 4]> { + self.layout(&window_key(key)) + } + + #[track_caller] + pub(crate) fn window_layout_with<T: PartialEq + 'static>(&self, key: &str, f: impl Fn([f32; 4]) -> T + 'static) -> Option<T> { + self.layout_with(&window_key(key), f) + } +} + +impl<S> Cx<S> { + /// The laid-out rect `[x, y, w, h]` of the element keyed `key` (or named by a key path such + /// as `"msg-42/body"`, as `Tx::fly_text` takes), or `None` when there is none. It is where + /// layout puts the element, not a frame of its spring, in window points as if every scroll + /// viewport it sits in were scrolled to the top-left: scrolling doesn't move it, so a read + /// inside a scrolling list costs no view run per frame. Outside any scroll viewport that's + /// where the window shows it. A view that needs where the element is in the window now, + /// after scrolling (to float something outside the list over a row, say), reads + /// [`Self::window_layout`] instead. + /// + /// Window points here are layout points: a visual transform on an ancestor, such as + /// [`El::scale`](crate::El::scale), isn't applied, because layout keeps the unscaled size. + /// Under a scaled ancestor, map a rect through that ancestor's scale and origin yourself. + /// The same holds for every layout read, [`Self::selection_rects`], [`Self::caret`] and + /// [`El::on_layout`](crate::El::on_layout). + /// + /// A view that reads it re-runs when that rect moves or resizes past half a point, in the + /// commit that moved it. Reading an element the view itself resizes (its own size, say) + /// settles: the commit re-runs the view at most twice more while the value moves, then + /// keeps the last layout, and layout reads alone can't keep causing commits. A view whose + /// output never reaches a fixed point gets a stale value rather than oscillating. + /// + /// A view that uses only part of the rect should read that part with [`Self::layout_size`] + /// or [`Self::layout_with`], which don't re-run it while the part it uses holds. + #[track_caller] + #[inline(always)] + pub fn layout(&self, key: &str) -> Option<[f32; 4]> { + self.core.layout(key) + } + + /// `f` of the rect [`Self::layout`] returns, re-running the view only when `f` of the new + /// rect differs from `f` of the old one (or the element appears or goes). Prefer it to + /// `layout` whenever the view needs something that changes less often than the rect: + /// `layout_with("card", |r| r[2] >= 400.0)` re-runs on the resizes that cross the + /// breakpoint, not on every resize. It settles on the first layout like `layout`, so the + /// first frame already has the right value. + /// + /// `f` runs again on each later layout until the view re-runs, so keep it cheap and pure. + /// A function item or a closure that captures nothing costs no more than `layout`, and + /// reading it again in the same view counts once. A closure that captures something, or a + /// `fn` pointer, isn't zero-sized: it costs an allocation per read, and each read counts + /// (and is checked) separately, so keep those out of loops. + #[track_caller] + #[inline(always)] + pub fn layout_with<T: PartialEq + 'static>(&self, key: &str, f: impl Fn([f32; 4]) -> T + 'static) -> Option<T> { + self.core.layout_with(key, f) + } + + /// `[w, h]` of the rect [`Self::layout`] returns: [`Self::layout_with`] the size. Prefer it + /// whenever the view uses only the size: it re-runs when the width or height changes, not + /// when the element only moves. + #[track_caller] + #[inline(always)] + pub fn layout_size(&self, key: &str) -> Option<[f32; 2]> { + self.core.layout_size(key) + } + + /// [`Self::layout`] where the window shows the element now, after its viewports' scrolling. + /// A view that reads it re-runs the next frame a scroll moves the element past half a + /// point, so every frame of a scroll: read it only for what has to follow the scroll, and + /// prefer [`Self::window_layout_with`] for a value that changes less often. + #[track_caller] + #[inline(always)] + pub fn window_layout(&self, key: &str) -> Option<[f32; 4]> { + self.core.window_layout(key) + } + + /// [`Self::layout_with`] of the rect [`Self::window_layout`] returns: + /// `window_layout_with("r1", |r| r[1] < 0.0)` re-runs a header on the frames row 1 scrolls + /// past the top of the window, not on every frame of the scroll. + #[track_caller] + #[inline(always)] + pub fn window_layout_with<T: PartialEq + 'static>(&self, key: &str, f: impl Fn([f32; 4]) -> T + 'static) -> Option<T> { + self.core.window_layout_with(key, f) + } +} + +/// The layout-read key a window-position read of `key` is noted under. +pub(crate) fn window_key(key: &str) -> String { + format!("{WINDOW}{key}") +} + +/// The element key a window-position read's key stands for, or `None` for an unscrolled read. +#[cfg(debug_assertions)] +pub(crate) fn window_read_key(key: &str) -> Option<&str> { + key.strip_prefix(WINDOW) +} + +/// The prefix of a window-position read's key, which no element key starts with. +const WINDOW: &str = "\u{1}window:"; + +/// `[w, h]` of `rect`. +pub(crate) fn size(rect: [f32; 4]) -> [f32; 2] { + [rect[2], rect[3]] +} + +/// Whether a whole-rect read counts `a` to `b` as a move: an edge moved past [`MOVED`], or +/// the element appeared or went. +pub(crate) fn moved(a: Option<[f32; 4]>, b: Option<[f32; 4]>) -> bool { + match (a, b) { + (Some(a), Some(b)) => a.iter().zip(b).any(|(x, y)| (x - y).abs() > MOVED), + (None, None) => false, + _ => true, + } +} + +impl types::TreeState { + /// Node `i`'s unscrolled layout rect, under its own and its ancestors' static `El::scale`, + /// `El::origin` and `El::rotate`. + pub(super) fn static_layout(&self, i: usize) -> [f32; 4] { + let t = self.nodes[i].target; + let (k, turn) = std::iter::successors(Some(i), |&p| self.nodes[p].parent) + .fold((1.0_f32, 0.0_f32), |(k, a), p| { + let [ox, oy] = self.nodes[p].vis.origin.unwrap_or([0.5, 0.5]); + (k * self.nodes[p].static_scale, a + self.nodes[p].vis.rotate + (ox - 0.5) + (oy - 0.5)) + }); + [t[0] * k + turn, t[1] * k + turn, (t[2] - t[0]) * k, (t[3] - t[1]) * k] + } +} + +impl RuntimeCore { + /// Node `i`'s laid-out rect `[x, y, w, h]` in window points, after its viewports' scrolling. + fn laid_out(&self, nodes: &[Node], i: usize) -> [f32; 4] { + self.placed(nodes, i, true) + } + + /// [`Self::laid_out`], or when not `scrolled`, where it would be with every viewport + /// scrolled to its origin, which only a commit moves. + fn placed(&self, nodes: &[Node], i: usize, scrolled: bool) -> [f32; 4] { + let unscrolled; + let scrolls = if scrolled { &self.scroll.scrolls } else { unscrolled = HashMap::default(); &unscrolled }; + let t = nodes[i].target; + let (mut dx, mut dy) = (0.0, 0.0); + let mut up = nodes[i].parent.filter(|_| nodes[i].above.is_none() && scrolled); + while let Some(p) = up { + if let Some(st) = scrolls.get(&nodes[p].id) { + dy += st.offset as f32; + dx += st.x.shift() as f32; + } + up = nodes[p].parent.filter(|_| nodes[p].above.is_none()); + } + if let Some(anc) = std::iter::successors(Some(i), |&p| nodes[p].parent).find(|&p| nodes[p].above.is_some()) + && let Some(a) = &nodes[anc].above + && let Some(k) = anchor_index(&nodes, anc, a) + { + let at = sticky::anchored_target(nodes, scrolls, k, self.viewport); + let (w, h) = (nodes[anc].target[2] - nodes[anc].target[0], nodes[anc].target[3] - nodes[anc].target[1]); + let (ax, ay) = anchor_position(a, at, (w, h), self.viewport); + dx -= ax - nodes[anc].target[0]; + dy -= ay - nodes[anc].target[1]; + } + // Layout's own size, not the edges' difference, which rounds differently where it sits. + [t[0] - dx, t[1] - dy, nodes[i].local.w, nodes[i].local.h] + } + + fn layout_of(&self, nodes: &[Node], index: Option<&KeyIndex>, key: &str) -> Option<[f32; 4]> { + if key == SELECTION { return None; } + let (key, scrolled) = key.strip_prefix(WINDOW).map_or((key, false), |key| (key, true)); + let first = match index { + Some(index) => index.first(nodes, key), + None => key_index::scan_first(nodes, key), + }; + if let Some(i) = first { + return Some(self.placed(nodes, i, scrolled)); + } + let (i, [x0, y0, x1, y1]) = self.highlight_target_with(nodes, index, None, key)?; + let node_rect = self.placed(nodes, i, scrolled); + let t = nodes[i].target; + Some([node_rect[0] + (x0 - t[0]), node_rect[1] + (y0 - t[1]), x1 - x0, y1 - y0]) + } + + /// Checks `reads` (the last view's when `None`) against `nodes` (the current frame's when + /// `None`), by what each read depends on. When one moved, or when `force`, the next view + /// gets the current rects; otherwise it keeps what the reads last saw, so drift below a + /// read's threshold adds up. Returns whether one moved. + pub(super) fn layout_moved(&mut self, reads: Option<LayoutReads>, pass: Option<(&[Node], &[SelectedRange])>, force: bool) -> bool { + let reads = reads.unwrap_or_else(|| std::mem::take(&mut self.commit.layout_seen.reads)); + #[cfg(debug_assertions)] + let nodes_given = pass.is_some(); + // A pass's own nodes are seen once; the current nodes are seen again every frame. + let own; + let (nodes, index) = match pass { + Some((nodes, _)) => { + own = (reads.len() > key_index::SCAN_READS).then(|| KeyIndex::of(nodes)); + (nodes, own.as_ref()) + } + None => { + self.tree.prepare_key_index(self.commit.commit_gen(), reads.len()); + (&self.tree.nodes[..], self.tree.key_index_for(&self.tree.nodes, self.commit.commit_gen())) + } + }; + let now: Vec<Option<[f32; 4]>> = reads.iter().map(|r| self.layout_of(nodes, index, &r.key)).collect(); + let boxes = reads.iter().any(|r| r.key == SELECTION).then(|| match pass { + Some((nodes, ranges)) => self.selection_boxes_in(nodes, ranges), + None => self.selection_boxes(), + }); + let rects = &mut self.commit.layout_seen.rects; + let moved = reads.iter().zip(&now).position(|(r, rect)| rects.get(&r.key).is_none_or(|old| r.moved(*old, *rect))); + let changed = moved.is_some() || boxes.as_ref().is_some_and(|b| boxes_moved(&rects.selection, b)); + // The once-a-frame check names the read for the scroll warning. + #[cfg(debug_assertions)] + if !nodes_given && let Some(k) = moved { self.commit.watch.meter.read(&reads[k].key, reads[k].at); } + if changed || force { + if let Some(b) = boxes { rects.selection = b.into(); } + for (r, rect) in reads.iter().zip(now) { + match rects.get_mut(&r.key) { + Some(seen) => *seen = rect, + None => { rects.insert(r.key.clone(), rect); } + } + } + } + self.commit.layout_seen.reads = reads; + changed + } + + /// Before a commit runs the view: what it is given for each key it read becomes the + /// current rect, since it re-runs anyway. + pub(super) fn refresh_layout_seen(&mut self) { + if self.commit.layout_seen.rects.is_empty() { return; } + self.tree.prepare_key_index(self.commit.commit_gen(), self.commit.layout_seen.rects.len()); + let index = self.tree.key_index_for(&self.tree.nodes, self.commit.commit_gen()); + let now: Vec<_> = self.commit.layout_seen.rects.keys().map(|k| self.layout_of(&self.tree.nodes, index, k)).collect(); + for (seen, rect) in self.commit.layout_seen.rects.values_mut().zip(now) { *seen = rect; } + if self.commit.layout_seen.rects.contains_key(SELECTION) { self.commit.layout_seen.rects.selection = self.selection_boxes().into(); } + } + + /// Once a frame: whether a layout read moved, so the view re-runs. Scrolling reopens + /// feedback first, so the first scroll frame after feedback stopped still checks. + pub(super) fn layout_reads_moved(&mut self) -> bool { + if self.commit.layout_seen.is_empty() { return false; } + if self.scrolling() { self.commit.step_feedback(FeedbackEvent::Reopened); } + if self.selection_read_moved() { self.commit.dirty = true; } + self.layout_feedback_open() && self.layout_moved(None, None, false) + } + + /// Re-measures `measured` while a layout read moved, at most [`PASSES`] times, then leaves + /// the reads matching the final layout so a view that can't settle doesn't loop. Keys no + /// pass read any more go only at the end, so one read behind a gate the next pass opens + /// keeps its rect. + pub(super) fn settle_layout_reads(&mut self, app: &dyn ViewDriver, mut measured: Measured, tx: &Tx) -> Measured { + if measured.layout_reads.is_empty() { + self.commit.layout_seen = LayoutSeen::default(); + return measured; + } + let mut settled = false; + for _ in 0..PASSES { + if !self.layout_moved(Some(std::mem::take(&mut measured.layout_reads)), Some((&measured.nodes, &measured.selection)), false) { + settled = true; + break; + } + self.discard_measured(measured); + measured = self.measure(app, tx); + } + if !settled { self.layout_moved(Some(std::mem::take(&mut measured.layout_reads)), Some((&measured.nodes, &measured.selection)), true); } + let LayoutSeen { rects, reads } = &mut self.commit.layout_seen; + rects.retain(|k, _| reads.iter().any(|r| r.key == *k)); + if !rects.contains_key(SELECTION) { rects.selection = Rc::default(); } + measured + } + + /// Whether layout feedback may still cause a commit (see the module docs). + pub(super) fn layout_feedback_open(&self) -> bool { + self.commit.feedback_open() + } + + /// Counts a frame's commit toward [`ECHOES`]: `feedback` when layout reads or `on_layout` + /// caused it, `other` when anything else did. + pub(super) fn count_layout_echo(&mut self, feedback: bool, other: bool) { + let event = if other || self.scrolling() { FeedbackEvent::Reopened } else { FeedbackEvent::Commit { feedback, other } }; + self.commit.step_feedback(event); + } + + /// A hand, momentum, an instant scroll or a glide moves a viewport. + pub(crate) fn scrolling(&self) -> bool { + self.scroll.scrolls.values().any(|st| st.direct() || st.moving()) + } + + /// Queues `on_layout` and `on_screen_layout` for elements whose laid-out rect changed (or + /// that were just laid out). + pub(super) fn report_layout(&mut self) { + let quiet = !self.layout_feedback_open(); + self.report_rects(quiet, false); + self.report_rects(quiet, true); + } + + /// The host's window content moved to `origin`, its top-left in global screen points. + /// Queues `on_screen_layout` for the elements that moved with it; true when it queued any, + /// so the host draws a frame to deliver them. A window move is outside feedback, like a + /// scroll, so it reopens layout feedback (see the module docs). + pub(crate) fn set_window_origin(&mut self, origin: (f32, f32)) -> bool { + if !self.host.set_window_origin(origin) { return false; } + self.commit.step_feedback(FeedbackEvent::Reopened); + self.report_rects(false, true) + } + + /// Queues `on_drawn_layout` for elements whose drawn rect moved since it last reported, + /// once their own and their ancestors' springs rest. A move its laid-out rect explains is + /// layout feedback and falls quiet with the rest of it; one it doesn't (a live value) always + /// reports, as scrolling reopens feedback. True when it queued any. + pub(super) fn report_drawn(&mut self) -> bool { + if !self.tree.has_drawn_layout() && self.commit.drawn_fired_empty() { return false; } + let mut queued = false; + let quiet = !self.layout_feedback_open(); + let last = self.commit.take_drawn_fired(); + let mut fired = HashMap::with_capacity_and_hasher(last.len(), Default::default()); + for i in 0..self.tree.nodes.len() { + let n = &self.tree.nodes[i]; + if n.handlers.get().is_none_or(|h| h.on_drawn_layout.is_none()) || self.subtree_exiting(i) { continue; } + let Some(&drawn) = self.paint.drawn.get(i) else { continue }; + let id = n.id; + if self.rect_springing(i) { + if let Some(old) = last.get(&id) { fired.insert(id, *old); } + continue; + } + let laid = self.tree.static_layout(i); + let old = last.get(&id).copied(); + if !moved(old.map(|o| o.0), Some(drawn)) { + fired.insert(id, old.unwrap_or((drawn, laid))); + continue; + } + let external = old.is_some_and(|(_, l)| !moved(Some(l), Some(laid))); + if quiet && !external { + fired.insert(id, (drawn, laid)); + continue; + } + let path = n.path.clone(); + self.frame.queue.retain(|a| !matches!(a, Action::DrawnLayout(p, ..) if *p == path)); + self.frame.queue.push(Action::DrawnLayout(path, drawn, external)); + fired.insert(id, (drawn, laid)); + queued = true; + } + self.commit.set_drawn_fired(fired); + queued + } + + /// Writes each element's drawn rect to its `El::drawn_rect_into` value, on every frame it + /// moves (scrolls, glides and springs included), with no handler and no commit. True when + /// one this window binds changed, so the next frame shows what follows it. + pub(super) fn write_drawn_rects(&mut self) -> bool { + if !self.tree.has_drawn_layout() { return false; } + let mut wrote = false; + for (i, n) in self.tree.nodes.iter().enumerate() { + let Some(live) = n.handlers.get().and_then(|h| h.drawn_rect.as_ref()) else { continue }; + if let Some(&drawn) = self.paint.drawn.get(i) && !self.subtree_exiting(i) { wrote |= live.set(drawn); } + } + wrote && self.live_pending() + } + + /// Whether a spring is moving node `i`'s drawn rect: its own, its anchor's, or an ancestor's. + pub(super) fn rect_springing(&self, i: usize) -> bool { + let store = self.scene.store(); + let n = &self.tree.nodes[i]; + self.motion.flights().iter().any(|f| f.lands(&n.path, n.key.as_deref())) + || std::iter::successors(Some(i), |&p| step_up(&self.tree.nodes, p)).any(|p| { + let id = self.tree.nodes[p].id; + store.is_animating(id, prop::FRAME) || store.is_animating(id, prop::TRAVEL) || store.is_animating(id, prop::PRESENCE) + || store.is_animating(id, prop::OFFSET) || store.is_animating(id, prop::SCALE) || store.is_animating(id, P_PRESS_SCALE) + || store.is_animating(id, P_SCALE) || store.is_animating(id, prop::ROTATION) + || self.motion.grows.get(&id).is_some_and(|g| g.moving()) + || self.motion.stacks.get(&id).is_some_and(|s| s.moving) + || self.scroll.scrolls.get(&id).is_some_and(|s| s.slack.height() > 0.0 || s.glide().is_some()) + }) + } + + /// Queues `on_layout`, or `on_screen_layout` when `screen`, for rects that moved; true when + /// it queued any. + fn report_rects(&mut self, quiet: bool, screen: bool) -> bool { + let last = self.commit.take_layout_fired(screen); + // On screen, the view's points are the window's over its zoom. + let ((ox, oy), k) = if screen { (self.host.window_origin(), self.host.zoom()) } else { ((0.0, 0.0), 1.0) }; + let mut fired = HashMap::with_capacity_and_hasher(last.len(), Default::default()); + let mut queued = false; + for i in 0..self.tree.nodes.len() { + let n = &self.tree.nodes[i]; + if n.handlers.get().is_none_or(|h| if screen { h.on_screen_layout.is_none() } else { h.on_layout.is_none() }) || self.subtree_exiting(i) { continue; } + let id = n.id; + let [x, y, w, h] = self.laid_out(&self.tree.nodes, i); + let r = [x * k + ox, y * k + oy, w * k, h * k]; + if !quiet && moved(last.get(&id).copied(), Some(r)) { + let path = self.tree.nodes[i].path.clone(); + queued = true; + if screen { + // Several moves between frames (a window drag) deliver only the latest. + self.frame.queue.retain(|a| !matches!(a, Action::ScreenLayout(p, _) if *p == path)); + self.frame.queue.push(Action::ScreenLayout(path, r)); + } else { + self.frame.queue.push(Action::Layout(path, r)); + } + } else if let Some(old) = last.get(&id).filter(|_| !quiet) { + // Unchanged: keep the rect last reported, so drift below the threshold adds up. + fired.insert(id, *old); + continue; + } + fired.insert(id, r); + } + self.commit.set_layout_fired(screen, fired); + queued + } +} + +#[cfg(test)] +mod tests { + use crate::{Env, Runtime, col, el}; + + #[derive(Default)] + struct S { screen: Vec<[f32; 4]>, local: Vec<[f32; 4]> } + + fn view(_: &S, _: &mut crate::Cx<S>) -> crate::El { + col().w_full().h_full().padding(10.0).child(el().key("card").w(100.0).h(40.0) + .on_layout(|s: &mut S, r| s.local.push(r)) + .on_screen_layout(|s: &mut S, r| s.screen.push(r))) + } + + fn frames(rt: &mut Runtime<S>, n: usize) { + for _ in 0..n { rt.frame(1.0 / 120.0); } + } + + #[test] + fn reads_of_one_key_count_once_per_function_and_once_for_the_whole_rect() { + use super::{LayoutRead, Same, note_read, size}; + let mut reads: Vec<LayoutRead> = Vec::new(); + for _ in 0..3 { note_read(&mut reads, "a", Some(Same::new(size))); } + assert!(matches!(reads[..], [LayoutRead { same: Some(Same::Static(..)), .. }]), "no allocation, one dependency"); + let top = 3.0; + note_read(&mut reads, "a", Some(Same::new(move |r: [f32; 4]| r[1] < top))); + assert!(matches!(reads[1].same, Some(Same::Shared(_)))); + note_read(&mut reads, "b", Some(Same::new(size))); + note_read(&mut reads, "a", None); + note_read(&mut reads, "a", Some(Same::new(size))); + let kept: Vec<_> = reads.iter().map(|r| (r.key.as_str(), r.same.is_some())).collect(); + assert_eq!(kept, [("a", true), ("a", true), ("b", true), ("a", false)], "a whole-rect read keeps the value reads"); + } + + #[test] + fn a_screen_rect_is_the_laid_out_rect_plus_the_window_origin() { + let mut rt = Runtime::new(S::default(), view, (300.0, 200.0), Env::new(true, 2.0)); + assert!(!rt.set_window_origin((400.0, 250.0)), "nothing laid out yet"); + rt.frame(0.0); + frames(&mut rt, 4); + assert_eq!(rt.state.local, [[10.0, 10.0, 100.0, 40.0]]); + assert_eq!(rt.state.screen, [[410.0, 260.0, 100.0, 40.0]], "first layout, origin added"); + } + + #[test] + fn moving_the_window_reports_screen_rects_without_a_relayout() { + let mut rt = Runtime::new(S::default(), view, (300.0, 200.0), Env::new(true, 2.0)); + rt.set_window_origin((400.0, 250.0)); + rt.frame(0.0); + frames(&mut rt, 4); + let commits = rt.stats.commits; + + // A move draws a frame that delivers the new rect; on_layout hears nothing. + assert!(rt.set_window_origin((1700.0, -80.0)), "queued, so the host draws"); + frames(&mut rt, 2); + assert_eq!(rt.state.screen.last(), Some(&[1710.0, -70.0, 100.0, 40.0])); + assert_eq!(rt.state.local.len(), 1, "on_layout is window points: unmoved"); + + // Below half a point it waits, and the drift adds up until it counts. + assert!(!rt.set_window_origin((1700.3, -80.0))); + assert!(rt.set_window_origin((1700.6, -80.0))); + frames(&mut rt, 2); + assert_eq!(rt.state.screen.len(), 3, "{:?}", rt.state.screen); + assert!((rt.state.screen[2][0] - 1710.6).abs() < 1e-3, "{:?}", rt.state.screen); + + // A drag's moves between two frames deliver only the latest. + rt.set_window_origin((1800.0, 0.0)); + rt.set_window_origin((1900.0, 0.0)); + frames(&mut rt, 2); + assert_eq!(&rt.state.screen[3..], [[1910.0, 10.0, 100.0, 40.0]]); + assert!(rt.stats.commits > commits, "handlers changed state"); + + // Settled: nothing more runs. + let (screen, commits) = (rt.state.screen.len(), rt.stats.commits); + frames(&mut rt, 10); + assert_eq!((rt.state.screen.len(), rt.stats.commits), (screen, commits)); + } + + #[test] + fn a_window_move_with_no_screen_handler_asks_for_no_frame() { + let mut rt = Runtime::new(S::default(), |_: &S, _: &mut crate::Cx<S>| { + el().key("card").w(100.0).h(40.0).on_layout(|s: &mut S, r| s.local.push(r)) + }, (300.0, 200.0), Env::new(true, 2.0)); + rt.frame(0.0); + frames(&mut rt, 2); + assert!(!rt.set_window_origin((50.0, 50.0))); + assert_eq!(rt.state.local.len(), 1); + } +} diff --git a/app/vendor/rune/crates/rune/src/runtime/line_clamp_tests.rs b/app/vendor/rune/crates/rune/src/runtime/line_clamp_tests.rs new file mode 100644 index 0000000..d4684c0 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/line_clamp_tests.rs @@ -0,0 +1,222 @@ +//! `El::max_lines`: wrapped text stops after n lines with "…" ending the last, measures n lines +//! tall, cuts between graphemes, refits on resize, and copying and tools keep the whole string. +use super::*; +use crate::{Color, Cx, El, Env, Key, KeyEvent, Link, Mods, Span, TextStyle, col, rich}; +use unicode_segmentation::UnicodeSegmentation; + +const TITLE: &str = "Move the sidebar's search into the toolbar, keep its results in the list, and let the \ + filter chips wrap onto a second row when the window is narrow enough that they would overflow"; + +fn style() -> TextStyle { TextStyle::new(13.0, 400.0).lh(16.0) } + +/// Content, the line limit, and a byte range that is both a coloured span and a link. +type S = (&'static str, usize, Option<(usize, usize)>); + +fn mark() -> Color { crate::color::hex("#e6339a").unwrap() } + +fn clamp(content: &'static str, lines: usize, marked: Option<(usize, usize)>, width: f32) -> Runtime<S> { + fn view(s: &S, _: &mut Cx<S>) -> El { + let spans = s.2.map(|(a, b)| Span { color: Some(mark()), ..Span::new(a, b) }).into_iter().collect(); + let mut t = rich(s.0, spans).key("t").font(style()).selectable(true).max_lines(s.1); + if let Some((a, b)) = s.2 { t = t.link(Link::new(a..b, "marked")).on_link(|_: &mut S, _, _| {}); } + col().w_full().child(t) + } + let mut rt = Runtime::new((content, lines, marked), view, (width, 400.0), Env::new(true, 2.0)); + rt.frame(0.0); + rt +} + +fn node<'a>(rt: &'a Runtime<S>) -> &'a Node { + rt.tree.nodes.iter().find(|n| n.key.as_deref() == Some("t")).unwrap() +} + +/// The string node "t" draws, its cut, its line count and its height in points. +fn drawn(rt: &Runtime<S>) -> (String, Option<Elision>, usize, f32) { + let n = node(rt); + let content = &n.text.as_ref().unwrap().content; + let shown = match n.elided { + Some(e) => [&content[..e.head], "…", &content[e.tail..]].concat(), + None => content.clone(), + }; + (shown, n.elided, n.text_layout.as_ref().and_then(crate::text::TextLayout::single).unwrap().len(), n.target[3] - n.target[1]) +} + +#[test] +fn stops_after_n_lines_with_an_ellipsis_and_measures_n_lines() { + let mut rt = clamp(TITLE, 3, None, 200.0); + let (shown, e, lines, h) = drawn(&rt); + let e = e.expect("the title runs past three lines at 200 pt"); + assert!(shown.ends_with('…') && !shown[..shown.len() - "…".len()].ends_with(' '), "{shown}"); + assert_eq!(e.tail, TITLE.len(), "everything after the cut is hidden"); + assert_eq!((lines, h), (3, 48.0), "three 16 pt lines: {shown}"); + let el = rt.elements().into_iter().find(|e| e.key.as_deref() == Some("t")).unwrap(); + assert_eq!(el.text.as_deref(), Some(TITLE), "tools and accessibility read the whole title"); + + rt.set_viewport((320.0, 400.0), 2.0); + rt.frame(0.1); + let (wider, _, lines, h) = drawn(&rt); + assert!(wider.len() > shown.len() && (lines, h) == (3, 48.0), "a wider box keeps more: {wider}"); + + rt.set_viewport((2000.0, 400.0), 2.0); + rt.frame(0.2); + let (all, e, lines, h) = drawn(&rt); + assert_eq!((all.as_str(), e, lines, h), (TITLE, None, 1, 16.0), "room for it all: no cut, one line tall"); + + rt.set_viewport((200.0, 400.0), 2.0); + rt.frame(0.3); + assert_eq!(drawn(&rt).0, shown, "narrowing again cuts as before"); +} + +#[test] +fn text_within_the_limit_is_untouched() { + let rt = clamp("Short title", 3, None, 200.0); + assert_eq!(drawn(&rt), ("Short title".to_owned(), None, 1, 16.0)); + // 0 shows every line. + let rt = clamp(TITLE, 0, None, 200.0); + let (shown, e, lines, h) = drawn(&rt); + assert!(shown == TITLE && e.is_none() && lines > 3 && h == 16.0 * lines as f32); +} + +#[test] +fn a_line_break_before_the_cut_is_dropped() { + let rt = clamp("first\nsecond\nthird", 2, None, 400.0); + assert_eq!(drawn(&rt).0, "first\nsecond…"); + assert_eq!(drawn(&rt).3, 32.0); +} + +#[test] +fn cuts_fall_between_graphemes() { + const MIXED: &str = "👩‍👩‍👧‍👦 cafe\u{301} שלום עולם 🇯🇵 नमस्ते e\u{301}e\u{301}e\u{301} 👩‍👩‍👧‍👦 done and some more words to wrap 👩‍👩‍👧‍👦"; + let bounds: Vec<usize> = MIXED.grapheme_indices(true).map(|(i, _)| i).chain([MIXED.len()]).collect(); + let mut rt = clamp(MIXED, 2, None, 60.0); + let mut cuts = 0; + for w in (60..400).step_by(7) { + rt.set_viewport((w as f32, 400.0), 2.0); + rt.frame(1.0); + let (shown, e, lines, _) = drawn(&rt); + let Some(e) = e else { continue }; + cuts += 1; + assert!(lines <= 2, "{w}: {shown}"); + assert!(bounds.contains(&e.head), "{w}: {e:?} splits a grapheme: {shown}"); + } + assert!(cuts > 10, "most widths cut: {cuts}"); +} + +#[test] +fn copying_a_clamped_text_copies_all_of_it() { + let mut rt = clamp(TITLE, 2, None, 200.0); + let r = node(&rt).target; + let (x, y) = (r[0] + 20.0, r[1] + 8.0); + rt.pointer_move(x, y); + rt.pointer_down(x, y); + rt.pointer_up(x, y); + rt.frame(1.0); + rt.key(KeyEvent { key: Key::Command('a'), mods: Mods { cmd: true, ..Mods::default() } }); + rt.frame(1.1); + assert_eq!(rt.selected_text().as_deref(), Some(TITLE)); +} + +#[test] +fn spans_and_links_past_the_cut_are_hidden() { + let at = TITLE.find("overflow").unwrap(); + let marked = (at, at + "overflow".len()); + let coloured = |rt: &Runtime<S>| { + let want = mark().premul(1.0); + rt.instances.iter().filter(|i| i.fill.iter().zip(want).all(|(a, b)| (a - b).abs() < 1e-3)).count() + }; + let rt = clamp(TITLE, 2, Some(marked), 200.0); + assert!(drawn(&rt).1.is_some_and(|e| e.head < marked.0)); + assert!(!rt.elements().iter().any(|e| e.path.ends_with("#link-0")), "a link past the cut isn't pressable"); + assert_eq!(coloured(&rt), 0); + let rt = clamp(TITLE, 0, Some(marked), 200.0); + assert!(rt.elements().iter().any(|e| e.path.ends_with("#link-0"))); + assert!(coloured(&rt) > 0, "shown, the span draws its colour"); +} + +/// One word with no break opportunity, wider than the box. +const TOKEN: &str = "line_clamp_measures_the_whole_identifier_before_it_decides_where_the_ellipsis_falls"; + +/// The drawn last line's width and the element's, in points. +fn widths(rt: &Runtime<S>) -> (f32, f32) { + let n = node(rt); + (last_line_width(n.text_layout.as_ref().and_then(crate::text::TextLayout::single).unwrap(), n.text.as_ref().unwrap().max_lines.max(1)) / 2.0, n.target[2] - n.target[0]) +} + +#[test] +fn a_word_wider_than_the_box_is_cut_to_fit() { + let rt = clamp(TOKEN, 0, None, 200.0); + assert_eq!(drawn(&rt).2, 1, "the word shapes as one overflowing line"); + let rt = clamp(TOKEN, 1, None, 200.0); + let (shown, e, lines, h) = drawn(&rt); + assert!(e.is_some() && shown.ends_with('…') && shown.len() > 10, "{shown}"); + assert_eq!((lines, h), (1, 16.0)); + let (line, element) = widths(&rt); + assert!(line <= 200.25 && line > 150.0 && element <= 200.0, "{line} {element}: {shown}"); +} + +#[test] +fn a_wrapped_word_fills_the_last_line() { + let content: &'static str = Box::leak(format!("See {TOKEN}").into_boxed_str()); + let rt = clamp(content, 1, None, 200.0); + let (shown, _, lines, _) = drawn(&rt); + assert!(shown.starts_with("See line_") && shown.ends_with('…') && lines == 1, "{shown}"); + let (line, element) = widths(&rt); + assert!(line <= 200.25 && line > 150.0 && element <= 200.0, "{line} {element}: {shown}"); + + // In two lines the word moves to the second and is cut there. + let rt = clamp(content, 2, None, 200.0); + let (shown, _, lines, _) = drawn(&rt); + assert!(shown.starts_with("See\nline_") || shown.starts_with("See line_"), "{shown}"); + assert!(lines <= 2 && widths(&rt).0 <= 200.25, "{shown}"); + + // With `wrap_anywhere`, an unbroken token wraps across lines 1..n and cuts at the end of line n. + fn anywhere(_: &(), _: &mut Cx<()>) -> El { + col().w_full().child(crate::text(TOKEN).key("t").font(style()).wrap_anywhere().max_lines(2)) + } + let mut rt = Runtime::new((), anywhere, (200.0, 400.0), Env::new(true, 2.0)); + rt.frame(0.0); + let n = rt.tree.nodes.iter().find(|n| n.key.as_deref() == Some("t")).unwrap(); + let e = n.elided.expect("the token wraps past two lines at 200 pt"); + let l = n.text_layout.as_ref().and_then(crate::text::TextLayout::single).unwrap(); + assert_eq!(l.len(), 2, "wraps onto two lines before cutting"); + assert!(e.head > 40 && l.full_width() <= 400.5, "both lines fill the 200 pt box: head={}, width={}", e.head, l.full_width()); +} + +/// A field's caret and selection index its own text, so it takes no cut. +#[test] +fn a_text_field_ignores_the_clamp_and_truncation() { + fn view(e: &crate::TextEdit, _: &mut Cx<crate::TextEdit>) -> El { + col().w_full() + .child(crate::text_input(e, style()).key("t").w_full().max_lines(1)) + .child(crate::text_input(e, style()).key("u").w_full().truncate_middle()) + } + let mut rt = Runtime::new(crate::TextEdit::new(TITLE), view, (200.0, 400.0), Env::new(true, 2.0)); + rt.frame(0.0); + for key in ["t", "u"] { + let n = rt.tree.nodes.iter().find(|n| n.key.as_deref() == Some(key)).unwrap(); + let t = n.text.as_ref().unwrap(); + assert!(n.elided.is_none() && t.max_lines == 0 && !t.truncate, "{key}"); + let r = n.target; + let (x, y) = (r[2] - 4.0, r[1] + 8.0); + rt.pointer_move(x, y); + rt.pointer_down(x, y); + rt.pointer_up(x, y); + rt.frame(1.0); + rt.key(KeyEvent { key: Key::Right, mods: Mods::default() }); + rt.frame(1.1); + } +} + +#[test] +fn clamped_elision_cache_reuses_cut_across_commits() { + let mut rt = clamp(TITLE, 2, Some((9, 25)), 180.0); + let (_, cut0, lines0, _) = drawn(&rt); + assert_eq!(lines0, 2); + assert!(cut0.is_some()); + assert_eq!(rt.text.cached_elision_count(), 1); + let shaped_before = rt.text.shaped; + rt.invalidate(); + rt.frame(1.0 / 60.0); + assert_eq!(rt.text.shaped, shaped_before, "repeat commit reuses cached clamped cut"); + assert_eq!(drawn(&rt).1, cut0); +} diff --git a/app/vendor/rune/crates/rune/src/runtime/live_check_tests.rs b/app/vendor/rune/crates/rune/src/runtime/live_check_tests.rs new file mode 100644 index 0000000..4784f17 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/live_check_tests.rs @@ -0,0 +1,270 @@ +//! Debug builds' check of `Tx::live_only` handlers: what its warning names, and hover rows, +//! whose paint changes without a commit, that it must not flag. +use super::*; +use crate::{Cx, El, Env, Key, Mods, col, el, row, text}; + +/// Which side copies, as a diff's code cells track it: rows on the old side and the new. +#[derive(Clone, Copy, PartialEq, Debug)] +enum Side { Old, New } + +struct Rows { + copy: Side, + hovered: Vec<usize>, + changes: usize, + /// `on_selection_change` calls, which the view shows. + selections: usize, +} + +const ROW_H: f32 = 20.0; + +fn side(i: usize) -> Side { if i % 4 == 3 { Side::Old } else { Side::New } } + +/// Rows with hover paint whose code cell tracks the hovered side: it calls `Tx::live_only` on +/// the branch that changes nothing, and the copy side picks which rows' text is selectable. +fn rows_view(s: &Rows, _: &mut Cx<Rows>) -> El { + let rows = (0..24).map(|i| { + let side = side(i); + let copy = s.copy == side; + let mut t = text(format!("let value_{i} = compute({i});")).key("text"); + if copy { t = t.selectable(true).selection_color(Color::WHITE); } + let code = col().key("code").grow(1.0).min_h(ROW_H).child(t).on_hover_change(move |s: &mut Rows, inside, tx: &mut Tx| { + if inside { s.hovered.push(i) } else { s.hovered.retain(|&h| h != i) } + if inside && s.copy != side { s.copy = side; s.changes += 1; } else { tx.live_only(); } + }); + row().key(format!("r{i}")).w_full().min_h(ROW_H) + .fill(if copy { Color::BLACK } else { Color::TRANSPARENT }) + .hover(Color::WHITE.alpha(0.06)).hover_group() + .child(el().key("gutter").w(40.0).h(ROW_H).child(text(i.to_string()).key("n").group_color(Color::WHITE))) + .child(code) + }); + col().w_full().h_full().scroll(ScrollSpec { stick_bottom: false }) + .child(text(format!("{} selections", s.selections)).key("selections")) + .child(col().key("rows").w_full().selection_group(true).children(rows) + .on_selection_change(|s: &mut Rows, _, _| s.selections += 1)) +} + +fn rows_app() -> Runtime<Rows> { + let mut rt = Runtime::new(Rows { copy: Side::New, hovered: Vec::new(), changes: 0, selections: 0 }, rows_view, (400.0, 600.0), Env::new(true, 2.0)); + for _ in 0..60 { rt.frame(1.0 / 60.0); } + rt +} + +/// Below the "selections" line. +fn row_y(i: usize) -> f32 { (i + 1) as f32 * ROW_H + ROW_H / 2.0 } + +#[test] +fn hover_rows_at_rest_are_not_a_view_change() { + let mut rt = rows_app(); + // The new-side rows one after another, each move a quarter second after the last commit: + // checked, with hover tracks fading in and out. Then the same a frame apart. + for (n, i) in [0, 1, 2, 4, 5, 6, 8, 9, 10, 12, 13, 14].into_iter().enumerate() { + rt.frame(if n < 6 { 0.3 } else { 1.0 / 60.0 }); + rt.pointer_move(200.0, row_y(i)); + for _ in 0..3 { rt.frame(1.0 / 60.0); } + } + assert!(rt.frame.live_checks() >= 6, "the moves were checked: {}", rt.frame.live_checks()); + assert_eq!(rt.state.changes, 0); + assert!(rt.frame.live_only_warnings().is_empty(), "{:#?}", rt.frame.live_only_warnings()); +} + +#[test] +fn a_leave_and_an_enter_in_one_frame_blame_neither_when_the_enter_changes_state() { + let mut rt = rows_app(); + rt.frame(0.3); + rt.pointer_move(200.0, row_y(2)); + for _ in 0..30 { rt.frame(1.0 / 60.0); } + // To an old-side row a quarter second on: the leave is live-only and checked, the enter + // in the same frame changes the copy side, and the commit is the enter's. + rt.frame(0.3); + let checks = rt.frame.live_checks(); + rt.pointer_move(200.0, row_y(3)); + rt.frame(1.0 / 60.0); + assert_eq!((rt.state.copy, rt.state.changes, rt.frame.live_checks() - checks), (Side::Old, 1, 1)); + assert!(rt.frame.live_only_warnings().is_empty(), "{:#?}", rt.frame.live_only_warnings()); + let fill = |rt: &Runtime<Rows>, key: &str| rt.tree.nodes.iter().find(|n| n.key.as_deref() == Some(key)).unwrap().vis.fill; + assert_eq!(fill(&rt, "r3"), Color::BLACK, "the commit built the new copy side"); + + // The other order: the changing enter first, then a checked live-only leave. + rt.frame(0.3); + let code = |rt: &Runtime<Rows>, row: &str| rt.tree.nodes.iter() + .find(|n| n.key.as_deref() == Some("code") && n.parent.is_some_and(|p| rt.tree.nodes[p].key.as_deref() == Some(row))) + .unwrap().path.clone(); + let (enter, leave) = (code(&rt, "r4"), code(&rt, "r3")); + rt.frame.queue.push(Action::HoverChange(enter, true)); + rt.frame.queue.push(Action::HoverChange(leave, false)); + rt.frame(1.0 / 60.0); + assert_eq!((rt.state.copy, rt.state.changes), (Side::New, 2)); + assert!(rt.frame.live_only_warnings().is_empty(), "{:#?}", rt.frame.live_only_warnings()); + assert_eq!(fill(&rt, "r4"), Color::BLACK); +} + +#[test] +fn dragging_a_text_selection_across_hover_rows_blames_no_hover_handler() { + let mut rt = rows_app(); + rt.pointer_move(60.0, row_y(0)); + rt.pointer_down(60.0, row_y(0)); + for _ in 0..30 { rt.frame(1.0 / 60.0); } + // Each move enters a new-side row (a live-only hover change, checked a quarter second on) + // and grows the selection, whose handler changes what the view shows. + for i in [1, 2, 4, 5] { + rt.frame(0.3); + rt.pointer_move(200.0, row_y(i)); + rt.frame(1.0 / 60.0); + } + rt.pointer_up(200.0, row_y(5)); + rt.frame(1.0 / 60.0); + assert!(rt.state.selections > 1 && rt.frame.live_checks() >= 4, "{} selections, {} checks", rt.state.selections, rt.frame.live_checks()); + assert!(rt.frame.live_only_warnings().is_empty(), "{:#?}", rt.frame.live_only_warnings()); +} + +/// A view that builds one thing differently once a live-only key handler (wrongly) flips +/// `changed`. +struct Case { + case: u8, + changed: bool, +} + +fn case_view(s: &Case, _: &mut Cx<Case>) -> El { + let on = s.changed; + let mut c = col().key("list").w(200.0) + .child(el().key("box").w(if on && s.case == 0 { 60.0 } else { 40.0 }).h(20.0) + .fill(if on && s.case == 1 { Color::WHITE } else { Color::BLACK })) + .child(text(if on && s.case == 2 { "a much longer label than the one before it, cut short" } else { "label" }).key("label").w(200.0).h(20.0)); + if on && s.case == 3 { c = c.child(el().key("extra").size(10.0, 10.0)); } + if !(on && s.case == 4) { c = c.child(el().key("tail").size(10.0, 10.0)); } + c +} + +fn case_app(case: u8) -> Runtime<Case> { + let mut rt = Runtime::new(Case { case, changed: false }, case_view, (400.0, 400.0), Env::new(true, 1.0)); + rt.on_key = Some(|s, _, tx| { s.changed = !s.changed; tx.live_only(); true }); + rt.frame(0.0); + rt +} + +fn list_path(rt: &Runtime<Case>) -> String { + rt.tree.nodes.iter().find(|n| n.key.as_deref() == Some("list")).unwrap().path.clone() +} + +#[test] +fn the_warning_names_the_element_and_property_that_differed() { + let want = [ + r#"layout rect of "{list}/box" went from [0.0, 0.0, 40.0, 20.0] to [0.0, 0.0, 60.0, 20.0]"#, + r##"fill of "{list}/box" went from #000000ff to #ffffffff"##, + r#"text of "{list}/label" went from "label" to "a much longer label than the one before …""#, + r#"added element of "{list}/extra""#, + r#"removed element of "{list}/tail""#, + ]; + for (case, want) in want.into_iter().enumerate() { + let mut rt = case_app(case as u8); + let want = want.replace("{list}", &list_path(&rt)); + rt.frame(0.5); + rt.key(KeyEvent { key: Key::Right, mods: Mods::default() }); + rt.frame(1.0 / 60.0); + assert_eq!(rt.frame.live_only_warnings().len(), 1, "case {case}: {:?}", rt.frame.live_only_warnings()); + let w = &rt.frame.live_only_warnings()[0]; + assert!(w.starts_with("rune: on_key called Tx::live_only, but the view built something else after it: "), "{w}"); + assert!(w.contains(&want), "case {case}: {w}\nwanted {want}"); + } +} + +#[test] +fn the_warning_repeats_only_for_another_element_or_property() { + let mut rt = case_app(1); + for _ in 0..4 { + rt.frame(0.5); + rt.key(KeyEvent { key: Key::Right, mods: Mods::default() }); + rt.frame(1.0 / 60.0); + } + assert_eq!(rt.frame.live_checks(), 4); + assert_eq!(rt.frame.live_only_warnings().len(), 1, "the same handler, element and property: {:#?}", rt.frame.live_only_warnings()); + rt.state.case = 0; + rt.frame(0.5); + rt.key(KeyEvent { key: Key::Right, mods: Mods::default() }); + rt.frame(1.0 / 60.0); + assert_eq!(rt.frame.live_only_warnings().len(), 2, "{:#?}", rt.frame.live_only_warnings()); + let head = format!("layout rect of \"{}/box\"", list_path(&rt)); + assert!(rt.frame.live_only_warnings()[1].contains(&head), "{}", rt.frame.live_only_warnings()[1]); +} + +#[test] +fn a_selection_handler_after_a_checked_event_is_not_blamed_on_it() { + struct Sel { heard: u32 } + fn view(s: &Sel, _: &mut Cx<Sel>) -> El { + col().w(400.0) + .child(text("some selectable words to drag across").key("t").w(400.0).selectable(true) + .on_selection_change(|s: &mut Sel, _, _| s.heard += 1)) + .child(text(s.heard.to_string()).key("heard")) + } + let mut rt = Runtime::new(Sel { heard: 0 }, view, (400.0, 200.0), Env::new(true, 1.0)); + rt.on_key = Some(|_, _, tx| { tx.live_only(); true }); + rt.frame(0.0); + let (x, y) = rt.find("t").unwrap(); + rt.pointer_down(x - 150.0, y); + rt.pointer_move(x - 100.0, y); + for _ in 0..30 { rt.frame(1.0 / 60.0); } + // Still dragging: a checked live-only key, and the drag grows the selection in one frame. + rt.frame(0.5); + let (heard, checks) = (rt.state.heard, rt.frame.live_checks()); + rt.key(KeyEvent { key: Key::Function(5), mods: Mods::default() }); + rt.pointer_move(x + 100.0, y); + rt.frame(1.0 / 60.0); + assert_eq!(rt.frame.live_checks() - checks, 1); + assert!(rt.state.heard > heard, "the selection handler ran"); + assert!(rt.frame.live_only_warnings().is_empty(), "{:#?}", rt.frame.live_only_warnings()); +} + +/// 2,000 index-built rows whose cells call `Tx::live_only` on hover. Rows from `stale_from` on +/// show `s.hovers`, which the handler counts: state a live-only handler mustn't change. +struct Long { hovers: u32, stale_from: usize } + +fn long_app(stale_from: usize) -> Runtime<Long> { + fn view(_: &Long, _: &mut Cx<Long>) -> El { + let list = col().key("rows").w_full().growth(crate::GrowthSpec::default()) + .virtual_rows(2000, ROW_H, |_: &Long, i| format!("r{i}").into(), |s: &Long, i| { + let label = if i >= s.stale_from { format!("{i}: {}", s.hovers) } else { i.to_string() }; + col().w_full().h(ROW_H).child(text(label).key("cell").w_full().h(ROW_H) + .on_hover_change(|s: &mut Long, _, tx| { if s.stale_from < 2000 { s.hovers += 1; } tx.live_only(); })) + }); + col().w_full().h_full() + .child(col().key("scroll").w_full().grow(1.0).min_h(0.0).scroll(ScrollSpec { stick_bottom: false }).child(list)) + } + let mut rt = Runtime::new(Long { hovers: 0, stale_from }, view, (400.0, 300.0), Env::new(true, 2.0)); + rt.frame(0.0); + for _ in 0..60 { rt.frame(1.0 / 60.0); } + rt +} + +/// The viewport grows without the virtual window moving (its rows still cover it), then a +/// checked live-only hover: the check's commit must not re-pick the overscan and report the +/// rows it would add below the viewport. +#[test] +fn a_grown_viewport_does_not_make_the_overscan_a_view_change() { + let mut rt = long_app(usize::MAX); + // Each hover lands on another row. + for (row, h) in [310.0, 330.0, 360.0, 400.0].into_iter().enumerate() { + let checks = rt.frame.live_checks(); + rt.set_viewport((400.0, h), 2.0); + for _ in 0..10 { rt.frame(1.0 / 60.0); } + rt.frame(0.3); + rt.pointer_move(200.0, (row as f32 + 0.5) * ROW_H); + for _ in 0..3 { rt.frame(1.0 / 60.0); } + assert!(rt.frame.live_checks() > checks, "viewport {h}: the hover was checked"); + } + assert!(rt.frame.live_only_warnings().is_empty(), "{:#?}", rt.frame.live_only_warnings()); +} + +/// A row mounted below the viewport shows on screen when scrolled to without a commit, so a +/// live-only handler that changes it is still named after the viewport grows. +#[test] +fn a_stale_row_mounted_below_the_viewport_still_warns_after_the_viewport_grows() { + let mut rt = long_app(30); + rt.set_viewport((400.0, 360.0), 2.0); + for _ in 0..10 { rt.frame(1.0 / 60.0); } + rt.frame(0.3); + rt.pointer_move(200.0, 45.0); + for _ in 0..3 { rt.frame(1.0 / 60.0); } + assert_eq!(rt.frame.live_only_warnings().len(), 1, "{:#?}", rt.frame.live_only_warnings()); + let w = &rt.frame.live_only_warnings()[0]; + assert!(w.contains("text of") && w.contains("/rows/r30/cell"), "{w}"); +} diff --git a/app/vendor/rune/crates/rune/src/runtime/live_colors_tests.rs b/app/vendor/rune/crates/rune/src/runtime/live_colors_tests.rs new file mode 100644 index 0000000..cdfbd3c --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/live_colors_tests.rs @@ -0,0 +1,95 @@ +use super::*; +use crate::motion_gate::check::paint::{C_BORDER, C_GRADIENT, C_SHADOW, C_TEXT}; +use crate::{Live, el, text}; + +struct State { + ink: Live<Color>, + edge: Live<Color>, + glow: Live<Color>, + top: Live<Color>, + bottom: Live<Color>, + smooth: bool, + views: std::cell::Cell<u32>, +} + +fn view(s: &State, _: &mut Cx<State>) -> El { + s.views.set(s.views.get() + 1); + let card = el().key("card").size(80.0, 40.0).fill(Color::BLACK) + .border(1.0, Color::BLACK).shadow(2.0, 6.0, Color::BLACK).gradient(Color::BLACK, Color::BLACK); + let card = if s.smooth { + card.live_border(s.edge.smooth(Spring::new(0.25, 0.0))) + } else { + card.live_border(&s.edge) + }; + el().size(200.0, 200.0).child( + card.live_shadow(&s.glow).live_gradient(&s.top, &s.bottom) + .child(text("hi").key("ink").color(Color::BLACK).live_text_color(&s.ink)), + ) +} + +fn runtime(smooth: bool) -> Runtime<State> { + let s = State { + ink: Live::new(Color::WHITE), + edge: Live::new(Color::WHITE), + glow: Live::new(Color::WHITE), + top: Live::new(Color::WHITE), + bottom: Live::new(Color::WHITE), + smooth, + views: Default::default(), + }; + let mut rt = Runtime::new(s, view, (200.0, 200.0), Env::new(true, 1.0)); + rt.frame(0.0); + rt +} + +fn paint(rt: &Runtime<State>, key: &str) -> crate::motion_gate::check::paint::Paint { + let n = rt.tree.nodes.iter().find(|n| n.key.as_deref() == Some(key)).unwrap(); + rt.paints().remove(&(n.path.clone(), false)).unwrap() +} + +const RED: Color = Color { r: 1.0, g: 0.0, b: 0.0, a: 1.0 }; +const GREEN: Color = Color { r: 0.0, g: 1.0, b: 0.0, a: 1.0 }; +const BLUE: Color = Color { r: 0.0, g: 0.0, b: 1.0, a: 1.0 }; + +#[test] +fn text_border_shadow_and_gradient_colours_change_without_a_view_rerun() { + let mut rt = runtime(false); + let card = paint(&rt, "card"); + assert_eq!(card.colors[C_BORDER], Color::WHITE, "the binding wins over the authored colour"); + assert_eq!(paint(&rt, "ink").colors[C_TEXT], Color::WHITE); + let (views, commits) = (rt.state.views.get(), rt.stats.commits); + rt.state.ink.set(RED); + rt.state.edge.set(GREEN); + rt.state.glow.set(BLUE); + rt.state.top.set(RED); + rt.state.bottom.set(GREEN); + assert!(rt.live_pending()); + rt.frame(1.0 / 120.0); + assert_eq!((rt.state.views.get(), rt.stats.commits, rt.stats.shaped), (views, commits, 0)); + let card = paint(&rt, "card"); + assert_eq!(card.colors[C_BORDER], GREEN); + assert_eq!(card.colors[C_SHADOW], BLUE); + assert_eq!(card.colors[C_GRADIENT], RED); + assert_eq!(card.gradient_end, GREEN); + assert_eq!(paint(&rt, "ink").colors[C_TEXT], RED); + + rt.invalidate(); + rt.frame(0.0); + let card = paint(&rt, "card"); + assert_eq!(card.colors[C_BORDER], GREEN, "a rebuild keeps what the binding last set"); + assert_eq!(card.colors[C_SHADOW], BLUE); + assert_eq!((card.colors[C_GRADIENT], card.gradient_end), (RED, GREEN)); + assert_eq!(paint(&rt, "ink").colors[C_TEXT], RED); +} + +#[test] +fn a_smoothed_border_colour_springs_then_lands_exactly() { + let mut rt = runtime(true); + rt.state.edge.set(BLUE); + rt.frame(0.03); + let mid = paint(&rt, "card").colors[C_BORDER]; + assert!(mid.r > 0.0 && mid.r < 1.0 && mid.b == 1.0, "moving: {mid:?}"); + for _ in 0..240 { rt.frame(1.0 / 120.0); } + assert_eq!(paint(&rt, "card").colors[C_BORDER], BLUE); + assert!(!rt.animating); +} diff --git a/app/vendor/rune/crates/rune/src/runtime/live_only_tests.rs b/app/vendor/rune/crates/rune/src/runtime/live_only_tests.rs new file mode 100644 index 0000000..cd1cab1 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/live_only_tests.rs @@ -0,0 +1,302 @@ +//! `Tx::live_only` on the physical key path native windows use, and debug builds' check that +//! a live-only handler didn't change what the view reads. +use super::*; +use crate::{Cx, El, Env, Key, Live, Mods, PhysicalInput, PhysicalKeyCode, el, text}; + +struct S { + /// Read by the view. + count: u32, + /// Handlers bump `count` (what the view reads) as well as `pan`. + misuse: bool, + pan: Live<[f32; 2]>, + physical: usize, +} + +impl S { + fn nudge(&mut self, tx: &mut Tx) { + let [x, y] = self.pan.get(); + self.pan.set([x + 10.0, y]); + if self.misuse { self.count += 1; } + tx.live_only(); + } +} + +fn view(s: &S, _: &mut Cx<S>) -> El { + el().size(200.0, 200.0) + .child(el().key("camera").size(50.0, 50.0).live_offset(&s.pan).on_press(|s: &mut S| s.count += 1)) + .child(text(format!("{}", s.count)).key("count")) + .child(el().key("recorder").size(40.0, 40.0).focusable(true) + .on_physical_input(|s: &mut S, e, tx| { + if !matches!(e, PhysicalInput::Key { pressed: false, .. }) { return false; } + s.physical += 1; + s.nudge(tx); + true + })) + .on_key_up(|s: &mut S, _, tx| { s.nudge(tx); true }) +} + +fn app(misuse: bool) -> Runtime<S> { + let state = S { count: 0, misuse, pan: Live::new([0.0, 0.0]), physical: 0 }; + let mut rt = Runtime::new(state, view, (200.0, 200.0), Env::new(true, 1.0)); + rt.on_key = Some(|s, e, tx| { if e.key != Key::Right { return false; } s.nudge(tx); true }); + rt.frame(0.0); + rt +} + +fn key(code: PhysicalKeyCode, key: Key, pressed: bool) -> (PhysicalInput, Option<KeyEvent>) { + (PhysicalInput::Key { key: code, mods: Mods::default(), pressed, repeat: false }, Some(KeyEvent { key, mods: Mods::default() })) +} + +fn camera_x(rt: &Runtime<S>) -> f32 { + rt.elements().into_iter().find(|e| e.key.as_deref() == Some("camera")).unwrap().rect[0] +} + +#[test] +fn physical_keys_and_their_releases_can_be_live_only() { + let mut rt = app(false); + rt.check_live_only(false); + let before = rt.stats.commits; + let (ev, fallback) = key(PhysicalKeyCode::ArrowRight, Key::Right, true); + rt.physical_with_fallback(ev, fallback); + rt.frame(1.0 / 120.0); + let (ev, fallback) = key(PhysicalKeyCode::ArrowRight, Key::Right, false); + rt.physical_with_fallback(ev, fallback); + rt.frame(1.0 / 120.0); + rt.frame(1.0 / 120.0); + assert_eq!((rt.stats.commits - before, rt.frame.live_only_skips), (0, 2), "on_key, then on_key_up"); + assert_eq!(camera_x(&rt), 20.0, "the frames drew both"); + + // A key the app declines goes on to Rune's own handling and commits as before. + let (ev, fallback) = key(PhysicalKeyCode::Tab, Key::Tab, true); + rt.physical_with_fallback(ev, fallback); + rt.frame(1.0 / 120.0); + assert_eq!(rt.stats.commits - before, 1); +} + +#[test] +fn a_physical_release_heard_at_rest_can_be_live_only() { + let mut rt = app(false); + rt.check_live_only(false); + let (x, y) = rt.find("recorder").unwrap(); + rt.pointer_down(x, y); + rt.pointer_up(x, y); + for _ in 0..60 { rt.frame(1.0 / 120.0); } + let before = rt.stats.commits; + // No logical key: the focused handler hears it at once, outside a frame. + let event = PhysicalInput::Key { key: PhysicalKeyCode::ShiftLeft, mods: Mods::default(), pressed: false, repeat: false }; + assert!(rt.physical_with_fallback(event, None), "it still asks for a frame to draw"); + assert!(!rt.commit.dirty); + rt.frame(1.0 / 120.0); + assert_eq!((rt.state.physical, rt.stats.commits - before), (1, 0)); + assert_eq!(camera_x(&rt), 10.0); +} + +#[test] +fn debug_builds_warn_when_a_live_only_handler_changed_what_the_view_reads() { + let mut rt = app(true); + // A quarter second after the last commit, a live-only event is checked: it commits, and + // the view built a different count. + rt.frame(0.5); + rt.key(KeyEvent { key: Key::Right, mods: Mods::default() }); + rt.frame(1.0 / 120.0); + assert_eq!(rt.frame.live_only_warnings().len(), 1, "{:?}", rt.frame.live_only_warnings()); + assert!(rt.frame.live_only_warnings()[0].contains("on_key"), "{}", rt.frame.live_only_warnings()[0]); + + // Used as meant, the check commits and stays quiet; events between checks skip the view. + let mut rt = app(false); + rt.frame(0.5); + let before = rt.stats.commits; + for _ in 0..10 { + rt.key_up(KeyEvent { key: Key::Right, mods: Mods::default() }); + rt.frame(1.0 / 120.0); + } + assert!(rt.frame.live_only_warnings().is_empty(), "{:?}", rt.frame.live_only_warnings()); + assert_eq!((rt.stats.commits - before, rt.frame.live_checks(), rt.frame.live_only_skips), (1, 1, 9)); +} + +#[test] +fn the_check_ignores_a_change_another_event_made_in_the_same_frame() { + let mut rt = app(false); + rt.frame(0.5); + // The release is checked, and then a press in the same frame changes the count. + rt.key_up(KeyEvent { key: Key::Right, mods: Mods::default() }); + let (x, y) = rt.find("camera").unwrap(); + rt.pointer_down(x, y); + rt.pointer_up(x, y); + rt.frame(1.0 / 120.0); + assert_eq!((rt.state.count, rt.frame.live_checks()), (1, 1)); + assert!(rt.frame.live_only_warnings().is_empty(), "{:?}", rt.frame.live_only_warnings()); +} + +#[test] +fn declined_element_key_does_not_hide_an_ancestor_change() { + fn view(s: &u32, _: &mut Cx<u32>) -> El { + el().on_key(|s: &mut u32, _, _| { *s += 1; true }) + .child(el().key("field").size(40.0, 40.0).focusable(true) + .on_key(|_: &mut u32, _, tx| { tx.live_only(); false })) + .child(text(s.to_string()).key("count")) + } + let mut rt = Runtime::new(0, view, (200.0, 200.0), Env::new(true, 1.0)); + rt.check_live_only(false); + rt.frame(0.0); + let (x, y) = rt.find("field").unwrap(); + rt.pointer_down(x, y); rt.pointer_up(x, y); rt.frame(0.0); + let before = rt.stats.commits; + rt.key(KeyEvent { key: Key::Right, mods: Mods::default() }); + rt.frame(0.0); + assert_eq!(rt.state, 1); + assert_eq!(rt.stats.commits, before + 1); +} + +#[test] +fn live_only_does_not_cancel_poll_update_or_later_event_commits() { + for source in 0..3 { + let mut rt = app(false); + rt.check_live_only(false); + if source == 0 { rt.poll = Some(|s, _, _| { s.count += 1; true }); } + if source == 1 { rt.update(|s, _| s.count += 1); } + rt.key_up(KeyEvent { key: Key::Right, mods: Mods::default() }); + if source == 2 { + let (x, y) = rt.find("camera").unwrap(); + rt.pointer_down(x, y); rt.pointer_up(x, y); + } + let before = rt.stats.commits; + rt.frame(0.0); + assert_eq!(rt.state.count, 1); + assert!(rt.stats.commits > before); + assert_eq!(rt.tree.nodes.iter().find(|n| n.key.as_deref() == Some("count")).unwrap().text.as_ref().unwrap().content, "1"); + } +} + +#[test] +fn live_values_published_by_poll_draw_in_that_frame_after_a_scroll_callback() { + fn view(pan: &Live<[f32; 2]>, _: &mut Cx<Live<[f32; 2]>>) -> El { + let follow = pan.clone(); + el().size(200.0, 200.0) + .child(el().key("scroll").size(100.0, 100.0) + .scroll(crate::ScrollSpec { stick_bottom: false }) + .on_scroll_offset(move |at| { follow.set([at.offset[1], 0.0]); }) + .child(el().size(100.0, 1000.0))) + .child(el().key("marker").absolute(0.0, 0.0).size(10.0, 10.0).live_offset(pan)) + } + let mut rt = Runtime::new(Live::new([0.0, 0.0]), view, (200.0, 200.0), Env::default()); + rt.frame(0.0); + rt.wheel(50.0, 50.0, -20.0); + rt.frame(1.0 / 60.0); + rt.frame(1.0 / 60.0); + assert_eq!(rt.state.get(), [20.0, 0.0]); + assert!(!rt.live_pending(), "the scroll callback's publication was already drawn"); + let commits = rt.stats.commits; + // A scroll-triggered animation continues through Live values, without rebuilding its view. + rt.poll = Some(|pan, _, _| { pan.set([pan.get()[0] + 5.0, 0.0]); false }); + for frame in 1..=4 { + rt.frame(1.0 / 60.0); + assert_eq!(rt.state.get()[0], 20.0 + frame as f32 * 5.0); + let marker = rt.elements().into_iter().find(|e| e.key.as_deref() == Some("marker")).unwrap(); + assert_eq!(marker.rect[0], 20.0 + frame as f32 * 5.0, "poll's position in frame {frame}"); + assert_eq!(rt.stats.commits, commits, "live animation does not rebuild the view"); + } +} + +#[test] +fn debug_check_does_not_blame_live_only_for_layout_feedback_before_a_key() { + let mut rt = app(false); + rt.frame(0.5); + // A layout callback changed view state, then a checked event, then another key + // forces the queue's mid-frame commit rather than the final commit. + rt.tree.nodes[0].handlers.on_layout = Some(Rc::new(|s, _, _| s.cast::<S>().unwrap().count += 1)); + rt.frame.queue.push(Action::Layout(rt.tree.nodes[0].path.clone(), [0.0; 4])); + rt.key_up(KeyEvent { key: Key::Right, mods: Mods::default() }); + rt.key(KeyEvent { key: Key::Left, mods: Mods::default() }); + rt.frame(0.0); + assert!(rt.frame.live_only_warnings().is_empty(), "{:?}", rt.frame.live_only_warnings()); +} + +#[test] +fn retained_exit_pruning_does_not_change_the_view_print() { + let mut rt = app(false); + let before = rt.view_print(); + let id = rt.tree.nodes.last().unwrap().id; + rt.scene.remove(id); + let exiting = rt.view_print(); + assert!(before.first_difference(&exiting).is_some()); + rt.scene.set_time(10.0); rt.scene.frame(); rt.prune_exited(); + assert_eq!(exiting.first_difference(&rt.view_print()), None); +} + +#[test] +fn live_only_keeps_clipboard_scroll_and_wake_requests() { + fn view(_: &(), _: &mut Cx<()>) -> El { + el().child(el().key("scroll").size(100.0, 100.0).scroll(crate::ScrollSpec { stick_bottom: false }) + .child(el().size(100.0, 1000.0))) + } + let mut rt = Runtime::new((), view, (200.0, 200.0), Env::new(true, 1.0)); + rt.check_live_only(false); + rt.on_key = Some(|_, _, tx| { + tx.live_only(); tx.copy("copied"); tx.scroll_to_y("scroll", 300.0); + tx.wake_after(std::time::Duration::from_secs(1)); true + }); + rt.frame(0.0); + let before = rt.stats.commits; + rt.key(KeyEvent { key: Key::Right, mods: Mods::default() }); rt.frame(0.0); + assert_eq!(rt.stats.commits, before); + assert_eq!(rt.copy_request.as_ref().unwrap().content().text(), "copied"); + let id = rt.tree.nodes.iter().find(|n| n.key.as_deref() == Some("scroll")).unwrap().id; + assert_eq!(rt.scroll.scrolls[&id].offset, 300.0); + // The scroll armed a 33 ms hover hold whose wake comes first; the 1 s request stands after it. + rt.frame(1.0 / 20.0); + assert_eq!(rt.wake_deadline(), Some(1.0)); +} + +#[test] +fn local_points_follow_scroll_offsets_in_windows_and_overlays() { + fn view(_: &(), _: &mut Cx<()>) -> El { + el().child(el().key("scroll").size(200.0, 200.0).scale(1.5).scroll(crate::ScrollSpec { stick_bottom: false }) + .child(el().size(200.0, 1000.0).child(el().key("target").size(50.0, 50.0)))) + } + for overlay in [false, true] { + let mut rt = Runtime::new((), view, (400.0, 400.0), Env::new(true, 2.0)); + rt.host.native_overlay = overlay; + rt.frame(0.0); + rt.update(|_, tx| tx.scroll_to_y("scroll", 100.0)); rt.frame(0.0); + let i = rt.tree.nodes.iter().position(|n| n.key.as_deref() == Some("target")).unwrap(); + let r = rt.paint.drawn[i]; + let p = rt.pointer_event(i, r[0] + 15.0, r[1] + 30.0); + assert_eq!((p.x, p.y), (10.0, 20.0)); + assert_eq!((p.window_x, p.window_y), (r[0] + 15.0, r[1] + 30.0)); + } +} + +#[test] +fn live_transform_refreshes_hover_paint_without_a_handler() { + fn view(s: &Live<[f32; 2]>, _: &mut Cx<Live<[f32; 2]>>) -> El { + el().child(el().key("moving").size(40.0, 40.0).live_offset(s).hover(Color::WHITE)) + } + let mut rt = Runtime::new(Live::new([100.0, 0.0]), view, (200.0, 200.0), Env::new(true, 1.0)); + rt.frame(0.0); rt.pointer_move(20.0, 20.0); rt.frame(0.0); + rt.state.set([0.0, 0.0]); + assert!(rt.frame(0.0), "changed hover paint must schedule its sample frame"); + let id = rt.tree.nodes.iter().find(|n| n.key.as_deref() == Some("moving")).unwrap().id; + rt.frame(1.0 / 120.0); + assert_eq!(rt.scene.get(id, P_HOVER), Some(1.0)); +} + +#[test] +fn a_commit_records_why_for_the_frame_log() { + for (source, want) in [(0, CommitWhy::POLL), (1, CommitWhy::INPUT)] { + let mut rt = app(false); + rt.check_live_only(false); + rt.frame(0.0); + rt.commit.clear_commit_why(); + rt.key_up(KeyEvent { key: Key::Right, mods: Mods::default() }); + rt.frame(0.0); + assert_eq!(rt.commit.commit_why(), 0, "a live-only key commits nothing"); + if source == 0 { rt.poll = Some(|s, _, _| { s.count += 1; true }); } + if source == 1 { + let (x, y) = rt.find("camera").unwrap(); + rt.pointer_down(x, y); rt.pointer_up(x, y); + } + rt.frame(0.0); + assert_eq!(rt.commit.commit_why() & want, want, "source {source}: {:?}", CommitWhy::names(rt.commit.commit_why())); + } +} diff --git a/app/vendor/rune/crates/rune/src/runtime/memo_reuse_tests.rs b/app/vendor/rune/crates/rune/src/runtime/memo_reuse_tests.rs new file mode 100644 index 0000000..430556e --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/memo_reuse_tests.rs @@ -0,0 +1,852 @@ +//! Byte-for-byte equivalence tests between `memo`-reusing builds (across Stages a, b and c) and +//! fresh un-memoized builds across exiting nodes, focus, hover, selection, scroll, layout reads, +//! env/theme/blend/scale/accent/reduced-motion changes, live values, keys, `virtual_rows` inside +//! and outside memos, parent-path rebasing, and hot-reload cache clears. + +use std::borrow::Cow; + +use rune_motion::Transition; + +use crate::render::Instance; +use crate::text::Span; +use crate::{ + Color, Cx, El, Env, GrowthSpec, Ime, Key, KeyEvent, Live, LiveText, Mods, Pixels, Runtime, + ScrollSpec, SystemAccent, TextEdit, TextStyle, col, el, memo, rich, row, text, text_input, +}; + +fn maybe_memo(use_memo: bool, id: impl Into<String>, ver: impl std::hash::Hash, build: impl FnOnce() -> El) -> El { + let key = id.into(); + if use_memo { + memo(key, ver, build) + } else { + build().key(key) + } +} + +fn assert_same_state<S: 'static>(memo_rt: &Runtime<S>, fresh_rt: &Runtime<S>, step: &str) { + assert_eq!(memo_rt.tree.nodes.len(), fresh_rt.tree.nodes.len(), "{step}: node count"); + for (idx, (a, b)) in memo_rt.tree.nodes.iter().zip(&fresh_rt.tree.nodes).enumerate() { + assert_eq!(a.id, b.id, "{step}: node[{idx}] ({}) id", a.path); + assert_eq!(a.path, b.path, "{step}: node[{idx}] path"); + assert_eq!(a.key, b.key, "{step}: node[{idx}] key"); + assert_eq!(a.role, b.role, "{step}: node[{idx}] role"); + assert_eq!(a.label, b.label, "{step}: node[{idx}] label"); + assert_eq!(a.parent, b.parent, "{step}: node[{idx}] parent"); + assert_eq!(a.local, b.local, "{step}: node[{idx}] local ({})", a.path); + assert_eq!(a.target, b.target, "{step}: node[{idx}] target ({})", a.path); + assert_eq!(a.inset, b.inset, "{step}: node[{idx}] inset ({})", a.path); + assert_eq!(a.inert, b.inert, "{step}: node[{idx}] inert ({})", a.path); + assert_eq!(a.scale_track, b.scale_track, "{step}: node[{idx}] scale_track ({})", a.path); + assert_eq!(a.group_fade, b.group_fade, "{step}: node[{idx}] group_fade ({})", a.path); + assert_eq!(a.elided, b.elided, "{step}: node[{idx}] elided ({})", a.path); + assert_eq!(a.vis.opacity.to_bits(), b.vis.opacity.to_bits(), "{step}: node[{idx}] opacity ({})", a.path); + assert_eq!(a.vis.paint_alpha.to_bits(), b.vis.paint_alpha.to_bits(), "{step}: node[{idx}] paint_alpha ({})", a.path); + assert_eq!(a.vis.fill, b.vis.fill, "{step}: node[{idx}] fill ({})", a.path); + assert_eq!(a.vis.radii(), b.vis.radii(), "{step}: node[{idx}] radius ({})", a.path); + assert_eq!( + a.text.as_ref().map(|t| (&t.content, t.color, t.shape)), + b.text.as_ref().map(|t| (&t.content, t.color, t.shape)), + "{step}: node[{idx}] text ({})", + a.path, + ); + } + + assert_eq!(memo_rt.hit.hits, fresh_rt.hit.hits, "{step}: hit rects"); + + let (ea, eb) = (memo_rt.elements(), fresh_rt.elements()); + assert_eq!(ea.len(), eb.len(), "{step}: ElementInfo count"); + for (i, (a, b)) in ea.iter().zip(&eb).enumerate() { + assert_eq!( + (&a.path, &a.key, a.exiting, a.focused, a.focus_visible, a.inert, &a.text, &a.selected, a.caret), + (&b.path, &b.key, b.exiting, b.focused, b.focus_visible, b.inert, &b.text, &b.selected, b.caret), + "{step}: ElementInfo[{i}] identity/state", + ); + assert_eq!( + (a.rect, a.target, a.visible, a.opacity.to_bits(), a.scale.to_bits(), a.hover.to_bits(), a.press.to_bits(), a.moving), + (b.rect, b.target, b.visible, b.opacity.to_bits(), b.scale.to_bits(), b.hover.to_bits(), b.press.to_bits(), b.moving), + "{step}: ElementInfo[{i}] ({}) geometry/motion", + a.path, + ); + } + + assert_eq!(memo_rt.instances.len(), fresh_rt.instances.len(), "{step}: instance count"); + let bytes_a: &[u8] = bytemuck::cast_slice::<Instance, u8>(&memo_rt.instances); + let bytes_b: &[u8] = bytemuck::cast_slice::<Instance, u8>(&fresh_rt.instances); + if bytes_a != bytes_b { + for (k, (ia, ib)) in memo_rt.instances.iter().zip(&fresh_rt.instances).enumerate() { + assert_eq!( + bytemuck::bytes_of(ia), + bytemuck::bytes_of(ib), + "{step}: instance[{k}] differs:\n memo: {ia:?}\n fresh: {ib:?}", + ); + } + } +} + +fn step_both<S: 'static>( + a: &mut Runtime<S>, + b: &mut Runtime<S>, + dt: f64, + label: &str, + mut f: impl FnMut(&mut Runtime<S>), +) { + f(a); + f(b); + let anim_a = a.frame(dt); + let anim_b = b.frame(dt); + assert_eq!(anim_a, anim_b, "{label}: animating mismatch"); + assert_same_state(a, b, label); +} + +#[derive(Clone)] +struct CardsState { + use_memo: bool, + banner_h: f32, + tick: u32, + card_ver: [u32; 4], + show_card: [bool; 4], + swap_order: bool, + nest_in_right: bool, + dim_first: bool, +} + +fn card_body(i: usize, ver: u32, use_memo: bool) -> El { + let title = format!("Card {i} v{ver}"); + let body = format!("Detailed body copy for card {i} at version {ver} with wrapping words."); + col() + .w_full() + .padding(10.0) + .gap(6.0) + .radius(8.0) + .fill(Color { r: 0.12, g: 0.14, b: 0.18, a: 1.0 }) + .border(1.0, Color::WHITE.alpha(0.15)) + .hover(Color::WHITE.alpha(0.06)) + .press(Color::WHITE.alpha(0.12)) + .press_scale(0.97) + .hover_group() + .focusable(true) + .on_press(move |s: &mut CardsState| s.tick += (i as u32) + 1) + .transition(Transition::opacity()) + .children([ + row().key("head").w_full().gap(8.0).center_y().children([ + el().key("badge").size(10.0, 10.0).radius(5.0).fill(Color { r: 0.3, g: 0.7, b: 0.9, a: 1.0 }).group_opacity(0.6, 1.0), + text(title).key("title").font(TextStyle::new(14.0, 600.0)).color(Color::WHITE).grow(1.0).shrink().truncate(), + maybe_memo(use_memo, "nested-pill", ver, || { + let overlay = crate::system_scroll_bars().is_overlay(crate::system_scroller_overlay()); + row().padding(if overlay { 4.0 } else { 6.0 }).radius(4.0).fill(Color::WHITE.alpha(0.08)) + .child(text(format!("#{ver}")).key("v").font(TextStyle::new(11.0, 500.0))) + }), + ]), + rich(body, vec![Span { start: 0, end: 8, weight: Some(700.0), color: Some(Color { r: 0.9, g: 0.8, b: 0.4, a: 1.0 }), ..Default::default() }]) + .key("desc") + .w_full() + .selectable(true), + ]) + .children((ver % 2 == 0).then(|| { + text("Optional footer note").key("footer").font(TextStyle::new(11.0, 400.0)).color(Color::WHITE.alpha(0.6)).transition(Transition::opacity()) + })) +} + +fn cards_view(s: &CardsState, cx: &mut Cx<CardsState>) -> El { + let m = s.use_memo; + let indices: Vec<usize> = if s.swap_order { vec![2, 1, 0, 3] } else { vec![0, 1, 2, 3] }; + let mut left_kids = Vec::new(); + let mut right_kids = Vec::new(); + for i in indices { + if !s.show_card[i] { + continue; + } + let ver = s.card_ver[i]; + let mut c = maybe_memo(m, format!("card-{i}"), ver, || card_body(i, ver, m)); + if i == 0 && s.dim_first { + c = c.opacity(0.45); + } + if i == 1 && s.nest_in_right { + right_kids.push(c); + } else { + left_kids.push(c); + } + } + if !s.nest_in_right { + // Occupy `#0/columns/right/card-1` before `card-1` rebases onto that exact path. + right_kids.push(el().key("card-1").w_full().h(18.0).fill(Color::WHITE.alpha(0.05))); + } + let accent = cx.accent(); + col().w_full().h_full().padding(12.0).gap(8.0).selection_group(true).children([ + el().key("banner").w_full().h(s.banner_h).radius(6.0).fill(accent), + text(format!("tick {}", s.tick)).key("tick").font(TextStyle::new(12.0, 400.0)), + row().key("columns").w_full().grow(1.0).min_h(0.0).gap(12.0).children([ + col().key("left").grow(1.0).shrink().gap(8.0).children(left_kids), + col().key("right").w(180.0).gap(8.0).children(right_kids), + ]), + ]) +} + +#[test] +fn steady_commits_moving_ancestors_rebase_exits_and_modifiers_match_fresh_build() { + let init = |use_memo| CardsState { + use_memo, + banner_h: 24.0, + tick: 0, + card_ver: [0, 0, 0, 0], + show_card: [true; 4], + swap_order: false, + nest_in_right: false, + dim_first: false, + }; + let mut rt_m = Runtime::new(init(true), cards_view, (560.0, 520.0), Env::new(true, 2.0)); + let mut rt_f = Runtime::new(init(false), cards_view, (560.0, 520.0), Env::new(true, 2.0)); + step_both(&mut rt_m, &mut rt_f, 0.0, "initial", |_| {}); + let first_builds = rt_m.commit.memo_builds(); + assert!(first_builds >= 4); + + // Steady commits: nothing moves, Stage (b) + Stage (c) skip flatten and apply on all cards. + for k in 0..5 { + step_both(&mut rt_m, &mut rt_f, 1.0 / 120.0, &format!("steady-{k}"), |rt| { + rt.update(|s, _| s.tick += 1); + }); + } + assert_eq!(rt_m.commit.memo_builds(), first_builds, "no memo rebuilt during steady ticks"); + + // Ancestor move: banner expands, shifting every card's window rect while keeping interior local rects. + step_both(&mut rt_m, &mut rt_f, 1.0 / 120.0, "banner-grow", |rt| { + rt.update(|s, _| s.banner_h = 68.0); + }); + for f in 0..30 { + step_both(&mut rt_m, &mut rt_f, 1.0 / 120.0, &format!("banner-spring-{f}"), |rt| { + if f == 5 { + rt.update(|s, _| s.tick += 1); + } + }); + } + + // Sibling reorder + parent-path rebase onto a path previously occupied by another node. + step_both(&mut rt_m, &mut rt_f, 1.0 / 120.0, "reorder-and-rebase", |rt| { + rt.update(|s, _| { + s.swap_order = true; + s.nest_in_right = true; + }); + }); + for f in 0..25 { + step_both(&mut rt_m, &mut rt_f, 1.0 / 120.0, &format!("rebase-spring-{f}"), |_| {}); + } + + // Caller root modifier toggled outside `memo(...)` without changing `ver`. + step_both(&mut rt_m, &mut rt_f, 1.0 / 120.0, "root-modifier-on", |rt| { + rt.update(|s, _| s.dim_first = true); + }); + for f in 0..15 { + step_both(&mut rt_m, &mut rt_f, 1.0 / 120.0, &format!("dim-spring-{f}"), |_| {}); + } + step_both(&mut rt_m, &mut rt_f, 1.0 / 120.0, "root-modifier-off", |rt| { + rt.update(|s, _| s.dim_first = false); + }); + + // Interior child exit (bumping card_ver[2] to odd drops its footer) + whole-card exit + prune + revive. + step_both(&mut rt_m, &mut rt_f, 1.0 / 120.0, "exits-begin", |rt| { + rt.update(|s, _| { + s.card_ver[2] += 1; + s.show_card[1] = false; + }); + }); + for f in 0..45 { + step_both(&mut rt_m, &mut rt_f, 1.0 / 60.0, &format!("exits-step-{f}"), |rt| { + if f == 4 { + rt.update(|s, _| s.tick += 1); + } + }); + } + // Commits after `prune_exited` compacted `self.nodes`. + for k in 0..3 { + step_both(&mut rt_m, &mut rt_f, 1.0 / 60.0, &format!("after-prune-{k}"), |rt| { + rt.update(|s, _| s.tick += 1); + }); + } + // Revive during an exit. + step_both(&mut rt_m, &mut rt_f, 1.0 / 60.0, "remove-card-3", |rt| { + rt.update(|s, _| s.show_card[3] = false); + }); + step_both(&mut rt_m, &mut rt_f, 1.0 / 60.0, "mid-exit", |_| {}); + step_both(&mut rt_m, &mut rt_f, 1.0 / 60.0, "revive-card-3", |rt| { + rt.update(|s, _| s.show_card[3] = true); + }); + for f in 0..20 { + step_both(&mut rt_m, &mut rt_f, 1.0 / 60.0, &format!("revive-settle-{f}"), |_| {}); + } +} + +#[test] +fn hover_press_focus_selection_env_blend_and_hot_clear_match_fresh_build() { + let init = |use_memo| CardsState { + use_memo, + banner_h: 24.0, + tick: 0, + card_ver: [0, 0, 0, 0], + show_card: [true; 4], + swap_order: false, + nest_in_right: false, + dim_first: false, + }; + let mut rt_m = Runtime::new(init(true), cards_view, (560.0, 520.0), Env::new(true, 1.0)); + let mut rt_f = Runtime::new(init(false), cards_view, (560.0, 520.0), Env::new(true, 1.0)); + step_both(&mut rt_m, &mut rt_f, 0.0, "init", |_| {}); + + // Hover + group_opacity + press + press_scale while commits fire. + let (cx, cy) = rt_m.find("card-0").unwrap(); + step_both(&mut rt_m, &mut rt_f, 1.0 / 120.0, "hover-enter", |rt| rt.pointer_move(cx, cy)); + for f in 0..8 { + step_both(&mut rt_m, &mut rt_f, 1.0 / 120.0, &format!("hover-spring-{f}"), |rt| { + if f == 3 { + rt.update(|s, _| s.tick += 1); + } + }); + } + step_both(&mut rt_m, &mut rt_f, 1.0 / 120.0, "press-down", |rt| rt.pointer_down(cx, cy)); + step_both(&mut rt_m, &mut rt_f, 1.0 / 120.0, "press-held-commit", |rt| rt.update(|s, _| s.tick += 1)); + step_both(&mut rt_m, &mut rt_f, 1.0 / 120.0, "press-up", |rt| rt.pointer_up(cx, cy)); + assert_eq!(rt_m.state.tick, rt_f.state.tick); + + // Keyboard Tab focus across focusable memo cards. + for t in 0..3 { + step_both(&mut rt_m, &mut rt_f, 1.0 / 120.0, &format!("tab-{t}"), |rt| { + rt.key(KeyEvent { key: Key::Tab, mods: Mods::default() }); + }); + } + + // Programmatic text selection across memoized selectable paragraphs + unrelated commit. + step_both(&mut rt_m, &mut rt_f, 1.0 / 120.0, "select-all", |rt| { + rt.update(|_, tx| tx.select_all_text("columns")); + }); + step_both(&mut rt_m, &mut rt_f, 1.0 / 120.0, "selection-commit", |rt| { + rt.update(|s, _| s.tick += 1); + }); + + // Env, dark mode, scale, system accent, sRGB blend, reduced motion, and hot-reload cache clear. + step_both(&mut rt_m, &mut rt_f, 1.0 / 60.0, "dark-false", |rt| rt.set_system_dark(false)); + step_both(&mut rt_m, &mut rt_f, 1.0 / 60.0, "scale-2x", |rt| rt.set_viewport((560.0, 520.0), 2.0)); + step_both(&mut rt_m, &mut rt_f, 1.0 / 60.0, "srgb-on", |rt| rt.set_srgb_blend(true)); + step_both(&mut rt_m, &mut rt_f, 1.0 / 60.0, "srgb-off", |rt| rt.set_srgb_blend(false)); + step_both(&mut rt_m, &mut rt_f, 1.0 / 60.0, "accent", |rt| { + let c = Color { r: 0.9, g: 0.3, b: 0.4, a: 1.0 }; + rt.set_system_accent(SystemAccent::new(c, c)); + }); + step_both(&mut rt_m, &mut rt_f, 1.0 / 60.0, "scroll-bars-always", |rt| { + rt.set_system_scroll_bars(crate::ScrollBars::Always); + }); + step_both(&mut rt_m, &mut rt_f, 1.0 / 60.0, "scroll-bars-auto-pad", |rt| { + rt.set_system_scroll_bars(crate::ScrollBars::Automatic); + rt.set_system_scroller_overlay(true); + }); + step_both(&mut rt_m, &mut rt_f, 1.0 / 60.0, "scroll-bars-auto-mouse", |rt| { + rt.set_system_scroller_overlay(false); + }); + step_both(&mut rt_m, &mut rt_f, 1.0 / 60.0, "reduced-motion", |rt| rt.set_system_reduced_motion(true)); + + let before_hot = rt_m.commit.memo_builds(); + rt_m.commit.clear_memo(); + step_both(&mut rt_m, &mut rt_f, 1.0 / 60.0, "hot-clear-rebuild", |rt| rt.update(|s, _| s.tick += 1)); + assert!(rt_m.commit.memo_builds() > before_hot, "hot clear rebuilds memos cleanly"); +} + +struct WorkspaceState { + use_memo: bool, + probe_w: f32, + panel_ver: u32, + rows: Vec<(String, u32)>, + composer: TextEdit, + live_opacity: Live<f32>, + live_label: LiveText, + pixels: Pixels, + dup_keys: bool, +} + +fn workspace_view(s: &WorkspaceState, cx: &mut Cx<WorkspaceState>) -> El { + let m = s.use_memo; + let probe_sz = cx.layout_size("probe").unwrap_or([0.0, 0.0]); + let inner_sz = cx.layout_size("live-card").unwrap_or([0.0, 0.0]); + + // A `virtual_rows` list nested INSIDE an outer `memo`, whose rows are ALSO `memo`s. + let panel = maybe_memo(m, "outer-panel", s.panel_ver, || { + col().w_full().grow(1.0).min_h(0.0).scroll(ScrollSpec { stick_bottom: false }).child( + col().key("vrows").w_full().gap(4.0).growth(GrowthSpec::default()).virtual_rows( + s.rows.len(), + 36.0, + |_: &WorkspaceState, i| Cow::Owned(format!("vr-{i}")), + |s: &WorkspaceState, i| { + let (label, ver) = &s.rows[i]; + let label = label.clone(); + maybe_memo(s.use_memo, format!("vr-{i}"), *ver, move || { + row().w_full().h(36.0).px(8.0).gap(6.0).center_y() + .fill(Color::WHITE.alpha(0.05)) + .children([ + el().key("dot").size(6.0, 6.0).radius(3.0).fill(Color::WHITE), + text(label).key("txt").font(TextStyle::new(13.0, 400.0)).grow(1.0).shrink().truncate(), + ]) + }) + }, + ), + ) + }); + + let live_op = s.live_opacity.clone(); + let live_txt = s.live_label.clone(); + let px = s.pixels.clone(); + let dup = s.dup_keys; + let live_card = maybe_memo(m, "live-card", dup, move || { + row().w_full().h(30.0).gap(8.0).center_y() + .live_opacity(&live_op) + .children([ + el().key("avatar").size(16.0, 16.0).pixels(&px), + text("init").key("clock").font(TextStyle::new(12.0, 400.0)).live_text(&live_txt), + el().key("dup").size(8.0, 8.0), + el().key(if dup { "dup" } else { "unique" }).size(8.0, 8.0), + ]) + }); + + let size_reader = maybe_memo(m, "size-reader", 0u32, move || { + let w = crate::memo::layout_size("probe").map_or(-1.0, |r| r[0]); + text(format!("probe={w:.0}")).key("probe-txt").font(TextStyle::new(12.0, 400.0)) + }); + + col().w_full().h_full().padding(8.0).gap(6.0).children([ + el().key("probe").w(s.probe_w).h(10.0).fill(Color::WHITE.alpha(0.2)), + text(format!("seen {:?} {:?}", probe_sz, inner_sz)).key("summary").font(TextStyle::new(11.0, 400.0)), + size_reader, + live_card, + panel, + text_input(&s.composer, TextStyle::new(13.0, 400.0)) + .key("composer") + .w_full() + .h(32.0) + .on_edit(|s: &mut WorkspaceState| &mut s.composer), + ]) +} + +#[test] +fn virtual_rows_inside_memos_layout_reads_live_values_and_duplicate_keys_match_fresh_build() { + let make = |use_memo| { + let live_opacity = Live::new(0.85); + let live_label = LiveText::new("00:01"); + let pixels = Pixels::new(); + pixels.set(4, 4, vec![200u8; 64]); + let mut composer = TextEdit::new("hello "); + composer.focused = true; + composer.set_caret(composer.text.len()); + WorkspaceState { + use_memo, + probe_w: 120.0, + panel_ver: 0, + rows: (0..80).map(|i| (format!("Row item {i}"), 0)).collect(), + composer, + live_opacity, + live_label, + pixels, + dup_keys: false, + } + }; + let mut rt_m = Runtime::new(make(true), workspace_view, (420.0, 380.0), Env::new(true, 2.0)); + let mut rt_f = Runtime::new(make(false), workspace_view, (420.0, 380.0), Env::new(true, 2.0)); + rt_m.set_live_visible(true); + rt_f.set_live_visible(true); + rt_m.commit.enable_key_warnings(); + rt_f.commit.enable_key_warnings(); + + step_both(&mut rt_m, &mut rt_f, 0.0, "init", |_| {}); + for f in 0..8 { + step_both(&mut rt_m, &mut rt_f, 1.0 / 120.0, &format!("overscan-fill-{f}"), |_| {}); + } + + // Typing into the sibling composer while outer-panel and virtual rows stay memoized. + for ch in ["a", "b", "c"] { + step_both(&mut rt_m, &mut rt_f, 1.0 / 120.0, &format!("type-{ch}"), |rt| { + rt.ime(Ime::Commit(ch.into())); + }); + } + + // Scrolling the `virtual_rows` list INSIDE `memo("outer-panel")` without changing `panel_ver`. + for s in 0..12 { + step_both(&mut rt_m, &mut rt_f, 1.0 / 120.0, &format!("scroll-down-{s}"), |rt| { + rt.wheel(200.0, 220.0, -140.0); + }); + } + // Mutating one mounted row's version inside the unchanged outer memo, then scrolling back up. + step_both(&mut rt_m, &mut rt_f, 1.0 / 120.0, "bump-row", |rt| { + rt.update(|s, _| { + for (lbl, ver) in &mut s.rows { + *lbl = format!("{lbl}!"); + *ver += 1; + } + }); + }); + for s in 0..12 { + step_both(&mut rt_m, &mut rt_f, 1.0 / 120.0, &format!("scroll-up-{s}"), |rt| { + rt.wheel(200.0, 220.0, 140.0); + }); + } + + // Layout size read invalidates `size-reader` when `probe_w` changes, and reuses when unchanged. + step_both(&mut rt_m, &mut rt_f, 1.0 / 60.0, "resize-probe", |rt| { + rt.update(|s, _| s.probe_w = 210.0); + }); + for f in 0..15 { + step_both(&mut rt_m, &mut rt_f, 1.0 / 60.0, &format!("probe-spring-{f}"), |_| {}); + } + + // Live values (`Live`, `LiveText`, `Pixels`) update across frames and across unrelated commits. + step_both(&mut rt_m, &mut rt_f, 1.0 / 60.0, "live-update", |rt| { + rt.state.live_opacity.set(0.5); + rt.state.live_label.set("00:42"); + rt.state.pixels.set(4, 4, vec![90u8; 64]); + }); + step_both(&mut rt_m, &mut rt_f, 1.0 / 60.0, "commit-after-live", |rt| { + rt.ime(Ime::Commit("!".into())); + }); + + // Duplicate sibling keys inside a memo repair identically. + step_both(&mut rt_m, &mut rt_f, 1.0 / 60.0, "dup-keys", |rt| { + rt.update(|s, _| s.dup_keys = true); + }); + assert_eq!(rt_m.commit.key_warnings(), rt_f.commit.key_warnings(), "duplicate-key warnings match"); +} + +#[test] +fn self_prefix_rebase_box_into_box_box_and_back_matches_fresh_build() { + fn view(s: &(bool, bool), _: &mut Cx<(bool, bool)>) -> El { + let leaf = maybe_memo(s.0, "box", 0u32, || { + col().w(80.0).h(30.0).fill(Color::WHITE).child(text("inner").key("box")) + }); + col().size(200.0, 200.0).child(if s.1 { + col().key("box").w(120.0).h(60.0).child(leaf) + } else { + leaf + }) + } + let mut rt_m = Runtime::new((true, false), view, (200.0, 200.0), Env::new(true, 1.0)); + let mut rt_f = Runtime::new((false, false), view, (200.0, 200.0), Env::new(true, 1.0)); + step_both(&mut rt_m, &mut rt_f, 0.0, "flat", |_| {}); + step_both(&mut rt_m, &mut rt_f, 1.0 / 60.0, "into-wrapper", |rt| rt.update(|s, _| s.1 = true)); + for f in 0..20 { + step_both(&mut rt_m, &mut rt_f, 1.0 / 60.0, &format!("wrap-settle-{f}"), |_| {}); + } + step_both(&mut rt_m, &mut rt_f, 1.0 / 60.0, "out-of-wrapper", |rt| rt.update(|s, _| s.1 = false)); + for f in 0..20 { + step_both(&mut rt_m, &mut rt_f, 1.0 / 60.0, &format!("unwrap-settle-{f}"), |_| {}); + } +} + +struct MoveHarness { + use_memo: bool, + tick: u32, + theme_ver: u32, + header_h: f32, + show_modal: bool, + show_banner_chip: bool, + show_mid_memo: bool, + list_ver: u32, + vrows_len: usize, + editor: TextEdit, + modal_input: TextEdit, +} + +fn move_harness_view(s: &MoveHarness, cx: &mut Cx<MoveHarness>) -> El { + let m = s.use_memo; + let dark = cx.env().system_dark; + let hdr_rect = cx.layout("dyn-hdr").unwrap_or([0.0; 4]); + let caret = cx.caret("editor").unwrap_or([0.0; 4]); + let card_bg = if dark && s.theme_ver % 2 == 0 { + Color { r: 0.13, g: 0.15, b: 0.20, a: 1.0 } + } else { + Color { r: 0.88, g: 0.89, b: 0.93, a: 1.0 } + }; + let ink = if dark && s.theme_ver % 2 == 0 { Color::WHITE } else { Color { r: 0.1, g: 0.12, b: 0.16, a: 1.0 } }; + + // Styled memo cards with shadows, gradients, radial stops, outlines and selectable text, + // exercising `apply`'s paint-track `prev_node` path whenever `skip_spans` is bypassed. + let styled_card = |idx: usize| { + maybe_memo(m, format!("styled-{idx}"), s.theme_ver, move || { + col() + .w_full() + .padding(8.0) + .gap(4.0) + .radius(6.0) + .fill(card_bg) + .border(1.0, ink.alpha(0.2)) + .shadow(2.0, 6.0, Color::BLACK.alpha(0.25)) + .gradient(card_bg, card_bg.alpha(0.85)) + .radial_gradient([0.5, 0.5], 40.0, [(0.0, ink.alpha(0.08)), (1.0, Color::TRANSPARENT)]) + .outline(1.0, 1.0, ink.alpha(0.15)) + .hover(ink.alpha(0.06)) + .press(ink.alpha(0.12)) + .focusable(true) + .transition(Transition::opacity()) + .children([ + text(format!("Styled memo {idx}")).key("h").font(TextStyle::new(13.0, 600.0)).color(ink), + text(format!("Selectable line inside moved memo {idx} for drag & copy")).key("p").font(TextStyle::new(12.0, 400.0)).color(ink).selectable(true), + ]) + }) + }; + + // A single `memo` owning a long scrollable list (140 items, >420 nodes moved in one slice). + let long_static_list = maybe_memo(m, "long-list-memo", (s.list_ver, s.theme_ver), || { + col() + .w_full() + .h(120.0) + .scroll(ScrollSpec { stick_bottom: false }) + .child( + col().key("items").w_full().gap(2.0).children((0..140).map(|i| { + row() + .key(format!("li-{i}")) + .w_full() + .h(22.0) + .px(6.0) + .gap(6.0) + .center_y() + .fill(card_bg.alpha(0.5)) + .focusable(i % 25 == 0) + .children([ + el().key("b").size(6.0, 6.0).radius(3.0).fill(ink), + text(format!("Long memo item #{i}")).key("t").font(TextStyle::new(12.0, 400.0)).color(ink).selectable(true), + ]) + })), + ) + }); + + // A long `virtual_rows` list inside a `memo` whose true row height (64 pt) intentionally + // exceeds its 14 pt estimate so `measure_virtuals` exercises multi-pass retry restoration. + let long_virtual_memo = maybe_memo(m, "long-vlist-memo", s.vrows_len, || { + col() + .w_full() + .grow(1.0) + .min_h(0.0) + .scroll(ScrollSpec { stick_bottom: true }) + .child( + col().key("vstack").w_full().gap(4.0).growth(GrowthSpec::default()).virtual_rows( + s.vrows_len, + 14.0, + |_: &MoveHarness, i| Cow::Owned(format!("mv-{i}")), + |s: &MoveHarness, i| { + maybe_memo(s.use_memo, format!("mv-{i}"), s.theme_ver, move || { + col().w_full().h(64.0).padding(6.0).fill(Color::WHITE.alpha(0.04)).children([ + text(format!("Virtual row {i}")).key("vt").font(TextStyle::new(12.0, 500.0)), + text("Second line keeping row taller than estimate").key("vs").font(TextStyle::new(11.0, 400.0)), + ]) + }) + }, + ), + ) + }); + + let mut body = col() + .w_full() + .h_full() + .padding(10.0) + .gap(6.0) + .selection_group(true) + .child_exit(Transition::opacity()) + .children([ + el().key("dyn-hdr").w_full().h(s.header_h).fill(ink.alpha(0.1)), + text(format!("t={} hdr={:.0} caret={:.1}", s.tick, hdr_rect[3], caret[0])) + .key("readout") + .font(TextStyle::new(11.0, 400.0)), + styled_card(0), + ]); + if s.show_banner_chip { + body = body.child( + row().key("leaving-chip").w_full().h(20.0).fill(ink.alpha(0.15)).transition(Transition::opacity()) + .child(text("Transient banner").key("lbl").font(TextStyle::new(11.0, 400.0))), + ); + } + if s.show_mid_memo { + body = body.child(styled_card(1)); + } + body = body.children([ + long_static_list, + long_virtual_memo, + text_input(&s.editor, TextStyle::new(13.0, 400.0)) + .key("editor") + .w_full() + .h(30.0) + .on_edit(|s: &mut MoveHarness| &mut s.editor), + ]); + if s.show_modal { + body = body.child( + col() + .key("popover") + .w_full() + .padding(6.0) + .focus_return("styled-0") + .transition(Transition::opacity()) + .child( + text_input(&s.modal_input, TextStyle::new(13.0, 400.0)) + .key("modal-field") + .w_full() + .h(28.0) + .on_edit(|s: &mut MoveHarness| &mut s.modal_input), + ), + ); + } + body +} + +#[test] +fn move_path_preserves_allocations_and_matches_fresh_across_exits_focus_selection_scroll_theme_and_long_lists() { + let make = |use_memo| { + let mut editor = TextEdit::new("seed "); + editor.focused = true; + editor.set_caret(editor.text.len()); + MoveHarness { + use_memo, + tick: 0, + theme_ver: 0, + header_h: 18.0, + show_modal: false, + show_banner_chip: true, + show_mid_memo: true, + list_ver: 0, + vrows_len: 320, + editor, + modal_input: TextEdit::new("modal"), + } + }; + let mut rt_m = Runtime::new(make(true), move_harness_view, (500.0, 620.0), Env::new(true, 2.0)); + let mut rt_f = Runtime::new(make(false), move_harness_view, (500.0, 620.0), Env::new(true, 2.0)); + step_both(&mut rt_m, &mut rt_f, 0.0, "init", |_| {}); + for f in 0..8 { + step_both(&mut rt_m, &mut rt_f, 1.0 / 120.0, &format!("init-fill-{f}"), |_| {}); + } + + // Proof that `same_path` memo reuse moves `Node`s rather than cloning their owned heap strings. + let path_ptr = |rt: &Runtime<MoveHarness>, path: &str| { + rt.tree.nodes.iter().find(|n| n.path == path).unwrap().path.as_ptr() as usize + }; + let p_styled = path_ptr(&rt_m, "#0/styled-0/p"); + let p_long = path_ptr(&rt_m, "#0/long-list-memo/items/li-95/t"); + + // Non-committing `content_height()` must leave `rt_m.tree.nodes` intact AND recycle `spare_nodes`. + assert_eq!(rt_m.content_height(), rt_f.content_height(), "content_height matches"); + assert!(rt_m.tree.spare_nodes.capacity() >= rt_m.tree.nodes.len(), "content_height recycled spare_nodes"); + let (buf_a, buf_b) = (rt_m.tree.nodes.as_ptr() as usize, rt_m.tree.spare_nodes.as_ptr() as usize); + + for k in 0..4 { + step_both(&mut rt_m, &mut rt_f, 1.0 / 120.0, &format!("steady-move-{k}"), |rt| { + rt.update(|s, _| s.tick += 1); + }); + assert_eq!(path_ptr(&rt_m, "#0/styled-0/p"), p_styled, "styled memo path moved without reallocation"); + assert_eq!(path_ptr(&rt_m, "#0/long-list-memo/items/li-95/t"), p_long, "long-list node moved without reallocation"); + let pair = (rt_m.tree.nodes.as_ptr() as usize, rt_m.tree.spare_nodes.as_ptr() as usize); + assert!(pair == (buf_a, buf_b) || pair == (buf_b, buf_a), "nodes and spare_nodes ping-pong without reallocating"); + } + + // Typing moves `cx.caret("editor")`, triggering `caret_moved` -> `discard_measured` -> re-measure + // after pass 1 already moved `styled-0`, `styled-1` and `long-list-memo`. + for ch in ["x", "y", "z"] { + step_both(&mut rt_m, &mut rt_f, 1.0 / 120.0, &format!("caret-remeasure-{ch}"), |rt| { + rt.ime(Ime::Commit(ch.into())); + }); + } + assert_eq!(path_ptr(&rt_m, "#0/styled-0/p"), p_styled, "caret re-measure restored and re-moved node"); + + // Changing `header_h` shifts `cx.layout("dyn-hdr")` AND shifts `styled-0`'s local rect (bypassing + // `skip_spans` so `apply`'s `prev_node` runs on shadows/gradients/radials/outlines) AND triggers + // `settle_layout_reads` -> `discard_measured` -> re-measure. + step_both(&mut rt_m, &mut rt_f, 1.0 / 120.0, "layout-read-remeasure", |rt| { + rt.update(|s, _| s.header_h = 54.0); + }); + for f in 0..10 { + step_both(&mut rt_m, &mut rt_f, 1.0 / 120.0, &format!("hdr-spring-{f}"), |rt| { + if f == 4 { + rt.update(|s, tx| { + s.tick += 1; + tx.settle(); + }); + } + }); + } + + // Elements leaving: both an un-memoized sibling (`leaving-chip`) and a moved memo (`styled-1`) + // exit while commits continue, then prune, then `styled-1` revives. + step_both(&mut rt_m, &mut rt_f, 1.0 / 60.0, "elements-leave", |rt| { + rt.update(|s, _| { + s.show_banner_chip = false; + s.show_mid_memo = false; + }); + }); + for f in 0..25 { + step_both(&mut rt_m, &mut rt_f, 1.0 / 60.0, &format!("leaving-fade-{f}"), |rt| { + if f == 3 || f == 12 { + rt.update(|s, _| s.tick += 1); + } + }); + } + step_both(&mut rt_m, &mut rt_f, 1.0 / 60.0, "revive-mid-memo", |rt| { + rt.update(|s, _| s.show_mid_memo = true); + }); + + // Focus request (`sync_requested_focus` -> `discard_measured` -> re-measure) + `focus_return` on close, + // followed by Tab traversal and text selection across moved memos. + step_both(&mut rt_m, &mut rt_f, 1.0 / 60.0, "open-focused-modal", |rt| { + rt.update(|s, _| { + s.show_modal = true; + s.modal_input.focused = true; + }); + }); + step_both(&mut rt_m, &mut rt_f, 1.0 / 60.0, "close-modal-focus-return", |rt| { + rt.update(|s, tx| { + s.show_modal = false; + s.modal_input.focused = false; + tx.instant(); + }); + }); + for t in 0..4 { + step_both(&mut rt_m, &mut rt_f, 1.0 / 60.0, &format!("focus-tab-{t}"), |rt| { + rt.key(KeyEvent { key: Key::Tab, mods: Mods::default() }); + }); + } + step_both(&mut rt_m, &mut rt_f, 1.0 / 60.0, "select-all-moved", |rt| { + rt.update(|_, tx| tx.select_all_text("")); + }); + let (sx, sy) = rt_m.find("styled-0/p").unwrap(); + let (ex, ey) = rt_m.find("styled-1/p").unwrap(); + step_both(&mut rt_m, &mut rt_f, 1.0 / 60.0, "drag-sel-down", |rt| rt.pointer_down(sx, sy)); + step_both(&mut rt_m, &mut rt_f, 1.0 / 60.0, "drag-sel-move", |rt| rt.pointer_move(ex, ey)); + step_both(&mut rt_m, &mut rt_f, 1.0 / 60.0, "drag-sel-up", |rt| rt.pointer_up(ex, ey)); + step_both(&mut rt_m, &mut rt_f, 1.0 / 60.0, "commit-with-selection", |rt| rt.update(|s, _| s.tick += 1)); + + // Scrolling BOTH the long static list inside `long-list-memo` and the long `virtual_rows` list + // inside `long-vlist-memo` while commits run. + let (lx, ly) = rt_m.find("long-list-memo").unwrap(); + for s in 0..8 { + step_both(&mut rt_m, &mut rt_f, 1.0 / 120.0, &format!("scroll-long-static-{s}"), |rt| { + rt.wheel(lx, ly, -120.0); + if s % 2 == 1 { + rt.update(|st, _| st.tick += 1); + } + }); + } + let (vx, vy) = rt_m.find("long-vlist-memo").unwrap(); + for s in 0..10 { + step_both(&mut rt_m, &mut rt_f, 1.0 / 120.0, &format!("scroll-long-virtual-{s}"), |rt| { + rt.wheel(vx, vy, 220.0); + if s % 3 == 0 { + rt.update(|st, _| st.tick += 1); + } + }); + } + + // Theme changes: both `Env::system_dark` flip and app-versioned theme crossfade across moved memos. + step_both(&mut rt_m, &mut rt_f, 1.0 / 60.0, "system-light", |rt| rt.set_system_dark(false)); + for f in 0..10 { + step_both(&mut rt_m, &mut rt_f, 1.0 / 60.0, &format!("light-crossfade-{f}"), |rt| { + if f == 2 { + rt.update(|s, _| s.tick += 1); + } + }); + } + step_both(&mut rt_m, &mut rt_f, 1.0 / 60.0, "app-theme-bump", |rt| { + rt.update(|s, _| s.theme_ver += 1); + }); + for f in 0..10 { + step_both(&mut rt_m, &mut rt_f, 1.0 / 60.0, &format!("app-theme-fade-{f}"), |_| {}); + } + step_both(&mut rt_m, &mut rt_f, 1.0 / 60.0, "system-dark-again", |rt| rt.set_system_dark(true)); +} diff --git a/app/vendor/rune/crates/rune/src/runtime/motion.rs b/app/vendor/rune/crates/rune/src/runtime/motion.rs new file mode 100644 index 0000000..bc5994f --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/motion.rs @@ -0,0 +1,21 @@ +//! Render-side motion tracks, growth rows/runs, flights, reveals, loop/timer clocks, live latches, +//! idle metering and rewind recording. +use super::*; + +pub(super) mod content_slide; +pub(super) mod flights; +pub(super) mod fold_hold; +pub(super) mod growth_rows; +pub(super) mod growth_runs; +pub(super) mod idle_meter; +pub(super) mod landing_hold; +pub(super) mod live_check; +pub(super) mod live_latch; +pub(super) mod loop_clock; +pub(super) mod motion_elements; +pub(super) mod props; +pub(super) mod reveal_phase; +pub(super) mod rewind; +pub(super) mod timer_wake; +pub(super) mod tracks; +pub(super) mod unseen_presence; diff --git a/app/vendor/rune/crates/rune/src/runtime/motion/content_slide.rs b/app/vendor/rune/crates/rune/src/runtime/motion/content_slide.rs new file mode 100644 index 0000000..8c3e6fd --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/motion/content_slide.rs @@ -0,0 +1,124 @@ +//! Contents that slide with their growth row. When the top of a parent's contents moves in a +//! growth row (a padding or gap above them changed) and the row's height changes the other way +//! to fit, they slide as its growth opens: the slide left shrinks with the growth left. A list +//! pinned to its end moves the row by what it grows, so contents whose place doesn't change hold +//! still on every frame, instead of netting a spring against the growth. A growth retargeted so +//! it no longer opens toward them lets the rest spring out on the row's growth spring. +use super::*; + +/// The contents of a growth stack's rows sliding with them, drawn outside the scene. +#[derive(Clone, Debug, Default)] +pub(in crate::runtime) struct ContentSlides(Vec<Slide>); + +#[derive(Clone, Copy, Debug)] +struct Slide { + node: NodeId, + row: NodeId, + phase: SlidePhase, +} + +/// Where a slide is: how far down from its layout it shows, and how fast that changes +/// (points, per second). +#[derive(Clone, Copy, Debug, PartialEq)] +enum SlidePhase { + /// Shrinking with the growth left to open; `at` is the row's presented height when `dy` + /// was last measured, and `v` how fast it last moved, which a spring takes over. + Following { dy: f32, v: f32, at: f32 }, + /// Springing to its layout on the row's growth spring, once the growth stopped opening + /// toward it. It never follows again. + Settling { dy: f32, v: f32 }, +} + +impl SlidePhase { + fn dy(self) -> f32 { + match self { SlidePhase::Following { dy, .. } | SlidePhase::Settling { dy, .. } => dy } + } + + /// The phase after row growth `g` took `steps`. + fn step(self, g: &GrowTrack, spring: Spring, steps: impl Into<crate::growth::Substeps>) -> SlidePhase { + let steps = steps.into(); + let dt: f32 = steps.sum(); + let (mut dy, mut v) = match self { + SlidePhase::Following { dy, v, at } => { + let (was, left) = (g.target - at, g.target - g.h); + if was * dy < 0.0 && was.abs() > 1.0 / 64.0 { + let next = dy * (left / was).clamp(0.0, 1.0); + let v = if dt > 0.0 { (next - dy) / dt } else { v }; + return SlidePhase::Following { dy: next, v, at: g.h }; + } + (dy, v) + } + SlidePhase::Settling { dy, v } => (dy, v), + }; + for step in steps { + (dy, v) = spring.sample(dy, v, 0.0, step); + } + SlidePhase::Settling { dy, v } + } + + /// Whether it still shows off its layout, or still moves toward it. + fn live(self) -> bool { + match self { + SlidePhase::Following { dy, .. } => dy.abs() > 1.0 / 128.0, + SlidePhase::Settling { dy, v } => dy.abs() > 1.0 / 128.0 || v.abs() > 0.5, + } + } +} + +impl ContentSlides { + /// Each sliding node and how far down from its layout it shows. + pub(in crate::runtime) fn shifts(&self) -> impl Iterator<Item = (NodeId, f32)> + '_ { + self.0.iter().map(|s| (s.node, s.phase.dy())) + } + + /// Slides `node`, drawn `dy` points down from its layout plus any slide it still had, with + /// row `row`'s growth `g`, if that growth opens toward its layout. Otherwise it stops + /// following and the whole amount is returned, for the caller to slide some other way. + fn follow(&mut self, node: NodeId, row: NodeId, g: &GrowTrack, dy: f32) -> f32 { + let dy = dy + self.0.iter().position(|s| s.node == node).map_or(0.0, |k| self.0.swap_remove(k).phase.dy()); + let left = g.target - g.h; + if left * dy < 0.0 && left.abs() > 1.0 / 64.0 { + self.0.push(Slide { node, row, phase: SlidePhase::Following { dy, v: 0.0, at: g.h } }); + return 0.0; + } + dy + } + + /// Lands row `row`'s slides at once (its growth landed at once). + pub(in crate::runtime) fn land(&mut self, row: NodeId) { + self.0.retain(|s| s.row != row); + } + + /// Steps row `row`'s slides after its growth `g` took `steps`. Whether any still + /// moves. + pub(in crate::runtime) fn step(&mut self, row: NodeId, g: &GrowTrack, spring: Spring, steps: crate::growth::Substeps) -> bool { + for s in self.0.iter_mut().filter(|s| s.row == row) { + s.phase = s.phase.step(g, spring, steps); + } + self.0.retain(|s| s.phase.live()); + self.0.iter().any(|s| s.row == row) + } + + /// Drops the slides of rows that left the stack. + pub(in crate::runtime) fn keep(&mut self, rows: &[NodeId]) { + self.0.retain(|s| rows.contains(&s.row)); + } +} + +impl tracks::MotionState { + /// Before node `id`, a child of `parent` whose contents' top moved `dy` points down in its + /// growth row (drawn less new), takes that slide: with the row's growth where it opens + /// toward them. How far it still has to slide from where it was drawn. + pub(in crate::runtime) fn slide_with_row(&mut self, nodes: &[Node], parent: usize, id: NodeId, dy: f32) -> f32 { + let Some(row) = std::iter::successors(Some(parent), |&p| nodes[p].parent) + .find(|&r| nodes[r].parent.is_some_and(|c| nodes[c].growth.is_some())) + else { return dy }; + let Some(c) = nodes[row].parent else { return dy }; + let (Some(stack), Some(g)) = (self.stacks.get_mut(&nodes[c].id), self.grows.get(&nodes[row].id)) else { return dy }; + stack.slides.follow(id, nodes[row].id, g, dy) + } +} + +#[cfg(test)] +#[path = "content_slide_tests.rs"] +mod tests; diff --git a/app/vendor/rune/crates/rune/src/runtime/motion/content_slide_tests.rs b/app/vendor/rune/crates/rune/src/runtime/motion/content_slide_tests.rs new file mode 100644 index 0000000..99b6c13 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/motion/content_slide_tests.rs @@ -0,0 +1,47 @@ +use super::*; +use crate::growth::{GROWTH, SUBSTEP}; + +/// A row growth from `h` toward `target`. +fn growth(h: f32, target: f32) -> GrowTrack { + let mut g = GrowTrack::settled(h); + g.target = target; + g +} + +#[test] +fn a_slide_shrinks_with_the_growth_left_to_open() { + let phase = SlidePhase::Following { dy: -20.0, v: 0.0, at: 0.0 }; + let next = phase.step(&growth(50.0, 100.0), GROWTH, 12); + let SlidePhase::Following { dy, v, at } = next else { panic!("still follows: {next:?}") }; + assert_eq!((dy, at), (-10.0, 50.0), "half the growth left, half the slide"); + assert!((v - 10.0 / (12.0 * SUBSTEP)).abs() < 1e-3, "its speed is measured for a spring to take over: {v}"); + // No time passed: it moves with the growth but keeps the speed it had. + let same = next.step(&growth(75.0, 100.0), GROWTH, 0); + assert_eq!(same, SlidePhase::Following { dy: -5.0, v, at: 75.0 }); +} + +#[test] +fn a_growth_that_stops_opening_toward_it_hands_its_speed_to_a_spring() { + let phase = SlidePhase::Following { dy: -10.0, v: 300.0, at: 50.0 }; + // Retargeted below the height it had: the growth no longer opens toward the contents. + let next = phase.step(&growth(50.0, 20.0), GROWTH, 1); + let SlidePhase::Settling { dy, v } = next else { panic!("springs: {next:?}") }; + let (want_dy, want_v) = GROWTH.sample(-10.0, 300.0, 0.0, SUBSTEP); + assert_eq!((dy, v), (want_dy, want_v), "from where it was, at the speed it had"); + // A growth opening toward it again doesn't bring the following back. + assert!(matches!(next.step(&growth(0.0, 100.0), GROWTH, 1), SlidePhase::Settling { .. })); +} + +#[test] +fn a_slide_ends_at_its_layout_and_a_spring_once_it_also_stops() { + assert!(!SlidePhase::Following { dy: 0.001, v: 900.0, at: 10.0 }.live(), "a following slide at its layout is done"); + assert!(SlidePhase::Settling { dy: 0.001, v: 900.0 }.live(), "a spring passing its layout still moves"); + assert!(!SlidePhase::Settling { dy: 0.001, v: 0.1 }.live()); + let mut phase = SlidePhase::Settling { dy: -40.0, v: 0.0 }; + let mut frames = 0; + while phase.live() { + phase = phase.step(&growth(0.0, 0.0), GROWTH, 2); + frames += 1; + assert!(frames < 240, "springs home within 2 s: {phase:?}"); + } +} diff --git a/app/vendor/rune/crates/rune/src/runtime/motion/flights.rs b/app/vendor/rune/crates/rune/src/runtime/motion/flights.rs new file mode 100644 index 0000000..db4316e --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/motion/flights.rs @@ -0,0 +1,507 @@ +//! Elements that fly to their place on one screen path: `El::matched` pairs and `Tx::launch`. +use crate::machine::{Attempt, Effects, Seq}; +use super::*; + +/// `Tx::launch` and `El::matched` flights: each one from the frame it is asked for until it +/// lands, and the launches still waiting for their destination to mount. +#[derive(Default)] +pub(in crate::runtime) struct Launches { + seq: Seq, + launches: Vec<Launch>, +} + +/// One launch or matched flight, with the attempt that names it while it has no node to fly to +/// yet. +struct Launch { + attempt: Attempt, + phase: LaunchPhase, +} + +/// Where a launch is between being asked for and landing. +enum LaunchPhase { + /// `Tx::launch`: its source's text was at `from` on screen, and it waits for the commit + /// that mounts `target`. Its answer carries the attempt back. + Waiting { target: String, from: [f32; 2] }, + /// In the air, at the node it flies to. + Airborne(Airborne), +} + +/// A flight in the air: a `Tx::launch`, which flies a path of its own, or an `El::matched` +/// flight started under `Tx::unclipped_flights`, which flies the scene's and draws outside +/// every clip until it lands. +enum Airborne { + Launched(Launched), + Unclipped { id: NodeId }, +} + +/// What moves a launch on, from being asked for to landing. +enum LaunchEvent<'a> { + /// `Tx::launch` asked for `target` this frame, whose source's text was at `from` on screen. + Ask { target: String, from: [f32; 2] }, + /// A commit builds: hand out the launches waiting for a destination to mount. + Commit, + /// The destination the launch `attempt` waited for mounted, and its flight starts there. + TakeOff { attempt: Attempt, flight: Launched }, + /// It didn't mount, so the launch is over. + Missed { attempt: Attempt }, + /// An `El::matched` flight on `id` starts (`on`) or stops drawing outside every clip. + Unclip { id: NodeId, on: bool }, + /// The window's flights are `flying`: the ones in the air that left them landed. + Flights { flying: &'a [(NodeId, MRect)] }, +} + +/// What a transition asks its caller to do: find `target`'s node in the commit's tree and start +/// its path from `from`, then feed the flight back as `TakeOff`, or `Missed` when it didn't +/// mount. A launch keeps its attempt while it waits, so a late answer changes nothing. +enum LaunchEffect { + Mount { attempt: Attempt, target: String, from: [f32; 2] }, +} + +impl Launch { + /// The node it flies to, once it has one. + fn airborne_id(&self) -> Option<NodeId> { + match &self.phase { + LaunchPhase::Waiting { .. } => None, + LaunchPhase::Airborne(Airborne::Launched(flight)) => Some(flight.id), + LaunchPhase::Airborne(Airborne::Unclipped { id }) => Some(*id), + } + } +} + +/// A launch in the air, the offsets outside the scene it was started against, the ones its +/// last frame drew it under (none before its first frame), and how fast they last moved +/// between frames with no commit. Its re-aims folded `folded` of what its flight added to them +/// into its path, when `1 - travel` was `folded_at`. +struct Launched { + id: NodeId, + shift: [f32; 2], + drawn: Option<Drawn>, + drift: [f32; 2], + folded: [f32; 2], + folded_at: [f32; 2], +} + +/// The offsets outside the scene a launch's frame drew it under, at scene time `at`, after +/// commit `commit`. +#[derive(Clone, Copy)] +struct Drawn { + offset: [f32; 2], + at: f64, + commit: u64, +} + +impl Launches { + pub(in crate::runtime) fn pending(&self) -> bool { self.launches.iter().any(|l| matches!(l.phase, LaunchPhase::Waiting { .. })) } + + /// `Tx::launch` asked for `target` this frame, whose source's text was at `from` on screen. + pub(in crate::runtime) fn wait(&mut self, target: String, from: [f32; 2]) { + self.step(LaunchEvent::Ask { target, from }); + } + + /// What this commit mounts, in the order they were asked for. Each launch waits for its + /// answer (`take_off` or `miss`) before it is over. + fn commit(&mut self) -> Vec<LaunchEffect> { self.step(LaunchEvent::Commit).into_iter().collect() } + + /// The destination `attempt` waited for mounted, and `flight` starts at its node. + fn take_off(&mut self, attempt: Attempt, flight: Launched) { + self.step(LaunchEvent::TakeOff { attempt, flight }); + } + + /// The destination `attempt` waited for didn't mount, so its launch is over. + pub(in crate::runtime) fn miss(&mut self, attempt: Attempt) { self.step(LaunchEvent::Missed { attempt }); } + + /// Starts (`on`) or drops the entry for `id`'s `El::matched` flight, which draws it outside + /// every clip until it lands. A `Tx::launch` on the same node draws it so already. + pub(in crate::runtime) fn unclip(&mut self, id: NodeId, on: bool) { self.step(LaunchEvent::Unclip { id, on }); } + + /// Drops the flights in the air that landed (left `flying`). Launches still waiting for + /// their destination stay for the commit that mounts it. + pub(in crate::runtime) fn keep(&mut self, flying: &[(NodeId, MRect)]) { self.step(LaunchEvent::Flights { flying }); } + + /// One transition: the phase each event leaves a launch in, and the mount attempts a commit + /// hands out. The caller finds the node and starts its path, then feeds the answer back. + fn step(&mut self, event: LaunchEvent) -> Effects<LaunchEffect> { + match event { + LaunchEvent::Ask { target, from } => { + let attempt = self.seq.next(); + self.launches.push(Launch { attempt, phase: LaunchPhase::Waiting { target, from } }); + Effects::none() + } + LaunchEvent::Commit => { + let mut mounts = Effects::none(); + for launch in &self.launches { + if let LaunchPhase::Waiting { target, from } = &launch.phase { + mounts.push(LaunchEffect::Mount { attempt: launch.attempt, target: target.clone(), from: *from }); + } + } + mounts + } + LaunchEvent::TakeOff { attempt, flight } => { + let waiting = self.launches.iter().position(|l| l.attempt == attempt && matches!(l.phase, LaunchPhase::Waiting { .. })); + // An answer whose launch is no longer waiting changes nothing. + if let Some(at) = waiting { + let to = flight.id; + self.launches.remove(at); + // It takes over the flight its node already had: a matched one, unclipped. + self.launches.retain(|l| l.airborne_id() != Some(to)); + self.launches.push(Launch { attempt, phase: LaunchPhase::Airborne(Airborne::Launched(flight)) }); + } + Effects::none() + } + LaunchEvent::Missed { attempt } => { + self.launches.retain(|l| !(l.attempt == attempt && matches!(l.phase, LaunchPhase::Waiting { .. }))); + Effects::none() + } + LaunchEvent::Unclip { id, on } => { + self.launches.retain(|l| !matches!(&l.phase, LaunchPhase::Airborne(Airborne::Unclipped { id: other }) if *other == id)); + if on && !self.flying(id) { + let attempt = self.seq.next(); + self.launches.push(Launch { attempt, phase: LaunchPhase::Airborne(Airborne::Unclipped { id }) }); + } + Effects::none() + } + LaunchEvent::Flights { flying } => { + self.launches.retain(|l| l.airborne_id().is_none_or(|id| flying.iter().any(|f| f.0 == id))); + Effects::none() + } + } + } + + /// Draws outside every clip until it lands: a launch, at its own size, or an unclipped + /// matched flight. + pub(in crate::runtime) fn flying(&self, id: NodeId) -> bool { self.launches.iter().any(|l| l.airborne_id() == Some(id)) } + + /// A launch in the air, which flies at its own size. + pub(in crate::runtime) fn launched(&self, id: NodeId) -> bool { self.flight(id).is_some() } + + /// The launch in the air at `id`, whose own path is what makes it a launch. + fn flight(&self, id: NodeId) -> Option<&Launched> { + self.launches.iter().find_map(|l| match &l.phase { + LaunchPhase::Airborne(Airborne::Launched(f)) if f.id == id => Some(f), + _ => None, + }) + } + + fn flight_mut(&mut self, id: NodeId) -> Option<&mut Launched> { + self.launches.iter_mut().find_map(|l| match &mut l.phase { + LaunchPhase::Airborne(Airborne::Launched(f)) if f.id == id => Some(f), + _ => None, + }) + } + + /// Before its destination's layout moves mid-flight and its path restarts from where it is + /// drawn: the offset and velocity outside the scene its last frame drew it with, which the + /// new path takes over, so the restart keeps its place and speed. It then flies on under + /// the offsets it was last drawn under. + pub(in crate::runtime) fn restart(&mut self, scene: &Scene, id: NodeId) -> [rune_motion::Vec2; 2] { + let Some(l) = self.flight_mut(id) else { return [rune_motion::Vec2::ZERO; 2] }; + let ([ox, oy], [vx, vy]) = l.blend(scene); + if let Some(drawn) = l.drawn { + let carried = l.carried(scene); + let travel = scene.get(id, prop::TRAVEL).unwrap_or(rune_motion::Vec2::new(1.0, 1.0)); + (l.folded, l.folded_at) = (carried, [1.0 - travel.x, 1.0 - travel.y]); + l.shift = drawn.offset; + } + [rune_motion::Vec2::new(ox, oy), rune_motion::Vec2::new(vx, vy)] + } + + /// How much of the scroll under it launch `id` doesn't ride yet: what its flight adds to the + /// offsets outside the scene, and what its re-aims folded into its path, let go as it + /// travels. Without a launch, nothing. + pub(in crate::runtime) fn carried(&self, scene: &Scene, id: NodeId) -> [f32; 2] { + self.flight(id).map_or([0.0; 2], |l| l.carried(scene)) + } + + /// What launch `id`'s flight adds to the offsets outside the scene it is drawn under, and + /// how much faster that moves it than they do. + pub(in crate::runtime) fn lead(&self, scene: &Scene, id: NodeId) -> [rune_motion::Vec2; 2] { + let Some(l) = self.flight(id) else { return [rune_motion::Vec2::ZERO; 2] }; + let ([ox, oy], [vx, vy]) = l.blend(scene); + [rune_motion::Vec2::new(ox, oy), rune_motion::Vec2::new(vx - l.drift[0], vy - l.drift[1])] + } + + /// A launch leaves from where its source was seen and flies to where its destination is + /// now: it starts under the offsets outside the scene it launched against and ends under + /// this frame's `offset`, blending by its travel. A growth row above still resizing, a + /// moved virtual window, or a row whose slot moves under an offset that hides the move + /// (an inserted row's growth) shifts where it lands, never where it is. What to add to it. + /// A commit's offset step comes with a layout move that hides it, so only frames with + /// no commit between them measure the offsets' drift. + pub(in crate::runtime) fn offset_fix(&mut self, scene: &Scene, id: NodeId, offset: [f32; 2], commit: u64) -> [f32; 2] { + let Some(l) = self.flight_mut(id) else { return [0.0; 2] }; + let now = scene.now(); + if let Some(last) = l.drawn && last.commit == commit && now > last.at { + let dt = (now - last.at) as f32; + l.drift = [(offset[0] - last.offset[0]) / dt, (offset[1] - last.offset[1]) / dt]; + } + l.drawn = Some(Drawn { offset, at: now, commit }); + let travel = scene.get(id, prop::TRAVEL).unwrap_or(rune_motion::Vec2::new(1.0, 1.0)); + [(l.shift[0] - offset[0]) * (1.0 - travel.x), (l.shift[1] - offset[1]) * (1.0 - travel.y)] + } +} + +impl Launched { + fn carried(&self, scene: &Scene) -> [f32; 2] { + let travel = scene.get(self.id, prop::TRAVEL).unwrap_or(rune_motion::Vec2::new(1.0, 1.0)); + let (blend, _) = self.blend(scene); + let left = [1.0 - travel.x, 1.0 - travel.y]; + [0, 1].map(|k| blend[k] + if self.folded_at[k] > 1e-4 { self.folded[k] * (left[k] / self.folded_at[k]).clamp(0.0, 1.0) } else { 0.0 }) + } + + /// What its flight adds to the offsets outside the scene it is drawn under, and how fast + /// that moves it. Drawn under `offset + (shift - offset) * (1 - travel)`: its rate is the + /// offset's drift times travel plus `(offset - shift) * rate`. + fn blend(&self, scene: &Scene) -> ([f32; 2], [f32; 2]) { + let Some(Drawn { offset: last, .. }) = self.drawn else { return ([0.0; 2], [0.0; 2]) }; + let travel = scene.get(self.id, prop::TRAVEL).unwrap_or(rune_motion::Vec2::new(1.0, 1.0)); + let rate = scene.store().sample_velocity(self.id, prop::TRAVEL).unwrap_or(rune_motion::Vec2::ZERO); + let (t, r) = ([travel.x, travel.y], [rate.x, rate.y]); + ( + [0, 1].map(|k| (self.shift[k] - last[k]) * (1.0 - t[k])), + [0, 1].map(|k| self.drift[k] * t[k] + (last[k] - self.shift[k]) * r[k]), + ) + } +} + +impl tracks::MotionState { + /// Starts the text flights and launches handlers asked for this frame. + #[allow(clippy::too_many_arguments)] + pub(in crate::runtime) fn capture_flights( + &mut self, + nodes: &[Node], + paint: &mut paint_state::PaintState, + text: &mut TextSystem, + scale: f32, + viewport: (f32, f32), + t: f64, + tx: &mut Tx, + ) { + for (source, target) in std::mem::take(&mut tx.text_flights) { + self.capture_text_flight(nodes, paint, text, scale, viewport, t, source, target); + } + for (source, target) in std::mem::take(&mut tx.launches) { + self.capture_launch(nodes, &paint.drawn, scale, source, target); + } + } + + /// Flights drawn within a quarter of a device pixel of where their layout would show them, + /// and moving under that a frame (60 Hz) faster than it: as good as landed, kept in the + /// air only by their springs' settle tails. They draw on the same pixels landed. + pub(in crate::runtime) fn landing_flights(&self, scene: &Scene, scale: f32) -> Vec<NodeId> { + let near = 0.25 / scale.max(1.0); + let within = |v: rune_motion::Vec2| v.x.abs().max(v.y.abs()) <= near; + self.flying.iter().map(|f| f.0).filter(|&id| { + let Some([p, v]) = scene.path_lead(id) else { return false }; + let [bp, bv] = self.launches.lead(scene, id); + let add = |a: rune_motion::Vec2, b: rune_motion::Vec2| rune_motion::Vec2::new(a.x + b.x, a.y + b.y); + let v = add(v, bv); + within(add(p, bp)) && within(rune_motion::Vec2::new(v.x / 60.0, v.y / 60.0)) + }).collect() + } + + /// Lands flight `id` at its layout, as if it had landed: it rides its parent from here. + pub(in crate::runtime) fn land_flight(&mut self, scene: &mut Scene, id: NodeId) { + self.flying.retain(|f| f.0 != id); + self.launches.keep(&self.flying); + scene.land_path(id); + } + + /// Shared-element motion (`El::matched`): each of the last commit's matched elements that + /// left the tree hands its geometry, radius, fill and opacity to the element with its id that + /// just mounted. Costs nothing without matched elements; else O(matched), plus one pass over + /// the old nodes when a pair matches. + #[allow(clippy::too_many_arguments)] + pub(in crate::runtime) fn match_elements( + &mut self, + tree: &types::TreeState, + paint: &paint_state::PaintState, + scene: &mut Scene, + commit: &mut commit::CommitState, + nodes: &[Node], + arrivals: &[(Rc<str>, usize, bool)], + tx: &Tx, + instant: bool, + reduced_motion: bool, + ) { + let mut by_id: HashMap<Rc<str>, (usize, bool)> = HashMap::with_capacity_and_hasher(arrivals.len(), Default::default()); + for (key, i, arriving) in arrivals { + if by_id.insert(key.clone(), (*i, *arriving)).is_some() { self.warn_duplicate_match(commit, key); } + } + let mut current: Vec<(Rc<str>, NodeId)> = by_id.iter().map(|(key, &(i, _))| (key.clone(), nodes[i].id)).collect(); + current.sort_unstable_by_key(|(key, _)| by_id[key].0); + let old = std::mem::replace(&mut self.matched, current); + // Under Reduce Motion the old one exits and the new one enters, each by its own + // transition (a crossfade in place) and with the parents it leaves or enters with. + if instant || tx.commit.lands() || reduced_motion { return; } + let mut old_index: Option<HashMap<NodeId, usize>> = None; + let mut built_index: Option<HashMap<NodeId, usize>> = None; + // Descendants first: matching an element unmounts its old subtree, matched ones included. + for (key, from) in old.into_iter().rev() { + let Some(&(i, true)) = by_id.get(&key) else { continue }; + let to = nodes[i].id; + let is_exiting = matches!(scene.phase(from), Some(PresencePhase::Exiting { .. })); + if from == to || tree.node_index.contains_key(&from) || !scene.contains(from) || is_exiting { continue; } + let index = old_index.get_or_insert_with(|| tree.nodes.iter().enumerate().map(|(k, n)| (n.id, k)).collect()); + let Some(&from_i) = index.get(&from) else { continue }; + // Scroll offsets live outside the scene: start where `from` was seen on screen. They + // come from the last build, which a commit earlier in the same frame (a glide's poll + // before the key that closes it) leaves in place, so look nodes up by id. + let built = &*built_index.get_or_insert_with(|| tree.built_ids.iter().enumerate().map(|(k, &id)| (id, k)).collect()); + // Flights drop the cover offsets of flights around them. + let shift = |id: NodeId| built.get(&id).and_then(|&k| paint.inh_scratch.get(k)).map_or([0.0; 2], |h| [h.dx - h.cover[0], h.dy - h.cover[1]]); + let source = tree.nodes[from_i].parent.map_or([0.0; 2], |p| shift(tree.nodes[p].id)); + let row = built.get(&from).and_then(|&k| paint.row_dy.get(k)).copied().unwrap_or(0.0); + let dest = std::iter::successors(nodes[i].parent, |&p| nodes[p].parent) + .map(|p| nodes[p].id).find(|id| built.contains_key(id)).map_or([0.0; 2], shift); + let offset = rune_motion::Vec2::new(source[0] - dest[0], source[1] + row - dest[1]); + let spring = tx.motion.map(MotionSource::spring).or(nodes[i].matched.as_ref().and_then(|m| m.1)).unwrap_or(crate::tok::motion::REFLOW); + let rest_fill = tree.nodes[from_i].vis.fill; + let fill = if scene.store().is_animating(from, P_FILL) { scene.get(from, P_FILL).unwrap_or(rest_fill) } else { rest_fill }; + let opacity = scene.get(from, prop::OPACITY); + scene.match_geometry_offset(from, to, offset, LayoutAnim::new(spring).screen()); + let live = |p: crate::live::Property| nodes[i].live.iter().any(|b| b.property == p); + if fill != nodes[i].vis.fill && !live(crate::live::Property::Fill) { + scene.set(to, P_FILL, fill); + scene.animate(to, P_FILL, nodes[i].vis.fill, spring); + } + if let Some(o) = opacity.filter(|&o| o != nodes[i].vis.opacity) && !live(crate::live::Property::Opacity) { + scene.set(to, prop::OPACITY, o); + scene.animate(to, prop::OPACITY, nodes[i].vis.opacity, spring); + } + // Its content mounted with it and flies as part of what was seen, so none of it fades + // in on its own (each fresh level under a present parent otherwise would). + for j in i + 1..nodes.len() { + if !std::iter::successors(nodes[j].parent, |&p| nodes[p].parent).any(|p| p == i) { break; } + scene.enter_now(nodes[j].id); + } + self.flying.retain(|f| f.0 != to); + self.flying.push((to, nodes[i].local)); + self.launches.unclip(to, tx.unclipped_flights); + } + } + + #[allow(clippy::too_many_arguments)] + pub(in crate::runtime) fn capture_text_flight( + &mut self, + nodes: &[Node], + paint: &mut paint_state::PaintState, + text: &mut TextSystem, + scale: f32, + viewport: (f32, f32), + t: f64, + source: String, + target: String, + ) { + let Some((i, n)) = nodes.iter().enumerate().find(|(_, n)| crate::flight::selects(&source, &n.path, n.key.as_deref())) else { return }; + let (Some(spec), Some(laid), Some(r)) = (&n.text, &n.text_layout, paint.drawn.get(i)) else { return }; + if spec.redacted || spec.content.is_empty() { return; } + let (rect, origin) = text_extent(n, spec, laid.view(), *r, scale); + let clip = screen_clip_of(n.parent, &paint.inh_scratch, &paint.turn_scratch).map(|v| v / scale); + let clip = [rect.x.max(clip[0]).max(0.0), rect.y.max(clip[1]).max(0.0), + (rect.x + rect.w).min(clip[2]).min(viewport.0), (rect.y + rect.h).min(clip[3]).min(viewport.1)]; + if rect.w <= 0.0 || clip[2] <= clip[0] || clip[3] <= clip[1] { return; } + paint.glyph_scratch.clear(); + text.set_glyph_inks(spec.color, &[]); + // From outlines where text draws them, which a flight's zoom magnifies without blurring. + text.set_emit(text.moving_emit()); + for p in laid.view().pieces() { + text.glyphs_for_layout(p.layout, scale, [origin[0] * scale, origin[1] * scale + p.y], false, &mut paint.glyph_scratch); + } + text.set_emit(crate::text::outline::Emit::Atlas); + let color = spec.color; + let srgb = paint.srgb_blend(); + // Colour glyphs live in the image atlas, which may move them before the flight ends. + let glyphs = paint.glyph_scratch.iter().filter(|q| q.color == 0 && q.rect[1] < clip[3] * scale && q.rect[1] + q.rect[3] > clip[1] * scale) + .map(|q| glyph(q, premul(color, 1.0, srgb), clip.map(|v| v * scale), [0.0; 4])).collect(); + self.flights.push(TextFlight::new(source, target, rect, clip, glyphs, scale, t)); + } + + /// `Tx::launch`, before the commit: where the source's text starts on screen. + pub(in crate::runtime) fn capture_launch(&mut self, nodes: &[Node], drawn: &[[f32; 4]], scale: f32, source: String, target: String) { + let Some((i, n)) = nodes.iter().enumerate().find(|(_, n)| crate::flight::selects(&source, &n.path, n.key.as_deref())) else { return }; + let (Some(spec), Some(laid), Some(r)) = (&n.text, &n.text_layout, drawn.get(i)) else { return }; + let (_, origin) = text_extent(n, spec, laid.view(), *r, scale); + self.launches.wait(target, origin); + } + + /// `Tx::launch`, in the commit: each destination that just mounted starts with its first + /// text where its source's text was seen, at its own size, and flies to its place unclipped. + #[allow(clippy::too_many_arguments)] + pub(in crate::runtime) fn launch_elements( + &mut self, + tree: &types::TreeState, + paint: &paint_state::PaintState, + scene: &mut Scene, + nodes: &[Node], + tx: &Tx, + instant: bool, + scale: f32, + reduced_motion: bool, + ) { + let mounts = self.launches.commit(); + if instant || tx.commit.lands() || reduced_motion { + for LaunchEffect::Mount { attempt, .. } in mounts { self.launches.miss(attempt); } + return; + } + let index: HashMap<NodeId, usize> = tree.nodes.iter().enumerate().map(|(k, n)| (n.id, k)).collect(); + let built: HashMap<NodeId, usize> = tree.built_ids.iter().enumerate().map(|(k, &id)| (id, k)).collect(); + for mount in mounts { + let LaunchEffect::Mount { attempt, target, from } = mount; + let Some(i) = nodes.iter().position(|n| crate::flight::selects(&target, &n.path, n.key.as_deref())) else { + self.launches.miss(attempt); + continue; + }; + let to = nodes[i].id; + if index.contains_key(&to) && !matches!(scene.phase(to), Some(PresencePhase::Exiting { .. })) { + self.launches.miss(attempt); + continue; + } + let within = |mut j: usize| loop { + match nodes[j].parent { + Some(p) if p == i => break true, + Some(p) if p > i => j = p, + _ => break false, + } + }; + // Its first text, or its own top-left. + let t = nodes[i].target; + let rel = (i..nodes.len()).take_while(|&j| j == i || within(j)).find_map(|j| { + let (Some(spec), Some(laid)) = (&nodes[j].text, &nodes[j].text_layout) else { return None }; + let r = nodes[j].target; + let (_, origin) = text_extent(&nodes[j], spec, laid.view(), [r[0], r[1], r[2] - r[0], r[3] - r[1]], scale); + Some([origin[0] - t[0], origin[1] - t[1]]) + }).unwrap_or([0.0; 2]); + // Scroll offsets live outside the scene: subtract the destination's. Under a still + // scale, its screen point maps back through it to where it is laid out. Both come + // from the last build, which a commit earlier in the same frame leaves in place. + let (mut shift, mut zoom) = ([0.0; 2], (1.0, [0.0; 2], [0.0; 2])); + if let Some(h) = std::iter::successors(nodes[i].parent, |&p| nodes[p].parent) + .find_map(|p| built.get(&nodes[p].id).copied()) + .and_then(|k| paint.inh_scratch.get(k)) + { + shift = [h.dx - h.cover[0], h.dy - h.cover[1]]; + zoom = h.still; + } + let (k, anchor, anchor_to) = zoom; + let at = |axis: usize| anchor[axis] + (from[axis] - anchor_to[axis]) / k - rel[axis] - shift[axis]; + let (w, h) = (t[2] - t[0], t[3] - t[1]); + let start = MRect::new(at(0), at(1), w, h); + let spring = tx.motion.map_or(crate::tok::motion::REFLOW, MotionSource::spring); + scene.launch(to, start, LayoutAnim::new(spring).screen()); + self.flying.retain(|f| f.0 != to); + self.flying.push((to, nodes[i].local)); + self.launches.take_off(attempt, Launched { id: to, shift, drawn: None, drift: [0.0; 2], folded: [0.0; 2], folded_at: [0.0; 2] }); + } + } + + fn warn_duplicate_match(&mut self, commit: &mut commit::CommitState, key: &Rc<str>) { + let message = || format!("duplicate matched id {key:?}: the last element in tree order is matched; give each element its own id"); + commit.push_key_warning(message); + #[cfg(debug_assertions)] + if self.matched_warned.insert(key.clone()) { eprintln!("rune: {}", message()); } + } +} + +#[cfg(test)] +#[path = "flights_tests.rs"] +mod tests; diff --git a/app/vendor/rune/crates/rune/src/runtime/motion/flights_tests.rs b/app/vendor/rune/crates/rune/src/runtime/motion/flights_tests.rs new file mode 100644 index 0000000..c22af36 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/motion/flights_tests.rs @@ -0,0 +1,97 @@ +use super::*; + +/// A launch at `id`, as `launch_elements` starts it. +fn flight(id: NodeId) -> Launched { + Launched { id, shift: [0.0; 2], drawn: None, drift: [0.0; 2], folded: [0.0; 2], folded_at: [0.0; 2] } +} + +/// A flight of the window's, which keeps the launches at its node in the air. +fn air(id: NodeId) -> (NodeId, MRect) { (id, MRect::new(0.0, 0.0, 1.0, 1.0)) } + +/// The attempts this commit hands out, one per launch waiting for a destination. +fn mounts(launches: &mut Launches) -> Vec<(Attempt, String, [f32; 2])> { + launches.commit().into_iter().map(|mount| { + let LaunchEffect::Mount { attempt, target, from } = mount; + (attempt, target, from) + }).collect() +} + +/// How many flights the launch at `id` has in the air: one, or the state is wrong. +fn airborne(launches: &Launches, id: NodeId) -> usize { + launches.launches.iter().filter(|l| l.airborne_id() == Some(id)).count() +} + +#[test] +fn a_launch_waits_for_its_destination_under_its_own_attempt() { + let mut launches = Launches::default(); + assert!(!launches.pending(), "nothing asked for"); + launches.wait("msg-2/body".into(), [4.0, 9.0]); + launches.wait("msg-3".into(), [0.0; 2]); + assert!(launches.pending()); + let asked = mounts(&mut launches); + assert_eq!(asked.len(), 2); + assert_eq!((asked[0].0, asked[1].0), (Attempt(1), Attempt(2)), "one attempt per launch"); + assert_eq!((asked[0].1.as_str(), asked[0].2), ("msg-2/body", [4.0, 9.0]), "where its source's text was"); + assert!(launches.pending(), "it waits for the answer the mount attempt gets"); + assert!(!launches.flying(NodeId(1)), "a launch waiting for its node flies nothing"); +} + +#[test] +fn a_waiting_launch_whose_destination_never_mounts_ends_by_its_answer() { + let mut launches = Launches::default(); + launches.wait("nowhere".into(), [0.0; 2]); + let asked = mounts(&mut launches); + launches.miss(asked[0].0); + assert!(!launches.pending(), "answered, it is over rather than waiting forever"); + let wanted = NodeId(4); + launches.take_off(asked[0].0, flight(wanted)); + assert!(!launches.flying(wanted), "an answer to a launch that is gone changes nothing"); +} + +#[test] +fn a_launch_in_the_air_flies_at_its_own_size_until_its_flight_leaves() { + let mut launches = Launches::default(); + launches.wait("body".into(), [0.0; 2]); + let asked = mounts(&mut launches); + let to = NodeId(7); + launches.take_off(asked[0].0, flight(to)); + assert!(launches.flying(to) && launches.launched(to), "in the air, drawn outside every clip"); + assert_eq!(airborne(&launches, to), 1, "one flight at its node"); + assert!(!launches.pending(), "taken off, it no longer waits"); + launches.keep(&[air(to)]); + assert!(launches.flying(to), "kept while its flight is in the air"); + launches.keep(&[]); + assert!(!launches.flying(to) && !launches.launched(to), "landed, it clips again"); +} + +#[test] +fn a_matched_flight_started_unclipped_draws_outside_every_clip_until_it_lands() { + let mut launches = Launches::default(); + let to = NodeId(3); + launches.unclip(to, true); + assert!(launches.flying(to) && !launches.launched(to), "unclipped, but not a launch"); + assert_eq!(airborne(&launches, to), 1); + launches.keep(&[air(to)]); + launches.keep(&[]); + assert!(!launches.flying(to), "landed, it clips again"); + // A match without the flag leaves nothing behind, and neither does asking twice. + launches.unclip(to, true); + launches.unclip(to, true); + assert_eq!(airborne(&launches, to), 1, "one entry, however often it is asked for"); + launches.unclip(to, false); + assert!(!launches.flying(to)); +} + +#[test] +fn a_launch_over_a_node_matched_unclipped_is_one_flight_that_stays_unclipped() { + let mut launches = Launches::default(); + let to = NodeId(9); + launches.unclip(to, true); + launches.wait("body".into(), [1.0, 2.0]); + let asked = mounts(&mut launches); + launches.take_off(asked[0].0, flight(to)); + assert_eq!(airborne(&launches, to), 1, "the matched entry gives way to the launch, not beside it"); + assert!(launches.launched(to) && launches.flying(to), "one flight per node, still unclipped"); + launches.keep(&[]); + assert!(!launches.flying(to), "gone with its flight"); +} diff --git a/app/vendor/rune/crates/rune/src/runtime/motion/fold_hold.rs b/app/vendor/rune/crates/rune/src/runtime/motion/fold_hold.rs new file mode 100644 index 0000000..e2ca75c --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/motion/fold_hold.rs @@ -0,0 +1,144 @@ +//! A fold shutting under its own header, held stuck to the top of its viewport by +//! `Tx::keep_on_screen`. Most of what it held may sit above that header, out of sight: that part +//! goes at once, with the viewport's offset dropping by as much so nothing on screen moves, and +//! the contents left ride the fold's bottom edge (`GrowTrack::hide_above`). What shows then +//! slides up under the header on the fold's spring, the rows below rising with it. When the +//! viewport's end will stop them short, the header gives way from the start instead, coming +//! down a fixed share of each point the fold shuts by (`give_way`), so the bottom edge eases +//! into its rest as the header comes down over the rest, and the two land together. Opened +//! again before it lands, the contents ride back down, and what went above comes back there +//! as the glide lands (`restore_above`), again with the offset taking it up; at a pinned end, +//! it grows from its bottom instead, the header rising back to the top (`ride_from_end`). +use super::*; + +impl RuntimeCore { + /// Row `j` of the commit's `nodes`, a fold shutting to `to` points: how many of its points + /// sit above the header held stuck in it, and that header's path, when it keeps no more + /// than that header shows. + pub(in crate::runtime) fn fold_hidden_above(&self, nodes: &[Node], j: usize, to: f32) -> Option<(f32, String)> { + if !self.scroll.requests.has_keeps() || !self.tree.built || self.scroll.stuck.len() != self.tree.nodes.len() { return None; } + let row = &nodes[j].path; + let within = |path: &str| path.starts_with(row.as_str()) && path.as_bytes().get(row.len()) == Some(&b'/'); + let hold = self.scroll.requests.keeps().filter_map(|k| k.hold.as_ref()).find(|h| within(&h.path))?; + let mut end = j + 1; + while end < nodes.len() && nodes[end].parent.is_some_and(|p| p >= j) { end += 1; } + let header = (j + 1..end).find(|&i| nodes[i].path == hold.path)?; + if to > nodes[header].target[3] - nodes[j].target[1] + 0.5 { return None; } + let header_id = nodes[header].id; + let was = self.tree.nodes.iter().position(|n| n.id == header_id) + .or_else(|| (self.tree.built_ids.len() == self.scroll.stuck.len()).then(|| self.tree.built_ids.iter().position(|&id| id == header_id)).flatten())?; + Some((self.scroll.stuck[was], hold.path.clone())).filter(|&(s, _)| s > 0.5) + } + + /// The scroll viewport around growth stack `c` of the commit's `nodes` steps `cut` points + /// back, as the folds in it dropped that much above what shows. + pub(in crate::runtime) fn scroll_by_cut(&mut self, nodes: &[Node], c: usize, cut: f32) { + let Some(s) = std::iter::successors(nodes[c].parent, |&p| nodes[p].parent) + .find(|&p| nodes[p].scroll.is_some() && nodes[p].scroll_axes.y()) else { return }; + let Some(st) = self.scroll.scrolls.get_mut(&nodes[s].id) else { return }; + let cut = f64::from(cut); + st.offset = (st.offset - cut).max(0.0); + st.max = (st.max - cut).max(0.0); + if let ScrollMode::Glide { to: GlideTo::Offset(to) | GlideTo::ShrunkEnd(to), .. } = &mut st.mode { *to = (*to - cut).max(0.0); } + } + + /// Folds `held` (id, points cut below the window) in growth stack `c` of the commit's + /// `nodes` just shut under their held headers. Riding their bottom edges up, what shows would + /// meet the viewport's end, stop dead and leave the header to come down the rest on its own: + /// instead each header comes down the share of the fold's travel the end can't take, so the + /// bottom slides `slack` points over the whole shut, on the same spring. + pub(in crate::runtime) fn give_way(&mut self, nodes: &[Node], c: usize, held: &[(NodeId, f32)]) { + let Some(s) = std::iter::successors(nodes[c].parent, |&p| nodes[p].parent) + .find(|&p| nodes[p].scroll.is_some() && nodes[p].scroll_axes.y()) else { return }; + let Some(st) = self.scroll.scrolls.get(&nodes[s].id) else { return }; + // How far the content's end sits below the viewport's bottom once the cuts land. + let slack = (st.max - st.offset) as f32 - held.iter().map(|&(_, below)| below).sum::<f32>(); + let travel: f32 = held.iter().filter_map(|(id, _)| self.motion.grows.get(id)).map(|g| g.h - g.target).sum(); + if travel <= 1.0 || slack >= travel { return; } + let share = 1.0 - slack.max(0.0) / travel; + for (id, _) in held { + if let Some(g) = self.motion.grows.get_mut(id) { g.give = Some(share); } + } + } + + /// Fold `row`, shutting under its held header with `GrowTrack::give`, shut `d` points + /// further times its share: the hold on its header expects it that much lower. + pub(in crate::runtime) fn lower_hold(&mut self, row: NodeId, d: f32) { + let Some(header) = self.motion.fold_headers.get(&row) else { return }; + for k in self.scroll.requests.keeps_mut().filter(|k| k.hold.as_ref().is_some_and(|h| h.path == *header)) { + k.was += d; + } + } + + /// A header giving way lands as its viewport's end comes within pinning distance: the end + /// brings it the last fraction of a point, rather than the two trading it back and forth. + /// Short of that, a frame that shuts more than the end has left clamps the viewport at its + /// end before the hold moves it back; the hold stays. + pub(in crate::runtime) fn end_takes_over(&mut self) { + if self.motion.fold_headers.is_empty() || !self.scroll.requests.has_keeps() { return; } + let giving: Vec<&String> = self.motion.fold_headers.iter() + .filter(|(id, _)| self.motion.grows.get(id).is_some_and(|g| g.give.is_some_and(|share| (g.h - g.target) * (1.0 - share) < 0.5))) + .map(|(_, p)| p).collect(); + if giving.is_empty() { return; } + let pinned = |viewport: &str| self.tree.path_ids.get(viewport).and_then(|id| self.scroll.scrolls.get(id)).is_some_and(|st| st.pinned()); + self.scroll.requests.step(requests::EndTakesOver { giving: &giving, pinned }); + } + + /// Row `j` of the commit's `nodes`, a fold opening from rest or again while its contents + /// draw lifted, in growth stack `c`: with its viewport pinned to its end, or its header giving way to it + /// (`giving`), the holds on it, in it or above it let go, so it grows from its bottom with + /// the end (or, short of it, the row below) held and its contents still, rather than pushing + /// the end down and then snapping its header up as it lands. + pub(in crate::runtime) fn ride_from_end(&mut self, nodes: &[Node], c: usize, j: usize, giving: bool) { + let Some(s) = std::iter::successors(nodes[c].parent, |&p| nodes[p].parent) + .find(|&p| nodes[p].scroll.is_some() && nodes[p].scroll_axes.y()) else { return }; + let pinned = self.scroll.scrolls.get(&nodes[s].id).is_some_and(|st| st.pinned()); + if !pinned && !giving { return; } + let mut end = j + 1; + while end < nodes.len() && nodes[end].parent.is_some_and(|p| p >= j) { end += 1; } + let viewport = &nodes[s].path; + self.scroll.requests.step(requests::FoldOpens { viewport, end, index: |path: &str| nodes.iter().position(|n| n.path == path) }); + if !pinned && self.paint.drawn.len() == self.tree.nodes.len() + && let Some(below) = nodes.get(end).filter(|n| n.path.starts_with(viewport.as_str())) + && let Some(i) = self.tree.nodes.iter().position(|n| n.id == below.id) + && let Some(v) = self.tree.nodes.iter().position(|n| n.id == nodes[s].id) + { + let was = sticky::keep_y(&self.paint.drawn, &self.paint.drawn_scale, i, v); + self.scroll.requests.step(requests::Event::Arrive(requests::Request::FoldAnchor(sticky::Keep { + path: below.path.clone(), + viewport: viewport.clone(), + was, + virtual_row: None, + hold: None, + }))); + } + // How far below the viewport's top the fold's top showed: its header rises that far. + let shown = (self.paint.drawn.len() == self.tree.nodes.len()).then(|| { + let row = self.tree.nodes.iter().position(|n| n.id == nodes[j].id)?; + let view = self.tree.nodes.iter().position(|n| n.id == nodes[s].id)?; + let scale = self.paint.drawn_scale.get(view).copied().filter(|&k| k > 1e-4)?; + Some(((self.paint.drawn[row][1] - self.paint.drawn[view][1]) / scale).max(0.0)) + }).flatten().unwrap_or(0.0); + let Some(g) = self.motion.grows.get_mut(&nodes[j].id) else { return }; + // And what its contents hid below its bottom edge shows: for a fold opening from rest, + // all it opens, so its spring carries it whole with its contents still in its layout. + let below = (g.target - g.h - g.lift()).max(0.0); + g.ride_up(shown + below); + } + + /// Fold `row` in growth stack `ci` landed whole with `r` points of its contents still drawn + /// lifted: they come back above it, out of sight, so its viewport's offset steps `r` on and + /// the holds on the fold or above it expect it that much higher. + pub(in crate::runtime) fn restore_above(&mut self, ci: usize, row: NodeId, r: f32) { + let Some(s) = self.viewport_of(ci) else { return }; + let (path, id) = (self.tree.nodes[s].path.clone(), self.tree.nodes[s].id); + let Some(st) = self.scroll.scrolls.get_mut(&id) else { return }; + if st.pinned() { return; } + st.offset += f64::from(r); + st.max = st.max.max(st.offset); + let Some(&ri) = self.tree.node_index.get(&row) else { return }; + for k in self.scroll.requests.keeps_mut().filter(|k| k.viewport == path) { + if self.tree.nodes.iter().position(|n| n.path == k.path).is_some_and(|i| i <= ri) { k.was -= r; } + } + } +} diff --git a/app/vendor/rune/crates/rune/src/runtime/motion/growth_rows.rs b/app/vendor/rune/crates/rune/src/runtime/motion/growth_rows.rs new file mode 100644 index 0000000..afe283f --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/motion/growth_rows.rs @@ -0,0 +1,97 @@ +//! Where a frame presents each growth row: its top offset, its height and its bottom feather +//! mask, per node index, from its stack's tracks. +use super::*; + +impl RuntimeCore { + pub(in crate::runtime) fn growth_feather(&self, i: usize) -> f32 { + let width = (self.paint.row_mask[i] * self.env.scale).clamp(0.0, 65504.0); + if self.motion.grows.get(&self.tree.nodes[i].id).is_some_and(|g| g.linear_edge) { -width } else { width } + } + + /// Fills `row_dy`, `row_h` and `row_mask` for this frame's nodes. + pub(in crate::runtime) fn place_growth_rows(&mut self) { + let (s, n_nodes) = (self.env.scale, self.tree.nodes.len()); + self.paint.row_dy.clear(); + self.paint.row_dy.resize(n_nodes, 0.0); + self.paint.row_h.clear(); + self.paint.row_h.resize(n_nodes, -1.0); + self.paint.row_mask.clear(); + self.paint.row_mask.resize(n_nodes, -1.0); + self.paint.clear_row_lifts(); + let mut emptied = Vec::new(); + for (cid, stack) in &self.motion.stacks { + let Some(&ci) = self.tree.node_index.get(cid) else { continue }; + let Some(spec) = self.tree.nodes[ci].growth.as_deref().copied() else { continue }; + let origin = self.commit.virtuals.get(&self.tree.nodes[ci].path).map_or(0.0, |v| v.before); + self.paint.row_dy[ci] = grid(origin, s); + let mut y = stack.pad_top - origin; + let mut first_row = true; + for id in &stack.order { + let Some(g) = self.motion.grows.get(id) else { continue }; + if !first_row { y += stack.gap; } + first_row = false; + let top_rel = stack.tops.get(id).copied().unwrap_or(0.0) - origin; + let cur = y; + if let Some(&ri) = self.tree.node_index.get(id) { + self.paint.row_dy[ri] = cur - top_rel; + self.paint.row_h[ri] = g.h; + let withheld = if g.streaming { (self.tree.nodes[ri].local.h - g.target).max(0.0) } else { 0.0 }; + let rewrap = stack.pending_heights.contains_key(id) && self.tree.nodes[ri].local.h > g.h + 0.01; + let overflows = spec.edge.overflow && (g.streaming || g.paced()); + // A fold that landed shut keeps what it folded away where it drew, lifted + // and clipped, until that has left: let go as it lands, the contents would + // drop back to their layout for the frames their exit has left. + let landed = g.shut() && !g.moving(); + let folded = landed && self.holds_exiting(ri); + if landed && !folded { emptied.push(*id); } + if spec.edge.clip && !overflows && (g.h < g.target - 0.01 || g.mask > 0.01 || withheld > 0.01 || rewrap || g.shutting_fold() || folded) { + self.paint.row_mask[ri] = g.mask.max(withheld.min(spec.edge.floor)).max(if rewrap { spec.edge.floor } else { 0.0 }); + } + let lift = if landed && !folded { 0.0 } else { g.lift() }; + if lift > 0.0 { + self.paint.push_row_lift(ri, lift); + } + } + y = cur + g.h; + } + // The stack itself presents the rows' heights, which scrolling follows. + self.paint.row_h[ci] = y + stack.pad_bottom; + for (id, dy) in stack.slides.shifts() { + if let Some(&i) = self.tree.node_index.get(&id) { self.paint.row_dy[i] += dy; } + } + } + for id in emptied { + if let Some(g) = self.motion.grows.get_mut(&id) { g.forget_folded(); } + } + // A fold's lifted contents (`GrowTrack::hide_above`) draw that far up inside it, all but + // the header it shuts under. + for idx in 0..self.paint.row_lifts().len() { + let (ri, lift) = self.paint.row_lifts()[idx]; + let mut k = ri + 1; + while k < n_nodes && self.tree.nodes[k].parent.is_some_and(|p| p >= ri) { + if self.tree.nodes[k].parent == Some(ri) { self.paint.row_dy[k] -= lift; } + k += 1; + } + let header = self.motion.fold_headers.get(&self.tree.nodes[ri].id).and_then(|p| self.tree.path_ids.get(p)).and_then(|id| self.tree.node_index.get(id)); + if let Some(&h) = header.filter(|&&h| h > ri && h < k) { self.paint.row_dy[h] += lift; } + } + self.place_joined_rows(); + if !self.motion.fold_headers.is_empty() { + let lifted: Vec<NodeId> = self.paint.row_lifts().iter().map(|&(ri, _)| self.tree.nodes[ri].id).collect(); + self.motion.fold_headers.retain(|id, _| lifted.contains(id)); + } + } + + /// Something inside row `ri` is leaving. Leaving nodes follow the ones that stay, so they + /// needn't sit in one run after it. + fn holds_exiting(&self, ri: usize) -> bool { + let inside = |mut i: usize| loop { + match self.tree.nodes[i].parent { + Some(p) if p == ri => return true, + Some(p) if p > ri => i = p, + _ => return false, + } + }; + (ri + 1..self.tree.nodes.len()).any(|i| inside(i) && self.is_exiting(self.tree.nodes[i].id)) + } +} diff --git a/app/vendor/rune/crates/rune/src/runtime/motion/growth_runs.rs b/app/vendor/rune/crates/rune/src/runtime/motion/growth_runs.rs new file mode 100644 index 0000000..2c9f149 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/motion/growth_runs.rs @@ -0,0 +1,138 @@ +//! Fold rows that open or shut together move as one block. Consecutive `El::fold_glide` rows a +//! commit brings into a growth stack (or takes out of it) share one spring, which fills them top +//! to bottom (or empties them bottom to top) under one feathered edge, as a code diff opens a +//! hunk. On their own spring each, every row of the block would open at once, each half open +//! under an edge of its own, and the rows below would cross the block's lower lines. +use super::*; +use crate::growth::{FoldGlide, GrowTrack}; + +#[derive(Clone, Debug)] +pub(in crate::runtime) enum GrowthRun { + /// Consecutive rows of one stack, moving on one spring. + Formed { + rows: Vec<NodeId>, + /// Each row's full extent: its target when opening, its height when shutting. + extents: Vec<f32>, + /// What each row aimed at when the block formed; a later change to any breaks the block. + targets: Vec<f32>, + /// The block's height on the rows' fold spring. + track: GrowTrack, + }, + /// The block no longer stands: it broke at the commit that moved a row off its aim, and its + /// rows carry on alone from where they are. + Broken, +} + +impl GrowthRun { + /// One block of `ids` (consecutive rows of one stack), from their tracks as they stand. + fn link(ids: &[NodeId], grows: &HashMap<NodeId, GrowTrack>) -> Option<GrowthRun> { + let tracks: Vec<&GrowTrack> = ids.iter().map(|id| grows.get(id)).collect::<Option<_>>()?; + let spring = tracks[0].glide()?; + let mut track = GrowTrack::settled(tracks.iter().map(|g| g.h).sum()); + track.set_kind(false, true, Some((FoldGlide { spring, feather: tracks[0].feather() }, f32::INFINITY))); + track.retarget(tracks.iter().map(|g| g.target).sum()); + Some(GrowthRun::Formed { + rows: ids.to_vec(), + extents: tracks.iter().map(|g| g.target.max(g.h)).collect(), + targets: tracks.iter().map(|g| g.target).collect(), + track, + }) + } + + /// A commit's verdict on the block: true while every row still aims where it did and they + /// still stand together in `order`. Otherwise it breaks, and each row carries on alone from + /// where it is, the row at the edge with the block's speed. + fn commit(&mut self, order: &[NodeId], grows: &mut HashMap<NodeId, GrowTrack>) -> bool { + let GrowthRun::Formed { rows, targets, track, .. } = self else { return false }; + let aims = rows.iter().zip(&*targets).all(|(id, &t)| grows.get(id).is_none_or(|g| (g.target - t).abs() < 1e-4)); + let present: Vec<usize> = rows.iter().filter_map(|id| order.iter().position(|o| o == id)).collect(); + if aims && present.windows(2).all(|w| w[1] == w[0] + 1) { return true; } + let speed = track.v; + for id in rows.iter() { + if let Some(g) = grows.get_mut(id) && g.h > 1e-4 && g.h < g.target.max(g.h) - 1e-4 { + g.v = speed; + } + } + *self = GrowthRun::Broken; + false + } + + /// The block's rows, none of them once it has broken. + fn rows(&self) -> &[NodeId] { + match self { + GrowthRun::Formed { rows, .. } => rows, + GrowthRun::Broken => &[], + } + } + + /// Whether the block still has motion to step. + fn moving(&self) -> bool { + matches!(self, GrowthRun::Formed { track, .. } if track.moving()) + } + + /// Steps the block and gives each row its share: rows above the edge whole, the row at the + /// edge its part and the feather, rows past it nothing. Returns how far the rows grew. + fn step(&mut self, steps: crate::growth::Substeps, spring: rune_motion::Spring, edge: &crate::growth::StreamEdge, grows: &mut HashMap<NodeId, GrowTrack>) -> f32 { + let GrowthRun::Formed { rows, extents, track, .. } = self else { return 0.0 }; + for dt in steps { + track.step_by(dt, spring, edge, false); + } + let (mut left, mut grown) = (track.h, 0.0); + for (id, &extent) in rows.iter().zip(&*extents) { + let h = left.clamp(0.0, extent); + left -= extent; + let Some(g) = grows.get_mut(id) else { continue }; + let at_edge = h > 1e-4 && h < extent - 1e-4; + grown += (h - g.h).max(0.0); + g.h = h; + g.v = if at_edge { track.v } else { 0.0 }; + g.mask = if at_edge { track.mask } else { 0.0 }; + } + grown + } +} + +impl tracks::MotionState { + /// At a commit, after the stack's rows have their new targets: breaks blocks this commit + /// changed and forms new ones from runs of rows in `order` that were `opened` (new fold rows + /// growing from nothing) or `shut` (fold rows that left) by it. + pub(in crate::runtime) fn link_growth_runs(&mut self, stack: &mut Stack, order: &[NodeId], opened: &[NodeId], shut: &[NodeId]) { + let grows = &mut self.grows; + stack.runs.retain_mut(|run| run.commit(order, grows)); + for id in shut { + if let Some(g) = grows.get_mut(id) { g.retarget(0.0); } + } + let fold = |g: &GrowTrack| (g.glide(), g.feather()); + for set in [opened, shut] { + let mut block: Vec<NodeId> = Vec::new(); + for id in order.iter().map(Some).chain([None]) { + let eligible = id.filter(|id| set.contains(id)) + .and_then(|id| grows.get(id)) + .filter(|g| g.glide().is_some() && !g.staged() && g.lift() == 0.0); + if let (Some(g), Some(id)) = (eligible, id) + && block.last().and_then(|last| grows.get(last)).is_none_or(|last| fold(last) == fold(g)) + { + block.push(*id); + continue; + } + if block.len() > 1 && let Some(run) = GrowthRun::link(&block, grows) { + stack.runs.push(run); + } + block.clear(); + if let (Some(_), Some(id)) = (eligible, id) { block.push(*id); } + } + } + } + + /// Steps a stack's blocks before its rows, and returns the rows they moved (which skip their + /// own step this frame) and how far they grew. + pub(in crate::runtime) fn step_growth_runs(stack: &mut Stack, grows: &mut HashMap<NodeId, GrowTrack>, steps: crate::growth::Substeps, spec: crate::el::GrowthSpec) -> (Vec<NodeId>, f32) { + let (mut rows, mut grown) = (Vec::new(), 0.0); + stack.runs.retain_mut(|run| { + grown += run.step(steps, spec.spring, &spec.edge, grows); + rows.extend(run.rows().iter().copied()); + run.moving() + }); + (rows, grown) + } +} diff --git a/app/vendor/rune/crates/rune/src/runtime/motion/idle_meter.rs b/app/vendor/rune/crates/rune/src/runtime/motion/idle_meter.rs new file mode 100644 index 0000000..b6f2364 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/motion/idle_meter.rs @@ -0,0 +1,43 @@ +//! The runtime's side of `perf_warn`'s idle meters: what woke a frame, and what it drew. +use super::*; + +impl timer_wake::FrameState { + /// Before a frame's poll. `timer`: a due `wake_after` woke it, or a resting wake's poll + /// stands for it; `live`: a live value did. + #[inline(always)] + #[cfg_attr(not(debug_assertions), allow(unused_variables))] + pub(in crate::runtime) fn idle_frame_begins(&mut self, animating: bool, timer: bool, live: bool) { + #[cfg(debug_assertions)] + self.idle_meter.begins(self.queue.is_empty() && !animating, timer, live); + } + + /// After a frame built its instances. + #[cfg(debug_assertions)] + #[inline(always)] + #[allow(clippy::too_many_arguments)] + pub(in crate::runtime) fn idle_frame_ends( + &mut self, + clock: f64, + animating: bool, + clear: [f32; 4], + viewport: (f32, f32), + scale: f32, + srgb_blend: bool, + transparent: bool, + image_copies: u64, + instances: &[Instance], + opaque: bool, + title: Option<&str>, + ) { + use std::hash::{Hash, Hasher}; + let mut key = std::collections::hash_map::DefaultHasher::new(); + (clear.map(f32::to_bits), viewport.0.to_bits(), viewport.1.to_bits(), scale.to_bits()).hash(&mut key); + (srgb_blend, transparent, image_copies).hash(&mut key); + let drawn = crate::tooling::perf_warn::Drawn { + instances: bytemuck::cast_slice(instances), + key: key.finish(), + opaque, + }; + self.idle_meter.ends(clock, animating, drawn, || title.map(str::to_owned)); + } +} diff --git a/app/vendor/rune/crates/rune/src/runtime/motion/landing_hold.rs b/app/vendor/rune/crates/rune/src/runtime/motion/landing_hold.rs new file mode 100644 index 0000000..2a3f657 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/motion/landing_hold.rs @@ -0,0 +1,85 @@ +//! `El::hold_landing_width`: a column whose width springs (a side panel opening beside it) takes +//! its landing layout at once, so its text wraps once, and slides as one from where its first +//! child in view was drawn. The commit lands the held subtree's layout and gives the holding +//! element an offset of that child's jump, which springs back to its own offset. +use super::*; + +/// The nodes the last commit held at their landing width, kept for the frame that draws them: +/// motion checks take that frame's re-layout as designed. +#[derive(Debug, Default)] +pub(in crate::runtime) struct LandingHolds(HashSet<NodeId>); + +impl LandingHolds { + pub(in crate::runtime) fn clear(&mut self) { + self.0.clear(); + } + + pub(in crate::runtime) fn holds(&self, id: NodeId) -> bool { + !self.0.is_empty() && self.0.contains(&id) + } +} + +impl tracks::MotionState { + /// Marks in `held`, per node of `nodes`, those this commit lands under an + /// `El::hold_landing_width` element whose width changes, and returns each such element's + /// index with how far it shifts so its anchor child stays where it was drawn. `held` stays + /// empty when nothing holds. + #[allow(clippy::too_many_arguments)] + pub(in crate::runtime) fn landing_holds( + &mut self, + nodes: &[Node], + old_nodes: &[Node], + seen: &[bool], + scene: &Scene, + animated: bool, + reduced_motion: bool, + held: &mut Vec<bool>, + ) -> Vec<(usize, f32)> { + held.clear(); + let mut out = Vec::new(); + if !animated || reduced_motion { + return out; + } + let mut last = paint_tracks::Finder::default(); + for (i, n) in nodes.iter().enumerate() { + if !n.vis.cold.get().is_some_and(|c| c.hold_landing) || !scene.contains(n.id) { + continue; + } + let Some(drawn) = scene.get(n.id, prop::FRAME) else { continue }; + let was = scene.store().target(n.id, prop::FRAME).unwrap_or(drawn); + if (was.w - n.local.w).abs() < 0.5 { + continue; + } + let end = subtree_end(nodes, i); + let present: Vec<usize> = (i + 1..end) + .filter(|&c| { + let cid = nodes[c].id; + nodes[c].parent == Some(i) + && scene.contains(cid) + && !matches!(scene.phase(cid), Some(PresencePhase::Exiting { .. })) + }) + .collect(); + let anchor = present.iter().copied() + .find(|&c| last.find(old_nodes, nodes[c].id).is_some_and(|o| Self::drew(old_nodes, seen, o))) + .or(present.first().copied()); + let jump = anchor.and_then(|c| scene.get(nodes[c].id, prop::FRAME).map(|r| r.x - nodes[c].local.x)).unwrap_or(0.0); + held.resize(nodes.len(), false); + for (j, h) in held.iter_mut().enumerate().take(end).skip(i) { + *h = true; + self.landing_holds.0.insert(nodes[j].id); + } + out.push((i, drawn.x - n.local.x + jump)); + } + out + } + + /// Whether old node `o`, or anything under it, drew in the last build. + fn drew(old_nodes: &[Node], seen: &[bool], o: usize) -> bool { + seen.len() == old_nodes.len() && (o..subtree_end(old_nodes, o)).any(|j| seen[j]) + } +} + +/// One past the last node of `i`'s subtree. +fn subtree_end(nodes: &[Node], i: usize) -> usize { + (i + 1..nodes.len()).find(|&j| nodes[j].parent < Some(i)).unwrap_or(nodes.len()) +} diff --git a/app/vendor/rune/crates/rune/src/runtime/motion/live_check.rs b/app/vendor/rune/crates/rune/src/runtime/motion/live_check.rs new file mode 100644 index 0000000..b84d127 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/motion/live_check.rs @@ -0,0 +1,249 @@ +//! `Tx::live_only` skip accounting and debug stale-view checks. +use super::*; + +/// Seconds after a commit before debug builds check a `Tx::live_only` event (`skip_view`). +#[cfg(debug_assertions)] +const LIVE_ONLY_CHECK: f64 = 0.25; + +impl RuntimeCore { + /// Events whose handler called [`Tx::live_only`] and so didn't re-run the view, since the + /// runtime started. + pub fn live_only_events(&self) -> u64 { + self.frame.live_only_skips + } + + /// Whether debug builds check `Tx::live_only` handlers (on by default): a live-only event + /// a quarter second or more after the last commit still commits, and Rune warns when the + /// view built something else. A test counting commits turns it off. Release builds never + /// check. + pub fn check_live_only(&mut self, on: bool) { + #[cfg(debug_assertions)] + { self.frame.live_only_check = on; } + let _ = on; + } + + /// The stale-view warnings debug builds have printed for `Tx::live_only` handlers, each + /// naming the element and property that differed, so a test can assert there are none. + /// Always empty in release builds. + pub fn live_only_warnings(&self) -> &[String] { + #[cfg(debug_assertions)] + { self.frame.live_only_warnings() } + #[cfg(not(debug_assertions))] + { &[] } + } + + /// An event whose handler called `Tx::live_only`: false, so it doesn't commit, while this + /// frame still latches the live values it set. Debug builds check one such event a quarter + /// second after the last commit by committing anyway (true) and comparing what it built. + pub(in crate::runtime) fn skip_view(&mut self, label: impl std::fmt::Display) -> bool { + #[cfg(debug_assertions)] + if self.frame.live_only_check && self.clock - self.commit.last_commit_clock() >= LIVE_ONLY_CHECK { + if self.frame.live_check.is_none() { self.frame.live_check = Some((label.to_string(), self.view_print())); } + self.frame.live_checks += 1; + self.frame.live.set(); + return true; + } + let _ = label; + self.frame.live_only_skips += 1; + self.frame.live.set(); + false + } + + /// Whether the commit about to run is a live-only check's, which builds what skipping it + /// would have left on screen, so virtual lists keep their mounted rows. + pub(in crate::runtime) fn checking_live_only(&self) -> bool { + #[cfg(debug_assertions)] + { self.frame.live_check.is_some() } + #[cfg(not(debug_assertions))] + { false } + } + + /// What the last commit built: each element's path, layout, colours and text. Live values + /// are left out, since a commit rebuilds them from the view and the next latch sets them. + #[cfg(debug_assertions)] + pub(in crate::runtime) fn view_print(&self) -> ViewPrint { + ViewPrint(self.tree.nodes.iter() + // Retained exits can disappear between commits without a model change. + .filter(|n| !self.is_exiting(n.id)) + .map(|n| { + let live = super::paint_tracks::live_colors(n); + let mut text = n.text.clone(); + if live.text && let Some(t) = &mut text { t.color = Color::TRANSPARENT; } + NodePrint { + path: n.path.clone(), + target: n.target, + fill: (!live.fill).then_some(n.vis.fill), + border: (if live.border { Color::TRANSPARENT } else { n.vis.border() }, n.vis.border_width()), + opacity: n.vis.opacity, + radius: n.vis.radii(), + text, + } + }) + .collect()) + } + + /// After the commit a live-only check forced: warn when the view built something else, as + /// it does when the handler changed state the view reads. Names the first element that + /// differs and what about it, once per handler, element and property. + #[cfg(debug_assertions)] + pub(in crate::runtime) fn compare_live_check(&mut self, check: Option<(String, ViewPrint)>) { + let Some((handler, before)) = check else { return }; + let Some(d) = before.first_difference(&self.view_print()) else { return }; + let head = format!("rune: {handler} called Tx::live_only, but the view built something else after it: {} of {:?}", d.what, d.path); + if self.frame.live_only_warnings.iter().any(|w| w.starts_with(&head)) { return; } + let values = d.values.map(|(was, now)| format!(" went from {was} to {now}")).unwrap_or_default(); + let warning = format!( + "{head}{values}. The handler may have changed state the view reads, which stays stale until another event \ + commits. Set only Live values in a live-only handler; for a time-dependent view, disable this heuristic \ + with check_live_only(false)." + ); + eprintln!("{warning}"); + self.frame.live_only_warnings.push(warning); + } +} + +/// What a commit built, node by node, taken only while a live-only check runs. +#[cfg(debug_assertions)] +pub(crate) struct ViewPrint(Vec<NodePrint>); + +#[cfg(debug_assertions)] +struct NodePrint { + path: String, + target: [f32; 4], + /// `None` while a `Live` sets it. + fill: Option<Color>, + border: (Color, f32), + opacity: f32, + radius: [f32; 4], + text: Option<crate::cold::SharedBox<TextSpec>>, +} + +/// The first element whose build differs: what differs, and the two values where they're short. +#[cfg(debug_assertions)] +#[derive(Debug, PartialEq)] +pub(crate) struct Difference { + pub path: String, + pub what: &'static str, + pub values: Option<(String, String)>, +} + +#[cfg(debug_assertions)] +impl ViewPrint { + pub(crate) fn first_difference(&self, after: &ViewPrint) -> Option<Difference> { + let (a, b) = (&self.0, &after.0); + let has = |list: &[NodePrint], path: &str| list.iter().any(|n| n.path == path); + let node = |what, path: &str| Difference { path: path.to_owned(), what, values: None }; + let (mut i, mut j) = (0, 0); + while i < a.len() && j < b.len() { + let (x, y) = (&a[i], &b[j]); + if x.path == y.path { + if let Some(d) = x.difference(y) { return Some(d); } + i += 1; + j += 1; + } else if !has(b, &x.path) { + return Some(node("removed element", &x.path)); + } else if !has(a, &y.path) { + return Some(node("added element", &y.path)); + } else { + return Some(node("order", &x.path)); + } + } + a.get(i).map(|x| node("removed element", &x.path)).or_else(|| b.get(j).map(|y| node("added element", &y.path))) + } +} + +/// A property's hash, comparing floats by their bits as the check always has. +#[cfg(debug_assertions)] +fn key(f: impl FnOnce(&mut std::hash::DefaultHasher)) -> u64 { + use std::hash::Hasher; + let mut h = std::hash::DefaultHasher::new(); + f(&mut h); + h.finish() +} + +#[cfg(debug_assertions)] +fn bits(xs: &[f32]) -> Vec<u32> { + xs.iter().map(|x| x.to_bits()).collect() +} + +#[cfg(debug_assertions)] +fn rgba(c: Color) -> Vec<u32> { + bits(&[c.r, c.g, c.b, c.a]) +} + +/// `#rrggbbaa` in sRGB. +#[cfg(debug_assertions)] +fn colour(c: Color) -> String { + let byte = |x: f32| (x.clamp(0.0, 1.0) * 255.0).round() as u8; + format!("#{:02x}{:02x}{:02x}{:02x}", byte(srgb_encode(c.r)), byte(srgb_encode(c.g)), byte(srgb_encode(c.b)), byte(c.a)) +} + +#[cfg(debug_assertions)] +fn points(xs: &[f32]) -> String { + let xs: Vec<String> = xs.iter().map(|x| format!("{x:.1}")).collect(); + format!("[{}]", xs.join(", ")) +} + +#[cfg(debug_assertions)] +fn snippet(t: &TextSpec) -> String { + if t.redacted { return "[redacted]".into(); } + if t.cold.live.is_some() { return "(live)".into(); } + const MAX: usize = 40; + match t.content.char_indices().nth(MAX) { + Some((at, _)) => format!("{:?}", format!("{}…", &t.content[..at])), + None => format!("{:?}", t.content), + } +} + +#[cfg(debug_assertions)] +impl NodePrint { + fn difference(&self, now: &NodePrint) -> Option<Difference> { + use std::hash::Hash; + type Part = (&'static str, fn(&NodePrint) -> u64, fn(&NodePrint) -> String); + let parts: [Part; 5] = [ + ("layout rect", |n| key(|h| bits(&n.target).hash(h)), |n| points(&n.target)), + ("fill", |n| key(|h| n.fill.map(rgba).hash(h)), |n| n.fill.map_or("(live)".into(), colour)), + ("border", |n| key(|h| (rgba(n.border.0), n.border.1.to_bits()).hash(h)), |n| format!("{} {:.1}pt", colour(n.border.0), n.border.1)), + ("opacity", |n| key(|h| n.opacity.to_bits().hash(h)), |n| format!("{:.3}", n.opacity)), + ("radius", |n| key(|h| bits(&n.radius).hash(h)), |n| points(&n.radius)), + ]; + let differs = |(what, k, show): &Part| (k(self) != k(now)).then(|| Difference { + path: self.path.clone(), what, values: Some((show(self), show(now))), + }); + if let Some(d) = parts.iter().find_map(differs) { return Some(d); } + let (a, b) = match (&self.text, &now.text) { + (None, None) => return None, + (Some(a), Some(b)) => (a, b), + (a, b) => { + let show = |t: &Option<crate::cold::SharedBox<TextSpec>>| t.as_ref().map_or("no text".into(), |t| snippet(t)); + return Some(Difference { path: self.path.clone(), what: "text", values: Some((show(a), show(b))) }); + } + }; + type TextPart = (&'static str, fn(&TextSpec) -> u64, Option<fn(&TextSpec) -> String>); + let parts: [TextPart; 7] = [ + ("text", |t| key(|h| t.cold.live.is_none().then_some(&t.content).hash(h)), Some(snippet)), + ("text colour", |t| key(|h| rgba(t.color).hash(h)), Some(|t| colour(t.color))), + ("text style", |t| key(|h| bits(&[t.style.size, t.style.weight]).hash(h)), Some(|t| format!("{:.1}pt weight {}", t.style.size, t.style.weight))), + ("pills", |t| key(|h| for p in &t.cold.pills { + (p.start, p.end, p.icon.map(|i| i.name), p.bg, p.fg).hash(h); + p.bare.as_ref().map(|b| (b.size.to_bits(), b.gap.to_bits(), b.radius.to_bits(), b.image.as_ref().map(crate::pixels::Pixels::signature), b.replace.map(|r| bits(&[r.width, r.ascent, r.descent, r.bleed])))).hash(h); + }), None), + ("rings", |t| key(|h| for &(a, b, c, w) in &t.cold.rings { (a, b, c, w.to_bits()).hash(h) }), None), + ("strikes", |t| key(|h| t.cold.strikes.hash(h)), None), + ("highlights", |t| key(|h| for hl in &t.cold.highlights { + (hl.start, hl.end, hl.bg, hl.fg, hl.pad.to_bits(), &hl.key, hl.ring.map(|(c, w)| (c, w.to_bits()))).hash(h) + }), None), + ]; + parts.iter().find(|(_, k, _)| k(a) != k(b)).map(|&(what, _, show)| Difference { + path: self.path.clone(), + what, + values: show.map(|s| (s(a), s(b))), + }) + } +} + +/// Folds one handler's `Tx::live_only` into its event's: live-only when every handler that +/// took the event said so. +pub(crate) fn fold_live(live: &mut Option<bool>, took: bool, one: &Tx) { + if took { *live = Some(live.unwrap_or(true) && one.live_only); } +} diff --git a/app/vendor/rune/crates/rune/src/runtime/motion/live_latch.rs b/app/vendor/rune/crates/rune/src/runtime/motion/live_latch.rs new file mode 100644 index 0000000..c3bce71 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/motion/live_latch.rs @@ -0,0 +1,396 @@ +//! Live values bound to elements: subscribing to their sources, the wake lane, and latching +//! what they publish into the scene each frame. +use super::*; +use std::sync::atomic::Ordering; + +/// Whether a window has live work, as one state: hidden or visible, whether a value waits for the +/// next frame, and whether a frame is reading the sources. +/// +/// The shared [`crate::live::Wake`] is the other thread's half: publication and visibility +/// changes share an atomic so only one writer wakes the host. [`LiveLane`] owns that wake +/// beside this state, and reads it only when a step asks +/// (at the frame boundary), so the state never has to be written by another thread. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum LiveWake { + /// Hidden: no frame latches or draws. `dirty` is work kept for the frame after showing. + Hidden { dirty: bool }, + /// Visible, and nothing waits. + Idle, + /// Visible, with a value waiting for the next frame. + Pending, + /// A frame has taken the shared wake and is reading what it published. `dirty` is work that + /// landed after the take, or a value still moving, kept for the next frame. + Latching { dirty: bool }, +} + +/// Something that changes whether a window has live work to do. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum LiveEvent { + /// The window showed or hid (`Runtime::set_live_visible`). + Show, + Hide, + /// A commit re-derived the bound sources; `sampled` says the scene binds a value to read. + Subscribe { sampled: bool }, + /// A prune re-derived them; `keep` is whether a value was waiting before it. + Prune { keep: bool }, + /// A live-only event published without a commit. + Set, + /// The frame is reading the sources now, after `LiveLane::latch_begin` found work. + LatchBegin, + /// The latch read the sources; `active` says one is still moving. + LatchEnd { active: bool }, +} + +impl LiveWake { + /// Work kept for a later frame. + fn dirty(self) -> bool { + match self { + LiveWake::Hidden { dirty } | LiveWake::Latching { dirty } => dirty, + LiveWake::Pending => true, + LiveWake::Idle => false, + } + } + + /// One transition. Only a frame with work to do reaches this; the empty and hidden fast + /// paths return first. Returns the next state and the event's answer: whether the latch + /// should read, or whether a read value is still moving. + pub(crate) fn step(self, event: LiveEvent) -> (LiveWake, bool) { + use LiveWake::{Hidden, Idle, Latching, Pending}; + match (self, event) { + // A hidden window keeps a value for its first visible frame. + (Hidden { dirty }, LiveEvent::Show) => (if dirty { Pending } else { Idle }, dirty), + (_, LiveEvent::Show) => (self, self.dirty()), + (s, LiveEvent::Hide) => (Hidden { dirty: s.dirty() }, false), + // A commit resets the waiting bit to whether the scene bound a value. + (Hidden { .. }, LiveEvent::Subscribe { sampled }) => (Hidden { dirty: sampled }, sampled), + (_, LiveEvent::Subscribe { sampled }) => (if sampled { Pending } else { Idle }, sampled), + // A prune keeps only work the state already had. + (s, LiveEvent::Prune { keep }) => { + let dirty = s.dirty() && keep; + let next = match s { + Hidden { .. } => Hidden { dirty }, + _ if dirty => Pending, + _ => Idle, + }; + (next, dirty) + } + // A live-only event published a value without a commit: one is owed next frame. + (Hidden { .. }, LiveEvent::Set) => (Hidden { dirty: true }, true), + (_, LiveEvent::Set) => (Pending, true), + // The frame reads what it took; a hidden window or one with no sources never gets here. + (_, LiveEvent::LatchBegin) => (Latching { dirty: false }, true), + // A value still moving after the read keeps the next frame due. + (Hidden { dirty }, LiveEvent::LatchEnd { active }) => (Hidden { dirty: dirty || active }, active), + (_, LiveEvent::LatchEnd { active }) => (if active { Pending } else { Idle }, active), + } + } +} + +/// A window's live wake: the state above and the shared [`crate::live::Wake`] publishers notify. +pub(crate) struct LiveLane { + wake: Arc<crate::live::Wake>, + state: LiveWake, +} + +impl LiveLane { + pub(crate) fn new(waker: Waker) -> Self { + Self { wake: crate::live::Wake::new(waker), state: LiveWake::Idle } + } + + /// The shared wake, for a source to subscribe to and a video to notify. + pub(crate) fn waker(&self) -> &Arc<crate::live::Wake> { &self.wake } + + /// Install a new wake lane, keeping the visibility and the work the last one held. + pub(crate) fn replace_waker(&mut self, waker: Waker) { + self.wake = crate::live::Wake::new(waker); + self.wake.visible(self.visible()); + } + + pub(crate) fn visible(&self) -> bool { !matches!(self.state, LiveWake::Hidden { .. }) } + + pub(crate) fn dirty(&self) -> bool { self.state.dirty() } + + /// Whether a value waits for this window. Hidden windows keep their wake for show, and a + /// step's own dirty bit is checked before the shared atomic, as published values always were. + pub(crate) fn pending(&self) -> bool { + match self.state { + LiveWake::Hidden { .. } => false, + LiveWake::Pending => true, + LiveWake::Idle => self.wake.visible_pending(), + LiveWake::Latching { dirty } => dirty || self.wake.visible_pending(), + } + } + + pub(crate) fn set_visible(&mut self, visible: bool) { + self.wake.visible(visible); + self.apply(if visible { LiveEvent::Show } else { LiveEvent::Hide }); + } + + /// A source published on another thread. + pub(crate) fn publish(&self) { self.wake.notify(); } + + pub(crate) fn subscribed(&mut self, sampled: bool) { self.apply(LiveEvent::Subscribe { sampled }); } + + pub(crate) fn pruned(&mut self, keep: bool) { self.apply(LiveEvent::Prune { keep }); } + + /// A live-only event published a value without a commit. + pub(crate) fn set(&mut self) { self.apply(LiveEvent::Set); } + + /// Take the shared wake for this frame; a hidden window keeps it for show. The take never + /// changes what the UI thread holds, so a visible frame with nothing pending does no work + /// beyond dev's visibility test and swap. + pub(crate) fn take(&mut self) -> bool { + if !self.visible() { return false; } + self.wake.take_visible() + } + + /// Whether the frame should read its sources now. The hidden, source-less and clean cases + /// return before any transition, as an unpending frame always did. + pub(crate) fn latch_begin(&mut self, can: bool, has_subs: bool) -> bool { + if !self.visible() || !has_subs || (!can && !self.state.dirty()) { return false; } + self.apply1(LiveEvent::LatchBegin) + } + + /// Whether a read value is still moving. + pub(crate) fn latch_end(&mut self, active: bool) -> bool { + self.apply1(LiveEvent::LatchEnd { active }) + } + + fn apply(&mut self, event: LiveEvent) { let (state, _) = self.state.step(event); self.state = state; } + + fn apply1(&mut self, event: LiveEvent) -> bool { + let (state, answer) = self.state.step(event); + self.state = state; + answer + } +} + +impl timer_wake::FrameState { + pub(in crate::runtime) fn subscribe_live(&mut self, nodes: &mut [Node], scene: &Scene, clock: f64) { + for node in nodes.iter_mut() { + if let Some(cold) = node.cold.get_mut_if_some() { + for bound in &mut cold.live { bound.attach(&self.live_clock, clock); } + } + } + for sub in &self.live_subscriptions { sub.active.store(false, Ordering::Release); } + // Pixels only wake: each frame's build uploads their current image, so unlike bound + // values they leave nothing to sample on a later visible frame. + let mut sampled = false; + for node in nodes.iter() { + let text = node.text.as_ref().and_then(|t| t.cold.live.as_ref()).map(|t| &t.source); + let pixels = node.vis.cold.get().and_then(|v| v.pixels.as_ref()).map(|p| &p.source); + let has_live = node.cold.get().is_some_and(|c| !c.live.is_empty()); + if !has_live && text.is_none() && pixels.is_none() { + continue; + } + // An element removed outright leaves the scene now but `nodes` only at the next + // prune. Exiting elements and their children are still drawn, so their text and + // pixels keep waking until the exit ends (commit already dropped their bindings). + if !scene.contains(node.id) { continue; } + sampled |= text.is_some() || has_live; + for source in node.live.iter().map(|b| &b.source).chain(text).chain(pixels) { + if let Some(sub) = self.live_subscriptions.iter().find(|s| s.source_id == source.id()) { + sub.active.store(true, Ordering::Release); + } else { + self.live_subscriptions.push(source.subscribe(self.live.waker())); + } + } + } + self.live_subscriptions.retain(|s| s.active.load(Ordering::Acquire)); + self.live.subscribed(sampled); + } + + pub(in crate::runtime) fn latch_live( + &mut self, + nodes: &mut [Node], + scene: &mut Scene, + text: &mut TextSystem, + scale: f32, + clock: f64, + pending: bool, + ) -> bool { + if !self.live.latch_begin(pending, !self.live_subscriptions.is_empty()) { return false; } + let mut active = false; + for node in nodes { + if let Some(spec) = &mut node.text + && let Some(live) = &spec.cold.live + { + let seen = &mut node.cold.live_text_seen; + if let Some(live_text) = live.read(seen) && spec.source_text() != &*live_text { + spec.replace_content(live_text.to_string()); + spec.apply_case(); + node.text_layout = Some(TextLayout::Single(text.layout_live(&spec.content, spec.style, scale))); + } + } + let Some(cold) = node.cold.get_mut_if_some() else { continue }; + for bound in &mut cold.live { + let (op, active_now) = bound.read(&self.live_clock, clock); + active |= active_now; + let Some(op) = op else { continue }; + let (enter, leave) = (bound.spring, bound.rest_spring); + use crate::live::{LatchOp, LiveValue, Property}; + fn apply<T: rune_motion::Animatable + Copy>( + scene: &mut Scene, + id: NodeId, + prop: Prop<T>, + enter: Option<Spring>, + leave: Option<Spring>, + decode: impl Fn(u128) -> T, + op: LatchOp, + choose_leave: impl Fn(Option<T>, T) -> bool, + ) { + match op { + LatchOp::Snap(bits) => scene.set(id, prop, decode(bits)), + LatchOp::Set(bits) => { + let v = decode(bits); + let spring = if choose_leave(scene.get(id, prop), v) { leave.or(enter) } else { enter }; + match spring { + Some(s) => scene.animate(id, prop, v, s), + None => scene.set(id, prop, v), + } + } + LatchOp::Pulse { active, rest, hold } => { + let rest_v = decode(rest); + let Some(enter_s) = enter else { + scene.set(id, prop, rest_v); + return; + }; + let active_v = decode(active); + let leave_s = leave.unwrap_or(enter_s); + scene.animate(id, prop, active_v, enter_s); + scene.animate(id, prop, rest_v, rune_motion::Anim { delay: (hold as f32).max(1e-4), ..leave_s.into() }); + } + } + } + match bound.property { + Property::Opacity => apply( + scene, node.id, prop::OPACITY, enter, leave, + |b| f32::decode(b).clamp(0.0, 1.0), op, + |cur, to| cur.is_some_and(|c| to < c), + ), + Property::Blur => apply( + scene, node.id, prop::BLUR, enter, leave, + |b| f32::decode(b).max(0.0), op, + |cur, to| cur.is_some_and(|c| to < c), + ), + Property::Scale => apply( + scene, node.id, prop::SCALE, enter, leave, + |b| f32::decode(b).max(0.0), op, + |cur, to| cur.is_some_and(|c| to < c), + ), + Property::Offset => apply( + scene, node.id, prop::OFFSET, enter, leave, + |b| { let [x, y] = <[f32; 2]>::decode(b); rune_motion::Vec2::new(x, y) }, op, + |_, _| false, + ), + Property::Trim => apply( + scene, node.id, P_TRIM, enter, leave, + |b| { let [s, e] = <[f32; 2]>::decode(b); rune_motion::Vec2::new(s, e) }, op, + |_, _| false, + ), + Property::Fill | Property::TextColor | Property::Border | Property::Shadow | Property::GradientTop | Property::GradientBottom => { + let bits = match op { + LatchOp::Snap(b) | LatchOp::Set(b) | LatchOp::Pulse { rest: b, .. } => b, + }; + // The renderer uses the exact authored colour after its track settles. + let c = Color::decode(bits); + let p = match bound.property { + Property::Fill => { node.vis.fill = c; P_FILL } + Property::TextColor => { + if let Some(spec) = &mut node.text { if spec.color != c { spec.color = c; } } + else if node.vis.icon.is_some_and(|(_, ic)| ic != c) && let Some((_, ic)) = &mut node.vis.cold_mut().icon { *ic = c; } + P_TEXT + } + Property::Border => { node.vis.set_border_color(c); P_BORDER } + Property::Shadow => { + if node.vis.shadows.first().is_some_and(|s| s.color != c) { node.vis.cold_mut().shadows[0].color = c; } + P_SHADOWS[0] + } + _ => { + let k = usize::from(bound.property == Property::GradientBottom); + if node.vis.gradient.as_deref().is_some_and(|g| g[k] != c) + && let Some(g) = node.vis.cold_mut().gradient.as_deref_mut() { g[k] = c; } + P_GRADIENT[k] + } + }; + apply(scene, node.id, p, enter, leave, Color::decode, op, |_, _| false); + } + Property::Rect => { + let frame_of = |b| { + let [x, y, w, h] = <[f32; 4]>::decode(b); + MRect::new(x, y, w.max(0.0), h.max(0.0)) + }; + match (op, enter) { + (LatchOp::Snap(b) | LatchOp::Pulse { rest: b, .. }, _) | (LatchOp::Set(b), None) => { + scene.land_frame(node.id, frame_of(b)); + } + (LatchOp::Set(b), Some(spring)) => { + scene.set_frame(node.id, frame_of(b), LayoutAnim::new(spring)); + } + } + } + } + } + } + self.live.latch_end(active) + } +} + +impl RuntimeCore { + /// The window's live wake: another thread tells it to get the window's next frame drawn. + #[inline] + pub(crate) fn live_wake(&self) -> &Arc<crate::live::Wake> { self.frame.live.waker() } + + /// Install before the first frame. Live updates use this separate coalesced wake lane. + pub(crate) fn set_live_waker(&mut self, waker: Waker) { + for sub in &self.frame.live_subscriptions { sub.active.store(false, Ordering::Release); } + self.frame.live_subscriptions.clear(); + self.frame.live.replace_waker(waker); + self.subscribe_live(); + } + + pub(crate) fn set_live_visible(&mut self, app: &mut dyn AppDriver, visible: bool) { + let changed = visible != self.frame.live.visible(); + self.frame.live.set_visible(visible); + if !visible { self.motion.clear_loop_wake(); } + // The window's own setup shows and hides it before the first frame; the app hears the + // changes after that (`App::on_visibility`). + if changed && self.commit.commits > 0 && app.has_on_visibility() { + let (mut one, stall) = self.begin_update(app); + app.on_visibility(visible, &mut one); + self.finish_update(app, stall, one, true, false); + } + } + /// What asks for this runtime's next frame as a live value does, from any thread. + #[inline] + pub(crate) fn live_notifier(&self) -> impl FnOnce() + Send + 'static { + let wake = self.frame.live.waker().clone(); + move || wake.notify() + } + #[inline] + pub(crate) fn live_visible(&self) -> bool { self.frame.live.visible() } + #[inline] + pub fn live_pending(&self) -> bool { + self.frame.live.pending() + } + + #[inline] + pub(in crate::runtime) fn subscribe_live(&mut self) { + self.frame.subscribe_live(&mut self.tree.nodes, &self.scene, self.clock); + } + + /// Clear before this frame reads anything a source publishes (a picture's size for layout, + /// a bound value): a concurrent publication either lands in this frame or keeps a wake for + /// the next. Never clear after reading (lost wake race). Hidden hosts keep the wake for show. + #[inline] + pub(in crate::runtime) fn take_live_wake(&mut self) -> bool { self.frame.live.take() } + + #[inline] + pub(in crate::runtime) fn latch_live(&mut self, pending: bool) -> bool { + self.frame.latch_live(&mut self.tree.nodes, &mut self.scene, &mut self.text, self.env.scale, self.clock, pending) + } +} + +#[cfg(test)] +#[path = "live_latch_tests.rs"] +mod tests; diff --git a/app/vendor/rune/crates/rune/src/runtime/motion/live_latch_tests.rs b/app/vendor/rune/crates/rune/src/runtime/motion/live_latch_tests.rs new file mode 100644 index 0000000..51c2ff3 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/motion/live_latch_tests.rs @@ -0,0 +1,325 @@ +//! The live wake against a literal transcription of its origin/dev logic: `surface_visible`, +//! `live_dirty` and the shared `Wake`'s `pending` atomic, with dev's branches in dev's order. +//! The walk drives the production lane one step at a time and lets the publishing thread run +//! between every step, then compares what a window sees after each: whether it is visible, +//! whether a value waits, whether a take found one, whether a latch read, and how often the +//! wake reached the host. A lost or doubled wake is a failed assertion, not a missed frame. +use super::*; +use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; + +/// Origin/dev's shared wake: `pending` set by a publisher, `visible` by the host, and a callback +/// that fires once when a hidden host with a wake shows. +struct DevWake { + pending: AtomicBool, + visible: AtomicBool, + fired: Arc<AtomicUsize>, +} + +impl DevWake { + fn new(fired: Arc<AtomicUsize>) -> Self { + Self { pending: AtomicBool::new(false), visible: AtomicBool::new(true), fired } + } + fn visible(&self, visible: bool) { + let was = self.visible.swap(visible, Ordering::AcqRel); + if visible && !was && self.pending.load(Ordering::Acquire) { self.fired.fetch_add(1, Ordering::SeqCst); } + } + fn notify(&self) { + if !self.pending.swap(true, Ordering::AcqRel) && self.visible.load(Ordering::Acquire) { + self.fired.fetch_add(1, Ordering::SeqCst); + } + } +} + +/// Origin/dev's three gates for "may this window wake", transcribed. +struct Dev { + visible: bool, + dirty: bool, + subs: bool, + wake: DevWake, +} + +impl Dev { + fn new(fired: Arc<AtomicUsize>) -> Self { + Self { visible: true, dirty: false, subs: true, wake: DevWake::new(fired) } + } + fn set_visible(&mut self, visible: bool) { + self.wake.visible(visible); + self.visible = visible; + } + fn publish(&self) { self.wake.notify(); } + fn pending(&self) -> bool { self.visible && (self.dirty || self.wake.pending.load(Ordering::Acquire)) } + fn subscribe(&mut self, sampled: bool) { self.dirty = sampled; } + fn prune(&mut self, sampled: bool) { + let dirty = self.dirty; + self.subscribe(sampled); + self.dirty &= dirty; + } + fn set(&mut self) { self.dirty = true; } + fn take(&mut self) -> bool { self.visible && self.wake.pending.swap(false, Ordering::AcqRel) } + fn latch_begin(&mut self, pending: bool) -> bool { + if !self.visible || !self.subs { return false; } + if !pending && !self.dirty { return false; } + self.dirty = false; + true + } + fn latch_end(&mut self, active: bool) -> bool { + self.dirty |= active; + self.dirty + } +} + +#[derive(Clone, Copy, Debug)] +enum Ev { + Publish, + Show, + Hide, + Subscribe(bool), + Prune(bool), + Set, + Take, + LatchBegin, + LatchEnd(bool), + Subs(bool), +} + +/// Run one sequence through both, comparing after every step. +fn walk(events: &[Ev]) { + let fired_dev = Arc::new(AtomicUsize::new(0)); + let fired_new = Arc::new(AtomicUsize::new(0)); + let mut dev = Dev::new(fired_dev.clone()); + let mut new = LiveLane::new({ + let fired = fired_new.clone(); + Arc::new(move || { fired.fetch_add(1, Ordering::SeqCst); }) + }); + let (mut woke_dev, mut woke_new) = (false, false); + let (mut reading_dev, mut reading_new) = (false, false); + for (i, &event) in events.iter().enumerate() { + let (answer_dev, answer_new) = match event { + Ev::Publish => { dev.publish(); new.publish(); (None, None) } + Ev::Show => { dev.set_visible(true); new.set_visible(true); (None, None) } + Ev::Hide => { dev.set_visible(false); new.set_visible(false); (None, None) } + Ev::Subscribe(sampled) => { dev.subscribe(sampled); new.subscribed(sampled); (None, None) } + Ev::Prune(sampled) => { + let keep_dev = dev.dirty; + dev.prune(sampled); + let keep_new = new.dirty(); + new.subscribed(sampled); + new.pruned(keep_new); + debug_assert_eq!(keep_dev, keep_new); + (None, None) + } + Ev::Set => { dev.set(); new.set(); (None, None) } + Ev::Take => { + let (a, b) = (dev.take(), new.take()); + woke_dev |= a; + woke_new |= b; + (Some(a), Some(b)) + } + Ev::LatchBegin => { + let a = dev.latch_begin(woke_dev || dev.pending()); + let b = new.latch_begin(woke_new || new.pending(), dev.subs); + reading_dev = a; + reading_new = b; + woke_dev = false; + woke_new = false; + (Some(a), Some(b)) + } + Ev::LatchEnd(active) => { + let a = reading_dev.then(|| dev.latch_end(active)); + let b = reading_new.then(|| new.latch_end(active)); + (a, b) + } + Ev::Subs(has) => { dev.subs = has; (None, None) } + }; + assert_eq!(answer_dev, answer_new, "answer differed after {event:?} at step {i} of {events:?}"); + assert_eq!(dev.visible, new.visible(), "visible differed after {event:?} at step {i} of {events:?}"); + assert_eq!(dev.pending(), new.pending(), "pending differed after {event:?} at step {i} of {events:?}"); + assert_eq!( + fired_dev.load(Ordering::SeqCst), + fired_new.load(Ordering::SeqCst), + "wake count differed after {event:?} at step {i} of {events:?}" + ); + } +} + +/// Every sequence up to length 6 of the events a frame, a commit, a host and a publisher send. +/// Length 6 reaches every interleaving the frame has: a publish before, between or after a +/// take and a latch, a show or hide around either, and two publishes before one frame. +#[test] +fn every_short_sequence_matches_dev() { + const EVENTS: [Ev; 11] = [ + Ev::Publish, + Ev::Show, + Ev::Hide, + Ev::Subscribe(true), + Ev::Subscribe(false), + Ev::Prune(true), + Ev::Prune(false), + Ev::Set, + Ev::Take, + Ev::LatchBegin, + Ev::LatchEnd(true), + ]; + walk(&[]); + let n = EVENTS.len(); + for len in 1..=6 { + let mut sequence = vec![Ev::Publish; len]; + for mut code in 0..n.pow(len as u32) { + for slot in &mut sequence { + *slot = EVENTS[code % n]; + code /= n; + } + walk(&sequence); + } + } +} + +/// A publish that lands while the frame reads keeps a wake for the next frame; the atomic is +/// taken before the read and never cleared after it. +#[test] +fn a_publish_while_the_frame_reads_survives() { + let mut lane = LiveLane::new(Arc::new(|| {})); + lane.subscribed(true); + lane.publish(); + assert!(lane.take(), "the frame takes the publish"); + lane.publish(); + assert!(lane.latch_begin(true, true), "the frame reads"); + assert!(!lane.latch_end(false), "nothing is still moving"); + assert!(lane.pending(), "the publish that landed during the read keeps a wake"); + assert!(lane.take(), "and the next frame takes exactly it"); + assert!(!lane.pending()); +} + +/// A hidden window keeps one coalesced wake for show, and draws nothing in between. +#[test] +fn a_hidden_window_keeps_one_wake_for_show() { + let fired = Arc::new(AtomicUsize::new(0)); + let mut lane = LiveLane::new({ + let fired = fired.clone(); + Arc::new(move || { fired.fetch_add(1, Ordering::SeqCst); }) + }); + lane.set_visible(false); + lane.publish(); + lane.publish(); + assert_eq!(fired.load(Ordering::SeqCst), 0, "a hidden window is not woken"); + assert!(!lane.pending(), "a hidden window has nothing to draw"); + assert!(!lane.take(), "and the take leaves the wake for show"); + assert!(!lane.latch_begin(true, true), "so no latch runs"); + lane.set_visible(true); + assert_eq!(fired.load(Ordering::SeqCst), 1, "showing delivers the one coalesced wake"); + assert!(lane.take()); + assert!(!lane.take(), "and it is delivered once"); + assert_eq!(fired.load(Ordering::SeqCst), 1); +} + +/// Hiding and showing between a publish and its frame neither loses the wake nor doubles it. +#[test] +fn hiding_and_showing_between_a_publish_and_its_frame_keeps_one_wake() { + let fired = Arc::new(AtomicUsize::new(0)); + let mut lane = LiveLane::new({ + let fired = fired.clone(); + Arc::new(move || { fired.fetch_add(1, Ordering::SeqCst); }) + }); + lane.publish(); + assert_eq!(fired.load(Ordering::SeqCst), 1); + lane.set_visible(false); + lane.set_visible(true); + assert_eq!(fired.load(Ordering::SeqCst), 2, "the show finds the wake still waiting"); + assert!(lane.take()); + assert!(!lane.take()); + assert_eq!(fired.load(Ordering::SeqCst), 2); +} + +/// Two publishes before one frame coalesce into one wake and one take. +#[test] +fn two_publishes_before_one_frame_coalesce() { + let fired = Arc::new(AtomicUsize::new(0)); + let mut lane = LiveLane::new({ + let fired = fired.clone(); + Arc::new(move || { fired.fetch_add(1, Ordering::SeqCst); }) + }); + lane.publish(); + lane.publish(); + assert_eq!(fired.load(Ordering::SeqCst), 1); + assert!(lane.take()); + assert!(!lane.take()); + assert_eq!(fired.load(Ordering::SeqCst), 1); +} + +/// A value an app thread publishes still wakes an idle window through the real `Live` source, +/// and a hidden one holds that wake until it shows. +#[test] +fn an_app_thread_set_wakes_an_idle_window() { + let fired = Arc::new(AtomicUsize::new(0)); + let mut lane = LiveLane::new({ + let fired = fired.clone(); + Arc::new(move || { fired.fetch_add(1, Ordering::SeqCst); }) + }); + let value = crate::live::Live::new(0.0f32); + let _sub = value.source.subscribe(lane.waker()); + assert!(!lane.pending()); + assert!(value.set(1.0)); + assert_eq!(fired.load(Ordering::SeqCst), 1, "an idle window is woken"); + assert!(lane.pending()); + assert!(lane.take()); + + lane.set_visible(false); + assert!(value.set(2.0)); + assert_eq!(fired.load(Ordering::SeqCst), 1, "a hidden window is not"); + assert!(!lane.pending()); + lane.set_visible(true); + assert_eq!(fired.load(Ordering::SeqCst), 2, "showing delivers the held wake"); + assert!(lane.take()); + assert!(!lane.take(), "once"); + assert_eq!(fired.load(Ordering::SeqCst), 2); +} + +/// A visible frame with nothing pending does dev's one atomic swap and nothing else: the state is +/// not stepped or written. Only a frame with work goes through `step`. +#[test] +fn an_empty_frame_leaves_the_state_untouched() { + let mut lane = LiveLane::new(Arc::new(|| {})); + assert_eq!(lane.state, LiveWake::Idle); + assert!(!lane.take(), "nothing published"); + assert_eq!(lane.state, LiveWake::Idle, "a take with nothing pending changes nothing"); + assert!(!lane.latch_begin(false, true), "nothing to read"); + assert_eq!(lane.state, LiveWake::Idle, "a clean latch changes nothing"); + + // The scroll path's second latch, with nothing left to read. + lane.state = LiveWake::Latching { dirty: false }; + assert!(!lane.latch_begin(false, true)); + assert_eq!(lane.state, LiveWake::Latching { dirty: false }); + + // A take with work waiting records nothing either: the work is the dirty bit it keeps. + lane.state = LiveWake::Pending; + assert!(!lane.take()); + assert_eq!(lane.state, LiveWake::Pending); + + // No bound sources is dev's early return, before any transition. + assert!(!lane.latch_begin(true, false)); + assert_eq!(lane.state, LiveWake::Pending); +} + +/// A live-only event without a commit keeps the frame due, and a commit that samples a value +/// keeps it due until the latch reads. +#[test] +fn a_live_only_set_keeps_the_frame_due() { + let mut lane = LiveLane::new(Arc::new(|| {})); + assert!(!lane.pending()); + lane.set(); + assert!(lane.pending(), "a live-only publish asks for a frame"); + assert!(!lane.take(), "with no shared wake"); + assert!(lane.latch_begin(false, true), "but the latch still reads"); + assert!(!lane.latch_end(false)); + assert!(!lane.pending(), "and rests once read"); +} + +/// A window with no bound sources never reads, and a hidden one never draws. +#[test] +fn nothing_reads_without_sources_or_while_hidden() { + let mut lane = LiveLane::new(Arc::new(|| {})); + lane.subscribed(true); + assert!(!lane.latch_begin(true, false), "no sources, no read"); + lane.set_visible(false); + assert!(!lane.latch_begin(true, true), "hidden, no read"); +} diff --git a/app/vendor/rune/crates/rune/src/runtime/motion/loop_clock.rs b/app/vendor/rune/crates/rune/src/runtime/motion/loop_clock.rs new file mode 100644 index 0000000..b3e02fc --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/motion/loop_clock.rs @@ -0,0 +1,86 @@ +//! Loops keep the app's time. Animation time drops most of what a covered, hidden, idle or +//! suspended window spends, so motion never teleports. A periodic loop is a rhythm, though, +//! often one an app keys to its own clock with `LoopSpec::delay`, and two loops started at +//! different times fell out of step by whatever animation time dropped between their starts: +//! a shimmer's window and the bright copy that slides back inside it stopped cancelling, and +//! the copy sat off its label. Every periodic loop gets the time animation time dropped +//! before any commit can start another, and a frame's commits start loops at the frame's +//! presented time, so loops whose delays come from the app clock stay in step however late +//! each mounts. +use super::*; + +/// Below this, a difference between the clocks is a frame's timing jitter, not dropped time. +const JITTER: f64 = 1.0 / 30.0; + +#[derive(Default)] +pub(in crate::runtime) struct LoopClock { + /// App clock and presented animation time when the loops last caught up. + last: Option<(f64, f64)>, + /// App time (times the time scale) animation time hasn't seen yet. + owed: f64, + /// The step this frame still takes after its commits; loops they start begin after it. + lead: f64, +} + +impl tracks::MotionState { + /// Before a frame's commits, which then step `dt` more. + #[inline] + pub(in crate::runtime) fn keep_loops_on_clock(&mut self, scene: &Scene, t: f64, clock: f64, time_scale: f32, dt: f64) { + self.loop_clock.lead = dt * f64::from(time_scale); + self.catch_loops_up(scene, t, clock, time_scale); + } + + /// Gives running loops the app time animation time dropped since they last caught up. + /// Commits call it too, so a loop a hidden wake starts isn't given time from before it. + pub(in crate::runtime) fn catch_loops_up(&mut self, scene: &Scene, t: f64, clock: f64, time_scale: f32) { + let k = f64::from(time_scale); + let end = t + self.loop_clock.lead; + let c = &mut self.loop_clock; + if let Some((last_clock, last_t)) = c.last { + c.owed = (c.owed + (clock - last_clock) * k - (end - last_t)).max(-JITTER); + } + c.last = Some((clock, end)); + if c.owed <= JITTER { return; } + let owed = std::mem::take(&mut c.owed); + for (id, track) in &mut self.loops { + track.advance(owed * f64::from(scene.store().node_time_scale(*id))); + } + } + + /// Where a loop a commit starts at node time `t` begins. + #[inline] + pub(in crate::runtime) fn loop_start(&self, scene: &Scene, id: NodeId, t: f64) -> f64 { + t + self.loop_clock.lead * f64::from(scene.store().node_time_scale(id)) + } + + /// The frame's step: commits after it start their loops where they are. + #[inline] + pub(in crate::runtime) fn loops_stepped(&mut self) { + self.loop_clock.lead = 0.0; + } + + /// Runs each of `nodes` from `scales.len()` on at its `El::time_scale` times its parent's, + /// pushing the products onto `scales`. `exiting` nodes drop their own factor, which the app + /// can no longer change, and follow their parent's. A node whose clock changes keeps its + /// place: the store rebases its tracks, and its reveal words and loop shift by the same amount. + pub(in crate::runtime) fn sync_time_scales(&mut self, scene: &mut Scene, nodes: &[Node], scales: &mut Vec<f32>, exiting: bool) { + for n in &nodes[scales.len()..] { + let own = if exiting { 1.0 } else { n.time_scale }; + let k = own * n.parent.and_then(|p| scales.get(p).copied()).unwrap_or(1.0); + scales.push(k); + // Unmounted at once this commit: its clock went with it. (Present nodes not yet in + // the scene get theirs now, before their first tracks.) + if exiting && !scene.contains(n.id) { continue; } + let store = scene.store_mut(); + let before = store.node_time(n.id); + store.set_node_time_scale(n.id, k); + let shift = store.node_time(n.id) - before; + if shift != 0.0 { + if let Some(st) = self.reveals.get_mut(&n.id) { + st.step(RevealEvent::Shift { shift }); + } + if let Some(l) = self.loops.get_mut(&n.id) { l.shift(shift); } + } + } + } +} diff --git a/app/vendor/rune/crates/rune/src/runtime/motion/motion_elements.rs b/app/vendor/rune/crates/rune/src/runtime/motion/motion_elements.rs new file mode 100644 index 0000000..572a2ab --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/motion/motion_elements.rs @@ -0,0 +1,159 @@ +//! `Runtime::motion_elements`: the part of [`ElementInfo`] a frame-by-frame motion watcher reads, +//! cheap enough to take on every drawn frame. No strings are copied (a watcher caches paths by +//! [`NodeId`] through [`Runtime::element_path`]), text is a hash, and the flags an element takes +//! from its ancestors come from one pass down the tree instead of a walk up from each element. +use super::*; + +/// One presented element as [`Runtime::motion_elements`] reports it. +#[non_exhaustive] +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct MotionElement { + pub id: NodeId, + /// Index into the same list (`out`) of its nearest presented ancestor, as + /// [`ElementInfo::parent`] is into [`Runtime::elements`]. Always less than its own index. + pub parent: Option<u32>, + /// Drawn `[x, y, w, h]` in points, as [`ElementInfo::rect`]. + pub rect: [f32; 4], + /// The part inside its ancestors' clips, as [`ElementInfo::visible`]. + pub visible: [f32; 4], + pub opacity: f32, + pub scale: f32, + /// [`ElementInfo::loop_phase`], NaN when it has no loop. + pub loop_phase: f32, + /// A hash of its words: their length and first and last 64 bytes, so it costs the same for + /// any length. 0 for none and for secure text. + pub text_hash: u64, + pub flags: u16, +} + +impl MotionElement { + /// It or an ancestor is leaving ([`ElementInfo::exiting`]). + pub const EXITING: u16 = 1; + /// An ancestor scroll is being scrolled ([`ElementInfo::scrolling`]). + pub const SCROLLING: u16 = 2; + /// [`ElementInfo::in_growing_row`] or [`ElementInfo::revealing`]. + pub const GROWING: u16 = 4; + /// [`ElementInfo::live_intent`] is non-zero. + pub const LIVE: u16 = 8; + /// [`ElementInfo::virtual_extent`]. + pub const VIRTUAL: u16 = 16; + /// Its role is `"text"`. + pub const TEXT: u16 = 32; + pub const LOOP: u16 = 64; + /// It has a visible fill or words. + pub const PAINTS: u16 = 128; + + /// Whether it has `flag`, one of the consts above. + pub fn is(&self, flag: u16) -> bool { + self.flags & flag != 0 + } +} + +fn text_hash(text: &str) -> u64 { + let b = text.as_bytes(); + if b.is_empty() { return 0; } + let mut h = 0xcbf2_9ce4_8422_2325 ^ b.len() as u64; + let mut mix = |part: &[u8]| { + for w in part.chunks(8) { + let mut v = [0; 8]; + v[..w.len()].copy_from_slice(w); + h = (h ^ u64::from_le_bytes(v)).wrapping_mul(0x9e37_79b9_7f4a_7c15).rotate_left(29); + } + }; + let head = b.len().min(64); + mix(&b[..head]); + mix(&b[b.len().saturating_sub(64).max(head)..]); + h.max(1) +} + +fn intent(n: &Node) -> bool { + n.live.iter().any(|b| b.spring.is_none() && !b.property.is_color() && !matches!(b.property, crate::live::Property::Blur | crate::live::Property::Trim)) +} + +impl RuntimeCore { + /// Clears `out` and fills it with the presented elements of the last frame, in tree order, + /// as [`Self::elements`] lists them but without flight sources, links and highlights, and + /// without the instant-hover-group rule that marks a group-opacity swap as live. + /// `out` keeps its capacity, so a caller that reuses it allocates nothing per frame. + pub fn motion_elements(&self, out: &mut Vec<MotionElement>) { + self.motion_elements_into(out, &mut self.motion.motion_scratch.borrow_mut()); + } + + fn motion_elements_into(&self, out: &mut Vec<MotionElement>, down: &mut Vec<(u32, u16, bool)>) { + out.clear(); + down.clear(); + // Per node: its index in `out` (or its nearest listed ancestor's), the flags it passes + // to what's under it, and whether it or an ancestor is leaving. + let s = self.env.scale; + for (i, node) in self.tree.nodes.iter().enumerate() { + // `elements` steps up to an `El::above` target before the parent. + let up = step_up(&self.tree.nodes, i); + let mut flags = up.map_or(0, |u| down[u].1); + let mut pass = flags; + if intent(node) || self.motion.landing_holds.holds(node.id) { pass |= MotionElement::LIVE; } + if self.scroll.scrolls.get(&node.id).is_some_and(ScrollState::moving) { pass |= MotionElement::SCROLLING; } + if self.motion.grows.get(&node.id).is_some_and(|g| g.moving()) { pass |= MotionElement::GROWING; } + let parent = node.parent.map(|p| down[p].0).filter(|&p| p != u32::MAX); + let exiting = self.is_exiting(node.id) || node.parent.is_some_and(|p| down[p].2); + down.push((parent.unwrap_or(u32::MAX), pass, exiting)); + if exiting { flags |= MotionElement::EXITING; } + let Some(p) = self.scene.presented(node.id) else { continue }; + let flight = if self.motion.flights.is_empty() { None } else { self.motion.flights.iter().find(|f| f.lands(&node.path, node.key.as_deref())) }; + if flight.is_some() || self.motion.reveals.get(&node.id).is_some_and(|r| r.fading()) { flags |= MotionElement::GROWING; } + if intent(node) || self.motion.landing_holds.holds(node.id) { flags |= MotionElement::LIVE; } + let drawn = self.paint.drawn.get(i).copied().unwrap_or([p.rect.x, p.rect.y, p.rect.w, p.rect.h]); + let rect = flight.map_or(drawn, |f| { + let (d, c) = (f.destination, f.presented); + let (zx, zy) = (c.w / d.w.max(1e-3), c.h / d.h.max(1e-3)); + [c.x + (drawn[0] - d.x) * zx, c.y + (drawn[1] - d.y) * zy, drawn[2] * zx, drawn[3] * zy] + }); + // O(1): the parent's clip and turn were worked out when the frame drew. + let clip = if self.motion.launches.flying(node.id) { NO_CLIP } else { + flight.map_or_else(|| self.screen_clip_of_parent(node.parent), |f| f.clip.map(|v| v * s)) + }; + let (x0, y0) = (rect[0].max(clip[0] / s), rect[1].max(clip[1] / s)); + let (x1, y1) = ((rect[0] + rect[2]).min(clip[2] / s), (rect[1] + rect[3]).min(clip[3] / s)); + let secure = node.a11y.secure || node.text.as_ref().is_some_and(|t| t.redacted) + || node.input.as_ref().is_some_and(|i| i.edit.is_secure()); + let text = match &node.text { + Some(t) => t.source_text(), + None if node.role == "text" => node.label.as_deref().unwrap_or(""), + None => "", + }; + let text_hash = if secure { 0 } else { text_hash(text) }; + if node.role == "text" { flags |= MotionElement::TEXT; } + if node.vis.fill.a > 0.01 || text_hash != 0 { flags |= MotionElement::PAINTS; } + let v = &node.vis; + if v.fill.a == 0.0 && v.border_width() == 0.0 && v.shadows.is_empty() && node.text.is_none() && v.icon.is_none() + && !self.commit.virtuals.is_empty() && self.commit.virtuals.contains_key(&node.path) + { + flags |= MotionElement::VIRTUAL; + } + let loop_phase = self.motion.loops.get(&node.id).map_or(f32::NAN, |l| { + flags |= MotionElement::LOOP; + if self.reduced_motion && !matches!(node.looping.as_ref().map(|s| s.kind), Some(rune_motion::LoopKind::Sequence(_))) { 0.0 } + else { l.phase(self.scene.store().node_time(node.id)) as f32 } + }); + let inh = self.paint.inh_scratch.get(i); + down[i].0 = out.len() as u32; + out.push(MotionElement { + id: node.id, + parent, + rect, + visible: [x0, y0, (x1 - x0).max(0.0), (y1 - y0).max(0.0)], + opacity: flight.map_or_else(|| inh.map_or(p.opacity, |h| h.opacity), |f| f.target_alpha), + scale: if flight.is_some() { 1.0 } else { inh.map_or(p.transform.scale.x, |h| h.scale) }, + loop_phase, + text_hash, + flags, + }); + } + } + + /// The path and key of the element `id` names, as [`ElementInfo::path`] and + /// [`ElementInfo::key`]. An id names one path for the runtime's life, so a watcher can cache + /// them. + pub fn element_path(&self, id: NodeId) -> Option<(&str, Option<&str>)> { + self.tree.node_index.get(&id).map(|&i| (self.tree.nodes[i].path.as_str(), self.tree.nodes[i].key.as_deref())) + } +} diff --git a/app/vendor/rune/crates/rune/src/runtime/motion/props.rs b/app/vendor/rune/crates/rune/src/runtime/motion/props.rs new file mode 100644 index 0000000..ce847ec --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/motion/props.rs @@ -0,0 +1,154 @@ +//! The runtime's own animated properties beside `rune_motion::prop`: their ids, trace names and settle time. +use super::*; + +pub(in crate::runtime) const P_FILL: Prop<Color> = Prop::custom(64, PropClass::Color); +pub(in crate::runtime) const P_BORDER: Prop<Color> = Prop::custom(65, PropClass::Color); +pub(in crate::runtime) const P_TEXT: Prop<Color> = Prop::custom(66, PropClass::Color); +pub(in crate::runtime) const P_HOVER_C: Prop<Color> = Prop::custom(67, PropClass::Color); +pub(in crate::runtime) const P_PRESS_C: Prop<Color> = Prop::custom(68, PropClass::Color); +pub(in crate::runtime) const P_SHADOWS: [Prop<Color>; 4] = [ + Prop::custom(69, PropClass::Color), + Prop::custom(70, PropClass::Color), + Prop::custom(71, PropClass::Color), + Prop::custom(72, PropClass::Color), +]; +pub(in crate::runtime) const P_HOVER: Prop<f32> = Prop::custom(73, PropClass::Opacity); +pub(in crate::runtime) const P_PRESS: Prop<f32> = Prop::custom(74, PropClass::Opacity); +pub(in crate::runtime) const P_GRADIENT: [Prop<Color>; 2] = [Prop::custom(75, PropClass::Color), Prop::custom(76, PropClass::Color)]; +pub(in crate::runtime) const P_OUTLINE: Prop<Color> = Prop::custom(77, PropClass::Color); +pub(in crate::runtime) const P_BORDER_BOTTOM: Prop<Color> = Prop::custom(78, PropClass::Color); +/// `El::press_scale`'s presented factor, multiplied into the element's own scale. +pub(in crate::runtime) const P_PRESS_SCALE: Prop<f32> = Prop::custom(79, PropClass::Scale); +pub(in crate::runtime) const P_RADIAL: [Prop<Color>; 8] = [ + Prop::custom(80, PropClass::Color), + Prop::custom(81, PropClass::Color), + Prop::custom(82, PropClass::Color), + Prop::custom(83, PropClass::Color), + Prop::custom(84, PropClass::Color), + Prop::custom(85, PropClass::Color), + Prop::custom(86, PropClass::Color), + Prop::custom(87, PropClass::Color), +]; +/// A property's name in traces. +pub(in crate::runtime) fn prop_name(id: u16) -> &'static str { + const BUILTIN: [&str; 12] = ["opacity", "frame", "offset", "scale", "rotation", "blur", "radius", "fill", "mask", "scroll", "presence", "travel"]; + match id { + 0..12 => BUILTIN[id as usize], + 64 => "fill-color", + 65 => "border-color", + 66 => "text-color", + 67 => "hover-color", + 68 => "press-color", + 69..=72 => "shadow-color", + 73 => "hover", + 74 => "press", + 75 | 76 => "gradient-color", + 77 => "outline-color", + 78 => "border-bottom-color", + 79 => "press-scale", + 80..=87 => "radial-color", + 88 => "icon-turn", + 89 => "scale", + 90..=93 => "shadow", + 94 => "group-rest", + 95 => "trim", + _ => "custom", + } +} + +/// `El::icon_rotation`'s presented turn, in radians. +pub(in crate::runtime) const P_ICON_TURN: Prop<f32> = Prop::custom(88, PropClass::Rotation); +/// `El::scale`'s presented factor. `prop::SCALE` belongs to `live_scale`; they multiply. +pub(in crate::runtime) const P_SCALE: Prop<f32> = Prop::custom(89, PropClass::Scale); +/// `El::group_opacity`'s presented rest level, so a new rest fades in rather than cutting. +pub(in crate::runtime) const P_GROUP_REST: Prop<f32> = Prop::custom(94, PropClass::Opacity); +/// `El::live_trim`'s presented span of a shape's strokes, start and end as 0…1 fractions. +pub(in crate::runtime) const P_TRIM: Prop<rune_motion::Vec2> = Prop::custom(95, PropClass::Other); +/// The first four shadows' geometry: x, y, blur and spread in a rect's lanes. +pub(in crate::runtime) const P_SHADOW_GEO: [Prop<rune_motion::Rect>; 4] = [ + Prop::custom(90, PropClass::Shape), + Prop::custom(91, PropClass::Shape), + Prop::custom(92, PropClass::Shape), + Prop::custom(93, PropClass::Shape), +]; +/// Whether a shadow colour or geometry spring, or an icon's turn, is moving node `id`. +pub(in crate::runtime) fn paint_pose_springing(store: &rune_motion::AnimationStore, id: NodeId) -> bool { + store.is_animating(id, P_ICON_TURN) + || P_SHADOWS.iter().any(|&p| store.is_animating(id, p)) + || P_SHADOW_GEO.iter().any(|&p| store.is_animating(id, p)) +} +/// Seconds a changed `El::scale` holds still before its text rasterizes at that size. +pub(in crate::runtime) const STATIC_SCALE_SETTLE: f64 = 0.1; + +/// Moves node `id`'s group-opacity rest to `group`'s on its opacity motion (the +/// transaction's spring without one), or lands it when `quiet`: an instant change or motion, +/// a mount, reduced motion. No group opacity draws at full, so an element that takes one on +/// or drops it fades from or to 1. Returns whether a dropped one is still fading to full. +pub(in crate::runtime) fn set_group_rest( + scene: &mut Scene, + id: NodeId, + group: Option<[f32; 2]>, + motion: Option<Anim>, + spring: Spring, + quiet: bool, +) -> bool { + let store = scene.store(); + let had = store.has(id, P_GROUP_REST); + let motion = motion.unwrap_or(spring.into()); + let quiet = quiet || matches!(motion.curve, rune_motion::Curve::Instant); + let settled = !store.is_animating(id, P_GROUP_REST) && store.get(id, P_GROUP_REST) == Some(1.0); + let to = group.map_or(1.0, |g| g[0]); + if group.is_none() && (!had || quiet || settled) { + if had { scene.store_mut().remove(id, P_GROUP_REST); } + return false; + } + if quiet { + scene.set(id, P_GROUP_REST, to); + } else if !had { + scene.set(id, P_GROUP_REST, 1.0); + scene.animate(id, P_GROUP_REST, to, motion); + } else if store.target(id, P_GROUP_REST) != Some(to) { + scene.animate(id, P_GROUP_REST, to, motion); + } + group.is_none() +} + +/// Drops the rest track of each dropped group opacity whose fade to full landed this frame. +pub(in crate::runtime) fn land_group_fades(scene: &mut Scene, nodes: &mut [Node], node_index: &NodeIndex) { + let landed: Vec<usize> = scene.store().events().iter() + .filter_map(|e| match *e { + rune_motion::MotionEvent::Settled { node, prop, .. } if prop == P_GROUP_REST.id => node_index.get(&node).copied(), + _ => None, + }) + .filter(|&i| nodes[i].group_fade && !scene.store().is_animating(nodes[i].id, P_GROUP_REST)) + .collect(); + for i in landed { + nodes[i].group_fade = false; + scene.store_mut().remove(nodes[i].id, P_GROUP_REST); + } +} + +/// The opacity factor `El::group_opacity` gives node `n` under a hover group at `group`. +/// A dropped one fading to full shows at full under the hover. +#[inline] +pub(in crate::runtime) fn group_factor( + scene: &Scene, + focus_keyboard: bool, + focus_path: Option<&str>, + n: &Node, + group: f32, +) -> f32 { + let [rest, hovered] = match n.vis.group_opacity { + Some(g) => g, + None if n.group_fade => [1.0, 1.0], + None => return 1.0, + }; + let rest = scene.get(n.id, P_GROUP_REST).unwrap_or(rest); + // A control the keyboard reached shows as if hovered, as CSS reveals a hover-only button + // on `:focus-visible` (or `:focus-within` around it): focus is never on something unseen. + let focused = focus_keyboard && focus_path.is_some_and(|f| { + f.strip_prefix(n.path.as_str()).is_some_and(|rest| rest.is_empty() || rest.starts_with('/')) + }); + let group = if focused { 1.0 } else { group }; + rest + (hovered - rest) * group +} diff --git a/app/vendor/rune/crates/rune/src/runtime/motion/reveal_phase.rs b/app/vendor/rune/crates/rune/src/runtime/motion/reveal_phase.rs new file mode 100644 index 0000000..d080760 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/motion/reveal_phase.rs @@ -0,0 +1,246 @@ +//! A streaming text's word reveal: `Idle` with every word shown, `Fading` the words that +//! arrived since, and the window's chain of them, which makes one chunk's words cross texts in +//! reading order. +//! +//! A commit says what a text's content is now (`commit/apply.rs`), a frame tick says how far its +//! clock has run (`motion/tracks.rs`), a clock change moves its word times +//! (`motion/loop_clock.rs`), and the node leaving keeps the state for a return, dropping the +//! oldest past `REVEALS_KEPT` (`commit/prune.rs`). The last of those is the only way a text +//! forgets a fade it was in the middle of. +use crate::machine::Effects; + +/// How a text arrived at one commit. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(in crate::runtime) enum Arrival { + /// It was here at the last commit. + Kept, + /// It is new and shows whole: the commit lands its changes (`Tx::instant`), no input caused + /// it (`Tx::unprompted`), or it mounted inside a remounting row. + Landed, + /// It is new while its entrance still plays: its words fade in from none. + Entering, + /// Its content was replaced or cut (`Tx::instant`, a shorter text, a word boundary moved): + /// what faded is gone and the text shows from its start. + Replaced, +} + +/// What a commit, a frame tick or a clock change says about one streaming text. +pub(in crate::runtime) enum RevealEvent<'a> { + /// A commit: its content now ends at `content.len()` bytes. + Commit { + content: &'a str, + /// Seconds each word fades in over (`TextSpec::reveal`, or the reduced-motion fade). + fade: f32, + arrival: Arrival, + /// The window's chain of streaming words, for a text on the window's clock; `None` for + /// one on its own (`El::time_scale`), which queues behind nothing. + chain: Option<&'a RevealChain>, + now: f64, + reduced_motion: bool, + }, + /// A frame ticked `now` on the text's clock. + Tick { now: f64 }, + /// The text's clock changed scale: its word times move by `shift`. + Shift { shift: f64 }, +} + +/// What a transition asks the caller to carry out. +#[derive(Clone, Copy, Debug, PartialEq)] +pub(in crate::runtime) enum RevealEffect { + /// A word starts fading at this time; the window's chain queues the next text behind it. + Started(f64), +} + +/// A streaming text's word reveal. +#[derive(Clone, Debug)] +pub(in crate::runtime) enum RevealPhase { + /// Caught up: `shown` bytes of its content are visible and no word fades. + Idle { shown: usize }, + /// The words in `words` (`(start byte, start time)`, oldest first) fade in over `fade` + /// seconds each; the text shows the first `shown` bytes whole. Never empty: a commit with + /// no new words leaves the phase `Idle`. + Fading { shown: usize, words: Vec<(u32, f64)>, fade: f32 }, +} + +impl Default for RevealPhase { + fn default() -> Self { RevealPhase::Idle { shown: 0 } } +} + +impl RevealPhase { + /// The state after `event`, and the effects the caller carries out. + pub(in crate::runtime) fn step(&mut self, event: RevealEvent<'_>) -> Effects<RevealEffect> { + match event { + RevealEvent::Tick { now } => { + // Only once every word has shown does the phase go back to `Idle`: the front of + // the list leaving alone would move `shown` backwards. + if let RevealPhase::Fading { shown, words, fade } = self + && words.iter().all(|w| now - w.1 >= f64::from(*fade)) + { + *self = RevealPhase::Idle { shown: *shown }; + } + Effects::none() + } + RevealEvent::Shift { shift } => { + if let RevealPhase::Fading { words, .. } = self { + for w in words { w.1 += shift; } + } + Effects::none() + } + RevealEvent::Commit { content, fade, arrival, chain, now, reduced_motion } => { + self.commit(content, fade, arrival, chain, now, reduced_motion) + } + } + } + + /// A commit's news about the text: its content ends at `content.len()` bytes, and `arrival` + /// says how it got there. + fn commit( + &mut self, + content: &str, + fade: f32, + arrival: Arrival, + chain: Option<&RevealChain>, + now: f64, + reduced_motion: bool, + ) -> Effects<RevealEffect> { + // The words a commit keeps, and the byte its fade had already consumed. + let (mut words, from) = match arrival { + Arrival::Kept => match std::mem::take(self) { + RevealPhase::Idle { shown } => (Vec::new(), shown), + RevealPhase::Fading { shown, words, .. } => (words, shown), + }, + Arrival::Entering => (Vec::new(), 0), + Arrival::Landed | Arrival::Replaced => (Vec::new(), content.len()), + }; + let mut effects = Effects::none(); + if content.len() > from && fade > 0.0 { + let mut starts = Vec::new(); + word_starts(content, from, &mut starts); + // A word continuing across the old end keeps its time. New words wait behind every + // streaming text's newest word, taken in reading order, so one edge moves down the + // page: a chunk spanning several paragraphs or list items fades them one after + // another, never all at once. Only while the newest word is still fading: texts + // mounting at once behind a long run (a remount, a restored turn) fade together as + // before, never waiting through still frames. + let own = words.last().map_or(now, |w| w.1.max(now)); + let chain_at = chain.map_or(now, |chain| chain.start(now, fade)); + let queued = ((chain_at - now) / 0.0055) as usize; + let pending = words.iter().filter(|w| w.1 > now).count() + starts.len() + queued; + let stagger = if reduced_motion { + 0.0 + } else { + let k = (pending as f32 / 24.0).clamp(0.0, 1.0); + (0.020 + (0.0055 - 0.020) * k) as f64 + }; + let mut tn = if chain_at > own { chain_at + stagger } else { own }; + for b in starts { + words.push((b, tn)); + tn += stagger; + } + if let (true, Some(last)) = (chain.is_some(), words.last()) { + // A text on its own clock keeps its words to itself, and so does the chain. + effects.push(RevealEffect::Started(last.1)); + } + } + *self = + if words.is_empty() { RevealPhase::Idle { shown: content.len() } } + else { RevealPhase::Fading { shown: content.len(), words, fade } }; + effects + } + + /// Every word caught up: nothing fades. + pub(in crate::runtime) fn fading(&self) -> bool { matches!(self, RevealPhase::Fading { .. }) } + + /// The byte its words have been shown up to. + pub(in crate::runtime) fn shown(&self) -> usize { + match *self { + RevealPhase::Idle { shown } | RevealPhase::Fading { shown, .. } => shown, + } + } + + /// Nothing fading, and `end` bytes of content are all shown: a memo or a cache holding this + /// text holds what the text draws. + pub(in crate::runtime) fn caught_up(&self, end: usize) -> bool { !self.fading() && self.shown() == end } + + /// The words still fading, oldest first; empty when the text has caught up. + #[cfg(test)] + pub(in crate::runtime) fn words(&self) -> &[(u32, f64)] { + match self { + RevealPhase::Idle { .. } => &[], + RevealPhase::Fading { words, .. } => words, + } + } + + /// The fade it is in, for paint to carry over a piece's glyphs: taken once per piece, so no + /// glyph looks at the phase again. + pub(in crate::runtime) fn fade(&self) -> Option<Fade<'_>> { + match self { + RevealPhase::Fading { words, fade, .. } => Some(Fade { words, fade: *fade }), + RevealPhase::Idle { .. } => None, + } + } +} + +/// The words still fading and how long each takes. +#[derive(Clone, Copy, Debug)] +pub(in crate::runtime) struct Fade<'a> { + words: &'a [(u32, f64)], + fade: f32, +} + +impl Fade<'_> { + /// The alpha of `byte`'s word, `now` on the text's clock: 1 anywhere no word fades. + pub(in crate::runtime) fn alpha(self, byte: u32, now: f64) -> f32 { + let i = self.words.partition_point(|w| w.0 <= byte); + if i == 0 { return 1.0; } + let t0 = self.words[i - 1].1; + if self.fade <= 0.0 { + return if now >= t0 { 1.0 } else { 0.0 }; + } + ease_out(((now - t0) / self.fade as f64) as f32) + } +} + +/// The window's chain of streaming words: the newest word's start, which the next text's words +/// queue behind. +/// +/// It holds a start only while a run still fades: a start more than one fade ahead is a run +/// longer than a fade, and the texts behind it fade together rather than wait it out. A run +/// that ended is replaced by the next word's start, so the chain never drifts into the past. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub(in crate::runtime) struct RevealChain { + until: f64, +} + +impl RevealChain { + /// Where `now`'s first new word starts: behind the newest one while it still fades, else + /// now. + pub(in crate::runtime) fn start(self, now: f64, fade: f32) -> f64 { + if self.until - now > f64::from(fade) { now } else { self.until.max(now) } + } + + /// `at` is a word's start: the chain reaches no further back than it. + pub(in crate::runtime) fn started(&mut self, at: f64) { self.until = self.until.max(at); } + + /// The newest streaming word's start. + #[cfg(test)] + pub(in crate::runtime) fn until(self) -> f64 { self.until } +} + +/// Where each word of `s` after `from` starts, as byte offsets. +fn word_starts(s: &str, from: usize, out: &mut Vec<u32>) { + let mut prev_space = true; + for (i, c) in s[from..].char_indices() { + let space = c.is_whitespace(); + if !space && prev_space { + out.push((from + i) as u32); + } + prev_space = space; + } +} + +/// A word's fade curve: fast in, easing to full. +fn ease_out(x: f32) -> f32 { + let x = x.clamp(0.0, 1.0); + 1.0 - (1.0 - x) * (1.0 - x) * (1.0 - x) +} diff --git a/app/vendor/rune/crates/rune/src/runtime/motion/rewind.rs b/app/vendor/rune/crates/rune/src/runtime/motion/rewind.rs new file mode 100644 index 0000000..5ca56de --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/motion/rewind.rs @@ -0,0 +1,26 @@ +//! Feeds an attached [`Rewind`](crate::rewind::Rewind) each frame: every keyed or trace-named +//! element on screen, its drawn rect and opacity (ancestors included). + +use super::*; + +impl tracks::MotionState { + pub(crate) fn record_rewind(&self, clock: f64, viewport: (f32, f32), nodes: &[Node], paint: &paint_state::PaintState) { + let Some(rewind) = &self.rewind else { return }; + let mut tape = rewind.lock(); + if tape.paused { return; } + tape.begin(clock, viewport); + if paint.drawn.len() == nodes.len() && paint.inh_scratch.len() == nodes.len() { + for (i, n) in nodes.iter().enumerate() { + if n.key.is_none() && n.trace_name.is_none() { continue; } + if !paint.was_seen(i, true) { continue; } + let q = crate::rewind::quantize(paint.drawn[i], paint.inh_scratch[i].opacity); + tape.sample(n.id.0, q, || n.trace_name.map_or_else(|| n.key.clone().unwrap_or_else(|| n.path.clone()), str::to_owned)); + } + } + tape.end(); + } + + /// The recorder attached with `Tx::record_rewind`, if any. + #[inline] + pub(crate) fn rewind(&self) -> Option<&crate::rewind::Rewind> { self.rewind.as_ref() } +} diff --git a/app/vendor/rune/crates/rune/src/runtime/motion/timer_wake.rs b/app/vendor/rune/crates/rune/src/runtime/motion/timer_wake.rs new file mode 100644 index 0000000..bbba5ff --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/motion/timer_wake.rs @@ -0,0 +1,440 @@ +//! A due timer on a window that draws nothing new. `poll` runs on its own first, and the view, +//! layout and drawing wait for a frame until that poll or something else changes what shows: +//! always on a hidden window, and on a shown one while it rests. +use super::*; + +/// Frame loop, timer wake deadlines, action queue, pending transaction, live value latch, +/// tracing and hot-reload session state owned by [`RuntimeCore`]. Under `#[repr(C)]`, the +/// cold `pending: Tx` buffer precedes the hot per-frame fields (`wake_deadlines`, `timer_wake`, +/// `queue`, `live`) so they sit directly adjacent to [`CommitState`]'s `dirty`/`relayout` flags. +#[repr(C)] +pub(crate) struct FrameState { + /// What `update` asked of the next commit. + pub(in crate::runtime) pending: Tx, + pub(super) idle_meter: crate::tooling::perf_warn::IdleMeter, + /// When the frame being built will present; videos pull the picture for it. + frame_target: Option<crate::time::Instant>, + #[cfg(test)] + test_clock: Option<crate::Clock>, + /// Tooling opts in before any callbacks. Absent in ordinary app runs. + trace_channels: Option<HashMap<&'static str, (&'static str, f32)>>, + #[cfg(feature = "hot")] + hot: Option<crate::hot::Session>, + /// The live-only event this frame's commit checks: its handler, and what the view had built. + #[cfg(debug_assertions)] + pub(super) live_check: Option<(String, live_check::ViewPrint)>, + /// Live-only events checked (and so committed) so far. + #[cfg(debug_assertions)] + pub(super) live_checks: u64, + /// Stale-view warnings printed for `Tx::live_only` handlers, each once. + #[cfg(debug_assertions)] + pub(super) live_only_warnings: Vec<String>, + pub(super) live_clock: Arc<()>, + pub(super) live_subscriptions: Vec<Arc<crate::live::Subscription>>, + /// Events whose handler said `Tx::live_only`, and so didn't commit. + pub(in crate::runtime) live_only_skips: u64, + last_dt: f64, + /// Record `events` without a trace: headless runs. Live hosts turn it off. + record_events: bool, + /// Debug builds check `Tx::live_only` events (`skip_view`). + #[cfg(debug_assertions)] + pub(super) live_only_check: bool, + wake_deadlines: Vec<f64>, + timer_wake: TimerWake, + pub(in crate::runtime) queue: ActionQueue, + pub(in crate::runtime) live: live_latch::LiveLane, +} + +impl FrameState { + // Single-caller constructor for `RuntimeCore::new`; inlined so it stays in its caller's + // codegen unit instead of shifting partitioning and dropping inlining in the paint walk. + #[inline] + pub(in crate::runtime) fn new() -> Self { + Self { + queue: ActionQueue::default(), + pending: Tx::default(), + wake_deadlines: Vec::new(), + timer_wake: Default::default(), + idle_meter: Default::default(), + last_dt: 0.0, + frame_target: None, + #[cfg(test)] + test_clock: None, + live: live_latch::LiveLane::new(Arc::new(|| {})), + live_clock: Arc::new(()), + live_subscriptions: Vec::new(), + live_only_skips: 0, + #[cfg(debug_assertions)] + live_only_check: true, + #[cfg(debug_assertions)] + live_check: None, + #[cfg(debug_assertions)] + live_checks: 0, + #[cfg(debug_assertions)] + live_only_warnings: Vec::new(), + record_events: true, + trace_channels: None, + #[cfg(feature = "hot")] + hot: None, + } + } + + #[inline] + pub(in crate::runtime) fn record_poll(&mut self, changed: bool) -> bool { + self.idle_meter.polled(changed) + } + + #[inline] + pub(in crate::runtime) fn frame_target(&self) -> Option<crate::time::Instant> { + self.frame_target + } + + #[inline] + pub(crate) fn set_frame_target(&mut self, at: crate::time::Instant) { + self.frame_target = Some(at); + } + + #[cfg(test)] + #[inline] + pub(crate) fn set_test_clock(&mut self, clock: crate::Clock) { + self.test_clock = Some(clock); + } + + #[cfg(test)] + #[inline] + pub(crate) fn test_clock_mut(&mut self) -> Option<&mut crate::Clock> { + self.test_clock.as_mut() + } + + #[cfg(test)] + #[inline] + pub(in crate::runtime) fn test_clock_now(&self) -> Option<f64> { + self.test_clock.as_ref().map(crate::Clock::now) + } + + #[inline] + pub(crate) fn tracing_channels(&self) -> bool { + self.trace_channels.is_some() + } + + #[inline] + pub(crate) fn trace_channels(&self) -> Option<&HashMap<&'static str, (&'static str, f32)>> { + self.trace_channels.as_ref() + } + + #[inline] + pub(crate) fn enable_trace_channels(&mut self, enabled: bool) { + self.trace_channels = enabled.then(Default::default); + } + + #[inline] + pub(in crate::runtime) fn record_trace_channel(&mut self, name: &'static str, kind: &'static str, value: f32) { + if let Some(channels) = &mut self.trace_channels { + channels.insert(name, (kind, value)); + } + } + + #[inline] + pub(crate) fn has_hot(&self) -> bool { + #[cfg(feature = "hot")] + return self.hot.is_some(); + #[cfg(not(feature = "hot"))] + false + } + + #[cfg(feature = "hot")] + #[inline] + pub(crate) fn hot(&self) -> Option<&crate::hot::Session> { + self.hot.as_ref() + } + + #[cfg(all(test, feature = "hot"))] + #[inline] + pub(crate) fn hot_mut(&mut self) -> Option<&mut crate::hot::Session> { + self.hot.as_mut() + } + + #[cfg(feature = "hot")] + #[inline] + pub(crate) fn set_hot(&mut self, session: crate::hot::Session) { + self.hot = Some(session); + } + + #[inline] + pub(in crate::runtime) fn hot_pending(&self) -> bool { + #[cfg(feature = "hot")] + return self.hot.as_ref().is_some_and(crate::hot::Session::pending); + #[cfg(not(feature = "hot"))] + false + } + + #[cfg(feature = "hot")] + #[inline] + pub(in crate::runtime) fn hot_changed(&mut self) -> bool { + self.hot.as_mut().is_some_and(crate::hot::Session::changed) + } + + #[cfg(debug_assertions)] + #[inline] + pub(in crate::runtime) fn clear_live_check(&mut self) { + self.live_check = None; + } + + #[cfg(debug_assertions)] + #[inline] + pub(in crate::runtime) fn take_live_check(&mut self) -> Option<(String, live_check::ViewPrint)> { + self.live_check.take() + } + + #[cfg(debug_assertions)] + #[inline] + pub(in crate::runtime) fn live_checks(&self) -> u64 { + self.live_checks + } + + #[cfg(debug_assertions)] + #[inline] + pub(in crate::runtime) fn live_only_warnings(&self) -> &[String] { + &self.live_only_warnings + } + + #[inline] + pub(in crate::runtime) fn has_live_subscriptions(&self) -> bool { + !self.live_subscriptions.is_empty() + } + + #[inline] + pub(in crate::runtime) fn set_last_dt(&mut self, dt: f64) { + self.last_dt = dt; + } + + #[inline] + pub(crate) fn record_events(&self) -> bool { + self.record_events + } + + #[inline] + pub(crate) fn set_record_events(&mut self, record: bool) { + self.record_events = record; + } + + #[inline] + pub(in crate::runtime) fn schedule_wakes_from(&mut self, now: f64, wakes: impl IntoIterator<Item = std::time::Duration>) { + for delay in wakes { + let deadline = now + delay.as_secs_f64(); + if let Err(index) = self.wake_deadlines.binary_search_by(|t| t.total_cmp(&deadline)) { + self.wake_deadlines.insert(index, deadline); + } + } + } + + #[inline] + pub(in crate::runtime) fn next_wake_deadline(&self) -> Option<f64> { + self.wake_deadlines.first().copied() + } + + #[inline] + pub(in crate::runtime) fn begin_frame_poll(&mut self, clock: f64) -> (bool, usize) { + let polled = self.timer_wake.frame_polled(self.wake_deadlines.first().is_some_and(|t| *t <= clock)); + let due = self.wake_deadlines.partition_point(|t| *t <= clock); + (polled, due) + } + + #[inline] + pub(in crate::runtime) fn drain_due_wakes(&mut self, due: usize) { + self.wake_deadlines.drain(..due); + } + + #[inline] + pub(in crate::runtime) fn polled_at(&self, fallback: f64) -> f64 { + self.timer_wake.polled_at().unwrap_or(fallback) + } + + #[cfg(test)] + #[inline] + pub(in crate::runtime) fn wake_deadlines(&self) -> &[f64] { + &self.wake_deadlines + } + + #[cfg(test)] + #[inline] + pub(in crate::runtime) fn clear_wake_deadlines(&mut self) { + self.wake_deadlines.clear(); + } +} + +/// A resting window's timer poll, and the frame it asked for. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub(in crate::runtime) enum TimerWake { + /// No timer poll stands for a frame. + #[default] + Idle, + /// A timer's poll ran `at`, and the frame it asked for is still to come. The frame takes the + /// poll as its own, and the poll's `wake_after`s wait in `pending` to count from that frame. + Asked { at: f64 }, + /// A frame took the poll at `polled_at` as its own. + Taken { polled_at: f64 }, +} + +pub(in crate::runtime) enum TimerWakeEvent { + /// A resting wake's poll ran `at` and asked for a frame. + Asked { at: f64 }, + /// A frame polls; `due`: a deadline came due since the timer's poll, so it polls again. + Frame { due: bool }, + /// The frame asked for won't stand for its poll: the window hid or showed, or a wake asks + /// the next frame to poll. + Cancel, + /// A poll runs alone: no earlier poll stands for anything now. + PollAlone, +} + +impl TimerWake { + /// The state after `event`, and, for a frame, whether a timer's poll already stands for it; + /// for a cancel, the poll time the poll's timers count from. + pub(in crate::runtime) fn step(self, event: TimerWakeEvent) -> (TimerWake, Option<f64>) { + match (self, event) { + (_, TimerWakeEvent::Asked { at }) => (TimerWake::Asked { at }, None), + (_, TimerWakeEvent::PollAlone) => (TimerWake::Idle, None), + (TimerWake::Asked { at }, TimerWakeEvent::Frame { due: false }) => (TimerWake::Taken { polled_at: at }, Some(at)), + (_, TimerWakeEvent::Frame { .. }) => (TimerWake::Idle, None), + (TimerWake::Asked { at }, TimerWakeEvent::Cancel) => (TimerWake::Idle, Some(at)), + (state, TimerWakeEvent::Cancel) => (state, None), + } + } + + /// At a frame's poll: whether a timer's poll already stands for it. A deadline that came + /// due since (`due`) still gets this frame's poll. + pub(in crate::runtime) fn frame_polled(&mut self, due: bool) -> bool { + let (next, taken) = self.step(TimerWakeEvent::Frame { due }); + *self = next; + taken.is_some() + } + + pub(in crate::runtime) fn polled_at(&self) -> Option<f64> { + match *self { + TimerWake::Taken { polled_at } => Some(polled_at), + _ => None, + } + } + + fn asked(&self) -> bool { matches!(self, TimerWake::Asked { .. }) } +} + +impl RuntimeCore { + /// `poll` alone, for a hidden window's wake: its timers and inbox advance while nothing + /// lays out, animates or draws. Like `update`, its changes wait, dirty, for the next frame. + /// Returns whether the last frame went out of date: `poll` reported a change or asked for a + /// scroll or text flight, or a live-edit patch arrived. A `wake_after` alone doesn't count. + /// + /// A resting wake's poll still stands for a frame it asked for that runs covered or misses + /// its drawable: its timers count from it, and nothing polls again unless another came due. + pub(crate) fn poll_hidden(&mut self, app: &mut dyn AppDriver) -> bool { + let now = self.now_clock(); + if self.frame.timer_wake.asked() && self.frame.wake_deadlines.first().is_none_or(|t| *t > now) { + self.cancel_timer_frame(); + return self.needs_commit(); + } + let stale = self.poll_alone(app); + let wakes = std::mem::take(&mut self.frame.pending.wakes); + self.schedule_wakes(wakes); + stale + } + + /// `poll_hidden`, leaving the poll's `wake_after`s in `pending`. + fn poll_alone(&mut self, app: &mut dyn AppDriver) -> bool { + self.frame.timer_wake = self.frame.timer_wake.step(TimerWakeEvent::PollAlone).0; + if let Some(clock) = self.wall_clock() { self.clock = clock; } + // An `update`'s `wake_after` counts from now; no frame may come to schedule it. + let wakes = std::mem::take(&mut self.frame.pending.wakes); + self.schedule_wakes(wakes); + // Due timers are spent with or without a poll, as a frame spends them; one left due + // would wake the host again every frame interval. + let due = self.frame.wake_deadlines.partition_point(|t| *t <= self.clock); + self.frame.wake_deadlines.drain(..due); + // A glyph mask cache write that came due while nothing draws (`mask_cache`). + let _ = self.text.mask_cache_frame(false); + let patched = self.patch_pending(); + if !app.has_poll() { return patched; } + let mut one = self.transaction(app); + let changed = self.frame.idle_meter.polled(crate::tooling::perf_warn::timed("poll", || app.poll(self.clock, &mut one))); + self.commit.dirty |= changed; + self.frame.pending.polled_change |= changed; + let asks_frame = one.srgb_blend.is_some_and(|b| b != self.paint.srgb_blend()) || one.font_smoothing.is_some_and(|m| m != self.text.smoothing) || self.changes_families(&one) || (one.blur && self.kbd.focus.path().is_some()); + self.latch_requests(app, &mut one); + let stale = changed || one.frame_work() || patched || asks_frame; + merge(&mut self.frame.pending, one); + stale + } + + /// A shown window's due timer. While the window rests, `poll` runs alone, as on a hidden + /// window, and the result says whether that poll wants a frame: it changed what shows, + /// asked for a window frame, or asked for the next frame (`wake_after(ZERO)`). The host + /// answers with `resting_wake_frame`. `None` when anything else wants this frame, which + /// then draws as any other: motion, scrolls or a window frame in flight, queued input, a + /// hover or tooltip delay, a loop, a live value, `SurfaceDraw` content, or a poll stepping + /// every frame. + pub(crate) fn resting_wake(&mut self, app: &mut dyn AppDriver) -> Option<bool> { + if !self.rests() { return None; } + let stale = self.poll_alone(app); + let steps = self.frame.pending.wakes.iter().any(|d| d.is_zero()); + // A starved fill's wake draws the frame that resumes it; the poll alone never does. + Some(stale || self.host.window_frame.is_some() || steps || self.commit.virtual_fill.resuming(self.clock)) + } + + /// Whether the host asked for a frame after `resting_wake`. That frame doesn't poll again + /// and its timers count from it; without one they count from the poll. + pub(crate) fn resting_wake_frame(&mut self, frame: bool) { + if frame { + self.frame.timer_wake = self.frame.timer_wake.step(TimerWakeEvent::Asked { at: self.clock }).0; + } else { + let wakes = std::mem::take(&mut self.frame.pending.wakes); + self.schedule_wakes(wakes); + } + } + + /// The frame a resting wake asked for won't stand for its poll: the window hid or showed, + /// or an `AppHandle::wake` asks the next frame to poll. The poll's timers count from it. + pub(crate) fn cancel_timer_frame(&mut self) { + let (next, polled) = self.frame.timer_wake.step(TimerWakeEvent::Cancel); + self.frame.timer_wake = next; + let Some(polled) = polled else { return }; + let wakes = std::mem::take(&mut self.frame.pending.wakes); + self.schedule_wakes_from(polled, wakes); + } + + /// Nothing but a timer asks this runtime for a frame. + pub(crate) fn rests(&self) -> bool { + self.motion.loop_wake().is_none() && self.rests_except_loop() + } + + /// `rests`, apart from a loop's own wake (`paint_cycle_tick`). + pub(in crate::runtime) fn rests_except_loop(&self) -> bool { + !self.animating && self.rests_but_motion() + } + + /// Nothing waits for a frame but motion: no commit, input, held work, live value or timer + /// due now (`loop_step` asks the motion apart). + pub(in crate::runtime) fn rests_but_motion(&self) -> bool { + self.waiting_work().is_none() + } + + /// What waits for a frame besides motion, if anything (`rests_but_motion`). + pub(in crate::runtime) fn waiting_work(&self) -> Option<&'static str> { + #[cfg(feature = "hot")] + if self.frame.has_hot() { return Some("live edit"); } + if self.stale() { Some("a commit or input") } + else if self.commit.is_settling() || self.host.window_frame.is_some() { Some("a settle or window frame") } + else if self.pointer.hover_delays.waiting() || self.tooltip_waiting() || self.press_repeat_waiting() || self.drag_ends_pending() || self.pointer.drag_out_request.is_some() { Some("pointer work") } + else if self.files_held() { Some("files") } + else if self.live_pending() { Some("a live value") } + else if !self.surfaces.is_empty() { Some("a native surface") } + else if self.steps_frames() { Some("a poll that steps every frame") } + else { None } + } + + /// The last poll asked for the next frame (`wake_after(ZERO)`, due at once): it steps + /// something every frame. + fn steps_frames(&self) -> bool { + self.frame.wake_deadlines.first().is_some_and(|t| *t <= self.clock) + } +} diff --git a/app/vendor/rune/crates/rune/src/runtime/motion/tracks.rs b/app/vendor/rune/crates/rune/src/runtime/motion/tracks.rs new file mode 100644 index 0000000..1283497 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/motion/tracks.rs @@ -0,0 +1,721 @@ +//! Render-side growth, scroll and streaming word-reveal tracks, plus animated paint samples. +use super::*; +use crate::runtime::scroll_mode::{self, Event as ModeEvent}; + +/// Scroll momentum decay (iOS normal: 0.998 per ms). +pub(in crate::runtime) const SCROLL_DECAY: f32 = 2.002; + +/// Retained render-side motion state: growth stacks, streaming word reveals, matched/launch/text +/// flights, loops and rewind capture. Ordered hot-first under `#[repr(C)]` so `flying`, `flights`, +/// frame flags and `loops` read during the paint walk sit together and first. +#[repr(C)] +pub(crate) struct MotionState { + /// Elements flying from a matched one, with their scene target. They paint last. + pub(in crate::runtime) flying: Vec<(NodeId, MRect)>, + pub(super) flights: Vec<TextFlight>, + caught_up: f32, + slack_dt: f32, + /// Why the last frame was animating, as [`AnimSource`] bits, for traces. + pub(in crate::runtime) anim_sources: u16, + loops_active: bool, + /// Some node ran on a scaled clock (`El::time_scale`) at the last commit. + time_scaled: bool, + /// Motion has a cause (`Tx::unprompted`): a commit no input in this window caused mounts and + /// unmounts at once. On for every window an app opens (`tooling::runtime_for`); a bare + /// `Runtime` keeps every commit's motion. + pub(in crate::runtime) motion_needs_cause: bool, + pub(super) loops: HashMap<NodeId, rune_motion::LoopTrack>, + /// Shared host deadline: unscaled wake time and corresponding animation time. + loop_wake: Option<(f64, f64)>, + /// `Tx::launch` flights, waiting for their commit or in the air. + pub(super) launches: flights::Launches, + pub(in crate::runtime) grows: HashMap<NodeId, GrowTrack>, + pub(in crate::runtime) stacks: HashMap<NodeId, Stack>, + /// The header each lifted fold shuts under, by the fold's id, which draws where it's laid out. + pub(super) fold_headers: HashMap<NodeId, String>, + /// What this frame's commits held at their landing width (`El::hold_landing_width`). + pub(super) landing_holds: landing_hold::LandingHolds, + pub(super) reveals: HashMap<NodeId, RevealPhase>, + /// The reveal states `reveals` keeps for texts that have left the tree, newest first, at + /// most `prune::REVEALS_KEPT` of them (see `prune_exited`). + reveals_kept: Vec<NodeId>, + /// The newest streamed word of any text, which the next text's words queue behind. + reveal_chain: RevealChain, + /// The last commit's `El::matched` ids, one present element each (the last in tree order). + pub(super) matched: Vec<(Rc<str>, NodeId)>, + pub(super) loop_clock: loop_clock::LoopClock, + /// `motion_elements`' per-node scratch, kept so a frame doesn't allocate. + pub(in crate::runtime) motion_scratch: std::cell::RefCell<Vec<(u32, u16, bool)>>, + /// The recorder `Tx::record_rewind` attached (`runtime/motion/rewind.rs`). + pub(super) rewind: Option<crate::rewind::Rewind>, + #[cfg(debug_assertions)] + pub(super) matched_warned: HashSet<Rc<str>>, +} + +impl MotionState { + // Single-caller constructor for `RuntimeCore::new`; inlined so it stays in its caller's + // codegen unit instead of shifting partitioning and dropping inlining in the paint walk. + #[inline] + pub(in crate::runtime) fn new() -> Self { + Self { + flying: Vec::new(), + flights: Vec::new(), + caught_up: 0.0, + slack_dt: 0.0, + anim_sources: 0, + loops_active: false, + time_scaled: false, + motion_needs_cause: false, + loops: HashMap::default(), + loop_wake: None, + launches: Default::default(), + grows: HashMap::default(), + stacks: HashMap::default(), + fold_headers: HashMap::default(), + landing_holds: Default::default(), + reveals: HashMap::default(), + reveals_kept: Vec::new(), + reveal_chain: RevealChain::default(), + matched: Vec::new(), + loop_clock: Default::default(), + motion_scratch: Default::default(), + rewind: None, + #[cfg(debug_assertions)] + matched_warned: HashSet::default(), + } + } + + #[inline] + pub(in crate::runtime) fn flights(&self) -> &[TextFlight] { + &self.flights + } + + #[inline] + pub(in crate::runtime) fn flights_mut(&mut self) -> &mut Vec<TextFlight> { + &mut self.flights + } + + #[inline] + pub(in crate::runtime) fn clear_flights(&mut self) { + self.flights.clear(); + } + + #[inline] + pub(in crate::runtime) fn add_caught_up(&mut self, step: f32) { + self.caught_up += step; + } + + #[inline] + pub(in crate::runtime) fn begin_slack_step(&mut self, step: f32) { + self.slack_dt = std::mem::take(&mut self.caught_up) + step; + } + + #[inline] + pub(crate) fn anim_sources(&self) -> u16 { + self.anim_sources + } + + #[inline] + pub(in crate::runtime) fn set_anim_sources(&mut self, sources: u16) { + self.anim_sources = sources; + } + + #[inline] + pub(in crate::runtime) fn add_anim_sources(&mut self, bits: u16) { + self.anim_sources |= bits; + } + + #[inline] + pub(in crate::runtime) fn loops_active(&self) -> bool { + self.loops_active + } + + #[inline] + pub(in crate::runtime) fn reset_loops_active(&mut self) { + self.loops_active = false; + } + + #[inline] + pub(in crate::runtime) fn mark_loops_active(&mut self, active: bool) { + self.loops_active |= active; + } + + #[inline] + pub(in crate::runtime) fn time_scaled(&self) -> bool { + self.time_scaled + } + + #[inline] + pub(in crate::runtime) fn set_time_scaled(&mut self, scaled: bool) { + self.time_scaled = scaled; + } + + #[inline] + pub(crate) fn enable_motion_needs_cause(&mut self) { + self.motion_needs_cause = true; + } + + #[inline] + pub(in crate::runtime) fn motion_needs_cause(&self) -> bool { + self.motion_needs_cause + } + + #[inline] + pub(in crate::runtime) fn loop_track(&self, id: NodeId) -> Option<&rune_motion::LoopTrack> { + self.loops.get(&id) + } + + #[inline] + pub(in crate::runtime) fn has_loop(&self, id: NodeId) -> bool { + self.loops.contains_key(&id) + } + + #[inline] + pub(in crate::runtime) fn loops_is_empty(&self) -> bool { + self.loops.is_empty() + } + + #[inline] + pub(in crate::runtime) fn loops_len(&self) -> usize { + self.loops.len() + } + + #[inline] + pub(in crate::runtime) fn loop_ids(&self) -> impl Iterator<Item = NodeId> + '_ { + self.loops.keys().copied() + } + + #[inline] + pub(in crate::runtime) fn loop_active(&self, id: NodeId, node_time: f64) -> bool { + self.loops.get(&id).is_some_and(|l| l.active(node_time)) + } + + #[inline] + pub(in crate::runtime) fn loop_offset(&self, id: NodeId, time: f64, reduced_motion: bool) -> Option<[f32; 2]> { + self.loops.get(&id)?.offset(time, reduced_motion) + } + + #[inline] + pub(in crate::runtime) fn loop_wake(&self) -> Option<(f64, f64)> { + self.loop_wake + } + + #[inline] + pub(in crate::runtime) fn clear_loop_wake(&mut self) { + self.loop_wake = None; + } + + #[inline] + pub(in crate::runtime) fn set_loop_wake(&mut self, wake: (f64, f64)) { + self.loop_wake = Some(wake); + } + + #[inline] + pub(in crate::runtime) fn arm_loop_wake(&mut self, wake: f64, at: f64) { + if self.loop_wake.is_none_or(|w| wake < w.0) { + self.loop_wake = Some((wake, at)); + } + } + + #[inline] + pub(in crate::runtime) fn launches(&self) -> &flights::Launches { + &self.launches + } + + #[inline] + pub(in crate::runtime) fn launches_mut(&mut self) -> &mut flights::Launches { + &mut self.launches + } + + #[inline] + pub(in crate::runtime) fn insert_fold_header(&mut self, id: NodeId, header: String) { + self.fold_headers.insert(id, header); + } + + #[inline] + pub(in crate::runtime) fn clear_landing_holds(&mut self) { + self.landing_holds.clear(); + } + + #[inline] + pub(in crate::runtime) fn holds_landing(&self, id: NodeId) -> bool { + self.landing_holds.holds(id) + } + + #[inline] + pub(in crate::runtime) fn has_reveal(&self, id: NodeId) -> bool { + !self.reveals.is_empty() && self.reveals.contains_key(&id) + } + + #[inline] + pub(in crate::runtime) fn reveal_fading(&self, id: NodeId) -> bool { + self.reveals.get(&id).is_some_and(RevealPhase::fading) + } + + #[inline] + pub(in crate::runtime) fn reveal_caught_up(&self, id: NodeId, len: usize) -> bool { + self.reveals.get(&id).is_some_and(|r| r.caught_up(len)) + } + + #[inline] + pub(in crate::runtime) fn reveal_fade(&self, id: NodeId) -> Option<reveal_phase::Fade<'_>> { + self.reveals.get(&id).and_then(RevealPhase::fade) + } + + #[inline] + pub(in crate::runtime) fn remove_reveal(&mut self, id: NodeId) { + self.reveals.remove(&id); + } + + #[inline] + pub(in crate::runtime) fn has_matched(&self) -> bool { + !self.matched.is_empty() + } + + #[inline] + pub(in crate::runtime) fn set_rewind(&mut self, rewind: Option<crate::rewind::Rewind>) { + self.rewind = rewind; + } + + #[cfg(test)] + #[inline] + pub(in crate::runtime) fn reveals_map(&self) -> &HashMap<NodeId, RevealPhase> { + &self.reveals + } + + #[cfg(test)] + #[inline] + pub(in crate::runtime) fn clear_reveals_for_test(&mut self) { + self.reveals.clear(); + self.reveal_chain = RevealChain::default(); + } + + #[cfg(test)] + #[inline] + pub(in crate::runtime) fn reveals_kept_len(&self) -> usize { + self.reveals_kept.len() + } + + #[cfg(test)] + #[inline] + pub(in crate::runtime) fn reveal_chain_until(&self) -> f64 { + self.reveal_chain.until() + } + + #[cfg(test)] + #[inline] + pub(in crate::runtime) fn matched_ids(&self) -> Vec<NodeId> { + self.matched.iter().map(|m| m.1).collect() + } + + /// Commits streaming word reveal state for node `id` during `apply`. + #[allow(clippy::too_many_arguments)] + pub(in crate::runtime) fn commit_reveal( + &mut self, + id: NodeId, + content: &str, + fade: f32, + now: f64, + time_scaled: bool, + was_present: bool, + instant: bool, + unprompted: bool, + virtual_mount: bool, + reduced_motion: bool, + ) { + use std::collections::hash_map::Entry; + // A text that has never faded here starts level with its content, or at none when + // it is entering. A state that outlived its node (an instant parent unmount keeps + // the reveal, and its path, for the child's return) keeps its words. + let mounted_late = !was_present && !instant && !unprompted && !virtual_mount; + let (st, vacant) = match self.reveals.entry(id) { + Entry::Occupied(st) => (st.into_mut(), false), + Entry::Vacant(st) => { + let shown = if mounted_late { 0 } else { content.len() }; + (st.insert(RevealPhase::Idle { shown }), true) + } + }; + let arrival = if instant || (!was_present && virtual_mount) || content.len() < st.shown() || !content.is_char_boundary(st.shown()) { + Arrival::Replaced + } else if !vacant { + Arrival::Kept + } else if mounted_late { + Arrival::Entering + } else { + Arrival::Landed + }; + let chain = if time_scaled { None } else { Some(&self.reveal_chain) }; + let effects = st.step(RevealEvent::Commit { + content, + fade, + arrival, + chain, + now, + reduced_motion, + }); + for effect in effects { + match effect { + RevealEffect::Started(at) => self.reveal_chain.started(at), + } + } + } + + /// Reconciles loop tracks after a commit, catching running loops up on the app clock first. + #[allow(clippy::too_many_arguments)] + pub(in crate::runtime) fn sync_loops( + &mut self, + nodes: &[Node], + scene: &Scene, + t: f64, + clock: f64, + time_scale: f32, + time_scaled: bool, + any_loop: bool, + land_loops: bool, + ) { + self.catch_loops_up(scene, t, clock, time_scale); + if any_loop || !self.loops.is_empty() { + for n in nodes { + let t = if time_scaled { scene.store().node_time(n.id) } else { t }; + if let Some(&spec) = n.looping.as_deref() { + let start = self.loop_start(scene, n.id, t); + let track = self.loops.entry(n.id).and_modify(|l| { l.retime(spec, t); l.enabled(true, t); }) + .or_insert_with(|| rune_motion::LoopTrack::new(spec, start)); + if land_loops { track.finish(); } + } else if let Some(l) = self.loops.get_mut(&n.id) { + l.enabled(false, t); + } + } + } + } + + /// Writes each active slide loop's current offset into `scene` before stepping tracks. + pub(in crate::runtime) fn step_loops_into_scene( + &self, + nodes: &[Node], + node_index: &NodeIndex, + scene: &mut Scene, + reduced_motion: bool, + ) { + for (id, track) in &self.loops { + if let Some([x, y]) = track.offset(scene.store().node_time(*id), reduced_motion) + && let Some(n) = node_index.get(id).map(|&i| &nodes[i]) + { + let offset = rune_motion::Vec2::new(x * n.local.w, y * n.local.h); + if scene.get(*id, prop::OFFSET) != Some(offset) { + scene.set(*id, prop::OFFSET, offset); + } + } + } + } + + /// Drops landed matched/launch flights from `flying` and `launches`; returns whether any left. + pub(in crate::runtime) fn prune_landed_flights(&mut self, scene: &Scene) -> bool { + if self.flying.is_empty() { + return false; + } + let before = self.flying.len(); + // Screen travel ends once it lands and no ancestor still moves. An exiting flight + // stays lifted until it's gone. + self.flying.retain(|(id, _)| scene.store().has(*id, prop::TRAVEL) + || matches!(scene.phase(*id), Some(PresencePhase::Exiting { .. }))); + if self.flying.len() != before { + self.launches.keep(&self.flying); + true + } else { + false + } + } + + /// Keeps at most the newest `limit` reveal states for texts that have left `node_index`, + /// dropping the oldest first. + pub(in crate::runtime) fn cap_reveals(&mut self, node_index: &NodeIndex, limit: usize) { + if self.reveals.is_empty() { + self.reveals_kept.clear(); + return; + } + // A text's reveal state and the id its path maps to outlive the node, so a keyed child + // that comes back under its old path keeps its words (r349). Nodes dropped during an + // instant parent unmount leave their reveal behind, so bound those orphans here. + let mut kept = std::mem::take(&mut self.reveals_kept); + kept.retain(|id| self.reveals.contains_key(id) && !node_index.contains_key(id)); + let mut gone: Vec<NodeId> = self.reveals.keys().copied() + .filter(|id| !node_index.contains_key(id) && !kept.contains(id)) + .collect(); + if !gone.is_empty() { + gone.sort_unstable_by(|a, b| b.cmp(a)); + gone.append(&mut kept); + kept = gone; + } + if kept.len() > limit { + for id in kept.split_off(limit) { self.reveals.remove(&id); } + } + self.reveals_kept = kept; + } + + /// Prunes loop, reveal, flying and launch entries for detached nodes. + pub(in crate::runtime) fn prune_detached( + &mut self, + scene: &Scene, + node_index: &NodeIndex, + reveals_limit: usize, + ) { + if !self.loops.is_empty() { + self.loops.retain(|id, _| scene.contains(*id)); + } + self.cap_reveals(node_index, reveals_limit); + // A flight that left the tree stays lifted and covered while it exits, so it doesn't pop. + self.flying.retain(|(id, _)| node_index.contains_key(id)); + self.launches.keep(&self.flying); + } + + /// Advances all reveal phases against `scene`'s node clocks; returns whether any are still fading. + pub(in crate::runtime) fn reveals_active(&mut self, scene: &Scene) -> bool { + let store = scene.store(); + let mut any = false; + for (id, st) in self.reveals.iter_mut() { + let now = store.node_time(*id); + st.step(RevealEvent::Tick { now }); + any |= st.fading() && store.node_time_scale(*id) > 0.0; + } + any + } + + /// Presented content extent of node `c` if it is a growth stack (points). + #[inline] + pub(in crate::runtime) fn stack_extent(&self, nodes: &[Node], c: usize) -> Option<f64> { + let n = &nodes[c]; + n.growth.as_ref()?; + let stack = self.stacks.get(&n.id)?; + let mut count = 0usize; + let rows: f64 = stack.order.iter().filter_map(|id| self.grows.get(id)).map(|g| { count += 1; f64::from(g.h) }).sum(); + let gaps = f64::from(stack.gap) * count.saturating_sub(1) as f64; + Some(f64::from(stack.pad_top) + rows + gaps + f64::from(stack.pad_bottom)) + } +} + +/// The (x, y) scroll offsets of node `i`'s scroll viewports, innermost first. +pub(in crate::runtime) fn scroll_offsets<'a>(scrolls: &'a HashMap<NodeId, ScrollState>, nodes: &'a [Node], i: usize) -> impl Iterator<Item = [f32; 2]> + 'a { + std::iter::successors(Some(i), |&p| nodes[p].parent.filter(|_| nodes[p].above.is_none())) + .skip(1) + .filter_map(|p| scrolls.get(&nodes[p].id).map(|st| [st.x.shift() as f32, st.offset as f32])) +} + +/// Marks every ancestor of a marked node. +pub(in crate::runtime) fn mark_ancestors(nodes: &[Node], marked: &mut [bool]) { + for i in 0..nodes.len() { + if !marked[i] { continue; } + let mut p = nodes[i].parent; + while let Some(j) = p { + if marked[j] { break; } + marked[j] = true; + p = nodes[j].parent; + } + } +} + +impl RuntimeCore { + pub(in crate::runtime) fn set_or_anim<T: rune_motion::Animatable>(&mut self, id: NodeId, p: Prop<T>, val: T, s: Spring, instant: bool) { + if instant { + self.scene.set(id, p, val); + } else { + self.scene.animate(id, p, val, s); + } + } + + pub(in crate::runtime) fn color(&self, id: NodeId, prop: Prop<Color>, rest: Color) -> Color { + if self.scene.store().is_animating(id, prop) { self.scene.get(id, prop).unwrap_or(rest) } else { rest } + } + + /// Shadow `k` of node `id` with its geometry where its spring has it. + pub(in crate::runtime) fn shadow_at(&self, id: NodeId, k: usize, sh: &crate::el::Shadow) -> crate::el::Shadow { + match P_SHADOW_GEO.get(k) { + Some(&prop) if self.scene.store().active_len() > 0 && self.scene.store().is_animating(id, prop) => match self.scene.get(id, prop) { + Some(g) => crate::el::Shadow { x: g.x, y: g.y, blur: g.w.max(0.0), spread: g.h, ..*sh }, + None => *sh, + }, + _ => *sh, + } + } + + pub(in crate::runtime) fn step_growth(&mut self, dt: f32) -> bool { + if self.motion.stacks.is_empty() { + return false; + } + // Frame time, stepped in whole substeps and the rest (`growth::substeps`). + let steps = crate::growth::substeps(dt); + let now = self.t; + let mut moving = false; + let mut placed = false; + let (mut restored, mut gave) = (Vec::new(), Vec::new()); + for (cid, stack) in self.motion.stacks.iter_mut() { + let Some(&ci) = self.tree.node_index.get(cid) else { continue }; + let Some(spec) = self.tree.nodes[ci].growth.as_deref().copied() else { continue }; + let n_rows = stack.order.len(); + let mut st_growing = !stack.pending_heights.is_empty(); + let mut st_moving = st_growing; + let (in_runs, run_grown) = MotionState::step_growth_runs(stack, &mut self.motion.grows, steps, spec); + stack.grown += run_grown; + for (k, id) in stack.order.iter().enumerate() { + let Some(g) = self.motion.grows.get_mut(id) else { continue }; + let h0 = g.h; + let in_run = in_runs.contains(id); + if let Some(&at) = stack.closing.get(id) + && now >= at + { + if self.reduced_motion { + *g = GrowTrack::settled(0.0); + } else { + g.retarget(0.0); + } + } + // A row above the tail (the last row) carries it. + let carrying = k + 2 == n_rows; + let mut left = dt.min(1.0); + for step in steps.filter(|_| !in_run) { + if !stack.pending_heights.is_empty() { + let at = now - f64::from(left); + if !stack.width_hold.defers(at) && let Some(height) = stack.pending_heights.remove(id) { + g.retarget(height); + } + } + g.step_by(step, spec.spring, &spec.edge, carrying); + left -= step; + } + // A row nobody saw last frame draws no feather: it has none to ease, and grows one + // again as it comes into view. + if g.mask > 0.0 && self.tree.built + && self.tree.node_index.get(id).is_some_and(|&i| !self.paint.was_seen(i, true)) + { + g.mask = 0.0; + } + let r = std::mem::take(&mut g.restore); + if r > 0.0 { restored.push((ci, *id, r)); } + if let Some(share) = g.give { gave.push((*id, (h0 - g.h) * share)); } + if !g.moving() { g.give = None; } + stack.grown += (g.h - h0).max(0.0); + st_growing |= g.target > g.h + 1.0 / 128.0; + st_moving |= g.moving() || (g.h - h0).abs() > 1e-5; + st_moving |= stack.slides.step(*id, g, spec.spring, steps); + } + stack.order.retain(|id| { + let keep = !stack.closing.contains_key(id) || self.motion.grows.get(id).is_some_and(|g| g.h > 0.01 || g.target > 0.0); + if !keep { + self.motion.grows.remove(id); + } + keep + }); + stack.closing.retain(|id, _| stack.order.contains(id)); + stack.slides.keep(&stack.order); + stack.growing = st_growing; + stack.moving = st_moving; + placed |= stack.handoff.place(&mut self.motion.grows, &mut self.scene, &self.tree.nodes, &self.tree.node_index, &mut self.scroll.scrolls); + // Keep the shared clock awake through the hold. No timer thread or remeasurement. + moving |= st_moving; + } + // Growth steps after Scene::frame. Scroll follow and painting must see this step's + // shared edge, even in a viewport with no scroll-offset callback to present it. + if placed { self.scene.present(); } + for (ci, id, r) in restored { self.restore_above(ci, id, r); } + for (id, d) in gave { self.lower_hold(id, d); } + moving + } + + /// Presented content extent of node `c` if it is a growth stack (points). + #[inline] + pub(in crate::runtime) fn stack_extent(&self, c: usize) -> Option<f64> { + self.motion.stack_extent(&self.tree.nodes, c) + } + + /// How far scroll viewport `i`'s content reaches past its bottom, negative while it fits. + pub(in crate::runtime) fn scroll_overflow(&self, i: usize) -> f64 { + let view = self.tree.nodes[i].target; + let content_h = self.scroll_children(i).map(|c| { + let n = &self.tree.nodes[c]; + f64::from(n.target[1] - view[1]) + self.stack_extent(c).unwrap_or(f64::from(n.target[3] - n.target[1])) + }).reduce(f64::max).unwrap_or(0.0); + content_h - f64::from(view[3] - view[1]) + } + + pub(in crate::runtime) fn step_scroll(&mut self, dt: f32) -> bool { self.step_scroll_by(dt, false) } + + /// Steps every scroll viewport `dt` seconds on: a frame's own step, or (`catch_up`) the time + /// it charges to motion that was already running (`frame::clock::split`). + pub(in crate::runtime) fn step_scroll_by(&mut self, dt: f32, catch_up: bool) -> bool { + let slack_dt = std::mem::take(&mut self.motion.slack_dt); + let scale = f64::from(self.env.scale * self.zoom()); + // Motion reduced mid-ease: a wheel's ease lands where it was going, at once. + let land_wheels = !self.wheel_glides(); + let mut moving = false; + for i in 0..self.tree.nodes.len() { + let Some(sp) = self.tree.nodes[i].scroll else { continue }; + if self.subtree_exiting(i) { continue; } + let id = self.tree.nodes[i].id; + let axes = self.tree.nodes[i].scroll_axes; + if axes.x() { moving |= self.step_scroll_x(i, dt, catch_up); } + // A horizontal viewport doesn't move vertically, even with content taller than it. + let overflow = if axes.y() { self.scroll_overflow(i) } else { 0.0 }; + if let Some(active) = self.step_touch_scroll(id, overflow, dt, false) { + moving |= active; + continue; + } + let held = !self.scroll.requests.is_empty() && { + let path = &self.tree.nodes[i].path; + self.scroll.requests.owns(path) + && self.scroll_stack(i).and_then(|c| self.motion.stacks.get(&self.tree.nodes[c].id)).is_some_and(|s| s.growing) + }; + let laid = if axes.y() { self.ease_to_shrunk_end(i, overflow) } else { None }; + let Some(st) = self.scroll.scrolls.get_mut(&id) else { continue }; + let _ = scroll_mode::step(&mut st.mode, ModeEvent::Step { x_v: st.x.coast() }); + st.max = overflow.max(0.0); + match st.mode { + ScrollMode::Pinned(_) if sp.stick_bottom => { + // A reader stuck on a shrinking stack's end doesn't rise with its rows' last fraction. + st.offset = laid.filter(|&end| st.offset <= end + 1e-6).map_or(st.max, |end| st.max.min(end)); + } + ScrollMode::Glide { .. } => moving |= scroll_bottom::glide(st, dt), + ScrollMode::Momentum { v, .. } if v.abs() > 1.0 => { + // Exact for exponential decay, so a long frame carries the same distance as + // the short frames it stands for. + let decay = (-SCROLL_DECAY * dt).exp(); + st.offset += f64::from(v * (1.0 - decay) / SCROLL_DECAY); + let edge = st.offset <= 0.0 || st.offset >= st.max; + st.mode = if edge { st.mode.to_rest() } else { st.mode.to_momentum(v * decay) }; + moving = true; + } + ScrollMode::Momentum { .. } => st.mode = st.mode.to_rest(), + ScrollMode::Wheel { mut curve, .. } => { + curve.follow(st.offset); + // An end that shrank under the ease takes its target with it; one that grew does + // too when the wheel was sent to the end of a viewport that follows its bottom + // (a reply streaming in), so it lands there and pins. + if curve.target() > st.max || (sp.stick_bottom && curve.to_end() && curve.target() < st.max) { curve.retarget(st.max, scale); } + if land_wheels { curve.advance(f64::INFINITY, false) } else { curve.advance(f64::from(dt), catch_up) } + // On whole device pixels, as Chromium's scroll offsets are: everything inside + // moves by the same whole pixels each frame and draws as it did, rather than + // landing at a new fraction of a pixel every frame. + st.offset = scroll_wheel::on_grid_or_end(curve.value(), st.max, scale); + curve.applied(st.offset); + // The hand moved it: the app hears a wheel's ease as the wheel. + st.moved(); + // An ease sent to a following viewport's end pins the frame it gets there, though + // the end growing under it restarts its segment every frame a reply grows. + let pins = sp.stick_bottom && curve.to_end() && st.offset == st.max; + if curve.done() || pins { st.land(sp.stick_bottom) } else { st.mode = st.mode.to_wheel(curve); moving = true; } + } + ScrollMode::Pinned(_) | ScrollMode::Rest(_) => {} + } + st.offset = st.offset.clamp(0.0, st.max); + // Landed on a shrinking stack's new end: stick once its rows are within half a point + // of it, not while they're still short of it. A glide that reaches the end hands it + // to the pin. + let shrinking = laid.is_some_and(|end| end < st.max - 0.5 && st.offset < st.max - 1e-3); + if sp.stick_bottom && !held && !shrinking && st.glide().is_none() && st.mode.wheel().is_none() && st.offset >= st.max - 0.5 && st.coast().abs() <= 1.0 { + st.pin(); + } + let _ = scroll_mode::step(&mut st.mode, ModeEvent::Laid(laid)); + if sp.stick_bottom && axes.y() && slack_dt > 0.0 { moving |= self.step_slack(i, slack_dt); } + } + moving + } +} diff --git a/app/vendor/rune/crates/rune/src/runtime/motion/unseen_presence.rs b/app/vendor/rune/crates/rune/src/runtime/motion/unseen_presence.rs new file mode 100644 index 0000000..0849884 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/motion/unseen_presence.rs @@ -0,0 +1,188 @@ +//! Presence nobody would see. A removed node that drew nothing last frame has no exit to show: it +//! faded out already, sits under a parent that hid at once, or lies out of the window or its +//! clips with everything it holds (a filtered list's rows scrolled out of view). It goes at +//! once rather than fading where nothing shows; what mounts out of sight enters at once, and a +//! node out of sight before and after (or transparent, or under a clip with no area) lands its +//! layout and colours. Likewise a virtual row that +//! a change mounted with its entrance but that landed out of view lands its entrance at once, +//! and one nobody saw that a filter brings into view enters like the rows new to it. +use super::*; +use crate::el::Flow; + +impl RuntimeCore { + /// Per node of the last build: neither it nor anything under it drew. Empty before the first + /// build and after a commit, until the next one draws. + pub(in crate::runtime) fn drew_nothing(&self) -> Vec<bool> { + if !self.tree.built || self.paint.seen().len() != self.tree.nodes.len() || self.paint.inh_scratch.len() != self.tree.nodes.len() { + return Vec::new(); + } + let mut seen = self.paint.seen().to_vec(); + mark_ancestors(&self.tree.nodes, &mut seen); + seen.iter().zip(&self.paint.inh_scratch).map(|(&seen, h)| !seen || h.opacity < 1.0 / 512.0).collect() + } + + /// How tall growth row `id` can be, in its own points, before its bottom passes the bottom + /// of its clip (a scroll's viewport, the window), from where and how big it last drew + /// (`El::fold_glide`); unbounded before it draws. + pub(in crate::runtime) fn fold_limit(&self, id: NodeId) -> f32 { + if !self.tree.built || self.paint.drawn.len() != self.tree.nodes.len() { return f32::INFINITY; } + let Some(i) = self.tree.nodes.iter().position(|n| n.id == id) else { return f32::INFINITY }; + let Some(h) = self.motion.grows.get(&id).map(|g| g.h).filter(|&h| h > 0.5) else { return f32::INFINITY }; + let d = self.paint.drawn[i]; + let k = d[3] / h; + if !(k > 0.01) { return f32::INFINITY; } + let bottom = (self.screen_clip_of_parent(self.tree.nodes[i].parent)[3] / self.env.scale).min(self.viewport.1); + h + (bottom - d[1] - d[3]) / k + } + + /// Node `i` of the commit is out of sight before and after (`unseen_before_and_after`), so + /// its entrance, colours and blur land. A matched element still flies to its match. + pub(in crate::runtime) fn enters_unseen(&self, nodes: &[Node], unseen: &[bool], i: usize) -> bool { + unseen.get(i).copied().unwrap_or(false) && nodes[i].matched.is_none() + } + + /// Ends the exits that drew nothing last frame. A flight paints outside its clips, so it stays. + pub(in crate::runtime) fn end_unseen_exits(&mut self) { + if !self.tree.built { return; } + let mut hid: Option<Vec<bool>> = None; + for i in 0..self.tree.nodes.len() { + let id = self.tree.nodes[i].id; + let faded = self.paint.inh_scratch.get(i).is_some_and(|h| h.opacity < 1.0 / 512.0); + if (!faded && self.paint.was_seen(i, true)) || !self.is_exiting(id) || self.motion.flying.iter().any(|f| f.0 == id) { + continue; + } + if hid.get_or_insert_with(|| self.drew_nothing()).get(i).copied().unwrap_or(false) { + self.scene.unmount(id); + } + } + } + + /// Row `i` of the commit's `nodes`, kept by a change that replaced what the reader saw + /// ([`crate::el::virtual_list::VirtualList::replaced_view`]) but drawn nowhere before, enters + /// like the rows new to the view instead of appearing whole. + pub(in crate::runtime) fn reenter_unseen_row(&mut self, nodes: &[Node], i: usize, unseen: &HashSet<NodeId>) { + if !unseen.contains(&nodes[i].id) { return; } + let Some(p) = nodes[i].parent else { return }; + let Some(v) = self.commit.virtuals.get_mut(&nodes[p].path) else { return }; + let Some(key) = nodes[i].path.strip_prefix(nodes[p].path.as_str()).and_then(|k| k.strip_prefix('/')) else { return }; + if !v.replaced_view() { return; } + v.entering.insert(key.to_owned()); + self.scene.reenter(nodes[i].id); + } + + /// Virtual rows mounted with their entrance have just drawn once: the ones out of view land. + /// Its own fade starts a row at no opacity, so only where it drew counts, strictly: a row + /// touching its viewport's edge shows nothing. Runs after each draw, since a list filling its + /// window commits again on the frames that follow. + pub(in crate::runtime) fn land_unseen_entrances(&mut self) { + if self.commit.virtuals.values().all(|v| v.entering.is_empty()) { return; } + let s = self.env.scale; + let (w, h) = self.viewport; + let mut land = Vec::new(); + for (path, v) in &mut self.commit.virtuals { + for key in v.entering.drain() { + let Some(&id) = self.tree.path_ids.get(&format!("{path}/{key}")) else { continue }; + let Some(&i) = self.tree.node_index.get(&id) else { continue }; + let Some(&[x, y, rw, rh]) = self.paint.drawn.get(i) else { continue }; + let clip = screen_clip_of(self.tree.nodes[i].parent, &self.paint.inh_scratch, &self.paint.turn_scratch); + let shows = (x + rw).min(clip[2] / s).min(w) > x.max(clip[0] / s).max(0.0) + && (y + rh).min(clip[3] / s).min(h) > y.max(clip[1] / s).max(0.0); + if !shows { land.push(id); } + } + } + for id in land { self.scene.enter_now(id); } + } + + /// Per node of the new tree `nodes`: neither it nor anything under it drew in the last + /// build (out of sight or transparent), and none of its swept path lands in sight in this + /// layout (in the window, inside its clips, not transparent). Empty when nothing non-skipped + /// qualifies. + pub(in crate::runtime) fn unseen_before_and_after(&self, nodes: &[Node], skip: &[memo_reuse::CleanApplySpan]) -> Vec<bool> { + let seen: Vec<bool> = self.drew_nothing().into_iter().map(|nothing| !nothing).collect(); + // New nodes may mount out of sight however much drew. + let mounts = nodes.len() > self.tree.nodes.len(); + if seen.is_empty() || (!mounts && seen.iter().all(|&s| s)) { + return Vec::new(); + } + let any_active_unseen = self.tree.nodes.iter().zip(&seen).any(|(old, &s)| { + !s && self.tree.node_index.get(&old.id).is_some_and(|&ni| !memo_reuse::is_in_clean_spans(skip, ni)) + }); + if !any_active_unseen && !mounts { return Vec::new(); } + // Each new node's place in the last build, found walking both trees in step. + let mut last = paint_tracks::Finder::default(); + let olds: Vec<Option<usize>> = nodes.iter().map(|n| last.find(&self.tree.nodes, n.id)).collect(); + let window = [0.0, 0.0, self.viewport.0, self.viewport.1]; + // Per node: the swept clip and scroll-offset range its children are under, in points. + let mut inner = vec![(window, [0.0f32; 2], [0.0f32; 2]); nodes.len()]; + let mut after = vec![false; nodes.len()]; + // Per node: the opacity it rests at, its ancestors' included. A live opacity or a loop + // may show it whatever it rests at. + let mut alpha = vec![1.0f32; nodes.len()]; + for (i, n) in nodes.iter().enumerate() { + // A hover group's hidden actions (`El::group_opacity`) rest at their rest level. + let own = if n.looping.is_some() || n.live.iter().any(|b| b.property == crate::live::Property::Opacity) { 1.0 } else { n.vis.opacity * n.vis.group_opacity.map_or(1.0, |g| g[0].max(0.0)) }; + alpha[i] = own * n.parent.filter(|&p| p < i).map_or(1.0, |p| alpha[p]); + let (clip, shift_min, shift_max) = match n.parent { + Some(p) if n.above.is_none() && p < i => inner[p], + Some(_) if n.above.is_none() => { after[i] = true; (window, [0.0; 2], [0.0; 2]) } + _ => (window, [0.0; 2], [0.0; 2]), + }; + // A stuck element draws where it's held, not where scrolling puts it: its shift last + // frame brings it, and everything it holds, back into its viewport (a header's + // ticking number mounts in sight there). + let (shift_min, shift_max) = match olds[i].filter(|_| self.tree.has_sticky).and_then(|o| self.scroll.stuck.get(o).filter(|s| **s != 0.0).map(|&s| (o, s))) { + Some((o, s)) => { + let axis = usize::from(!matches!(self.sticky_of(o), Some((crate::el::StickyEdge::Left, ..)))); + let (mut lo, mut hi) = (shift_min, shift_max); + lo[axis] -= s; + hi[axis] -= s; + (lo, hi) + } + None => (shift_min, shift_max), + }; + let t = n.target; + let r = [t[0] - shift_max[0], t[1] - shift_max[1], t[2] - shift_min[0], t[3] - shift_min[1]]; + let drew = olds[i].filter(|&o| { let t = self.tree.nodes[o].target; t[2] > t[0] || t[3] > t[1] }); + let swept = match drew.map(|o| self.drawn_edges(o)) { + Some(b) => [b[0].min(r[0]), b[1].min(r[1]), b[2].max(r[2]), b[3].max(r[3])], + None => r, + }; + // Under a clip with no area nothing draws, shadows included. + // Room for its shadows, blur and a focus ring, which draw past its rect. + let margin = n.vis.shadows.iter().filter(|s| !s.inset).map(|s| s.x.abs() + s.y.abs() + s.spread.max(0.0) + s.blur * 1.5).fold(0.0, f32::max) + n.vis.blur * 3.0 + + if n.focus.enabled { 4.0 } else { 0.0 }; + // A rect that only touches the clip's edge draws nothing inside it. + after[i] |= alpha[i] >= 1.0 / 512.0 && clip[2] > clip[0] && clip[3] > clip[1] + && swept[2] > clip[0] - margin && swept[0] < clip[2] + margin + && swept[3] > clip[1] - margin && swept[1] < clip[3] + margin; + let clip = if n.vis.clip.is_some() || n.scroll.is_some() { + intersect(clip, swept) + } else { clip }; + let (shift_min, shift_max) = match (self.scroll.scrolls.get(&n.id), n.scroll) { + (Some(st), Some(sp)) => { + let children = || (i + 1..nodes.len()).take_while(|&j| nodes[j].parent >= Some(i)).filter(|&j| nodes[j].parent == Some(i)); + let max_x = match (n.scroll_axes.x(), st.x.flow) { + (false, _) => 0.0, + (true, Flow::Ltr) => children().fold(0.0_f32, |m, c| m.max(nodes[c].target[2] - n.target[2])), + (true, Flow::Rtl) => children().fold(0.0_f32, |m, c| m.max(n.target[0] - nodes[c].target[0])), + }; + let max_y = if n.scroll_axes.y() { children().fold(0.0_f32, |m, c| m.max(nodes[c].target[3] - n.target[3])) } else { 0.0 }; + let ox0 = st.x.shift() as f32; + let ox1 = match st.x.flow { Flow::Ltr => ox0.clamp(0.0, max_x), Flow::Rtl => ox0.clamp(-max_x, 0.0) }; + let oy0 = st.offset as f32 + st.slack.height(); + let oy1 = if st.pinned() && sp.stick_bottom { max_y + st.slack.height() } else { oy0.clamp(0.0, max_y + st.slack.height()) }; + ( + [shift_min[0] + ox0.min(ox1), shift_min[1] + oy0.min(oy1)], + [shift_max[0] + ox0.max(ox1), shift_max[1] + oy0.max(oy1)], + ) + } + _ => (shift_min, shift_max), + }; + inner[i] = (clip, shift_min, shift_max); + } + mark_ancestors(nodes, &mut after); + // A node new out of sight (a ticking digit in a row scrolled out of view, a row mounting + // past its list's viewport) enters where nothing shows, so it lands at once too. + (0..nodes.len()).map(|i| !after[i] && olds[i].is_none_or(|o| !seen[o])).collect() + } +} diff --git a/app/vendor/rune/crates/rune/src/runtime/node_index.rs b/app/vendor/rune/crates/rune/src/runtime/node_index.rs new file mode 100644 index 0000000..59f6def --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/node_index.rs @@ -0,0 +1,52 @@ +//! Flat node positions by id. Sequential ids go straight to a slot without hashing. Size the +//! table from the tree being placed, not the largest id ever issued: a virtual list can mint +//! millions of ids with only a few dozen mounted. Old live ids sharing a slot go in `overflow`. +use super::{HashMap, NodeId}; + +#[derive(Default)] +pub(in crate::runtime) struct NodeIndex { + slots: Vec<(NodeId, usize)>, + overflow: HashMap<NodeId, usize>, + len: usize, +} + +impl NodeIndex { + pub(in crate::runtime) fn rebuild(&mut self, nodes: usize) { + self.slots.clear(); + self.slots.resize(nodes.next_power_of_two(), (NodeId(0), usize::MAX)); + self.overflow.clear(); + self.len = 0; + } + + pub(in crate::runtime) fn insert(&mut self, id: NodeId, i: usize) { + if self.slots.is_empty() { + self.slots.resize(1, (NodeId(0), usize::MAX)); + } + let at = id.0 as usize & (self.slots.len() - 1); + let slot = &mut self.slots[at]; + if slot.1 == usize::MAX { + *slot = (id, i); + self.len += 1; + } else if slot.0 == id { + slot.1 = i; + } else if self.overflow.insert(id, i).is_none() { + self.len += 1; + } + } + + #[inline] + pub(in crate::runtime) fn get(&self, id: &NodeId) -> Option<&usize> { + let (stored, i) = self.slots.get(id.0 as usize & self.slots.len().wrapping_sub(1))?; + if *stored == *id && *i != usize::MAX { Some(i) } + else if self.overflow.is_empty() { None } + else { self.overflow.get(id) } + } + + pub(in crate::runtime) fn contains_key(&self, id: &NodeId) -> bool { self.get(id).is_some() } + pub(in crate::runtime) fn len(&self) -> usize { self.len } +} + +impl std::ops::Index<&NodeId> for NodeIndex { + type Output = usize; + fn index(&self, id: &NodeId) -> &usize { self.get(id).expect("node not indexed") } +} diff --git a/app/vendor/rune/crates/rune/src/runtime/on_key_tests.rs b/app/vendor/rune/crates/rune/src/runtime/on_key_tests.rs new file mode 100644 index 0000000..34bcbf6 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/on_key_tests.rs @@ -0,0 +1,369 @@ +//! `El::on_key`, `El::icon_rotation`, `El::level` and `El::expanded`, `El::help_when_truncated` +//! and `Tx::mods`: what a virtualised tree or table needs from the core. +use super::*; +use crate::{Cx, El, Env, Icon, Key, KeyEvent, Mods, PhysicalInput, TextEdit, TextStyle, col, el, icon, row, text_input}; + +#[derive(Default)] +struct Keys { + log: Vec<String>, + field: TextEdit, + /// The outer handler takes Down too. + outer_down: bool, +} + +/// A focusable list that owns its keys (with a focus-group child row it must beat to the +/// arrows), inside an outer handler, beside a text field. +fn keyed(s: &Keys, _: &mut Cx<Keys>) -> El { + let rows = col().key("rows").role("listbox").focus_group().children((0..3).map(|i| { + row().key(format!("row{i}")).size(100.0, 20.0).focusable(true).on_press(move |s: &mut Keys| s.log.push(format!("press {i}"))) + })); + let list = col() + .key("list") + .role("tree") + .focusable(true) + .size(120.0, 80.0) + .on_key(|s: &mut Keys, ev: &KeyEvent, _: &mut Tx| { + let hit = matches!(ev.key, Key::Down | Key::Up); + if hit { + s.log.push(format!("list {:?}", ev.key)); + } + hit + }) + .child(rows); + let outer = col() + .key("outer") + .on_key(|s: &mut Keys, ev: &KeyEvent, _: &mut Tx| { + let hit = matches!(ev.key, Key::Down | Key::Left) && (ev.key == Key::Left || s.outer_down); + if hit { + s.log.push(format!("outer {:?}", ev.key)); + } + hit + }) + .child(list) + .child(text_input(&s.field, TextStyle::new(14.0, 400.0)).key("field").size(200.0, 30.0).on_edit(|s: &mut Keys| &mut s.field)); + col().size(300.0, 200.0).child(el().key("pad").size(300.0, 10.0)).child(outer) +} + +fn press(rt: &mut Runtime<Keys>, key: Key) { + rt.key(KeyEvent { key, mods: Mods::default() }); + rt.frame(0.0); +} + +fn focused<S: 'static>(rt: &Runtime<S>) -> Option<String> { + rt.elements().into_iter().find(|e| e.focused).and_then(|e| e.key) +} + +fn center<S: 'static>(rt: &Runtime<S>, key: &str) -> (f32, f32) { + let r = rt.elements().into_iter().find(|e| e.key.as_deref() == Some(key)).unwrap().rect; + (r[0] + r[2] * 0.5, r[1] + r[3] * 0.5) +} + +fn click<S: 'static>(rt: &mut Runtime<S>, (x, y): (f32, f32)) { + rt.pointer_down(x, y); + rt.pointer_up(x, y); + rt.frame(0.0); +} + +#[test] +fn a_keyed_control_takes_its_keys_before_focus_navigation_innermost_first() { + let mut rt = Runtime::new(Keys::default(), keyed, (300.0, 200.0), Env::new(true, 1.0)); + rt.frame(0.0); + press(&mut rt, Key::Tab); + assert_eq!(focused(&rt).as_deref(), Some("list"), "Tab reaches a control that owns its keys, without Full Keyboard Access"); + rt.state.outer_down = true; + press(&mut rt, Key::Down); + press(&mut rt, Key::Left); + assert_eq!(rt.state.log, ["list Down", "outer Left"], "the list answers Down before the outer handler; Left falls through to it"); + assert_eq!(focused(&rt).as_deref(), Some("list"), "focus navigation never saw the arrow"); +} + +#[test] +fn a_focused_text_field_keeps_its_keys() { + let mut rt = Runtime::new(Keys::default(), keyed, (300.0, 200.0), Env::new(true, 1.0)); + rt.frame(0.0); + rt.update(|s, _| s.field.focused = true); + rt.frame(0.0); + press(&mut rt, Key::Left); + press(&mut rt, Key::Text("a".into())); + assert!(rt.state.log.is_empty(), "{:?}", rt.state.log); + assert_eq!(rt.state.field.text, "a"); +} + +#[test] +fn a_click_inside_a_keyed_control_focuses_it() { + #[derive(Default)] + struct S { + pressed: u32, + } + fn view(_: &S, _: &mut Cx<S>) -> El { + col().size(300.0, 200.0).child( + col() + .key("table") + .focusable(true) + .size(200.0, 100.0) + .on_key(|_: &mut S, _: &KeyEvent, _: &mut Tx| false) + .child(row().key("row").size(200.0, 20.0).on_press(|s: &mut S| s.pressed += 1)), + ) + } + let mut rt = Runtime::new(S::default(), view, (300.0, 200.0), Env::new(true, 1.0)); + rt.frame(0.0); + let at = center(&rt, "row"); + click(&mut rt, at); + assert_eq!(rt.state.pressed, 1); + assert_eq!(focused(&rt).as_deref(), Some("table"), "the row's click focuses the table, not nothing"); +} + +#[test] +fn a_press_sees_the_modifiers_held() { + #[derive(Default)] + struct S { + seen: Vec<Mods>, + } + fn view(_: &S, _: &mut Cx<S>) -> El { + col().size(100.0, 100.0).child(el().key("b").size(100.0, 100.0).on_press_tx(|s: &mut S, tx: &mut Tx| s.seen.push(tx.mods()))) + } + let mut rt = Runtime::new(S::default(), view, (100.0, 100.0), Env::new(true, 1.0)); + rt.frame(0.0); + click(&mut rt, (50.0, 50.0)); + let shift = Mods { shift: true, ..Mods::default() }; + rt.physical_input(PhysicalInput::Modifiers(shift)); + rt.frame(0.0); + click(&mut rt, (50.0, 50.0)); + rt.physical_input(PhysicalInput::Modifiers(Mods::default())); + rt.frame(0.0); + click(&mut rt, (50.0, 50.0)); + assert_eq!(rt.state.seen, [Mods::default(), shift, Mods::default()]); +} + +#[test] +fn icon_rotation_springs_and_jumps_under_reduced_motion() { + struct S { + open: bool, + } + fn view(s: &S, _: &mut Cx<S>) -> El { + static CHEVRON: Icon = Icon { name: "test-chevron", view: 16.0, body: r#"<path d="M5 6.5L8 9.5L11 6.5" stroke="currentColor"/>"# }; + col().size(100.0, 100.0).child( + icon(&CHEVRON, 16.0) + .key("chevron") + .color(Color::WHITE) + .icon_rotation(if s.open { 0.0 } else { -std::f32::consts::FRAC_PI_2 }) + .motion(crate::tok::motion::DEFAULT), + ) + } + fn turn(rt: &Runtime<S>) -> f32 { + rt.instances.iter().find(|q| q.params[1] == KIND_GLYPH).expect("the chevron draws").params[0] + } + let quarter = -std::f32::consts::FRAC_PI_2; + for reduced in [false, true] { + let mut rt = Runtime::new(S { open: false }, view, (100.0, 100.0), Env::new(true, 1.0)); + rt.set_system_reduced_motion(reduced); + rt.frame(0.0); + assert!((turn(&rt) - quarter).abs() < 1e-4, "a closed chevron starts turned, without animating in"); + rt.update(|s, _| s.open = true); + rt.frame(1.0 / 60.0); + rt.frame(2.0 / 60.0); + let mid = turn(&rt); + if reduced { + assert!(mid.abs() < 1e-4, "reduced motion lands at once: {mid}"); + } else { + assert!(mid < -0.05 && mid > quarter + 0.05, "two frames in, the turn is on its way: {mid}"); + } + for f in 3..120 { + rt.frame(f as f64 / 60.0); + } + assert!(turn(&rt).abs() < 1e-3, "it settles open"); + + // Mounting open (`0.0`) and then closing (`-FRAC_PI_2`) must also spring from 0.0. + let mut rt = Runtime::new(S { open: true }, view, (100.0, 100.0), Env::new(true, 1.0)); + rt.set_system_reduced_motion(reduced); + rt.frame(0.0); + assert!(turn(&rt).abs() < 1e-4, "an open chevron starts at 0"); + rt.update(|s, _| s.open = false); + rt.frame(1.0 / 60.0); + rt.frame(2.0 / 60.0); + let mid = turn(&rt); + if reduced { + assert!((mid - quarter).abs() < 1e-4, "reduced motion lands closed at once: {mid}"); + } else { + assert!(mid < -0.05 && mid > quarter + 0.05, "two frames in, closing is on its way: {mid}"); + } + } +} + +#[test] +fn a_modal_stops_keys_from_bubbling_to_an_ancestors_on_key() { + #[derive(Default)] + struct S { + outer_keys: u32, + } + fn view(_: &S, _: &mut Cx<S>) -> El { + col() + .size(200.0, 200.0) + .on_key(|s: &mut S, _: &KeyEvent, _: &mut Tx| { + s.outer_keys += 1; + true + }) + .child( + col() + .key("dialog") + .modal(true, |_: &mut S| {}) + .size(100.0, 100.0) + .child(el().key("inside").focusable(true).size(50.0, 20.0)), + ) + } + let mut rt = Runtime::new(S::default(), view, (200.0, 200.0), Env::new(true, 1.0)); + rt.frame(0.0); + rt.key(KeyEvent { key: Key::Tab, mods: Mods::default() }); + rt.frame(0.0); + assert_eq!(focused(&rt).as_deref(), Some("inside")); + rt.key(KeyEvent { key: Key::Down, mods: Mods::default() }); + rt.frame(0.0); + assert_eq!(rt.state.outer_keys, 0, "an on_key ancestor outside the modal must not see keys inside it"); +} + +#[test] +fn outline_state_reaches_the_element_tree() { + fn view(_: &(), _: &mut Cx<()>) -> El { + col() + .size(200.0, 100.0) + .role("tree") + .child(row().key("folder").role("treeitem").level(1).expanded(true).focus_selected(true).size(200.0, 20.0)) + .child(row().key("file").role("treeitem").level(2).size(200.0, 20.0)) + } + let mut rt = Runtime::new((), view, (200.0, 100.0), Env::new(true, 1.0)); + rt.frame(0.0); + let e = rt.elements(); + let get = |k: &str| e.iter().find(|e| e.key.as_deref() == Some(k)).unwrap(); + let (folder, file) = (get("folder"), get("file")); + assert_eq!((folder.level, folder.expanded, folder.item_selected), (Some(1), Some(true), true)); + assert_eq!((file.level, file.expanded, file.item_selected), (Some(2), None, false)); +} + +#[cfg(target_os = "macos")] +#[test] +fn a_truncation_tooltip_shows_only_while_the_text_is_cut() { + struct S { + w: f32, + } + fn view(s: &S, _: &mut Cx<S>) -> El { + col().size(400.0, 100.0).child( + row().size(s.w, 20.0).child( + crate::text("A rather long file name.rs").key("cell").font(TextStyle::new(13.0, 400.0)).truncate().shrink().help_when_truncated("A rather long file name.rs"), + ), + ) + } + let mut rt = Runtime::new(S { w: 60.0 }, view, (400.0, 100.0), Env::new(true, 1.0)); + rt.set_native_help(true); + rt.frame(0.0); + assert_eq!(rt.help_regions().len(), 1, "cut short, the cell offers its whole text"); + assert_eq!(rt.elements().into_iter().find(|e| e.key.as_deref() == Some("cell")).unwrap().help.as_deref(), Some("A rather long file name.rs")); + rt.update(|s, _| s.w = 380.0); + rt.frame(0.0); + assert!(rt.help_regions().is_empty(), "the whole text shows, so no tooltip"); + assert_eq!(rt.elements().into_iter().find(|e| e.key.as_deref() == Some("cell")).unwrap().help, None); +} + +#[cfg(target_os = "macos")] +#[test] +fn a_faded_text_that_runs_past_its_box_reads_as_cut() { + struct S { + w: f32, + } + fn view(s: &S, _: &mut Cx<S>) -> El { + col().size(400.0, 100.0).child( + row().size(s.w, 20.0).child( + crate::text("A rather long file name.rs").key("cell").font(TextStyle::new(13.0, 400.0)).truncate_fade().shrink().help_when_truncated("A rather long file name.rs"), + ), + ) + } + let mut rt = Runtime::new(S { w: 60.0 }, view, (400.0, 100.0), Env::new(true, 2.0)); + rt.set_native_help(true); + rt.frame(0.0); + let i = rt.tree.nodes.iter().position(|n| n.key.as_deref() == Some("cell")).unwrap(); + assert!(rt.tree.nodes[i].text_cut(2.0) && rt.tree.nodes[i].elided.is_none(), "a fade cuts nothing out of the layout"); + assert_eq!(rt.help_regions().len(), 1, "faded out, the cell offers its whole text"); + assert_eq!(rt.elements().into_iter().find(|e| e.key.as_deref() == Some("cell")).unwrap().help.as_deref(), Some("A rather long file name.rs")); + rt.update(|s, _| s.w = 380.0); + rt.frame(0.0); + assert!(rt.help_regions().is_empty(), "the whole text shows, so no tooltip"); + assert_eq!(rt.elements().into_iter().find(|e| e.key.as_deref() == Some("cell")).unwrap().help, None); +} + +/// Two lists keyed alike, side by side, each in its own scope. +fn twins(_: &(), _: &mut Cx<()>) -> El { + let list = |scope: &str| { + col().key(scope.to_owned()).w(100.0).h(200.0).child( + col().key("viewport").w_full().h_full().scroll(crate::ScrollSpec { stick_bottom: false }).child( + col().key("rows").w_full().growth(crate::GrowthSpec::default()).virtual_rows(1000, 20.0, + |_: &(), i| std::borrow::Cow::Owned(format!("r{i}")), + |_: &(), _| el().w_full().h(20.0)), + ), + ) + }; + row().child(list("a")).child(list("b")) +} + +#[test] +fn scroll_into_view_in_reveals_only_inside_its_scope() { + let mut rt = Runtime::new((), twins, (200.0, 200.0), Env::new(true, 1.0)); + rt.frame(0.0); + let offset = |rt: &Runtime<()>, scope: &str| { + let id = rt.tree.path_ids[&format!("#0/{scope}/viewport")]; + rt.scroll.scrolls[&id].offset + }; + rt.update(|_, tx| tx.scroll_into_view_in("b", "r500")); + rt.frame(0.0); + assert_eq!(offset(&rt, "a"), 0.0, "the other list keeps still"); + assert!(offset(&rt, "b") > 9000.0, "{}", offset(&rt, "b")); + rt.update(|_, tx| tx.scroll_into_view_in("a", "r900")); + rt.frame(0.0); + assert!(offset(&rt, "a") > 17_000.0 && offset(&rt, "b") < 10_100.0, "{} {}", offset(&rt, "a"), offset(&rt, "b")); +} + +#[test] +fn key_handler_removals_fade_by_default_and_unmount_at_once_with_tx_instant() { + struct S { + shown: bool, + instant: bool, + } + fn view(s: &S, _: &mut Cx<S>) -> El { + let mut root = col().size(200.0, 100.0).focusable(true).on_key(|s: &mut S, ev, tx| { + if ev.key == Key::Escape { + s.shown = false; + if s.instant { + tx.instant(); + } + return true; + } + false + }); + if s.shown { + root = root.child(el().key("banner").size(80.0, 24.0)); + } + root + } + + // Default key-handler commit: the removed element fades out over its default opacity transition. + let mut rt = Runtime::new(S { shown: true, instant: false }, view, (200.0, 100.0), Env::new(true, 1.0)); + rt.frame(0.0); + rt.key(KeyEvent { key: Key::Tab, mods: Mods::default() }); + rt.frame(1.0 / 60.0); + rt.key(KeyEvent { key: Key::Escape, mods: Mods::default() }); + assert!(rt.frame(1.0 / 60.0), "default removal animates the exit fade"); + assert!( + rt.elements().iter().any(|e| e.key.as_deref() == Some("banner")), + "banner stays mounted in the scene while fading out" + ); + + // With `tx.instant()` in the key handler, the removed element unmounts in the same frame. + let mut rt = Runtime::new(S { shown: true, instant: true }, view, (200.0, 100.0), Env::new(true, 1.0)); + rt.frame(0.0); + rt.key(KeyEvent { key: Key::Tab, mods: Mods::default() }); + rt.frame(1.0 / 60.0); + rt.key(KeyEvent { key: Key::Escape, mods: Mods::default() }); + assert!(!rt.frame(1.0 / 60.0), "tx.instant() unmounts with no exit fade"); + assert!( + !rt.elements().iter().any(|e| e.key.as_deref() == Some("banner")), + "banner is gone in the commit frame" + ); +} diff --git a/app/vendor/rune/crates/rune/src/runtime/paint.rs b/app/vendor/rune/crates/rune/src/runtime/paint.rs new file mode 100644 index 0000000..f8efdde --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/paint.rs @@ -0,0 +1,23 @@ +//! Paint pass, reuse cache, pixel snapping, layer caches, text/shape/border/shadow/band painting +//! and retained paint state. +use super::*; + +pub(super) mod bands; +pub(super) mod blend; +pub(super) mod border; +pub(super) mod build; +pub(super) mod cache_layer; +pub(super) mod content; +pub(super) mod exit_mask; +pub(super) mod grid; +pub(super) mod helpers; +pub(super) mod keep; +pub(super) mod pixel_snap; +pub(super) mod raster_check; +pub(super) mod shadow; +pub(super) mod shape; +pub(super) mod slots; +pub(super) mod soft_edges; +pub(super) mod state; +pub(super) mod text_flights; +pub(super) mod tracks; diff --git a/app/vendor/rune/crates/rune/src/runtime/paint/bands.rs b/app/vendor/rune/crates/rune/src/runtime/paint/bands.rs new file mode 100644 index 0000000..7416b98 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/paint/bands.rs @@ -0,0 +1,43 @@ +//! A blurred shadow under an opaque box, and a border with nothing inside it, cover a quad that +//! shows nothing in its middle. Drawn whole, a window-sized panel's shadow shades every pixel of +//! the panel each frame. Past a size they draw as four bands around that middle instead: `uv` +//! gives each band's window relative to the rect, `[x0, y0, -x1, y1]` (a negative `uv.z` marks +//! it; shader.wgsl `base_vs`), and each band shades exactly what the whole quad did there. +use crate::render::{Instance, corner_extent}; + +/// The middle must be at least this many device pixels both ways for bands to pay. +const MIN_HOLE: f32 = 96.0; + +/// Pushes the outer shadow `inst` of an opaque box at `caster` (device px, x y w h) with +/// corner `radii` (negative for continuous corners): the box hides the shadow inside it. +pub(in crate::runtime) fn push_shadow(out: &mut Vec<Instance>, inst: Instance, caster: [f32; 4], radii: [f32; 4]) { + let e = radii.map(corner_extent).into_iter().fold(0.0, f32::max) + 1.0; + let (x, y) = (caster[0] - inst.rect[0], caster[1] - inst.rect[1]); + push(out, inst, [x + e, y + e, x + caster[2] - e, y + caster[3] - e], inst.params[2] * 3.0 + 1.0); +} + +/// Pushes the border-only `inst` (its fill clear): nothing draws past its ring. +pub(in crate::runtime) fn push_ring(out: &mut Vec<Instance>, inst: Instance) { + let e = inst.radii.map(corner_extent).into_iter().fold(0.0, f32::max) + inst.params[0] + inst.params[2].max(0.5) + 1.0; + let [_, _, w, h] = inst.rect; + push(out, inst, [e, e, w - e, h - e], 1.0 + inst.params[2] * 2.0); +} + +/// `inst` whole, or as bands around `hole` (x0 y0 x1 y1 relative to its rect) when that's big +/// enough. `grow` is how far the shader grows the quad past the rect. +fn push(out: &mut Vec<Instance>, inst: Instance, hole: [f32; 4], grow: f32) { + let [hx0, hy0, hx1, hy1] = hole; + let [qx0, qy0, qx1, qy1] = [-grow, -grow, inst.rect[2] + grow, inst.rect[3] + grow]; + // The left band's right edge carries the mark as its sign, so it must be past the origin. + if hx1 - hx0 < MIN_HOLE || hy1 - hy0 < MIN_HOLE || hx0 < 1.0 || hy0 <= qy0 || hx1 >= qx1 || hy1 >= qy1 || inst.uv != [0.0; 4] { + out.push(inst); + return; + } + for [x0, y0, x1, y1] in [[qx0, qy0, qx1, hy0], [qx0, hy0, hx0, hy1], [hx1, hy0, qx1, hy1], [qx0, hy1, qx1, qy1]] { + out.push(Instance { uv: [x0, y0, -x1, y1], ..inst }); + } +} + +#[cfg(test)] +#[path = "../bands_tests.rs"] +mod tests; diff --git a/app/vendor/rune/crates/rune/src/runtime/paint/blend.rs b/app/vendor/rune/crates/rune/src/runtime/paint/blend.rs new file mode 100644 index 0000000..8abc0fd --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/paint/blend.rs @@ -0,0 +1,146 @@ +//! How a runtime's colours blend and its glyphs rasterise: sRGB or linear-light blending, +//! the font smoothing mode, and the per-glyph instances they shape. + +use super::*; +use crate::text::FontSmoothing; + +impl RuntimeCore { + /// Enable or disable gamma-space (sRGB) blending for translucent fills, shadows, blurs, + /// images and video, as `App::srgb_blend` does for a window. Every colour the next frame + /// builds, hover and press tints included, is premultiplied in sRGB encoding + /// (`Color::premul_srgb`). A runtime drawn by the app itself (`Runtime::with_text`, a + /// headless snapshot) then draws with `Renderer::set_srgb_blend(true)` into a non-sRGB + /// target (`format.remove_srgb_suffix()`), cleared to `clear_color()`. + pub fn set_srgb_blend(&mut self, enabled: bool) { + if self.paint.set_srgb_blend(enabled) { + self.commit.dirty = true; + } + } + + pub fn srgb_blend(&self) -> bool { + self.paint.srgb_blend() + } + + pub fn fade_stops(&self) -> [f32; 2] { + self.tree.fade_stops + } + + /// Rasterise and place glyphs in `mode` from the next frame, as `App::font_smoothing` does + /// for a window. Glyphs already rasterised in another mode stay cached for a switch back. + /// Blending is separate: both modes match CoreText with [`Self::set_srgb_blend`] on. + pub fn set_font_smoothing(&mut self, mode: FontSmoothing) { + if self.text.font_smoothing() != mode { + self.text.set_font_smoothing(mode); + self.commit.dirty = true; + } + } + + pub fn font_smoothing(&self) -> FontSmoothing { + self.text.font_smoothing() + } + + pub fn clear_color(&self) -> [f32; 4] { + if self.transparent { return [0.0; 4]; } + self.tree.nodes.get(self.app_root()).map_or([0.0, 0.0, 0.0, 1.0], |n| { + let c = self.color(n.id, P_FILL, n.vis.fill); + if self.paint.srgb_blend { + [srgb_encode(c.r), srgb_encode(c.g), srgb_encode(c.b), 1.0] + } else { + [c.r, c.g, c.b, 1.0] + } + }) + } +} + +pub(crate) fn glyph_uv_page(uv: [f32; 2]) -> ([f32; 2], f32) { + let page = (uv[1] as u32) / crate::text::ATLAS_SIZE; + ([uv[0], uv[1] - (page * crate::text::ATLAS_SIZE) as f32], page as f32) +} + +pub(crate) fn glyph(q: &GlyphQuad, fill: [f32; 4], clip: [f32; 4], fade: [f32; 4]) -> Instance { + if let Some(o) = q.outline { + // `text::Outline`'s layout: radii.w > 0 tells the shader to read the outline store. + return Instance { + rect: q.rect, + radii: [o.pen[0], o.pen[1], o.scale, o.zoom], + fill, + border: [o.record as f32, o.hint as f32, o.radius, o.coverage as f32], + params: [0.0, KIND_GLYPH, 0.0, 1.0], + uv: [0.0; 4], + clip, + fade: crate::render::pack_fade(fade, clip, clip), + }; + } + let (uv, page) = glyph_uv_page(q.uv); + Instance { + rect: q.rect, + // `radii.x` marks a subpixel mask, three texels a pixel (outline.wgsl's `lcd_mask`). + radii: [q.lcd as u8 as f32, 0.0, 0.0, 0.0], + fill, + border: [0.0; 4], + params: [0.0, KIND_GLYPH, page, 1.0], + uv: [uv[0], uv[1], 0.0, 0.0], + clip, + fade: crate::render::pack_fade(fade, clip, clip), + } +} + +/// An icon's `KIND_GLYPH` instance at `pos` with drawn side `drawn`. At an unrotated, whole-pixel +/// 1:1 placement it loads texels directly (`span == 0`); when fractional, scaled or turned it +/// expands one texel into the icon's transparent atlas border so bilinear filtering neither clips +/// at `KIND_GLYPH`'s quad edge nor bleeds across the shelf gutter. +pub(crate) fn icon_inst( + q: &GlyphQuad, + pos: [f32; 2], + drawn: f32, + turn: f32, + fill: [f32; 4], + clip: [f32; 4], + fade: [f32; 4], +) -> Instance { + let (uv, page) = glyph_uv_page(q.uv); + let px = q.rect[2].max(1.0); + let near = |v: f32| (v - v.round()).abs() < 1.0 / 512.0; + let (rect, uv) = if turn == 0.0 && near(pos[0]) && near(pos[1]) && (drawn - px).abs() < 1.0 / 512.0 { + ([pos[0].round(), pos[1].round(), px, px], [uv[0], uv[1], 0.0, 0.0]) + } else { + let t = drawn / px; + ( + [pos[0] - t, pos[1] - t, drawn + 2.0 * t, drawn + 2.0 * t], + [uv[0] - 1.0, uv[1] - 1.0, px + 2.0, px + 2.0], + ) + }; + Instance { + rect, + radii: [0.0; 4], + fill, + border: [0.0; 4], + params: [turn, KIND_GLYPH, page, 1.0], + uv, + clip, + fade: crate::render::pack_fade(fade, clip, clip), + } +} + +/// An icon instance's place in the atlas (`uv.xy` and page), which no text glyph shares. +pub(crate) fn apron_key(i: &Instance) -> [u32; 3] { + [i.uv[0].to_bits(), i.uv[1].to_bits(), i.params[2].to_bits()] +} + +pub(crate) fn premul(c: Color, opacity: f32, srgb: bool) -> [f32; 4] { + if srgb { c.premul_srgb(opacity) } else { c.premul(opacity) } +} + +/// The transfer curve maps linear 1 to encoded 1 exactly. The f32 power formula at that +/// endpoint yields 0.99999994: half white would round to RGB 127 but alpha 128, darkening +/// even white over white. Preserve the authored endpoint before the two painters take their +/// byte steps. This isn't a near-white threshold or a change to gradient interpolation. +pub(in crate::runtime) fn flat_base(c: Color, srgb: bool, translucent: bool) -> [f32; 4] { + let mut rgba = premul(c, 1.0, srgb); + if srgb && translucent { + for (channel, linear) in rgba[..3].iter_mut().zip([c.r, c.g, c.b]) { + if linear == 1.0 { *channel = c.a; } + } + } + rgba +} diff --git a/app/vendor/rune/crates/rune/src/runtime/paint/border.rs b/app/vendor/rune/crates/rune/src/runtime/paint/border.rs new file mode 100644 index 0000000..b31d940 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/paint/border.rs @@ -0,0 +1,49 @@ +//! Painter-stream instances for what CSS layers between an element's background and its border: +//! the fill drawn on its own under the ring, and inset shadows inside the border +//! (`El::border`, `El::box_shadow`). +use super::*; + +/// `rect` and its signed `radii` brought in by `by` device pixels on each side, `[top, right, +/// bottom, left]`; each corner's radius shrinks by the wider of its two sides, as the inner +/// edge of a CSS border does. +pub(in crate::runtime) fn inset_box(rect: [f32; 4], radii: [f32; 4], by: [f32; 4]) -> ([f32; 4], [f32; 4]) { + let [t, r, b, l] = by; + let cut = [t.max(l), t.max(r), b.max(r), b.max(l)]; + ( + [rect[0] + l, rect[1] + t, (rect[2] - l - r).max(0.0), (rect[3] - t - b).max(0.0)], + std::array::from_fn(|k| (radii[k].abs() - cut[k]).max(0.0).copysign(radii[k])), + ) +} + +/// The fill of the bordered box `boxed` (its `ring` instance with the fill set) drawn without +/// its ring, which then draws over what goes between. With `shrink`, an opaque border all round +/// a rounded box pulls it in by half the border's width, as the shader does for a fill and ring +/// drawn together (shader.wgsl `border_over`), and as Chromium's bleed avoidance does. +pub(in crate::runtime) fn fill_under(boxed: Instance, shrink: bool) -> Instance { + let [bw, kind, soft, o] = boxed.params; + let opaque = |c: [f32; 4]| c[3] / o.clamp(1e-6, 1.0) > 0.999; + let uniform = kind == KIND_GRADIENT || boxed.uv == [0.0; 4]; + let hides = opaque(boxed.border) && (kind != KIND_GRADIENT || opaque(boxed.uv)); + let (rect, radii) = if shrink && uniform && hides && boxed.radii != [0.0; 4] { + inset_box(boxed.rect, boxed.radii, [bw * 0.5; 4]) + } else { + (boxed.rect, boxed.radii) + }; + Instance { rect, radii, border: [0.0; 4], params: [0.0, KIND_RECT, soft, o], uv: [0.0; 4], ..boxed } +} + +/// The inset shadow `sh` in premultiplied `fill`, inside the box `inner` (the padding box, so +/// inside any border). `scale` is device pixels per point and the window's scale. +pub(in crate::runtime) fn inset_shadow(sh: &crate::el::Shadow, fill: [f32; 4], inner: ([f32; 4], [f32; 4]), scale: (f32, f32), clip: [f32; 4], fade: [f32; 4]) -> Instance { + let (k_px, s) = scale; + Instance { + rect: inner.0, + radii: inner.1, + fill, + border: [0.0; 4], + params: [sh.spread * k_px, KIND_INSET, if sh.blur > 0.0 { (sh.blur * s * 0.5).max(0.5) } else { 0.0 }, 1.0], + uv: [sh.x * k_px, sh.y * k_px, 0.0, 0.0], + clip, + fade: crate::render::pack_fade(fade, clip, clip), + } +} diff --git a/app/vendor/rune/crates/rune/src/runtime/paint/build.rs b/app/vendor/rune/crates/rune/src/runtime/paint/build.rs new file mode 100644 index 0000000..820dcdb --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/paint/build.rs @@ -0,0 +1,709 @@ +//! Frame paint pass: `Scene` presented poses, clips, layers and text → GPU `Instance`s. +use super::*; + +mod layers; +mod pose; +mod primitives; + +impl RuntimeCore { + pub(in crate::runtime) fn build(&mut self) -> bool { + let (_paint_time, _blend) = (crate::frame::profile::Scope::new(crate::frame::profile::Phase::Paint), crate::theme::scope(self.paint.srgb_blend)); + let s = self.env.scale; + let snap_px = |v: f32| grid(v, s) * s; + self.keep_swap(); + self.instances.clear(); + self.paint.quads_frame += 1; + // Quads a text hasn't drawn with for a while go, with the layouts they hold. + if self.paint.quads_frame % 64 == 0 { + let frame = self.paint.quads_frame; + self.paint.text_quads.retain(|_, (_, used)| frame - *used < 64); + } + let mut pinned_pages = 0u32; + for f in self.motion.flights() { + for q in &f.glyphs { + if q.params[1] == KIND_GLYPH { + pinned_pages |= 1u32 << (q.params[2] as u32).min(31); + } + } + } + if let Some(after) = self.text.begin_frame_pinned(pinned_pages) { + self.schedule_wakes([after]); + } + self.marks.clear(); + self.paint.icon_aprons.clear(); + self.surfaces.clear(); + self.paint.materials.clear(); + self.hit.hits.clear(); + self.hit.wheel_hits.clear(); + self.clear_help_hits(); + self.clear_drop_hits(); + self.motion.reset_loops_active(); + self.paint.scale_frame = None; + self.paint.videos_active = false; + self.paint.animated_icons = false; + self.paint.animated_icons_shown = false; + self.paint.node_animated_icon = false; + self.paint.icon_anim_wake = None; + let now = crate::time::now(); + let video_clock = match self.wall_start { + None => crate::video::Clock::Virtual(self.clock), + Some(_) => crate::video::Clock::Display(self.frame.frame_target().filter(|t| *t > now).unwrap_or(now)), + }; + let mut video_signature = 0u64; + self.motion.clear_loop_wake(); + self.hit.overlay_hits.clear(); + let n_nodes = self.tree.nodes.len(); + self.paint.inh_scratch.clear(); + self.paint.turn_scratch.clear(); + self.paint.unturned_drawn.clear(); + self.paint.inh_scratch.resize(n_nodes, Inh::default()); + self.paint.drawn.clear(); + self.paint.drawn.resize(n_nodes, [0.0; 4]); + self.paint.drawn_scale.clear(); + self.paint.drawn_scale.resize(n_nodes, 1.0); + self.paint.seen.clear(); + self.paint.seen.resize(n_nodes, false); + self.scroll.stuck.clear(); + self.scroll.sticky_bands.clear(); + self.scroll.sticky_frame.clear(); + if self.tree.has_sticky { + self.scroll.stuck.resize(n_nodes, 0.0); + self.scroll.sticky_frame.resize(n_nodes, sticky::UNBOUNDED); + } + let sel_ranges = self.selection_ranges(); + let mark_ranges = self.mark_ranges(); + self.ime_area = None; + self.edit.ime_option_as_alt = false; + let now = self.t; + let vp = [0.0, 0.0, self.viewport.0 * s, self.viewport.1 * s]; + let mut glyph_count = 0usize; + let mut backdrop_blurs = 0usize; + let mut ambient: Option<f32> = None; + // Retain scope capacity across frames. Records preserve absolute instance indices + // for images, video insertions, retained springs and compositor list ranges. + let mut layers = std::mem::take(&mut self.paint.layer_scratch); + layers.clear(); + + self.paint.prepare_dissolve(&self.tree, &self.scene, &self.motion, self.clock, self.reduced_motion, self.kbd.focus.keyboard(), self.kbd.focus.path()); + + let paint_state_hash = self.prepare_cache_layers(&sel_ranges, &mark_ranges); + + self.place_growth_rows(); + + let flying = !self.motion.flying.is_empty(); + let tree_order = self.paint.needs_tree_order(&self.tree, &self.scene, flying); + let default_ring = self.default_ring_owner(); + self.keep_begin(tree_order, vp, default_ring, &sel_ranges, &mark_ranges); + let mut active_cache: Option<ActiveCache> = None; + self.paint.pixel_snap.begin_frame(self.t, [vp[2], vp[3]]); + // One past the subtree the last one copied from the last paint. + let mut skip_to = 0; + for paint_index in 0..n_nodes { + if paint_index < skip_to { continue; } + let i = if tree_order { self.paint.layer_paint_order[paint_index] } else { paint_index }; + if let Some(rank) = self.paint.paint_rank.as_mut() { + rank.resize(n_nodes, 0); + rank[i] = paint_index as u32; + } + let node_id = self.tree.nodes[i].id; + let node_parent = self.tree.nodes[i].parent; + // A flight paints outside every ancestor's layer, above the whole window. + let lift = flying && self.motion.flying.iter().any(|f| f.0 == node_id); + let raised = (self.tree.nodes[i].vis_flags.raise() || (tree_order && self.paint.is_lifted_anchor(i))) && !lift; + if lift || raised { + self.paint.close_all_layers(&self.tree.nodes, &mut self.instances, &mut self.surfaces, &mut self.marks, self.track_marks, &mut self.text, self.commit.commit_gen(), &mut layers, &mut active_cache, &mut glyph_count); + } + self.keep_close(Some(node_parent), &mut layers, &mut active_cache, &mut glyph_count); + self.paint.close_layers_to_parent(&self.tree.nodes, &mut self.instances, &mut self.surfaces, &mut self.marks, self.track_marks, &mut self.text, self.commit.commit_gen(), node_parent, &mut layers, &mut active_cache, &mut glyph_count); + self.keep_open(i, glyph_count, &sel_ranges, &mark_ranges); + let n = &self.tree.nodes[i]; + let Some(p) = self.scene.presented(n.id) else { continue }; + let mut pinh = n.parent.map_or_else(|| self.root_inh(), |pr| self.paint.inh_scratch[pr]); + if pinh.anchor_hidden { + self.paint.inh_scratch[i] = pinh; + self.paint.drawn[i] = [0.0; 4]; + self.paint.seen[i] = false; + self.keep_painted(i, false); + continue; + } + // A stuck header's title (its first child) fades as the next header comes up. + if pinh.first_fade < 1.0 && n.parent.is_some_and(|pr| pr + 1 == i) { + pinh.opacity *= pinh.first_fade; + pinh.paint_opacity *= pinh.first_fade; + } + pinh.first_fade = 1.0; + // `El::stuck_reveal`: shown as far as its sticky parent has held. + if let Some(span) = n.sticky.as_ref().and_then(|s| s.reveal) + && let Some(pr) = n.parent + { + let held = if self.tree.has_sticky { self.scroll.stuck.get(pr).map_or(0.0, |s| s.abs()) } else { 0.0 }; + let shown = (held / span).clamp(0.0, 1.0); + pinh.opacity *= shown; + pinh.paint_opacity *= shown; + } + pinh.dy += self.paint.row_dy[i]; + pinh.snap.grow(self.paint.row_dy[i]); + if let Some(a) = self.tree.nodes[i].above.clone() { + if let Some(j) = anchor_index_live(&self.tree.nodes, i, &a, |idx| self.subtree_exiting(idx)) { + let saved = self.anchored_inh(i, j, &a, &p, &mut pinh); + self.paint.last_anchor_targets.insert(node_id, saved); + } else if self.subtree_exiting(i) + && let Some((target, k)) = self.paint.last_anchor_targets.get(&node_id).copied() + { + self.anchored_inh_at(i, &a, target, k, ScaleMotion::Still, &p, &mut pinh); + } else { + // Never draw an anchored overlay at (0, 0) when its anchor cannot be resolved. + let path = self.tree.nodes[i].path.clone(); + if self.paint.unresolved_anchor_warnings.insert((path.clone(), a.key.clone())) { + eprintln!("rune: anchored overlay {path:?} could not resolve anchor {:?}; suppressed (never drawn at origin)", a.key); + } + pinh.anchor_hidden = true; + pinh.opacity = 0.0; + pinh.paint_opacity = 0.0; + pinh.hit_opacity = 0.0; + self.paint.inh_scratch[i] = pinh; + self.paint.drawn[i] = [0.0; 4]; + self.paint.seen[i] = false; + self.keep_painted(i, false); + continue; + } + } + let kids_fade = if self.tree.has_sticky { + self.apply_sticky_inh(i, node_parent, &p, &mut pinh) + } else { + 1.0 + }; + if let Some(len) = self.keep_or_paint(i, &pinh, &mut glyph_count) { + skip_to = paint_index + len; + continue; + } + if raised { + self.paint.reopen_raised_layers(&self.tree.nodes, &self.scene, &mut self.instances, self.surfaces.len(), node_parent, &mut pinh, &mut layers, s); + } + if lift { + self.motion.lift_flight_inh(&self.paint, &self.scene, self.commit.commit_gen(), node_id, node_parent, &mut pinh); + } + let n = &self.tree.nodes[i]; + let mark = if n.vis.mark != 0 { n.vis.mark } else { pinh.mark }; + let mut own = p.opacity; + let mut hit_own = own * group_factor(&self.scene, self.kbd.focus.keyboard(), self.kbd.focus.path(), n, 1.0); + own *= group_factor(&self.scene, self.kbd.focus.keyboard(), self.kbd.focus.path(), n, pinh.group); + let base_opacity = (own * pinh.opacity).clamp(0.0, 1.0); + let hover_owner = n.vis.hover().a > 0.0 || n.vis_flags.hover_group(); + let group = if hover_owner { + self.scene.get(n.id, P_HOVER).unwrap_or(0.0).clamp(0.0, 1.0) + } else { + pinh.group + }; + let (pressed, press_to) = match n.vis.cold.get().and_then(|c| c.press_color) { + Some(c) => (self.scene.get(n.id, P_PRESS).unwrap_or(0.0).clamp(0.0, 1.0), Some(c)), + None => (pinh.pressed, pinh.press_to), + }; + // Loops and reveals run on the node's clock (`El::time_scale`). + let track = self.motion.loop_track(n.id); + let lnow = if track.is_some() { self.scene.store().node_time(n.id) } else { self.t }; + let loop_value = track.map(|l| l.sample_at(lnow, self.clock, self.reduced_motion)); + if fades(n.looping.as_deref().copied()) && let Some(v) = loop_value { + own *= v; + hit_own *= v; + } + let effective_opacity = (own * pinh.opacity).clamp(0.0, 1.0); + let hit_opacity = (hit_own * pinh.hit_opacity).clamp(0.0, 1.0); + let next = if tree_order { self.paint.layer_paint_order.get(paint_index + 1).copied() } else { (i + 1 < n_nodes).then_some(i + 1) }; + let dissolve = self.tree.has_dissolve && self.paint.dissolve_scratch[i]; + let additive_parent = self.tree.has_dissolve && n.parent.is_some_and(|p| self.paint.dissolve_scratch[p]); + // `El::layer_opacity` fades paint only; hit testing and what elements report keep + // `own`. + let paint_own = own * n.vis.layer_opacity; + // A fading node with children, or a shape whose pieces overlap, takes its opacity + // once as a layer rather than each primitive taking it over the ones beneath. So + // does a layer opacity over two paints of the node's own (a label on its fill). + let mut isolate = effective_opacity > 0.001 && (p.blur > 0.0 || dissolve + || additive_parent || (paint_own > 0.001 && paint_own < 1.0 + && (next.is_some_and(|j| self.tree.nodes[j].parent == Some(i)) || n.vis.shape.as_ref().is_some_and(|s| s.overlaps()) + || (n.vis.layer_opacity < 1.0 && own_paints(n) >= 2)))); + let (mut clip, mut fade) = (pinh.paint_clip, pinh.paint_fade); + let mut fade_origin = pinh.paint_fade_origin; + let mut rounded = pinh.rounded; + let has_press_scale = n.handlers.get().is_some_and(|h| h.press_scale.is_some()); + let press_k = if has_press_scale { self.scene.get(n.id, P_PRESS_SCALE).unwrap_or(1.0) } else { 1.0 }; + let sequence = track + .filter(|_| matches!(n.looping.as_ref().map(|l| l.kind), Some(rune_motion::LoopKind::Sequence(_)))); + let static_k = if n.scale_track { self.scene.get(n.id, P_SCALE).unwrap_or(n.static_scale) } else { n.static_scale }; + let own_sc = p.transform.scale.x * press_k * static_k + * sequence.and_then(|l| l.pose(lnow, self.reduced_motion)).map_or(1.0, |p| p.scale); + // An `El::scale` or `El::live_scale` an app drives from a slider, wheel or pinch + // counts as moving until it holds still, then rasterizes crisp at its resting scale. + let has_live_scale = n.live.iter().any(|b| b.property == crate::live::Property::Scale); + let tracked_scale = if has_live_scale { static_k * p.transform.scale.x } else { static_k }; + let scale_settling = if tracked_scale != 1.0 || has_live_scale || self.paint.static_scales.contains_key(&n.id) { + pose::step_static_scale(&mut self.paint.static_scales, &mut self.paint.scale_frame, n.id, tracked_scale, self.t, self.settled, has_live_scale) + } else { false }; + let store = self.scene.store(); + let scale_animating = store.is_animating(n.id, prop::SCALE) || store.is_animating(n.id, prop::PRESENCE) + || (has_press_scale && store.is_animating(n.id, P_PRESS_SCALE)) + || (n.scale_track && store.is_animating(n.id, P_SCALE)) + || sequence.is_some_and(|l| !self.reduced_motion && l.active(lnow)); + let scale_motion = pinh.scale_motion.max( + if !has_live_scale && (scale_animating || scale_settling) { + ScaleMotion::Moving + } else if has_live_scale && (scale_settling || scale_animating) { + ScaleMotion::Live + } else { + ScaleMotion::Still + }); + // Scale about this node's centre where its ancestors' scales put it, so a scaled child + // of a scaled parent stays in place. + let sc = pinh.scale * own_sc; + let pivot = match n.vis.origin { + Some([ox, oy]) => [p.rect.x + ox * p.rect.w, p.rect.y + oy * p.rect.h], + None => [p.anchor.x, p.anchor.y], + }; + let centre = [pivot[0] + pinh.dx, pivot[1] + pinh.dy]; + let centre_to = [pinh.anchor_to[0] + (centre[0] - pinh.anchor[0]) * pinh.scale, + pinh.anchor_to[1] + (centre[1] - pinh.anchor[1]) * pinh.scale]; + let (anchor, anchor_to) = if (own_sc - 1.0).abs() > 1e-5 { (centre, centre_to) } else { (pinh.anchor, pinh.anchor_to) }; + // A pressed element still hits at its resting size, so a press near its edge stays inside. + let press_anchor = centre_to; + let blur = pinh.blur + p.blur * sc; + // An effect slot's bleed can reach into view from a rect outside it. + let filter_margin = blur * s * 3.0 + n.vis.effect.map_or(0.0, |e| e.bleed * sc * s); + + let mut raw_edges = p.rect.edges(); + raw_edges[0] += pinh.dx; + raw_edges[2] += pinh.dx; + raw_edges[1] += pinh.dy; + raw_edges[3] += pinh.dy; + if self.paint.row_h[i] >= 0.0 { + raw_edges[3] = raw_edges[1] + self.paint.row_h[i]; + } + if self.tree.has_sticky { + pose::update_sticky_frame(&mut self.scroll.sticky_frame, i, n, raw_edges); + } + // A product of 1 (0.5 inside 2.0) can still move the box. + let mut rect_pt = if (sc - 1.0).abs() > 1e-5 || anchor != anchor_to { + [ + anchor_to[0] + (raw_edges[0] - anchor[0]) * sc, + anchor_to[1] + (raw_edges[1] - anchor[1]) * sc, + anchor_to[0] + (raw_edges[2] - anchor[0]) * sc, + anchor_to[1] + (raw_edges[3] - anchor[1]) * sc, + ] + } else { + raw_edges + }; + // Land a sub-quantum size residual before snapping both edges. Otherwise a + // translating/scaling box can alternate between neighbouring widths at rest. + for (axis, target) in [n.local.w, n.local.h].into_iter().enumerate() { + let target = grid(target, s); + if ((rect_pt[axis + 2] - rect_pt[axis]) - target).abs() * s < 1.0 / 32.0 { + rect_pt[axis + 2] = rect_pt[axis] + target; + } + } + // A matched flight scales its laid-out content uniformly to cover the moving rect, + // centred: `k` and the centring offset in points. A launch flies at its own size. + let cover = if lift && n.local.w > 0.0 && n.local.h > 0.0 { + pose::flight_cover(self.motion.launches(), node_id, n, rect_pt) + } else { None }; + let r_exact = rect_pt.map(snap_px); + // A node the visibility test below culls paints nothing, and any clip it hands down is + // off screen too, so it keeps its exact edges. + let rigid = pinh.snap.rigid.map(|v| v * s); + // What a stepped window holds glides with its slide; the window itself snaps as a still box, + // and its clip glides along the slide only (`slide_anchor`). + let can_snap = !pinh.snap.off && !n.vis_flags.no_pixel_snap() && p.transform.rotate == 0.0 + && !(paint_state::PaintState::slide_glides(&self.tree.nodes, &self.motion, self.reduced_motion, i) + && !paint_state::PaintState::slide_pair(&self.tree.nodes, &self.motion, i)); + let snaps = can_snap && (pinh.in_cache || { + let m = filter_margin + 2.0; + r_exact[2].max(r_exact[0]) >= clip[0].max(vp[0]) - m && r_exact[0] <= clip[2].min(vp[2]) + m + && r_exact[3].max(r_exact[1]) >= clip[1].max(vp[1]) - m && r_exact[1] <= clip[3].min(vp[3]) + m + }); + let unscaled = (sc - 1.0).abs() <= 1e-5 && anchor == anchor_to; + let animating = p.flags & (rune_motion::flags::ANIMATED | rune_motion::flags::ANCESTOR_ANIMATED) != 0; + // A node with its own scale, or an anchored overlay inheriting its anchor's zoom after + // `anchored_inh` cleared `snap.layer`, heads a scaled snap layer so its subtree snaps + // onto whole pixels once still. + let opens_snap_layer = (own_sc - 1.0).abs() > 1e-5 || (n.above.is_some() && !unscaled); + let snap_layer = if can_snap && opens_snap_layer { + self.paint.pixel_snap.layer(n.id, (r_exact, raw_edges.map(snap_px)), rigid, pinh.in_cache || n.vis_flags.cache()) + } else { + pinh.snap.layer + }; + let steps = pinh.snap.steps || n.vis.cold.get().is_some_and(|c| c.motion_snaps); + let rest = if snaps && animating && !steps { self.scene.rest(n.id) } else { None }; + let gliding = snaps && (rest.is_some() || !unscaled); + let (mut r, snap_rest) = if !snaps { + (r_exact, None) + } else if rest.is_none() && unscaled { + self.paint.pixel_snap.at_rest(n.id, r_exact, rigid, pinh.snap.parent) + } else { + let motion = pixel_snap::motion(&p, rest, s, n.above.is_some(), self.paint.row_h[i] >= 0.0); + let raw = if unscaled { r_exact } else { raw_edges.map(snap_px) }; + self.paint.pixel_snap.snapped(n.id, motion, (r_exact, raw), rigid, (snap_layer, sc), pinh.snap.parent) + }; + let hairline_alpha = if n.vis.cold.get().is_some_and(|c| c.hairline) { + let (hr, a) = pixel_snap::hairline(r, r_exact); + r = hr; + a + } else { + 1.0 + }; + let (w, h) = ((r[2] - r[0]).max(0.0), (r[3] - r[1]).max(0.0)); + // `El::rotate`: this subtree draws into a layer turned about its origin. + // The layer takes the clips from above; the node's own clips apply inside, upright. + let own_turn = p.transform.rotate; + let own_turn = (own_turn != 0.0 && own_turn.is_finite() && own_turn.abs() > 1e-6 && !lift).then_some(own_turn); + let turn_pivot = [centre_to[0] * s, centre_to[1] * s]; + let (node_turn, turn_index) = if pinh.turn == 0 && own_turn.is_none() { + (None, 0) + } else { + let mut outer_clip = intersect(pinh.clip, clip); + if let Some((mask, _)) = rounded { outer_clip = intersect(outer_clip, mask); } + compose_turn(&mut self.paint.turn_scratch, pinh.turn, own_turn, ([r[0], r[1], w, h], turn_pivot, outer_clip)) + }; + if let Some(angle) = own_turn { + if !pinh.skip_paint { + open_turned_layer(&mut self.instances, &mut layers, (i, self.surfaces.len()), [r[0], r[1], w, h], + (angle, turn_pivot), (&mut clip, &mut fade, &mut fade_origin, &mut rounded)); + } else { + (clip, fade, fade_origin, rounded) = (NO_CLIP, [0.0; 4], NO_CLIP, None); + } + pinh.clip = NO_CLIP; + pinh.fade = [0.0; 4]; + pinh.fade_origin = NO_CLIP; + } + // Where the node shows on screen, upright: the turned box's bounds. + let mut screen_r = [r_exact[0], r_exact[1], r_exact[2].max(r_exact[0]), r_exact[3].max(r_exact[1])]; + if let Some(t) = node_turn { screen_r = t.bbox(screen_r); } + self.paint.drawn[i] = [screen_r[0] / s, screen_r[1] / s, (screen_r[2] - screen_r[0]) / s, (screen_r[3] - screen_r[1]) / s]; + if cover.is_none() { self.paint.drawn_scale[i] = sc; } + let radii = p.radius.0.map(|v| v * sc * s); + + if !p.mask.is_none() { + let ins = p.mask.inset.0.map(|v| v * sc * s); + let fea = p.mask.feather.0.map(|v| (v * sc * s).clamp(-65504.0, 65504.0)); + clip = [ + (r[0] + ins[0]).max(clip[0]), + (r[1] + ins[1]).max(clip[1]), + (r[2] - ins[2]).min(clip[2]), + (r[3] - ins[3]).min(clip[3]), + ]; + inherit_fade(&mut fade, &mut fade_origin, [r[0] + ins[0], r[1] + ins[1], r[2] - ins[2], r[3] - ins[3]], fea); + } + let m = filter_margin + 2.0; + let visible = match node_turn { + None => { + let vis_clip = if pinh.in_cache { intersect(pinh.clip, clip) } else { clip }; + // Under a clip with no area nothing draws, however near its edge. + vis_clip[2] > vis_clip[0] && vis_clip[3] > vis_clip[1] + && screen_r[2] >= vis_clip[0].max(vp[0]) - m + && screen_r[0] <= vis_clip[2].min(vp[2]) + m + && screen_r[3] >= vis_clip[1].max(vp[1]) - m + && screen_r[1] <= vis_clip[3].min(vp[3]) + m + } + Some(t) => { + let lc = intersect(pinh.clip, clip); + let oc = t.outer_clip; + r[2] >= lc[0] - m && r[0] <= lc[2] + m && r[3] >= lc[1] - m && r[1] <= lc[3] + m + && screen_r[2] >= oc[0].max(vp[0]) - m + && screen_r[0] <= oc[2].min(vp[2]) + m + && screen_r[3] >= oc[1].max(vp[1]) - m + && screen_r[1] <= oc[3].min(vp[3]) + m + } + }; + self.paint.seen[i] = visible; + + // A slide may sweep wholly outside its clip; judge visibility at its resting place. + let home = match n.looping.as_ref().map(|l| l.kind) { + Some(rune_motion::LoopKind::Slide { .. } | rune_motion::LoopKind::SlideEased { .. }) => { + let o = self.scene.get(n.id, prop::OFFSET).unwrap_or(rune_motion::Vec2::ZERO); + [r[0] - o.x * s, r[1] - o.y * s, r[2] - o.x * s, r[3] - o.y * s] + } + _ => r, + }; + // A loop at its brightest under one 8-bit step can't be seen: let it sleep. + let loop_vis = match node_turn { + None => home[2] > clip[0].max(vp[0] - filter_margin) && home[0] < clip[2].min(vp[2] + filter_margin) + && home[3] > clip[1].max(vp[1] - filter_margin) && home[1] < clip[3].min(vp[3] + filter_margin), + Some(t) => { + let lc = intersect(pinh.clip, clip); + let sh = t.bbox(home); + let oc = t.outer_clip; + home[2] > lc[0] - filter_margin && home[0] < lc[2] + filter_margin + && home[3] > lc[1] - filter_margin && home[1] < lc[3] + filter_margin + && sh[2] > oc[0].max(vp[0] - filter_margin) && sh[0] < oc[2].min(vp[2] + filter_margin) + && sh[3] > oc[1].max(vp[1] - filter_margin) && sh[1] < oc[3].min(vp[3] + filter_margin) + } + }; + if self.frame.live.visible() && base_opacity >= 1.0 / 255.0 && !self.reduced_motion && loop_vis { + self.motion.schedule_loop_wake(&mut self.paint, &self.scene, self.clock, self.time_scale, node_id, lnow, now, &mut ambient); + } + + let layers::LayerScope { + o, + skip_paint, + in_cache, + open_cache, + blur_hole, + glyphs_clear, + mut hit_clip, + mut hit_fade, + mut hit_origin, + primitive_start, + surface_start, + } = self.open_node_layers( + i, + s, + now, + &p, + &pinh, + r, + r_exact, + radii, + w, + h, + sc, + m, + effective_opacity, + paint_own, + visible, + dissolve, + lift, + own_turn, + node_turn.as_ref(), + next, + scale_motion, + vp, + paint_state_hash, + glyph_count, + &mut clip, + &mut fade, + &mut fade_origin, + &mut rounded, + &mut isolate, + &mut backdrop_blurs, + &mut layers, + &mut active_cache, + ); + + let first_instance = self.instances.len(); + let n = &self.tree.nodes[i]; + // Native input readiness follows focus, not entrance opacity. An input + // mounting at opacity zero still needs its IME area in this frame. + let input_caret = n.input.as_ref().filter(|input| input.edit.focused && self.can_focus(i)) + .filter(|_| !self.motion.flights().iter().any(|f| n.key.as_deref() == Some(&f.source_key) + && f.alphas(f.destination, now, self.reduced_motion).0 > 0.0)) + .and_then(|_| input_caret(n, r, sc, s, gliding, &mut self.edit.input_scroll)); + if let Some((_, area)) = input_caret + && n.input.as_ref().is_some_and(|input| !input.edit.is_secure()) { self.ime_area = Some(area); } + else if n.ime_cursor && self.ime_area.is_none() && self.allowed(i) && !self.subtree_exiting(i) { self.ime_area = Some(app_ime::area(r, s)); self.edit.ime_option_as_alt = n.ime_option_as_alt; } + let paint_visible = if in_cache { + r[2] >= clip[0] - filter_margin - 2.0 + && r[0] <= clip[2] + filter_margin + 2.0 + && r[3] >= clip[1] - filter_margin - 2.0 + && r[1] <= clip[3] + filter_margin + 2.0 + } else { + visible + }; + let painted = !skip_paint && effective_opacity > 0.001 && o > 0.001 && paint_visible; + debug_assert!(!pinh.anchor_hidden, "anchored overlay {:?} reached paint without a resolved anchor", n.path); + // Unpulled out of sight, a video still counts, so a scroll across a clip edge doesn't commit. + if !painted && let Some((surface, _)) = &n.vis.surface { video_signature = crate::video::fold_unpulled(video_signature, surface); } + self.paint.node_animated_icon = false; + let faded_slot = if painted { + self.paint_node_box( + i, + s, + now, + &pinh, + r, + r_exact, + raw_edges, + radii, + w, + h, + sc, + o * hairline_alpha, + effective_opacity, + base_opacity, + p.draw, + m, + clip, + fade, + fade_origin, + vp, + pressed, + press_to, + loop_value, + blur_hole, + cover, + scale_motion, + snap_rest.as_ref(), + next, + default_ring, + primitive_start, + mark, + isolate, + in_cache, + skip_paint, + loop_vis, + gliding, + node_turn.is_some(), + input_caret.map(|(caret, _)| caret), + video_clock, + &sel_ranges, + &mark_ranges, + &mut video_signature, + &mut glyph_count, + ) + } else { + None + }; + let packed_fade = crate::render::pack_fade(fade, fade_origin, clip); + for instance in &mut self.instances[first_instance..] { + instance.fade = packed_fade; + } + self.clip_text_instances(i, first_instance, (r, r_exact), sc, clip, fade, fade_origin); + let n = &self.tree.nodes[i]; + if let Some((_, radii)) = rounded { + for instance in &mut self.instances[primitive_start..] { + if glyphs_clear && instance.params[1] == KIND_GLYPH { continue; } + instance.round_clip_corners(radii); + } + let packed = crate::render::pack_clip_radii(clip, radii); + for surface in &mut self.surfaces[surface_start..] { surface.fade[3] = packed; } + } + // A faded effect slot's layer carries its clip; the slot and the layer's end don't. + if let Some(at) = faded_slot { + for instance in &mut self.instances[at..at + 2] { instance.fade = [0; 4]; } + } + if self.track_marks { + self.marks.resize(self.instances.len(), mark); + } + // A scroll viewport clips its content with a hard edge unless it sets soft ones. + if let Some(f) = n.vis.clip.or(n.scroll.map(|_| [0.0; 4])) { + let outer = [clip, fade, fade_origin]; + // A sliding window a step moves clips from its anchor's pose (`slide_anchor`). + let rs = self.paint.slide_anchor(&self.tree.nodes, &self.motion, &self.scene, s, self.reduced_motion, i, rect_pt, r_exact, r, if unscaled { 1.0 } else { sc }); + clip = intersect(rs, clip); + let (own, origin) = self.scroll_edge_fade(i, f, rs, sc * s, p.rect.edges()[3]); + inherit_fade(&mut fade, &mut fade_origin, origin, own); + let root_inh = self.root_inh(); + self.paint.note_slide(&self.tree.nodes, &self.motion, &self.scene, self.instances.len(), s, self.viewport, self.reduced_motion, root_inh, i, outer, rect_pt, rs, (if unscaled { 1.0 } else { sc }, sc)); + } + let n = &self.tree.nodes[i]; + let mask = self.paint.row_mask[i]; + if mask >= 0.0 { + clip[3] = clip[3].min(r[3]); + // A fold's lifted contents (`GrowTrack::hide_above`) never draw above its top. + if self.paint.row_lifts.iter().any(|&(ri, _)| ri == i) { clip[1] = clip[1].max(r[1]); } + inherit_fade(&mut fade, &mut fade_origin, r, [0.0, 0.0, 0.0, self.growth_feather(i)]); + } + let mut dy = pinh.dy; + let snap_off = pinh.snap.off || n.vis_flags.no_pixel_snap() || turn_index != 0; + let mut snap = pinh.snap; + // `El::paint_contained`: its children snap against the containing box's origin, + // rounded on its own, as a translation that snaps as a whole. + if let Some(o) = n.vis.cold.get().and_then(|c| c.paint_contain) { + snap.contain_at(o); + } + if n.scroll.is_some() + && let Some(st) = self.scroll.scrolls.get(&n.id) + { + let offset = self.stuck_offset(i, p.rect.edges()[3]).unwrap_or(st.offset); + let held = self.bottom_offset(i, p.rect.edges()[3]).is_some_and(|b| (offset - b).abs() < 0.5); + let exact = offset as f32 + st.slack.height(); + let (drawn, hold) = st.drawn.draw(exact, st.offset as f32, st.pinned(), s); + dy -= drawn; + snap.scroll(1, -drawn); + if let Some(st) = self.scroll.scrolls.get_mut(&self.tree.nodes[i].id) { (st.held, st.drawn) = (held, hold); } + } + let (mut scale, mut anchor, mut anchor_to, mut dx) = (sc, anchor, anchor_to, pinh.dx); + if n.scroll_axes.x() && let Some(st) = self.scroll.scrolls.get_mut(&self.tree.nodes[i].id) { + st.drawn_x = grid(st.x.shift() as f32, s); + dx -= st.drawn_x; + snap.scroll(0, -st.drawn_x); + } + if open_cache && sc > 1e-4 { + dx += (r_exact[0] / s - rect_pt[0]) / sc; + dy += (r_exact[1] / s - rect_pt[1]) / sc; + } + let (mut cover_offset, mut outer) = (pinh.cover, pinh.outer); + let scale_motion = if cover.is_some() { ScaleMotion::Moving } else { scale_motion }; + if let Some((k, c)) = cover { + // Children ride this node's presented origin at their rest layout. Scale them by + // `k` about the drawn origin, centred, and clip them to the moving rect. + clip = intersect(clip, r); + hit_clip = intersect(hit_clip, r); + let plain = [dx, dy]; + dx = rect_pt[0] - p.rect.x + c[0] / k; + dy += rect_pt[1] - p.rect.y - pinh.dy + c[1] / k; + (scale, anchor, anchor_to) = (k, [rect_pt[0], rect_pt[1]], [rect_pt[0], rect_pt[1]]); + cover_offset = [dx - plain[0], dy - plain[1]]; + outer = Some([pinh.clip, pinh.fade, pinh.fade_origin]); + } + inherit_fade(&mut hit_fade, &mut hit_origin, fade_origin, fade); + let full_clip = intersect(hit_clip, clip); + if node_turn.is_some() { + if self.paint.unturned_drawn.is_empty() { + self.paint.unturned_drawn.resize(n_nodes, ([0.0; 4], NO_CLIP)); + } + self.paint.unturned_drawn[i] = (r.map(|v| v / s), full_clip); + } + let group_rect = if hover_owner { rect_pt } else { pinh.group_rect }; + self.paint.inh_scratch[i] = Inh { opacity: effective_opacity, paint_opacity: o, first_fade: kids_fade, + clip: full_clip, fade: hit_fade, fade_origin: hit_origin, + paint_clip: clip, paint_fade: fade, paint_fade_origin: fade_origin, rounded, scale, anchor, anchor_to, blur, dy, dx, + cover: cover_offset, outer, mark, group, pressed, press_to, + hit_opacity: hit_opacity * kids_fade, group_rect, + scale_motion, still: if scale_motion == ScaleMotion::Still { (scale, anchor, anchor_to) } else { pinh.still }, + in_cache, skip_paint, anchor_hidden: false, turn: turn_index, + snap: pixel_snap::Inherit { off: snap_off, steps, shifted: pinh.snap.shifted || n.vis.offset != [0.0; 2], layer: if cover.is_some() { 0 } else { snap_layer }, parent: snap_rest.filter(|_| cover.is_none() && snap.rigid == pinh.snap.rigid && pixel_snap::frames(&n.vis)), ..snap } }; + // Shown only under its group's hover, it takes presses where the pointer hovers the + // group: a press in the same frame as the move that reveals it finds it, as a page's + // `:hover` applies before the press does. + let (hit_opacity, hit_rect) = if effective_opacity > 0.001 { (effective_opacity, rect_pt) } else { (hit_opacity, intersect(rect_pt, pinh.group_rect)) }; + self.register_node_hits(i, pinh.clip, (hit_opacity, visible), hit_rect, (press_k, press_anchor)); + if self.tree.has_sticky { + self.fade_below_header(i, s); + } + self.keep_painted(i, !self.paint.node_animated_icon && own_turn.is_none() && !opens_snap_layer && snap_layer == 0 && !in_cache && !skip_paint && cover.is_none() && !lift && !raised); + } + if !self.paint.icon_anim_mounts.is_empty() { + self.paint.icon_anim_mounts.retain(|(id, _), _| self.tree.node_index.contains_key(id)); + } + if !self.paint.last_anchor_targets.is_empty() { + self.paint.last_anchor_targets.retain(|id, _| self.tree.node_index.contains_key(id)); + } + self.keep_close(None, &mut layers, &mut active_cache, &mut glyph_count); + self.keep_end(); + self.paint.close_all_layers(&self.tree.nodes, &mut self.instances, &mut self.surfaces, &mut self.marks, self.track_marks, &mut self.text, self.commit.commit_gen(), &mut layers, &mut active_cache, &mut glyph_count); + // A moving chip can enter a stationary pointer. Re-evaluate against this frame's + // geometry without inventing pointer-move or drag events on animation frames. Tooltips + // follow the hold this decides. + let queued = self.frame.queue.len(); + let held = self.pointer.pos.map(|(x, y)| self.refresh_hover(x, y)); + self.frame.queue.observe_since(queued); + self.update_help(); + self.paint.layer_scratch = layers; + self.tree.built = true; + self.land_unseen_entrances(); + self.tree.built_ids.clear(); + self.tree.built_ids.extend(self.tree.nodes.iter().map(|n| n.id)); + if video_signature != self.paint.video_signature { + // A video loaded, ended or failed: views reading its state re-run next frame. + self.paint.video_signature = video_signature; + self.commit.dirty = true; + self.paint.videos_active = true; + } + if self.track_marks { self.marks.resize(self.instances.len(), 0); } + self.stats.glyphs = glyph_count; + self.ambient = ambient; + // A live transform can change hover paint with no handler and no running spring. + // Retarget from the new geometry and schedule the frame that samples that paint. A + // commit that moved the indices left keyboard focus hover (`El::hover_group`) to + // this pass too. + let interaction = (self.pointer.pos.is_some() || self.kbd.focus.keyboard()) && self.update_interaction(held); + self.frame.queue.len() > queued || interaction + } +} diff --git a/app/vendor/rune/crates/rune/src/runtime/paint/build/layers.rs b/app/vendor/rune/crates/rune/src/runtime/paint/build/layers.rs new file mode 100644 index 0000000..dd6e305 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/paint/build/layers.rs @@ -0,0 +1,470 @@ +//! Paint layer scoping: dissolve pre-pass, tree-order check, layer stack closing, raised ancestor +//! reopening, `El::cache` eligibility/opening, rounded clips, backdrop blur, cutouts and isolation. +use super::*; + +#[derive(Clone, Copy)] +pub(super) struct LayerScope { + pub(super) o: f32, + pub(super) skip_paint: bool, + pub(super) in_cache: bool, + pub(super) open_cache: bool, + pub(super) blur_hole: Option<f32>, + pub(super) glyphs_clear: bool, + pub(super) hit_clip: [f32; 4], + pub(super) hit_fade: [f32; 4], + pub(super) hit_origin: [f32; 4], + pub(super) primitive_start: usize, + pub(super) surface_start: usize, +} + +#[inline(always)] +fn strip_round_mask(clip: &mut [f32; 4], round: &mut Option<([f32; 4], [f32; 4])>) { + if let Some((mask, radii)) = *round { + let e = radii.map(crate::render::corner_extent); + let (left, right, top, bottom) = (e[0].max(e[3]), e[1].max(e[2]), e[0].max(e[1]), e[2].max(e[3])); + let cut = intersect(*clip, mask); + if cut[2] <= cut[0] || cut[3] <= cut[1] + || (cut[0] >= mask[0] + left && cut[2] <= mask[2] - right) + || (cut[1] >= mask[1] + top && cut[3] <= mask[3] - bottom) + { + *clip = cut; + *round = None; + } + } +} + +impl paint_state::PaintState { + // Phases of `build`'s single paint loop; keep them inlined into it. + #[inline(always)] + #[allow(clippy::too_many_arguments)] + pub(super) fn prepare_dissolve( + &mut self, + tree: &types::TreeState, + scene: &Scene, + motion: &crate::runtime::tracks::MotionState, + clock: f64, + reduced_motion: bool, + focus_keyboard: bool, + focus_path: Option<&str>, + ) { + let n_nodes = tree.nodes.len(); + // One linear pass, including retained exits, Live opacity, presence and loops. Reuse + // inherited scratch for hover groups so activation samples exactly the paint values. + self.dissolve_scratch.clear(); + if tree.has_dissolve { self.dissolve_scratch.resize(n_nodes, false); } + for index in 0..if tree.has_dissolve { n_nodes } else { 0 } { + let i = self.layer_paint_order.get(index).copied().unwrap_or(index); + let n = &tree.nodes[i]; + let inherited_group = n.parent.map_or(0.0, |p| self.inh_scratch[p].group); + self.inh_scratch[i].group = if n.vis.hover().a > 0.0 || n.vis_flags.hover_group() { + scene.get(n.id, P_HOVER).unwrap_or(0.0).clamp(0.0, 1.0) + } else { inherited_group }; + let Some(parent) = n.parent.filter(|&p| tree.nodes[p].vis_flags.blend() == crate::render::Blend::PlusLighter) else { continue }; + let Some(p) = scene.presented(n.id) else { continue }; + let mut opacity = p.opacity * n.vis.layer_opacity; + opacity *= group_factor(scene, focus_keyboard, focus_path, n, inherited_group); + if fades(n.looping.as_deref().copied()) && let Some(track) = motion.loop_track(n.id) { + opacity *= track.sample_at(scene.store().node_time(n.id), clock, reduced_motion); + } + self.dissolve_scratch[parent] |= opacity > 0.001 && opacity < 1.0; + } + } + + #[inline(always)] + pub(super) fn needs_tree_order(&self, tree: &types::TreeState, scene: &Scene, flying: bool) -> bool { + // Exiting descendants are appended to storage. Bring them back into their subtree + // only when isolation requires it; the ordinary painter stream stays byte-identical. + // Matched flights paint last (see `update_layer_paint_order`). + ((flying || tree.has_sticky || tree.has_raise || tree.has_paint_order) && !self.layer_paint_order.is_empty()) || self.layer_paint_order.windows(2).any(|pair| { + let n = &tree.nodes[pair[0]]; + tree.nodes[pair[1]].parent == Some(pair[0]) && ((tree.has_dissolve && self.dissolve_scratch[pair[0]]) || n.vis_flags.cache() || n.vis.clip_radius.is_some() || n.vis.group_opacity.is_some() || n.group_fade + || n.vis.layer_opacity < 1.0 || fades(n.looping.as_deref().copied()) + || scene.presented(n.id).is_some_and(|p| (p.opacity > 0.0 && p.opacity < 1.0) || p.blur > 0.0 || p.transform.rotate.abs() > 1e-6)) + }) + } + + #[inline] + #[allow(clippy::too_many_arguments)] + pub(super) fn close_all_layers( + &mut self, + nodes: &[Node], + instances: &mut Vec<Instance>, + surfaces: &mut [crate::native_surface::SurfaceDraw], + marks: &mut Vec<u32>, + track_marks: bool, + text: &mut TextSystem, + commit_gen: u64, + layers: &mut Vec<(usize, usize, usize)>, + active_cache: &mut Option<ActiveCache>, + glyph_count: &mut usize, + ) { + while let Some((_, start, surface_start)) = layers.pop() { + if active_cache.is_some_and(|ac| ac.instance_start == start) { + let ac = active_cache.take().unwrap(); + self.close_cached_layer(nodes, instances, surfaces, marks, track_marks, text, commit_gen, ac, start, surface_start, glyph_count); + } else { + crate::render::end_layer(instances, surfaces, marks, start, surface_start); + } + } + } + + #[inline(always)] + #[allow(clippy::too_many_arguments)] + pub(super) fn close_layers_to_parent( + &mut self, + nodes: &[Node], + instances: &mut Vec<Instance>, + surfaces: &mut [crate::native_surface::SurfaceDraw], + marks: &mut Vec<u32>, + track_marks: bool, + text: &mut TextSystem, + commit_gen: u64, + node_parent: Option<usize>, + layers: &mut Vec<(usize, usize, usize)>, + active_cache: &mut Option<ActiveCache>, + glyph_count: &mut usize, + ) { + while let Some(&(ancestor, start, surface_start)) = layers.last() { + let mut parent = node_parent; + while parent.is_some_and(|p| p != ancestor) { parent = nodes[parent.unwrap()].parent; } + if parent == Some(ancestor) { break; } + if active_cache.is_some_and(|ac| ac.instance_start == start) { + let ac = active_cache.take().unwrap(); + self.close_cached_layer(nodes, instances, surfaces, marks, track_marks, text, commit_gen, ac, start, surface_start, glyph_count); + } else { + crate::render::end_layer(instances, surfaces, marks, start, surface_start); + } + layers.pop(); + } + } + + #[inline(always)] + #[allow(clippy::too_many_arguments)] + pub(super) fn reopen_raised_layers( + &self, + nodes: &[Node], + scene: &Scene, + instances: &mut Vec<Instance>, + surfaces_len: usize, + node_parent: Option<usize>, + pinh: &mut Inh, + layers: &mut Vec<(usize, usize, usize)>, + s: f32, + ) { + // Out of its ancestors' layers: their opacity applies directly instead. + pinh.paint_opacity = pinh.opacity; + pinh.paint_clip = pinh.clip; + pinh.paint_fade = pinh.fade; + pinh.paint_fade_origin = pinh.fade_origin; + pinh.in_cache = false; + pinh.skip_paint = false; + // Rounded clips and turns consumed by an ancestor's layer must be reapplied + // outside that layer too. Reopen only the masks and turns, not opacity or blur. + pinh.rounded = None; + let mut chain = Vec::new(); + let mut parent = node_parent; + while let Some(p) = parent { + chain.push(p); + parent = nodes[p].parent; + } + for &p in chain.iter().rev() { + let ancestor = &nodes[p]; + let k = self.inh_scratch[p].turn; + if k != 0 && ancestor.parent.map_or(0, |pp| self.inh_scratch[pp].turn) != k { + let t = self.turn_scratch[k as usize - 1]; + let start = instances.len(); + let marker = Instance::begin_layer(t.rect, t.outer_clip, Default::default()).turned(t.angle, t.pivot); + instances.push(marker); + layers.push((p, start, surfaces_len)); + } + if let Some(radius) = ancestor.vis.clip_radius { + let [x, y, w, h] = self.unturned_drawn.get(p).filter(|_| k != 0) + .map_or_else(|| self.drawn[p].map(|v| v * s), |&(b, _)| [b[0] * s, b[1] * s, (b[2] - b[0]) * s, (b[3] - b[1]) * s]); + let radii = ancestor.vis.clip_corners.unwrap_or_else(|| { + if ancestor.vis.radii() != [0.0; 4] { + scene.presented(ancestor.id).map_or(ancestor.vis.radii(), |p| p.radius.0) + } else { [radius; 4] } + }).map(|radius| { + let radius = (radius.max(0.0) * self.inh_scratch[p].scale * s).min(w.min(h) * 0.5); + if ancestor.vis_flags.continuous_corners() { -radius } else { radius } + }); + let start = instances.len(); + let mut marker = Instance::begin_layer([x, y, w, h], [x, y, x + w, y + h], Default::default()); + marker.round_clip_corners(radii); + instances.push(marker); + layers.push((p, start, surfaces_len)); + } + } + } +} + +impl RuntimeCore { + + #[inline(always)] + #[allow(clippy::too_many_arguments)] + pub(super) fn open_node_layers( + &mut self, + i: usize, + s: f32, + now: f64, + p: &rune_motion::Presented, + pinh: &Inh, + r: [f32; 4], + r_exact: [f32; 4], + radii: [f32; 4], + w: f32, + h: f32, + sc: f32, + m: f32, + effective_opacity: f32, + paint_own: f32, + visible: bool, + dissolve: bool, + lift: bool, + own_turn: Option<f32>, + node_turn: Option<&Turn>, + next: Option<usize>, + scale_motion: ScaleMotion, + vp: [f32; 4], + paint_state_hash: u64, + glyph_count: usize, + clip: &mut [f32; 4], + fade: &mut [f32; 4], + fade_origin: &mut [f32; 4], + rounded: &mut Option<([f32; 4], [f32; 4])>, + isolate: &mut bool, + backdrop_blurs: &mut usize, + layers: &mut Vec<(usize, usize, usize)>, + active_cache: &mut Option<ActiveCache>, + ) -> LayerScope { + let n = &self.tree.nodes[i]; + if n.vis_flags.cache() && self.paint.cache_live_scratch[i] { + if let Some(entry) = self.paint.node_caches.get_mut(&n.id) { + entry.phase = RasterPhase::Live; + } + } + let mut skip_paint = pinh.skip_paint; + let mut in_cache = pinh.in_cache; + let mut open_cache = false; + // A scale changed by view commits may accompany arbitrary content edits. Draw + // live until it rests instead of trusting a partial content hash or allocating a + // new raster on each commit. Live-only transforms still composite the old raster. + let mut committed_scale_moving = false; + if n.vis_flags.cache() && let Some(entry) = self.paint.node_caches.get_mut(&n.id) + && entry.commit_gen != self.commit.commit_gen() + && let Some(frame) = entry.committed_scale(sc * s, now) + { + committed_scale_moving = true; + self.paint.scale_frame = Some(frame); + } + if n.vis_flags.cache() && active_cache.is_none() && !lift && !skip_paint && !self.paint.cache_live_scratch[i] + && !committed_scale_moving && own_turn.is_none() + && effective_opacity > 0.001 && w > 0.0 && h > 0.0 + { + let eff_scale = sc * s; + let est_bounds = if let Some(entry) = self.paint.node_caches.get(&n.id) { + let k = eff_scale / entry.raster_scale.max(1e-4); + [ + r[0] + entry.rel_bounds[0] * k, + r[1] + entry.rel_bounds[1] * k, + r[0] + entry.rel_bounds[2] * k, + r[1] + entry.rel_bounds[3] * k, + ] + } else { + let sh = n.vis.shadows.iter().enumerate().fold(0.0f32, |m, (k, sh)| { + let sh = self.shadow_at(n.id, k, sh); + m.max((sh.x.abs() + sh.y.abs() + sh.spread.max(0.0) + sh.blur * 3.0) * eff_scale) + }); + [r[0] - sh, r[1] - sh, r[2] + sh, r[3] + sh] + }; + let cache_vis = match node_turn { + None => est_bounds[2] >= clip[0].max(vp[0]) - m + && est_bounds[0] <= clip[2].min(vp[2]) + m + && est_bounds[3] >= clip[1].max(vp[1]) - m + && est_bounds[1] <= clip[3].min(vp[3]) + m, + Some(t) => { + let lc = intersect(pinh.clip, *clip); + let sb = t.bbox(est_bounds); + let oc = t.outer_clip; + est_bounds[2] >= lc[0] - m && est_bounds[0] <= lc[2] + m + && est_bounds[3] >= lc[1] - m && est_bounds[1] <= lc[3] + m + && sb[2] >= oc[0].max(vp[0]) - m && sb[0] <= oc[2].min(vp[2]) + m + && sb[3] >= oc[1].max(vp[1]) - m && sb[1] <= oc[3].min(vp[3]) + m + } + }; + if !cache_vis { + skip_paint = true; + } else { + let est_w = (est_bounds[2] - est_bounds[0]).ceil(); + let est_h = (est_bounds[3] - est_bounds[1]).ceil(); + if est_w <= 4096.0 && est_h <= 4096.0 { + open_cache = true; + } + } + } + // A negative clip radius rounds with continuous corners (`render::corner_extent`). + let mut own_round = n.vis.clip_corners.or_else(|| { + n.vis.clip_radius.map(|radius| { + if n.vis.radii() != [0.0; 4] { + p.radius.0 + } else { + [radius; 4] + } + }) + }).map(|radii| { + let half = w.min(h) * 0.5; + let radii = radii.map(|radius| { + let r = (radius.max(0.0) * sc * s).min(half); + if n.vis_flags.continuous_corners() && r > 0.0 { -r } else { r } + }); + (r, radii) + }); + let mut hit_clip = intersect(pinh.clip, *clip); + if let Some((rect, _)) = own_round { hit_clip = intersect(hit_clip, rect); } + let (mut hit_fade, mut hit_origin) = (pinh.fade, pinh.fade_origin); + inherit_fade(&mut hit_fade, &mut hit_origin, *fade_origin, *fade); + // A rectangle wholly in either central strip misses all four corner squares. + // Its hard edges already exclude everything the rounded mask would remove. + strip_round_mask(clip, rounded); + if !open_cache { + strip_round_mask(clip, &mut own_round); + } + // A backdrop blur samples what is drawn before it, so it goes ahead of any layer this + // element opens (a fade still blurs the window) and of its shadows, which skip it. + let blur_hole = (n.vis.backdrop_blur > 0.0 && !skip_paint && visible && *backdrop_blurs < crate::MAX_BACKDROP_BLURS + && effective_opacity > 0.001 && paint_own * pinh.paint_opacity * n.vis.paint_alpha > 0.001) + .then(|| paint_slots::push_backdrop_blur(&mut self.instances, n.vis.backdrop_blur, ([r[0], r[1], w, h], radii, n.vis_flags.continuous_corners()), + (*clip, *fade, *fade_origin), *rounded, sc * s, (paint_own * pinh.paint_opacity * n.vis.paint_alpha).clamp(0.0, 1.0))); + *backdrop_blurs += blur_hole.is_some() as usize; + // The packed ABI carries one clip rectangle. Preserve a rectangular cut through + // a rounded corner on a separate outer scope, never recenter the rounded mask. + if !skip_paint && let Some((mask, _)) = rounded.or(own_round) + && intersect(*clip, mask) != mask { + let mut marker = Instance::begin_layer([r[0], r[1], w, h], *clip, Default::default()); + marker.fade = crate::render::pack_fade(*fade, *fade_origin, *clip); + layers.push((i, self.instances.len(), self.surfaces.len())); + self.instances.push(marker); + *clip = NO_CLIP; *fade = [0.0; 4]; *fade_origin = NO_CLIP; + } + // Two rounded rectangles cannot generally be represented by one rounded rectangle. + // Consume the ancestor on an outer composite, retaining both original corner centres. + if !skip_paint && rounded.is_some() && own_round.is_some() && *rounded != own_round { + let (mask, radii) = rounded.take().unwrap(); + let mut marker = Instance::begin_layer([r[0], r[1], w, h], mask, Default::default()); + marker.fade = crate::render::pack_fade(*fade, *fade_origin, mask); + marker.round_clip_corners(radii); + layers.push((i, self.instances.len(), self.surfaces.len())); + self.instances.push(marker); + *clip = NO_CLIP; *fade = [0.0; 4]; *fade_origin = NO_CLIP; + } + if let Some(mask) = own_round { *rounded = Some(mask); } + if let Some((mask, _)) = *rounded { + *clip = intersect(*clip, mask); + } + // `El::cutout_circle`: the subtree draws in a layer whose composite cuts the hole, + // after the clips from above, which it takes. + if !skip_paint && let Some(c) = n.vis.cutout { + let k = sc * s; + let mut marker = Instance::begin_layer([r[0], r[1], w, h], *clip, Default::default()); + marker.fade = crate::render::pack_fade(*fade, *fade_origin, *clip); + if let Some((_, radii)) = *rounded { marker.round_clip_corners(radii); } + marker.radii = [r[0] + c[0] * k, r[1] + c[1] * k, c[2] * k, c[3] * k]; + layers.push((i, self.instances.len(), self.surfaces.len())); + self.instances.push(marker); + *clip = NO_CLIP; *fade = [0.0; 4]; *fade_origin = NO_CLIP; *rounded = None; + } + // Live/truncated text adds a glyph-only rectangle below. Consume the inherited + // rounded mask first so the text clip cannot move its corner centres, unless that + // rectangle sits clear of the corners and the glyphs can skip the mask. + let glyphs_clear = rounded.is_some_and(|(mask, radii)| { + self.text_clip(i, (r, r_exact), sc, *clip).is_some_and(|(text, ..)| inside_rounded(text, mask, radii)) + }); + *isolate |= open_cache || (rounded.is_some() && (n.text.as_ref().is_some_and(|t| (t.truncate_fade || t.cold.live.is_some()) && !glyphs_clear) + || n.input.as_ref().is_some_and(|i| i.single_line))); + // A soft clip fades each primitive on its own, so where one paints over another (an + // image over its placeholder fill, a label over its bubble) the one beneath shows + // through the fade, and the stack brightens or darkens towards the edge. A stack that + // reaches into a soft edge composites as one layer, which takes the fade once. + if !*isolate && visible && effective_opacity > 0.001 && fade.iter().any(|&f| f != 0.0) + && in_fade([r[0], r[1], r[0] + w, r[1] + h], *clip, *fade, *fade_origin) + { + let paints = own_paints(n); + let parent = next.is_some_and(|j| self.tree.nodes[j].parent == Some(i)); + *isolate = paints >= 2 || (paints == 1 && parent); + } + let o = if *isolate { 1.0 } else { (paint_own * pinh.paint_opacity).clamp(0.0, 1.0) }; + if !skip_paint && *isolate { + let start_idx = self.instances.len(); + layers.push((i, start_idx, self.surfaces.len())); + let mut marker = Instance::begin_layer([r[0], r[1], w, h], *clip, + crate::render::LayerSpec { opacity: paint_own * pinh.paint_opacity, + blend: if dissolve { crate::render::Blend::PlusLighter } else { crate::render::Blend::SourceOver }, + blur: p.blur * sc * s, clip_radius: 0.0 }); + marker.fade = crate::render::pack_fade(*fade, *fade_origin, *clip); + if let Some((_, radii)) = *rounded { marker.round_clip_corners(radii); } + self.instances.push(marker); + // Clip the completed layer, never its inputs (including off-wall blur taps). + *clip = NO_CLIP; *fade = [0.0; 4]; *fade_origin = NO_CLIP; *rounded = None; + if open_cache { + in_cache = true; + let eff_scale = sc * s; + let paint_hash = { + use std::hash::Hasher; + let mut h = rune_motion::Fx::default(); + h.write_u64(paint_state_hash); + h.write_u64(self.paint.cache_paint_scratch[i]); + h.write_u32(pinh.group.to_bits()); + h.finish() + }; + let (scale, pass, frame) = + if let Some(entry) = self.paint.node_caches.get(&n.id) { + let is_resident = self.text.atlas.resident_caches.get(&n.id.0) == Some(&entry.signature); + entry.open(eff_scale, s, self.settled, now, self.commit.commit_gen(), is_resident, + scale_motion, paint_hash, || self.paint.cache_check_scratch[i], glyph_count) + } else { + (ScaleSettle::Still(eff_scale), RasterPass::Paint { glyph_start: glyph_count }, None) + }; + if frame.is_some() { self.paint.scale_frame = frame; } + if matches!(pass, RasterPass::Elide { .. }) { + skip_paint = true; + } + *active_cache = Some(ActiveCache { + node_index: i, + node_id: n.id, + instance_start: start_idx, + origin: [r[0], r[1]], + size: [w, h], + cur_scale: eff_scale, + scale, + env_scale: s, + paint_hash, + pass, + }); + } + } + let primitive_start = self.instances.len(); + let surface_start = self.surfaces.len(); + // Include native surface geometry, which lives beside the primitive stream. + if !skip_paint && n.vis.surface.is_some() { + for &(_, at, _) in layers.iter() { + let b = &mut self.instances[at].rect; + let hi = [(b[0] + b[2]).max(r[2].min(clip[2])), (b[1] + b[3]).max(r[3].min(clip[3]))]; + b[0] = b[0].min(r[0].max(clip[0])); b[1] = b[1].min(r[1].max(clip[1])); + b[2] = hi[0] - b[0]; b[3] = hi[1] - b[1]; + } + } + LayerScope { + o, + skip_paint, + in_cache, + open_cache, + blur_hole, + glyphs_clear, + hit_clip, + hit_fade, + hit_origin, + primitive_start, + surface_start, + } + } +} diff --git a/app/vendor/rune/crates/rune/src/runtime/paint/build/pose.rs b/app/vendor/rune/crates/rune/src/runtime/paint/build/pose.rs new file mode 100644 index 0000000..876a357 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/paint/build/pose.rs @@ -0,0 +1,177 @@ +//! Per-node pose helpers extracted from `build`: sticky and flight inheritance, static-scale +//! settling, sticky frame bounds, matched-flight cover, and loop wake scheduling. +use super::*; + +#[inline(always)] +pub(super) fn step_static_scale( + static_scales: &mut HashMap<NodeId, ScaleSettle>, + scale_frame: &mut Option<AnotherFrame>, + node_id: NodeId, + tracked_scale: f32, + t: f64, + settled: bool, + has_live_scale: bool, +) -> bool { + let seen = static_scales.entry(node_id).or_insert(ScaleSettle::Still(tracked_scale)); + let moving = matches!(seen.step(tracked_scale, t, settled, 1e-5, true), crate::machine::Effects::One(_)); + if !has_live_scale && moving { + *scale_frame = Some(AnotherFrame); + } + moving +} + +#[inline(always)] +pub(super) fn update_sticky_frame(sticky_frame: &mut [[f32; 8]], i: usize, n: &Node, raw_edges: [f32; 4]) { + let up = n.parent.map_or(sticky::UNBOUNDED, |pr| sticky_frame[pr]); + // Content scrolls without end on a viewport's scrolling axes; non-scrolling axes + // bound sticky children to this node's content box. + let sc_y = n.scroll.is_some() && n.scroll_axes.y(); + let sc_x = n.scroll.is_some() && n.scroll_axes.x(); + let v = if sc_y { + [raw_edges[1], raw_edges[3], f32::NEG_INFINITY, f32::INFINITY] + } else { + [up[0], up[1], raw_edges[1] + n.inset[1], raw_edges[3] - n.inset[3]] + }; + let x = if sc_x { + [raw_edges[0], raw_edges[2], f32::NEG_INFINITY, f32::INFINITY] + } else { + [up[4], up[5], raw_edges[0] + n.inset[0], raw_edges[2] - n.inset[2]] + }; + sticky_frame[i] = [v[0], v[1], v[2], v[3], x[0], x[1], x[2], x[3]]; +} + +#[inline(always)] +pub(super) fn flight_cover( + launches: &flights::Launches, + node_id: NodeId, + n: &Node, + rect_pt: [f32; 4], +) -> Option<(f32, [f32; 2])> { + if launches.launched(node_id) { + return None; + } + let (pw, ph) = (rect_pt[2] - rect_pt[0], rect_pt[3] - rect_pt[1]); + if n.vis.cold.get().is_some_and(|c| c.flight_crop) { + // `El::matched_crop`: at its own size, from the leading edge. + Some((1.0, [0.0, (ph - n.local.h) * 0.5])) + } else { + let k = (pw / n.local.w).max(ph / n.local.h).max(1e-3); + Some((k, [(pw - n.local.w * k) * 0.5, (ph - n.local.h * k) * 0.5])) + } +} + +impl RuntimeCore { + #[inline(always)] + pub(super) fn apply_sticky_inh( + &mut self, + i: usize, + node_parent: Option<usize>, + p: &rune_motion::Presented, + pinh: &mut Inh, + ) -> f32 { + // `El::stuck_fade`: how much of a stuck header's title shows. + let mut kids_fade = 1.0f32; + if let Some((edge, inset, tail)) = self.sticky_of(i) { + let n = &self.tree.nodes[i]; + // Worked out from this frame's offsets, which the viewport above already applied. + // Exclude this node's own `prop::OFFSET` (`live_offset`) so it translates from the + // stuck place rather than being clamped away by the sticky edge. + let (frame, viewport) = self.sticky_frame_of(i, edge); + let own_off = self.scene.get(n.id, prop::OFFSET).unwrap_or(rune_motion::Vec2::ZERO); + let (top, left) = (p.rect.y - own_off.y + pinh.dy, p.rect.x - own_off.x + pinh.dx); + let h = if self.paint.row_h[i] >= 0.0 { self.paint.row_h[i] } else { p.rect.h }; + let shift = sticky::shift(edge, if tail { inset - h } else { inset }, [top, top + h, left, left + p.rect.w], frame); + self.scroll.stuck[i] = shift; + if edge == crate::el::StickyEdge::Top { kids_fade = self.stuck_fade(i, top + shift, pinh.dy); } + // A header whose section's rows fade under it keeps the clip they lost. + if let Some(&(_, top)) = self.scroll.sticky_bands.iter().find(|b| Some(b.0) == node_parent) { + pinh.paint_clip[1] = top; + } + if edge == crate::el::StickyEdge::Left { pinh.dx += shift } else { pinh.dy += shift } + pinh.snap.scroll((edge != crate::el::StickyEdge::Left) as usize, shift); + // A sticky element stays crisp against the viewport edge it sticks to while rows + // scrolling under its fill fade out. + let slot = match edge { + crate::el::StickyEdge::Left => 0, + crate::el::StickyEdge::Top => 1, + crate::el::StickyEdge::Bottom => 3, + }; + if let Some(viewport) = viewport.filter(|&v| self.tree.nodes[v].scroll_edges.fade > 0.0) { + let (width, origin) = self.sticky_fade(n.parent.unwrap(), viewport, slot, false); + pinh.fade[slot] = width; + pinh.fade_origin[slot] = origin; + let (width, origin) = self.sticky_fade(n.parent.unwrap(), viewport, slot, true); + pinh.paint_fade[slot] = width; + pinh.paint_fade_origin[slot] = origin; + } + } + kids_fade + } +} + +impl crate::runtime::tracks::MotionState { + #[inline(always)] + #[allow(clippy::too_many_arguments)] + pub(super) fn lift_flight_inh( + &mut self, + paint: &paint_state::PaintState, + scene: &Scene, + commit_gen: u64, + node_id: NodeId, + node_parent: Option<usize>, + pinh: &mut Inh, + ) { + // Keep the destination's clips (consumed ones included) and offsets. Drop its + // ancestors' opacity, scale and blur: an entering parent's fade or scale would + // otherwise hide the flight or jump it off the rect it was seen at. The scales + // holding still above that parent (an app-wide zoom) stay, so it flies at the size + // it lands at. Inside another flight, also drop that flight's cover offset and clip. + let [clip, fade, fade_origin] = if self.launches().flying(node_id) { + // A launch leaves where its clips don't reach. + [crate::render::NO_CLIP, [0.0; 4], pinh.fade_origin] + } else { + pinh.outer.unwrap_or_else(|| { + let clip = if pinh.turn != 0 { screen_clip_of(node_parent, &paint.inh_scratch, &paint.turn_scratch) } else { pinh.clip }; + [clip, pinh.fade, pinh.fade_origin] + }) + }; + let (scale, anchor, anchor_to) = pinh.still; + *pinh = Inh { opacity: 1.0, paint_opacity: 1.0, hit_opacity: 1.0, clip, fade, fade_origin, paint_clip: clip, paint_fade: fade, + paint_fade_origin: fade_origin, rounded: None, scale, anchor, anchor_to, blur: 0.0, + dx: pinh.dx - pinh.cover[0], dy: pinh.dy - pinh.cover[1], cover: [0.0; 2], outer: None, + scale_motion: ScaleMotion::Still, in_cache: false, skip_paint: false, turn: 0, snap: pixel_snap::Inherit { layer: 0, parent: None, ..pinh.snap }, ..*pinh }; + let fix = self.launches_mut().offset_fix(scene, node_id, [pinh.dx, pinh.dy], commit_gen); + (pinh.dx, pinh.dy) = (pinh.dx + fix[0], pinh.dy + fix[1]); + } + + #[inline(always)] + #[allow(clippy::too_many_arguments)] + pub(super) fn schedule_loop_wake( + &mut self, + paint: &mut paint_state::PaintState, + scene: &Scene, + clock: f64, + time_scale: f32, + node_id: NodeId, + lnow: f64, + now: f64, + ambient: &mut Option<f32>, + ) { + if let Some(track) = self.loop_track(node_id).copied() { + let node_k = scene.store().node_time_scale(node_id) as f64; + if let Some(dt) = track.frame_interval().filter(|_| track.active(lnow)) { + *ambient = Some(ambient.map_or(dt as f32, |a| a.min(dt as f32))); + let wake = clock + dt; + self.arm_loop_wake(wake, now + dt * time_scale as f64); + } else if time_scale > 0.0 && node_k > 0.0 { + self.mark_loops_active(track.active(lnow)); + } + if time_scale > 0.0 && node_k > 0.0 && let Some(start) = track.pending_start(lnow) { + let window_start = now + (start - lnow) / node_k; + paint.note_cycle_other_deadline(); + let wake = clock + (window_start - now) / time_scale as f64; + self.arm_loop_wake(wake, window_start); + } + } + } +} diff --git a/app/vendor/rune/crates/rune/src/runtime/paint/build/primitives.rs b/app/vendor/rune/crates/rune/src/runtime/paint/build/primitives.rs new file mode 100644 index 0000000..a322582 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/paint/build/primitives.rs @@ -0,0 +1,417 @@ +//! Per-node GPU primitive emission: native materials, outer and inset shadows, fills, gradients, +//! video/native surfaces, borders, effect slots, focus rings/outlines and leaf content. +use super::*; + +impl RuntimeCore { + #[inline(always)] + #[allow(clippy::too_many_arguments)] + pub(super) fn paint_node_box( + &mut self, + i: usize, + s: f32, + now: f64, + pinh: &Inh, + r: [f32; 4], + r_exact: [f32; 4], + raw_edges: [f32; 4], + radii: [f32; 4], + w: f32, + h: f32, + sc: f32, + o: f32, + effective_opacity: f32, + base_opacity: f32, + draw: f32, + m: f32, + clip: [f32; 4], + fade: [f32; 4], + fade_origin: [f32; 4], + vp: [f32; 4], + pressed: f32, + press_to: Option<Color>, + loop_value: Option<f32>, + blur_hole: Option<f32>, + cover: Option<(f32, [f32; 2])>, + scale_motion: ScaleMotion, + snap_rest: Option<&pixel_snap::Parent>, + next: Option<usize>, + default_ring: Option<usize>, + primitive_start: usize, + mark: u32, + isolate: bool, + in_cache: bool, + skip_paint: bool, + loop_vis: bool, + gliding: bool, + turned: bool, + caret: Option<[f32; 4]>, + video_clock: crate::video::Clock, + sel_ranges: &[(usize, usize, usize)], + mark_ranges: &[(usize, usize, usize)], + video_signature: &mut u64, + glyph_count: &mut usize, + ) -> Option<usize> { + let n = &self.tree.nodes[i]; + let mut faded_slot = None; + // Disabled styling is distributed to each authored paint leaf at build time. + // Keep this local to emission: it neither propagates to children nor opens scopes. + let o = o * n.vis.paint_alpha; + let srgb = self.paint.srgb_blend; + // Subtree blur runs once after rasterization, never on each primitive as well. + let blur = 0.0; + let k_px = sc * s; + let native_material = match n.material { + // A dimmed-out element takes no native view: its fallback draws nothing. + Some(material) if self.paint.materials.len() < crate::MAX_NATIVE_MATERIALS + && effective_opacity * n.vis.paint_alpha > 0.001 => { + let radius = crate::system_material::clamp_radius(radii, w, h); + let continuous = n.vis_flags.continuous_corners(); + self.paint.materials.push(crate::system_material::MaterialDraw { + id: n.id, material, rect: [r[0], r[1], w, h], radius, continuous, + opacity: effective_opacity * n.vis.paint_alpha, + }); + self.paint.native_materials.then_some(if continuous { -radius } else { radius }) + } + _ => None, + }; + let stuck_k = if self.tree.has_sticky { (self.scroll.stuck[i].abs() / sticky::SHADOW_RAMP).min(1.0) } else { 0.0 }; + let stuck_shadows: (f32, &[crate::el::Shadow]) = match &n.sticky { + Some(s) if stuck_k > 0.0 => (stuck_k, &s.shadows), + _ => (0.0, &[]), + }; + // `El::focus_within_flat`: focus inside drops its own shadows and hover fill. + let focus_flat = n.focus.flat_within && self.focus_within(i); + let casts = !n.vis.shadows.is_empty() && native_material.is_none() && blur_hole.is_none() && n.material.is_none(); + let fill_a = if casts { self.color(n.id, P_FILL, n.vis.fill).a } else { 0.0 }; + let solid = casts && fill_a >= 1.0; + // A box that paints itself solid hides the middle of its shadows (bands.rs). Dimmed + // (`El::dim`), or filled with a translucent colour, it leaves that middle clear, as + // CSS clips box-shadow to outside the box: a 6% white button shows the surface + // under it, not its own shadows. + let opaque = solid && o >= 1.0 && n.vis.gradient.is_none() && n.vis.radial.is_none() && n.vis.surface.is_none(); + let see_through = casts && fill_a > 0.0 && fill_a < 1.0; + let dim_hole = ((solid && o < 1.0) || see_through).then(|| crate::system_material::clamp_radius(radii, w, h) * if n.vis_flags.continuous_corners() { -1.0 } else { 1.0 }); + let cast = shadow_paint::Caster { + rect: [r[0], r[1], w, h], radii, shape: if n.vis_flags.continuous_corners() { radii.map(|v| -v) } else { radii }, + k_px, scale: s, opacity: o, srgb, clip, fade, hole: native_material.or(blur_hole).or(dim_hole), opaque, + }; + for (k, sh) in n.vis.shadows.iter().chain(stuck_shadows.1).enumerate() { + let c = if k >= n.vis.shadows.len() { sh.color.alpha(sh.color.a * stuck_shadows.0) } + else if k < P_SHADOWS.len() { self.color(n.id, P_SHADOWS[k], sh.color) } else { sh.color }; + if c.a <= 0.0 || sh.inset || (focus_flat && k < n.vis.shadows.len()) { + continue; + } + let sh = &if k < n.vis.shadows.len() { self.shadow_at(n.id, k, sh) } else { *sh }; + shadow_paint::push_shadow(&mut self.instances, sh, c, &cast); + } + // Shadows keep circular corners; the element's own shapes take the sign, and + // negative radii draw continuous corners (shader.wgsl `sd_rounded`). + let radii = if n.vis_flags.continuous_corners() { radii.map(|v| -v) } else { radii }; + let mut overlay = [0.0f32; 4]; + if let Some(c) = n.focus.highlight && self.highlight_visible(i) { + overlay = over(premul(c, 1.0, srgb), overlay); + } + if let Some(c) = n.focus.fill && self.focus_ring_visible(i) { + overlay = over(premul(c, 1.0, srgb), overlay); + } + if !focus_flat && (n.vis.hover().a > 0.0 || self.scene.store().is_animating(n.id, P_HOVER_C)) { + let hov_v = self.scene.get(n.id, P_HOVER).unwrap_or(0.0).clamp(0.0, 1.0); + if hov_v > 0.0 { + overlay = over(premul(self.color(n.id, P_HOVER_C, n.vis.hover()), hov_v, srgb), overlay); + } + } + if n.vis.press().a > 0.0 || self.scene.store().is_animating(n.id, P_PRESS_C) { + let prs_v = self.scene.get(n.id, P_PRESS).unwrap_or(0.0).clamp(0.0, 1.0); + if prs_v > 0.0 { + overlay = over(premul(self.color(n.id, P_PRESS_C, n.vis.press()), prs_v, srgb), overlay); + } + } + let layered = n.vis.gradient.is_some() || n.vis.radial.is_some() || n.vis.surface.is_some(); + let base_color = |c: Color| blend::flat_base(c, srgb, !layered && n.vis.border_width() == 0.0 && c.a * o < 1.0); + let base = match n.material { + _ if native_material.is_some() => [0.0; 4], + Some(_) => base_color(self.color(n.id, P_FILL, crate::system_material::fallback_fill(n.vis.fill, self.env.system_dark))), + None => base_color(self.color(n.id, P_FILL, n.vis.fill)), + }; + let fill = if layered { base } else { over(overlay, base) }.map(|c| c * o); + let bw = pixel_snap::line_width(n.vis.border_width() * s) * sc; + let border = if bw > 0.0 { premul(self.color(n.id, P_BORDER, n.vis.border()), o, srgb) } else { [0.0; 4] }; + // A gradient border draws as KIND_GRADIENT with a width: `border` top, `uv` bottom. + // After a switch back to `border`, it stays a gradient until both stops meet. + let store = self.scene.store(); + let springing = store.has(n.id, P_BORDER_BOTTOM) + && (store.is_animating(n.id, P_BORDER_BOTTOM) || store.is_animating(n.id, P_BORDER)); + let border_bottom = (bw > 0.0 && (n.vis.border_bottom.is_some() || springing)) + .then(|| premul(self.color(n.id, P_BORDER_BOTTOM, n.vis.border_bottom.unwrap_or(n.vis.border())), o, srgb)) + .filter(|b| n.vis.border_bottom.is_some() || *b != border); + let (border_kind, border_uv) = border_bottom.map_or((KIND_RECT, [0.0; 4]), |b| (KIND_GRADIENT, b)); + let border_a = border[3].max(border_uv[3]); + // A dashed ring is its own instance over the fill, which then draws without a ring. + let dashed = n.vis.border_dash.filter(|_| bw > 0.0 && border_a > 0.0005).map(|[dash, gap]| Instance { + rect: [r[0], r[1], w, h], + radii, + fill: border, + border: border_bottom.unwrap_or(border), + params: [bw, KIND_DASHED, blur * s, 1.0], + uv: [dash * k_px, gap * k_px, n.vis.border_dash_phase * k_px, 0.0], + clip, + fade: crate::render::pack_fade(fade, clip, clip), + }); + // Per-side widths (`El::border_sides`), each snapped as `bw` is; the widest is `bw`. + let sides = n.vis.border_sides.filter(|_| bw > 0.0).map(|ws| ws.map(|v| pixel_snap::line_width(v * s) * sc)); + let padding = sides.unwrap_or([bw; 4]); + let (bw, border, border_kind, border_uv, border_a) = + if n.vis.border_dash.is_some() { (0.0, [0.0; 4], KIND_RECT, [0.0; 4], 0.0) } else { (bw, border, border_kind, border_uv, border_a) }; + // The border's own instance, `o` in `params.w` so the shader knows how much it + // hides the fill under it (shader.wgsl `border_over`). With inset shadows it draws + // apart, over them, as CSS layers an inset box-shadow between background and border. + let ring = Instance { + rect: [r[0], r[1], w, h], + radii, + fill: [0.0; 4], + border, + params: [bw, border_kind, blur * s, o], + uv: if border_kind == KIND_RECT { sides.unwrap_or([0.0; 4]) } else { border_uv }, + clip, + fade: crate::render::pack_fade(fade, clip, clip), + }; + let apart = bw > 0.0 && border_a > 0.0005 && n.vis.shadows.iter().chain(stuck_shadows.1).any(|sh| sh.inset); + // Dimmed, an opaque fill and its gradient draw as one opaque gradient, so they fade + // together as a layer at that opacity would (CSS `opacity`), not one through the other. + let flat = layered && o < 1.0 && base[3] >= 1.0 && n.vis.gradient.is_some(); + if layered { + // Fill, gradient and overlays first, then the border on top, as in CSS. + if fill[3] > 0.0005 && !flat { + self.instances.push(Instance { + rect: [r[0], r[1], w, h], + radii, + fill, + border: [0.0; 4], + params: [0.0, KIND_RECT, blur * s, 1.0], + uv: [0.0; 4], + clip, + fade: crate::render::pack_fade(fade, clip, clip), + }); + } + let g = n.vis.gradient.as_deref().copied().unwrap_or_default(); + let stop = |c| if flat { over(premul(c, 1.0, srgb), base).map(|v| v * o) } else { premul(c, o, srgb) }; + let top = stop(self.color(n.id, P_GRADIENT[0], g[0])); + let bottom = stop(self.color(n.id, P_GRADIENT[1], g[1])); + if top[3] > 0.0005 || bottom[3] > 0.0005 { + self.instances.push(Instance { + rect: [r[0], r[1], w, h], + radii, + fill: top, + border: [0.0; 4], + params: [0.0, KIND_GRADIENT, 0.0, 1.0], + uv: bottom, + clip, + fade: crate::render::pack_fade(fade, clip, clip), + }); + } + if let Some(rg) = &n.vis.radial { + let segs = rg.stops.len().saturating_sub(1); + let rmax = radii[0].max(radii[1]).max(radii[2]).max(radii[3]).min(w * 0.5).min(h * 0.5); + let pad = 1.0 + blur * s * 2.0; + for seg in 0..segs { + let c0 = rg.stops[seg].1; + let c0 = if seg < P_RADIAL.len() { self.color(n.id, P_RADIAL[seg], c0) } else { c0 }; + let c1 = rg.stops[seg + 1].1; + let c1 = if seg + 1 < P_RADIAL.len() { self.color(n.id, P_RADIAL[seg + 1], c1) } else { c1 }; + let c0 = premul(c0, o, srgb); + let c1 = premul(c1, o, srgb); + if c0[3] <= 0.0005 && c1[3] <= 0.0005 { + continue; + } + let t0_val = rg.stops[seg].0; + let t1_val = rg.stops[seg + 1].0; + let (seg_rect, seg_radii, uv) = match rg.geometry { + crate::el::GradientGeometry::Radial { center, radius } => { + let cx = center[0] * w; + let cy = center[1] * h; + let rx = (radius[0] * k_px).max(1e-3); + let ry = (radius[1] * k_px).max(1e-3); + if seg + 1 < segs { + let mut lx0 = (cx - t1_val * rx - pad).floor().max(0.0); + let mut ly0 = (cy - t1_val * ry - pad).floor().max(0.0); + let mut lx1 = (cx + t1_val * rx + pad).ceil().min(w); + let mut ly1 = (cy + t1_val * ry + pad).ceil().min(h); + if rmax > 0.0 { + if lx0 < rmax && (ly0 < rmax || ly1 > h - rmax) { lx0 = 0.0; } + if lx1 > w - rmax && (ly0 < rmax || ly1 > h - rmax) { lx1 = w; } + if ly0 < rmax && (lx0 < rmax || lx1 > w - rmax) { ly0 = 0.0; } + if ly1 > h - rmax && (lx0 < rmax || lx1 > w - rmax) { ly1 = h; } + if lx0 == 0.0 && (ly0 == 0.0 || ly1 == h) { lx1 = lx1.max((2.0 * rmax).min(w)); } + if lx1 == w && (ly0 == 0.0 || ly1 == h) { lx0 = lx0.min((w - 2.0 * rmax).max(0.0)); } + if ly0 == 0.0 && (lx0 == 0.0 || lx1 == w) { ly1 = ly1.max((2.0 * rmax).min(h)); } + if ly1 == h && (lx0 == 0.0 || lx1 == w) { ly0 = ly0.min((h - 2.0 * rmax).max(0.0)); } + } + if lx1 <= lx0 || ly1 <= ly0 { + continue; + } + let br = [ + if lx0 == 0.0 && ly0 == 0.0 { radii[0] } else { 0.0 }, + if lx1 == w && ly0 == 0.0 { radii[1] } else { 0.0 }, + if lx1 == w && ly1 == h { radii[2] } else { 0.0 }, + if lx0 == 0.0 && ly1 == h { radii[3] } else { 0.0 }, + ]; + ([r[0] + lx0, r[1] + ly0, lx1 - lx0, ly1 - ly0], br, [cx - lx0, cy - ly0, rx, ry]) + } else { + ([r[0], r[1], w, h], radii, [cx, cy, rx, ry]) + } + } + crate::el::GradientGeometry::Linear { angle } => { + let (sin, cos) = angle.sin_cos(); + let (dx, dy) = (sin, -cos); + let span = (dx.abs() * w + dy.abs() * h).max(1e-3); + ([r[0], r[1], w, h], radii, [dx / span, dy / span, 0.0, 0.0]) + } + }; + let t0 = t0_val + if seg > 0 { 2.0 } else { 0.0 }; + let t1 = t1_val + if seg + 1 < segs { 2.0 } else { 0.0 }; + self.instances.push(Instance { + rect: seg_rect, + radii: seg_radii, + fill: c0, + border: c1, + params: [t0, KIND_RADIAL, blur * s, t1], + uv, + clip, + fade: crate::render::pack_fade(fade, clip, clip), + }); + } + } + if let Some((surface, fit)) = &n.vis.surface { + if let Some(pulled) = surface.pull_video(video_clock, self.frame.live.waker()) { + // A clip whose next picture isn't due for a while wakes the window + // then, instead of drawing every refresh in between. + let wait = pulled.due.map(|due| due.saturating_duration_since(crate::time::now()).as_secs_f64()); + match wait { + Some(wait) if pulled.active && wait > crate::video::WAKE_MIN => { + let wake = self.clock + wait; + self.paint.keep.cycles.other_deadline(); + self.motion.arm_loop_wake(wake, now + wait * self.time_scale as f64); + } + _ => self.paint.videos_active |= pulled.active, + } + *video_signature = crate::video::fold(*video_signature, pulled.generation, surface.key()); + } + self.surfaces.push(crate::native_surface::SurfaceDraw { + surface: surface.placed(n.vis.surface_place), fit: *fit, before_instance: self.instances.len() as u32, + rect: [r[0], r[1], w, h], radii, clip, fade: crate::render::pack_fade(fade, fade_origin, clip), opacity: o, + }); + } + let ov = overlay.map(|c| c * o); + if apart && ov[3] > 0.0005 { + self.instances.push(border_paint::fill_under(Instance { fill: ov, ..ring }, false)); + } else if !apart && (ov[3] > 0.0005 || border_a > 0.0005) { + self.instances.push(Instance { fill: ov, ..ring }); + } + } else if apart { + if fill[3] > 0.0005 { self.instances.push(border_paint::fill_under(Instance { fill, ..ring }, true)); } + } else if fill[3] > 0.0005 || border_a > 0.0005 { + if fill == [0.0; 4] && border_kind == KIND_RECT && bw > 0.0 && sides.is_none() { + bands::push_ring(&mut self.instances, ring); + } else { + if let Some(rune_motion::LoopKind::OpacityCycle(curve)) = n.looping.as_ref().map(|l| l.kind) + && n.a11y.hidden && !next.is_some_and(|j| self.tree.nodes[j].parent == Some(i)) + && !isolate && !in_cache && !skip_paint && loop_vis && base_opacity > 0.0 + && pinh.paint_opacity > 0.0 && loop_value.is_some_and(|v| v > 0.0) && n.vis.layer_opacity == 1.0 + && n.vis.paint_alpha == 1.0 && bw == 0.0 && overlay == [0.0; 4] + && self.instances.len() == primitive_start && n.text.is_none() && n.input.is_none() + && n.vis.shape.is_none() && n.vis.pixels.is_none() && n.vis.effect.is_none() + && n.vis.shadows.is_empty() && n.handlers.get().is_none() && n.focus.get().is_none() + && !n.vis_flags.hit() && !turned && cover.is_none() && n.help.is_none() + && curve.stops.iter().all(|&(_, a)| a.is_finite() && a > 0.001 && a <= 1.0 && base[3] * a > 0.0005) + { + self.paint.keep.cycles.record(i, self.instances.len(), curve, (base, o / loop_value.unwrap_or(1.0)), ring.rect); + } + self.instances.push(Instance { fill, ..ring }); + } + } + // Inset shadows draw inside the border (CSS's padding box), under it. + let (inner, inner_radii) = border_paint::inset_box([r[0], r[1], w, h], radii, padding); + for (k, sh) in n.vis.shadows.iter().chain(stuck_shadows.1).enumerate() { + if !sh.inset || (focus_flat && k < n.vis.shadows.len()) { + continue; + } + let c = if k >= n.vis.shadows.len() { sh.color.alpha(sh.color.a * stuck_shadows.0) } + else if k < P_SHADOWS.len() { self.color(n.id, P_SHADOWS[k], sh.color) } else { sh.color }; + if c.a <= 0.0 { + continue; + } + let sh = &if k < n.vis.shadows.len() { self.shadow_at(n.id, k, sh) } else { *sh }; + self.instances.push(border_paint::inset_shadow(sh, premul(c, o, srgb), (inner, inner_radii), (k_px, s), clip, fade)); + } + if apart { + if sides.is_none() && border_kind == KIND_RECT { bands::push_ring(&mut self.instances, ring); } else { self.instances.push(ring); } + } + self.instances.extend(dashed); + if let Some(effect) = n.vis.effect { + let fade = crate::render::pack_fade(fade, clip, clip); + faded_slot = paint_slots::push_effect(&mut self.instances, (effect, mark), ([r[0], r[1], w, h], radii, clip, fade), k_px, o); + } + let focus_ring = if default_ring == Some(i) || self.forced_default_ring(i) { Some(self.default_focus_ring()) } + else if let Some(key) = n.focus.ring_for.as_deref() { + n.focus.ring.filter(|_| self.kbd.focus.keyboard() && self.kbd.focus.path().is_some_and(|p| p.rsplit('/').next() == Some(key))) + } + else if n.focus.within { n.focus.ring.filter(|_| self.focus_within(i) && (!n.focus.within_keyboard || self.kbd.focus.entered_by_keys())) } + else { self.focus_ring_visible(i).then_some(n.focus.ring).flatten() }; + if let Some(ol) = focus_ring.or(n.vis.outline) { + let c = if focus_ring.is_some() { ol.color } else { self.color(n.id, P_OUTLINE, ol.color) }; + let ow = pixel_snap::line_width(ol.width * s) * sc; + let g = pixel_snap::line_width(ol.offset * s) * sc + ow; + if c.a > 0.0 && ol.width > 0.0 { + self.instances.push(Instance { + rect: [r[0] - g, r[1] - g, w + 2.0 * g, h + 2.0 * g], + radii: radii.map(|v| if v != 0.0 { v + g.copysign(v) } else { 0.0 }), + fill: [0.0; 4], + border: premul(c, o, srgb), + params: [ow, KIND_RECT, 0.0, 1.0], + uv: [0.0; 4], + clip, + fade: crate::render::pack_fade(fade, clip, clip), + }); + } + } + self.paint_content( + i, + paint_content::LeafBox { + r, + r_exact, + // Its exact resting place against its snapped one, inside its containment's + // own rounding (`LeafBox::exact_off`). + // Under an offset (`El::offset`, a translation as CSS transforms are) it moves + // with its box, as it did before this: a glide toward a moving offset keeps + // the text on its card, and lands as a card that never moved draws. + exact_off: if pinh.snap.shifted || n.vis.offset != [0.0; 2] { [0.0; 2] } else { + let o = snap_rest.map_or([0.0; 2], |p| p.exact_off(pinh.snap.steady.map(|v| v * s))); + let c = pinh.snap.contain.map(|v| v * s); + [o[0] + (c[0] + 0.5).floor() - c[0], o[1] + (c[1] + 0.5).floor() - c[1]] + }, + raw_size: [raw_edges[2] - raw_edges[0], raw_edges[3] - raw_edges[1]], + contain: pinh.snap.contain.map(|v| v * s), + radii, + sc, + o, + draw, + clip, + fade, + group: pinh.group, + pressed, + press_to, + loop_value, + cover, + scale_motion, + rest: pinh.still.0, + gliding, + caret, + shown: if !turned && !pinh.in_cache { [clip[1].max(vp[1] - m), clip[3].min(vp[3] + m)] } else { [clip[1], clip[3]] }, + }, + sel_ranges, + mark_ranges, + glyph_count, + ); + faded_slot + } +} diff --git a/app/vendor/rune/crates/rune/src/runtime/paint/cache_layer.rs b/app/vendor/rune/crates/rune/src/runtime/paint/cache_layer.rs new file mode 100644 index 0000000..027bf9e --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/paint/cache_layer.rs @@ -0,0 +1,434 @@ +//! `El::cache` offscreen raster caching: subtree eligibility and state hashing before paint, +//! and bounds/signature sealing when a cached layer closes. +use super::*; +use crate::machine::Effects; + +#[cfg(test)] +#[path = "cache_layer_tests.rs"] +mod tests; + +#[derive(Clone, Copy, Debug, PartialEq)] +pub(in crate::runtime) enum ScaleSettle { + Still(f32), + Settling { scale: f32, since: f64 }, +} + +#[derive(Clone, Copy)] +pub(in crate::runtime) struct AnotherFrame; + +impl ScaleSettle { + /// Paint samples the animation clock, not a wall-clock deadline. Continue to + /// request frames during the interval, including when the clock is slowed. + #[inline] + pub(in crate::runtime) fn step(&mut self, scale: f32, now: f64, reset: bool, epsilon: f32, poll: bool) -> Effects<AnotherFrame> { + let (seen, since) = match *self { + Self::Still(seen) => (seen, f64::NEG_INFINITY), + Self::Settling { scale, since } => (scale, since), + }; + // A real change is a strict comparison, as dev's was: a NaN or infinite scale + // equals neither, so it never restarts the window. + let changed = !reset && (scale - seen).abs() > epsilon; + let since = if reset { + *self = Self::Still(scale); + f64::NEG_INFINITY + } else if changed { + *self = Self::Settling { scale, since: now }; + now + } else { + since + }; + // Frames follow elapsed time since that change, so nothing compared per frame can + // extend the window past `STATIC_SCALE_SETTLE`. + if poll && now - since < STATIC_SCALE_SETTLE { Effects::One(AnotherFrame) } else { Effects::None } + } +} + +#[derive(Clone, Copy, Debug)] +pub(in crate::runtime) enum RasterPhase { + Live, + Raster { paint_hash: u64 }, +} + +#[derive(Clone, Copy, Debug, PartialEq)] +pub(in crate::runtime) enum RasterPass { + Paint { glyph_start: usize }, + Elide { glyphs: usize }, +} + +#[derive(Clone, Debug)] +pub(in crate::runtime) struct NodeCache { + pub(in crate::runtime) signature: u64, + pub(in crate::runtime) raster_scale: f32, + pub(in crate::runtime) scale: ScaleSettle, + pub(in crate::runtime) env_scale: f32, + pub(in crate::runtime) phase: RasterPhase, + pub(in crate::runtime) rel_bounds: [f32; 4], + pub(in crate::runtime) glyphs: usize, + pub(in crate::runtime) commit_gen: u64, +} + +#[derive(Clone, Copy)] +pub(in crate::runtime) struct ActiveCache { + pub(in crate::runtime) node_index: usize, + pub(in crate::runtime) node_id: NodeId, + pub(in crate::runtime) instance_start: usize, + pub(in crate::runtime) origin: [f32; 2], + pub(in crate::runtime) size: [f32; 2], + pub(in crate::runtime) cur_scale: f32, + pub(in crate::runtime) scale: ScaleSettle, + pub(in crate::runtime) env_scale: f32, + /// Everything outside commits that paints the subtree: hover, press, links, an outside + /// hover group and the window-wide state in `build`'s paint hash. + pub(in crate::runtime) paint_hash: u64, + pub(in crate::runtime) pass: RasterPass, +} + +impl NodeCache { + #[inline] + pub(in crate::runtime) fn committed_scale(&mut self, scale: f32, now: f64) -> Option<AnotherFrame> { + if (scale - self.raster_scale).abs() > 1e-4 + && matches!(self.scale.step(scale, now, false, 1e-4, true), Effects::One(_)) + { + self.phase = RasterPhase::Live; + Some(AnotherFrame) + } else { None } + } + + #[inline] + pub(in crate::runtime) fn open(&self, eff_scale: f32, s: f32, settled: bool, now: f64, commit_gen: u64, + is_resident: bool, scale_motion: ScaleMotion, paint_hash: u64, check: impl FnOnce() -> bool, + glyph_start: usize) -> (ScaleSettle, RasterPass, Option<AnotherFrame>) { + let env_same = (s - self.env_scale).abs() <= 1e-4 && !settled; + let mut scale = self.scale; + let scale_diff = (eff_scale - self.raster_scale).abs() > 1e-4; + let same_commit = commit_gen == self.commit_gen; + let eligible = same_commit && scale_diff && env_same && is_resident && matches!(self.phase, RasterPhase::Raster { .. }); + let pending = scale.step(eff_scale, now, !env_same, 1e-4, eligible); + let scale_settling = eligible && (matches!(pending, Effects::One(_)) || scale_motion == ScaleMotion::Moving); + // A commit can change any paint property. Never use a partial + // model hash to skip checking the actual emitted draw output. + let content_same = same_commit && (!scale_diff || scale_settling); + let can_elide = is_resident + && matches!(self.phase, RasterPhase::Raster { .. }) + && content_same + && matches!(self.phase, RasterPhase::Raster { paint_hash: hash } if hash == paint_hash) + && !check(); + let pass = if can_elide { RasterPass::Elide { glyphs: self.glyphs } } else { RasterPass::Paint { glyph_start } }; + (scale, pass, scale_settling.then_some(AnotherFrame)) + } +} + +impl RuntimeCore { + pub(in crate::runtime) fn prepare_cache_layers(&mut self, sel_ranges: &[(usize, usize, usize)], mark_ranges: &[(usize, usize, usize)]) -> u64 { + let (s, n_nodes) = (self.env.scale, self.tree.nodes.len()); + self.paint.cache_live_scratch.clear(); + self.paint.cache_check_scratch.clear(); + self.paint.cache_paint_scratch.clear(); + self.paint.cache_inside_scratch.clear(); + let mut paint_state_hash = 0u64; + if self.tree.has_cache { + use std::hash::{Hash, Hasher}; + let mut h = rune_motion::Fx::default(); + self.pointer.hovered.hash(&mut h); + self.pointer.hover_within.hash(&mut h); + self.kbd.focus.path().hash(&mut h); + self.kbd.focus.keyboard().hash(&mut h); + self.kbd.focus.hovered().hash(&mut h); + self.commit.defaults.force_focus_rings.hash(&mut h); + if let Some(ring) = self.commit.defaults.focus_ring { + let c = ring.color; + [ring.width, ring.offset, c.r, c.g, c.b, c.a].map(f32::to_bits).hash(&mut h); + } + (self.paint.srgb_blend, self.text.smoothing, self.text.families(), crate::text::icon::swap_id()).hash(&mut h); + h.write_u32(s.to_bits()); + sel_ranges.hash(&mut h); + // A selection's colours follow the window's focus (`El::selection_style`). + if !sel_ranges.is_empty() { + self.host.window_focused.hash(&mut h); + } + mark_ranges.hash(&mut h); + let mut scroll_mix = 0u64; + for (&id, st) in &self.scroll.scrolls { + let mut sh = rune_motion::Fx::default(); + sh.write_u64(id.0); + sh.write_u64(st.offset.to_bits()); + sh.write_u64(st.x.offset.to_bits()); + sh.write_u32(st.held as u32); + sh.write_u32(st.slack.height().to_bits()); + scroll_mix = scroll_mix.wrapping_add(sh.finish()); + } + for (path, &off) in &self.edit.input_scroll { + let mut sh = rune_motion::Fx::default(); + path.hash(&mut sh); + sh.write_u32(off.to_bits()); + scroll_mix = scroll_mix.wrapping_add(sh.finish()); + } + h.write_u64(scroll_mix); + paint_state_hash = h.finish(); + + self.paint.cache_live_scratch.resize(n_nodes, false); + self.paint.cache_check_scratch.resize(n_nodes, false); + self.paint.cache_paint_scratch.resize(n_nodes, 0); + // Only cached subtrees read these, so skip everything outside them. + self.paint.cache_inside_scratch.resize(n_nodes, false); + for i in 0..n_nodes { + let n = &self.tree.nodes[i]; + self.paint.cache_inside_scratch[i] = n.vis_flags.cache() || n.parent.is_some_and(|p| self.paint.cache_inside_scratch[p]); + } + let store = self.scene.store(); + for i in (0..n_nodes).rev() { + if !self.paint.cache_inside_scratch[i] { continue; } + let n = &self.tree.nodes[i]; + let live = store.is_node_animating(n.id) + // Sticky and anchored descendants move within a raster without motion tracks. + || self.sticky_of(i).is_some() + || n.above.is_some() + || (!self.reduced_motion && self.motion.loop_active(n.id, store.node_time(n.id))) + || (!self.reduced_motion + && self.text.has_animated_icons() + && (n.vis.icon.is_some_and(|(ic, _)| { + let mount_t = self.paint.icon_mount_time(n.id, ic as *const crate::text::Icon as usize, self.t); + self.text.icon_anim_live(ic, self.t, mount_t) + }) || n.text.as_ref().is_some_and(|t| { + t.cold.pills.iter().any(|p| { + p.icon.is_some_and(|ic| { + let mount_t = self.paint.icon_mount_time(n.id, ic as *const crate::text::Icon as usize, self.t); + self.text.icon_anim_live(ic, self.t, mount_t) + }) + }) + }))) + || self.motion.grows.get(&n.id).is_some_and(|g| g.moving()) + || self.scroll.scrolls.get(&n.id).is_some_and(|st| st.slack.height() > 0.0) + || self.motion.reveal_fading(n.id) + || self.subtree_exiting(i) + || (!self.motion.flights().is_empty() && self.motion.flights().iter().any(|f| f.departs(&n.path, n.key.as_deref()) || f.lands(&n.path, n.key.as_deref()))) + || n.vis.effect.is_some() + // A publication can replace texels without moving the atlas slot, so + // identical image primitives do not imply identical raster contents. + || n.vis.pixels.is_some() + || n.vis.surface.is_some() + || (n.material.is_some() && self.paint.native_materials) + // Never retain a raster of a secret, even when the field is unfocused. + || n.text.as_ref().is_some_and(|t| t.redacted) + || n.input.as_ref().is_some_and(|inp| inp.edit.focused || inp.edit.is_secure()) + || n.text.as_ref().is_some_and(|t| t.cold.advance_in.is_some()); + let check = n.text.as_ref().is_some_and(|t| t.cold.live.is_some()) + || n.live.iter().any(|b| !n.vis_flags.cache() || !matches!(b.property, crate::live::Property::Offset | crate::live::Property::Scale)); + self.paint.cache_live_scratch[i] |= live; + self.paint.cache_check_scratch[i] |= check; + // Hover, press and link paint land without a commit (an instant track or a + // pointer move inside one text), so hash what this frame samples. + let links = n.text.as_ref().is_some_and(|t| !t.cold.links.is_empty()); + if n.vis.hover().a > 0.0 || n.vis_flags.hover_group() || n.vis.tracks_press() || n.handlers.get().is_some_and(|h| h.press_scale.is_some()) || links { + let mut ph = rune_motion::Fx::default(); + ph.write_u64(n.id.0); + for prop in [P_HOVER, P_PRESS, P_PRESS_SCALE] { + ph.write_u32(self.scene.get(n.id, prop).unwrap_or(0.0).to_bits()); + } + if links { self.link_states(i).hash(&mut ph); } + self.paint.cache_paint_scratch[i] = self.paint.cache_paint_scratch[i].wrapping_add(ph.finish()); + } + if let Some(p) = n.parent { + self.paint.cache_paint_scratch[p] = self.paint.cache_paint_scratch[p].wrapping_add(self.paint.cache_paint_scratch[i]); + // A lifted descendant draws outside this raster; don't elide its inputs. + self.paint.cache_live_scratch[p] |= self.paint.cache_live_scratch[i] || n.vis_flags.raise(); + self.paint.cache_check_scratch[p] |= self.paint.cache_check_scratch[i] || !n.live.is_empty(); + } + } + } + paint_state_hash + } +} + +impl state::PaintState { + #[allow(clippy::too_many_arguments)] + pub(in crate::runtime) fn close_cached_layer( + &mut self, + nodes: &[Node], + instances: &mut Vec<Instance>, + surfaces: &mut [crate::native_surface::SurfaceDraw], + marks: &mut Vec<u32>, + track_marks: bool, + text: &mut TextSystem, + commit_gen: u64, + ac: ActiveCache, + start: usize, + surface_start: usize, + glyph_count: &mut usize, + ) { + use std::hash::Hasher; + let layer_grow = (3.0 * crate::render::layer_blur::sigma(instances[start].params[2])).ceil(); + let glyph_start = match ac.pass { + RasterPass::Paint { glyph_start } => glyph_start, + RasterPass::Elide { glyphs } => { + let entry = self.node_caches.get_mut(&ac.node_id).expect("elided cache entry"); + entry.scale = ac.scale; + let k = if (ac.cur_scale - entry.raster_scale).abs() <= 1e-4 { + 1.0 + } else { + ac.cur_scale / entry.raster_scale.max(1e-4) + }; + let b0 = (ac.origin[0] + entry.rel_bounds[0] * k).floor(); + let b1 = (ac.origin[1] + entry.rel_bounds[1] * k).floor(); + let b2 = (ac.origin[0] + entry.rel_bounds[2] * k).ceil(); + let b3 = (ac.origin[1] + entry.rel_bounds[3] * k).ceil(); + let sig = entry.signature; + Self::seal_cache_marker(instances, marks, track_marks, start, [b0, b1, (b2 - b0).max(0.0), (b3 - b1).max(0.0)], ac.node_id, sig); + *glyph_count += glyphs; + return; + } + }; + + if instances.len() == start + 1 && surfaces.len() == surface_start { + instances.pop(); + if track_marks { + marks.truncate(instances.len()); + } + self.evict_cache(text, ac.node_id); + return; + } + + let mut bounds = [ac.origin[0], ac.origin[1], ac.origin[0] + ac.size[0], ac.origin[1] + ac.size[1]]; + let mut h = rune_motion::Fx::default(); + h.write_u64(ac.node_id.0); + // Blur is baked into the target, unlike opacity and clipping on the composite. + h.write_u32(instances[start].params[2].to_bits()); + h.write_u8(self.srgb_blend as u8 | (text.smoothing as u8) << 1); + h.write_u32(ac.cur_scale.to_bits()); + h.write_u32(ac.size[0].to_bits()); + h.write_u32(ac.size[1].to_bits()); + if let Some(key) = nodes[ac.node_index].vis.cache_key { + h.write_u8(1); + h.write_u64(key); + } else { + h.write_u8(0); + } + let q = |v: f32| (v * 64.0).round() as i64; + let mut turn_stack: Vec<Option<Turn>> = Vec::new(); + for inst in &instances[start + 1..] { + if inst.params[1] == crate::render::KIND_LAYER_END { + turn_stack.pop(); + } else { + let active_turn = turn_stack.last().copied().flatten(); + let (mut c0, mut c1, mut c2, mut c3) = if inst.params[1] == crate::render::KIND_LAYER { + let next = if inst.border[1] != 0.0 { + let own = Turn::about(inst.border[1], [inst.border[2], inst.border[3]], inst.rect, NO_CLIP); + Some(active_turn.map_or(own, |t| t.after(own))) + } else { + active_turn + }; + turn_stack.push(next); + let g = (3.0 * crate::render::layer_blur::sigma(inst.params[2])).ceil(); + let mut r = [inst.rect[0] - g, inst.rect[1] - g, inst.rect[0] + inst.rect[2] + g, inst.rect[1] + inst.rect[3] + g]; + if inst.border[1] != 0.0 { + r = Turn::about(inst.border[1], [inst.border[2], inst.border[3]], inst.rect, NO_CLIP).bbox(r); + } + ( + r[0].max(inst.clip[0]), + r[1].max(inst.clip[1]), + r[2].min(inst.clip[2]), + r[3].min(inst.clip[3]), + ) + } else { + let mut rect = inst.rect; + if inst.params[1] == KIND_GLYPH && inst.params[0] != 0.0 { + let (sin, cos) = inst.params[0].sin_cos(); + let width = cos.abs() * rect[2] + sin.abs() * rect[3]; + let height = sin.abs() * rect[2] + cos.abs() * rect[3]; + rect = [rect[0] + (rect[2] - width) * 0.5, rect[1] + (rect[3] - height) * 0.5, width, height]; + } + let grow = match inst.params[1] { + KIND_GLYPH => 0.0, + KIND_SHADOW => inst.params[2] * 3.0 + 1.0, + KIND_EFFECT => inst.params[2] + 1.0, + KIND_RECT | KIND_GRADIENT | KIND_DASHED | KIND_RADIAL => 1.0 + inst.params[2] * 2.0, + _ => 1.0, + }; + ( + (rect[0] - grow).max(inst.clip[0]), + (rect[1] - grow).max(inst.clip[1]), + (rect[0] + rect[2] + grow).min(inst.clip[2]), + (rect[1] + rect[3] + grow).min(inst.clip[3]), + ) + }; + if c2 > c0 && c3 > c1 { + if let Some(t) = active_turn { + [c0, c1, c2, c3] = t.bbox([c0, c1, c2, c3]); + } + bounds[0] = bounds[0].min(c0); + bounds[1] = bounds[1].min(c1); + bounds[2] = bounds[2].max(c2); + bounds[3] = bounds[3].max(c3); + } + } + h.write_i64(q(inst.rect[0] - ac.origin[0])); + h.write_i64(q(inst.rect[1] - ac.origin[1])); + h.write_i64(q(inst.rect[2])); + h.write_i64(q(inst.rect[3])); + for r in inst.radii { h.write_u32(r.to_bits()); } + for f in inst.fill { h.write_u32(f.to_bits()); } + for b in inst.border { h.write_u32(b.to_bits()); } + for p in inst.params { h.write_u32(p.to_bits()); } + for u in inst.uv { h.write_u32(u.to_bits()); } + for k in 0..4 { + let cv = inst.clip[k]; + if cv.abs() < 1e6 { + h.write_i64(q(cv - ac.origin[k & 1])); + } else { + h.write_u32(cv.to_bits()); + } + } + for fd in inst.fade { h.write_u32(fd); } + } + let b0 = (bounds[0] - layer_grow).floor(); + let b1 = (bounds[1] - layer_grow).floor(); + let b2 = (bounds[2] + layer_grow).ceil(); + let b3 = (bounds[3] + layer_grow).ceil(); + let bw = (b2 - b0).max(0.0); + let bh = (b3 - b1).max(0.0); + if bw > 4096.0 || bh > 4096.0 { + self.evict_cache(text, ac.node_id); + crate::render::end_layer(instances, surfaces, marks, start, surface_start); + return; + } + let mut sig = h.finish(); + if sig == 0 { sig = 1; } + let rel_bounds = [b0 - ac.origin[0], b1 - ac.origin[1], b2 - ac.origin[0], b3 - ac.origin[1]]; + let glyphs = *glyph_count - glyph_start; + let is_resident = text.atlas.resident_caches.get(&ac.node_id.0) == Some(&sig); + self.node_caches.insert(ac.node_id, NodeCache { + signature: sig, + raster_scale: ac.cur_scale, + scale: ac.scale, + env_scale: ac.env_scale, + phase: RasterPhase::Raster { paint_hash: ac.paint_hash }, + rel_bounds, + glyphs, + commit_gen, + }); + if is_resident && surfaces.len() == surface_start { + instances.truncate(start + 1); + } + Self::seal_cache_marker(instances, marks, track_marks, start, [b0, b1, bw, bh], ac.node_id, sig); + } + + /// Finishes a cached layer's marker at `rect`, naming its cache entry and signature, and + /// closes the layer. + fn seal_cache_marker(instances: &mut Vec<Instance>, marks: &mut Vec<u32>, track_marks: bool, start: usize, rect: [f32; 4], id: NodeId, sig: u64) { + let marker = &mut instances[start]; + marker.rect = rect; + marker.params[3] = 1.0; + marker.radii = crate::render::pack_u64_f32(id.0); + marker.uv = crate::render::pack_u64_f32(sig); + instances.push(Instance::end_layer()); + if track_marks { + let mark = marks.get(start).copied().unwrap_or(0); + marks.resize(instances.len(), mark); + } + } + + fn evict_cache(&mut self, text: &mut TextSystem, id: NodeId) { + self.node_caches.remove(&id); + text.atlas.resident_caches.remove(&id.0); + } +} diff --git a/app/vendor/rune/crates/rune/src/runtime/paint/cache_layer_tests.rs b/app/vendor/rune/crates/rune/src/runtime/paint/cache_layer_tests.rs new file mode 100644 index 0000000..a4be34b --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/paint/cache_layer_tests.rs @@ -0,0 +1,184 @@ +use super::*; + +#[derive(Clone, Copy, Debug)] +enum Event { Paint, Zoom, CommitZoom, Wait, LoseRaster, Settle, Overflow, Nan } + +#[derive(Clone, Copy)] +struct OldEntry { + raster_scale: f32, seen_scale: f32, scale_changed_at: f64, env_scale: f32, + was_live: bool, glyphs: usize, commit_gen: u64, paint_state_hash: u64, +} + +#[derive(Clone, Copy, Default)] +struct Old { entry: Option<OldEntry>, static_scale: Option<(f32, f64)> } + +// One cached solid rect: no live bindings, animated ancestors or checked descendants. +// The paint hash is constant. The renderer reports residency separately for each paint. +impl Old { + fn paint(&mut self, eff_scale: f32, now: f64, commit_gen: u64, settled: bool, is_resident: bool) -> bool { + let mut static_scale_settling = false; + let moving = if eff_scale != 1.0 || self.static_scale.is_some() { + let seen = self.static_scale.get_or_insert((eff_scale, f64::NEG_INFINITY)); + if settled { + *seen = (eff_scale, f64::NEG_INFINITY); + } else if (seen.0 - eff_scale).abs() > 1e-5 { + *seen = (eff_scale, now); + } + let moving = now - seen.1 < 0.1; + static_scale_settling |= moving; + moving + } else { false }; + let mut committed_scale_moving = false; + if let Some(entry) = &mut self.entry && entry.commit_gen != commit_gen && (eff_scale - entry.raster_scale).abs() > 1e-4 { + if (eff_scale - entry.seen_scale).abs() > 1e-4 { + entry.seen_scale = eff_scale; + entry.scale_changed_at = now; + } + committed_scale_moving = now - entry.scale_changed_at < 0.1; + if committed_scale_moving { + entry.was_live = true; + static_scale_settling = true; + } + } + // Dev only opens a cache whose estimated bounds fit in 4096 px; this 32 px box + // estimates at `32 * scale`, so an infinite, NaN or enormous scale opens none, and + // the entry stays as it was. + if !committed_scale_moving && (32.0 * eff_scale).ceil() <= 4096.0 { + let (raster_scale, seen_scale, scale_changed_at, elided, _) = if let Some(entry) = self.entry { + let env_same = (1.0 - entry.env_scale).abs() <= 1e-4 && !settled; + let (seen_scale, scale_changed_at) = if !env_same { + (eff_scale, f64::NEG_INFINITY) + } else if (eff_scale - entry.seen_scale).abs() > 1e-4 { + (eff_scale, now) + } else { (entry.seen_scale, entry.scale_changed_at) }; + let scale_diff = (eff_scale - entry.raster_scale).abs() > 1e-4; + let same_commit = commit_gen == entry.commit_gen; + let scale_settling = same_commit && scale_diff && env_same && is_resident && !entry.was_live + && (now - scale_changed_at < 0.1 || moving); + static_scale_settling |= scale_settling; + let content_same = same_commit && (!scale_diff || scale_settling); + let can_elide = is_resident && !entry.was_live && content_same && 0 == entry.paint_state_hash; + let raster_scale = if can_elide && scale_settling { entry.raster_scale } else { eff_scale }; + (raster_scale, seen_scale, scale_changed_at, can_elide, entry.glyphs) + } else { (eff_scale, eff_scale, f64::NEG_INFINITY, false, 0) }; + if elided { + let entry = self.entry.as_mut().unwrap(); + entry.seen_scale = seen_scale; + entry.scale_changed_at = scale_changed_at; + } else { + self.entry = Some(OldEntry { raster_scale, seen_scale, scale_changed_at, env_scale: 1.0, + was_live: false, glyphs: 0, commit_gen, paint_state_hash: 0 }); + } + } + static_scale_settling + } +} + +fn fields(scale: ScaleSettle) -> (f32, f64) { + match scale { + ScaleSettle::Still(s) => (s, f64::NEG_INFINITY), + ScaleSettle::Settling { scale, since } => (scale, since), + } +} + +/// Bit patterns, so an infinite or NaN observation compares equal to itself. +fn bits((scale, since): (f32, f64)) -> (u32, u64) { + (scale.to_bits(), since.to_bits()) +} + +#[test] +fn every_paint_cache_walk_matches_dev() { + let mut rt = Runtime::new((), |_, _| crate::el().key("cache").size(32.0, 32.0).cache().fill(Color::WHITE), + (64.0, 64.0), Env::new(true, 1.0)); + rt.frame(0.0); + let i = rt.tree.nodes.iter().position(|n| n.key.as_deref() == Some("cache")).unwrap(); + let id = rt.tree.nodes[i].id; + rt.paint.node_caches.clear(); + rt.paint.static_scales.clear(); + fn walk(rt: &mut Runtime<()>, i: usize, id: NodeId, old: Old, scale: f32, now: f64, generation: u64, depth: u32) { + if depth == 5 { return; } + let saved = rt.paint.node_caches.clone(); + let tracked = rt.paint.static_scales.clone(); + for event in [Event::Paint, Event::Zoom, Event::CommitZoom, Event::Wait, Event::LoseRaster, Event::Settle, Event::Overflow, Event::Nan] { + rt.paint.node_caches.clone_from(&saved); + rt.paint.static_scales.clone_from(&tracked); + let mut old = old; + // An overflowing commit reaches the cache at an infinite scale; the paints after + // it return to a size the raster path can open at, so the reference's always-opens + // model stays the one dev had. + let commit = matches!(event, Event::CommitZoom | Event::Overflow | Event::Nan); + let finite = if (-4.0..=4.0).contains(&scale) { scale } else { 1.5 }; + let scale = match event { + Event::Zoom => 3.0 - finite, + Event::CommitZoom => 3.0 - finite, + Event::Overflow => f32::MAX, + Event::Nan => f32::NAN, + _ => finite, + }; + let now = now + if matches!(event, Event::Wait) { 0.1 } else { 0.03125 }; + let generation = generation + commit as u64; + let settled = matches!(event, Event::Settle); + let resident = !matches!(event, Event::LoseRaster); + // A nonzero cached glyph count makes reuse distinguishable from repainting this rect. + rt.text.atlas.resident_caches.clear(); + if let Some(entry) = rt.paint.node_caches.get_mut(&id) { + entry.glyphs = 17; + if resident { rt.text.atlas.resident_caches.insert(id.0, entry.signature); } + } + if let Some(entry) = &mut old.entry { entry.glyphs = 17; } + rt.tree.nodes[i].static_scale = scale; + rt.t = now; + rt.settled = settled; + rt.commit.set_commit_gen(generation); + rt.build(); + let expected_frame = old.paint(scale, now, generation, settled, resident); + assert_eq!(rt.paint.scale_frame.is_some(), expected_frame, "{event:?} at {now}"); + assert_eq!(rt.paint.static_scales.get(&id).copied().map(fields).map(bits), old.static_scale.map(bits)); + match (old.entry, rt.paint.node_caches.get(&id)) { + (Some(e), Some(a)) => assert_eq!( + (a.raster_scale.to_bits(), bits(fields(a.scale)), a.env_scale.to_bits(), matches!(a.phase, RasterPhase::Live), a.glyphs, a.commit_gen), + (e.raster_scale.to_bits(), bits((e.seen_scale, e.scale_changed_at)), e.env_scale.to_bits(), e.was_live, e.glyphs, e.commit_gen), + "{event:?} at {now}"), + (None, None) => {}, + (e, a) => panic!("{event:?} at {now}: a cache entry survived on one side only: {} / {}", e.is_some(), a.is_some()), + } + walk(rt, i, id, old, scale, now, generation, depth + 1); + } + } + walk(&mut rt, i, id, Old::default(), 1.0, 0.0, 1, 0); +} + +#[test] +fn a_scale_that_overflows_at_two_x_stops_asking_for_frames() { + fn view(_: &(), _: &mut Cx<()>) -> El { + crate::el().key("cache").size(32.0, 32.0).cache().fill(Color::WHITE) + } + // Committing `f32::MAX` on a 2× display overflows the scale the cache sees to infinity, + // so an unchanged paint compares `∞ - ∞`, which is NaN. + let mut rt = Runtime::new((), view, (64.0, 64.0), Env::new(true, 2.0)); + rt.frame(0.0); + let i = rt.tree.nodes.iter().position(|n| n.key.as_deref() == Some("cache")).unwrap(); + let id = rt.tree.nodes[i].id; + assert!(rt.paint.node_caches.contains_key(&id), "a cached raster to reuse"); + rt.tree.nodes[i].static_scale = f32::MAX; + let (mut now, mut generation, mut frames) = (1.0, rt.commit.commit_gen(), 0); + // A drag commits every frame. + while now < 1.5 { + now += 1.0 / 60.0; + generation += 1; + rt.t = now; + rt.commit.set_commit_gen(generation); + rt.build(); + if rt.paint.scale_frame.is_none() { break; } + frames += 1; + } + assert!(frames < 12, "frames stop after the settle window, not every frame: {frames}"); + for _ in 0..5 { + now += 1.0 / 60.0; + generation += 1; + rt.t = now; + rt.commit.set_commit_gen(generation); + rt.build(); + assert!(rt.paint.scale_frame.is_none(), "and stay stopped"); + } +} diff --git a/app/vendor/rune/crates/rune/src/runtime/paint/content.rs b/app/vendor/rune/crates/rune/src/runtime/paint/content.rs new file mode 100644 index 0000000..cfa249f --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/paint/content.rs @@ -0,0 +1,978 @@ +//! Leaf content painting inside a box: vector shapes, images, icons and rich text. +use super::*; + +pub(in crate::runtime) struct LeafBox { + pub r: [f32; 4], + pub r_exact: [f32; 4], + /// Where its exact box rests against where its snapped box rests (device px), its paint + /// containment's rounding in: Blink's text lays out from the exact place. + pub exact_off: [f32; 2], + pub raw_size: [f32; 2], + /// The paint containment's origin above (`El::paint_contained`), device px: what draws + /// from its exact box's origin rounds against it, as Blink rounds inside it. + pub contain: [f32; 2], + pub radii: [f32; 4], + pub sc: f32, + pub o: f32, + pub draw: f32, + pub clip: [f32; 4], + pub fade: [f32; 4], + pub group: f32, + /// The nearest `El::press_color` (here or above) and how far a press on it is held. + pub pressed: f32, + pub press_to: Option<Color>, + pub loop_value: Option<f32>, + pub cover: Option<(f32, [f32; 2])>, + pub scale_motion: ScaleMotion, + /// The scale of the nearest still ancestor, which moving text rasterizes at. + pub rest: f32, + pub gliding: bool, + pub caret: Option<[f32; 4]>, + /// The rows of the screen, in pixels, where what it draws can show: its clip's, cut to the + /// window's unless it draws into a layer turned or cached first. A long text draws its + /// lines there and no others. + pub shown: [f32; 2], +} + +/// `v` (device px) on the device grid inside a paint containment at `c`: the containment's +/// origin and the offset in it each round half up, as Blink rounds them. +fn on_grid(v: f32, c: f32) -> f32 { + let round = |x: f32| (x + 0.5).floor(); + round(v - c) + round(c) +} + +impl RuntimeCore { + pub(in crate::runtime) fn paint_content( + &mut self, + i: usize, + b: LeafBox, + sel_ranges: &[(usize, usize, usize)], + mark_ranges: &[(usize, usize, usize)], + glyph_count: &mut usize, + ) { + let s = self.env.scale; + let srgb = self.paint.srgb_blend; + let now = self.t; + let LeafBox { + r, + r_exact, + exact_off, + raw_size, + contain, + radii, + sc, + o, + draw, + clip, + fade, + group, + pressed, + press_to, + loop_value, + cover, + scale_motion, + rest, + gliding, + caret: input_caret, + shown, + } = b; + let (w, h) = ((r[2] - r[0]).max(0.0), (r[3] - r[1]).max(0.0)); + let (w_exact, h_exact) = ((r_exact[2] - r_exact[0]).max(0.0), (r_exact[3] - r_exact[1]).max(0.0)); + let k_px = sc * s; + let link_fx = self.tree.nodes[i].text.is_some().then(|| self.link_fx(i)); + let node_id = self.tree.nodes[i].id; + let text_color = self.tree.nodes[i].vis.icon.map(|(_, c)| c) + .or_else(|| self.tree.nodes[i].text.as_ref().map(|sp| sp.color)) + .map(|c| self.color(node_id, P_TEXT, c)); + // A terminal's cell grid paints its rows itself (`grid.rs`). + if let Some(g) = self.tree.nodes[i].vis.grid.clone() { + self.paint.paint_grid(node_id, self.tree.nodes[i].flow, s, &g, r, r_exact, clip, fade, o, glyph_count, &mut self.text, &mut self.images, &mut self.instances); + } + self.fill_visible_by_line(i, r, exact_off, sc, cover, scale_motion, rest, gliding, shown); + let n = &self.tree.nodes[i]; + let text_tint = |c: Color| paint_tracks::press_tint(paint_tracks::group_tint(n, c, group), press_to, pressed); + if let Some(shape) = &n.vis.shape { + // At rest a shape draws from its exact box's origin rounded to the device grid, at its + // exact scale, as Chromium draws a canvas or an inline SVG: what it holds keeps its + // geometry against the grid, so a sheet's 1 px header line covers the same device rows + // (one whole and half the next at 1.5x) wherever the sheet sits. Moving or scaled, it + // stays centred in its snapped box, sharing the centre fills, borders and icons use, so + // a glide or a swap to an icon doesn't wobble. A view-boxed shape stretches to the box. + let still = cover.is_none() && scale_motion == ScaleMotion::Still && !gliding && (sc - 1.0).abs() < 1e-5; + let at = if still { + [on_grid(r_exact[0], contain[0]), on_grid(r_exact[1], contain[1])] + } else { + [r[0] + (w - w_exact) * 0.5, r[1] + (h - h_exact) * 0.5] + }; + let (origin, k) = match shape.view_box { + Some([vw, vh]) => ([r[0], r[1]], [w / vw, h / vh]), + None => (at, [k_px, k_px]), + }; + if let Some(t) = self.scene.get(node_id, P_TRIM) { + // A presence draw traces the trimmed span on from its start. + let end = t.x + (t.y - t.x) * draw; + push_shape(&mut self.instances, &shape.trimmed(t.x, end), origin, k, k_px, o, srgb, clip, fade); + } else if draw < 1.0 { + push_shape(&mut self.instances, &shape.drawn(draw), origin, k, k_px, o, srgb, clip, fade); + } else { + push_shape(&mut self.instances, shape, origin, k, k_px, o, srgb, clip, fade); + } + } + if let Some(pixels) = &n.vis.pixels { + let snap_u = if cover.is_none() { (1.0 - (sc - 1.0).abs() * 32.0).clamp(0.0, 1.0) } else { 0.0 }; + let (rect, crop) = crate::pixels::fit_in(n.vis.pixels_fit, n.vis.surface_place, [r[0], r[1], w, h], pixels.size(), snap_u); + let span = [crop[2] - crop[0], crop[3] - crop[1]]; + // The mip covers the whole image's drawn size, not just its visible window. + let placed = self.images.place_at(pixels, [rect[2] / span[0], rect[3] / span[1]], Some(now)); + // An animated image wakes the window for its next frame only while drawn in a shown + // window: off screen it isn't painted, so it asks for nothing. + if let Some((_, Some(at))) = placed && self.frame.live.visible() && self.time_scale > 0.0 { + let wake = self.clock + (at - now).max(0.0) / self.time_scale as f64; + self.paint.keep.cycles.other_deadline(); + self.motion.arm_loop_wake(wake, at); + } + if let Some((image, _)) = placed { + let [x, y, iw, ih] = image.rect.map(|v| v as f32); + // A letterboxed image rounds its own, smaller corners. + let half = rect[2].min(rect[3]) * 0.5; + self.instances.push(Instance { + rect, + radii: if n.vis.pixels_fit.is_some() { radii.map(|v| v.min(half)) } else { radii }, + fill: [0.0, 0.0, 0.0, o], + border: [0.0; 4], + params: [image.page as f32, KIND_IMAGE, image.premultiplied as u8 as f32, 1.0], + // The shader samples from a whole-texel origin; the span may be fractional. + uv: [x + (crop[0] * iw).round(), y + (crop[1] * ih).round(), span[0] * iw, span[1] * ih], + clip, + fade: crate::render::pack_fade(fade, clip, clip), + }); + } + } + if let Some((ic, _)) = n.vis.icon { + let color = text_tint(text_color.unwrap()); + let looped = if matches!(n.looping.as_ref().map(|l| l.kind), Some(rune_motion::LoopKind::Rotation)) { loop_value.unwrap_or(0.0) } else { 0.0 }; + let turn = looped + if self.scene.store().has(n.id, P_ICON_TURN) { + self.scene.get(n.id, P_ICON_TURN).unwrap_or(n.vis.icon_turn) + } else { n.vis.icon_turn }; + // `El::mirror_in_rtl`: the drawing mirrors (its turn already runs the other way). + let facing = match (n.flow, n.vis.mirror_rtl) { + (crate::el::Flow::Rtl, true) => crate::text::Facing::Mirrored, + _ => crate::text::Facing::Upright, + }; + let tk = if cover.is_some() { 1.0 } else { sc }; + let raster = if cover.is_some() { 1.0 } else { scale_motion.raster(sc, rest) }; + if cover.is_none() && scale_motion == ScaleMotion::Live { + self.paint.scale_frame = Some(AnotherFrame); + } + let zoom = tk / raster.max(1e-4); + let exact_side = w_exact.min(h_exact); + let raw_side = raw_size[0].min(raw_size[1]).max(0.0) * s; + let snap_u = if cover.is_none() && (raw_side - raw_side.round()).abs() < 1.0 / 512.0 { + (1.0 - (sc - 1.0).abs() * 32.0).clamp(0.0, 1.0) + } else { + 0.0 + }; + let drawn = exact_side + (w.min(h) - exact_side) * snap_u; + let px = if cover.is_none() && scale_motion != ScaleMotion::Still { + (raw_side * raster).round().max(1.0) as u32 + } else { + (drawn / zoom.max(1e-4)).round().max(1.0) as u32 + }; + let pos = [(r[0] + r[2] - drawn) * 0.5, (r[1] + r[3] - drawn) * 0.5]; + // At rest, a monochrome icon draws as Chromium paints an inline SVG: its box's own + // origin rounded to the device grid (not the box a centring snap shrank by a pixel, + // which redrew it at another scale), and the drawing at its exact scale on a canvas + // the size rounded up, 1:1 on the grid. A 1 pt stroke at 1.875x covers two pixels + // at 94% instead of one whole and two at 40%. Moving, turned or scaled icons keep + // the sub-pixel path below. + let resting = cover.is_none() && scale_motion == ScaleMotion::Still && !gliding && turn == 0.0 && (sc - 1.0).abs() < 1e-5; + let exact = w_exact.min(h_exact); + let kind = self.text.icon_kind(ic); + if kind == crate::text::IconKind::AnimatedMono && !self.reduced_motion && drawn > 1e-4 { + let (canvas, scale_side, at, draw_side) = if resting && exact > 1e-4 { + let canvas = (exact - 1.0 / 64.0).ceil().max(1.0) as u32; + let at = [on_grid(r_exact[0] + (w_exact - exact) * 0.5, contain[0]), on_grid(r_exact[1] + (h_exact - exact) * 0.5, contain[1])]; + (canvas, exact, at, canvas as f32) + } else { + (px, px as f32, pos, drawn) + }; + if !paint_animated_icon( + &mut self.text, + &mut self.paint, + &mut self.instances, + self.frame.live.visible(), + self.t, + self.time_scale, + n.id, + ic, + (canvas, scale_side), + at, + draw_side, + turn, + facing, + color, + o, + srgb, + clip, + fade, + ) && let Some(q) = self.text.icon_quad_sized(ic, (canvas, scale_side), at, facing) + { + self.push_icon(icon_inst(&q, at, draw_side, turn, premul(color, o, srgb), clip, fade)); + } + } else if resting && exact > 1e-4 && kind != crate::text::IconKind::Color { + let canvas = (exact - 1.0 / 64.0).ceil().max(1.0) as u32; + let at = [on_grid(r_exact[0] + (w_exact - exact) * 0.5, contain[0]), on_grid(r_exact[1] + (h_exact - exact) * 0.5, contain[1])]; + if let Some(q) = self.text.icon_quad_sized(ic, (canvas, exact), at, facing) { + self.push_icon(icon_inst(&q, at, canvas as f32, 0.0, premul(color, o, srgb), clip, fade)); + } + // An icon that paints its own colours draws as its image (or its silhouette in + // `color`, `El::icon_one_color`), upright, faded only by the + // element's opacity and its colour's alpha. + } else if kind == crate::text::IconKind::Color && drawn > 1e-4 && let Some(pixels) = self.text.color_icon(ic, px, color, n.vis.icon_one_color) { + if let Some(image) = self.images.place(pixels, [drawn, drawn]) { + self.instances.push(Instance { + rect: [pos[0], pos[1], drawn, drawn], + radii: [0.0; 4], + fill: [0.0, 0.0, 0.0, premul(color, o, srgb)[3]], + border: [0.0; 4], + params: [image.page as f32, KIND_IMAGE, image.premultiplied as u8 as f32, 1.0], + uv: image.rect.map(|v| v as f32), + clip, + fade: crate::render::pack_fade(fade, clip, clip), + }); + } + } else if drawn > 1e-4 && let Some(q) = self.text.icon_quad_facing(ic, px, pos, facing) { + self.push_icon(icon_inst(&q, pos, drawn, turn, premul(color, o, srgb), clip, fade)); + } + } else if let (Some(spec), Some(laid)) = (&n.text, &n.text_layout) { + let flow = laid.view(); + let link_fx = link_fx.unwrap(); + let color = text_tint(text_color.unwrap()); + // A matched flight places its own text in its scaled content box. Its glyphs keep + // their rest size so a label doesn't pop at the swap. + let (zk, zr) = match cover { + Some((k, c)) => (k, [r[0] + c[0] * s, r[1] + c[1] * s, + r[0] + (c[0] + n.local.w * k) * s, r[1] + (c[1] + n.local.h * k) * s]), + None => (sc, r), + }; + // Everywhere else text scales with its box (`El::scale`, `live_scale`, + // `press_scale`, transitions): `tk` about the text's origin. It rasterizes at + // `raster` and draws filtered by the rest, `tk / raster`. + let tk = if cover.is_some() { 1.0 } else { sc }; + let raster = if cover.is_some() { 1.0 } else { scale_motion.raster(sc, rest) }; + if cover.is_none() && scale_motion == ScaleMotion::Live { + self.paint.scale_frame = Some(AnotherFrame); + } + // Text whose scale moves draws from its outlines, magnified to `tk`: crisp all the way, + // and the same outline on the frame it lands as the atlas mask it rests as. + let place_masks = self.text.begin_text(node_id.0, cover.is_none() && scale_motion != ScaleMotion::Still) + .into_iter().any(|e| e == crate::text::outline::PathEffect::PlaceMasks); + // The frame it lands draws outlines while its masks are placed; one more frame draws + // the masks, so text never rests on its landing frame. + if place_masks { + self.paint.scale_frame = Some(AnotherFrame); + } + let direct = self.text.emit() == crate::text::outline::Emit::Outline; + let ins = n.inset.map(|v| v * zk * s); + // Text lays out from its box's place moved by how far its exact resting box sits from its + // snapped one (inside its paint containment), as Blink paints a text fragment from its + // exact place: its glyphs then round as Skia rounds them (the baseline half up, pens to + // a quarter pixel) where Chromium has them, rather than from a box already snapped. A + // gliding box carries its rest's offset, so the frame a glide ends or + // a flight lands places glyphs exactly as the resting frame after it. A field keeps its + // snapped box, which its caret and selection share. + let zr = if scale_motion == ScaleMotion::Still && (sc - 1.0).abs() < 1e-5 && n.input.is_none() { + let by = exact_off; + [zr[0] + by[0], zr[1] + by[1], zr[2] + by[0], zr[3] + by[1]] + } else { + zr + }; + let (x0, x1) = (zr[0] + ins[0], zr[2] - ins[2]); + let mut origin = [text_x(spec, x0, x1, text_width(flow.full_width() * tk), flow.flow()), zr[1] + ins[1]]; + // A gliding box's glyphs and decorations lay out from its nearest whole pixel (plus its rest's + // fraction, above) and move the rest. Within a 64th of a pixel they don't move, but still lay + // out from that pixel, as at rest. + let (glide, off) = if gliding && cover.is_none() && scale_motion == ScaleMotion::Still { + ([pixel_snap::text_glide(r[0]), pixel_snap::text_glide(r[1])], [r[0] - r[0].round(), r[1] - r[1].round()]) + } else { + ([0.0; 2], [0.0; 2]) + }; + let mut clip = clip; + if let Some(inp) = n.input.as_ref().filter(|i| i.single_line) && let Some(layout) = laid.single() { + let scroll = single_line_scroll(&mut self.edit.input_scroll, &n.path, inp, &spec.content, layout, s, (x1 - x0) / tk.max(1e-4)) * tk; + origin[0] -= scroll; + if layout.full_width() * tk > x1 - x0 { + clip = [clip[0].max(x0), clip[1], clip[2].min(x1), clip[3]]; + } + } + let rest_origin = [origin[0] - off[0], origin[1] - off[1]]; + // Paragraph block backgrounds, quote bars and list markers. + if spec.cold.blocks.iter().any(|&b| b != crate::edit::Block::Paragraph) { + emit_block_decorations( + &mut self.instances, + &mut self.text, + &mut self.images, + &mut self.paint.glyph_scratch, + spec, + flow, + rest_origin, + (x0 - glide[0], x1 - glide[0]), + s, + tk, + raster, + scale_motion, + glide, + color, + o, + srgb, + clip, + fade, + ); + } + // Text fields: selection under the text, placeholder, caret over it. + let mut caret = None; + // The selected display bytes and the ink their `El::selection_style` gives them. + let mut selected_ink: Option<(usize, usize, [f32; 4])> = None; + if let Some(inp) = &n.input { + let e = &inp.edit; + // The bytes of the paragraphs the clip shows, which a long draft's selection and + // spelling marks are drawn in; the newline after the last one included. + let (top, bottom) = if tk > 1e-4 { ((shown[0] - origin[1]) / tk, (shown[1] - origin[1]) / tk) } else { (f32::NEG_INFINITY, f32::INFINITY) }; + let (shown_a, shown_b) = flow.pieces_in(top, bottom).fold((usize::MAX, 0), |(lo, hi), p| (lo.min(p.start), hi.max(p.end.saturating_add(1)))); + let departing = self.motion.flights().iter().any(|f| f.departs(&n.path, n.key.as_deref()) + && f.alphas(f.destination, now, self.reduced_motion).0 > 0.0); + if e.text.is_empty() && e.preedit().is_none() && !inp.placeholder.is_empty() && !departing { + let pl_indent = spec.cold.blocks.first().map_or(0.0, |b| (b.indent_pt(spec.style.size) * s).round() * tk); + // A one-line field's placeholder stays on its line, cut by the field's clip, as its + // text does; a multi-line field's wraps at its width. + let wrap = (!inp.single_line).then(|| (x1 - x0 - pl_indent).max(1.0) / tk.max(1e-4)); + // A by-paragraph field's placeholder is a `dir="auto"` text of its own, as + // Desktop's composer draws it: in its own direction, its field's padding with it. + let own = spec.by_paragraph(true); + let options = crate::text::RichLayoutOptions::new().flow(match spec.dir { + crate::el::TextDir::Fixed(f) if !own => Some(f), + _ => None, + }); + let pl = self.text.layout_rich_with(&inp.placeholder, &[], inp.placeholder_style.unwrap_or(spec.style), s, wrap, options); + let pl_flow = crate::el::Flow::of_layout(&pl); + let start = if own && pl_flow != n.flow { rest_origin[0] + ins[2] - ins[0] } else { rest_origin[0] }; + // Right to left it ends at the field's start edge, its right. + let pl_x = match (pl_flow, wrap) { + (crate::el::Flow::Ltr, _) => start + pl_indent, + (crate::el::Flow::Rtl, Some(_)) => start, + (crate::el::Flow::Rtl, None) => start - pl_indent - text_width(pl.full_width() * tk), + }; + let pl_origin = [pl_x, rest_origin[1]]; + let pl_r_origin = if scale_motion == ScaleMotion::Still { pl_origin } else { [0.0, 0.0] }; + self.paint.glyph_scratch.clear(); + self.text.set_glyph_inks(inp.placeholder_color, &[]); + self.text.set_glide(glide); + self.text.glyphs_for_layout_scaled(&pl, pl_r_origin, raster, false, &mut self.paint.glyph_scratch); + self.text.set_glide([0.0; 2]); + let pc = premul(inp.placeholder_color, o, srgb); + for q in &self.paint.glyph_scratch { + self.instances.extend(glyph_or_image(q, &self.text, &mut self.images, pc, clip, fade) + .map(|g| zoom_glyph(g, pl_origin, pl_r_origin, tk / raster))); + } + } + if e.focused && !departing { + let (a, b) = e.range(); + if a != b && e.preedit().is_none() { + let (da, db) = e.display_selection_range(a, b); + // An inactive window paints a field's selection in its inactive pair, as a browser does. + let (highlight, ink) = inp.selection_style.map_or((inp.selection, None), |st| st.pick(self.host.window_focused != Some(false))); + selectable::push_field_selection(&mut self.instances, flow, da.max(shown_a), db.min(shown_b), + origin, tk, premul(highlight, o, srgb), s, clip, fade); + selected_ink = ink.map(|c| (da, db, premul(c, o, srgb))); + } + // A range selection hides the caret, as a browser's field and a native one do. + if a == b || e.is_composing() { + caret = input_caret; + } + // The composition's underline: thin under what's composed, thick under the + // clause being converted, each clause a point short at both ends so clauses + // read apart, as Chromium draws them (`CompositionMarkerPainter`). + if e.preedit().is_some() { + let pa = e.range().0; + for clause in e.preedit_clauses() { + let (a, b, thick) = (pa + clause.range().start, pa + clause.range().end, if clause.is_target() { 2.0 } else { 1.0 }); + for (bb, _) in flow.range_boxes(a, b, false) { + let (x0, x1) = (origin[0] + bb.x0 as f32 * tk, origin[0] + bb.x1 as f32 * tk); + let inset = if x1 - x0 > 4.0 * s { s } else { 0.0 }; + let h = thick * s; + self.instances.push(rect_inst( + [x0 + inset, origin[1] + bb.y1 as f32 * tk - h, x1 - x0 - 2.0 * inset, h], + premul(color, o, srgb), + 0.0, + clip, + fade, + )); + } + } + } + } + // Misspelled words (`El::spellcheck`), but the one the caret is typing. + if inp.spellcheck && !e.is_secure() && e.preedit().is_none() && !departing { + // Windows and the web check word by word, so the paragraphs shown are checked + // alone: a 20,000-line draft hashes and walks only what's on screen. macOS + // finds each text's language from the whole of it. + let (from, to) = (shown_a.min(e.text.len()), shown_b.min(e.text.len())); + let found = if cfg!(any(target_os = "windows", target_arch = "wasm32")) && (from > 0 || to < e.text.len()) && e.text.is_char_boundary(from) && e.text.is_char_boundary(to) { + std::rc::Rc::new(crate::spell::misspelled(&e.text[from..to], Some(self.frame.live.waker())).iter().map(|&(a, b)| (a + from, b + from)).collect::<Vec<_>>()) + } else { + crate::spell::misspelled(&e.text, Some(self.frame.live.waker())) + }; + // The word typing left the caret in waits unmarked until the pause ends (`spell::pause`). + // Typing shows in the paragraphs shown, the caret's among them. + let watched = if e.text.is_char_boundary(from) && e.text.is_char_boundary(to) { &e.text[from..to] } else { e.text.as_str() }; + let caret = if e.focused { crate::spell::pause::observe(&mut self.edit.spell_watch, &n.path, watched, e.range(), self.clock) } else { None }; + let color = premul(SPELLING, o, srgb); + for &(a, b) in found.iter().filter(|&&(a, b)| caret.is_none_or(|c| c < a || c > b)) { + let (da, db) = e.display_selection_range(a, b); + if db < shown_a || da > shown_b { continue; } + for (bb, baseline) in flow.range_boxes(da, db, false) { + // Its top a point under the baseline, as Chromium's. + let top = origin[1] + (baseline + s) * tk; + let (x0, x1) = (origin[0] + bb.x0 as f32 * tk, origin[0] + bb.x1 as f32 * tk); + push_spelling_marker(&mut self.instances, x0, x1, top, s * tk, color, clip, fade); + } + } + } + } + // Each paragraph a by-paragraph field or by-line block shows (or its one layout), in + // the rows the clip shows with two ems either side for ink past the line box. + let rows = crate::runtime::text_fill::visible_text_rows(spec, rest_origin[1], shown, tk, raster, s); + if let crate::text::TextLayout::Paragraphs(p) = laid && p.waiting() { + self.paint.text_rows.insert(n.id, (rows.start, rows.end)); + } + let (base_origin, base_rest) = (origin, rest_origin); + let base_d_origin = if scale_motion == ScaleMotion::Still && tk == 1.0 { base_rest } else { [0.0, 0.0] }; + let reveal = if spec.cold.advance_in.is_none() { self.motion.reveal_fade(n.id) } else { None }; + let drawn_len = n.elided.map_or(spec.content.len(), |e| e.drawn_len(spec.content.len())); + self.paint.deco_scratch.clear(); + let mut pill_icons = Vec::new(); + let mut bare_all = Vec::new(); + let pill_bg = spec.cold.pill_colors.map_or(spec.rich_style().link.alpha(0.2), |(bg, _)| bg); + for piece in flow.pieces_in(rows.start, rows.end) { + let layout = piece.layout; + let d_origin = [base_d_origin[0], base_d_origin[1] + piece.y]; + let (spans_here, pills) = (piece.spans(&spec.spans), piece.pills(&spec.cold.pills)); + let from = self.paint.deco_scratch.len(); + crate::text::pill_chips(layout, &pills, spec.style.size, s, d_origin, pill_bg, &mut self.paint.deco_scratch, &mut pill_icons); + // Elided text draws its decorations over the drawn string's offsets. + let drawn_spans = n.elided.map(|e| e.spans(&spans_here)); + let spans = drawn_spans.as_deref().unwrap_or(&spans_here); + let drawn_rings = n.elided.map(|e| e.rings(&spec.cold.rings)); + self.text.decorations_with_rings(layout, spans, drawn_rings.as_deref().unwrap_or(&spec.cold.rings), spec.cold.span_radius, s, d_origin, &mut self.paint.deco_scratch); + if !piece.is_whole() { + for d in &mut self.paint.deco_scratch[from..] { d.byte = piece.content(d.byte as usize) as u32; } + } + if !pills.is_empty() { + let mut bare = Vec::new(); + crate::text::bare_icons(layout, &pills, s, d_origin, &mut bare); + bare_all.extend(bare.into_iter().map(|(k, at, px)| (pills[k].clone(), at, px))); + } + } + if !spec.cold.highlights.is_empty() { + let drawn = n.elided.map(|e| e.highlights(&spec.cold.highlights)); + let marks = drawn.as_deref().unwrap_or(&spec.cold.highlights); + self.text.highlight_decorations_flow(flow, marks, drawn_len, s, base_d_origin, rows.clone(), &mut self.paint.deco_scratch); + } + for piece in flow.pieces_in(rows.start, rows.end) { + let d_origin = [base_d_origin[0], base_d_origin[1] + piece.y]; + let strikes = piece.strikes(&spec.cold.strikes); + let from = self.paint.deco_scratch.len(); + if !strikes.is_empty() { + let spans_here = piece.spans(&spec.spans); + let drawn_spans = n.elided.map(|e| e.spans(&spans_here)); + let spans = drawn_spans.as_deref().unwrap_or(&spans_here); + let drawn = n.elided.map(|e| e.strikes(&strikes)); + self.text.strike_decorations(piece.layout, spans, drawn.as_deref().unwrap_or(&strikes), color, s, d_origin, &mut self.paint.deco_scratch); + } + link_fx.decos_piece(&piece, drawn_len, s, d_origin, &mut self.paint.deco_scratch); + if !piece.is_whole() { + for d in &mut self.paint.deco_scratch[from..] { d.byte = piece.content(d.byte as usize) as u32; } + } + } + if !spec.cold.rings.is_empty() || spec.cold.highlights.iter().any(|h| h.ring.is_some()) { + // Adjacent backgrounds overlap by bg_pad. Paint ringed chips after + // plain fills so a neighboring fill cannot erase an inset edge; + // keep underlines above both. No sorting on the ringless path. + self.paint.deco_scratch.sort_by_key(|d| if d.radius == 0.0 { 2 } else { u8::from(d.ring.is_some()) }); + } + if base_d_origin != base_rest || tk != 1.0 { + for d in &mut self.paint.deco_scratch { + d.rect = scale_about(d.rect, base_rest, base_d_origin, tk); + d.radius *= tk; + if let Some((_, rw)) = &mut d.ring { *rw *= tk; } + } + } + if glide != [0.0; 2] { + for d in &mut self.paint.deco_scratch { d.rect[0] += glide[0]; d.rect[1] += glide[1]; } + } + for d in &self.paint.deco_scratch { + let alpha = if d.ring.is_some() { + reveal.map_or(1.0, |fade| fade.alpha(d.byte, self.scene.store().node_time(n.id))) + } else { 1.0 }; + let c = premul(d.color, o * alpha, srgb); + let mut inst = rect_inst(d.rect, c, d.radius, clip, fade); + if let Some((rc, rw)) = d.ring { + inst.border = premul(rc, o * alpha, srgb); + inst.params[0] = rw; + // The opacity the colours carry, so the ring hides the chip's fill by its own alpha. + inst.params[3] = o * alpha; + } + self.instances.push(inst); + } + let pill_fg = spec.cold.pill_colors.and_then(|(_, fg)| fg).unwrap_or(color); + for (icon, px, at, fg) in pill_icons { + let pill_fg = fg.unwrap_or(pill_fg); + let at = [ + base_rest[0] + (at[0] - base_d_origin[0]) * tk + glide[0], + base_rest[1] + (at[1] - base_d_origin[1]) * tk + glide[1], + ]; + let drawn = px as f32 * tk; + let px_r = (px as f32 * raster).round().max(1.0) as u32; + paint_inline_icon( + &mut self.text, + &mut self.paint, + &mut self.instances, + self.reduced_motion, + self.frame.live.visible(), + self.t, + self.time_scale, + n.id, + icon, + px_r, + drawn, + at, + pill_fg, + o, + srgb, + clip, + fade, + ); + } + for (pill, at, px) in bare_all { + let Some(b) = pill.bare.as_deref() else { continue }; + let mut at = [ + base_rest[0] + (at[0] - base_d_origin[0]) * tk + glide[0], + base_rest[1] + (at[1] - base_d_origin[1]) * tk + glide[1], + ]; + let mut drawn = [px[0] * tk, px[1] * tk]; + // A replacing image's clear margins draw past its box. + if let Some(bleed) = b.replace.map(|r| r.bleed * s * tk).filter(|&v| v > 0.0) { + at = [at[0] - bleed, at[1] - bleed]; + drawn = [drawn[0] + 2.0 * bleed, drawn[1] + 2.0 * bleed]; + } + // An image fits its box, keeping its shape; a glyph takes the text's colour. + if let Some(pixels) = &b.image + && let (w, h) = pixels.size() + && w > 0 + && h > 0 + { + let (w, h) = (w as f32, h as f32); + let k = (drawn[0] / w).min(drawn[1] / h); + let rect = [at[0] + (drawn[0] - w * k) * 0.5, at[1] + (drawn[1] - h * k) * 0.5, w * k, h * k]; + if let Some(image) = self.images.place(pixels, [rect[2], rect[3]]) { + self.instances.push(Instance { + rect, + radii: [(b.radius * s * tk).min(rect[2].min(rect[3]) * 0.5); 4], + fill: [0.0, 0.0, 0.0, o], + border: [0.0; 4], + params: [image.page as f32, KIND_IMAGE, image.premultiplied as u8 as f32, 1.0], + uv: image.rect.map(|v| v as f32), + clip, + fade: crate::render::pack_fade(fade, clip, clip), + }); + } + continue; + } + let Some(icon) = pill.icon else { continue }; + let px_r = (px[0] * raster).round().max(1.0) as u32; + paint_inline_icon( + &mut self.text, + &mut self.paint, + &mut self.instances, + self.reduced_motion, + self.frame.live.visible(), + self.t, + self.time_scale, + n.id, + icon, + px_r, + drawn[0], + at, + pill.fg.unwrap_or(color), + o, + srgb, + clip, + fade, + ); + } + if spec.selectable && n.input.is_none() { + // A mark keeps the active selection's highlight, whatever the window's focus, and + // the glyphs their own ink, as a custom highlight's background does. + let highlight = spec.cold.selection_style.map_or(spec.cold.selection, |st| st.pick(true).0); + let fill = premul(highlight, o, srgb); + for &(_, a, b) in mark_ranges.iter().filter(|m| m.0 == i) { + let map = |a, b| n.elided.map_or((a, b), |e| e.range(a, b)); + text_marks::push_mark(&mut self.instances, flow, &spec.content, (a, b), map, base_origin, tk, fill, clip, fade); + } + if let Some((a, b)) = selectable::range_in(sel_ranges, i) { + let (a, b) = n.elided.map_or((a, b), |e| e.range(a, b)); + // `::selection` with a colour recolours the selected glyphs, as a field's does. + let (highlight, ink) = spec.cold.selection_style.map_or((spec.cold.selection, None), |st| st.pick(self.host.window_focused != Some(false))); + selectable::push_selection(&mut self.instances, flow, a, b, base_origin, tk, premul(highlight, o, srgb), s, clip, fade); + if let Some(c) = ink { + selected_ink = Some((a, b, premul(c, o, srgb))); + } + } + } + for piece in flow.pieces_in(rows.start, rows.end) { + let layout = piece.layout; + let spans_here = piece.spans(&spec.spans); + let drawn_spans = n.elided.map(|e| e.spans(&spans_here)); + let spans = drawn_spans.as_deref().unwrap_or(&spans_here); + self.paint.glyph_scratch.clear(); + self.text.set_glyph_inks(color, spans); + let origin = [base_rest[0], base_rest[1] + piece.y * tk]; + self.text.set_glide(glide); + let r_origin = if scale_motion == ScaleMotion::Still { origin } else { [0.0, 0.0] }; + let has_hl_fg = spec.cold.highlights.iter().any(|h| h.fg.is_some()); + // A cell of a longer run draws its slice of the run's glyphs, shaped in context, at the + // same raster factor as a paragraph: under a zoom its masks are made at the zoomed size + // rather than magnified, and the frame it comes to rest places them. + // A still text whose quads this frame would draw as the last one did copies them, + // as `El::grid` rows do: `quads` is the entry to record them under otherwise. + let mut copied = false; + let mut quads: Option<((NodeId, crate::text::LayoutId), u64, usize, usize)> = None; + let mut pages: Option<Vec<(u16, u32)>> = None; + let zoom = if let (Some(r), Some((_, at))) = (&n.run_layout, &spec.cold.advance_in) + && let Some(x) = r.x(*at) + { + let cell = [r_origin[0] - x * raster, r_origin[1]]; + self.text.glyphs_in_scaled(r, *at, cell, raster, &mut self.paint.glyph_scratch); + if place_masks { + let mut masks = Vec::new(); + self.text.set_emit(crate::text::outline::Emit::Atlas); + self.text.glyphs_in_scaled(r, *at, cell, raster, &mut masks); + self.text.set_emit(crate::text::outline::Emit::Outline); + } + tk / raster + } else { + // Only the lines the clip shows, with two ems either side for ink past + // the line box; the per-glyph test below still decides what draws. + let band = if tk > 1e-4 { + let em = spec.spans.iter().filter_map(|sp| sp.size).fold(spec.style.size.max(spec.style.line_px()), f32::max); + let pad = 2.0 * em * s + 2.0 / raster.max(1e-4); + (shown[0] - origin[1]) / tk - pad..(shown[1] - origin[1]) / tk + pad + } else { + f32::NEG_INFINITY..f32::INFINITY + }; + let bytes = reveal.is_some() || !link_fx.is_empty() || has_hl_fg || selected_ink.is_some(); + // A secret's glyphs aren't kept past the frame that draws them. + let secret = spec.redacted || n.input.as_ref().is_some_and(|i| i.edit.is_secure()); + let shared = piece.shared.or(laid.single()); + let still = scale_motion == ScaleMotion::Still && glide == [0.0; 2] && !bytes && !place_masks + && !self.motion.flights().iter().any(|f| f.lands(&n.path, n.key.as_deref())); + // A layout whose stamp the id table dropped draws from its glyphs, uncopied. + if let Some(l) = shared.filter(|_| still && !direct && !secret) + && let Some(layout_id) = self.text.layout_id(l) + { + use std::hash::{Hash, Hasher}; + let mut h = rune_motion::Fx::default(); + (origin.map(f32::to_bits), clip.map(f32::to_bits), fade.map(f32::to_bits), shown.map(f32::to_bits), [tk, raster, s].map(f32::to_bits)).hash(&mut h); + (premul(color, o, srgb).map(f32::to_bits), srgb, self.text.emit_key()).hash(&mut h); + spans.len().hash(&mut h); + for sp in spans.iter() { + (sp.start, sp.end, sp.color.map(|c| premul(c, o, srgb).map(f32::to_bits))).hash(&mut h); + } + let (id, key) = ((n.id, layout_id), h.finish()); + match self.paint.text_quads.get_mut(&id).filter(|(d, _)| d.key == key) { + Some((d, used)) => { + *used = self.paint.quads_frame; + self.instances.extend_from_slice(&d.instances); + d.pages.iter().for_each(|&(page, texels)| self.text.touch_quad(page, texels)); + *glyph_count += d.glyphs; + copied = true; + #[cfg(test)] + { + self.paint.quads_copied += 1; + } + } + None => { + quads = Some((id, key, self.instances.len(), *glyph_count)); + pages = Some(Vec::new()); + } + } + } + match shared.filter(|_| !direct && !secret) { + _ if copied => {} + Some(l) => self.text.glyphs_in_band_cached(l, r_origin, raster, bytes, band.clone(), &mut self.paint.glyph_scratch), + None => self.text.glyphs_in_band(layout, r_origin, raster, bytes, band.clone(), &mut self.paint.glyph_scratch), + } + if place_masks && !secret && let Some(layout) = shared { + // Landing: the masks the next frame draws, placed now and not drawn. + let mut masks = Vec::new(); + self.text.set_emit(crate::text::outline::Emit::Atlas); + self.text.glyphs_in_band_cached(layout, r_origin, raster, bytes, band, &mut masks); + self.text.set_emit(crate::text::outline::Emit::Outline); + } + tk / raster + }; + self.text.set_glide([0.0; 2]); + let base = premul(color, o, srgb); + let lands = self.motion.flights().iter().any(|f| f.lands(&n.path, n.key.as_deref())); + for q in if lands { &[][..] } else { &self.paint.glyph_scratch[..] } { + let [x0, y0] = if zoom == 1.0 && origin == r_origin { [q.rect[0], q.rect[1]] } else { + std::array::from_fn(|k| origin[k] + (q.rect[k] - r_origin[k]) * zoom) + }; + let (x1, y1) = (x0 + q.rect[2] * zoom, y0 + q.rect[3] * zoom); + // Wholly outside the clip, a glyph draws nothing: a long line in an + // `El::scroll_x` skips the glyphs scrolled out of sight. + let out = y0 > clip[3] || y1 < clip[1] || x0 > clip[2] || x1 < clip[0]; + self.paint.keep.cycles.glyph([x0, y0, x1, y1], !out); + if out { continue; } + let mut f = base; + if q.ink > 0 + && let Some(c) = spans.get(q.ink as usize - 1).and_then(|sp| sp.color) + { + f = premul(c, o, srgb); + } + let cbyte = piece.content(q.byte as usize); + if let Some((a, b, c)) = selected_ink + && (a..b).contains(&cbyte) + { + f = c; + } + if has_hl_fg + && let Some(c) = spec.cold.highlights.iter().rev().find_map(|h| { + let (a, b) = n.elided.map_or((h.start as usize, h.end as usize), |e| e.mark(h.start as usize, h.end as usize, false)); + (a..b).contains(&cbyte).then_some(h.fg).flatten() + }) + { + f = premul(c, o, srgb); + } + if !link_fx.is_empty() && let Some(c) = link_fx.glyph_color(cbyte as u32) { + f = premul(c, o, srgb); + } + if let Some(fade) = reveal { + let a = fade.alpha(cbyte as u32, self.scene.store().node_time(n.id)); + if a <= 0.0 { + continue; + } + f = f.map(|v| v * a); + } + self.instances.extend(glyph_or_image(q, &self.text, &mut self.images, f, clip, fade) + .map(|g| zoom_glyph(g, origin, r_origin, zoom))); + *glyph_count += 1; + // A colour or outline glyph draws per frame, from another atlas or a record. + if q.color != 0 || q.outline.is_some() { + pages = None; + } else if let Some(pages) = pages.as_mut() { + let (page, texels) = (q.atlas_page() as u16, (q.rect[2] * if q.lcd { 3.0 } else { 1.0 } * q.rect[3]) as u32); + match pages.iter_mut().find(|p| p.0 == page) { + Some(p) => p.1 += texels, + None => pages.push((page, texels)), + } + } + } + if let (Some((id, key, start, glyphs)), Some(pages)) = (quads, pages) { + let d = crate::el::grid::DrawnRow { key, instances: self.instances[start..].to_vec(), pages, glyphs: *glyph_count - glyphs }; + self.paint.text_quads.insert(id, (d, self.paint.quads_frame)); + } + } + if let (Some(c), Some(inp)) = (caret, &n.input) { + self.instances.push(rect_inst(c, premul(inp.caret, o, srgb), 0.0, clip, fade)); + } + self.text.set_emit(crate::text::outline::Emit::Atlas); + } + } + + fn push_icon(&mut self, inst: Instance) { + if self.paint.paint_rank.is_some() && inst.uv[2] > 0.0 { self.paint.icon_aprons.push(apron_key(&inst)); } + self.instances.push(inst); + } + + /// The rectangle a live or truncated text clips its glyphs to (edges, device pixels), its + /// box, and whether it runs past that box; `None` for other text. + pub(in crate::runtime) fn text_clip(&self, i: usize, (r, r_exact): ([f32; 4], [f32; 4]), sc: f32, clip: [f32; 4]) -> Option<([f32; 4], [f32; 4], bool)> { + let s = self.env.scale; + let n = &self.tree.nodes[i]; + let (Some(spec), Some(layout)) = (&n.text, n.text_layout.as_ref().and_then(TextLayout::single)) else { return None }; + if !(spec.truncate_fade || spec.cold.live.is_some()) { return None; } + let ins = n.inset.map(|v| v * sc * s); + let mut bounds = [r[0] + ins[0], r[1] + ins[1], r[2] - ins[2], r[3] - ins[3]]; + // Layout width already includes display scale `s`; bounds also include the + // element/ancestor transform `sc`. Compare both after that transform. A text fades + // only when it runs past its laid-out box and the box drawn now: snapping each edge + // to a whole pixel can leave the drawn box a sliver short, and a box springing to a + // new layout (`animate_layout`, a flight) is short until it lands. A text that fits + // isn't clipped by either. + let exact = r_exact[2] - r_exact[0] - ins[0] - ins[2]; + let laid_out = (n.local.w - n.inset[0] - n.inset[2]).max(0.0) * s; + let overflows = layout.full_width() > laid_out + 0.5 + && layout.full_width() * sc > (bounds[2] - bounds[0]).max(exact) + 0.5 * sc; + // A right-to-left paragraph runs out past its left edge. + match (overflows, crate::el::Flow::of_layout(layout)) { + (true, _) => {} + (false, crate::el::Flow::Ltr) => bounds[2] = bounds[2].max(bounds[0] + exact.max(layout.full_width() * sc)), + (false, crate::el::Flow::Rtl) => bounds[0] = bounds[0].min(bounds[2] - exact.max(layout.full_width() * sc)), + } + Some((intersect(clip, bounds), bounds, overflows)) + } + + /// Text-only clipping leaves the box's fill/border and descendants untouched. + pub(in crate::runtime) fn clip_text_instances( + &mut self, + i: usize, + first_instance: usize, + (r, r_exact): ([f32; 4], [f32; 4]), + sc: f32, + clip: [f32; 4], + fade: [f32; 4], + fade_origin: [f32; 4], + ) { + let s = self.env.scale; + if let Some((text_clip, bounds, overflows)) = self.text_clip(i, (r, r_exact), sc, clip) + && let Some(spec) = &self.tree.nodes[i].text + { + let mut widths = fade; + let mut origins = fade_origin; + if spec.truncate_fade && overflows { + let width = (spec.style.size * spec.fade_em * sc * s).min((bounds[2] - bounds[0]).max(0.0)).clamp(0.0, 65504.0); + // The fade is where the text is cut: the end of its own paragraph, which runs out + // past the box on that side. An Arabic title in a left-to-right row fades on the + // left and keeps its first words whole; a Latin one in a right-to-left row on the + // right. + let line = self.tree.nodes[i].text_layout.as_ref().and_then(TextLayout::single).map_or(crate::el::Flow::Ltr, |l| crate::el::Flow::of_layout(l)); + let own = if (spec.align == Align::End) != (line == crate::el::Flow::Rtl) { [width, 0.0, 0.0, 0.0] } + else { [0.0, 0.0, width, 0.0] }; + inherit_fade(&mut widths, &mut origins, bounds, own); + } + for instance in &mut self.instances[first_instance..] { + if instance.params[1] == KIND_GLYPH { + instance.clip = text_clip; + instance.fade = crate::render::pack_fade(widths, origins, text_clip); + } + } + } + } +} + +#[allow(clippy::too_many_arguments)] +fn paint_inline_icon( + text: &mut TextSystem, + paint: &mut state::PaintState, + instances: &mut Vec<Instance>, + reduced_motion: bool, + live_visible: bool, + t: f64, + time_scale: f32, + node_id: NodeId, + icon: &'static crate::text::Icon, + px: u32, + drawn: f32, + at: [f32; 2], + fg: Color, + o: f32, + srgb: bool, + clip: [f32; 4], + fade: [f32; 4], +) { + if !reduced_motion + && text.icon_kind(icon) == crate::text::IconKind::AnimatedMono + && paint_animated_icon(text, paint, instances, live_visible, t, time_scale, node_id, icon, (px, px as f32), at, drawn, 0.0, crate::text::Facing::Upright, fg, o, srgb, clip, fade) + { + return; + } + if let Some(q) = text.icon_quad(icon, px, at) { + let inst = icon_inst(&q, at, drawn, 0.0, premul(fg, o, srgb), clip, fade); + if paint.paint_rank.is_some() && inst.uv[2] > 0.0 { paint.icon_aprons.push(apron_key(&inst)); } + instances.push(inst); + } +} + +/// Paints a monochrome animated icon via its double-buffered glyph-atlas tile pair, gating wakes +/// on visibility (`live_visible`), non-zero alpha (`> 1/255`), and active state. Returns `false` +/// when the caller should fall back to the static `t = 0` quad. +#[allow(clippy::too_many_arguments)] +fn paint_animated_icon( + text: &mut TextSystem, + paint: &mut state::PaintState, + instances: &mut Vec<Instance>, + live_visible: bool, + t: f64, + time_scale: f32, + node_id: NodeId, + ic: &'static crate::text::Icon, + sized: (u32, f32), + at: [f32; 2], + draw_side: f32, + turn: f32, + facing: crate::text::Facing, + color: Color, + o: f32, + srgb: bool, + clip: [f32; 4], + fade: [f32; 4], +) -> bool { + const ALPHA_MIN: f32 = 1.0 / 255.0; + if o <= ALPHA_MIN || color.a <= ALPHA_MIN { + return false; + } + let mount_t = if text.icon_anim_is_finite(ic) { + paint.get_or_insert_icon_mount(node_id, ic as *const crate::text::Icon as usize, t) + } else { + 0.0 + }; + // Occluded, minimised, or hidden windows must not rasterize or keep the frame loop awake + // (`loop_sleep.rs:153`), but still report `animated_icons_shown` so Windows occlusion polling + // (`look.rs:88`) wakes when uncovered. + if !live_visible { + if text.icon_anim_live(ic, t, mount_t) { + paint.animated_icons_shown = true; + paint.node_animated_icon = true; + } + return false; + } + let Some(anim) = text.animated_icon_quad(ic, sized, at, facing, t, mount_t, node_id.0) else { + return false; + }; + match anim.state { + crate::text::AnimState::Moving => { + paint.animated_icons_shown = true; + paint.node_animated_icon = true; + if time_scale > 0.0 { + paint.animated_icons = true; + } + } + crate::text::AnimState::WaitingUntil(wake_at) => { + paint.animated_icons_shown = true; + paint.node_animated_icon = true; + if time_scale > 0.0 { + paint.note_icon_anim_wake(wake_at); + } + } + crate::text::AnimState::Finished => {} + } + let inst = icon_inst(&anim.quad, at, draw_side, turn, premul(color, o, srgb), clip, fade); + let slot_index = instances.len(); + if paint.paint_rank.is_some() && inst.uv[2] > 0.0 { paint.icon_aprons.push(apron_key(&inst)); } + if !matches!(anim.state, crate::text::AnimState::Finished) { + paint.keep.cycles.record_icon(super::keep::cycle::IconSlot { + at: slot_index, + node_id, + ic, + sized, + origin: at, + draw_side, + turn, + facing, + rect: inst.rect, + }); + } + instances.push(inst); + true +} diff --git a/app/vendor/rune/crates/rune/src/runtime/paint/cycle.rs b/app/vendor/rune/crates/rune/src/runtime/paint/cycle.rs new file mode 100644 index 0000000..e318fed --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/paint/cycle.rs @@ -0,0 +1,349 @@ +//! A loop-only step: what a loop changes on screen, without the scene being built again. The +//! ordinary paint records the instances each eligible loop drew: a spinner's dot (a hidden, +//! decorative leaf with one plain fill and an opacity cycle, nothing else about it moving), and +//! a shimmer's sliding window (`slide.rs`). A step samples the loops into those instances, and +//! nothing else runs. Every paint starts the record again. The host draws only what changed +//! (`Renderer::arm_cycle` on the web, `Renderer::arm_loop` in a window). + +use super::*; + +#[derive(Default)] +pub(in crate::runtime) struct CyclePaint { + /// Counts paints: a renderer told the instances are the same paint's as last frame's knows + /// only the slots can differ. + paint: u64, + generation: u64, + slots: Vec<Slot>, + pub(super) slides: Vec<super::slide::Slide>, + pub(super) icons: Vec<IconSlot>, + mixed: bool, + /// The node paint last reached, and how many instances it had drawn by then. + pub(super) opened: (usize, usize), + /// The sliding window whose subtree paints now. + pub(super) open: Option<usize>, + /// Why this paint recorded no window for a sliding loop it drew, if it didn't. + pub(super) missed: Option<&'static str>, + /// What the last step would have drawn, while `RUNE_LOOP_CHECK=1` runs ordinary frames instead. + check: Option<Vec<Instance>>, + /// The clock the checked step sampled at: the ordinary frame that runs instead samples there + /// too (`Runtime::frame`), so the two compare one instant. + pub(in crate::runtime) check_clock: Option<f64>, + /// Sliding windows' anchors from the last paint, those this paint posed from, and the one it + /// posed last (`slide_anchor`). + pub(super) anchors: Vec<super::slide::Anchor>, + pub(super) next_anchors: Vec<super::slide::Anchor>, + pub(super) anchor: Option<(usize, super::slide::Anchor)>, +} + +struct Slot { + node: usize, + at: usize, + curve: crate::Cycle, + ink: [f32; 4], + /// What else fades it: its own and its ancestors' opacity besides the cycle. + scale: f32, + rect: [f32; 4], +} + +#[derive(Clone, Copy)] +pub(in crate::runtime) struct IconSlot { + pub(in crate::runtime) at: usize, + pub(in crate::runtime) node_id: NodeId, + pub(in crate::runtime) ic: &'static crate::text::Icon, + pub(in crate::runtime) sized: (u32, f32), + pub(in crate::runtime) origin: [f32; 2], + pub(in crate::runtime) draw_side: f32, + pub(in crate::runtime) turn: f32, + pub(in crate::runtime) facing: crate::text::Facing, + pub(in crate::runtime) rect: [f32; 4], +} + +impl CyclePaint { + pub(in crate::runtime) fn begin(&mut self, generation: u64) { + self.paint += 1; + self.generation = generation; + self.slots.clear(); + self.slides.clear(); + self.icons.clear(); + self.open = None; + self.missed = None; + self.opened = (usize::MAX, 0); + self.mixed = false; + self.anchors = std::mem::take(&mut self.next_anchors); + self.anchor = None; + } + + pub(in crate::runtime) fn other_deadline(&mut self) { self.mixed = true; } + + pub(in crate::runtime) fn record(&mut self, node: usize, at: usize, curve: crate::Cycle, (ink, scale): ([f32; 4], f32), rect: [f32; 4]) { + self.slots.push(Slot { node, at, curve, ink, scale, rect }); + } + + pub(in crate::runtime) fn record_icon(&mut self, slot: IconSlot) { + self.icons.push(slot); + } + + /// A glyph at `quad` (x0, y0, x1, y1), drawn or left out: a sliding window over it notes it. + pub(in crate::runtime) fn glyph(&mut self, quad: [f32; 4], drawn: bool) { + if let Some(k) = self.open { self.slides[k].glyphs.push((quad, drawn)); } + } +} + +/// `RUNE_LOOP_CHECK=1`: a frame a loop-only step could draw runs as an ordinary one, and the +/// two are compared (`loop_checked`). A headless run (`--frames`, on the virtual clock) asks +/// too, before every frame no script event reached (`tooling::headless`), on any platform. +/// `RUNE_LOOP_CHECK_DETAIL=1`: `loop_checked` prints each differing instance. +fn detail() -> bool { + static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("RUNE_LOOP_CHECK_DETAIL").is_some()) +} + +pub(crate) fn checking() -> bool { + static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("RUNE_LOOP_CHECK").is_some_and(|v| v == "1")) +} + +impl RuntimeCore { + /// The paint the instances come from, and the instances a loop-only step changes (ascending). + #[cfg_attr(not(target_arch = "wasm32"), allow(dead_code))] + pub(crate) fn cycle_paint(&self) -> (u64, Vec<u32>) { + let c = &self.paint.keep.cycles; + (c.paint, c.slots.iter().map(|s| s.at as u32).collect()) + } + + /// The paint the instances come from. + pub(crate) fn paint_count(&self) -> u64 { + self.paint.keep.cycles.paint + } + + /// A loop's wake on a window that otherwise rests: samples the cycles into their slots of + /// the last paint, and nothing else runs. False, for an ordinary frame, when anything else + /// is due: another deadline, the app's timer, input, a commit, a changed scene. + #[cfg_attr(not(target_arch = "wasm32"), allow(dead_code))] + pub(crate) fn paint_cycle_tick(&mut self) -> bool { + let Some((due, _)) = self.motion.loop_wake() else { return false }; + let wall = self.now_clock(); + let keep = &self.paint.keep.cycles; + if wall < due || keep.mixed || !keep.icons.is_empty() || keep.generation != self.commit.commits || keep.slots.is_empty() + || keep.slots.len() != self.motion.loops_len() || self.reduced_motion || self.time_scale <= 0.0 + || !self.live_visible() || !self.rests_except_loop() || self.tracing() + || self.poll_wake_deadline().is_some_and(|d| d <= wall) + { return false; } + if self.ambient.is_none() || !self.slots_hold() { return false; } + if self.commit.virtual_fill.resuming(wall) { return false; } + // No poll: as on a window resting without a loop, the app's poll runs when its timers, + // wakes or input ask, each of which takes an ordinary frame. + self.clock = wall; + let _ = self.text.mask_cache_frame(false); + self.sample_cycles(&mut Vec::new()); + true + } + + /// A frame that only a window's loops asked for, `dt` seconds after the last: samples every + /// loop into the instances it drew, and nothing else runs (no poll, view, layout or paint). + /// Returns the instances it wrote (ascending), or why it takes an ordinary frame: anything + /// else is due (input, a wake, a timer, a commit, other motion), a loop on screen is one a + /// step can't draw, or a step would show or hide anything. + pub(crate) fn loop_step(&mut self, dt: f64) -> Result<Vec<u32>, &'static str> { + // Checked on the virtual clock (headless), the step is due where the frame will be. + let virtual_check = checking() && self.wall_start.is_none(); + let wall = if virtual_check { self.clock + dt } else { self.now_clock() }; + let keep = &self.paint.keep.cycles; + let loops = keep.slots.len() + 2 * keep.slides.len(); + let has_icons = !keep.icons.is_empty(); + let why = if self.motion.loops_is_empty() && !has_icons { "no loop" } + else if has_icons && !self.motion.loops_is_empty() { "an animated icon beside a loop" } + else if loops != self.motion.loops_len() { self.loop_refusal() } + else if keep.mixed || keep.generation != self.commit.commits { "other motion or a commit" } + else if (self.wall_start.is_none() && !virtual_check) || self.reduced_motion || self.time_scale <= 0.0 || !self.live_visible() || self.tracing() { "not live" } + else if dt < 0.0 || (!has_icons && dt > 1.0 / 30.0) { "late" } + else if self.poll_wake_deadline().is_some_and(|d| d <= wall) { "timer due" } + else if self.commit.virtual_fill.resuming(wall) { "a list filling" } + else if let Some(work) = self.waiting_work() { work } + else { "" }; + if !why.is_empty() { return Err(why); } + // Running, only loops move; resting, a stepped cycle's or animated icon's wake is due. + let due = self.motion.loop_wake().is_some_and(|(due, _)| wall >= due); + if self.animating && self.motion.anim_sources != AnimSource::LOOP { + let other = [(AnimSource::TRACKS, "motion: a track"), (AnimSource::GROWTH, "motion: growth"), (AnimSource::SCROLL, "motion: a scroll"), + (AnimSource::REVEAL, "motion: a reveal"), (AnimSource::LIVE, "motion: a live value"), (AnimSource::TEXT_FILL, "motion: text filling"), + (AnimSource::VIRTUAL_FILL, "motion: a list filling"), (AnimSource::SCALE_SETTLE, "motion: a scale settling"), + (AnimSource::VIDEO, "motion: a video"), (AnimSource::TEXT_FLIGHT, "motion: a text flight"), + (AnimSource::ICON_ANIM, "motion: an animated icon")]; + return Err(other.iter().find(|(bit, _)| self.motion.anim_sources & bit != 0).map_or("motion: unknown", |o| o.1)); + } + if !self.animating && !due { return Err("no loop due"); } + if has_icons { + if self.animating || !self.slots_hold() { return Err("a slot moved"); } + if !self.icon_slots_ready() { return Err("an animated icon needs an atlas slot"); } + if checking() { return Err("checked against an ordinary frame"); } + let Some((deadline, phase)) = self.motion.loop_wake() else { return Err("no loop due"); }; + let t = (phase + (wall - deadline).max(0.0) * f64::from(self.time_scale)).max(self.t); + self.clock = wall; + self.t = t; + self.scene.set_time(t); + let _ = self.text.mask_cache_frame(false); + let mut patched = Vec::new(); + self.sample_icon_slots(&mut patched); + patched.sort_unstable(); + return Ok(patched); + } + if !self.slots_hold() || (due && self.ambient.is_none()) { return Err("a slot moved"); } + let t = self.t + dt * f64::from(self.time_scale); + let poses = self.paint.slide_poses(&self.tree.nodes, &self.motion, &self.scene, &self.instances, self.t, self.reduced_motion, t)?; + if checking() { + // What the step would draw, for the ordinary frame that runs instead (`loop_checked`). + let mut predicted = self.instances.clone(); + for s in &self.paint.keep.cycles.slots { + let a = s.curve.sample(wall) * s.scale; + predicted[s.at].fill = s.ink.map(|v| v * a); + predicted[s.at].params[3] = a; + } + for (sl, &(clip, fade)) in self.paint.keep.cycles.slides.iter().zip(&poses) { + for q in &mut predicted[sl.instances.clone()] { q.clip = clip; q.fade = fade; } + } + self.paint.keep.cycles.check = Some(predicted); + self.paint.keep.cycles.check_clock = Some(wall); + return Err("checked against an ordinary frame"); + } + self.clock = wall; + self.t = t; + self.scene.set_time(t); + let _ = self.text.mask_cache_frame(false); + let mut patched = Vec::new(); + self.sample_cycles(&mut patched); + self.paint.apply_slides(&poses, &mut self.instances, &mut patched); + patched.sort_unstable(); + Ok(patched) + } + + /// `RUNE_LOOP_CHECK=1` is set (`checking`). + pub(crate) fn loop_check_on(&self) -> bool { checking() } + + /// Why a loop on screen has no slot or window (`loop_step`'s answer): the first such loop's + /// reason, from what paint read. + fn loop_refusal(&self) -> &'static str { + let c = &self.paint.keep.cycles; + if let Some(why) = c.missed { return why; } + for id in self.motion.loop_ids() { + let Some(&i) = self.tree.node_index.get(&id) else { continue }; + if c.slots.iter().any(|s| s.node == i) || c.slides.iter().any(|s| s.window == i || s.counter == i) { continue; } + let n = &self.tree.nodes[i]; + let Some(rune_motion::LoopKind::OpacityCycle(_)) = n.looping.as_ref().map(|l| l.kind) else { return "a loop that isn't a cycle or a window" }; + let parent = n.parent.map_or_else(|| self.root_inh(), |p| self.paint.inh_scratch[p]); + return if !self.paint.seen.get(i).copied().unwrap_or(false) { "a cycle out of sight" } + else if !n.a11y.hidden { "a cycle screen readers see" } + else if self.tree.nodes.get(i + 1).is_some_and(|m| m.parent == Some(i)) { "a cycle with children" } + else if n.vis.layer_opacity != 1.0 || n.vis.paint_alpha != 1.0 { "a cycle that fades itself" } + else if parent.in_cache || parent.skip_paint || parent.turn != 0 { "a cycle in a layer" } + else if n.handlers.get().is_some() || n.focus.get().is_some() || n.vis_flags.hit() { "a cycle that takes input" } + else { "a cycle paint didn't record" }; + } + "a loop it can't draw" + } + + /// `RUNE_LOOP_CHECK=1`: what the last loop-only step would have drawn against what the + /// ordinary frame that ran instead drew. The instances that differ, and by how much at most + /// (the largest difference in any field, in pixels or colour; infinite when their number or + /// soft edges differ). None when no step was checked. + pub(crate) fn loop_checked(&mut self) -> Option<(usize, f32)> { + let predicted = self.paint.keep.cycles.check.take()?; + if predicted.len() != self.instances.len() { return Some((usize::MAX, f32::INFINITY)); } + let (mut differ, mut worst) = (0, 0.0f32); + for (i, (p, q)) in predicted.iter().zip(&self.instances).enumerate() { + if bytemuck::bytes_of(p) == bytemuck::bytes_of(q) { continue; } + let fields = |i: &Instance| [i.rect, i.radii, i.fill, i.border, i.params, i.uv, i.clip]; + let d = if p.fade != q.fade { f32::INFINITY } else { + fields(p).iter().flatten().zip(fields(q).iter().flatten()).map(|(a, b)| (a - b).abs()).fold(0.0, f32::max) + }; + if d > 1e-3 { + differ += 1; + // `RUNE_LOOP_CHECK_DETAIL=1`: which instance, and what the step and the frame had. + if detail() { + eprintln!("rune: loop check: instance {i} (kind {}) step {:?} frame {:?}", q.params[1], (p.rect, p.fill, p.params, p.clip, p.uv), (q.rect, q.fill, q.params, q.clip, q.uv)); + } + } + worst = worst.max(d); + } + Some((differ, worst)) + } + + /// A layer may have folded a primitive after its slot was observed. Never patch a different + /// instance, even if the instance count stayed the same. + fn slots_hold(&self) -> bool { + self.paint.keep.cycles.slots.iter().all(|s| self.instances.get(s.at).is_some_and(|q| q.rect == s.rect && q.params[1] == KIND_RECT)) + && self.paint.keep.cycles.icons.iter().all(|s| self.instances.get(s.at).is_some_and(|q| q.rect == s.rect && q.params[1] == KIND_GLYPH)) + } + + /// True when every recorded animated icon already has both double-buffered atlas slots on + /// live (non-evicted) pages so `loop_step` never allocates or evicts a glyph page. + fn icon_slots_ready(&self) -> bool { + self.paint.keep.cycles.icons.iter().all(|s| self.text.icon_anim_slots_ready(s.ic, s.sized, s.facing, s.node_id.0)) + } + + /// Evaluates animated SVG icon slots in place without rebuilding or walking the paint tree, + /// patching only the `uv` and atlas page of instances whose quantized pixels actually changed + /// and advancing the wake to the next quantized change timestamp. + fn sample_icon_slots(&mut self, patched: &mut Vec<u32>) { + if self.paint.keep.cycles.icons.is_empty() { + return; + } + let mut next_wake: Option<f64> = None; + let mut any_live = false; + let count = self.paint.keep.cycles.icons.len(); + for idx in 0..count { + let s = self.paint.keep.cycles.icons[idx]; + let mount_t = if self.text.icon_anim_is_finite(s.ic) { + self.paint.icon_mount_time(s.node_id, s.ic as *const crate::text::Icon as usize, self.t) + } else { + 0.0 + }; + let Some(anim) = self.text.animated_icon_quad_in_place(s.ic, s.sized, s.origin, s.facing, self.t, mount_t, s.node_id.0) else { + continue; + }; + match anim.state { + crate::text::AnimState::Moving => { + any_live = true; + next_wake = Some(match next_wake { Some(w) => w.min(self.t + 1.0 / 30.0), None => self.t + 1.0 / 30.0 }); + } + crate::text::AnimState::WaitingUntil(at) => { + any_live = true; + next_wake = Some(match next_wake { Some(w) => w.min(at), None => at }); + } + crate::text::AnimState::Finished => {} + } + let next = icon_inst(&anim.quad, s.origin, s.draw_side, s.turn, [0.0; 4], [0.0; 4], [0.0; 4]); + let q = &mut self.instances[s.at]; + if anim.changed || q.uv != next.uv || q.params[2] != next.params[2] { + q.uv = next.uv; + q.params[2] = next.params[2]; + patched.push(s.at as u32); + } + } + self.paint.animated_icons_shown = any_live; + self.motion.clear_loop_wake(); + if let Some(at) = next_wake && self.time_scale > 0.0 { + let wake = self.clock + (at - self.t).max(0.0) / f64::from(self.time_scale); + self.motion.arm_loop_wake(wake, at); + } + } + + /// Samples each cycle at the clock into its slot, and moves a stepped cycle's wake on. + fn sample_cycles(&mut self, patched: &mut Vec<u32>) { + for s in &self.paint.keep.cycles.slots { + let a = s.curve.sample(self.clock) * s.scale; + let q = &mut self.instances[s.at]; + q.fill = s.ink.map(|v| v * a); + q.params[3] = a; + let inh = &mut self.paint.inh_scratch[s.node]; + inh.opacity = a; inh.paint_opacity = a; inh.hit_opacity = a; + // Every dot, moved or not: what the screen shows is the renderer's to know (a frame + // that missed its drawable drew nothing), and `arm_loop` redraws only those that + // differ from what it holds. + patched.push(s.at as u32); + } + if let (Some((due, phase)), Some(dt)) = (self.motion.loop_wake(), self.ambient.map(f64::from)) && self.clock >= due { + self.motion.set_loop_wake((self.clock + dt, phase + (self.clock + dt - due) * f64::from(self.time_scale))); + } + } +} diff --git a/app/vendor/rune/crates/rune/src/runtime/paint/exit_mask.rs b/app/vendor/rune/crates/rune/src/runtime/paint/exit_mask.rs new file mode 100644 index 0000000..ab8f45e --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/paint/exit_mask.rs @@ -0,0 +1,68 @@ +//! Which nodes sit in an exiting subtree, found once a frame. Hit registration, reports and +//! sticky headers ask this of most nodes; without it each asks the scene for every ancestor. + +use super::*; + +/// One flag per node of the commit it was filled for: the node or an ancestor is exiting. +pub(in crate::runtime) enum Mask { + /// The last frame's flags, kept only for their buffer: they answer nothing. + Forgotten { exiting: Vec<bool> }, + /// The flags of commit `commit`, one per node: they answer only while that commit and the + /// node count hold. + Fresh { exiting: Vec<bool>, commit: u64 }, +} + +impl Default for Mask { + fn default() -> Self { Mask::Forgotten { exiting: Vec::new() } } +} + +impl Mask { + /// The flags, wherever they came from: the buffer a fill builds into. + fn into_flags(self) -> Vec<bool> { + match self { + Mask::Forgotten { exiting } | Mask::Fresh { exiting, .. } => exiting, + } + } + + pub(in crate::runtime) fn forget(&mut self) { + *self = Mask::Forgotten { exiting: std::mem::take(self).into_flags() }; + } + + fn get(&self, i: usize, len: usize, commit: u64) -> Option<bool> { + match self { + Mask::Fresh { exiting, commit: c } if *c == commit && exiting.len() == len => Some(exiting[i]), + Mask::Forgotten { .. } | Mask::Fresh { .. } => None, + } + } +} + +impl RuntimeCore { + /// Fills the mask for this frame's paint and reports. Call [`Self::end_exit_mask`] once + /// they're done, so nothing reads it after a phase changes. + pub(in crate::runtime) fn begin_exit_mask(&mut self) { + let mut exiting = std::mem::take(&mut self.tree.exit_mask).into_flags(); + exiting.clear(); + exiting.reserve(self.tree.nodes.len()); + for i in 0..self.tree.nodes.len() { + let n = &self.tree.nodes[i]; + let up = n.parent.is_some_and(|p| if p < i { exiting[p] } else { self.subtree_exiting(p) }); + exiting.push(up || self.is_exiting(n.id)); + } + self.tree.exit_mask = Mask::Fresh { exiting, commit: self.commit.commit_gen() }; + } + + pub(in crate::runtime) fn end_exit_mask(&mut self) { + self.tree.exit_mask.forget(); + } + + pub(crate) fn subtree_exiting(&self, mut i: usize) -> bool { + if let Some(exiting) = self.tree.exit_mask.get(i, self.tree.nodes.len(), self.commit.commit_gen()) { + return exiting; + } + loop { + if self.is_exiting(self.tree.nodes[i].id) { return true; } + let Some(parent) = self.tree.nodes[i].parent else { return false }; + i = parent; + } + } +} diff --git a/app/vendor/rune/crates/rune/src/runtime/paint/grid.rs b/app/vendor/rune/crates/rune/src/runtime/paint/grid.rs new file mode 100644 index 0000000..ba0f300 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/paint/grid.rs @@ -0,0 +1,224 @@ +//! Painting a terminal's cell grid (`El::grid`): each row as the elements it replaces drew it. +//! +//! A row was a box of the grid's width and one cell tall holding its background boxes, a +//! one-line `rich` text with a zero-width truncate fade, a `text` per pinned cell, and a +//! `canvas` over them, all at the row's top-left. Each part here is placed where layout and the +//! pixel snap put that element (edges rounded to the device grid from their 1/64 px exact +//! positions), and draws through the same calls: the fill's rect instance, the text's +//! decorations and glyph quads from the shared atlas, the shape's instances. So the pixels are +//! the same, from one node instead of a few per row. +//! +//! A row draws only when it changed: its instances are kept with a key of all they depend on +//! (where it sits, the clip, opacity, how glyphs rasterize and the atlas's clock), and a frame +//! where the key holds copies them, keeping the atlas pages they sample resident. A row with a +//! colour glyph or an outline glyph (another atlas, or a record drawn per frame) always draws. + +use std::rc::Rc; + +use super::*; +use crate::el::grid::{DrawnRow, Grid, GridRow, LaidRow}; + +impl state::PaintState { + /// Paints node `node`'s grid inside its snapped box `r` (exact `r_exact`, device px edges). + #[allow(clippy::too_many_arguments)] + pub(in crate::runtime) fn paint_grid( + &mut self, + node: NodeId, + flow: crate::el::Flow, + s: f32, + g: &Grid, + r: [f32; 4], + r_exact: [f32; 4], + clip: [f32; 4], + fade: [f32; 4], + o: f32, + glyph_count: &mut usize, + text: &mut TextSystem, + images: &mut crate::pixels::ImageAtlas, + instances: &mut Vec<Instance>, + ) { + let srgb = self.srgb_blend; + // The device grid an element's edges land on, and how far the box's own snap moved it + // past plain rounding (a translation that snaps as a whole). + let round = |v: f32| (v + 0.5).floor(); + let shift = [r[0] - round(r_exact[0]), r[1] - round(r_exact[1])]; + let origin_pt = [r_exact[0] / s, r_exact[1] / s]; + let px = |pt: f32| rune_motion::snap::grid(pt, s) * s; + let [cw, ch] = g.cell; + let _ = text.begin_text(node.0, false); + let cols = f32::from(g.cols); + for (k, row) in g.rows.iter().enumerate() { + let y0 = px(origin_pt[1] + k as f32 * ch); + let y1 = px(origin_pt[1] + (k + 1) as f32 * ch); + // Rows wholly outside the clip draw nothing. + if round(y0) + shift[1] > clip[3] || round(y1) + shift[1] < clip[1] { + continue; + } + let x0 = px(origin_pt[0]); + let x1 = px(origin_pt[0] + cols * cw); + let edge = |e: [f32; 4]| [round(e[0]) + shift[0], round(e[1]) + shift[1], round(e[2]).max(round(e[0]) + 1.0) + shift[0], round(e[3]).max(round(e[1]) + 1.0) + shift[1]]; + let row_r = edge([x0, y0, x1, y1]); + let key = |emit: u64| { + use std::hash::{Hash, Hasher}; + let mut h = rune_motion::Fx::default(); + (row_r.map(f32::to_bits), clip.map(f32::to_bits), fade.map(f32::to_bits), o.to_bits(), s.to_bits(), srgb, emit).hash(&mut h); + h.finish() + }; + if let Some(d) = row.drawn.borrow().as_ref().filter(|d| d.key == key(text.emit_key())) { + instances.extend_from_slice(&d.instances); + d.pages.iter().for_each(|&(page, texels)| text.touch_quad(page, texels)); + *glyph_count += d.glyphs; + continue; + } + let (start, glyphs) = (instances.len(), *glyph_count); + let mut pages = Some(Vec::new()); + let laid = Self::laid_row(text, s, row, cols * cw, flow); + + // Background and selection runs: a filled box each, under the text. + for f in &row.fills { + let fx0 = px(origin_pt[0] + f32::from(f.start) * cw); + let fx1 = px(origin_pt[0] + f32::from(f.end) * cw); + let b = edge([fx0, y0, fx1, y1]); + let fill = premul(f.color, o, srgb); + if fill[3] > 0.0005 { + instances.push(Instance { + rect: [b[0], b[1], b[2] - b[0], b[3] - b[1]], + radii: [0.0; 4], + fill, + border: [0.0; 4], + params: [0.0, KIND_RECT, 0.0, 1.0], + uv: [0.0; 4], + clip, + fade: crate::render::pack_fade(fade, clip, clip), + }); + } + } + + // The line: a `rich` text clipped to its row (its truncate fade). + let line = &laid.line; + let line_flow = crate::el::Flow::of_layout(line); + let origin = [text_x(&row.line, row_r[0], row_r[2], text_width(line.full_width()), line_flow), row_r[1]]; + let exact_w = x1 - x0; + let overflows = line.full_width() > cols * cw * s + 0.5 && line.full_width() > (row_r[2] - row_r[0]).max(exact_w) + 0.5; + let mut bounds = row_r; + if !overflows { + match line_flow { + crate::el::Flow::Ltr => bounds[2] = bounds[2].max(bounds[0] + exact_w.max(line.full_width())), + crate::el::Flow::Rtl => bounds[0] = bounds[0].min(bounds[2] - exact_w.max(line.full_width())), + } + } + let text_clip = intersect(clip, bounds); + self.paint_grid_text(s, text, images, instances, &row.line, line, origin, clip, Some(text_clip), fade, o, glyph_count, &mut pages); + + // Pinned cells: a `text` each, at its column's left edge and the row's top. + for (cell, layout) in row.cells.iter().zip(laid.cells.iter()) { + let layout: &Rc<parley::Layout<crate::text::Ink>> = layout; + let cx = round(px(origin_pt[0] + f32::from(cell.col) * cw)) + shift[0]; + let cell_flow = crate::el::Flow::of_layout(layout); + let w = layout.full_width().ceil(); + let at = [text_x(&cell.spec, cx, cx + w, w, cell_flow), row_r[1]]; + self.paint_grid_text(s, text, images, instances, &cell.spec, layout, at, clip, None, fade, o, glyph_count, &mut pages); + } + + // The vector layer over the text, from its box's origin rounded to the device grid. + if let Some(shape) = &row.over { + let at = [round(x0) + shift[0], round(y0) + shift[1]]; + push_shape(instances, shape, at, [s, s], s, o, srgb, clip, fade); + } + *row.drawn.borrow_mut() = pages.map(|pages| DrawnRow { + key: key(text.emit_key()), + instances: instances[start..].to_vec(), + pages, + glyphs: *glyph_count - glyphs, + }); + } + text.set_emit(crate::text::outline::Emit::Atlas); + } + + /// Row `row`'s shaped line and cells at this scale and width, shaped on its first paint. + fn laid_row(text: &mut TextSystem, s: f32, row: &GridRow, width_pt: f32, flow: crate::el::Flow) -> LaidRowRef { + let fits = |l: &LaidRow| l.scale == s.to_bits() && l.width == width_pt.to_bits(); + if let Some(l) = row.laid.borrow().as_ref().filter(|l| fits(l)) { + return LaidRowRef { line: l.line.clone(), cells: l.cells.clone() }; + } + // As commit lays a text node out: its direction from the element's flow, and its layout + // at its box's width when it wraps. A row's texts start left to right, so most need no + // copy; the layout's key is the one commit's shape key gives. + let mut shape = |spec: &crate::el::TextSpec, wrap: Option<f32>| { + let dir = crate::el::step_text_dir(spec.dir, crate::el::TextDirEvent::Flatten(Some(flow))); + if spec.dir == dir && spec.shape.is_none() { + return text.layout_for_spec(&spec.as_text_input(s, false), s, wrap, line_alignment(spec)); + } + let mut spec = spec.clone(); + spec.dir = dir; + spec.shape = None; + text.layout_for_spec(&spec.as_text_input(s, false), s, wrap, line_alignment(&spec)) + }; + let line = shape(&row.line, row.line.wrap.then_some(width_pt * s)); + let cells: Vec<_> = row.cells.iter().map(|c| shape(&c.spec, None)).collect(); + *row.laid.borrow_mut() = Some(LaidRow { scale: s.to_bits(), width: width_pt.to_bits(), line: line.clone(), cells: cells.clone() }); + LaidRowRef { line, cells } + } + + /// One text's decorations and glyphs from `origin`, as a still, unscaled text node paints + /// them; `text_clip` is the clip its glyphs take when it has one of its own. Adds the atlas + /// pages its glyphs sample to `pages`, or empties it for a glyph a copy can't draw again. + #[allow(clippy::too_many_arguments)] + fn paint_grid_text( + &mut self, + s: f32, + text: &mut TextSystem, + images: &mut crate::pixels::ImageAtlas, + instances: &mut Vec<Instance>, + spec: &crate::el::TextSpec, + layout: &Rc<parley::Layout<crate::text::Ink>>, + origin: [f32; 2], + clip: [f32; 4], + text_clip: Option<[f32; 4]>, + fade: [f32; 4], + o: f32, + glyph_count: &mut usize, + pages: &mut Option<Vec<(u16, u32)>>, + ) { + let srgb = self.srgb_blend; + self.deco_scratch.clear(); + text.decorations_with_rings(layout, &spec.spans, &[], spec.cold.span_radius, s, origin, &mut self.deco_scratch); + for d in &self.deco_scratch { + instances.push(rect_inst(d.rect, premul(d.color, o, srgb), d.radius, clip, fade)); + } + self.glyph_scratch.clear(); + text.set_glyph_inks(spec.color, &spec.spans); + text.set_glide([0.0; 2]); + let em = spec.spans.iter().filter_map(|sp| sp.size).fold(spec.style.size.max(spec.style.line_px()), f32::max); + let pad = 2.0 * em * s + 2.0; + let band = (clip[1] - origin[1]) - pad..(clip[3] - origin[1]) + pad; + text.glyphs_in_band_cached(layout, origin, 1.0, false, band, &mut self.glyph_scratch); + let base = premul(spec.color, o, srgb); + let glyph_clip = text_clip.unwrap_or(clip); + for q in &self.glyph_scratch { + let [x0, y0] = [q.rect[0], q.rect[1]]; + let (x1, y1) = (x0 + q.rect[2], y0 + q.rect[3]); + if y0 > clip[3] || y1 < clip[1] || x0 > clip[2] || x1 < clip[0] { + continue; + } + let f = if q.ink > 0 && let Some(c) = spec.spans.get(q.ink as usize - 1).and_then(|sp| sp.color) { premul(c, o, srgb) } else { base }; + instances.extend(glyph_or_image(q, text, images, f, glyph_clip, fade)); + *glyph_count += 1; + if q.color != 0 || q.outline.is_some() { + *pages = None; + } else if let Some(pages) = pages.as_mut() { + let (page, texels) = (q.atlas_page() as u16, (q.rect[2] * if q.lcd { 3.0 } else { 1.0 } * q.rect[3]) as u32); + match pages.iter_mut().find(|p| p.0 == page) { + Some(p) => p.1 += texels, + None => pages.push((page, texels)), + } + } + } + } +} + +/// A row's laid-out line and cells, for one paint. +struct LaidRowRef { + line: Rc<parley::Layout<crate::text::Ink>>, + cells: Vec<Rc<parley::Layout<crate::text::Ink>>>, +} diff --git a/app/vendor/rune/crates/rune/src/runtime/paint/helpers.rs b/app/vendor/rune/crates/rune/src/runtime/paint/helpers.rs new file mode 100644 index 0000000..f2f6b2a --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/paint/helpers.rs @@ -0,0 +1,350 @@ +//! Free paint helpers for rich-text block decorations, field carets, glyphs and rects. +use super::*; + +#[allow(clippy::too_many_arguments)] +pub(in crate::runtime) fn emit_block_decorations( + instances: &mut Vec<Instance>, + text_sys: &mut TextSystem, + images: &mut crate::pixels::ImageAtlas, + glyph_scratch: &mut Vec<crate::text::GlyphQuad>, + spec: &TextSpec, + layout: TextFlow<'_>, + origin: [f32; 2], + (x0, x1): (f32, f32), + s: f32, + tk: f32, + raster: f32, + scale_motion: ScaleMotion, + glide: [f32; 2], + text_color: Color, + o: f32, + srgb: bool, + clip: [f32; 4], + fade: [f32; 4], +) { + use crate::edit::{Block, MAX_LIST_LEVEL}; + let line_h_default = spec.style.line_px() * s * tk; + let box_w = (x1 - x0).max(layout.full_width() * tk).max(40.0 * s * tk); + let mut para_idx = 0usize; + let mut first_line_of_para = true; + let mut list_counts = [0u32; (MAX_LIST_LEVEL as usize) + 1]; + let mut code_run: Option<(f32, f32)> = None; + let mut quote_run: Option<(f32, f32)> = None; + let mut markers: Vec<(f32, f32, Block, u32)> = Vec::new(); + + let flush_code = |instances: &mut Vec<Instance>, run: &mut Option<(f32, f32)>| { + if let Some((top, bot)) = run.take() { + let pad_y = if tk == 1.0 { (2.0 * s).round() } else { 2.0 * s * tk }; + instances.push(rect_inst( + [x0 + glide[0], top - pad_y + glide[1], box_w, (bot - top) + 2.0 * pad_y], + premul(spec.rich_style().code_block_bg, o, srgb), + 6.0 * s * tk, + clip, + fade, + )); + } + }; + let flush_quote = |instances: &mut Vec<Instance>, run: &mut Option<(f32, f32)>| { + if let Some((top, bot)) = run.take() { + let bar_w = if tk == 1.0 { (3.0 * s).round().max(2.0) } else { (3.0 * s * tk).max(2.0 * tk) }; + let bar_x = if tk == 1.0 { (origin[0] + 2.0 * s).round() } else { origin[0] + 2.0 * s * tk } + glide[0]; + let inset_y = if tk == 1.0 { (2.0 * s).round() } else { 2.0 * s * tk }; + instances.push(rect_inst( + [bar_x, top + inset_y + glide[1], bar_w, (bot - top - 2.0 * inset_y).max(4.0 * s * tk)], + premul(spec.rich_style().quote_bar, o, srgb), + bar_w * 0.5, + clip, + fade, + )); + } + }; + + let mut had_lines = false; + for line in layout.block_lines(spec.style.line_px() * s) { + had_lines = true; + let blk = spec.cold.blocks.get(para_idx).copied().unwrap_or(Block::Paragraph); + let is_soft = spec.cold.soft_breaks.binary_search(&(para_idx as u32)).is_ok(); + let top = origin[1] + line.top * tk; + let bot = origin[1] + line.bottom * tk; + let baseline = origin[1] + line.baseline * tk; + + if blk == Block::Code { + flush_quote(instances, &mut quote_run); + match &mut code_run { + Some((_, b)) => *b = bot, + None => code_run = Some((top, bot)), + } + } else if blk == Block::Quote { + flush_code(instances, &mut code_run); + match &mut quote_run { + Some((_, b)) => *b = bot, + None => quote_run = Some((top, bot)), + } + } else { + flush_code(instances, &mut code_run); + flush_quote(instances, &mut quote_run); + } + + if first_line_of_para { + match blk { + Block::Bullet(lvl) => { + let l = (lvl.min(MAX_LIST_LEVEL)) as usize; + for c in &mut list_counts[l + 1..] { + *c = 0; + } + list_counts[l] = 0; + if !is_soft { + let indent = (blk.indent_pt(spec.style.size) * s).round(); + markers.push((indent, baseline, blk, 0)); + } + } + Block::Numbered(lvl) => { + let l = (lvl.min(MAX_LIST_LEVEL)) as usize; + for c in &mut list_counts[l + 1..] { + *c = 0; + } + if !is_soft { + list_counts[l] += 1; + let indent = (blk.indent_pt(spec.style.size) * s).round(); + markers.push((indent, baseline, blk, list_counts[l])); + } + } + Block::Paragraph | Block::Quote | Block::Code => { + if !is_soft { + list_counts = [0; (MAX_LIST_LEVEL as usize) + 1]; + } + } + } + } + + if line.last { + para_idx += 1; + first_line_of_para = true; + } else { + first_line_of_para = false; + } + } + + if !had_lines + && let Some(&blk) = spec.cold.blocks.first() + { + let top = origin[1]; + let bot = top + line_h_default; + let baseline = top + spec.style.size * 0.8 * s * tk; + match blk { + Block::Code => code_run = Some((top, bot)), + Block::Quote => quote_run = Some((top, bot)), + Block::Bullet(_) => { + let indent = (blk.indent_pt(spec.style.size) * s).round(); + markers.push((indent, baseline, blk, 0)); + } + Block::Numbered(_) => { + let indent = (blk.indent_pt(spec.style.size) * s).round(); + markers.push((indent, baseline, blk, 1)); + } + Block::Paragraph => {} + } + } + + flush_code(instances, &mut code_run); + flush_quote(instances, &mut quote_run); + + if !markers.is_empty() { + let marker_color = spec.rich_style().marker.unwrap_or_else(|| text_color.alpha(0.68)); + let mc = premul(marker_color, o, srgb); + for (indent_px, baseline_y, blk, num) in markers { + match blk { + Block::Bullet(lvl) => { + let d = if tk == 1.0 { (4.5 * s).round().max(3.0) } else { (4.5 * s * tk).max(3.0 * tk) }; + let cx = origin[0] + (indent_px - (7.0 * s).round()) * tk - d; + let cy = baseline_y - 0.34 * spec.style.size * s * tk - d * 0.5; + let (cx, cy) = if tk == 1.0 { (cx.round(), cy.round()) } else { (cx, cy) }; + let radius = if lvl >= 2 { 1.0 * s * tk } else { d * 0.5 }; + let c = if lvl == 1 { premul(marker_color.alpha(marker_color.a * 0.65), o, srgb) } else { mc }; + instances.push(rect_inst([cx + glide[0], cy + glide[1], d, d], c, radius, clip, fade)); + } + Block::Numbered(_) => { + let label = format!("{num}."); + let ml = text_sys.layout_rich(&label, &[], spec.style, s, None); + let mw = ml.full_width(); + let m_base = ml.lines().next().map_or(spec.style.size * 0.8 * s, |l| l.metrics().baseline); + let mx = origin[0] + (indent_px - (5.0 * s).round() - mw) * tk; + let my = baseline_y - m_base * tk; + let m_origin = if tk == 1.0 { [mx.round(), my.round()] } else { [mx, my] }; + let m_r_origin = if scale_motion == ScaleMotion::Still { m_origin } else { [0.0, 0.0] }; + glyph_scratch.clear(); + text_sys.set_glyph_inks(marker_color, &[]); + text_sys.set_glide(glide); + text_sys.glyphs_for_layout_scaled(&ml, m_r_origin, raster, false, glyph_scratch); + text_sys.set_glide([0.0; 2]); + for q in &*glyph_scratch { + instances.extend( + glyph_or_image(q, text_sys, images, mc, clip, fade) + .map(|g| zoom_glyph(g, m_origin, m_r_origin, tk / raster)), + ); + } + } + _ => {} + } + } + } +} + +/// Pixel caret and logical-point IME area use the same shaped cursor geometry. +pub(in crate::runtime) fn input_caret(n: &Node, r: [f32; 4], scale: f32, s: f32, gliding: bool, scrolls: &mut HashMap<String, f32>) -> Option<([f32; 4], [f32; 4])> { + let (spec, laid, input) = (n.text.as_ref()?, n.text_layout.as_ref()?, n.input.as_ref()?); + let layout = laid.view(); + let e = &input.edit; + let ins = n.inset.map(|v| v * scale * s); + let (x0, x1) = (r[0] + ins[0], r[2] - ins[2]); + // The text scales with its box, so the caret does too. + let mut x = text_x(spec, x0, x1, text_width(layout.full_width() * scale), layout.flow()); + if input.single_line && let Some(l) = laid.single() { + x -= single_line_scroll(scrolls, &n.path, input, &spec.content, l, s, (x1 - x0) / scale.max(1e-4)) * scale; + } + let bb = layout.caret(caret_index(e, &spec.content), e.affinity, 1.5 * s); + let (cx, cy) = (x + bb.x0 as f32 * scale, r[1] + ins[1] + bb.y0 as f32 * scale); + let h = (if bb.y1 > bb.y0 { (bb.y1 - bb.y0) as f32 } else { spec.style.line_px() * s }) * scale; + let (caret_x, caret_w) = if (scale - 1.0).abs() <= 1e-5 { + let gx = if gliding { pixel_snap::text_glide(r[0]) } else { 0.0 }; + ((cx - gx).round() + gx, (1.5 * s).round().max(1.0)) + } else { + (cx, (1.5 * s * scale).max(1.0)) + }; + // The candidate window opens under the clause being converted, its left edge at the + // clause's start, as it does in a native field; else at the caret. + let area = match (e.preedit_target(), e.range().0) { + (Some((ta, tb)), at) => { + let len = spec.content.len(); + let (a, b) = (layout.caret((at + ta).min(len), e.affinity, 0.0), layout.caret((at + tb).min(len), e.affinity, 0.0)); + let (ax, ay) = (x + a.x0 as f32 * scale, r[1] + ins[1] + a.y0 as f32 * scale); + let w = if (b.y0 - a.y0).abs() < 0.5 && b.x0 > a.x0 { (b.x0 - a.x0) as f32 * scale } else { 2.0 * scale * s }; + [ax / s, ay / s, w / s, h / s] + } + (None, _) => [cx / s, cy / s, 2.0 * scale, h / s], + }; + Some(([caret_x, cy + h * 0.1, caret_w, h * 0.8], area)) +} + +/// Whether `looping`'s sampled value multiplies the element's opacity. +pub(in crate::runtime) fn fades(looping: Option<rune_motion::LoopSpec>) -> bool { + matches!(looping.map(|l| l.kind), Some(rune_motion::LoopKind::Opacity { .. } | rune_motion::LoopKind::OpacityCycle(_) | rune_motion::LoopKind::Sequence(_))) +} + +/// How many separate things node `n` paints itself (fill, border, gradient, shape, image, +/// shadows, words), which can lie one over another. +pub(in crate::runtime) fn own_paints(n: &Node) -> usize { + let v = &n.vis; + [ + v.fill.a > 0.0, + v.border_width() > 0.0 && (v.border().a > 0.0 || v.border_bottom.is_some()), + v.gradient.is_some() || v.radial.is_some() || v.surface.is_some(), + v.shape.is_some(), + v.grid.is_some(), + v.pixels.is_some(), + !v.shadows.is_empty(), + n.text.is_some(), + ].into_iter().filter(|&b| b).count() +} + +/// Whether `rect` (edges) lies a pixel or more inside the rounded rectangle `mask` (edges) with +/// corner `radii` `[tl, tr, br, bl]`, so that rounding the mask's corners can't touch it. The +/// mask is convex, so it's enough that `rect`'s corners are inside; a continuous corner counts +/// as its whole corner square. +pub(in crate::runtime) fn inside_rounded(rect: [f32; 4], mask: [f32; 4], radii: [f32; 4]) -> bool { + const AA: f32 = 1.0; + if rect[2] <= rect[0] || rect[3] <= rect[1] { return true; } + if rect[0] < mask[0] || rect[1] < mask[1] || rect[2] > mask[2] || rect[3] > mask[3] { return false; } + let corners = [(mask[0], mask[1], 1.0, 1.0), (mask[2], mask[1], -1.0, 1.0), (mask[2], mask[3], -1.0, -1.0), (mask[0], mask[3], 1.0, -1.0)]; + corners.iter().zip(radii).all(|(&(cx, cy, sx, sy), radius)| { + let e = crate::render::corner_extent(radius); + [(rect[0], rect[1]), (rect[2], rect[1]), (rect[2], rect[3]), (rect[0], rect[3])].iter().all(|&(x, y)| { + let (dx, dy) = ((x - cx) * sx, (y - cy) * sy); + if dx >= e || dy >= e { return true; } + radius > 0.0 && (radius - dx).hypot(radius - dy) <= radius - AA + }) + }) +} + +/// `rect` (x, y, w, h) magnified `k` times from `r_origin` to `origin`. +pub(in crate::runtime) fn scale_about(rect: [f32; 4], origin: [f32; 2], r_origin: [f32; 2], k: f32) -> [f32; 4] { + [origin[0] + (rect[0] - r_origin[0]) * k, origin[1] + (rect[1] - r_origin[1]) * k, rect[2] * k, rect[3] * k] +} + +/// A glyph instance drawn `k` times its rasterized size about `origin`. An alpha glyph keeps +/// its atlas footprint in `uv.zw`, so the shader samples it filtered. +pub(in crate::runtime) fn zoom_glyph(mut g: Instance, origin: [f32; 2], r_origin: [f32; 2], k: f32) -> Instance { + if k == 1.0 && origin == r_origin { return g; } + if g.params[1] == KIND_GLYPH && g.radii[3] > 0.0 { + // An outline glyph (`text::Outline`) magnifies its pen and pixel instead of its mask. + g.radii = [origin[0] + (g.radii[0] - r_origin[0]) * k, origin[1] + (g.radii[1] - r_origin[1]) * k, g.radii[2], g.radii[3] * k]; + } else if g.params[1] == KIND_GLYPH && g.uv[2] == 0.0 { + // A subpixel mask's footprint is three texels a pixel wide. + (g.uv[2], g.uv[3]) = (g.rect[2] * if g.radii[0] > 0.5 { 3.0 } else { 1.0 }, g.rect[3]); + } + g.rect = [ + origin[0] + (g.rect[0] - r_origin[0]) * k, + origin[1] + (g.rect[1] - r_origin[1]) * k, + g.rect[2] * k, + g.rect[3] * k, + ]; + g +} + +/// A text glyph's instance: alpha-atlas coverage tinted by `fill`, or a colour glyph's image +/// at `fill`'s alpha. None when the image atlas can't place it. +pub(in crate::runtime) fn glyph_or_image(q: &GlyphQuad, text: &TextSystem, images: &mut crate::pixels::ImageAtlas, fill: [f32; 4], clip: [f32; 4], fade: [f32; 4]) -> Option<Instance> { + if q.color == 0 { + let mut g = glyph(q, fill, clip, fade); + g.params[3] = text.coverage_exponent(fill); + return Some(g); + } + let image = images.place(text.color_glyph(q.color), [q.rect[2], q.rect[3]])?; + Some(Instance { + rect: q.rect, + radii: [0.0; 4], + fill: [0.0, 0.0, 0.0, fill[3]], + border: [0.0; 4], + params: [image.page as f32, KIND_IMAGE, image.premultiplied as u8 as f32, 1.0], + uv: image.rect.map(|v| v as f32), + clip, + fade: crate::render::pack_fade(fade, clip, clip), + }) +} + +pub(in crate::runtime) fn rect_inst(rect: [f32; 4], fill: [f32; 4], radius: f32, clip: [f32; 4], fade: [f32; 4]) -> Instance { + Instance { + rect, + radii: [radius; 4], + fill, + border: [0.0; 4], + params: [0.0, KIND_RECT, 0.0, 1.0], + uv: [0.0; 4], + clip, + fade: crate::render::pack_fade(fade, clip, clip), + } +} + +/// A misspelled word's marker: Chromium's red, on macOS a row of dots and elsewhere a wavy line. +/// (Linear light: #FF3B30 on macOS, #FF0000 elsewhere.) +pub(in crate::runtime) const SPELLING: Color = if cfg!(target_os = "macos") { Color { r: 1.0, g: 0.0437, b: 0.0296, a: 1.0 } } else { Color { r: 1.0, g: 0.0, b: 0.0, a: 1.0 } }; + +/// The spelling marker from device x `x0` to `x1`, its top at `y`, `k` device px a point: on +/// macOS 3 pt dots every 4 pt, elsewhere Chromium's 1 pt line waving 2 pt down and back every 6 pt. +#[allow(clippy::too_many_arguments)] +pub(in crate::runtime) fn push_spelling_marker(out: &mut Vec<Instance>, x0: f32, x1: f32, y: f32, k: f32, color: [f32; 4], clip: [f32; 4], fade: [f32; 4]) { + if cfg!(target_os = "macos") { + let (d, step) = (3.0 * k, 4.0 * k); + let count = ((x1 - x0 - d) / step).floor().max(0.0) as usize + 1; + let x = x0 + ((x1 - x0) - (count - 1) as f32 * step - d) / 2.0; + out.extend((0..count).map(|n| rect_inst([x + n as f32 * step, y, d, d], color, d / 2.0, clip, fade))); + return; + } + const WAVE: [f32; 6] = [0.0, 1.0, 2.0, 2.0, 1.0, 0.0]; + let t = k.max(1.0).round(); + let start = x0.round(); + out.extend((0..(x1.round() - start).max(0.0) as usize).map(|n| { + let wave = WAVE[(n as f32 / k) as usize % WAVE.len()]; + rect_inst([start + n as f32, (y + wave * k).round(), 1.0, t], color, 0.0, clip, fade) + })); +} diff --git a/app/vendor/rune/crates/rune/src/runtime/paint/keep.rs b/app/vendor/rune/crates/rune/src/runtime/paint/keep.rs new file mode 100644 index 0000000..2e20661 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/paint/keep.rs @@ -0,0 +1,597 @@ +//! Paint: a subtree that would paint what it painted last time copies it instead. +//! +//! Each paint records, for every node, what its subtree emitted (its instances and their marks, +//! its hits, the atlas pages its glyphs sample, its glyph count) and what that depended on: the +//! node's commit epoch (a node built again from its element gets a new one; a node a region kept +//! keeps its own), the per-node rows paint reads (`row_dy`, `row_h`, `row_mask`), and the hash of +//! the state it inherited (`Inh`). The next paint copies a subtree whose nodes are the same ones, +//! in the same shape, none of whose scene values were presented again since, under the same +//! inherited state, in a window whose shared paint state (scale, viewport, blending, the glyph +//! atlas's key, focus) is the same. What paint would read elsewhere, or as time passes, keeps a +//! node from being copied (`static_ok`, `dynamic_ok`, and what the paint of it found). +//! +//! Debug builds paint a subtree they would copy and say on stderr where the copy would differ. + +use std::hash::{Hash, Hasher}; +use std::sync::atomic::{AtomicU32, Ordering}; + +use super::*; + +static EPOCH: AtomicU32 = AtomicU32::new(1); + +/// A new commit epoch for a node built from its element. +pub(in crate::runtime) fn next_epoch() -> u32 { + EPOCH.fetch_add(1, Ordering::Relaxed) +} + +const NONE: u32 = u32::MAX; + +#[derive(Clone, Copy)] +pub(in crate::runtime) struct PaintRec { + id: NodeId, + epoch: u32, + /// Its index less its parent's (0 for a root). + up: u32, + own: u64, + inh: u64, + /// One past its subtree's last node. + end: u32, + inst: [u32; 2], + hits: [u32; 2], + /// Its range of `Runtime::wheel_hits`, kept with the hits so a reused subtree's wheel entries come back too. + wheel: [u32; 2], + overlay: [u32; 2], + help: [u32; 2], + drop: [u32; 2], + pages: [u32; 2], + glyphs: [u32; 2], + /// What its own fields say (`static_ok`), kept while its epoch is. + fits: bool, + keep: bool, +} + +impl Default for PaintRec { + fn default() -> Self { + PaintRec { id: NodeId(u64::MAX), epoch: 0, up: 0, own: 0, inh: 0, end: 0, inst: [0; 2], hits: [0; 2], wheel: [0; 2], overlay: [0; 2], help: [0; 2], drop: [0; 2], pages: [0; 2], glyphs: [0; 2], fits: false, keep: false } + } +} + +#[derive(Default)] +pub(in crate::runtime) struct PaintKeep { + pub(in crate::runtime) cycles: cycle::CyclePaint, + recs: Vec<PaintRec>, + prev: Vec<PaintRec>, + instances: Vec<Instance>, + marks: Vec<u32>, + hits: Vec<(NodeId, [f32; 4])>, + wheel: Vec<(NodeId, [f32; 4])>, + overlay: Vec<[f32; 4]>, + help: Vec<(NodeId, [f32; 4], usize, Option<usize>)>, + drop: Vec<(NodeId, [f32; 4], usize)>, + drawn: Vec<[f32; 4]>, + drawn_scale: Vec<f32>, + seen: Vec<bool>, + inh: Vec<Inh>, + sticky_frame: Vec<[f32; 8]>, + pages: Vec<(u16, u32)>, + prev_pages: Vec<(u16, u32)>, + /// Nodes presented again since the last paint. + pub(in crate::runtime) moved: Vec<NodeId>, + moved_at: Vec<bool>, + /// The window's shared paint state at the last paint, when it could be kept from. + key: Option<u64>, + /// This paint copies what it can, and records what it paints (in tree order only). + on: bool, + recording: bool, + /// Frames stepped, and the one the last paint ran in: a second paint in a frame paints all. + pub(in crate::runtime) frame: u64, + painted: u64, + /// This paint's nodes: last paint's index of each, one past each subtree, whether each + /// subtree is as it was. + old: Vec<u32>, + end: Vec<u32>, + clean: Vec<bool>, + fits: Vec<bool>, + open: Vec<usize>, + /// Last paint's index of each node by id, built when this paint's order leaves last paint's. + by_id: HashMap<NodeId, u32>, + /// Debug builds: the last paint's index of a subtree painted to check its copy. + verify: Vec<u32>, + verify_span: (usize, usize), + /// Nodes copied this paint, and why the others weren't as they were (`RUNE_PAINT_KEEP_LOG`). + kept: usize, + why: [usize; 6], + /// The next paint paints everything (the raster check's fresh paint). + pub(in crate::runtime) off_once: bool, +} + +fn disabled() -> bool { + static OFF: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + *OFF.get_or_init(|| std::env::var_os("RUNE_PAINT_KEEP").is_some_and(|v| v == "0")) +} + +fn logging() -> bool { + static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("RUNE_PAINT_KEEP_LOG").is_some_and(|v| v != "0")) +} + +#[inline(always)] +fn bits(h: &mut rune_motion::Fx, v: &[f32]) { + // Two values a word: half the hasher's rounds. + let mut pairs = v.chunks_exact(2); + for p in &mut pairs { + h.write_u64(u64::from(p[0].to_bits()) | u64::from(p[1].to_bits()) << 32); + } + if let [x] = pairs.remainder() { + h.write_u32(x.to_bits()); + } +} + +/// The bits of what a node inherits. +pub(in crate::runtime) fn inh_key(p: &Inh) -> u64 { + let mut h = rune_motion::Fx::default(); + bits(&mut h, &[p.opacity, p.paint_opacity, p.first_fade, p.scale, p.blur, p.dy, p.dx, p.group, p.hit_opacity]); + for a in [p.clip, p.fade, p.fade_origin, p.paint_clip, p.paint_fade, p.paint_fade_origin, p.group_rect] { + bits(&mut h, &a); + } + bits(&mut h, &p.anchor); + bits(&mut h, &p.anchor_to); + bits(&mut h, &p.cover); + match p.rounded { + Some((a, b)) => { h.write_u8(1); bits(&mut h, &a); bits(&mut h, &b); } + None => h.write_u8(0), + } + match p.outer { + Some(o) => { h.write_u8(1); for a in o { bits(&mut h, &a); } } + None => h.write_u8(0), + } + h.write_u32(p.mark); + h.write_u8(p.scale_motion as u8); + bits(&mut h, &[p.still.0]); + bits(&mut h, &p.still.1); + bits(&mut h, &p.still.2); + (p.in_cache, p.skip_paint, p.anchor_hidden, p.turn).hash(&mut h); + p.snap.hash_bits(&mut h); + h.finish() +} + +impl RuntimeCore { + /// Before a paint clears them: last paint's output and side tables become the record copies + /// come from. + pub(in crate::runtime) fn keep_swap(&mut self) { + let k = &mut self.paint.keep; + k.cycles.begin(self.commit.commits); + std::mem::swap(&mut self.instances, &mut k.instances); + // Both sides of the swap retain the warmed paint budget, even if a reveal + // temporarily emits fewer glyphs on the frames painted into one of them. + self.instances.clear(); + self.instances.reserve_exact(k.instances.capacity()); + std::mem::swap(&mut self.marks, &mut k.marks); + std::mem::swap(&mut self.hit.hits, &mut k.hits); + std::mem::swap(&mut self.hit.wheel_hits, &mut k.wheel); + std::mem::swap(&mut self.hit.overlay_hits, &mut k.overlay); + std::mem::swap(&mut self.hit.help_hits, &mut k.help); + std::mem::swap(&mut self.hit.drop_hits, &mut k.drop); + std::mem::swap(&mut self.paint.drawn, &mut k.drawn); + std::mem::swap(&mut self.paint.drawn_scale, &mut k.drawn_scale); + std::mem::swap(&mut self.paint.seen, &mut k.seen); + std::mem::swap(&mut self.paint.inh_scratch, &mut k.inh); + std::mem::swap(&mut self.scroll.sticky_frame, &mut k.sticky_frame); + std::mem::swap(&mut k.recs, &mut k.prev); + std::mem::swap(&mut k.pages, &mut k.prev_pages); + // The other pairs too, as the instances above: a paint that grows one buffer doesn't + // leave the frame after it to grow the other. + twin(&mut self.marks, &k.marks); + twin(&mut self.hit.hits, &k.hits); + twin(&mut self.hit.wheel_hits, &k.wheel); + twin(&mut self.hit.overlay_hits, &k.overlay); + twin(&mut self.hit.help_hits, &k.help); + twin(&mut self.hit.drop_hits, &k.drop); + twin(&mut k.pages, &k.prev_pages); + k.pages.clear(); + k.recs.clear(); + k.recs.resize(self.tree.nodes.len(), PaintRec::default()); + k.open.clear(); + k.kept = 0; + } + + /// Whether this paint copies what it can, from the window's shared state, and if so which + /// of its subtrees are as last paint left them. + pub(in crate::runtime) fn keep_begin(&mut self, tree_order: bool, vp: [f32; 4], default_ring: Option<usize>, sel: &[(usize, usize, usize)], marks: &[(usize, usize, usize)]) { + let second = self.paint.keep.painted == self.paint.keep.frame; + self.paint.keep.painted = self.paint.keep.frame; + // Paint goes depth first, siblings in paint order (`update_layer_paint_order`), so a subtree + // paints in one run unless it holds a node lifted out to paint last. + let lifted = !self.motion.flying.is_empty() || self.tree.has_raise; + let shareable = !lifted && self.motion.flights().is_empty() && self.paint.paint_rank.is_none() + && self.kbd.modal_scope.is_none() && !self.commit.defaults.force_focus_rings && !disabled(); + let key = shareable.then(|| { + let mut h = rune_motion::Fx::default(); + bits(&mut h, &[self.env.scale]); + bits(&mut h, &vp); + (self.paint.srgb_blend, self.track_marks, self.reduced_motion, self.env.system_dark, self.text.emit_key(), self.tree.has_sticky, tree_order).hash(&mut h); + (self.kbd.focus.path(), self.kbd.focus.keyboard(), self.kbd.focus.shown()).hash(&mut h); + default_ring.map(|i| self.tree.nodes[i].id).hash(&mut h); + let ring = self.default_focus_ring(); + bits(&mut h, &[ring.width, ring.offset, ring.color.r, ring.color.g, ring.color.b, ring.color.a]); + h.finish() + }); + if logging() && !shareable { + eprintln!("rune: paint keep off: raise {}, text flights {}, flying {}, rank {}, modal {}", self.tree.has_raise, self.motion.flights().len(), self.motion.flying.len(), self.paint.paint_rank.is_some(), self.kbd.modal_scope.is_some()); + } + let k = &mut self.paint.keep; + k.recording = !lifted; + k.on = key.is_some() && key == k.key && !second && !std::mem::take(&mut k.off_once) && !k.prev.is_empty(); + k.key = key; + let n = self.tree.nodes.len(); + k.verify.clear(); + k.verify.resize(n, NONE); + k.verify_span = (0, 0); + if !k.recording { + return; + } + // Last paint's index of each node: in order, as kept regions leave them. + k.old.clear(); + k.old.resize(n, NONE); + // Scratch kept from paint to paint: a frame allocates nothing here. + k.by_id.clear(); + let mut cursor = 0usize; + for i in 0..n { + let id = self.tree.nodes[i].id; + let o = if k.prev.get(cursor).is_some_and(|r| r.id == id) { Some(cursor) } else { + if k.by_id.is_empty() { + k.by_id.extend(k.prev.iter().enumerate().map(|(o, r)| (r.id, o as u32))); + } + k.by_id.get(&id).map(|&o| o as usize) + }; + if let Some(o) = o { + k.old[i] = o as u32; + cursor = o + 1; + } + } + // What each node's own fields say, read again only for a node built again. + k.fits.clear(); + for i in 0..n { + let o = k.old[i]; + let fits = match k.prev.get(o as usize).filter(|r| o != NONE && r.epoch == self.tree.nodes[i].epoch) { + Some(r) => r.fits, + None => static_ok(&self.tree.nodes[i]), + }; + k.fits.push(fits); + } + if !k.on { + return; + } + k.moved_at.clear(); + k.moved_at.resize(n, false); + for id in &k.moved { + if let Some(&i) = self.tree.node_index.get(id) && i < n { + k.moved_at[i] = true; + } + } + // One past each subtree, and whether each node is as it was. + k.end.clear(); + k.end.resize(n, n as u32); + k.clean.clear(); + k.clean.resize(n, false); + k.open.clear(); + for i in 0..n { + let parent = self.tree.nodes[i].parent; + let (own, fit) = (own_key(self, i), self.paint.keep.fits[i] && dynamic_ok(self, i, sel, marks)); + let k = &mut self.paint.keep; + while let Some(&r) = k.open.last() && parent.is_none_or(|p| r > p) { + k.end[r] = i as u32; + k.open.pop(); + } + k.open.push(i); + let o = k.old[i]; + if logging() { + let why = if !fit { 0 } else if o == NONE { 1 } else if k.moved_at[i] { 2 } else if k.prev[o as usize].epoch != self.tree.nodes[i].epoch { 3 } else if k.prev[o as usize].own != own { 4 } else { 5 }; + k.why[why] += 1; + if (why == 2 || why == 3) && std::env::var_os("RUNE_PAINT_KEEP_LOG").is_some_and(|v| v == "2") { + eprintln!("rune: paint keep: {} {}", if why == 2 { "moved" } else { "rebuilt" }, self.tree.nodes[i].path); + } + } + k.clean[i] = fit && o != NONE && !k.moved_at[i] && { + let r = &k.prev[o as usize]; + let up = parent.map_or(0, |p| (i - p) as u32); + r.epoch == self.tree.nodes[i].epoch && r.up == up && r.own == own + && parent.is_none_or(|p| k.old[p] != NONE && k.old[p] + up == o) + }; + } + let k = &mut self.paint.keep; + k.open.clear(); + for i in (1..n).rev() { + if !k.clean[i] && let Some(p) = self.tree.nodes[i].parent { + k.clean[p] = false; + } + } + } + + /// Opens node `i`'s record, before it paints anything. + pub(in crate::runtime) fn keep_open(&mut self, i: usize, glyphs: usize, sel: &[(usize, usize, usize)], marks: &[(usize, usize, usize)]) { + self.paint.slide_node_opens(i, self.instances.len(), self.env.scale); + if !self.paint.keep.recording { return; } + let rec = PaintRec { + id: self.tree.nodes[i].id, + epoch: self.tree.nodes[i].epoch, + up: self.tree.nodes[i].parent.map_or(0, |p| (i - p) as u32), + own: own_key(self, i), + inh: 0, + end: 0, + inst: [self.instances.len() as u32; 2], + hits: [self.hit.hits.len() as u32; 2], + wheel: [self.hit.wheel_hits.len() as u32; 2], + overlay: [self.hit.overlay_hits.len() as u32; 2], + help: [self.hit.help_hits.len() as u32; 2], + drop: [self.hit.drop_hits.len() as u32; 2], + pages: [self.paint.keep.pages.len() as u32; 2], + glyphs: [glyphs as u32; 2], + fits: self.paint.keep.fits[i], + keep: self.paint.keep.fits[i] && dynamic_ok(self, i, sel, marks), + }; + self.paint.keep.recs[i] = rec; + self.paint.keep.open.push(i); + } + + /// Node `i` inherits `pinh`: copies its subtree from the last paint when that's what it would + /// paint, and returns how many nodes it holds. + pub(in crate::runtime) fn keep_or_paint(&mut self, i: usize, pinh: &Inh, glyph_count: &mut usize) -> Option<usize> { + // Only a node that can be copied needs what it inherits. + if !self.paint.keep.recording || !self.paint.keep.recs[i].keep { return None; } + let inh = inh_key(pinh); + self.paint.keep.recs[i].inh = inh; + let k = &self.paint.keep; + if !k.on || !k.clean[i] { + return None; + } + let o = k.old[i] as usize; + let r = k.prev[o]; + let end = k.end[i] as usize; + if !r.keep || r.inh != inh || r.end as usize - o != end - i { + return None; + } + if cfg!(debug_assertions) { + // Checked as one: what it holds paints as it does, inside it. + let (a, b) = self.paint.keep.verify_span; + if !(a..b).contains(&i) { + self.paint.keep.verify[i] = o as u32; + self.paint.keep.verify_span = (i, end); + self.paint.keep.kept += end - i; + } + return None; + } + self.keep_copy(i, o, end, glyph_count); + Some(end - i) + } + + fn keep_copy(&mut self, i: usize, o: usize, end: usize, glyph_count: &mut usize) { + let k = &mut self.paint.keep; + k.open.pop(); + let r = k.prev[o]; + let range = |a: [u32; 2]| a[0] as usize..a[1] as usize; + let at = [self.instances.len(), self.hit.hits.len(), self.hit.overlay_hits.len(), k.pages.len()]; + self.instances.extend_from_slice(&k.instances[range(r.inst)]); + if self.track_marks { + self.marks.resize(at[0], 0); + self.marks.extend_from_slice(&k.marks[range(r.inst)]); + } + self.hit.hits.extend_from_slice(&k.hits[range(r.hits)]); + let at_wheel = self.hit.wheel_hits.len(); + self.hit.wheel_hits.extend_from_slice(&k.wheel[range(r.wheel)]); + self.hit.overlay_hits.extend_from_slice(&k.overlay[range(r.overlay)]); + let seq = |s: usize| s + at[1] - r.hits[0] as usize; + let (at_help, at_drop) = (self.hit.help_hits.len(), self.hit.drop_hits.len()); + self.hit.help_hits.extend(k.help[range(r.help)].iter().map(|&(id, rect, s, l)| (id, rect, seq(s), l))); + self.hit.drop_hits.extend(k.drop[range(r.drop)].iter().map(|&(id, rect, s)| (id, rect, seq(s)))); + let pages = range(r.pages); + k.pages.extend_from_slice(&k.prev_pages[pages.clone()]); + for &(page, texels) in &k.prev_pages[pages] { + self.text.touch_quad(page, texels); + } + *glyph_count += (r.glyphs[1] - r.glyphs[0]) as usize; + let len = end - i; + self.paint.drawn[i..end].copy_from_slice(&k.drawn[o..o + len]); + self.paint.drawn_scale[i..end].copy_from_slice(&k.drawn_scale[o..o + len]); + self.paint.seen[i..end].copy_from_slice(&k.seen[o..o + len]); + self.paint.inh_scratch[i..end].copy_from_slice(&k.inh[o..o + len]); + if self.tree.has_sticky { + self.scroll.sticky_frame[i..end].copy_from_slice(&k.sticky_frame[o..o + len]); + } + // Records for the next paint, as if it had painted them here. + let shift = |a: [u32; 2], from: u32, to: usize| a.map(|v| v - from + to as u32); + let glyphs = *glyph_count as u32 - (r.glyphs[1] - r.glyphs[0]); + for d in 0..len { + let p = k.prev[o + d]; + k.recs[i + d] = PaintRec { + end: p.end - o as u32 + i as u32, + inst: shift(p.inst, r.inst[0], at[0]), + hits: shift(p.hits, r.hits[0], at[1]), + wheel: shift(p.wheel, r.wheel[0], at_wheel), + overlay: shift(p.overlay, r.overlay[0], at[2]), + help: shift(p.help, r.help[0], at_help), + drop: shift(p.drop, r.drop[0], at_drop), + pages: shift(p.pages, r.pages[0], at[3]), + glyphs: shift(p.glyphs, r.glyphs[0], glyphs as usize), + ..p + }; + } + k.kept += len; + } + + /// Node `i` painted itself (not yet its children): what it emitted, and what painting it + /// found, say whether it can be copied. + pub(in crate::runtime) fn keep_painted(&mut self, i: usize, painted_ok: bool) { + let k = &mut self.paint.keep; + if !k.recording { return; } + let start = k.recs[i].inst[0] as usize; + let mut ok = painted_ok; + for q in &self.instances[start..] { + let kind = q.params[1]; + if kind == KIND_IMAGE || kind == KIND_EFFECT || kind == crate::render::KIND_BACKDROP_BLUR || (kind == KIND_GLYPH && q.radii[3] > 0.0) { + ok = false; + } else if kind == KIND_GLYPH { + let (page, texels) = (q.params[2] as u16, (q.rect[2] * if q.radii[0] == 1.0 { 3.0 } else { 1.0 } * q.rect[3]) as u32); + let from = k.recs[i].pages[0] as usize; + match k.pages[from..].iter_mut().find(|p| p.0 == page) { + Some(p) => p.1 += texels, + None => k.pages.push((page, texels)), + } + } + } + k.recs[i].keep &= ok; + } + + /// Closes the records of the open subtrees node `next`'s parent isn't inside (all of them + /// for None), with the layers they opened. + pub(in crate::runtime) fn keep_close(&mut self, parent: Option<Option<usize>>, layers: &mut Vec<(usize, usize, usize)>, active_cache: &mut Option<ActiveCache>, glyph_count: &mut usize) { + if !self.paint.keep.recording { return; } + while let Some(&r) = self.paint.keep.open.last() { + if let Some(Some(p)) = parent && r <= p { + break; + } + while let Some(&(owner, start, surface_start)) = layers.last() { + if owner < r { break; } + layers.pop(); + let before = self.instances.len(); + if active_cache.is_some_and(|ac| ac.instance_start == start) { + let ac = active_cache.take().unwrap(); + self.paint.close_cached_layer(&self.tree.nodes, &mut self.instances, &mut self.surfaces, &mut self.marks, self.track_marks, &mut self.text, self.commit.commit_gen(), ac, start, surface_start, glyph_count); + } else { + crate::render::end_layer(&mut self.instances, &mut self.surfaces, &mut self.marks, start, surface_start); + } + // A scope folded into its one primitive took its marker out: what its subtree + // recorded after the marker moved down one. + if self.instances.len() < before { + for rec in &mut self.paint.keep.recs[owner + 1..] { + for v in rec.inst.iter_mut() { + if *v as usize > start { *v -= 1; } + } + } + } else if self.instances.len() != before + 1 { + // A cached scope elided or replaced what it drew. + self.paint.keep.recs[owner].keep = false; + } + } + self.paint.keep.open.pop(); + let (help, drop) = (self.hit.help_hits.len() as u32, self.hit.drop_hits.len() as u32); + let k = &mut self.paint.keep; + let rec = &mut k.recs[r]; + (rec.help[1], rec.drop[1]) = (help, drop); + rec.inst[1] = self.instances.len() as u32; + rec.hits[1] = self.hit.hits.len() as u32; + rec.wheel[1] = self.hit.wheel_hits.len() as u32; + rec.overlay[1] = self.hit.overlay_hits.len() as u32; + rec.pages[1] = k.pages.len() as u32; + rec.glyphs[1] = *glyph_count as u32; + let keep = rec.keep; + if let Some(p) = self.tree.nodes[r].parent { k.recs[p].keep &= keep; } + if cfg!(debug_assertions) && self.paint.keep.verify.get(r).is_some_and(|&o| o != NONE) { + self.keep_check(r); + } + } + } + + + /// The end of a paint: what was moved is painted, and what wasn't kept is said. + pub(in crate::runtime) fn keep_end(&mut self) { + self.paint.close_slide(self.instances.len(), self.env.scale); + let k = &mut self.paint.keep; + k.moved.clear(); + if !k.recording { + k.recs.clear(); + return; + } + // Subtree ends, from the tree: a record holds one past its subtree. + let n = self.tree.nodes.len(); + let open = &mut k.open; + debug_assert!(open.is_empty(), "paint closed every subtree"); + for i in 0..n { + let parent = self.tree.nodes[i].parent; + while let Some(&r) = open.last() && parent.is_none_or(|p| r > p) { + k.recs[r].end = i as u32; + open.pop(); + } + open.push(i); + } + for r in open.drain(..) { k.recs[r].end = n as u32; } + k.moved.clear(); + if logging() { + eprintln!("rune: paint keep: {} of {} nodes copied (on: {}; unfit {}, new {}, moved {}, rebuilt {}, rows {}, as they were {})", k.kept, n, k.on, k.why[0], k.why[1], k.why[2], k.why[3], k.why[4], k.why[5]); + k.why = [0; 6]; + } + } + + /// Debug builds: subtree `r` painted what its copy from the last paint would have. + fn keep_check(&mut self, r: usize) { + let k = &self.paint.keep; + let o = k.verify[r] as usize; + let (now, was) = (k.recs[r], k.prev[o]); + let range = |a: [u32; 2]| a[0] as usize..a[1] as usize; + let bytes = bytemuck::cast_slice::<Instance, u8>; + let mut differ = Vec::new(); + if bytes(&self.instances[range(now.inst)]) != bytes(&k.instances[range(was.inst)]) { differ.push("instances"); } + if self.hit.hits[range(now.hits)] != k.hits[range(was.hits)] { differ.push("hits"); } + if self.hit.wheel_hits[range(now.wheel)] != k.wheel[range(was.wheel)] { differ.push("wheel hits"); } + // Rebased hits compared in place, as the bytes are: a debug frame's check allocates nothing. + let help = |v: &[(NodeId, [f32; 4], usize, Option<usize>)], from: u32, at: usize| { let (id, rect, s, l) = v[at]; (id, rect, s - from as usize, l) }; + let (a, b) = (&self.hit.help_hits[range(now.help)], &k.help[range(was.help)]); + if a.len() != b.len() || (0..a.len()).any(|j| help(a, now.hits[0], j) != help(b, was.hits[0], j)) { differ.push("help hits"); } + let drop = |v: &[(NodeId, [f32; 4], usize)], from: u32, at: usize| { let (id, rect, s) = v[at]; (id, rect, s - from as usize) }; + let (a, b) = (&self.hit.drop_hits[range(now.drop)], &k.drop[range(was.drop)]); + if a.len() != b.len() || (0..a.len()).any(|j| drop(a, now.hits[0], j) != drop(b, was.hits[0], j)) { differ.push("drop hits"); } + if self.track_marks && self.marks.get(range(now.inst)) != k.marks.get(range(was.inst)) { differ.push("marks"); } + let len = k.end[r] as usize - r; + if self.paint.drawn[r..r + len] != k.drawn[o..o + len] || self.paint.drawn_scale[r..r + len] != k.drawn_scale[o..o + len] || self.paint.seen[r..r + len] != k.seen[o..o + len] { differ.push("drawn rects"); } + if (0..len).any(|d| inh_key(&self.paint.inh_scratch[r + d]) != inh_key(&k.inh[o + d])) { differ.push("inherited state"); } + if self.tree.has_sticky && self.scroll.sticky_frame[r..r + len] != k.sticky_frame[o..o + len] { differ.push("sticky frames"); } + if self.hit.overlay_hits[range(now.overlay)] != k.overlay[range(was.overlay)] { differ.push("overlay hits"); } + if now.glyphs[1] - now.glyphs[0] != was.glyphs[1] - was.glyphs[0] { differ.push("glyph count"); } + if k.pages[range(now.pages)] != k.prev_pages[range(was.pages)] { differ.push("atlas pages"); } + if !differ.is_empty() { + eprintln!("rune: paint keep: {} would have copied what differs: {}", self.tree.nodes[r].path, differ.join(", ")); + } + } +} + +#[path = "cycle.rs"] +pub(super) mod cycle; +#[path = "slide.rs"] +mod slide; + +/// `now` with room for as much as `was` holds room for. +fn twin<T>(now: &mut Vec<T>, was: &Vec<T>) { + if now.capacity() < was.capacity() { + now.reserve_exact(was.capacity() - now.len()); + } +} + +/// The per-node rows paint reads besides the node. +fn own_key(rt: &RuntimeCore, i: usize) -> u64 { + let mut h = rune_motion::Fx::default(); + bits(&mut h, &[rt.paint.row_dy[i], rt.paint.row_h[i], rt.paint.row_mask[i]]); + h.write_u8((rt.tree.has_dissolve && rt.paint.dissolve_scratch.get(i).copied().unwrap_or(false)) as u8); + h.finish() +} + +/// What a node's own fields say: paint reads nothing for it that changes without a new epoch +/// or a scene value. +fn static_ok(n: &Node) -> bool { + n.input.is_none() && !n.ime_cursor && n.scroll.is_none() && n.looping.is_none() && n.live.is_empty() + && n.vis.surface.is_none() && n.material.is_none() && !n.vis_flags.cache() && !n.vis_flags.raise() + && n.vis.backdrop_blur <= 0.0 && n.vis.effect.is_none() && n.vis.pixels.is_none() + && n.sticky.is_none() && n.above.is_none() && n.matched.is_none() + && n.static_scale == 1.0 && !n.scale_track && n.vis.mark == 0 + && n.text.as_ref().is_none_or(|t| t.cold.links.is_empty() && t.cold.live.is_none() && t.cold.advance_in.is_none()) +} + +/// What the runtime holds for a node besides it: selection, marks, reveals, loops, scales +/// settling and folds. +fn dynamic_ok(rt: &RuntimeCore, i: usize, sel: &[(usize, usize, usize)], marks: &[(usize, usize, usize)]) -> bool { + let id = rt.tree.nodes[i].id; + !sel.iter().any(|r| r.0 == i) && !marks.iter().any(|r| r.0 == i) + && !rt.motion.reveal_fading(id) + && !rt.motion.has_loop(id) + && (rt.paint.static_scales.is_empty() || !rt.paint.static_scales.contains_key(&id)) + && rt.paint.row_mask[i] < 0.0 +} diff --git a/app/vendor/rune/crates/rune/src/runtime/paint/pixel_snap.rs b/app/vendor/rune/crates/rune/src/runtime/paint/pixel_snap.rs new file mode 100644 index 0000000..1c7dcbb --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/paint/pixel_snap.rs @@ -0,0 +1,633 @@ +//! Paint-time pixel snapping (`El::pixel_snap`). Layout stays fractional; only where a box's +//! fill, border and clips land on the device grid changes, so a 1.1 pt gap at 2× still draws +//! hard edges. +//! +//! Edges snap, not origin plus size: each of a box's four edges rounds to the nearest device +//! pixel, so two boxes that share an edge round it the same way and meet with no seam or +//! overlap. A box at least half a pixel across keeps at least one pixel; a thinner one keeps +//! its exact edges on that axis rather than vanish. +//! +//! Motion: a moving box's edges are corrected toward the rounding of where it comes to rest +//! (every track at its target), not of where it is, so it glides at full sub-pixel precision +//! with no stepping. When the rest changes, each edge eases from the correction it drew with +//! at that moment to the new rest's, in proportion to how far it has left to travel, so a +//! motion starts where the box was and its last frame is the snapped resting rect: no jump at +//! either end. Boxes that move together share their progress, so a child keeps its place +//! against its parent's edges as both glide. Translations that are not animation tracks +//! (scroll offsets, sticky shifts, rows growing above) move a whole subtree together: they snap +//! as one rounded translation, so the rows of a scrolling list stay crisp and keep their +//! spacing every frame. A scaled subtree doesn't snap while the scale moves its edges by a +//! pixel or more; over the last pixel of a scale settling at 1 the snap fades in, so it lands +//! without a jump either. Turned subtrees don't snap. +//! +//! Scaled layers: a node with its own scale (a zoomed canvas, a pressed button) heads a layer, +//! and its subtree snaps against the grid where the scale puts it once the layer holds still. +//! While the layer moves (a zoom, a pinch, a spring), its content draws at its exact sub-pixel +//! edges, except that each box lets go of its resting correction over the first pixel that box +//! moves, so content at the pivot stays put. Once the layer holds still the correction to the +//! grid eases in over [`SETTLE`], so a zoom ends with no pop. Nothing depends on where a box +//! sits against the pivot: whether the layer moves is how far it moves points of the window, +//! and how near its scale is to 1 is one value for the whole layer, how far the scale moves the +//! layer's edges. Two layers that draw a point in the same place snap it alike, wherever each +//! is anchored, except while a scale is within a pixel of 1, where each lands on the unscaled +//! grid. +//! +//! Centring: a box whose resting edges sit centred in its parent's on an axis keeps equal +//! whole-pixel gaps to its parent's resting rounding there, and gives up to a pixel of its size +//! for it, as a 16 pt knob in a 20 pt track at 1.25× can't sit 2.5 px from each edge on whole +//! pixels. The gap rounds by size, not position, so the same control draws alike wherever it +//! sits. It is decided at rest, so a glide eases into and out of it. + +use std::collections::HashMap; + +use rune_motion::{NodeId, Presented, Rect}; + +/// How far each edge of a moving node is from where it comes to rest (device px), and that +/// resting rect (points), which keys its glide. +#[derive(Clone, Copy)] +pub(in crate::runtime) struct Motion { + by: [f32; 4], + rest: [f32; 4], + /// The scale `by` is drawn at: 1 for the unscaled rect, a layer's scale for the drawn one. + k: f32, +} + +/// `p`'s motion toward `rest`, the rect the scene gives while the node is moving. An anchored +/// element is placed from its anchor, not its frame, so its frame's motion doesn't move it; a +/// growth row draws its bottom edge at its top plus its current height. +pub(in crate::runtime) fn motion(p: &Presented, rest: Option<Rect>, s: f32, anchored: bool, growth_row: bool) -> Option<Motion> { + let rest = rest.filter(|_| !anchored)?; + let (a, b) = (p.rect.edges(), rest.edges()); + let mut by: [f32; 4] = core::array::from_fn(|k| (a[k] - b[k]) * s); + if growth_row { + by[3] = by[1]; + } + Some(Motion { by, rest: b, k: 1.0 }) +} + +/// How far a gliding box's top (device px) sits below its nearest whole pixel: its glyphs lay +/// out from that pixel (moved by the fraction its resting box sits off the grid, as at rest) and +/// move down by this ([`crate::text::TextSystem::set_glide`]), so they keep their place against +/// the box instead of stepping a pixel at a time, and its last frame lays out as rest does. +pub(in crate::runtime) fn text_glide(top: f32) -> f32 { + let g = top - top.round(); + if g.abs() < 1.0 / 64.0 { 0.0 } else { g } +} + +/// One moving node's glide: its edges' corrections go from `from` to `to` (the resting rect's +/// rounding) as their motion goes from `span` to 0. +#[derive(Clone, Copy)] +struct Glide { + rest: [f32; 4], + k: f32, + /// Resting edges in device px, less the rigid translation. + rest_px: [f32; 4], + from: [f32; 4], + to: [f32; 4], + span: [f32; 4], + seen: u32, + /// The parent's glide left and resting edges last frame, which edges with no span follow. + follow: [f32; 4], + parent: [f32; 4], +} + +impl Glide { + /// Edge `k`'s correction with `m` px left to travel. Past the start (a retarget that carries + /// it further away) it holds the starting correction. + fn at(&self, k: usize, to: f32, m: f32, follow: f32) -> f32 { + to + (self.from[k] - to) * self.left(k, m, follow) + } + + /// How much of edge `k`'s glide is left, 1 to 0. An edge that doesn't move goes with its + /// parent's (`follow`), so its centring eases as the parent's edges glide around it. + fn left(&self, k: usize, m: f32, follow: f32) -> f32 { + if self.span[k].abs() > 1.0 / 64.0 { (m / self.span[k]).clamp(-1.0, 1.0) } else { follow } + } +} + +/// What a node hands its subtree for snapping. +#[derive(Clone, Copy, Default)] +pub(in crate::runtime) struct Inherit { + /// `El::pixel_snap(false)` above, or a turn: this subtree draws at its exact edges. + pub off: bool, + /// The translation in points from scrolls, sticky shifts and growth rows above, which + /// snaps as a whole. + pub rigid: [f32; 2], + /// `rigid` less the scrolls' offsets, the sticky shifts and the growth offsets (`row_dy`: rows' + /// and stacks' windows'): the paint containments' origins alone (overlays start it again at + /// zero). A text lays out from its exact place against this, so while rows glide or a list + /// scrolls it moves in whole pixels with its box, as one piece with the lines and borders + /// beside it, and at rest it sits against its box the same way wherever the list is. + pub steady: [f32; 2], + /// The origin in points of the paint containment above (`El::paint_contained`), which is + /// part of `rigid`: what draws from its own exact box rounds against it too. + pub contain: [f32; 2], + /// `El::motion_snaps` here or above: a moving box snaps where it is each frame. + pub steps: bool, + /// An `El::offset` here or above comes to rest away from zero: a translation, as a CSS + /// transform is, which moves a text with its box rather than laying it out again from its + /// exact place (`LeafBox::exact_off` is zero under it). + pub shifted: bool, + /// The nearest scaled layer above or here, as an index into this frame's layers plus one + /// (0: none). + pub layer: u32, + /// The parent's edges, for centring. None when it paints nothing to centre against, its + /// children don't share its rigid translation, or it doesn't snap on the plain grid. + pub parent: Option<Parent>, +} + +impl Inherit { + /// A translation that moves the subtree as a scroll does, `by` points on `axis`: a scroll's + /// drawn offset, a sticky shift (which, while stuck, cancels the scroll's motion), or a page's + /// band. It moves the subtree's boxes, which round it with the rest of `rigid`, and not what + /// its text lays out against, so text moves in whole pixels with its box, as Chromium draws a + /// scroller's contents from its pixel-snapped offset. + pub(in crate::runtime) fn scroll(&mut self, axis: usize, by: f32) { + self.rigid[axis] += by; + } + + /// A growth offset `dy`: a row's, which glides, or a stack's own, its virtual window's, which + /// moves as a scroll does. Either moves its boxes but not what its text lays out against. + pub(in crate::runtime) fn grow(&mut self, dy: f32) { + self.rigid[1] += dy; + } + + /// `El::paint_contained` at `o` (points): its children snap against it, rounded on its own. + pub(in crate::runtime) fn contain_at(&mut self, o: [f32; 2]) { + let c = self.contain; + self.rigid = [self.rigid[0] - c[0] + o[0], self.rigid[1] - c[1] + o[1]]; + self.steady = [self.steady[0] - c[0] + o[0], self.steady[1] - c[1] + o[1]]; + self.contain = o; + } + + /// Its bits, for `paint_keep`'s comparison of what a subtree inherits. + pub(in crate::runtime) fn hash_bits(&self, h: &mut impl std::hash::Hasher) { + h.write_u8(self.off as u8); + h.write_u8(self.shifted as u8); + for v in self.rigid.iter().chain(&self.steady).chain(&self.contain) { h.write_u32(v.to_bits()); } + h.write_u32(self.layer); + match &self.parent { + Some(p) => { + h.write_u8(1); + for v in p.rest.exact.iter().chain(&p.rest.at).chain(&p.now.exact).chain(&p.now.at).chain(&p.left) { h.write_u32(v.to_bits()); } + } + None => h.write_u8(0), + } + } +} + +/// A box's edges (device px, less its rigid translation): `exact`, and `at` where it draws them. +#[derive(Clone, Copy, Debug, PartialEq)] +pub(in crate::runtime) struct Rest { + exact: [f32; 4], + at: [f32; 4], +} + +/// A box's edges where it comes to rest, which its children centre against, where it is now, +/// which a child that starts to glide measures the correction it drew with against, and how +/// much of each edge's glide is left. +#[derive(Clone, Copy, Debug, PartialEq)] +pub(in crate::runtime) struct Parent { + rest: Rest, + now: Rest, + left: [f32; 4], +} + +impl Parent { + /// How far its exact resting top-left sits from where it rests snapped (device px), `rigid` + /// as it was snapped with: where a text inside lays out from, at rest and through a glide alike. + pub(in crate::runtime) fn exact_off(&self, rigid: [f32; 2]) -> [f32; 2] { + core::array::from_fn(|a| self.rest.exact[a] + rigid[a] - self.rest.at[a] - round(rigid[a])) + } +} + +/// The glides of the nodes moving now and the scaled layers, owned by the runtime. +#[derive(Default)] +pub(in crate::runtime) struct Glides { + glides: HashMap<NodeId, Glide>, + layers: HashMap<NodeId, Layer>, + /// This frame's layers, which `Inherit::layer` indexes from 1. + now: Vec<LayerSnap>, + frame: u32, + t: f64, + /// The window (device px). + size: [f32; 2], + /// A layer's correction still has a visible way to go. + easing: bool, +} + +/// Frames a glide outlives its node's last paint (a cached subtree, a removed node). +const KEEP: u32 = 120; + +/// Seconds a still scaled layer's correction to the grid takes to ease in. +pub(in crate::runtime) const SETTLE: f64 = 0.1; + +/// A node with its own scale, which heads a scaled layer. +#[derive(Clone, Copy)] +struct Layer { + /// Its drawn rect (device px, less its rigid translation) last frame. + rect: [f32; 4], + seen: u32, + phase: LayerPhase, + /// Rests it has left, each its rect there and the weight its correction was drawn with + /// when the layer left it: the two heaviest, fading out. + outs: [([f32; 4], f32); 2], +} + +/// Whether a scaled layer moves or holds, and since when. +#[derive(Clone, Copy, Debug, PartialEq)] +enum LayerPhase { + /// It moved, last at `last`: no correction to the grid. + Moving { last: f64 }, + /// It holds where it came to rest at `since`, its correction easing in over `SETTLE`. + Rest { since: f64 }, +} + +/// A scaled layer's snapping this frame, handed down its subtree. +#[derive(Clone, Copy)] +struct LayerSnap { + /// Weight of the snap where the layer is now: 0 while it moves, easing to 1 once it holds. + to: f32, + /// Weight of the snap to the unscaled grid: 1 while the scale moves the layer's edges by + /// no more than 1/16 px, fading out over the pixel before, so a scale settling at 1 lands + /// without a jump. + near: f32, + /// The corrections drawn at rests the layer left, fading out: each maps a device px + /// coordinate now to where it was at that rest (`x * a + b` per axis), with its weight. + outs: [([f32; 4], f32); 2], + /// The layer's rigid translation (device px). + rigid: [f32; 2], +} + +const IDENTITY: [f32; 4] = [1.0, 0.0, 1.0, 0.0]; + +const NO_LAYER: LayerSnap = LayerSnap { to: 0.0, near: 0.0, outs: [(IDENTITY, 0.0); 2], rigid: [0.0; 2] }; + +/// The largest distance between matching edges. +fn far(a: [f32; 4], b: [f32; 4]) -> f32 { + (0..4).map(|k| (a[k] - b[k]).abs()).fold(0.0, f32::max) +} + +/// The map `x * a + b` per axis that takes `from`'s edges to `to`'s. +fn affine(from: [f32; 4], to: [f32; 4]) -> [f32; 4] { + let mut map = IDENTITY; + for a in 0..2 { + let (w, to_w) = (from[a + 2] - from[a], to[a + 2] - to[a]); + let k = if w.abs() > 1e-3 { to_w / w } else { 1.0 }; + (map[a * 2], map[a * 2 + 1]) = (k, to[a] - from[a] * k); + } + map +} + +/// How far `map` moves a point of a window `size` across at most (device px). +fn reach(map: [f32; 4], size: [f32; 2]) -> f32 { + (0..2).map(|a| map[a * 2 + 1].abs().max(((map[a * 2] - 1.0) * size[a] + map[a * 2 + 1]).abs())).fold(0.0, f32::max) +} + +impl Glides { + /// Called once before each paint pass, at animation time `t`, in a window `size` across + /// (device px). + pub(in crate::runtime) fn begin_frame(&mut self, t: f64, size: [f32; 2]) { + self.frame = self.frame.wrapping_add(1); + (self.t, self.size) = (t, size); + self.now.clear(); + self.easing = false; + let frame = self.frame; + if !self.glides.is_empty() { + self.glides.retain(|_, g| frame.wrapping_sub(g.seen) < KEEP); + } + if !self.layers.is_empty() { + self.layers.retain(|_, l| frame.wrapping_sub(l.seen) < KEEP); + } + } + + /// Whether a scaled layer's correction is still easing in or out: the last paint asks for + /// another frame. + pub(in crate::runtime) fn easing(&self) -> bool { + self.easing + } + + /// Node `id` has its own scale and heads a layer: `r` is its drawn rect and `unscaled` the + /// same rect before the scales on it and above it (device px edges), and `rigid` its rigid + /// translation (device px). `cached` content snaps without easing, as its raster isn't + /// redrawn while the correction eases. The returned index goes in `Inherit::layer`. + pub(in crate::runtime) fn layer(&mut self, id: NodeId, (r, unscaled): ([f32; 4], [f32; 4]), rigid: [f32; 2], cached: bool) -> u32 { + let cur: [f32; 4] = core::array::from_fn(|k| r[k] - rigid[k % 2]); + let (t, frame, size) = (self.t, self.frame, self.size); + let l = self.layers.entry(id).or_insert(Layer { rect: cur, seen: frame, phase: LayerPhase::Rest { since: f64::NEG_INFINITY }, outs: [(cur, 0.0); 2] }); + let eased = |since: f64| { + let x = if cached { 1.0 } else { ((t - since) / SETTLE).clamp(0.0, 1.0) as f32 }; + x * x * (3.0 - 2.0 * x) + }; + let to; + if reach(affine(l.rect, cur), size) > 1.0 / 256.0 { + if let LayerPhase::Rest { since } = l.phase { + // It drew `f` of this rest's correction, and `1 - f` of what the rests before it + // still drew. + let f = eased(since); + let [a, b] = l.outs.map(|(rest, w)| (rest, w * (1.0 - f))); + let mut outs = [(l.rect, f), a, b]; + outs.sort_by(|x, y| y.1.total_cmp(&x.1)); + l.outs = [outs[0], outs[1]]; + } + (l.rect, l.phase) = (cur, LayerPhase::Moving { last: t }); + to = 0.0; + } else { + let since = match l.phase { + // Still since its last paint, which already drew it here. + LayerPhase::Moving { last } => last, + LayerPhase::Rest { since } => since, + }; + l.phase = LayerPhase::Rest { since }; + to = eased(since); + if to == 1.0 { + l.outs = [(cur, 0.0); 2]; + } + } + l.seen = frame; + let outs = l.outs.map(|(rest, w)| if w > 0.0 { (affine(cur, rest), w * (1.0 - to)) } else { (IDENTITY, 0.0) }); + let near = ((1.0 - far(r, unscaled)) / (1.0 - 1.0 / 16.0)).clamp(0.0, 1.0); + self.now.push(LayerSnap { to, near, outs, rigid }); + self.now.len() as u32 + } + + /// Node `id` is at rest and unscaled: its paint rect `r` (device px edges) snapped, with + /// `rigid` from `Inherit::rigid` in device px and `parent` from `Inherit::parent`, and its + /// resting edges for its children. + #[inline] + pub(in crate::runtime) fn at_rest(&mut self, id: NodeId, r: [f32; 4], rigid: [f32; 2], parent: Option<Parent>) -> ([f32; 4], Option<Parent>) { + // Centred in a parent that still glides, it goes with the parent's glide. + let gliding = |p: &Parent| p.left != [0.0; 4] && (0..2).any(|a| resting(p.rest, a, (r[a] - rigid[a], r[a + 2] - rigid[a])).is_some()); + if let Some(p) = parent.filter(gliding) { + let (out, parent) = self.glide(id, Motion { by: [0.0; 4], rest: r, k: 1.0 }, r, rigid, Some(p)); + return (out, Some(parent)); + } + if !self.glides.is_empty() { + self.glides.remove(&id); + } + let (out, rest) = snap(r, [0.0; 4], rigid, parent.map(|p| p.rest), |_, c| c); + (out, Some(Parent { rest, now: rest, left: [0.0; 4] })) + } + + /// Node `id`'s paint rect `r` (device px edges) snapped. `unscaled` is the same rect before + /// the scales on it and above it, `motion` from [`motion`], and `rigid` and `parent` as in + /// [`Self::at_rest`]. `layer` is `Inherit::layer` and `sc` the node's scale. Its resting + /// edges come back only where it snaps on the plain grid. + pub(in crate::runtime) fn snapped(&mut self, id: NodeId, motion: Option<Motion>, (r, unscaled): ([f32; 4], [f32; 4]), rigid: [f32; 2], (layer, sc): (u32, f32), parent: Option<Parent>) -> ([f32; 4], Option<Parent>) { + // Snapping to the unscaled grid fades in over the last pixel scaling moves the edges, so + // a scale settling at 1 lands on the grid without a jump. In a layer that is how far + // its scale moves the layer's edges, the same for every box in it. + let l = layer.checked_sub(1).map_or(NO_LAYER, |i| self.now[i as usize]); + let weight = if layer == 0 { ((1.0 - far(r, unscaled)) / (1.0 - 1.0 / 16.0)).clamp(0.0, 1.0) } else { l.near }; + let mut out = r; + let plain = layer == 0 && weight >= 1.0; + let parent = parent.filter(|_| plain); + let mut rest = None; + if weight > 0.0 && l.to < 1.0 { + let (snapped, at) = match motion { + None => self.at_rest(id, unscaled, rigid, parent), + Some(m) if l.to == 0.0 => { + let (out, at) = self.glide(id, m, unscaled, rigid, parent); + (out, Some(at)) + } + Some(m) => (snap(unscaled, m.by, rigid, None, |_, c| c).0, None), + }; + rest = at.filter(|_| plain); + for k in 0..4 { + out[k] += (snapped[k] - r[k]) * weight * (1.0 - l.to); + } + } + if layer == 0 { + return (out, rest); + } + // Translations inside the layer are scaled with it. + let lr = l.rigid; + let rigid: [f32; 2] = core::array::from_fn(|a| lr[a] + (rigid[a] - lr[a]) * sc); + let mut left = 0.0f32; + for (map, w) in l.outs { + if w <= 0.0 || weight >= 1.0 { + continue; + } + let m: [f32; 4] = core::array::from_fn(|k| { + let a = k % 2; + (r[k] - lr[a]) * map[a * 2] + map[a * 2 + 1] + lr[a] + }); + // Each box lets go of it over the first pixel it moves from that rest. + let w = w * (1.0 - weight) * (1.0 - far(r, m)).clamp(0.0, 1.0); + let (at, _) = snap(m, [0.0; 4], rigid, None, |_, c| c); + for k in 0..4 { + let c = (at[k] - m[k]) * w; + out[k] += c; + left = left.max(c.abs()); + } + } + let at = match motion { + Some(m) if l.to > 0.0 => self.glide(id, Motion { by: m.by.map(|v| v * sc), k: sc, ..m }, r, rigid, None).0, + _ if l.to > 0.0 => self.at_rest(id, r, rigid, None).0, + // Moving: where holding still would take it, to know if it has anywhere to go. + _ => snap(r, [0.0; 4], rigid, None, |_, c| c).0, + }; + if l.to == 1.0 { + return (at, None); + } + for k in 0..4 { + out[k] += (at[k] - r[k]) * l.to; + left = left.max((at[k] - r[k]).abs() * (1.0 - l.to)); + } + self.easing |= left > 1.0 / 128.0; + (out, None) + } + + fn glide(&mut self, id: NodeId, m: Motion, r: [f32; 4], rigid: [f32; 2], parent: Option<Parent>) -> ([f32; 4], Parent) { + let free: [f32; 4] = core::array::from_fn(|k| r[k] - rigid[k % 2]); + let (follow, parent_rest) = parent.map_or(([0.0; 4], [0.0; 4]), |p| (p.left, p.rest.exact)); + let mut g = match self.glides.get(&id) { + Some(g) if g.rest == m.rest && g.k == m.k => { + let mut g = *g; + if g.parent != parent_rest { + // The parent retargets and starts its glide over: an edge that follows it + // starts over from what it drew. + for k in (0..4).filter(|&k| g.span[k].abs() <= 1.0 / 64.0) { + g.from[k] = g.at(k, g.to[k], 0.0, g.follow[k]); + } + } + g + } + prev => { + // A new rest: start from the correction drawn with now, so nothing jumps. + let from = match prev { + Some(g) => core::array::from_fn(|k| g.at(k, g.to[k], free[k] - g.rest_px[k], g.follow[k])), + None => start(r, rigid, parent.map(|p| p.now)), + }; + let rest_px = core::array::from_fn(|k| free[k] - m.by[k]); + Glide { rest: m.rest, k: m.k, rest_px, from, to: from, span: m.by, seen: 0, follow, parent: parent_rest } + } + }; + let (out, rest) = snap(r, m.by, rigid, parent.map(|p| p.rest), |k, c| { + g.to[k] = c; + g.at(k, c, m.by[k], follow[k]) + }); + (g.seen, g.follow, g.parent) = (self.frame, follow, parent_rest); + self.glides.insert(id, g); + let now = Rest { exact: free, at: core::array::from_fn(|k| out[k] - round(rigid[k % 2])) }; + (out, Parent { rest, now, left: core::array::from_fn(|k| g.left(k, m.by[k], follow[k])) }) + } +} + +/// Rounds half up on the device grid, the same way at every position. +fn round(v: f32) -> f32 { + (v + 0.5).floor() +} + +/// `r` (device px edges, `x0, y0, x1, y1`) snapped, and its resting edges. `motion` is how far +/// each edge is from where it comes to rest and `rigid` the translation that snaps as a whole +/// (both device px). On an axis where its rest is centred in `parent`'s, its gaps to the +/// parent's resting rounding match. Each edge's correction toward its resting rounding passes +/// through `ease(edge, correction)`. +#[inline] +pub(in crate::runtime) fn snap(r: [f32; 4], motion: [f32; 4], rigid: [f32; 2], parent: Option<Rest>, mut ease: impl FnMut(usize, f32) -> f32) -> ([f32; 4], Rest) { + let mut out = r; + let mut rest = Rest { exact: [0.0; 4], at: [0.0; 4] }; + // A scaled layer's edges and its scaled rigid translation each land a little off the 1/64 px + // grid, so their difference wobbles by up to 1/128 px frame to frame even while the content + // holds still against the scroll. Back on the grid it holds, and an edge resting on a half + // pixel rounds the same way every frame instead of flickering a pixel. + let grid = |v: f32| (v * 64.0).round() / 64.0; + for axis in 0..2 { + let (a, b) = (axis, axis + 2); + let (rest_a, rest_b) = (grid(r[a] - motion[a] - rigid[axis]), grid(r[b] - motion[b] - rigid[axis])); + (rest.exact[a], rest.exact[b]) = (rest_a, rest_b); + (rest.at[a], rest.at[b]) = (rest_a, rest_b); + if rest_b - rest_a < 0.5 { + continue; + } + let shift = round(rigid[axis]); + let (lo, hi) = parent.and_then(|p| resting(p, axis, (rest_a, rest_b))).unwrap_or_else(|| { + let lo = round(rest_a); + (lo, round(rest_b).max(lo + 1.0)) + }); + (rest.at[a], rest.at[b]) = (lo, hi); + for (k, rest, at) in [(a, rest_a, lo), (b, rest_b, hi)] { + // Built from the rounded edge, so a box at rest lands exactly on whole pixels. + let (c, eased) = (at - rest, ease(k, at - rest)); + out[k] = if eased == c { at } else { rest + eased } + shift + motion[k]; + } + } + (out, rest) +} + +/// Scales a hairline box (`El::hairline`) by half on its thin axis around its midpoint, matching +/// Chromium's `height: 1px; transform: scaleY(0.5)` (or vertical `scaleX(0.5)`): the 1 pt box +/// snaps its origin `r[axis]` and pre-scale extent `round(extent).max(1.0)` to device pixels, +/// then scales `[0, h]` by 0.5 around `0.5 * extent`: +/// - At 1.0x (`extent = 1.0`, `h = 1.0`): `[lo, lo + 1.0]` at 0.50 alpha (exact 0.50 coverage in +/// row `lo`; `KIND_RECT` evaluates `0.5 - sd`, which gives 0.75 on a 0.5 px thin rect). +/// - At 1.5x (`extent = 1.5`, `h = 2.0`): `[lo + 0.375, lo + 1.375]` (0.625 in `lo`, 0.375 in `lo + 1`). +/// - At 2.0x (`extent = 2.0`, `h = 2.0`): `[lo + 0.5, lo + 1.5]` (1.0 device px centred in 2 px). +#[inline] +pub(in crate::runtime) fn hairline(mut r: [f32; 4], exact: [f32; 4]) -> ([f32; 4], f32) { + let (ew, eh) = ((exact[2] - exact[0]).max(0.0), (exact[3] - exact[1]).max(0.0)); + let axis = usize::from(eh <= ew); + let extent = if axis == 1 { eh } else { ew }; + let h = round(extent).max(1.0); + let lo = r[axis]; + if 0.5 * h < 1.0 { + r[axis] = lo; + r[axis + 2] = lo + 1.0; + return (r, 0.5 * h); + } + let pad = 0.25 * extent; + r[axis] = lo + pad; + r[axis + 2] = lo + 0.5 * h + pad; + (r, 1.0) +} + +/// A border's or outline's width, or an outline's offset, `w` device px, snapped as Chromium +/// snaps CSS border and outline widths: under a pixel it draws one whole pixel, above that it +/// floors to whole pixels. So 0.5 pt is one crisp pixel at 1×, 1.25× and 1.5×, and 1 pt is one +/// pixel at 1.25× and 1.5×. Zero stays zero; the sign stays. +pub(in crate::runtime) fn line_width(w: f32) -> f32 { + if w == 0.0 || !w.is_finite() { + return w; + } + // Scene values sit on a 1/64 px grid, so 2.99 px is 3. + (w.abs() + 1.0 / 64.0).floor().max(1.0).copysign(w) +} + +/// Whether a box paints something its children's gaps show against. Elsewhere centring would +/// cost a pixel of size for nothing. +pub(in crate::runtime) fn frames(v: &crate::el::Visual) -> bool { + let border = v.border_width() > 0.0 && (v.border().a > 0.0 || v.border_bottom.is_some()); + v.fill.a > 0.0 || v.hover().a > 0.0 || v.press().a > 0.0 || v.gradient.is_some() || v.radial.is_some() || border +} + +/// The correction a box at rest last frame drew with, now that it starts to glide from `r`: +/// its rounding here, eased toward its centred one over the first pixel it is off centre. +fn start(r: [f32; 4], rigid: [f32; 2], parent: Option<Rest>) -> [f32; 4] { + let mut now = [0.0; 4]; + snap(r, [0.0; 4], rigid, None, |k, c| { + now[k] = c; + c + }); + let Some(p) = parent else { return now }; + for axis in 0..2 { + let (a, b) = (axis, axis + 2); + let (ra, rb) = (r[a] - rigid[axis], r[b] - rigid[axis]); + if rb - ra < 0.5 { + continue; + } + if let Some((lo, hi)) = centred(p, (a, b), (ra, rb), 1.0) { + let w = 1.0 - ((ra - p.exact[a]) - (p.exact[b] - rb)).abs(); + now[a] += (lo - ra - now[a]) * w; + now[b] += (hi - rb - now[b]) * w; + } + } + now +} + +/// Resting edges `lo..hi` on `axis` with equal whole-pixel gaps to `parent`'s resting +/// rounding, if the rest `ra..rb` is centred in the parent's and the parent snaps on that axis. +fn resting(parent: Rest, axis: usize, (ra, rb): (f32, f32)) -> Option<(f32, f32)> { + let (a, b) = (axis, axis + 2); + if parent.at[a].fract() != 0.0 || parent.at[b].fract() != 0.0 { + return None; + } + // Scene rects sit on a 1/64 px grid, so a centred box can be off by twice that. + centred(parent, (a, b), (ra, rb), 1.0 / 16.0) +} + +/// Edges `lo..hi` on the axis of edges `a` and `b` with equal whole-pixel gaps to `parent`'s +/// drawn edges, if `ra..rb` is centred in its exact ones to within `slack` px. +fn centred(parent: Rest, (a, b): (usize, usize), (ra, rb): (f32, f32), slack: f32) -> Option<(f32, f32)> { + let ([pa, pb], [qa, qb]) = ([parent.exact[a], parent.exact[b]], [parent.at[a], parent.at[b]]); + if ((ra - pa) - (pb - rb)).abs() >= slack { + return None; + } + let gap = round((qb - qa - (rb - ra)) / 2.0); + (qb - qa - 2.0 * gap >= 1.0).then_some((qa + gap, qb - gap)) +} + +#[cfg(test)] +mod layer_tests { + use super::*; + + #[test] + fn a_scaled_layer_eases_to_the_grid_from_its_last_move() { + let (id, frame) = (NodeId(1), 1.0 / 60.0); + let mut g = Glides::default(); + let paint = |g: &mut Glides, t: f64, r: [f32; 4]| { + g.begin_frame(t, [800.0, 600.0]); + g.layer(id, (r, r), [0.0; 2], false); + (g.layers[&id].phase, g.now[0].to) + }; + let (a, b) = ([10.3, 10.3, 50.3, 50.3], [12.6, 10.3, 52.6, 50.3]); + assert_eq!(paint(&mut g, 0.0, a), (LayerPhase::Rest { since: f64::NEG_INFINITY }, 1.0), "first seen still: snapped"); + assert_eq!(paint(&mut g, frame, b), (LayerPhase::Moving { last: frame }, 0.0)); + assert_eq!(g.layers[&id].outs[0], (a, 1.0), "the rest it left, at the weight it drew"); + let (phase, to) = paint(&mut g, 2.0 * frame, b); + assert_eq!(phase, LayerPhase::Rest { since: frame }, "at rest from the paint that drew it there"); + assert!(to > 0.0 && to < 1.0, "easing in: {to}"); + assert_eq!(paint(&mut g, frame + 2.0 * SETTLE, b).1, 1.0); + assert_eq!(g.layers[&id].outs[0].1, 0.0, "the old rest let go once settled"); + } +} diff --git a/app/vendor/rune/crates/rune/src/runtime/paint/raster_check.rs b/app/vendor/rune/crates/rune/src/runtime/paint/raster_check.rs new file mode 100644 index 0000000..2ed6362 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/paint/raster_check.rs @@ -0,0 +1,51 @@ +//! `RUNE_RASTER_CHECK=1` (debug builds): on every frame that comes to rest, checks that each +//! glyph and icon draws as one painted for the first time would, and that none draws its atlas +//! mask magnified or shrunk. A mask made for another scale (a cell rasterized before a zoom, a run +//! of text that never left its moving path, an icon rasterized at whole pixels and stretched to a +//! zoom's fractional size) shows soft or blocky beside its neighbours; this names it on stderr. + +use super::*; + +pub(in crate::runtime) fn on() -> bool { + // Read once: a frame at rest asks, and reading the environment allocates on Windows. + static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + cfg!(debug_assertions) && *ON.get_or_init(|| std::env::var_os("RUNE_RASTER_CHECK").is_some_and(|v| v != "0")) +} + +impl RuntimeCore { + /// Paints the frame again with every text's raster path and cached glyph runs forgotten, + /// and reports the glyphs that differ, then any resting glyph that magnifies its mask. + pub(in crate::runtime) fn check_resting_raster(&mut self) { + let settled = glyphs(&self.instances); + self.text.forget_raster_state(); + self.paint.keep.off_once = true; + self.build(); + let fresh = glyphs(&self.instances); + let differ: Vec<_> = settled.iter().zip(&fresh).filter(|(a, b)| a != b).collect(); + if !differ.is_empty() || settled.len() != fresh.len() { + eprintln!("rune: raster check at {:.3} s: {} of {} resting glyphs and icons draw unlike a fresh paint, first:", self.clock, differ.len(), settled.len()); + for (a, b) in differ.iter().take(3) { + eprintln!(" resting {a:?}\n fresh {b:?}"); + } + } + let magnified: Vec<_> = self.instances.iter().filter(|i| magnifies(i)).map(|i| (i.rect, i.uv)).collect(); + if !magnified.is_empty() { + eprintln!("rune: raster check at {:.3} s: {} resting glyphs or icons draw a mask stretched, first (rect, atlas uv) {:?}", self.clock, magnified.len(), &magnified[..magnified.len().min(3)]); + } + } +} + +/// A glyph instance's rect, pen (radii), outline record (border), params and atlas footprint. +type Glyph = ([f32; 4], [f32; 4], [f32; 4], [f32; 4], [f32; 2]); + +fn glyphs(instances: &[Instance]) -> Vec<Glyph> { + instances.iter().filter(|i| i.params[1] == KIND_GLYPH).map(|i| (i.rect, i.radii, i.border, i.params, [i.uv[2], i.uv[3]])).collect() +} + +/// An unturned glyph or icon drawn larger or smaller than its mask, by more than a 256th: at rest +/// both draw their masks 1:1, so even the 1.5% an icon at whole pixels is stretched to at 110% +/// zoom shows here. +fn magnifies(i: &Instance) -> bool { + let texels = if i.radii[0] > 0.5 { 3.0 } else { 1.0 }; + i.params[1] == KIND_GLYPH && i.params[0] == 0.0 && i.uv[2] > 0.0 && (i.rect[2] * texels / i.uv[2] - 1.0).abs() > 1.0 / 256.0 +} diff --git a/app/vendor/rune/crates/rune/src/runtime/paint/shadow.rs b/app/vendor/rune/crates/rune/src/runtime/paint/shadow.rs new file mode 100644 index 0000000..1e0c7eb --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/paint/shadow.rs @@ -0,0 +1,73 @@ +//! Painter-stream instances for an element's outer shadows (`El::box_shadow`). +use super::*; + +/// The box casting the shadows and how they paint, in device pixels. +pub(in crate::runtime) struct Caster { + pub rect: [f32; 4], + /// Circular corner radii; shadows keep circular corners. + pub radii: [f32; 4], + /// The radii the box itself draws with (negative for continuous corners), for `bands`. + pub shape: [f32; 4], + /// Device pixels per point. + pub k_px: f32, + pub scale: f32, + pub opacity: f32, + pub srgb: bool, + pub clip: [f32; 4], + pub fade: [f32; 4], + /// The radius of a hole the shadows leave over the box (negative for continuous corners). + pub hole: Option<f32>, + /// The box paints itself solid, hiding the middle of its shadows (bands.rs). + pub opaque: bool, +} + +/// One outer shadow `sh` in colour `c` (straight alpha) under `cast`. +pub(in crate::runtime) fn push_shadow(out: &mut Vec<Instance>, sh: &crate::el::Shadow, c: Color, cast: &Caster) { + let [x, y, w, h] = cast.rect; + let sp = sh.spread * cast.k_px; + let rect = [x + sh.x * cast.k_px - sp, y + sh.y * cast.k_px - sp, w + 2.0 * sp, h + 2.0 * sp]; + let sradii = cast.radii.map(|v| if v > 0.0 { (v + sp).max(0.0) } else { 0.0 }); + let (clip, fade) = (cast.clip, crate::render::pack_fade(cast.fade, cast.clip, cast.clip)); + let fill = premul(c, cast.opacity, cast.srgb); + let ring = sh.x == 0.0 && sh.y == 0.0; + // A crisp offset copy over a hole draws as the sharpest blurred shadow, which can leave one. + if sh.blur <= 0.0 && (ring || cast.hole.is_none()) { + // A crisp shadow: a ring when it sits exactly around the box, else a solid + // offset copy (hidden under an opaque element, as in CSS). + if ring && sp <= 0.0 { + return; + } + out.push(Instance { + rect, + radii: sradii, + fill: if ring { [0.0; 4] } else { fill }, + border: if ring { fill } else { [0.0; 4] }, + params: [if ring { sp } else { 0.0 }, KIND_RECT, 0.0, 1.0], + uv: [0.0; 4], + clip, + fade, + }); + return; + } + // Over a native material, backdrop blur or dimmed box, the shadow leaves the interior clear: + // `uv` holds the hole relative to the shadow's rect, `radii[3]` its radius. + let (radii, uv) = match cast.hole { + Some(hole) => ([sradii[0], sradii[1], sradii[2], hole], [x - rect[0], y - rect[1], w, h]), + None => (sradii, [0.0; 4]), + }; + let inst = Instance { + rect, + radii, + fill, + border: [0.0; 4], + params: [0.0, KIND_SHADOW, (sh.blur * cast.scale * 0.5).max(0.5), 1.0], + uv, + clip, + fade, + }; + if cast.opaque { + bands::push_shadow(out, inst, cast.rect, cast.shape); + } else { + out.push(inst); + } +} diff --git a/app/vendor/rune/crates/rune/src/runtime/paint/shape.rs b/app/vendor/rune/crates/rune/src/runtime/paint/shape.rs new file mode 100644 index 0000000..aea085f --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/paint/shape.rs @@ -0,0 +1,58 @@ +//! Painter-stream instances for vector shapes (`El::shape`). +use super::*; + +/// Instances for a vector shape whose origin sits at `origin` (device px), with `k` device px per +/// coordinate unit on each axis and `k_px` device px per point for stroke widths. +#[allow(clippy::too_many_arguments)] +pub(in crate::runtime) fn push_shape(out: &mut Vec<Instance>, shape: &Shape, origin: [f32; 2], k: [f32; 2], k_px: f32, opacity: f32, srgb: bool, clip: [f32; 4], fade: [f32; 4]) { + let at = |p: [f32; 2]| [origin[0] + p[0] * k[0], origin[1] + p[1] * k[1]]; + for op in &shape.ops { + match op { + Op::Stroke { points, closed, width, cap, color } => { + let fill = premul(*color, opacity, srgb); + if fill[3] <= 0.0005 { + continue; + } + let hw = width * k_px * 0.5; + let pad = hw.max(0.5) + 1.0; + let n = points.len(); + let count = if *closed { n } else { n - 1 }; + for i in 0..count { + let (a, b) = (at(points[i]), at(points[(i + 1) % n])); + let (x0, y0) = (a[0].min(b[0]) - pad, a[1].min(b[1]) - pad); + out.push(Instance { + rect: [x0, y0, a[0].max(b[0]) + pad - x0, a[1].max(b[1]) + pad - y0], + radii: [a[0], a[1], b[0], b[1]], + fill, + border: [0.0; 4], + params: [hw, KIND_SEGMENT, if *cap == LineCap::Round { 1.0 } else { 0.0 }, 1.0], + uv: [0.0; 4], + clip, + fade: crate::render::pack_fade(fade, clip, clip), + }); + } + } + Op::Fill { points, color } => { + let fill = premul(*color, opacity, srgb); + if fill[3] <= 0.0005 { + continue; + } + for ([ia, ib, ic], aa) in crate::shape::triangulate(points) { + let (a, b, c) = (at(points[ia]), at(points[ib]), at(points[ic])); + let (x0, y0) = (a[0].min(b[0]).min(c[0]), a[1].min(b[1]).min(c[1])); + let (x1, y1) = (a[0].max(b[0]).max(c[0]), a[1].max(b[1]).max(c[1])); + out.push(Instance { + rect: [x0, y0, x1 - x0, y1 - y0], + radii: [a[0], a[1], b[0], b[1]], + fill, + border: [0.0; 4], + params: [aa as f32, KIND_TRIANGLE, 0.0, 1.0], + uv: [c[0], c[1], 0.0, 0.0], + clip, + fade: crate::render::pack_fade(fade, clip, clip), + }); + } + } + } + } +} diff --git a/app/vendor/rune/crates/rune/src/runtime/paint/slide.rs b/app/vendor/rune/crates/rune/src/runtime/paint/slide.rs new file mode 100644 index 0000000..c026d66 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/paint/slide.rs @@ -0,0 +1,376 @@ +//! A loop-only step for a window that slides over content sliding back inside it, as a text +//! shimmer is made (`El::clip_fade` on a `LoopSpec::slide`, whose only child slides the other +//! way): the content stays where it is, so a step moves only the window's clip and its soft +//! edges in the instances under it. The ordinary paint records each such window (`note_slide`), +//! the glyphs under it it drew or left out, and whether each node under it showed. A step that +//! would move the content, show or hide anything, or change what the paint drew there any other +//! way takes an ordinary frame. + +use std::ops::Range; + +use super::*; + +pub(in crate::runtime) struct Slide { + pub(super) window: usize, + pub(super) counter: usize, + /// One past the window's subtree, in node order. + pub(super) end: usize, + pub(super) instances: Range<usize>, + /// The window's anchor (`Anchor`: a rect in points, its ancestors' scale applied, at a slide + /// offset), the offset this paint drew it at, and that offset with its child's, which cancels it. + rect: [f32; 4], + offset: [f32; 2], + /// Its top and bottom (pixels), snapped as a still box's. + y: [f32; 2], + painted: [f32; 2], + net: [f32; 2], + /// The rect's points per offset point (an ancestor's scale), and the display scale. + k: f32, + s: f32, + /// Its laid-out size on the grid, which paint lands a rect's size on. + size: [f32; 2], + /// The clip, fade widths and fade origins it inherits, and its own fade widths (pixels). + outer: [[f32; 4]; 3], + own: [f32; 4], + vp: [f32; 4], + /// Each node under it: where it showed (pixels) and whether it did. + shown: Vec<([f32; 4], bool)>, + /// Each glyph under it (x0, y0, x1, y1) and whether it drew. + pub(super) glyphs: Vec<([f32; 4], bool)>, + /// Its instances are what this record says they are: checked on the first step. + checked: Option<bool>, +} + +/// What a step draws the window's instances with: their clip and packed fade. +type Pose = ([f32; 4], [u32; 4]); + +/// Where a sliding window is posed from, kept across paints while its laid-out place holds: its +/// rect (points) at a slide offset, and the rect's points per offset point, scale and grid size. +/// Paint and a loop-only step both pose the window from it at the offset they draw (`pose_rect`), +/// so the two reach one number for the same offset. Posed from each paint's own rect instead, +/// they would reach it by different float sums (the scene's layout origin plus offset, then the +/// ancestors' translation; against the last paint's rect plus the offset's change), which land a +/// grid step apart where the offset sits on a grid line's half. +#[derive(Clone, Copy, PartialEq)] +pub(in crate::runtime) struct Anchor { + node: rune_motion::NodeId, + rect: [f32; 4], + offset: [f32; 2], + k: f32, + s: f32, + size: [f32; 2], + /// Its top and bottom as paint snapped them (pixels): across the slide it sits where a still + /// box does, on whole pixels, as on every other platform. + y: [f32; 2], +} + +/// The window's rect in pixels at slide offset `ow` (points), posed from `a`. +fn pose_rect(a: &Anchor, ow: [f32; 2]) -> [f32; 4] { posed(a.rect, a.offset, a.k, a.s, a.size, a.y, ow) } + +/// Along the slide, on paint's 1/64-pixel grid, moved by the offset's change from `at` (points); +/// across it, `y`. +fn posed(at: [f32; 4], offset: [f32; 2], k: f32, s: f32, size: [f32; 2], y: [f32; 2], ow: [f32; 2]) -> [f32; 4] { + let d = [(ow[0] - offset[0]) * k, (ow[1] - offset[1]) * k]; + let mut rect = [at[0] + d[0], at[1] + d[1], at[2] + d[0], at[3] + d[1]]; + for axis in 0..2 { + if ((rect[axis + 2] - rect[axis]) - size[axis]).abs() * s < 1.0 / 32.0 { + rect[axis + 2] = rect[axis] + size[axis]; + } + } + let r = rect.map(|v| grid(v, s) * s); + [r[0], y[0], r[2], y[1]] +} + +/// One past node `i`'s subtree: nodes go depth first, so the first node after it whose parent +/// comes before `i`. +fn subtree_end(nodes: &[Node], i: usize) -> usize { + (i + 1..nodes.len()).find(|&j| nodes[j].parent.is_none_or(|p| p < i)).unwrap_or(nodes.len()) +} + +fn slides(spec: Option<&rune_motion::LoopSpec>) -> bool { + matches!(spec.map(|l| l.kind), Some(rune_motion::LoopKind::Slide { .. } | rune_motion::LoopKind::SlideEased { .. })) +} + +/// A slide that moves only sideways. Text paints only the lines in its clip's band, plus two ems +/// either side (`content.rs`), so a window moving up or down could uncover a line paint never +/// drew, which no step can draw. +fn sideways(spec: Option<&rune_motion::LoopSpec>) -> bool { + matches!(spec.map(|l| l.kind), Some(rune_motion::LoopKind::Slide { from, to } | rune_motion::LoopKind::SlideEased { from, to, .. }) if from[1] == 0.0 && to[1] == 0.0) +} + +/// Paint's test for whether a box at `r` (x0, y0, x1, y1) under `clip` shows (`build`). +fn shows(r: [f32; 4], clip: [f32; 4], vp: [f32; 4]) -> bool { + let m = 2.0; + clip[2] > clip[0] && clip[3] > clip[1] + && r[2] >= clip[0].max(vp[0]) - m && r[0] <= clip[2].min(vp[2]) + m + && r[3] >= clip[1].max(vp[1]) - m && r[1] <= clip[3].min(vp[3]) + m +} + +impl paint_state::PaintState { + /// Node `i`'s loop glides: its edges land where the slide puts them, not on whole pixels, as + /// a browser's compositor moves a transformed layer, so that a loop-only step (which moves + /// only the clip and soft edges) and an ordinary frame draw the same picture. Only for what a + /// step can move, on the platform that steps it (Windows): a window sliding sideways over + /// content that slides back inside it, and that content. What the content holds still snaps. + /// Any other slide, and every slide elsewhere, snaps as before. + #[inline] + pub(in crate::runtime::paint) fn slide_glides( + nodes: &[Node], + motion: &crate::runtime::tracks::MotionState, + reduced_motion: bool, + i: usize, + ) -> bool { + if !cfg!(target_os = "windows") || reduced_motion { return false; } + let n = &nodes[i]; + if !slides(n.looping.as_deref()) || !motion.has_loop(n.id) { return false; } + Self::slide_pair(nodes, motion, i) || n.parent.is_some_and(|p| p + 1 == i && Self::slide_pair(nodes, motion, p)) + } + + /// Node `i` is a window a step could move, by its shape alone: it clips and slides sideways, + /// and its only child holds everything under it and slides back, sideways. Shape only, decided + /// before paint: a pair `slide_fits` then refuses (in a layer, over input, out of sight) still + /// glides, drawn by ordinary frames, so its picture doesn't change with whether a step ran. + #[inline] + pub(in crate::runtime::paint) fn slide_pair( + nodes: &[Node], + motion: &crate::runtime::tracks::MotionState, + i: usize, + ) -> bool { + let n = &nodes[i]; + let (counter, end) = (i + 1, subtree_end(nodes, i)); + n.vis.clip.is_some() && counter < end && subtree_end(nodes, counter) == end + && sideways(n.looping.as_deref()) && sideways(nodes[counter].looping.as_deref()) + && motion.has_loop(n.id) && motion.has_loop(nodes[counter].id) + } + + /// Paint reached node `i`: a window whose subtree it has passed is complete. + pub(super) fn slide_node_opens(&mut self, i: usize, instances_len: usize, scale: f32) { + let c = &mut self.keep.cycles; + c.opened = (i, instances_len); + // A subtree paints in one run, in tree order or the layers' (`update_layer_paint_order`), + // as long as nothing in it is lifted or raised out to paint later. + if c.open.is_some_and(|k| i < c.slides[k].window || i >= c.slides[k].end) { + self.close_slide(instances_len, scale); + } + } + + /// The rect, in pixels, that sliding window `i` clips and fades what it holds with: drawn at + /// `exact` (`rect` in points, `k` points per offset point) and snapped to `r` as a still box + /// is. Across the slide, `r`'s top and bottom; along it, posed from its anchor, kept from an + /// earlier paint while its top and bottom hold and this paint's exact edges land within a grid + /// step of the anchor's pose (its laid-out place held), else anchored here. Any other node + /// keeps `r`. + #[allow(clippy::too_many_arguments)] + pub(in crate::runtime::paint) fn slide_anchor( + &mut self, + nodes: &[Node], + motion: &crate::runtime::tracks::MotionState, + scene: &Scene, + s: f32, + reduced_motion: bool, + i: usize, + rect: [f32; 4], + exact: [f32; 4], + r: [f32; 4], + k: f32, + ) -> [f32; 4] { + if !Self::slide_glides(nodes, motion, reduced_motion, i) || !Self::slide_pair(nodes, motion, i) { return r; } + let n = &nodes[i]; + let ow = scene.get(n.id, prop::OFFSET).unwrap_or(rune_motion::Vec2::ZERO); + let ow = [ow.x, ow.y]; + let here = Anchor { node: n.id, rect, offset: ow, k, s, size: [grid(n.local.w, s), grid(n.local.h, s)], y: [r[1], r[3]] }; + let c = &mut self.keep.cycles; + let kept = c.anchors.iter().copied().find(|a| a.node == here.node && (a.k, a.s, a.size, a.y) == (here.k, here.s, here.size, here.y) + && { let p = pose_rect(a, ow); [0, 2].iter().all(|&e| (p[e] - exact[e]).abs() <= 1.0 / 64.0 + 1e-4) }); + let a = kept.unwrap_or(here); + c.next_anchors.push(a); + c.anchor = Some((i, a)); + pose_rect(&a, ow) + } + + /// Node `i` clipped what it holds to `r` under `outer` (clip, fade widths, fade origins), + /// from `rect` (points) at `k` points of rect per point of offset and ancestors' scale `sc`: + /// recorded if it is a sliding window a loop-only step can move. + #[allow(clippy::too_many_arguments)] + pub(in crate::runtime::paint) fn note_slide( + &mut self, + nodes: &[Node], + motion: &crate::runtime::tracks::MotionState, + scene: &Scene, + instances_len: usize, + s: f32, + viewport: (f32, f32), + reduced_motion: bool, + root_inh: Inh, + i: usize, + outer: [[f32; 4]; 3], + rect: [f32; 4], + r: [f32; 4], + (k, sc): (f32, f32), + ) { + if !Self::slide_glides(nodes, motion, reduced_motion, i) { return; } + let vp = [0.0, 0.0, viewport.0 * s, viewport.1 * s]; + let (counter, end, f) = match self.slide_fits(nodes, motion, scene, instances_len, root_inh, i, r, outer[0], vp) { + Ok(fits) => fits, + Err(why) => { self.keep.cycles.missed = Some(why); return; } + }; + let n = &nodes[i]; + let off = |j: usize| scene.get(nodes[j].id, prop::OFFSET).unwrap_or(rune_motion::Vec2::ZERO); + let (ow, oc) = (off(i), off(counter)); + // Posed from its anchor (`slide_anchor`, this paint's), else from this paint's own rect. + let (rect, offset, y) = match self.keep.cycles.anchor { Some((j, a)) if j == i => (a.rect, a.offset, a.y), _ => (rect, [ow.x, ow.y], [r[1], r[3]]) }; + let slide = Slide { + window: i, + counter, + end, + instances: instances_len..instances_len, + rect, + offset, + y, + painted: [ow.x, ow.y], + net: [ow.x + oc.x, ow.y + oc.y], + k, + s, + size: [grid(n.local.w, s), grid(n.local.h, s)], + outer, + own: f.map(|v| v * sc * s), + vp, + shown: Vec::new(), + glyphs: Vec::new(), + checked: None, + }; + let c = &mut self.keep.cycles; + c.open = Some(c.slides.len()); + c.slides.push(slide); + } + + /// Whether sliding node `i`, drawn at `r` under `clip`, is a window a step can move: its only + /// child slides back and holds everything under it, nothing under it takes input, clips, + /// blurs, sticks or moves on its own, and it shows. Its child, one past its subtree, and its + /// fade widths; or why not. + #[allow(clippy::too_many_arguments)] + fn slide_fits( + &self, + nodes: &[Node], + motion: &crate::runtime::tracks::MotionState, + scene: &Scene, + instances_len: usize, + root_inh: Inh, + i: usize, + r: [f32; 4], + clip: [f32; 4], + vp: [f32; 4], + ) -> Result<(usize, usize, [f32; 4]), &'static str> { + let c = &self.keep.cycles; + if !motion.flying.is_empty() { return Err("a slide while something flies"); } + if c.open.is_some() { return Err("a slide inside a slide"); } + if c.opened != (i, instances_len) { return Err("a slide that draws itself"); } + let n = &nodes[i]; + let (counter, end) = (i + 1, subtree_end(nodes, i)); + let Some(f) = n.vis.clip else { return Err("a slide that doesn't clip") }; + if counter >= end || subtree_end(nodes, counter) != end || !slides(nodes[counter].looping.as_deref()) + || !motion.has_loop(nodes[counter].id) { return Err("a slide whose child doesn't slide back"); } + if !sideways(n.looping.as_deref()) || !sideways(nodes[counter].looping.as_deref()) { return Err("a slide up or down"); } + if n.scroll.is_some() || self.row_h[i] >= 0.0 || self.row_mask[i] >= 0.0 { return Err("a slide that scrolls or folds"); } + let parent = n.parent.map_or(root_inh, |p| self.inh_scratch[p]); + if parent.in_cache || parent.skip_paint || parent.turn != 0 || parent.rounded.is_some() || parent.blur != 0.0 { return Err("a slide in a layer"); } + let plain = (i..end).all(|j| { + let m = &nodes[j]; + m.handlers.get().is_none() && m.focus.get().is_none() && !m.vis_flags.hit() && m.input.is_none() && m.sticky.is_none() + && m.vis.effect.is_none() && m.help.is_none() && m.above.is_none() && m.matched.is_none() && !m.vis_flags.raise() + }); + if !plain { return Err("a slide over input"); } + let still = (i..end).all(|j| { + let m = &nodes[j]; + scene.presented(m.id).is_some_and(|p| p.blur == 0.0 && p.mask.is_none() && p.transform.rotate == 0.0) + && (j == i || (m.vis.clip.is_none() && m.scroll.is_none() && (j == counter || m.looping.is_none()))) + }); + if !still { return Err("a slide over clips or motion"); } + if !shows([r[0], r[1], r[2].max(r[0]), r[3].max(r[1])], clip, vp) { return Err("a slide out of sight"); } + Ok((counter, end, f)) + } + + /// The open window's subtree is painted: its instances, and what each node under it showed. + pub(super) fn close_slide(&mut self, len: usize, s: f32) { + let Some(k) = self.keep.cycles.open.take() else { return }; + let (drawn, seen) = (&self.drawn, &self.seen); + let sl = &mut self.keep.cycles.slides[k]; + sl.instances.end = len; + sl.shown = (sl.window + 1..sl.end) + .map(|j| (drawn.get(j).map_or([0.0; 4], |d| [d[0] * s, d[1] * s, (d[0] + d[2]) * s, (d[1] + d[3]) * s]), seen.get(j).copied().unwrap_or(false))) + .collect(); + } + + /// Where window `sl` would clip and fade its content with its own offset at `ow` (points): + /// None when the step can't move it alone (the content would move, or something under it + /// would show or hide, or a glyph draw or not). + fn slide_pose(sl: &Slide, ow: [f32; 2]) -> Option<Pose> { + let r = posed(sl.rect, sl.offset, sl.k, sl.s, sl.size, sl.y, ow); + if !shows([r[0], r[1], r[2].max(r[0]), r[3].max(r[1])], sl.outer[0], sl.vp) { return None; } + let clip = intersect(r, sl.outer[0]); + let (mut fade, mut origin) = (sl.outer[1], sl.outer[2]); + inherit_fade(&mut fade, &mut origin, r, sl.own); + if sl.shown.iter().any(|&(at, was)| shows(at, clip, sl.vp) != was) { return None; } + if sl.glyphs.iter().any(|&(q, drew)| (q[1] > clip[3] || q[3] < clip[1] || q[0] > clip[2] || q[2] < clip[0]) == drew) { return None; } + Some((clip, crate::render::pack_fade(fade, origin, clip))) + } + + /// The pose each window's instances take at the loops' offsets at animation time `t`, or + /// why a step can't draw one of them. + #[allow(clippy::too_many_arguments)] + pub(super) fn slide_poses( + &mut self, + nodes: &[Node], + motion: &crate::runtime::tracks::MotionState, + scene: &Scene, + instances: &[Instance], + now_t: f64, + reduced_motion: bool, + t: f64, + ) -> Result<Vec<Pose>, &'static str> { + let at = |j: usize| -> Option<[f32; 2]> { + let n = &nodes[j]; + let store = scene.store(); + let time = store.node_time(n.id) + (t - now_t) * f64::from(store.node_time_scale(n.id)); + let [x, y] = motion.loop_offset(n.id, time, reduced_motion)?; + Some([x * n.local.w, y * n.local.h]) + }; + let mut poses = Vec::with_capacity(self.keep.cycles.slides.len()); + for k in 0..self.keep.cycles.slides.len() { + if !self.slide_checked(k, instances) { return Err("a slide drew otherwise"); } + let sl = &self.keep.cycles.slides[k]; + let (ow, oc) = at(sl.window).zip(at(sl.counter)).ok_or("a slide stopped")?; + // The content holds still only while the two offsets cancel as they did. + if (ow[0] + oc[0] - sl.net[0]).abs() > 1e-3 || (ow[1] + oc[1] - sl.net[1]).abs() > 1e-3 { return Err("a slide's content moves"); } + poses.push(Self::slide_pose(sl, ow).ok_or("a slide shows or hides something")?); + } + Ok(poses) + } + + /// Window `k`'s instances are what its record says: the pose it was painted at, the glyphs + /// it drew, no layer. Asked once a paint. + fn slide_checked(&mut self, k: usize, instances: &[Instance]) -> bool { + let sl = &self.keep.cycles.slides[k]; + if let Some(ok) = sl.checked { return ok; } + let range = sl.instances.clone(); + let ok = range.end <= instances.len() && Self::slide_pose(sl, sl.painted).is_some_and(|(clip, fade)| { + let here = &instances[range.clone()]; + here.iter().all(|q| q.clip == clip && q.fade == fade && q.params[1] != crate::render::KIND_LAYER && q.params[1] != crate::render::KIND_LAYER_END) + && here.iter().filter(|q| q.params[1] == KIND_GLYPH).count() == sl.glyphs.iter().filter(|g| g.1).count() + }); + self.keep.cycles.slides[k].checked = Some(ok); + ok + } + + /// Draws each window's instances at its pose; returns the instances it wrote. + pub(super) fn apply_slides(&self, poses: &[Pose], instances: &mut [Instance], patched: &mut Vec<u32>) { + for (sl, &(clip, fade)) in self.keep.cycles.slides.iter().zip(poses) { + for at in sl.instances.clone() { + let q = &mut instances[at]; + q.clip = clip; + q.fade = fade; + patched.push(at as u32); + } + } + } +} diff --git a/app/vendor/rune/crates/rune/src/runtime/paint/slots.rs b/app/vendor/rune/crates/rune/src/runtime/paint/slots.rs new file mode 100644 index 0000000..7aaa221 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/paint/slots.rs @@ -0,0 +1,60 @@ +//! Paint records that keep a place in the painter stream for pixels Rune doesn't paint itself: +//! effect slots a compositor fills (`El::effect`) and backdrop blurs (`El::backdrop_blur`). +use super::intersect; +use crate::render::{Instance, KIND_BACKDROP_BLUR, KIND_EFFECT, LayerSpec, NO_CLIP}; + +/// Pushes the effect slot `effect` tagged `mark` over `rect` with corner `radii`, clipped by +/// `clip` and the packed `fade`, at `k_px` device pixels per point and paint opacity `o`. +/// A compositor paints whatever it likes at a slot, so a faded slot gets its own layer that +/// applies the opacity, instead of a factor it could forget. Returns the index of that slot. +pub(in crate::runtime) fn push_effect(instances: &mut Vec<Instance>, (effect, mark): (crate::el::effect::EffectSlot, u32), + (rect, radii, clip, fade): ([f32; 4], [f32; 4], [f32; 4], [u32; 4]), k_px: f32, o: f32) -> Option<usize> { + let slot = Instance { + rect, + radii, + fill: [0.0, 0.0, 0.0, 1.0], + border: [(mark & 0xFFFF) as f32, (mark >> 16) as f32, 0.0, 0.0], + params: [if effect.backdrop { 1.0 } else { 0.0 }, KIND_EFFECT, effect.bleed * k_px, k_px], + uv: effect.data, + clip, + fade, + }; + if o >= 1.0 { + instances.push(slot); + return None; + } + let mut marker = Instance::begin_layer(rect, clip, LayerSpec { opacity: o, ..Default::default() }); + marker.fade = fade; + instances.push(marker); + instances.push(Instance { clip: NO_CLIP, ..slot }); + instances.push(Instance::end_layer()); + Some(instances.len() - 2) +} + +/// Pushes a backdrop blur record (`El::backdrop_blur`) of `sigma` points over `rect` with corner +/// `radii` (continuous when `continuous`), cut by `clip`, the soft edges `fade` from +/// `fade_origin` and an ancestor's rounded clip `rounded`, at `k_px` device pixels per point and +/// opacity `o`. Returns the signed corner radius an outer shadow leaves clear over the blur. +pub(in crate::runtime) fn push_backdrop_blur(instances: &mut Vec<Instance>, sigma: f32, (rect, radii, continuous): ([f32; 4], [f32; 4], bool), + (clip, fade, fade_origin): ([f32; 4], [f32; 4], [f32; 4]), rounded: Option<([f32; 4], [f32; 4])>, k_px: f32, o: f32) -> f32 { + // One clip rectangle fits the packed ABI: a rounded clip cut by `clip` keeps only the cut. + let (clip, round) = match rounded { + Some((mask, radii)) if intersect(clip, mask) == mask => (mask, Some(radii)), + Some((mask, _)) => (intersect(clip, mask), None), + None => (clip, None), + }; + let mut record = Instance { + rect, + radii: if continuous { radii.map(|v| -v) } else { radii }, + fill: [0.0, 0.0, 0.0, o], + border: [0.0; 4], + params: [sigma * k_px, KIND_BACKDROP_BLUR, 0.0, k_px], + uv: [0.0; 4], + clip, + fade: crate::render::pack_fade(fade, fade_origin, clip), + }; + if let Some(radii) = round { record.round_clip_corners(radii); } + instances.push(record); + let radius = crate::system_material::clamp_radius(radii, rect[2], rect[3]); + if continuous { -radius } else { radius } +} diff --git a/app/vendor/rune/crates/rune/src/runtime/paint/soft_edges.rs b/app/vendor/rune/crates/rune/src/runtime/paint/soft_edges.rs new file mode 100644 index 0000000..7d009bd --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/paint/soft_edges.rs @@ -0,0 +1,36 @@ +//! Soft clip edges: how a fade inherits down the tree, and whether a rect reaches into one. + +/// Device-pixel extent of a tagged fade width (`< 0` = linear, `> STOP_FADE_BIAS` = explicit stops). +#[inline] +pub(in crate::runtime) fn fade_extent(w: f32) -> f32 { + if w > crate::render::STOP_FADE_BIAS { + w - crate::render::STOP_FADE_BIAS + } else { + w.abs() + } +} + +// Carry the declaring edge with the inherited width. Descendant clipping must not restart +// its ramp; an inner fade takes over once the ancestor's ramp is fully opaque there. Widths +// compare by size: a negative one is a linear ramp (`El::clip_fade_linear`), and one above +// `STOP_FADE_BIAS` uses explicit stops (`ScrollFade::stops`). +pub(in crate::runtime) fn inherit_fade(width: &mut [f32; 4], origin: &mut [f32; 4], rect: [f32; 4], own: [f32; 4]) { + for edge in 0..4 { + let inset = if edge < 2 { rect[edge] - origin[edge] } else { origin[edge] - rect[edge] }; + let (o, w) = (fade_extent(own[edge]), fade_extent(width[edge])); + if o > 0.0 && (o >= w || inset >= w) { + width[edge] = own[edge]; + origin[edge] = rect[edge]; + } + } +} + +/// Whether `r` (x0, y0, x1, y1) reaches into a soft edge of `clip`: one fading over `width` +/// from `origin`, edge by edge (left, top, right, bottom). +pub(in crate::runtime) fn in_fade(r: [f32; 4], clip: [f32; 4], width: [f32; 4], origin: [f32; 4]) -> bool { + let width = width.map(fade_extent); + (width[0] > 0.0 && r[0] < origin[0] + width[0] && r[2] > clip[0]) + || (width[1] > 0.0 && r[1] < origin[1] + width[1] && r[3] > clip[1]) + || (width[2] > 0.0 && r[2] > origin[2] - width[2] && r[0] < clip[2]) + || (width[3] > 0.0 && r[3] > origin[3] - width[3] && r[1] < clip[3]) +} diff --git a/app/vendor/rune/crates/rune/src/runtime/paint/state.rs b/app/vendor/rune/crates/rune/src/runtime/paint/state.rs new file mode 100644 index 0000000..52df7ff --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/paint/state.rs @@ -0,0 +1,437 @@ +//! Per-frame paint scratch buffers, drawn geometry, layer caches, text quad caches and paint +//! outputs owned by [`RuntimeCore`]. +use super::*; + +/// Retained paint-pass scratch, reuse record, drawn geometry, layer caches and per-frame paint +/// outputs. Ordered hot-first under `#[repr(C)]` so per-node vectors (`inh_scratch`, `drawn`, +/// `row_dy`, `row_h`, `row_mask`, `drawn_scale`, `seen`) and `pixel_snap` sit together and first +/// ahead of the larger reuse record and cold cache tables. +#[repr(C)] +pub(crate) struct PaintState { + pub(in crate::runtime) inh_scratch: Vec<Inh>, + /// Drawn rect per node (points, root space), for tools and hit tests. + pub(crate) drawn: Vec<[f32; 4]>, + pub(super) quads_frame: u64, + /// Opt-in gamma-space (sRGB) blending for translucent fills, shadows and blurs. + pub(in crate::runtime) srgb_blend: bool, + /// The shell shows native views for the first `MAX_NATIVE_MATERIALS` of `materials`; their + /// elements skip their fill and cut their shadows out of their interior. + pub(super) native_materials: bool, + /// A drawn video is playing or seeking: keep drawing frames. + pub(super) videos_active: bool, + /// A drawn animated SVG icon is advancing right now: keep drawing frames. + pub(super) animated_icons: bool, + /// A painted animated SVG icon is active (moving or waiting on a flat hold), even while the + /// window is covered: tells Windows occlusion polling (`loops_shown`) to watch for uncover. + pub(super) animated_icons_shown: bool, + /// Current node painted a live animated icon (moving or waiting): prevents `PaintKeep` from + /// freezing its quad across frames while active, without blocking sibling subtrees. + pub(super) node_animated_icon: bool, + /// Earliest runtime timestamp when a flat-hold animated icon resumes moving (`wake_for_motion`). + pub(super) icon_anim_wake: Option<f64>, + /// Mount time (runtime `t`) per `(NodeId, icon_ptr)` for finite-duration animated icons. + pub(super) icon_anim_mounts: HashMap<(NodeId, usize), f64>, + /// Frame requested by scale settling or pixel snapping in the last paint. + pub(super) scale_frame: Option<AnotherFrame>, + /// Per node index this frame: presented row top dy, row height override, and bottom feather mask. + pub(in crate::runtime) row_dy: Vec<f32>, + pub(in crate::runtime) row_h: Vec<f32>, + pub(in crate::runtime) row_mask: Vec<f32>, + /// The scale each node's text drew at (its own and its ancestors'), for text hit tests. + pub(crate) drawn_scale: Vec<f32>, + /// Per node: it drew inside its clip and the window in the last build. + pub(super) seen: Vec<bool>, + /// Drawn videos' state generations; a change re-runs the view. + pub(super) video_signature: u64, + pub(super) pixel_snap: pixel_snap::Glides, + /// Last scale observation per node that has a scale or had one. See [`ScaleMotion`]. + pub(super) static_scales: HashMap<NodeId, ScaleSettle>, + /// What the last paint painted, for subtrees that would paint it again (`paint_keep`). + pub(super) keep: paint_keep::PaintKeep, + /// The composed turns `Inh::turn` points into, rebuilt each paint. + pub(in crate::runtime) turn_scratch: Vec<Turn>, + /// For nodes inside a turned layer: `(unturned_rect_pt, unturned_clip_px)`. Empty unless a + /// node turns. + pub(in crate::runtime) unturned_drawn: Vec<([f32; 4], [f32; 4])>, + /// Growth rows whose contents draw lifted this frame (`GrowTrack::hide_above`): index, points. + pub(super) row_lifts: Vec<(usize, f32)>, + /// Only nonempty when retained exit nodes or matched flights make storage order differ + /// from paint order. + pub(super) layer_paint_order: Vec<usize>, + /// Sorted indices of anchored overlays lifted in `update_layer_paint_order` so they paint + /// after (and above) a `.raise()` or flying subtree containing their anchor. + pub(super) lifted_anchors: Vec<usize>, + /// Last resolved `(target_rect, zoom)` per anchored overlay node id, so an exiting overlay + /// holds its position if its anchor unmounts mid-exit instead of snapping to `(0, 0)`. + pub(in crate::runtime) last_anchor_targets: HashMap<NodeId, ([f32; 4], f32)>, + /// Deduplicated `(overlay_path, anchor_key)` pairs logged when an anchored overlay could not + /// resolve its anchor and was suppressed. + pub(in crate::runtime) unresolved_anchor_warnings: HashSet<(String, String)>, + pub(super) dissolve_scratch: Vec<bool>, + pub(in crate::runtime) glyph_scratch: Vec<GlyphQuad>, + pub(super) deco_scratch: Vec<PaintedDeco>, + pub(super) layer_scratch: Vec<(usize, usize, usize)>, + pub(in crate::runtime) cache_live_scratch: Vec<bool>, + pub(super) cache_check_scratch: Vec<bool>, + pub(super) cache_paint_scratch: Vec<u64>, + pub(super) cache_inside_scratch: Vec<bool>, + pub(in crate::runtime) node_caches: HashMap<NodeId, NodeCache>, + /// The device rows of each field with waiting paragraphs its last paint showed (`text_fill`). + pub(in crate::runtime) text_rows: HashMap<NodeId, (f32, f32)>, + /// Each still text's quads as it drew them, by node and layout id, and the paint they were + /// last used in (`paint_content`): a frame that draws it the same copies them. + pub(super) text_quads: HashMap<(NodeId, crate::text::LayoutId), (crate::el::grid::DrawnRow, u64)>, + /// `El::system_material` elements built this frame, in paint order. + pub(super) materials: Vec<crate::system_material::MaterialDraw>, + /// Each node's place in the paint order, kept by the frame build while `Some` (the motion + /// gate's `z-order`). + pub(super) paint_rank: Option<Vec<u32>>, + /// While `paint_rank` is kept: this frame's icons drawn through their transparent one-texel + /// apron (`icon_inst` off the pixel grid), by atlas place (`apron_key`), for the gate's raster. + pub(super) icon_aprons: Vec<[u32; 3]>, + /// Still texts that copied their quads, for tests. + #[cfg(test)] + pub(super) quads_copied: u64, +} + +impl PaintState { + // Single-caller constructor for `RuntimeCore::new`; inlined so it stays in its caller's + // codegen unit instead of shifting partitioning and dropping inlining in the paint walk. + #[inline] + pub(in crate::runtime) fn new() -> Self { + Self { + inh_scratch: Vec::new(), + drawn: Vec::new(), + quads_frame: 0, + srgb_blend: false, + native_materials: false, + videos_active: false, + animated_icons: false, + animated_icons_shown: false, + node_animated_icon: false, + icon_anim_wake: None, + icon_anim_mounts: HashMap::default(), + scale_frame: None, + row_dy: Vec::new(), + row_h: Vec::new(), + row_mask: Vec::new(), + drawn_scale: Vec::new(), + seen: Vec::new(), + video_signature: 0, + pixel_snap: Default::default(), + static_scales: HashMap::default(), + keep: Default::default(), + turn_scratch: Vec::new(), + unturned_drawn: Vec::new(), + row_lifts: Vec::new(), + layer_paint_order: Vec::new(), + lifted_anchors: Vec::new(), + last_anchor_targets: HashMap::default(), + unresolved_anchor_warnings: HashSet::default(), + dissolve_scratch: Vec::new(), + glyph_scratch: Vec::new(), + deco_scratch: Vec::new(), + layer_scratch: Vec::new(), + cache_live_scratch: Vec::new(), + cache_check_scratch: Vec::new(), + cache_paint_scratch: Vec::new(), + cache_inside_scratch: Vec::new(), + node_caches: HashMap::default(), + text_rows: HashMap::default(), + text_quads: HashMap::default(), + materials: Vec::new(), + paint_rank: None, + icon_aprons: Vec::new(), + #[cfg(test)] + quads_copied: 0, + } + } + + #[inline] + pub(in crate::runtime) fn srgb_blend(&self) -> bool { + self.srgb_blend + } + + #[inline] + pub(in crate::runtime) fn set_srgb_blend(&mut self, enabled: bool) -> bool { + let changed = self.srgb_blend != enabled; + self.srgb_blend = enabled; + changed + } + + #[cfg(test)] + #[inline] + pub(crate) fn native_materials(&self) -> bool { + self.native_materials + } + + #[cfg(any(test, target_os = "macos"))] + #[inline] + pub(crate) fn set_native_materials(&mut self, native: bool) { + self.native_materials = native; + } + + #[inline] + pub(in crate::runtime) fn videos_active(&self) -> bool { + self.videos_active + } + + #[inline] + pub(in crate::runtime) fn animated_icons(&self) -> bool { + self.animated_icons + } + + #[inline] + pub(in crate::runtime) fn animated_icons_shown(&self) -> bool { + self.animated_icons_shown + } + + #[inline] + pub(in crate::runtime) fn icon_anim_wake(&self) -> Option<f64> { + self.icon_anim_wake + } + + #[inline] + pub(in crate::runtime) fn note_icon_anim_wake(&mut self, at: f64) { + self.icon_anim_wake = Some(match self.icon_anim_wake { + Some(prev) => prev.min(at), + None => at, + }); + } + + #[inline] + pub(in crate::runtime) fn icon_mount_time(&self, id: NodeId, icon_ptr: usize, fallback: f64) -> f64 { + self.icon_anim_mounts.get(&(id, icon_ptr)).copied().unwrap_or(fallback) + } + + #[inline] + pub(in crate::runtime) fn get_or_insert_icon_mount(&mut self, id: NodeId, icon_ptr: usize, now: f64) -> f64 { + *self.icon_anim_mounts.entry((id, icon_ptr)).or_insert(now) + } + + #[inline] + pub(in crate::runtime) fn scale_settling(&self) -> bool { + self.scale_frame.is_some() || self.pixel_snap.easing() + } + + #[inline] + pub(in crate::runtime) fn seen(&self) -> &[bool] { + &self.seen + } + + #[inline] + pub(in crate::runtime) fn was_seen(&self, i: usize, default: bool) -> bool { + self.seen.get(i).copied().unwrap_or(default) + } + + #[inline] + pub(in crate::runtime) fn prune_static_scales(&mut self, scene: &Scene) { + if !self.static_scales.is_empty() { + self.static_scales.retain(|id, _| scene.contains(*id)); + } + } + + #[cfg(test)] + #[inline] + pub(in crate::runtime) fn tracks_static_scale(&self, id: NodeId) -> bool { + self.static_scales.contains_key(&id) + } + + #[inline] + pub(in crate::runtime) fn prune_caches( + &mut self, + has_cache: bool, + scene: &Scene, + resident_caches: &mut std::collections::HashMap<u64, u64>, + ) { + if !has_cache { + if !self.node_caches.is_empty() { self.node_caches.clear(); } + if !resident_caches.is_empty() { resident_caches.clear(); } + } else { + if !self.node_caches.is_empty() { + self.node_caches.retain(|id, _| scene.contains(*id)); + } + if !resident_caches.is_empty() { + resident_caches.retain(|id, _| scene.contains(NodeId(*id))); + } + } + } + + #[inline] + pub(in crate::runtime) fn begin_frame(&mut self) { + self.keep.frame += 1; + } + + #[inline] + pub(in crate::runtime) fn record_moved(&mut self, ids: impl IntoIterator<Item = NodeId>) { + self.keep.moved.extend(ids); + } + + #[inline] + pub(in crate::runtime) fn note_cycle_other_deadline(&mut self) { + self.keep.cycles.other_deadline(); + } + + #[inline] + pub(in crate::runtime) fn take_cycle_check_clock(&mut self) -> Option<f64> { + self.keep.cycles.check_clock.take() + } + + #[inline] + pub(in crate::runtime) fn clear_row_lifts(&mut self) { + self.row_lifts.clear(); + } + + #[inline] + pub(in crate::runtime) fn push_row_lift(&mut self, ri: usize, lift: f32) { + self.row_lifts.push((ri, lift)); + } + + #[inline] + pub(in crate::runtime) fn row_lifts(&self) -> &[(usize, f32)] { + &self.row_lifts + } + + #[inline] + pub(in crate::runtime) fn layer_paint_order(&self) -> &[usize] { + &self.layer_paint_order + } + + #[inline] + pub(in crate::runtime) fn clear_layer_paint_order(&mut self) { + self.layer_paint_order.clear(); + self.lifted_anchors.clear(); + } + + #[inline] + pub(in crate::runtime) fn is_lifted_anchor(&self, i: usize) -> bool { + self.lifted_anchors.binary_search(&i).is_ok() + } + + /// Subtree (preorder) paint order, then each flying or raised element's subtree on top. + /// A sticky element paints after its normal siblings (and before overlay siblings), so it + /// covers the rows it's stuck over. + pub(in crate::runtime) fn update_layer_paint_order( + &mut self, + tree: &types::TreeState, + flying: &[(NodeId, MRect)], + sticky_of: impl Fn(usize) -> bool, + ) { + let n = tree.nodes.len(); + let mut first = vec![n; n + 1]; + let mut next = vec![n; n]; + // Siblings paint by `El::paint_order`, then (with sticky elements about) sticky ones over + // the rows they're stuck over and anchored overlays and modals over both. + let rank = |i: usize| { + let nd = &tree.nodes[i]; + let place = if !tree.has_sticky { 0 } + else if nd.above.is_some() || nd.handlers.modal.is_some() { 2 } + else if sticky_of(i) { 1 } + else { 0 }; + (nd.vis.paint_order, place) + }; + if tree.has_sticky || tree.has_paint_order { + let mut ranks: Vec<_> = (0..n).map(|i| (rank(i), i)).collect(); + ranks.sort_unstable(); + for &(_, i) in ranks.iter().rev() { + let parent = tree.nodes[i].parent.map_or(0, |p| p + 1); + next[i] = first[parent]; first[parent] = i; + } + } else { + for i in (0..n).rev() { + let parent = tree.nodes[i].parent.map_or(0, |p| p + 1); + next[i] = first[parent]; first[parent] = i; + } + } + let mut lifted: Vec<usize> = flying.iter().filter_map(|(id, _)| tree.node_index.get(id).copied()).collect(); + if tree.has_raise { lifted.extend((0..n).filter(|&i| tree.nodes[i].vis_flags.raise())); } + lifted.sort_unstable(); + lifted.dedup(); + self.lifted_anchors.clear(); + if !lifted.is_empty() { + // An anchored overlay whose anchor lives inside a lifted (`.raise()` or flying) subtree + // must paint after that subtree so `drawn[anchor]` is populated and the overlay draws + // above its anchor (e.g. a hover card or menu over a peeked sidebar or raised modal). + let mut lifted_mask = vec![false; n]; + for &r in &lifted { lifted_mask[r] = true; } + let lifted_root = |mut k: usize, mask: &[bool]| -> Option<usize> { + loop { + if mask[k] { return Some(k); } + k = tree.nodes[k].parent?; + } + }; + let mut changed = true; + while changed { + changed = false; + for i in 0..n { + if lifted_mask[i] { continue; } + let Some(a) = &tree.nodes[i].above else { continue }; + let Some(j) = super::anchor_index(&tree.nodes, i, a) else { continue }; + let Some(ar) = lifted_root(j, &lifted_mask) else { continue }; + if lifted_root(i, &lifted_mask) != Some(ar) { + lifted_mask[i] = true; + lifted.push(i); + self.lifted_anchors.push(i); + changed = true; + } + } + } + if !self.lifted_anchors.is_empty() { + lifted.sort_unstable(); + self.lifted_anchors.sort_unstable(); + } + } + self.layer_paint_order.clear(); + for top in std::iter::once(None).chain(lifted.iter().map(|&r| Some(r))) { + let mut i = top.unwrap_or(first[0]); + while i < n { + // A flying subtree paints in its own pass, not where the tree reaches it. + if top == Some(i) || lifted.binary_search(&i).is_err() { + self.layer_paint_order.push(i); + if first[i + 1] < n { i = first[i + 1]; continue; } + } + loop { + if top == Some(i) { i = n; break; } + if next[i] < n { i = next[i]; break; } + match tree.nodes[i].parent { Some(parent) => i = parent, None => { i = n; break; } } + } + } + } + if self.layer_paint_order.iter().copied().eq(0..n) { + self.layer_paint_order.clear(); + self.lifted_anchors.clear(); + } + } + + #[cfg(test)] + #[inline] + pub(in crate::runtime) fn dissolve_scratch(&self) -> &[bool] { + &self.dissolve_scratch + } + + #[inline] + pub(crate) fn materials(&self) -> &[crate::system_material::MaterialDraw] { + &self.materials + } + + #[inline] + pub(crate) fn enable_paint_rank(&mut self) { + self.paint_rank = Some(Vec::new()); + } + + #[inline] + pub(in crate::runtime) fn paint_rank(&self, i: usize) -> u32 { + self.paint_rank.as_ref().and_then(|r| r.get(i)).copied().unwrap_or(i as u32) + } + + #[inline] + pub(crate) fn icon_aprons(&self) -> &[[u32; 3]] { + &self.icon_aprons + } + + #[cfg(test)] + #[inline] + pub(in crate::runtime) fn quads_copied(&self) -> u64 { + self.quads_copied + } +} diff --git a/app/vendor/rune/crates/rune/src/runtime/paint/text_flights.rs b/app/vendor/rune/crates/rune/src/runtime/paint/text_flights.rs new file mode 100644 index 0000000..e40afe9 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/paint/text_flights.rs @@ -0,0 +1,81 @@ +//! Text flights drawn as an overlay of glyph instances, from their source text to their landed text. +use super::*; + +impl state::PaintState { + /// All destination rectangles below come from this frame's completed growth/scroll build. + /// The overlay only writes draw instances, never layout or app state. + #[allow(clippy::too_many_arguments)] + pub(in crate::runtime) fn draw_text_flights( + &mut self, + flights: &mut Vec<TextFlight>, + nodes: &[Node], + scene: &Scene, + text: &mut TextSystem, + images: &mut crate::pixels::ImageAtlas, + instances: &mut Vec<Instance>, + s: f32, + now: f64, + reduced: bool, + viewport: (f32, f32), + ) -> bool { + let srgb = self.srgb_blend; + let viewport = [0.0, 0.0, viewport.0, viewport.1]; + flights.retain(|f| nodes.iter().any(|n| f.lands(&n.path, n.key.as_deref()) + && !matches!(scene.phase(n.id), Some(PresencePhase::Exiting { .. })))); + let mut done = Vec::new(); + for (fi, f) in flights.iter_mut().enumerate() { + let Some((i, n)) = nodes.iter().enumerate().find(|(_, n)| f.lands(&n.path, n.key.as_deref())) else { continue }; + let (Some(spec), Some(layout)) = (&n.text, n.text_layout.as_ref().and_then(TextLayout::single)) else { done.push(fi); continue }; + // Both ends are measured by their laid-out text, so a destination box wider than its + // text (a body stretched across a column) doesn't scale the flight. + let (target, origin) = text_extent(n, spec, TextFlow::Single(layout), self.drawn[i], s); + if f.measure(target, now, reduced) { done.push(fi); } + // Land sub-quantum size residuals before snapping both edges. Otherwise a settled + // height can alternate by one quantum while its still-moving top crosses the grid. + let quantum = 1.0 / (64.0 * s); + if (f.presented.w - target.w).abs() < quantum { f.presented.w = target.w; } + if (f.presented.h - target.h).abs() < quantum { f.presented.h = target.h; } + let edges = f.presented.edges().map(|v| grid(v, s)); + f.presented = MRect::new(edges[0], edges[1], edges[2] - edges[0], edges[3] - edges[1]); + let p = f.progress(now, reduced); + let (source_alpha, target_alpha) = f.alphas(target, now, reduced); + let actual_clip = screen_clip_of(n.parent, &self.inh_scratch, &self.turn_scratch).map(|v| v / s); + let actual_clip = [actual_clip[0].max(0.0), actual_clip[1].max(0.0), actual_clip[2].min(viewport[2]), actual_clip[3].min(viewport[3])]; + let current = f.presented; + let zoom = current.w / f.source.w; + let start_clip = [current.x + (f.source_clip[0] - f.source.x) * zoom, + current.y + (f.source_clip[1] - f.source.y) * zoom, + current.x + (f.source_clip[2] - f.source.x) * zoom, + current.y + (f.source_clip[3] - f.source.y) * zoom]; + // A travelling overlay is above the composer and the growing bubble's mask. Using + // that destination mask here can hide the text before it has reached the bubble. + // The normal ancestor clip takes over only once the flight has landed. + let end_clip = viewport; + let clip = std::array::from_fn(|j| start_clip[j] + (end_clip[j] - start_clip[j]) * p); + f.clip = if reduced { actual_clip } else { clip }; + f.source_alpha = source_alpha; + f.target_alpha = target_alpha; + let final_fade = n.parent.and_then(|p| self.inh_scratch.get(p)).map_or([0.0; 4], |h| h.fade.map(|v| v / s)); + let fade = [0.0; 4]; + if source_alpha > 0.0 { + let source_rect = if reduced { f.source } else { current }; + let source_clip = if reduced { f.source_clip } else { clip }; + for q in &f.glyphs { + instances.push(transformed(*q, f.source, source_rect, f.scale, source_alpha, source_clip, fade)); + } + } + self.glyph_scratch.clear(); + text.set_glyph_inks(spec.color, &[]); + text.set_emit(text.moving_emit()); + text.glyphs_for_layout(layout, s, [origin[0] * s, origin[1] * s], false, &mut self.glyph_scratch); + text.set_emit(crate::text::outline::Emit::Atlas); + for q in &self.glyph_scratch { + let Some(q) = glyph_or_image(q, text, images, premul(spec.color, 1.0, srgb), NO_CLIP, [0.0; 4]) else { continue }; + instances.push(transformed(q, target, current, s, target_alpha, + if reduced { actual_clip } else { clip }, if reduced { final_fade } else { fade })); + } + } + for i in done.into_iter().rev() { flights.remove(i); } + !flights.is_empty() + } +} diff --git a/app/vendor/rune/crates/rune/src/runtime/paint/tracks.rs b/app/vendor/rune/crates/rune/src/runtime/paint/tracks.rs new file mode 100644 index 0000000..fde803f --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/paint/tracks.rs @@ -0,0 +1,293 @@ +//! A node's paint: colours, shadow geometry, hover and press. Most of it never changes, so a +//! property gets a track only when it does, starting from what was last drawn. + +use super::*; + +/// Finds new nodes in the last build. Both trees are mostly in the same order, so it walks +/// them together, and once a node is out of step it walks together no more: it finds every +/// later one in a map built on that first miss. +#[derive(Debug)] +pub(in crate::runtime) enum Finder { + /// Both trees agree on every node so far: the next one to compare sits at `next`. + InStep { next: usize }, + /// The first node out of step built `map` of the last build, from `next` on. + Mapped { next: usize, map: HashMap<NodeId, usize> }, +} + +impl Default for Finder { + fn default() -> Self { Finder::InStep { next: 0 } } +} + +impl Finder { + pub(in crate::runtime) fn find(&mut self, old: &[Node], id: NodeId) -> Option<usize> { + let at = match self { + Finder::InStep { next } => match old.get(*next) { + Some(n) if n.id == id => *next, + _ => { + let (next, map): (usize, HashMap<NodeId, usize>) = (*next, old.iter().enumerate().map(|(i, n)| (n.id, i)).collect()); + let at = map.get(&id).copied(); + *self = Finder::Mapped { next, map }; + at? + } + }, + Finder::Mapped { next, map } => match old.get(*next) { + Some(n) if n.id == id => *next, + _ => map.get(&id).copied()?, + }, + }; + self.advance(at + 1); + Some(at) + } + + pub(in crate::runtime) fn advance(&mut self, next: usize) { + match self { + Finder::InStep { next: at } | Finder::Mapped { next: at, .. } => *at = next, + } + } +} + +/// Resolves `old` against `old_nodes`, falling back to `nodes[i]` when `old` was moved out of +/// `old_nodes` by a `same_path` memo reuse (leaving its paint and text fields unchanged on `nodes[i]`). +#[inline] +pub(in crate::runtime) fn prev_node<'a>(old_nodes: &'a [Node], nodes: &'a [Node], old: Option<usize>, i: usize) -> Option<&'a Node> { + old.map(|o| if old_nodes[o].is_moved_stub() { &nodes[i] } else { &old_nodes[o] }) +} + +/// The colour a node's text or icon draws in. +pub(in crate::runtime) fn text_color(n: &Node) -> Option<Color> { + n.text.as_ref().map(|t| t.color).or(n.vis.icon.map(|(_, c)| c)) +} + +/// Text or icon colour `c` as it paints while its hover group is `group` hovered (0 to 1): +/// mixed toward its `El::group_color`. +pub(in crate::runtime) fn group_tint(n: &Node, c: Color, group: f32) -> Color { + match n.vis.group_color { + Some(g) if group > 0.0 => c.mix(g, group), + _ => c, + } +} + +/// Text or icon colour `c` while a press on the nearest `El::press_color` element is held (`pressed`, +/// 0 to 1): mixed toward that colour. +pub(in crate::runtime) fn press_tint(c: Color, to: Option<Color>, pressed: f32) -> Color { + match to { + Some(p) if pressed > 0.0 => c.mix(p, pressed), + _ => c, + } +} + +/// Which of a node's colours a live value owns. A commit leaves those tracks to the latch. +#[derive(Clone, Copy, Default)] +pub(in crate::runtime) struct LiveColors { + pub(in crate::runtime) fill: bool, + pub(in crate::runtime) text: bool, + pub(in crate::runtime) border: bool, + pub(in crate::runtime) shadow: bool, + pub(in crate::runtime) gradient: [bool; 2], +} + +pub(in crate::runtime) fn live_colors(n: &Node) -> LiveColors { + let mut c = LiveColors::default(); + for b in n.live.iter() { c.add(b.property); } + c +} + +impl LiveColors { + pub(in crate::runtime) fn add(&mut self, p: crate::live::Property) { + use crate::live::Property; + match p { + Property::Fill => self.fill = true, + Property::TextColor => self.text = true, + Property::Border => self.border = true, + Property::Shadow => self.shadow = true, + Property::GradientTop => self.gradient[0] = true, + Property::GradientBottom => self.gradient[1] = true, + _ => {} + } + } + + /// Puts back on `new` the colours `old` last latched for the bindings it kept, since the + /// view authored its own placeholder colour. + pub(in crate::runtime) fn carry(self, old: &Node, new: &mut Node) { + if self.fill { new.vis.fill = old.vis.fill; } + if self.border { new.vis.set_border_color(old.vis.border()); } + if self.text && let Some(c) = text_color(old) { + if let Some(spec) = &mut new.text { if spec.color != c { spec.color = c; } } + else if new.vis.icon.is_some_and(|(_, ic)| ic != c) && let Some((_, ic)) = &mut new.vis.cold_mut().icon { *ic = c; } + } + if self.shadow && let Some(c) = old.vis.shadows.first().map(|s| s.color) + && new.vis.shadows.first().is_some_and(|s| s.color != c) + { + new.vis.cold_mut().shadows[0].color = c; + } + for k in 0..2 { + if self.gradient[k] && let Some(c) = old.vis.gradient.as_deref().map(|g| g[k]) + && new.vis.gradient.as_deref().is_some_and(|g| g[k] != c) + && let Some(g) = new.vis.cold_mut().gradient.as_deref_mut() + { + g[k] = c; + } + } + } +} + +/// Readies `p` (hover, press, press scale), which reads `rest` without a track, to move to +/// `to`: false when it has no track and `to` is `rest`, so there's nothing to do; otherwise it +/// has a track, made at `rest` if it had none. +pub(in crate::runtime) fn ready_from_rest(scene: &mut Scene, id: NodeId, p: Prop<f32>, rest: f32, to: f32) -> bool { + if scene.store().has(id, p) { + return true; + } + if to == rest { + return false; + } + scene.set(id, p, rest); + true +} + +/// A shadow's geometry as its track holds it. +pub(in crate::runtime) fn shadow_geo(sh: &crate::el::Shadow) -> rune_motion::Rect { + rune_motion::Rect { x: sh.x, y: sh.y, w: sh.blur, h: sh.spread } +} + +/// Commits `to` on paint property `p` of node `id`, which last drew `from` (None if it's +/// new). Without a track a node draws its own value (`Runtime::color`, `shadow_at`), so it +/// needs none until the value changes, and a commit that leaves it changes nothing. +#[inline] +pub(in crate::runtime) fn commit_paint<T: rune_motion::Animatable + PartialEq>( + scene: &mut Scene, + id: NodeId, + p: Prop<T>, + from: Option<T>, + to: T, + s: Spring, + instant: bool, +) { + if !instant && from == Some(to) { + // Its track, if any, already heads to `to`: nothing else moves this property. + return; + } + let tracked = scene.store().has(id, p); + if from == Some(to) && !tracked { + return; + } + if !tracked { + match from { + Some(from) if !instant => scene.set(id, p, from), + _ => return, + } + } + if instant { + scene.set(id, p, to); + } else { + scene.animate(id, p, to, s); + } +} + +#[allow(clippy::too_many_arguments)] +pub(in crate::runtime) fn commit_cold_paint( + scene: &mut Scene, + old_nodes: &[Node], + id: NodeId, + vis: &Visual, + old: Option<usize>, + live: LiveColors, + spring_c: Spring, + spring_l: Spring, + instant: bool, +) { + fn prev_vis<'a>(old_nodes: &'a [Node], vis: &'a Visual, old: Option<usize>) -> Option<&'a Visual> { + let o = old?; + Some(if old_nodes[o].is_moved_stub() { vis } else { &old_nodes[o].vis }) + } + for (k, sh) in vis.shadows.iter().take(P_SHADOWS.len()).enumerate() { + let was = prev_vis(old_nodes, vis, old).and_then(|o| o.shadows.get(k).copied()); + // An inset ring where a drop shadow was (or the other way) is another shadow, not this + // one changing: it lands rather than morphing between the two. + let instant = instant || was.is_some_and(|w| w.inset != sh.inset); + if !(k == 0 && live.shadow) { + commit_paint(scene, id, P_SHADOWS[k], was.map(|w| w.color), sh.color, spring_c, instant); + } + commit_paint(scene, id, P_SHADOW_GEO[k], was.map(|w| shadow_geo(&w)), shadow_geo(sh), spring_l, instant); + } + let prev_shadows = prev_vis(old_nodes, vis, old).map_or(0, |o| o.shadows.len()).min(P_SHADOWS.len()); + for k in vis.shadows.len()..prev_shadows { + scene.store_mut().remove(id, P_SHADOWS[k]); + scene.store_mut().remove(id, P_SHADOW_GEO[k]); + } + if let Some(&g) = vis.gradient.as_deref() { + let was = prev_vis(old_nodes, vis, old).and_then(|o| o.gradient.as_deref().copied()); + for k in 0..2 { + if !live.gradient[k] { + commit_paint(scene, id, P_GRADIENT[k], was.map(|w| w[k]), g[k], spring_c, instant); + } + } + } + if let Some(rg) = &vis.radial { + for (k, &(_, c)) in rg.stops.iter().take(P_RADIAL.len()).enumerate() { + let was = prev_vis(old_nodes, vis, old).and_then(|o| o.radial.as_ref()?.stops.get(k).map(|s| s.1)); + commit_paint(scene, id, P_RADIAL[k], was, c, spring_c, instant); + } + } + if let Some(ol) = vis.outline { + let was = prev_vis(old_nodes, vis, old).and_then(|o| o.outline.map(|w| w.color)); + commit_paint(scene, id, P_OUTLINE, was, ol.color, spring_c, instant); + } +} + +/// True when `nodes[i]` has the same parent, frame, visual, text colour, transition and +/// resting scene state as `old_nodes[old]`, so `apply`'s per-node diff has nothing to move. +#[allow(clippy::too_many_arguments)] +pub(in crate::runtime) fn unchanged_node_resting( + tree: &types::TreeState, + scene: &Scene, + motion: &crate::runtime::tracks::MotionState, + nodes: &[Node], + i: usize, + old: Option<usize>, + scene_rect: MRect, + parent_virtual: Option<&crate::el::virtual_list::VirtualList>, + reorder_jump: impl FnOnce() -> f32, +) -> bool { + let Some(o_idx) = old else { return false }; + let o = &tree.nodes[o_idx]; + if o.is_moved_stub() { + return false; + } + let n = &nodes[i]; + let plain_cold = |nd: &Node| { + nd.cold.get().is_none_or(|c| { + c.matched.is_none() + && c.looping.is_none() + && c.live.is_empty() + && c.transition.is_none() + && c.opacity_motion.is_none() + }) + }; + n.local == o.local + && !o.scale_track + && n.static_scale == 1.0 + && !o.group_fade + && n.parent.map(|p| nodes[p].id) == o.parent.map(|p| tree.nodes[p].id) + && plain_cold(n) + && plain_cold(o) + && (motion.flying.is_empty() || !motion.flying.iter().any(|f| f.0 == n.id)) + && (tree.aspect_snap.is_empty() || !tree.aspect_snap.contains(&n.id)) + && !parent_virtual.is_some_and(crate::el::virtual_list::VirtualList::replaced_view) + && memo_reuse::same_visual(&n.vis, &o.vis) + && text_color(n) == text_color(o) + && n.text.as_ref().is_none_or(|t| { + t.reveal < 0.0 || motion.reveal_caught_up(n.id, t.content.len()) + }) + && scene.is_resting_at(n.id, scene_rect) + && (motion.stacks.is_empty() + || n.parent.is_none_or(|p| nodes[p].growth.is_none()) + || reorder_jump() == 0.0) +} + +#[cfg(test)] +#[path = "../paint_tracks_tests.rs"] +mod tests; +#[cfg(test)] +#[path = "../live_colors_tests.rs"] +mod live_colors_tests; diff --git a/app/vendor/rune/crates/rune/src/runtime/paint_probe.rs b/app/vendor/rune/crates/rune/src/runtime/paint_probe.rs new file mode 100644 index 0000000..2fea99c --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/paint_probe.rs @@ -0,0 +1,92 @@ +//! What each node paints this frame, for `rune::motion_gate`: its presented colours, corners, +//! blurs, shadow, effect payload, image and place in the paint order. +use super::*; +use crate::motion_gate::check::paint::{C_BORDER, C_FILL, C_GRADIENT, C_OUTLINE, C_SHADOW, C_TEXT, Paint, S_BACKDROP, S_BLUR, S_BORDER, S_RADIUS, S_SHADOW}; + +impl RuntimeCore { + /// Every presented node's paint, keyed by its path and whether it's leaving. Paint ranks come + /// from the last frame built once [`Runtime::paint_rank`] is on. + pub(crate) fn paints(&self) -> HashMap<(String, bool), Paint> { + let mut out = HashMap::default(); + for (i, n) in self.tree.nodes.iter().enumerate() { + let Some(p) = self.scene.presented(n.id) else { continue }; + let v = &n.vis; + let mut overlay = Color::TRANSPARENT; + let mut pointer = [0.0; 2]; + let mut over_c = |c: Color, k: f32| { + if k > 0.0 && c.a > 0.0 { overlay = unpremul(over(c.premul(k), overlay.premul(1.0))); } + }; + if v.hover().a > 0.0 || self.scene.store().is_animating(n.id, P_HOVER_C) { + pointer[0] = self.scene.get(n.id, P_HOVER).unwrap_or(0.0).clamp(0.0, 1.0); + over_c(self.color(n.id, P_HOVER_C, v.hover()), pointer[0]); + } + if v.press().a > 0.0 || self.scene.store().is_animating(n.id, P_PRESS_C) { + pointer[1] = self.scene.get(n.id, P_PRESS).unwrap_or(0.0).clamp(0.0, 1.0); + over_c(self.color(n.id, P_PRESS_C, v.press()), pointer[1]); + } + let base = self.color(n.id, P_FILL, v.fill); + let fill = unpremul(over(overlay.premul(1.0), base.premul(1.0))); + // Static fades, as they show: its own `dim` and the layer opacity of it and every + // element it sits in. + let k = v.paint_alpha + * std::iter::successors(Some(i), |&j| self.tree.nodes[j].parent).map(|j| self.tree.nodes[j].vis.layer_opacity).product::<f32>(); + let mut colors = [Color::TRANSPARENT; 6]; + colors[C_FILL] = fill.alpha(fill.a * k); + if v.border_width() > 0.0 { colors[C_BORDER] = self.color(n.id, P_BORDER, v.border()).alpha_times(k); } + // As it paints: a hovered group's `El::group_color` mixes in. + let group = self.paint.inh_scratch.get(i).map_or(0.0, |h| h.group); + if let Some(c) = paint_tracks::text_color(n) { colors[C_TEXT] = paint_tracks::group_tint(n, self.color(n.id, P_TEXT, c), group).alpha_times(k); } + // A group's hover lands its colour as the pointer moves, as a hover fill does. + if v.group_color.is_some() { pointer[0] = pointer[0].max(group); } + let mut sizes = [0.0; 5]; + sizes[S_RADIUS] = p.radius.0[0]; + sizes[S_BORDER] = v.border_width(); + sizes[S_BLUR] = self.paint.inh_scratch.get(i).map_or(p.blur, |h| h.blur); + sizes[S_BACKDROP] = v.backdrop_blur; + if let Some(sh) = v.shadows.iter().find(|s| !s.inset) { + let at = self.shadow_at(n.id, 0, sh); + colors[C_SHADOW] = self.color(n.id, P_SHADOWS[0], sh.color).alpha_times(k); + sizes[S_SHADOW] = at.blur + at.spread.abs() + at.x.abs().max(at.y.abs()); + } + let mut gradient_end = Color::TRANSPARENT; + if let Some(g) = &v.gradient { + colors[C_GRADIENT] = self.color(n.id, P_GRADIENT[0], g[0]).alpha_times(k); + gradient_end = self.color(n.id, P_GRADIENT[1], g[1]).alpha_times(k); + } else if let Some(g) = &v.radial && let (Some(first), Some(last)) = (g.stops.first(), g.stops.last()) { + colors[C_GRADIENT] = self.color(n.id, P_RADIAL[0], first.1).alpha_times(k); + let end = (g.stops.len() - 1).min(P_RADIAL.len() - 1); + gradient_end = if g.stops.len() - 1 < P_RADIAL.len() { self.color(n.id, P_RADIAL[end], last.1) } else { last.1 }.alpha_times(k); + } + if let Some(o) = v.outline.filter(|o| o.width > 0.0) { colors[C_OUTLINE] = self.color(n.id, P_OUTLINE, o.color); } + let intent = std::iter::successors(Some(i), |&j| self.tree.nodes[j].parent).fold(0u16, |bits, j| bits | self.tree.nodes[j].vis.motion_intent.bits()); + let paint = Paint { + colors, + sizes, + gradient_end, + effect: v.effect.as_ref().map(|e| e.data), + image: v.pixels.as_ref().map(crate::pixels::Pixels::signature), + rank: self.paint.paint_rank(i), + intent, + instant: n.instant_changes, + at_once: crate::motion_gate::check::paint::at_once(v.instant_motion, v.blur_motion.as_deref().map(|a| a.curve == rune_motion::Curve::Instant)), + pointer, + }; + out.entry((n.path.clone(), self.subtree_exiting(i))).or_insert(paint); + } + out + } +} + +fn unpremul([r, g, b, a]: [f32; 4]) -> Color { + if a <= 1e-6 { Color::TRANSPARENT } else { Color { r: r / a, g: g / a, b: b / a, a } } +} + +trait AlphaTimes { + fn alpha_times(self, k: f32) -> Self; +} + +impl AlphaTimes for Color { + fn alpha_times(self, k: f32) -> Color { + self.alpha(self.a * k) + } +} diff --git a/app/vendor/rune/crates/rune/src/runtime/paint_tracks_tests.rs b/app/vendor/rune/crates/rune/src/runtime/paint_tracks_tests.rs new file mode 100644 index 0000000..de46865 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/paint_tracks_tests.rs @@ -0,0 +1,154 @@ +use super::*; +use crate::{col, el, text}; + +struct State { dark: bool } + +fn view(s: &State, _: &mut Cx<State>) -> El { + let (bg, fg) = if s.dark { (Color::BLACK, Color::WHITE) } else { (Color::WHITE, Color::BLACK) }; + col().w_full().h_full().fill(bg).children((0..12).map(|i| { + el().key(format!("row-{i}")).w_full().h(20.0).fill(bg).radius(4.0).opacity(0.9) + .border(1.0, fg).shadow(2.0, 6.0, fg).outline(1.0, 1.0, fg) + .hover(fg.alpha(0.1)).press(fg.alpha(0.2)).press_scale(0.97) + .child(text(format!("row {i}")).color(fg)) + .child(el().w(8.0).h(8.0).gradient(bg, fg)) + })) +} + +fn settled(dark: bool) -> Runtime<State> { + let mut rt = Runtime::new(State { dark }, view, (200.0, 300.0), Env::new(true, 1.0)); + rt.frame(0.0); + let mut n = 0; + while n < 240 && rt.frame(1.0 / 120.0) { n += 1; } + rt.scene.frame(); + rt +} + +fn row(rt: &Runtime<State>) -> &Node { + rt.tree.nodes.iter().find(|n| n.key.as_deref() == Some("row-3")).unwrap() +} + +fn label(rt: &Runtime<State>) -> &Node { + let row = rt.tree.nodes.iter().position(|n| n.key.as_deref() == Some("row-3")).unwrap(); + rt.tree.nodes.iter().find(|n| n.parent == Some(row) && n.text.is_some()).unwrap() +} + +#[test] +fn a_static_tree_keeps_no_motion_tracks() { + let mut rt = settled(false); + assert_eq!(rt.scene.store().track_len(), 0, "nothing here has moved"); + rt.invalidate(); + rt.frame(1.0 / 120.0); + assert_eq!(rt.scene.store().track_len(), 0, "an unchanged rebuild makes none either"); +} + +#[test] +fn an_unchanged_commit_leaves_the_scene_clean() { + let mut rt = settled(false); + let tx = rt.transaction(); + rt.commit(&tx); + assert!(rt.scene.frame().changed.is_empty(), "no node presents again"); +} + +#[test] +fn a_first_colour_change_still_crossfades_from_the_drawn_colour() { + let mut rt = settled(false); + rt.update(|s, _| s.dark = true); + rt.frame(1.0 / 120.0); + rt.frame(1.0 / 120.0); + let n = row(&rt); + let fill = rt.color(n.id, P_FILL, n.vis.fill); + assert!(fill.r < 1.0 && fill.r > 0.0, "the fill is between white and black: {fill:?}"); + let l = label(&rt); + let text = rt.color(l.id, P_TEXT, l.text.as_ref().unwrap().color); + assert!(text.r > 0.0 && text.r < 1.0, "the text is between black and white: {text:?}"); + let border = rt.color(n.id, P_BORDER, n.vis.border()); + assert!(border.r > 0.0 && border.r < 1.0, "the border is between black and white: {border:?}"); + let shadow = rt.color(n.id, P_SHADOWS[0], n.vis.shadows[0].color); + assert!(shadow.r > 0.0 && shadow.r < 1.0, "the shadow is between black and white: {shadow:?}"); + let mut k = 0; + while k < 240 && rt.frame(1.0 / 120.0) { k += 1; } + let n = row(&rt); + assert_eq!(rt.color(n.id, P_FILL, n.vis.fill), Color::BLACK); + assert_eq!(rt.color(n.id, P_BORDER, n.vis.border()), Color::WHITE); +} + +#[test] +fn an_instant_colour_change_lands_without_a_track() { + let mut rt = settled(false); + rt.update(|s, tx| { s.dark = true; tx.instant(); }); + rt.frame(1.0 / 120.0); + let n = row(&rt); + assert_eq!(rt.color(n.id, P_FILL, n.vis.fill), Color::BLACK); + assert_eq!(rt.scene.store().track_len(), 0); +} + +#[test] +fn rebuilding_reuses_node_paths_and_restores_on_layout_retry() { + #[derive(Default)] + struct RetryState { open: bool, tick: u32 } + fn retry_view(s: &RetryState, cx: &mut Cx<RetryState>) -> El { + let measured = cx.layout_size("box").map_or(10.0, |[w, _]| w * 0.5); + let mut sheet = crate::row().key("sheet").w(60.0).h(40.0); + if s.open { + sheet = sheet + .child(el().key("btn").w(30.0).h(20.0).focusable(true)) + .child(el().size(0.0, 0.0).focus_return("anchor")); + } + col().w_full().h_full() + .child(el().key("box").w(if s.tick == 0 { 80.0 } else { 120.0 }).h(measured).child(text(format!("{}", s.tick)))) + .child(el().key("anchor").w(40.0).h(20.0).focusable(true)) + .child(sheet) + } + let mut rt = Runtime::new(RetryState { open: true, tick: 0 }, retry_view, (200.0, 200.0), Env::new(true, 1.0)); + rt.frame(0.0); + let ptr0 = rt.tree.nodes.iter().find(|n| n.key.as_deref() == Some("anchor")).unwrap().path.as_ptr(); + rt.invalidate(); + rt.frame(1.0 / 120.0); + let ptr1 = rt.tree.nodes.iter().find(|n| n.key.as_deref() == Some("anchor")).unwrap().path.as_ptr(); + assert_eq!(ptr0, ptr1, "steady-state rebuild moves the previous commit's path String in place"); + + // Trigger both a layout-read settle retry (`tick = 1` changes `box` width) and `return_focus_to` + // under `sheet` (whose own path was moved on the previous commit). + let btn_path = rt.tree.nodes.iter().find(|n| n.key.as_deref() == Some("btn")).unwrap().path.clone(); + rt.kbd.focus.focus = crate::runtime::focus_machine::Focus::On { path: btn_path, hovered: false, from: None }; + rt.update(|s, _| { s.open = false; s.tick = 1; }); + rt.frame(1.0 / 120.0); + let anchor_path = rt.tree.nodes.iter().find(|n| n.key.as_deref() == Some("anchor")).unwrap().path.clone(); + assert_eq!(rt.kbd.focus.path(), Some(anchor_path.as_str())); +} + +#[test] +fn changing_one_sibling_skips_resting_siblings_without_drift() { + struct SibState { active: usize } + fn sib_view(s: &SibState, _: &mut Cx<SibState>) -> El { + col().w_full().h_full().children((0..8).map(|i| { + let fg = if i == s.active { Color::WHITE } else { Color::BLACK }; + el().key(format!("r-{i}")).w_full().h(20.0).fill(fg).hover(fg.alpha(0.2)).focusable(true) + .child(text(format!("item {i}")).color(fg)) + })) + } + let mut rt = Runtime::new(SibState { active: 0 }, sib_view, (200.0, 200.0), Env::new(true, 1.0)); + rt.frame(0.0); + while rt.frame(1.0 / 120.0) {} + rt.pointer_move(20.0, 70.0); // hover row 3 + rt.frame(1.0 / 120.0); + while rt.frame(1.0 / 120.0) {} + + rt.update(|s, _| s.active = 5); + rt.frame(1.0 / 120.0); + let r5 = rt.tree.nodes.iter().find(|n| n.key.as_deref() == Some("r-5")).unwrap().id; + let r2 = rt.tree.nodes.iter().find(|n| n.key.as_deref() == Some("r-2")).unwrap().id; + assert!(rt.scene.store().is_node_animating(r5), "changed sibling animates its colour"); + assert!(!rt.scene.store().is_node_animating(r2), "unchanged sibling stays at rest with no track"); + while rt.frame(1.0 / 120.0) {} + + let mut fresh = Runtime::new(SibState { active: 5 }, sib_view, (200.0, 200.0), Env::new(true, 1.0)); + fresh.frame(0.0); + while fresh.frame(1.0 / 120.0) {} + for k in 0..8 { + let key = format!("r-{k}"); + let na = rt.tree.nodes.iter().find(|n| n.key.as_deref() == Some(key.as_str())).unwrap(); + let nb = fresh.tree.nodes.iter().find(|n| n.key.as_deref() == Some(key.as_str())).unwrap(); + assert_eq!(rt.color(na.id, P_FILL, na.vis.fill), fresh.color(nb.id, P_FILL, nb.vis.fill)); + } +} diff --git a/app/vendor/rune/crates/rune/src/runtime/pixel_snap_tests.rs b/app/vendor/rune/crates/rune/src/runtime/pixel_snap_tests.rs new file mode 100644 index 0000000..1112873 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/pixel_snap_tests.rs @@ -0,0 +1,614 @@ +use super::*; +use crate::render::{Gpu, KIND_GLYPH, KIND_RECT, Offscreen, Renderer}; +use crate::{Color, Cx, El, Env, Runtime, col, el, row, text}; + +const FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Rgba8Unorm; + +fn snap(r: [f32; 4], motion: [f32; 4], rigid: [f32; 2]) -> [f32; 4] { + super::pixel_snap::snap(r, motion, rigid, None, |_, c| c).0 +} + +/// The alpha channel of a headless 2× render of `view`, `w` × `h` points, row-major. +fn coverage<S: 'static>(state: S, view: fn(&S, &mut Cx<S>) -> El, w: u32, h: u32) -> Vec<u8> { + render(state, view, w, h, 2.0).chunks(4).map(|p| p[3]).collect() +} + +/// A headless RGBA render of `view`, `w` × `h` points at `scale`, row-major. +fn render<S: 'static>(state: S, view: fn(&S, &mut Cx<S>) -> El, w: u32, h: u32, scale: f32) -> Vec<u8> { + let gpu = Gpu::headless(); + let mut renderer = Renderer::new(&gpu.device, FORMAT); + let (dw, dh) = ((w as f32 * scale) as u32, (h as f32 * scale) as u32); + let target = Offscreen::with_format(&gpu.device, dw, dh, FORMAT); + let mut rt = Runtime::new(state, view, (w as f32, h as f32), Env::new(true, scale)); + rt.frame(0.0); + renderer.prepare(&gpu.device, &gpu.queue, &mut rt.text.atlas, &rt.instances, (dw, dh)); + let mut enc = gpu.device.create_command_encoder(&Default::default()); + renderer.draw(&mut enc, &target.view, [0.0; 4]); + target.copy(&mut enc); + renderer.submit(&gpu.queue, enc); + target.read(&gpu.device) +} + +fn fills<S: 'static>(rt: &Runtime<S>) -> Vec<[f32; 4]> { + rt.instances.iter().filter(|i| i.params[1] == KIND_RECT && i.fill[3] > 0.0).map(|i| i.rect).collect() +} + +fn whole(v: f32) -> bool { + v.fract() == 0.0 +} + +#[test] +fn shared_edges_round_alike() { + let a = snap([0.0, 10.3, 50.0, 30.5], [0.0; 4], [0.0; 2]); + let b = snap([0.0, 30.5, 50.0, 52.7], [0.0; 4], [0.0; 2]); + assert_eq!(a[3], b[1]); + assert_eq!(a, [0.0, 10.0, 50.0, 31.0]); +} + +#[test] +fn keeps_a_pixel_and_thin_rects() { + let s = snap([0.0, 4.6, 9.0, 5.4], [0.0; 4], [0.0; 2]); + assert_eq!((s[1], s[3]), (5.0, 6.0)); + let thin = snap([0.0, 4.6, 9.0, 4.9], [0.0; 4], [0.0; 2]); + assert_eq!((thin[1], thin[3]), (4.6, 4.9)); +} + +#[test] +fn motion_carries_the_resting_correction() { + // Resting at y 10.3..20.3, snapped to 10..20: the -0.3 rides along the flight. + let moving = snap([0.0, 15.55, 9.0, 25.55], [0.0, 5.25, 0.0, 5.25], [0.0; 2]); + assert!((moving[1] - 15.25).abs() < 1e-4 && (moving[3] - 25.25).abs() < 1e-4); +} + +#[test] +fn rigid_translation_snaps_as_one() { + // Two rows 2.2 px apart, scrolled: the gap is the same whole number at every offset. + for k in 0..64 { + let d = -(k as f32) * 0.37; + let a = snap([0.0, 10.0 + d, 9.0, 20.0 + d], [0.0; 4], [0.0, d]); + let b = snap([0.0, 22.2 + d, 9.0, 32.2 + d], [0.0; 4], [0.0, d]); + assert_eq!(b[1] - a[3], 2.0); + assert!(whole(a[1])); + } +} + +fn gap_column(on: &bool, _: &mut Cx<bool>) -> El { + let rows = (0..6).map(|_| el().size(20.0, 7.3).fill(Color::WHITE)); + col().gap(1.1).padding(0.3).pixel_snap(*on).children(rows) +} + +#[test] +fn rows_with_a_fractional_gap_have_hard_edges() { + for on in [true, false] { + let a = coverage(on, gap_column, 24, 52); + let column: Vec<u8> = (0..104).map(|y| a[y * 48 + 10]).collect(); + let soft = column.iter().filter(|&&v| v > 1 && v < 254).count(); + if on { + assert_eq!(soft, 0, "{column:?}"); + // Six rows, each separated by a visible gap. + let starts = column.windows(2).filter(|w| w[0] < 128 && w[1] >= 128).count() + (column[0] >= 128) as usize; + assert_eq!(starts, 6, "{column:?}"); + } else { + assert!(soft > 0, "the opt-out still paints at fractional edges"); + } + } +} + +#[test] +fn layout_and_drawn_rects_stay_fractional() { + let mut rt = Runtime::new(true, gap_column, (24.0, 52.0), Env::new(true, 2.0)); + rt.frame(0.0); + let rows: Vec<_> = rt.elements().into_iter().filter(|e| (e.rect[3] - 7.3).abs() < 0.02).collect(); + assert_eq!(rows.len(), 6); + for (k, e) in rows.iter().enumerate() { + let y = 0.3 + k as f32 * 8.4; + assert!((e.rect[1] - y).abs() < 1.0 / 64.0, "row {k}: {:?} vs {y}", e.rect); + } + // What paints is on whole pixels. + for r in fills(&rt) { + assert!(r.iter().all(|&v| whole(v)), "{r:?}"); + } +} + +#[test] +fn adjacent_boxes_meet_without_a_seam() { + fn view(_: &(), _: &mut Cx<()>) -> El { + row().padding(0.35).children((0..5).map(|_| el().size(7.15, 10.0).fill(Color::WHITE))) + } + let a = coverage((), view, 40, 12); + let line = &a[12 * 80..13 * 80]; + let lit: Vec<usize> = (0..80).filter(|&x| line[x] > 0).collect(); + let (first, last) = (lit[0], *lit.last().unwrap()); + assert!(line[first..=last].iter().all(|&v| v == 255), "{line:?}"); + assert!(line.iter().all(|&v| v == 0 || v == 255), "{line:?}"); +} + +#[test] +fn hairline_border_is_one_crisp_pixel() { + fn view(_: &(), _: &mut Cx<()>) -> El { + el().size(32.0, 32.0).child(el().absolute(3.3, 4.15).size(20.3, 12.45).border(0.5, Color::WHITE)) + } + let a = coverage((), view, 32, 32); + let column: Vec<u8> = (0..64).map(|y| a[y * 64 + 20]).collect(); + assert!(column.iter().all(|&v| v <= 1 || v >= 254), "{column:?}"); + assert_eq!(column.iter().filter(|&&v| v >= 254).count(), 2, "{column:?}"); +} + +#[test] +fn an_opted_out_element_paints_its_exact_offset() { + fn view(on: &bool, _: &mut Cx<bool>) -> El { + el().size(40.0, 40.0).child(el().size(10.0, 10.0).offset(3.3, 2.15).pixel_snap(*on).fill(Color::WHITE)) + } + for on in [true, false] { + let mut rt = Runtime::new(on, view, (40.0, 40.0), Env::new(true, 2.0)); + rt.frame(0.0); + let r = fills(&rt)[0]; + if on { + assert_eq!([r[0], r[1]], [7.0, 4.0], "{r:?}"); + } else { + assert!((r[0] - 6.6).abs() < 1.0 / 32.0 && (r[1] - 4.3).abs() < 1.0 / 32.0, "{r:?}"); + } + } +} + +#[test] +fn a_moving_element_glides_and_lands_snapped() { + fn view(down: &bool, _: &mut Cx<bool>) -> El { + let y = if *down { 10.3 } else { 0.0 }; + el().size(40.0, 40.0) + .child(el().size(10.0, 10.0).absolute(1.15, 1.15).offset(0.0, y).offset_motion(Spring::new(0.4, 0.0)).fill(Color::WHITE)) + } + let mut rt = Runtime::new(false, view, (40.0, 40.0), Env::new(true, 2.0)); + rt.frame(0.0); + assert_eq!(fills(&rt)[0][1], 2.0); + rt.state = true; + rt.invalidate(); + let mut ys = Vec::new(); + for _ in 0..120 { + rt.frame(1.0 / 120.0); + ys.push(fills(&rt)[0][1]); + } + let end = *ys.last().unwrap(); + assert_eq!(end, 23.0, "lands on the snapped resting pixel"); + // It starts where it was: the first frame moves it about as far as the spring does (0.17 px). + assert!(ys[0] - 2.0 < 0.25, "{ys:?}"); + assert!(ys.iter().any(|&y| !whole(y)), "glides between pixels: {ys:?}"); + // A spring that eases out never jumps: each step is no bigger than the one before. + let steps: Vec<f32> = ys.windows(2).map(|w| w[1] - w[0]).collect(); + let peak = steps.iter().cloned().fold(0.0, f32::max); + let after = steps.iter().position(|&d| d == peak).unwrap(); + for w in steps[after..].windows(2) { + assert!(w[1] <= w[0] + 1.0 / 32.0 && w[1] >= -1.0 / 32.0, "{steps:?}"); + } +} + +#[test] +fn text_keeps_its_place_against_its_fill() { + fn view(y: &f32, _: &mut Cx<f32>) -> El { + el().size(80.0, 40.0).child(text("Hg").padding(2.3).absolute(4.0, *y).fill(Color::WHITE.mix(Color::BLACK, 0.8))) + } + let place = |y: f32| { + let mut rt = Runtime::new(y, view, (80.0, 40.0), Env::new(true, 2.0)); + rt.frame(0.0); + let fill = fills(&rt)[0]; + let glyph = rt.instances.iter().filter(|i| i.params[1] == KIND_GLYPH).map(|i| i.rect[1]).fold(f32::MAX, f32::min); + assert!(glyph < f32::MAX, "draws glyphs"); + (glyph, fill[1]) + }; + // The fill snaps to whole pixels. The text lays out from its box's exact place and rounds + // once, as Blink paints a text fragment (#935), so it keeps its place against where its box + // is rather than its snapped fill: half a point (a device pixel) further down, it draws one + // pixel lower, at every phase; and between, it steps at most a pixel, never back. + for k in 0..10 { + let y = 10.0 + k as f32 * 0.05; + let ((glyph, top), (next, _), (lower, _)) = (place(y), place(y + 0.05), place(y + 0.5)); + assert!(whole(top), "{top}"); + assert_eq!(lower, glyph + 1.0, "y {y}: a device pixel lower draws a pixel lower"); + assert!(next == glyph || next == glyph + 1.0, "y {y}: {glyph} then {next}"); + } +} + +#[test] +fn scrolled_rows_stay_crisp_and_keep_their_spacing() { + fn view(_: &(), _: &mut Cx<()>) -> El { + col().size(40.0, 60.0).gap(1.1).scroll(crate::el::ScrollSpec { stick_bottom: false }) + .children((0..20).map(|i| el().key(format!("r{i}")).size(20.0, 7.3).fill(Color::WHITE))) + } + let mut rt = Runtime::new((), view, (40.0, 60.0), Env::new(true, 2.0)); + rt.frame(0.0); + let pitch = |rt: &Runtime<()>| fills(rt).windows(2).map(|w| w[1][1] - w[0][1]).collect::<Vec<_>>(); + let want = pitch(&rt); + let mut fractional = false; + for _ in 0..12 { + rt.wheel(20.0, 30.0, -0.37); + rt.frame(1.0 / 120.0); + let r0 = rt.elements().into_iter().find(|e| e.key.as_deref() == Some("r0")).unwrap().rect; + fractional |= !whole(r0[1] * 2.0); + assert!(fills(&rt).iter().all(|r| r.iter().all(|&v| whole(v))), "{:?}", fills(&rt)); + assert_eq!(pitch(&rt), want); + } + assert!(fractional, "scrolled by fractional pixels"); +} + +#[test] +fn a_scale_settling_at_one_lands_snapped_without_a_jump() { + fn view(big: &bool, _: &mut Cx<bool>) -> El { + let k = if *big { 1.0 } else { 0.8 }; + el().size(60.0, 60.0) + .child(el().size(20.3, 20.3).absolute(10.15, 10.15).scale(k).scale_motion(Spring::new(0.4, 0.0)).fill(Color::WHITE)) + } + let mut rt = Runtime::new(false, view, (60.0, 60.0), Env::new(true, 2.0)); + rt.frame(0.0); + rt.state = true; + rt.invalidate(); + let mut frames = Vec::new(); + for _ in 0..120 { + rt.frame(1.0 / 120.0); + frames.push(fills(&rt)[0]); + } + let end = *frames.last().unwrap(); + assert!(end.iter().all(|&v| whole(v)), "lands on whole pixels: {end:?}"); + // Each edge eases in: once the scale is nearly done, no frame moves an edge further than the + // frame before it did. + for k in 0..2 { + let steps: Vec<f32> = frames.windows(2).map(|w| (w[1][k] - w[0][k]).abs()).collect(); + let tail = &steps[steps.len() / 3..]; + for w in tail.windows(2) { + assert!(w[1] <= w[0] + 1.0 / 32.0, "edge {k}: {steps:?}"); + } + } +} + +#[test] +fn a_trailing_child_holds_its_place_against_a_widening_parent() { + fn view(wide: &bool, _: &mut Cx<bool>) -> El { + let w = if *wide { 50.7 } else { 30.3 }; + el().size(80.0, 20.0).child( + el().size(w, 12.0).absolute(3.15, 2.0).fill(Color::WHITE.mix(Color::BLACK, 0.5)) + .child(el().size(6.0, 6.0).absolute(w - 9.15, 3.0).ride_trailing().fill(Color::WHITE)), + ) + } + let mut rt = Runtime::new(false, view, (80.0, 20.0), Env::new(true, 2.0)); + rt.frame(0.0); + let gap = |f: &[[f32; 4]]| (f[0][0] + f[0][2]) - (f[1][0] + f[1][2]); + let before = gap(&fills(&rt)); + rt.state = true; + rt.invalidate(); + let (mut moved, mut last) = (false, before); + let mut gaps = Vec::new(); + for _ in 0..120 { + rt.frame(1.0 / 120.0); + let f = fills(&rt); + moved |= f[0][2] != 61.0 && f[0][2] != 101.0; + gaps.push(gap(&f)); + // The child glides with the parent's edge: their gap eases between its two resting + // roundings, never stepping a pixel at once. + assert!((gap(&f) - last).abs() < 0.25, "{gaps:?}"); + last = gap(&f); + } + assert!(moved, "the parent's width animates"); + let f = fills(&rt); + assert!(f.iter().flatten().all(|&v| whole(v)), "{f:?}"); +} + +/// A zoomed canvas (`El::scale`) with boxes at fractional places, snapping or not. +fn canvas(st: &(f32, bool), _: &mut Cx<(f32, bool)>) -> El { + let boxes = (0..4).map(|i| el().size(17.3, 11.1).absolute(3.3 + i as f32 * 21.7, 5.45 + i as f32 * 9.2).fill(Color::WHITE)); + el().size(160.0, 120.0).child( + el().size(100.3, 70.15).absolute(20.15, 15.3).scale(st.0).pixel_snap(st.1) + .fill(Color::WHITE.mix(Color::BLACK, 0.5)).children(boxes), + ) +} + +fn edges(f: &[[f32; 4]]) -> Vec<f32> { + f.iter().flat_map(|r| [r[0], r[1], r[0] + r[2], r[1] + r[3]]).collect() +} + +#[test] +fn a_still_zoomed_canvas_draws_on_whole_pixels() { + for on in [true, false] { + let mut rt = Runtime::new((1.37, on), canvas, (160.0, 120.0), Env::new(true, 2.0)); + rt.frame(0.0); + let e = edges(&fills(&rt)); + assert_eq!(e.len(), 20); + if on { + assert!(e.iter().all(|&v| whole(v)), "{e:?}"); + } else { + assert!(e.iter().any(|&v| !whole(v)), "the opt-out draws at the exact scaled edges: {e:?}"); + } + } +} + +#[test] +fn a_zoom_draws_exact_while_it_moves_and_eases_onto_the_grid() { + let mut snapped = Runtime::new((1.2, true), canvas, (160.0, 120.0), Env::new(true, 2.0)); + let mut exact = Runtime::new((1.2, false), canvas, (160.0, 120.0), Env::new(true, 2.0)); + snapped.frame(0.0); + exact.frame(0.0); + // A pinch: the zoom lands at once on every frame for 30 frames, then holds. + let mut frames = Vec::new(); + for k in 1..=80 { + if k <= 30 { + let z = 1.2 + 0.17 * k as f32 / 30.0; + for rt in [&mut snapped, &mut exact] { + rt.update(|st, tx| { + st.0 = z; + tx.instant(); + }); + } + } + let asks = snapped.frame(1.0 / 120.0); + exact.frame(1.0 / 120.0); + let (a, b) = (edges(&fills(&snapped)), edges(&fills(&exact))); + // Once each box has moved a pixel, the zoom draws at its exact sub-pixel edges. + if (8..=30).contains(&k) { + assert!(a.iter().zip(&b).all(|(a, b)| (a - b).abs() < 1.0 / 64.0), "frame {k}: {a:?} vs {b:?}"); + } + assert!(a.iter().zip(&b).all(|(a, b)| (a - b).abs() <= 0.5 + 1.0 / 64.0), "frame {k}: {a:?} vs {b:?}"); + frames.push((a, asks)); + } + // Held still, it eases onto whole pixels within a few frames and then stops asking for them. + let (end, asks) = frames.last().unwrap(); + assert!(end.iter().all(|&v| whole(v)), "{end:?}"); + assert!(!asks, "an idle canvas draws nothing"); + let landed = frames.iter().position(|(e, _)| e.iter().all(|&v| whole(v))).unwrap(); + assert!(landed <= 30 + 16, "lands {} frames after the zoom stops", landed + 1 - 30); + assert!(frames[30..landed].iter().all(|(_, asks)| *asks), "asks for each frame of the ease"); + // No pop: once the zoom stops, no edge moves more than the ease's steepest step. + for w in frames[29..].windows(2) { + let step = w[0].0.iter().zip(&w[1].0).map(|(a, b)| (a - b).abs()).fold(0.0, f32::max); + assert!(step < 0.07, "{step}: {:?} -> {:?}", w[0].0, w[1].0); + } +} + +#[test] +fn a_scale_spring_glides_exact_and_lands_snapped() { + fn view(big: &bool, _: &mut Cx<bool>) -> El { + let k = if *big { 1.37 } else { 1.0 }; + el().size(160.0, 120.0).child( + el().size(60.3, 40.15).absolute(40.15, 35.3).scale(k).scale_motion(Spring::new(0.4, 0.0)).fill(Color::WHITE) + .child(el().size(17.3, 11.1).absolute(13.3, 9.45).fill(Color::BLACK)), + ) + } + let mut rt = Runtime::new(false, view, (160.0, 120.0), Env::new(true, 2.0)); + rt.frame(0.0); + rt.state = true; + rt.invalidate(); + let mut frames = Vec::new(); + for _ in 0..160 { + rt.frame(1.0 / 120.0); + frames.push(edges(&fills(&rt))); + } + let end = frames.last().unwrap(); + assert!(end.iter().all(|&v| whole(v)), "lands on whole pixels: {end:?}"); + let fractional = frames.iter().filter(|e| e.iter().any(|&v| !whole(v))).count(); + assert!(fractional > 20, "glides between pixels while it scales ({fractional} frames)"); + // Each edge eases in: once the spring is nearly done, no frame moves an edge further than + // the frame before it did, beyond the ease onto the grid. + for k in 0..end.len() { + let steps: Vec<f32> = frames.windows(2).map(|w| (w[1][k] - w[0][k]).abs()).collect(); + for w in steps[steps.len() / 3..].windows(2) { + assert!(w[1] <= w[0] + 0.07, "edge {k}: {steps:?}"); + } + } +} + +/// A zoomed canvas (`zoom`, scaled about `origin`) with boxes across it, some straddling the +/// point it scales about, and an overlay layer on top scaled about the window's centre and +/// shifted to line up, outlining each box: art and outlines drawn by two layers anchored apart. +#[derive(Clone, Copy)] +struct Anchored { + zoom: f32, + snap: bool, + origin: [f32; 2], + overlay: bool, +} + +const CANVAS: [f32; 4] = [20.15, 15.3, 100.3, 70.15]; + +fn anchored(st: &Anchored, _: &mut Cx<Anchored>) -> El { + let spots = [(41.3, 29.45), (45.85, 31.2), (3.3, 5.45), (70.1, 48.35), (12.6, 50.9), (0.0, 0.0)]; + let boxes = |dx: f32, dy: f32| spots.map(|(x, y)| el().size(17.3, 11.1).absolute(x + dx, y + dy).fill(Color::WHITE)); + let [cx, cy, cw, ch] = CANVAS; + let mut root = el().size(160.0, 120.0).child( + el().size(cw, ch).absolute(cx, cy).scale(st.zoom).origin(st.origin[0], st.origin[1]).pixel_snap(st.snap).children(boxes(0.0, 0.0)), + ); + if st.overlay { + // Scaled about (80, 60) and shifted so it maps a point the way the canvas does. + let pivot = [cx + cw * st.origin[0], cy + ch * st.origin[1]]; + let off = [(pivot[0] - 80.0) * (1.0 - st.zoom), (pivot[1] - 60.0) * (1.0 - st.zoom)]; + root = root.child(el().size(160.0, 120.0).absolute(0.0, 0.0).scale(st.zoom).offset(off[0], off[1]).pixel_snap(st.snap).children(boxes(cx, cy))); + } + root +} + +fn pinch(rts: &mut [&mut Runtime<Anchored>], k: usize) { + if k <= 30 { + let z = 1.2 + 0.17 * k as f32 / 30.0; + for rt in rts.iter_mut() { + rt.update(|st, tx| { + st.zoom = z; + tx.instant(); + }); + } + } + for rt in rts.iter_mut() { + rt.frame(1.0 / 120.0); + } +} + +#[test] +fn outlines_on_a_layer_anchored_elsewhere_stay_on_the_art() { + for origin in [[0.5, 0.5], [0.0, 0.0], [0.41, 0.62], [3.0, -2.0]] { + let mut rt = Runtime::new(Anchored { zoom: 1.2, snap: true, origin, overlay: true }, anchored, (160.0, 120.0), Env::new(true, 2.0)); + rt.frame(0.0); + for k in 1..=80 { + pinch(&mut [&mut rt], k); + let e = edges(&fills(&rt)); + let (art, outline) = e.split_at(e.len() / 2); + // Each layer lands a box's exact edges on the 1/64 px quantum through its own sums, + // so they can sit a quantum apart, and so can how far each says the box has moved. + let worst = art.iter().zip(outline).map(|(a, b)| (a - b).abs()).fold(0.0, f32::max); + assert!(worst <= 1.0 / 32.0, "origin {origin:?}, frame {k}: off by {worst}: {art:?} vs {outline:?}"); + if k == 80 { + assert!(e.iter().all(|&v| whole(v)), "origin {origin:?}: {e:?}"); + } + } + } +} + +/// rune-kit's Small switch: a 16 pt knob inset 2 pt in a 20 pt track, `y` points down, the knob +/// `offset` points below its rest. +fn knob(&(y, offset): &(f32, f32), _: &mut Cx<(f32, f32)>) -> El { + let knob = el().size(26.0, 16.0).absolute(2.0, 2.0).offset(0.0, offset).offset_motion(Spring::new(0.4, 0.0)); + el().size(80.0, 60.0).child(el().size(44.0, 20.0).absolute(3.0, y).fill(Color::BLACK).child(knob.fill(Color::WHITE))) +} + +/// The gaps above and below the knob in its track (device px). +fn knob_gaps(f: &[[f32; 4]]) -> [f32; 2] { + let (track, knob) = (f[0], f[1]); + [knob[1] - track[1], (track[1] + track[3]) - (knob[1] + knob[3])] +} + +#[test] +fn a_centred_knob_keeps_even_gaps_at_fractional_scales() { + // 2 pt is 2.5 px at 1.25×: each edge rounding on its own put the knob 2 px from one edge + // and 3 px from the other. + for scale in [1.25, 1.5, 1.75, 2.0] { + let mut heights = std::collections::HashSet::new(); + for k in 0..64 { + let y = 10.0 + k as f32 / 16.0; + let mut rt = Runtime::new((y, 0.0), knob, (80.0, 60.0), Env::new(true, scale)); + rt.frame(0.0); + let f = fills(&rt); + let [above, below] = knob_gaps(&f); + assert_eq!(above, below, "{scale}× at y {y}: {f:?}"); + assert!(f.iter().flatten().all(|&v| whole(v)), "{scale}× at y {y}: {f:?}"); + heights.insert(f[1][3] as u32); + } + assert_eq!(heights.len(), 1, "{scale}×: the knob draws one height wherever it sits: {heights:?}"); + } +} + +#[test] +fn a_centred_knob_draws_even_gaps_in_device_pixels_at_1_25x() { + // Where an app's Small switch sat: the track 559.25 pt down is 699.0625 px, as 11.25 pt is. + let rgba = render((11.25, 0.0), knob, 80, 60, 1.25); + let column: Vec<[u8; 4]> = (0..75).map(|y| { + let i = (y * 100 + 22) * 4; + [rgba[i], rgba[i + 1], rgba[i + 2], rgba[i + 3]] + }).collect(); + let track: Vec<usize> = (0..75).filter(|&y| column[y][3] == 255).collect(); + let knob: Vec<usize> = (0..75).filter(|&y| column[y][0] == 255).collect(); + assert!(column.iter().all(|p| p[3] == 0 || p[3] == 255), "hard edges: {column:?}"); + let (above, below) = (knob[0] - track[0], track.last().unwrap() - knob.last().unwrap()); + assert_eq!((track.len(), above, below), (25, 3, 3), "{column:?}"); +} + +#[test] +fn an_unpainted_parent_leaves_a_centred_child_its_size() { + // Nothing shows the gaps to a parent that paints nothing, so the child keeps its own + // rounding: 20 pt is 25 px at 1.25× wherever it sits. + fn view(y: &f32, _: &mut Cx<f32>) -> El { + el().size(80.0, 60.0).child(el().size(44.0, 22.0).absolute(3.0, *y).child(el().size(44.0, 20.0).absolute(0.0, 1.0).fill(Color::WHITE))) + } + for k in 0..16 { + let y = 10.0 + k as f32 / 16.0; + let mut rt = Runtime::new(y, view, (80.0, 60.0), Env::new(true, 1.25)); + rt.frame(0.0); + assert_eq!(fills(&rt)[0][3], 25.0, "y {y}"); + } +} + +#[test] +fn a_knob_glides_into_and_out_of_its_centred_rest() { + let mut rt = Runtime::new((11.25, 0.0), knob, (80.0, 60.0), Env::new(true, 1.25)); + rt.frame(0.0); + for offset in [3.1, 0.0] { + let before = fills(&rt)[1]; + rt.state.1 = offset; + rt.invalidate(); + let mut bottoms = vec![before[1] + before[3]]; + for _ in 0..120 { + rt.frame(1.0 / 120.0); + let k = fills(&rt)[1]; + bottoms.push(k[1] + k[3]); + } + // The spring's own first step is about 0.2 px: no edge steps a pixel at either end. + let steps: Vec<f32> = bottoms.windows(2).map(|w| (w[1] - w[0]).abs()).collect(); + assert!(steps[0] < 0.3 && steps[steps.len() - 20..].iter().all(|&d| d < 0.1), "{bottoms:?}"); + let f = fills(&rt); + assert!(f.iter().flatten().all(|&v| whole(v)), "lands snapped: {f:?}"); + if offset == 0.0 { + let [above, below] = knob_gaps(&f); + assert_eq!(above, below, "{f:?}"); + } + } +} + +#[test] +fn a_knob_keeps_even_gaps_while_its_track_slides() { + fn view(slide: &f32, _: &mut Cx<f32>) -> El { + let knob = el().size(26.0, 16.0).absolute(2.0, 2.0).fill(Color::WHITE); + let track = el().size(44.0, 20.0).absolute(3.0, 11.25).offset(0.0, *slide).offset_motion(Spring::new(0.4, 0.0)); + el().size(80.0, 60.0).child(track.fill(Color::BLACK).child(knob)) + } + let mut rt = Runtime::new(0.0, view, (80.0, 60.0), Env::new(true, 1.25)); + rt.frame(0.0); + for slide in [7.3, 0.0] { + rt.state = slide; + rt.invalidate(); + let mut tops = vec![fills(&rt)[1][1]]; + for _ in 0..120 { + rt.frame(1.0 / 120.0); + let f = fills(&rt); + let [above, below] = knob_gaps(&f); + assert!((above - below).abs() < 1e-3, "{f:?}"); + tops.push(f[1][1]); + } + let steps: Vec<f32> = tops.windows(2).map(|w| (w[1] - w[0]).abs()).collect(); + assert!(steps[0] < 0.3 && steps[steps.len() - 20..].iter().all(|&d| d < 0.1), "{tops:?}"); + assert!(fills(&rt).iter().flatten().all(|&v| whole(v))); + } +} + +/// A 16 pt knob centred in a track `h` points tall, growing around the knob's centre. +fn growing(h: &f32, _: &mut Cx<f32>) -> El { + let knob = el().size(26.0, 16.0).absolute(2.0, (h - 16.0) / 2.0).fill(Color::WHITE); + el().size(80.0, 60.0).child(el().size(44.0, *h).absolute(3.0, 11.25 - (h - 20.0) / 2.0).fill(Color::BLACK).child(knob)) +} + +#[test] +fn a_still_knob_eases_with_its_track_growing_around_it() { + // The knob doesn't move, but its centred rounding changes: it goes with the track's glide + // rather than jump at the start, and starts over from where it is when the track retargets. + for retarget in [None, Some(10)] { + let mut rt = Runtime::new(20.0, growing, (80.0, 60.0), Env::new(true, 1.25)); + rt.frame(0.0); + let start = fills(&rt)[1]; + rt.state = 20.8; + rt.invalidate(); + let mut knobs = vec![start]; + for i in 0..120 { + if retarget == Some(i) { + rt.state = 22.4; + rt.invalidate(); + } + rt.frame(1.0 / 120.0); + knobs.push(fills(&rt)[1]); + } + settles_without_a_jump(&rt, &knobs, start); + } +} + +fn settles_without_a_jump(rt: &Runtime<f32>, knobs: &[[f32; 4]], start: [f32; 4]) { + let edges = |k: &[f32; 4]| [k[1], k[1] + k[3]]; + for w in knobs.windows(2) { + let (a, b) = (edges(&w[0]), edges(&w[1])); + assert!((0..2).all(|i| (a[i] - b[i]).abs() < 0.3), "{knobs:?}"); + } + let f = fills(rt); + let [above, below] = knob_gaps(&f); + assert!(above == below && f.iter().flatten().all(|&v| whole(v)), "{f:?}"); + assert_ne!(edges(&start), edges(knobs.last().unwrap()), "the knob's rounding changes"); +} diff --git a/app/vendor/rune/crates/rune/src/runtime/playground.rs b/app/vendor/rune/crates/rune/src/runtime/playground.rs new file mode 100644 index 0000000..e398e1d --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/playground.rs @@ -0,0 +1,277 @@ +//! The runtime's side of [`App::playground`](crate::App::playground): its keys, its requests, +//! and what a new stage leaves behind. + +use super::*; +use crate::playground::{FILTER, Moved, Nav, Region, Request}; + +impl RuntimeCore { + /// The node the app's view returned: the first, or with the playground attached, the one + /// above its bar or on its stage. Root handlers (window focus, paste, file drops) are there. + #[inline] + pub(super) fn app_root(&self) -> usize { + self.tree.app_root() + } + + #[inline] + pub(super) fn find_app_root(&mut self) { + self.tree.find_app_root(); + } + + /// Moves a Tx's playground requests to the runtime, for the next commit to apply before its + /// view. + pub(super) fn latch_playground(&mut self, app: &mut dyn AppDriver, tx: &mut Tx) { + let requests = std::mem::take(&mut tx.playground); + if requests.is_empty() { return; } + // The playground swaps whole views: no fades between them. + tx.commit = tx.commit.instant(); + let Some(playground) = app.playground_mut() else { return }; + playground.request(requests); + self.commit.dirty = true; + } + + /// Applies queued playground requests. Focus leaves the old stage first, while the states + /// its fields were built for are still there; a replay keeps it in the side column. + pub(super) fn apply_playground(&mut self, app: &mut dyn AppDriver) { + self.sync_region(app); + let (has_pending, swaps, replays_only, was_open) = { + let Some(playground) = app.playground() else { return }; + (playground.has_pending(), playground.pending_swaps_stage(), playground.pending_replays_only(), playground.is_open()) + }; + if !has_pending { return; } + let keep = replays_only && self.focused_index().is_some_and(|i| self.tree.under(i, |k| k == "playground-side")); + if swaps && !keep && self.kbd.focus.path().is_some() { self.set_focus(app, None, false); } + let clock = self.clock; + if !app.playground_apply(clock) { return; } + self.commit.clear_memo(); + if swaps { self.leave_stage(app, was_open); } + // A new stage state gets its first poll on the next frame, as an app's does. + if app.playground().is_some_and(|p| p.polls()) { self.schedule_wakes([std::time::Duration::ZERO]); } + } + + /// The old stage's elements, and the pointer's hold on them, go with its state: their + /// handlers were built for it. Its exits end now, nothing it held hears a release or a + /// hover ending, and the time scale it set goes back to the app's. + fn leave_stage(&mut self, app: &mut dyn AppDriver, was_open: bool) { + let exiting: Vec<_> = self.tree.nodes.iter().map(|n| n.id).filter(|&id| self.is_exiting(id)).collect(); + for id in exiting { self.scene.unmount(id); } + self.drop_drag_out_request(); + self.select_step(selectable::phase::Event::Release); + self.edit.input_click.clear(); + self.pointer.clear_for_stage(); + self.host.clear_titlebar(); + let Some(playground) = app.playground_mut() else { return }; + if was_open { self.time_scale = playground.app_time_scale(); } else { playground.set_app_time_scale(self.time_scale); } + } + + /// Whether node `i` or an ancestor has a key `is` takes. + #[inline] + pub(super) fn under(&self, i: usize, is: impl Fn(&str) -> bool) -> bool { + self.tree.under(i, is) + } + + /// Keys nothing else took: Escape gives the keyboard back to the list from the stage, else + /// goes Back. + pub(super) fn playground_key(&mut self, app: &mut dyn AppDriver, ev: &KeyEvent, one: &mut Tx) -> bool { + let plain = !ev.mods.cmd && !ev.mods.alt && !ev.mods.ctrl && !ev.mods.shift; + if ev.key != crate::Key::Escape || !plain || !app.playground().is_some_and(|p| p.is_open()) { return false; } + self.sync_region(app); + if app.playground().is_some_and(|p| p.region() != Region::List) { self.to_list(app); } else { one.close_playground(); } + true + } + + /// The playground's own keys, ahead of the stage's `on_key` and focus traversal: its + /// shortcut, and while it's open, the keys of the column that has the keyboard (see + /// [`Region`]). A focused text field keeps its keys, and the stage all of its own. + pub(super) fn playground_nav(&mut self, app: &mut dyn AppDriver, ev: &KeyEvent, one: &mut Tx) -> bool { + let Some(shortcut) = app.playground().map(|p| p.is_shortcut(ev)) else { return false }; + if shortcut { + if !one.key_repeat { one.toggle_playground(); } + return true; + } + // Ahead of fields too: route_key doesn't offer it again. + if app.playground_typing() && app.has_on_key() && Tx::took(app.on_key(ev, one), one) { return true; } + if !app.playground().is_some_and(|p| p.is_open()) { return false; } + self.sync_region(app); + if self.focused_input().is_some() { return self.filter_key(app, ev, one); } + if self.on_side_keys() { + if matches!(ev.key, crate::Key::Escape | crate::Key::Tab) { + self.to_list(app); + return true; + } + if app.playground_mut().is_some_and(|p| p.side_key(ev, one)) { return true; } + } + let nav = match app.playground() { + Some(playground) => playground.nav(ev, playground.region()), + None => return false, + }; + let side = self.playground_side(); + let at = self.kbd.focus.path().filter(|_| !self.kbd.focus.hovered()).and_then(|f| side.iter().position(|p| p == f)); + match nav { + Nav::Pass => false, + Nav::Stay => true, + Nav::Request(request) => { + let trigger = matches!(request, Request::Trigger(_) | Request::Replay); + if !(trigger && one.key_repeat) { one.playground.push(request); } + true + } + Nav::IntoSide => { + if let Some(first) = side.first() { self.set_focus(app, Some(first.clone()), true); } + self.give_region(app, Region::Side); + true + } + Nav::IntoStage => { + self.set_focus(app, None, true); + self.give_region(app, Region::Stage); + true + } + Nav::Filter => { + let Some(path) = self.tree.key_path(FILTER) else { return false }; + self.set_focus(app, Some(path), true); + true + } + Nav::OutOfSide => { + self.to_list(app); + true + } + Nav::SideStep(_) if side.is_empty() => true, + Nav::SideStep(by) => { + let n = side.len() as isize; + let to = match at { + Some(at) => (at as isize + by).rem_euclid(n), + None if by > 0 => 0, + None => n - 1, + }; + let path = side[to as usize].clone(); + self.set_focus(app, Some(path.clone()), true); + one.scroll_to.push(crate::runtime::ScrollReveal::into_view(None, path)); + true + } + } + } + + /// Keys in a focused text field. In the list's filter, ↓ goes down into the matches, onto + /// the first; Return goes to the list on the first match, if the selection isn't one; and + /// Esc empties it, then goes to the list. Every other key edits it, and every other field + /// keeps all its keys. + fn filter_key(&mut self, app: &mut dyn AppDriver, ev: &KeyEvent, one: &mut Tx) -> bool { + use crate::Key::*; + let plain = !ev.mods.alt && !ev.mods.ctrl && !ev.mods.cmd && !ev.mods.shift; + if self.focused_index().and_then(|i| self.tree.nodes[i].key.as_deref()) != Some(FILTER) || !plain { return false; } + let Some(playground) = app.playground_mut() else { return false }; + let to = match ev.key { + Escape if playground.clear_filter() => { + self.commit.dirty = true; + return true; + } + Down => playground.first_shown(), + Enter => playground.first_match(), + Escape => None, + _ => return false, + }; + if let Some(i) = to { one.playground.push(Request::Select(i)); } + self.set_focus(app, None, true); + true + } + + /// The list takes the keyboard back: focus leaves the stage or the side column. + fn to_list(&mut self, app: &mut dyn AppDriver) { + self.set_focus(app, None, true); + self.give_region(app, Region::List); + } + + /// Gives `region` the keyboard, redrawing the columns' focus. + fn give_region(&mut self, app: &mut dyn AppDriver, region: Region) { + let focus = self.kbd.focus.owned(); + let Some(playground) = app.playground_mut() else { return }; + if playground.moved(Moved::Give { region, seen: focus }) { self.commit.dirty = true; } + } + + /// A press in the open playground gives its column the keyboard. + pub(super) fn playground_pointer_down(&mut self, app: &mut dyn AppDriver, x: f32) { + let width = self.viewport.0; + let Some(region) = app.playground().filter(|p| p.is_open()).map(|p| p.region_at(x, width)) else { return }; + self.give_region(app, region); + } + + /// Focus that moved into a column since the last look gives that column the keyboard: a + /// field focused in the stage, Tab into the side column. Focus a hover moved (a menu-like + /// row under the pointer) is passed over, and so is focus leaving: the column keeps it. + fn sync_region(&mut self, app: &mut dyn AppDriver) { + if app.playground().is_none_or(|p| p.saw_focus(self.kbd.focus.path())) { return; } + let at = if self.kbd.focus.hovered() { None } else { self.focused_index() }; + let region = at.map(|i| { + if self.tree.under(i, |k| k == "playground-side") { + Region::Side + } else if self.tree.under(i, crate::playground::is_stage) { + Region::Stage + } else { + Region::List + } + }); + let focus = self.kbd.focus.owned(); + let Some(playground) = app.playground_mut() else { return }; + if playground.moved(Moved::Focus { focus, region }) { self.commit.dirty = true; } + } + + /// Polls the open stage, then queues the keys its steps pressed ([`Play::press`]) behind + /// the input already waiting, so they route on this frame as a person's keys would. + /// + /// [`Play::press`]: crate::playground::Play::press + pub(super) fn poll_playground(&mut self, app: &mut dyn AppDriver, clock: f64, one: &mut Tx) -> bool { + let Some(playground) = app.playground_mut() else { return false }; + let ran = playground.poll_stage(clock, one); + let pressed = playground.take_pressed(); + for ev in pressed { + self.trace_event(format_args!("press {:?}", ev.key)); + self.queue_key(ev, true); + } + ran + } + + /// Routes a key a step pressed as [`Runtime::route_key`] routes a person's, with the stage + /// holding the keyboard. Focus outside the stage (the list's filter, a side control) is set + /// aside for it, and the keyboard goes back where the person left it. + pub(super) fn route_stage_key(&mut self, app: &mut dyn AppDriver, ev: &KeyEvent, one: &mut Tx) -> bool { + let Some(region) = app.playground().filter(|p| p.is_open()).map(|p| p.region()) else { return self.route_key(app, ev, false, one) }; + let aside = self.focused_index().filter(|&i| !self.tree.under(i, crate::playground::is_stage)).and_then(|_| self.kbd.focus.set_aside()); + if let Some(p) = app.playground_mut() { + p.moved(Moved::Hold(Region::Stage)); + p.set_pressing(true); + } + let took = self.route_key(app, ev, false, one); + if let Some(p) = app.playground_mut() { p.set_pressing(false); } + // Focus goes back only if the key left it where it was: otherwise what it focused stays, + // and the next look at focus gives that column the keyboard. + let back = aside.filter(|_| self.kbd.focus.path().is_none()); + let path = back.as_ref().and_then(|aside| match aside { + focus_machine::Focus::On { path, .. } => Some(path.clone()), + _ => None, + }); + let Some(p) = app.playground_mut() else { return took }; + p.moved(Moved::Resume { region, back: path }); + if let Some(aside) = back { + self.kbd.focus.put_back(aside); + // A key that blurred it reported the slot off; it's back. + self.sync_side_focus(app); + } + took + } + + /// The keyboard is on the open story's side controls that take keys (`Story::side_keys`), + /// whose slot is focusable only then. + fn on_side_keys(&self) -> bool { + !self.kbd.focus.hovered() && self.focused_index().is_some_and(|i| self.tree.nodes[i].key.as_deref().is_some_and(|k| k.starts_with("playground-slot-"))) + } + + /// Tells the keyboard whether the side controls that take keys have focus, so their view + /// can mark what the keys move; a change rebuilds the view. + pub(super) fn sync_side_focus(&mut self, app: &mut dyn AppDriver) { + let slot = self.on_side_keys(); + if app.playground_mut().is_some_and(|p| p.moved(Moved::Slot(slot))) { self.commit.dirty = true; } + } + + /// The paths of the focusable controls in the playground's side column, in order. + fn playground_side(&self) -> Vec<String> { + (0..self.tree.nodes.len()).filter(|&i| self.can_focus(i) && self.tree.under(i, |k| k == "playground-side")).map(|i| self.tree.nodes[i].path.clone()).collect() + } +} diff --git a/app/vendor/rune/crates/rune/src/runtime/recorder_tests.rs b/app/vendor/rune/crates/rune/src/runtime/recorder_tests.rs new file mode 100644 index 0000000..a037030 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/recorder_tests.rs @@ -0,0 +1,66 @@ +use crate::{FakeMicrophone, Recorder}; +use std::path::PathBuf; + +/// A temporary directory, removed on drop. +struct Scratch(PathBuf); +impl Scratch { + fn new(name: &str) -> Self { + let dir = std::env::temp_dir().join(format!("rune-recorder-rt-{}-{name}", std::process::id())); + std::fs::remove_dir_all(&dir).ok(); + std::fs::create_dir_all(&dir).unwrap(); + Self(dir) + } + fn join(&self, name: &str) -> PathBuf { + self.0.join(name) + } +} +impl Drop for Scratch { + fn drop(&mut self) { + std::fs::remove_dir_all(&self.0).ok(); + } +} + +fn runtime() -> crate::Runtime<()> { + crate::Runtime::new((), |_: &(), _: &mut crate::Cx<()>| crate::el().size(10.0, 10.0), (10.0, 10.0), crate::Env::new(true, 2.0)) +} + +#[track_caller] +fn near(got: f64, want: f64, tolerance: f64) { + assert!((got - want).abs() <= tolerance, "got {got}, want {want}"); +} + +#[test] +fn a_new_runtime_restarts_elapsed_from_its_own_clock() { + FakeMicrophone::silence().install(); + let dir = Scratch::new("clock"); + let mut old = runtime(); + old.frame(5.0); + let rec = Recorder::to_file(dir.join("note.wav")); + rec.start(); + let mut rt = runtime(); + rt.frame(0.1); + rt.frame(0.1); + near(rec.elapsed(), 0.2, 1e-9); +} + +/// A bound meter shows this frame's level in this frame, and draws nothing while idle. +#[test] +fn a_bound_meter_follows_the_level_on_the_same_frame() { + let dir = Scratch::new("bound"); + FakeMicrophone::sine(1000.0, 0.5).install(); + let rec = Recorder::to_file(dir.join("a.wav")); + let view = |r: &Recorder, _: &mut crate::Cx<Recorder>| { + crate::el().key("meter").size(10.0, 10.0).fill(crate::Color::WHITE).live_opacity(&r.live_level()) + }; + let mut rt = crate::Runtime::new(rec.clone(), view, (10.0, 10.0), crate::Env::new(true, 2.0)); + rt.frame(0.0); + assert_eq!(rt.presented("meter").unwrap().1, 0.0); + assert!(!rt.frame(0.1), "an idle recorder asks for no frames"); + rec.start(); + rt.frame(1.0); + near(rt.presented("meter").unwrap().1 as f64, rec.level().meter() as f64, 1e-6); + assert!(rec.level().meter() > 0.8); + rec.stop().unwrap(); + rt.frame(0.1); + assert_eq!(rt.presented("meter").unwrap().1, 0.0); +} diff --git a/app/vendor/rune/crates/rune/src/runtime/rounded_clip_tests.rs b/app/vendor/rune/crates/rune/src/runtime/rounded_clip_tests.rs new file mode 100644 index 0000000..c82c508 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/rounded_clip_tests.rs @@ -0,0 +1,580 @@ +use super::*; +use super::tests::pixels; +use crate::{Color, Cx, El, Env, Live, Runtime, el}; + +#[test] +fn packed_clip_radii_boundaries_and_fade_lanes_do_not_collide() { + let rect = [0.0, 0.0, 2000.0, 2000.0]; + for (radii, want) in [ + ([0.0, 0.24, 12.26, 63.5], [0.0, 0.0, 12.5, 63.5]), + ([0.0, 63.6, 127.0, 254.0], [0.0, 64.0, 128.0, 254.0]), + ([0.0, 256.0, 500.0, 2000.0], [0.0, 254.0, 254.0, 254.0]), + ([-1.0, -12.5, 0.0, -63.5], [-1.0, -12.5, 0.0, -63.5]), + ] { + assert_eq!(unpack_clip_radii(pack_clip_radii(rect, radii)), want); + } + for r in [0.0, 0.125, 63.75, 254.5, 999.0, -999.0] { + assert_eq!(unpack_clip_radii(pack_clip_radii(rect, [r; 4])), [r; 4]); + } + for r in [1e30, -1e30, f32::INFINITY] { + let word = pack_clip_radii([0.0, 0.0, 1e35, 1e35], [r; 4]); + assert_ne!(word & 0x6000_0000, 0x6000_0000, "uniform radius cannot become a tag"); + assert!(unpack_clip_radii(word).iter().all(|v| v.is_finite() && v.abs() > 1e18)); + } + let fade = pack_fade([65504.0; 4], rect, rect); + assert_eq!(fade[3], 0, "even maximal fade widths never occupy the radius word"); +} + +#[test] +fn rounded_clip_follows_paint_radii_unless_explicitly_overridden() { + fn view(mode: &u8, _: &mut Cx<u8>) -> El { + let card = el().size(80.0, 40.0).corners([12.0; 4]).clip_rounded(4.0); + let card = match mode { + 1 => card.clip_corners([4.0; 4]), + 2 => card.clip_corners([4.0; 4]).clip_rounded(8.0), + _ => card, + }; + card.child(el().size(80.0, 40.0).fill(Color::WHITE)) + } + for (mode, want) in [(0, 12.0), (1, 4.0), (2, 12.0)] { + let mut rt = Runtime::new(mode, view, (80.0, 40.0), Env::new(true, 1.0)); + rt.frame(0.0); + assert!(rt.instances.iter().any(|i| unpack_clip_radii(i.fade[3]) == [want; 4])); + } +} + +#[test] +fn per_corner_video_clip_matches_the_primitive_mask() { + use crate::native_surface::{ByteFrame, ColorInfo, Format, NativeSurface, SurfaceFit}; + type State = (NativeSurface, bool, bool); + fn view(s: &State, _: &mut Cx<State>) -> El { + let mut card = el().size(48.0, 32.0).absolute(8.0, 8.0).corners([12.0, 4.0, 0.0, 8.0]); + if s.2 { card = card.continuous_corners(); } + if s.1 { + card.clip_rounded(2.0).child(el().size(64.0, 48.0).absolute(-8.0, -8.0).native_surface(&s.0, SurfaceFit::Fill)) + } else { + card.clip_soft(0.0).fill(Color::WHITE) + } + } + let surface = NativeSurface::new(); + surface.push_bytes(ByteFrame { width: 1, height: 1, format: Format::Bgra, color: ColorInfo::default(), + planes: [vec![255; 4], vec![]] }, 1).unwrap(); + let gpu = Gpu::headless(); + // Compare mask coverage directly, without sRGB amplification of near-zero AA residuals. + let format = wgpu::TextureFormat::Rgba8Unorm; + let mut renderer = Renderer::new(&gpu.device, format); + let target = Offscreen::with_format(&gpu.device, 64, 48, format); + for continuous in [false, true] { + let mut outs = Vec::new(); + for video in [false, true] { + let mut rt = Runtime::new((surface.clone(), video, continuous), view, (64.0, 48.0), Env::new(true, 1.0)); + rt.frame(0.0); + renderer.prepare(&gpu.device, &gpu.queue, &mut rt.text.atlas, &rt.instances, (64, 48)); + renderer.prepare_surfaces(&gpu.device, &gpu.queue, &rt.surfaces, (64, 48)); + outs.push(pixels(&gpu, &renderer, &target)); + } + for (byte, (a, b)) in outs[0].iter().zip(&outs[1]).enumerate() { + assert!(a.abs_diff(*b) <= 1, "continuous={continuous} byte={byte} primitive={a} video={b}"); + } + } +} + +#[test] +fn raised_children_keep_the_ancestors_per_corner_clip() { + fn view(_: &(), _: &mut Cx<()>) -> El { + el().child(el().size(48.0, 32.0).absolute(8.0, 8.0) + .corners([12.0, 4.0, 0.0, 8.0]).continuous_corners().clip_rounded(2.0).opacity(0.8) + .child(el().size(64.0, 48.0).absolute(-8.0, -8.0).fill(Color::WHITE).raise())) + } + let mut rt = Runtime::new((), view, (64.0, 48.0), Env::new(true, 1.0)); + rt.frame(0.0); + let masks: Vec<_> = rt.instances.iter().filter(|i| i.params[1] == KIND_LAYER && i.fade[3] != 0).collect(); + assert!(!masks.is_empty()); + for mask in masks { + assert_eq!(mask.clip, [8.0, 8.0, 56.0, 40.0]); + assert_eq!(unpack_clip_radii(mask.fade[3]), [-12.0, -4.0, 0.0, -8.0]); + } +} + +// Circle-corner coverage oracle, independent of the shader's rounded-box distance expression. +fn mask(x: f32, y: f32, rect: [f32; 4], radius: f32) -> f32 { + let cx = x.clamp(rect[0] + radius, rect[2] - radius); + let cy = y.clamp(rect[1] + radius, rect[3] - radius); + let corner = (radius + 0.5 - (x - cx).hypot(y - cy)).clamp(0.0, 1.0); + corner * (x - rect[0] + 0.5).clamp(0.0, 1.0) * (rect[2] - x + 0.5).clamp(0.0, 1.0) + * (y - rect[1] + 0.5).clamp(0.0, 1.0) * (rect[3] - y + 0.5).clamp(0.0, 1.0) +} + +#[test] +fn rounded_clip_direct_nested_and_rectangular_intersections() { + fn view(mode: &u8, _: &mut Cx<u8>) -> El { + let white = el().size(100.0, 100.0).absolute(-30.0, -30.0).fill(Color::WHITE); + let child = if *mode == 0 { white } else { + el().size(40.0, 48.0).absolute(14.0, -8.0).clip_rounded(10.0).child(white) + }; + let capsule = el().size(48.0, 32.0).absolute(8.0, 8.0).clip_rounded(16.0).child(child); + if *mode == 2 { + // Clip starts at x=24 without recentering either rounded rectangle. + el().child(el().size(40.0, 48.0).absolute(24.0, 0.0).clip_soft(0.0) + .child(el().size(64.0, 48.0).absolute(-24.0, 0.0).child(capsule))) + } else { el().child(capsule) } + } + assert_eq!(std::mem::size_of::<Instance>(), 128); + let gpu = Gpu::headless(); + let mut renderer = Renderer::new(&gpu.device, OFFSCREEN_FORMAT); + let target = Offscreen::new(&gpu.device, 64, 48); + for mode in 0..3 { + let mut rt = Runtime::new(mode, view, (64.0, 48.0), Env { scale: 1.0, system_dark: true }); + rt.frame(0.0); + renderer.prepare(&gpu.device, &gpu.queue, &mut rt.text.atlas, &rt.instances, (64, 48)); + if mode == 0 { assert_eq!(renderer.layer_stats().extra_passes, 0, "ordinary rounded clip stays direct"); } + let out = pixels(&gpu, &renderer, &target); + for y in 0..48 { for x in 0..64 { + let (px, py) = (x as f32 + 0.5, y as f32 + 0.5); + let mut a = mask(px, py, [8.0, 8.0, 56.0, 40.0], 16.0); + if mode > 0 { a *= mask(px, py, [22.0, 0.0, 62.0, 48.0], 10.0); } + if mode == 2 && x < 24 { a = 0.0; } + let got = out[(y * 64 + x) * 4 + 3]; + assert!(got.abs_diff((a * 255.0).round() as u8) <= 1, "mode={mode} ({x},{y}): {got} vs {a}"); + } } + } +} + +#[test] +fn rounded_clip_blurred_exiting_chip_stays_inside_capsule() { + type State = (bool, Live<[f32; 2]>); + fn view(s: &State, _: &mut Cx<State>) -> El { + let mut capsule = el().size(400.0, 40.0).absolute(24.0, 24.0); + if s.0 { capsule = capsule.clip_rounded(20.0); } + el().child(capsule.child(el().size(72.0, 28.0).absolute(370.0, 6.0) + .live_offset(&s.1).opacity(0.65).blur(1.5).radius(8.0) + .fill(Color { r: 0.06, g: 0.32, b: 1.0, a: 1.0 }) + .child(crate::text("Leaving").color(Color::WHITE).absolute(8.0, 6.0)))) + } + let gpu = Gpu::headless(); + let mut renderer = Renderer::new(&gpu.device, OFFSCREEN_FORMAT); + let target = Offscreen::new(&gpu.device, 896, 176); + let mut plain = Runtime::new((false, Live::new([0.0; 2])), view, (448.0, 88.0), Env { scale: 2.0, system_dark: true }); + let mut clipped = Runtime::new((true, Live::new([0.0; 2])), view, (448.0, 88.0), Env { scale: 2.0, system_dark: true }); + let mut sheet = vec![0; 1792 * 528 * 4]; + for (row, offset) in [0.0, 26.0, 32.0].into_iter().enumerate() { + let mut outputs = Vec::new(); + for rt in [&mut plain, &mut clipped] { + rt.state.1.set([offset, 0.0]); rt.frame(0.0); + renderer.prepare(&gpu.device, &gpu.queue, &mut rt.text.atlas, &rt.instances, (896, 176)); + outputs.push(pixels(&gpu, &renderer, &target)); + } + let mut retained = false; + let mut removed = false; + for y in 0..176 { for x in 0..896 { + let a = mask(x as f32 + 0.5, y as f32 + 0.5, [48.0, 48.0, 848.0, 128.0], 40.0); + let at = (y * 896 + x) * 4; + let want = (outputs[0][at + 3] as f32 * a).round() as u8; + assert!(outputs[1][at + 3].abs_diff(want) <= 1, "offset={offset} ({x},{y})"); + if a == 0.0 { assert_eq!(&outputs[1][at..at + 4], &[0; 4]); removed |= outputs[0][at + 3] > 0; } + if a == 1.0 && outputs[1][at + 3] > 0 { retained = true; } + // Dark review sheet with a subtle capsule guide, left unmasked / right clipped. + for (column, out) in outputs.iter().enumerate() { + let dst = ((row * 176 + y) * 1792 + column * 896 + x) * 4; + let alpha = out[at + 3] as f32 / 255.0; + for c in 0..3 { + let v = out[at + c] as f32 / 255.0; + let linear = if v <= 0.04045 { v / 12.92 } else { ((v + 0.055) / 1.055).powf(2.4) }; + let linear = linear + (0.008 + a * 0.025) * (1.0 - alpha); + sheet[dst + c] = ((1.055 * linear.powf(1.0 / 2.4) - 0.055) * 255.0).clamp(0.0, 255.0) as u8; + } + sheet[dst + 3] = 255; + } + } } + assert!(removed && retained, "clip removes the halo but keeps off-wall source contributions"); + let layer = clipped.instances.iter().find(|i| i.params[1] == KIND_LAYER && i.params[2] > 0.0).unwrap(); + assert_eq!(layer.clip, [48.0, 48.0, 848.0, 128.0]); + assert_eq!(f32::from_bits(layer.fade[3]), 40.0); + assert_eq!(layer.uv, [0.0; 4]); + assert_eq!(layer.radii, [0.0; 4]); + } + if let Some(path) = std::env::var_os("RUNE_CLIP_STILL") { + write_png(&std::path::PathBuf::from(path), 1792, 528, &sheet).unwrap(); + } +} + +#[test] +fn rounded_clip_preserves_every_primitive_lane_and_feathers() { + let gpu = Gpu::headless(); + let format = wgpu::TextureFormat::Rgba8Unorm; + let mut renderer = Renderer::new(&gpu.device, format); + let target = Offscreen::with_format(&gpu.device, 64, 48, format); + let mut atlas = crate::text::TextSystem::default().atlas; + atlas.data.resize(crate::text::ATLAS_SIZE.pow(2) as usize, 0); + for y in 0..48 { atlas.data[y * crate::text::ATLAS_SIZE as usize..y * crate::text::ATLAS_SIZE as usize + 64].fill(128); } + atlas.dirty = Some((0, 48)); + let mut images = crate::pixels::ImageAtlas::default(); + let image = crate::pixels::Pixels::new(); image.set(1, 1, vec![80, 160, 240, 200]); + let image = images.place(&image, [64.0, 48.0]).unwrap(); + renderer.upload_images(&gpu.device, &gpu.queue, &mut images); + for kind in 0..8 { + let mut instance = Instance { rect: [0.0, 0.0, 64.0, 48.0], radii: [3.0, 5.0, 7.0, 9.0], + fill: [0.2, 0.4, 0.6, 0.8], border: [0.8, 0.1, 0.2, 0.9], params: [2.0, kind as f32, 2.0, 1.4], + uv: [0.0; 4], clip: [8.0, 8.0, 56.0, 40.0], + fade: pack_fade([1.0, 2.0, 3.0, 4.0], [8.0, 8.0, 56.0, 40.0], [8.0, 8.0, 56.0, 40.0]) }; + match kind { + 2 => { instance.params[0] = 0.0; instance.radii = [0.0; 4]; instance.uv = [0.0, 0.0, 64.0, 48.0]; } + 3 => { instance.uv = [4.0, 6.0, 0.0, 0.0]; instance.params[0] = 12.0; } + 4 => instance.uv = [0.8, 0.2, 0.3, 1.0], + 5 => { instance.radii = [4.0, 24.0, 60.0, 24.0]; instance.params[0] = 24.0; instance.params[2] = 1.0; } + 6 => { instance.radii = [-20.0, -20.0, 100.0, -20.0]; instance.uv = [32.0, 100.0, 0.0, 0.0]; instance.params[0] = 7.0; } + 7 => { instance.uv = image.rect.map(|v| v as f32); instance.params[0] = image.page as f32; instance.params[2] = 0.0; } + _ => {} + } + renderer.prepare(&gpu.device, &gpu.queue, &mut atlas, &[instance], (64, 48)); + let plain = pixels(&gpu, &renderer, &target); + instance.round_clip(16.0); + renderer.prepare(&gpu.device, &gpu.queue, &mut atlas, &[instance], (64, 48)); + let clipped = pixels(&gpu, &renderer, &target); + assert_eq!(renderer.layer_stats().extra_passes, 0); + let mut cut = false; + for y in 0..48 { for x in 0..64 { + let a = mask(x as f32 + 0.5, y as f32 + 0.5, instance.clip, 16.0); + let at = (y * 64 + x) * 4; + for c in 0..4 { + let want = (plain[at + c] as f32 * a).round() as u8; + assert!(clipped[at + c].abs_diff(want) <= 1, "kind={kind} ({x},{y}) channel={c}"); + } + cut |= plain[at + 3] > clipped[at + 3]; + } } + assert!(cut, "kind {kind} exercised a rounded corner"); + } +} + +#[test] +fn rounded_clip_native_video_inherits_capsule_without_a_layer() { + use crate::native_surface::{ByteFrame, ColorInfo, Format, NativeSurface, SurfaceFit}; + fn view(surface: &NativeSurface, _: &mut Cx<NativeSurface>) -> El { + el().child(el().size(48.0, 32.0).absolute(8.0, 8.0).clip_rounded(16.0) + .child(el().size(64.0, 48.0).absolute(-8.0, -8.0).native_surface(surface, SurfaceFit::Fill))) + } + let gpu = Gpu::headless(); + let mut renderer = Renderer::new(&gpu.device, OFFSCREEN_FORMAT); + let target = Offscreen::new(&gpu.device, 64, 48); + let surface = NativeSurface::new(); + surface.push_bytes(ByteFrame { width: 1, height: 1, format: Format::Bgra, color: ColorInfo::default(), + planes: [vec![255; 4], vec![]] }, 1).unwrap(); + let mut rt = Runtime::new(surface, view, (64.0, 48.0), Env { scale: 1.0, system_dark: true }); + rt.frame(0.0); + renderer.prepare(&gpu.device, &gpu.queue, &mut rt.text.atlas, &rt.instances, (64, 48)); + renderer.prepare_surfaces(&gpu.device, &gpu.queue, &rt.surfaces, (64, 48)); + assert_eq!(renderer.layer_stats().extra_passes, 0); + let out = pixels(&gpu, &renderer, &target); + for y in 0..48 { for x in 0..64 { + let a = mask(x as f32 + 0.5, y as f32 + 0.5, [8.0, 8.0, 56.0, 40.0], 16.0); + assert!(out[(y * 64 + x) * 4 + 3].abs_diff((a * 255.0).round() as u8) <= 1); + } } +} + +#[test] +fn rounded_clip_live_truncated_text_preserves_corner_centres() { + type State = (bool, crate::LiveText, bool); + fn view(s: &State, _: &mut Cx<State>) -> El { + let mut capsule = el().size(48.0, 32.0).absolute(8.0, 8.0); + if s.0 { capsule = capsule.clip_rounded(16.0); } + let mut label = crate::text("MMMMMMMM").live_text(&s.1).size(44.0, 32.0) + .absolute(2.0, -2.0).font(crate::TextStyle::new(28.0, 700.0)).color(Color::WHITE); + if s.2 { label = label.truncate_fade(); } + el().child(capsule.child(label)) + } + let gpu = Gpu::headless(); + for scale in [1.0, 2.0] { for truncate in [false, true] { + let size = ((64.0 * scale) as u32, (48.0 * scale) as u32); + let target = Offscreen::new(&gpu.device, size.0, size.1); + let mut renderer = Renderer::new(&gpu.device, OFFSCREEN_FORMAT); + let value = crate::LiveText::new("MMMMMMMM"); + let mut plain = Runtime::new((false, value.clone(), truncate), view, (64.0, 48.0), Env::new(true, scale)); + let mut clipped = Runtime::new((true, value.clone(), truncate), view, (64.0, 48.0), Env::new(true, scale)); + for words in ["MMMMMMMM", "WW", "MMMMMMMMMMMM"] { + value.set(words); + let mut outputs = Vec::new(); + for rt in [&mut plain, &mut clipped] { + rt.frame(0.0); + renderer.prepare(&gpu.device, &gpu.queue, &mut rt.text.atlas, &rt.instances, size); + outputs.push(pixels(&gpu, &renderer, &target)); + } + let mut cut = false; + let mut kept = false; + for y in 0..size.1 { for x in 0..size.0 { + let a = mask(x as f32 + 0.5, y as f32 + 0.5, + [8.0, 8.0, 56.0, 40.0].map(|v| v * scale), 16.0 * scale); + let at = ((y * size.0 + x) * 4 + 3) as usize; + let want = (outputs[0][at] as f32 * a).round() as u8; + assert!(outputs[1][at].abs_diff(want) <= 1, + "scale={scale} truncate={truncate} words={words} ({x},{y})"); + cut |= outputs[0][at] > outputs[1][at]; + kept |= outputs[1][at] > 0; + } } + assert!(cut && kept, "exercise glyph coverage inside and outside the corner"); + } + } } +} + +#[test] +fn live_text_clear_of_rounded_corners_draws_without_a_layer() { + type State = (bool, crate::LiveText); + fn view(s: &State, _: &mut Cx<State>) -> El { + let mut card = el().size(120.0, 64.0).absolute(8.0, 8.0).radius(16.0).fill(crate::oklch(0.25, 0.04, 260.0)); + if s.0 { card = card.clip_rounded(16.0); } + let label = crate::text("0000").live_text(&s.1).size(80.0, 24.0) + .absolute(10.0, 8.0).font(crate::TextStyle::new(20.0, 700.0)).color(Color::WHITE); + el().child(card.child(label)) + } + let gpu = Gpu::headless(); + for scale in [1.0, 2.0] { + let size = ((136.0 * scale) as u32, (80.0 * scale) as u32); + let target = Offscreen::new(&gpu.device, size.0, size.1); + let mut renderer = Renderer::new(&gpu.device, OFFSCREEN_FORMAT); + let value = crate::LiveText::new("0000"); + let mut plain = Runtime::new((false, value.clone()), view, (136.0, 80.0), Env::new(true, scale)); + let mut clipped = Runtime::new((true, value.clone()), view, (136.0, 80.0), Env::new(true, scale)); + for words in ["0000", "8888", "WWWW"] { + value.set(words); + let mut outputs = Vec::new(); + for rt in [&mut plain, &mut clipped] { + rt.frame(0.0); + assert!(rt.instances.iter().all(|i| i.params[1] != KIND_LAYER), "scale={scale} words={words}: no layer"); + renderer.prepare(&gpu.device, &gpu.queue, &mut rt.text.atlas, &rt.instances, size); + outputs.push(pixels(&gpu, &renderer, &target)); + } + // The glyphs match; the card's own edge differs, a hard clip over its feathered fill. + let (x0, y0, x1, y1) = ((18.0 * scale) as u32, (16.0 * scale) as u32, (98.0 * scale) as u32, (40.0 * scale) as u32); + let mut lit = false; + for y in y0..y1 { for x in x0..x1 { + let at = ((y * size.0 + x) * 4) as usize; + assert!((0..4).all(|c| outputs[0][at + c].abs_diff(outputs[1][at + c]) <= 1), "scale={scale} words={words} ({x},{y})"); + lit |= outputs[1][at] > 200; + } } + assert!(lit, "the glyphs drew"); + } + } +} + +#[test] +fn rounded_clip_and_dissolve_follow_retained_presence() { + fn view(show: &bool, _: &mut Cx<bool>) -> El { + el().size(80.0, 40.0).clip_rounded(20.0).dissolve() + .children(show.then(|| el().key("chip").size(40.0, 28.0).fill(Color::WHITE) + .transition(rune_motion::Transition::blur_replace()))) + } + let mut rt = Runtime::new(true, view, (80.0, 40.0), Env { scale: 2.0, system_dark: true }); + rt.frame(0.0); + assert!(rt.instances.iter().all(|i| i.params[1] != KIND_LAYER)); + rt.state = false; rt.invalidate(); rt.frame(0.0); rt.frame(0.04); + assert!(rt.instances.iter().any(|i| i.params[1] == KIND_LAYER && i.params[0] == 1.0 && f32::from_bits(i.fade[3]) == 40.0)); + assert!(rt.instances.iter().any(|i| i.params[1] == KIND_LAYER && i.params[2] > 0.0)); + for _ in 0..120 { rt.frame(1.0 / 120.0); } + assert!(rt.instances.iter().all(|i| i.params[1] != KIND_LAYER)); +} + +#[test] +fn rounded_clip_leaves_central_scroll_rectangles_on_the_direct_path() { + type State = (bool, bool); + fn view(s: &State, _: &mut Cx<State>) -> El { + let mut capsule = el().size(80.0, 48.0).absolute(8.0, 8.0); + if s.0 { capsule = capsule.clip_rounded(16.0); } + let (x, y, w, h) = if s.1 { (0.0, 16.0, 80.0, 16.0) } else { (16.0, 0.0, 48.0, 48.0) }; + el().child(capsule.child(el().absolute(x, y).size(w, h).scroll(crate::ScrollSpec { stick_bottom: false }) + .child(el().size(120.0, 120.0).fill(Color::WHITE)))) + } + let gpu = Gpu::headless(); + let mut renderer = Renderer::new(&gpu.device, OFFSCREEN_FORMAT); + let target = Offscreen::new(&gpu.device, 96, 64); + for horizontal in [false, true] { + let mut frames = Vec::new(); + for rounded in [false, true] { + let mut rt = Runtime::new((rounded, horizontal), view, (96.0, 64.0), Env::new(true, 1.0)); + rt.frame(0.0); + renderer.prepare(&gpu.device, &gpu.queue, &mut rt.text.atlas, &rt.instances, (96, 64)); + assert_eq!(renderer.layer_stats().targets, 0); + frames.push(pixels(&gpu, &renderer, &target)); + } + assert_eq!(frames[0], frames[1], "central strip misses every rounded corner"); + } +} + +#[test] +fn rounded_clip_single_line_input_keeps_the_original_mask() { + type State = (bool, crate::TextEdit); + fn view(s: &State, _: &mut Cx<State>) -> El { + let mut capsule = el().size(80.0, 40.0).absolute(8.0, 8.0); + if s.0 { capsule = capsule.clip_rounded(20.0); } + el().child(capsule.child(crate::text_input(&s.1, crate::TextStyle::new(28.0, 700.0)) + .single_line().size(64.0, 40.0).absolute(8.0, 0.0))) + } + let gpu = Gpu::headless(); + for scale in [1.0, 2.0] { + let size = ((96.0 * scale) as u32, (56.0 * scale) as u32); + let mut renderer = Renderer::new(&gpu.device, OFFSCREEN_FORMAT); + let target = Offscreen::new(&gpu.device, size.0, size.1); + let mut frames = Vec::new(); + for rounded in [false, true] { + let mut rt = Runtime::new((rounded, crate::TextEdit::new("MMMMMMMMMMMM")), view, + (96.0, 56.0), Env::new(true, scale)); + rt.frame(0.0); + renderer.prepare(&gpu.device, &gpu.queue, &mut rt.text.atlas, &rt.instances, size); + frames.push(pixels(&gpu, &renderer, &target)); + } + assert!(frames[0].chunks_exact(4).any(|p| p[3] > 0)); + for y in 0..size.1 { for x in 0..size.0 { + let a = mask(x as f32 + 0.5, y as f32 + 0.5, + [8.0, 8.0, 88.0, 48.0].map(|v| v * scale), 20.0 * scale); + let at = ((y * size.0 + x) * 4 + 3) as usize; + assert!(frames[1][at].abs_diff((frames[0][at] as f32 * a).round() as u8) <= 1, + "scale={scale} ({x},{y})"); + } } + } +} + +#[test] +fn per_corner_continuous_card_clips_image_child_and_nested_layers() { + let gpu = Gpu::headless(); + let mut renderer = Renderer::new(&gpu.device, OFFSCREEN_FORMAT); + let target = Offscreen::new(&gpu.device, 128, 96); + + let card_img = crate::pixels::Pixels::new(); + let mut card_rgba = Vec::with_capacity(80 * 56 * 4); + for y in 0..56u32 { + for x in 0..80u32 { + card_rgba.extend_from_slice(&[ + (36 + x * 2) as u8, + (64 + y * 3) as u8, + (210 - x * 2) as u8, + 255, + ]); + } + } + card_img.set(80, 56, card_rgba); + + // Overflowing 96x72 child image: identical to `card_img` inside the 80x56 card (offset by 8,8), + // with an opaque bleed ring outside that the card's clip must remove completely. + let child_img = crate::pixels::Pixels::new(); + let mut child_rgba = Vec::with_capacity(96 * 72 * 4); + for y in 0..72i32 { + for x in 0..96i32 { + if (8..88).contains(&x) && (8..64).contains(&y) { + let (cx, cy) = ((x - 8) as u32, (y - 8) as u32); + child_rgba.extend_from_slice(&[ + (36 + cx * 2) as u8, + (64 + cy * 3) as u8, + (210 - cx * 2) as u8, + 255, + ]); + } else { + child_rgba.extend_from_slice(&[255, 60, 120, 255]); + } + } + } + child_img.set(96, 72, child_rgba); + + // 1. Continuous-corner card with mixed radii (`[14, 14, 0, 0]` top banner and `[18, 6, 14, 4]` + // all four distinct): `clip_rounded` follows the element's own `corners` + `continuous_corners` + // with no extra call, clipping an overflowing `El::pixels` child to its own edge. + for corners in [[14.0, 14.0, 0.0, 0.0], [18.0, 6.0, 14.0, 4.0]] { + type State = (crate::pixels::Pixels, crate::pixels::Pixels, [f32; 4], u8); + fn view(s: &State, _: &mut Cx<State>) -> El { + let (card_img, child_img, corners, mode) = (&s.0, &s.1, s.2, s.3); + match mode { + // Reference: 80x56 image drawn directly on the continuous-corner card inside its + // hard bounds. + 0 => el().child( + el().size(80.0, 56.0) + .absolute(24.0, 20.0) + .clip_soft(0.0) + .child( + el().size(80.0, 56.0) + .corners(corners) + .continuous_corners() + .pixels(card_img), + ), + ), + // Direct clip path: card with `corners` + `continuous_corners` + `clip_rounded` + // clipping an overflowing 96x72 child image to its own edge. + 1 => el().child( + el().size(80.0, 56.0) + .absolute(24.0, 20.0) + .corners(corners) + .continuous_corners() + .clip_rounded(corners[0]) + .child(el().size(96.0, 72.0).absolute(-8.0, -8.0).pixels(child_img)), + ), + // Explicit `clip_corners` on an isolated layer (`opacity(0.9999)` forces a layer). + _ => el().child( + el().size(80.0, 56.0) + .absolute(24.0, 20.0) + .continuous_corners() + .clip_corners(corners) + .opacity(0.9999) + .child(el().size(96.0, 72.0).absolute(-8.0, -8.0).pixels(child_img)), + ), + } + } + + let mut outs = Vec::new(); + for mode in 0..3u8 { + let mut rt = Runtime::new( + (card_img.clone(), child_img.clone(), corners, mode), + view, + (128.0, 96.0), + Env::new(true, 1.0), + ); + rt.frame(0.0); + renderer.upload_images(&gpu.device, &gpu.queue, &mut rt.images); + renderer.prepare(&gpu.device, &gpu.queue, &mut rt.text.atlas, &rt.instances, (128, 96)); + if mode == 1 { + assert_eq!(renderer.layer_stats().extra_passes, 0, "mixed continuous clip stays on the direct path"); + } else if mode == 2 { + assert_eq!(renderer.layer_stats().extra_passes, 1, "isolated layer path exercised"); + } + outs.push(pixels(&gpu, &renderer, &target)); + } + // Check that top-left is rounded away while bottom-right is sharp when corners[2] == 0.0. + if corners[2] == 0.0 { + let tl_alpha = outs[1][(20 * 128 + 24) * 4 + 3]; + let br_alpha = outs[1][((20 + 55) * 128 + (24 + 79)) * 4 + 3]; + assert_eq!(tl_alpha, 0, "top-left continuous corner is clipped"); + assert_eq!(br_alpha, 255, "bottom-right zero-radius corner stays sharp"); + } + for mode in [1usize, 2] { + for (idx, (&got, &want)) in outs[mode].iter().zip(&outs[0]).enumerate() { + assert!( + got.abs_diff(want) <= 1, + "corners={corners:?} mode={mode} byte {idx}: got {got} vs want {want}" + ); + } + } + } + + // 2. Nested mixed-corner clips fall back to an outer layer and intersect both masks. + fn nested(img: &crate::pixels::Pixels, _: &mut Cx<crate::pixels::Pixels>) -> El { + el().child( + el().size(80.0, 56.0) + .absolute(24.0, 20.0) + .corners([16.0, 16.0, 0.0, 0.0]) + .continuous_corners() + .clip_rounded(16.0) + .child( + el().size(80.0, 56.0) + .corners([0.0, 0.0, 16.0, 16.0]) + .continuous_corners() + .clip_rounded(16.0) + .child(el().size(80.0, 56.0).pixels(img)), + ), + ) + } + let mut rt = Runtime::new(card_img, nested, (128.0, 96.0), Env::new(true, 1.0)); + rt.frame(0.0); + renderer.upload_images(&gpu.device, &gpu.queue, &mut rt.images); + renderer.prepare(&gpu.device, &gpu.queue, &mut rt.text.atlas, &rt.instances, (128, 96)); + assert_eq!(renderer.layer_stats().extra_passes, 1, "nested distinct per-corner clips open one outer layer"); + let out = pixels(&gpu, &renderer, &target); + for (x, y) in [(24, 20), (103, 20), (103, 75), (24, 75)] { + assert_eq!(out[(y * 128 + x) * 4 + 3], 0, "all four corners are clipped by the nested intersection at ({x},{y})"); + } + assert_eq!(out[(48 * 128 + 64) * 4 + 3], 255, "interior remains opaque"); +} diff --git a/app/vendor/rune/crates/rune/src/runtime/row_reorder_tests.rs b/app/vendor/rune/crates/rune/src/runtime/row_reorder_tests.rs new file mode 100644 index 0000000..3173d6c --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/row_reorder_tests.rs @@ -0,0 +1,288 @@ +use super::*; +use crate::{GrowthSpec, ScrollSpec, col, el}; + +/// A chat's rows, top to bottom, with their heights: messages, the last bubble `p` (36 pt) and a +/// "working" row `w` (77 pt). +type Rows = Vec<(&'static str, f32)>; + +fn chat_rows() -> Rows { + vec![("m0", 120.0), ("m1", 60.0), ("m2", 90.0), ("p", 36.0), ("w", 77.0)] +} + +fn chat(rows: &Rows, cx: &mut Cx<Rows>) -> El { + chat_in(rows, cx, true) +} + +fn chat_in(rows: &Rows, _: &mut Cx<Rows>, pinned: bool) -> El { + let stack = col().key("stack").w_full().padding(12.0).gap(8.0).growth(GrowthSpec::default()) + .children(rows.iter().map(|&(k, h)| el().key(k).w_full().h(h).fill(Color::WHITE))); + col().w_full().h_full() + .child(col().key("scroll").w_full().h(300.0).scroll(ScrollSpec { stick_bottom: pinned }).child(stack)) +} + +fn settled(rows: Rows) -> Runtime<Rows> { + let mut rt = Runtime::new(rows, chat, (300.0, 300.0), Env::new(true, 2.0)); + rt.frame(0.0); + for _ in 0..240 { rt.frame(1.0 / 120.0); } + assert!(!rt.animating); + rt +} + +fn y(rt: &Runtime<Rows>, key: &str) -> f32 { + rt.elements().into_iter().find(|e| e.key.as_deref() == Some(key) && !e.exiting).unwrap().rect[1] +} + +fn offset_tracked(rt: &Runtime<Rows>, key: &str) -> bool { + rt.tree.nodes.iter().find(|n| n.path.ends_with(&format!("/{key}"))).is_some_and(|n| rt.scene.store().has(n.id, prop::OFFSET)) +} + +fn swap_last_two(rows: &mut Rows) { + let n = rows.len(); + rows.swap(n - 2, n - 1); +} + +/// Each row's top every frame for `frames` frames at 120 Hz. +fn trace(rt: &mut Runtime<Rows>, keys: &[&str], frames: usize) -> Vec<Vec<f32>> { + (0..frames).map(|_| { rt.frame(1.0 / 120.0); keys.iter().map(|k| y(rt, k)).collect() }).collect() +} + +/// Asserts `ys` leaves `from` without a jump, heads one way to `to` in steps no bigger than +/// `step`, and lands there. +fn slides(name: &str, from: f32, to: f32, ys: &[f32], step: f32) { + let mut last = from; + for (f, &y) in ys.iter().enumerate() { + assert!((y - last).abs() <= step, "{name} jumps {} pt at frame {f}: {ys:?}", y - last); + assert!((y - last) * (to - from) >= -0.01, "{name} heads back at frame {f}: {ys:?}"); + last = y; + } + assert!((ys[0] - from).abs() > 0.01, "{name} moves on the commit's frame: {ys:?}"); + assert!((last - to).abs() < 0.01, "{name} lands at {to}: {ys:?}"); +} + +#[test] +fn a_reordered_growth_row_and_the_row_it_passes_slide_into_place() { + let mut rt = settled(chat_rows()); + let (p0, w0, m2) = (y(&rt, "p"), y(&rt, "w"), y(&rt, "m2")); + rt.update(|rows, _| swap_last_two(rows)); + let frames = trace(&mut rt, &["p", "w", "m2"], 120); + let col = |k: usize| frames.iter().map(|f| f[k]).collect::<Vec<_>>(); + slides("p", p0, p0 + 77.0 + 8.0, &col(0), 8.0); + slides("w", w0, p0, &col(1), 8.0); + assert!(col(2).iter().all(|&y| y == m2), "the rows above hold still: {:?}", col(2)); + assert!(!rt.animating); + // Swapping back mid-slide turns both rows around from where they show. + rt.update(|rows, _| swap_last_two(rows)); + let mid = trace(&mut rt, &["p", "w"], 12); + let (p1, w1) = (mid[11][0], mid[11][1]); + rt.update(|rows, _| swap_last_two(rows)); + let back = trace(&mut rt, &["p", "w"], 120); + assert!((back[0][0] - p1).abs() <= 8.0 && (back[0][1] - w1).abs() <= 8.0, "no jump turning around: {:?} from {p1}, {w1}", back[0]); + assert!((back[119][0] - (p0 + 85.0)).abs() < 0.01 && (back[119][1] - p0).abs() < 0.01, "{:?}", back[119]); +} + +#[test] +fn an_instant_or_reduced_motion_reorder_lands_at_once() { + for reduced in [false, true] { + let mut rt = settled(chat_rows()); + rt.set_system_reduced_motion(reduced); + let p0 = y(&rt, "p"); + rt.update(|rows, tx| { if !reduced { tx.instant(); } swap_last_two(rows) }); + rt.frame(1.0 / 120.0); + assert_eq!((y(&rt, "w"), y(&rt, "p")), (p0, p0 + 85.0), "reduced={reduced}"); + assert!(!offset_tracked(&rt, "p") && !offset_tracked(&rt, "w")); + } +} + +#[test] +fn rows_reordered_out_of_sight_land_at_once() { + // Read from the top, the last two rows are below the viewport before and after. + let rows = vec![("m0", 400.0), ("p", 36.0), ("w", 77.0)]; + let mut rt = Runtime::new(rows, |rows, cx| chat_in(rows, cx, false), (300.0, 300.0), Env::new(true, 2.0)); + rt.frame(0.0); + for _ in 0..240 { rt.frame(1.0 / 120.0); } + let p0 = y(&rt, "p"); + assert!(p0 >= 400.0, "{p0}"); + rt.update(|rows, _| swap_last_two(rows)); + rt.frame(1.0 / 120.0); + assert_eq!((y(&rt, "w"), y(&rt, "p")), (p0, p0 + 85.0)); + assert!(!offset_tracked(&rt, "p") && !offset_tracked(&rt, "w")); +} + +#[test] +fn a_row_moved_past_others_slides_them_and_only_them() { + let mut rt = settled(chat_rows()); + let before: Vec<f32> = ["m0", "m1", "m2", "p", "w"].iter().map(|k| y(&rt, k)).collect(); + // m1 moves below m2 and p; m0 and w keep their places. + rt.update(|rows, _| { let r = rows.remove(1); rows.insert(3, r); }); + let frames = trace(&mut rt, &["m0", "m1", "m2", "p", "w"], 120); + let col = |k: usize| frames.iter().map(|f| f[k]).collect::<Vec<_>>(); + slides("m1", before[1], before[1] + 90.0 + 36.0 + 16.0, &col(1), 12.0); + slides("m2", before[2], before[2] - 68.0, &col(2), 8.0); + slides("p", before[3], before[3] - 68.0, &col(3), 8.0); + assert!(col(0).iter().all(|&y| y == before[0]) && col(4).iter().all(|&y| y == before[4])); + assert!(!offset_tracked(&rt, "m0") && !offset_tracked(&rt, "w"), "rows nobody passed don't slide"); +} + +#[test] +fn rows_inserted_or_removed_above_a_row_move_it_on_growth_not_a_slide() { + // Growth carries a visible row through an insert or a removal above it: no jump, and no slide. + for insert in [true, false] { + let mut rt = settled(chat_rows()); + let (p0, w0) = (y(&rt, "p"), y(&rt, "w")); + rt.update(|rows, _| if insert { rows.insert(3, ("n", 50.0)) } else { rows.remove(2); }); + let frames = trace(&mut rt, &["p", "w"], 120); + let mut last = (p0, w0); + for f in &frames { + assert!((f[0] - last.0).abs() <= 8.0 && (f[1] - last.1).abs() <= 8.0, "insert={insert}: {frames:?}"); + last = (f[0], f[1]); + } + assert!(!offset_tracked(&rt, "p") && !offset_tracked(&rt, "w"), "insert={insert}"); + } +} + +#[test] +fn reorder_measures_only_rows_that_changed_order() { + let ids: Vec<NodeId> = (1..=5).map(NodeId).collect(); + let h = |id: NodeId| Some(id.0 as f32 * 10.0); + let mut r = Reorder::default(); + // Inserting, removing and keeping order: nothing moves. + r.measure(true, &ids, &[ids[0], NodeId(9), ids[1], ids[3], ids[4]], 2.0, |id| if id.0 == 9 { Some(0.0) } else { h(id) }); + assert!(r.jumps.is_empty()); + // Moving the first row last passes every other row. + r.measure(true, &ids, &[ids[1], ids[2], ids[3], ids[4], ids[0]], 2.0, h); + assert_eq!(r.jump(ids[0]), -(20.0 + 30.0 + 40.0 + 50.0 + 4.0 * 2.0)); + assert_eq!(r.jump(ids[1]), 12.0); + assert_eq!(r.jump(ids[4]), 12.0); + // A commit that lands its changes measures nothing. + r.measure(false, &ids, &[ids[1], ids[0], ids[2], ids[3], ids[4]], 2.0, h); + assert!(r.jumps.is_empty()); +} + +/// 30 virtual rows of alternating heights, in a 300 pt viewport. +fn list(rows: &Rows, _: &mut Cx<Rows>) -> El { + let stack = col().key("stack").w_full().gap(4.0).growth(GrowthSpec::default()).virtualize(40.0) + .children(rows.iter().map(|&(k, h)| el().key(k).w_full().h(h).fill(Color::WHITE))); + col().w_full().h_full() + .child(col().key("scroll").w_full().h(300.0).scroll(ScrollSpec { stick_bottom: false }).child(stack)) +} + +fn virtual_rows() -> Runtime<Rows> { + const KEYS: [&str; 30] = ["v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8", "v9", "v10", "v11", "v12", "v13", "v14", + "v15", "v16", "v17", "v18", "v19", "v20", "v21", "v22", "v23", "v24", "v25", "v26", "v27", "v28", "v29"]; + let rows = KEYS.iter().enumerate().map(|(i, &k)| (k, if i % 2 == 0 { 36.0 } else { 77.0 })).collect(); + let mut rt = Runtime::new(rows, list, (300.0, 300.0), Env::new(true, 2.0)); + rt.frame(0.0); + for _ in 0..240 { rt.frame(1.0 / 120.0); } + rt +} + +#[test] +fn reordered_virtual_rows_slide_and_a_scroll_moves_none() { + // Rows below the reader's first row, then the first row itself. + for (a, b) in [(2, 3), (0, 1)] { + let mut rt = virtual_rows(); + let (ka, kb) = (rt.state[a].0, rt.state[b].0); + let (ya, yb, hb) = (y(&rt, ka), y(&rt, kb), rt.state[b].1); + let below = rt.state[b + 1].0; + let y_below = y(&rt, below); + rt.update(|rows, _| rows.swap(a, b)); + let frames = trace(&mut rt, &[ka, kb, below], 120); + let col = |k: usize| frames.iter().map(|f| f[k]).collect::<Vec<_>>(); + slides(ka, ya, ya + hb + 4.0, &col(0), 8.0); + slides(kb, yb, ya, &col(1), 8.0); + assert!(col(2).iter().all(|&y| y == y_below), "rows nobody passed hold still: {:?}", col(2)); + } + // Scrolling shifts the window and mounts rows: nothing slides. + let mut rt = virtual_rows(); + for _ in 0..30 { rt.wheel(100.0, 100.0, -40.0); rt.frame(1.0 / 120.0); } + for _ in 0..240 { rt.frame(1.0 / 120.0); } + assert!(rt.elements().iter().all(|e| e.key.as_deref() != Some("v0")), "scrolled past the first rows"); + let keys: Vec<&str> = rt.state.iter().map(|r| r.0).collect(); + assert!(keys.iter().all(|k| !offset_tracked(&rt, k)), "a window shift slides no row"); +} + +#[test] +fn a_row_that_moves_and_grows_slides_without_a_step() { + // A delivered prompt grows from 53 to 77 pt and moves above the Working row in one commit. + let mut rt = settled(vec![("m0", 120.0), ("m1", 60.0), ("m2", 90.0), ("w", 77.0), ("a", 53.0), ("b", 53.0)]); + let (a0, w0, b0) = (y(&rt, "a"), y(&rt, "w"), y(&rt, "b")); + rt.update(|rows, _| { rows[4].1 = 77.0; let a = rows.remove(4); rows.insert(3, a); }); + let frames = trace(&mut rt, &["a", "w", "b"], 120); + assert!(!rt.animating); + let col = |k: usize| frames.iter().map(|f| f[k]).collect::<Vec<_>>(); + let end = &frames[119]; + assert!((end[1] - end[0] - 85.0).abs() < 0.01, "Working rests under the grown row: {end:?}"); + slides("a", a0, end[0], &col(0), 8.0); + slides("w", w0, end[1], &col(1), 8.0); + let mut last = b0; + for (f, &y) in col(2).iter().enumerate() { + assert!((y - last).abs() <= 8.0, "b jumps {} pt at frame {f}: {:?}", y - last, col(2)); + last = y; + } +} + +/// Three rows whose contents sit under a gap, with a foot under each body; the middle row's gap +/// and body height are the state. +fn gapped(&(gap, body): &(f32, f32), _: &mut Cx<(f32, f32)>) -> El { + let row = |k: &'static str, pt: f32, h: f32| col().key(k).w_full().pt(pt) + .child(el().key(format!("{k}-body")).w_full().h(h).fill(Color::WHITE)) + .child(el().key(format!("{k}-foot")).w_full().h(20.0).mt(4.0).fill(Color::WHITE)); + let stack = col().key("stack").w_full().padding(12.0).gap(8.0).growth(GrowthSpec::default()) + .child(row("a", 16.0, 37.0)).child(row("b", gap, body)).child(row("c", 16.0, 37.0)); + col().w_full().h_full().child(col().key("scroll").w_full().h(400.0).scroll(ScrollSpec { stick_bottom: false }).child(stack)) +} + +#[test] +fn contents_whose_gap_in_their_row_changes_slide_from_where_they_were_drawn() { + // A steer stops joining the prompt above it: its gap grows from 4 to 16 pt. + let mut rt = Runtime::new((4.0f32, 37.0f32), gapped, (300.0, 400.0), Env::new(true, 2.0)); + rt.frame(0.0); + for _ in 0..240 { rt.frame(1.0 / 120.0); } + let at = |rt: &Runtime<(f32, f32)>, k: &str| rt.elements().into_iter().find(|e| e.key.as_deref() == Some(k) && !e.exiting).unwrap().rect[1]; + let keys = ["b-body", "b-foot", "c-body"]; + let ys0 = keys.map(|k| at(&rt, k)); + rt.update(|s, _| s.0 = 16.0); + let frames: Vec<[f32; 3]> = (0..120).map(|_| { rt.frame(1.0 / 120.0); keys.map(|k| at(&rt, k)) }).collect(); + assert!(!rt.animating); + for (k, key) in keys.iter().enumerate() { + slides(key, ys0[k], ys0[k] + 12.0, &frames.iter().map(|f| f[k]).collect::<Vec<_>>(), 3.0); + } + // A body that grows moves the foot under it at once, as the row's growth reveals it. + let foot = at(&rt, "b-foot"); + rt.update(|s, _| s.1 = 77.0); + rt.frame(1.0 / 120.0); + assert_eq!(at(&rt, "b-foot"), foot + 40.0); + // Instant, the gap lands at once. + rt.update(|s, tx| { tx.instant(); s.0 = 4.0 }); + rt.frame(1.0 / 120.0); + assert_eq!(at(&rt, "b-body"), ys0[0]); +} + +/// A tall row, then a last row whose contents sit under a gap it fits around, in a list pinned to +/// its end; the gap is the state. +fn pinned_gap(&gap: &f32, _: &mut Cx<f32>) -> El { + let last = col().key("b").w_full().pt(gap) + .child(el().key("b-body").w_full().h(37.0).fill(Color::WHITE)) + .child(el().key("b-foot").w_full().h(20.0).mt(4.0).fill(Color::WHITE)); + let stack = col().key("stack").w_full().padding(12.0).gap(8.0).growth(GrowthSpec::default()) + .child(el().key("a").w_full().h(400.0).fill(Color::WHITE)).child(last); + col().w_full().h_full().child(col().key("scroll").w_full().h(300.0).scroll(ScrollSpec { stick_bottom: true }).child(stack)) +} + +#[test] +fn contents_whose_gap_opens_as_their_row_grows_at_a_pinned_end_hold_still() { + // The last steer stops joining the prompt above it: its gap and its height grow by 12 pt, so + // its row rises 12 pt and its contents keep their place on every frame. + let mut rt = Runtime::new(4.0f32, pinned_gap, (300.0, 300.0), Env::new(true, 2.0)); + rt.frame(0.0); + for _ in 0..240 { rt.frame(1.0 / 120.0); } + let at = |rt: &Runtime<f32>, k: &str| rt.elements().into_iter().find(|e| e.key.as_deref() == Some(k) && !e.exiting).unwrap().rect[1]; + let (row0, body0, foot0) = (at(&rt, "b"), at(&rt, "b-body"), at(&rt, "b-foot")); + rt.update(|s, _| *s = 16.0); + let frames: Vec<[f32; 3]> = (0..120).map(|_| { rt.frame(1.0 / 120.0); ["b", "b-body", "b-foot"].map(|k| at(&rt, k)) }).collect(); + assert!(!rt.animating); + slides("b", row0, row0 - 12.0, &frames.iter().map(|f| f[0]).collect::<Vec<_>>(), 3.0); + for (f, ys) in frames.iter().enumerate() { + assert!((ys[1] - body0).abs() < 1.0 / 64.0 && (ys[2] - foot0).abs() < 1.0 / 64.0, "the contents move at frame {f}: {frames:?}"); + } +} diff --git a/app/vendor/rune/crates/rune/src/runtime/scroll.rs b/app/vendor/rune/crates/rune/src/runtime/scroll.rs new file mode 100644 index 0000000..8279f24 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/scroll.rs @@ -0,0 +1,18 @@ +//! Scroll viewports, wheel and touch scrolling, scroll anchoring, reveal/keep requests, sticky +//! headers and scroll-watch notifications. +use super::*; + +pub(super) mod anchor; +pub(super) mod bottom; +pub(super) mod drawn; +pub(super) mod edge; +pub(super) mod mode; +pub(super) mod nudge; +pub(super) mod offset; +pub(super) mod requests; +pub(super) mod reveal; +pub(super) mod sticky; +pub(super) mod touch; +pub(super) mod watch; +pub(super) mod wheel; +pub(super) mod x; diff --git a/app/vendor/rune/crates/rune/src/runtime/scroll/anchor.rs b/app/vendor/rune/crates/rune/src/runtime/scroll/anchor.rs new file mode 100644 index 0000000..9c5d2fa --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/scroll/anchor.rs @@ -0,0 +1,54 @@ +//! `El::scroll_anchor`: a viewport keeps the row at the top of its view where it is when a +//! commit changes the content above it, as CSS `overflow-anchor: auto` does. Each commit +//! holds that row with the same `Keep` a `Tx::keep_on_screen` makes, so it follows growth and +//! layout springs too; a commit that changes nothing above the row moves nothing. +use super::*; + +impl requests::ScrollTables { + /// Whether viewport `s` anchors now: scrolled off its top, not following its bottom, still + /// (a hold would stop a fling or a glide where it is), and not already holding a row or + /// revealing one. + pub(super) fn anchor_holds(&self, nodes: &[Node], s: usize) -> bool { + let path = &nodes[s].path; + if self.requests.owns(path) { return false; } + self.scrolls.get(&nodes[s].id).is_some_and(|st| { + st.offset > 0.5 && !st.pinned() && !st.scrolling() && !st.direct() && st.coast() == 0.0 && st.glide().is_none() + }) + } +} + +impl RuntimeCore { + /// Before a commit: puts each anchored viewport's top row ahead of the app's own + /// `Tx::keep_on_screen` keys, which win when they name a row in the same viewport. + pub(in crate::runtime) fn anchor_keeps(&self, tx: &mut Tx) { + if !self.tree.built || self.paint.drawn.len() != self.tree.nodes.len() { return; } + let rows: Vec<String> = (0..self.tree.nodes.len()) + .filter(|&s| self.tree.nodes[s].scroll_edges.anchor && self.tree.nodes[s].scroll_axes.y()) + .filter(|&s| self.scroll.anchor_holds(&self.tree.nodes, s)) + .filter_map(|s| self.anchor_row(s)) + .map(|i| self.tree.nodes[i].path.clone()) + .collect(); + if rows.is_empty() { return; } + tx.keep_on_screen.splice(0..0, rows); + } + + /// The row viewport `s` anchors to: the first child drawn in its view, or inside a child + /// that starts above the view, the first of that child's children, and so on down. Virtual + /// rows keep their own anchor, so a virtual list holds none. + fn anchor_row(&self, s: usize) -> Option<usize> { + let top = self.paint.drawn[s][1]; + let bottom = top + self.paint.drawn[s][3]; + let mut parent = s; + if self.commit.virtuals.contains_key(&self.tree.nodes[s].path) { return None; } + loop { + let child = (parent + 1..self.tree.nodes.len()).filter(|&j| self.tree.nodes[j].parent == Some(parent)).find(|&j| { + let [_, y, w, h] = self.paint.drawn[j]; + w > 0.0 && h > 0.0 && y + h > top + 0.5 && y < bottom && self.tree.nodes[j].sticky.is_none() && !self.subtree_exiting(j) + })?; + if self.commit.virtuals.contains_key(&self.tree.nodes[child].path) { return None; } + let into = self.paint.drawn[child][1] < top - 0.5 && self.tree.nodes.get(child + 1).is_some_and(|n| n.parent == Some(child)); + if !into { return Some(child); } + parent = child; + } + } +} diff --git a/app/vendor/rune/crates/rune/src/runtime/scroll/bottom.rs b/app/vendor/rune/crates/rune/src/runtime/scroll/bottom.rs new file mode 100644 index 0000000..c09f0e7 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/scroll/bottom.rs @@ -0,0 +1,345 @@ +//! Where a scroll viewport stands against its bottom: `El::on_at_bottom` reports changes, and +//! `Tx::scroll_to_bottom` glides there (a chat's "jump to latest"). +use super::*; + +/// The glide's spring (`motion::GLIDE`) retargets each frame, so content growing under it +/// extends the trip. +/// A glide starts at most this many viewports above the bottom (a longer trip cuts first). +pub(in crate::runtime) const GLIDE_REACH: f64 = 2.0; +/// Within this many points of the bottom a viewport counts as showing it. +const AT_BOTTOM: f64 = 1.0; +/// Slack starts closing once its stack has stopped growing for this long (seconds). +const SLACK_WAIT: f64 = 0.12; + +/// Room a pinned viewport gains at its bottom (a composer shrinking under it), held under its +/// growth stack's last row instead of carrying the rows down. Rows growing in fill it first; +/// once the stack has stopped growing for `SLACK_WAIT`, the rest closes on the growth spring. +/// Without it, a send dips the rows: the composer gives its room back faster than the new +/// row's capped growth takes it. +#[derive(Clone, Copy, Debug, Default)] +pub(in crate::runtime) struct Slack { + /// `h` is the slack in points, stepped toward 0 once closing. + track: GrowTrack, + phase: SlackPhase, + /// The last step moved `h`, so the frame after it still counts as moving. + stepped: bool, + /// The viewport's presented top and bottom last frame. + edges: Option<[f32; 2]>, + /// The window size at the last commit: a resize lands the slack. + pub(in crate::runtime) window: (f32, f32), + /// `Tx::follow_edge`: until the viewport's edges reach their layout, the rows ride them + /// and the room they free adds no slack. + pub(in crate::runtime) follow: bool, +} + +/// Whether the slack waits under the rows or closes on the growth spring. +#[derive(Clone, Copy, Debug, PartialEq)] +enum SlackPhase { + /// Held while the stack grows, and for `SLACK_WAIT` after a row last grew (`grew_at`). + Held { grew_at: f64 }, + /// Closing, stepped by each frame's time. + Closing, +} + +impl Default for SlackPhase { + fn default() -> Self { SlackPhase::Held { grew_at: 0.0 } } +} + +/// Done closing without the stack growing again: the wait is already over, so slack that opens +/// next closes at once. +const WAITED: SlackPhase = SlackPhase::Held { grew_at: f64::NEG_INFINITY }; + +impl Slack { + pub(in crate::runtime) fn height(&self) -> f32 { self.track.h } + + pub(in crate::runtime) fn moving(&self) -> bool { self.track.h > 0.0 || self.stepped } + + /// No slack, in a window of this size. + pub(in crate::runtime) fn landed(window: (f32, f32)) -> Slack { Slack { window, ..Slack::default() } } + + /// Moves the phase on at `now` with `dt` of frame time, once `h` has this frame's growth + /// and edges: a growing stack holds the slack, one quiet for `SLACK_WAIT` starts it closing, + /// and closing steps `h` toward 0 on the stack's spring. + fn settle(&mut self, growing: bool, now: f64, dt: f32, spec: &crate::GrowthSpec) { + if growing { + self.phase = SlackPhase::Held { grew_at: now }; + self.track.v = 0.0; + } + if self.track.h <= 1.0 / 128.0 { + self.track = GrowTrack::default(); + if matches!(self.phase, SlackPhase::Closing) { self.phase = WAITED; } + } else if let SlackPhase::Held { grew_at } = self.phase && now - grew_at >= SLACK_WAIT { + self.phase = SlackPhase::Closing; + self.track.age = 0.0; + self.track.v = 0.0; + } + if let SlackPhase::Closing = self.phase { + for step in crate::growth::substeps(dt) { + self.track.step_by(step, spec.spring, &spec.edge, false); + } + self.phase = if self.track.moving() { SlackPhase::Closing } else { + self.track = GrowTrack::default(); + WAITED + }; + } + } +} + +/// Steps a glide toward the current bottom, or the offset `Tx::scroll_to` asked for while the +/// content reaches it. Returns whether it is still moving. +pub(in crate::runtime) fn glide(st: &mut ScrollState, dt: f32) -> bool { + let ScrollMode::Glide { v, to: aim, .. } = st.mode else { return false }; + let to = aim.offset().map_or(st.max, |to| to.min(st.max)); + // Content shrinking past the glide's end lands it there, rather than its speed carrying + // it past and springing back. + if st.offset >= st.max && to >= st.max { + st.offset = st.max; + st.mode = st.mode.to_rest(); + return false; + } + let mut glide = Some(v); + let moving = scroll_offset::glide_axis(st.glide_spring(), &mut st.offset, &mut glide, to, dt); + st.mode = match glide { + Some(v) => st.mode.to_glide(v, aim), + None => st.mode.to_rest(), + }; + moving +} + +impl requests::ScrollTables { + #[inline] + pub(in crate::runtime) fn at_bottom(&self, id: NodeId) -> Option<bool> { + self.scrolls.get(&id).map(|st| st.offset >= st.max - AT_BOTTOM) + } +} + +impl RuntimeCore { + /// The scroll viewport `key` names (`Node::named`), or the nearest one containing it. + pub(in crate::runtime) fn scroll_viewport(&self, key: &str) -> Option<usize> { + let mut i = self.tree.nodes.iter().enumerate() + .position(|(i, n)| n.named(key) && !self.subtree_exiting(i))?; + loop { + if self.tree.nodes[i].scroll.is_some() && self.tree.nodes[i].scroll_axes.y() { return Some(i); } + i = self.tree.nodes[i].parent?; + } + } + + pub(in crate::runtime) fn scroll_to_bottom(&mut self, app: &mut dyn AppDriver, requests: Vec<(String, bool)>) { + // This frame's commit may have changed the content: measure the extent first. + self.step_scroll(0.0); + let mut targets = Vec::new(); + for (key, animated) in requests { + let Some(i) = self.scroll_viewport(&key) else { continue }; + let (id, sticky, view_h) = (self.tree.nodes[i].id, self.tree.nodes[i].scroll.is_some_and(|s| s.stick_bottom), f64::from(self.tree.nodes[i].local.h)); + let Some(st) = self.scroll.scrolls.get_mut(&id) else { continue }; + targets.push((id, animated, sticky, view_h, st.offset, st.glide())); + // Stand at the bottom first so a virtual list mounts and measures its tail rows, + // which can differ from the estimate: the trip below then ends at the true bottom. + st.offset = st.max; + st.pin(); + } + for _ in 0..3 { + if !self.virtual_window_changed() { break; } + self.commit(app, &Tx::default()); + self.step_scroll(0.0); + for (id, ..) in &targets { + if let Some(st) = self.scroll.scrolls.get_mut(id) { st.offset = st.max; } + } + } + for (id, animated, sticky, view_h, start, glide) in targets { + let Some(st) = self.scroll.scrolls.get_mut(&id) else { continue }; + // A settled frame (a window showing or uncovering) lands at the end. + if animated && !self.reduced_motion && !self.settled && st.max - start > 0.5 { + st.offset = start.max(st.max - GLIDE_REACH * view_h); + st.mode = st.mode.to_glide(glide.unwrap_or(0.0), GlideTo::Bottom); + st.spring = None; + } else { + st.offset = st.max; + if sticky { st.pin() } else { st.mode = st.mode.to_rest() } + } + } + if self.virtual_window_changed() { + self.commit(app, &Tx::default()); + self.step_scroll(0.0); + } + } + + /// `Tx::scroll_page`: each viewport moves by its requested pages. + pub(in crate::runtime) fn scroll_pages(&mut self, app: &mut dyn AppDriver, requests: Vec<(String, i32)>) { + // This frame's commit may have changed the content: measure the extent first. + self.step_scroll(0.0); + for (key, pages) in requests { + let Some(i) = self.scroll_viewport(&key) else { continue }; + self.page_to(i, |offset, _, page| offset + page * f64::from(pages)); + } + if self.virtual_window_changed() { + self.commit(app, &Tx::default()); + self.step_scroll(0.0); + } + } + + /// The offset to draw stuck-to-bottom viewport `i` at, whose presented bottom edge is + /// `bottom`: layout's offset keeps the content's target bottom on the viewport's target + /// bottom, but while either is still animating (the viewport resizing under a banner) + /// that would jump the rows and slide them back. This keeps the presented edges together. + /// + /// Rows that sat on the bottom hold it as the content crosses between overflowing and + /// fitting: while they still end on the bottom (`justify_end`), or until the content's top + /// would carry them above it, after which they ride the content's top. The offset goes + /// negative while fitting rows sit low in a box that has not shrunk yet. + pub(in crate::runtime) fn stuck_offset(&self, i: usize, bottom: f32) -> Option<f64> { + let n = &self.tree.nodes[i]; + let st = self.scroll.scrolls.get(&n.id).filter(|st| st.pinned())?; + if !n.scroll.is_some_and(|s| s.stick_bottom) { return None; } + let c = self.scroll_content(i)?; + let lag = self.stuck_lag(i, c, bottom)?; + // How far the rows end above the bottom in the layout (negative past it), beside the + // stack's own bottom padding and border. + let content_bottom = self.scroll_children(i) + .map(|k| { + let pad = self.motion.stacks.get(&self.tree.nodes[k].id).map_or(0.0, |s| (s.pad_bottom - self.tree.nodes[k].inset[3]).max(0.0)); + self.tree.nodes[k].target[3] - pad + }) + .reduce(f32::max)?; + let short = f64::from(n.target[3] - content_bottom); + // Stuck on a shrinking stack's end: the rows' last fraction collapses under it (see `step_scroll`). + let end = st.laid().filter(|&end| st.offset <= end + 1e-6).unwrap_or(f64::INFINITY); + if st.held && (short <= 0.5 || lag - short >= -0.5) { + Some(self.scroll_overflow(i).min(end) + lag) + } else if st.max > 0.0 { + Some((st.max.min(end) + lag).max(0.0)) + } else { + // Content that fits the viewport's layout can still reach past its presented bottom + // while the viewport grows toward it (a composer shrinking after a send): follow it + // from there, not from when the layout overflows, which landed the gap in one frame. + let at = self.scroll_overflow(i).min(end) + lag; + (at > 0.0).then_some(at) + } + } + + /// The offset that draws viewport `i`'s content bottom on its presented bottom `bottom`. + pub(in crate::runtime) fn bottom_offset(&self, i: usize, bottom: f32) -> Option<f64> { + let c = self.scroll_content(i)?; + Some(self.scroll_overflow(i) + self.stuck_lag(i, c, bottom)?) + } + + /// Scroll viewport `i`'s present direct children. + pub(in crate::runtime) fn scroll_children(&self, i: usize) -> impl Iterator<Item = usize> + '_ { + (i + 1..self.tree.nodes.len()) + .take_while(move |&j| self.tree.nodes[j].parent >= Some(i)) + .filter(move |&j| self.tree.nodes[j].parent == Some(i) && !self.is_exiting(self.tree.nodes[j].id) && self.scene.contains(self.tree.nodes[j].id)) + } + + /// Scroll viewport `i`'s growth-stack child, or the child that supplies its content end. + pub(in crate::runtime) fn scroll_content(&self, i: usize) -> Option<usize> { + let view = self.tree.nodes[i].target; + self.scroll_stack(i).or_else(|| { + self.scroll_children(i).max_by(|&a, &b| { + let end = |c: usize| { + let n = &self.tree.nodes[c]; + f64::from(n.target[1] - view[1]) + self.stack_extent(c).unwrap_or(f64::from(n.target[3] - n.target[1])) + }; + end(a).total_cmp(&end(b)) + }) + }) + } + + /// Scroll viewport `i`'s growth-stack child, if any. + pub(in crate::runtime) fn scroll_stack(&self, i: usize) -> Option<usize> { + self.scroll_children(i).find(|&c| self.tree.nodes[c].growth.is_some()) + } + + /// How much further content `c` of viewport `i` has to travel to its layout than the + /// viewport's presented bottom `bottom` has. + fn stuck_lag(&self, i: usize, c: usize, bottom: f32) -> Option<f64> { + let top = self.scene.presented(self.tree.nodes[c].id)?.rect.edges()[1]; + Some(f64::from((top - self.tree.nodes[c].target[1]) - (bottom - self.tree.nodes[i].target[3]))) + } + + /// Steps stick-to-bottom viewport `i`'s `Slack` after its offset. Returns whether any is left. + pub(in crate::runtime) fn step_slack(&mut self, i: usize, dt: f32) -> bool { + let id = self.tree.nodes[i].id; + if self.scroll.scrolls.get(&id).is_some_and(|st| !st.pinned() && !st.slack.moving()) { + if let Some(st) = self.scroll.scrolls.get_mut(&id) { st.slack.edges = None; } + return false; + } + let Some(c) = self.scroll_content(i) else { return false }; + let stack = self.tree.nodes[c].growth.as_deref().copied().and_then(|spec| Some((spec, self.motion.stacks.get_mut(&self.tree.nodes[c].id)?))); + let view = self.scene.presented(id).map(|p| p.rect.edges()); + let (Some((spec, stack)), Some(view), false) = (stack, view, self.reduced_motion) else { + if let Some(st) = self.scroll.scrolls.get_mut(&id) { st.slack = Slack::landed(st.slack.window); } + return false; + }; + let grown = std::mem::take(&mut stack.grown); + let growing = stack.growing; + let pad = (stack.pad_bottom - self.tree.nodes[c].inset[3]).max(0.0); + let short = self.tree.nodes[i].target[3] - (self.tree.nodes[c].target[3] - pad); + let top_c = self.scene.presented(self.tree.nodes[c].id).map_or(view[1], |p| p.rect.edges()[1]); + let limit = top_c + (self.tree.nodes[c].target[3] - self.tree.nodes[c].target[1] - pad); + let now = self.t; + let target = self.tree.nodes[i].target; + let Some(st) = self.scroll.scrolls.get_mut(&id) else { return false }; + let pinned = st.pinned(); + let s = &mut st.slack; + let h0 = s.track.h; + let [top, bottom] = [view[1], view[3]]; + if pinned { + // Growth fills the slack first. Room the bottom edge gains while the rows sit on it + // joins it, unless the whole viewport moved down with it. + let mut h = s.track.h - grown; + if let Some([top0, bottom0]) = s.edges && st.held && !s.follow { + let (b0, b1) = if short > 0.5 { (bottom0.min(limit), bottom.min(limit)) } else { (bottom0, bottom) }; + h += (b1 - b0) - (top - top0).max(0.0); + } + s.track.h = h.max(0.0); + } + s.edges = Some([top, bottom]); + if s.follow && (top - target[1]).abs() < 0.01 && (bottom - target[3]).abs() < 0.01 { s.follow = false; } + s.settle(growing, now, dt, &spec); + s.stepped = (s.track.h - h0).abs() > 1e-5; + s.moving() + } + + /// Queues `on_at_bottom` and `on_far_from_bottom` for viewports whose state changed this + /// frame. + pub(in crate::runtime) fn report_at_bottom(&mut self) { + for i in 0..self.tree.nodes.len() { + let n = &self.tree.nodes[i]; + let Some(h) = n.handlers.get().filter(|h| h.on_at_bottom.is_some() || h.on_far_from_bottom.is_some()) else { continue }; + if self.subtree_exiting(i) { continue; } + let Some(st) = self.scroll.scrolls.get_mut(&n.id) else { continue }; + if h.on_at_bottom.is_some() { + let at = st.offset >= st.max - AT_BOTTOM; + if st.at_bottom != Some(at) { + st.at_bottom = Some(at); + self.frame.queue.push(Action::AtBottom(n.path.clone(), at)); + } + } + if let Some((min, under, _)) = &h.on_far_from_bottom { + // Under a frame, its height counts: the nearest ancestor with that key. + let tall = under.as_deref().and_then(|k| { + self.tree.nodes.iter().filter(|m| m.key.as_deref() == Some(k) && n.path.starts_with(&m.path) && n.path[m.path.len()..].starts_with('/')) + .max_by_key(|m| m.path.len()).map(|m| m.local.h) + }).unwrap_or(n.local.h); + // Rows collapsing measure from the end they head for, glide or not. + let end = st.laid().map_or(st.max, |end| end.min(st.max)); + let far = end - st.offset > f64::from(min.max(tall)); + if st.far_from_bottom != Some(far) { + st.far_from_bottom = Some(far); + self.frame.queue.push(Action::FarFromBottom(n.path.clone(), far)); + } + } + } + } + + /// Whether the scroll viewport keyed `key` (or the one containing it) shows its bottom, + /// as of the last frame. + pub fn scroll_at_bottom(&self, key: &str) -> Option<bool> { + let i = self.scroll_viewport(key)?; + self.scroll.at_bottom(self.tree.nodes[i].id) + } +} + +#[cfg(test)] +#[path = "bottom_tests.rs"] +mod tests; diff --git a/app/vendor/rune/crates/rune/src/runtime/scroll/bottom_tests.rs b/app/vendor/rune/crates/rune/src/runtime/scroll/bottom_tests.rs new file mode 100644 index 0000000..cefc740 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/scroll/bottom_tests.rs @@ -0,0 +1,750 @@ +use super::*; +use crate::el::{col, el}; + +#[test] +fn slack_waits_out_growth_then_closes_and_slack_after_that_closes_at_once() { + let (spec, dt) = (GrowthSpec::default(), 1.0 / 120.0); + let mut s = Slack::default(); + s.track.h = 40.0; + s.settle(true, 1.0, dt, &spec); + assert_eq!(s.phase, SlackPhase::Held { grew_at: 1.0 }); + s.settle(false, 1.0 + SLACK_WAIT * 0.9, dt, &spec); + assert_eq!((s.phase, s.track.h), (SlackPhase::Held { grew_at: 1.0 }, 40.0), "held through the wait"); + s.settle(false, 1.0 + SLACK_WAIT, dt, &spec); + assert!(matches!(s.phase, SlackPhase::Closing { .. }) && s.track.h < 40.0); + let h = s.track.h; + s.settle(true, 1.2, dt, &spec); + assert_eq!((s.phase, s.track.h), (SlackPhase::Held { grew_at: 1.2 }, h), "growth holds it again"); + + let mut now = 1.2; + while s.phase != WAITED { + now += f64::from(dt); + s.settle(false, now, dt, &spec); + assert!(now < 3.0, "closes: {s:?}"); + } + assert_eq!(s.track.h, 0.0); + s.track.h = 10.0; + s.settle(false, now + f64::from(dt), dt, &spec); + assert!(matches!(s.phase, SlackPhase::Closing { .. }), "the wait was already over"); +} + +// One state type for every test here: each type monomorphises a whole `Runtime<S>`. +#[derive(Default)] +struct Chat { rows: usize, reports: Vec<bool>, instant: bool, reduced: bool, virtualized: bool, loose: bool, tall_tail: bool, composer: Option<crate::TextEdit>, sends: bool, track_drawn: bool, drawn: Vec<f32>, far: Vec<bool>, dock: Option<f32>, under: bool } + +fn view(s: &Chat, cx: &mut Cx<Chat>) -> El { + cx.reduced_motion(s.reduced); + let mut stack = col().key("stack").w_full().growth(GrowthSpec::default()); + if s.virtualized { stack = stack.virtualize(60.0); } + for i in 0..s.rows { + let h = if s.tall_tail && i + 10 >= s.rows { 150.0 } else { 40.0 + (i % 3) as f32 * 10.0 }; + let mut row = el().key(format!("r{i}")).w_full().h(h); + if i == 0 && s.track_drawn { + row = row.on_drawn_layout(|s: &mut Chat, r| s.drawn.push(r[1])); + } + stack = stack.child(row); + } + let scroll = col().key("scroll").w_full().grow(1.0).shrink().scroll(ScrollSpec { stick_bottom: !s.loose }) + .on_at_bottom(|s: &mut Chat, at| s.reports.push(at)); + let scroll = if s.under { + scroll.on_far_from_bottom_under(400.0, "pane", |s: &mut Chat, far| s.far.push(far)) + } else { + scroll.on_far_from_bottom(400.0, |s: &mut Chat, far| s.far.push(far)) + }; + let root = col().key("pane").w_full().h_full().child(scroll.child(stack)) + .child(el().key("jump").w_full().h(40.0).on_press_tx(|s: &mut Chat, tx| { + if s.instant { tx.scroll_to_bottom_instant("stack") } else { tx.scroll_to_bottom("scroll") } + })); + // A dock under the list that grows and shrinks with no row coming in. + let root = match s.dock { Some(h) => root.child(el().key("dock").w_full().h(h)), None => root }; + // A multi-line composer below the list, in its own small scroll area. + let Some(edit) = &s.composer else { return root }; + let field = crate::text_input(edit, crate::TextStyle::new(14.0, 400.0)).key("composer").w_full() + .on_edit(|s: &mut Chat| s.composer.as_mut().unwrap()); + // A chat's composer: sending clears it, so it shrinks on its spring as the row grows in. + if s.sends { + return root.child(field.animate_edit_layout().on_submit(|s: &mut Chat, _| { + s.composer.as_mut().unwrap().clear(); + s.rows += 1; + })); + } + root.child(col().key("composer-scroll").w_full().h(60.0).scroll(ScrollSpec { stick_bottom: false }).child(field)) +} + +fn chat(state: Chat) -> Runtime<Chat> { + let mut rt = Runtime::new(state, view, (200.0, 340.0), Env::new(true, 2.0)); + rt.frame(0.0); + rt.frame(1.0 / 120.0); + rt +} + +fn press(rt: &mut Runtime<Chat>, key: &str) { + let (x, y) = rt.find(key).unwrap(); + rt.pointer_down(x, y); + rt.pointer_up(x, y); +} + +fn bottom_gap(rt: &Runtime<Chat>) -> f32 { + let last = rt.elements().into_iter().find(|e| e.key.as_deref() == Some(&*format!("r{}", rt.state.rows - 1))).unwrap(); + 300.0 - (last.rect[1] + last.rect[3]) +} + +#[test] +fn at_bottom_reports_once_per_change_and_glides_back() { + let mut rt = chat(Chat { rows: 40, ..Default::default() }); + assert_eq!(rt.state.reports, [true], "the first layout reports its state"); + assert_eq!(rt.scroll_at_bottom("scroll"), Some(true)); + for _ in 0..5 { + rt.wheel(100.0, 100.0, 300.0); + rt.frame(1.0 / 120.0); + } + rt.frame(1.0 / 120.0); + assert_eq!(rt.state.reports, [true, false], "scrolling further up does not report again"); + let commits = rt.stats.commits; + for _ in 0..30 { rt.frame(1.0 / 120.0); } + assert_eq!(rt.stats.commits, commits, "no per-frame callbacks or commits at rest"); + assert!(bottom_gap(&rt) < -1000.0, "reading far up: {}", bottom_gap(&rt)); + + press(&mut rt, "jump"); + rt.frame(1.0 / 120.0); + let start = bottom_gap(&rt); + assert!((-600.0..0.0).contains(&start), "a long trip cuts to two viewports from the end: {start}"); + let mut previous = start; + let mut frames = 0; + while rt.state.reports.len() < 3 && frames < 240 { + rt.frame(1.0 / 120.0); + let gap = bottom_gap(&rt); + assert!(gap >= previous - 0.01, "the glide only moves toward the bottom: {previous} -> {gap}"); + previous = gap; + frames += 1; + } + assert!(frames > 10, "the glide is animated ({frames} frames)"); + assert_eq!(rt.state.reports, [true, false, true]); + for _ in 0..60 { rt.frame(1.0 / 120.0); } + assert!(bottom_gap(&rt).abs() < 0.05, "{}", bottom_gap(&rt)); + assert!(!rt.animating); + rt.state.rows += 1; + rt.invalidate(); + for _ in 0..120 { rt.frame(1.0 / 120.0); } + assert!(bottom_gap(&rt).abs() < 0.05, "a sticky viewport follows the end again after landing"); + assert_eq!(rt.state.reports, [true, false, true]); + assert!(!rt.animating); +} + +/// Far from the bottom means more than the viewport's height (300 here) and at least +/// `min` (400) above it; a glide back reports near before it lands. +#[test] +fn far_from_bottom_reports_past_its_threshold_only() { + let mut rt = chat(Chat { rows: 40, ..Default::default() }); + assert_eq!(rt.state.far, [false], "the first layout reports its state"); + rt.update(|_, tx| tx.scroll_to_y("scroll", 1e6)); + let max = rt.elements().into_iter().find(|e| e.key.as_deref() == Some("stack")).unwrap().rect[3] - 300.0; + rt.update(|_, tx| tx.scroll_to_y("scroll", max - 350.0)); + for _ in 0..3 { rt.frame(1.0 / 120.0); } + assert_eq!(rt.state.far, [false], "350 above the bottom is within 400"); + rt.update(|_, tx| tx.scroll_to_y("scroll", max - 450.0)); + for _ in 0..3 { rt.frame(1.0 / 120.0); } + assert_eq!(rt.state.far, [false, true]); + let commits = rt.stats.commits; + for _ in 0..30 { rt.frame(1.0 / 120.0); } + assert_eq!(rt.stats.commits, commits, "no per-frame callbacks at rest"); + press(&mut rt, "jump"); + let mut near_at = None; + for f in 0..240 { + rt.frame(1.0 / 120.0); + if near_at.is_none() && rt.state.far.len() == 3 { near_at = Some((f, bottom_gap(&rt))); } + } + let (_, gap) = near_at.expect("the glide reports near"); + assert!((-400.0..0.0).contains(&gap), "near once within 400 of the end, before landing: {gap}"); + assert_eq!(rt.state.far, [false, true, false]); +} + +/// Under its pane, a viewport counts the pane's height (640) rather than its own (600, the +/// jump row under it), read as it scrolls: 620 up is near, 660 far, and a resize runs no view. +#[test] +fn far_under_a_frame_counts_the_frames_height() { + let far_at = |under: bool, up: f32| { + let mut rt = Runtime::new(Chat { rows: 60, under, ..Default::default() }, view, (200.0, 640.0), Env::new(true, 2.0)); + rt.frame(0.0); + rt.frame(1.0 / 120.0); + rt.update(|_, tx| tx.scroll_to_y("scroll", 1e6)); + let max = rt.elements().into_iter().find(|e| e.key.as_deref() == Some("stack")).unwrap().rect[3] - 600.0; + rt.update(|_, tx| tx.scroll_to_y("scroll", max - up)); + for _ in 0..3 { rt.frame(1.0 / 120.0); } + rt.state.far.last().copied() + }; + assert_eq!(far_at(false, 620.0), Some(true), "past its own 600"); + assert_eq!(far_at(true, 620.0), Some(false), "within the pane's 640"); + assert_eq!(far_at(true, 660.0), Some(true), "past the pane's 640"); +} + +/// A scroll to the bottom asked for while the window is covered (or hidden) waits for the +/// frame that uncovers it, which settles: that frame shows the bottom, with no glide after. +/// (Settling already pins a sticky viewport; this one isn't.) +#[test] +fn a_scroll_asked_while_covered_lands_when_it_uncovers() { + let mut rt = chat(Chat { rows: 40, loose: true, ..Default::default() }); + for _ in 0..5 { + rt.wheel(100.0, 100.0, 300.0); + rt.frame(1.0 / 120.0); + } + for _ in 0..60 { rt.frame(1.0 / 120.0); } + assert!(bottom_gap(&rt) < -1000.0, "reading far up: {}", bottom_gap(&rt)); + rt.set_live_visible(false); + rt.update(|_, tx| tx.scroll_to_bottom("scroll")); + rt.hidden_wake(); + assert!(bottom_gap(&rt) < -1000.0, "nothing moves while covered"); + rt.set_live_visible(true); + rt.settle_all(); + rt.frame(1.0 / 120.0); + assert!(bottom_gap(&rt).abs() < 0.05, "the uncovering frame shows the bottom: {}", bottom_gap(&rt)); + assert!(!rt.animating, "with no glide left to play"); +} + +#[test] +fn an_update_that_changes_nothing_still_scrolls() { + let mut rt = chat(Chat { rows: 40, instant: true, ..Default::default() }); + for _ in 0..5 { + rt.wheel(100.0, 100.0, 300.0); + rt.frame(1.0 / 120.0); + } + for _ in 0..60 { rt.frame(1.0 / 120.0); } + assert_eq!(rt.scroll_at_bottom("scroll"), Some(false)); + assert!(rt.update_if(|_, tx| { tx.scroll_to_bottom_instant("stack"); false }), "a scroll takes a frame"); + assert!(rt.stale()); + for _ in 0..3 { rt.frame(1.0 / 120.0); } + assert_eq!(rt.scroll_at_bottom("scroll"), Some(true)); +} + +#[test] +fn wheel_interrupts_a_glide() { + let mut rt = chat(Chat { rows: 40, ..Default::default() }); + rt.wheel(100.0, 100.0, 400.0); + rt.frame(1.0 / 120.0); + press(&mut rt, "jump"); + for _ in 0..4 { rt.frame(1.0 / 120.0); } + rt.wheel(100.0, 100.0, 50.0); + rt.frame(1.0 / 120.0); + let held = bottom_gap(&rt); + for _ in 0..60 { rt.frame(1.0 / 120.0); } + assert_eq!(bottom_gap(&rt), held, "the hand takes over from the glide"); + assert_eq!(rt.scroll_at_bottom("r3"), Some(false), "a row finds its viewport"); +} + +#[test] +fn instant_and_reduced_motion_land_in_the_same_frame() { + for state in [Chat { rows: 40, instant: true, ..Default::default() }, Chat { rows: 40, reduced: true, ..Default::default() }] { + let mut rt = chat(state); + rt.wheel(100.0, 100.0, 800.0); + rt.frame(1.0 / 120.0); + press(&mut rt, "jump"); + rt.frame(1.0 / 120.0); + assert!(bottom_gap(&rt).abs() < 0.05, "{}", bottom_gap(&rt)); + rt.frame(1.0 / 120.0); + assert_eq!(rt.state.reports, [true, false, true]); + } +} + +/// A hidden host's poll that scrolls changes no state, yet the last frame no longer shows +/// the window: a launcher's cached reveal must refresh. A poll that only schedules a wake +/// leaves it fresh. +#[test] +fn a_hidden_poll_that_scrolls_leaves_the_last_frame_out_of_date() { + let mut rt = chat(Chat { rows: 40, ..Default::default() }); + rt.wheel(100.0, 100.0, 800.0); + for _ in 0..30 { rt.frame(1.0 / 120.0); } + let up = bottom_gap(&rt); + assert!(up < -100.0, "{up}"); + rt.poll = Some(|s: &mut Chat, _, tx: &mut Tx| { + tx.wake_after(std::time::Duration::from_secs(1)); + if std::mem::take(&mut s.instant) { tx.scroll_to_bottom_instant("stack"); } + false + }); + assert!(!rt.poll_hidden(), "a wake alone draws nothing new"); + assert!(!rt.needs_commit()); + rt.state.instant = true; + assert!(rt.poll_hidden(), "a scroll asked for while hidden schedules a hidden refresh"); + assert!(rt.needs_commit(), "and the cached frame isn't fresh"); + assert_eq!(bottom_gap(&rt), up, "nothing scrolled while hidden"); + rt.frame(0.0); + assert!(bottom_gap(&rt).abs() < 0.05, "{}", bottom_gap(&rt)); + assert!(!rt.needs_commit()); +} + +#[test] +fn glides_to_the_exact_bottom_of_a_virtual_list() { + let mut rt = chat(Chat { rows: 600, virtualized: true, ..Default::default() }); + for _ in 0..40 { + rt.wheel(100.0, 100.0, 2000.0); + rt.frame(1.0 / 120.0); + } + assert!(rt.tree.nodes.iter().all(|n| n.key.as_deref() != Some("r599")), "the tail is unmounted while reading the top"); + press(&mut rt, "jump"); + for _ in 0..240 { rt.frame(1.0 / 120.0); } + assert!(bottom_gap(&rt).abs() < 0.05, "{}", bottom_gap(&rt)); + assert_eq!(rt.state.reports.last(), Some(&true)); + assert!(!rt.animating); +} + +fn max(rt: &Runtime<Chat>) -> f64 { + let i = rt.scroll_viewport("scroll").unwrap(); + rt.scroll.scrolls[&rt.tree.nodes[i].id].max +} + +/// Reads far up a virtual list whose unmounted tail rows are much taller than the estimate. +fn far_from_a_tall_tail(state: Chat) -> Runtime<Chat> { + let mut rt = chat(Chat { rows: 600, virtualized: true, tall_tail: true, ..state }); + for _ in 0..40 { + rt.wheel(100.0, 100.0, 2000.0); + rt.frame(1.0 / 120.0); + } + for _ in 0..30 { rt.frame(1.0 / 120.0); } + assert!(rt.tree.nodes.iter().all(|n| n.key.as_deref() != Some("r599")), "the tail is unmounted"); + rt +} + +#[test] +fn instant_lands_on_an_unmeasured_virtual_tail() { + for loose in [true, false] { + let mut rt = far_from_a_tall_tail(Chat { instant: true, loose, ..Default::default() }); + press(&mut rt, "jump"); + rt.frame(1.0 / 120.0); + assert!(bottom_gap(&rt).abs() < 0.05, "loose {loose}: {}", bottom_gap(&rt)); + for _ in 0..10 { rt.frame(1.0 / 120.0); } + assert!(bottom_gap(&rt).abs() < 0.05, "loose {loose}: stays at the bottom: {}", bottom_gap(&rt)); + } +} + +#[test] +fn a_glide_measures_the_virtual_tail_before_it_starts() { + for loose in [true, false] { + let mut rt = far_from_a_tall_tail(Chat { loose, ..Default::default() }); + press(&mut rt, "jump"); + rt.frame(1.0 / 120.0); + let trip = max(&rt); + assert!(bottom_gap(&rt) >= -2.0 * 300.0 - 0.5, "loose {loose}: starts two viewports from the true bottom: {}", bottom_gap(&rt)); + let mut frames = 0; + while rt.animating && frames < 240 { + rt.frame(1.0 / 120.0); + assert_eq!(max(&rt), trip, "loose {loose}: the bottom holds still mid-glide (frame {frames})"); + frames += 1; + } + assert!(frames > 10, "loose {loose}: animated ({frames} frames)"); + assert!(bottom_gap(&rt).abs() < 0.05, "loose {loose}: {}", bottom_gap(&rt)); + } +} + +fn scroll_state<'a>(rt: &'a Runtime<Chat>, key: &str) -> &'a ScrollState { + let i = rt.scroll_viewport(key).unwrap(); + &rt.scroll.scrolls[&rt.tree.nodes[i].id] +} + +fn page_height(rt: &Runtime<Chat>, key: &str) -> f64 { + f64::from(rt.tree.nodes[rt.scroll_viewport(key).unwrap()].local.h * 0.9) +} + +fn key(rt: &mut Runtime<Chat>, key: crate::Key) { + rt.key(KeyEvent { key, mods: Default::default() }); + rt.frame(1.0 / 120.0); +} + +fn with_composer(text: &str) -> Runtime<Chat> { + let mut edit = crate::TextEdit::new(text); + edit.focused = true; + chat(Chat { rows: 40, composer: Some(edit), ..Default::default() }) +} + +#[test] +fn page_keys_from_a_short_composer_page_the_message_list_beside_it() { + let mut rt = with_composer("hello"); + assert_eq!(scroll_state(&rt, "composer-scroll").max, 0.0, "the draft fits its scroll area"); + let (bottom, page) = (max(&rt), page_height(&rt, "scroll")); + assert!(bottom > 3.0 * page); + assert_eq!(scroll_state(&rt, "scroll").offset, bottom); + key(&mut rt, crate::Key::PageUp); + assert_eq!(scroll_state(&rt, "scroll").offset, bottom - page, "the list pages, not the composer"); + assert!(!scroll_state(&rt, "scroll").pinned()); + // The pointer over the composer doesn't claim the keys either. + let (x, y) = rt.find("composer").unwrap(); + rt.pointer_move(x, y); + key(&mut rt, crate::Key::PageUp); + assert_eq!(scroll_state(&rt, "scroll").offset, bottom - 2.0 * page); + key(&mut rt, crate::Key::PageDown); + key(&mut rt, crate::Key::PageDown); + assert_eq!(scroll_state(&rt, "scroll").offset, bottom); + assert!(scroll_state(&rt, "scroll").pinned(), "back on the end, the list follows it again"); + let composer = rt.state.composer.as_ref().unwrap(); + assert!(composer.focused); + assert_eq!(composer.text, "hello"); +} + +#[test] +fn an_overflowing_composer_keeps_the_page_keys_even_at_its_edge() { + let mut rt = with_composer(&vec!["line"; 12].join("\n")); + let list = max(&rt); + let composer = scroll_state(&rt, "composer-scroll").max; + assert!(composer > 0.0, "the draft overflows: {composer}"); + for _ in 0..10 { key(&mut rt, crate::Key::PageUp); } + assert_eq!(scroll_state(&rt, "composer-scroll").offset, 0.0, "the composer paged to its top"); + assert_eq!(scroll_state(&rt, "scroll").offset, list, "and the list never moved, as an NSTextView keeps them"); +} + +#[test] +fn tx_scroll_page_pages_a_viewport_and_repins_its_end() { + let mut rt = chat(Chat { rows: 40, ..Default::default() }); + let (bottom, page) = (max(&rt), page_height(&rt, "scroll")); + assert!(rt.update_if(|_, tx| { tx.scroll_page("scroll", -2); false }), "a page takes a frame"); + rt.frame(1.0 / 120.0); + assert_eq!(scroll_state(&rt, "scroll").offset, bottom - 2.0 * page); + assert_eq!(rt.scroll_at_bottom("scroll"), Some(false)); + let row = rt.elements().into_iter().find(|e| e.rect[1] > 0.0 && e.rect[1] < 200.0 && e.key.as_deref().is_some_and(|k| k.starts_with('r'))).unwrap().key.unwrap(); + rt.update_if(move |_, tx| { tx.scroll_page(row, 1); false }); + rt.frame(1.0 / 120.0); + assert_eq!(scroll_state(&rt, "scroll").offset, bottom - page, "a row's key pages the viewport it's in"); + rt.update_if(|_, tx| { tx.scroll_page("scroll", 5); false }); + rt.frame(1.0 / 120.0); + assert_eq!(scroll_state(&rt, "scroll").offset, bottom, "clamped at the end"); + assert!(scroll_state(&rt, "scroll").pinned()); + rt.state.rows += 5; + rt.invalidate(); + for _ in 0..120 { rt.frame(1.0 / 120.0); } + assert!(bottom_gap(&rt).abs() < 0.05, "a stick_bottom list follows new rows again: {}", bottom_gap(&rt)); + assert!(!rt.animating); +} + +#[test] +fn tx_scroll_page_finds_the_list_of_a_key_inside_a_virtual_row() { + let mut rt = chat(Chat { rows: 600, virtualized: true, ..Default::default() }); + let (bottom, page) = (max(&rt), page_height(&rt, "scroll")); + assert!(rt.tree.nodes.iter().all(|n| n.key.as_deref() != Some("r0")), "the head is unmounted"); + rt.update_if(|_, tx| { tx.scroll_page("r599", -3); false }); + rt.frame(1.0 / 120.0); + // Rows mounting on the way measure against their estimate, which moves the extent a little. + let st = scroll_state(&rt, "scroll"); + let pages = (st.max - st.offset) / page; + assert!((2.5..3.5).contains(&pages), "three pages above the end: {pages} (bottom was {bottom})"); + assert!(!scroll_state(&rt, "scroll").pinned()); + let shown = rt.elements().into_iter().filter(|e| e.key.as_deref().is_some_and(|k| k.starts_with('r')) && e.rect[1] + e.rect[3] > 0.0 && e.rect[1] < 300.0).count(); + assert!(shown >= 5, "the window mounted the rows it pages to ({shown})"); +} + +/// The rects of this frame's keyed elements. +fn rects(rt: &Runtime<Chat>) -> std::collections::HashMap<String, [f32; 4]> { + rt.elements().into_iter().filter_map(|e| Some((e.key?, e.rect))).collect() +} + +/// How often `ys` turns around (moves under 0.01 pt don't count). +fn reversals(ys: &[f32]) -> usize { + let (mut dir, mut turns) = (0.0, 0); + for w in ys.windows(2) { + let d = w[1] - w[0]; + if d.abs() < 0.01 { continue; } + if dir != 0.0 && d.signum() != dir { turns += 1; } + dir = d.signum(); + } + turns +} + +/// The gap between the last row's bottom and the list viewport's. +fn slack_gap(rt: &Runtime<Chat>) -> f32 { + let r = rects(rt); + let (view, last) = (r["scroll"], r[&format!("r{}", rt.state.rows - 1)]); + view[1] + view[3] - (last[1] + last[3]) +} + +fn growing(rt: &Runtime<Chat>) -> bool { + rt.motion.grows.values().any(|g| g.target > g.h + 1.0 / 128.0) +} + +fn sending(lines: usize) -> Runtime<Chat> { + let mut edit = crate::TextEdit::new(&vec!["line"; lines].join("\n")); + edit.focused = true; + chat(Chat { rows: 40, composer: Some(edit), sends: true, ..Default::default() }) +} + +fn enter(rt: &mut Runtime<Chat>) { + rt.key(KeyEvent { key: crate::Key::Enter, mods: Default::default() }); +} + +struct Sent { rt: Runtime<Chat>, ys: Vec<Vec<f32>>, shrank: f32, grew_until: usize, frames: usize } + +/// Sends a draft of `lines` lines from a composer under a pinned growth stack, and records +/// the rows on screen at 120 fps until everything rests. +fn send(lines: usize) -> Sent { + let mut rt = sending(lines); + let before = rects(&rt); + let view = before["scroll"]; + let shown: Vec<String> = (0..40).map(|i| format!("r{i}")) + .filter(|k| before[k][1] + before[k][3] > view[1] && before[k][1] < view[1] + view[3]).collect(); + enter(&mut rt); + let mut ys: Vec<Vec<f32>> = shown.iter().map(|k| vec![before[k][1]]).collect(); + let (mut grew_until, mut frames) = (0, 0); + while frames < 600 && (frames < 2 || rt.animating) { + rt.frame(1.0 / 120.0); + frames += 1; + if growing(&rt) { grew_until = frames; } + let r = rects(&rt); + for (k, y) in shown.iter().zip(&mut ys) { y.push(r[k][1]); } + assert_eq!(rt.scroll_at_bottom("scroll"), Some(true), "the list reports its bottom through the slack"); + } + assert_eq!(rt.state.rows, 41, "the draft was sent"); + let shrank = before["composer"][3] - rects(&rt)["composer"][3]; + Sent { rt, ys, shrank, grew_until, frames } +} + +/// Sending shrinks the composer under a pinned list while the new row grows in on its +/// slower-starting spring. The freed room waits under the last row, so rows on screen only +/// rise; nothing dips and comes back. +#[test] +fn a_send_only_moves_the_rows_up() { + let Sent { rt, ys, shrank, .. } = send(3); + assert!(shrank > 30.0, "the composer gave back its room: {shrank}"); + for y in &ys { + assert!(y.windows(2).all(|w| w[1] <= w[0] + 0.01), "a row moved down: {y:?}"); + assert!(y[0] - y[y.len() - 1] > 5.0, "the row rose by the new row less the freed room: {y:?}"); + } + assert!(slack_gap(&rt).abs() < 0.05, "the last row ends on the bottom: {}", slack_gap(&rt)); + assert_eq!(rt.state.reports, [true]); +} + +/// Room freed beyond what the new row fills stays under it until the growth has stopped +/// for a moment, then closes on the growth spring. +#[test] +fn room_the_new_row_does_not_fill_closes_after_its_growth() { + let Sent { rt, ys, shrank, grew_until, frames } = send(7); + assert!(shrank > 80.0, "{shrank}"); + let mut first_down: Option<usize> = None; + for y in &ys { + assert!(reversals(y) <= 1, "{y:?}"); + if let Some(k) = y.windows(2).position(|w| w[1] > w[0] + 0.01) { + first_down = Some(first_down.map_or(k + 1, |f| f.min(k + 1))); + } + } + let first_down = first_down.expect("the slack closed by moving the rows down"); + assert!(first_down >= grew_until + 14, "the slack waits 120 ms after growth: down at {first_down}, grew until {grew_until}"); + assert!(frames < 240, "and closes in time ({frames} frames)"); + assert!(slack_gap(&rt).abs() < 0.05, "{}", slack_gap(&rt)); +} + +/// The gap between the last row and the list's bottom each frame as the dock under it +/// changes to `h` on a tween, following its edge or not. +fn dock_gaps(rt: &mut Runtime<Chat>, h: f32, follow: bool) -> Vec<f32> { + rt.update(|s, tx| { + s.dock = Some(h); + tx.motion_curve(rune_motion::Curve::tween(0.3, rune_motion::Easing::EASE_OUT)); + if follow { tx.follow_edge(); } + }); + let mut gaps = vec![slack_gap(rt)]; + for _ in 0..90 { + rt.frame(1.0 / 120.0); + gaps.push(slack_gap(rt)); + } + gaps +} + +/// With `Tx::follow_edge`, a pinned list rides a dock's top edge both ways on the dock's +/// curve, frame by frame. Without it the room a shrinking dock frees waits under the last +/// row as slack, as a send's does, and closes late. +#[test] +fn follow_edge_carries_pinned_rows_with_a_dock() { + let mut rt = chat(Chat { rows: 40, dock: Some(160.0), ..Default::default() }); + for (h, way) in [(40.0, "shrinking"), (160.0, "growing"), (40.0, "shrinking again")] { + let gaps = dock_gaps(&mut rt, h, true); + let worst = gaps.iter().map(|g| g.abs()).fold(0.0, f32::max); + assert!(worst < 0.05, "{way}: the rows leave the edge by {worst}: {gaps:?}"); + } + assert!(rects(&rt)["dock"][3] < 41.0, "the dock moved"); + rt.update(|s, tx| { s.dock = Some(160.0); tx.settle(); }); + rt.frame(1.0 / 120.0); + let held = dock_gaps(&mut rt, 40.0, false).into_iter().fold(0.0, f32::max); + assert!(held > 30.0, "without it the freed room waits as slack: {held}"); +} + +/// A hand on the list during the slack moves the rows from where they are drawn. +#[test] +fn scrolling_up_through_slack_does_not_jump() { + let mut rt = sending(7); + enter(&mut rt); + while growing(&rt) || rt.state.rows < 41 { rt.frame(1.0 / 120.0); } + rt.frame(1.0 / 120.0); + let gap = slack_gap(&rt); + assert!(gap > 10.0, "slack is held under the last row: {gap}"); + let y = rects(&rt)["r30"][1]; + rt.wheel(100.0, 100.0, 30.0); + rt.frame(1.0 / 120.0); + let moved = rects(&rt)["r30"][1] - y; + assert!((moved - 30.0).abs() < 1.0, "the wheel moves the rows 30 pt from where they were: {moved}"); + assert_eq!(rt.scroll_at_bottom("scroll"), Some(false)); + for _ in 0..240 { rt.frame(1.0 / 120.0); } + assert!(!rt.animating); + assert!((slack_gap(&rt) + 30.0).abs() < 0.05, "the slack closed under the reader: {}", slack_gap(&rt)); +} + +/// A window growing taller opens no slack: the rows stay on the bottom. +#[test] +fn a_taller_window_keeps_the_rows_on_the_bottom() { + let mut rt = sending(7); + enter(&mut rt); + while growing(&rt) || rt.state.rows < 41 { rt.frame(1.0 / 120.0); } + assert!(slack_gap(&rt) > 10.0); + rt.set_viewport((200.0, 400.0), 2.0); + rt.frame(1.0 / 120.0); + assert!(slack_gap(&rt).abs() < 0.05, "a resize lands the slack: {}", slack_gap(&rt)); + for k in 1..8 { + rt.set_viewport((200.0, 400.0 + 10.0 * k as f32), 2.0); + rt.frame(1.0 / 120.0); + assert!(slack_gap(&rt).abs() < 0.05, "the rows follow the bottom: {}", slack_gap(&rt)); + } +} + +/// An instant change (a zoom, say) lands the slack with it, not on a glide a moment later. +#[test] +fn an_instant_change_lands_the_slack_at_once() { + let mut rt = sending(7); + let y = rects(&rt)["r35"][1]; + rt.update(|s, tx| { tx.instant(); s.composer.as_mut().unwrap().clear() }); + rt.frame(1.0 / 120.0); + let landed = rects(&rt)["r35"][1]; + assert!(landed - y > 80.0, "the rows came down with the change: {y} -> {landed}"); + assert!(slack_gap(&rt).abs() < 0.05, "{}", slack_gap(&rt)); + for _ in 0..60 { rt.frame(1.0 / 120.0); } + assert_eq!(rects(&rt)["r35"][1], landed, "and stayed there"); +} + +/// A composer shrinking with nothing growing in lets the rows down after it, once. +#[test] +fn a_composer_shrinking_alone_lets_the_rows_down_once() { + let mut rt = sending(7); + let mut ys = vec![rects(&rt)["r35"][1]]; + rt.update(|s, _| s.composer.as_mut().unwrap().clear()); + for _ in 0..240 { + rt.frame(1.0 / 120.0); + ys.push(rects(&rt)["r35"][1]); + } + assert!(ys.windows(2).all(|w| w[1] >= w[0] - 0.01), "{ys:?}"); + assert!(ys[ys.len() - 1] - ys[0] > 80.0, "{ys:?}"); + assert!(slack_gap(&rt).abs() < 0.05, "{}", slack_gap(&rt)); + assert!(!rt.animating); +} + +/// A row removed at the bottom closes and the rows above come down once, never rising. +#[test] +fn a_row_removed_at_the_bottom_lets_the_rows_down_once() { + let mut rt = chat(Chat { rows: 40, ..Default::default() }); + rt.state.rows = 39; + rt.invalidate(); + let mut ys = Vec::new(); + for _ in 0..240 { + rt.frame(1.0 / 120.0); + ys.push(rects(&rt)["r35"][1]); + } + assert!(ys.windows(2).all(|w| w[1] >= w[0] - 0.01), "{ys:?}"); + assert!(ys[ys.len() - 1] - ys[0] > 30.0, "{ys:?}"); + assert!(bottom_gap(&rt).abs() < 0.05, "{}", bottom_gap(&rt)); + assert!(!rt.animating); +} + +/// An app's own `REFLOW` override on send slows the new row with the composer, so rows +/// neither overshoot upward on a short draft nor dip before rising on a tall one. +#[test] +fn a_send_on_reflow_motion_never_dips() { + let mut rt = sending(3); + let before = rects(&rt)["r38"][1]; + rt.update(|s, tx| { + tx.motion(crate::tok::motion::REFLOW); + s.composer.as_mut().unwrap().clear(); + s.rows += 1; + }); + let mut ys = vec![before]; + while ys.len() < 400 && (ys.len() < 3 || rt.animating) { + rt.frame(1.0 / 120.0); + ys.push(rects(&rt)["r38"][1]); + } + assert!(ys.windows(2).all(|w| w[1] <= w[0] + 0.01), "3-line reflow send moved down: {ys:?}"); + assert!(slack_gap(&rt).abs() < 0.05, "{}", slack_gap(&rt)); + + let mut rt = sending(7); + let before = rects(&rt)["r38"][1]; + rt.update(|s, tx| { + tx.motion(crate::tok::motion::REFLOW); + s.composer.as_mut().unwrap().clear(); + s.rows += 1; + }); + let mut ys = vec![before]; + while ys.len() < 400 && (ys.len() < 3 || rt.animating) { + rt.frame(1.0 / 120.0); + ys.push(rects(&rt)["r38"][1]); + } + assert!(reversals(&ys) <= 1, "7-line reflow send reversed more than once: {ys:?}"); + assert!(slack_gap(&rt).abs() < 0.05, "{}", slack_gap(&rt)); +} + +/// Split frames (`catch_up` before the commit, `dt` after) pair the full frame's growth with +/// the full frame's edge step, keep `ElementInfo::moving` on while slack closes, and deliver +/// the resting `on_drawn_layout` rect once slack reaches zero. +#[test] +fn split_frames_and_drawn_layout_follow_slack_to_rest() { + let mut edit = crate::TextEdit::new(&vec!["line"; 7].join("\n")); + edit.focused = true; + let mut rt = chat(Chat { rows: 6, composer: Some(edit), sends: true, track_drawn: true, ..Default::default() }); + rt.state.drawn.clear(); + let y0 = rects(&rt)["r0"][1]; + enter(&mut rt); + let mut ys = vec![y0]; + let mut frames = 0; + while frames < 360 && (frames < 2 || rt.animating) { + rt.frame_split(0.5 / 120.0, 0.5 / 120.0); + frames += 1; + let r0 = rt.elements().into_iter().find(|e| e.key.as_deref() == Some("r0")).unwrap(); + if rt.animating && (r0.rect[1] - *ys.last().unwrap()).abs() > 0.01 { + assert!(r0.moving, "r0 moved at frame {frames} with moving=false"); + } + ys.push(r0.rect[1]); + } + assert!(reversals(&ys) <= 1, "{ys:?}"); + assert!(slack_gap(&rt).abs() < 0.05, "{}", slack_gap(&rt)); + assert!((*rt.state.drawn.last().unwrap() - *ys.last().unwrap()).abs() < 0.05, "drawn_layout settled on final y"); +} + +/// Top-aligned rows that already fit, or cross from overflowing into fitting as the composer +/// shrinks, never get pushed above the top of the viewport (`r0.y > 0` from negative offset). +#[test] +fn top_aligned_rows_do_not_rise_above_the_top_when_the_composer_shrinks() { + for rows in [2, 5] { + let mut edit = crate::TextEdit::new(&vec!["line"; 7].join("\n")); + edit.focused = true; + let mut rt = chat(Chat { rows, composer: Some(edit), sends: true, ..Default::default() }); + let mut ys = vec![rects(&rt)["r0"][1]]; + rt.update(|s, _| s.composer.as_mut().unwrap().clear()); + for _ in 0..240 { + rt.frame(1.0 / 120.0); + let y = rects(&rt)["r0"][1]; + assert!(y <= 0.05, "rows={rows}: r0 had a gap above it at the top of the viewport: {y}"); + ys.push(y); + } + assert!(ys.windows(2).all(|w| w[1] >= w[0] - 0.01), "rows={rows}: r0 moved up: {ys:?}"); + assert!((*ys.last().unwrap()).abs() < 0.05, "rows={rows}: r0 rests at the top: {:?}", ys.last()); + } +} + +/// Rows that fit the list's layout but grow past its bottom while the composer shrinks +/// under it start following from the first point past it, with no kick. +#[test] +fn rows_crossing_into_overflow_as_the_composer_shrinks_start_smoothly() { + for lines in [2, 3] { + let mut edit = crate::TextEdit::new(&vec!["line"; lines].join("\n")); + edit.focused = true; + let mut rt = chat(Chat { rows: 5, composer: Some(edit), sends: true, ..Default::default() }); + let mut ys = vec![rects(&rt)["r0"][1]]; + enter(&mut rt); + for _ in 0..240 { + rt.frame(1.0 / 120.0); + ys.push(rects(&rt)["r0"][1]); + } + assert!(*ys.last().unwrap() < -5.0, "lines={lines}: the rows overflowed: {ys:?}"); + let steps: Vec<f32> = ys.windows(2).map(|w| w[1] - w[0]).collect(); + for w in steps.windows(2) { + assert!((w[1] - w[0]).abs() < 1.5, "lines={lines}: r0's speed kicks {} pt a frame: {ys:?}", w[1] - w[0]); + } + } +} diff --git a/app/vendor/rune/crates/rune/src/runtime/scroll/drawn.rs b/app/vendor/rune/crates/rune/src/runtime/scroll/drawn.rs new file mode 100644 index 0000000..0ee64d3 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/scroll/drawn.rs @@ -0,0 +1,123 @@ +//! Where a scroll viewport drew its content last frame, and the hold that keeps a pinned end's +//! pixel through a sub-pixel reversal. +//! +//! As a pinned growth stack's rows and slack settle, its offset can creep back and forth by a +//! fraction of a rounding quantum, which the drawn offset would otherwise follow between two +//! values and re-rasterize the rows under it. A step straight back by less than one quantum +//! holds the pixel it drew; a step one way rounds as ever. +use super::*; + +/// Where a scroll viewport drew its content's vertical offset last frame. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub(crate) enum PixelHold { + /// Nothing drawn yet. + #[default] + Unseen, + /// Drawn at `drawn`, stepping `dir` (-1, 0 or 1), with `pinned` the mode it stepped in. + Stepping { drawn: f32, dir: i8, pinned: bool }, + /// Held at `drawn` through a reversal at a pinned end, last stepping `dir`. + Holding { drawn: f32, dir: i8 }, +} + +impl PixelHold { + /// The vertical offset the last frame drew at, in points. + pub(crate) fn y(self) -> f32 { + match self { + PixelHold::Unseen => 0.0, + PixelHold::Stepping { drawn, .. } | PixelHold::Holding { drawn, .. } => drawn, + } + } + + /// The offset to draw this frame's `exact` content offset at, and the hold after it. + /// `offset` is the viewport's layout offset, which a held step never draws away from. + pub(in crate::runtime) fn draw(self, exact: f32, offset: f32, pinned: bool, s: f32) -> (f32, PixelHold) { + // `grid` rounds to 1/64 of a device pixel, so a hold spanning under one quantum only + // absorbs rounding noise. Real travel always lands at the layout offset. + let rounded = grid(exact, s); + let (drawn, dir, stepped_pinned) = match self { + PixelHold::Unseen => (0.0, 0, false), + PixelHold::Stepping { drawn, dir, pinned } => (drawn, dir, pinned), + PixelHold::Holding { drawn, dir } => (drawn, dir, true), + }; + let step = (rounded - drawn).signum() as i8; + // Only a step drawn at a pinned end may be reversed into a hold. A direction a gesture + // or glide left behind is not the settle's, and holding it would swallow the first real + // step after the end pins. + let back = pinned + && stepped_pinned + && rounded != grid(offset, s) + && step == -dir + && ((exact - drawn) * s).abs() < 1.0 / 64.0; + if back { + return (drawn, PixelHold::Holding { drawn, dir }); + } + let dir = if rounded == drawn { dir } else { step }; + // A frame that drew no step keeps the mode that last stepped: pinning while the end + // holds still doesn't make the gesture's direction the settle's. + let stepped_pinned = if rounded == drawn { stepped_pinned } else { pinned }; + (rounded, PixelHold::Stepping { drawn: rounded, dir, pinned: stepped_pinned }) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Drawn at 100 pt at 2× (`grid` is 1/128 pt there), last stepping `dir` at a pinned end. + fn drawn(dir: i8) -> PixelHold { + PixelHold::Stepping { drawn: 100.0, dir, pinned: true } + } + + #[test] + fn a_pinned_end_holds_its_pixel_through_a_reversal() { + // The content creeps back by 0.012 device pixels, across a rounding boundary. + let (at, next) = drawn(-1).draw(100.006, 100.0, true, 2.0); + assert_eq!(at, 100.0, "held where it drew"); + assert_eq!(next, PixelHold::Holding { drawn: 100.0, dir: -1 }); + } + + #[test] + fn a_direction_from_another_mode_does_not_hold() { + // A gesture or glide drew the last step, then the end pinned. Its direction isn't the + // settle's: the first step back is real motion and draws. + let carried = PixelHold::Stepping { drawn: 100.0, dir: -1, pinned: false }; + let (at, next) = carried.draw(100.006, 100.0, true, 2.0); + assert_eq!(at, grid(100.006, 2.0), "the step drew, not held"); + assert_eq!(next, PixelHold::Stepping { drawn: grid(100.006, 2.0), dir: 1, pinned: true }); + } + + #[test] + fn a_stationary_pinned_frame_keeps_the_mode_that_stepped() { + // The end pins and holds still for a frame before the content moves. That frame drew no + // step, so it can't relabel the gesture's direction as the settle's. + let carried = PixelHold::Stepping { drawn: 100.0, dir: -1, pinned: false }; + let (still, next) = carried.draw(100.0, 100.0, true, 2.0); + assert_eq!(still, 100.0); + assert_eq!(next, PixelHold::Stepping { drawn: 100.0, dir: -1, pinned: false }); + let (at, next) = next.draw(100.006, 100.0, true, 2.0); + assert_eq!(at, grid(100.006, 2.0), "the first real step drew, not held"); + assert_eq!(next, PixelHold::Stepping { drawn: grid(100.006, 2.0), dir: 1, pinned: true }); + } + + #[test] + fn motion_one_way_rounds_as_before() { + let (at, next) = drawn(1).draw(100.013, 100.0, true, 2.0); + assert_eq!(at, grid(100.013, 2.0)); + assert_eq!(next, PixelHold::Stepping { drawn: grid(100.013, 2.0), dir: 1, pinned: true }); + } + + #[test] + fn the_layout_offset_always_lands() { + // No slack or stuck offset: the exact offset is the layout offset, so it draws there. + let (at, _) = drawn(-1).draw(100.006, 100.006, true, 2.0); + assert_eq!(at, grid(100.006, 2.0)); + } + + #[test] + fn a_held_pixel_let_go_lands_where_the_content_is() { + let held = PixelHold::Holding { drawn: 100.0, dir: 1 }; + let (at, next) = held.draw(100.02, 100.0, true, 2.0); + assert_eq!(at, grid(100.02, 2.0), "past one quantum, it steps"); + assert_eq!(next, PixelHold::Stepping { drawn: grid(100.02, 2.0), dir: 1, pinned: true }); + } +} diff --git a/app/vendor/rune/crates/rune/src/runtime/scroll/edge.rs b/app/vendor/rune/crates/rune/src/runtime/scroll/edge.rs new file mode 100644 index 0000000..6b63363 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/scroll/edge.rs @@ -0,0 +1,204 @@ +//! Content-aware scroll edges: `El::scroll_edge_fade` fades an edge only while content is hidden +//! under it, and `El::scroll_margin` stops `Tx::scroll_into_view` clear of that fade. +use super::*; + +/// Hidden extent (points) at which an edge's fade reaches full strength. +const FADE_IN: f64 = 15.0; + +/// A fade at `strength` (0..=1) as a packed ramp `(width, offset)`: the shader's smoothstep ramp +/// starts `offset` of the way in, so the edge shows `1 - strength` and reaches full alpha +/// `width` in. Zero strength is a hard edge. +fn partial(width: f32, strength: f32) -> (f32, f32) { + if strength <= 0.0 || width <= 0.0 { return (0.0, 0.0); } + if strength >= 1.0 { return (width, 0.0); } + // Inverse smoothstep: where the ramp already stands at alpha `1 - strength`. + let offset = 0.5 - ((2.0 * strength - 1.0).clamp(-1.0, 1.0).asin() / 3.0).sin(); + let offset = offset.clamp(0.0, 0.995); + (width / (1.0 - offset), offset) +} + +/// The scroll offset that shows `[top, top + height)` with `margin` to spare, moving as little +/// as possible from `offset` (unclamped). A row taller than the viewport that already fills it +/// stays put, so placing it again doesn't flip it from its end to its start. +pub(in crate::runtime) fn reveal(offset: f64, top: f64, height: f64, viewport: f64, margin: f64) -> f64 { + let margin = margin.min(((viewport - height) / 2.0).max(0.0)); + let (start, end) = (top - margin, top + height + margin); + if start <= offset && end >= offset + viewport { offset } + else if start < offset { start } + else if end > offset + viewport { end - viewport } + else { offset } +} + +impl requests::ScrollTables { + /// Node `n`'s own soft-clip widths `f` (points) as a device-pixel fade and the rect its ramps + /// start from, given its optional stuck-to-bottom offset. + pub(super) fn edge_fade(&self, n: &Node, f: [f32; 4], r: [f32; 4], k: f32, stuck: Option<f64>) -> ([f32; 4], [f32; 4]) { + let mut own = f.map(|v| (v * k).clamp(-65504.0, 65504.0)); + let width = n.scroll_edges.fade; + let Some(st) = self.scrolls.get(&n.id).filter(|_| width > 0.0 && n.scroll.is_some()) else { return (own, r) }; + let offset = stuck.unwrap_or(st.offset) + f64::from(st.slack.height()); + let below = if stuck.is_some() { 0.0 } else { st.max - offset }; + let mut origin = r; + let (y, x) = (n.scroll_axes.y(), n.scroll_axes.x()); + let style = n.scroll_edges.fade_style; + // What hides past the left and right edges: a right-to-left viewport starts at its right. + let (left, right) = (st.x.offset, st.x.max - st.x.offset); + let (left, right) = match st.x.flow { crate::el::Flow::Ltr => (left, right), crate::el::Flow::Rtl => (right, left) }; + let edges = [(y, 1, offset, -1.0), (y, 3, below, 1.0), (x, 0, left, -1.0), (x, 2, right, 1.0)]; + for (_, edge, hidden, out) in edges.into_iter().filter(|e| e.0 && !(style.end_only && e.3 < 0.0)) { + let (style, width) = style.edge(width, out > 0.0); + let (w, o) = edge_ramp(style, width * k, hidden, k); + own[edge] = w; + origin[edge] = r[edge] + out * o * paint::soft_edges::fade_extent(w); + } + (own, origin) + } +} + +impl RuntimeCore { + /// Node `i`'s own soft-clip widths `f` (points) as a device-pixel fade and the rect its ramps + /// start from. With `scroll_edge_fade`, top and bottom follow the content hidden under them: + /// the ramp starts outside `r` so the edge itself only partly fades. `bottom` is the + /// presented bottom edge (see `stuck_offset`). + pub(in crate::runtime) fn scroll_edge_fade(&self, i: usize, f: [f32; 4], r: [f32; 4], k: f32, bottom: f32) -> ([f32; 4], [f32; 4]) { + let n = &self.tree.nodes[i]; + let stuck = if n.scroll_edges.fade > 0.0 && n.scroll.is_some() { self.stuck_offset(i, bottom) } else { None }; + self.scroll.edge_fade(n, f, r, k, stuck) + } + + /// Under [`crate::ScrollFade::below_sticky`], the fade under the header heading `section` + /// (its first child, `El::sticky_top`) while it's stuck at the top of its viewport, handed to + /// the section's rows through its inherited paint state, from the section's own pass: the + /// header paints above its siblings, so after them. The strength follows how far the section + /// has scrolled past where the header sticks; from where the next section's top comes within + /// a header of the viewport's top (it's about to push this header away) the rows are clear, + /// as Desktop's `search-list.tsx` takes the next section as current there. The rows clip at + /// the header's bottom, under its fill, so the ramp may start above it; the header keeps + /// the clip it had (`sticky_bands`). + pub(in crate::runtime) fn fade_below_header(&mut self, section: usize, s: f32) { + let h = section + 1; + if self.tree.nodes.get(h).is_none_or(|c| c.parent != Some(section)) { return; } + let Some((crate::el::StickyEdge::Top, inset, false)) = self.sticky_of(h) else { return }; + let (frame, Some(viewport)) = self.sticky_frame_of(h, crate::el::StickyEdge::Top) else { return }; + let edges = self.tree.nodes[viewport].scroll_edges; + if !edges.fade_style.below_sticky || edges.fade <= 0.0 { return; } + let n = &self.tree.nodes[h]; + let Some(p) = self.scene.presented(n.id) else { return }; + let own = self.scene.get(n.id, prop::OFFSET).unwrap_or(rune_motion::Vec2::ZERO); + let inh = self.paint.inh_scratch[section]; + let top = p.rect.y - own.y + inh.dy + self.paint.row_dy[h]; + let left = p.rect.x - own.x + inh.dx; + let height = if self.paint.row_h[h] >= 0.0 { self.paint.row_h[h] } else { p.rect.h }; + let shift = sticky::shift(crate::el::StickyEdge::Top, inset, [top, top + height, left, left + p.rect.w], frame); + let (band, hidden) = (frame[0] + inset, frame[0] + inset - top); + let next_top = frame[3] + self.tree.nodes[section].inset[3]; + if shift <= 0.0 || next_top - band < height { return; } + let k = inh.scale * s; + let (w, o) = edge_ramp(edges.fade_style, edges.fade * k, f64::from(hidden), k); + if w == 0.0 { return; } + let raw_top = inh.anchor_to[1] + (top + shift - inh.anchor[1]) * inh.scale; + let raw_bottom = inh.anchor_to[1] + (top + shift + height - inh.anchor[1]) * inh.scale; + let bottom = if !inh.snap.off && !n.vis_flags.no_pixel_snap() && inh.turn == 0 && p.transform.rotate == 0.0 && (inh.scale - 1.0).abs() <= 1e-5 { + // Snap to the same device-pixel edge the stuck header box itself draws at (`pixel_snap::snap`), + // applying the header's sticky shift so `rigid[1]` cancels the viewport scroll offset. + let mut snap = inh.snap; + snap.scroll(1, shift); + let exact = [0.0, grid(raw_top, s) * s, 0.0, grid(raw_bottom, s) * s]; + paint::pixel_snap::snap(exact, [0.0; 4], snap.rigid.map(|v| v * s), None, |_, c| c).0[3] + } else { + raw_bottom * s + }; + let inh = &mut self.paint.inh_scratch[section]; + self.scroll.sticky_bands.push((section, inh.paint_clip[1])); + inh.paint_clip[1] = inh.paint_clip[1].max(bottom); + inh.paint_fade[1] = w; + inh.paint_fade_origin[1] = bottom - o * paint::soft_edges::fade_extent(w); + } +} + +/// The packed ramp `(width, offset)` (see [`partial`]) for an edge with `hidden` points under +/// it, `width` device pixels wide at `k` device pixels a point; a negative width ramps linearly, +/// and a width above [`crate::render::instance::STOP_FADE_BIAS`] uses explicit piecewise-linear stops. +fn edge_ramp(style: crate::el::FadeStyle, width: f32, hidden: f64, k: f32) -> (f32, f32) { + let width = width.clamp(0.0, 65504.0); + if style.feather { + let w = width.min(hidden.max(0.0) as f32 * k).min(65504.0); + if w <= 0.0 { return (0.0, 0.0); } + if style.stops.is_some() { return (crate::render::STOP_FADE_BIAS + w, 0.0); } + return (if style.linear { -w } else { w }, 0.0); + } + let full = if style.full_at > 0.0 { f64::from(style.full_at) } else { FADE_IN }; + let strength = (hidden / full).clamp(0.0, 1.0) as f32; + if let Some(stops) = style.stops { + let (w, o) = partial_stops(width, strength, stops); + return (if w > 0.0 { crate::render::STOP_FADE_BIAS + w.min(65504.0) } else { 0.0 }, o); + } + if !style.linear { + let (w, o) = partial(width, strength); + return (w.min(65504.0), o); + } + let (w, o) = partial_linear(width, strength); + (-w.min(65504.0), o) +} + +/// [`partial`] on a piecewise-linear ramp through `stops`: finds the exact normalized `offset` +/// whose curve value equals `1 - strength` so the edge shows `1 - strength` and reaches full +/// alpha `width` pixels in. +fn partial_stops(width: f32, strength: f32, stops: [(f32, f32); 3]) -> (f32, f32) { + if strength <= 0.0 || width <= 0.0 { return (0.0, 0.0); } + if strength >= 1.0 { return (width, 0.0); } + let target = 1.0 - strength; + let pts = [stops[0], stops[1], stops[2], (1.0, 1.0)]; + let (mut px, mut py) = (0.0f32, 0.0f32); + let mut offset = target; + for (nx, ny) in pts { + if target <= ny { + let dy = ny - py; + offset = if dy > 1e-6 { px + (nx - px) * ((target - py) / dy) } else { nx }; + break; + } + px = nx; + py = ny; + } + let offset = offset.clamp(0.0, 0.995); + (width / (1.0 - offset), offset) +} + +/// [`partial`] on a linear ramp: it starts `1 - strength` of the way in, so the edge shows +/// `1 - strength` and the ramp reaches full alpha `width` in. +fn partial_linear(width: f32, strength: f32) -> (f32, f32) { + if strength <= 0.0 || width <= 0.0 { return (0.0, 0.0); } + if strength >= 1.0 { return (width, 0.0); } + let offset = (1.0 - strength).min(0.995); + (width / (1.0 - offset), offset) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn partial_ramp_starts_at_one_minus_strength_and_ends_at_the_full_width() { + let smooth = |x: f32| { let x = x.clamp(0.0, 1.0); x * x * (3.0 - 2.0 * x) }; + assert_eq!(partial(24.0, 0.0), (0.0, 0.0), "nothing hidden: a hard edge"); + assert_eq!(partial(24.0, 1.0), (24.0, 0.0), "fully hidden: the plain ramp"); + for s in [0.1, 0.25, 0.5, 0.75, 0.9] { + let (w, o) = partial(24.0, s); + assert!((smooth(o) - (1.0 - s)).abs() < 1e-4, "edge alpha {} at strength {s}", smooth(o)); + assert!(((1.0 - o) * w - 24.0).abs() < 1e-3, "full alpha 24 in at strength {s}"); + } + } + + #[test] + fn reveal_leaves_the_margin_unless_the_row_cannot_fit_it() { + assert_eq!(reveal(100.0, 300.0, 20.0, 200.0, 0.0), 120.0, "flush below"); + assert_eq!(reveal(100.0, 300.0, 20.0, 200.0, 24.0), 144.0, "clear of a 24pt fade below"); + assert_eq!(reveal(100.0, 90.0, 20.0, 200.0, 24.0), 66.0, "and above"); + assert_eq!(reveal(100.0, 150.0, 20.0, 200.0, 24.0), 100.0, "already clear: no move"); + assert_eq!(reveal(100.0, 300.0, 180.0, 200.0, 24.0), 290.0, "a tall row splits what space is left"); + assert_eq!(reveal(100.0, 300.0, 500.0, 200.0, 24.0), 600.0, "a row taller than the viewport, below: its end"); + assert_eq!(reveal(600.0, 300.0, 500.0, 200.0, 24.0), 600.0, "and placing it again leaves it there"); + assert_eq!(reveal(400.0, 300.0, 500.0, 200.0, 24.0), 400.0, "a row filling the viewport: no move"); + assert_eq!(reveal(700.0, 300.0, 500.0, 200.0, 24.0), 300.0, "its end in view: its start"); + } +} diff --git a/app/vendor/rune/crates/rune/src/runtime/scroll/mode.rs b/app/vendor/rune/crates/rune/src/runtime/scroll/mode.rs new file mode 100644 index 0000000..55d4631 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/scroll/mode.rs @@ -0,0 +1,243 @@ +//! What moves a scroll viewport's vertical offset, and the hand latches around it, one frame +//! at a time. One `ScrollMode` carries the motion that is valid with the frame's hand data, and +//! one [`step`] folds a frame's facts into it, so a hand move, the step's derived `scrolling`, +//! the watcher's `by_hand`, a growth stack's `shrink_cut` and its layout end can't sit in +//! combinations that mean nothing. +use super::*; +use crate::machine::Effects; +use super::scroll_wheel::WheelCurve; + +/// What moves a viewport's vertical offset, one motion at a time, so it can't follow its +/// bottom while it glides, or coast while a glide carries it, with the hand latches that belong +/// to the frame. +#[derive(Clone, Copy, Debug, PartialEq)] +pub(in crate::runtime) enum ScrollMode { + /// At rest where a hand, an app or a glide left it. + Rest(Hand), + /// A stick-to-bottom viewport following its content's end. + Pinned(Hand), + /// Coasting from a fling, keys or wheel momentum at `v` points a second, decaying. + Momentum { v: f32, hand: Hand }, + /// Gliding on a spring (`ScrollState::glide_spring`) at `v` points a second. + Glide { v: f32, to: GlideTo, hand: Hand }, + /// Easing to where a notched mouse wheel sent it (`runtime/scroll/wheel.rs`). + Wheel { curve: WheelCurve, hand: Hand }, +} + +/// The hand latches a mode carries from frame to frame, whatever moves the offset. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub(in crate::runtime) struct Hand { + /// A hand (the wheel, keys, a drag, a touch) or an app's instant jump moved the offset + /// since the last step. The step clears it. + pub(in crate::runtime) direct: bool, + /// It moved in the last step: a hand, its momentum or a glide (derived there). + pub(in crate::runtime) scrolling: bool, + /// A hand or an app's instant jump moved it since `El::on_scroll_offset` was last told, + /// across the frame's steps; taken once at the frame's end. + pub(in crate::runtime) by_hand: bool, + /// A hand scrolled while the growth stack moved: no shrink glide until it settles. + pub(in crate::runtime) shrink_cut: bool, + /// The growth stack's layout end while its rows still move (see `ease_to_shrunk_end`). + pub(in crate::runtime) laid: Option<f64>, +} + +impl Default for ScrollMode { + fn default() -> Self { ScrollMode::Rest(Hand::default()) } +} + +/// Test builds count the mode writes each transition makes, so a landing that changes nothing +/// can be told from one that writes the same mode over itself. +#[cfg(test)] +mod writes { + use std::cell::Cell; + + thread_local! { static COUNT: Cell<usize> = const { Cell::new(0) }; } + + pub(super) fn note() { COUNT.with(|c| c.set(c.get() + 1)); } + + /// The writes since the last call. + pub(super) fn take() -> usize { COUNT.with(|c| c.replace(0)) } +} + +#[cfg(test)] +use writes::note as note_write; + +impl ScrollMode { + /// At rest, with no hand data: a viewport nobody has moved. + pub(in crate::runtime) fn rest() -> Self { ScrollMode::Rest(Hand::default()) } + + /// Following its content's end, with no hand data: a stick-to-bottom viewport that opens at + /// the bottom. + pub(in crate::runtime) fn following() -> Self { ScrollMode::Pinned(Hand::default()) } + + /// The hand latches this mode carries. + pub(in crate::runtime) fn hand(self) -> Hand { + match self { + ScrollMode::Rest(hand) | ScrollMode::Pinned(hand) => hand, + ScrollMode::Momentum { hand, .. } | ScrollMode::Glide { hand, .. } | ScrollMode::Wheel { hand, .. } => hand, + } + } + + fn hand_mut(&mut self) -> &mut Hand { + match self { + ScrollMode::Rest(hand) | ScrollMode::Pinned(hand) => hand, + ScrollMode::Momentum { hand, .. } | ScrollMode::Glide { hand, .. } | ScrollMode::Wheel { hand, .. } => hand, + } + } + + /// The same mode at rest, keeping the hand's latches. + pub(in crate::runtime) fn to_rest(self) -> Self { + #[cfg(test)] + note_write(); + ScrollMode::Rest(self.hand()) + } + + /// The same mode following its bottom, keeping the hand's latches. + pub(in crate::runtime) fn to_pinned(self) -> Self { + #[cfg(test)] + note_write(); + ScrollMode::Pinned(self.hand()) + } + + /// The same mode coasting at `v`, keeping the hand's latches. + pub(in crate::runtime) fn to_momentum(self, v: f32) -> Self { + #[cfg(test)] + note_write(); + ScrollMode::Momentum { v, hand: self.hand() } + } + + /// The same mode gliding at `v` toward `to`, keeping the hand's latches. + pub(in crate::runtime) fn to_glide(self, v: f32, to: GlideTo) -> Self { + #[cfg(test)] + note_write(); + ScrollMode::Glide { v, to, hand: self.hand() } + } + + /// The same mode easing on a wheel's `curve`, keeping the hand's latches. + pub(in crate::runtime) fn to_wheel(self, curve: WheelCurve) -> Self { + ScrollMode::Wheel { curve, hand: self.hand() } + } + + /// The wheel's ease, while one runs. + pub(in crate::runtime) fn wheel(self) -> Option<WheelCurve> { + match self { + ScrollMode::Wheel { curve, .. } => Some(curve), + _ => None, + } + } + + /// Its momentum (points a second), 0 unless coasting. + pub(in crate::runtime) fn coast(self) -> f32 { + match self { + ScrollMode::Momentum { v, .. } => v, + _ => 0.0, + } + } + + /// It follows its content's bottom. + pub(in crate::runtime) fn pinned(self) -> bool { matches!(self, ScrollMode::Pinned(_)) } + + /// The running glide's speed (points a second), while one runs. + pub(in crate::runtime) fn glide(self) -> Option<f32> { + match self { + ScrollMode::Glide { v, .. } => Some(v), + _ => None, + } + } +} + +/// What a frame did to a viewport. +pub(in crate::runtime) enum Event { + /// A hand or an app put the offset where it is. + Moved, + /// A touch holds the viewport (`El::scroll` under a finger). + Hold, + /// A touch's coast moved it (`moving`) or came to rest. + Coast { moving: bool }, + /// The viewport was concealed: nothing moved it, whatever a hand had done before. + Still, + /// A scroll step began: the growth stack is `moving`, so a hand's scroll cuts the shrink + /// glide until it settles. + Growth { moving: bool }, + /// The step's motion is over: derive `scrolling` from `direct` and the coast speeds, grow + /// the watcher's `by_hand`, and clear `direct`. + Step { x_v: f32 }, + /// The growth stack's layout end this frame. + Laid(Option<f64>), + /// `El::on_scroll_offset` asks for a hand move to report. + Take, + /// The motion stops, unless the viewport follows its bottom. + Halt, + /// The motion comes to rest where it is. + Rest, + /// The viewport follows its content's end from here. + Pin, + /// The viewport stops following its content's end, where it stands. + Unpin, +} + +#[derive(Debug, PartialEq)] +pub(in crate::runtime) enum Effect { + /// `El::on_scroll_offset`'s handler hears of a hand move at the frame's end. + Tell, +} + +/// Folds `event` into `mode`, returning what the caller should carry out. +pub(in crate::runtime) fn step(mode: &mut ScrollMode, event: Event) -> Effects<Effect> { + match event { + Event::Moved => mode.hand_mut().direct = true, + Event::Hold => { + let hand = mode.hand_mut(); + hand.scrolling = true; + hand.by_hand = true; + } + Event::Coast { moving } => { + let hand = mode.hand_mut(); + hand.scrolling = moving; + hand.by_hand |= moving; + hand.direct = false; + } + Event::Still => mode.hand_mut().scrolling = false, + Event::Growth { moving } => { + let coast = mode.coast(); + let hand = mode.hand_mut(); + hand.shrink_cut = moving && (hand.shrink_cut || hand.direct || coast.abs() > 1.0); + } + Event::Step { x_v } => { + let coast = mode.coast(); + let hand = mode.hand_mut(); + hand.scrolling = hand.direct || coast.abs() > 1.0 || x_v.abs() > 1.0; + hand.by_hand |= hand.scrolling; + hand.direct = false; + } + Event::Laid(laid) => mode.hand_mut().laid = laid, + Event::Take => { + return if std::mem::take(&mut mode.hand_mut().by_hand) { + Effects::one(Effect::Tell) + } else { + Effects::none() + }; + } + Event::Halt => { + if !mode.pinned() { + *mode = mode.to_rest(); + } + } + Event::Pin => { + if !mode.pinned() { + *mode = mode.to_pinned(); + } + } + Event::Unpin => { + if mode.pinned() { + *mode = mode.to_rest(); + } + } + Event::Rest => *mode = mode.to_rest(), + } + Effects::none() +} + +#[cfg(test)] +#[path = "mode_tests.rs"] +mod tests; diff --git a/app/vendor/rune/crates/rune/src/runtime/scroll/mode_tests.rs b/app/vendor/rune/crates/rune/src/runtime/scroll/mode_tests.rs new file mode 100644 index 0000000..69ea039 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/scroll/mode_tests.rs @@ -0,0 +1,228 @@ +use super::*; + +/// origin/dev's hand latches, transcribed from `runtime/motion/tracks.rs` (the step's +/// derivation), `runtime/scroll/offset.rs` (`ease_to_shrunk_end`'s cut) and +/// `runtime/scroll/touch.rs` (a finger's hold and coast), as the loose fields they were. +#[derive(Default)] +struct Dev { + direct: bool, + scrolling: bool, + by_hand: bool, + shrink_cut: bool, + laid: Option<f64>, + mode: DevMode, + /// Mode writes made by the last event. + writes: usize, +} + +#[derive(Clone, Copy, Default, PartialEq, Debug)] +enum DevMode { + #[default] + Rest, + Pinned, + Momentum(f32), + Glide(f32), +} + +impl Dev { + fn coast(&self) -> f32 { + match self.mode { + DevMode::Momentum(v) => v, + _ => 0.0, + } + } + + /// `runtime/motion/tracks.rs`: the step's `scrolling`, `by_hand` and `direct`. + fn step(&mut self, x_v: f32) { + self.scrolling = self.direct || self.coast().abs() > 1.0 || x_v.abs() > 1.0; + self.by_hand |= self.scrolling; + self.direct = false; + } + + /// `runtime/scroll/offset.rs`: the cut a hand puts on a shrink glide. + fn growth(&mut self, moving: bool) { + self.shrink_cut = moving && (self.shrink_cut || self.direct || self.coast().abs() > 1.0); + } + + fn write(&mut self, mode: DevMode) { + self.mode = mode; + self.writes += 1; + } + + /// `ScrollState::pin`: writing nothing when it already follows its bottom. + fn pin(&mut self) { + if self.mode != DevMode::Pinned { self.write(DevMode::Pinned); } + } + + fn halt(&mut self) { + if self.mode != DevMode::Pinned { self.write(DevMode::Rest); } + } + + fn unpin(&mut self) { + if self.mode == DevMode::Pinned { self.write(DevMode::Rest); } + } + + /// `ScrollState::land`: a pinned end stays as it is, and `stick` short-circuits the + /// comparison with the offset and its max. + fn land(&mut self, offset: f64, max: f64, stick: bool) { + if stick && offset >= max - 0.5 { self.pin() } else { self.write(DevMode::Rest); } + } +} + +#[derive(Clone, Copy, Debug)] +enum Act { + Moved, + Hold, + Coast(bool), + Still, + Growth(bool), + Step { x_v: f32 }, + Laid(bool), + Take, + Rest, + Halt, + Pin, + Unpin, + Land { offset: f64, max: f64, stick: bool }, + Momentum(f32), + Glide, +} + +fn production_mode(mode: ScrollMode) -> DevMode { + match mode { + ScrollMode::Rest(_) => DevMode::Rest, + ScrollMode::Pinned(_) => DevMode::Pinned, + ScrollMode::Momentum { v, .. } => DevMode::Momentum(v), + ScrollMode::Glide { v, .. } => DevMode::Glide(v), + ScrollMode::Wheel { .. } => unreachable!("no act starts a wheel's ease"), + } +} + +/// Drives every sequence through the production machine and through dev's fields, one +/// event at a time, comparing what each holds, and how many mode writes each made, after +/// every event. +fn walk(acts: &[Act]) { + let (mut st, mut dev) = (ScrollState::default(), Dev::default()); + for (i, act) in acts.iter().enumerate() { + dev.writes = 0; + match act { + Act::Moved => { st.moved(); dev.direct = true; } + Act::Hold => { + let _ = step(&mut st.mode, Event::Hold); + dev.scrolling = true; + dev.by_hand = true; + } + Act::Coast(moving) => { + let _ = step(&mut st.mode, Event::Coast { moving: *moving }); + dev.scrolling = *moving; + dev.by_hand |= *moving; + dev.direct = false; + } + Act::Still => { let _ = step(&mut st.mode, Event::Still); dev.scrolling = false; } + Act::Growth(moving) => { let _ = step(&mut st.mode, Event::Growth { moving: *moving }); dev.growth(*moving); } + Act::Step { x_v } => { let _ = step(&mut st.mode, Event::Step { x_v: *x_v }); dev.step(*x_v); } + Act::Laid(has) => { + let end = has.then_some(120.0); + let _ = step(&mut st.mode, Event::Laid(end)); + dev.laid = end; + } + Act::Take => { + let effects: Vec<Effect> = step(&mut st.mode, Event::Take).into_iter().collect(); + let was = std::mem::take(&mut dev.by_hand); + assert_eq!(effects, if was { vec![Effect::Tell] } else { vec![] }, "{acts:?}, event {i}: the take"); + } + Act::Rest => { st.mode = st.mode.to_rest(); dev.write(DevMode::Rest); } + Act::Halt => { st.halt(); dev.halt(); } + Act::Pin => { st.pin(); dev.pin(); } + Act::Unpin => { st.unpin(); dev.unpin(); } + Act::Land { offset, max, stick } => { + st.offset = *offset; + st.max = *max; + st.land(*stick); + dev.land(*offset, *max, *stick); + } + Act::Momentum(v) => { st.mode = st.mode.to_momentum(*v); dev.write(DevMode::Momentum(*v)); } + Act::Glide => { st.mode = st.mode.to_glide(2.0, GlideTo::Bottom); dev.write(DevMode::Glide(2.0)); } + } + let at = format!("{acts:?}, event {i} ({act:?})"); + assert_eq!(st.mode.hand().direct, dev.direct, "direct: {at}"); + assert_eq!(st.mode.hand().scrolling, dev.scrolling, "scrolling: {at}"); + assert_eq!(st.mode.hand().by_hand, dev.by_hand, "by_hand: {at}"); + assert_eq!(st.mode.hand().shrink_cut, dev.shrink_cut, "shrink_cut: {at}"); + assert_eq!(st.mode.hand().laid, dev.laid, "laid: {at}"); + assert_eq!(production_mode(st.mode), dev.mode, "mode: {at}"); + assert_eq!(writes::take(), dev.writes, "mode writes: {at}"); + } +} + +/// Every order of hand moves, growth steps, step derivations, takes and motion changes up +/// to five long: the folded latches must match dev's loose fields after each event. +#[test] +fn the_latches_match_devs_fields_over_every_order() { + let acts = [ + Act::Moved, Act::Hold, Act::Coast(true), Act::Coast(false), Act::Still, + Act::Growth(true), Act::Growth(false), Act::Step { x_v: 4.0 }, Act::Step { x_v: 0.0 }, + Act::Laid(true), Act::Laid(false), Act::Take, Act::Rest, Act::Halt, Act::Pin, + Act::Unpin, Act::Land { offset: 100.0, max: 100.0, stick: true }, + Act::Land { offset: 0.0, max: 100.0, stick: true }, Act::Land { offset: 100.0, max: 100.0, stick: false }, + Act::Momentum(2.0), Act::Glide, + ]; + for len in 0..=4 { + walk_all(&acts, len, &mut Vec::new()); + } +} + +/// dev's `land` calls the guarded `pin`, so a landing that changes nothing writes nothing. +#[test] +fn a_landing_on_a_pinned_viewport_writes_nothing() { + let mut st = ScrollState { offset: 100.0, max: 100.0, ..ScrollState::default() }; + st.pin(); + let _ = writes::take(); + st.land(true); + assert_eq!(writes::take(), 0, "already at the pinned end, the landing writes nothing"); + st.land(false); + assert_eq!(writes::take(), 1, "off the end it writes the rest"); + st.offset = 0.0; + st.land(true); + assert_eq!(writes::take(), 1, "short of the end it writes the rest"); +} + +fn walk_all(acts: &[Act], len: usize, prefix: &mut Vec<Act>) { + if prefix.len() == len { + walk(prefix); + return; + } + for &act in acts { + prefix.push(act); + walk_all(acts, len, prefix); + prefix.pop(); + } +} + +/// A hand move is cleared by the step that derives it, and a take reports the hand's move +/// once, however many steps grew it. +#[test] +fn a_hand_move_is_told_once_and_the_steps_keep_growing_it() { + let mut mode = ScrollMode::default(); + let _ = step(&mut mode, Event::Moved); + let _ = step(&mut mode, Event::Step { x_v: 0.0 }); + assert!(mode.hand().scrolling && mode.hand().by_hand && !mode.hand().direct); + let _ = step(&mut mode, Event::Step { x_v: 0.0 }); + assert!(!mode.hand().scrolling, "the step moved nothing"); + assert!(mode.hand().by_hand, "the watcher still has to hear it"); + assert_eq!(step(&mut mode, Event::Take).into_iter().collect::<Vec<_>>(), [Effect::Tell]); + assert_eq!(step(&mut mode, Event::Take).into_iter().collect::<Vec<_>>(), []); +} + +/// Whichever motion the mode changes to, the hand's latches come with it. +#[test] +fn a_motion_change_keeps_the_hands_latches() { + let mut mode = ScrollMode::default(); + let _ = step(&mut mode, Event::Moved); + let _ = step(&mut mode, Event::Laid(Some(300.0))); + for changed in [mode.to_glide(1.0, GlideTo::Offset(40.0)), mode.to_momentum(2.0), mode.to_pinned(), mode.to_rest()] { + assert!(changed.hand().direct && changed.hand().laid == Some(300.0), "{changed:?}"); + mode = changed; + } + assert!(mode.hand().direct && mode.hand().laid == Some(300.0)); +} diff --git a/app/vendor/rune/crates/rune/src/runtime/scroll/nudge.rs b/app/vendor/rune/crates/rune/src/runtime/scroll/nudge.rs new file mode 100644 index 0000000..f367483 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/scroll/nudge.rs @@ -0,0 +1,95 @@ +//! An app's instant scroll (`Tx::scroll_to_instant` and the like) holds hover under a still +//! pointer: content moved with nothing under the pointer moving, so hover waits out the hold +//! instead of lighting each row an app's own, frame-by-frame glide carries past. The hold is a +//! time on the clock, so it lasts as long on a 30 Hz display as on a 120 Hz one: the frame the +//! scroll lands in holds, and hover resolves once at the pointer when the hold is over +//! (`runtime/input/hover.rs`). A held nudge draws nothing in between: it asks for one frame at +//! its due time, the frame that ends it. +use crate::machine::{Attempt, Effects, Seq}; + +/// How long an instant scroll holds hover: the two frames at 60 Hz its frame countdown took. +pub(in crate::runtime) const NUDGE_HOLD: f64 = 2.0 / 60.0; + +/// A deadline comparison's slack, so a frame that lands on the due time ends the hold. +const SLACK: f64 = 1e-6; + +/// A viewport's hold: armed as one [`Attempt`] due at a clock time, so a wake an earlier arm +/// asked for changes nothing. +#[derive(Clone, Debug, Default)] +pub(in crate::runtime) struct Nudge { + seq: Seq, + state: Hold, +} + +/// Where the hold stands. +#[derive(Clone, Debug, Default, PartialEq)] +pub(in crate::runtime) enum Hold { + /// Nothing holds hover. + #[default] + Free, + /// An instant scroll landed, and hover holds until this clock time, as `attempt`. + Held { attempt: Attempt, due: f64 }, +} + +pub(in crate::runtime) enum Event { + /// An app's instant scroll landed at this clock time. + Arm { now: f64 }, + /// A frame at `now`, carrying the `attempt` its arm asked for: the hold ends only if that + /// is still the armed one. + Due { attempt: Attempt, now: f64 }, +} + +#[derive(Debug, PartialEq)] +pub(in crate::runtime) enum Effect { + /// Wake at this clock time, when the hold is due. + WakeAt(f64), +} + +pub(in crate::runtime) fn step(seq: &mut Seq, state: &mut Hold, event: Event) -> Effects<Effect> { + match event { + Event::Arm { now } => { + let (attempt, due) = (seq.next(), now + NUDGE_HOLD); + *state = Hold::Held { attempt, due }; + Effects::one(Effect::WakeAt(due)) + } + Event::Due { attempt, now } => match state { + Hold::Held { attempt: armed, due } if *armed == attempt && *due <= now + SLACK => { + *state = Hold::Free; + Effects::none() + } + _ => Effects::none(), + }, + } +} + +impl Nudge { + /// An instant scroll landed at `now` from the clock: hover holds, and this asks for the + /// wake that brings the frame the hold ends on. + pub(in crate::runtime) fn arm(&mut self, now: f64) -> Effects<Effect> { + step(&mut self.seq, &mut self.state, Event::Arm { now }) + } + + /// A frame at `now`, the one its wake asked for: a hold that came due ends. + pub(in crate::runtime) fn tick(&mut self, now: f64) { + if let Hold::Held { attempt, .. } = self.state { + let _ = step(&mut self.seq, &mut self.state, Event::Due { attempt, now }); + } + } + + /// Hover holds at `now`. + pub(in crate::runtime) fn hold_at(&self, now: f64) -> bool { + matches!(self.state, Hold::Held { due, .. } if now + SLACK < due) + } + + /// The clock time a pending hold ends. + pub(in crate::runtime) fn due(&self) -> Option<f64> { + match self.state { + Hold::Held { due, .. } => Some(due), + Hold::Free => None, + } + } +} + +#[cfg(test)] +#[path = "nudge_tests.rs"] +mod tests; diff --git a/app/vendor/rune/crates/rune/src/runtime/scroll/nudge_tests.rs b/app/vendor/rune/crates/rune/src/runtime/scroll/nudge_tests.rs new file mode 100644 index 0000000..403b31e --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/scroll/nudge_tests.rs @@ -0,0 +1,135 @@ +use super::*; + +/// origin/dev's countdown, transcribed from `runtime/scroll/offset.rs`: a jump armed two +/// frames, and each frame took one off and reported whether one still held. +/// +/// differs from dev: this holds on the clock, so its hold ends a fixed time after the last +/// instant scroll instead of a fixed number of frames; the two agree only at 60 Hz, the rate +/// its two frames were timed for (`the_hold_matches_the_countdown_at_sixty_hertz`), and part +/// company at every other rate (`the_hold_ends_a_fixed_time_after_the_land` drives 30 and 120). +#[derive(Default)] +struct Dev { + nudged: u8, +} + +impl Dev { + fn arm(&mut self) { + self.nudged = 2; + } + + fn frame(&mut self) -> bool { + self.nudged = self.nudged.saturating_sub(1); + self.nudged > 0 + } + + fn held(&self) -> bool { + self.nudged > 0 + } +} + +/// One 60 Hz frame: the rate dev's two-frame countdown and this hold are the same at. +const FRAME: f64 = 1.0 / 60.0; + +#[derive(Clone, Copy, Debug)] +enum Act { + Arm, + Frame, +} + +/// Drives one sequence through the machine and through the countdown, one event at a time, and +/// compares what each reports after every event. +fn walk(acts: &[Act]) { + let (mut nudge, mut dev, mut now) = (Nudge::default(), Dev::default(), 0.0); + for (at, &act) in acts.iter().enumerate() { + match act { + Act::Arm => { + let effects = nudge.arm(now); + dev.arm(); + assert_eq!(effects, Effects::one(Effect::WakeAt(now + NUDGE_HOLD)), "{acts:?} at {at}: the arm asks for its due time"); + } + Act::Frame => { + now += FRAME; + nudge.tick(now); + dev.frame(); + } + } + assert_eq!(nudge.hold_at(now), dev.held(), "{acts:?}: held after event {at}, at {now}"); + } +} + +/// Every sequence of arms and frames up to six long: an arm at a frame's clock time and the +/// frames after it, in any order, must hold hover exactly where dev's countdown did. +#[test] +fn the_hold_matches_the_countdown_at_sixty_hertz() { + let mut acts = Vec::new(); + for len in 0..=6 { + acts.clear(); + enumerate(&mut acts, len); + } +} + +fn enumerate(acts: &mut Vec<Act>, len: usize) { + if acts.len() == len { + walk(acts); + return; + } + for act in [Act::Arm, Act::Frame] { + acts.push(act); + enumerate(acts, len); + acts.pop(); + } +} + +/// A hold that came due releases hover; before it, the arm's own frame and the one after hold. +#[test] +fn the_hold_covers_the_landing_frame_and_the_next() { + let mut nudge = Nudge::default(); + let landed = 4.5; + let _ = nudge.arm(landed); + assert!(nudge.hold_at(landed), "the frame it landed holds"); + nudge.tick(landed + FRAME); + assert!(nudge.hold_at(landed + FRAME), "so does the next"); + nudge.tick(landed + 2.0 * FRAME); + assert!(!nudge.hold_at(landed + 2.0 * FRAME), "and it is over on the third"); + assert_eq!(nudge.state, Hold::Free); + nudge.tick(landed + 3.0 * FRAME); + assert!(!nudge.hold_at(landed + 3.0 * FRAME), "a spent hold stays free"); +} + +/// differs from dev: dev took a frame off the countdown whatever the frame rate, so it held +/// hover for two frames at 30 Hz as at 120. This one ends the same time after the land at +/// either rate, which is the whole point of the change. +#[test] +fn the_hold_ends_a_fixed_time_after_the_land() { + for rate in [30.0, 120.0] { + let (mut nudge, mut now) = (Nudge::default(), 0.0); + let _ = nudge.arm(now); + let mut freed = None; + for _ in 0..10 { + now += 1.0 / rate; + nudge.tick(now); + if !nudge.hold_at(now) { + freed = Some(now); + break; + } + } + let freed = freed.unwrap_or_else(|| panic!("{rate} fps: the hold ends")); + assert!(freed >= NUDGE_HOLD - 1e-9 && freed < NUDGE_HOLD + 1.0 / rate + 1e-9, "{rate} fps: held {freed} seconds"); + } +} + +/// A due carried by an earlier arm changes nothing: the newer arm keeps its own deadline. +#[test] +fn a_due_from_an_earlier_arm_changes_nothing() { + let (mut nudge, mut now) = (Nudge::default(), 0.0); + let _ = nudge.arm(now); + let Hold::Held { attempt: first, due: first_due } = nudge.state else { panic!("armed") }; + now += FRAME; + let _ = nudge.arm(now); + let Hold::Held { attempt: second, due } = nudge.state else { panic!("armed") }; + assert_ne!(second, first); + assert_eq!(due, now + NUDGE_HOLD); + let _ = step(&mut nudge.seq, &mut nudge.state, Event::Due { attempt: first, now: first_due + 1.0 }); + assert!(nudge.hold_at(now), "the newer arm still holds"); + assert_eq!(nudge.state, Hold::Held { attempt: second, due }); +} diff --git a/app/vendor/rune/crates/rune/src/runtime/scroll/offset.rs b/app/vendor/rune/crates/rune/src/runtime/scroll/offset.rs new file mode 100644 index 0000000..1e2c9af --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/scroll/offset.rs @@ -0,0 +1,342 @@ +//! `Tx::scroll_to`, `Tx::scroll_to_with`, `Tx::scroll_to_instant`, `Tx::scroll_to_x` and +//! `Tx::scroll_to_y`: moving a viewport to an offset its app picked, gliding there or at once; +//! and `Tx::scroll_key_to`, landing an element at a height in its viewport. +use super::*; +use crate::runtime::scroll_mode::{self as mode, Event as ModeEvent}; + +/// How a keyed scroll request anchors its target within the viewport. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum ScrollAnchor { + None, + /// Place the target's top `y` points below the viewport's top (`Tx::scroll_key_to`). + Top, + /// Place the target's vertical midpoint (for a `TextHighlight`, its inline font-metric box + /// `[baseline - ascent, baseline + descent]`) `y` points below the viewport's top, snapped to + /// whole device pixels (`Tx::scroll_key_center_at`). + CenterSnapped, +} + +/// A request to move a viewport to an offset on one axis or both. +#[derive(Clone, Debug)] +pub(crate) struct ScrollRequest { + pub key: String, + pub x: Option<f32>, + pub y: Option<f32>, + /// The spring it glides on, or None to jump. + pub glide: Option<Spring>, + pub anchor: ScrollAnchor, +} + +impl RuntimeCore { + /// Each request moves the viewport keyed (or pathed) by its key, or the nearest one around + /// it that scrolls an axis it asks for, clamped to its content. Axes the viewport doesn't + /// scroll are left alone. + pub(in crate::runtime) fn scroll_to_offsets(&mut self, app: &mut dyn AppDriver, requests: Vec<ScrollRequest>) { + // This frame's commit may have changed the content: measure the extent first. + self.step_scroll(0.0); + let animate = !self.reduced_motion && !self.settled; + // Jumps: (viewport, horizontal, offset), reapplied once virtual rows land. + let mut jumps = Vec::new(); + // Anchored jumps, placed again from the new layout once virtual rows land. + let mut anchors = Vec::new(); + for r in requests { + if r.anchor != ScrollAnchor::None { + let Some((i, to)) = self.anchor_offset(&r.key, r.y.unwrap_or(0.0), r.anchor) else { continue }; + jumps.push((self.tree.nodes[i].id, false, to)); + anchors.push((jumps.len() - 1, r.key, r.y.unwrap_or(0.0), r.anchor)); + if let Some(st) = self.scroll.scrolls.get_mut(&self.tree.nodes[i].id) { st.halt(); } + continue; + } + let Some(i) = self.scroll_viewport_on(&r.key, r.x.is_some(), r.y.is_some()) else { continue }; + let (id, axes) = (self.tree.nodes[i].id, self.tree.nodes[i].scroll_axes); + let (view_w, view_h) = (f64::from(self.tree.nodes[i].local.w), f64::from(self.tree.nodes[i].local.h)); + let Some(st) = self.scroll.scrolls.get_mut(&id) else { continue }; + let glide = r.glide.filter(|_| animate); + if glide.is_some() { st.spring = glide; } + if let Some(x) = r.x.filter(|_| axes.x()) { + let to = f64::from(x).max(0.0); + // A glide that starts during a wheel's ease keeps the ease's speed. + let v = match st.x.motion { XMotion::Glide { v, .. } => v, XMotion::Wheel(c) => c.velocity() as f32, _ => 0.0 }; + if let Some(spring) = glide && (to.min(st.x.max) - st.x.offset).abs() > 0.5 { + // A long trip cuts to a couple of viewports out first, as a glide to the bottom does. + let reach = scroll_bottom::GLIDE_REACH * view_w; + let end = to.min(st.x.max); + st.x.offset = st.x.offset.clamp(end - reach, end + reach); + st.x.motion = XMotion::Glide { v: retarget_v(spring, st.x.offset, v, end), aim: to }; + } else { + st.x.motion = XMotion::Rest; + jumps.push((id, true, to)); + } + } + if let Some(y) = r.y.filter(|_| axes.y()) { + let to = f64::from(y).max(0.0); + if let Some(spring) = glide && (to.min(st.max) - st.offset).abs() > 0.5 { + let reach = scroll_bottom::GLIDE_REACH * view_h; + let end = to.min(st.max); + st.offset = st.offset.clamp(end - reach, end + reach); + let v = retarget_v(spring, st.offset, st.glide().or_else(|| st.mode.wheel().map(|c| c.velocity() as f32)).unwrap_or(0.0), end); + st.mode = st.mode.to_glide(v, GlideTo::Offset(to)); + } else { + st.halt(); + jumps.push((id, false, to)); + } + } + } + self.scroll.apply_jumps(&self.tree.nodes, self.clock, &jumps); + // Landing mounts the virtual rows there, which measure and can move the end it clamped to. + for _ in 0..3 { + if !self.virtual_window_changed() { break; } + // A jump is at once, and so are the rows it mounts: none fades in where it lands. + self.commit(app, &Tx { commit: Commit::Instant, ..Tx::default() }); + self.step_scroll(0.0); + for (j, key, at, mode) in &anchors { + if let Some((_, to)) = self.anchor_offset(key, *at, *mode) { jumps[*j].2 = to; } + } + self.scroll.apply_jumps(&self.tree.nodes, self.clock, &jumps); + } + } + + /// The vertical viewport around the element or `TextHighlight` `key` and the offset that + /// anchors it `at` points below the viewport's top (by top edge or device-pixel-snapped + /// vertical midpoint), before clamping. + /// A virtual row not mounted yet stands where its list's estimates put it: the jump there + /// mounts it, and is placed again from its laid-out geometry once it has (`scroll_to_offsets`). + fn anchor_offset(&self, key: &str, at: f32, mode: ScrollAnchor) -> Option<(usize, f64)> { + let found = |scope: Option<&str>, key: &str| { + self.live_named(scope, key) + .map(|i| { + let y0 = self.tree.nodes[i].target[1]; + let y = match mode { + ScrollAnchor::CenterSnapped => y0 + self.tree.nodes[i].local.h * 0.5, + _ => y0, + }; + (i, y) + }) + .or_else(|| { + let (i, [_, y0, _, y1]) = match mode { + ScrollAnchor::CenterSnapped => self.highlight_inline_target_in(&self.tree.nodes, scope, key)?, + _ => self.highlight_target_in(&self.tree.nodes, scope, key)?, + }; + let y = match mode { + ScrollAnchor::CenterSnapped => (y0 + y1) * 0.5, + _ => y0, + }; + (!self.subtree_exiting(i)).then_some((i, y)) + }) + }; + // `"row/mark"`: element or highlight `mark` anywhere inside the element keyed `row`. + let target = found(None, key).or_else(|| key.split_once('/').and_then(|(row, mark)| found(Some(row), mark))); + if let Some((i, y)) = target { + let v = std::iter::successors(Some(i), |&p| self.tree.nodes[p].parent).find(|&p| self.tree.nodes[p].scroll.is_some() && self.tree.nodes[p].scroll_axes.y())?; + let raw = f64::from(y - self.tree.nodes[v].target[1] - at).max(0.0); + let to = match mode { + ScrollAnchor::CenterSnapped => { + let s = f64::from(self.env.scale).max(1.0); + (raw * s).round() / s + } + _ => raw, + }; + return Some((v, to)); + } + self.tree.nodes.iter().find_map(|n| { + let list = self.commit.virtuals.get(&n.path)?; + // A row that isn't mounted stands where the estimates put it; the jump mounts it and + // `scroll_to_offsets` places `mark` once it has. + let index = list.index_of(key).or_else(|| list.index_of(key.split_once('/')?.0))?; + let v = *self.tree.node_index.get(self.tree.path_ids.get(&list.scroll_path)?)?; + Some((v, f64::from(list.top + list.pad_top + list.prefix(index) - at).max(0.0))) + }) + } + + /// The viewport keyed (or pathed) `key`, or the nearest one around it, that scrolls + /// horizontally (`x`) or vertically (`y`). + fn scroll_viewport_on(&self, key: &str, x: bool, y: bool) -> Option<usize> { + let i = self.tree.nodes.iter().enumerate() + .position(|(i, n)| n.named(key) && !self.subtree_exiting(i)) + .or_else(|| self.highlight_target_in(&self.tree.nodes, None, key).map(|(i, _)| i))?; + std::iter::successors(Some(i), |&p| self.tree.nodes[p].parent).find(|&p| { + let n = &self.tree.nodes[p]; + n.scroll.is_some() && ((x && n.scroll_axes.x()) || (y && n.scroll_axes.y())) + }) + } + + /// A growth stack shrinking under a reader who scrolled up, until its layout ends above + /// their offset: viewport `i` glides to that end from rest, as `Tx::scroll_to` would, rather + /// than riding the presented end down at the collapse's own speed and stopping with it. + /// `overflow` is this frame's presented overflow. A keep or reveal owns its viewport, and an + /// end already above the offset (a settled or instant change) clamps at once. The glide + /// follows the end as it moves again, and stops once the rows regrow past the offset; a + /// hand scrolling mid-collapse keeps the viewport until the rows settle. + /// + /// Returns the layout's end while rows are still moving, which a viewport landed there + /// waits for before it sticks to the end, so the presented end's last fraction of a point + /// doesn't lift it back up. + pub(in crate::runtime) fn ease_to_shrunk_end(&mut self, i: usize, overflow: f64) -> Option<f64> { + let c = self.scroll_stack(i)?; + let stack = self.motion.stacks.get(&self.tree.nodes[c].id)?; + let moving = stack.moving || !stack.closing.is_empty(); + let path = &self.tree.nodes[i].path; + let owned = self.scroll.requests.owns(path); + let bottom = self.scroll_children(i).map(|k| self.tree.nodes[k].target[3]).reduce(f32::max).unwrap_or(self.tree.nodes[c].target[3]); + let end = f64::from(bottom - self.tree.nodes[i].target[3]).max(0.0); + let held = self.reduced_motion || owned; + let st = self.scroll.scrolls.get_mut(&self.tree.nodes[i].id)?; + let _ = mode::step(&mut st.mode, ModeEvent::Growth { moving }); + match st.mode { + ScrollMode::Glide { to: GlideTo::ShrunkEnd(_), .. } if held || st.shrink_cut() || end >= st.offset => st.mode = st.mode.to_rest(), + ScrollMode::Glide { v, to: GlideTo::ShrunkEnd(_), .. } => st.mode = st.mode.to_glide(v, GlideTo::ShrunkEnd(end)), + ScrollMode::Rest(_) | ScrollMode::Momentum { .. } if moving && !(held || st.shrink_cut() || st.offset > overflow || st.offset - end <= 0.5) => { + st.mode = st.mode.to_glide(0.0, GlideTo::ShrunkEnd(end)); + st.spring = None; + } + _ => {} + } + moving.then_some(end) + } +} + +/// The speed a running glide at `offset` keeps when it's sent to `to` on `spring`: all of it, +/// unless that would carry it past `to` and back (a critically damped spring heading for its +/// end faster than ω times the distance left overshoots), so a glide sent somewhere nearer +/// stops there on one path instead of bouncing. Retargets that keep their speed, as key +/// repeat sending a glide one row on at a time does, run as one motion rather than steps. +pub(in crate::runtime) fn retarget_v(spring: Spring, offset: f64, v: f32, to: f64) -> f32 { + let d = (offset - to) as f32; + let most = spring.omega() * d.abs(); + if v * d < 0.0 && v.abs() > most { -d.signum() * most } else { v } +} + +/// How near its end a glide lands, in points: its speed, in points a second, under 40 times that. +const LAND: f32 = 0.1; + +/// Steps a glide on one axis toward `to` on `spring`. Returns whether it is still moving. +pub(in crate::runtime) fn glide_axis(spring: Spring, offset: &mut f64, glide: &mut Option<f32>, to: f64, dt: f32) -> bool { + let Some(v) = *glide else { return false }; + // Sample the displacement, not the absolute offset: f32 loses sub-point precision far down. + let (d, v) = spring.sample((*offset - to) as f32, v, 0.0, dt); + // Lands under a tenth of a point out, so the last step is no bigger than the ones before it. + if d.abs() < LAND && v.abs() < 40.0 * LAND { + *offset = to; + *glide = None; + return false; + } + *offset = to + f64::from(d); + *glide = Some(v); + true +} + +impl ScrollState { + /// The spring the running glide steps on. + pub(in crate::runtime) fn glide_spring(&self) -> Spring { + self.spring.unwrap_or(crate::tok::motion::GLIDE) + } + + /// A hand, its momentum or a glide is moving the content this frame: what + /// [`ElementInfo::scrolling`](crate::ElementInfo) reports for everything inside. + pub(crate) fn moving(&self) -> bool { + self.scrolling() || self.glide().is_some() || self.mode.wheel().is_some() || self.x.carried() + } + + /// It follows its content's bottom. + pub(in crate::runtime) fn pinned(&self) -> bool { self.mode.pinned() } + + /// The running glide's speed (points a second), while one runs. + pub(in crate::runtime) fn glide(&self) -> Option<f32> { self.mode.glide() } + + /// Where the running glide heads, when that isn't the bottom. + #[cfg(test)] + pub(in crate::runtime) fn glide_to(&self) -> Option<f64> { + match self.mode { + ScrollMode::Glide { to, .. } => to.offset(), + _ => None, + } + } + + /// Its momentum (points a second), 0 unless coasting. + pub(in crate::runtime) fn coast(&self) -> f32 { self.mode.coast() } + + /// A hand or its momentum moved it in the last step. + pub(in crate::runtime) fn scrolling(&self) -> bool { self.mode.hand().scrolling } + + /// A hand or an app moved it since the last step. + pub(in crate::runtime) fn direct(&self) -> bool { self.mode.hand().direct } + + /// A hand scrolled while the growth stack moved. + pub(in crate::runtime) fn shrink_cut(&self) -> bool { self.mode.hand().shrink_cut } + + /// The growth stack's layout end while its rows still move. + pub(in crate::runtime) fn laid(&self) -> Option<f64> { self.mode.hand().laid } + + /// A hand or an app put the offset where it is. + pub(in crate::runtime) fn moved(&mut self) { let _ = mode::step(&mut self.mode, mode::Event::Moved); } + + /// The viewport was concealed: nothing moved it, whatever a hand did before. + pub(in crate::runtime) fn still(&mut self) { let _ = mode::step(&mut self.mode, mode::Event::Still); } + + /// Follow the bottom from here (a pinned viewport keeps how its end last stepped). + pub(in crate::runtime) fn pin(&mut self) { let _ = mode::step(&mut self.mode, mode::Event::Pin); } + + /// Stop following the bottom, where it stands. + pub(in crate::runtime) fn unpin(&mut self) { let _ = mode::step(&mut self.mode, mode::Event::Unpin); } + + /// Momentum and any glide stop; a pinned viewport stays pinned. + pub(in crate::runtime) fn halt(&mut self) { let _ = mode::step(&mut self.mode, mode::Event::Halt); } + + /// A hand or an app put the offset where it is: momentum and any glide stop, and a + /// stick-to-bottom viewport (`stick`) follows its end only if it sits there. + /// An app's keep moved the offset (rows above measured, an anchor held what's on screen): a + /// wheel's ease goes on, moved with it on its next step (`WheelCurve::follow`), as Chromium's + /// `ApplyAdjustment` moves a running smooth scroll; anything else lands as `Self::land` does. + pub(in crate::runtime) fn keep_land(&mut self, stick: bool) { if self.mode.wheel().is_none() { self.land(stick) } } + + pub(in crate::runtime) fn land(&mut self, stick: bool) { + if stick && self.offset >= self.max - 0.5 { self.pin() } else { let _ = mode::step(&mut self.mode, mode::Event::Rest); } + } + + /// An app's instant scroll landed less than `scroll_nudge::NUDGE_HOLD` ago: content moved + /// under a still pointer, so hover waits as it does for a glide it stepped itself. + pub(in crate::runtime) fn hold_at(&self, now: f64) -> bool { self.nudge.hold_at(now) } +} + +impl requests::ScrollTables { + pub(super) fn apply_jumps(&mut self, nodes: &[Node], now: f64, jumps: &[(NodeId, bool, f64)]) { + for &(id, horizontal, to) in jumps { + let stick = nodes.iter().find(|n| n.id == id).and_then(|n| n.scroll).is_some_and(|s| s.stick_bottom); + let Some(st) = self.scrolls.get_mut(&id) else { continue }; + st.moved(); + let was = if horizontal { st.x.offset } else { st.offset }; + if horizontal { + st.x.offset = to.min(st.x.max); + } else { + st.offset = to.min(st.max); + // The jump halted the old motion when queued. Don't cancel a later + // request in the same transaction to glide from the new offset. + if st.glide().is_none() { st.land(stick); } + } + if (if horizontal { st.x.offset } else { st.offset } - was).abs() > 1e-3 { + // The arm's due is taken back from the state each frame (`step_nudges`), so a + // later arm in the same frame wins and nothing here has to keep it. + let _ = st.nudge.arm(now); + } + } + } + + /// Steps the holds an app's instant scrolls armed, and returns the earliest due one still + /// pending: the frame that carries it resolves hover at the pointer. A held nudge asks for + /// no frame itself, so the frame's end wakes for that one, however often the app re-armed it. + pub(in crate::runtime) fn step_nudges(&mut self, now: f64) -> Option<f64> { + let mut due: Option<f64> = None; + for st in self.scrolls.values_mut() { + st.nudge.tick(now); + if let Some(at) = st.nudge.due() { due = Some(due.map_or(at, |d: f64| d.min(at))); } + } + due + } +} + +impl RuntimeCore { + #[inline] + pub(in crate::runtime) fn step_nudges(&mut self) -> Option<f64> { + self.scroll.step_nudges(self.clock) + } +} diff --git a/app/vendor/rune/crates/rune/src/runtime/scroll/requests.rs b/app/vendor/rune/crates/rune/src/runtime/scroll/requests.rs new file mode 100644 index 0000000..e731324 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/scroll/requests.rs @@ -0,0 +1,343 @@ +//! Requests that outlive a commit: `Tx::keep_on_screen` anchors, a fold's row held below its +//! header, and `Tx::scroll_into_view`/`Tx::scroll_center` reveals. One [`Request`] and one +//! [`Requests::step`] own their life, so which request a viewport keeps, and when it gives way +//! to another, is answered in one place instead of five scans across three files. +//! +//! They are stored in two lanes because they are consumed apart: the paint pass reads only +//! keeps, and the nested commit that remounts virtual rows lifts only the keeps out, leaving +//! the reveals' buffer where it is. +//! +//! Events that test every request on every frame are types of their own, generic over what +//! they measure, so a caller's measurements compile into the loop with no indirect call. +use super::sticky::{Hold, Keep, Reveal}; +use super::{AppDriver, HashMap, NodeId, RuntimeCore, ScrollState, Tx, scroll_x}; +use crate::machine::{Attempt, Effects}; + +/// Retained scroll viewports, wheel gesture locking, scroll requests and per-frame sticky state. +/// Ordered hot-first under `#[repr(C)]` so per-node sticky vectors and `scrolls` stay contiguous. +#[repr(C)] +pub(crate) struct ScrollTables { + /// Each node's sticky shift this frame (points), while `has_sticky`. + pub(in crate::runtime) stuck: Vec<f32>, + /// Per node, what its children stick within: the nearest vertical viewport's top and + /// bottom, then the node's own content box top and bottom (unscaled points), while + /// `has_sticky`. + pub(in crate::runtime) sticky_frame: Vec<[f32; 8]>, + /// Sections whose rows fade under their stuck header this frame (`ScrollFade::below_sticky`), + /// with the paint clip top the header keeps. + pub(in crate::runtime) sticky_bands: Vec<(usize, f32)>, + pub(crate) scrolls: HashMap<NodeId, ScrollState>, + /// `Tx::keep_on_screen` across the commit underway, and `Tx::scroll_into_view` requests that + /// follow their target while growth/layout springs run. + pub(in crate::runtime) requests: Requests, + /// The axis the current wheel or trackpad gesture scrolls (`runtime/scroll/x.rs`). + pub(super) wheel_lock: scroll_x::WheelLock, + /// Whole notches of a mouse wheel ease where the platform's browsers do (`Runtime::set_wheel_glide`). + wheel_glide: bool, +} + +impl ScrollTables { + // Single-caller constructor for `RuntimeCore::new`; inlined so it stays in its caller's + // codegen unit instead of shifting partitioning and dropping inlining in the paint walk. + #[inline] + pub(in crate::runtime) fn new() -> Self { + Self { + stuck: Vec::new(), + sticky_frame: Vec::new(), + sticky_bands: Vec::new(), + scrolls: HashMap::default(), + requests: Default::default(), + wheel_lock: Default::default(), + wheel_glide: true, + } + } + + /// Whether whole notches of a mouse wheel ease rather than jump. + #[inline] + pub(in crate::runtime) fn wheel_glides(&self, reduced_motion: bool, settled: bool) -> bool { + self.wheel_glide && !reduced_motion && !settled + } + + #[inline] + pub(in crate::runtime) fn set_wheel_glide(&mut self, on: bool) { + self.wheel_glide = on; + } + + #[inline] + pub(in crate::runtime) fn wheel_gesture(&self) -> Attempt { + self.wheel_lock.gesture + } + + #[inline] + pub(in crate::runtime) fn wheel_momentum(&self) -> bool { + self.wheel_lock.momentum() + } + + #[inline] + pub(in crate::runtime) fn wheel_phased(&self) -> bool { + self.wheel_lock.phased() + } + + #[inline] + pub(in crate::runtime) fn wheel_notched(&mut self, now: f64, notch: bool) -> bool { + self.wheel_lock.notched(now, notch) + } + + #[inline] + pub(in crate::runtime) fn wheel_owner(&self) -> &scroll_x::WheelOwner { + self.wheel_lock.owner() + } + + #[inline] + pub(in crate::runtime) fn wheel_owner_of(&self, gesture: Attempt) -> Option<&scroll_x::WheelOwner> { + self.wheel_lock.owner_of(gesture) + } + + #[inline] + pub(in crate::runtime) fn sync_wheel_gesture(&mut self, gesture: Attempt) { + self.wheel_lock.sync_gesture(gesture); + } + + #[inline] + pub(in crate::runtime) fn set_wheel_owner(&mut self, gesture: Attempt, owner: scroll_x::WheelOwner) { + self.wheel_lock.set_owner(gesture, owner); + } + + #[inline] + pub(in crate::runtime) fn wheel_vertical_run(&mut self, now: f64, x: f32, y: f32, dy: f32) -> Option<NodeId> { + self.wheel_lock.vertical_run(now, x, y, dy) + } + + #[inline] + pub(in crate::runtime) fn end_wheel_vertical(&mut self) { + self.wheel_lock.end_vertical(); + } + + #[inline] + pub(in crate::runtime) fn ran_wheel_vertical(&mut self, id: NodeId, now: f64, x: f32, y: f32, dy: f32, moved: bool, held: bool) { + self.wheel_lock.ran_vertical(id, now, x, y, dy, moved, held); + } + + /// A user or explicit scroll ends the holds and reveals that would pull the view back. + #[inline] + pub(in crate::runtime) fn drop_holds(&mut self) { + self.requests.step(Event::Cancel); + } + + /// Whether a `Tx::keep_on_screen` holds a stuck header (`Hold`). + #[inline] + pub(in crate::runtime) fn holding(&self) -> bool { + self.requests.keeps().any(|k| k.hold.is_some()) + } + + #[inline] + pub(in crate::runtime) fn hold_of(&self, path: &str) -> Option<&Hold> { + if !self.requests.has_keeps() { return None; } + self.requests.keeps().find_map(|k| k.hold.as_ref().filter(|h| h.path == path)) + } +} + +/// One request outliving the commit that made it. +pub(in crate::runtime) enum Request { + /// A `Tx::keep_on_screen` element: it and any reveal on its viewport give way to it. + Capture(Keep), + /// The row below a fold's header, held where it shows: it takes the viewport's earlier + /// keeps, while a reveal of the same viewport stays. + FoldAnchor(Keep), + /// A `Tx::scroll_into_view` or `Tx::scroll_center` target. + Reveal(Reveal), +} + +#[derive(Default, Clone)] +pub(in crate::runtime) struct Requests { + keeps: Vec<Keep>, + reveals: Vec<Reveal>, +} + +pub(in crate::runtime) enum Event<'a> { + Arrive(Request), + /// A reveal placed its target: `from` and `to` are its viewport's offset before and after, + /// and `first` says whether this is the placement that created it. + Place { first: bool, scope: Option<&'a str>, key: &'a str, viewport: &'a str, + center: bool, at_end: bool, from: f64, to: f64 }, + /// A virtual list's last row left the view: an end-pinned reveal follows the row that took + /// its place. + NewTail { viewport: &'a str, key: &'a str }, + /// A user or explicit scroll ends every request that would pull the view back. + Cancel, + /// An explicit destination wins over a reveal for its whole lifetime; holds stay. + Destination, +} + +/// What placing a reveal asks of its viewport. +#[derive(Debug, PartialEq)] +pub(in crate::runtime) enum Effect { Rest, Move(f64) } + +/// A fold starts opening: the keeps on its viewport above its end give way. `index` is a path's +/// position in the commit's nodes. +pub(in crate::runtime) struct FoldOpens<'a, I> { pub viewport: &'a str, pub end: usize, pub index: I } + +/// Folds nearly shut have left their viewports' ends to take over: a keep holding one of the +/// `giving` headers on a `pinned` viewport gives way. +pub(in crate::runtime) struct EndTakesOver<'a, P> { pub giving: &'a [&'a String], pub pinned: P } + +/// Where a keep's element shows, for [`EndClamps`]. +pub(in crate::runtime) enum Shown { + /// Not in the tree: the keep waits for it. + Unmounted, + /// In the tree with no vertical viewport around it. + Loose, + /// In a viewport that isn't pinned to its end. + Free, + /// This far below the top of a viewport pinned to its end. + Pinned(f32), +} + +/// A frame followed its keeps: one the content's end pushed down, or that lost its viewport, +/// gives way to stick-bottom. +pub(in crate::runtime) struct EndClamps<F> { pub shown: F } + +/// A frame ended: keeps last while their viewport's subtree moves, reveals while their viewport +/// glides or moves with their target mounted in it. +pub(in crate::runtime) struct Finish<G, A, M> { pub gliding: G, pub animating: A, pub mounted: M } + +/// Anything [`Requests::step`] takes. +pub(in crate::runtime) trait Transition { + fn apply(self, requests: &mut Requests) -> Effects<Effect>; +} + +impl Requests { + pub fn is_empty(&self) -> bool { self.keeps.is_empty() && self.reveals.is_empty() } + pub fn has_keeps(&self) -> bool { !self.keeps.is_empty() } + pub fn keeps(&self) -> impl Iterator<Item = &Keep> { self.keeps.iter() } + pub fn keeps_mut(&mut self) -> impl Iterator<Item = &mut Keep> { self.keeps.iter_mut() } + pub fn reveals(&self) -> impl Iterator<Item = &Reveal> { self.reveals.iter() } + + /// Keeps some request, of either kind, holds `path` back. + pub fn owns(&self, path: &str) -> bool { + self.keeps.iter().any(|k| k.viewport == path) || self.reveals.iter().any(|r| r.viewport == path) + } + + /// Lifts the keeps out for the nested commit that remounts virtual rows, which sees no + /// holds and leaves the reveals in place. No allocation, as no buffer moves. + pub fn take_keeps(&mut self) -> Vec<Keep> { + std::mem::take(&mut self.keeps) + } + + pub fn restore_keeps(&mut self, keeps: Vec<Keep>) { + self.keeps = keeps; + } + + fn arrive(&mut self, request: Request) { + match request { + Request::Capture(k) => { + self.keeps.retain(|old| old.viewport != k.viewport); + self.reveals.retain(|old| old.viewport != k.viewport); + self.keeps.push(k); + } + Request::FoldAnchor(k) => { + self.keeps.retain(|old| old.viewport != k.viewport); + self.keeps.push(k); + } + Request::Reveal(r) => { + self.reveals.retain(|old| old.viewport != r.viewport); + self.reveals.push(r); + } + } + } + + pub fn step(&mut self, event: impl Transition) -> Effects<Effect> { + event.apply(self) + } +} + +impl Transition for Event<'_> { + #[inline(always)] + fn apply(self, requests: &mut Requests) -> Effects<Effect> { + match self { + Event::Arrive(request) => requests.arrive(request), + Event::Place { first, scope, key, viewport, center, at_end, from, to } => { + if first { + requests.arrive(Request::Reveal(Reveal { scope: scope.map(str::to_owned), + key: key.to_owned(), viewport: viewport.to_owned(), center, at_end })); + } else if let Some(r) = requests.reveals.iter_mut().find(|r| r.viewport == viewport) { + r.at_end |= at_end; + } + if (to - from).abs() < 0.5 { + if first { return Effects::one(Effect::Rest); } + } else { return Effects::one(Effect::Move(to)); } + } + Event::NewTail { viewport, key } => { + if let Some(r) = requests.reveals.iter_mut().find(|r| r.viewport == viewport && r.at_end) { + r.scope = None; + r.key = key.to_owned(); + } + } + Event::Cancel => { requests.keeps.clear(); requests.reveals.clear(); } + Event::Destination => requests.reveals.clear(), + } + Effects::none() + } +} + +impl<I: Fn(&str) -> Option<usize>> Transition for FoldOpens<'_, I> { + fn apply(self, requests: &mut Requests) -> Effects<Effect> { + let Self { viewport, end, index } = self; + requests.keeps.retain(|k| k.viewport != viewport || index(&k.path).is_none_or(|i| i >= end)); + Effects::none() + } +} + +impl<P: Fn(&str) -> bool> Transition for EndTakesOver<'_, P> { + fn apply(self, requests: &mut Requests) -> Effects<Effect> { + let Self { giving, pinned } = self; + requests.keeps.retain(|k| !(k.hold.as_ref().is_some_and(|h| giving.contains(&&h.path)) && pinned(&k.viewport))); + Effects::none() + } +} + +impl<F: Fn(&Keep) -> Shown> Transition for EndClamps<F> { + fn apply(self, requests: &mut Requests) -> Effects<Effect> { + requests.keeps.retain(|k| match (self.shown)(k) { + Shown::Loose => false, + Shown::Pinned(top) if top > k.was + 0.5 => false, + _ => true, + }); + Effects::none() + } +} + +impl<G, A, M> Transition for Finish<G, A, M> +where G: Fn(&str) -> bool, A: Fn(&str) -> bool, M: Fn(&Reveal) -> bool { + fn apply(self, requests: &mut Requests) -> Effects<Effect> { + let Self { gliding, animating, mounted } = self; + requests.keeps.retain(|k| animating(&k.viewport)); + requests.reveals.retain(|r| gliding(&r.viewport) || (animating(&r.viewport) && mounted(r))); + Effects::none() + } +} + +impl RuntimeCore { + /// Resolve reveals and destinations against the tree from the update that requested them. + pub(in crate::runtime) fn finish_scroll_requests(&mut self, app: &mut dyn AppDriver, tx: &mut Tx, follow: bool) { + let destination = !tx.scroll_bottom.is_empty() || !tx.scroll_pages.is_empty() || !tx.scroll_offsets.is_empty(); + if tx.scroll_to.is_empty() && !destination && !follow { return; } + self.drop_scroll_holds(); + for r in tx.scroll_to.drain(..) { self.reveal_row(app, &r, tx.commit.snaps()); } + if !destination && !follow { return; } + self.step_scroll(0.0); + if follow { self.follow_caret(app); } + if tx.commit.snaps() { + for (_, animated) in &mut tx.scroll_bottom { *animated = false; } + for r in &mut tx.scroll_offsets { r.glide = None; } + } + if !tx.scroll_bottom.is_empty() { self.scroll_to_bottom(app, std::mem::take(&mut tx.scroll_bottom)); } + if !tx.scroll_pages.is_empty() { self.scroll_pages(app, std::mem::take(&mut tx.scroll_pages)); } + if !tx.scroll_offsets.is_empty() { self.scroll_to_offsets(app, std::mem::take(&mut tx.scroll_offsets)); } + if destination { self.scroll.requests.step(Event::Destination); } + } +} + +#[cfg(test)] +#[path = "requests_tests.rs"] +mod tests; diff --git a/app/vendor/rune/crates/rune/src/runtime/scroll/requests_tests.rs b/app/vendor/rune/crates/rune/src/runtime/scroll/requests_tests.rs new file mode 100644 index 0000000..93070bf --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/scroll/requests_tests.rs @@ -0,0 +1,190 @@ +use super::super::sticky::{Hold, Keep}; +use super::*; + +/// What a frame measured about the keeps' elements: the one element in the tree, whether a +/// viewport surrounds it, whether that viewport is pinned, and how far down it was drawn. +#[derive(Clone, Copy, Debug)] +struct Scene { mounted: Option<&'static str>, viewport: bool, pinned: bool, top: f32 } + +#[derive(Clone, Copy, Debug)] +enum Input { + CaptureKey { viewport: &'static str, virtualized: bool, header: Option<&'static str> }, Fold, + FoldOpen { viewport: &'static str, mounted: Option<&'static str>, end: usize }, + Place { viewport: &'static str, first: bool, to: f64, at_end: bool }, Tail, + EndGives { header: &'static str, pinned: &'static str }, EndClamp(Scene), + Frame { glide: &'static str, moving: &'static str, mounted: bool }, InputScroll, Destination, +} +use Input::*; + +#[derive(Clone, Debug, Default, PartialEq)] +struct Old { + keeps: Vec<OldKeep>, + scroll_reveals: Vec<OldReveal>, +} +#[derive(Clone, Debug, PartialEq)] +struct OldKeep { path: String, viewport: String, was: f32, virtual_row: Option<(String, String, f32)>, hold: Option<(String, f32)> } +#[derive(Clone, Debug, PartialEq)] +struct OldReveal { viewport: String, scope: Option<String>, key: String, center: bool, at_end: bool } + +#[derive(Debug, PartialEq)] +enum Placement { None, Rest, Move(f64) } + +// The old fields and mutations, independent of the request machine. The placement event +// supplies the already measured offset, just as reveal_row_once did after clamping it. +impl Old { + fn apply(&mut self, input: Input) -> Placement { + match input { + CaptureKey { viewport, virtualized, header } => { + self.keeps.retain(|k| k.viewport != viewport); + self.scroll_reveals.retain(|r| r.viewport != viewport); + let row = virtualized.then(|| ("list".into(), "row".into(), 3.0)); + self.keeps.push(OldKeep { path: "item".into(), viewport: viewport.into(), was: 7.0, virtual_row: row, + hold: header.map(|h| (h.into(), 1.0)) }); + } + Fold => { + self.keeps.retain(|k| k.viewport != "a"); + self.keeps.push(OldKeep { path: "below".into(), viewport: "a".into(), was: 7.0, virtual_row: None, hold: None }); + } + // fold_hold.rs: a fold opening. + FoldOpen { viewport, mounted, end } => { + let nodes = ["root", mounted.unwrap_or("absent")]; + self.keeps.retain(|k| k.viewport != viewport || nodes.iter().position(|n| *n == k.path).is_none_or(|i| i >= end)); + } + Place { viewport, first, to, at_end } => { + if first { + self.scroll_reveals.retain(|r| r.viewport != viewport); + self.scroll_reveals.push(OldReveal { viewport: viewport.into(), scope: Some("scope".into()), + key: "mark".into(), center: viewport == "a", at_end }); + } else if let Some(r) = self.scroll_reveals.iter_mut().find(|r| r.viewport == viewport) { + r.at_end |= at_end; + } + if (to - 5.0).abs() < 0.5 { + if first { return Placement::Rest; } + return Placement::None; + } + return Placement::Move(to); + } + Tail => if let Some(r) = self.scroll_reveals.iter_mut().find(|r| r.viewport == "a" && r.at_end) { + r.scope = None; + r.key = "new".into(); + }, + // fold_hold.rs: end_takes_over. + EndGives { header, pinned: on } => { + let header = header.to_string(); + let giving: Vec<&String> = vec![&header]; + let pinned = |viewport: &str| viewport == on; + let drop: Vec<usize> = self.keeps.iter().enumerate() + .filter(|(_, k)| k.hold.as_ref().is_some_and(|h| giving.contains(&&h.0)) && pinned(&k.viewport)).map(|(i, _)| i).collect(); + for i in drop.into_iter().rev() { self.keeps.remove(i); } + } + // sticky.rs: the end of follow_keeps. + EndClamp(Scene { mounted, viewport, pinned, top }) => { + let nodes = [mounted.unwrap_or("absent"), "viewport"]; + let drawn = [top, 0.0]; + let viewport_of = |_: usize| viewport.then_some(1); + let scrolls = [(1, pinned)]; + let mut keeps = std::mem::take(&mut self.keeps); + keeps.retain(|k| { + let Some(i) = nodes.iter().position(|n| *n == k.path) else { return true }; + let Some(s) = viewport_of(i) else { return false }; + !(scrolls.iter().find(|st| st.0 == s).is_some_and(|st| st.1) + && drawn[i] - drawn[s] > k.was + 0.5) + }); + self.keeps = keeps; + } + Frame { glide, moving, mounted } => { + if self.keeps.is_empty() && self.scroll_reveals.is_empty() { return Placement::None; } + let animating = |viewport: &str| viewport == moving; + let gliding = |viewport: &str| viewport == glide; + self.keeps.retain(|k| animating(&k.viewport)); + self.scroll_reveals.retain(|r| gliding(&r.viewport) || (animating(&r.viewport) && mounted)); + } + InputScroll => { self.keeps.clear(); self.scroll_reveals.clear(); } + Destination => self.scroll_reveals.clear(), + } + Placement::None + } +} + +fn drive(requests: &mut Requests, input: Input) -> Placement { + let anchor = |v: &str, p: &str, header: Option<&str>| Keep { path: p.into(), viewport: v.into(), was: 7.0, virtual_row: None, + hold: header.map(|h| Hold { path: h.into(), inset: 1.0 }) }; + let effects = match input { + CaptureKey { viewport, virtualized, header } => requests.step(Event::Arrive(Request::Capture(Keep { virtual_row: + virtualized.then(|| ("list".into(), "row".into(), 3.0)), ..anchor(viewport, "item", header) }))), + Fold => requests.step(Event::Arrive(Request::FoldAnchor(anchor("a", "below", None)))), + FoldOpen { viewport, mounted, end } => requests.step(FoldOpens { viewport, end, + index: |path: &str| (Some(path) == mounted).then_some(1) }), + Place { viewport, first, to, at_end } => requests.step(Event::Place { viewport, scope: Some("scope"), + key: "mark", center: viewport == "a", first, at_end, from: 5.0, to }), + Tail => requests.step(Event::NewTail { viewport: "a", key: "new" }), + EndGives { header, pinned } => requests.step(EndTakesOver { giving: &[&header.to_string()], + pinned: |v: &str| v == pinned }), + EndClamp(Scene { mounted, viewport, pinned, top }) => requests.step(EndClamps { shown: |k: &Keep| { + if mounted != Some(k.path.as_str()) { Shown::Unmounted } + else if !viewport { Shown::Loose } + else if !pinned { Shown::Free } + else { Shown::Pinned(top) } + } }), + Frame { glide, moving, mounted } => requests.step(Finish { gliding: |v: &str| v == glide, + animating: |v: &str| v == moving, mounted: |_: &Reveal| mounted }), + InputScroll => requests.step(Event::Cancel), + Destination => requests.step(Event::Destination), + }; + match effects { + Effects::None => Placement::None, Effects::One(Effect::Rest) => Placement::Rest, + Effects::One(Effect::Move(to)) => Placement::Move(to), _ => panic!("unexpected placements"), + } +} + +fn walk(inputs: &[Input], old: &Old, real: &Requests, sequence: &mut Vec<Input>) { + if sequence.len() == 5 { return; } + for &input in inputs { + sequence.push(input); + let (mut old, mut real) = (old.clone(), real.clone()); + assert_eq!(drive(&mut real, input), old.apply(input), "{sequence:?}"); + let snapshot = Old { keeps: real.keeps().map(|k| OldKeep { path: k.path.clone(), viewport: k.viewport.clone(), + was: k.was, virtual_row: k.virtual_row.clone(), hold: k.hold.as_ref().map(|h| (h.path.clone(), h.inset)) }).collect(), + scroll_reveals: real.reveals().map(|r| OldReveal { viewport: r.viewport.clone(), scope: r.scope.clone(), + key: r.key.clone(), center: r.center, at_end: r.at_end }).collect() }; + assert_eq!(snapshot, old, "{sequence:?}"); + walk(inputs, &old, &real, sequence); + sequence.pop(); + } +} + +const HELD_A: Input = CaptureKey { viewport: "a", virtualized: false, header: Some("header") }; +const PINNED_PAST: Scene = Scene { mounted: Some("below"), viewport: true, pinned: true, top: 7.75 }; + +#[test] +fn every_request_sequence_matches_the_separate_keep_and_reveal_lists() { + const INPUTS: &[Input] = &[HELD_A, CaptureKey { viewport: "b", virtualized: true, header: Some("header") }, Fold, + Place { viewport: "a", first: true, to: 4.5, at_end: false }, + Place { viewport: "b", first: true, to: 5.25, at_end: true }, + Place { viewport: "a", first: false, to: 5.0, at_end: true }, Tail, + EndGives { header: "header", pinned: "a" }, EndClamp(PINNED_PAST), + Frame { glide: "b", moving: "", mounted: false }, Frame { glide: "", moving: "a", mounted: false }, + Frame { glide: "", moving: "a", mounted: true }, Frame { glide: "a", moving: "b", mounted: true }, + InputScroll, Destination]; + walk(INPUTS, &Old::default(), &Requests::default(), &mut Vec::new()); +} + +/// Each release condition, on anchors that must stay and anchors that must go. +#[test] +fn every_keep_release_matches_the_old_conditions() { + const INPUTS: &[Input] = &[HELD_A, CaptureKey { viewport: "a", virtualized: false, header: None }, + CaptureKey { viewport: "b", virtualized: false, header: Some("header") }, Fold, + Place { viewport: "a", first: true, to: 4.5, at_end: false }, + EndGives { header: "header", pinned: "a" }, EndGives { header: "header", pinned: "" }, + EndGives { header: "other", pinned: "a" }, + EndClamp(Scene { mounted: None, viewport: true, pinned: true, top: 9.0 }), + EndClamp(Scene { mounted: Some("item"), viewport: false, pinned: false, top: 7.0 }), + EndClamp(Scene { mounted: Some("item"), viewport: true, pinned: false, top: 9.0 }), + EndClamp(Scene { mounted: Some("below"), viewport: true, pinned: true, top: 7.5 }), + EndClamp(PINNED_PAST), + FoldOpen { viewport: "a", mounted: Some("item"), end: 2 }, + FoldOpen { viewport: "a", mounted: Some("item"), end: 1 }, + FoldOpen { viewport: "a", mounted: None, end: 2 }, + FoldOpen { viewport: "b", mounted: Some("item"), end: 2 }]; + walk(INPUTS, &Old::default(), &Requests::default(), &mut Vec::new()); +} diff --git a/app/vendor/rune/crates/rune/src/runtime/scroll/reveal.rs b/app/vendor/rune/crates/rune/src/runtime/scroll/reveal.rs new file mode 100644 index 0000000..5b2f876 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/scroll/reveal.rs @@ -0,0 +1,182 @@ +//! `Tx::scroll_into_view` and `Tx::scroll_center`: revealing or centring a keyed element, +//! virtual row or `TextHighlight` inside its scroll viewport. +use super::*; + +/// One `Tx::scroll_into_view` or `Tx::scroll_center` request. +#[derive(Clone, Debug)] +pub(crate) struct ScrollReveal { + pub scope: Option<String>, + pub key: String, + /// Centre the target vertically rather than scroll it just into view. + pub center: bool, + /// Glide there on the scroll spring rather than jump. + pub animated: bool, +} + +impl ScrollReveal { + pub fn into_view(scope: Option<String>, key: String) -> Self { + ScrollReveal { scope, key, center: false, animated: false } + } + + pub fn center(scope: Option<String>, key: String, animated: bool) -> Self { + ScrollReveal { scope, key, center: true, animated } + } +} + +/// The offset that centres `[top, top + height)` in the viewport, or that scrolls it into view +/// from `offset`, before clamping. +pub(in crate::runtime) fn place(center: bool, offset: f64, top: f64, height: f64, viewport: f64, margin: f64) -> f64 { + if center { + (top - ((viewport - height) * 0.5).max(0.0)).max(0.0) + } else { + scroll_edge::reveal(offset, top, height, viewport, margin) + } +} + +impl RuntimeCore { + /// Scrolls so row or highlight `r.key` shows, or sits centred when `r.center`. A virtual row + /// placed by estimates may measure differently once mounted, along with the rows around it, + /// so this places it again from what the commit measured until it stays put. Those commits + /// are `instant` when the request's was, or when it glides: the glide then starts back + /// where the viewport stood and runs to that place, keeping the speed of one already running. + pub(in crate::runtime) fn reveal_row(&mut self, app: &mut dyn AppDriver, r: &ScrollReveal, instant: bool) { + let (scope, key) = (r.scope.as_deref(), r.key.as_str()); + let glide = r.animated && !instant && !self.reduced_motion && !self.settled; + let (mut window, was) = self.reveal_row_once(app, scope, key, r.center, true, instant || glide); + for _ in 0..8 { + if !window { break; } + window = self.reveal_row_once(app, scope, key, r.center, false, instant || glide).0; + } + if glide && let Some(Was { id, offset: start, glide: v, viewport }) = was + && let Some(st) = self.scroll.scrolls.get_mut(&id) + && (st.offset - start).abs() > 0.5 + { + // A long trip cuts to a couple of viewports out first, as `Tx::scroll_to` does. + let end = st.offset; + let reach = scroll_bottom::GLIDE_REACH * viewport; + st.offset = start.clamp(end - reach, end + reach); + st.mode = st.mode.to_glide(scroll_offset::retarget_v(crate::tok::motion::GLIDE, st.offset, v.unwrap_or(0.0), end), GlideTo::Offset(end)); + st.spring = None; + st.moved(); + if self.virtual_window_changed() { + self.commit(app, &Tx { commit: Commit::Instant, ..Tx::default() }); + } + } + self.reveal_row_x(scope, key); + } + + /// One placement of [`Self::reveal_row`]: whether it committed, and on the first, where the + /// viewport stood before. After the first, it moves only when the row would land somewhere + /// else. + fn reveal_row_once(&mut self, app: &mut dyn AppDriver, scope: Option<&str>, key: &str, center: bool, first: bool, instant: bool) -> (bool, Option<Was>) { + let target_node = self.live_named(scope, key) + .map(|i| (i, self.tree.nodes[i].target[1], self.tree.nodes[i].local.h, true)) + .or_else(|| { + let (i, [_, y0, _, y1]) = self.highlight_target_in(&self.tree.nodes, scope, key)?; + (!self.subtree_exiting(i)).then_some((i, y0, (y1 - y0).max(0.0), false)) + }); + let geometry = target_node.and_then(|(i, target_top, target_h, is_whole_node)| { + let s = self.viewport_of(i)?; + let parent = &self.tree.nodes[s]; + let (laid_top, laid_h) = (target_top - parent.target[1], target_h); + let (top, height) = std::iter::successors(Some(i), |&p| self.tree.nodes[p].parent) + .take_while(|&p| p != s) + .find_map(|r| { + let c = self.tree.nodes[r].parent?; + self.tree.nodes[c].growth.as_ref()?; + let stack = self.motion.stacks.get(&self.tree.nodes[c].id)?; + let rid = self.tree.nodes[r].id; + let mut count = 0usize; + let before_r: f32 = stack.order.iter() + .take_while(|&&id| id != rid) + .filter_map(|id| self.motion.grows.get(id)) + .map(|g| { count += 1; g.h }) + .sum::<f32>() + stack.gap * count as f32; + let r_top = (self.tree.nodes[c].target[1] - parent.target[1]) + stack.pad_top + before_r; + let r_h = self.motion.grows.get(&rid).map_or(self.tree.nodes[r].local.h, |g| g.h); + if i == r && is_whole_node { + Some((r_top, r_h)) + } else { + let in_row = target_top - self.tree.nodes[r].target[1]; + Some((r_top + in_row, target_h)) + } + }) + .unwrap_or((laid_top, laid_h)); + let laid_end = self.scroll_children(s).map(|c| self.tree.nodes[c].target[3] - parent.target[1]).reduce(f32::max).unwrap_or(0.0); + Some((parent.path.clone(), f64::from(top), f64::from(height), f64::from(parent.local.h), f64::from(laid_top), f64::from(laid_h), f64::from(laid_end))) + }).or_else(|| { + self.tree.nodes.iter().filter(|n| in_scope(&n.path, scope)).filter_map(|n| { + let v = self.commit.virtuals.get(&n.path)?; + let index = v.index_of(key).or_else(|| { + key.rmatch_indices('/').find_map(|(at, _)| { + let (scope, row_key) = (&key[..at], &key[at + 1..]); + let mut keyed = n.path.rsplit('/').filter(|seg| !seg.starts_with('#')); + scope.rsplit('/').all(|seg| keyed.next() == Some(seg)).then(|| v.index_of(row_key))? + }) + }).or_else(|| { + // `"row/mark"` names an element or highlight inside unmounted row `row`. + key.match_indices('/').find_map(|(at, _)| v.index_of(&key[..at])) + })?; + let row_key = &v.keys[index]; + let top = f64::from(v.top + v.pad_top + v.prefix(index)); + let height = f64::from(v.height(row_key)); + let end = f64::from(v.top + v.pad_top + v.prefix(v.keys.len()) + v.pad_bottom); + Some((v.scroll_path.clone(), top, height, f64::from(v.viewport), top, height, end)) + }).next() + }); + let Some((path, top, height, viewport, laid_top, laid_h, laid_end)) = geometry else { return (false, None) }; + // Stuck headers cover the viewport's top: land the row below them. + let Some(cover) = self.stuck_cover(&path, key) else { return (false, None) }; + let (top, height) = (top - cover, height + cover); + let (laid_top, laid_h) = (laid_top - cover, laid_h + cover); + let margin = self.node(&path).map_or(0.0, |n| f64::from(n.scroll_edges.margin)); + let Some(&id) = self.tree.path_ids.get(&path) else { return (false, None) }; + let Some(&s_idx) = self.tree.node_index.get(&id) else { return (false, None) }; + let stick = self.tree.nodes[s_idx].scroll.is_some_and(|s| s.stick_bottom); + let max = self.scroll_overflow(s_idx).max(0.0); + let Some(scroll) = self.scroll.scrolls.get_mut(&id) else { return (false, None) }; + let was = first.then_some(Was { id, offset: scroll.offset, glide: scroll.glide(), viewport }); + scroll.max = max; + if first { scroll.halt(); } + let offset = place(center, scroll.offset, top, height, viewport, margin).clamp(0.0, scroll.max); + let laid_max = (laid_end - viewport).max(0.0); + let laid_to = place(center, scroll.offset, laid_top, laid_h, viewport, margin).clamp(0.0, laid_max); + let at_end = stick && (scroll.pinned() || offset >= scroll.max - 0.5) && laid_to >= laid_max - 0.5; + let effects = self.scroll.requests.step(requests::Event::Place { first, scope, key, viewport: &path, + center, at_end, from: scroll.offset, to: offset }); + let Some(effect) = effects.into_iter().next() else { return (false, was) }; + match effect { + requests::Effect::Move(to) => { + scroll.offset = to; + scroll.mode = scroll.mode.to_rest(); + scroll.moved(); + } + requests::Effect::Rest => { + scroll.mode = scroll.mode.to_rest(); + return (false, was); + } + } + let window = self.virtual_window_changed(); + if window { + self.commit(app, &Tx { commit: if instant { Commit::Instant } else { Commit::Animate }, ..Tx::default() }); + // The commit measured rows that were estimates: the next placement clamps to the end + // they make. + if let Some(i) = self.tree.nodes.iter().position(|n| n.id == id) { + let max = self.scroll_overflow(i).max(0.0); + if let Some(scroll) = self.scroll.scrolls.get_mut(&id) { + scroll.max = max; + scroll.mode = scroll.mode.to_rest(); + } + } + } + (window, was) + } +} + +/// Where a reveal's viewport stood before it moved, for the glide that follows. +struct Was { + id: NodeId, + offset: f64, + glide: Option<f32>, + viewport: f64, +} diff --git a/app/vendor/rune/crates/rune/src/runtime/scroll/sticky.rs b/app/vendor/rune/crates/rune/src/runtime/scroll/sticky.rs new file mode 100644 index 0000000..6fcab36 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/scroll/sticky.rs @@ -0,0 +1,496 @@ +//! `El::sticky_top`, `El::sticky_bottom` and `El::sticky_left`: elements held to an edge of +//! their scroll viewport while their parent is in view (CSS `position: sticky`), and +//! `Tx::keep_on_screen`, which holds an element where it shows across a commit. +//! +//! The shift is worked out in the paint pass from the offsets that frame applies, so a stuck +//! header never trails a scroll. Layout is untouched: only drawing, hit testing and what tools +//! read move. A sticky element paints after its siblings (`update_layer_paint_order`). +use super::*; +use crate::el::StickyEdge; + +/// No viewport band and no parent box: nothing to stick within. +pub(in crate::runtime) const UNBOUNDED: [f32; 8] = [f32::NEG_INFINITY, f32::INFINITY, f32::NEG_INFINITY, f32::INFINITY, f32::NEG_INFINITY, f32::INFINITY, f32::NEG_INFINITY, f32::INFINITY]; + +/// Points of shift over which `El::stuck_shadow` fades in. +pub(in crate::runtime) const SHADOW_RAMP: f32 = 8.0; + +/// One `Tx::keep_on_screen` anchor captured before a commit. +#[derive(Clone)] +pub(in crate::runtime) struct Keep { + pub path: String, + pub viewport: String, + pub was: f32, + /// When the element lives inside a virtual row: `(virtual_list_path, row_key, y_in_row)`. + pub virtual_row: Option<(String, String, f32)>, + /// The element, or the header it's in, was stuck to the top: it stays there for the commit. + pub hold: Option<Hold>, +} + +/// A header stuck to the top when a `Tx::keep_on_screen` commit started. Until the motion +/// settles it sticks `inset` points below its viewport's top whether or not it's still sticky, +/// bounded by the bottom of the growth row it's drawn in rather than its parent's new layout, so +/// the rows under it fold up to it before the scroll moves, on the same frame. +#[derive(Clone)] +pub(in crate::runtime) struct Hold { + pub path: String, + pub inset: f32, +} + +/// One `Tx::scroll_into_view` or `Tx::scroll_center` request that follows its target while the +/// viewport's subtree moves. +#[derive(Clone)] +pub(in crate::runtime) struct Reveal { + pub scope: Option<String>, + pub key: String, + pub viewport: String, + pub center: bool, + /// Whether this reveal lands at the bottom of a `stick_bottom` viewport. + pub at_end: bool, +} + +/// Node `i`'s drawn top below viewport `s`'s top, in unscaled viewport points. +pub(in crate::runtime) fn keep_y(drawn: &[[f32; 4]], drawn_scale: &[f32], i: usize, s: usize) -> f32 { + let scale = drawn_scale.get(s).copied().unwrap_or(1.0).max(1e-4); + (drawn[i][1] - drawn[s][1]) / scale +} + +/// The nearest vertical scroll viewport around node `i` of `nodes`. +fn vertical_viewport(nodes: &[Node], i: usize) -> Option<usize> { + std::iter::successors(nodes[i].parent, |&p| nodes[p].parent) + .find(|&p| nodes[p].scroll.is_some() && nodes[p].scroll_axes.y()) +} + +/// How far a sticky box with edges `top`, `bottom`, `left` and `right` moves from where +/// scrolling put it, along the edge's axis. `frame` holds its viewport's top and bottom, then +/// its parent's content box top and bottom, then the same four for the horizontal axis. +pub(in crate::runtime) fn shift(edge: StickyEdge, inset: f32, [top, bottom, left, right]: [f32; 4], frame: [f32; 8]) -> f32 { + let [band_top, band_bottom, box_top, box_bottom, band_left, _, _, box_right] = frame; + let d = match edge { + StickyEdge::Left => (band_left + inset - left).min(box_right - right).max(0.0), + StickyEdge::Top => (band_top + inset - top).min(box_bottom - bottom).max(0.0), + StickyEdge::Bottom => (band_bottom - inset - bottom).max(box_top - top).min(0.0), + }; + if d.is_finite() { d } else { 0.0 } +} + +/// Target rect of node `j` after its scroll viewports' offsets and any sticky shift on `j` or +/// its ancestors, for `El::anchored`. +pub(in crate::runtime) fn anchored_target(nodes: &[Node], scrolls: &HashMap<NodeId, ScrollState>, j: usize, viewport: (f32, f32)) -> [f32; 4] { + let mut t = nodes[j].target; + for [ox, oy] in scroll_offsets(scrolls, nodes, j) { + t[0] -= ox; + t[2] -= ox; + t[1] -= oy; + t[3] -= oy; + } + let [mut dx, mut dy] = target_shift(nodes, scrolls, j); + if let Some(anc) = std::iter::successors(Some(j), |&p| nodes[p].parent).find(|&p| nodes[p].above.is_some()) + && let Some(a) = &nodes[anc].above + && let Some(k) = super::anchor_index(nodes, anc, a) + { + let at = anchored_target(nodes, scrolls, k, viewport); + let (w, h) = (nodes[anc].target[2] - nodes[anc].target[0], nodes[anc].target[3] - nodes[anc].target[1]); + let (ax, ay) = super::anchor_position(a, at, (w, h), viewport); + dx += ax - nodes[anc].target[0]; + dy += ay - nodes[anc].target[1]; + } + t[0] += dx; + t[2] += dx; + t[1] += dy; + t[3] += dy; + t +} + +/// Total sticky shift `[dx, dy]` on node `j` and its ancestors from `nodes`'s laid-out rects and +/// `scrolls`. +fn target_shift(nodes: &[Node], scrolls: &HashMap<NodeId, ScrollState>, j: usize) -> [f32; 2] { + let mut total = [0.0; 2]; + for a in std::iter::successors(Some(j), |&p| nodes[p].parent.filter(|_| nodes[p].above.is_none())) { + let Some((edge, inset, tail)) = nodes[a].sticky.as_ref().and_then(|s| Some((s.edge?, s.inset, s.tail))) else { continue }; + let Some(p) = nodes[a].parent else { continue }; + if edge == StickyEdge::Left { + let Some(s) = std::iter::successors(Some(p), |&u| nodes[u].parent) + .find(|&u| nodes[u].scroll.is_some() && nodes[u].scroll_axes.x()) else { continue }; + let ox: f32 = std::iter::successors(Some(p), |&u| nodes[u].parent) + .take_while(|&u| u != s) + .chain(std::iter::once(s)) + .filter_map(|u| scrolls.get(&nodes[u].id).map(|st| st.x.shift() as f32)) + .sum(); + let st_x = nodes[s].target[0]; + let band_w = nodes[s].target[2] - st_x; + let (box_left, box_right) = if p == s { + (f32::NEG_INFINITY, f32::INFINITY) + } else { + (nodes[p].target[0] - st_x - ox + nodes[p].inset[0], nodes[p].target[2] - st_x - ox - nodes[p].inset[2]) + }; + let left = nodes[a].target[0] - st_x - ox; + let right = nodes[a].target[2] - st_x - ox; + let frame = [f32::NEG_INFINITY, f32::INFINITY, f32::NEG_INFINITY, f32::INFINITY, 0.0, band_w, box_left, box_right]; + total[0] += shift(edge, inset, [0.0, 0.0, left, right], frame); + } else { + let Some(s) = std::iter::successors(Some(p), |&u| nodes[u].parent) + .find(|&u| nodes[u].scroll.is_some() && nodes[u].scroll_axes.y()) else { continue }; + let oy: f32 = std::iter::successors(Some(p), |&u| nodes[u].parent) + .take_while(|&u| u != s) + .chain(std::iter::once(s)) + .filter_map(|u| scrolls.get(&nodes[u].id).map(|st| st.offset as f32)) + .sum(); + let st_y = nodes[s].target[1]; + let band_h = nodes[s].target[3] - st_y; + let (box_top, box_bottom) = if p == s { + (f32::NEG_INFINITY, f32::INFINITY) + } else { + (nodes[p].target[1] - st_y - oy + nodes[p].inset[1], nodes[p].target[3] - st_y - oy - nodes[p].inset[3]) + }; + let top = nodes[a].target[1] - st_y - oy; + let bottom = nodes[a].target[3] - st_y - oy; + let frame = [0.0, band_h, box_top, box_bottom, f32::NEG_INFINITY, f32::INFINITY, f32::NEG_INFINITY, f32::INFINITY]; + total[1] += shift(edge, if tail { inset - (bottom - top) } else { inset }, [top, bottom, 0.0, 0.0], frame); + } + } + total +} + +impl requests::ScrollTables { + /// Node `i`, or the header holding it, if it's drawn stuck to the top of viewport `s`. + pub(super) fn stuck_header(&self, nodes: &[Node], has_sticky: bool, i: usize, s: usize) -> Option<usize> { + if !has_sticky || self.stuck.len() != nodes.len() { return None; } + std::iter::successors(Some(i), |&p| nodes[p].parent) + .take_while(|&p| p != s) + .find(|&h| self.stuck[h] > 0.0 && self.sticky_of(nodes, h).is_some_and(|(edge, ..)| edge == StickyEdge::Top)) + } + + /// Node `i`'s sticky edge, inset and whether the inset counts from its bottom: a `Hold`'s, + /// else its own. + #[inline] + pub(in crate::runtime) fn sticky_of(&self, nodes: &[Node], i: usize) -> Option<(StickyEdge, f32, bool)> { + if let Some(h) = self.hold_of(&nodes[i].path) { return Some((StickyEdge::Top, h.inset, false)); } + nodes[i].sticky.as_ref().and_then(|s| Some((s.edge?, s.inset, s.tail))) + } +} + +impl RuntimeCore { + /// Replay just one inherited fade edge without the nearest viewport's content-aware + /// fade. Explicit clips inside it and fades outside it still apply. Recursion follows + /// parents already painted this frame and needs no scratch allocation. + pub(in crate::runtime) fn sticky_fade(&self, i: usize, viewport: usize, slot: usize, paint: bool) -> (f32, f32) { + if i == viewport { + let up = self.tree.nodes[i].parent.map_or(Inh::default(), |p| self.paint.inh_scratch[p]); + return if paint { (up.paint_fade[slot], up.paint_fade_origin[slot]) } + else { (up.fade[slot], up.fade_origin[slot]) }; + } + let n = &self.tree.nodes[i]; + let (width, origin) = self.sticky_fade(n.parent.unwrap(), viewport, slot, paint); + let mut widths = [0.0; 4]; + let mut origins = NO_CLIP; + widths[slot] = width; + origins[slot] = origin; + let r = self.paint.drawn[i].map(|v| v * self.env.scale); + let r = [r[0], r[1], r[0] + r[2], r[1] + r[3]]; + if let Some(clip) = n.vis.clip { + inherit_fade(&mut widths, &mut origins, r, clip.map(|v| (v * self.paint.inh_scratch[i].scale * self.env.scale).clamp(-65504.0, 65504.0))); + } + if self.paint.row_mask[i] >= 0.0 { + inherit_fade(&mut widths, &mut origins, r, [0.0, 0.0, 0.0, self.growth_feather(i)]); + } + // An isolation layer already consumed the parent's paint fade. Its descendants + // must not apply that same fade a second time. + if paint && self.paint.inh_scratch[i].paint_fade[slot] == 0.0 { return (0.0, NO_CLIP[slot]); } + (widths[slot], origins[slot]) + } + + /// The nearest vertical scroll viewport around node `i`. + pub(in crate::runtime) fn viewport_of(&self, i: usize) -> Option<usize> { + vertical_viewport(&self.tree.nodes, i) + } + + /// Records where each `Tx::keep_on_screen` element showed on the last frame, before the + /// commit moves it. + pub(in crate::runtime) fn capture_keeps(&mut self, tx: &mut Tx) { + self.anchor_keeps(tx); + if tx.keep_on_screen.is_empty() { return; } + let keys = std::mem::take(&mut tx.keep_on_screen); + // The last frame's rects describe these nodes only until a commit replaces them. + if !self.tree.built || self.paint.drawn.len() != self.tree.nodes.len() { return; } + for key in keys { + let Some(i) = self.live_named(None, &key) else { continue }; + let Some(s) = self.viewport_of(i) else { continue }; + let hold = self.scroll.stuck_header(&self.tree.nodes, self.tree.has_sticky, i, s).map(|h| Hold { + path: self.tree.nodes[h].path.clone(), + inset: keep_y(&self.paint.drawn, &self.paint.drawn_scale, h, s), + }); + let virtual_row = std::iter::successors(Some(i), |&p| self.tree.nodes[p].parent) + .take_while(|&p| p != s) + .find_map(|r| { + let c = self.tree.nodes[r].parent?; + self.commit.virtuals.contains_key(&self.tree.nodes[c].path).then(|| ( + self.tree.nodes[c].path.clone(), + self.tree.nodes[r].key.clone().unwrap_or_default(), + self.tree.nodes[i].target[1] - self.tree.nodes[r].target[1], + )) + }); + self.scroll.requests.step(requests::Event::Arrive(requests::Request::Capture(Keep { + path: self.tree.nodes[i].path.clone(), + viewport: self.tree.nodes[s].path.clone(), + was: keep_y(&self.paint.drawn, &self.paint.drawn_scale, i, s), + virtual_row, + hold, + }))); + } + } + + /// Whether a `Tx::keep_on_screen` holds a stuck header (`Hold`). + #[inline] + pub(in crate::runtime) fn holding(&self) -> bool { + self.scroll.holding() + } + + /// Node `i`'s sticky edge, inset and whether the inset counts from its bottom: a `Hold`'s, + /// else its own. + #[inline] + pub(in crate::runtime) fn sticky_of(&self, i: usize) -> Option<(StickyEdge, f32, bool)> { + self.scroll.sticky_of(&self.tree.nodes, i) + } + + /// `El::stuck_fade`: how much of node `i`'s children show, drawn with its top at `drawn` + /// (a frame point, `dy` the offset its siblings draw at): whole until the next sticky-top + /// sibling's top comes within `lead + span` of it, gone at `lead`. + pub(in crate::runtime) fn stuck_fade(&self, i: usize, drawn: f32, dy: f32) -> f32 { + let n = &self.tree.nodes[i]; + let Some([lead, span]) = n.sticky.as_ref().and_then(|s| s.fade) else { return 1.0 }; + let next = (i + 1..self.tree.nodes.len()) + .filter(|&j| self.tree.nodes[j].parent == n.parent) + .find(|&j| self.tree.nodes[j].sticky.as_ref().is_some_and(|s| s.edge == Some(StickyEdge::Top))); + let Some(p) = next.and_then(|j| self.scene.presented(self.tree.nodes[j].id).map(|p| (j, p))) else { return 1.0 }; + let (j, p) = p; + let own = self.scene.get(self.tree.nodes[j].id, prop::OFFSET).unwrap_or(rune_motion::Vec2::ZERO); + let top = p.rect.y - own.y + dy + self.paint.row_dy[j] - self.paint.row_dy[i]; + ((top - drawn - lead) / span.max(1e-3)).clamp(0.0, 1.0) + } + + /// The bands and box node `i` sticks within along `edge` (see `shift`), from its ancestors' + /// drawn places this frame, and the viewport it sticks to. + pub(in crate::runtime) fn sticky_frame_of(&self, i: usize, edge: StickyEdge) -> ([f32; 8], Option<usize>) { + let n = &self.tree.nodes[i]; + let mut frame = n.parent.map_or(UNBOUNDED, |pr| self.scroll.sticky_frame[pr]); + let horizontal = edge == StickyEdge::Left; + let mut ancestor = n.parent; + let mut viewport = None; + while let Some(a) = ancestor { + let nd = &self.tree.nodes[a]; + if nd.scroll.is_some() && if horizontal { nd.scroll_axes.x() } else { nd.scroll_axes.y() } { + viewport = Some(a); + break; + } + // A section nested inside a growth row must stop at that row's presented + // bottom, not its descendants' final layout height. Only sticky nodes + // need this ancestor walk; ordinary painting keeps its existing fast path. + if !horizontal && self.paint.row_h[a] >= 0.0 { + frame[2] = frame[2].max(self.scroll.sticky_frame[a][2]); + frame[3] = frame[3].min(self.scroll.sticky_frame[a][3]); + } + ancestor = nd.parent; + } + // A held header's parent may have shrunk in the commit while the growth row it's drawn + // in folds: it stops at that row's drawn bottom, less what the row lays out below the + // parent, so it rests where its parent ends once the row settles. + if !horizontal && self.scroll.hold_of(&n.path).is_some() && let Some(p) = n.parent { + let r = std::iter::successors(Some(p), |&a| self.tree.nodes[a].parent) + .take_while(|&a| Some(a) != viewport) + .find(|&a| self.paint.row_h[a] >= 0.0) + .unwrap_or(p); + let content_bottom = |a: usize| self.tree.nodes[a].target[3] - self.tree.nodes[a].inset[3]; + frame[2] = f32::NEG_INFINITY; + frame[3] = self.scroll.sticky_frame[r][3] - (content_bottom(r) - content_bottom(p)); + } + (frame, viewport) + } + + /// Scrolls each kept element's viewport so the element's top lands where it showed before + /// the commit, clamped to the content, re-pinning a `stick_bottom` end, and remounting any + /// virtual rows the jump brings into view. + pub(in crate::runtime) fn apply_keeps(&mut self, app: &mut dyn AppDriver) { + if !self.scroll.requests.has_keeps() { return; } + let mut keeps = self.scroll.requests.take_keeps(); + for pass in 0..4 { + // Step with the keeps in place: they own their viewports (`ease_to_shrunk_end`). + self.scroll.requests.restore_keeps(keeps); + self.step_scroll(0.0); + keeps = self.scroll.requests.take_keeps(); + let mut moved = false; + for k in &keeps { + let Some(s) = self.tree.nodes.iter().position(|n| n.path == k.viewport && n.scroll.is_some() && n.scroll_axes.y()) else { continue }; + let laid = if let Some(i) = self.tree.nodes.iter().position(|n| n.path == k.path) { + if self.viewport_of(i) != Some(s) { continue; } + if self.scroll_stack(s).and_then(|c| self.motion.stacks.get(&self.tree.nodes[c].id)).is_some_and(|st| st.growing) + && let Some(st) = self.scroll.scrolls.get_mut(&self.tree.nodes[s].id) + { + st.unpin(); + } + // Mounted anchors follow drawn geometry after the motion step. + continue; + } else if let Some((v_path, row_key, in_row)) = &k.virtual_row + && let Some(v) = self.commit.virtuals.get(v_path) + && let Some(idx) = v.index_of(row_key) + { + f64::from(v.top + v.pad_top + v.prefix(idx) + *in_row) + } else { + continue; + }; + let stick = self.tree.nodes[s].scroll.is_some_and(|sc| sc.stick_bottom); + let id = self.tree.nodes[s].id; + let Some(st) = self.scroll.scrolls.get_mut(&id) else { continue }; + st.moved(); + let to = (laid - f64::from(k.was)).clamp(0.0, st.max); + if pass > 0 && (to - st.offset).abs() < 0.5 { continue; } + st.offset = to; + st.keep_land(stick); + moved = true; + } + if !moved || !self.virtual_window_changed() { break; } + self.commit(app, &Tx::default()); + } + self.scroll.requests.restore_keeps(keeps); + } + + /// Compensate this frame's drawn displacement, in viewport coordinates. Sticky + /// clamping may absorb part of a correction; the caller permits a bounded repaint. + pub(in crate::runtime) fn follow_keeps(&mut self) -> bool { + if self.scroll.requests.is_empty() { return false; } + self.end_takes_over(); + let mut moved = false; + for k in self.scroll.requests.keeps() { + let Some(i) = self.tree.nodes.iter().enumerate().position(|(i, n)| n.path == k.path && !self.subtree_exiting(i)) else { continue }; + let Some(s) = self.viewport_of(i).filter(|&s| self.tree.nodes[s].path == k.viewport) else { continue }; + let scale = self.paint.drawn_scale[s]; + if scale <= 1e-4 { continue; } + let delta = (self.paint.drawn[i][1] - self.paint.drawn[s][1]) / scale - k.was; + if delta.abs() < 1.0 / 64.0 { continue; } + let stick = self.tree.nodes[s].scroll.is_some_and(|s| s.stick_bottom); + let Some(st) = self.scroll.scrolls.get_mut(&self.tree.nodes[s].id) else { continue }; + let to = (st.offset + f64::from(delta)).clamp(0.0, st.max); + if (to - st.offset).abs() < 1e-5 { continue; } + st.offset = to; + st.keep_land(stick && delta >= 0.0); + st.moved(); + moved = true; + } + for r in self.scroll.requests.reveals() { + let target = (0..self.tree.nodes.len()).find(|&i| self.reveal_names(r, i)) + .map(|i| (i, self.paint.drawn[i][1], self.paint.drawn[i][3])) + .or_else(|| { + let (i, [_, y0, _, y1]) = self.highlight_target_in(&self.tree.nodes, r.scope.as_deref(), &r.key)?; + if self.subtree_exiting(i) { return None; } + let scale = self.paint.drawn_scale.get(i).copied().unwrap_or(1.0); + let dy = (y0 - self.tree.nodes[i].target[1]) * scale; + Some((i, self.paint.drawn[i][1] + dy, (y1 - y0).max(0.0) * scale)) + }); + let Some((i, drawn_top, drawn_h)) = target else { continue }; + let Some(s) = self.viewport_of(i).filter(|&s| self.tree.nodes[s].path == r.viewport) else { continue }; + let scale = self.paint.drawn_scale[s]; + if scale <= 1e-4 { continue; } + let Some(cover) = self.stuck_cover(&r.viewport, &r.key) else { continue }; + let cover = cover / f64::from(scale); + let rel_top = f64::from((drawn_top - self.paint.drawn[s][1]) / scale) - cover; + let height = f64::from(drawn_h / scale) + cover; + let viewport = f64::from(self.paint.drawn[s][3] / scale); + let margin = f64::from(self.tree.nodes[s].scroll_edges.margin); + let stick = self.tree.nodes[s].scroll.is_some_and(|s| s.stick_bottom); + let growing = self.scroll_stack(s).and_then(|c| self.motion.stacks.get(&self.tree.nodes[c].id)).is_some_and(|st| st.growing); + let Some(st) = self.scroll.scrolls.get_mut(&self.tree.nodes[s].id) else { continue }; + let top = st.offset + rel_top; + let to = reveal::place(r.center, st.offset, top, height, viewport, margin).clamp(0.0, st.max); + // A `Tx::scroll_center` glide follows its target once the target moves. + if let ScrollMode::Glide { v, to: aim, .. } = st.mode { + if aim.offset().is_none_or(|g| (to - g).abs() >= 1.0 / 64.0) { + let aim = if let GlideTo::ShrunkEnd(_) = aim { GlideTo::ShrunkEnd(to) } else { GlideTo::Offset(to) }; + st.mode = st.mode.to_glide(scroll_offset::retarget_v(st.glide_spring(), st.offset, v, to), aim); + } + continue; + } + if (to - st.offset).abs() < 1.0 / 64.0 { + if growing { st.unpin(); } + continue; + } + st.offset = to; + st.keep_land(stick && !growing); + st.moved(); + moved = true; + } + // Once the content end prevents holding the anchor, let stick-bottom own the + // viewport again, including growth committed while the collapse is still settling. + self.scroll.requests.step(requests::EndClamps { shown: |k: &Keep| { + let Some(i) = self.tree.nodes.iter().position(|n| n.path == k.path) else { return requests::Shown::Unmounted }; + let Some(s) = vertical_viewport(&self.tree.nodes, i) else { return requests::Shown::Loose }; + if !self.scroll.scrolls.get(&self.tree.nodes[s].id).is_some_and(|st| st.pinned()) { return requests::Shown::Free; } + requests::Shown::Pinned(keep_y(&self.paint.drawn, &self.paint.drawn_scale, i, s)) + } }); + moved + } + + /// A user or explicit scroll ends the holds and reveals that would pull the view back. + #[inline] + pub(in crate::runtime) fn drop_scroll_holds(&mut self) { + self.scroll.drop_holds(); + } + + /// Colour, hover or decorative motion must not extend the anchor's lifetime. + pub(in crate::runtime) fn finish_keeps(&mut self) { + if self.scroll.requests.is_empty() { return; } + let mut requests = std::mem::take(&mut self.scroll.requests); + let animating = |viewport: &str| self.tree.nodes.iter().any(|n| { + let within = n.path == viewport || (n.path.starts_with(viewport) + && n.path.as_bytes().get(viewport.len()) == Some(&b'/')); + within && (self.scene.store().is_animating(n.id, prop::FRAME) + || self.scene.store().is_animating(n.id, prop::TRAVEL) + || self.motion.grows.get(&n.id).is_some_and(|g| g.moving()) + || self.scroll.scrolls.get(&n.id).is_some_and(|st| st.slack.moving())) + }); + let gliding = |viewport: &str| self.tree.path_ids.get(viewport) + .and_then(|id| self.scroll.scrolls.get(id)) + .is_some_and(|st| st.glide().is_some()); + // A glide keeps its reveal until it lands; otherwise a reveal lasts while its viewport's + // subtree moves with its target in it. + requests.step(requests::Finish { animating, gliding, mounted: |r: &Reveal| self.reveal_mounted(r) }); + self.scroll.requests = requests; + } + + /// Whether node `i` is reveal `r`'s target element. + fn reveal_names(&self, r: &Reveal, i: usize) -> bool { + let n = &self.tree.nodes[i]; + n.named(&r.key) && !self.subtree_exiting(i) + && n.parent.is_none_or(|p| super::in_scope(&self.tree.nodes[p].path, r.scope.as_deref())) + } + + /// Whether reveal `r`'s target element or highlight is mounted in its viewport. + fn reveal_mounted(&self, r: &Reveal) -> bool { + let in_viewport = |i: usize| self.viewport_of(i).is_some_and(|s| self.tree.nodes[s].path == r.viewport); + (0..self.tree.nodes.len()).any(|i| self.reveal_names(r, i) && in_viewport(i)) + || self.highlight_target_in(&self.tree.nodes, r.scope.as_deref(), &r.key) + .is_some_and(|(i, _)| !self.subtree_exiting(i) && in_viewport(i)) + } + + /// What a reveal of row `key` in viewport `path` must leave to stuck headers: `None` when + /// the row is, or is inside, a header stuck in view (it shows already), else the height + /// stuck headers cover at the viewport's top, which the reveal keeps the row clear of. + pub(in crate::runtime) fn stuck_cover(&self, path: &str, key: &str) -> Option<f64> { + if !self.tree.has_sticky || self.scroll.stuck.len() != self.tree.nodes.len() || self.paint.drawn.len() != self.tree.nodes.len() { return Some(0.0) } + let Some(s) = self.tree.nodes.iter().position(|n| n.path == path) else { return Some(0.0) }; + let view = self.paint.drawn[s]; + let row = self.live_named(None, key); + let holder = row.and_then(|r| std::iter::successors(Some(r), |&p| self.tree.nodes[p].parent).take_while(|&p| p != s).find(|&p| self.scroll.stuck[p] != 0.0 && self.tree.nodes[p].sticky.as_ref().is_none_or(|s| s.edge != Some(StickyEdge::Left)))); + if let (Some(r), Some(_)) = (row, holder) { + let d = self.paint.drawn[r]; + if d[1] >= view[1] - 0.5 && d[1] + d[3] <= view[1] + view[3] + 0.5 { return None; } + } + let cover = (0..self.tree.nodes.len()) + .filter(|&j| self.scroll.stuck[j] > 0.0 && self.tree.nodes[j].sticky.as_ref().is_none_or(|s| s.edge != Some(StickyEdge::Left)) && Some(j) != holder && self.viewport_of(j) == Some(s)) + .map(|j| self.paint.drawn[j][1] + self.paint.drawn[j][3] - view[1]) + .fold(0.0f32, f32::max); + Some(f64::from(cover)) + } +} + +#[cfg(test)] +#[path = "sticky_tests.rs"] +mod tests; diff --git a/app/vendor/rune/crates/rune/src/runtime/scroll/sticky_tests.rs b/app/vendor/rune/crates/rune/src/runtime/scroll/sticky_tests.rs new file mode 100644 index 0000000..82bbdcb --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/scroll/sticky_tests.rs @@ -0,0 +1,240 @@ +use super::*; +use crate::{Align, Live, Side, col, el, row}; + +#[derive(Default)] +struct FollowState { + height: f32, + removed: bool, + hidden: bool, + streaming: bool, +} + +fn follow_view(s: &FollowState, _: &mut Cx<FollowState>) -> El { + if s.hidden { return el(); } + let mut stack = col().key("stack").w_full().growth(GrowthSpec::default()) + .child(el().key("lead").w_full().h(400.0)) + .child(el().key("grow").w_full().h(s.height).streaming(s.streaming)); + if !s.removed { stack = stack.child(el().key("tail").w_full().h(35.0)); } + col().key("scroll").size(300.0, 200.0).scroll(ScrollSpec { stick_bottom: true }).child(stack) +} + +fn following(keep: bool) -> Runtime<FollowState> { + let mut rt = Runtime::new(FollowState { height: 37.0, ..Default::default() }, follow_view, (300.0, 200.0), Env::default()); + rt.frame(0.0); + rt.update(move |s, tx| { + s.height = 130.0; + if keep { tx.keep_on_screen("tail"); } else { tx.scroll_into_view("tail"); } + }); + rt.frame(1.0 / 120.0); + rt +} + +fn scroll(rt: &Runtime<FollowState>) -> &ScrollState { + &rt.scroll.scrolls[&rt.node("scroll").unwrap().id] +} + +#[test] +fn completed_reveal_and_keep_repin_the_end_and_go_idle() { + for keep in [false, true] { + let mut rt = following(keep); + if !keep { assert!(!scroll(&rt).pinned()); } + for _ in 0..240 { rt.frame(1.0 / 120.0); } + assert!(rt.scroll.requests.is_empty()); + assert!(!rt.animating); + assert!(scroll(&rt).pinned(), "the completed hold returns the end to stick_bottom"); + rt.update(|s, _| { s.height = 230.0; s.streaming = true; }); + for _ in 0..60 { + rt.frame(1.0 / 120.0); + assert!(scroll(&rt).pinned()); + assert!((scroll(&rt).offset - scroll(&rt).max).abs() < 0.05); + } + } +} + +#[test] +fn all_scroll_input_and_later_destinations_cancel_a_reveal() { + for input in 0..5 { + let mut rt = following(false); + assert!(rt.scroll.requests.reveals().next().is_some()); + match input { + 0 => rt.wheel_xy(100.0, 100.0, 0.0, 50.0), + 1 => { let i = rt.tree.node_index[&rt.node("scroll").unwrap().id]; rt.page_to(i, |_, _, _| 0.0); } + 2 => rt.wheel(100.0, 100.0, 50.0), + 3 => rt.fling(100.0, 100.0, 100.0), + _ => rt.update(|_, tx| { tx.scroll_into_view("tail"); tx.scroll_to_y("scroll", 0.0); }), + } + if input != 4 { assert!(rt.scroll.requests.reveals().next().is_none(), "input {input} cancels at arrival, even before wheel dispatch"); } + rt.frame(1.0 / 120.0); + assert!(rt.scroll.requests.reveals().next().is_none(), "input {input} cancels the reveal"); + let offset = scroll(&rt).offset; + if input != 3 { + for _ in 0..60 { rt.frame(1.0 / 120.0); } + assert!((scroll(&rt).offset - offset).abs() < 0.05, "no reveal fights input {input}"); + } + } +} + +#[test] +fn a_missing_reveal_target_or_viewport_is_pruned_during_other_growth() { + for hidden in [false, true] { + let mut rt = following(false); + rt.update(move |s, _| { s.removed = true; s.hidden = hidden; s.height = 300.0; }); + rt.frame(1.0 / 120.0); + assert!(rt.scroll.requests.reveals().next().is_none(), "missing targets must not wait for unrelated growth"); + for _ in 0..240 { rt.frame(1.0 / 120.0); } + assert!(!rt.animating); + } +} + +#[test] +fn instant_only_overrides_scroll_requests_in_that_commit() { + let mut rt = Runtime::new(FollowState { height: 37.0, ..Default::default() }, follow_view, (300.0, 200.0), Env::default()); + rt.frame(0.0); + rt.update(|_, tx| tx.scroll_to("scroll", 0.0, 0.0)); + rt.frame(1.0 / 120.0); + assert!(scroll(&rt).glide_to().is_some()); + rt.update(|_, tx| tx.instant()); + rt.frame(1.0 / 120.0); + assert!(scroll(&rt).glide_to().is_some(), "an unrelated instant commit leaves an existing glide alone"); + rt.update(|_, tx| { tx.instant(); tx.scroll_to("scroll", 0.0, 100.0); }); + rt.frame(1.0 / 120.0); + assert!(scroll(&rt).glide_to().is_none()); + assert!((scroll(&rt).offset - 100.0).abs() < 0.05); + rt.update(|_, tx| { tx.instant(); tx.scroll_to_bottom("scroll"); }); + rt.frame(1.0 / 120.0); + assert!(scroll(&rt).glide().is_none()); + assert!((scroll(&rt).offset - scroll(&rt).max).abs() < 0.05); +} + +#[test] +fn revealing_an_already_visible_row_stops_a_running_glide() { + let mut rt = Runtime::new(FollowState { height: 37.0, ..Default::default() }, follow_view, (300.0, 200.0), Env::default()); + rt.frame(0.0); + rt.update(|_, tx| tx.scroll_to("scroll", 0.0, 0.0)); + rt.frame(0.0); + assert!(scroll(&rt).glide_to().is_some()); + rt.update(|_, tx| tx.scroll_into_view("tail")); + rt.frame(1.0 / 120.0); + assert!(scroll(&rt).glide().is_none() && scroll(&rt).glide_to().is_none()); + assert!((scroll(&rt).offset - scroll(&rt).max).abs() < 0.05); + assert!(!rt.animating); +} + +#[test] +fn revealing_another_viewport_does_not_move_a_virtual_reading_anchor() { + fn view(_: &[f32; 2], _: &mut Cx<[f32; 2]>) -> El { + row().size(600.0, 200.0).children((0..2).map(|list| { + col().key(format!("scroll{list}")).size(300.0, 200.0).scroll(ScrollSpec { stick_bottom: false }) + .child(col().key(format!("stack{list}")).w_full().growth(GrowthSpec::default()) + .virtual_rows(12, 50.0, + move |_: &[f32; 2], i| format!("r{list}-{i}").into(), + move |s: &[f32; 2], i| el().w_full().h(if i == 1 { s[list] } else { 50.0 }))) + })) + } + let mut rt = Runtime::new([50.0; 2], view, (600.0, 200.0), Env::default()); + rt.frame(0.0); + rt.update(|_, tx| tx.scroll_to_y("scroll1", 150.0)); + for _ in 0..30 { rt.frame(1.0 / 120.0); } + let y = |rt: &Runtime<[f32; 2]>| rt.elements().into_iter().find(|e| e.key.as_deref() == Some("r1-3")).unwrap().rect[1]; + let was = y(&rt); + for height in [100.0, 30.0] { + rt.update(move |s, tx| { s[1] = height; tx.scroll_into_view("r0-4"); }); + for _ in 0..60 { + rt.frame(1.0 / 120.0); + assert!((y(&rt) - was).abs() < 0.05, "the reader's row moved after height {height}: {} vs {was}", y(&rt)); + } + } +} + +#[test] +fn sticky_left_holds_a_header_to_the_viewport_while_content_scrolls_sideways() { + struct S { + pressed: usize, + offset: Live<[f32; 2]>, + } + fn view(s: &S, _: &mut Cx<S>) -> El { + col().size(300.0, 200.0) + .child(col().key("scroll").size(300.0, 200.0).scroll(ScrollSpec { stick_bottom: false }).scroll_xy() + .child(col().key("content").min_w(1000.0) + .child(row().key("header").w(300.0).h(30.0).justify_end().items_center().fill(Color::WHITE).sticky_left(0.0) + .live_offset(&s.offset) + .child(el().key("action").size(40.0, 20.0).focusable(true).help("Run action").on_press(|s: &mut S| s.pressed += 1))) + .child(el().w_full().h(600.0)))) + .child(el().key("pop").size(50.0, 20.0).anchored("action", Side::Bottom, Align::End, 0.0)) + } + let mut rt = Runtime::new(S { pressed: 0, offset: Live::new([0.0, 0.0]) }, view, (300.0, 200.0), Env::default()); + rt.frame(0.0); + rt.wheel_xy(100.0, 100.0, -250.0, 0.0); + for _ in 0..60 { rt.frame(1.0 / 60.0); } + let els = rt.elements(); + let h = els.iter().find(|e| e.key.as_deref() == Some("header")).unwrap(); + assert_eq!(h.rect[0], 0.0); + assert_eq!(h.stuck, 250.0); + + // A control at the trailing end of the shifted header is clickable, focusable and anchors + // overlays and tooltips at its shifted viewport coordinates. + let action = els.iter().find(|e| e.key.as_deref() == Some("action")).unwrap(); + assert_eq!(action.rect, [260.0, 5.0, 40.0, 20.0]); + let pop = els.iter().find(|e| e.key.as_deref() == Some("pop")).unwrap(); + assert_eq!(pop.rect[0], 242.0, "anchored overlay follows sticky_left shift (kept 8pt inside viewport)"); + + rt.pointer_move(280.0, 15.0); + rt.frame(0.0); + rt.frame(rt.help_delay); + assert!(rt.help_tooltip().is_some(), "tooltip shows on shifted sticky_left child"); + rt.pointer_down(280.0, 15.0); + rt.pointer_up(280.0, 15.0); + rt.frame(0.0); + assert_eq!(rt.state.pressed, 1, "shifted header action takes press after sideways scroll"); + + // `live_offset` on a sticky_left element translates from the stuck position rather than + // being clamped away by the sticky edge. + rt.state.offset.set([-12.0, 4.0]); + rt.frame(0.0); + let h = rt.elements().into_iter().find(|e| e.key.as_deref() == Some("header")).unwrap(); + assert_eq!((h.rect[0], h.rect[1], h.stuck), (-12.0, 4.0, 250.0)); +} + +#[test] +fn sticky_left_inside_nested_scrollers_moves_vertically_and_stops_at_parent_right() { + fn view(_: &(), _: &mut Cx<()>) -> El { + col().key("vscroll").size(300.0, 200.0).scroll(ScrollSpec { stick_bottom: false }) + .child(col().w_full() + .child(el().w_full().h(50.0)) + .child(col().key("hscroll").w(300.0).h(100.0).scroll(ScrollSpec { stick_bottom: false }).scroll_x() + .child(row().key("band").w(500.0).h(40.0).pr(20.0) + .child(el().key("pin").w(100.0).h(40.0).sticky_left(10.0)))) + .child(el().w_full().h(400.0))) + } + let mut rt = Runtime::new((), view, (300.0, 200.0), Env::default()); + rt.frame(0.0); + // Scroll horizontally inside `hscroll` and vertically in `vscroll`. + rt.wheel_xy(150.0, 80.0, -120.0, 0.0); + rt.wheel(150.0, 80.0, -30.0); + for _ in 0..60 { rt.frame(1.0 / 60.0); } + let pin = rt.elements().into_iter().find(|e| e.key.as_deref() == Some("pin")).unwrap(); + assert_eq!(pin.rect[0], 10.0, "held at inset from horizontal viewport's left"); + assert_eq!(pin.rect[1], 20.0, "scrolled vertically with its outer row"); + assert_eq!(pin.stuck, 130.0); +} + +#[test] +fn cached_section_with_sticky_descendant_stays_live_on_scroll() { + fn view(_: &(), _: &mut Cx<()>) -> El { + col().key("scroll").size(300.0, 200.0).scroll(ScrollSpec { stick_bottom: false }).scroll_xy() + .child(col().key("cached").w_full().cache() + .child(el().key("header").w_full().h(30.0).fill(Color::WHITE).sticky_top(0.0)) + .child(el().key("left").w(300.0).h(30.0).fill(Color::WHITE).sticky_left(0.0)) + .child(el().w_full().h(600.0))) + } + let mut rt = Runtime::new((), view, (300.0, 200.0), Env::default()); + rt.frame(0.0); + rt.wheel_xy(100.0, 100.0, -80.0, -100.0); + rt.frame(0.0); + let cached = rt.tree.nodes.iter().position(|n| n.key.as_deref() == Some("cached")).unwrap(); + assert!(rt.paint.cache_live_scratch[cached], "sticky contents must not reuse a frozen raster"); + assert!(!rt.paint.node_caches.contains_key(&rt.tree.nodes[cached].id)); + let h = rt.elements().into_iter().find(|e| e.key.as_deref() == Some("header")).unwrap(); + assert_eq!(h.rect[1], 0.0); + assert_eq!(h.stuck, 100.0); +} diff --git a/app/vendor/rune/crates/rune/src/runtime/scroll/touch.rs b/app/vendor/rune/crates/rune/src/runtime/scroll/touch.rs new file mode 100644 index 0000000..64381ef --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/scroll/touch.rs @@ -0,0 +1,275 @@ +//! Touch scrolling: a finger pans the scroll viewport under it, rubber-bands past its ends, +//! and flings it on with momentum, on every platform that reports touches (`runtime/input/touch.rs` +//! turns touches into presses, drags and these pans). +use super::*; +use crate::machine::Effects; +use crate::runtime::scroll_mode::{self as mode, Event as ModeEvent}; + +/// What a touch holds: the viewport its finger went down on, one it pans, or one it let go +/// that is still settling. +#[derive(Clone, Copy, Debug, PartialEq)] +pub(in crate::runtime) enum TouchScroll { + /// The finger is down on this viewport, before its pan picks an axis. `origin` is the + /// offset it holds it at. + Held { id: NodeId, origin: f64, horizontal: bool }, + /// The finger pans this viewport from `origin`, the offset it caught it at. + Dragging { id: NodeId, origin: f64, horizontal: bool }, + /// The finger let go; the viewport settles on its own momentum or edge return. + Coasting { id: NodeId, horizontal: bool }, +} + +impl TouchScroll { + /// The viewport it holds. + fn id(self) -> NodeId { + match self { + Self::Held { id, .. } | Self::Dragging { id, .. } | Self::Coasting { id, .. } => id, + } + } + + /// Whether it moves the viewport's horizontal axis (`El::scroll_x`). + fn horizontal(self) -> bool { + match self { + Self::Held { horizontal, .. } | Self::Dragging { horizontal, .. } | Self::Coasting { horizontal, .. } => horizontal, + } + } + + /// The offset the finger holds or caught the viewport at, while it has it. + fn origin(self) -> Option<f64> { + match self { + Self::Held { origin, .. } | Self::Dragging { origin, .. } => Some(origin), + Self::Coasting { .. } => None, + } + } + + /// Whether the finger has let go and the viewport settles on its own. + fn coasting(self) -> bool { + matches!(self, Self::Coasting { .. }) + } +} + +/// What happens to a touch's pan. +#[derive(Clone, Copy, Debug)] +pub(in crate::runtime) enum TouchEvent { + /// A finger went down: `across` is the horizontal viewport under it and `vertical` the + /// vertical one, each with its current offset. + Down { across: Option<(NodeId, f64)>, vertical: Option<(NodeId, f64)> }, + /// The finger started panning, mostly horizontally or not. + Pan { horizontal: bool, across: Option<(NodeId, f64)>, vertical: Option<(NodeId, f64)> }, + /// The finger lifted from `id` with `velocity` along its axis. + Up { id: Option<NodeId>, velocity: f32 }, + /// The finger moved `d` points from the offset it caught the viewport at. + Move { id: NodeId, d: f32 }, + /// A frame for the viewport's panned axis: its overflow bounds and the frame's time. + Tick { id: NodeId, horizontal: bool, overflow: f64, dt: f32 }, + /// A settling viewport is still moving (`true`) or has come to rest (`false`). + Settled { moving: bool }, +} + +/// What carrying out a transition does to the scroll viewports. +#[derive(Clone, Copy, Debug, PartialEq)] +pub(in crate::runtime) enum TouchEffect { + /// Stop this viewport's momentum. + Halt(NodeId), + /// Stop this viewport's horizontal momentum: a touch landed across it. + StopAcross(NodeId), + /// Give this viewport the lifted finger's velocity along its axis. + Fling { id: NodeId, horizontal: bool, velocity: f32 }, + /// Move this viewport `d` points from the offset the finger caught it at. + Pan { id: NodeId, origin: f64, horizontal: bool, d: f32 }, + /// A frame while the finger holds this viewport: set its pane's bounds to `overflow`. + Hold { id: NodeId, horizontal: bool, overflow: f64 }, + /// A frame while the viewport coasts: step its momentum and edge return by `dt`. + Coast { id: NodeId, horizontal: bool, overflow: f64, dt: f32 }, +} + +/// The pan's next state, and what to do to the viewports. A finger holds the viewport it +/// went down on until its pan picks an axis, drags it from the offset it caught it at, then +/// lets it coast until it comes to rest. +pub(in crate::runtime) fn step(state: &mut Option<TouchScroll>, event: TouchEvent) -> Effects<TouchEffect> { + match (*state, event) { + (current, TouchEvent::Down { across, vertical }) => { + let caught = matches!((current, across), (Some(t), Some((id, _))) if t.horizontal() && t.id() == id); + if caught { + *state = across.map(|(id, at)| TouchScroll::Held { id, origin: at, horizontal: true }); + } else if let Some((id, at)) = vertical { + *state = Some(TouchScroll::Held { id, origin: at, horizontal: false }); + } + let mut effects = Effects::none(); + if let Some((id, _)) = across { + effects.push(TouchEffect::StopAcross(id)); + } + if let Some((id, _)) = vertical { + effects.push(TouchEffect::Halt(id)); + } + effects + } + (_, TouchEvent::Pan { horizontal: true, across: Some((id, at)), .. }) => { + *state = Some(TouchScroll::Dragging { id, origin: at, horizontal: true }); + Effects::none() + } + (Some(t), TouchEvent::Pan { vertical: Some((id, at)), .. }) => { + // A horizontal viewport the touch caught lets go, and the vertical one takes the pan. + let origin = if t.horizontal() { at } else { t.origin().unwrap_or(at) }; + *state = Some(TouchScroll::Dragging { id, origin, horizontal: false }); + Effects::none() + } + (Some(t), TouchEvent::Pan { .. }) if t.horizontal() => { + *state = Some(TouchScroll::Coasting { id: t.id(), horizontal: true }); + Effects::none() + } + (_, TouchEvent::Pan { .. }) => Effects::none(), + (Some(t), TouchEvent::Up { id, velocity }) => { + *state = Some(TouchScroll::Coasting { id: t.id(), horizontal: t.horizontal() }); + if Some(t.id()) == id { + Effects::one(TouchEffect::Fling { id: t.id(), horizontal: t.horizontal(), velocity }) + } else { + Effects::none() + } + } + (Some(TouchScroll::Dragging { id: held, origin, horizontal }), TouchEvent::Move { id, d }) if held == id => { + Effects::one(TouchEffect::Pan { id, origin, horizontal, d }) + } + (Some(t), TouchEvent::Tick { id, horizontal, overflow, dt }) if t.id() == id && t.horizontal() == horizontal => { + if t.coasting() { + Effects::one(TouchEffect::Coast { id, horizontal, overflow, dt }) + } else { + Effects::one(TouchEffect::Hold { id, horizontal, overflow }) + } + } + (Some(t), TouchEvent::Settled { moving: false }) if t.coasting() => { + *state = None; + Effects::none() + } + (_, _) => Effects::none(), + } +} + +/// A critically damped edge return, integrated exactly for variable frame times. +fn rebound(offset: f64, velocity: f32, target: f64, dt: f32) -> (f64, f32) { + let dt = f64::from(dt); + let displacement = offset - target; + let b = f64::from(velocity) + 14.0 * displacement; + let decay = (-14.0 * dt).exp(); + (target + (displacement + b * dt) * decay, ((f64::from(velocity) - 14.0 * b * dt) * decay) as f32) +} + +impl RuntimeCore { + /// A touch went down: it stops the momentum of the viewports under it and holds the + /// vertical one until the pan picks its axis (`touch_scroll_pan`). A horizontal one still + /// settling from an earlier touch (momentum or its edge return) holds where the finger + /// caught it instead. + pub(in crate::runtime) fn touch_scroll_start(&mut self, x: f32, y: f32) -> Option<NodeId> { + let across = self.scroll_at_axis(x, y, true).and_then(|id| self.scroll.scrolls.get(&id).map(|st| (id, st.x.offset))); + let vertical = self.scroll_at(x, y); + let held = vertical.and_then(|id| self.scroll.scrolls.get(&id).map(|st| (id, st.offset))); + self.step_touch(TouchEvent::Down { across, vertical: held }); + vertical + } + + /// The touch that went down at (x, y) started panning, mostly horizontally or not: a + /// horizontal pan takes the innermost horizontal viewport there, and any other pan stays + /// with the vertical one. Returns the viewport and whether it moves horizontally. + pub(in crate::runtime) fn touch_scroll_pan(&mut self, x: f32, y: f32, horizontal: bool, vertical: Option<NodeId>) -> (Option<NodeId>, bool) { + let across = horizontal + .then(|| self.scroll_at_axis(x, y, true)) + .flatten() + .and_then(|id| self.scroll.scrolls.get(&id).map(|st| (id, st.x.offset))); + let held = vertical.and_then(|id| self.scroll.scrolls.get(&id).map(|st| (id, st.offset))); + self.step_touch(TouchEvent::Pan { horizontal, across, vertical: held }); + match across { + Some((id, _)) => (Some(id), true), + None => (vertical, false), + } + } + + /// The pan moved `d` points along its axis from where the touch went down. + pub(in crate::runtime) fn touch_scroll_move(&mut self, id: NodeId, d: f32) { + self.step_touch(TouchEvent::Move { id, d }); + } + + /// The touch lifted from viewport `id` (None when it held none) with `velocity` along its + /// axis. Whatever it held lets go, a viewport it caught without panning included. + pub(in crate::runtime) fn touch_scroll_end(&mut self, id: Option<NodeId>, velocity: f32) { + self.step_touch(TouchEvent::Up { id, velocity }); + } + + /// Own the touched viewport's panned axis through momentum and its edge return. Other + /// viewports use the native wheel path, including native clamping and stick-to-bottom. + pub(in crate::runtime) fn step_touch_scroll(&mut self, id: NodeId, overflow: f64, dt: f32, horizontal: bool) -> Option<bool> { + let effects = step(self.pointer.touch_scroll_mut(), TouchEvent::Tick { id, horizontal, overflow, dt }); + self.apply_touch(effects) + } + + /// Step the pan and carry out what the transition asked for. + fn step_touch(&mut self, event: TouchEvent) { + let effects = step(self.pointer.touch_scroll_mut(), event); + let _ = self.apply_touch(effects); + } + + /// Carry out what a touch transition asked for on the scroll viewports: the drag's and the + /// coast's math lives here, and a coast reports whether its viewport is still moving. + fn apply_touch(&mut self, effects: Effects<TouchEffect>) -> Option<bool> { + let mut active = None; + for effect in effects { + match effect { + TouchEffect::Halt(id) => { + if let Some(st) = self.scroll.scrolls.get_mut(&id) { st.halt(); } + } + TouchEffect::StopAcross(id) => { + if let Some(st) = self.scroll.scrolls.get_mut(&id) && matches!(st.x.motion, XMotion::Momentum(_) | XMotion::Wheel(_)) { st.x.motion = XMotion::Rest; } + } + TouchEffect::Fling { id, horizontal, velocity } => { + let Some(st) = self.scroll.scrolls.get_mut(&id) else { continue }; + let v = f64::from(velocity.clamp(-8000.0, 8000.0)); + if horizontal { st.x.set_coast(st.x.toward(v) as f32) } else { st.mode = st.mode.to_momentum(-v as f32) } + } + TouchEffect::Pan { id, origin, horizontal, d } => { + let Some(st) = self.scroll.scrolls.get_mut(&id) else { continue }; + let toward = if horizontal { st.x.toward(f64::from(d)) } else { -f64::from(d) }; + let (offset, max) = st.axis(horizontal); + let to = origin + toward; + let edge = to.clamp(0.0, max); + let over = to - edge; + *offset = edge + over * 0.55 / (1.0 + over.abs() * 0.55 / 300.0); + if !horizontal { st.mode = st.mode.to_rest(); } + st.moved(); + self.pointer.scroll_cancels_press(&self.tree.nodes, id); + } + TouchEffect::Hold { id, horizontal, overflow } => { + let Some(st) = self.scroll.scrolls.get_mut(&id) else { continue }; + if horizontal { st.x.max = overflow.max(0.0); } else { st.max = overflow.max(0.0); } + let _ = mode::step(&mut st.mode, ModeEvent::Hold); + active = Some(false); + } + TouchEffect::Coast { id, horizontal, overflow, dt } => { + let moving = { + let Some(st) = self.scroll.scrolls.get_mut(&id) else { continue }; + if horizontal { st.x.max = overflow.max(0.0); } else { st.max = overflow.max(0.0); } + let mut v = if horizontal { st.x.coast() } else { st.coast() }; + let _ = mode::step(&mut st.mode, ModeEvent::Coast { moving: v.abs() > 1.0 }); + let (offset, max) = st.axis(horizontal); + let edge = offset.clamp(0.0, max); + if *offset != edge { + (*offset, v) = rebound(*offset, v, edge, dt); + if (*offset - edge).abs() < 0.1 && v.abs() < 1.0 { *offset = edge; v = 0.0; } + } else { + let decay = (-SCROLL_DECAY * dt).exp(); + *offset += f64::from(v * (1.0 - decay) / SCROLL_DECAY); + v *= decay; + } + let moving = v.abs() > 1.0 || *offset < 0.0 || *offset > max; + if horizontal { st.x.set_coast(v); } else if v != 0.0 { st.mode = st.mode.to_momentum(v); } else { st.halt(); } + moving + }; + self.step_touch(TouchEvent::Settled { moving }); + active = Some(moving); + } + } + } + active + } +} + +#[cfg(test)] +#[path = "touch_tests.rs"] +mod tests; diff --git a/app/vendor/rune/crates/rune/src/runtime/scroll/touch_tests.rs b/app/vendor/rune/crates/rune/src/runtime/scroll/touch_tests.rs new file mode 100644 index 0000000..80fa472 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/scroll/touch_tests.rs @@ -0,0 +1,164 @@ +use super::*; + +#[test] +fn a_touch_pan_moves_the_axis_its_first_direction_picks() { + fn view(_: &(), _: &mut Cx<()>) -> El { + let tiles = (0..10).fold(crate::row(), |r, i| r.child(crate::el().key(format!("tile{i}")).w(100.0).h(100.0))); + let rows = (0..20).fold(crate::col().w_full().child(crate::col().key("strip").w_full().h(100.0).scroll_x().child(tiles)), + |c, i| c.child(crate::el().key(format!("row{i}")).w_full().h(40.0))); + crate::col().w_full().h_full().child(crate::col().key("page").w_full().h(300.0) + .scroll(crate::ScrollSpec { stick_bottom: false }).child(rows)) + } + let mut rt = Runtime::new((), view, (300.0, 300.0), Env::default()); + rt.frame(0.0); + let id = |rt: &Runtime<()>, key: &str| rt.tree.nodes.iter().find(|n| n.key.as_deref() == Some(key)).unwrap().id; + let (page, strip) = (id(&rt, "page"), id(&rt, "strip")); + + let vertical = rt.touch_scroll_start(150.0, 50.0); + assert_eq!(vertical, Some(page)); + assert_eq!(rt.touch_scroll_pan(150.0, 50.0, true, vertical), (Some(strip), true)); + rt.touch_scroll_move(strip, -50.0); + assert_eq!((rt.scroll.scrolls[&strip].x.offset, rt.scroll.scrolls[&page].offset), (50.0, 0.0)); + rt.touch_scroll_end(Some(strip), 0.0); + + // A vertical pan over the strip passes through to the page. + let vertical = rt.touch_scroll_start(150.0, 50.0); + assert_eq!(rt.touch_scroll_pan(150.0, 50.0, false, vertical), (Some(page), false)); + rt.touch_scroll_move(page, -30.0); + assert_eq!((rt.scroll.scrolls[&strip].x.offset, rt.scroll.scrolls[&page].offset), (50.0, 30.0)); + rt.touch_scroll_end(Some(page), 0.0); + + // A touch on the strip while it springs back past its left edge holds it there, until a + // tap lets it go or a sideways pan carries on from where it was caught. + let held = |rt: &Runtime<()>| rt.pointer.touch_scroll().map(|t| (t.id(), t.horizontal(), !t.coasting(), t.origin())); + rt.scroll.scrolls.get_mut(&strip).unwrap().x.offset = -20.0; + *rt.pointer.touch_scroll_mut() = Some(TouchScroll::Coasting { id: strip, horizontal: true }); + let vertical = rt.touch_scroll_start(150.0, 50.0); + assert_eq!(held(&rt), Some((strip, true, true, Some(-20.0))), "caught, not handed to the page"); + rt.touch_scroll_end(vertical, 0.0); + assert_eq!(held(&rt), Some((strip, true, false, None)), "a tap lets it go back"); + let vertical = rt.touch_scroll_start(150.0, 50.0); + assert_eq!(rt.touch_scroll_pan(150.0, 50.0, true, vertical), (Some(strip), true)); + rt.touch_scroll_move(strip, 10.0); + assert!(rt.scroll.scrolls[&strip].x.offset < -20.0 * 0.55, "still rubber-banding: {}", rt.scroll.scrolls[&strip].x.offset); + rt.touch_scroll_end(Some(strip), 0.0); + + // Caught there, a vertical pan lets the strip go and moves the page. + rt.touch_scroll_start(150.0, 50.0); + assert_eq!(rt.touch_scroll_pan(150.0, 50.0, false, vertical), (Some(page), false)); + assert_eq!(held(&rt).map(|h| (h.0, h.1, h.2)), Some((page, false, true))); +} + +#[test] +fn edge_return_is_frame_rate_independent() { + let one = rebound(-50.0, -400.0, 0.0, 0.5); + let mut many = (-50.0, -400.0); + for _ in 0..60 { many = rebound(many.0, many.1, 0.0, 0.5 / 60.0); } + assert!((one.0 - many.0).abs() < 0.001); + assert!((one.1 - many.1).abs() < 0.01); + assert!(one.0 < 0.0 && one.0 > -1.0); +} + +fn run(state: &mut Option<TouchScroll>, event: TouchEvent) -> Vec<TouchEffect> { + step(state, event).into_iter().collect() +} + +#[test] +fn a_down_holds_the_viewport_under_it_and_stops_its_motion() { + let (page, strip) = (NodeId(1), NodeId(2)); + let mut state = None; + let effects = run(&mut state, TouchEvent::Down { across: Some((strip, 5.0)), vertical: Some((page, 7.0)) }); + assert_eq!(state, Some(TouchScroll::Held { id: page, origin: 7.0, horizontal: false })); + assert_eq!(effects, vec![TouchEffect::StopAcross(strip), TouchEffect::Halt(page)]); + + // A horizontal viewport still settling is caught where the finger lands on it. + let mut state = Some(TouchScroll::Coasting { id: strip, horizontal: true }); + run(&mut state, TouchEvent::Down { across: Some((strip, -20.0)), vertical: Some((page, 7.0)) }); + assert_eq!(state, Some(TouchScroll::Held { id: strip, origin: -20.0, horizontal: true }), "caught, not handed to the page"); + + // A touch outside every viewport leaves the settling one alone. + let mut state = Some(TouchScroll::Coasting { id: strip, horizontal: false }); + run(&mut state, TouchEvent::Down { across: None, vertical: None }); + assert_eq!(state, Some(TouchScroll::Coasting { id: strip, horizontal: false })); +} + +#[test] +fn a_pan_turns_a_held_viewport_into_a_drag_with_the_offset_it_was_caught_at() { + let (page, strip) = (NodeId(1), NodeId(2)); + let mut state = Some(TouchScroll::Held { id: page, origin: 7.0, horizontal: false }); + run(&mut state, TouchEvent::Pan { horizontal: false, across: None, vertical: Some((page, 9.0)) }); + assert_eq!(state, Some(TouchScroll::Dragging { id: page, origin: 7.0, horizontal: false }), "keeps the offset the finger went down at"); + + // A horizontal pan takes the horizontal viewport under the finger, from its offset now. + let mut state = Some(TouchScroll::Held { id: page, origin: 7.0, horizontal: false }); + run(&mut state, TouchEvent::Pan { horizontal: true, across: Some((strip, 4.0)), vertical: Some((page, 9.0)) }); + assert_eq!(state, Some(TouchScroll::Dragging { id: strip, origin: 4.0, horizontal: true })); + + // A finger down on a horizontal viewport with no vertical one still pans it. + let mut state = None; + run(&mut state, TouchEvent::Pan { horizontal: true, across: Some((strip, 4.0)), vertical: None }); + assert_eq!(state, Some(TouchScroll::Dragging { id: strip, origin: 4.0, horizontal: true })); + + // A vertical pan lets a caught horizontal viewport go to the vertical one. + let mut state = Some(TouchScroll::Held { id: strip, origin: -20.0, horizontal: true }); + run(&mut state, TouchEvent::Pan { horizontal: false, across: Some((strip, -20.0)), vertical: Some((page, 9.0)) }); + assert_eq!(state, Some(TouchScroll::Dragging { id: page, origin: 9.0, horizontal: false })); + // With no vertical viewport under it, the horizontal one is left settling. + let mut state = Some(TouchScroll::Held { id: strip, origin: -20.0, horizontal: true }); + run(&mut state, TouchEvent::Pan { horizontal: false, across: None, vertical: None }); + assert_eq!(state, Some(TouchScroll::Coasting { id: strip, horizontal: true })); +} + +#[test] +fn a_lift_starts_the_coast_and_flings_only_the_viewport_it_held() { + let (page, strip) = (NodeId(1), NodeId(2)); + let mut state = Some(TouchScroll::Dragging { id: page, origin: 0.0, horizontal: false }); + let effects = run(&mut state, TouchEvent::Up { id: Some(page), velocity: -1200.0 }); + assert_eq!(state, Some(TouchScroll::Coasting { id: page, horizontal: false })); + assert_eq!(effects, vec![TouchEffect::Fling { id: page, horizontal: false, velocity: -1200.0 }]); + + // A lift from another viewport still lets this one go, without a fling. + let mut state = Some(TouchScroll::Dragging { id: page, origin: 0.0, horizontal: false }); + assert_eq!(run(&mut state, TouchEvent::Up { id: Some(strip), velocity: 0.0 }), vec![]); + assert_eq!(state, Some(TouchScroll::Coasting { id: page, horizontal: false })); +} + +#[test] +fn a_move_and_a_frame_tick_go_through_step() { + let page = NodeId(1); + let mut state = Some(TouchScroll::Dragging { id: page, origin: 5.0, horizontal: false }); + assert_eq!( + run(&mut state, TouchEvent::Move { id: page, d: -30.0 }), + vec![TouchEffect::Pan { id: page, origin: 5.0, horizontal: false, d: -30.0 }] + ); + assert_eq!( + run(&mut state, TouchEvent::Tick { id: page, horizontal: false, overflow: 40.0, dt: 1.0 / 60.0 }), + vec![TouchEffect::Hold { id: page, horizontal: false, overflow: 40.0 }], + "a held viewport only has its bounds set" + ); + let mut state = Some(TouchScroll::Coasting { id: page, horizontal: false }); + assert_eq!( + run(&mut state, TouchEvent::Tick { id: page, horizontal: false, overflow: 40.0, dt: 1.0 / 60.0 }), + vec![TouchEffect::Coast { id: page, horizontal: false, overflow: 40.0, dt: 1.0 / 60.0 }], + "a coasting one is stepped" + ); + + // A move of a viewport the finger no longer drags, or a tick for another axis, asks for nothing. + let mut state = Some(TouchScroll::Held { id: page, origin: 5.0, horizontal: false }); + assert_eq!(run(&mut state, TouchEvent::Move { id: page, d: -30.0 }), vec![]); + assert_eq!(run(&mut state, TouchEvent::Tick { id: page, horizontal: true, overflow: 40.0, dt: 0.1 }), vec![]); +} + +#[test] +fn a_coast_reaches_rest_and_nothing_else_is_cleared() { + let page = NodeId(1); + let mut state = Some(TouchScroll::Coasting { id: page, horizontal: false }); + run(&mut state, TouchEvent::Settled { moving: true }); + assert_eq!(state, Some(TouchScroll::Coasting { id: page, horizontal: false }), "still moving"); + run(&mut state, TouchEvent::Settled { moving: false }); + assert_eq!(state, None, "came to rest"); + + let mut state = Some(TouchScroll::Dragging { id: page, origin: 0.0, horizontal: false }); + run(&mut state, TouchEvent::Settled { moving: false }); + assert_eq!(state, Some(TouchScroll::Dragging { id: page, origin: 0.0, horizontal: false }), "a drag never settles itself"); +} diff --git a/app/vendor/rune/crates/rune/src/runtime/scroll/watch.rs b/app/vendor/rune/crates/rune/src/runtime/scroll/watch.rs new file mode 100644 index 0000000..60ef61c --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/scroll/watch.rs @@ -0,0 +1,103 @@ +//! `El::on_scroll_offset`: telling a scroll viewport's watcher where this frame scrolled it, +//! after the frame's scrolling steps and before it draws, so live values set from it show in +//! the same frame. `El::on_drawn_layout` hears of a move a frame later, and not at all while a +//! glide runs, which is too late for something that rides the scroll. +use super::*; +use crate::machine::Effects; +use crate::runtime::scroll_mode::{self, Event as ModeEvent}; + +thread_local! { + static SCROLL_WATCH_STATE: std::cell::Cell<(bool, bool, f64)> = const { std::cell::Cell::new((false, false, 0.0)) }; +} + +/// Inside an [`El::on_scroll_offset`](crate::El::on_scroll_offset) callback: whether a hand +/// moved this viewport's scroll offset (`scrolled`: the wheel, keys, a drag, their momentum or +/// an app's instant jump, but not following its bottom as content grows, a glide such as +/// `Tx::scroll_to_bottom`, or an anchor holding what's on screen), whether this frame ran an instant or settled +/// commit (`instant`), and the runtime's unscaled clock (`now`, the same clock [`Tx::clock`](crate::Tx::clock) +/// publishes). +#[doc(hidden)] +pub fn scroll_watch_state() -> (bool, bool, f64) { + SCROLL_WATCH_STATE.get() +} + +impl RuntimeCore { + /// Calls each viewport's `on_scroll_offset` whose offset or extent moved, that is new, or + /// whose handler is; true when it called any. + pub(in crate::runtime) fn tell_scroll_offsets(&mut self, instant: bool) -> bool { + let now = self.clock; + let mut calls = Vec::new(); + for n in &self.tree.nodes { + let Some(h) = n.handlers.get() else { continue }; + let Some(f) = h.on_scroll_offset.as_ref() else { continue }; + let Some(st) = self.scroll.scrolls.get_mut(&n.id) else { continue }; + let viewport = [n.local.w, n.local.h]; + // The presented rect is snapped to the pixel grid; only a spring moves it further. + let drawn = self.scene.presented(n.id).map_or(viewport, |p| { + let near = |drawn: f32, target: f32| if (drawn - target).abs() > 0.05 { drawn } else { target }; + [near(p.rect.w, viewport[0]), near(p.rect.h, viewport[1])] + }); + let direction = match n.flow { crate::el::Flow::Ltr => crate::Direction::Ltr, crate::el::Flow::Rtl => crate::Direction::Rtl }; + let at = crate::ScrollPos { offset: [st.x.offset as f32, st.offset as f32 + st.slack.height()], max: [st.x.max as f32, st.max as f32], + viewport, drawn, direction }; + let by_hand = !scroll_mode::step(&mut st.mode, ModeEvent::Take).is_empty(); + for effect in step(&mut st.watch, Event::Seen { at, handler: Some(f), by_hand }) { + let Effect::Tell { at, scrolled } = effect; + calls.push((f.clone(), at, scrolled)); + } + } + for (f, at, scrolled) in &calls { + let prev_ctx = SCROLL_WATCH_STATE.replace((*scrolled, instant, now)); + f(*at); + SCROLL_WATCH_STATE.set(prev_ctx); + } + !calls.is_empty() + } +} + +/// What a viewport's `El::on_scroll_offset` has been told, and which of its handlers heard it. +#[derive(Clone, Debug, Default)] +pub(in crate::runtime) struct Watch { + /// Where the viewport stood when the handler was last told. + told: Option<crate::ScrollPos>, + /// The handler that was told, held weakly: a rebuilt view's new handler hears where the + /// viewport stands, though it didn't move. A weak reference keeps the old handler's + /// allocation alive, so a later handler can't be built at its address and pass for it. + handler: Option<std::rc::Weak<dyn Fn(crate::ScrollPos)>>, +} + +pub(in crate::runtime) enum Event<'a> { + /// The viewport stands at `at`, its handler is `handler` (None when it has none), and a + /// hand or an app's instant jump moved it since the last tell (`by_hand`). + Seen { at: crate::ScrollPos, handler: Option<&'a std::rc::Rc<dyn Fn(crate::ScrollPos)>>, by_hand: bool }, +} + +#[derive(Debug, PartialEq)] +pub(in crate::runtime) enum Effect { + /// Call the handler with `at`; `scrolled` says a hand moved it since the last tell. + Tell { at: crate::ScrollPos, scrolled: bool }, +} + +/// Calls the handler when where the viewport stands changed, or when it is a new one that has +/// not heard it: the effect says what to tell it. +pub(in crate::runtime) fn step(watch: &mut Watch, event: Event<'_>) -> Effects<Effect> { + let Event::Seen { at, handler, by_hand } = event; + let Some(f) = handler else { return Effects::none() }; + let prev = watch.told.replace(at); + let changed = prev != Some(at); + let new_handler = !watch.handler.as_ref().is_some_and(|by| std::ptr::addr_eq(by.as_ptr(), std::rc::Rc::as_ptr(f))); + if new_handler { + watch.handler = Some(std::rc::Rc::downgrade(f)); + } + if !changed && !new_handler { + return Effects::none(); + } + let scrolled = by_hand && prev.is_some_and(|old| { + (old.offset[0] - at.offset[0]).abs() > 0.01 || (old.offset[1] - at.offset[1]).abs() > 0.01 + }); + Effects::one(Effect::Tell { at, scrolled }) +} + +#[cfg(test)] +#[path = "watch_tests.rs"] +mod tests; diff --git a/app/vendor/rune/crates/rune/src/runtime/scroll/watch_tests.rs b/app/vendor/rune/crates/rune/src/runtime/scroll/watch_tests.rs new file mode 100644 index 0000000..aa142d9 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/scroll/watch_tests.rs @@ -0,0 +1,288 @@ +use crate::*; +use std::rc::{Rc, Weak}; +use super::{step, Effect, Event, Watch}; + +thread_local! { static TOLD: std::cell::Cell<ScrollPos> = std::cell::Cell::new(ScrollPos::default()); } + +struct S { + follow: Live<[f32; 2]>, + told: std::rc::Rc<std::cell::Cell<usize>>, +} + +/// A marker outside the viewport that moves up as far as the content scrolls. +fn view(s: &S, _: &mut Cx<S>) -> El { + let (follow, told) = (s.follow.clone(), s.told.clone()); + col().size(300.0, 300.0) + .child(col().key("scroll").size(300.0, 200.0).scroll(ScrollSpec { stick_bottom: false }) + .on_scroll_offset(move |at: ScrollPos| { TOLD.with(|t| t.set(at)); told.set(told.get() + 1); follow.set([0.0, -at.offset[1]]); }) + .child(el().key("content").w_full().h(1000.0))) + .child(el().key("marker").size(10.0, 10.0).live_offset(&s.follow)) +} + +fn y(rt: &Runtime<S>, key: &str) -> f32 { + rt.elements().iter().find(|e| e.key.as_deref() == Some(key)).map(|e| e.rect[1]).unwrap() +} + +fn rig() -> (Runtime<S>, std::rc::Rc<std::cell::Cell<usize>>) { + let told = std::rc::Rc::new(std::cell::Cell::new(0)); + let mut rt = Runtime::new(S { follow: Live::new([0.0, 0.0]), told: told.clone() }, view, (300.0, 300.0), Env::default()); + rt.set_live_waker(std::sync::Arc::new(|| {})); + rt.frame(0.0); + rt.frame(1.0 / 60.0); + (rt, told) +} + +#[test] +fn a_live_value_set_from_the_offset_shows_in_the_frame_that_scrolled() { + let (mut rt, _) = rig(); + let (content0, marker0) = (y(&rt, "content"), y(&rt, "marker")); + for dy in [-7.0, -13.5, -40.0, 22.0, -3.0] { + rt.wheel(100.0, 100.0, dy); + rt.frame(1.0 / 60.0); + assert_eq!(y(&rt, "marker") - marker0, y(&rt, "content") - content0, "after a wheel of {dy}"); + } +} + +#[test] +fn it_follows_every_frame_of_a_glide() { + let (mut rt, _) = rig(); + let (content0, marker0) = (y(&rt, "content"), y(&rt, "marker")); + rt.update(|_, tx| tx.scroll_to("scroll", 0.0, 500.0)); + let mut moved = 0; + for _ in 0..60 { + let before = y(&rt, "content"); + rt.frame(1.0 / 60.0); + moved += usize::from(y(&rt, "content") != before); + assert_eq!(y(&rt, "marker") - marker0, y(&rt, "content") - content0); + } + assert!(moved > 5, "the glide ran over several frames ({moved})"); + assert_eq!(y(&rt, "content") - content0, -500.0); +} + +#[test] +fn it_is_told_at_first_then_only_when_the_offset_moves() { + let (mut rt, told) = rig(); + let first = told.get(); + assert!(first >= 1, "told where it starts"); + for _ in 0..10 { rt.frame(1.0 / 60.0); } + assert_eq!(told.get(), first, "not again while nothing scrolls or rebuilds"); + rt.wheel(100.0, 100.0, -10.0); + rt.frame(1.0 / 60.0); + rt.frame(1.0 / 60.0); + assert_eq!(told.get(), first + 1); + assert_eq!(TOLD.with(|t| t.get()), ScrollPos { offset: [0.0, 10.0], max: [0.0, 800.0], viewport: [300.0, 200.0], drawn: [300.0, 200.0], direction: Direction::Ltr }); +} + +#[test] +fn a_rebuilt_handler_hears_where_the_viewport_stands() { + let (mut rt, told) = rig(); + rt.wheel(100.0, 100.0, -30.0); + rt.frame(1.0 / 60.0); + let before = told.get(); + rt.update(|_, _| {}); + rt.frame(1.0 / 60.0); + assert_eq!(told.get(), before + 1, "the commit told the new handler, though nothing moved"); + assert_eq!(TOLD.with(|t| t.get()).offset, [0.0, 30.0]); + rt.frame(1.0 / 60.0); + assert_eq!(told.get(), before + 1, "and the frame after didn't again"); +} + +#[test] +fn a_live_rect_set_from_the_offset_lands_in_the_frame_that_mounts_it() { + struct On { on: bool, bar: Live<[f32; 4]> } + fn view(s: &On, _: &mut Cx<On>) -> El { + let mut root = col().size(200.0, 100.0); + if s.on { + let bar = s.bar.clone(); + root = root + .child(col().size(200.0, 100.0).scroll(ScrollSpec { stick_bottom: false }) + .on_scroll_offset(move |at: ScrollPos| { bar.set([10.0, 5.0, 6.0, at.max[1] / 10.0]); }) + .child(el().w_full().h(400.0))) + .child(el().key("bar").absolute(0.0, 0.0).live_rect(&s.bar).fill(Color::WHITE)); + } + root + } + let mut rt = Runtime::new(On { on: false, bar: Live::new([0.0; 4]) }, view, (200.0, 100.0), Env::default()); + rt.set_live_waker(std::sync::Arc::new(|| {})); + rt.frame(0.0); + rt.update(|s, tx| { s.on = true; tx.instant(); }); + rt.frame(1.0 / 120.0); + let bar = info(&rt, "bar"); + assert_eq!(bar.rect, [10.0, 5.0, 6.0, 30.0]); + assert!(!bar.moving); +} + +fn info<T>(rt: &Runtime<T>, key: &str) -> ElementInfo { + rt.elements().into_iter().find(|e| e.key.as_deref() == Some(key)).unwrap() +} + +#[test] +fn what_a_glide_carries_knows_how_far() { + let (mut rt, _) = rig(); + let content0 = y(&rt, "content"); + rt.update(|_, tx| tx.scroll_to("scroll", 0.0, 500.0)); + for _ in 0..60 { + rt.frame(1.0 / 60.0); + let c = info(&rt, "content"); + assert_eq!(c.rect[1] + c.scrolled[1], content0); + assert_eq!(info(&rt, "marker").scrolled, [0.0; 2], "outside the viewport"); + } + assert_eq!(info(&rt, "content").scrolled, [0.0, 500.0]); +} + +#[test] +fn what_a_pinned_end_carries_knows_how_far() { + // Content growing under a stuck bottom carries the rows up without a glide. + fn view(h: &f32, _: &mut Cx<f32>) -> El { + col().key("scroll").size(300.0, 200.0).scroll(ScrollSpec { stick_bottom: true }) + .child(col().key("stack").w_full().growth(GrowthSpec::default()) + .child(el().key("lead").w_full().h(400.0)) + .child(el().key("grow").w_full().h(*h))) + } + let mut rt = Runtime::new(37.0, view, (300.0, 200.0), Env::default()); + rt.frame(0.0); + rt.update(|h, _| *h = 230.0); + let mut seen = Vec::new(); + for _ in 0..60 { + rt.frame(1.0 / 120.0); + let lead = info(&rt, "lead"); + assert!((lead.rect[1] + lead.scrolled[1]).abs() < 0.01, "{lead:?}"); + assert!(!lead.scrolling); + if seen.last() != Some(&lead.scrolled[1]) { seen.push(lead.scrolled[1]); } + } + assert!(seen.len() > 5, "the end followed over several frames: {seen:?}"); +} + +/// origin/dev's watcher, transcribed from `runtime/scroll/watch.rs`: it kept where it last +/// told (`told`) and a weak reference to the handler that heard it (`told_by`), and called +/// when where the viewport stood changed, or the handler was new. +#[derive(Default)] +struct Dev { + told: Option<ScrollPos>, + told_by: Option<Weak<dyn Fn(ScrollPos)>>, +} + +impl Dev { + fn seen(&mut self, y: f32, handler: Option<&Rc<dyn Fn(ScrollPos)>>, by_hand: bool) -> Option<(ScrollPos, bool)> { + let f = handler?; + let at = pos(y); + let prev = self.told.replace(at); + let changed = prev != Some(at); + let new_handler = !self.told_by.as_ref().is_some_and(|by| std::ptr::addr_eq(by.as_ptr(), Rc::as_ptr(f))); + if new_handler { + self.told_by = Some(Rc::downgrade(f)); + } + if !changed && !new_handler { + return None; + } + let scrolled = by_hand && prev.is_some_and(|old| { + (old.offset[0] - at.offset[0]).abs() > 0.01 || (old.offset[1] - at.offset[1]).abs() > 0.01 + }); + Some((at, scrolled)) + } +} + +fn pos(y: f32) -> ScrollPos { + ScrollPos { offset: [0.0, y], max: [0.0, 800.0], viewport: [300.0, 200.0], drawn: [300.0, 200.0], direction: Direction::Ltr } +} + +/// Two handlers built separately, whose allocations stay alive for the walk. +fn handlers() -> Vec<Rc<dyn Fn(ScrollPos)>> { + (0..2).map(|_| Rc::new(|_: ScrollPos| {}) as Rc<dyn Fn(ScrollPos)>).collect() +} + +fn same_handler(a: &Option<Weak<dyn Fn(ScrollPos)>>, b: &Option<Weak<dyn Fn(ScrollPos)>>) -> bool { + match (a, b) { + (None, None) => true, + (Some(a), Some(b)) => Weak::ptr_eq(a, b), + _ => false, + } +} + +#[derive(Clone, Copy, Debug)] +struct Act { + y: f32, + /// 0: the viewport has no handler; otherwise one of the walk's handlers. + handler: usize, + by_hand: bool, +} + +/// Drives every sequence through the watcher and through dev's, one event at a time, and +/// compares what each does after every event. +fn walk(acts: &[Act]) { + let (mut watch, mut dev) = (Watch::default(), Dev::default()); + let handlers = handlers(); + for (i, act) in acts.iter().enumerate() { + let handler = (act.handler != 0).then(|| &handlers[act.handler - 1]); + let effects: Vec<Effect> = step(&mut watch, Event::Seen { at: pos(act.y), handler, by_hand: act.by_hand }).into_iter().collect(); + let expected = dev.seen(act.y, handler, act.by_hand); + match expected { + Some((at, scrolled)) => assert_eq!(effects, [Effect::Tell { at, scrolled }], "{acts:?}, event {i}"), + None => assert!(effects.is_empty(), "{acts:?}, event {i}: told though nothing changed"), + } + assert_eq!(watch.told, dev.told, "{acts:?}, event {i}"); + assert!(same_handler(&watch.handler, &dev.told_by), "{acts:?}, event {i}: the handler told"); + } +} + +/// Two handlers built separately are two handlers, even at the same offset: the weak +/// reference tells them apart, where an attempt that wrapped would not. +#[test] +fn two_handlers_at_the_same_offset_each_hear_the_first_time() { + let handlers = handlers(); + let (first, second) = (&handlers[0], &handlers[1]); + let mut watch = Watch::default(); + let at = pos(0.0); + let told = |watch: &mut Watch, handler: &Rc<dyn Fn(ScrollPos)>| { + step(watch, Event::Seen { at, handler: Some(handler), by_hand: false }).into_iter().collect::<Vec<_>>() + }; + assert_eq!(told(&mut watch, first), [Effect::Tell { at, scrolled: false }]); + assert_eq!(told(&mut watch, first), [], "the same handler hears it once"); + assert_eq!(told(&mut watch, second), [Effect::Tell { at, scrolled: false }], "a second handler is new, even with the same value"); +} + +#[test] +fn the_watcher_matches_devs_told_offset_and_handler_over_every_order() { + let acts: Vec<Act> = [0.0, 12.0].into_iter().flat_map(|y| [0, 1, 2].into_iter().flat_map(move |handler| { + [false, true].into_iter().map(move |by_hand| Act { y, handler, by_hand }) + })).collect(); + for len in 0..=5 { + for_each_walk(&acts, len, &mut Vec::new()); + } +} + +fn for_each_walk(acts: &[Act], len: usize, prefix: &mut Vec<Act>) { + if prefix.len() == len { + walk(prefix); + return; + } + for &act in acts { + prefix.push(act); + for_each_walk(acts, len, prefix); + prefix.pop(); + } +} + +#[test] +fn scroll_watch_state_uses_runtime_clock_after_idle_gap() { + fn view(seen: &Rc<std::cell::Cell<f64>>, _: &mut Cx<Rc<std::cell::Cell<f64>>>) -> El { + let seen = seen.clone(); + col() + .key("scroll") + .size(300.0, 200.0) + .scroll(ScrollSpec { stick_bottom: false }) + .on_scroll_offset(move |_: ScrollPos| { + seen.set(scroll_watch_state().2); + }) + .child(el().w_full().h(1000.0)) + } + let seen = Rc::new(std::cell::Cell::new(0.0f64)); + let mut rt = Runtime::new(seen.clone(), view, (300.0, 200.0), Env::default()); + rt.frame(0.0); + rt.frame(1.0 / 60.0); + // Simulate a 5 s idle wake: `clock` advances by 5 s while animation time `t` caps at RESUME_STEP. + crate::frame::clock::advance_by(&mut rt, 5.0); + rt.wheel(100.0, 100.0, -40.0); + crate::frame::clock::advance_by(&mut rt, 1.0 / 60.0); + assert!(seen.get() >= 5.0, "scroll_watch_state clock {} must track unscaled runtime clock after 5 s idle", seen.get()); +} diff --git a/app/vendor/rune/crates/rune/src/runtime/scroll/wheel.rs b/app/vendor/rune/crates/rune/src/runtime/scroll/wheel.rs new file mode 100644 index 0000000..c2570fb --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/scroll/wheel.rs @@ -0,0 +1,180 @@ +//! A notched mouse wheel's motion, as Chromium animates it on Windows and Linux +//! (`cc/animation/scroll_offset_animation_curve.cc`, a mouse wheel's `kInverseDelta` curve): +//! each notch moves the target, and the offset eases there over a time that shrinks as the +//! distance grows (200 ms for 120 device pixels or less, 100 ms for 480 or more), on +//! `cubic-bezier(0.42, 0, 0.58, 1)`. A notch that comes while it moves sends it on from where +//! it is, keeping its speed, so stacked notches run as one motion and a notch back turns it +//! round without a jump. Sampled at whatever time each frame steps, so it runs at the +//! display's rate. +use rune_motion::CubicBezier; + +/// Frames of 60 Hz a wheel's ease lasts at most and at least, and the distances in device +/// pixels where it starts and stops shortening (`kInverseDelta*`). +const LONGEST: f64 = 12.0; +const SHORTEST: f64 = 6.0; +const RAMP_START: f64 = 120.0; +const RAMP_END: f64 = 480.0; +/// Closer than this (in device pixels) is there (`kEpsilon`). +const THERE: f64 = 0.01; + +/// One notched wheel's ease from `from` to `to` (offsets in points), `t` seconds into a segment +/// of `duration` seconds. +#[derive(Clone, Copy, Debug, PartialEq)] +pub(crate) struct WheelCurve { + from: f64, + to: f64, + t: f64, + duration: f64, + ease: CubicBezier, + /// Set since a notch began or retargeted it, until the first frame that steps it: time a + /// frame catches up for motion that was already running is none of its. + fresh: bool, + /// The offset it last put the viewport at: one that differs when the ease next steps was + /// moved under it (rows above measured or arrived, an anchor kept what's on screen). + applied: f64, + /// Its target was the viewport's end when a notch set it: a stick-to-bottom viewport whose end + /// grows under it (a reply streaming) takes its target with the end, and lands pinned. + to_end: bool, +} + +impl WheelCurve { + /// An ease from `from` to `to`, `scale` device pixels to a point. + pub(crate) fn new(from: f64, to: f64, scale: f64) -> Self { + WheelCurve { from, to, t: 0.0, duration: duration(to - from, scale), ease: CubicBezier::new(0.42, 0.0, 0.58, 1.0), fresh: true, applied: from, to_end: false } + } + + /// No ease, at rest at `at`: where a notch's ease starts from when none is running. It is + /// finished, so a notch that sends it nowhere new moves nothing and changes no mode. + pub(crate) fn still(at: f64) -> Self { + WheelCurve { from: at, to: at, t: 0.0, duration: 0.0, ease: CubicBezier::new(0.42, 0.0, 0.58, 1.0), fresh: false, applied: at, to_end: false } + } + + /// The viewport's offset is `offset` before the ease steps: whatever moved it since the ease + /// last did (rows above measured, an anchor holding what's on screen) moves the whole ease + /// with it, so the content under the reader doesn't jump back (Chromium's `ApplyAdjustment`). + pub(crate) fn follow(&mut self, offset: f64) { + let moved = offset - self.applied; + if moved != 0.0 { + self.from += moved; + self.to += moved; + self.applied = offset; + } + } + + /// The ease put the viewport at `offset`. + pub(crate) fn applied(&mut self, offset: f64) { self.applied = offset; } + + /// Where it heads. + pub(crate) fn target(&self) -> f64 { self.to } + + /// Whether a notch sent it to the viewport's end (`Self::aimed_at_end`). + pub(crate) fn to_end(&self) -> bool { self.to_end } + + /// A notch sent it to o: the viewport's end when `at_end`. + pub(crate) fn aimed_at_end(&mut self, at_end: bool) { self.to_end = at_end; } + + /// The offset now. + pub(crate) fn value(&self) -> f64 { + if self.duration <= 0.0 || self.t >= self.duration { return self.to; } + let (y, _) = self.ease.eval_with_slope((self.t / self.duration) as f32); + self.from + (self.to - self.from) * f64::from(y) + } + + /// Its speed now, in points a second. + pub(crate) fn velocity(&self) -> f64 { + if self.duration <= 0.0 || self.t >= self.duration { return 0.0; } + let (_, slope) = self.ease.eval_with_slope((self.t / self.duration) as f32); + f64::from(slope) * (self.to - self.from) / self.duration + } + + /// It has reached its target. + pub(crate) fn done(&self) -> bool { self.t >= self.duration } + + /// Steps it `dt` seconds on: a frame's own step, or (`catch_up`) the time a frame charges to + /// motion already running, which a notch that came since then doesn't take. + pub(crate) fn advance(&mut self, dt: f64, catch_up: bool) { + // Landing at once (reduced motion, or an app that turned the glide off) lands whatever. + if dt.is_infinite() { + self.fresh = false; + self.t = self.duration.max(0.0); + return; + } + // A step of nothing (a commit's `step_scroll(0.0)`) isn't the first frame. + if dt == 0.0 { return; } + // An ease from rest starts at its first frame, as Chromium's does (the animation's start + // time is that frame's, and official's first frame after a notch draws where it was): that + // frame's catch-up and step both pass, and the next frame moves. + if self.fresh { + if !catch_up { self.fresh = false; } + return; + } + self.t = (self.t + dt).min(self.duration.max(0.0)); + } + + /// Sends it on to `to` from where it is now, keeping its speed (`UpdateTarget`). Returns + /// false when it's already there and nothing is left to move. + pub(crate) fn retarget(&mut self, to: f64, scale: f64) -> bool { + // What it last put the viewport at stays: a new segment starts from there. + let applied = self.applied; + let moving = self.send_to(to, scale); + self.applied = applied; + moving + } + + fn send_to(&mut self, to: f64, scale: f64) -> bool { + if ((self.to - to) * scale).abs() < THERE { + self.to = to; + return !self.done(); + } + let at = self.value(); + let delta = to - at; + if (delta * scale).abs() < THERE { + *self = WheelCurve { from: to, to, t: 0.0, duration: 0.0, ..*self }; + return false; + } + if self.done() || self.duration <= 0.0 { + *self = WheelCurve::new(at, to, scale); + return true; + } + let v = self.velocity(); + // At this speed it would get there in this long, with room to ease out: a long segment + // after a fast one would make it rubber-band (`VelocityBasedDurationBound`). + // Heading the other way, there's no bound. + let bound = delta / v * 2.5; + let bound = if (v * scale).abs() < THERE || bound < 0.0 { f64::INFINITY } else { bound }; + let duration = duration(delta, scale).min(bound); + if duration < THERE { + *self = WheelCurve { from: to, to, t: 0.0, duration: 0.0, ..*self }; + return false; + } + // The new segment starts at the old one's speed (`EaseInOutWithInitialSlope`). It is the + // same motion going on, so it keeps whether its first frame has come: an ease from rest + // that a second notch retargets before that frame still starts on it, and one already + // moving keeps the frame's catch-up (marking it fresh would make the frame after each + // stacked notch a half step at 60 Hz). + let slope = (v * duration / delta).clamp(-1000.0, 1000.0) as f32; + *self = WheelCurve { from: at, to, t: 0.0, duration, ease: CubicBezier::new(0.42, 0.42 * slope, 0.58, 1.0), ..*self }; + true + } + +} + +/// `offset` on the device grid (`device_pixel`), except within a device pixel of the end `max`: +/// there the end wins, so a viewport the ease takes to its end reads as at its end (the room +/// test hands the next run on, and a stick-to-bottom viewport pins) rather than a fraction short. +pub(crate) fn on_grid_or_end(offset: f64, max: f64, scale: f64) -> f64 { + let v = device_pixel(offset, scale); + if (max - v) * scale < 1.0 { max } else { v.clamp(0.0, max) } +} + +/// `offset` points on the nearest whole device pixel, `scale` of them to a point. +pub(crate) fn device_pixel(offset: f64, scale: f64) -> f64 { + if scale > 0.0 { (offset * scale).round() / scale } else { offset } +} + +/// How long a wheel's ease over `delta` points lasts, in seconds. +fn duration(delta: f64, scale: f64) -> f64 { + let slope = (SHORTEST - LONGEST) / (RAMP_END - RAMP_START); + let frames = (LONGEST - RAMP_START * slope + (delta * scale).abs() * slope).clamp(SHORTEST, LONGEST); + frames / 60.0 +} diff --git a/app/vendor/rune/crates/rune/src/runtime/scroll/x.rs b/app/vendor/rune/crates/rune/src/runtime/scroll/x.rs new file mode 100644 index 0000000..a57304e --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/scroll/x.rs @@ -0,0 +1,666 @@ +//! Horizontal scrolling for `El::scroll_x` and `El::scroll_xy` viewports: the axis a wheel or +//! trackpad gesture locks to, Shift with a mouse wheel, momentum, `Tx::scroll_into_view` and +//! `Tx::scroll_to_x` on x. +//! +//! A gesture moves one axis, picked by its first delta, as AppKit's predominant-axis scrolling +//! does: mostly horizontal goes to the innermost horizontal viewport under the pointer, else to +//! the innermost vertical one, and a diagonal never moves both. The gesture keeps that axis +//! wherever the pointer ends up, as AppKit latches a gesture to the view it began on: one that +//! began outside any horizontal viewport stays vertical when the content scrolls one under the +//! pointer. Without phases (a mouse wheel), only a pause or a delta wholly on the other axis +//! ends the lock, so Shift + wheel and then the plain wheel each scroll at once. +use super::*; +use crate::machine::{Attempt, Seq}; + +/// Seconds without a delta after which the next one starts a new gesture, where the platform +/// reports no phases (a mouse wheel, most trackpads off macOS). +const WHEEL_IDLE: f64 = 0.1; +/// Seconds without a delta after which a gesture the platform began counts as over, should its +/// end never come (the window lost the pointer or focus mid-gesture). +const PHASED_IDLE: f64 = 1.0; +/// A gesture that begins within this many seconds of one ending is its momentum (AppKit +/// reports momentum as a phase of its own), so it keeps the axis. +const MOMENTUM_GAP: f64 = 0.05; +/// A run of vertical deltas stays with the viewport it began on while each comes within this +/// many seconds of the last and the pointer within this many points of where it began, as +/// Chromium latches a wheel's scroll (`content/browser/renderer_host/input/ +/// mouse_wheel_phase_handler.cc`: `kDefaultMouseWheelLatchingTransaction`, `kWheelLatchingSlopRegion`). +const RUN_IDLE: f64 = 0.5; +const RUN_SLOP: f32 = 10.0; + +/// The wheel or trackpad gesture in progress, and who has it. Its phase carries when its last +/// delta came and, once the platform ended it, when that was: one fact, in one place. +#[derive(Debug, Default)] +pub(in crate::runtime) struct WheelLock { + seq: Seq, + /// The gesture deltas arriving now belong to: a new one whenever a gesture starts or the + /// window loses the gesture. + pub(in crate::runtime) gesture: Attempt, + /// Who has the gesture's deltas: the arriving gesture's owner, or the previous gesture's + /// while deltas of it still wait in the queue for `on_wheel` handlers. + run: WheelRun, + phase: WheelPhase, + /// The vertical viewport the current run of deltas scrolls, once one has. + vertical: Option<VerticalRun>, + /// Whether the current run of deltas is a notched wheel's. + kind: DeltaKind, +} + +/// What a run of wheel deltas is while its deltas keep coming (within `RUN_IDLE`): a notched +/// wheel's whole lines, or a precision touchpad's or a free-spinning wheel's fractions. A run is +/// notched while every delta is whole, and precise from its first fraction to its end: a fast +/// swipe's delta that happens to be a whole line stays precise, rather than starting an ease the +/// next fraction throws away. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +enum DeltaKind { + #[default] + Idle, + Notched { at: f64 }, + Precise { at: f64 }, +} + +impl DeltaKind { + /// A delta at `now`, whole lines (`whole`) or not: what the run it belongs to is. + fn step(&mut self, now: f64, whole: bool) -> bool { + let notched = match *self { + DeltaKind::Notched { at } | DeltaKind::Precise { at } if now - at > RUN_IDLE => whole, + // A fraction ends a run of whole lines' easing: a touchpad swipe whose first delta was + // exactly a line is precise from its first fraction on. + DeltaKind::Notched { .. } => whole, + DeltaKind::Precise { .. } => false, + DeltaKind::Idle => whole, + }; + *self = if notched { DeltaKind::Notched { at: now } } else { DeltaKind::Precise { at: now } }; + notched + } +} + +/// A run of vertical deltas and the viewport it keeps to: cc scrolls only the latched scroller, +/// so one that reaches its end mid-run takes the rest of the run, and the one around it moves +/// from the next run on. `down` is its first delta's direction; `moved`, whether that delta +/// moved the viewport: only a run whose first delta moved nothing ends when the wheel turns +/// (`ShouldBreakLatchingDueToDirectionChange`). +#[derive(Clone, Copy, Debug)] +struct VerticalRun { + id: NodeId, + at: f64, + x: f32, + y: f32, + down: bool, + moved: bool, +} + +/// Who has the deltas still to run, keyed by the gesture each belongs to: the gesture arriving +/// now, and, until they run, the older gesture whose queued deltas already had an owner. +#[derive(Clone, Debug, PartialEq)] +enum WheelRun { + /// The arriving gesture has `owner`: its deltas go to it, and its first delta picks it + /// afresh. + Arriving(WheelOwner), + /// Deltas of `gesture` still wait in the queue: `owner` takes them. The gesture arriving + /// now has `arriving` of its own, which it picks when one of its deltas scrolls before + /// those queued ones run. + Waiting { gesture: Attempt, owner: WheelOwner, arriving: WheelOwner }, +} + +impl Default for WheelRun { + fn default() -> Self { WheelRun::Arriving(WheelOwner::default()) } +} + +impl WheelRun { + /// Who has the gesture arriving now. + fn arriving(&self) -> &WheelOwner { + match self { + WheelRun::Arriving(owner) => owner, + WheelRun::Waiting { arriving, .. } => arriving, + } + } + + fn arriving_mut(&mut self) -> &mut WheelOwner { + match self { + WheelRun::Arriving(owner) => owner, + WheelRun::Waiting { arriving, .. } => arriving, + } + } + + /// Who has `gesture`'s queued deltas, while the lock holds them. + fn waiting(&self, gesture: Attempt) -> Option<&WheelOwner> { + match self { + WheelRun::Waiting { gesture: g, owner, .. } if *g == gesture => Some(owner), + _ => None, + } + } + + fn waiting_mut(&mut self, gesture: Attempt) -> Option<&mut WheelOwner> { + match self { + WheelRun::Waiting { gesture: g, owner, .. } if *g == gesture => Some(owner), + _ => None, + } + } +} + +/// Who has the gesture `WheelLock` runs. +#[derive(Clone, Debug, Default, PartialEq)] +pub(in crate::runtime) enum WheelOwner { + /// Nobody yet: its first delta picks. + #[default] + Unpicked, + /// The `on_wheel` element that took the gesture's first delta and hears the rest. + Handler(String), + /// Scrolling vertically. + Vertical, + /// Scrolling the horizontal viewport the gesture began on, latched through the gesture + /// and its momentum. + Horizontal(NodeId), +} + +impl WheelOwner { + /// Horizontal (`true`) or vertical, once a delta picked an axis. + fn horizontal(&self) -> Option<bool> { + match self { + WheelOwner::Vertical => Some(false), + WheelOwner::Horizontal(_) => Some(true), + WheelOwner::Unpicked | WheelOwner::Handler(_) => None, + } + } +} + +/// Whether the platform reports the gesture's phases, and when it last moved or ended. +#[derive(Clone, Copy, Debug, PartialEq)] +enum WheelPhase { + /// No phases (a mouse wheel): a pause or a delta wholly on the other axis ends it. `at` is + /// when its last delta came, `None` before the first. + Unphased { at: Option<f64> }, + /// The platform began it at `at`: it holds the axis until it ends, however slowly it moves. + Phased { at: f64 }, + /// The momentum of a phased gesture that ended, last moving at `at`. One that begins as + /// momentum ends is a new touch (a finger caught the coasting content), not more momentum. + Momentum { at: f64 }, + /// The platform ended it at `at`. `from` is the phase it had then: a gesture that started + /// unphased still picks its axis afresh, and one that ended as momentum never begins its + /// own momentum. + Ended { at: f64, from: GestureKind }, +} + +/// The phase a gesture had when the platform ended it. +#[derive(Clone, Copy, Debug, PartialEq)] +enum GestureKind { + Unphased, + Phased, + Momentum, +} + +impl Default for WheelPhase { + fn default() -> Self { WheelPhase::Unphased { at: None } } +} + +impl WheelPhase { + /// The gesture is the momentum of one that ended, or ended as momentum. + fn momentum(self) -> bool { + matches!(self, WheelPhase::Momentum { .. } | WheelPhase::Ended { from: GestureKind::Momentum, .. }) + } + + /// Whether the platform reports its phases: it has begun it, or it ended one that had. + fn phased(self) -> bool { + !matches!(self, WheelPhase::Unphased { .. } | WheelPhase::Ended { from: GestureKind::Unphased, .. }) + } + + /// When its last delta came. + fn at(self) -> Option<f64> { + match self { + WheelPhase::Unphased { at } => at, + WheelPhase::Phased { at } | WheelPhase::Momentum { at } | WheelPhase::Ended { at, .. } => Some(at), + } + } + + /// When the platform ended it, while that is what happened last. + fn ended(self) -> Option<f64> { + match self { + WheelPhase::Ended { at, .. } => Some(at), + _ => None, + } + } + + /// The same live phase, with its last delta at `now`. + fn moving(self, now: f64) -> Self { + match self { + WheelPhase::Unphased { .. } => WheelPhase::Unphased { at: Some(now) }, + WheelPhase::Phased { .. } => WheelPhase::Phased { at: now }, + WheelPhase::Momentum { .. } => WheelPhase::Momentum { at: now }, + WheelPhase::Ended { .. } => self, + } + } +} + +impl WheelLock { + /// Whether a delta at `now` that is whole lines (`whole`) is a notch: the run it belongs to decides. + pub(in crate::runtime) fn notched(&mut self, now: f64, whole: bool) -> bool { self.kind.step(now, whole) } + + /// Who has the gesture arriving now: deltas of older gestures don't reach it. + pub(in crate::runtime) fn owner(&self) -> &WheelOwner { self.run.arriving() } + + /// Who has `gesture`'s deltas: the arriving gesture's own, or an older gesture's while its + /// queued deltas still run. + pub(in crate::runtime) fn owner_of(&self, gesture: Attempt) -> Option<&WheelOwner> { + if gesture == self.gesture { Some(self.run.arriving()) } else { self.run.waiting(gesture) } + } + + /// Who has `gesture`'s deltas becomes `owner`, giving a gesture the lock doesn't hold a + /// fresh start of its own beside the arriving one's. + pub(in crate::runtime) fn set_owner(&mut self, gesture: Attempt, owner: WheelOwner) { + if gesture == self.gesture { + *self.run.arriving_mut() = owner; + } else { + self.sync_gesture(gesture); + if let Some(slot) = self.run.waiting_mut(gesture) { *slot = owner; } + } + } + + /// Whether the platform reports the phases of the gesture the lock runs. + pub(in crate::runtime) fn phased(&self) -> bool { self.phase.phased() } + + /// A delta of `gesture` runs: an owner the lock already holds for that gesture takes it, and + /// any other queued gesture starts afresh, beside the arriving gesture's own owner. + pub(in crate::runtime) fn sync_gesture(&mut self, gesture: Attempt) { + if gesture == self.gesture || self.run.waiting(gesture).is_some() { return; } + let arriving = std::mem::take(self.run.arriving_mut()); + self.run = WheelRun::Waiting { gesture, owner: WheelOwner::Unpicked, arriving }; + } + + /// The gesture is the momentum of one that ended (`WheelEvent::momentum`). + pub(in crate::runtime) fn momentum(&self) -> bool { self.phase.momentum() } + + /// The next gesture starts, unphased. Only an owner whose gesture still has a delta waiting + /// for `on_wheel` handlers keeps its place: `pending` is the gesture the oldest queued delta + /// belongs to, so one that has run its last delta gives its owner up. + fn restart(&mut self, pending: Option<Attempt>) { + let arriving = self.gesture; + let mut run = std::mem::take(&mut self.run); + self.gesture = self.seq.next(); + self.phase = WheelPhase::Unphased { at: None }; + self.run = match pending { + None => WheelRun::Arriving(WheelOwner::Unpicked), + Some(next) if next == arriving => { + WheelRun::Waiting { gesture: next, owner: std::mem::take(run.arriving_mut()), arriving: WheelOwner::Unpicked } + } + Some(next) => WheelRun::Waiting { + gesture: next, + owner: run.waiting_mut(next).map(std::mem::take).unwrap_or_default(), + arriving: WheelOwner::Unpicked, + }, + }; + } + + /// The axis `gesture`'s owner keeps for a delta (dx, dy): horizontal (`true`) or vertical, or + /// `None` when it picks afresh. `phased` is the delta's own gesture's policy: without phases, + /// a delta wholly on the other axis is another wheel turning (Shift let go, a tilt, a second + /// device). + fn keeps_axis(&self, gesture: Attempt, dx: f32, dy: f32, phased: bool) -> Option<bool> { + let h = self.owner_of(gesture)?.horizontal()?; + (phased || if h { dx != 0.0 } else { dy != 0.0 }).then_some(h) + } + + /// A delta picked afresh: the horizontal viewport under it (`across`), else vertical. + /// Returns whether it scrolls horizontally. + fn repick(&mut self, gesture: Attempt, across: Option<NodeId>) -> bool { + self.set_owner(gesture, across.map_or(WheelOwner::Vertical, WheelOwner::Horizontal)); + across.is_some() + } + + /// A delta arrived at `now`, on (dx, dy) points: a gesture idle too long, ended, or wholly + /// on the other axis (Shift let go, a tilt, a second wheel), is over, and this delta starts + /// the next. + fn delta(&mut self, now: f64, dx: f32, dy: f32, pending: Option<Attempt>) { + let phased = self.phase.phased(); + let idle = if phased { PHASED_IDLE } else { WHEEL_IDLE }; + let flipped = !phased && self.run.arriving().horizontal().is_some_and(|h| if h { dx == 0.0 } else { dy == 0.0 }); + let stale = self.phase.ended().is_some() || self.phase.at().is_none_or(|a| now - a > idle) || flipped; + if stale { self.restart(pending); } + self.phase = self.phase.moving(now); + } + + /// The viewport a vertical delta `dy` at (x, y) at `now` keeps to, when it continues the run. + pub(in crate::runtime) fn vertical_run(&self, now: f64, x: f32, y: f32, dy: f32) -> Option<NodeId> { + let run = self.vertical?; + let continues = now - run.at <= RUN_IDLE && (x - run.x).hypot(y - run.y) < RUN_SLOP && (run.moved || (dy < 0.0) == run.down); + continues.then_some(run.id) + } + + /// A vertical delta `dy` at (x, y) at `now` scrolled viewport `id` (`moved`: it moved it); + /// `continued`, as part of the run, or else starting one. + pub(in crate::runtime) fn ran_vertical(&mut self, id: NodeId, now: f64, x: f32, y: f32, dy: f32, moved: bool, continued: bool) { + match &mut self.vertical { + Some(run) if continued => run.at = now, + _ => self.vertical = Some(VerticalRun { id, at: now, x, y, down: dy < 0.0, moved }), + } + } + + /// No viewport takes the run: the next delta starts afresh. + pub(in crate::runtime) fn end_vertical(&mut self) { self.vertical = None; } + + /// The platform began a gesture at `now`: its first delta picks the axis afresh, unless it + /// is the momentum of one that just ended. + fn began(&mut self, now: f64, active: bool, queued: bool, pending: Option<Attempt>) { + let momentum = !self.phase.momentum() && (active || queued) && self.phase.ended().is_some_and(|e| now - e <= MOMENTUM_GAP); + // A new touch is a new run; its momentum keeps the one it has. + if !momentum { self.restart(pending); self.vertical = None; } + self.phase = if momentum { WheelPhase::Momentum { at: now } } else { WheelPhase::Phased { at: now } }; + } + + /// The platform ended the gesture at `now`, keeping the phase it had. + fn ended_at(&mut self, now: f64) { + let from = match self.phase { + WheelPhase::Unphased { .. } => GestureKind::Unphased, + WheelPhase::Phased { .. } => GestureKind::Phased, + WheelPhase::Momentum { .. } => GestureKind::Momentum, + WheelPhase::Ended { from, .. } => from, + }; + self.phase = WheelPhase::Ended { at: now, from }; + } + + /// The window lost the pointer or focus: a gesture in progress won't report its end here. + fn lost(&mut self, pending: Option<Attempt>) { self.restart(pending); self.vertical = None; } +} + +/// A wheel event's delta in points, positive moving content right and down. With Shift, a delta +/// with no horizontal part turns horizontal, as browsers and Windows and Linux apps do for a +/// mouse wheel. macOS turns it itself (`shift` is false there), and a delta that already has a +/// horizontal part was turned by the system or comes from a trackpad. +pub(crate) fn wheel_delta(delta: winit::event::MouseScrollDelta, scale: f32, shift: bool, line_points: f32) -> (f32, f32) { + let (dx, dy) = match delta { + winit::event::MouseScrollDelta::PixelDelta(p) => (p.x as f32 / scale, p.y as f32 / scale), + winit::event::MouseScrollDelta::LineDelta(x, y) => (x * line_points, y * line_points), + }; + if shift && dx == 0.0 { (dy, 0.0) } else { (dx, dy) } +} + +// Chromium 152: ui/events/event.cc (kWheelDelta on Linux), ui/events/x/events_x_utils.cc +// (XI2 scroll increments), ui/events/cocoa/cocoa_event_utils.h (kScrollbarPixelsPerCocoaTick) +// and cc/input/scroll_utils.h (kPixelsPerLineStep for browser line units). +#[cfg(any(not(target_os = "windows"), test))] +pub(crate) const LINE_POINTS: f32 = if cfg!(target_os = "linux") { 120.0 } else { 40.0 }; + +#[cfg(target_os = "windows")] +impl RuntimeCore { + #[allow(unsafe_code)] + pub(crate) fn windows_wheel_points(&self, delta: winit::event::MouseScrollDelta, shift: bool) -> f32 { + use windows_sys::Win32::UI::WindowsAndMessaging::{SystemParametersInfoW, SPI_GETWHEELSCROLLCHARS, SPI_GETWHEELSCROLLLINES}; + let winit::event::MouseScrollDelta::LineDelta(x, y) = delta else { return 0.0 }; + let horizontal = x != 0.0; + let (setting, default) = if horizontal { (SPI_GETWHEELSCROLLCHARS, 1u32) } else { (SPI_GETWHEELSCROLLLINES, 3u32) }; + let mut count = default; + // SAFETY: both SPI queries write one UINT. Read per event so Settings changes apply immediately. + if unsafe { SystemParametersInfoW(setting, 0, (&raw mut count).cast(), 0) } == 0 { count = default; } + // Chromium 152: ui/events/blink/web_input_event_builders_win.cc, WebMouseWheelEventBuilder. + const POINTS_PER_SCROLL_LINE: f32 = 100.0 / 3.0; + if !horizontal && count == u32::MAX { + // WHEEL_PAGESCROLL: cc/input/input_handler.cc, ResolveScrollGranularityToPixels, + // uses the smaller of the scroller and the window. Clamp after applying the ticks. + const PAGE_FRACTION: f32 = 0.875; + let viewport = self.pointer().and_then(|(x, y)| self.scroll_at_axis(x, y, shift)) + .and_then(|id| self.tree.node_index.get(&id)).map(|&i| self.tree.nodes[i].local); + let (window, scroller) = if shift { (self.viewport.0, viewport.map(|r| r.w)) } else { (self.viewport.1, viewport.map(|r| r.h)) }; + let page = scroller.unwrap_or(window).min(window) * self.zoom() * PAGE_FRACTION; + if y == 0.0 { 0.0 } else { page.max(1.0 / y.abs()) } + } else { count as f32 * POINTS_PER_SCROLL_LINE } + } +} + +/// Whether Shift turns the wheel on this platform (macOS does it before the app sees the event). +#[cfg_attr(target_arch = "wasm32", allow(dead_code))] +pub(crate) const SHIFT_TURNS_WHEEL: bool = !cfg!(target_os = "macos"); + +impl ScrollState { + /// The offset, velocity and limit on one axis. + pub(in crate::runtime) fn axis(&mut self, horizontal: bool) -> (&mut f64, f64) { + if horizontal { (&mut self.x.offset, self.x.max) } else { (&mut self.offset, self.max) } + } +} + +impl requests::ScrollTables { + /// A delta arrived: a gesture idle too long, or ended and not followed by its momentum, + /// is over, and this delta starts the next. Without phases, a delta wholly on the other + /// axis (Shift let go, a tilt, a second wheel) also starts a new gesture. + #[inline] + pub(in crate::runtime) fn wheel_delta(&mut self, now: f64, dx: f32, dy: f32, pending: Option<Attempt>) { + self.drop_holds(); + self.wheel_lock.delta(now, dx, dy, pending); + } + + #[inline] + pub(super) fn wheel_began_at(&mut self, now: f64, queued: bool, pending: Option<Attempt>) { + let active = self.wheel_lock.owner() != &WheelOwner::Unpicked; + self.wheel_lock.began(now, active, queued, pending); + } + + #[inline] + pub(super) fn wheel_ended_at(&mut self, now: f64) { + self.wheel_lock.ended_at(now); + } + + #[inline] + pub(super) fn wheel_lost(&mut self, pending: Option<Attempt>) { + self.wheel_lock.lost(pending); + } + + /// Steps viewport `id`'s horizontal limit and momentum once `overflow` is known. + pub(super) fn step_x_state(&mut self, id: NodeId, overflow: f64, dt: f32, catch_up: bool, scale: f64, land_wheel: bool) -> bool { + let Some(st) = self.scrolls.get_mut(&id) else { return false }; + st.x.max = overflow.max(0.0); + let mut moving = false; + match st.x.motion { + XMotion::Glide { v, aim } => { + let mut glide = Some(v); + moving = scroll_offset::glide_axis(st.glide_spring(), &mut st.x.offset, &mut glide, aim.min(st.x.max), dt); + st.x.motion = glide.map_or(XMotion::Rest, |v| XMotion::Glide { v, aim }); + } + XMotion::Momentum(v) if v.abs() > 1.0 => { + let decay = (-SCROLL_DECAY * dt).exp(); + st.x.offset += f64::from(v * (1.0 - decay) / SCROLL_DECAY); + let edge = st.x.offset <= 0.0 || st.x.offset >= st.x.max; + st.x.motion = if edge { XMotion::Rest } else { XMotion::Momentum(v * decay) }; + moving = true; + } + XMotion::Momentum(_) => st.x.motion = XMotion::Rest, + XMotion::Wheel(mut curve) => { + curve.follow(st.x.offset); + if curve.target() > st.x.max { curve.retarget(st.x.max, scale); } + if land_wheel { curve.advance(f64::INFINITY, false) } else { curve.advance(f64::from(dt), catch_up) } + st.x.offset = scroll_wheel::on_grid_or_end(curve.value(), st.x.max, scale); + curve.applied(st.x.offset); + st.moved(); + if curve.done() { st.x.motion = XMotion::Rest; } else { st.x.motion = XMotion::Wheel(curve); moving = true; } + } + XMotion::Rest => {} + } + st.x.offset = st.x.offset.clamp(0.0, st.x.max); + moving + } +} + +impl RuntimeCore { + /// A wheel or trackpad delta in points on both axes (positive moves content right and + /// down). The gesture's first delta picks the axis and the rest of the gesture keeps it: + /// mostly horizontal scrolls the innermost [`El::scroll_x`] or [`El::scroll_xy`] viewport + /// under (x, y), anything else the innermost vertical one as [`Self::wheel`] does. Call + /// [`Self::wheel_began`] and [`Self::wheel_ended`] where the platform reports phases; + /// without them a pause of 0.1 s ends a gesture. An [`El::on_wheel`] handler under the + /// pointer hears it first; [`Self::wheel_event`] also passes modifiers and phases. + pub fn wheel_xy(&mut self, x: f32, y: f32, dx: f32, dy: f32) { + if dx == 0.0 && dy == 0.0 { return; } + self.wheel_event(crate::WheelEvent::new(dx, dy).at(x, y)); + } + + /// The gesture the oldest wheel delta still waiting for `on_wheel` handlers belongs to: the + /// only owner a new gesture can hand over to, since the queue runs in order. + pub(in crate::runtime) fn wheel_pending(&self) -> Option<Attempt> { + self.frame.queue.iter().find_map(|a| match a { + Action::Wheel { gesture, .. } => Some(*gesture), + _ => None, + }) + } + + /// Whether a wheel delta waits in the queue for `on_wheel` handlers: one of gesture `of`, + /// or of any gesture. + pub(in crate::runtime) fn wheel_queued(&self, of: Option<Attempt>) -> bool { + self.frame.queue.iter().any(|a| matches!(a, Action::Wheel { gesture: g, .. } if of.is_none_or(|of| *g == of))) + } + + /// Scrolls by a delta no `on_wheel` handler took, on the axis the gesture locked to. + /// `phased` is that delta's own gesture's policy, which a delta queued before a newer + /// gesture began keeps. + pub(in crate::runtime) fn wheel_scroll_for(&mut self, gesture: Attempt, ev: crate::WheelEvent, phased: bool, start: crate::runtime::gesture_dispatch::WheelStart) { + let (x, y, dx, dy) = (ev.x, ev.y, ev.dx, ev.dy); + if dx == 0.0 && dy == 0.0 { return; } + self.scroll.wheel_lock.sync_gesture(gesture); + // Without phases, a delta wholly on the other axis is another wheel turning (Shift let + // go, a tilt, a second device), so it picks afresh rather than being dropped. + let horizontal = match self.scroll.wheel_lock.keeps_axis(gesture, dx, dy, phased) { + Some(h) => h, + None => { + let scroller = (dx.abs() > dy.abs()).then(|| self.scroll_at_axis_from(x, y, true, start)).flatten(); + self.scroll.wheel_lock.repick(gesture, scroller) + } + }; + if horizontal { + if dx != 0.0 { self.wheel_x(gesture, x, y, dx, ev.notch, start); } + } else if dy != 0.0 { + if ev.notch { self.wheel_notch(x, y, dy, start) } else { self.wheel_from(x, y, dy, start) } + } + } + + /// The platform began a trackpad gesture (winit's `TouchPhase::Started` on a wheel event): + /// its first delta picks the axis afresh, unless it is the momentum of one that just ended. + pub fn wheel_began(&mut self) { + let now = self.now_clock(); + let gesture = self.scroll.wheel_lock.gesture; + // A delta queued for `on_wheel` handlers hasn't picked who has the gesture yet. + let queued = self.wheel_queued(Some(gesture)); + let pending = self.wheel_pending(); + self.scroll.wheel_began_at(now, queued, pending); + } + + /// The platform ended a trackpad gesture (`TouchPhase::Ended` or `Cancelled`). + pub fn wheel_ended(&mut self) { + let now = self.now_clock(); + self.scroll.wheel_ended_at(now); + } + + /// The window lost the pointer or focus: a gesture in progress won't report its end here. + pub(in crate::runtime) fn wheel_lost(&mut self) { + let pending = self.wheel_pending(); + self.scroll.wheel_lost(pending); + } + + /// Scrolls the horizontal viewport latched for `gesture` (or the innermost one at (x, y)) by + /// `dx` points: 1:1, or for whole notches of a wheel eased there as the vertical axis does + /// (`Self::wheel_notch`). + fn wheel_x(&mut self, gesture: Attempt, x: f32, y: f32, dx: f32, notch: bool, start: crate::runtime::gesture_dispatch::WheelStart) { + self.release_hover_hold(); + self.dismiss_help(); + let latched = match self.scroll.wheel_lock.owner_of(gesture) { Some(WheelOwner::Horizontal(id)) => Some(*id), _ => None }.filter(|id| { + self.tree.node_index.get(id).is_some_and(|&i| self.is_scroll_viewport(i, true)) + }); + let Some(id) = latched.or_else(|| self.scroll_at_axis_from(x, y, true, start)) else { return }; + let glides = notch && self.wheel_glides(); + let scale = f64::from(self.env.scale * self.zoom()); + let Some(st) = self.scroll.scrolls.get_mut(&id) else { return }; + let before = st.x.offset; + if glides { + let easing = matches!(st.x.motion, XMotion::Wheel(_)); + let mut curve = match st.x.motion { XMotion::Wheel(c) => c, _ => scroll_wheel::WheelCurve::still(st.x.offset) }; + curve.follow(st.x.offset); + let to = (curve.target() + st.x.toward(f64::from(dx))).clamp(0.0, st.x.max); + if !curve.retarget(to, scale) { + // Sent back to where it is: it stays put. + if easing { st.x.motion = XMotion::Rest; } + return; + } + st.x.motion = XMotion::Wheel(curve); + st.moved(); + log_event!(self, "wheel-x-notch {dx:.1}"); + self.pointer.scroll_cancels_press(&self.tree.nodes, id); + return; + } + st.x.offset = (st.x.offset + st.x.toward(f64::from(dx))).clamp(0.0, st.x.max); + st.x.motion = XMotion::Rest; + st.moved(); + log_event!(self, "wheel-x {dx:.1}"); + if st.x.offset != before { self.pointer.scroll_cancels_press(&self.tree.nodes, id); } + } + + /// Releases a scroll with velocity (vx, vy) in points per second (positive moves content + /// right and down), which the runtime decays, on the axis [`Self::wheel_xy`] would pick + /// for it. [`Self::fling`] is the vertical one. + pub fn fling_xy(&mut self, x: f32, y: f32, vx: f32, vy: f32) { + if vx.abs() <= vy.abs() || self.scroll_at_axis(x, y, true).is_none() { + self.fling(x, y, vy); + return; + } + self.release_hover_hold(); + self.dismiss_help(); + let Some(id) = self.scroll_at_axis(x, y, true) else { return }; + if let Some(st) = self.scroll.scrolls.get_mut(&id) { + st.x.motion = XMotion::Momentum(st.x.toward(f64::from(vx)) as f32); + log_event!(self, "fling-x {vx:.0}"); + if vx != 0.0 { self.pointer.scroll_cancels_press(&self.tree.nodes, id); } + } + } + + /// How far horizontal viewport `i`'s content reaches past its end edge (its right, or its + /// left right to left), negative while it fits. + fn scroll_overflow_x(&self, i: usize) -> f64 { + let view = self.tree.nodes[i].target; + let reach = |c: usize| match self.tree.nodes[i].flow { + crate::el::Flow::Ltr => self.tree.nodes[c].target[2] - view[0], + crate::el::Flow::Rtl => view[2] - self.tree.nodes[c].target[0], + }; + let content_w = self.scroll_children(i).map(|c| f64::from(reach(c))).reduce(f64::max).unwrap_or(0.0); + content_w - f64::from(view[2] - view[0]) + } + + /// Steps viewport `i`'s horizontal limit and momentum, as `step_scroll` does the vertical. + pub(in crate::runtime) fn step_scroll_x(&mut self, i: usize, dt: f32, catch_up: bool) -> bool { + let id = self.tree.nodes[i].id; + let overflow = self.scroll_overflow_x(i); + if let Some(active) = self.step_touch_scroll(id, overflow, dt, true) { return active; } + let scale = f64::from(self.env.scale * self.zoom()); + let land_wheel = !self.wheel_glides(); + self.scroll.step_x_state(id, overflow, dt, catch_up, scale, land_wheel) + } + + /// `Tx::scroll_into_view` on x: scrolls the nearest horizontal viewport around row `key` + /// just far enough to show it, leaving its `El::scroll_margin`. + pub(in crate::runtime) fn reveal_row_x(&mut self, scope: Option<&str>, key: &str) { + let target = self.live_named(scope, key) + .map(|i| (i, self.tree.nodes[i].target[0], self.tree.nodes[i].local.w)) + .or_else(|| { + let (i, [x0, _, x1, _]) = self.highlight_target_in(&self.tree.nodes, scope, key)?; + (!self.subtree_exiting(i)).then_some((i, x0, (x1 - x0).max(0.0))) + }); + let Some((i, target_x, target_w)) = target else { return }; + let Some(v) = std::iter::successors(self.tree.nodes[i].parent, |&p| self.tree.nodes[p].parent) + .find(|&p| self.tree.nodes[p].scroll.is_some() && self.tree.nodes[p].scroll_axes.x()) else { return }; + let view = &self.tree.nodes[v]; + // From the viewport's start edge: its right, right to left. + let start = match view.flow { + crate::el::Flow::Ltr => target_x - view.target[0], + crate::el::Flow::Rtl => view.target[2] - (target_x + target_w), + }; + let (left, width, viewport) = (f64::from(start), f64::from(target_w), f64::from(view.local.w)); + let (margin, id) = (f64::from(view.scroll_edges.margin), view.id); + // A vertical reveal may have just mounted rows (virtual ones) that widened the content. + let max = self.scroll_overflow_x(v).max(0.0); + let Some(st) = self.scroll.scrolls.get_mut(&id) else { return }; + st.x.max = max; + let offset = scroll_edge::reveal(st.x.offset, left, width, viewport, margin).clamp(0.0, max); + if offset == st.x.offset { return; } + st.x.offset = offset; + st.x.motion = XMotion::Rest; + st.moved(); + } +} + +#[cfg(test)] +#[path = "x_tests.rs"] +mod tests; diff --git a/app/vendor/rune/crates/rune/src/runtime/scroll/x_tests.rs b/app/vendor/rune/crates/rune/src/runtime/scroll/x_tests.rs new file mode 100644 index 0000000..56aba92 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/scroll/x_tests.rs @@ -0,0 +1,371 @@ +use super::*; +use winit::dpi::PhysicalPosition; +use winit::event::MouseScrollDelta::{LineDelta, PixelDelta}; + +#[test] +fn a_gesture_begun_as_one_ends_is_its_momentum_once() { + use crate::{GesturePhase, WheelEvent}; + fn view(_: &(), _: &mut Cx<()>) -> El { + crate::col().w_full().h_full().child(crate::col().w_full().h(300.0) + .scroll(crate::ScrollSpec { stick_bottom: false }).child(crate::el().w_full().h(2000.0))) + } + let mut rt = Runtime::new((), view, (300.0, 300.0), Env::default()); + rt.frame(0.0); + let wheel = |rt: &mut Runtime<()>, phase| rt.wheel_event(WheelEvent::new(0.0, -10.0).at(100.0, 100.0).phase(phase)); + wheel(&mut rt, GesturePhase::Began); + let first = rt.scroll.wheel_lock.gesture; + assert_eq!((rt.scroll.wheel_lock.owner().clone(), rt.scroll.wheel_lock.momentum()), (WheelOwner::Vertical, false)); + wheel(&mut rt, GesturePhase::Ended); + wheel(&mut rt, GesturePhase::Began); + assert!(rt.scroll.wheel_lock.momentum(), "began right as one ended: its momentum"); + assert_eq!((rt.scroll.wheel_lock.gesture, rt.scroll.wheel_lock.owner().clone()), (first, WheelOwner::Vertical), "keeping the gesture"); + wheel(&mut rt, GesturePhase::Ended); + wheel(&mut rt, GesturePhase::Began); + assert!(!rt.scroll.wheel_lock.momentum(), "a finger caught the momentum: a new gesture"); + let second = rt.scroll.wheel_lock.gesture; + assert_ne!(second, first); + + rt.wheel_lost(); + assert_ne!(rt.scroll.wheel_lock.gesture, second); + assert_eq!((rt.scroll.wheel_lock.owner().clone(), rt.scroll.wheel_lock.momentum()), (WheelOwner::Unpicked, false)); + rt.wheel_xy(100.0, 100.0, 0.0, -10.0); + let wheel_gesture = rt.scroll.wheel_lock.gesture; + rt.wheel_xy(100.0, 100.0, -10.0, 0.0); + assert_ne!(rt.scroll.wheel_lock.gesture, wheel_gesture, "without phases, a delta wholly on the other axis starts another"); +} + +/// A viewport whose content fits is passed over: the wheel over a section that is its own +/// viewport, as tall as its rows, scrolls the list around it, on either axis. +#[test] +fn the_wheel_over_a_viewport_with_nothing_to_scroll_scrolls_the_one_around_it() { + fn view(_: &(), _: &mut Cx<()>) -> El { + let fits = crate::col().key("section").w_full().h(200.0).scroll(crate::ScrollSpec { stick_bottom: false }).child(crate::el().w_full().h(200.0)); + let fits_x = crate::row().key("chips").w_full().h(40.0).scroll_x().child(crate::el().w(100.0).h(40.0)); + let list = crate::col().w_full().child(fits_x).child(fits).child(crate::el().w_full().h(2000.0)); + crate::col().key("list").w_full().h(300.0).scroll(crate::ScrollSpec { stick_bottom: false }).child(list) + } + let mut rt = Runtime::new((), view, (300.0, 300.0), Env::default()); + rt.frame(0.0); + rt.frame(1.0 / 60.0); + let id = |rt: &Runtime<()>, key: &str| rt.tree.nodes.iter().find(|n| n.key.as_deref() == Some(key)).unwrap().id; + let (list, section) = (id(&rt, "list"), id(&rt, "section")); + // The strip that fits sideways is no horizontal viewport for the wheel, and over it the list scrolls. + assert_eq!(rt.scroll_at_axis(100.0, 20.0, true), None); + assert_eq!(rt.scroll_at(100.0, 20.0), Some(list)); + rt.wheel_xy(100.0, 100.0, 0.0, -30.0); + assert_eq!((rt.scroll.scrolls[&list].offset, rt.scroll.scrolls[&section].offset), (30.0, 0.0)); +} + +#[test] +fn the_phase_carries_when_the_gesture_last_moved_and_when_it_ended() { + let mut lock = WheelLock::default(); + lock.delta(1.0, 0.0, -10.0, None); + assert_eq!(lock.phase, WheelPhase::Unphased { at: Some(1.0) }, "a delta starts it, timed"); + lock.delta(1.05, 0.0, -10.0, None); + assert_eq!(lock.phase, WheelPhase::Unphased { at: Some(1.05) }, "a pause under the idle keeps the gesture"); + let gesture = lock.gesture; + lock.delta(1.05 + WHEEL_IDLE + 0.01, 0.0, -10.0, None); + assert_ne!(lock.gesture, gesture, "a longer pause starts another"); + assert_eq!(lock.phase, WheelPhase::Unphased { at: Some(1.05 + WHEEL_IDLE + 0.01) }, "timed from the new delta"); + lock.set_owner(lock.gesture, WheelOwner::Vertical); + lock.ended_at(2.0); + assert_eq!(lock.phase, WheelPhase::Ended { at: 2.0, from: GestureKind::Unphased }, "an unphased end keeps its phase"); + let ended = lock.gesture; + lock.delta(2.001, 0.0, -10.0, None); + assert_ne!(lock.gesture, ended, "a delta after the end starts another gesture at once"); + lock.lost(None); + assert_eq!(lock.phase, WheelPhase::Unphased { at: None }, "the loss forgets when it last moved"); +} + +#[test] +fn an_ended_gestures_momentum_has_the_gap_its_end_time_measures() { + let mut lock = WheelLock::default(); + lock.delta(0.0, 0.0, -10.0, None); + lock.set_owner(lock.gesture, WheelOwner::Vertical); + lock.ended_at(1.0); + let gesture = lock.gesture; + let soon = 1.0 + MOMENTUM_GAP * 0.5; + lock.began(soon, true, false, None); + assert_eq!(lock.phase, WheelPhase::Momentum { at: soon }, "within the gap: its momentum"); + assert_eq!(lock.gesture, gesture, "keeping the gesture"); + assert!(lock.momentum()); + lock.ended_at(2.0); + assert_eq!(lock.phase, WheelPhase::Ended { at: 2.0, from: GestureKind::Momentum }); + lock.began(2.0 + MOMENTUM_GAP * 0.5, true, false, None); + assert!(matches!(lock.phase, WheelPhase::Phased { .. }), "one that ended as momentum is a new touch"); + assert!(!lock.momentum()); + + let mut lock = WheelLock::default(); + lock.delta(0.0, 0.0, -10.0, None); + lock.set_owner(lock.gesture, WheelOwner::Vertical); + lock.ended_at(1.0); + let gesture = lock.gesture; + lock.began(1.0 + MOMENTUM_GAP + 0.01, true, false, None); + assert_ne!(lock.gesture, gesture, "after the gap it is its own gesture"); +} + +/// The queued deltas of an unphased gesture that ended before the frame drained them still +/// pick each axis as they arrive: the end doesn't make the gesture phased. +#[test] +fn a_queued_cross_axis_delta_after_an_unphased_end_picks_its_axis() { + fn view(_: &(), _: &mut Cx<()>) -> El { + crate::col().size(200.0, 200.0) + .child(crate::col().key("xy").size(200.0, 200.0).scroll_xy() + .on_wheel(|_: &mut (), _: crate::WheelEvent, _: &mut Tx| false) + .child(crate::el().key("content").w(1000.0).h(1000.0))) + } + use crate::WheelEvent; + let mut rt = Runtime::new((), view, (200.0, 200.0), Env::default()); + rt.frame(0.0); + rt.frame(1.0 / 60.0); + rt.wheel_event(WheelEvent::new(-10.0, 0.0).at(100.0, 100.0)); + rt.wheel_event(WheelEvent::new(0.0, -20.0).at(100.0, 100.0)); + rt.wheel_ended(); + rt.frame(1.0 / 60.0); + let id = rt.tree.nodes.iter().find(|n| n.key.as_deref() == Some("xy")).unwrap().id; + assert_eq!((rt.scroll.scrolls[&id].x.offset, rt.scroll.scrolls[&id].offset), (10.0, 20.0), "each queued delta scrolls the axis it picks"); +} + +/// A phased gesture beginning while an unphased one's deltas wait keeps each delta's own +/// axis policy: the cross-axis one still picks its axis, rather than the successor's +/// phases holding the earlier gesture to its first axis. +#[test] +fn a_delta_queued_before_a_phased_gesture_began_keeps_its_own_axis_policy() { + fn view(_: &(), _: &mut Cx<()>) -> El { + crate::col().size(200.0, 200.0) + .child(crate::col().key("xy").size(200.0, 200.0).scroll_xy() + .on_wheel(|_: &mut (), _: crate::WheelEvent, _: &mut Tx| false) + .child(crate::el().key("content").w(1000.0).h(1000.0))) + } + use crate::WheelEvent; + let mut rt = Runtime::new((), view, (200.0, 200.0), Env::default()); + rt.frame(0.0); + rt.frame(1.0 / 60.0); + rt.wheel_event(WheelEvent::new(-10.0, 0.0).at(100.0, 100.0)); + rt.wheel_event(WheelEvent::new(0.0, -20.0).at(100.0, 100.0)); + rt.wheel_began(); + rt.frame(1.0 / 60.0); + let id = rt.tree.nodes.iter().find(|n| n.key.as_deref() == Some("xy")).unwrap().id; + assert_eq!((rt.scroll.scrolls[&id].x.offset, rt.scroll.scrolls[&id].offset), (10.0, 20.0), "the queued cross-axis delta keeps its own policy"); +} + +/// origin/dev's wheel lock, transcribed from this file: when its last delta came (`at`), +/// whether the gesture was phased and momentum, and when the platform ended it (`ended`), +/// beside the owner, in place of the phase that carries them. +#[derive(Default)] +struct DevLock { + gesture: u32, + run_gesture: u32, + owner: DevOwner, + at: Option<f64>, + phased: bool, + momentum: bool, + ended: Option<f64>, +} + +#[derive(Clone, Copy, Default, PartialEq, Debug)] +enum DevOwner { + #[default] + Unpicked, + Vertical, + Horizontal, +} + +impl DevLock { + fn restart(&mut self, queued: bool) { + self.gesture += 1; + self.phased = false; + self.momentum = false; + self.ended = None; + if !queued { + self.run_gesture = self.gesture; + self.owner = DevOwner::Unpicked; + } + } + + fn delta(&mut self, now: f64, dx: f32, dy: f32, queued: bool) { + let idle = if self.phased { PHASED_IDLE } else { WHEEL_IDLE }; + let flipped = !self.phased && self.run_gesture == self.gesture && match self.owner { + DevOwner::Horizontal => dx == 0.0, + DevOwner::Vertical => dy == 0.0, + DevOwner::Unpicked => false, + }; + let stale = self.ended.is_some() || self.at.is_none_or(|a| now - a > idle) || flipped; + if stale { self.restart(queued); } + self.at = Some(now); + } + + fn began(&mut self, now: f64, active: bool, queued: bool, any_queued: bool) { + let momentum = !self.momentum && (active || queued) && self.ended.is_some_and(|e| now - e <= MOMENTUM_GAP); + if !momentum { self.restart(any_queued); } + self.phased = true; + self.momentum = momentum; + self.ended = None; + self.at = Some(now); + } + + fn lost(&mut self, queued: bool) { + self.restart(queued); + self.at = None; + } + + fn horizontal(&self) -> Option<bool> { + match self.owner { + DevOwner::Unpicked => None, + DevOwner::Vertical => Some(false), + DevOwner::Horizontal => Some(true), + } + } + + fn scroll(&mut self, dx: f32, dy: f32, across: bool) -> bool { + match self.horizontal() { + Some(h) if self.phased || if h { dx != 0.0 } else { dy != 0.0 } => h, + _ => { + self.owner = if across { DevOwner::Horizontal } else { DevOwner::Vertical }; + across + } + } + } +} + +/// The gesture dev's `run_gesture` mirrors: the older one whose queued deltas still wait, +/// else the arriving one. +fn running(lock: &WheelLock) -> Attempt { + match &lock.run { + WheelRun::Waiting { gesture, .. } => *gesture, + WheelRun::Arriving(_) => lock.gesture, + } +} + +/// Who dev's single `owner` mirrors: the owner of the gesture it runs. +fn running_owner(lock: &WheelLock) -> &WheelOwner { + match &lock.run { + WheelRun::Waiting { owner, .. } => owner, + WheelRun::Arriving(owner) => owner, + } +} + +fn owner_kind(owner: &WheelOwner) -> Option<DevOwner> { + match owner { + WheelOwner::Unpicked => Some(DevOwner::Unpicked), + WheelOwner::Vertical => Some(DevOwner::Vertical), + WheelOwner::Horizontal(_) => Some(DevOwner::Horizontal), + // A handler owns the gesture only after `run_wheel` took a delta, which this walk + // never drives. + WheelOwner::Handler(_) => None, + } +} + +#[derive(Clone, Copy, Debug)] +enum WAct { + Delta { dx: f32, dy: f32, gap: f64, queued: bool }, + Began { gap: f64, queued: bool }, + Ended { gap: f64 }, + Lost { queued: bool }, + Scroll { dx: f32, dy: f32, across: bool }, +} + +/// Drives every sequence through the lock and through dev's fields, one event at a time, +/// comparing the phase's facts, the owner and the axis each delta scrolls after every event. +fn wheel_walk(acts: &[WAct]) { + let (mut lock, mut dev, mut now) = (WheelLock::default(), DevLock::default(), 0.0); + for (i, act) in acts.iter().enumerate() { + let before = lock.gesture; + let dev_before = dev.gesture; + match act { + WAct::Delta { dx, dy, gap, queued } => { + now += gap; + let pending = (*queued).then_some(running(&lock)); + lock.delta(now, *dx, *dy, pending); + dev.delta(now, *dx, *dy, *queued); + } + WAct::Began { gap, queued } => { + now += gap; + let active = lock.owner() != &WheelOwner::Unpicked; + let pending = (*queued).then_some(running(&lock)); + lock.began(now, active, *queued, pending); + let dev_active = dev.run_gesture == dev.gesture && dev.owner != DevOwner::Unpicked; + dev.began(now, dev_active, *queued, *queued); + } + WAct::Ended { gap } => { + now += gap; + lock.ended_at(now); + dev.ended = Some(now); + } + WAct::Lost { queued } => { + let pending = (*queued).then_some(running(&lock)); + lock.lost(pending); + dev.lost(*queued); + } + WAct::Scroll { dx, dy, across } => { + // A delta of the gesture dev runs: the older one while its deltas wait, else + // the arriving one. It carries that gesture's own policy. + let gesture = running(&lock); + let h = match lock.keeps_axis(gesture, *dx, *dy, lock.phased()) { + Some(h) => h, + None => lock.repick(gesture, across.then_some(NodeId(1))), + }; + assert_eq!(h, dev.scroll(*dx, *dy, *across), "{acts:?}, event {i}: axis"); + } + } + let at = format!("{acts:?}, event {i} ({act:?})"); + assert_eq!((lock.gesture != before), (dev.gesture != dev_before), "gesture: {at}"); + assert_eq!(lock.phase.phased(), dev.phased, "phased: {at}"); + assert_eq!(lock.phase.momentum(), dev.momentum, "momentum: {at}"); + // An ended phase keeps its end time where dev kept a separate `ended`: the last + // delta's time is no longer read, so only a live phase's is compared. + if dev.ended.is_none() { + assert_eq!(lock.phase.at(), dev.at, "at: {at}"); + } + assert_eq!(lock.phase.ended(), dev.ended, "ended: {at}"); + assert_eq!(owner_kind(running_owner(&lock)), Some(dev.owner), "owner: {at}"); + } +} + +/// Every order of deltas, platform phases, losses and the deltas that later scroll, up to +/// five long, including an unphased gesture that ends with a cross-axis delta queued. +#[test] +fn the_phase_matches_devs_fields_over_every_order() { + let acts = [ + WAct::Delta { dx: -10.0, dy: 0.0, gap: 0.0, queued: false }, + WAct::Delta { dx: -10.0, dy: 0.0, gap: 0.0, queued: true }, + WAct::Delta { dx: 0.0, dy: -20.0, gap: 0.0, queued: false }, + WAct::Delta { dx: 0.0, dy: -20.0, gap: 0.0, queued: true }, + WAct::Delta { dx: -10.0, dy: 0.0, gap: 0.2, queued: false }, + WAct::Ended { gap: 0.0 }, + WAct::Ended { gap: 0.2 }, + WAct::Began { gap: 0.02, queued: false }, + WAct::Began { gap: 0.02, queued: true }, + WAct::Lost { queued: false }, + WAct::Lost { queued: true }, + WAct::Scroll { dx: -10.0, dy: 0.0, across: true }, + WAct::Scroll { dx: 0.0, dy: -20.0, across: true }, + WAct::Scroll { dx: 0.0, dy: -20.0, across: false }, + ]; + for len in 0..=5 { + wheel_walk_all(&acts, len, &mut Vec::new()); + } +} + +fn wheel_walk_all(acts: &[WAct], len: usize, prefix: &mut Vec<WAct>) { + if prefix.len() == len { + wheel_walk(prefix); + return; + } + for &act in acts { + prefix.push(act); + wheel_walk_all(acts, len, prefix); + prefix.pop(); + } +} + +#[test] +fn shift_turns_only_a_purely_vertical_wheel() { + let wheel_delta = |delta, scale, shift| wheel_delta(delta, scale, shift, LINE_POINTS); + assert_eq!(wheel_delta(LineDelta(0.0, -1.0), 2.0, false), (0.0, -LINE_POINTS)); + assert_eq!(wheel_delta(LineDelta(0.0, -1.0), 2.0, true), (-LINE_POINTS, 0.0), "Shift + mouse wheel"); + assert_eq!(wheel_delta(LineDelta(0.5, 0.0), 2.0, false), (LINE_POINTS / 2.0, 0.0), "a fractional horizontal scroll increment"); + let trackpad = PixelDelta(PhysicalPosition::new(-8.0, 20.0)); + assert_eq!(wheel_delta(trackpad, 2.0, true), (-4.0, 10.0), "a delta with a horizontal part stays as it is"); + assert!(SHIFT_TURNS_WHEEL != cfg!(target_os = "macos")); +} diff --git a/app/vendor/rune/crates/rune/src/runtime/select_all_tests.rs b/app/vendor/rune/crates/rune/src/runtime/select_all_tests.rs new file mode 100644 index 0000000..26186c2 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/select_all_tests.rs @@ -0,0 +1,99 @@ +//! Cmd+A with nothing selected: the last clicked group, else the window's only one. +use super::*; +use crate::{Cx, El, Env, Key, KeyEvent, Mods, TextEdit, TextStyle, col, el, text, text_input}; + +#[derive(Default)] +struct S { two: bool, field: TextEdit, app_takes: bool, app_saw: u32 } + +fn view(s: &S, _: &mut Cx<S>) -> El { + let style = TextStyle::new(14.0, 400.0).lh(20.0); + let t = |content: &str, key: &str| text(content.to_owned()).key(key).font(style).w(200.0).selectable(true); + let mut root = col().key("root").size(300.0, 300.0).padding(10.0).focusable(true) + .on_key(|s: &mut S, ev: &KeyEvent, _: &mut Tx| { + let hit = s.app_takes && ev.key == Key::Command('a'); + s.app_saw += u32::from(hit); + hit + }) + .child(col().key("one").selection_group(true).child(t("alpha one", "a0")).child(t("alpha two", "a1"))); + if s.two { + root = root.child(col().key("two").selection_group(true).mt(10.0).child(t("beta one", "b0")).child(t("beta two", "b1"))); + } + root.child(text_input(&s.field, style).key("field").size(200.0, 24.0).mt(10.0).on_edit(|s: &mut S| &mut s.field)) + .child(el().key("blank").size(200.0, 60.0)) +} + +fn runtime(two: bool) -> Runtime<S> { + let mut rt = Runtime::new(S { two, ..S::default() }, view, (300.0, 300.0), Env::new(true, 1.0)); + rt.frame(0.0); + rt +} + +fn center(rt: &Runtime<S>, key: &str) -> (f32, f32) { + let r = rt.elements().into_iter().find(|e| e.key.as_deref() == Some(key)).unwrap().rect; + (r[0] + r[2] * 0.5, r[1] + r[3] * 0.5) +} + +fn click(rt: &mut Runtime<S>, key: &str) { + let (x, y) = center(rt, key); + rt.pointer_down(x, y); + rt.pointer_up(x, y); + rt.frame(0.0); +} + +fn select_all(rt: &mut Runtime<S>) { + rt.key(KeyEvent { key: Key::Command('a'), mods: Mods { cmd: true, ..Mods::default() } }); + rt.frame(0.0); +} + +#[test] +fn the_only_group_is_selected() { + let mut rt = runtime(false); + select_all(&mut rt); + assert_eq!(rt.selected_text().as_deref(), Some("alpha one\nalpha two")); +} + +#[test] +fn the_last_clicked_group_is_selected() { + let mut rt = runtime(true); + click(&mut rt, "b1"); + click(&mut rt, "blank"); + assert_eq!(rt.selected_text(), None); + select_all(&mut rt); + assert_eq!(rt.selected_text().as_deref(), Some("beta one\nbeta two")); +} + +#[test] +fn two_groups_and_no_click_select_nothing() { + let mut rt = runtime(true); + select_all(&mut rt); + assert_eq!(rt.selected_text(), None); +} + +#[test] +fn a_group_that_unmounted_falls_back_to_the_only_one() { + let mut rt = runtime(true); + click(&mut rt, "b0"); + click(&mut rt, "blank"); + rt.update(|s, _| s.two = false); + rt.frame(0.0); + select_all(&mut rt); + assert_eq!(rt.selected_text().as_deref(), Some("alpha one\nalpha two")); +} + +#[test] +fn a_focused_field_keeps_its_own_select_all() { + let mut rt = runtime(false); + click(&mut rt, "field"); + select_all(&mut rt); + assert_eq!(rt.selected_text(), None); +} + +#[test] +fn an_app_that_handles_the_key_keeps_it() { + let mut rt = runtime(false); + rt.state.app_takes = true; + rt.set_focus(Some("root".to_owned()), false); + select_all(&mut rt); + assert_eq!(rt.state.app_saw, 1); + assert_eq!(rt.selected_text(), None); +} diff --git a/app/vendor/rune/crates/rune/src/runtime/selection.rs b/app/vendor/rune/crates/rune/src/runtime/selection.rs new file mode 100644 index 0000000..9d94251 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/selection.rs @@ -0,0 +1,9 @@ +//! Text selection, links, text marks, field click/caret handling and select-all. +use super::*; + +pub(super) mod caret; +pub(super) mod click; +pub(super) mod links; +pub(super) mod select_all; +pub(crate) mod selectable; +pub(super) mod text_marks; diff --git a/app/vendor/rune/crates/rune/src/runtime/selection/caret.rs b/app/vendor/rune/crates/rune/src/runtime/selection/caret.rs new file mode 100644 index 0000000..5cd6216 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/selection/caret.rs @@ -0,0 +1,251 @@ +//! The focused text field's caret in window points, for views (`Cx::caret`) and tools +//! (`ElementInfo::caret`). It comes from layout, not the drawn frame, so a view that reads it +//! is re-measured in the same commit when an edit moves it. +use super::*; + +/// Text selection, links, field click/scroll, caret, IME, spellcheck and clipboard state owned by +/// [`RuntimeCore`]. +pub(crate) struct TextInputState { + /// The selection in `El::selectable` text. + pub(in crate::runtime) selectable: selectable::phase::TextSel, + /// `Tx::text_selection`'s snapshot, kept while neither a commit nor the selection changed. + pub(super) sel_snapshot: std::cell::RefCell<Option<selectable::Snapshot>>, + /// What each `El::on_selection_change` element (by path) last heard. + pub(in crate::runtime) sel_heard: selectable::Heard, + pub(super) links: links::LinkState, + /// Multi-click and drag selection state for `text_input`. + pub(in crate::runtime) input_click: input_click::InputClick, + /// Sideways scroll of focused single-line fields, in points, keyed by node path. + pub(crate) input_scroll: HashMap<String, f32>, + /// The focused field's caret (path, window rect) the next view sees through `Cx::caret`. + pub(in crate::runtime) caret: Option<(String, [f32; 4])>, + /// The last view read the caret, so it re-runs when the caret moves. + pub(in crate::runtime) caret_watch: bool, + /// An edit ran this frame: keep the caret in its scroll viewport after the commit. + pub(in crate::runtime) caret_follow: bool, + /// The composition `App::on_ime` currently has open. + app_ime_comp: app_ime::AppComposition, + /// The `El::ime_cursor` that has the input method asks for Option as Alt (`El::ime_option_as_alt`). + pub(crate) ime_option_as_alt: bool, + /// The shell cancels native composition before enabling the new text focus. + pub(crate) ime_reset: bool, + /// The focused spellchecked field's word at the caret (`spell::pause`). + pub(in crate::runtime) spell_watch: Option<crate::spell::pause::Watch>, + /// Linux's primary selection (`runtime/input/primary_selection.rs`). + #[cfg(target_os = "linux")] + pub(crate) primary: primary_selection::PrimarySelection, + // Outer None: no read; inner None: app-level paste rather than a focused editor. + pub(crate) paste_request: Option<Option<String>>, + /// `Tx::read_clipboard` reads for the shell to start, by id. + pub(crate) read_requests: Vec<u64>, + /// Their callbacks, until the clipboard answers. + pub(in crate::runtime) clipboard_reads: Vec<(u64, crate::el::ReadFn)>, + /// The plain text and pill ranges of this runtime's last copy that held pills, for web + /// clipboard pastes where the OS worker does not own the pasteboard. + pub(in crate::runtime) pill_copy: Option<(zeroize::Zeroizing<String>, Vec<(std::ops::Range<usize>, String)>)>, + pub(in crate::runtime) next_clipboard_read: u64, + pub(crate) clear_secret_request: bool, + /// `Runtime::use_clipboard`: a test clipboard that replaces the OS one. + clipboard: Option<crate::clipboard::MemoryClipboard>, +} + +impl TextInputState { + // Single-caller constructor for `RuntimeCore::new`; inlined so it stays in its caller's + // codegen unit instead of shifting partitioning and dropping inlining in the paint walk. + #[inline] + pub(in crate::runtime) fn new() -> Self { + Self { + selectable: Default::default(), + sel_snapshot: Default::default(), + sel_heard: Default::default(), + links: Default::default(), + input_click: Default::default(), + input_scroll: HashMap::default(), + caret: None, + caret_watch: false, + caret_follow: false, + app_ime_comp: Default::default(), + ime_option_as_alt: false, + ime_reset: false, + spell_watch: None, + #[cfg(target_os = "linux")] + primary: Default::default(), + paste_request: None, + read_requests: Vec::new(), + clipboard_reads: Vec::new(), + pill_copy: None, + next_clipboard_read: 0, + clear_secret_request: false, + clipboard: None, + } + } + + #[inline] + pub(in crate::runtime) fn app_ime_composing(&self) -> bool { + self.app_ime_comp.composing() + } + + #[inline] + pub(in crate::runtime) fn step_app_ime(&mut self, ev: &Ime) { + self.app_ime_comp.step(ev); + } + + #[inline] + pub(in crate::runtime) fn take_app_ime_composing(&mut self) -> Option<String> { + self.app_ime_comp.take_composing() + } + + #[inline] + pub(crate) fn clipboard(&self) -> Option<&crate::clipboard::MemoryClipboard> { + self.clipboard.as_ref() + } + + #[inline] + pub(crate) fn has_clipboard(&self) -> bool { + self.clipboard.is_some() + } + + #[inline] + pub(crate) fn set_clipboard(&mut self, clipboard: crate::clipboard::MemoryClipboard) { + self.clipboard = Some(clipboard); + } + + #[inline] + pub(in crate::runtime) fn single_line_scroll(&self, path: &str) -> f32 { + self.input_scroll.get(path).copied().unwrap_or(0.0) + } + + #[inline] + pub(in crate::runtime) fn set_caret_if_moved(&mut self, next: Option<(&str, [f32; 4])>) -> bool { + let same = match (&self.caret, next) { + (Some((path, rect)), Some((next_path, r))) => path.as_str() == next_path && *rect == r, + (None, None) => true, + _ => false, + }; + if same { return false; } + self.caret = next.map(|(path, r)| (path.to_owned(), r)); + true + } + + #[inline] + pub(in crate::runtime) fn take_clipboard_read(&mut self, id: u64) -> Option<crate::el::ReadFn> { + let i = self.clipboard_reads.iter().position(|(read, _)| *read == id)?; + Some(self.clipboard_reads.remove(i).1) + } + + #[inline] + pub(in crate::runtime) fn has_pill_copy_matching(&self, text: &str, html: &str) -> bool { + self.pill_copy.as_ref().is_some_and(|(t, pills)| { + t.as_str() == text && { + let frag = crate::TextEdit::from_html(html); + frag.pills().count() == pills.len() + && frag.pills().zip(pills).all(|((r1, id1), (r2, id2))| r1 == *r2 && id1 == id2) + } + }) + } + + #[inline] + pub(in crate::runtime) fn set_shift(&mut self, shift: bool) { + self.selectable.shift = shift; + } +} + +impl RuntimeCore { + /// Any vertical shift from ancestor growth rows whose presented height has not settled to layout. + pub(in crate::runtime) fn stack_row_dy(&self, nodes: &[Node], i: usize) -> f32 { + let mut dy = 0.0; + let applied = std::ptr::eq(nodes, self.tree.nodes.as_slice()); + for r in std::iter::successors(Some(i), |&p| nodes[p].parent.filter(|_| nodes[p].above.is_none())) { + let Some(c) = nodes[r].parent.filter(|&c| nodes[c].growth.is_some()) else { continue }; + let Some(stack) = self.motion.stacks.get(&nodes[c].id) else { continue }; + if applied && let Some(&top) = stack.tops.get(&nodes[r].id) { + let mut count = 0usize; + let before_r: f32 = stack.order.iter() + .take_while(|&&id| id != nodes[r].id) + .filter_map(|id| self.motion.grows.get(id)) + .map(|g| { count += 1; g.h }) + .sum::<f32>() + stack.gap * count as f32; + dy += stack.pad_top + before_r - top; + } else if stack.moving { + for j in (c + 1..r).filter(|&j| nodes[j].parent == Some(c)) { + if let Some(g) = self.motion.grows.get(&nodes[j].id) { + dy += g.h - nodes[j].local.h; + } + } + } + } + dy + } + + /// Node `i`'s caret line `[x, y, w, h]` in window points at its laid-out place, after + /// scrolling and sticky shifts, if it is a focused text field. + pub(in crate::runtime) fn caret_rect(&self, nodes: &[Node], i: usize) -> Option<[f32; 4]> { + let n = &nodes[i]; + let (inp, spec, laid) = (n.input.as_ref()?, n.text.as_ref()?, n.text_layout.as_ref()?); + if !inp.edit.focused { return None; } + let layout = laid.view(); + let s = self.env.scale; + let t = sticky::anchored_target(nodes, &self.scroll.scrolls, i, self.viewport); + let y = t[1] + self.stack_row_dy(nodes, i); + let tw = text_width(layout.full_width()) / s; + let (x0, x1) = (t[0] + n.inset[0], t[2] - n.inset[2]); + let mut x = text_x(spec, x0, x1, tw, layout.flow()); + if inp.single_line && let Some(l) = laid.single() { + let prev = self.edit.single_line_scroll(&n.path); + x -= single_line_offset(prev, inp, &spec.content, l, s, (x1 - x0) * s) / s; + } + let bb = layout.caret(caret_index(&inp.edit, &spec.content), inp.edit.affinity, 1.5 * s); + let h = if bb.y1 > bb.y0 { (bb.y1 - bb.y0) as f32 / s } else { spec.style.line_px() }; + Some([x + bb.x0 as f32 / s, y + n.inset[1] + bb.y0 as f32 / s, 1.5, h]) + } + + /// After an edit, scrolls the focused field's nearest scroll viewport on each axis just far + /// enough to show the caret line, as a browser does for a textarea, leaving the viewport's + /// `El::scroll_margin` like CSS `scroll-padding`. + pub(in crate::runtime) fn follow_caret(&mut self, app: &mut dyn AppDriver) { + let Some(i) = self.focused_index() else { return }; + let Some(r) = self.caret_rect(&self.tree.nodes, i) else { return }; + let mut scrolled = false; + for horizontal in [false, true] { + let Some(v) = std::iter::successors(Some(i), |&p| self.tree.nodes[p].parent.filter(|_| self.tree.nodes[p].above.is_none())) + .skip(1) + .find(|&p| self.tree.nodes[p].scroll.is_some() && self.tree.nodes[p].scroll_axes.has(horizontal)) else { continue }; + let a = usize::from(!horizontal); + let start = scroll_offsets(&self.scroll.scrolls, &self.tree.nodes, v).fold(self.tree.nodes[v].target[a], |p, o| p - o[a]); + let view = f64::from(self.tree.nodes[v].target[a + 2] - self.tree.nodes[v].target[a]); + let (at, len) = (f64::from(r[a] - start), f64::from(r[a + 2])); + let margin = f64::from(self.tree.nodes[v].scroll_edges.margin); + let delta = scroll_edge::reveal(0.0, at, len, view, margin); + if delta == 0.0 { continue; } + let stick = self.tree.nodes[v].scroll.is_some_and(|s| s.stick_bottom); + let Some(st) = self.scroll.scrolls.get_mut(&self.tree.nodes[v].id) else { continue }; + if horizontal { + st.x.offset = (st.x.offset + st.x.toward(-delta)).clamp(0.0, st.x.max); + st.x.motion = XMotion::Rest; + } else { + st.offset = (st.offset + delta).clamp(0.0, st.max); + st.land(stick); + scrolled = true; + } + st.moved(); + } + if scrolled && self.virtual_window_changed() { + self.commit(app, &Tx::default()); + self.step_scroll(0.0); + } + } + + /// Refreshes the caret the next view sees from `nodes` (the current frame's when `None`). + /// Returns whether it moved. + pub(in crate::runtime) fn caret_moved(&mut self, nodes: Option<&[Node]>) -> bool { + let nodes = nodes.unwrap_or(&self.tree.nodes); + let next = nodes.iter().position(|n| n.input.as_ref().is_some_and(|inp| inp.edit.focused)) + .and_then(|i| Some((i, self.caret_rect(nodes, i)?))); + let next = next.map(|(i, r)| (nodes[i].path.as_str(), r)); + self.edit.set_caret_if_moved(next) + } +} + +#[cfg(test)] +#[path = "caret_tests.rs"] +mod tests; diff --git a/app/vendor/rune/crates/rune/src/runtime/selection/caret_tests.rs b/app/vendor/rune/crates/rune/src/runtime/selection/caret_tests.rs new file mode 100644 index 0000000..f145655 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/selection/caret_tests.rs @@ -0,0 +1,274 @@ +use crate::{Cx, El, Env, GrowthSpec, Ime, Key, KeyEvent, Mods, Runtime, ScrollSpec, TextEdit, TextStyle, col, text_input}; + +fn make_blocks(count: usize, focus_at: Option<usize>) -> Vec<TextEdit> { + (0..count) + .map(|i| { + let lines = 1 + (i * 5 + 2) % 7; + let text = (0..lines) + .map(|l| format!("block {i} line {l} with prose words to vary height")) + .collect::<Vec<_>>() + .join("\n"); + let mut edit = TextEdit::new(text); + if focus_at == Some(i) { + edit.focused = true; + } + edit + }) + .collect() +} + +fn blocks_view(s: &Vec<TextEdit>, _: &mut Cx<Vec<TextEdit>>) -> El { + let style = TextStyle::new(15.0, 400.0); + let children = s.iter().enumerate().map(|(i, edit)| { + text_input(edit, style) + .key(format!("b{i}")) + .w_full() + .on_edit(move |s: &mut Vec<TextEdit>| &mut s[i]) + .on_submit(move |s: &mut Vec<TextEdit>, _| { + let _ = s[i].insert("\n"); + }) + }); + col().w_full().h_full().padding(20.0).child( + col() + .key("viewport") + .w_full() + .grow(1.0) + .scroll(ScrollSpec { stick_bottom: false }) + .child( + col() + .key("rows") + .w_full() + .gap(10.0) + .children(children) + .growth(GrowthSpec::default()) + .virtualize(36.0), + ), + ) +} + +fn assert_caret_aligned(rt: &Runtime<Vec<TextEdit>>, key: &str, step: &str) { + let els = rt.elements(); + let viewport = els.iter().find(|e| e.key.as_deref() == Some("viewport")).expect("viewport").rect; + let field = els.iter().find(|e| e.key.as_deref() == Some(key)).unwrap_or_else(|| panic!("{step}: {key} not mounted")); + assert!(field.focused, "{step}: {key} should be focused"); + let caret = field.caret.unwrap_or_else(|| panic!("{step}: {key} missing ElementInfo::caret")); + assert!( + caret[0] >= field.rect[0] - 1.0 + && caret[0] + caret[2] <= field.rect[0] + field.rect[2] + 2.0 + && caret[1] >= field.rect[1] - 1.0 + && caret[1] + caret[3] <= field.rect[1] + field.rect[3] + 1.0, + "{step}: caret {caret:?} outside field rect {:?}", + field.rect + ); + assert!( + caret[1] >= viewport[1] - 1.0 && caret[1] + caret[3] <= viewport[1] + viewport[3] + 1.0, + "{step}: caret {caret:?} outside viewport {viewport:?}" + ); + let ime = rt.ime_area.unwrap_or_else(|| panic!("{step}: missing ime_area")); + assert!( + (ime[0] - caret[0]).abs() <= 1.0 && (ime[1] - caret[1]).abs() <= 1.0, + "{step}: ime_area {ime:?} disagrees with caret {caret:?}" + ); +} + +#[test] +fn growth_gap_is_painted_and_included_in_scroll_extent() { + // Cover both a plain growth column and a virtual window. Fixed row heights make + // the expected painted spacing independent of text shaping and estimates. + for virtualized in [false, true] { + let mut rt = Runtime::new(virtualized, |virtualized: &bool, _: &mut Cx<bool>| { + let mut rows = col().key("rows").w_full().gaps(7.0, 19.0) + .growth(GrowthSpec::default()) + .children((0..100).map(|i| crate::el().key(format!("r{i}")).h(20.0).w_full())); + if *virtualized { rows = rows.virtualize(20.0); } + col().w_full().h_full().scroll(ScrollSpec { stick_bottom: false }).child(rows) + }, (300.0, 120.0), Env::new(true, 1.0)); + rt.frame(0.0); + let elements = rt.elements(); + let a = elements.iter().find(|e| e.key.as_deref() == Some("r0")).unwrap(); + let b = elements.iter().find(|e| e.key.as_deref() == Some("r1")).unwrap(); + assert_eq!(b.rect[1] - a.rect[1] - a.rect[3], 7.0, "virtualized={virtualized}"); + assert!((rt.scroll.scrolls.values().next().unwrap().max - 2573.0).abs() < 0.01); + rt.update(|_, tx| tx.scroll_into_view("r99")); + rt.frame(0.0); + let end = rt.elements().into_iter().find(|e| e.key.as_deref() == Some("r99")).unwrap(); + assert!((end.rect[1] + end.rect[3] - 120.0).abs() < 0.01, "last row lands at bottom: {:?}", end.rect); + let commits = rt.stats.commits; + rt.frame(0.0); + assert_eq!(rt.stats.commits, commits, "an idle frame does not recommit"); + } +} + +#[test] +fn offscreen_focus_is_deterministic_and_does_not_resurrect_after_blur_or_removal() { + let mut blocks = make_blocks(240, Some(180)); + blocks[190].focused = true; + let mut rt = Runtime::new(blocks, blocks_view, (640.0, 500.0), Env::new(true, 2.0)); + rt.frame(0.0); + assert!(rt.state[180].focused, "the first offscreen path wins simultaneous requests"); + assert!(!rt.state[190].focused); + rt.update(|s, _| s[180].focused = false); + rt.frame(0.0); + assert!(rt.kbd.focus.path().is_none(), "explicitly blurred offscreen input stays blurred"); + rt.update(|s, _| s[190].focused = true); + rt.frame(0.0); + assert!(rt.state[190].focused); + rt.update(|s, _| { s.truncate(100); }); + rt.frame(0.0); + assert!(rt.kbd.focus.path().is_none(), "deleted offscreen input loses focus"); + rt.update(|s, tx| { s.extend(make_blocks(140, None)); tx.scroll_into_view("b190"); }); + rt.frame(0.0); + assert!(!rt.state[190].focused, "reusing a deleted path must not restore focus"); +} + +#[test] +fn virtual_growth_stack_scroll_into_view_keeps_focus_and_aligns_caret() { + // Focus an initially offscreen far block before the first frame, then reveal and type. + let mut rt = Runtime::new(make_blocks(240, Some(150)), blocks_view, (640.0, 500.0), Env::new(true, 2.0)); + rt.frame(0.0); + assert!(rt.state[150].focused, "offscreen focused field keeps focus across initial commit"); + rt.update(|_, tx| tx.scroll_into_view("b150")); + rt.frame(1.0 / 120.0); + assert_caret_aligned(&rt, "b150", "revealed b150"); + + let before = rt.state[150].text.clone(); + for (step, ch) in ["!", "?", "#"].into_iter().enumerate() { + rt.ime(Ime::Commit(ch.into())); + rt.frame(1.0 / 120.0); + assert_caret_aligned(&rt, "b150", &format!("b150 type {step}")); + } + assert_eq!(rt.state[150].text, format!("{before}!?#")); + + // Focus the last block (239) via update + scroll_into_view and type in the same frame and next frames. + let end_before = rt.state[239].text.clone(); + rt.update(|s, tx| { + s[150].focused = false; + s[239].focused = true; + tx.scroll_into_view("b239"); + }); + for (step, ch) in ["a", "b", "c"].into_iter().enumerate() { + rt.ime(Ime::Commit(ch.into())); + rt.frame(1.0 / 120.0); + assert_caret_aligned(&rt, "b239", &format!("b239 type {step}")); + } + assert_eq!(rt.state[239].text, format!("{end_before}abc")); +} + +#[test] +fn virtual_growth_stack_scrolling_away_and_back_keeps_focus_and_caret_in_rect() { + let mut rt = Runtime::new(make_blocks(240, Some(180)), blocks_view, (640.0, 500.0), Env::new(true, 2.0)); + rt.frame(0.0); + rt.update(|_, tx| tx.scroll_into_view("b180")); + rt.frame(1.0 / 120.0); + assert_caret_aligned(&rt, "b180", "initial reveal b180"); + + let base = rt.state[180].text.clone(); + rt.ime(Ime::Commit(" alpha".into())); + rt.frame(1.0 / 120.0); + assert_eq!(rt.state[180].text, format!("{base} alpha")); + assert_caret_aligned(&rt, "b180", "after alpha"); + + // Scroll all the way up to the top so b180 leaves the mounted window, measuring rows above. + for step in 0..45 { + rt.wheel(320.0, 250.0, 600.0); + rt.frame(1.0 / 120.0); + assert!(rt.state[180].focused, "step {step}: b180 stays focused while scrolling away"); + if let Some(el) = rt.elements().into_iter().find(|e| e.key.as_deref() == Some("b180")) { + let caret = el.caret.expect("mounted b180 has caret"); + assert!( + caret[1] >= el.rect[1] - 1.0 && caret[1] + caret[3] <= el.rect[1] + el.rect[3] + 1.0, + "step {step} up: caret {caret:?} outside rect {:?}", + el.rect + ); + } + } + assert!(rt.find("b180").is_none(), "b180 is culled when scrolled to the top"); + + // Scroll back down in wheel steps until b180 is in the viewport again, checking caret alignment on every mounted frame. + for step in 0..45 { + rt.wheel(320.0, 250.0, -600.0); + rt.frame(1.0 / 120.0); + assert!(rt.state[180].focused, "step {step} down: b180 stays focused while scrolling back"); + if let Some(el) = rt.elements().into_iter().find(|e| e.key.as_deref() == Some("b180")) { + let caret = el.caret.expect("remounted b180 has caret"); + assert!( + caret[1] >= el.rect[1] - 1.0 && caret[1] + caret[3] <= el.rect[1] + el.rect[3] + 1.0, + "step {step} down: caret {caret:?} outside rect {:?}", + el.rect + ); + } + } + rt.update(|_, tx| tx.scroll_into_view("b180")); + rt.frame(1.0 / 120.0); + assert_caret_aligned(&rt, "b180", "revealed back at b180"); + + // Grow a mounted row above b180 and verify caret_rect tracks the active growth shift each frame. + rt.update(|s, _| { + let grown = format!("{}\nextra line 1\nextra line 2\nextra line 3", s[179].text); + s[179] = TextEdit::new(grown); + }); + for frame in 0..10 { + rt.frame(1.0 / 120.0); + assert_caret_aligned(&rt, "b180", &format!("above row growing frame {frame}")); + } + + rt.ime(Ime::Commit(" beta".into())); + rt.frame(1.0 / 120.0); + assert_eq!(rt.state[180].text, format!("{base} alpha beta")); + assert_caret_aligned(&rt, "b180", "after beta"); +} + +#[test] +fn virtual_growth_stack_arrow_key_follow_caret_tracks_drawn_caret() { + let mut blocks = make_blocks(220, None); + blocks[160] = TextEdit::new( + &(0..16).map(|l| format!("tall block line {l}")).collect::<Vec<_>>().join("\n"), + ); + blocks[160].focused = true; + blocks[160].set_caret(0); + let mut rt = Runtime::new(blocks, blocks_view, (640.0, 500.0), Env::new(true, 2.0)); + rt.frame(0.0); + rt.update(|_, tx| tx.scroll_into_view("b160")); + rt.frame(1.0 / 120.0); + // Position the scroll viewport so the top of b160 is near the bottom of the viewport, + // forcing Down arrow steps within b160 to scroll via follow_caret. + rt.wheel(320.0, 250.0, 260.0); + rt.frame(1.0 / 120.0); + assert_caret_aligned(&rt, "b160", "before arrow down"); + + for step in 0..15 { + rt.key(KeyEvent { key: Key::Down, mods: Mods::default() }); + rt.frame(1.0 / 120.0); + assert_caret_aligned(&rt, "b160", &format!("down step {step}")); + } +} + +#[test] +fn follow_caret_leaves_the_scroll_margin_clear_until_the_content_ends() { + let mut edit = TextEdit::new((0..40).map(|l| format!("line {l}")).collect::<Vec<_>>().join("\n")); + edit.focused = true; + let mut rt = Runtime::new(edit, |e: &TextEdit, _: &mut Cx<TextEdit>| { + col().w_full().h_full().child( + col().key("viewport").w_full().h(160.0).scroll(ScrollSpec { stick_bottom: false }).scroll_margin(16.0) + .child(text_input(e, TextStyle::new(13.0, 400.0).lh(20.0)).key("field").w_full().on_edit(|s: &mut TextEdit| s)), + ) + }, (300.0, 400.0), Env::new(true, 2.0)); + rt.frame(0.0); + rt.key(KeyEvent { key: Key::Text("!".into()), mods: Mods::default() }); + rt.frame(1.0 / 120.0); + let rects = |rt: &Runtime<TextEdit>| { + let els = rt.elements(); + let viewport = els.iter().find(|e| e.key.as_deref() == Some("viewport")).unwrap().rect; + let caret = els.iter().find(|e| e.key.as_deref() == Some("field")).unwrap().caret.unwrap(); + (viewport[1], viewport[1] + viewport[3], caret[1], caret[1] + caret[3]) + }; + let (_, bottom, _, low) = rects(&rt); + assert!((low - bottom).abs() < 1.0, "the last line stops flush with the content's end: {low} vs {bottom}"); + for step in 0..20 { + rt.key(KeyEvent { key: Key::Up, mods: Mods::default() }); + rt.frame(1.0 / 120.0); + let (top, bottom, high, low) = rects(&rt); + assert!(high >= top + 16.0 - 0.5, "up {step}: caret top {high} leaves 16 pt under {top}"); + assert!(low <= bottom + 0.5, "up {step}: caret bottom {low} inside {bottom}"); + } +} diff --git a/app/vendor/rune/crates/rune/src/runtime/selection/click.rs b/app/vendor/rune/crates/rune/src/runtime/selection/click.rs new file mode 100644 index 0000000..0f6f255 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/selection/click.rs @@ -0,0 +1,319 @@ +//! Pointer selection in `text_input`: single-click caret placement, click-and-drag character +//! selection, double-click word selection (and word-by-word drag), triple-click line/paragraph +//! selection (and line-by-line drag), and Shift-click selection extension. +//! +//! Word and paragraph boundaries and drag extension share `selectable`'s `Unit`, `unit_at` and +//! `extend`. +use std::collections::VecDeque; + +use super::selectable::{Unit, extend}; +use super::*; + +#[derive(Clone, Copy, Debug)] +enum Step { + Down { clicks: u8, shift: bool }, + Drag, + Cancelled, +} + +#[derive(Clone, Copy)] +pub(in crate::runtime) struct Hit { + pub(in crate::runtime) caret: usize, + /// The side of `caret` the press was on, where two runs of different direction meet. + side: parley::Affinity, + cluster: usize, +} + +/// Whether the runtime's held press belongs to a text field. +#[derive(Default)] +enum Capture { + #[default] + Free, + /// An input-selection press holds the pointer. `dragging` is the field whose selection its + /// moves extend, until focus leaves that field or it unmounts; the press stays the field's. + Held { dragging: Option<String> }, +} + +#[derive(Default)] +pub(in crate::runtime) struct InputClick { + /// The run of non-Shift presses on inputs. + presses: press_run::PressRun, + /// What the press that started the current selection selects by, and the unit range it + /// began on, which a drag keeps whole. They outlive the press: drag steps it queued still + /// read them after the release. + unit: Unit, + origin: (usize, usize), + capture: Capture, + /// Queued press/drag steps paired with `Action::Focus` entries in `Runtime::queue`. + steps: VecDeque<(String, Step)>, +} + +impl InputClick { + pub(in crate::runtime) fn dragging_path(&self) -> Option<&str> { + match &self.capture { + Capture::Held { dragging } => dragging.as_deref(), + Capture::Free => None, + } + } + + /// The runtime's held press is an input-selection press. + pub(in crate::runtime) fn captured(&self) -> bool { matches!(self.capture, Capture::Held { .. }) } + + pub(in crate::runtime) fn clear(&mut self) { + self.presses.clear(); + self.capture = Capture::Free; + self.cancel_drag_steps(); + } + + pub(in crate::runtime) fn clear_last(&mut self) { + self.presses.clear(); + } + + /// The field stops following the press: queued drag steps do nothing, and the press keeps + /// the pointer until it releases. + pub(in crate::runtime) fn drop_drag(&mut self) { + if let Capture::Held { dragging } = &mut self.capture { *dragging = None; } + self.cancel_drag_steps(); + } + + /// Queued drag steps stay, paired with their `Action::Focus` entries, but do nothing. + fn cancel_drag_steps(&mut self) { + for (_, step) in &mut self.steps { + if matches!(step, Step::Drag) { + *step = Step::Cancelled; + } + } + } + + /// The press released: whether it was an input-selection press. + pub(in crate::runtime) fn end_press(&mut self) -> bool { + matches!(std::mem::take(&mut self.capture), Capture::Held { .. }) + } + + pub(in crate::runtime) fn on_focus_change(&mut self, focused: Option<&str>) { + self.presses.keep_on(focused); + if self.dragging_path().is_some_and(|p| Some(p) != focused) { + self.drop_drag(); + } + } +} + +pub(in crate::runtime) fn hit(e: &crate::edit::TextEdit, l: TextFlow<'_>, x: f32, y: f32, s: f32, single: bool) -> Hit { + let h = (l.height() - 1e-3).max(0.0); + let ys = if single || x < 0.0 { (y * s).clamp(0.0, h) } else { (y * s).max(0.0) }; + let at = l.hit(x * s, ys); + let caret = e.model_index(at.index); + let cluster = at.before.map_or(caret, |b| e.model_index(b)); + Hit { caret, side: at.side, cluster } +} + +fn unit_at(e: &crate::edit::TextEdit, h: Hit, unit: Unit) -> (usize, usize) { + if unit == Unit::Char { + let to = e + .pills() + .find_map(|(r, _)| (r.start < h.caret && h.caret < r.end).then(|| if h.caret - r.start < r.end - h.caret { r.start } else { r.end })) + .unwrap_or(h.caret); + return (to, to); + } + if e.is_secure() || (unit == Unit::Paragraph && e.is_single_line()) { + return (0, e.text.len()); + } + let pill = e.pills().find_map(|(r, _)| r.contains(&h.cluster).then_some((r.start, r.end))); + if unit == Unit::Word + && let Some(p) = pill + { + return p; + } + let (mut a, mut b) = super::selectable::unit_at(&e.text, h.cluster, unit); + if let Some((ps, pe)) = pill { + (a, b) = (a.min(ps), b.max(pe)); + } + for (r, _) in e.pills() { + if r.start < a && a < r.end { + a = r.start; + } + if r.start < b && b < r.end { + b = r.end; + } + } + (a, b) +} + +impl RuntimeCore { + /// Window point `(x, y)` in text field `i`'s layout points, using the same `text_x` origin and + /// single-line horizontal scroll rule as paint (`links::origin`). + pub(in crate::runtime) fn input_text_point(&self, i: usize, x: f32, y: f32) -> Option<[f32; 2]> { + let n = &self.tree.nodes[i]; + let (inp, spec, laid) = (n.input.as_deref()?, n.text.as_deref()?, n.text_layout.as_ref()?); + let flow = laid.view(); + let s = self.env.scale; + let valid = self.tree.built && self.paint.drawn.len() == self.tree.nodes.len(); + let (rect, ux, uy) = if valid { self.unturned_box_and_point(i, x, y) } else { (n.target, x, y) }; + let z = if valid { self.paint.drawn_scale.get(i).copied().unwrap_or(1.0).max(1e-4) } else { 1.0 }; + let [mut ox, oy] = links::origin(n, spec, flow, rect, s, z); + if inp.single_line { + ox -= self.edit.single_line_scroll(&n.path) * z; + } + Some([(ux - ox) / z, (uy - oy) / z]) + } + + /// A press at (x, y) on text field `ji`, down at `down_at`; `second` when it's the second + /// of a double press. + pub(in crate::runtime) fn input_down(&mut self, ji: usize, x: f32, y: f32, down_at: f64, second: bool) { + let now = self.now_clock(); + let shift = self.kbd.held_mods.shift; + // Its text drew scaled or rotated with its box: map the press back to the rest layout. + let [lx, ly] = self.to_local(ji, x, y); + let jn = &self.tree.nodes[ji]; + let path = jn.path.clone(); + let r = jn.target; + let clicks = if shift { + self.edit.input_click.presses.clear(); + 1 + } else { + self.edit.input_click.presses.press(&path, now, (x, y), self.double_click_interval).min(3) as u8 + }; + self.edit.input_click.capture = Capture::Held { dragging: Some(path.clone()) }; + self.edit.input_click.steps.push_back((path.clone(), Step::Down { clicks, shift })); + self.frame.queue.push(Action::Focus(path.clone(), x, y)); + let d = Drag { + phase: Phase::Down, + x: lx, + y: ly, + w: r[2] - r[0], + h: r[3] - r[1], + start_x: lx, + start_y: ly, + dx: 0.0, + dy: 0.0, + data: 0.0, + clicks: u32::from(clicks), + cancelled: false, + window: [x, y], + screen: self.screen_at(x, y), + }; + self.pointer.hold_press(capture::Held::new(path, d, crate::PointerButton::Primary, (x, y), down_at, second, None)); + } + + /// Focuses text field `ji` with its caret at (x, y), as a single click does, but holds no + /// press: nothing drags from it (Linux's middle-click paste, `primary_selection.rs`). + #[cfg_attr(not(target_os = "linux"), allow(dead_code))] + pub(in crate::runtime) fn place_caret(&mut self, ji: usize, x: f32, y: f32) { + let path = self.tree.nodes[ji].path.clone(); + self.edit.input_click.presses.clear(); + self.edit.input_click.steps.push_back((path.clone(), Step::Down { clicks: 1, shift: false })); + self.frame.queue.push(Action::Focus(path, x, y)); + } + + pub(in crate::runtime) fn input_drag(&mut self, x: f32, y: f32, drag_move: bool) { + if !drag_move { + return; + } + let Some(path) = self.edit.input_click.dragging_path().map(str::to_owned) else { return }; + if self.pointer.press_held().is_some_and(|h| !press_run::within_slop(h.at, (x, y))) { + self.edit.input_click.presses.clear(); + } + if !self.tree.nodes.iter().enumerate().any(|(i, n)| n.path == path && !self.subtree_exiting(i) && n.input.is_some()) { + self.edit.input_click.drop_drag(); + return; + } + self.edit.input_click.steps.push_back((path.clone(), Step::Drag)); + self.frame.queue.push(Action::Focus(path, x, y)); + } + + pub(in crate::runtime) fn focus_input(&mut self, app: &mut dyn AppDriver, path: String, x: f32, y: f32, one: &mut Tx) -> bool { + let step = if self.edit.input_click.steps.front().is_some_and(|(p, _)| *p == path) { + self.edit.input_click.steps.pop_front().unwrap().1 + } else { + Step::Down { clicks: 1, shift: false } + }; + if matches!(step, Step::Cancelled) { + return false; + } + let Some(i) = self.tree.nodes.iter().enumerate() + .find(|&(i, n)| n.path == path && !self.subtree_exiting(i) && !self.subtree_unmounted(i)) + .map(|(i, _)| i) + else { + self.edit.input_click.drop_drag(); + return false; + }; + let Some(access) = self.tree.nodes[i].input.as_ref().and_then(|inp| inp.access.clone()) else { + self.edit.input_click.drop_drag(); + return false; + }; + let single = self.tree.nodes[i].input.as_ref().is_some_and(|inp| inp.single_line); + let layout = self.tree.nodes[i].text_layout.clone(); + let point = self.input_text_point(i, x, y); + let s = self.env.scale; + match step { + Step::Down { clicks, shift } => { + self.set_focus(app, Some(path), false); + // A press mid-composition writes it into the text first, as a browser's field + // does, then puts the caret where it landed: the layout it hits already shows + // the composition in place. + self.finish_field_composition(app, one); + let e = access(app.states()); + e.set_single_line(single); + e.break_history_group(); + e.clear_typing_style(); + if e.preedit().is_some() { + self.edit.input_click.clear(); + one.commit = one.commit.instant(); + return true; + } + if let (Some(l), Some([tx, ty])) = (layout, point) { + let h = hit(e, l.view(), tx, ty, s, single); + if shift { + let anchor = e.anchor; + self.edit.input_click.unit = Unit::Char; + self.edit.input_click.origin = (anchor, anchor); + e.set_selection(anchor, h.caret); + } else { + let unit = match clicks { + 1 => Unit::Char, + 2 => Unit::Word, + _ => Unit::Paragraph, + }; + let origin = unit_at(e, h, unit); + self.edit.input_click.unit = unit; + self.edit.input_click.origin = origin; + e.set_selection(origin.0, origin.1); + // A caret put down where two runs meet stays on the side pressed. + if origin == (h.caret, h.caret) { e.affinity = h.side; } + } + } + one.commit = one.commit.instant(); + true + } + Step::Drag => { + if self.kbd.focus.path() != Some(path.as_str()) { + self.edit.input_click.drop_drag(); + return false; + } + let e = access(app.states()); + e.set_single_line(single); + if e.preedit().is_some() { + self.edit.input_click.clear(); + return false; + } + let (Some(l), Some([tx, ty])) = (layout, point) else { return false }; + let h = hit(e, l.view(), tx, ty, s, single); + let at = unit_at(e, h, self.edit.input_click.unit); + let (anchor, focus) = extend(self.edit.input_click.origin, at); + let before = (e.anchor, e.focus); + e.set_selection(anchor, focus); + if (e.anchor, e.focus) == before { + return false; + } + e.break_history_group(); + one.commit = one.commit.instant(); + true + } + Step::Cancelled => false, + } + } +} + +#[cfg(test)] +#[path = "../input_click_tests.rs"] +mod tests; diff --git a/app/vendor/rune/crates/rune/src/runtime/selection/copy_html.rs b/app/vendor/rune/crates/rune/src/runtime/selection/copy_html.rs new file mode 100644 index 0000000..06d29d6 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/selection/copy_html.rs @@ -0,0 +1,198 @@ +//! The selection as HTML, for the clipboard's `text/html` beside its plain text, as a browser +//! copies a page's selection: pasted into a document or a mail it keeps its headings, lists, +//! tables, bold, italic, code and links. + +use super::*; + +/// The block a selected text belongs to: the nearest heading, list item, table cell or code +/// text around it (by node index), else the paragraph it is. +#[derive(Clone, Copy, PartialEq, Eq)] +enum Block { + Heading(usize, u8), + Item { list: usize, item: usize, ordered: bool }, + Cell { table: usize, row: usize, cell: usize, head: bool }, + Code(usize), + Paragraph(usize), +} + +impl RuntimeCore { + /// The selection as HTML (`None` with nothing selected, or a selection reaching rows that + /// aren't built). Each selected text sits in its block; its spans are `<strong>`, `<em>` and + /// `<code>`, its links `<a href>` and its strikes `<s>`. + pub(crate) fn copy_html(&self) -> Option<String> { + if self.selection_spans_unmounted() { return None; } + let ranges = self.selection_ranges(); + if ranges.is_empty() { return None; } + let mut out = String::new(); + let mut prev: Option<(Block, usize)> = None; + // The lists open around the last item, outermost first: (list, item, ordered). + let mut lists: Vec<(usize, usize, bool)> = Vec::new(); + let close_lists = |out: &mut String, lists: &mut Vec<(usize, usize, bool)>, keep: usize| { + while lists.len() > keep { + let (_, _, ordered) = lists.pop().unwrap_or_default(); + out.push_str(if ordered { "</li></ol>" } else { "</li></ul>" }); + } + }; + for &(i, a, b) in &ranges { + let Some(spec) = self.tree.nodes[i].text.as_ref() else { continue }; + let block = self.block_of(i); + // A list's markers are the list's own: `<ol>` and `<ul>` draw them. + if self.tree.nodes[i].a11y.hidden && matches!(block, Block::Item { .. }) { continue; } + let inline = inline_html(spec, a, b); + if inline.trim().is_empty() { continue; } + match prev { + Some((p, last)) if p == block => { + if self.beside(last, i) && !out.ends_with(' ') && !inline.starts_with(' ') { out.push(' '); } else if !self.beside(last, i) { out.push_str("<br>"); } + } + _ => { + if let Some((p, _)) = prev.filter(|(p, _)| !matches!(p, Block::Item { .. })) { close(&mut out, p, Some(block)); } + match block { + // A list nested in an item opens inside it; a later item of an outer + // list closes the lists inside first. + Block::Item { list, item, ordered } => { + let keep = lists.iter().rposition(|&(l, it, _)| l == list || self.within(list, it)).map_or(0, |k| k + 1); + close_lists(&mut out, &mut lists, keep); + match lists.last_mut() { + Some(top) if top.0 == list => { + out.push_str("</li><li>"); + top.1 = item; + } + _ => { + out.push_str(if ordered { "<ol><li>" } else { "<ul><li>" }); + lists.push((list, item, ordered)); + } + } + } + _ => { + close_lists(&mut out, &mut lists, 0); + open(&mut out, prev.map(|(p, _)| p), block); + } + } + } + } + out.push_str(&inline); + prev = Some((block, i)); + } + let (p, _) = prev?; + if !matches!(p, Block::Item { .. }) { close(&mut out, p, None); } + close_lists(&mut out, &mut lists, 0); + Some(out) + } + + /// Node `j` is inside node `a`'s subtree. + fn within(&self, j: usize, a: usize) -> bool { + std::iter::successors(self.tree.nodes[j].parent, |&p| self.tree.nodes[p].parent).any(|p| p == a) + } + + fn block_of(&self, i: usize) -> Block { + let mono = self.tree.nodes[i].text.as_ref().is_some_and(|t| matches!(t.style.family, crate::tok::Family::Mono | crate::tok::Family::SystemMono)); + let up = || std::iter::successors(Some(i), |&p| self.tree.nodes[p].parent); + let role = |j: usize| self.tree.nodes[j].role; + for j in up() { + match role(j) { + "heading" => return Block::Heading(j, self.tree.nodes[j].a11y.level.unwrap_or(2).clamp(1, 6) as u8), + "listitem" => { + let list = std::iter::successors(self.tree.nodes[j].parent, |&p| self.tree.nodes[p].parent).find(|&p| role(p) == "list").unwrap_or(j); + // A list whose first item's marker is a number is ordered. + let ordered = self.tree.nodes.get(j + 1).and_then(|n| n.text.as_ref()).is_some_and(|t| t.content.trim_end_matches('.').chars().all(|c| c.is_ascii_digit()) && !t.content.is_empty()); + return Block::Item { list, item: j, ordered }; + } + "cell" | "columnheader" | "rowheader" => { + let ancestors = || std::iter::successors(self.tree.nodes[j].parent, |&p| self.tree.nodes[p].parent); + let row = ancestors().find(|&p| role(p) == "row").unwrap_or(j); + let table = ancestors().find(|&p| role(p) == "table").unwrap_or(row); + return Block::Cell { table, row, cell: j, head: role(j) != "cell" }; + } + _ => {} + } + } + if mono { Block::Code(self.tree.nodes[i].parent.unwrap_or(i)) } else { Block::Paragraph(i) } + } +} + +/// Opens `block`'s elements after `prev`'s closed: a list or table already open stays open. +fn open(out: &mut String, prev: Option<Block>, block: Block) { + match block { + Block::Heading(_, level) => { write!(out, "<h{level}>").ok(); } + // Lists open and close in `copy_html`, which nests them. + Block::Item { .. } => {} + Block::Cell { table, row, head, .. } => { + let (same_table, same_row) = match prev { + Some(Block::Cell { table: t, row: r, .. }) => (t == table, t == table && r == row), + _ => (false, false), + }; + if !same_table { out.push_str("<table>"); } + if !same_row { out.push_str("<tr>"); } + out.push_str(if head { "<th>" } else { "<td>" }); + } + Block::Code(_) => out.push_str("<pre><code>"), + Block::Paragraph(_) => out.push_str("<p>"), + } +} + +/// Closes `block`'s elements before `next`'s open: a list or table `next` continues stays open. +fn close(out: &mut String, block: Block, next: Option<Block>) { + match block { + Block::Heading(_, level) => { write!(out, "</h{level}>").ok(); } + Block::Item { .. } => {} + Block::Cell { table, row, head, .. } => { + out.push_str(if head { "</th>" } else { "</td>" }); + let (same_table, same_row) = match next { + Some(Block::Cell { table: t, row: r, .. }) => (t == table, t == table && r == row), + _ => (false, false), + }; + if !same_row { out.push_str("</tr>"); } + if !same_table { out.push_str("</table>"); } + } + Block::Code(_) => out.push_str("</code></pre>"), + Block::Paragraph(_) => out.push_str("</p>"), + } +} + +use std::fmt::Write; + +/// Bytes `a..b` of `spec` as inline HTML: split where a span, a link or a strike starts or ends. +fn inline_html(spec: &crate::el::TextSpec, a: usize, b: usize) -> String { + let len = spec.content.len(); + let (a, b) = (a.min(len), b.min(len)); + let links = &spec.cold.links; + let strikes = &spec.cold.strikes; + let mut cuts: Vec<usize> = vec![a, b]; + cuts.extend(spec.spans.iter().flat_map(|s| [s.start as usize, s.end as usize])); + cuts.extend(links.iter().flat_map(|l| [l.start as usize, l.end as usize])); + cuts.extend(strikes.iter().flat_map(|s| [s.0 as usize, s.1 as usize])); + cuts.retain(|&c| c >= a && c <= b && spec.content.is_char_boundary(c)); + cuts.sort_unstable(); + cuts.dedup(); + let mut out = String::new(); + let mut href: Option<&str> = None; + for w in cuts.windows(2) { + let (s, e) = (w[0], w[1]); + let Some(text) = spec.copy_slice(s as u32, e as u32) else { continue }; + if text.is_empty() { continue; } + let inside = |x: u32, y: u32| (x as usize) <= s && e <= y as usize; + let bold = spec.spans.iter().any(|sp| inside(sp.start, sp.end) && sp.weight.is_some_and(|w| w >= 600.0)) || spec.style.weight >= 600.0; + let italic = spec.spans.iter().any(|sp| inside(sp.start, sp.end) && sp.italic) && !spec.style.italic; + let code = spec.spans.iter().any(|sp| inside(sp.start, sp.end) && sp.mono); + let struck = strikes.iter().any(|st| inside(st.0, st.1)); + let link = links.iter().find(|l| inside(l.start, l.end)).map(|l| l.id.as_str()).filter(|id| id.contains("://") || id.starts_with("mailto:")); + if href != link { + if href.is_some() { out.push_str("</a>"); } + if let Some(h) = link { write!(out, "<a href=\"{}\">", escape(h)).ok(); } + href = link; + } + let mut piece = escape(&text).replace('\n', "<br>"); + if code { piece = format!("<code>{piece}</code>"); } + if struck { piece = format!("<s>{piece}</s>"); } + if italic { piece = format!("<em>{piece}</em>"); } + // A heading's own weight isn't markup. + if bold && spec.style.weight < 600.0 { piece = format!("<strong>{piece}</strong>"); } + out.push_str(&piece); + } + if href.is_some() { out.push_str("</a>"); } + out +} + +fn escape(s: &str) -> String { + s.replace('&', "&amp;").replace('<', "&lt;").replace('>', "&gt;").replace('"', "&quot;") +} diff --git a/app/vendor/rune/crates/rune/src/runtime/selection/copy_join.rs b/app/vendor/rune/crates/rune/src/runtime/selection/copy_join.rs new file mode 100644 index 0000000..8c75fec --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/selection/copy_join.rs @@ -0,0 +1,73 @@ +//! How copying joins the texts a selection takes: a tab between texts side by side (table +//! cells), else as many newlines as the two texts' [`El::copy_breaks`](crate::El::copy_breaks) +//! ask for (one by default, two for a blank line between paragraphs), and a text's +//! [`El::copy_prefix`](crate::El::copy_prefix) when the copy takes it from its start along with +//! other texts (a list item's `- `). +use std::ops::Range; + +use super::{floor_boundary, trim_uncopied}; +use crate::el::TextSpec; + +/// Copied text, built a selected piece at a time. +#[derive(Default)] +pub(crate) struct CopyJoin { + out: String, + /// The newlines the last piece wants after it. + after: u8, + pieces: usize, + /// The first piece's prefix, in bytes: a copy of one text alone goes without it. + first_prefix: usize, +} + +impl CopyJoin { + /// The text so far. + pub(crate) fn text(&self) -> &str { &self.out } + + /// Adds `piece`, what bytes `range` of `spec` copy as. `beside`: it sits beside the last + /// piece, as a table row's next cell does. `true` when `cap` bytes cut it short. + pub(crate) fn push(&mut self, spec: &TextSpec, range: Range<usize>, piece: &str, beside: bool, cap: usize) -> bool { + let mut lead = String::new(); + if self.pieces > 0 { + if beside { + lead.push('\t'); + } else { + let want = usize::from(self.after.max(spec.cold.copy_breaks[0]).max(1)); + let have = self.out.bytes().rev().take_while(|&b| b == b'\n').count(); + lead.extend(std::iter::repeat_n('\n', want.saturating_sub(have))); + } + } + let prefix = spec.cold.copy_prefix.as_deref().filter(|_| from_start(spec, &range)).unwrap_or(""); + if self.pieces == 0 { + self.first_prefix = prefix.len(); + } + lead.push_str(prefix); + self.pieces += 1; + self.after = spec.cold.copy_breaks[1]; + if self.out.len() + lead.len() > cap { + return true; + } + self.out.push_str(&lead); + if self.out.len() + piece.len() <= cap { + self.out.push_str(piece); + return false; + } + let take = floor_boundary(piece, cap.saturating_sub(self.out.len())); + self.out.push_str(&piece[..take]); + true + } + + /// The copied text: a single text goes without its prefix. + pub(crate) fn finish(mut self) -> String { + if self.pieces == 1 && self.first_prefix > 0 { + self.out.drain(..self.first_prefix); + } + self.out + } +} + +/// `range` takes `spec` from its first copied byte. +fn from_start(spec: &TextSpec, range: &Range<usize>) -> bool { + let len = spec.content.len(); + let first = if spec.cold.uncopied.is_empty() { 0 } else { trim_uncopied(&spec.cold.uncopied, (0, len)).0 }; + !range.is_empty() && range.start <= first +} diff --git a/app/vendor/rune/crates/rune/src/runtime/selection/edge_scroll.rs b/app/vendor/rune/crates/rune/src/runtime/selection/edge_scroll.rs new file mode 100644 index 0000000..6fe4191 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/selection/edge_scroll.rs @@ -0,0 +1,316 @@ +//! A held press extending a selection keeps scrolling its list while the pointer stays at or past +//! the list's top or bottom edge, as an AppKit text view autoscrolls on its periodic events: each +//! step moves the list by an amount that grows with how far past the edge the pointer is. A step +//! is a timer: [`step`] keeps its `Attempt` and asks for the next frame, which feeds it back as +//! `Due`. The frame that takes a step scrolls, lays the list out, and only then extends the +//! selection to the point under the pointer (`Laid`), painting it again if that changed it, so +//! the selection always matches what that frame shows and nothing waits on a later step. A +//! pointer back inside, +//! the end of the list, a step that moved nothing (a list pinned to its bottom pulling it back), +//! and the drag ending stop it. Stopped at an edge it can't scroll past, a press still held there +//! waits without a wake for the list's extent to change (rows arriving at its end): the frame that +//! lays that out looks at the edge again, and goes on if there's room. Each step lets go of a +//! list stuck to its bottom before `step_scroll` can pull it back, so it leaves the bottom however small its steps are; once it +//! stops within half a point of the bottom, the list sticks there again. +use crate::machine::{Attempt, Effects, Seq}; + +use super::*; + +/// Points a second per point the pointer is past the edge. AppKit's `autoscroll:` moves a clip +/// view by the pointer's distance outside it on each periodic event, which a text view's drag asks +/// for every tenth of a second. +const RATE: f32 = 10.0; +/// The least distance past the edge a step counts, so a pointer held at the edge (a window flush +/// with the screen's edge stops it there) still scrolls, at 80 points a second. +const MIN_PAST: f32 = 8.0; +/// The fastest it scrolls, in points a second. +const MAX_SPEED: f32 = 4000.0; +/// How far inside the edge still counts as at it, in points. +const AT: f32 = 1.0; +/// The longest a step covers, so a late frame doesn't jump. +const MAX_STEP: f64 = 0.05; + +/// The edge scroll: stepping one viewport or not, and the attempts its steps carry. +#[derive(Debug, Default)] +pub(in crate::runtime) struct EdgeScroll { + seq: Seq, + state: State, +} + +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub(in crate::runtime) enum State { + #[default] + Idle, + /// Scrolling viewport `scroll`: it last stepped at `last` (clock seconds), from offset `from` + /// when that step moved it, and steps again at `due` as attempt `attempt`. + Running { attempt: Attempt, scroll: NodeId, last: f64, from: Option<f64>, due: f64 }, + /// This frame stepped `scroll` at `last`, whose extent was `max`; once it's laid out the + /// selection follows, and the next step is attempt `next`, or none when this one reached the + /// end. + Laying { next: Option<Attempt>, scroll: NodeId, last: f64, from: Option<f64>, max: f64 }, + /// Held at an edge of `scroll` with nothing left to scroll that way, or whose last step + /// moved nothing, when its extent was `max`: it asks for no frame, and a layout that changes + /// that extent looks at the edge again. + AtEnd { scroll: NodeId, max: f64 }, +} + +/// The held pointer at or past an edge of the viewport the selection is in. +#[derive(Clone, Copy, Debug, PartialEq)] +pub(in crate::runtime) struct Edge { + pub(in crate::runtime) scroll: NodeId, + /// Points a second, positive scrolling down. + pub(in crate::runtime) speed: f32, + /// How much further it can scroll that way, in points. + pub(in crate::runtime) room: f64, + /// Where it has scrolled to, in points. + pub(in crate::runtime) offset: f64, + /// How far it scrolls at most, in points: its content's extent past the viewport. + pub(in crate::runtime) max: f64, +} + +impl Edge { + fn moves(&self) -> bool { self.speed != 0.0 && self.room > 0.0 } +} + +/// Where a pointer at `edge` rests when it doesn't scroll `scroll` (any viewport when `None`): +/// at its end, waiting on its extent, or idle when it isn't at that viewport's edge. +fn rest(edge: Option<Edge>, scroll: Option<NodeId>) -> State { + match edge { + Some(e) if e.speed != 0.0 && scroll.is_none_or(|s| s == e.scroll) => State::AtEnd { scroll: e.scroll, max: e.max }, + _ => State::Idle, + } +} + +pub(in crate::runtime) enum Event { + /// The held pointer moved, to `edge` or away from every edge. + Moved { now: f64, edge: Option<Edge> }, + /// A frame at `now` for the step asked for as `attempt`, with the pointer at `edge`. + Due { attempt: Attempt, now: f64, edge: Option<Edge> }, + /// The frame that stepped has laid the list out. + Laid, + /// A layout changed the extent of the viewport it rests at the end of; the pointer is at + /// `edge`. Grown, it goes on if there's room, and otherwise extends the selection over what + /// came in; shrunk, it stops waiting. + Extent { now: f64, edge: Option<Edge> }, + /// The drag ended. + Stop, +} + +#[derive(Clone, Copy, Debug, PartialEq)] +pub(in crate::runtime) enum Effect { + /// Scroll `scroll` by `by` points. + Scroll { scroll: NodeId, by: f64 }, + /// Extend the selection to the pointer. + Extend, + /// Wake at this clock time, when the next step is due. + WakeAt(f64), +} + +pub(in crate::runtime) fn step(seq: &mut Seq, state: &mut State, event: Event) -> Effects<Effect> { + match event { + Event::Moved { now, edge } => match (edge.filter(Edge::moves), *state) { + (None, _) => { + *state = rest(edge, None); + Effects::none() + } + // The next step reads how far past the edge the pointer is now. + (Some(e), State::Running { scroll, .. }) if scroll == e.scroll => Effects::none(), + (Some(e), _) => { + let attempt = seq.next(); + *state = State::Running { attempt, scroll: e.scroll, last: now, from: None, due: now }; + Effects::one(Effect::WakeAt(now)) + } + }, + Event::Due { attempt, now, edge } => match *state { + State::Running { attempt: armed, scroll, last, from, due } if armed == attempt && now >= due => { + let Some(e) = edge.filter(|e| e.moves() && e.scroll == scroll) else { + *state = rest(edge, Some(scroll)); + return Effects::none(); + }; + // The last step moved nothing: whatever undid it would undo the next, until the + // content changes. + if from.is_some_and(|f| (e.offset - f).abs() <= 1e-9) { + *state = State::AtEnd { scroll, max: e.max }; + return Effects::none(); + } + let by = f64::from(e.speed) * (now - last).clamp(0.0, MAX_STEP); + // A step that reaches the end, or comes within a thousandth of a point of it, + // goes exactly there, and is the last. + let (by, end) = if e.room - by.abs() <= 1e-3 { (e.room.copysign(f64::from(e.speed)), true) } else { (by, false) }; + let next = (!end).then(|| seq.next()); + *state = State::Laying { next, scroll, last: now, from: (by != 0.0).then_some(e.offset), max: e.max }; + let mut effects = Effects::one(Effect::Scroll { scroll, by }); + if !end { effects.push(Effect::WakeAt(now)); } + effects + } + _ => Effects::none(), + }, + Event::Laid => { + let State::Laying { next, scroll, last, from, max } = *state else { return Effects::none() }; + // At the end, a layout that has changed the extent this step saw looks again. + *state = next.map_or(State::AtEnd { scroll, max }, |attempt| State::Running { attempt, scroll, last, from, due: last }); + Effects::one(Effect::Extend) + } + Event::Extent { now, edge } => { + let State::AtEnd { scroll, max } = *state else { return Effects::none() }; + match edge { + // The content it waited at the end of shrank: rows that arrive later aren't the + // ones it waited for. + Some(e) if e.scroll == scroll && e.max < max => { + *state = State::Idle; + Effects::none() + } + Some(e) if e.moves() && e.scroll == scroll => { + let attempt = seq.next(); + *state = State::Running { attempt, scroll, last: now, from: None, due: now }; + Effects::one(Effect::WakeAt(now)) + } + // Grown, with the list already at its new end (one stuck to its bottom follows + // it): the selection follows the pointer over the rows that came in under it. + Some(e) if e.scroll == scroll && e.speed != 0.0 && e.max > max => { + *state = State::AtEnd { scroll, max: e.max }; + Effects::one(Effect::Extend) + } + _ => { + *state = rest(edge, Some(scroll)); + Effects::none() + } + } + } + Event::Stop => { + *state = State::Idle; + Effects::none() + } + } +} + +impl EdgeScroll { + fn step(&mut self, event: Event) -> Effects<Effect> { step(&mut self.seq, &mut self.state, event) } + + /// The attempt the next step carries, while one is asked for. + fn attempt(&self) -> Option<Attempt> { + match self.state { + State::Running { attempt, .. } => Some(attempt), + State::Laying { next, .. } => next, + State::Idle | State::AtEnd { .. } => None, + } + } + + /// Stepping, or about to: not idle, nor resting at an end. + pub(in crate::runtime) fn running(&self) -> bool { matches!(self.state, State::Running { .. } | State::Laying { .. }) } +} + +/// Points a second for a pointer `past` points beyond the edge. +fn speed(past: f32) -> f32 { (RATE * past.max(MIN_PAST)).min(MAX_SPEED) } + +impl caret::TextInputState { + /// The drag ended. + #[inline] + pub(in crate::runtime) fn stop_edge_scroll(&mut self) { + let _ = self.selectable.edge.step(Event::Stop); + } +} + +impl RuntimeCore { + /// The held pointer moved to height `y`: step while it's at or past an edge the selection's + /// viewport can still scroll past, and stop when it isn't. + pub(in crate::runtime) fn edge_scroll_moved(&mut self, y: f32) { + if !self.edit.selectable.phase.dragging() && self.edit.selectable.edge.state == State::Idle { return; } + let edge = self.edge_at(y); + let now = self.now_clock(); + let effects = self.edit.selectable.edge.step(Event::Moved { now, edge }); + self.carry_edge_scroll(effects); + } + + /// Takes the step due by this frame. + pub(in crate::runtime) fn fire_edge_scroll(&mut self) { + let Some(attempt) = self.edit.selectable.edge.attempt() else { return }; + let edge = self.pointer.pos.and_then(|(_, y)| self.edge_at(y)); + let effects = self.edit.selectable.edge.step(Event::Due { attempt, now: self.clock, edge }); + self.carry_edge_scroll(effects); + } + + /// The frame that took a step has laid it out: the selection follows the pointer over that + /// layout, and what changed is heard. True when the selection changed, so the frame paints + /// again. Resting at the end of a list instead, it hears whether this layout changed the + /// list's extent. + pub(in crate::runtime) fn laid_edge_scroll(&mut self, app: &dyn ViewDriver) -> bool { + if !matches!(self.edit.selectable.edge.state, State::Laying { .. }) { return self.edge_scroll_extent(app); } + let changed = self.edge_step_heard(app, Event::Laid); + // A step that reached the end, when this layout changed the extent it saw. + self.edge_scroll_extent(app) | changed + } + + /// A press resting at the end of a list hears that this frame's layout changed the list's + /// extent (rows arrived at its end, or left): it goes on scrolling if it now can, or the + /// selection follows the pointer over what came in. True when the selection changed. + fn edge_scroll_extent(&mut self, app: &dyn ViewDriver) -> bool { + let State::AtEnd { scroll, max } = self.edit.selectable.edge.state else { return false }; + if self.scroll.scrolls.get(&scroll).is_some_and(|st| st.max == max) { return false; } + let edge = self.pointer.pos.and_then(|(_, y)| self.edge_at(y)); + self.edge_step_heard(app, Event::Extent { now: self.clock, edge }) + } + + /// Steps the edge scroll after a layout and carries out what it asks for; what that changed + /// in the selection is heard. True when it changed, so the frame paints again. + fn edge_step_heard(&mut self, app: &dyn ViewDriver, event: Event) -> bool { + let ends = |rt: &Self| rt.edit.selectable.phase.selection().map(|s| (s.anchor, s.focus, s.far.as_ref().map(|f| f.path.clone()))); + let before = ends(self); + let effects = self.edit.selectable.edge.step(event); + self.carry_edge_scroll(effects); + let changed = ends(self) != before; + if changed { + let heard = self.selection_changes(app); + self.frame.queue.extend(heard); + } + changed + } + + fn carry_edge_scroll(&mut self, effects: Effects<Effect>) { + for effect in effects { + match effect { + Effect::Scroll { scroll, by } => self.edge_scroll_by(scroll, by), + Effect::Extend => if let Some((x, y)) = self.pointer.pos { self.selection_drag(x, y) }, + Effect::WakeAt(due) => self.wake_at(due), + } + } + } + + /// Scrolls viewport `id` by `by` points, as the wheel does, except that a list stuck to its + /// bottom lets go of it even when the step leaves it within the half point the wheel pins in. + fn edge_scroll_by(&mut self, id: NodeId, by: f64) { + let Some(st) = self.scroll.scrolls.get_mut(&id) else { return }; + let before = st.offset; + st.offset = (st.offset + by).clamp(0.0, st.max); + st.moved(); + st.land(false); + if st.offset != before { self.pointer.scroll_cancels_press(&self.tree.nodes, id); } + } + + /// Where height `y` is against the edges of the vertical viewport around the selection a + /// held press is extending: at or past its top or bottom (as drawn, inside its clips and the + /// window), how fast that scrolls, and how far it still can. + fn edge_at(&self, y: f32) -> Option<Edge> { + if !self.edit.selectable.phase.dragging() || !self.pointer.pressing() { return None; } + let holder = self.selection_holder()?; + let i = std::iter::successors(Some(holder), |&p| self.tree.nodes[p].parent) + .find(|&p| self.tree.nodes[p].scroll.is_some() && self.tree.nodes[p].scroll_axes.has(false))?; + let id = self.tree.nodes[i].id; + let st = self.scroll.scrolls.get(&id)?; + let clip = self.screen_clip_of_parent(self.tree.nodes[i].parent).map(|v| v / self.env.scale); + let [_, top, _, bottom] = intersect(intersect(self.drawn_edges(i), clip), [0.0, 0.0, self.viewport.0, self.viewport.1]); + if bottom - top <= 2.0 * AT { return None; } + let (speed, room) = if y >= bottom - AT { + (speed(y - (bottom - AT)), st.max - st.offset) + } else if y <= top + AT { + (-speed(top + AT - y), st.offset) + } else { + return None; + }; + Some(Edge { scroll: id, speed, room, offset: st.offset, max: st.max }) + } +} + +#[cfg(test)] +#[path = "edge_scroll_tests.rs"] +mod tests; diff --git a/app/vendor/rune/crates/rune/src/runtime/selection/edge_scroll_tests.rs b/app/vendor/rune/crates/rune/src/runtime/selection/edge_scroll_tests.rs new file mode 100644 index 0000000..fa3ffa9 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/selection/edge_scroll_tests.rs @@ -0,0 +1,677 @@ +use super::*; +use crate::{Cx, El, Env, GrowthSpec, Key, KeyEvent, Mods, PhysicalInput, Runtime, ScrollSpec, TextStyle, col, text}; + +const ROWS: usize = 40; +const ROW_H: f32 = 40.0; +const LIST: &str = "root/scroll/list"; +/// The viewport's bottom edge, in window points. +const BOTTOM: f32 = 120.0; +/// What each row reads. +const LEN: usize = 6; + +/// The list each test builds: virtual rows or plain ones, how many, whether it sticks to its +/// bottom, and whether row 10 is half height. +#[derive(Clone, Copy)] +struct List { + rows: usize, + virtual_rows: bool, + stick: bool, + short: bool, +} + +const VIRTUAL: List = List { rows: ROWS, virtual_rows: true, stick: false, short: false }; +const PLAIN: List = List { rows: ROWS, virtual_rows: false, stick: false, short: false }; + +fn row(s: &List, i: usize) -> El { + let h = if s.short && i == 10 { ROW_H / 2.0 } else { ROW_H }; + text(format!("row {i:02}")).font(TextStyle::new(14.0, 400.0)).w_full().h(h).selectable(true) +} + +fn view(s: &List, _: &mut Cx<List>) -> El { + let list = col().key("list").w_full().growth(GrowthSpec::default()).selection_group(true); + let list = if s.virtual_rows { + list.virtual_rows(s.rows, ROW_H, |_: &List, i| format!("r{i}").into(), |s: &List, i| row(s, i)) + } else { + list.children((0..s.rows).map(|i| row(s, i).key(format!("r{i}")))) + }; + col().key("root").w(300.0).h(BOTTOM).child(col().key("scroll").w_full().h(BOTTOM).scroll(ScrollSpec { stick_bottom: s.stick }).child(list)) +} + +fn window(list: List) -> Runtime<List> { + let mut rt = Runtime::new(list, view, (300.0, BOTTOM), Env::new(true, 1.0)); + settle(&mut rt); + rt +} + +fn settle(rt: &mut Runtime<List>) { + for _ in 0..60 { + if !rt.frame(1.0 / 60.0) { break; } + } +} + +fn offset(rt: &Runtime<List>) -> f64 { rt.scroll.scrolls.values().next().expect("one scroll").offset } + +fn max(rt: &Runtime<List>) -> f64 { rt.scroll.scrolls.values().next().expect("one scroll").max } + +fn row_of(path: &str) -> usize { path.rsplit_once("/r").and_then(|(_, r)| r.parse().ok()).expect("a row path") } + +/// The rows holding the selection's anchor and focus. +fn ends(rt: &Runtime<List>) -> (usize, usize) { + let sel = rt.edit.selectable.phase.selection().expect("a selection"); + (row_of(&sel.path), sel.far.as_ref().map_or(row_of(&sel.path), |f| row_of(&f.path))) +} + +/// The selection's anchor and focus, as (row, byte). +fn range(rt: &Runtime<List>) -> ((usize, usize), (usize, usize)) { + let sel = rt.edit.selectable.phase.selection().expect("a selection"); + let (a, f) = ends(rt); + ((a, sel.anchor), (f, sel.focus)) +} + +/// Presses the start of row 0 and drags `past` points below the list, where it holds still. +fn hold_below_in(list: List, past: f32) -> Runtime<List> { + let mut rt = window(list); + rt.pointer_down(2.0, 20.0); + rt.frame(1.0 / 60.0); + rt.pointer_move(150.0, BOTTOM + past); + rt +} + +fn hold_below(past: f32) -> Runtime<List> { hold_below_in(VIRTUAL, past) } + +#[test] +fn held_still_past_the_bottom_the_list_and_the_selection_keep_going() { + let mut rt = hold_below(200.0); + let (mut last_offset, mut last_focus) = (offset(&rt), 0); + let mut advanced = 0; + for tick in 0..30 { + rt.frame(1.0 / 60.0); + let (anchor, focus) = ends(&rt); + assert_eq!(anchor, 0, "tick {tick}: the anchor stays"); + assert!(offset(&rt) > last_offset, "tick {tick}: the list scrolls under a still pointer"); + assert!(focus >= last_focus, "tick {tick}: the focus only moves down"); + advanced += usize::from(focus > last_focus); + (last_offset, last_focus) = (offset(&rt), focus); + } + assert!(advanced >= 10 && last_focus >= 15, "the selection followed the list: focus row {last_focus}, moved {advanced} times"); + assert!(!rt.commit.virtuals[LIST].range.contains(&0), "the anchor's row scrolled out: {:?}", rt.commit.virtuals[LIST].range); + rt.pointer_up(150.0, BOTTOM + 200.0); + rt.frame(1.0 / 60.0); + let (_, focus) = ends(&rt); + let copied = rt.selected_text().expect("a selection"); + assert!(focus >= last_focus && copied.starts_with("row 00\nrow 01\n") && copied.ends_with(&format!("row {focus:02}")), "{copied:?}"); +} + +#[test] +fn the_step_grows_with_the_distance_past_the_edge() { + let step = |past: f32| { + let mut rt = hold_below(past); + rt.frame(1.0 / 60.0); + let before = offset(&rt); + rt.frame(1.0 / 60.0); + offset(&rt) - before + }; + let (at, near, far) = (step(0.0), step(20.0), step(80.0)); + assert!(at > 0.0, "at the edge it still scrolls"); + assert!(near > at && far > near, "{at} {near} {far}"); + assert!((far - 810.0 / 60.0).abs() < 0.5, "81 points past the band at the edge: 810 points a second, {far} a frame"); +} + +#[test] +fn held_still_above_the_top_it_scrolls_back_up() { + let mut rt = window(VIRTUAL); + rt.wheel(150.0, 60.0, -10_000.0); + settle(&mut rt); + let end = offset(&rt); + assert!(end > 0.0); + rt.pointer_down(296.0, 100.0); + rt.frame(1.0 / 60.0); + rt.pointer_move(150.0, -200.0); + let mut last = end; + for tick in 0..10 { + rt.frame(1.0 / 60.0); + assert!(offset(&rt) < last, "tick {tick}"); + last = offset(&rt); + } + let (anchor, focus) = ends(&rt); + assert!(anchor == ROWS - 1 && focus < ROWS - 5, "the focus followed the list up: {anchor} {focus}"); +} + +#[test] +fn release_stops_it_and_leaves_no_wake() { + let mut rt = hold_below(100.0); + for _ in 0..3 { rt.frame(1.0 / 60.0); } + assert!(rt.edit.selectable.edge.running()); + rt.pointer_up(150.0, BOTTOM + 100.0); + assert!(!rt.edit.selectable.edge.running(), "the release stops it at once"); + rt.frame(1.0 / 60.0); + assert_eq!(rt.wake_deadline(), None, "nothing left to wake for"); + let at = offset(&rt); + settle(&mut rt); + assert_eq!(offset(&rt), at, "the list stays where the release left it"); + assert!(!rt.frame(1.0 / 60.0)); +} + +/// Escape lets go of a selection drag in plain rows, which no drag handler holds, and in virtual +/// rows whose anchor has scrolled out: the list and the selection stay where they are. +#[test] +fn escape_stops_it_and_keeps_the_selection() { + let escapes: [fn(&mut Runtime<List>); 2] = [ + |rt| rt.key(KeyEvent { key: Key::Escape, mods: Mods::default() }), + |rt| rt.physical_input(PhysicalInput::Key { key: crate::PhysicalKeyCode::Escape, mods: Mods::default(), pressed: true, repeat: false }), + ]; + for (list, ticks) in [(PLAIN, 3), (VIRTUAL, 3), (VIRTUAL, 30)] { + for escape in escapes { + let mut rt = hold_below_in(list, 100.0); + for _ in 0..ticks { rt.frame(1.0 / 60.0); } + if ticks == 30 { assert!(!rt.commit.virtuals[LIST].range.contains(&0), "the anchor's row is out"); } + assert!(rt.edit.selectable.edge.running()); + escape(&mut rt); + assert!(!rt.edit.selectable.edge.running(), "Escape stops it at once"); + let (at, selected) = (offset(&rt), range(&rt)); + rt.frame(1.0 / 120.0); + assert_eq!(rt.wake_deadline(), None, "no step asked for"); + for _ in 0..10 { rt.frame(1.0 / 120.0); } + rt.pointer_move(150.0, BOTTOM + 200.0); + for _ in 0..10 { rt.frame(1.0 / 120.0); } + assert_eq!((offset(&rt), range(&rt)), (at, selected), "the list and the selection stay put"); + assert!(!rt.pointer.pressing() && !rt.edit.selectable.phase.dragging()); + } + } +} + +#[test] +fn moving_back_inside_or_losing_focus_stops_it() { + let mut rt = hold_below(100.0); + rt.frame(1.0 / 60.0); + rt.pointer_move(150.0, 60.0); + assert!(!rt.edit.selectable.edge.running(), "back inside"); + let at = offset(&rt); + settle(&mut rt); + assert_eq!(offset(&rt), at); + assert!(rt.edit.selectable.phase.dragging(), "still selecting, only not scrolling"); + + let mut rt = hold_below(100.0); + rt.frame(1.0 / 60.0); + rt.window_focus(true); + rt.window_focus(false); + assert!(!rt.edit.selectable.edge.running(), "focus lost"); + rt.frame(1.0 / 60.0); + assert_eq!(rt.wake_deadline(), None); +} + +/// The step that reaches the end brings the last row in; the one after it, over that layout, +/// selects it, before any release. 371 points past at 60 Hz, the last step goes from 1426 to +/// 1480, which shows row 39 only after it. +#[test] +fn the_last_row_a_scroll_brings_in_is_selected() { + for list in [VIRTUAL, PLAIN] { + for hz in [40.0, 60.0, 120.0] { + for past in [371.0, 100.0, 3000.0] { + let mut rt = hold_below_in(list, past); + let mut ticks = 0; + while rt.edit.selectable.edge.running() { + rt.frame(1.0 / hz); + ticks += 1; + assert!(ticks < 2000, "reached the end"); + } + assert_eq!(offset(&rt), max(&rt)); + assert_eq!(range(&rt), ((0, 0), (ROWS - 1, LEN)), "virtual {} at {hz} Hz, {past} past", list.virtual_rows); + } + } + } +} + +/// The frame whose step brings row 39 in selects it: blurring right after that frame, with no +/// step left to take, leaves the selection at what shows. +#[test] +fn losing_focus_right_after_the_last_row_scrolls_in_keeps_it_selected() { + for (list, past) in [(VIRTUAL, 371.0), (PLAIN, 371.0), (VIRTUAL, 100.0)] { + let mut rt = hold_below_in(list, past); + let mut ticks = 0; + while offset(&rt) < max(&rt) { + rt.frame(1.0 / 60.0); + ticks += 1; + assert!(ticks < 2000, "reached the end"); + } + rt.window_focus(true); + rt.window_focus(false); + assert!(!rt.edit.selectable.edge.running() && !rt.edit.selectable.phase.dragging()); + assert_eq!(range(&rt), ((0, 0), (ROWS - 1, LEN)), "virtual {}, {past} past", list.virtual_rows); + } + // And midway: each frame's selection reaches the last row that frame shows. + let mut rt = hold_below(200.0); + for tick in 0..20 { + rt.frame(1.0 / 60.0); + let shown = ((offset(&rt) + f64::from(BOTTOM)) / f64::from(ROW_H)).ceil() as usize - 1; + assert_eq!(range(&rt).1, (shown, LEN), "tick {tick} at {}", offset(&rt)); + } +} + +#[test] +fn at_the_end_of_the_list_it_stops_asking_for_frames() { + let mut rt = hold_below(400.0); + let mut ticks = 0; + while rt.edit.selectable.edge.running() { + rt.frame(1.0 / 60.0); + ticks += 1; + assert!(ticks < 200, "reached the end"); + } + assert_eq!(offset(&rt), max(&rt), "scrolled to the end"); + assert_eq!(ends(&rt), (0, ROWS - 1), "the selection reaches the last row"); + settle(&mut rt); + assert_eq!(rt.wake_deadline(), None, "no wake while the pointer stays held at the end"); + assert!(!rt.frame(1.0 / 60.0), "an idle frame"); + assert!(rt.pointer.pressing() && rt.edit.selectable.phase.dragging(), "still held"); +} + +/// A list stuck to its bottom lets go of it while the edge scroll runs, however small each step +/// is: at 240 Hz a step at the edge is a third of a point, inside the half point that re-pins it. +/// It travels to the top, then stops waking; no step at 120 Hz is longer than its speed asks. +#[test] +fn a_list_stuck_to_its_bottom_scrolls_up_and_then_rests() { + for hz in [240.0, 120.0] { + let mut rt = window(List { rows: 10, virtual_rows: true, stick: true, short: false }); + rt.wheel(150.0, 60.0, -10_000.0); + settle(&mut rt); + let end = max(&rt); + assert!(end > 0.0 && offset(&rt) == end && rt.scroll.scrolls.values().next().unwrap().pinned(), "pinned at its end"); + rt.pointer_down(296.0, 100.0); + rt.frame(1.0 / hz); + // Inside the band at the top edge: 80 points a second. + rt.pointer_move(150.0, 0.5); + let mut last = offset(&rt); + for tick in 0..120 { + rt.frame(1.0 / hz); + let moved = last - offset(&rt); + assert!(moved > 0.0 && moved <= 80.0 / hz + 1e-6, "{hz} Hz tick {tick}: moved {moved}"); + last = offset(&rt); + } + let mut ticks = 0; + while rt.edit.selectable.edge.running() { + rt.frame(1.0 / hz); + ticks += 1; + assert!(ticks < 2000, "{hz} Hz: reached the top"); + } + assert_eq!(offset(&rt), 0.0, "{hz} Hz"); + rt.frame(1.0 / hz); + assert_eq!(rt.wake_deadline(), None, "{hz} Hz: no wake once at the top"); + } +} + +#[test] +fn an_idle_window_with_no_drag_draws_nothing() { + let mut rt = window(VIRTUAL); + // A placed selection, and a pointer past the edge with no press. + rt.pointer_down(2.0, 20.0); + rt.pointer_move(150.0, 60.0); + rt.pointer_up(150.0, 60.0); + settle(&mut rt); + rt.pointer_move(150.0, BOTTOM + 100.0); + settle(&mut rt); + let commits = rt.stats.commits; + for _ in 0..10 { assert!(!rt.frame(1.0 / 60.0)); } + assert_eq!(rt.wake_deadline(), None); + assert_eq!(rt.stats.commits, commits, "nothing rebuilt"); + assert!(!rt.edit.selectable.edge.running()); + assert_eq!(offset(&rt), 0.0); +} + +fn edge(speed: f32, room: f64, offset: f64) -> Option<Edge> { Some(Edge { scroll: NodeId(7), speed, room, offset, max: 1000.0 }) } + +#[test] +fn a_stale_step_does_nothing() { + let (mut seq, mut state) = (Seq::default(), State::Idle); + let e = edge(600.0, 1000.0, 0.0); + assert_eq!(step(&mut seq, &mut state, Event::Moved { now: 1.0, edge: e }), Effects::one(Effect::WakeAt(1.0))); + let State::Running { attempt: first, .. } = state else { panic!("{state:?}") }; + let _ = step(&mut seq, &mut state, Event::Stop); + assert_eq!(step(&mut seq, &mut state, Event::Due { attempt: first, now: 1.1, edge: e }), Effects::none(), "stopped"); + assert_eq!(state, State::Idle); + let _ = step(&mut seq, &mut state, Event::Moved { now: 1.2, edge: e }); + let held = state; + assert_eq!(step(&mut seq, &mut state, Event::Due { attempt: first, now: 1.3, edge: e }), Effects::none(), "an earlier drag's step"); + assert_eq!(state, held); + let State::Running { attempt, .. } = state else { panic!() }; + assert_ne!(attempt, first); + assert_eq!(step(&mut seq, &mut state, Event::Due { attempt, now: 1.15, edge: e }), Effects::none(), "a frame before it's due"); + assert_eq!(state, held); + let effects = step(&mut seq, &mut state, Event::Due { attempt, now: 1.25, edge: e }); + assert_eq!(effects, Effects::two(Effect::Scroll { scroll: NodeId(7), by: 30.0 }, Effect::WakeAt(1.25)), "600 points a second for 50 ms"); + assert_eq!(step(&mut seq, &mut state, Event::Due { attempt, now: 1.25, edge: e }), Effects::none(), "a step is taken once"); + assert_eq!(step(&mut seq, &mut state, Event::Laid), Effects::one(Effect::Extend), "laid out, the selection follows"); + assert_eq!(step(&mut seq, &mut state, Event::Laid), Effects::none()); +} + +#[test] +fn a_step_stops_at_the_room_left_and_a_late_frame_doesnt_jump() { + let (mut seq, mut state) = (Seq::default(), State::Idle); + let up = |room, offset| edge(-600.0, room, offset); + let _ = step(&mut seq, &mut state, Event::Moved { now: 0.0, edge: up(100.0, 100.0) }); + let State::Running { attempt, .. } = state else { panic!() }; + let effects = step(&mut seq, &mut state, Event::Due { attempt, now: 1.0, edge: up(100.0, 100.0) }); + assert_eq!(effects, Effects::two(Effect::Scroll { scroll: NodeId(7), by: -30.0 }, Effect::WakeAt(1.0)), "a second late steps 50 ms"); + let _ = step(&mut seq, &mut state, Event::Laid); + let State::Running { attempt, .. } = state else { panic!() }; + let effects = step(&mut seq, &mut state, Event::Due { attempt, now: 1.05, edge: up(10.0, 10.0) }); + assert_eq!(effects, Effects::one(Effect::Scroll { scroll: NodeId(7), by: -10.0 }), "the last step asks for no other"); + assert_eq!(step(&mut seq, &mut state, Event::Laid), Effects::one(Effect::Extend), "the selection follows it in the same frame"); + assert_eq!(state, State::AtEnd { scroll: NodeId(7), max: 1000.0 }, "at the end, waiting on the extent"); + let _ = step(&mut seq, &mut state, Event::Moved { now: 2.0, edge: up(0.0, 0.0) }); + assert_eq!(state, State::AtEnd { scroll: NodeId(7), max: 1000.0 }, "nothing left to scroll"); + assert!(step(&mut seq, &mut state, Event::Laid).is_empty()); +} + +/// A step that something undid (here a list pulling itself back to its bottom) ends it, with no +/// wake asked for; a step that moved nothing because no time passed doesn't. +#[test] +fn a_step_that_moved_nothing_ends_it() { + let (mut seq, mut state) = (Seq::default(), State::Idle); + let up = |offset| edge(-60.0, offset, offset); + let _ = step(&mut seq, &mut state, Event::Moved { now: 0.0, edge: up(500.0) }); + let State::Running { attempt, .. } = state else { panic!() }; + assert_eq!(step(&mut seq, &mut state, Event::Due { attempt, now: 0.0, edge: up(500.0) }).into_iter().count(), 2, "no time: no move, and on"); + let _ = step(&mut seq, &mut state, Event::Laid); + let State::Running { attempt, .. } = state else { panic!() }; + let _ = step(&mut seq, &mut state, Event::Due { attempt, now: 0.01, edge: up(500.0) }); + let _ = step(&mut seq, &mut state, Event::Laid); + let State::Running { attempt, .. } = state else { panic!() }; + assert_eq!(step(&mut seq, &mut state, Event::Due { attempt, now: 0.02, edge: up(500.0) }), Effects::none(), "pulled back"); + assert_eq!(state, State::AtEnd { scroll: NodeId(7), max: 1000.0 }, "until the content changes"); +} + +/// Frames until the edge scroll stops stepping. +fn run_out(rt: &mut Runtime<List>) { + let mut ticks = 0; + while rt.edit.selectable.edge.running() { + rt.frame(1.0 / 60.0); + ticks += 1; + assert!(ticks < 2000, "reached the end"); + } +} + +/// Holds below the list until it has scrolled to its end and rests there with no wake. +fn rest_at_end(list: List) -> Runtime<List> { + let mut rt = hold_below_in(list, 400.0); + run_out(&mut rt); + settle(&mut rt); + assert_eq!((offset(&rt), ends(&rt).1), (max(&rt), ROWS - 1), "at the end, the last row selected"); + assert_eq!(rt.wake_deadline(), None, "no wake while it rests"); + assert!(matches!(rt.edit.selectable.edge.state, State::AtEnd { .. }), "{:?}", rt.edit.selectable.edge.state); + rt +} + +/// Held still past the end of a list it scrolled to the end of, rows arriving at that end set it +/// going again: it scrolls to the new end, selecting them, and rests there with no wake again. +#[test] +fn rows_arriving_at_the_end_a_held_drag_rests_at_set_it_going_again() { + for list in [VIRTUAL, PLAIN] { + let mut rt = rest_at_end(list); + let (before, anchor) = (max(&rt), range(&rt).0); + rt.update(|s, _| s.rows += 20); + rt.frame(1.0 / 60.0); + assert!(max(&rt) > before, "virtual {}: the extent grew", list.virtual_rows); + let at = offset(&rt); + for _ in 0..3 { rt.frame(1.0 / 60.0); } + assert!(offset(&rt) > at, "virtual {}: it goes on under a still pointer", list.virtual_rows); + run_out(&mut rt); + settle(&mut rt); + assert_eq!(offset(&rt), max(&rt), "to the new end"); + assert_eq!(range(&rt), (anchor, (ROWS + 19, LEN)), "virtual {}: the new rows selected", list.virtual_rows); + assert_eq!(rt.wake_deadline(), None, "and rests again"); + assert!(!rt.frame(1.0 / 60.0), "an idle frame"); + assert!(rt.pointer.pressing() && rt.edit.selectable.phase.dragging(), "still held"); + } +} + +/// Rows that arrive after the drag let go of the edge (released, Escape, back inside, focus +/// lost) move neither the list nor the selection. +#[test] +fn rows_arriving_after_it_let_go_of_the_end_change_nothing() { + let stops: [(&str, fn(&mut Runtime<List>)); 4] = [ + ("release", |rt| rt.pointer_up(150.0, BOTTOM + 400.0)), + ("escape", |rt| rt.key(KeyEvent { key: Key::Escape, mods: Mods::default() })), + ("inside", |rt| rt.pointer_move(150.0, 60.0)), + ("blur", |rt| { rt.window_focus(true); rt.window_focus(false); }), + ]; + for list in [VIRTUAL, PLAIN] { + for (name, stop) in stops { + let mut rt = rest_at_end(list); + stop(&mut rt); + assert_eq!(rt.edit.selectable.edge.state, State::Idle, "{name}"); + settle(&mut rt); + let (at, selected) = (offset(&rt), range(&rt)); + rt.update(|s, _| s.rows += 20); + settle(&mut rt); + assert_eq!((offset(&rt), range(&rt)), (at, selected), "virtual {} {name}: the list and the selection stay", list.virtual_rows); + assert_eq!(rt.wake_deadline(), None, "{name}"); + } + } +} + +/// A list stuck to its bottom follows rows that arrive there under a still pointer held below +/// it: the selection follows the pointer over them, to the new last row, and it rests there +/// with no wake. +#[test] +fn a_list_stuck_to_its_bottom_brings_new_rows_into_a_held_selection() { + let mut rt = rest_at_end(List { stick: true, ..VIRTUAL }); + assert!(rt.scroll.scrolls.values().next().unwrap().pinned(), "stuck to its bottom"); + let anchor = range(&rt).0; + rt.update(|s, _| s.rows += 20); + let mut frames = 0; + while offset(&rt) < max(&rt) || frames == 0 { + rt.frame(1.0 / 60.0); + frames += 1; + assert!(frames < 600, "the list followed its bottom"); + } + settle(&mut rt); + assert_eq!(offset(&rt), max(&rt), "at the new end"); + assert_eq!(range(&rt), (anchor, (ROWS + 19, LEN)), "the selection reaches the new last row"); + assert_eq!(rt.wake_deadline(), None, "and rests"); + assert!(!rt.frame(1.0 / 60.0), "an idle frame"); + assert!(rt.pointer.pressing() && rt.edit.selectable.phase.dragging(), "still held"); +} + +/// A list that shrinks while a held drag waits at its end ends the wait: rows appended after it +/// move neither the list nor the selection, whose ends both stay. +#[test] +fn a_list_that_shrinks_under_a_resting_drag_ends_the_wait() { + let mut rt = rest_at_end(PLAIN); + let (before, selected) = (max(&rt), range(&rt)); + rt.update(|s, _| s.short = true); + settle(&mut rt); + assert!(max(&rt) < before, "the extent shrank"); + assert_eq!((offset(&rt), range(&rt)), (max(&rt), selected), "at the new end, the selection as it was"); + let at = offset(&rt); + rt.update(|s, _| s.rows += 20); + settle(&mut rt); + assert_eq!((offset(&rt), range(&rt)), (at, selected), "the rows that arrive after it move nothing"); + assert_eq!(rt.wake_deadline(), None); + assert!(rt.pointer.pressing() && rt.edit.selectable.phase.dragging(), "still held"); +} + +/// The edge scroll's letters, as the runtime feeds them: a pointer move, the frame for the step +/// asked for (or an old one's), a stepped layout, a layout that changed the extent, a stop. +#[derive(Clone, Copy, Debug)] +enum Letter { Moved(At), Due(At), Stale, Laid, Extent(At), Stop } + +/// Where the pointer is: inside, at the bottom of viewport 7 with room, with less room than a +/// step, at its end, at its end after more rows arrived or after some left, at the bottom of +/// another viewport. +#[derive(Clone, Copy, Debug)] +enum At { Inside, Room, Near, End, Grown, Shrunk, Other } + +fn at(at: At) -> Option<Edge> { + let e = |scroll, room, offset, max| Some(Edge { scroll: NodeId(scroll), speed: 600.0, room, offset, max }); + match at { + At::Inside => None, + At::Room => e(7, 100.0, 0.0, 100.0), + At::Near => e(7, 3.0, 97.0, 100.0), + At::End => e(7, 0.0, 100.0, 100.0), + At::Grown => e(7, 50.0, 100.0, 150.0), + At::Shrunk => e(7, 0.0, 80.0, 80.0), + At::Other => e(8, 100.0, 0.0, 100.0), + } +} + +/// origin/dev's `edge_scroll::step`, transcribed: its three states, and where it went instead of +/// resting at an end. +#[derive(Clone, Copy, Debug, PartialEq)] +enum Dev { + Idle, + Running { attempt: u32, scroll: NodeId, last: f64, from: Option<f64>, due: f64 }, + Laying { next: Option<u32>, scroll: NodeId, last: f64, from: Option<f64>, + /// differs from dev: the extent the step saw. + max: f64 }, + /// differs from dev: dev went idle wherever this rests. + AtEnd { scroll: NodeId, max: f64 }, +} + +struct Reference { seq: u32, state: Dev } + +impl Reference { + fn next(&mut self) -> u32 { self.seq += 1; self.seq } + + fn moves(e: &Edge) -> bool { e.speed != 0.0 && e.room > 0.0 } + + /// differs from dev: dev went idle; at an edge of `scroll` (any, when `None`) it rests. + fn rest(edge: Option<Edge>, scroll: Option<NodeId>) -> Dev { + match edge { + Some(e) if e.speed != 0.0 && (scroll.is_none() || scroll == Some(e.scroll)) => Dev::AtEnd { scroll: e.scroll, max: e.max }, + _ => Dev::Idle, + } + } + + fn moved(&mut self, now: f64, edge: Option<Edge>) -> Vec<Effect> { + match (edge.filter(Self::moves), self.state) { + (None, _) => { + self.state = Self::rest(edge, None); + vec![] + } + (Some(e), Dev::Running { scroll, .. }) if scroll == e.scroll => vec![], + (Some(e), _) => { + let attempt = self.next(); + self.state = Dev::Running { attempt, scroll: e.scroll, last: now, from: None, due: now }; + vec![Effect::WakeAt(now)] + } + } + } + + fn due(&mut self, attempt: u32, now: f64, edge: Option<Edge>) -> Vec<Effect> { + match self.state { + Dev::Running { attempt: armed, scroll, last, from, due } if armed == attempt && now >= due => { + let Some(e) = edge.filter(|e| Self::moves(e) && e.scroll == scroll) else { + self.state = Self::rest(edge, Some(scroll)); + return vec![]; + }; + if from.is_some_and(|f| (e.offset - f).abs() <= 1e-9) { + // differs from dev: dev went idle. + self.state = Dev::AtEnd { scroll, max: e.max }; + return vec![]; + } + let by = f64::from(e.speed) * (now - last).clamp(0.0, 0.05); + let (by, end) = if e.room - by.abs() <= 1e-3 { (e.room.copysign(f64::from(e.speed)), true) } else { (by, false) }; + let next = if end { None } else { Some(self.next()) }; + self.state = Dev::Laying { next, scroll, last: now, from: if by != 0.0 { Some(e.offset) } else { None }, max: e.max }; + let mut effects = vec![Effect::Scroll { scroll, by }]; + if !end { effects.push(Effect::WakeAt(now)); } + effects + } + _ => vec![], + } + } + + fn laid(&mut self) -> Vec<Effect> { + let Dev::Laying { next, scroll, last, from, max } = self.state else { return vec![] }; + self.state = match next { + Some(attempt) => Dev::Running { attempt, scroll, last, from, due: last }, + // differs from dev: dev went idle. + None => Dev::AtEnd { scroll, max }, + }; + vec![Effect::Extend] + } + + /// differs from dev: dev had no such event; resting at the end, room the layout made goes on. + fn extent(&mut self, now: f64, edge: Option<Edge>) -> Vec<Effect> { + let Dev::AtEnd { scroll, max } = self.state else { return vec![] }; + match edge { + Some(e) if e.scroll == scroll && e.max < max => { + self.state = Dev::Idle; + vec![] + } + Some(e) if Self::moves(&e) && e.scroll == scroll => { + let attempt = self.next(); + self.state = Dev::Running { attempt, scroll, last: now, from: None, due: now }; + vec![Effect::WakeAt(now)] + } + // differs from dev: dev rested at the new extent without extending the selection. + Some(e) if e.scroll == scroll && e.speed != 0.0 && e.max > max => { + self.state = Dev::AtEnd { scroll, max: e.max }; + vec![Effect::Extend] + } + _ => { + self.state = Self::rest(edge, Some(scroll)); + vec![] + } + } + } +} + +fn same(state: &State, dev: &Dev) -> bool { + match (*state, *dev) { + (State::Idle, Dev::Idle) => true, + (State::Running { attempt, scroll, last, from, due }, Dev::Running { attempt: a, scroll: s, last: l, from: f, due: d }) => + (attempt.0, scroll, last, from, due) == (a, s, l, f, d), + (State::Laying { next, scroll, last, from, max }, Dev::Laying { next: n, scroll: s, last: l, from: f, max: m }) => + (next.map(|a| a.0), scroll, last, from, max) == (n, s, l, f, m), + (State::AtEnd { scroll, max }, Dev::AtEnd { scroll: s, max: m }) => (scroll, max) == (s, m), + _ => false, + } +} + +/// Drives `letters` through `step` and the reference, a letter a frame's tenth apart, comparing +/// the effects and the state after every one. +fn walk(letters: &[Letter]) { + let (mut seq, mut state) = (Seq::default(), State::Idle); + let mut dev = Reference { seq: 0, state: Dev::Idle }; + for (i, &letter) in letters.iter().enumerate() { + let now = 1.0 + i as f64 * 0.01; + // The runtime asks for a step with the attempt its state holds; an old one is attempt 0. + let armed = match state { State::Running { attempt, .. } => attempt, State::Laying { next: Some(a), .. } => a, _ => Attempt(0) }; + let (event, theirs) = match letter { + Letter::Moved(a) => (Event::Moved { now, edge: at(a) }, dev.moved(now, at(a))), + Letter::Due(a) => (Event::Due { attempt: armed, now, edge: at(a) }, dev.due(armed.0, now, at(a))), + Letter::Stale => (Event::Due { attempt: Attempt(0), now, edge: at(At::Room) }, dev.due(0, now, at(At::Room))), + Letter::Laid => (Event::Laid, dev.laid()), + Letter::Extent(a) => (Event::Extent { now, edge: at(a) }, dev.extent(now, at(a))), + Letter::Stop => (Event::Stop, { dev.state = Dev::Idle; vec![] }), + }; + let ours: Vec<Effect> = step(&mut seq, &mut state, event).into_iter().collect(); + assert_eq!(ours, theirs, "{letters:?}, letter {i}"); + assert!(same(&state, &dev.state), "{letters:?}, letter {i}: {state:?}, reference {:?}", dev.state); + } +} + +fn walks(alphabet: &[Letter], len: usize, prefix: &mut Vec<Letter>, ran: &mut usize) { + walk(prefix); + *ran += 1; + if prefix.len() == len { return; } + for &letter in alphabet { + prefix.push(letter); + walks(alphabet, len, prefix, ran); + prefix.pop(); + } +} + +#[test] +fn every_short_sequence_steps_as_the_reference_does() { + let ats = [At::Inside, At::Room, At::Near, At::End, At::Grown, At::Shrunk, At::Other]; + let alphabet: Vec<Letter> = ats.iter().map(|&a| Letter::Moved(a)) + .chain(ats.iter().map(|&a| Letter::Due(a))) + .chain(ats.iter().map(|&a| Letter::Extent(a))) + .chain([Letter::Stale, Letter::Laid, Letter::Stop]) + .collect(); + let mut ran = 0; + walks(&alphabet, 5, &mut Vec::new(), &mut ran); + assert_eq!(ran, (0..=5).map(|n| alphabet.len().pow(n)).sum::<usize>()); +} diff --git a/app/vendor/rune/crates/rune/src/runtime/selection/links.rs b/app/vendor/rune/crates/rune/src/runtime/selection/links.rs new file mode 100644 index 0000000..84e6f49 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/selection/links.rs @@ -0,0 +1,583 @@ +//! Pressable spans in text (`El::link`). Each link's line boxes come from the shaped layout, +//! so only its glyphs take the pointer. The text element holds focus for its links and +//! `LinkState::focus` says which one; links are reported to tools as their own elements. +use super::*; +use crate::text::LinkPaint; + +/// The focused text element's focused link. A press's link is the press's +/// (`capture::Held::link`, `capture::Secondary::Held`). +#[derive(Default)] +pub(in crate::runtime) struct LinkState { + focus: Option<usize>, +} + +/// Where node `n`'s text starts inside its border box `rect` (points, x0 y0 x1 y1), its text +/// drawn `k` times its size. +pub(crate) fn origin(n: &Node, spec: &TextSpec, flow: TextFlow<'_>, rect: [f32; 4], s: f32, k: f32) -> [f32; 2] { + let x = text_x(spec, rect[0] + n.inset[0] * k, rect[2] - n.inset[2] * k, text_width(flow.full_width() * k) / s, flow.flow()); + [x, rect[1] + n.inset[1] * k] +} + +/// Link bytes `a..b` of node `n`'s text as bytes of its drawn layout, which truncation may +/// have cut (empty when the cut hides the link). +fn drawn(n: &Node, a: u32, b: u32) -> (u32, u32) { + let (a, b) = n.elided.map_or((a as usize, b as usize), |e| e.mark(a as usize, b as usize, true)); + (a as u32, b as u32) +} + +/// The byte length of node `n`'s drawn text. +fn layout_len(n: &Node, spec: &TextSpec) -> usize { + n.elided.map_or(spec.content.len(), |e| e.drawn_len(spec.content.len())) +} + +/// Line boxes of bytes `start..end` in layout device px, with each box's line index. +fn boxes(layout: &Layout<Ink>, len: usize, start: u32, end: u32) -> Vec<(parley::BoundingBox, usize)> { + let (a, b) = ((start as usize).min(len), (end as usize).min(len)); + crate::text::range_boxes(layout, a, b, false) +} + +/// The link paints to draw this frame, by byte range, with the resting span's `bg_pad`. +pub(in crate::runtime) struct LinkFx(Vec<(u32, u32, LinkPaint, f32, bool)>); + +impl LinkFx { + pub(in crate::runtime) fn is_empty(&self) -> bool { self.0.is_empty() } + + pub(in crate::runtime) fn glyph_color(&self, byte: u32) -> Option<Color> { + self.0.iter().find(|(a, b, p, _, _)| byte >= *a && byte < *b && p.color.is_some()).and_then(|(_, _, p, _, _)| p.color) + } + + pub(in crate::runtime) fn decos_piece(&self, piece: &crate::text::Piece<'_>, len: usize, s: f32, origin: [f32; 2], out: &mut Vec<PaintedDeco>) { + if self.is_empty() { return; } + if piece.is_whole() { return self.decos(piece.layout, len, s, origin, out); } + let clipped: Vec<_> = self.0.iter().filter_map(|&(a, b, p, pad, rings)| { + let (sa, sb) = piece.clip((a as usize).min(len), (b as usize).min(len))?; + Some((sa as u32, sb as u32, p, pad, rings)) + }).collect(); + if !clipped.is_empty() { LinkFx(clipped).decos(piece.layout, piece.shaped(piece.end), s, origin, out); } + } + + /// Backgrounds and underlines (device px, layout top-left at `origin`). + pub(in crate::runtime) fn decos(&self, layout: &Layout<Ink>, len: usize, s: f32, origin: [f32; 2], out: &mut Vec<PaintedDeco>) { + for &(a, b, p, bg_pad, has_rings) in &self.0 { + for (bb, line) in boxes(layout, len, a, b) { + let (x0, w) = (origin[0] + bb.x0 as f32, (bb.x1 - bb.x0) as f32); + if p.bg.is_some() || p.ring.is_some() { + let pad = bg_pad * s; + let (mut y0, mut y1) = ((origin[1] + bb.y0 as f32).round(), (origin[1] + bb.y1 as f32).round()); + if let Some(l) = layout.get(line) { + let base = origin[1] + l.metrics().baseline; + let (mut asc, mut desc) = (0.0f32, 0.0f32); + for run in l.runs() { + let r = run.text_range(); + if r.start < b as usize && (a as usize) < r.end { + let fm = run.font_metrics(); + (asc, desc) = (asc.max(fm.ascent), desc.max(fm.descent.abs())); + } + } + if asc > 0.0 || desc > 0.0 { + y0 = (base - asc - 1.0 * s).round(); + y1 = (base + desc + 1.0 * s).round(); + } + } + let rect = [x0 - pad, y0, w + 2.0 * pad, y1 - y0]; + let ring = p.ring.map(|(c, rw)| (c, rw * s)); + // A ring can split an otherwise uniform link background. Recolor those + // pieces in place, but don't mistake an isolated inline-code background + // for the whole link's hover background. + let contained = |d: &&PaintedDeco| { + d.radius > 0.0 && d.rect[0] >= rect[0] - 1.5 + && d.rect[0] + d.rect[2] <= rect[0] + rect[2] + 1.5 + && d.rect[1] < y1 && y0 < d.rect[1] + d.rect[3] + }; + let split = has_rings && out.iter().filter(contained).any(|d| d.ring.is_some()) + && out.iter().filter(contained).any(|d| (d.rect[0] - rect[0]).abs() < 1.5) + && out.iter().filter(contained).any(|d| (d.rect[0] + d.rect[2] - rect[0] - rect[2]).abs() < 1.5); + let mut matched = false; + for d in out.iter_mut().filter(|d| { + d.radius > 0.0 + && d.rect[0] >= rect[0] - 1.5 + && d.rect[0] + d.rect[2] <= rect[0] + rect[2] + 1.5 + && (split || ((d.rect[0] - rect[0]).abs() < 1.5 && (d.rect[2] - rect[2]).abs() < 1.5)) + && d.rect[1] < y1 + && y0 < d.rect[1] + d.rect[3] + }) { + matched = true; + if let Some(c) = p.bg { + d.color = c; + } + if ring.is_some() { + d.ring = ring; + } + } + if !matched { + out.push(PaintedDeco { deco: Deco { rect, color: p.bg.unwrap_or(Color::TRANSPARENT), radius: 4.0 * s }, ring, byte: b.saturating_sub(1) }); + } + } + if let (Some(c), Some(l)) = (p.underline, layout.get(line)) { + let y = (origin[1] + l.metrics().baseline + 2.0 * s).round(); + let (x0, x1) = crate::text::underline_edges(&l, origin[0], bb.x0 as f32, bb.x1 as f32); + let w = x1 - x0; + if let Some(d) = out.iter_mut().find(|d| { + d.radius == 0.0 + && (d.rect[0] - x0).abs() < 1.5 + && (d.rect[2] - w).abs() < 1.5 + && (d.rect[1] - y).abs() < 1.5 + }) { + d.color = c; + } else { + out.push(PaintedDeco { deco: Deco { rect: [x0, y, w, s.max(1.0)], color: c, radius: 0.0 }, ring: None, byte: 0 }); + } + } + } + } + } +} + +pub(in crate::runtime) fn link_count(n: &Node) -> usize { + n.text.as_ref().map_or(0, |t| t.cold.links.len()) +} + +impl caret::TextInputState { + /// Tab inside the focused text's links: moves to its next (or previous) link and returns + /// true, or false at its last (first) link so Tab leaves it. + #[inline] + pub(in crate::runtime) fn link_tab(&mut self, n: &Node, backward: bool) -> bool { + let count = link_count(n); + let Some(k) = self.links.focus.filter(|_| count > 0) else { return false }; + let next = if backward { k.checked_sub(1) } else { Some(k + 1).filter(|&j| j < count) }; + if next.is_some() { self.links.focus = next; } + next.is_some() + } + + /// Tab focused node `n`: start at its first link, or its last going backward. + #[inline] + pub(in crate::runtime) fn enter_links(&mut self, n: &Node, backward: bool) { + let count = link_count(n); + self.links.focus = (count > 0).then(|| if backward { count - 1 } else { 0 }); + } + + #[inline] + pub(in crate::runtime) fn blur_links(&mut self) { + self.links.focus = None; + } + + /// The focused text's focused link, if any (it may not be in range for that text). + #[inline] + pub(in crate::runtime) fn link_focus(&self) -> Option<usize> { self.links.focus } + + /// Focuses link `k` of the text about to take focus, as Tab into it does. + #[inline] + pub(in crate::runtime) fn set_link_focus(&mut self, k: usize) { self.links.focus = Some(k); } + + /// Whether focused node `n` has a link focused, which takes Return. + #[inline] + pub(in crate::runtime) fn link_focused(&self, n: &Node) -> bool { + self.links.focus.is_some_and(|k| k < link_count(n)) + } + + /// The id of focused node `n`'s focused link, which tools list as its own element. + pub(in crate::runtime) fn focused_link_id(&self, n: &Node) -> Option<String> { + let k = self.links.focus?; + n.text.as_ref()?.cold.links.get(k).map(|l| l.id.clone()) + } +} + +impl RuntimeCore { + /// Node `i`'s border box as drawn this frame (points, x0 y0 x1 y1). + pub(crate) fn drawn_box(&self, i: usize) -> [f32; 4] { + self.paint.drawn.get(i).filter(|d| d[2] > 0.0 || d[3] > 0.0) + .map_or(self.tree.nodes[i].target, |d| [d[0], d[1], d[0] + d[2], d[1] + d[3]]) + } + + /// Inline font-metric boxes `(x0, y0, x1, y1)` in window points for each `(start, end)` byte + /// span in `spans` of node `n`, matching Blink's `Range::getBoundingClientRect()`. + fn span_inline_boxes(&self, n: &Node, rect: [f32; 4], z: f32, spans: impl IntoIterator<Item = (u32, u32)>) -> Vec<(usize, [f32; 4])> { + let (Some(spec), Some(laid)) = (&n.text, &n.text_layout) else { return Vec::new() }; + let flow = laid.view(); + let s = self.env.scale; + let [ox, oy] = origin(n, spec, flow, rect, s, z); + let px = s / z.max(1e-4); + let len = layout_len(n, spec); + let mut out = Vec::new(); + for (k, (start, end)) in spans.into_iter().enumerate() { + let (a, b) = drawn(n, start, end); + for bb in flow.inline_range_boxes((a as usize).min(len), (b as usize).min(len)) { + out.push((k, [ox + bb.x0 as f32 / px, oy + bb.y0 as f32 / px, ox + bb.x1 as f32 / px, oy + bb.y1 as f32 / px])); + } + } + out + } + + /// Line boxes in window points `(x0, y0, x1, y1)` for each `(start, end)` byte span in `spans` + /// of node `n`, inside border box `rect` drawn at scale `z`. + fn span_boxes(&self, n: &Node, rect: [f32; 4], z: f32, spans: impl IntoIterator<Item = (u32, u32)>) -> Vec<(usize, [f32; 4])> { + let (Some(spec), Some(laid)) = (&n.text, &n.text_layout) else { return Vec::new() }; + let flow = laid.view(); + let s = self.env.scale; + let [ox, oy] = origin(n, spec, flow, rect, s, z); + let px = s / z.max(1e-4); + let len = layout_len(n, spec); + let mut out = Vec::new(); + for (k, (start, end)) in spans.into_iter().enumerate() { + let (a, b) = drawn(n, start, end); + for (bb, _) in flow.range_boxes((a as usize).min(len), (b as usize).min(len), false) { + out.push((k, [ox + bb.x0 as f32 / px, oy + bb.y0 as f32 / px, ox + bb.x1 as f32 / px, oy + bb.y1 as f32 / px])); + } + } + out + } + + /// Node `i`'s link line boxes in window points (x0, y0, x1, y1) for border box `rect`. + pub(crate) fn link_boxes(&self, i: usize, rect: [f32; 4]) -> Vec<(usize, [f32; 4])> { + self.link_boxes_in(&self.tree.nodes, i, rect, self.paint.drawn_scale.get(i).copied().unwrap_or(1.0)) + } + + fn link_boxes_in(&self, nodes: &[Node], i: usize, rect: [f32; 4], z: f32) -> Vec<(usize, [f32; 4])> { + let n = &nodes[i]; + let Some(spec) = n.text.as_deref() else { return Vec::new() }; + if spec.cold.links.is_empty() { return Vec::new(); } + self.span_boxes(n, rect, z, spec.cold.links.iter().map(|l| (l.start, l.end))) + } + + /// The link of node `i` under window point (x, y). + pub(in crate::runtime) fn link_at(&self, i: usize, x: f32, y: f32) -> Option<usize> { + if self.tree.nodes[i].text.as_ref().is_none_or(|t| t.cold.links.is_empty()) { return None; } + let (rect, x, y) = self.unturned_box_and_point(i, x, y); + self.link_boxes(i, rect).into_iter() + .find(|(_, r)| contains(*r, x, y)).map(|(k, _)| k) + } + + /// The id of the `Mark::Pill` in text field `i` under window point `(x, y)`, if any. + pub(in crate::runtime) fn input_pill_at(&self, i: usize, x: f32, y: f32) -> Option<String> { + let n = &self.tree.nodes[i]; + let input = n.input.as_deref()?; + if input.edit.is_secure() || input.edit.preedit().is_some() { return None; } + let pills = input.edit.display_pills(); + if pills.is_empty() { return None; } + let (rect, ux, uy) = self.unturned_box_and_point(i, x, y); + let z = self.paint.drawn_scale.get(i).copied().unwrap_or(1.0); + let scroll_x = if input.single_line { self.edit.input_scroll.get(&n.path).copied().unwrap_or(0.0) * z } else { 0.0 }; + self.span_boxes(n, rect, z, pills.iter().map(|&(s, e, _)| (s, e))) + .into_iter() + .find(|(_, r)| contains([r[0] - scroll_x, r[1], r[2] - scroll_x, r[3]], ux, uy)) + .map(|(k, _)| pills[k].2.to_owned()) + } + + /// Hit rects for node `i`: only its links' boxes, clipped like `clipped`. False when it + /// has no links, or is selectable (it takes its whole box). + pub(in crate::runtime) fn push_link_hits(&mut self, i: usize, rect: [f32; 4], clipped: [f32; 4]) -> bool { + if self.tree.nodes[i].text.as_ref().is_none_or(|t| t.cold.links.is_empty() || t.selectable) { return false; } + let id = self.tree.nodes[i].id; + for (_, r) in self.link_boxes(i, rect) { + let c = [r[0].max(clipped[0]), r[1].max(clipped[1]), r[2].min(clipped[2]), r[3].min(clipped[3])]; + if c[2] > c[0] && c[3] > c[1] { self.hit.push_hit(id, c); } + } + true + } + + /// Which of node `i`'s links are hovered, pressed and keyboard-focused. + pub(in crate::runtime) fn link_states(&self, i: usize) -> (Option<usize>, Option<usize>, Option<usize>) { + let path = &self.tree.nodes[i].path; + let hovered = self.pointer.pos.filter(|_| self.pointer.hovered.as_deref() == Some(path)) + .and_then(|(x, y)| self.link_at(i, x, y)); + let pressed = self.pointer.press_held().filter(|h| h.path == *path && h.inside()).and_then(|h| h.link).filter(|&k| hovered == Some(k)); + let focused = self.edit.link_focus().filter(|_| self.kbd.focus.keyboard() && self.kbd.focus.path() == Some(path)); + (hovered, pressed, focused) + } + + /// The paints node `i`'s links show this frame. + pub(in crate::runtime) fn link_fx(&self, i: usize) -> LinkFx { + let Some(spec) = self.tree.nodes[i].text.as_ref().filter(|t| !t.cold.links.is_empty()) else { return LinkFx(Vec::new()) }; + let (hovered, pressed, focused) = self.link_states(i); + let mut fx = Vec::new(); + for (k, l) in spec.cold.links.iter().enumerate() { + let paint = if pressed == Some(k) { + l.pressed.unwrap_or(l.hover) + } else if hovered == Some(k) { + l.hover + } else if focused == Some(k) { + let p = l.focused.unwrap_or(l.hover); + if p.is_empty() { + let ink = spec.spans.iter().filter(|sp| sp.start <= l.start && sp.end > l.start).find_map(|sp| sp.color); + LinkPaint::new().underline(ink.unwrap_or(spec.color)) + } else { p } + } else { continue }; + let (a, b) = drawn(&self.tree.nodes[i], l.start, l.end); + let pad = spec.spans.iter().find(|sp| sp.start < l.end && sp.end > l.start && sp.bg.is_some()).map_or(2.0, |sp| sp.bg_pad); + fx.push((a, b, paint, pad, !spec.cold.rings.is_empty())); + } + LinkFx(fx) + } + + /// Pointer up on text `path` of a press with `button` that began on its link `k`: ending on + /// the same link activates it. + pub(in crate::runtime) fn link_up(&mut self, path: &str, k: usize, x: f32, y: f32, button: crate::PointerButton) { + let Some(i) = self.tree.nodes.iter().position(|n| n.path == path) else { return }; + if self.link_at(i, x, y) == Some(k) { + self.frame.queue.push(Action::Link(path.to_owned(), k, button)); + } + } + + /// Runs the `on_link` handler of node `path` for link `k`. + pub(in crate::runtime) fn press_link(&mut self, app: &mut dyn AppDriver, path: &str, k: usize, tx: &mut Tx) -> bool { + let Some((f, id)) = self.node(path).and_then(|n| { + let t = n.text.as_ref()?; + Some((t.cold.on_link.clone()?, t.cold.links.get(k)?.id.clone())) + }) else { return false }; + log_event!(self, "link {path} {id}"); + (f.0)(app.states(), &id, tx); + true + } + + /// Node `i`'s link under (x, y), if its text takes secondary presses on links. + pub(in crate::runtime) fn secondary_link_at(&self, i: usize, x: f32, y: f32) -> Option<usize> { + self.tree.nodes[i].text.as_ref()?.cold.on_link_secondary.as_ref()?; + self.link_at(i, x, y) + } + + /// Runs the `on_link_secondary` handler of node `path` for link `k`. + pub(in crate::runtime) fn secondary_press_link(&mut self, app: &mut dyn AppDriver, path: &str, k: usize, point: PointerEvent, tx: &mut Tx) -> bool { + let Some((f, id)) = self.node(path).and_then(|n| { + let t = n.text.as_ref()?; + Some((t.cold.on_link_secondary.clone()?, t.cold.links.get(k)?.id.clone())) + }) else { return false }; + log_event!(self, "link secondary {path} {id}"); + (f.0)(app.states(), &id, point.window(), tx); + true + } + + /// Centre of the first drawn line box of the link whose id is `id`, in points. + pub(in crate::runtime) fn find_link(&self, id: &str) -> Option<(f32, f32)> { + (0..self.tree.nodes.len()).filter(|&i| !self.subtree_exiting(i)).find_map(|i| { + let k = self.tree.nodes[i].text.as_ref()?.cold.links.iter().position(|l| l.id == id)?; + let (_, r) = self.link_boxes(i, self.drawn_box(i)).into_iter().find(|(j, _)| *j == k)?; + Some(((r[0] + r[2]) * 0.5, (r[1] + r[3]) * 0.5)) + }) + } + + /// The focused text's focused link, if any (it may not be in range for that text). + #[inline] + pub(crate) fn link_focus(&self) -> Option<usize> { self.edit.link_focus() } + + /// Focuses link `k` of the text about to take focus, as Tab into it does. + #[inline] + pub(crate) fn set_link_focus(&mut self, k: usize) { self.edit.set_link_focus(k); } + + /// The Menu key on focused node `i`'s focused link: its `on_link_secondary`, at the + /// bottom-left of its first line box. + pub(in crate::runtime) fn focused_link_menu(&mut self, app: &mut dyn AppDriver, i: usize, tx: &mut Tx) -> bool { + let Some(k) = self.edit.link_focus().filter(|&k| k < link_count(&self.tree.nodes[i])) else { return false }; + if self.tree.nodes[i].text.as_ref().is_none_or(|t| t.cold.on_link_secondary.is_none()) { return false; } + let Some((_, r)) = self.link_boxes(i, self.drawn_box(i)).into_iter().find(|(j, _)| *j == k) else { return false }; + let path = self.tree.nodes[i].path.clone(); + let point = self.pointer_event(i, r[0], r[3]); + self.secondary_press_link(app, &path, k, point, tx) + } + + /// Enter or Space on a focused link presses it. + pub(in crate::runtime) fn link_key(&mut self, app: &mut dyn AppDriver, i: usize, tx: &mut Tx) -> bool { + let Some(k) = self.edit.link_focus().filter(|&k| k < link_count(&self.tree.nodes[i])) else { return false }; + let path = self.tree.nodes[i].path.clone(); + self.press_link(app, &path, k, tx); + true + } + + /// Reports each link as its own element after its text, which hands it its focus. + pub(in crate::runtime) fn link_elements(&self, elements: &mut Vec<ElementInfo>) { + for i in 0..self.tree.nodes.len() { + let n = &self.tree.nodes[i]; + let Some(spec) = n.text.as_ref().filter(|t| !t.cold.links.is_empty()) else { continue }; + let Some(at) = elements.iter().position(|e| e.path == n.path) else { continue }; + let text = elements[at].clone(); + elements[at].focusable = false; + elements[at].focused = false; + elements[at].focus_visible = false; + let (hovered, pressed, _) = self.link_states(i); + let focused = self.edit.link_focus().filter(|_| self.kbd.focus.path() == Some(&n.path)); + let boxes = self.link_boxes(i, self.drawn_box(i)); + let targets = self.link_boxes_in(&self.tree.nodes, i, n.target, 1.0); + let union = |k: usize, bs: &[(usize, [f32; 4])]| bs.iter().filter(|(j, _)| *j == k).fold(None, |u: Option<[f32; 4]>, (_, r)| { + Some(u.map_or(*r, |u| [u[0].min(r[0]), u[1].min(r[1]), u[2].max(r[2]), u[3].max(r[3])])) + }); + for (k, l) in spec.cold.links.iter().enumerate() { + let Some(r) = union(k, &boxes) else { continue }; + let t = union(k, &targets).unwrap_or(r); + let v = text.visible; + let (x0, y0) = (r[0].max(v[0]), r[1].max(v[1])); + let (x1, y1) = (r[2].min(v[0] + v[2]), r[3].min(v[1] + v[3])); + let words = (!spec.redacted).then(|| spec.source_slice(l.start, l.end).map(str::to_owned)).flatten(); + elements.push(ElementInfo { + stuck: 0.0, + path: format!("{}#link-{k}", n.path), + key: Some(l.id.clone()), + role: l.role, + label: l.label.clone().or_else(|| words.clone()), + text: words, + rect: [r[0], r[1], r[2] - r[0], r[3] - r[1]], + target: [t[0], t[1], t[2] - t[0], t[3] - t[1]], + visible: [x0, y0, (x1 - x0).max(0.0), (y1 - y0).max(0.0)], + focusable: text.focusable, + focused: focused == Some(k), + focus_visible: self.kbd.focus.keyboard() && focused == Some(k), + hover: if hovered == Some(k) { 1.0 } else { 0.0 }, + press: if pressed == Some(k) { 1.0 } else { 0.0 }, + parent: Some(i), + caret: None, + selected: None, + level: None, + expanded: None, + item_selected: false, + help: l.help.clone(), + ..text.clone() + }); + } + } + } + + /// Node `i`'s highlight line boxes in window points (x0, y0, x1, y1) for border box `rect`. + pub(in crate::runtime) fn highlight_boxes(&self, i: usize, rect: [f32; 4]) -> Vec<(usize, [f32; 4])> { + self.highlight_boxes_in(&self.tree.nodes, i, rect, self.paint.drawn_scale.get(i).copied().unwrap_or(1.0)) + } + + pub(in crate::runtime) fn highlight_boxes_in(&self, nodes: &[Node], i: usize, rect: [f32; 4], z: f32) -> Vec<(usize, [f32; 4])> { + let n = &nodes[i]; + let Some(spec) = n.text.as_deref() else { return Vec::new() }; + if spec.cold.highlights.is_empty() || n.is_secure() { return Vec::new(); } + self.span_boxes(n, rect, z, spec.cold.highlights.iter().map(|h| (h.start, h.end))) + } + + /// Unscrolled inline font-metric target rect `[x0, y0, x1, y1]` (in window points) and first + /// node index for the highlight keyed `key` (or scoped `path/key`), matching Blink's + /// `Range::getBoundingClientRect()`. + pub(in crate::runtime) fn highlight_inline_target_in(&self, nodes: &[Node], scope: Option<&str>, key: &str) -> Option<(usize, [f32; 4])> { + let index = self.key_index_for(nodes); + let mut first_node = None; + let mut union: Option<[f32; 4]> = None; + let mut visit = |i: usize| { + let n = &nodes[i]; + let Some(spec) = n.text.as_ref().filter(|t| !t.cold.highlights.is_empty() && !n.is_secure()) else { return }; + if !n.parent.is_none_or(|p| super::in_scope(&nodes[p].path, scope)) { + return; + } + let matches: Vec<_> = spec.cold.highlights.iter().map(|h| h.key.as_deref().is_some_and(|hkey| { + crate::flight::selects_under(key, &n.path, hkey) + })).collect(); + if matches.iter().any(|m| *m) { + for (k, r) in self.span_inline_boxes(n, n.target, 1.0, spec.cold.highlights.iter().map(|h| (h.start, h.end))) { + if matches[k] { + first_node.get_or_insert(i); + union = Some(union.map_or(r, |u| [u[0].min(r[0]), u[1].min(r[1]), u[2].max(r[2]), u[3].max(r[3])])); + } + } + } + }; + match index { + Some(index) => index.marked(key).into_iter().for_each(&mut visit), + None => (0..nodes.len()).for_each(&mut visit), + } + Some((first_node?, union?)) + } + + /// Unscrolled target rect `[x0, y0, x1, y1]` (in window points) and first node index for + /// the highlight keyed `key` (or scoped `path/key`). + pub(in crate::runtime) fn highlight_target_in(&self, nodes: &[Node], scope: Option<&str>, key: &str) -> Option<(usize, [f32; 4])> { + self.highlight_target_with(nodes, self.key_index_for(nodes), scope, key) + } + + /// [`Self::highlight_target_in`], looking only at the nodes `index` lists for `key`. + pub(in crate::runtime) fn highlight_target_with(&self, nodes: &[Node], index: Option<&super::key_index::KeyIndex>, scope: Option<&str>, key: &str) -> Option<(usize, [f32; 4])> { + let mut first_node = None; + let mut union: Option<[f32; 4]> = None; + let mut visit = |i: usize| { + let n = &nodes[i]; + let Some(spec) = n.text.as_ref().filter(|t| !t.cold.highlights.is_empty()) else { return }; + if !n.parent.is_none_or(|p| super::in_scope(&nodes[p].path, scope)) { + return; + } + let matches: Vec<_> = spec.cold.highlights.iter().map(|h| h.key.as_deref().is_some_and(|hkey| { + crate::flight::selects_under(key, &n.path, hkey) + })).collect(); + if matches.iter().any(|m| *m) { + for (k, r) in self.highlight_boxes_in(nodes, i, n.target, 1.0) { + if matches[k] { + first_node.get_or_insert(i); + union = Some(union.map_or(r, |u| [u[0].min(r[0]), u[1].min(r[1]), u[2].max(r[2]), u[3].max(r[3])])); + } + } + } + }; + match index { + Some(index) => index.marked(key).into_iter().for_each(&mut visit), + None => (0..nodes.len()).for_each(&mut visit), + } + Some((first_node?, union?)) + } + + /// Centre of the first drawn line box of the highlight keyed `key`, in points. + pub(in crate::runtime) fn find_highlight(&self, key: &str) -> Option<(f32, f32)> { + (0..self.tree.nodes.len()).filter(|&i| !self.subtree_exiting(i)).find_map(|i| { + let n = &self.tree.nodes[i]; + let k = n.text.as_ref()?.cold.highlights.iter().position(|h| { + h.key.as_deref().is_some_and(|hk| crate::flight::selects_under(key, &n.path, hk)) + })?; + let (_, r) = self.highlight_boxes(i, self.drawn_box(i)).into_iter().find(|(j, _)| *j == k)?; + Some(((r[0] + r[2]) * 0.5, (r[1] + r[3]) * 0.5)) + }) + } + + /// Reports each text highlight as its own `"mark"` element after its text. + pub(in crate::runtime) fn highlight_elements(&self, elements: &mut Vec<ElementInfo>) { + if !self.tree.nodes.iter().any(|n| n.text.as_ref().is_some_and(|t| !t.cold.highlights.is_empty())) { return; } + let text_elements: std::collections::HashMap<_, _> = elements.iter().enumerate().map(|(i, e)| (e.path.clone(), i)).collect(); + for i in 0..self.tree.nodes.len() { + let n = &self.tree.nodes[i]; + let Some(spec) = n.text.as_ref().filter(|t| !t.cold.highlights.is_empty()) else { continue }; + let Some(&at) = text_elements.get(&n.path) else { continue }; + let text = elements[at].clone(); + let boxes = self.highlight_boxes(i, self.drawn_box(i)); + let targets = self.highlight_boxes_in(&self.tree.nodes, i, n.target, 1.0); + let unions = |bs: &[(usize, [f32; 4])]| { + let mut out = vec![None; spec.cold.highlights.len()]; + for &(k, r) in bs { + out[k] = Some(out[k].map_or(r, |u: [f32; 4]| [u[0].min(r[0]), u[1].min(r[1]), u[2].max(r[2]), u[3].max(r[3])])); + } + out + }; + let (boxes, targets) = (unions(&boxes), unions(&targets)); + for (k, h) in spec.cold.highlights.iter().enumerate() { + let Some(r) = boxes[k] else { continue }; + let t = targets[k].unwrap_or(r); + let v = text.visible; + let (x0, y0) = (r[0].max(v[0]), r[1].max(v[1])); + let (x1, y1) = (r[2].min(v[0] + v[2]), r[3].min(v[1] + v[3])); + let words = spec.source_slice(h.start, h.end).map(str::to_owned); + elements.push(ElementInfo { + stuck: 0.0, + path: format!("{}#mark-{k}", n.path), + key: h.key.clone(), + role: "mark", + label: words.clone(), + text: words, + rect: [r[0], r[1], r[2] - r[0], r[3] - r[1]], + target: [t[0], t[1], t[2] - t[0], t[3] - t[1]], + visible: [x0, y0, (x1 - x0).max(0.0), (y1 - y0).max(0.0)], + fill: h.bg, + text_color: h.fg.or(text.text_color), + radius: 4.0, + focusable: false, + focused: false, + focus_visible: false, + hover: 0.0, + press: 0.0, + parent: Some(i), + caret: None, + selected: None, + level: None, + expanded: None, + item_selected: false, + ..text.clone() + }); + } + } + } +} diff --git a/app/vendor/rune/crates/rune/src/runtime/selection/phase.rs b/app/vendor/rune/crates/rune/src/runtime/selection/phase.rs new file mode 100644 index 0000000..b78881a --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/selection/phase.rs @@ -0,0 +1,183 @@ +//! What selectable text holds: nothing, a selection, or a selection a held press is extending. +//! A press, a drag, a release and the ways a selection is made at once or cleared are events, and +//! [`step`] moves between the three; what resolving the selection's texts asks for afterwards +//! (pinning its virtual rows, sealing the texts between its ends) comes back as effects. +use std::collections::HashMap; + +use crate::machine::Effects; + +use super::Unit; +use super::virtual_selection::VirtualEnd; + +/// The selectable-text side of the runtime: the selection's phase, the run of presses that makes +/// double and triple clicks, Shift as the host last reported it, and where Select All goes with +/// no selection. +#[derive(Default)] +pub(in crate::runtime) struct TextSel { + pub(in crate::runtime) phase: Phase, + /// The run of presses on selectable text. + pub(in crate::runtime) presses: crate::runtime::press_run::PressRun, + /// Shift is held (from the host's modifier events), so a press extends the selection. + pub(in crate::runtime) shift: bool, + pub(in crate::runtime) pick: crate::runtime::select_all::Pick, // where Select All goes with no selection + /// Hashes of mounted rows strictly between the selection's anchor and focus in a virtual + /// list. It sits beside the phase so a new selection clears it in place and keeps its + /// buckets; with nothing selected it's empty. + pub(in crate::runtime) mounted_between: HashMap<String, u64>, + /// The list scrolling while the held pointer stays at its edge. + pub(in crate::runtime) edge: super::edge_scroll::EdgeScroll, +} + +#[derive(Default)] +pub(in crate::runtime) enum Phase { + /// No text holds a selection. + #[default] + Empty, + /// A selection no press is making. + Placed(Selection), + /// The held press is extending this selection by `unit`, keeping whole the unit it began on + /// (`Selection::origin`). + Dragging { selection: Selection, unit: Unit }, +} + +impl Phase { + pub(in crate::runtime) fn selection(&self) -> Option<&Selection> { + match self { + Phase::Empty => None, + Phase::Placed(s) | Phase::Dragging { selection: s, .. } => Some(s), + } + } + + pub(in crate::runtime) fn selection_mut(&mut self) -> Option<&mut Selection> { + match self { + Phase::Empty => None, + Phase::Placed(s) | Phase::Dragging { selection: s, .. } => Some(s), + } + } + + /// The held press is extending the selection. + pub(in crate::runtime) fn dragging(&self) -> bool { matches!(self, Phase::Dragging { .. }) } +} + +/// A selection: its anchor in one text and its focus in the same text or, in `far`, another text +/// of its selection group. +pub(in crate::runtime) struct Selection { + /// The text holding the anchor, and its content when last seen. + pub(in crate::runtime) path: String, + pub(in crate::runtime) content: String, + pub(in crate::runtime) anchor: usize, + /// An offset into the anchor's text, or into `far`'s when that's set. + pub(in crate::runtime) focus: usize, + /// The range of the unit the press that made it began on, which a drag keeps whole. + pub(in crate::runtime) origin: (usize, usize), + /// Virtual-list row identity of the anchor when inside a virtual list. + pub(in crate::runtime) anchor_end: Option<VirtualEnd>, + /// The text holding the focus when it's another text of the anchor's selection group. + pub(in crate::runtime) far: Option<Far>, + /// A hash of the texts strictly between the anchor's and the focus's (their paths and + /// content), taken when the selection changes, so a commit that rewrites, adds or removes + /// one drops it. + pub(in crate::runtime) between: u64, +} + +impl Selection { + /// `anchor..focus` in text `path` reading `content`, made from the unit range `origin`. + pub(in crate::runtime) fn new(path: String, content: String, (anchor, focus): (usize, usize), origin: (usize, usize)) -> Self { + Self { path, content, anchor, focus, origin, anchor_end: None, far: None, between: 0 } + } +} + +/// The text of the anchor's group holding a selection's focus. +pub(in crate::runtime) struct Far { + /// Its path and content when last seen. + pub(in crate::runtime) path: String, + pub(in crate::runtime) content: String, + /// Its virtual-list row identity when inside a virtual list. + pub(in crate::runtime) end: Option<VirtualEnd>, +} + +impl Far { + pub(in crate::runtime) fn new(path: String, content: String) -> Self { Self { path, content, end: None } } +} + +/// Where a drag's focus landed: the anchor's text, or another text of its group. +pub(in crate::runtime) enum Reach<'a> { + Anchor, + Far { path: &'a str, content: &'a str }, +} + +pub(in crate::runtime) enum Event<'a> { + /// A primary press placed a new selection, `origin` in text `path`, to be extended by `unit`. + Press { path: String, content: String, unit: Unit, origin: (usize, usize) }, + /// A Shift-press keeps the anchor and moves the focus to `focus`, in `far` or the anchor's + /// text; the drag that follows extends by character. + Extend { focus: usize, far: Option<Far> }, + /// The held press moved the selection's ends to `anchor` and `focus`, the focus in `reach`. + Drag { anchor: usize, focus: usize, reach: Reach<'a> }, + /// The press ended: released, cancelled, lost, or taken by a draggable row. + Release, + /// A selection made at once: Select All, `Tx::select_text`, a secondary press's word. + Select(Selection), + /// The selection goes. + Clear, +} + +/// What the runtime does after a step, in order. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(in crate::runtime) enum Effect { + /// Re-pin the virtual rows the selection's ends are in. + SyncPins, + /// The selection changed shape: re-pin and hash the texts between its ends. + Seal, +} + +pub(in crate::runtime) fn step(phase: &mut Phase, event: Event<'_>) -> Effects<Effect> { + match event { + Event::Press { path, content, unit, origin } => { + *phase = Phase::Dragging { selection: Selection::new(path, content, origin, origin), unit }; + Effects::one(Effect::Seal) + } + Event::Extend { focus, far } => { + let (Phase::Placed(selection) | Phase::Dragging { selection, .. }) = std::mem::take(phase) else { + return Effects::none(); + }; + let mut selection = selection; + selection.origin = (selection.anchor, selection.anchor); + selection.focus = focus; + selection.far = far; + *phase = Phase::Dragging { selection, unit: Unit::Char }; + Effects::one(Effect::Seal) + } + Event::Drag { anchor, focus, reach } => { + let Phase::Dragging { selection: sel, .. } = phase else { return Effects::none() }; + let same_far = match reach { + Reach::Anchor => sel.far.is_none(), + Reach::Far { path, .. } => sel.far.as_ref().is_some_and(|f| f.path == path), + }; + if (sel.anchor, sel.focus) == (anchor, focus) && same_far { return Effects::none(); } + (sel.anchor, sel.focus) = (anchor, focus); + match reach { + Reach::Anchor => sel.far = None, + Reach::Far { path, content } if !same_far => sel.far = Some(Far::new(path.to_owned(), content.to_owned())), + Reach::Far { .. } => {} + } + Effects::one(if same_far { Effect::SyncPins } else { Effect::Seal }) + } + Event::Release => { + if let Phase::Dragging { .. } = phase + && let Phase::Dragging { selection, .. } = std::mem::take(phase) + { + *phase = Phase::Placed(selection); + } + Effects::none() + } + Event::Select(selection) => { + *phase = Phase::Placed(selection); + Effects::one(Effect::Seal) + } + Event::Clear => { + *phase = Phase::Empty; + Effects::one(Effect::SyncPins) + } + } +} diff --git a/app/vendor/rune/crates/rune/src/runtime/selection/rects.rs b/app/vendor/rune/crates/rune/src/runtime/selection/rects.rs new file mode 100644 index 0000000..72f1413 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/selection/rects.rs @@ -0,0 +1,97 @@ +//! `Cx::selection_rects`: the line boxes of the [`El::selectable`](crate::El::selectable) +//! text selection, for a view that places something over it (a Quote button). It is a layout +//! read like `Cx::layout`, under a key no element can have, so it settles, replays from +//! `memo` and re-runs the view the same way; the boxes ride along with the rects the view is +//! given. +use super::*; + +/// The layout-read key `Cx::selection_rects` reads under. +pub(crate) const SELECTION: &str = "\u{1}selection"; + +impl cx::CxCore { + pub(crate) fn selection_rects(&self) -> Vec<[f32; 4]> { + layout_read::note_read(&mut self.layout_reads.borrow_mut(), SELECTION, None); + crate::memo::read_selection(&self.layout.selection); + self.layout.selection.to_vec() + } +} + +impl<S> Cx<S> { + /// The line boxes of the text selection, `[x, y, w, h]` each in window points after + /// scrolling, in reading order: one per line of each selected text, as its highlight draws + /// them. Empty (and allocating nothing) when nothing is selected or only a caret is placed. + /// Boxes aren't clipped to their scroll viewport, so a view can tell when the selection has + /// scrolled out of sight. Only mounted texts have boxes: the rows of a virtual list that + /// scrolled away have none. Like [`Cx::layout`], boxes are layout points: an ancestor's + /// [`El::scale`](crate::El::scale) isn't applied. + /// + /// A view that reads it re-runs when a box appears, goes, or moves by more than half a + /// point: in the same commit when layout moved it, the next frame when the selection + /// changed or scrolling moved it. While a drag changes the selection that's every frame, + /// so a toolbar that waits for the release + /// ([`SelectionChange::dragging`](crate::SelectionChange::dragging)) should only read it + /// once shown. A `memo` that reads it is rebuilt when the boxes move. + #[inline(always)] + pub fn selection_rects(&self) -> Vec<[f32; 4]> { + self.core.selection_rects() + } +} + +/// Bytes `a..b` of the text at a path. +pub(crate) type SelectedRange = (String, usize, usize); + +/// Whether any box of `a` and `b` differs by more than half a point, or one has a box the +/// other lacks. +pub(crate) fn boxes_moved(a: &[[f32; 4]], b: &[[f32; 4]]) -> bool { + a.len() != b.len() || a.iter().zip(b).any(|(x, y)| layout_read::moved(Some(*x), Some(*y))) +} + +impl RuntimeCore { + /// The selection's line boxes laid out in the last commit's nodes. + pub(super) fn selection_boxes(&self) -> Vec<[f32; 4]> { + let mut out = Vec::new(); + for (i, a, b) in self.selection_ranges() { self.text_boxes(&self.tree.nodes, i, a, b, &mut out); } + out + } + + /// The selection's ranges by the path of each selected text. A measure reads them before it + /// runs: reusing a `memo` moves its nodes out of the last commit's, leaving placeholders + /// the selection can't be found in. + pub(crate) fn selection_by_path(&self) -> Vec<SelectedRange> { + self.selection_ranges().into_iter().map(|(i, a, b)| (self.tree.nodes[i].path.clone(), a, b)).collect() + } + + /// The line boxes of `ranges` laid out in a measure's `nodes`, found there by path. + pub(super) fn selection_boxes_in(&self, nodes: &[Node], ranges: &[SelectedRange]) -> Vec<[f32; 4]> { + let mut out = Vec::new(); + for (path, a, b) in ranges { + if let Some(j) = nodes.iter().position(|n| n.path == *path) { self.text_boxes(nodes, j, *a, *b, &mut out); } + } + out + } + + /// Pushes the line boxes of bytes `a..b` of node `j`'s text onto `out`. + fn text_boxes(&self, nodes: &[Node], j: usize, a: usize, b: usize, out: &mut Vec<[f32; 4]>) { + let n = &nodes[j]; + let (Some(spec), Some(laid)) = (&n.text, &n.text_layout) else { return }; + let flow = laid.view(); + let len = spec.content.len(); + let (a, b) = (a.min(len), b.min(len)); + if a >= b { return; } + let (a, b) = n.elided.map_or((a, b), |e| e.range(a, b)); + let [x, y, w, h] = self.laid_out(nodes, j); + let s = self.env.scale; + let [ox, oy] = links::origin(n, spec, flow, [x, y, x + w, y + h], s, 1.0); + for (bb, _) in flow.range_boxes(a, b, true) { + let (x0, y0) = (ox + bb.x0 as f32 / s, oy + bb.y0 as f32 / s); + out.push([x0, y0, (bb.x1 - bb.x0) as f32 / s, (bb.y1 - bb.y0) as f32 / s]); + } + } + + /// Once a frame: the selection moved since the view last read it (a drag, a click, code, + /// scrolling). That isn't layout feedback, so the view re-runs as for a state change. + pub(super) fn selection_read_moved(&self) -> bool { + let seen = &self.commit.layout_seen.rects; + seen.contains_key(SELECTION) && boxes_moved(&seen.selection, &self.selection_boxes()) + } +} diff --git a/app/vendor/rune/crates/rune/src/runtime/selection/select_all.rs b/app/vendor/rune/crates/rune/src/runtime/selection/select_all.rs new file mode 100644 index 0000000..c387a03 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/selection/select_all.rs @@ -0,0 +1,93 @@ +//! Cmd+A with nothing selected yet. A read-only selectable text has no selection to hold the +//! key, so it goes to the group the user last clicked or selected in, else the window's only +//! selectable group, as a click makes an AppKit text view the first responder. +use super::*; + +/// The group (or ungrouped text) the selection last touched, by path. +#[derive(Default)] +pub(in crate::runtime) struct Pick(Option<String>); + +impl RuntimeCore { + /// The selection group of text `i`, or the text itself when it's in none. + fn select_unit(&self, i: usize) -> usize { + self.group_of(i).unwrap_or(i) + } + + /// Remembers the unit of the text holding the selection. + pub(in crate::runtime) fn remember_pick(&mut self) { + let unit = self.selection_holder_end().map(|h| { + self.end_group_path(h).unwrap_or_else(|| self.end_path(h)).to_owned() + }); + if unit.is_some() { + self.edit.selectable.pick.0 = unit; + } + } + + /// Where Cmd+A goes: the selection's group, else the last picked while it's mounted, else + /// the only one in the window. + fn select_all_target(&self) -> Option<usize> { + if let Some(h) = self.selection_holder_end() { + return match h { + selectable::virtual_selection::EndRef::Mounted(i) => Some(self.select_unit(i)), + selectable::virtual_selection::EndRef::Offscreen(..) => { + self.end_group_path(h).and_then(|gp| self.live(gp)) + } + }; + } + let live = |i: usize| self.is_selectable(i) && !self.subtree_exiting(i) && self.allowed(i); + let picked = self.edit.selectable.pick.0.as_deref().and_then(|p| self.live(p)).filter(|&u| { + if self.tree.nodes[u].selection_group { (u + 1..self.tree.nodes.len()).any(|j| self.member(j, u)) } else { live(u) } + }); + if picked.is_some() { + return picked; + } + let mut units = (0..self.tree.nodes.len()).filter(|&i| live(i)).map(|i| self.select_unit(i)); + let first = units.next()?; + units.all(|u| u == first).then_some(first) + } + + /// Cmd+A when nothing else took it: selects all of `select_all_target`. + pub(in crate::runtime) fn select_all_key(&mut self, app: &dyn ViewDriver) -> bool { + if let Some(h @ selectable::virtual_selection::EndRef::Offscreen(vi, _)) = self.selection_holder_end() { + match self.end_group_path(h).map(str::to_owned) { + None => { + let path = self.end_path(h).to_owned(); + self.select_span_ends(h, h); + log_event!(self, "select all {path}"); + return true; + } + Some(gp) if self.live(&gp).is_none() => { + let texts = self.commit.virtuals.iter().nth(vi).unwrap().1.selection.pins.texts(); + let mut members = texts.iter().enumerate() + .filter(|(_, t)| t.group_path.as_deref() == Some(gp.as_str())) + .map(|(ti, _)| selectable::virtual_selection::EndRef::Offscreen(vi, ti)); + let Some(first) = members.next() else { return false }; + let last = members.last().unwrap_or(first); + self.select_span_ends(first, last); + log_event!(self, "select all {gp}"); + return true; + } + Some(_) => {} + } + } + let Some(u) = self.select_all_target() else { return false }; + if self.tree.nodes[u].selection_group + && let Some((first, last)) = self.virtual_span_under(app, u) + { + let path = self.tree.nodes[u].path.clone(); + self.select_span_ends(first, last); + log_event!(self, "select all {path}"); + return true; + } + let (first, last) = if self.tree.nodes[u].selection_group { + let texts = self.group_texts(u); + let (Some(&first), Some(&last)) = (texts.first(), texts.last()) else { return false }; + (first, last) + } else { + (u, u) + }; + self.select_span(first, last); + log_event!(self, "select all {}", self.tree.nodes[u].path); + true + } +} diff --git a/app/vendor/rune/crates/rune/src/runtime/selection/selectable.rs b/app/vendor/rune/crates/rune/src/runtime/selection/selectable.rs new file mode 100644 index 0000000..35f78e2 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/selection/selectable.rs @@ -0,0 +1,801 @@ +//! Read-only text people can select and copy (`El::selectable`), as SwiftUI's +//! `.textSelection(.enabled)` does on the Mac. It shares the text fields' machinery: Parley's +//! layout hit-tests the pointer into byte offsets, the highlight is the fields' own selection +//! boxes (`push_selection`), and copying goes through `Tx::copy`. The selection lives here, not in +//! app state, so selecting never re-runs the view or re-lays out the text. +//! +//! One text holds the selection at a time, or one selection group (`El::selection_group`): the +//! anchor is in one of its texts, the focus in another, and every text of the group between them +//! in tree order is selected whole. A press elsewhere clears it, as does focus moving to another +//! element. The selection is byte offsets into the texts' content; a view that changes the +//! selected part of a text drops it, while text appended after it (a message streaming in) +//! keeps it. +//! +//! Code reads the selection with `Tx::text_selection` and sets it with `Tx::select_text`, +//! `Tx::select_all_text` and `Tx::clear_text_selection`; an `El::selection_copy` element +//! decides what copying a selection inside it takes. +use super::*; +use std::ops::Range; + +/// A secondary press outside the selection selects the word under it first: AppKit text does, +/// Chromium on Windows and Linux doesn't. +const SECONDARY_SELECTS_WORD: bool = cfg!(target_os = "macos"); + +#[path = "copy_html.rs"] +mod copy_html; +#[path = "copy_join.rs"] +mod copy_join; +#[path = "edge_scroll.rs"] +pub(crate) mod edge_scroll; +#[path = "phase.rs"] +pub(crate) mod phase; +#[path = "toolbar.rs"] +mod selection_toolbar; +#[path = "text_selection.rs"] +mod text_selection; +pub(crate) use copy_join::CopyJoin; +pub(crate) use selection_toolbar::OnPress; +pub use text_selection::{SelectedText, SelectionChange, TextSelection}; + +/// The commit, the selection's ends and whether a press is making it: what a selection read +/// from them depends on. +type Basis = (u64, Option<String>, usize, usize, Option<String>, bool); + +/// `Tx::text_selection`'s snapshot and what it was taken from. +pub(in crate::runtime) struct Snapshot { + from: Basis, + selection: Option<Rc<TextSelection>>, +} + +/// What each `El::on_selection_change` element last heard, by path, and what that was checked +/// against. +#[derive(Default)] +pub(in crate::runtime) struct Heard { + from: Option<Basis>, + by_path: HashMap<String, Rc<TextSelection>>, +} + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(crate) enum Unit { + #[default] + Char, + Word, + Paragraph, +} + +/// The char boundary at or before byte `i` of `text`. +pub(in crate::runtime) fn floor_boundary(text: &str, i: usize) -> usize { + text.floor_char_boundary(i) +} + +/// The char boundary before byte `i` (a boundary) of `text`. +fn prev_boundary(text: &str, i: usize) -> usize { floor_boundary(text, i.saturating_sub(1)) } + +/// The range of `unit` at byte `i` of `text`: a word (or run of spaces or punctuation) by +/// Unicode word boundaries, Chinese, Japanese, Thai, Lao, Khmer and Burmese words by ICU's +/// dictionaries as a browser finds them, or a paragraph with its line break. Past the end of a +/// line (on its break, or past the end of the text) it takes the line's last word or paragraph, +/// as AppKit does. +pub(crate) fn unit_at(text: &str, i: usize, unit: Unit) -> (usize, usize) { + let mut i = floor_boundary(text, i); + if i > 0 && i == text.len() && unit != Unit::Char { i = prev_boundary(text, i); } + match unit { + Unit::Char => (i, i), + Unit::Word => { + if i > 0 && text[i..].starts_with(['\n', '\r']) && !text[..i].ends_with('\n') { + i = prev_boundary(text, i); + if text[i..].starts_with('\r') && i > 0 && !text[..i].ends_with('\n') { i = prev_boundary(text, i); } + } + let mut last = (i, i); + let mut start = 0; + for end in word_ends(text) { + last = (start, end); + if i < end { return last; } + start = end; + } + last + } + Unit::Paragraph => { + let start = text[..i].rfind('\n').map_or(0, |n| n + 1); + let end = text[i..].find('\n').map_or(text.len(), |n| i + n + 1); + (start, end) + } + } +} + +/// Where each of `text`'s words ends, in order, the last at `text.len()`: ICU4X's dictionaries +/// natively, the browser's (`Intl.Segmenter`) in a page and Windows' own (`icu.dll`) on Windows, +/// which link none. +fn word_ends(text: &str) -> impl Iterator<Item = usize> { + rune_text::segmenter::words(text).into_iter() +} + +/// The selection a drag from unit range `origin` to unit range `at` makes: (anchor, focus). +pub(crate) fn extend(origin: (usize, usize), at: (usize, usize)) -> (usize, usize) { + if at.0 < origin.0 { (origin.1, at.0) } else { (origin.0, at.1.max(origin.1)) } +} + +/// Pushes the selection boxes of bytes `a..b` of `layout`, whose top-left draws at `origin` +/// (device px) `k` times its size. Text fields and selectable text both draw through here, so +/// their highlights match. +#[allow(clippy::too_many_arguments)] +pub(in crate::runtime) fn push_selection(out: &mut Vec<Instance>, flow: TextFlow<'_>, a: usize, b: usize, origin: [f32; 2], k: f32, + fill: [f32; 4], s: f32, clip: [f32; 4], fade: [f32; 4]) { + for (bb, _) in flow.range_boxes(a, b, true) { + let rect = super::text_marks::pixel_rect(origin, bb, k); + let radius = 2.0 * s * k; + extend_run(out, rect, fill, radius, clip, fade, 40.0 * s * k); + } +} + +/// A text field's selection: one layout, so no runs to join, and a field's own fill behind it +/// is the field, not a chip the highlight should stretch to. +pub(in crate::runtime) fn push_field_selection(out: &mut Vec<Instance>, layout: TextFlow<'_>, a: usize, b: usize, origin: [f32; 2], k: f32, + fill: [f32; 4], s: f32, clip: [f32; 4], fade: [f32; 4]) { + for (bb, _) in layout.range_boxes(a, b, true) { + out.push(rect_inst(super::text_marks::pixel_rect(origin, bb, k), fill, 2.0 * s * k, clip, fade)); + } +} + +/// Words flowed as separate texts each draw their own highlight. One that starts where a recent +/// one on the same line ended (or after the little gap a chip's icon and padding leave) joins +/// it, so a run reads as one rect with no seams, as tall as the line's tallest text. When +/// something filled was drawn in between (a chip's background), a rect of its own is drawn on +/// top, reaching back to where the last one ended. +fn extend_run(out: &mut Vec<Instance>, mut rect: [f32; 4], fill: [f32; 4], radius: f32, clip: [f32; 4], fade: [f32; 4], reach: f32) { + let from = out.len().saturating_sub(256); + let found = out[from..].iter().rposition(|i| { + let gap = rect[0] - (i.rect[0] + i.rect[2]); + let overlap = (i.rect[1] + i.rect[3]).min(rect[1] + rect[3]) - i.rect[1].max(rect[1]); + i.fill == fill && i.clip == clip && i.radii == [radius; 4] && i.params[1] == crate::render::KIND_RECT + && (-1.0..=reach).contains(&gap) && overlap > 0.6 * i.rect[3].min(rect[3]) + }).map(|k| from + k); + let Some(at) = found else { + // First on its line, inside a chip's background: start the highlight at the chip's edge. + let chip = out[from..].iter().rev().find(|i| { + let overlap = (i.rect[1] + i.rect[3]).min(rect[1] + rect[3]) - i.rect[1].max(rect[1]); + i.params[1] == crate::render::KIND_RECT && i.fill != fill && i.fill[3] > 0.0 && i.rect[0] >= rect[0] - reach && i.rect[0] < rect[0] + && i.rect[0] + i.rect[2] > rect[0] && i.rect[3] <= 1.8 * rect[3] && overlap > 0.6 * rect[3] + }).map(|i| i.rect); + if let Some(c) = chip { + let (top, bottom) = (c[1].min(rect[1]), (c[1] + c[3]).max(rect[1] + rect[3])); + rect = [c[0], top, rect[0] + rect[2] - c[0], bottom - top]; + } + return out.push(rect_inst(rect, fill, radius, clip, fade)); + }; + let covered = out[at + 1..].iter().any(|i| i.params[1] == crate::render::KIND_RECT && i.fill != fill && i.fill[3] > 0.0); + let prev = &mut out[at]; + let (top, bottom) = (prev.rect[1].min(rect[1]), (prev.rect[1] + prev.rect[3]).max(rect[1] + rect[3])); + if covered { + let left = (prev.rect[0] + prev.rect[2]).min(rect[0]); + rect = [left, top, rect[0] + rect[2] - left, bottom - top]; + return out.push(rect_inst(rect, fill, radius, clip, fade)); + } + prev.rect[2] = prev.rect[0].max(rect[0] + rect[2]) - prev.rect[0]; + prev.rect[1] = top; + prev.rect[3] = bottom - top; +} + +/// `now` still reads as `then` did up to byte `upto`: text added after it (streaming in) keeps +/// a selection, a change inside it doesn't. With nothing selected in it (`upto` 0) only text +/// appended keeps it. +pub(in crate::runtime) fn kept(then: &str, now: &str, upto: usize) -> bool { + if upto == 0 { return now.starts_with(then); } + then.get(..upto).is_some_and(|a| now.get(..upto) == Some(a)) +} + +/// `r`, a word, without the [`El::uncopied`] bytes at its ends, unless that leaves nothing. +pub(in crate::runtime) fn trim_uncopied(uncopied: &[(u32, u32)], (mut a, mut b): (usize, usize)) -> (usize, usize) { + let r0 = (a, b); + while let Some(&(_, e)) = uncopied.iter().find(|r| (r.0 as usize) <= a && a < r.1 as usize && a < b) { a = (e as usize).min(b); } + while let Some(&(st, _)) = uncopied.iter().find(|r| (r.0 as usize) < b && b <= r.1 as usize && a < b) { b = (st as usize).max(a); } + if a < b { (a, b) } else { r0 } +} + +/// Node `i`'s selected bytes among `ranges` (from `selection_ranges`). +pub(in crate::runtime) fn range_in(ranges: &[(usize, usize, usize)], i: usize) -> Option<(usize, usize)> { + ranges.iter().find(|r| r.0 == i).map(|r| (r.1, r.2)) +} + +/// How far `x` is outside box `r` (x0, y0, x1, y1) horizontally. +fn dist_x(r: [f32; 4], x: f32) -> f32 { (r[0] - x).max(x - r[2]).max(0.0) } + +/// Whether `a` and `b` have the same keyed segments and the same unkeyed tail after their last +/// key, so a keyed text keeps its selection when a sibling shifts an unkeyed ancestor's index. +pub(in crate::runtime) fn same_keyed_path(a: &str, b: &str) -> bool { + fn split(p: &str) -> Option<(&str, &str)> { + let last_key = p.rmatch_indices('/').find(|&(i, _)| !p[i + 1..].starts_with('#')) + .map_or_else(|| (!p.starts_with('#')).then_some(0), |(i, _)| Some(i + 1))?; + let end = last_key + p[last_key..].find('/').unwrap_or(p.len() - last_key); + Some((&p[..end], &p[end..])) + } + let (Some((ka, ta)), Some((kb, tb))) = (split(a), split(b)) else { return false }; + ta == tb && ka.split('/').filter(|s| !s.starts_with('#')).eq(kb.split('/').filter(|s| !s.starts_with('#'))) +} + +impl caret::TextInputState { + /// With nothing selected the basis reads ends of 0: nothing that compares it can change its + /// answer, since any selection made since differs in its path. + pub(super) fn same_selection_basis(&self, commits: u64, from: &Basis) -> bool { + let phase = &self.selectable.phase; + let sel = phase.selection(); + from.0 == commits + && from.1.as_deref() == sel.map(|s| s.path.as_str()) + && from.2 == sel.map_or(0, |s| s.anchor) + && from.3 == sel.map_or(0, |s| s.focus) + && from.4.as_deref() == sel.and_then(|s| s.far.as_ref()).map(|f| f.path.as_str()) + && from.5 == phase.dragging() + } + + pub(super) fn selection_basis(&self, commits: u64) -> Basis { + let phase = &self.selectable.phase; + let sel = phase.selection(); + (commits, sel.map(|s| s.path.clone()), sel.map_or(0, |s| s.anchor), sel.map_or(0, |s| s.focus), + sel.and_then(|s| s.far.as_ref()).map(|f| f.path.clone()), phase.dragging()) + } + + pub(super) fn cached_selection_snapshot(&self, commits: u64) -> Option<Option<Rc<TextSelection>>> { + let cache = self.sel_snapshot.borrow(); + cache.as_ref().filter(|s| self.same_selection_basis(commits, &s.from)).map(|s| s.selection.clone()) + } + + pub(super) fn cache_selection_snapshot(&self, commits: u64, selection: Option<Rc<TextSelection>>) { + let from = self.selection_basis(commits); + *self.sel_snapshot.borrow_mut() = Some(Snapshot { from, selection }); + } +} + +impl RuntimeCore { + pub(in crate::runtime) fn is_selectable(&self, i: usize) -> bool { + let n = &self.tree.nodes[i]; + n.input.is_none() && n.text.as_ref().is_some_and(|t| t.selectable && !t.redacted) + } + + pub(in crate::runtime) fn live(&self, path: &str) -> Option<usize> { + (0..self.tree.nodes.len()).find(|&i| self.tree.nodes[i].path == path && !self.subtree_exiting(i) && self.allowed(i)) + } + + pub(in crate::runtime) fn content_of(&self, i: usize) -> &str { + self.tree.nodes[i].text.as_ref().map_or("", |t| t.content.as_str()) + } + + /// The selection group node `i` is in: its nearest `El::selection_group` ancestor. + pub(in crate::runtime) fn group_of(&self, i: usize) -> Option<usize> { + std::iter::successors(self.tree.nodes[i].parent, |&p| self.tree.nodes[p].parent).find(|&p| self.tree.nodes[p].selection_group) + } + + /// Node `j` is a selectable text of group `g` (not of a group inside it). + pub(in crate::runtime) fn member(&self, j: usize, g: usize) -> bool { + self.is_selectable(j) && self.group_of(j) == Some(g) && !self.subtree_exiting(j) && self.allowed(j) + } + + /// Group `g`'s selectable texts, in tree order. + pub(crate) fn group_texts(&self, g: usize) -> Vec<usize> { + // Nodes are in tree order, so a subtree is the run after its root. + let inside = |j: usize| std::iter::successors(self.tree.nodes[j].parent, |&p| self.tree.nodes[p].parent).any(|p| p == g); + (g + 1..self.tree.nodes.len()).take_while(|&j| inside(j)).filter(|&j| self.member(j, g)).collect() + } + + /// The range of `unit` at byte `at` of node `i`'s text, a word without uncopied ends. + pub(in crate::runtime) fn unit_in(&self, i: usize, at: usize, unit: Unit) -> (usize, usize) { + let r = unit_at(self.content_of(i), at, unit); + match (unit, &self.tree.nodes[i].text) { + (Unit::Word, Some(t)) if !t.cold.uncopied.is_empty() => trim_uncopied(&t.cold.uncopied, r), + _ => r, + } + } + + /// The node holding the anchor, while it's still there, still selectable and still reads as + /// it did up to the selection. + pub(in crate::runtime) fn selection_holder(&self) -> Option<usize> { + use virtual_selection::EndRef; + let h = self.selection_holder_end()?; + match h { + EndRef::Mounted(i) => Some(i), + EndRef::Offscreen(vi, ti) => match self.focus_holder_end(h) { + Some(EndRef::Mounted(j)) => Some(j), + _ => self.end_group_path(h).and_then(|g| self.live(g)).or_else(|| self.live(&self.offscreen_text(vi, ti).list_path)), + }, + } + } + + /// Every text the selection covers with its selected bytes, in tree order, none empty. + pub(in crate::runtime) fn selection_ranges(&self) -> Vec<(usize, usize, usize)> { + use virtual_selection::EndRef; + let Some(h) = self.selection_holder_end() else { return Vec::new() }; + let Some(f) = self.focus_holder_end(h) else { return Vec::new() }; + let Some(sel) = self.edit.selectable.phase.selection() else { return Vec::new() }; + if f == h { + let EndRef::Mounted(i) = h else { return Vec::new() }; + let (a, b) = (sel.anchor.min(sel.focus), sel.anchor.max(sel.focus)); + return if a < b && b <= self.content_of(i).len() { vec![(i, a, b)] } else { Vec::new() }; + } + let ((first, a), (last, b)) = if self.tree_order(h) < self.tree_order(f) { + ((h, sel.anchor), (f, sel.focus)) + } else { + ((f, sel.focus), (h, sel.anchor)) + }; + let Some(g_path) = self.end_group_path(h) else { return Vec::new() }; + let Some(g) = self.live(g_path) else { return Vec::new() }; + if let (EndRef::Mounted(i0), EndRef::Mounted(i1)) = (first, last) { + return (i0..=i1).filter(|&j| self.member(j, g)).filter_map(|j| { + let len = self.content_of(j).len(); + let (a, b) = (if j == i0 { a.min(len) } else { 0 }, if j == i1 { b.min(len) } else { len }); + (a < b).then_some((j, a, b)) + }).collect(); + } + let (first_ord, last_ord) = (self.tree_order(first), self.tree_order(last)); + self.group_texts(g).into_iter().filter_map(|j| { + let end_j = EndRef::Mounted(j); + let ord = self.tree_order(end_j); + if ord < first_ord || ord > last_ord { return None; } + let len = self.content_of(j).len(); + let (a, b) = (if end_j == first { a.min(len) } else { 0 }, if end_j == last { b.min(len) } else { len }); + (a < b).then_some((j, a, b)) + }).collect() + } + + /// The text holding the selection's anchor and its selected byte range there (empty after a + /// single click), for tests and tools. + pub fn text_selection(&self) -> Option<(&str, std::ops::Range<usize>)> { + let h = self.selection_holder_end()?; + let sel = self.edit.selectable.phase.selection()?; + let range = match &sel.far { + None => sel.anchor.min(sel.focus)..sel.anchor.max(sel.focus), + Some(_) => { + let f = self.focus_holder_end(h)?; + if f == h { + sel.anchor.min(sel.focus)..sel.anchor.max(sel.focus) + } else { + let len = self.end_content(h).len(); + let (a, b) = if self.tree_order(h) < self.tree_order(f) { + (sel.anchor.min(len), len) + } else { + (0, sel.anchor.min(len)) + }; + if a < b { a..b } else { sel.anchor..sel.anchor } + } + } + }; + Some((sel.path.as_str(), range)) + } + + /// The selected text as drawn, as copying puts it on the clipboard without an + /// [`El::selection_copy`] (as authored, before `El::text_case`). Across a selection group's + /// texts: a newline between texts, a tab between texts side by side (table cells). + /// + /// When the selection spans unbuilt rows of an [`El::virtual_rows`] or [`El::virtualize`] + /// list, those rows are built on demand (view only: no layout, mount or GPU) to collect their + /// selectable text in tree order. On-demand collection is bounded to 10,000 unbuilt rows and + /// 4 MiB of UTF-8 text; past either cap, collection stops building further unbuilt rows and + /// truncates the returned string on a character boundary. + pub(crate) fn selected_text(&self, app: &dyn ViewDriver) -> Option<String> { + if self.selection_spans_unmounted() { + return self.collect_virtual_selection(app, None).map(|s| s.text); + } + let out = self.joined(&self.selection_ranges()); + (!out.is_empty()).then_some(out) + } + + /// The selection as [`Tx::text_selection`] reads it, `None` with nothing selected. + pub(crate) fn selection(&self, app: &dyn ViewDriver) -> Option<TextSelection> { + if self.selection_spans_unmounted() { + return self.collect_virtual_selection(app, None); + } + let ranges = self.selection_ranges(); + if ranges.is_empty() { return None; } + let texts = ranges.iter().map(|&(i, a, b)| self.selected_piece(i, a..b, None)).collect(); + Some(TextSelection { texts, text: self.joined(&ranges), backward: self.selection_backward() }) + } + + /// [`Runtime::selection`] for a handler's `Tx`, kept until a commit or the selection changes. + pub(in crate::runtime) fn selection_snapshot(&self, app: &dyn ViewDriver) -> Option<Rc<TextSelection>> { + self.edit.selectable.phase.selection()?; + if let Some(cached) = self.edit.cached_selection_snapshot(self.commit.commits) { + return cached; + } + let selection = self.selection(app).map(Rc::new); + self.edit.cache_selection_snapshot(self.commit.commits, selection.clone()); + selection + } + + /// The `El::on_selection_change` calls owed since the last check: each element whose part + /// of the selection changed, started or cleared. + pub(in crate::runtime) fn selection_changes(&mut self, app: &dyn ViewDriver) -> Vec<Action> { + if self.edit.sel_heard.from.as_ref().is_some_and(|f| self.edit.same_selection_basis(self.commit.commits, f)) { return Vec::new(); } + // A release is heard by whoever holds the selection, though it didn't change. + let released = self.edit.sel_heard.from.as_ref().is_some_and(|f| f.5 && !self.edit.selectable.phase.dragging()); + self.edit.sel_heard.from = Some(self.edit.selection_basis(self.commit.commits)); + if self.edit.sel_heard.by_path.is_empty() && !self.tree.nodes.iter().any(|n| n.handlers.get().is_some_and(|h| h.on_selection_change.is_some())) { + return Vec::new(); + } + let watchers: Vec<usize> = (0..self.tree.nodes.len()) + .filter(|&i| self.tree.nodes[i].handlers.get().is_some_and(|h| h.on_selection_change.is_some()) && !self.subtree_exiting(i) && self.allowed(i)) + .collect(); + if watchers.is_empty() && self.edit.sel_heard.by_path.is_empty() { return Vec::new(); } + let mut selected: Vec<usize> = self.selection_ranges().into_iter().filter(|r| r.1 < r.2).map(|r| r.0).collect(); + if self.has_nonempty_selection() + && let Some(h) = self.selection_holder_end() + { + for e in [Some(h), self.focus_holder_end(h)].into_iter().flatten() { + if let virtual_selection::EndRef::Offscreen(vi, ti) = e + && let Some(ln) = self.live(&self.offscreen_text(vi, ti).list_path) + && !selected.contains(&ln) + { + selected.push(ln); + } + } + } + let inside = |w: usize, j: usize| std::iter::successors(Some(j), |&p| self.tree.nodes[p].parent).any(|p| p == w); + if self.edit.sel_heard.by_path.is_empty() && !watchers.iter().any(|&w| selected.iter().any(|&j| inside(w, j))) { + return Vec::new(); + } + let sel = (!selected.is_empty()).then(|| self.selection_snapshot(app)).flatten(); + let (mut out, mut heard) = (Vec::new(), HashMap::default()); + for w in watchers { + let path = self.tree.nodes[w].path.clone(); + let now = sel.clone().filter(|_| selected.iter().any(|&j| inside(w, j))); + let before = self.edit.sel_heard.by_path.remove(&path).or_else(|| { + let k = self.edit.sel_heard.by_path.keys().find(|k| same_keyed_path(k, &path))?.clone(); + self.edit.sel_heard.by_path.remove(&k) + }); + let same = match (&before, &now) { + (Some(a), Some(b)) => { + Rc::ptr_eq(a, b) + || (a.text == b.text + && a.backward == b.backward + && a.texts.len() == b.texts.len() + && a.texts.iter().zip(&b.texts).all(|(x, y)| { + x.key == y.key + && x.range == y.range + && x.len == y.len + && x.whole == y.whole + && x.text == y.text + && (x.path == y.path || same_keyed_path(&x.path, &y.path)) + })) + } + (a, b) => a.is_none() && b.is_none(), + }; + if !same || (released && now.is_some()) { + let change = SelectionChange { selection: now.clone(), was: before.is_some(), dragging: self.edit.selectable.phase.dragging() }; + out.push(Action::SelectionChange(path.clone(), change)); + } + if let Some(now) = now { heard.insert(path, now); } + } + self.edit.sel_heard.by_path = heard; + out + } + + /// Node `i` as a [`SelectedText`] with `range` selected, its path relative to `base`'s. + pub(in crate::runtime) fn selected_piece(&self, i: usize, range: Range<usize>, base: Option<usize>) -> SelectedText { + let n = &self.tree.nodes[i]; + let path = match base { + Some(b) if b == i => String::new(), + Some(b) => n.path.strip_prefix(&self.tree.nodes[b].path).and_then(|p| p.strip_prefix('/')).unwrap_or(&n.path).to_owned(), + None => n.path.clone(), + }; + let len = self.content_of(i).len(); + let (full_a, full_b) = n.text.as_ref().filter(|t| !t.cold.uncopied.is_empty()) + .map_or((0, len), |t| trim_uncopied(&t.cold.uncopied, (0, len))); + let whole = !range.is_empty() && len > 0 && range.start <= full_a && range.end >= full_b; + let text = n.text.as_ref().and_then(|t| t.copy_slice(range.start as u32, range.end as u32)).unwrap_or_default(); + let content = self.content_of(i).get(range.clone()).unwrap_or_default().to_owned(); + SelectedText { path, key: n.key.clone(), range, len, whole, text, content } + } + + /// What copying the selection puts on the clipboard: the nearest [`El::selection_copy`] + /// around it says, else the text as drawn. + pub(crate) fn copy_text(&self, app: &dyn ViewDriver) -> Option<String> { + if self.selection_spans_unmounted() { + return self.copy_virtual_text(app); + } + let ranges = self.selection_ranges(); + let (&(first, ..), &(last, ..)) = (ranges.first()?, ranges.last()?); + let drawn = self.joined(&ranges); + let around = |a: usize, j: usize| std::iter::successors(Some(j), |&p| self.tree.nodes[p].parent).any(|p| p == a); + let provider = std::iter::successors(Some(first), |&p| self.tree.nodes[p].parent) + .find(|&p| self.tree.nodes[p].handlers.selection_copy.is_some() && around(p, last)); + if let Some(p) = provider && let Some(f) = self.tree.nodes[p].handlers.selection_copy.clone() { + let g = self.group_of(first); + let texts = (p..self.tree.nodes.len()) + .take_while(|&j| around(p, j)) + .filter(|&j| self.is_selectable(j) && !self.subtree_exiting(j) && self.allowed(j)) + .filter(|&j| match g { Some(g) => self.group_of(j) == Some(g), None => j == first }) + .map(|j| self.selected_piece(j, range_in(&ranges, j).map_or(0..0, |(a, b)| a..b), Some(p))) + .collect(); + if let Some(text) = f(&TextSelection { texts, text: drawn.clone(), backward: self.selection_backward() }) { return Some(text); } + } + (!drawn.is_empty()).then_some(drawn) + } + + /// The texts of `ranges` joined as copying joins them. + fn joined(&self, ranges: &[(usize, usize, usize)]) -> String { + let mut out = CopyJoin::default(); + let mut prev: Option<usize> = None; + for &(i, a, b) in ranges { + let Some(spec) = self.tree.nodes[i].text.as_ref() else { continue }; + let Some(piece) = spec.copy_slice(a as u32, b as u32) else { continue }; + out.push(spec, a..b, &piece, prev.is_some_and(|p| self.beside(p, i)), usize::MAX); + prev = Some(i); + } + out.finish() + } + + /// Text `i` was drawn beside text `p` on the same line, past it on either side: a table row's + /// cells, which a right-to-left table draws from the right. + pub(crate) fn beside(&self, p: usize, i: usize) -> bool { + let (pb, nb) = (self.drawn_box(p), self.drawn_box(i)); + nb[1] < pb[3] - 0.5 && (nb[0] >= pb[2] - 0.5 || nb[2] <= pb[0] + 0.5) + } + + /// Selects from the start of text `first` to the end of text `last`, a later text of its + /// selection group or `first` itself. + pub(crate) fn select_span(&mut self, first: usize, last: usize) { + use virtual_selection::EndRef; + self.select_span_ends(EndRef::Mounted(first), EndRef::Mounted(last)); + } + + /// The held press is selecting text by dragging, and has selected some. + pub(in crate::runtime) fn selected_by_drag(&self) -> bool { + self.edit.selectable.phase.dragging() && self.pointer.press_held().is_some_and(|h| h.moved) && (!self.selection_ranges().is_empty() || self.has_nonempty_selection()) + } + + pub(in crate::runtime) fn clear_text_selection(&mut self) { + self.select_step(phase::Event::Clear); + } + + /// Steps the selection's phase and carries out what it asks for. + pub(in crate::runtime) fn select_step(&mut self, event: phase::Event<'_>) { + // Only the held press's own drag keeps the list scrolling at its edge. + if !matches!(event, phase::Event::Drag { .. }) { self.edit.stop_edge_scroll(); } + let effects = phase::step(&mut self.edit.selectable.phase, event); + self.carry_select(effects); + } + + fn carry_select(&mut self, effects: crate::machine::Effects<phase::Effect>) { + for effect in effects { + match effect { + phase::Effect::SyncPins => self.sync_selection_pins(), + phase::Effect::Seal => self.seal_between(), + } + } + } + + /// Byte offset of node `i`'s text under window point (x, y), where it was drawn this frame. + fn text_index_at(&self, i: usize, x: f32, y: f32) -> Option<usize> { + let n = &self.tree.nodes[i]; + let (spec, flow) = (n.text.as_ref()?, n.text_layout.as_ref()?.view()); + let s = self.env.scale; + let z = self.paint.drawn_scale.get(i).copied().unwrap_or(1.0).max(1e-4); + let (rect, x, y) = self.unturned_box_and_point(i, x, y); + let [ox, oy] = links::origin(n, spec, flow, rect, s, z); + let px = s / z; + let at = flow.hit((x - ox) * px, (y - oy) * px).index; + Some(n.elided.map_or(at, |e| e.content(at)).min(spec.content.len())) + } + + /// The text of group `g` a drag from `anchor` reaches at (x, y), and the byte there. Texts + /// whose boxes overlap vertically (a table row's cells) form a band; in a band the point + /// takes the text nearest it across. Between bands a drag down stops at the end of the band + /// above, and a drag up at the start of the band below, so it reaches no further than the + /// pointer has. + fn group_point(&self, g: usize, anchor: virtual_selection::EndRef, x: f32, y: f32) -> Option<(usize, usize)> { + use virtual_selection::EndRef; + let mut boxes: Vec<_> = self.group_texts(g).into_iter().filter_map(|j| Some((j, self.shown_box(j)?))).collect(); + boxes.sort_by(|a, b| a.1[1].total_cmp(&b.1[1])); + // Bands as (top, bottom, first text, last text), with their texts in `boxes[from..to]`. + let mut bands: Vec<(f32, f32, usize, usize)> = Vec::new(); + for (k, &(_, r)) in boxes.iter().enumerate() { + match bands.last_mut() { + Some(b) if r[1] < b.1 => { b.1 = b.1.max(r[3]); b.3 = k + 1; } + _ => bands.push((r[1], r[3], k, k + 1)), + } + } + let texts = |b: &(f32, f32, usize, usize)| boxes[b.2..b.3].iter().map(|t| t.0); + if let Some(b) = bands.iter().find(|b| y >= b.0 && y < b.1) { + let &(j, _) = boxes[b.2..b.3].iter().min_by(|p, q| dist_x(p.1, x).total_cmp(&dist_x(q.1, x)))?; + return Some((j, self.text_index_at(j, x, y)?)); + } + let above = bands.iter().rev().find(|b| b.1 <= y); + let below = bands.iter().find(|b| b.0 > y); + match (above, below) { + (a, Some(b)) if a.is_none() || self.tree_order(EndRef::Mounted(texts(b).min()?)) <= self.tree_order(anchor) => { + Some((texts(b).min()?, 0)) + } + (Some(a), _) => texts(a).max().map(|j| (j, self.content_of(j).len())), + _ => None, + } + } + + /// The part of text `j` (x0, y0, x1, y1) that shows inside the clips around it, None when + /// none does. Text clipped out of sight can lie under the words that show (a folded part + /// above them, or the hidden lines of a long folded prompt), and a drag that reached it + /// selected everything between it and the press. + fn shown_box(&self, j: usize) -> Option<[f32; 4]> { + let r = self.drawn_box(j); + if self.paint.inh_scratch.len() != self.tree.nodes.len() || self.paint.drawn.get(j).is_none_or(|d| d[2] <= 0.0 && d[3] <= 0.0) { + return Some(r); + } + let c = self.screen_clip_of_parent(Some(j)).map(|v| v / self.env.scale); + let v = [r[0].max(c[0]), r[1].max(c[1]), r[2].min(c[2]), r[3].min(c[3])]; + (v[0] < v[2] && v[1] < v[3]).then_some(v) + } + + /// A primary press on `target` (None: on nothing). On selectable text away from its links it + /// starts a selection: one click places it, two select a word, three a paragraph, and Shift + /// extends the current one, into another text of its selection group too. Anywhere else it + /// clears the selection. + pub(in crate::runtime) fn selection_down(&mut self, target: Option<usize>, x: f32, y: f32) { + use virtual_selection::EndRef; + let Some(i) = target.filter(|&i| self.is_selectable(i) && self.link_at(i, x, y).is_none()) else { + self.clear_text_selection(); + self.edit.selectable.presses.clear(); + return; + }; + let Some(at) = self.text_index_at(i, x, y) else { return }; + let path = self.tree.nodes[i].path.clone(); + let content = self.content_of(i).to_owned(); + let now = self.now_clock(); + let clicks = self.edit.selectable.presses.press(&path, now, (x, y), self.double_click_interval).min(3); + let i_end = EndRef::Mounted(i); + let holder = self.selection_holder_end().filter(|&h| h == i_end || self.end_same_group(h, i_end)); + match holder { + // Keep the anchor; the focus follows the pointer from here. + Some(h) if clicks == 1 && self.edit.selectable.shift => { + self.select_step(phase::Event::Extend { focus: at, far: (h != i_end).then(|| phase::Far::new(path, content)) }); + } + _ => { + let unit = match clicks { 1 => Unit::Char, 2 => Unit::Word, _ => Unit::Paragraph }; + let origin = self.unit_in(i, at, unit); + self.select_step(phase::Event::Press { path, content, unit, origin }); + } + } + } + + /// The held press moved: extend the selection it started to the pointer, by its unit, into + /// the other texts of its selection group. The press itself may belong to an ancestor (a + /// clickable row), so this follows the selection's own text. + pub(in crate::runtime) fn selection_drag(&mut self, x: f32, y: f32) { + use virtual_selection::EndRef; + let phase::Phase::Dragging { unit, selection } = &self.edit.selectable.phase else { return }; + let (unit, origin) = (*unit, selection.origin); + let Some(h) = self.selection_holder_end() else { self.clear_text_selection(); return }; + let g = self.end_group_path(h).and_then(|gp| self.live(gp)); + let Some((j, at)) = (match (g, h) { + (Some(g), _) => self.group_point(g, h, x, y), + (None, EndRef::Mounted(hi)) => self.text_index_at(hi, x, y).map(|at| (hi, at)), + (None, EndRef::Offscreen(..)) => None, + }) else { return }; + let j_end = EndRef::Mounted(j); + let at = self.unit_in(j, at, unit); + let (anchor, focus) = if j_end == h { + extend(origin, at) + } else if self.tree_order(j_end) > self.tree_order(h) { + (origin.0, at.1) + } else { + (origin.1, at.0) + }; + let reach = if j_end == h { + phase::Reach::Anchor + } else { + let n = &self.tree.nodes[j]; + phase::Reach::Far { path: &n.path, content: n.text.as_ref().map_or("", |t| t.content.as_str()) } + }; + let effects = phase::step(&mut self.edit.selectable.phase, phase::Event::Drag { anchor, focus, reach }); + self.carry_select(effects); + } + + /// Cmd+C (Ctrl+C elsewhere) copies a non-empty selection and Cmd+A selects all of the text + /// holding it, or all of its selection group (a click on it makes it the holder, as it makes + /// an AppKit text view first responder), unless a text field has the keyboard. Only the plain + /// chord: with Shift, Option (Alt) or Control added it's the app's shortcut. + pub(in crate::runtime) fn selection_key(&mut self, app: &dyn ViewDriver, ev: &KeyEvent, tx: &mut Tx) -> bool { + let crate::Key::Command(c @ ('c' | 'a')) = ev.key else { return false }; + let m = ev.mods; + let plain = m.cmd && !m.shift && !m.alt && !(m.ctrl && m.logo); + if !plain || self.focused_input().is_some() || (c == 'c' && self.edit.selectable.phase.selection().is_none()) { return false; } + let holder = self.selection_holder_end(); + if holder.is_none() { self.clear_text_selection(); } + if c == 'a' { return self.select_all_key(app); } + let Some(h) = holder else { return false }; + let path = self.end_path(h).to_owned(); + let Some(text) = self.copy_text(app) else { return false }; + log_event!(self, "copy {path}"); + // Its formatting too, as a browser copies a page's selection. + match self.copy_html() { + Some(html) => tx.copy_rich(crate::ClipboardContent::new(text).with_html(html)), + None => tx.copy(text), + } + true + } + + /// A secondary click on selectable text `path` without its own `on_secondary_press` opens the + /// Copy menu. On macOS it selects the word under the pointer first when the click is outside + /// the selection, as AppKit text does; elsewhere the selection stays as it is, as Chromium's + /// does on Windows and Linux. False when the app's handler should run instead. + pub(in crate::runtime) fn selection_menu(&mut self, app: &dyn ViewDriver, path: &str, x: f32, y: f32) -> bool { + let Some(i) = self.live(path) else { return false }; + if !self.is_selectable(i) || self.tree.nodes[i].handlers.on_secondary_press.is_some() { return false; } + if SECONDARY_SELECTS_WORD + && let Some(at) = self.text_index_at(i, x, y) + && range_in(&self.selection_ranges(), i).is_none_or(|(a, b)| at < a || at >= b) + { + let content = self.content_of(i).to_owned(); + let (a, b) = self.unit_in(i, at, Unit::Word); + self.edit.selectable.presses = Default::default(); + self.select_step(phase::Event::Select(phase::Selection::new(path.to_owned(), content, (a, b), (a, b)))); + } + let text = self.copy_text(app); + let html = text.as_ref().and_then(|_| self.copy_html()); + let mut copy = crate::PopupItem::new("copy", crate::labels::label(crate::Label::Copy)).enabled(text.is_some()); + // The primary modifier, as the copy key handler takes it: ⌘C on macOS, Ctrl+C elsewhere. + if let Ok(shortcut) = "mod+c".parse::<crate::Shortcut>() { copy = copy.key_equivalent(shortcut); } + log_event!(self, "selection menu {path}"); + self.host.popups.push_back(crate::popup_menu::Request { + menu: crate::PopupMenu::new().item(copy), + anchor: crate::PopupAnchor::Point(x, y), + on_pick: Box::new(move |_, picked, tx| { + if picked == Some("copy") && let Some(text) = text { + match html { + Some(html) => tx.copy_rich(crate::ClipboardContent::new(text).with_html(html)), + None => tx.copy(text), + } + } + }), + field: None, + }); + true + } +} + +#[path = "../virtual_list/selection.rs"] +pub(crate) mod virtual_selection; +#[cfg(test)] +#[path = "../virtual_selection_tests.rs"] +mod virtual_selection_tests; + +#[cfg(test)] +mod tests { + use super::{Unit, extend, unit_at}; + + #[test] + fn units_cover_words_spaces_and_paragraphs() { + let s = "opencode --port 4096\nnext line"; + assert_eq!(unit_at(s, 3, Unit::Word), (0, 8)); + assert_eq!(unit_at(s, 8, Unit::Word), (8, 9), "a space run is its own word"); + assert_eq!(unit_at(s, 12, Unit::Word), (11, 15)); + assert_eq!(unit_at(s, s.len(), Unit::Word), (26, 30), "past the end takes the last word"); + assert_eq!(unit_at(s, 5, Unit::Paragraph), (0, 21), "a paragraph takes its line break"); + assert_eq!(unit_at(s, 23, Unit::Paragraph), (21, s.len())); + assert_eq!(unit_at("", 0, Unit::Word), (0, 0)); + } + + #[test] + fn line_ends_take_the_lines_last_word_and_paragraph() { + let s = "first line\nsecond"; + assert_eq!(unit_at(s, 10, Unit::Word), (6, 10), "on the break: the line's last word"); + assert_eq!(unit_at("a\r\nb", 1, Unit::Word), (0, 1)); + assert_eq!(unit_at("first line\n", 11, Unit::Paragraph), (0, 11), "past the end: the last paragraph"); + assert_eq!(unit_at("first line\n", 11, Unit::Word), (6, 10)); + assert_eq!(unit_at("a\n\nb", 2, Unit::Word), (2, 3), "an empty line's break is its own word"); + } + + #[test] + fn offsets_inside_a_character_stay_on_its_boundary() { + let s = "a —"; + for i in 0..=s.len() + 2 { + for unit in [Unit::Char, Unit::Word, Unit::Paragraph] { + let (a, b) = unit_at(s, i, unit); + assert!(s.is_char_boundary(a) && s.is_char_boundary(b), "{i} {unit:?}"); + } + } + } + + #[test] + fn a_drag_keeps_the_unit_it_began_on_whole() { + assert_eq!(extend((8, 12), (20, 24)), (8, 24)); + assert_eq!(extend((8, 12), (0, 4)), (12, 0)); + assert_eq!(extend((8, 12), (9, 10)), (8, 12)); + assert_eq!(extend((5, 5), (2, 2)), (5, 2)); + } +} diff --git a/app/vendor/rune/crates/rune/src/runtime/selection/text_marks.rs b/app/vendor/rune/crates/rune/src/runtime/selection/text_marks.rs new file mode 100644 index 0000000..05c9227 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/selection/text_marks.rs @@ -0,0 +1,100 @@ +//! Text a view keeps painted as selected after the selection has gone ([`Cx::mark_texts`]), as a +//! web page paints a CSS custom highlight styled like its `::selection`: a quote's source in a +//! transcript while its comment is written, say. Each mark names a text by path and a range of +//! its bytes, with the bytes it held then; it paints only while the text still holds them there, +//! so a text that changed under it never lights up something else. +use super::*; +use std::ops::Range; + +/// A range of an [`El::selectable`](crate::El::selectable) text to paint as selected +/// ([`Cx::mark_texts`]): the text's path ([`ElementInfo::path`](crate::ElementInfo)), the +/// bytes of its content, and what they held when marked. Take one from a selection with +/// [`SelectedText::mark`](crate::SelectedText::mark). +#[derive(Clone, Debug, PartialEq, Eq, Hash)] +pub struct TextMark { + path: String, + range: Range<usize>, + text: String, +} + +impl TextMark { + /// Bytes `range` of the text at `path`, which hold `text`. + pub fn new(path: impl Into<String>, range: Range<usize>, text: impl Into<String>) -> TextMark { + TextMark { path: path.into(), range, text: text.into() } + } + /// The text's path. + pub fn path(&self) -> &str { &self.path } + /// The marked bytes of the text's content. + pub fn range(&self) -> Range<usize> { self.range.clone() } + /// What the marked bytes held. + pub fn text(&self) -> &str { &self.text } +} + +impl cx::CxCore { + pub(crate) fn mark_texts(&mut self, marks: impl IntoIterator<Item = TextMark>) { + let mut all = self.defaults.marks.to_vec(); + all.extend(marks); + self.defaults.marks = all.into(); + } +} + +impl<S> Cx<S> { + /// Paints `marks` as the selection paints, in each text's own selection colour + /// ([`El::selection_color`](crate::El::selection_color)), while the view keeps declaring + /// them: one square box per line of each mark, a line tall and as wide as its glyphs, with + /// no newline's width at a line's end, as a CSS custom highlight's background is drawn over + /// a text's line boxes. A mark whose text has gone, isn't mounted, or no longer holds the + /// marked bytes there paints nothing. Set them on every run of the view; a later call adds + /// to the earlier ones. + #[inline(always)] + pub fn mark_texts(&mut self, marks: impl IntoIterator<Item = TextMark>) { + self.core.mark_texts(marks); + } +} + +impl RuntimeCore { + /// The marks the view declared, as (node, start, end) for each mounted text that still + /// holds its marked bytes, in node order. + pub(in crate::runtime) fn mark_ranges(&self) -> Vec<(usize, usize, usize)> { + if self.commit.defaults.marks.is_empty() { return Vec::new(); } + let mut by_path: HashMap<&str, Vec<&TextMark>> = HashMap::default(); + for m in self.commit.defaults.marks.iter() { by_path.entry(m.path.as_str()).or_default().push(m); } + let mut out = Vec::new(); + for (i, n) in self.tree.nodes.iter().enumerate() { + let Some(marks) = by_path.get(n.path.as_str()) else { continue }; + if self.subtree_exiting(i) { continue; } + let content = self.content_of(i); + for m in marks { + if !m.range.is_empty() && content.get(m.range.clone()) == Some(m.text.as_str()) { + out.push((i, m.range.start, m.range.end)); + } + } + } + out + } +} + +/// Pushes the boxes of mark `a..b` of `layout`'s `content`, drawn at `origin` (device px) `k` +/// times its size: square, one per line, the line box tall, each line's run of glyphs wide +/// without the newline that may end it. +/// `laid` maps content bytes to the layout's (an elided text's differ). +#[allow(clippy::too_many_arguments)] +pub(in crate::runtime) fn push_mark(out: &mut Vec<Instance>, flow: TextFlow<'_>, content: &str, (a, b): (usize, usize), laid: impl Fn(usize, usize) -> (usize, usize), + origin: [f32; 2], k: f32, fill: [f32; 4], clip: [f32; 4], fade: [f32; 4]) { + let Some(marked) = content.get(a..b) else { return }; + let mut at = a; + for line in marked.split_inclusive('\n') { + let (from, to) = laid(at, at + line.trim_end_matches(['\n', '\r']).len()); + for (bb, _) in flow.range_boxes(from, to, true) { + out.push(rect_inst(pixel_rect(origin, bb, k), fill, 0.0, clip, fade)); + } + at += line.len(); + } +} + +/// A highlight's box from text at `origin` drawn `k` times its size, its edges on the device grid, +/// as Chromium snaps a selection's rect: hard-edged wherever the text's origin falls. +pub(in crate::runtime) fn pixel_rect(origin: [f32; 2], bb: parley::BoundingBox, k: f32) -> [f32; 4] { + let [x0, y0, x1, y1] = [origin[0] + bb.x0 as f32 * k, origin[1] + bb.y0 as f32 * k, origin[0] + bb.x1 as f32 * k, origin[1] + bb.y1 as f32 * k].map(f32::round); + [x0, y0, x1 - x0, y1 - y0] +} diff --git a/app/vendor/rune/crates/rune/src/runtime/selection/text_selection.rs b/app/vendor/rune/crates/rune/src/runtime/selection/text_selection.rs new file mode 100644 index 0000000..c21f0f2 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/selection/text_selection.rs @@ -0,0 +1,92 @@ +//! What code sees of the [`El::selectable`](crate::El::selectable) text selection: the +//! selection itself ([`TextSelection`], one [`SelectedText`] per text) and what an +//! [`El::on_selection_change`](crate::El::on_selection_change) element hears +//! ([`SelectionChange`]). The selection's state and behaviour are in `runtime/selection/selectable.rs`. +use std::ops::Range; +use std::rc::Rc; + +/// A selection of [`El::selectable`](crate::El::selectable) text, as +/// [`Tx::text_selection`](crate::Tx::text_selection) reads it and an +/// [`El::selection_copy`](crate::El::selection_copy) element sees it. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct TextSelection { + pub(super) texts: Vec<SelectedText>, + pub(super) text: String, + pub(super) backward: bool, +} + +impl TextSelection { + /// The selected texts in tree order (for [`El::selection_copy`](crate::El::selection_copy), + /// every text it could reach). + pub fn texts(&self) -> &[SelectedText] { &self.texts } + /// The selected text as copying takes it without + /// [`El::selection_copy`](crate::El::selection_copy): as authored (before + /// [`El::text_case`](crate::El::text_case)), without [`El::uncopied`](crate::El::uncopied) + /// bytes, with a newline between texts and a tab between texts side by side (table cells). + pub fn text(&self) -> &str { &self.text } + /// The selection's focus (where a drag is, or ended) comes before its anchor (where it + /// began): it was made dragging up or to the left. A toolbar over it can open at the end + /// the pointer is at. + pub fn backward(&self) -> bool { self.backward } +} + +/// One [`El::selectable`](crate::El::selectable) text of a [`TextSelection`]. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct SelectedText { + pub(super) path: String, + pub(super) key: Option<String>, + pub(super) range: Range<usize>, + pub(super) len: usize, + pub(super) whole: bool, + pub(super) text: String, + /// The selected bytes of the content, as drawn. + pub(super) content: String, +} + +impl SelectedText { + /// The text element's path ([`ElementInfo::path`](crate::ElementInfo)); for + /// [`El::selection_copy`](crate::El::selection_copy), relative to the element that asks, + /// empty for that element itself. + pub fn path(&self) -> &str { &self.path } + /// The text element's own key, if it has one. + pub fn key(&self) -> Option<&str> { self.key.as_deref() } + /// The selected bytes of the text's content, empty when none are. + pub fn range(&self) -> Range<usize> { self.range.clone() } + /// The length in bytes of the text's content. + pub fn len(&self) -> usize { self.len } + /// The text has no content. + pub fn is_empty(&self) -> bool { self.len == 0 } + /// Some of the text is selected. + pub fn is_selected(&self) -> bool { !self.range.is_empty() } + /// All of the text is selected. + pub fn is_whole(&self) -> bool { self.whole } + /// The selected part as copying takes it. + pub fn text(&self) -> &str { &self.text } + /// The selected part as a [`TextMark`](crate::TextMark), to paint it as selected after the + /// selection has gone ([`Cx::mark_texts`](crate::Cx::mark_texts)). Only for a selection + /// whose paths are whole ([`Tx::text_selection`](crate::Tx::text_selection), + /// [`El::on_selection_change`](crate::El::on_selection_change)). + pub fn mark(&self) -> crate::TextMark { crate::TextMark::new(self.path.clone(), self.range.clone(), self.content.clone()) } +} + +/// What an [`El::on_selection_change`](crate::El::on_selection_change) element hears. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct SelectionChange { + pub(super) selection: Option<Rc<TextSelection>>, + pub(super) was: bool, + pub(super) dragging: bool, +} + +impl SelectionChange { + /// The whole selection while any of it is inside the element, `None` otherwise. + pub fn selection(&self) -> Option<&TextSelection> { self.selection.as_deref() } + /// A selection appeared inside the element, where there was none. + pub fn started(&self) -> bool { !self.was && self.selection.is_some() } + /// The selection cleared or left the element. + pub fn cleared(&self) -> bool { self.was && self.selection.is_none() } + /// A press is still making the selection (a drag, or the press of a double-click). When it + /// releases, an element holding some of the selection hears it once more with this false, + /// even though the selection didn't change, so a toolbar can wait for the release to + /// open. A selection made by code is never dragging. + pub fn dragging(&self) -> bool { self.dragging } +} diff --git a/app/vendor/rune/crates/rune/src/runtime/selection/toolbar.rs b/app/vendor/rune/crates/rune/src/runtime/selection/toolbar.rs new file mode 100644 index 0000000..18b949b --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/selection/toolbar.rs @@ -0,0 +1,66 @@ +//! What a toolbar floating over a text selection needs from the selection: which way it was +//! made ([`TextSelection::backward`](crate::TextSelection::backward)), and controls a press on +//! which leaves the selection and the keyboard focus as they are +//! ([`El::keeps_text_selection`]). Where its line boxes are is +//! [`Cx::selection_rects`](crate::Cx::selection_rects). +use super::*; + +/// What a press on an element and its descendants leaves as it is. +#[derive(Clone, Copy, Debug, Default)] +pub(crate) struct OnPress { + /// The focused field ([`El::preserve_focus_on_press`]). + pub(crate) focus: bool, + /// The text selection and the focus ([`El::keeps_text_selection`]). + pub(crate) selection: bool, +} + +impl El { + /// A press on this element or anything inside it leaves the + /// [`El::selectable`] text selection and the keyboard focus as they are, as a web page's + /// `preventDefault` on `mousedown` does: a Quote or Copy button floating over a selection + /// can read it when pressed ([`Tx::text_selection`]), and a drag that starts on it doesn't + /// start a new one. Focusable controls inside don't take focus either. The press still + /// reaches `on_press` and the other handlers. + pub fn keeps_text_selection(mut self) -> Self { + self.cold_mut().focus.preserve_on_press.selection = true; + self + } +} + +impl RuntimeCore { + /// What a press on node `i` leaves as it is, from it and its ancestors. + fn on_press_keeps(&self, i: usize) -> OnPress { + std::iter::successors(Some(i), |&p| self.tree.nodes[p].parent) + .take_while(|&p| self.allowed(p)) + .map(|p| self.tree.nodes[p].focus.preserve_on_press) + .fold(OnPress::default(), |a, b| OnPress { focus: a.focus || b.focus, selection: a.selection || b.selection }) + } + + /// A press on node `i` keeps the text selection (and so the focus too). + pub(in crate::runtime) fn press_keeps_selection(&self, i: usize) -> bool { + self.on_press_keeps(i).selection + } + + /// A press on node `i` leaves the focused field focused. + pub(in crate::runtime) fn press_keeps_focus(&self, i: usize) -> bool { + let keeps = self.on_press_keeps(i); + keeps.focus || keeps.selection + } + + /// The selection side of a primary press on `target` at (x, y): it starts or clears a + /// selection, unless the press is on an [`El::keeps_text_selection`] element. + pub(in crate::runtime) fn press_selection(&mut self, target: Option<usize>, x: f32, y: f32) { + if target.is_some_and(|t| self.press_keeps_selection(t)) { return; } + self.selection_down(self.selectable_at(x, y), x, y); + } + + /// The selection's focus comes before its anchor. + pub(in crate::runtime) fn selection_backward(&self) -> bool { + let Some(h) = self.selection_holder_end() else { return false }; + match self.focus_holder_end(h) { + Some(f) if f != h => self.tree_order(f) < self.tree_order(h), + Some(_) => self.edit.selectable.phase.selection().is_some_and(|s| s.focus < s.anchor), + None => false, + } + } +} diff --git a/app/vendor/rune/crates/rune/src/runtime/selection_api_tests.rs b/app/vendor/rune/crates/rune/src/runtime/selection_api_tests.rs new file mode 100644 index 0000000..58f2466 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/selection_api_tests.rs @@ -0,0 +1,38 @@ +//! A selection a handler asks for (`Tx::select_text`) is the one a key later in the same frame +//! copies, on the physical key path native windows use. +use super::*; +use crate::{Cx, El, Env, Key, Mods, PhysicalInput, PhysicalKeyCode, TextStyle, col, text}; + +#[derive(Default)] +struct S { seen: Option<String> } + +fn view(_: &S, _: &mut Cx<S>) -> El { + col() + .key("root") + .w(300.0) + .padding(10.0) + .focusable(true) + .on_physical_input(|s: &mut S, _, tx| { + s.seen = tx.text_selection().map(|sel| sel.text().to_owned()); + false + }) + .child(text("lone text here").key("lone").font(TextStyle::new(14.0, 400.0)).w_full().selectable(true)) +} + +#[test] +fn a_physical_copy_in_the_same_frame_copies_what_code_selected() { + let mut rt = Runtime::new(S::default(), view, (320.0, 120.0), Env::new(true, 2.0)); + rt.frame(0.0); + let clipboard = crate::clipboard::memory(); + rt.use_clipboard(&clipboard); + rt.set_focus(Some("root".to_owned()), false); + rt.update(|_, tx| tx.select_text("lone", 5..9)); + let cmd = Mods { cmd: true, ..Mods::default() }; + rt.physical_with_fallback( + PhysicalInput::Key { key: PhysicalKeyCode::KeyC, mods: cmd, pressed: true, repeat: false }, + Some(KeyEvent { key: Key::Command('c'), mods: cmd }), + ); + rt.frame(1.0 / 60.0); + assert_eq!(rt.state.seen.as_deref(), Some("text")); + assert_eq!(clipboard.text().as_deref().map(String::as_str), Some("text")); +} diff --git a/app/vendor/rune/crates/rune/src/runtime/size_tests.rs b/app/vendor/rune/crates/rune/src/runtime/size_tests.rs new file mode 100644 index 0000000..bc78bd2 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/size_tests.rs @@ -0,0 +1,15 @@ +use super::Node; +use crate::El; + +/// Every builder call moves an `El`, and flatten moves each into a `Node`, so their sizes are +/// paid per element per rebuild. Fields most elements leave unset live behind a pointer. +#[test] +fn elements_and_nodes_stay_small() { + let (el, node) = (std::mem::size_of::<El>(), std::mem::size_of::<Node>()); + eprintln!( + "SIZES El={el} Node={node} Visual={} CompactStyle={}", + std::mem::size_of::<crate::el::Visual>(), + std::mem::size_of::<rune_taffy::CompactStyle>(), + ); + assert!(el <= 800 && node <= 512, "El is {el} bytes and Node {node}"); +} diff --git a/app/vendor/rune/crates/rune/src/runtime/system_settings.rs b/app/vendor/rune/crates/rune/src/runtime/system_settings.rs new file mode 100644 index 0000000..743d207 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/system_settings.rs @@ -0,0 +1,220 @@ +//! The host's system settings: appearance, accent, scroll bars, titlebar inset, keyboard access +//! and reduced motion. + +use std::sync::atomic::{AtomicU64, Ordering}; + +use super::*; + +pub(super) struct ScrollBarHost { + pub(super) state: crate::platform::scroll_bars::SystemScrollBars, + pub(super) runtime_id: u64, +} + +impl Default for ScrollBarHost { + fn default() -> Self { + static NEXT_ID: AtomicU64 = AtomicU64::new(1); + Self { + state: Default::default(), + runtime_id: NEXT_ID.fetch_add(1, Ordering::Relaxed), + } + } +} + +impl window_requests::HostState { + #[inline] + pub(super) fn set_titlebar_inset(&mut self, points: f32) -> bool { + if points == self.titlebar_inset { return false; } + self.titlebar_inset = points; + true + } + + /// What [`Cx::accent`] and [`Cx::focus_color`] report, and the colour of default focus + /// rings. Native windows set it from [`system_accent`](crate::system_accent) and again when + /// the user picks another accent; a change re-runs the view. Headless runs keep + /// [`SystemAccent::DEFAULT`](crate::SystemAccent::DEFAULT) unless a test sets one. + #[inline] + pub(crate) fn system_accent(&self) -> crate::SystemAccent { + self.system_accent + } + + #[inline] + pub(super) fn set_system_accent(&mut self, accent: crate::SystemAccent) -> bool { + if accent == self.system_accent { return false; } + self.system_accent = accent; + true + } + + #[inline] + pub(super) fn set_system_contrast(&mut self, contrast: Option<crate::SystemContrast>) -> bool { + if contrast == self.system_contrast { return false; } + self.system_contrast = contrast; + true + } + + #[inline] + pub(super) fn set_system_increased_contrast(&mut self, on: bool) -> bool { + if on == self.system_increased_contrast { return false; } + self.system_increased_contrast = on; + true + } + + #[inline] + pub(super) fn set_system_reduced_motion(&mut self, reduced: bool) -> bool { + if self.system_reduced_motion == reduced { return false; } + self.system_reduced_motion = reduced; + true + } + + /// Host accessibility preference; false by default in a headless runtime. + #[inline] + pub(crate) fn system_reduced_motion(&self) -> bool { + self.system_reduced_motion + } + + #[inline] + pub(crate) fn system_scroll_bars_state(&self) -> crate::platform::scroll_bars::SystemScrollBars { + self.scroll_bars.state + } + + #[inline] + pub(super) fn set_system_scroll_bars_state(&mut self, next: crate::platform::scroll_bars::SystemScrollBars) -> bool { + if next == self.scroll_bars.state { return false; } + self.scroll_bars.state = next; + true + } + + #[inline] + pub(super) fn set_system_scroll_bars(&mut self, bars: crate::ScrollBars) -> bool { + self.set_system_scroll_bars_state(crate::platform::scroll_bars::SystemScrollBars { + bars, + ..self.scroll_bars.state + }) + } + + #[inline] + pub(crate) fn system_scroll_bars(&self) -> crate::ScrollBars { + self.scroll_bars.state.bars + } + + #[inline] + pub(super) fn set_system_scroller_overlay(&mut self, overlay: bool) -> bool { + self.set_system_scroll_bars_state(crate::platform::scroll_bars::SystemScrollBars { + scroller_overlay: overlay, + ..self.scroll_bars.state + }) + } + + #[inline] + pub(crate) fn system_scroller_overlay(&self) -> bool { + self.scroll_bars.state.scroller_overlay + } + + #[inline] + pub(super) fn set_system_scroller_jumps(&mut self, jumps: bool) -> bool { + self.set_system_scroll_bars_state(crate::platform::scroll_bars::SystemScrollBars { + jump_to_click: jumps, + ..self.scroll_bars.state + }) + } + + #[inline] + pub(crate) fn system_scroller_jumps(&self) -> bool { + self.scroll_bars.state.jump_to_click + } + + /// Whether scroll bars currently overlay and fade out at rest (`true` for + /// [`ScrollBars::WhenScrolling`](crate::ScrollBars::WhenScrolling), `false` for + /// [`ScrollBars::Always`](crate::ScrollBars::Always), and [`Self::system_scroller_overlay`] + /// for [`ScrollBars::Automatic`](crate::ScrollBars::Automatic); always `true` on iOS). + #[inline] + pub(crate) fn overlay_scroll_bars(&self) -> bool { + self.scroll_bars.state.is_overlay() + } +} + +impl RuntimeCore { + pub fn set_system_dark(&mut self, dark: bool) { + if dark != self.env.system_dark { + self.env.system_dark = dark; + self.commit.dirty = true; + } + } + + /// What [`Cx::titlebar_inset`] reports. Native macOS windows set it from AppKit's buttons on + /// every resize, full screen included; a change re-runs the view. + #[inline] + pub fn set_titlebar_inset(&mut self, points: f32) { + if self.host.set_titlebar_inset(points) { self.commit.dirty = true; } + } + + #[inline] + pub(crate) fn system_accent(&self) -> crate::SystemAccent { + self.host.system_accent() + } + + #[inline] + pub fn set_system_accent(&mut self, accent: crate::SystemAccent) { + if self.host.set_system_accent(accent) { self.commit.dirty = true; } + } + + /// Tab visits every control when on, else only text fields and lists, like macOS with + /// Keyboard navigation (Full Keyboard Access) off. Native windows follow the system setting. + pub fn set_full_keyboard_access(&mut self, on: bool) { + self.kbd.full_keyboard_access = on; + } + /// Tab visits every control whatever [`Runtime::set_full_keyboard_access`] says + /// (`App::tab_visits_controls`). + pub fn set_tab_visits_controls(&mut self, on: bool) { + self.kbd.tab_visits_controls = on; + } + /// What [`Cx::system_contrast`] reports. Native Windows windows set it from the system's + /// contrast theme as they open and when it changes; headless runs keep None. + #[inline] + pub fn set_system_contrast(&mut self, contrast: Option<crate::SystemContrast>) { + if self.host.set_system_contrast(contrast) { self.commit.dirty = true; } + } + /// What [`Cx::system_increased_contrast`] reports. Native windows set it from the system as + /// they open, gain focus, and when its display options change; headless runs keep false. + #[inline] + pub fn set_system_increased_contrast(&mut self, on: bool) { + if self.host.set_system_increased_contrast(on) { self.commit.dirty = true; } + } + #[inline] + pub fn set_system_reduced_motion(&mut self, reduced: bool) { + if self.host.set_system_reduced_motion(reduced) { self.commit.dirty = true; } + } + + #[inline] + pub(crate) fn system_scroll_bars_state(&self) -> crate::platform::scroll_bars::SystemScrollBars { + self.host.system_scroll_bars_state() + } + + #[inline] + pub(crate) fn set_system_scroll_bars_state(&mut self, next: crate::platform::scroll_bars::SystemScrollBars) { + if self.host.set_system_scroll_bars_state(next) { self.commit.dirty = true; } + } + + /// What [`Cx::scroll_bars`] reports. Native macOS windows set it from `AppleShowScrollBars` and + /// `NSPreferredScrollerStyleDidChangeNotification`; a change re-runs the view and its memos. + /// Headless runs default to [`ScrollBars::WhenScrolling`](crate::ScrollBars::WhenScrolling). + #[inline] + pub fn set_system_scroll_bars(&mut self, bars: crate::ScrollBars) { + if self.host.set_system_scroll_bars(bars) { self.commit.dirty = true; } + } + + /// Whether the connected pointing device prefers overlay scroll bars under + /// [`ScrollBars::Automatic`](crate::ScrollBars::Automatic) (`true` for a trackpad or touch + /// surface, `false` for a mouse). Headless runs default to `true`. + #[inline] + pub fn set_system_scroller_overlay(&mut self, overlay: bool) { + if self.host.set_system_scroller_overlay(overlay) { self.commit.dirty = true; } + } + + /// Whether a click in a scroll bar's track jumps to the spot clicked (`true`) or pages toward + /// it (`false`), as [`crate::system_scroller_jumps`] reports. Native macOS windows set it from + /// `AppleScrollerPagingBehavior`; headless runs default to paging. A change re-runs the view. + #[inline] + pub fn set_system_scroller_jumps(&mut self, jumps: bool) { + if self.host.set_system_scroller_jumps(jumps) { self.commit.dirty = true; } + } +} diff --git a/app/vendor/rune/crates/rune/src/runtime/tests/app_ime.rs b/app/vendor/rune/crates/rune/src/runtime/tests/app_ime.rs new file mode 100644 index 0000000..0207fde --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/tests/app_ime.rs @@ -0,0 +1,89 @@ +use super::*; +use crate::{Key, KeyEvent, Mods, TextEdit, TextStyle, text_input}; + +#[derive(Default)] +struct Editor { + /// What `App::on_ime` and `on_key` heard, in order. + log: Vec<String>, + field: TextEdit, + /// The app's editor draws its caret (and so has the input method). + caret: bool, +} + +fn view(s: &Editor, _: &mut Cx<Editor>) -> El { + col().size(300.0, 200.0).children([ + text_input(&s.field, TextStyle::new(14.0, 400.0)).key("field").size(200.0, 30.0).on_edit(|s: &mut Editor| &mut s.field), + el().key("page").size(300.0, 100.0) + .children(s.caret.then(|| el().key("caret").absolute(40.0, 20.0).size(2.0, 18.0).ime_cursor())), + ]) +} + +fn editor() -> Runtime<Editor> { + let mut rt = Runtime::new(Editor { caret: true, ..Default::default() }, view, (300.0, 200.0), Env::new(true, 1.0)); + rt.hooks.on_ime = Some(|s, ev, _| { s.log.push(format!("{ev:?}")); true }); + rt.on_key = Some(|s, ev, _| { s.log.push(format!("key {:?}", ev.key)); true }); + rt.frame(0.0); + rt +} + +fn press(rt: &mut Runtime<Editor>, key: Key) { + rt.key(KeyEvent { key, mods: Mods::default() }); + rt.frame(0.0); +} + +#[test] +fn an_ime_cursor_turns_the_input_method_on_at_its_rect_unless_a_field_has_focus() { + let mut rt = editor(); + assert_eq!(rt.ime_area, Some([40.0, 50.0, 2.0, 18.0]), "the caret's drawn rect, below the 30 pt field"); + rt.update(|s, _| s.field.focused = true); + rt.frame(0.0); + let field = rt.ime_area.expect("the field's caret"); + assert!(field[1] < 30.0, "a focused field's caret wins: {field:?}"); + rt.update(|s, _| { s.field.focused = false; s.caret = false; }); + rt.frame(0.0); + assert_eq!(rt.ime_area, None, "no caret, no input method"); +} + +#[test] +fn the_app_hears_the_composition_and_typing_arrives_once() { + let mut rt = editor(); + press(&mut rt, Key::Text("a".into())); + rt.ime(Ime::Enabled); + rt.ime(Ime::Preedit("か".into(), Some((0, 3)), Vec::new())); + rt.frame(0.0); + press(&mut rt, Key::Enter); + press(&mut rt, Key::Escape); + rt.ime(Ime::Commit("家".into())); + rt.frame(0.0); + press(&mut rt, Key::Enter); + assert_eq!(rt.state.log, [ + "key Text(\"a\")", "Enabled", "Preedit(\"か\", Some((0, 3)), [])", "Commit(\"家\")", "key Enter", + ], "plain typing is a key; Return and Escape mid-composition are the input method's"); +} + +#[test] +fn a_focused_field_takes_the_input_method_but_the_apps_composition_ends_in_the_app() { + let mut rt = editor(); + rt.ime(Ime::Preedit("か".into(), None, Vec::new())); + rt.frame(0.0); + rt.update(|s, _| s.field.focused = true); + rt.frame(0.0); + // Turning the input method over to the field ends the app's composition. + rt.ime(Ime::Preedit(String::new(), None, Vec::new())); + rt.ime(Ime::Disabled); + rt.ime(Ime::Preedit("ね".into(), None, Vec::new())); + rt.ime(Ime::Commit("猫".into())); + rt.frame(0.0); + assert_eq!(rt.state.log, ["Preedit(\"か\", None, [])", "Preedit(\"\", None, [])", "Disabled"]); + assert_eq!(rt.state.field.text, "猫", "the field's own composition stays the field's"); +} + +#[test] +fn without_on_ime_an_ime_cursor_hears_nothing() { + let mut rt = editor(); + rt.hooks.on_ime = None; + rt.ime(Ime::Preedit("か".into(), None, Vec::new())); + rt.frame(0.0); + press(&mut rt, Key::Enter); + assert_eq!(rt.state.log, ["key Enter"], "nothing composing holds Return back"); +} diff --git a/app/vendor/rune/crates/rune/src/runtime/tests/context_menu_key.rs b/app/vendor/rune/crates/rune/src/runtime/tests/context_menu_key.rs new file mode 100644 index 0000000..0f222f5 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/tests/context_menu_key.rs @@ -0,0 +1,27 @@ +use super::*; +use crate::{Key, KeyEvent, Mods}; + +#[test] +fn the_menu_key_opens_nothing_for_a_focused_link_whose_subtree_is_inert() { + #[derive(Default)] + struct State { menus: Vec<String> } + fn view(_: &State, _: &mut Cx<State>) -> El { + col().key("row").size(300.0, 100.0) + .on_secondary_press(|s: &mut State, _, _| s.menus.push("row".into())) + .child(crate::rich("see the docs", Vec::new()).key("para").w(200.0) + .link(crate::Link::new(8..12, "docs")) + .on_link_secondary(|s: &mut State, id, _, _| s.menus.push(id.into()))) + } + let mut rt = Runtime::new(State::default(), view, (300.0, 100.0), Env::new(true, 1.0)); + rt.frame(0.0); + rt.key(KeyEvent { key: Key::Tab, mods: Mods::default() }); + for _ in 0..30 { rt.frame(1.0 / 60.0); } + assert_eq!(rt.focused_key().as_deref(), Some("docs")); + // Focus normally drops at the commit that makes it inert; the key must not depend on that. + for n in &mut rt.tree.nodes { n.inert = true; } + for (key, shift) in [(Key::ContextMenu, false), (Key::Function(10), true)] { + rt.key(KeyEvent { key, mods: Mods { shift, ..Mods::default() } }); + rt.frame(0.0); + } + assert!(rt.state.menus.is_empty(), "{:?}", rt.state.menus); +} diff --git a/app/vendor/rune/crates/rune/src/runtime/tests/draw_on.rs b/app/vendor/rune/crates/rune/src/runtime/tests/draw_on.rs new file mode 100644 index 0000000..08328b4 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/tests/draw_on.rs @@ -0,0 +1,66 @@ +use super::*; +use crate::{Shape, canvas}; + +/// A 100-point line in 10 segments, drawn on when `.0` mounts it. +fn line_view(s: &(bool, Transition), _: &mut Cx<(bool, Transition)>) -> El { + let line: Vec<[f32; 2]> = (0..=10).map(|i| [i as f32 * 10.0, 20.0]).collect(); + col().size(200.0, 100.0).children(s.0.then(|| canvas(Shape::new().stroke(line, 2.0, crate::Color::WHITE)).key("line").size(120.0, 40.0).transition(s.1))) +} + +fn segments(rt: &Runtime<(bool, Transition)>) -> usize { + rt.instances.iter().filter(|q| q.params[1] == KIND_SEGMENT).count() +} + +#[test] +fn a_draw_transition_traces_a_shape_on_and_reduce_motion_draws_it_whole() { + let mut rt = Runtime::new((false, Transition::draw()), line_view, (200.0, 100.0), Env::new(true, 1.0)); + rt.frame(0.0); + rt.update(|s, _| s.0 = true); + rt.frame(0.0); + let mut seen = vec![segments(&rt)]; + for _ in 0..90 { + rt.frame(1.0 / 120.0); + seen.push(segments(&rt)); + } + assert!(seen[0] < 3, "starts undrawn: {seen:?}"); + assert!(seen.windows(2).all(|w| w[0] <= w[1]), "draws on, never back: {seen:?}"); + assert!(seen.iter().any(|&n| n > 3 && n < 10), "passes through partly drawn: {seen:?}"); + assert_eq!(*seen.last().unwrap(), 10, "ends whole: {seen:?}"); + + let mut rt = Runtime::new((false, Transition::draw()), line_view, (200.0, 100.0), Env::new(true, 1.0)); + rt.set_system_reduced_motion(true); + rt.frame(0.0); + rt.update(|s, _| s.0 = true); + rt.frame(0.0); + assert_eq!(segments(&rt), 10, "drawn whole the frame it mounts under Reduce Motion"); +} + +#[test] +fn a_live_trim_cuts_a_shape_every_frame_without_rebuilding() { + type S = crate::Tween<[f32; 2]>; + fn view(s: &S, _: &mut Cx<S>) -> El { + let line: Vec<[f32; 2]> = (0..=10).map(|i| [i as f32 * 10.0, 20.0]).collect(); + col().size(200.0, 100.0).child(canvas(Shape::new().stroke(line, 2.0, crate::Color::WHITE)).key("line").size(120.0, 40.0).live_trim(s)) + } + let count = |rt: &Runtime<S>| rt.instances.iter().filter(|q| q.params[1] == KIND_SEGMENT).count(); + let tween = crate::Tween::linear([0.0, 1.0], [1.0, 1.0], std::time::Duration::from_secs(1)); + let mut rt = Runtime::new(tween, view, (200.0, 100.0), Env::new(true, 1.0)); + rt.frame(0.0); + assert_eq!(count(&rt), 10, "starts whole"); + let commits = rt.stats.commits; + let mut seen = Vec::new(); + for _ in 0..10 { + assert!(rt.frame(0.1 - 1e-4), "keeps drawing while it runs"); + seen.push(count(&rt)); + } + assert!(seen.windows(2).all(|w| w[0] >= w[1]), "only shortens: {seen:?}"); + assert!(seen.contains(&5), "half gone at half time: {seen:?}"); + rt.frame(0.01); + assert_eq!(count(&rt), 0, "gone at the end"); + assert!(!rt.frame(0.1), "settles"); + assert_eq!(rt.stats.commits, commits, "no view rebuild"); + + rt.update(|s, _| *s = crate::Tween::linear([0.25, 0.5], [0.25, 0.5], std::time::Duration::ZERO)); + rt.frame(0.0); + assert_eq!(count(&rt), 3, "a fixed span keeps its stretch, cut mid-segment at both ends"); +} diff --git a/app/vendor/rune/crates/rune/src/runtime/tests/edit.rs b/app/vendor/rune/crates/rune/src/runtime/tests/edit.rs new file mode 100644 index 0000000..c40fd0c --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/tests/edit.rs @@ -0,0 +1,330 @@ +//! Runtime integration tests for `rune-edit` (`TextEdit` wired through `Runtime`, `El`, +//! `text_input`, and `clipboard::memory`). + +use std::ops::Range; + +use crate::{ + Block, ClipboardContent, Color, Cx, El, Env, Ime, Key, KeyEvent, MAX_LIST_LEVEL, Mark, Mods, + Runtime, Span, TextEdit, TextStyle, col, text_input, +}; + +fn k(key: Key) -> KeyEvent { + KeyEvent { key, mods: Mods::default() } +} + +fn cmd(c: char) -> KeyEvent { + KeyEvent { key: Key::Command(c), mods: Mods { cmd: true, ..Mods::default() } } +} + +fn chord(s: &str, mods: Mods) -> KeyEvent { + KeyEvent { key: Key::Text(s.into()), mods } +} + +/// `"a @x-agent b"` with the label a pill carrying `agent:x`, the caret after it. +fn with_pill() -> TextEdit { + let mut e = TextEdit::new("a b").rich(); + e.set_caret(2); + e.insert_pill("agent:x", "@x-agent"); + e +} + +fn pills_of(e: &TextEdit) -> Vec<(Range<usize>, String)> { + e.pills().map(|(r, id)| (r, id.to_owned())).collect() +} + +fn assert_invariants(e: &TextEdit, ctx: &str) { + let t = &e.text; + let lines = 1 + t.bytes().filter(|&b| b == b'\n').count(); + assert_eq!(e.blocks().len(), lines, "{ctx}: one block per line"); + assert!(e.blocks().iter().all(|b| b.list_level().is_none_or(|l| l <= MAX_LIST_LEVEL)), "{ctx}: list levels"); + assert!(e.soft_breaks().windows(2).all(|w| w[0] < w[1]), "{ctx}: soft breaks sorted"); + assert!(e.soft_breaks().iter().all(|&i| i > 0 && (i as usize) < lines), "{ctx}: soft breaks in range"); + assert!(t.is_char_boundary(e.anchor) && t.is_char_boundary(e.focus), "{ctx}: caret on a char boundary"); + let ms = e.marks(); + assert!(ms.windows(2).all(|w| w[0].start <= w[1].start), "{ctx}: marks sorted"); + for m in ms { + assert!(m.start < m.end && m.end <= t.len(), "{ctx}: mark {m:?} in range"); + assert!(t.is_char_boundary(m.start) && t.is_char_boundary(m.end), "{ctx}: mark {m:?} on char boundaries"); + for line in e.line_of_byte(m.start)..=e.line_of_byte(m.end - 1) { + assert_ne!(e.blocks()[line], Block::Code, "{ctx}: mark {m:?} reaches code line {line}"); + } + } + for (i, a) in ms.iter().enumerate() { + for b in &ms[i + 1..] { + if a.mark.same_kind(&b.mark) { + assert!(b.start >= a.end, "{ctx}: same-kind marks {a:?} {b:?} overlap"); + assert!(!(b.start == a.end && a.mark == b.mark), "{ctx}: equal marks {a:?} {b:?} not merged"); + } + } + } +} + +#[test] +fn command_chord_reaches_on_key() { + struct Form { pw: TextEdit, keys: Vec<Key> } + fn view(s: &Form, _: &mut Cx<Form>) -> El { + text_input(&s.pw, TextStyle::new(14.0, 400.0)).single_line().key("pw").size(200.0, 40.0) + .on_edit(|s: &mut Form| &mut s.pw) + } + let mut pw = TextEdit::new("").secure(); + pw.focused = true; + let mut rt = Runtime::new(Form { pw, keys: vec![] }, view, (200.0, 40.0), Env::new(true, 1.0)); + rt.on_key = Some(|s, ev, _| { s.keys.push(ev.key.clone()); true }); + rt.frame(0.0); + rt.key(chord(" ", Mods { cmd: true, shift: true, logo: true, ..Mods::default() })); rt.frame(0.0); + rt.key(chord("x", Mods::default())); rt.frame(0.0); + assert_eq!(rt.state.pw.text, "x"); + assert_eq!(rt.state.keys, [Key::Text(" ".into())]); +} + +#[test] +fn spans_on_text_input_hold_through_ime_and_undo() { + struct App { + edit: TextEdit, + } + fn view(s: &App, _: &mut Cx<App>) -> El { + // Highlight the first 3 bytes ("let") with a caller-supplied Span on plain text_input. + let end = s.edit.text.len().min(3); + let spans = if end > 0 { + vec![Span::new(0, end).color(Color::WHITE).bold()] + } else { + vec![] + }; + text_input(&s.edit, TextStyle::new(14.0, 400.0)) + .key("ed") + .size(240.0, 60.0) + .spans(spans) + .on_edit(|s: &mut App| &mut s.edit) + } + let mut edit = TextEdit::new("let x = 1;"); + edit.focused = true; + edit.set_caret(0); + let mut rt = Runtime::new(App { edit }, view, (240.0, 60.0), Env::new(true, 1.0)); + rt.frame(0.0); + + // Start IME preedit at byte 0: display text becomes "あlet x = 1;", so caller's 0..3 + // span on `edit.text` shifts automatically to 3..6 in the rendered TextSpec! + rt.ime(Ime::Preedit("あ".into(), Some((0, 3)), Vec::new())); + rt.frame(0.0); + let spec_spans = &rt.tree.nodes.iter().find(|n| n.key.as_deref() == Some("ed")).unwrap().text.as_ref().unwrap().spans; + assert_eq!(spec_spans.len(), 1); + assert_eq!((spec_spans[0].start, spec_spans[0].end), (3, 6)); + + // Commit IME preedit, then undo back to "let x = 1;": span returns to 0..3. + rt.ime(Ime::Commit("あ".into())); + rt.frame(0.0); + rt.key(KeyEvent { key: Key::Command('z'), mods: Mods { cmd: true, ..Mods::default() } }); + rt.frame(0.0); + assert_eq!(rt.state.edit.text, "let x = 1;"); + let spec_spans = &rt.tree.nodes.iter().find(|n| n.key.as_deref() == Some("ed")).unwrap().text.as_ref().unwrap().spans; + assert_eq!(spec_spans.len(), 1); + assert_eq!((spec_spans[0].start, spec_spans[0].end), (0, 3)); +} + +#[test] +fn runtime_routes_mark_shortcuts_list_tabs_and_renders_decorations() { + struct App { + edit: TextEdit, + other: TextEdit, + } + fn view(s: &App, _: &mut Cx<App>) -> El { + col() + .size(320.0, 200.0) + .child( + text_input(&s.edit, TextStyle::new(14.0, 400.0)) + .key("ed") + .size(300.0, 140.0) + .on_edit(|s: &mut App| &mut s.edit), + ) + .child( + text_input(&s.other, TextStyle::new(14.0, 400.0)) + .key("other") + .size(300.0, 40.0) + .on_edit(|s: &mut App| &mut s.other), + ) + } + let mut edit = TextEdit::from_html( + "<ul><li>item</li></ul><ol><li><del>struck</del></li></ol><blockquote>quote</blockquote><pre><code>let x = 1;</code></pre>", + ); + edit.focused = true; + edit.anchor = 0; + edit.focus = 4; // "item" + let mut rt = Runtime::new( + App { edit, other: TextEdit::new("next") }, + view, + (320.0, 200.0), + Env::new(true, 1.0), + ); + rt.frame(0.0); + let base_instances = rt.instances.len(); + assert!(base_instances > 10); + + // Cmd+B, Cmd+I, Cmd+U toggle marks on the selection through Runtime::key. + rt.key(KeyEvent { key: Key::Command('b'), mods: Mods { cmd: true, ..Mods::default() } }); + rt.key(KeyEvent { key: Key::Command('i'), mods: Mods { cmd: true, ..Mods::default() } }); + rt.key(KeyEvent { key: Key::Command('u'), mods: Mods { cmd: true, ..Mods::default() } }); + rt.frame(0.0); + assert!(rt.state.edit.has_mark(&Mark::Bold)); + assert!(rt.state.edit.has_mark(&Mark::Italic)); + assert!(rt.state.edit.has_mark(&Mark::Underline)); + + // Tab inside a list item indents the list item instead of moving focus to "other"! + rt.key(KeyEvent { key: Key::Tab, mods: Mods::default() }); + rt.frame(0.0); + assert!(rt.state.edit.focused); + assert!(!rt.state.other.focused); + assert_eq!(rt.state.edit.blocks()[0], Block::Bullet(1)); + + // Shift+Tab outdents the list item back to Bullet(0). + rt.key(KeyEvent { key: Key::Tab, mods: Mods { shift: true, ..Mods::default() } }); + rt.frame(0.0); + assert_eq!(rt.state.edit.blocks()[0], Block::Bullet(0)); +} + +#[test] +fn plain_field_leaves_format_chords_to_the_app() { + struct Form { f: TextEdit, keys: Vec<Key> } + fn view(s: &Form, _: &mut Cx<Form>) -> El { + text_input(&s.f, TextStyle::new(14.0, 400.0)).key("f").size(200.0, 40.0).on_edit(|s: &mut Form| &mut s.f) + } + let mut f = TextEdit::new("hello"); + f.focused = true; + f.set_selection(0, 5); + let mut rt = Runtime::new(Form { f, keys: vec![] }, view, (200.0, 40.0), Env::new(true, 1.0)); + rt.on_key = Some(|s, ev, _| { s.keys.push(ev.key.clone()); true }); + rt.frame(0.0); + for c in ['b', 'i', 'u'] { rt.key(cmd(c)); rt.frame(0.0); } + assert_eq!(rt.state.keys, [Key::Command('b'), Key::Command('i'), Key::Command('u')]); + assert!(rt.state.f.marks().is_empty()); + // A field with no formatting lays out as plain text: no spans, blocks or soft breaks. + let n = rt.tree.nodes.iter().find(|n| n.key.as_deref() == Some("f")).unwrap(); + let t = n.text.as_ref().unwrap(); + assert!(t.spans.is_empty() && t.cold.blocks.is_empty() && t.cold.soft_breaks.is_empty() && t.cold.strikes.is_empty()); +} + +#[test] +fn direct_text_assignment_never_panics_in_runtime() { + let mut e = TextEdit::from_html("<ul><li><b>bold</b> <a href=\"https://a.b\">item</a></li></ul><pre><code>a\nb</code></pre><p>x<br>y</p>"); + e.set_caret(e.text.len()); + e.focused = true; + + struct App { e: TextEdit } + fn view(s: &App, _: &mut Cx<App>) -> El { + text_input(&s.e, TextStyle::new(14.0, 400.0)).key("e").size(200.0, 120.0).on_edit(|s: &mut App| &mut s.e) + } + let mut rt = Runtime::new(App { e }, view, (200.0, 120.0), Env::new(true, 1.0)); + rt.frame(0.0); + rt.update(|s, _| { + s.e.text = "é🦀".into(); + s.e.anchor = 1; + s.e.focus = 3; + }); + rt.frame(0.0); + rt.ime(Ime::Preedit("あ".into(), None, Vec::new())); + rt.frame(0.0); + rt.key(k(Key::Right)); + rt.ime(Ime::Commit("あ".into())); + rt.frame(0.0); + assert_invariants(&rt.state.e, "runtime"); +} + +#[test] +fn copy_from_one_rich_field_pastes_marks_and_blocks_into_another() { + struct App { a: TextEdit, b: TextEdit, plain: TextEdit } + fn view(s: &App, _: &mut Cx<App>) -> El { + let st = TextStyle::new(14.0, 400.0); + col().size(320.0, 360.0) + .child(text_input(&s.a, st).key("a").size(300.0, 140.0).on_edit(|s: &mut App| &mut s.a)) + .child(text_input(&s.b, st).key("b").size(300.0, 140.0).on_edit(|s: &mut App| &mut s.b)) + .child(text_input(&s.plain, st).key("plain").size(300.0, 40.0).on_edit(|s: &mut App| &mut s.plain)) + } + let mut a = TextEdit::from_html( + "<p>Hello <b>bold</b> <a href=\"https://example.com\">link</a></p><ul><li>one</li><li><i>two</i></li></ul><blockquote>q</blockquote>", + ); + a.focused = true; + a.set_selection(0, a.text.len()); + let m = crate::clipboard::memory(); + let mut rt = Runtime::new(App { a, b: TextEdit::new("").rich(), plain: TextEdit::new("") }, view, (320.0, 360.0), Env::new(true, 1.0)); + rt.use_clipboard(&m); + rt.frame(0.0); + rt.key(cmd('c')); + rt.frame(0.0); + let copied = m.content().unwrap(); + assert_eq!(copied.text(), rt.state.a.text); + assert!(copied.html().is_some_and(|h| h.contains("<strong>bold</strong>") && h.contains("<ul>")), "{copied:?}"); + + rt.update(|s, _| { s.a.focused = false; s.b.focused = true; }); + rt.frame(0.0); + rt.update(|_, tx| tx.request_paste()); + rt.frame(0.0); + let (a, b) = (&rt.state.a, &rt.state.b); + assert_eq!((&b.text, b.marks(), b.blocks()), (&a.text, a.marks(), a.blocks())); + + // Cut carries the formatting it removes. + rt.update(|s, _| s.b.set_selection(6, 10)); + rt.key(cmd('x')); + rt.frame(0.0); + assert_eq!(rt.state.b.text, format!("Hello link{}", &rt.state.a.text[15..])); + assert!(m.content().unwrap().html().is_some_and(|h| h.contains("<strong>bold</strong>"))); + + // A plain field pastes the text only and copies no HTML. + rt.update(|s, _| { s.b.focused = false; s.plain.focused = true; }); + rt.frame(0.0); + rt.update(|_, tx| tx.request_paste()); + rt.frame(0.0); + assert_eq!(rt.state.plain.text, "bold"); + assert!(rt.state.plain.is_plain()); + rt.update(|s, _| s.plain.set_selection(0, 4)); + rt.key(cmd('c')); + rt.frame(0.0); + assert_eq!(m.content().unwrap().html(), None); +} + +#[test] +fn a_pill_copied_from_one_rich_field_pastes_whole_into_another() { + struct App { a: TextEdit, b: TextEdit, hooked: TextEdit } + fn view(s: &App, _: &mut Cx<App>) -> El { + let st = TextStyle::new(14.0, 400.0); + col().size(320.0, 360.0) + .child(text_input(&s.a, st).key("a").size(300.0, 100.0).on_edit(|s: &mut App| &mut s.a)) + .child(text_input(&s.b, st).key("b").size(300.0, 100.0).on_edit(|s: &mut App| &mut s.b)) + .child(text_input(&s.hooked, st).key("hooked").size(300.0, 100.0).on_edit(|s: &mut App| &mut s.hooked) + .on_input_paste(|s: &mut App, content, _| { + let Some(html) = content.html() else { return false }; + s.hooked.paste_html_with_pills(html, content.text()); + true + })) + } + let mut a = with_pill(); + a.focused = true; + a.set_selection(0, a.text.len()); + let m = crate::clipboard::memory(); + let mut rt = Runtime::new(App { a, b: TextEdit::new("").rich(), hooked: TextEdit::new("").rich() }, view, (320.0, 360.0), Env::new(true, 1.0)); + rt.use_clipboard(&m); + rt.frame(0.0); + rt.key(cmd('c')); + rt.frame(0.0); + let copied = m.content().unwrap(); + assert_eq!(copied.text(), "a @x-agent b"); + assert!(copied.html().is_some_and(|h| h.contains("<span data-pill=\"agent:x\">@x-agent</span>")), "{copied:?}"); + let paste_into = |rt: &mut Runtime<App>, which: fn(&mut App) -> &mut TextEdit| { + rt.update(move |s, _| { s.a.focused = false; s.b.focused = false; s.hooked.focused = false; which(s).focused = true; }); + rt.frame(0.0); + rt.update(|_, tx| tx.request_paste()); + rt.frame(0.0); + }; + paste_into(&mut rt, |s| &mut s.b); + assert_eq!(pills_of(&rt.state.b), [(2..10, "agent:x".to_owned())], "its own copy pastes the pill back"); + + // The same HTML from outside (another app's copy) pastes plain labels, even with identical plain text, unless a hook keeps them. + m.set_content(ClipboardContent::new("a @x-agent b").with_html("a <span data-pill=\"agent:x\">@x-agent</span> b")); + rt.update(|s, _| s.b.set_selection(0, s.b.text.len())); + paste_into(&mut rt, |s| &mut s.b); + assert_eq!((rt.state.b.text.as_str(), rt.state.b.pills().count()), ("a @x-agent b", 0)); + m.set_content(ClipboardContent::new("x @x-agent").with_html("x <span data-pill=\"agent:x\">@x-agent</span>")); + rt.update(|s, _| s.b.set_selection(0, s.b.text.len())); + paste_into(&mut rt, |s| &mut s.b); + assert_eq!((rt.state.b.text.as_str(), rt.state.b.pills().count()), ("x @x-agent", 0)); + paste_into(&mut rt, |s| &mut s.hooked); + assert_eq!(pills_of(&rt.state.hooked), [(2..10, "agent:x".to_owned())]); +} diff --git a/app/vendor/rune/crates/rune/src/runtime/tests/event_markers.rs b/app/vendor/rune/crates/rune/src/runtime/tests/event_markers.rs new file mode 100644 index 0000000..63505e7 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/tests/event_markers.rs @@ -0,0 +1,42 @@ +use super::*; + +fn view(_: &usize, _: &mut Cx<usize>) -> El { + el().key("tap").size(40.0, 40.0).on_press(|n: &mut usize| *n += 1) +} + +fn tap(rt: &mut Runtime<usize>) { + rt.pointer_move(20.0, 20.0); + rt.pointer_down(20.0, 20.0); + rt.pointer_up(20.0, 20.0); + rt.frame(1.0 / 120.0); +} + +fn presses(rt: &Runtime<usize>) -> usize { + rt.events.iter().filter(|e| e.starts_with("press ") && e.ends_with("tap")).count() +} + +#[test] +fn a_live_window_records_no_input_markers_unless_tracing() { + let mut rt = Runtime::new(0, view, (100.0, 100.0), Env::new(true, 1.0)); + rt.frame.set_record_events(false); + rt.frame(0.0); + tap(&mut rt); + assert_eq!(rt.state, 1); + assert!(rt.events.is_empty(), "nothing reads them: {:?}", rt.events); + rt.frame.enable_trace_channels(true); + tap(&mut rt); + assert_eq!(rt.state, 2); + assert_eq!(presses(&rt), 1, "a trace reads them: {:?}", rt.events); +} + +#[test] +fn unread_input_markers_stay_bounded() { + let mut rt = Runtime::new(0, view, (100.0, 100.0), Env::new(true, 1.0)); + rt.frame(0.0); + let taps = event_log::CAP + 40; + for _ in 0..taps { tap(&mut rt); } + assert_eq!(rt.state, taps); + assert!(rt.events.len() <= event_log::CAP, "{} unread markers", rt.events.len()); + assert!(presses(&rt) >= event_log::CAP / 2, "the newest stay"); + assert!(rt.events.last().is_some_and(|e| e.starts_with("press "))); +} diff --git a/app/vendor/rune/crates/rune/src/runtime/tests/find_key.rs b/app/vendor/rune/crates/rune/src/runtime/tests/find_key.rs new file mode 100644 index 0000000..762e216 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/tests/find_key.rs @@ -0,0 +1,123 @@ +use super::*; +use crate::el::row; + +#[test] +fn a_key_path_skips_elements_without_keys() { + struct State; + fn view(_: &State, _: &mut Cx<State>) -> El { + col() + .child(el().key("other").child(el().key("knob").size(10.0, 10.0))) + .child( + el().key("form").child( + row().child(el().size(30.0, 10.0)).child(el().key("slider").child(col().child(el().key("knob").size(20.0, 20.0)))), + ), + ) + } + let mut rt = Runtime::new(State, view, (100.0, 100.0), Env { system_dark: true, scale: 2.0 }); + rt.frame(0.0); + assert_eq!(rt.find("slider/knob"), Some((40.0, 20.0))); + assert_eq!(rt.find("form/slider/knob"), Some((40.0, 20.0))); + assert_eq!(rt.find("other/knob"), Some((5.0, 5.0))); + assert_eq!(rt.find("form/knob"), None, "keyed segments must still be adjacent"); + assert_eq!(rt.find("knob"), Some((5.0, 5.0)), "a bare key finds the first element with it"); +} + +#[test] +fn scaled_link_and_highlight_elements_keep_unscaled_targets() { + fn view(scale: &f32, _: &mut Cx<f32>) -> El { + col().size(400.0, 200.0).child( + col().size(200.0, 100.0).scale(*scale).origin(0.0, 0.0).child( + crate::rich("Check link and mark here.", vec![]) + .key("body").padding(8.0) + .link(crate::Link::new(6..10, "doc")) + .text_highlight(crate::TextHighlight::new(15..19, Color::WHITE).key("hl")), + ), + ) + } + let make = |scale: f32| { + let mut rt = Runtime::new(scale, view, (400.0, 200.0), Env::new(true, 1.0)); + rt.frame(0.0); + rt + }; + let rt1 = make(1.0); + let rt2 = make(2.0); + let find_el = |rt: &Runtime<f32>, key: &str| rt.elements().into_iter().find(|e| e.key.as_deref() == Some(key)).unwrap(); + for key in ["doc", "hl"] { + let e1 = find_el(&rt1, key); + let e2 = find_el(&rt2, key); + assert!((e2.rect[2] - e1.rect[2] * 2.0).abs() < 0.5, "{key}: drawn rect scales by 2x"); + assert!( + e1.target.iter().zip(e2.target).all(|(a, b)| (a - b).abs() < 0.2), + "{key}: target must stay unscaled layout rect, got {:?} vs {:?}", e1.target, e2.target + ); + } +} + +#[test] +fn keyed_lookups_skip_exiting_nodes_and_popup_anchors_match_keyed_suffix() { + // 1. PopupMenu anchor_rect matches keyed-suffix paths across unkeyed wrappers (like Runtime::find). + { + let mut rt = Runtime::new((), |_: &(), _: &mut Cx<()>| { + col().size(200.0, 100.0).child( + col().key("slider").child(row().child(el().key("knob").size(20.0, 20.0))), + ) + }, (200.0, 100.0), Env::new(true, 1.0)); + rt.frame(0.0); + assert!(rt.find("slider/knob").is_some()); + rt.update(|_, tx| { + tx.popup_menu(crate::PopupMenu::new().item(crate::PopupItem::new("a", "A")), "slider/knob", |_: &mut (), _, _| {}); + }); + rt.frame(0.0); + let opened = rt.take_popup(); + assert!(matches!(opened, Some(Some(_))), "popup anchor_rect must match slider/knob across unkeyed wrapper"); + } + + // 2. reveal_row_x skips exiting (and instantly unmounted) elements instead of scrolling a horizontal viewport to them. + { + fn view(show: &bool, _: &mut Cx<bool>) -> El { + let mut inner = row().w(800.0).h(40.0).child(el().size(180.0, 40.0)); + if *show { + // Straddles the 200pt viewport edge (180..240) so it draws on screen, plays its exit + // transition when removed, and would scroll `hx` by 40pt if `reveal_row_x` matched it. + inner = inner.child(el().key("gone").size(60.0, 40.0).fill(Color::WHITE).transition(crate::Transition::opacity())); + } + col().size(200.0, 60.0).child( + row().key("hx").size(200.0, 40.0).scroll_x().child(inner), + ) + } + let mut rt = Runtime::new(true, view, (200.0, 60.0), Env::new(true, 1.0)); + rt.frame(0.0); + rt.update(|show, tx| { + *show = false; + tx.scroll_into_view("gone"); + }); + rt.frame(1.0 / 60.0); + let gone_idx = rt.tree.nodes.iter().position(|n| n.key.as_deref() == Some("gone")).expect("gone plays its exit"); + assert!(rt.core().subtree_exiting(gone_idx), "gone must be actively exiting"); + let hx = rt.tree.nodes.iter().find(|n| n.key.as_deref() == Some("hx")).unwrap().id; + assert_eq!(rt.scroll.scrolls[&hx].x.offset, 0.0, "reveal_row_x must ignore exiting target"); + } + + // 3. stuck_cover matches keyed suffixes via Node::named and ignores exiting nodes. + { + fn view(show: &bool, _: &mut Cx<bool>) -> El { + let mut hdr = col().key("hdr").w_full().h(30.0).fill(Color::WHITE).sticky_top(0.0) + .child(row().child(el().key("pin").size(40.0, 20.0))); + if *show { + hdr = hdr.child(el().key("leaving").size(40.0, 20.0).transition(crate::Transition::opacity())); + } + col().size(200.0, 120.0).child( + col().key("sc").size(200.0, 120.0).scroll(crate::ScrollSpec { stick_bottom: false }) + .child(col().w_full().child(hdr).child(el().w_full().h(400.0))), + ) + } + let mut rt = Runtime::new(true, view, (200.0, 120.0), Env::new(true, 1.0)); + rt.frame(0.0); + rt.wheel(50.0, 50.0, -80.0); + rt.update(|show, _| *show = false); + rt.frame(1.0 / 60.0); + let sc_path = rt.tree.nodes.iter().find(|n| n.key.as_deref() == Some("sc")).unwrap().path.clone(); + assert_eq!(rt.core().stuck_cover(&sc_path, "hdr/pin"), None, "stuck_cover must match keyed suffix inside stuck header"); + assert!(rt.core().stuck_cover(&sc_path, "leaving").is_some_and(|c| c > 0.0), "stuck_cover must ignore exiting node"); + } +} diff --git a/app/vendor/rune/crates/rune/src/runtime/tests/fold_glide.rs b/app/vendor/rune/crates/rune/src/runtime/tests/fold_glide.rs new file mode 100644 index 0000000..1cccb15 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/tests/fold_glide.rs @@ -0,0 +1,518 @@ +use super::*; +use crate::el::GrowthSpec; + +/// A growth stack whose middle row is 600 pt open or 40 pt shut, with `El::fold_glide` or else +/// `El::arrives_whole`. +fn stack(open: bool, fold: bool) -> El { + let mut row = el().key("group").h(if open { 600.0 } else { 40.0 }).w_full(); + row = if fold { row.fold_glide(rune_motion::Spring::new(0.18, 0.0)) } else { row.arrives_whole() }; + col().key("root").child(col().key("stack").growth(GrowthSpec::default()).children([ + el().key("above").h(100.0).w_full(), + row, + el().key("below").h(100.0).w_full(), + ])) +} + +/// Seconds until the row shut from 600 pt is within half a point of shut, at 120 Hz. +fn shut_secs(fold: bool) -> f32 { + fn folded(s: &(bool, bool), _: &mut Cx<(bool, bool)>) -> El { + stack(s.0, s.1) + } + let mut rt = Runtime::new((true, fold), folded, (400.0, 900.0), Env::new(true, 2.0)); + rt.frame(0.0); + rt.state.0 = false; + rt.commit.dirty = true; + for k in 1..240 { + rt.frame(1.0 / 120.0); + if fold && k < 12 { + assert!(rt.paint.row_mask.iter().any(|&m| m >= 0.0), "shutting, the row clips what it held"); + } + let below = rt.elements().into_iter().find(|e| e.key.as_deref() == Some("below")).unwrap(); + if (below.rect[1] - 140.0).abs() < 0.5 { + return k as f32 / 120.0; + } + } + panic!("still moving after 2 s"); +} + +#[test] +fn a_fold_glide_row_folds_on_its_own_spring() { + let own = shut_secs(true); + let stack = shut_secs(false); + assert!(own < 0.3, "the row's own 0.18 s spring: {own} s"); + assert!(stack > own + 0.2, "the stack's 0.32 s spring, stretched for the distance: {stack} s"); +} + +/// The row's drawn top and height each frame of opening, in a 300 pt window with the stack +/// drawn at `zoom`. +fn opening(zoom: f32) -> Vec<(f32, f32)> { + fn folded(s: &(bool, f32), _: &mut Cx<(bool, f32)>) -> El { + col().key("zoom").scale(s.1).child(stack(s.0, true)) + } + let mut rt = Runtime::new((false, zoom), folded, (400.0, 300.0), Env::new(true, 2.0)); + rt.frame(0.0); + rt.frame(1.0 / 120.0); + rt.state.0 = true; + rt.commit.dirty = true; + (0..60).map(|_| { + rt.frame(1.0 / 120.0); + let row = rt.elements().into_iter().find(|e| e.key.as_deref() == Some("group")).unwrap(); + (row.rect[1], row.rect[3]) + }).collect() +} + +#[test] +fn a_zoomed_fold_moves_only_what_shows_of_it() { + let frames = opening(1.5); + let (top, full) = (frames[0].0, 600.0 * 1.5); + assert!(top < 300.0, "{frames:?}"); + assert!(frames.iter().all(|&(y, h)| y + h <= 300.5 || h == full), "glides to the window's edge, then lands: {frames:?}"); + assert!(frames[20].0 + frames[20].1 > 290.0 && frames[59].1 == full, "{frames:?}"); +} + +#[test] +fn a_fold_moves_only_what_shows_of_it() { + fn folded(open: &bool, _: &mut Cx<bool>) -> El { + stack(*open, true) + } + // The row starts 100 pt down a 300 pt window, so 200 pt of it shows. + let mut rt = Runtime::new(false, folded, (400.0, 300.0), Env::new(true, 2.0)); + rt.frame(0.0); + rt.frame(1.0 / 120.0); + rt.state = true; + rt.commit.dirty = true; + let mut heights = Vec::new(); + for _ in 0..60 { + rt.frame(1.0 / 120.0); + let row = rt.elements().into_iter().find(|e| e.key.as_deref() == Some("group")).unwrap(); + heights.push(row.rect[3]); + } + assert!(heights.iter().all(|&h| h <= 200.5 || h == 600.0), "glides to the window's edge, then lands: {heights:?}"); + assert!(heights[0] < 100.0 && heights[20] > 190.0 && heights[59] == 600.0, "{heights:?}"); +} + +/// Rows `a` (a fold, 600 pt open or 40 pt shut) and `b` (100 pt), in either order, between a +/// 100 pt row above and one below. +fn reordering(s: &(bool, bool), _: &mut Cx<(bool, bool)>) -> El { + let a = el().key("a").w_full().h(if s.0 { 600.0 } else { 40.0 }).fold_glide(rune_motion::Spring::new(0.18, 0.0)); + let b = el().key("b").w_full().h(100.0); + let (first, second) = if s.1 { (b, a) } else { (a, b) }; + col().key("root").child(col().key("stack").w_full().growth(GrowthSpec::default()).children([ + el().key("above").h(100.0).w_full(), + first, + second, + el().key("below").h(100.0).w_full(), + ])) +} + +/// Each key's (top, height) every frame for one second after `a` shuts and swaps with `b` in +/// one commit, in a window `window_h` tall. +fn shut_and_swap(window_h: f32) -> (Runtime<(bool, bool)>, Vec<HashMap<&'static str, (f32, f32)>>) { + let mut rt = Runtime::new((true, false), reordering, (400.0, window_h), Env::new(true, 2.0)); + rt.frame(0.0); + for _ in 0..4 { rt.frame(1.0 / 120.0); } + rt.update(|s, _| *s = (false, true)); + let frames = (0..120).map(|_| { + rt.frame(1.0 / 120.0); + let els = rt.elements(); + ["above", "a", "b", "below"].into_iter().map(|k| { + let e = els.iter().find(|e| e.key.as_deref() == Some(k) && !e.exiting).unwrap(); + (k, (e.rect[1], e.rect[3])) + }).collect() + }).collect(); + (rt, frames) +} + +#[test] +fn a_fold_that_reorders_in_the_same_commit_slides_and_folds_at_once() { + // All on screen: the fold shuts on its spring while it and `b` slide into their new places, + // without a jump, and everything lands where the new order lays it out. + let (rt, frames) = shut_and_swap(900.0); + for w in frames.windows(2) { + for k in ["above", "a", "b", "below"] { + let ((y0, h0), (y1, h1)) = (w[0][k], w[1][k]); + assert!((y1 - y0).abs() < 60.0 && (h1 - h0).abs() < 60.0, "{k} jumps from {y0}+{h0} to {y1}+{h1}: {frames:?}"); + } + assert!(w[1]["a"].1 <= w[0]["a"].1 + 1e-3, "the fold only shuts: {frames:?}"); + } + let last = frames.last().unwrap(); + assert_eq!((last["above"], last["b"], last["a"], last["below"]), ((0.0, 100.0), (100.0, 100.0), (200.0, 40.0), (240.0, 100.0))); + assert!(frames[36]["a"].1 < 41.0, "the fold shuts on its own 0.18 s spring: {:?}", frames[36]["a"]); + assert!(!rt.animating); + // The fold past the window's bottom: what shows of it still shuts and slides without a jump, + // and `b`, drawn below the window, comes in from its edge rather than from far below it. + let (_, frames) = shut_and_swap(300.0); + for w in frames.windows(2) { + let ((y0, h0), (y1, h1)) = (w[0]["a"], w[1]["a"]); + assert!((y1 - y0).abs() < 60.0 && ((y1 + h1).min(300.0) - (y0 + h0).min(300.0)).abs() < 60.0, "a jumps from {y0}+{h0} to {y1}+{h1}: {frames:?}"); + assert!((w[1]["b"].0 - w[0]["b"].0).abs() < 60.0, "b jumps: {frames:?}"); + } + assert!(frames[0]["b"].0 <= 300.0, "{:?}", frames[0]["b"]); + let last = frames.last().unwrap(); + assert_eq!((last["b"], last["a"]), ((100.0, 100.0), (200.0, 40.0))); +} + +/// A section in a fold row: a 28 pt header, sticky to the top, over 1,120 pt of steps when open, +/// 200 pt down a 200 pt scroll whose rows below are 100 pt each. +fn section(open: &bool, _: &mut Cx<bool>) -> El { + let mut group = col().key("group").w_full().child(el().key("hdr").w_full().h(28.0).sticky_top(0.0)); + if *open { + group = group.child(col().key("steps").w_full().children((0..40).map(|k| el().key(format!("step-{k}")).w_full().h(28.0)))); + } + let stack = col().key("stack").w_full().growth(GrowthSpec::default()).children([ + el().key("before").w_full().h(200.0), + col().key("turn").w_full().fold_glide(rune_motion::Spring::new(0.18, 0.0)).child(group), + el().key("after").w_full().h(100.0), + el().key("tail").w_full().h(100.0), + ]); + col().key("scroll").size(300.0, 200.0).scroll(ScrollSpec { stick_bottom: true }).child(stack) +} + +#[test] +fn keep_on_screen_holds_a_stuck_header_while_its_fold_shuts() { + let mut rt = Runtime::new(true, section, (300.0, 200.0), Env::new(true, 1.0)); + rt.frame(0.0); + rt.update(|_, tx| tx.scroll_to_instant("scroll", 0.0, 700.0)); + for _ in 0..4 { rt.frame(1.0 / 120.0); } + let find = |rt: &Runtime<bool>, k: &str| rt.elements().into_iter().find(|e| e.key.as_deref() == Some(k) && !e.exiting).unwrap(); + assert!(find(&rt, "hdr").rect[1] == 0.0 && find(&rt, "hdr").stuck > 400.0, "{:?}", find(&rt, "hdr")); + rt.update(|open, tx| { *open = false; tx.keep_on_screen("hdr"); }); + let mut after = Vec::new(); + for f in 0..120 { + rt.frame(1.0 / 120.0); + let hdr = find(&rt, "hdr").rect[1]; + assert!(hdr.abs() < 0.5, "frame {f}: the header moved to {hdr}"); + let a = find(&rt, "after").rect[1]; + // The row below never shows under the header, nor drops once it shows. + assert!(a >= 28.0 - 0.5, "frame {f}: the row below rose to {a}, over the header"); + after.push(a); + } + let shown: Vec<f32> = after.iter().copied().skip_while(|&a| a >= 200.0).collect(); + assert!(shown.windows(2).all(|w| w[1] <= w[0] + 0.5), "the row below only rises once it shows: {after:?}"); + assert!(after[36] < 28.5, "it reaches the header on the fold's own spring: {after:?}"); + assert!(*after.last().unwrap() == 28.0 && !rt.scroll.requests.has_keeps() && !rt.animating, "{after:?}"); +} + +/// A fold shutting from 600 pt feathers its moving bottom edge to its `fold_feather` depth, +/// and nothing once it lands. +#[test] +fn a_fold_feathers_its_edge_shutting_too() { + fn folded(open: &bool, _: &mut Cx<bool>) -> El { + let row = el().key("group").h(if *open { 600.0 } else { 40.0 }).w_full().fold_glide(rune_motion::Spring::new(0.18, 0.0)).fold_feather(16.0); + col().key("root").child(col().key("stack").growth(GrowthSpec::default()).children([el().key("above").h(100.0).w_full(), row])) + } + let mut rt = Runtime::new(true, folded, (400.0, 900.0), Env::new(true, 2.0)); + rt.frame(0.0); + rt.update(|s, _| *s = false); + let group = |rt: &Runtime<bool>| rt.tree.nodes.iter().position(|n| n.named("group")).unwrap(); + let masks: Vec<f32> = (0..60).map(|_| { + rt.frame(1.0 / 120.0); + rt.paint.row_mask[group(&rt)] + }).collect(); + let peak = masks.iter().copied().fold(0.0, f32::max); + assert!((peak - 16.0).abs() < 1e-3, "shutting, the moving edge feathers {peak} pt deep: {masks:?}"); + assert!(masks.last().is_some_and(|&m| m < 0.0), "and nothing is feathered once it lands: {masks:?}"); +} + +/// A fold of 40 steps under a sticky 28 pt header, between a 200 pt row above and a row `after` +/// points tall below, in a 200 pt scroll. +fn held_section(s: &(bool, f32), _: &mut Cx<(bool, f32)>) -> El { + let mut group = col().key("group").w_full().child(el().key("hdr").w_full().h(28.0).sticky_top(0.0)); + if s.0 { + group = group.child(col().key("steps").w_full().children((0..40).map(|k| el().key(format!("step-{k}")).w_full().h(28.0)))); + } + let stack = col().key("stack").w_full().growth(GrowthSpec::default()).children([ + el().key("before").w_full().h(200.0), + col().key("turn").w_full().fold_glide(rune_motion::Spring::new(0.18, 0.0)).child(group), + el().key("after").w_full().h(s.1), + ]); + col().key("scroll").size(300.0, 200.0).scroll(ScrollSpec { stick_bottom: true }).child(stack) +} + +/// Shuts the fold from its stuck header with the timeline scrolled to `offset`, holding the +/// header, and returns each frame's tops of the header, the rows around the fold and every step +/// that draws in the window. +fn shut_from_stuck(after: f32, offset: f32) -> Vec<HashMap<String, f32>> { + let mut rt = Runtime::new((true, after), held_section, (300.0, 200.0), Env::new(true, 1.0)); + rt.frame(0.0); + rt.update(|_, tx| tx.scroll_to_instant("scroll", 0.0, offset)); + for _ in 0..4 { rt.frame(1.0 / 120.0); } + let hdr = rt.elements().into_iter().find(|e| e.key.as_deref() == Some("hdr")).unwrap(); + assert!(hdr.rect[1] == 0.0 && hdr.stuck > 400.0, "{hdr:?}"); + rt.update(|s, tx| { s.0 = false; tx.keep_on_screen("hdr"); }); + let frames = (0..90).map(|_| { + rt.frame(1.0 / 120.0); + rt.elements().into_iter().filter_map(|e| { + let k = e.key.clone()?; + let shows = e.rect[1] < 200.0 && e.rect[1] + e.rect[3] > 28.0; + (["hdr", "before", "after"].contains(&k.as_str()) || (k.starts_with("step-") && shows)).then_some((k, e.rect[1])) + }).collect() + }).collect(); + assert!(!rt.animating && !rt.scroll.requests.has_keeps()); + frames +} + +/// The most anything that shows moved in one frame, and the frame. +fn biggest_step(frames: &[HashMap<String, f32>]) -> (f32, usize) { + let mut most = (0.0, 0); + for (f, w) in frames.windows(2).enumerate() { + for (k, &y1) in &w[1] { + let Some(&y0) = w[0].get(k) else { continue }; + let seen = |y: f32| y > -28.0 && y < 200.0; + if (seen(y0) || seen(y1)) && (y1 - y0).abs() > most.0 { most = ((y1 - y0).abs(), f + 1); } + } + } + most +} + +#[test] +fn a_fold_shut_from_its_stuck_header_at_the_end_slides_up_under_it() { + // 1,120 pt of steps, the header stuck at the top, the last steps and the row below in view: + // shut, the timeline ends 128 pt down what it shows, so the header comes down to 72. + let frames = shut_from_stuck(100.0, 1100.0); + let (most, at) = biggest_step(&frames); + assert!(most < 24.0, "nothing that shows moves {most} pt in a frame (frame {at}): {:?}", &frames[at.saturating_sub(1)..=at]); + let after: Vec<f32> = frames.iter().map(|f| f["after"]).collect(); + assert!(after.windows(2).all(|w| w[1] <= w[0] + 0.01), "the row below only rises: {after:?}"); + // The steps that show ride up with the row below the whole way, slowing as the header + // comes down over them. + for w in frames.windows(2) { + for (k, &y1) in w[1].iter().filter(|(k, _)| k.starts_with("step-")) { + if let Some(&y0) = w[0].get(k) { assert!(y1 <= y0 + 0.01, "{k} moves down, {y0} to {y1}"); } + } + } + let last = frames.last().unwrap(); + assert_eq!((last["hdr"], last["after"], last["before"]), (72.0, 100.0, -128.0)); + assert!(frames[40]["hdr"] > 71.0, "it lands on the fold's own spring: {:?}", frames[40]); +} + +#[test] +fn a_fold_shut_from_its_stuck_header_mid_timeline_still_glides() { + // The rows below fill the window: the header stays, and what shows slides up under it on + // the fold's spring with the row below, instead of vanishing. + let frames = shut_from_stuck(300.0, 1100.0); + let (most, at) = biggest_step(&frames); + assert!(most < 24.0, "nothing that shows moves {most} pt in a frame (frame {at}): {:?}", &frames[at.saturating_sub(1)..=at]); + assert!(frames.iter().all(|f| f["hdr"].abs() < 0.01), "the header holds"); + let after: Vec<f32> = frames.iter().map(|f| f["after"]).collect(); + assert!(after[2] > 100.0 && after[12] < 100.0 && after[40] < 28.5, "glides, rather than landing at once: {after:?}"); + assert!(frames[4].keys().any(|k| k.starts_with("step-")), "the steps still show as it shuts: {:?}", frames[4]); + assert_eq!(*after.last().unwrap(), 28.0); +} + +#[test] +fn a_long_fold_shut_from_its_stuck_header_at_the_end_is_one_motion() { + // The rehearsal's long tool group: shut from its stuck header with the timeline's end just + // below the window. What shows used to ride the bottom edge up for 2 or 3 frames, stop dead + // when the end held the row below, and leave the header to come down over it alone, so the + // steps it covered landed out of sight. Now the steps slow as the header comes down, without + // a dead stop, nothing moves faster than the fold's own spring, and nothing lands unseen. + // Down to a few points short of the end, where a frame's shut is more than the end has + // left to give, and the viewport clamps at its end before the header's hold moves it. + for short in [130.0, 80.0, 40.0, 20.0, 8.0] { + let mut rt = Runtime::new((true, 100.0), held_section, (300.0, 200.0), Env::new(true, 1.0)); + rt.frame(0.0); + let max = rt.scroll.scrolls.values().next().unwrap().max as f32; + let offset = max - short; + rt.update(|_, tx| tx.scroll_to_instant("scroll", 0.0, offset)); + for _ in 0..4 { rt.frame(1.0 / 120.0); } + rt.update(|s, tx| { s.0 = false; tx.keep_on_screen("hdr"); }); + // Each frame: the fold's height, and each element's top, visible height and height. + let mut frames: Vec<(f32, HashMap<String, (f32, f32, f32)>)> = Vec::new(); + for _ in 0..120 { + rt.frame(1.0 / 120.0); + let els = rt.elements(); + let turn = els.iter().find(|e| e.key.as_deref() == Some("turn")).unwrap().rect[3]; + frames.push((turn, els.into_iter().filter_map(|e| { + let k = e.key.clone()?; + (k == "hdr" || k == "after" || k.starts_with("step-")).then_some((k, (e.rect[1], e.visible[3], e.rect[3]))) + }).collect())); + } + assert!(!rt.animating, "{offset}: it settles"); + let at = |f: usize, k: &str| frames[f].1.get(k).copied(); + for f in 2..frames.len() { + let spring = (frames[f].0 - frames[f - 1].0).abs(); + for (k, &(y, seen, _)) in &frames[f].1 { + let (Some((y1, seen1, _)), Some((y0, _, _))) = (at(f - 1, k), at(f - 2, k)) else { continue }; + if seen < 0.5 && seen1 < 0.5 { continue; } + let (v0, v) = (y1 - y0, y - y1); + assert!(v.abs() <= spring + 0.5, "{offset}: {k} moves {v} pt in frame {f}, the fold {spring}"); + // Still in view, it doesn't go from moving to stopped (or turn back) in a frame. + if seen > 0.5 && v0.abs() > 2.0 { + assert!(v * v0.signum() >= 0.5 * v0.abs(), "{offset}: {k} goes from {v0} to {v} pt a frame in frame {f}"); + } + } + } + // Nothing travels 40 pt in plain view and then drops out of it in one frame where it rests. + let last = &frames.last().unwrap().1; + for (k, &(rest, _, _)) in last.iter().filter(|(k, _)| k.starts_with("step-")) { + let mut travelled = 0.0; + for f in 1..frames.len() { + let (Some((y0, seen0, h)), Some((y, seen, _))) = (at(f - 1, k), at(f, k)) else { continue }; + if seen0 >= h - 0.5 { travelled += (y - y0).abs(); } + assert!(!(travelled >= 40.0 && seen0 > h * 0.5 && seen < 0.5 && (y - rest).abs() < 0.5), + "{offset}: {k} travels {travelled} pt in view, then is cut from view where it rests in frame {f}"); + } + } + } +} + +/// Shuts the fold from its stuck header as `shut_from_stuck` does, then `at` frames later (0: +/// in the same tick, before a frame draws) opens it again holding its top, and returns each +/// frame's tops of the header, the rows around the fold and every step, from the shut on. No +/// step ever shows above the header. +fn reopen_from_stuck(after: f32, offset: f32, at: usize) -> Vec<HashMap<String, f32>> { + let mut rt = Runtime::new((true, after), held_section, (300.0, 200.0), Env::new(true, 1.0)); + rt.frame(0.0); + rt.update(|_, tx| tx.scroll_to_instant("scroll", 0.0, offset)); + for _ in 0..4 { rt.frame(1.0 / 120.0); } + rt.update(|s, tx| { s.0 = false; tx.keep_on_screen("hdr"); }); + let mut frames = Vec::new(); + for f in 0..at + 120 { + if f == at { rt.update(|s, tx| { s.0 = true; tx.keep_on_screen("turn"); }); } + rt.frame(1.0 / 120.0); + let els = rt.elements(); + let hdr = els.iter().find(|e| e.key.as_deref() == Some("hdr")).unwrap().rect[1]; + for e in els.iter().filter(|e| e.key.as_deref().is_some_and(|k| k.starts_with("step-")) && e.visible[3] > 0.5) { + assert!(e.visible[1] >= hdr - 0.5, "frame {f}: {:?} shows from {} above the header at {hdr}", e.key, e.visible[1]); + } + frames.push(els.into_iter().filter_map(|e| { + let k = e.key.clone()?; + (["hdr", "before", "after"].contains(&k.as_str()) || k.starts_with("step-")).then_some((k, e.rect[1])) + }).collect()); + } + assert!(!rt.animating, "it settles"); + let turn = rt.elements().into_iter().find(|e| e.key.as_deref() == Some("turn")).unwrap(); + assert_eq!(turn.rect[3], 28.0 + 40.0 * 28.0, "it ends fully open"); + frames +} + +/// The most anything with more than two points in view moved in one frame (a glide opening +/// past the window lands the rest once its edge is within a point or so), and the frame. +fn biggest_reopen_step(frames: &[HashMap<String, f32>]) -> (f32, usize, String) { + let mut most = (0.0, 0, String::new()); + for (f, w) in frames.windows(2).enumerate() { + for (k, &y1) in &w[1] { + let Some(&y0) = w[0].get(k) else { continue }; + let seen = |y: f32| y > -26.0 && y < 198.0; + if (seen(y0) || seen(y1)) && (y1 - y0).abs() > most.0 { most = ((y1 - y0).abs(), f + 1, k.clone()); } + } + } + most +} + +#[test] +fn a_fold_reopened_as_it_shuts_from_its_stuck_header_never_jumps() { + // At the end (the header comes down once the end holds the row below) and mid-timeline, + // opened again in the shut's own tick, while its contents ride up under the header, and + // once the header is coming down: nothing in view moves more than a frame's spring, and + // what was hidden above comes back above. + for (after, label) in [(100.0, "at the end"), (300.0, "mid-timeline")] { + for at in [0, 1, 3, 8, 16, 30] { + let frames = reopen_from_stuck(after, 1100.0, at); + let (most, f, key) = biggest_reopen_step(&frames); + assert!(most < 24.0, "{label}, reopened {at} frames in: {key} moves {most} pt in frame {f}: {:?} -> {:?}", + frames[f - 1].get(&key), frames[f].get(&key)); + let last = frames.last().unwrap(); + assert!(last.contains_key("step-0") && last["after"] > 0.0, "{label}, {at}: {last:?}"); + } + } +} + +#[test] +fn a_fold_shut_from_its_stuck_header_makes_no_jump_that_shows() { + // What drops above the window drops in one frame, with the scroll offset by as much: the + // fold's top and height step, but nothing that shows moves. Shut by a tap or by data, with + // no input to excuse what the offset brings into view. + for (after, tap) in [(100.0, true), (300.0, true), (100.0, false), (300.0, false)] { + let mut run = crate::motion_gate::Run::new(Runtime::new((true, after), held_section, (300.0, 200.0), Env::new(true, 1.0)), 120.0); + run.rt.update(|_, tx| tx.scroll_to_instant("scroll", 0.0, 1100.0)); + run.idle(0.1); + run.step(); + let shut = |rt: &mut Runtime<(bool, f32)>| rt.update(|s, tx| { s.0 = false; tx.keep_on_screen("hdr"); }); + if tap { run.act("shut", shut) } else { shut(&mut run.rt); run.step() } + run.play(0.75); + let jumps: Vec<String> = run.finish().iter().filter(|f| ["jump", "jerk", "offset-jump"].contains(&f.kind)).map(|f| f.to_string()).collect(); + assert!(jumps.is_empty(), "after {after}, tap {tap}: {jumps:#?}"); + } +} + +/// Where `below` is drawn on each of the first `n` frames at 120 Hz after the middle row (a +/// fold, or a plain row) leaves the stack. +fn after_removal(fold: bool, n: usize) -> Vec<f32> { + fn view(s: &(bool, bool), _: &mut Cx<(bool, bool)>) -> El { + let (present, fold) = *s; + let mut rows = vec![el().key("above").h(100.0).w_full()]; + if present { + let row = el().key("group").h(40.0).w_full(); + rows.push(if fold { row.fold_glide(rune_motion::Spring::new(0.3, 0.0)) } else { row }); + } + rows.push(el().key("below").h(100.0).w_full()); + col().key("root").child(col().key("stack").growth(GrowthSpec::default()).children(rows)) + } + let mut rt = Runtime::new((true, fold), view, (400.0, 600.0), Env::new(true, 2.0)); + rt.frame(0.0); + rt.state.0 = false; + rt.commit.dirty = true; + (0..n).map(|_| { + rt.frame(1.0 / 120.0); + rt.elements().into_iter().find(|e| e.key.as_deref() == Some("below")).unwrap().rect[1] + }).collect() +} + +#[test] +fn a_fold_glide_row_that_leaves_shuts_at_once() { + let fold = after_removal(true, 12); + assert!(fold[1] < 140.0 - 0.5, "the fold starts shutting within two frames: {fold:?}"); + assert!(fold.windows(2).all(|w| w[1] <= w[0]), "and shuts monotonically: {fold:?}"); + let plain = after_removal(false, 12); + assert!(plain.iter().all(|&y| (y - 140.0).abs() < 1e-3), "a plain row still holds its space while it fades: {plain:?}"); +} + +/// Each frame at 120 Hz after rows `r0`–`r2` (20 pt folds) come into or leave the stack +/// together: their drawn heights, and where `below` is drawn. +fn block(opening: bool, frames: usize) -> Vec<([f32; 3], f32)> { + fn view(present: &bool, _: &mut Cx<bool>) -> El { + let mut rows = vec![el().key("above").h(100.0).w_full()]; + if *present { + rows.extend((0..3).map(|i| el().key(format!("r{i}")).h(20.0).w_full().fold_glide(rune_motion::Spring::new(0.3, 0.0)))); + } + rows.push(el().key("below").h(100.0).w_full()); + col().key("root").child(col().key("stack").growth(GrowthSpec::default()).children(rows)) + } + let mut rt = Runtime::new(!opening, view, (400.0, 600.0), Env::new(true, 2.0)); + rt.frame(0.0); + rt.state = opening; + rt.commit.dirty = true; + (0..frames).map(|_| { + rt.frame(1.0 / 120.0); + let els = rt.elements(); + let h = |k: &str| els.iter().find(|e| e.key.as_deref() == Some(k)).map_or(0.0, |e| e.rect[3]); + ([h("r0"), h("r1"), h("r2")], els.iter().find(|e| e.key.as_deref() == Some("below")).unwrap().rect[1]) + }).collect() +} + +#[test] +fn fold_rows_that_open_together_fill_top_to_bottom() { + let frames = block(true, 90); + for (k, (hs, _)) in frames.iter().enumerate() { + let part = hs.iter().filter(|&&h| h > 0.01 && h < 19.99).count(); + assert!(part <= 1, "frame {k}: one row at the edge at a time: {hs:?}"); + assert!(hs.windows(2).all(|w| w[1] <= 0.01 || w[0] >= 19.99), "frame {k}: a row opens once the one above is open: {hs:?}"); + } + assert!(frames.windows(2).all(|w| w[1].1 >= w[0].1), "below moves down, never back: {frames:?}"); + assert!(frames[8].0[0] > 19.99 && frames[8].0[2] < 0.01, "a third in, the top row is open and the last still shut: {:?}", frames[8]); + assert_eq!(frames.last().unwrap(), &([20.0; 3], 160.0)); +} + +#[test] +fn fold_rows_that_leave_together_empty_bottom_to_top() { + let frames = block(false, 90); + for (k, (hs, _)) in frames.iter().enumerate() { + let part = hs.iter().filter(|&&h| h > 0.01 && h < 19.99).count(); + assert!(part <= 1, "frame {k}: one row at the edge at a time: {hs:?}"); + } + assert!(frames.windows(2).all(|w| w[1].1 <= w[0].1), "below moves up, never back: {frames:?}"); + assert!(frames[1].1 < 160.0, "the block starts shutting at once: {:?}", frames[1]); + assert!((frames.last().unwrap().1 - 100.0).abs() < 1e-3); +} diff --git a/app/vendor/rune/crates/rune/src/runtime/tests/glyph_replay.rs b/app/vendor/rune/crates/rune/src/runtime/tests/glyph_replay.rs new file mode 100644 index 0000000..744e11a --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/tests/glyph_replay.rs @@ -0,0 +1,62 @@ +use super::*; +use crate::el::ScrollSpec; + +const PROSE: &str = "Amber lantern orchard quiet harbor, copper meadow signal drift. Pebble willow \ + ember tide under a juniper kestrel; nimbus opal prism and a quiet harbor beneath the lantern. "; + +fn prose(_: &(), _: &mut Cx<()>) -> El { + col().key("scroll").size(320.0, 240.0).scroll(ScrollSpec { stick_bottom: false }).children((0..40).map(|i| { + crate::text(format!("{i}. {}", PROSE.repeat(1 + i % 3))).key(format!("p{i}")) + .font(crate::TextStyle::new(13.0, 400.0)).color(crate::Color::WHITE).w_full() + })) +} + +fn instance_bytes(rt: &Runtime<()>) -> Vec<u8> { + bytemuck::cast_slice(&rt.instances).to_vec() +} + +/// Scrolling replays each paragraph's glyphs: a frame walks Parley only for lines it hasn't +/// drawn before, and draws exactly what a fresh window scrolled to the same place draws. +#[test] +fn scrolling_replays_glyphs_it_has_drawn() { + let mut rt = Runtime::new((), prose, (320.0, 240.0), Env::new(true, 2.0)); + rt.frame(0.0); + for _ in 0..12 { + rt.wheel(160.0, 120.0, -7.0); + rt.frame(1.0 / 120.0); + } + let flattened = rt.text.glyph_cache.flattened; + for _ in 0..12 { + rt.wheel(160.0, 120.0, 7.0); + rt.frame(1.0 / 120.0); + } + assert_eq!(rt.text.glyph_cache.flattened, flattened, "scrolling back walks no Parley lines"); + for _ in 0..12 { + rt.wheel(160.0, 120.0, -7.0); + rt.frame(1.0 / 120.0); + } + assert_eq!(rt.text.glyph_cache.flattened, flattened); + for _ in 0..30 { rt.frame(1.0 / 120.0); } + + let mut fresh = Runtime::new((), prose, (320.0, 240.0), Env::new(true, 2.0)); + fresh.frame(0.0); + fresh.wheel(160.0, 120.0, -84.0); + for _ in 0..30 { fresh.frame(1.0 / 120.0); } + assert_eq!(fresh.scroll.scrolls.values().next().map(|s| s.offset), rt.scroll.scrolls.values().next().map(|s| s.offset)); + assert!(rt.instances.len() > 200); + assert!(instance_bytes(&rt) == instance_bytes(&fresh), "replayed glyphs draw as freshly walked ones"); +} + +/// A secret's glyphs never stay in the replay cache. +#[test] +fn secure_fields_keep_no_glyphs() { + fn view(s: &crate::TextEdit, _: &mut Cx<crate::TextEdit>) -> El { + crate::text_input(s, crate::TextStyle::new(16.0, 400.0)).single_line().secure() + .key("secret").size(200.0, 40.0).on_edit(|s: &mut crate::TextEdit| s) + } + let mut rt = Runtime::new(crate::TextEdit::new("hunter2"), view, (200.0, 40.0), Env::new(true, 2.0)); + rt.frame(0.0); + rt.frame(1.0 / 60.0); + assert!(rt.instances.iter().any(|q| q.params[1] == KIND_GLYPH)); + assert_eq!(rt.text.glyph_cache.len(), 0); +} diff --git a/app/vendor/rune/crates/rune/src/runtime/tests/group_opacity.rs b/app/vendor/rune/crates/rune/src/runtime/tests/group_opacity.rs new file mode 100644 index 0000000..b0fe2d0 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/tests/group_opacity.rs @@ -0,0 +1,146 @@ +use super::*; + +type S = (bool, bool, bool); + +/// A row whose "act" child rests at `s.0`'s level and shows on hover; `s.1` mounts a second +/// one; `s.2` turns on reduced motion. +fn view(s: &S, cx: &mut Cx<S>) -> El { + cx.reduced_motion(s.2); + let rest = if s.0 { 1.0 } else { 0.0 }; + let mut row = crate::row().key("row").size(200.0, 40.0).hover_group() + .child(el().key("act").size(10.0, 10.0).fill(Color::WHITE).group_opacity(rest, 1.0)); + if s.1 { + row = row.child(el().key("new").size(10.0, 10.0).fill(Color::WHITE).group_opacity(0.0, 1.0)); + } + col().size(200.0, 100.0).child(row) +} + +fn alpha(rt: &Runtime<S>, key: &str) -> f32 { + rt.elements().into_iter().find(|e| e.key.as_deref() == Some(key)).map_or(-1.0, |e| e.opacity) +} + +#[test] +fn a_rest_change_animates_with_the_element() { + let mut rt = Runtime::new((false, false, false), view, (200.0, 100.0), Env::new(true, 1.0)); + rt.frame(0.0); + assert_eq!(alpha(&rt, "act"), 0.0); + rt.update(|s, _| s.0 = true); + let mut seen = Vec::new(); + for _ in 0..120 { + rt.frame(1.0 / 120.0); + seen.push(alpha(&rt, "act")); + } + assert!(seen[0] < 0.5, "the first frame doesn't cut to the new rest: {seen:?}"); + assert!(seen.windows(2).all(|w| w[1] >= w[0] - 1e-4), "it rises: {seen:?}"); + assert!((seen[119] - 1.0).abs() < 1e-3, "and lands: {seen:?}"); + assert!(!rt.animating); +} + +#[test] +fn a_rest_change_snaps_when_instant_or_reduced() { + let mut rt = Runtime::new((false, false, false), view, (200.0, 100.0), Env::new(true, 1.0)); + rt.frame(0.0); + rt.update(|s, tx| { tx.instant(); s.0 = true }); + rt.frame(1.0 / 120.0); + assert_eq!(alpha(&rt, "act"), 1.0, "an instant change lands in the frame"); + let mut rt = Runtime::new((true, false, true), view, (200.0, 100.0), Env::new(true, 1.0)); + rt.frame(0.0); + rt.update(|s, _| s.0 = false); + rt.frame(1.0 / 120.0); + assert_eq!(alpha(&rt, "act"), 0.0, "reduced motion lands in the frame"); +} + +#[test] +fn a_row_mounting_before_a_hovered_one_draws_its_actions_at_rest() { + // The new row comes first in the tree but sits away from the still pointer, so every later + // index shifts under it. + fn rows(n: &bool, _: &mut Cx<bool>) -> El { + let row = |k: &str| crate::row().key(k).size(200.0, 20.0).hover_group() + .child(el().key(format!("{k}-act")).size(10.0, 10.0).fill(Color::WHITE).group_opacity(0.0, 1.0)); + let mut list = col().size(200.0, 100.0); + if *n { list = list.child(row("new").absolute(0.0, 60.0)); } + list.child(row("old")) + } + let mut rt = Runtime::new(false, rows, (200.0, 100.0), Env::new(true, 1.0)); + rt.frame(0.0); + rt.pointer_move(100.0, 10.0); + rt.frame(1.0 / 120.0); + let alpha = |rt: &Runtime<bool>, key: &str| rt.elements().into_iter().find(|e| e.key.as_deref() == Some(key)).unwrap().opacity; + assert_eq!(alpha(&rt, "old-act"), 1.0); + rt.update(|n, _| *n = true); + for f in 0..10 { + rt.frame(1.0 / 120.0); + assert_eq!(alpha(&rt, "new-act"), 0.0, "frame {f}"); + assert_eq!(alpha(&rt, "old-act"), 1.0, "frame {f}"); + } +} + +#[test] +fn a_new_mount_draws_at_its_rest_on_its_first_frame() { + let mut rt = Runtime::new((true, false, false), view, (200.0, 100.0), Env::new(true, 1.0)); + rt.frame(0.0); + rt.update(|s, _| s.1 = true); + for f in 0..30 { + rt.frame(1.0 / 120.0); + let a = alpha(&rt, "new"); + assert!((0.0..1.0 / 512.0).contains(&a), "frame {f}: a new child resting at 0 draws {a}"); + } +} + +/// A row that drops `group_opacity` (its actions shown at rest) fades them to full on its +/// motion, and fades them back out when it takes the rest level again, rather than cutting. +#[test] +fn adding_or_dropping_group_opacity_fades() { + fn view(on: &bool, _: &mut Cx<bool>) -> El { + let act = el().key("act").size(10.0, 10.0).fill(Color::WHITE); + let act = if *on { act.group_opacity(0.0, 1.0) } else { act }; + col().size(200.0, 100.0).child(crate::row().key("row").size(200.0, 40.0).hover_group().child(act)) + } + let alpha = |rt: &Runtime<bool>| rt.elements().into_iter().find(|e| e.key.as_deref() == Some("act")).unwrap().opacity; + let mut rt = Runtime::new(true, view, (200.0, 100.0), Env::new(true, 1.0)); + rt.frame(0.0); + assert_eq!(alpha(&rt), 0.0); + for (on, from, to) in [(false, 0.0, 1.0), (true, 1.0, 0.0)] { + rt.update(|s, _| *s = on); + let mut seen = Vec::new(); + for _ in 0..120 { + rt.frame(1.0 / 120.0); + seen.push(alpha(&rt)); + } + assert!((seen[0] - from).abs() < 0.5, "the first frame doesn't cut to {to}: {seen:?}"); + assert!(seen.windows(2).all(|w| (w[1] - w[0]).abs() < 0.2), "it fades: {seen:?}"); + assert!((seen[119] - to).abs() < 1e-3, "and lands on {to}: {seen:?}"); + } + assert!(!rt.animating); +} + +/// A dropped group opacity's fade to full leaves nothing behind once it lands, with no further +/// commit: no rest track, nothing that paints the row in tree order. An instant opacity motion +/// drops it at once. +#[test] +fn a_dropped_group_opacity_leaves_nothing_once_it_lands() { + fn view(s: &(bool, bool), _: &mut Cx<(bool, bool)>) -> El { + let mut act = el().key("act").size(10.0, 10.0).fill(Color::WHITE); + if s.0 { act = act.group_opacity(0.0, 1.0); } + if s.1 { act = act.opacity_motion(Anim::INSTANT); } + col().size(200.0, 100.0).child(crate::row().key("row").size(200.0, 40.0).hover_group().child(act)) + } + let left = |rt: &Runtime<(bool, bool)>| { + let n = rt.tree.nodes.iter().find(|n| n.key.as_deref() == Some("act")).unwrap(); + (n.vis.group_opacity, rt.scene.store().has(n.id, P_GROUP_REST), n.group_fade) + }; + let mut rt = Runtime::new((true, false), view, (200.0, 100.0), Env::new(true, 1.0)); + rt.frame(0.0); + rt.update(|s, _| s.0 = false); + rt.frame(1.0 / 120.0); + assert_eq!(left(&rt), (None, true, true), "the fade to full runs"); + for _ in 0..120 { rt.frame(1.0 / 120.0); } + assert!(!rt.animating); + assert_eq!(left(&rt), (None, false, false), "and leaves nothing once it lands"); + + rt.update(|s, _| *s = (true, true)); + rt.frame(1.0 / 120.0); + rt.update(|s, _| s.0 = false); + rt.frame(1.0 / 120.0); + assert_eq!(left(&rt), (None, false, false), "an instant motion drops it at once"); +} diff --git a/app/vendor/rune/crates/rune/src/runtime/tests/id_pruning.rs b/app/vendor/rune/crates/rune/src/runtime/tests/id_pruning.rs new file mode 100644 index 0000000..b83d266 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/tests/id_pruning.rs @@ -0,0 +1,62 @@ +use super::*; +use crate::el::GrowthSpec; + +fn view(start: &usize, _: &mut Cx<usize>) -> El { + let stack = col().key("stack").w_full().growth(GrowthSpec::default()) + .children((*start..*start + 3).map(|i| el().key(format!("r{i}")).w_full().child(el().key("label").h(20.0)))); + col().key("root").size(200.0, 200.0).child(stack) +} + +#[test] +fn rows_that_left_leave_no_ids_or_stack_tops_behind() { + let mut rt = Runtime::new(0usize, view, (200.0, 200.0), Env::new(true, 1.0)); + rt.frame(0.0); + let mounted = rt.tree.path_ids.len(); + for _ in 0..40 { + rt.update(|n, _| *n += 3); + for _ in 0..90 { rt.frame(1.0 / 60.0); } + } + let stack = rt.tree.nodes.iter().find(|n| n.key.as_deref() == Some("stack")).unwrap().id; + let tops = rt.motion.stacks[&stack].tops.len(); + assert!(tops <= 6, "{tops} row tops kept for 3 rows"); + assert!(rt.tree.path_ids.len() <= mounted + 6, "{} ids kept for {mounted} mounted paths", rt.tree.path_ids.len()); + assert!(rt.find("r120").is_some(), "the current rows still draw"); +} + +#[test] +fn a_path_keeps_its_id_while_it_holds_state() { + fn view(on: &bool, _: &mut Cx<bool>) -> El { + let list = col().children((0..20).map(|i| el().key(format!("i{i}")).h(40.0))); + let scroll = col().key("scroll").size(100.0, 100.0).scroll(ScrollSpec { stick_bottom: false }).child(list); + col().key("root").size(100.0, 100.0).children(on.then_some(scroll)) + } + let mut rt = Runtime::new(true, view, (100.0, 100.0), Env::new(true, 1.0)); + rt.frame(0.0); + rt.wheel(50.0, 50.0, -120.0); + for _ in 0..60 { rt.frame(1.0 / 60.0); } + let id = rt.tree.nodes.iter().find(|n| n.key.as_deref() == Some("scroll")).unwrap().id; + rt.update(|on, tx| { *on = false; tx.instant(); }); + rt.frame(1.0 / 60.0); + rt.update(|on, tx| { *on = true; tx.instant(); }); + rt.frame(1.0 / 60.0); + let again = rt.tree.nodes.iter().find(|n| n.key.as_deref() == Some("scroll")).unwrap().id; + assert_eq!(id, again, "a scroll view coming back finds its scroll state"); +} + +/// Commits and prunes trade two node buffers instead of growing a new one each time a row +/// leaves. +#[test] +fn pruning_left_rows_reuses_the_node_buffers() { + let mut rt = Runtime::new(0usize, view, (200.0, 200.0), Env::new(true, 1.0)); + rt.frame(0.0); + let mut buffers = std::collections::HashSet::new(); + for round in 0..12 { + rt.update(|n, _| *n += 3); + for _ in 0..90 { rt.frame(1.0 / 60.0); } + if round >= 4 { + buffers.insert(rt.tree.nodes.as_ptr() as usize); + assert!(rt.tree.spare_nodes.capacity() >= rt.tree.nodes.len(), "the spare holds a whole commit"); + } + } + assert!(buffers.len() <= 2, "{} node buffers in 8 rounds", buffers.len()); +} diff --git a/app/vendor/rune/crates/rune/src/runtime/tests/input_clipboard.rs b/app/vendor/rune/crates/rune/src/runtime/tests/input_clipboard.rs new file mode 100644 index 0000000..ab7a563 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/tests/input_clipboard.rs @@ -0,0 +1,433 @@ +use super::*; + + +#[test] +fn page_keys_reach_an_input_and_scroll_its_scroll_view_by_most_of_a_viewport() { + struct State { edit: crate::TextEdit, keys: Vec<crate::Key> } + fn view(s: &State, _: &mut Cx<State>) -> El { + let field = crate::text_input(&s.edit, crate::TextStyle::new(14.0, 400.0)).key("field").size(200.0, 40.0) + .on_edit(|s: &mut State| &mut s.edit) + .on_input_key(|s: &mut State, ev, _| { s.keys.push(ev.key.clone()); false }); + let list = col().key("list").w_full().child(field) + .children((0..20).map(|i| el().key(format!("r{i}")).size(200.0, 40.0))); + col().size(200.0, 200.0).child(col().key("scroll").size(200.0, 200.0).scroll(ScrollSpec { stick_bottom: false }).child(list)) + } + let mut edit = crate::TextEdit::new("hello"); + edit.focused = true; + let mut rt = Runtime::new(State { edit, keys: Vec::new() }, view, (200.0, 200.0), Env::new(true, 1.0)); + rt.frame(0.0); + let top = |rt: &Runtime<State>| rt.presented("r0").unwrap().0[1]; + assert_eq!(top(&rt), 40.0); + let page = |rt: &mut Runtime<State>, key: crate::Key, t: f64| { + rt.key(KeyEvent { key, mods: Default::default() }); + rt.frame(t); + }; + page(&mut rt, crate::Key::PageDown, 0.1); + assert_eq!(rt.state.keys, [crate::Key::PageDown], "the input's key handler sees it"); + assert_eq!(top(&rt), 40.0 - 180.0, "a page is 90% of the viewport"); + assert_eq!(rt.state.edit.text, "hello"); + page(&mut rt, crate::Key::PageDown, 0.2); + page(&mut rt, crate::Key::PageDown, 0.3); + page(&mut rt, crate::Key::PageDown, 0.4); + assert_eq!(top(&rt), 40.0 - 640.0, "clamped at the bottom"); + page(&mut rt, crate::Key::PageUp, 0.5); + assert_eq!(top(&rt), 40.0 - 460.0); + assert_eq!(crate::tooling::key_named("PageDown"), Some(crate::Key::PageDown)); +} + +#[test] +fn a_focused_scroll_view_scrolls_on_arrows_and_space() { + fn view(_: &(), _: &mut Cx<()>) -> El { + let list = col().key("list").w_full().children((0..20).map(|i| el().key(format!("r{i}")).size(200.0, 40.0))); + col().size(200.0, 200.0).child(col().key("scroll").size(200.0, 200.0).scroll(ScrollSpec { stick_bottom: false }).focusable(true).child(list)) + } + let mut rt = Runtime::new((), view, (200.0, 200.0), Env::new(true, 1.0)); + rt.frame(0.0); + rt.pointer_down(100.0, 100.0); rt.pointer_up(100.0, 100.0); rt.frame(0.05); + assert_eq!(rt.elements().iter().find(|e| e.focused).and_then(|e| e.key.as_deref()), Some("scroll")); + let top = |rt: &Runtime<()>| rt.presented("r0").unwrap().0[1]; + let press = |rt: &mut Runtime<()>, key: crate::Key, shift: bool, t: f64| { + rt.key(KeyEvent { key, mods: crate::Mods { shift, ..Default::default() } }); + rt.frame(t); + }; + press(&mut rt, crate::Key::Down, false, 0.1); + assert_eq!(top(&rt), -40.0, "Down scrolls a line"); + press(&mut rt, crate::Key::Text(" ".into()), false, 0.2); + assert_eq!(top(&rt), -220.0, "Space scrolls a page"); + press(&mut rt, crate::Key::Text(" ".into()), true, 0.3); + assert_eq!(top(&rt), -40.0, "Shift+Space scrolls back a page"); + press(&mut rt, crate::Key::Up, false, 0.4); + assert_eq!(top(&rt), 0.0); + press(&mut rt, crate::Key::PageDown, false, 0.5); + assert_eq!(top(&rt), -180.0); +} + +#[test] +fn page_keys_keep_paging_the_list_of_a_focused_field_that_scrolled_out() { + struct State { edit: crate::TextEdit } + fn view(s: &State, _: &mut Cx<State>) -> El { + let field = crate::text_input(&s.edit, crate::TextStyle::new(14.0, 400.0)).key("field").size(100.0, 40.0) + .on_edit(|s: &mut State| &mut s.edit); + let rows = col().key("rows").w_full().growth(crate::GrowthSpec::default()) + .child(col().key("r0").child(field)) + .children((1..100).map(|i| el().key(format!("r{i}")).size(100.0, 40.0))) + .virtualize(40.0); + let other = col().key("other").w_full().children((0..100).map(|i| el().key(format!("o{i}")).size(100.0, 40.0))); + crate::row().size(200.0, 200.0) + .child(col().key("left").size(100.0, 200.0).scroll(ScrollSpec { stick_bottom: false }).child(rows)) + .child(col().key("right").size(100.0, 200.0).scroll(ScrollSpec { stick_bottom: false }).child(other)) + } + let mut edit = crate::TextEdit::new("hello"); + edit.focused = true; + let mut rt = Runtime::new(State { edit }, view, (200.0, 200.0), Env::new(true, 1.0)); + rt.frame(0.0); + rt.pointer_move(150.0, 100.0); + let y = |rt: &Runtime<State>, key: &str| rt.presented(key).map(|p| p.0[1]); + for n in 1..=8 { + rt.key(KeyEvent { key: crate::Key::PageDown, mods: Default::default() }); + rt.frame(n as f64 * 0.1); + } + assert!(y(&rt, "field").is_none(), "the field's row scrolled out of the window"); + assert_eq!(y(&rt, "r40"), Some(40.0 * 40.0 - 8.0 * 180.0), "every page moved the focused field's list"); + assert_eq!(y(&rt, "o0"), Some(0.0), "the list under the pointer stayed"); + assert!(rt.state.edit.focused); +} + +#[test] +fn single_line_input_scrolls_to_the_caret_instead_of_wrapping() { + fn view(s: &crate::TextEdit, _: &mut Cx<crate::TextEdit>) -> El { + crate::text_input(s, crate::TextStyle::new(16.0, 400.0)).single_line() + .key("search").size(100.0, 24.0).on_edit(|s: &mut crate::TextEdit| s) + } + let text = "a very long search query that keeps going past the edge"; + let mut edit = crate::TextEdit::new(text); + edit.focused = true; + let mut rt = Runtime::new(edit, view, (100.0, 24.0), Env::new(true, 2.0)); + rt.frame(0.0); + let n = rt.tree.nodes.iter().find(|n| n.key.as_deref() == Some("search")).unwrap(); + let path = n.path.clone(); + assert_eq!(n.text_layout.as_ref().and_then(crate::text::TextLayout::single).unwrap().lines().count(), 1); + let scroll = rt.edit.input_scroll[&path]; + assert!(scroll > 100.0, "the end of the text is in view: {scroll}"); + let caret_x = rt.ime_area.unwrap()[0]; + assert!((0.0..=100.0).contains(&caret_x), "caret {caret_x} stays inside the field"); + + // A click lands on the scrolled text, not on the hidden start. + rt.frame.queue.push(Action::Focus(path.clone(), 1.0, 12.0)); + rt.frame(0.0); + assert!(rt.state.focus > 10, "clicked index {}", rt.state.focus); + + rt.frame.queue.push(Action::Blur); + rt.frame(0.0); + assert!(!rt.state.focused); + assert!(!rt.edit.input_scroll.contains_key(&path), "unfocused fields rest at their start"); +} + +#[test] +fn grapheme_arrow_caret_hit_tests_roundtrip_after_single_line_scroll() { + fn view(s: &crate::TextEdit, _: &mut Cx<crate::TextEdit>) -> El { + crate::text_input(s, crate::TextStyle::new(16.0, 400.0)).single_line() + .key("search").size(100.0, 40.0).on_edit(|s: &mut crate::TextEdit| s) + } + let graphemes = ["W", "W", "W", "W", "W", "W", "W", "W", "W", "W", " ", + "👨\u{200D}👩\u{200D}👧", "🇯🇵", "👋🏽", "e\u{301}", "❤\u{FE0F}", "Z"]; + let mut edit = crate::TextEdit::new(graphemes.concat()); + edit.focused = true; + let mut rt = Runtime::new(edit, view, (100.0, 40.0), Env::new(true, 1.0)); + rt.frame(0.0); + rt.key(KeyEvent { key: crate::Key::Home, mods: Default::default() }); + rt.frame(0.0); + let path = rt.tree.nodes.iter().find(|n| n.key.as_deref() == Some("search")).unwrap().path.clone(); + let mut offset = 0; + for grapheme in graphemes { + offset += grapheme.len(); + rt.key(KeyEvent { key: crate::Key::Right, mods: Default::default() }); + rt.frame(0.0); + assert_eq!(rt.state.focus, offset, "arrow must cross the whole {grapheme:?}"); + let [x, y, _, height] = rt.ime_area.unwrap(); + assert!((0.0..=100.0).contains(&x), "caret must remain in the scrolled field"); + rt.frame.queue.push(Action::Focus(path.clone(), x + 0.1, y + height * 0.5)); + rt.frame(0.0); + assert_eq!(rt.state.focus, offset, "clicking the reported caret after {grapheme:?} must hit that boundary"); + } + assert!(rt.edit.input_scroll[&path] > 0.0, "the fixture must exercise scrolled caret geometry"); +} + +#[test] +fn clipboard_paste_routes_to_window_or_field_and_discards_late_reads() { + #[derive(Default)] + struct State { field: crate::TextEdit, pasted: String } + fn view(s: &State, _: &mut Cx<State>) -> El { + col().size(200.0, 100.0) + .on_paste(|s: &mut State, text, tx| { s.pasted = text.to_owned(); tx.copy_secret(text, std::time::Duration::from_secs(30)); }) + .child(crate::text_input(&s.field, crate::TextStyle::new(16.0, 400.0)).key("field").size(200.0, 40.0) + .on_edit(|s: &mut State| &mut s.field)) + } + let mut rt = Runtime::new(State::default(), view, (200.0, 100.0), Env::new(true, 1.0)); + rt.frame(0.0); + assert!(rt.accepts_paste()); + rt.paste("window fixture"); rt.frame(0.0); + assert_eq!(rt.state.pasted, "window fixture"); + assert!(rt.events.iter().any(|e| e == "paste window")); + assert!(!format!("{:?}", rt.copy_request).contains("window fixture")); + rt.update(|s, _| s.field.focused = true); rt.frame(0.0); + rt.paste_result(None, crate::ClipboardContent::new("late window reply")); rt.frame(0.0); + assert!(rt.state.field.text.is_empty()); + assert_eq!(rt.state.pasted, "window fixture"); + let target = rt.paste_target(); + rt.paste_result(target, crate::ClipboardContent::new("field fixture")); rt.frame(0.0); + assert_eq!(rt.state.field.text, "field fixture"); + assert!(rt.events.iter().any(|e| e == "paste field")); +} + +#[test] +fn rich_pastes_reach_paste_hooks_and_plain_fields_keep_pasting_text() { + use crate::ClipboardContent; + use crate::clipboard::Forms; + #[derive(Default)] + struct State { plain: crate::TextEdit, rich: crate::TextEdit, take: bool, hook: Vec<Option<String>>, changes: u32, window: Vec<ClipboardContent> } + fn view(s: &State, _: &mut Cx<State>) -> El { + let style = crate::TextStyle::new(16.0, 400.0); + col().size(200.0, 100.0) + .on_paste_content(|s: &mut State, content, _| s.window.push(content.clone())) + .child(crate::text_input(&s.plain, style).key("plain").size(200.0, 40.0).on_edit(|s: &mut State| &mut s.plain)) + .child(crate::text_input(&s.rich, style).key("rich").size(200.0, 40.0).on_edit(|s: &mut State| &mut s.rich) + .on_input_change(|s: &mut State, _| s.changes += 1) + .on_input_paste(|s: &mut State, content, _| { + s.hook.push(content.html().map(Into::into)); + if s.take { s.rich.paste("[rich]"); } + s.take + })) + } + let m = crate::clipboard::memory(); + let mut rt = Runtime::new(State::default(), view, (200.0, 100.0), Env::new(true, 1.0)); + rt.use_clipboard(&m); + rt.frame(0.0); + let paste = |rt: &mut Runtime<State>| { rt.update(|_, tx| tx.request_paste()); rt.frame(0.0); }; + m.set_content(ClipboardContent::new("Hello").with_html("<b>Hello</b><script>steal()</script>")); + + paste(&mut rt); + let window = rt.state.window.pop().unwrap(); + assert_eq!((window.text(), window.html()), ("Hello", Some("<b>Hello</b>")), "the window hears every form, sanitised"); + + rt.update(|s, _| s.plain.focused = true); rt.frame(0.0); + assert_eq!(rt.paste_forms(rt.paste_target().as_deref()), Forms::Text); + paste(&mut rt); + assert_eq!(rt.state.plain.text, "Hello", "a field without a hook pastes the text, as before"); + + rt.update(|s, _| { s.plain.focused = false; s.rich.focused = true; }); rt.frame(0.0); + assert_eq!(rt.paste_forms(rt.paste_target().as_deref()), Forms::All); + paste(&mut rt); + assert_eq!((rt.state.rich.text.as_str(), rt.state.changes), ("Hello", 1), "a declining hook leaves the paste to the editor"); + rt.update(|s, _| { s.take = true; s.rich.text.clear(); s.rich.anchor = 0; s.rich.focus = 0; }); rt.frame(0.0); + paste(&mut rt); + assert_eq!((rt.state.rich.text.as_str(), rt.state.changes), ("[rich]", 2), "a hook that takes it edits the field; on_input_change runs"); + assert_eq!(rt.state.hook, vec![Some("<b>Hello</b>".to_owned()); 2]); + + // HTML with no plain text: only rich hooks hear it, never a plain field or text handler. + m.set_content(ClipboardContent::new("").with_html("<i>only</i>")); + rt.update(|s, _| s.take = false); rt.frame(0.0); + paste(&mut rt); + assert_eq!((rt.state.rich.text.as_str(), rt.state.hook.last().cloned().flatten().as_deref()), ("[rich]", Some("<i>only</i>"))); + assert!(rt.state.window.is_empty(), "a focused field's paste never falls through to the window"); + assert_eq!(rt.paste_forms(None), Forms::All); + + let mut plain_root = Runtime::new(Vec::<String>::new(), |_: &Vec<String>, _: &mut Cx<Vec<String>>| { + col().size(200.0, 100.0).on_paste(|s: &mut Vec<String>, text, _| s.push(text.to_owned())) + }, (200.0, 100.0), Env::new(true, 1.0)); + plain_root.use_clipboard(&m); + plain_root.frame(0.0); + assert_eq!(plain_root.paste_forms(None), Forms::Text, "a plain root on_paste never requests HTML or RTF"); + plain_root.update(|_, tx| tx.request_paste()); + plain_root.frame(0.0); + assert!(plain_root.state.is_empty(), "an HTML-only clipboard never triggers a plain root on_paste"); +} + +#[test] +fn pasted_images_reach_hooks_only() { + use crate::{ClipboardContent, ClipboardImage}; + use crate::clipboard::Forms; + #[derive(Default)] + struct State { plain: crate::TextEdit, rich: crate::TextEdit, hooked: crate::TextEdit, hook: Vec<ClipboardContent>, window: Vec<ClipboardContent>, reads: Vec<ClipboardContent> } + fn view(s: &State, _: &mut Cx<State>) -> El { + let style = crate::TextStyle::new(16.0, 400.0); + col().size(200.0, 150.0) + .on_paste_content(|s: &mut State, content, _| s.window.push(content.clone())) + .child(crate::text_input(&s.plain, style).key("plain").size(200.0, 40.0).on_edit(|s: &mut State| &mut s.plain)) + .child(crate::text_input(&s.rich, style).key("rich").size(200.0, 40.0).on_edit(|s: &mut State| &mut s.rich)) + .child(crate::text_input(&s.hooked, style).key("hooked").size(200.0, 40.0).on_edit(|s: &mut State| &mut s.hooked) + .on_input_paste(|s: &mut State, content, _| { + s.hook.push(content.clone()); + let Some(image) = content.image() else { return false }; + let (w, h) = image.size(); + s.hooked.insert_pill(format!("image:{}", image.png().len()), &format!("{w}×{h}")); + true + })) + } + let rgba: Vec<u8> = (0..12u8).flat_map(|i| [i * 20, 0, 255 - i * 20, 255]).collect(); + let image = ClipboardImage::from_rgba(4, 3, &rgba).unwrap(); + assert_eq!(image.size(), (4, 3)); + assert!(ClipboardImage::from_png(&b"GIF89a"[..]).is_none()); + let m = crate::clipboard::memory(); + let mut rt = Runtime::new(State { rich: crate::TextEdit::new("").rich(), hooked: crate::TextEdit::new("").rich(), ..State::default() }, view, (200.0, 150.0), Env::new(true, 1.0)); + rt.use_clipboard(&m); + rt.frame(0.0); + let paste = |rt: &mut Runtime<State>| { rt.update(|_, tx| tx.request_paste()); rt.frame(0.0); }; + let focus = |rt: &mut Runtime<State>, which: fn(&mut State) -> &mut crate::TextEdit| { + rt.update(move |s, _| { s.plain.focused = false; s.rich.focused = false; s.hooked.focused = false; which(s).focused = true; }); + rt.frame(0.0); + }; + + // A screenshot: an image and no text. + m.set_content(ClipboardContent::new("").with_image(image.clone())); + paste(&mut rt); + assert_eq!(rt.state.window.pop().and_then(|c| c.image().cloned()).as_ref(), Some(&image), "the root's on_paste_content gets the image"); + focus(&mut rt, |s| &mut s.plain); + paste(&mut rt); + focus(&mut rt, |s| &mut s.rich); + assert_eq!(rt.paste_forms(rt.paste_target().as_deref()), Forms::Rich, "a rich field with no hook never fetches the image"); + paste(&mut rt); + assert_eq!((rt.state.plain.text.as_str(), rt.state.rich.text.as_str()), ("", ""), "an image alone pastes nothing into a field without a hook"); + focus(&mut rt, |s| &mut s.hooked); + assert_eq!(rt.paste_forms(rt.paste_target().as_deref()), Forms::All); + paste(&mut rt); + assert_eq!(rt.state.hooked.text, "4×3"); + assert_eq!(rt.state.hooked.pills().map(|(_, id)| id.to_owned()).collect::<Vec<_>>(), [format!("image:{}", image.png().len())]); + assert!(rt.state.window.is_empty(), "a focused field's paste never reaches the root"); + + // Text beside an image: a declining hook leaves the text to the editor. + m.set_content(ClipboardContent::new(" caption")); + paste(&mut rt); + assert_eq!(rt.state.hooked.text, "4×3 caption"); + assert!(rt.state.hook.last().is_some_and(|c| c.image().is_none())); + + m.set_content(ClipboardContent::new("alt").with_image(image.clone())); + rt.update(|_, tx| tx.read_clipboard(|s: &mut State, content, _| s.reads.push(content.clone()))); + rt.frame(0.0); + rt.frame(0.0); + assert_eq!(rt.state.reads.iter().map(|c| (c.text(), c.image().map(ClipboardImage::size))).collect::<Vec<_>>(), [("alt", Some((4, 3)))]); +} + +#[test] +fn copied_images_and_files_round_trip_and_reach_only_hooks() { + use std::path::PathBuf; + use crate::{ClipboardContent, ClipboardImage}; + #[derive(Default)] + struct State { field: crate::TextEdit, rich: crate::TextEdit, reads: Vec<ClipboardContent> } + fn view(s: &State, _: &mut Cx<State>) -> El { + let style = crate::TextStyle::new(16.0, 400.0); + col().size(200.0, 100.0) + .child(crate::text_input(&s.field, style).key("field").size(200.0, 40.0).on_edit(|s: &mut State| &mut s.field)) + .child(crate::text_input(&s.rich, style).key("rich").size(200.0, 40.0).on_edit(|s: &mut State| &mut s.rich)) + } + let rgba: Vec<u8> = (0..4u8).flat_map(|i| [i * 60, 0, 0, 255]).collect(); + let image = ClipboardImage::from_rgba(2, 2, &rgba).unwrap(); + let files = [PathBuf::from("/fixtures/a.txt"), PathBuf::from("/fixtures/b c.png")]; + let only_files = ClipboardContent::default().with_files(files.clone()); + assert!(only_files.is_rich() && !only_files.is_empty() && !only_files.has_plain()); + assert_eq!(only_files.files(), &files[..]); + assert_ne!(only_files, ClipboardContent::default(), "files take part in equality"); + assert!(!format!("{only_files:?}").contains("fixtures")); + + let m = crate::clipboard::memory(); + let mut rt = Runtime::new(State { rich: crate::TextEdit::new("").rich(), ..State::default() }, view, (200.0, 100.0), Env::new(true, 1.0)); + rt.use_clipboard(&m); + rt.frame(0.0); + let copied = ClipboardContent::new("two files").with_image(image.clone()).with_files(files.clone()); + rt.update(|_, tx| tx.copy_rich(copied.clone())); + assert_eq!(m.content().as_ref(), Some(&copied), "the memory clipboard keeps every form"); + rt.update(|_, tx| tx.read_clipboard(|s: &mut State, content, _| s.reads.push(content.clone()))); + rt.frame(0.0); + assert_eq!(rt.state.reads.pop().as_ref(), Some(&copied), "a read gets the image and files back"); + + rt.update(|_, tx| tx.copy_rich(only_files.clone())); + for which in [(|s: &mut State| &mut s.field) as fn(&mut State) -> &mut crate::TextEdit, |s| &mut s.rich] { + rt.update(move |s, _| { s.field.focused = false; s.rich.focused = false; which(s).focused = true; }); + rt.frame(0.0); + rt.update(|_, tx| tx.request_paste()); + rt.frame(0.0); + } + assert_eq!((rt.state.field.text.as_str(), rt.state.rich.text.as_str()), ("", ""), "files alone paste nothing into a field without a hook"); +} + +#[test] +fn a_paste_of_files_alone_keeps_the_selection_of_a_field_without_a_hook() { + use crate::ClipboardContent; + struct State { field: crate::TextEdit } + fn view(s: &State, _: &mut Cx<State>) -> El { + col().size(200.0, 100.0).child(crate::text_input(&s.field, crate::TextStyle::new(16.0, 400.0)).key("field").size(200.0, 40.0) + .on_edit(|s: &mut State| &mut s.field)) + } + for rich in [false, true] { + let mut field = crate::TextEdit::new("keep me"); + if rich { field = field.rich(); } + field.focused = true; + field.set_selection(0, 7); + let m = crate::clipboard::memory(); + let mut rt = Runtime::new(State { field }, view, (200.0, 100.0), Env::new(true, 1.0)); + rt.use_clipboard(&m); + rt.frame(0.0); + rt.update(|_, tx| tx.copy_rich(ClipboardContent::default().with_files([std::path::PathBuf::from("/fixtures/a.txt")]))); + rt.update(|_, tx| tx.request_paste()); + rt.frame(0.0); + rt.frame(0.0); + assert_eq!((rt.state.field.text.as_str(), rt.state.field.selected()), ("keep me", "keep me"), "rich {rich}"); + } +} + +#[test] +fn read_clipboard_answers_once_even_when_empty_and_pastes_nowhere() { + use crate::ClipboardContent; + #[derive(Default)] + struct State { field: crate::TextEdit, reads: Vec<ClipboardContent> } + fn view(s: &State, _: &mut Cx<State>) -> El { + col().size(200.0, 100.0).child(crate::text_input(&s.field, crate::TextStyle::new(16.0, 400.0)).key("field").size(200.0, 40.0) + .on_edit(|s: &mut State| &mut s.field)) + } + let m = crate::clipboard::memory(); + let mut rt = Runtime::new(State::default(), view, (200.0, 100.0), Env::new(true, 1.0)); + rt.use_clipboard(&m); + rt.frame(0.0); + rt.update(|s, _| s.field.focused = true); rt.frame(0.0); + let read = |rt: &mut Runtime<State>| { + rt.update(|_, tx| tx.read_clipboard(|s: &mut State, content, _| s.reads.push(content.clone()))); + rt.frame(0.0); + rt.frame(0.0); + }; + read(&mut rt); + assert_eq!(rt.state.reads, [ClipboardContent::default()], "an empty clipboard still answers"); + m.set_content(ClipboardContent::new("a").with_html("<a href='javascript:x'>a</a>").with_rtf("{\\rtf1 a}")); + read(&mut rt); + let got = rt.state.reads.pop().unwrap(); + assert_eq!((got.text(), got.html(), got.rtf()), ("a", Some("<a>a</a>"), Some("{\\rtf1 a}"))); + assert!(rt.state.field.text.is_empty() && rt.state.reads.len() == 1); + assert!(rt.edit.clipboard_reads.is_empty() && rt.edit.read_requests.is_empty()); +} + +#[test] +fn clipboard_requests_follow_handler_order_and_are_consumed_once() { + use crate::edit::{Key, KeyEvent, Mods, TextEdit}; + fn view(edit: &TextEdit, _: &mut Cx<TextEdit>) -> El { + col() + .child(el().key("copy").size(40.0, 28.0).on_press_tx(|_: &mut TextEdit, tx| tx.copy("response"))) + .child(crate::el::text_input(edit, crate::tok::TextStyle::new(14.0, 400.0)).key("input").on_edit(|e: &mut TextEdit| e)) + } + let mut edit = TextEdit::new("héllo 👋"); + edit.anchor = 0; + let mut rt = Runtime::new(edit, view, (300.0, 200.0), Env::new(true, 2.0)); + rt.frame(0.0); + let button = rt.tree.nodes.iter().find(|n| n.key.as_deref() == Some("copy")).unwrap().path.clone(); + let input = rt.tree.nodes.iter().find(|n| n.key.as_deref() == Some("input")).unwrap().path.clone(); + rt.set_focus(Some(input), true); + let copy_key = KeyEvent { key: Key::Command('c'), mods: Mods { cmd: true, ..Mods::default() } }; + rt.frame.queue.push(Action::Press(button.clone(), crate::PointerButton::Primary, false)); + rt.frame.queue.push(Action::Key { ev: copy_key.clone(), repeat: false, stage: false }); + rt.frame(1.0 / 120.0); + assert_eq!(rt.copy_request.take().as_deref(), Some("héllo 👋")); + rt.frame(1.0 / 120.0); + assert!(rt.copy_request.is_none()); + rt.frame.queue.push(Action::Key { ev: copy_key, repeat: false, stage: false }); + rt.frame.queue.push(Action::Press(button, crate::PointerButton::Primary, false)); + rt.frame(1.0 / 120.0); + assert_eq!(rt.copy_request.take().as_deref(), Some("response")); +} diff --git a/app/vendor/rune/crates/rune/src/runtime/tests/layout_hover.rs b/app/vendor/rune/crates/rune/src/runtime/tests/layout_hover.rs new file mode 100644 index 0000000..4eb0b02 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/tests/layout_hover.rs @@ -0,0 +1,260 @@ +use super::*; + +const DT: f64 = 1.0 / 120.0; + +/// What the rows heard: `on_hover` enters and `on_hover_change` changes. +#[derive(Default)] +struct Rows { + growth: bool, open: bool, gone: bool, modal: bool, + /// Rows with only a hover fill, and a pressable spot over row 5 that `pan` moves. + plain: bool, pan: Option<crate::live::Live<[f32; 2]>>, spot: Vec<bool>, + /// Rows with tooltips, and cursors that differ from their neighbours'. + tips: bool, + enters: Vec<usize>, changes: Vec<(usize, bool)>, +} + +const CURSORS: [crate::el::Cursor; 3] = [crate::el::Cursor::Pointer, crate::el::Cursor::Move, crate::el::Cursor::Grab]; + +/// Twelve 20-point rows, each revealing an action on hover and darkening while pressed. +/// Opening row 0 grows it by 200 points, and the rows below slide down under the pointer. +fn view(s: &Rows, _: &mut Cx<Rows>) -> El { + let rows = (0..12).filter(|&k| !(s.gone && k == 5)).map(|k| { + let row = crate::row().key(format!("r{k}")).w_full().h(if k == 0 && s.open { 220.0 } else { 20.0 }); + let row = if s.plain { row.hover(Color::WHITE) } else { + row.hover_group().press(Color::WHITE).press_scale(0.9) + .on_press(|_: &mut Rows| {}) + .on_hover(move |s: &mut Rows| s.enters.push(k)) + .on_hover_change(move |s: &mut Rows, inside, _| s.changes.push((k, inside))) + .child(el().key(format!("a{k}")).size(10.0, 10.0).fill(Color::WHITE).group_opacity(0.0, 1.0)) + }; + if s.tips { row.help(format!("row {k}")).cursor(CURSORS[k % 3]) } else { row } + }); + let mut list = col().key("rows").w_full().children(rows); + if s.growth { list = list.growth(crate::el::GrowthSpec::default()); } + let mut root = col().size(200.0, 400.0).child(list); + if let Some(pan) = &s.pan { + root = root.child(el().key("spot").absolute(90.0, 100.0).size(20.0, 20.0).live_offset(pan) + .on_press(|_: &mut Rows| {}).on_hover_change(|s: &mut Rows, inside, _| s.spot.push(inside))); + } + if s.modal { root.child(col().key("sheet").absolute(150.0, 350.0).size(40.0, 40.0).modal(true, |s: &mut Rows| s.modal = false)) } else { root } +} + +/// The rows whose action shows at all this frame. +fn shown(rt: &Runtime<Rows>) -> Vec<String> { + rt.elements().into_iter().filter(|e| e.key.as_ref().is_some_and(|k| k.starts_with('a')) && e.opacity > 0.0) + .filter_map(|e| e.key).collect() +} + +/// The row drawn under `y` this frame. +fn row_at(rt: &Runtime<Rows>, y: f32) -> Option<usize> { + rt.elements().into_iter().filter(|e| e.rect[1] <= y && y < e.rect[1] + e.rect[3]) + .find_map(|e| e.key?.strip_prefix('r')?.parse().ok()) +} + +fn top(rt: &Runtime<Rows>, key: &str) -> f32 { + rt.elements().into_iter().find(|e| e.key.as_deref() == Some(key)).unwrap().rect[1] +} + +/// The pointer resting over row 5. +fn resting(rows: Rows) -> Runtime<Rows> { + let mut rt = Runtime::new(rows, view, (200.0, 400.0), Env::new(true, 1.0)); + rt.frame(0.0); + rt.pointer_move(100.0, 110.0); + rt.frame(DT); + rt.frame(DT); + rt +} + +/// Row 5 hovered under a still pointer, then row 0 opening. +fn sliding(growth: bool) -> Runtime<Rows> { + let mut rt = resting(Rows { growth, ..Rows::default() }); + assert_eq!(shown(&rt), ["a5"]); + assert_eq!((&rt.state.enters[..], &rt.state.changes[..]), (&[5][..], &[(5, true)][..])); + rt.update(|s, _| s.open = true); + rt +} + +/// Runs frames until row 11 stops moving, returning how many it moved on and every action shown. +fn settle(rt: &mut Runtime<Rows>) -> (usize, Vec<String>) { + let (mut moved, mut seen) = (0, Vec::new()); + let mut y = top(rt, "r11"); + for _ in 0..600 { + rt.frame(DT); + for k in shown(rt) { if !seen.contains(&k) { seen.push(k); } } + let now = top(rt, "r11"); + if (now - y).abs() < 1e-4 && !rt.animating { break; } + if now != y { moved += 1; } + y = now; + } + for _ in 0..30 { rt.frame(DT); } + (moved, seen) +} + +#[test] +fn rows_sliding_under_a_still_pointer_dont_take_its_hover() { + for growth in [false, true] { + let mut rt = sliding(growth); + let (moved, seen) = settle(&mut rt); + assert!(moved > 5, "growth {growth}: the rows slid"); + assert_eq!(seen, ["a5", "a0"], "growth {growth}: no row passing under the pointer lit up"); + assert_eq!(rt.state.enters, [5, 0], "growth {growth}"); + assert_eq!(rt.state.changes, [(5, true), (5, false), (0, true)], "growth {growth}"); + assert_eq!(row_at(&rt, 110.0), Some(0), "growth {growth}"); + assert_eq!(shown(&rt), ["a0"], "growth {growth}: once they settle, the row under the pointer has it"); + assert!(!rt.pointer.hover_hold().held() && !rt.pointer.hover_hold().released()); + } +} + +#[test] +fn moving_the_pointer_during_a_slide_retargets_at_once() { + let mut rt = sliding(false); + for _ in 0..6 { rt.frame(DT); } + assert_eq!(shown(&rt), ["a5"]); + assert!(rt.pointer.hover_hold().held()); + let under = row_at(&rt, 111.0).unwrap(); + assert_ne!(under, 5, "a row slid under the pointer"); + rt.pointer_move(100.0, 111.0); + rt.frame(DT); + assert_eq!(rt.state.enters, [5, under]); + assert_eq!(rt.state.changes, [(5, true), (5, false), (under, true)]); + let now = format!("a{}", row_at(&rt, 111.0).unwrap()); + assert!(shown(&rt).contains(&now), "{now}: {:?}", shown(&rt)); +} + +#[test] +fn the_hovered_row_leaving_mid_slide_lets_go() { + let mut rt = sliding(false); + for _ in 0..4 { rt.frame(DT); } + rt.update(|s, _| s.gone = true); + rt.frame(DT); + rt.frame(DT); + assert_eq!(rt.state.changes, [(5, true), (5, false)], "the leaving row hears the pointer go"); + let (_, seen) = settle(&mut rt); + assert!(seen.iter().all(|k| k == "a5" || k == "a0"), "nothing else lit up: {seen:?}"); + assert_eq!(rt.state.enters, [5, 0]); + assert_eq!(rt.state.changes, [(5, true), (5, false), (0, true)]); +} + +#[test] +fn a_modal_opening_mid_slide_lets_go() { + let mut rt = sliding(false); + for _ in 0..4 { rt.frame(DT); } + rt.update(|s, _| s.modal = true); + rt.frame(DT); + rt.frame(DT); + assert_eq!(rt.state.changes, [(5, true), (5, false)], "the inert row hears the pointer go"); + settle(&mut rt); + assert_eq!(shown(&rt), Vec::<String>::new()); + assert_eq!(rt.state.enters, [5]); +} + +#[test] +fn a_press_during_a_slide_still_shows_and_lets_go() { + let mut rt = sliding(false); + for _ in 0..4 { rt.frame(DT); } + let under = row_at(&rt, 110.0).unwrap(); + let id = rt.tree.nodes.iter().find(|n| n.named(&format!("r{under}"))).unwrap().id; + rt.pointer_down(100.0, 110.0); + rt.frame(DT); + assert_eq!(rt.scene.store().target(id, P_PRESS), Some(1.0), "the press shows mid-slide"); + assert_eq!(rt.scene.store().target(id, P_PRESS_SCALE), Some(0.9)); + rt.pointer_up(100.0, 110.0); + rt.frame(DT); + rt.frame(DT); + assert_eq!(rt.scene.store().target(id, P_PRESS), Some(0.0), "the press lets go mid-slide"); + assert_eq!(rt.scene.store().target(id, P_PRESS_SCALE), Some(1.0)); + assert!(!rt.pointer.hover_hold().held() && rt.pointer.hover_hold().released(), "the press let go of the hold until the slide settles"); +} + +/// Each row's enters minus its leaves, from `on_hover_change`. +fn inside(rt: &Runtime<Rows>) -> Vec<usize> { + let mut net = [0i32; 12]; + for &(k, on) in &rt.state.changes { net[k] += if on { 1 } else { -1 }; } + assert!(net.iter().all(|&n| n == 0 || n == 1), "every enter is heard once before its leave: {:?}", rt.state.changes); + (0..12).filter(|&k| net[k] == 1).collect() +} + +#[test] +fn a_press_mid_slide_follows_the_pointer_and_pairs_each_enter_with_a_leave() { + let mut rt = sliding(false); + for _ in 0..4 { rt.frame(DT); } + rt.pointer_down(100.0, 110.0); + assert!(rt.pointer.hover_hold().released(), "a press lets go of the hold"); + for _ in 0..40 { + rt.frame(DT); + let inside = inside(&rt); + assert!(inside.len() <= 2, "the pressed row and the one under the pointer: {inside:?}"); + assert!(rt.pointer.hover_within.len() <= 2, "{:?}", rt.pointer.hover_within); + } + rt.pointer_up(100.0, 110.0); + settle(&mut rt); + assert_eq!(inside(&rt), [0]); + assert_eq!(rt.pointer.hover_within.len(), 1); +} + +#[test] +fn a_move_before_the_next_tick_sees_layout_just_set_moving() { + // A spring a commit between frames started (a scroll's), not yet ticked. + let mut rt = resting(Rows::default()); + let id = rt.tree.nodes.iter().find(|n| n.named("r3")).unwrap().id; + rt.scene.animate(id, prop::OFFSET, rune_motion::Vec2::new(0.0, 40.0), crate::tok::motion::SNAPPY); + rt.pointer_move(100.0, 111.0); + assert!(rt.pointer.hover_hold().released(), "an untouched spring"); + // A growing element's height. + let mut rt = resting(Rows::default()); + let id = rt.tree.nodes.iter().find(|n| n.named("r3")).unwrap().id; + let mut grow = crate::growth::GrowTrack::default(); + grow.target = 100.0; + rt.motion.grows.insert(id, grow); + rt.pointer_move(100.0, 111.0); + assert!(rt.pointer.hover_hold().released(), "a growth"); +} + +#[test] +fn a_hold_keeps_all_three_hover_states_together() { + let pan = crate::live::Live::new([0.0, 0.0]); + let mut rt = resting(Rows { plain: true, pan: Some(pan.clone()), ..Rows::default() }); + let target = |rt: &Runtime<Rows>, key: &str| { + let id = rt.tree.nodes.iter().find(|n| n.named(key)).unwrap().id; + rt.scene.store().target(id, P_HOVER) + }; + let spot = rt.tree.nodes.iter().find(|n| n.named("spot")).unwrap().path.clone(); + assert_eq!(rt.pointer.hovered.as_deref(), Some(spot.as_str())); + assert_eq!((&rt.state.spot[..], target(&rt, "r5")), (&[true][..], Some(1.0))); + rt.update(|s, _| s.open = true); + for _ in 0..6 { rt.frame(DT); } + assert_ne!(row_at(&rt, 110.0), Some(5), "a row slid under the pointer"); + assert_eq!(target(&rt, "r5"), Some(1.0), "the rows' hover is held"); + // The spot jumps out from under the pointer while the rows' hover is held. + pan.set([-80.0, 0.0]); + rt.frame(DT); + rt.frame(DT); + assert_eq!(target(&rt, "r5"), Some(1.0)); + assert_eq!(rt.state.spot, [true], "the spot's leave waits with the rows' hover"); + assert_eq!(rt.pointer.hovered.as_deref(), Some(spot.as_str()), "and so does the hovered element"); + settle(&mut rt); + assert_eq!(rt.state.spot, [true, false]); + assert_eq!(rt.pointer.hovered, None); + assert_eq!((target(&rt, "r5"), target(&rt, "r0")), (Some(0.0), Some(1.0))); +} + +#[test] +fn the_cursor_and_tooltip_stay_with_the_held_row() { + let mut rt = resting(Rows { tips: true, ..Rows::default() }); + rt.help_delay = 0.0; + rt.frame(DT); + rt.frame(DT); + assert_eq!((rt.cursor(), rt.help_tooltip().map(|t| t.0.to_owned())), (CURSORS[2], Some("row 5".to_owned()))); + rt.update(|s, _| s.open = true); + let (mut cursors, mut tips) = (Vec::new(), Vec::new()); + for _ in 0..120 { + rt.frame(DT); + if !cursors.contains(&rt.cursor()) { cursors.push(rt.cursor()); } + let tip = rt.help_tooltip().map(|t| t.0.to_owned()); + if !tips.contains(&tip) { tips.push(tip); } + } + settle(&mut rt); + assert_eq!(cursors, [CURSORS[2], CURSORS[0]], "row 5's cursor, then row 0's"); + assert!(tips.iter().flatten().all(|t| t == "row 5" || t == "row 0"), "no tooltip for a passing row: {tips:?}"); + assert_eq!((rt.cursor(), rt.help_tooltip().map(|t| t.0.to_owned())), (CURSORS[0], Some("row 0".to_owned()))); +} diff --git a/app/vendor/rune/crates/rune/src/runtime/tests/layout_reads.rs b/app/vendor/rune/crates/rune/src/runtime/tests/layout_reads.rs new file mode 100644 index 0000000..152e5c3 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/tests/layout_reads.rs @@ -0,0 +1,65 @@ +//! Layout reads find their element whether a few reads scan the tree or many index it. + +use super::*; +use crate::el::row; + +struct Cells { width: f32, reads: usize, seen: std::rc::Rc<std::cell::RefCell<Vec<Option<[f32; 2]>>>> } + +fn view(s: &Cells, cx: &mut Cx<Cells>) -> El { + let mut seen: Vec<Option<[f32; 2]>> = (0..s.reads).map(|i| cx.layout_size(&format!("cell{i}"))).collect(); + seen.push(cx.layout_size("panel/cell3")); + seen.push(cx.layout_size("missing")); + *s.seen.borrow_mut() = seen; + let cells = |w: f32| (0..12).map(move |i| el().key(format!("cell{i}")).w(w + i as f32).h(10.0)); + col() + .child(row().key("other").children(cells(1.0))) + .child(row().key("panel").children(cells(s.width))) +} + +#[test] +fn few_and_many_reads_see_the_same_rects() { + for reads in [2, 12] { + let seen = std::rc::Rc::default(); + let mut rt = Runtime::new(Cells { width: 20.0, reads, seen: std::rc::Rc::clone(&seen) }, view, (400.0, 200.0), Env::new(true, 1.0)); + rt.frame(0.0); + rt.frame(1.0 / 60.0); + rt.update(|s, _| s.width = 30.0); + for _ in 0..3 { rt.frame(1.0 / 60.0); } + let seen = seen.borrow(); + assert_eq!(seen.len(), reads + 2); + for (i, size) in seen[..reads].iter().enumerate() { + assert_eq!(*size, Some([1.0 + i as f32, 10.0]), "{reads} reads: cell{i} is the first one keyed so"); + } + assert_eq!(seen[reads], Some([33.0, 10.0]), "{reads} reads: a scoped selector finds the panel's cell"); + assert_eq!(seen[reads + 1], None, "{reads} reads"); + } +} + +type Seen = std::rc::Rc<std::cell::RefCell<[Option<[f32; 4]>; 2]>>; + +/// A 200-point viewport over a hundred 40-point virtual rows, each with a keyed label 5 points +/// down, reading where row 27 and its label lie. +fn virtual_view(seen: &Seen, cx: &mut Cx<Seen>) -> El { + *seen.borrow_mut() = [cx.window_layout("r27"), cx.window_layout("r27/label")]; + let rows = col().key("rows").w_full().growth(crate::GrowthSpec::default()) + .virtual_rows(100, 40.0, |_: &Seen, i| format!("r{i}").into(), |_: &Seen, _| { + col().w_full().h(40.0).pt(5.0).child(el().key("label").w(10.0).h(10.0)) + }); + col().w_full().h_full().child(col().key("list").w_full().h(200.0).scroll(crate::ScrollSpec { stick_bottom: false }).child(rows)) +} + +#[test] +fn a_virtual_row_reads_where_it_draws_with_rows_culled_above() { + let seen = Seen::default(); + let mut rt = Runtime::new(std::rc::Rc::clone(&seen), virtual_view, (300.0, 300.0), Env::new(true, 1.0)); + rt.frame(0.0); + rt.update(|_, tx| tx.scroll_to_instant("list", 0.0, 1000.0)); + for _ in 0..4 { rt.frame(1.0 / 60.0); } + assert!(rt.commit.virtuals.values().next().unwrap().before > 0.0, "rows above the window are culled"); + let drawn = |key: &str| rt.elements().into_iter().find(|e| e.key.as_deref() == Some(key)).map(|e| e.rect); + let [row, label] = *seen.borrow(); + assert_eq!(drawn("r27").map(|r| r[1]), Some(80.0), "row 27 draws 1080 points down, scrolled 1000"); + assert_eq!(row, drawn("r27"), "the row reads where it draws"); + let label_drawn = rt.elements().into_iter().find(|e| e.path.contains("/r27/") && e.key.as_deref() == Some("label")).map(|e| e.rect); + assert_eq!(label, label_drawn, "so does an element inside it"); +} diff --git a/app/vendor/rune/crates/rune/src/runtime/tests/layout_rows.rs b/app/vendor/rune/crates/rune/src/runtime/tests/layout_rows.rs new file mode 100644 index 0000000..f2522f2 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/tests/layout_rows.rs @@ -0,0 +1,333 @@ +use super::*; + + +#[test] +fn duplicate_sibling_keys_keep_the_first_and_lay_out_without_a_panic() { + fn view(s: &u32, _: &mut Cx<u32>) -> El { + col().children((0..*s).map(|i| el().key("row:R-94").size(10.0, 10.0 + i as f32))) + } + let mut rt = Runtime::new(2, view, (100.0, 100.0), Env::new(true, 1.0)); + rt.frame(0.0); + let h = |rt: &Runtime<u32>, key: &str| rt.presented(key).map(|(r, _)| r[3]); + assert_eq!(h(&rt, "row:R-94"), Some(10.0), "the first keeps the key"); + assert_eq!(h(&rt, "row:R-94#dup1"), Some(11.0), "the duplicate still draws"); + rt.update(|s, _| *s = 3); + rt.frame(0.1); + assert_eq!(h(&rt, "row:R-94#dup2"), Some(12.0)); +} + +#[test] +fn duplicate_sibling_keys_tooling_reports_and_lays_out() { + let mut rt = Runtime::new((), duplicate_view, (100.0, 100.0), Env::new(true, 1.0)); + rt.commit.enable_key_warnings(); + rt.frame(0.0); + assert_eq!(rt.commit.key_warnings().unwrap().len(), 1); + assert_eq!(rt.tree.nodes.len(), 3); + assert_eq!(rt.tree.nodes[0].local.w, 100.0); +} + +#[test] +fn side_panel_wraps_once_and_releases_height_after_stable_width() { + use crate::el::{row, text}; + fn view(s: &(f32, bool), cx: &mut Cx<(f32, bool)>) -> El { + cx.reduced_motion(s.1); + row().key("window").w_full().h_full() + .child(col().key("viewport").grow(1.0).shrink().h_full() + .scroll(ScrollSpec { stick_bottom: true }).clip_soft(18.0) + .child(col().key("stack").w_full().growth(GrowthSpec::default()) + .child(col().key("message").w_full().child(text("Wrap once at the landing width. ".repeat(30)).wrap().w_full())))) + .child(el().key("side-panel").w(s.0).h_full()) + } + fn run(fps: usize, reduced: bool) -> Vec<f32> { + let mut rt = Runtime::new((0.0, reduced), view, (480.0, 700.0), Env::new(true, 2.0)); + rt.frame(0.0); + let id = rt.tree.nodes.iter().find(|n| n.key.as_deref() == Some("message")).unwrap().id; + let original = rt.motion.grows[&id].h; + let mut trace = std::env::var_os("RUNE_WIDTH_TRACE").map(|dir| { + let dir = std::path::PathBuf::from(dir).join(format!("width-{fps}-{}", if reduced { "reduced" } else { "normal" })); + std::fs::create_dir_all(&dir).unwrap(); + crate::tooling::Trace::open(&dir.join("trace.jsonl"), (480.0, 700.0), fps as f64, 2.0) + }); + if let Some(trace) = &mut trace { trace.frame(&mut rt, 0.0, 0.0); } + rt.state.0 = 160.0; + rt.invalidate(); + rt.frame(0.0); + let commits = rt.stats.commits; + let measured = rt.tree.nodes.iter().find(|n| n.id == id).unwrap().local.h; + assert!(measured > original); + if reduced { assert_eq!(rt.motion.grows[&id].h, measured); } + else { assert_eq!(rt.motion.grows[&id].target, original); } + let mut samples = vec![]; + for frame in 1..=fps * 2 { + rt.frame(1.0 / fps as f64); + assert_eq!(rt.stats.commits, commits, "presentation must not remeasure the wrapping"); + assert_eq!(rt.stats.shaped, 0); + if frame as f64 / (fps as f64) < 0.12 && !reduced { + assert_eq!(rt.motion.grows[&id].h, original); + assert!(rt.animating, "the hold must keep the shared clock awake"); + } + if frame % (fps / 30) == 0 { samples.push(rt.motion.grows[&id].h); } + if let Some(trace) = &mut trace { trace.frame(&mut rt, frame as f64 * 1000.0 / fps as f64, 0.0); } + } + assert!((rt.motion.grows[&id].h - measured).abs() < 0.05); + // A second target during a hold restarts the stable-width interval. + rt.state.0 = 80.0; + rt.invalidate(); + rt.frame(0.0); + for _ in 0..fps / 10 { rt.frame(1.0 / fps as f64); } + rt.state.0 = 120.0; + rt.invalidate(); + rt.frame(0.0); + for _ in 0..fps / 10 { rt.frame(1.0 / fps as f64); } + if !reduced { + assert_eq!(rt.motion.grows[&id].h, measured, "a changing width must restart the hold"); + assert!(!rt.motion.stacks.values().next().unwrap().pending_heights.is_empty()); + } + // Settle/resume bypasses even an active hold completely. + rt.settle_all(); + rt.frame(0.0); + assert!(rt.motion.stacks.values().all(|s| s.pending_heights.is_empty())); + assert!(!rt.animating); + samples + } + for reduced in [false, true] { + let a = run(30, reduced); + let b = run(120, reduced); + for (a, b) in a.into_iter().zip(b) { assert!((a - b).abs() < 0.05, "frame-rate dependent hold: {a} vs {b}"); } + } +} + +#[test] +fn measurement_cannot_change_presented_geometry_or_motion_policy() { + fn view(changed: &bool, cx: &mut Cx<bool>) -> El { + cx.reduced_motion(*changed); + col().key("stack").w_full().growth(GrowthSpec::default()) + .child(el().key("row").w_full().h(if *changed { 160.0 } else { 40.0 })) + } + let mut rt = Runtime::new(false, view, (300.0, 300.0), Env::new(true, 2.0)); + rt.frame(0.0); + let id = rt.tree.nodes.iter().find(|n| n.key.as_deref() == Some("row")).unwrap().id; + let before = rt.scene.presented(id).unwrap().rect; + rt.state = true; + let measured = rt.measure(&Tx::default()); + assert_eq!(rt.scene.presented(id).unwrap().rect, before); + assert_eq!(rt.scene.store().active_len(), 0); + assert_eq!(rt.motion.grows[&id].h, 40.0); + assert!(!rt.reduced_motion && !rt.scene.store().reduced_motion()); + rt.apply(measured, &Tx::default()); + assert!(rt.reduced_motion && rt.scene.store().reduced_motion()); + assert_eq!(rt.motion.grows[&id].h, 160.0); +} + +#[test] +fn send_flight_follows_the_measured_bubble_while_earlier_rows_land() { + struct State { draft: crate::edit::TextEdit, sent: bool, height: f32 } + fn view(s: &State, _: &mut Cx<State>) -> El { + let mut rows = col().w_full().growth(GrowthSpec::default()) + .child(el().key("earlier").w_full().h(s.height)); + if s.sent { rows = rows.child(col().key("bubble").w_full().py(8.0) + .child(crate::el::text("héllo flight").key("destination").wrap())); } + col().w_full().h_full() + .child(col().key("scroll").w_full().grow(1.0).shrink().scroll(ScrollSpec { stick_bottom: true }).child(rows)) + .child(crate::el::text_input(&s.draft, crate::tok::TextStyle::new(14.0, 400.0)).key("source").w_full().h(60.0) + .on_edit(|s: &mut State| &mut s.draft) + .on_submit(|s: &mut State, tx: &mut Tx| { + s.sent = true; + s.draft.clear(); + tx.fly_text("source", "destination"); + })) + } + let mut draft = crate::edit::TextEdit::new("héllo flight"); + draft.focused = true; + let mut rt = Runtime::new(State { draft, sent: false, height: 80.0 }, view, (400.0, 300.0), Env::new(true, 2.0)); + rt.frame(0.0); + rt.state.height = 400.0; + rt.invalidate(); + rt.frame(1.0 / 120.0); + rt.key(KeyEvent { key: crate::edit::Key::Enter, mods: Default::default() }); + rt.frame(1.0 / 120.0); + assert_eq!(rt.motion.flights().len(), 1); + assert!(!rt.motion.flights()[0].glyphs.is_empty(), "the visible composer glyphs survive clearing the model"); + let mut previous_target = rt.motion.flights()[0].destination; + let mut retargets = 0; + for _ in 0..240 { + rt.frame(1.0 / 120.0); + if let Some(f) = rt.motion.flights().first() { + assert!(rt.instances.iter().any(|q| q.params[1] == KIND_GLYPH && (q.uv[2] > 0.0 || q.radii[3] > 0.0) && q.fill[3] > 0.1 + && q.rect[0].max(q.clip[0]) + 1.0 < (q.rect[0] + q.rect[2]).min(q.clip[2]) + && q.rect[1].max(q.clip[1]) + 1.0 < (q.rect[1] + q.rect[3]).min(q.clip[3])), + "the source/destination handoff never loses every visible glyph"); + let target = rt.tree.nodes.iter().position(|n| n.key.as_deref() == Some("destination")).unwrap(); + assert!((f.destination.y - rt.paint.drawn[target][1]).abs() < 0.01, "destination is this frame's post-scroll geometry"); + if f.destination != previous_target { retargets += 1; } + previous_target = f.destination; + } + } + assert!(retargets > 3, "earlier row growth actually moved the destination"); + assert!(rt.motion.flights().is_empty(), "flight lands and releases the captured glyphs"); + assert!(!rt.animating); +} + +#[test] +fn virtual_rows_match_full_layout_while_paging_and_keep_a_keyed_anchor() { + struct State { virtualized: bool, keys: Vec<usize> } + fn view(s: &State, _: &mut Cx<State>) -> El { + let mut stack = col().key("rows").w_full().pt(8.0).pb(24.0).growth(GrowthSpec::default()); + if s.virtualized { stack = stack.virtualize(80.0); } + for &i in &s.keys { + stack = stack.child(col().key(format!("r{i}")).w_full().pb(9.0).child( + crate::el::text(format!("Row {i}: {}", "variable height héllo naïve ".repeat(i % 7 + 1))).wrap().w_full() + )); + } + col().key("scroll").w_full().h_full().clip_fade(0.0, 8.0, 0.0, 8.0).scroll(ScrollSpec { stick_bottom: true }).child(stack) + } + let env = Env::new(true, 2.0); + let mut full = Runtime::new(State { virtualized: false, keys: (0..600).collect() }, view, (240.0, 300.0), env); + let mut window = Runtime::new(State { virtualized: true, keys: (0..600).collect() }, view, (240.0, 300.0), env); + full.frame(0.0); + window.frame(0.0); + assert!(window.tree.nodes.len() < 100, "offscreen rows aren't laid out or retained in the scene"); + assert!(window.text.shaped < full.text.shaped / 5, "offscreen text isn't shaped"); + let visible = |r: &Runtime<State>| r.elements().into_iter() + .filter(|e| e.key.as_ref().is_some_and(|k| k.starts_with('r') && k != "rows") && e.visible[3] > 0.0) + .map(|e| (e.key.unwrap(), e.rect)).collect::<Vec<_>>(); + for step in 0..135 { + let a = visible(&full); + let b = visible(&window); + assert_eq!(a.len(), b.len(), "visible count at step {step}: {a:?} vs {b:?}"); + for ((ak, ar), (bk, br)) in a.iter().zip(&b) { + assert_eq!(ak, bk, "visible identity at step {step}"); + assert!(ar.iter().zip(br).all(|(a, b)| (a - b).abs() < 0.05), "anchor at step {step}: {ak} {ar:?} vs {br:?}"); + } + let dy = if step < 90 { 137.25 } else { -137.25 }; + full.wheel(120.0, 150.0, dy); + window.wheel(120.0, 150.0, dy); + full.frame(1.0 / 120.0); + window.frame(1.0 / 120.0); + } + let before = visible(&window); + window.state.keys.insert(0, 9000); + window.invalidate(); + window.frame(1.0 / 120.0); + assert_eq!(before, visible(&window), "prepending outside the window preserves its keyed anchor"); + assert!(window.tree.nodes.len() < 150 && window.motion.grows.len() < 70, "paging releases old row state"); + let anchor = visible(&window)[0].clone(); + window.set_viewport((320.0, 300.0), 2.0); + window.frame(0.0); + for _ in 0..60 { + let after = visible(&window); + let rect = after.iter().find(|(key, _)| key == &anchor.0).expect("resize retains the visible keyed anchor"); + assert!((rect.1[1] - anchor.1[1]).abs() < 0.05, "resize anchor moved: {:?} vs {:?}", anchor, rect); + window.frame(1.0 / 120.0); + } + window.settle_all(); + window.frame(0.0); + let last = visible(&window).pop().unwrap(); + assert_eq!(last.0, "r599"); + assert!((last.1[1] + last.1[3] - 276.0).abs() < 0.05, "return lands at the exact bottom"); + assert!(!window.animating, "moving: {:?}; active: {}", window.elements().into_iter().filter(|e| e.moving).map(|e| (e.path, e.rect, e.target, e.opacity)).collect::<Vec<_>>(), window.scene.store().active_len()); +} + +#[test] +fn reduced_motion_rows_land_immediately_but_keep_the_presence_fade() { + fn view(show: &bool, cx: &mut Cx<bool>) -> El { + cx.reduced_motion(true); + let mut stack = col().w_full().growth(GrowthSpec::default()); + if *show { + stack = stack.child(el().key("row").size(200.0, 100.0)); + } + stack + } + let mut rt = Runtime::new(false, view, (200.0, 300.0), Env::new(true, 2.0)); + assert!(!rt.frame(0.0)); + rt.state = true; + rt.invalidate(); + rt.frame(1.0 / 120.0); + let row = rt.elements().into_iter().find(|e| e.key.as_deref() == Some("row")).unwrap(); + assert_eq!(row.rect[3], 100.0, "reduced motion removes growth travel"); + assert!(row.opacity > 0.0 && row.opacity < 1.0, "new rows still fade in"); + rt.frame(0.2); + assert!(!rt.animating); + assert_eq!(rt.elements().into_iter().find(|e| e.key.as_deref() == Some("row")).unwrap().opacity, 1.0); + rt.state = false; + rt.invalidate(); + rt.frame(1.0 / 120.0); + let row = rt.elements().into_iter().find(|e| e.key.as_deref() == Some("row")).unwrap(); + assert!(row.opacity > 0.0 && row.opacity < 1.0, "removed rows stay for their fade"); + for _ in 0..60 { rt.frame(1.0 / 120.0); } + assert!(!rt.animating); + assert!(rt.elements().iter().all(|e| e.key.as_deref() != Some("row"))); +} + +#[test] +fn streaming_fill_and_width_rewrap_land_on_completion() { + fn view(state: &(String, bool), _: &mut Cx<(String, bool)>) -> El { + col().w_full().growth(GrowthSpec::default()).child( + col().key("row").w_full().streaming(state.1).child(crate::el::text(state.0.clone()).wrap().w_full().reveal(0.18)) + ) + } + let mut rt = Runtime::new(("one".into(), true), view, (180.0, 500.0), Env::new(true, 2.0)); + rt.frame(0.0); + rt.state.0 = "one two three four five six seven eight nine ten eleven".into(); + rt.invalidate(); + rt.frame(1.0 / 120.0); + let row = rt.tree.nodes.iter().find(|n| n.key.as_deref() == Some("row")).unwrap().id; + let n = &rt.tree.nodes[rt.tree.node_index[&row]]; + let full = n.local.h; + assert!(rt.motion.grows[&row].target < full, "new line is held back while filling"); + for _ in 0..240 { rt.frame(1.0 / 120.0); } + assert!(!rt.animating, "partial line at rest must stop ticking"); + let old_h = rt.motion.grows[&row].h; + rt.set_viewport((600.0, 500.0), 2.0); + rt.state.0.push_str(" twelve"); + rt.invalidate(); + rt.frame(1.0 / 120.0); + assert_eq!(rt.motion.grows[&row].target, old_h, "rewrap waits for stable width"); + for _ in 0..15 { rt.frame(1.0 / 120.0); } + assert!(rt.motion.grows[&row].target < old_h, "width change may shrink a streaming row"); + assert!(rt.motion.grows[&row].h > rt.motion.grows[&row].target, "rewrapped height eases instead of snapping"); + rt.state.0 = "one two".into(); + rt.invalidate(); + rt.frame(0.0); + assert!(rt.motion.grows[&row].target < rt.motion.grows[&row].h, "streaming may still shrink inside the 400 ms rewrap window"); + for _ in 0..120 { rt.frame(1.0 / 120.0); } + let landed = rt.motion.grows[&row].h; + rt.state.0 = "o".into(); + rt.invalidate(); + rt.frame(0.0); + assert_eq!(rt.motion.grows[&row].target, landed, "streaming cannot shrink after the rewrap window"); + rt.state.1 = false; + rt.invalidate(); + for _ in 0..240 { rt.frame(1.0 / 120.0); } + assert!(!rt.animating); + assert_eq!(rt.motion.grows[&row].h, rt.tree.nodes[rt.tree.node_index[&row]].local.h); +} + +#[test] +fn retained_layout_matches_fresh_tree_across_edits() { + fn view(seed: &usize, _: &mut Cx<usize>) -> El { + let mut root = col().key("root").w_full(); + for k in 0..8 { + let i = (k + seed) % 8; + if (i + seed) % 5 == 0 { continue; } + let body = "some words ".repeat((i + seed) % 10 + 1); + let child = if (i + seed) % 7 == 0 { el().h(31.0) } else { crate::el::text(body).wrap() }; + root = root.child(child.key(format!("row-{i}")).w_full().px((seed % 3) as f32)); + } + root + } + let env = Env::new(true, 2.0); + let mut cached = Runtime::new(0usize, view, (320.0, 600.0), env); + for seed in 0..40 { + let size = (240.0 + (seed % 4) as f32 * 30.0, 600.0); + let scale = if seed % 3 == 0 { 1.0 } else { 2.0 }; + cached.state = seed; + cached.set_viewport(size, scale); + cached.settle_all(); + cached.frame(0.0); + let mut fresh = Runtime::new(seed, view, size, Env { scale, ..env }); + fresh.frame(0.0); + let rects = |r: &Runtime<usize>| r.elements().into_iter().filter(|e| e.opacity > 0.0).map(|e| (e.path, e.target)).collect::<Vec<_>>(); + assert_eq!(rects(&cached), rects(&fresh), "edit {seed}"); + } +} diff --git a/app/vendor/rune/crates/rune/src/runtime/tests/loop_sleep.rs b/app/vendor/rune/crates/rune/src/runtime/tests/loop_sleep.rs new file mode 100644 index 0000000..bbd23a2 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/tests/loop_sleep.rs @@ -0,0 +1,181 @@ +use super::*; + + +#[test] +fn delayed_loops_sleep_on_the_shared_deadline_and_resume_after_native_idle() { + fn view(s: &(f32, f32), cx: &mut Cx<(f32, f32)>) -> El { + cx.time_scale(s.1); + el().size(100.0, 100.0).opacity(s.0).child(el().size(20.0, 20.0) + .looping(rune_motion::LoopSpec::opacity(1.0, 2.0, 0.0, 1.0))) + } + let make = |opacity, scale| Runtime::new((opacity, scale), view, (100.0, 100.0), Env::new(true, 1.0)); + let mut rt = make(1.0, 1.0); + assert!(!rt.frame(0.0)); + assert_eq!(rt.wake_deadline(), Some(2.0)); + let commits = rt.stats.commits; + assert!(!rt.frame(1.0)); + assert_eq!(rt.wake_deadline(), Some(2.0)); + assert!(rt.frame(1.0), "a zero-opacity first pose must still start the loop"); + assert_eq!(rt.stats.commits, commits); + assert_eq!(rt.wake_deadline(), None); + let mut rt = make(1.0, 1.0); + rt.frame(0.0); + rt.wall_start = Some(crate::time::now() - std::time::Duration::from_secs(1)); + assert!(!rt.frame(1.0 / 120.0)); + assert!((rt.wake_deadline().unwrap() - 2.0).abs() < 0.001, "an input during idle must not postpone the loop"); + rt.wall_start = Some(crate::time::now() - std::time::Duration::from_secs(2)); + assert!(rt.frame(1.0 / 120.0)); + assert!((rt.t - 2.0).abs() < 0.001, "idle dt must not postpone the start again"); + let mut rt = make(1.0, 0.5); + assert!(!rt.frame(0.0)); + assert_eq!(rt.wake_deadline(), Some(4.0)); + rt.set_live_visible(false); + assert_eq!(rt.wake_deadline(), None); + rt.frame(0.0); + assert_eq!(rt.wake_deadline(), None); + for (opacity, scale) in [(0.0, 1.0), (1.0, 0.0)] { + let mut rt = make(opacity, scale); + assert!(!rt.frame(0.0)); + assert_eq!(rt.wake_deadline(), None); + } +} + +#[test] +fn cycles_share_deadlines_and_sleep_when_hidden_by_hover_groups() { + fn view(hidden: &bool, _: &mut Cx<bool>) -> El { + el().size(100.0, 100.0).hover_group().child(el().key("cycle").size(20.0, 20.0) + .group_opacity(if *hidden { 0.0 } else { 1.0 }, 1.0) + .cycle(crate::Cycle { period: 1.0, phase: 0.0, + stops: &[(0.0, 0.0), (0.5, 1.0), (1.0, 0.0)], still: 0.4, fps: 30.0 })) + } + let mut rt = Runtime::new(false, view, (100.0, 100.0), Env::new(true, 1.0)); + assert!(!rt.frame(0.0), "cycles must sleep rather than request continuous frames"); + assert!((rt.wake_deadline().unwrap() - 1.0 / 30.0).abs() < 1e-7); + assert_eq!(rt.motion.loops_len(), 1); + let commits = rt.stats.commits; + rt.frame(0.5); + assert_eq!(rt.stats.commits, commits); + assert!((rt.ambient.unwrap() - 1.0 / 30.0).abs() < 1e-7); + // A new rest fades on the element's motion; an instant one lands in the frame. + rt.update(|s, tx| { tx.instant(); *s = true }); rt.frame(0.0); + assert_eq!(rt.wake_deadline(), None, "group-opacity zero must not wake"); + rt.update(|s, tx| { tx.instant(); *s = false }); rt.frame(0.0); + assert!(rt.wake_deadline().is_some()); + rt.set_live_visible(false); rt.frame(0.0); + assert_eq!(rt.wake_deadline(), None); + rt.set_live_visible(true); rt.frame(0.0); + assert!(rt.wake_deadline().is_some()); + rt.reduced_motion = true; rt.frame(0.0); + assert_eq!(rt.wake_deadline(), None); +} + +#[test] +fn loops_sleep_below_one_8_bit_step_of_opacity() { + fn view(rest: &f32, _: &mut Cx<f32>) -> El { + el().size(100.0, 100.0).hover_group().child(el().key("cycle").size(20.0, 20.0) + .group_opacity(*rest, 1.0) + .cycle(crate::Cycle { period: 1.0, phase: 0.0, + stops: &[(0.0, 0.0), (0.5, 1.0), (1.0, 0.0)], still: 0.4, fps: 30.0 })) + } + for (rest, wakes) in [(0.003, false), (0.005, true)] { + let mut rt = Runtime::new(rest, view, (100.0, 100.0), Env::new(true, 1.0)); + rt.frame(0.0); + assert_eq!(rt.wake_deadline().is_some(), wakes, "rest opacity {rest}"); + } +} + +#[test] +fn loops_sleep_offscreen_hidden_reduced_and_after_exit() { + fn view(s: &(f32, bool, bool), cx: &mut Cx<(f32, bool, bool)>) -> El { + cx.reduced_motion(s.2); + let mut root = col().key("root").size(100.0, 100.0).clip_soft(0.0); + if s.1 { + root = root.child(el().key("loop").absolute(0.0, s.0).size(20.0, 20.0).fill(Color::WHITE) + .looping(rune_motion::LoopSpec::opacity(1.0, 0.0, 0.4, 1.0))); + } + root + } + for (y, shown, reduced, active) in [(0.0, true, false, true), (200.0, true, false, false), + (0.0, false, false, false), (0.0, true, true, false)] { + let mut rt = Runtime::new((y, shown, reduced), view, (100.0, 100.0), Env::new(true, 2.0)); + assert_eq!(rt.frame(0.0), active); + // Model the shell's scheduling gate: zero requested frames over ten seconds at rest. + let mut requested = 0; + for _ in 0..1200 { if rt.animating { requested += 1; rt.frame(1.0 / 120.0); } } + assert_eq!(requested, if active { 1200 } else { 0 }); + if active { + rt.state.1 = false; rt.invalidate(); rt.frame(0.0); + assert!(rt.elements().iter().any(|e| e.key.as_deref() == Some("loop") && e.opacity > 0.0)); + for _ in 0..240 { rt.frame(1.0 / 120.0); } + assert!(!rt.animating); + assert!(!rt.elements().iter().any(|e| e.key.as_deref() == Some("loop"))); + } + } +} + +#[test] +fn slides_sweep_through_their_clip_and_sleep_when_hidden_or_reduced() { + type S = (bool, bool, Option<rune_motion::Easing>); + fn view(s: &S, cx: &mut Cx<S>) -> El { + cx.reduced_motion(s.1); + let mut track = crate::row().key("track").size(100.0, 8.0).clip_soft(0.0); + if s.0 { + let mut spec = rune_motion::LoopSpec::slide(1.0, [-1.0, 0.0], [4.0, 0.0]); + if let Some(e) = s.2 { spec = spec.easing(e); } + track = track.child(el().key("bar").w_frac(0.25).h_full().fill(Color::WHITE).looping(spec)); + } + col().size(100.0, 100.0).child(track) + } + let bar = |rt: &Runtime<S>| { + rt.elements().into_iter().find(|e| e.key.as_deref() == Some("bar")).map(|e| e.rect[0]) + }; + for easing in [None, Some(rune_motion::Easing::LINEAR)] { + let mut rt = Runtime::new((true, false, easing), view, (100.0, 100.0), Env::new(true, 2.0)); + assert!(rt.frame(0.0), "a slide starting outside its clip must still run"); + assert_eq!(bar(&rt), Some(-25.0)); + let mut xs = Vec::new(); + for _ in 0..128 { assert!(rt.frame(1.0 / 128.0)); xs.push(bar(&rt).unwrap()); } + assert!((xs[63] - 37.5).abs() < 0.01, "halfway through the period is the sweep's midpoint: {}", xs[63]); + assert!(xs[..127].windows(2).all(|w| w[1] >= w[0])); + if easing == Some(rune_motion::Easing::LINEAR) { + let step = 125.0 / 128.0; + assert!(xs[..126].windows(2).all(|w| (w[1] - w[0] - step).abs() < 0.05)); + } + assert_eq!(xs[127], -25.0, "the sweep wraps"); + rt.state.0 = false; rt.invalidate(); + for _ in 0..240 { rt.frame(1.0 / 120.0); } + assert!(!rt.animating); + let mut rt = Runtime::new((true, true, easing), view, (100.0, 100.0), Env::new(true, 2.0)); + assert!(!rt.frame(0.0)); + assert_eq!(bar(&rt), Some(37.5), "reduced motion holds the midpoint"); + let mut rt = Runtime::new((true, false, easing), view, (100.0, 100.0), Env::new(true, 2.0)); + rt.frame(0.0); + rt.set_live_visible(false); + assert!(!rt.frame(1.0 / 120.0)); + } +} + +#[test] +fn delayed_opacity_handoff_never_overprints_the_outgoing_label() { + use rune_motion::AnimExt; + fn view(s: &(bool, bool), cx: &mut Cx<(bool, bool)>) -> El { + cx.reduced_motion(s.1); + let fade = |show| rune_motion::Curve::ease_in_out(0.18).delay(if show { 0.18 } else { 0.0 }); + col().child(el().key("copy").size(28.0, 28.0).opacity(if s.0 { 0.0 } else { 1.0 }).opacity_motion(fade(!s.0))) + .child(el().key("working").size(28.0, 28.0).opacity(if s.0 { 1.0 } else { 0.0 }).opacity_motion(fade(s.0))) + } + for reduced in [false, true] { + let mut rt = Runtime::new((false, reduced), view, (100.0, 100.0), Env::new(true, 2.0)); + rt.frame(0.0); + for busy in [true, false] { + rt.state.0 = busy; + rt.invalidate(); + for _ in 0..60 { + rt.frame(1.0 / 120.0); + let alpha = |key| rt.elements().into_iter().find(|e| e.key.as_deref() == Some(key)).unwrap().opacity; + assert!(alpha("copy").min(alpha("working")) < 0.001); + } + assert!(!rt.animating); + } + } +} diff --git a/app/vendor/rune/crates/rune/src/runtime/tests/matched_scroll.rs b/app/vendor/rune/crates/rune/src/runtime/tests/matched_scroll.rs new file mode 100644 index 0000000..5ad9629 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/tests/matched_scroll.rs @@ -0,0 +1,43 @@ +use super::*; +use crate::{Color, Key, Mods, ScrollSpec}; + +#[derive(Default)] +struct Viewer { + open: bool, + glide: u32, +} + +/// A tile in a list scrolled out of its first rows, or open over it, outside the scroll. +fn view(s: &Viewer, _: &mut Cx<Viewer>) -> El { + let tile = |size: f32| el().key("tile").matched("tile").size(size, size).fill(Color::WHITE); + let slot = if s.open { el().key("held").size(40.0, 40.0) } else { tile(40.0) }; + let rows = col().key("rows").w_full().child(el().w_full().h(200.0)).child(slot).child(el().w_full().h(400.0)); + let list = col().key("list").size(300.0, 200.0).scroll(ScrollSpec { stick_bottom: false }).child(rows); + let root = col().size(300.0, 200.0).child(list); + if s.open { root.child(tile(160.0).absolute(100.0, 0.0)) } else { root } +} + +fn close(s: &mut Viewer, _: &KeyEvent, _: &mut Tx) -> bool { + s.open = false; + true +} + +#[test] +fn a_flight_home_after_an_earlier_commit_in_its_frame_starts_where_it_was_seen() { + let mut rt = Runtime::new(Viewer::default(), view, (300.0, 200.0), Env::new(true, 1.0)); + rt.on_key = Some(close); + rt.frame(0.0); + rt.wheel(150.0, 100.0, -150.0); + for _ in 0..30 { rt.frame(1.0 / 60.0); } + assert_eq!(rt.presented("tile").expect("tile").0, [0.0, 50.0, 40.0, 40.0]); + rt.update(|s, _| s.open = true); + for _ in 0..120 { rt.frame(1.0 / 60.0); } + assert_eq!(rt.presented("tile").expect("tile").0, [100.0, 0.0, 160.0, 160.0]); + // A glide changes state each frame, so the frame commits it before routing the key that + // closes the viewer: the flight home starts from the second commit. + rt.update(|s, _| s.glide += 1); + rt.key(KeyEvent { key: Key::Escape, mods: Mods::default() }); + rt.frame(1.0 / 120.0); + let first = rt.presented("tile").expect("tile").0; + assert!(first[0] > 90.0 && first[1] > -10.0 && first[1] < 10.0, "starts where it showed open: {first:?}"); +} diff --git a/app/vendor/rune/crates/rune/src/runtime/tests/mod.rs b/app/vendor/rune/crates/rune/src/runtime/tests/mod.rs new file mode 100644 index 0000000..4c6615b --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/tests/mod.rs @@ -0,0 +1,62 @@ +use super::*; +use crate::PointerPress; +use crate::el::{col, el}; + +mod app_ime; +mod context_menu_key; +mod draw_on; +mod edit; +mod event_markers; +mod find_key; +mod fold_glide; +mod glyph_replay; +mod group_opacity; +mod id_pruning; +mod input_clipboard; +mod layout_hover; +mod layout_reads; +mod layout_rows; +mod loop_sleep; +mod matched_scroll; +mod no_motion; +mod one_snap; +mod picture_scale; +mod pointer_drag; +mod pointer_hit; +mod press_moving; +mod relayout; +mod remount; +mod reveal_chain; +mod reveal_phase; +mod scroll_carried; +mod scroll_children; +mod scroll_growth; +mod scroll_hover; +mod scroll_retarget; +mod scroll_spring; +mod secure_text; +mod selection_edge_walk; +mod selection_phase; +mod selection_phase_virtual; +mod settle_input; +mod shimmer; +mod springs; +mod stream_overflow; +mod stream_pace; +mod text_glide; +mod text_keys; +mod text_quads; +mod text_rebreak; +mod titlebar_press; +mod unseen_entrances; +mod window_wake; + +thread_local! { + /// Runs once inside the next frame, after layout and just before live values latch: a + /// publication from another thread landing at the worst moment. + pub(super) static MID_FRAME: std::cell::RefCell<Option<Box<dyn FnOnce()>>> = const { std::cell::RefCell::new(None) }; +} + +fn duplicate_view(_: &(), _: &mut Cx<()>) -> El { + col().children([el().key("card"), el().key("card")]) +} diff --git a/app/vendor/rune/crates/rune/src/runtime/tests/no_motion.rs b/app/vendor/rune/crates/rune/src/runtime/tests/no_motion.rs new file mode 100644 index 0000000..f5e453a --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/tests/no_motion.rs @@ -0,0 +1,79 @@ +use super::*; +use crate::{SpringPair, TextEdit, TextStyle, text_input}; + +fn find<S: 'static>(rt: &Runtime<S>, key: &str) -> Option<ElementInfo> { + rt.elements().into_iter().find(|e| e.key.as_deref() == Some(key)) +} + +/// (shown, transition): a pill over a row that its mount pushes down. +fn pill_view(s: &(bool, Transition), _: &mut Cx<(bool, Transition)>) -> El { + col().size(200.0, 200.0) + .children(s.0.then(|| el().key("pill").size(100.0, 40.0).transition(s.1))) + .child(el().key("row").size(100.0, 40.0)) +} + +#[test] +fn a_none_transition_lands_in_the_frame_while_the_rest_animates() { + let short = crate::Spring::new(0.001, 0.0); + for reduced in [false, true] { + let mut rt = Runtime::new((false, Transition::none()), pill_view, (200.0, 200.0), Env::new(true, 1.0)); + rt.set_system_reduced_motion(reduced); + rt.frame(0.0); + rt.update(|s, _| s.0 = true); + rt.frame(0.0); + let pill = find(&rt, "pill").unwrap(); + assert_eq!(pill.opacity, 1.0, "whole in the frame it mounts (reduced motion: {reduced})"); + if !reduced { + let row = find(&rt, "row").unwrap(); + assert!(row.rect[1] < row.target[1] - 1.0, "the row it pushes still springs: {:?}", row.rect); + } + rt.update(|s, _| s.0 = false); + rt.frame(0.0); + assert!(find(&rt, "pill").is_none_or(|p| p.opacity == 0.0), "gone in the frame it's removed"); + rt.frame(0.0); + assert!(find(&rt, "pill").is_none(), "and unmounted by the next"); + } + // Under Reduce Motion a very short spring becomes a fade, so its node lingers; `none` doesn't. + let mut rt = Runtime::new((true, Transition::identity().springs(SpringPair::new(short, short))), pill_view, (200.0, 200.0), Env::new(true, 1.0)); + rt.set_system_reduced_motion(true); + rt.frame(0.0); + rt.update(|s, _| s.0 = false); + rt.frame(0.0); + rt.frame(0.0); + assert!(find(&rt, "pill").is_some()); +} + +#[derive(Default)] +struct Form { open: bool, field: TextEdit, modal: bool, none: bool, instant: bool } + +fn button(key: &str) -> El { el().key(key).size(30.0, 30.0).focusable(true).role("button") } + +fn form_view(s: &Form, _: &mut Cx<Form>) -> El { + let field = text_input(&s.field, TextStyle::new(14.0, 400.0)).key("field").size(120.0, 30.0).on_edit(|s: &mut Form| &mut s.field); + let mut popup = col().key("popup").absolute(100.0, 0.0).size(150.0, 100.0).child(field); + popup = if s.modal { popup.modal(true, |s: &mut Form| s.open = false) } else { popup.focus_return("opener") }; + if s.none { popup = popup.transition(Transition::none()); } + col().key("root").size(300.0, 300.0) + .child(button("opener").on_press(|s: &mut Form| { s.open = true; s.field.focused = true; })) + .children(s.open.then_some(popup)) +} + +#[test] +fn closing_at_once_returns_focus_to_the_opener() { + let focused = |rt: &Runtime<Form>| rt.elements().into_iter().find(|e| e.focused).and_then(|e| e.key); + for modal in [false, true] { + for (none, instant) in [(false, true), (true, false), (true, true)] { + let mut rt = Runtime::new(Form { modal, none, instant, ..Form::default() }, form_view, (300.0, 300.0), Env::new(true, 1.0)); + rt.frame(0.0); + let (x, y) = rt.find("opener").unwrap(); + rt.pointer_down(x, y); rt.pointer_up(x, y); rt.frame(0.0); + assert_eq!(focused(&rt).as_deref(), Some("field")); + // The handler leaves the field's own `focused` set: it unmounts without a blur. + rt.update(|s, tx| { if s.instant { tx.instant(); } s.open = false; }); + rt.frame(0.0); + rt.frame(1.0 / 60.0); + assert!(find(&rt, "popup").is_none()); + assert_eq!(focused(&rt).as_deref(), Some("opener"), "modal {modal}, none {none}, instant {instant}"); + } + } +} diff --git a/app/vendor/rune/crates/rune/src/runtime/tests/one_snap.rs b/app/vendor/rune/crates/rune/src/runtime/tests/one_snap.rs new file mode 100644 index 0000000..16b962f --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/tests/one_snap.rs @@ -0,0 +1,658 @@ +//! Sub-pixel and pixel-snapped concentric placement across fills, vector shapes, icons and text +//! (`t1193`): two primitives in the same box keep the same centre and drawn size whether still, +//! scaled, anchored, gliding on a spring, or swapping between `canvas` and `icon`. +use crate::el::{Align, Side}; +use crate::render::{Gpu, KIND_GLYPH, KIND_RECT, Offscreen, Renderer, write_png}; +use crate::shape::Shape; +use crate::{Color, Cx, El, Env, Icon, Runtime, TextStyle, canvas, col, el, icon, row, text}; +use rune_motion::Spring; + +const FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Rgba8Unorm; +const RED: Color = Color { r: 1.0, g: 0.0, b: 0.0, a: 1.0 }; +const GREEN: Color = Color { r: 0.0, g: 1.0, b: 0.0, a: 1.0 }; +const BLUE: Color = Color { r: 0.0, g: 0.0, b: 1.0, a: 1.0 }; + +static RING_ICON: Icon = Icon { + name: "ring", + view: 16.0, + body: r#"<circle cx="8" cy="8" r="6.5" stroke="currentColor" stroke-width="1.5" fill="none"/>"#, +}; + +static DISC_ICON: Icon = Icon { + name: "disc", + view: 16.0, + body: r#"<circle cx="8" cy="8" r="4" fill="currentColor"/>"#, +}; + +/// Symmetric 64-gon around `(cx, cy)`: 4-fold symmetric so its exact centroid is `(cx, cy)`. +fn circle_pts(cx: f32, cy: f32, r: f32) -> Vec<[f32; 2]> { + (0..64) + .map(|k| { + let a = std::f32::consts::TAU * k as f32 / 64.0; + [cx + r * a.cos(), cy + r * a.sin()] + }) + .collect() +} + +fn disc_shape(r: f32, color: Color) -> Shape { + Shape::new().fill(circle_pts(8.0, 8.0, r), color) +} + +struct Bench { + gpu: Gpu, + renderer: Renderer, + target: Offscreen, + dw: u32, + dh: u32, +} + +impl Bench { + fn new(w: u32, h: u32, scale: f32) -> Self { + let gpu = Gpu::headless(); + let renderer = Renderer::new(&gpu.device, FORMAT); + let (dw, dh) = ((w as f32 * scale) as u32, (h as f32 * scale) as u32); + let target = Offscreen::with_format(&gpu.device, dw, dh, FORMAT); + Self { gpu, renderer, target, dw, dh } + } + + fn draw<S: 'static>(&mut self, rt: &mut Runtime<S>, clear: [f64; 4]) -> Vec<u8> { + self.renderer.prepare( + &self.gpu.device, + &self.gpu.queue, + &mut rt.text.atlas, + &rt.instances, + (self.dw, self.dh), + ); + let mut enc = self.gpu.device.create_command_encoder(&Default::default()); + self.renderer.draw( + &mut enc, + &self.target.view, + clear.map(|v| v as f32), + ); + self.target.copy(&mut enc); + self.renderer.submit(&self.gpu.queue, enc); + self.target.read(&self.gpu.device) + } +} + +/// Coverage-weighted `[cx, cy]` (device px) and total pixel area (`sum(cov / 255)`) of channel `ch` +/// inside `rgba` (`dw × dh`). +fn channel_moments(rgba: &[u8], dw: u32, dh: u32, ch: usize) -> ([f32; 2], f32) { + let (mut sum, mut sx, mut sy) = (0.0f64, 0.0f64, 0.0f64); + for y in 0..dh { + for x in 0..dw { + let v = rgba[((y * dw + x) * 4) as usize + ch] as f64 / 255.0; + if v > 0.0 { + sum += v; + sx += v * (x as f64 + 0.5); + sy += v * (y as f64 + 0.5); + } + } + } + assert!(sum > 0.0, "channel {ch} must have non-zero coverage"); + ([(sx / sum) as f32, (sy / sum) as f32], sum as f32) +} + +fn whole(v: f32) -> bool { + (v - v.round()).abs() < 1e-4 +} + +fn percentile(mut xs: Vec<f32>, p: f32) -> f32 { + if xs.is_empty() { + return 0.0; + } + xs.sort_by(f32::total_cmp); + let idx = ((xs.len() - 1) as f32 * p).round() as usize; + xs[idx] +} + +#[derive(Clone, Copy)] +struct ScaledCase { + at: [f32; 2], + zoom: f32, + anchored: bool, + only_icon_disc: bool, +} + +fn scaled_view(s: &ScaledCase, _: &mut Cx<ScaledCase>) -> El { + let badge = if s.only_icon_disc { + el().key("badge") + .size(16.0, 16.0) + .child(icon(&DISC_ICON, 16.0).color(RED).absolute(0.0, 0.0)) + } else { + el().key("badge") + .size(16.0, 16.0) + .fill(BLUE) + .child(icon(&RING_ICON, 16.0).color(RED).absolute(0.0, 0.0)) + .child(canvas(disc_shape(4.0, GREEN)).size(16.0, 16.0).absolute(0.0, 0.0)) + }; + if s.anchored { + let page = col() + .key("page") + .size(120.0, 120.0) + .scale(s.zoom) + .origin(0.0, 0.0) + .child(el().key("anchor").absolute(12.0 + s.at[0], 10.0 + s.at[1]).size(24.0, 8.0)); + let pop = col() + .key("pop") + .padding(6.0) + .fill(Color { r: 0.0, g: 0.0, b: 0.25, a: 1.0 }) + .child(badge) + .anchored("anchor", Side::Bottom, Align::Start, 4.0); + col().size(160.0, 160.0).children([page, pop]) + } else { + col().size(160.0, 160.0).child( + col() + .key("scaled") + .size(100.0, 100.0) + .scale(s.zoom) + .origin(0.0, 0.0) + .child(badge.absolute(14.0 + s.at[0], 14.0 + s.at[1])), + ) + } +} + +/// (1) Still-scaled concentric icon + `canvas` shape in the same fractional rect (1.6× zoom on 2× +/// display, both direct `El::scale` and `El::anchored`), plus matching drawn area (`515 px`, no 2% +/// rounding drop) and whole-pixel snapping of the held `1.6×` anchored popover. +#[test] +fn concentric_icon_and_shape_share_centre_and_size_at_scaled_rest() { + let mut bench = Bench::new(160, 160, 2.0); + for anchored in [false, true] { + let mut max_err = 0.0f32; + let (mut min_icon_area, mut max_icon_area) = (f32::MAX, 0.0f32); + for iy in 0..5 { + for ix in 0..5 { + let at = [ix as f32 * 0.21, iy as f32 * 0.21]; + let mut rt = Runtime::new( + ScaledCase { at, zoom: 1.6, anchored, only_icon_disc: false }, + scaled_view, + (160.0, 160.0), + Env::new(true, 2.0), + ); + rt.frame(0.0); + rt.frame(1.0 / 120.0); + + // Every resting fill inside the scaled / anchored subtree must snap to whole pixels. + let fills: Vec<[f32; 4]> = rt + .instances + .iter() + .filter(|i| i.params[1] == KIND_RECT && i.fill[3] > 0.0) + .map(|i| i.rect) + .collect(); + assert!(!fills.is_empty()); + for r in &fills { + assert!( + r.iter().all(|&v| whole(v)), + "anchored={anchored} at={at:?}: held 1.6x fill must snap to whole device px, got {r:?}" + ); + } + + let rgba = bench.draw(&mut rt, [0.0; 4]); + let (c_icon, _) = channel_moments(&rgba, bench.dw, bench.dh, 0); + let (c_shape, shape_disc_area) = channel_moments(&rgba, bench.dw, bench.dh, 1); + let err_x = (c_icon[0] - c_shape[0]).abs(); + let err_y = (c_icon[1] - c_shape[1]).abs(); + max_err = max_err.max(err_x).max(err_y); + assert!( + err_x <= 0.125 && err_y <= 0.125, + "anchored={anchored} at={at:?}: icon centre {c_icon:?} vs shape centre {c_shape:?} (err=({err_x:.4}, {err_y:.4}))" + ); + + // Compare the drawn area of the r=4 disc icon across both 51 px and 52 px snapped + // boxes (`iy == 2`, `ix = 0..5`): continuous `drawn` sizing keeps the icon's area + // steady within 0.5% (no `51 <-> 52 px` 4% jump) and within 1.5% of the ear-clipped + // polygon disc. + if iy == 2 { + let mut rt_disc = Runtime::new( + ScaledCase { at, zoom: 1.6, anchored, only_icon_disc: true }, + scaled_view, + (160.0, 160.0), + Env::new(true, 2.0), + ); + rt_disc.frame(0.0); + rt_disc.frame(1.0 / 120.0); + let rgba_disc = bench.draw(&mut rt_disc, [0.0; 4]); + let (_, icon_disc_area) = channel_moments(&rgba_disc, bench.dw, bench.dh, 0); + min_icon_area = min_icon_area.min(icon_disc_area); + max_icon_area = max_icon_area.max(icon_disc_area); + let rel = (icon_disc_area - shape_disc_area).abs() / shape_disc_area; + assert!( + rel < 0.015, + "anchored={anchored} at={at:?}: icon disc area {icon_disc_area:.2} vs shape disc area {shape_disc_area:.2} (rel={rel:.4})" + ); + } + } + } + let spread = (max_icon_area - min_icon_area) / min_icon_area; + assert!( + spread < 0.005, + "anchored={anchored}: icon disc area jumped across pixel phases: {min_icon_area:.2}..{max_icon_area:.2} ({:.2}%)", + spread * 100.0 + ); + eprintln!( + "still-scaled (anchored={anchored}): max axis centre offset = {max_err:.4} px, icon disc area = {min_icon_area:.2}..{max_icon_area:.2} px" + ); + } +} + +#[derive(Clone, Copy)] +struct MovingCase { + at: [f32; 2], + zoom: f32, +} + +fn moving_view(s: &MovingCase, _: &mut Cx<MovingCase>) -> El { + let badge = el() + .key("badge") + .size(16.0, 16.0) + .fill(BLUE) + .offset(s.at[0], s.at[1]) + .offset_motion(Spring::new(0.45, 0.0)) + .child(icon(&RING_ICON, 16.0).color(RED).absolute(0.0, 0.0)) + .child(canvas(disc_shape(4.0, GREEN)).size(16.0, 16.0).absolute(0.0, 0.0)); + col().size(120.0, 120.0).child( + col() + .key("stage") + .size(96.0, 96.0) + .scale(s.zoom) + .origin(0.0, 0.0) + .child(badge.absolute(14.15, 16.35)), + ) +} + +/// (2) Moving box (`offset_motion` spring): fill, icon and `canvas` shape keep the same centre +/// within `1/8 px` on every frame of a diagonal glide, at `1×` and `1.6×` zoom. +#[test] +fn concentric_icon_shape_and_fill_glide_together_during_motion() { + let mut bench = Bench::new(120, 120, 2.0); + for zoom in [1.0, 1.6] { + let mut rt = Runtime::new( + MovingCase { at: [0.0, 0.0], zoom }, + moving_view, + (120.0, 120.0), + Env::new(true, 2.0), + ); + rt.frame(0.0); + rt.frame(1.0 / 120.0); + rt.update(|s, _| s.at = [17.35, 13.65]); + + let mut max_icon_shape = 0.0f32; + let mut max_icon_fill = 0.0f32; + for f in 0..90 { + rt.frame(1.0 / 120.0); + let rgba = bench.draw(&mut rt, [0.0; 4]); + let (c_icon, _) = channel_moments(&rgba, bench.dw, bench.dh, 0); + let (c_shape, _) = channel_moments(&rgba, bench.dw, bench.dh, 1); + let (c_fill, _) = channel_moments(&rgba, bench.dw, bench.dh, 3); + let d_is = (c_icon[0] - c_shape[0]).abs().max((c_icon[1] - c_shape[1]).abs()); + let d_if = (c_icon[0] - c_fill[0]).abs().max((c_icon[1] - c_fill[1]).abs()); + max_icon_shape = max_icon_shape.max(d_is); + max_icon_fill = max_icon_fill.max(d_if); + assert!( + d_is <= 0.125 && d_if <= 0.125, + "zoom={zoom} frame={f}: icon={c_icon:?} shape={c_shape:?} fill={c_fill:?} (d_is={d_is:.4}, d_if={d_if:.4})" + ); + } + eprintln!( + "moving (zoom={zoom}): max |icon - shape| = {max_icon_shape:.4} px, max |icon - fill| = {max_icon_fill:.4} px" + ); + } +} + +#[derive(Clone, Copy)] +struct SwapCase { + swapped: bool, + disc_r: f32, +} + +fn swap_view(s: &SwapCase, _: &mut Cx<SwapCase>) -> El { + let page = col() + .key("page") + .size(120.0, 120.0) + .scale(1.6) + .origin(0.0, 0.0) + .child(el().key("anchor").absolute(12.2, 10.35).size(24.0, 8.0)); + let indicator = if s.swapped { + el().key("badge") + .size(16.0, 16.0) + .child(icon(&RING_ICON, 16.0).color(BLUE).absolute(0.0, 0.0)) + .child(icon(&DISC_ICON, 16.0).color(RED).absolute(0.0, 0.0)) + } else { + el().key("badge") + .size(16.0, 16.0) + .child(icon(&RING_ICON, 16.0).color(BLUE).absolute(0.0, 0.0)) + .child(canvas(disc_shape(s.disc_r, RED)).size(16.0, 16.0).absolute(0.0, 0.0)) + }; + let pop = col() + .key("pop") + .padding(6.15) + .child(indicator) + .anchored("anchor", Side::Bottom, Align::Start, 4.1); + col().size(160.0, 160.0).children([page, pop]) +} + +/// (3) Shape-to-icon swap: unmounting `canvas(Shape)` and mounting the matching `El::icon` in the +/// same `16 × 16 pt` box inside a `1.6×` anchored popover causes no centre jump (`<= 1/8 px`) and +/// no area drop (`< 1%`). +#[test] +fn swapping_canvas_shape_to_icon_keeps_centre_and_area_steady() { + let mut bench = Bench::new(160, 160, 2.0); + let mut rt = Runtime::new( + SwapCase { swapped: false, disc_r: 2.8 }, + swap_view, + (160.0, 160.0), + Env::new(true, 2.0), + ); + rt.frame(0.0); + + let mut centres = Vec::new(); + let mut areas = Vec::new(); + for f in 0..60 { + let u = (f as f32 / 30.0).clamp(0.0, 1.0); + let r = 2.8 + (4.0 - 2.8) * (1.0 - (1.0 - u).powi(3)); + let swapped = f >= 36; + rt.update(|s, _| { + s.disc_r = r; + s.swapped = swapped; + }); + rt.frame(1.0 / 120.0); + let rgba = bench.draw(&mut rt, [0.0; 4]); + let (c, area) = channel_moments(&rgba, bench.dw, bench.dh, 0); + centres.push(c); + areas.push(area); + } + + let before = centres[35]; + let after = centres[36]; + let jump_x = (after[0] - before[0]).abs(); + let jump_y = (after[1] - before[1]).abs(); + let area_rel = (areas[36] - areas[35]).abs() / areas[35]; + eprintln!( + "swap at 1.6x anchored: centre {before:?} -> {after:?} (jump=({jump_x:.4}, {jump_y:.4}) px), area {:.2} -> {:.2} (rel={area_rel:.4})", + areas[35], areas[36] + ); + assert!( + jump_x <= 0.125 && jump_y <= 0.125, + "shape->icon swap jumped in centre: {before:?} -> {after:?} ({jump_x:.4}, {jump_y:.4})" + ); + assert!( + area_rel < 0.01, + "shape->icon swap changed drawn area by {:.2}% ({:.2} -> {:.2})", + area_rel * 100.0, + areas[35], + areas[36] + ); + let c0 = centres[0]; + for (f, c) in centres.iter().enumerate() { + let dx = (c[0] - c0[0]).abs(); + let dy = (c[1] - c0[1]).abs(); + assert!(dx <= 0.125 && dy <= 0.125, "frame {f}: centre drifted from {c0:?} to {c:?}"); + } +} + +/// Large text (`24 pt` at `2×` = `48 ppem > 33⅓ ppem`, where resting CoreGraphics x quantisation +/// has only 1 step/px) glides horizontally in sub-pixel phases with its pixel-snapped card and +/// returns to exact resting instances once still. +#[test] +fn large_heading_glides_horizontally_within_a_phase() { + #[derive(Clone, Copy)] + struct HeadingCard { + x: f32, + } + fn view(s: &HeadingCard, _: &mut Cx<HeadingCard>) -> El { + el().size(280.0, 100.0).child( + col() + .absolute(20.0, 20.0) + .padding(10.0) + .fill(Color::WHITE.mix(Color::BLACK, 0.8)) + .offset(s.x, 0.0) + .offset_motion(Spring::new(0.35, 0.0)) + .child(text("Centered").font(TextStyle::new(24.0, 600.0)).color(Color::WHITE)), + ) + } + let ink_x = |rt: &Runtime<HeadingCard>| { + let size = crate::text::ATLAS_SIZE as usize; + let (mut sum, mut sx) = (0.0f64, 0.0f64); + for i in rt.instances.iter().filter(|i| i.params[1] == KIND_GLYPH) { + let data = rt.text.atlas.page_data(i.params[2] as usize).unwrap(); + let (u, v) = (i.uv[0] as usize, i.uv[1] as usize); + for y in 0..i.rect[3] as usize { + for x in 0..i.rect[2] as usize { + let c = data[(v + y) * size + u + x] as f64; + sum += c; + sx += c * (i.rect[0] as f64 + x as f64 + 0.5); + } + } + } + (sx / sum) as f32 + }; + + let mut rt = Runtime::new(HeadingCard { x: 0.0 }, view, (280.0, 100.0), Env::new(true, 2.0)); + rt.frame(0.0); + let glyphs = rt.instances.iter().filter(|i| i.params[1] == KIND_GLYPH).count(); + let masks0 = rt.text.atlas.glyph_entries(); + let (mut lo, mut hi) = (f32::MAX, f32::MIN); + for k in 1..=180 { + let t = k as f32 / 60.0; + let d = 2.5 * (0.5 - 0.5 * (std::f32::consts::TAU * t / 3.0).cos()); + rt.update(|s, _| s.x = d); + rt.frame(1.0 / 60.0); + let card_x = rt.instances.iter().find(|i| i.params[1] == KIND_RECT && i.fill[3] > 0.0).unwrap().rect[0]; + let off = ink_x(&rt) - card_x; + (lo, hi) = (lo.min(off), hi.max(off)); + } + let spread = hi - lo; + let added = rt.text.atlas.glyph_entries() - masks0; + assert!(spread <= 0.30, "48 ppem heading x-glide spread {spread:.3} px > 0.30 px"); + assert!(added <= glyphs * crate::text::GLIDE_PHASES as usize, "{added} masks for {glyphs} glyphs"); +} + +#[derive(Clone, Copy)] +struct ProofScene { + at: [f32; 2], + zoom: f32, + disc_r: f32, + swapped: bool, +} + +fn proof_view(s: &ProofScene, _: &mut Cx<ProofScene>) -> El { + let accent = Color { r: 0.96, g: 0.28, b: 0.24, a: 1.0 }; + let ring_col = Color { r: 0.92, g: 0.94, b: 0.98, a: 1.0 }; + let card_bg = Color { r: 0.08, g: 0.09, b: 0.12, a: 1.0 }; + let card_border = Color { r: 0.20, g: 0.23, b: 0.30, a: 1.0 }; + + let indicator = if s.swapped { + el().key("badge") + .size(16.0, 16.0) + .child(icon(&RING_ICON, 16.0).color(ring_col).absolute(0.0, 0.0)) + .child(icon(&DISC_ICON, 16.0).color(accent).absolute(0.0, 0.0)) + } else { + el().key("badge") + .size(16.0, 16.0) + .child(icon(&RING_ICON, 16.0).color(ring_col).absolute(0.0, 0.0)) + .child(canvas(disc_shape(s.disc_r, accent)).size(16.0, 16.0).absolute(0.0, 0.0)) + }; + + let page = col() + .key("page") + .size(90.0, 90.0) + .scale(s.zoom) + .scale_motion(Spring::new(0.42, 0.0)) + .origin(0.0, 0.0) + .child( + el().key("anchor") + .absolute(7.2, 4.35) + .offset(s.at[0], s.at[1]) + .offset_motion(Spring::new(0.55, 0.0)) + .size(20.0, 4.0), + ); + + let pop = row() + .key("pop") + .padding(7.15) + .gap(6.0) + .radius(8.0) + .fill(card_bg) + .border(1.0, card_border) + .child(indicator) + .anchored("anchor", Side::Bottom, Align::Start, 3.1); + + col().size(80.0, 80.0).children([page, pop]) +} + +/// Optional headless metric + frame exporter driven by `RUNE_ONE_SNAP_DUMP=<dir>` for generating +/// before/after proof clips and p95/max centre-offset tables without touching a real display. +#[test] +fn capture_one_snap_proof() { + let Some(dir) = std::env::var_os("RUNE_ONE_SNAP_DUMP") else { return }; + let dir = std::path::PathBuf::from(dir); + std::fs::create_dir_all(&dir).unwrap(); + + let mut bench160 = Bench::new(160, 160, 2.0); + let mut still_scaled_errs = Vec::new(); + let mut still_anchored_errs = Vec::new(); + let mut disc_icon_area = 0.0f32; + let mut disc_shape_area = 0.0f32; + + for anchored in [false, true] { + for iy in 0..5 { + for ix in 0..5 { + let at = [ix as f32 * 0.21, iy as f32 * 0.21]; + let mut rt = Runtime::new( + ScaledCase { at, zoom: 1.6, anchored, only_icon_disc: false }, + scaled_view, + (160.0, 160.0), + Env::new(true, 2.0), + ); + rt.frame(0.0); + rt.frame(1.0 / 120.0); + let rgba = bench160.draw(&mut rt, [0.0; 4]); + let (ci, _) = channel_moments(&rgba, bench160.dw, bench160.dh, 0); + let (cs, s_area) = channel_moments(&rgba, bench160.dw, bench160.dh, 1); + let dist = ((ci[0] - cs[0]).powi(2) + (ci[1] - cs[1]).powi(2)).sqrt(); + if anchored { + still_anchored_errs.push(dist); + } else { + still_scaled_errs.push(dist); + } + if anchored && ix == 1 && iy == 2 { + disc_shape_area = s_area; + let mut rt_disc = Runtime::new( + ScaledCase { at, zoom: 1.6, anchored: true, only_icon_disc: true }, + scaled_view, + (160.0, 160.0), + Env::new(true, 2.0), + ); + rt_disc.frame(0.0); + rt_disc.frame(1.0 / 120.0); + let rgba_d = bench160.draw(&mut rt_disc, [0.0; 4]); + disc_icon_area = channel_moments(&rgba_d, bench160.dw, bench160.dh, 0).1; + } + } + } + } + + let mut bench120 = Bench::new(120, 120, 2.0); + let mut moving_errs = Vec::new(); + let mut rt_move = Runtime::new( + MovingCase { at: [0.0, 0.0], zoom: 1.6 }, + moving_view, + (120.0, 120.0), + Env::new(true, 2.0), + ); + rt_move.frame(0.0); + rt_move.frame(1.0 / 120.0); + rt_move.update(|s, _| s.at = [17.35, 13.65]); + for _ in 0..90 { + rt_move.frame(1.0 / 120.0); + let rgba = bench120.draw(&mut rt_move, [0.0; 4]); + let (ci, _) = channel_moments(&rgba, bench120.dw, bench120.dh, 0); + let (cs, _) = channel_moments(&rgba, bench120.dw, bench120.dh, 1); + moving_errs.push(((ci[0] - cs[0]).powi(2) + (ci[1] - cs[1]).powi(2)).sqrt()); + } + + let mut rt_swap = Runtime::new( + SwapCase { swapped: false, disc_r: 2.8 }, + swap_view, + (160.0, 160.0), + Env::new(true, 2.0), + ); + rt_swap.frame(0.0); + let mut swap_centres = Vec::new(); + let mut swap_areas = Vec::new(); + for f in 0..60 { + let u = (f as f32 / 30.0).clamp(0.0, 1.0); + let r = 2.8 + (4.0 - 2.8) * (1.0 - (1.0 - u).powi(3)); + let swapped = f >= 36; + rt_swap.update(|s, _| { + s.disc_r = r; + s.swapped = swapped; + }); + rt_swap.frame(1.0 / 120.0); + let rgba = bench160.draw(&mut rt_swap, [0.0; 4]); + let (c, a) = channel_moments(&rgba, bench160.dw, bench160.dh, 0); + swap_centres.push(c); + swap_areas.push(a); + } + let swap_step_errs: Vec<f32> = swap_centres + .windows(2) + .map(|w| ((w[1][0] - w[0][0]).powi(2) + (w[1][1] - w[0][1]).powi(2)).sqrt()) + .collect(); + let swap_jump = swap_step_errs[35]; + + // Render 210 tightly-cropped 160×160 px frames of the 3-act visual sequence: + // 0..70: zoom 1.0 -> 1.6 while inner canvas disc pulses inside outer icon ring + // 70..130: held at 1.6x fractional offset; frame 100 swaps canvas disc -> icon disc + // 130..210: diagonal spring glide across subpixel offsets and settle + let mut bench_clip = Bench::new(80, 80, 2.0); + let mut rt_clip = Runtime::new( + ProofScene { at: [0.0, 0.0], zoom: 1.0, disc_r: 2.6, swapped: false }, + proof_view, + (80.0, 80.0), + Env::new(true, 2.0), + ); + rt_clip.frame(0.0); + for f in 0..210 { + rt_clip.update(|s, _| { + s.zoom = if f >= 4 { 1.6 } else { 1.0 }; + let u = ((f as f32 - 4.0) / 56.0).clamp(0.0, 1.0); + s.disc_r = 2.6 + (4.0 - 2.6) * (1.0 - (1.0 - u).powi(3)); + s.swapped = (100..150).contains(&f) || f >= 185; + if f == 130 { + s.at = [7.35, 6.65]; + } + }); + rt_clip.frame(1.0 / 120.0); + let rgba = bench_clip.draw(&mut rt_clip, [0.03, 0.035, 0.045, 1.0]); + write_png(&dir.join(format!("frame_{f:03}.png")), bench_clip.dw, bench_clip.dh, &rgba).unwrap(); + } + + let report = serde_json::json!({ + "still_scaled": { + "max_px": percentile(still_scaled_errs.clone(), 1.0), + "p95_px": percentile(still_scaled_errs.clone(), 0.95), + "median_px": percentile(still_scaled_errs, 0.50), + }, + "still_anchored": { + "max_px": percentile(still_anchored_errs.clone(), 1.0), + "p95_px": percentile(still_anchored_errs.clone(), 0.95), + "median_px": percentile(still_anchored_errs, 0.50), + }, + "moving": { + "max_px": percentile(moving_errs.clone(), 1.0), + "p95_px": percentile(moving_errs.clone(), 0.95), + "median_px": percentile(moving_errs, 0.50), + }, + "swap": { + "boundary_jump_px": swap_jump, + "max_step_px": percentile(swap_step_errs.clone(), 1.0), + "p95_step_px": percentile(swap_step_errs, 0.95), + "shape_area_px": swap_areas[35], + "icon_area_px": swap_areas[36], + "disc_shape_area_px": disc_shape_area, + "disc_icon_area_px": disc_icon_area, + } + }); + std::fs::write(dir.join("metrics.json"), serde_json::to_string_pretty(&report).unwrap()).unwrap(); +} diff --git a/app/vendor/rune/crates/rune/src/runtime/tests/picture_scale.rs b/app/vendor/rune/crates/rune/src/runtime/tests/picture_scale.rs new file mode 100644 index 0000000..e25d57a --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/tests/picture_scale.rs @@ -0,0 +1,420 @@ +use super::*; + + +#[test] +fn text_inside_a_scale_draws_at_that_size() { + #[derive(Clone, Copy, PartialEq)] + enum How { Static, Live, Press } + struct State { k: f32, how: How, pressed: u32 } + fn view(s: &State, _: &mut Cx<State>) -> El { + let label = crate::el::text("Hamburgefonstiv").key("label"); + let card = el().key("card").size(200.0, 80.0).on_press(|s: &mut State| s.pressed += 1).child(label); + let card = match s.how { + How::Static => card.scale(s.k), + How::Live => card.live_scale(&crate::live::Live::new(s.k)), + How::Press => card.press_scale(s.k), + }; + col().size(300.0, 200.0).child(card) + } + // Device px: the glyphs' bounding box, and whether all of them sample their atlas 1:1 + // (neither filtered atlas masks nor moving outline glyphs). + fn glyphs(rt: &Runtime<State>) -> ([f32; 4], bool) { + let gs: Vec<_> = rt.instances.iter().filter(|q| q.params[1] == KIND_GLYPH).collect(); + assert!(gs.len() >= 10, "the label draws its glyphs"); + let b = gs.iter().fold([f32::MAX, f32::MAX, f32::MIN, f32::MIN], |b, q| { + [b[0].min(q.rect[0]), b[1].min(q.rect[1]), b[2].max(q.rect[0] + q.rect[2]), b[3].max(q.rect[1] + q.rect[3])] + }); + (b, gs.iter().all(|q| q.uv[2] == 0.0 && q.radii[3] == 0.0)) + } + let run = |k: f32, how: How| { + let mut rt = Runtime::new(State { k, how, pressed: 0 }, view, (300.0, 200.0), Env::new(true, 2.0)); + rt.frame(0.0); + rt.frame(1.0 / 120.0); + rt + }; + let (rest, _) = glyphs(&run(1.0, How::Static)); + let (w, h) = (rest[2] - rest[0], rest[3] - rest[1]); + // The card's centre in device px, which the scale is about. + let c = [200.0, 80.0]; + for how in [How::Static, How::Live] { + let rt = run(0.5, how); + let (half, crisp) = glyphs(&rt); + let (hw, hh) = (half[2] - half[0], half[3] - half[1]); + // Windfoil mask quads include a fixed 3–4 px vertical apron (1 px either side plus the + // y-glide row) that does not shrink with scale, so at 0.5x `hh` sits ~2 px above `h / 2`. + assert!((hw / w - 0.5).abs() < 0.03 && (hh - h * 0.5).abs() <= 2.5, "glyphs draw at half size: {hw}x{hh} vs {w}x{h}"); + for axis in 0..2 { + let want = c[axis] + (rest[axis] - c[axis]) * 0.5; + assert!((half[axis] - want).abs() < 1.5, "about the card's centre: {} vs {want}", half[axis]); + } + assert!(crisp, "a still scale rasterizes at the scaled size"); + } + + // Static scale needs no layout change, and hits follow the drawn rect: 50..150 x 20..60. + let mut rt = run(0.5, How::Static); + let card = rt.elements().into_iter().find(|e| e.key.as_deref() == Some("card")).unwrap(); + assert_eq!(card.target, [0.0, 0.0, 200.0, 80.0], "layout keeps the unscaled size"); + assert!((card.rect[0] - 50.0).abs() < 0.05 && (card.rect[2] - 100.0).abs() < 0.05, "drawn about its centre: {:?}", card.rect); + for (x, hit) in [(20.0, 0), (100.0, 1)] { + rt.pointer_move(x, 40.0); + rt.pointer_down(x, 40.0); + rt.pointer_up(x, 40.0); + rt.frame(1.0 / 120.0); + assert_eq!(rt.state.pressed, hit, "a press at x {x}"); + } + + // A press scale's text shrinks too; while it springs back, it samples rest-size glyphs. + let mut rt = run(0.9, How::Press); + rt.pointer_move(100.0, 40.0); + rt.pointer_down(100.0, 40.0); + for _ in 0..30 { rt.frame(1.0 / 120.0); } + let (held, crisp) = glyphs(&rt); + assert!(((held[2] - held[0]) / w - 0.9).abs() < 0.02, "held text is 90%: {held:?}"); + assert!(crisp, "the held size rasterizes crisp"); + rt.pointer_up(100.0, 40.0); + rt.frame(1.0 / 120.0); + let (moving, crisp) = glyphs(&rt); + let mw = (moving[2] - moving[0]) / w; + assert!(mw > 0.9 && mw < 1.0, "springing back: {mw}"); + assert!(!crisp, "a moving scale samples its rest-size glyphs"); + for _ in 0..120 { rt.frame(1.0 / 120.0); } + assert_eq!(glyphs(&rt), (rest, true), "back at rest exactly as before"); +} + +#[test] +fn nested_scales_compose_about_each_mapped_centre() { + #[derive(Clone, Copy, PartialEq, Debug)] + enum How { Press, Static, ProductOfOne, ThreeLevels } + struct State { how: How, pressed: u32 } + fn view(s: &State, _: &mut Cx<State>) -> El { + let leaf = el().key("c").size(40.0, 40.0).on_press(|s: &mut State| s.pressed += 1); + let inner = match s.how { + How::Press => leaf.press_scale(0.96), + How::Static => leaf.scale(0.8), + How::ProductOfOne => leaf.scale(2.0), + How::ThreeLevels => el().key("mid").size(100.0, 100.0).items_start() + .live_scale(&crate::live::Live::new(0.8)).child(leaf.press_scale(0.9)), + }; + col().size(400.0, 400.0).items_start() + .child(el().key("p").size(200.0, 200.0).items_start().scale(0.5).child(inner)) + } + let edges = |rt: &Runtime<State>| { + let r = rt.elements().into_iter().find(|e| e.key.as_deref() == Some("c")).unwrap().rect; + [r[0], r[1], r[0] + r[2], r[1] + r[3]] + }; + let near = |a: [f32; 4], b: [f32; 4]| a.iter().zip(b).all(|(a, b)| (a - b).abs() < 0.3); + let run = |how| { + let mut rt = Runtime::new(State { how, pressed: 0 }, view, (400.0, 400.0), Env::new(true, 2.0)); + rt.frame(0.0); + rt.frame(1.0 / 120.0); + rt + }; + let press = |rt: &mut Runtime<State>, x: f32, y: f32| { + rt.pointer_move(x, y); + rt.pointer_down(x, y); + rt.pointer_up(x, y); + rt.frame(1.0 / 120.0); + }; + // The parent draws [50, 50, 150, 150]; the child's centre (20, 20) lands at (60, 60). + for (how, rest, held) in [ + (How::Press, [50.0, 50.0, 70.0, 70.0], Some([50.4, 50.4, 69.6, 69.6])), + (How::Static, [52.0, 52.0, 68.0, 68.0], None), + // 0.5 × 2.0 is 1, but the child still moves with its parent. + (How::ProductOfOne, [40.0, 40.0, 80.0, 80.0], None), + // The middle level draws [50, 50, 90, 90] at 0.4, putting the child's centre at 63. + (How::ThreeLevels, [55.0, 55.0, 71.0, 71.0], Some([55.8, 55.8, 70.2, 70.2])), + ] { + let mut rt = run(how); + assert!(near(edges(&rt), rest), "{how:?} at rest: {:?} vs {rest:?}", edges(&rt)); + press(&mut rt, rest[0] - 1.0, rest[1] - 1.0); + press(&mut rt, rest[0] + 1.0, rest[1] + 1.0); + assert_eq!(rt.state.pressed, 1, "{how:?}: hits follow the drawn rect"); + let Some(held) = held else { continue }; + let (cx, cy) = ((rest[0] + rest[2]) * 0.5, (rest[1] + rest[3]) * 0.5); + rt.pointer_move(cx, cy); + rt.pointer_down(cx, cy); + for _ in 0..30 { rt.frame(1.0 / 120.0); } + assert!(near(edges(&rt), held), "{how:?} held: {:?} vs {held:?}", edges(&rt)); + // Still hit at its resting size: a release just inside its resting corner presses. + rt.pointer_up(rest[2] - 0.2, rest[3] - 0.2); + rt.frame(1.0 / 120.0); + assert_eq!(rt.state.pressed, 2, "{how:?}: a held press hits at the resting rect"); + } +} + +#[test] +fn a_changing_static_scale_keeps_the_glyph_atlas_bounded() { + struct State { k: f32 } + fn view(s: &State, _: &mut Cx<State>) -> El { + col().size(300.0, 200.0) + .child(el().key("card").size(200.0, 80.0).scale(s.k).scale_motion(rune_motion::Curve::Instant) + .child(crate::el::text("Hamburgefonstiv"))) + } + let crisp = |rt: &Runtime<State>| rt.instances.iter().filter(|q| q.params[1] == KIND_GLYPH).all(|q| q.uv[2] == 0.0 && q.radii[3] == 0.0); + let mut rt = Runtime::new(State { k: 1.0 }, view, (300.0, 200.0), Env::new(true, 2.0)); + rt.frame(0.0); + let rest = rt.text.atlas.glyph_entries(); + // A slider or pinch: a new scale every frame, holding still now and then. + for i in 0..1000 { + rt.state.k = 0.5 + i as f32 * 0.0007; + rt.invalidate(); + rt.frame(1.0 / 120.0); + assert!(i == 0 || !crisp(&rt), "a scale changing every frame samples rest-size glyphs"); + if i % 100 == 99 { for _ in 0..30 { rt.frame(1.0 / 120.0); } } + } + let grown = rt.text.atlas.glyph_entries() - rest; + assert!(grown < 1000, "1,000 scales added {grown} glyph entries (one size each would add 15,000)"); + rt.state.k = 0.75; + rt.invalidate(); + rt.frame(1.0 / 120.0); + assert!(!crisp(&rt)); + for _ in 0..30 { rt.frame(1.0 / 120.0); } + assert!(crisp(&rt), "once it holds still, text rasterizes at the scale"); + assert!(!rt.frame(1.0 / 120.0), "and nothing keeps animating"); +} + +#[test] +fn a_held_press_scale_keeps_its_hover_and_a_scroll_cancels_it() { + struct State { pressed: Vec<usize> } + fn view(_: &State, _: &mut Cx<State>) -> El { + let mut list = col().key("list").w_full(); + for i in 0..10 { + list = list.child(el().key(format!("b{i}")).size(200.0, 40.0).hover(crate::color::oklcha(1.0, 0.0, 0.0, 0.1)) + .press_scale(0.96).on_press(move |s: &mut State| s.pressed.push(i))); + } + col().size(200.0, 200.0).child(col().key("scroll").size(200.0, 200.0).scroll(ScrollSpec { stick_bottom: false }).child(list)) + } + let mut rt = Runtime::new(State { pressed: Vec::new() }, view, (200.0, 200.0), Env::new(true, 2.0)); + rt.frame(0.0); + let id = rt.tree.nodes.iter().find(|n| n.key.as_deref() == Some("b0")).unwrap().id; + // Held at its right edge, which the shrunk row no longer covers: still hovered. + rt.pointer_move(199.0, 20.0); + rt.pointer_down(199.0, 20.0); + for _ in 0..30 { rt.frame(1.0 / 120.0); } + assert_eq!(rt.scene.get(id, P_PRESS_SCALE), Some(0.96)); + assert_eq!(rt.scene.get(id, P_HOVER), Some(1.0), "the held row keeps its highlight"); + rt.pointer_up(199.0, 20.0); + rt.frame(1.0 / 120.0); + assert_eq!(rt.state.pressed, [0]); + + // Scrolling under a held press cancels it: the row lets go, and the release presses nothing. + for _ in 0..60 { rt.frame(1.0 / 120.0); } + rt.pointer_move(100.0, 20.0); + rt.pointer_down(100.0, 20.0); + for _ in 0..10 { rt.frame(1.0 / 120.0); } + assert!(rt.scene.get(id, P_PRESS_SCALE).unwrap() < 0.97, "held"); + rt.wheel(100.0, 100.0, -120.0); + for _ in 0..60 { rt.frame(1.0 / 120.0); } + assert!((rt.scene.get(id, P_PRESS_SCALE).unwrap() - 1.0).abs() < 1e-3, "the scrolled-away row springs back"); + rt.pointer_up(100.0, 20.0); + rt.frame(1.0 / 120.0); + assert_eq!(rt.state.pressed, [0], "a scroll cancels the press"); + // A fling does too. + rt.pointer_move(100.0, 20.0); + rt.pointer_down(100.0, 20.0); + rt.fling(100.0, 100.0, 600.0); + rt.pointer_up(100.0, 20.0); + rt.frame(1.0 / 120.0); + assert_eq!(rt.state.pressed, [0]); +} + +#[test] +fn press_scale_shrinks_while_held_and_springs_back() { + struct State { pressed: u32, reduced: bool } + fn view(s: &State, cx: &mut Cx<State>) -> El { + cx.reduced_motion(s.reduced); + col().size(200.0, 200.0).child(el().key("tile").size(100.0, 100.0).press_scale(0.96) + .on_press(|s: &mut State| s.pressed += 1) + .child(el().key("dot").size(10.0, 10.0))) + } + fn info(rt: &Runtime<State>, key: &str) -> ElementInfo { + rt.elements().into_iter().find(|e| e.key.as_deref() == Some(key)).unwrap() + } + let settle = |rt: &mut Runtime<State>| for _ in 0..90 { rt.frame(1.0 / 120.0); }; + let mut rt = Runtime::new(State { pressed: 0, reduced: false }, view, (200.0, 200.0), Env::new(true, 1.0)); + rt.frame(0.0); + let rest = info(&rt, "tile"); + assert_eq!(rest.scale, 1.0); + // Near the right edge, which the shrunken tile no longer covers. + rt.pointer_move(99.0, 50.0); + rt.pointer_down(99.0, 50.0); + settle(&mut rt); + let held = info(&rt, "tile"); + assert!((held.scale - 0.96).abs() < 1e-4, "held scale {}", held.scale); + assert_eq!(held.target, rest.target, "layout keeps the resting size"); + assert!((held.rect[0] - 2.0).abs() < 0.05 && (held.rect[2] - 96.0).abs() < 0.05, "shrinks about its centre: {:?}", held.rect); + assert!((info(&rt, "dot").scale - 0.96).abs() < 1e-4, "children shrink with it"); + assert!(rt.pointer.press_inside(), "a press near the edge stays inside the resting rect"); + rt.pointer_move(150.0, 50.0); + settle(&mut rt); + assert!((info(&rt, "tile").scale - 1.0).abs() < 1e-4, "leaving springs back"); + rt.pointer_move(99.0, 50.0); + rt.frame(1.0 / 120.0); + let returning = info(&rt, "tile").scale; + assert!(returning < 1.0 && returning > 0.96, "re-entering shrinks again, from where it was: {returning}"); + settle(&mut rt); + rt.pointer_up(99.0, 50.0); + rt.frame(1.0 / 120.0); + assert_eq!(rt.state.pressed, 1); + let mut last = info(&rt, "tile").scale; + assert!(last > 0.96 && last < 1.0, "the release springs, not jumps: {last}"); + let mut peak: f32 = last; + for _ in 0..90 { + rt.frame(1.0 / 120.0); + let s = info(&rt, "tile").scale; + assert!((s - last).abs() < 0.01, "no frame jumps more than 1%: {last} -> {s}"); + peak = peak.max(s); + last = s; + } + assert!((last - 1.0).abs() < 1e-4, "settles at rest: {last}"); + assert!(peak > 1.0, "the release has a little bounce: {peak}"); + + let mut reduced = Runtime::new(State { pressed: 0, reduced: true }, view, (200.0, 200.0), Env::new(true, 1.0)); + reduced.frame(0.0); + reduced.pointer_move(50.0, 50.0); + reduced.pointer_down(50.0, 50.0); + settle(&mut reduced); + assert_eq!(info(&reduced, "tile").scale, 1.0, "Reduce Motion turns press scale off"); +} + +/// A picture with one side set takes the other from its image, as SwiftUI's +/// `.resizable().aspectRatio(contentMode:)` does; both sides set keep the box. +#[test] +fn a_picture_with_one_side_sizes_the_other_from_its_image() { + use crate::Pixels; + use crate::SurfaceFit::{Fill, Fit}; + fn view(p: &Pixels, _: &mut Cx<Pixels>) -> El { + crate::col().w(240.0).items_start() + .child(el().key("w").w(120.0).pixels(p)) + .child(el().key("h").h(30.0).pixels_fit(p, Fit)) + .child(el().key("full").w_full().pixels_fit(p, Fill)) + .child(el().key("box").size(100.0, 100.0).pixels_fit(p, Fit)) + .child(el().key("neither").pixels(p)) + .child(el().key("explicit").w(120.0).aspect_ratio(4.0).pixels(p)) + .child(el().key("plain").h(25.0).aspect_ratio(2.0)) + } + let size = |rt: &Runtime<Pixels>, key: &str| { + let e = rt.elements().into_iter().find(|e| e.key.as_deref() == Some(key)).unwrap(); + [e.target[2], e.target[3]] + }; + let px = Pixels::new(); + let mut rt = Runtime::new(px.clone(), view, (240.0, 600.0), Env::new(true, 1.0)); + rt.frame(0.0); + assert_eq!(size(&rt, "w"), [120.0, 0.0], "an empty (still decoding) image has no ratio yet"); + assert_eq!(size(&rt, "explicit"), [120.0, 30.0]); + assert_eq!(size(&rt, "plain"), [50.0, 25.0], "any box can set a ratio"); + + // The image arrives without the view re-running, as a decode completing does. + px.set(4, 2, vec![255; 4 * 4 * 2]); + rt.frame(1.0 / 120.0); + assert_eq!(size(&rt, "w"), [120.0, 60.0]); + assert_eq!(size(&rt, "h"), [60.0, 30.0]); + assert_eq!(size(&rt, "full"), [240.0, 120.0]); + assert_eq!(size(&rt, "box"), [100.0, 100.0], "a fixed box keeps its size and letterboxes"); + assert_eq!(size(&rt, "neither"), [0.0, 0.0], "a picture with no side set is unchanged"); + assert_eq!(size(&rt, "explicit"), [120.0, 30.0], "an explicit ratio wins"); + assert!(!rt.elements().iter().any(|e| e.moving), "the new shape lands without animating"); + + px.set(2, 4, vec![255; 4 * 2 * 4]); + rt.frame(1.0 / 120.0); + assert_eq!(size(&rt, "w"), [120.0, 240.0], "a stream that changes shape relays out"); + let commits = rt.commit.commits; + for _ in 0..4 { rt.frame(1.0 / 120.0); } + assert_eq!(rt.commit.commits, commits, "an unchanged image costs no commits"); + + // The image lands on a frame that also re-runs the view (`Pixels::set`, then the + // handle's `update`, or a hover that frame): it still appears at its size. + let px = Pixels::new(); + let mut rt = Runtime::new(px.clone(), view, (240.0, 600.0), Env::new(true, 1.0)); + rt.frame(0.0); + px.set(4, 2, vec![255; 4 * 4 * 2]); + rt.invalidate(); + rt.frame(1.0 / 120.0); + let w = rt.elements().into_iter().find(|e| e.key.as_deref() == Some("w")).unwrap(); + assert_eq!((w.rect[3], w.target[3]), (60.0, 60.0), "drawn at its size, not springing open"); + assert!(!w.moving); +} + +/// A decode or stream landing after this frame read the picture's size still gets a frame +/// that sizes it, though the frame latched live values after the set. +#[test] +fn a_picture_set_mid_frame_wakes_another_frame_to_size_it() { + use crate::Pixels; + fn view(p: &Pixels, _: &mut Cx<Pixels>) -> El { + col().w(240.0).items_start().child(el().key("w").w(120.0).pixels(p)) + } + let height = |rt: &Runtime<Pixels>| rt.elements().into_iter().find(|e| e.key.as_deref() == Some("w")).unwrap().target[3]; + let px = Pixels::new(); + let mut rt = Runtime::new(px.clone(), view, (240.0, 600.0), Env::new(true, 1.0)); + let wakes = counting_waker(&mut rt); + rt.frame(0.0); + assert_eq!(height(&rt), 0.0); + + let set = px.clone(); + MID_FRAME.with(|hook| *hook.borrow_mut() = Some(Box::new(move || set.set(4, 2, vec![255; 4 * 4 * 2])))); + assert!(!rt.frame(1.0 / 120.0)); + assert_eq!(wakes.load(std::sync::atomic::Ordering::Relaxed), 1); + assert!(rt.live_pending(), "the set's wake outlives the frame it landed in"); + rt.frame(1.0 / 120.0); + assert_eq!(height(&rt), 60.0); + assert!(!rt.live_pending()); +} + +fn counting_waker<S: 'static>(rt: &mut Runtime<S>) -> Arc<std::sync::atomic::AtomicUsize> { + let wakes = Arc::new(std::sync::atomic::AtomicUsize::new(0)); + let count = wakes.clone(); + rt.set_live_waker(Arc::new(move || { count.fetch_add(1, std::sync::atomic::Ordering::Relaxed); })); + wakes +} + +#[test] +fn a_picture_removed_outright_stops_waking_in_the_frame_that_removes_it() { + use crate::Pixels; + fn view(s: &(Pixels, bool), _: &mut Cx<(Pixels, bool)>) -> El { + let root = el().size(8.0, 8.0); + if s.1 { root.child(el().key("pic").size(4.0, 4.0).pixels(&s.0)) } else { root } + } + let px = Pixels::new(); + let mut rt = Runtime::new((px.clone(), true), view, (8.0, 8.0), Env::new(true, 1.0)); + let wakes = counting_waker(&mut rt); + rt.frame(0.0); + rt.update(|s, tx| { s.1 = false; tx.settle(); }); + let set = px.clone(); + MID_FRAME.with(|hook| *hook.borrow_mut() = Some(Box::new(move || set.set(1, 1, vec![255; 4])))); + rt.frame(0.0); + assert_eq!(wakes.load(std::sync::atomic::Ordering::Relaxed), 0, "unmounted before the set"); + assert!(!rt.live_pending()); +} + +/// Everything an exit still draws keeps updating: an exiting picture and a picture inside +/// an exiting element both wake until the exit ends. +#[test] +fn pictures_in_an_exit_wake_until_it_ends() { + use crate::Pixels; + use std::sync::atomic::Ordering::Relaxed; + type State = (Pixels, Pixels, bool); + fn view(s: &State, _: &mut Cx<State>) -> El { + let root = el().size(20.0, 20.0); + if !s.2 { return root; } + root.child(el().key("direct").size(4.0, 4.0).pixels(&s.0).transition(Transition::opacity())) + .child(el().key("card").size(8.0, 8.0).transition(Transition::opacity()) + .child(el().key("child").size(4.0, 4.0).pixels(&s.1))) + } + let (direct, child) = (Pixels::new(), Pixels::new()); + let mut rt = Runtime::new((direct.clone(), child.clone(), true), view, (20.0, 20.0), Env::new(true, 1.0)); + let wakes = counting_waker(&mut rt); + rt.frame(0.0); + rt.update(|s, _| s.2 = false); + assert!(rt.frame(0.0), "the exit runs"); + direct.set(1, 1, vec![1; 4]); + assert_eq!(wakes.load(Relaxed), 1, "an exiting picture wakes"); + rt.frame(1.0 / 120.0); + child.set(1, 1, vec![1; 4]); + assert_eq!(wakes.load(Relaxed), 2, "a picture inside an exiting element wakes"); + for _ in 0..240 { if !rt.frame(1.0 / 120.0) { break; } } + assert!(!rt.elements().iter().any(|e| e.key.as_deref() == Some("child")), "the exit ended"); + direct.set(1, 1, vec![2; 4]); + child.set(1, 1, vec![2; 4]); + assert_eq!(wakes.load(Relaxed), 2, "gone pictures stay asleep"); + assert!(!rt.live_pending()); +} diff --git a/app/vendor/rune/crates/rune/src/runtime/tests/pointer_drag.rs b/app/vendor/rune/crates/rune/src/runtime/tests/pointer_drag.rs new file mode 100644 index 0000000..701eb99 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/tests/pointer_drag.rs @@ -0,0 +1,607 @@ +use super::*; + + +#[test] +fn a_drag_reports_pointer_travel_when_its_window_moves() { + type State = Vec<(f32, f32)>; + fn view(_: &State, _: &mut Cx<State>) -> El { + el().key("pill").size(100.0, 40.0).on_drag(|s: &mut State, d, _| s.push((d.dx, d.dy))) + } + let mut rt = Runtime::new(Vec::new(), view, (200.0, 200.0), Env::new(true, 1.0)); + rt.frame(0.0); + rt.pointer_move(10.0, 10.0); + rt.pointer_down(10.0, 10.0); + rt.pointer_move(40.0, 14.0); + rt.window_moved(30.0, 4.0); + rt.pointer_move(15.0, 10.0); + rt.pointer_up(15.0, 10.0); + rt.frame(0.0); + assert_eq!(rt.state.last(), Some(&(35.0, 4.0)), "travel is measured on screen, not in the moving window"); + assert!(rt.state.contains(&(30.0, 4.0))); +} + +#[test] +fn taking_the_pointer_away_ends_a_held_drag_cancelled() { + type State = Vec<(Phase, bool)>; + fn view(_: &State, _: &mut Cx<State>) -> El { + el().key("pill").size(100.0, 40.0).on_drag(|s: &mut State, d, _| s.push((d.phase, d.cancelled()))) + } + let mut rt = Runtime::new(Vec::new(), view, (200.0, 200.0), Env::new(true, 1.0)); + rt.frame(0.0); + rt.pointer_down(10.0, 10.0); + rt.pointer_move(40.0, 10.0); + rt.cancel_pointer(); + rt.frame(0.0); + assert_eq!(rt.state.last(), Some(&(Phase::Up, true))); + rt.pointer_up(40.0, 10.0); + rt.frame(0.0); + assert_eq!(rt.state.iter().filter(|d| d.0 == Phase::Up).count(), 1, "the release after it does nothing"); +} + +#[derive(Default)] +struct LostRelease { drags: Vec<(Phase, bool, f32)>, presses: u32 } + +fn lost_release_view(_: &LostRelease, _: &mut Cx<LostRelease>) -> El { + el().key("pill").size(100.0, 40.0) + .on_drag(|s: &mut LostRelease, d, _| s.drags.push((d.phase, d.cancelled(), d.x))) + .on_press(|s: &mut LostRelease| s.presses += 1) +} + +#[test] +fn a_lost_release_cancels_a_held_drag_where_the_button_rose() { + let mut rt = Runtime::new(LostRelease::default(), lost_release_view, (200.0, 200.0), Env::new(true, 1.0)); + rt.frame(0.0); + rt.pointer_down(10.0, 10.0); + rt.pointer_move(40.0, 10.0); + rt.pointer_release_lost(60.0, 10.0); + rt.frame(0.0); + assert!(!rt.pointer_captured()); + assert_eq!(rt.pointer(), Some((60.0, 10.0))); + assert_eq!(rt.state.drags.last(), Some(&(Phase::Up, true, 60.0))); + assert_eq!(rt.state.presses, 0, "a press whose release was lost clicks nothing when it dragged"); + rt.pointer_up(60.0, 10.0); + rt.frame(0.0); + assert_eq!(rt.state.drags.iter().filter(|d| d.0 == Phase::Up).count(), 1, "a late Up does nothing"); +} + +#[test] +fn a_lost_release_before_the_next_press_leaves_that_press_alone() { + let mut rt = Runtime::new(LostRelease::default(), lost_release_view, (200.0, 200.0), Env::new(true, 1.0)); + rt.frame(0.0); + rt.pointer_down(10.0, 10.0); + rt.pointer_release_lost(10.0, 10.0); + rt.pointer_down(20.0, 10.0); + assert!(rt.pointer_captured(), "the new press holds"); + rt.pointer_up(20.0, 10.0); + rt.frame(0.0); + let ups: Vec<_> = rt.state.drags.iter().filter(|d| d.0 == Phase::Up).map(|d| d.1).collect(); + assert_eq!(ups, [true, false], "the old drag is cancelled, the new one ends normally"); +} + +type ClickRun = Vec<(Phase, u32)>; + +fn click_run_runtime() -> Runtime<ClickRun> { + fn view(_: &ClickRun, _: &mut Cx<ClickRun>) -> El { + el().size(100.0, 40.0).on_drag(|s: &mut ClickRun, d, _| s.push((d.phase, d.clicks))) + } + let mut rt = Runtime::new(Vec::new(), view, (200.0, 200.0), Env::new(true, 1.0)); + rt.frame(0.0); + rt +} + +#[test] +fn a_lost_release_that_moved_ends_the_run_of_clicks() { + // (seen moving to, released at, the next press's count) + for (seen, released, clicks) in [(Some(40.0), 40.0, 1), (Some(40.0), 10.0, 1), (None, 40.0, 1), (None, 12.0, 2), (None, 10.0, 2)] { + let mut rt = click_run_runtime(); + rt.pointer_down(10.0, 10.0); + if let Some(x) = seen { rt.pointer_move(x, 10.0); } + rt.pointer_release_lost(released, 10.0); + rt.pointer_down(10.0, 10.0); + rt.frame(0.0); + assert_eq!(rt.state.last(), Some(&(Phase::Down, clicks)), "moved to {seen:?}, released at {released}"); + } +} + +#[test] +fn a_stationary_escape_keeps_the_run_of_clicks() { + let mut rt = click_run_runtime(); + rt.pointer_down(10.0, 10.0); + rt.physical_key_input(crate::PhysicalInput::Key { key: crate::PhysicalKeyCode::Escape, + mods: crate::Mods::default(), pressed: true, repeat: false }, KeyEvent { key: crate::Key::Escape, mods: crate::Mods::default() }, None); + rt.pointer_up(10.0, 10.0); + rt.pointer_down(10.0, 10.0); + rt.frame(0.0); + assert_eq!(rt.state.last(), Some(&(Phase::Down, 2))); +} + +#[test] +fn a_lost_release_without_a_drag_still_releases_the_press() { + fn view(_: &u32, _: &mut Cx<u32>) -> El { el().size(100.0, 40.0).on_press(|n: &mut u32| *n += 1) } + let mut rt = Runtime::new(0, view, (200.0, 200.0), Env::new(true, 1.0)); + rt.frame(0.0); + rt.pointer_down(10.0, 10.0); + rt.pointer_release_lost(10.0, 10.0); + rt.frame(0.0); + assert!(!rt.pointer_captured()); + assert_eq!(rt.state, 1); +} + +#[test] +fn native_escape_with_a_logical_fallback_cancels_the_drag() { + fn view(_: &Vec<bool>, _: &mut Cx<Vec<bool>>) -> El { + el().size(100.0, 100.0).on_drag(|s: &mut Vec<bool>, d, _| { + if d.phase == Phase::Up { s.push(d.cancelled()); } + }) + } + let mut rt = Runtime::new(Vec::new(), view, (200.0, 200.0), Env::new(true, 1.0)); + rt.frame(0.0); + rt.pointer_down(10.0, 10.0); + rt.frame(0.0); + rt.physical_key_input(crate::PhysicalInput::Key { key: crate::PhysicalKeyCode::Escape, + mods: crate::Mods::default(), pressed: true, repeat: false }, KeyEvent { key: crate::Key::Escape, mods: crate::Mods::default() }, None); + rt.frame(0.0); + assert_eq!(rt.state, [true]); + rt.pointer_up(10.0, 10.0); + rt.frame(0.0); + assert_eq!(rt.state, [true]); +} + +#[derive(Default)] +struct DragOutState { presses: u32, drags: u32, offer: bool, ended: Vec<crate::DragOutcome>, dragging: bool, starts: u32, log: Vec<String> } + +fn drag_out_view(_: &DragOutState, _: &mut Cx<DragOutState>) -> El { + col().size(200.0, 200.0).child(el().key("file").size(100.0, 40.0) + .on_press(|s: &mut DragOutState| s.presses += 1) + .on_drag(|s: &mut DragOutState, _, _| s.drags += 1) + .drag_out(|s: &DragOutState| s.offer.then(|| crate::DragItem::new().file("/Applications/Example.app"))) + .on_drag_start(|s: &mut DragOutState, _| { s.dragging = true; s.starts += 1; s.log.push("start".into()); }) + .on_drag_end(|s: &mut DragOutState, outcome, _| { s.dragging = false; s.ended.push(outcome); s.log.push(format!("end {outcome:?}")); })) +} + +fn drag_out_rt(offer: bool) -> Runtime<DragOutState> { + let mut rt = Runtime::new(DragOutState { offer, ..Default::default() }, drag_out_view, (200.0, 200.0), Env::new(true, 1.0)); + rt.frame(0.0); + rt.pointer_move(10.0, 10.0); + rt.pointer_down(10.0, 10.0); + rt +} + +#[test] +fn crossing_the_threshold_hands_a_drag_out_to_the_host_and_releases_the_pointer() { + let mut rt = drag_out_rt(true); + let t = crate::drag_out::DRAG_THRESHOLD; + rt.pointer_move(10.0 + t, 10.0); + assert!(rt.take_drag_out().is_none(), "at the threshold it's still a press"); + assert!(rt.pointer_captured()); + rt.pointer_move(12.0 + t, 10.0); + let start = rt.take_drag_out().expect("drag-out requested"); + assert_eq!(start.item.paths(), [std::path::PathBuf::from("/Applications/Example.app")]); + assert_eq!(start.press, (10.0, 10.0)); + assert_eq!(start.rect, [0.0, 0.0, 100.0, 40.0]); + assert!(rt.events.iter().any(|e| e.starts_with("drag-out ") && e.ends_with("file")), "{:?}", rt.events); + assert!(!rt.pointer_captured() && rt.pointer().is_none(), "nothing stays pressed or hovered"); + rt.pointer_move(40.0, 30.0); + assert!(rt.take_drag_out().is_none(), "one request per press"); + rt.pointer_up(40.0, 30.0); + rt.frame(0.0); + assert_eq!((rt.state.presses, rt.state.drags), (0, 0), "neither on_press nor on_drag runs"); +} + +#[test] +fn an_element_sets_its_own_drag_threshold() { + fn view(_: &DragOutState, _: &mut Cx<DragOutState>) -> El { + col().size(200.0, 200.0) + .child(el().key("near").size(100.0, 40.0).drag_threshold(3.0) + .drag_out(|_: &DragOutState| Some(crate::DragItem::new().text("near")))) + .child(el().key("far").size(100.0, 40.0).drag_threshold(12.0) + .drag_out(|_: &DragOutState| Some(crate::DragItem::new().text("far")))) + } + let mut rt = Runtime::new(DragOutState::default(), view, (200.0, 200.0), Env::new(true, 1.0)); + rt.frame(0.0); + rt.pointer_move(10.0, 10.0); + rt.pointer_down(10.0, 10.0); + rt.pointer_move(13.0, 10.0); + assert!(rt.take_drag_out().is_none(), "exactly 3 pt is still a press"); + rt.pointer_move(13.5, 10.0); + assert!(rt.take_drag_out().is_some_and(|s| s.path.ends_with("near")), "3.5 pt passes a 3 pt threshold, under the default"); + rt.pointer_up(13.5, 10.0); + rt.frame(0.0); + rt.pointer_move(10.0, 50.0); + rt.pointer_down(10.0, 50.0); + rt.pointer_move(18.0, 50.0); + assert!(rt.take_drag_out().is_none(), "8 pt is past the default but under this element's 12"); + rt.pointer_move(23.0, 50.0); + assert!(rt.take_drag_out().is_some_and(|s| s.path.ends_with("far"))); +} + +#[test] +fn a_drag_out_released_before_the_threshold_is_a_press() { + let mut rt = drag_out_rt(true); + rt.pointer_move(11.0, 11.0); + rt.pointer_up(11.0, 11.0); + rt.frame(0.0); + assert!(rt.take_drag_out().is_none()); + assert_eq!((rt.state.presses, rt.state.drags), (1, 0), "on_drag never runs on a drag-out element"); + assert!(rt.events.iter().all(|e| !e.starts_with("drag-out"))); +} + +#[test] +fn a_drag_out_that_offers_nothing_stays_a_press() { + let mut rt = drag_out_rt(false); + rt.pointer_move(40.0, 10.0); + assert!(rt.take_drag_out().is_none()); + assert!(rt.pointer_captured(), "the press holds on"); + rt.pointer_move(20.0, 10.0); + rt.pointer_up(20.0, 10.0); + rt.frame(0.0); + assert_eq!(rt.state.presses, 1); +} + +#[test] +fn a_drag_out_that_offers_nothing_tracks_leaving_the_element() { + let mut rt = drag_out_rt(false); + assert!(rt.pointer.press_inside()); + rt.pointer_move(150.0, 10.0); + assert!(rt.pointer_captured(), "the press holds on"); + assert!(!rt.pointer.press_inside(), "the move that declined the drag left the element, so it no longer shows pressed"); +} + +#[test] +fn hosts_without_os_drags_keep_on_drag() { + let mut rt = Runtime::new(DragOutState { offer: true, ..Default::default() }, drag_out_view, (200.0, 200.0), Env::new(true, 1.0)); + rt.set_os_drag(false); + rt.frame(0.0); + rt.pointer_move(10.0, 10.0); + rt.pointer_down(10.0, 10.0); + rt.pointer_move(40.0, 10.0); + rt.pointer_up(40.0, 10.0); + rt.frame(0.0); + assert!(rt.take_drag_out().is_none()); + assert!(rt.state.drags > 0, "on_drag runs as before"); +} + +#[test] +fn a_reported_drag_end_reaches_on_drag_end_next_frame() { + let mut rt = drag_out_rt(true); + rt.pointer_move(40.0, 10.0); + let start = rt.take_drag_out().unwrap(); + let sink = rt.drag_end_sink(); + sink.borrow_mut().push((start.path, crate::DragOutcome::Copied)); + assert!(rt.drag_ends_pending()); + rt.frame(0.0); + assert_eq!(rt.state.ended, [crate::DragOutcome::Copied]); + assert!(!rt.drag_ends_pending()); + assert!(rt.events.iter().any(|e| e.starts_with("drag-end Copied "))); + assert!(rt.elements().iter().any(|e| e.key.as_deref() == Some("file") && e.drag_out)); +} + +#[test] +fn on_drag_start_runs_once_the_drag_is_handed_over_and_before_its_end() { + let mut rt = drag_out_rt(true); + rt.pointer_move(12.0, 10.0); + rt.frame(0.0); + assert_eq!(rt.state.starts, 0, "not before the threshold"); + rt.pointer_move(40.0, 10.0); + let start = rt.take_drag_out().unwrap(); + assert_eq!(rt.state.starts, 0, "handlers run between frames, after the host took the drag image"); + rt.frame(0.0); + assert!(rt.state.dragging && rt.state.starts == 1); + rt.drag_end_sink().borrow_mut().push((start.path, crate::DragOutcome::Cancelled)); + rt.frame(0.0); + assert!(!rt.state.dragging); + assert_eq!((rt.state.starts, rt.state.ended.as_slice()), (1, &[crate::DragOutcome::Cancelled][..])); +} + +#[test] +fn a_drag_start_and_end_reported_together_run_in_order() { + let mut rt = drag_out_rt(true); + rt.pointer_move(40.0, 10.0); + let start = rt.take_drag_out().unwrap(); + rt.drag_end_sink().borrow_mut().push((start.path, crate::DragOutcome::Copied)); + rt.frame(0.0); + assert!(!rt.state.dragging, "the end runs after the start"); + assert_eq!((rt.state.starts, rt.state.ended.as_slice()), (1, &[crate::DragOutcome::Copied][..])); +} + +#[test] +fn a_drag_out_no_host_took_ends_cancelled_on_the_next_frame() { + let mut rt = drag_out_rt(true); + rt.pointer_move(40.0, 10.0); + rt.frame(0.0); + assert!(!rt.state.dragging); + assert_eq!(rt.state.log, ["start", "end Cancelled"]); + assert!(rt.events.iter().any(|e| e.starts_with("drag-end Cancelled "))); + rt.frame(0.0); + assert_eq!(rt.state.log.len(), 2, "exactly one end"); +} + +#[test] +fn a_cancelled_press_ends_a_drag_out_no_host_took() { + let mut rt = drag_out_rt(true); + rt.pointer_move(40.0, 10.0); + rt.cancel_pointer(); + assert!(rt.take_drag_out().is_none(), "the cancel ended the request"); + rt.frame(0.0); + assert_eq!(rt.state.log, ["start", "end Cancelled"]); +} + +#[test] +fn untaken_drags_started_in_one_turn_end_in_order() { + let mut rt = drag_out_rt(true); + rt.pointer_move(40.0, 10.0); + rt.pointer_up(40.0, 10.0); + rt.pointer_move(10.0, 10.0); + rt.pointer_down(10.0, 10.0); + rt.pointer_move(40.0, 10.0); + rt.frame(0.0); + assert_eq!(rt.state.log, ["start", "end Cancelled", "start", "end Cancelled"]); +} + +#[test] +fn a_stale_sessions_end_runs_before_the_next_drags_start() { + let mut rt = drag_out_rt(true); + rt.pointer_move(40.0, 10.0); + let first = rt.take_drag_out().unwrap(); + rt.frame(0.0); + rt.pointer_move(10.0, 10.0); + rt.pointer_down(10.0, 10.0); + rt.pointer_move(40.0, 10.0); + let second = rt.take_drag_out().unwrap(); + // macOS reports a session it never ended when the next one replaces it. + rt.drag_end_sink().borrow_mut().push((first.path, crate::DragOutcome::Cancelled)); + rt.frame(0.0); + assert_eq!(rt.state.log, ["start", "end Cancelled", "start"]); + assert!(rt.state.dragging, "the second drag is still running"); + rt.drag_end_sink().borrow_mut().push((second.path, crate::DragOutcome::Copied)); + rt.frame(0.0); + assert_eq!(rt.state.log, ["start", "end Cancelled", "start", "end Copied"]); +} + +#[test] +fn a_drag_image_over_the_element_gets_its_unclipped_bounds() { + fn view(_: &DragOutState, _: &mut Cx<DragOutState>) -> El { + col().child(col().size(200.0, 100.0).clip_soft(0.0).child(el().size(200.0, 80.0)).child(el().key("row").size(200.0, 40.0) + .drag_out(|_: &DragOutState| Some(crate::DragItem::new().text("row"))))) + } + let mut rt = Runtime::new(DragOutState::default(), view, (200.0, 200.0), Env::new(true, 1.0)); + rt.frame(0.0); + rt.pointer_move(10.0, 90.0); + rt.pointer_down(10.0, 90.0); + rt.pointer_move(40.0, 90.0); + let start = rt.take_drag_out().unwrap(); + assert_eq!(start.rect, [0.0, 80.0, 200.0, 20.0], "the visible strip"); + assert_eq!(start.bounds, [0.0, 80.0, 200.0, 40.0], "the whole row"); +} + +#[test] +fn cursor_follows_the_hovered_target_and_its_ancestors() { + use crate::el::Cursor; + struct State { field: crate::edit::TextEdit } + fn view(s: &State, _: &mut Cx<State>) -> El { + col().size(200.0, 200.0) + .child(el().key("button").size(200.0, 40.0).cursor(Cursor::Pointer).on_press(|_: &mut State| {})) + .child(el().key("handle").size(200.0, 40.0).cursor(Cursor::Grab) + .child(el().key("inner").size(100.0, 40.0).on_press(|_: &mut State| {}))) + .child(crate::el::text_input(&s.field, crate::tok::TextStyle::new(14.0, 400.0)).key("field").size(200.0, 40.0) + .on_edit(|s: &mut State| &mut s.field)) + .child(el().key("plain").size(200.0, 40.0).on_press(|_: &mut State| {})) + } + let mut rt = Runtime::new(State { field: crate::edit::TextEdit::new("") }, view, (200.0, 200.0), Env::new(true, 1.0)); + rt.frame(0.0); + assert_eq!(rt.cursor(), Cursor::Default); + for (y, cursor) in [(20.0, Cursor::Pointer), (60.0, Cursor::Grab), (100.0, Cursor::Text), (140.0, Cursor::Default)] { + rt.pointer_move(50.0, y); + assert_eq!(rt.cursor(), cursor, "at y {y}"); + } + rt.pointer_move(50.0, 20.0); + rt.pointer_down(50.0, 20.0); + rt.pointer_move(50.0, 140.0); + assert_eq!(rt.cursor(), Cursor::Pointer, "a held press keeps its cursor"); + rt.pointer_up(50.0, 140.0); + assert_eq!(rt.cursor(), Cursor::Default); + rt.pointer_leave(); + assert_eq!(rt.cursor(), Cursor::Default); +} + +#[test] +fn hidden_cursor_ends_with_its_hover_and_its_element() { + use crate::el::Cursor; + fn view(picking: &bool, _: &mut Cx<bool>) -> El { + let picker = el().key("picker").size(200.0, 100.0).cursor(Cursor::Hidden).on_press(|_: &mut bool| {}) + .child(el().key("area").size(100.0, 100.0).cursor(Cursor::Crosshair).on_press(|_: &mut bool| {})); + col().size(200.0, 200.0).child(if *picking { picker } else { el().key("idle").size(200.0, 100.0) }) + } + let mut rt = Runtime::new(true, view, (200.0, 200.0), Env::new(true, 1.0)); + rt.frame(0.0); + rt.pointer_move(50.0, 50.0); + assert_eq!(rt.cursor(), Cursor::Crosshair); + rt.pointer_move(150.0, 50.0); + assert_eq!(rt.cursor(), Cursor::Hidden); + rt.pointer_move(150.0, 150.0); + assert_eq!(rt.cursor(), Cursor::Default, "hover left the element"); + rt.pointer_move(150.0, 50.0); + rt.pointer_leave(); + assert_eq!(rt.cursor(), Cursor::Default, "pointer left the window"); + rt.pointer_move(150.0, 50.0); + assert_eq!(rt.cursor(), Cursor::Hidden); + rt.update(|picking: &mut bool, _| *picking = false); + rt.frame(0.0); + assert_eq!(rt.cursor(), Cursor::Default, "the element went away"); +} + +#[test] +fn hidden_cursor_ends_when_a_drag_is_released_outside_the_window() { + use crate::el::Cursor; + fn view(_: &(), _: &mut Cx<()>) -> El { + el().size(200.0, 200.0).child(el().key("picker").size(200.0, 100.0).cursor(Cursor::Hidden).on_press(|_: &mut ()| {})) + } + let mut rt = Runtime::new((), view, (200.0, 200.0), Env::new(true, 1.0)); + rt.frame(0.0); + rt.pointer_move(50.0, 50.0); + rt.pointer_down(50.0, 50.0); + assert_eq!(rt.cursor(), Cursor::Hidden); + rt.pointer_move(250.0, 50.0); + assert_eq!(rt.cursor(), Cursor::Default, "never an element's cursor outside the window"); + rt.pointer_up(250.0, 50.0); + assert_eq!(rt.pointer(), None, "a release outside the window is a leave"); + + // The host saw the pointer leave mid-press, then releases at its last inside position. + rt.pointer_move(50.0, 50.0); + rt.pointer_down(50.0, 50.0); + rt.pointer_leave(); + assert_eq!(rt.cursor(), Cursor::Hidden, "the press still holds the pointer"); + rt.pointer_up(50.0, 50.0); + assert_eq!(rt.pointer(), None, "the deferred leave lands on release"); + assert_eq!(rt.cursor(), Cursor::Default); +} + +#[test] +fn cursor_follows_a_sibling_that_replaces_an_exiting_element_under_a_still_pointer() { + use crate::el::Cursor; + fn view(first: &bool, _: &mut Cx<bool>) -> El { + let item = |key: &str, cursor: Cursor| el().key(key).absolute(0.0, 0.0).size(100.0, 100.0).cursor(cursor) + .on_press(|_: &mut bool| {}).transition(Transition::opacity()); + el().size(200.0, 200.0).child(if *first { item("a", Cursor::Crosshair) } else { item("b", Cursor::Hidden) }) + } + let mut rt = Runtime::new(true, view, (200.0, 200.0), Env::new(true, 1.0)); + rt.frame(0.0); + rt.pointer_move(50.0, 50.0); + assert_eq!(rt.cursor(), Cursor::Crosshair); + rt.update(|first: &mut bool, _| *first = false); + rt.frame(1.0 / 120.0); + assert!(rt.tree.nodes.iter().any(|n| n.key.as_deref() == Some("a")), "a is still exiting"); + assert_eq!(rt.cursor(), Cursor::Hidden, "the sibling under the still pointer takes over"); +} + +#[test] +fn hover_lands_at_once_and_fades_out() { + fn view(_: &(), _: &mut Cx<()>) -> El { + col().size(200.0, 80.0) + .child(el().key("row").size(200.0, 40.0).hover(crate::color::oklcha(1.0, 0.0, 0.0, 0.1)).on_press(|_: &mut ()| {})) + } + let mut rt = Runtime::new((), view, (200.0, 80.0), Env::new(true, 1.0)); + rt.frame(0.0); + let id = rt.tree.nodes.iter().find(|n| n.key.as_deref() == Some("row")).unwrap().id; + let hover = |rt: &Runtime<()>| rt.scene.get(id, P_HOVER).unwrap_or(0.0); + rt.pointer_move(50.0, 20.0); + rt.frame(1.0 / 120.0); + assert_eq!(hover(&rt), 1.0, "the first frame under the pointer is fully hovered"); + rt.pointer_move(50.0, 60.0); + rt.frame(1.0 / 120.0); + let leaving = hover(&rt); + assert!(leaving > 0.0 && leaving < 1.0, "leaving fades: {leaving}"); + rt.frame(0.5); + assert_eq!(hover(&rt), 0.0); +} + +#[test] +fn rows_mounting_above_keep_a_still_pointers_hover() { + // Nodes mounting earlier in the tree shift every later index; last frame's geometry + // mustn't be read under the new indices (the hover would drop for a frame). + fn view(n: &usize, _: &mut Cx<usize>) -> El { + col().size(200.0, 80.0) + .child(col().size(200.0, 40.0).clip_rounded(0.0).children((0..*n).map(|k| el().key(format!("r{k}")).size(200.0, 10.0)))) + .child(crate::row().key("row").size(200.0, 40.0).hover_group() + .child(el().key("reveal").size(10.0, 10.0).fill(Color::WHITE).group_opacity(0.0, 1.0))) + } + let mut rt = Runtime::new(1usize, view, (200.0, 80.0), Env::new(true, 1.0)); + rt.frame(0.0); + rt.pointer_move(150.0, 60.0); + rt.frame(1.0 / 120.0); + let group = |rt: &Runtime<usize>| { + let i = rt.tree.nodes.iter().position(|n| n.key.as_deref() == Some("reveal")).unwrap(); + rt.paint.inh_scratch[i].group + }; + assert_eq!(group(&rt), 1.0); + for _ in 0..3 { + rt.update(|n: &mut usize, _| *n += 1); + rt.frame(1.0 / 120.0); + assert_eq!(group(&rt), 1.0, "the reveal stays shown while rows mount above"); + } +} + +#[test] +fn a_drag_counts_its_run_of_clicks() { + type State = Vec<(Phase, u32)>; + fn view(_: &State, _: &mut Cx<State>) -> El { + col().children([ + el().key("text").size(100.0, 40.0).on_drag(|s: &mut State, d, _| s.push((d.phase, d.clicks))) + .on_double_press(|s: &mut State| s.push((Phase::Up, 0))), + el().key("other").size(100.0, 40.0).on_drag(|s: &mut State, d, _| s.push((d.phase, d.clicks))), + ]) + } + let mut rt = Runtime::new(Vec::new(), view, (200.0, 200.0), Env::new(true, 1.0)); + rt.frame(0.0); + let click = |rt: &mut Runtime<State>, x: f32, y: f32| { + rt.pointer_down(x, y); + rt.pointer_up(x, y); + rt.frame(0.1); + let downs: Vec<u32> = rt.state.iter().filter(|e| e.0 == Phase::Down).map(|e| e.1).collect(); + rt.state.clear(); + downs[0] + }; + let presses: Vec<u32> = (0..4).map(|i| click(&mut rt, 10.0 + i as f32, 10.0)).collect(); + assert_eq!(presses, [1, 2, 3, 4], "each press within the interval and 4 pt of the last counts on"); + rt.frame(1.0); + assert_eq!(click(&mut rt, 10.0, 10.0), 1, "a press after the interval starts again"); + assert_eq!(click(&mut rt, 10.0, 50.0), 1, "another element starts again"); + assert_eq!(click(&mut rt, 20.0, 10.0), 1, "farther than 4 pt starts again"); + + rt.pointer_down(20.0, 10.0); + rt.pointer_move(40.0, 10.0); + rt.pointer_up(40.0, 10.0); + rt.frame(0.1); + assert!(rt.state.iter().all(|e| e.1 == 2), "every phase of a double-click drag says 2: {:?}", rt.state); + rt.state.clear(); + assert_eq!(click(&mut rt, 20.0, 10.0), 1, "a press that dragged ends the run"); + + rt.frame(1.0); + rt.pointer_down(10.0, 10.0); + rt.pointer_up(10.0, 10.0); + rt.frame(0.1); + rt.pointer_down(10.0, 10.0); + rt.pointer_up(10.0, 10.0); + rt.frame(0.1); + assert!(rt.state.contains(&(Phase::Up, 0)), "on_double_press still runs: {:?}", rt.state); +} + +#[test] +fn a_held_press_hears_its_drag_again_until_released() { + type State = Vec<(Phase, bool, f32)>; + fn view(_: &State, _: &mut Cx<State>) -> El { + el().key("pill").size(100.0, 40.0).on_drag(|s: &mut State, d, tx| { + s.push((d.phase, tx.drag_repeat(), d.x)); + if d.phase == Phase::Down || tx.drag_repeat() { + tx.drag_repeat_after(std::time::Duration::from_millis(if tx.drag_repeat() { 50 } else { 300 })); + } + }) + } + let repeats = |rt: &Runtime<State>| rt.state.iter().filter(|e| e.1).count(); + let mut rt = Runtime::new(Vec::new(), view, (200.0, 200.0), Env::new(true, 1.0)); + rt.frame(0.0); + rt.pointer_move(10.0, 10.0); + rt.pointer_down(10.0, 10.0); + rt.frame(1.0 / 60.0); + assert_eq!(rt.state, vec![(Phase::Down, false, 10.0)]); + assert!(rt.wake_deadline().is_some(), "a still window wakes for the repeat"); + for _ in 0..15 { rt.frame(1.0 / 60.0); } + assert_eq!(repeats(&rt), 0, "not before the delay"); + for _ in 0..4 { rt.frame(1.0 / 60.0); } + assert_eq!(repeats(&rt), 1); + assert_eq!(rt.state.last(), Some(&(Phase::Move, true, 10.0)), "a still pointer is heard again"); + + rt.pointer_move(30.0, 10.0); + rt.frame(1.0 / 60.0); + assert!(rt.state.contains(&(Phase::Move, false, 30.0)), "the hand's move isn't a repeat"); + for _ in 0..12 { rt.frame(1.0 / 60.0); } + assert!(repeats(&rt) >= 4, "then every interval: {:?}", rt.state); + assert_eq!(rt.state.last().map(|e| (e.1, e.2)), Some((true, 30.0)), "where the pointer is now"); + + rt.pointer_up(30.0, 10.0); + rt.frame(1.0 / 60.0); + let heard = rt.state.len(); + for _ in 0..30 { rt.frame(1.0 / 60.0); } + assert_eq!(rt.state.len(), heard, "the release ends it"); + assert_eq!(rt.state.last().map(|e| e.0), Some(Phase::Up)); +} diff --git a/app/vendor/rune/crates/rune/src/runtime/tests/pointer_hit.rs b/app/vendor/rune/crates/rune/src/runtime/tests/pointer_hit.rs new file mode 100644 index 0000000..d25e088 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/tests/pointer_hit.rs @@ -0,0 +1,435 @@ +use super::*; + + +#[test] +fn overlay_hit_regions_follow_live_geometry_and_ancestor_clips_in_the_same_frame() { + struct State { offset: crate::Live<[f32; 2]>, opacity: crate::Live<f32>, pressed: u32, hovered: u32, visible: bool } + fn view(s: &State, _: &mut Cx<State>) -> El { + el().child(el().size(60.0, 60.0).clip_soft(0.0) + .children(s.visible.then(|| el().key("chip").size(40.0, 20.0).pin(Some(30.0), Some(0.0), None, None) + .live_offset(&s.offset).live_opacity(&s.opacity).hit() + .on_hover(|s: &mut State| s.hovered += 1).on_press(|s: &mut State| s.pressed += 1)))) + .child(el().size(10.0, 10.0).on_hover(|_: &mut State| {})) + } + let offset = crate::Live::new([0.0, 0.0]); + let opacity = crate::Live::new(1.0); + let mut rt = Runtime::new(State { offset: offset.clone(), opacity: opacity.clone(), pressed: 0, hovered: 0, visible: true }, view, (100.0, 100.0), Env { system_dark: true, scale: 2.0 }); + rt.host.native_overlay = true; + rt.frame(0.0); + assert_eq!(rt.hit_regions(), &[[30.0, 0.0, 60.0, 20.0]]); + rt.pointer_move(15.0, 10.0); + offset.set([20.0, 0.0]); + rt.frame(0.0); + assert_eq!(rt.hit_regions(), &[[50.0, 0.0, 60.0, 20.0]], "logical regions must use this frame's live offset, not the previous layout"); + offset.set([-20.0, 0.0]); + rt.frame(0.0); + assert_eq!(rt.hit_regions(), &[[10.0, 0.0, 50.0, 20.0]]); + rt.pointer_down(15.0, 10.0); + rt.pointer_up(15.0, 10.0); + rt.frame(0.0); + assert_eq!(rt.state.pressed, 1, "the native hit and Rune release must agree on the moved chip"); + assert_eq!(rt.state.hovered, 1, "a chip moving under a stationary pointer enters hover once"); + assert!(!rt.has_pending_input(), "stationary hover must not generate an endless frame loop"); + rt.pointer_down(15.0, 10.0); + rt.pointer_up(55.0, 10.0); + rt.frame(0.0); + assert_eq!(rt.state.pressed, 1, "release inside the old layout but outside the drawn chip must cancel"); + opacity.set(0.0); + rt.frame(0.0); + assert!(rt.hit_regions().is_empty(), "transparent nodes and hover-only elements do not block native input"); + opacity.set(1.0); + rt.update(|s, _| s.visible = false); + rt.frame(0.0); + assert!(rt.hit_regions().is_empty(), "exiting chips must immediately release native input"); +} + +#[test] +fn overlay_pointer_observation_does_not_require_a_native_hit_region() { + fn view(_: &Vec<PointerPress>, _: &mut Cx<Vec<PointerPress>>) -> El { + el().on_pointer_move(|s: &mut Vec<PointerPress>, p| s.push(p)) + } + let mut rt = Runtime::new(Vec::new(), view, (100.0, 100.0), Env { system_dark: true, scale: 1.0 }); + rt.frame(0.0); + rt.pointer_move(20.0, 40.0); + rt.frame(0.0); + assert_eq!(rt.state, [PointerPress { x: 20.0, y: 40.0 }]); + assert!(rt.hit_regions().is_empty()); +} + +#[test] +fn overlay_idle_pointer_does_not_request_unchanged_frames() { + fn view(_: &u32, _: &mut Cx<u32>) -> El { + el().child(el().size(40.0, 20.0).hit().on_hover(|n: &mut u32| *n += 1)) + } + let mut rt = Runtime::new(0, view, (100.0, 100.0), Env { system_dark: true, scale: 1.0 }); + rt.frame(0.0); + assert!(rt.observe_pointer(5.0, 5.0), "enter must run the hover callback"); + rt.frame(0.0); + assert_eq!(rt.state, 1); + assert!(!rt.observe_pointer(6.0, 5.0), "movement within an unchanged chip needs no frame"); + assert!(!rt.observe_pointer(6.0, 5.0), "duplicate monitor/winit observations need no frame"); + assert!(!rt.observe_pointer(90.0, 90.0)); + assert!(!rt.observe_pointer(200.0, 90.0), "movement outside the canvas needs no frame"); + assert!(!rt.has_pending_input()); +} + +#[test] +fn hit_tests_leave_out_the_right_and_bottom_edges() { + fn tile(k: &'static str) -> El { + el().key(k).size(40.0, 20.0) + .on_press(move |s: &mut Vec<String>| s.push(format!("press {k}"))) + .on_hover(move |s: &mut Vec<String>| s.push(format!("hover {k}"))) + .on_hover_change(move |s: &mut Vec<String>, inside, _| if inside { s.push(format!("enter {k}")) }) + .on_pointer_move(move |s: &mut Vec<String>, _| s.push(format!("move {k}"))) + } + fn view(_: &Vec<String>, _: &mut Cx<Vec<String>>) -> El { + col().gap(20.0).child(crate::row().child(tile("a")).child(tile("b"))).child(tile("lone")) + } + let mut rt = Runtime::new(Vec::new(), view, (200.0, 200.0), Env { system_dark: true, scale: 1.0 }); + rt.frame(0.0); + assert_eq!(rt.presented("lone").unwrap().0, [0.0, 40.0, 40.0, 20.0]); + let mut click = |x, y| { + rt.pointer_move(x, y); + rt.pointer_down(x, y); + rt.pointer_up(x, y); + rt.frame(0.0); + let mut events = std::mem::take(&mut rt.state); + rt.pointer_leave(); + rt.frame(0.0); + rt.state.clear(); + events.sort(); + events.dedup(); + events + }; + assert_eq!(click(40.0, 10.0), ["enter b", "hover b", "move b", "press b"], "the shared edge is b's alone"); + assert_eq!(click(40.0, 50.0), Vec::<String>::new(), "a lone node's right edge is outside it"); + assert_eq!(click(20.0, 60.0), Vec::<String>::new(), "and so is its bottom edge"); + assert_eq!(click(0.0, 40.0), ["enter lone", "hover lone", "move lone", "press lone"], "its top-left corner is inside"); +} + +#[test] +fn deleting_a_focused_row_does_not_call_its_stale_edit_accessor() { + fn view(s: &Vec<crate::TextEdit>, _: &mut Cx<Vec<crate::TextEdit>>) -> El { + col().children(s.iter().enumerate().map(|(i, edit)| { + crate::text_input(edit, crate::TextStyle::new(14.0, 400.0)) + .key(format!("row-{i}")) + .on_edit(crate::edit_access(move |s: &mut Vec<crate::TextEdit>| &mut s[i])) + })).child(el().key("delete").size(40.0, 40.0).on_press(|s: &mut Vec<crate::TextEdit>| { s.clear(); })) + } + let mut edit = crate::TextEdit::default(); + edit.focused = true; + let mut rt = Runtime::new(vec![edit], view, (100.0, 100.0), Env::new(true, 1.0)); + rt.frame(0.0); + let path = rt.tree.nodes.iter().find(|n| n.key.as_deref() == Some("delete")).unwrap().path.clone(); + rt.frame.queue.push(Action::Press(path, crate::PointerButton::Primary, false)); + rt.frame(0.0); + assert!(rt.state.is_empty()); + assert!(!rt.has_focus()); +} + +#[test] +fn secondary_only_children_preserve_primary_click_hover_and_background_blur() { + type State = (u32, u32, bool); + fn view(s: &State, _: &mut Cx<State>) -> El { + let parent = el().key("parent").size(80.0, 80.0); + let parent = if s.2 { parent } else { + parent.on_press(|s: &mut State| s.0 += 1) + .on_hover(|s: &mut State| s.1 += 1) + }; + parent.child(el().key("child").size(40.0, 40.0) + .on_secondary_press(|_: &mut State, _, _| {})) + } + let mut rt = Runtime::new((0, 0, false), view, (100.0, 100.0), Env::new(true, 1.0)); + rt.frame(0.0); + rt.pointer_move(10.0, 10.0); + rt.pointer_down(10.0, 10.0); + rt.pointer_up(10.0, 10.0); + rt.frame(0.0); + assert_eq!(rt.state, (1, 1, false)); + rt.state.2 = true; + rt.invalidate(); + rt.frame(0.0); + rt.kbd.focus.focus = crate::runtime::focus_machine::Focus::On { path: "previous-input".into(), hovered: false, from: None }; + rt.pointer_move(10.0, 10.0); + rt.pointer_down(10.0, 10.0); + assert!(rt.pointer.hovered.is_none()); + assert!(matches!(rt.frame.queue.iter().last(), Some(Action::Blur))); + assert!(rt.secondary_target(10.0, 10.0).is_some()); +} + +#[test] +fn secondary_press_routes_to_ancestor_without_primary_and_cancels_outside() { + type State = (u32, Vec<PointerPress>, bool); + fn view(s: &State, _: &mut Cx<State>) -> El { + col().child(if s.2 { + el() + } else { + el().key("parent").size(80.0, 80.0) + .on_secondary_press(|s: &mut State, p, _| s.1.push(p)) + .child(el().key("child").size(40.0, 40.0).on_press(|s: &mut State| s.0 += 1)) + }) + } + let mut rt = Runtime::new((0, Vec::new(), false), view, (100.0, 100.0), Env::new(true, 1.0)); + rt.frame(0.0); + rt.secondary_down(10.0, 10.0); + rt.secondary_up(12.0, 12.0); + rt.frame(0.0); + assert_eq!(rt.state.0, 0); + assert_eq!(rt.state.1, [PointerPress { x: 12.0, y: 12.0 }]); + rt.secondary_down(10.0, 10.0); + rt.secondary_up(90.0, 90.0); + rt.frame(0.0); + assert_eq!(rt.state.1.len(), 1); + rt.secondary_down(10.0, 10.0); + rt.state.2 = true; + rt.invalidate(); + rt.frame(0.0); + rt.secondary_up(12.0, 12.0); + rt.frame(0.0); + assert_eq!(rt.state.1.len(), 1); +} + +#[test] +fn presses_land_inside_a_scrolled_view() { + struct State { pressed: Vec<usize> } + fn view(_: &State, _: &mut Cx<State>) -> El { + let mut list = col().key("list").w_full(); + for i in 0..10 { + list = list.child(el().key(format!("b{i}")).size(200.0, 40.0).on_press(move |s: &mut State| s.pressed.push(i))); + } + col().size(200.0, 200.0).child(col().key("scroll").size(200.0, 200.0).scroll(ScrollSpec { stick_bottom: false }).child(list)) + } + let mut rt = Runtime::new(State { pressed: Vec::new() }, view, (200.0, 200.0), Env { system_dark: true, scale: 1.0 }); + rt.frame(0.0); + rt.wheel(100.0, 100.0, -120.0); + rt.frame(1.0 / 120.0); + let (x, y) = rt.find("b5").expect("b5 is drawn"); + assert!(y < 200.0, "b5 scrolled into view at {y}"); + rt.pointer_move(x, y); + rt.pointer_down(x, y); + rt.pointer_up(x, y); + rt.frame(1.0 / 120.0); + assert_eq!(rt.state.pressed, [5]); +} + +#[test] +fn a_double_press_follows_the_first_press_within_the_interval_and_tolerance() { + #[derive(Default)] + struct State { presses: u32, doubles: u32, other: u32 } + fn view(_: &State, _: &mut Cx<State>) -> El { + crate::row().size(300.0, 100.0) + .child(el().key("row").size(100.0, 100.0) + .on_press(|s: &mut State| s.presses += 1) + .on_double_press(|s: &mut State| s.doubles += 1)) + .child(el().key("other").size(100.0, 100.0).on_press(|s: &mut State| s.other += 1)) + } + let tick = |rt: &mut Runtime<State>, seconds: f64| for _ in 0..(seconds * 120.0).round() as usize { rt.frame(1.0 / 120.0); }; + let click = |rt: &mut Runtime<State>, (x, y): (f32, f32)| { + rt.pointer_move(x, y); + rt.pointer_down(x, y); + rt.frame(1.0 / 120.0); + rt.pointer_up(x, y); + rt.frame(1.0 / 120.0); + }; + let counts = |rt: &Runtime<State>| (rt.state.presses, rt.state.doubles); + let mut rt = Runtime::new(State::default(), view, (300.0, 100.0), Env::new(true, 1.0)); + rt.frame(0.0); + + click(&mut rt, (50.0, 50.0)); + assert_eq!(counts(&rt), (1, 0), "the first press runs on_press right away"); + tick(&mut rt, 0.1); + click(&mut rt, (53.0, 47.0)); + assert_eq!(counts(&rt), (2, 1), "the second press inside the interval and 4 pt is a double press"); + assert!(rt.events.iter().any(|e| e.starts_with("double press"))); + tick(&mut rt, 0.1); + click(&mut rt, (50.0, 50.0)); + assert_eq!(counts(&rt), (3, 1), "a third press starts a new pair"); + tick(&mut rt, 0.1); + click(&mut rt, (50.0, 50.0)); + assert_eq!(counts(&rt), (4, 2)); + + tick(&mut rt, 0.1); + click(&mut rt, (50.0, 50.0)); + let slow = rt.double_click_interval + 0.05; + tick(&mut rt, slow); + click(&mut rt, (50.0, 50.0)); + assert_eq!(counts(&rt), (6, 2), "too slow"); + + tick(&mut rt, 0.6); + click(&mut rt, (50.0, 50.0)); + click(&mut rt, (55.0, 50.0)); + assert_eq!(counts(&rt), (8, 2), "moved more than 4 pt"); + + tick(&mut rt, 0.6); + click(&mut rt, (50.0, 50.0)); + click(&mut rt, (150.0, 50.0)); + click(&mut rt, (50.0, 50.0)); + assert_eq!((counts(&rt), rt.state.other), ((10, 2), 1), "a press elsewhere breaks the pair"); + + tick(&mut rt, 0.6); + click(&mut rt, (50.0, 50.0)); + rt.pointer_down(50.0, 50.0); + rt.frame(1.0 / 120.0); + rt.pointer_move(250.0, 50.0); + rt.pointer_up(250.0, 50.0); + rt.frame(1.0 / 120.0); + assert_eq!(counts(&rt), (11, 2), "a second press released outside is cancelled"); + + // A second press that drags 40 pt (still inside) and lets go 5 s later is no click. + tick(&mut rt, 0.6); + click(&mut rt, (50.0, 50.0)); + rt.pointer_down(50.0, 50.0); + rt.frame(1.0 / 120.0); + rt.pointer_move(90.0, 50.0); + rt.pointer_move(60.0, 50.0); + tick(&mut rt, 5.0); + rt.pointer_up(60.0, 50.0); + rt.frame(1.0 / 120.0); + assert_eq!(counts(&rt), (13, 2), "a drag or a long press doesn't finish a double press"); + // Held without moving past the interval, it's no click either. + tick(&mut rt, 0.6); + click(&mut rt, (50.0, 50.0)); + rt.pointer_down(50.0, 50.0); + let long = rt.double_click_interval + 0.05; + tick(&mut rt, long); + rt.pointer_up(50.0, 50.0); + rt.frame(1.0 / 120.0); + assert_eq!(counts(&rt), (15, 2), "a long second press"); + // A first press that drags doesn't arm one. + tick(&mut rt, 0.6); + rt.pointer_down(50.0, 50.0); + rt.pointer_move(50.0, 90.0); + rt.pointer_move(50.0, 50.0); + rt.pointer_up(50.0, 50.0); + rt.frame(1.0 / 120.0); + click(&mut rt, (50.0, 50.0)); + assert_eq!(counts(&rt), (17, 2), "a dragged first press"); + + // Headless, a slower system setting is honoured on the same virtual clock. + rt.double_click_interval = 1.0; + tick(&mut rt, 1.1); + click(&mut rt, (50.0, 50.0)); + tick(&mut rt, 0.8); + click(&mut rt, (50.0, 50.0)); + assert_eq!(counts(&rt), (19, 3)); +} + +#[test] +fn an_element_with_only_a_double_press_is_a_press_target() { + struct State { doubles: u32, behind: u32 } + fn view(_: &State, _: &mut Cx<State>) -> El { + el().size(100.0, 100.0).on_press(|s: &mut State| s.behind += 1) + .child(el().size(100.0, 100.0).on_double_press(|s: &mut State| s.doubles += 1)) + } + let mut rt = Runtime::new(State { doubles: 0, behind: 0 }, view, (100.0, 100.0), Env::new(true, 1.0)); + rt.frame(0.0); + for _ in 0..2 { + rt.pointer_move(50.0, 50.0); + rt.pointer_down(50.0, 50.0); + rt.frame(1.0 / 120.0); + rt.pointer_up(50.0, 50.0); + rt.frame(1.0 / 120.0); + } + assert_eq!((rt.state.doubles, rt.state.behind), (1, 0)); +} + +#[test] +fn presses_on_a_window_drag_region_move_the_window_but_not_its_buttons() { + struct State { pressed: u32 } + fn view(_: &State, _: &mut Cx<State>) -> El { + col().size(200.0, 200.0) + .child(crate::el::row().key("titlebar").size(200.0, 40.0).window_drag() + .child(el().key("button").size(40.0, 40.0).on_press(|s: &mut State| s.pressed += 1))) + .child(el().key("body").size(200.0, 40.0)) + } + let mut rt = Runtime::new(State { pressed: 0 }, view, (200.0, 200.0), Env::new(true, 1.0)); + rt.frame(0.0); + for (x, y, drags) in [(100.0, 20.0, true), (20.0, 20.0, false), (100.0, 60.0, false)] { + rt.pointer_move(x, y); + rt.pointer_down(x, y); + assert_eq!(rt.take_titlebar_action() == Some(TitlebarAction::Drag), drags, "at {x}, {y}"); + assert!(rt.take_titlebar_action().is_none(), "a drag request is taken once"); + rt.pointer_up(x, y); + } + rt.frame(1.0 / 120.0); + assert_eq!(rt.state.pressed, 1, "the button inside the title bar still presses"); +} + +#[test] +fn a_double_press_on_nothing_in_the_native_titlebar_band_takes_the_titlebar_action() { + fn view(_: &(), _: &mut Cx<()>) -> El { + col().size(200.0, 200.0).child(el().key("button").size(40.0, 40.0).on_press(|_: &mut ()| {})) + } + let mut rt = Runtime::new((), view, (200.0, 200.0), Env::new(true, 1.0)); + rt.frame(0.0); + let double = |rt: &mut Runtime<()>, x: f32, y: f32| { + let mut actions = Vec::new(); + for _ in 0..2 { + rt.pointer_move(x, y); + rt.pointer_down(x, y); + actions.push(rt.take_titlebar_action()); + rt.pointer_up(x, y); + } + actions + }; + assert_eq!(double(&mut rt, 100.0, 10.0), [None, None], "no native band, nothing to do"); + rt.set_native_titlebar_band(28.0); + assert_eq!(double(&mut rt, 100.0, 10.0), [None, Some(TitlebarAction::DoubleClick)], "the system drags; Rune adds the double click"); + assert_eq!(double(&mut rt, 100.0, 60.0), [None, None], "below the band"); + assert_eq!(double(&mut rt, 20.0, 10.0), [None, None], "a button in the band keeps its presses"); +} + +#[test] +fn hover_change_spans_descendants_and_holds_through_a_press() { + type State = (Vec<bool>, u32, u32); + fn view(_: &State, _: &mut Cx<State>) -> El { + col().size(200.0, 200.0) + .child(el().key("pill").size(100.0, 40.0).on_hover_change(|s: &mut State, inside, _| s.0.push(inside)) + .child(el().key("button").size(40.0, 40.0) + .on_press(|s: &mut State| s.1 += 1).on_hover(|s: &mut State| s.2 += 1))) + } + let mut rt = Runtime::new((Vec::new(), 0, 0), view, (200.0, 200.0), Env::new(true, 1.0)); + rt.frame(0.0); + rt.pointer_move(80.0, 20.0); + rt.frame(0.0); + assert_eq!(rt.state.0, [true]); + rt.pointer_move(20.0, 20.0); + rt.pointer_down(20.0, 20.0); + rt.pointer_up(20.0, 20.0); + rt.frame(0.0); + assert_eq!(rt.state, (vec![true], 1, 1), "the child keeps its hover and press; entering it is not a leave"); + rt.pointer_down(20.0, 20.0); + rt.pointer_move(20.0, 120.0); + rt.pointer_leave(); + rt.frame(0.0); + assert_eq!(rt.state.0, [true], "a held press stays inside"); + rt.pointer_up(20.0, 120.0); + rt.frame(0.0); + assert_eq!(rt.state.0, [true, false]); + rt.pointer_move(50.0, 20.0); + rt.pointer_leave(); + rt.frame(0.0); + assert_eq!(rt.state.0, [true, false, true, false]); +} + +#[test] +fn interactive_overlay_immediately_after_non_interactive_help_suppresses_tooltip() { + fn view(_: &(), _: &mut Cx<()>) -> El { + col().size(200.0, 100.0) + .child(el().key("label").size(100.0, 40.0).help("Behind cover")) + .child(el().key("cover").absolute(0.0, 0.0).size(100.0, 40.0).on_press(|_: &mut ()| {})) + .child(el().key("own").absolute(100.0, 0.0).size(100.0, 40.0).help("Own tip").on_press(|_: &mut ()| {})) + } + let mut rt = Runtime::new((), view, (200.0, 100.0), Env::new(true, 1.0)); + rt.frame(0.0); + rt.pointer_move(50.0, 20.0); + rt.frame(0.0); + rt.frame(rt.help_delay + 0.1); + assert!(rt.help_tooltip().is_none(), "interactive cover at hit index == seq must suppress underlying tooltip"); + + // An interactive element with help of its own (at hit index == seq) still shows its tooltip. + rt.pointer_move(150.0, 20.0); + rt.frame(0.0); + rt.frame(rt.help_delay + 0.1); + assert!(rt.help_tooltip().is_some(), "uncovered interactive element still shows its own tooltip"); +} diff --git a/app/vendor/rune/crates/rune/src/runtime/tests/press_moving.rs b/app/vendor/rune/crates/rune/src/runtime/tests/press_moving.rs new file mode 100644 index 0000000..7f57376 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/tests/press_moving.rs @@ -0,0 +1,35 @@ +use super::*; + +struct State { + x: f32, + pressed: u32, +} + +fn view(s: &State, _: &mut Cx<State>) -> El { + el().child(el().key("button").size(40.0, 20.0).absolute(s.x, 0.0).on_press(|s: &mut State| s.pressed += 1)) +} + +fn press_then_slide(move_after: Option<(f32, f32)>) -> u32 { + let mut rt = Runtime::new(State { x: 0.0, pressed: 0 }, view, (300.0, 100.0), Env::new(true, 2.0)); + rt.frame(0.0); + rt.pointer_move(20.0, 10.0); + rt.pointer_down(20.0, 10.0); + rt.state.x = 200.0; + rt.invalidate(); + rt.frame(1.0 / 60.0); + let (x, y) = move_after.unwrap_or((20.0, 10.0)); + rt.pointer_move(x, y); + rt.pointer_up(x, y); + rt.frame(0.0); + rt.state.pressed +} + +#[test] +fn a_button_that_moves_out_from_under_a_still_pointer_still_takes_the_press() { + assert_eq!(press_then_slide(None), 1); +} + +#[test] +fn a_pointer_that_moves_off_the_button_still_cancels_the_press() { + assert_eq!(press_then_slide(Some((25.0, 60.0))), 0); +} diff --git a/app/vendor/rune/crates/rune/src/runtime/tests/relayout.rs b/app/vendor/rune/crates/rune/src/runtime/tests/relayout.rs new file mode 100644 index 0000000..f903642 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/tests/relayout.rs @@ -0,0 +1,444 @@ +//! A resize with nothing else changed lays the last tree out again without running the view; +//! anything the view reads that the resize moves still runs it. +use super::*; +use crate::{TextEdit, TextStyle, memo, row, text, text_input}; +use std::cell::Cell; + +mod live; + +thread_local! { + static VIEWS: Cell<u32> = const { Cell::new(0) }; + static MEMOS: Cell<u32> = const { Cell::new(0) }; +} + +fn ran() { VIEWS.set(VIEWS.get() + 1); } + +/// How many times `f` ran a view. +fn views(f: impl FnOnce()) -> u32 { + let before = VIEWS.get(); + f(); + VIEWS.get() - before +} + +fn resize<S>(rt: &mut Runtime<S>, width: f32, scale: f32) -> u32 { + views(|| { + rt.set_viewport((width, 600.0), scale); + rt.frame(1.0 / 120.0); + }) +} + +fn paragraphs(n: &u32, _: &mut Cx<u32>) -> El { + ran(); + let para = "Paragraph text long enough to wrap over several lines as the window narrows."; + col().w_full().children((0..3 + *n).map(|i| text(format!("{i}. {para}")).w_full().wrap().key(format!("t{i}")))) + .child(memo("tail", 0, || { + MEMOS.set(MEMOS.get() + 1); + text("tail").key("tail") + })) +} + +fn node<'a, S>(rt: &'a Runtime<S>, key: &str) -> &'a Node { + rt.tree.nodes.iter().find(|n| n.key.as_deref() == Some(key)).unwrap() +} + +fn content<S>(rt: &Runtime<S>, key: &str) -> String { + node(rt, key).text.as_ref().unwrap().content.clone() +} + +/// Every node's path, layout rect and text line count. +fn layout<S>(rt: &Runtime<S>) -> Vec<(String, [f32; 4], usize)> { + rt.tree.nodes.iter().map(|n| (n.path.clone(), n.target, n.text_layout.as_ref().and_then(crate::text::TextLayout::single).map_or(0, |l| l.len()))).collect() +} + +#[test] +fn a_resize_alone_lays_the_tree_out_again_without_the_view_as_a_full_commit_would() { + let mut rt = Runtime::new(0, paragraphs, (700.0, 600.0), Env::new(true, 2.0)); + let mut full = Runtime::new(0, paragraphs, (700.0, 600.0), Env::new(true, 2.0)); + rt.frame(0.0); + full.frame(0.0); + for w in [600.0, 420.0, 300.0, 520.0] { + assert_eq!(resize(&mut rt, w, 2.0), 0, "at {w}"); + full.invalidate(); + assert_eq!(resize(&mut full, w, 2.0), 1); + assert_eq!(layout(&rt), layout(&full), "at {w}"); + if w == 300.0 { assert!(node(&rt, "t0").text_layout.as_ref().and_then(crate::text::TextLayout::single).unwrap().len() > 1, "the narrow window wrapped the text"); } + } +} + +/// A resize lays out into the node buffer the last commit let go of, as a flatten does. +#[test] +fn a_resize_reuses_the_last_commits_node_buffer() { + let mut rt = Runtime::new(0, paragraphs, (700.0, 600.0), Env::new(true, 2.0)); + rt.frame(0.0); + // The first commit let go of an empty buffer. + rt.invalidate(); + rt.frame(1.0 / 120.0); + for w in [600.0, 420.0, 300.0] { + let (spare, last) = (rt.tree.spare_nodes.as_ptr(), rt.tree.nodes.as_ptr()); + assert!(rt.tree.spare_nodes.capacity() >= rt.tree.nodes.len()); + assert_eq!(resize(&mut rt, w, 2.0), 0, "at {w}"); + assert_eq!(rt.tree.nodes.as_ptr(), spare, "at {w}"); + assert_eq!(rt.tree.spare_nodes.as_ptr(), last, "at {w}"); + } +} + +#[test] +fn a_resize_keeps_the_memos_the_view_built() { + let mut rt = Runtime::new(0, paragraphs, (700.0, 600.0), Env::new(true, 2.0)); + rt.frame(0.0); + assert_eq!(resize(&mut rt, 600.0, 2.0), 0); + let memos = MEMOS.get(); + rt.invalidate(); + assert_eq!(resize(&mut rt, 500.0, 2.0), 1); + assert_eq!(MEMOS.get(), memos, "the memo built before the resize is still cached"); +} + +#[test] +fn a_resize_with_a_state_change_runs_the_view() { + let mut rt = Runtime::new(0, paragraphs, (700.0, 600.0), Env::new(true, 2.0)); + rt.frame(0.0); + rt.update(|n, _| *n = 1); + assert_eq!(resize(&mut rt, 600.0, 2.0), 1); + assert_eq!(content(&rt, "t3").get(..2), Some("3.")); +} + +/// A view can read the scale (`Cx::env`), and text lays out at it. +#[test] +fn a_new_scale_runs_the_view() { + let mut rt = Runtime::new(0, paragraphs, (700.0, 600.0), Env::new(true, 2.0)); + rt.frame(0.0); + assert_eq!(resize(&mut rt, 700.0, 1.0), 1); + assert_eq!(resize(&mut rt, 600.0, 1.0), 0, "and the next resize at that scale doesn't"); +} + +/// Theme colours resolve per blend mode, so a resize in the frame the mode switched runs the view. +#[test] +fn a_new_blend_mode_runs_the_view() { + let mut rt = Runtime::new(0, paragraphs, (700.0, 600.0), Env::new(true, 2.0)); + rt.frame(0.0); + rt.set_srgb_blend(!rt.srgb_blend()); + assert_eq!(resize(&mut rt, 600.0, 2.0), 1); + assert_eq!(resize(&mut rt, 500.0, 2.0), 0, "and the next resize in that mode doesn't"); +} + +/// A node still showing its exit has left the layout tree, so the tree can't be laid out again. +#[test] +fn a_resize_during_an_exit_runs_the_view_and_the_exit_carries_on() { + let mut rt = Runtime::new(1, paragraphs, (700.0, 600.0), Env::new(true, 2.0)); + rt.frame(0.0); + rt.update(|n, _| *n = 0); + rt.frame(1.0 / 120.0); + let leaving = node(&rt, "t3").id; + assert!(rt.is_exiting(leaving)); + assert_eq!(resize(&mut rt, 600.0, 2.0), 1); + assert!(rt.is_exiting(leaving)); +} + +/// A transcript of rows that wrap, built by index in a scroll view. +fn transcript(sticky: &bool, _: &mut Cx<bool>) -> El { + ran(); + let rows = col().key("rows").w_full().px(8.0).growth(crate::el::GrowthSpec::default()).virtual_rows( + 300, 40.0, + |_: &bool, i| std::borrow::Cow::Owned(format!("m{i}")), + |_: &bool, i| text(format!("{i}. {}", "Words that wrap over more lines as the window narrows. ".repeat(1 + i % 4))).w_full().wrap(), + ); + col().w_full().h_full().child(col().key("scroll").w_full().grow(1.0).min_h(0.0).scroll(crate::ScrollSpec { stick_bottom: *sticky }).child(rows)) +} + +/// Resizes by the full path: the view runs, as it did before resizes reused the tree. +fn full_resize<S>(rt: &mut Runtime<S>, size: (f32, f32)) -> u32 { + rt.commit.set_reuse_scale(f32::NAN); + views(|| { + rt.set_viewport(size, 2.0); + rt.frame(1.0 / 120.0); + }) +} + +/// What shows of each element in the window, by path. A virtual list's extent counts rows it +/// hasn't mounted at their estimates, so it isn't something that shows. +fn shown<S>(rt: &Runtime<S>) -> Vec<(String, [i32; 4])> { + let mut shown: Vec<_> = rt.elements().into_iter().filter(|e| e.visible[2] > 0.0 && e.visible[3] > 0.0 && !e.virtual_extent) + .map(|e| (e.path, e.rect.map(|x| (x * 100.0).round() as i32))).collect(); + shown.sort(); + shown +} + +fn scrolled_transcript(sticky: bool) -> Runtime<bool> { + let mut rt = Runtime::new(sticky, transcript, (700.0, 600.0), Env::new(true, 2.0)); + rt.frame(0.0); + for _ in 0..8 { rt.frame(1.0 / 120.0); } + if !sticky { + rt.wheel(300.0, 300.0, -3000.0); + for _ in 0..30 { rt.frame(1.0 / 120.0); } + } + rt +} + +/// A virtual list keeps the rows it mounted: they lay out again at the new width, and the +/// reader stays on the row they were reading, as when the view runs. +#[test] +fn a_resize_lays_a_virtual_lists_mounted_rows_out_again_without_the_view() { + for sticky in [false, true] { + let mut rt = scrolled_transcript(sticky); + let mut full = scrolled_transcript(sticky); + assert_eq!(shown(&rt), shown(&full)); + let range = rt.commit.virtuals["#0/scroll/rows"].range.clone(); + let mut fast = 0; + for w in (1..=40).map(|k| 700.0 - 5.0 * k as f32) { + fast += u32::from(resize(&mut rt, w, 2.0) == 0); + assert_eq!(full_resize(&mut full, (w, 600.0)), 1); + assert_eq!(shown(&rt), shown(&full), "at {w}, sticky {sticky}"); + } + assert!(fast >= 30, "{fast} of 40 steps skipped the view (sticky {sticky})"); + assert!(rt.commit.virtuals["#0/scroll/rows"].range.start >= range.start.saturating_sub(4)); + } +} + +/// Rows that grow as the window narrows lay out only until the ones outside the overscan add +/// up to a viewport; then the view runs and the window lets them go. +#[test] +fn a_narrowing_window_lets_go_of_rows_the_overscan_no_longer_holds() { + let mut rt = scrolled_transcript(false); + let mut ran = 0; + for w in (1..=80).map(|k| 700.0 - 5.0 * k as f32) { + ran += resize(&mut rt, w, 2.0); + let v = &rt.commit.virtuals["#0/scroll/rows"]; + let offset = rt.scroll.scrolls[&rt.tree.path_ids["#0/scroll"]].offset as f32 - v.top; + assert!(v.spare(offset, false) <= v.viewport, "at {w}"); + } + assert!((1..20).contains(&ran), "the view ran {ran} times in 80 steps"); +} + +/// A resize that brings the viewport near the edge of the mounted rows runs the view to mount +/// more. +#[test] +fn a_resize_that_moves_a_virtual_window_runs_the_view() { + let mut rt = scrolled_transcript(false); + let mut full = scrolled_transcript(false); + let before = rt.commit.virtuals["#0/scroll/rows"].range.clone(); + rt.set_viewport((700.0, 1800.0), 2.0); + assert_eq!(views(|| { rt.frame(1.0 / 120.0); }), 1); + assert_eq!(full_resize(&mut full, (700.0, 1800.0)), 1); + assert_ne!(rt.commit.virtuals["#0/scroll/rows"].range, before, "the window moved"); + assert_eq!(shown(&rt), shown(&full)); +} + +/// A text leaving at a breakpoint fades out with its text, though the resize took the text +/// layouts before the view ran. +#[test] +fn text_leaving_at_a_breakpoint_keeps_its_layout() { + fn view(_: &u32, cx: &mut Cx<u32>) -> El { + let narrow = cx.layout_with("root", |r| r[2] < 500.0).unwrap_or(false); + let label = (!narrow).then(|| text("Only while wide, long enough to wrap when it has to").key("wide").w_full().wrap()); + col().key("root").w_full().h_full().children(label).child(text("always").key("always")) + } + let mut rt = Runtime::new(0, view, (700.0, 600.0), Env::new(true, 2.0)); + rt.frame(0.0); + rt.frame(1.0 / 120.0); + let wide = node(&rt, "wide").id; + resize(&mut rt, 400.0, 2.0); + assert!(rt.is_exiting(wide)); + assert!(node(&rt, "wide").text_layout.is_some(), "the exiting text still has lines to draw"); +} + +/// A view sized from `Cx::layout_size` runs when the resize changes the size it read, and +/// shows the new one. +#[test] +fn a_layout_read_the_resize_moves_runs_the_view() { + fn view(_: &u32, cx: &mut Cx<u32>) -> El { + ran(); + let w = cx.layout_size("bar").map_or(-1.0, |s| s[0]); + col().w_full().child(el().key("bar").w_full().h(10.0)).child(text(format!("{w}")).key("label")) + } + let mut rt = Runtime::new(0, view, (700.0, 600.0), Env::new(true, 2.0)); + rt.frame(0.0); + rt.frame(1.0 / 120.0); + assert_eq!(content(&rt, "label"), "700"); + assert!(resize(&mut rt, 600.0, 2.0) >= 1); + assert_eq!(content(&rt, "label"), "600"); +} + +#[test] +fn a_layout_read_the_resize_leaves_alone_keeps_the_view() { + fn view(_: &u32, cx: &mut Cx<u32>) -> El { + ran(); + let w = cx.layout_size("side").map_or(-1.0, |s| s[0]); + row().w_full().child(el().key("side").w(120.0).h(10.0)).child(text(format!("{w}")).key("label").w_full().wrap()) + } + let mut rt = Runtime::new(0, view, (700.0, 600.0), Env::new(true, 2.0)); + rt.frame(0.0); + rt.frame(1.0 / 120.0); + assert_eq!(content(&rt, "label"), "120"); + assert_eq!(resize(&mut rt, 600.0, 2.0), 0); + assert_eq!(content(&rt, "label"), "120"); +} + +/// A scroll moving what a view read in the frame the window resizes runs the view, though the +/// resize alone leaves the read alone. +#[test] +fn a_resize_in_the_frame_a_scroll_moves_a_layout_read_runs_the_view() { + fn view(_: &u32, cx: &mut Cx<u32>) -> El { + ran(); + let y = cx.window_layout("r5").map_or(-1.0, |r| r[1]); + let rows = col().w_full().children((0..50).map(|k| el().key(format!("r{k}")).w(100.0).h(20.0))); + col().w_full().children([ + col().key("scroll").w_full().h(200.0).scroll(crate::ScrollSpec { stick_bottom: false }).child(rows), + text(format!("{y}")).key("label"), + ]) + } + let mut rt = Runtime::new(0, view, (700.0, 600.0), Env::new(true, 2.0)); + rt.frame(0.0); + rt.frame(1.0 / 120.0); + assert_eq!(content(&rt, "label"), "100"); + rt.wheel(100.0, 100.0, -50.0); + assert!(resize(&mut rt, 600.0, 2.0) >= 1); + assert_eq!(content(&rt, "label"), "50"); +} + +/// A breakpoint: the view lays two panes out side by side above 500 pt and stacked below, +/// reading only which side of it the window is on (`Cx::layout_with`). +#[test] +fn crossing_a_breakpoint_runs_the_view_and_resizing_within_one_does_not() { + fn view(_: &u32, cx: &mut Cx<u32>) -> El { + ran(); + let narrow = cx.layout_with("root", |r| r[2] < 500.0).unwrap_or(false); + let panes = [el().key("a").h(50.0).grow(1.0), el().key("b").h(50.0).grow(1.0)]; + let body = if narrow { col().w_full().children(panes) } else { row().w_full().children(panes) }; + col().key("root").w_full().h_full().child(body) + } + let mut rt = Runtime::new(0, view, (700.0, 600.0), Env::new(true, 2.0)); + rt.frame(0.0); + rt.frame(1.0 / 120.0); + let stacked = |rt: &Runtime<u32>| node(rt, "b").target[1] > node(rt, "a").target[1]; + assert!(!stacked(&rt)); + assert_eq!(resize(&mut rt, 600.0, 2.0), 0, "still wide"); + assert!(resize(&mut rt, 400.0, 2.0) >= 1, "crossed the breakpoint"); + assert!(stacked(&rt)); + assert_eq!(resize(&mut rt, 450.0, 2.0), 0, "still narrow"); + assert!(stacked(&rt)); + assert!(resize(&mut rt, 650.0, 2.0) >= 1); + assert!(!stacked(&rt)); +} + +/// A view showing the caret's place runs when the resize moves the field it is in. +#[test] +fn a_caret_read_the_resize_moves_runs_the_view() { + fn view(s: &TextEdit, cx: &mut Cx<TextEdit>) -> El { + ran(); + let x = cx.caret("field").map_or(-1.0, |r| r[0]); + col().w_full().items_center().children([ + text_input(s, TextStyle::new(14.0, 400.0)).key("field").size(200.0, 40.0).on_edit(|s: &mut TextEdit| s), + text(format!("{x}")).key("label"), + ]) + } + let mut edit = TextEdit::new("hello"); + edit.focused = true; + let mut rt = Runtime::new(edit, view, (700.0, 600.0), Env::new(true, 2.0)); + rt.frame(0.0); + rt.frame(1.0 / 120.0); + let before = content(&rt, "label"); + assert_ne!(before, "-1"); + assert!(resize(&mut rt, 500.0, 2.0) >= 1); + let after = content(&rt, "label"); + assert_ne!(after, before); + let caret = rt.edit.caret.as_ref().unwrap().1[0]; + assert_eq!(after, format!("{caret}"), "the view shows where the caret is now"); +} + +/// Layout fits an `aspect_fit` element by rewriting its style, which a resize has to undo. +#[test] +fn a_resize_refits_aspect_fit_elements_as_a_full_commit_would() { + fn view(_: &u32, _: &mut Cx<u32>) -> El { + ran(); + col().w_full().h_full().items_center().child(el().key("pic").aspect_fit(2.0)).child(text("caption").key("cap")) + } + let mut rt = Runtime::new(0, view, (700.0, 600.0), Env::new(true, 2.0)); + let mut full = Runtime::new(0, view, (700.0, 600.0), Env::new(true, 2.0)); + rt.frame(0.0); + full.frame(0.0); + for w in [600.0, 900.0, 300.0] { + resize(&mut rt, w, 2.0); + full.invalidate(); + resize(&mut full, w, 2.0); + assert_eq!(layout(&rt), layout(&full), "at {w}"); + } +} + +/// Moving `Node`s on resize skips cloning paths/specs, keeps a fixed-width sidebar's scene rects +/// and focused `TextEdit` intact, and restores moved nodes cleanly if a virtual window shifts. +#[test] +fn a_resize_moves_nodes_keeps_inputs_and_restores_on_virtual_window_fallback() { + struct App { + edit: TextEdit, + } + fn view(s: &App, _: &mut Cx<App>) -> El { + ran(); + let side = col().key("side").w(180.0).h_full().children( + (0..20).map(|i| row().key(format!("s{i}")).w_full().h(24.0).child(text(format!("Item {i}")))), + ); + let list = col().key("rows").w_full().growth(crate::el::GrowthSpec::default()).virtual_rows( + 200, + 32.0, + |_: &App, i| std::borrow::Cow::Owned(format!("r{i}")), + |_: &App, i| text(format!("{i}: {}", "wrapping row prose ".repeat(1 + i % 3))).w_full().wrap(), + ); + row().w_full().h_full().children([ + side, + col().key("main").grow(1.0).h_full().children([ + text_input(&s.edit, TextStyle::new(14.0, 400.0)).key("composer").w_full().h(36.0).on_edit(|a: &mut App| &mut a.edit), + col().key("scroll").w_full().grow(1.0).min_h(0.0).scroll(crate::ScrollSpec { stick_bottom: false }).child(list), + ]), + ]) + } + let mut edit = TextEdit::new("draft"); + edit.focused = true; + let mut rt = Runtime::new(App { edit: edit.clone() }, view, (800.0, 600.0), Env::new(true, 2.0)); + let mut full = Runtime::new(App { edit }, view, (800.0, 600.0), Env::new(true, 2.0)); + rt.frame(0.0); + full.frame(0.0); + rt.wheel(400.0, 300.0, -600.0); + full.wheel(400.0, 300.0, -600.0); + rt.frame(1.0 / 120.0); + full.frame(1.0 / 120.0); + + // Narrow steps keep the window (0 view runs); a huge jump shifts the window and falls back cleanly. + for &(w, h) in &[(760.0, 600.0), (700.0, 600.0), (420.0, 1200.0), (780.0, 600.0)] { + rt.set_viewport((w, h), 2.0); + rt.frame(1.0 / 120.0); + full.commit.set_reuse_scale(f32::NAN); + full.set_viewport((w, h), 2.0); + full.frame(1.0 / 120.0); + assert_eq!(shown(&rt), shown(&full), "at {w}x{h}"); + assert_eq!(rt.kbd.focus.path(), Some("#0/main/composer")); + } +} + +/// One decision for both shortcuts: a resize relays out, a quiet commit with virtual rows +/// remounts, and anything the view reads that changed runs it either way. +#[test] +fn a_commit_picks_its_kind_once_from_what_changed() { + use crate::runtime::relayout::CommitKind; + let mut rt = scrolled_transcript(false); + let (tx, settle) = (Tx::default(), Tx { commit: Commit::SettleAnimated, ..Tx::default() }); + rt.commit.set_state_unchanged(true); + assert_eq!(rt.commit_kind(&tx), CommitKind::Remount); + rt.commit.relayout = true; + assert_eq!(rt.commit_kind(&tx), CommitKind::Relayout, "a resize never remounts"); + for relayout in [true, false] { + rt.commit.relayout = relayout; + assert_eq!(rt.commit_kind(&settle), CommitKind::Rebuild); + rt.commit.set_read_moved(true); + assert_eq!(rt.commit_kind(&tx), CommitKind::Rebuild, "a read moved"); + rt.commit.set_read_moved(false); + rt.commit.set_reuse_scale(f32::NAN); + assert_eq!(rt.commit_kind(&tx), CommitKind::Rebuild, "a new scale"); + rt.commit.set_reuse_scale(rt.env.scale); + rt.commit.set_state_unchanged(false); + assert_eq!(rt.commit_kind(&tx), CommitKind::Rebuild, "the state changed"); + rt.commit.set_state_unchanged(true); + } + let mut plain = Runtime::new(0, paragraphs, (700.0, 600.0), Env::new(true, 2.0)); + plain.frame(0.0); + plain.commit.set_state_unchanged(true); + assert_eq!(plain.commit_kind(&tx), CommitKind::Rebuild, "no virtual rows to remount"); +} diff --git a/app/vendor/rune/crates/rune/src/runtime/tests/relayout/live.rs b/app/vendor/rune/crates/rune/src/runtime/tests/relayout/live.rs new file mode 100644 index 0000000..afdc289 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/tests/relayout/live.rs @@ -0,0 +1,117 @@ +use super::*; +use crate::Live; + +struct Bindings { + spring: bool, + offset: Live<[f32; 2]>, + rect: Live<[f32; 4]>, + opacity: Live<f32>, + scale: Live<f32>, + blur: Live<f32>, + fill: Live<Color>, +} + +impl Default for Bindings { + fn default() -> Self { + Self { + spring: false, + offset: Live::new([7.0, 11.0]), + rect: Live::new([30.0, 40.0, 60.0, 70.0]), + opacity: Live::new(0.7), + scale: Live::new(0.8), + blur: Live::new(2.0), + fill: Live::new(Color::WHITE), + } + } +} + +fn view(s: &Bindings, _: &mut Cx<Bindings>) -> El { + ran(); + let offset = if s.spring { s.offset.smooth(Spring::new(0.4, 0.0)) } else { (&s.offset).into() }; + row().w_full().h_full().justify_end().child( + col().key("bound").w(100.0).h_full() + .live_offset(offset) + .live_opacity(&s.opacity) + .live_scale(&s.scale) + .live_blur(&s.blur) + .live_fill(&s.fill) + .child(el().key("thumb").absolute(0.0, 0.0).live_rect(&s.rect).fill(Color::WHITE)), + ) +} + +#[test] +fn resizing_during_a_live_spring_keeps_its_progress_and_velocity() { + let mut rt = Runtime::new(Bindings { spring: true, ..Bindings::default() }, view, (700.0, 600.0), Env::new(true, 2.0)); + let mut reference = Runtime::new(Bindings { spring: true, ..Bindings::default() }, view, (700.0, 600.0), Env::new(true, 2.0)); + for r in [&mut rt, &mut reference] { + r.frame(0.0); + r.state.offset.set([90.0, 110.0]); + } + for i in 0..90 { + if i == 8 { // Reverse while both springs are still moving. + rt.state.offset.set([20.0, 30.0]); + reference.state.offset.set([20.0, 30.0]); + } + assert_eq!(resize(&mut rt, 700.0 - i as f32, 2.0), 0); + reference.frame(1.0 / 120.0); + assert_eq!(rt.scene.get(node(&rt, "bound").id, prop::OFFSET), reference.scene.get(node(&reference, "bound").id, prop::OFFSET), "frame {i}: resize never relatches or restarts the spring"); + } +} + +#[test] +fn a_layout_read_retry_restores_the_moved_live_nodes() { + fn reading(s: &Bindings, cx: &mut Cx<Bindings>) -> El { + cx.layout_size("window"); + view(s, cx).key("window") + } + let mut rt = Runtime::new(Bindings::default(), reading, (700.0, 600.0), Env::new(true, 2.0)); + rt.frame(0.0); + assert!(resize(&mut rt, 500.0, 2.0) > 0, "changed layout reads still run the view"); + rt.state.offset.set([30.0, 50.0]); + rt.frame(1.0 / 120.0); + assert_eq!(rt.scene.get(node(&rt, "bound").id, prop::OFFSET), Some(rune_motion::Vec2::new(30.0, 50.0))); + assert_eq!(node(&rt, "bound").vis.fill, Color::WHITE); +} + +fn compare(rt: &Runtime<Bindings>, full: &Runtime<Bindings>) { + assert_eq!(layout(rt), layout(full)); + for key in ["bound", "thumb"] { + assert_eq!(rt.presented(key), full.presented(key), "drawn {key}"); + let (a, b) = (node(rt, key), node(full, key)); + assert_eq!(a.vis.fill, b.vis.fill, "settled fill is retained"); + assert_eq!(rt.scene.get(a.id, prop::OFFSET), full.scene.get(b.id, prop::OFFSET)); + assert_eq!(rt.scene.get(a.id, prop::SCALE), full.scene.get(b.id, prop::SCALE)); + assert_eq!(rt.scene.get(a.id, prop::BLUR), full.scene.get(b.id, prop::BLUR)); + assert!(a.live.iter().zip(&b.live).all(|(a, b)| a.seen == b.seen)); + } +} + +#[test] +fn resize_keeps_live_bindings_without_running_the_view() { + let mut rt = Runtime::new(Bindings::default(), view, (700.0, 600.0), Env::new(true, 2.0)); + let mut full = Runtime::new(Bindings::default(), view, (700.0, 600.0), Env::new(true, 2.0)); + rt.frame(0.0); + full.frame(0.0); + for w in [600.0, 420.0, 300.0, 520.0] { + assert_eq!(resize(&mut rt, w, 2.0), 0, "live bindings allow relayout at {w}"); + // A real resize lands layout. The forced full build must use the same policy rather + // than treating the geometry change as an animated application-state update. + full.update(|_, tx| tx.instant()); + assert_eq!(resize(&mut full, w, 2.0), 1); + compare(&rt, &full); + for state in [&rt.state, &full.state] { + state.offset.set([w / 20.0, 15.0]); + state.rect.set([10.0, w / 10.0, 8.0, 40.0]); + state.opacity.set(w / 1000.0); + state.scale.set(w / 700.0); + state.blur.set(w / 100.0); + state.fill.set(Color::BLACK); + } + assert!(rt.live_pending(), "the retained subscription wakes after resize"); + assert_eq!(views(|| { rt.frame(1.0 / 120.0); }), 0); + full.frame(1.0 / 120.0); + compare(&rt, &full); + assert_eq!(rt.scene.get(node(&rt, "bound").id, prop::OFFSET), Some(rune_motion::Vec2::new(w / 20.0, 15.0))); + assert_eq!(rt.scene.get(node(&rt, "thumb").id, prop::FRAME), Some(MRect::new(10.0, w / 10.0, 8.0, 40.0))); + } +} diff --git a/app/vendor/rune/crates/rune/src/runtime/tests/remount.rs b/app/vendor/rune/crates/rune/src/runtime/tests/remount.rs new file mode 100644 index 0000000..b36d602 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/tests/remount.rs @@ -0,0 +1,318 @@ +//! Virtual-window shifts (`CommitWhy::VIRTUAL`) remount only newly entering `virtual_rows`, +//! leaving `view`, sibling subtrees and already-mounted rows untouched unless a read moves. +use super::*; +use crate::el::GrowthSpec; +use crate::{ScrollSpec, memo, row, text}; +use std::borrow::Cow; +use std::cell::{Cell, RefCell}; + +thread_local! { + static VIEWS: Cell<u32> = const { Cell::new(0) }; + static SIDES: Cell<u32> = const { Cell::new(0) }; + static BUILT_ROWS: RefCell<Vec<usize>> = const { RefCell::new(Vec::new()) }; +} + +fn take_views<R>(f: impl FnOnce() -> R) -> (u32, R) { + let before = VIEWS.get(); + let r = f(); + (VIEWS.get() - before, r) +} + +fn take_built() -> Vec<usize> { + BUILT_ROWS.with_borrow_mut(std::mem::take) +} + +fn shown_elements<S>(rt: &Runtime<S>) -> Vec<(String, [i32; 4], Option<String>)> { + let mut out: Vec<_> = rt + .elements() + .into_iter() + .filter(|e| e.visible[2] > 0.0 && e.visible[3] > 0.0 && !e.virtual_extent) + .map(|e| (e.path, e.rect.map(|x| (x * 100.0).round() as i32), e.text)) + .collect(); + out.sort_by(|a, b| a.0.cmp(&b.0)); + out +} + +fn plain_workspace(tick: &u32, _: &mut Cx<u32>) -> El { + VIEWS.set(VIEWS.get() + 1); + SIDES.set(SIDES.get() + 1); + let side = col().key("side").w(180.0).h_full().gap(4.0).children( + (0..24).map(|i| text(format!("Side {i}: {tick}")).key(format!("s{i}")).h(18.0)), + ); + let list = col().key("rows").w_full().px(8.0).growth(GrowthSpec::default()).virtual_rows( + 500, + 36.0, + |_: &u32, i| Cow::Owned(format!("r{i}")), + |t: &u32, i| { + BUILT_ROWS.with_borrow_mut(|b| b.push(i)); + row().w_full().h(36.0).gap(6.0).children([ + text(format!("Row {i}")).key("title").grow(1.0), + text(format!("v{t}")).key("ver"), + ]) + }, + ); + let footer = text(format!("Footer {tick}")).key("footer").h(28.0); + row().w_full().h_full().children([ + side, + col().key("main").grow(1.0).h_full().children([ + col() + .key("scroll") + .w_full() + .grow(1.0) + .min_h(0.0) + .scroll(ScrollSpec { stick_bottom: false }) + .child(list), + footer, + ]), + ]) +} + +#[test] +fn scrolling_virtual_rows_without_memo_skips_view_and_keeps_mounted_rows() { + let mut rt = Runtime::new(0u32, plain_workspace, (640.0, 420.0), Env::new(true, 2.0)); + let mut full = Runtime::new(0u32, plain_workspace, (640.0, 420.0), Env::new(true, 2.0)); + rt.frame(0.0); + full.frame(0.0); + while rt.frame(1.0 / 120.0) {} + while full.frame(1.0 / 120.0) {} + + SIDES.set(0); + take_built(); + let mut scroll_commits = 0u32; + let mut full_commits = 0u32; + for step in 0..40 { + take_built(); + let c0 = rt.stats.commits; + let (views_ran, _) = take_views(|| { + rt.wheel(400.0, 200.0, -90.0); + rt.frame(1.0 / 120.0); + }); + assert_eq!(views_ran, 0, "step {step}: scrolling must not re-run view"); + let built = take_built(); + if rt.stats.commits > c0 { + scroll_commits += 1; + let mounted_len = rt.commit.virtuals["#0/main/scroll/rows"].range.len(); + assert!( + built.len() < mounted_len, + "step {step}: built {} rows for a {mounted_len}-row window", + built.len() + ); + } else { + assert!(built.is_empty(), "step {step}: non-committing frame built {built:?}"); + } + + // Force full view on the reference runtime and check exact visible parity. + let fc0 = full.stats.commits; + full.commit.set_reuse_scale(f32::NAN); + full.wheel(400.0, 200.0, -90.0); + full.frame(1.0 / 120.0); + if full.stats.commits > fc0 { + full_commits += 1; + } + assert_eq!(shown_elements(&rt), shown_elements(&full), "step {step}"); + } + assert!(scroll_commits >= 10, "expected window shifts, got {scroll_commits}"); + assert_eq!(SIDES.get(), full_commits, "only full-commit reference steps ran the sidebar; rt ran 0"); + + // Hover and press on both a kept row and a newly scrolled-in row still work, and a state + // mutation runs the view again with updated content everywhere. + rt.update(|t, _| *t = 7); + let (views_ran, _) = take_views(|| { + rt.frame(1.0 / 120.0); + }); + assert_eq!(views_ran, 1); + full.update(|t, _| *t = 7); + full.frame(1.0 / 120.0); + assert_eq!(shown_elements(&rt), shown_elements(&full)); +} + +#[test] +fn virtual_remount_reruns_view_when_a_layout_read_of_a_culled_row_changes() { + fn view(_: &(), cx: &mut Cx<()>) -> El { + VIEWS.set(VIEWS.get() + 1); + let r0_mounted = cx.layout("r0").is_some(); + let list = col().key("rows").w_full().growth(GrowthSpec::default()).virtual_rows( + 200, + 40.0, + |_: &(), i| Cow::Owned(format!("r{i}")), + |_: &(), i| text(format!("Row {i}")).h(40.0), + ); + col().w_full().h_full().children([ + text(format!("r0={r0_mounted}")).key("status").h(24.0), + col() + .key("scroll") + .w_full() + .grow(1.0) + .min_h(0.0) + .scroll(ScrollSpec { stick_bottom: false }) + .child(list), + ]) + } + + let mut rt = Runtime::new((), view, (300.0, 240.0), Env::new(true, 1.0)); + rt.frame(0.0); + while rt.frame(1.0 / 120.0) {} + let status = |rt: &Runtime<()>| { + rt.elements().into_iter().find(|e| e.key.as_deref() == Some("status")).and_then(|e| e.text) + }; + assert_eq!(status(&rt).as_deref(), Some("r0=true")); + + // Scroll far enough down that `r0` leaves the mounted window; `settle_layout_reads` sees + // `cx.layout("r0")` become `None` and re-runs `view` to update `status`. + rt.wheel(150.0, 120.0, -3000.0); + rt.frame(1.0 / 120.0); + assert_eq!(status(&rt).as_deref(), Some("r0=false")); +} + +#[test] +fn virtual_remount_preserves_text_selection_across_scrolled_out_rows() { + fn view(_: &(), _: &mut Cx<()>) -> El { + VIEWS.set(VIEWS.get() + 1); + let list = col() + .key("rows") + .w_full() + .selection_group(true) + .growth(GrowthSpec::default()) + .virtual_rows( + 200, + 32.0, + |_: &(), i| Cow::Owned(format!("r{i}")), + |_: &(), i| text(format!("Line {i}")).key("txt").selectable(true).h(32.0), + ); + col().w_full().h_full().child( + col() + .key("scroll") + .w_full() + .grow(1.0) + .min_h(0.0) + .scroll(ScrollSpec { stick_bottom: false }) + .child(list), + ) + } + + let mut rt = Runtime::new((), view, (300.0, 200.0), Env::new(true, 1.0)); + rt.frame(0.0); + while rt.frame(1.0 / 120.0) {} + + // Drag-select starting at x=0 in row 0, then scroll row 0 out of the mounted window while dragging. + rt.pointer_down(0.0, 10.0); + rt.pointer_move(120.0, 50.0); + rt.frame(1.0 / 120.0); + for _ in 0..10 { + let (views_ran, _) = take_views(|| { + rt.wheel(150.0, 100.0, -300.0); + rt.pointer_move(120.0, 150.0); + rt.frame(1.0 / 120.0); + }); + assert_eq!(views_ran, 0); + } + rt.pointer_up(120.0, 150.0); + rt.frame(1.0 / 120.0); + assert!(rt.find("r0").is_none(), "r0 scrolled out of the mounted window"); + let copied = rt.selected_text().unwrap_or_default(); + assert!(copied.starts_with("Line 0\n"), "pinned row 0 stays in selection: {copied:?}"); +} + +#[test] +fn virtual_remount_keeps_view_and_mounted_row_memos_and_evicts_culled_ones() { + thread_local! { + static HEADER_BUILDS: Cell<u32> = const { Cell::new(0) }; + static ROW_MEMO_BUILDS: RefCell<Vec<usize>> = const { RefCell::new(Vec::new()) }; + } + struct S { + tick: u32, + clicked: Option<usize>, + edit: crate::TextEdit, + } + fn view(s: &S, _: &mut Cx<S>) -> El { + let _ = s.tick; + let header = memo("hdr", 0u32, || { + HEADER_BUILDS.set(HEADER_BUILDS.get() + 1); + text("Header").h(24.0) + }); + let list = col().key("rows").w_full().growth(GrowthSpec::default()).virtual_rows( + 300, + 32.0, + |_: &S, i| Cow::Owned(format!("r{i}")), + |s: &S, i| { + memo(format!("m{i}"), 0u32, || { + ROW_MEMO_BUILDS.with_borrow_mut(|b| b.push(i)); + row() + .w_full() + .h(32.0) + .on_press(move |s: &mut S| s.clicked = Some(i)) + .children([ + text(format!("Row {i}")).grow(1.0), + crate::text_input(&s.edit, crate::TextStyle::new(13.0, 400.0)).w(60.0), + ]) + }) + }, + ); + col().w_full().h_full().children([ + header, + col() + .key("scroll") + .w_full() + .grow(1.0) + .min_h(0.0) + .scroll(ScrollSpec { stick_bottom: false }) + .child(list), + ]) + } + + let mut rt = Runtime::new( + S { tick: 0, clicked: None, edit: crate::TextEdit::default() }, + view, + (320.0, 220.0), + Env::new(true, 1.0), + ); + rt.frame(0.0); + while rt.frame(1.0 / 120.0) {} + assert_eq!(HEADER_BUILDS.get(), 1); + + // Scroll far down across many windows: non-reusable `text_input` row memos that leave must be + // evicted, while `hdr` and currently mounted rows stay cached when `tick` finally runs `view`. + for _ in 0..30 { + rt.wheel(160.0, 120.0, -240.0); + rt.frame(1.0 / 120.0); + } + while rt.frame(1.0 / 120.0) {} + + let mounted = rt.commit.virtuals["#0/scroll/rows"].range.clone(); + assert!(mounted.start > 50, "scrolled past early rows: {mounted:?}"); + ROW_MEMO_BUILDS.with_borrow_mut(Vec::clear); + + // A state mutation runs `view`: neither `hdr` nor any row already in `mounted` rebuilds. + rt.update(|s, _| s.tick += 1); + rt.frame(1.0 / 120.0); + assert_eq!(HEADER_BUILDS.get(), 1, "view-level memo survived partial commits"); + let rebuilt: Vec<usize> = ROW_MEMO_BUILDS + .with_borrow_mut(std::mem::take) + .into_iter() + .filter(|i| mounted.contains(i)) + .collect(); + assert!(rebuilt.is_empty(), "mounted row memos survived partial commits, got {rebuilt:?}"); + // And culled early rows (`0..mounted.start`) were evicted rather than accumulating in MemoCache. + assert!( + rt.commit.memo_len() <= rt.commit.virtuals["#0/scroll/rows"].range.len() + 2, + "culled row memos evicted: memo len {}, mounted {:?}", + rt.commit.memo_len(), + rt.commit.virtuals["#0/scroll/rows"].range + ); + + // Press an on-screen scrolled-in row and confirm hit testing + handler dispatch works. + let (expected_idx, vis_row) = rt + .elements() + .into_iter() + .find_map(|e| { + let idx = e.key.as_deref()?.strip_prefix('r')?.parse::<usize>().ok()?; + (e.visible[3] >= 20.0).then_some((idx, e)) + }) + .expect("on-screen row"); + let (cx, cy) = (vis_row.visible[0] + 10.0, vis_row.visible[1] + 10.0); + rt.pointer_move(cx, cy); + rt.pointer_down(cx, cy); + rt.pointer_up(cx, cy); + rt.frame(1.0 / 120.0); + assert_eq!(rt.state.clicked, Some(expected_idx)); +} diff --git a/app/vendor/rune/crates/rune/src/runtime/tests/reveal_chain.rs b/app/vendor/rune/crates/rune/src/runtime/tests/reveal_chain.rs new file mode 100644 index 0000000..5f8e00e --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/tests/reveal_chain.rs @@ -0,0 +1,83 @@ +//! Streamed words fade in reading order across texts: a chunk that spans several paragraphs or +//! list items fades them one after another, so the fading edge is only ever on the newest words. +use super::*; + +#[derive(Default)] +struct Doc { + paras: Vec<String>, +} + +fn view(s: &Doc, _: &mut Cx<Doc>) -> El { + col().w_full().children(s.paras.iter().enumerate().map(|(i, p)| crate::text(p.clone()).wrap().w_full().reveal(0.3).key(format!("p{i}")))) +} + +fn words(n: usize) -> String { + (0..n).map(|i| format!("word{i}")).collect::<Vec<_>>().join(" ") +} + +/// Each paragraph's (first, last) word start time. +fn times(rt: &Runtime<Doc>, key: &str) -> Option<(f64, f64)> { + let id = rt.tree.nodes.iter().find(|n| n.key.as_deref() == Some(key))?.id; + let w = rt.motion.reveals_map().get(&id)?.words(); + Some((w.first()?.1, w.last()?.1)) +} + +fn runtime() -> Runtime<Doc> { + let mut rt = Runtime::new(Doc { paras: vec![String::new()] }, view, (600.0, 800.0), Env::new(true, 2.0)); + rt.frame(0.0); + rt.frame(1.0 / 60.0); + rt +} + +#[test] +fn one_chunk_over_three_paragraphs_fades_them_in_order() { + let mut rt = runtime(); + rt.state.paras = vec![words(12), words(12), words(12)]; + rt.invalidate(); + rt.frame(1.0 / 60.0); + let [a, b, c] = ["p0", "p1", "p2"].map(|k| times(&rt, k).unwrap_or_else(|| panic!("{k} reveals"))); + assert!(b.0 > a.1 && c.0 > b.1, "each paragraph starts after the one above ends: {a:?} {b:?} {c:?}"); +} + +#[test] +fn a_new_paragraph_waits_for_the_last_ones_tail() { + let mut rt = runtime(); + rt.state.paras = vec![words(30)]; + rt.invalidate(); + rt.frame(1.0 / 60.0); + let a = times(&rt, "p0").unwrap(); + rt.state.paras.push(words(4)); + rt.invalidate(); + rt.frame(1.0 / 60.0); + let b = times(&rt, "p1").unwrap(); + assert!(b.0 > a.1, "the next paragraph starts after the last word above: {a:?} then {b:?}"); +} + +#[test] +fn once_everything_has_shown_a_new_paragraph_starts_at_once() { + let mut rt = runtime(); + rt.state.paras = vec![words(8)]; + rt.invalidate(); + rt.frame(1.0 / 60.0); + for _ in 0..120 { + rt.frame(1.0 / 60.0); + } + rt.state.paras.push(words(4)); + rt.invalidate(); + rt.frame(1.0 / 60.0); + let (first, _) = times(&rt, "p1").unwrap(); + assert!((first - rt.t).abs() < 0.02, "no wait once nothing is fading: starts {first}, now {}", rt.t); +} + +/// Texts mounting together behind a run longer than a fade (a remount, a restored turn) fade +/// together, as before, rather than one after another through still frames. +#[test] +fn texts_behind_a_long_run_fade_together() { + let mut rt = runtime(); + rt.state.paras = vec![words(120), words(120), words(120)]; + rt.invalidate(); + rt.frame(1.0 / 60.0); + let [a, b, c] = ["p0", "p1", "p2"].map(|k| times(&rt, k).unwrap_or_else(|| panic!("{k} reveals"))); + assert!(a.1 - a.0 > 0.3, "the first paragraph's run outlasts a fade: {a:?}"); + assert!(b.0 < a.1 && c.0 < a.1, "the rest don't wait for it: {a:?} {b:?} {c:?}"); +} diff --git a/app/vendor/rune/crates/rune/src/runtime/tests/reveal_phase.rs b/app/vendor/rune/crates/rune/src/runtime/tests/reveal_phase.rs new file mode 100644 index 0000000..ed2264c --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/tests/reveal_phase.rs @@ -0,0 +1,893 @@ +//! Drives every short sequence of streaming-text events through the runtime and checks the +//! reveal after every one against a literal transcription of the code before `RevealPhase`: one +//! `RevealState { len, words, fade }` per text and the window's bare `reveal_chain: f64`, in +//! `commit/apply.rs`, the reveal step in `motion/tracks.rs`, the clock shift in +//! `motion/loop_clock.rs` and the drop in `commit/prune.rs`. +//! +//! The reference sees only what a letter says: the text's content, the fade, whether the text +//! was in the scene at the last commit, whether the commit lands its changes, and the clock. +//! The sequence walk's window keeps every commit's motion, has no virtual list, doesn't reduce +//! motion and runs every clock at 1×, so those stay constants on both sides; the directed walks +//! below vary the window's facts instead. A phase is compared by what shows: the shown bytes, +//! the words still fading and their fade, the window's chain, and every byte's alpha at the +//! text's clock. The fade an `Idle` state carried is the one thing not compared, because nothing +//! reads it until a word fades. +use std::sync::Mutex; +use std::sync::atomic::{AtomicUsize, Ordering}; + +use super::*; +use crate::el::col; +use crate::{TextStyle, text}; + +/// The gated walk's depth: every sequence up to this many letters. +const LENGTH: usize = 5; +/// The ignored deep run's depth: the same walk, one letter further. +const DEEP: usize = 6; +/// `El::reveal`: seconds each word takes to fade. +const FADE: f32 = 0.05; +/// Words one `Chunk` brings: at this fade, a chunk's run outlasts it, so a later commit meets a +/// chain longer than a fade. +const CHUNK: usize = 6; +/// The window's facts the reveal reads, as dev read them. +#[derive(Clone, Copy, Debug, PartialEq)] +struct Facts { + /// `TextSpec::reveal >= 0`: the text tracks a reveal at all. A negative reveal skips the + /// whole block, words, length and fade alike. + reveal: bool, + /// The fade dev gives each word (`TextSpec::reveal`, or 0.15 under reduced motion). + fade: f32, + reduced_motion: bool, + /// Some node's clock is scaled (`El::time_scale`), which takes the text out of the chain. + time_scaled: bool, +} + +/// The walk's window: the reveal tracks the text, nothing reduces motion, every clock runs 1×. +const STEADY: Facts = Facts { reveal: true, fade: FADE, reduced_motion: false, time_scaled: false }; + +/// What the letters that edit change. +#[derive(Clone, Default, PartialEq)] +struct Doc { + /// Words the stream has brought. + words: usize, + /// A short replacement shows instead of the stream. + replaced: bool, + /// The text's mount: every remount (and every reset) is a new node at a new path. + mounts: u32, + /// The text's parent column is in the tree; without it the keyed text leaves, and comes back + /// under the same path when the parent returns. + parent: bool, +} + +impl Doc { + fn content(&self) -> String { + if self.replaced { + return "a b".to_owned(); + } + let mut s = String::new(); + for i in 0..self.words { + if i > 0 { + s.push(' '); + } + s.push('w'); + } + s + } + + fn key(&self) -> String { format!("t{}", self.mounts) } + + fn path(&self) -> String { format!("root/p/{}", self.key()) } +} + +fn view(doc: &Doc, _: &mut Cx<Doc>) -> El { + let text = text(doc.content()).key(doc.key()).w_full().wrap().font(TextStyle::new(14.0, 400.0)).reveal(FADE); + col().key("root").w(200.0).children(doc.parent.then(|| col().key("p").child(text))) +} + +#[derive(Clone, Copy, Debug, PartialEq)] +enum Letter { + /// A chunk arrives: the stream appends words. + Chunk, + /// A frame ticks. + Tick, + /// A frame past the fade: the words that were fading finish. + Fade, + /// A chunk arrives while words still fade. + MidChunk, + /// The text is replaced with a shorter one. + Replace, + /// The stream ends: a commit that changes no content. + End, + /// The text remounts as a new node under a new key, still entering. + Remount, + /// Its parent unmounts instantly and returns: the keyed text comes back with the reveal state + /// it kept, under the same key. + Return, +} + +const ALPHABET: [Letter; 8] = [ + Letter::Chunk, + Letter::Tick, + Letter::Fade, + Letter::MidChunk, + Letter::Replace, + Letter::End, + Letter::Remount, + Letter::Return, +]; + +/// `RevealState` and `reveal_chain` as `Runtime` held them before `RevealPhase`. +#[derive(Clone, Debug, Default, PartialEq)] +struct Dev { + state: Option<DevReveal>, + chain: f64, +} + +#[derive(Clone, Debug, PartialEq)] +struct DevReveal { + len: usize, + words: Vec<(u32, f64)>, + fade: f32, +} + +impl Dev { + /// `commit/apply.rs`'s reveal block, as it was. + fn commit(&mut self, content: &str, was_present: bool, instant: bool, now: f64, facts: Facts) { + // Dev's `if spec.reveal >= 0.0`: a text with its reveal off keeps whatever it had, its + // length included, so bytes that arrived meanwhile fade in when it comes back. + if !facts.reveal { + return; + } + let fade = facts.fade; + // The walk's window keeps every commit's motion, so no commit is unprompted. + let mounted_late = !was_present && !instant; + let st = self.state.get_or_insert_with(|| DevReveal { + len: if mounted_late { 0 } else { content.len() }, + words: Vec::new(), + fade, + }); + st.fade = fade; + if instant || content.len() < st.len || !content.is_char_boundary(st.len) { + st.len = content.len(); + st.words.clear(); + } else if content.len() > st.len && fade > 0.0 { + let mut starts = Vec::new(); + word_starts(content, st.len, &mut starts); + let own = st.words.last().map_or(now, |w| w.1.max(now)); + let chained = !facts.time_scaled && self.chain - now <= f64::from(fade); + let chain = if chained { self.chain.max(now) } else { now }; + let queued = ((chain - now) / 0.0055) as usize; + let pending = st.words.iter().filter(|w| w.1 > now).count() + starts.len() + queued; + let stagger = if facts.reduced_motion { + 0.0 + } else { + let k = (pending as f32 / 24.0).clamp(0.0, 1.0); + (0.020 + (0.0055 - 0.020) * k) as f64 + }; + let mut tn = if chain > own { chain + stagger } else { own }; + for b in starts { + st.words.push((b, tn)); + tn += stagger; + } + if !facts.time_scaled && let Some(last) = st.words.last() { + self.chain = self.chain.max(last.1); + } + st.len = content.len(); + } else { + st.len = content.len(); + } + } + + /// `reveals_active`'s step, as it was. + fn tick(&mut self, now: f64) { + let Some(st) = &mut self.state else { return }; + let fade = st.fade as f64; + let done = st.words.iter().take_while(|w| now - w.1 >= fade).count(); + if done > 0 && done == st.words.len() { + st.words.clear(); + } + } + + /// `sync_time_scales`: its clock changed scale, so its word times move by `shift`. + fn shift(&mut self, shift: f64) { + let Some(st) = &mut self.state else { return }; + for w in &mut st.words { + w.1 += shift; + } + } + + /// `prune_exited`: the node left the scene. + fn left(&mut self) { self.state = None; } + + /// A word's alpha, as `reveal_alpha` gave it. + fn alpha(&self, byte: u32, now: f64) -> f32 { + let Some(st) = &self.state else { return 1.0 }; + let i = st.words.partition_point(|w| w.0 <= byte); + if i == 0 { + return 1.0; + } + let t0 = st.words[i - 1].1; + if st.fade <= 0.0 { + return if now >= t0 { 1.0 } else { 0.0 }; + } + ease_out(((now - t0) / st.fade as f64) as f32) + } +} + +/// `word_starts`, as it was. +fn word_starts(s: &str, from: usize, out: &mut Vec<u32>) { + let mut prev_space = true; + for (i, c) in s[from..].char_indices() { + let space = c.is_whitespace(); + if !space && prev_space { + out.push((from + i) as u32); + } + prev_space = space; + } +} + +/// `ease_out`, as it was. +fn ease_out(x: f32) -> f32 { + let x = x.clamp(0.0, 1.0); + 1.0 - (1.0 - x) * (1.0 - x) * (1.0 - x) +} + +struct Walk { + rt: Runtime<Doc>, + doc: Doc, + dev: Dev, + /// The text was in the scene at the last commit. + present: bool, + /// The text's node, kept while it is out of the tree: its reveal state outlives the node. + id: Option<NodeId>, +} + +impl Walk { + fn new() -> Self { + let mut rt = Runtime::new(Doc::default(), view, (200.0, 200.0), Env::new(true, 1.0)); + rt.frame(0.0); + rt.frame(0.0); + assert!(!rt.reduced_motion && !rt.host.system_reduced_motion, "the walk takes a window that doesn't reduce motion"); + assert!(!rt.motion.motion_needs_cause, "the walk takes a window where every commit keeps its motion"); + assert!(!rt.motion.time_scaled() && rt.time_scale == 1.0, "the walk takes a text on the window's clock"); + let mut walk = Self { rt, doc: Doc::default(), dev: Dev::default(), present: true, id: None }; + walk.reset(); + walk + } + + /// A fresh text node with the stream at rest and the reveal as a new window's: every sequence + /// starts from the same state on both sides. + fn reset(&mut self) { + self.doc = Doc { mounts: self.doc.mounts + 1, parent: true, ..Doc::default() }; + self.rt.motion.clear_reveals_for_test(); + self.dev = Dev::default(); + self.present = false; + self.commit(true).expect("a reset starts level"); + // One long frame: the faded-out texts of the last sequence leave the scene, so their + // nodes and reveal state don't pile up across sequences. Nothing fades on the new text. + self.rt.frame(1.0); + assert_eq!(self.rt.motion.reveals_map().len(), 1, "only the live text keeps reveal state"); + } + + /// An edit and its frame: the commit at the frame's clock, then the frame's reveal step at + /// the same time (a `dt` of zero). + fn commit(&mut self, instant: bool) -> Result<(), String> { self.frame_commit(instant, true) } + + /// `commit`, with the text out of the tree: its commit never reaches the reveal, while the + /// frame still ticks the state it kept. + fn commit_absent(&mut self, instant: bool) -> Result<(), String> { self.frame_commit(instant, false) } + + fn frame_commit(&mut self, instant: bool, in_tree: bool) -> Result<(), String> { + let now = self.rt.t; + let doc = self.doc.clone(); + let content = doc.content(); + let was_present = self.present; + let commits = self.rt.stats.commits; + self.rt.update(|s, tx| { + *s = doc.clone(); + if instant { + tx.instant(); + } + }); + self.rt.frame(0.0); + if self.rt.stats.commits != commits + 1 { + return Err(format!("an edit committed {} times", self.rt.stats.commits - commits)); + } + if in_tree { + self.dev.commit(&content, was_present, instant, now, STEADY); + self.present = true; + } + self.dev.tick(now); + self.compare() + } + + /// A frame with no edit: only the reveal steps, at the frame's new time. + fn tick(&mut self, dt: f64) -> Result<(), String> { + let commits = self.rt.stats.commits; + self.rt.frame(dt); + if self.rt.stats.commits != commits { + return Err(format!("a frame with no edit committed {} times", self.rt.stats.commits - commits)); + } + let now = self.rt.t; + self.dev.tick(now); + self.compare() + } + + /// Plays one letter on the runtime and the reference. + fn play(&mut self, letter: Letter) -> Result<(), String> { + match letter { + Letter::Chunk => { + self.doc.words += CHUNK; + self.commit(false) + } + Letter::Tick => self.tick(1.0 / 60.0), + Letter::Fade => self.tick(f64::from(FADE)), + Letter::MidChunk => { + self.tick(f64::from(FADE) / 2.0)?; + self.doc.words += 1; + self.commit(false) + } + Letter::Replace => { + self.doc.replaced = !self.doc.replaced; + self.commit(false) + } + Letter::End => self.commit(false), + Letter::Remount => { + self.doc.mounts += 1; + self.present = false; + self.dev.left(); + self.commit(false) + } + Letter::Return => { + self.doc.parent = false; + self.commit_absent(true)?; + self.present = false; + self.doc.parent = true; + self.commit(false) + } + } + } + + /// The visible reveal and the fade state, against dev's. + fn compare(&mut self) -> Result<(), String> { + let path = self.doc.path(); + let node = self.rt.tree.nodes.iter().find(|n| n.path == path).map(|n| n.id); + if let Some(id) = node { + self.id = Some(id); + } + let id = self.id.ok_or_else(|| format!("no text at {path}, and none before it"))?; + if node.is_none() && self.doc.parent { + return Err(format!("no text at {path}")); + } + let ours = self.rt.motion.reveals_map().get(&id); + let theirs = self.dev.state.as_ref(); + match (ours, theirs) { + (None, None) => {} + (Some(phase), Some(st)) => { + if phase.shown() != st.len { + return Err(format!("shown {}, dev {}", phase.shown(), st.len)); + } + let words = phase.words(); + if words != st.words.as_slice() { + return Err(format!("words {words:?}, dev {:?}", st.words)); + } + if let RevealPhase::Fading { fade, .. } = phase && *fade != st.fade { + return Err(format!("fade {fade}, dev {}", st.fade)); + } + } + (phase, st) => return Err(format!("reveal {phase:?}, dev {st:?}")), + } + if self.rt.motion.reveal_chain_until() != self.dev.chain { + return Err(format!("chain {}, dev {}", self.rt.motion.reveal_chain_until(), self.dev.chain)); + } + // Out of the tree, nothing draws: its state is all there is to compare. + let Some(_) = node else { return Ok(()) }; + let now = self.rt.scene.store().node_time(id); + for byte in 0..=self.doc.content().len() as u32 { + let ours = ours.and_then(RevealPhase::fade).map_or(1.0, |fade| fade.alpha(byte, now)); + let theirs = self.dev.alpha(byte, now); + if ours != theirs { + return Err(format!("alpha at byte {byte}: {ours}, dev {theirs}")); + } + } + Ok(()) + } +} + +/// Plays every sequence that starts with `sequence`, recording the first one that differs. +fn visit(walk: &mut Walk, alphabet: &[Letter], depth: usize, sequence: &mut Vec<Letter>, ran: &mut usize, failure: &mut Option<String>) { + if failure.is_some() { + return; + } + *ran += 1; + walk.reset(); + for &letter in sequence.iter() { + if let Err(why) = walk.play(letter) { + *failure = Some(format!("{sequence:?}: {why}")); + return; + } + } + if sequence.len() == depth { + return; + } + for &letter in alphabet { + sequence.push(letter); + visit(walk, alphabet, depth, sequence, ran, failure); + sequence.pop(); + } +} + +fn walk_all(alphabet: &[Letter], depth: usize) { + let next = AtomicUsize::new(0); + let results = Mutex::new(Vec::new()); + let workers = std::thread::available_parallelism().map_or(4, |n| n.get()).min(8); + std::thread::scope(|scope| { + for _ in 0..workers { + scope.spawn(|| { + let mut walk = Walk::new(); + let (mut ran, mut failure) = (0, None); + while let Some(&letter) = alphabet.get(next.fetch_add(1, Ordering::Relaxed)) { + visit(&mut walk, alphabet, depth, &mut vec![letter], &mut ran, &mut failure); + } + results.lock().unwrap().push((ran, failure)); + }); + } + }); + let mut total = 0; + let mut failures = Vec::new(); + for (ran, failure) in results.into_inner().unwrap() { + total += ran; + failures.extend(failure); + } + println!("{total} sequences up to length {depth}"); + assert!(failures.is_empty(), "sequences differ from dev: {failures:#?}"); + let expected: usize = (1..=depth as u32).map(|n| alphabet.len().pow(n)).sum(); + assert_eq!(total, expected, "every sequence ran"); +} + +#[test] +fn every_short_sequence_of_streaming_events_leaves_what_dev_left() { + walk_all(&ALPHABET, LENGTH); +} + +// The deep run: `cargo test -p rune --lib -- --ignored every_deeper_sequence`. +#[ignore = "the deep run"] +#[test] +fn every_deeper_sequence_of_streaming_events_leaves_what_dev_left() { + walk_all(&ALPHABET, DEEP); +} + +/// The state the walk compares against is the one dev left: a text whose stream a chunk filled +/// fades word by word, and the window's chain follows its newest word. +#[test] +fn a_chunk_fades_its_words_and_the_chain_follows() { + let mut walk = Walk::new(); + walk.play(Letter::Chunk).unwrap(); + let id = walk.rt.tree.nodes.iter().find(|n| n.path == walk.doc.path()).unwrap().id; + let RevealPhase::Fading { words, .. } = walk.rt.motion.reveals_map().get(&id).unwrap() else { + panic!("a chunk's words fade"); + }; + assert_eq!(words.len(), CHUNK, "every word of the chunk fades"); + assert!(walk.rt.motion.reveal_chain_until() >= words.last().unwrap().1, "the chain holds the newest word"); + let now = walk.rt.scene.store().node_time(id); + assert!(walk.rt.motion.reveal_chain_until() - now > f64::from(FADE), "a chunk's run outlasts a fade, so a later one meets a chain longer than it"); +} + +/// A remounted text fades in from none: it is new, and its entrance is still playing. +#[test] +fn a_remount_starts_its_words_from_none() { + let mut walk = Walk::new(); + walk.play(Letter::Chunk).unwrap(); + walk.play(Letter::Remount).unwrap(); + let id = walk.rt.tree.nodes.iter().find(|n| n.path == walk.doc.path()).unwrap().id; + let phase = walk.rt.motion.reveals_map().get(&id).unwrap(); + let RevealPhase::Fading { words, .. } = phase else { panic!("a remount fades its words in") }; + assert_eq!(words.first().unwrap().0, 0, "it starts at its first word"); +} + +/// A keyed child that comes back after its parent unmounted instantly keeps its words: the +/// runtime kept its reveal state, so nothing fades again. +#[test] +fn a_returning_child_keeps_its_words_after_an_instant_parent_unmount() { + #[derive(Default)] + struct S { + parent: bool, + } + fn view(s: &S, _: &mut Cx<S>) -> El { + col().key("root").w(300.0).children( + s.parent.then(|| col().key("p").child(text("a b c").key("t").w_full().wrap().reveal(FADE))), + ) + } + let mut rt = Runtime::new(S::default(), view, (300.0, 200.0), Env::new(true, 1.0)); + rt.frame(0.0); + rt.update(|s, _| s.parent = true); + rt.frame(0.0); + rt.frame(0.1); + let id = rt.tree.nodes.iter().find(|n| n.path == "root/p/t").unwrap().id; + assert!(rt.motion.reveals_map().get(&id).is_some_and(|p| p.caught_up(5)), "the first words have shown"); + rt.update(|s, tx| { + s.parent = false; + tx.instant(); + }); + rt.frame(0.0); + assert!(rt.motion.reveals_map().contains_key(&id), "the unmounted child keeps its reveal state"); + rt.update(|s, _| s.parent = true); + rt.frame(0.0); + let back = rt.tree.nodes.iter().find(|n| n.path == "root/p/t").unwrap().id; + assert_eq!(back, id, "the same key returns under the same id"); + let phase = rt.motion.reveals_map().get(&id).unwrap(); + assert!(phase.caught_up(5), "it comes back showing its words, not replaying them: {phase:?}"); +} + +/// An instant commit clears the words that were fading: dev's reset, whatever the content. +#[test] +fn an_instant_commit_clears_a_fade() { + #[derive(Default)] + struct S { + longer: bool, + } + fn view(s: &S, _: &mut Cx<S>) -> El { + let content = if s.longer { "a b c" } else { "a" }; + col().key("root").w(300.0).child(text(content).key("t").w_full().wrap().reveal(FADE)) + } + let mut rt = Runtime::new(S::default(), view, (300.0, 200.0), Env::new(true, 1.0)); + rt.frame(0.0); + rt.update(|s, _| s.longer = true); + rt.frame(0.0); + let id = rt.tree.nodes.iter().find(|n| n.path == "root/t").unwrap().id; + assert!(rt.motion.reveals_map().get(&id).is_some_and(RevealPhase::fading), "the new words fade"); + rt.update(|_, tx| tx.instant()); + rt.frame(0.0); + assert!(rt.motion.reveals_map().get(&id).is_some_and(|p| p.caught_up(5)), "the instant commit shows them at once"); +} + +/// A commit no input caused lands a new text whole: `Tx::unprompted` takes dev's reset, not the +/// fade a prompted mount gets. +#[test] +fn an_unprompted_commit_lands_a_new_text_whole() { + #[derive(Default)] + struct S { + shown: bool, + } + fn view(s: &S, _: &mut Cx<S>) -> El { + col().key("root").w(200.0).children(s.shown.then(|| text("a b c d").key("t").w_full().wrap().reveal(FADE))) + } + let mut rt = Runtime::new(S::default(), view, (200.0, 200.0), Env::new(true, 1.0)); + rt.motion.motion_needs_cause = true; + rt.frame(0.0); + rt.update(|s, _| s.shown = true); + rt.frame(0.0); + let id = rt.tree.nodes.iter().find(|n| n.path == "root/t").unwrap().id; + assert!(rt.motion.reveals_map().get(&id).is_some_and(|p| p.caught_up(7)), "no input caused it, so it shows whole"); +} + +/// A byte that no longer starts a word shows whole: dev's boundary check clears the fade rather +/// than slicing through a character. +#[test] +fn a_cut_through_a_character_shows_whole() { + #[derive(Default)] + struct S { + content: String, + } + fn view(s: &S, _: &mut Cx<S>) -> El { + col().key("root").w(200.0).child(text(s.content.clone()).key("t").w_full().wrap().reveal(FADE)) + } + let mut rt = Runtime::new(S::default(), view, (200.0, 200.0), Env::new(true, 1.0)); + rt.frame(0.0); + rt.update(|s, _| s.content = "aaa bbbb".to_owned()); + rt.frame(0.0); + let id = rt.tree.nodes.iter().find(|n| n.path == "root/t").unwrap().id; + assert!(rt.motion.reveals_map().get(&id).is_some_and(RevealPhase::fading), "the first chunk fades"); + // Byte 8 is inside "é" (bytes 7 and 8) now, so the old end still fading can't be kept. + rt.update(|s, _| s.content = "aaaaaaaé".to_owned()); + rt.frame(0.0); + assert!(rt.motion.reveals_map().get(&id).is_some_and(|p| p.caught_up("aaaaaaaé".len())), "a moved boundary shows whole"); +} + +/// A directed walk's window: one streaming text whose reveal, clock and window can change between +/// commits, stepped against the same transcription of dev. +#[derive(Clone, Default, PartialEq)] +struct Stream { + content: String, + /// `El::reveal`; negative leaves the text out of the reveal, as an app that stops streaming + /// its words does. + reveal: f32, + /// `El::time_scale(0)` on the text: its clock stops while the window's runs on. + paused: bool, + /// The window reduces motion (`Cx::reduced_motion`). + reduced: bool, +} + +impl Stream { + fn facts(&self) -> Facts { + Facts { + reveal: self.reveal >= 0.0, + fade: if self.reduced { 0.15 } else { self.reveal }, + reduced_motion: self.reduced, + time_scaled: self.paused, + } + } + + fn streamed(content: &str) -> Self { Self { content: content.to_owned(), reveal: FADE, ..Self::default() } } +} + +fn stream_view(s: &Stream, cx: &mut Cx<Stream>) -> El { + cx.reduced_motion(s.reduced); + let mut t = text(s.content.clone()).key("t").w_full().wrap(); + if s.reveal >= 0.0 { + t = t.reveal(s.reveal); + } + if s.paused { + t = t.time_scale(0.0); + } + col().key("root").w(300.0).child(t) +} + +struct Driven { + rt: Runtime<Stream>, + state: Stream, + dev: Dev, + present: bool, +} + +impl Driven { + fn new(state: Stream) -> Self { + let mut rt = Runtime::new(state.clone(), stream_view, (300.0, 200.0), Env::new(true, 1.0)); + rt.frame(0.0); + // The first commit is an instant one: the text lands whole. + let mut dev = Dev::default(); + dev.commit(&state.content, false, true, 0.0, state.facts()); + Self { rt, state, dev, present: true } + } + + fn id(&self) -> Option<NodeId> { + self.rt.tree.nodes.iter().find(|n| n.key.as_deref() == Some("t")).map(|n| n.id) + } + + /// The text's clock, which a commit and the frame step both read. + fn now(&self) -> f64 { self.id().map_or(self.rt.t, |id| self.rt.scene.store().node_time(id)) } + + /// Changes the text, commits, and checks against dev. + fn set(&mut self, f: impl FnOnce(&mut Stream)) -> Result<(), String> { + f(&mut self.state); + self.commit(false) + } + + fn commit(&mut self, instant: bool) -> Result<(), String> { + let before = self.now(); + let state = self.state.clone(); + let was_present = self.present; + self.rt.update(|s, tx| { + *s = state.clone(); + if instant { + tx.instant(); + } + }); + self.rt.frame(0.0); + let now = self.now(); + // Its clock changed scale this commit, so its words move with it. + if now != before { + self.dev.shift(now - before); + } + self.dev.commit(&state.content, was_present, instant, now, state.facts()); + self.dev.tick(now); + self.present = true; + self.check() + } + + fn tick(&mut self, dt: f64) -> Result<(), String> { + self.rt.frame(dt); + let now = self.now(); + self.dev.tick(now); + self.check() + } + + /// Dev's state against the runtime's, every byte's alpha, and the wake the reveal keeps: a + /// phase fades exactly while dev has words, and only a fade on a running clock asks for frames. + fn check(&self) -> Result<(), String> { + let Some(id) = self.id() else { return Err("no text".to_owned()) }; + let ours = self.rt.motion.reveals_map().get(&id); + let theirs = self.dev.state.as_ref(); + match (ours, theirs) { + (None, None) => {} + (Some(phase), Some(st)) => { + if phase.shown() != st.len { + return Err(format!("shown {}, dev {}", phase.shown(), st.len)); + } + if phase.words() != st.words.as_slice() { + return Err(format!("words {:?}, dev {:?}", phase.words(), st.words)); + } + if phase.fading() != !st.words.is_empty() { + return Err(format!("fading {}, dev words {:?}", phase.fading(), st.words)); + } + if let RevealPhase::Fading { fade, .. } = phase && *fade != st.fade { + return Err(format!("fade {fade}, dev {}", st.fade)); + } + } + (phase, st) => return Err(format!("reveal {phase:?}, dev {st:?}")), + } + if self.rt.motion.reveal_chain_until() != self.dev.chain { + return Err(format!("chain {}, dev {}", self.rt.motion.reveal_chain_until(), self.dev.chain)); + } + let now = self.now(); + for byte in 0..=self.state.content.len() as u32 { + let ours = ours.and_then(RevealPhase::fade).map_or(1.0, |fade| fade.alpha(byte, now)); + let theirs = self.dev.alpha(byte, now); + if ours != theirs { + return Err(format!("alpha at byte {byte}: {ours}, dev {theirs}")); + } + } + let fading = theirs.is_some_and(|st| !st.words.is_empty()); + let wakes = fading && !self.state.paused; + let source = self.rt.motion.anim_sources & AnimSource::REVEAL != 0; + if source != wakes { + return Err(format!("REVEAL source {source}, dev fading {fading}, paused {}", self.state.paused)); + } + Ok(()) + } +} + +/// A reveal turned off mid-fade stops tracking the text: the bytes that arrive meanwhile fade in +/// from their start when it comes back, whitespace and half words included. +#[test] +fn a_reveal_turned_off_mid_fade_keeps_what_arrives_for_later() { + let mut w = Driven::new(Stream::streamed("a b")); + w.set(|s| s.content = "a b c d".to_owned()).unwrap(); + w.set(|s| s.reveal = -1.0).unwrap(); + w.set(|s| s.content = "a b c d ".to_owned()).unwrap(); + w.tick(1.0).unwrap(); + w.set(|s| s.content = "a b c d ef".to_owned()).unwrap(); + w.set(|s| s.reveal = FADE).unwrap(); + assert!(w.rt.motion.reveals_map().values().any(|p| p.words().iter().any(|w| w.0 >= 8)), "the bytes that arrived while off fade in: {:?}", w.rt.motion.reveals_map()); + w.set(|s| s.content = "a b c d efg".to_owned()).unwrap(); + w.tick(0.3).unwrap(); +} + +/// A reveal of zero shows every word at once: a chunk's bytes are shown and no word waits. +#[test] +fn a_reveal_of_zero_shows_future_words_whole() { + let mut w = Driven::new(Stream::streamed("a b")); + w.set(|s| s.reveal = 0.0).unwrap(); + w.set(|s| s.content = "a b c d".to_owned()).unwrap(); + w.set(|s| s.content = "a b c d e".to_owned()).unwrap(); + w.tick(0.1).unwrap(); +} + +/// Under reduced motion every word of a chunk starts together, over the one fade the window uses. +#[test] +fn reduced_motion_fades_every_word_together() { + let mut w = Driven::new(Stream::streamed("a b")); + w.set(|s| s.reduced = true).unwrap(); + w.set(|s| s.content = "a b c d e f".to_owned()).unwrap(); + let times: Vec<f64> = w.rt.motion.reveals_map().values().flat_map(|p| p.words().iter().map(|w| w.1)).collect(); + assert!(times.len() > 1, "the chunk's words fade: {times:?}"); + assert!(times.windows(2).all(|p| p[0] == p[1]), "no stagger, so they start together: {times:?}"); + w.tick(0.2).unwrap(); + w.set(|s| s.reduced = false).unwrap(); + w.set(|s| s.content = "a b c d e f g".to_owned()).unwrap(); + w.tick(0.2).unwrap(); +} + +/// A clock paused on the text freezes its fade, and its resume moves every word time with the +/// clock: nothing behind it waits, and the chain is left alone while the clock is scaled. +#[test] +fn a_paused_clock_freezes_the_fade_and_its_resume_shifts_the_words() { + let mut w = Driven::new(Stream::streamed("a b")); + w.set(|s| s.content = "a b c d".to_owned()).unwrap(); + let before: Vec<f64> = w.rt.motion.reveals_map().values().flat_map(|p| p.words().iter().map(|w| w.1)).collect(); + let chain = w.rt.motion.reveal_chain_until(); + w.set(|s| s.paused = true).unwrap(); + w.tick(0.2).unwrap(); + assert_eq!(before, w.rt.motion.reveals_map().values().flat_map(|p| p.words().iter().map(|w| w.1)).collect::<Vec<_>>(), "a frozen clock doesn't fade"); + w.set(|s| s.content = "a b c d e".to_owned()).unwrap(); + let frozen = w.now(); + w.set(|s| s.content = "a b c d e f".to_owned()).unwrap(); + let added: Vec<f64> = w.rt.motion.reveals_map().values().flat_map(|p| p.words().iter().filter(|w| w.0 >= 9).map(|w| w.1)).collect(); + assert!(added.iter().all(|t| *t >= frozen), "a chunk on a scaled clock starts at its own time: {added:?} from {frozen}"); + assert_eq!(chain, w.rt.motion.reveal_chain_until(), "a scaled clock never joins the chain"); + w.set(|s| s.paused = false).unwrap(); + let resumed = w.now(); + assert!(resumed > frozen, "the clock jumped on resume: {resumed} from {frozen}"); + let shifted: Vec<f64> = w.rt.motion.reveals_map().values().flat_map(|p| p.words().iter().map(|w| w.1)).collect(); + assert!(shifted.iter().zip(&before).all(|(a, b)| a - b >= resumed - frozen - 1e-9), "every word moved with the clock: {shifted:?} from {before:?}"); + w.tick(0.2).unwrap(); + w.set(|s| s.content = "a b c d e f g".to_owned()).unwrap(); + w.tick(0.2).unwrap(); +} + +/// A child that never comes back leaves its reveal behind, and so keeps the path that maps to +/// it: only the newest `REVEALS_KEPT` that left are kept for a return, the oldest go. +#[test] +fn removed_children_keep_at_most_the_newest_reveals() { + use crate::runtime::prune::REVEALS_KEPT; + #[derive(Default)] + struct S { + n: usize, + present: bool, + } + fn view(s: &S, _: &mut Cx<S>) -> El { + col().key("root").w(300.0).children( + s.present.then(|| col().key(format!("p{}", s.n)).child(text("a b c").key("t").w_full().wrap().reveal(FADE))), + ) + } + let mut rt = Runtime::new(S::default(), view, (300.0, 200.0), Env::new(true, 1.0)); + rt.frame(0.0); + let mounted = rt.tree.path_ids.len(); + let count = REVEALS_KEPT * 2; + for n in 0..count { + rt.update(|s, _| { + s.n = n; + s.present = true; + }); + rt.frame(0.0); + rt.frame(0.1); + rt.update(|s, tx| { + s.present = false; + tx.instant(); + }); + rt.frame(0.0); + } + assert_eq!(rt.motion.reveals_map().len(), REVEALS_KEPT, "the newest keys' reveals stay and the oldest left"); + assert!(rt.motion.reveals_kept_len() <= REVEALS_KEPT, "{} orphans tracked", rt.motion.reveals_kept_len()); + // A dropped reveal's path leaves with the next commit's `prune_path_ids`. + rt.update(|s, _| s.n += 1); + rt.frame(0.0); + assert!(rt.tree.path_ids.len() <= mounted + REVEALS_KEPT, "{} ids kept for {mounted} mounted paths", rt.tree.path_ids.len()); + let newest = format!("root/p{}/t", count.saturating_sub(1)); + assert!(rt.tree.path_ids.contains_key(&newest), "the newest key's reveal stays for a return"); + assert!(!rt.tree.path_ids.contains_key("root/p0/t"), "the oldest key's reveal left with its path"); +} + +/// A child that comes back after its parent unmounted instantly keeps its words while its reveal +/// is still one of the newest `REVEALS_KEPT`, however many other keys have left since. +#[test] +fn a_child_returning_within_the_bound_keeps_its_words() { + use crate::runtime::prune::REVEALS_KEPT; + #[derive(Default)] + struct S { + parent: bool, + other: usize, + other_present: bool, + } + fn view(s: &S, _: &mut Cx<S>) -> El { + let mut kids = Vec::new(); + if s.parent { + kids.push(col().key("p").child(text("a b c").key("t").w_full().wrap().reveal(FADE))); + } + if s.other_present { + kids.push(col().key(format!("o{}", s.other)).child(text("a b c").key("t").w_full().wrap().reveal(FADE))); + } + col().key("root").w(300.0).children(kids) + } + let mut rt = Runtime::new(S::default(), view, (300.0, 200.0), Env::new(true, 1.0)); + rt.frame(0.0); + rt.update(|s, _| s.parent = true); + rt.frame(0.0); + rt.frame(0.1); + let id = rt.tree.nodes.iter().find(|n| n.path == "root/p/t").unwrap().id; + assert!(rt.motion.reveals_map().get(&id).is_some_and(|p| p.caught_up(5)), "the first words have shown"); + rt.update(|s, tx| { + s.parent = false; + tx.instant(); + }); + rt.frame(0.0); + for n in 0..REVEALS_KEPT / 2 { + rt.update(|s, _| { + s.other = n; + s.other_present = true; + }); + rt.frame(0.0); + rt.frame(0.1); + rt.update(|s, tx| { + s.other_present = false; + tx.instant(); + }); + rt.frame(0.0); + } + assert!(rt.motion.reveals_map().contains_key(&id), "the returning child's reveal is still within the bound"); + rt.update(|s, _| s.parent = true); + rt.frame(0.0); + let back = rt.tree.nodes.iter().find(|n| n.path == "root/p/t").unwrap().id; + assert_eq!(back, id, "the same key returns under the same id"); + let phase = rt.motion.reveals_map().get(&back).unwrap(); + assert!(phase.caught_up(5), "it comes back showing its words, not replaying them: {phase:?}"); +} diff --git a/app/vendor/rune/crates/rune/src/runtime/tests/scroll_carried.rs b/app/vendor/rune/crates/rune/src/runtime/tests/scroll_carried.rs new file mode 100644 index 0000000..ac836ae --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/tests/scroll_carried.rs @@ -0,0 +1,49 @@ +use super::*; +use crate::ScrollSpec; + +/// Where a zoom sits around a scroll viewport. +#[derive(Clone, Copy, Debug)] +enum Zoom { + /// The viewport inside a 1.6× zoom. + Around, + /// A 1.6× zoom inside the viewport, around its rows. + Within, + /// The viewport inside a 1.6× zoom turned a little. + Turned, +} + +fn zoomed(z: &Zoom, _: &mut Cx<Zoom>) -> El { + let rows = (0..30).fold(col().key("rows").w_full(), |c, i| c.child(el().key(format!("row{i}")).w_full().h(40.0))); + let rows = if matches!(z, Zoom::Within) { col().key("zoom").w_full().scale(1.6).child(rows) } else { rows }; + let list = col().key("scroll").size(300.0, 200.0).scroll(ScrollSpec { stick_bottom: false }).child(rows); + match z { + Zoom::Within => col().child(list), + Zoom::Around => col().key("zoom").scale(1.6).child(list), + Zoom::Turned => col().key("zoom").scale(1.6).rotate(0.3).child(list), + } +} + +#[test] +fn what_a_scroll_carries_is_measured_in_the_window_through_a_zoom() { + // A row that only rides a glide stays put against what it scrolls with, however a zoom or + // a turn around the viewport (or a zoom inside it) multiplies the offset on screen. + for z in [Zoom::Around, Zoom::Within, Zoom::Turned] { + let mut rt = Runtime::new(z, zoomed, (600.0, 600.0), Env::new(true, 1.0)); + rt.frame(0.0); + let row = |rt: &Runtime<Zoom>| rt.elements().into_iter().find(|e| e.key.as_deref() == Some("row3")).unwrap(); + let own = |e: &ElementInfo| [e.rect[0] + e.scrolled[0], e.rect[1] + e.scrolled[1]]; + let start = own(&row(&rt)); + rt.update(|_, tx| tx.scroll_to("scroll", 0.0, 300.0)); + let mut carried = 0.0f32; + for _ in 0..90 { + rt.frame(1.0 / 120.0); + let e = row(&rt); + let [x, y] = own(&e); + assert!((x - start[0]).abs() <= 1.0 && (y - start[1]).abs() <= 1.0, "{z:?}: the row rides the scroll alone, {start:?} → {:?}", [x, y]); + carried = carried.max(e.scrolled[0].hypot(e.scrolled[1])); + } + // A zoom inside the viewport scales about a centre the scroll carries too. + let screen = if matches!(z, Zoom::Within) { 300.0 } else { 480.0 }; + assert!((carried - screen).abs() < 1.0, "{z:?}: 300 pt of scroll is {screen} pt on screen, not {carried}"); + } +} diff --git a/app/vendor/rune/crates/rune/src/runtime/tests/scroll_children.rs b/app/vendor/rune/crates/rune/src/runtime/tests/scroll_children.rs new file mode 100644 index 0000000..068c1b9 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/tests/scroll_children.rs @@ -0,0 +1,357 @@ +use super::*; +use crate::el::{GrowthSpec, ScrollSpec, row}; + +fn fifty_rows_view(_: &(), _: &mut Cx<()>) -> El { + col() + .key("scroll") + .size(200.0, 200.0) + .scroll(ScrollSpec { stick_bottom: false }) + .children((0..50).map(|i| row().key(format!("r{i}")).w_full().h(30.0))) +} + +#[test] +fn scroll_with_fifty_direct_row_children_scrolls_to_the_last_row() { + let mut rt = Runtime::new((), fifty_rows_view, (200.0, 200.0), Env::new(true, 1.0)); + rt.frame(0.0); + let last = rt.elements().into_iter().find(|e| e.key.as_deref() == Some("r49")).unwrap(); + assert_eq!(last.rect[1], 1470.0); + + rt.wheel(100.0, 100.0, -10_000.0); + rt.frame(1.0 / 60.0); + let last = rt.elements().into_iter().find(|e| e.key.as_deref() == Some("r49")).unwrap(); + assert_eq!(last.rect[1] + last.rect[3], 200.0, "scrolled flush to the 50th direct child"); + assert_eq!(rt.scroll_at_bottom("scroll"), Some(true)); +} + +#[test] +fn scroll_x_with_fifty_direct_children_scrolls_to_the_last_child() { + fn view(_: &(), _: &mut Cx<()>) -> El { + row() + .key("strip") + .size(200.0, 60.0) + .scroll_x() + .children((0..50).map(|i| el().key(format!("c{i}")).w(40.0).h(60.0))) + } + let mut rt = Runtime::new((), view, (200.0, 60.0), Env::new(true, 1.0)); + rt.frame(0.0); + let last = rt.elements().into_iter().find(|e| e.key.as_deref() == Some("c49")).unwrap(); + assert_eq!(last.rect[0], 1960.0); + + rt.wheel_xy(100.0, 30.0, -10_000.0, 0.0); + rt.frame(1.0 / 60.0); + let last = rt.elements().into_iter().find(|e| e.key.as_deref() == Some("c49")).unwrap(); + assert_eq!(last.rect[0] + last.rect[2], 200.0, "scrolled flush to the 50th direct horizontal child"); +} + +#[test] +fn stick_bottom_with_several_direct_children_stays_pinned_as_rows_arrive() { + fn view(count: &usize, _: &mut Cx<usize>) -> El { + col() + .key("scroll") + .size(200.0, 150.0) + .scroll(ScrollSpec { stick_bottom: true }) + .children((0..*count).map(|i| row().key(format!("r{i}")).w_full().h(40.0))) + } + let mut rt = Runtime::new(6usize, view, (200.0, 150.0), Env::new(true, 1.0)); + rt.frame(0.0); + let last = rt.elements().into_iter().find(|e| e.key.as_deref() == Some("r5")).unwrap(); + assert_eq!(last.rect[1] + last.rect[3], 150.0, "opens pinned to the last direct child"); + + for next in 7..=10 { + rt.update(move |n, _| *n = next); + for _ in 0..60 { + rt.frame(1.0 / 120.0); + } + let key = format!("r{}", next - 1); + let last = rt.elements().into_iter().find(|e| e.key.as_deref() == Some(key.as_str())).unwrap(); + assert!( + (last.rect[1] + last.rect[3] - 150.0).abs() < 0.05, + "after adding {key}, bottom was {} instead of 150.0", + last.rect[1] + last.rect[3] + ); + assert_eq!(rt.scroll_at_bottom("scroll"), Some(true)); + } +} + +#[test] +fn scroll_into_view_reaches_the_fortieth_direct_child() { + let mut rt = Runtime::new((), fifty_rows_view, (200.0, 200.0), Env::new(true, 1.0)); + rt.frame(0.0); + rt.update(|_, tx| tx.scroll_into_view("r39")); + rt.frame(1.0 / 60.0); + let r39 = rt.elements().into_iter().find(|e| e.key.as_deref() == Some("r39")).unwrap(); + assert_eq!(r39.rect[1] + r39.rect[3], 200.0, "40th direct child brought into view at bottom edge"); +} + +#[test] +fn growth_stack_child_after_a_header_child_grows_and_stays_pinned() { + fn view(count: &usize, _: &mut Cx<usize>) -> El { + let stack = col() + .key("stack") + .w_full() + .growth(GrowthSpec::default()) + .children((0..*count).map(|i| row().key(format!("r{i}")).w_full().h(50.0))); + col() + .key("scroll") + .size(200.0, 200.0) + .scroll(ScrollSpec { stick_bottom: true }) + .child(el().key("banner").w_full().h(60.0)) + .child(stack) + } + let mut rt = Runtime::new(5usize, view, (200.0, 200.0), Env::new(true, 1.0)); + rt.frame(0.0); + let r4 = rt.elements().into_iter().find(|e| e.key.as_deref() == Some("r4")).unwrap(); + assert!((r4.rect[1] + r4.rect[3] - 200.0).abs() < 0.05); + + rt.update(|n, _| *n = 6); + rt.frame(1.0 / 120.0); + assert!(rt.animating, "growth stack child animates new row"); + for _ in 0..120 { + rt.frame(1.0 / 120.0); + } + let r5 = rt.elements().into_iter().find(|e| e.key.as_deref() == Some("r5")).unwrap(); + assert!((r5.rect[1] + r5.rect[3] - 200.0).abs() < 0.05); +} + +#[test] +fn scroll_xy_with_direct_children_scrolls_both_axes_and_warns_on_trailing_growth_sibling() { + let _warnings = layout_diagnostics::scope(); + fn view(bad: &bool, _: &mut Cx<bool>) -> El { + if *bad { + return col() + .key("scroll") + .size(200.0, 200.0) + .scroll(ScrollSpec { stick_bottom: false }) + .child(col().key("stack").w_full().growth(GrowthSpec::default()).child(el().h(50.0))) + .child(el().key("after").w_full().h(50.0)); + } + col() + .key("scroll") + .size(200.0, 200.0) + .scroll_xy() + .children((0..20).map(|i| row().key(format!("r{i}")).w(500.0).h(30.0))) + } + let mut rt = Runtime::new(false, view, (200.0, 200.0), Env::new(true, 1.0)); + rt.frame(0.0); + rt.update(|_, tx| tx.scroll_to_instant("scroll", 9_999.0, 9_999.0)); + rt.frame(1.0 / 60.0); + let r19 = rt.elements().into_iter().find(|e| e.key.as_deref() == Some("r19")).unwrap(); + assert_eq!((r19.rect[0] + r19.rect[2], r19.rect[1] + r19.rect[3]), (200.0, 200.0)); + assert!(!layout_diagnostics::warned_at("growth-sibling:")); + + rt.update(|bad, _| *bad = true); + rt.frame(1.0 / 60.0); + assert!(layout_diagnostics::warned_at("growth-sibling:")); +} + +#[test] +fn animated_header_above_pinned_growth_stack_keeps_last_row_on_bottom_every_frame() { + fn view(tall: &bool, _: &mut Cx<bool>) -> El { + let stack = col() + .key("stack") + .w_full() + .growth(GrowthSpec::default()) + .children((0..6).map(|i| row().key(format!("r{i}")).w_full().h(40.0))); + col() + .key("scroll") + .size(200.0, 200.0) + .scroll(ScrollSpec { stick_bottom: true }) + .child(el().key("header").w_full().h(if *tall { 120.0 } else { 40.0 })) + .child(stack) + } + let mut rt = Runtime::new(false, view, (200.0, 200.0), Env::new(true, 1.0)); + rt.frame(0.0); + rt.update(|tall, _| *tall = true); + for frame in 0..90 { + rt.frame(1.0 / 120.0); + let r5 = rt.elements().into_iter().find(|e| e.key.as_deref() == Some("r5")).unwrap(); + assert!( + (r5.rect[1] + r5.rect[3] - 200.0).abs() < 0.05, + "frame {frame}: last row bottom {} left viewport bottom 200.0", + r5.rect[1] + r5.rect[3] + ); + } +} + +#[test] +fn header_before_virtual_stack_reveals_unmounted_row_and_keeps_header_at_origin() { + fn view(_: &(), _: &mut Cx<()>) -> El { + let stack = col() + .key("rows") + .w_full() + .growth(GrowthSpec::default()) + .virtualize(20.0) + .children((0..100).map(|i| row().key(format!("r{i}")).w_full().h(20.0))); + col() + .key("scroll") + .size(200.0, 200.0) + .scroll(ScrollSpec { stick_bottom: false }) + .child(el().key("header").w_full().h(500.0)) + .child(stack) + } + let mut rt = Runtime::new((), view, (200.0, 200.0), Env::new(true, 1.0)); + rt.frame(0.0); + assert!(rt.elements().iter().all(|e| e.key.as_deref() != Some("r35")), "r35 starts unmounted"); + + // Scrolling near the bottom of the 500pt header must keep r0 mounted and visible. + rt.wheel(100.0, 100.0, -450.0); + rt.frame(1.0 / 60.0); + let r0 = rt.elements().into_iter().find(|e| e.key.as_deref() == Some("r0")).expect("r0 stays mounted below header"); + assert!((r0.rect[1] - 50.0).abs() < 0.05, "r0 at y={} instead of 50.0", r0.rect[1]); + + // Revealing an initially unmounted row accounts for the header height and does not shift the header by `before`. + rt.update(|_, tx| tx.scroll_into_view("r35")); + rt.frame(1.0 / 60.0); + assert!(rt.commit.virtuals["scroll/rows"].before > 0.0, "earlier virtual rows were culled"); + let r35 = rt.elements().into_iter().find(|e| e.key.as_deref() == Some("r35")).expect("r35 mounted and revealed"); + assert!((r35.rect[1] + r35.rect[3] - 200.0).abs() < 0.05, "r35 bottom {} != 200.0", r35.rect[1] + r35.rect[3]); + let header = rt.elements().into_iter().find(|e| e.key.as_deref() == Some("header")).unwrap(); + assert!((header.rect[1] - (-1020.0)).abs() < 0.05, "header top {} moved with virtual culling", header.rect[1]); +} + +#[test] +fn scroll_x_with_multiple_children_unwraps_w_full_text_column() { + fn view(_: &(), _: &mut Cx<()>) -> El { + row() + .key("strip") + .size(200.0, 80.0) + .scroll_x() + .child(el().key("badge").w(40.0).h(20.0)) + .child(col().key("wide").w_full().child(crate::el::text("unwrapped horizontal text ".repeat(12)).wrap())) + .child(col().key("short").w_full().child(crate::el::text("ok"))) + } + let mut rt = Runtime::new((), view, (200.0, 80.0), Env::new(true, 1.0)); + rt.frame(0.0); + let badge = rt.elements().into_iter().find(|e| e.key.as_deref() == Some("badge")).unwrap(); + let wide = rt.elements().into_iter().find(|e| e.key.as_deref() == Some("wide")).unwrap(); + let short = rt.elements().into_iter().find(|e| e.key.as_deref() == Some("short")).unwrap(); + assert_eq!(badge.rect[2], 40.0); + assert!(wide.rect[2] > 400.0, "w_full column in multi-child scroll_x unwraps past viewport width, got {}", wide.rect[2]); + assert_eq!(short.rect[2], 200.0, "w_full child keeps min-width 100% of viewport when narrower"); +} + + +#[test] +fn scroll_into_view_of_a_virtual_row_taller_than_the_viewport_lands_its_end_from_above() { + // Short rows, one 500pt row in a 200pt viewport, and a varying tail after it. + fn view(tail: &usize, _: &mut Cx<usize>) -> El { + let n = 31 + *tail; + let stack = col() + .key("rows") + .w_full() + .growth(GrowthSpec::default()) + .virtual_rows(n, 20.0, |_: &usize, i| format!("r{i}").into(), |_: &usize, i| { + row().w_full().h(if i == 30 { 500.0 } else { 20.0 }) + }); + col() + .key("scroll") + .size(200.0, 200.0) + .scroll(ScrollSpec { stick_bottom: false }) + .child(stack) + } + for tail in [0usize, 1, 2, 5] { + let mut rt = Runtime::new(tail, view, (200.0, 200.0), Env::new(true, 1.0)); + rt.frame(0.0); + rt.update(|_, tx| tx.scroll_into_view("r30")); + for _ in 0..30 { + rt.frame(1.0 / 120.0); + } + let r30 = rt.elements().into_iter().find(|e| e.key.as_deref() == Some("r30")).expect("r30 revealed"); + assert!( + (r30.rect[1] + r30.rect[3] - 200.0).abs() < 0.05, + "tail {tail}: moving down, the row's end lands at the viewport's bottom, not its top: {:?}", + r30.rect + ); + } +} + +#[test] +fn raised_and_anchored_overlays_occlude_horizontal_wheel_touch_fling_and_autoscroll() { + fn view(_: &(), _: &mut Cx<()>) -> El { + col().size(300.0, 200.0) + .child( + col().key("bg").size(300.0, 200.0) + .scroll(ScrollSpec { stick_bottom: false }).scroll_xy() + .child(el().size(1000.0, 1000.0)), + ) + .child(el().key("panel").absolute(0.0, 0.0).size(150.0, 150.0).raise().fill(Color::WHITE)) + .child(el().key("anchor").absolute(160.0, 0.0).size(20.0, 20.0)) + .child(el().key("pop").size(80.0, 80.0).fill(Color::WHITE) + .anchored("anchor", crate::Side::Bottom, crate::Align::Start, 0.0)) + } + let mut rt = Runtime::new((), view, (300.0, 200.0), Env::new(true, 1.0)); + rt.frame(0.0); + let bg = rt.tree.nodes.iter().find(|n| n.key.as_deref() == Some("bg")).unwrap().id; + + // Clear of overlays, bg is found on both axes. + assert_eq!(rt.scroll_at_axis(260.0, 160.0, true), Some(bg)); + assert_eq!(rt.scroll_at_axis(260.0, 160.0, false), Some(bg)); + + // Over the raised panel (50, 50) and anchored popover (180, 50), bg is occluded. + for (x, y, label) in [(50.0, 50.0, "raised panel"), (180.0, 50.0, "anchored popover")] { + assert_eq!(rt.scroll_at_axis(x, y, true), None, "horizontal scroll_at_axis over {label}"); + assert_eq!(rt.scroll_at_axis(x, y, false), None, "vertical scroll_at_axis over {label}"); + rt.wheel_xy(x, y, -60.0, 0.0); + rt.fling(x, y, -400.0); + rt.frame(1.0 / 60.0); + assert_eq!(rt.scroll.scrolls[&bg].x.offset, 0.0, "horizontal wheel over {label} must not scroll bg"); + assert_eq!(rt.scroll.scrolls[&bg].offset, 0.0, "fling over {label} must not scroll bg"); + } + + // Touch pan over the raised panel must not scroll bg. + rt.touch(1, crate::TouchPhase::Started, 50.0, 50.0, 0.0); + rt.touch(1, crate::TouchPhase::Moved, 10.0, 50.0, 0.02); + rt.touch(1, crate::TouchPhase::Moved, 10.0, 10.0, 0.04); + rt.touch(1, crate::TouchPhase::Ended, 10.0, 10.0, 0.06); + rt.frame(1.0 / 60.0); + assert_eq!((rt.scroll.scrolls[&bg].x.offset, rt.scroll.scrolls[&bg].offset), (0.0, 0.0), "touch over panel must not scroll bg"); + + // Middle-click autoscroll over the raised panel must not latch onto bg. + if cfg!(any(target_os = "windows", target_os = "linux")) { + rt.button_down(50.0, 50.0, crate::PointerButton::Middle); + assert!(rt.core().autoscroll_cursor().is_none(), "autoscroll over raised panel must not start on occluded bg"); + } +} + +#[test] +fn keep_on_screen_virtual_row_in_scaled_viewport_holds_its_position() { + fn view(inserted: &usize, _: &mut Cx<usize>) -> El { + let ins = *inserted; + let n = 60 + ins; + let stack = col().key("rows").w_full().growth(GrowthSpec::default()) + .virtual_rows(n, 50.0, move |_: &usize, i| { + if i < 2 { format!("r{i}").into() } + else if i < 2 + ins { format!("ins-{}", i - 2).into() } + else { format!("r{}", i - ins).into() } + }, |_: &usize, _| el().w_full().h(50.0)); + col().size(1200.0, 1200.0).child( + col().key("scroll").size(200.0, 200.0).scale(4.0).origin(0.0, 0.0) + .scroll(ScrollSpec { stick_bottom: false }) + .child(stack), + ) + } + let mut rt = Runtime::new(0usize, view, (1200.0, 1200.0), Env::new(true, 1.0)); + rt.frame(0.0); + // r4 is at layout y = 200. Scroll to 50 so r1 is the virtual reading anchor while r4 sits + // 150 unscaled points (= 600 scaled points) below the viewport top. + rt.update(|_, tx| tx.scroll_to_instant("scroll", 0.0, 50.0)); + rt.frame(1.0 / 60.0); + let rel_y = |rt: &Runtime<usize>| { + let s = rt.elements().into_iter().find(|e| e.key.as_deref() == Some("scroll")).unwrap().rect[1]; + rt.elements().into_iter().find(|e| e.key.as_deref() == Some("r4")).map(|e| e.rect[1] - s) + }; + let before = rel_y(&rt).expect("r4 mounted before commit"); + assert!((before - 600.0).abs() < 0.5, "r4 at 150 unscaled = 600 scaled: {before}"); + + // Insert 40 rows after r1 (keeping r1 as the virtual anchor while pushing r4 to index 44, + // outside the mounted window) and ask to keep r4 on screen: `apply_keeps` must restore r4 via + // `virtual_row` using unscaled viewport points. + rt.update(|ins, tx| { + *ins = 40; + tx.instant(); + tx.keep_on_screen("r4"); + }); + rt.frame(1.0 / 60.0); + let after = rel_y(&rt).expect("r4 must remain mounted in view after keep_on_screen"); + assert!((after - before).abs() < 0.5, "scaled keep_on_screen jumped: before={before}, after={after}"); +} diff --git a/app/vendor/rune/crates/rune/src/runtime/tests/scroll_growth.rs b/app/vendor/rune/crates/rune/src/runtime/tests/scroll_growth.rs new file mode 100644 index 0000000..c389709 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/tests/scroll_growth.rs @@ -0,0 +1,512 @@ +use super::*; + + +#[test] +fn growth_rows_grow_and_sticky_scroll_lands_at_bottom() { + use crate::el::{GrowthSpec, ScrollSpec}; + fn view(n: &usize, _cx: &mut Cx<usize>) -> El { + let mut stack = col().key("stack").growth(GrowthSpec::default()); + for i in 0..*n { + stack = stack.child(el().key(format!("r{i}")).h(100.0).w_full()); + } + col().key("root").child(col().key("scroll").h(300.0).w_full().scroll(ScrollSpec { stick_bottom: true }).child(stack)) + } + let mut rt = Runtime::new(10usize, view, (200.0, 300.0), Env::new(true, 2.0)); + rt.frame(0.0); + // First frame: at the bottom, nothing animating (guarantee 8). + assert!(!rt.animating); + let last = rt.elements().into_iter().find(|e| e.key.as_deref() == Some("r9")).unwrap(); + assert!((last.rect[1] + last.rect[3] - 300.0).abs() < 0.05, "{:?}", last.rect); + // A new row grows from 0 and the end stays pinned. + rt.state = 11; + rt.commit.dirty = true; + rt.frame(1.0 / 60.0); + assert!(rt.animating); + let r10 = rt.elements().into_iter().find(|e| e.key.as_deref() == Some("r10")).unwrap(); + assert!(r10.rect[3] < 100.0 && r10.rect[3] > 0.0); + for _ in 0..120 { + rt.frame(1.0 / 60.0); + } + assert!(!rt.animating); + let r10 = rt.elements().into_iter().find(|e| e.key.as_deref() == Some("r10")).unwrap(); + assert!((r10.rect[1] + r10.rect[3] - 300.0).abs() < 0.05, "{:?}", r10.rect); +} + +#[test] +fn animate_layout_springs_a_growth_row_s_contents() { + use crate::el::GrowthSpec; + fn view(s: &(f32, bool), _cx: &mut Cx<(f32, bool)>) -> El { + let mut trigger = crate::row().key("trigger").h(28.0) + .child(el().key("label").size(s.0, 16.0).width_leads()) + .child(el().key("chevron").size(14.0, 14.0)); + if s.1 { trigger = trigger.animate_layout(); } + col().key("stack").w_full().growth(GrowthSpec::default()) + .child(col().key("r0").w_full().child(trigger)) + } + let chevron_x = |rt: &Runtime<(f32, bool)>| rt.elements().into_iter() + .find(|e| e.key.as_deref() == Some("chevron")).unwrap().rect[0]; + let label_w = |rt: &Runtime<(f32, bool)>| rt.elements().into_iter() + .find(|e| e.key.as_deref() == Some("label")).unwrap().rect[2]; + for animate in [false, true] { + let mut rt = Runtime::new((53.0, animate), view, (300.0, 100.0), Env::new(true, 2.0)); + rt.frame(0.0); + assert_eq!(chevron_x(&rt), 53.0); + rt.update(|s, _| s.0 = 88.0); + rt.frame(1.0 / 120.0); + let (x, w) = (chevron_x(&rt), label_w(&rt)); + if animate { + assert!(x > 53.0 && x < 60.0, "springs from where it was: {x}"); + assert!(w > x, "width_leads still leads inside a growth row: {w} vs {x}"); + for _ in 0..120 { rt.frame(1.0 / 120.0); } + assert_eq!(chevron_x(&rt), 88.0); + } else { + assert_eq!(x, 88.0, "a growth row's contents snap by default"); + } + } +} + +#[test] +fn animate_layout_in_a_growth_row_leaves_vertical_to_growth() { + use crate::el::GrowthSpec; + // (label width, space above the header, a second row) + fn view(s: &(f32, f32, bool), _cx: &mut Cx<(f32, f32, bool)>) -> El { + let head = |k: &str, w: f32| crate::row().key(k).h(28.0).animate_layout() + .child(el().key(format!("{k}-names")).size(w, 16.0)) + .child(el().key(format!("{k}-chevron")).size(14.0, 14.0)); + let mut stack = col().key("stack").w_full().growth(GrowthSpec::default()) + .child(col().key("r0").w_full().child(el().key("above").w_full().h(s.1)).child(head("h0", s.0))); + if s.2 { stack = stack.child(col().key("r1").w_full().child(head("h1", 40.0))); } + stack + } + let find = |rt: &Runtime<(f32, f32, bool)>, key: &str| rt.elements().into_iter().find(|e| e.key.as_deref() == Some(key)).unwrap(); + let mut rt = Runtime::new((31.5, 0.0, false), view, (300.0, 200.0), Env::new(true, 2.0)); + rt.frame(0.0); + rt.update(|s, _| *s = (92.0, 20.0, true)); + rt.frame(1.0 / 120.0); + let (chevron, names) = (find(&rt, "h0-chevron").rect, find(&rt, "h0-names").rect); + assert!(chevron[0] > 31.5 && chevron[0] < 40.0, "x springs: {chevron:?}"); + assert!(names[2] > 31.5 && names[2] < 40.0, "width springs: {names:?}"); + assert_eq!(chevron[1], 20.0, "y lands at once; the row's growth carries it"); + assert_eq!(find(&rt, "h1-names").opacity, 1.0, "a new row's contents ride its growth"); +} + +#[test] +fn layout_out_of_sight_before_and_after_moves_at_once() { + fn view(wide: &bool, _cx: &mut Cx<bool>) -> El { + let rows = (0..40).map(|i| el().key(format!("r{i}")).w(if *wide { 200.0 } else { 100.0 }).h(40.0).fill(Color::WHITE)); + col().w_full().h_full() + .child(col().key("scroll").w_full().h(100.0) + .scroll(ScrollSpec { stick_bottom: false }).child(col().children(rows))) + .child(el().key("crosser").absolute(if *wide { -80.0 } else { 380.0 }, 20.0).size(20.0, 20.0).fill(Color::WHITE)) + .child(col().key("drawer").w_full().h(if *wide { 100.0 } else { 0.0 }).clip_soft(0.0) + .child(el().key("inside-closing").absolute(10.0, if *wide { 180.0 } else { 20.0 }).size(40.0, 20.0).fill(Color::WHITE))) + } + let mut rt = Runtime::new(true, view, (300.0, 300.0), Env::new(true, 2.0)); + rt.frame(0.0); + rt.frame(1.0 / 120.0); + rt.update(|s, _| *s = false); + rt.frame(1.0 / 120.0); + let rect = |rt: &Runtime<bool>, key: &str| rt.elements().into_iter().find(|e| e.key.as_deref() == Some(key)).unwrap().rect; + assert!(rect(&rt, "r0")[2] > 190.0, "a row in sight springs: {}", rect(&rt, "r0")[2]); + assert_eq!(rect(&rt, "r30")[2], 100.0, "a row out of sight before and after lands at once"); + assert!(rect(&rt, "crosser")[0] < 0.0, "an element sweeping across the window animates: {:?}", rect(&rt, "crosser")); + assert!(rect(&rt, "inside-closing")[1] > 150.0, "an element entering a still-closing clip animates: {:?}", rect(&rt, "inside-closing")); +} + +#[test] +fn animate_layout_lets_a_growth_row_s_new_contents_fade_in() { + use crate::el::GrowthSpec; + fn view(s: &(bool, bool), _cx: &mut Cx<(bool, bool)>) -> El { + let trigger = crate::row().key("trigger").h(28.0).animate_layout() + .child(el().key(if s.0 { "after" } else { "before" }).size(if s.0 { 88.0 } else { 53.0 }, 16.0)); + let mut stack = col().key("stack").w_full().growth(GrowthSpec::default()); + if s.1 { stack = stack.virtualize(40.0); } + col().w_full().h_full().child(col().key("scroll").w_full().h(100.0).scroll(ScrollSpec { stick_bottom: true }) + .child(stack.child(col().key("r0").w_full().child(col().key("part").child(trigger))))) + } + let opacity = |rt: &Runtime<(bool, bool)>, key: &str| rt.elements().into_iter() + .find(|e| e.key.as_deref() == Some(key)).map(|e| e.opacity); + for virtualized in [false, true] { + let mut rt = Runtime::new((false, virtualized), view, (300.0, 100.0), Env::new(true, 2.0)); + rt.frame(0.0); + for _ in 0..30 { rt.frame(1.0 / 120.0); } + rt.update(|s, _| s.0 = true); + rt.frame(1.0 / 120.0); + let (before, after) = (opacity(&rt, "before").unwrap_or(0.0), opacity(&rt, "after").unwrap()); + assert!(before > 0.5 && after < 0.5, "virtualized {virtualized}: crossfades, {before} out and {after} in"); + } +} + +#[test] +fn explicit_transitions_play_inside_a_growth_row() { + use crate::el::GrowthSpec; + fn view(s: &(bool, bool), _cx: &mut Cx<(bool, bool)>) -> El { + let mut trigger = crate::row().key("trigger").h(28.0).child(el().key("label").size(53.0, 16.0)); + if s.0 { + trigger = trigger.child(el().key("badge").size(16.0, 16.0) + .transition(Transition::offset(0.0, 8.0).combined(Transition::opacity()))); + } + if s.1 { trigger = trigger.animate_layout(); } + col().key("stack").w_full().growth(GrowthSpec::default()) + .child(col().key("r0").w_full().child(trigger)) + } + let badge = |rt: &Runtime<(bool, bool)>| rt.elements().into_iter() + .find(|e| e.key.as_deref() == Some("badge")).map(|e| (e.opacity, e.exiting)); + for animate in [false, true] { + let mut rt = Runtime::new((false, animate), view, (300.0, 100.0), Env::new(true, 2.0)); + rt.frame(0.0); + for _ in 0..30 { rt.frame(1.0 / 120.0); } + rt.update(|s, _| s.0 = true); + rt.frame(1.0 / 120.0); + let (op, _) = badge(&rt).unwrap(); + assert!(op < 0.5, "animate_layout {animate}: it enters on its transition: {op}"); + for _ in 0..120 { rt.frame(1.0 / 120.0); } + rt.update(|s, _| s.0 = false); + rt.frame(1.0 / 120.0); + let (op, exiting) = badge(&rt).expect("it plays its exit"); + assert!(exiting && op > 0.5, "animate_layout {animate}: it exits on its transition: {op}"); + } +} + +/// A long text in a scroll view walks only the lines its clip shows: the glyphs of lines +/// far below aren't rasterized until scrolled to, while a tall span whose line box sits +/// more than two base ems below the clip still paints the ascenders that reach inside. +#[test] +fn a_long_scrolled_text_paints_only_its_visible_lines() { + use crate::{text, text_input, Span, TextEdit, TextStyle}; + struct Note { edit: TextEdit } + fn view(s: &Note, _: &mut Cx<Note>) -> El { + col().w_full().h_full().child(col().key("viewport").w_full().h(200.0).scroll(ScrollSpec { stick_bottom: false }) + .child(text_input(&s.edit, TextStyle::new(14.0, 400.0).lh(20.0)).key("note").w_full().on_edit(|s: &mut Note| &mut s.edit))) + } + let mut content = "plain lowercase words only\n".repeat(500); + content += "QUIZ JOKE VEX"; + let mut rt = Runtime::new(Note { edit: TextEdit::new(content) }, view, (300.0, 300.0), Env::new(true, 2.0)); + rt.frame(0.0); + let top = rt.text.atlas.glyph_entries(); + let glyphs = rt.stats.glyphs; + assert!(glyphs > 0 && glyphs < 400, "about ten visible lines painted: {glyphs}"); + rt.wheel(150.0, 100.0, -1e5); + rt.frame(1.0 / 60.0); + assert!(rt.text.atlas.glyph_entries() > top, "the capitals on the last line rasterize only once shown"); + + // Line 15 starts at y = 75 pt, 25 pt (> 2 * 10 pt) below the 50 pt clip. The 120 pt span keeps + // the paragraph's 0.5 leading ratio, so its box is 60 pt tall and the glyph overhangs it: + // the ascender reaches up into the clip and must still paint. + fn span_view(_: &(), _: &mut Cx<()>) -> El { + let s = "a\n".repeat(15) + "T"; + col().w_full().h_full().child(col().w_full().h(50.0).scroll(ScrollSpec { stick_bottom: false }) + .child(text(&s).font(TextStyle::new(10.0, 400.0).lh(5.0)).spans(vec![Span::new(30, 31).size(120.0)]))) + } + let mut rt = Runtime::new((), span_view, (200.0, 200.0), Env::new(true, 2.0)); + rt.frame(0.0); + assert_eq!(rt.stats.glyphs, 11, "10 visible 'a' lines plus the overhanging 'T' glyph"); + assert_eq!(rt.text.atlas.glyph_entries(), 2, "'a' and overhanging 'T' both rasterized"); +} + +#[test] +fn a_window_resize_lands_rewrapped_rows_under_a_pinned_tail() { + use crate::el::text; + fn view(_: &(), _: &mut Cx<()>) -> El { + col().key("viewport").w_full().h_full().scroll(ScrollSpec { stick_bottom: true }) + .child(col().key("stack").w_full().growth(GrowthSpec::default()) + .child(col().key("first").w_full().child(text("Wrap again as the window narrows. ".repeat(40)).wrap().w_full())) + .child(col().key("last").w_full().child(text("The tail stays pinned. ".repeat(20)).wrap().w_full()))) + } + let mut rt = Runtime::new((), view, (600.0, 300.0), Env::new(true, 2.0)); + rt.frame(0.0); + let gap = |rt: &Runtime<()>| { + let el = rt.elements(); + let end = |k: &str| el.iter().find(|e| e.key.as_deref() == Some(k)).map(|e| e.rect[1] + e.rect[3]).unwrap(); + end("viewport") - end("last") + }; + let rest = gap(&rt); + let first = rt.tree.nodes.iter().find(|n| n.key.as_deref() == Some("first")).unwrap().id; + let before = rt.motion.grows[&first].h; + // One step a frame, as a person drags the corner. + for w in (420..600).rev().step_by(6) { + rt.set_viewport((w as f32, 300.0), 2.0); + rt.frame(1.0 / 120.0); + assert!((gap(&rt) - rest).abs() < 0.5, "at width {w} the tail moved off the bottom: {} vs {rest}", gap(&rt)); + let el = rt.elements(); + let rect = |k: &str| el.iter().find(|e| e.key.as_deref() == Some(k)).unwrap().rect; + let (a, b) = (rect("first"), rect("last")); + assert!(a[1] + a[3] <= b[1] + 0.5, "at width {w} the first row runs into the last: {a:?} {b:?}"); + } + assert!(rt.motion.grows[&first].h > before + 1.0, "the first row rewrapped taller"); + let measured = rt.tree.nodes.iter().find(|n| n.id == first).unwrap().local.h; + assert_eq!(rt.motion.grows[&first].h, measured, "and its slot landed with it"); +} + +#[test] +fn rows_all_leaving_a_padded_growth_stack_hold_their_place() { + use crate::el::GrowthSpec; + fn view(n: &usize, _cx: &mut Cx<usize>) -> El { + let stack = col().key("stack").w_full().padding(8.0).growth(GrowthSpec::default()) + .children((0..*n).map(|i| el().key(format!("r{i}")).h(20.0).w_full().fill(Color::WHITE))); + col().key("root").size(200.0, 200.0).child(stack) + } + let tops = |rt: &Runtime<usize>| -> Vec<f32> { + (0..3).filter_map(|i| rt.elements().into_iter().find(|e| e.key.as_deref() == Some(&*format!("r{i}"))).map(|e| e.rect[1])).collect() + }; + for left in [0usize, 1] { + let mut rt = Runtime::new(3usize, view, (200.0, 200.0), Env::new(true, 1.0)); + rt.frame(0.0); + assert_eq!(tops(&rt), [8.0, 28.0, 48.0]); + rt.update(|n, _| *n = left); + rt.frame(1.0 / 120.0); + let now = tops(&rt); + assert_eq!(now[..2], [8.0, 28.0], "{left} left: the leaving rows hold on frame 1: {now:?}"); + } +} + +/// `n` rows of 100 pt in a growth stack, in a 300 pt `stick_bottom` viewport. +fn shrinking(n: &usize, _cx: &mut Cx<usize>) -> El { + use crate::el::{GrowthSpec, ScrollSpec}; + let mut stack = col().key("stack").w_full().growth(GrowthSpec::default()); + for i in 0..*n { + stack = stack.child(el().key(format!("r{i}")).h(100.0).w_full()); + } + col().key("root").child(col().key("scroll").h(300.0).w_full().scroll(ScrollSpec { stick_bottom: true }).child(stack)) +} + +/// Twenty `shrinking` rows, read 200 pt above their end. +fn reading(hz: f64) -> Runtime<usize> { + let mut rt = Runtime::new(20usize, shrinking, (200.0, 300.0), Env::new(true, 2.0)); + rt.frame(0.0); + rt.frame(1.0 / hz); + rt.wheel(100.0, 100.0, 200.0); + for _ in 0..30 { rt.frame(1.0 / hz); } + assert_eq!(rt.scroll.scrolls.values().next().unwrap().offset, 1500.0, "reading 200 pt above the end"); + rt +} + +/// Rows removed under a reader who scrolled up end the content above their offset: the +/// viewport glides to the new end from rest and lands at rest, never past the presented end, +/// instead of picking up the collapse's speed in a frame. +#[test] +fn content_shrinking_under_a_reader_eases_to_its_new_end() { + let scroll = |rt: &Runtime<usize>| rt.scroll.scrolls.values().next().map(|st| (st.offset, st.max)).unwrap(); + // (rows left, frame rate, largest first step and frame-to-frame change, as parts of the peak speed) + for (left, hz, onset, step) in [(15usize, 120.0, 0.3, 0.4), (5, 120.0, 0.3, 0.4), (15, 60.0, 0.4, 0.55)] { + let mut rt = reading(hz); + let (mut last, _) = scroll(&rt); + rt.update(|n, _| *n = left); + let mut v = Vec::new(); + for _ in 0..hz as usize { + rt.frame(1.0 / hz); + let (offset, max) = scroll(&rt); + assert!(offset <= max + 1e-6, "{left} left at {hz} Hz: the end never rises into view"); + v.push((offset - last) * hz); + last = offset; + } + let end = left as f64 * 100.0 - 300.0; + assert!((last - end).abs() < 0.01, "{left} left at {hz} Hz: lands on the new end: {last}"); + let moving: Vec<f64> = v.iter().copied().skip_while(|s| s.abs() < 1e-9).collect(); + let peak = moving.iter().fold(0.0f64, |a, s| a.max(s.abs())); + let speeds: Vec<i64> = moving.iter().map(|s| s.round() as i64).collect(); + assert!(moving[0].abs() <= onset * peak, "{left} left at {hz} Hz: starts from rest: {speeds:?}"); + assert!(moving.windows(2).all(|w| (w[1] - w[0]).abs() <= step * peak), "{left} left at {hz} Hz: no speed jumps: {speeds:?}"); + let tail = moving.iter().rev().find(|s| s.abs() > 1e-9).unwrap(); + assert!(tail.abs() <= 0.05 * peak, "{left} left at {hz} Hz: lands at rest: {speeds:?}"); + } +} + +/// A wheel mid-glide hands the viewport back: no glide starts again until the rows settle. +#[test] +fn a_hand_scroll_mid_shrink_keeps_the_viewport() { + let mut rt = reading(120.0); + rt.update(|n, _| *n = 15); + for _ in 0..6 { rt.frame(1.0 / 120.0); } + assert!(rt.scroll.scrolls.values().next().unwrap().glide().is_some(), "the collapse glides"); + rt.wheel(100.0, 100.0, 10.0); + for f in 0..120 { + rt.frame(1.0 / 120.0); + assert!(rt.scroll.scrolls.values().next().unwrap().glide().is_none(), "frame {f}: no glide takes the viewport back from the hand"); + } +} + +/// A second removal mid-glide retargets it to the newer end without braking, and rows coming +/// back past the offset end it where it is. +#[test] +fn a_shrink_glide_follows_the_end_as_it_moves() { + let mut rt = reading(120.0); + rt.update(|n, _| *n = 15); + for _ in 0..8 { rt.frame(1.0 / 120.0); } + let v = rt.scroll.scrolls.values().next().unwrap().glide().unwrap(); + assert!(v.abs() > 1.0, "gliding at {v}"); + rt.update(|n, _| *n = 10); + rt.frame(1.0 / 120.0); + let st = rt.scroll.scrolls.values().next().unwrap(); + assert_eq!(st.glide_to(), Some(700.0), "the glide aims at the newer end"); + assert!(st.glide().unwrap().abs() >= v.abs() * 0.5, "and keeps its speed: {:?} from {v}", st.glide()); + for _ in 0..120 { rt.frame(1.0 / 120.0); } + assert!((rt.scroll.scrolls.values().next().unwrap().offset - 700.0).abs() < 0.01, "lands on the newer end"); + + let mut rt = reading(120.0); + rt.update(|n, _| *n = 15); + for _ in 0..8 { rt.frame(1.0 / 120.0); } + rt.update(|n, _| *n = 20); + rt.frame(1.0 / 120.0); + let st = rt.scroll.scrolls.values().next().unwrap(); + assert!(st.glide().is_none(), "rows coming back past the offset end the glide"); + let at = st.offset; + for _ in 0..60 { rt.frame(1.0 / 120.0); } + assert_eq!(rt.scroll.scrolls.values().next().unwrap().offset, at, "and the viewport stays where it was"); +} + +/// A row kept on screen owns its viewport through a collapse: no shrink glide pulls it away. +#[test] +fn a_kept_row_holds_its_viewport_through_a_shrink() { + let mut rt = reading(120.0); + let top = |rt: &Runtime<usize>| rt.elements().into_iter().find(|e| e.key.as_deref() == Some("r15")).unwrap().rect[1]; + let was = top(&rt); + rt.update(|n, tx| { *n = 17; tx.keep_on_screen("r15"); }); + for f in 0..20 { + rt.frame(1.0 / 120.0); + assert!(rt.scroll.scrolls.values().next().unwrap().glide().is_none(), "frame {f}: no shrink glide on a kept viewport"); + assert!((top(&rt) - was).abs() < 0.5, "frame {f}: the kept row holds its place"); + } +} + +/// Content shrinking past a glide's end lands it there instead of overshooting and springing back. +#[test] +fn a_glide_whose_end_shrinks_past_it_lands_there() { + let mut rt = reading(120.0); + rt.update(|_, tx| tx.scroll_to("scroll", 0.0, 1000.0)); + for _ in 0..6 { rt.frame(1.0 / 120.0); } + assert!(rt.scroll.scrolls.values().next().unwrap().glide().is_some_and(|v| v.abs() > 100.0), "gliding up"); + rt.update(|n, tx| { *n = 12; tx.instant(); }); + let mut low = f64::MAX; + for _ in 0..60 { + rt.frame(1.0 / 120.0); + low = low.min(rt.scroll.scrolls.values().next().unwrap().offset); + } + let st = rt.scroll.scrolls.values().next().unwrap(); + assert_eq!((st.offset, st.max), (900.0, 900.0)); + assert!(low >= 900.0 - 1e-6, "never dips below the end: {low}"); +} + +/// The collapse's spring tail can run on for a while under a fraction of a point. A reader +/// the glide landed on the new end sticks to it once the rows are within half a point of it, +/// so rows arriving in that tail grow in under a pinned end rather than below the viewport. +#[test] +fn a_reader_landed_on_a_shrunk_end_follows_rows_arriving_in_its_tail() { + let mut rt = reading(120.0); + rt.update(|n, _| *n = 15); + for f in 0.. { + rt.frame(1.0 / 120.0); + let st = rt.scroll.scrolls.values().next().unwrap(); + if st.glide().is_none() && st.max - 1200.0 < 0.5 { break; } + assert!(f < 240, "the glide lands and the rows near the end"); + } + assert!(rt.motion.stacks.values().next().unwrap().moving, "the rows are still settling"); + assert!(rt.scroll.scrolls.values().next().unwrap().pinned(), "the reader sticks to the end"); + rt.update(|n, _| *n = 20); + for _ in 0..120 { rt.frame(1.0 / 120.0); } + let st = rt.scroll.scrolls.values().next().unwrap(); + assert_eq!((st.offset, st.max), (1700.0, 1700.0), "and follows the rows that come back"); +} + +/// While a collapse glides a reader to the new end, `on_far_from_bottom` measures from the end +/// they're headed to: the presented end, still collapsing, doesn't report them far for a moment. +#[test] +fn a_shrink_glide_never_reports_far_from_the_end_it_heads_for() { + use crate::el::{GrowthSpec, ScrollSpec}; + fn view(s: &(usize, Vec<bool>), _: &mut Cx<(usize, Vec<bool>)>) -> El { + let mut stack = col().key("stack").w_full().growth(GrowthSpec::default()); + for i in 0..s.0 { + stack = stack.child(el().key(format!("r{i}")).h(100.0).w_full()); + } + let scroll = col().key("scroll").h(300.0).w_full().scroll(ScrollSpec { stick_bottom: true }) + .on_far_from_bottom(300.0, |s: &mut (usize, Vec<bool>), far| s.1.push(far)); + col().key("root").child(scroll.child(stack)) + } + let mut rt = Runtime::new((20usize, Vec::new()), view, (200.0, 300.0), Env::new(true, 2.0)); + rt.frame(0.0); + rt.frame(1.0 / 120.0); + rt.wheel(100.0, 100.0, 200.0); + for _ in 0..30 { rt.frame(1.0 / 120.0); } + assert_eq!(rt.state.1, [false], "200 above the end is near"); + rt.update(|s, _| s.0 = 15); + for _ in 0..120 { rt.frame(1.0 / 120.0); } + assert_eq!(rt.state.1, [false], "gliding to the new end stays near"); +} + +/// The glide lands on the new end before the rows' last fraction of a point has collapsed. +/// The reader sticks there without the presented end lifting it: the offset never steps up. +#[test] +fn a_reader_stuck_in_the_collapse_tail_never_steps_up() { + let top = |rt: &Runtime<usize>| rt.elements().into_iter().find(|e| e.key.as_deref() == Some("r10")).unwrap().rect[1]; + let mut rt = reading(120.0); + rt.update(|n, _| *n = 15); + let (mut offset, mut y) = (rt.scroll.scrolls.values().next().unwrap().offset, top(&rt)); + let mut stuck_in_tail = false; + for f in 0..240 { + rt.frame(1.0 / 120.0); + let st = rt.scroll.scrolls.values().next().unwrap(); + stuck_in_tail |= st.pinned() && st.max > 1200.0; + assert!(st.offset <= offset, "frame {f}: the offset steps up from {offset} to {}", st.offset); + let now = top(&rt); + assert!(now >= y - 1e-3, "frame {f}: the rows step up from {y} to {now}"); + (offset, y) = (st.offset, now); + } + assert!(stuck_in_tail, "the reader sticks while the rows still collapse"); + assert_eq!(offset, 1200.0); +} + +/// `n` rows of 100 pt and a last row `tall` pt high in a 300 pt `stick_bottom` viewport, which +/// records `on_far_from_bottom`. +fn far_reader(s: &(usize, f32, Vec<bool>), _: &mut Cx<(usize, f32, Vec<bool>)>) -> El { + use crate::el::{GrowthSpec, ScrollSpec}; + let mut stack = col().key("stack").w_full().growth(GrowthSpec::default()); + for i in 0..s.0 { + stack = stack.child(el().key(format!("r{i}")).h(100.0).w_full()); + } + if s.1 > 0.0 { stack = stack.child(el().key("tall").h(s.1).w_full()); } + let scroll = col().key("scroll").h(300.0).w_full().scroll(ScrollSpec { stick_bottom: true }) + .on_far_from_bottom(300.0, |s: &mut (usize, f32, Vec<bool>), far| s.2.push(far)); + col().key("root").child(scroll.child(stack)) +} + +/// `far_reader` scrolled `up` from its end. +fn far_reading(rows: usize, tall: f32, up: f32) -> Runtime<(usize, f32, Vec<bool>)> { + let mut rt = Runtime::new((rows, tall, Vec::new()), far_reader, (200.0, 300.0), Env::new(true, 2.0)); + rt.frame(0.0); + rt.frame(1.0 / 120.0); + rt.wheel(100.0, 100.0, up); + for _ in 0..30 { rt.frame(1.0 / 120.0); } + assert_eq!(rt.state.2.last(), Some(&true), "{up} above the end is far"); + rt.state.2.clear(); + rt +} + +/// A short glide lands on the new end long before a tall row has collapsed: the reader is near +/// the layout's end, and isn't reported far again while the presented end catches up. +#[test] +fn a_landed_glide_over_a_collapsing_tall_row_stays_near() { + let mut rt = far_reading(10, 3000.0, 2800.0); + rt.update(|s, _| s.1 = 0.0); + for _ in 0..360 { rt.frame(1.0 / 120.0); } + assert_eq!(rt.scroll.scrolls.values().next().unwrap().offset, 700.0, "the glide lands on the new end"); + assert_eq!(rt.state.2, [false], "a tall row collapsing under a landed glide stays near"); +} + +/// Rows coming back partway end a shrink glide short of the presented end: the reader is near +/// the regrown layout's end, and isn't reported far while the other rows collapse to it. +#[test] +fn rows_regrowing_under_a_shrink_glide_stay_near() { + let mut rt = far_reading(20, 0.0, 600.0); + rt.update(|s, _| s.0 = 5); + for f in 0.. { + rt.frame(1.0 / 120.0); + let st = rt.scroll.scrolls.values().next().unwrap(); + assert!(st.glide().is_some() && f < 120, "the glide passes 850"); + if st.offset < 850.0 { break; } + } + rt.update(|s, _| s.0 = 12); + rt.frame(1.0 / 120.0); + assert!(rt.scroll.scrolls.values().next().unwrap().glide().is_none(), "rows coming back past the offset end the glide"); + for _ in 0..240 { rt.frame(1.0 / 120.0); } + assert_eq!(rt.state.2, [false], "the regrown end is near, while the rows still collapse to it"); +} diff --git a/app/vendor/rune/crates/rune/src/runtime/tests/scroll_hover.rs b/app/vendor/rune/crates/rune/src/runtime/tests/scroll_hover.rs new file mode 100644 index 0000000..b95f251 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/tests/scroll_hover.rs @@ -0,0 +1,325 @@ +use super::*; +use crate::runtime::scroll_nudge::NUDGE_HOLD; + +/// Forty 20-point rows in a 200-point viewport, each revealing an action on hover. +fn view(_: &(), _: &mut Cx<()>) -> El { + let rows = col().key("rows").w_full().children((0..40).map(|k| crate::row().key(format!("r{k}")).w_full().h(20.0).hover_group() + .child(el().key(format!("a{k}")).size(10.0, 10.0).fill(Color::WHITE).group_opacity(0.0, 1.0)))); + col().size(200.0, 200.0).child(col().key("scroll").size(200.0, 200.0).scroll(crate::ScrollSpec { stick_bottom: false }).child(rows)) +} + +/// The rows whose action shows at all this frame. +fn shown(rt: &Runtime<()>) -> Vec<String> { + rt.elements().into_iter().filter(|e| e.key.as_ref().is_some_and(|k| k.starts_with('a')) && e.opacity > 0.0) + .filter_map(|e| e.key).collect() +} + +fn hovering() -> Runtime<()> { + let mut rt = Runtime::new((), view, (200.0, 200.0), Env::new(true, 1.0)); + rt.frame(0.0); + rt.pointer_move(100.0, 110.0); + rt.frame(1.0 / 120.0); + assert_eq!(shown(&rt), ["a5"]); + rt +} + +#[test] +fn a_glide_holds_a_still_pointers_hover_until_it_stops() { + let mut rt = hovering(); + rt.update(|_, tx| tx.scroll_to("scroll", 0.0, 400.0)); + let mut frames = 0; + for f in 0..600 { + rt.frame(1.0 / 120.0); + if rt.scroll.scrolls.values().all(|s| s.glide().is_none()) { break; } + frames += 1; + assert_eq!(shown(&rt), ["a5"], "frame {f}: no row passing under the pointer takes its hover"); + } + assert!(frames > 5, "it glided"); + for _ in 0..30 { rt.frame(1.0 / 120.0); } + assert_eq!(shown(&rt), ["a25"], "once it stops, the row under the pointer has it"); +} + +#[test] +fn moving_the_pointer_during_a_glide_hovers_again() { + let mut rt = hovering(); + rt.update(|_, tx| tx.scroll_to_bottom("scroll")); + for _ in 0..4 { rt.frame(1.0 / 120.0); } + assert_eq!(shown(&rt), ["a5"]); + rt.pointer_move(100.0, 111.0); + rt.frame(1.0 / 120.0); + rt.frame(1.0 / 120.0); + // Hover paints a frame behind the moving rows, as with a wheel scroll. + let offset = rt.scroll.scrolls.values().next().unwrap().offset as f32; + let under = ((offset + 111.0) / 20.0) as usize; + let rows: Vec<usize> = shown(&rt).iter().map(|k| k[1..].parse().unwrap()).collect(); + assert!(rows.iter().any(|&k| k != 5 && k + 2 >= under && k <= under), "the moved pointer hovers near row {under}: {rows:?}"); +} + +#[test] +fn a_wheel_scroll_still_hovers_each_row_it_brings_under_the_pointer() { + let mut rt = hovering(); + rt.wheel(100.0, 110.0, -40.0); + // Hover retargets from the frame's drawn rows and paints on the next. + rt.frame(1.0 / 120.0); + rt.frame(1.0 / 120.0); + let offset = rt.scroll.scrolls.values().next().unwrap().offset as f32; + assert!(offset > 0.0); + let under = format!("a{}", ((offset + 110.0) / 20.0) as usize); + assert!(shown(&rt).contains(&under), "{under}: {:?}", shown(&rt)); +} + +#[test] +fn a_hover_a_glide_carried_out_of_view_lets_go_at_once() { + let mut rt = hovering(); + let id = rt.tree.nodes.iter().find(|n| n.named("r5")).unwrap().id; + rt.update(|_, tx| tx.scroll_to("scroll", 0.0, 400.0)); + for f in 0..600 { + rt.frame(1.0 / 120.0); + if rt.scene.store().target(id, P_HOVER) == Some(0.0) { + assert!(rt.scroll.scrolls.values().all(|s| s.glide().is_none()), "frame {f}: the hold kept r5's hover through the glide"); + assert!(!rt.scene.store().is_animating(id, P_HOVER), "r5, out of view, lands its leave instead of fading it unseen"); + return; + } + } + panic!("r5 never let go of its hover"); +} + +/// Forty rows, each darkening while pressed and gliding twenty rows on when pressed. +fn pressing(_: &(), _: &mut Cx<()>) -> El { + let rows = col().key("rows").w_full().children((0..40).map(|k| crate::row().key(format!("r{k}")).w_full().h(20.0) + .press(Color::WHITE).press_scale(0.9).on_press_tx(|_: &mut (), tx: &mut Tx| tx.scroll_to("scroll", 0.0, 400.0)))); + col().size(200.0, 200.0).child(col().key("scroll").size(200.0, 200.0).scroll(crate::ScrollSpec { stick_bottom: false }).child(rows)) +} + +#[test] +fn a_press_that_starts_a_glide_still_lets_go() { + let mut rt = Runtime::new((), pressing, (200.0, 200.0), Env::new(true, 1.0)); + rt.frame(0.0); + rt.pointer_move(100.0, 110.0); + rt.frame(1.0 / 120.0); + rt.pointer_down(100.0, 110.0); + rt.frame(1.0 / 120.0); + let id = rt.tree.nodes.iter().find(|n| n.named("r5")).unwrap().id; + assert_eq!(rt.scene.store().target(id, P_PRESS), Some(1.0)); + assert_eq!(rt.scene.store().target(id, P_PRESS_SCALE), Some(0.9)); + rt.pointer_up(100.0, 110.0); + rt.frame(1.0 / 120.0); + rt.frame(1.0 / 120.0); + assert!(rt.pointer.hover_hold().held(), "the press's glide holds hover"); + assert_eq!(rt.scene.store().target(id, P_PRESS), Some(0.0), "the press lets go mid-glide"); + assert_eq!(rt.scene.store().target(id, P_PRESS_SCALE), Some(1.0), "the press scale springs back mid-glide"); +} + +#[test] +fn the_hold_ends_with_its_glide() { + let mut rt = hovering(); + rt.update(|_, tx| tx.scroll_to("scroll", 0.0, 400.0)); + let mut held = false; + for _ in 0..600 { + rt.frame(1.0 / 120.0); + held |= rt.pointer.hover_hold().held(); + if rt.scroll.scrolls.values().all(|s| s.glide().is_none()) { break; } + } + assert!(held, "the glide held hover"); + assert!(!rt.pointer.hover_hold().held() && !rt.pointer.hover_hold().released(), "no stale hold is left for a later glide"); +} + +/// Two viewports side by side, and a modal over both while `open`. +fn pair(open: &bool, _: &mut Cx<bool>) -> El { + let side = |key: &str| col().key(key).size(100.0, 200.0).scroll(crate::ScrollSpec { stick_bottom: false }) + .child(col().w_full().children((0..40).map(|k| crate::row().key(format!("{key}{k}")).w_full().h(20.0).hover_group() + .child(el().key(format!("a{key}{k}")).size(10.0, 10.0).fill(Color::WHITE).group_opacity(0.0, 1.0))))); + let root = crate::row().size(200.0, 200.0).child(side("l")).child(side("r")); + if *open { root.child(col().key("sheet").absolute(150.0, 150.0).size(40.0, 40.0).modal(true, |s: &mut bool| *s = false)) } else { root } +} + +fn gliding_pair() -> Runtime<bool> { + let mut rt = Runtime::new(false, pair, (200.0, 200.0), Env::new(true, 1.0)); + rt.frame(0.0); + rt.pointer_move(50.0, 110.0); + rt.frame(1.0 / 120.0); + rt.update(|_, tx| { tx.scroll_to("l", 0.0, 400.0); tx.scroll_to("r", 0.0, 400.0); }); + // Until a row other than the hovered one glides under the pointer. + for _ in 0..30 { + rt.frame(1.0 / 120.0); + if rt.pointer.hover_hold().held() { return rt; } + } + panic!("the glides held hover"); +} + +#[test] +fn a_hand_scroll_anywhere_lets_go_of_the_hold() { + let mut rt = gliding_pair(); + rt.wheel(150.0, 110.0, -10.0); + rt.frame(1.0 / 120.0); + assert!(rt.scroll.scrolls.values().any(|s| s.glide().is_some()), "the viewport under the pointer still glides"); + assert!(rt.pointer.hover_hold().released() && !rt.pointer.hover_hold().held(), "a wheel over the other viewport lets hover follow the pointer again"); +} + +#[test] +fn a_viewport_under_a_modal_holds_no_hover() { + let mut rt = gliding_pair(); + rt.update(|s, _| *s = true); + rt.frame(1.0 / 120.0); + assert!(rt.scroll.scrolls.values().any(|s| s.glide().is_some())); + assert!(!rt.pointer.hover_hold().held(), "a modal makes the gliding viewport inert"); +} + +/// Two hundred virtual rows, each recording its `on_hover_change`. +fn hover_rows(_: &Vec<(usize, bool)>, _: &mut Cx<Vec<(usize, bool)>>) -> El { + let rows = col().key("rows").w_full().growth(crate::el::GrowthSpec::default()).virtualize(20.0).children((0..200).map(|k| crate::row().key(format!("r{k}")).w_full().h(20.0) + .on_hover_change(move |s: &mut Vec<(usize, bool)>, inside, _| s.push((k, inside))))); + col().size(200.0, 200.0).child(col().key("scroll").size(200.0, 200.0).scroll(crate::ScrollSpec { stick_bottom: false }).child(rows)) +} + +#[test] +fn a_row_leaving_the_tree_under_a_held_glide_hears_the_pointer_leave() { + let mut rt = Runtime::new(Vec::new(), hover_rows, (200.0, 200.0), Env::new(true, 1.0)); + rt.frame(0.0); + rt.pointer_move(100.0, 110.0); + rt.frame(1.0 / 120.0); + rt.frame(1.0 / 120.0); + assert_eq!(rt.state, [(5, true)]); + rt.update(|_, tx| tx.scroll_to("scroll", 0.0, 3000.0)); + rt.frame(1.0 / 120.0); + assert!(rt.pointer.hover_hold().held()); + assert!(!rt.tree.nodes.iter().any(|n| n.named("r5") && !rt.is_exiting(n.id)), "the glide's cut unmounts the row"); + for _ in 0..120 { + rt.frame(1.0 / 120.0); + if rt.state.contains(&(5, false)) { break; } + } + assert!(rt.state.contains(&(5, false)), "the row heard the leave before it was pruned: {:?}", rt.state); + assert!(rt.pointer.hover_hold().held(), "while the glide still holds hover"); +} + +/// An instant scroll holds hover for the same time whether frames come at 30 or 240 a second: +/// dev counted two frames, so a slow display held twice as long as a fast one. +#[test] +fn an_instant_scroll_holds_hover_for_a_time_not_a_frame_count() { + for rate in [30.0, 60.0, 120.0, 240.0] { + let mut rt = hovering(); + let start = rt.clock; + rt.update(|_, tx| tx.scroll_to_instant("scroll", 0.0, 400.0)); + let mut freed = None; + for _ in 0..60 { + rt.frame(1.0 / rate); + if rt.scroll.scrolls.values().all(|s| !s.hold_at(rt.clock)) { freed = Some(rt.clock - start); break; } + } + let held = freed.unwrap_or_else(|| panic!("{rate} fps: the hold ends")); + assert!(held >= NUDGE_HOLD && held <= NUDGE_HOLD + 2.0 / rate, "{rate} fps: held {held} seconds"); + } +} + +/// A held nudge draws nothing while it waits: the frame the jump lands in holds hover and asks +/// for no next frame, and the wake it armed brings the one frame that resolves hover. +#[test] +fn a_held_nudge_draws_no_frames_until_its_wake() { + let mut rt = hovering(); + rt.update(|_, tx| tx.scroll_to_instant("scroll", 0.0, 400.0)); + rt.frame(1.0 / 120.0); + assert!(!rt.animating, "the landing frame asks for no next frame"); + assert_eq!(shown(&rt), ["a5"], "and hover holds under it"); + let due = rt.wake_deadline().expect("the hold wakes a frame"); + assert!((due - rt.clock - NUDGE_HOLD).abs() < 1e-6, "due one hold after the land: {due} at {}", rt.clock); + rt.frame(0.0); + assert!(!rt.animating, "a frame while it waits still asks for none"); + assert_eq!(shown(&rt), ["a5"]); + assert_eq!(rt.wake_deadline(), Some(due), "and the wake still stands"); + rt.frame(due - rt.clock); + assert_eq!(shown(&rt), ["a25"], "the wake's frame resolves hover once, at the pointer"); + assert!(!rt.pointer.hover_hold().held()); +} + +/// A second instant scroll before the hold's due moves the wake to its own due: nothing is +/// left holding hover past it waiting for some other frame to come. +#[test] +fn a_scroll_again_before_the_hold_ends_still_wakes_at_its_own_due() { + let mut rt = hovering(); + rt.update(|_, tx| tx.scroll_to_instant("scroll", 0.0, 200.0)); + rt.frame(1.0 / 120.0); + rt.update(|_, tx| tx.scroll_to_instant("scroll", 0.0, 400.0)); + rt.frame(1.0 / 120.0); + assert_eq!(shown(&rt), ["a5"], "both holds keep hover where it was"); + let due = rt.wake_deadline().expect("the second hold wakes a frame"); + assert!((due - rt.clock - NUDGE_HOLD).abs() < 1e-6, "due one hold after the second scroll, not the first: {due} at {}", rt.clock); + rt.frame(due - rt.clock); + assert_eq!(shown(&rt), ["a25"], "its frame resolves hover once, at the pointer"); +} + +/// Forty 20-point rows, each revealing an action on hover and recording its `on_hover_change`. +fn logged_rows(_: &Vec<(usize, bool)>, _: &mut Cx<Vec<(usize, bool)>>) -> El { + let rows = col().key("rows").w_full().children((0..40).map(|k| crate::row().key(format!("r{k}")).w_full().h(20.0).hover_group() + .on_hover_change(move |s: &mut Vec<(usize, bool)>, inside, _| s.push((k, inside))) + .child(el().key(format!("a{k}")).size(10.0, 10.0).fill(Color::WHITE).group_opacity(0.0, 1.0)))); + col().size(200.0, 200.0).child(col().key("scroll").size(200.0, 200.0).scroll(crate::ScrollSpec { stick_bottom: false }).child(rows)) +} + +#[test] +fn an_app_stepping_its_own_glide_holds_a_still_pointers_hover_until_it_stops() { + let mut rt = Runtime::new(Vec::new(), logged_rows, (200.0, 200.0), Env::new(true, 1.0)); + rt.frame(0.0); + rt.pointer_move(100.0, 110.0); + rt.frame(1.0 / 120.0); + rt.frame(1.0 / 120.0); + assert_eq!(rt.state, [(5, true)]); + // The app glides 400 points itself, an instant scroll each frame. + let mut flashes = 0; + for f in 1..=100 { + rt.update(move |_, tx| tx.scroll_to_instant("scroll", 0.0, 4.0 * f as f32)); + rt.frame(1.0 / 120.0); + let shown: Vec<String> = rt.elements().into_iter().filter(|e| e.key.as_ref().is_some_and(|k| k.starts_with('a')) && e.opacity > 0.0) + .filter_map(|e| e.key).collect(); + flashes += usize::from(shown != ["a5"]); + } + let commits = rt.state.len() - 1; + assert_eq!((commits, flashes), (0, 0), "no hover commits or chrome under the still pointer mid-scroll: {:?}", rt.state); + for _ in 0..30 { rt.frame(1.0 / 120.0); } + assert_eq!(rt.state, [(5, true), (5, false), (25, true)], "once it stops, hover resolves once at the pointer"); + assert!(!rt.pointer.hover_hold().held(), "and lets go"); +} + +/// What forty rows' hover handlers heard: `on_hover_change` and `on_hover`. +#[derive(Default)] +struct Heard { + changes: Vec<(usize, bool)>, + enters: Vec<usize>, +} + +fn heard_rows(_: &Heard, _: &mut Cx<Heard>) -> El { + let rows = col().key("rows").w_full().children((0..40).map(|k| crate::row().key(format!("r{k}")).w_full().h(20.0) + .on_hover_change(move |s: &mut Heard, inside, _| s.changes.push((k, inside))) + .on_hover(move |s: &mut Heard| s.enters.push(k)))); + col().size(200.0, 200.0).child(col().key("scroll").size(200.0, 200.0).scroll(crate::ScrollSpec { stick_bottom: false }).child(rows)) +} + +#[test] +fn a_glide_to_an_offset_runs_no_hover_handler_under_a_still_pointer_until_it_lands() { + for spring in [None, Some(crate::Spring::new(0.18, 0.0))] { + let mut rt = Runtime::new(Heard::default(), heard_rows, (200.0, 200.0), Env::new(true, 1.0)); + rt.frame(0.0); + rt.pointer_move(100.0, 110.0); + rt.frame(1.0 / 120.0); + rt.frame(1.0 / 120.0); + assert_eq!((&rt.state.changes[..], &rt.state.enters[..]), (&[(5, true)][..], &[5][..])); + rt.update_if(move |_, tx| { + match spring { + Some(spring) => tx.scroll_to_with("scroll", 0.0, 400.0, spring), + None => tx.scroll_to("scroll", 0.0, 400.0), + } + false + }); + let commits = rt.stats.commits; + let mut frames = 0; + for _ in 0..600 { + rt.frame(1.0 / 120.0); + if rt.scroll.scrolls.values().all(|s| s.glide().is_none()) { break; } + frames += 1; + } + assert!(frames > 5, "{spring:?}: it glided"); + assert_eq!(rt.stats.commits, commits, "{spring:?}: no hover handler ran mid-glide: {:?}", rt.state.changes); + for _ in 0..30 { rt.frame(1.0 / 120.0); } + assert_eq!(rt.state.changes, [(5, true), (5, false), (25, true)], "{spring:?}: once it lands, hover resolves once at the pointer"); + assert_eq!(rt.state.enters, [5, 25], "{spring:?}"); + assert!(!rt.pointer.hover_hold().held()); + } +} diff --git a/app/vendor/rune/crates/rune/src/runtime/tests/scroll_retarget.rs b/app/vendor/rune/crates/rune/src/runtime/tests/scroll_retarget.rs new file mode 100644 index 0000000..e7758af --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/tests/scroll_retarget.rs @@ -0,0 +1,103 @@ +use super::*; + +const DT: f64 = 1.0 / 60.0; + +/// Forty 50-point rows in a 200-point viewport. +fn view(_: &(), _: &mut Cx<()>) -> El { + let rows = col().key("rows").w_full().children((0..40).map(|k| el().key(format!("r{k}")).w_full().h(50.0))); + col().size(200.0, 200.0).child(col().key("scroll").size(200.0, 200.0).scroll(crate::ScrollSpec { stick_bottom: false }).child(rows)) +} + +fn offset(rt: &Runtime<()>) -> f64 { + rt.scroll.scrolls.values().next().unwrap().offset +} + +/// The offset each frame until the glide stops. +fn glide(rt: &mut Runtime<()>) -> Vec<f64> { + let mut path = vec![offset(rt)]; + for _ in 0..240 { + rt.frame(DT); + path.push(offset(rt)); + if rt.scroll.scrolls.values().all(|s| s.glide().is_none()) { break; } + } + path +} + +fn at(to: f32) -> Runtime<()> { + let mut rt = Runtime::new((), view, (200.0, 200.0), Env::new(true, 1.0)); + rt.frame(0.0); + rt.update(|_, tx| tx.scroll_to_instant("scroll", 0.0, to)); + rt.frame(DT); + rt +} + +#[test] +fn a_glide_sent_nearer_mid_flight_stops_there_without_going_past() { + let mut rt = at(1000.0); + rt.update(|_, tx| tx.scroll_to("scroll", 0.0, 0.0)); + for _ in 0..5 { rt.frame(DT); } + let mid = offset(&rt); + assert!(mid < 900.0, "it's well under way: {mid}"); + // A second press sends it to a stop just ahead, while it's still fast. + let to = mid - 40.0; + rt.update(|_, tx| tx.scroll_to("scroll", 0.0, to as f32)); + let path = glide(&mut rt); + let past = path.iter().map(|y| to - y).fold(0.0, f64::max); + assert!(past < 0.05, "it went {past:.2} points past {to:.1} and came back: {path:.1?}"); + assert!(path.windows(2).all(|w| w[1] <= w[0] + 1e-6), "one way only: {path:.1?}"); + assert_eq!(*path.last().unwrap(), to); +} + +#[test] +fn a_glide_sent_further_mid_flight_keeps_its_speed() { + let mut rt = at(1000.0); + rt.update(|_, tx| tx.scroll_to("scroll", 0.0, 500.0)); + for _ in 0..5 { rt.frame(DT); } + let [a, b] = [offset(&rt), { rt.frame(DT); offset(&rt) }]; + rt.update(|_, tx| tx.scroll_to("scroll", 0.0, 0.0)); + rt.frame(DT); + assert!(b - offset(&rt) >= (a - b) - 0.5, "it goes on at least as fast: {a:.1} {b:.1} {:.1}", offset(&rt)); +} + +#[test] +fn a_glide_lands_without_a_last_step() { + let mut rt = at(1000.0); + rt.update(|_, tx| tx.scroll_to("scroll", 0.0, 0.0)); + let path = glide(&mut rt); + let steps: Vec<f64> = path.windows(2).map(|w| w[0] - w[1]).collect(); + let n = steps.len(); + assert!(n > 10, "it glided: {path:.1?}"); + // The landing frame moves no more than a tenth of a point past the frame before's step. + assert!(steps[n - 1] <= steps[n - 2] + 0.1, "the last step jumps: {:.2?}", &steps[n - 4..]); +} + +#[test] +fn a_centring_glide_sent_nearer_mid_flight_stops_there_without_going_past() { + let mut rt = at(0.0); + rt.update(|_, tx| tx.scroll_center("r30")); + for _ in 0..5 { rt.frame(DT); } + let mid = offset(&rt); + // The first row whose centred offset (its top less 75 points) lies just ahead. + let k = ((mid + 40.0 + 75.0) / 50.0).ceil(); + let to = k * 50.0 - 75.0; + assert!(to < 1425.0, "it's well short of r30: {mid}"); + rt.update(|_, tx| tx.scroll_center(format!("r{k}"))); + let path = glide(&mut rt); + let past = path.iter().map(|y| y - to).fold(0.0, f64::max); + assert!(past < 0.05, "it went {past:.2} points past {to:.1} and came back: {path:.1?}"); + assert!(path.windows(2).all(|w| w[1] >= w[0] - 1e-6), "one way only: {path:.1?}"); + assert_eq!(*path.last().unwrap(), to); +} + +#[test] +fn a_centring_glide_sent_further_mid_flight_keeps_its_speed() { + let mut rt = at(0.0); + rt.update(|_, tx| tx.scroll_center("r20")); + for _ in 0..5 { rt.frame(DT); } + let [a, b] = [offset(&rt), { rt.frame(DT); offset(&rt) }]; + rt.update(|_, tx| tx.scroll_center("r35")); + rt.frame(DT); + assert!(offset(&rt) - b >= (b - a) - 0.5, "it goes on at least as fast: {a:.1} {b:.1} {:.1}", offset(&rt)); + glide(&mut rt); + assert_eq!(offset(&rt), 35.0 * 50.0 - 75.0); +} diff --git a/app/vendor/rune/crates/rune/src/runtime/tests/scroll_spring.rs b/app/vendor/rune/crates/rune/src/runtime/tests/scroll_spring.rs new file mode 100644 index 0000000..52ba442 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/tests/scroll_spring.rs @@ -0,0 +1,179 @@ +//! `Tx::scroll_to_with`: a programmatic glide on the app's spring, and glides retargeted by key +//! repeat running as one motion. +//! +//! No scroll request follows the change's motion (`Tx::motion`, `Tx::motion_curve`): each keeps +//! the spring it names, and the tests here hold that. +use super::*; + +const DT: f64 = 1.0 / 120.0; +const ROW: usize = 60; +const VIEW: usize = 300; + +/// Four hundred 60-point rows in a 300-point viewport. +fn view(_: &(), _: &mut Cx<()>) -> El { + let rows = col().key("rows").w_full().children((0..400).map(|k| el().key(format!("r{k}")).w_full().h(ROW as f32))); + col().size(200.0, VIEW as f32).child(col().key("scroll").size(200.0, VIEW as f32).scroll(crate::ScrollSpec { stick_bottom: false }).child(rows)) +} + +fn offset(rt: &Runtime<()>) -> f64 { + rt.scroll.scrolls.values().next().unwrap().offset +} + +fn runtime() -> Runtime<()> { + let mut rt = Runtime::new((), view, (200.0, VIEW as f32), Env::new(true, 1.0)); + rt.frame(0.0); + rt +} + +/// ↓ held for a second at 30 Hz key repeat, at 120 frames a second: each press selects the +/// next row and `ask` keeps it in view, given the offset that lands the row on the viewport's +/// bottom and where the viewport stands. The offset's move each frame of the hold. +fn hold(ask: impl Fn(&mut Tx, f32, f32)) -> Vec<f64> { + let mut rt = runtime(); + let mut moves = Vec::new(); + let mut last = offset(&rt); + for f in 0..120 { + if f % 4 == 0 { + // Row 4 is the last that shows whole at the top: the first press goes to row 5. + let selected = 5 + f / 4; + let y = ((selected + 1) * ROW - VIEW) as f32; + let at = offset(&rt) as f32; + rt.update(|_, tx| ask(tx, y, at)); + } + rt.frame(DT); + moves.push(offset(&rt) - last); + last = offset(&rt); + } + moves +} + +/// The coefficient of variation of `moves`: their spread over their mean. +fn cv(moves: &[f64]) -> f64 { + let mean = moves.iter().sum::<f64>() / moves.len() as f64; + let var = moves.iter().map(|m| (m - mean).powi(2)).sum::<f64>() / moves.len() as f64; + var.sqrt() / mean +} + +/// Over the hold's second half, once the glide has caught up with the presses from rest: the +/// coefficient of variation, and the slowest frame's move against the mean. +fn steady(moves: &[f64]) -> (f64, f64) { + let steady = &moves[moves.len() / 2..]; + let mean = steady.iter().sum::<f64>() / steady.len() as f64; + (cv(steady), steady.iter().copied().fold(f64::MAX, f64::min) / mean) +} + +#[test] +fn key_repeat_retargets_glide_as_one_motion() { + let quick = Spring::new(0.18, 0.0); + let glide = hold(|tx, y, _| tx.scroll_to("scroll", 0.0, y)); + let with = hold(|tx, y, _| tx.scroll_to_with("scroll", 0.0, y, quick)); + // What steps look like: each press starts the glide again from rest. + let stairs = hold(|tx, y, at| { + tx.scroll_to_instant("scroll", 0.0, at); + tx.scroll_to("scroll", 0.0, y); + }); + for (name, moves) in [("glide", &glide), ("quick", &with), ("from rest", &stairs)] { + let (steady_cv, slowest) = steady(moves); + eprintln!("{name}: hold cv {:.3}, steady cv {steady_cv:.3}, slowest {slowest:.2} of the mean, frame 1 {:.2} pt", cv(moves), moves[0]); + } + for (name, moves) in [("glide", &glide), ("quick", &with)] { + let (steady_cv, slowest) = steady(moves); + assert!(steady_cv < 0.05 && slowest > 0.9, "{name}: the glide keeps its speed between presses: cv {steady_cv:.3}, slowest {slowest:.2}: {moves:.1?}"); + } + let (steady_cv, slowest) = steady(&stairs); + assert!(steady_cv > 0.25 && slowest < 0.5, "restarting from rest steps: cv {steady_cv:.3}, slowest {slowest:.2}"); +} + +#[test] +fn a_quicker_spring_covers_more_of_the_first_frame() { + let first = |ask: &dyn Fn(&mut Tx)| { + let mut rt = runtime(); + rt.update(|_, tx| ask(tx)); + rt.frame(DT); + offset(&rt) + }; + let glide = first(&|tx| tx.scroll_to("scroll", 0.0, 500.0)); + let quick = first(&|tx| tx.scroll_to_with("scroll", 0.0, 500.0, Spring::new(0.18, 0.0))); + eprintln!("frame 1 of a 500-point glide: glide {glide:.2} pt, quick {quick:.2} pt"); + assert!(quick > glide * 2.5, "{quick:.2} against {glide:.2}"); +} + +#[test] +fn without_a_spring_a_glide_runs_on_glide() { + let path = |ask: &dyn Fn(&mut Tx)| { + let mut rt = runtime(); + rt.update(|_, tx| ask(tx)); + let mut path = Vec::new(); + for _ in 0..120 { + rt.frame(DT); + path.push(offset(&rt)); + } + path + }; + let glide = path(&|tx| tx.scroll_to("scroll", 0.0, 500.0)); + assert_eq!(glide, path(&|tx| tx.scroll_to_with("scroll", 0.0, 500.0, crate::tok::motion::GLIDE))); + // The same path a spring on `GLIDE` steps from rest. + let (mut d, mut v) = (-500.0f32, 0.0); + for (f, y) in glide.iter().enumerate().take(30) { + (d, v) = crate::tok::motion::GLIDE.sample(d, v, 0.0, DT as f32); + assert!((y - (500.0 + f64::from(d))).abs() < 1e-3, "frame {f}: {y} against {}", 500.0 + d); + } + assert_eq!(*glide.last().unwrap(), 500.0); +} + +#[test] +fn another_glide_after_a_springed_one_runs_on_glide_again() { + let mut rt = runtime(); + rt.update(|_, tx| tx.scroll_to_with("scroll", 0.0, 500.0, Spring::new(0.18, 0.0))); + for _ in 0..120 { rt.frame(DT); } + assert_eq!(offset(&rt), 500.0); + rt.update(|_, tx| tx.scroll_to_bottom("scroll")); + rt.frame(DT); + assert!(rt.scroll.scrolls.values().next().unwrap().spring.is_none(), "a glide to the bottom takes the default spring"); +} + +/// The viewport's offset each of 120 frames of the request `ask` makes. +fn glide_frames(ask: &dyn Fn(&mut Tx)) -> Vec<f64> { + let mut rt = runtime(); + rt.update(|_, tx| ask(tx)); + let mut path = Vec::new(); + for _ in 0..120 { + rt.frame(DT); + path.push(offset(&rt)); + } + path +} + +/// `Tx::motion` and `Tx::motion_curve` move the change's own layout; the scroll requests asked +/// for in the same handler keep the spring each names, so an app tuning its layout curve can't +/// quietly retime a glide. Each path is the one the same request walks without an override. +fn same_glide(name: &str, plain: &dyn Fn(&mut Tx), with_curve: &dyn Fn(&mut Tx), with_spring: &dyn Fn(&mut Tx)) { + let plain = glide_frames(plain); + assert!(plain.last().unwrap() > &0.0, "{name} moved"); + assert_eq!(glide_frames(with_curve), plain, "{name}: `Tx::motion_curve` retimed the scroll"); + assert_eq!(glide_frames(with_spring), plain, "{name}: `Tx::motion` retimed the scroll"); +} + +#[test] +fn a_motion_override_leaves_scroll_requests_alone() { + let curve = rune_motion::Curve::tween(0.3, rune_motion::Easing::EASE_OUT); + let spring = Spring::new(0.18, 0.0); + same_glide( + "scroll_to", + &|tx| tx.scroll_to("scroll", 0.0, 500.0), + &|tx| { tx.motion_curve(curve); tx.scroll_to("scroll", 0.0, 500.0) }, + &|tx| { tx.motion(spring); tx.scroll_to("scroll", 0.0, 500.0) }, + ); + same_glide( + "scroll_to_bottom", + &|tx| tx.scroll_to_bottom("scroll"), + &|tx| { tx.motion_curve(curve); tx.scroll_to_bottom("scroll") }, + &|tx| { tx.motion(spring); tx.scroll_to_bottom("scroll") }, + ); + same_glide( + "scroll_center", + &|tx| tx.scroll_center("r20"), + &|tx| { tx.motion_curve(curve); tx.scroll_center("r20") }, + &|tx| { tx.motion(spring); tx.scroll_center("r20") }, + ); +} diff --git a/app/vendor/rune/crates/rune/src/runtime/tests/secure_text.rs b/app/vendor/rune/crates/rune/src/runtime/tests/secure_text.rs new file mode 100644 index 0000000..c4caf17 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/tests/secure_text.rs @@ -0,0 +1,804 @@ +use super::*; + + +#[test] +fn secure_input_masks_layout_inspector_and_unicode_pointer_indices() { + fn view(s: &crate::TextEdit, _: &mut Cx<crate::TextEdit>) -> El { + crate::text_input(s, crate::TextStyle::new(16.0, 400.0)).single_line().secure() + .key("secret").size(200.0, 40.0).on_edit(|s: &mut crate::TextEdit| s) + } + let mut edit = crate::TextEdit::new("hé🙂"); + edit.focused = true; + let mut rt = Runtime::new(edit, view, (200.0, 40.0), Env::new(true, 1.0)); + rt.frame(0.0); + assert!(rt.state.is_secure() && rt.has_secure_focus()); + assert!(rt.ime_area.is_none()); + assert!(rt.elements().iter().all(|e| e.text.is_none())); + let n = rt.tree.nodes.iter().find(|n| n.key.as_deref() == Some("secret")).unwrap(); + assert_eq!(n.text.as_ref().unwrap().content, "•••"); + let path = n.path.clone(); + let layout = rt.focused_layout().and_then(|l| l.single().cloned()).unwrap(); + let caret = Cursor::from_byte_index(&layout, 6, Affinity::Downstream).geometry(&layout, 1.0); + rt.frame.queue.push(Action::Focus(path, caret.x0 as f32 + 0.1, ((caret.y0 + caret.y1) * 0.5) as f32)); + rt.frame(0.0); + assert_eq!(rt.state.focus, 3); + rt.paste("界"); rt.frame(0.0); + assert_eq!(rt.state.text, "hé界🙂"); + rt.key(KeyEvent { key: crate::Key::Command('a'), mods: Default::default() }); rt.frame(0.0); + rt.key(KeyEvent { key: crate::Key::Command('c'), mods: Default::default() }); rt.frame(0.0); + assert!(rt.copy_request.is_none()); + rt.ime(Ime::Commit("ignored".into())); rt.frame(0.0); + assert_eq!(rt.state.text, "hé界🙂"); + assert!(rt.events.iter().all(|e| !e.contains("hé"))); +} + +/// The app clears its password as the card leaves; the exiting copy of the field must +/// hold no plaintext from that frame on, yet paint the same dots and no placeholder. +#[test] +fn an_exiting_secure_field_paints_dots_without_its_secret() { + use crate::{text_input, TextEdit, TextStyle}; + struct Card { pw: TextEdit, open: bool } + fn view(s: &Card, _: &mut Cx<Card>) -> El { + let mut root = col().key("root").size(200.0, 100.0); + if s.open { + root = root.child(text_input(&s.pw, TextStyle::new(14.0, 400.0)).single_line() + .placeholder("Enter your password", Color::WHITE).key("pw").size(200.0, 40.0) + .transition(Transition::blur_replace()).on_edit(|s: &mut Card| &mut s.pw)); + } + root + } + let mut rt = Runtime::new(Card { pw: TextEdit::new("hunter2").secure(), open: true }, view, (200.0, 100.0), Env::new(true, 2.0)); + rt.frame(0.0); + let painted = rt.instances.iter().filter(|i| i.params[1] == KIND_GLYPH).count(); + rt.update(|s, _| { s.pw.clear(); s.open = false; }); + assert!(rt.frame(1.0 / 60.0)); + let n = rt.tree.nodes.iter().find(|n| n.key.as_deref() == Some("pw")).expect("exiting field stays drawn"); + assert!(rt.is_exiting(n.id)); + let edit = &n.input.as_ref().unwrap().edit; + assert_eq!(edit.text, "•".repeat(7), "only the mask remains"); + assert!(!edit.has_history() && !edit.focused); + assert_eq!(n.text.as_ref().unwrap().content, "•".repeat(7)); + // Exit blur adds balanced layer markers; compare the actual dots, not scope records. + assert_eq!(rt.instances.iter().filter(|i| i.params[1] == KIND_GLYPH).count(), painted, "the same dots, no placeholder"); + assert!(!format!("{:?}", rt.elements()).contains("hunter2")); + + // A revealed secure field must also conceal to bullets on the very first exit frame, + // leaving no plaintext in `input.edit`, `text.content`, `text_layout`, or `Debug`. + let mut rt = Runtime::new( + Card { pw: TextEdit::new("hunter2").secure().revealed(true), open: true }, + view, + (200.0, 100.0), + Env::new(true, 2.0), + ); + rt.frame(0.0); + let n_open = rt.tree.nodes.iter().find(|n| n.key.as_deref() == Some("pw")).unwrap(); + assert_eq!(n_open.text.as_ref().unwrap().content, "hunter2"); + assert!(!format!("{:?}", n_open.input).contains("hunter2")); + assert!(!format!("{:?}", n_open.text).contains("hunter2")); + rt.update(|s, _| { s.pw.clear(); s.open = false; }); + assert!(rt.frame(1.0 / 60.0)); + let n = rt.tree.nodes.iter().find(|n| n.key.as_deref() == Some("pw")).expect("exiting field stays drawn"); + assert!(rt.is_exiting(n.id)); + let edit = &n.input.as_ref().unwrap().edit; + assert!(!edit.is_revealed(), "conceal resets revealed on exit"); + assert_eq!(edit.text, "•".repeat(7), "only the mask remains"); + assert_eq!(n.text.as_ref().unwrap().content, "•".repeat(7)); + assert_eq!(rt.instances.iter().filter(|i| i.params[1] == KIND_GLYPH).count(), painted, "exiting revealed field paints bullets"); + assert!(!format!("{:?}", rt.elements()).contains("hunter2")); + assert!(!format!("{:?}", n.input).contains("hunter2")); + assert!(!format!("{:?}", n.text).contains("hunter2")); +} + +#[test] +fn secure_revealed_display_does_not_survive_in_layout_or_raster_caches() { + use crate::{text_input, TextEdit, TextStyle}; + fn view(s: &TextEdit, _: &mut Cx<TextEdit>) -> El { + col().key("cache").cache().size(240.0, 100.0).child( + text_input(s, TextStyle::new(16.0, 400.0)).key("secret") + .single_line().size(220.0, 40.0).selectable(true) + .text_case(crate::TextCase::Uppercase) + .on_edit(|s: &mut TextEdit| s), + ) + } + let mut rt = Runtime::new(TextEdit::new("sensitive fixture").secure().revealed(true), view, + (240.0, 100.0), Env::new(true, 1.0)); + let cached = rt.text.cached_layout_count(); + rt.frame(0.0); + let i = rt.tree.nodes.iter().position(|n| n.key.as_deref() == Some("secret")).unwrap(); + let n = &rt.tree.nodes[i]; + assert!(!rt.is_selectable(i), "selectable cannot opt secure input into text selection"); + assert_eq!(n.text.as_ref().unwrap().content, "sensitive fixture"); + assert!(n.text.as_ref().unwrap().source.is_none(), "case conversion is ignored on inputs"); + assert_eq!(Rc::strong_count(n.text_layout.as_ref().and_then(crate::text::TextLayout::single).unwrap()), 1, "only the node owns the shaped run"); + assert_eq!(rt.text.cached_layout_count(), cached, "measurement and paint leave no cached run"); + assert!(rt.paint.node_caches.is_empty(), "an unfocused secret also disables ancestor raster caches"); + assert!(rt.text.atlas.resident_caches.is_empty()); + let path = n.path.clone(); + assert!(!rt.selection_menu(&path, 10.0, 10.0), "no context-menu copy"); + rt.set_focus(Some(path), true); + rt.frame(0.0); + let layout = rt.focused_layout().and_then(|l| l.single().cloned()).unwrap(); + assert_eq!(Rc::strong_count(&layout), 1, "input hit testing also bypasses the layout cache"); + drop(layout); + let mut tx = Tx::default(); + // Application key-up hooks may observe their own events, but Rune must not keep + // typed secrets in the dev/event log when such a hook handles the release. + let root = rt.tree.nodes.iter().position(|n| n.key.as_deref() == Some("cache")).unwrap(); + rt.tree.nodes[root].focus.key_up = Some(Rc::new(|_, _, _| true)); + rt.events.clear(); + assert!(rt.route_key_up(&KeyEvent { key: crate::Key::Text("private fixture".into()), mods: Default::default() }, &mut tx)); + assert!(rt.events.iter().any(|e| e == "key-up [redacted]")); + assert!(!format!("{:?}", rt.events).contains("private fixture")); + rt.update(|s, _| s.set_revealed(false)); + rt.frame(0.0); + assert_eq!(rt.text.cached_layout_count(), cached); + rt.update(|s, _| s.clear()); + rt.frame(0.0); + let n = rt.tree.nodes.iter().find(|n| n.key.as_deref() == Some("secret")).unwrap(); + assert!(rt.state.text.is_empty() && n.input.as_ref().unwrap().edit.text.is_empty()); + assert!(n.text.as_ref().unwrap().content.is_empty(), "clearing without exit wipes the display"); + assert_eq!(rt.text.cached_layout_count(), cached); +} + +#[test] +fn revealed_secure_input_matches_plain_layout_and_keeps_protections() { + use crate::{text_input, TextEdit, TextStyle}; + struct Form { + plain: TextEdit, + secret: TextEdit, + } + fn view(s: &Form, _: &mut Cx<Form>) -> El { + let style = TextStyle::new(16.0, 400.0); + col().size(240.0, 100.0) + .child(text_input(&s.plain, style).single_line().key("plain").size(200.0, 40.0).on_edit(|s: &mut Form| &mut s.plain)) + .child(text_input(&s.secret, style).single_line().key("secret").size(200.0, 40.0).on_edit(|s: &mut Form| &mut s.secret)) + } + let mut plain = TextEdit::new("hé🙂 world"); + plain.set_selection(1, 7); + let mut secret = TextEdit::new("hé🙂 world").secure().revealed(true); + secret.set_selection(1, 7); + secret.focused = true; + let mut rt = Runtime::new(Form { plain, secret }, view, (240.0, 100.0), Env::new(true, 1.0)); + rt.frame(0.0); + + assert!(rt.state.secret.is_secure() && rt.state.secret.is_revealed()); + assert!(rt.has_secure_focus()); + assert!(rt.ime_area.is_none()); + let els = rt.elements(); + let plain_el = els.iter().find(|e| e.key.as_deref() == Some("plain")).unwrap(); + let secret_el = els.iter().find(|e| e.key.as_deref() == Some("secret")).unwrap(); + assert_eq!(plain_el.text.as_deref(), Some("hé🙂 world")); + assert!(secret_el.text.is_none(), "accessibility text remains None when revealed"); + + let np = rt.tree.nodes.iter().find(|n| n.key.as_deref() == Some("plain")).unwrap(); + let ns = rt.tree.nodes.iter().find(|n| n.key.as_deref() == Some("secret")).unwrap(); + assert_eq!(ns.text.as_ref().unwrap().content, "hé🙂 world"); + assert!(!format!("{:?}", ns.input).contains("hé🙂")); + assert!(!format!("{:?}", ns.text).contains("hé🙂")); + let lp = np.text_layout.as_ref().and_then(crate::text::TextLayout::single).unwrap().clone(); + let ls = ns.text_layout.as_ref().and_then(crate::text::TextLayout::single).unwrap().clone(); + assert_eq!(lp.full_width(), ls.full_width(), "revealed layout width matches plain text"); + let secret_caret = secret_el.caret.expect("focused revealed field has caret"); + let secret_sel: Vec<[f32; 4]> = rt.instances.iter() + .filter(|i| i.params[1] == KIND_RECT && i.rect[1] >= secret_el.rect[1] && i.rect[1] < secret_el.rect[1] + secret_el.rect[3]) + .map(|i| [i.rect[0] - secret_el.rect[0], i.rect[1] - secret_el.rect[1], i.rect[2], i.rect[3]]) + .collect(); + assert!(!secret_sel.is_empty()); + + // Focus the plain field with the same selection and verify caret and selection rects match. + rt.update(|s, _| { s.secret.focused = false; s.plain.focused = true; }); + rt.frame(0.0); + let plain_el = rt.elements().into_iter().find(|e| e.key.as_deref() == Some("plain")).unwrap(); + let plain_caret = plain_el.caret.expect("focused plain field has caret"); + assert_eq!([plain_caret[0] - plain_el.rect[0], plain_caret[1] - plain_el.rect[1], plain_caret[2], plain_caret[3]], + [secret_caret[0] - secret_el.rect[0], secret_caret[1] - secret_el.rect[1], secret_caret[2], secret_caret[3]]); + let plain_sel: Vec<[f32; 4]> = rt.instances.iter() + .filter(|i| i.params[1] == KIND_RECT && i.rect[1] >= plain_el.rect[1] && i.rect[1] < plain_el.rect[1] + plain_el.rect[3]) + .map(|i| [i.rect[0] - plain_el.rect[0], i.rect[1] - plain_el.rect[1], i.rect[2], i.rect[3]]) + .collect(); + assert_eq!(plain_sel, secret_sel); + + // Refocus secret field: copy, cut, undo and IME must do nothing, and toggling revealed re-measures. + rt.update(|s, _| { s.plain.focused = false; s.secret.focused = true; }); + rt.frame(0.0); + for ch in ['c', 'x'] { + rt.key(KeyEvent { key: crate::Key::Command(ch), mods: crate::Mods { cmd: true, ..Default::default() } }); + rt.frame(0.0); + assert!(rt.copy_request.is_none(), "⌘{} on revealed field must never write to clipboard", ch.to_uppercase()); + assert_eq!(rt.state.secret.text, "hé🙂 world"); + } + rt.ime(Ime::Preedit("comp".into(), Some((0, 4)), Vec::new())); + rt.ime(Ime::Commit("commit".into())); + rt.frame(0.0); + assert_eq!(rt.state.secret.text, "hé🙂 world"); + rt.key(KeyEvent { key: crate::Key::Text("X".into()), mods: Default::default() }); + rt.frame(0.0); + assert_eq!(rt.state.secret.text, "hX world"); + rt.key(KeyEvent { key: crate::Key::Command('z'), mods: crate::Mods { cmd: true, ..Default::default() } }); + rt.frame(0.0); + assert_eq!(rt.state.secret.text, "hX world", "no undo on revealed field"); + + let revealed_w = rt.tree.nodes.iter().find(|n| n.key.as_deref() == Some("secret")).unwrap().text_layout.as_ref().and_then(crate::text::TextLayout::single).unwrap().full_width(); + rt.update(|s, _| { s.secret.set_selection(1, 4); s.secret.set_revealed(false); }); + rt.frame(0.0); + assert_eq!(rt.state.secret.range(), (1, 4), "toggling revealed keeps selection"); + let ns = rt.tree.nodes.iter().find(|n| n.key.as_deref() == Some("secret")).unwrap(); + assert_eq!(ns.text.as_ref().unwrap().content, "••••••••"); + let hidden_w = ns.text_layout.as_ref().and_then(crate::text::TextLayout::single).unwrap().full_width(); + assert_ne!(revealed_w, hidden_w, "toggling revealed re-layouts the text"); +} + +#[test] +fn multiline_secure_input_hides_length_and_lines_wraps_anywhere_and_conceals_on_exit() { + use crate::{text_input, TextEdit, TextStyle}; + struct State { + secret: TextEdit, + open: bool, + } + fn view(s: &State, _: &mut Cx<State>) -> El { + let mut root = col().size(240.0, 200.0); + if s.open { + root = root.child( + text_input(&s.secret, TextStyle::new(14.0, 400.0)) + .secure() + .key("secret") + .w(180.0) + .on_edit(|s: &mut State| &mut s.secret), + ); + } + root + } + + let short_secret = "short-key!"; + let long_secret = (0..50) + .map(|i| format!("FAKEPEMLINE{i:02}AAAAB3NzaC1yc2EAAAADAQABAAABAQDfakebase64payloadblock0123456789ABCDEFGH==")) + .collect::<Vec<_>>() + .join("\n"); + assert!(long_secret.len() >= 4096); + + let mut short_edit = TextEdit::new(short_secret); + short_edit.focused = true; + let mut rt_short = Runtime::new(State { secret: short_edit, open: true }, view, (240.0, 200.0), Env::new(true, 1.0)); + rt_short.frame(0.0); + + let mut long_edit = TextEdit::new(long_secret.clone()); + long_edit.focused = true; + let mut rt_long = Runtime::new(State { secret: long_edit, open: true }, view, (240.0, 200.0), Env::new(true, 1.0)); + rt_long.frame(0.0); + + let el_short = rt_short.elements().into_iter().find(|e| e.key.as_deref() == Some("secret")).unwrap(); + let el_long = rt_long.elements().into_iter().find(|e| e.key.as_deref() == Some("secret")).unwrap(); + assert!(el_short.text.is_none() && el_long.text.is_none()); + assert_eq!(el_short.rect, el_long.rect, "hidden multi-line rect must not leak content length or line count"); + assert_eq!(el_short.caret, el_long.caret, "hidden multi-line caret rect must be identical"); + + let n_short = rt_short.tree.nodes.iter().find(|n| n.key.as_deref() == Some("secret")).unwrap(); + let n_long = rt_long.tree.nodes.iter().find(|n| n.key.as_deref() == Some("secret")).unwrap(); + assert_eq!(n_short.text.as_ref().unwrap().content, crate::edit::MULTILINE_SECURE_MASK); + assert_eq!(n_long.text.as_ref().unwrap().content, crate::edit::MULTILINE_SECURE_MASK); + let l_short = n_short.text_layout.as_ref().and_then(crate::text::TextLayout::single).unwrap(); + let l_long = n_long.text_layout.as_ref().and_then(crate::text::TextLayout::single).unwrap(); + assert_eq!(l_short.len(), 1); + assert_eq!(l_long.len(), 1); + assert_eq!(l_short.full_width(), l_long.full_width()); + let glyphs_short = rt_short.instances.iter().filter(|i| i.params[1] == KIND_GLYPH).count(); + let glyphs_long = rt_long.instances.iter().filter(|i| i.params[1] == KIND_GLYPH).count(); + assert_eq!(glyphs_short, 12); + assert_eq!(glyphs_long, 12); + + // Clicking near the left edge of the hidden mask pins the caret to text.len(), never leaking an interior byte index. + rt_long.pointer_down(el_long.rect[0] + 4.0, el_long.rect[1] + 4.0); + rt_long.pointer_up(el_long.rect[0] + 4.0, el_long.rect[1] + 4.0); + rt_long.frame(0.0); + assert_eq!(rt_long.state.secret.focus, long_secret.len()); + + // Revealing wraps unbroken lines at character boundaries within 180pt width. + rt_long.update(|s, _| s.secret.set_revealed(true)); + rt_long.frame(0.0); + let n_rev = rt_long.tree.nodes.iter().find(|n| n.key.as_deref() == Some("secret")).unwrap(); + let l_rev = n_rev.text_layout.as_ref().and_then(crate::text::TextLayout::single).unwrap(); + assert!(l_rev.len() > 100, "50 long unbroken lines must wrap into >100 visual lines"); + assert!(l_rev.full_width() <= 180.5, "wrapped unbroken lines must fit within field width (got {})", l_rev.full_width()); + + // Exiting while revealed conceals back to the fixed multi-line mask on the first exit frame. + rt_long.update(|s, _| s.open = false); + rt_long.frame(0.0); + let exiting = rt_long.tree.nodes.iter().find(|n| n.key.as_deref() == Some("secret")).expect("exiting node present"); + let exit_edit = &exiting.input.as_ref().unwrap().edit; + assert!(!exit_edit.is_revealed()); + assert_eq!(exit_edit.text, crate::edit::MULTILINE_SECURE_MASK); + assert_eq!(exiting.text.as_ref().unwrap().content, crate::edit::MULTILINE_SECURE_MASK); + assert_eq!(exiting.text_layout.as_ref().and_then(crate::text::TextLayout::single).unwrap().len(), 1); + assert!(!format!("{:?}", exiting.input).contains("FAKEPEMLINE")); + assert!(!format!("{:?}", exiting.text).contains("FAKEPEMLINE")); +} + +#[test] +fn secure_multiline_conceal_snaps_geometry_scroll_and_bypasses_caches() { + fn view(s: &crate::TextEdit, _: &mut Cx<crate::TextEdit>) -> El { + col().cache().w(120.0).child(crate::auto_grow( + crate::text_input(s, crate::TextStyle::new(14.0, 400.0)) + .w_full().key("secret").on_edit(|s: &mut crate::TextEdit| s), 1, 3)) + } + let mut edit = crate::TextEdit::new("fictional line\n".repeat(60)).secure().revealed(true); + edit.focused = true; + let mut rt = Runtime::new(edit, view, (180.0, 200.0), Env::new(true, 1.0)); + rt.frame(0.0); + assert_eq!(rt.text.cached_layout_count(), 0); + assert!(rt.paint.node_caches.is_empty()); + let scroll_id = rt.tree.nodes.iter().find(|n| n.scroll.is_some()).unwrap().id; + assert!(rt.scroll.scrolls[&scroll_id].max > 100.0); + rt.scroll.scrolls.get_mut(&scroll_id).unwrap().offset = 300.0; + rt.update(|s, _| s.set_revealed(false)); // No tx.instant(): conceal must do this itself. + rt.frame(0.0); + let st = &rt.scroll.scrolls[&scroll_id]; + assert_eq!((st.offset, st.max), (0.0, 0.0)); + assert!(st.glide().is_none()); + let elements = rt.elements(); + for e in &elements { + assert_eq!(e.rect[3], e.target[3], "concealed height must not spring: {}", e.path); + } + let secret = rt.tree.nodes.iter().find(|n| n.key.as_deref() == Some("secret")).unwrap(); + assert_eq!(secret.text_layout.as_ref().and_then(crate::text::TextLayout::single).unwrap().len(), 1); + assert_eq!(Rc::strong_count(secret.text_layout.as_ref().and_then(crate::text::TextLayout::single).unwrap()), 1); + assert_eq!(rt.text.cached_layout_count(), 0); + assert!(rt.ime_area.is_none()); + let info = elements.iter().find(|e| e.key.as_deref() == Some("secret")).unwrap(); + assert!(info.text.is_none() && info.selected.is_none()); + + // Even a narrow hidden field keeps one mask line, including after wrap_anywhere. + fn narrow(s: &crate::TextEdit, _: &mut Cx<crate::TextEdit>) -> El { + crate::text_input(s, crate::TextStyle::new(14.0, 400.0)).wrap_anywhere().w(12.0) + } + let mut narrow = Runtime::new(rt.state.clone(), narrow, (50.0, 100.0), Env::new(true, 1.0)); + narrow.frame(0.0); + assert_eq!(narrow.tree.nodes[0].text_layout.as_ref().and_then(crate::text::TextLayout::single).unwrap().len(), 1); +} + +#[test] +fn wrap_anywhere_wraps_unbroken_tokens_keeps_word_breaks_and_lowers_min_content_width() { + use crate::{rich, row, text, Span}; + const LONG_BASE64: &str = "AAAAB3NzaC1yc2EAAAADAQABAAABAQDfakebase64publickeymaterialwithoutspaces0123456789ABCDEF=="; + const WORDS: &str = "alpha beta gamma delta epsilon zeta eta theta"; + + let mut explicit = text("token"); + explicit.style.set_flex_shrink(0.25); + assert_eq!(explicit.wrap_anywhere().style.flex_shrink(), 0.25); + assert_eq!(text("token").wrap_anywhere().style.flex_shrink(), 0.0); + + fn view(_: &(), _: &mut Cx<()>) -> El { + col() + .size(400.0, 500.0) + // Default .wrap() vs .wrap_anywhere() in a narrow 160pt box. + .child(col().w(160.0).child(text(LONG_BASE64).wrap().key("default_wrap"))) + .child(col().w(160.0).child(text(LONG_BASE64).wrap_anywhere().key("anywhere_wrap"))) + // In a flex row, wrap_anywhere lowers min-content width so the flex parent can shrink it. + .child(row().w(160.0).child(text(LONG_BASE64).wrap_anywhere().shrink().key("row_anywhere"))) + // Normal words with spaces in the same 160pt width. + .child(col().w(160.0).child(text(WORDS).wrap().key("words_default"))) + .child(col().w(160.0).child(text(WORDS).wrap_anywhere().key("words_anywhere"))) + // Rich text with wrap_anywhere. + .child(col().w(160.0).child(rich(LONG_BASE64, vec![Span::new(0, 16).bold()]).wrap_anywhere().key("rich_anywhere"))) + } + + let mut rt = Runtime::new((), view, (400.0, 500.0), Env::new(true, 1.0)); + rt.frame(0.0); + + let node = |k: &str| rt.tree.nodes.iter().find(|n| n.key.as_deref() == Some(k)).unwrap(); + let el = |k: &str| rt.elements().into_iter().find(|e| e.key.as_deref() == Some(k)).unwrap(); + + // Default .wrap() does not break inside an unbroken token and keeps its full min-content width. + let def_layout = node("default_wrap").text_layout.as_ref().and_then(crate::text::TextLayout::single).unwrap(); + assert_eq!(def_layout.len(), 1, "default wrap leaves unbroken base64 on 1 line"); + assert!(def_layout.full_width() > 400.0, "default wrap keeps full unbroken token width"); + + // .wrap_anywhere() wraps inside the 160pt box and shrinks inside a 160pt flex row with no glyph past the right edge. + let any_el = el("anywhere_wrap"); + let any_node = node("anywhere_wrap"); + let any_layout = any_node.text_layout.as_ref().and_then(crate::text::TextLayout::single).unwrap(); + assert!(any_el.rect[2] <= 160.5, "wrap_anywhere fits 160pt box (got {})", any_el.rect[2]); + assert!(el("row_anywhere").rect[2] <= 160.5, "wrap_anywhere shrinks inside 160pt flex row (got {})", el("row_anywhere").rect[2]); + assert!(any_layout.len() >= 4, "long base64 wraps across multiple lines (got {})", any_layout.len()); + assert!(any_layout.full_width() <= 160.5, "no line exceeds the 160pt box (got {})", any_layout.full_width()); + for line in any_layout.lines() { + assert!( + line.metrics().advance - line.metrics().hanging_advance <= 160.5, + "line advance {} exceeds 160pt right edge", + line.metrics().advance + ); + } + + // Min-content width (max_width = Some(0.0)) shrinks from the full token width to a single character's width. + let min_def = rt.text.layout_for_spec(&node("default_wrap").text.as_ref().unwrap().as_text_input(1.0, false), 1.0, Some(0.0), parley::Alignment::Start); + let min_any = rt.text.layout_for_spec(&any_node.text.as_ref().unwrap().as_text_input(1.0, false), 1.0, Some(0.0), parley::Alignment::Start); + assert!(min_def.full_width() > 400.0); + assert!(min_any.full_width() < 20.0, "wrap_anywhere min-content width is a single grapheme (got {})", min_any.full_width()); + + // Normal words that fit on a line still break at spaces identically to .wrap(). + let w_def = node("words_default").text_layout.as_ref().and_then(crate::text::TextLayout::single).unwrap(); + let w_any = node("words_anywhere").text_layout.as_ref().and_then(crate::text::TextLayout::single).unwrap(); + let ranges_def: Vec<_> = w_def.lines().map(|l| l.text_range()).collect(); + let ranges_any: Vec<_> = w_any.lines().map(|l| l.text_range()).collect(); + assert_eq!(ranges_def, ranges_any, "normal words break at spaces identically under wrap_anywhere"); + + // Rich text also supports wrap_anywhere. + let rich_layout = node("rich_anywhere").text_layout.as_ref().and_then(crate::text::TextLayout::single).unwrap(); + assert!(rich_layout.len() >= 4 && rich_layout.full_width() <= 160.5); +} + +#[test] +fn secure_label_masks_reveals_conceals_and_never_leaks_plaintext() { + use crate::{text, Transition}; + const SINGLE_SECRET: &str = "sk-fictional-token-987654"; + const MULTI_SECRET: &str = "-----BEGIN FAKE KEY-----\nAAAAB3NzaC1yc2EAAAADAQABAAABAQDfakebase64payload0123456789ABCDEFGH==\n-----END FAKE KEY-----"; + + #[derive(Clone)] + struct State { + revealed: bool, + open: bool, + } + fn view(s: &State, _: &mut Cx<State>) -> El { + let mut root = col().cache().size(240.0, 240.0); + if s.open { + root = root + .child( + text(SINGLE_SECRET) + .secure() + .revealed(s.revealed) + .selectable(true) + .text_case(crate::TextCase::Uppercase) + .transition(Transition::blur_replace()) + .key("single"), + ) + .child( + text(SINGLE_SECRET) + .selectable(true) + .secure() + .revealed(s.revealed) + .truncate() + .w(60.0) + .key("trunc"), + ) + .child( + col() + .w(140.0) + .max_h(44.0) + .scroll(ScrollSpec { stick_bottom: false }) + .key("scroll") + .child( + text(MULTI_SECRET) + .wrap_anywhere() + .secure() + .revealed(s.revealed) + .transition(Transition::blur_replace()) + .key("multi"), + ), + ) + .child( + col().w(140.0).child( + text(MULTI_SECRET) + .secure() + .max_lines(2) + .revealed(s.revealed) + .key("clamped"), + ), + ); + } + root + } + + let mut rt = Runtime::new(State { revealed: false, open: true }, view, (240.0, 240.0), Env::new(true, 1.0)); + let cached0 = rt.text.cached_layout_count(); + rt.frame(0.0); + + // 1. All hidden labels show the same fixed mask, hiding length and line count. + let check_no_leak = |rt: &mut Runtime<State>| { + let tree = crate::tooling::tree_json(rt, 0.0).to_string(); + let specs: Vec<_> = rt.tree.nodes.iter().map(|n| (&n.text, &n.input)).collect(); + let dbg = format!("{:?} {:?}", rt.elements(), specs); + for needle in ["sk-fictional", "987654", "BEGIN FAKE KEY", "AAAAB3Nza"] { + assert!(!tree.contains(needle), "--tree leaked {needle}: {tree}"); + assert!(!dbg.contains(needle), "Debug/elements leaked {needle}"); + } + assert_eq!(rt.text.cached_layout_count(), cached0, "secure labels must bypass TextSystem layout/shape caches"); + assert!(rt.paint.node_caches.is_empty(), "secure labels must disable ancestor El::cache raster"); + assert!(rt.text.atlas.resident_caches.is_empty()); + for key in ["single", "trunc", "multi", "clamped"] { + let i = rt.tree.nodes.iter().position(|n| n.key.as_deref() == Some(key)).unwrap(); + let path = rt.tree.nodes[i].path.clone(); + assert_eq!(Rc::strong_count(rt.tree.nodes[i].text_layout.as_ref().and_then(crate::text::TextLayout::single).unwrap()), 1, "{key} layout owned only by node"); + assert!(!rt.is_selectable(i), "{key} must not be selectable"); + assert!(!rt.selection_menu(&path, 5.0, 5.0), "{key} must not offer Copy menu"); + let info = rt.elements().into_iter().find(|e| e.key.as_deref() == Some(key)).unwrap(); + assert_eq!(info.role, "text"); + assert!(rt.element_is_secure(&info.path), "{key} must report secure state"); + assert!(info.text.is_none(), "{key} must omit ElementInfo::text"); + assert!(info.selected.is_none(), "{key} must omit ElementInfo::selected"); + } + assert!(tree.contains("\"secure\":true"), "--tree must include secure flag: {tree}"); + }; + check_no_leak(&mut rt); + + let n_single = rt.tree.nodes.iter().find(|n| n.key.as_deref() == Some("single")).unwrap(); + assert_eq!(n_single.text.as_ref().unwrap().content, crate::edit::MULTILINE_SECURE_MASK); + let n_multi = rt.tree.nodes.iter().find(|n| n.key.as_deref() == Some("multi")).unwrap(); + assert_eq!(n_multi.text.as_ref().unwrap().content, crate::edit::MULTILINE_SECURE_MASK); + assert_eq!(n_multi.text_layout.as_ref().and_then(crate::text::TextLayout::single).unwrap().len(), 1); + let n_clamped = rt.tree.nodes.iter().find(|n| n.key.as_deref() == Some("clamped")).unwrap(); + assert_eq!(n_clamped.text.as_ref().unwrap().content, crate::edit::MULTILINE_SECURE_MASK); + assert_eq!(n_clamped.text_layout.as_ref().and_then(crate::text::TextLayout::single).unwrap().len(), 1); + + // Try selecting and copying via pointer + Cmd+C while hidden. + let single_rect = rt.elements().into_iter().find(|e| e.key.as_deref() == Some("single")).unwrap().rect; + rt.pointer_down(single_rect[0] + 2.0, single_rect[1] + 4.0); + rt.pointer_move(single_rect[0] + 60.0, single_rect[1] + 4.0); + rt.pointer_up(single_rect[0] + 60.0, single_rect[1] + 4.0); + rt.key(KeyEvent { key: crate::Key::Command('c'), mods: crate::Mods { cmd: true, ..Default::default() } }); + assert!(rt.selected_text().is_none() && rt.copy_request.is_none()); + + // 2. Revealed state: lays out plaintext (with wrap_anywhere, max_lines, truncate) without leaking to caches/tree/Debug. + rt.update(|s, _| s.revealed = true); + rt.frame(0.0); + check_no_leak(&mut rt); + + let n_single = rt.tree.nodes.iter().find(|n| n.key.as_deref() == Some("single")).unwrap(); + assert_eq!(n_single.text.as_ref().unwrap().content, SINGLE_SECRET); + let n_trunc = rt.tree.nodes.iter().find(|n| n.key.as_deref() == Some("trunc")).unwrap(); + assert!(n_trunc.elided.is_some(), "truncate elides overflowing revealed label"); + let n_multi = rt.tree.nodes.iter().find(|n| n.key.as_deref() == Some("multi")).unwrap(); + assert!(n_multi.text_layout.as_ref().and_then(crate::text::TextLayout::single).unwrap().len() >= 4, "wrap_anywhere wraps revealed multi-line label"); + let n_clamped = rt.tree.nodes.iter().find(|n| n.key.as_deref() == Some("clamped")).unwrap(); + assert_eq!(n_clamped.text_layout.as_ref().and_then(crate::text::TextLayout::single).unwrap().len(), 2, "max_lines(2) clamps revealed multi-line label"); + assert!(n_clamped.elided.is_some()); + + // Try selecting and copying while revealed: still blocked. + rt.pointer_down(single_rect[0] + 2.0, single_rect[1] + 4.0); + rt.pointer_move(single_rect[0] + 60.0, single_rect[1] + 4.0); + rt.pointer_up(single_rect[0] + 60.0, single_rect[1] + 4.0); + rt.key(KeyEvent { key: crate::Key::Command('c'), mods: crate::Mods { cmd: true, ..Default::default() } }); + assert!(rt.selected_text().is_none() && rt.copy_request.is_none()); + + // 3. Concealing (revealed(true) -> revealed(false)) wipes plaintext and snaps geometry and scroll without animating. + let scroll_id = rt.tree.nodes.iter().find(|n| n.key.as_deref() == Some("scroll")).unwrap().id; + assert!(rt.scroll.scrolls[&scroll_id].max > 10.0); + rt.scroll.scrolls.get_mut(&scroll_id).unwrap().offset = 24.0; + rt.update(|s, _| s.revealed = false); // No tx.instant(): conceal must snap itself. + rt.frame(0.0); + check_no_leak(&mut rt); + let st = &rt.scroll.scrolls[&scroll_id]; + assert_eq!((st.offset, st.max), (0.0, 0.0), "concealing resets ancestor scroll immediately"); + for e in rt.elements() { + assert_eq!(e.rect[3], e.target[3], "concealed height must not spring: {}", e.path); + } + let n_multi = rt.tree.nodes.iter().find(|n| n.key.as_deref() == Some("multi")).unwrap(); + assert_eq!(n_multi.text.as_ref().unwrap().content, crate::edit::MULTILINE_SECURE_MASK); + + // 4. Exiting while revealed conceals to the mask on the first exit frame. + rt.update(|s, tx| { + s.revealed = true; + tx.instant(); + }); + rt.frame(0.0); + rt.update(|s, _| s.open = false); + assert!(rt.frame(1.0 / 60.0)); + let ex_single = rt.tree.nodes.iter().find(|n| n.key.as_deref() == Some("single")).expect("exiting single label"); + assert!(rt.is_exiting(ex_single.id)); + assert_eq!(ex_single.text.as_ref().unwrap().content, crate::edit::MULTILINE_SECURE_MASK); + assert!(!format!("{:?}", ex_single.text).contains("sk-fictional")); + + if let Some(dir) = std::env::var_os("RUNE_SECURE_LABEL_STILLS") { + use crate::render::{Gpu, OFFSCREEN_FORMAT, Offscreen, Renderer, write_png}; + use crate::{oklch, row, TextStyle}; + let dir = std::path::PathBuf::from(dir); + std::fs::create_dir_all(&dir).unwrap(); + fn card_view(revealed: &bool, _: &mut Cx<bool>) -> El { + let bg = oklch(0.18, 0.01, 260.0); + let surface = oklch(0.23, 0.012, 260.0); + let border = oklch(0.34, 0.015, 260.0); + let muted = oklch(0.68, 0.015, 260.0); + let fg = oklch(0.95, 0.008, 260.0); + let badge = if *revealed { "REVEALED" } else { "HIDDEN" }; + col() + .size(420.0, 230.0) + .padding(20.0) + .gap(14.0) + .fill(bg) + .child( + row() + .w_full() + .justify_between() + .items_center() + .child(text("Fictional Credential Detail").font(TextStyle::new(14.0, 600.0)).color(fg)) + .child(text(badge).font(TextStyle::new(11.0, 600.0).mono()).color(muted)), + ) + .child( + col() + .w_full() + .padding(12.0) + .gap(6.0) + .fill(surface) + .radius(8.0) + .border(1.0, border) + .child(text("API token (single-line secure label)").font(TextStyle::new(11.0, 500.0)).color(muted)) + .child( + text(SINGLE_SECRET) + .font(TextStyle::new(13.0, 400.0).mono()) + .color(fg) + .secure() + .revealed(*revealed), + ), + ) + .child( + col() + .w_full() + .padding(12.0) + .gap(6.0) + .fill(surface) + .radius(8.0) + .border(1.0, border) + .child(text("SSH key (multi-line secure label, wrap_anywhere)").font(TextStyle::new(11.0, 500.0)).color(muted)) + .child( + text(MULTI_SECRET) + .font(TextStyle::new(12.0, 400.0).mono()) + .color(fg) + .wrap_anywhere() + .secure() + .revealed(*revealed), + ), + ) + } + let gpu = Gpu::headless(); + let (w, h) = (840, 460); + for (name, rev) in [("secure-label-hidden.png", false), ("secure-label-revealed.png", true)] { + let mut rt = Runtime::new(rev, card_view, (420.0, 230.0), Env::new(true, 2.0)); + rt.frame(0.0); + let mut renderer = Renderer::new(&gpu.device, OFFSCREEN_FORMAT); + renderer.prepare(&gpu.device, &gpu.queue, &mut rt.text.atlas, &rt.instances, (w, h)); + renderer.upload_images(&gpu.device, &gpu.queue, &mut rt.images); + let target = Offscreen::new(&gpu.device, w, h); + let mut enc = gpu.device.create_command_encoder(&Default::default()); + renderer.draw(&mut enc, &target.view, [0.07, 0.08, 0.09, 1.0]); + target.copy(&mut enc); + gpu.queue.submit([enc.finish()]); + let out = target.read(&gpu.device); + write_png(&dir.join(name), w, h, &out).unwrap(); + } + } +} + +#[test] +fn secure_rich_labels_have_no_links_flights_or_retained_measure_hashes() { + fn view(revealed: &bool, _: &mut Cx<bool>) -> El { + col().child(crate::rich("fictional-secret", vec![]) + .link(crate::Link::new(0..9, "fictional-url-secret").label("fictional-link-secret")) + .secure().revealed(*revealed).key("secret")) + .child(crate::text("destination").key("target")) + } + let mut rt = Runtime::new(true, view, (300.0, 100.0), Env::new(true, 1.0)); + rt.frame(0.0); + let n = rt.tree.nodes.iter().find(|n| n.key.as_deref() == Some("secret")).unwrap(); + assert!(n.text.as_ref().unwrap().cold.links.is_empty()); + assert_eq!(rt.commit.layout.measure_hash(n.id.0), Some(Some(0))); + assert!(rt.element_is_secure(&n.path)); + assert!(!rt.element_is_secure("missing")); + assert!(!crate::tooling::tree_json(&rt, 0.0).to_string().contains("fictional-")); + rt.capture_text_flight("secret".into(), "target".into()); + assert!(rt.motion.flights().is_empty(), "a revealed secret must not survive as flying glyphs"); + rt.update(|s, _| *s = false); + rt.frame(0.0); + let n = rt.tree.nodes.iter().find(|n| n.key.as_deref() == Some("secret")).unwrap(); + assert_eq!(n.text.as_ref().unwrap().content, crate::edit::MULTILINE_SECURE_MASK); +} + +#[test] +fn hidden_multiline_pristine_composes_with_runtime_and_app_on_change() { + use crate::{text_input, Key, KeyEvent, Mods, TextEdit, TextStyle}; + + struct App { + secret: TextEdit, + saved: String, + app_pristine: bool, + revealed: bool, + } + impl App { + fn new(saved: &str) -> Self { + Self { + secret: TextEdit::new(saved), + saved: saved.to_owned(), + app_pristine: !saved.is_empty(), + revealed: false, + } + } + /// Simulates an app that also implements the pristine-replace rule in `on_input_change`: + /// if `TextEdit` had appended to `saved` while pristine, strip `saved`; if `TextEdit` + /// had deleted a suffix of `saved`, clear it; otherwise keep `secret.text`. + fn on_secret_change(&mut self) { + if self.app_pristine && !self.revealed && !self.saved.is_empty() { + self.app_pristine = false; + if self.secret.text.len() > self.saved.len() + && let Some(inserted) = self.secret.text.strip_prefix(&self.saved) + { + let inserted = inserted.to_owned(); + self.secret.replace_text(inserted); + } else if !self.secret.text.is_empty() + && self.secret.text.len() == self.saved.len() - 1 + && self.saved.starts_with(&self.secret.text) + { + self.secret.clear(); + } + } + } + } + + fn view(s: &App, _: &mut Cx<App>) -> El { + col().size(240.0, 120.0).child( + text_input(&s.secret, TextStyle::new(14.0, 400.0)) + .secure() + .revealed(s.revealed) + .key("secret") + .w(200.0) + .on_edit(|s: &mut App| &mut s.secret) + .on_input_change(|s: &mut App, _| s.on_secret_change()), + ) + } + + let focus_by_click = |rt: &mut Runtime<App>| { + let r = rt.elements().into_iter().find(|e| e.key.as_deref() == Some("secret")).unwrap().rect; + rt.pointer_down(r[0] + 6.0, r[1] + 6.0); + rt.pointer_up(r[0] + 6.0, r[1] + 6.0); + rt.frame(0.0); + }; + + // Case 1: Typing after clicking and pressing arrows replaces the whole value, then appends. + let mut rt = Runtime::new(App::new("old-fictional-private-key\nsecond-line"), view, (240.0, 120.0), Env::new(true, 1.0)); + rt.frame(0.0); + focus_by_click(&mut rt); + rt.key(KeyEvent { key: Key::Left, mods: Mods::default() }); + rt.key(KeyEvent { key: Key::Home, mods: Mods::default() }); + rt.key(KeyEvent { key: Key::Text("x".into()), mods: Mods::default() }); + rt.frame(0.0); + assert_eq!(rt.state.secret.text, "x"); + assert!(!rt.state.secret.is_pristine()); + rt.key(KeyEvent { key: Key::Text("y".into()), mods: Mods::default() }); + rt.frame(0.0); + assert_eq!(rt.state.secret.text, "xy"); + + // Keyboard focus does not consume pristine state either. + let mut tabbed = Runtime::new(App::new("fictional-key"), view, (240.0, 120.0), Env::new(true, 1.0)); + tabbed.frame(0.0); + tabbed.key(KeyEvent { key: Key::Tab, mods: Mods::default() }); + tabbed.frame(0.0); + assert!(tabbed.elements().iter().any(|e| e.key.as_deref() == Some("secret") && e.focused)); + assert!(tabbed.state.secret.is_pristine()); + tabbed.key(KeyEvent { key: Key::Text("t".into()), mods: Mods::default() }); + tabbed.frame(0.0); + assert_eq!(tabbed.state.secret.text, "t"); + + // Case 2: Pasting after Show -> Hide (without editing) replaces the whole value, then appends. + let mut rt = Runtime::new(App::new("old-fictional-private-key\nsecond-line"), view, (240.0, 120.0), Env::new(true, 1.0)); + rt.frame(0.0); + focus_by_click(&mut rt); + rt.update(|s, _| s.revealed = true); + rt.frame(0.0); + rt.update(|s, _| s.revealed = false); + rt.frame(0.0); + assert!(rt.state.secret.is_pristine()); + rt.paste("pasted-key\nline-2"); + rt.frame(0.0); + assert_eq!(rt.state.secret.text, "pasted-key\nline-2"); + rt.paste("\nline-3"); + rt.frame(0.0); + assert_eq!(rt.state.secret.text, "pasted-key\nline-2\nline-3"); + + // Case 3: Backspace while pristine empties the field; subsequent typing starts from "". + let mut rt = Runtime::new(App::new("old-fictional-private-key\nsecond-line"), view, (240.0, 120.0), Env::new(true, 1.0)); + rt.frame(0.0); + focus_by_click(&mut rt); + rt.key(KeyEvent { key: Key::Backspace, mods: Mods::default() }); + rt.frame(0.0); + assert_eq!(rt.state.secret.text, ""); + assert!(!rt.state.secret.is_pristine()); + rt.key(KeyEvent { key: Key::Text("n".into()), mods: Mods::default() }); + rt.frame(0.0); + assert_eq!(rt.state.secret.text, "n"); +} diff --git a/app/vendor/rune/crates/rune/src/runtime/tests/selection_edge_walk.rs b/app/vendor/rune/crates/rune/src/runtime/tests/selection_edge_walk.rs new file mode 100644 index 0000000..0e7cd9b --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/tests/selection_edge_walk.rs @@ -0,0 +1,488 @@ +//! The edge scroll's walk: from each state a selection can be in when the pointer reaches the +//! edge of its virtual list (no press, a press by character, word or paragraph, a press whose +//! anchor row has scrolled out, a press at the list's end), every short sequence of the pointer +//! leaving below or above the list or coming back inside, frames, release, Escape and a lost +//! press, checked after every letter against a reference: `selection_phase_virtual`'s +//! transcription of the code before `selectable::phase`, on forty rows that never change, with +//! the list's offset kept as a number and the rows each spot is over worked out from it. The edge +//! scroll itself and Escape ending a selection drag are new, marked `differs from dev`. +//! Both sides' selection, virtual ends, offset and whether a step is asked for are compared. + +use std::sync::Mutex; +use std::sync::atomic::{AtomicUsize, Ordering}; + +use super::*; +use crate::runtime::selectable::Unit; +use crate::runtime::selectable::phase::Phase; +use crate::{GrowthSpec, Key, KeyEvent, Mods, ScrollSpec, TextStyle, text}; + +/// Sequences of up to this many letters after each seed. +const LENGTH: usize = 4; +const ROWS: usize = 40; +const ROW_H: f64 = 40.0; +const VIEW_H: f64 = 120.0; +/// How far the list scrolls. +const MAX: f64 = ROWS as f64 * ROW_H - VIEW_H; +const LIST: &str = "root/scroll/list"; +const LEN: usize = 6; +const SLOP: f32 = 4.0; +/// One frame, and the speed of a pointer 301 points past an edge (`edge_scroll`'s rate of ten +/// points a second per point, counting from a point inside the edge). +const FRAME: f64 = 1.0 / 60.0; +const SPEED: f32 = 3010.0; + +fn content(row: usize) -> String { format!("row {row:02}") } + +fn path(row: usize) -> String { format!("{LIST}/r{row}") } + +fn row_of(path: &str) -> usize { path.rsplit_once("/r").and_then(|(_, r)| r.parse().ok()).expect("a row path") } + +#[derive(Clone, Copy, Debug, PartialEq)] +enum Spot { HiStart, LoEnd, Below, Above } + +fn point(spot: Spot) -> (f32, f32) { + match spot { + Spot::HiStart => (2.0, 20.0), + Spot::LoEnd => (296.0, 100.0), + Spot::Below => (150.0, 420.0), + Spot::Above => (150.0, -300.0), + } +} + +/// The row under `spot` with the list scrolled to `offset`, and the byte a press or drag there +/// lands on: inside, the row at its height; below the list, the end of its last row that shows; +/// above it, the start of its first. +fn under(spot: Spot, offset: f64) -> (usize, usize) { + let row = |y: f64| ((y / ROW_H).floor() as usize).min(ROWS - 1); + match spot { + Spot::HiStart => (row(offset + 20.0), 0), + Spot::LoEnd => (row(offset + 100.0), LEN), + Spot::Below => (((offset + VIEW_H) / ROW_H).ceil() as usize - 1, LEN), + Spot::Above => (row(offset), 0), + } +} + +#[derive(Clone, Copy, Debug)] +enum Letter { Move(Spot), Tick, Ticks, Up, Escape, Lost } + +const ALPHABET: [Letter; 8] = [ + Letter::Move(Spot::Below), Letter::Move(Spot::Above), Letter::Move(Spot::LoEnd), + Letter::Tick, Letter::Ticks, Letter::Up, Letter::Escape, Letter::Lost, +]; + +#[derive(Clone, Copy, Debug)] +enum Seed { None, Char, Word, Paragraph, Offscreen, AtEnd } + +const SEEDS: [Seed; 6] = [Seed::None, Seed::Char, Seed::Word, Seed::Paragraph, Seed::Offscreen, Seed::AtEnd]; + +fn view(_: &(), _: &mut Cx<()>) -> El { + col().key("root").w(300.0).h(VIEW_H as f32).child( + col().key("scroll").w_full().h(VIEW_H as f32).scroll(ScrollSpec { stick_bottom: false }).child( + col().key("list").w_full().growth(GrowthSpec::default()).selection_group(true).virtual_rows( + ROWS, + ROW_H as f32, + |_: &(), i| format!("r{i}").into(), + |_: &(), i| text(content(i)).font(TextStyle::new(14.0, 400.0)).w_full().h(ROW_H as f32).selectable(true), + ), + ), + ) +} + +#[derive(Clone, Copy, Debug, PartialEq)] +enum U { Char, Word, Paragraph } + +fn unit_at(i: usize, unit: U) -> (usize, usize) { + let i = if i == LEN && unit != U::Char { i - 1 } else { i }; + match unit { + U::Char => (i, i), + U::Paragraph => (0, LEN), + U::Word => match i { 0..=2 => (0, 3), 3 => (3, 4), _ => (4, LEN) }, + } +} + +fn extend(origin: (usize, usize), at: (usize, usize)) -> (usize, usize) { + if at.0 < origin.0 { (origin.1, at.0) } else { (origin.0, at.1.max(origin.1)) } +} + +struct Run { + path: String, + point: (f32, f32), + count: u32, +} + +/// differs from dev: the edge scroll, which dev doesn't have. +#[derive(Clone, Copy, Debug, PartialEq)] +enum EdgeRef { Idle, Running } + +/// The selection as dev kept it (`selection_phase_virtual`'s `Dev`), the list's offset, and the +/// edge scroll. +struct Dev { + path: Option<String>, + content: String, + anchor: usize, + focus: usize, + far: Option<(String, String)>, + unit: U, + origin: (usize, usize), + dragging: bool, + presses: Option<Run>, + offset: f64, + at: Spot, + edge: EdgeRef, +} + +impl Dev { + fn new() -> Self { + Self { + path: None, content: String::new(), anchor: 0, focus: 0, far: None, unit: U::Char, origin: (0, 0), dragging: false, + presses: None, offset: 0.0, at: Spot::HiStart, edge: EdgeRef::Idle, + } + } + + fn press_count(&mut self, path: &str, point: (f32, f32)) -> u32 { + match &mut self.presses { + Some(last) if last.path == path && (point.0 - last.point.0).abs() <= SLOP && (point.1 - last.point.1).abs() <= SLOP => { + last.point = point; + last.count += 1; + last.count + } + _ => { + self.presses = Some(Run { path: path.to_owned(), point, count: 1 }); + 1 + } + } + } + + fn down(&mut self, spot: Spot) { + let (row, at) = under(spot, self.offset); + let clicks = self.press_count(&path(row), point(spot)).min(3); + let unit = match clicks { 1 => U::Char, 2 => U::Word, _ => U::Paragraph }; + let origin = unit_at(at, unit); + (self.unit, self.origin) = (unit, origin); + (self.anchor, self.focus) = origin; + self.path = Some(path(row)); + self.content = content(row); + self.far = None; + self.dragging = true; + self.at = spot; + } + + /// `selection_drag` to `self.at` over the list at its offset. + fn drag(&mut self) { + if !self.dragging { return; } + let Some(h) = self.path.as_deref().map(row_of) else { return }; + let (j, at) = under(self.at, self.offset); + let at = unit_at(at, self.unit); + let (anchor, focus) = if j == h { extend(self.origin, at) } else if j > h { (self.origin.0, at.1) } else { (self.origin.1, at.0) }; + let same_far = if j == h { self.far.is_none() } else { self.far.as_ref().is_some_and(|(p, _)| *p == path(j)) }; + if (self.anchor, self.focus) == (anchor, focus) && same_far { return; } + (self.anchor, self.focus) = (anchor, focus); + if j == h { + self.far = None; + } else if !same_far { + self.far = Some((path(j), content(j))); + } + } + + /// differs from dev: how fast the held pointer scrolls the list, and the room left that way. + fn edge_at(&self) -> Option<(f32, f64)> { + if !self.dragging { return None; } + let e = match self.at { + Spot::Below => (SPEED, MAX - self.offset), + Spot::Above => (-SPEED, self.offset), + _ => return None, + }; + (e.1 > 0.0).then_some(e) + } + + /// The held pointer moved to `spot`. + fn moved(&mut self, spot: Spot) { + self.at = spot; + self.drag(); + // differs from dev: at an edge with room it steps (on from a step it was taking); + // anywhere else it stops. + self.edge = if self.edge_at().is_some() { EdgeRef::Running } else { EdgeRef::Idle }; + } + + /// differs from dev: a frame takes the step due, scrolling and then extending over the + /// list at its new offset; the step that reaches the end is the last. + fn tick(&mut self) { + match self.edge { + EdgeRef::Idle => {} + EdgeRef::Running => { + let Some((speed, room)) = self.edge_at() else { + self.edge = EdgeRef::Idle; + return; + }; + let by = (f64::from(speed) * FRAME).clamp(-room, room); + let landing = room - by.abs() <= 1e-3; + let by = if landing { room.copysign(f64::from(speed)) } else { by }; + self.offset = (self.offset + by).clamp(0.0, MAX); + self.drag(); + self.edge = if landing { EdgeRef::Idle } else { EdgeRef::Running }; + } + } + } + + /// The press ends without a click. + fn let_go(&mut self) { + self.dragging = false; + self.edge = EdgeRef::Idle; + } + + fn text_selection(&self) -> Option<(String, std::ops::Range<usize>)> { + let path = self.path.clone()?; + let h = row_of(&path); + let range = match &self.far { + None => self.anchor.min(self.focus)..self.anchor.max(self.focus), + Some((far, _)) => { + let f = row_of(far); + if f == h { + self.anchor.min(self.focus)..self.anchor.max(self.focus) + } else { + let (a, b) = if h < f { (self.anchor.min(LEN), LEN) } else { (0, self.anchor.min(LEN)) }; + if a < b { a..b } else { self.anchor..self.anchor } + } + } + }; + Some((path, range)) + } +} + +struct Walk { + rt: Runtime<()>, + dev: Dev, + /// Frames the letters ran. + frames: usize, +} + +impl Walk { + fn new() -> Self { + let mut rt = Runtime::new((), view, (300.0, VIEW_H as f32), Env::new(true, 1.0)); + rt.double_click_interval = 0.3; + let mut walk = Self { rt, dev: Dev::new(), frames: 0 }; + walk.settle(); + walk + } + + fn settle(&mut self) { + for _ in 0..60 { + if !self.rt.frame(FRAME) { break; } + } + self.rt.clock = 0.0; + } + + fn offset(&self) -> f64 { self.rt.scroll.scrolls.values().next().expect("one scroll").offset } + + fn to_end(&mut self) { + self.rt.wheel(150.0, 60.0, -10_000.0); + self.settle(); + self.dev.offset = MAX; + } + + fn press(&mut self, spot: Spot) { + let (x, y) = point(spot); + self.rt.pointer_move(x, y); + self.rt.pointer_down(x, y); + self.dev.down(spot); + } + + fn up(&mut self) { + let (x, y) = point(self.dev.at); + self.rt.pointer_up(x, y); + self.dev.drag(); + self.dev.let_go(); + } + + fn reset(&mut self, seed: Seed) { + self.rt.cancel_pointer(); + self.rt.edit.selectable = Default::default(); + self.rt.sync_selection_pins(); + self.rt.frame.queue.retain(|_| false); + self.rt.frame.clear_wake_deadlines(); + if self.offset() != 0.0 { + self.rt.wheel(150.0, 60.0, 10_000.0); + self.settle(); + } + self.rt.clock = 0.0; + self.dev = Dev::new(); + match seed { + Seed::None => {} + Seed::Char => self.press(Spot::HiStart), + Seed::Word | Seed::Paragraph => { + for _ in 0..if matches!(seed, Seed::Word) { 1 } else { 2 } { + self.press(Spot::HiStart); + self.up(); + } + self.press(Spot::HiStart); + } + Seed::Offscreen => { + self.press(Spot::HiStart); + self.to_end(); + } + Seed::AtEnd => { + self.to_end(); + self.press(Spot::LoEnd); + } + } + } + + fn frame(&mut self) { + self.frames += 1; + self.rt.frame(FRAME); + self.dev.tick(); + } + + fn play(&mut self, letter: Letter) -> Result<(), String> { + let frames = self.frames; + match letter { + Letter::Move(spot) => { + let (x, y) = point(spot); + self.rt.pointer_move(x, y); + self.dev.moved(spot); + } + Letter::Tick => self.frame(), + Letter::Ticks => { + for _ in 0..100 { + if self.dev.edge == EdgeRef::Idle { break; } + self.frame(); + } + } + Letter::Up => self.up(), + Letter::Escape => { + self.rt.key(KeyEvent { key: Key::Escape, mods: Mods::default() }); + // differs from dev: Escape ends a selection drag where it stands, without a click. + self.dev.let_go(); + } + Letter::Lost => { + self.rt.cancel_pointer(); + self.dev.let_go(); + } + } + self.compare(letter, self.frames != frames) + } + + /// `framed`: a frame ran since the last letter, so every step asked for before it was taken. + fn compare(&self, letter: Letter, framed: bool) -> Result<(), String> { + let dev = &self.dev; + if (self.offset() - dev.offset).abs() > 1e-6 { + return Err(format!("after {letter:?}: offset {}, dev {}", self.offset(), dev.offset)); + } + let running = dev.edge != EdgeRef::Idle; + if self.rt.edit.selectable.edge.running() != running { + return Err(format!("after {letter:?}: edge running {}, dev {:?}", self.rt.edit.selectable.edge.running(), dev.edge)); + } + if framed && self.rt.wake_deadline().is_some() != running { + return Err(format!("after {letter:?}: wake {:?}, dev {:?}", self.rt.wake_deadline(), dev.edge)); + } + match (&self.rt.edit.selectable.phase, &dev.path) { + (Phase::Empty, None) if !dev.dragging && self.rt.edit.selectable.mounted_between.is_empty() => {} + (phase @ (Phase::Placed(sel) | Phase::Dragging { selection: sel, .. }), Some(path)) => { + let unit = match phase { + Phase::Dragging { unit, .. } => Some(match unit { Unit::Char => U::Char, Unit::Word => U::Word, Unit::Paragraph => U::Paragraph }), + _ => None, + }; + let far = sel.far.as_ref().map(|f| (f.path.clone(), f.content.clone())); + let ours = (&sel.path, &sel.content, sel.anchor, sel.focus, sel.origin, &far, unit); + let theirs = (path, &dev.content, dev.anchor, dev.focus, dev.origin, &dev.far, dev.dragging.then_some(dev.unit)); + if ours != theirs { return Err(format!("after {letter:?}: {ours:?}, dev {theirs:?}")); } + let end = |e: &Option<crate::runtime::selectable::virtual_selection::VirtualEnd>| { + e.as_ref().map(|e| (e.list_path.clone(), e.row_key.clone(), e.row_index, e.rel_path.clone(), e.offset)) + }; + let row = |p: &str| { let r = row_of(p); (LIST.to_owned(), format!("r{r}"), r, String::new()) }; + let (r, k, i, rel) = row(path); + if end(&sel.anchor_end) != Some((r, k, i, rel, dev.anchor)) { + return Err(format!("after {letter:?}: anchor end {:?}", sel.anchor_end)); + } + if let (Some(far), Some((fp, _))) = (&sel.far, &dev.far) { + let (r, k, i, rel) = row(fp); + if end(&far.end) != Some((r, k, i, rel, dev.focus)) { return Err(format!("after {letter:?}: focus end {:?}", far.end)); } + } + let (h, f) = (row_of(path), dev.far.as_ref().map_or(row_of(path), |(p, _)| row_of(p))); + if let Some(k) = self.rt.edit.selectable.mounted_between.keys().find(|k| { + let r: usize = k[1..].parse().unwrap_or(usize::MAX); + r <= h.min(f) || r >= h.max(f) + }) { + return Err(format!("after {letter:?}: row {k} hashed as between rows {h} and {f}")); + } + } + (phase, _) => { + let phase = match phase { Phase::Empty => "empty", Phase::Placed(_) => "placed", Phase::Dragging { .. } => "dragging" }; + return Err(format!("after {letter:?}: {phase}, dev path {:?} dragging {}", dev.path, dev.dragging)); + } + } + let ours = self.rt.text_selection().map(|(p, r)| (p.to_owned(), r)); + if ours != dev.text_selection() { return Err(format!("after {letter:?}: text_selection {ours:?}, dev {:?}", dev.text_selection())); } + Ok(()) + } +} + +fn visit(walk: &mut Walk, seed: Seed, sequence: &mut Vec<Letter>, ran: &mut usize, failure: &mut Option<String>) { + if failure.is_some() { return; } + *ran += 1; + walk.reset(seed); + if let Err(why) = walk.compare(Letter::Up, false) { + *failure = Some(format!("{seed:?} seeded: {why}")); + return; + } + for &letter in sequence.iter() { + if let Err(why) = walk.play(letter) { + *failure = Some(format!("{seed:?} {sequence:?}: {why}")); + return; + } + } + if sequence.len() == LENGTH { return; } + for letter in ALPHABET { + sequence.push(letter); + visit(walk, seed, sequence, ran, failure); + sequence.pop(); + } +} + +#[test] +fn every_short_edge_sequence_leaves_what_the_reference_leaves() { + let jobs: Vec<(Seed, Letter)> = SEEDS.iter().flat_map(|&s| ALPHABET.iter().map(move |&l| (s, l))).collect(); + let next = AtomicUsize::new(0); + let results = Mutex::new(Vec::new()); + let workers = std::thread::available_parallelism().map_or(4, |n| n.get()).min(8); + std::thread::scope(|scope| { + for _ in 0..workers { + scope.spawn(|| { + let mut walk = Walk::new(); + let (mut ran, mut failure) = (0, None); + while let Some(&(seed, letter)) = jobs.get(next.fetch_add(1, Ordering::Relaxed)) { + visit(&mut walk, seed, &mut vec![letter], &mut ran, &mut failure); + } + results.lock().unwrap().push((ran, failure)); + }); + } + }); + let mut total = 0; + let mut failures = Vec::new(); + for (ran, failure) in results.into_inner().unwrap() { + total += ran; + failures.extend(failure); + } + println!("{total} sequences up to length {LENGTH}"); + assert!(failures.is_empty(), "sequences differ from the reference: {failures:#?}"); + let expected: usize = SEEDS.len() * (1..=LENGTH as u32).map(|n| ALPHABET.len().pow(n)).sum::<usize>(); + assert_eq!(total, expected, "every sequence ran"); +} + +/// The facts the reference takes as constants: how far the list scrolls, which row each spot is +/// over at either end, and that a seed's anchor row scrolls out. +#[test] +fn the_edge_reference_knows_the_list() { + let mut walk = Walk::new(); + walk.to_end(); + assert_eq!(walk.offset(), MAX); + walk.reset(Seed::Offscreen); + assert!(!walk.rt.commit.virtuals[LIST].range.contains(&0), "{:?}", walk.rt.commit.virtuals[LIST].range); + for (seed, at) in [(Seed::Char, (0, 0)), (Seed::AtEnd, (ROWS - 1, LEN))] { + walk.reset(seed); + assert_eq!(walk.rt.text_selection(), Some((path(at.0).as_str(), at.1..at.1)), "{seed:?}"); + } + assert_eq!(under(Spot::Below, 0.0), (2, LEN)); + assert_eq!(under(Spot::Below, MAX), (ROWS - 1, LEN)); + assert_eq!(under(Spot::Above, MAX), (ROWS - 3, 0)); +} diff --git a/app/vendor/rune/crates/rune/src/runtime/tests/selection_phase.rs b/app/vendor/rune/crates/rune/src/runtime/tests/selection_phase.rs new file mode 100644 index 0000000..261e746 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/tests/selection_phase.rs @@ -0,0 +1,739 @@ +//! Drives every short sequence of selectable-text input through the runtime and checks the +//! selection after every letter against a literal transcription of the code before +//! `selectable::phase` replaced it: one `Held` struct with `path: Option<String>`, `content`, +//! `anchor`, `focus`, `far: Option<(String, String)>`, the `between` hash, `unit`, `origin`, a +//! `dragging: bool`, the run of presses, `shift` and the Select All pick. +//! +//! The reference sees only the letters and the document they edit. It keeps its own fields, its +//! own run of presses and its own copy of the document, and knows the window's few facts as +//! constants: which text each spot is on, the byte a press there lands on (a line's start or +//! end), and the words of these texts. `between` is kept as the list it hashed, which compares +//! the same way. The window has no virtual list, so the virtual ends stay empty on both sides, +//! and both compare that. +//! +//! Two alphabets: one for the orders a press, drag, release, lost release, Shift and the double +//! click interval come in, one for what happens to a selection while it's held or placed (the +//! text changing or remounting under it, focus moving, Select All, the Copy menu's word, a +//! handler clearing it). + +use std::sync::Mutex; +use std::sync::atomic::{AtomicUsize, Ordering}; + +use super::*; +use crate::runtime::selectable::phase::Phase; +use crate::runtime::selectable::Unit; +use crate::{Key, KeyEvent, Mods, PhysicalInput, TextStyle, text}; + +/// Sequences of up to this many letters. +const LENGTH: usize = 5; +/// The double-click interval both sides run with. +const INTERVAL: f64 = 0.3; +/// `CLICK_SLOP`, as the reference transcribes it. +const SLOP: f32 = 4.0; +/// Each text's row height, and the x of a line's start and of a point past its end. +const ROW: f32 = 24.0; +const LEFT: f32 = 2.0; +const RIGHT: f32 = 296.0; +/// `SECONDARY_SELECTS_WORD`, transcribed. +const MENU_SELECTS_WORD: bool = cfg!(target_os = "macos"); + +/// The window's selectable texts, top to bottom: A, M and B in a selection group, C on its own. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum T { A, M, B, C } + +/// Where a pointer letter goes: the start of a text's line, a point past its end, or the empty +/// space under everything. +#[derive(Clone, Copy, Debug, PartialEq)] +enum Spot { Start(T), End(T), Blank } + +fn row(t: T) -> f32 { + match t { T::A => 0.0, T::M => 1.0, T::B => 2.0, T::C => 3.0 } +} + +fn point(spot: Spot) -> (f32, f32) { + match spot { + Spot::Start(t) => (LEFT, row(t) * ROW + ROW / 2.0), + Spot::End(t) => (RIGHT, row(t) * ROW + ROW / 2.0), + Spot::Blank => (LEFT, 150.0), + } +} + +#[derive(Clone, Copy, Debug)] +enum Letter { + Press(Spot), + Drag(Spot), + Up, + Lost, + Shift, + Tick, + Menu, + SelectAll, + Focus, + Append, + Rewrite, + EditM, + Remount, +} + +const POINTER: [Letter; 12] = [ + Letter::Press(Spot::Start(T::A)), Letter::Press(Spot::End(T::A)), Letter::Press(Spot::End(T::B)), + Letter::Press(Spot::Start(T::C)), Letter::Press(Spot::Blank), Letter::Drag(Spot::Start(T::A)), + Letter::Drag(Spot::End(T::B)), Letter::Drag(Spot::End(T::C)), Letter::Up, Letter::Lost, Letter::Shift, Letter::Tick, +]; + +/// `Tx::clear_text_selection` clears through the same call focus moving away does, so a +/// handler's clear plays only in the walk over virtual rows (`selection_phase_virtual`). +const HELD: [Letter; 12] = [ + Letter::Press(Spot::Start(T::A)), Letter::Press(Spot::End(T::B)), Letter::Press(Spot::Start(T::C)), + Letter::Drag(Spot::End(T::B)), Letter::Up, Letter::Menu, Letter::SelectAll, Letter::Focus, + Letter::Append, Letter::Rewrite, Letter::EditM, Letter::Remount, +]; + +/// The app's state: what the letters that edit change. +#[derive(Clone, Default, PartialEq)] +struct Doc { + /// A spacer goes before the group, so the group's unkeyed index (and every path in it) moves. + remounted: bool, + /// Words streamed onto A's end. + appended: u8, + /// A's first letter is capitalised: a change inside what's selected. + rewritten: bool, + /// M, between A and B, is rewritten. + m_edited: bool, +} + +impl Doc { + fn content(&self, t: T) -> String { + match t { + T::A => { + let mut a = if self.rewritten { "Alpha beta".to_owned() } else { "alpha beta".to_owned() }; + for _ in 0..self.appended { a.push_str(" x"); } + a + } + T::M => if self.m_edited { "MIDDLE".to_owned() } else { "middle".to_owned() }, + T::B => "gamma".to_owned(), + T::C => "delta".to_owned(), + } + } + + fn group_path(&self) -> &'static str { + if self.remounted { "root/#1" } else { "root/#0" } + } + + fn path(&self, t: T) -> String { + match t { + T::A => format!("{}/a", self.group_path()), + T::M => format!("{}/m", self.group_path()), + T::B => format!("{}/b", self.group_path()), + T::C => "root/c".to_owned(), + } + } + + /// The live selectable text at `path`. + fn find(&self, path: &str) -> Option<T> { + [T::A, T::M, T::B, T::C].into_iter().find(|&t| self.path(t) == path) + } +} + +fn view(doc: &Doc, _: &mut Cx<Doc>) -> El { + let line = |key: &'static str, content: String| { + text(content).key(key).font(TextStyle::new(14.0, 400.0)).w_full().h(ROW).selectable(true) + }; + let mut root = col().key("root").w(300.0); + if doc.remounted { root = root.child(el().w(300.0).h(0.0)); } + root.child(col().w_full().selection_group(true) + .child(line("a", doc.content(T::A))) + .child(line("m", doc.content(T::M))) + .child(line("b", doc.content(T::B)))) + .child(line("c", doc.content(T::C))) + .child(el().key("button").w(100.0).h(20.0).focusable(true)) + .child(el().key("blank").w_full().h(80.0)) +} + +/// What a press on `t` at `spot` lands on: a line's start, or its end. +fn hit(doc: &Doc, t: T, spot: Spot) -> usize { + match spot { + Spot::Start(_) | Spot::Blank => 0, + Spot::End(_) => doc.content(t).len(), + } +} + +/// Which way the selection's drag reaches: `selectable::Unit`, as the reference keeps it. +#[derive(Clone, Copy, Debug, PartialEq)] +enum U { Char, Word, Paragraph } + +/// `unit_at` on these texts: single lines of ASCII words split by single spaces. +fn unit_at(text: &str, i: usize, unit: U) -> (usize, usize) { + let mut i = i.min(text.len()); + if i > 0 && i == text.len() && unit != U::Char { i -= 1; } + match unit { + U::Char => (i, i), + U::Paragraph => (0, text.len()), + U::Word => { + let b = text.as_bytes(); + let space = |k: usize| b[k] == b' '; + if text.is_empty() { return (0, 0); } + let (mut a, mut e) = (i, i + 1); + while a > 0 && space(a - 1) == space(i) { a -= 1; } + while e < b.len() && space(e) == space(i) { e += 1; } + (a, e) + } + } +} + +/// `extend`, transcribed. +fn extend(origin: (usize, usize), at: (usize, usize)) -> (usize, usize) { + if at.0 < origin.0 { (origin.1, at.0) } else { (origin.0, at.1.max(origin.1)) } +} + +/// `kept`, transcribed. +fn kept(then: &str, now: &str, upto: usize) -> bool { + if upto == 0 { return now.starts_with(then); } + then.get(..upto).is_some_and(|a| now.get(..upto) == Some(a)) +} + +/// `same_keyed_path`, transcribed. +fn same_keyed_path(a: &str, b: &str) -> bool { + fn split(p: &str) -> Option<(&str, &str)> { + let last_key = p.rmatch_indices('/').find(|&(i, _)| !p[i + 1..].starts_with('#')) + .map_or_else(|| (!p.starts_with('#')).then_some(0), |(i, _)| Some(i + 1))?; + let end = last_key + p[last_key..].find('/').unwrap_or(p.len() - last_key); + Some((&p[..end], &p[end..])) + } + let (Some((ka, ta)), Some((kb, tb))) = (split(a), split(b)) else { return false }; + ta == tb && ka.split('/').filter(|s| !s.starts_with('#')).eq(kb.split('/').filter(|s| !s.starts_with('#'))) +} + +fn grouped(t: T) -> bool { t != T::C } + +fn order(t: T) -> f32 { row(t) } + +/// `end_same_group`: both in the one group. +fn same_group(a: T, b: T) -> bool { grouped(a) && grouped(b) } + +/// `press_run::PressRun`'s last press. +struct Run { + path: String, + at: f64, + point: (f32, f32), + count: u32, +} + +/// What Select All's pick names in the window now. +enum Picked { Group, Text(T) } + +/// `selectable::Held` and the runtime's selection code before `selectable::phase`, field for +/// field. +struct Dev { + path: Option<String>, + content: String, + anchor: usize, + focus: usize, + far: Option<(String, String)>, + /// The texts the `between` hash was taken over. + between: Vec<(String, String)>, + unit: U, + origin: (usize, usize), + dragging: bool, + presses: Option<Run>, + shift: bool, + pick: Option<String>, +} + +impl Dev { + fn new() -> Self { + Self { path: None, content: String::new(), anchor: 0, focus: 0, far: None, between: Vec::new(), unit: U::Char, + origin: (0, 0), dragging: false, presses: None, shift: false, pick: None } + } + + fn press_count(&mut self, path: &str, now: f64, point: (f32, f32)) -> u32 { + let follows = |then: f64, was: (f32, f32)| { + now - then <= INTERVAL && (point.0 - was.0).abs() <= SLOP && (point.1 - was.1).abs() <= SLOP + }; + match &mut self.presses { + Some(last) if last.path == path && follows(last.at, last.point) => { + (last.at, last.point) = (now, point); + last.count += 1; + last.count + } + _ => { + self.presses = Some(Run { path: path.to_owned(), at: now, point, count: 1 }); + 1 + } + } + } + + /// `selection_holder_end`. + fn holder(&self, doc: &Doc) -> Option<T> { + let path = self.path.as_deref()?; + let h = doc.find(path)?; + let upto = match &self.far { + None => self.anchor.max(self.focus).max(self.origin.1), + Some((far, _)) if doc.find(far).is_some_and(|f| order(f) > order(h)) => self.content.len(), + Some(_) => self.anchor.max(self.origin.1), + }; + kept(&self.content, &doc.content(h), upto).then_some(h) + } + + /// `focus_holder_end`. + fn focus_holder(&self, doc: &Doc, holder: T) -> Option<T> { + let Some((path, content)) = &self.far else { return Some(holder) }; + let f = doc.find(path)?; + let upto = if order(f) > order(holder) { self.focus } else { content.len() }; + (same_group(f, holder) && kept(content, &doc.content(f), upto)).then_some(f) + } + + fn ends(&self, doc: &Doc) -> Option<(T, T)> { + let h = self.holder(doc)?; + Some((h, self.focus_holder(doc, h)?)) + } + + /// `selection_ranges`. + fn ranges(&self, doc: &Doc) -> Vec<(T, usize, usize)> { + let Some((h, f)) = self.ends(doc) else { return Vec::new() }; + if f == h { + let (a, b) = (self.anchor.min(self.focus), self.anchor.max(self.focus)); + return if a < b && b <= doc.content(h).len() { vec![(h, a, b)] } else { Vec::new() }; + } + let ((first, a), (last, b)) = if order(h) < order(f) { ((h, self.anchor), (f, self.focus)) } else { ((f, self.focus), (h, self.anchor)) }; + [T::A, T::M, T::B].into_iter().filter(|&j| order(j) >= order(first) && order(j) <= order(last)).filter_map(|j| { + let len = doc.content(j).len(); + let (a, b) = (if j == first { a.min(len) } else { 0 }, if j == last { b.min(len) } else { len }); + (a < b).then_some((j, a, b)) + }).collect() + } + + /// `Runtime::text_selection`. + fn text_selection(&self, doc: &Doc) -> Option<(String, std::ops::Range<usize>)> { + let h = self.holder(doc)?; + let range = match &self.far { + None => self.anchor.min(self.focus)..self.anchor.max(self.focus), + Some(_) => { + let f = self.focus_holder(doc, h)?; + if f == h { + self.anchor.min(self.focus)..self.anchor.max(self.focus) + } else { + let len = doc.content(h).len(); + let (a, b) = if order(h) < order(f) { (self.anchor.min(len), len) } else { (0, self.anchor.min(len)) }; + if a < b { a..b } else { self.anchor..self.anchor } + } + } + }; + Some((self.path.clone()?, range)) + } + + /// `between_hash_ends`, as the texts it hashes. + fn between_texts(&self, doc: &Doc, h: T, f: T) -> Vec<(String, String)> { + if h == f || !grouped(h) { return Vec::new(); } + let (first, last) = if order(h) < order(f) { (h, f) } else { (f, h) }; + [T::A, T::M, T::B].into_iter().filter(|&j| order(j) > order(first) && order(j) < order(last)) + .map(|j| (doc.path(j), doc.content(j))).collect() + } + + /// `seal_between`, with `sync_selection_pins` a no-op without virtual lists, and + /// `remember_pick`. + fn seal(&mut self, doc: &Doc) { + self.between = match self.ends(doc) { + None => Vec::new(), + Some((h, f)) => self.between_texts(doc, h, f), + }; + if let Some(h) = self.holder(doc) { + self.pick = Some(if grouped(h) { doc.group_path().to_owned() } else { doc.path(h) }); + } + } + + /// `clear_text_selection`: `clear_held`, then the pins. + fn clear(&mut self) { + self.path = None; + self.far = None; + self.dragging = false; + } + + /// `selection_down` from `press_selection`. + fn down(&mut self, doc: &Doc, spot: Spot, now: f64) { + let target = match spot { Spot::Start(t) | Spot::End(t) => Some(t), Spot::Blank => None }; + let Some(i) = target else { + self.clear(); + self.presses = None; + return; + }; + let at = hit(doc, i, spot); + let (path, content) = (doc.path(i), doc.content(i)); + let clicks = self.press_count(&path, now, point(spot)).min(3); + let holder = self.holder(doc).filter(|&h| h == i || same_group(h, i)); + match holder { + Some(h) if clicks == 1 && self.shift => { + self.unit = U::Char; + self.origin = (self.anchor, self.anchor); + self.focus = at; + self.far = (h != i).then_some((path, content)); + } + _ => { + let unit = match clicks { 1 => U::Char, 2 => U::Word, _ => U::Paragraph }; + let origin = unit_at(&content, at, unit); + (self.unit, self.origin) = (unit, origin); + (self.anchor, self.focus) = origin; + self.path = Some(path); + self.content = content; + self.far = None; + } + } + self.dragging = true; + self.seal(doc); + } + + /// `selection_drag`: in the group a spot below it reaches B's end; C, on its own, takes the + /// byte its own line has under the spot's x. + fn drag(&mut self, doc: &Doc, spot: Spot) { + if !self.dragging { return; } + let Some(h) = self.holder(doc) else { self.clear(); return }; + let (j, at) = if grouped(h) { + match spot { + Spot::Start(t) | Spot::End(t) if grouped(t) => (t, hit(doc, t, spot)), + _ => (T::B, doc.content(T::B).len()), + } + } else { + (h, hit(doc, h, spot)) + }; + let at = unit_at(&doc.content(j), at, self.unit); + let (anchor, focus) = if j == h { + extend(self.origin, at) + } else if order(j) > order(h) { + (self.origin.0, at.1) + } else { + (self.origin.1, at.0) + }; + let same_far = if j == h { self.far.is_none() } else { self.far.as_ref().is_some_and(|(p, _)| *p == doc.path(j)) }; + if (self.anchor, self.focus) == (anchor, focus) && same_far { return; } + self.anchor = anchor; + self.focus = focus; + if j == h { + self.far = None; + } else if !same_far { + self.far = Some((doc.path(j), doc.content(j))); + } + if !same_far { self.seal(doc); } + } + + /// `selection_menu` on A's start. + fn menu(&mut self, doc: &Doc) { + let at = 0; + if MENU_SELECTS_WORD && self.ranges(doc).iter().find(|r| r.0 == T::A).is_none_or(|r| at < r.1 || at >= r.2) { + let content = doc.content(T::A); + let (a, b) = unit_at(&content, at, U::Word); + *self = Dev { path: Some(doc.path(T::A)), content, anchor: a, focus: b, far: None, between: Vec::new(), unit: U::Word, + origin: (a, b), dragging: false, presses: None, shift: self.shift, pick: self.pick.take() }; + self.seal(doc); + } + } + + /// `selection_key` for Cmd+A, then `select_all_key`. + fn select_all(&mut self, doc: &Doc) { + let holder = self.holder(doc); + if holder.is_none() { self.clear(); } + let target = match holder { + Some(h) => Some(if grouped(h) { Picked::Group } else { Picked::Text(h) }), + None => self.pick.as_deref().and_then(|p| { + if p == doc.group_path() { Some(Picked::Group) } else { doc.find(p).map(Picked::Text) } + }), + }; + let (first, last) = match target { + Some(Picked::Group) => (T::A, T::B), + Some(Picked::Text(t)) => (t, t), + None => return, + }; + // `select_span_ends`. + let content = doc.content(first); + let far = (first != last).then(|| (doc.path(last), doc.content(last))); + let end = far.as_ref().map_or(content.len(), |f| f.1.len()); + self.origin = if far.is_some() { (0, 0) } else { (0, end) }; + (self.path, self.content, self.anchor, self.focus, self.unit, self.far) = (Some(doc.path(first)), content, 0, end, U::Char, far); + self.dragging = false; + self.seal(doc); + } + + /// `rebound`. + fn rebound(doc: &Doc, path: &str, content: &str, upto: usize) -> Option<T> { + let mut hits = [T::A, T::M, T::B, T::C].into_iter() + .filter(|&t| same_keyed_path(path, &doc.path(t)) && kept(content, &doc.content(t), upto)); + let first = hits.next()?; + hits.next().is_none().then_some(first) + } + + /// `prune_text_selection`, after a commit. + fn prune(&mut self, doc: &Doc) { + if self.path.is_none() { return; } + let mut rebind = false; + if self.holder(doc).is_none() + && let Some(old) = self.path.clone() + && let Some(i) = Self::rebound(doc, &old, &self.content, self.anchor.max(self.focus).max(self.origin.1)) + { + self.path = Some(doc.path(i)); + rebind = true; + } + if let Some(h) = self.holder(doc) + && self.focus_holder(doc, h).is_none() + && let Some((far, content)) = self.far.clone() + && let Some(j) = Self::rebound(doc, &far, &content, self.focus) + { + self.far = Some((doc.path(j), content)); + rebind = true; + } + if rebind && let Some((h, f)) = self.ends(doc) { self.between = self.between_texts(doc, h, f); } + let Some((h, f)) = self.ends(doc) else { self.clear(); return }; + if self.far.is_some() && self.between_texts(doc, h, f) != self.between { self.clear(); return; } + self.path = Some(doc.path(h)); + self.content = doc.content(h); + if f != h && let Some(far) = &mut self.far { *far = (doc.path(f), doc.content(f)); } + } + + /// `set_focus` to another element by keyboard. + fn focus_away(&mut self, doc: &Doc) { + if self.text_selection(doc).is_some() { self.clear(); } + } +} + +/// The runtime with the four texts, and the reference. +struct Walk { + rt: Runtime<Doc>, + dev: Dev, + /// The reference's copy of the document. + doc: Doc, + /// The virtual clock both sides read. + now: f64, + /// Where the pointer last went, which a release happens at. + at: Spot, +} + +impl Walk { + fn new() -> Self { + let mut rt = Runtime::new(Doc::default(), view, (320.0, 240.0), Env::new(true, 1.0)); + rt.double_click_interval = INTERVAL; + rt.frame(0.0); + Self { rt, dev: Dev::new(), doc: Doc::default(), now: 0.0, at: Spot::Blank } + } + + /// Whatever the last sequence left goes, without stepping: the next starts with nothing + /// selected on the unedited document. + fn reset(&mut self) { + self.rt.cancel_pointer(); + self.rt.edit.selectable = Default::default(); + self.rt.kbd.held_mods = Mods::default(); + self.rt.frame.queue.retain(|_| false); + self.rt.clock = 0.0; + self.now = 0.0; + if self.rt.state != Doc::default() { + let remounted = self.rt.state.remounted; + self.rt.update(|doc, _| *doc = Doc::default()); + if remounted { self.settle(); } else { self.rt.frame(0.0); } + self.rt.clock = 0.0; + } + self.dev = Dev::new(); + self.doc = Doc::default(); + self.at = Spot::Blank; + } + + /// Runs frames until the window is still, as a host would after a commit: a remounted + /// text takes presses once its entrance is drawn. The clock goes back to the walk's. + fn settle(&mut self) { + for _ in 0..8 { + if !self.rt.frame(1.0) { break; } + } + self.rt.clock = self.now; + } + + /// An edit and its commit. Only a remount needs the window to settle; a text that changes + /// in place takes presses on the next frame. + fn edit(&mut self, f: fn(&mut Doc)) { + let remounted = self.doc.remounted; + f(&mut self.doc); + self.rt.update(|doc, _| f(doc)); + if self.doc.remounted != remounted { self.settle(); } else { self.rt.frame(0.0); } + self.rt.clock = self.now; + self.dev.prune(&self.doc); + } + + /// Plays one letter on the runtime and the reference, and compares what each left behind. + fn play(&mut self, letter: Letter) -> Result<(), String> { + match letter { + Letter::Press(spot) => { + let (x, y) = point(spot); + self.rt.pointer_down(x, y); + self.dev.down(&self.doc, spot, self.now); + self.at = spot; + } + Letter::Drag(spot) => { + let (x, y) = point(spot); + self.rt.pointer_move(x, y); + self.dev.drag(&self.doc, spot); + self.at = spot; + } + Letter::Up => { + let (x, y) = point(self.at); + self.rt.pointer_up(x, y); + // The release moves the pointer to where it is, which drags there again. + self.dev.drag(&self.doc, self.at); + self.dev.dragging = false; + } + Letter::Lost => { + self.rt.cancel_pointer(); + self.dev.dragging = false; + } + Letter::Shift => { + let shift = !self.dev.shift; + self.rt.physical_input(PhysicalInput::Modifiers(Mods { shift, ..Mods::default() })); + self.dev.shift = shift; + } + Letter::Tick => { + self.now += 1.0; + self.rt.clock = self.now; + } + Letter::Menu => { + let (x, y) = point(Spot::Start(T::A)); + self.rt.secondary_down(x, y); + self.rt.secondary_up(x, y); + self.rt.host.popups = Default::default(); + self.dev.menu(&self.doc); + } + Letter::SelectAll => { + // The key waits in the queue for the frame. + self.rt.key(KeyEvent { key: Key::Command('a'), mods: Mods { cmd: true, ..Mods::default() } }); + self.rt.frame(0.0); + self.rt.clock = self.now; + self.dev.select_all(&self.doc); + } + Letter::Focus => { + self.rt.set_focus(Some("root/button".to_owned()), true); + self.rt.set_focus(None, false); + self.dev.focus_away(&self.doc); + } + Letter::Append => self.edit(|doc| doc.appended += 1), + Letter::Rewrite => self.edit(|doc| doc.rewritten = !doc.rewritten), + Letter::EditM => self.edit(|doc| doc.m_edited = !doc.m_edited), + Letter::Remount => self.edit(|doc| doc.remounted = !doc.remounted), + } + self.compare(letter) + } + + fn compare(&self, letter: Letter) -> Result<(), String> { + let dev = &self.dev; + let ours = &self.rt.edit.selectable; + if ours.shift != dev.shift { return Err(format!("after {letter:?}: shift {}, dev {}", ours.shift, dev.shift)); } + match (&ours.phase, &dev.path) { + (Phase::Empty, None) if !dev.dragging => {} + (Phase::Placed(sel) | Phase::Dragging { selection: sel, .. }, Some(path)) => { + let unit = match &ours.phase { + Phase::Dragging { unit, .. } => Some(match unit { Unit::Char => U::Char, Unit::Word => U::Word, Unit::Paragraph => U::Paragraph }), + _ => None, + }; + let far = sel.far.as_ref().map(|f| (f.path.clone(), f.content.clone())); + let ours = (&sel.path, &sel.content, sel.anchor, sel.focus, sel.origin, &far, unit); + let theirs = (path, &dev.content, dev.anchor, dev.focus, dev.origin, &dev.far, dev.dragging.then_some(dev.unit)); + if ours != theirs { return Err(format!("after {letter:?}: {ours:?}, dev {theirs:?}")); } + if sel.anchor_end.is_some() || sel.far.as_ref().is_some_and(|f| f.end.is_some()) || !self.rt.edit.selectable.mounted_between.is_empty() { + return Err(format!("after {letter:?}: virtual ends outside a virtual list")); + } + } + (phase, _) => { + let phase = match phase { Phase::Empty => "empty", Phase::Placed(_) => "placed", Phase::Dragging { .. } => "dragging" }; + return Err(format!("after {letter:?}: {phase}, dev path {:?} dragging {}", dev.path, dev.dragging)); + } + } + let ours = self.rt.text_selection().map(|(p, r)| (p.to_owned(), r)); + let theirs = dev.text_selection(&self.doc); + if ours != theirs { return Err(format!("after {letter:?}: text_selection {ours:?}, dev {theirs:?}")); } + Ok(()) + } +} + +/// Plays every sequence that starts with `sequence`, recording the first one that differs. +fn visit(walk: &mut Walk, alphabet: &[Letter], sequence: &mut Vec<Letter>, ran: &mut usize, failure: &mut Option<String>) { + if failure.is_some() { return; } + *ran += 1; + walk.reset(); + for &letter in sequence.iter() { + if let Err(why) = walk.play(letter) { + *failure = Some(format!("{sequence:?}: {why}")); + return; + } + } + if sequence.len() == LENGTH { return; } + for &letter in alphabet { + sequence.push(letter); + visit(walk, alphabet, sequence, ran, failure); + sequence.pop(); + } +} + +fn walk_all(alphabet: &[Letter]) { + let next = AtomicUsize::new(0); + let results = Mutex::new(Vec::new()); + let workers = std::thread::available_parallelism().map_or(4, |n| n.get()).min(8); + std::thread::scope(|scope| { + for _ in 0..workers { + scope.spawn(|| { + let mut walk = Walk::new(); + let (mut ran, mut failure) = (0, None); + while let Some(&letter) = alphabet.get(next.fetch_add(1, Ordering::Relaxed)) { + visit(&mut walk, alphabet, &mut vec![letter], &mut ran, &mut failure); + } + results.lock().unwrap().push((ran, failure)); + }); + } + }); + let mut total = 0; + let mut failures = Vec::new(); + for (ran, failure) in results.into_inner().unwrap() { + total += ran; + failures.extend(failure); + } + println!("{total} sequences up to length {LENGTH}"); + assert!(failures.is_empty(), "sequences differ from dev: {failures:#?}"); + let expected: usize = (1..=LENGTH as u32).map(|n| alphabet.len().pow(n)).sum(); + assert_eq!(total, expected, "every sequence ran"); +} + +#[test] +fn every_short_sequence_of_presses_drags_and_releases_leaves_what_dev_left() { + walk_all(&POINTER); +} + +#[test] +fn every_short_sequence_of_edits_under_a_selection_leaves_what_dev_left() { + walk_all(&HELD); +} + +/// The facts the reference takes as constants: where a press on each spot lands, and what a +/// drag from C (on its own) reaches at each spot. +#[test] +fn the_reference_knows_where_each_spot_lands() { + let mut walk = Walk::new(); + for t in [T::A, T::M, T::B, T::C] { + for spot in [Spot::Start(t), Spot::End(t)] { + walk.reset(); + let (x, y) = point(spot); + walk.rt.pointer_down(x, y); + let at = hit(&walk.doc, t, spot); + assert_eq!(walk.rt.text_selection(), Some((walk.doc.path(t).as_str(), at..at)), "{spot:?}"); + } + } + for spot in [Spot::Start(T::A), Spot::End(T::A), Spot::End(T::B), Spot::Blank] { + walk.reset(); + let (x, y) = point(Spot::End(T::C)); + walk.rt.pointer_down(x, y); + let (x, y) = point(spot); + walk.rt.pointer_move(x, y); + let len = walk.doc.content(T::C).len(); + let at = hit(&walk.doc, T::C, spot); + assert_eq!(walk.rt.text_selection(), Some(("root/c", at.min(len)..len)), "drag from C to {spot:?}"); + } + walk.reset(); + walk.rt.update(|doc, _| doc.remounted = true); + walk.rt.frame(0.0); + for t in [T::A, T::M, T::B, T::C] { + let doc = Doc { remounted: true, ..Doc::default() }; + assert!(walk.rt.tree.nodes.iter().any(|n| n.path == doc.path(t)), "{t:?} at {}", doc.path(t)); + } + assert!(walk.rt.tree.nodes.iter().any(|n| n.path == "root/#1" && n.selection_group)); +} + diff --git a/app/vendor/rune/crates/rune/src/runtime/tests/selection_phase_virtual.rs b/app/vendor/rune/crates/rune/src/runtime/tests/selection_phase_virtual.rs new file mode 100644 index 0000000..453928f --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/tests/selection_phase_virtual.rs @@ -0,0 +1,408 @@ +//! `selection_phase`'s walk over the rows of a virtual list: a selection whose anchor row +//! scrolls out of the mounted window and back, a drag while the list scrolls, Select All over +//! rows never built, a handler clearing it. The reference is the same transcription of the code +//! before `selectable::phase`, on a list of forty rows that never change, so every text the +//! selection names stays resolvable (its rows are pinned) and only the pointer's row depends on +//! the scroll. Both sides' virtual ends are compared after every letter: the anchor's row and +//! offset, the focus's when it's in another row, and that the mounted rows hashed between them +//! lie strictly between them. + +use std::collections::HashSet; +use std::sync::Mutex; +use std::sync::atomic::{AtomicUsize, Ordering}; + +use super::*; +use crate::runtime::selectable::Unit; +use crate::runtime::selectable::phase::Phase; +use crate::{GrowthSpec, Key, KeyEvent, Mods, ScrollSpec, TextStyle, text}; + +/// Sequences of up to this many letters. +const LENGTH: usize = 5; +const ROWS: usize = 40; +const ROW_H: f32 = 40.0; +const LIST: &str = "root/scroll/list"; +/// What each row reads: every row the same length. +const LEN: usize = 6; +/// `CLICK_SLOP`, as the reference transcribes it. +const SLOP: f32 = 4.0; + +fn content(row: usize) -> String { format!("row {row:02}") } + +fn path(row: usize) -> String { format!("{LIST}/r{row}") } + +fn row_of(path: &str) -> usize { path.rsplit_once("/r").and_then(|(_, r)| r.parse().ok()).expect("a row path") } + +/// The top line of the viewport at its start, or its bottom line past the end. +#[derive(Clone, Copy, Debug, PartialEq)] +enum Spot { HiStart, LoEnd } + +fn point(spot: Spot) -> (f32, f32) { + match spot { Spot::HiStart => (2.0, 20.0), Spot::LoEnd => (296.0, 100.0) } +} + +/// The row under `spot`, with the list scrolled to its top or its end, and the byte a press +/// there lands on. +fn under(spot: Spot, top: bool) -> (usize, usize) { + match (spot, top) { + (Spot::HiStart, true) => (0, 0), + (Spot::LoEnd, true) => (2, LEN), + (Spot::HiStart, false) => (ROWS - 3, 0), + (Spot::LoEnd, false) => (ROWS - 1, LEN), + } +} + +#[derive(Clone, Copy, Debug)] +enum Letter { Press(Spot), Drag(Spot), Up, Lost, Down, Top, SelectAll, Clear } + +const ALPHABET: [Letter; 10] = [ + Letter::Press(Spot::HiStart), Letter::Press(Spot::LoEnd), Letter::Drag(Spot::HiStart), Letter::Drag(Spot::LoEnd), + Letter::Up, Letter::Lost, Letter::Down, Letter::Top, Letter::SelectAll, Letter::Clear, +]; + +fn view(_: &(), _: &mut Cx<()>) -> El { + col().key("root").w(300.0).h(120.0).child( + col().key("scroll").w_full().h(120.0).scroll(ScrollSpec { stick_bottom: false }).child( + col().key("list").w_full().growth(GrowthSpec::default()).selection_group(true).virtual_rows( + ROWS, + ROW_H, + |_: &(), i| format!("r{i}").into(), + |_: &(), i| text(content(i)).font(TextStyle::new(14.0, 400.0)).w_full().h(ROW_H).selectable(true), + ), + ), + ) +} + +#[derive(Clone, Copy, Debug, PartialEq)] +enum U { Char, Word, Paragraph } + +/// `unit_at` on "row NN". +fn unit_at(i: usize, unit: U) -> (usize, usize) { + let i = if i == LEN && unit != U::Char { i - 1 } else { i }; + match unit { + U::Char => (i, i), + U::Paragraph => (0, LEN), + U::Word => match i { 0..=2 => (0, 3), 3 => (3, 4), _ => (4, LEN) }, + } +} + +/// `extend`, transcribed. +fn extend(origin: (usize, usize), at: (usize, usize)) -> (usize, usize) { + if at.0 < origin.0 { (origin.1, at.0) } else { (origin.0, at.1.max(origin.1)) } +} + +struct Run { + path: String, + point: (f32, f32), + count: u32, +} + +/// `selectable::Held` before `selectable::phase`, on rows that never change: the anchor's and +/// the focus's texts always resolve, and resolve to the rows their paths name. +struct Dev { + path: Option<String>, + content: String, + anchor: usize, + focus: usize, + far: Option<(String, String)>, + unit: U, + origin: (usize, usize), + dragging: bool, + presses: Option<Run>, +} + +impl Dev { + fn new() -> Self { + Self { path: None, content: String::new(), anchor: 0, focus: 0, far: None, unit: U::Char, origin: (0, 0), dragging: false, presses: None } + } + + /// `PressRun::press` with the clock standing still. + fn press_count(&mut self, path: &str, point: (f32, f32)) -> u32 { + match &mut self.presses { + Some(last) if last.path == path && (point.0 - last.point.0).abs() <= SLOP && (point.1 - last.point.1).abs() <= SLOP => { + last.point = point; + last.count += 1; + last.count + } + _ => { + self.presses = Some(Run { path: path.to_owned(), point, count: 1 }); + 1 + } + } + } + + fn clear(&mut self) { + self.path = None; + self.far = None; + self.dragging = false; + } + + /// `selection_down` on the row under `spot`: no Shift, so every press starts a selection. + fn down(&mut self, spot: Spot, top: bool) { + let (row, at) = under(spot, top); + let clicks = self.press_count(&path(row), point(spot)).min(3); + let unit = match clicks { 1 => U::Char, 2 => U::Word, _ => U::Paragraph }; + let origin = unit_at(at, unit); + (self.unit, self.origin) = (unit, origin); + (self.anchor, self.focus) = origin; + self.path = Some(path(row)); + self.content = content(row); + self.far = None; + self.dragging = true; + } + + /// `selection_drag`: the group reaches the row the pointer is over. + fn drag(&mut self, spot: Spot, top: bool) { + if !self.dragging { return; } + let Some(h) = self.path.as_deref().map(row_of) else { self.clear(); return }; + let (j, at) = under(spot, top); + let at = unit_at(at, self.unit); + let (anchor, focus) = if j == h { extend(self.origin, at) } else if j > h { (self.origin.0, at.1) } else { (self.origin.1, at.0) }; + let same_far = if j == h { self.far.is_none() } else { self.far.as_ref().is_some_and(|(p, _)| *p == path(j)) }; + if (self.anchor, self.focus) == (anchor, focus) && same_far { return; } + (self.anchor, self.focus) = (anchor, focus); + if j == h { + self.far = None; + } else if !same_far { + self.far = Some((path(j), content(j))); + } + } + + /// `selection_key`'s Cmd+A: the group is the list, so it selects every row. + fn select_all(&mut self) { + let far = (path(ROWS - 1), content(ROWS - 1)); + (self.path, self.content, self.anchor, self.focus, self.origin, self.unit) = (Some(path(0)), content(0), 0, LEN, (0, 0), U::Char); + self.far = Some(far); + self.dragging = false; + } + + /// `Runtime::text_selection`. + fn text_selection(&self) -> Option<(String, std::ops::Range<usize>)> { + let path = self.path.clone()?; + let h = row_of(&path); + let range = match &self.far { + None => self.anchor.min(self.focus)..self.anchor.max(self.focus), + Some((far, _)) => { + let f = row_of(far); + if f == h { + self.anchor.min(self.focus)..self.anchor.max(self.focus) + } else { + let (a, b) = if h < f { (self.anchor.min(LEN), LEN) } else { (0, self.anchor.min(LEN)) }; + if a < b { a..b } else { self.anchor..self.anchor } + } + } + }; + Some((path, range)) + } +} + +struct Walk { + rt: Runtime<()>, + dev: Dev, + /// The list is scrolled to its top (else to its end). + top: bool, + at: Spot, +} + +impl Walk { + fn new() -> Self { + let mut rt = Runtime::new((), view, (300.0, 120.0), Env::new(true, 1.0)); + rt.double_click_interval = 0.3; + let mut walk = Self { rt, dev: Dev::new(), top: true, at: Spot::HiStart }; + walk.settle(); + walk + } + + fn settle(&mut self) { + for _ in 0..60 { + if !self.rt.frame(1.0 / 60.0) { break; } + } + self.rt.clock = 0.0; + } + + fn scroll(&mut self, top: bool) { + self.rt.wheel(150.0, 60.0, if top { 10_000.0 } else { -10_000.0 }); + self.settle(); + self.top = top; + } + + fn reset(&mut self) { + self.rt.cancel_pointer(); + self.rt.edit.selectable = Default::default(); + self.rt.sync_selection_pins(); + self.rt.frame.queue.retain(|_| false); + if !self.top { self.scroll(true); } + self.rt.clock = 0.0; + self.dev = Dev::new(); + self.at = Spot::HiStart; + } + + fn play(&mut self, letter: Letter) -> Result<(), String> { + match letter { + Letter::Press(spot) => { + let (x, y) = point(spot); + self.rt.pointer_down(x, y); + self.dev.down(spot, self.top); + self.at = spot; + } + Letter::Drag(spot) => { + let (x, y) = point(spot); + self.rt.pointer_move(x, y); + self.dev.drag(spot, self.top); + self.at = spot; + } + Letter::Up => { + let (x, y) = point(self.at); + self.rt.pointer_up(x, y); + self.dev.drag(self.at, self.top); + self.dev.dragging = false; + } + Letter::Lost => { + self.rt.cancel_pointer(); + self.dev.dragging = false; + } + Letter::Down => self.scroll(false), + Letter::Top => self.scroll(true), + Letter::SelectAll => { + self.rt.key(KeyEvent { key: Key::Command('a'), mods: Mods { cmd: true, ..Mods::default() } }); + self.settle(); + self.dev.select_all(); + } + Letter::Clear => { + self.rt.update(|_, tx| tx.clear_text_selection()); + self.settle(); + self.dev.clear(); + } + } + self.compare(letter) + } + + fn compare(&self, letter: Letter) -> Result<(), String> { + let dev = &self.dev; + match (&self.rt.edit.selectable.phase, &dev.path) { + (Phase::Empty, None) if !dev.dragging && self.rt.edit.selectable.mounted_between.is_empty() => {} + (phase @ (Phase::Placed(sel) | Phase::Dragging { selection: sel, .. }), Some(path)) => { + let unit = match phase { + Phase::Dragging { unit, .. } => Some(match unit { Unit::Char => U::Char, Unit::Word => U::Word, Unit::Paragraph => U::Paragraph }), + _ => None, + }; + let far = sel.far.as_ref().map(|f| (f.path.clone(), f.content.clone())); + let ours = (&sel.path, &sel.content, sel.anchor, sel.focus, sel.origin, &far, unit); + let theirs = (path, &dev.content, dev.anchor, dev.focus, dev.origin, &dev.far, dev.dragging.then_some(dev.unit)); + if ours != theirs { return Err(format!("after {letter:?}: {ours:?}, dev {theirs:?}")); } + // `sync_selection_pins` names the rows of both ends, at their offsets. + let end = |e: &Option<crate::runtime::selectable::virtual_selection::VirtualEnd>| { + e.as_ref().map(|e| (e.list_path.clone(), e.row_key.clone(), e.row_index, e.rel_path.clone(), e.offset)) + }; + let row = |p: &str| { let r = row_of(p); (LIST.to_owned(), format!("r{r}"), r, String::new()) }; + let (r, k, i, rel) = row(path); + if end(&sel.anchor_end) != Some((r, k, i, rel, dev.anchor)) { + return Err(format!("after {letter:?}: anchor end {:?}", sel.anchor_end)); + } + if let (Some(far), Some((fp, _))) = (&sel.far, &dev.far) { + let (r, k, i, rel) = row(fp); + if end(&far.end) != Some((r, k, i, rel, dev.focus)) { return Err(format!("after {letter:?}: focus end {:?}", far.end)); } + } + let (h, f) = (row_of(path), dev.far.as_ref().map_or(row_of(path), |(p, _)| row_of(p))); + let between: HashSet<String> = (h.min(f) + 1..h.max(f)).map(|r| format!("r{r}")).collect(); + if let Some(k) = self.rt.edit.selectable.mounted_between.keys().find(|k| !between.contains(*k)) { + return Err(format!("after {letter:?}: row {k} hashed as between rows {h} and {f}")); + } + } + (phase, _) => { + let phase = match phase { Phase::Empty => "empty", Phase::Placed(_) => "placed", Phase::Dragging { .. } => "dragging" }; + return Err(format!("after {letter:?}: {phase}, dev path {:?} dragging {}", dev.path, dev.dragging)); + } + } + let ours = self.rt.text_selection().map(|(p, r)| (p.to_owned(), r)); + let theirs = dev.text_selection(); + if ours != theirs { return Err(format!("after {letter:?}: text_selection {ours:?}, dev {theirs:?}")); } + Ok(()) + } +} + +fn visit(walk: &mut Walk, sequence: &mut Vec<Letter>, ran: &mut usize, failure: &mut Option<String>) { + if failure.is_some() { return; } + *ran += 1; + walk.reset(); + for &letter in sequence.iter() { + if let Err(why) = walk.play(letter) { + *failure = Some(format!("{sequence:?}: {why}")); + return; + } + } + if sequence.len() == LENGTH { return; } + for letter in ALPHABET { + sequence.push(letter); + visit(walk, sequence, ran, failure); + sequence.pop(); + } +} + +#[test] +fn every_short_sequence_over_virtual_rows_leaves_what_dev_left() { + let next = AtomicUsize::new(0); + let results = Mutex::new(Vec::new()); + let workers = std::thread::available_parallelism().map_or(4, |n| n.get()).min(8); + std::thread::scope(|scope| { + for _ in 0..workers { + scope.spawn(|| { + let mut walk = Walk::new(); + let (mut ran, mut failure) = (0, None); + while let Some(&letter) = ALPHABET.get(next.fetch_add(1, Ordering::Relaxed)) { + visit(&mut walk, &mut vec![letter], &mut ran, &mut failure); + } + results.lock().unwrap().push((ran, failure)); + }); + } + }); + let mut total = 0; + let mut failures = Vec::new(); + for (ran, failure) in results.into_inner().unwrap() { + total += ran; + failures.extend(failure); + } + println!("{total} sequences up to length {LENGTH}"); + assert!(failures.is_empty(), "sequences differ from dev: {failures:#?}"); + let expected: usize = (1..=LENGTH as u32).map(|n| ALPHABET.len().pow(n)).sum(); + assert_eq!(total, expected, "every sequence ran"); +} + +/// The facts the reference takes as constants: the row under each spot at either end of the +/// list, and that the anchor's row leaves the mounted window when the list scrolls to its end. +#[test] +fn the_virtual_reference_knows_which_row_each_spot_is_on() { + let mut walk = Walk::new(); + for top in [true, false] { + for spot in [Spot::HiStart, Spot::LoEnd] { + walk.reset(); + if !top { walk.scroll(false); } + let (x, y) = point(spot); + walk.rt.pointer_down(x, y); + let (row, at) = under(spot, top); + assert_eq!(walk.rt.text_selection(), Some((path(row).as_str(), at..at)), "{spot:?} top {top}"); + } + } + walk.reset(); + assert!(walk.rt.commit.virtuals[LIST].range.contains(&0)); + walk.scroll(false); + assert!(!walk.rt.commit.virtuals[LIST].range.contains(&0) && !walk.rt.commit.virtuals[LIST].range.contains(&2), "{:?}", walk.rt.commit.virtuals[LIST].range); + walk.scroll(true); + assert!(!walk.rt.commit.virtuals[LIST].range.contains(&(ROWS - 1)), "{:?}", walk.rt.commit.virtuals[LIST].range); +} + +/// A selection made again over the same rows reuses the buckets of the map that hashes the +/// mounted rows between its ends: a press, a handler's clear and the next drag clear it in place. +#[test] +fn a_repeated_drag_across_virtual_rows_keeps_the_mounted_row_map() { + let mut walk = Walk::new(); + let capacity = |walk: &Walk| walk.rt.edit.selectable.mounted_between.capacity(); + for letter in [Letter::Press(Spot::HiStart), Letter::Drag(Spot::LoEnd), Letter::Up] { walk.play(letter).unwrap(); } + assert!(walk.rt.edit.selectable.mounted_between.contains_key("r1"), "row 1 lies between rows 0 and 2"); + let warm = capacity(&walk); + assert!(warm > 0); + for letter in [Letter::Press(Spot::HiStart), Letter::Drag(Spot::LoEnd), Letter::Up, Letter::Clear, Letter::Press(Spot::HiStart), Letter::Drag(Spot::LoEnd)] { + walk.play(letter).unwrap(); + assert_eq!(capacity(&walk), warm, "after {letter:?}"); + } + assert!(walk.rt.edit.selectable.mounted_between.contains_key("r1")); +} diff --git a/app/vendor/rune/crates/rune/src/runtime/tests/settle_input.rs b/app/vendor/rune/crates/rune/src/runtime/tests/settle_input.rs new file mode 100644 index 0000000..6caef34 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/tests/settle_input.rs @@ -0,0 +1,189 @@ +//! A host settle (an uncover, a restore, a shown window) lands the tree the frame began with, +//! never the change that frame's input makes: a dialog closed by the first press or key after +//! the window comes back still plays its exit. +use super::*; +use crate::{Cx, El, Env, Key, KeyEvent, Mods, Spring, Transition, col, el, row}; + +/// A focusable root and a sheet its Escape closes. +struct Sheet { + shown: bool, +} + +fn sheet_view(s: &Sheet, _: &mut Cx<Sheet>) -> El { + col() + .size(200.0, 200.0) + .focusable(true) + .on_key(|s: &mut Sheet, ev: &KeyEvent, _: &mut Tx| { + if ev.key == Key::Escape && s.shown { + s.shown = false; + return true; + } + false + }) + .children( + s.shown + .then(|| el().key("sheet").size(80.0, 40.0).transition(Transition::opacity())), + ) +} + +/// A sheet whose Close button, pressed with the pointer, closes it. +struct Dialog { + shown: bool, +} + +fn dialog_view(s: &Dialog, _: &mut Cx<Dialog>) -> El { + let mut root = col().size(200.0, 200.0); + if s.shown { + root = root.child( + col() + .key("sheet") + .size(160.0, 120.0) + .transition(Transition::opacity()) + .child( + row() + .key("close") + .size(80.0, 24.0) + .on_press(|s: &mut Dialog| s.shown = false), + ), + ); + } + root +} + +/// A spring in flight and a sheet its Escape closes: one settle frame does both. +struct Moving { + x: f32, + shown: bool, +} + +fn moving_view(s: &Moving, _: &mut Cx<Moving>) -> El { + col() + .size(200.0, 200.0) + .focusable(true) + .on_key(|s: &mut Moving, ev: &KeyEvent, _: &mut Tx| { + if ev.key == Key::Escape && s.shown { + s.shown = false; + return true; + } + false + }) + .child(el().key("box").absolute(s.x, 0.0).size(10.0, 10.0)) + .children( + s.shown + .then(|| el().key("sheet").size(80.0, 40.0).transition(Transition::opacity())), + ) +} + +fn find<S: 'static>(rt: &Runtime<S>, key: &str) -> Option<ElementInfo> { + rt.elements().into_iter().find(|e| e.key.as_deref() == Some(key)) +} + +/// The sheet is mounted, exiting, and mid-fade rather than unmounted in the settle frame. +fn assert_exiting<S: 'static>(rt: &Runtime<S>) { + let sheet = find(rt, "sheet").expect("the sheet stays mounted while its exit plays"); + assert!( + sheet.exiting, + "it is exiting, not unmounted in the settle frame: {sheet:?}" + ); + assert!( + sheet.opacity > 0.0 && sheet.opacity < 1.0, + "mid-fade: {}", + sheet.opacity + ); +} + +fn assert_gone<S: 'static>(rt: &mut Runtime<S>) { + for _ in 0..120 { + rt.frame(1.0 / 60.0); + } + assert!(find(rt, "sheet").is_none(), "gone once the exit settles"); +} + +#[test] +fn a_settle_with_input_still_exits_the_element_that_input_removes() { + let mut rt = Runtime::new( + Sheet { shown: true }, + sheet_view, + (200.0, 200.0), + Env::new(true, 1.0), + ); + rt.frame(0.0); + rt.key(KeyEvent { key: Key::Tab, mods: Mods::default() }); + rt.frame(1.0 / 60.0); + // The host's catch-up settle and the input that closes the sheet land on one frame. + rt.settle_all(); + rt.key(KeyEvent { key: Key::Escape, mods: Mods::default() }); + assert!(rt.frame(1.0 / 60.0), "the sheet's exit still animates"); + assert_exiting(&rt); + assert_gone(&mut rt); +} + +/// A frame that lands a settle and changes nothing else still says it painted settled, as it did +/// before the settle moved ahead of the input. +#[test] +fn an_unhandled_key_on_a_settle_frame_still_reports_settled() { + let mut rt = Runtime::new( + Sheet { shown: true }, + sheet_view, + (200.0, 200.0), + Env::new(true, 1.0), + ); + rt.frame(0.0); + rt.key(KeyEvent { key: Key::Tab, mods: Mods::default() }); + rt.frame(1.0 / 60.0); + rt.settle_all(); + rt.key(KeyEvent { key: Key::Enter, mods: Mods::default() }); + rt.frame(1.0 / 60.0); + assert!(rt.settled, "the frame painted the settled tree and says so"); + assert!(find(&rt, "sheet").is_some(), "the unhandled key changed nothing"); +} + +#[test] +fn a_settle_with_a_press_still_exits_the_sheet_that_press_closes() { + let mut rt = Runtime::new( + Dialog { shown: true }, + dialog_view, + (200.0, 200.0), + Env::new(true, 1.0), + ); + rt.frame(0.0); + let close = find(&rt, "close").expect("the Close button").rect; + let (x, y) = (close[0] + close[2] / 2.0, close[1] + close[3] / 2.0); + rt.settle_all(); + rt.pointer_down(x, y); + rt.pointer_up(x, y); + assert!(rt.frame(1.0 / 60.0), "the sheet's exit still animates"); + assert_exiting(&rt); + assert_gone(&mut rt); +} + +#[test] +fn a_settle_lands_running_motion_and_the_input_still_exits() { + let mut rt = Runtime::new( + Moving { x: 0.0, shown: true }, + moving_view, + (200.0, 200.0), + Env::new(true, 1.0), + ); + rt.frame(0.0); + rt.key(KeyEvent { key: Key::Tab, mods: Mods::default() }); + rt.frame(1.0 / 60.0); + rt.update(|s, tx| { + s.x = 80.0; + tx.motion(Spring::new(0.3, 0.0)); + }); + rt.frame(1.0 / 120.0); + rt.frame(0.05); + let mid = rt.presented("box").unwrap().0[0]; + assert!(mid > 0.0 && mid < 80.0 && rt.animating, "in flight: {mid}"); + rt.settle_all(); + rt.key(KeyEvent { key: Key::Escape, mods: Mods::default() }); + rt.frame(1.0 / 60.0); + assert_eq!( + rt.presented("box").unwrap().0[0], + 80.0, + "the settle lands the spring in its frame" + ); + assert_exiting(&rt); + assert_gone(&mut rt); +} diff --git a/app/vendor/rune/crates/rune/src/runtime/tests/shimmer.rs b/app/vendor/rune/crates/rune/src/runtime/tests/shimmer.rs new file mode 100644 index 0000000..c92c69d --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/tests/shimmer.rs @@ -0,0 +1,348 @@ +use super::*; +use crate::render::KIND_GLYPH; +use crate::{Color, TextStyle, text}; + +/// A text shimmer: a clipped window slides across a dim label while the bright copy inside it +/// slides back by the same amount, so the copy stays on the label. Both loops wait out the +/// same delay, which the view works out afresh from the clock each time it builds. +#[derive(Clone, Copy)] +struct Shimmer { + since: f64, + now: f64, + snap: bool, + zoom: f32, + on: bool, + tail: bool, + pad: f32, + ring: bool, + band: f32, + /// When the bright copy mounts (app clock); the window mounts with `on`. + lit_at: f64, +} + +const DIM: Color = Color { r: 0.3, g: 0.3, b: 0.3, a: 1.0 }; +const LIT: Color = Color { r: 1.0, g: 1.0, b: 1.0, a: 1.0 }; +const LABEL_W: f32 = 52.0; +const SPEED: f32 = 90.0; + +fn base() -> Shimmer { + Shimmer { since: 0.0, now: 0.0, snap: true, zoom: 1.0, on: true, tail: false, pad: 0.0, ring: false, band: 30.0, lit_at: f64::NEG_INFINITY } +} + +fn period(s: &Shimmer) -> f64 { f64::from((LABEL_W + s.band) / SPEED) } + +fn shimmer_view(s: &Shimmer, _: &mut Cx<Shimmer>) -> El { + let font = TextStyle::new(13.0, 400.0); + let w = s.band; + let (x0, x1) = (-w, LABEL_W); + let p = period(s); + let delay = { let d = (-(s.now - s.since) / p).rem_euclid(1.0) * p; if d > p - 1e-6 { 0.0 } else { d } }; + let spec = |a: f32, b: f32| rune_motion::LoopSpec { delay, ..rune_motion::LoopSpec::slide(p, [a, 0.0], [b, 0.0]).easing(rune_motion::Easing::LINEAR) }; + let lit = el().key("lit").absolute(0.0, 0.0).w(w).h_full().looping(spec(-x0 / w, -x1 / w)) + .child(text("Working").font(font).color(LIT).absolute(0.0, 0.0)); + let sheen = el().key("sheen").absolute(0.0, 0.0).w(w).h_full().clip_fade(w / 2.0, 0.0, w / 2.0, 0.0) + .looping(spec(x0 / w, x1 / w)).children((s.now >= s.lit_at).then_some(lit)).pixel_snap(s.snap); + let label = crate::row().child(text("Working").key("label").font(font).color(DIM)).children(s.on.then_some(sheen)); + let mut ring = el().key("ring").size(14.0, 14.0); + if s.ring { + for k in 0..3 { + ring = ring.child(el().key(format!("d{k}")).absolute(k as f32 * 5.0, 5.0).size(3.0, 3.0).fill(DIM) + .cycle(crate::Cycle { period: 1.2, phase: k as f32 / 3.0, stops: &[(0.0, 0.2), (0.5, 1.0), (1.0, 0.2)], still: 0.2, fps: 30.0 })); + } + } + let row = crate::row().key("working").h(28.0).gap(8.0).center_y().pb(12.0).child(ring).child(label); + let row = if s.tail { el().w_full().h(28.0).motion(rune_motion::Spring::new(0.3, 0.0)).child(row.absolute(0.0, 0.0).opacity(1.0)) } else { row }; + let content = col().size(400.0, 60.0).pl(s.pad).pt(s.pad / 2.0).child(row); + // The whole UI zoomed, as an app's zoom setting does it. + el().size(400.0, 60.0).center().child(el().size(400.0 / s.zoom, 60.0 / s.zoom).scale(s.zoom).child(content)) +} + +/// For each bright glyph quad, how far (device px) its centre sits from the dim glyph it +/// copies. A glyph drawn between pixels takes a slightly larger quad, and one sampled from its +/// rest-size raster under a zoom that is still settling a larger one again, so sizes match +/// loosely. +fn lit_offsets(rt: &Runtime<Shimmer>) -> Vec<f32> { + let glyphs = |c: Color| rt.instances.iter().filter(|i| i.params[1] == KIND_GLYPH && (i.fill[0] - c.r).abs() < 0.02 && (i.fill[1] - c.g).abs() < 0.02) + .map(|i| i.rect).collect::<Vec<_>>(); + let (dim, lit) = (glyphs(DIM), glyphs(LIT)); + lit.iter().map(|l| { + dim.iter().filter(|d| (d[2] - l[2]).abs() < 3.0 && (d[3] - l[3]).abs() < 3.0) + .map(|d| (l[0] + l[2] / 2.0) - (d[0] + d[2] / 2.0)).min_by(|a, b| a.abs().total_cmp(&b.abs())).unwrap_or(f32::NAN) + }).collect() +} + +/// A shimmer at 2× in the default font smoothing. +fn shimmer_rt(s: Shimmer) -> Runtime<Shimmer> { + Runtime::new(s, shimmer_view, (400.0, 60.0), Env::new(true, 2.0)) +} + +/// Pixel snapping moves a glyph by up to one device px. Above 33 ppem (13 pt zoomed 1.6×) +/// CoreGraphics' pens go to whole pixels, so a copy whose origin is a fraction off can land one +/// more pixel away, as CoreText's would. More is a misplaced copy: these tests check motion, +/// not placement. +const GLYPH_PX: f32 = 2.0; + +fn worst_of(rt: &Runtime<Shimmer>, worst: f32) -> f32 { + let w = lit_offsets(rt).into_iter().fold(0.0f32, |a, b| if b.is_nan() || b.abs() > a.abs() { b } else { a }); + if w.is_nan() || w.abs() > worst.abs() { w } else { worst } +} + +fn run(rt: &mut Runtime<Shimmer>, frames: usize) -> f32 { + let mut worst = 0.0f32; + let dt = 1.0 / 120.0; + for _ in 0..frames { + rt.state.now += dt; + rt.invalidate(); + rt.frame(dt); + worst = worst_of(rt, worst); + } + worst +} + +fn worst_offset(snap: bool, zoom: f32, mount_at: f64) -> f32 { + let s = Shimmer { now: mount_at, snap, zoom, ..base() }; + let mut rt = shimmer_rt(s); + rt.frame(0.0); + run(&mut rt, (period(&s) * 2.5 * 120.0) as usize) +} + +#[test] +fn a_counter_sliding_shimmer_keeps_its_bright_copy_on_the_label() { + let mut bad = Vec::new(); + for zoom in [1.0, 1.1, 0.9, 1.25] { + for snap in [true, false] { + for mount_at in [0.0, 0.5] { + let w = worst_offset(snap, zoom, mount_at); + // An opted-out shimmer over a snapped label rounds its glyphs on its own, up to + // a whole pixel from the label's. + let bound = if snap { GLYPH_PX } else { GLYPH_PX + 1.0 / 64.0 }; + if !(w.abs() < bound) { bad.push((zoom, snap, mount_at, w)); } + } + } + } + assert!(bad.is_empty(), "the bright copy drifts off the label (zoom, snap, mounted at, px): {bad:?}"); +} + +#[test] +fn a_shimmer_that_stops_and_starts_again_keeps_its_bright_copy_on_the_label() { + let mut bad = Vec::new(); + for tail in [false, true] { + for off_frames in [1usize, 6, 60] { + for stop_at in [0.3f64, 0.9, 1.5] { + let s = Shimmer { tail, ..base() }; + let mut rt = shimmer_rt(s); + rt.frame(0.0); + run(&mut rt, (stop_at * 120.0) as usize); + rt.state.on = false; + run(&mut rt, off_frames); + rt.state.on = true; + rt.state.since = rt.state.now; + let w = run(&mut rt, (period(&s) * 2.5 * 120.0) as usize); + if !(w.abs() < GLYPH_PX) { bad.push((tail, off_frames, stop_at, w)); } + } + } + } + assert!(bad.is_empty(), "the bright copy drifts off the label after a restart (tail, frames off, stopped at, px): {bad:?}"); +} + +fn loop_offsets(rt: &Runtime<Shimmer>) -> Option<(f32, f32)> { + let find = |key: &str| rt.tree.nodes.iter().find(|n| n.path.ends_with(key)).map(|n| n.id); + let (s, l) = (find("/sheen")?, find("/lit")?); + let off = |id| rt.scene.get(id, prop::OFFSET).map_or(0.0, |v| v.x); + Some((off(s), off(l))) +} + +#[test] +fn a_shimmer_stopped_while_waiting_restarts_in_step() { + let mut bad = Vec::new(); + for stop_at in [0.2f64, 0.7, 1.2] { + for gap in [0.05f64, 0.5] { + // Mounted 0.8 s into a 2.13 s pass: both loops wait 1.33 s for the next. + let s = Shimmer { since: -0.8, band: 140.0, ..base() }; + let mut rt = shimmer_rt(s); + rt.frame(0.0); + run(&mut rt, (stop_at * 120.0) as usize); + rt.state.on = false; + run(&mut rt, (gap * 120.0) as usize); + rt.state.on = true; + rt.state.since = rt.state.now; + let mut worst = 0.0f32; + for _ in 0..(period(&s) * 1.5 * 120.0) as usize { + rt.state.now += 1.0 / 120.0; + rt.invalidate(); + rt.frame(1.0 / 120.0); + if let Some((a, b)) = loop_offsets(&rt) { + let d = a + b; + if d.abs() > worst.abs() { worst = d; } + } + } + if worst.abs() > 0.01 { bad.push((stop_at, gap, worst)); } + } + } + assert!(bad.is_empty(), "the bright copy's slide falls out of step with its window (stopped at, gap, pt): {bad:?}"); +} + +#[test] +fn a_shimmer_under_a_hovering_pointer_and_late_frames_stays_in_step() { + let mut bad = Vec::new(); + for seed in 0..6u64 { + let s = Shimmer { since: -0.8, band: 140.0, ring: true, tail: true, zoom: 1.6, pad: 40.0, ..base() }; + let mut rt = shimmer_rt(s); + rt.frame(0.0); + let mut x = seed.wrapping_mul(0x9E37_79B9_7F4A_7C15) | 1; + let mut rnd = move || { x ^= x << 13; x ^= x >> 7; x ^= x << 17; (x % 1000) as f64 / 1000.0 }; + let (mut worst, mut glyph) = (0.0f32, 0.0f32); + for k in 0..900 { + let r = rnd(); + let (catch_up, dt) = if r < 0.05 { (0.15 + rnd() * 0.3, 1.0 / 120.0) } else if r < 0.15 { (1.0 / 60.0, 1.0 / 120.0) } else { (0.0, 1.0 / 120.0) }; + rt.state.now = rt.clock + catch_up + dt; + if rnd() < 0.2 { rt.invalidate(); } + if rnd() < 0.3 { rt.pointer_move(150.0 + rnd() as f32 * 120.0, 20.0 + rnd() as f32 * 20.0); } + if k == 300 { rt.state.on = false; rt.invalidate(); } + if k == 300 + (seed as usize % 3) * 4 + 1 { rt.state.on = true; rt.state.since = rt.state.now - 0.3; rt.invalidate(); } + rt.frame_split(catch_up, dt); + if let Some((a, b)) = loop_offsets(&rt) { if (a + b).abs() > worst.abs() { worst = a + b; } } + glyph = worst_of(&rt, glyph); + } + if worst.abs() > 0.01 || !(glyph.abs() < GLYPH_PX) { bad.push((seed, worst, glyph)); } + } + assert!(bad.is_empty(), "out of step (seed, loop sum pt, glyph px): {bad:?}"); +} + +#[derive(Clone, Copy, Debug)] +enum Ev { + /// No frame for this long, then one late frame, as `FrameClock` steps it. + Stall(f64), + /// Covered for this long: hidden wakes only, then uncovered (settles, as the window does). + Covered(f64), + /// Covered for this long, stopping at once and starting again halfway through. + RestartCovered(f64), + Stop, + Start, +} + +/// Steps `rt` like the window host for `secs` of 120 Hz frames, applying each due event and +/// recording the worst loop sum (pt) and, away from events, the worst glyph offset (px). +fn window(rt: &mut Runtime<Shimmer>, secs: f64, events: &mut Vec<(f64, Ev)>, worst: &mut (f32, f32)) { + let start = rt.clock; + let mut quiet_from = start + 0.6; + while rt.clock < start + secs { + let mut covered = false; + let gap = match events.first().filter(|e| rt.clock - start >= e.0).map(|e| e.1) { + None => 1.0 / 120.0, + Some(ev) => { + events.remove(0); + quiet_from = quiet_from.max(rt.clock + 1.5); + match ev { + Ev::Stall(g) => g, + Ev::Stop => { rt.state.on = false; 1.0 / 120.0 } + Ev::Start => { rt.state.on = true; rt.state.since = rt.clock; 1.0 / 120.0 } + Ev::Covered(g) | Ev::RestartCovered(g) => { + rt.set_live_visible(false); + let end = rt.clock + g; + let restart = matches!(ev, Ev::RestartCovered(_)); + if restart { rt.state.on = false; } + while rt.clock < end { + rt.clock += 0.05; + rt.state.now = rt.clock; + if restart && !rt.state.on && rt.clock >= end - g / 2.0 { rt.state.on = true; rt.state.since = rt.clock; } + rt.invalidate(); + rt.hidden_wake(); + } + rt.set_live_visible(true); + rt.settle_all(); + covered = true; + g + } + } + } + }; + let step = crate::frame::clock::split(gap, rt.animating); + if !covered { rt.clock += (gap - step.total()).max(0.0); } + rt.state.now = rt.clock + step.total(); + rt.invalidate(); + rt.frame_split(step.catch_up, step.dt); + // A copy mounted mid-pass waits at its start for the next pass, while the window runs. + let waiting = |key: &str| rt.tree.nodes.iter().find(|n| n.path.ends_with(key)).and_then(|n| rt.motion.loop_track(n.id)) + .is_some_and(|l| l.pending_start(rt.t).is_some()); + if waiting("/sheen") != waiting("/lit") { continue; } + if let Some((a, b)) = loop_offsets(rt) && (a + b).abs() > worst.0.abs() { worst.0 = a + b; } + if rt.clock >= quiet_from && rt.state.on { worst.1 = worst_of(rt, worst.1); } + } +} + +#[test] +fn a_shimmer_through_what_a_real_window_does_stays_in_step() { + let s = Shimmer { since: -0.8, band: 140.0, ring: true, tail: true, zoom: 1.6, pad: 40.0, ..base() }; + let mut cases: Vec<(String, Shimmer, Vec<(f64, Ev)>)> = Vec::new(); + for lit_at in [0.3, 1.6, 2.9] { + cases.push((format!("lit_at={lit_at}"), Shimmer { lit_at, ..s }, vec![])); + cases.push((format!("lit_at={lit_at} covered"), Shimmer { lit_at, ..s }, vec![(lit_at - 0.2, Ev::Covered(0.5))])); + } + for at in [0.5, 1.7, 2.0] { + for g in [0.2, 0.6, 3.0] { + cases.push((format!("stall at={at} g={g}"), s, vec![(at, Ev::Stall(g))])); + } + for g in [0.3, 2.0, 6.0] { + cases.push((format!("covered at={at} g={g}"), s, vec![(at, Ev::Covered(g))])); + cases.push((format!("restart covered at={at} g={g}"), s, vec![(at, Ev::RestartCovered(g))])); + } + for off in [0.02, 0.2] { + cases.push((format!("restart at={at} off={off} stall"), s, vec![(at, Ev::Stop), (at + off, Ev::Start), (at + off + 0.1, Ev::Stall(0.4))])); + } + } + let mut bad = Vec::new(); + for (tag, s, mut events) in cases { + let mut rt = shimmer_rt(s); + rt.frame(0.0); + let mut worst = (0.0f32, 0.0f32); + window(&mut rt, 7.0, &mut events, &mut worst); + if worst.0.abs() > 0.01 || !(worst.1.abs() < GLYPH_PX) { bad.push((tag, worst)); } + } + assert!(bad.is_empty(), "out of step (case, (loop sum pt, glyph px)): {bad:?}"); +} + +/// Drives `rt` like a window: a frame every 1/120 s while it animates, otherwise asleep until +/// its wake deadline. The app clock follows the host clock; the view commits only at `events` +/// (host time, change to the state). +fn host(rt: &mut Runtime<Shimmer>, until: f64, events: &mut Vec<(f64, fn(&mut Shimmer))>) -> f32 { + let mut worst = 0.0f32; + let mut dt: f64 = 1.0 / 120.0; + while rt.clock < until { + let next = events.first().map_or(f64::INFINITY, |e| e.0); + let dt_now = dt.min((next - rt.clock).max(0.0)); + rt.state.now = rt.clock + dt_now; + if events.first().is_some_and(|e| e.0 <= rt.clock + dt_now + 1e-9) { + let (_, f) = events.remove(0); + f(&mut rt.state); + rt.state.since = if rt.state.on && rt.state.since < 0.0 { rt.state.now } else { rt.state.since }; + rt.invalidate(); + } + let animating = rt.frame(dt_now); + worst = worst_of(rt, worst); + dt = if animating { 1.0 / 120.0 } else { rt.wake_deadline().map_or(0.25, |d| (d - rt.clock).max(1.0 / 120.0)) }; + } + worst +} + +#[test] +fn a_shimmer_on_a_sleeping_host_keeps_its_bright_copy_on_the_label() { + let mut bad = Vec::new(); + for zoom in [1.0f32, 1.6] { + for gap in [0.05f64, 0.4, 1.3] { + for stop_at in [0.7f64, 1.6, 2.05] { + let s = Shimmer { since: -0.8, ring: true, band: 140.0, tail: true, zoom, ..base() }; + let mut rt = shimmer_rt(s); + rt.frame(0.0); + let mut events: Vec<(f64, fn(&mut Shimmer))> = vec![ + (stop_at, |s| s.on = false), + (stop_at + gap, |s| { s.on = true; s.since = -1.0; }), + (stop_at + gap + 1.1, |s| s.zoom += 0.0), + ]; + let w = host(&mut rt, stop_at + gap + 3.0 * period(&s), &mut events); + if !(w.abs() < GLYPH_PX) { bad.push((zoom, gap, stop_at, w)); } + } + } + } + assert!(bad.is_empty(), "the bright copy drifts off the label on a sleeping host (zoom, gap, stopped at, px): {bad:?}"); +} diff --git a/app/vendor/rune/crates/rune/src/runtime/tests/springs.rs b/app/vendor/rune/crates/rune/src/runtime/tests/springs.rs new file mode 100644 index 0000000..3f9393f --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/tests/springs.rs @@ -0,0 +1,442 @@ +use super::*; + + +#[test] +fn dissolve_prepass_only_runs_for_trees_with_dissolve_nodes() { + fn view(enabled: &bool, _: &mut Cx<bool>) -> El { + let root = el().size(64.0, 32.0).child(el().size(32.0, 32.0).opacity(0.5).fill(Color::WHITE)); + if *enabled { root.dissolve() } else { root } + } + let mut rt = Runtime::new(false, view, (64.0, 32.0), Env::new(true, 1.0)); + for enabled in [false, true, false] { + rt.state = enabled; rt.invalidate(); rt.frame(0.0); + assert_eq!(rt.tree.has_dissolve, enabled); + assert_eq!(rt.paint.dissolve_scratch().is_empty(), !enabled); + if enabled { assert!(rt.paint.dissolve_scratch()[0]); } + } +} + +#[test] +fn a_child_too_faint_to_paint_does_not_isolate_its_dissolve_parent() { + fn view(opacity: &f32, _: &mut Cx<f32>) -> El { + el().size(64.0, 32.0).dissolve().child(el().size(32.0, 32.0).opacity(*opacity).fill(Color::WHITE)) + } + let mut rt = Runtime::new(0.0005, view, (64.0, 32.0), Env::new(true, 1.0)); + rt.frame(0.0); + assert!(!rt.paint.dissolve_scratch()[0]); + rt.state = 0.5; rt.invalidate(); + for _ in 0..60 { rt.frame(1.0 / 60.0); } + assert!(rt.paint.dissolve_scratch()[0]); +} + +#[test] +fn sequences_run_without_commits_then_sleep_and_settle() { + fn view(_: &(), _: &mut Cx<()>) -> El { + const BEATS: &[crate::Beat] = &[ + crate::Beat::new(0.0).opacity(0.0).scale(0.8), + crate::Beat::new(0.3).easing(crate::Easing::LINEAR), + crate::Beat::new(0.6).opacity(0.5).scale(1.1).easing(crate::Easing::LINEAR), + crate::Beat::new(0.9).easing(crate::Easing::LINEAR), + ]; + el().key("root").size(200.0, 100.0).child(el().key("beat").size(80.0, 40.0) + .sequence(crate::Sequence::new(BEATS).delay(0.2))) + } + let make = || Runtime::new((), view, (200.0, 100.0), Env { scale: 1.0, system_dark: true }); + let mut rt = make(); + assert!(!rt.frame(0.0)); + assert_eq!(rt.wake_deadline(), Some(0.2)); + let commits = rt.stats.commits; + assert!(rt.frame(0.35)); + let pose = |rt: &Runtime<()>| rt.elements().into_iter().find(|e| e.key.as_deref() == Some("beat")).unwrap(); + assert!((pose(&rt).opacity - 0.5).abs() < 1e-5); + assert!((pose(&rt).scale - 0.9).abs() < 1e-5); + assert_eq!(rt.stats.commits, commits); + rt.invalidate(); rt.frame(0.0); + assert!((pose(&rt).opacity - 0.5).abs() < 1e-5, "unrelated commits must not restart the sequence"); + assert!(!rt.frame(1.0)); + assert_eq!(rt.wake_deadline(), None); + assert_eq!(pose(&rt).opacity, 1.0); + assert_eq!(pose(&rt).scale, 1.0); + let mut settled = make(); settled.frame(0.0); settled.settle_all(); + assert!(!settled.frame(0.0)); + assert_eq!(pose(&settled).opacity, 1.0); + assert_eq!(settled.wake_deadline(), None); + let mut reduced = make(); reduced.set_system_reduced_motion(true); + assert!(!reduced.frame(0.0)); + assert_eq!(pose(&reduced).scale, 1.0); + assert_eq!(pose(&reduced).opacity, 1.0); + assert_eq!(pose(&reduced).loop_phase, Some(1.0)); + assert_eq!(reduced.wake_deadline(), None); +} + +#[test] +fn motion_curve_moves_layout_on_a_tween() { + fn view(h: &f32, _: &mut Cx<f32>) -> El { + col().size(200.0, 300.0).child(el().key("card").w(100.0).h(*h)) + } + let h = |rt: &Runtime<f32>| rt.elements().into_iter().find(|e| e.key.as_deref() == Some("card")).unwrap().rect[3]; + let run = |set: fn(&mut Tx)| { + let mut rt = Runtime::new(100.0_f32, view, (200.0, 300.0), Env { scale: 1.0, system_dark: true }); + rt.frame(0.0); + rt.update(|x, tx| { *x = 200.0; set(tx); }); + rt.frame(0.0); + let mut hs = vec![]; + for _ in 0..60 { rt.frame(1.0 / 120.0); hs.push(h(&rt)); } + hs + }; + let linear = run(|tx| tx.motion_curve(rune_motion::Curve::linear(0.4))); + // Halfway through a 0.4 s linear tween is halfway there, and it lands on time. + assert!((linear[23] - 150.0).abs() < 3.0, "{}", linear[23]); + assert!((linear[47] - 200.0).abs() < 0.01, "{}", linear[47]); + let spring = run(|tx| tx.motion(Spring::new(0.4, 0.0))); + assert!((spring[23] - linear[23]).abs() > 3.0, "a spring is not the tween"); + // A spring passed as a curve is that spring; a later `motion` replaces the curve. + assert_eq!(run(|tx| tx.motion_curve(Spring::new(0.4, 0.0))), spring); + assert_eq!(run(|tx| { tx.motion_curve(rune_motion::Curve::linear(0.4)); tx.motion(Spring::new(0.4, 0.0)) }), spring); +} + +#[test] +fn layout_motion_does_not_replace_explicit_transition_exit() { + fn view(s: &(bool, f32), _: &mut Cx<(bool, f32)>) -> El { + col().size(200.0, 100.0).children(s.0.then(|| el().key("pill").size(100.0, 40.0) + .motion(Spring::new(s.1, 0.0)) + .transition(Transition::scale(0.96).springs(rune_motion::SpringPair { + enter: Spring::new(0.3, 0.0), exit: Spring::new(0.8, 0.0), + })))) + } + let make = |duration| Runtime::new((true, duration), view, (200.0, 100.0), Env { scale: 1.0, system_dark: true }); + let (mut fast, mut slow) = (make(0.05), make(0.6)); + for rt in [&mut fast, &mut slow] { + rt.frame(0.0); + rt.state.0 = false; rt.invalidate(); rt.frame(0.0); + rt.frame(0.1); + } + let opacity = |rt: &Runtime<(bool, f32)>| rt.elements().into_iter() + .find(|e| e.key.as_deref() == Some("pill")).unwrap().opacity; + assert!(opacity(&fast) > 0.5, "the explicit slow exit must survive fast layout tuning"); + assert!((opacity(&fast) - opacity(&slow)).abs() < 1e-6); +} + +#[test] +fn a_node_leaves_with_the_transition_of_its_last_render() { + // (shown, way): the page slides out the way of the last render. + fn view(s: &(bool, f32), _: &mut Cx<(bool, f32)>) -> El { + col().size(200.0, 100.0).children(s.0.then(|| el().key("page").size(100.0, 40.0) + .transition(Transition::offset(40.0 * s.1, 0.0)))) + } + let x = |rt: &Runtime<(bool, f32)>| rt.elements().into_iter() + .find(|e| e.key.as_deref() == Some("page")).unwrap().rect[0]; + let make = |shown| Runtime::new((shown, -1.0), view, (200.0, 100.0), Env { scale: 1.0, system_dark: true }); + + // Entering from the left; a new render mid-entrance doesn't change the entrance. + let (mut kept, mut turned) = (make(false), make(false)); + for rt in [&mut kept, &mut turned] { + rt.frame(0.0); + rt.state.0 = true; rt.invalidate(); rt.frame(0.0); rt.frame(0.05); + } + turned.state.1 = 1.0; turned.invalidate(); + kept.frame(0.05); turned.frame(0.05); + assert!(x(&turned) < 0.0, "still entering from the left: {}", x(&turned)); + assert!((x(&kept) - x(&turned)).abs() < 1e-4, "the running entrance is unaffected"); + + // Removed after the render that turned it: it leaves to the right. + let mut rt = make(true); + rt.frame(0.0); rt.frame(2.0); + assert_eq!(x(&rt), 0.0); + rt.state.1 = 1.0; rt.invalidate(); rt.frame(0.0); + rt.state.0 = false; rt.invalidate(); rt.frame(0.0); rt.frame(0.1); + assert!(x(&rt) > 1.0, "leaves the way of its last render: {}", x(&rt)); +} + +#[test] +fn element_effects_include_ancestor_opacity_scale_and_exit_blur() { + fn view(show: &bool, _: &mut Cx<bool>) -> El { + col().size(200.0, 100.0).children(show.then(|| el().key("parent").size(100.0, 60.0) + .opacity(0.5).live_scale(&crate::live::Live::new(0.8)).transition(Transition::blur(4.0)) + .child(el().key("child").size(20.0, 20.0).opacity(0.5).live_scale(&crate::live::Live::new(0.5))))) + } + let mut rt = Runtime::new(true, view, (200.0, 100.0), Env { scale: 2.0, system_dark: true }); + rt.frame(0.0); + let child = rt.elements().into_iter().find(|e| e.key.as_deref() == Some("child")).unwrap(); + assert!((child.opacity - 0.25).abs() < 1e-6); + assert!((child.scale - 0.4).abs() < 1e-6); + assert_eq!(child.blur, 0.0); + rt.state = false; rt.invalidate(); rt.frame(0.0); rt.frame(0.05); + let elements = rt.elements(); + let parent = elements.iter().find(|e| e.key.as_deref() == Some("parent")).unwrap(); + let child = elements.iter().find(|e| e.key.as_deref() == Some("child")).unwrap(); + assert!(parent.blur > 0.0); + assert_eq!(child.blur, parent.blur); + assert!((child.opacity - parent.opacity * 0.5).abs() < 1e-6); +} + +#[test] +fn exiting_elements_are_flagged_and_gone_from_key_lookups() { + fn view(show: &bool, _: &mut Cx<bool>) -> El { + col().size(200.0, 100.0).children(show.then(|| el().key("card").size(100.0, 60.0) + .transition(Transition::blur(4.0)) + .child(el().key("label").size(20.0, 20.0)))) + } + let mut rt = Runtime::new(true, view, (200.0, 100.0), Env { scale: 1.0, system_dark: true }); + rt.frame(0.0); + assert!(rt.find("card").is_some() && rt.find("label").is_some()); + assert!(rt.elements().iter().all(|e| !e.exiting)); + rt.state = false; rt.invalidate(); rt.frame(0.0); rt.frame(0.05); + let elements = rt.elements(); + for key in ["card", "label"] { + let e = elements.iter().find(|e| e.key.as_deref() == Some(key)).expect("still drawn while it exits"); + assert!(e.exiting && e.inert, "{key} is exiting"); + assert_eq!(rt.find(key), None, "{key} is gone from lookups"); + assert!(rt.presented(key).is_some(), "presented still reads {key}"); + } +} + +#[test] +fn a_duplicate_matched_id_matches_the_last_one_and_warns() { + fn view(_: &(), _: &mut Cx<()>) -> El { + col().child(el().key("a").matched("tile").size(10.0, 10.0)) + .child(el().key("b").matched("tile").size(10.0, 10.0)) + } + let mut rt = Runtime::new((), view, (100.0, 100.0), Env::new(true, 1.0)); + rt.commit.enable_key_warnings(); + rt.frame(0.0); + let warnings = rt.commit.key_warnings().unwrap(); + assert!(warnings.len() == 1 && warnings[0].contains("duplicate matched id \"tile\""), "{warnings:?}"); + let b = rt.tree.nodes.iter().find(|n| n.key.as_deref() == Some("b")).unwrap().id; + assert_eq!(rt.motion.matched_ids(), [b]); +} + +#[test] +fn presence_exits_stay_drawn_and_revive_mid_flight() { + fn view(show: &bool, _cx: &mut Cx<bool>) -> El { + let mut root = col().key("root").size(200.0, 100.0); + if *show { + root = root.child( + el().key("badge") + .size(80.0, 30.0) + .fill(Color::WHITE) + .transition(Transition::blur_replace()), + ); + } + root + } + + let mut rt = Runtime::new(true, view, (200.0, 100.0), Env::new(true, 2.0)); + assert!(!rt.frame(0.0), "first mount never animates"); + assert_eq!(rt.elements().len(), 2); + + // Remove the badge: it stays in the tree while its blur-replace exit runs. + rt.state = false; + rt.commit.dirty = true; + assert!(rt.frame(1.0 / 60.0)); + let badge = rt.elements().into_iter().find(|e| e.key.as_deref() == Some("badge")).unwrap(); + assert!(badge.opacity > 0.0 && badge.opacity < 1.0); + + // Revive mid-exit: continues without a jump. + let before = rt.elements().into_iter().find(|e| e.key.as_deref() == Some("badge")).unwrap().opacity; + rt.state = true; + rt.commit.dirty = true; + rt.frame(1.0 / 60.0); + let after = rt.elements().into_iter().find(|e| e.key.as_deref() == Some("badge")).unwrap().opacity; + assert!((after - before).abs() < 0.15, "{before} -> {after}"); + + // Remove again and run until settled: unmounts only after opacity reaches 0. + rt.state = false; + rt.commit.dirty = true; + for _ in 0..120 { + rt.frame(1.0 / 60.0); + } + assert!(!rt.animating); + assert!(rt.elements().iter().all(|e| e.key.as_deref() != Some("badge"))); +} + +/// Target opacities of a dot outside every `time_scale` and one inside `outer > inner`, +/// plus an exiting badge under `inner`. +#[derive(Clone, Copy)] +struct Lab { outside: f32, inside: f32, badge: bool, outer: f32, inner: f32 } + +impl Lab { + fn at(outer: f32, inner: f32) -> Lab { Lab { outside: 1.0, inside: 1.0, badge: true, outer, inner } } + fn runtime(self) -> Runtime<Lab> { + fn view(s: &Lab, _: &mut Cx<Lab>) -> El { + let dot = |key: &str, o: f32| el().key(key).size(20.0, 20.0).fill(Color::WHITE).opacity(o); + let mut inner = col().key("inner").time_scale(s.inner).child(dot("inside", s.inside)); + if s.badge { inner = inner.child(el().key("badge").size(20.0, 20.0).fill(Color::WHITE).transition(Transition::opacity())); } + col().key("root").size(200.0, 200.0) + .child(dot("outside", s.outside)) + .child(col().key("outer").time_scale(s.outer).child(inner)) + } + let mut rt = Runtime::new(self, view, (200.0, 200.0), Env::new(true, 1.0)); + assert!(!rt.frame(0.0)); + rt + } +} + +const LAB_DT: f64 = 1.0 / 60.0; + +fn lab_set(rt: &mut Runtime<Lab>, f: impl FnOnce(&mut Lab)) { + f(&mut rt.state); + rt.commit.dirty = true; +} + +fn lab_steps(rt: &mut Runtime<Lab>, n: usize) { + for _ in 0..n { rt.frame(LAB_DT); } +} + +fn lab_opacity(rt: &Runtime<Lab>, key: &str) -> Option<f32> { + rt.elements().into_iter().find(|e| e.key.as_deref() == Some(key)).map(|e| e.opacity) +} + +#[test] +fn time_scale_zero_freezes_its_subtree_while_the_rest_moves() { + let mut rt = Lab::at(1.0, 0.0).runtime(); + lab_set(&mut rt, |s| { s.outside = 0.0; s.inside = 0.0; }); + lab_steps(&mut rt, 12); + let outside = lab_opacity(&rt, "outside").unwrap(); + assert!(outside < 0.9, "outside fades: {outside}"); + assert_eq!(lab_opacity(&rt, "inside"), Some(1.0), "inside holds exactly"); +} + +#[test] +fn half_time_scale_reaches_the_same_point_at_twice_the_time() { + let mut rt = Lab::at(1.0, 0.5).runtime(); + lab_set(&mut rt, |s| { s.outside = 0.0; s.inside = 0.0; }); + lab_steps(&mut rt, 10); + let reference = lab_opacity(&rt, "outside").unwrap(); + assert!(reference > 0.05 && reference < 0.95, "mid-flight: {reference}"); + lab_steps(&mut rt, 10); + let inside = lab_opacity(&rt, "inside").unwrap(); + assert!((inside - reference).abs() < 1e-4, "{inside} at 2t vs {reference} at t"); +} + +#[test] +fn nested_time_scales_multiply() { + let mut rt = Lab::at(0.5, 0.5).runtime(); + lab_set(&mut rt, |s| { s.outside = 0.0; s.inside = 0.0; }); + lab_steps(&mut rt, 5); + let reference = lab_opacity(&rt, "outside").unwrap(); + assert!(reference > 0.05 && reference < 0.95, "mid-flight: {reference}"); + lab_steps(&mut rt, 15); + let inside = lab_opacity(&rt, "inside").unwrap(); + assert!((inside - reference).abs() < 1e-4, "{inside} at 4t vs {reference} at t"); +} + +#[test] +fn a_frozen_subtree_with_pending_motion_requests_no_frames() { + let mut rt = Lab::at(1.0, 0.0).runtime(); + lab_set(&mut rt, |s| s.inside = 0.0); + for _ in 0..5 { + assert!(!rt.frame(LAB_DT), "a frozen fade asks for no frames"); + } + assert!(rt.scene.store().active_len() > 0, "the fade is still pending"); + assert_eq!(rt.wake_deadline(), None); + assert_eq!(lab_opacity(&rt, "inside"), Some(1.0)); + lab_set(&mut rt, |s| s.inner = 1.0); + assert!(rt.frame(LAB_DT), "resuming runs it"); + assert!(lab_opacity(&rt, "inside").unwrap() < 1.0); +} + +#[test] +fn resuming_a_frozen_subtree_continues_from_the_same_value() { + let mut rt = Lab::at(1.0, 1.0).runtime(); + lab_set(&mut rt, |s| { s.outside = 0.0; s.inside = 0.0; }); + lab_steps(&mut rt, 5); + let held = lab_opacity(&rt, "inside").unwrap(); + assert!(held < 1.0); + lab_set(&mut rt, |s| s.inner = 0.0); + lab_steps(&mut rt, 5); + // The dot outside is ten frames in; the frozen one is still five frames in. + let reference = lab_opacity(&rt, "outside").unwrap(); + lab_steps(&mut rt, 5); + assert_eq!(lab_opacity(&rt, "inside"), Some(held), "no drift while frozen"); + lab_set(&mut rt, |s| s.inner = 1.0); + rt.frame(0.0); + assert_eq!(lab_opacity(&rt, "inside"), Some(held), "resumes from the held value"); + lab_steps(&mut rt, 5); + let inside = lab_opacity(&rt, "inside").unwrap(); + assert!((inside - reference).abs() < 1e-4, "continues on the same curve: {inside} vs {reference}"); +} + +#[test] +fn an_exit_in_a_frozen_subtree_finishes_after_resuming() { + let mut rt = Lab::at(1.0, 0.0).runtime(); + lab_set(&mut rt, |s| s.badge = false); + lab_steps(&mut rt, 120); + assert!(!rt.animating); + let badge = rt.elements().into_iter().find(|e| e.key.as_deref() == Some("badge")).expect("still exiting"); + assert!(badge.exiting && badge.opacity == 1.0, "held at the start of its exit: {}", badge.opacity); + lab_set(&mut rt, |s| s.inner = 1.0); + lab_steps(&mut rt, 3); + assert!(lab_opacity(&rt, "badge").is_some_and(|o| o < 1.0), "the exit runs"); + lab_steps(&mut rt, 120); + assert!(!rt.animating); + assert_eq!(lab_opacity(&rt, "badge"), None, "and is removed"); +} + +#[test] +fn a_node_unmounted_at_once_in_a_scaled_subtree_drops_its_clock() { + let mut rt = Lab::at(1.0, 0.5).runtime(); + let badge = rt.tree.nodes.iter().find(|n| n.key.as_deref() == Some("badge")).unwrap().id; + assert_eq!(rt.scene.store().node_time_scale(badge), 0.5); + lab_set(&mut rt, |s| s.badge = false); + rt.settle_all(); + rt.frame(LAB_DT); + assert_eq!(lab_opacity(&rt, "badge"), None); + assert_eq!(rt.scene.store().node_time_scale(badge), 1.0, "its clock went with it"); +} + +#[test] +fn an_exiting_element_drops_its_own_time_scale() { + fn view(show: &bool, _: &mut Cx<bool>) -> El { + let mut root = col().key("root").size(200.0, 100.0); + if *show { + root = root.child(el().key("card").size(80.0, 30.0).fill(Color::WHITE) + .time_scale(0.0).transition(Transition::opacity())); + } + root + } + let mut rt = Runtime::new(true, view, (200.0, 100.0), Env::new(true, 1.0)); + assert!(!rt.frame(0.0)); + rt.state = false; + rt.commit.dirty = true; + for _ in 0..3 { rt.frame(LAB_DT); } + let card = rt.elements().into_iter().find(|e| e.key.as_deref() == Some("card")).expect("exiting"); + assert!(card.exiting && card.opacity < 1.0, "its exit runs: {}", card.opacity); + for _ in 0..120 { rt.frame(LAB_DT); } + assert!(rt.elements().iter().all(|e| e.key.as_deref() != Some("card")), "and it leaves"); +} + +#[test] +fn removing_what_draws_nothing_skips_its_exit() { + // (shown, glow opacity, parent hidden) + fn view(s: &(bool, f32, bool), _: &mut Cx<(bool, f32, bool)>) -> El { + col().key("root").size(200.0, 200.0) + .child(col().key("group").size(100.0, 100.0).opacity(if s.2 { 0.0 } else { 1.0 }).opacity_motion(rune_motion::Anim::INSTANT) + .children(s.0.then(|| el().key("dot").size(10.0, 10.0).fill(Color::WHITE).transition(Transition::opacity())))) + .children(s.0.then(|| el().key("glow").size(50.0, 50.0).fill(Color::WHITE).opacity(s.1).transition(Transition::opacity()))) + } + let exiting = |rt: &Runtime<(bool, f32, bool)>, k: &str| rt.elements().into_iter().any(|e| e.key.as_deref() == Some(k)); + let mut rt = Runtime::new((true, 1.0, false), view, (200.0, 200.0), Env::new(true, 1.0)); + rt.frame(0.0); + for _ in 0..60 { rt.frame(1.0 / 60.0); } + // Visible: both fade out. + rt.update(|s, _| s.0 = false); + rt.frame(1.0 / 60.0); + assert!(exiting(&rt, "dot") && exiting(&rt, "glow"), "a visible element fades out"); + for _ in 0..60 { rt.frame(1.0 / 60.0); } + // Faded out already, or under a hidden parent: gone in the frame. + rt.update(|s, _| *s = (true, 0.0, true)); + for _ in 0..60 { rt.frame(1.0 / 60.0); } + rt.update(|s, _| s.0 = false); + rt.frame(1.0 / 60.0); + assert!(!exiting(&rt, "glow"), "the glow at opacity 0 has no exit"); + assert!(!exiting(&rt, "dot"), "nor the dot under a hidden parent"); + assert!(!rt.animating); + // The parent hides at once in the same commit: the dot's exit stops when it draws nothing. + rt.update(|s, _| *s = (true, 1.0, false)); + for _ in 0..60 { rt.frame(1.0 / 60.0); } + rt.update(|s, _| *s = (false, 1.0, true)); + rt.frame(1.0 / 60.0); + rt.frame(1.0 / 60.0); + assert!(!exiting(&rt, "dot"), "the dot under a parent that hid at once is gone"); +} diff --git a/app/vendor/rune/crates/rune/src/runtime/tests/stream_overflow.rs b/app/vendor/rune/crates/rune/src/runtime/tests/stream_overflow.rs new file mode 100644 index 0000000..573f4c9 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/tests/stream_overflow.rs @@ -0,0 +1,31 @@ +use super::*; +use crate::el::GrowthSpec; +use crate::growth::{StreamEdge, edge}; + +/// A stack whose streaming row grows from 40 to 400 pt and whose fold shuts from 600 to 40 pt, +/// under `edge`. +fn masks(edge: StreamEdge) -> (Vec<f32>, Vec<f32>) { + fn view(s: &(bool, StreamEdge), _: &mut Cx<(bool, StreamEdge)>) -> El { + let reply = el().key("reply").h(if s.0 { 400.0 } else { 40.0 }).w_full().streaming(true); + let fold = el().key("fold").h(if s.0 { 40.0 } else { 600.0 }).w_full().fold_glide(rune_motion::Spring::new(0.18, 0.0)).fold_feather(16.0); + col().key("root").child(col().key("stack").growth(GrowthSpec { edge: s.1, ..GrowthSpec::default() }).children([fold, reply])) + } + let mut rt = Runtime::new((false, edge), view, (400.0, 1400.0), Env::new(true, 2.0)); + rt.frame(0.0); + rt.update(|s, _| s.0 = true); + let at = |rt: &Runtime<(bool, StreamEdge)>, k: &str| rt.tree.nodes.iter().position(|n| n.named(k)).unwrap(); + (0..60).map(|_| { + rt.frame(1.0 / 120.0); + (rt.paint.row_mask[at(&rt, "reply")], rt.paint.row_mask[at(&rt, "fold")]) + }).unzip() +} + +#[test] +fn an_overflowing_edge_leaves_only_streaming_rows_unclipped() { + let (reply, fold) = masks(edge::FEATHER); + assert!(reply.iter().any(|&m| m >= 0.0), "the feather clips a growing reply: {reply:?}"); + let (reply, fold_over) = masks(StreamEdge { overflow: true, ..edge::FEATHER }); + assert!(reply.iter().all(|&m| m < 0.0), "overflowing, the reply draws past its height: {reply:?}"); + assert_eq!(fold, fold_over, "a shutting fold clips as before"); + assert!(fold_over.iter().any(|&m| m >= 0.0), "and does clip: {fold_over:?}"); +} diff --git a/app/vendor/rune/crates/rune/src/runtime/tests/stream_pace.rs b/app/vendor/rune/crates/rune/src/runtime/tests/stream_pace.rs new file mode 100644 index 0000000..bc807df --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/tests/stream_pace.rs @@ -0,0 +1,98 @@ +//! A reply streaming into a pinned timeline at any pace: the climb is steady, not one kick per +//! line or per word. +use super::*; +use crate::el::{GrowthSpec, ScrollSpec}; + +const WORDS: &[&str] = &[ + "the", "follower", "keeps", "pace", "with", "whatever", "arrives,", "so", "a", "slow", "reply", + "creeps", "steadily", "and", "a", "fast", "one", "keeps", "up", "without", "kicking", "for", + "each", "line;", "words", "fade", "in", "under", "the", "edge", "as", "they", "come,", "and", + "nothing", "stops", "dead", "until", "the", "stream", "pauses.", +]; + +#[derive(Default)] +struct Chat { + text: String, + streaming: bool, +} + +fn view(s: &Chat, _: &mut Cx<Chat>) -> El { + let mut stack = col().key("stack").w_full().growth(GrowthSpec::default()); + for i in 0..12 { + stack = stack.child(el().key(format!("r{i}")).w_full().h(60.0)); + } + stack = stack.child(col().key("reply").w_full().streaming(s.streaming) + .child(crate::el::text(s.text.clone()).wrap().w_full().reveal(0.18))); + col().w_full().h_full().child(col().key("scroll").w_full().grow(1.0).shrink().scroll(ScrollSpec { stick_bottom: true }).child(stack)) +} + +/// When each word arrives, in seconds. +fn pace(name: &str) -> Vec<f64> { + let n = 160; + match name { + "slow" | "slow, wide" => (0..n).map(|i| i as f64 * 0.3).collect(), + "medium" => (0..n).map(|i| i as f64 * 0.05).collect(), + "fast" => (0..n).map(|i| (i / 6) as f64 / 60.0).collect(), + // Bursts of 4–12 words a few ms apart, then pauses of 0.1–0.9 s, as real models stream. + _ => { + let (mut t, mut out, mut seed) = (0.0, Vec::new(), 7u32); + let mut rand = || { seed = seed.wrapping_mul(1_103_515_245).wrapping_add(12_345); (seed >> 16) as f64 / 65_536.0 }; + while out.len() < n { + for _ in 0..4 + (rand() * 9.0) as usize { out.push(t); t += 0.012; } + t += 0.1 + rand() * 0.8; + } + out.truncate(n); + out + } + } +} + +/// The first row's top each frame at 120 Hz while words arrive on `at`, the stream ending with +/// the last, then 1.5 s after, and how far the reply's drawn height trails its text. +fn climb(at: &[f64], width: f32) -> (Vec<f32>, Vec<f32>) { + let mut rt = Runtime::new(Chat { text: String::new(), streaming: true }, view, (width, 400.0), Env::new(true, 2.0)); + rt.frame(0.0); + for _ in 0..60 { rt.frame(1.0 / 120.0); } + let top = |rt: &Runtime<Chat>| rt.elements().into_iter().find(|e| e.key.as_deref() == Some("r0")).unwrap().rect[1]; + let reply = rt.tree.nodes.iter().find(|n| n.key.as_deref() == Some("reply")).unwrap().id; + let (mut ys, mut lags, mut next, mut t) = (Vec::new(), Vec::new(), 0, 0.0); + let end = at.last().copied().unwrap_or(0.0) + 1.5; + while t < end { + t += 1.0 / 120.0; + while next < at.len() && at[next] <= t { + if !rt.state.text.is_empty() { rt.state.text.push(' '); } + rt.state.text.push_str(WORDS[next % WORDS.len()]); + next += 1; + rt.state.streaming = next < at.len(); + rt.invalidate(); + } + rt.frame(1.0 / 120.0); + ys.push(top(&rt)); + lags.push(rt.motion.grows.get(&reply).map_or(0.0, |g| g.target - g.h)); + } + (ys, lags) +} + +/// Once a reply overflows, a pinned timeline climbs without resting until its last word lands, +/// however fast or unevenly the words come: no stop and kick per line or per word. A steady +/// stream trails its text by under a line, and the last of it lands within half a second. +#[test] +fn a_stream_climbs_steadily_at_any_pace() { + // A wide window's last line fills, and its reveal rises, a fraction of a point a word. + for name in ["slow", "slow, wide", "medium", "fast", "bursty"] { + let at = pace(name); + let (ys, lags) = climb(&at, if name.ends_with("wide") { 1000.0 } else { 420.0 }); + let steps: Vec<f32> = ys.windows(2).map(|w| w[0] - w[1]).collect(); + // (Drawn rects move in 1/128 pt steps, so a climb has to be underway to show each frame.) + let first = steps.iter().position(|&d| d > 0.02).expect("the reply overflows"); + let last = (at[at.len() - 1] * 120.0) as usize; + let rests: Vec<usize> = (first..last).filter(|&k| steps[k] < 0.005).collect(); + assert!(rests.is_empty(), "{name}: rests {} times, first at frame {:?}", rests.len(), rests.first()); + if name != "fast" { + let most = lags.iter().copied().fold(0.0, f32::max); + assert!(most < 20.0, "{name}: trails its text by {most} pt"); + } + let landed = last + 60; + assert!(lags[landed..].iter().all(|&l| l < 0.05), "{name}: still {} pt short 0.5 s after the last word", lags[landed]); + } +} diff --git a/app/vendor/rune/crates/rune/src/runtime/tests/text_glide.rs b/app/vendor/rune/crates/rune/src/runtime/tests/text_glide.rs new file mode 100644 index 0000000..c765b96 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/tests/text_glide.rs @@ -0,0 +1,120 @@ +use super::*; +use crate::render::{KIND_GLYPH, KIND_RECT}; +use crate::{Color, TextStyle}; +use rune_motion::Spring; + +/// Where the app puts the card, and the spring (seconds) it glides there on. +#[derive(Clone, Copy)] +struct Card { + at: [f32; 2], + spring: f32, +} + +/// A card with a fill, a border and a line of text, which the app moves by `offset` every frame +/// and which glides there on a spring. +fn card(s: &Card, _: &mut Cx<Card>) -> El { + let label = crate::text("Quiet harbor glides").font(TextStyle::new(13.0, 500.0)).color(Color::WHITE); + el().size(240.0, 120.0).child( + col().absolute(20.0, 30.0).padding(12.0).radius(10.0).fill(Color::WHITE.mix(Color::BLACK, 0.8)) + .border(1.0, Color::WHITE.mix(Color::BLACK, 0.6)) + .offset(s.at[0], s.at[1]).offset_motion(Spring::new(s.spring, 0.0)).child(label), + ) +} + +/// The card's drawn top-left (device px). +fn card_at(rt: &Runtime<Card>) -> [f32; 2] { + let r = rt.instances.iter().find(|i| i.params[1] == KIND_RECT && i.fill[3] > 0.0).expect("the card's fill").rect; + [r[0], r[1]] +} + +/// The coverage-weighted centre of the text's ink (device px), read from the atlas masks its +/// glyph quads draw. +fn ink_at(rt: &Runtime<Card>) -> [f32; 2] { + let atlas = &rt.text.atlas; + let size = crate::text::ATLAS_SIZE as usize; + let (mut sum, mut at) = (0.0f64, [0.0f64; 2]); + for i in rt.instances.iter().filter(|i| i.params[1] == KIND_GLYPH) { + let data = atlas.page_data(i.params[2] as usize).expect("an atlas page"); + let (u, v) = (i.uv[0] as usize, i.uv[1] as usize); + for y in 0..i.rect[3] as usize { + for x in 0..i.rect[2] as usize { + let c = data[(v + y) * size + u + x] as f64; + sum += c; + at[0] += c * (i.rect[0] as f64 + x as f64 + 0.5); + at[1] += c * (i.rect[1] as f64 + y as f64 + 0.5); + } + } + } + assert!(sum > 0.0, "draws glyphs"); + [(at[0] / sum) as f32, (at[1] / sum) as f32] +} + +/// The repro: the app bobs the card by `-2.5 * (0.5 - 0.5 cos(2π t / 5))` on `axis` for five +/// seconds at `hz`, on a `spring`. Returns the spread (device px) of where the ink sits against +/// the card's drawn edge, how far the card moved, and how many alpha masks the atlas gained. +fn glide(axis: usize, spring: f32, hz: u32) -> (f32, f32, usize) { + let mut rt = Runtime::new(Card { at: [0.0; 2], spring }, card, (240.0, 120.0), Env::new(true, 2.0)); + rt.frame(0.0); + let masks = rt.text.atlas.glyph_entries(); + let (mut lo, mut hi) = (f32::MAX, f32::MIN); + let (mut top_lo, mut top_hi) = (f32::MAX, f32::MIN); + for k in 1..=5 * hz { + let t = k as f32 / hz as f32; + let d = -2.5 * (0.5 - 0.5 * (std::f32::consts::TAU * t / 5.0).cos()); + rt.update(|s, _| s.at[axis] = d); + rt.frame(1.0 / hz as f64); + let off = ink_at(&rt)[axis] - card_at(&rt)[axis]; + (lo, hi) = (lo.min(off), hi.max(off)); + let top = card_at(&rt)[axis]; + (top_lo, top_hi) = (top_lo.min(top), top_hi.max(top)); + } + (hi - lo, top_hi - top_lo, rt.text.atlas.glyph_entries() - masks) +} + +/// Text glides with its box: the ink keeps its place against the card's drawn edge to within a +/// glide phase while pixel snapping glides the card by fractions of a pixel, on both axes. +#[test] +fn text_glides_with_its_box() { + let mut ticks = Vec::new(); + for (spring, hz) in [(0.08, 120), (0.08, 60), (0.3, 60), (1.0, 120)] { + for axis in [1, 0] { + let (spread, travel, masks) = glide(axis, spring, hz); + eprintln!("spring {spring} s at {hz} Hz, axis {axis}: the ink spreads {spread:.3} px against the card over {travel:.2} px of travel; {masks} new masks"); + assert!(travel > 4.5, "the card moves five device px: {travel}"); + if spread > 0.3 { + ticks.push((spring, hz, axis, spread)); + } + } + } + assert!(ticks.is_empty(), "the ink ticks against its card (spring, Hz, axis, px): {ticks:?}"); +} + +/// The glide phases are few: moving text adds at most a few masks per glyph to the atlas. +#[test] +fn a_glide_keeps_the_atlas_bounded() { + let mut rt = Runtime::new(Card { at: [0.0; 2], spring: 0.3 }, card, (240.0, 120.0), Env::new(true, 2.0)); + rt.frame(0.0); + let glyphs = rt.instances.iter().filter(|i| i.params[1] == KIND_GLYPH).count(); + let (_, _, masks) = glide(1, 0.3, 60); + assert!(masks <= glyphs * crate::text::GLIDE_PHASES as usize, "{masks} new masks for {glyphs} glyphs"); +} + +/// Once the card comes to rest, the frame is byte for byte what a card that never moved draws +/// there. +#[test] +fn a_glide_lands_on_the_resting_frame() { + let mut rt = Runtime::new(Card { at: [0.0; 2], spring: 0.3 }, card, (240.0, 120.0), Env::new(true, 2.0)); + rt.frame(0.0); + for k in 1..=40 { + rt.update(|s, _| s.at = [0.7 * k as f32 / 40.0, -1.3 * k as f32 / 40.0]); + rt.frame(1.0 / 60.0); + } + for _ in 0..120 { + rt.frame(1.0 / 60.0); + } + let mut still = Runtime::new(Card { at: [0.7, -1.3], spring: 0.3 }, card, (240.0, 120.0), Env::new(true, 2.0)); + still.frame(0.0); + let bytes = |rt: &Runtime<Card>| bytemuck::cast_slice::<_, u8>(&rt.instances).to_vec(); + assert!(bytes(&rt) == bytes(&still), "the landed card draws as a still one"); +} + diff --git a/app/vendor/rune/crates/rune/src/runtime/tests/text_keys.rs b/app/vendor/rune/crates/rune/src/runtime/tests/text_keys.rs new file mode 100644 index 0000000..a4f6c58 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/tests/text_keys.rs @@ -0,0 +1,45 @@ +use super::*; + +fn keyed_view(_: &(), _: &mut Cx<()>) -> El { + col().w_full().children([ + crate::text("Plain words that wrap at the column width").wrap().key("plain"), + crate::text("cased").text_case(crate::TextCase::Uppercase).key("cased"), + crate::text("a-long-token-without-spaces").wrap().wrap_anywhere().key("anywhere"), + crate::text("hunter2").secure().key("secret"), + ]) +} + +fn spec<'a>(rt: &'a Runtime<()>, key: &str) -> &'a TextSpec { + rt.tree.nodes.iter().find(|n| n.key.as_deref() == Some(key)).and_then(|n| n.text.as_ref()).unwrap() +} + +/// Flatten hashes each text once; measuring and laying it out at every width reuse that key, +/// and it names the same cached layout the unkeyed path does. +#[test] +fn texts_carry_one_shape_key_that_names_their_cached_layout() { + let mut rt = Runtime::new((), keyed_view, (240.0, 400.0), Env::new(true, 2.0)); + rt.frame(0.0); + for key in ["plain", "cased", "anywhere"] { + let s = spec(&rt, key).clone(); + let (bits, shape) = s.shape.unwrap_or_else(|| panic!("{key} has no shape key")); + assert_eq!(bits, 2f32.to_bits()); + assert_eq!(shape, crate::text::shape_key(&s.content, &s.spans, s.style, 2.0, s.wrap_anywhere, &s.cold.pills)); + assert_eq!(s.shape_key(1.0), None, "a key at another scale isn't reused"); + let keyed = rt.text.layout_for_spec(&s.as_text_input(2.0, false), 2.0, Some(300.0), parley::Alignment::Start); + let unkeyed = rt.text.layout_blocks_inner(&s.content, &s.spans, &s.cold.blocks, &s.cold.pills, s.style, 2.0, Some(300.0), parley::Alignment::Start, s.wrap_anywhere, true); + assert!(Rc::ptr_eq(&keyed, &unkeyed), "{key}"); + } + assert_eq!(spec(&rt, "cased").content, "CASED"); + assert_eq!(spec(&rt, "secret").shape, None, "secure text keeps no content-derived key"); +} + +#[test] +fn replacing_a_texts_content_drops_its_key() { + let mut rt = Runtime::new((), keyed_view, (240.0, 400.0), Env::new(true, 2.0)); + rt.frame(0.0); + let mut s = spec(&rt, "plain").clone(); + s.replace_content("Other words".into()); + assert_eq!(s.shape_key(2.0), None); + let l = rt.text.layout_for_spec(&s.as_text_input(2.0, false), 2.0, None, parley::Alignment::Start); + assert!(Rc::ptr_eq(&l, &rt.text.layout_rich("Other words", &[], s.style, 2.0, None))); +} diff --git a/app/vendor/rune/crates/rune/src/runtime/tests/text_quads.rs b/app/vendor/rune/crates/rune/src/runtime/tests/text_quads.rs new file mode 100644 index 0000000..a74af5b --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/tests/text_quads.rs @@ -0,0 +1,123 @@ +use super::*; +use parley::Layout; +use crate::text::{Ink, TextSystem}; + +fn label(s: &u32, _: &mut Cx<u32>) -> El { + col().w_full().child(crate::el::text("a label that stays put").key("label")).child(crate::el::text(format!("token {s}")).key("body")) +} + +/// `a` and `b` draw the same placements, whatever atlas pages their masks landed on. +fn draws_alike<S>(a: &Runtime<S>, b: &Runtime<S>) -> bool { + a.instances.len() == b.instances.len() + && a.instances.iter().zip(&b.instances).all(|(x, y)| { + x.rect == y.rect && x.radii == y.radii && x.fill == y.fill && x.border == y.border + && x.params == y.params && x.clip == y.clip && x.fade == y.fade + }) +} + +fn instance_bytes<S>(rt: &Runtime<S>) -> Vec<u8> { + bytemuck::cast_slice(&rt.instances).to_vec() +} + +fn layout_of<'a, S>(rt: &'a Runtime<S>, key: &str) -> &'a Rc<Layout<Ink>> { + rt.tree.nodes.iter().find(|n| n.key.as_deref() == Some(key)).and_then(|n| n.text_layout.as_ref()?.single()).unwrap() +} + +/// A commit rebuilds the view but leaves a still text's layout alone: its quads are copied, as +/// they are on a frame that commits nothing. +#[test] +fn a_still_text_across_a_commit_copies_its_quads() { + let mut rt = Runtime::new(0u32, label, (400.0, 200.0), Env::new(true, 2.0)); + rt.frame(0.0); + rt.frame(1.0 / 120.0); + let copies = rt.paint.quads_copied(); + rt.update(|s, _| *s += 1); + rt.frame(2.0 / 120.0); + assert!(rt.paint.quads_copied() > copies, "the label copied its quads across a commit"); +} + +fn paragraph(_: &bool, _: &mut Cx<bool>) -> El { + col().w_full().child(crate::el::text("Paragraph text long enough to wrap over several lines as the window narrows.").w_full().wrap().key("para")) +} + +/// A text re-broken in place keeps its address but not its identity: the next frame draws its +/// new lines instead of copying the quads of its old ones. +#[test] +fn a_rebroken_layout_draws_its_own_quads() { + let mut rt = Runtime::new(true, paragraph, (700.0, 900.0), Env::new(true, 2.0)); + rt.frame(0.0); + rt.frame(1.0 / 120.0); + let (before, copies, kept) = (instance_bytes(&rt), rt.paint.quads_copied(), Rc::as_ptr(layout_of(&rt, "para"))); + rt.set_viewport((300.0, 900.0), 2.0); + rt.frame(2.0 / 120.0); + assert_eq!(Rc::as_ptr(layout_of(&rt, "para")), kept, "re-broken in place"); + assert_eq!(rt.paint.quads_copied(), copies, "a re-broken layout copies nothing"); + assert!(instance_bytes(&rt) != before, "wrapped at a new width, the text draws new quads"); +} + +fn note(s: &Vec<&'static str>, _: &mut Cx<Vec<&'static str>>) -> El { + col().w_full().child(crate::el::text(s[0]).key("note")) +} + +/// A layout replaced by another text's is a new layout with a new id: the frame after the swap +/// never copies the old text's quads, and draws what a fresh window does. +#[test] +fn a_replaced_layout_copies_nothing() { + let mut rt = Runtime::new(vec!["Show"], note, (400.0, 200.0), Env::new(true, 2.0)); + rt.frame(0.0); + rt.frame(1.0 / 120.0); + let copies = rt.paint.quads_copied(); + rt.update(|s, _| s[0] = "Hide"); + rt.frame(2.0 / 120.0); + assert_eq!(rt.paint.quads_copied(), copies, "a replaced layout copies nothing"); + + let mut fresh = Runtime::new(vec!["Hide"], note, (400.0, 200.0), Env::new(true, 2.0)); + fresh.frame(0.0); + fresh.frame(1.0 / 120.0); + assert!(draws_alike(&rt, &fresh), "the swap draws the new text as a fresh window does"); +} + +/// An address handed to another layout is stamped anew: the quads drawn at that address before +/// are not copied, even though the address still holds a layout. +#[test] +fn a_restamped_address_copies_nothing() { + let mut rt = Runtime::new(vec!["Show"], note, (400.0, 200.0), Env::new(true, 2.0)); + rt.frame(0.0); + rt.frame(1.0 / 120.0); + let copies = rt.paint.quads_copied(); + let layout = layout_of(&rt, "note").clone(); + rt.text.restamp_for_test(&layout); + rt.frame(2.0 / 120.0); + assert_eq!(rt.paint.quads_copied(), copies, "a restamped address copies nothing"); + assert!(!rt.instances.is_empty(), "the text still draws"); +} + +/// A new text system's ids never match the quads the one it replaced drew. +#[test] +fn a_replaced_text_system_copies_nothing() { + let mut rt = Runtime::new(vec!["Show"], note, (400.0, 200.0), Env::new(true, 2.0)); + rt.frame(0.0); + rt.frame(1.0 / 120.0); + let copies = rt.paint.quads_copied(); + rt.text = TextSystem::default(); + rt.update(|s, _| s[0] = "Different words"); + rt.frame(2.0 / 120.0); + assert_eq!(rt.paint.quads_copied(), copies, "the new text system's ids never match the old one's"); +} + +/// A layout whose stamp the id table dropped misses every paint until it is built again: a +/// lookup never stamps it back, so the cache can't refill itself frame after frame. +#[test] +fn a_layout_whose_stamp_went_copies_nothing() { + let mut rt = Runtime::new(vec!["Show"], note, (400.0, 200.0), Env::new(true, 2.0)); + rt.frame(0.0); + rt.frame(1.0 / 120.0); + let copies = rt.paint.quads_copied(); + let layout = layout_of(&rt, "note").clone(); + rt.text.forget_stamp_for_test(&layout); + rt.frame(2.0 / 120.0); + assert_eq!(rt.paint.quads_copied(), copies, "a dropped stamp doesn't copy"); + rt.frame(3.0 / 120.0); + assert_eq!(rt.paint.quads_copied(), copies, "a lookup never stamps the layout back"); + assert!(!rt.instances.is_empty(), "the text still draws"); +} diff --git a/app/vendor/rune/crates/rune/src/runtime/tests/text_rebreak.rs b/app/vendor/rune/crates/rune/src/runtime/tests/text_rebreak.rs new file mode 100644 index 0000000..fddf9d7 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/tests/text_rebreak.rs @@ -0,0 +1,124 @@ +use super::*; +use parley::Layout; +use crate::text::Ink; + +fn resize_view(s: &bool, _: &mut Cx<bool>) -> El { + let para = "Paragraph text long enough to wrap over several lines as the window narrows."; + col().w_full().children((0..3).filter(|&i| *s || i != 2).map(|i| crate::el::text(format!("{i}. {para}")).w_full().wrap().key(format!("t{i}")))) +} + +fn layout_of<'a>(rt: &'a Runtime<bool>, key: &str) -> &'a Rc<Layout<Ink>> { + rt.tree.nodes.iter().find(|n| n.key.as_deref() == Some(key)).and_then(|n| n.text_layout.as_ref()?.single()).unwrap() +} + +/// A commit lets go of the last commit's text layouts before measuring, so on a resize each +/// wrapped text re-breaks its own layout in place; a text that leaves keeps its layout to draw +/// its exit. +#[test] +fn resizing_rebreaks_kept_texts_in_place_and_leaving_ones_keep_their_layout() { + let mut rt = Runtime::new(true, resize_view, (700.0, 900.0), Env::new(true, 2.0)); + rt.frame(0.0); + rt.set_viewport((600.0, 900.0), 2.0); + rt.frame(1.0 / 120.0); + let kept = Rc::as_ptr(layout_of(&rt, "t0")); + rt.set_viewport((300.0, 900.0), 2.0); + rt.frame(2.0 / 120.0); + assert_eq!(Rc::as_ptr(layout_of(&rt, "t0")), kept, "re-broken in place"); + assert!(layout_of(&rt, "t0").len() > 1); + let leaving = layout_of(&rt, "t2").clone(); + rt.update(|s, _| *s = false); + rt.frame(3.0 / 120.0); + assert!(rt.is_exiting(rt.tree.nodes.iter().find(|n| n.key.as_deref() == Some("t2")).unwrap().id)); + assert!(Rc::ptr_eq(layout_of(&rt, "t2"), &leaving), "the leaving text draws its exit from its own layout"); +} + +/// Measuring the content's height without committing leaves the drawn nodes' layouts alone. +#[test] +fn measuring_content_height_keeps_the_drawn_layouts() { + let mut rt = Runtime::new(true, resize_view, (700.0, 900.0), Env::new(true, 2.0)); + rt.frame(0.0); + let l = layout_of(&rt, "t0").clone(); + rt.host.fit_height = true; + rt.content_height(); + assert!(Rc::ptr_eq(layout_of(&rt, "t0"), &l)); +} + +fn typed(s: &String, _: &mut Cx<String>) -> El { + col().w_full().child(crate::el::text(s.clone()).w_full().wrap().key("para")).child(crate::el::text("label").key("label")) +} + +/// Typing into a paragraph keeps no stale copy of each edit's layout: the replaced text's +/// layouts go when the commit that replaced it ends. +#[test] +fn typing_keeps_no_layout_of_each_edit() { + let para = "Paragraph text long enough to wrap over several lines as the window narrows. ".repeat(8); + let mut rt = Runtime::new(para.clone(), typed, (700.0, 900.0), Env::new(true, 2.0)); + rt.frame(0.0); + let cached = rt.text.cached_layout_count(); + for i in 0..200 { + rt.update(|s, _| s.push(char::from(b'a' + (i % 26) as u8))); + rt.frame((i + 1) as f64 / 120.0); + } + assert!(rt.text.cached_layout_count() <= cached + 2, "{} layouts cached, {cached} at first", rt.text.cached_layout_count()); +} + +fn field(s: &crate::TextEdit, _: &mut Cx<crate::TextEdit>) -> El { + crate::text_input(s, crate::TextStyle::new(14.0, 400.0)).key("field").w(600.0).on_edit(|s: &mut crate::TextEdit| s) +} + +/// The same for a focused text field. +#[test] +fn typing_into_a_field_keeps_no_layout_of_each_edit() { + let mut edit = crate::TextEdit::new("Paragraph text long enough to wrap over several lines as the window narrows. ".repeat(8)); + edit.focused = true; + let mut rt = Runtime::new(edit, field, (700.0, 900.0), Env::new(true, 2.0)); + rt.frame(0.0); + let cached = rt.text.cached_layout_count(); + for i in 0..200 { + rt.update(|s, _| s.insert("k")); + rt.frame((i + 1) as f64 / 120.0); + } + assert!(rt.text.cached_layout_count() <= cached + 2, "{} layouts cached, {cached} at first", rt.text.cached_layout_count()); +} + +fn rows(s: &Vec<&'static str>, _: &mut Cx<Vec<&'static str>>) -> El { + col().children(s.iter().map(|&t| crate::el::text(t))) +} + +/// A text replaced by an unrelated one, as a reader showing another note, keeps its layout for +/// when it's shown again. +#[test] +fn a_text_shown_again_after_another_keeps_its_layout() { + let mut rt = Runtime::new(vec!["The first note's opening paragraph"], rows, (400.0, 300.0), Env::new(true, 2.0)); + rt.frame(0.0); + let shaped = rt.text.shaped; + rt.update(|s, _| s[0] = "Something else entirely, from another note"); + for f in 1..4 { rt.frame(f as f64 / 120.0); } + rt.update(|s, _| s[0] = "The first note's opening paragraph"); + for f in 4..8 { rt.frame(f as f64 / 120.0); } + assert_eq!(rt.text.shaped, shaped + 1, "only the other note shaped"); +} + +/// An edited text's old layout stays while another node shows the same text. +#[test] +fn an_edited_text_shown_elsewhere_keeps_its_layout() { + let mut rt = Runtime::new(vec!["same words", "same words"], rows, (400.0, 300.0), Env::new(true, 2.0)); + rt.frame(0.0); + let shaped = rt.text.shaped; + rt.update(|s, _| s[0] = "same wordz"); + for f in 1..4 { rt.frame(f as f64 / 120.0); } + rt.update(|s, _| s[0] = "same words"); + for f in 4..8 { rt.frame(f as f64 / 120.0); } + assert_eq!(rt.text.shaped, shaped + 1, "only the edit shaped"); +} + +#[test] +fn an_edit_shares_most_of_its_text_and_a_replacement_does_not() { + use super::super::text_layout::edited; + assert!(edited("hello world", "hello world!")); + assert!(edited("hello world", "hello, world")); + assert!(edited("12", "13")); + assert!(!edited("same", "same")); + assert!(!edited("Show", "Hide")); + assert!(!edited("The first note", "Another one")); +} diff --git a/app/vendor/rune/crates/rune/src/runtime/tests/titlebar_press.rs b/app/vendor/rune/crates/rune/src/runtime/tests/titlebar_press.rs new file mode 100644 index 0000000..de581f1 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/tests/titlebar_press.rs @@ -0,0 +1,317 @@ +//! Drives every short sequence of titlebar presses through the runtime and checks the press +//! state, the request handed to the shell and the window menu against a literal transcription of +//! the code before `TitlebarPress` replaced it: `action: Option<TitlebarAction>`, a `PressRun` +//! for the pair, `secondary_on_region: bool` and `window_menu`. +//! +//! The reference sees only the letters. It keeps its own run of presses (with `PressRun`'s count, +//! as it was), its own band, its own secondary flag and its own request slot, and the runtime's +//! answers are compared with it after every letter, on both a custom titlebar that draws caption +//! buttons and one that draws none. + +use std::sync::Mutex; +use std::sync::atomic::{AtomicUsize, Ordering}; + +use super::*; + +/// Sequences of up to this many letters. +const LENGTH: usize = 5; +/// The double-click interval both sides run with. +const INTERVAL: f64 = 0.3; +/// `CLICK_SLOP`, as the reference transcribes it. +const SLOP: f32 = 4.0; +/// The native titlebar band both sides run with. +const BAND: f32 = 28.0; + +/// A press on the bare `.window_drag()` region. +const REGION: (f32, f32) = (100.0, 50.0); +/// A press on the same region, past the click slop of `REGION`. +const REGION_FAR: (f32, f32) = (140.0, 50.0); +/// A press on the button inside the region. +const BUTTON: (f32, f32) = (20.0, 50.0); +/// A press on nothing, in the native band and clear of the caption buttons. +const EMPTY_BAND: (f32, f32) = (20.0, 10.0); +/// A press on nothing, below the band. +const EMPTY_BELOW: (f32, f32) = (100.0, 160.0); + +#[derive(Clone, Copy, Debug)] +enum Letter { + Region, + RegionFar, + Button, + EmptyBand, + EmptyBelow, + SecDownRegion, + SecDownButton, + SecUpRegion, + SecUpButton, + Clear, + Tick, + TakeAction, + TakeMenu, +} + +const ALPHABET: [Letter; 13] = [ + Letter::Region, Letter::RegionFar, Letter::Button, Letter::EmptyBand, Letter::EmptyBelow, + Letter::SecDownRegion, Letter::SecDownButton, Letter::SecUpRegion, Letter::SecUpButton, + Letter::Clear, Letter::Tick, Letter::TakeAction, Letter::TakeMenu, +]; + +/// Whether a press at `point` is this press's second: `press_run::follows`, transcribed. +fn follows(then: f64, was: (f32, f32), now: f64, point: (f32, f32), interval: f64) -> bool { + now - then <= interval && (point.0 - was.0).abs() <= SLOP && (point.1 - was.1).abs() <= SLOP +} + +/// `press_run::PressRun`'s last press: its element (always the titlebar's `""`), time, point and +/// count. +struct Run { + at: f64, + point: (f32, f32), + count: u32, +} + +/// `Titlebar` and the runtime's two entry points before `TitlebarPress`, field for field. +struct Dev { + action: Option<TitlebarAction>, + run: Option<Run>, + native_band: f32, + secondary_on_region: bool, + window_menu: Option<WindowMenu>, +} + +impl Dev { + fn new(native_band: f32) -> Self { + Self { action: None, run: None, native_band, secondary_on_region: false, window_menu: None } + } + + fn press_region(&mut self, now: f64, x: f32, y: f32, interval: f64) { + self.action = Some(if self.double(now, x, y, interval) { TitlebarAction::DoubleClick } else { TitlebarAction::Drag }); + } + + fn press_empty(&mut self, now: f64, x: f32, y: f32, interval: f64) { + if y < self.native_band && self.double(now, x, y, interval) { + self.action = Some(TitlebarAction::DoubleClick); + } + } + + fn clear(&mut self) { + self.run = None; + // differs from dev: a replaced stage no longer owns a secondary press either. + self.secondary_on_region = false; + } + + /// `PressRun::press("", ..) >= 2`, after which the next press starts a new pair. + fn double(&mut self, now: f64, x: f32, y: f32, interval: f64) -> bool { + let count = match &mut self.run { + Some(last) if follows(last.at, last.point, now, (x, y), interval) => { + (last.at, last.point) = (now, (x, y)); + last.count += 1; + last.count + } + _ => { + self.run = Some(Run { at: now, point: (x, y), count: 1 }); + 1 + } + }; + if count >= 2 { self.run = None; } + count >= 2 + } + + fn secondary_down(&mut self, region: bool) { + self.secondary_on_region = region; + } + + fn secondary_up(&mut self, region: bool) { + if std::mem::take(&mut self.secondary_on_region) && region { self.window_menu = Some(WindowMenu::Pointer); } + } + + fn take_action(&mut self) -> Option<TitlebarAction> { self.action.take() } + + fn take_menu(&mut self) -> Option<WindowMenu> { self.window_menu.take() } + + /// The press the next one would pair with, and a secondary press that still owes its release. + fn state(&self) -> (Option<(f64, (f32, f32))>, bool) { + (self.run.as_ref().map(|run| (run.at, run.point)), self.secondary_on_region) + } +} + +/// The same two facts, read out of the branch's press. +fn state_of(press: titlebar::TitlebarPress) -> (Option<(f64, (f32, f32))>, bool) { + match press { + titlebar::TitlebarPress::Rest => (None, false), + titlebar::TitlebarPress::Armed(pair) => (Some((pair.at, pair.point)), false), + titlebar::TitlebarPress::SecondaryOnRegion(pair) => (pair.map(|pair| (pair.at, pair.point)), true), + } +} + +/// The runtime with a bare drag region, a button in it and space around it, and the reference. +struct Walk { + rt: Runtime<()>, + dev: Dev, + /// The virtual clock both sides read, as the host's would tick on. + now: f64, + /// Whether the custom titlebar draws caption buttons, which the secondary press needs. + caption: bool, +} + +impl Walk { + fn new(caption: bool) -> Self { + fn view(_: &(), _: &mut Cx<()>) -> El { + col().size(200.0, 200.0) + // The band the system drags, and room for the caption buttons a custom titlebar + // draws over the top right. + .child(el().key("top").size(200.0, 32.0)) + .child(crate::el::row().key("titlebar").size(200.0, 40.0).window_drag() + .child(el().key("button").size(40.0, 40.0).on_press(|_: &mut ()| {}))) + .child(el().key("body").size(200.0, 40.0)) + } + let mut rt = Runtime::new((), view, (200.0, 200.0), Env::new(true, 1.0)); + rt.double_click_interval = INTERVAL; + rt.set_native_titlebar_band(BAND); + if caption { rt.set_caption(Some(crate::titlebar::Caption::new(BAND))); } + rt.frame(0.0); + Self { rt, dev: Dev::new(BAND), now: 0.0, caption } + } + + /// Whatever the last sequence left goes, without stepping: the next starts at `Rest`. + fn reset(&mut self) { + self.rt.cancel_pointer(); + self.rt.host.titlebar.press = titlebar::TitlebarPress::Rest; + self.rt.host.titlebar.action = None; + self.rt.take_window_menu(); + self.rt.frame.queue.retain(|_| false); + self.rt.clock = 0.0; + self.dev = Dev::new(BAND); + self.now = 0.0; + } + + /// Whether a secondary press at `point` lands on the bare region: a custom titlebar that + /// draws caption buttons, and a point inside its drag row clear of the button. + fn on_region(&self, point: (f32, f32)) -> bool { + self.caption && (point == REGION || point == REGION_FAR) + } + + /// A primary press and release at `point`; `ask` is what the reference's press asked for, + /// after `pointer_down` dropped the request nobody took. + fn press(&mut self, point: (f32, f32), ask: impl FnOnce(&mut Dev)) { + self.dev.action = None; + self.rt.pointer_down(point.0, point.1); + self.rt.pointer_up(point.0, point.1); + ask(&mut self.dev); + } + + /// Plays one letter on the runtime and the reference, and compares what each left behind. + fn play(&mut self, letter: Letter) -> Result<(), String> { + let now = self.now; + match letter { + Letter::Region => self.press(REGION, |dev| dev.press_region(now, REGION.0, REGION.1, INTERVAL)), + Letter::RegionFar => self.press(REGION_FAR, |dev| dev.press_region(now, REGION_FAR.0, REGION_FAR.1, INTERVAL)), + Letter::Button => self.press(BUTTON, |_| {}), + Letter::EmptyBand => self.press(EMPTY_BAND, |dev| dev.press_empty(now, EMPTY_BAND.0, EMPTY_BAND.1, INTERVAL)), + Letter::EmptyBelow => self.press(EMPTY_BELOW, |dev| dev.press_empty(now, EMPTY_BELOW.0, EMPTY_BELOW.1, INTERVAL)), + Letter::SecDownRegion | Letter::SecDownButton => { + let point = if matches!(letter, Letter::SecDownRegion) { REGION } else { BUTTON }; + self.rt.secondary_down(point.0, point.1); + let region = self.on_region(point); + self.dev.secondary_down(region); + } + Letter::SecUpRegion | Letter::SecUpButton => { + let point = if matches!(letter, Letter::SecUpRegion) { REGION } else { BUTTON }; + self.rt.secondary_up(point.0, point.1); + let region = self.on_region(point); + self.dev.secondary_up(region); + } + Letter::Clear => { + self.rt.host.titlebar.clear(); + self.dev.clear(); + } + Letter::Tick => { + self.now += 0.5; + self.rt.clock = self.now; + } + Letter::TakeAction => { + let (ours, reference) = (self.rt.take_titlebar_action(), self.dev.take_action()); + if ours != reference { return Err(format!("take action {ours:?}, dev {reference:?}")); } + } + Letter::TakeMenu => { + let (ours, reference) = (self.rt.take_window_menu(), self.dev.take_menu()); + if ours != reference { return Err(format!("take menu {ours:?}, dev {reference:?}")); } + } + } + self.compare(letter) + } + + fn compare(&self, letter: Letter) -> Result<(), String> { + if self.rt.host.titlebar.action != self.dev.action { + return Err(format!("after {letter:?}: action {:?}, dev {:?}, press {:?}", self.rt.host.titlebar.action, + self.dev.action, self.rt.host.titlebar.press)); + } + let (ours, reference) = (state_of(self.rt.host.titlebar.press), self.dev.state()); + if ours != reference { return Err(format!("after {letter:?}: press {ours:?}, dev {reference:?}")); } + Ok(()) + } +} + +#[test] +fn focus_loss_cancels_titlebar_press() { + let mut rt = Walk::new(true).rt; + let (x, y) = REGION; + rt.pointer_down(x, y); + rt.secondary_down(x, y); + rt.window_focus(false); + rt.window_focus(true); + assert_eq!(rt.take_titlebar_action(), Some(TitlebarAction::Drag)); + rt.secondary_up(x, y); + assert_eq!(rt.take_window_menu(), None); + rt.pointer_down(x, y); + assert_eq!(rt.take_titlebar_action(), Some(TitlebarAction::Drag)); + rt.pointer_down(x, y); + assert_eq!(rt.take_titlebar_action(), Some(TitlebarAction::DoubleClick)); +} + +/// Plays every sequence that starts with `sequence`, recording the first one that differs. +fn visit(walk: &mut Walk, sequence: &mut Vec<Letter>, ran: &mut usize, failure: &mut Option<String>) { + if failure.is_some() { return; } + *ran += 1; + walk.reset(); + for &letter in sequence.iter() { + if let Err(why) = walk.play(letter) { + *failure = Some(format!("cap={} {sequence:?}: {why}", walk.caption)); + return; + } + } + if sequence.len() == LENGTH { return; } + for letter in ALPHABET { + sequence.push(letter); + visit(walk, sequence, ran, failure); + sequence.pop(); + } +} + +#[test] +fn every_short_sequence_of_titlebar_presses_leaves_what_dev_left() { + let jobs: Vec<(bool, Letter)> = [false, true].into_iter().flat_map(|caption| ALPHABET.map(|letter| (caption, letter))).collect(); + let next = AtomicUsize::new(0); + let results = Mutex::new(Vec::new()); + let workers = std::thread::available_parallelism().map_or(4, |n| n.get()).min(8); + std::thread::scope(|scope| { + for _ in 0..workers { + scope.spawn(|| { + let mut walks = [Walk::new(false), Walk::new(true)]; + let (mut ran, mut failure) = (0, None); + while let Some(&(caption, letter)) = jobs.get(next.fetch_add(1, Ordering::Relaxed)) { + visit(&mut walks[usize::from(caption)], &mut vec![letter], &mut ran, &mut failure); + } + results.lock().unwrap().push((ran, failure)); + }); + } + }); + let mut total = 0; + let mut failures = Vec::new(); + for (ran, failure) in results.into_inner().unwrap() { + total += ran; + failures.extend(failure); + } + println!("{total} sequences up to length {LENGTH}"); + assert!(failures.is_empty(), "sequences differ from dev: {failures:#?}"); + assert!(total > 100_000, "only {total} sequences ran"); +} diff --git a/app/vendor/rune/crates/rune/src/runtime/tests/unseen_entrances.rs b/app/vendor/rune/crates/rune/src/runtime/tests/unseen_entrances.rs new file mode 100644 index 0000000..e1d5860 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/tests/unseen_entrances.rs @@ -0,0 +1,46 @@ +use super::*; +use crate::el::ScrollSpec; + +/// A 100 pt scroll over 40 rows; `n` odd lights every row. +fn lit(n: &u32, _cx: &mut Cx<u32>) -> El { + let fill = if n % 2 == 1 { Color::WHITE } else { Color::TRANSPARENT }; + let rows = (0..40).map(|i| col().key(format!("r{i}")).w_full().h(40.0).fill(fill)); + col().w_full().h_full().child(col().key("scroll").w_full().h(100.0).scroll(ScrollSpec { stick_bottom: false }).child(col().children(rows))) +} + +#[test] +fn colours_out_of_sight_land_at_once() { + let mut rt = Runtime::new(0u32, lit, (300.0, 300.0), Env::new(true, 2.0)); + rt.frame(0.0); + rt.frame(1.0 / 120.0); + rt.update(|n, _| *n = 1); + rt.frame(1.0 / 120.0); + let fading = |rt: &Runtime<u32>, key: &str| { + let id = rt.tree.nodes.iter().find(|n| n.named(key)).unwrap().id; + rt.scene.store().is_animating(id, P_FILL) + }; + assert!(fading(&rt, "r0"), "a row in sight fades its fill"); + assert!(!fading(&rt, "r30"), "a row out of sight lands it"); +} + +/// A 100 pt scroll over 40 rows, each with a digit; `n` ticks every row's digit. +fn ticking(n: &u32, _cx: &mut Cx<u32>) -> El { + let rows = (0..40).map(|i| { + let digit = el().key(format!("d{i}-{n}")).size(10.0, 10.0).fill(Color::WHITE).transition(Transition::opacity()); + col().key(format!("r{i}")).w_full().h(40.0).child(digit) + }); + col().w_full().h_full().child(col().key("scroll").w_full().h(100.0).scroll(ScrollSpec { stick_bottom: false }).child(col().children(rows))) +} + +#[test] +fn what_mounts_out_of_sight_enters_at_once() { + let mut rt = Runtime::new(0u32, ticking, (300.0, 300.0), Env::new(true, 2.0)); + rt.frame(0.0); + rt.frame(1.0 / 120.0); + rt.update(|n, _| *n = 1); + rt.frame(1.0 / 120.0); + let opacity = |key: &str| rt.elements().into_iter().find(|e| e.key.as_deref() == Some(key)).map(|e| e.opacity); + assert!(opacity("d0-1").is_some_and(|o| o < 1.0), "a digit in sight fades in: {:?}", opacity("d0-1")); + assert_eq!(opacity("d30-1"), Some(1.0), "a digit out of sight lands at once"); + assert_eq!(opacity("d30-0"), None, "and the one it replaced goes at once"); +} diff --git a/app/vendor/rune/crates/rune/src/runtime/tests/window_wake.rs b/app/vendor/rune/crates/rune/src/runtime/tests/window_wake.rs new file mode 100644 index 0000000..467aaef --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/tests/window_wake.rs @@ -0,0 +1,261 @@ +use super::*; + + +#[test] +fn window_frame_requests_take_the_change_spring() { + let mut rt = Runtime::new((), |_: &(), _: &mut Cx<()>| el(), (100.0, 100.0), Env::new(true, 1.0)); + let spring = |rt: &mut Runtime<()>, f: fn(&mut Tx)| { + rt.update(move |_, tx| f(tx)); + rt.host.window_frame.take().unwrap().spring + }; + assert_eq!(spring(&mut rt, |tx| tx.resize_window((1.0, 2.0))), Some(crate::tok::motion::DEFAULT)); + assert_eq!(spring(&mut rt, |tx| { tx.motion(crate::tok::motion::SNAP); tx.resize_window((1.0, 2.0)) }), Some(crate::tok::motion::SNAP)); + assert_eq!(spring(&mut rt, |tx| { tx.instant(); tx.resize_window((1.0, 2.0)) }), None); + assert_eq!(spring(&mut rt, |tx| tx.resize_window_instant((1.0, 2.0))), None); + rt.set_system_reduced_motion(true); + rt.frame(0.0); + assert_eq!(spring(&mut rt, |tx| tx.resize_window((1.0, 2.0))), None); + rt.update(|_, tx| { tx.resize_window((1.0, 2.0)); tx.center_window(); }); + let request = rt.host.window_frame.take().unwrap(); + assert_eq!((request.size, request.center), (Some((1.0, 2.0)), true)); +} + +#[test] +fn a_window_resize_step_keeps_springs_and_flights_going() { + fn view(grown: &bool, _: &mut Cx<bool>) -> El { + let tile = || el().key("tile").matched("tile").size(40.0, 40.0).fill(Color::WHITE); + let (mut left, mut right) = (el().key("left").size(100.0, 60.0), el().key("right").size(100.0, 60.0).ml(150.0)); + if *grown { right = right.child(tile()) } else { left = left.child(tile()) } + col().key("root").w_full().h_full() + .child(el().key("box").size(50.0, if *grown { 150.0 } else { 50.0 }).fill(Color::WHITE)) + .child(left).child(right) + .child(crate::el::spacer()) + .child(el().key("bar").w_full().h(20.0).fill(Color::WHITE)) + } + let resize = |user: bool| { + let mut rt = Runtime::new(false, view, (300.0, 400.0), Env::new(true, 1.0)); + rt.frame(0.0); + rt.update(|grown, tx| { *grown = true; tx.resize_window((300.0, 600.0)) }); + rt.frame(1.0 / 60.0); + rt.host.window_frame.take(); + if user { rt.set_viewport((300.0, 450.0), 1.0) } else { rt.step_viewport((300.0, 450.0), 1.0) } + rt.frame(1.0 / 60.0); + rt + }; + let rt = resize(false); + let rect = |rt: &Runtime<bool>, key: &str| rt.presented(key).unwrap().0; + let h = rect(&rt, "box")[3]; + assert!(h > 50.0 && h < 150.0, "the box's spring keeps going: {h}"); + assert!(rt.elements().iter().any(|e| e.key.as_deref() == Some("tile") && e.moving), "the tile is still in flight"); + let x = rect(&rt, "tile")[0]; + assert!(x > 0.0 && x < 150.0, "mid-flight: {x}"); + assert_eq!(rect(&rt, "bar")[1], 430.0, "content at rest follows the window"); + assert_eq!(rect(&resize(true), "box")[3], 150.0, "a user's resize lands running motion"); +} + +#[test] +fn a_window_that_fits_its_content_refits_after_a_user_resize() { + fn view(_: &(), _: &mut Cx<()>) -> El { col().key("root").w_full().child(el().size(100.0, 90.0)) } + let mut rt = Runtime::new((), view, (300.0, 400.0), Env::new(true, 1.0)); + rt.host.fit_height = true; + let height = rt.content_height(); + rt.set_viewport((300.0, height), 1.0); + rt.frame(0.0); + rt.host.window_frame.take(); + // Mid-move, the window's own frame changes aren't a user's resize. + rt.set_viewport((300.0, height + 40.0), 1.0); + rt.frame(1.0 / 60.0); + assert!(rt.host.window_frame.take().is_none()); + rt.host.window_resting = true; + rt.set_viewport((300.0, height + 100.0), 1.0); + rt.frame(1.0 / 60.0); + assert_eq!(rt.host.window_frame.take().and_then(|r| r.size), Some((300.0, height))); +} + +/// A window that fits its content, and grew while hidden, learns its new height before it +/// shows: its first frame isn't clipped, then resized in view. +#[test] +fn a_hidden_window_that_fits_its_content_learns_its_height_before_it_shows() { + fn view(s: &(usize, bool), _: &mut Cx<(usize, bool)>) -> El { + col().key("root").w_full().children((0..s.0).map(|_| el().size(100.0, 40.0))) + } + let mut rt = Runtime::new((1, false), view, (300.0, 400.0), Env::new(true, 1.0)); + rt.host.fit_height = true; + let height = rt.content_height(); + rt.set_viewport((300.0, height), 1.0); + rt.frame(0.0); + rt.host.window_frame.take(); + assert!(!rt.build_for_show(), "unchanged, the last frame still shows it"); + rt.poll = Some(|s: &mut (usize, bool), _, _: &mut Tx| { + if !std::mem::take(&mut s.1) { return false; } + s.0 += 1; + true + }); + rt.state.1 = true; + let commits = rt.stats.commits; + assert!(rt.poll_hidden()); + assert!(rt.host.window_frame.is_none() && rt.stats.commits == commits, "hidden, nothing builds yet"); + assert!(rt.build_for_show()); + let request = rt.host.window_frame.take().expect("the new height, before the window shows"); + assert_eq!(request.size, Some((300.0, 80.0))); + assert!(!request.animate, "it opens at that height"); + rt.set_viewport((300.0, 80.0), 1.0); + rt.frame(0.0); + assert_eq!(rt.stats.commits, commits + 1, "the first frame shown has nothing left to build"); + assert!(rt.host.window_frame.is_none()); +} + +#[test] +fn timed_wakes_are_exact_coalesced_and_do_not_commit_or_animate() { + use std::time::Duration; + fn view(_: &Vec<f64>, cx: &mut Cx<Vec<f64>>) -> El { + cx.time_scale(0.1); + el() + } + fn poll(seen: &mut Vec<f64>, clock: f64, tx: &mut Tx) -> bool { + seen.push(clock); + if clock == 0.0 { + tx.wake_after(Duration::from_millis(250)); + tx.wake_after(Duration::from_millis(250)); + tx.wake_after(Duration::from_millis(375)); + } + false + } + let mut rt = Runtime::new(Vec::new(), view, (100.0, 100.0), Env::new(true, 1.0)); + rt.poll = Some(poll); + assert!(!rt.frame(0.0)); + assert_eq!(rt.frame.wake_deadlines(), [0.25, 0.375]); + assert!(!rt.frame(0.5)); + assert_eq!(rt.state, [0.0, 0.25, 0.375, 0.5]); + assert_eq!(rt.commit.commits, 1); + assert_eq!(rt.wake_deadline(), None); + assert!((rt.t - 0.05).abs() < 1e-8); +} + +#[test] +fn wakes_a_poll_keeps_asking_for_collapse_to_one_poll_a_frame() { + use std::time::Duration; + // (polls this frame, delay each poll asks for) + fn poll(s: &mut (usize, f64), _: f64, tx: &mut Tx) -> bool { + s.0 += 1; + tx.wake_after(Duration::from_secs_f64(s.1)); + false + } + // A wake every frame, a wake that lands between frames, a save timer that rearms on + // every poll, and one that lands just past a frame boundary. + for delay in [0.0, 1.0 / 60.0, 1.0 / 120.0, 0.505, 0.5] { + fn view(_: &(usize, f64), _: &mut Cx<(usize, f64)>) -> El { el() } + let mut rt = Runtime::new((0, delay), view, (100.0, 100.0), Env::new(true, 1.0)); + rt.poll = Some(poll); + for frame in 0..1000 { + rt.state.0 = 0; + rt.frame(1.0 / 60.0); + assert_eq!(rt.state.0, 1, "delay {delay}: frame {frame} polled {} times", rt.state.0); + } + assert!(rt.frame.wake_deadlines().len() <= 32, "delay {delay}: {} deadlines pending", rt.frame.wake_deadlines().len()); + } +} + +#[test] +fn a_zero_wake_does_not_hide_a_later_wake_in_a_coarse_frame() { + use std::time::Duration; + fn poll(s: &mut Vec<f64>, now: f64, tx: &mut Tx) -> bool { + s.push((now * 1000.0).round() / 1000.0); + if s.len() == 1 { + tx.wake_after(Duration::ZERO); + tx.wake_after(Duration::from_millis(50)); + } + false + } + fn view(_: &Vec<f64>, _: &mut Cx<Vec<f64>>) -> El { el() } + let mut rt = Runtime::new(Vec::new(), view, (100.0, 100.0), Env::new(true, 1.0)); + rt.poll = Some(poll); + rt.frame(0.0); + rt.frame(0.1); + assert_eq!(rt.state, [0.0, 0.017, 0.05, 0.1]); +} + +#[test] +fn timed_wakes_from_handlers_survive_transaction_merging() { + fn view(_: &(), _: &mut Cx<()>) -> El { + el().key("button").size(100.0, 100.0).on_press_tx(|_: &mut (), tx| { + tx.wake_after(std::time::Duration::from_millis(250)); + }) + } + let mut rt = Runtime::new((), view, (100.0, 100.0), Env::new(true, 1.0)); + rt.frame(0.0); + rt.pointer_down(10.0, 10.0); + rt.pointer_up(10.0, 10.0); + rt.frame(0.1); + assert_eq!(rt.wake_deadline(), Some(0.35)); + rt.frame(0.25); + assert_eq!(rt.wake_deadline(), None); +} + +#[test] +fn a_titlebar_inset_change_rebuilds_the_view() { + fn view(_: &(), cx: &mut Cx<()>) -> El { + crate::row().size(300.0, 40.0).child(el().key("leading").w(cx.titlebar_inset())).child(el().key("title").size(50.0, 20.0)) + } + let x = |rt: &Runtime<()>| rt.presented("title").unwrap().0[0]; + let mut rt = Runtime::new((), view, (300.0, 40.0), Env::new(true, 1.0)); + rt.frame(0.0); + assert_eq!(x(&rt), 0.0, "no traffic lights by default"); + rt.set_titlebar_inset(crate::Chrome::DEFAULT.titlebar_inset()); + rt.frame(0.1); + rt.frame(5.0); + assert_eq!(x(&rt), 67.0, "AppKit's default lights end at 7 + 2 × 23 + 14"); + rt.set_titlebar_inset(0.0); + rt.frame(5.1); + rt.frame(10.0); + assert_eq!(x(&rt), 0.0, "full screen hides them"); + let titled = crate::Chrome { full_size_content: false, ..crate::Chrome::DEFAULT }; + assert_eq!(titled.titlebar_inset(), 0.0); +} + +#[test] +fn a_new_system_accent_rebuilds_the_view_and_its_memos() { + // Widths stand in for colours: the view draws what it read. + fn view(_: &(), cx: &mut Cx<()>) -> El { + let (accent, focus) = (cx.accent(), cx.focus_color()); + crate::row().size(300.0, 40.0) + .child(el().key("accent").size(accent.g * 100.0, 10.0)) + .child(crate::memo("ring", 0, || el().key("ring").size(focus.a * 100.0, 10.0))) + } + let mut rt = Runtime::new((), view, (300.0, 40.0), Env::new(true, 1.0)); + rt.frame(0.0); + let w = |rt: &Runtime<()>, key: &str| (rt.presented(key).unwrap().0[2] * 10.0).round() / 10.0; + assert_eq!((w(&rt, "accent"), w(&rt, "ring")), (23.1, 50.0), "macOS's dark blue, rings at 50%"); + let pink = crate::Color { r: 1.0, g: 0.2, b: 0.6, a: 1.0 }; + rt.set_system_accent(crate::SystemAccent::new(pink, pink).with_focus(pink, pink.alpha(0.7))); + rt.frame(0.1); + rt.frame(5.0); + assert_eq!((w(&rt, "accent"), w(&rt, "ring")), (20.0, 70.0)); +} + +#[test] +fn a_new_system_scroll_bar_setting_rebuilds_the_view_and_its_memos() { + fn view(_: &(), cx: &mut Cx<()>) -> El { + let overlay = cx.overlay_scroll_bars(); + crate::row().size(300.0, 40.0) + .child(el().key("cx").size(if overlay { 20.0 } else { 80.0 }, 10.0)) + .child(crate::memo("memo", 0, || { + let scoped = crate::system_scroll_bars().is_overlay(crate::system_scroller_overlay()); + el().size(if scoped { 30.0 } else { 90.0 }, 10.0) + })) + } + let mut rt = Runtime::new((), view, (300.0, 40.0), Env::new(true, 1.0)); + rt.frame(0.0); + let w = |rt: &Runtime<()>, key: &str| rt.presented(key).unwrap().0[2]; + assert_eq!((w(&rt, "cx"), w(&rt, "memo")), (20.0, 30.0), "headless defaults to WhenScrolling"); + rt.set_system_scroll_bars(crate::ScrollBars::Always); + rt.frame(5.0); + assert_eq!((w(&rt, "cx"), w(&rt, "memo")), (80.0, 90.0)); + rt.set_system_scroll_bars(crate::ScrollBars::Automatic); + rt.set_system_scroller_overlay(true); + rt.frame(5.0); + assert_eq!((w(&rt, "cx"), w(&rt, "memo")), (20.0, 30.0)); + rt.set_system_scroller_overlay(false); + rt.frame(5.0); + assert_eq!((w(&rt, "cx"), w(&rt, "memo")), (80.0, 90.0)); +} diff --git a/app/vendor/rune/crates/rune/src/runtime/text_fill.rs b/app/vendor/rune/crates/rune/src/runtime/text_fill.rs new file mode 100644 index 0000000..82144ae --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/text_fill.rs @@ -0,0 +1,128 @@ +//! A long paste's paragraphs that wait to be shaped (`text::Lazy`): shaped a few a frame, those +//! the field shows first, and all of those near what an input needs before it reads them. +use super::*; + +/// How long a frame shapes waiting paragraphs. +const BUDGET: std::time::Duration = std::time::Duration::from_micros(1_500); + +/// Visible vertical row range (in unscaled layout device pixels) drawn by `paint_content` and `fill_visible_by_line`. +pub(crate) fn visible_text_rows(spec: &crate::el::TextSpec, rest_y: f32, shown: [f32; 2], tk: f32, raster: f32, s: f32) -> std::ops::Range<f32> { + let em = spec.spans.iter().filter_map(|sp| sp.size).fold(spec.style.size.max(spec.style.line_px()), f32::max); + let pad = 2.0 * em * s + 2.0 / raster.max(1e-4); + if tk > 1e-4 { (shown[0] - rest_y) / tk - pad..(shown[1] - rest_y) / tk + pad } else { f32::NEG_INFINITY..f32::INFINITY } +} + +impl types::TreeState { + /// Whether any painted text still has unshaped paragraphs needing a background fill frame: + /// every waiting paragraph for an input field, or those within a viewport's height of the + /// painted clip for a read-only `by_line` block (whose off-screen lines stay compact runs). + pub(super) fn text_fill_due(&self, text_rows: &HashMap<NodeId, (f32, f32)>) -> bool { + text_rows.iter().any(|(&id, &(r0, r1))| { + let Some(n) = self.node_by_id(id) else { return false }; + let Some(crate::text::TextLayout::Paragraphs(p)) = &n.text_layout else { return false }; + if !p.waiting() { return false; } + if n.input.is_some() { return true; } + let reach = (r1 - r0).max(0.0) + 1.0; + p.paragraphs.iter().any(|q| !q.shaped && q.y + q.height >= r0 - reach && q.y <= r1 + reach) + }) + } +} + +impl RuntimeCore { + /// Shapes waiting paragraphs of each field for up to [`BUDGET`], the rows it drew last + /// first. True while some still wait, so another frame comes. + pub(super) fn fill_text(&mut self) -> bool { + self.fill_text_within(BUDGET, None) + } + + /// Before an input that reads a field's layout (a caret key, a press, a drag): every + /// waiting paragraph within a window's height of the rows each field drew, shaped now. + pub(super) fn fill_text_near(&mut self) { + self.fill_text_within(std::time::Duration::MAX, Some(1.0)); + } + + #[inline] + pub(super) fn text_fill_due(&self) -> bool { + self.tree.text_fill_due(&self.paint.text_rows) + } + + /// Before painting a `by_line` node (`input.is_none()`): shapes any waiting lines inside its + /// visible clip with no time budget, so a jump, scrollbar drag, `End` or restored session + /// never paints interior lines blank for a frame; `fill_text` keeps its budget for the margin. + #[allow(clippy::too_many_arguments)] + pub(super) fn fill_visible_by_line( + &mut self, + i: usize, + r: [f32; 4], + exact_off: [f32; 2], + sc: f32, + cover: Option<(f32, [f32; 2])>, + scale_motion: ScaleMotion, + rest: f32, + gliding: bool, + shown: [f32; 2], + ) { + if self.tree.nodes[i].input.is_some() { return; } + let (Some(spec), Some(crate::text::TextLayout::Paragraphs(p))) = (&self.tree.nodes[i].text, &self.tree.nodes[i].text_layout) else { return }; + if !p.waiting() { return; } + let s = self.env.scale; + let tk = if cover.is_some() { 1.0 } else { sc }; + let zk = match cover { Some((k, _)) => k, None => sc }; + let raster = if cover.is_some() { 1.0 } else { scale_motion.raster(sc, rest) }; + let still = scale_motion == ScaleMotion::Still; + let y_top = match cover { Some((_, c)) => r[1] + c[1] * s, None => r[1] } + + if still && (sc - 1.0).abs() < 1e-5 { exact_off[1] } else { 0.0 } + + self.tree.nodes[i].inset[1] * zk * s; + let rest_y = y_top - if gliding && cover.is_none() && still { r[1] - r[1].round() } else { 0.0 }; + let rows = visible_text_rows(spec, rest_y, shown, tk, raster, s); + let rows = (rows.start, rows.end); + if !p.paragraphs.iter().any(|q| !q.shaped && q.y + q.height >= rows.0 && q.y <= rows.1) { return; } + let p = p.clone(); + if let Some((built, moved)) = self.text.fill_paragraphs(&p, std::time::Duration::MAX, rows, 0.0) { + self.tree.nodes[i].text_layout = Some(crate::text::TextLayout::Paragraphs(built)); + if moved { self.commit.dirty = true; } + } + } + + fn fill_text_within(&mut self, budget: std::time::Duration, reach: Option<f32>) -> bool { + let mut more = false; + for i in 0..self.tree.nodes.len() { + let is_input = self.tree.nodes[i].input.is_some(); + let Some(crate::text::TextLayout::Paragraphs(p)) = &self.tree.nodes[i].text_layout else { continue }; + if !p.waiting() { continue; } + let id = self.tree.nodes[i].id; + let rows = match (is_input, self.paint.text_rows.get(&id).copied()) { + (true, r) => r.unwrap_or((0.0, 0.0)), + (false, Some(r)) => r, + (false, None) => continue, + }; + let p = p.clone(); + let eff_reach = match (is_input, reach) { + (true, None) => f32::INFINITY, + (_, r) => (rows.1 - rows.0).max(0.0) * r.unwrap_or(1.0) + 1.0, + }; + let Some((built, moved)) = self.text.fill_paragraphs(&p, budget, rows, eff_reach) else { continue }; + if is_input { + more |= built.waiting(); + } else { + more |= built.paragraphs.iter().any(|q| !q.shaped && q.y + q.height >= rows.0 - eff_reach && q.y <= rows.1 + eff_reach); + } + let n = &mut self.tree.nodes[i]; + n.text_layout = Some(crate::text::TextLayout::Paragraphs(built)); + n.epoch = paint_keep::next_epoch(); + // A waiting height is exact; should one not be, the field lays out again. + if moved { + #[cfg(debug_assertions)] + eprintln!("rune: text fill: a waiting paragraph of {} wasn't the height it waited at", self.tree.nodes[i].path); + self.commit.dirty = true; + } + } + let tree = &self.tree; + self.paint.text_rows.retain(|&id, _| { + tree.node_by_id(id) + .and_then(|n| n.text_layout.as_ref()) + .is_some_and(|l| matches!(l, crate::text::TextLayout::Paragraphs(p) if p.waiting())) + }); + more + } +} diff --git a/app/vendor/rune/crates/rune/src/runtime/timer_wake_tests.rs b/app/vendor/rune/crates/rune/src/runtime/timer_wake_tests.rs new file mode 100644 index 0000000..4613e53 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/timer_wake_tests.rs @@ -0,0 +1,224 @@ +//! A shown window's due timer while it rests: `poll` runs alone, and a frame follows only +//! when that poll changed something or anything else wants frames. +use super::*; +use crate::{Cx, El, Env}; +use std::time::Duration; + +/// The poll's timer. The runtime follows the real clock, so it is long enough that a stalled +/// test machine never finds a timer due that the test didn't move the clock to. +const PERIOD: Duration = Duration::from_secs(5); + +#[derive(Default)] +struct App { + polls: u32, + /// The poll that reports a change; none at 0. + change_at: u32, + /// Asks for the next frame (`wake_after(ZERO)`) instead of a quarter second. + step: bool, + width: f32, +} + +fn view(s: &App, _: &mut Cx<App>) -> El { + crate::col().children([crate::el().key("box").size(10.0 + s.width, 8.0)]) +} + +fn poll(s: &mut App, _: f64, tx: &mut Tx) -> bool { + s.polls += 1; + tx.wake_after(if s.step { Duration::ZERO } else { PERIOD }); + s.step || s.polls == s.change_at +} + +fn runtime(app: App) -> Runtime<App> { + let mut rt = Runtime::new(app, view, (200.0, 50.0), Env::default()); + rt.poll = Some(poll); + rt.wall_start = Some(crate::time::now()); + rt.frame(0.0); + rt.frame(crate::frame::clock::RESUME_STEP); + assert!(!rt.animating); + rt +} + +/// Moves the wall clock `secs` on. +fn advance(rt: &mut Runtime<App>, secs: f64) { + rt.wall_start = rt.wall_start.map(|t| t - Duration::from_secs_f64(secs)); +} + +/// Moves the wall clock to just past every armed timer: the setup frames each armed one a +/// moment apart in real time, and the later ones would otherwise outlast the poll. +fn reach_timer(rt: &mut Runtime<App>) { + let due = rt.frame.wake_deadlines().last().copied().expect("a timer is armed"); + let now = rt.wall_start.unwrap().elapsed().as_secs_f64(); + advance(rt, (due - now).max(0.0) + 1e-4); +} + +/// As the window host's `new_events`: a resting window polls first, `shell` runs what that +/// left (a close may hide the window), and a frame is asked for only when needed. Returns +/// whether it asked; the frame itself comes later. +fn host_wake(rt: &mut Runtime<App>, shell: impl FnOnce(&mut Runtime<App>) -> bool) -> bool { + reach_timer(rt); + let Some(stale) = rt.resting_wake() else { return true }; + let visible = shell(rt); + let frame = (stale || rt.stale()) && visible; + rt.resting_wake_frame(frame); + frame +} + +/// A timer wake with nothing between it and its frame. Returns whether it drew. +fn timer_wake(rt: &mut Runtime<App>) -> bool { + if !host_wake(rt, |_| true) { return false; } + rt.frame(crate::frame::clock::RESUME_STEP); + true +} + +#[test] +fn a_resting_window_s_timer_draws_only_for_a_poll_that_changed_something() { + let mut rt = runtime(App::default()); + let (commits, polls) = (rt.stats.commits, rt.state.polls); + rt.state.change_at = polls + 9; + for _ in 0..8 { assert!(!timer_wake(&mut rt), "a poll that returns false builds and draws nothing"); } + assert_eq!(rt.state.polls, polls + 8, "each timer still polls"); + assert_eq!(rt.stats.commits, commits, "and runs no view"); + let deadline = rt.wake_deadline().unwrap(); + assert!(deadline > rt.clock, "the poll's next timer is armed: {deadline} after {}", rt.clock); + + let frames = (0..6).filter(|_| timer_wake(&mut rt)).count(); + assert_eq!(frames, 1, "the poll that returns true gets exactly one frame"); + assert_eq!(rt.stats.commits, commits + 1); + assert_eq!(rt.state.polls, polls + 14, "one poll a wake: the frame doesn't poll again"); +} + +#[test] +fn a_poll_stepping_every_frame_still_draws_every_frame() { + let mut rt = runtime(App { step: true, ..App::default() }); + let polls = rt.state.polls; + for _ in 0..10 { assert!(timer_wake(&mut rt), "`wake_after(ZERO)` steps on frames"); } + assert_eq!(rt.state.polls - polls, 10, "the frames poll; the wakes don't poll first"); + // Steps reported as no change still take their frames, as before. + rt.poll = Some(|s, _, tx| { s.polls += 1; tx.wake_after(Duration::ZERO); false }); + rt.frame(crate::frame::clock::RESUME_STEP); + for _ in 0..5 { assert!(timer_wake(&mut rt)); } + // A resting window's poll that starts stepping takes the next frame. + let mut rt = runtime(App::default()); + assert!(!timer_wake(&mut rt)); + rt.poll = Some(|s, _, tx| { s.polls += 1; tx.wake_after(Duration::ZERO); false }); + let polls = rt.state.polls; + assert!(timer_wake(&mut rt), "its first step draws"); + assert!(timer_wake(&mut rt), "and so does every one after"); + assert_eq!(rt.state.polls, polls + 2, "one step each"); +} + +#[test] +fn motion_in_flight_takes_the_timer_s_frame() { + let mut rt = runtime(App::default()); + rt.update(|s, _| s.width = 120.0); + rt.frame(crate::frame::clock::RESUME_STEP); + assert!(rt.animating, "the box springs to its new width"); + let polls = rt.state.polls; + assert_eq!(rt.resting_wake(), None); + assert_eq!(rt.state.polls, polls, "the frame polls, not the wake"); +} + +#[test] +fn a_wake_before_the_timer_s_frame_gets_a_poll() { + let mut rt = runtime(App::default()); + let polls = rt.state.polls; + rt.state.change_at = polls + 1; + assert!(host_wake(&mut rt, |_| true)); + // `AppHandle::wake` lands before the frame (the display link is starting). + rt.cancel_timer_frame(); + let armed = rt.wake_deadline().expect("the timer poll's own timer counts from it"); + rt.frame(crate::frame::clock::RESUME_STEP); + assert_eq!(rt.state.polls, polls + 2, "the frame polls for the wake"); + assert_eq!(rt.frame.wake_deadlines().first(), Some(&armed)); +} + +#[test] +fn a_timer_due_between_the_poll_and_its_frame_gets_the_frame_s_poll() { + let mut rt = runtime(App::default()); + let polls = rt.state.polls; + rt.state.change_at = polls + 1; + assert!(host_wake(&mut rt, |_| true)); + let polled = rt.clock; + rt.schedule_wakes_from(polled, [Duration::from_millis(2)]); + advance(&mut rt, 0.005); + rt.frame(crate::frame::clock::RESUME_STEP); + assert_eq!(rt.state.polls, polls + 2, "the later timer polls"); + assert!(rt.frame.wake_deadlines().iter().all(|t| *t > rt.clock), "nothing due is left behind: {:?}", rt.frame.wake_deadlines()); + assert!(rt.resting_wake().is_some(), "and the window rests again"); +} + +#[test] +fn the_timer_s_frame_keeps_the_poll_s_time() { + let mut rt = runtime(App::default()); + let polls = rt.state.polls; + rt.state.change_at = polls + 1; + assert!(host_wake(&mut rt, |_| true)); + let polled = rt.clock; + advance(&mut rt, 0.004); + rt.frame(crate::frame::clock::RESUME_STEP); + assert_eq!(rt.state.polls, polls + 1); + assert!(rt.clock > polled); + assert_eq!(rt.polled_at(), polled, "timers pace from the poll, not the frame"); + let next = rt.wake_deadline().unwrap(); + assert!((next - (rt.clock + PERIOD.as_secs_f64())).abs() < 1e-9, "the poll's timer counts from the frame that took it"); +} + +#[test] +fn a_timer_poll_that_leaves_work_for_the_frame_is_its_only_poll() { + let mut rt = runtime(App::default()); + let polls = rt.state.polls; + // The poll changes nothing, but a command the host runs after it does. + assert!(host_wake(&mut rt, |rt| { rt.update(|s, _| s.width = 4.0); true })); + rt.frame(crate::frame::clock::RESUME_STEP); + assert_eq!(rt.state.polls, polls + 1, "the frame doesn't poll a second time"); +} + +#[test] +fn a_timer_poll_that_hides_the_window_asks_no_frame() { + let mut rt = runtime(App::default()); + let polls = rt.state.polls; + rt.state.change_at = polls + 1; + assert!(!host_wake(&mut rt, |_| false), "a keep-running window the poll closed"); + let polled = rt.clock; + assert!((rt.wake_deadline().unwrap() - (polled + PERIOD.as_secs_f64())).abs() < 1e-9, "its timer still runs, hidden"); + rt.frame(crate::frame::clock::RESUME_STEP); + assert_eq!(rt.state.polls, polls + 2, "the frame that shows it polls"); + + // Hidden or shown after the frame was asked for: the next frame polls, and the timer runs. + let mut rt = runtime(App::default()); + let polls = rt.state.polls; + rt.state.change_at = polls + 1; + assert!(host_wake(&mut rt, |_| true)); + let polled = rt.clock; + rt.cancel_timer_frame(); + assert!((rt.wake_deadline().unwrap() - (polled + PERIOD.as_secs_f64())).abs() < 1e-9); + rt.frame(crate::frame::clock::RESUME_STEP); + assert_eq!(rt.state.polls, polls + 2); +} + +/// The frame a resting wake asked for runs covered or misses its drawable (`covered_step`): +/// the wake's poll stands for it, and its timers count from that poll. +#[test] +fn a_timer_frame_that_runs_covered_does_not_poll_again() { + let mut rt = runtime(App::default()); + let polls = rt.state.polls; + rt.state.change_at = polls + 1; + assert!(host_wake(&mut rt, |_| true)); + let polled = rt.clock; + assert!(rt.hidden_wake(), "the poll's change is still to draw"); + assert_eq!(rt.state.polls, polls + 1, "one poll for the wake"); + assert!((rt.wake_deadline().unwrap() - (polled + PERIOD.as_secs_f64())).abs() < 1e-9, "its timer counts from the poll"); + rt.frame(crate::frame::clock::RESUME_STEP); + assert_eq!(rt.state.polls, polls + 2, "the frame that draws next polls"); + + // Another timer due by then still polls. + let mut rt = runtime(App::default()); + let polls = rt.state.polls; + rt.state.change_at = polls + 1; + assert!(host_wake(&mut rt, |_| true)); + let polled = rt.clock; + rt.schedule_wakes_from(polled, [Duration::from_millis(2)]); + advance(&mut rt, 0.005); + rt.hidden_wake(); + assert_eq!(rt.state.polls, polls + 2); +} diff --git a/app/vendor/rune/crates/rune/src/runtime/truncate_fade_tests.rs b/app/vendor/rune/crates/rune/src/runtime/truncate_fade_tests.rs new file mode 100644 index 0000000..743b49f --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/truncate_fade_tests.rs @@ -0,0 +1,83 @@ +//! `El::truncate_fade` fades a label only when it runs past its box, wherever the box lands. + +use super::*; +use crate::{Cx, El, Env, TextStyle, el, row, text}; + +/// (zoom, offset before the label, label, room after it) +type S = (f32, f32, &'static str, f32); + +fn view(s: &S, _: &mut Cx<S>) -> El { + let (zoom, offset, label, room) = *s; + el().w(400.0 / zoom).h(60.0 / zoom).scale(zoom).child( + row().w(400.0 / zoom).child(el().w(offset).h(1.0)).child( + el().max_w(room).child(text(label).key("label").font(TextStyle::new(13.0, 500.0)).truncate_fade().shrink()), + ), + ) +} + +/// The widest right-edge fade on the label's glyphs, in device px. +fn fade<T>(rt: &Runtime<T>) -> f32 { + rt.instances.iter() + .filter(|i| i.params[1] == crate::render::KIND_GLYPH) + .map(|i| crate::render::unpack_fade(i.fade).0[2]) + .fold(0.0, f32::max) +} + +#[test] +fn a_label_that_fits_never_fades_wherever_it_lands() { + let mut faded = Vec::new(); + for scale in [1.0, 2.0] { + for zoom in [1.0, 1.1, 1.25, 1.3, 1.5, 1.6] { + for label in ["Skill, Shell", "Read, Grep", "Shell"] { + for k in 0..40 { + let offset = 30.0 + k as f32 * 0.137; + let mut rt = Runtime::new((zoom, offset, label, 300.0), view, (400.0, 60.0), Env::new(true, scale)); + rt.frame(0.0); + let f = fade(&rt); + if f > 0.0 { + faded.push(format!("{scale}x, zoom {zoom}, {label:?} after {offset}: fades {f} px")); + } + } + } + } + } + assert!(faded.is_empty(), "{} labels with room faded: {faded:#?}", faded.len()); +} + +#[test] +fn a_label_cut_short_still_fades() { + for scale in [1.0, 2.0] { + for zoom in [1.0, 1.3] { + let mut rt = Runtime::new((zoom, 30.0, "Skill, Shell", 40.0), view, (400.0, 60.0), Env::new(true, scale)); + rt.frame(0.0); + assert!(fade(&rt) > 0.0, "{scale}x, zoom {zoom}"); + } + } +} + +/// A label in a row that springs to its new layout (`El::animate_layout`). +fn growing(label: &&'static str, _: &mut Cx<&'static str>) -> El { + row().w(400.0).h(40.0).child( + text(*label).key("label").font(TextStyle::new(13.0, 500.0)).truncate_fade().shrink().animate_layout(), + ) +} + +#[test] +fn a_label_that_fits_its_layout_never_fades_while_its_box_grows_to_it() { + for scale in [1.0, 2.0] { + let mut rt = Runtime::new("Read", growing, (400.0, 40.0), Env::new(true, scale)); + for _ in 0..60 { rt.frame(1.0 / 60.0); } + rt.update(|s, _| *s = "Read, Shell"); + let mut grew = false; + for f in 0..60 { + rt.frame(1.0 / 120.0); + let label = rt.elements().into_iter().find(|e| e.key.as_deref() == Some("label")).unwrap(); + grew |= label.rect[2] + 1.0 < label.target[2]; + assert_eq!(fade(&rt), 0.0, "{scale}x frame {f}: drawn {:?}, laid out {:?}", label.rect, label.target); + let right = rt.instances.iter().filter(|i| i.params[1] == crate::render::KIND_GLYPH) + .map(|i| i.clip[2] - (i.rect[0] + i.rect[2])).fold(f32::MAX, f32::min); + assert!(right >= -1.0, "{scale}x frame {f}: a glyph ends {} px past its clip", -right); + } + assert!(grew, "{scale}x: the box should spring wider over frames"); + } +} diff --git a/app/vendor/rune/crates/rune/src/runtime/truncate_tests.rs b/app/vendor/rune/crates/rune/src/runtime/truncate_tests.rs new file mode 100644 index 0000000..9d43d62 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/truncate_tests.rs @@ -0,0 +1,242 @@ +//! `El::truncate_middle` and `El::truncate_head`: the ellipsis replaces the middle or the start, +//! cuts fall between graphemes, a resize refits the cut, and copying and tools keep the whole +//! string. +use super::*; +use crate::el::Elide; +use crate::{Color, Cx, El, Env, Key, KeyEvent, Link, Mods, Span, TextStyle, col, rich}; +use unicode_segmentation::UnicodeSegmentation; + +const PATH: &str = "~/Projects/rune/crates/rune-kit/src/components/settings/appearance_panel.rs"; + +fn style() -> TextStyle { TextStyle::new(13.0, 400.0).lh(16.0) } + +/// Content, how it's cut, and a byte range that is both an inline-code span and a link. +type S = (&'static str, Elide, Option<(usize, usize)>); + +fn pill() -> Color { crate::color::hex("#e6339a").unwrap() } + +/// `content` in a `width` pt window, cut in the middle (or at its head). +fn runtime(content: &'static str, head: bool, width: f32) -> Runtime<S> { + cut_at(content, if head { Elide::Head } else { Elide::Middle }, None, width) +} + +fn cut_at(content: &'static str, elide: Elide, marked: Option<(usize, usize)>, width: f32) -> Runtime<S> { + fn view(s: &S, _: &mut Cx<S>) -> El { + let spans = s.2.map(|(a, b)| Span { mono: true, bg: Some(pill()), ..Span::new(a, b) }).into_iter().collect(); + let mut t = rich(s.0, spans).key("t").font(style()).selectable(true); + if let Some((a, b)) = s.2 { t = t.link(Link::new(a..b, "marked")).on_link(|_: &mut S, _, _| {}); } + col().w_full().child(match s.1 { Elide::End => t.truncate(), Elide::Middle => t.truncate_middle(), Elide::Head => t.truncate_head() }) + } + let mut rt = Runtime::new((content, elide, marked), view, (width, 40.0), Env::new(true, 2.0)); + rt.frame(0.0); + rt +} + +fn node<'a>(rt: &'a Runtime<S>) -> &'a Node { + rt.tree.nodes.iter().find(|n| n.key.as_deref() == Some("t")).unwrap() +} + +/// The string node "t" draws, and its cut. +fn drawn(rt: &Runtime<S>) -> (String, Option<Elision>) { + let n = node(rt); + let content = &n.text.as_ref().unwrap().content; + match n.elided { + Some(e) => ([&content[..e.head], "…", &content[e.tail..]].concat(), Some(e)), + None => (content.clone(), None), + } +} + +fn fits(rt: &Runtime<S>) -> bool { + let n = node(rt); + let w = (n.target[2] - n.target[0]) * 2.0; + n.text_layout.as_ref().and_then(crate::text::TextLayout::single).unwrap().full_width() <= w + 0.5 +} + +#[test] +fn middle_truncation_keeps_both_ends_and_refits_on_resize() { + let mut rt = runtime(PATH, false, 200.0); + let (shown, e) = drawn(&rt); + let e = e.expect("the path overflows 200 pt"); + assert!(fits(&rt), "{shown}"); + assert!(shown.starts_with("~/Projects") && shown.ends_with("panel.rs") && shown.contains('…'), "{shown}"); + let (head, tail) = (PATH[..e.head].graphemes(true).count(), PATH[e.tail..].graphemes(true).count()); + assert!(head.abs_diff(tail) <= 1, "both ends keep half: {shown}"); + let el = rt.elements().into_iter().find(|e| e.key.as_deref() == Some("t")).unwrap(); + assert_eq!(el.text.as_deref(), Some(PATH), "tools and accessibility read the whole path"); + + rt.set_viewport((320.0, 40.0), 2.0); + rt.frame(0.1); + let (wider, _) = drawn(&rt); + assert!(fits(&rt) && wider.len() > shown.len(), "a wider box keeps more: {wider}"); + + rt.set_viewport((900.0, 40.0), 2.0); + rt.frame(0.2); + assert_eq!(drawn(&rt), (PATH.to_owned(), None), "room for it all: no cut"); + + rt.set_viewport((200.0, 40.0), 2.0); + rt.frame(0.3); + assert_eq!(drawn(&rt).0, shown, "narrowing again cuts as before"); +} + +#[test] +fn head_truncation_keeps_the_end() { + let rt = runtime(PATH, true, 160.0); + let (shown, e) = drawn(&rt); + assert_eq!(e.map(|e| e.head), Some(0)); + assert!(fits(&rt) && shown.starts_with('…') && shown.ends_with("appearance_panel.rs"), "{shown}"); +} + +#[test] +fn cuts_fall_between_graphemes() { + const MIXED: &str = "👩‍👩‍👧‍👦 cafe\u{301} שלום עולם 🇯🇵 नमस्ते e\u{301}e\u{301}e\u{301} 👩‍👩‍👧‍👦 done"; + let mut rt = runtime(MIXED, false, 60.0); + let bounds: Vec<usize> = MIXED.grapheme_indices(true).map(|(i, _)| i).chain([MIXED.len()]).collect(); + let mut cuts = 0; + for w in (60..400).step_by(7) { + rt.set_viewport((w as f32, 40.0), 2.0); + rt.frame(1.0); + let (shown, e) = drawn(&rt); + let Some(e) = e else { continue }; + cuts += 1; + assert!(fits(&rt), "{w}: {shown}"); + assert!(bounds.contains(&e.head) && bounds.contains(&e.tail), "{w}: {e:?} splits a grapheme: {shown}"); + } + assert!(cuts > 10, "most widths cut: {cuts}"); +} + +#[test] +fn copying_a_cut_text_copies_all_of_it() { + let mut rt = runtime(PATH, false, 200.0); + let r = node(&rt).target; + let (y, left, right) = ((r[1] + r[3]) / 2.0, r[0] + 0.5, r[2] - 0.5); + + // A drag across the ellipsis selects what it hides too. + rt.pointer_move(left, y); + rt.pointer_down(left, y); + rt.frame(1.0 / 60.0); + rt.pointer_move(right, y); + rt.frame(2.0 / 60.0); + rt.pointer_up(right, y); + rt.frame(3.0 / 60.0); + assert_eq!(rt.selected_text().as_deref(), Some(PATH)); + + // So does Select All. + rt.pointer_move(left + 20.0, y); + rt.pointer_down(left + 20.0, y); + rt.pointer_up(left + 20.0, y); + rt.frame(1.0); + rt.key(KeyEvent { key: Key::Command('a'), mods: Mods { cmd: true, ..Mods::default() } }); + rt.frame(1.1); + assert_eq!(rt.selected_text().as_deref(), Some(PATH)); +} + +/// Instances filled with the code span's pill colour. +fn pills(rt: &Runtime<S>) -> usize { + let want = pill().premul(1.0); + rt.instances.iter().filter(|i| i.fill.iter().zip(want).all(|(a, b)| (a - b).abs() < 1e-3)).count() +} + +#[test] +fn a_cut_hides_the_spans_and_links_inside_it() { + // A link that is also an inline-code span, at the end, in the middle and at the start. + let cases = [ + ("See the docs", Elide::End, (8, 12)), + ("Open the config file in your editor today", Elide::Middle, (9, 15)), + ("docs are here for you to read", Elide::Head, (0, 4)), + ]; + for (content, elide, (a, b)) in cases { + let mut rt = cut_at(content, elide, Some((a, b)), 20.0); + let mut hidden = 0; + for w in (20..300).step_by(3) { + rt.set_viewport((w as f32, 40.0), 2.0); + rt.frame(1.0); + let (shown, e) = drawn(&rt); + let gone = e.is_some_and(|e| a >= e.head && b <= e.tail); + hidden += usize::from(gone); + let link = rt.elements().iter().any(|e| e.path.ends_with("#link-0")); + assert_eq!(link, !gone, "{w}: {shown}: the link is pressable only while it shows"); + assert_eq!(pills(&rt) > 0, !gone, "{w}: {shown}: the code pill draws only while it shows"); + } + assert!(hidden > 0, "{content}: some width hides the link"); + } +} + +#[test] +fn trimming_spaces_keeps_graphemes_whole() { + // A space that begins a grapheme (before a combining accent) or ends one (after a + // prepended mark) stays with it rather than being trimmed off beside the ellipsis. + const SPACED: &str = "ab\u{600} cd \u{301}ef gh \u{301}ij"; + let bounds: Vec<usize> = SPACED.grapheme_indices(true).map(|(i, _)| i).chain([SPACED.len()]).collect(); + for elide in [Elide::End, Elide::Middle, Elide::Head] { + let mut rt = cut_at(SPACED, elide, None, 10.0); + for w in 10..140 { + rt.set_viewport((w as f32, 40.0), 2.0); + rt.frame(1.0); + let (shown, e) = drawn(&rt); + let Some(e) = e else { continue }; + assert!(bounds.contains(&e.head) && bounds.contains(&e.tail), "{elide:?} {w}: {shown:?}"); + } + } +} + +#[test] +fn elision_maps_ranges_across_the_cut() { + // "abcdefgh" drawn "ab…gh". + let e = Elision { head: 2, tail: 6 }; + assert_eq!(e.content(0), 0); + assert_eq!(e.content(2), 2, "before the ellipsis"); + assert_eq!(e.content(5), 6, "after it: where the hidden middle ends"); + assert_eq!(e.content(7), 8); + + // Selections reaching into the cut highlight the ellipsis. + assert_eq!(e.range(1, 4), (1, 5)); + assert_eq!(e.range(3, 8), (2, 7)); + assert_eq!(e.range(6, 8), (5, 7)); + + // Links: hidden ones are empty, edges clamp, and only one showing on both sides takes "…". + let empty = |(a, b): (usize, usize)| a == b; + assert!(empty(e.mark(3, 5, true)) && empty(e.mark(2, 6, true))); + assert_eq!(e.mark(1, 4, true), (1, 2)); + assert_eq!(e.mark(4, 8, true), (5, 7)); + assert_eq!(e.mark(1, 7, true), (1, 6)); + assert_eq!((e.mark(0, 2, true), e.mark(6, 8, true)), ((0, 2), (5, 7))); + + // Spans: also hidden when wholly cut, but "…" takes the style of the text it replaces + // when that span shows beside it. + assert!(empty(e.mark(3, 5, false)) && empty(e.mark(2, 6, false))); + assert_eq!(e.mark(1, 4, false), (1, 5)); + assert_eq!(e.mark(2, 8, false), (2, 7)); + assert_eq!(e.mark(4, 8, false), (5, 7), "starting after the cut's first byte: not the ellipsis"); + assert_eq!(e.mark(1, 7, false), (1, 6)); +} + +#[test] +fn elision_cache_reuses_cut_evicts_superseded_and_bypasses_secure() { + fn view(s: &String, _: &mut Cx<String>) -> El { + col().w_full().child(crate::text(s.as_str()).key("t").font(style()).truncate_middle()) + } + let mut rt = Runtime::new(PATH.to_owned(), view, (140.0, 40.0), Env::new(true, 2.0)); + rt.frame(0.0); + let cut0 = rt.tree.nodes.iter().find(|n| n.key.as_deref() == Some("t")).unwrap().elided; + assert!(cut0.is_some()); + assert_eq!(rt.text.cached_elision_count(), 1); + let shaped_before = rt.text.shaped; + rt.invalidate(); + rt.frame(1.0 / 60.0); + assert_eq!(rt.text.shaped, shaped_before, "repeat commit reuses cached truncated cut"); + assert_eq!(rt.tree.nodes.iter().find(|n| n.key.as_deref() == Some("t")).unwrap().elided, cut0); + + // Editing the string supersedes the old shaping and drops its cached cut on end_commit. + rt.update(|s, _| s.push_str("/extra_leaf_module.rs")); + rt.frame(1.0 / 60.0); + assert_eq!(rt.text.cached_elision_count(), 1, "superseded cut is replaced rather than accumulating"); + + // Redacted (`secure`) text never enters the elision cache. + fn secure_view(s: &String, _: &mut Cx<String>) -> El { + col().w_full().child(crate::text(s.as_str()).key("t").font(style()).secure().revealed(true).truncate()) + } + let mut sec = Runtime::new(PATH.to_owned(), secure_view, (140.0, 40.0), Env::new(true, 2.0)); + sec.frame(0.0); + assert!(sec.tree.nodes.iter().find(|n| n.key.as_deref() == Some("t")).unwrap().elided.is_some()); + assert_eq!(sec.text.cached_elision_count(), 0, "redacted text bypasses elision cache"); +} diff --git a/app/vendor/rune/crates/rune/src/runtime/turn.rs b/app/vendor/rune/crates/rune/src/runtime/turn.rs new file mode 100644 index 0000000..5ab972a --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/turn.rs @@ -0,0 +1,122 @@ +//! Composed `El::rotate` affine transforms (`Turn`), turned layer openings and clip bounds. +use super::*; + +/// A 2×3 affine in device pixels, `[a, b, c, d, tx, ty]`: `(x, y)` lands at +/// `(a·x + b·y + tx, c·x + d·y + ty)`. The composed `El::rotate` layers above a node. +#[derive(Clone, Copy, Debug, PartialEq)] +pub(super) struct Turn { + pub(super) mat: [f32; 6], + pub(super) rect: [f32; 4], + pub(super) angle: f32, + pub(super) pivot: [f32; 2], + pub(super) outer_clip: [f32; 4], +} + +/// The composed turn for a node under `Inh::turn` index `inherited` turning `own` radians about +/// `pivot`: pushed onto `turns` when it turns itself. Off the paint loop's common path. +#[cold] +#[inline(never)] +pub(super) fn compose_turn( + turns: &mut Vec<Turn>, + inherited: u32, + own: Option<f32>, + (rect, pivot, outer_clip): ([f32; 4], [f32; 2], [f32; 4]), +) -> (Option<Turn>, u32) { + let above = inherited.checked_sub(1).map(|k| turns[k as usize]); + match own { + None => (above, inherited), + Some(a) => { + let own = Turn::about(a, pivot, rect, outer_clip); + let t = above.map_or(own, |t| t.after(own)); + turns.push(t); + (Some(t), turns.len() as u32) + } + } +} + +/// Open the layer a turned node draws into, upright, at `rect` (x, y, w, h in device pixels). +/// The layer takes the clips from above, so the node's own clips start fresh inside it; a +/// rectangular cut through the inherited rounded mask gets an outer scope of its own. +#[cold] +#[inline(never)] +pub(super) fn open_turned_layer(instances: &mut Vec<Instance>, layers: &mut Vec<(usize, usize, usize)>, (i, surfaces): (usize, usize), + rect: [f32; 4], (angle, pivot): (f32, [f32; 2]), + (clip, fade, fade_origin, rounded): (&mut [f32; 4], &mut [f32; 4], &mut [f32; 4], &mut Option<([f32; 4], [f32; 4])>)) +{ + if let Some((mask, _)) = *rounded && intersect(*clip, mask) != mask { + let mut marker = Instance::begin_layer(rect, *clip, Default::default()); + marker.fade = crate::render::pack_fade(*fade, *fade_origin, *clip); + layers.push((i, instances.len(), surfaces)); + instances.push(marker); + (*clip, *fade, *fade_origin) = (NO_CLIP, [0.0; 4], NO_CLIP); + } + if let Some((mask, _)) = *rounded { *clip = intersect(*clip, mask); } + let mut marker = Instance::begin_layer(rect, *clip, Default::default()).turned(angle, pivot); + marker.fade = crate::render::pack_fade(*fade, *fade_origin, *clip); + if let Some((_, radii)) = *rounded { marker.round_clip_corners(radii); } + layers.push((i, instances.len(), surfaces)); + instances.push(marker); + (*clip, *fade, *fade_origin, *rounded) = (NO_CLIP, [0.0; 4], NO_CLIP, None); +} + +/// The overlap of two `[x0, y0, x1, y1]` rects (inverted when they don't meet). +pub(crate) fn intersect(a: [f32; 4], b: [f32; 4]) -> [f32; 4] { + [a[0].max(b[0]), a[1].max(b[1]), a[2].min(b[2]), a[3].min(b[3])] +} + +pub(super) fn screen_clip_of(parent: Option<usize>, inh: &[Inh], turns: &[Turn]) -> [f32; 4] { + let Some(pi) = parent else { return NO_CLIP }; + let Some(h) = inh.get(pi) else { return NO_CLIP }; + if let Some(&t) = h.turn.checked_sub(1).and_then(|k| turns.get(k as usize)) { + let ic = if h.clip == NO_CLIP { NO_CLIP } else { t.bbox(h.clip) }; + let oc = t.outer_clip; + intersect(oc, ic) + } else { + h.clip + } +} + +impl Turn { + /// `angle` radians clockwise about `p`. + pub(super) fn about(angle: f32, p: [f32; 2], rect: [f32; 4], outer_clip: [f32; 4]) -> Turn { + let (sn, c) = angle.sin_cos(); + Turn { + mat: [c, -sn, sn, c, p[0] - c * p[0] + sn * p[1], p[1] - sn * p[0] - c * p[1]], + rect, + angle, + pivot: p, + outer_clip, + } + } + + /// `inner`, then `self`. + pub(super) fn after(self, inner: Turn) -> Turn { + let [a, b, c, d, x, y] = self.mat; + let [e, f, g, h, u, v] = inner.mat; + let ic = if inner.outer_clip == NO_CLIP { NO_CLIP } else { self.bbox(inner.outer_clip) }; + let oc = self.outer_clip; + Turn { + mat: [a * e + b * g, a * f + b * h, c * e + d * g, c * f + d * h, a * u + b * v + x, c * u + d * v + y], + outer_clip: intersect(oc, ic), + ..inner + } + } + + /// The upright bounding box of edges `r` once turned. + pub(super) fn bbox(self, r: [f32; 4]) -> [f32; 4] { + let [a, b, c, d, x, y] = self.mat; + let mut out = [f32::INFINITY, f32::INFINITY, f32::NEG_INFINITY, f32::NEG_INFINITY]; + for (px, py) in [(r[0], r[1]), (r[2], r[1]), (r[0], r[3]), (r[2], r[3])] { + let (qx, qy) = (a * px + b * py + x, c * px + d * py + y); + out = [out[0].min(qx), out[1].min(qy), out[2].max(qx), out[3].max(qy)]; + } + out + } + + /// Unturns a screen-space point `q` back into the layer's upright device pixels. + pub(super) fn unturn(self, [qx, qy]: [f32; 2]) -> [f32; 2] { + let [a, b, c, d, tx, ty] = self.mat; + let (dx, dy) = (qx - tx, qy - ty); + [a * dx + c * dy, b * dx + d * dy] + } +} diff --git a/app/vendor/rune/crates/rune/src/runtime/types.rs b/app/vendor/rune/crates/rune/src/runtime/types.rs new file mode 100644 index 0000000..fb444df --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/types.rs @@ -0,0 +1,769 @@ +//! Retained node, inherited paint state, scroll, growth stack and frame stats types. +use super::*; + +/// A node's place under a growth stack's row. The row's height carries vertical motion there. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub(super) enum RowLayout { + /// Not inside a growth row. + Free, + /// Inside one: layout snaps. + Snaps, + /// Inside one under `El::animate_layout`: x and width spring, y and height snap. + Horizontal, +} + +/// Rarely set per-node metadata, motion overrides, accessibility, live bindings and container +/// specs, kept behind `Cold<NodeCold>` so common nodes stay under four hundred bytes. +#[derive(Clone)] +pub(crate) struct NodeCold { + pub trace_name: Option<&'static str>, + pub trace_namespace: Option<(&'static str, &'static str)>, + pub label: Option<std::borrow::Cow<'static, str>>, + pub(super) live: Vec<crate::live::Bound>, + /// The run a cell measures and draws from (see `El::advance_in`). + pub(super) run_layout: Option<Rc<crate::text::RunLayout>>, + pub(super) live_text_seen: Option<u128>, + pub(super) looping: Option<Box<rune_motion::LoopSpec>>, + pub(super) opacity_motion: Option<Box<rune_motion::Anim>>, + pub(super) lead: Option<(Spring, Spring)>, + pub(super) transition: Option<Box<Transition>>, + /// `El::matched` id, with the element's own (not inherited) layout spring. + pub(super) matched: Option<(Rc<str>, Option<Spring>)>, + pub(super) above: Option<crate::el::Anchor>, + pub(crate) scroll: Option<ScrollSpec>, + pub(super) scroll_axes: crate::el::ScrollAxes, + pub(super) scroll_edges: crate::el::ScrollEdges, + /// `El::wheel_scrolls`: the viewport a wheel over this node scrolls, in place of what it + /// starts on. + pub(super) wheel_scrolls: Option<Box<str>>, + /// `El::sticky_top`, `El::sticky_bottom` and `El::stuck_shadow`. + pub(super) sticky: Option<Box<crate::el::Sticky>>, + pub(super) growth: Option<Box<GrowthSpec>>, + pub(super) glide: Option<crate::growth::FoldGlide>, + pub(crate) a11y: crate::el::A11y, + /// The image ratio this picture's layout took, when it sizes one side from its pixels. + pub(super) pixel_aspect: Option<f32>, + /// `El::aspect_fit`: the ratio and the element's own style, which the fitted size replaces. + pub(super) aspect_fit: Option<Box<(f32, CompactStyle)>>, + pub(super) material: Option<crate::SystemMaterial>, + /// `El::help`. + pub(crate) help: Option<String>, + /// `El::help_when_truncated`. + pub(crate) help_cut: bool, + /// `El::help_side`. + pub(super) help_side: Option<crate::Side>, + /// `El::help_open`. + pub(super) help_open: bool, + #[cfg(debug_assertions)] + pub(super) scroll_source: Option<&'static std::panic::Location<'static>>, +} + +impl crate::cold::Empty for NodeCold { + const EMPTY: &'static Self = &NodeCold { + trace_name: None, + trace_namespace: None, + label: None, + live: Vec::new(), + run_layout: None, + live_text_seen: None, + looping: None, + opacity_motion: None, + lead: None, + transition: None, + matched: None, + above: None, + scroll: None, + scroll_axes: crate::el::ScrollAxes::Y, + scroll_edges: crate::el::ScrollEdges { fade: 0.0, fade_style: crate::el::FadeStyle::SMOOTH, margin: 0.0, anchor: false }, + wheel_scrolls: None, + sticky: None, + growth: None, + glide: None, + a11y: crate::el::A11y::EMPTY, + pixel_aspect: None, + aspect_fit: None, + material: None, + help: None, + help_cut: false, + help_side: None, + help_open: false, + #[cfg(debug_assertions)] + scroll_source: None, + }; +} + +#[derive(Clone)] +pub(crate) struct Node { + pub id: NodeId, + pub path: String, + pub key: Option<String>, + pub role: &'static str, + pub parent: Option<usize>, + pub(super) taffy: SlotId, + pub text: Option<crate::cold::SharedBox<TextSpec>>, + pub text_layout: Option<crate::text::TextLayout>, + /// Where `text_layout` cut the text for `El::truncate` and its kin. + pub(crate) elided: Option<Elision>, + pub(crate) input: Option<Box<InputSpec>>, + pub(crate) focus: crate::cold::Cold<crate::el::FocusSpec>, + pub(crate) handlers: crate::cold::Cold<crate::el::Handlers>, + pub(super) cold: crate::cold::Cold<NodeCold>, + pub vis: Visual, + pub(crate) vis_flags: crate::el::VisualFlags, + /// The hover curves of the nearest `El::hover_motion_within` at or above it (or above its + /// anchor). Kept here, not in `vis`, so inheriting them doesn't copy every node's visuals. + pub(super) hover_within: Option<Rc<(Anim, Anim)>>, + /// Layout target in root space: x0, y0, x1, y1 in points. + pub target: [f32; 4], + /// Layout target in parent space. + pub local: MRect, + /// Padding plus border (left, top, right, bottom): text draws inside it. + pub(super) inset: [f32; 4], + pub(super) motion: Spring, + /// `El::scale`: a factor on the element's own scale, springing on `P_SCALE`. + pub(super) static_scale: f32, + /// `El::time_scale`: this element's own factor; the scene multiplies ancestors' in. + pub(super) time_scale: f32, + /// Where it sits relative to a growth row, which carries its contents' motion. + pub(super) in_row: RowLayout, + pub(super) width_leads: bool, + /// Inside an `El::instant_changes` element, or one itself. + pub(super) instant_changes: bool, + pub(super) streaming: bool, + pub(super) whole: bool, + /// Inside an `El::inert` subtree (this element or an ancestor). + pub(crate) inert: bool, + /// The direction it lays out in (`El::dir`, its own or inherited): right to left, its + /// children's x mirror inside it and its inset's sides swap. + pub(crate) flow: crate::el::Flow, + /// Whether an explicit direction governs this subtree's paragraphs. + pub(crate) directed: bool, + /// Where it sits in its parent (`El::unmirrored`). + pub(crate) pin: crate::el::Pin, + /// `P_SCALE` has a track: paint reads the sprung factor. + pub(super) scale_track: bool, + /// `P_GROUP_REST` fades a dropped `El::group_opacity` to full: paint reads it until it lands. + pub(super) group_fade: bool, + pub(super) virtual_mount: bool, + /// `El::selection_group`. + pub(super) selection_group: bool, + pub(super) window_drag: crate::el::WindowDrag, + pub(super) ime_cursor: bool, + /// `El::ime_option_as_alt`. + pub(super) ime_option_as_alt: bool, + /// Placeholder left in `self.nodes` after `try_reuse_memo` moves a node into the new pass. + pub(super) moved_stub: bool, + /// A new one each time it's built from its element; a node a region keeps keeps it + /// (`paint_keep`). + pub(super) epoch: u32, +} + +impl std::ops::Deref for Node { + type Target = NodeCold; + #[inline(always)] + fn deref(&self) -> &NodeCold { + &self.cold + } +} + +impl Node { + #[inline] + pub(super) fn cold_mut(&mut self) -> &mut NodeCold { + &mut self.cold + } + + #[inline] + pub(super) fn clear_run_layout(&mut self) { + if self.cold.get().is_some_and(|c| c.run_layout.is_some()) { + self.cold_mut().run_layout = None; + } + } + + /// Zero-allocation placeholder left in `self.nodes` when a committing pass moves a + /// `same_path` memo-reused node into the new `nodes` slice. Retains the last commit's + /// identity, parent index, geometry and track flags that `apply` and retry restoration read. + pub(super) fn moved_stub(old: &Self) -> Self { + Node { + id: old.id, + path: String::new(), + key: None, + role: "group", + parent: old.parent, + taffy: old.taffy, + text: None, + text_layout: None, + elided: None, + input: None, + focus: Default::default(), + handlers: Default::default(), + cold: Default::default(), + vis: Visual::default(), + vis_flags: crate::el::VisualFlags::default(), + hover_within: None, + target: old.target, + local: old.local, + inset: old.inset, + motion: old.motion, + static_scale: 1.0, + time_scale: 1.0, + in_row: RowLayout::Free, + width_leads: false, + instant_changes: false, + streaming: false, + whole: false, + inert: false, + flow: old.flow, + directed: old.directed, + pin: old.pin, + scale_track: old.scale_track, + group_fade: old.group_fade, + virtual_mount: false, + selection_group: false, + window_drag: crate::el::WindowDrag::None, + ime_cursor: false, + ime_option_as_alt: false, + moved_stub: true, + epoch: 0, + } + } + + /// Its hover track's curves: its own `El::hover_motion`, else the inherited + /// `El::hover_motion_within` pair. + #[inline] + pub(super) fn hover_motion(&self) -> Option<(Anim, Anim)> { + self.vis.hover_motion.as_deref().or(self.hover_within.as_deref()).copied() + } + + #[inline] + pub(crate) fn is_moved_stub(&self) -> bool { + self.moved_stub + } + + /// Whether its text is a secret: marked secure, redacted, or a secure field. + pub(crate) fn is_secure(&self) -> bool { + self.cold.get().is_some_and(|c| c.a11y.secure) + || self.text.as_ref().is_some_and(|t| t.redacted) + || self.input.as_ref().is_some_and(|i| i.edit.is_secure()) + } + /// Whether a press, hover or drag can go to this node itself. + pub(super) fn has_primary_handler(&self) -> bool { + self.handlers.get().is_some_and(crate::el::Handlers::has_primary) + } + /// Whether `selector` names this node, as `Cx::layout` reads it: its key, its full path, or + /// a key path such as `msg-42/body` (see `flight::selects`). + pub(crate) fn named(&self, selector: &str) -> bool { + self.path == selector || crate::flight::selects(selector, &self.path, self.key.as_deref()) + } +} + +/// What kept a frame animating, as bits in traces (`quality.why`). +pub(crate) struct AnimSource; + +impl AnimSource { + pub const TRACKS: u16 = 1; + pub const GROWTH: u16 = 2; + pub const SCROLL: u16 = 4; + pub const REVEAL: u16 = 8; + pub const LOOP: u16 = 16; + pub const SCALE_SETTLE: u16 = 32; + pub const VIDEO: u16 = 64; + pub const TEXT_FLIGHT: u16 = 128; + pub const LIVE: u16 = 256; + pub const VIRTUAL_FILL: u16 = 512; + pub const TEXT_FILL: u16 = 1024; + pub const ICON_ANIM: u16 = 2048; + pub const NAMES: [&'static str; 12] = + ["tracks", "growth", "scroll", "reveal", "loop", "scale-settle", "video", "text-flight", "live", "virtual-fill", "text-fill", "icon-anim"]; + + pub fn names(bits: u16) -> Vec<&'static str> { + Self::NAMES.iter().enumerate().filter(|(i, _)| bits & (1 << i) != 0).map(|(_, n)| *n).collect() + } +} + +#[derive(Clone, Copy)] +pub(super) struct Inh { + pub(super) opacity: f32, + pub(super) paint_opacity: f32, + /// `El::stuck_fade`: how much of a stuck header's first child (its title) shows. + pub(super) first_fade: f32, + pub(super) clip: [f32; 4], + pub(super) fade: [f32; 4], + pub(super) fade_origin: [f32; 4], + /// Paint clips are consumed by isolation; logical clips remain for hit tests/inspection. + pub(super) paint_clip: [f32; 4], + pub(super) paint_fade: [f32; 4], + pub(super) paint_fade_origin: [f32; 4], + pub(super) rounded: Option<([f32; 4], [f32; 4])>, + /// Ancestors' scales, composed: a point `x` (points, with `dx`/`dy` applied) draws at + /// `anchor_to + (x - anchor) * scale`. The anchors differ when scales nest. + pub(super) scale: f32, + pub(super) anchor: [f32; 2], + pub(super) anchor_to: [f32; 2], + pub(super) blur: f32, + /// Vertical offset in points from scroll viewports and growth rows above. + pub(super) dy: f32, + /// Horizontal offset in points: a matched flight centring its scaled children. + pub(super) dx: f32, + /// The part of `dx`/`dy` from flights' covers above. A flight nested in another travels its + /// own root-space path, so it drops this. + pub(super) cover: [f32; 2], + /// The clip, fade and fade origin outside the nearest flight above, for a flight nested in it. + pub(super) outer: Option<[[f32; 4]; 3]>, + pub(super) mark: u32, + /// The nearest hover group's hover amount (0-1), for `group_*` styles. + pub(super) group: f32, + /// The nearest `El::press_color` above or here, and how far a press on it is held (0-1). + pub(super) pressed: f32, + pub(super) press_to: Option<Color>, + /// `opacity` with each `El::group_opacity` at its hovered level: a press where the pointer + /// hovers the group finds what the hover shows, before a frame has drawn it. + pub(super) hit_opacity: f32, + /// The nearest hover group's rect in points (x0, y0, x1, y1): where a pointer hovers it. + pub(super) group_rect: [f32; 4], + /// How `scale` is changing, which decides how text rasterizes under it. + pub(super) scale_motion: ScaleMotion, + /// `(scale, anchor, anchor_to)` of the ancestors whose scales hold still from the root down, + /// as an app-wide zoom does, stopping at the first that moves. A flight keeps this part. + pub(super) still: (f32, [f32; 2], [f32; 2]), + /// Inside an active `El::cache` scope: do not cull children against the window viewport. + pub(super) in_cache: bool, + /// Inside an elided or off-screen `El::cache` scope: skip primitive emission. + pub(super) skip_paint: bool, + /// Inside an `El::anchored` overlay whose anchor could not be resolved: suppress paint and hits. + pub(super) anchor_hidden: bool, + /// Ancestors' `El::rotate` layers, composed, as an index into `turn_scratch` plus one + /// (0: none): where this subtree's device pixels land. An index keeps `Inh` small. + pub(super) turn: u32, + pub(super) snap: pixel_snap::Inherit, +} + +/// How a subtree's scale is changing. Text under a still scale rasterizes at its scaled size. +/// Under a live zoom gesture it steps through logarithmic $2^{1/4}$ buckets and lands on the +/// exact resting scale once still; under a short spring it samples its rest-size glyphs. +#[derive(Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord)] +pub(super) enum ScaleMotion { + #[default] + Still, + /// Bound to a live scale that is actively changing: rasterize at $2^{1/4}$ octave buckets. + Live, + Moving, +} + +impl ScaleMotion { + /// The scale text under `sc` rasterizes at. It draws at `sc`, filtered, when they differ. + /// Moving text rasterizes at `rest`, the scale of its nearest still ancestor (an app's zoom, + /// say), so text that moves inside a zoomed window stays as crisp as at rest and doesn't + /// sharpen when the motion ends. + pub(super) fn raster(self, sc: f32, rest: f32) -> f32 { + let k = match self { + ScaleMotion::Still => sc, + ScaleMotion::Live => 2.0f32.powf((sc.max(1e-4).log2() * 4.0).round() * 0.25), + ScaleMotion::Moving => rest, + }; + // A tiny or huge raster isn't worth its atlas space; sample the rest size instead. + if (1.0 / 16.0..=4.0).contains(&k) { k } else { 1.0 } + } +} + +impl Default for Inh { + fn default() -> Self { + Inh { opacity: 1.0, paint_opacity: 1.0, first_fade: 1.0, clip: NO_CLIP, fade: [0.0; 4], fade_origin: NO_CLIP, + paint_clip: NO_CLIP, paint_fade: [0.0; 4], paint_fade_origin: NO_CLIP, rounded: None, + scale: 1.0, anchor: [0.0; 2], anchor_to: [0.0; 2], blur: 0.0, dy: 0.0, dx: 0.0, cover: [0.0; 2], outer: None, mark: 0, group: 0.0, pressed: 0.0, press_to: None, + hit_opacity: 1.0, group_rect: [f32::NEG_INFINITY, f32::NEG_INFINITY, f32::INFINITY, f32::INFINITY], + scale_motion: ScaleMotion::Still, still: (1.0, [0.0; 2], [0.0; 2]), in_cache: false, skip_paint: false, anchor_hidden: false, turn: 0, + snap: Default::default() } + } +} + +/// Where a glide goes. +#[derive(Clone, Copy, Debug, PartialEq)] +pub(super) enum GlideTo { + /// The content's bottom, as it moves (`Tx::scroll_to_bottom`). + Bottom, + /// An offset an app or a reveal asked for (`Tx::scroll_to`), while the content reaches it. + Offset(f64), + /// The end a growth stack shrinks to under a reader who scrolled up (`ease_to_shrunk_end`), + /// retargeted as its rows move. + ShrunkEnd(f64), +} + +impl GlideTo { + /// The offset it heads for, `None` for the bottom. + pub(super) fn offset(self) -> Option<f64> { + match self { + GlideTo::Bottom => None, + GlideTo::Offset(to) | GlideTo::ShrunkEnd(to) => Some(to), + } + } +} + +#[derive(Clone, Debug, Default)] +pub(crate) struct ScrollState { + pub(crate) offset: f64, + /// What moves it, with the hand's latches for this frame (`runtime/scroll/mode.rs`). + pub(super) mode: ScrollMode, + pub(crate) max: f64, + /// At-bottom state last sent to `El::on_at_bottom`. + pub(super) at_bottom: Option<bool>, + /// State last sent to `El::on_far_from_bottom`. + pub(super) far_from_bottom: Option<bool>, + /// Whether the last frame drew the content's bottom on the viewport's (see `stuck_offset`). + pub(super) held: bool, + /// The horizontal offset the last frame drew the content at, in points. + pub(crate) drawn_x: f32, + /// Where it drew the vertical offset, and the pinned end's hold (`scroll_drawn`). + pub(crate) drawn: PixelHold, + /// Room freed under a pinned growth stack, held under its last row (see `step_slack`). + pub(super) slack: scroll_bottom::Slack, + /// The horizontal axis of `El::scroll_x` and `El::scroll_xy`; all zero on a vertical one. + pub(crate) x: AxisScroll, + /// What `El::on_scroll_offset` has been told, and which handler heard it + /// (`runtime/scroll/watch.rs`). + pub(super) watch: super::scroll_watch::Watch, + /// The spring `Tx::scroll_to_with` gave the running glide, on both axes; `GLIDE` when none. + pub(super) spring: Option<rune_motion::Spring>, + /// An app's instant scroll (`Tx::scroll_to_instant` and the like) landed less than + /// `scroll_nudge::NUDGE_HOLD` ago, so content moved under a still pointer and hover waits + /// for it to pass while the app steps its own glide frame by frame + /// (`runtime/input/hover.rs`). + pub(super) nudge: scroll_nudge::Nudge, +} + +/// What moves a viewport's horizontal offset, one motion at a time. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub(super) enum XMotion { + /// Where a hand, an app or a motion left it. + #[default] + Rest, + /// Coasting from a fling or a touch at `v` points a second, decaying. + Momentum(f32), + /// Gliding on a spring (`ScrollState::glide_spring`) at `v` points a second to `aim` + /// (`Tx::scroll_to`). + Glide { v: f32, aim: f64 }, + /// Easing to where a notched mouse wheel sent it (`runtime/scroll/wheel.rs`). + Wheel(scroll_wheel::WheelCurve), +} + +/// A scroll viewport's horizontal offset, motion and limit (points). +#[derive(Clone, Copy, Debug, Default)] +pub(crate) struct AxisScroll { + pub(crate) offset: f64, + pub(super) motion: XMotion, + pub(crate) max: f64, + /// The viewport's flow (`El::dir`): right to left, its content starts at its right edge and + /// `offset` counts how far it moved right, uncovering what is to the left. + pub(super) flow: crate::el::Flow, +} + +impl AxisScroll { + /// How far left the content draws, in points: `offset`, or less it in a right-to-left + /// viewport. + pub(super) fn shift(&self) -> f64 { + match self.flow { crate::el::Flow::Ltr => self.offset, crate::el::Flow::Rtl => -self.offset } + } + + /// `delta` points of physical movement (positive moving content right) as a change of + /// `offset`. + pub(crate) fn toward(&self, delta: f64) -> f64 { + match self.flow { crate::el::Flow::Ltr => -delta, crate::el::Flow::Rtl => delta } + } + + /// Its momentum (points a second), 0 unless coasting. + pub(super) fn coast(&self) -> f32 { + match self.motion { XMotion::Momentum(v) => v, _ => 0.0 } + } + + /// A glide or a wheel's ease moves it on its own. + pub(super) fn carried(&self) -> bool { + matches!(self.motion, XMotion::Glide { .. } | XMotion::Wheel(_)) + } + + /// Coasting at `v` from here; at 0 a coast stops, and a glide or a wheel's ease runs on. + pub(super) fn set_coast(&mut self, v: f32) { + if v != 0.0 { self.motion = XMotion::Momentum(v); } else if matches!(self.motion, XMotion::Momentum(_)) { self.motion = XMotion::Rest; } + } +} + +#[derive(Clone, Debug, Default)] +pub(super) struct Stack { + /// Row ids in presented order, including rows still closing after removal. + pub(super) order: Vec<NodeId>, + /// Removed rows: when their space starts closing. + pub(super) closing: HashMap<NodeId, f64>, + /// Last known target top (container-relative) per row, for rows that left. + pub(super) tops: HashMap<NodeId, f32>, + pub(super) pad_top: f32, + pub(super) pad_bottom: f32, + pub(super) gap: f32, + pub(super) width: f32, + /// A width change the rows still wait out (heights it defers go in `pending_heights`). + pub(super) width_hold: WidthHold, + pub(super) pending_heights: HashMap<NodeId, f32>, + /// The window size at the last commit. + pub(super) window: (f32, f32), + /// The list viewport in the last layout, apart from the window (e.g. above a dock). + pub(super) viewport_height: f32, + pub(super) handoff: row_reorder::handoff::Handoff, + /// How far its rows grew (positive steps only) this frame. + pub(super) grown: f32, + /// Whether any row in the stack still has height left to grow. + pub(crate) growing: bool, + /// Whether any row in the stack is still animating. + pub(crate) moving: bool, + pub(super) reorder: row_reorder::Reorder, + pub(super) seams: Vec<row_reorder::joined::Seam>, + pub(super) slides: content_slide::ContentSlides, + /// Fold rows opening or shutting together as one block. + pub(super) runs: Vec<growth_runs::GrowthRun>, +} + +/// A growth stack whose width changed: its rows measure at the new width at once, but their +/// new heights wait until the width is stable, and a streaming row shrinks only a while after. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub(super) enum WidthHold { + #[default] + Off, + /// Heights wait until `until`; a streaming row may shrink from `shrink_from`. + Rewrap { until: f64, shrink_from: f64 }, +} + +impl WidthHold { + /// Seconds new heights wait after a width change. + const HOLD: f64 = 0.12; + /// Seconds a streaming row keeps its height after a width change before it may shrink. + const SHRINK: f64 = 0.4; + + /// The width changed at `now`. + pub(super) fn rewrap(now: f64) -> WidthHold { + WidthHold::Rewrap { until: now + Self::HOLD, shrink_from: now + Self::SHRINK } + } + + /// Whether a height set at `at` waits for the width to settle. + pub(super) fn defers(self, at: f64) -> bool { + matches!(self, WidthHold::Rewrap { until, .. } if at < until) + } + + /// Whether a streaming row may shrink at `now`. + pub(super) fn may_shrink(self, now: f64) -> bool { + !matches!(self, WidthHold::Rewrap { shrink_from, .. } if now < shrink_from) + } +} + +/// What a press on a window drag region asks the shell to do, synchronously in that press. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum TitlebarAction { + /// Move the window with the pointer (the system tracks the drag). + Drag, + /// The titlebar double-click action (zoom, minimise or nothing, per system setting). + DoubleClick, +} + +#[derive(Clone, Copy, Debug, Default)] +pub struct FrameStats { + pub commits: u64, + pub layout_nodes: usize, + pub glyphs: usize, + pub shaped: u32, +} + +/// Retained node tree, id/key lookup tables and per-commit node capability flags. +/// Ordered hot-first under `#[repr(C)]` so `nodes`, per-commit capability flags and `node_index` +/// sit at offset 0 (landing inside `RuntimeCore`'s 128-byte `disp8` window). +#[repr(C)] +pub(crate) struct TreeState { + pub(crate) nodes: Vec<Node>, + /// Some element is `El::sticky_top` or `El::sticky_bottom` (see `runtime/scroll/sticky.rs`). + pub(in crate::runtime) has_sticky: bool, + pub(in crate::runtime) has_dissolve: bool, + /// Some element is `El::raise`d: paint order isn't tree order. + pub(in crate::runtime) has_raise: bool, + /// Some element sets `El::paint_order`: its siblings paint out of tree order. + pub(in crate::runtime) has_paint_order: bool, + pub(in crate::runtime) has_cache: bool, + /// Some picture sizes a side from its image's ratio (`pixel_aspect`). + pub(in crate::runtime) has_pixel_aspect: bool, + pub(in crate::runtime) has_drawn_layout: bool, + pub(in crate::runtime) has_key_up: bool, + pub(in crate::runtime) node_index: NodeIndex, + /// The node ids the last build indexed its scratch by. + pub(in crate::runtime) built_ids: Vec<NodeId>, + /// The last commit's node buffer, emptied, for the next flatten to fill: an app of a few + /// thousand elements otherwise maps and faults in megabytes every commit. + pub(in crate::runtime) spare_nodes: Vec<Node>, + pub(in crate::runtime) next_id: u64, + /// The node index the app's view returned when the playground is attached. + app_root: usize, + pub(in crate::runtime) path_ids: HashMap<String, NodeId>, + /// Pictures whose image changed shape since the last commit, which lays them out at once. + pub(in crate::runtime) aspect_snap: Vec<NodeId>, + /// `inh_scratch` and `row_dy` index `nodes`: no commit since the last build. + pub(in crate::runtime) built: bool, + /// Whether this runtime has an attached playground (`hooks.playground.is_some()`). + pub(crate) has_playground: bool, + pub(in crate::runtime) exit_mask: exit_mask::Mask, + key_index: key_index::KeyIndex, + /// Packed explicit piecewise-linear scroll-fade stops (`ScrollFade::stops`) for `Globals::flags[2..4]`. + pub(in crate::runtime) fade_stops: [f32; 2], +} + +impl TreeState { + // Single-caller constructor for `RuntimeCore::new`; inlined so it stays in its caller's + // codegen unit instead of shifting partitioning and dropping inlining in the paint walk. + #[inline] + pub(in crate::runtime) fn new() -> Self { + Self { + nodes: Vec::new(), + has_sticky: false, + has_dissolve: false, + has_raise: false, + has_paint_order: false, + has_cache: false, + has_pixel_aspect: false, + has_drawn_layout: false, + has_key_up: false, + built: false, + has_playground: false, + node_index: NodeIndex::default(), + path_ids: HashMap::default(), + spare_nodes: Vec::new(), + built_ids: Vec::new(), + aspect_snap: Vec::new(), + next_id: 1, + app_root: 0, + exit_mask: Default::default(), + key_index: Default::default(), + fade_stops: [0.0; 2], + } + } + + /// Whether any node in the tree is `El::sticky_top` or `El::sticky_bottom`. + #[inline] + pub(crate) fn has_sticky(&self) -> bool { + self.has_sticky + } + + #[inline] + pub(super) fn has_drawn_layout(&self) -> bool { + self.has_drawn_layout + } + + #[inline] + pub(super) fn is_built(&self) -> bool { + self.built + } + + /// Marks this tree as hosting a live playground so [`Self::app_root`] tracks the story root. + #[inline] + pub(super) fn attach_playground(&mut self) { + self.has_playground = true; + } + + /// The node the app's view returned: the first, or with the playground attached, the one + /// above its bar or on its stage. Root handlers (window focus, paste, file drops) are there. + #[inline] + pub(crate) fn app_root(&self) -> usize { + if self.has_playground { self.app_root } else { self.view_root() } + } + + /// The node the view returned: the first, or the first inside the frame that holds the + /// Windows caption buttons over it (`titlebar::frame`). + #[inline] + fn view_root(&self) -> usize { + usize::from(self.nodes.first().is_some_and(|n| n.key.as_deref() == Some(crate::titlebar::FRAME_KEY))) + } + + pub(super) fn find_app_root(&mut self) { + let view_root = self.view_root(); + if !self.has_playground { self.app_root = view_root; return; } + // A scrolling stage holds the root in a margin. + let margin = |k: Option<&str>| k == Some("playground-margin"); + let wraps = |k: &str| k == "playground-closed" || margin(Some(k)) || crate::playground::is_stage(k); + let nodes = &self.nodes; + self.app_root = nodes.iter().position(|n| !margin(n.key.as_deref()) && n.parent.is_some_and(|p| nodes[p].key.as_deref().is_some_and(wraps))).unwrap_or(view_root); + } + + /// The kept key index, when `nodes` are the current nodes as of `commit`. + #[inline] + pub(super) fn key_index_for(&self, nodes: &[Node], commit: u64) -> Option<&key_index::KeyIndex> { + self.key_index.get(nodes, commit) + } + + /// Prepares the key index for `self.nodes` as of `commit` when `lookups` warrants it. + #[inline] + pub(super) fn prepare_key_index(&mut self, commit: u64, lookups: usize) { + self.key_index.prepare(&self.nodes, commit, lookups); + } + + /// `self.nodes` changed without a commit: kept per-node answers no longer hold. + #[inline] + pub(super) fn nodes_replaced(&mut self) { + self.key_index.forget(); + self.exit_mask.forget(); + } + + #[inline] + pub(super) fn index_of_id(&self, id: NodeId) -> Option<usize> { + self.node_index.get(&id).copied() + } + + #[inline] + pub(super) fn node_by_id(&self, id: NodeId) -> Option<&Node> { + self.nodes.get(*self.node_index.get(&id)?) + } + + #[inline] + pub(super) fn id_of_path(&self, path: &str) -> Option<NodeId> { + self.path_ids.get(path).copied() + } + + /// Current node index for `path`, verified against `self.nodes` so stale ids return `None`. + #[inline] + pub(super) fn index_of_path(&self, path: &str) -> Option<usize> { + self.path_ids.get(path).and_then(|id| self.node_index.get(id)).copied().filter(|&i| self.nodes.get(i).is_some_and(|n| n.path == path)) + } + + /// Whether node `i` is `ancestor` or a descendant of `ancestor`. + #[inline] + pub(super) fn is_descendant(&self, i: usize, ancestor: usize) -> bool { + std::iter::successors(Some(i), |&p| self.nodes[p].parent).any(|p| p == ancestor) + } + + /// Whether node `i` or an ancestor has a key `is` takes. + #[inline] + pub(super) fn under(&self, i: usize, is: impl Fn(&str) -> bool) -> bool { + std::iter::successors(Some(i), |&j| self.nodes[j].parent).any(|j| self.nodes[j].key.as_deref().is_some_and(&is)) + } + + /// The path of the element keyed `key`. + #[inline] + pub(super) fn key_path(&self, key: &str) -> Option<String> { + self.nodes.iter().find(|n| n.key.as_deref() == Some(key)).map(|n| n.path.clone()) + } + + #[inline] + pub(super) fn index_of_key(&self, key: &str) -> Option<usize> { + self.nodes.iter().position(|n| n.key.as_deref() == Some(key)) + } + + #[inline] + pub(super) fn selects_index(&self, selector: &str) -> Option<usize> { + self.nodes.iter().position(|n| crate::flight::selects(selector, &n.path, n.key.as_deref())) + } + + /// Index of the last node inside `root`'s contiguous pre-order subtree (`root` if leaf). + #[inline] + pub(super) fn subtree_end(&self, root: usize) -> usize { + (root + 1..self.nodes.len()).take_while(|&j| self.is_descendant(j, root)).last().unwrap_or(root) + } + + /// Direct child of `parent` before `end` whose path equals `path`. + #[inline] + pub(super) fn direct_child_by_path(&self, parent: usize, end: usize, path: &str) -> Option<usize> { + (parent + 1..end).find(|&j| self.nodes[j].parent == Some(parent) && self.nodes[j].path == path) + } +} + +#[cfg(test)] +#[path = "width_hold_tests.rs"] +mod width_hold_tests; diff --git a/app/vendor/rune/crates/rune/src/runtime/video_tests.rs b/app/vendor/rune/crates/rune/src/runtime/video_tests.rs new file mode 100644 index 0000000..cb66663 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/video_tests.rs @@ -0,0 +1,319 @@ +use crate::native_surface::Format; +use crate::{PlayerState, Video}; +#[cfg(target_os = "macos")] +use crate::Player; +#[cfg(target_os = "macos")] +use std::sync::Arc; + +#[cfg(target_os = "macos")] +fn fixture() -> std::path::PathBuf { + std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/rgbw.mp4") +} + +#[cfg(target_os = "macos")] +fn sound(name: &str) -> std::path::PathBuf { + std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures").join(name) +} + +fn view(v: &Video, _: &mut crate::Cx<Video>) -> crate::El { + crate::el().key("clip").w(32.0).h(18.0).video(v, crate::SurfaceFit::Fit) +} + +/// The clip at the top of a list that scrolls it out of sight. +fn scrolled(v: &Video, _: &mut crate::Cx<Video>) -> crate::El { + crate::col().key("list").w(32.0).h(18.0).scroll(crate::ScrollSpec { stick_bottom: false }).child( + crate::col().w_full() + .child(crate::el().key("clip").w(32.0).h(18.0).video(v, crate::SurfaceFit::Fit)) + .child(crate::el().w_full().h(200.0)), + ) +} + +#[test] +fn failures_draw_a_placeholder_and_stop_drawing() { + let v = Video::file("/nonexistent/clip.mp4"); + let mut rt = crate::Runtime::new(v.clone(), view, (32.0, 18.0), crate::Env::new(true, 2.0)); + rt.frame(0.0); + let PlayerState::Failed(message) = v.state() else { panic!("{:?}", v.state()) }; + #[cfg(any(target_os = "macos", target_os = "windows"))] + assert!(message.contains("no such file"), "{message}"); + #[cfg(not(any(target_os = "macos", target_os = "windows")))] + assert_eq!(message, "video playback isn't supported on this platform yet"); + let frame = v.surface().latest().expect("placeholder frame"); + assert_eq!((frame.size, frame.format), ([32, 18], Format::Bgra)); + rt.frame(0.1); + assert!(!rt.frame(0.1), "a failed video requests no frames"); +} + +#[test] +fn a_failed_clip_scrolling_across_the_clip_edge_commits_nothing() { + let v = Video::file("/nonexistent/clip.mp4"); + let mut rt = crate::Runtime::new(v.clone(), scrolled, (32.0, 18.0), crate::Env::new(true, 2.0)); + rt.frame(0.0); + rt.frame(0.1); + assert!(matches!(v.state(), PlayerState::Failed(_))); + let commits = rt.stats.commits; + for dy in [-40.0, 40.0, -40.0, 40.0] { + let shown = rt.surfaces.len(); + rt.wheel(10.0, 10.0, dy); + rt.frame(0.1); + assert_ne!(rt.surfaces.len(), shown, "crossed the edge ({dy})"); + } + assert_eq!(rt.stats.commits, commits, "scrolling across the edge commits nothing"); +} + +#[cfg(target_os = "macos")] +mod headless { + use super::*; + use crate::render::{Gpu, OFFSCREEN_FORMAT, Offscreen, Renderer}; + + fn render(gpu: &Gpu, rt: &mut crate::Runtime<Video>) -> Vec<u8> { + let mut renderer = Renderer::new(&gpu.device, OFFSCREEN_FORMAT); + renderer.prepare(&gpu.device, &gpu.queue, &mut rt.text.atlas, &rt.instances, (64, 36)); + renderer.prepare_surfaces(&gpu.device, &gpu.queue, &rt.surfaces, (64, 36)); + let target = Offscreen::new(&gpu.device, 64, 36); + let mut encoder = gpu.device.create_command_encoder(&Default::default()); + renderer.draw(&mut encoder, &target.view, [0.0; 4]); + target.copy(&mut encoder); + renderer.submit(&gpu.queue, encoder); + target.read(&gpu.device) + } + + fn centre(p: &[u8]) -> [u8; 3] { + let i = (18 * 64 + 32) * 4; + [p[i], p[i + 1], p[i + 2]] + } + + fn near(got: [u8; 3], want: [u8; 3], what: &str) { + assert!(got.iter().zip(want).all(|(g, w)| g.abs_diff(w) <= 24), "{what}: got {got:?}, want ~{want:?}"); + } + + /// The fixture is four 0.25 s frames: red, green, blue, white. + #[test] + fn headless_playback_decodes_the_frame_at_virtual_time() { + let gpu = Gpu::new(Gpu::instance(), None); + let v = Video::file(fixture()); + let mut rt = crate::Runtime::new(v.clone(), view, (32.0, 18.0), crate::Env::new(true, 2.0)); + rt.frame(0.0); + assert_eq!(v.state(), PlayerState::Ready); + assert_eq!(v.natural_size(), Some((64, 36))); + assert!((v.duration().unwrap() - 1.0).abs() < 1e-3); + let first = render(&gpu, &mut rt); + near(centre(&first), [255, 0, 0], "first frame"); + rt.frame(0.0); + assert!(!rt.frame(0.5), "a paused video requests no frames"); + assert_eq!(render(&gpu, &mut rt), first, "deterministic"); + + v.play(); + assert!(rt.frame(0.0), "playing keeps frames coming"); + assert!(rt.frame(0.3)); + assert_eq!(v.state(), PlayerState::Playing); + assert!((v.time() - 0.3).abs() < 1e-9); + near(centre(&render(&gpu, &mut rt)), [0, 255, 0], "0.3 s"); + rt.frame(0.3); + near(centre(&render(&gpu, &mut rt)), [0, 0, 255], "0.6 s"); + let tree = crate::tooling::tree_json(&rt, 0.6); + let clip = tree["elements"].as_array().unwrap().iter().find(|e| e["key"] == "clip").unwrap(); + assert_eq!(clip["video"]["state"], "playing"); + assert_eq!(clip["video"]["time"], 0.6); + assert_eq!(clip["video"]["size"], serde_json::json!([64, 36])); + assert_eq!(clip["video"]["muted"], true); + + rt.frame(0.3); + near(centre(&render(&gpu, &mut rt)), [255, 255, 255], "0.9 s"); + rt.frame(0.3); + assert_eq!(v.state(), PlayerState::Ended); + assert_eq!(v.time(), 1.0); + near(centre(&render(&gpu, &mut rt)), [255, 255, 255], "the end holds the last frame"); + rt.frame(0.0); + assert!(!rt.frame(0.1), "an ended video requests no frames"); + + v.seek(0.3); + rt.frame(0.0); + near(centre(&render(&gpu, &mut rt)), [0, 255, 0], "seek while paused"); + v.set_looping(true); + v.set_rate(2.0); + v.play(); + rt.frame(0.0); + rt.frame(0.5); + assert!((v.time() - 0.3).abs() < 1e-9, "0.3 + 2 x 0.5 wraps to 0.3: {}", v.time()); + near(centre(&render(&gpu, &mut rt)), [0, 255, 0], "looped"); + } + + /// A playing clip scrolled out of its list and back commits nothing, and shows the frame + /// at the time it comes back, not the one it left on. + #[test] + fn a_playing_clip_scrolling_across_the_clip_edge_commits_nothing() { + let gpu = Gpu::new(Gpu::instance(), None); + let v = Video::file(fixture()); + v.set_looping(true); + let mut rt = crate::Runtime::new(v.clone(), scrolled, (32.0, 18.0), crate::Env::new(true, 2.0)); + v.play(); + rt.frame(0.0); + rt.frame(0.1); + near(centre(&render(&gpu, &mut rt)), [255, 0, 0], "0.1 s"); + let commits = rt.stats.commits; + rt.wheel(10.0, 10.0, -40.0); + rt.frame(0.1); + assert!(rt.surfaces.is_empty(), "scrolled out of sight"); + rt.frame(0.4); + rt.wheel(10.0, 10.0, 40.0); + rt.frame(0.0); + assert_eq!(rt.surfaces.len(), 1, "back in sight"); + near(centre(&render(&gpu, &mut rt)), [0, 0, 255], "0.6 s, pulled as it comes back"); + assert_eq!(v.state(), PlayerState::Playing); + assert_eq!(rt.stats.commits, commits, "scrolling across the edge commits nothing"); + } +} + +/// A local HTTP server that serves `body` (with byte ranges) only to requests carrying +/// `Authorization: Bearer let-me-in`, and counts the ones that didn't. +#[cfg(all(target_os = "macos", feature = "ogg-audio"))] +fn serve_with_auth(body: Vec<u8>, content_type: &'static str) -> (String, Arc<std::sync::atomic::AtomicUsize>) { + use std::io::{BufRead, BufReader, Write}; + let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let url = format!("http://127.0.0.1:{}/media/clip", listener.local_addr().unwrap().port()); + let refused = Arc::new(std::sync::atomic::AtomicUsize::new(0)); + let count = refused.clone(); + std::thread::spawn(move || { + for stream in listener.incoming() { + let Ok(stream) = stream else { return }; + let (body, count) = (body.clone(), count.clone()); + std::thread::spawn(move || { + let mut reader = BufReader::new(stream.try_clone().unwrap()); + let mut stream = stream; + loop { + let (mut authorized, mut range) = (false, None); + let mut line = String::new(); + if reader.read_line(&mut line).unwrap_or(0) == 0 { return; } + loop { + let mut header = String::new(); + if reader.read_line(&mut header).unwrap_or(0) == 0 { return; } + let header = header.trim_end(); + if header.is_empty() { break; } + let (name, value) = header.split_once(':').unwrap_or((header, "")); + match name.trim().to_ascii_lowercase().as_str() { + "authorization" => authorized = value.trim() == "Bearer let-me-in", + "range" => range = value.trim().strip_prefix("bytes=").map(str::to_owned), + _ => {} + } + } + if !authorized { + count.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + stream.write_all(b"HTTP/1.1 401 Unauthorized\r\nContent-Length: 0\r\n\r\n").ok(); + continue; + } + let len = body.len(); + let (start, end) = range.and_then(|r| { + let (a, b) = r.split_once('-')?; + let a: usize = a.parse().ok()?; + let b = b.parse::<usize>().map_or(len - 1, |b| b.min(len - 1)); + Some((a, b)) + }).unwrap_or((0, len - 1)); + let head = format!( + "HTTP/1.1 206 Partial Content\r\nContent-Type: {content_type}\r\nAccept-Ranges: bytes\r\nContent-Range: bytes {start}-{end}/{len}\r\nContent-Length: {}\r\n\r\n", + end + 1 - start + ); + if stream.write_all(head.as_bytes()).and_then(|_| stream.write_all(&body[start..=end])).is_err() { return; } + } + }); + } + }); + (url, refused) +} + +/// Ogg and WebM audio, which AVFoundation can't read, decode and open like any clip: by file +/// extension, by URL with request headers, and by their bytes when the URL has no extension. +/// Each fixture is 0.5 s. +#[cfg(all(target_os = "macos", feature = "ogg-audio"))] +#[test] +fn headless_ogg_and_webm_audio_open_and_follow_the_clock() { + let near = |a: &Player, what: &str| assert!((a.duration().unwrap_or(0.0) - 0.5).abs() < 0.03, "{what}: {:?} {:?}", a.state(), a.duration()); + for name in ["sine-vorbis.ogg", "sine-opus.ogg", "sine-opus.webm"] { + let a = Player::audio(sound(name)); + assert_eq!(a.state(), PlayerState::Ready, "{name}"); + near(&a, name); + } + let (url, refused) = serve_with_auth(std::fs::read(sound("sine-opus.webm")).unwrap(), "application/octet-stream"); + let by_url = Player::request(format!("{url}.webm")).header("Authorization", "Bearer let-me-in").audio(); + near(&by_url, "url"); + let sniffed = Player::request(url).header("Authorization", "Bearer let-me-in").audio(); + near(&sniffed, "no extension"); + assert_eq!(refused.load(std::sync::atomic::Ordering::SeqCst), 0, "every request carried the header"); + + let a = Player::audio(sound("sine-vorbis.ogg")); + let mut rt = crate::Runtime::new((), |_: &(), _: &mut crate::Cx<()>| crate::el().size(10.0, 10.0), (10.0, 10.0), crate::Env::new(true, 2.0)); + a.play(); + rt.frame(0.0); + rt.frame(0.2); + assert!((a.time() - 0.2).abs() < 1e-6, "{}", a.time()); + rt.frame(0.5); + assert_eq!(a.state(), PlayerState::Ended); + + let broken = Player::audio("/nonexistent/clip.ogg"); + assert!(matches!(broken.state(), PlayerState::Failed(e) if e.contains("can't read")), "{:?}", broken.state()); + // Ogg bytes that don't decode, at a URL with no extension, report the decode error. + let mut bytes = b"OggS".to_vec(); + bytes.extend([0x55; 400]); + let (url, _) = serve_with_auth(bytes, "application/octet-stream"); + let garbled = Player::request(url).header("Authorization", "Bearer let-me-in").audio(); + assert!(matches!(garbled.state(), PlayerState::Failed(e) if e.contains("can't decode")), "{:?}", garbled.state()); +} + +/// Headless audio follows the runtime clock silently: play, pause, rate, seek and the end. +#[cfg(target_os = "macos")] +#[test] +fn headless_audio_time_follows_the_virtual_clock() { + let a = Player::audio(sound("silence.wav")); + let ends = Arc::new(std::sync::atomic::AtomicUsize::new(0)); + let heard = ends.clone(); + let clip = a.clone(); + a.set_waker(Arc::new(move || { + if clip.surface().video().is_some_and(|v| v.snapshot().state == PlayerState::Ended) { + heard.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + } + })); + let mut rt = crate::Runtime::new((), |_: &(), _: &mut crate::Cx<()>| crate::el().size(10.0, 10.0), (10.0, 10.0), crate::Env::new(true, 2.0)); + let near = |t: f64, want: f64, what: &str| assert!((t - want).abs() < 1e-6, "{what}: {t}, want {want}"); + a.play(); + rt.frame(0.0); + rt.frame(0.1); + near(a.time(), 0.1, "playing"); + assert_eq!(a.state(), PlayerState::Playing); + a.pause(); + rt.frame(0.2); + near(a.time(), 0.1, "paused"); + a.set_rate(2.0); + a.play(); + rt.frame(0.05); + near(a.time(), 0.2, "double speed"); + a.seek(0.05); + near(a.time(), 0.05, "seek"); + rt.frame(0.1); + near(a.time(), 0.25, "plays on from the seek"); + assert_eq!(ends.load(std::sync::atomic::Ordering::SeqCst), 0); + rt.frame(0.5); + assert_eq!(a.state(), PlayerState::Ended); + near(a.time(), 0.5, "holds the end"); + assert_eq!(ends.load(std::sync::atomic::Ordering::SeqCst), 1, "the waker hears the end once"); + a.set_looping(true); + a.set_rate(1.0); + a.play(); + rt.frame(0.6); + near(a.time(), 0.1, "loops"); + assert!(a.is_playing()); +} + +/// A new runtime's clock starts at 0, never where an earlier runtime on this thread left off. +#[cfg(target_os = "macos")] +#[test] +fn a_new_runtime_starts_the_headless_clock_again() { + let view = |_: &(), _: &mut crate::Cx<()>| crate::el().size(10.0, 10.0); + let mut old = crate::Runtime::new((), view, (10.0, 10.0), crate::Env::new(true, 2.0)); + old.frame(5.0); + drop(old); + let a = Player::audio(sound("silence.wav")); + let mut rt = crate::Runtime::new((), view, (10.0, 10.0), crate::Env::new(true, 2.0)); + a.play(); + rt.frame(0.1); + assert!((a.time() - 0.1).abs() < 1e-6, "{}", a.time()); +} diff --git a/app/vendor/rune/crates/rune/src/runtime/virtual_list.rs b/app/vendor/rune/crates/rune/src/runtime/virtual_list.rs new file mode 100644 index 0000000..21994d5 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/virtual_list.rs @@ -0,0 +1,10 @@ +//! Virtual lists between commits: window checks, overscan fill and reordered growth rows. +use super::*; + +pub(super) mod fill; +#[cfg(test)] +mod fill_resume_tests; +#[cfg(test)] +mod live_tail_tests; +pub(super) mod row_reorder; +pub(super) mod window; diff --git a/app/vendor/rune/crates/rune/src/runtime/virtual_list/fill.rs b/app/vendor/rune/crates/rune/src/runtime/virtual_list/fill.rs new file mode 100644 index 0000000..99f34d4 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/virtual_list/fill.rs @@ -0,0 +1,174 @@ +//! An index-built list's fill: how many frames in a row the host kept drawing because a list +//! still wanted rows, and the wait that resumes a fill it couldn't finish in those frames. A +//! frame that finds no list asking settles it; a list whose heights keep changing for longer +//! than the bound waits, backs off and resumes, so it fills once they settle instead of going +//! blank. A wake whose attempt the fill no longer holds draws nothing and never starts it again. + +use crate::machine::{Attempt, Effects, Seq}; + +/// The most frames in a row an index-built list keeps the host drawing to fill its overscan. +/// Filling takes four at most (half a viewport per side each); this bounds a list whose +/// heights keep changing. +pub(super) const FILL_FRAMES: u16 = 12; + +/// How long the first resume waits, on the runtime clock: a few frames at 60 Hz. Each resume +/// without progress waits twice as long as the one before it. +const RESUME_WAIT: f64 = 3.0 / 60.0; + +/// Resumes without the unfilled range shrinking before the fill gives up. A list whose heights +/// never settle goes blank rather than waking forever. +const RESUME_LIMIT: u8 = 3; + +/// Where a fill's run stands. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub(super) enum State { + /// No list wants another frame. + #[default] + Idle, + /// This many frames in a row found a list wanting one. `best` is the smallest unfilled + /// range measured at the bound; `resumes` is how many resumes have run without it shrinking. + Filling { frames: u16, best: usize, resumes: u8 }, + /// The bound stopped a fill that still had rows to mount: `attempt` resumes it at `due`. + Waiting { attempt: Attempt, due: f64, best: usize, resumes: u8 }, + /// Resumes without progress ran out. Only a frame that moves a viewport or finds nothing to + /// fill starts the fill again; other frames change nothing, so a redraw or an old deadline + /// can't put a starved list back to drawing forever. + Stalled, +} + +/// The fill's state and the attempts it hands out, plus the one deadline it armed. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub(crate) struct Fill { + state: State, + seq: Seq, + /// The deadline this fill armed: the attempt it resumes and when. A wake whose attempt the + /// state no longer holds is stale, so the fill draws nothing for it. + wake: Option<(Attempt, f64)>, +} + +/// What a finished frame found. +#[derive(Clone, Copy, Debug, PartialEq)] +pub(crate) enum FillEvent { + /// A frame ended at `now`. `wanted` is whether an index-built list still wants its window + /// moved; `missing` is how many of its rows are still unmounted, read only when the run + /// reaches its bound ([`Fill::at_bound`]) so a fill that finishes inside the bound counts + /// nothing; `moved` is whether a scroll viewport moved this frame, which invalidates the + /// window the fill was chosen for. + Frame { now: f64, wanted: bool, missing: usize, moved: bool }, + /// The wake `attempt` asked for came due. + Due { attempt: Attempt, now: f64 }, +} + +/// What to do about it. +#[derive(Clone, Copy, Debug, PartialEq)] +pub(crate) enum FillEffect { + /// Draw another frame now: a commit of that frame mounts more of the overscan. + Draw, + /// Draw nothing before `due` (runtime clock seconds), then resume the fill there. + WakeAt(f64), +} + +impl Fill { + /// Whether the next frame reaches this run's bound, so the caller reads `missing` for it. + pub(super) fn at_bound(&self) -> bool { + matches!(self.state, State::Filling { frames, .. } if frames >= FILL_FRAMES) + } + + /// Takes this fill's armed deadline when it has come due: `None` before it, or once it has + /// been taken. The fill clears it when it leaves the wait, so this only answers for the run + /// that armed it. + pub(super) fn wake(&mut self, now: f64) -> Option<Attempt> { + let (attempt, due) = self.wake?; + if now < due { return None; } + self.wake = None; + Some(attempt) + } + + /// Whether an armed deadline is due at `now`, so a resting window draws the frame that + /// resumes it. + pub(in crate::runtime) fn resuming(&self, now: f64) -> bool { + self.wake.is_some_and(|(_, due)| now >= due) + } + + /// Arms this fill's deadline at `due` for `attempt`. + fn arm(&mut self, attempt: Attempt, due: f64) { + self.wake = Some((attempt, due)); + } + + pub(crate) fn step(&mut self, event: FillEvent) -> Effects<FillEffect> { + let effects = self.transition(event); + // Only a wait owns the deadline. Once the fill leaves it (nothing wanted, a moved + // viewport, the bound), that deadline is spent bookkeeping: it can neither draw for this + // fill nor turn away the first frame a list that replaces it wants. + if !matches!(self.state, State::Waiting { .. }) { self.wake = None; } + effects + } + + fn transition(&mut self, event: FillEvent) -> Effects<FillEffect> { + match (self.state, event) { + // No list wants a frame: the run is over, and any wait it left retires. + (_, FillEvent::Frame { wanted: false, .. }) => { + self.state = State::Idle; + Effects::none() + } + // // differs from dev: a viewport moved, so the window the fill was chosen for is + // gone; dev's spent count kept drawing nothing here. A fresh run draws from scratch. + (_, FillEvent::Frame { wanted: true, moved: true, .. }) => { + self.state = State::Filling { frames: 1, best: usize::MAX, resumes: 0 }; + Effects::one(FillEffect::Draw) + } + (State::Idle, FillEvent::Frame { wanted: true, .. }) => { + self.state = State::Filling { frames: 1, best: usize::MAX, resumes: 0 }; + Effects::one(FillEffect::Draw) + } + (State::Filling { frames, best, resumes }, FillEvent::Frame { now, wanted: true, missing, .. }) => { + let frames = frames.saturating_add(1).min(FILL_FRAMES + 1); + if frames <= FILL_FRAMES { + self.state = State::Filling { frames, best, resumes }; + return Effects::one(FillEffect::Draw); + } + // // differs from dev: at the bound the unfilled range decides between waiting + // for more frames, backing off, and giving up. Dev stopped at the bound for + // good, so a list whose heights kept changing went blank until something else + // asked for a frame. + let (best, resumes) = if missing < best { (missing, 0) } else { (best, resumes) }; + if missing == 0 { + self.state = State::Idle; + return Effects::none(); + } + if resumes >= RESUME_LIMIT { + self.state = State::Stalled; + return Effects::none(); + } + let attempt = self.seq.next(); + let resumes = resumes + 1; + let due = now + RESUME_WAIT * f64::from(1u32 << (resumes - 1)); + self.state = State::Waiting { attempt, due, best, resumes }; + self.arm(attempt, due); + Effects::one(FillEffect::WakeAt(due)) + } + // // differs from dev: a frame drawn for another cause while the fill waits changes + // nothing at all. It can't spend the run's budget or reset its no-progress count, so + // an old deadline or a plain redraw can't keep a starved fill drawing. + (State::Waiting { .. } | State::Stalled, FillEvent::Frame { wanted: true, .. }) => Effects::none(), + (State::Waiting { attempt, due, best, resumes }, FillEvent::Due { attempt: a, now }) + if attempt == a && now >= due => + { + self.state = State::Filling { frames: 1, best, resumes }; + Effects::one(FillEffect::Draw) + } + // A due time whose attempt the state no longer holds is stale and changes nothing. + _ => Effects::none(), + } + } + + /// Where the run stands, for tests. + #[cfg(test)] + pub(super) fn state(self) -> State { + self.state + } +} + +#[cfg(test)] +#[path = "fill_tests.rs"] +mod tests; diff --git a/app/vendor/rune/crates/rune/src/runtime/virtual_list/fill_resume_tests.rs b/app/vendor/rune/crates/rune/src/runtime/virtual_list/fill_resume_tests.rs new file mode 100644 index 0000000..8cecc8c --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/virtual_list/fill_resume_tests.rs @@ -0,0 +1,207 @@ +//! A virtual list whose row heights keep changing for longer than the fill's bound still fills +//! every visible row once they settle (r262). Dev stopped at the bound and left the rows it still +//! wanted unmounted until something else asked for a frame. A wake after the list fills or goes +//! away draws nothing. + +use std::cell::Cell; +use std::rc::Rc; + +use super::fill::{FILL_FRAMES, State}; +use super::*; +use crate::{GrowthSpec, ScrollSpec, col, el}; + +const ROWS: usize = 400; +const VIEWPORT: f32 = 200.0; +const ROW_H: f32 = 20.0; +const THIN: f32 = 4.0; + +/// Rows that measure shorter the more of them the list builds: the fill's budget buys rows at the +/// estimate, so each frame covers less of the overscan than it looks like it will. The first +/// rows are full height and the rest thin, which is what a list with heights still settling does. +struct Thinning { + builds: Rc<Cell<u32>>, + /// The list keeps only a few rows, so it fills at once. + short: bool, + /// The list is gone from the view. + gone: bool, +} + +fn thinning() -> Runtime<Thinning> { + let state = Thinning { builds: Rc::new(Cell::new(0)), short: false, gone: false }; + Runtime::new(state, thinning_view, (400.0, VIEWPORT), Env::new(true, 2.0)) +} + +fn thinning_view(s: &Thinning, _: &mut Cx<Thinning>) -> El { + if s.gone { return el().key("empty").w_full().h_full(); } + let builds = s.builds.clone(); + let count = if s.short { 3 } else { ROWS }; + let list = col().key("scroll").w(300.0).h(VIEWPORT).scroll(ScrollSpec { stick_bottom: false }).child( + col().key("rows").w_full().growth(GrowthSpec::default()).virtual_rows( + count, + ROW_H, + |_: &Thinning, i| format!("r{i}").into(), + move |_: &Thinning, i| { + let n = builds.get(); + builds.set(n + 1); + let height = if n < 12 { ROW_H } else { THIN }; + el().key(format!("r{i}")).w_full().h(height).fill(Color::WHITE) + }, + ), + ); + // A second viewport, so another scroller can move while the list waits. + let other = col().key("other").w(80.0).h(VIEWPORT).scroll(ScrollSpec { stick_bottom: false }).child( + col().key("other-rows").w_full().children( + (0..60).map(|i| el().key(format!("o{i}")).w_full().h(ROW_H).fill(Color::WHITE)), + ), + ); + crate::row().w_full().h_full().child(list).child(other) +} + +/// Draws while the runtime asks for a frame and wakes at any timer it armed, like a host does. +/// Returns the frames drawn before nothing was left to draw. +fn draw_while_asked<S: 'static>(rt: &mut Runtime<S>, mut drew: bool) -> usize { + let mut frames = 0; + loop { + frames += 1; + assert!(frames < 4_000, "the fill kept the host drawing"); + if drew { + drew = rt.frame(1.0 / 120.0); + continue; + } + let Some(due) = rt.wake_deadline() else { return frames }; + drew = rt.frame((due - rt.clock).max(1.0 / 120.0)); + } +} + +/// Draws like a host until the fill reaches its bound, returning the deadline it armed. +fn draw_to_wait<S: 'static>(rt: &mut Runtime<S>) -> f64 { + let mut drew = true; + for _ in 0..400 { + if matches!(rt.commit.virtual_fill.state(), State::Waiting { .. }) { + return rt.wake_deadline().expect("the wait armed a deadline"); + } + if drew { + drew = rt.frame(1.0 / 120.0); + continue; + } + let Some(due) = rt.wake_deadline() else { panic!("the fill stopped before its bound: {:?}", rt.commit.virtual_fill.state()) }; + drew = rt.frame((due - rt.clock).max(1.0 / 120.0)); + } + panic!("the fill never reached its bound"); +} + +fn list_path<S>(rt: &Runtime<S>) -> String { + rt.commit.virtuals.keys().next().expect("a virtual list").clone() +} + +/// The list's offset within its viewport, and whether the viewport is pinned to its end. +fn offset<S>(rt: &Runtime<S>, path: &str) -> (f32, bool) { + let v = &rt.commit.virtuals[path]; + let s = rt.tree.path_ids.get(&v.scroll_path).and_then(|id| rt.scroll.scrolls.get(id)); + s.map_or((0.0, false), |s| ((s.offset as f32 - v.top).max(0.0), s.pinned())) +} + +#[test] +fn heights_that_keep_changing_still_fill_every_visible_row() { + let mut rt = thinning(); + let frames = draw_while_asked(&mut rt, true); + let path = list_path(&rt); + let (offset, pinned) = offset(&rt, &path); + let v = &rt.commit.virtuals[&path]; + let visible = v.visible_range(offset, pinned); + assert!( + v.range.start <= visible.start && v.range.end >= visible.end, + "a visible row is blank after {frames} frames: mounted {:?}, visible {visible:?}", + v.range + ); + assert!(!v.needs_window(offset, pinned), "the fill stopped with rows unmounted after {frames} frames: mounted {:?}, visible {visible:?}", v.range); + assert!(frames > FILL_FRAMES as usize, "the fill needed more than its bound: {frames} frames"); +} + +#[test] +fn an_idle_list_with_nothing_to_fill_draws_nothing() { + struct Short; + fn view(_: &Short, _: &mut Cx<Short>) -> El { + col().w_full().h_full().child( + col().key("scroll").w_full().h(VIEWPORT).scroll(ScrollSpec { stick_bottom: false }).child( + col().key("rows").w_full().growth(GrowthSpec::default()).virtual_rows( + 5, + ROW_H, + |_: &Short, i| format!("r{i}").into(), + |_: &Short, i| el().key(format!("r{i}")).w_full().h(ROW_H).fill(Color::WHITE), + ), + ), + ) + } + let mut rt = Runtime::new(Short, view, (400.0, VIEWPORT), Env::new(true, 2.0)); + rt.frame(0.0); + let frames = draw_while_asked(&mut rt, true); + assert_eq!(rt.wake_deadline(), None, "an idle list arms nothing, after {frames} frames"); + assert!(!rt.frame(1.0 / 120.0), "and nothing asks for another frame"); +} + +/// r367: the list unmounts while a fill wake waits, and that wake draws nothing when it comes due. +#[test] +fn a_wake_after_the_list_unmounts_draws_nothing() { + let mut rt = thinning(); + let due = draw_to_wait(&mut rt); + rt.update(|s, _| s.gone = true); + // The frame that unmounts the list is also the one the wake comes due in. + let dt = (due - rt.clock).max(1.0 / 120.0); + rt.frame(dt); + assert!(rt.clock >= due - 1e-9, "the deadline came due"); + assert_eq!(rt.commit.virtual_fill.state(), State::Idle, "the unmounted list retires the wait, not resuming it"); + assert_eq!(rt.motion.anim_sources & AnimSource::VIRTUAL_FILL, 0, "and the fill adds no frame"); + assert_eq!(rt.wake_deadline(), None, "nothing is left armed"); +} + +/// r373: a list that unmounts mid-wait must not leave a deadline that turns away the first fill +/// frame of the list that replaces it. +#[test] +fn a_replacement_list_draws_its_first_fill_frame() { + let mut rt = thinning(); + let due = draw_to_wait(&mut rt); + rt.update(|s, _| s.gone = true); + // The frame the wake comes due in is also the one the list unmounts in. + rt.frame((due - rt.clock).max(1.0 / 120.0)); + assert_eq!(rt.commit.virtual_fill.state(), State::Idle, "the unmounted list retires the wait"); + // The replacement starts exactly as a list that was never here: its first frame fills. + rt.update(|s, _| s.gone = false); + rt.frame(1.0 / 120.0); + assert_ne!(rt.motion.anim_sources & AnimSource::VIRTUAL_FILL, 0, "the replacement's first fill frame draws"); + assert!(matches!(rt.commit.virtual_fill.state(), State::Filling { .. }), "and starts a run: {:?}", rt.commit.virtual_fill.state()); +} + +/// r372: another viewport scrolling is not this list's invalidation, so the fill keeps the budget +/// it has and still stops within its bound. +#[test] +fn an_unrelated_scroller_does_not_reset_the_fill() { + let mut rt = thinning(); + let due = draw_to_wait(&mut rt); + rt.wheel(340.0, 100.0, -60.0); + rt.frame(1.0 / 120.0); + assert!(rt.clock < due, "the frame is before the fill's deadline"); + assert!( + matches!(rt.commit.virtual_fill.state(), State::Waiting { .. }), + "another scroller leaves the wait alone: {:?}", + rt.commit.virtual_fill.state() + ); + let frames = draw_while_asked(&mut rt, false); + assert!(frames < 4_000, "the fill still stops: {frames} frames"); + assert_eq!(rt.wake_deadline(), None, "nothing is left armed"); +} + +/// r367: the wake that was waiting comes due after the list finished filling, and draws nothing. +#[test] +fn a_wake_after_the_fill_completes_draws_nothing() { + let mut rt = thinning(); + let due = draw_to_wait(&mut rt); + rt.update(|s, _| s.short = true); + // The frame that fills the last rows is also the one the wake comes due in. + let dt = (due - rt.clock).max(1.0 / 120.0); + rt.frame(dt); + assert!(rt.clock >= due - 1e-9, "the deadline came due"); + assert_eq!(rt.commit.virtual_fill.state(), State::Idle, "the filled list retires the wait, not resuming it"); + assert_eq!(rt.motion.anim_sources & AnimSource::VIRTUAL_FILL, 0, "and the fill adds no frame"); + assert_eq!(rt.wake_deadline(), None, "nothing is left armed"); +} diff --git a/app/vendor/rune/crates/rune/src/runtime/virtual_list/fill_tests.rs b/app/vendor/rune/crates/rune/src/runtime/virtual_list/fill_tests.rs new file mode 100644 index 0000000..0719125 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/virtual_list/fill_tests.rs @@ -0,0 +1,229 @@ +//! The fill machine against origin/dev's counter, and the wait that resumes a starved fill. +use super::{FILL_FRAMES, Fill, FillEffect, FillEvent, RESUME_LIMIT, State}; +use crate::machine::{Attempt, Effects}; + +/// origin/dev's `Runtime::virtual_filling`, transcribed as it was: `Runtime.virtual_fill: u32` +/// counted one more for each frame that found an index-built list wanting its window and reset +/// to zero for each frame that found none, and it answered `filling && virtual_fill <= 12` — +/// `VIRTUAL_FILL_FRAMES` at `runtime/virtual/window.rs:8`. It is never edited to fit the branch: +/// a walk that fails means the branch differs from dev. +struct Dev { + virtual_fill: u32, +} + +impl Dev { + fn frame(&mut self, filling: bool) -> bool { + self.virtual_fill = if filling { self.virtual_fill + 1 } else { 0 }; + filling && self.virtual_fill <= 12 + } +} + +fn sequence(bits: u32, len: usize) -> String { + (0..len).map(|i| if bits >> i & 1 == 1 { 'F' } else { '.' }).collect() +} + +/// Runs `fill` to the bound with `missing` rows unfilled, returning the wait it asked for. +fn run_to_bound(fill: &mut Fill, now: f64, missing: usize) -> Option<(f64, Attempt)> { + for _ in 0..FILL_FRAMES + 2 { + let count = if fill.at_bound() { missing } else { 0 }; + for effect in fill.step(FillEvent::Frame { now, wanted: true, missing: count, moved: false }) { + if let FillEffect::WakeAt(due) = effect + && let State::Waiting { attempt, .. } = fill.state() + { + return Some((due, attempt)); + } + } + if matches!(fill.state(), State::Idle | State::Stalled) { return None; } + } + None +} + +/// One frame as `Runtime::virtual_filling` runs it: the fill's own deadline draws for itself, a +/// stale one draws nothing, and any other frame counts as a fill frame. Returns whether it drew. +fn frame(fill: &mut Fill, now: f64, missing: usize, deadlines: &mut Vec<f64>) -> bool { + match fill.wake(now) { + Some(attempt) => !fill.step(FillEvent::Due { attempt, now }).is_empty(), + None => { + let count = if fill.at_bound() { missing } else { 0 }; + let effects = fill.step(FillEvent::Frame { now, wanted: true, missing: count, moved: false }); + let drew = effects.clone().into_iter().any(|e| e == FillEffect::Draw); + for effect in effects { + if let FillEffect::WakeAt(due) = effect { deadlines.push(due); } + } + drew + } + } +} + +/// Every sequence of frames up to two past the bound, each driven through `step` and its answer +/// compared with dev's after every frame. The wake is not a frame's answer, so the draw answers +/// still match dev exactly: past the bound both stop drawing until a frame finds nothing wanted. +#[test] +fn every_run_of_frames_draws_what_dev_draws() { + let longest = FILL_FRAMES as usize + 2; + for len in 1..=longest { + for bits in 0..1u32 << len { + let walk = sequence(bits, len); + let (mut fill, mut dev) = (Fill::default(), Dev { virtual_fill: 0 }); + for (i, wanted) in (0..len).map(|i| (i, bits >> i & 1 == 1)) { + let missing = if fill.at_bound() { 1 } else { 0 }; + let drew = fill.step(FillEvent::Frame { now: 0.0, wanted, missing, moved: false }).into_iter().any(|e| e == FillEffect::Draw); + assert_eq!( + drew, + dev.frame(wanted), + "frame {i} of {walk}: wanted {wanted}, state {:?}", + fill.state() + ); + } + } + } +} + +/// One frame's answer is all the runtime keeps of the fill, so a settled list asks again at once, +/// while a run keeps asking until the bound and not after it. +#[test] +fn a_settled_frame_forgets_the_run_and_the_bound_stops_it() { + let mut fill = Fill::default(); + let frame = |fill: &mut Fill, wanted: bool| { + let missing = if fill.at_bound() { 8 } else { 0 }; + fill.step(FillEvent::Frame { now: 0.0, wanted, missing, moved: false }).into_iter().any(|e| e == FillEffect::Draw) + }; + let drew: Vec<bool> = (0..FILL_FRAMES as usize + 1).map(|_| frame(&mut fill, true)).collect(); + assert!(drew[..FILL_FRAMES as usize].iter().all(|d| *d), "the first {FILL_FRAMES} frames draw: {drew:?}"); + assert!(!drew[FILL_FRAMES as usize], "the bound stops drawing: {drew:?}"); + // // differs from dev: the bound leaves a wait behind, not a spent count. + assert!(matches!(fill.state(), State::Waiting { .. }), "the bound waits: {:?}", fill.state()); + assert!(fill.step(FillEvent::Frame { now: 0.0, wanted: false, missing: 0, moved: false }).is_empty()); + assert_eq!(fill.state(), State::Idle, "a frame with nothing to fill settles it"); + assert!(frame(&mut fill, true), "a settled list asks again at once"); +} + +/// A fill that hits its bound with rows still unfilled waits, and only the wake it holds resumes +/// it. A stale attempt, a pre-due frame and a redrawn frame all change nothing. +#[test] +fn the_bound_waits_and_the_wake_resumes_the_fill() { + let mut fill = Fill::default(); + let (due, attempt) = run_to_bound(&mut fill, 1.0, 4).expect("the bound asks for a wake"); + let waiting = fill.state(); + assert!(matches!(waiting, State::Waiting { .. })); + assert!(!fill.resuming(due - 0.001), "nothing resumes before the wake is due"); + assert!(fill.resuming(due)); + + // A stale wake: an attempt the state never issued changes nothing. + assert!(fill.step(FillEvent::Due { attempt: Attempt(999), now: 2.0 }).is_empty()); + assert_eq!(fill.state(), waiting); + + // A frame drawn for another cause while the fill waits: no draw, no reset. + assert!(fill.step(FillEvent::Frame { now: 1.5, wanted: true, missing: 4, moved: false }).is_empty()); + assert_eq!(fill.state(), waiting, "a redraw changes nothing"); + + // Its own wake resumes the run it was waiting in. + let effects = fill.step(FillEvent::Due { attempt, now: due }); + assert!(effects.into_iter().any(|e| e == FillEffect::Draw), "the wake draws again"); + assert!(matches!(fill.state(), State::Filling { frames: 1, resumes: 1, .. }), "{:?}", fill.state()); +} + +/// A list whose heights never settle resumes with a longer wait each time, then stalls: nothing +/// after that asks for a frame, whatever else draws. +#[test] +fn a_starved_fill_stops_after_its_resumes_without_progress() { + let mut fill = Fill::default(); + let mut now = 0.0; + let mut waits = Vec::new(); + while let Some((due, attempt)) = run_to_bound(&mut fill, now, 8) { + waits.push(due - now); + now = due; + assert!(waits.len() <= RESUME_LIMIT as usize, "resumes are bounded: {waits:?}"); + assert!(!fill.step(FillEvent::Due { attempt, now }).is_empty(), "the wake resumes it"); + } + assert_eq!(waits.len(), RESUME_LIMIT as usize, "resumes are bounded: {waits:?}"); + assert!(waits.windows(2).all(|w| w[1] > w[0]), "each resume backs off: {waits:?}"); + assert_eq!(fill.state(), State::Stalled, "and the fill stops asking"); + assert!(!fill.resuming(now + 100.0), "nothing is left armed"); + // Redraws and stale deadlines after it change nothing. + for _ in 0..5 { + assert!(fill.step(FillEvent::Frame { now: now + 1.0, wanted: true, missing: 8, moved: false }).is_empty()); + assert!(fill.step(FillEvent::Due { attempt: Attempt(999), now: now + 1.0 }).is_empty()); + } + assert_eq!(fill.state(), State::Stalled); +} + +/// The reviewer's replay, 36,001 ticks at 359.94 Hz: wanted true with the same eight rows missing +/// forever, one frame per draw and one per deadline, and extra deadlines left in the set. The +/// fill must stop drawing within its bound and leave nothing armed. +#[test] +fn stale_deadlines_never_restart_the_fill() { + const TICKS: usize = 36_001; + let dt = 1.0 / 359.94; + let mut fill = Fill::default(); + // Deadlines nobody's attempt stands for, as a retired wait leaves behind. + let mut deadlines: Vec<f64> = (0..20).map(|i| dt * f64::from(i * 7 + 3)).collect(); + let (mut now, mut draw, mut frames, mut drawn) = (0.0, true, 0, 0); + for _ in 0..TICKS { + now += dt; + let due = deadlines.iter().any(|d| *d <= now); + if !draw && !due { continue; } + frames += 1; + deadlines.retain(|d| *d > now); + draw = frame(&mut fill, now, 8, &mut deadlines); + if draw { drawn += 1; } + } + assert!(drawn <= 4 * FILL_FRAMES as usize + 4, "the fill stopped drawing: {drawn} frames of {frames}"); + assert_eq!(fill.state(), State::Stalled, "and it stays stalled"); + assert!(deadlines.is_empty(), "no deadline is left armed: {deadlines:?}"); +} + +/// r367: a due wake after the list finished or unmounted draws nothing, and starts nothing. +#[test] +fn a_wake_after_the_list_is_gone_draws_nothing() { + let mut fill = Fill::default(); + let (due, attempt) = run_to_bound(&mut fill, 0.0, 4).expect("the bound asks for a wake"); + assert!(matches!(fill.state(), State::Waiting { .. })); + + // The list finishes or unmounts: the wait retires with it, and its deadline is forgotten. + assert!(fill.step(FillEvent::Frame { now: 0.1, wanted: false, missing: 0, moved: false }).is_empty()); + assert_eq!(fill.state(), State::Idle); + assert!(!fill.resuming(due), "a retired deadline resumes nothing"); + assert_eq!(fill.wake(due), None, "the deadline it left is no longer the fill's"); + assert!(fill.step(FillEvent::Due { attempt, now: due }).is_empty(), "and draws nothing"); + assert_eq!(fill.state(), State::Idle); + // A list that replaces it starts exactly as one that was never here: its first frame draws. + assert!(fill.step(FillEvent::Frame { now: due + 1.0, wanted: true, missing: 8, moved: false }) + .into_iter().any(|e| e == FillEffect::Draw)); +} + +/// A resume that finds the unfilled range smaller counts as progress and resets the bound, so a +/// slow fill that is still shrinking keeps going. +#[test] +fn a_resume_that_finds_progress_gets_a_fresh_bound() { + let mut fill = Fill::default(); + let mut now = 0.0; + let mut missing = 40; + let mut wakes = 0; + while let Some((due, attempt)) = run_to_bound(&mut fill, now, missing) { + wakes += 1; + now = due; + missing = missing.saturating_sub(6); + assert!(!fill.step(FillEvent::Due { attempt, now }).is_empty()); + assert!(wakes <= 8, "progress keeps it going: {wakes}"); + } + assert!(wakes > RESUME_LIMIT as usize, "the shrinking range earned more resumes: {wakes}"); +} + +/// A viewport that moved invalidates the window the fill was chosen for, so even a stalled fill +/// starts again; a redraw alone does not. +#[test] +fn a_moved_viewport_starts_the_fill_again() { + let mut fill = Fill::default(); + let mut now = 0.0; + while let Some((due, attempt)) = run_to_bound(&mut fill, now, 8) { + now = due; + fill.step(FillEvent::Due { attempt, now }); + } + assert_eq!(fill.state(), State::Stalled); + assert!(fill.step(FillEvent::Frame { now: now + 1.0, wanted: true, missing: 8, moved: false }).is_empty()); + assert_eq!(fill.state(), State::Stalled, "a redraw leaves it stalled"); + let effects: Effects<FillEffect> = fill.step(FillEvent::Frame { now: now + 2.0, wanted: true, missing: 8, moved: true }); + assert!(effects.into_iter().any(|e| e == FillEffect::Draw), "a scroll starts it again"); + assert!(matches!(fill.state(), State::Filling { frames: 1, resumes: 0, .. }), "{:?}", fill.state()); +} diff --git a/app/vendor/rune/crates/rune/src/runtime/virtual_list/handoff.rs b/app/vendor/rune/crates/rune/src/runtime/virtual_list/handoff.rs new file mode 100644 index 0000000..d55d35f --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/virtual_list/handoff.rs @@ -0,0 +1,70 @@ +//! The viewport and the panel that gave it room share the incoming row's actual height +//! track. Only local vertical edges that changed at their seam need a presentation delta. +use super::*; + +#[derive(Clone, Debug, Default)] +pub(in crate::runtime) enum Handoff { + #[default] + Idle, + Growing { row: NodeId, viewport: NodeId, frames: Vec<(NodeId, rune_motion::Rect, f32, f32)>, rows: Vec<(NodeId, f32, f32)> }, +} + +impl types::TreeState { + #[allow(clippy::too_many_arguments)] + pub(super) fn tail_handoff( + &self, + scene: &Scene, + grows: &HashMap<NodeId, GrowTrack>, + nodes: &[Node], + stack: usize, + viewport: usize, + row: &str, + room: &str, + ) -> Option<Handoff> { + let (r, panel) = nodes.iter().enumerate().find(|(_, n)| n.named(room))?; + let view = &nodes[viewport]; + let old = |id| self.nodes.iter().find(|n| n.id == id); + let (a, b) = (old(view.id)?.target, old(panel.id)?.target); + let close = |x: f32, y: f32| (x - y).abs() < 1.0 / 64.0; + if panel.target[1] <= b[1] || !close(a[3], b[1]) || !close(view.target[3], panel.target[1]) + || !close(panel.target[3], b[3]) || a[..3] != view.target[..3] { return None; } + let row = nodes.iter().find(|n| n.parent == Some(stack) && n.key.as_deref() == Some(row) && !n.virtual_mount && !scene.contains(n.id))?; + let ancestors = |k| std::iter::successors(Some(k), |&j: &usize| nodes[j].parent); + let mut chain: HashSet<usize> = ancestors(viewport).collect(); + chain.extend(ancestors(r)); + let end = r + 1 + nodes[r+1..].iter().take_while(|n| n.parent >= Some(r)).count(); + let frames = nodes.iter().enumerate().filter(|(k,n)| chain.contains(k) || (r..end).contains(k) + || (n.parent == panel.parent && old(n.id).is_some_and(|o| o.target == n.target))) + .filter_map(|(_,n)| { + let was = scene.get(n.id, prop::FRAME)?; + let (dy, dh) = (was.y - n.local.y, was.h - n.local.h); + (dy != 0.0 || dh != 0.0).then_some((n.id, n.local, dy, dh)) + }).collect(); + // A kept row can lose its footer to the arriving row. Tie that height to the same + // progress too: independent whole-row springs land at different absolute tolerances. + let rows = nodes.iter().filter(|n| n.parent == Some(stack) && n.whole && !n.streaming && n.id != row.id) + .filter_map(|n| { let from = grows.get(&n.id)?.h; + (from != n.local.h).then_some((n.id, from, n.local.h)) }).collect(); + Some(Handoff::Growing { row: row.id, viewport: view.id, frames, rows }) + } +} + +impl Handoff { + pub(in crate::runtime) fn place(&mut self, grows: &mut HashMap<NodeId, GrowTrack>, scene: &mut rune_motion::Scene, nodes: &[Node], index: &NodeIndex, scrolls: &mut HashMap<NodeId, ScrollState>) -> bool { + let Self::Growing { row, viewport, frames, rows } = self else { return false }; + let (left, rate) = grows.get(row).filter(|g| g.target > 0.0).map_or((0.0, 0.0), |g| ((1.0 - g.h / g.target).clamp(0.0, 1.0), g.v / g.target)); + for &(id, from, to) in rows.iter() { + if let Some(g) = grows.get_mut(&id) && g.target == to { g.h = to + (from - to) * left; g.v = (to - from) * rate; } + } + // The edge was already paid for by the row. Don't add the same space to slack. + if let Some(s) = scrolls.get_mut(viewport) { s.slack.follow = true; } + for &(id, target, dy, dh) in frames.iter() { + let Some(n) = index.get(&id).map(|&k| &nodes[k]) else { continue }; + // A later measurement (e.g. typing or a resize) owns its new geometry. + if n.local.y != target.y || n.local.h != target.h { continue; } + scene.set(id, prop::FRAME, rune_motion::Rect { y: target.y + dy * left, h: target.h + dh * left, ..n.local }); + } + if left == 0.0 { *self = Self::Idle; } + true + } +} diff --git a/app/vendor/rune/crates/rune/src/runtime/virtual_list/live_tail_tests.rs b/app/vendor/rune/crates/rune/src/runtime/virtual_list/live_tail_tests.rs new file mode 100644 index 0000000..ef4afaf --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/virtual_list/live_tail_tests.rs @@ -0,0 +1,182 @@ +use super::*; +use crate::{GrowthSpec, ScrollSpec, col, el, motion_gate::{Run, Recording, gate_rows}}; + +#[derive(Clone, Copy, Debug, PartialEq)] +enum Case { Delivery, Room, GeometryOnly, Narrow, Rewrapping, BelowList, Unpinned, InstantChild } + +#[derive(Clone, Copy, PartialEq)] +enum Phase { Waiting, Rewrapping, Delivered } + +struct Feed { case: Case, phase: Phase } + +fn view(feed: &Feed, _: &mut Cx<Feed>) -> El { + let delivered = feed.phase == Phase::Delivered; + let narrow = matches!(feed.case, Case::Narrow | Case::Rewrapping) && feed.phase != Phase::Waiting; + let label = el().key("label").w(40.0).h(10.0).fill(if delivered { Color::WHITE } else { Color::BLACK }); + let mut content = col().key("content").w_full().pt(if delivered { 12.0 } else { 4.0 }).child(label); + if feed.case == Case::InstantChild { content = content.instant_changes(); } + content = content.child_exit(Transition::opacity()).children((!delivered).then(|| el().key("badge").size(10.0, 10.0).fill(Color::WHITE))); + let pending = col().key("pending").w_full().h(if delivered { 64.0 } else { 48.0 }).arrives_whole().child(content); + let working = el().key("working").w(40.0).h(20.0).fill(Color::WHITE); + if feed.case == Case::Room { + let rows = col().key("rows").w_full().growth(GrowthSpec::default()).virtualize(48.0) + .child(el().key("earlier").w_full().h(320.0)) + .children(delivered.then(|| el().key("arrival").w_full().h(64.0).arrives_whole())).child(working); + return col().w_full().h_full().child(col().key("viewport").w_full().grow(1.0).min_h(0.0) + .scroll(ScrollSpec { stick_bottom: true }).child(rows)) + .child(el().key("room").w_full().h(if delivered { 0.0 } else { 40.0 })); + } + let stack = col().key("rows").w_full().growth(GrowthSpec::default()).virtualize(48.0) + .child(el().key("earlier").w_full().h(320.0)) + .children(if delivered { [pending, working] } else { [working, pending] }); + let view = col().key("viewport").w(if narrow { 200.0 } else { 280.0 }).h(180.0) + .scroll(ScrollSpec { stick_bottom: feed.case != Case::Unpinned }).child(stack); + col().w_full().h_full().child(if feed.case == Case::BelowList { view.child(el().key("after").w_full().h(96.0)) } else { view }) +} + +fn poll(s: &mut Feed, t: f64, tx: &mut Tx) -> bool { + if s.phase == Phase::Waiting && s.case == Case::Rewrapping && (0.47..0.5).contains(&t) { s.phase = Phase::Rewrapping; return true; } + if s.phase != Phase::Delivered && t >= 0.5 { + s.phase = Phase::Delivered; + if s.case == Case::Room { tx.grow_visible_tail_from("rows", "arrival", "room"); } else { if s.case == Case::GeometryOnly { tx.grow_visible_tail("rows"); } else { tx.grow_visible_tail_with_ink("rows"); } } + return true; + } + false +} + +fn record(case: Case) -> Recording { + let mut rt = Runtime::new(Feed { case, phase: Phase::Waiting }, view, (300.0, 180.0), Env::new(true, 1.0)); + rt.motion.motion_needs_cause = true; + rt.poll = Some(poll); + let mut run = Run::new(rt, 120.0); + run.idle(0.45); + run.step(); + let growing = matches!(case, Case::Delivery | Case::GeometryOnly | Case::InstantChild); + while run.rt.state.phase != Phase::Delivered { assert!(run.rt.t < 0.6, "delivery did not poll"); run.step(); } + let row = run.rt.tree.nodes.iter().find(|n| n.key.as_deref() == Some("pending")); + if case == Case::Room { + let room = run.rt.tree.nodes.iter().position(|n| n.key.as_deref() == Some("room")).unwrap(); + let first = run.rt.paint.drawn[room][3]; + assert!(first > 0.0 && first < 40.0, "room snapped to {first}"); + let row = run.rt.tree.nodes.iter().find(|n| n.key.as_deref() == Some("arrival")).unwrap(); + let remaining = 1.0 - run.rt.motion.grows[&row.id].h / 64.0; + assert!((first - 40.0 * remaining).abs() < 1.0 / 64.0, "room {first} must follow the drawn row on the first frame"); + } + if growing { + let h = run.rt.motion.grows[&row.unwrap().id].h; + assert!((48.0..64.0).contains(&h), "live row started at {h}"); + if case == Case::Delivery { + let badge = run.rt.tree.nodes.iter().find(|n| n.named("badge")).expect("the visible badge fades on its row"); + assert!(run.rt.is_exiting(badge.id)); + let label = run.rt.tree.nodes.iter().find(|n| n.named("label")).unwrap(); + assert!(run.rt.scene.store().is_animating(label.id, P_FILL)); + } + if case == Case::GeometryOnly { + assert!(!run.rt.tree.nodes.iter().any(|n| n.named("badge")), "geometry-only growth lands child exits"); + } + if case == Case::InstantChild { + let label = run.rt.tree.nodes.iter().position(|n| n.key.as_deref() == Some("label")).unwrap(); + let group = run.rt.tree.nodes[label].parent.unwrap(); + assert!((run.rt.paint.drawn[label][1] - run.rt.paint.drawn[group][1] - 12.0).abs() < 0.01, "explicitly instant contents must land within the moving row"); + } + } else if let Some(row) = row { + let g = &run.rt.motion.grows[&row.id]; + assert_eq!(g.h, 64.0, "{case:?}: the row should land whole"); + assert!(!g.moving(), "{case:?}: no tail growth work"); + } + run.play(1.0); + run.quiet(); + run.step_n(4); + run.rec +} + +#[test] +fn live_tail_motion_gate() { + // A jump is an error in these two traces. In the instant controls below it's required: + // check the actual landing height instead of allowlisting jumps in a motion recording. + gate_rows([Case::Delivery, Case::Room, Case::Unpinned].into_iter() + .map(|case| (format!("live-tail/{case:?}"), Box::new(move || record(case)) as crate::motion_gate::Job)).collect(), &[]); +} + +#[test] +fn live_tail_motion_gate_instant_controls() { + for case in [Case::GeometryOnly, Case::Narrow, Case::Rewrapping, Case::BelowList, Case::InstantChild] { record(case); } +} + +#[test] +fn live_tail_motion_gate_joined_corner_retargets_on_adjacent_deliveries() { + fn grouped(accepted: &usize, _: &mut Cx<usize>) -> El { + let apart = *accepted == 1; + let second = el().key("second").w_full().h(30.0) + .corners([10.0, if apart { 10.0 } else { 4.0 }, 10.0, 10.0]) + .opacity(if apart { 0.75 } else { 1.0 }); + let first = el().key("first").w_full().h(30.0); + let working = el().key("working").w_full().h(20.0); + let order = match accepted { 0 => [working, first, second], 1 => [first, working, second], _ => [first, second, working] }; + col().w_full().h_full().scroll(ScrollSpec { stick_bottom: true }).child(col().key("rows").w_full() + .growth(GrowthSpec::default()).virtualize(30.0).child(el().key("earlier").w_full().h(240.0)).children(order)) + } + let mut rt = Runtime::new(0, grouped, (280.0, 180.0), Env::new(true, 1.0)); + rt.motion.motion_needs_cause = true; + rt.poll = Some(|accepted, t, tx| { + if t < 0.5 || *accepted == 2 { return false; } + *accepted += 1; + tx.grow_visible_tail_with_ink("rows"); + true + }); + let mut run = Run::new(rt, 60.0); + while run.rt.state == 0 { assert!(run.rt.t < 0.6); run.step(); } + let id = run.rt.tree.nodes.iter().find(|n| n.named("second")).unwrap().id; + let radii = |rt: &Runtime<usize>| rt.scene.presented(id).unwrap().radius.0; + let [tl, first, br, bl] = radii(&run.rt); + assert_eq!([tl, br, bl], [10.0; 3]); + assert!(first > 4.0 && first < 6.0, "the corner begins to open: {first}"); + assert_eq!(run.rt.scene.get(id, prop::OPACITY), Some(0.75), "only corners inherit the neighbour's motion"); + run.step(); + assert_eq!(run.rt.state, 2); + let next = radii(&run.rt)[1]; + assert!(next > 4.0 && (next - first).abs() < 1.0, "retarget from {first}, not the intermediate goal: {next}"); + run.play(1.0); + assert_eq!(radii(&run.rt), [10.0, 4.0, 10.0, 10.0]); +} + +#[test] +fn live_tail_motion_gate_joined_faces_share_their_drawn_and_interactive_seam() { + fn view(s: &(u8, u8), _: &mut Cx<(u8, u8)>) -> El { + let split = s.0 == 1; + let prompt = |key, label, hit| col().key(key).w_full().arrives_whole().joined_row_face(label) + .pt(if split { 12.0 } else { 4.0 }).pb(if split { 20.0 } else { 0.0 }) + .child(el().key(label).w_full().h(30.0).hit().fill(Color::WHITE).on_press(move |s: &mut (u8,u8)| s.1 = hit)); + let (a,b) = (prompt("a", "top", 1), prompt("b", "bottom", 2)); + let between = el().key("between").w(20.0).h(36.0); + let order = match s.0 { 0 => [between,a,b], 1 => [a,between,b], _ => [a,b,between] }; + col().w_full().h_full().scroll(ScrollSpec { stick_bottom: true }).child(col().key("rows").w_full() + .growth(GrowthSpec::default()).virtualize(40.0).child(el().key("older").w_full().h(300.0)).children(order)) + } + let mut rt = Runtime::new((0,0), view, (280.0,180.0), Env::new(true,1.0)); + rt.motion.motion_needs_cause = true; + rt.poll = Some(|s,t,tx| { if t < 0.5 || s.0 == 2 { return false; } s.0 += 1; tx.grow_visible_tail("rows"); true }); + let mut run = Run::new(rt,60.0); + while run.rt.state.0 == 0 { assert!(run.rt.t < 0.6); run.step(); } + for step in 0..36 { + let rect = |key| run.rt.paint.drawn[run.rt.tree.nodes.iter().position(|n| n.named(key)).unwrap()]; + let (a,b) = (rect("top"),rect("bottom")); + assert!((b[1]-a[1]-a[3]-4.0).abs()<0.05, "step {step}: {a:?} {b:?}"); + if step == 4 { + for (r,hit) in [(a,1),(b,2)] { run.rt.pointer_down(80.0,r[1]+15.0); run.rt.pointer_up(80.0,r[1]+15.0); run.rt.frame(0.0); assert_eq!(run.rt.state.1,hit); } + } + run.step(); + } +} + +#[test] +fn live_tail_motion_gate_covered_polls_keep_one_request_per_selector() { + let mut pending = Tx::default(); + for _ in 0..32 { + let mut poll = Tx::default(); + poll.grow_visible_tail("left/rows"); + poll.grow_visible_tail("right/rows"); + crate::runtime::action::merge(&mut pending, poll); + } + assert_eq!(pending.live_growth, [("left/rows".into(), false), ("right/rows".into(), false)]); +} diff --git a/app/vendor/rune/crates/rune/src/runtime/virtual_list/pins.rs b/app/vendor/rune/crates/rune/src/runtime/virtual_list/pins.rs new file mode 100644 index 0000000..e628396 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/virtual_list/pins.rs @@ -0,0 +1,246 @@ +//! What a virtual list keeps for text selection between commits: the rows a selection pinned, +//! their selectable texts, and the source every unbuilt row is built from. They change together +//! in [`Pins::sync`], so a commit and a selection change can't leave them disagreeing. + +use std::collections::HashMap; + +use crate::el::{El, SelectionCopy, TextSpec}; + +/// Where an offscreen row comes from: the view's row builder, or the row the view built itself +/// and the list kept by index. One or the other, never both. +pub(crate) enum Source { + /// `El::virtual_rows`: a row is built when selection needs it. + Rebuild(std::rc::Rc<crate::el::virtual_rows::RowSource>), + /// Rows the view built; the ones outside the window are kept in + /// [`PinnedSelection::stored`]. + Stored, +} + +impl Default for Source { + fn default() -> Self { + Source::Stored + } +} + +impl Source { + /// The row builder, when rows are built by index. + pub(crate) fn rebuild(&self) -> Option<&std::rc::Rc<crate::el::virtual_rows::RowSource>> { + match self { + Source::Rebuild(rows) => Some(rows), + Source::Stored => None, + } + } +} + +/// One selectable text inside an offscreen virtual row. +#[derive(Clone, Debug)] +pub(crate) struct OffscreenText { + pub list_path: String, + pub row_key: String, + pub row_index: usize, + pub order_in_row: usize, + pub rel_path: String, + pub path: String, + pub key: Option<String>, + pub group_path: Option<String>, + pub spec: TextSpec, + /// True when this text and the previous selectable text in the same row share a horizontal + /// (`FlexDirection::Row | FlexDirection::RowReverse`) lowest common ancestor (table cells). + pub tab_before: bool, +} + +/// What the last commit collected offscreen rows under: the selection group they belong to and +/// whether the list is inert. They are written together, so they always describe one commit. +#[derive(Clone, Debug, Default)] +pub(crate) struct Scope { + pub group_path: Option<String>, + pub inert: bool, +} + +/// Offscreen selection state retained on a [`crate::el::virtual_list::VirtualList`]. +#[derive(Default)] +pub(crate) struct PinnedSelection { + /// The pinned rows, their texts and the source every unbuilt row comes from. + pub pins: Pins, + /// The rows the view built, by index, while the pins' source is [`Source::Stored`]. Cleared + /// in place at every commit, so its capacity carries over as dev's did, and kept beside the + /// pins so a source change doesn't drop it. + pub stored: HashMap<usize, El>, + pub scope: Scope, +} + +impl std::fmt::Debug for PinnedSelection { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("PinnedSelection") + .field("rows", &self.pins.rows().len()) + .field("texts", &self.pins.texts().len()) + .field("group_path", &self.scope.group_path) + .field("inert", &self.scope.inert) + .finish() + } +} + +/// What a list keeps for text selection. One state, so the pinned rows, their texts and the row +/// source are cleared and filled together. +#[derive(Default)] +pub(crate) enum Pins { + /// The list has not committed yet: nothing pinned and no source to build a row from. + #[default] + None, + /// The selection's rows in this list, the selectable texts built from them, and the source + /// every unbuilt row comes from. `rows` is empty when the list has a source but nothing in it + /// is selected. + Pinned { + /// The selection's anchor and focus rows, anchor first, deduplicated. + rows: Vec<String>, + /// Selectable texts of `rows` that were offscreen when the commit built them. + texts: Vec<OffscreenText>, + /// `selection_copy` providers found beside `texts`. + providers: Vec<(String, SelectionCopy)>, + source: Source, + }, +} + +/// What changes what a list keeps. +pub(crate) enum PinsEvent<'a> { + /// No text is selected: drop the rows and their texts. The source stays. + Clear, + /// The selection's anchor and focus rows in this list (each `None` when that end is not a row + /// of it). They become the pins; texts of other rows go. + Select { + anchor: Option<&'a str>, + focus: Option<&'a str>, + }, + /// A selection request pinned `key` and built the texts for it. + Pin { + key: String, + texts: Vec<OffscreenText>, + providers: Vec<(String, SelectionCopy)>, + }, +} + +impl Pins { + pub(crate) fn rows(&self) -> &[String] { + match self { + Pins::None => &[], + Pins::Pinned { rows, .. } => rows, + } + } + + pub(crate) fn texts(&self) -> &[OffscreenText] { + match self { + Pins::None => &[], + Pins::Pinned { texts, .. } => texts, + } + } + + pub(crate) fn source(&self) -> Option<&Source> { + match self { + Pins::None => None, + Pins::Pinned { source, .. } => Some(source), + } + } + + /// Whether row `key`'s texts are already kept. + pub(crate) fn has_text_row(&self, key: &str) -> bool { + self.texts().iter().any(|t| t.row_key == key) + } + + /// Clears the kept texts and providers in place at the start of a commit. The vectors keep + /// their allocations, and a builder that panics partway leaves what it already collected. + pub(crate) fn clear_texts(&mut self) { + if let Pins::Pinned { texts, providers, .. } = self { + texts.clear(); + providers.clear(); + } + } + + /// The vectors a commit collects a built row's texts into, borrowed from the state so a + /// panic, an early return or a fallback keeps what came before. + pub(crate) fn text_buffers( + &mut self, + ) -> Option<(&mut Vec<OffscreenText>, &mut Vec<(String, SelectionCopy)>)> { + match self { + Pins::None => None, + Pins::Pinned { texts, providers, .. } => Some((texts, providers)), + } + } + + /// Installs the commit's row source, keeping the kept rows, texts and providers. + pub(crate) fn set_source(&mut self, source: Source) { + match self { + Pins::None => { + *self = Pins::Pinned { + rows: Vec::new(), + texts: Vec::new(), + providers: Vec::new(), + source, + }; + } + Pins::Pinned { source: current, .. } => *current = source, + } + } + + /// Applies `event`, keeping the rows, their texts and the source one state that a commit and + /// a selection change can't leave disagreeing. + pub(crate) fn sync(&mut self, event: PinsEvent<'_>) { + match event { + PinsEvent::Clear => { + if let Pins::Pinned { rows, texts, providers, .. } = self { + rows.clear(); + texts.clear(); + providers.clear(); + } + } + PinsEvent::Select { anchor, focus } => { + let (rows, texts, _, _) = self.fields(); + rows.clear(); + if let Some(key) = anchor { + rows.push(key.to_owned()); + } + if let Some(key) = focus + && !rows.iter().any(|r| r == key) + { + rows.push(key.to_owned()); + } + // Dev kept the copy providers across a selection change; only a commit and a + // cleared selection drop them. + texts.retain(|t| rows.iter().any(|r| r == &t.row_key)); + } + PinsEvent::Pin { key, texts, providers } => { + let (rows, current, current_providers, _) = self.fields(); + if !rows.iter().any(|r| r == &key) { + rows.push(key); + } + current.extend(texts); + current_providers.extend(providers); + } + } + } + + /// The mutable parts, turning `None` into a pinned state with a default source when a + /// selection needs one. + fn fields( + &mut self, + ) -> ( + &mut Vec<String>, + &mut Vec<OffscreenText>, + &mut Vec<(String, SelectionCopy)>, + &mut Source, + ) { + if let Pins::None = self { + *self = Pins::Pinned { + rows: Vec::new(), + texts: Vec::new(), + providers: Vec::new(), + source: Source::default(), + }; + } + let Pins::Pinned { rows, texts, providers, source } = self else { unreachable!() }; + (rows, texts, providers, source) + } +} + +#[cfg(test)] +#[path = "pins_tests.rs"] +mod tests; diff --git a/app/vendor/rune/crates/rune/src/runtime/virtual_list/pins_tests.rs b/app/vendor/rune/crates/rune/src/runtime/virtual_list/pins_tests.rs new file mode 100644 index 0000000..d1c1e5b --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/virtual_list/pins_tests.rs @@ -0,0 +1,595 @@ +//! The pins state against origin/dev's separate fields: every order of a selection change, a +//! live pin, a commit, a builder panic and a remount fallback, compared after every event. +use std::panic::{AssertUnwindSafe, catch_unwind}; +use std::rc::Rc; + +use super::{Pins, PinsEvent, Source}; +use crate::runtime::selectable::virtual_selection::{ + collect_row_into_pins, collect_virtual_row_selection, +}; +use crate::El; + +/// The fixture's offscreen rows, in child order, with their indices. A longer list keys its +/// later rows `r{i}`. +const ROWS: [&str; 3] = ["a", "b", "c"]; + +fn index_of(key: &str) -> usize { + ROWS.iter() + .position(|r| *r == key) + .or_else(|| key.strip_prefix('r')?.parse().ok()) + .expect("a fixture row") +} + +fn key_of(i: usize) -> String { + ROWS.get(i).map_or_else(|| format!("r{i}"), |key| (*key).to_owned()) +} + +/// The row a builder returns: one selectable text with a copy provider on the row. +fn row_el(key: &str) -> El { + crate::col() + .key(key.to_owned()) + .selection_copy(|_| None) + .child(crate::text("text").key("t0").selectable(true)) +} + +/// Collects `key`'s texts the way a commit does, into the state itself. +fn write(pins: &mut Pins, key: &str) { + collect_row_into_pins(pins, &row_el(key), "/list", key, index_of(key), None, false); +} + +/// The texts and provider `row_el` gives for `key`, written out rather than run through the +/// collector, so the reference never calls production code. +fn collected(key: &str) -> (Vec<(String, String)>, Vec<String>) { + (vec![(key.to_owned(), format!("/list/{key}/t0"))], vec![format!("/list/{key}")]) +} + +fn source(name: &'static str) -> Source { + match name { + "rebuild" => Source::Rebuild(Rc::new(crate::el::virtual_rows::RowSource::new::<()>( + 0, + |_, _| "".into(), + |_, _| crate::el(), + ))), + "stored" => Source::Stored, + _ => unreachable!("{name}"), + } +} + +fn source_name(source: &Source) -> &'static str { + if source.rebuild().is_some() { "rebuild" } else { "stored" } +} + +/// Which commit dev runs, since each fills the kept rows in its own order. +#[derive(Clone, Copy, PartialEq, Eq)] +enum Kind { + /// `populate_virtual_children` for `El::virtual_rows`: a focused row first, then pinned rows. + Indexed, + /// `populate_virtual_children` for rows the view built: every kept child in child order. + Stored, + /// `remount_virtuals`: a focused row first, then pinned rows, keeping the source. + Remount, +} + +/// One thing that can change what a list keeps. +#[derive(Clone, Copy)] +enum Ev { + Clear, + Select(Option<&'static str>, Option<&'static str>), + Pin(&'static str), + Commit(Kind, Option<&'static str>), + /// A row builder panics at build step `at`; `catch_unwind` catches it like the runtime does. + Panic(Kind, Option<&'static str>, usize), + /// A remount falls back when an entering row holds a nested virtual list, either in this list + /// or in one before it. + Fallback(Boundary), +} + +/// Where a remount's fallback falls relative to this list. It is found among a list's entering +/// rows, which build after that list's focused and pinned rows, and it skips every later list. +#[derive(Clone, Copy, PartialEq, Eq)] +enum Boundary { + /// This list's entering row (with the given focused row): its pins are already collected. + Here(Option<&'static str>), + /// An earlier list's entering row: this list was cleared while planning and builds nothing. + Earlier, +} + +const EVENTS: [Ev; 12] = [ + Ev::Clear, + Ev::Select(Some("a"), Some("b")), + Ev::Select(Some("a"), None), + Ev::Pin("a"), + Ev::Pin("b"), + Ev::Commit(Kind::Indexed, None), + Ev::Commit(Kind::Indexed, Some("b")), + Ev::Commit(Kind::Stored, None), + Ev::Commit(Kind::Remount, None), + Ev::Panic(Kind::Stored, None, 1), + Ev::Fallback(Boundary::Here(Some("b"))), + Ev::Fallback(Boundary::Earlier), +]; + +fn name(event: Ev) -> &'static str { + match event { + Ev::Clear => "clear", + Ev::Select(Some("a"), Some("b")) => "select(a,b)", + Ev::Select(Some("a"), None) => "select(a,-)", + Ev::Select(..) => "select(-,-)", + Ev::Pin("a") => "pin(a)", + Ev::Pin(_) => "pin(b)", + Ev::Commit(Kind::Indexed, None) => "commit(indexed)", + Ev::Commit(Kind::Indexed, _) => "commit(indexed,b)", + Ev::Commit(Kind::Stored, _) => "commit(stored)", + Ev::Commit(Kind::Remount, _) => "commit(remount)", + Ev::Panic(Kind::Indexed, ..) => "panic(indexed,1)", + Ev::Panic(Kind::Stored, ..) => "panic(stored,1)", + Ev::Panic(..) => "panic(remount,1)", + Ev::Fallback(Boundary::Here(_)) => "fallback(here,b)", + Ev::Fallback(Boundary::Earlier) => "fallback(earlier)", + } +} + +/// The steps a commit builds, in dev's order. +fn steps(pins: &Pins, kind: Kind, focused: Option<&str>) -> Vec<String> { + match kind { + // `measure.rs` enumerates the stored children, so the kept texts come in child order + // however the pins were made. + Kind::Stored => ROWS.iter().map(|r| (*r).to_owned()).collect(), + // `measure.rs` and `remount.rs` build the focused row first, then the pinned rows in pin + // order (anchor then focus), skipping the focused one again. + Kind::Indexed | Kind::Remount => { + let mut steps: Vec<String> = focused.map(str::to_owned).into_iter().collect(); + steps.extend(pins.rows().iter().filter(|r| Some(r.as_str()) != focused).cloned()); + steps + } + } +} + +/// One commit through the state under test, stopping at `stop` the way a panic does: what it +/// already wrote stays in the state. +fn commit(pins: &mut Pins, kind: Kind, focused: Option<&'static str>, stop: Option<usize>) { + pins.clear_texts(); + if kind == Kind::Stored { + // `measure.rs` installs the stored source before the children loop. + pins.set_source(source("stored")); + } + for (step, key) in steps(pins, kind, focused).into_iter().enumerate() { + if stop == Some(step) { + catch_unwind(AssertUnwindSafe(|| panic!("row builder"))).ok(); + return; + } + if pins.rows().iter().any(|r| *r == key) { + write(pins, &key); + } + } + if kind == Kind::Indexed { + pins.set_source(source("rebuild")); + } +} + +fn apply(pins: &mut Pins, event: Ev) { + match event { + Ev::Clear => pins.sync(PinsEvent::Clear), + Ev::Select(anchor, focus) => pins.sync(PinsEvent::Select { anchor, focus }), + Ev::Pin(key) => { + let (texts, providers) = if pins.has_text_row(key) { + (Vec::new(), Vec::new()) + } else { + let (mut texts, mut providers) = (Vec::new(), Vec::new()); + collect_virtual_row_selection( + &row_el(key), "/list", key, index_of(key), None, false, &mut texts, &mut providers, + ); + (texts, providers) + }; + pins.sync(PinsEvent::Pin { key: key.to_owned(), texts, providers }); + } + Ev::Commit(kind, focused) => commit(pins, kind, focused, None), + Ev::Panic(kind, focused, at) => commit(pins, kind, focused, Some(at)), + // The remount collects this list's rows and then meets the nested list among its + // entering rows, which write nothing to the pins. + Ev::Fallback(Boundary::Here(focused)) => commit(pins, Kind::Remount, focused, None), + // Planning cleared this list; the loop broke out before reaching it. + Ev::Fallback(Boundary::Earlier) => pins.clear_texts(), + } +} + +/// origin/dev's pin state, transcribed as it was: `VirtualList::pinned_rows` beside +/// `PinnedSelection { texts, copy_providers, source }`, cleared and filled by +/// `sync_selection_pins`, `populate_virtual_children`, `remount_virtuals` and +/// `pin_offscreen_row`. It is never edited to fit the branch: a failed walk means the branch +/// differs from dev. +#[derive(Default)] +struct Dev { + pinned_rows: Vec<String>, + /// Each kept text as `(row key, path)`, which is all dev's state decides for a walk. + texts: Vec<(String, String)>, + providers: Vec<String>, + source: Option<&'static str>, +} + +impl Dev { + fn push(&mut self, key: &str) { + let (texts, providers) = collected(key); + self.texts.extend(texts); + self.providers.extend(providers); + } + + fn pinned_indices(&self) -> Vec<usize> { + self.pinned_rows.iter().map(|r| index_of(r)).collect() + } + + fn apply(&mut self, event: Ev) { + match event { + // `clear_text_selection` -> `sync_selection_pins` with no selection. + Ev::Clear => { + self.pinned_rows.clear(); + self.texts.clear(); + self.providers.clear(); + } + // `sync_selection_pins` with a selection. + Ev::Select(anchor, focus) => { + self.pinned_rows.clear(); + if let Some(key) = anchor { + self.pinned_rows.push(key.to_owned()); + } + if let Some(key) = focus + && !self.pinned_rows.iter().any(|r| r == key) + { + self.pinned_rows.push(key.to_owned()); + } + self.texts.retain(|(row, _)| self.pinned_rows.iter().any(|r| r == row)); + } + // `pin_offscreen_row`, which pushes the row and adds its texts unless they are kept. + Ev::Pin(key) => { + let already = self.texts.iter().any(|(row, _)| row == key); + if !self.pinned_rows.iter().any(|r| r == key) { + self.pinned_rows.push(key.to_owned()); + } + if !already { + self.push(key); + } + } + Ev::Commit(kind, focused) => self.commit(kind, focused, None), + Ev::Panic(kind, focused, at) => self.commit(kind, focused, Some(at)), + Ev::Fallback(at) => self.remount_falling_back(at), + } + } + + /// `remount_virtuals` (remount.rs:202–203 and 266–320) when an entering row holds a nested + /// virtual list. Planning clears every list's texts and providers first; the build loop then + /// runs list by list in tree order, and within a list builds the focused row, then the + /// pinned rows, then the entering rows, where the nested list sets `nested_virtual` and + /// breaks out of that list and every later one. The source is never touched. + fn remount_falling_back(&mut self, at: Boundary) { + // The plan loop, for every list. + self.texts.clear(); + self.providers.clear(); + let pinned = self.pinned_indices(); + // The build loop broke out in an earlier list, so it never reaches this one. + let Boundary::Here(focused) = at else { return }; + let focused = focused.map(index_of); + if let Some(i) = focused + && pinned.contains(&i) + { + self.push(&key_of(i)); + } + for &i in &pinned { + if Some(i) == focused { + continue; + } + self.push(&key_of(i)); + } + // The entering rows: the first one holding a nested virtual list breaks here, with + // this list's focused and pinned rows already collected. + } + + /// Dev's three commit paths, written as they are: each clears the texts and providers in + /// place and writes each built row's texts straight into the retained list. + fn commit(&mut self, kind: Kind, focused: Option<&'static str>, stop: Option<usize>) { + self.texts.clear(); + self.providers.clear(); + match kind { + // measure.rs:565 installs the source before the children loop, then enumerates the + // children, collecting only the pinned ones. + Kind::Stored => { + self.source = Some("stored"); + let pinned = self.pinned_indices(); + for i in 0..ROWS.len() { + if stop == Some(i) { + return; + } + if pinned.contains(&i) { + self.push(&key_of(i)); + } + } + } + // measure.rs builds a focused offscreen row first, then the pinned rows, and + // installs the source after collecting (line 550). + Kind::Indexed | Kind::Remount => { + let pinned = self.pinned_indices(); + let mut steps: Vec<usize> = focused.map(index_of).into_iter().collect(); + steps.extend(pinned.iter().copied().filter(|i| Some(*i) != focused.map(index_of))); + for (step, i) in steps.iter().enumerate() { + if stop == Some(step) { + return; + } + if pinned.contains(i) { + self.push(&key_of(*i)); + } + } + if kind == Kind::Indexed { + self.source = Some("rebuild"); + } + } + } + } + + fn view(&self) -> (Vec<String>, Vec<(String, String)>, Vec<String>, Option<&'static str>) { + (self.pinned_rows.clone(), self.texts.clone(), self.providers.clone(), self.source) + } +} + +fn view(pins: &Pins) -> (Vec<String>, Vec<(String, String)>, Vec<String>, Option<&'static str>) { + let rows = pins.rows().to_vec(); + let texts = pins.texts().iter().map(|t| (t.row_key.clone(), t.path.clone())).collect(); + let providers = match pins { + Pins::None => Vec::new(), + Pins::Pinned { providers, .. } => providers.iter().map(|(path, _)| path.clone()).collect(), + }; + (rows, texts, providers, pins.source().map(source_name)) +} + +/// Every sequence of up to five events after the commit a list must have before it can pin, +/// each driven through the one state and compared with dev's fields after every event. +#[test] +fn every_order_of_pins_commits_panics_and_fallbacks_keeps_what_dev_keeps() { + const LONGEST: u32 = 5; + for len in 1..=LONGEST { + for bits in 0..(EVENTS.len() as u32).pow(len) { + let mut n = bits; + let order: Vec<Ev> = (0..len) + .map(|_| { + let i = (n % EVENTS.len() as u32) as usize; + n /= EVENTS.len() as u32; + EVENTS[i] + }) + .collect(); + let walk = order.iter().map(|e| name(*e)).collect::<Vec<_>>().join(", "); + // A virtual list exists only after a commit, so its source is set before any + // selection can pin a row. + let (mut pins, mut dev) = (Pins::None, Dev::default()); + apply(&mut pins, Ev::Commit(Kind::Stored, None)); + dev.apply(Ev::Commit(Kind::Stored, None)); + assert_eq!(view(&pins), dev.view(), "the first commit"); + for (step, &event) in order.iter().enumerate() { + apply(&mut pins, event); + dev.apply(event); + assert_eq!(view(&pins), dev.view(), "step {step} of {walk}"); + } + } + } +} + +/// `measure.rs` enumerates stored children, so a stored commit keeps its texts in child order +/// however the pins were made; an indexed one builds a focused pinned row first. +#[test] +fn a_stored_commit_orders_texts_by_child_while_an_indexed_one_builds_the_focused_row_first() { + let (mut pins, mut dev) = (Pins::None, Dev::default()); + for event in [ + Ev::Commit(Kind::Stored, None), + Ev::Pin("b"), + Ev::Pin("a"), + Ev::Commit(Kind::Stored, None), + ] { + apply(&mut pins, event); + dev.apply(event); + assert_eq!(view(&pins), dev.view(), "{}", name(event)); + } + let stored: Vec<&str> = pins.texts().iter().map(|t| t.row_key.as_str()).collect(); + assert_eq!(stored, ["a", "b"], "stored children in index order, not pin order"); + + apply(&mut pins, Ev::Commit(Kind::Indexed, Some("b"))); + dev.apply(Ev::Commit(Kind::Indexed, Some("b"))); + assert_eq!(view(&pins), dev.view()); + let indexed: Vec<&str> = pins.texts().iter().map(|t| t.row_key.as_str()).collect(); + assert_eq!(indexed, ["b", "a"], "the focused pinned row builds first"); +} + +/// A builder that panics keeps the pinned rows' texts and providers collected before it, and +/// the source dev had installed by then. +#[test] +fn a_panicking_builder_keeps_the_pins_collected_before_it() { + for kind in [Kind::Indexed, Kind::Stored] { + let (mut pins, mut dev) = (Pins::None, Dev::default()); + for event in [Ev::Commit(Kind::Stored, None), Ev::Pin("a"), Ev::Pin("b")] { + apply(&mut pins, event); + dev.apply(event); + } + // An indexed commit starts from the stored source, so a late installed one differs. + if kind == Kind::Indexed { + apply(&mut pins, Ev::Commit(Kind::Indexed, None)); + dev.apply(Ev::Commit(Kind::Indexed, None)); + } + let event = Ev::Panic(kind, None, 1); + apply(&mut pins, event); + dev.apply(event); + assert_eq!(view(&pins), dev.view(), "{}", name(event)); + assert_eq!(pins.texts().len(), 1, "row a survives the panic building b"); + assert_eq!(pins.texts()[0].row_key, "a", "the already collected pin stays first"); + // A stored commit installs its source before the loop; an indexed one only after it, so + // an interrupted indexed commit keeps the stored source it began with. + let expected = if kind == Kind::Indexed { "rebuild" } else { "stored" }; + assert_eq!(pins.source().map(source_name), Some(expected), "{}", name(event)); + } +} + +/// Clearing for a commit, a remount fallback and a source change keep the texts' and +/// providers' allocations; nothing is taken out of the state. +#[test] +fn a_commit_fallback_and_source_change_keep_the_texts_allocation() { + let mut pins = Pins::None; + pins.set_source(Source::Stored); + write(&mut pins, "a"); + write(&mut pins, "b"); + let capacity = pins.text_buffers().expect("a committed list").0.capacity(); + assert!(capacity >= 2); + + pins.clear_texts(); + assert!(pins.texts().is_empty()); + assert!( + pins.text_buffers().expect("a committed list").0.capacity() >= capacity, + "a commit clears in place" + ); + + pins.set_source(source("rebuild")); + assert!( + pins.text_buffers().expect("a committed list").0.capacity() >= capacity, + "a source change keeps the buffers" + ); + write(&mut pins, "a"); + assert_eq!(pins.texts().len(), 1, "and the next commit refills them"); +} + +/// Dev's remount collects every pinned row of the list that falls back before it reaches the +/// entering row holding a nested list: a focused pinned `b`, then `a`. +#[test] +fn a_fallback_in_this_list_keeps_all_its_pins_and_one_before_it_keeps_none() { + let start = [Ev::Commit(Kind::Stored, None), Ev::Select(Some("a"), Some("b")), Ev::Commit(Kind::Indexed, None)]; + for (at, expected) in [(Boundary::Here(Some("b")), vec!["b", "a"]), (Boundary::Earlier, vec![])] { + let (mut pins, mut dev) = (Pins::None, Dev::default()); + for event in start.into_iter().chain([Ev::Fallback(at)]) { + apply(&mut pins, event); + dev.apply(event); + assert_eq!(view(&pins), dev.view(), "{}", name(event)); + } + let kept: Vec<&str> = pins.texts().iter().map(|t| t.row_key.as_str()).collect(); + assert_eq!(kept, expected, "{}", name(Ev::Fallback(at))); + } +} + +/// Rows of the two-list fixture. From `NESTED` on, every row holds a nested virtual list, so a +/// remount that has one enter falls back. +const LIST_ROWS: usize = 400; +const NESTED: usize = 150; +const ROW_H: f32 = 20.0; + +struct Lists; + +fn list_row(_: &Lists, i: usize) -> El { + let row = crate::col() + .w_full() + .h(ROW_H) + .selection_copy(|_| None) + .child(crate::text(format!("row {i}")).key("t0").w_full().selectable(true)); + if i < NESTED { row } else { row.child(crate::col().key("inner").virtualize(ROW_H)) } +} + +fn lists_view(_: &Lists, _: &mut crate::Cx<Lists>) -> El { + let list = |name: &'static str| { + crate::col().key(format!("s{name}")).w_full().grow(1.0).scroll(crate::ScrollSpec { stick_bottom: false }).child( + crate::col() + .key(name) + .w_full() + .growth(crate::GrowthSpec::default()) + .selection_group(true) + .virtual_rows(LIST_ROWS, ROW_H, |_: &Lists, i| key_of(i).into(), list_row), + ) + }; + crate::col().w_full().h_full().children([list("one"), list("two")]) +} + +fn lists() -> crate::Runtime<Lists> { + let mut rt = crate::Runtime::new(Lists, lists_view, (640.0, 420.0), crate::Env::new(true, 2.0)); + rt.frame(0.0); + while rt.frame(1.0 / 120.0) {} + rt +} + +fn list_path(rt: &crate::Runtime<Lists>, name: &str) -> String { + let suffix = format!("/{name}"); + rt.commit.virtuals.keys().find(|p| p.ends_with(&suffix)).expect("a mounted list").clone() +} + +/// Selects all of list `name`, pinning its first and last rows, and wheels it (at height `y`) +/// to the middle, where neither is mounted and no nested row is yet. +fn select_all_and_scroll(rt: &mut crate::Runtime<Lists>, name: &'static str, y: f32) { + rt.update(|_, tx| tx.select_all_text(name)); + rt.frame(1.0 / 60.0); + let path = list_path(rt, name); + for _ in 0..40 { + if rt.commit.virtuals[&path].range.start > 40 { + break; + } + rt.wheel(320.0, y, -200.0); + rt.frame(1.0 / 60.0); + } + for _ in 0..40 { + if !rt.frame(1.0 / 60.0) { + break; + } + } + let range = rt.commit.virtuals[&path].range.clone(); + assert!(range.start > 1 && range.end < NESTED, "{name} scrolled to the middle: {range:?}"); +} + +/// Moves list `name` straight into its nested rows and runs the real remount on its own. +fn remount_into_nested(rt: &mut crate::Runtime<Lists>, name: &str) -> bool { + let scroll = rt.commit.virtuals[&list_path(rt, name)].scroll_path.clone(); + let id = rt.tree.path_ids[&scroll]; + rt.scroll.scrolls.get_mut(&id).expect("the list's scroll").offset = ((NESTED + 20) as f32 * ROW_H) as f64; + rt.remount_falls_back() +} + +/// The pinned rows, the rows of the kept texts and the rows of the kept providers. +type Kept = (Vec<String>, Vec<String>, Vec<String>); + +fn kept(pins: &Pins) -> Kept { + let (_, texts, providers, _) = view(pins); + let row = |path: String| path.rsplit('/').next().unwrap_or_default().to_owned(); + (pins.rows().to_vec(), texts.into_iter().map(|(key, _)| key).collect(), providers.into_iter().map(row).collect()) +} + +fn dev_kept(dev: &Dev) -> Kept { + let row = |path: &String| path.rsplit('/').next().unwrap_or_default().to_owned(); + (dev.pinned_rows.clone(), dev.texts.iter().map(|(key, _)| key.clone()).collect(), dev.providers.iter().map(row).collect()) +} + +/// The real remount, falling back in the list whose pins it is collecting, keeps what dev's +/// remount keeps: every pinned row, collected before the entering rows. +#[test] +fn the_real_remount_collects_this_lists_pins_before_it_falls_back() { + let mut rt = lists(); + select_all_and_scroll(&mut rt, "one", 100.0); + let path = list_path(&rt, "one"); + let mut dev = Dev::default(); + for event in [Ev::Select(Some("a"), Some("r399")), Ev::Commit(Kind::Remount, None)] { + dev.apply(event); + } + assert_eq!(kept(&rt.commit.virtuals[&path].selection.pins), dev_kept(&dev), "before the fallback"); + + assert!(remount_into_nested(&mut rt, "one"), "a nested list entering falls back"); + dev.apply(Ev::Fallback(Boundary::Here(None))); + assert_eq!(kept(&rt.commit.virtuals[&path].selection.pins), dev_kept(&dev), "after the fallback"); +} + +/// A list after the one that falls back keeps its pins, and its texts are cleared in place, +/// as dev's planning loop leaves them. +#[test] +fn the_real_remount_clears_later_lists_in_place_when_an_earlier_one_falls_back() { + let mut rt = lists(); + select_all_and_scroll(&mut rt, "two", 310.0); + let path = list_path(&rt, "two"); + let mut dev = Dev::default(); + for event in [Ev::Select(Some("a"), Some("r399")), Ev::Commit(Kind::Remount, None)] { + dev.apply(event); + } + assert_eq!(kept(&rt.commit.virtuals[&path].selection.pins), dev_kept(&dev), "before the fallback"); + let pins = &mut rt.commit.virtuals.get_mut(&path).expect("list two").selection.pins; + let capacity = pins.text_buffers().expect("a committed list").0.capacity(); + + assert!(remount_into_nested(&mut rt, "one"), "a nested list entering list one falls back"); + dev.apply(Ev::Fallback(Boundary::Earlier)); + let pins = &mut rt.commit.virtuals.get_mut(&path).expect("list two").selection.pins; + assert_eq!(kept(pins), dev_kept(&dev), "after the fallback"); + assert!(pins.text_buffers().expect("a committed list").0.capacity() >= capacity, "cleared in place"); +} diff --git a/app/vendor/rune/crates/rune/src/runtime/virtual_list/row_reorder.rs b/app/vendor/rune/crates/rune/src/runtime/virtual_list/row_reorder.rs new file mode 100644 index 0000000..7bd5ea9 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/virtual_list/row_reorder.rs @@ -0,0 +1,116 @@ +//! Rows a commit reorders in a growth stack, and so in a virtual list, slide from where they +//! were drawn into their new places. A growth stack owns its rows' vertical places and lays them +//! out at once, so without this a reordered row would jump there in one frame. +//! +//! Only a change of order counts. The rows a stack held before and after the commit are placed +//! twice, in their old order and in their new one, each at its presented height, and a row slides +//! by the difference. Rows that kept their order relative to each other (the old places that +//! still increase) place the same unless a moved row passed them, which moves them by its +//! height. Rows that came or went, window shifts, estimate corrections and height changes move +//! no row here: growth carries those, as it does a row inserted or removed above another. +use super::*; + +#[path = "handoff.rs"] +pub(in crate::runtime) mod handoff; +pub(in crate::runtime) mod joined; + +/// One growth stack's rows that the last commit reordered. +#[derive(Clone, Debug, Default)] +pub(in crate::runtime) struct Reorder { + /// How far each moved row's top jumped: where it was drawn, less where it now lays out. + jumps: HashMap<NodeId, f32>, +} + +impl Reorder { + /// Measures a commit taking the stack from `old` to `new` presented order, given each row's + /// presented height (`None` for a row with none) and the gap between rows. A commit that + /// lands its changes (`animates` false) moves nothing. + pub(in crate::runtime) fn measure(&mut self, animates: bool, old: &[NodeId], new: &[NodeId], gap: f32, h: impl Fn(NodeId) -> Option<f32>) { + self.jumps.clear(); + if !animates || old == new { return; } + let old_at: HashMap<NodeId, usize> = old.iter().enumerate().filter(|(_, id)| h(**id).is_some()).map(|(k, id)| (*id, k)).collect(); + let kept: Vec<(NodeId, usize)> = new.iter().filter_map(|id| old_at.get(id).map(|&k| (*id, k))).collect(); + if kept.windows(2).all(|w| w[0].1 < w[1].1) { return; } + let mut before: Vec<(usize, NodeId)> = kept.iter().map(|&(id, k)| (k, id)).collect(); + before.sort_unstable_by_key(|&(k, _)| k); + let mut top = 0.0; + let mut was: HashMap<NodeId, f32> = HashMap::default(); + for (_, id) in before { + was.insert(id, top); + top += h(id).unwrap_or(0.0) + gap; + } + let mut top = 0.0; + for (id, _) in kept { + let jump = was[&id] - top; + if jump.abs() > 1.0 / 64.0 { self.jumps.insert(id, jump); } + top += h(id).unwrap_or(0.0) + gap; + } + } + + pub(in crate::runtime) fn jump(&self, id: NodeId) -> f32 { + self.jumps.get(&id).copied().unwrap_or(0.0) + } +} + +#[derive(Clone, Copy)] +pub(in crate::runtime) struct LiveRow { + pub ink: bool, + /// Some(0) for a resizing row: its inset still rides its height. + pub shift: Option<f32>, + /// A row that stays put can gain or lose a joined corner as its neighbour moves. + pub joins: bool, +} + +impl RuntimeCore { + pub(in crate::runtime) fn live_row(&self, row: &Node, reorder: &Reorder, ink: bool, joins: bool, list: &crate::el::virtual_list::VirtualList, range: &std::ops::Range<usize>) -> Option<(NodeId, LiveRow)> { + let jump = reorder.jump(row.id); + let shift = (jump != 0.0 || ink && self.motion.grows.get(&row.id).is_some_and(|g| g.moving())).then_some(jump); + if shift.is_none() && !joins { return None; } + let key = row.key.as_deref()?; + (range.contains(&list.index_of(key)?) && list.drawn.iter().any(|old| old == key)).then_some((row.id, LiveRow { ink, shift, joins })) + } + + /// Only a virtual list already showing its tail, in the same viewport, can grow it for a + /// live arrival. If its viewport changes height too (a tray closing under it), landing + /// both together avoids first moving by the tray's height and then back by the row's. + pub(in crate::runtime) fn live_tail(&self, nodes: &[Node], i: usize, tx: &Tx, stack: &mut Stack) -> Option<std::ops::Range<usize>> { + let node = &nodes[i]; + if tx.commit != Commit::Unprompted || node.instant_changes || !tx.live_growth.iter().any(|(key, _)| node.named(key)) { return None; } + let list = self.commit.virtuals.get(&node.path)?; + let scroll = self.tree.id_of_path(&list.scroll_path)?; + if list.nested || list.replaced_view() || list.drawn.is_empty() || !self.scroll.scrolls.get(&scroll)?.pinned() { return None; } + // The list's own tail is the viewport's tail only if nothing extends below it. + // A toolbar *after* the list may cover even its last overscanned rows. + let parent = node.parent?; + if nodes[parent].id != scroll || nodes[i + 1..].iter().take_while(|n| n.parent >= Some(parent)) + .any(|n| n.parent == Some(parent) && n.target[3] > node.target[3]) { return None; } + let range = list.visible_range(0.0, true); + if (stack.viewport_height - list.viewport).abs() >= 1.0 / 64.0 { + let (_, row, room) = tx.tail_rooms.iter().rev().find(|(key, _, _)| node.named(key))?; + if !range.contains(&list.index_of(row)?) { return None; } + stack.handoff = self.tree.tail_handoff(&self.scene, &self.motion.grows, nodes, i, parent, row, room)?; + } + Some(range) + } + + /// How far node `i`, a growth row, jumped because its stack's rows changed order this commit. + pub(in crate::runtime) fn reorder_jump(&self, nodes: &[Node], i: usize) -> f32 { + nodes[i].parent.and_then(|p| self.motion.stacks.get(&nodes[p].id)).map_or(0.0, |s| s.reorder.jump(nodes[i].id)) + } + + /// Starts row `id`'s offset `jump` points down from where it shows, so it stays where it was + /// drawn, and springs it to `to` on `anim`, keeping the speed it had. + pub(in crate::runtime) fn slide_reordered(&mut self, id: NodeId, jump: f32, to: rune_motion::Vec2, anim: Anim) { + let now = self.scene.get(id, prop::OFFSET).unwrap_or(rune_motion::Vec2::ZERO); + let speed = self.scene.store().velocity(id, prop::OFFSET).filter(|v| *v != rune_motion::Vec2::ZERO); + self.scene.set(id, prop::OFFSET, rune_motion::Vec2::new(now.x, now.y + jump)); + self.scene.animate(id, prop::OFFSET, to, anim); + if let Some(v) = speed { + self.scene.store_mut().animate_with_velocity(id, prop::OFFSET, to, v, anim); + } + } +} + +#[cfg(test)] +#[path = "../row_reorder_tests.rs"] +mod tests; diff --git a/app/vendor/rune/crates/rune/src/runtime/virtual_list/row_reorder/joined.rs b/app/vendor/rune/crates/rune/src/runtime/virtual_list/row_reorder/joined.rs new file mode 100644 index 0000000..504a114 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/virtual_list/row_reorder/joined.rs @@ -0,0 +1,139 @@ +//! A run of already visible faces uses its trailing face as its coordinate. Reordering +//! selects the real rows immediately; only the presented seam is shared. A row passing +//! between two faces opens that seam as its presented edge reaches it. +use super::*; + +#[derive(Clone, Copy, Debug)] +struct Face { + row: NodeId, + ink: NodeId, + height: f32, +} + +#[derive(Clone, Copy, Debug)] +enum Boundary { + Joined { raw_from: f32 }, + Opening { between: NodeId }, +} + +#[derive(Clone, Copy, Debug)] +pub(in crate::runtime) struct Seam { + top: Face, + bottom: Face, + from: f32, + raw: f32, + boundary: Boundary, +} + +impl RuntimeCore { + pub(in crate::runtime) fn join_live_rows( + &self, + stack: &mut Stack, + nodes: &[Node], + rows: &[usize], + list: &crate::el::virtual_list::VirtualList, + range: &std::ops::Range<usize>, + ) { + let old = std::mem::take(&mut stack.seams); + if stack.reorder.jumps.is_empty() && old.is_empty() { + return; + } + let mut previous: Option<(usize, Face, f32)> = None; + let mut saved = paint_tracks::Finder::default(); + for (at, &r) in rows.iter().enumerate() { + let Some(key) = nodes[r].vis.row_face else { continue }; + if !nodes[r].whole || nodes[r].streaming || nodes[r].instant_changes { + previous = None; + continue; + } + let Some(i) = + (r..nodes.len()).take_while(|&j| j == r || nodes[j].parent.is_some_and(|p| p >= r)).find(|&j| nodes[j].named(key)) + else { + previous = None; + continue; + }; + let face = Face { row: nodes[r].id, ink: nodes[i].id, height: nodes[i].local.h }; + let seen = nodes[r] + .key + .as_deref() + .is_some_and(|k| list.index_of(k).is_some_and(|p| range.contains(&p)) && list.drawn.iter().any(|s| s == k)); + let Some(ink) = saved + .find(&self.tree.nodes, face.ink) + .and_then(|oi| self.paint.drawn.get(oi)) + .filter(|d| seen && d[3] > 0.0 && (d[3] - nodes[i].local.h).abs() < 0.1) + else { + previous = None; + continue; + }; + let Some((prev, top, edge)) = previous.replace((at, face, ink[1] + ink[3])) else { continue }; + let joined = prev + 1 == at; + let was_joined = stack.order.windows(2).any(|w| w == [top.row, face.row]); + let kept = old.iter().find(|s| s.top.row == top.row && s.bottom.row == face.row); + if !joined && !was_joined && kept.is_none() { + continue; + } + if kept.is_none() && stack.reorder.jump(top.row) == 0.0 && stack.reorder.jump(face.row) == 0.0 { + continue; + } + let from = ink[1] - edge; + let raw = kept.map_or(from, |s| s.raw); + let boundary = + if joined { Boundary::Joined { raw_from: raw } } else { Boundary::Opening { between: nodes[rows[prev + 1]].id } }; + stack.seams.push(Seam { top, bottom: face, from, raw, boundary }); + } + } + + pub(in crate::runtime) fn place_joined_rows(&mut self) { + for stack in self.motion.stacks.values_mut().filter(|s| !s.seams.is_empty()) { + // Trailing to leading: a third face inherits the same boundary, not a new spring. + for seam in stack.seams.iter_mut().rev() { + let indices = |f: Face| Some((self.tree.index_of_id(f.row)?, self.tree.index_of_id(f.ink)?)); + let (Some((a, i)), Some((b, j))) = (indices(seam.top), indices(seam.bottom)) else { continue }; + if self.tree.nodes[i].local.h != seam.top.height || self.tree.nodes[j].local.h != seam.bottom.height { + continue; + } + let top = |row: usize, ink: usize, dy: &[f32]| { + self.scene.presented(self.tree.nodes[ink].id).map(|p| { + p.rect.y + + std::iter::successors(Some(ink), |&k| self.tree.nodes[k].parent.filter(|&q| q >= row)).map(|k| dy[k]).sum::<f32>() + }) + }; + let (Some(ay), Some(by)) = (top(a, i, &self.paint.row_dy), top(b, j, &self.paint.row_dy)) else { continue }; + let end = ay + self.tree.nodes[i].local.h; + let raw = by - end; + let goal = self.tree.nodes[j].target[1] - self.tree.nodes[i].target[3]; + let want = match seam.boundary { + Boundary::Joined { raw_from } => { + let left = if (raw_from - goal).abs() < 0.01 { 0.0 } else { ((raw - goal) / (raw_from - goal)).clamp(0.0, 1.0) }; + goal + (seam.from - goal) * left + } + Boundary::Opening { between } => { + let Some(k) = self.tree.index_of_id(between) else { continue }; + let Some(y) = top(k, k, &self.paint.row_dy) else { continue }; + let depth = self.tree.nodes[k].target[3] - self.tree.nodes[i].target[3]; + let t = ((y + self.paint.row_h[k] - end) / depth.max(1.0)).clamp(0.0, 1.0); + seam.from + (raw - seam.from) * t * t * (3.0 - 2.0 * t) + } + }; + seam.raw = raw; + self.paint.row_dy[a] += raw - want; + // These complete faces were both visible before the reorder and have not + // grown. Only their surrounding room changes. Don't composite their words + // through a reveal layer; new rows and streaming edges retain their masks. + for r in [a, b] { + if self.motion.grows.get(&self.tree.nodes[r].id).is_some_and(|g| g.whole && g.linear_edge) { + self.paint.row_mask[r] = -1.0; + } + } + } + if !stack.moving + && !stack + .seams + .iter() + .any(|s| [s.top.row, s.bottom.row].iter().any(|&id| self.scene.store().is_animating(id, prop::OFFSET))) + { + stack.seams.clear(); + } + } + } +} diff --git a/app/vendor/rune/crates/rune/src/runtime/virtual_list/selection.rs b/app/vendor/rune/crates/rune/src/runtime/virtual_list/selection.rs new file mode 100644 index 0000000..e9d3bf1 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/virtual_list/selection.rs @@ -0,0 +1,641 @@ +//! Virtual-row text selection: pinned ends, identity-based endpoints, and pruning. +#[path = "selection_collect.rs"] +mod collect; + +use std::hash::{Hash, Hasher}; +use std::ops::Range; + +use taffy::style::{Display, FlexDirection}; + +use super::phase::{self, Far, Selection}; +use super::{SelectedText, kept, same_keyed_path, trim_uncopied}; +use crate::el::{El, SelectionCopy, TextSpec}; +use crate::runtime::RuntimeCore; + +#[path = "pins.rs"] +pub(crate) mod pins; +pub(crate) use pins::{OffscreenText, PinnedSelection, Pins, PinsEvent, Scope, Source}; + +/// Maximum number of unbuilt virtual rows built on demand when copying or reading a selection. +/// Past this cap, collection stops building further unbuilt rows and returns the prefix collected +/// so far. +pub(crate) const MAX_VIRTUAL_COPY_ROWS: usize = 10_000; + +/// Maximum number of UTF-8 bytes collected when copying or reading a selection across unbuilt +/// virtual rows (4 MiB). Past this cap, collection stops and truncates on a character boundary. +pub(crate) const MAX_VIRTUAL_COPY_BYTES: usize = 4 * 1024 * 1024; + +/// Identity of a selection endpoint inside a virtual list: `(row key/index, element path within +/// the row, text offset)`. +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) struct VirtualEnd { + pub list_path: String, + pub row_key: String, + pub row_index: usize, + pub rel_path: String, + pub offset: usize, +} + +impl VirtualEnd { + pub fn full_path(&self) -> String { + if self.rel_path.is_empty() { + format!("{}/{}", self.list_path, self.row_key) + } else { + format!("{}/{}/{}", self.list_path, self.row_key, self.rel_path) + } + } +} + +/// A resolved selection endpoint: either a mounted node index in `Runtime::nodes` or an offscreen +/// text `(virtual_list_iter_index, text_index)` in `PinnedSelection::texts`. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum EndRef { + Mounted(usize), + Offscreen(usize, usize), +} + +/// Collects selectable texts and `selection_copy` providers from an offscreen row `row_el`. +#[allow(clippy::too_many_arguments)] +pub(crate) fn collect_virtual_row_selection( + row_el: &El, + list_path: &str, + row_key: &str, + row_index: usize, + list_group: Option<&str>, + list_inert: bool, + texts: &mut Vec<OffscreenText>, + copy_providers: &mut Vec<(String, SelectionCopy)>, +) { + let mut order_in_row = 0usize; + let row_path = format!("{list_path}/{row_key}"); + walk_row_el( + row_el, list_path, row_key, row_index, &row_path, "", + list_group, list_inert, &mut order_in_row, texts, copy_providers, + ); +} + +/// Collects one built row's selectable texts into `pins`. A row builder that panics before this +/// leaves everything collected before it in the state, as dev wrote straight into its list did. +#[allow(clippy::too_many_arguments)] +pub(crate) fn collect_row_into_pins( + pins: &mut Pins, + row_el: &El, + list_path: &str, + row_key: &str, + row_index: usize, + list_group: Option<&str>, + list_inert: bool, +) { + if let Some((texts, providers)) = pins.text_buffers() { + collect_virtual_row_selection( + row_el, list_path, row_key, row_index, list_group, list_inert, texts, providers, + ); + } +} + +#[allow(clippy::too_many_arguments)] +fn walk_row_el<'a>( + el: &'a El, + list_path: &str, + row_key: &str, + row_index: usize, + path: &'a str, + rel_path: &str, + parent_group: Option<&'a str>, + parent_inert: bool, + order_in_row: &mut usize, + texts: &mut Vec<OffscreenText>, + copy_providers: &mut Vec<(String, SelectionCopy)>, +) { + let inert = parent_inert || el.flags.has(crate::el::ElFlags::INERT); + let group = if el.flags.has(crate::el::ElFlags::SELECTION_GROUP) { Some(path) } else { parent_group }; + if !inert && let Some(f) = el.handlers.get().and_then(|h| h.selection_copy.as_ref()) { + copy_providers.push((path.to_owned(), f.clone())); + } + let is_row = el.style.display() == Display::Flex + && matches!(el.style.flex_direction(), FlexDirection::Row | FlexDirection::RowReverse); + let mut had_child_text = false; + if !inert && el.cold.input.is_none() && let Some(t) = &el.text && t.selectable && !t.redacted { + let mut spec = TextSpec::clone(t); + spec.apply_isolates(); + spec.apply_case(); + texts.push(OffscreenText { + list_path: list_path.to_owned(), + row_key: row_key.to_owned(), + row_index, + order_in_row: *order_in_row, + rel_path: rel_path.to_owned(), + path: path.to_owned(), + key: el.key.clone(), + group_path: group.map(str::to_owned), + spec, + tab_before: false, + }); + *order_in_row += 1; + had_child_text = true; + } + for (i, child) in el.all_children().enumerate() { + let child_path = crate::runtime::flatten::node_path(path, child.key.as_deref(), i); + let child_rel = crate::runtime::flatten::node_path(rel_path, child.key.as_deref(), i); + let before_len = texts.len(); + walk_row_el( + child, list_path, row_key, row_index, &child_path, &child_rel, + group, inert, order_in_row, texts, copy_providers, + ); + if texts.len() > before_len { + if had_child_text { + texts[before_len].tab_before = is_row; + } + had_child_text = true; + } + } +} + +pub(super) fn offscreen_piece(t: &OffscreenText, range: Range<usize>, base: Option<&str>) -> SelectedText { + let path = match base { + Some(b) if b == t.path => String::new(), + Some(b) => t.path.strip_prefix(b).and_then(|p| p.strip_prefix('/')).unwrap_or(&t.path).to_owned(), + None => t.path.clone(), + }; + let len = t.spec.content.len(); + let (full_a, full_b) = if t.spec.cold.uncopied.is_empty() { + (0, len) + } else { + trim_uncopied(&t.spec.cold.uncopied, (0, len)) + }; + let whole = !range.is_empty() && len > 0 && range.start <= full_a && range.end >= full_b; + let text = t.spec.copy_slice(range.start as u32, range.end as u32).unwrap_or_default(); + let content = t.spec.content.get(range.clone()).unwrap_or_default().to_owned(); + SelectedText { path, key: t.key.clone(), range, len, whole, text, content } +} + +impl RuntimeCore { + pub(crate) fn virtual_list_allowed(&self, list_path: &str) -> bool { + self.live(list_path).is_some() + && !self.commit.virtuals.get(list_path).is_some_and(|v| v.selection.scope.inert) + } + + pub(crate) fn offscreen_text(&self, vi: usize, ti: usize) -> &OffscreenText { + &self.commit.virtuals.iter().nth(vi).unwrap().1.selection.pins.texts()[ti] + } + + pub(crate) fn end_path(&self, end: EndRef) -> &str { + match end { + EndRef::Mounted(i) => &self.tree.nodes[i].path, + EndRef::Offscreen(vi, ti) => &self.offscreen_text(vi, ti).path, + } + } + + pub(crate) fn end_content(&self, end: EndRef) -> &str { + match end { + EndRef::Mounted(i) => self.content_of(i), + EndRef::Offscreen(vi, ti) => &self.offscreen_text(vi, ti).spec.content, + } + } + + pub(crate) fn end_group_path(&self, end: EndRef) -> Option<&str> { + match end { + EndRef::Mounted(i) => self.group_of(i).map(|g| self.tree.nodes[g].path.as_str()), + EndRef::Offscreen(vi, ti) => self.offscreen_text(vi, ti).group_path.as_deref(), + } + } + + pub(crate) fn end_same_group(&self, a: EndRef, b: EndRef) -> bool { + self.end_group_path(a).is_some_and(|ga| self.end_group_path(b) == Some(ga)) + } + + /// Canonical pre-order key `(list_or_node_slot, row_index, in_row_order)` for any mounted or + /// offscreen selectable text. + pub(crate) fn tree_order(&self, end: EndRef) -> (usize, usize, usize) { + match end { + EndRef::Offscreen(vi, ti) => { + let t = self.offscreen_text(vi, ti); + let list_node = self.live(&t.list_path).unwrap_or(0); + let row_index = self.commit.virtuals.get(&t.list_path) + .and_then(|v| v.index_of(&t.row_key)) + .unwrap_or(t.row_index); + (list_node * 2 + 1, row_index, t.order_in_row) + } + EndRef::Mounted(i) => { + let mut cur = i; + while let Some(p) = self.tree.nodes[cur].parent { + if let Some(v) = self.commit.virtuals.get(&self.tree.nodes[p].path) { + let row_index = self.tree.nodes[cur].key.as_deref() + .and_then(|k| v.index_of(k)) + .unwrap_or(0); + return (p * 2 + 1, row_index, i); + } + cur = p; + } + (i * 2, 0, 0) + } + } + } + + /// Virtual-list row identity of `end`, if `end` lies inside a virtual list. + pub(crate) fn virtual_end_of(&self, end: EndRef, offset: usize) -> Option<VirtualEnd> { + match end { + EndRef::Offscreen(vi, ti) => { + let t = self.offscreen_text(vi, ti); + let row_index = self.commit.virtuals.get(&t.list_path) + .and_then(|v| v.index_of(&t.row_key)) + .unwrap_or(t.row_index); + Some(VirtualEnd { + list_path: t.list_path.clone(), + row_key: t.row_key.clone(), + row_index, + rel_path: t.rel_path.clone(), + offset, + }) + } + EndRef::Mounted(i) => { + let mut cur = i; + while let Some(p) = self.tree.nodes[cur].parent { + if let Some(v) = self.commit.virtuals.get(&self.tree.nodes[p].path) { + let row_key = self.tree.nodes[cur].key.clone()?; + let row_index = v.index_of(&row_key)?; + let row_path = &self.tree.nodes[cur].path; + let rel_path = if i == cur { + String::new() + } else { + self.tree.nodes[i].path.strip_prefix(row_path)?.strip_prefix('/')?.to_owned() + }; + return Some(VirtualEnd { + list_path: self.tree.nodes[p].path.clone(), + row_key, + row_index, + rel_path, + offset, + }); + } + cur = p; + } + None + } + } + } + + pub(crate) fn resolve_end(&self, path: &str, v_end: Option<&VirtualEnd>) -> Option<EndRef> { + if let Some(end) = v_end && let Some(r) = self.resolve_virtual_end(end) { + return Some(r); + } + if let Some(i) = self.live(path).filter(|&i| self.is_selectable(i)) { + return Some(EndRef::Mounted(i)); + } + for (vi, (list_path, v)) in self.commit.virtuals.iter().enumerate() { + if !self.virtual_list_allowed(list_path) { + continue; + } + for (ti, t) in v.selection.pins.texts().iter().enumerate() { + if t.path == path && v.index_of(&t.row_key).is_some_and(|r| !v.range.contains(&r)) { + return Some(EndRef::Offscreen(vi, ti)); + } + } + } + None + } + + fn resolve_virtual_end(&self, end: &VirtualEnd) -> Option<EndRef> { + for (vi, (list_path, v)) in self.commit.virtuals.iter().enumerate() { + if list_path != &end.list_path || !self.virtual_list_allowed(list_path) { + continue; + } + let row_idx = v.index_of(&end.row_key)?; + if v.range.contains(&row_idx) { + let full = end.full_path(); + return self.live(&full).filter(|&i| self.is_selectable(i)).map(EndRef::Mounted); + } + for (ti, t) in v.selection.pins.texts().iter().enumerate() { + if t.row_key == end.row_key && t.rel_path == end.rel_path { + return Some(EndRef::Offscreen(vi, ti)); + } + } + } + None + } + + pub(crate) fn selection_holder_end(&self) -> Option<EndRef> { + let sel = self.edit.selectable.phase.selection()?; + let h = self.resolve_end(&sel.path, sel.anchor_end.as_ref())?; + let upto = match &sel.far { + None => sel.anchor.max(sel.focus).max(sel.origin.1), + Some(far) + if self.resolve_end(&far.path, far.end.as_ref()) + .is_some_and(|f| self.tree_order(f) > self.tree_order(h)) => + { + sel.content.len() + } + Some(_) => sel.anchor.max(sel.origin.1), + }; + kept(&sel.content, self.end_content(h), upto).then_some(h) + } + + pub(crate) fn focus_holder_end(&self, holder: EndRef) -> Option<EndRef> { + let sel = self.edit.selectable.phase.selection()?; + let Some(far) = &sel.far else { return Some(holder) }; + let f = self.resolve_end(&far.path, far.end.as_ref())?; + let upto = if self.tree_order(f) > self.tree_order(holder) { sel.focus } else { far.content.len() }; + (self.end_same_group(f, holder) && kept(&far.content, self.end_content(f), upto)).then_some(f) + } + + /// Updates the selection's `anchor_end` and far `end`, and each list's pins. + pub(crate) fn sync_selection_pins(&mut self) { + let Some(sel) = self.edit.selectable.phase.selection() else { + // With nothing selected nothing lies between its ends. + self.edit.selectable.mounted_between.clear(); + for v in self.commit.virtuals.values_mut() { + v.selection.pins.sync(PinsEvent::Clear); + } + return; + }; + let (anchor, focus, far) = (sel.anchor, sel.focus, sel.far.is_some()); + let ends = self.selection_holder_end().map(|h| { + let focus_end = if far { self.focus_holder_end(h).and_then(|f| self.virtual_end_of(f, focus)) } else { None }; + (self.virtual_end_of(h, anchor), focus_end) + }); + let Some(sel) = self.edit.selectable.phase.selection_mut() else { return }; + if let Some((anchor_end, focus_end)) = ends { + sel.anchor_end = anchor_end; + if let Some(far) = &mut sel.far { far.end = focus_end; } + } + let a_end = sel.anchor_end.clone(); + let f_end = sel.far.as_ref().and_then(|f| f.end.clone()); + for (list_path, v) in &mut self.commit.virtuals { + let anchor = a_end.as_ref().filter(|a| &a.list_path == list_path).map(|a| a.row_key.as_str()); + let focus = f_end.as_ref().filter(|f| &f.list_path == list_path).map(|f| f.row_key.as_str()); + v.selection.pins.sync(PinsEvent::Select { anchor, focus }); + } + } + + /// Whether `h` and `f` span across virtual rows (either between different rows of a virtual + /// list, or between an element outside the virtual list and a row inside or past it). + fn is_cross_row_virtual(&self, h: EndRef, f: EndRef) -> Option<(String, usize, usize)> { + let (first, last) = if self.tree_order(h) <= self.tree_order(f) { (h, f) } else { (f, h) }; + let va = self.virtual_end_of(first, 0); + let vb = self.virtual_end_of(last, 0); + match (va, vb) { + (Some(a), Some(b)) => { + (a.list_path == b.list_path && a.row_index != b.row_index) + .then(|| (a.list_path, a.row_index.min(b.row_index), a.row_index.max(b.row_index))) + } + (Some(a), None) => { + let v = self.commit.virtuals.get(&a.list_path)?; + (!v.keys.is_empty()).then(|| (a.list_path, a.row_index, v.keys.len() - 1)) + } + (None, Some(b)) => Some((b.list_path, 0, b.row_index)), + (None, None) => { + let (first_ord, last_ord) = (self.tree_order(first), self.tree_order(last)); + self.commit.virtuals.iter().find_map(|(lp, v)| { + if v.keys.is_empty() { return None; } + let ln = self.live(lp)?; + let list_ord = (ln * 2 + 1, 0, 0); + (first_ord < list_ord && last_ord > list_ord) + .then(|| (lp.clone(), 0, v.keys.len() - 1)) + }) + } + } + } + + fn mounted_row_hash(&self, list_path: &str, row_key: &str, g_path: &str) -> Option<u64> { + let list_node = self.live(list_path)?; + let row_path = format!("{list_path}/{row_key}"); + let row_node = self.tree.direct_child_by_path(list_node, self.tree.nodes.len(), &row_path)?; + let mut hasher = rustc_hash::FxHasher::default(); + for j in (row_node..self.tree.nodes.len()).take_while(|&j| self.tree.is_descendant(j, row_node)) { + if self.is_selectable(j) + && !self.subtree_exiting(j) + && self.allowed(j) + && self.group_of(j).is_some_and(|g| self.tree.nodes[g].path == g_path) + { + (&self.tree.nodes[j].path, self.content_of(j)).hash(&mut hasher); + } + } + Some(hasher.finish()) + } + + pub(crate) fn between_hash_ends(&self, h: EndRef, f: EndRef) -> u64 { + let mut hasher = rustc_hash::FxHasher::default(); + let Some(g_path) = self.end_group_path(h).filter(|_| h != f) else { + return hasher.finish(); + }; + let (first, last) = if self.tree_order(h) < self.tree_order(f) { (h, f) } else { (f, h) }; + if let Some((list_path, r0, r1)) = self.is_cross_row_virtual(first, last) { + if let Some(g) = self.live(g_path) && let Some(ln) = self.live(&list_path) { + let (first_ord, last_ord) = (self.tree_order(first), self.tree_order(last)); + for j in (g + 1..self.tree.nodes.len()).filter(|&j| !self.tree.is_descendant(j, ln) && self.member(j, g)) { + let ord = self.tree_order(EndRef::Mounted(j)); + if ord > first_ord && ord < last_ord { + (&self.tree.nodes[j].path, self.content_of(j)).hash(&mut hasher); + } + } + } + if let Some(v) = self.commit.virtuals.get(&list_path) && r1 < v.keys.len() { + v.keys[r0..=r1].hash(&mut hasher); + } + return hasher.finish(); + } + match (first, last) { + (EndRef::Mounted(i0), EndRef::Mounted(i1)) => { + if let Some(g) = self.group_of(i0) { + for j in (i0 + 1..i1).filter(|&j| self.member(j, g)) { + (&self.tree.nodes[j].path, self.content_of(j)).hash(&mut hasher); + } + } + } + (EndRef::Offscreen(vi0, ti0), EndRef::Offscreen(vi1, ti1)) if vi0 == vi1 => { + let (_, v) = self.commit.virtuals.iter().nth(vi0).unwrap(); + let texts = v.selection.pins.texts(); + let row_key = &texts[ti0].row_key; + let (o0, o1) = (texts[ti0].order_in_row, texts[ti1].order_in_row); + for t in texts { + if &t.row_key == row_key && t.order_in_row > o0 && t.order_in_row < o1 && t.group_path.as_deref() == Some(g_path) { + (&t.path, t.spec.content.as_str()).hash(&mut hasher); + } + } + } + _ => {} + } + hasher.finish() + } + + pub(crate) fn seal_between(&mut self) { + self.sync_selection_pins(); + self.edit.selectable.mounted_between.clear(); + let Some((h, f)) = self.selection_holder_end().and_then(|h| Some((h, self.focus_holder_end(h)?))) else { + if let Some(sel) = self.edit.selectable.phase.selection_mut() { sel.between = 0; } + self.remember_pick(); + return; + }; + let between = self.between_hash_ends(h, f); + if let Some(sel) = self.edit.selectable.phase.selection_mut() { sel.between = between; } + if let Some(g_path) = self.end_group_path(h).map(str::to_owned) + && let Some((list_path, r0, r1)) = self.is_cross_row_virtual(h, f) + && let Some(v) = self.commit.virtuals.get(&list_path) + { + let range = v.range.clone(); + let keys: Vec<String> = ((r0 + 1)..r1) + .filter(|r| range.contains(r)) + .filter_map(|r| v.keys.get(r).cloned()) + .collect(); + for key in keys { + if let Some(hash) = self.mounted_row_hash(&list_path, &key, &g_path) { + self.edit.selectable.mounted_between.insert(key, hash); + } + } + } + self.remember_pick(); + } + + pub(crate) fn between_matches(&mut self, h: EndRef, f: EndRef) -> bool { + let Some(sealed) = self.edit.selectable.phase.selection().filter(|s| s.far.is_some()).map(|s| s.between) else { + return true; + }; + if self.between_hash_ends(h, f) != sealed { + return false; + } + if let Some(g_path) = self.end_group_path(h).map(str::to_owned) + && let Some((list_path, r0, r1)) = self.is_cross_row_virtual(h, f) + && let Some(v) = self.commit.virtuals.get(&list_path) + { + let range = v.range.clone(); + let keys: Vec<String> = ((r0 + 1)..r1) + .filter(|r| range.contains(r)) + .filter_map(|r| v.keys.get(r).cloned()) + .collect(); + for key in keys { + if let Some(hash) = self.mounted_row_hash(&list_path, &key, &g_path) { + if let Some(&prev) = self.edit.selectable.mounted_between.get(&key) { + if prev != hash { + return false; + } + } else { + self.edit.selectable.mounted_between.insert(key, hash); + } + } + } + } + true + } + + /// True when the current selection is non-empty (mounted or offscreen). + pub(crate) fn has_nonempty_selection(&self) -> bool { + let Some(h) = self.selection_holder_end() else { return false }; + let Some(f) = self.focus_holder_end(h) else { return false }; + if h == f { + let Some(sel) = self.edit.selectable.phase.selection() else { return false }; + let (a, b) = (sel.anchor.min(sel.focus), sel.anchor.max(sel.focus)); + a < b && b <= self.end_content(h).len() + } else { + true + } + } + + /// True when the selection touches any offscreen/unbuilt virtual row. + pub(crate) fn selection_spans_unmounted(&self) -> bool { + let Some(h) = self.selection_holder_end() else { return false }; + let Some(f) = self.focus_holder_end(h) else { return false }; + if matches!(h, EndRef::Offscreen(..)) || matches!(f, EndRef::Offscreen(..)) { + return true; + } + let (EndRef::Mounted(i0), EndRef::Mounted(i1)) = (h, f) else { return true }; + if i0 == i1 { + return false; + } + let (first_ord, last_ord) = (self.tree_order(EndRef::Mounted(i0.min(i1))), self.tree_order(EndRef::Mounted(i0.max(i1)))); + self.commit.virtuals.iter().any(|(list_path, v)| { + if v.keys.is_empty() || (v.range.start == 0 && v.range.end >= v.keys.len()) { + return false; + } + let Some(ln) = self.live(list_path) else { return false }; + let head_unmounted = v.range.start > 0 + && (ln * 2 + 1, 0, usize::MAX) >= first_ord + && (ln * 2 + 1, 0, 0) <= last_ord; + let last_r = v.keys.len() - 1; + let tail_unmounted = v.range.end < v.keys.len() + && (ln * 2 + 1, last_r, usize::MAX) >= first_ord + && (ln * 2 + 1, last_r, 0) <= last_ord; + head_unmounted || tail_unmounted + }) + } + + /// A unique live selectable node at `path`'s keyed identity when an unkeyed ancestor moved. + fn rebound(&self, path: &str, content: &str, upto: usize) -> Option<usize> { + let mut hits = (0..self.tree.nodes.len()).filter(|&i| { + self.is_selectable(i) && !self.subtree_exiting(i) && self.allowed(i) + && same_keyed_path(path, &self.tree.nodes[i].path) && kept(content, self.content_of(i), upto) + }); + let first = hits.next()?; + hits.next().is_none().then_some(first) + } + + /// After a commit: drop a selection whose texts went away, stopped being selectable or + /// changed what it selected, or whose texts between its ends changed. + pub(crate) fn prune_text_selection(&mut self) { + if self.edit.selectable.phase.selection().is_none() { return; } + let mut rebind = false; + if self.selection_holder_end().is_none() + && let Some(sel) = self.edit.selectable.phase.selection().filter(|s| s.anchor_end.is_none()) + { + let old_path = sel.path.clone(); + let upto = sel.anchor.max(sel.focus).max(sel.origin.1); + if let Some(i) = self.rebound(&old_path, &sel.content, upto) { + let old_ancs: Vec<&str> = std::iter::successors(Some(old_path.as_str()), |p| p.rsplit_once('/').map(|(a, _)| a)).collect(); + let new_ancs: Vec<usize> = std::iter::successors(Some(i), |&p| self.tree.nodes[p].parent).collect(); + for (&old_anc, &new_anc) in old_ancs.iter().zip(&new_ancs) { + if let Some(v) = self.edit.sel_heard.by_path.remove(old_anc) { + self.edit.sel_heard.by_path.insert(self.tree.nodes[new_anc].path.clone(), v); + } + } + if let Some(sel) = self.edit.selectable.phase.selection_mut() { sel.path = self.tree.nodes[i].path.clone(); } + rebind = true; + } + } + if let Some(h) = self.selection_holder_end() + && self.focus_holder_end(h).is_none() + && let Some(sel) = self.edit.selectable.phase.selection() + && let Some(far) = sel.far.as_ref().filter(|f| f.end.is_none()) + && let Some(j) = self.rebound(&far.path, &far.content, sel.focus) + { + if let Some(far) = self.edit.selectable.phase.selection_mut().and_then(|s| s.far.as_mut()) { far.path = self.tree.nodes[j].path.clone(); } + rebind = true; + } + if rebind && let Some((h, f)) = self.selection_holder_end().and_then(|h| Some((h, self.focus_holder_end(h)?))) { + let between = self.between_hash_ends(h, f); + if let Some(sel) = self.edit.selectable.phase.selection_mut() { sel.between = between; } + } + let Some((h, f)) = self.selection_holder_end().and_then(|h| Some((h, self.focus_holder_end(h)?))) else { + self.clear_text_selection(); + return; + }; + if !self.between_matches(h, f) { + self.clear_text_selection(); + return; + } + let (h_path, h_content) = (self.end_path(h).to_owned(), self.end_content(h).to_owned()); + let far = (f != h).then(|| (self.end_path(f).to_owned(), self.end_content(f).to_owned())); + if let Some(sel) = self.edit.selectable.phase.selection_mut() { + if sel.path != h_path { sel.path = h_path; } + if sel.content != h_content { sel.content = h_content; } + if let Some((f_path, f_content)) = far && let Some(far) = &mut sel.far { + if far.path != f_path { far.path = f_path; } + if far.content != f_content { far.content = f_content; } + } + } + self.sync_selection_pins(); + } + + /// Selects from the start of `first` to the end of `last` (mounted or offscreen). + pub(crate) fn select_span_ends(&mut self, first: EndRef, last: EndRef) { + let head = self.end_path(first).to_owned(); + let content = self.end_content(first).to_owned(); + let far = (first != last).then(|| Far::new(self.end_path(last).to_owned(), self.end_content(last).to_owned())); + let end = far.as_ref().map_or(content.len(), |f| f.content.len()); + let origin = if far.is_some() { (0, 0) } else { (0, end) }; + let anchor_end = self.virtual_end_of(first, 0); + let focus_end = (first != last).then(|| self.virtual_end_of(last, end)).flatten(); + let mut sel = Selection::new(head, content, (0, end), origin); + sel.anchor_end = anchor_end; + sel.far = far.map(|far| Far { end: focus_end, ..far }); + self.select_step(phase::Event::Select(sel)); + } +} diff --git a/app/vendor/rune/crates/rune/src/runtime/virtual_list/selection_collect.rs b/app/vendor/rune/crates/rune/src/runtime/virtual_list/selection_collect.rs new file mode 100644 index 0000000..82f0d88 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/virtual_list/selection_collect.rs @@ -0,0 +1,528 @@ +//! On-demand unbuilt virtual-row building, copy collection, ⌘A span resolution, and programmatic +//! selection requests on unbuilt rows. +use super::{ + EndRef, MAX_VIRTUAL_COPY_BYTES, MAX_VIRTUAL_COPY_ROWS, OffscreenText, PinsEvent, Source, + collect_virtual_row_selection, offscreen_piece, +}; +use crate::el::{SelectRequest, SelectionCopy}; +use crate::runtime::selectable::phase::{self, Selection}; +use crate::runtime::selectable::{CopyJoin, SelectedText, TextSelection, floor_boundary}; +use crate::runtime::types::TreeState; +use crate::runtime::{RuntimeCore, ViewDriver}; + +impl TreeState { + /// Nearest `selection_copy` provider ancestor covering both `n0` and `n1`. + fn selection_copy_provider(&self, n0: usize, n1: usize) -> Option<(usize, SelectionCopy)> { + let p = std::iter::successors(Some(n0), |&p| self.nodes[p].parent) + .find(|&p| self.nodes[p].handlers.selection_copy.is_some() && self.is_descendant(n1, p))?; + Some((p, self.nodes[p].handlers.selection_copy.clone()?)) + } +} + +impl RuntimeCore { + pub(crate) fn copy_virtual_text(&self, app: &dyn ViewDriver) -> Option<String> { + let h = self.selection_holder_end()?; + let f = self.focus_holder_end(h)?; + let node_for = |e: EndRef| match e { + EndRef::Mounted(i) => Some(i), + EndRef::Offscreen(vi, ti) => self.live(&self.offscreen_text(vi, ti).list_path), + }; + let (n0, n1) = (node_for(h)?, node_for(f)?); + if let Some((p, copy_fn)) = self.tree.selection_copy_provider(n0, n1) { + let sel = self.collect_virtual_selection(app, Some(p))?; + if let Some(text) = copy_fn(&sel) { + return Some(text); + } + return Some(sel.text); + } + self.collect_virtual_selection(app, None).map(|s| s.text) + } + + /// Builds an unmounted row `r` of `list_path` on demand (view only, no layout/mount/GPU) and + /// collects its selectable texts. + pub(super) fn build_unmounted_row( + &self, + app: &dyn ViewDriver, + list_path: &str, + r: usize, + texts: &mut Vec<OffscreenText>, + providers: &mut Vec<(String, SelectionCopy)>, + ) { + let Some(v) = self.commit.virtuals.get(list_path) else { return }; + let Some(key) = v.keys.get(r) else { return }; + let (group_path, inert) = (v.selection.scope.group_path.as_deref(), v.selection.scope.inert); + match v.selection.pins.source() { + Some(Source::Rebuild(rows)) => { + let state = app.states_ref(); + let mut row = (rows.build)(state, r).key(key.clone()); + if !crate::input::key_diagnostics::clean(&row) { + let _ = crate::input::key_diagnostics::repair_at(&mut row, &format!("{list_path}/{key}")); + } + collect_virtual_row_selection(&row, list_path, key, r, group_path, inert, texts, providers); + } + Some(Source::Stored) => { + if let Some(row) = v.selection.stored.get(&r) { + collect_virtual_row_selection(row, list_path, key, r, group_path, inert, texts, providers); + } + } + // Before the list's first commit there is nothing to build a row from, as dev's + // default `Source::Stored` with an empty map had. + None => {} + } + } + + /// Pins row `r` of `list_path` and ensures its offscreen texts are kept. + pub(crate) fn pin_offscreen_row(&mut self, app: &dyn ViewDriver, list_path: &str, r: usize) { + let Some(v) = self.commit.virtuals.get(list_path) else { return }; + if v.range.contains(&r) || r >= v.keys.len() { + return; + } + let row_key = v.keys[r].clone(); + let already = v.selection.pins.has_text_row(&row_key); + let (mut texts, mut providers) = (Vec::new(), Vec::new()); + if !already { + self.build_unmounted_row(app, list_path, r, &mut texts, &mut providers); + } + if let Some(v) = self.commit.virtuals.get_mut(list_path) { + v.selection.pins.sync(PinsEvent::Pin { key: row_key, texts, providers }); + } + } + + /// Collects the full [`TextSelection`] when the selection touches offscreen or unbuilt rows, + /// bounded by [`MAX_VIRTUAL_COPY_ROWS`] and [`MAX_VIRTUAL_COPY_BYTES`]. + pub(crate) fn collect_virtual_selection(&self, app: &dyn ViewDriver, base: Option<usize>) -> Option<TextSelection> { + let h = self.selection_holder_end()?; + let f = self.focus_holder_end(h)?; + let sel = self.edit.selectable.phase.selection()?; + let base_path = base.map(|b| self.tree.nodes[b].path.as_str()); + + if h == f { + let (a, b) = (sel.anchor.min(sel.focus), sel.anchor.max(sel.focus)); + return match h { + EndRef::Mounted(i) => { + if a >= b || b > self.content_of(i).len() { return None; } + let piece = self.selected_piece(i, a..b, base); + let text = piece.text().to_owned(); + Some(TextSelection { texts: vec![piece], text, backward: self.selection_backward() }) + } + EndRef::Offscreen(vi, ti) => { + let t = self.offscreen_text(vi, ti); + if a >= b || b > t.spec.content.len() { return None; } + let piece = offscreen_piece(t, a..b, base_path); + let text = piece.text().to_owned(); + Some(TextSelection { texts: vec![piece], text, backward: self.selection_backward() }) + } + }; + } + + let ((first_end, first_byte), (last_end, last_byte)) = if self.tree_order(h) < self.tree_order(f) { + ((h, sel.anchor), (f, sel.focus)) + } else { + ((f, sel.focus), (h, sel.anchor)) + }; + let (first_ord, last_ord) = (self.tree_order(first_end), self.tree_order(last_end)); + let g_path = self.end_group_path(h)?; + + // Both ends in the same offscreen row (e.g. a row with its own `selection_group`). + if let (EndRef::Offscreen(vi0, ti0), EndRef::Offscreen(vi1, ti1)) = (first_end, last_end) + && vi0 == vi1 + { + let (_, v) = self.commit.virtuals.iter().nth(vi0)?; + let kept = v.selection.pins.texts(); + let row_key = &kept[ti0].row_key; + if self.offscreen_text(vi1, ti1).row_key == *row_key { + let (mut texts, mut out) = (Vec::new(), CopyJoin::default()); + for (ti, t) in kept.iter().enumerate() { + if &t.row_key != row_key || t.group_path.as_deref() != Some(g_path) { continue; } + let end_ref = EndRef::Offscreen(vi0, ti); + let ord = self.tree_order(end_ref); + if ord < first_ord || ord > last_ord { continue; } + let len = t.spec.content.len(); + let a = if end_ref == first_end { first_byte.min(len) } else { 0 }; + let b = if end_ref == last_end { last_byte.min(len) } else { len }; + if a >= b { continue; } + let piece = offscreen_piece(t, a..b, base_path); + let hit_cap = out.push(&t.spec, a..b, piece.text(), t.tab_before, MAX_VIRTUAL_COPY_BYTES); + texts.push(piece); + if hit_cap { break; } + } + let text = out.finish(); + return (!text.is_empty()).then_some(TextSelection { texts, text, backward: self.selection_backward() }); + } + } + + // General group selection spanning a virtual list. + let list_path = self.virtual_end_of(first_end, 0) + .or_else(|| self.virtual_end_of(last_end, 0)) + .map(|e| e.list_path) + .or_else(|| { + let g = self.live(g_path)?; + (g..self.tree.nodes.len()) + .take_while(|&j| self.tree.is_descendant(j, g)) + .find_map(|j| self.commit.virtuals.contains_key(&self.tree.nodes[j].path).then(|| self.tree.nodes[j].path.clone())) + })?; + let list_node = self.live(&list_path)?; + let v = self.commit.virtuals.get(&list_path)?; + let g = self.live(g_path)?; + + let (mut texts, mut out) = (Vec::new(), CopyJoin::default()); + let (mut unbuilt_rows, mut prev_mounted, mut hit_cap) = (0usize, None, false); + + let append_mounted = |j: usize, out: &mut CopyJoin, texts: &mut Vec<SelectedText>, prev_mounted: &mut Option<usize>| -> bool { + let end_ref = EndRef::Mounted(j); + let ord = self.tree_order(end_ref); + if ord < first_ord || ord > last_ord { return false; } + let len = self.content_of(j).len(); + let a = if end_ref == first_end { first_byte.min(len) } else { 0 }; + let b = if end_ref == last_end { last_byte.min(len) } else { len }; + if a >= b { return false; } + let piece = self.selected_piece(j, a..b, base); + let Some(spec) = self.tree.nodes[j].text.as_ref() else { return false }; + let beside = prev_mounted.is_some_and(|p| self.beside(p, j)); + let capped = out.push(spec, a..b, piece.text(), beside, MAX_VIRTUAL_COPY_BYTES); + texts.push(piece); + *prev_mounted = Some(j); + capped + }; + + // 1. Mounted group members before `list_node`. + for j in (g + 1..list_node).filter(|&j| self.tree.is_descendant(j, g) && self.member(j, g)) { + if append_mounted(j, &mut out, &mut texts, &mut prev_mounted) { + hit_cap = true; + break; + } + } + + // 2. Rows of the virtual list in `[row_start..=row_end]`. + if !hit_cap && !v.keys.is_empty() { + let row_start = self.virtual_end_of(first_end, 0) + .filter(|e| e.list_path == list_path) + .map_or(0, |e| e.row_index); + let row_end = self.virtual_end_of(last_end, 0) + .filter(|e| e.list_path == list_path) + .map_or(v.keys.len() - 1, |e| e.row_index.min(v.keys.len() - 1)); + + let list_end = self.tree.subtree_end(list_node); + + for r in row_start..=row_end { + if v.range.contains(&r) { + let row_path = format!("{list_path}/{}", v.keys[r]); + let Some(row_node) = self.tree.direct_child_by_path(list_node, list_end + 1, &row_path) + else { continue }; + for j in (row_node..=list_end).take_while(|&j| self.tree.is_descendant(j, row_node)).filter(|&j| self.member(j, g)) { + if append_mounted(j, &mut out, &mut texts, &mut prev_mounted) { + hit_cap = true; + break; + } + } + if hit_cap { break; } + } else { + prev_mounted = None; + let row_key = &v.keys[r]; + let mut built_texts = Vec::new(); + let row_texts: Vec<&OffscreenText> = if v.selection.pins.has_text_row(row_key) { + v.selection.pins.texts().iter().filter(|t| &t.row_key == row_key).collect() + } else { + if unbuilt_rows >= MAX_VIRTUAL_COPY_ROWS || out.text().len() >= MAX_VIRTUAL_COPY_BYTES { + hit_cap = true; + break; + } + unbuilt_rows += 1; + let mut ignored = Vec::new(); + self.build_unmounted_row(app, &list_path, r, &mut built_texts, &mut ignored); + built_texts.iter().collect() + }; + let mut first_in_row = true; + for t in row_texts { + if t.group_path.as_deref() != Some(g_path) { continue; } + let ord = (list_node * 2 + 1, r, t.order_in_row); + if ord < first_ord || ord > last_ord { continue; } + let len = t.spec.content.len(); + let a = if ord == first_ord { first_byte.min(len) } else { 0 }; + let b = if ord == last_ord { last_byte.min(len) } else { len }; + if a >= b { continue; } + let piece = offscreen_piece(t, a..b, base_path); + let capped = out.push(&t.spec, a..b, piece.text(), !first_in_row && t.tab_before, MAX_VIRTUAL_COPY_BYTES); + texts.push(piece); + first_in_row = false; + if capped { + hit_cap = true; + break; + } + } + if hit_cap { break; } + } + } + + // 3. Mounted group members after the virtual list's subtree. + if !hit_cap { + for j in (list_end + 1..self.tree.nodes.len()).take_while(|&j| self.tree.is_descendant(j, g)).filter(|&j| self.member(j, g)) { + if append_mounted(j, &mut out, &mut texts, &mut prev_mounted) { + break; + } + } + } + } + + let text = out.finish(); + (!text.is_empty()).then_some(TextSelection { texts, text, backward: self.selection_backward() }) + } + + /// Finds the first and last selectable texts inside mounted node `root` (including unbuilt rows + /// of any virtual list under `root`), pinning offscreen end rows as needed. + pub(crate) fn virtual_span_under(&mut self, app: &dyn ViewDriver, root: usize) -> Option<(EndRef, EndRef)> { + let list_path = (root..self.tree.nodes.len()) + .take_while(|&j| self.tree.is_descendant(j, root)) + .find_map(|j| { + self.commit.virtuals.get(&self.tree.nodes[j].path) + .filter(|v| !v.keys.is_empty()) + .map(|_| self.tree.nodes[j].path.clone()) + })?; + let list_node = self.live(&list_path)?; + let g_path = if self.tree.nodes[root].selection_group { + Some(self.tree.nodes[root].path.clone()) + } else { + self.group_of(root).map(|g| self.tree.nodes[g].path.clone()) + }; + + // 1. Find the first selectable text under `root`. + let first_before = (root..list_node) + .filter(|&j| self.tree.is_descendant(j, root) && self.is_selectable(j) && !self.subtree_exiting(j) && self.allowed(j)) + .find(|&j| match &g_path { + Some(gp) => self.group_of(j).is_some_and(|g| &self.tree.nodes[g].path == gp), + None => true, + }) + .map(EndRef::Mounted); + + let mut first_row_pin: Option<(usize, String)> = None; + let first_end = if let Some(e) = first_before { + Some(e) + } else { + let count = self.commit.virtuals[&list_path].keys.len(); + let mut found = None; + for r in 0..count { + let range = self.commit.virtuals[&list_path].range.clone(); + if range.contains(&r) { + let row_path = format!("{list_path}/{}", self.commit.virtuals[&list_path].keys[r]); + if let Some(j) = (list_node + 1..self.tree.nodes.len()) + .take_while(|&j| self.tree.is_descendant(j, root)) + .filter(|&j| { + (self.tree.nodes[j].path == row_path + || self.tree.nodes[j].path.strip_prefix(&row_path).is_some_and(|s| s.starts_with('/'))) + && self.is_selectable(j) && !self.subtree_exiting(j) && self.allowed(j) + }) + .find(|&j| match &g_path { + Some(gp) => self.group_of(j).is_some_and(|g| &self.tree.nodes[g].path == gp), + None => true, + }) + { + found = Some(EndRef::Mounted(j)); + break; + } + } else { + let (mut texts, mut providers) = (Vec::new(), Vec::new()); + self.build_unmounted_row(app, &list_path, r, &mut texts, &mut providers); + if let Some(t) = texts.iter().find(|t| match &g_path { + Some(gp) => t.group_path.as_deref() == Some(gp.as_str()), + None => true, + }) { + first_row_pin = Some((r, t.path.clone())); + break; + } + } + } + if let Some((r, path)) = first_row_pin { + self.pin_offscreen_row(app, &list_path, r); + found = self.resolve_end(&path, None); + } + found + }?; + + let target_group = g_path.or_else(|| self.end_group_path(first_end).map(str::to_owned)); + let Some(gp) = target_group else { + return Some((first_end, first_end)); + }; + + // 2. Find the last selectable text under `root` in `gp`. + let list_end = self.tree.subtree_end(list_node); + let last_after = (list_end + 1..self.tree.nodes.len()) + .take_while(|&j| self.tree.is_descendant(j, root)) + .filter(|&j| { + self.is_selectable(j) && !self.subtree_exiting(j) && self.allowed(j) + && self.group_of(j).is_some_and(|g| self.tree.nodes[g].path == gp) + }) + .last() + .map(EndRef::Mounted); + + let last_end = if let Some(e) = last_after { + e + } else { + let count = self.commit.virtuals[&list_path].keys.len(); + let mut last_row_pin: Option<(usize, String)> = None; + let mut found = None; + for r in (0..count).rev() { + let range = self.commit.virtuals[&list_path].range.clone(); + if range.contains(&r) { + let row_path = format!("{list_path}/{}", self.commit.virtuals[&list_path].keys[r]); + if let Some(j) = (list_node + 1..=list_end) + .filter(|&j| { + (self.tree.nodes[j].path == row_path + || self.tree.nodes[j].path.strip_prefix(&row_path).is_some_and(|s| s.starts_with('/'))) + && self.is_selectable(j) && !self.subtree_exiting(j) && self.allowed(j) + && self.group_of(j).is_some_and(|g| self.tree.nodes[g].path == gp) + }) + .last() + { + found = Some(EndRef::Mounted(j)); + break; + } + } else { + let (mut texts, mut providers) = (Vec::new(), Vec::new()); + self.build_unmounted_row(app, &list_path, r, &mut texts, &mut providers); + if let Some(t) = texts.iter().rev().find(|t| t.group_path.as_deref() == Some(gp.as_str())) { + last_row_pin = Some((r, t.path.clone())); + break; + } + } + } + if let Some((r, path)) = last_row_pin { + self.pin_offscreen_row(app, &list_path, r); + found = self.resolve_end(&path, None); + } + found.unwrap_or(first_end) + }; + + let first_path = self.end_path(first_end).to_owned(); + let last_path = self.end_path(last_end).to_owned(); + Some((self.resolve_end(&first_path, None)?, self.resolve_end(&last_path, None)?)) + } + + /// Carries out a `Tx::select_text`, `select_all_text` or `clear_text_selection`. + pub(crate) fn select_request(&mut self, app: &dyn ViewDriver, request: SelectRequest) { + let named = |key: &str| (0..self.tree.nodes.len()).find(|&i| self.tree.nodes[i].named(key) && !self.subtree_exiting(i) && self.allowed(i)); + match request { + SelectRequest::Clear => self.clear_text_selection(), + SelectRequest::Range(key, range) => { + let Some(i) = named(&key).filter(|&i| self.is_selectable(i)) else { + self.select_unmounted_request(app, &SelectRequest::Range(key, range)); + return; + }; + let content = self.content_of(i).to_owned(); + let (a, b) = (floor_boundary(&content, range.start), floor_boundary(&content, range.end.max(range.start))); + let path = self.tree.nodes[i].path.clone(); + self.select_step(phase::Event::Select(Selection::new(path, content, (a, b), (a, b)))); + } + SelectRequest::All(key) => { + let Some(i) = named(&key) else { + self.select_unmounted_request(app, &SelectRequest::All(key)); + return; + }; + if let Some((first, last)) = self.virtual_span_under(app, i) { + self.select_span_ends(first, last); + return; + } + if self.tree.nodes[i].selection_group { + let members = self.group_texts(i); + if let (Some(&first), Some(&last)) = (members.first(), members.last()) { + self.select_span(first, last); + return; + } + } + let texts = || (i..self.tree.nodes.len()).take_while(|&j| self.tree.is_descendant(j, i)) + .filter(|&j| self.is_selectable(j) && !self.subtree_exiting(j) && self.allowed(j)); + let Some(first) = texts().next() else { return }; + let last = match self.group_of(first) { + Some(g) => texts().filter(|&j| self.group_of(j) == Some(g)).last().unwrap_or(first), + None => first, + }; + self.select_span(first, last); + } + } + } + + /// `select_request`, recording what an `El::on_selection_change` callback changed as already + /// heard so it doesn't fire again on its own request. + pub(crate) fn apply_select_request(&mut self, app: &dyn ViewDriver, request: SelectRequest, from_change: bool) { + self.select_request(app, request); + if from_change { + let _ = self.selection_changes(app); + } + } + + /// Handles `Tx::select_text` / `Tx::select_all_text` when `selector` names an element in an + /// unbuilt virtual row. + pub(crate) fn select_unmounted_request(&mut self, app: &dyn ViewDriver, request: &SelectRequest) -> bool { + let selector = match request { + SelectRequest::Clear => return false, + SelectRequest::Range(k, _) | SelectRequest::All(k) => k.as_str(), + }; + let lists: Vec<String> = self.commit.virtuals.keys() + .filter(|lp| self.virtual_list_allowed(lp)) + .cloned() + .collect(); + + for list_path in lists { + let Some(v) = self.commit.virtuals.get(&list_path) else { continue }; + let count = v.keys.len(); + let range = v.range.clone(); + let mut candidate_rows: Vec<usize> = (0..count) + .filter(|r| !range.contains(r)) + .filter(|&r| { + let rk = &v.keys[r]; + selector == rk + || selector.strip_prefix(rk.as_str()).is_some_and(|s| s.starts_with('/')) + || selector.rsplit('/').any(|seg| seg == rk) + }) + .collect(); + if candidate_rows.is_empty() { + candidate_rows.extend((0..count).filter(|r| !range.contains(r)).take(MAX_VIRTUAL_COPY_ROWS)); + } + for r in candidate_rows { + let (mut texts, mut providers) = (Vec::new(), Vec::new()); + self.build_unmounted_row(app, &list_path, r, &mut texts, &mut providers); + match request { + SelectRequest::Range(_, byte_range) => { + if let Some(t) = texts.iter().find(|t| t.path == selector || crate::flight::selects(selector, &t.path, t.key.as_deref())) { + let target_path = t.path.clone(); + let content = t.spec.content.clone(); + let (a, b) = ( + floor_boundary(&content, byte_range.start), + floor_boundary(&content, byte_range.end.max(byte_range.start)), + ); + self.pin_offscreen_row(app, &list_path, r); + let Some(end_ref) = self.resolve_end(&target_path, None) else { return false }; + let mut sel = Selection::new(target_path, content, (a, b), (a, b)); + sel.anchor_end = self.virtual_end_of(end_ref, a); + self.select_step(phase::Event::Select(sel)); + return true; + } + } + SelectRequest::All(_) => { + let row_path = format!("{list_path}/{}", self.commit.virtuals[&list_path].keys[r]); + let row_key = &self.commit.virtuals[&list_path].keys[r]; + let row_matches = row_path == selector || crate::flight::selects(selector, &row_path, Some(row_key)); + let matching: Vec<&OffscreenText> = if row_matches { + texts.iter().collect() + } else { + texts.iter().filter(|t| t.path == selector || crate::flight::selects(selector, &t.path, t.key.as_deref())).collect() + }; + if let Some(&first_t) = matching.first() { + let gp = first_t.group_path.as_deref(); + let last_t = match gp { + Some(g) => matching.iter().copied().filter(|t| t.group_path.as_deref() == Some(g)).last().unwrap_or(first_t), + None => first_t, + }; + let (p0, p1) = (first_t.path.clone(), last_t.path.clone()); + self.pin_offscreen_row(app, &list_path, r); + let (Some(e0), Some(e1)) = (self.resolve_end(&p0, None), self.resolve_end(&p1, None)) else { return false }; + self.select_span_ends(e0, e1); + return true; + } + } + SelectRequest::Clear => {} + } + } + } + false + } +} diff --git a/app/vendor/rune/crates/rune/src/runtime/virtual_list/window.rs b/app/vendor/rune/crates/rune/src/runtime/virtual_list/window.rs new file mode 100644 index 0000000..0ada4f9 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/virtual_list/window.rs @@ -0,0 +1,133 @@ +//! Virtual lists between commits: whether a window wants moving, and which rows show. + +use super::*; +use super::fill::{FillEffect, FillEvent}; + +impl types::TreeState { + /// Notes each list's rows drawn inside its viewport on the last frame, so the next window + /// keeps them mounted while they're still on screen. + pub(in crate::runtime) fn note_drawn_rows( + &self, + drawn: &[[f32; 4]], + virtuals: &mut HashMap<String, crate::el::virtual_list::VirtualList>, + ) { + if virtuals.is_empty() { return; } + // The last frame's rects describe these nodes only until a commit replaces them. + let fresh = self.is_built() && drawn.len() == self.nodes.len(); + let nodes = &self.nodes; + for (path, v) in virtuals.iter_mut() { + v.drawn.clear(); + let (true, Some(list), Some(view)) = (fresh, self.index_of_path(path), self.index_of_path(&v.scroll_path)) else { continue }; + let (top, bottom) = (drawn[view][1], drawn[view][1] + drawn[view][3]); + let rows = (list + 1..nodes.len()).take_while(|&j| nodes[j].parent >= Some(list)).filter(|&j| nodes[j].parent == Some(list)); + for j in rows.filter(|&j| drawn[j][3] > 0.0 && drawn[j][1] < bottom && drawn[j][1] + drawn[j][3] > top) { + v.drawn.extend(nodes[j].key.clone()); + } + } + } + + /// A list's scroll offset within its window, and whether that viewport is pinned to its end. + #[inline] + pub(in crate::runtime) fn virtual_window_offset( + &self, + scrolls: &HashMap<NodeId, ScrollState>, + v: &crate::el::virtual_list::VirtualList, + ) -> (f32, bool) { + self.id_of_path(&v.scroll_path).and_then(|id| scrolls.get(&id)) + .map_or((0.0, false), |s| v.at(s.offset as f32, s.pinned())) + } +} + +impl RuntimeCore { + pub(in crate::runtime) fn virtual_window_changed(&self) -> bool { + self.commit.virtuals.iter().any(|(path, v)| self.wants_window(path, v)) + } + + pub(in crate::runtime) fn report_visible_rows(&mut self) -> bool { + if self.commit.virtuals.is_empty() { return false; } + let mut queued = false; + for i in 0..self.tree.nodes.len() { + if self.tree.nodes[i].handlers.get().is_none_or(|h| h.on_visible_rows.is_none()) || self.subtree_exiting(i) { continue; } + let path = &self.tree.nodes[i].path; + let Some(v) = self.commit.virtuals.get_mut(path) else { continue }; + let (offset, pinned) = self.tree.virtual_window_offset(&self.scroll.scrolls, v); + let range = v.visible_range(offset, pinned); + if v.reported_visible.as_ref() != Some(&range) { + v.reported_visible = Some(range.clone()); + let p = path.clone(); + self.frame.queue.retain(|a| !matches!(a, Action::VisibleRows(q, _) if *q == p)); + self.frame.queue.push(Action::VisibleRows(p, range)); + queued = true; + } + } + queued + } + + /// Notes each list's rows drawn inside its viewport on the last frame, so the next window + /// keeps them mounted while they're still on screen. + #[inline] + pub(in crate::runtime) fn note_drawn_rows(&mut self) { + self.tree.note_drawn_rows(&self.paint.drawn, &mut self.commit.virtuals); + } + + pub(in crate::runtime) fn wants_window(&self, path: &str, v: &crate::el::virtual_list::VirtualList) -> bool { + let Some(i) = self.tree.id_of_path(path).and_then(|id| self.tree.index_of_id(id)) else { return false }; + if self.subtree_exiting(i) { return false; } + let (offset, pinned) = self.tree.virtual_window_offset(&self.scroll.scrolls, v); + v.needs_window(offset, pinned) + } + + /// Whether an index-built list wants its window moved, and whether one of those lists' own + /// viewports moved this frame. Another viewport's motion invalidates nothing here. + fn virtual_demand(&self) -> (bool, bool) { + let (mut wanted, mut moved) = (false, false); + for (path, v) in &self.commit.virtuals { + if !v.indexed || !self.wants_window(path, v) { continue; } + wanted = true; + moved |= self.tree.id_of_path(&v.scroll_path).and_then(|id| self.scroll.scrolls.get(&id)).is_some_and(|s| s.moving()); + } + (wanted, moved) + } + + /// Rows an index-built list still has to mount across the lists that want a window moved; + /// zero when every one of them is filled. + fn virtual_unfilled(&self) -> usize { + let mut unfilled = 0; + for (path, v) in &self.commit.virtuals { + if !v.indexed || !self.wants_window(path, v) { continue; } + let (offset, pinned) = self.tree.virtual_window_offset(&self.scroll.scrolls, v); + unfilled += v.unfilled(offset, pinned); + } + unfilled + } + + /// Whether an index-built list still mounts its overscan a little per frame, so the host + /// should draw another. Each such frame commits more rows; a few frames fill it. A list + /// whose heights keep changing past those frames waits a few frames out and resumes, until + /// the unfilled range stops shrinking. + pub(in crate::runtime) fn virtual_filling(&mut self) -> bool { + let now = self.clock; + let (wanted, moved) = self.virtual_demand(); + // A wake must draw nothing for a list that finished, unmounted or stopped filling: it + // retires the wait, and the deadline it left draws no frame of its own. + if !wanted { + self.commit.virtual_fill.step(FillEvent::Frame { now, wanted: false, missing: 0, moved: false }); + return false; + } + // The fill's own deadline, which it clears when it leaves the wait: a deadline a retired + // run left behind is not this call's cause, so the frame is read as any other. + if let Some(attempt) = self.commit.virtual_fill.wake(now) { + return !self.commit.virtual_fill.step(FillEvent::Due { attempt, now }).is_empty(); + } + // The count is only read at the bound, so a fill that finishes inside it costs none. + let missing = if self.commit.virtual_fill.at_bound() { self.virtual_unfilled() } else { 0 }; + let mut draw = false; + for effect in self.commit.virtual_fill.step(FillEvent::Frame { now, wanted, missing, moved }) { + match effect { + FillEffect::Draw => draw = true, + FillEffect::WakeAt(due) => self.wake_at(due), + } + } + draw + } +} diff --git a/app/vendor/rune/crates/rune/src/runtime/virtual_selection_tests.rs b/app/vendor/rune/crates/rune/src/runtime/virtual_selection_tests.rs new file mode 100644 index 0000000..2c4fc34 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/virtual_selection_tests.rs @@ -0,0 +1,470 @@ +//! Headless tests for text selection across virtual rows (`El::virtual_rows` / `El::virtualize`): +//! pinned anchor and focus rows, identity-based ends across mount/unmount, on-demand copy across +//! unbuilt rows (with `\t` for side-by-side cells and `\n` otherwise), Cmd+A / +//! `Tx::select_all_text` over a virtual list, `Tx::select_text` on an unbuilt row, and bounded +//! off-screen collection. +use std::cell::Cell; + +use crate::runtime::ElementInfo; +use crate::{Cx, El, Env, GrowthSpec, Key, KeyEvent, Mods, PhysicalInput, Runtime, ScrollSpec, TextStyle, col, row, text}; + +const ROWS: usize = 55; +const ROW_H: f32 = 56.0; + +#[derive(Default)] +struct Timeline { + count: usize, + big_bytes: usize, +} + +impl Timeline { + fn new(count: usize) -> Self { + Self { count, big_bytes: 0 } + } +} + +thread_local! { + static BUILT_ROWS: Cell<usize> = const { Cell::new(0) }; +} + +fn row_expected(i: usize) -> String { + if i % 5 == 2 { + format!("Row {i:02} header\nleft-{i:02}\tright-{i:02}") + } else { + format!("Row {i:02} header\nMessage body for virtual row {i:02} with words to select.") + } +} + +fn build_timeline_row(s: &Timeline, i: usize) -> El { + BUILT_ROWS.set(BUILT_ROWS.get() + 1); + let style = TextStyle::new(14.0, 400.0).lh(20.0); + let head = text(format!("Row {i:02} header")) + .key("head") + .font(style) + .w_full() + .selectable(true); + let body = if s.big_bytes > 0 { + let filler = "abcd ".repeat(s.big_bytes / 5); + text(format!("Row {i:05} {filler}")) + .key(format!("t{i}")) + .font(style) + .w_full() + .selectable(true) + } else if i % 5 == 2 { + row().key("cells").w_full().children([ + text(format!("left-{i:02}")).key("c0").font(style).w(160.0).selectable(true), + text(format!("right-{i:02}")).key("c1").font(style).w(160.0).selectable(true), + ]) + } else { + text(format!("Message body for virtual row {i:02} with words to select.")) + .key("body") + .font(style) + .w_full() + .selectable(true) + }; + col().w_full().h(ROW_H).padding(6.0).gap(4.0).children([head, body]) +} + +fn timeline_view(s: &Timeline, _: &mut Cx<Timeline>) -> El { + col().w_full().h_full().child( + col().key("scroll").w_full().grow(1.0).scroll(ScrollSpec { stick_bottom: false }).child( + col() + .key("timeline") + .w_full() + .growth(GrowthSpec::default()) + .selection_group(true) + .virtual_rows( + s.count, + ROW_H, + |_: &Timeline, i| format!("r{i}").into(), + build_timeline_row, + ), + ), + ) +} + +fn timeline(count: usize) -> Runtime<Timeline> { + let mut rt = Runtime::new(Timeline::new(count), timeline_view, (1280.0, 420.0), Env::new(true, 2.0)); + rt.frame(0.0); + while rt.frame(1.0 / 120.0) {} + BUILT_ROWS.set(0); + rt +} + +fn tick<S: 'static>(rt: &mut Runtime<S>) { + rt.frame(1.0 / 60.0); +} + +fn settle<S: 'static>(rt: &mut Runtime<S>) { + for _ in 0..20 { + if !rt.frame(1.0 / 60.0) { + break; + } + } +} + +fn command<S: 'static>(rt: &mut Runtime<S>, c: char) { + rt.key(KeyEvent { key: Key::Command(c), mods: Mods { cmd: true, ..Mods::default() } }); + tick(rt); +} + +fn find_path<S: 'static>(rt: &Runtime<S>, suffix: &str) -> ElementInfo { + rt.elements() + .into_iter() + .find(|e| e.path.ends_with(suffix)) + .unwrap_or_else(|| panic!("missing element {suffix}")) +} + +fn glyphs_at<S: 'static>(rt: &Runtime<S>, suffix: &str) -> Vec<(f32, f32)> { + let e = find_path(rt, suffix); + let mut out: Vec<(f32, f32)> = rt + .instances + .iter() + .filter(|i| i.params[1] == crate::render::KIND_GLYPH) + .map(|i| ((i.rect[0] + i.rect[2] / 2.0) / 2.0, (i.rect[1] + i.rect[3] / 2.0) / 2.0)) + .filter(|&(x, y)| x >= e.rect[0] && x <= e.rect[0] + e.rect[2] && y >= e.rect[1] && y <= e.rect[1] + e.rect[3]) + .collect(); + out.sort_by(|a, b| a.0.partial_cmp(&b.0).unwrap()); + out +} + +fn before(g: (f32, f32)) -> (f32, f32) { + (g.0 - 3.0, g.1) +} + +#[test] +fn cmd_a_and_select_all_text_over_55_virtual_rows_copy_every_row() { + let mut rt = timeline(ROWS); + let clipboard = crate::clipboard::memory(); + rt.use_clipboard(&clipboard); + + let mounted = rt.commit.virtuals["#0/scroll/timeline"].range.clone(); + assert_eq!(mounted, 0..23, "55 rows in 1280x420 mounts 23 rows"); + + let expected: String = (0..ROWS).map(row_expected).collect::<Vec<_>>().join("\n"); + + // 1. Cmd+A selects from the first row to the last row without mounting the unbuilt middle. + BUILT_ROWS.set(0); + command(&mut rt, 'a'); + assert!( + BUILT_ROWS.get() <= mounted.len() + 3, + "Cmd+A builds only the mounted window plus offscreen end row(s), built {}", + BUILT_ROWS.get() + ); + assert_eq!(rt.commit.virtuals["#0/scroll/timeline"].range, 0..23, "mounted window unchanged"); + assert_eq!(find_path(&rt, "r0/head").selected.as_deref(), Some("Row 00 header")); + assert_eq!(find_path(&rt, "r22/head").selected.as_deref(), Some("Row 22 header")); + + command(&mut rt, 'c'); + assert_eq!(clipboard.text().as_deref().map(String::as_str), Some(expected.as_str())); + assert_eq!(rt.selected_text().as_deref(), Some(expected.as_str())); + + // Clearing the selection releases the pinned rows. + rt.update(|_, tx| tx.clear_text_selection()); + tick(&mut rt); + assert!(rt.commit.virtuals["#0/scroll/timeline"].selection.pins.rows().is_empty()); + + // 2. Scrolled to the middle (neither r0 nor r54 mounted), Tx::select_all_text("timeline") + // pins both ends and copies all 55 rows. + for _ in 0..6 { + rt.wheel(640.0, 210.0, -160.0); + tick(&mut rt); + } + settle(&mut rt); + let mid_range = rt.commit.virtuals["#0/scroll/timeline"].range.clone(); + assert!(mid_range.start > 0 && mid_range.end < ROWS, "middle window: {mid_range:?}"); + + rt.update(|_, tx| tx.select_all_text("timeline")); + tick(&mut rt); + assert_eq!(rt.selected_text().as_deref(), Some(expected.as_str())); +} + +#[test] +fn selection_from_row_3_to_row_40_copies_all_rows_in_between_in_order() { + let mut rt = timeline(ROWS); + let clipboard = crate::clipboard::memory(); + rt.use_clipboard(&clipboard); + + // Built-only selection (row 1 to row 2, which has side-by-side cells) stays byte-identical. + // Non-space glyph indices in "Message body for virtual row XX with words to select.": + // 0..7 = "Message", 7..11 = "body", 11..14 = "for", 14..21 = "virtual", 21..24 = "row", 24..26 = "XX", 26..30 = "with" + let r1 = glyphs_at(&rt, "r1/body"); + let r2_c1 = glyphs_at(&rt, "r2/cells/c1"); + rt.pointer_move(before(r1[7]).0, before(r1[7]).1); + rt.pointer_down(before(r1[7]).0, before(r1[7]).1); + tick(&mut rt); + rt.pointer_move(before(r2_c1[5]).0, before(r2_c1[5]).1); + tick(&mut rt); + rt.pointer_up(before(r2_c1[5]).0, before(r2_c1[5]).1); + tick(&mut rt); + assert_eq!( + rt.selected_text().as_deref(), + Some("body for virtual row 01 with words to select.\nRow 02 header\nleft-02\tright") + ); + + // Click inside row 3 body ("virtual row 03 with words to select.") to place the anchor. + let r3 = glyphs_at(&rt, "r3/body"); + let start_pt = before(r3[14]); // before "virtual" + rt.pointer_move(start_pt.0, start_pt.1); + rt.pointer_down(start_pt.0, start_pt.1); + rt.pointer_up(start_pt.0, start_pt.1); + tick(&mut rt); + + // Scroll down until row 40 is visible inside the 420px viewport (40 * 56 - 1980 = 260) and row 3 is outside the viewport window. + for _ in 0..11 { + rt.wheel(640.0, 210.0, -180.0); + tick(&mut rt); + } + settle(&mut rt); + let range = rt.commit.virtuals["#0/scroll/timeline"].range.clone(); + assert!(!range.contains(&3) && range.contains(&40), "r3 unmounted, r40 mounted: {range:?}"); + + // Shift-click in row 40 body right after "40" (glyph 25). + let r40 = glyphs_at(&rt, "r40/body"); + let end_pt = (r40[25].0 + 3.0, r40[25].1); + assert!(end_pt.1 > 0.0 && end_pt.1 < 420.0, "r40/body inside viewport: {end_pt:?}"); + rt.physical_input(PhysicalInput::Modifiers(Mods { shift: true, ..Mods::default() })); + rt.pointer_move(end_pt.0, end_pt.1); + rt.pointer_down(end_pt.0, end_pt.1); + rt.pointer_up(end_pt.0, end_pt.1); + rt.physical_input(PhysicalInput::Modifiers(Mods::default())); + tick(&mut rt); + + let mut expected_parts = vec!["virtual row 03 with words to select.".to_owned()]; + for i in 4..40 { + expected_parts.push(row_expected(i)); + } + expected_parts.push("Row 40 header\nMessage body for virtual row 40".to_owned()); + let expected = expected_parts.join("\n"); + + assert_eq!(rt.selected_text().as_deref(), Some(expected.as_str())); + command(&mut rt, 'c'); + assert_eq!(clipboard.text().as_deref().map(String::as_str), Some(expected.as_str())); +} + +#[test] +fn selection_scrolled_far_away_and_back_keeps_highlight() { + let mut rt = timeline(ROWS); + let g = glyphs_at(&rt, "r1/body"); + let (p0, p1) = (before(g[0]), (g[10].0 + 3.0, g[10].1)); + rt.pointer_move(p0.0, p0.1); + rt.pointer_down(p0.0, p0.1); + tick(&mut rt); + rt.pointer_move(p1.0, p1.1); + tick(&mut rt); + rt.pointer_up(p1.0, p1.1); + tick(&mut rt); + + assert_eq!(rt.selected_text().as_deref(), Some("Message body")); + assert_eq!(find_path(&rt, "r1/body").selected.as_deref(), Some("Message body")); + + // Scroll to the very bottom so row 1 is far outside the mounted window. + for _ in 0..20 { + rt.wheel(640.0, 210.0, -200.0); + tick(&mut rt); + } + settle(&mut rt); + assert!(!rt.elements().iter().any(|e| e.path.ends_with("r1/body")), "r1 is unmounted"); + assert_eq!(rt.selected_text().as_deref(), Some("Message body"), "selection survives offscreen"); + + // Scroll all the way back to the top: the highlight on r1/body is still there. + for _ in 0..20 { + rt.wheel(640.0, 210.0, 200.0); + tick(&mut rt); + } + settle(&mut rt); + assert_eq!(find_path(&rt, "r1/body").selected.as_deref(), Some("Message body")); + assert_eq!(rt.selected_text().as_deref(), Some("Message body")); +} + +#[test] +fn dragging_selection_while_scrolling_across_virtual_rows_keeps_working() { + let mut rt = timeline(ROWS); + let g3 = glyphs_at(&rt, "r3/head"); + let p0 = before(g3[0]); + rt.pointer_move(p0.0, p0.1); + rt.pointer_down(p0.0, p0.1); + tick(&mut rt); + + // Drag down while the list scrolls until row 3 is unmounted and row 40 is under the pointer. + for _ in 0..12 { + rt.wheel(640.0, 210.0, -180.0); + rt.pointer_move(p0.0 + 40.0, 350.0); + tick(&mut rt); + } + settle(&mut rt); + assert!(!rt.commit.virtuals["#0/scroll/timeline"].range.contains(&3), "anchor row 3 scrolled out"); + + let g40 = glyphs_at(&rt, "r40/head"); + let p1 = (g40.last().unwrap().0 + 4.0, g40.last().unwrap().1); + rt.pointer_move(p1.0, p1.1); + tick(&mut rt); + rt.pointer_up(p1.0, p1.1); + tick(&mut rt); + + let mut expected_parts: Vec<String> = (3..40).map(row_expected).collect(); + expected_parts.push("Row 40 header".to_owned()); + let expected = expected_parts.join("\n"); + assert_eq!(rt.selected_text().as_deref(), Some(expected.as_str())); +} + +#[test] +fn tx_select_text_on_unbuilt_row_pins_and_applies_without_scrolling() { + let mut rt = timeline(ROWS); + assert_eq!(rt.commit.virtuals["#0/scroll/timeline"].range, 0..23); + assert!(!rt.elements().iter().any(|e| e.path.ends_with("r45/body")), "r45 starts unbuilt"); + + rt.update(|_, tx| tx.select_text("r45/body", 0..12)); + tick(&mut rt); + + // Must not scroll or mount row 45 into the layout window. + assert_eq!(rt.commit.virtuals["#0/scroll/timeline"].range, 0..23, "did not scroll"); + assert_eq!(rt.selected_text().as_deref(), Some("Message body")); + assert_eq!( + rt.text_selection(), + Some(("#0/scroll/timeline/r45/body", 0..12)), + ); + + // When the user later scrolls down to row 45, its highlight is drawn. + for _ in 0..20 { + rt.wheel(640.0, 210.0, -200.0); + tick(&mut rt); + } + settle(&mut rt); + assert_eq!(find_path(&rt, "r45/body").selected.as_deref(), Some("Message body")); +} + +#[test] +fn offscreen_collection_is_bounded_in_rows_and_bytes() { + // 1. Row count cap: 50,000 rows builds at most MAX_VIRTUAL_COPY_ROWS unbuilt rows on copy. + let mut rt = timeline(50_000); + let mounted_len = rt.commit.virtuals["#0/scroll/timeline"].range.len(); + BUILT_ROWS.set(0); + rt.update(|_, tx| tx.select_all_text("timeline")); + tick(&mut rt); + let built_on_select = BUILT_ROWS.get(); + assert!( + built_on_select <= mounted_len + 3, + "selecting all builds only mounted window + pinned ends, got {built_on_select}" + ); + + BUILT_ROWS.set(0); + let start = crate::time::now(); + let copied = rt.selected_text().expect("bounded copy returns prefix"); + let elapsed = start.elapsed(); + let built_on_copy = BUILT_ROWS.get(); + assert!( + built_on_copy <= super::virtual_selection::MAX_VIRTUAL_COPY_ROWS, + "built {built_on_copy} rows > cap {}", + super::virtual_selection::MAX_VIRTUAL_COPY_ROWS + ); + assert!(copied.starts_with("Row 00 header\n")); + assert!(elapsed.as_secs_f64() < 2.0, "bounded collection took {elapsed:?}"); + + // 2. Byte cap: large rows stop building as soon as MAX_VIRTUAL_COPY_BYTES is reached. + let mut rt = Runtime::new( + Timeline { count: 5_000, big_bytes: 4_000 }, + timeline_view, + (1280.0, 420.0), + Env::new(true, 2.0), + ); + rt.frame(0.0); + settle(&mut rt); + rt.update(|_, tx| tx.select_all_text("timeline")); + tick(&mut rt); + BUILT_ROWS.set(0); + let copied = rt.selected_text().expect("byte-capped copy"); + assert!( + copied.len() <= super::virtual_selection::MAX_VIRTUAL_COPY_BYTES, + "copied {} bytes > cap {}", + copied.len(), + super::virtual_selection::MAX_VIRTUAL_COPY_BYTES + ); + assert!( + BUILT_ROWS.get() < 1_200, + "byte cap stopped building early after {} rows", + BUILT_ROWS.get() + ); +} + +fn header_timeline_view(s: &Timeline, _: &mut Cx<Timeline>) -> El { + let style = TextStyle::new(14.0, 400.0).lh(20.0); + col().w_full().h_full().child( + col() + .key("scroll") + .w_full() + .grow(1.0) + .scroll(ScrollSpec { stick_bottom: false }) + .selection_group(true) + .children([ + col().key("header").w_full().h(84.0).padding(6.0).child( + text("Pinned thread header").key("title").font(style).w_full().selectable(true), + ), + col() + .key("timeline") + .w_full() + .growth(GrowthSpec::default()) + .virtual_rows( + s.count, + ROW_H, + |_: &Timeline, i| format!("r{i}").into(), + build_timeline_row, + ), + ]), + ) +} + +#[test] +fn header_before_virtual_list_keeps_pinned_selection_and_copies_across_unbuilt_rows() { + let mut rt = Runtime::new(Timeline::new(ROWS), header_timeline_view, (1280.0, 420.0), Env::new(true, 2.0)); + rt.frame(0.0); + while rt.frame(1.0 / 120.0) {} + let clipboard = crate::clipboard::memory(); + rt.use_clipboard(&clipboard); + assert_eq!(rt.commit.virtuals["#0/scroll/timeline"].top, 84.0); + + // Click in row 3 body before "virtual" (y = 84 + 3 * 56 = 252..308, inside the 420px viewport). + let r3 = glyphs_at(&rt, "r3/body"); + let start_pt = before(r3[14]); + rt.pointer_move(start_pt.0, start_pt.1); + rt.pointer_down(start_pt.0, start_pt.1); + rt.pointer_up(start_pt.0, start_pt.1); + tick(&mut rt); + + // Scroll down until row 3 is unmounted and row 40 is visible inside the viewport. + for _ in 0..11 { + rt.wheel(640.0, 210.0, -180.0); + tick(&mut rt); + } + settle(&mut rt); + let range = rt.commit.virtuals["#0/scroll/timeline"].range.clone(); + assert!(!range.contains(&3) && range.contains(&40), "r3 unmounted, r40 mounted: {range:?}"); + + let r40 = glyphs_at(&rt, "r40/body"); + let end_pt = (r40[25].0 + 3.0, r40[25].1); + assert!(end_pt.1 > 0.0 && end_pt.1 < 420.0, "r40/body inside viewport: {end_pt:?}"); + rt.physical_input(PhysicalInput::Modifiers(Mods { shift: true, ..Mods::default() })); + rt.pointer_move(end_pt.0, end_pt.1); + rt.pointer_down(end_pt.0, end_pt.1); + rt.pointer_up(end_pt.0, end_pt.1); + rt.physical_input(PhysicalInput::Modifiers(Mods::default())); + tick(&mut rt); + + let mut expected_parts = vec!["virtual row 03 with words to select.".to_owned()]; + for i in 4..40 { + expected_parts.push(row_expected(i)); + } + expected_parts.push("Row 40 header\nMessage body for virtual row 40".to_owned()); + let expected = expected_parts.join("\n"); + assert_eq!(rt.selected_text().as_deref(), Some(expected.as_str())); + command(&mut rt, 'c'); + assert_eq!(clipboard.text().as_deref().map(String::as_str), Some(expected.as_str())); + + // Selecting all of the group from the middle window includes the header and all 55 rows. + rt.update(|_, tx| tx.select_all_text("scroll")); + tick(&mut rt); + let mut full_parts = vec!["Pinned thread header".to_owned()]; + full_parts.extend((0..ROWS).map(row_expected)); + let full_expected = full_parts.join("\n"); + assert_eq!(rt.selected_text().as_deref(), Some(full_expected.as_str())); +} diff --git a/app/vendor/rune/crates/rune/src/runtime/virtual_store_tests.rs b/app/vendor/rune/crates/rune/src/runtime/virtual_store_tests.rs new file mode 100644 index 0000000..96cf3ba --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/virtual_store_tests.rs @@ -0,0 +1,71 @@ +//! A commit's kept offscreen rows go before that commit's row builders run +//! (`commit/measure.rs`), so a row holding a resource doesn't keep it through building its +//! replacement. + +use std::cell::Cell; +use std::rc::Rc; + +use super::*; +use crate::{GrowthSpec, ScrollSpec, col, el}; + +const COUNT: usize = 30; +const ROW_H: f32 = 40.0; +/// Far below the 200 pt viewport, so this row is kept, not mounted. +const HELD_ROW: usize = 25; + +struct List { + /// Build rows with [`El::virtual_rows`] instead of children. + indexed: bool, + /// A resource the kept row holds while it lives; only the row clones it. + held: Rc<()>, + /// Row builders that found the resource still alive. + saw_held: Cell<usize>, +} + +impl List { + fn new() -> Self { + List { indexed: false, held: Rc::new(()), saw_held: Cell::new(0) } + } +} + +fn list(s: &List, _: &mut Cx<List>) -> El { + let stack = if s.indexed { + col().key("stack").w_full().growth(GrowthSpec::default()).virtual_rows( + COUNT, + ROW_H, + |_: &List, i| format!("r{i}").into(), + |s: &List, i| { + if Rc::strong_count(&s.held) > 1 { + s.saw_held.set(s.saw_held.get() + 1); + } + el().key(format!("r{i}")).w_full().h(ROW_H).fill(Color::WHITE) + }, + ) + } else { + let held = s.held.clone(); + col().key("stack").w_full().growth(GrowthSpec::default()).virtualize(ROW_H).children((0..COUNT).map(|i| { + let row = el().key(format!("r{i}")).w_full().h(ROW_H).fill(Color::WHITE); + if i == HELD_ROW { + let held = held.clone(); + row.on_press(move |_: &mut List| { let _ = &held; }) + } else { + row + } + })) + }; + col().w_full().h_full() + .child(col().key("scroll").w_full().h(200.0).scroll(ScrollSpec { stick_bottom: false }).child(stack)) +} + +#[test] +fn stored_rows_drop_before_the_row_builders_run() { + let mut rt = Runtime::new(List::new(), list, (400.0, 200.0), Env::new(true, 2.0)); + rt.frame(0.0); + while rt.frame(1.0 / 120.0) {} + let kept = &rt.commit.virtuals["#0/scroll/stack"].selection.stored; + assert!(kept.contains_key(&HELD_ROW), "a row below the viewport is kept: {:?}", kept.keys().collect::<Vec<_>>()); + assert_eq!(Rc::strong_count(&rt.state.held), 2, "the kept row holds the resource"); + rt.update(|s, _| s.indexed = true); + while rt.frame(1.0 / 120.0) {} + assert_eq!(rt.state.saw_held.get(), 0, "the kept rows went before any builder ran"); +} diff --git a/app/vendor/rune/crates/rune/src/runtime/visible.rs b/app/vendor/rune/crates/rune/src/runtime/visible.rs new file mode 100644 index 0000000..9e3a086 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/visible.rs @@ -0,0 +1,48 @@ +//! `El::on_visible`: telling an element when it comes on screen and when it leaves, as a web +//! page's `IntersectionObserver` does, so a demo plays when the reader reaches it and a loop +//! stops when they scroll past. It reads where each frame drew the element, after scroll +//! viewports and a web page's own scroll (`App::web_document`). +use super::*; + +/// Whether `rect` (`[x, y, w, h]`) counts as on screen in a window `view` points big: half of +/// it shows, or it covers half the window (an element taller than the window). +pub(crate) fn on_screen(rect: [f32; 4], view: (f32, f32)) -> bool { + let w = (rect[0] + rect[2]).min(view.0) - rect[0].max(0.0); + let h = (rect[1] + rect[3]).min(view.1) - rect[1].max(0.0); + if w <= 0.0 || h <= 0.0 { return false; } + let need = 0.5 * (rect[2] * rect[3]).min(view.0 * view.1); + w * h >= need +} + +impl RuntimeCore { + /// Queues `on_visible` for elements that came on screen or left it since the last frame. + /// True when it queued any. + pub(super) fn report_visible(&mut self) -> bool { + if !self.tree.has_drawn_layout() && self.commit.visible_fired_empty() { return false; } + let last = self.commit.take_visible_fired(); + let mut seen = HashMap::with_capacity_and_hasher(last.len(), Default::default()); + let mut queued = false; + // A page draws a band that starts above the window and ends below it; what's on screen is + // the window inside the band, not the band. + let (top, view) = self.page_window(); + for i in 0..self.tree.nodes.len() { + let n = &self.tree.nodes[i]; + if n.handlers.get().is_none_or(|h| h.on_visible.is_none()) || self.subtree_exiting(i) { continue; } + let Some(&drawn) = self.paint.drawn.get(i) else { continue }; + let on = on_screen([drawn[0], drawn[1] - top, drawn[2], drawn[3]], (self.viewport.0, view)); + seen.insert(n.id, on); + if last.get(&n.id).copied().unwrap_or(false) != on { + let path = n.path.clone(); + self.frame.queue.retain(|a| !matches!(a, Action::Visible(p, _) if *p == path)); + self.frame.queue.push(Action::Visible(path, on)); + queued = true; + } + } + self.commit.set_visible_fired(seen); + queued + } +} + +#[cfg(test)] +#[path = "visible_tests.rs"] +mod tests; diff --git a/app/vendor/rune/crates/rune/src/runtime/visible_tests.rs b/app/vendor/rune/crates/rune/src/runtime/visible_tests.rs new file mode 100644 index 0000000..7d67cfd --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/visible_tests.rs @@ -0,0 +1,51 @@ +use super::*; + +#[derive(Default)] +struct Seen { + log: Vec<bool>, +} + +fn page(_: &Seen, _: &mut Cx<Seen>) -> El { + crate::col().w_full() + .child(crate::col().key("top").w_full().h(500.0)) + .child(crate::col().key("demo").w_full().h(100.0).on_visible(|s: &mut Seen, on, _| s.log.push(on))) + .child(crate::col().key("bottom").w_full().h(600.0)) +} + +#[test] +fn an_element_hears_when_the_page_scrolls_it_on_screen_and_off() { + let mut rt = Runtime::new(Seen::default(), page, (400.0, 200.0), Env::default()); + rt.page_mode(); + rt.frame(0.0); + rt.frame(0.0); + assert!(rt.state.log.is_empty(), "off screen at first, and nothing to say"); + + rt.set_page_scroll(330.0); + rt.frame(0.0); + rt.frame(0.0); + assert!(rt.state.log.is_empty(), "30 of its 100 points show: not yet"); + + rt.set_page_scroll(360.0); + rt.frame(0.0); + rt.frame(0.0); + assert_eq!(rt.state.log, [true], "60 points show"); + + rt.set_page_scroll(450.0); + rt.frame(0.0); + rt.frame(0.0); + assert_eq!(rt.state.log, [true], "still on screen: no second report"); + + rt.set_page_scroll(800.0); + rt.frame(0.0); + rt.frame(0.0); + assert_eq!(rt.state.log, [true, false]); +} + +#[test] +fn half_of_it_or_half_the_window_counts() { + let view = (400.0, 200.0); + assert!(on_screen([0.0, 150.0, 400.0, 100.0], view)); + assert!(!on_screen([0.0, 151.0, 400.0, 100.0], view)); + assert!(on_screen([0.0, -400.0, 400.0, 1000.0], view), "taller than the window, covering it"); + assert!(!on_screen([0.0, 200.0, 400.0, 100.0], view)); +} diff --git a/app/vendor/rune/crates/rune/src/runtime/web.rs b/app/vendor/rune/crates/rune/src/runtime/web.rs new file mode 100644 index 0000000..eb8c143 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/web.rs @@ -0,0 +1,8 @@ +//! Web runtime bridge, accessibility mirror, page metadata and static HTML export. +use super::*; + +pub(crate) mod a11y; +pub(crate) mod export; +pub(crate) mod page; +#[cfg(any(test, target_arch = "wasm32"))] +pub(crate) mod runtime; diff --git a/app/vendor/rune/crates/rune/src/runtime/web/a11y.rs b/app/vendor/rune/crates/rune/src/runtime/web/a11y.rs new file mode 100644 index 0000000..3cbb46a --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/web/a11y.rs @@ -0,0 +1,746 @@ +//! Hidden semantic DOM mirror for the browser shell: landmarks, headings, text runs with inline +//! links, links, images and buttons positioned over the canvas so assistive tech, the keyboard +//! and browser Find-in-page see the scene. In a page (`App::web_document`) the rects are in +//! document coordinates and the mirror carries the page's scroll, selection and anchors. +#![cfg_attr(not(target_arch = "wasm32"), allow(dead_code))] +use std::hash::{Hash, Hasher}; + +use serde_json::{Value, json}; + +use super::*; +use crate::a11y::roles; + +#[derive(Default)] +pub(crate) struct A11yMirror { + commits: u64, + viewport: (u32, u32), + scroll_digest: u64, + /// Whether motion ran at the last build, and when (clock seconds) it was. + moving: bool, + built_at: f64, + json: String, + /// The focus proxy last sent (`web_a11y_focus`), and the commit and focus it was read at. + focus_at: (u64, String), + focus_json: String, +} + +/// While motion runs (a sheet sliding in, a panel opening), how often the mirror follows what's +/// drawn. Its boxes are the drawn ones, so a build at the commit alone keeps a sliding element +/// where it started: off screen for a sheet, under a reader's focus ring. +const MOVING_EVERY: f64 = 0.1; + +#[derive(Debug, PartialEq)] +pub(crate) struct A11yItem { + pub kind: &'static str, + pub path: String, + /// `[x, y, w, h]` in CSS pixels: viewport points, or document points in a page. + pub rect: [f32; 4], + pub font_size: f32, + pub level: Option<u32>, + pub expanded: Option<bool>, + pub text: String, + pub runs: Vec<A11yRun>, + /// The HTML element a container stands for (`main`, `nav`, `section`, `ul`, ...). + pub tag: Option<&'static str>, + /// The ARIA role it carries (a table's parts: `table`, `row`, `cell`, ...). + pub role: Option<&'static str>, + /// The index of the container item it sits in. + pub parent: Option<usize>, + /// The element id an anchor link scrolls to (`#key`). + pub id: Option<String>, + /// A link's URL. + pub href: Option<String>, + /// Text's font, so the browser's Find highlight (and, in a page, its selection) lands on the + /// drawn glyphs. + pub font: Option<A11yFont>, + /// Text the browser selects and copies, in a page: `El::selectable` text, and text outside + /// anything that takes the pointer (`Runtime::page_text_selects`). + pub selectable: bool, + /// What describes it beyond its name (`El::description`, `El::described_by`'s words): + /// `aria-description`. + pub description: String, + /// A control's states, for a button carrying a control's role (`role`): `aria-selected`, + /// `aria-checked`, and its place in its set (`El::position_in_set`). + pub selected: Option<bool>, + pub checked: Option<&'static str>, + pub set: Option<(usize, usize)>, +} + +#[derive(Clone, Debug, PartialEq)] +pub(crate) struct A11yFont { + /// `"sans"`, `"mono"` or a family name. + pub family: String, + pub weight: f32, + pub line_height: f32, + pub tracking: f32, + pub italic: bool, + /// `"left"`, `"center"` or `"right"`. + pub align: &'static str, +} + +#[derive(Clone, Debug, PartialEq)] +pub(crate) struct A11yRun { + pub text: String, + pub href: Option<String>, + pub path: Option<String>, + pub link: Option<usize>, +} + +impl A11yItem { + fn new(kind: &'static str, path: &str, rect: [f32; 4]) -> Self { + A11yItem { kind, path: path.to_owned(), rect, font_size: 0.0, level: None, expanded: None, text: String::new(), + runs: Vec::new(), tag: None, role: None, parent: None, id: None, href: None, font: None, selectable: false, description: String::new(), selected: None, checked: None, set: None } + } + + fn to_json(&self) -> Value { + let mut obj = serde_json::Map::new(); + obj.insert("k".into(), json!(self.kind)); + obj.insert("p".into(), json!(self.path)); + obj.insert("r".into(), json!(self.rect)); + if self.font_size != 0.0 { obj.insert("s".into(), json!(self.font_size)); } + if let Some(l) = self.level { obj.insert("l".into(), json!(l)); } + if let Some(x) = self.expanded { obj.insert("x".into(), json!(x)); } + if !self.text.is_empty() { obj.insert("t".into(), json!(self.text)); } + if !self.description.is_empty() { obj.insert("d".into(), json!(self.description)); } + if let Some(s) = self.selected { obj.insert("se".into(), json!(s)); } + if let Some(c) = self.checked { obj.insert("c".into(), json!(c)); } + if let Some((pos, size)) = self.set { obj.insert("n".into(), json!([pos, size])); } + if let Some(g) = self.tag { obj.insert("g".into(), json!(g)); } + if let Some(o) = self.role { obj.insert("o".into(), json!(o)); } + if let Some(a) = self.parent { obj.insert("a".into(), json!(a)); } + if let Some(id) = &self.id { obj.insert("i".into(), json!(id)); } + if let Some(h) = &self.href { obj.insert("h".into(), json!(h)); } + if let Some(f) = &self.font { + obj.insert("f".into(), json!([f.family, f.weight, f.line_height, f.tracking, f.italic, f.align])); + } + if self.selectable { obj.insert("e".into(), json!(true)); } + if !self.runs.is_empty() { + let runs: Vec<Value> = self.runs.iter().map(|r| { + let mut ro = serde_json::Map::new(); + ro.insert("t".into(), json!(r.text)); + if let Some(h) = &r.href { ro.insert("h".into(), json!(h)); } + if let Some(p) = &r.path { ro.insert("p".into(), json!(p)); } + if let Some(i) = r.link { ro.insert("i".into(), json!(i)); } + Value::Object(ro) + }).collect(); + obj.insert("u".into(), Value::Array(runs)); + } + Value::Object(obj) + } +} + +/// An element id from a key, for anchors: letters, digits, `-` and `_`, starting with a letter. +pub(crate) fn anchor_id(key: Option<&str>) -> Option<String> { + let key = key?; + let ok = key.chars().next().is_some_and(|c| c.is_ascii_alphabetic()) + && key.chars().all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_'); + ok.then(|| key.to_owned()) +} + +pub(crate) fn family_name(family: crate::tok::Family) -> String { + match family { + crate::tok::Family::Sans => "sans".into(), + crate::tok::Family::Mono | crate::tok::Family::SystemMono => "mono".into(), + crate::tok::Family::Named(name) => name.into(), + } +} + +pub(crate) fn align_name(align: crate::el::Align) -> &'static str { + match align { + crate::el::Align::Center => "center", + crate::el::Align::End => "right", + crate::el::Align::Start => "left", + } +} + +/// Node `n` takes the pointer: a press, drag, gesture or pointer handler, a control, or a field. +/// Hover alone doesn't count; the page's mirror forwards hover to the canvas. +pub(crate) fn takes_pointer(n: &Node) -> bool { + let h = &n.handlers; + h.on_press.is_some() || h.on_double_press.is_some() || h.on_secondary_press.is_some() || h.on_middle_press.is_some() + || h.on_pointer_move.is_some() || h.on_drag.is_some() || h.drag_out.is_some() || h.on_drag_start.is_some() + || h.gestures.as_ref().is_some_and(|g| g.takes_gestures()) + || n.input.is_some() || n.window_drag == crate::el::WindowDrag::Drag + || n.a11y.more.as_ref().is_some_and(|m| m.href.is_some()) + || roles::takes_pointer(n.role) +} + +fn round1(v: f32) -> f32 { (v * 10.0).round() / 10.0 } + +pub(crate) fn clean_slice(spec: &crate::el::TextSpec, a: usize, b: usize) -> String { + let a = a.min(spec.content.len()); + let b = b.min(spec.content.len()).max(a); + if spec.cold.uncopied.is_empty() { + return spec.content[a..b].to_owned(); + } + let mut out = String::with_capacity(b - a); + let mut cur = a; + for &(ua, ub) in &spec.cold.uncopied { + let (ua, ub) = (ua as usize, ub as usize); + if ub <= cur || ua >= b { continue; } + let stop = ua.max(cur).min(b); + if cur < stop { out.push_str(&spec.content[cur..stop]); } + cur = ub.min(b); + } + if cur < b { out.push_str(&spec.content[cur..b]); } + out +} + +fn text_runs(path: &str, spec: &crate::el::TextSpec) -> Vec<A11yRun> { + if spec.cold.links.is_empty() { + let t = clean_slice(spec, 0, spec.content.len()); + return if t.is_empty() { Vec::new() } else { vec![A11yRun { text: t, href: None, path: None, link: None }] }; + } + let mut out = Vec::new(); + let mut at = 0usize; + for (idx, link) in spec.cold.links.iter().enumerate() { + let (la, lb) = ((link.start as usize).min(spec.content.len()), (link.end as usize).min(spec.content.len())); + if la > at { + let before = clean_slice(spec, at, la); + if !before.is_empty() { + out.push(A11yRun { text: before, href: None, path: None, link: None }); + } + } + if lb > la { + let label = clean_slice(spec, la, lb); + if !label.is_empty() { + out.push(A11yRun { + text: label, + href: Some(link.id.clone()), + path: Some(path.to_owned()), + link: Some(idx), + }); + } + } + at = at.max(lb); + } + if at < spec.content.len() { + let tail = clean_slice(spec, at, spec.content.len()); + if !tail.is_empty() { + out.push(A11yRun { text: tail, href: None, path: None, link: None }); + } + } + out +} + +impl RuntimeCore { + fn scroll_digest(&self) -> u64 { + let mut h = std::collections::hash_map::DefaultHasher::new(); + // A page hands horizontal scrolling to the DOM, whose container scrolls its own children: + // its offset changes nothing in the mirror, and hashing it would rewrite the whole page's + // items on every frame of a horizontal flick. + let mut entries: Vec<_> = self.scroll.scrolls.iter() + .map(|(id, s)| (id.0, s.offset.to_bits(), if self.host.page.is_some() { 0 } else { s.x.offset.to_bits() })) + .collect(); + entries.sort_unstable_by_key(|e| e.0); + entries.hash(&mut h); + h.finish() + } + + pub(crate) fn subtree_end(&self, root: usize) -> usize { + let mut j = root + 1; + while j < self.tree.nodes.len() { + if std::iter::successors(self.tree.nodes[j].parent, |&p| self.tree.nodes[p].parent).any(|p| p == root) { + j += 1; + } else { + break; + } + } + j + } + + /// Every live node's contiguous subtree end, in one pass. Exiting nodes sit after the live + /// tree with `parent` pointing back into it, so they must not stretch a live ancestor's span + /// past its later live siblings. + fn subtree_ends(&self) -> Vec<usize> { + let mut ends: Vec<usize> = (1..=self.tree.nodes.len()).collect(); + let mut open: Vec<usize> = Vec::new(); + for (i, n) in self.tree.nodes.iter().enumerate() { + if self.is_exiting(n.id) || !self.scene.contains(n.id) { + for done in open.drain(..) { ends[done] = i; } + continue; + } + while open.last().is_some_and(|&a| Some(a) != n.parent) { + let done = open.pop().unwrap(); + ends[done] = i; + } + // A descendant of an exiting or unmounted node has no live parent on `open`; leave it + // unopened so it cannot pull later nodes into a span. + if n.parent.is_none() || open.last() == n.parent.as_ref() { + open.push(i); + } + } + for done in open { ends[done] = self.tree.nodes.len(); } + ends + } + + /// In a page, which nodes' text the browser selects without `El::selectable`, as a web page's + /// text selects: all of it but text inside something that takes the pointer (mirrored text + /// takes the pointer from the canvas, so it would swallow that control's press) or inside + /// `El::unselectable`. Empty outside a page. A parent always comes before its children. + pub(crate) fn page_text_selects(&self) -> Vec<bool> { + if self.host.page.is_none() { return Vec::new(); } + let mut out = vec![false; self.tree.nodes.len()]; + for (i, n) in self.tree.nodes.iter().enumerate() { + let inherited = n.parent.is_none_or(|p| out[p]); + out[i] = inherited && !n.a11y.unselectable && !takes_pointer(n); + } + out + } + + pub(crate) fn descendant_label(&self, root: usize, end: usize) -> String { + let mut parts = Vec::new(); + for j in root..end { + if !self.allowed(j) || self.subtree_exiting(j) || self.tree.nodes[j].vis.opacity <= 0.01 { continue; } + if let Some(lbl) = self.tree.nodes[j].label.as_deref().filter(|s| !s.trim().is_empty()) { + parts.push(lbl.trim().to_owned()); + continue; + } + if let Some(spec) = self.tree.nodes[j].text.as_deref().filter(|t| !t.redacted && self.tree.nodes[j].input.is_none()) { + let s = clean_slice(spec, 0, spec.content.len()); + if !s.trim().is_empty() { parts.push(s.trim().to_owned()); } + } + } + parts.join(" ") + } + + /// Collect semantic DOM items for the current laid-out scene. + pub fn a11y_json(&self) -> String { + let values: Vec<Value> = self.web_a11y_items().iter().map(A11yItem::to_json).collect(); + serde_json::to_string(&values).unwrap_or_else(|_| "[]".into()) + } + + /// Node `i`'s drawn box in the mirror's coordinates: the band's, plus where the band starts in + /// the document, and `dx` points right for content inside a horizontal scroller the browser + /// scrolls itself. Both are added in `f64` and rounded once, so a fractional device-pixel + /// scroll offset can't round the same document position two ways between frames. + fn mirror_rect(&self, i: usize, dx: f64) -> [f32; 4] { + let b = self.drawn_box(i); + let (dx, dy) = (dx, f64::from(self.page_offset())); + let (left, right) = (f64::from(b[0]) + dx, f64::from(b[2]) + dx); + let (top, bottom) = (f64::from(b[1]) + dy, f64::from(b[3]) + dy); + [round1(left as f32), round1(top as f32), round1((right - left).max(0.0) as f32), round1((bottom - top).max(0.0) as f32)] + } + + pub(crate) fn web_a11y_items(&self) -> Vec<A11yItem> { + let mut out: Vec<A11yItem> = Vec::new(); + let mut last_flow_parent: Option<usize> = None; + let mut inline: Option<Inline> = None; + let ends = self.subtree_ends(); + let selects = self.page_text_selects(); + // Open containers: (end of their node subtree, their item index). + let mut open: Vec<(usize, usize)> = Vec::new(); + // Open horizontal scrollers and how far the browser has scrolled each, so their content + // mirrors where it sits inside them rather than where the scroll puts it. + let mut scrollers: Vec<(usize, f64)> = Vec::new(); + let mut i = 0; + while i < self.tree.nodes.len() { + while open.last().is_some_and(|&(end, _)| i >= end) { open.pop(); } + while scrollers.last().is_some_and(|&(end, _)| i >= end) { scrollers.pop(); } + let parent = open.last().map(|&(_, item)| item); + let n = &self.tree.nodes[i]; + let end = ends[i]; + // An open modal's ancestors (the root among them) are outside its scope but hold it: + // go into them, saying nothing of them, so the modal is mirrored and the rest isn't. + if !n.inert && !self.modal_member(i) && self.modal_ancestor(i, end) { + i += 1; + last_flow_parent = None; + continue; + } + if !self.allowed(i) || self.subtree_exiting(i) || n.vis.opacity <= 0.01 || n.a11y.hidden + || matches!(n.role, "none" | "presentation") + { + i = end; + last_flow_parent = None; + continue; + } + if n.input.is_some() { + i = end; + last_flow_parent = None; + continue; + } + // A page hands every horizontal viewport to the DOM: iOS scrolls it natively, at the + // compositor's rate, with axis locking, momentum and text selection. + if self.host.page.is_some() && n.scroll_axes == crate::el::ScrollAxes::X { + let rect = self.mirror_rect(i, 0.0); + let shift = self.scroll.scrolls.get(&n.id).map_or(0.0, |st| st.x.shift()); + let mut item = A11yItem::new("scroll_x", &n.path, rect); + item.tag = Some("div"); + item.parent = parent; + out.push(item); + open.push((end, out.len() - 1)); + scrollers.push((end, shift)); + last_flow_parent = None; + i += 1; + continue; + } + let shift: f64 = scrollers.iter().map(|&(_, offset)| offset).sum(); + let rect = self.mirror_rect(i, shift); + let push = |out: &mut Vec<A11yItem>, mut item: A11yItem| { + item.parent = parent; + out.push(item); + }; + + // A labelled `group` (a game's surface naming its keys, a set of controls) is a div + // with the role and its label; an unlabelled one adds nothing a reader would say. + let labelled_group = n.role == "group" && self.mirror_name(i).is_some(); + if let Some(tag) = roles::container_tag(n.role).or(labelled_group.then_some("div")) { + let mut item = A11yItem::new("group", &n.path, rect); + item.tag = Some(tag); + item.role = roles::container_aria(n.role).or(labelled_group.then_some("group")); + item.id = anchor_id(n.key.as_deref()); + item.text = self.mirror_name(i).unwrap_or_default(); + item.description = self.mirror_description(i); + push(&mut out, item); + open.push((end, out.len() - 1)); + last_flow_parent = None; + i += 1; + continue; + } + if let Some(href) = n.a11y.more.as_ref().and_then(|m| m.href.clone()) { + let label = self.mirror_name(i).unwrap_or_else(|| self.descendant_label(i, end)); + if !label.is_empty() && rect[2] > 0.0 && rect[3] > 0.0 { + let mut item = A11yItem::new("link", &n.path, rect); + item.text = label; + item.href = Some(href); + item.id = anchor_id(n.key.as_deref()); + push(&mut out, item); + } + i = end; + last_flow_parent = None; + continue; + } + if matches!(n.role, "image" | "img") && let Some(label) = self.mirror_name(i) { + let mut item = A11yItem::new("image", &n.path, rect); + item.text = label; + push(&mut out, item); + i = end; + last_flow_parent = None; + continue; + } + let button_like = (n.role == "button" || n.handlers.on_press.is_some()) && n.window_drag != crate::el::WindowDrag::Drag; + // Only collapse a pressable container into one button when it doesn't wrap an entire + // multi-block section with independent buttons inside. + let nested_press = (i + 1..end).any(|j| self.tree.nodes[j].handlers.on_press.is_some() || self.tree.nodes[j].role == "button"); + if button_like && !nested_press && rect[2] > 0.0 && rect[3] > 0.0 { + let label = self.mirror_name(i).unwrap_or_else(|| self.descendant_label(i, end)); + if !label.is_empty() { + let mut item = A11yItem::new("button", &n.path, rect); + item.expanded = n.a11y.expanded; + item.text = label; + item.description = self.mirror_description(i); + if let Some(role) = roles::web_control_role(n.role) { + item.role = Some(role); + if self.a11y_role(i).is_some_and(roles::selectable_item) { item.selected = Some(n.focus.selected); } + item.checked = n.a11y.checked.map(|c| match c { crate::el::Checked::True => "true", crate::el::Checked::False => "false", crate::el::Checked::Mixed => "mixed" }) + .or_else(|| (n.role == "radio").then_some(if n.focus.selected { "true" } else { "false" })); + item.set = n.a11y.more.as_ref().and_then(|m| m.set); + } + push(&mut out, item); + i = end; + last_flow_parent = None; + continue; + } + } + if let Some(spec) = n.text.as_deref().filter(|t| !t.redacted && rect[2] > 0.0 && rect[3] > 0.0) { + let runs = text_runs(&n.path, spec); + let selectable = spec.selectable || selects.get(i).copied().unwrap_or(false); + if !runs.is_empty() { + let is_heading = n.role == "heading"; + // Flowed word-by-word paragraphs (`pr_chips::flow`) put sibling words (or 1-word + // wrapper rows) inside one flex-wrap line row: merge consecutive inline text runs + // sharing that flow container so screen readers and Find-in-page see whole sentences. + let flow_group = n.parent.and_then(|p| { + if self.tree.nodes[p].key.as_deref().is_none() && self.tree.nodes[p].parent.is_some() + && self.tree.nodes[i].key.as_deref().is_some_and(|k| k.starts_with("flow-")) + { + self.tree.nodes[p].parent + } else if self.tree.nodes[i].key.as_deref().is_some_and(|k| k.starts_with("flow-")) { + Some(p) + } else { + None + } + }); + if !is_heading && flow_group.is_some() && flow_group == last_flow_parent + && let Some(prev) = out.last_mut().filter(|it| it.kind == "text") + { + merge_flow(prev, rect, runs); + i += 1; + continue; + } + let text_rect = inset_rect(rect, n.inset); + if !is_heading && flow_group.is_none() + && let Some(prev) = inline.filter(|l| l.item + 1 == out.len() && l.parent == n.parent) + && let Some(gap) = prev.gap(n.target, spec.style, selectable) + && let Some(item) = out.last_mut().filter(|it| it.kind == "text") + { + join_inline(item, text_rect, runs, gap > spec.style.size * 0.15); + inline = Some(Inline { right: n.target[2], ..prev }); + i += 1; + continue; + } + let (plain, rich_runs) = if runs.len() == 1 && runs[0].href.is_none() && flow_group.is_none() { + (runs.into_iter().next().unwrap().text, Vec::new()) + } else { + (String::new(), runs) + }; + let mut item = A11yItem::new(if is_heading { "heading" } else { "text" }, &n.path, rect); + item.font_size = round1(spec.style.size); + item.level = is_heading.then(|| n.a11y.level.unwrap_or(2).clamp(1, 6)); + item.text = plain; + item.runs = rich_runs; + item.id = if is_heading { anchor_id(n.key.as_deref()) } else { None }; + // Laid out in the drawn text's font, so the browser's Find highlight (and, in a + // page, its selection) lands on the glyphs. + item.rect = text_rect; + let style = spec.style; + item.font = Some(A11yFont { + family: family_name(style.family), + weight: style.weight, + line_height: round1(if style.line_height > 0.0 { style.line_height } else { style.size * 1.25 }), + tracking: style.tracking, + italic: style.italic, + align: align_name(spec.align), + }); + if self.host.page.is_some() { + item.selectable = selectable; + } + push(&mut out, item); + last_flow_parent = if is_heading { None } else { flow_group }; + inline = (!is_heading && flow_group.is_none()).then(|| Inline { + parent: n.parent, + item: out.len() - 1, + right: n.target[2], + top: n.target[1], + bottom: n.target[3], + style: spec.style, + selectable, + }); + } + } else if n.role == "heading" && let Some(lbl) = self.mirror_name(i) { + let mut item = A11yItem::new("heading", &n.path, rect); + item.font_size = 16.0; + item.level = Some(n.a11y.level.unwrap_or(2).clamp(1, 6)); + item.text = lbl; + item.id = anchor_id(n.key.as_deref()); + push(&mut out, item); + last_flow_parent = None; + } + i += 1; + } + out + } + + /// Node `i`'s name in the mirror, as the native tree names it: its label, else the words of + /// the element `El::labelled_by` names. + fn mirror_name(&self, i: usize) -> Option<String> { + let n = &self.tree.nodes[i]; + n.label.as_deref().filter(|s| !s.trim().is_empty()).map(str::to_owned).or_else(|| { + let key = n.a11y.more.as_deref()?.labelled_by.as_deref()?; + Some(self.a11y_words(self.a11y_keyed(i, key)?)).filter(|w| !w.trim().is_empty()) + }) + } + + /// Node `i`'s description in the mirror: `El::description`, else the words of the element + /// `El::described_by` names. + fn mirror_description(&self, i: usize) -> String { + let Some(more) = self.tree.nodes[i].a11y.more.as_deref() else { return String::new() }; + more.description.as_deref().map(str::to_owned) + .or_else(|| more.described_by.as_deref().and_then(|k| self.a11y_keyed(i, k)).map(|j| self.a11y_words(j))) + .filter(|w| !w.trim().is_empty()) + .unwrap_or_default() + } + + /// The page's horizontal scroll viewports: their paths and how far each is scrolled right. + /// The browser's mirror holds the containers, so the DOM keeps an offset Rune scrolls too. + pub(crate) fn page_scroll_x(&self) -> Vec<(String, f32)> { + if self.host.page.is_none() { return Vec::new(); } + self.tree.nodes.iter() + .filter(|n| n.scroll_axes == crate::el::ScrollAxes::X) + .filter_map(|n| self.scroll.scrolls.get(&n.id).map(|st| (n.path.clone(), st.x.offset as f32))) + .collect() + } + + /// Returns updated JSON only when layout commits, viewport or scroll positions changed. + /// Whether only scrolling moved the mirror since it was last built: nothing committed and the + /// viewport is the same. + #[cfg_attr(not(target_arch = "wasm32"), allow(dead_code))] + pub(crate) fn web_a11y_scrolled_only(&self, mirror: &A11yMirror) -> bool { + mirror.commits == self.commit.commits && !mirror.json.is_empty() && mirror.scroll_digest != self.scroll_digest() + } + + pub(crate) fn web_a11y<'a>(&self, mirror: &'a mut A11yMirror) -> Option<&'a str> { + let vp = (self.viewport.0.to_bits(), if self.host.page.is_some() { 0 } else { self.viewport.1.to_bits() }); + let sd = self.scroll_digest(); + // Motion moves drawn boxes without a commit: follow it while it runs, and once more where it stops. + let moving = self.animating; + let follow = moving != mirror.moving || (moving && self.clock - mirror.built_at >= MOVING_EVERY); + if mirror.commits == self.commit.commits && mirror.viewport == vp && mirror.scroll_digest == sd && !follow && !mirror.json.is_empty() { + return None; + } + mirror.moving = moving; + mirror.built_at = self.clock; + mirror.commits = self.commit.commits; + mirror.viewport = vp; + mirror.scroll_digest = sd; + let values: Vec<Value> = self.web_a11y_items().iter().map(A11yItem::to_json).collect(); + let next = serde_json::to_string(&values).unwrap_or_else(|_| "[]".into()); + if mirror.json == next { + return None; + } + mirror.json = next; + Some(&mirror.json) + } + + /// An app's focus, for the canvas's focus proxy (`focusA11y` in `bridge.js`): the page keeps + /// the browser's focus on the canvas (keys go there) or its text field, so without this a + /// reader heard nothing as Tab, arrows or a request moved Rune's focus. The focused + /// element's ARIA role, name, description and states; empty when nothing has focus. `None` + /// when unchanged since the last call. + pub(crate) fn web_a11y_focus<'a>(&self, mirror: &'a mut A11yMirror) -> Option<&'a str> { + let at = (self.commit.commits, self.kbd.focus.path().unwrap_or_default().to_owned()); + if mirror.focus_at == at { return None; } + mirror.focus_at = at; + // A field naming a highlighted row (`El::active_descendant`, the palette's): the row is + // what a reader is told about, as the native trees hand it focus. + let next = self.focused_index().map(|i| match self.a11y_active_descendant(i) { + Some(row) => { + let mut item = self.web_focus_item(row); + if let Some(o) = item.as_object_mut() { o.insert("f".into(), json!(self.mirror_name(i).unwrap_or_default())); } + item.to_string() + } + None => self.web_focus_item(i).to_string(), + }).unwrap_or_default(); + if mirror.focus_json == next { return None; } + mirror.focus_json = next; + Some(&mirror.focus_json) + } + + fn web_focus_item(&self, i: usize) -> Value { + let n = &self.tree.nodes[i]; + let role = self.a11y_role(i); + let mut o = serde_json::Map::new(); + o.insert("o".into(), json!(role.map_or("group", roles::focus_role))); + let name = self.mirror_name(i).unwrap_or_else(|| self.descendant_label(i, self.subtree_end(i))); + o.insert("t".into(), json!(name)); + let description = self.mirror_description(i); + if !description.is_empty() { o.insert("d".into(), json!(description)); } + let checked = n.a11y.checked.or_else(|| (role == Some(accesskit::Role::RadioButton)).then_some(if n.focus.selected { crate::el::Checked::True } else { crate::el::Checked::False })); + if let Some(c) = checked { + o.insert("c".into(), json!(match c { crate::el::Checked::True => "true", crate::el::Checked::False => "false", crate::el::Checked::Mixed => "mixed" })); + } + if role.is_some_and(roles::selectable_item) { o.insert("s".into(), json!(n.focus.selected)); } + if let Some(open) = n.a11y.expanded { o.insert("x".into(), json!(open)); } + if let Some((pos, size)) = n.a11y.more.as_ref().and_then(|m| m.set) { o.insert("n".into(), json!([pos, size])); } + if let Some(level) = n.a11y.level { o.insert("l".into(), json!(level)); } + Value::Object(o) + } + + /// Dispatches assistive-tech activation of a mirrored button or inline link. + pub(crate) fn web_a11y_action(&mut self, event: &serde_json::Value) -> bool { + let Some(path) = event["path"].as_str() else { return false }; + match event["kind"].as_str() { + Some("a11y_press") => { + let Some(i) = self.live(path) else { return false }; + if self.tree.nodes[i].handlers.on_press.is_none() { return false; } + self.frame.queue.push(Action::Press(path.to_owned(), crate::PointerButton::Primary, false)); + true + } + Some("a11y_link") => { + let Some(k) = event["link"].as_u64().and_then(|n| usize::try_from(n).ok()) else { return false }; + let Some(i) = self.live(path) else { return false }; + if self.tree.nodes[i].text.as_ref().is_none_or(|t| k >= t.cold.links.len()) { return false; } + self.frame.queue.push(Action::Link(path.to_owned(), k, crate::PointerButton::Primary)); + true + } + _ => false, + } + } +} + +/// Joins one more flowed word run into the paragraph item before it. +fn merge_flow(prev: &mut A11yItem, rect: [f32; 4], runs: Vec<A11yRun>) { + prev.rect = union(prev.rect, rect); + let needs_space = prev.runs.last().is_some_and(|r| !r.text.ends_with(char::is_whitespace)) + && runs.first().is_some_and(|r| !r.text.starts_with(char::is_whitespace) && !r.text.starts_with([')', ']', '.', ',', ';', ':'])); + if needs_space { + if let Some(last) = prev.runs.last_mut().filter(|r| r.href.is_none()) { + last.text.push(' '); + } else { + prev.runs.push(A11yRun { text: " ".into(), href: None, path: None, link: None }); + } + } + if runs.len() == 1 && runs[0].href.is_none() + && let Some(last) = prev.runs.last_mut().filter(|r| r.href.is_none()) + { + last.text.push_str(&runs[0].text); + } else { + prev.runs.extend(runs); + } +} + +fn union(a: [f32; 4], b: [f32; 4]) -> [f32; 4] { + let (x0, y0) = (a[0].min(b[0]), a[1].min(b[1])); + let (x1, y1) = ((a[0] + a[2]).max(b[0] + b[2]), (a[1] + a[3]).max(b[1] + b[3])); + [x0, y0, round1(x1 - x0), round1(y1 - y0)] +} + +fn inset_rect(rect: [f32; 4], inset: [f32; 4]) -> [f32; 4] { + [round1(rect[0] + inset[0]), round1(rect[1] + inset[1]), + round1((rect[2] - inset[0] - inset[2]).max(0.0)), round1((rect[3] - inset[1] - inset[3]).max(0.0))] +} + +/// The last text item and where its node's laid-out box ends, so a sibling text that carries on +/// the same line joins it: a code line drawn one text per token mirrors as one line, which reads, +/// finds and copies as the line rather than token by token. +#[derive(Clone, Copy)] +struct Inline { + parent: Option<usize>, + item: usize, + right: f32, + top: f32, + bottom: f32, + style: crate::tok::TextStyle, + selectable: bool, +} + +impl Inline { + /// The gap in points from the last text to `target`, when `target` carries on its line in the + /// same face; a larger gap is a separate column, not the same run of text. + fn gap(&self, target: [f32; 4], style: crate::tok::TextStyle, selectable: bool) -> Option<f32> { + let a = self.style; + let same_face = (a.family, a.size, a.weight, a.tracking) == (style.family, style.size, style.weight, style.tracking) + && self.selectable == selectable; + let height = (self.bottom - self.top).min(target[3] - target[1]); + let overlap = self.bottom.min(target[3]) - self.top.max(target[1]); + let gap = target[0] - self.right; + (same_face && height > 0.0 && overlap >= height * 0.5 && (-0.5..=style.size * 0.6).contains(&gap)).then_some(gap) + } +} + +/// Appends a sibling's text to the line item before it, with a space when a visible gap stands +/// for one. +fn join_inline(prev: &mut A11yItem, rect: [f32; 4], mut runs: Vec<A11yRun>, gap: bool) { + prev.rect = union(prev.rect, rect); + let ends_blank = if prev.runs.is_empty() { prev.text.ends_with(char::is_whitespace) } else { prev.runs.last().is_some_and(|r| r.text.ends_with(char::is_whitespace)) }; + if gap && !ends_blank && runs.first().is_some_and(|r| !r.text.starts_with(char::is_whitespace)) { + runs.insert(0, A11yRun { text: " ".into(), href: None, path: None, link: None }); + } + if prev.runs.is_empty() && runs.iter().all(|r| r.href.is_none()) { + for r in runs { prev.text.push_str(&r.text); } + return; + } + if prev.runs.is_empty() { + prev.runs.push(A11yRun { text: std::mem::take(&mut prev.text), href: None, path: None, link: None }); + } + for r in runs { + match prev.runs.last_mut() { + Some(last) if last.href.is_none() && r.href.is_none() => last.text.push_str(&r.text), + _ => prev.runs.push(r), + } + } +} + +#[cfg(test)] +#[path = "a11y_tests.rs"] +mod tests; diff --git a/app/vendor/rune/crates/rune/src/runtime/web/a11y_tests.rs b/app/vendor/rune/crates/rune/src/runtime/web/a11y_tests.rs new file mode 100644 index 0000000..590bb92 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/web/a11y_tests.rs @@ -0,0 +1,340 @@ +use super::*; +use serde_json::json; + +#[test] +fn mirrors_headings_inline_links_and_buttons_and_skips_idle_frames() { + fn view(open: &(bool, usize), _: &mut Cx<(bool, usize)>) -> El { + let mut body = crate::rich("Read spec for details.", vec![]).font(crate::tok::type_::BODY) + .link(crate::Link::new(5..9, "https://example.com/spec")) + .on_link(|s: &mut (bool, usize), _, _| s.1 += 1); + body = body.selectable(true); + let toggle = crate::row().key("fold").role("button").label(if open.0 { "Hide details" } else { "Show details" }) + .expanded(open.0) + .on_press(|s: &mut (bool, usize)| s.0 = !s.0) + .child(crate::text("Details")); + crate::col().w_full().gap(8.0) + .child(crate::text("Release notes").role("heading").level(1).font(crate::tok::type_::TITLE)) + .child(body) + .child(toggle) + } + let mut rt = Runtime::new((false, 0usize), view, (480.0, 320.0), Env::default()); + rt.frame(0.0); + let mut mirror = A11yMirror::default(); + let first = rt.web_a11y(&mut mirror).expect("initial tree").to_owned(); + assert!(rt.web_a11y(&mut mirror).is_none(), "unchanged frame emits nothing"); + + let items = rt.web_a11y_items(); + assert_eq!(items.len(), 3); + assert_eq!((items[0].kind, items[0].level, items[0].text.as_str()), ("heading", Some(1), "Release notes")); + assert_eq!(items[1].kind, "text"); + assert_eq!(items[1].runs.len(), 3); + assert_eq!((items[1].runs[1].text.as_str(), items[1].runs[1].href.as_deref()), ("spec", Some("https://example.com/spec"))); + assert_eq!((items[2].kind, items[2].text.as_str(), items[2].expanded), ("button", "Show details", Some(false))); + assert!(items[1].font.is_some(), "text carries its font, so Find highlights land on the glyphs"); + assert!(!items[1].selectable, "outside a page the canvas selects text itself"); + + let btn_path = items[2].path.clone(); + let link_path = items[1].path.clone(); + assert!(rt.web_a11y_action(&json!({"kind": "a11y_press", "path": btn_path}))); + rt.frame(0.0); + assert!(rt.state.0); + let updated = rt.web_a11y(&mut mirror).expect("button flip updates expanded state"); + assert_ne!(first, updated); + assert!(updated.contains("Hide details")); + + assert!(rt.web_a11y_action(&json!({"kind": "a11y_link", "path": link_path, "link": 0}))); + rt.frame(0.0); + assert_eq!(rt.state.1, 1); +} + +fn page(_: &(), _: &mut Cx<()>) -> El { + crate::col().w_full().role("main") + .child(crate::col().key("intro").role("region").label("Intro").w_full().h(400.0) + .child(crate::text("Rune").key("title").role("heading").level(1).font(crate::tok::type_::TITLE)) + .child(crate::text("A Rust UI framework.").key("lede").font(crate::tok::type_::BODY).selectable(true).padding(4.0))) + .child(crate::col().key("links").role("navigation").w_full() + .child(crate::row().key("gh").href("https://github.com/example/rune").child(crate::text("GitHub"))) + .child(crate::col().key("still").role("img").label("Liquid metal").w(200.0).h(100.0))) +} + +#[test] +fn a_page_mirrors_landmarks_ids_links_and_images_in_document_coordinates() { + let mut rt = Runtime::new((), page, (480.0, 300.0), Env::default()); + rt.page_mode(); + rt.frame(0.0); + rt.set_page_scroll(120.0); + rt.frame(0.0); + let items = rt.web_a11y_items(); + let kinds: Vec<_> = items.iter().map(|i| (i.kind, i.tag, i.parent)).collect(); + assert_eq!(kinds, [ + ("group", Some("main"), None), + ("group", Some("section"), Some(0)), + ("heading", None, Some(1)), + ("text", None, Some(1)), + ("group", Some("nav"), Some(0)), + ("link", None, Some(4)), + ("image", None, Some(4)), + ]); + assert_eq!((items[1].id.as_deref(), items[1].text.as_str()), (Some("intro"), "Intro")); + assert_eq!(items[2].id.as_deref(), Some("title"), "a heading is an anchor"); + assert_eq!(items[3].id, None); + assert_eq!((items[5].href.as_deref(), items[5].text.as_str()), (Some("https://github.com/example/rune"), "GitHub")); + assert_eq!(items[6].text, "Liquid metal"); + assert_eq!(items[4].rect[1], 400.0, "rects are in the document, whatever the scroll"); + + let font = items[3].font.as_ref().expect("text in a page carries its font"); + assert_eq!((font.family.as_str(), font.align), ("sans", "left")); + assert!(items[3].selectable); + assert!(items[2].selectable, "a page's plain text selects without asking"); + assert_eq!(items[3].rect[0], 4.0, "selectable text sits at its text box, inside the padding"); +} + +/// Plain text beside text inside things that take the pointer: a pressable card (holding a button, +/// so its text mirrors on its own), a draggable row, a tab, and an opted-out header. +fn controls(_: &(), _: &mut Cx<()>) -> El { + let body = crate::tok::type_::BODY; + crate::col().w_full().role("main") + .child(crate::text("Plain words").key("plain").font(body)) + .child(crate::col().key("card").on_press(|_: &mut ()| {}) + .child(crate::text("Card words").key("card-words").font(body)) + .child(crate::text("Pinned words").key("pinned").font(body).selectable(true)) + .child(crate::row().key("go").on_press(|_: &mut ()| {}).child(crate::text("Go")))) + .child(crate::row().key("drag").on_drag(|_: &mut (), _, _| {}).child(crate::text("Drag words").font(body))) + .child(crate::row().key("tab").role("tab").child(crate::text("Tab words").font(body))) + .child(crate::col().key("brand").unselectable() + .child(crate::text("Brand words").font(body)) + .child(crate::text("Kept words").font(body).selectable(true))) +} + +fn selectable_texts<S: 'static>(rt: &Runtime<S>) -> Vec<(String, bool)> { + rt.web_a11y_items().into_iter().filter(|i| i.kind == "text").map(|i| (i.text, i.selectable)).collect() +} + +#[test] +fn a_page_selects_its_text_but_not_text_inside_controls() { + let mut rt = Runtime::new((), controls, (480.0, 400.0), Env::default()); + rt.page_mode(); + rt.frame(0.0); + let texts = selectable_texts(&rt); + let want = |s: &str, on: bool| (s.to_owned(), on); + assert_eq!(texts, [ + want("Plain words", true), + want("Card words", false), + want("Pinned words", true), + want("Drag words", false), + want("Tab words", false), + want("Brand words", false), + want("Kept words", true), + ]); + let items = rt.web_a11y_items(); + assert!(items.iter().any(|i| i.kind == "button" && i.text == "Go"), "the card's button still mirrors"); + let plain = items.iter().find(|i| i.text == "Plain words").expect("plain text mirrors"); + assert_eq!(plain.to_json()["e"], json!(true), "the bridge makes it selectable"); +} + +#[test] +fn outside_a_page_only_selectable_text_is_marked() { + let mut rt = Runtime::new((), controls, (480.0, 400.0), Env::default()); + rt.frame(0.0); + assert!(selectable_texts(&rt).iter().all(|(_, on)| !on), "a full-window app's canvas selects text itself"); +} + +#[test] +fn a_page_mirror_does_not_change_while_the_page_scrolls() { + let mut rt = Runtime::new((), page, (480.0, 300.0), Env::default()); + rt.page_mode(); + rt.frame(0.0); + let mut mirror = A11yMirror::default(); + assert!(rt.web_a11y(&mut mirror).is_some()); + rt.set_page_scroll(200.0); + rt.frame(0.0); + assert!(rt.web_a11y(&mut mirror).is_none(), "scrolling the page leaves the mirror alone"); +} + +/// A page whose only change between frames is a colour, at a document offset that sits on a +/// rounding boundary (100.05 points rounds the other way either side of it). +fn tinted(tone: &u32, _: &mut Cx<u32>) -> El { + crate::col().w_full().role("main") + .child(crate::col().key("intro").role("region").label("Intro").w_full().h(100.05) + .child(crate::text("Rune").key("title").role("heading").level(1).font(crate::tok::type_::TITLE))) + .child(crate::text("A Rust UI framework.").key("lede").font(crate::tok::type_::BODY).selectable(true) + .fill(crate::Color::WHITE.alpha(f32::from(u8::try_from(*tone % 200).expect("byte")) / 400.0))) +} + +#[test] +fn fractional_scroll_offsets_never_rewrite_a_page_mirror() { + let mut rt = Runtime::new(0u32, tinted, (480.0, 300.0), Env::new(true, 3.0)); + rt.page_mode(); + rt.frame(0.0); + let mut mirror = A11yMirror::default(); + assert!(rt.web_a11y(&mut mirror).is_some()); + // At `@3x` a scroll offset is a third of a pixel, so the band's offset and the document's + // position never add back exactly in `f32`. A commit that only redraws the band used to round + // an item's position the other way and rewrite the whole page's mirror. + for i in 1..20u32 { + let y = f32::from(u16::try_from(i).expect("small")) * 137.3333; + assert!(rt.set_page_scroll(y), "each offset is a new page position"); + rt.state = i; + rt.frame(0.0); + assert!(rt.web_a11y(&mut mirror).is_none(), "the mirror changed at {y}"); + } +} + +/// A page with a wide code snippet in a horizontal viewport, as a site puts one. +fn strip(_: &(), _: &mut Cx<()>) -> El { + crate::col().w_full().role("main") + .child(crate::row().key("scroll").w(200.0).h(40.0).scroll_x() + .child(crate::text("fn main() { println!(\"hello\"); }").key("code").w(600.0).h(40.0) + .font(crate::tok::type_::BODY).selectable(true))) +} + +#[test] +fn a_page_mirrors_a_horizontal_viewport_as_a_scroller_the_browser_scrolls() { + let mut rt = Runtime::new((), strip, (400.0, 300.0), Env::default()); + rt.page_mode(); + rt.frame(0.0); + let items = rt.web_a11y_items(); + let scroll = items.iter().find(|i| i.kind == "scroll_x").expect("the strip mirrors as a scroller"); + assert_eq!((scroll.tag, scroll.rect[0], scroll.rect[2]), (Some("div"), 0.0, 200.0)); + let code = items.iter().find(|i| i.text.contains("println")).expect("the code still mirrors"); + let placed = code.rect[0]; + let mut mirror = A11yMirror::default(); + assert!(rt.web_a11y(&mut mirror).is_some()); + + let path = scroll.path.clone(); + assert!(rt.set_page_scroll_x(&path, 120.0), "the browser scrolled the strip"); + rt.frame(0.0); + assert!(rt.web_a11y(&mut mirror).is_none(), "the container's own scroll leaves the mirror alone"); + let after = rt.web_a11y_items(); + let code = after.iter().find(|i| i.text.contains("println")).expect("the code still mirrors"); + assert_eq!(code.rect[0], placed, "the text keeps its place inside the scroller"); + assert!(!rt.set_page_scroll_x(&path, 120.0), "the same offset is no change"); +} + +/// Code drawn one text per token, as an editor that animates tokens does, beside a gutter +/// number; then words a small gap apart, and a label and value set far apart. +fn code(_: &(), _: &mut Cx<()>) -> El { + let mono = crate::tok::type_::BODY.mono(); + let line = |n: usize, toks: &[&str]| { + let mut row = crate::row().key("toks"); + for (k, t) in toks.iter().enumerate() { + row = row.child(crate::text(*t).key(format!("t{k}")).font(mono).w(t.chars().count() as f32 * 8.0).h(20.0)); + } + crate::row().key(format!("ln{n}")).h(20.0) + .child(crate::row().key("num").w(32.0).child(crate::text(n.to_string()).font(mono))) + .child(row) + }; + crate::col().w_full() + .child(line(1, &["type", " ", "Port", " = ", "Int"])) + .child(line(2, &["listen", "(", "port", ")"])) + .child(crate::row().key("words").gap(4.0).child(crate::text("Hello")).child(crate::text("world"))) + .child(crate::row().key("pair").w(300.0).justify_between().child(crate::text("Name")).child(crate::text("Kit"))) +} + +#[test] +fn a_row_of_token_texts_mirrors_as_one_line() { + let mut rt = Runtime::new((), code, (480.0, 300.0), Env::default()); + rt.frame(0.0); + let items = rt.web_a11y_items(); + let texts: Vec<_> = items.iter().map(|i| (i.kind, i.text.as_str(), i.runs.len())).collect(); + assert_eq!(texts, [ + ("text", "1", 0), + ("text", "type Port = Int", 0), + ("text", "2", 0), + ("text", "listen(port)", 0), + ("text", "Hello world", 0), + ("text", "Name", 0), + ("text", "Kit", 0), + ]); + let line = &items[1]; + assert_eq!((line.rect[0], line.rect[2]), (32.0, 15.0 * 8.0), "the line's box spans its tokens"); +} + +#[test] +fn href_presses_open_absolute_urls() { let mut rt = Runtime::new((), page, (480.0, 300.0), Env::default()); + rt.frame(0.0); + let gh = rt.tree.nodes.iter().find(|n| n.key.as_deref() == Some("gh")).unwrap().path.clone(); + assert_eq!(rt.tree.nodes.iter().find(|n| n.key.as_deref() == Some("gh")).unwrap().role, "link"); + assert!(rt.web_a11y_action(&json!({"kind": "a11y_press", "path": gh}))); + rt.frame(0.0); + assert_eq!(rt.take_url_requests(), ["https://github.com/example/rune"]); +} + +#[test] +fn mac_meta_copy_and_select_all_work_on_selectable_text() { + fn view(_: &(), _: &mut Cx<()>) -> El { + crate::col().key("doc").selection_group(true) + .child(crate::text("First paragraph").key("p1").font(crate::tok::type_::BODY).selectable(true)) + .child(crate::text("Second paragraph").key("p2").font(crate::tok::type_::BODY).selectable(true)) + } + let mut rt = Runtime::new((), view, (400.0, 200.0), Env::default()); + let board = crate::clipboard::memory(); + rt.use_clipboard(&board); + rt.frame(0.0); + rt.pointer_down(12.0, 8.0); + rt.pointer_up(12.0, 8.0); + rt.frame(0.0); + // Simulate macOS browser Meta+A (meta=true, ctrl=false) then Meta+C. + rt.web_key(&json!({"kind":"key", "key":"a", "code":"KeyA", "meta":true, "ctrl":false, "shift":false, "alt":false})); + rt.frame(0.0); + assert_eq!(rt.copy_text().as_deref(), Some("First paragraph\nSecond paragraph")); + rt.web_key(&json!({"kind":"key", "key":"c", "code":"KeyC", "meta":true, "ctrl":false, "shift":false, "alt":false})); + rt.frame(0.0); + crate::clipboard::flush_memory(rt.core_mut()); + assert_eq!(board.text().as_deref().map(String::as_str), Some("First paragraph\nSecond paragraph")); +} + +#[test] +fn exiting_children_do_not_swallow_or_misparent_live_siblings() { + fn view(show: &bool, _: &mut Cx<bool>) -> El { + let mut btn = crate::row().key("btn").role("button").label("Action").on_press(|_: &mut bool| {}) + .size(100.0, 24.0); + if *show { + btn = btn.child(crate::el().key("badge").size(10.0, 10.0).transition(crate::Transition::opacity())); + } + let mut box_a = crate::col().key("box-a").role("region").label("Box A").size(200.0, 40.0); + if *show { + box_a = box_a.child(crate::el().key("old").size(10.0, 10.0).transition(crate::Transition::opacity())); + } + crate::col().w_full().role("main") + .child(btn) + .child(crate::text("Live sibling after button").key("after-btn").font(crate::tok::type_::BODY)) + .child(box_a) + .child(crate::col().key("box-b").role("region").label("Box B").size(200.0, 40.0) + .child(crate::text("Box B text").font(crate::tok::type_::BODY))) + } + let mut rt = Runtime::new(true, view, (480.0, 300.0), Env::default()); + rt.frame(0.0); + rt.update(|s, _| *s = false); + rt.frame(1.0 / 60.0); + assert!(rt.tree.nodes.iter().enumerate().any(|(i, _)| rt.core().subtree_exiting(i)), "exiting tail must be active"); + + let items = rt.web_a11y_items(); + let after = items.iter().find(|it| it.text == "Live sibling after button") + .expect("live sibling after button with exiting child must remain mirrored"); + assert_eq!(after.parent, Some(0), "sibling stays directly under main"); + let box_b = items.iter().find(|it| it.text == "Box B") + .expect("live sibling region after exiting-child region must remain mirrored"); + assert_eq!(box_b.parent, Some(0), "Box B must remain a child of main, not mis-parented under Box A"); +} + +#[test] +fn rtl_horizontal_scroller_mirror_undoes_rtl_shift() { + fn view(_: &(), _: &mut Cx<()>) -> El { + crate::col().w_full().child( + crate::row().key("strip").dir(crate::Direction::Rtl).size(200.0, 60.0).scroll_x() + .child(crate::row().w(600.0).h(60.0) + .child(crate::text("مرحبا").key("word").font(crate::tok::type_::BODY))), + ) + } + let mut rt = Runtime::new((), view, (400.0, 200.0), Env::default()); + rt.page_mode(); + rt.frame(0.0); + let x0 = rt.web_a11y_items().into_iter().find(|it| it.text == "مرحبا").unwrap().rect[0]; + rt.wheel_xy(100.0, 30.0, 80.0, 0.0); + rt.frame(0.0); + let strip = rt.tree.nodes.iter().find(|n| n.key.as_deref() == Some("strip")).unwrap().id; + assert!((rt.scroll.scrolls[&strip].x.offset - 80.0).abs() < 0.5, "RTL horizontal scroll moved offset"); + let x1 = rt.web_a11y_items().into_iter().find(|it| it.text == "مرحبا").unwrap().rect[0]; + assert!((x1 - x0).abs() < 0.2, "mirror rect must stay in scroller content coordinates across RTL scroll: {x0} -> {x1}"); +} diff --git a/app/vendor/rune/crates/rune/src/runtime/web/export.rs b/app/vendor/rune/crates/rune/src/runtime/web/export.rs new file mode 100644 index 0000000..0c117a5 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/web/export.rs @@ -0,0 +1,154 @@ +//! A page's static first frame (`--html`): the laid-out scene as HTML elements with CSS taken +//! from each element's flexbox style, paint and text, so the browser draws the same page before +//! the wasm arrives, and readers, crawlers and link previews see real text, headings and links. +//! The layout stays the browser's (flex, percentages, wrapping), so it holds between the widths +//! it was taken at; `page` folds several widths into `@media` rules. + +use std::fmt::Write; + +use super::*; +use crate::a11y::roles; +use crate::runtime::web_a11y::anchor_id; + +mod css; +mod page; +pub(crate) use page::page; + +/// One element of the exported tree, in document order. +#[derive(Debug, Clone, PartialEq)] +pub(crate) struct ExportNode { + pub path: String, + pub depth: usize, + pub tag: &'static str, + /// Attributes besides `class`, already escaped: ` id="views" href="…"`. + pub attrs: String, + /// Inner HTML for text and shapes; children follow otherwise. + pub inner: String, + /// CSS declarations, property then value. + pub decls: Vec<(&'static str, String)>, + /// Laid-out width in points, which an image's `sizes` follows across widths. + pub width: f32, + /// A text element: its children are inline runs, not elements. + pub text: bool, +} + +pub(crate) fn escape(s: &str) -> String { + let mut out = String::with_capacity(s.len()); + for c in s.chars() { + match c { + '&' => out.push_str("&amp;"), + '<' => out.push_str("&lt;"), + '>' => out.push_str("&gt;"), + '"' => out.push_str("&quot;"), + c => out.push(c), + } + } + out +} + +impl RuntimeCore { + /// The visible scene as `ExportNode`s: what `--html` writes for one width. + pub(crate) fn export_nodes(&self) -> Vec<ExportNode> { + let mut out = Vec::new(); + // Ancestors' tags, to keep inline content inside links, headings and buttons. + let mut stack: Vec<(usize, &'static str)> = Vec::new(); + let selects = self.page_text_selects(); + let mut i = 0; + while i < self.tree.nodes.len() { + let n = &self.tree.nodes[i]; + let end = self.subtree_end(i); + while stack.last().is_some_and(|&(e, _)| i >= e) { stack.pop(); } + if !self.allowed(i) || self.subtree_exiting(i) || n.vis.opacity <= 0.01 || n.input.is_some() { + i = end; + continue; + } + let inline = stack.iter().any(|&(_, t)| matches!(t, "a" | "h1" | "h2" | "h3" | "h4" | "h5" | "h6" | "span" | "p")); + let mut node = self.export_node(i, stack.len(), inline); + // A page's text selects as the live mirror's will, once the wasm takes over: not + // inside a control, unless it's `El::selectable`. + if let Some(&on) = selects.get(i) { + let parent = n.parent.is_none_or(|p| selects[p]); + let explicit = n.text.as_deref().is_some_and(|t| t.selectable); + let value = match (on, parent, explicit) { + (false, true, false) => Some("none"), + (false, false, true) => Some("text"), + _ => None, + }; + if let Some(v) = value { + node.decls.push(("-webkit-user-select", v.into())); + node.decls.push(("user-select", v.into())); + } + } + stack.push((end, node.tag)); + out.push(node); + // Shapes and text carry their content; an image has none. + if out.last().is_some_and(|e| e.tag == "img") { i = end; stack.pop(); continue; } + i += 1; + } + out + } + + fn export_node(&self, i: usize, depth: usize, inline: bool) -> ExportNode { + let n = &self.tree.nodes[i]; + let mut attrs = String::new(); + let mut inner = String::new(); + let href = n.a11y.more.as_ref().and_then(|m| m.href.clone()); + let label = n.label.as_deref().filter(|s| !s.trim().is_empty()); + let pixels = n.vis.cold.pixels.as_ref().filter(|_| i + 1 == self.subtree_end(i)); + let pixels_url = pixels.and_then(|p| p.source_url()); + let tag: &'static str = if let Some(t) = roles::container_tag(n.role) { + t + } else if href.is_some() { + "a" + } else if n.role == "heading" { + ["h1", "h2", "h3", "h4", "h5", "h6"][n.a11y.level.unwrap_or(2).clamp(1, 6) as usize - 1] + } else if pixels_url.is_some() { + "img" + } else if n.text.is_some() { + if inline { "span" } else { "p" } + } else if inline { + "span" + } else { + "div" + }; + if matches!(tag, "a" | "h1" | "h2" | "h3" | "h4" | "h5" | "h6") || roles::container_tag(n.role).is_some() { + if let Some(id) = anchor_id(n.key.as_deref()) { write!(attrs, " id=\"{id}\"").ok(); } + } + if let Some(role) = roles::container_aria(n.role) { write!(attrs, " role=\"{role}\"").ok(); } + if let Some(h) = &href { write!(attrs, " href=\"{}\"", escape(h)).ok(); } + if let Some(url) = pixels_url { + let [x0, y0, x1, y1] = n.target; + write!(attrs, " src=\"{}\" alt=\"{}\" width=\"{}\" height=\"{}\" decoding=\"async\"", + escape(url), escape(label.unwrap_or("")), (x1 - x0).round(), (y1 - y0).round()).ok(); + // `page` adds `sizes`, which needs every width. + if let Some(set) = pixels.and_then(|p| p.source_set()) { write!(attrs, " srcset=\"{}\"", escape(set)).ok(); } + // Images below the first screen wait until the reader scrolls near them. + if y0 > 900.0 { attrs.push_str(" loading=\"lazy\""); } + } else if let Some(l) = label.filter(|_| n.text.is_none() && tag != "a") { + let role = matches!(n.role, "image" | "img").then_some(" role=\"img\"").unwrap_or(""); + write!(attrs, "{role} aria-label=\"{}\"", escape(l)).ok(); + } + if n.a11y.hidden { attrs.push_str(" aria-hidden=\"true\""); } + let mut decls = css::layout(&self.commit.layout.style(n.taffy).to_style(), i == 0); + let [x0, y0, x1, y1] = n.target; + css::paint(&n.vis, (x1 - x0, y1 - y0), &mut decls); + if let Some(spec) = n.text.as_deref() { + css::text(spec, &mut decls); + inner = css::text_html(spec); + } else if let Some(shape) = n.vis.cold.shape.as_deref() { + inner = css::svg(shape, (x1 - x0, y1 - y0)); + } + if tag == "img" { + let fit = match n.vis.cold.pixels_fit { + None => "fill", + Some(crate::SurfaceFit::Fit) => "contain", + Some(crate::SurfaceFit::Fill) => "cover", + }; + decls.push(("object-fit", fit.into())); + } + ExportNode { path: n.path.clone(), depth, tag, attrs, inner, decls, width: x1 - x0, text: n.text.is_some() } + } +} + +#[cfg(test)] +mod tests; diff --git a/app/vendor/rune/crates/rune/src/runtime/web/export/css.rs b/app/vendor/rune/crates/rune/src/runtime/web/export/css.rs new file mode 100644 index 0000000..5aa50b2 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/web/export/css.rs @@ -0,0 +1,332 @@ +//! CSS for an exported element: its Taffy style as flexbox, its paint and its text. + +use std::fmt::Write; + +use taffy::style::{CompactLength, Display, FlexDirection, FlexWrap, Overflow, Position, Style}; + +use super::escape; +use crate::color::Color; +use crate::el::{GradientGeometry, RadialGradient, TextSpec, Visual}; + +pub(super) type Decls = Vec<(&'static str, String)>; + +fn num(v: f32) -> String { + let r = (v * 100.0).round() / 100.0; + if r == r.trunc() { format!("{}", r as i64) } else { format!("{r}") } +} + +fn px(v: f32) -> String { + if v == 0.0 { "0".into() } else { format!("{}px", num(v)) } +} + +/// A length, percentage or `auto`; `None` for what CSS can't take as is (calc, fr). +fn len(raw: CompactLength) -> Option<String> { + match raw.tag() { + CompactLength::LENGTH_TAG => Some(px(raw.value())), + CompactLength::PERCENT_TAG => Some(format!("{}%", num(raw.value() * 100.0))), + CompactLength::AUTO_TAG => Some("auto".into()), + _ => None, + } +} + +/// A Rust variant name in CSS's spelling: `SpaceBetween` to `space-between`. +fn kebab(debug: String) -> String { + let mut out = String::new(); + for (k, c) in debug.chars().enumerate() { + if c.is_ascii_uppercase() { + if k > 0 { out.push('-'); } + out.push(c.to_ascii_lowercase()); + } else { + out.push(c); + } + } + out +} + +pub(super) fn color(c: Color) -> String { + let hex = c.hex(); + match hex.strip_suffix("ff") { + Some(opaque) => opaque.to_owned(), + None => hex, + } +} + +/// The element's box: what differs from a Rune element's defaults, which the page's base rule +/// (`display: flex; position: relative; box-sizing: border-box`) already sets. +pub(super) fn layout(s: &Style, root: bool) -> Decls { + let mut d: Decls = Vec::new(); + let push_len = |d: &mut Decls, prop: &'static str, raw: CompactLength, default: &str| { + if let Some(v) = len(raw).filter(|v| v != default) { d.push((prop, v)); } + }; + match s.display { + Display::Flex => {} + Display::Grid => d.push(("display", "grid".into())), + Display::None => d.push(("display", "none".into())), + _ => d.push(("display", "block".into())), + } + if s.flex_direction != FlexDirection::Row { d.push(("flex-direction", kebab(format!("{:?}", s.flex_direction)))); } + if s.flex_wrap != FlexWrap::NoWrap { d.push(("flex-wrap", kebab(format!("{:?}", s.flex_wrap)))); } + let align = |keyword: String, safe: bool| if safe { format!("safe {}", kebab(keyword)) } else { kebab(keyword) }; + let safe = |debug: String| debug == "Safe"; + if format!("{:?}", s.align_items.keyword) != "Normal" { + d.push(("align-items", align(format!("{:?}", s.align_items.keyword), safe(format!("{:?}", s.align_items.safety))))); + } + if let Some(a) = s.align_self { d.push(("align-self", align(format!("{:?}", a.keyword), safe(format!("{:?}", a.safety))))); } + if format!("{:?}", s.justify_content.keyword) != "Normal" { + d.push(("justify-content", align(format!("{:?}", s.justify_content.keyword), safe(format!("{:?}", s.justify_content.safety))))); + } + if format!("{:?}", s.align_content.keyword) != "Normal" { + d.push(("align-content", align(format!("{:?}", s.align_content.keyword), false))); + } + push_len(&mut d, "row-gap", s.gap.height.into_raw(), "0"); + push_len(&mut d, "column-gap", s.gap.width.into_raw(), "0"); + if s.flex_grow != 0.0 { d.push(("flex-grow", num(s.flex_grow))); } + if s.flex_shrink != 1.0 { d.push(("flex-shrink", num(s.flex_shrink))); } + push_len(&mut d, "flex-basis", s.flex_basis.into_raw(), "auto"); + if matches!(s.position, Position::Absolute | Position::Fixed) { + d.push(("position", "absolute".into())); + push_len(&mut d, "left", s.inset.left.into_raw(), "auto"); + push_len(&mut d, "right", s.inset.right.into_raw(), "auto"); + push_len(&mut d, "top", s.inset.top.into_raw(), "auto"); + push_len(&mut d, "bottom", s.inset.bottom.into_raw(), "auto"); + } + if root { + // The root fills the page's width and grows with its content. + d.push(("width", "100%".into())); + } else { + push_len(&mut d, "width", s.size.width.into_raw(), "auto"); + push_len(&mut d, "height", s.size.height.into_raw(), "auto"); + push_len(&mut d, "min-width", s.min_size.width.into_raw(), "auto"); + push_len(&mut d, "min-height", s.min_size.height.into_raw(), "auto"); + push_len(&mut d, "max-width", s.max_size.width.into_raw(), "auto"); + push_len(&mut d, "max-height", s.max_size.height.into_raw(), "auto"); + } + if let Some(r) = s.aspect_ratio { d.push(("aspect-ratio", num(r))); } + let sides = |r: &taffy::geometry::Rect<CompactLength>| [r.top, r.right, r.bottom, r.left].map(len); + let shorthand = |vals: [Option<String>; 4]| -> Option<String> { + let v: Vec<String> = vals.into_iter().map(|v| v.unwrap_or_else(|| "0".into())).collect(); + if v.iter().all(|x| x == "0") { return None; } + Some(if v[0] == v[2] && v[1] == v[3] { + if v[0] == v[1] { v[0].clone() } else { format!("{} {}", v[0], v[1]) } + } else { + v.join(" ") + }) + }; + let raw = |r: taffy::geometry::Rect<CompactLength>| r; + let margin = raw(taffy::geometry::Rect { + left: s.margin.left.into_raw(), right: s.margin.right.into_raw(), top: s.margin.top.into_raw(), bottom: s.margin.bottom.into_raw(), + }); + let padding = raw(taffy::geometry::Rect { + left: s.padding.left.into_raw(), right: s.padding.right.into_raw(), top: s.padding.top.into_raw(), bottom: s.padding.bottom.into_raw(), + }); + let border = raw(taffy::geometry::Rect { + left: s.border.left.into_raw(), right: s.border.right.into_raw(), top: s.border.top.into_raw(), bottom: s.border.bottom.into_raw(), + }); + if let Some(v) = shorthand(sides(&margin)) { d.push(("margin", v)); } + if let Some(v) = shorthand(sides(&padding)) { d.push(("padding", v)); } + if let Some(v) = shorthand(sides(&border)) { d.push(("border-width", v)); } + let overflow = |o: Overflow| match o { + Overflow::Visible => None, + Overflow::Clip => Some("clip"), + Overflow::Hidden => Some("hidden"), + Overflow::Scroll => Some("auto"), + }; + if let Some(v) = overflow(s.overflow.x) { d.push(("overflow-x", v.into())); } + if let Some(v) = overflow(s.overflow.y) { d.push(("overflow-y", v.into())); } + d +} + +/// Fill, gradients, border, corners, shadows, opacity, blurs and soft clips, for an element +/// `size` points big. +pub(super) fn paint(v: &Visual, size: (f32, f32), d: &mut Decls) { + // Rune paints the fill, then the vertical gradient, then the radial or angled one: CSS lists + // background layers top first, with the colour last. + let mut layers: Vec<String> = Vec::new(); + if let Some(r) = v.cold.radial.as_deref() { layers.push(gradient(r, size)); } + if let Some(g) = v.cold.gradient.as_deref() { layers.push(format!("linear-gradient({},{})", color(g[0]), color(g[1]))); } + if v.fill.a > 0.0 { layers.push(color(v.fill)); } + if !layers.is_empty() { d.push(("background", layers.join(","))); } + if let Some(clip) = v.cold.clip { mask(clip, d); } + let r = v.radii(); + if r.iter().any(|&c| c > 0.0) { + let value = if r.iter().all(|&c| c == r[0]) { px(r[0]) } else { r.map(px).join(" ") }; + d.push(("border-radius", value)); + } + let laid_out_border = d.iter().any(|(p, _)| *p == "border-width"); + let mut shadows: Vec<String> = Vec::new(); + if v.border_width() > 0.0 && v.border().a > 0.0 { + if laid_out_border { + d.push(("border-style", "solid".into())); + d.push(("border-color", color(v.border()))); + } else if let Some([t, r, b, l]) = v.cold.border_sides { + for (x, y, w) in [(0.0, t, t), (-r, 0.0, r), (0.0, -b, b), (l, 0.0, l)] { + if w > 0.0 { shadows.push(format!("inset {} {} 0 0 {}", px(x), px(y), color(v.border()))); } + } + } else { + shadows.push(format!("inset 0 0 0 {} {}", px(v.border_width()), color(v.border()))); + } + } + for s in &v.cold.shadows { + let inset = if s.inset { "inset " } else { "" }; + shadows.push(format!("{inset}{} {} {} {} {}", px(s.x), px(s.y), px(s.blur), px(s.spread), color(s.color))); + } + if !shadows.is_empty() { d.push(("box-shadow", shadows.join(","))); } + let opacity = v.opacity * v.layer_opacity; + if opacity < 0.999 { d.push(("opacity", num(opacity))); } + if v.cold.clip.is_some() || v.cold.clip_radius.is_some() { + if !d.iter().any(|(p, _)| p.starts_with("overflow")) { d.push(("overflow", "hidden".into())); } + } + if v.cold.backdrop_blur > 0.0 { d.push(("backdrop-filter", format!("blur({})", px(v.cold.backdrop_blur)))); } + if v.blur > 0.0 { d.push(("filter", format!("blur({})", px(v.blur)))); } +} + +/// A radial gradient's radii as percentages of the box, so it scales with the box between the +/// widths the page was taken at. +fn gradient(r: &RadialGradient, (w, h): (f32, f32)) -> String { + let stops: Vec<String> = r.stops.iter().map(|&(t, c)| format!("{} {}%", color(c), num(t * 100.0))).collect(); + match r.geometry { + GradientGeometry::Radial { center, radius } => { + let pct = |r: f32, side: f32| if side > 0.0 { format!("{}%", num(r / side * 100.0)) } else { px(r) }; + format!("radial-gradient({} {} at {}% {}%,{})", pct(radius[0], w), pct(radius[1], h), + num(center[0] * 100.0), num(center[1] * 100.0), stops.join(",")) + } + GradientGeometry::Linear { angle } => format!("linear-gradient({}deg,{})", num(angle.to_degrees()), stops.join(",")), + } +} + +/// A soft clip as a mask: one ramp per axis, intersected. Rune eases a positive width and ramps a +/// negative one linearly; CSS ramps both, which meet at the middle of the fade. +fn mask([l, t, r, b]: [f32; 4], d: &mut Decls) { + let ramp = |to: &str, a: f32, z: f32| -> Option<String> { + if a == 0.0 && z == 0.0 { return None; } + let side = |w: f32, from_end: bool| -> Vec<String> { + let at = |p: f32| if from_end { format!("calc(100% - {})", px(p)) } else { px(p) }; + let edge = if from_end { "100%" } else { "0" }; + let mut s = vec![format!("transparent {edge}"), format!("#000 {}", at(w.abs()))]; + if from_end { s.reverse(); } + s + }; + let mut stops = if a != 0.0 { side(a, false) } else { vec!["#000 0".to_owned()] }; + stops.extend(if z != 0.0 { side(z, true) } else { vec!["#000 100%".to_owned()] }); + Some(format!("linear-gradient(to {to},{})", stops.join(","))) + }; + let layers: Vec<String> = [ramp("right", l, r), ramp("bottom", t, b)].into_iter().flatten().collect(); + if layers.is_empty() { return; } + let image = layers.join(","); + d.push(("-webkit-mask-image", image.clone())); + d.push(("mask-image", image)); + if layers.len() == 2 { + d.push(("-webkit-mask-composite", "source-in".into())); + d.push(("mask-composite", "intersect".into())); + } +} + +fn family(f: crate::tok::Family) -> String { + match f { + crate::tok::Family::Sans => "var(--rune-sans)".into(), + crate::tok::Family::Mono | crate::tok::Family::SystemMono => "var(--rune-mono)".into(), + crate::tok::Family::Named(name) => format!("\"{}\"", escape(name)), + } +} + +/// The text's font, colour, alignment and wrapping. +pub(super) fn text(spec: &TextSpec, d: &mut Decls) { + let s = spec.style; + if !d.iter().any(|(p, _)| *p == "display") { d.push(("display", "block".into())); } + d.push(("font-family", family(s.family))); + d.push(("font-size", px(s.size))); + d.push(("font-weight", num(s.weight))); + d.push(("line-height", px(if s.line_height > 0.0 { s.line_height } else { s.size * 1.25 }))); + if s.tracking != 0.0 { d.push(("letter-spacing", px(s.tracking))); } + if s.italic { d.push(("font-style", "italic".into())); } + d.push(("color", color(spec.color))); + match spec.align { + crate::el::Align::Start => {} + crate::el::Align::Center => d.push(("text-align", "center".into())), + crate::el::Align::End => d.push(("text-align", "right".into())), + } + if spec.justify { d.push(("text-align", "justify".into())); } + if spec.truncate { + d.push(("white-space", "pre".into())); + d.push(("overflow", "hidden".into())); + d.push(("text-overflow", "ellipsis".into())); + } else { + d.push(("white-space", if spec.wrap { "pre-wrap" } else { "pre" }.into())); + if spec.wrap_anywhere { d.push(("overflow-wrap", "anywhere".into())); } + if spec.pretty() { d.push(("text-wrap-style", "pretty".into())); } + } +} + +/// The text with its spans (weight, size, colour, code backgrounds, underlines) and its links. +pub(super) fn text_html(spec: &TextSpec) -> String { + let content = &spec.content; + let mut cuts: Vec<usize> = vec![0, content.len()]; + for s in &spec.spans { cuts.extend([s.start as usize, s.end as usize]); } + for l in &spec.cold.links { cuts.extend([l.start as usize, l.end as usize]); } + cuts.retain(|&c| c <= content.len() && content.is_char_boundary(c)); + cuts.sort_unstable(); + cuts.dedup(); + let mut out = String::new(); + let mut open_link: Option<usize> = None; + for w in cuts.windows(2) { + let (a, b) = (w[0], w[1]); + let link = spec.cold.links.iter().position(|l| (l.start as usize) <= a && b <= l.end as usize); + if link != open_link { + if open_link.is_some() { out.push_str("</a>"); } + if let Some(k) = link { write!(out, "<a href=\"{}\">", escape(&spec.cold.links[k].id)).ok(); } + open_link = link; + } + let piece = escape(&content[a..b]); + let mut style = String::new(); + if let Some(s) = spec.spans.iter().rev().find(|s| (s.start as usize) <= a && b <= s.end as usize) { + if let Some(w) = s.weight { write!(style, "font-weight:{};", num(w)).ok(); } + if s.mono { style.push_str("font-family:var(--rune-mono);"); } + if let Some(z) = s.size { write!(style, "font-size:{};", px(z)).ok(); } + if let Some(c) = s.color { write!(style, "color:{};", color(c)).ok(); } + if let Some(c) = s.bg { write!(style, "background:{};border-radius:3px;padding:0 {};", color(c), px(s.bg_pad)).ok(); } + if let Some(c) = s.underline { write!(style, "text-decoration:underline {};", color(c)).ok(); } + if s.italic { style.push_str("font-style:italic;"); } + } + if style.is_empty() { + out.push_str(&piece); + } else { + write!(out, "<span style=\"{}\">{piece}</span>", style.trim_end_matches(';')).ok(); + } + } + if open_link.is_some() { out.push_str("</a>"); } + out +} + +/// A shape as inline SVG: fills as paths, strokes as polylines, stretched like Rune's. +pub(super) fn svg(shape: &crate::Shape, size: (f32, f32)) -> String { + let [w, h] = shape.view_box.unwrap_or([size.0, size.1]); + let mut out = format!( + "<svg viewBox=\"0 0 {} {}\" preserveAspectRatio=\"none\" width=\"100%\" height=\"100%\" aria-hidden=\"true\" focusable=\"false\" shape-rendering=\"crispEdges\">", + num(w), num(h), + ); + let points = |pts: &[[f32; 2]]| pts.iter().map(|p| format!("{},{}", num(p[0]), num(p[1]))).collect::<Vec<_>>().join(" "); + // Consecutive fills of one colour share a path. + let mut fill: Option<(Color, String)> = None; + let flush = |out: &mut String, fill: &mut Option<(Color, String)>| { + if let Some((c, d)) = fill.take() { write!(out, "<path fill=\"{}\" d=\"{d}\"/>", color(c)).ok(); } + }; + for op in &shape.ops { + match op { + crate::shape::Op::Fill { points: pts, color: c } => { + if fill.as_ref().is_some_and(|(fc, _)| fc != c) { flush(&mut out, &mut fill); } + let d = &mut fill.get_or_insert_with(|| (*c, String::new())).1; + write!(d, "M{}Z", points(pts).replace(' ', "L")).ok(); + } + crate::shape::Op::Stroke { points: pts, closed, width, cap, color: c } => { + flush(&mut out, &mut fill); + let el = if *closed { "polygon" } else { "polyline" }; + let cap = if *cap == crate::shape::LineCap::Round { "round" } else { "butt" }; + write!(out, "<{el} fill=\"none\" stroke=\"{}\" stroke-width=\"{}\" stroke-linecap=\"{cap}\" stroke-linejoin=\"round\" vector-effect=\"non-scaling-stroke\" points=\"{}\"/>", + color(*c), num(*width), points(pts)).ok(); + } + } + } + flush(&mut out, &mut fill); + out.push_str("</svg>"); + out +} diff --git a/app/vendor/rune/crates/rune/src/runtime/web/export/page.rs b/app/vendor/rune/crates/rune/src/runtime/web/export/page.rs new file mode 100644 index 0000000..d8ccd8a --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/web/export/page.rs @@ -0,0 +1,121 @@ +//! Folds the scene taken at several widths into one HTML body and one stylesheet: the first +//! width's tree, with each element's CSS for the narrowest width as its base and `@media +//! (min-width)` overrides where a wider one differs. Identical rules share a class. + +use std::collections::{BTreeMap, HashMap}; +use std::fmt::Write; + +use super::ExportNode; + +/// The rule every exported element starts from: a Rune element is a flex row, positioned, with +/// its border inside its size. A text element (class `t`) holds inline runs instead. +pub(crate) const BASE_CSS: &str = "[data-rune-static],[data-rune-static] *{box-sizing:border-box;display:flex;position:relative;margin:0;padding:0;min-width:0;border:0 solid transparent}[data-rune-static] a{color:inherit;text-decoration:none}[data-rune-static] .t>*{display:inline;position:static}[data-rune-static] img{display:block}:where([data-rune-static]) img{height:auto}[data-rune-static] svg{display:block;position:absolute;inset:0}"; + +/// The value a property takes where a width sets nothing, matching `BASE_CSS`. +fn initial(prop: &str) -> &'static str { + match prop { + "display" => "flex", + "position" => "relative", + "min-width" => "0", + "border-width" => "0", + "margin" | "padding" => "0", + "flex-direction" => "row", + "flex-wrap" => "nowrap", + "flex-grow" | "row-gap" | "column-gap" | "border-radius" => "0", + "flex-shrink" | "opacity" => "1", + "background" | "box-shadow" | "filter" | "backdrop-filter" => "none", + _ => "unset", + } +} + +const RANGE_PREFIX: [char; 6] = ['a', 'b', 'c', 'd', 'e', 'f']; + +/// `widths`: the scene at each `(min-width, nodes)`, narrowest first. Returns the body (the +/// first width's tree) and the stylesheet. +pub(crate) fn page(widths: &[(f32, Vec<ExportNode>)]) -> (String, String) { + let Some((_, primary)) = widths.first() else { return (String::new(), String::new()) }; + let widths = &widths[..widths.len().min(RANGE_PREFIX.len())]; + let by_path: Vec<HashMap<&str, &ExportNode>> = + widths.iter().map(|(_, nodes)| nodes.iter().map(|n| (n.path.as_str(), n)).collect()).collect(); + // Per range: declaration text to class name. + let mut classes: Vec<BTreeMap<String, String>> = vec![BTreeMap::new(); widths.len()]; + let mut node_classes: Vec<Vec<String>> = Vec::with_capacity(primary.len()); + for node in primary { + let found: Vec<Option<&ExportNode>> = by_path.iter().map(|m| m.get(node.path.as_str()).copied()).collect(); + let mut props: Vec<&'static str> = Vec::new(); + for n in found.iter().flatten() { + for (p, _) in &n.decls { + if !props.contains(p) { props.push(p); } + } + } + if found.iter().any(Option::is_none) && !props.contains(&"display") { props.push("display"); } + let mut mine = Vec::new(); + let mut last: Option<String> = None; + for (k, n) in found.iter().enumerate() { + let text = match n { + None => "display:none".to_owned(), + Some(n) => props.iter().map(|p| { + let v = n.decls.iter().rev().find(|(q, _)| q == p).map_or(initial(p), |(_, v)| v.as_str()); + format!("{p}:{v}") + }).collect::<Vec<_>>().join(";"), + }; + // Only the base width writes a rule that sets nothing. + if last.as_deref() != Some(&text) && !(k == 0 && text.is_empty()) { + let next = classes[k].len(); + let name = classes[k].entry(text.clone()).or_insert_with(|| format!("{}{}", RANGE_PREFIX[k], base36(next))).clone(); + mine.push(name); + } + last = Some(text); + } + node_classes.push(mine); + } + let mut css = String::from(BASE_CSS); + for (k, rules) in classes.iter().enumerate() { + let mut block = String::new(); + let mut sorted: Vec<(&String, &String)> = rules.iter().collect(); + sorted.sort_by(|a, b| a.1.len().cmp(&b.1.len()).then(a.1.cmp(b.1))); + for (decls, name) in sorted { write!(block, ".{name}{{{decls}}}").ok(); } + if k == 0 { css.push_str(&block); } else if !block.is_empty() { + write!(css, "@media (min-width:{}px){{{block}}}", widths[k].0).ok(); + } + } + let mut body = String::new(); + let mut open: Vec<&'static str> = Vec::new(); + for (node, cls) in primary.iter().zip(&node_classes) { + while open.len() > node.depth { write!(body, "</{}>", open.pop().unwrap()).ok(); } + let names: Vec<&str> = node.text.then_some("t").into_iter().chain(cls.iter().map(String::as_str)).collect(); + let class = if names.is_empty() { String::new() } else { format!(" class=\"{}\"", names.join(" ")) }; + let root = if node.depth == 0 { " data-rune-static" } else { "" }; + let sizes = if node.attrs.contains(" srcset=") { sizes(node, widths, &by_path) } else { String::new() }; + write!(body, "<{}{root}{class}{}{sizes}>", node.tag, node.attrs).ok(); + if node.tag == "img" { continue; } + body.push_str(&node.inner); + open.push(node.tag); + } + while let Some(tag) = open.pop() { write!(body, "</{tag}>").ok(); } + (body, css) +} + +/// An image's `sizes`: the share of the viewport it took at each width, widest first, so the +/// browser picks a `srcset` file for the width it shows at. +fn sizes(node: &ExportNode, widths: &[(f32, Vec<ExportNode>)], by_path: &[HashMap<&str, &ExportNode>]) -> String { + let vw = |k: usize| by_path[k].get(node.path.as_str()).map(|n| (n.width / widths[k].0 * 100.0).ceil()); + let mut parts: Vec<String> = Vec::new(); + for k in (1..widths.len()).rev() { + if let Some(v) = vw(k) { parts.push(format!("(min-width:{}px) {v}vw", widths[k].0)); } + } + parts.push(format!("{}vw", vw(0).unwrap_or(100.0))); + format!(" sizes=\"{}\"", parts.join(",")) +} + +fn base36(mut n: usize) -> String { + let digits = b"0123456789abcdefghijklmnopqrstuvwxyz"; + let mut out = Vec::new(); + loop { + out.push(digits[n % 36]); + n /= 36; + if n == 0 { break; } + } + out.reverse(); + String::from_utf8(out).unwrap() +} diff --git a/app/vendor/rune/crates/rune/src/runtime/web/export/tests.rs b/app/vendor/rune/crates/rune/src/runtime/web/export/tests.rs new file mode 100644 index 0000000..16239b6 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/web/export/tests.rs @@ -0,0 +1,121 @@ +use super::*; + +fn site(_: &(), cx: &mut Cx<()>) -> El { + let wide = cx.layout_size("root").is_some_and(|s| s[0] >= 700.0); + let cards = if wide { crate::row() } else { crate::col() }; + crate::col().key("root").w_full().role("main").fill(crate::color::hex("#0b0d12").unwrap()).padding(24.0).gap(16.0) + .child(crate::text("Rune").key("title").role("heading").level(1).font(crate::tok::type_::TITLE).color(crate::Color::WHITE)) + .child(crate::rich("Read the <docs> & more.", vec![]).font(crate::tok::type_::BODY) + .link(crate::Link::new(9..15, "https://example.com/docs?a=1&b=2"))) + .child(cards.key("views").role("region").label("Views").gap(12.0) + .child(crate::col().key("a").grow(1.0).radius(12.0).border(1.0, crate::color::hex("#2a2f3a").unwrap()).child(crate::text("Plain Rust"))) + .child(crate::col().key("b").grow(1.0).child(crate::text("Tested"))) + .children(wide.then(|| crate::col().key("c").grow(1.0).child(crate::text("Wide only"))))) + .child(crate::row().key("gh").href("https://github.com/example/rune").child(crate::text("GitHub"))) + .child(crate::col().key("idle").opacity(0.0).child(crate::text("Hidden"))) +} + +fn taken(rt: &mut Runtime<()>, w: f32) -> Vec<ExportNode> { + rt.set_viewport((w, 600.0), 2.0); + rt.frame(0.0); + rt.frame(0.0); + rt.export_nodes() +} + +#[test] +fn exports_landmarks_headings_links_and_text_with_their_css() { + let mut rt = Runtime::new((), site, (400.0, 600.0), Env::default()); + rt.page_mode(); + let nodes = taken(&mut rt, 400.0); + let tags: Vec<&str> = nodes.iter().map(|n| n.tag).collect(); + assert_eq!(tags[..2], ["main", "h1"]); + assert!(nodes.iter().any(|n| n.tag == "section" && n.attrs.contains("id=\"views\"")), "{tags:?}"); + let link = nodes.iter().find(|n| n.tag == "a").expect("href element"); + assert!(link.attrs.contains("href=\"https://github.com/example/rune\"") && link.attrs.contains("id=\"gh\"")); + let lede = nodes.iter().find(|n| n.inner.contains("docs")).expect("rich text"); + assert_eq!(lede.inner, "Read the <a href=\"https://example.com/docs?a=1&amp;b=2\">&lt;docs&gt;</a> &amp; more."); + assert!(!nodes.iter().any(|n| n.inner.contains("Hidden")), "an invisible subtree is left out"); + let root = &nodes[0].decls; + assert!(root.contains(&("flex-direction", "column".into())) && root.contains(&("width", "100%".into()))); + assert!(root.contains(&("padding", "24px".into())) && root.contains(&("row-gap", "16px".into()))); + let card = nodes.iter().find(|n| n.path.ends_with("a") && n.decls.iter().any(|d| d.0 == "border-radius")).expect("card"); + assert!(card.decls.contains(&("border-radius", "12px".into()))); + assert!(card.decls.iter().any(|d| d.0 == "box-shadow" && d.1.starts_with("inset 0 0 0 1px")), "a paint-only border is an inset shadow"); + let title = &nodes[1]; + assert!(title.decls.contains(&("color", "#ffffff".into())) && title.decls.iter().any(|d| d.0 == "font-size")); + assert!(!nodes.iter().any(|n| n.tag != "a" && n.decls.iter().any(|d| d.0 == "user-select")), "page text selects"); + assert!(link.decls.contains(&("user-select", "none".into())), "as the live mirror's, a link's text doesn't"); +} + +#[test] +fn folds_widths_into_media_rules_and_hides_what_a_width_lacks() { + let mut rt = Runtime::new((), site, (400.0, 600.0), Env::default()); + rt.page_mode(); + let narrow = taken(&mut rt, 400.0); + let wide = taken(&mut rt, 900.0); + let (body, css) = page(&[(400.0, narrow), (900.0, wide.clone())]); + assert!(body.starts_with("<main data-rune-static")); + assert!(css.starts_with(page::BASE_CSS)); + let media = css.split_once("@media (min-width:900px){").expect("a wide block").1; + assert!(media.contains("flex-direction:row"), "{media}"); + assert!(!body.contains("Wide only"), "the body is the narrowest tree: {body}"); + assert!(wide.iter().any(|n| n.inner == "Wide only")); + assert!(css.contains(".t>*{display:inline"), "a text element's runs stay inline: {css}"); + assert!(body.contains("<p class=\"t"), "{body}"); + let opened = body.matches('<').count() - body.matches("</").count(); + assert_eq!(opened, body.matches("</").count(), "every element closes: {body}"); +} + +#[test] +fn a_node_missing_at_a_wider_width_is_hidden_there() { + let narrow = vec![ExportNode { path: "0".into(), depth: 0, tag: "div", attrs: String::new(), inner: String::new(), decls: vec![], width: 100.0, text: false }, + ExportNode { path: "0.1".into(), depth: 1, tag: "p", attrs: String::new(), inner: "x".into(), decls: vec![("color", "#fff".into())], width: 100.0, text: true }]; + let wide = vec![narrow[0].clone()]; + let (body, css) = page(&[(360.0, narrow), (800.0, wide)]); + assert_eq!(body, "<div data-rune-static><p class=\"t a0 b0\">x</p></div>"); + assert!(css.ends_with(".a0{color:#fff;display:flex}@media (min-width:800px){.b0{display:none}}"), "{css}"); +} + +#[test] +fn radial_gradients_scale_with_the_box_and_soft_clips_become_masks() { + fn view(_: &(), _: &mut Cx<()>) -> El { + let black = crate::Color::BLACK; + crate::col().key("root").w_full().role("main") + .child(crate::col().key("vignette").w(200.0).h(100.0).fill(black) + .radial_gradient([0.5, 0.5], [100.0, 50.0], [(0.58, crate::Color::TRANSPARENT), (1.0, black)])) + .child(crate::row().key("trace").w(200.0).h(20.0).clip_fade_linear(40.0, 0.0, 0.0, 0.0) + .child(crate::text("x"))) + } + let mut rt = Runtime::new((), view, (400.0, 600.0), Env::default()); + rt.page_mode(); + let nodes = taken(&mut rt, 400.0); + let decl = |prop: &str| nodes.iter().flat_map(|n| &n.decls).find(|d| d.0 == prop).map(|d| d.1.clone()).unwrap_or_default(); + assert_eq!(decl("background"), "radial-gradient(50% 50% at 50% 50%,#00000000 58%,#000000 100%),#000000"); + assert_eq!(decl("mask-image"), "linear-gradient(to right,transparent 0,#000 40px,#000 100%)"); +} + +#[test] +fn text_that_wraps_anywhere_breaks_inside_a_long_word() { + fn view(_: &(), _: &mut Cx<()>) -> El { + crate::row().key("root").w_full().role("main") + .child(crate::text("crates/rune-motion/tests/spring.rs:124").key("path").wrap_anywhere().shrink()) + .child(crate::text("words that wrap at spaces").key("prose").wrap()) + } + let mut rt = Runtime::new((), view, (400.0, 600.0), Env::default()); + rt.page_mode(); + let nodes = taken(&mut rt, 120.0); + let decls = |text: &str| nodes.iter().find(|n| n.inner.starts_with(text)).map(|n| n.decls.clone()).unwrap_or_default(); + assert!(decls("crates/").contains(&("overflow-wrap", "anywhere".into())), "{:?}", decls("crates/")); + assert!(!decls("words").iter().any(|d| d.0 == "overflow-wrap")); +} + +#[test] +fn an_image_source_set_gets_sizes_from_every_width() { + let img = |w: f32| ExportNode { path: "0.0".into(), depth: 1, tag: "img", attrs: " src=\"a-640.avif\" srcset=\"a-640.avif 640w, a-1280.avif 1280w\"".into(), inner: String::new(), decls: vec![], width: w, text: false }; + let root = ExportNode { path: "0".into(), depth: 0, tag: "div", attrs: String::new(), inner: String::new(), decls: vec![], width: 0.0, text: false }; + let (body, css) = page(&[(360.0, vec![root.clone(), img(328.0)]), (1000.0, vec![root, img(500.0)])]); + assert!(body.contains(" sizes=\"(min-width:1000px) 50vw,92vw\">"), "{body}"); + // The `height` attribute is the size it was laid out at; at any other width its class's + // `aspect-ratio` or height decides, so the reset sits under every class (`:where`). + assert!(css.contains(":where([data-rune-static]) img{height:auto}"), "{css}"); +} diff --git a/app/vendor/rune/crates/rune/src/runtime/web/page.rs b/app/vendor/rune/crates/rune/src/runtime/web/page.rs new file mode 100644 index 0000000..e1a45d7 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/web/page.rs @@ -0,0 +1,141 @@ +//! A window onto a taller document (`App::web_document`): the root lays out at its natural +//! height, as a window that fits its content does, and the frame draws the band the browser +//! scrolls through. The host sets the offset; nothing in the runtime scrolls it. +//! +//! The canvas is not a viewport-sized window fixed to the screen: it is a *band* of the document, +//! taller than the viewport by a skirt of overscan at each end, that the browser's own compositor +//! scrolls with the page. Rune draws a new band only when the viewport comes near one of its +//! edges, so a phone pans static pixels at its display's rate instead of waiting for a frame. +use super::*; + +/// How close the viewport may come to the band's edge before a frame draws a new band around it. +const MARGIN: f32 = 64.0; + +/// The band of a taller document the window shows rather than the whole root, and where it +/// starts in the document, in points. +#[derive(Clone, Copy, Debug, Default)] +pub(crate) struct Page { + /// The browser's own scroll position, in points on the device-pixel grid: negative while it + /// rubber-bands past the top. + pub scroll: f32, + /// Where the canvas's texture starts in the document, in points on the same grid. + pub top: f32, + /// The canvas's height in points: the band of the document it covers. + pub band: f32, + /// How much of the band the page shows at once (the layout viewport's height, from the + /// largest viewport so a phone's toolbar doesn't change it). + pub view: f32, +} + +impl RuntimeCore { + /// Lay the root out at its natural height and draw the band of it the host scrolls to + /// with [`Self::set_page_scroll`]. The viewport stays the band's size. + pub(crate) fn page_mode(&mut self) { + self.host.page.get_or_insert_default().view = self.viewport.1; + self.host.fit_height = true; + self.commit.relayout = true; + } + + /// The document's height in points: the root's laid-out height. + #[cfg_attr(not(target_arch = "wasm32"), allow(dead_code))] + pub(crate) fn page_height(&self) -> f32 { + self.tree.nodes.first().map_or(self.viewport.1, |root| root.local.h.max(0.0)) + } + + /// The band's size in points: the canvas covers `band` points of the document, of which + /// `view` are on screen at once. The host sets it from the canvas's own size. Returns whether + /// the band moved (the next frame draws it). + #[cfg_attr(not(target_arch = "wasm32"), allow(dead_code))] + pub(crate) fn set_band(&mut self, band: f32, view: f32) -> bool { + let Some(mut page) = self.host.page else { return false }; + let (band, view) = (band.max(0.0), view.max(0.0)); + if page.band == band && page.view == view { return false; } + page.band = band; + page.view = view; + let top = self.band_top_for(&page, page.scroll).unwrap_or(page.top); + let moved = top != page.top; + page.top = top; + self.host.page = Some(page); + moved + } + + /// Draw the band holding `y`, the browser's `scrollY` (rounded to device pixels, so text + /// keeps its grid). `y` goes negative while a phone rubber-bands past the top: the band + /// follows it, so the page bounces with the finger rather than stopping at the first pixel. + /// Returns whether a frame must draw a new band; while the viewport stays inside the skirt the + /// browser's compositor scrolls the canvas it already has and nothing is drawn. + #[cfg_attr(not(target_arch = "wasm32"), allow(dead_code))] + pub(crate) fn set_page_scroll(&mut self, y: f32) -> bool { + let Some(page) = self.host.page else { return false }; + let y = if y.is_finite() { self.snap_band(y) } else { 0.0 }; + if y == page.scroll { return false; } + let top = self.band_top_for(&page, y).unwrap_or(page.top); + self.host.page = Some(Page { scroll: y, top, ..page }); + top != page.top + } + + /// Where `page`'s band starts for a scroll position, or `None` while the viewport is + /// comfortably inside the band already drawn. A band no taller than the viewport has no room + /// to coast in: the canvas follows the page every frame, as a fixed viewport-sized one did. + fn band_top_for(&self, page: &Page, scroll: f32) -> Option<f32> { + let (view, band) = (page.view, page.band); + if band <= view + 2.0 * MARGIN { return Some(self.snap_band(scroll)); } + let top = page.top; + if scroll >= top + MARGIN && scroll + view <= top + band - MARGIN { return None; } + let want = scroll - (band - view) * 0.5; + Some(self.snap_band(want.clamp(0.0, (self.page_height() - band).max(0.0)))) + } + + fn snap_band(&self, y: f32) -> f32 { + let s = self.env.scale.max(1e-3); + (y * s).round() / s + } + + /// The browser's scroll position, in points. + #[cfg_attr(not(target_arch = "wasm32"), allow(dead_code))] + pub(crate) fn page_scroll_y(&self) -> f32 { + self.host.page.map_or(0.0, |p| p.scroll) + } + + /// The part of the band that is on screen: where it starts in the band's points, and how tall + /// it is. `(0, viewport)` outside a page. + pub(crate) fn page_window(&self) -> (f32, f32) { + let Some(page) = self.host.page else { return (0.0, self.viewport.1) }; + let view = if page.view > 0.0 { page.view } else { self.viewport.1 }; + (page.scroll - page.top, view) + } + + /// Draw a horizontal viewport at `path` scrolled `x` points from its content's left edge. A + /// page's horizontal viewports are the browser's: it scrolls its own mirror's container and + /// tells Rune where it went. Returns whether the content moved (the next frame draws it). + #[cfg_attr(not(target_arch = "wasm32"), allow(dead_code))] + pub(crate) fn set_page_scroll_x(&mut self, path: &str, x: f32) -> bool { + if self.host.page.is_none() || !x.is_finite() { return false; } + let Some(i) = self.live(path) else { return false }; + let Some(st) = self.scroll.scrolls.get_mut(&self.tree.nodes[i].id) else { return false }; + let offset = f64::from(x.max(0.0)).min(st.x.max.max(0.0)); + if (st.x.offset - offset).abs() < 0.01 { return false; } + st.x.offset = offset; + st.x.motion = XMotion::Rest; + true + } + + /// What the root hands its subtree in the paint pass: the band's offset as a rigid scroll. + pub(in crate::runtime) fn root_inh(&self) -> Inh { + let mut inh = Inh::default(); + let dy = -self.page_offset(); + inh.dy = dy; + inh.snap.scroll(1, dy); + inh + } + + /// The band's top down the document, in points (0 outside page mode). A mirror's document + /// position is what a frame drew plus this. + pub(crate) fn page_offset(&self) -> f32 { + self.host.page.map_or(0.0, |p| p.top) + } +} + +#[cfg(test)] +#[path = "page_tests.rs"] +mod tests; diff --git a/app/vendor/rune/crates/rune/src/runtime/web/page_tests.rs b/app/vendor/rune/crates/rune/src/runtime/web/page_tests.rs new file mode 100644 index 0000000..e35fb00 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/web/page_tests.rs @@ -0,0 +1,160 @@ +use super::*; + +fn tall(_: &u32, _: &mut Cx<u32>) -> El { + crate::col().w_full() + .child(crate::col().key("top").w_full().h(300.0)) + .child(crate::col().key("button").w_full().h(100.0).on_press(|n: &mut u32| *n += 1)) + .child(crate::col().key("bottom").w_full().h(600.0)) +} + +#[test] +fn a_page_lays_out_at_its_height_and_draws_the_band_it_is_scrolled_to() { + let mut rt = Runtime::new(0u32, tall, (400.0, 200.0), Env::default()); + rt.page_mode(); + rt.frame(0.0); + assert_eq!(rt.page_height(), 1000.0, "the root keeps its natural height"); + assert_eq!(rt.viewport, (400.0, 200.0), "the window stays the band's size"); + let button = rt.tree.nodes.iter().position(|n| n.key.as_deref() == Some("button")).unwrap(); + assert_eq!(rt.drawn_box(button)[1], 300.0); + + assert!(rt.set_page_scroll(250.4)); + assert!(!rt.set_page_scroll(250.4), "the same offset is no change"); + rt.frame(0.0); + assert_eq!(rt.page_offset(), 250.0, "rounded to the device-pixel grid"); + assert_eq!(rt.drawn_box(button)[1], 50.0, "the button draws 250 points higher"); + + // A press lands where the button draws in the band, not where it sits in the document. + rt.pointer_down(100.0, 80.0); + rt.pointer_up(100.0, 80.0); + rt.frame(0.0); + assert_eq!(rt.state, 1); +} + +#[test] +fn negative_scroll_rubber_bands_the_page_downward() { + fn doc(_: &u32, _: &mut Cx<u32>) -> El { + crate::col().w_full() + .child(crate::text("Top of the page").key("top").w_full().h(300.0)) + .child(crate::col().key("bottom").w_full().h(600.0)) + } + let mut rt = Runtime::new(0u32, doc, (400.0, 200.0), Env::default()); + rt.page_mode(); + rt.frame(0.0); + // Pulling down at the top reports a negative `scrollY`; the band follows it, as the browser's + // own scroll indicator does, instead of stopping dead at the first pixel. + assert!(rt.set_page_scroll(-60.0)); + rt.frame(0.0); + assert_eq!(rt.page_offset(), -60.0); + assert_eq!(rt.drawn_box(1)[1], 60.0, "the page rides down with the bounce"); + let items = rt.web_a11y_items(); + let top = items.iter().find(|i| i.text.contains("Top of the page")).expect("the heading mirrors"); + assert_eq!(top.rect[1], 0.0, "the mirror keeps its document position"); +} + +#[test] +fn page_scroll_is_ignored_outside_page_mode() { + let mut rt = Runtime::new(0u32, tall, (400.0, 200.0), Env::default()); + rt.frame(0.0); + assert!(!rt.set_page_scroll(100.0)); + assert_eq!(rt.page_offset(), 0.0); +} + +#[test] +fn resizing_the_band_does_not_lay_the_page_out_again() { + let mut rt = Runtime::new(0u32, tall, (400.0, 200.0), Env::default()); + rt.page_mode(); + rt.frame(0.0); + let scale = rt.env.scale; + rt.set_viewport((400.0, 160.0), scale); + assert!(!rt.commit.relayout, "a mobile toolbar collapsing only changes the band"); + assert_eq!(rt.viewport, (400.0, 160.0)); + assert_eq!(rt.page_height(), 1000.0); +} + +/// Ten 500-point blocks, 5,000 points of document. +fn blocks(_: &u32, _: &mut Cx<u32>) -> El { + let mut page = crate::col().w_full(); + for i in 0..10 { + page = page.child(crate::col().key(format!("block-{i}")).w_full().h(500.0)); + } + page +} + +#[test] +fn a_band_only_draws_again_when_the_viewport_nears_its_edge() { + let mut rt = Runtime::new(0u32, blocks, (400.0, 800.0), Env::default()); + rt.page_mode(); + rt.set_band(1312.0, 800.0); + rt.frame(0.0); + assert_eq!(rt.page_offset(), 0.0, "the first band starts at the top"); + + // Inside the skirt the browser's compositor scrolls the pixels Rune already drew. + assert!(!rt.set_page_scroll(120.0)); + assert_eq!(rt.page_offset(), 0.0); + assert!(!rt.set_page_scroll(400.0), "up to 64 points from the band's foot is still inside"); + assert_eq!(rt.page_offset(), 0.0); + + // Nearer than that, a frame draws a new band centred on the window: 256 points of skirt. + assert!(rt.set_page_scroll(1000.0)); + assert_eq!(rt.page_offset(), 744.0); + assert!(!rt.set_page_scroll(1100.0), "and the new band holds the next stretch of scroll"); + + // The last band stops at the document's foot instead of showing empty page below it. + assert!(rt.set_page_scroll(4200.0)); + assert_eq!(rt.page_offset(), 3688.0, "5000 - 1312"); + assert_eq!(rt.page_offset() + 1312.0, rt.page_height()); +} + +#[test] +fn a_band_no_taller_than_the_window_follows_the_page_every_frame() { + let mut rt = Runtime::new(0u32, blocks, (400.0, 800.0), Env::default()); + rt.page_mode(); + rt.set_band(800.0, 800.0); + rt.frame(0.0); + assert!(rt.set_page_scroll(20.0)); + assert_eq!(rt.page_offset(), 20.0, "no skirt to coast in"); +} + +#[test] +fn a_mirror_keeps_its_document_position_across_band_anchors() { + let mut rt = Runtime::new(0u32, blocks, (480.0, 300.0), Env::default()); + rt.page_mode(); + rt.set_band(812.0, 300.0); + rt.frame(0.0); + let before: Vec<_> = rt.web_a11y_items().iter().map(|i| (i.path.clone(), i.rect)).collect(); + assert!(rt.set_page_scroll(1200.0), "the band is drawn again"); + rt.frame(0.0); + let after: Vec<_> = rt.web_a11y_items().iter().map(|i| (i.path.clone(), i.rect)).collect(); + assert_eq!(before, after); +} + +#[test] +fn a_band_knows_which_part_of_it_the_window_shows() { + fn tall_visible(_: &u32, _: &mut Cx<u32>) -> El { + crate::col().w_full() + .child(crate::col().key("button").w_full().h(100.0).on_visible(|s: &mut u32, on: bool, _| *s = u32::from(on))) + .child(crate::col().key("fill").w_full().h(900.0)) + } + let mut rt = Runtime::new(0u32, tall_visible, (400.0, 200.0), Env::default()); + rt.page_mode(); + rt.set_band(712.0, 200.0); + for _ in 0..3 { rt.frame(0.0); } + assert_eq!(rt.state, 1, "the button is on screen at the top"); + + // Inside the skirt no frame is drawn at all: the window moves within the band, and the band + // still holds the button where it drew it. + assert!(!rt.set_page_scroll(380.0)); + for _ in 0..3 { rt.frame(0.0); } + assert_eq!(rt.page_window(), (380.0, 200.0), "the window is inside the band, not at its top"); + assert_eq!(rt.drawn_box(1)[1], 0.0, "the band still draws it where it was drawn"); + assert_eq!(rt.state, 0, "but the window has moved past it"); +} + +#[test] +fn a_window_that_is_not_a_page_has_no_band_to_move() { + let mut rt = Runtime::new(0u32, tall, (400.0, 200.0), Env::default()); + rt.frame(0.0); + assert!(!rt.set_band(600.0, 200.0) && !rt.set_page_scroll(250.0)); + assert!(rt.host.page.is_none(), "the host's band and scroll don't make it one"); + assert_eq!((rt.page_offset(), rt.page_scroll_y(), rt.page_window()), (0.0, 0.0, (0.0, 200.0))); +} diff --git a/app/vendor/rune/crates/rune/src/runtime/web/runtime.rs b/app/vendor/rune/crates/rune/src/runtime/web/runtime.rs new file mode 100644 index 0000000..7a311d1 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/web/runtime.rs @@ -0,0 +1,233 @@ +//! Browser-only access to the focused edit, kept beside Runtime so the shell sees no nodes. +#![cfg_attr(not(target_arch = "wasm32"), allow(dead_code))] +use super::*; + +/// The last context sent to the DOM. Secure text never enters this cache. +#[derive(Default)] +pub(crate) struct Mirror { + pub key: String, + pub text: String, + /// UTF-8 byte offset in the model; DOM offsets are UTF-16 relative to this window. + pub base: usize, + pub anchor: u32, + pub focus: u32, + pub secure: bool, +} + +/// Read at most 512 UTF-16 units on each side, without scanning the document prefix. +fn context_window(edit: &crate::TextEdit) -> (usize, &str, u32, u32) { + let (a, b) = edit.range(); + let (raw_anchor, raw_focus) = if edit.anchor <= edit.focus { (a, b) } else { (b, a) }; + let mut start = a; + let mut units = 0; + for (i, ch) in edit.text[..a].char_indices().rev() { + if units + ch.len_utf16() > 512 { break; } + units += ch.len_utf16(); + start = i; + } + let mut end = b; + let mut units = 0; + for ch in edit.text[b..].chars() { + if units + ch.len_utf16() > 512 { break; } + units += ch.len_utf16(); + end += ch.len_utf8(); + } + let anchor = edit.text[start..raw_anchor].encode_utf16().count() as u32; + let focus = edit.text[start..raw_focus].encode_utf16().count() as u32; + (start, &edit.text[start..end], anchor, focus) +} + +/// UTF-16 units a window may grow by at each end to take in the rest of a line it cuts. +const LINE_MORE: usize = 2048; + +/// `window` grown to whole lines at either end, where the line it cuts ends within +/// [`LINE_MORE`] more units: a screen reader reads the page's field a line at a time, so the +/// caret's lines are whole however long the draft. A longer line stays cut. +fn whole_lines<'a>(edit: &'a crate::TextEdit, (start, text, anchor, focus): (usize, &'a str, u32, u32)) -> (usize, &'a str, u32, u32) { + let s = edit.text.as_str(); + let end = start + text.len(); + // Only as far back and on as could be taken in (4 bytes a unit at most). + let from = s.floor_char_boundary(start.saturating_sub(LINE_MORE * 4)); + let head = match s[from..start].rfind('\n') { + Some(p) => from + p + 1, + None if from == 0 => 0, + None => start, + }; + let to = s.ceil_char_boundary((end + LINE_MORE * 4).min(s.len())); + let tail = match s[end..to].find('\n') { + Some(p) => end + p, + None if to == s.len() => to, + None => end, + }; + let units = |a: usize, b: usize| s[a..b].encode_utf16().count(); + let head = if units(head, start) <= LINE_MORE { head } else { start }; + let tail = if units(end, tail) <= LINE_MORE { tail } else { end }; + let shift = units(head, start) as u32; + (head, &s[head..tail], anchor + shift, focus + shift) +} + +impl Mirror { + fn update(&mut self, key: &str, edit: Option<&crate::TextEdit>) -> bool { + let secure = edit.is_some_and(|e| e.is_secure()); + let (base, text, anchor, focus) = edit.filter(|_| !secure).map(|e| whole_lines(e, context_window(e))).unwrap_or((0, "", 0, 0)); + if self.key == key && self.base == base && self.text == text && self.anchor == anchor + && self.focus == focus && self.secure == secure { return false; } + self.key.clear(); self.key.push_str(key); + self.text.clear(); self.text.push_str(text); + self.base = base; self.anchor = anchor; self.focus = focus; self.secure = secure; + true + } +} + +/// Reject offsets in the middle of a surrogate pair, rather than corrupting the Rust string. +fn byte_at(text: &str, utf16: usize) -> Option<usize> { + let mut units = 0; + for (byte, ch) in text.char_indices() { + if units == utf16 { return Some(byte); } + units += ch.len_utf16(); + } + (units == utf16).then_some(text.len()) +} + +impl RuntimeCore { + /// An action whose handler may ask for what a browser allows only inside the input's event + /// (the clipboard, a new tab, a menu, a dialog) or that routes keys and focus: it runs in a + /// frame inside that event. The rest (a move's hover, enter and leave, what a frame reports + /// for the next: layout, visibility, rows shown, a selection's change) waits for the display. + fn web_needs_event(action: &Action) -> bool { + matches!(action, Action::Press(..) | Action::DoublePress(_) | Action::MiddlePress(_) | Action::Link(..) | Action::LinkSecondary(..) + | Action::SecondaryPress(..) | Action::Drag(..) | Action::DragRepeat(..) | Action::DragStart(_) | Action::DragEnd(..) | Action::Dismiss(_) + | Action::FieldMenu(..) | Action::Files(_) | Action::Paste(..) | Action::ClipboardRead(..) | Action::FileDialog(..) | Action::Key { .. } + | Action::KeyUp(_) | Action::Physical(..) | Action::Focus(..) | Action::FocusControl(_) | Action::Blur) + } + + /// Whether a release (or an edit) left a handler that has to run inside the input's event. + pub(crate) fn web_release_needs_frame(&self) -> bool { + self.frame.queue.iter().any(Self::web_needs_event) + } + + /// A press whose only such action focuses a text field runs that action now, as a frame + /// would (its double click and its composition included), so the page's own field takes + /// focus inside the press and the next key goes to it; the rest of the queue and the frame + /// wait for the display's. False, with nothing run, when any other such action is queued or + /// a focus is already asked for. + pub(crate) fn web_focus_field(&mut self, app: &mut dyn AppDriver) -> bool { + if self.commit.relayout || self.kbd.focus_request.is_some() || self.frame.pending.focus_to.is_some() { return false; } + let needs: Vec<usize> = self.frame.queue.iter().enumerate().filter(|(_, a)| Self::web_needs_event(a)).map(|(i, _)| i).collect(); + let [pos] = needs[..] else { return false }; + if !matches!(self.frame.queue.iter().nth(pos), Some(Action::Focus(..))) { return false; } + let mut tx = self.transaction(app); + let action = self.frame.queue.remove(pos); + let changed = self.run_action(app, action, &mut tx); + self.commit.dirty |= changed; + merge(&mut self.frame.pending, tx); + true + } + + /// The focused field's context from the model, which an edit or a focus just changed, for + /// the page's field before its next key; None when what's pending needs a whole frame now + /// (a handler that asked for the clipboard, a link, focus or a selection). + pub(crate) fn web_edit_context(&mut self, app: &mut dyn AppDriver, mirror: &mut Mirror) -> Option<bool> { + let tx = &self.frame.pending; + if self.web_release_needs_frame() || self.kbd.focus_request.is_some() || tx.blur || tx.focus_to.is_some() || tx.select.is_some() || !tx.keys.is_empty() + || tx.copy.is_some() || tx.paste || !tx.clipboard_reads.is_empty() || !tx.pick_reads.is_empty() + || !tx.open_urls.is_empty() || !tx.file_dialogs.is_empty() || !tx.popups.is_empty() || tx.clear_secret { + return None; + } + let access = self.focused_input()?.access.clone()?; + let key = self.kbd.focus.path()?; + Some(mirror.update(key, Some(access(app.states())))) + } + pub(crate) fn web_context(&self, mirror: &mut Mirror) -> bool { + match self.focused_input().filter(|i| i.access.is_some()) { + Some(input) => mirror.update(self.kbd.focus.path().unwrap_or_default(), Some(&input.edit)), + None => mirror.update("", None), + } + } + + pub(crate) fn web_key(&mut self, app: &mut dyn AppDriver, event: &serde_json::Value) -> bool { + let flag = |key: &str| event[key].as_bool().unwrap_or(false); + let mods = crate::input::key_table::web_mods(flag("shift"), flag("ctrl"), flag("alt"), flag("meta")); + let name = event["key"].as_str().unwrap_or_default(); + let code = event["code"].as_str().filter(|c| !c.is_empty() && !c.contains('+')) + .and_then(|c| c.parse::<crate::Shortcut>().ok()) + .map(|s| s.physical_key()); + let key = match crate::input::key_table::named_key_from_str(name) { + Some(key) => key, + None if name == " " => crate::Key::Text(" ".into()), + None if mods.cmd => { + let mut chars = name.chars(); + match (chars.next(), chars.next()) { + (Some(c), None) => { + let c = if !c.is_ascii() { code.and_then(crate::shortcuts::us_char).unwrap_or(c) } else { c }; + crate::Key::Command(c.to_ascii_lowercase()) + } + _ => return false, + } + } + None => return false, + }; + let event_key = crate::KeyEvent { key, mods }; + let activate = event_key.key == crate::Key::Tab; + let repeat = flag("repeat"); + if let Some(key) = code { + self.physical_with_fallback(app, crate::PhysicalInput::Key { key, mods, pressed: true, repeat }, Some(event_key)); + } else if repeat { + self.repeat_key(event_key); + } else { + self.key(event_key); + } + activate + } + + pub(crate) fn web_secure(&mut self, key: &str, text: String) { + let event = crate::KeyEvent { key: crate::Key::Text(text), mods: crate::Mods::default() }; + if self.kbd.focus.path() == Some(key) && self.has_secure_focus() { + self.key(event); + } + } + + pub(crate) fn web_edit(&mut self, app: &mut dyn AppDriver, event: &serde_json::Value) { + let Some(key) = event["key"].as_str() else { return }; + if self.kbd.focus.path() != Some(key) || self.has_secure_focus() { return; } + let number = |key: &str| event[key].as_u64().and_then(|n| usize::try_from(n).ok()); + let Some(base) = number("base") else { return }; + let Some(expected) = event["expected"].as_str() else { return }; + let mut tx = self.transaction(app); + let composing_before = self.composing(app); + let changed = self.with_focused(app, |edit| { + // Browser edits belong to the snapshot from which its context was mirrored. + if !edit.text.get(base..).is_some_and(|s| s.starts_with(expected)) { return EditOutcome::default(); } + if event["kind"] == "edit" || event["kind"] == "preedit" { + let Some((start, end)) = number("start").zip(number("end")) else { return EditOutcome::default() }; + let Some((a, b)) = byte_at(expected, start).zip(byte_at(expected, end)) else { return EditOutcome::default() }; + if a > b { return EditOutcome::default(); } + edit.ime(&Ime::Preedit(String::new(), None, Vec::new())); + let raw = (base + a, base + b); + edit.anchor = raw.0; edit.focus = raw.1; + edit.snap_to_pills(); + let snapped = (edit.anchor, edit.focus) != raw; + let text = event["text"].as_str().unwrap_or_default(); + if event["kind"] == "preedit" { + edit.ime(&Ime::Preedit(text.to_owned(), Some((text.len(), text.len())), Vec::new())); + return EditOutcome::default(); + } + edit.insert(text); + if snapped { return EditOutcome::default(); } + } + if let Some((anchor, focus)) = number("anchor").zip(number("focus")) + && let Some((a, f)) = byte_at(&edit.text[base..], anchor).zip(byte_at(&edit.text[base..], focus)) { + edit.anchor = base + a; edit.focus = base + f; + edit.snap_to_pills(); + } + EditOutcome::default() + }, &mut tx); + if composing_before || event["kind"] == "preedit" { self.kbd.ime_took_key(); } + if changed { self.commit.dirty = true; } + merge(&mut self.frame.pending, tx); + } +} + +#[cfg(test)] +#[path = "runtime_tests.rs"] +mod tests; diff --git a/app/vendor/rune/crates/rune/src/runtime/web/runtime_tests.rs b/app/vendor/rune/crates/rune/src/runtime/web/runtime_tests.rs new file mode 100644 index 0000000..871191c --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/web/runtime_tests.rs @@ -0,0 +1,181 @@ +use super::*; +use serde_json::json; + +#[test] +fn utf16_replacement_preserves_callbacks_and_rejects_stale_context() { + fn view(state: &(crate::TextEdit, usize), _: &mut Cx<(crate::TextEdit, usize)>) -> El { + crate::text_input(&state.0, crate::tok::type_::BODY).key("input") + .on_edit(|s: &mut (crate::TextEdit, usize)| &mut s.0) + .on_input_change(|s: &mut (crate::TextEdit, usize), _| s.1 += 1) + } + let mut rt = Runtime::new((crate::TextEdit::new("a🦀c"), 0), view, (300.0, 100.0), Env::default()); + rt.frame(0.0); + let key = rt.tree.nodes.iter().find(|n| n.key.as_deref() == Some("input")).unwrap().path.clone(); + rt.set_focus(Some(key.clone()), true); + let event = json!({"kind":"edit", "key":key, "base":0, "expected":"a🦀c", + "start":1, "end":3, "text":"é", "anchor":2, "focus":2}); + rt.web_edit(&event); + rt.frame(0.0); + assert_eq!((&*rt.state.0.text, rt.state.1, rt.state.0.focus), ("aéc", 1, 3)); + rt.web_edit(&event); + rt.frame(0.0); + assert_eq!((&*rt.state.0.text, rt.state.1), ("aéc", 1)); + assert_eq!(byte_at("a🦀c", 2), None); +} + +#[test] +fn context_is_bounded_at_unicode_boundaries_and_keeps_the_selection() { + let mut edit = crate::TextEdit::new("é🦀a".repeat(800)); + let boundaries: Vec<_> = edit.text.char_indices().map(|(i, _)| i).chain([edit.text.len()]).collect(); + for &a in boundaries.iter().step_by(157) { + for &f in boundaries.iter().step_by(271) { + edit.anchor = a; edit.focus = f; + let (base, text, anchor, focus) = context_window(&edit); + assert_eq!(base + byte_at(text, anchor as usize).unwrap(), a); + assert_eq!(base + byte_at(text, focus as usize).unwrap(), f); + let before = edit.text[base..a.min(f)].encode_utf16().count(); + let after = edit.text[a.max(f)..base + text.len()].encode_utf16().count(); + assert!(before <= 512 && after <= 512); + if base > 0 { assert!(before + edit.text[..base].chars().next_back().unwrap().len_utf16() > 512); } + if base + text.len() < edit.text.len() { + assert!(after + edit.text[base + text.len()..].chars().next().unwrap().len_utf16() > 512); + } + } + } +} + +#[test] +fn mirror_skips_unchanged_frames_and_never_caches_secure_text() { + let mut mirror = Mirror::default(); + let mut edit = crate::TextEdit::new("🦀".repeat(10_000)); + assert!(mirror.update("field", Some(&edit))); + assert_eq!(mirror.text.encode_utf16().count(), 512); + let allocation = mirror.text.as_ptr(); + for _ in 0..120 { assert!(!mirror.update("field", Some(&edit))); } + assert_eq!(mirror.text.as_ptr(), allocation); + edit.anchor -= 4; + assert!(mirror.update("field", Some(&edit)), "selection-only changes sync"); + edit.text.push('x'); + assert!(mirror.update("field", Some(&edit)), "edits within the window sync"); + assert!(mirror.update("other", Some(&edit)), "same contents in a different field sync"); + edit.set_secure(true); + assert!(mirror.update("other", Some(&edit))); + assert!(mirror.secure && mirror.text.is_empty()); + assert_eq!((mirror.base, mirror.anchor, mirror.focus), (0, 0, 0)); + edit.insert("secret"); + assert!(!mirror.update("other", Some(&edit)), "secret edits don't mirror to the DOM"); + edit.set_revealed(true); + assert!(!mirror.update("other", Some(&edit)), "revealing changes only the GPU display, not DOM text services"); + assert!(mirror.secure && mirror.text.is_empty()); + assert_eq!((mirror.base, mirror.anchor, mirror.focus), (0, 0, 0)); + assert!(mirror.update("", None)); + assert!(!mirror.update("", None)); +} + +#[test] +fn recomposition_replaces_its_range_without_changing_committed_text() { + fn view(edit: &crate::TextEdit, _: &mut Cx<crate::TextEdit>) -> El { + crate::text_input(edit, crate::tok::type_::BODY).key("input").on_edit(|s: &mut crate::TextEdit| s) + } + let mut rt = Runtime::new(crate::TextEdit::new("🦀 hello "), view, (300.0, 100.0), Env::default()); + rt.frame(0.0); + let key = rt.tree.nodes.iter().find(|n| n.key.as_deref() == Some("input")).unwrap().path.clone(); + rt.set_focus(Some(key.clone()), true); + let mut event = json!({"kind":"preedit", "key":key, "base":5, "expected":"hello ", + "start":0, "end":6, "text":"hello", "anchor":5, "focus":5}); + rt.web_edit(&event); + assert_eq!(rt.state.text, "🦀 hello "); + assert_eq!(rt.state.display().0, "🦀 hello", "preedit replaces the word, not appends"); + event["text"] = json!("help"); + event["anchor"] = json!(4); event["focus"] = json!(4); + rt.web_edit(&event); + assert_eq!(rt.state.display().0, "🦀 help"); + event["kind"] = json!("edit"); + rt.web_edit(&event); + assert_eq!(rt.state.text, "🦀 help"); + assert!(rt.state.preedit().is_none()); + assert_eq!(rt.state.focus, rt.state.text.len()); + rt.web_edit(&event); + assert_eq!(rt.state.text, "🦀 help", "stale context rejected"); + event["base"] = json!(1); + rt.web_edit(&event); + assert_eq!(rt.state.text, "🦀 help", "base must be a UTF-8 boundary"); +} + +#[test] +fn replacement_offsets_are_local_utf16_and_cannot_escape_the_snapshot() { + fn view(edit: &crate::TextEdit, _: &mut Cx<crate::TextEdit>) -> El { + crate::text_input(edit, crate::tok::type_::BODY).key("input").on_edit(|s: &mut crate::TextEdit| s) + } + let mut rt = Runtime::new(crate::TextEdit::new("é🦀 tail"), view, (300.0, 100.0), Env::default()); + rt.frame(0.0); + let key = rt.tree.nodes.iter().find(|n| n.key.as_deref() == Some("input")).unwrap().path.clone(); + rt.set_focus(Some(key.clone()), true); + let mut event = json!({"kind":"edit", "key":key, "base":2, "expected":"🦀 ", + "start":1, "end":2, "text":"x", "anchor":1, "focus":1}); + rt.web_edit(&event); + assert_eq!(rt.state.text, "é🦀 tail", "mid-surrogate offsets rejected"); + event["start"] = json!(0); event["end"] = json!(4); + rt.web_edit(&event); + assert_eq!(rt.state.text, "é🦀 tail", "replacement must stay inside expected context"); + event["end"] = json!(2); + rt.web_edit(&event); + assert_eq!(rt.state.text, "éx tail"); + assert_eq!(rt.state.focus, 3); +} + +#[test] +fn web_key_forwards_dom_code_for_digits_letters_and_punctuation() { + type Seen = Vec<(crate::Key, Option<crate::PhysicalKeyCode>, bool)>; + fn view(_: &Seen, _: &mut Cx<Seen>) -> El { crate::el() } + let mut rt = Runtime::new(Seen::new(), view, (100.0, 100.0), Env::default()); + rt.on_key = Some(|s, ev, tx| { s.push((ev.key.clone(), tx.physical_key(), tx.key_repeat())); true }); + rt.frame(0.0); + for (key, code, repeat) in [("/", "Digit7", false), ("/", "Slash", true), (":", "Period", false), ("k", "KeyK", false)] { + rt.web_key(&json!({"kind":"key", "key":key, "code":code, "meta":true, "shift":true, "repeat":repeat})); + rt.frame(0.0); + } + use crate::PhysicalKeyCode::*; + assert_eq!(rt.state, [ + (crate::Key::Command('/'), Some(Digit7), false), + (crate::Key::Command('/'), Some(Slash), true), + (crate::Key::Command(':'), Some(Period), false), + (crate::Key::Command('k'), Some(KeyK), false), + ]); +} + +#[test] +fn web_key_forwards_function_keys_f1_through_f24() { + type Seen = Vec<(crate::Key, Option<crate::PhysicalKeyCode>)>; + fn view(_: &Seen, _: &mut Cx<Seen>) -> El { crate::el() } + let mut rt = Runtime::new(Seen::new(), view, (100.0, 100.0), Env::default()); + rt.on_key = Some(|s, ev, tx| { s.push((ev.key.clone(), tx.physical_key())); true }); + rt.frame(0.0); + for (key, code) in [("F1", "F1"), ("F12", "F12"), ("F24", "F24"), ("F0", ""), ("F01", ""), ("F25", "")] { + rt.web_key(&json!({"kind":"key", "key":key, "code":code})); + rt.frame(0.0); + } + use crate::PhysicalKeyCode::*; + assert_eq!(rt.state, [ + (crate::Key::Function(1), Some(F1)), + (crate::Key::Function(12), Some(F12)), + (crate::Key::Function(24), Some(F24)), + ]); +} + +#[test] +fn web_key_keeps_cmd_space_as_text_and_normalizes_non_ascii_chords() { + type Seen = Vec<(crate::Key, Option<crate::PhysicalKeyCode>)>; + fn view(_: &Seen, _: &mut Cx<Seen>) -> El { crate::el() } + let mut rt = Runtime::new(Seen::new(), view, (100.0, 100.0), Env::default()); + rt.on_key = Some(|s, ev, tx| { s.push((ev.key.clone(), tx.physical_key())); true }); + rt.frame(0.0); + rt.web_key(&json!({"kind":"key", "key":" ", "code":"Space", "ctrl":true})); + rt.frame(0.0); + rt.web_key(&json!({"kind":"key", "key":"м", "code":"KeyV", "ctrl":true})); + rt.frame(0.0); + assert_eq!(rt.state, [ + (crate::Key::Text(" ".into()), Some(crate::PhysicalKeyCode::Space)), + (crate::Key::Command('v'), Some(crate::PhysicalKeyCode::KeyV)), + ]); +} diff --git a/app/vendor/rune/crates/rune/src/runtime/width_hold_tests.rs b/app/vendor/rune/crates/rune/src/runtime/width_hold_tests.rs new file mode 100644 index 0000000..4a88ae6 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/width_hold_tests.rs @@ -0,0 +1,17 @@ +use super::WidthHold; + +#[test] +fn a_width_change_defers_heights_then_lets_a_streaming_row_shrink() { + let hold = WidthHold::rewrap(2.0); + assert!(hold.defers(2.0) && hold.defers(2.11)); + assert!(!hold.defers(2.12), "heights land once the width is stable"); + assert!(!hold.may_shrink(2.12) && !hold.may_shrink(2.39)); + assert!(hold.may_shrink(2.4), "a streaming row may shrink once the rewrap is well past"); +} + +#[test] +fn no_width_change_defers_nothing() { + for at in [-1.0, 0.0, 5.0] { + assert!(!WidthHold::Off.defers(at) && WidthHold::Off.may_shrink(at), "at {at}"); + } +} diff --git a/app/vendor/rune/crates/rune/src/runtime/window_requests.rs b/app/vendor/rune/crates/rune/src/runtime/window_requests.rs new file mode 100644 index 0000000..ad6339e --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/window_requests.rs @@ -0,0 +1,354 @@ +//! What a commit asks of the window besides its pixels: the content height a window that +//! fits its content asks for (`App::fit_content_height`), and the title (`Tx::set_title`). +use super::*; + +/// Window/host boundary state owned by [`RuntimeCore`]: system settings, zoom, titlebar, window +/// frame/title/fit/minimize requests, popups, file dialogs, open-URL requests, accessibility and +/// web page bands. +pub(crate) struct HostState { + /// The view's UI zoom and the window it applies to (`Cx::zoom`). + pub(in crate::runtime) zoom: zoom::Zoom, + pub(in crate::runtime) titlebar: titlebar::Titlebar, + pub(in crate::runtime) titlebar_inset: f32, + pub(in crate::runtime) system_reduced_motion: bool, + pub(in crate::runtime) system_accent: crate::SystemAccent, + /// What [`Cx::system_contrast`] reports. + pub(in crate::runtime) system_contrast: Option<crate::SystemContrast>, + /// What [`Cx::system_increased_contrast`] reports. + pub(in crate::runtime) system_increased_contrast: bool, + pub(in crate::runtime) scroll_bars: system_settings::ScrollBarHost, + pub(crate) native_overlay: bool, + /// The window or overlay surface's frame counts, published by its host. + pub(crate) surface_stats: Option<std::sync::Arc<std::sync::Mutex<crate::SurfaceStats>>>, + /// `App::dev_stats`. + pub(crate) app_stats: Option<fn() -> String>, + /// The window's content top-left in global screen points, as its host last saw it. + window_origin: (f32, f32), + /// The window's content top-left in desktop pixels, as its host last saw it (`Drag::screen_point`). + pub(in crate::runtime) window_pixels: Option<(i32, i32)>, + pub(in crate::runtime) window_focused: Option<bool>, + /// The host's window frame isn't moving or about to: set by the host before each frame. + pub(crate) window_resting: bool, + /// A frame change for the window (`Tx::resize_window`), with its spring resolved. + pub(crate) window_frame: Option<crate::window::frame::FrameRequest>, + /// The window's title (`Tx::set_title`), from `AppSpec`'s. + pub(crate) window_title: Title, + /// The window's height follows the root's natural height (`App::fit_content_height`). + pub(crate) fit_height: bool, + /// The height a window that fits its content last asked for, and the frame its move + /// starts with. The host takes the hold as it starts the move. + pub(crate) fit: FitWindow, + /// A handler or `update` asked to minimize the window (`Tx::minimize`); the shell takes it, + /// after a show the same turn asked for (`window::Minimize`). + pub(crate) minimize: crate::window::Minimize, + /// Links handlers asked to open that this runtime left unopened (`Runtime::take_url_requests`). + url_requests: Vec<String>, + /// True when attached to a live window, overlay or web canvas, not a headless or scripted run. + pub(crate) open_urls_natively: bool, + /// Pop-up menus asked for (`Tx::popup_menu`) and not yet answered, oldest first. + pub(in crate::runtime) popups: popup_dispatch::Popups, + /// The file dialog asked for (`Tx::open_file`, `Tx::save_file`) and not yet answered. + pub(in crate::runtime) file_dialog: crate::file_dialog::DialogState, + /// File dialog callbacks, by id, until their answer runs. + pub(in crate::runtime) file_dialog_answers: Vec<(u64, crate::file_dialog::AnswerFn)>, + pub(in crate::runtime) next_file_dialog: u64, + /// `Tx::announce`'s last words, for the accessibility tree's live region. + pub(crate) announcement: crate::a11y::Announcement, + /// The accessibility tree, while an assistive client listens (`a11y/tree.rs`). + pub(in crate::runtime) a11y: Option<Box<crate::a11y::tree::A11yTree>>, + /// The band of a taller document the window draws (`App::web_document`). + pub(in crate::runtime) page: Option<web_page::Page>, +} + +impl HostState { + // Single-caller constructor for `RuntimeCore::new`; inlined so it stays in its caller's + // codegen unit instead of shifting partitioning and dropping inlining in the paint walk. + #[inline] + pub(in crate::runtime) fn new(viewport: (f32, f32), env: &Env) -> Self { + Self { + zoom: zoom::Zoom { k: 1.0, window: viewport, window_scale: env.scale }, + titlebar: Default::default(), + titlebar_inset: 0.0, + system_reduced_motion: false, + system_accent: crate::SystemAccent::DEFAULT, + system_contrast: None, + system_increased_contrast: false, + scroll_bars: Default::default(), + native_overlay: false, + surface_stats: None, + app_stats: None, + window_origin: (0.0, 0.0), + window_pixels: None, + window_focused: None, + window_resting: false, + window_frame: None, + window_title: Default::default(), + fit_height: false, + fit: Default::default(), + minimize: Default::default(), + url_requests: Vec::new(), + open_urls_natively: false, + popups: Default::default(), + file_dialog: Default::default(), + file_dialog_answers: Vec::new(), + next_file_dialog: 0, + announcement: Default::default(), + a11y: None, + page: None, + } + } + + #[inline] + pub(super) fn window_origin(&self) -> (f32, f32) { + self.window_origin + } + + /// Updates the cached global screen origin; returns true when it changed. + #[inline] + pub(super) fn set_window_origin(&mut self, origin: (f32, f32)) -> bool { + if self.window_origin == origin { return false; } + self.window_origin = origin; + true + } + + /// Takes the links handlers asked to open that this runtime didn't open: all of them in a + /// headless run or test, none in a window. Each was already checked. + #[inline] + pub(crate) fn take_url_requests(&mut self) -> Vec<String> { + std::mem::take(&mut self.url_requests) + } + + #[inline] + pub(crate) fn push_url_request(&mut self, url: String) { + self.url_requests.push(url); + } + + #[inline] + pub(crate) fn a11y(&self) -> Option<&crate::a11y::tree::A11yTree> { + self.a11y.as_deref() + } + + #[inline] + pub(crate) fn a11y_mut(&mut self) -> Option<&mut crate::a11y::tree::A11yTree> { + self.a11y.as_deref_mut() + } + + #[inline] + pub(crate) fn a11y_or_insert(&mut self) -> &mut crate::a11y::tree::A11yTree { + self.a11y.get_or_insert_with(Default::default) + } + + #[inline] + pub(crate) fn a11y_deactivate(&mut self) { + self.a11y = None; + } + + #[cfg(test)] + #[inline] + pub(crate) fn popup_is_open(&self) -> bool { + self.popups.is_open() + } + + #[inline] + pub(super) fn clear_titlebar(&mut self) { + self.titlebar.clear(); + } + + #[inline] + pub(crate) fn set_app_stats(&mut self, stats: Option<fn() -> String>) { + self.app_stats = stats; + } + + /// Asks the window for the content's new height, on this commit's spring. The first + /// commit, a viewport change and `Tx::instant` jump. + #[allow(clippy::too_many_arguments)] + pub(super) fn fit_window( + &mut self, + height: f32, + viewport: (f32, f32), + scale: f32, + reduced_motion: bool, + headless: bool, + tx: &Tx, + first: bool, + ) { + let height = height.ceil_to(scale).max(1.0); + if !self.fit.ask(height, viewport.1) { return; } + let jump = first || tx.commit.snaps() || tx.relayout || reduced_motion; + // Only a macOS window and headless runs move the frame on a spring. + if !jump && self.window_resting && (cfg!(target_os = "macos") || headless) { self.fit.hold = FitHold::Asked; } + let request = crate::window::frame::FrameRequest { + size: Some((viewport.0, height)), animate: !jump, + spring: (!jump).then(|| tx.motion.map_or(crate::tok::motion::DEFAULT, MotionSource::spring)), center: false, + }; + self.window_frame = Some(self.window_frame.unwrap_or_default().merge(request)); + } + + #[inline] + pub(super) fn content_height_from(&self, view_height: f32) -> f32 { + (view_height * self.zoom.k).ceil_to(self.zoom.window_scale).max(1.0) + } + + /// Someone resized a window that fits its content (not a page's band) to `height`: it + /// goes back to the content's height. + #[inline] + pub(super) fn fit_resized(&mut self, height: f32, current_height: f32) -> bool { + self.fit_height && self.page.is_none() && self.window_resting && self.fit.resized(height, current_height) + } + + /// Whether this frame holds its motion for the window (see [`FitHold`]). + #[inline] + pub(super) fn fit_frame_holds(&mut self) -> bool { + self.fit.frame_holds() + } +} + +/// The window's title: `AppSpec`'s until a handler sets another, and whether the window has +/// yet to show the last one set. +#[derive(Debug, Default)] +pub(crate) enum Title { + /// No title yet: the window hasn't taken `AppSpec`'s. + #[default] + Unset, + /// The title the window shows. + Shown(String), + /// A title set since the window last showed one. + Pending(String), +} + +/// What moves the title on. +#[derive(Debug)] +pub(super) enum TitleEvent { + /// The window opens with `AppSpec`'s title. + Start(String), + /// A handler set `title`. + Set(String), + /// The window showed the title it was given. + Shown, +} + +impl Title { + /// The title the window opens with, before any handler sets one. + pub(crate) fn start(&mut self, title: &str) { + *self = std::mem::take(self).step(TitleEvent::Start(title.to_owned())).0; + } + + pub(super) fn set(&mut self, title: String) { + *self = std::mem::take(self).step(TitleEvent::Set(title)).0; + } + + pub(crate) fn current(&self) -> Option<&str> { + match self { + Title::Unset => None, + Title::Shown(title) | Title::Pending(title) => Some(title), + } + } + + /// A title set since the window last took one, for the window to show. + pub(crate) fn take_change(&mut self) -> Option<&str> { + let (title, showed) = std::mem::take(self).step(TitleEvent::Shown); + *self = title; + showed.then(|| self.current()).flatten() + } + + /// The title after `event`, and whether the window shows something new. + fn step(self, event: TitleEvent) -> (Title, bool) { + match (self, event) { + (Title::Unset, TitleEvent::Start(title)) => (Title::Shown(title), false), + (title, TitleEvent::Start(_)) => (title, false), + (title, TitleEvent::Set(next)) if title.current() == Some(next.as_str()) => (title, false), + (_, TitleEvent::Set(title)) => (Title::Pending(title), false), + (Title::Pending(title), TitleEvent::Shown) => (Title::Shown(title), true), + (title, TitleEvent::Shown) => (title, false), + } + } +} + +/// A window that fits its content (`App::fit_content_height`): the height it last asked the +/// window for, and the frame its move starts with. +#[derive(Debug, Default)] +pub(crate) struct FitWindow { + /// None until it asks, and again once someone else resizes the window. + asked: Option<f32>, + hold: FitHold, +} + +/// A fitting window at rest asked to move. The window can't move until the next frame, so the +/// frame that asked shows the commit's motion at its start, and the host starts the window's +/// own move from that frame: both then start moving on the same frame. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +enum FitHold { + #[default] + None, + /// A commit asked; the frame's motion step holds. + Asked, + /// The last frame held, for the host to start the window's move from. + Held, +} + +impl FitWindow { + /// Whether the window should be asked for `height`: it isn't already asked for it, nor + /// (asked for nothing since it was last resized) already `current` tall. + fn ask(&mut self, height: f32, current: f32) -> bool { + if self.asked.unwrap_or(current) == height { return false; } + self.asked = Some(height); + true + } + + /// The window was resized to `height` from outside: forgets what it asked, so the next + /// commit asks for the content's height again. True when that differs from what it asked + /// (or, never asked, from `current`). + fn resized(&mut self, height: f32, current: f32) -> bool { + if (self.asked.unwrap_or(current) - height).abs() <= 0.5 { return false; } + self.asked = None; + true + } + + /// The frame steps its motion: whether a commit asked it to hold. + fn frame_holds(&mut self) -> bool { + self.hold = if self.hold == FitHold::Asked { FitHold::Held } else { FitHold::None }; + self.hold == FitHold::Held + } + + /// Whether the last frame held its motion for the window, for the host starting the + /// window's move. The hold ends with it. + pub(crate) fn take_held(&mut self) -> bool { + std::mem::take(&mut self.hold) == FitHold::Held + } +} + +impl RuntimeCore { + /// Asks the window for the content's new height, on this commit's spring. The first + /// commit, a viewport change and `Tx::instant` jump. + #[inline] + pub(super) fn fit_window(&mut self, height: f32, tx: &Tx, first: bool) { + self.host.fit_window(height, self.viewport, self.env.scale, self.reduced_motion, self.wall_start.is_none(), tx, first); + } + + /// The root's natural height at the current width, in window points (the view's times its + /// zoom), measured without committing, so a window that fits its content can open at that + /// height. + pub(crate) fn content_height(&mut self, app: &dyn ViewDriver) -> f32 { + let measured = self.measure_pass(app, &Tx::default(), false); + let height = measured.nodes.first().map_or(self.viewport.1, |root| root.local.h); + self.discard_measured(measured); + self.host.content_height_from(height) + } + + /// Someone resized a window that fits its content (not a page's band) to `height`: it + /// goes back to the content's height. + #[inline] + pub(super) fn fit_resized(&mut self, height: f32) -> bool { + self.host.fit_resized(height, self.viewport.1) + } + + /// Whether this frame holds its motion for the window (see [`FitHold`]). + #[inline] + pub(super) fn fit_frame_holds(&mut self) -> bool { + self.host.fit_frame_holds() + } +} + +#[cfg(test)] +#[path = "window_requests_tests.rs"] +mod tests; diff --git a/app/vendor/rune/crates/rune/src/runtime/window_requests_tests.rs b/app/vendor/rune/crates/rune/src/runtime/window_requests_tests.rs new file mode 100644 index 0000000..068026c --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/window_requests_tests.rs @@ -0,0 +1,35 @@ +use super::*; + +#[test] +fn a_fitting_window_asks_once_per_height() { + let mut fit = FitWindow::default(); + assert!(!fit.ask(300.0, 300.0), "never asked, and already that tall"); + assert!(fit.ask(420.0, 300.0)); + assert!(!fit.ask(420.0, 300.0), "asked already, though the window hasn't moved yet"); + assert!(fit.ask(300.0, 360.0)); +} + +#[test] +fn a_resize_from_outside_forgets_what_it_asked() { + let mut fit = FitWindow::default(); + assert!(fit.ask(420.0, 300.0)); + assert!(!fit.resized(420.3, 300.0), "the window reached what it asked, within half a point"); + assert!(fit.resized(500.0, 420.0)); + assert!(fit.ask(420.0, 500.0), "the next commit asks for the content's height again"); + assert!(!FitWindow::default().resized(300.0, 300.0), "never asked: only a change of height counts"); +} + +#[test] +fn a_hold_lasts_the_frame_that_asked_and_ends_when_the_host_takes_it() { + let mut fit = FitWindow::default(); + assert!(!fit.frame_holds() && !fit.take_held(), "nothing asked"); + fit.hold = FitHold::Asked; + assert!(fit.frame_holds()); + assert!(fit.take_held()); + assert!(!fit.take_held(), "taken once"); + // A host that doesn't take it: the next frame doesn't hold, and neither is it reported. + fit.hold = FitHold::Asked; + assert!(fit.frame_holds()); + assert!(!fit.frame_holds()); + assert!(!fit.take_held()); +} diff --git a/app/vendor/rune/crates/rune/src/runtime/zoom.rs b/app/vendor/rune/crates/rune/src/runtime/zoom.rs new file mode 100644 index 0000000..437b60e --- /dev/null +++ b/app/vendor/rune/crates/rune/src/runtime/zoom.rs @@ -0,0 +1,121 @@ +//! The view's UI zoom (`Cx::zoom`), applied as a browser applies page zoom: as part of the device +//! scale. The view lays out in the window's points over the zoom, at the window's scale times +//! the zoom, so every border, icon, glyph and pixel snap lands on the device grid as it does +//! unzoomed, and everything that moves (flights, morphs, presences, springs) moves in the one +//! zoomed space the layout is in. Chromium does the same (zoom for DSF): a 1px border at 125% +//! on a 1.5x display is one device pixel, not 1.875 of them. +//! +//! The host speaks window points: [`Runtime::set_viewport`] takes the window's size and scale, +//! and what the runtime hands back for the window (the IME area, menus at a point, a fitted +//! height, chrome insets) is in window points. Pointer, wheel and touch input arrive in view +//! points: the host converts device pixels with [`Runtime::input_scale`]. + +use super::*; + +/// The zoom and the window it applies to. +#[derive(Clone, Copy, Debug)] +pub(crate) struct Zoom { + /// The view's zoom, 1 unzoomed. + pub(crate) k: f32, + /// The window's viewport in its own points, and its scale (device pixels per point). + pub(crate) window: (f32, f32), + pub(crate) window_scale: f32, +} + +impl Default for Zoom { + fn default() -> Self { + Self { k: 1.0, window: (0.0, 0.0), window_scale: 1.0 } + } +} + +impl Zoom { + /// The view's viewport and scale for the window's. + pub(crate) fn view(&self) -> ((f32, f32), f32) { + ((self.window.0 / self.k, self.window.1 / self.k), self.window_scale * self.k) + } +} + +/// A zoom the view may ask for: finite, and within what a page zoom allows. +pub(crate) fn clamp(k: f32) -> f32 { + if k.is_finite() { k.clamp(0.1, 10.0) } else { 1.0 } +} + +impl window_requests::HostState { + /// The view's UI zoom ([`Cx::zoom`]), 1 unzoomed. + #[inline] + pub(crate) fn zoom(&self) -> f32 { + self.zoom.k + } + + /// The window's viewport in its own points, as the host last set it. + #[inline] + pub(crate) fn window_viewport(&self) -> (f32, f32) { + self.zoom.window + } + + /// The window's scale (device pixels per window point), as the host last set it. + #[inline] + pub(crate) fn window_scale(&self) -> f32 { + self.zoom.window_scale + } + + /// A rect in view points as window points, for what the host places by the window: the IME + /// area, a menu, a drag image. + #[inline] + pub(crate) fn to_window(&self, r: [f32; 4]) -> [f32; 4] { + r.map(|v| v * self.zoom.k) + } + + /// Updates the UI zoom to clamped `k`, returning the resulting `(viewport, scale)` when it changed. + #[inline] + pub(super) fn set_zoom(&mut self, k: f32) -> Option<((f32, f32), f32)> { + let k = clamp(k); + if k == self.zoom.k { return None; } + self.zoom.k = k; + Some(self.zoom.view()) + } +} + +impl RuntimeCore { + /// The view's UI zoom ([`Cx::zoom`]), 1 unzoomed. + #[inline] + pub fn zoom(&self) -> f32 { + self.host.zoom() + } + + /// The window's viewport in its own points, as the host last set it. + #[inline] + pub fn window_viewport(&self) -> (f32, f32) { + self.host.window_viewport() + } + + /// The window's scale (device pixels per window point), as the host last set it. + #[inline] + pub fn window_scale(&self) -> f32 { + self.host.window_scale() + } + + /// Device pixels per view point: what a host divides a pointer's or touch's pixels by to + /// hand them to the runtime. The window's scale times the zoom. + #[inline] + pub fn input_scale(&self) -> f32 { + self.env.scale + } + + /// A rect in view points as window points, for what the host places by the window: the IME + /// area, a menu, a drag image. + #[inline] + pub fn to_window(&self, r: [f32; 4]) -> [f32; 4] { + self.host.to_window(r) + } + + /// The zoom the last view asked for: the viewport and scale follow it. False when it was + /// already the zoom. + pub(super) fn apply_zoom(&mut self, k: f32) -> bool { + let Some((viewport, scale)) = self.host.set_zoom(k) else { return false }; + self.change_viewport(viewport, scale); + // The window's controls and the caption buttons it draws are in window points. + self.commit.dirty = true; + true + } +} diff --git a/app/vendor/rune/crates/rune/src/shaders/backdrop_blur.wgsl b/app/vendor/rune/crates/rune/src/shaders/backdrop_blur.wgsl new file mode 100644 index 0000000..285574c --- /dev/null +++ b/app/vendor/rune/crates/rune/src/shaders/backdrop_blur.wgsl @@ -0,0 +1,71 @@ +// Backdrop blur pyramid (dual filter): a 13-tap downsample chain (Jimenez) from the backdrop +// copy at half resolution, over the region being blurred (`u.map` places level 0 in the copy), +// then a 9-tap tent upsample chain back to half resolution. The level the up chain starts from +// sets the blur width; `u.w.x` crossfades it with the next finer level so the width is +// continuous. Every tap is clamped to the copied region, so texels outside it never leak in and +// edges repeat instead of darkening. +@group(0) @binding(0) var src: texture_2d<f32>; +@group(0) @binding(1) var fine: texture_2d<f32>; +@group(0) @binding(2) var smp: sampler; + +struct Level { + // x: share of the coarser level in an up pass. + w: vec4<f32>, + // The region's bounds in the source's uv: min xy, max xy. + region: vec4<f32>, + // Source uv from target uv: uv * xy + zw. + map: vec4<f32>, + place: vec4<f32>, +}; +@group(0) @binding(3) var<uniform> u: Level; + +struct V { + @builtin(position) pos: vec4<f32>, + @location(0) uv: vec2<f32>, +}; + +@vertex +fn vs(@builtin(vertex_index) vi: u32) -> V { + let p = vec2<f32>(f32((vi << 1u) & 2u), f32(vi & 2u)); + var o: V; + o.pos = vec4<f32>(p * 2.0 - 1.0, 0.0, 1.0); + o.uv = vec2<f32>(p.x, 1.0 - p.y); + return o; +} + +fn s(uv: vec2<f32>) -> vec4<f32> { + return textureSampleLevel(src, smp, clamp(uv, u.region.xy, u.region.zw), 0.0); +} + +@fragment +fn fs_down(in: V) -> @location(0) vec4<f32> { + let t = 1.0 / vec2<f32>(textureDimensions(src, 0)); + let uv = in.uv * u.map.xy + u.map.zw; + let a = s(uv + t * vec2<f32>(-2.0, -2.0)); + let b = s(uv + t * vec2<f32>(0.0, -2.0)); + let c = s(uv + t * vec2<f32>(2.0, -2.0)); + let d = s(uv + t * vec2<f32>(-1.0, -1.0)); + let e = s(uv + t * vec2<f32>(1.0, -1.0)); + let f = s(uv + t * vec2<f32>(-2.0, 0.0)); + let g = s(uv); + let h = s(uv + t * vec2<f32>(2.0, 0.0)); + let i = s(uv + t * vec2<f32>(-1.0, 1.0)); + let j = s(uv + t * vec2<f32>(1.0, 1.0)); + let k = s(uv + t * vec2<f32>(-2.0, 2.0)); + let l = s(uv + t * vec2<f32>(0.0, 2.0)); + let m = s(uv + t * vec2<f32>(2.0, 2.0)); + return (d + e + i + j) * 0.125 + (a + b + g + f) * 0.03125 + (b + c + h + g) * 0.03125 + + (f + g + l + k) * 0.03125 + (g + h + m + l) * 0.03125; +} + +@fragment +fn fs_up(in: V) -> @location(0) vec4<f32> { + let t = 1.0 / vec2<f32>(textureDimensions(src, 0)); + let uv = in.uv * u.map.xy + u.map.zw; + var c = s(uv) * 4.0; + c += (s(uv + vec2<f32>(t.x, 0.0)) + s(uv - vec2<f32>(t.x, 0.0)) + s(uv + vec2<f32>(0.0, t.y)) + s(uv - vec2<f32>(0.0, t.y))) * 2.0; + c += s(uv + t) + s(uv - t) + s(uv + vec2<f32>(t.x, -t.y)) + s(uv + vec2<f32>(-t.x, t.y)); + c /= 16.0; + let f = textureSampleLevel(fine, smp, clamp(uv, u.region.xy, u.region.zw), 0.0); + return mix(f, c, u.w.x); +} diff --git a/app/vendor/rune/crates/rune/src/shaders/backdrop_composite.wgsl b/app/vendor/rune/crates/rune/src/shaders/backdrop_composite.wgsl new file mode 100644 index 0000000..397df15 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/shaders/backdrop_composite.wgsl @@ -0,0 +1,71 @@ +// Draws a blurred backdrop (`backdrop_blur.wgsl`'s half-resolution result) inside a backdrop +// blur record's rounded rect, cut by its clip, at its opacity (`fill.a`). Group 0 is the uber +// shader's, so the record lands in whichever target (frame or isolated layer) is being drawn. +// Prepended with `clip.wgsl`. + +struct Globals { + viewport: vec2<f32>, + pad: vec2<f32>, + flags: vec4<f32>, +}; + +@group(0) @binding(0) var<uniform> g: Globals; +@group(0) @binding(3) var<uniform> projection: vec4<f32>; +@group(1) @binding(0) var blurred: texture_2d<f32>; +@group(1) @binding(1) var smp: sampler; + +struct Level { + w: vec4<f32>, + region: vec4<f32>, + map: vec4<f32>, + // The pyramid's window origin xy and extent zw, in device pixels. + place: vec4<f32>, +}; +@group(1) @binding(2) var<uniform> u: Level; + +struct In { + @builtin(vertex_index) vi: u32, + @location(0) rect: vec4<f32>, + @location(1) radii: vec4<f32>, + @location(2) fill: vec4<f32>, + @location(6) clip: vec4<f32>, + @location(7) fade: vec4<u32>, +}; + +struct Out { + @builtin(position) pos: vec4<f32>, + @location(0) @interpolate(flat) rect: vec4<f32>, + @location(1) @interpolate(flat) radii: vec4<f32>, + @location(2) @interpolate(flat) alpha: f32, + @location(3) @interpolate(flat) clip: vec4<f32>, + @location(4) @interpolate(flat) fade: vec4<u32>, +}; + +@vertex +fn vs(i: In) -> Out { + let corner = vec2<f32>(f32(i.vi & 1u), f32(i.vi >> 1u)); + let p = i.rect.xy - vec2<f32>(1.0) + corner * (i.rect.zw + vec2<f32>(2.0)); + let size_px = select(g.viewport, projection.zw, projection.z > 0.0); + let local = p - projection.xy; + var o: Out; + o.pos = vec4<f32>(local.x / size_px.x * 2.0 - 1.0, 1.0 - local.y / size_px.y * 2.0, 0.0, 1.0); + o.rect = i.rect; + o.radii = i.radii; + o.alpha = i.fill.a; + o.clip = i.clip; + o.fade = i.fade; + return o; +} + +@fragment +fn fs(i: Out) -> @location(0) vec4<f32> { + // Fragment position is the rasterizer's exact pixel centre; interpolated quad coordinates + // drift by subpixel ULPs on D3D12, leaving top/left edge coverage below 1.0 in Rgba16Float + // layers and shifting blur pyramid sample UVs. + let screen = i.pos.xy + projection.xy; + let half = i.rect.zw * 0.5; + let d = sd_rounded(screen - (i.rect.xy + half), half, i.radii); + let cov = clamp(0.5 - d, 0.0, 1.0) * clip_alpha_stops(screen, i.clip, i.fade, g.flags.zw) * i.alpha; + let col = textureSampleLevel(blurred, smp, (screen - u.place.xy) / u.place.zw, 0.0); + return col * cov; +} diff --git a/app/vendor/rune/crates/rune/src/shaders/clip.wgsl b/app/vendor/rune/crates/rune/src/shaders/clip.wgsl new file mode 100644 index 0000000..6fc7288 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/shaders/clip.wgsl @@ -0,0 +1,167 @@ +// Shared clip maths: the uber shader and compositor shaders (`rune::render::CLIP_WGSL`) use these. +// `clip_alpha(p, clip, fade)` takes a window device-pixel position, an instance's `clip` and its +// `fade` words (`vec4<u32>`), and returns the coverage of its rectangular, soft-edged and rounded +// (circular or continuous) clip. + +// Apple's continuous corner of radius r: its curve leaves each edge K·r from the corner, and +// from the point (K·r, K·r) inside the corner it lies K·r·g(u) away, u running -1..1 across +// the quarter turn (0 on the diagonal; within 0.32% of r). Each quadrant takes its own +// corner's whole curve, as Core Animation does when K·r passes half the shorter side. +const CONTINUOUS_K: f32 = 1.52866483; +fn sd_continuous(p: vec2<f32>, half: vec2<f32>, r: f32) -> f32 { + let e = CONTINUOUS_K * r; + let q = half - abs(p); + let v = vec2<f32>(e) - q; + if (v.x <= 0.0 || v.y <= 0.0) { return max(-q.x, -q.y); } + let u = atan2(v.y, v.x) * (4.0 / 3.14159265) - 1.0; + let u2 = u * u; + return length(v) - e * (1.14602295 + u2 * (-0.37573161 + u2 * (0.30796609 - 0.07724354 * u2))); +} + +fn sd_rounded(p: vec2<f32>, half: vec2<f32>, radii: vec4<f32>) -> f32 { + // radii: top-left, top-right, bottom-right, bottom-left (y down). Negative is continuous. + var r = radii.x; + if (p.x > 0.0) { + r = select(radii.y, radii.z, p.y > 0.0); + } else { + r = select(radii.x, radii.w, p.y > 0.0); + } + if (r < 0.0) { return sd_continuous(p, half, min(-r, min(half.x, half.y))); } + r = min(r, min(half.x, half.y)); + let q = abs(p) - half + vec2<f32>(r); + return min(max(q.x, q.y), 0.0) + length(max(q, vec2<f32>(0.0))) - r; +} + +// A soft edge's coverage `d` in from it: smoothstep over `fade`, linear over `-fade` when it's +// negative (`El::clip_fade_linear`), and a hard, anti-aliased edge at zero. +fn ramp(d: f32, fade: f32) -> f32 { + if (fade == 0.0) { + return clamp(d + 0.5, 0.0, 1.0); + } + let x = clamp(d / abs(fade), 0.0, 1.0); + if (fade < 0.0) { + return x; + } + return x * x * (3.0 - 2.0 * x); +} + +// Piecewise-linear soft edge through up to three interior `(t, alpha)` stops already unpacked +// into `ts` and `ys`, anchored at `(0, 0)` and `(1, 1)` (`ScrollFade::stops`). +fn ramp_stops(d: f32, fade: f32, ts: vec4<f32>, ys: vec4<f32>) -> f32 { + if (fade == 0.0) { + return clamp(d + 0.5, 0.0, 1.0); + } + let w = abs(fade); + if (d >= w) { + return 1.0; + } + if (d <= 0.0) { + return 0.0; + } + let x = d / w; + var px = 0.0; + var py = 0.0; + for (var k = 0u; k < 4u; k++) { + let nx = ts[k]; + let ny = ys[k]; + if (x <= nx) { + let span = nx - px; + if (span > 1e-6) { + return mix(py, ny, (x - px) / span); + } + return ny; + } + px = nx; + py = ny; + } + return 1.0; +} + +fn unpack_clip_radii(w: u32) -> vec4<f32> { + if (w == 0u) { return vec4<f32>(0.0); } + if ((w & 0x60000000u) != 0x60000000u) { + return vec4<f32>(bitcast<f32>(w)); + } + let step = select(0.5, 2.0, (w & 0x10000000u) != 0u); + let sgn = select(1.0, -1.0, (w & 0x80000000u) != 0u); + return vec4<f32>( + f32(w & 0x7fu), + f32((w >> 7u) & 0x7fu), + f32((w >> 14u) & 0x7fu), + f32((w >> 21u) & 0x7fu), + ) * (step * sgn); +} + +fn clip_alpha_stops(p: vec2<f32>, c: vec4<f32>, packed: vec4<u32>, stops: vec2<f32>) -> f32 { + let f = vec4<f32>(unpack2x16float(packed.x), unpack2x16float(packed.y)); + let hard = vec4<f32>(p - c.xy, c.zw - p); + var alpha = 1.0; + // `packed.z` is `@interpolate(flat)`, so these branches are uniform across every pixel of an + // instance: instances without stop-tagged edges never unpack `stops` or run `ramp_stops`. + if (packed.z == 0u) { + alpha = ramp(hard.x, f.x) * ramp(hard.y, f.y) * ramp(hard.z, f.z) * ramp(hard.w, f.w); + } else if ((packed.z & 0x80808080u) == 0u) { + for (var edge = 0u; edge < 4u; edge++) { + let off_u = (packed.z >> (edge * 8u)) & 0x7Fu; + var a: f32; + if (off_u >= 127u) { + a = ramp(hard[edge], 0.0); + } else if (off_u > 0u) { + let offset = f32(off_u) * (1.0 / 127.0); + a = min(ramp(hard[edge], 0.0), ramp(hard[edge] + offset * abs(f[edge]), f[edge])); + } else { + a = ramp(hard[edge], f[edge]); + } + alpha *= a; + } + } else { + // Unpack the three interior `(t, alpha)` stops once outside the edge loop (`1/200` quantization). + let lo = u32(stops.x + 0.5); + let hi = u32(stops.y + 0.5); + let ts = vec4<f32>( + f32(lo & 0xFFu), + f32((lo >> 16u) & 0xFFu), + f32((hi >> 8u) & 0xFFu), + 200.0, + ) * (1.0 / 200.0); + let ys = vec4<f32>( + f32((lo >> 8u) & 0xFFu), + f32(hi & 0xFFu), + f32((hi >> 16u) & 0xFFu), + 200.0, + ) * (1.0 / 200.0); + for (var edge = 0u; edge < 4u; edge++) { + let raw_off = (packed.z >> (edge * 8u)) & 0xFFu; + let is_stops = (raw_off & 0x80u) != 0u; + let off_u = raw_off & 0x7Fu; + // Keep the original sub-pixel ramp exactly when its origin is the hard edge. + var a: f32; + if (off_u >= 127u) { + a = ramp(hard[edge], 0.0); + } else if (off_u > 0u) { + let shifted = hard[edge] + (f32(off_u) * (1.0 / 127.0)) * abs(f[edge]); + var r: f32; + if (is_stops) { + r = ramp_stops(shifted, f[edge], ts, ys); + } else { + r = ramp(shifted, f[edge]); + } + a = min(ramp(hard[edge], 0.0), r); + } else if (is_stops) { + a = ramp_stops(hard[edge], f[edge], ts, ys); + } else { + a = ramp(hard[edge], f[edge]); + } + alpha *= a; + } + } + if packed.w != 0u { + let half = (c.zw - c.xy) * 0.5; + alpha *= clamp(0.5 - sd_rounded(p - c.xy - half, half, unpack_clip_radii(packed.w)), 0.0, 1.0); + } + return alpha; +} + +fn clip_alpha(p: vec2<f32>, c: vec4<f32>, packed: vec4<u32>) -> f32 { + return clip_alpha_stops(p, c, packed, vec2<f32>(0.0)); +} diff --git a/app/vendor/rune/crates/rune/src/shaders/layer_blur.wgsl b/app/vendor/rune/crates/rune/src/shaders/layer_blur.wgsl new file mode 100644 index 0000000..5089ffe --- /dev/null +++ b/app/vendor/rune/crates/rune/src/shaders/layer_blur.wgsl @@ -0,0 +1,67 @@ +struct Uniforms { + config: vec4<f32>, + mapping: vec4<f32>, + taps: array<vec4<f32>, 128>, +}; +@group(0) @binding(0) var source: texture_2d<f32>; +@group(0) @binding(1) var linear: sampler; +@group(0) @binding(2) var<uniform> u: Uniforms; +override MODE: u32 = 0; +override ADDITIVE: bool = false; + +@vertex +fn vs(@builtin(vertex_index) v: u32) -> @builtin(position) vec4<f32> { + return vec4<f32>(f32((v << 1u) & 2u) * 2.0 - 1.0, f32(v & 2u) * 2.0 - 1.0, 0.0, 1.0); +} + +fn sample_zero(p: vec2<f32>) -> vec4<f32> { + if (ADDITIVE) { + // Plus-lighter saturates each source texel BEFORE interpolation or convolution. + let q = p - 0.5; + let base = vec2<i32>(floor(q)); + let fraction = fract(q); + let a = bounded_load(base); + let b = bounded_load(base + vec2(1, 0)); + let c = bounded_load(base + vec2(0, 1)); + let d = bounded_load(base + vec2(1, 1)); + return mix(mix(a, b, fraction.x), mix(c, d, fraction.x), fraction.y); + } + // Explicit transparent border, independent of bucket padding. Clamping the sample to the + // used texel centres then attenuating the edge implements bilinear zero extension exactly. + let edge = clamp(p + 0.5, vec2(0.0), vec2(1.0)) * clamp(u.config.xy + 0.5 - p, vec2(0.0), vec2(1.0)); + let uv = clamp(p, vec2(0.5), u.config.xy - 0.5) / vec2<f32>(textureDimensions(source)); + return textureSampleLevel(source, linear, uv, 0.0) * edge.x * edge.y; +} + +fn bounded_load(p: vec2<i32>) -> vec4<f32> { + if (any(p < vec2(0)) || any(p >= vec2<i32>(u.config.xy))) { return vec4(0.0); } + let color = textureLoad(source, p, 0); + return select(color, clamp(color, vec4(0.0), vec4(1.0)), ADDITIVE); +} + +@fragment +fn fs(@builtin(position) p: vec4<f32>) -> @location(0) vec4<f32> { + if (MODE == 2u) { + // Exact area prefilter for fractional reductions: no missed pixels or phase-dependent + // brightness as the continuously animated sigma changes the intermediate dimensions. + let lo = (p.xy - 0.5) * u.mapping.xy; + let hi = (p.xy + 0.5) * u.mapping.xy; + var sum = vec4(0.0); + for (var y = i32(floor(lo.y)); y < i32(ceil(hi.y)); y++) { + let wy = max(0.0, min(hi.y, f32(y + 1)) - max(lo.y, f32(y))); + for (var x = i32(floor(lo.x)); x < i32(ceil(hi.x)); x++) { + let wx = max(0.0, min(hi.x, f32(x + 1)) - max(lo.x, f32(x))); + sum += bounded_load(vec2(x, y)) * wx * wy; + } + } + return sum / (u.mapping.x * u.mapping.y); + } + if (MODE == 3u) { return sample_zero(p.xy * u.mapping.xy); } + let axis = select(vec2(1.0, 0.0), vec2(0.0, 1.0), u.config.z > 0.5); + var color = sample_zero(p.xy) * u.taps[0].y; + for (var tap = 1u; tap < u32(u.config.w); tap++) { + let offset = axis * u.taps[tap].x; + color += (sample_zero(p.xy + offset) + sample_zero(p.xy - offset)) * u.taps[tap].y; + } + return color; +} diff --git a/app/vendor/rune/crates/rune/src/shaders/outline.wgsl b/app/vendor/rune/crates/rune/src/shaders/outline.wgsl new file mode 100644 index 0000000..987d1eb --- /dev/null +++ b/app/vendor/rune/crates/rune/src/shaders/outline.wgsl @@ -0,0 +1,313 @@ +// The Windfoil variant of the uber shader (render/variant.rs): shader.wgsl with glyphs that +// draw from their outlines (`text::Outline`, `radii.w > 0`) as well as from the atlas. + +// Glyph outlines (text/outline.rs): banded records of xy-monotone quadratics in font units. +@group(0) @binding(4) var outlines: texture_2d<u32>; + +// Glyph coverage from outlines: Windfoil's closed-form box filter (DesLauriers 2026; the +// integrals are texel-org/windfoil-algorithm's, Apache-2.0) over a record's pieces, each moved +// by CoreGraphics' dilation and y autohint first (text/outline/build.rs has the record layout). + +fn outline_texel(i: u32) -> vec4<u32> { + return textureLoad(outlines, vec2<i32>(i32(i & 1023u), i32(i >> 10u)), 0); +} + +// The move of a piece's code in radii: x in -1..1, y in 0..2. +fn outline_move(code: u32) -> vec2<f32> { + return vec2<f32>(f32(code & 3u) - 1.0, f32((code >> 2u) & 3u)); +} + +// CoreGraphics' y autohint (`HintTransform::apply`): values [-d, lo, x, xt] [middle, mt, cap, ct] +// [s1, s2, s3]. +fn outline_hint(y: f32, a: vec4<f32>, b: vec4<f32>, c: vec4<f32>) -> f32 { + if (y < a.y) { return y; } + if (y <= a.z) { return (y - a.y) * c.x + a.y; } + if (y <= b.x) { return (y - a.z) * c.y + a.w; } + if (y <= b.z) { return y + (b.y - b.x); } + return (y - b.z) * c.z + b.w; +} + +fn outline_inside(a2: vec2<f32>, a1: vec2<f32>, x0: f32, ta: f32, tb: f32, hx: f32) -> f32 { + if (tb <= ta) { return 0.0; } + let tm = 0.5 * (ta + tb); + let d = 0.5 * (tb - ta); + let x_mid = (a2.x * tm + a1.x) * tm + x0 + hx; + let dmid = 2.0 * a2 * tm + a1; + return 2.0 * d * x_mid * dmid.y + (2.0 * d * d * d / 3.0) * (a2.x * dmid.y + 2.0 * a2.y * dmid.x); +} + +// The box-filtered winding of one monotone piece (relative to the pixel centre) between rows +// `lo` and `hi`, `2 * hx` wide. +fn outline_integrate(q1: vec2<f32>, q2: vec2<f32>, q3: vec2<f32>, lo: f32, hi: f32, hx: f32) -> f32 { + let a2 = q1 - 2.0 * q2 + q3; + let a1 = 2.0 * (q2 - q1); + let y_rising = q3.y >= q1.y; + let x_rising = q3.x >= q1.x; + let A2 = a2.yyxx; + let A1 = a1.yyxx; + let V = vec4<f32>(select(vec2<f32>(hi, lo), vec2<f32>(lo, hi), y_rising), -hx, hx); + let R = vec2<bool>(y_rising, x_rising).xxyy; + let SG = select(vec4<f32>(-1.0), vec4<f32>(1.0), R); + let C = q1.yyxx - V; + let sat0 = (C * SG) >= vec4<f32>(0.0); + let sat1 = ((q3.yyxx - V) * SG) <= vec4<f32>(0.0); + let disc = max(A1 * A1 - 4.0 * A2 * C, vec4<f32>(0.0)); + let sq = sqrt(disc); + let qq = -0.5 * (A1 + select(-sq, sq, A1 >= vec4<f32>(0.0))); + let use_r1 = (A1 < vec4<f32>(0.0)) == R; + let num = select(C, qq, use_r1); + let den = select(qq, A2, use_r1); + let valid = den != vec4<f32>(0.0); + let t_raw = clamp(select(vec4<f32>(0.0), num / select(vec4<f32>(1.0), den, valid), valid), vec4<f32>(0.0), vec4<f32>(1.0)); + let T = select(select(t_raw, vec4<f32>(1.0), sat1), vec4<f32>(0.0), sat0); + if (T.y <= T.x) { return 0.0; } + let tc = clamp(T.zw, T.xx, T.yy); + let t1 = select(tc.y, tc.x, x_rising); + let t2 = max(select(tc.x, tc.y, x_rising), t1); + var acc = outline_inside(a2, a1, q1.x, t1, t2, hx); + let rab = select(vec2<f32>(T.x, t1), vec2<f32>(t2, T.y), x_rising); + let d = max(rab.y - rab.x, 0.0); + let tm = 0.5 * (rab.x + rab.y); + acc = acc + d * (2.0 * a2.y * tm + a1.y) * (2.0 * hx); + return acc; +} + +// How much of a box `2 * hx` wide and `2 * hw` tall (rest px) at `local` (rest px from the pen, +// y up) the glyph of record `rec` covers, `scale` rest px a font unit, dilated by `r` rest px and +// hinted by record `hint` (0: none). A pixel is `hx == hw`; a subpixel a third as wide. +fn outline_coverage(rec: u32, hint: u32, local: vec2<f32>, scale: f32, r: f32, hw: f32, hx: f32) -> f32 { + let head = outline_texel(rec); + let count = head.y; + let y0 = bitcast<f32>(head.z); + let inv_h = bitcast<f32>(head.w); + let hinted = hint != 0u; + var ha = vec4<f32>(0.0); + var hb = vec4<f32>(0.0); + var hc = vec4<f32>(0.0); + if (hinted) { + ha = bitcast<vec4<f32>>(outline_texel(hint)); + hb = bitcast<vec4<f32>>(outline_texel(hint + 1u)); + hc = bitcast<vec4<f32>>(outline_texel(hint + 2u)); + } + // Pieces from as far as 2r below move up into this row; the hint moves them up to its reach. + let reach = select(0.0, OUTLINE_HINT_REACH, hinted); + var b0 = 0u; + var b1 = 0u; + if (count > 1u) { + let last = f32(count - 1u); + b0 = u32(clamp(floor(((local.y - hw - 2.0 * r - reach) / scale - y0) * inv_h), 0.0, last)); + b1 = u32(clamp(floor(((local.y + hw + reach) / scale - y0) * inv_h), 0.0, last)); + } + var acc = 0.0; + for (var band = b0; band <= b1; band = band + 1u) { + // A piece counts within its band's rows, moved as it moves; a connector lies in one band. + var e0 = -3.0e38; + var e1 = 3.0e38; + if (count > 1u) { + e0 = (y0 + f32(band) / inv_h) * scale; + e1 = (y0 + f32(band + 1u) / inv_h) * scale; + } + let entry = outline_texel(head.x + band); + let sorted = entry.y > 4u; + for (var k = 0u; k < entry.y; k = k + 1u) { + let t0 = outline_texel(entry.x + 2u * k); + let t1 = outline_texel(entry.x + 2u * k + 1u); + // Sorted by right edge: once one sits left of the pixel, all the rest do. + if (bitcast<f32>(t1.w) * scale + r - local.x <= -hx) { + if (sorted) { break; } + continue; + } + let code = t1.z; + let oa = outline_move(code & 15u) * r; + let ob = outline_move((code >> 4u) & 15u) * r; + var p0 = bitcast<vec2<f32>>(t0.xy) * scale + oa; + var p1 = bitcast<vec2<f32>>(t0.zw) * scale + oa; + var p2 = bitcast<vec2<f32>>(t1.xy) * scale + ob; + var wlo = -hw; + var whi = hw; + var be0 = e0 + oa.y; + var be1 = e1 + oa.y; + if (hinted) { + p0.y = outline_hint(p0.y, ha, hb, hc); + p1.y = outline_hint(p1.y, ha, hb, hc); + p2.y = outline_hint(p2.y, ha, hb, hc); + be0 = outline_hint(be0, ha, hb, hc); + be1 = outline_hint(be1, ha, hb, hc); + } + if ((code & 256u) != 0u) { + p1 = (p0 + p2) * 0.5; + } else { + wlo = max(wlo, be0 - local.y); + whi = min(whi, be1 - local.y); + } + let q1 = p0 - local; + let q3 = p2 - local; + let lo = max(wlo, min(q1.y, q3.y)); + let hi = min(whi, max(q1.y, q3.y)); + if (hi <= lo || max(q1.x, q3.x) <= -hx) { continue; } + if (min(q1.x, q3.x) >= hx) { + acc = acc + 2.0 * hx * (clamp(q3.y, wlo, whi) - clamp(q1.y, wlo, whi)); + continue; + } + acc = acc + outline_integrate(q1, p1 - local, q3, lo, hi, hx); + } + } + return min(abs(acc) / (4.0 * hx * hw), 1.0); +} + +const OUTLINE_HINT_REACH: f32 = 1.5; + +// Where along monotone quadratic `p0 p1 p2`'s axis `a` (0: x, 1: y) it reaches `c`, from 0 to 1. +fn outline_root(p0: f32, p1: f32, p2: f32, c: f32) -> f32 { + let a2 = p0 - 2.0 * p1 + p2; + let a1 = 2.0 * (p1 - p0); + let a0 = p0 - c; + if (abs(a2) < 1.0e-6) { + return clamp(-a0 / select(a1, 1.0e-6, abs(a1) < 1.0e-6), 0.0, 1.0); + } + let sq = sqrt(max(a1 * a1 - 4.0 * a2 * a0, 0.0)); + let t0 = (-a1 - sq) / (2.0 * a2); + let t1 = (-a1 + sq) / (2.0 * a2); + return clamp(select(t1, t0, t0 >= -1.0e-4 && t0 <= 1.0 + 1.0e-4), 0.0, 1.0); +} + +// Slug's coverage (Lengyel 2017): the winding along a horizontal and a vertical ray through the +// pixel's centre, each crossing spread over the pixel's width, the two averaged. Same record, +// moves and hint as `outline_coverage`. The vertical ray is the centre's winding (from the +// horizontal one) changed by the crossings within the pixel's height. +fn outline_slug(rec: u32, hint: u32, local: vec2<f32>, scale: f32, r: f32, hw: f32) -> f32 { + let head = outline_texel(rec); + let count = head.y; + let y0 = bitcast<f32>(head.z); + let inv_h = bitcast<f32>(head.w); + let hinted = hint != 0u; + var ha = vec4<f32>(0.0); + var hb = vec4<f32>(0.0); + var hc = vec4<f32>(0.0); + if (hinted) { + ha = bitcast<vec4<f32>>(outline_texel(hint)); + hb = bitcast<vec4<f32>>(outline_texel(hint + 1u)); + hc = bitcast<vec4<f32>>(outline_texel(hint + 2u)); + } + // Only the bands about the pixel's rows hold what either ray meets within it. + let reach = select(0.0, OUTLINE_HINT_REACH, hinted); + var b0 = 0u; + var b1 = 0u; + if (count > 1u) { + let last = f32(count - 1u); + b0 = u32(clamp(floor(((local.y - hw - 2.0 * r - reach) / scale - y0) * inv_h), 0.0, last)); + b1 = u32(clamp(floor(((local.y + hw + reach) / scale - y0) * inv_h), 0.0, last)); + } + var across = 0.0; + var winding = 0.0; + var down = 0.0; + for (var band = b0; band <= b1; band = band + 1u) { + var e0 = -3.0e38; + var e1 = 3.0e38; + if (count > 1u) { + e0 = (y0 + f32(band) / inv_h) * scale; + e1 = (y0 + f32(band + 1u) / inv_h) * scale; + } + let entry = outline_texel(head.x + band); + for (var k = 0u; k < entry.y; k = k + 1u) { + let t0 = outline_texel(entry.x + 2u * k); + let t1 = outline_texel(entry.x + 2u * k + 1u); + let code = t1.z; + let oa = outline_move(code & 15u) * r; + let ob = outline_move((code >> 4u) & 15u) * r; + var p0 = bitcast<vec2<f32>>(t0.xy) * scale + oa; + var p1 = bitcast<vec2<f32>>(t0.zw) * scale + oa; + var p2 = bitcast<vec2<f32>>(t1.xy) * scale + ob; + var be0 = e0 + oa.y; + var be1 = e1 + oa.y; + if (hinted) { + p0.y = outline_hint(p0.y, ha, hb, hc); + p1.y = outline_hint(p1.y, ha, hb, hc); + p2.y = outline_hint(p2.y, ha, hb, hc); + be0 = outline_hint(be0, ha, hb, hc); + be1 = outline_hint(be1, ha, hb, hc); + } + // A connector lies in one band; a piece counts only within its band's rows. + if ((code & 256u) != 0u) { + p1 = (p0 + p2) * 0.5; + be0 = -3.0e38; + be1 = 3.0e38; + } + let q0 = p0 - local; + let q1 = p1 - local; + let q2 = p2 - local; + let ylo = max(min(q0.y, q2.y), be0 - local.y); + let yhi = min(max(q0.y, q2.y), be1 - local.y); + // Horizontal ray: where the piece crosses the centre's row, spread across the pixel; + // and the centre's winding, which the vertical ray starts from. + if (q0.y != q2.y && ylo <= 0.0 && 0.0 < yhi) { + let t = outline_root(q0.y, q1.y, q2.y, 0.0); + let x = mix(mix(q0.x, q1.x, t), mix(q1.x, q2.x, t), t); + let s = sign(q2.y - q0.y); + across = across + s * clamp(x / (2.0 * hw) + 0.5, 0.0, 1.0); + winding = winding + s * select(0.0, 1.0, x > 0.0); + } + // Vertical ray: only crossings within the pixel's height change it from the centre's + // winding, each counted in its band's rows. + if (q0.x != q2.x && min(q0.x, q2.x) <= 0.0 && 0.0 < max(q0.x, q2.x)) { + let t = outline_root(q0.x, q1.x, q2.x, 0.0); + let y = mix(mix(q0.y, q1.y, t), mix(q1.y, q2.y, t), t); + if (abs(y) < hw && y >= be0 - local.y && y < be1 - local.y) { + down = down - sign(q2.x - q0.x) * (clamp(y / (2.0 * hw) + 0.5, 0.0, 1.0) - select(0.0, 1.0, y > 0.0)); + } + } + } + } + return 0.5 * (min(abs(across), 1.0) + min(abs(winding + down), 1.0)); +} + +// The subpixel coverage (red, green, blue; w = 1) of the glyph this fragment draws, or zero +// for any other: the dual-source entry (render/variant.rs) blends each channel by its own. +var<private> lcd_cov: vec4<f32>; + +// A glyph instance drawn from its outline (`text::Outline`): radii = pen, scale, zoom; border = +// record, hint, radius, coverage (0: Windfoil's box, 1: Slug's rays, 2: Windfoil's box about +// each subpixel, 3: one subpixel per texel, filling a subpixel mask three texels a pixel). Rest px, +// y up, a device pixel 1 / zoom of them across. +fn outline_glyph(i: Out, screen: vec2<f32>) -> f32 { + let z = i.radii.w; + let rec = u32(i.border.x); + let hint = u32(i.border.y); + let hw = 0.5 / z; + let mode = u32(i.border.w + 0.5); + // A subpixel mask's texels are thirds of a pixel; its boxes are still a pixel wide. + let across = select(1.0, 3.0, mode == 3u); + let local = vec2<f32>((screen.x - i.radii.x) / across, i.radii.y - screen.y) / z; + if (mode == 1u) { + return outline_slug(rec, hint, local, i.radii.z, i.border.z, hw); + } + if (mode == 2u && OUTLINE_SUBPIXEL) { + return outline_rgb(rec, hint, local, i.radii.z, i.border.z, hw); + } + return outline_coverage(rec, hint, local, i.radii.z, i.border.z, hw, hw); +} + +// Whether this shader blends subpixel text by channel: false here, so a subpixel glyph draws +// its grayscale coverage; the subpixel variant (render/variant.rs) sets it. +const OUTLINE_SUBPIXEL: bool = false; + +// A subpixel glyph's three coverages, red to blue, each a pixel-wide box about its subpixel's +// centre (FreeType's light LCD filter, thirds, which keeps the colour fringes faint). +fn outline_rgb(rec: u32, hint: u32, local: vec2<f32>, scale: f32, r: f32, hw: f32) -> f32 { + let third = vec2<f32>(2.0 * hw / 3.0, 0.0); + let c = vec3<f32>( + outline_coverage(rec, hint, local - third, scale, r, hw, hw), + outline_coverage(rec, hint, local, scale, r, hw, hw), + outline_coverage(rec, hint, local + third, scale, r, hw, hw)); + lcd_cov = vec4<f32>(c, 1.0); + return (c.x + c.y + c.z) / 3.0; +} + +// A subpixel atlas mask (`radii.x == 1`): three texels a pixel, red to blue. +fn lcd_mask(i: Out, screen: vec2<f32>) -> f32 { + let p = floor(screen - i.rect.xy); + let t = vec2<i32>(i.uv.xy) + vec2<i32>(i32(p.x) * 3, i32(p.y)); + let c = vec3<f32>(textureLoad(atlas, t, 0).r, textureLoad(atlas, t + vec2<i32>(1, 0), 0).r, textureLoad(atlas, t + vec2<i32>(2, 0), 0).r); + lcd_cov = vec4<f32>(c, 1.0); + return (c.x + c.y + c.z) / 3.0; +} diff --git a/app/vendor/rune/crates/rune/src/shaders/shader.wgsl b/app/vendor/rune/crates/rune/src/shaders/shader.wgsl new file mode 100644 index 0000000..eb35f91 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/shaders/shader.wgsl @@ -0,0 +1,574 @@ +// One instanced "uber-quad": rounded rects with per-corner radius and border (kind 0), analytic +// Gaussian rounded-rect shadows (kind 1), glyph-atlas text (kind 2), inset shadows (kind 3), +// vertical-gradient rounded rects or borders (kind 4), stroke segments (kind 5) and filled +// triangles (kind 6) for vector shapes, RGBA images (kind 7), and premultiplied layer composites +// (kind 8), dashed borders (kind 10), and radial or angled linear gradients (kind 11). +// Scope-end records (kind 9) never reach this shader. Every ordinary instance carries a +// soft-edge clip. Output is premultiplied linear colour into an sRGB target (or sRGB into a +// non-sRGB target when `srgb_blend` is enabled). + +struct Globals { + viewport: vec2<f32>, + pad: vec2<f32>, + flags: vec4<f32>, +}; + +@group(0) @binding(0) var<uniform> g: Globals; +@group(0) @binding(1) var atlas: texture_2d<f32>; +@group(0) @binding(2) var images: texture_2d<f32>; +// Zero size selects the window viewport. Layer targets keep all geometry/clip coordinates +// absolute and change only the final projection, including GPU-spring translations. +@group(0) @binding(3) var<uniform> projection: vec4<f32>; + +struct In { + @builtin(vertex_index) vi: u32, + @location(0) rect: vec4<f32>, + @location(1) radii: vec4<f32>, + @location(2) fill: vec4<f32>, + @location(3) border: vec4<f32>, + @location(4) params: vec4<f32>, + @location(5) uv: vec4<f32>, + @location(6) clip: vec4<f32>, + @location(7) fade: vec4<u32>, +}; + +struct Out { + @builtin(position) pos: vec4<f32>, + @location(0) p: vec2<f32>, + @location(1) @interpolate(flat) rect: vec4<f32>, + @location(2) @interpolate(flat) radii: vec4<f32>, + @location(3) @interpolate(flat) fill: vec4<f32>, + @location(4) @interpolate(flat) border: vec4<f32>, + @location(5) @interpolate(flat) params: vec4<f32>, + @location(6) @interpolate(flat) uv: vec4<f32>, + @location(7) @interpolate(flat) clip: vec4<f32>, + @location(8) @interpolate(flat) fade: vec4<u32>, +}; + +// Layer composites use `vs` even with GPU springs: the layer's contents already sampled the +// retained instance tracks using their original absolute instance indices. +@vertex +fn vs(i: In) -> Out { + return base_vs(i); +} + +fn base_vs(i: In) -> Out { + let corner = vec2<f32>(f32(i.vi & 1u), f32(i.vi >> 1u)); + let kind = i.params.y; + var grow = 1.0 + i.params.z * 2.0; + if (kind > 0.5 && kind < 1.5) { + grow = i.params.z * 3.0 + 1.0; + } else if (kind > 1.5 && kind < 2.5) { + grow = 0.0; + } else if (kind > 2.5 && kind < 3.5) { + grow = 1.0; + } else if (kind > 4.5 && kind < 9.5) { + grow = 1.0; + } + var lo = i.rect.xy - vec2<f32>(grow); + // Effect slots (kind 12) reserve their place in the stream and cover no pixels. + let size = select(i.rect.zw + vec2<f32>(2.0 * grow), vec2<f32>(0.0), kind > 11.5); + var hi = lo + size; + // One band of a big shadow or border ring rasterizes only its window (runtime/bands.rs). + // Neighbouring bands compute a shared edge the same way, so they meet without a seam. + if (kind < 1.5 && i.uv.z < 0.0) { + lo = max(lo, i.rect.xy + i.uv.xy); + hi = max(min(hi, i.rect.xy + vec2<f32>(-i.uv.z, i.uv.w)), lo); + } + let p = select(lo, hi, corner > vec2<f32>(0.5)); + var screen = p; + // Icon loops rotate the quad, not its atlas allocation. Local p still samples the glyph. + if (kind > 1.5 && kind < 2.5 && i.params.x != 0.0) { + let center = i.rect.xy + i.rect.zw * 0.5; + let q = p - center; + let c = cos(i.params.x); + let s = sin(i.params.x); + screen = center + vec2<f32>(c * q.x - s * q.y, s * q.x + c * q.y); + } + // A turned layer composite (`Instance::turned`): border.y radians about border.zw. + if (kind > 7.5 && kind < 8.5 && i.border.y != 0.0) { + let q = p - i.border.zw; + let c = cos(i.border.y); + let s = sin(i.border.y); + screen = i.border.zw + vec2<f32>(c * q.x - s * q.y, s * q.x + c * q.y); + } + var o: Out; + let size_px = select(g.viewport, projection.zw, projection.z > 0.0); + let local = screen - projection.xy; + o.pos = vec4<f32>(local.x / size_px.x * 2.0 - 1.0, 1.0 - local.y / size_px.y * 2.0, 0.0, 1.0); + o.p = p; + o.rect = i.rect; + o.radii = i.radii; + o.fill = i.fill; + o.border = i.border; + o.params = i.params; + o.uv = i.uv; + o.clip = i.clip; + o.fade = i.fade; + return o; +} + +// Evan Wallace's analytic rounded-box shadow (as in GPUI): exact along x, 4 samples along y. +fn gaussian(x: f32, sigma: f32) -> f32 { + return exp(-(x * x) / (2.0 * sigma * sigma)) / (sqrt(2.0 * 3.14159265) * sigma); +} + +fn erf2(x: vec2<f32>) -> vec2<f32> { + let s = sign(x); + let a = abs(x); + var r = 1.0 + (0.278393 + (0.230389 + 0.078108 * (a * a)) * a) * a; + r = r * r; + return s - s / (r * r); +} + +fn shadow_x(x: f32, y: f32, sigma: f32, corner: f32, half: vec2<f32>) -> f32 { + let delta = min(half.y - corner - abs(y), 0.0); + let curved = half.x - corner + sqrt(max(0.0, corner * corner - delta * delta)); + let integral = 0.5 + 0.5 * erf2((x + vec2<f32>(-curved, curved)) * (sqrt(0.5) / sigma)); + return integral.y - integral.x; +} + +// What `shadow` sums to well inside the box, where every row it samples is fully covered: the +// four midpoint weights of the ±3σ window, 3·(g(0.75) + g(2.25)) for a unit Gaussian g. +const SHADOW_INSIDE: f32 = 0.99863125; + +fn shadow(p: vec2<f32>, half: vec2<f32>, sigma: f32, corner: f32) -> f32 { + // A big panel's shadow is mostly interior, and its erf rows there cost a 5K frame + // milliseconds. 6σ in, each row is within 1e-6 of fully covered. + if (abs(p.x) <= half.x - 6.0 * sigma && abs(p.y) <= half.y - corner - 6.0 * sigma) { + return SHADOW_INSIDE; + } + let lo = p.y - half.y; + let hi = p.y + half.y; + let start = clamp(-3.0 * sigma, lo, hi); + let end = clamp(3.0 * sigma, lo, hi); + let step = (end - start) / 4.0; + var y = start + step * 0.5; + var v = 0.0; + for (var i = 0; i < 4; i = i + 1) { + v = v + shadow_x(p.x, p.y - y, sigma, corner, half) * gaussian(y, sigma) * step; + y = y + step; + } + return v; +} + +// Coverage of a stroke segment from a to b, `hw` half width, round or butt caps. Strokes +// thinner than a pixel draw a pixel wide at proportionally lower coverage. +fn segment(p: vec2<f32>, a: vec2<f32>, b: vec2<f32>, hw: f32, round: bool) -> f32 { + let w = max(hw, 0.5); + let weight = min(hw * 2.0, 1.0); + let ab = b - a; + let len = length(ab); + let ap = p - a; + var d: f32; + if (len < 1e-4) { + if (!round) { + return 0.0; + } + d = length(ap) - w; + } else { + let dir = ab / len; + let along = dot(ap, dir); + if (round) { + d = length(ap - dir * clamp(along, 0.0, len)) - w; + } else { + let across = abs(dir.x * ap.y - dir.y * ap.x); + let q = vec2<f32>(abs(along - len * 0.5) - len * 0.5, across - w); + d = min(max(q.x, q.y), 0.0) + length(max(q, vec2<f32>(0.0))); + } + } + return clamp(0.5 - d, 0.0, 1.0) * weight; +} + +// Signed distance from p to the edge a->b, positive on the side `c` lies on. +fn edge(p: vec2<f32>, a: vec2<f32>, b: vec2<f32>, c: vec2<f32>) -> f32 { + let e = b - a; + let l = max(length(e), 1e-6); + let n = vec2<f32>(-e.y, e.x) / l; + let s = select(-1.0, 1.0, dot(c - a, n) >= 0.0); + return dot(p - a, n) * s; +} + +// Whether p is on c's side of the edge a-b, decided so that the two triangles sharing the edge +// compute the same value with opposite signs and exactly one of them owns every pixel: the +// endpoints are put in a fixed order and ties go to the positive side. +fn owns(p: vec2<f32>, a: vec2<f32>, b: vec2<f32>, c: vec2<f32>) -> bool { + let swap = a.x > b.x || (a.x == b.x && a.y > b.y); + let lo = select(a, b, swap); + let hi = select(b, a, swap); + let e = hi - lo; + let side = e.x * (c.y - lo.y) - e.y * (c.x - lo.x); + let v = e.x * (p.y - lo.y) - e.y * (p.x - lo.x); + if (side > 0.0) { + return v >= 0.0; + } + return v < 0.0; +} + +// Coverage across a polygon edge a->b. Only the edge itself is antialiased: past its ends +// (where a concave polygon's interior continues along the edge's line) the edge cuts hard, so +// the neighbouring triangle that owns those pixels is not shaded through. +fn soft(p: vec2<f32>, a: vec2<f32>, b: vec2<f32>, c: vec2<f32>) -> f32 { + let d = edge(p, a, b, c); + let e = b - a; + let t = dot(p - a, e) / max(dot(e, e), 1e-6); + if (t < 0.0 || t > 1.0) { + return select(0.0, 1.0, d >= 0.0); + } + return clamp(d + 0.5, 0.0, 1.0); +} + +// Coverage of a filled triangle; `aa` marks the polygon-boundary edges, which are antialiased +// (bits 0, 1, 2 for a->b, b->c, c->a). Other edges are shared with a neighbouring triangle and +// cut hard, with exactly one of the two owning each pixel. +fn triangle(p: vec2<f32>, a: vec2<f32>, b: vec2<f32>, c: vec2<f32>, aa: u32) -> f32 { + var cov = 1.0; + if ((aa & 1u) == 1u) { + cov = cov * soft(p, a, b, c); + } else if (!owns(p, a, b, c)) { + return 0.0; + } + if ((aa & 2u) == 2u) { + cov = cov * soft(p, b, c, a); + } else if (!owns(p, b, c, a)) { + return 0.0; + } + if ((aa & 4u) == 4u) { + cov = cov * soft(p, c, a, b); + } else if (!owns(p, c, a, b)) { + return 0.0; + } + return cov; +} + +fn srgb_encode(x: vec3<f32>) -> vec3<f32> { + let v = clamp(x, vec3<f32>(0.0), vec3<f32>(1.0)); + return select(1.055 * pow(v, vec3<f32>(1.0 / 2.4)) - 0.055, v * 12.92, v <= vec3<f32>(0.0031308)); +} + +/// One image texel, premultiplied (the atlas holds straight alpha) so filtering doesn't darken edges. +fn image_texel(t: vec2<i32>, premultiplied: bool) -> vec4<f32> { + let c = textureLoad(images, t, 0); + if (g.flags.x > 0.5) { + if (c.a <= 0.0) { return vec4<f32>(0.0); } + let lin = select(c.rgb, c.rgb / c.a, premultiplied); + return vec4<f32>(srgb_encode(lin) * c.a, c.a); + } + if premultiplied { return c; } + return vec4<f32>(c.rgb * c.a, c.a); +} + +// Arc length to the point nearest `p` (rect-local) on the centre line of a `bw`-wide ring inside +// the rounded rect, and the line's full length. It runs clockwise from where the top edge leaves +// the top-left corner; corners count along their arcs. +fn ring_arc(p: vec2<f32>, size: vec2<f32>, radii: vec4<f32>, bw: f32) -> vec2<f32> { + let h = bw * 0.5; + let half = size * 0.5; + let rc = max(min(abs(radii), vec4<f32>(min(half.x, half.y))) - vec4<f32>(h), vec4<f32>(0.0)); + let e = rc + vec4<f32>(h); + let arc = rc * 1.5707964; + let s_tr = max(size.x - bw - rc.x - rc.y, 0.0); + let s_right = s_tr + arc.y; + let s_br = s_right + max(size.y - bw - rc.y - rc.z, 0.0); + let s_bottom = s_br + arc.z; + let s_bl = s_bottom + max(size.x - bw - rc.z - rc.w, 0.0); + let s_left = s_bl + arc.w; + let s_tl = s_left + max(size.y - bw - rc.w - rc.x, 0.0); + let top = p.x - e.x; + let right = s_right + p.y - e.y; + let bottom = s_bottom + size.x - e.z - p.x; + let left = s_left + size.y - e.w - p.y; + var s: f32; + if (p.x > half.x) { + if (p.y > half.y) { + let v = p - (size - vec2<f32>(e.z)); + if (v.x > 0.0 && v.y > 0.0) { s = s_br + atan2(v.y, v.x) * rc.z; } + else { s = select(bottom, right, size.x - p.x < size.y - p.y); } + } else { + let v = p - vec2<f32>(size.x - e.y, e.y); + if (v.x > 0.0 && v.y < 0.0) { s = s_tr + atan2(v.x, -v.y) * rc.y; } + else { s = select(top, right, size.x - p.x < p.y); } + } + } else if (p.y > half.y) { + let v = p - vec2<f32>(e.w, size.y - e.w); + if (v.x < 0.0 && v.y > 0.0) { s = s_bl + atan2(-v.x, v.y) * rc.w; } + else { s = select(bottom, left, p.x < size.y - p.y); } + } else { + let v = p - vec2<f32>(e.x); + if (v.x < 0.0 && v.y < 0.0) { s = s_tl + atan2(-v.y, -v.x) * rc.x; } + else { s = select(top, left, p.x < p.y); } + } + return vec2<f32>(s, s_tl + arc.x); +} + +// Coverage of a dash pattern (dash, gap, phase) at arc length `s`. The period stretches or +// shrinks so a whole number of periods fills `total`, and the pattern meets itself at the seam. +fn dash_cov(s: f32, total: f32, d: vec3<f32>) -> f32 { + let nominal = d.x + d.y; + let k = max(total, 0.001) / (max(floor(total / nominal + 0.5), 1.0) * nominal); + let period = nominal * k; + let dash = d.x * k; + let a = s + d.z * k - dash * 0.5; + let m = a - period * floor(a / period + 0.5); + return clamp(dash * 0.5 - abs(m) + 0.5, 0.0, 1.0); +} + +// A border over its own background, as CSS paints one: the background runs under the border to +// the outer edge (`background-clip: border-box`) and the ring of `edge` draws over it. `d` and +// `inner_d` are the distances to the outer and inner edges. `opacity` is what the colours were +// already multiplied by, so `edge.a / opacity` is how much the border hides the fill. An opaque +// border all round a rounded box (`shrink`) pulls the fill in by half its width, as Chromium's +// bleed avoidance does, so no fill fringes the anti-aliased outer edge. +fn border_over(fill: vec4<f32>, edge: vec4<f32>, d: f32, inner_d: f32, soft: f32, bw: f32, opacity: f32, shrink: bool) -> vec4<f32> { + let cov = clamp(0.5 - d / (soft * 2.0), 0.0, 1.0); + let ring = max(cov - clamp(0.5 - inner_d / (soft * 2.0), 0.0, 1.0), 0.0); + let hide = clamp(edge.a / clamp(opacity, 1e-6, 1.0), 0.0, 1.0); + let under = clamp(0.5 - (d + select(0.0, bw * 0.5, shrink && hide > 0.999)) / (soft * 2.0), 0.0, 1.0); + return edge * ring + fill * (under * (1.0 - hide * ring)); +} + +// How much of the pixel at `p` the box covers. Where the corner is square that's the exact +// area, as Chromium rasterises a rect; a rounded corner takes the distance estimate. +fn box_cov(p: vec2<f32>, half: vec2<f32>, radii: vec4<f32>) -> f32 { + var r = radii.x; + if (p.x > 0.0) { + r = select(radii.y, radii.z, p.y > 0.0); + } else { + r = select(radii.x, radii.w, p.y > 0.0); + } + if (r == 0.0) { + let e = clamp(min(half, p + vec2<f32>(0.5)) - max(-half, p - vec2<f32>(0.5)), vec2<f32>(0.0), vec2<f32>(1.0)); + return e.x * e.y; + } + return clamp(0.5 - sd_rounded(p, half, radii), 0.0, 1.0); +} + +// A layer composite's round hole (`El::cutout_circle`): centre `h.xy`, clear within `h.z`, whole +// from `h.w`, linear between and at least a pixel wide; none when `h.w` is zero. +fn hole_alpha(p: vec2<f32>, h: vec4<f32>) -> f32 { + if (h.w <= 0.0) { return 1.0; } + return clamp((length(p - h.xy) - (h.z + h.w) * 0.5) / max(h.w - h.z, 1.0) + 0.5, 0.0, 1.0); +} + +// A texel of a layer, clamped to [0, 1] when `clamp_unit` is set (`Blend::PlusLighter`), so +// bilinear filtering saturates each accumulated source texel before interpolation (as +// `layer_blur.wgsl` does before convolution). +fn layer_load(t: vec2<i32>, clamp_unit: bool) -> vec4<f32> { + let c = textureLoad(images, t, 0); + return select(c, clamp(c, vec4<f32>(0.0), vec4<f32>(1.0)), clamp_unit); +} + +// A texel of a layer `size` pixels across; transparent outside it. +fn layer_texel(t: vec2<i32>, size: vec2<f32>, clamp_unit: bool) -> vec4<f32> { + if (any(t < vec2<i32>(0)) || any(t >= vec2<i32>(size))) { return vec4<f32>(0.0); } + return layer_load(t, clamp_unit); +} + +// The kind of shape a fragment draws: the instance's, or, in a pipeline built for one kind (render/variant.rs +// `pinned_wgsl`), that kind, fixed when the shader compiles, so the compiler drops every other kind's code +// and a fragment no longer pays for shapes it isn't. -1 is the shader every kind can draw with. +const PINNED_KIND: f32 = -1.0; + +fn fragment_kind(i: Out) -> f32 { + if (PINNED_KIND >= 0.0) { return PINNED_KIND; } + return i.params.y; +} + +@fragment +fn fs(i: Out) -> @location(0) vec4<f32> { + if (fragment_kind(i) == 8.0) { + // Filters consume unmasked source pixels. Decode the same packed clip as primitives + // only here, on the completed layer, including the radius in word 3. + let screen = i.pos.xy + projection.xy; + var p = screen - i.rect.xy; + // Float intermediates accumulate One/One without saturation. Saturate each texel before + // bilinear filtering and before applying this scope's opacity so resampling and nesting + // preserve plus-lighter's bounded coverage. + let additive = i.params.x == 1.0; + var color: vec4<f32>; + if (i.border.y != 0.0) { + // Turned: sample the upright contents where this pixel turns back to, bilinearly, + // with nothing outside the layer. + let q = screen - i.border.zw; + let c = cos(i.border.y); + let s = sin(i.border.y); + p = i.border.zw + vec2<f32>(c * q.x + s * q.y, c * q.y - s * q.x) - i.rect.xy; + let local = p - vec2<f32>(0.5); + let base = floor(local); + let f = local - base; + let t0 = vec2<i32>(base); + color = mix(mix(layer_texel(t0, i.rect.zw, additive), layer_texel(t0 + vec2<i32>(1, 0), i.rect.zw, additive), f.x), + mix(layer_texel(t0 + vec2<i32>(0, 1), i.rect.zw, additive), layer_texel(t0 + vec2<i32>(1, 1), i.rect.zw, additive), f.x), f.y); + } else if (any(p < vec2<f32>(0.0)) || any(p >= i.rect.zw)) { + discard; + } else if (i.uv.z > 0.0) { + let local = p * i.uv.zw / i.rect.zw - vec2<f32>(0.5); + let hi = vec2<i32>(i.uv.zw) - vec2<i32>(1); + let base = floor(local); + let f = local - base; + let t0 = clamp(vec2<i32>(base), vec2<i32>(0), hi); + let t1 = clamp(vec2<i32>(base) + vec2<i32>(1, 1), vec2<i32>(0), hi); + color = mix(mix(layer_load(t0, additive), layer_load(vec2<i32>(t1.x, t0.y), additive), f.x), + mix(layer_load(vec2<i32>(t0.x, t1.y), additive), layer_load(t1, additive), f.x), f.y); + } else { + color = layer_load(vec2<i32>(floor(p)), additive); + } + return color * i.fill.a * clip_alpha_stops(screen, i.clip, i.fade, g.flags.zw) * hole_alpha(screen, i.radii); + } + let kind = fragment_kind(i); + if (kind > 11.5) { discard; } + // Fragment position is the rasterizer's exact pixel centre; interpolated `i.p` drifts by + // subpixel ULPs on D3D12, turning exact 1.0 edge coverage into 1.0 - eps (which drops to + // 1 - 1/2048 in Rgba16Float layer targets). Only rotated glyphs need interpolated `i.p`. + let screen = i.pos.xy + projection.xy; + let half = i.rect.zw * 0.5; + let center = i.rect.xy + half; + var col = vec4<f32>(0.0); + if (kind < 0.5) { + let d = sd_rounded(screen - center, half, i.radii); + let soft = max(i.params.z, 0.5); + let bw = i.params.x; + if (bw > 0.0) { + // Per-side widths (top, right, bottom, left) in `uv`, as CSS `border-bottom` and the + // like; all zero is `bw` all round, and a band window (runtime/bands.rs) has a + // negative `uv.z`. + let w = i.uv; + let sides = w.z >= 0.0 && any(w != vec4<f32>(0.0)); + var inner_d = d + bw; + if (sides) { + let ih = max(half - vec2<f32>(w.y + w.w, w.x + w.z) * 0.5, vec2<f32>(0.0)); + let ic = center + vec2<f32>(w.w - w.y, w.x - w.z) * 0.5; + let cut = vec4<f32>(max(w.x, w.w), max(w.x, w.y), max(w.z, w.y), max(w.z, w.w)); + inner_d = sd_rounded(screen - ic, ih, sign(i.radii) * max(abs(i.radii) - cut, vec4<f32>(0.0))); + } + col = border_over(i.fill, i.border, d, inner_d, soft, bw, i.params.w, !sides && any(i.radii != vec4<f32>(0.0))); + } else { + col = i.fill * clamp(0.5 - d / (soft * 2.0), 0.0, 1.0); + } + } else if (kind < 1.5) { + let sigma = max(i.params.z, 0.01); + let corner = min(abs(i.radii.x), min(half.x, half.y)); + col = i.fill * shadow(screen - center, half, sigma, corner); + // A shadow under a native system material leaves its interior clear: `uv` holds the + // hole relative to this rect and `radii.w` its corner radius. + if (i.uv.z > 0.0) { + let hole = i.uv.zw * 0.5; + col = col * clamp(0.5 + sd_rounded(screen - (i.rect.xy + i.uv.xy + hole), hole, vec4<f32>(i.radii.w)), 0.0, 1.0); + } + } else if (kind > 6.5) { + let d = sd_rounded(screen - center, half, i.radii); + if (kind > 10.5) { + // Radial (`uv.z > 0`) or angled linear (`uv.z == 0`) gradient stop segment from + // `fill` at t0 (`params.x`) to `border` at t1 (`params.w`); `+ 2.0` marks an open + // interior stop boundary so adjacent segments partition the quad without overlap. + let soft = max(i.params.z, 0.5); + let cov = clamp(0.5 - d / (soft * 2.0), 0.0, 1.0); + let t0_raw = i.params.x; + let t1_raw = i.params.w; + let lower_open = t0_raw >= 1.5; + let upper_open = t1_raw >= 1.5; + let t0 = select(t0_raw, t0_raw - 2.0, lower_open); + let t1 = select(t1_raw, t1_raw - 2.0, upper_open); + var t: f32; + if (i.uv.z > 0.0) { + t = length((screen - i.rect.xy - i.uv.xy) / i.uv.zw); + } else { + t = 0.5 + dot(screen - center, i.uv.xy); + } + if ((lower_open && t < t0) || (upper_open && t >= t1)) { + col = vec4<f32>(0.0); + } else { + let u = select(clamp((t - t0) / (t1 - t0), 0.0, 1.0), select(0.0, 1.0, t >= t0), t1 <= t0 + 1e-6); + col = mix(i.fill, i.border, u) * cov; + } + } else if (kind > 9.5) { + // Dashed border: kind 0's ring, colour running from `fill` (top) to `border` + // (bottom), masked by the dash pattern in `uv.xyz` along the ring's centre line. + let soft = max(i.params.z, 0.5); + let bw = i.params.x; + let ring = clamp(0.5 - d / (soft * 2.0), 0.0, 1.0) - clamp(0.5 - (d + bw) / (soft * 2.0), 0.0, 1.0); + let t = clamp((screen.y - i.rect.y) / max(i.rect.w, 1.0), 0.0, 1.0); + let arc = ring_arc(screen - i.rect.xy, i.rect.zw, i.radii, bw); + col = mix(i.fill, i.border, t) * (ring * dash_cov(arc.x, arc.y, i.uv.xyz)); + } else { + // Bilinear, clamped to the image's own texels so neighbours in the atlas never bleed. + let local = (screen - i.rect.xy) * i.uv.zw / i.rect.zw - vec2<f32>(0.5); + let lo = vec2<i32>(i.uv.xy); + let hi = lo + vec2<i32>(i.uv.zw) - vec2<i32>(1); + let base = floor(local); + let f = local - base; + let t0 = clamp(lo + vec2<i32>(base), lo, hi); + let t1 = clamp(lo + vec2<i32>(base) + vec2<i32>(1, 1), lo, hi); + let premultiplied = i.params.z > 0.5; + let c = mix(mix(image_texel(t0, premultiplied), image_texel(vec2<i32>(t1.x, t0.y), premultiplied), f.x), + mix(image_texel(vec2<i32>(t0.x, t1.y), premultiplied), image_texel(t1, premultiplied), f.x), f.y); + col = c * (i.fill.a * clamp(0.5 - d, 0.0, 1.0)); + } + } else if (kind > 4.5 && kind < 5.5) { + col = i.fill * segment(screen, i.radii.xy, i.radii.zw, i.params.x, i.params.z > 0.5); + } else if (kind > 5.5 && kind < 6.5) { + col = i.fill * triangle(screen, i.radii.xy, i.radii.zw, i.uv.xy, u32(i.params.x + 0.5)); + } else if (kind > 2.5) { + if (kind < 3.5) { + // Inset shadow: the element's shape minus a blurred copy of it shrunk by the spread + // and moved by the offset. Square corners take exact pixel areas, so a hairline + // ring's corner pixel is as dark as Chromium draws it. + let spread = i.params.x; + let ih = max(half - vec2<f32>(spread), vec2<f32>(0.0)); + let q = screen - center - i.uv.xy; + var lit: f32; + if (i.params.z < 0.3) { + lit = box_cov(q, ih, sign(i.radii) * max(abs(i.radii) - vec4<f32>(spread), vec4<f32>(0.0))); + } else { + lit = shadow(q, ih, i.params.z, max(min(abs(i.radii.x) - spread, min(ih.x, ih.y)), 0.0)); + } + col = i.fill * box_cov(screen - center, half, i.radii) * (1.0 - clamp(lit, 0.0, 1.0)); + } else { + // With a border width, kind 0 whose ring runs from `border` (top) to `uv` (bottom). + let d = sd_rounded(screen - center, half, i.radii); + let t = clamp((screen.y - i.rect.y) / max(i.rect.w, 1.0), 0.0, 1.0); + let soft = max(i.params.z, 0.5); + let bw = i.params.x; + if (bw > 0.0) { + col = border_over(i.fill, mix(i.border, i.uv, t), d, d + bw, soft, bw, i.params.w, any(i.radii != vec4<f32>(0.0))); + } else { + col = mix(i.fill, i.uv, t) * clamp(0.5 - d / (soft * 2.0), 0.0, 1.0); + } + } + } else { + let rotated = i.params.x != 0.0; + var cov: f32; + if i.uv.z > 0.0 || rotated { + // Flying text keeps the original atlas footprint while its quad scales uniformly. + // A turned icon samples at its unturned point, filtered: no texel lines up with a pixel. + let p = select(screen, i.p, rotated); + let span = select(i.rect.zw, i.uv.zw, i.uv.z > 0.0); + let local = (p - i.rect.xy) * span / i.rect.zw - vec2<f32>(0.5); + let uv = vec2<i32>(i.uv.xy + floor(local)); + let f = fract(local); + cov = mix(mix(textureLoad(atlas, uv, 0).r, textureLoad(atlas, uv + vec2<i32>(1, 0), 0).r, f.x), + mix(textureLoad(atlas, uv + vec2<i32>(0, 1), 0).r, textureLoad(atlas, uv + vec2<i32>(1, 1), 0).r, f.x), f.y); + } else { + let texel = vec2<i32>(i.uv.xy + floor(screen - i.rect.xy)); + cov = textureLoad(atlas, texel, 0).r; + } + if (i.params.w < 0.0) { + // An atlas fill (render/fill.rs): the coverage rounded to the R8 target's levels here, + // ties to even, so the target stores it exactly. A GPU's own float-to-unorm rounding + // differs between vendors; this is the rounding the CPU's fill uses (fill_texel). + col = vec4<f32>(round(cov * 255.0) / 255.0); + } else { + col = i.fill * pow(cov, i.params.w); + } + } + let source = col * clip_alpha_stops(screen, i.clip, i.fade, g.flags.zw); + // On a direct byte surface cpu_boot::blend converts the source *after* mask gamma, + // colour, shape coverage and clipping. The mask texel itself isn't the blend source. + let flat_fill = kind == 0.0 && i.params.x == 0.0 && i.fill.a > 0.0 && i.fill.a < 1.0; + let gray_mask = kind == 2.0 && i.radii.w == 0.0 && i.radii.x == 0.0 && i.params.x == 0.0 && i.uv.z == 0.0 && i.params.w >= 0.0; + // Keep float layers, dual-source, outline/filtered glyphs and atlas population unchanged. + if (g.flags.y > 0.5 && projection.z == 0.0 && (flat_fill || gray_mask)) { + return round(clamp(source, vec4<f32>(0.0), vec4<f32>(1.0)) * 255.0) / 255.0; + } + return source; +} diff --git a/app/vendor/rune/crates/rune/src/shaders/surface_alpha.wgsl b/app/vendor/rune/crates/rune/src/shaders/surface_alpha.wgsl new file mode 100644 index 0000000..952ea60 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/shaders/surface_alpha.wgsl @@ -0,0 +1,11 @@ +// Premultiplied to straight alpha (render/surface_alpha.rs). Precompiled for DX12 by regen_dxbc. +@group(0) @binding(0) var source: texture_2d<f32>; +@vertex fn vs(@builtin(vertex_index) index: u32) -> @builtin(position) vec4<f32> { + let points = array(vec2(-1.0, -1.0), vec2(3.0, -1.0), vec2(-1.0, 3.0)); + return vec4(points[index], 0.0, 1.0); +} +@fragment fn fs(@builtin(position) point: vec4<f32>) -> @location(0) vec4<f32> { + let color = textureLoad(source, vec2<i32>(point.xy), 0); + if color.a > 0.0 { return vec4(color.rgb / color.a, color.a); } + return vec4(0.0); +} diff --git a/app/vendor/rune/crates/rune/src/shaders/uber.metallib b/app/vendor/rune/crates/rune/src/shaders/uber.metallib new file mode 100644 index 0000000..afac7fa Binary files /dev/null and b/app/vendor/rune/crates/rune/src/shaders/uber.metallib differ diff --git a/app/vendor/rune/crates/rune/src/shaders/uber_native.metallib b/app/vendor/rune/crates/rune/src/shaders/uber_native.metallib new file mode 100644 index 0000000..7ba4bd1 Binary files /dev/null and b/app/vendor/rune/crates/rune/src/shaders/uber_native.metallib differ diff --git a/app/vendor/rune/crates/rune/src/shaders/uber_windfoil.metallib b/app/vendor/rune/crates/rune/src/shaders/uber_windfoil.metallib new file mode 100644 index 0000000..9d26339 Binary files /dev/null and b/app/vendor/rune/crates/rune/src/shaders/uber_windfoil.metallib differ diff --git a/app/vendor/rune/crates/rune/src/shaders/uber_windfoil_native.metallib b/app/vendor/rune/crates/rune/src/shaders/uber_windfoil_native.metallib new file mode 100644 index 0000000..54fc1cf Binary files /dev/null and b/app/vendor/rune/crates/rune/src/shaders/uber_windfoil_native.metallib differ diff --git a/app/vendor/rune/crates/rune/src/shortcuts/README.md b/app/vendor/rune/crates/rune/src/shortcuts/README.md new file mode 100644 index 0000000..b247e54 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/shortcuts/README.md @@ -0,0 +1,237 @@ +# Global shortcuts + +```rust,ignore +let app = App::new(spec) + .global_shortcut("cmd+shift+space", |state, tx| { + state.quick_panel_open = true; + if let Some(token) = tx.activation_token() { + state.app_handle.activate(token); + } else { + state.app_handle.open(); + } + }) + .windowless(); +app.run(); +``` + +The handler receives the same state as its `App`/`WindowSpec`, on the app thread. +It runs through `Runtime::update`, including animation and shell requests. Native +activation wakes the loop even while no window is visible. + +Static builder failures print once and can be drained with +`handle.take_shortcut_errors()`. The builder defers registration until the app's +host exists, so `run_windows_with` factories can construct apps normally. + +Runtime registration returns the actual result: + +```rust,ignore +let id = handle.register_shortcut("ctrl+alt+k".parse()?, |state, tx| { + state.open_quick_panel(tx.activation_token()); +})?; +handle.unregister_shortcut(id)?; +``` + +After a `Conflict`, `handle.shortcut_owner(&shortcut)` names the holder when Rune or +the desktop knows it: this App or another Rune App in the process (its `AppSpec` +title), or a macOS system shortcut ("Spotlight", "Mission Control", "Input Sources", +"Screenshot", "App Switcher", "macOS" for other enabled symbolic hotkeys), at the chord +the user remapped it to. The macOS lookup answers only on the main thread. A chord +another Rune App in the process holds is refused with `Conflict` on every backend. Other apps' +grabs, Windows, X11 and the portal name nobody, so it returns None. Headless runs +answer only for their own virtual registrations. `ShortcutError::Conflict` itself is +unchanged. + +A chord needs ⌘, ⌃ or ⌥ (Ctrl, Alt or Super elsewhere), or an F1–F24 key, because a +global Space or ⇧A would take that key from typing in every app. Both the builder and +`register_shortcut` refuse one without them with `InvalidAccelerator` +(`shortcut.require_modifier()` checks it), unless the App opts in with +`.allow_unmodified_shortcuts()`. + +Call runtime registration after the host starts (an `on_window` or queued +`handle.update` callback works, including one on another window of the same +`run_windows`). Calls before startup or after shutdown return `NotRunning`. On macOS/Windows other threads may call it, but wait for the app +thread, so the app thread must not join those callers. Linux registration can +run off-thread. Dropping the host unregisters everything, +even if other threads retain `AppHandle`s. + +## Desktop behavior + +- macOS: Carbon `RegisterEventHotKey`, no Accessibility permission. Command is + the Super modifier. Hardware key positions follow the US layout; F21–F24 have + no Carbon key code and return `InvalidAccelerator`. +- Windows: `RegisterHotKey` on a message-only window owned by the event thread. + Repeat is disabled. Windows-reserved combinations may fail registration. +- X11: checked passive grabs on every root, including CapsLock/NumLock variants. + A failed variant rolls back the registration. Autorepeat is filtered, so a held + chord fires once, as on macOS and Windows. Keys use the current keymap's + base keysyms; restart/re-register after changing the keymap. +- Wayland: xdg-desktop-portal GlobalShortcuts. No portal returns `Unsupported`. + The portal may ask for permission or let the user choose another trigger; + `preferred_trigger` is a preference, not an exclusive-grab guarantee. Cancellation + is `PermissionDenied`, not `Conflict`. Each shortcut owns a portal session so + unregister also works with version 1. The activation token is available only + during its handler, through `Tx::activation_token()`. + +Registration is synchronous, including portal consent, with a two-minute bound. +Register startup shortcuts before showing windows; use a worker thread for +runtime Wayland binding so a consent dialog does not block the event thread. + +Only an actual registration creates native resources: macOS/Windows need no +listener thread; X11/Wayland each create a listener that is joined on teardown. +No-shortcut apps never open a shortcut display or portal connection. + +## Deterministic testing + +Headless scripts register virtually and invoke the same handlers: + +```json +[{"t": 0, "shortcut": "cmd+shift+space"}] +``` + +Unknown/unregistered shortcuts fail the script. Parsing is case-insensitive; +Display normalizes modifiers to `ctrl+alt+shift+super`, then the lowercase key. +`cmd`, `command`, `meta`, and `logo` alias `super`; `option` aliases `alt`. + +`scripts/check-global-shortcut-macos.py <shortcut_probe>` checks two-process +conflicts and real CuaDriver input on a GUI test Mac, under an exclusive GUI lock file. +The probe stays windowless and verifies handler thread identity. + +## Shortcut recorder + +`rune_kit::ShortcutRecorder` uses app-owned `ShortcutRecorderState` and renders the +existing `Keybind` component: + +```rust,ignore +ShortcutRecorder::new("shortcut", &state.shortcut, |s: &mut State| &mut s.shortcut) + .on_change(|state, shortcut, tx| state.replace_shortcut(shortcut, tx)) + .build(&kit) +``` + +The change callback returns `Result<(), ShortcutError>`. A registration failure +retains the old binding; the recorder keeps showing the refused chord with a message +until another modifier starts the next chord. Unchanged chords skip the callback, +unless `state.mark_unregistered()` says the shortcut isn't registered (it failed at +launch): then recording it again retries it through the callback. The +default message names the chord ("⌃J is already in use."); `.error_message(|error, +chord| ...)` rewords it, falling back on `rune_kit::shortcut_error_message`, and +`ShortcutRecorderState::refused()` reads the chord. A chord without a modifier (other +than F1–F24) is refused before the callback with "Add ⌘, ⌃ or ⌥." unless +`.allow_unmodified()`. +Click or keyboard activation starts recording, held modifiers preview immediately, +Escape cancels, Backspace clears, and focus loss or disabling cancels recording. +Repeated key presses are consumed without registering again. +`scripts/shortcut-recorder.json` records a chord headlessly. + +`Shortcut` stores a `PhysicalKeyCode`. Parsing and Display use canonical US physical +names; `keycaps()` is for display only. On the macOS main thread, printable labels +use `TISCopyCurrentKeyboardLayoutInputSource` and `UCKeyTranslate` without changing +the input source. Other platforms, background callers and unavailable layouts use +US labels. Persist the canonical shortcut, not its translated keycaps. +`menu_keycaps()` is the label a menu shows: the key the accelerator names on every +layout (`cmd+b` is ⌘B on Dvorak, where `keycaps()` says ⌘X). Use it for menu items and +hints of keys an app matches by character, `keycaps()` for global shortcuts. + +Physical input and its logical fallback are processed together in event order. +Focused capture runs before modal Escape, text editing and paste. A consumed chord +never reads the clipboard. Otherwise eligible Cmd-V requests the asynchronous +clipboard worker and consumes the command even for empty/image-only clipboards. +The captured paste target prevents a later focus change from receiving the reply. +Single-line and secure editors retain their ordinary editing and copy protections. +Key-taking launcher panels retain winit's input view/delegate and use the window +input path; overlays and Wayland layer surfaces also forward physical input. + +## Native application and Dock menus + +```rust,ignore +let app = App::new(spec) + .menu_item(MenuItem::new("Open Quick Panel", open_panel).id("quick") + .key_equivalent("cmd+shift+space".parse()?)) + .menu_item(MenuItem::new("Preferences", preferences).menu("Tools")) + .menu_item(MenuItem::new("Open Quick Panel", open_panel).id("dock-quick").dock()) + .menu_item(MenuItem::new("New Window", new_window).menu("File")) + .menu_item(MenuItem::separator().menu("File")) + .menu_item(MenuItem::new("Close Tab", close_tab).menu("File")); + +handle.set_menu([ + MenuItem::new("Open Quick Panel", open_panel).id("quick") + .enabled(true).checked(true), +])?; +``` + +Actions are `fn(&mut S, &mut Tx)` queued on the app thread. `set_menu` replaces all +custom items for that App; an empty list removes them. It validates atomically and +queues installation. `take_menu_errors()` reports deferred startup/installation +errors. Replaced, disabled or removed items invalidate stale queued actions. +`MenuItem::separator()` is a separator line (`NSMenuItem.separatorItem` on macOS), placed +with `menu` or `dock` in list order like any item. It needs no id, takes no part in +id/title lookup and can't be fired. + +On macOS, one App owns the process-wide custom menus. Default Quit/Hide items and +existing named-menu items are preserved. The Dock adapter adds an absent +`applicationDockMenu:` selector to winit's existing delegate class, retaining the +delegate and all existing methods. An existing non-Rune selector is an error; the +Rune hook returns nil after teardown. Key equivalents are native menu equivalents, +not global registrations. AppKit matches them by the character typed, so an item's +equivalent is the character its accelerator names: `cmd+b` is "b" with ⌘ on every +layout, `cmd+shift+=` is "=" with ⇧⌘, and named keys use AppKit's characters (↩ ⇥ ⎋ ⌫ ⌦, +arrows, F-keys). App menu, named menus, Dock and context menus all show the same key. +When two items in the menu bar share an equivalent, AppKit gives it to the first and +the later one shows none, so one key never runs two items. Rune never sets the +function-key flag; the 🌐F in a menu titled View is AppKit's own Enter Full Screen. + +An accessory app that calls `set_dock_icon(true)` gets winit's standard app menu +if `NSApp.mainMenu` is absent: About, Services, Hide, Hide Others, Show All and Quit. +Creating custom menu items first uses that same default root; adding them later +inserts alongside the defaults. Existing roots are never replaced, and clearing +custom items or calling `set_dock_icon(false)` leaves the default menu intact. +A regular app whose menu bar is still winit's default also gets the standard items +below; an accessory app gets them only with `standard_menus()`. + +### Standard menus + +`App::standard_menus()` adds an Edit menu (Undo ⌘Z, Redo ⇧⌘Z, Cut ⌘X, Copy ⌘C, Paste +⌘V, Select All ⌘A) and a Window menu (Minimize ⌘M, Close ⌘W) to the process menu bar +when the first window of that App starts. A regular (non-accessory) app gets the same +items without asking, as long as its menu bar is still winit's default when its first +window starts; an app that set its own menu bar is left alone. Rune never adds Quit: +an accessory app that later shows its Dock icon gets winit's app menu (with Quit) as +before. Items go into existing menus of the same title, an item whose action is +already there is skipped, and custom `MenuItem`s keep working in either order. A +custom item with a standard item's equivalent (Close Tab ⌘W) takes it: the standard +item shows none until the custom one goes, whichever was set first. New custom menus +take the Mac order: File before Edit, the app's other menus before Window, Help last. +Clearing custom items keeps a menu the standard items share. An accessory app's menu +bar is hidden, but AppKit still matches its key equivalents. + +Every item has a nil target, so AppKit sends it to the key window's first responder: + +- An AppKit window in the process (an open panel, an updater's window) gets the + normal `copy:`, `paste:`, `selectAll:`, `undo:`, `performMiniaturize:` and + `performClose:` of its focused field or window. +- A Rune window's first responder is winit's view. AppKit consumes a matched key + equivalent even when no responder implements its action, which is why a plain Edit + menu would swallow ⌘C before Rune sees it. So the view gains the eight actions (added + to winit's view class, never replacing a method it has), and each hands Rune the key: + the very event that fired the item, so text fields, `on_key` and shortcuts see exactly + the `Key::Command` they did without the menu, once. A click on the item sends a + made-up press and release of its key instead. +- An IME composition (or a dead key's accent) in the focused field ends first, as in an + NSTextView: the input method commits it into the field, then the command acts. One + that doesn't commit is dropped, so the key still reaches Rune. +- ⌘W and ⌘M reach Rune the same way first. If no handler takes them and the window has + that title-bar button, the window then closes or minimizes as a click on the button + would: `on_close` and `keep_running` hiding apply. A window without the button + (borderless, an overlay or nonactivating panel) only gets the key. An app that binds ⌘W itself keeps it. + +Without `standard_menus`, an accessory app's keys don't change. + +Native Windows/Linux return `MenuError::Unsupported`; startup builders report it +through `take_menu_errors()`. Headless virtual menus work on every platform: +`{"menu":"Open Quick Panel"}` invokes by exact id or unambiguous title. Unknown, +disabled and ambiguous items fail the script. + +`scripts/check-native-menu-macos.py <menu_probe>` exercises the app-menu click, +key equivalent, named-menu click, runtime enabled/checked updates, preservation of +Quit/Hide and the Dock delegate selector on a GUI test Mac, under the same lock. +`scripts/check-dock-menu-macos.py <dock_menu_probe>` checks the accessory-to-Regular +default menu in both orders. `scripts/menu.json` exercises title/id dispatch headlessly. diff --git a/app/vendor/rune/crates/rune/src/shortcuts/keys.rs b/app/vendor/rune/crates/rune/src/shortcuts/keys.rs new file mode 100644 index 0000000..70cd777 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/shortcuts/keys.rs @@ -0,0 +1,150 @@ +//! Stable physical key names. Display text is a separate, layout-dependent operation. +use super::{Shortcut, ShortcutError, parse::{ALT, CTRL, SHIFT, SUPER}}; +pub use winit::keyboard::KeyCode as PhysicalKeyCode; + +const KEYS: &[(PhysicalKeyCode, &str)] = { + use PhysicalKeyCode::*; + &[ + (KeyA,"a"),(KeyB,"b"),(KeyC,"c"),(KeyD,"d"),(KeyE,"e"),(KeyF,"f"),(KeyG,"g"),(KeyH,"h"), + (KeyI,"i"),(KeyJ,"j"),(KeyK,"k"),(KeyL,"l"),(KeyM,"m"),(KeyN,"n"),(KeyO,"o"),(KeyP,"p"), + (KeyQ,"q"),(KeyR,"r"),(KeyS,"s"),(KeyT,"t"),(KeyU,"u"),(KeyV,"v"),(KeyW,"w"),(KeyX,"x"),(KeyY,"y"),(KeyZ,"z"), + (Digit0,"0"),(Digit1,"1"),(Digit2,"2"),(Digit3,"3"),(Digit4,"4"),(Digit5,"5"),(Digit6,"6"),(Digit7,"7"),(Digit8,"8"),(Digit9,"9"), + (F1,"f1"),(F2,"f2"),(F3,"f3"),(F4,"f4"),(F5,"f5"),(F6,"f6"),(F7,"f7"),(F8,"f8"),(F9,"f9"),(F10,"f10"), + (F11,"f11"),(F12,"f12"),(F13,"f13"),(F14,"f14"),(F15,"f15"),(F16,"f16"),(F17,"f17"),(F18,"f18"),(F19,"f19"),(F20,"f20"), + (F21,"f21"),(F22,"f22"),(F23,"f23"),(F24,"f24"), + (Escape,"escape"),(Enter,"enter"),(Space,"space"),(Tab,"tab"),(Backspace,"backspace"),(Delete,"delete"),(Insert,"insert"), + (Home,"home"),(End,"end"),(PageUp,"pageup"),(PageDown,"pagedown"),(ArrowLeft,"left"),(ArrowRight,"right"),(ArrowUp,"up"),(ArrowDown,"down"), + (Minus,"minus"),(Equal,"equal"),(Comma,"comma"),(Period,"period"),(Slash,"slash"),(Semicolon,"semicolon"),(Quote,"quote"), + (BracketLeft,"bracketleft"),(BracketRight,"bracketright"),(Backslash,"backslash"),(Backquote,"backquote"), + ] +}; + +pub(super) fn named(name: &str) -> Option<PhysicalKeyCode> { KEYS.iter().find(|(_, n)| *n == name).map(|(key, _)| *key) } +pub(super) fn name(key: PhysicalKeyCode) -> Option<&'static str> { KEYS.iter().find(|(k, _)| *k == key).map(|(_, name)| *name) } + +impl Shortcut { + /// Build from the hardware key reported by the window, never its typed/logical character. + /// Modifiers alone do not form a registerable shortcut. + pub fn from_physical_key(key: PhysicalKeyCode, mods: crate::Mods) -> Result<Self, ShortcutError> { + name(key).ok_or_else(|| ShortcutError::InvalidAccelerator(format!("{key:?}")))?; + let mut bits = 0; + if mods.ctrl || (!cfg!(target_os = "macos") && mods.cmd) { bits |= CTRL; } + if mods.alt { bits |= ALT; } + if mods.shift { bits |= SHIFT; } + if mods.logo || (cfg!(target_os = "macos") && mods.cmd) { bits |= SUPER; } + Ok(Self { key, mods: bits }) + } + + pub fn physical_key(&self) -> PhysicalKeyCode { self.key } + + /// Refuses a chord that would take its key from typing everywhere: no ⌘, ⌃ or ⌥ (Ctrl, + /// Alt or Super elsewhere) on a key other than F1–F24. Shift alone isn't enough. Global + /// registration applies it unless `App::allow_unmodified_shortcuts`. + pub fn require_modifier(&self) -> Result<(), ShortcutError> { + let function = self.key_name().strip_prefix('f').is_some_and(|n| !n.is_empty()); + if function || self.mods & (CTRL | ALT | SUPER) != 0 { return Ok(()); } + let names = if cfg!(target_os = "macos") { "⌘, ⌃ or ⌥" } else { "Ctrl, Alt or Super" }; + Err(ShortcutError::InvalidAccelerator(format!("{self} needs {names}"))) + } + + pub fn modifiers(&self) -> crate::Mods { + crate::Mods { ctrl: self.mods & CTRL != 0, alt: self.mods & ALT != 0, shift: self.mods & SHIFT != 0, + logo: self.mods & SUPER != 0, cmd: self.mods & if cfg!(target_os = "macos") { SUPER } else { CTRL } != 0 } + } + + pub(super) fn key_name(&self) -> &'static str { name(self.key).expect("validated physical shortcut key") } + + /// Whether `ev` is this chord, for a window that handles it without a menu: letter and + /// digit keys only. + pub(crate) fn matches_key(&self, ev: &crate::KeyEvent) -> bool { + let (want, m) = (self.modifiers(), ev.mods); + let logo = cfg!(target_os = "macos") || want.logo == m.logo; + if want.shift != m.shift || want.alt != m.alt || want.cmd != m.cmd || want.ctrl != m.ctrl || !logo { return false; } + let name = self.key_name(); + match &ev.key { + crate::Key::Command(c) => name.len() == 1 && name.starts_with(c.to_ascii_lowercase()), + crate::Key::Text(t) => name.len() == 1 && name.eq_ignore_ascii_case(t), + _ => false, + } + } + + /// Human-facing keycaps, ending in the key: a capital letter or symbol ("K", "/"), or a + /// name ("Space", "F5"; glyphs such as ↩ ⇥ ⎋ ⌫ on macOS). macOS translates the physical key + /// using the current keyboard layout on the UI thread, under the chord's ⌘ and ⌃ (some + /// layouts change while they're held); elsewhere (or when layout data is unavailable) + /// these are US labels. Persist Display/FromStr, not these labels. A menu shows + /// `menu_keycaps` instead. + pub fn keycaps(&self) -> Vec<String> { + let mut labels = modifier_keycaps(self.modifiers()); + labels.push(self.key_label()); + labels + } + + /// Keycaps as a menu shows this chord: the key the accelerator names, on every layout. + /// "cmd+b" is ⌘B on Dvorak too, where AppKit matches the menu item by the typed "b", not + /// by the key in QWERTY's B position (which types "x" there). Use these for menu items + /// and for hints of keys an app matches by character; `keycaps` for a global shortcut, + /// which follows the key's position. + pub fn menu_keycaps(&self) -> Vec<String> { + let mut labels = modifier_keycaps(self.modifiers()); + let name = self.key_name(); + labels.push(crate::input::key_table::shortcut_named_label(name) + .unwrap_or_else(|| crate::input::key_table::capital_keycap(us_label(name)))); + labels + } + + fn key_label(&self) -> String { + let name = self.key_name(); + if let Some(label) = crate::input::key_table::shortcut_named_label(name) { return label; } + #[cfg(target_os = "macos")] + if let Some(label) = super::macos::keycode(name) + .and_then(|key| super::layout_macos::label(key, super::macos::carbon_mods(self))) { + return crate::input::key_table::capital_keycap(&label); + } + crate::input::key_table::capital_keycap(us_label(name)) + } +} + +/// Keycaps for a chord being held, before a non-modifier key has been pressed. +pub fn modifier_keycaps(mods: crate::Mods) -> Vec<String> { + crate::input::key_table::modifier_keycaps(mods) +} + +/// The character `key` types unshifted on a US layout: 'a', '7', '['. None for keys that type +/// no single printable character (F1, Space, arrows). +pub(crate) fn us_char(key: PhysicalKeyCode) -> Option<char> { + let mut chars = us_label(name(key)?).chars(); + chars.next().filter(|_| chars.next().is_none()) +} + +fn us_label(name: &str) -> &str { + crate::input::key_table::punctuation_symbol(name).unwrap_or(name) +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn physical_storage_roundtrips_every_supported_key() { + for &(key, _) in KEYS { + let shortcut = Shortcut::from_physical_key(key, crate::Mods { ctrl: true, shift: true, ..Default::default() }).unwrap(); + assert_eq!(shortcut.to_string().parse::<Shortcut>().unwrap().physical_key(), key); + assert_eq!(shortcut.physical_key(), key); + } + assert!(Shortcut::from_physical_key(PhysicalKeyCode::ShiftLeft, crate::Mods::default()).is_err()); + } + + #[test] + fn keycaps_capitalize_characters_and_name_keys() { + let key = |s: &str| s.parse::<Shortcut>().unwrap().keycaps().pop().unwrap(); + assert_eq!(key("ctrl+space"), "Space"); + assert_eq!(key("ctrl+f5"), "F5"); + assert_eq!(key("ctrl+left"), "←"); + assert_eq!(key("ctrl+enter"), if cfg!(target_os = "macos") { "↩" } else { "Return" }); + assert_eq!(crate::input::key_table::capital_keycap("k"), "K"); + assert_eq!(crate::input::key_table::capital_keycap("ß"), "ß"); + assert_eq!(crate::input::key_table::capital_keycap("ı"), "ı"); + assert_eq!(crate::input::key_table::capital_keycap("K"), "K"); + assert_eq!(crate::input::key_table::capital_keycap("/"), "/"); + } +} diff --git a/app/vendor/rune/crates/rune/src/shortcuts/layout_macos.rs b/app/vendor/rune/crates/rune/src/shortcuts/layout_macos.rs new file mode 100644 index 0000000..3b2213d --- /dev/null +++ b/app/vendor/rune/crates/rune/src/shortcuts/layout_macos.rs @@ -0,0 +1,94 @@ +//! Translate only display labels. The input source is borrowed for one call and never changed. + +#![allow(unsafe_code)] + +use std::ffi::c_void; + +#[link(name = "Carbon", kind = "framework")] +unsafe extern "C" { + fn TISCopyCurrentKeyboardLayoutInputSource() -> *const c_void; + fn TISGetInputSourceProperty(source: *const c_void, key: *const c_void) -> *const c_void; + static kTISPropertyUnicodeKeyLayoutData: *const c_void; + fn LMGetKbdType() -> u8; + fn UCKeyTranslate(layout: *const c_void, key: u16, action: u16, modifiers: u32, + keyboard_type: u32, options: u32, dead: *mut u32, capacity: usize, + length: *mut usize, chars: *mut u16) -> i32; +} +#[link(name = "CoreFoundation", kind = "framework")] +unsafe extern "C" { + fn CFDataGetBytePtr(data: *const c_void) -> *const u8; + fn CFRelease(value: *const c_void); +} +unsafe extern "C" { fn pthread_main_np() -> i32; } + +struct Source(*const c_void); +impl Drop for Source { + fn drop(&mut self) { + // SAFETY: `self.0` is a non-null retained `TISInputSourceRef` from `TISCopyCurrentKeyboardLayoutInputSource`, released once on drop. + unsafe { CFRelease(self.0) }; + } +} + +#[cfg(test)] +thread_local! { + static FORCED: std::cell::Cell<Option<fn(u32, u32) -> Option<String>>> = const { std::cell::Cell::new(None) }; +} +/// Tests: translate labels on this thread with `layout` (Carbon key, modifiers) instead of +/// the current input source, or stop with `None`. +#[cfg(test)] +#[allow(dead_code)] +pub(crate) fn force(layout: Option<fn(u32, u32) -> Option<String>>) { FORCED.with(|forced| forced.set(layout)); } + +/// The label for `key` pressed with Carbon `modifiers` (`cmdKey`, `shiftKey`, ...). +pub(super) fn label(key: u32, modifiers: u32) -> Option<String> { + #[cfg(test)] + if let Some(layout) = FORCED.with(std::cell::Cell::get) { return layout(key, modifiers); } + // AppKit also calls TIS. A private mutex cannot serialize with it; stay on the + // UI thread. Background/headless callers get the documented US fallback. + // SAFETY: `pthread_main_np` takes no arguments and is safe to call from any thread. + if unsafe { pthread_main_np() } == 0 { return None; } + // SAFETY: on the main thread (checked above); `TISCopyCurrentKeyboardLayoutInputSource` returns + // a retained source wrapped in `Source` so `layout` stays valid for `chord_label`. + unsafe { + let source = TISCopyCurrentKeyboardLayoutInputSource(); + if source.is_null() { return None; } + let source = Source(source); + let data = TISGetInputSourceProperty(source.0, kTISPropertyUnicodeKeyLayoutData); + if data.is_null() { return None; } + let layout = CFDataGetBytePtr(data); + if layout.is_null() { return None; } + chord_label(layout.cast(), key, modifiers) + } +} + +const CMD: u32 = 1 << 8; +const CONTROL: u32 = 1 << 12; + +/// The character a menu shows for `key` in a chord with Carbon `modifiers`. Some input sources +/// switch layout while a modifier is held ("Dvorak – QWERTY ⌘" is QWERTY under ⌘), so ⌘ and ⌃ +/// pick the layout's table. ⇧ and ⌥ don't: like an AppKit key equivalent, the label is the +/// base key (⌥⌘K, not ⌥⌘˚). ⌃ tables usually hold control characters; those fall back to the +/// table without ⌃, then the base table. +/// +/// The layout must point to live TIS Unicode layout data, on the main thread. +pub(super) unsafe fn chord_label(layout: *const c_void, key: u32, modifiers: u32) -> Option<String> { + let modifiers = modifiers & (CMD | CONTROL); + // SAFETY: caller guarantees `layout` points to live TIS Unicode layout data on the main thread. + [modifiers, modifiers & !CONTROL, 0].into_iter().find_map(|state| unsafe { translate(layout, key, state) }) +} + +/// The layout must point to live TIS Unicode layout data, on the main thread. +pub(super) unsafe fn translate(layout: *const c_void, key: u32, modifiers: u32) -> Option<String> { + let mut chars = [0u16; 16]; + let mut length = 0usize; + let mut dead = 0; + // kUCKeyActionDisplay, kUCKeyTranslateNoDeadKeysMask. UCKeyTranslate takes Carbon + // modifiers shifted down a byte. + // SAFETY: caller guarantees `layout` is valid TIS layout data on the main thread; `dead`, + // `length`, and `chars` are live, writable output buffers matching `chars.len()`. + let status = unsafe { UCKeyTranslate(layout, key as u16, 3, (modifiers >> 8) & 0xff, LMGetKbdType() as u32, + 1, &mut dead, chars.len(), &mut length, chars.as_mut_ptr()) }; + if status != 0 || length == 0 || length > chars.len() { return None; } + let label = String::from_utf16(&chars[..length]).ok()?; + (!label.chars().any(char::is_control)).then_some(label) +} diff --git a/app/vendor/rune/crates/rune/src/shortcuts/macos.rs b/app/vendor/rune/crates/rune/src/shortcuts/macos.rs new file mode 100644 index 0000000..8c5822b --- /dev/null +++ b/app/vendor/rune/crates/rune/src/shortcuts/macos.rs @@ -0,0 +1,249 @@ +//! Carbon hotkeys do not require Accessibility or Input Monitoring permission. + +#![allow(unsafe_code)] + +use super::{Backend, Shortcut, ShortcutError, ShortcutId, Sink, native_status, parse::*}; +use objc2_core_foundation::{CFArray, CFBoolean, CFDictionary, CFNumber, CFPreferencesCopyAppValue, CFRetained, CFString, CFType}; +use std::{cell::RefCell, collections::HashMap, ffi::c_void, ptr}; + +type Ref = *mut c_void; +#[repr(C, packed(2))] +#[derive(Clone, Copy)] +struct HotKeyId { signature: u32, id: u32 } +#[repr(C, packed(2))] +struct EventType { class: u32, kind: u32 } +const SIGNATURE: u32 = u32::from_be_bytes(*b"rune"); +const KEYBOARD: u32 = u32::from_be_bytes(*b"keyb"); +const EXISTS: i64 = -9878; +const NOT_HANDLED: i32 = -9874; +// Without this flag Carbon permits another process to register the same combination. +const EXCLUSIVE: u32 = 1; + +#[link(name = "Carbon", kind = "framework")] +unsafe extern "C" { + fn GetApplicationEventTarget() -> Ref; + fn InstallEventHandler(target: Ref, handler: unsafe extern "C" fn(Ref, Ref, Ref) -> i32, count: usize, types: *const EventType, data: Ref, out: *mut Ref) -> i32; + fn RemoveEventHandler(handler: Ref) -> i32; + fn RegisterEventHotKey(code: u32, mods: u32, id: HotKeyId, target: Ref, options: u32, out: *mut Ref) -> i32; + fn UnregisterEventHotKey(hotkey: Ref) -> i32; + fn GetEventParameter(event: Ref, name: u32, ty: u32, actual: *mut u32, size: usize, actual_size: *mut usize, data: Ref) -> i32; +} + +struct Context { sink: Sink, keys: RefCell<HashMap<ShortcutId, Ref>> } +pub(super) struct Native { handler: Ref, context: Box<Context> } + +unsafe extern "C" fn activated(_: Ref, event: Ref, data: Ref) -> i32 { + // SAFETY: Carbon only calls this while the installed handler and its boxed context live. + // The application event target delivers callbacks on the registration/main thread. + unsafe { + let mut id = HotKeyId { signature: 0, id: 0 }; + if GetEventParameter(event, u32::from_be_bytes(*b"----"), u32::from_be_bytes(*b"hkid"), ptr::null_mut(), + std::mem::size_of::<HotKeyId>(), ptr::null_mut(), (&mut id as *mut HotKeyId).cast()) != 0 || id.signature != SIGNATURE { + return NOT_HANDLED; + } + let context = &*data.cast::<Context>(); + if !context.keys.borrow().contains_key(&ShortcutId(id.id)) { return NOT_HANDLED; } + // Never unwind across Carbon. Application handlers themselves run later, in Rune. + std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| (context.sink)(ShortcutId(id.id), None))).ok(); + 0 + } +} + +impl Native { + pub(super) fn new(sink: Sink) -> Result<Self, ShortcutError> { + if objc2::MainThreadMarker::new().is_none() { return Err(ShortcutError::Backend("Carbon requires the main thread".into())); } + let mut context = Box::new(Context { sink, keys: RefCell::default() }); + let mut handler = ptr::null_mut(); + // SAFETY: Context's address remains stable until after RemoveEventHandler in Drop. + native_status(unsafe { InstallEventHandler(GetApplicationEventTarget(), activated, 1, + &EventType { class: KEYBOARD, kind: 5 }, (&mut *context as *mut Context).cast(), &mut handler) }.into(), EXISTS)?; + Ok(Self { handler, context }) + } +} + +impl Backend for Native { + fn register(&mut self, id: ShortcutId, shortcut: &Shortcut) -> Result<(), ShortcutError> { + let code = keycode(shortcut.key_name()).ok_or_else(|| ShortcutError::InvalidAccelerator(shortcut.to_string()))?; + let mods = carbon_mods(shortcut); + let mut hotkey = ptr::null_mut(); + // SAFETY: On the main thread; pointers are valid output slots and target is Carbon-owned. + native_status(unsafe { RegisterEventHotKey(code, mods, HotKeyId { signature: SIGNATURE, id: id.0 }, + GetApplicationEventTarget(), EXCLUSIVE, &mut hotkey) }.into(), EXISTS)?; + self.context.keys.borrow_mut().insert(id, hotkey); + Ok(()) + } + fn unregister(&mut self, id: ShortcutId) -> Result<(), ShortcutError> { + let hotkey = *self.context.keys.borrow().get(&id).ok_or(ShortcutError::UnknownId)?; + // SAFETY: This registration is owned by this backend and has not been released. + native_status(unsafe { UnregisterEventHotKey(hotkey) }.into(), EXISTS)?; + self.context.keys.borrow_mut().remove(&id); + Ok(()) + } +} + +impl Drop for Native { + fn drop(&mut self) { + // SAFETY: Registrations and handler are owned here, on the app thread. Removing the + // handler before freeing Context prevents callbacks with a dangling user-data pointer. + unsafe { + for (_, hotkey) in self.context.keys.get_mut().drain() { UnregisterEventHotKey(hotkey); } + RemoveEventHandler(self.handler); + } + } +} + +const CMD: u32 = 1 << 8; +const SHIFT_KEY: u32 = 1 << 9; +const OPTION: u32 = 1 << 11; +const CONTROL: u32 = 1 << 12; +pub(super) fn carbon_mods(shortcut: &Shortcut) -> u32 { + [(SUPER, CMD), (SHIFT, SHIFT_KEY), (ALT, OPTION), (CTRL, CONTROL)].into_iter() + .filter(|(bit, _)| shortcut.mods & bit != 0).fold(0, |mods, (_, carbon)| mods | carbon) +} + +#[link(name = "Carbon", kind = "framework")] +unsafe extern "C" { + fn CopySymbolicHotKeys(out: *mut *const CFArray) -> i32; +} + +/// Default system shortcuts that can be named: (com.apple.symbolichotkeys id holding a user's +/// remapping, Carbon key code, Carbon modifiers, owner). The app switcher cannot be remapped. +const SYSTEM: &[(Option<&str>, u32, u32, &str)] = &[ + (Some("64"), 49, CMD, "Spotlight"), + (Some("65"), 49, CMD | OPTION, "Finder search"), + (Some("60"), 49, CONTROL, "Input Sources"), + (Some("61"), 49, CONTROL | OPTION, "Input Sources"), + (Some("28"), 20, CMD | SHIFT_KEY, "Screenshot"), + (Some("29"), 20, CONTROL | CMD | SHIFT_KEY, "Screenshot"), + (Some("30"), 21, CMD | SHIFT_KEY, "Screenshot"), + (Some("31"), 21, CONTROL | CMD | SHIFT_KEY, "Screenshot"), + (Some("184"), 23, CMD | SHIFT_KEY, "Screenshot"), + (Some("32"), 126, CONTROL, "Mission Control"), + (Some("33"), 125, CONTROL, "Mission Control"), + (Some("79"), 123, CONTROL, "Mission Control"), + (Some("81"), 124, CONTROL, "Mission Control"), + (None, 48, CMD, "App Switcher"), + (None, 48, CMD | SHIFT_KEY, "App Switcher"), +]; +const MODS: u32 = CMD | SHIFT_KEY | OPTION | CONTROL; + +/// An enabled macOS symbolic hotkey on this chord: its name when it is a known shortcut assigned +/// there (by default or remapped), otherwise "macOS". None off the main thread (HIToolbox). +pub(super) fn system_owner(shortcut: &Shortcut) -> Option<String> { + objc2::MainThreadMarker::new()?; + let chord = (keycode(shortcut.key_name())?, carbon_mods(shortcut)); + if !enabled_symbolic().contains(&chord) { return None; } + Some(named(chord, &remapped()).unwrap_or("macOS").into()) +} + +/// The known shortcut whose effective chord is this one: the user's remapping, else its default. +fn named(chord: (u32, u32), remapped: &[(&str, Option<(u32, u32)>)]) -> Option<&'static str> { + SYSTEM.iter().find(|(id, code, mods, _)| { + let remap = id.and_then(|id| remapped.iter().find(|(r, _)| *r == id)); + remap.map_or(Some((*code, *mods)), |(_, at)| *at) == Some(chord) + }).map(|(.., name)| *name) +} + +/// Carbon's effective symbolic hotkeys, defaults included, as (key code, modifiers). +fn enabled_symbolic() -> Vec<(u32, u32)> { + let mut array = ptr::null(); + // SAFETY: Copy rule: a successful call returns a retained array, released by CFRetained. + let array = unsafe { + if CopySymbolicHotKeys(&mut array) != 0 { return Vec::new(); } + let Some(array) = ptr::NonNull::new(array.cast_mut()) else { return Vec::new() }; + CFRetained::from_raw(array) + }; + // SAFETY: Each element is a CFDictionary keyed by CFStrings, per HIToolbox's documentation. + let array = unsafe { array.cast_unchecked::<CFDictionary<CFString, CFType>>() }; + let number = |d: &CFDictionary<CFString, CFType>, key: &CFString| d.get(key) + .and_then(|v| v.downcast::<CFNumber>().ok()).and_then(|n| n.as_i64()); + // HIToolbox defines these keys as CFSTR literals, not exported symbols. + let [code, mods, enabled] = ["kHISymbolicHotKeyCode", "kHISymbolicHotKeyModifiers", "kHISymbolicHotKeyEnabled"].map(CFString::from_str); + let (code, mods) = (&*code, &*mods); + array.iter().filter(|d| d.get(&enabled).and_then(|v| v.downcast::<CFBoolean>().ok()).is_some_and(|b| b.as_bool())) + .filter_map(|d| Some((u32::try_from(number(&d, code)?).ok()?, number(&d, mods)? as u32 & MODS))).collect() +} + +/// The user's remappings of the named ids: id and its chord now, None when unassigned or disabled. +fn remapped() -> Vec<(&'static str, Option<(u32, u32)>)> { + let Some(all) = CFPreferencesCopyAppValue(&CFString::from_str("AppleSymbolicHotKeys"), + &CFString::from_str("com.apple.symbolichotkeys")).and_then(|v| v.downcast::<CFDictionary>().ok()) else { return Vec::new() }; + // SAFETY: The preference is a property list: string keys, dictionary or other values. + let all = unsafe { all.cast_unchecked::<CFString, CFType>() }; + let dict = |v: CFRetained<CFType>| v.downcast::<CFDictionary>().ok(); + SYSTEM.iter().filter_map(|(id, ..)| { + let id = (*id)?; + let entry = dict(all.get(&CFString::from_str(id))?)?; + // SAFETY: As above, a property-list dictionary. + let entry = unsafe { entry.cast_unchecked::<CFString, CFType>() }; + let enabled = entry.get(&CFString::from_str("enabled")).and_then(|v| v.downcast::<CFBoolean>().ok()).map(|b| b.as_bool()); + let parameters = entry.get(&CFString::from_str("value")).and_then(dict).and_then(|value| { + // SAFETY: As above, a property-list dictionary. + unsafe { value.cast_unchecked::<CFString, CFType>() }.get(&CFString::from_str("parameters"))?.downcast::<CFArray>().ok() + }); + // SAFETY: parameters is (character, key code, NSEvent modifier flags) as CFNumbers. + let parameters = parameters.as_deref().map(|p| unsafe { p.cast_unchecked::<CFType>() }); + let at = |i| parameters?.get(i).and_then(|v| v.downcast::<CFNumber>().ok()).and_then(|n| n.as_i64()); + Some((id, remap(enabled, at(1), at(2))?)) + }).collect() +} + +/// A remap entry's chord: None (unassigned) when disabled or its key code is 65535; no remap +/// (outer None) when an enabled entry carries no chord. +fn remap(enabled: Option<bool>, code: Option<i64>, flags: Option<i64>) -> Option<Option<(u32, u32)>> { + if enabled == Some(false) { return Some(None); } + let (code, flags) = (code?, flags?); + Some((code != 65535).then(|| (code as u32, ns_event_mods(flags as u32)))) +} + +fn ns_event_mods(flags: u32) -> u32 { + [(1 << 17, SHIFT_KEY), (1 << 18, CONTROL), (1 << 19, OPTION), (1 << 20, CMD)].into_iter() + .filter(|(bit, _)| flags & bit != 0).fold(0, |mods, (_, carbon)| mods | carbon) +} + +pub(super) fn keycode(key: &str) -> Option<u32> { + // Carbon virtual key codes (physical ANSI positions, matching winit KeyCode semantics). + Some(match key { + "a" => 0, "s" => 1, "d" => 2, "f" => 3, "h" => 4, "g" => 5, "z" => 6, "x" => 7, "c" => 8, "v" => 9, + "b" => 11, "q" => 12, "w" => 13, "e" => 14, "r" => 15, "y" => 16, "t" => 17, + "1" => 18, "2" => 19, "3" => 20, "4" => 21, "6" => 22, "5" => 23, "equal" => 24, "9" => 25, + "7" => 26, "minus" => 27, "8" => 28, "0" => 29, "bracketright" => 30, "o" => 31, "u" => 32, + "bracketleft" => 33, "i" => 34, "p" => 35, "enter" => 36, "l" => 37, "j" => 38, "quote" => 39, + "k" => 40, "semicolon" => 41, "backslash" => 42, "comma" => 43, "slash" => 44, "n" => 45, + "m" => 46, "period" => 47, "tab" => 48, "space" => 49, "backquote" => 50, "backspace" => 51, "escape" => 53, + "f17" => 64, "f18" => 79, "f19" => 80, "f20" => 90, "f5" => 96, "f6" => 97, "f7" => 98, "f3" => 99, + "f8" => 100, "f9" => 101, "f11" => 103, "f13" => 105, "f16" => 106, "f14" => 107, "f10" => 109, + "f12" => 111, "f15" => 113, "insert" => 114, "home" => 115, "pageup" => 116, "delete" => 117, + "f4" => 118, "end" => 119, "f2" => 120, "pagedown" => 121, "f1" => 122, + "left" => 123, "right" => 124, "down" => 125, "up" => 126, + _ => return None, + }) +} + +#[cfg(test)] +mod tests { + #[test] + fn preference_modifiers_map_to_carbon_and_drop_fn() { + use super::*; + assert_eq!(ns_event_mods(1_179_648), CMD | SHIFT_KEY); + assert_eq!(ns_event_mods(8_650_752), CONTROL); + assert_eq!(ns_event_mods(786_432), CONTROL | OPTION); + } + + #[test] + fn a_remapped_system_shortcut_is_named_at_its_new_chord_only() { + use super::*; + // Spotlight (id 64) moved from ⌘Space to ⌃⌥⌘K. + let moved = remap(Some(true), Some(40), Some(1_835_008)).unwrap(); + assert_eq!(moved, Some((40, CMD | OPTION | CONTROL))); + assert_eq!(named((40, CMD | OPTION | CONTROL), &[("64", moved)]), Some("Spotlight")); + assert_eq!(named((49, CMD), &[("64", moved)]), None); + assert_eq!(named((49, CMD), &[]), Some("Spotlight")); + // Disabled or unassigned: no chord, so the default no longer names it. + assert_eq!(remap(Some(false), Some(49), Some(1_048_576)), Some(None)); + assert_eq!(remap(None, Some(65535), Some(0)), Some(None)); + assert_eq!(named((49, CMD), &[("64", None)]), None); + // An enabled entry without parameters is no remap. + assert_eq!(remap(Some(true), None, None), None); + } +} diff --git a/app/vendor/rune/crates/rune/src/shortcuts/mod.rs b/app/vendor/rune/crates/rune/src/shortcuts/mod.rs new file mode 100644 index 0000000..aacb080 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/shortcuts/mod.rs @@ -0,0 +1,158 @@ +//! System-wide shortcuts. Native registrations belong to the app's event-loop thread. +//! Nothing connects to the desktop until the first registration. +mod parse; +mod keys; +#[cfg(target_os = "macos")] +mod layout_macos; +#[cfg(all(test, target_os = "macos"))] +pub(crate) use layout_macos::force as force_layout; +pub use keys::{PhysicalKeyCode, modifier_keycaps}; +pub(crate) use keys::us_char; +mod service; +#[cfg(target_os = "macos")] +mod macos; +#[cfg(target_os = "windows")] +mod windows; +#[cfg(target_os = "linux")] +mod x11; +#[cfg(any(target_os = "linux", test))] +mod x11_repeat; +#[cfg(all(target_os = "linux", feature = "dbus"))] +mod wayland; + +pub use parse::Shortcut; +pub(crate) use service::{Guard, Hub, HubCore}; +use std::sync::Arc; + +/// An opaque registration, unique within this process. It is not an accelerator hash. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub struct ShortcutId(u32); + +/// Registration failures callers can act on without inspecting platform error strings. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum ShortcutError { + Conflict, + Unsupported, + InvalidAccelerator(String), + /// Runtime registration requires a running app. Static builders work before run(). + NotRunning, + UnknownId, + /// The user declined the portal's shortcut permission dialog. + PermissionDenied, + Backend(String), +} + +impl std::fmt::Display for ShortcutError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::Conflict => f.write_str("shortcut is already registered"), + Self::Unsupported => f.write_str("global shortcuts are unsupported in this desktop session"), + Self::InvalidAccelerator(s) => write!(f, "invalid accelerator: {s}"), + Self::NotRunning => f.write_str("the shortcut's app is not running"), + Self::UnknownId => f.write_str("unknown shortcut registration"), + Self::PermissionDenied => f.write_str("shortcut permission was declined"), + Self::Backend(s) => write!(f, "shortcut backend: {s}"), + } + } +} +impl std::error::Error for ShortcutError {} + +type Sink = Arc<dyn Fn(ShortcutId, Option<String>) + Send + Sync>; +trait Backend { + fn register(&mut self, id: ShortcutId, shortcut: &Shortcut) -> Result<(), ShortcutError>; + fn unregister(&mut self, id: ShortcutId) -> Result<(), ShortcutError>; +} + +#[cfg(target_os = "linux")] +type NativeBackend = Box<dyn Backend + Send>; +#[cfg(not(target_os = "linux"))] +type NativeBackend = Box<dyn Backend>; + +fn backend(wayland: bool, sink: Sink) -> Result<NativeBackend, ShortcutError> { + let _ = wayland; + #[cfg(target_os = "macos")] + return Ok(Box::new(macos::Native::new(sink)?)); + #[cfg(target_os = "windows")] + return Ok(Box::new(windows::Native::new(sink)?)); + #[cfg(target_os = "linux")] + return if wayland { + #[cfg(feature = "dbus")] + { Ok(Box::new(wayland::Native::new(sink)?)) } + #[cfg(not(feature = "dbus"))] + { Err(ShortcutError::Unsupported) } + } else { Ok(Box::new(x11::Native::new(sink)?)) }; + #[cfg(not(any(target_os = "macos", target_os = "windows", target_os = "linux")))] + { let _ = sink; Err(ShortcutError::Unsupported) } +} + +/// The desktop's own claim on a chord. Only macOS publishes one (its symbolic hotkeys). +fn system_owner(shortcut: &Shortcut) -> Option<String> { + #[cfg(target_os = "macos")] + return macos::system_owner(shortcut); + #[cfg(not(target_os = "macos"))] + { let _ = shortcut; None } +} + +// Keep native status mapping pure so tests can inject failures without grabbing the desktop. +#[cfg(any(test, target_os = "macos", target_os = "windows"))] +fn native_status(code: i64, conflict: i64) -> Result<(), ShortcutError> { + match code { + 0 => Ok(()), + c if c == conflict => Err(ShortcutError::Conflict), + c => Err(ShortcutError::Backend(format!("native status {c}"))), + } +} + +impl<S: 'static> crate::App<S> { + /// Register when the app starts, on the same thread and state as its windows. + /// Errors are reported once to stderr and retained by `AppHandle::take_shortcut_errors`. + /// Headless scripts register virtually, without connecting to the desktop. + pub fn global_shortcut(self, accelerator: &str, handler: fn(&mut S, &mut crate::Tx)) -> Self { + self.shared.shortcuts.pending(accelerator.parse(), Arc::new(handler)); + self + } + + /// Let `global_shortcut` and `register_shortcut` take a chord without ⌘, ⌃ or ⌥ (Ctrl, Alt + /// or Super elsewhere), such as Space or ⇧A, which then can't be typed in any app. By + /// default those fail with `InvalidAccelerator`; F1–F24 are always allowed alone. + pub fn allow_unmodified_shortcuts(self) -> Self { + self.shared.shortcuts.allow_unmodified(); + self + } +} + +impl<S: 'static> crate::AppHandle<S> { + /// Register a shortcut and return the actual backend result. On the app thread this is + /// immediate; on macOS/Windows other threads wait for the loop to process the request. + /// Do not join such callers from the app thread. Linux registrations can run off-thread; + /// use a worker for Wayland consent dialogs to keep the UI responsive. Portal consent is + /// bounded to two minutes and the user may choose a different trigger. + pub fn register_shortcut(&self, shortcut: Shortcut, handler: impl Fn(&mut S, &mut crate::Tx) + Send + Sync + 'static) -> Result<ShortcutId, ShortcutError> { + self.shared.shortcuts.register(shortcut, Arc::new(handler)) + } + + /// Release a registration owned by this app. Already queued activations become no-ops. + pub fn unregister_shortcut(&self, id: ShortcutId) -> Result<(), ShortcutError> { + self.shared.shortcuts.unregister(id) + } + + /// Who holds `shortcut`, when Rune or the desktop can say: this App or another Rune App in + /// the process (its title), or on macOS a system shortcut ("Spotlight", "Mission Control", + /// "macOS" for others). None when unknown, including other apps' Carbon, Win32, X11 and + /// portal grabs, before the app runs and for chords headless runs didn't register. + /// Ask after `ShortcutError::Conflict` to name the owner in a message. + pub fn shortcut_owner(&self, shortcut: &Shortcut) -> Option<String> { + self.shared.shortcuts.owner(shortcut) + } + + /// Drain startup registration failures. Runtime methods return their errors directly. + pub fn take_shortcut_errors(&self) -> Vec<ShortcutError> { + self.shared.shortcuts.errors() + } +} + +impl crate::Tx { + /// Wayland's compositor-issued token for this shortcut activation. Forward it to + /// `AppHandle::activate(token)` to show and focus the quick panel. None on other backends. + pub fn activation_token(&self) -> Option<&str> { self.shortcut_activation_token.as_deref() } +} diff --git a/app/vendor/rune/crates/rune/src/shortcuts/parse.rs b/app/vendor/rune/crates/rune/src/shortcuts/parse.rs new file mode 100644 index 0000000..57de826 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/shortcuts/parse.rs @@ -0,0 +1,123 @@ +use super::ShortcutError; +use std::{fmt, str::FromStr}; + +pub(super) const CTRL: u8 = 1; +pub(super) const ALT: u8 = 2; +pub(super) const SHIFT: u8 = 4; +pub(super) const SUPER: u8 = 8; +const PRIMARY_NAME: u8 = 16; + +/// A validated, layout-independent accelerator. cmd/command/logo/meta/win are aliases for +/// super; option/opt is alt; mod (primary) is super on macOS and ctrl elsewhere, as in a +/// [`Chord`](crate::Chord), and is stored as that key; plus is the key that types "+" on a US +/// layout (equal). Stored keys are physical US positions. Windows resolves these to virtual +/// keys at registration; Wayland's portal may rebind the preferred trigger. +/// Display uses ctrl+alt+shift+super order, lowercase keys and normalized aliases. +#[derive(Clone, Debug, PartialEq, Eq, Hash)] +pub struct Shortcut { + pub(super) mods: u8, + pub(super) key: super::PhysicalKeyCode, +} + +impl FromStr for Shortcut { + type Err = ShortcutError; + fn from_str(input: &str) -> Result<Self, Self::Err> { Self::parse_on(input, crate::KeyPlatform::current()) } +} + +impl Shortcut { + /// `str::parse` with `mod` resolved for `platform`: super on macOS, ctrl elsewhere. + pub fn parse_on(input: &str, platform: crate::KeyPlatform) -> Result<Self, ShortcutError> { + let invalid = || ShortcutError::InvalidAccelerator(input.into()); + let mut mods = 0; + // Names given, to refuse a repeat; "mod" is its own name, so "mod+ctrl" is ⌃⌘ on + // macOS and Ctrl elsewhere rather than an error on one platform. + let mut named = 0u8; + let mut key = None; + for part in input.split('+') { + let part = part.trim().to_ascii_lowercase(); + if let Some(m) = crate::input::key_table::modifier_named(&part) { + let (name, modifier) = match m { + crate::ChordMod::Ctrl => (CTRL, CTRL), + crate::ChordMod::Alt => (ALT, ALT), + crate::ChordMod::Shift => (SHIFT, SHIFT), + crate::ChordMod::Super => (SUPER, SUPER), + crate::ChordMod::Primary => (PRIMARY_NAME, if platform == crate::KeyPlatform::Mac { SUPER } else { CTRL }), + }; + if key.is_some() || named & name != 0 { return Err(invalid()); } + named |= name; + mods |= modifier; + } else { + if key.is_some() { return Err(invalid()); } + let name = match part.as_str() { + "numpadenter" => "enter", + "spacebar" => "space", + "plus" => "equal", + s => crate::input::key_table::canonical_named_alias(s) + .or_else(|| crate::input::key_table::punctuation_name(s)) + .or_else(|| s.strip_prefix("key").filter(|s| s.len() == 1 && s.as_bytes()[0].is_ascii_lowercase())) + .or_else(|| s.strip_prefix("digit").filter(|s| s.len() == 1 && s.as_bytes()[0].is_ascii_digit())) + .unwrap_or(s), + }; + key = Some(super::keys::named(name).ok_or_else(invalid)?); + } + } + Ok(Self { mods, key: key.ok_or_else(invalid)? }) + } +} + +impl fmt::Display for Shortcut { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + for (bit, name) in [(CTRL, "ctrl"), (ALT, "alt"), (SHIFT, "shift"), (SUPER, "super")] { + if self.mods & bit != 0 { write!(f, "{name}+")?; } + } + f.write_str(self.key_name()) + } +} + +#[cfg(all(target_os = "linux", feature = "dbus"))] +impl Shortcut { + pub(super) fn keysym_name(&self) -> String { + match self.key_name() { + "escape" => "Escape", "enter" => "Return", "tab" => "Tab", "backspace" => "BackSpace", + "delete" => "Delete", "insert" => "Insert", "home" => "Home", "end" => "End", "pageup" => "Prior", + "pagedown" => "Next", "left" => "Left", "right" => "Right", "up" => "Up", "down" => "Down", + "quote" => "apostrophe", "backquote" => "grave", + k if k.starts_with('f') && k.len() > 1 => return k.to_uppercase(), + k => k, + }.into() + } + + pub(super) fn portal_trigger(&self) -> String { + let mut s = String::new(); + for (bit, name) in [(CTRL, "CTRL"), (ALT, "ALT"), (SHIFT, "SHIFT"), (SUPER, "LOGO")] { + if self.mods & bit != 0 { s.push_str(name); s.push('+'); } + } + s.push_str(&self.keysym_name()); + s + } +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn canonical_aliases_round_trip() { + for (input, expected) in [ + ("CMD+Shift+Space", "shift+super+space"), + ("OPTION+Control+Return", "ctrl+alt+enter"), + ("super+SHIFT+ctrl+ALT+F24", "ctrl+alt+shift+super+f24"), + (" ctrl + A ", "ctrl+a"), ("esc", "escape"), ("cmd+/", "super+slash"), + ("KeyK", "k"), ("Digit7", "7"), ("BracketLeft", "bracketleft"), ("Semicolon", "semicolon"), + ] { + let shortcut: Shortcut = input.parse().unwrap(); + assert_eq!(shortcut.to_string(), expected); + assert_eq!(shortcut, expected.parse().unwrap()); + } + } + #[test] + fn reject_ambiguous_and_incomplete_accelerators() { + for input in ["", "cmd", "cmd+", "cmd++a", "cmd+super+a", "a+b", "a+shift", "ctrl+unknown", "F0", "f25", "f01", "é"] { + assert!(matches!(input.parse::<Shortcut>(), Err(ShortcutError::InvalidAccelerator(_))), "{input}"); + } + } +} diff --git a/app/vendor/rune/crates/rune/src/shortcuts/service.rs b/app/vendor/rune/crates/rune/src/shortcuts/service.rs new file mode 100644 index 0000000..2b47241 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/shortcuts/service.rs @@ -0,0 +1,637 @@ +use super::{Shortcut, ShortcutError, ShortcutId, Sink, NativeBackend}; +#[cfg(test)] +use super::Backend; +use crate::{Tx, app::Shared, runtime::Waker}; +use machine::{AttachEffect, AttachEvent, Attachment, BindEffect, BindEvent, Bindings, step_attachment, step_bindings}; +use std::{collections::HashMap, rc::Rc, sync::{Arc, Mutex, OnceLock, PoisonError, Weak, atomic::{AtomicBool, AtomicU32, AtomicU64, Ordering}}}; +#[cfg(not(target_os = "linux"))] +use std::cell::RefCell; +#[cfg(not(target_os = "linux"))] +use std::sync::atomic::AtomicUsize; +#[cfg(any(test, not(target_os = "linux")))] +use std::sync::mpsc; + +mod machine; + +type Handler<S> = Arc<dyn Fn(&mut S, &mut Tx) + Send + Sync>; +/// The host routing handed a registration to (0 until then), so a close clears only the hosts it ends. +type Stamp = Arc<AtomicU64>; +type Pending<S> = (Result<Shortcut, ShortcutError>, Handler<S>); +#[cfg(not(target_os = "linux"))] +type Job = Box<dyn FnOnce(&mut Engine) + Send>; +#[cfg(target_os = "linux")] +type Job = std::convert::Infallible; +type Connect = fn(bool, Sink) -> Result<NativeBackend, ShortcutError>; +#[cfg(not(target_os = "linux"))] +static NEXT_OWNER: AtomicUsize = AtomicUsize::new(1); +static NEXT_ID: AtomicU32 = AtomicU32::new(1); +/// Host generations, unique across Apps, so the receiving host a thread names is never another +/// App's. +static NEXT_GENERATION: AtomicU64 = AtomicU64::new(1); +/// Every App's native registrations in this process, with the App's title, so a conflict +/// between two Apps can name its owner. Headless registrations stay out of it. +static NATIVE: Mutex<Vec<(ShortcutId, Shortcut, &'static str)>> = Mutex::new(Vec::new()); + +/// The Linux engine and the host that installed it. The wake travels with the engine, so a call +/// that reaches the engine a newer host installed wakes that host, not the one it captured. +#[cfg(target_os = "linux")] +struct Slot { + engine: Arc<Mutex<Engine>>, + wake: Waker, + /// The generation of the host that installed it: only that host's close takes it. + generation: u64, +} + +/// An owner thread's engine and the generation of the host that installed it. +#[cfg(not(target_os = "linux"))] +type Installed = (u64, Rc<RefCell<Engine>>); + +struct Control { + #[cfg(not(target_os = "linux"))] + key: usize, + attachment: Mutex<Attachment<Job>>, + #[cfg(target_os = "linux")] + engine: Mutex<Option<Slot>>, + /// How many hosts have attached; changed and read under the routing lock. + hosts: AtomicU64, + /// The newest host's generation. On Linux it is stored as a host installs its engine, under + /// the slot lock, so the slot always holds the newest. Elsewhere it is stored as a host takes + /// routing, under the routing lock, so it always names the host routing hands calls to. A + /// guard, engine or activation holding another is stale, and changes nothing the newest owns. + generation: AtomicU64, +} + +pub(crate) struct HubCore { + control: Arc<Control>, + errors: Mutex<Vec<ShortcutError>>, + title: OnceLock<&'static str>, + unmodified: AtomicBool, +} + +impl Default for HubCore { + fn default() -> Self { + Self { + control: Arc::new(Control { + #[cfg(not(target_os = "linux"))] + key: NEXT_OWNER.fetch_add(1, Ordering::Relaxed), + attachment: Mutex::new(Attachment::Detached), + #[cfg(target_os = "linux")] + engine: Mutex::default(), + hosts: AtomicU64::new(0), + generation: AtomicU64::new(0), + }), + errors: Mutex::default(), + title: OnceLock::new(), + unmodified: AtomicBool::new(false), + } + } +} + +pub(crate) struct Hub<S> { + pub(crate) core: Arc<HubCore>, + pending: Mutex<Vec<Pending<S>>>, + handlers: Arc<Mutex<HashMap<ShortcutId, (Stamp, Handler<S>)>>>, +} + +impl<S> Default for Hub<S> { + fn default() -> Self { + Self { core: Arc::default(), pending: Mutex::default(), handlers: Arc::default() } + } +} + +impl<S> std::ops::Deref for Hub<S> { + type Target = HubCore; + fn deref(&self) -> &HubCore { &self.core } +} + +#[cfg(not(target_os = "linux"))] +thread_local! { + // Native handles never cross threads, even though AppHandle can. + static ENGINES: RefCell<HashMap<usize, Installed>> = RefCell::default(); +} + +thread_local! { + /// The generation of the host delivering updates on this thread, while it delivers them. + static RECEIVING: std::cell::Cell<Option<u64>> = const { std::cell::Cell::new(None) }; + /// Runs as a drain is about to take the waiting calls, so a test can pause it there. + #[cfg(all(test, not(target_os = "linux")))] + static BEFORE_DEQUEUE: RefCell<Option<Box<dyn FnOnce()>>> = RefCell::default(); + /// Runs as this thread is about to wake a host, so a test can pause it there. + #[cfg(test)] + static BEFORE_WAKE: std::cell::RefCell<Option<Box<dyn FnOnce()>>> = std::cell::RefCell::default(); +} + +/// A host's wake, which stops for good as the host closes. Its engine, its activations and +/// routing all wake the host through it, so a call that finishes after the close, or an +/// activation passed along after it, wakes nothing. The lock is held only to clone the waker, +/// never through the wake, so a close never waits for a wake (whose callback may wait for the +/// close). A wake that took the waker just before the close still fires, and the closed host's +/// event loop ignores it. +struct HostWake(Mutex<Option<Waker>>); + +impl HostWake { + /// The waker the host's engine, activations and routing hold, and what its close ends. + /// Only they keep the host's wake alive, so one nothing reaches any more lets it go. + fn new(wake: Waker) -> (Waker, Weak<Self>) { + let host = Arc::new(Self(Mutex::new(Some(wake)))); + let closer = Arc::downgrade(&host); + (Arc::new(move || host.wake()), closer) + } + + fn wake(&self) { + #[cfg(test)] + if let Some(pause) = BEFORE_WAKE.with(|hook| hook.borrow_mut().take()) { pause(); } + let wake = self.0.lock().unwrap_or_else(PoisonError::into_inner).clone(); + if let Some(wake) = wake { wake(); } + } + + /// Ends the host's wake: a wake that starts after this fires nothing. + fn close(host: &Weak<Self>) { + let Some(host) = host.upgrade() else { return }; + let wake = host.0.lock().unwrap_or_else(PoisonError::into_inner).take(); + // The host's own waker goes once the lock is free. + drop(wake); + } +} + +fn next_generation() -> u64 { NEXT_GENERATION.fetch_add(1, Ordering::Relaxed) } + +struct Engine { + title: &'static str, + wayland: bool, + sink: Sink, + connect: Connect, + bindings: Bindings<NativeBackend>, +} + +impl Engine { + fn register(&mut self, id: ShortcutId, shortcut: Shortcut) -> Result<(), ShortcutError> { + // Another App in this process holds it; some backends (the portal) wouldn't refuse. + let claimed = !matches!(self.bindings, Bindings::Virtual(_)) && NATIVE.lock().unwrap().iter().any(|(_, s, _)| s == &shortcut); + self.apply(BindEvent::Register { id, shortcut, claimed }) + } + + fn unregister(&mut self, id: ShortcutId) -> Result<(), ShortcutError> { + self.apply(BindEvent::Unregister(id)) + } + + /// Who holds `shortcut`: this App, another App in this process, or the platform. + /// Headless engines answer only for their own virtual registrations. + fn owner(&self, shortcut: &Shortcut) -> Option<String> { + if self.bindings.find(shortcut).is_some() { return Some(self.title.into()); } + if matches!(self.bindings, Bindings::Virtual(_)) { return None; } + let other = NATIVE.lock().unwrap().iter().find(|(_, s, _)| s == shortcut).map(|(.., title)| (*title).into()); + other.or_else(|| super::system_owner(shortcut)) + } + + fn release(&mut self) { + self.apply(BindEvent::Release).ok(); + } + + fn native(&mut self) -> &mut NativeBackend { + let Bindings::Connected { native, .. } = &mut self.bindings else { unreachable!("the machine only asks a connected engine") }; + native + } + + /// Steps the bindings and carries out what they ask for, answering with what came of it. + fn apply(&mut self, event: BindEvent<NativeBackend>) -> Result<(), ShortcutError> { + let mut answer = Ok(()); + for effect in step_bindings(&mut self.bindings, event) { + match effect { + BindEffect::Refuse(error) => answer = Err(error), + BindEffect::Connect { id, shortcut } => answer = match (self.connect)(self.wayland, self.sink.clone()) { + Ok(native) => self.apply(BindEvent::Opened { native, id, shortcut }), + Err(error) => Err(error), + }, + BindEffect::Bind { id, shortcut } => answer = match self.native().register(id, &shortcut) { + Ok(()) => self.apply(BindEvent::Bound { id, shortcut }), + Err(error) => self.apply(BindEvent::Rejected(error)), + }, + BindEffect::Unbind(id) => answer = match self.native().unregister(id) { + Ok(()) => self.apply(BindEvent::Unbound(id)), + Err(error) => Err(error), + }, + BindEffect::Claim { id, shortcut } => NATIVE.lock().unwrap().push((id, shortcut, self.title)), + BindEffect::Disclaim(id) => NATIVE.lock().unwrap().retain(|(native, ..)| *native != id), + BindEffect::DisclaimAll(registrations) => NATIVE.lock().unwrap().retain(|(id, ..)| !registrations.contains_key(id)), + // Drop the connection/listener when the last registration goes away. + BindEffect::Disconnect(native) => drop(native), + } + } + answer + } +} + +impl Drop for Engine { + fn drop(&mut self) { self.release(); } +} + +impl Control { + /// Whether `generation` belongs to the newest host. + fn current(&self, generation: u64) -> bool { self.generation.load(Ordering::Relaxed) == generation } + + fn call<T: Send + 'static>(&self, f: impl FnOnce(&mut Engine) -> Result<T, ShortcutError> + Send + 'static) -> Result<T, ShortcutError> { + self.call_stamped(None, f) + } + + /// Runs a call, stamping it with the latest host while routing can't change. + fn call_stamped<T: Send + 'static>(&self, stamp: Option<Stamp>, f: impl FnOnce(&mut Engine) -> Result<T, ShortcutError> + Send + 'static) -> Result<T, ShortcutError> { + let slot = Arc::new(Mutex::new(None)); + let out = slot.clone(); + self.call_erased(stamp, Box::new(move |engine| { + *out.lock().unwrap() = Some(f(engine)); + }))?; + slot.lock().unwrap().take().unwrap_or(Err(ShortcutError::NotRunning)) + } + + fn call_erased(&self, stamp: Option<Stamp>, run: Box<dyn FnOnce(&mut Engine) + Send>) -> Result<(), ShortcutError> { + let mut route = self.attachment.lock().unwrap(); + let call = AttachEvent::Call { from: std::thread::current().id(), shared: cfg!(target_os = "linux") }; + let effect = step_attachment(&mut route, call).into_iter().next(); + if let Some(stamp) = stamp { stamp.store(self.hosts.load(Ordering::Relaxed), Ordering::Relaxed); } + #[cfg(target_os = "linux")] + { + let Some(AttachEffect::Run { .. }) = effect else { return Err(ShortcutError::NotRunning) }; + // differs from dev: the routing wake only gates the call; the slot's host is woken. + // Letting routing's copy go here means a host the call no longer reaches isn't kept + // alive through another host's callback. + drop(effect); + let (shared, wake) = { + let slot = self.engine.lock().unwrap(); + let slot = slot.as_ref().ok_or(ShortcutError::NotRunning)?; + (slot.engine.clone(), slot.wake.clone()) + }; + // Acquire the engine before releasing routing, so shutdown cannot race a new call. + let mut engine = shared.lock().unwrap(); + drop(route); + run(&mut engine); + drop(engine); + // A finished call must not keep a replaced engine, and its backend's grabs, alive. + drop(shared); + wake(); + Ok(()) + } + #[cfg(not(target_os = "linux"))] + match effect { + Some(AttachEffect::Run { wake }) => { + drop(route); + let engine = ENGINES.with(|engines| engines.borrow().get(&self.key).map(|(_, engine)| engine.clone())).ok_or(ShortcutError::NotRunning)?; + run(&mut engine.borrow_mut()); + wake(); + Ok(()) + } + Some(AttachEffect::Wait) => { + let (done_tx, done_rx) = mpsc::sync_channel(1); + let posted = step_attachment(&mut route, AttachEvent::Post(Box::new(move |engine| { + run(engine); + done_tx.send(()).ok(); + }))); + drop(route); + for effect in posted { if let AttachEffect::Wake(wake) = effect { wake(); } } + done_rx.recv().map_err(|_| ShortcutError::NotRunning) + } + _ => Err(ShortcutError::NotRunning), + } + } +} + +impl HubCore { + fn prepare_register(&self, shortcut: &Shortcut) -> Result<(ShortcutId, Stamp), ShortcutError> { + if !self.unmodified.load(Ordering::Relaxed) { shortcut.require_modifier()?; } + let id = NEXT_ID.try_update(Ordering::Relaxed, Ordering::Relaxed, |n| n.checked_add(1)) + .map(ShortcutId).map_err(|_| ShortcutError::Backend("shortcut id space exhausted".into()))?; + Ok((id, Stamp::default())) + } + + fn commit_register(&self, id: ShortcutId, shortcut: Shortcut, stamp: Stamp) -> Result<(), ShortcutError> { + self.control.call_stamped(Some(stamp), move |engine| engine.register(id, shortcut)) + } + + fn unregister_engine(&self, id: ShortcutId, remove: Box<dyn FnOnce() + Send>) -> Result<(), ShortcutError> { + self.control.call(move |engine| { + engine.unregister(id)?; + remove(); + Ok(()) + }) + } + + pub(super) fn errors(&self) -> Vec<ShortcutError> { std::mem::take(&mut self.errors.lock().unwrap()) } + + fn record_error(&self, error: ShortcutError) { + eprintln!("rune: {error}"); + self.errors.lock().unwrap().push(error); + } + + pub(crate) fn named(&self, title: &'static str) { self.title.set(title).ok(); } + + pub(super) fn allow_unmodified(&self) { self.unmodified.store(true, Ordering::Relaxed); } + + pub(super) fn owner(&self, shortcut: &Shortcut) -> Option<String> { + let shortcut = shortcut.clone(); + self.control.call(move |engine| Ok(engine.owner(&shortcut))).ok().flatten() + } + + pub(crate) fn fire(&self, shortcut: &Shortcut) -> Result<(), ShortcutError> { + let shortcut = shortcut.clone(); + let (id, sink) = self.control.call(move |engine| { + let id = engine.bindings.find(&shortcut).ok_or(ShortcutError::UnknownId)?; + Ok((id, engine.sink.clone())) + })?; + // Pressed as a backend would, holding nothing, so the press's wake runs under no lock. + sink(id, None); + Ok(()) + } +} + +impl<S: 'static> Hub<S> { + pub(super) fn pending(&self, shortcut: Result<Shortcut, ShortcutError>, handler: Handler<S>) { + self.pending.lock().unwrap().push((shortcut, handler)); + } + + pub(super) fn register(&self, shortcut: Shortcut, handler: Handler<S>) -> Result<ShortcutId, ShortcutError> { + let (id, stamp) = self.core.prepare_register(&shortcut)?; + self.handlers.lock().unwrap().insert(id, (stamp.clone(), handler)); + if let Err(e) = self.core.commit_register(id, shortcut, stamp) { + self.handlers.lock().unwrap().remove(&id); + return Err(e); + } + Ok(id) + } + + pub(super) fn unregister(&self, id: ShortcutId) -> Result<(), ShortcutError> { + let handlers = self.handlers.clone(); + self.core.unregister_engine(id, Box::new(move || { handlers.lock().unwrap().remove(&id); })) + } + + fn register_pending(&self) { + for (shortcut, handler) in std::mem::take(&mut *self.pending.lock().unwrap()) { + if let Err(error) = shortcut.and_then(|s| self.register(s, handler)) { + self.core.record_error(error); + } + } + } +} + +/// Owned by the host, not AppHandle: closing/dropping the app releases native registrations. +pub(crate) struct Guard { + control: Arc<Control>, + /// The generation this host's engine was installed with. + generation: u64, + /// Told the last host the close ends. + cleanup: Option<Box<dyn FnOnce(u64)>>, + /// Held while the host lives, so an activation left for it is dropped once it has gone. + _live: Arc<()>, + /// Ended first as the host closes, so nothing wakes it once the guard has dropped. + closes_wake: Weak<HostWake>, + // The guard must be destroyed on the owning event-loop thread. + _thread: std::marker::PhantomData<Rc<()>>, +} + +/// A host whose engine is installed, before it takes routing. +struct Attaching { + control: Arc<Control>, + generation: u64, + /// The host's wake, which `closes_wake` ends. + wake: Waker, + closes_wake: Weak<HostWake>, + live: Arc<()>, + // Routing names this thread as the owner, and a macOS or Windows engine never leaves it. + _thread: std::marker::PhantomData<Rc<()>>, +} + +/// While held, this thread delivers updates for the host that made it. +pub(crate) struct Receiving(Option<u64>); + +impl Drop for Receiving { + fn drop(&mut self) { RECEIVING.with(|receiving| receiving.set(self.0)); } +} + +/// The host an engine's activations belong to. +struct Delivery<S> { + shared: std::sync::Weak<Shared<S>>, + generation: u64, + wake: Waker, + live: std::sync::Weak<()>, + /// The host's presses, oldest first. Each activation queued for them runs the oldest, so + /// however hosts pass the activations along, this host runs its presses in the order they came. + pressed: Mutex<std::collections::VecDeque<(ShortcutId, Option<String>)>>, +} + +/// A close part-way through. +struct Closing { + /// The last host the close ends: handlers stamped after it stay. + ended: u64, + /// This host was still the newest once routing closed. A stale close clears no handlers. + current: bool, +} + +/// What a backend calls when its chord is pressed: it queues the activation and wakes the +/// engine's own host, never the window that connected last, which may have closed. A press for +/// a host that has gone queues nothing, as its activation would run nothing. +fn sink<S: 'static>(delivery: Arc<Delivery<S>>) -> Sink { + Arc::new(move |id, token| { + if delivery.live.strong_count() == 0 { return; } + if let Some(shared) = delivery.shared.upgrade() { + delivery.pressed.lock().unwrap().push_back((id, token)); + shared.queue_update(deliver(delivery.clone())); + (delivery.wake)(); + } + }) +} + +/// An activation, as an update: it runs the host's oldest press. It runs only on its own host's +/// state, and only while that host is the newest. Another host delivering it leaves it for its own +/// host, and wakes that host; an activation whose host was replaced or has gone runs nothing, and +/// discards a press, so the host's presses are only those that can still run. +fn deliver<S: 'static>(delivery: Arc<Delivery<S>>) -> Box<dyn FnOnce(&mut S, &mut Tx) -> bool + Send> { + Box::new(move |state, tx| { + // Once stale, a host's presses all are, so which one goes doesn't matter. + let discard = || { delivery.pressed.lock().unwrap().pop_front(); false }; + let Some(shared) = delivery.shared.upgrade() else { return discard() }; + if !shared.shortcuts.control.current(delivery.generation) { return discard(); } + if RECEIVING.with(|receiving| receiving.get()) != Some(delivery.generation) { + if delivery.live.strong_count() == 0 { return discard(); } + let wake = delivery.wake.clone(); + shared.queue_update(deliver(delivery)); + wake(); + return false; + } + let Some((id, token)) = delivery.pressed.lock().unwrap().pop_front() else { return false }; + let Some(handler) = shared.shortcuts.handlers.lock().unwrap().get(&id).map(|(_, handler)| handler.clone()) else { return false }; + tx.shortcut_activation_token = token; + handler(state, tx); + tx.shortcut_activation_token = None; + true + }) +} + +impl Guard { + pub(crate) fn attach<S: 'static>(shared: &Arc<Shared<S>>, wake: Waker, headless: bool, wayland: bool) -> Self { + Self::attach_with(shared, wake, headless, wayland, super::backend) + } + + fn attach_with<S: 'static>(shared: &Arc<Shared<S>>, wake: Waker, headless: bool, wayland: bool, connect: Connect) -> Self { + Self::install(shared, wake, headless, wayland, connect).route(shared) + } + + /// The first half of an attach: a new engine, with the next generation, replaces the one this + /// thread (or, on Linux, the App) had. + fn install<S: 'static>(shared: &Arc<Shared<S>>, wake: Waker, headless: bool, wayland: bool, connect: Connect) -> Attaching { + Self::install_core(&shared.shortcuts.core, wake, headless, wayland, connect, &mut |generation, wake, live| { + sink(Arc::new(Delivery { shared: Arc::downgrade(shared), generation, wake, live, pressed: Mutex::default() })) + }) + } + + fn install_core( + core: &HubCore, + wake: Waker, + headless: bool, + wayland: bool, + connect: Connect, + make_sink: &mut dyn FnMut(u64, Waker, Weak<()>) -> Sink, + ) -> Attaching { + let control = core.control.clone(); + let title = core.title.get().copied().unwrap_or_default(); + let bindings = if headless { Bindings::Virtual(HashMap::new()) } else { Bindings::Disconnected }; + let live = Arc::new(()); + // Everything below wakes the host through this, so its close ends them all. + let (wake, closes_wake) = HostWake::new(wake); + let engine = |generation| { + let sink = make_sink(generation, wake.clone(), Arc::downgrade(&live)); + Engine { title, wayland, sink, connect, bindings } + }; + // Published when this host takes routing. + #[cfg(not(target_os = "linux"))] + let generation = { + let generation = next_generation(); + ENGINES.with(|engines| engines.borrow_mut().insert(control.key, (generation, Rc::new(RefCell::new(engine(generation)))))); + generation + }; + // A replaced engine closes with the slot locked, so callers wait until its chords are free. + #[cfg(target_os = "linux")] + let generation = { + let mut slot = control.engine.lock().unwrap(); + let generation = next_generation(); + control.generation.store(generation, Ordering::Relaxed); + *slot = Some(Slot { engine: Arc::new(Mutex::new(engine(generation))), wake: wake.clone(), generation }); + generation + }; + Attaching { control, generation, wake, closes_wake, live, _thread: std::marker::PhantomData } + } + + /// Names this host as the one delivering updates on this thread until the result drops. + pub(crate) fn receiving(&self) -> Receiving { + Receiving(RECEIVING.with(|receiving| receiving.replace(Some(self.generation)))) + } + + pub(crate) fn drain(&self) { + #[cfg(not(target_os = "linux"))] + { + #[cfg(test)] + if let Some(pause) = BEFORE_DEQUEUE.with(|hook| hook.borrow_mut().take()) { pause(); } + // Calls wait for the routed host, so another host leaves them for it. Routing changes + // only under this lock, so the host it names is the one the jobs were posted to. + let drained = step_attachment(&mut self.control.attachment.lock().unwrap(), AttachEvent::Drain { host: self.generation }); + let Some(AttachEffect::Jobs(jobs)) = drained.into_iter().next() else { return }; + // The routed host's thread holds its engine. + let engine = ENGINES.with(|engines| engines.borrow().get(&self.control.key).filter(|(generation, _)| *generation == self.generation).map(|(_, engine)| engine.clone())); + if let Some(engine) = engine { for job in jobs { job(&mut engine.borrow_mut()); } } + } + } + + /// Ends routing, whichever host holds it, and releases the callers waiting on it. + fn close_routing(&self) -> Closing { + let mut route = self.control.attachment.lock().unwrap(); + let closed = step_attachment(&mut route, AttachEvent::Close); + let ended = self.control.hosts.load(Ordering::Relaxed); + // A host that installs after this reads newer, and counts after `ended`. + let current = self.control.current(self.generation); + drop(route); + // Dropping queued reply senders releases waiting callers with NotRunning. + for effect in closed { if let AttachEffect::Release(jobs) = effect { drop(jobs); } } + Closing { ended, current } + } + + /// Takes and releases this host's own engine, and never one a newer host installed. + #[cfg_attr(not(target_os = "linux"), allow(unused_variables))] + fn release_engine(&self, closing: &mut Closing) { + #[cfg(not(target_os = "linux"))] + ENGINES.with(|engines| { + let own = engines.borrow().get(&self.control.key).is_some_and(|(generation, _)| *generation == self.generation); + if own { engines.borrow_mut().remove(&self.control.key); } + }); + // The slot stays locked through the release, so a new host can't start while this one's + // backend still holds its chords. + #[cfg(target_os = "linux")] + { + let mut slot = self.control.engine.lock().unwrap(); + if slot.as_ref().is_some_and(|slot| slot.generation == self.generation) && let Some(own) = slot.take() { + // As on dev, the close ends every host counted by now. None installed since this + // one, or the slot would hold its engine. + closing.ended = self.control.hosts.load(Ordering::Relaxed); + own.engine.lock().unwrap().release(); + } + } + } + + /// Clears the handlers of the hosts the close ended, unless a newer host owns them now. + fn end(&mut self, closing: Closing) { + if !closing.current { return; } + if let Some(cleanup) = self.cleanup.take() { cleanup(closing.ended); } + } +} + +impl Attaching { + /// The second half of an attach: this host takes routing, then registers what waited for it. + fn route<S: 'static>(self, shared: &Arc<Shared<S>>) -> Guard { + let handlers = shared.shortcuts.handlers.clone(); + // A host that attached after the close took routing keeps its handlers. + let cleanup = Box::new(move |ended: u64| handlers.lock().unwrap().retain(|_, (stamp, _)| stamp.load(Ordering::Relaxed) > ended)); + let guard = self.route_core(cleanup); + shared.shortcuts.register_pending(); + guard + } + + fn route_core(self, cleanup: Box<dyn FnOnce(u64)>) -> Guard { + let Self { control, generation, wake, closes_wake, live, .. } = self; + let routed = { + let mut route = control.attachment.lock().unwrap(); + control.hosts.fetch_add(1, Ordering::Relaxed); + // The routed host is the newest, in the same step that routes to it. + #[cfg(not(target_os = "linux"))] + control.generation.store(generation, Ordering::Relaxed); + step_attachment(&mut route, AttachEvent::Attach { owner: std::thread::current().id(), wake, host: generation }) + }; + // Calls this host inherited wait for it, so it is woken for them, once routing is free. + for effect in routed { if let AttachEffect::Wake(wake) = effect { wake(); } } + Guard { control, generation, cleanup: Some(cleanup), _live: live, closes_wake, _thread: std::marker::PhantomData } + } +} + +impl Drop for Guard { + fn drop(&mut self) { + // First, so nothing the close sets off wakes this host. + HostWake::close(&self.closes_wake); + let mut closing = self.close_routing(); + self.release_engine(&mut closing); + self.end(closing); + } +} + +#[cfg(test)] +mod lifecycle_tests; +#[cfg(test)] +mod machine_tests; +#[cfg(test)] +mod routing_tests; +#[cfg(test)] +mod host_handler_tests; +#[cfg(test)] +mod generation_tests; +#[cfg(test)] +mod closed_wake_tests; +#[cfg(all(test, target_os = "linux"))] +mod teardown_tests; + +#[cfg(test)] +mod tests; diff --git a/app/vendor/rune/crates/rune/src/shortcuts/service/closed_wake_tests.rs b/app/vendor/rune/crates/rune/src/shortcuts/service/closed_wake_tests.rs new file mode 100644 index 0000000..8a9ca12 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/shortcuts/service/closed_wake_tests.rs @@ -0,0 +1,139 @@ +//! A host's wake ends with the host: a call that finishes after the host closed wakes nothing, a +//! press wakes only its own host, and a close never waits on a wake. Real `Guard`s, real threads. + +use super::*; +use crate::{App, AppSpec, el}; +use std::{sync::atomic::AtomicUsize, time::Duration}; + +const PATIENCE: Duration = Duration::from_secs(30); + +fn app(title: &'static str) -> App<()> { App::new(AppSpec::new(title, (10.0, 10.0), || (), |_, _| el())) } + +/// Pauses this thread just before its next wake, until `resume` is sent. +fn pause_before_wake(paused: mpsc::Sender<()>, resume: mpsc::Receiver<()>) { + BEFORE_WAKE.with(|hook| *hook.borrow_mut() = Some(Box::new(move || { + paused.send(()).unwrap(); + resume.recv().unwrap(); + }))); +} + +#[test] +fn a_call_that_finishes_after_its_host_closed_wakes_nothing() { + let app = app("Closed"); + let wakes = Arc::new(AtomicUsize::new(0)); + let guard = { let wakes = wakes.clone(); Guard::attach(&app.shared, Arc::new(move || { wakes.fetch_add(1, Ordering::Relaxed); }), true, false) }; + + // The call is done with the engine (or, off Linux, has posted its job) and is about to wake. + let (paused, is_paused) = mpsc::channel(); + let (resume, resumed) = mpsc::channel(); + let handle = app.handle(); + let caller = std::thread::spawn(move || { + pause_before_wake(paused, resumed); + handle.shortcut_owner(&"ctrl+alt+shift+f19".parse().unwrap()) + }); + is_paused.recv_timeout(PATIENCE).expect("the call reached its wake"); + + drop(guard); + let at_close = wakes.load(Ordering::Relaxed); + resume.send(()).unwrap(); + assert_eq!(caller.join().unwrap(), None); + assert_eq!(wakes.load(Ordering::Relaxed), at_close, "a host that has closed was woken"); +} + +/// The deadlock a wake callback held under a lock made: the host's wake re-enters routing and +/// waits for a call the host's close must release. +#[cfg(not(target_os = "linux"))] +#[test] +fn a_close_releases_a_call_its_own_wake_is_waiting_on() { + let app = app("Reentrant"); + let armed = Arc::new(AtomicBool::new(false)); + let (nested, is_nested) = mpsc::channel(); + let (nested_answer, nested_answered) = mpsc::channel(); + let wake: Waker = { + let (armed, handle) = (armed.clone(), app.handle()); + let (nested, nested_answer) = (Mutex::new(Some(nested)), Mutex::new(Some(nested_answer))); + Arc::new(move || { + if !armed.swap(false, Ordering::Relaxed) { return; } + // Once the inner call has posted its job and is about to wake, it is waiting on it. + let nested = nested.lock().unwrap().take().unwrap(); + BEFORE_WAKE.with(|hook| *hook.borrow_mut() = Some(Box::new(move || nested.send(()).unwrap()))); + let answer = handle.shortcut_owner(&"ctrl+alt+shift+f9".parse().unwrap()); + nested_answer.lock().unwrap().take().unwrap().send(answer).unwrap(); + }) + }; + + let (attached, is_attached) = mpsc::channel(); + let (close, closes) = mpsc::channel::<()>(); + let (closed, is_closed) = mpsc::channel(); + let host = { + let shared = app.shared.clone(); + std::thread::spawn(move || { + let guard = Guard::attach(&shared, wake, true, false); + attached.send(()).unwrap(); + closes.recv().unwrap(); + drop(guard); + closed.send(()).unwrap(); + }) + }; + is_attached.recv_timeout(PATIENCE).unwrap(); + + armed.store(true, Ordering::Relaxed); + let handle = app.handle(); + let caller = std::thread::spawn(move || handle.shortcut_owner(&"ctrl+alt+shift+f10".parse().unwrap())); + is_nested.recv_timeout(PATIENCE).expect("the wake's own call posted and waits"); + + close.send(()).unwrap(); + // A deadlocked close never answers: fail rather than join threads that never finish. + assert!(is_closed.recv_timeout(PATIENCE).is_ok(), "the host's close waited on its own wake"); + assert_eq!(nested_answered.recv_timeout(PATIENCE).unwrap(), None, "the close released the wake's call"); + host.join().unwrap(); + assert_eq!(caller.join().unwrap(), None); +} + +/// The sink each `capture` backend was handed, so the test can press its chord. +static PRESS: Mutex<Option<Sink>> = Mutex::new(None); + +struct Accept; + +impl Backend for Accept { + fn register(&mut self, _: ShortcutId, _: &Shortcut) -> Result<(), ShortcutError> { Ok(()) } + fn unregister(&mut self, _: ShortcutId) -> Result<(), ShortcutError> { Ok(()) } +} + +fn capture(_: bool, sink: Sink) -> Result<NativeBackend, ShortcutError> { + *PRESS.lock().unwrap() = Some(sink); + Ok(Box::new(Accept)) +} + +fn counter() -> (Arc<AtomicUsize>, Waker) { + let count = Arc::new(AtomicUsize::new(0)); + let wake = { let count = count.clone(); Arc::new(move || { count.fetch_add(1, Ordering::Relaxed); }) }; + (count, wake) +} + +#[test] +fn a_press_wakes_its_own_host_and_never_a_closed_window() { + let app = app("Pressed"); + let (first_wakes, first_wake) = counter(); + app.shared.connect(first_wake.clone()); + let first = Guard::attach_with(&app.shared, first_wake, false, false, capture); + let id = app.handle().register_shortcut("ctrl+alt+shift+f8".parse().unwrap(), |_, _| {}).unwrap(); + let press = PRESS.lock().unwrap().take().expect("the backend connected"); + + // A second window connects, takes over shortcuts and closes; the first stays open. + let (second_wakes, second_wake) = counter(); + app.shared.connect(second_wake.clone()); + drop(Guard::attach_with(&app.shared, second_wake, false, false, capture)); + let (first_before, second_before) = (first_wakes.load(Ordering::Relaxed), second_wakes.load(Ordering::Relaxed)); + + press(id, None); + assert_eq!(second_wakes.load(Ordering::Relaxed), second_before, "a press woke a window that had closed"); + assert_eq!(first_wakes.load(Ordering::Relaxed), first_before + 1, "a press wakes the host whose engine it came from"); + assert_eq!(app.shared.take().updates.len(), 1); + + // Once its host has gone too, a press queues and wakes nothing. + drop(first); + press(id, None); + assert_eq!(first_wakes.load(Ordering::Relaxed), first_before + 1, "a press woke its closed host"); + assert!(app.shared.take().updates.is_empty(), "a press for a closed host was queued"); +} diff --git a/app/vendor/rune/crates/rune/src/shortcuts/service/generation_tests.rs b/app/vendor/rune/crates/rune/src/shortcuts/service/generation_tests.rs new file mode 100644 index 0000000..f657386 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/shortcuts/service/generation_tests.rs @@ -0,0 +1,569 @@ +//! One host acting on another host's work, through the real `Guard`, with each thread's steps +//! run one at a time and checked after every step. An outgoing close must not take a newer +//! engine or clear its handlers; an activation runs only on its own host's state, and not once +//! a newer host attached; and only the routed host runs the calls that wait for it, however the +//! hosts' installs and routes interleave. + +use super::*; +use crate::{App, AppSpec, el}; +use std::{sync::atomic::AtomicI32, time::Duration}; + +const PATIENCE: Duration = Duration::from_secs(30); + +fn app(title: &'static str) -> App<u32> { App::new(AppSpec::new(title, (10.0, 10.0), || 0, |_: &u32, _| el())) } + +fn chord(text: &str) -> Shortcut { text.parse().unwrap() } + +/// Backends each engine opened and hasn't dropped, by the index its `connect` names. The close +/// walk uses 0 and 1, the activation walk 2 and 3, the reversed routes 4 and 5. +static LIVE: [AtomicI32; 6] = [const { AtomicI32::new(0) }; 6]; +/// The sink each backend was opened with, so a test can press a chord as that backend would. +static SINKS: Mutex<Vec<(usize, Sink)>> = Mutex::new(Vec::new()); + +struct Counted(usize); + +impl Backend for Counted { + fn register(&mut self, _: ShortcutId, _: &Shortcut) -> Result<(), ShortcutError> { Ok(()) } + fn unregister(&mut self, _: ShortcutId) -> Result<(), ShortcutError> { Ok(()) } +} + +impl Drop for Counted { + fn drop(&mut self) { LIVE[self.0].fetch_sub(1, Ordering::Relaxed); } +} + +fn connect<const N: usize>(_: bool, sink: Sink) -> Result<NativeBackend, ShortcutError> { + LIVE[N].fetch_add(1, Ordering::Relaxed); + SINKS.lock().unwrap().push((N, sink)); + Ok(Box::new(Counted(N))) +} + +fn live(n: usize) -> i32 { LIVE[n].load(Ordering::Relaxed) } + +fn sink_of(n: usize) -> Sink { SINKS.lock().unwrap().iter().rev().find(|(i, _)| *i == n).map(|(_, sink)| sink.clone()).unwrap() } + +/// A host's guard, its attach or close in progress, and its own state, on the thread the guard +/// belongs to. +#[derive(Default)] +struct Host { + guard: Option<Guard>, + // Only the reversed routes, off Linux, attach in two steps on a host's own thread. + #[cfg_attr(target_os = "linux", allow(dead_code))] + attaching: Option<Attaching>, + closing: Option<Closing>, + state: u32, + held: Vec<crate::app::Update<u32>>, +} + +impl Host { + /// Runs the App's queued updates on this host's state, as its event loop does. + fn deliver(&mut self, shared: &Shared<u32>) -> u32 { + self.take(shared); + self.run_held() + } + + /// Takes the App's queued updates, as an event loop's drain starts by doing. + fn take(&mut self, shared: &Shared<u32>) { self.held.extend(shared.take().updates); } + + /// Runs the updates it took on its own state. + fn run_held(&mut self) -> u32 { + let _receiving = self.guard.as_ref().unwrap().receiving(); + for f in std::mem::take(&mut self.held) { f(&mut self.state, &mut Tx::default()); } + self.state + } +} + +/// Whether this thread's engine for the App keyed `key` holds `shortcut`. +#[cfg(not(target_os = "linux"))] +fn held(key: usize, shortcut: &Shortcut) -> bool { + ENGINES.with(|engines| engines.borrow().get(&key).is_some_and(|(_, engine)| engine.borrow().bindings.find(shortcut).is_some())) +} + +type Step = Box<dyn FnOnce(&mut Host) + Send>; + +/// Where host A lives: on the test's thread beside host B, or on a thread of its own that runs +/// one step at a time while the test waits. +enum Place { Here(Host), Away(mpsc::Sender<Step>, std::thread::JoinHandle<()>) } + +impl Place { + fn new(away: bool) -> Self { + if !away { return Self::Here(Host::default()); } + let (send, steps) = mpsc::channel::<Step>(); + let thread = std::thread::spawn(move || { + let mut host = Host::default(); + for step in steps { step(&mut host); } + }); + Self::Away(send, thread) + } + + fn run<T: Send + 'static>(&mut self, step: impl FnOnce(&mut Host) -> T + Send + 'static) -> T { + match self { + Self::Here(host) => step(host), + Self::Away(..) => self.start(step).recv_timeout(PATIENCE).expect("the host's thread finished the step"), + } + } + + /// Starts a step on the host's own thread without waiting for it. + fn start<T: Send + 'static>(&self, step: impl FnOnce(&mut Host) -> T + Send + 'static) -> mpsc::Receiver<T> { + let (answer, answered) = mpsc::channel(); + self.sender().send(Box::new(move |host| { answer.send(step(host)).ok(); })).unwrap(); + answered + } + + fn sender(&self) -> mpsc::Sender<Step> { + let Self::Away(send, _) = self else { panic!("only a host on its own thread takes steps") }; + send.clone() + } + + /// Drops whatever the host still holds, on its own thread, then ends the thread. A wake can + /// hold a way to send the thread steps, so the host goes before the thread is asked to end. + fn finish(mut self) { + if let Self::Away(..) = self { self.run(|host| drop(std::mem::take(host))); } + if let Self::Away(send, thread) = self { + drop(send); + thread.join().unwrap(); + } + } +} + +// A's close, one step at a time, as `Drop` runs them. +fn a_closes_routing(host: &mut Host) { host.closing = Some(host.guard.as_ref().unwrap().close_routing()); } + +fn a_releases_engine(host: &mut Host) { host.guard.as_ref().unwrap().release_engine(host.closing.as_mut().unwrap()); } + +fn a_ends(host: &mut Host) { + let mut guard = host.guard.take().unwrap(); + guard.end(host.closing.take().unwrap()); + // Its close already ran, step by step; dropping it would close again. + std::mem::forget(guard); +} + +/// Every order of `lanes` that keeps each lane's own order. +fn interleavings<T: Copy>(lanes: &[&[T]]) -> Vec<Vec<T>> { + if lanes.iter().all(|lane| lane.is_empty()) { return vec![vec![]]; } + let mut all = vec![]; + for (n, lane) in lanes.iter().enumerate() { + let Some((first, rest)) = lane.split_first() else { continue }; + let mut next = lanes.to_vec(); + next[n] = rest; + for tail in interleavings(&next) { all.push([vec![*first], tail].concat()); } + } + all +} + +#[derive(Clone, Copy, Debug)] +enum Close { AClosesRouting, AReleasesEngine, AEnds, BInstalls, BRoutes, BRegisters, CRegisters } + +/// What the walk expects, from the steps so far. +#[derive(Default)] +struct Expect { + /// The host routing names: A at first, nobody once A closes it, B once B takes it. + routed: Option<char>, + /// Whether A was still the newest host when it closed routing. + a_current: Option<bool>, + a_released: bool, + a_ended: bool, + b_installed: bool, + b_routed: bool, + b_registered: bool, + /// The engine a third caller's registration reached. + c: Option<char>, +} + +struct Ids { a: ShortcutId, b: Option<ShortcutId>, c: Option<ShortcutId> } + +/// Who holds each backend and handler. `replaces`: B's engine takes the place of A's. +fn check(app: &App<u32>, expect: &Expect, ids: &Ids, replaces: bool, at: &str) { + let a_alive = !(expect.b_installed && replaces) && !expect.a_released; + assert_eq!(live(0), i32::from(a_alive), "A's backend: {at}"); + let b_holds = expect.b_registered || expect.c == Some('B'); + assert_eq!(live(1), i32::from(b_holds), "B's backend lives while B holds a chord: {at}"); + let a_cleared = expect.a_ended && expect.a_current == Some(true); + let mut want = vec![]; + if !a_cleared { want.push(ids.a.0); } + want.extend(ids.b.map(|id| id.0)); + if let Some(c) = ids.c && !(expect.c == Some('A') && a_cleared) { want.push(c.0); } + want.sort(); + let mut have: Vec<u32> = app.shared.shortcuts.handlers.lock().unwrap().keys().map(|id| id.0).collect(); + have.sort(); + assert_eq!(have, want, "handlers: {at}"); +} + +const A_CHORD: &str = "ctrl+alt+super+f1"; +const B_CHORD: &str = "ctrl+alt+super+f2"; +const C_CHORD: &str = "ctrl+alt+super+f3"; +const D_CHORD: &str = "ctrl+alt+super+f4"; + +#[test] +fn an_outgoing_close_leaves_a_newer_hosts_engine_and_handlers_alone() { + use Close::*; + let a: &[Close] = &[AClosesRouting, AReleasesEngine, AEnds]; + let b: &[Close] = &[BInstalls, BRoutes, BRegisters]; + // On Linux any thread reaches the engine, so another caller can register at any point. + let lanes: Vec<&[Close]> = if cfg!(target_os = "linux") { vec![a, b, &[CRegisters]] } else { vec![a, b] }; + let (mut stale, mut current) = (false, false); + for away in [false, true] { + let replaces = cfg!(target_os = "linux") || !away; + for order in interleavings(&lanes) { + assert_eq!((live(0), live(1)), (0, 0), "the last walk let its backends go"); + let app = app("Successor"); + let handle = app.handle(); + let mut place = Place::new(away); + let a_id = { + let (shared, handle) = (app.shared.clone(), handle.clone()); + place.run(move |host| { + host.guard = Some(Guard::attach_with(&shared, Arc::new(|| {}), false, false, connect::<0>)); + handle.register_shortcut(chord(A_CHORD), |state, _| *state += 1).unwrap() + }) + }; + let mut expect = Expect { routed: Some('A'), ..Expect::default() }; + let mut ids = Ids { a: a_id, b: None, c: None }; + let (mut attaching, mut b) = (None, None); + check(&app, &expect, &ids, replaces, "A attached"); + for (n, step) in order.iter().enumerate() { + let at = format!("away {away}, {order:?} at {n}"); + match step { + AClosesRouting => { + place.run(a_closes_routing); + expect.routed = None; + // B is the newest once it installs on Linux, and once it routes elsewhere. + expect.a_current = Some(!if cfg!(target_os = "linux") { expect.b_installed } else { expect.b_routed }); + } + AReleasesEngine => { place.run(a_releases_engine); expect.a_released = true; } + AEnds => { place.run(a_ends); expect.a_ended = true; } + BInstalls => { + attaching = Some(Guard::install(&app.shared, Arc::new(|| {}), false, false, connect::<1>)); + expect.b_installed = true; + } + BRoutes => { b = Some(attaching.take().unwrap().route(&app.shared)); expect.routed = Some('B'); expect.b_routed = true; } + BRegisters => { + let answer = handle.register_shortcut(chord(B_CHORD), |state, _| *state += 10); + expect.b_registered = expect.routed == Some('B'); + assert_eq!(answer.is_ok(), expect.b_registered, "B's registration: {at}: {answer:?}"); + ids.b = answer.ok(); + } + CRegisters => { + let answer = handle.register_shortcut(chord(C_CHORD), |state, _| *state += 100); + expect.c = expect.routed.map(|_| if expect.b_installed { 'B' } else { 'A' }); + assert_eq!(answer.is_ok(), expect.c.is_some(), "another caller's registration: {at}: {answer:?}"); + ids.c = answer.ok(); + } + } + check(&app, &expect, &ids, replaces, &at); + } + let at = format!("away {away}, {order:?}"); + let fresh = handle.register_shortcut(chord(D_CHORD), |_, _| {}); + assert_eq!(fresh.is_ok(), expect.routed == Some('B'), "a call once A has gone reaches B: {at}: {fresh:?}"); + if fresh.is_ok() { assert_eq!(handle.shortcut_owner(&chord(D_CHORD)).as_deref(), Some("Successor"), "{at}"); } + stale |= expect.a_current == Some(false); + current |= expect.a_current == Some(true); + drop(b); + place.finish(); + assert!(app.shared.shortcuts.handlers.lock().unwrap().is_empty(), "B's close ends every handler: {at}"); + assert_eq!((live(0), live(1)), (0, 0), "every backend went: {at}"); + } + } + assert!(stale && current, "the walk closed A both before and after B installed"); +} + +/// Two hosts of one App, each with its own state, share the App's update queue. Letters: 0 A's +/// backend presses its chord; 1 B attaches and registers; 2 B's backend presses its chord; 3 A +/// delivers the queue on A's state; 4 B delivers it on B's state. +#[test] +fn an_activation_runs_only_on_its_own_hosts_state_while_that_host_is_newest() { + let (mut replaced, mut left) = (false, false); + for away in [false, true] { + super::machine_tests::every_sequence(5, 5, |sequence| { + let app = app("Pressed"); + let handle = app.handle(); + let mut place = Place::new(away); + let a_id = { + let (shared, handle) = (app.shared.clone(), handle.clone()); + place.run(move |host| { + host.guard = Some(Guard::attach_with(&shared, Arc::new(|| {}), false, false, connect::<2>)); + handle.register_shortcut(chord("ctrl+alt+super+f5"), |state, _| *state += 1).unwrap() + }) + }; + let a_sink = sink_of(2); + let b_woken = Arc::new(AtomicI32::new(0)); + let (mut b, mut b_sink) = (None::<Host>, None); + // The reference: activations wait in order. One runs only on its own host's state, + // and only while that host is the newest; another host leaves it, and wakes its host. + let (mut queued, mut want_a, mut want_b) = (vec![], 0, 0); + for (n, letter) in sequence.iter().enumerate() { + let at = format!("away {away}, {sequence:?} at {n}"); + match letter { + 0 => { a_sink(a_id, None); queued.push('A'); } + 1 if b.is_none() => { + let woken = b_woken.clone(); + let guard = Guard::attach_with(&app.shared, Arc::new(move || { woken.fetch_add(1, Ordering::Relaxed); }), false, false, connect::<3>); + b = Some(Host { guard: Some(guard), ..Host::default() }); + let id = handle.register_shortcut(chord("ctrl+alt+super+f6"), |state, _| *state += 10).unwrap(); + b_sink = Some((sink_of(3), id)); + } + 2 => if let Some((sink, id)) = &b_sink { sink(*id, None); queued.push('B'); }, + 3 => { + for &host in &queued { + if host == 'A' && b.is_none() { want_a += 1; } + replaced |= host == 'A' && b.is_some(); + } + queued.retain(|&host| host == 'B'); + left |= !queued.is_empty(); + let (shared, woken) = (app.shared.clone(), b_woken.load(Ordering::Relaxed)); + place.run(move |host| host.deliver(&shared)); + assert_eq!(b_woken.load(Ordering::Relaxed) - woken, queued.len() as i32, "A woke B for each activation it left: {at}"); + } + 4 => if let Some(b) = &mut b { + want_b += 10 * queued.iter().filter(|&&host| host == 'B').count() as u32; + queued.clear(); + b.deliver(&app.shared); + }, + _ => {} + } + assert_eq!(place.run(|host| host.state), want_a, "A's state: {at}"); + assert_eq!(b.as_ref().map_or(0, |b| b.state), want_b, "B's state: {at}"); + } + drop(b); + place.finish(); + SINKS.lock().unwrap().retain(|(n, _)| !matches!(n, 2 | 3)); + }); + } + assert!(replaced, "the walk delivered A's activation after B attached"); + assert!(left, "the walk had A deliver B's activation before B did"); +} + +/// A replaced host A stays alive on its own thread, and its engine's sink keeps taking presses. +/// Whichever host delivers them, each is discarded, so A's presses never pile up. +#[test] +fn a_replaced_engines_presses_are_discarded_not_kept() { + let app = app("Replaced"); + let mut a = Place::new(true); + let (generation, live) = { + let shared = app.shared.clone(); + a.run(move |host| { + let guard = Guard::attach(&shared, Arc::new(|| {}), true, false); + let seen = (guard.generation, Arc::downgrade(&guard._live)); + host.guard = Some(guard); + seen + }) + }; + // A's engine's sink, as `install` builds it. + let delivery = Arc::new(Delivery { shared: Arc::downgrade(&app.shared), generation, wake: Arc::new(|| {}), live, pressed: Mutex::default() }); + let press = sink(delivery.clone()); + let mut b = Host { guard: Some(Guard::attach(&app.shared, Arc::new(|| {}), true, false)), ..Host::default() }; + for n in 0..50 { + press(ShortcutId(u32::MAX - 3), None); + if n % 2 == 0 { b.deliver(&app.shared); } else { let shared = app.shared.clone(); a.run(move |host| { host.deliver(&shared); }); } + assert_eq!(delivery.pressed.lock().unwrap().len(), 0, "press {n} was discarded"); + assert!(app.shared.take().updates.is_empty(), "nothing waits for another host: press {n}"); + } + assert_eq!((a.run(|host| host.state), b.state), (0, 0), "no press ran"); + drop(b); + a.finish(); +} + +/// A caller off the owner thread waits for the newest host, B. A replaced host A on its own +/// thread drains before or after B: the call runs once, on B's engine. +#[cfg(not(target_os = "linux"))] +#[test] +fn a_replaced_host_leaves_waiting_calls_to_the_newest_engine() { + for a_first in [true, false] { + let app = app("Newest"); + let handle = app.handle(); + let control = app.shared.shortcuts.control.clone(); + let key = control.key; + let mut place = Place::new(true); + { + let shared = app.shared.clone(); + place.run(move |host| host.guard = Some(Guard::attach(&shared, Arc::new(|| {}), true, false))); + } + let (wake, woke) = mpsc::channel(); + let b = Guard::attach(&app.shared, Arc::new(move || { wake.send(()).ok(); }), true, false); + let shortcut = chord("ctrl+alt+super+f7"); + let waiting = || matches!(&*control.attachment.lock().unwrap(), Attachment::Attached { jobs, .. } if jobs.len() == 1); + let on_a = |place: &mut Place| { let shortcut = shortcut.clone(); place.run(move |_| held(key, &shortcut)) }; + + let caller = { let (handle, shortcut) = (handle.clone(), shortcut.clone()); std::thread::spawn(move || handle.register_shortcut(shortcut, |_, _| {})) }; + woke.recv_timeout(PATIENCE).expect("the call woke B"); + assert!(waiting(), "the call waits for B"); + for drainer in if a_first { ['A', 'B'] } else { ['B', 'A'] } { + let at = format!("A first {a_first}, after {drainer} drained"); + if drainer == 'A' { place.run(|host| host.guard.as_ref().unwrap().drain()); } else { b.drain(); } + let ran = drainer == 'B' || !a_first; + assert_eq!(waiting(), !ran, "the call waits until B drains: {at}"); + assert!(!on_a(&mut place), "A's engine never takes the call: {at}"); + assert_eq!(held(key, &shortcut), ran, "B's engine holds the chord once B drained: {at}"); + } + assert!(caller.join().unwrap().is_ok()); + assert_eq!(handle.shortcut_owner(&shortcut).as_deref(), Some("Newest")); + drop(b); + place.finish(); + } +} + +/// Two owner threads attach, and their routes finish in the reverse of their installs: B +/// installs after A but routes first, so routing ends on A. A waiting call wakes A, and that wake +/// alone drives A's drain: the call runs on A's engine, and A's chord reaches A's state. +#[cfg(not(target_os = "linux"))] +#[test] +fn a_host_that_installed_first_but_routed_last_runs_its_calls_and_activations() { + let app = app("Reversed"); + let handle = app.handle(); + let key = app.shared.shortcuts.control.key; + let (mut a, mut b) = (Place::new(true), Place::new(true)); + let connects: [Connect; 2] = [connect::<4>, connect::<5>]; + for (place, connect) in [(&mut a, connects[0]), (&mut b, connects[1])] { + // The host's wake asks its own thread to drain, as its event loop does. + let send = place.sender(); + let wake: Waker = Arc::new(move || { send.send(Box::new(|host: &mut Host| if let Some(guard) = &host.guard { guard.drain() })).ok(); }); + let shared = app.shared.clone(); + place.run(move |host| host.attaching = Some(Guard::install(&shared, wake, false, false, connect))); + } + for place in [&mut b, &mut a] { + let shared = app.shared.clone(); + place.run(move |host| host.guard = Some(host.attaching.take().unwrap().route(&shared))); + } + let shortcut = chord("ctrl+alt+super+f8"); + let (answer, answered) = mpsc::channel(); + { + let (handle, shortcut) = (handle.clone(), shortcut.clone()); + std::thread::spawn(move || { answer.send(handle.register_shortcut(shortcut, |state, _| *state += 1)).ok(); }); + } + let id = answered.recv_timeout(PATIENCE).expect("A's wake drained the waiting call").unwrap(); + let on = |place: &mut Place| { let shortcut = shortcut.clone(); place.run(move |_| held(key, &shortcut)) }; + assert!(on(&mut a), "A's engine ran the call"); + assert!(!on(&mut b), "B's engine never took it"); + sink_of(4)(id, None); + let shared = app.shared.clone(); + assert_eq!(a.run(move |host| host.deliver(&shared)), 1, "A's chord reaches A's state"); + // A's sink holds A's wake, which can send A's thread steps, so it goes before the thread. + SINKS.lock().unwrap().retain(|(n, _)| !matches!(n, 4 | 5)); + a.finish(); + b.finish(); + assert_eq!((live(4), live(5)), (0, 0), "both backends went"); +} + +/// The routed host A starts to drain a waiting call and pauses just before it takes the calls. +/// B attaches meanwhile, so the call is B's: A resumes and takes nothing, and B runs it. +#[cfg(not(target_os = "linux"))] +#[test] +fn a_host_paused_before_it_takes_the_calls_leaves_them_to_the_host_routed_meanwhile() { + let app = app("Paused"); + let handle = app.handle(); + let control = app.shared.shortcuts.control.clone(); + let key = control.key; + let mut a = Place::new(true); + let (a_woken, a_woke) = mpsc::channel(); + { + let shared = app.shared.clone(); + a.run(move |host| host.guard = Some(Guard::attach(&shared, Arc::new(move || { a_woken.send(()).ok(); }), true, false))); + } + let shortcut = chord("ctrl+alt+super+f9"); + let caller = { let (handle, shortcut) = (handle.clone(), shortcut.clone()); std::thread::spawn(move || handle.register_shortcut(shortcut, |_, _| {})) }; + a_woke.recv_timeout(PATIENCE).expect("the call woke A"); + let waiting = || matches!(&*control.attachment.lock().unwrap(), Attachment::Attached { jobs, .. } if jobs.len() == 1); + assert!(waiting(), "the call waits for A"); + + let (paused, pauses) = mpsc::channel(); + let (resume, resumes) = mpsc::channel::<()>(); + let drained = a.start(move |host| { + BEFORE_DEQUEUE.with(|hook| *hook.borrow_mut() = Some(Box::new(move || { paused.send(()).unwrap(); resumes.recv().unwrap(); }))); + host.guard.as_ref().unwrap().drain(); + }); + pauses.recv_timeout(PATIENCE).expect("A paused before it took the calls"); + let (b_woken, b_woke) = mpsc::channel(); + let b = Guard::attach(&app.shared, Arc::new(move || { b_woken.send(()).ok(); }), true, false); + resume.send(()).unwrap(); + drained.recv_timeout(PATIENCE).expect("A's drain finished"); + + let on_a = { let shortcut = shortcut.clone(); a.run(move |_| held(key, &shortcut)) }; + assert!(!on_a, "A's engine never ran B's call"); + assert!(waiting(), "the call waits for B"); + b_woke.recv_timeout(PATIENCE).expect("B was woken for the call it took over"); + b.drain(); + assert!(caller.join().unwrap().is_ok()); + assert!(held(key, &shortcut), "B's engine ran it"); + drop(b); + a.finish(); +} + +/// A caller waits for A, and only A is woken. B takes routing, and the call with it, before A +/// drains, so A's drain takes nothing. Each host drains only when its own wake asks: B's +/// attach wakes B for the call it took over, and B runs it. +#[cfg(not(target_os = "linux"))] +#[test] +fn a_host_that_takes_over_a_waiting_call_is_woken_for_it() { + let app = app("Inherited"); + let handle = app.handle(); + let key = app.shared.shortcuts.control.key; + let (mut a, mut b) = (Place::new(true), Place::new(true)); + // A's wake is only noted: A drains when the test says it answers it. + let (a_woken, a_woke) = mpsc::channel(); + { + let shared = app.shared.clone(); + a.run(move |host| host.guard = Some(Guard::attach(&shared, Arc::new(move || { a_woken.send(()).ok(); }), true, false))); + } + let shortcut = chord("ctrl+alt+super+f10"); + let (answer, answered) = mpsc::channel(); + { + let (handle, shortcut) = (handle.clone(), shortcut.clone()); + std::thread::spawn(move || { answer.send(handle.register_shortcut(shortcut, |_, _| {})).ok(); }); + } + a_woke.recv_timeout(PATIENCE).expect("the call woke A"); + // B's wake asks B's thread to drain, as its event loop does. + let send = b.sender(); + let wake: Waker = Arc::new(move || { send.send(Box::new(|host: &mut Host| if let Some(guard) = &host.guard { guard.drain() })).ok(); }); + { + let shared = app.shared.clone(); + b.run(move |host| host.guard = Some(Guard::attach(&shared, wake, true, false))); + } + // A answers its wake, after B took the call over. + a.run(|host| host.guard.as_ref().unwrap().drain()); + let answer = answered.recv_timeout(PATIENCE).expect("B's own wake drained the call it took over"); + assert!(answer.is_ok(), "{answer:?}"); + let on = |place: &mut Place| { let shortcut = shortcut.clone(); place.run(move |_| held(key, &shortcut)) }; + assert!(!on(&mut a), "A's engine never took the call"); + assert!(on(&mut b), "B's engine ran it"); + // B's wake, held by routing, can send B's thread steps, so B closes first. + b.finish(); + a.finish(); +} + +#[derive(Clone, Copy, Debug)] +enum Press { X, Y, ATakes, ARuns, BDelivers } + +/// B is the newest host throughout, and presses X, then Y, whose handlers don't commute. A +/// replaced host on its own thread takes the App's updates in one step and runs them in a later +/// one, and B delivers at any point: B runs X, then Y, whoever took them first. +#[test] +fn a_hosts_presses_run_in_the_order_they_came_whoever_takes_them_first() { + use Press::*; + let lanes: [&[Press]; 3] = [&[X, Y], &[ATakes, ARuns], &[BDelivers]]; + for order in interleavings(&lanes) { + let app = app("Ordered"); + let handle = app.handle(); + let mut a = Place::new(true); + { + let shared = app.shared.clone(); + a.run(move |host| host.guard = Some(Guard::attach(&shared, Arc::new(|| {}), true, false))); + } + let mut b = Host { guard: Some(Guard::attach(&app.shared, Arc::new(|| {}), true, false)), ..Host::default() }; + let (x, y) = (chord("ctrl+alt+super+f11"), chord("ctrl+alt+super+f12")); + handle.register_shortcut(x.clone(), |state, _| *state = *state * 10 + 1).unwrap(); + handle.register_shortcut(y.clone(), |state, _| *state = *state * 10 + 2).unwrap(); + for (n, step) in order.iter().enumerate() { + let at = format!("{order:?} at {n}"); + match step { + X => app.shared.shortcuts.fire(&x).unwrap(), + Y => app.shared.shortcuts.fire(&y).unwrap(), + ATakes => { let shared = app.shared.clone(); a.run(move |host| host.take(&shared)); } + ARuns => { a.run(|host| host.run_held()); } + BDelivers => { b.deliver(&app.shared); } + } + assert_eq!(a.run(|host| host.state), 0, "A runs none of B's presses: {at}"); + assert!([0, 1, 12].contains(&b.state), "B ran its presses in order: {at}: {}", b.state); + } + assert_eq!(b.deliver(&app.shared), 12, "B ran X, then Y: {order:?}"); + drop(b); + a.finish(); + } +} diff --git a/app/vendor/rune/crates/rune/src/shortcuts/service/host_handler_tests.rs b/app/vendor/rune/crates/rune/src/shortcuts/service/host_handler_tests.rs new file mode 100644 index 0000000..dfb60fd --- /dev/null +++ b/app/vendor/rune/crates/rune/src/shortcuts/service/host_handler_tests.rs @@ -0,0 +1,81 @@ +//! A close clears the handlers of the hosts it ends, and leaves a later host's alone, through the +//! real `Guard` and real threads. + +use super::*; +use crate::{App, AppSpec, el}; + +fn app(title: &'static str) -> App<u32> { App::new(AppSpec::new(title, (10.0, 10.0), || 0, |_: &u32, _| el())) } + +fn chord(text: &str) -> Shortcut { text.parse().unwrap() } + +/// Runs every queued update as `host` would, and returns how far the handlers moved the count. +fn deliver(app: &App<u32>, host: Option<&Guard>) -> u32 { + let mut state = 0; + let _receiving = host.map(Guard::receiving); + for f in app.shared.take().updates { f(&mut state, &mut Tx::default()); } + state +} + +#[test] +fn a_closing_host_leaves_a_later_hosts_handlers_alone() { + let app = app("Successor"); + let handle = app.handle(); + // A runs on its own thread; its close stops just before its cleanup. + let (entered, in_cleanup) = mpsc::channel(); + let (resume, resumed) = mpsc::channel::<()>(); + let (close, closes) = mpsc::channel::<()>(); + let first = { + let (shared, handle) = (app.shared.clone(), handle.clone()); + std::thread::spawn(move || { + let mut guard = Guard::attach(&shared, Arc::new(|| {}), true, false); + handle.register_shortcut(chord("ctrl+alt+g"), |state, _| *state += 100).unwrap(); + let cleanup = guard.cleanup.take().unwrap(); + guard.cleanup = Some(Box::new(move |ended| { + entered.send(()).unwrap(); + resumed.recv().unwrap(); + cleanup(ended); + })); + closes.recv().unwrap(); + drop(guard); + }) + }; + close.send(()).unwrap(); + in_cleanup.recv().unwrap(); + + // B attaches after A's close took routing, and registers. + let guard = Guard::attach(&app.shared, Arc::new(|| {}), true, false); + handle.register_shortcut(chord("ctrl+alt+h"), |state, _| *state += 1).unwrap(); + resume.send(()).unwrap(); + first.join().unwrap(); + + assert_eq!(app.shared.shortcuts.handlers.lock().unwrap().len(), 1, "only A's handler went"); + app.shared.shortcuts.fire(&chord("ctrl+alt+h")).unwrap(); + assert_eq!(deliver(&app, Some(&guard)), 1, "B's shortcut still reaches its handler"); + drop(guard); + assert!(app.shared.shortcuts.handlers.lock().unwrap().is_empty()); +} + +#[test] +fn closing_a_later_host_ends_the_handlers_of_the_host_it_replaced() { + let app = app("Replaced"); + let (finish, finishes) = mpsc::channel::<()>(); + let (queued, is_queued) = mpsc::channel(); + let first = { + let (shared, handle) = (app.shared.clone(), app.handle()); + std::thread::spawn(move || { + let guard = Guard::attach(&shared, Arc::new(|| {}), true, false); + handle.register_shortcut(chord("ctrl+alt+r"), |state, _| *state += 1).unwrap(); + shared.shortcuts.fire(&chord("ctrl+alt+r")).unwrap(); + queued.send(()).unwrap(); + finishes.recv().unwrap(); + drop(guard); + }) + }; + is_queued.recv().unwrap(); + // B replaces A without A closing, then closes: the service is closed, as on dev. + drop(Guard::attach(&app.shared, Arc::new(|| {}), true, false)); + assert!(app.shared.shortcuts.handlers.lock().unwrap().is_empty()); + assert_eq!(deliver(&app, None), 0, "A's queued activation runs nothing"); + finish.send(()).unwrap(); + first.join().unwrap(); +} diff --git a/app/vendor/rune/crates/rune/src/shortcuts/service/lifecycle_tests.rs b/app/vendor/rune/crates/rune/src/shortcuts/service/lifecycle_tests.rs new file mode 100644 index 0000000..527fbaa --- /dev/null +++ b/app/vendor/rune/crates/rune/src/shortcuts/service/lifecycle_tests.rs @@ -0,0 +1,104 @@ +//! A host attaching, closing and attaching again, through the real `Guard` and real threads. + +use super::*; +use crate::{App, AppSpec, el}; + +fn app(title: &'static str) -> App<()> { App::new(AppSpec::new(title, (10.0, 10.0), || (), |_, _| el())) } + +fn chord(text: &str) -> Shortcut { text.parse().unwrap() } + +#[test] +fn a_closed_service_refuses_and_a_new_host_starts_empty() { + let app = app("Reattach"); + let handle = app.handle(); + let chord = chord("ctrl+alt+r"); + assert_eq!(handle.register_shortcut(chord.clone(), |_, _| {}), Err(ShortcutError::NotRunning), "before a host"); + assert_eq!(app.shared.shortcuts.fire(&chord), Err(ShortcutError::NotRunning)); + + let guard = Guard::attach(&app.shared, Arc::new(|| {}), true, false); + let id = handle.register_shortcut(chord.clone(), |_, _| {}).unwrap(); + assert!(app.shared.shortcuts.handlers.lock().unwrap().contains_key(&id)); + drop(guard); + + assert!(app.shared.shortcuts.handlers.lock().unwrap().is_empty(), "closing clears the handlers"); + assert_eq!(handle.register_shortcut(chord.clone(), |_, _| {}), Err(ShortcutError::NotRunning), "after the host"); + assert_eq!(handle.unregister_shortcut(id), Err(ShortcutError::NotRunning)); + assert_eq!(handle.shortcut_owner(&chord), None); + assert_eq!(app.shared.shortcuts.fire(&chord), Err(ShortcutError::NotRunning)); + assert!(app.shared.shortcuts.handlers.lock().unwrap().is_empty(), "a refused registration leaves no handler"); + + let guard = Guard::attach(&app.shared, Arc::new(|| {}), true, false); + assert_eq!(handle.unregister_shortcut(id), Err(ShortcutError::UnknownId), "registrations die with their host"); + assert_eq!(app.shared.shortcuts.fire(&chord), Err(ShortcutError::UnknownId)); + let again = handle.register_shortcut(chord.clone(), |_, _| {}).unwrap(); + assert_ne!(again, id); + assert_eq!(handle.shortcut_owner(&chord).as_deref(), Some("Reattach")); + drop(guard); +} + +#[test] +fn static_shortcuts_wait_for_the_next_attach_whatever_the_state() { + let app = app("Pending").global_shortcut("ctrl+alt+p", |_, _| {}); + let guard = Guard::attach(&app.shared, Arc::new(|| {}), true, false); + app.shared.shortcuts.fire(&chord("ctrl+alt+p")).unwrap(); + + let app = app.global_shortcut("ctrl+alt+w", |_, _| {}); + assert_eq!(app.shared.shortcuts.fire(&chord("ctrl+alt+w")), Err(ShortcutError::UnknownId), "queued while attached"); + drop(guard); + + let app = app.global_shortcut("ctrl+alt+q", |_, _| {}).global_shortcut("q", |_, _| {}); + let guard = Guard::attach(&app.shared, Arc::new(|| {}), true, false); + app.shared.shortcuts.fire(&chord("ctrl+alt+w")).unwrap(); + app.shared.shortcuts.fire(&chord("ctrl+alt+q")).unwrap(); + assert_eq!(app.shared.shortcuts.fire(&chord("ctrl+alt+p")), Err(ShortcutError::UnknownId), "consumed by the first host"); + assert!(matches!(app.handle().take_shortcut_errors().as_slice(), [ShortcutError::InvalidAccelerator(_)])); + drop(guard); +} + +#[cfg(not(target_os = "linux"))] +#[test] +fn closing_releases_callers_waiting_for_the_owner() { + let app = app("Waiting"); + let (wake, woke) = mpsc::channel(); + let guard = Guard::attach(&app.shared, Arc::new(move || { wake.send(()).ok(); }), true, false); + let handle = app.handle(); + let caller = std::thread::spawn(move || handle.register_shortcut("ctrl+alt+c".parse().unwrap(), |_, _| {})); + woke.recv().unwrap(); + drop(guard); + assert_eq!(caller.join().unwrap(), Err(ShortcutError::NotRunning)); + assert!(app.shared.shortcuts.handlers.lock().unwrap().is_empty()); +} + +#[cfg(not(target_os = "linux"))] +#[test] +fn a_second_host_keeps_waiting_callers_and_either_close_ends_the_service() { + let app = app("Second"); + let (first_wake, first_woke) = mpsc::channel(); + let first = Guard::attach(&app.shared, Arc::new(move || { first_wake.send(()).ok(); }), true, false); + let handle = app.handle(); + let chord = chord("ctrl+alt+s"); + let caller = { let (handle, chord) = (handle.clone(), chord.clone()); std::thread::spawn(move || handle.register_shortcut(chord, |_, _| {})) }; + first_woke.recv().unwrap(); + + let second = Guard::attach(&app.shared, Arc::new(|| {}), true, false); + second.drain(); + caller.join().unwrap().unwrap(); + assert_eq!(handle.shortcut_owner(&chord).as_deref(), Some("Second"), "the waiting call ran on the newer engine"); + + drop(first); + assert_eq!(handle.register_shortcut(chord.clone(), |_, _| {}), Err(ShortcutError::NotRunning)); + second.drain(); + drop(second); + assert_eq!(handle.shortcut_owner(&chord), None); +} + +#[cfg(target_os = "linux")] +#[test] +fn off_thread_calls_run_without_waiting_for_the_owner() { + let app = app("Direct"); + let guard = Guard::attach(&app.shared, Arc::new(|| {}), true, false); + let handle = app.handle(); + let caller = std::thread::spawn(move || handle.register_shortcut("ctrl+alt+d".parse().unwrap(), |_, _| {})); + caller.join().unwrap().unwrap(); + drop(guard); +} diff --git a/app/vendor/rune/crates/rune/src/shortcuts/service/machine.rs b/app/vendor/rune/crates/rune/src/shortcuts/service/machine.rs new file mode 100644 index 0000000..2af0952 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/shortcuts/service/machine.rs @@ -0,0 +1,206 @@ +//! The service's state: whether an App has a host, and what its engine holds. These are two +//! enums because they live in different places. The attachment is read from any thread, while +//! a macOS or Windows engine never leaves its own, and a Linux engine sits in its own slot, whose +//! lock a closing backend holds so that nothing reaches the next engine until its chords are free. + +use super::super::{Shortcut, ShortcutError, ShortcutId}; +use crate::{machine::Effects, runtime::Waker}; +use std::{collections::HashMap, mem, thread::ThreadId}; + +pub(super) type Registrations = HashMap<ShortcutId, Shortcut>; + +/// Whether an App has a host. `J` is a call waiting for the owner thread. +pub(super) enum Attachment<J> { + /// No host has attached yet. + Detached, + /// `host` is the routed host's generation: the wake is its, and only it takes `jobs`. + Attached { owner: ThreadId, wake: Waker, host: u64, jobs: Vec<J> }, + /// The host closed. Calls are refused, and a later host can still attach. + Closed, +} + +// Linux calls reach the engine directly, so nothing posts or drains there. +#[cfg_attr(target_os = "linux", allow(dead_code))] +pub(super) enum AttachEvent<J> { + Attach { owner: ThreadId, wake: Waker, host: u64 }, + /// A call from `from`. When `shared`, any thread can reach the engine, so none waits. + Call { from: ThreadId, shared: bool }, + /// The job of a call told to `Wait`, sent under the same lock. + Post(J), + /// The host of generation `host` asks for the waiting calls. Only the routed host gets them. + Drain { host: u64 }, + Close, +} + +#[cfg_attr(target_os = "linux", allow(dead_code))] +pub(super) enum AttachEffect<J> { + /// Nothing is attached: the call fails with `NotRunning`. + Refuse, + /// Run the call on this thread. + Run { wake: Waker }, + /// Post a job and wait for the owner to run it. + Wait, + Wake(Waker), + /// Run these on the owner thread. + Jobs(Vec<J>), + /// The host closed: release its waiting callers. + Release(Vec<J>), +} + +pub(super) fn step_attachment<J>(state: &mut Attachment<J>, event: AttachEvent<J>) -> Effects<AttachEffect<J>> { + match event { + AttachEvent::Attach { owner, wake, host } => { + // Callers already waiting stay queued for the new host, which only its own wake + // brings to them: the old host's wake now drains nothing. + let jobs = match state { Attachment::Attached { jobs, .. } => mem::take(jobs), _ => Vec::new() }; + let effects = if jobs.is_empty() { Effects::none() } else { Effects::one(AttachEffect::Wake(wake.clone())) }; + *state = Attachment::Attached { owner, wake, host, jobs }; + effects + } + AttachEvent::Call { from, shared } => match state { + Attachment::Attached { owner, wake, .. } if shared || *owner == from => Effects::one(AttachEffect::Run { wake: wake.clone() }), + Attachment::Attached { .. } => Effects::one(AttachEffect::Wait), + _ => Effects::one(AttachEffect::Refuse), + }, + AttachEvent::Post(job) => match state { + Attachment::Attached { wake, jobs, .. } => { + jobs.push(job); + Effects::one(AttachEffect::Wake(wake.clone())) + } + _ => Effects::none(), + }, + AttachEvent::Drain { host: asking } => match state { + Attachment::Attached { host, jobs, .. } if *host == asking && !jobs.is_empty() => Effects::one(AttachEffect::Jobs(mem::take(jobs))), + _ => Effects::none(), + }, + AttachEvent::Close => match mem::replace(state, Attachment::Closed) { + Attachment::Attached { jobs, .. } => Effects::one(AttachEffect::Release(jobs)), + _ => Effects::none(), + }, + } +} + +/// What an engine holds. `N` is the native backend. +pub(super) enum Bindings<N> { + /// Headless: registrations are virtual and no backend ever connects. + Virtual(Registrations), + /// No backend. Nothing is registered, and nothing connects until something is. + Disconnected, + /// A backend and what it holds, which is nothing only until a first registration settles. + Connected { native: N, registrations: Registrations }, +} + +impl<N> Bindings<N> { + /// The registration of `shortcut`, if this engine holds one. + pub(super) fn find(&self, shortcut: &Shortcut) -> Option<ShortcutId> { + let (Self::Virtual(registrations) | Self::Connected { registrations, .. }) = self else { return None }; + find(registrations, shortcut) + } +} + +fn find(registrations: &Registrations, shortcut: &Shortcut) -> Option<ShortcutId> { + registrations.iter().find(|(_, s)| *s == shortcut).map(|(id, _)| *id) +} + +pub(super) enum BindEvent<N> { + /// `claimed`: another App in this process holds the chord. + Register { id: ShortcutId, shortcut: Shortcut, claimed: bool }, + /// The backend asked for by `Connect` opened. + Opened { native: N, id: ShortcutId, shortcut: Shortcut }, + /// The backend accepted a `Bind`. + Bound { id: ShortcutId, shortcut: Shortcut }, + /// The backend refused a `Bind`. + Rejected(ShortcutError), + Unregister(ShortcutId), + /// The backend carried out an `Unbind`. + Unbound(ShortcutId), + Release, +} + +pub(super) enum BindEffect<N> { + /// The operation fails with this error. + Refuse(ShortcutError), + /// Open a backend, then answer `Opened`. + Connect { id: ShortcutId, shortcut: Shortcut }, + /// Register with the backend, then answer `Bound` or `Rejected`. + Bind { id: ShortcutId, shortcut: Shortcut }, + /// Unregister from the backend, then answer `Unbound`. + Unbind(ShortcutId), + /// Record the chord against this App for the whole process. + Claim { id: ShortcutId, shortcut: Shortcut }, + Disclaim(ShortcutId), + DisclaimAll(Registrations), + /// Close this backend. + Disconnect(N), +} + +pub(super) fn step_bindings<N>(state: &mut Bindings<N>, event: BindEvent<N>) -> Effects<BindEffect<N>> { + match event { + BindEvent::Register { id, shortcut, claimed } => match state { + Bindings::Virtual(registrations) => { + if find(registrations, &shortcut).is_some() { return Effects::one(BindEffect::Refuse(ShortcutError::Conflict)); } + registrations.insert(id, shortcut); + Effects::none() + } + Bindings::Disconnected if claimed => Effects::one(BindEffect::Refuse(ShortcutError::Conflict)), + Bindings::Disconnected => Effects::one(BindEffect::Connect { id, shortcut }), + Bindings::Connected { registrations, .. } => { + if claimed || find(registrations, &shortcut).is_some() { return Effects::one(BindEffect::Refuse(ShortcutError::Conflict)); } + Effects::one(BindEffect::Bind { id, shortcut }) + } + }, + BindEvent::Opened { native, id, shortcut } => { + *state = Bindings::Connected { native, registrations: HashMap::new() }; + Effects::one(BindEffect::Bind { id, shortcut }) + } + BindEvent::Bound { id, shortcut } => { + let Bindings::Connected { registrations, .. } = state else { return Effects::none() }; + registrations.insert(id, shortcut.clone()); + Effects::one(BindEffect::Claim { id, shortcut }) + } + BindEvent::Rejected(error) => { + let mut effects = Effects::none(); + effects.extend(disconnect_if_empty(state)); + effects.push(BindEffect::Refuse(error)); + effects + } + BindEvent::Unregister(id) => match state { + Bindings::Virtual(registrations) => match registrations.remove(&id) { + Some(_) => Effects::none(), + None => Effects::one(BindEffect::Refuse(ShortcutError::UnknownId)), + }, + Bindings::Connected { registrations, .. } if registrations.contains_key(&id) => Effects::one(BindEffect::Unbind(id)), + _ => Effects::one(BindEffect::Refuse(ShortcutError::UnknownId)), + }, + BindEvent::Unbound(id) => { + let Bindings::Connected { registrations, .. } = state else { return Effects::none() }; + registrations.remove(&id); + // differs from dev: the backend retires before its claim goes, so no App can take the + // chord while this one's native grab is still live. + let mut effects = Effects::none(); + effects.extend(disconnect_if_empty(state)); + effects.push(BindEffect::Disclaim(id)); + effects + } + BindEvent::Release => match state { + Bindings::Virtual(registrations) => { + registrations.clear(); + Effects::none() + } + Bindings::Disconnected => Effects::none(), + Bindings::Connected { .. } => { + let Bindings::Connected { native, registrations } = mem::replace(state, Bindings::Disconnected) else { return Effects::none() }; + Effects::two(BindEffect::Disconnect(native), BindEffect::DisclaimAll(registrations)) + } + }, + } +} + +/// Close the connection when nothing is left on it. +fn disconnect_if_empty<N>(state: &mut Bindings<N>) -> Option<BindEffect<N>> { + if !matches!(state, Bindings::Connected { registrations, .. } if registrations.is_empty()) { return None; } + match mem::replace(state, Bindings::Disconnected) { + Bindings::Connected { native, .. } => Some(BindEffect::Disconnect(native)), + _ => None, + } +} diff --git a/app/vendor/rune/crates/rune/src/shortcuts/service/machine_tests.rs b/app/vendor/rune/crates/rune/src/shortcuts/service/machine_tests.rs new file mode 100644 index 0000000..baa3736 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/shortcuts/service/machine_tests.rs @@ -0,0 +1,836 @@ +//! Every short sequence of events through the machines, compared after each event with a +//! literal copy of the code they replaced. Both platform shapes run on every host, and a +//! teardown keeps running until the sequence says it finished. + +use super::*; +use std::{cell::RefCell, collections::BTreeSet, rc::Rc, sync::LazyLock}; + + +/// The sequences of `length` letters drawn from `0..letters`, each passed to `run`. +pub(super) fn every_sequence(letters: usize, length: u32, mut run: impl FnMut(&[usize])) { + let mut sequence = vec![0; length as usize]; + for code in 0..letters.pow(length) { + let mut rest = code; + for letter in &mut sequence { *letter = rest % letters; rest /= letters; } + run(&sequence); + } +} + +#[test] +fn only_a_close_reaches_closed_and_a_later_host_can_attach() { + let thread = std::thread::current().id(); + let mut state = Attachment::<u32>::Detached; + assert!(matches!(step_attachment(&mut state, AttachEvent::Call { from: thread, shared: true }).into_iter().next(), Some(AttachEffect::Refuse))); + assert!(matches!(state, Attachment::Detached)); + step_attachment(&mut state, AttachEvent::Attach { owner: thread, wake: Arc::new(|| {}), host: 1 }); + assert!(matches!(state, Attachment::Attached { .. })); + step_attachment(&mut state, AttachEvent::Close); + assert!(matches!(state, Attachment::Closed)); + assert!(matches!(step_attachment(&mut state, AttachEvent::Call { from: thread, shared: true }).into_iter().next(), Some(AttachEffect::Refuse))); + assert!(step_attachment(&mut state, AttachEvent::Attach { owner: thread, wake: Arc::new(|| {}), host: 2 }).is_empty()); + assert!(matches!(state, Attachment::Attached { .. })); +} + +#[test] +fn only_the_routed_host_takes_the_waiting_calls() { + let mut state = Attachment::<u32>::Detached; + step_attachment(&mut state, AttachEvent::Attach { owner: std::thread::current().id(), wake: Arc::new(|| {}), host: 1 }); + let other = std::thread::spawn(|| std::thread::current().id()).join().unwrap(); + assert!(matches!(step_attachment(&mut state, AttachEvent::Call { from: other, shared: false }).into_iter().next(), Some(AttachEffect::Wait))); + step_attachment(&mut state, AttachEvent::Post(7)); + // A later host takes routing; the call stays queued for it, and it is woken for it. + let wake: Waker = Arc::new(|| {}); + let attached = step_attachment(&mut state, AttachEvent::Attach { owner: std::thread::current().id(), wake: wake.clone(), host: 2 }); + assert!(matches!(attached.into_iter().next(), Some(AttachEffect::Wake(woken)) if Arc::ptr_eq(&woken, &wake)), "the host that inherits the call is woken"); + assert!(step_attachment(&mut state, AttachEvent::Drain { host: 1 }).is_empty(), "the replaced host leaves it"); + assert!(matches!(step_attachment(&mut state, AttachEvent::Drain { host: 2 }).into_iter().next(), Some(AttachEffect::Jobs(jobs)) if jobs == [7])); +} + +// The engine as it was, with `super::backend` behind a field and its own process-wide list. +static OLD_NATIVE: Mutex<Vec<(ShortcutId, Shortcut, &'static str)>> = Mutex::new(Vec::new()); + +struct OldEngine { + title: &'static str, + headless: bool, + wayland: bool, + sink: Sink, + connect: Connect, + native: Option<NativeBackend>, + registrations: HashMap<ShortcutId, Shortcut>, +} + +impl OldEngine { + fn register(&mut self, id: ShortcutId, shortcut: Shortcut) -> Result<(), ShortcutError> { + if self.registrations.values().any(|s| s == &shortcut) { return Err(ShortcutError::Conflict); } + if !self.headless { + // Another App in this process holds it; some backends (the portal) wouldn't refuse. + if OLD_NATIVE.lock().unwrap().iter().any(|(_, s, _)| s == &shortcut) { return Err(ShortcutError::Conflict); } + if self.native.is_none() { self.native = Some((self.connect)(self.wayland, self.sink.clone())?); } + if let Err(error) = self.native.as_mut().unwrap().register(id, &shortcut) { + if self.registrations.is_empty() { self.native = None; } + return Err(error); + } + } + if !self.headless { OLD_NATIVE.lock().unwrap().push((id, shortcut.clone(), self.title)); } + self.registrations.insert(id, shortcut); + Ok(()) + } + + fn unregister(&mut self, id: ShortcutId) -> Result<(), ShortcutError> { + if !self.registrations.contains_key(&id) { return Err(ShortcutError::UnknownId); } + if let Some(native) = self.native.as_mut() { native.unregister(id)?; } + self.registrations.remove(&id); + OLD_NATIVE.lock().unwrap().retain(|(native, ..)| *native != id); + // Drop the connection/listener when the last registration goes away. + if self.registrations.is_empty() { self.native = None; } + Ok(()) + } + + fn owner(&self, shortcut: &Shortcut) -> Option<String> { + if self.registrations.values().any(|s| s == shortcut) { return Some(self.title.into()); } + if self.headless { return None; } + let other = OLD_NATIVE.lock().unwrap().iter().find(|(_, s, _)| s == shortcut).map(|(.., title)| (*title).into()); + other.or_else(|| super::super::system_owner(shortcut)) + } + + fn release(&mut self) { + self.native = None; + OLD_NATIVE.lock().unwrap().retain(|(id, ..)| !self.registrations.contains_key(id)); + self.registrations.clear(); + } +} + +impl Drop for OldEngine { + fn drop(&mut self) { self.release(); } +} + +const X: &str = "ctrl+alt+shift+f20"; +const Y: &str = "ctrl+alt+shift+f21"; + +static CHORDS: LazyLock<[Shortcut; 2]> = LazyLock::new(|| [chord(X), chord(Y)]); + +fn chord(text: &str) -> Shortcut { text.parse().unwrap() } + +/// Claims on the chords these tests use, in order. Other tests share `NATIVE`. +fn claims(native: &Mutex<Vec<(ShortcutId, Shortcut, &'static str)>>) -> Vec<(u32, &'static str)> { + native.lock().unwrap().iter().filter(|(_, s, _)| CHORDS.contains(s)).map(|(id, _, title)| (id.0, *title)).collect() +} + +#[derive(Clone, Debug, PartialEq)] +enum Note { + Connect { wayland: bool }, + Register(u32), + Unregister(u32), + /// A backend closed while these claims stood. + Closed(Vec<u32>), +} + +#[derive(Clone, Copy, PartialEq)] +enum Side { Old, New } + +struct Rig { connect: Result<(), ShortcutError>, register: Result<(), ShortcutError>, unregister: Result<(), ShortcutError>, old: Vec<Note>, new: Vec<Note> } + +impl Rig { + fn note(&mut self, side: Side, note: Note) { if side == Side::Old { self.old.push(note) } else { self.new.push(note) } } +} + +thread_local! { + static RIG: RefCell<Rig> = RefCell::new(Rig { connect: Ok(()), register: Ok(()), unregister: Ok(()), old: vec![], new: vec![] }); +} + +struct Scripted(Side); + +impl Backend for Scripted { + fn register(&mut self, id: ShortcutId, _: &Shortcut) -> Result<(), ShortcutError> { + RIG.with(|rig| { let mut rig = rig.borrow_mut(); rig.note(self.0, Note::Register(id.0)); rig.register.clone() }) + } + fn unregister(&mut self, id: ShortcutId) -> Result<(), ShortcutError> { + RIG.with(|rig| { let mut rig = rig.borrow_mut(); rig.note(self.0, Note::Unregister(id.0)); rig.unregister.clone() }) + } +} + +impl Drop for Scripted { + fn drop(&mut self) { + let mut standing: Vec<u32> = claims(if self.0 == Side::Old { &OLD_NATIVE } else { &NATIVE }).into_iter().map(|(id, _)| id).collect(); + standing.sort(); + RIG.with(|rig| rig.borrow_mut().note(self.0, Note::Closed(standing))); + } +} + +fn connect(side: Side, wayland: bool) -> Result<NativeBackend, ShortcutError> { + RIG.with(|rig| { let mut rig = rig.borrow_mut(); rig.note(side, Note::Connect { wayland }); rig.connect.clone() })?; + Ok(Box::new(Scripted(side))) +} + +fn connect_old(wayland: bool, _: Sink) -> Result<NativeBackend, ShortcutError> { connect(Side::Old, wayland) } + +fn connect_new(wayland: bool, _: Sink) -> Result<NativeBackend, ShortcutError> { connect(Side::New, wayland) } + +#[derive(Clone, Copy, Debug)] +enum Start { Headless, NoBackend, EmptyBackend } + +fn old_engine(title: &'static str, start: Start) -> OldEngine { + let native = matches!(start, Start::EmptyBackend).then(|| Box::new(Scripted(Side::Old)) as NativeBackend); + OldEngine { title, headless: matches!(start, Start::Headless), wayland: true, sink: Arc::new(|_, _| {}), connect: connect_old, native, registrations: HashMap::new() } +} + +fn new_engine(title: &'static str, start: Start) -> Engine { + let bindings = match start { + Start::Headless => Bindings::Virtual(HashMap::new()), + Start::NoBackend => Bindings::Disconnected, + Start::EmptyBackend => Bindings::Connected { native: Box::new(Scripted(Side::New)) as NativeBackend, registrations: HashMap::new() }, + }; + Engine { title, wayland: true, sink: Arc::new(|_, _| {}), connect: connect_new, bindings } +} + +/// Whether a backend is connected, and the sorted registrations. +type EngineView = (bool, Vec<(u32, String)>); + +fn listed(registrations: &HashMap<ShortcutId, Shortcut>) -> Vec<(u32, String)> { + let mut list: Vec<_> = registrations.iter().map(|(id, s)| (id.0, format!("{s:?}"))).collect(); + list.sort(); + list +} + +fn old_view(engine: &OldEngine) -> EngineView { (engine.native.is_some(), listed(&engine.registrations)) } + +fn new_view(engine: &Engine) -> EngineView { + match &engine.bindings { + Bindings::Virtual(registrations) => (false, listed(registrations)), + Bindings::Disconnected => (false, vec![]), + Bindings::Connected { registrations, .. } => (true, listed(registrations)), + } +} + +/// The backend notes in order. The one approved difference: a native now closes before its last +/// claim goes, so a close reports dev's claims plus exactly the chord it just retired. Every other +/// close matches dev exactly. Returns whether the departure was seen. +fn assert_notes(old: &[Note], new: &[Note], at: &str, retiring: Option<u32>) -> bool { + assert_eq!(new.len(), old.len(), "{at}"); + let mut departed = false; + for (n, (new, old)) in new.iter().zip(old).enumerate() { + // differs from dev: a closing backend still holds the claim of the chord it retired for. + if let (Note::Closed(new), Note::Closed(old)) = (new, old) { + let mut expected = old.clone(); + if let Some(id) = retiring { if !expected.contains(&id) { expected.push(id); expected.sort(); } } + assert_eq!(new, &expected, "{at} note {n}: a close must report dev's claims, plus only the chord it retired"); + departed |= new != old; + continue; + } + assert_eq!(new, old, "{at} note {n}"); + } + departed +} + +/// Runs `body` against both engines' results with one script, then clears the script. +fn scripted<T>(connect: Result<(), ShortcutError>, register: Result<(), ShortcutError>, unregister: Result<(), ShortcutError>, body: impl FnOnce() -> T) -> T { + RIG.with(|rig| { let mut rig = rig.borrow_mut(); rig.connect = connect; rig.register = register; rig.unregister = unregister; }); + let result = body(); + RIG.with(|rig| { let mut rig = rig.borrow_mut(); rig.connect = Ok(()); rig.register = Ok(()); rig.unregister = Ok(()); }); + result +} + +const BASE_ID: u32 = 0x4000_0000; + +fn run_engines(start: Start, sequence: &[usize]) -> bool { + let (mut old, mut new) = (old_engine("Subject", start), new_engine("Subject", start)); + let (mut old_other, mut new_other) = (old_engine("Other", Start::NoBackend), new_engine("Other", Start::NoBackend)); + let [x, y] = &*CHORDS; + let (mut next, mut held_x, mut held_y) = (BASE_ID, ShortcutId(BASE_ID - 1), ShortcutId(BASE_ID - 2)); + let denied = || Err(ShortcutError::PermissionDenied); + let broken = || Err(ShortcutError::Backend("refused".into())); + let mut departed = false; + for (n, letter) in sequence.iter().enumerate() { + next += 1; + let id = ShortcutId(next); + let (expected, actual) = match letter { + 0 | 1 => { + let chord = if *letter == 0 { x } else { y }; + let results = (old.register(id, chord.clone()), new.register(id, chord.clone())); + if results.1.is_ok() { if *letter == 0 { held_x = id } else { held_y = id } } + results + } + 2 => scripted(denied(), Ok(()), Ok(()), || (old.register(id, x.clone()), new.register(id, x.clone()))), + 3 => scripted(Ok(()), broken(), Ok(()), || (old.register(id, y.clone()), new.register(id, y.clone()))), + 4 => (old.unregister(held_x), new.unregister(held_x)), + 5 => (old.unregister(held_y), new.unregister(held_y)), + 6 => scripted(Ok(()), Ok(()), broken(), || (old.unregister(held_x), new.unregister(held_x))), + 7 => (old_other.register(id, x.clone()), new_other.register(id, x.clone())), + 8 => { old_other.release(); new_other.release(); (Ok(()), Ok(())) } + _ => { old.release(); new.release(); (Ok(()), Ok(())) } + }; + let at = || format!("{start:?} {sequence:?} at {n}"); + assert_eq!(actual, expected, "{}", at()); + // The chord this event retired, if it did, so a close can only report that one extra claim. + let retiring = match letter { 4 | 6 => Some(held_x), 5 => Some(held_y), _ => None } + .filter(|_| expected.is_ok()).map(|id| id.0); + assert_eq!(new_view(&new), old_view(&old), "{}", at()); + assert_eq!(new_view(&new_other), old_view(&old_other), "{}", at()); + assert_eq!(claims(&NATIVE), claims(&OLD_NATIVE), "{}", at()); + for chord in [x, y] { + assert_eq!(new.owner(chord), old.owner(chord), "{}", at()); + assert_eq!(new.bindings.find(chord).is_some(), old.registrations.values().any(|s| s == chord), "{}", at()); + } + RIG.with(|rig| { + let mut rig = rig.borrow_mut(); + departed |= assert_notes(&rig.old, &rig.new, &at(), retiring); + rig.new.clear(); + rig.old.clear(); + }); + } + drop(old); drop(new); drop(old_other); drop(new_other); + assert!(claims(&NATIVE).is_empty() && claims(&OLD_NATIVE).is_empty(), "{start:?} {sequence:?}"); + RIG.with(|rig| { + let mut rig = rig.borrow_mut(); + departed |= assert_notes(&rig.old, &rig.new, &format!("teardown of {start:?} {sequence:?}"), None); + rig.new.clear(); + rig.old.clear(); + }); + departed +} + +#[test] +fn every_engine_sequence_matches_the_old_engine() { + let mut departed = false; + for start in [Start::Headless, Start::NoBackend, Start::EmptyBackend] { + every_sequence(10, 5, |sequence| departed |= run_engines(start, sequence)); + } + assert!(departed, "the walk never saw the backend retire before its claim went"); +} + +#[test] +fn no_backend_connects_while_an_empty_backend_binds() { + let (id, shortcut) = (ShortcutId(1), chord("ctrl+alt+shift+f22")); + let register = || BindEvent::Register { id, shortcut: shortcut.clone(), claimed: false }; + + let mut none = Bindings::<()>::Disconnected; + assert!(matches!(step_bindings(&mut none, register()).into_iter().next(), Some(BindEffect::Connect { .. }))); + assert!(matches!(none, Bindings::Disconnected), "connecting is the driver's to report"); + + let mut empty = Bindings::Connected { native: (), registrations: HashMap::new() }; + assert!(matches!(step_bindings(&mut empty, register()).into_iter().next(), Some(BindEffect::Bind { .. }))); + assert!(matches!(step_bindings(&mut empty, BindEvent::Rejected(ShortcutError::Unsupported)).into_iter().next(), Some(BindEffect::Disconnect(())))); + assert!(matches!(empty, Bindings::Disconnected), "a refused first registration closes the backend"); +} + +#[test] +fn the_last_unregistration_closes_before_disclaiming_and_release_closes_first() { + let (id, shortcut) = (ShortcutId(1), chord("ctrl+alt+shift+f22")); + let mut state = Bindings::Connected { native: (), registrations: HashMap::from([(id, shortcut.clone())]) }; + let effects: Vec<_> = step_bindings(&mut state, BindEvent::Unbound(id)).into_iter().collect(); + // differs from dev: the native goes first, so the claim outlives the grab it describes. + assert!(matches!(effects.as_slice(), [BindEffect::Disconnect(()), BindEffect::Disclaim(_)])); + + let mut state = Bindings::Connected { native: (), registrations: HashMap::from([(id, shortcut)]) }; + let effects: Vec<_> = step_bindings(&mut state, BindEvent::Release).into_iter().collect(); + assert!(matches!(effects.as_slice(), [BindEffect::Disconnect(()), BindEffect::DisclaimAll(_)])); + assert!(matches!(state, Bindings::Disconnected)); +} + +// Two hosts overlapping, and calls stopped partway through an engine. Three sides play each +// sequence: the code as it was, that code with the marked departure, and the new code. The new +// code must match the marked reference at every event, and the reference must match the old +// code up to the event where the departure first shows. +static OVERLAP_CHORD: LazyLock<Shortcut> = LazyLock::new(|| chord("ctrl+alt+shift+f18")); +const OVERLAP_ID: u32 = 0x5000_0000; + +const STALE_CLAIM: &str = "a replaced engine nobody is using kept its claim"; +const STALE_CONFLICT: &str = "a conflict came from an engine nobody is using"; +const GRAB_WITHOUT_OWNER: &str = "a live engine holds a chord with no owner on record"; +const OWNER_WITHOUT_GRAB: &str = "an owner is on record for a chord no live engine holds"; +const WAKE_LETS_GO: &str = "a call in its wake no longer keeps the engine's claims"; +const STALE_CLOSE_KEEPS: &str = "a replaced host's close left the newer host's engine and handlers"; + +fn overlap_claims(native: &Mutex<Vec<(ShortcutId, Shortcut, &'static str)>>) -> Vec<u32> { + let mut claims: Vec<_> = native.lock().unwrap().iter().filter(|(_, s, _)| *s == *OVERLAP_CHORD).map(|(id, ..)| id.0).collect(); + claims.sort(); + claims +} + +trait OverlapEngine { + fn fresh() -> Self; + fn add(&mut self, id: u32) -> Result<(), ShortcutError>; + fn remove(&mut self, id: u32) -> Result<(), ShortcutError>; + fn held(&self) -> Vec<u32>; + fn close(&mut self); +} + +impl OverlapEngine for OldEngine { + fn fresh() -> Self { old_engine("Overlap", Start::NoBackend) } + fn add(&mut self, id: u32) -> Result<(), ShortcutError> { self.register(ShortcutId(id), OVERLAP_CHORD.clone()) } + fn remove(&mut self, id: u32) -> Result<(), ShortcutError> { self.unregister(ShortcutId(id)) } + fn held(&self) -> Vec<u32> { self.registrations.keys().map(|id| id.0).collect() } + fn close(&mut self) { self.release(); } +} + +impl OverlapEngine for Engine { + fn fresh() -> Self { new_engine("Overlap", Start::NoBackend) } + fn add(&mut self, id: u32) -> Result<(), ShortcutError> { self.register(ShortcutId(id), OVERLAP_CHORD.clone()) } + fn remove(&mut self, id: u32) -> Result<(), ShortcutError> { self.unregister(ShortcutId(id)) } + fn held(&self) -> Vec<u32> { + let (Bindings::Virtual(registrations) | Bindings::Connected { registrations, .. }) = &self.bindings else { return vec![] }; + registrations.keys().map(|id| id.0).collect() + } + fn close(&mut self) { self.release(); } +} + +#[derive(Clone, Debug, PartialEq)] +enum Seen { Skipped, Done, Parked, Answer(Result<(), ShortcutError>) } + +type Handle<E> = Rc<RefCell<E>>; + +#[derive(Clone, Copy)] +enum Waiter { Register(u32), Unregister(u32) } + +/// What every side shares: the hosts, the slot, the handlers and the stopped calls. +struct Stage<E> { + attached: bool, + open: [bool; 2], + slot: Option<Handle<E>>, + handlers: BTreeSet<u32>, + /// A call is stopped in its wake, past the engine. + in_wake: bool, + /// What that call still holds. + held: Option<Handle<E>>, + /// A call stopped inside the engine, holding its lock. + inside: Option<Handle<E>>, + /// A call parked on the engine's lock, holding the routing lock. + waiting: Option<(Handle<E>, Waiter)>, + /// A host whose engine is in the slot but whose attach waits for that routing lock. + pending: Option<usize>, + /// The host that installed last, whose engine the slot holds until its close takes it. + newest: Option<usize>, + next: u32, + latest: Option<u32>, + /// The first registration this host made, which a successor never sees again. + first: Option<u32>, + broken: Vec<&'static str>, +} + +impl<E: OverlapEngine> Stage<E> { + fn new() -> Self { + Self { attached: false, open: [false; 2], slot: None, handlers: BTreeSet::new(), in_wake: false, held: None, inside: None, waiting: None, pending: None, newest: None, next: OVERLAP_ID, latest: None, first: None, broken: vec![] } + } + + fn slot_held(&self) -> Vec<u32> { self.slot.as_ref().map_or_else(Vec::new, |engine| engine.borrow().held()) } + + fn slot_is_inside(&self) -> bool { + matches!((&self.slot, &self.inside), (Some(slot), Some(inside)) if Rc::ptr_eq(slot, inside)) + } + + /// Every engine something still keeps alive. + fn alive(&self) -> Vec<&Handle<E>> { + self.slot.iter().chain(&self.held).chain(&self.inside).chain(self.waiting.iter().map(|(engine, _)| engine)).collect() + } + + /// A call reaches `engine`, and the caller lets go of it. + fn finish(&mut self, engine: Handle<E>, waiter: Waiter) -> Seen { + let on_slot = self.slot.as_ref().is_some_and(|slot| Rc::ptr_eq(slot, &engine)); + let answer = match waiter { + Waiter::Register(id) => engine.borrow_mut().add(id), + Waiter::Unregister(id) => engine.borrow_mut().remove(id), + }; + drop(engine); + match (waiter, &answer) { + (Waiter::Register(id), Ok(())) => { self.latest = Some(id); self.first.get_or_insert(id); } + (Waiter::Register(id), Err(error)) => { + self.handlers.remove(&id); + if *error == ShortcutError::Conflict && on_slot && self.slot_held().is_empty() && self.inside.is_none() { self.broken.push(STALE_CONFLICT); } + } + (Waiter::Unregister(id), Ok(())) => { self.handlers.remove(&id); } + (Waiter::Unregister(_), Err(_)) => {} + } + Seen::Answer(answer) + } + + fn call(&mut self, waiter: Waiter) -> Seen { + let Some(engine) = self.slot.clone().filter(|_| self.attached) else { + if let Waiter::Register(id) = waiter { self.handlers.remove(&id); } + return Seen::Answer(Err(ShortcutError::NotRunning)); + }; + if self.slot_is_inside() { + self.waiting = Some((engine, waiter)); + return Seen::Parked; + } + self.finish(engine, waiter) + } + + fn register(&mut self) -> Seen { + if self.waiting.is_some() { return Seen::Skipped; } + self.next += 1; + self.handlers.insert(self.next); + self.call(Waiter::Register(self.next)) + } + + fn unregister(&mut self) -> Seen { + let (Some(id), None) = (self.latest, &self.waiting) else { return Seen::Skipped }; + self.call(Waiter::Unregister(id)) + } + + /// Unregisters the first chord this host registered, which the successor no longer has. + fn unregister_first(&mut self) -> Seen { + let (Some(id), None) = (self.first, &self.waiting) else { return Seen::Skipped }; + self.call(Waiter::Unregister(id)) + } + + /// The engine goes in the slot under the slot's own lock; the attach then waits for routing. + fn attach(&mut self, host: usize) -> Seen { + self.slot = Some(Rc::new(RefCell::new(E::fresh()))); + self.newest = Some(host); + if self.waiting.is_some() { + self.pending = Some(host); + return Seen::Parked; + } + self.finish_attach(host); + Seen::Done + } + + fn finish_attach(&mut self, host: usize) { + self.open[host] = true; + self.attached = true; + } + + /// Any close ends routing. `own`: it also takes the slot's engine and clears the handlers. + fn close(&mut self, host: usize, own: bool) -> Seen { + self.open[host] = false; + self.attached = false; + if !own { return Seen::Done; } + if let Some(engine) = self.slot.take() { engine.borrow_mut().close(); } + self.handlers.clear(); + Seen::Done + } + + /// The call inside leaves. A call parked behind it takes the engine and lets go of routing, + /// and only then can an attach waiting for routing finish. + fn leave(&mut self) -> Seen { + self.inside = None; + let Some((engine, waiter)) = self.waiting.take() else { return Seen::Done }; + let seen = self.finish(engine, waiter); + if let Some(host) = self.pending.take() { self.finish_attach(host); } + seen + } +} + +trait Overlap { + type E: OverlapEngine; + fn stage(&mut self) -> &mut Stage<Self::E>; + fn stage_ref(&self) -> &Stage<Self::E>; + fn stop_in_wake(&mut self); + /// Whether `host`'s close takes the slot's engine and clears the handlers. + fn closes_own(&self, host: usize) -> bool; + fn claims(&self) -> Vec<u32>; +} + +/// The code as it was, or with `departures` the same code plus the marked change. +struct Reference { stage: Stage<OldEngine>, departures: bool } + +impl Overlap for Reference { + type E = OldEngine; + fn stage(&mut self) -> &mut Stage<OldEngine> { &mut self.stage } + fn stage_ref(&self) -> &Stage<OldEngine> { &self.stage } + + fn stop_in_wake(&mut self) { + // differs from dev: a call lets go of the engine before its wake. + if self.departures { return; } + self.stage.held = self.stage.slot.clone(); + } + + fn closes_own(&self, host: usize) -> bool { + // differs from dev: a replaced host's close leaves the newer host's engine and handlers. + !self.departures || self.stage.newest == Some(host) + } + + fn claims(&self) -> Vec<u32> { overlap_claims(&OLD_NATIVE) } +} + +/// The new code around the real engine: a call holds nothing during its wake. +struct NewOverlap(Stage<Engine>); + +impl Overlap for NewOverlap { + type E = Engine; + fn stage(&mut self) -> &mut Stage<Engine> { &mut self.0 } + fn stage_ref(&self) -> &Stage<Engine> { &self.0 } + fn stop_in_wake(&mut self) {} + /// A guard takes only its own generation's engine, and only the newest host's close clears + /// the handlers. + fn closes_own(&self, host: usize) -> bool { self.0.newest == Some(host) } + fn claims(&self) -> Vec<u32> { overlap_claims(&NATIVE) } +} + +/// Letters: 0, 1 attach a host; 2, 3 close one; 4 register the chord; 5 unregister the latest; +/// 6, 7 a call stops in its wake and goes; 8 a call stops inside the engine; 9 it leaves; +/// 10 it leaves and the backend then refuses what was waiting; 11 unregister the first chord. +fn overlap_play(world: &mut impl Overlap, letter: usize) -> Seen { + let own = matches!(letter, 2 | 3) && world.closes_own(letter - 2); + let stage = world.stage(); + let reachable = stage.attached && stage.slot.is_some(); + match letter { + 0 | 1 if stage.open[letter] || stage.pending.is_some() => Seen::Skipped, + 0 | 1 => stage.attach(letter), + 2 | 3 if !stage.open[letter - 2] || stage.inside.is_some() || stage.waiting.is_some() => Seen::Skipped, + 2 | 3 => stage.close(letter - 2, own), + 4 => stage.register(), + 5 => stage.unregister(), + 6 if stage.in_wake || !reachable || stage.slot_is_inside() || stage.waiting.is_some() => Seen::Skipped, + 6 => { stage.in_wake = true; world.stop_in_wake(); Seen::Done } + 7 if !stage.in_wake => Seen::Skipped, + 7 => { stage.in_wake = false; stage.held = None; Seen::Done } + 8 if stage.inside.is_some() || !reachable || stage.waiting.is_some() => Seen::Skipped, + 8 => { stage.inside = stage.slot.clone(); Seen::Done } + 9 if stage.inside.is_none() => Seen::Skipped, + 9 => stage.leave(), + 10 if stage.inside.is_none() || stage.waiting.is_none() => Seen::Skipped, + 10 => { + let broken = || Err(ShortcutError::Backend("refused".into())); + scripted(Ok(()), broken(), broken(), || stage.leave()) + } + _ => stage.unregister_first(), + } +} + +fn overlap_check(world: &mut impl Overlap) { + let claims = world.claims(); + let stage = world.stage(); + let live = stage.slot_held(); + let alive: Vec<u32> = stage.alive().iter().flat_map(|engine| engine.borrow().held()).collect(); + if stage.inside.is_none() && stage.waiting.is_none() && claims.iter().any(|id| !live.contains(id)) { stage.broken.push(STALE_CLAIM); } + if alive.iter().any(|id| !claims.contains(id)) { stage.broken.push(GRAB_WITHOUT_OWNER); } + if claims.iter().any(|id| !alive.contains(id)) { stage.broken.push(OWNER_WITHOUT_GRAB); } +} + +type OverlapView = (Seen, bool, [bool; 2], Vec<u32>, Vec<u32>, Vec<u32>, Vec<u32>); + +fn overlap_view(world: &impl Overlap, seen: Seen) -> OverlapView { + let stage = world.stage_ref(); + let mut live = stage.slot_held(); + live.sort(); + // Claims only an engine that a call in its wake alone keeps still holds. + let mut wake: Vec<u32> = stage.held.iter().filter(|held| !stage.slot.as_ref().is_some_and(|slot| Rc::ptr_eq(slot, held))).flat_map(|held| held.borrow().held()).collect(); + wake.sort(); + (seen, stage.attached, stage.open, stage.handlers.iter().copied().collect(), world.claims(), live, wake) +} + +fn clear_notes() { RIG.with(|rig| { let mut rig = rig.borrow_mut(); rig.new.clear(); rig.old.clear(); }); } + +/// What the code as it was does with `sequence`, and which invariants it broke. +fn overlap_dev_trace(sequence: &[usize], found: &mut BTreeSet<&'static str>) -> Vec<OverlapView> { + let mut dev = Reference { stage: Stage::new(), departures: false }; + let mut trace = vec![]; + for letter in sequence { + let seen = overlap_play(&mut dev, *letter); + overlap_check(&mut dev); + trace.push(overlap_view(&dev, seen)); + } + found.extend(dev.stage.broken.iter()); + drop(dev); + assert!(overlap_claims(&OLD_NATIVE).is_empty(), "{sequence:?}"); + trace +} + +/// The departure the marked reference shows against dev, or None when they agree. Every event is +/// checked, so a later event that differs for another reason still fails the walk. differs from +/// dev: a call lets go of its engine before its wake, so dev alone still holds the claims of an +/// engine nothing but that call keeps, and every registration those claims refused. +#[allow(clippy::too_many_arguments)] +fn approved_difference(dev: &OverlapView, want: &OverlapView, target: Option<u32>, registering: bool, departed: &mut BTreeSet<u32>, kept: &BTreeSet<u32>, sequence: &[usize], n: usize) -> Option<&'static str> { + if dev == want { return None; } + let at = format!("{sequence:?} at {n}\ndev {dev:?}\nwant {want:?}"); + assert_eq!((want.1, want.2), (dev.1, dev.2), "the hosts agree: {at}"); + // differs from dev: a replaced host's close leaves the newer host's engine and handlers, so + // `kept`, what they held then, may still stand where dev's close took it. + let only_kept = |dev: &[u32], want: &[u32]| dev.iter().all(|id| want.contains(id)) && want.iter().all(|id| dev.contains(id) || kept.contains(id)); + if (&dev.0, &dev.6) == (&want.0, &want.6) && only_kept(&dev.3, &want.3) && only_kept(&dev.4, &want.4) && only_kept(&dev.5, &want.5) { + return Some(STALE_CLOSE_KEEPS); + } + // An event that did nothing, stopped in its wake, or parked is not an answer, and must keep + // its exact kind: only the answers may move under the departure. + // An event that did nothing, stopped in its wake, or parked is not an answer, and must keep + // its exact kind: only the answers may move under the departure. + match (&dev.0, &want.0) { + (Seen::Answer(_), Seen::Answer(_)) => {} + (before, after) => assert_eq!(before, after, "an event kind changed for another reason: {at}"), + } + let answer = |view: &OverlapView| match &view.0 { Seen::Answer(answer) => Some(answer.clone()), _ => None }; + let (before, after) = (answer(dev), answer(want)); + let mut allowed: BTreeSet<u32> = departed.iter().copied().chain(dev.6.iter().copied()).collect(); + if before != after { + let succeeded = matches!((&before, &after), (Some(Err(ShortcutError::Conflict | ShortcutError::UnknownId)), Some(Ok(())))); + let backend = matches!((&before, &after), (Some(Err(ShortcutError::Conflict)), Some(Err(ShortcutError::Backend(_))))); + // differs from dev: the chord dev refused while its replaced engine still held it is + // registered here, so the successor's own duplicate check refuses the one dev took. + let occupied = matches!((&before, &after), (Some(Ok(())), Some(Err(ShortcutError::Conflict)))); + if occupied { + let gained: Vec<u32> = want.5.iter().copied().filter(|id| !dev.5.contains(id)).collect(); + assert!(!gained.is_empty() && gained.iter().all(|id| departed.contains(id)), + "a registration was refused with no approved registration holding the chord in {at}"); + if let Some(id) = target { allowed.insert(id); } + } + assert!(succeeded || backend || occupied, "an answer changed for another reason: {before:?} -> {after:?} in {at}"); + if succeeded { + let id = target.expect("a call that succeeded where dev refused has an id"); + if registering { + // Only the claim a call still held in its wake can refuse dev's registration. + assert!(!dev.6.is_empty(), "a registration succeeded with no wake-held claim: {at}"); + departed.insert(id); + } else { + // An unregister can only succeed where dev lacked the chord if the departure + // registered it on an earlier event. + assert!(departed.contains(&id), "an unregister succeeded where dev never had the chord: {at}"); + } + } + } + let aside = |dev: &[u32], want: &[u32]| { + let lost: Vec<u32> = dev.iter().copied().filter(|id| !want.contains(id)).collect(); + let gained: Vec<u32> = want.iter().copied().filter(|id| !dev.contains(id)).collect(); + (lost, gained) + }; + let (lost, gained) = aside(&dev.4, &want.4); + assert!(lost.iter().all(|id| allowed.contains(id)), "a claim went for another reason in {at}"); + assert!(gained.iter().all(|id| departed.contains(id) || kept.contains(id)), "a claim appeared for another reason in {at}"); + for (lost, gained) in [aside(&dev.3, &want.3), aside(&dev.5, &want.5)] { + assert!(lost.iter().all(|id| allowed.contains(id)), "a handler or engine entry went for another reason in {at}"); + assert!(gained.iter().all(|id| departed.contains(id) || kept.contains(id)), "a handler or engine entry appeared for another reason in {at}"); + } + Some(WAKE_LETS_GO) +} + +/// Replays `sequence`. Returns whether its last letter did anything. +fn overlap_replay(sequence: &[usize], found: &mut BTreeSet<&'static str>, fired: &mut BTreeSet<&'static str>) -> bool { + let dev = overlap_dev_trace(sequence, found); + let mut reference = Reference { stage: Stage::new(), departures: true }; + let mut new = NewOverlap(Stage::new()); + let (mut moved, mut departed, mut kept) = (false, BTreeSet::new(), BTreeSet::new()); + for (n, letter) in sequence.iter().enumerate() { + assert_eq!(new.0.next, reference.stage.next, "{sequence:?} at {n}"); + let (target, registering) = match letter { + 4 => (Some(new.0.next + 1), true), + 5 => (new.0.latest, false), + 9 | 10 => match new.0.waiting.as_ref().map(|(_, waiter)| *waiter) { + Some(Waiter::Register(id)) => (Some(id), true), + Some(Waiter::Unregister(id)) => (Some(id), false), + None => (None, false), + }, + 11 => (new.0.first, false), + _ => (None, false), + }; + let expected = overlap_play(&mut reference, *letter); + let actual = overlap_play(&mut new, *letter); + if matches!(letter, 2 | 3) && expected == Seen::Done && !reference.closes_own(letter - 2) { + kept.extend(reference.stage.handlers.iter().copied().chain(reference.stage.slot_held())); + } + moved = actual != Seen::Skipped; + overlap_check(&mut new); + assert!(new.0.broken.is_empty(), "{:?}: {sequence:?} at {n}", new.0.broken); + let want = overlap_view(&reference, expected); + assert_eq!(overlap_view(&new, actual), want, "{sequence:?} at {n}"); + if let Some(departure) = approved_difference(&dev[n], &want, target, registering, &mut departed, &kept, sequence, n) { + fired.insert(departure); + } + } + drop(reference); + drop(new); + assert!(overlap_claims(&NATIVE).is_empty() && overlap_claims(&OLD_NATIVE).is_empty(), "{sequence:?}"); + clear_notes(); + moved +} + +fn overlap_walk(sequence: &mut Vec<usize>, depth: usize, found: &mut BTreeSet<&'static str>, fired: &mut BTreeSet<&'static str>) { + for letter in 0..12 { + sequence.push(letter); + if overlap_replay(sequence, found, fired) && sequence.len() < depth { overlap_walk(sequence, depth, found, fired); } + sequence.pop(); + } +} + +/// The walks and their focused scripts share the process claim lists and the ids they use. +static CLAIMS: Mutex<()> = Mutex::new(()); + +#[test] +fn an_attach_waits_for_a_call_parked_on_routing() { + let _claims = CLAIMS.lock().unwrap_or_else(|error| error.into_inner()); + let mut dev = Reference { stage: Stage::new(), departures: false }; + let mut new = NewOverlap(Stage::new()); + // Attach A, a call stops inside A's engine, a registration parks behind it, B attaches, the + // call inside leaves. + let script = [(0, Seen::Done), (8, Seen::Done), (4, Seen::Parked), (1, Seen::Parked), (9, Seen::Answer(Ok(())))]; + for (n, (letter, expected)) in script.into_iter().enumerate() { + let (dev_seen, new_seen) = (overlap_play(&mut dev, letter), overlap_play(&mut new, letter)); + assert_eq!((&dev_seen, &new_seen), (&expected, &expected), "event {n}"); + assert_eq!(overlap_view(&new, new_seen), overlap_view(&dev, dev_seen), "event {n}"); + if n == 3 { assert_eq!((dev.stage.attached, dev.stage.open), (true, [true, false]), "B waits while the parked call holds routing"); } + } + // The parked call ran on A's engine, which still holds the chord, and then B took over. + assert_eq!((dev.stage.attached, dev.stage.open), (true, [true, true]), "B takes over once the call lets go of routing"); + drop(dev); + drop(new); + clear_notes(); +} + +#[test] +fn a_parked_unregister_finishes_on_the_engine_it_captured_and_the_successor_forgets_it() { + let _claims = CLAIMS.lock().unwrap_or_else(|error| error.into_inner()); + let mut dev = Reference { stage: Stage::new(), departures: false }; + let mut new = NewOverlap(Stage::new()); + // The parked unregister answers Ok on the engine that captured the chord; B never had it. + let script = [(0, Seen::Done), (4, Seen::Answer(Ok(()))), (8, Seen::Done), (5, Seen::Parked), (1, Seen::Parked), (9, Seen::Answer(Ok(()))), (11, Seen::Answer(Err(ShortcutError::UnknownId)))]; + for (n, (letter, expected)) in script.into_iter().enumerate() { + let (dev_seen, new_seen) = (overlap_play(&mut dev, letter), overlap_play(&mut new, letter)); + assert_eq!((&dev_seen, &new_seen), (&expected, &expected), "event {n}"); + assert_eq!(overlap_view(&new, new_seen), overlap_view(&dev, dev_seen), "event {n}"); + } + assert_eq!(new.0.open, [true, true], "B attaches once the parked call lets go of routing"); + assert!(new.0.handlers.is_empty(), "both hosts forgot the chord"); + drop(dev); + drop(new); + clear_notes(); +} + +/// The closes a host generation must leave as they were: the newest host's close takes its own +/// engine and handlers, and any close ends routing. +#[test] +fn the_newest_hosts_close_and_any_close_ending_routing_stay_as_they_were() { + let _claims = CLAIMS.lock().unwrap_or_else(|error| error.into_inner()); + let scripts: [&[usize]; 3] = [&[0, 4, 2], &[0, 1, 4, 3], &[0, 4, 1, 4, 3, 2]]; + for script in scripts { + let mut dev = Reference { stage: Stage::new(), departures: false }; + let mut new = NewOverlap(Stage::new()); + for (n, letter) in script.iter().enumerate() { + let (dev_seen, new_seen) = (overlap_play(&mut dev, *letter), overlap_play(&mut new, *letter)); + assert_ne!(new_seen, Seen::Skipped, "{script:?} at {n}"); + assert_eq!(overlap_view(&new, new_seen), overlap_view(&dev, dev_seen), "{script:?} at {n}"); + } + assert!(!new.0.attached && new.0.slot.is_none(), "the close took its own engine: {script:?}"); + assert!(new.0.handlers.is_empty() && new.claims().is_empty(), "and cleared its handlers and claims: {script:?}"); + drop(dev); + drop(new); + clear_notes(); + } + // A replaced host's close still ends routing, whoever holds it. + let mut new = NewOverlap(Stage::new()); + for letter in [0, 1, 2] { assert_eq!(overlap_play(&mut new, letter), Seen::Done); } + assert_eq!((new.0.attached, new.0.open), (false, [false, true]), "routing ended"); + assert_eq!(overlap_play(&mut new, 4), Seen::Answer(Err(ShortcutError::NotRunning)), "a call after it is refused"); + drop(new); + clear_notes(); +} + +#[test] +fn a_walk_difference_needs_the_marked_departure() { + use std::panic::{AssertUnwindSafe, catch_unwind}; + let view = |seen| (seen, true, [false, false], vec![], vec![], vec![], vec![]); + let rejected = |dev: OverlapView, want: OverlapView, registering| catch_unwind(AssertUnwindSafe(|| approved_difference(&dev, &want, Some(7), registering, &mut BTreeSet::new(), &BTreeSet::new(), &[], 0))).is_err(); + assert!(rejected(view(Seen::Done), view(Seen::Parked), false), "a parked event is not a completed one"); + assert!(rejected(view(Seen::Answer(Err(ShortcutError::Conflict))), view(Seen::Answer(Ok(()))), true), "a registration with no wake-held claim is not the departure"); +} + +#[test] +fn every_overlap_sequence_differs_from_dev_only_at_its_marked_departure() { + let _claims = CLAIMS.lock().unwrap_or_else(|error| error.into_inner()); + let (mut found, mut fired) = (BTreeSet::new(), BTreeSet::new()); + overlap_walk(&mut vec![], 7, &mut found, &mut fired); + for invariant in [STALE_CLAIM, STALE_CONFLICT] { + assert!(found.contains(invariant), "the walk never saw the old code break this, so it proves nothing: {invariant}"); + } + assert!(fired.contains(WAKE_LETS_GO), "the departure never took effect"); + assert!(fired.contains(STALE_CLOSE_KEEPS), "a replaced host's close never left the newer host's engine"); +} diff --git a/app/vendor/rune/crates/rune/src/shortcuts/service/routing_tests.rs b/app/vendor/rune/crates/rune/src/shortcuts/service/routing_tests.rs new file mode 100644 index 0000000..4d0b77b --- /dev/null +++ b/app/vendor/rune/crates/rune/src/shortcuts/service/routing_tests.rs @@ -0,0 +1,432 @@ +//! The routing and per-thread engine model, compared event by event with a literal copy of the +//! code they replaced. A Linux teardown keeps running until the sequence says it finished. + +use super::machine_tests::every_sequence; +use super::*; +use std::thread::ThreadId; + +fn other_thread() -> ThreadId { std::thread::spawn(|| std::thread::current().id()).join().unwrap() } + +fn address(wake: &Waker) -> usize { Arc::as_ptr(wake) as *const () as usize } + +#[derive(Clone, Debug, PartialEq)] +enum Outcome { + Attached, + /// The attach replaced this engine, whose teardown is now running. + Replacing { engine: u32 }, + Refused, + Ran { engine: u32, wake: usize }, + Queued { wake: usize }, + Drained { ran: Vec<u32>, dropped: Vec<u32> }, + Closed { jobs: Vec<u32>, engine: Option<u32> }, + /// Parked behind a running teardown, to finish when it does. + Blocked, + /// That thread is inside a teardown or parked, so it can't do anything else. + Skipped, +} + +/// An engine's number is also the generation of the host that installed it. +enum Op { Attach(Waker, u32), Call(u32), Drain, Close, ReleaseEngine(u32) } + +/// Teardowns still running, oldest first, each with the wake and generation of the attach it +/// holds up, the operations parked behind them, and each thread's guard, by its generation. A +/// thread's later attach takes the place of its guard here, and the guard it replaced never +/// closes. +#[derive(Default)] +struct Schedule { teardowns: Vec<(ThreadId, Option<(Waker, u32)>)>, parked: Vec<(ThreadId, Op)>, guards: HashMap<ThreadId, u32> } + +impl Schedule { + fn busy(&self, thread: ThreadId) -> bool { + self.teardowns.iter().any(|(t, _)| *t == thread) || self.parked.iter().any(|(t, _)| *t == thread) + } + + fn view(&self) -> (Vec<ThreadId>, Vec<ThreadId>) { + (self.teardowns.iter().map(|(t, _)| *t).collect(), self.parked.iter().map(|(t, _)| *t).collect()) + } +} + +/// Who owns the service, its wake, its waiting jobs, the Linux engine and the per-thread ones. +type RouteView = (Option<ThreadId>, Option<usize>, Vec<u32>, Option<u32>, Vec<(ThreadId, u32)>); + +fn sorted(engines: &HashMap<ThreadId, u32>) -> Vec<(ThreadId, u32)> { + let mut engines: Vec<_> = engines.iter().map(|(thread, engine)| (*thread, *engine)).collect(); + engines.sort_by_key(|(_, engine)| *engine); + engines +} + +/// One side of the comparison, split where the real code can block. +trait Model { + fn schedule(&mut self) -> &mut Schedule; + fn attach(&mut self, thread: ThreadId, wake: Waker, engine: u32) -> Outcome; + /// The routing half of an attach by the host of generation `host`, which runs once any + /// replaced engine is gone. + fn finish_attach(&mut self, thread: ThreadId, wake: Waker, host: u32); + fn call(&mut self, thread: ThreadId, job: u32) -> Outcome; + /// A drain by the thread's guard, of generation `host`. + fn drain(&mut self, thread: ThreadId, host: u32) -> Outcome; + /// The close of the thread's guard, of generation `host`. + fn close(&mut self, thread: ThreadId, host: u32) -> Outcome; + /// The engine half of a close on Linux. + fn release_engine(&mut self, thread: ThreadId, host: u32) -> Outcome; + fn view(&self) -> RouteView; +} + +fn perform(model: &mut impl Model, thread: ThreadId, op: Op) -> Outcome { + match op { + Op::Attach(wake, engine) => { + let outcome = model.attach(thread, wake, engine); + // A parked attach hasn't installed yet; it gets its guard when it does. + if outcome != Outcome::Blocked { model.schedule().guards.insert(thread, engine); } + outcome + } + Op::Call(job) => model.call(thread, job), + Op::Drain => { + let host = model.schedule().guards[&thread]; + model.drain(thread, host) + } + Op::Close => { + let host = model.schedule().guards.remove(&thread).expect("only a thread with a guard closes"); + model.close(thread, host) + } + Op::ReleaseEngine(host) => model.release_engine(thread, host), + } +} + +/// The oldest teardown ends. A parked caller holds the routing lock, so it runs before the +/// attach that teardown held up can finish. +fn finish_teardown(model: &mut impl Model) -> Vec<Outcome> { + let schedule = model.schedule(); + if schedule.teardowns.is_empty() { return vec![Outcome::Skipped]; } + let (thread, attaching) = schedule.teardowns.remove(0); + let (calls, others): (Vec<_>, Vec<_>) = std::mem::take(&mut schedule.parked).into_iter().partition(|(_, op)| matches!(op, Op::Call(_))); + let mut outcomes: Vec<_> = calls.into_iter().map(|(thread, op)| perform(model, thread, op)).collect(); + if let Some((wake, host)) = attaching { model.finish_attach(thread, wake, host); } + outcomes.extend(others.into_iter().map(|(thread, op)| perform(model, thread, op))); + outcomes +} + +// The routing as it was: Routing's fields, the Linux engine slot and the thread-local engines, +// with the current thread passed in and a job as a number. A running teardown on Linux holds +// the slot's lock. +#[derive(Default)] +struct OldRouting { + owner: Option<ThreadId>, + wake: Option<Waker>, + jobs: Vec<u32>, + // differs from dev: routing names the generation of the host it routes to. + host: Option<u32>, +} + +/// `left_newer` and `left_calls` note that a marked departure took effect. +#[derive(Default)] +struct OldControl { routing: OldRouting, engine: Option<u32>, engines: HashMap<ThreadId, u32>, linux: bool, schedule: Schedule, left_newer: bool, left_calls: bool } + +impl OldControl { + fn slot_locked(&self) -> bool { self.linux && !self.schedule.teardowns.is_empty() } +} + +impl Model for OldControl { + fn schedule(&mut self) -> &mut Schedule { &mut self.schedule } + + fn attach(&mut self, thread: ThreadId, wake: Waker, engine: u32) -> Outcome { + if self.slot_locked() { self.schedule.parked.push((thread, Op::Attach(wake, engine))); return Outcome::Blocked; } + let replaced = if self.linux { self.engine.replace(engine) } else { self.engines.insert(thread, engine) }; + if let Some(replaced) = replaced { + self.schedule.teardowns.push((thread, Some((wake, engine)))); + return Outcome::Replacing { engine: replaced }; + } + self.finish_attach(thread, wake, engine); + Outcome::Attached + } + + fn finish_attach(&mut self, thread: ThreadId, wake: Waker, host: u32) { + self.routing.owner = Some(thread); + self.routing.wake = Some(wake); + self.routing.host = Some(host); + } + + fn call(&mut self, thread: ThreadId, job: u32) -> Outcome { + if self.linux { + if self.routing.owner.is_none() { return Outcome::Refused; } + if self.slot_locked() { self.schedule.parked.push((thread, Op::Call(job))); return Outcome::Blocked; } + let Some(engine) = self.engine else { return Outcome::Refused }; + let wake = self.routing.wake.clone(); + return Outcome::Ran { engine, wake: address(&wake.unwrap()) }; + } + let route = &mut self.routing; + let Some(owner) = route.owner else { return Outcome::Refused }; + if owner == thread { + let wake = route.wake.clone(); + let Some(engine) = self.engines.get(&thread).copied() else { return Outcome::Refused }; + return Outcome::Ran { engine, wake: address(&wake.unwrap()) }; + } + route.jobs.push(job); + let wake = route.wake.clone(); + Outcome::Queued { wake: address(&wake.unwrap()) } + } + + fn drain(&mut self, thread: ThreadId, host: u32) -> Outcome { + if self.linux { return Outcome::Drained { ran: vec![], dropped: vec![] }; } + // differs from dev: only the routed host takes the waiting calls; another leaves them. + if self.routing.host != Some(host) { + self.left_calls |= !self.routing.jobs.is_empty(); + return Outcome::Drained { ran: vec![], dropped: vec![] }; + } + let jobs = std::mem::take(&mut self.routing.jobs); + // differs from dev: they run on the drainer's engine only if its own host installed it. + if self.engines.get(&thread) == Some(&host) { Outcome::Drained { ran: jobs, dropped: vec![] } } else { Outcome::Drained { ran: vec![], dropped: jobs } } + } + + fn close(&mut self, thread: ThreadId, host: u32) -> Outcome { + let route = std::mem::take(&mut self.routing); + if self.linux { + if self.slot_locked() { self.schedule.parked.push((thread, Op::ReleaseEngine(host))); return Outcome::Blocked; } + return self.release_engine(thread, host); + } + // differs from dev: a close takes only the engine its own host installed. + let engine = if self.engines.get(&thread) == Some(&host) { self.engines.remove(&thread) } else { None }; + if engine.is_some() { self.schedule.teardowns.push((thread, None)); } + Outcome::Closed { jobs: route.jobs, engine } + } + + fn release_engine(&mut self, thread: ThreadId, host: u32) -> Outcome { + if self.slot_locked() { self.schedule.parked.push((thread, Op::ReleaseEngine(host))); return Outcome::Blocked; } + // differs from dev: a close takes only the engine its own host installed, never a newer one. + let engine = if self.engine == Some(host) { self.engine.take() } else { None }; + self.left_newer |= engine.is_none() && self.engine.is_some(); + if engine.is_some() { self.schedule.teardowns.push((thread, None)); } + Outcome::Closed { jobs: vec![], engine } + } + + fn view(&self) -> RouteView { + (self.routing.owner, self.routing.wake.as_ref().map(address), self.routing.jobs.clone(), self.engine, sorted(&self.engines)) + } +} + +/// The machine with the glue `Guard` and `Control` wrap around it. +struct NewControl { attachment: Attachment<u32>, engine: Option<u32>, slot_wake: Option<Waker>, engines: HashMap<ThreadId, u32>, linux: bool, schedule: Schedule } + +impl NewControl { + fn slot_locked(&self) -> bool { self.linux && !self.schedule.teardowns.is_empty() } +} + +impl Model for NewControl { + fn schedule(&mut self) -> &mut Schedule { &mut self.schedule } + + fn attach(&mut self, thread: ThreadId, wake: Waker, engine: u32) -> Outcome { + if self.slot_locked() { self.schedule.parked.push((thread, Op::Attach(wake, engine))); return Outcome::Blocked; } + let replaced = if self.linux { + // differs from dev: the wake travels with the engine's slot, so a call that reaches a + // newer engine wakes its host, not the host routing still names. + self.slot_wake = Some(wake.clone()); + self.engine.replace(engine) + } else { self.engines.insert(thread, engine) }; + if let Some(replaced) = replaced { + self.schedule.teardowns.push((thread, Some((wake, engine)))); + return Outcome::Replacing { engine: replaced }; + } + self.finish_attach(thread, wake, engine); + Outcome::Attached + } + + fn finish_attach(&mut self, thread: ThreadId, wake: Waker, host: u32) { + let host = host.into(); + let own = address(&wake); + // differs from dev: a host that inherits waiting calls is woken for them. + for effect in step_attachment(&mut self.attachment, AttachEvent::Attach { owner: thread, wake, host }) { + assert!(matches!(effect, AttachEffect::Wake(wake) if address(&wake) == own), "an attach only wakes the host it routes to"); + } + } + + fn call(&mut self, thread: ThreadId, job: u32) -> Outcome { + match step_attachment(&mut self.attachment, AttachEvent::Call { from: thread, shared: self.linux }).into_iter().next() { + Some(AttachEffect::Run { wake }) => { + if self.slot_locked() { self.schedule.parked.push((thread, Op::Call(job))); return Outcome::Blocked; } + let engine = if self.linux { self.engine } else { self.engines.get(&thread).copied() }; + engine.map_or(Outcome::Refused, |engine| { + // differs from dev: routing's wake only says a call may run; the engine's + // slot names the host it wakes. + let wake = if self.linux { self.slot_wake.clone().expect("an engine in the slot has a host") } else { wake }; + Outcome::Ran { engine, wake: address(&wake) } + }) + } + Some(AttachEffect::Wait) => match step_attachment(&mut self.attachment, AttachEvent::Post(job)).into_iter().next() { + Some(AttachEffect::Wake(wake)) => Outcome::Queued { wake: address(&wake) }, + _ => panic!("a posted job wakes the owner"), + }, + _ => Outcome::Refused, + } + } + + fn drain(&mut self, thread: ThreadId, host: u32) -> Outcome { + if self.linux { return Outcome::Drained { ran: vec![], dropped: vec![] }; } + let Some(AttachEffect::Jobs(jobs)) = step_attachment(&mut self.attachment, AttachEvent::Drain { host: host.into() }).into_iter().next() else { + return Outcome::Drained { ran: vec![], dropped: vec![] }; + }; + // The routed host's thread holds its engine. + if self.engines.get(&thread) == Some(&host) { Outcome::Drained { ran: jobs, dropped: vec![] } } else { Outcome::Drained { ran: vec![], dropped: jobs } } + } + + fn close(&mut self, thread: ThreadId, host: u32) -> Outcome { + let mut released = vec![]; + for effect in step_attachment(&mut self.attachment, AttachEvent::Close) { + if let AttachEffect::Release(jobs) = effect { released = jobs; } + } + if self.linux { return self.release_engine(thread, host); } + let engine = if self.engines.get(&thread) == Some(&host) { self.engines.remove(&thread) } else { None }; + if engine.is_some() { self.schedule.teardowns.push((thread, None)); } + Outcome::Closed { jobs: released, engine } + } + + fn release_engine(&mut self, thread: ThreadId, host: u32) -> Outcome { + if self.slot_locked() { self.schedule.parked.push((thread, Op::ReleaseEngine(host))); return Outcome::Blocked; } + // Only the engine this host installed, with the wake that travels with it. + if self.engine != Some(host) { return Outcome::Closed { jobs: vec![], engine: None }; } + let engine = self.engine.take(); + self.slot_wake = None; + self.schedule.teardowns.push((thread, None)); + Outcome::Closed { jobs: vec![], engine } + } + + fn view(&self) -> RouteView { + let engines = sorted(&self.engines); + match &self.attachment { + Attachment::Attached { owner, wake, jobs, .. } => (Some(*owner), Some(address(wake)), jobs.clone(), self.engine, engines), + Attachment::Detached | Attachment::Closed => (None, None, vec![], self.engine, engines), + } + } +} + +/// The outcomes in order, allowing only the marked wake departure: the same engine ran the call, +/// and the wake names the host whose engine the slot holds. +fn assert_outcomes(old: &[Outcome], new: &[Outcome], linux: bool, at: &str) -> bool { + assert_eq!(new.len(), old.len(), "{at}"); + let mut departed = false; + for (new, old) in new.iter().zip(old) { + if let (Outcome::Ran { engine: a, wake: a_wake }, Outcome::Ran { engine: b, wake: b_wake }) = (old, new) { + assert_eq!(a, b, "the same engine ran the call: {at}"); + if a_wake != b_wake { + assert!(linux, "a wake moved between owner threads: {at}"); + departed = true; + continue; + } + } + assert_eq!(new, old, "{at}"); + } + departed +} + +/// Letters 0..8 are Attach, Call, Drain and Close from either thread; 8 ends the oldest teardown. +/// Only a thread with a guard drains or closes. +fn play(model: &mut impl Model, letter: usize, threads: &[ThreadId; 2], wakes: &[Waker; 2], number: u32) -> Vec<Outcome> { + if letter == 8 { return finish_teardown(model); } + let thread = threads[letter % 2]; + if model.schedule().busy(thread) { return vec![Outcome::Skipped]; } + let op = match letter / 2 { + 0 => Op::Attach(wakes[letter % 2].clone(), number), + 1 => Op::Call(number), + 2 => Op::Drain, + _ => Op::Close, + }; + if matches!(op, Op::Drain | Op::Close) && !model.schedule().guards.contains_key(&thread) { return vec![Outcome::Skipped]; } + vec![perform(model, thread, op)] +} + +/// Plays `steps` through both models, each letter with the outcomes given, and returns who +/// routing names at the end. +fn script(linux: bool, steps: &[(usize, Vec<Outcome>)], threads: &[ThreadId; 2], wakes: &[Waker; 2]) -> Option<ThreadId> { + let mut old = OldControl { linux, ..OldControl::default() }; + let mut new = NewControl { attachment: Attachment::Detached, engine: None, slot_wake: None, engines: HashMap::new(), linux, schedule: Schedule::default() }; + for (n, (letter, expected)) in steps.iter().enumerate() { + let number = n as u32 + 1; + assert_eq!(&play(&mut old, *letter, threads, wakes, number), expected, "linux {linux}, the old routing at {n}"); + assert_eq!(&play(&mut new, *letter, threads, wakes, number), expected, "linux {linux}, the new routing at {n}"); + assert_eq!(new.view(), old.view(), "linux {linux} at {n}"); + } + new.view().0 +} + +/// The cases a host generation must leave as they were: the newest host's close takes its own +/// engine, the routed host runs the calls waiting for it, and any close still ends routing and +/// releases those calls. +#[test] +fn the_newest_hosts_close_and_drain_and_any_close_ending_routing_stay_as_they_were() { + let threads = [std::thread::current().id(), other_thread()]; + let wakes: [Waker; 2] = [Arc::new(|| {}), Arc::new(|| { let _ = 1; })]; + let (w0, w1) = (address(&wakes[0]), address(&wakes[1])); + use Outcome::*; + // Off Linux: the owner drains a call from the other thread, then closes and takes its engine. + let routed = script(false, &[ + (0, vec![Attached]), + (3, vec![Queued { wake: w0 }]), + (4, vec![Drained { ran: vec![2], dropped: vec![] }]), + (6, vec![Closed { jobs: vec![], engine: Some(1) }]), + (8, vec![]), + ], &threads, &wakes); + assert_eq!(routed, None); + // The routed host drains the call that waits for it, though another host attached first. + let routed = script(false, &[ + (0, vec![Attached]), + (1, vec![Attached]), + (2, vec![Queued { wake: w1 }]), + (5, vec![Drained { ran: vec![3], dropped: vec![] }]), + ], &threads, &wakes); + assert_eq!(routed, Some(threads[1])); + // A replaced host's close still ends routing and releases its successor's waiting caller. + let routed = script(false, &[ + (0, vec![Attached]), + (1, vec![Attached]), + (2, vec![Queued { wake: w1 }]), + (6, vec![Closed { jobs: vec![3], engine: Some(1) }]), + (3, vec![Refused]), + ], &threads, &wakes); + assert_eq!(routed, None); + // On Linux: a lone host's close takes its engine. + let routed = script(true, &[ + (0, vec![Attached]), + (2, vec![Ran { engine: 1, wake: w0 }]), + (6, vec![Closed { jobs: vec![], engine: Some(1) }]), + (8, vec![]), + ], &threads, &wakes); + assert_eq!(routed, None); + // The newest host's close takes its own engine, once the one it replaced has gone. + let routed = script(true, &[ + (0, vec![Attached]), + (1, vec![Replacing { engine: 1 }]), + (8, vec![]), + (7, vec![Closed { jobs: vec![], engine: Some(2) }]), + (8, vec![]), + (2, vec![Refused]), + ], &threads, &wakes); + assert_eq!(routed, None); +} + +#[test] +fn every_attachment_sequence_matches_the_old_routing() { + let threads = [std::thread::current().id(), other_thread()]; + let wakes: [Waker; 2] = [Arc::new(|| {}), Arc::new(|| { let _ = 1; })]; + let (mut departed, mut left_newer, mut left_calls) = (false, false, false); + for linux in [false, true] { + every_sequence(9, 6, |sequence| { + let mut old = OldControl { linux, ..OldControl::default() }; + let mut new = NewControl { attachment: Attachment::Detached, engine: None, slot_wake: None, engines: HashMap::new(), linux, schedule: Schedule::default() }; + for (n, letter) in sequence.iter().enumerate() { + let number = n as u32 + 1; + let expected = play(&mut old, *letter, &threads, &wakes, number); + let actual = play(&mut new, *letter, &threads, &wakes, number); + departed |= assert_outcomes(&expected, &actual, linux, &format!("linux {linux}, {sequence:?} at {n}")); + assert_eq!(new.view(), old.view(), "linux {linux}, {sequence:?} at {n}"); + assert_eq!(new.schedule.view(), old.schedule.view(), "linux {linux}, {sequence:?} at {n}"); + if linux && actual.iter().any(|outcome| matches!(outcome, Outcome::Ran { .. })) { + assert!(new.schedule.teardowns.is_empty(), "a call reached an engine during a teardown: {sequence:?} at {n}"); + } + } + left_newer |= old.left_newer; + left_calls |= old.left_calls; + }); + } + assert!(departed, "the walk never saw a call that reached the engine a newer host installed"); + assert!(left_newer, "the walk never saw a replaced host's close leave the newer engine"); + assert!(left_calls, "the walk never saw a replaced host's drain leave the calls to the routed host"); +} + diff --git a/app/vendor/rune/crates/rune/src/shortcuts/service/teardown_tests.rs b/app/vendor/rune/crates/rune/src/shortcuts/service/teardown_tests.rs new file mode 100644 index 0000000..76fc917 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/shortcuts/service/teardown_tests.rs @@ -0,0 +1,377 @@ +//! A Linux backend still closing, through the real `Guard` and real threads. A closing backend +//! holds its chords until it is gone, so nothing may reach the next engine before then. + +use super::*; +use crate::{App, AppSpec, el}; +use std::{sync::Condvar, time::Duration}; + +const PATIENCE: Duration = Duration::from_secs(30); +/// How long a call must stay parked to count as waiting. A correct run always waits this out. +const STILL_WAITING: Duration = Duration::from_millis(200); + +/// Holds a backend's `Drop` open while armed. +struct Gate { state: Mutex<(bool, bool)>, changed: Condvar } + +static GATES: [Gate; 3] = [Gate::new(), Gate::new(), Gate::new()]; + +impl Gate { + const fn new() -> Self { Self { state: Mutex::new((false, false)), changed: Condvar::new() } } + + fn arm(&self) { self.state.lock().unwrap().0 = true; } + + fn open(&self) { + self.state.lock().unwrap().0 = false; + self.changed.notify_all(); + } + + fn pause(&self) { + let mut state = self.state.lock().unwrap(); + if !state.0 { return; } + state.1 = true; + self.changed.notify_all(); + while state.0 { state = self.changed.wait(state).unwrap(); } + } + + fn wait_until_paused(&self) { + let state = self.state.lock().unwrap(); + let (state, timeout) = self.changed.wait_timeout_while(state, PATIENCE, |state| !state.1).unwrap(); + drop(state); + assert!(!timeout.timed_out(), "the backend never started closing"); + } +} + +struct Pausing(&'static Gate); + +impl Backend for Pausing { + fn register(&mut self, _: ShortcutId, _: &Shortcut) -> Result<(), ShortcutError> { Ok(()) } + fn unregister(&mut self, _: ShortcutId) -> Result<(), ShortcutError> { Ok(()) } +} + +impl Drop for Pausing { + fn drop(&mut self) { self.0.pause(); } +} + +fn connect<const GATE: usize>(_: bool, _: Sink) -> Result<NativeBackend, ShortcutError> { + Ok(Box::new(Pausing(&GATES[GATE]))) +} + +fn app(title: &'static str) -> App<()> { App::new(AppSpec::new(title, (10.0, 10.0), || (), |_, _| el())) } + +#[test] +fn a_new_host_waits_for_the_closing_hosts_backend() { + let gate = &GATES[0]; + let app = app("Closing"); + let handle = app.handle(); + let chord: Shortcut = "ctrl+alt+shift+f23".parse().unwrap(); + + let (registered, first_id) = mpsc::channel(); + let (close, closing) = mpsc::channel::<()>(); + let closer = { + let (shared, handle, chord) = (app.shared.clone(), handle.clone(), chord.clone()); + std::thread::spawn(move || { + let guard = Guard::attach_with(&shared, Arc::new(|| {}), false, false, connect::<0>); + registered.send(handle.register_shortcut(chord, |_, _| {})).unwrap(); + closing.recv().unwrap(); + drop(guard); + }) + }; + first_id.recv_timeout(PATIENCE).unwrap().unwrap(); + + gate.arm(); + close.send(()).unwrap(); + gate.wait_until_paused(); + let refused = handle.register_shortcut(chord.clone(), |_, _| {}); + + let (answer, answered) = mpsc::channel(); + let next = { + let (shared, handle, chord) = (app.shared.clone(), handle.clone(), chord.clone()); + std::thread::spawn(move || { + let guard = Guard::attach_with(&shared, Arc::new(|| {}), false, false, connect::<0>); + answer.send(handle.register_shortcut(chord, |_, _| {})).unwrap(); + drop(guard); + }) + }; + let early = answered.recv_timeout(STILL_WAITING); + gate.open(); + let late = if early.is_err() { answered.recv_timeout(PATIENCE).ok() } else { None }; + closer.join().unwrap(); + next.join().unwrap(); + + assert_eq!(refused, Err(ShortcutError::NotRunning), "calls are refused while the host closes"); + assert_eq!(early.ok(), None, "the next host reached an engine while the old backend held the chord"); + assert!(matches!(late, Some(Ok(_))), "the chord is free once the old backend closed: {late:?}"); +} + +#[test] +fn a_replacement_engine_is_out_of_reach_until_the_old_backend_closes() { + let gate = &GATES[1]; + let app = app("Replacing"); + let handle = app.handle(); + let chord: Shortcut = "ctrl+alt+shift+f24".parse().unwrap(); + + let (registered, first_id) = mpsc::channel(); + let (finish_first, first_finishes) = mpsc::channel::<()>(); + let first = { + let (shared, handle, chord) = (app.shared.clone(), handle.clone(), chord.clone()); + std::thread::spawn(move || { + let guard = Guard::attach_with(&shared, Arc::new(|| {}), false, false, connect::<1>); + registered.send(handle.register_shortcut(chord, |_, _| {})).unwrap(); + first_finishes.recv().unwrap(); + drop(guard); + }) + }; + let old_id = first_id.recv_timeout(PATIENCE).unwrap().unwrap(); + + gate.arm(); + let (finish_second, second_finishes) = mpsc::channel::<()>(); + let second = { + let shared = app.shared.clone(); + std::thread::spawn(move || { + let guard = Guard::attach_with(&shared, Arc::new(|| {}), false, false, connect::<1>); + second_finishes.recv().unwrap(); + drop(guard); + }) + }; + gate.wait_until_paused(); + + let (answer, answered) = mpsc::channel(); + let caller = { + let (handle, chord) = (handle.clone(), chord.clone()); + std::thread::spawn(move || { + let forgotten = handle.unregister_shortcut(old_id); + answer.send((forgotten, handle.register_shortcut(chord, |_, _| {}))).unwrap(); + }) + }; + let early = answered.recv_timeout(STILL_WAITING); + gate.open(); + let late = if early.is_err() { answered.recv_timeout(PATIENCE).ok() } else { None }; + caller.join().unwrap(); + finish_second.send(()).unwrap(); + second.join().unwrap(); + finish_first.send(()).unwrap(); + first.join().unwrap(); + + assert_eq!(early.ok(), None, "a caller reached the replacement while the old backend held the chord"); + let (forgotten, again) = late.expect("the caller finishes once the old backend closed"); + assert_eq!(forgotten, Err(ShortcutError::UnknownId)); + assert!(again.is_ok(), "the chord is free once the old backend closed: {again:?}"); +} + +/// Chords held by live `Exclusive` backends, as a display server's grabs are. +static GRABS: Mutex<Vec<Shortcut>> = Mutex::new(Vec::new()); +const BUSY_CHORD: &str = "ctrl+alt+shift+f14"; + +/// A backend that refuses a chord another backend holds, until that backend is gone. Registering +/// `BUSY_CHORD` stops at gate 2 first, for a call stopped inside the engine. +#[derive(Default)] +struct Exclusive(Vec<Shortcut>); + +impl Backend for Exclusive { + fn register(&mut self, _: ShortcutId, shortcut: &Shortcut) -> Result<(), ShortcutError> { + if *shortcut == BUSY_CHORD.parse().unwrap() { GATES[2].pause(); } + let mut grabs = GRABS.lock().unwrap(); + if grabs.contains(shortcut) { return Err(ShortcutError::Conflict); } + grabs.push(shortcut.clone()); + self.0.push(shortcut.clone()); + Ok(()) + } + fn unregister(&mut self, _: ShortcutId) -> Result<(), ShortcutError> { Ok(()) } +} + +impl Drop for Exclusive { + fn drop(&mut self) { GRABS.lock().unwrap().retain(|grab| !self.0.contains(grab)); } +} + +fn connect_exclusive(_: bool, _: Sink) -> Result<NativeBackend, ShortcutError> { Ok(Box::<Exclusive>::default()) } + +/// A second App in this process, to ask who holds a chord. +fn witness() -> (App<()>, Guard) { + let app = app("Witness"); + let guard = Guard::attach_with(&app.shared, Arc::new(|| {}), false, false, connect_exclusive); + (app, guard) +} + +/// A host on its own thread, attached until `finish` is sent. +fn host(app: &App<()>, wake: Waker) -> (mpsc::Sender<()>, std::thread::JoinHandle<()>) { + let shared = app.shared.clone(); + let (attached, is_attached) = mpsc::channel::<()>(); + let (finish, finishes) = mpsc::channel::<()>(); + let thread = std::thread::spawn(move || { + let guard = Guard::attach_with(&shared, wake, false, false, connect_exclusive); + attached.send(()).unwrap(); + finishes.recv().unwrap(); + drop(guard); + }); + is_attached.recv_timeout(PATIENCE).expect("the host attached"); + (finish, thread) +} + +#[test] +fn a_call_in_its_wake_does_not_keep_a_replaced_backends_grab() { + static STOPPED: Gate = Gate::new(); + let app = app("Held"); + let handle = app.handle(); + let chord: Shortcut = "ctrl+alt+shift+f16".parse().unwrap(); + let (finish_first, first) = host(&app, Arc::new(|| STOPPED.pause())); + handle.register_shortcut(chord.clone(), |_, _| {}).unwrap(); + + STOPPED.arm(); + let holder = { let (handle, chord) = (handle.clone(), chord.clone()); std::thread::spawn(move || handle.shortcut_owner(&chord)) }; + STOPPED.wait_until_paused(); + + let (finish_second, second) = host(&app, Arc::new(|| {})); + let again = handle.register_shortcut(chord.clone(), |_, _| {}); + let (witness, witness_guard) = witness(); + let owner = witness.handle().shortcut_owner(&chord); + STOPPED.open(); + holder.join().unwrap(); + drop(witness_guard); + finish_second.send(()).unwrap(); + second.join().unwrap(); + finish_first.send(()).unwrap(); + first.join().unwrap(); + + assert!(again.is_ok(), "the old backend's grab went with the replacement: {again:?}"); + assert_eq!(owner.as_deref(), Some("Held"), "another App can still name who holds the chord"); +} + +#[test] +fn a_busy_replaced_engine_keeps_its_grab_and_owner_without_holding_up_the_new_host() { + let inside_gate = &GATES[2]; + let app = app("Busy"); + let handle = app.handle(); + let chord: Shortcut = "ctrl+alt+shift+f15".parse().unwrap(); + let (finish_first, first) = host(&app, Arc::new(|| {})); + handle.register_shortcut(chord.clone(), |_, _| {}).unwrap(); + + // A consent prompt keeps this call inside the engine, holding its lock. + inside_gate.arm(); + let inside = { let handle = handle.clone(); std::thread::spawn(move || handle.register_shortcut(BUSY_CHORD.parse().unwrap(), |_, _| {})) }; + inside_gate.wait_until_paused(); + + let shared = app.shared.clone(); + let (attached, is_attached) = mpsc::channel::<()>(); + let (finish_second, second_finishes) = mpsc::channel::<()>(); + let second = std::thread::spawn(move || { + let guard = Guard::attach_with(&shared, Arc::new(|| {}), false, false, connect_exclusive); + attached.send(()).unwrap(); + second_finishes.recv().unwrap(); + drop(guard); + }); + let returned = is_attached.recv_timeout(PATIENCE); + + // The old backend is still open, so the record says so. + let (witness, witness_guard) = witness(); + let owner = witness.handle().shortcut_owner(&chord); + let refused = handle.register_shortcut(chord.clone(), |_, _| {}); + inside_gate.open(); + let finished = inside.join().unwrap(); + let again = handle.register_shortcut(chord.clone(), |_, _| {}); + drop(witness_guard); + finish_second.send(()).unwrap(); + second.join().unwrap(); + finish_first.send(()).unwrap(); + first.join().unwrap(); + + assert!(returned.is_ok(), "the new host attached while the old call was still inside"); + assert_eq!(owner.as_deref(), Some("Busy"), "the owner stays on record while the grab stands"); + assert_eq!(refused, Err(ShortcutError::Conflict), "the old backend really does still hold it"); + assert!(finished.is_ok(), "the old call finishes on its own engine: {finished:?}"); + assert!(again.is_ok(), "the chord is free once the old call has gone: {again:?}"); +} + +/// Waits for `ready`, which another thread makes true. +fn wait_until(ready: impl Fn() -> bool) { + let deadline = crate::time::now() + PATIENCE; + while !ready() { + assert!(crate::time::now() < deadline, "the other thread never got there"); + std::thread::yield_now(); + } +} + +#[test] +fn a_call_that_reaches_the_new_engine_wakes_its_host_and_lets_the_old_one_go() { + let app = app("Rerouted"); + let control = app.shared.shortcuts.control.clone(); + // The first host's wake is the only thing that keeps it alive, so a Weak sees it dropped. + let alive = Arc::new(()); + let old = Arc::downgrade(&alive); + let token = alive.clone(); + let guard = Guard::attach_with(&app.shared, Arc::new(move || { let _ = &token; }), false, false, connect_exclusive); + drop(alive); + + // A second host installs its engine, as `attach` does before it takes routing, and its own + // wake. Routing still names the first host until that attach finishes. + let engine = Engine { title: "Rerouted", wayland: false, sink: Arc::new(|_, _| {}), connect: connect_exclusive, bindings: Bindings::Disconnected }; + let second = Arc::new(Mutex::new(engine)); + let seen = Arc::new(Mutex::new(None)); + let b_wake: Waker = { + let (old, seen) = (old.clone(), seen.clone()); + Arc::new(move || { *seen.lock().unwrap() = Some(old.upgrade().is_some()); }) + }; + let generation = next_generation(); + { + let mut slot = control.engine.lock().unwrap(); + control.generation.store(generation, Ordering::Relaxed); + *slot = Some(Slot { engine: second.clone(), wake: b_wake.clone(), generation }); + } + + // The call captures routing's wake (the first host) and the newer engine, then runs on it. + let (entered, enter) = mpsc::channel(); + let (finish, finished) = mpsc::channel::<()>(); + let caller = { + let control = control.clone(); + std::thread::spawn(move || control.call(move |_| { entered.send(()).unwrap(); finished.recv().unwrap(); Ok(()) })) + }; + enter.recv_timeout(PATIENCE).unwrap(); + // The newer host finishes its attach, so routing lets the first host's wake go; the call still + // holds the copy it captured. + step_attachment(&mut control.attachment.lock().unwrap(), AttachEvent::Attach { owner: std::thread::current().id(), wake: b_wake, host: generation }); + finish.send(()).unwrap(); + caller.join().unwrap().unwrap(); + + assert_eq!(*seen.lock().unwrap(), Some(false), "the first host's wake must be gone before the new host's callback runs"); + drop(guard); + drop(second); +} + +#[test] +fn a_call_parked_on_a_replaced_engine_still_runs_on_it_and_wakes_its_host() { + use std::sync::atomic::AtomicUsize; + static FIRST_WAKES: AtomicUsize = AtomicUsize::new(0); + static SECOND_WAKES: AtomicUsize = AtomicUsize::new(0); + let app = app("Parked"); + let handle = app.handle(); + let chord: Shortcut = "ctrl+alt+shift+f13".parse().unwrap(); + let guard = Guard::attach_with(&app.shared, Arc::new(|| { FIRST_WAKES.fetch_add(1, Ordering::Relaxed); }), false, false, connect_exclusive); + let id = handle.register_shortcut(chord, |_, _| {}).unwrap(); + let wakes_before = FIRST_WAKES.load(Ordering::Relaxed); + let control = app.shared.shortcuts.control.clone(); + + // Holding the engine's lock parks the call on it. Its own clone of the Arc shows it got there. + let old = control.engine.lock().unwrap().as_ref().map(|slot| slot.engine.clone()).unwrap(); + let locked = old.lock().unwrap(); + let caller = { let handle = handle.clone(); std::thread::spawn(move || handle.unregister_shortcut(id)) }; + wait_until(|| Arc::strong_count(&old) == 3); + + let (finish_second, second_finishes) = mpsc::channel::<()>(); + let second = { + let shared = app.shared.clone(); + std::thread::spawn(move || { + let guard = Guard::attach_with(&shared, Arc::new(|| { SECOND_WAKES.fetch_add(1, Ordering::Relaxed); }), false, false, connect_exclusive); + second_finishes.recv().unwrap(); + drop(guard); + }) + }; + wait_until(|| control.engine.try_lock().is_ok_and(|slot| slot.as_ref().is_some_and(|current| !Arc::ptr_eq(&current.engine, &old)))); + drop(locked); + + let answer = caller.join().unwrap(); + let (first_wakes, second_wakes) = (FIRST_WAKES.load(Ordering::Relaxed), SECOND_WAKES.load(Ordering::Relaxed)); + finish_second.send(()).unwrap(); + second.join().unwrap(); + drop(old); + drop(guard); + assert_eq!(answer, Ok(()), "the old engine still holds the registration"); + assert_eq!((first_wakes - wakes_before, second_wakes), (1, 0), "the call wakes the host whose engine ran it"); +} diff --git a/app/vendor/rune/crates/rune/src/shortcuts/service/tests.rs b/app/vendor/rune/crates/rune/src/shortcuts/service/tests.rs new file mode 100644 index 0000000..1c7baec --- /dev/null +++ b/app/vendor/rune/crates/rune/src/shortcuts/service/tests.rs @@ -0,0 +1,172 @@ +use super::*; +use crate::{App, AppSpec, el}; +#[test] +fn mock_backend_errors_are_not_confused_with_conflicts() { + struct Mock(ShortcutError); + impl Backend for Mock { + fn register(&mut self, _: ShortcutId, _: &Shortcut) -> Result<(), ShortcutError> { Err(self.0.clone()) } + fn unregister(&mut self, _: ShortcutId) -> Result<(), ShortcutError> { Ok(()) } + } + for error in [ShortcutError::Conflict, ShortcutError::Unsupported, ShortcutError::PermissionDenied, ShortcutError::Backend("disconnected".into())] { + let bindings = Bindings::Connected { native: Box::new(Mock(error.clone())) as NativeBackend, registrations: HashMap::new() }; + let mut engine = Engine { title: "mock", wayland: false, sink: Arc::new(|_, _| {}), connect: super::super::backend, bindings }; + assert_eq!(engine.register(ShortcutId(1), "ctrl+a".parse().unwrap()), Err(error)); + assert!(matches!(engine.bindings, Bindings::Disconnected)); + } + assert_eq!(super::super::native_status(-9878, -9878), Err(ShortcutError::Conflict)); + assert_eq!(super::super::native_status(1409, 1409), Err(ShortcutError::Conflict)); + assert!(matches!(super::super::native_status(5, 1409), Err(ShortcutError::Backend(_)))); +} + +#[test] +fn conflicts_name_the_app_that_holds_the_chord() { + struct Accept; + impl Backend for Accept { + fn register(&mut self, _: ShortcutId, _: &Shortcut) -> Result<(), ShortcutError> { Ok(()) } + fn unregister(&mut self, _: ShortcutId) -> Result<(), ShortcutError> { Ok(()) } + } + let chord: Shortcut = "ctrl+alt+shift+f17".parse().unwrap(); + let native = |title| Engine { title, wayland: false, sink: Arc::new(|_, _| {}), connect: super::super::backend, bindings: Bindings::Connected { native: Box::new(Accept) as NativeBackend, registrations: HashMap::new() } }; + let (mut first, mut second) = (native("First"), native("Second")); + first.register(ShortcutId(u32::MAX - 1), chord.clone()).unwrap(); + assert_eq!(second.register(ShortcutId(u32::MAX - 2), chord.clone()), Err(ShortcutError::Conflict), + "refused even when the backend accepts a same-process duplicate"); + assert_eq!(first.owner(&chord).as_deref(), Some("First")); + assert_eq!(second.owner(&chord).as_deref(), Some("First")); + drop(first); + // Off the main thread the system lookup answers None, so the claim is gone entirely. + assert_eq!(second.owner(&chord), None, "a dropped App releases its claim"); + second.register(ShortcutId(u32::MAX - 2), chord.clone()).unwrap(); + + let app = App::new(AppSpec::new("Owner", (10.0, 10.0), || (), |_, _| el())); + let handle = app.handle(); + let chord: Shortcut = "ctrl+alt+o".parse().unwrap(); + assert_eq!(handle.shortcut_owner(&chord), None, "not running"); + let guard = Guard::attach(&app.shared, Arc::new(|| {}), true, false); + handle.register_shortcut(chord.clone(), |_, _| {}).unwrap(); + assert_eq!(handle.register_shortcut(chord.clone(), |_, _| {}), Err(ShortcutError::Conflict)); + assert_eq!(handle.shortcut_owner(&chord).as_deref(), Some("Owner")); + // Headless runs never ask the desktop, so stills are the same everywhere. + assert_eq!(handle.shortcut_owner(&"super+space".parse().unwrap()), None); + drop(guard); +} + +#[test] +fn headless_handlers_share_state_and_unregister_cancels_queued_activation() { + let app = App::new(AppSpec::new("shortcuts", (100.0, 100.0), || 0, |_: &u32, _| el())) + .global_shortcut("cmd+shift+space", |s, tx| { *s += 1; tx.instant(); }); + let handle = app.handle(); + let guard = Guard::attach(&app.shared, Arc::new(|| {}), true, false); + let shortcut = "cmd+shift+space".parse().unwrap(); + app.shared.shortcuts.fire(&shortcut).unwrap(); + let mut state = 0; + let receiving = guard.receiving(); + for f in app.shared.take().updates { f(&mut state, &mut Tx::default()); } + assert_eq!(state, 1); + assert_eq!(handle.register_shortcut(shortcut, |_, _| {}), Err(ShortcutError::Conflict)); + let id = handle.register_shortcut("ctrl+a".parse().unwrap(), |s, _| *s += 10).unwrap(); + app.shared.shortcuts.fire(&"ctrl+a".parse().unwrap()).unwrap(); + handle.unregister_shortcut(id).unwrap(); + for f in app.shared.take().updates { f(&mut state, &mut Tx::default()); } + assert_eq!(state, 1); + drop(receiving); + drop(guard); + assert_eq!(handle.unregister_shortcut(id), Err(ShortcutError::NotRunning)); +} + +#[test] +fn a_chord_without_a_modifier_is_refused_unless_it_is_a_function_key() { + let app = App::new(AppSpec::new("bare", (10.0, 10.0), || (), |_, _| el())).global_shortcut("space", |_, _| {}); + let handle = app.handle(); + let guard = Guard::attach(&app.shared, Arc::new(|| {}), true, false); + assert!(matches!(handle.take_shortcut_errors().as_slice(), [ShortcutError::InvalidAccelerator(_)])); + for bare in ["space", "enter", "a", "shift+a", "shift+tab"] { + assert!(matches!(handle.register_shortcut(bare.parse().unwrap(), |_, _| {}), Err(ShortcutError::InvalidAccelerator(_))), "{bare}"); + } + for allowed in ["f5", "f24", "shift+f1", "ctrl+space", "alt+a", "super+enter"] { + assert!(handle.register_shortcut(allowed.parse().unwrap(), |_, _| {}).is_ok(), "{allowed}"); + } + drop(guard); + + let app = App::new(AppSpec::new("bare", (10.0, 10.0), || (), |_, _| el())).global_shortcut("space", |_, _| {}) + .allow_unmodified_shortcuts(); + let handle = app.handle(); + let guard = Guard::attach(&app.shared, Arc::new(|| {}), true, false); + assert!(handle.take_shortcut_errors().is_empty()); + assert!(handle.register_shortcut("shift+a".parse().unwrap(), |_, _| {}).is_ok()); + drop(guard); +} + +#[test] +fn background_registration_wakes_and_returns_the_backend_result() { + let app = App::new(AppSpec::new("shortcuts", (10.0, 10.0), || (), |_, _| el())); + let (wake, woke) = mpsc::channel(); + let guard = Guard::attach(&app.shared, Arc::new(move || { wake.send(()).unwrap(); }), true, false); + let handle = app.handle(); + let thread = std::thread::spawn(move || handle.register_shortcut("ctrl+space".parse().unwrap(), |_, _| {})); + woke.recv().unwrap(); + guard.drain(); + assert!(thread.join().unwrap().is_ok()); +} + +#[test] +fn activation_tokens_are_scoped_to_the_handler_and_shutdown_breaks_handle_cycles() { + let app = App::new(AppSpec::new("shortcuts", (10.0, 10.0), || false, |_, _| el())); + let weak = Arc::downgrade(&app.shared); + let guard = Guard::attach(&app.shared, Arc::new(|| {}), true, false); + let captured = app.handle(); + let id = app.handle().register_shortcut("ctrl+space".parse().unwrap(), move |state, tx| { + assert_eq!(tx.activation_token(), Some("compositor-token")); + captured.activate(tx.activation_token().unwrap()); + *state = true; + }).unwrap(); + app.shared.shortcuts.control.call(move |engine| { + (engine.sink)(id, Some("compositor-token".into())); + Ok(()) + }).unwrap(); + let mut state = false; + let mut tx = Tx::default(); + let receiving = guard.receiving(); + for f in app.shared.take().updates { f(&mut state, &mut tx); } + drop(receiving); + assert!(state); + assert_eq!(tx.activation_token(), None); + assert_eq!(app.shared.take().window, Some(crate::app::WindowRequest::Open(Some("compositor-token".into())))); + drop(app); + drop(guard); + assert!(weak.upgrade().is_none(), "handler captures must be released at host shutdown"); +} + +/// Whether a backend saw its chord still claimed as it was dropped. +static RETIRED_WITH_CLAIM: Mutex<Vec<bool>> = Mutex::new(Vec::new()); +const GRAB_CHORD: &str = "ctrl+alt+shift+f11"; + +struct Grab; + +impl Backend for Grab { + fn register(&mut self, _: ShortcutId, _: &Shortcut) -> Result<(), ShortcutError> { Ok(()) } + fn unregister(&mut self, _: ShortcutId) -> Result<(), ShortcutError> { Ok(()) } +} + +// A desktop grab stands until the backend is gone, so the claim that names it must stand too. +impl Drop for Grab { + fn drop(&mut self) { + let held = NATIVE.lock().unwrap().iter().any(|(.., s, _)| *s == GRAB_CHORD.parse::<Shortcut>().unwrap()); + RETIRED_WITH_CLAIM.lock().unwrap().push(held); + } +} + +fn grab(_: bool, _: Sink) -> Result<NativeBackend, ShortcutError> { Ok(Box::new(Grab)) } + +#[test] +fn a_backend_retires_before_its_chord_stops_naming_an_owner() { + RETIRED_WITH_CLAIM.lock().unwrap().clear(); + let shortcut = GRAB_CHORD.parse::<Shortcut>().unwrap(); + let mut engine = Engine { title: "Grab", wayland: false, sink: Arc::new(|_, _| {}), connect: grab, bindings: Bindings::Disconnected }; + let id = ShortcutId(0x7000_0001); + engine.register(id, shortcut.clone()).unwrap(); + engine.unregister(id).unwrap(); + assert!(engine.bindings.find(&shortcut).is_none(), "the registration went"); + assert!(!NATIVE.lock().unwrap().iter().any(|(.., s, _)| *s == shortcut), "the claim went with the registration"); + assert_eq!(*RETIRED_WITH_CLAIM.lock().unwrap(), vec![true], "the backend saw its chord still claimed while it was alive"); +} diff --git a/app/vendor/rune/crates/rune/src/shortcuts/wayland.rs b/app/vendor/rune/crates/rune/src/shortcuts/wayland.rs new file mode 100644 index 0000000..9e1d6c2 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/shortcuts/wayland.rs @@ -0,0 +1,190 @@ +//! xdg-desktop-portal GlobalShortcuts. Each binding owns a session so unregister works on +//! portal v1 (which cannot remove a binding from an existing session). +use super::{Backend, Shortcut, ShortcutError, ShortcutId, Sink}; +use crate::platform::portal::{self, DEST, PATH, RequestError, RequestTimeouts}; +use async_channel::{Sender, unbounded}; +use futures_lite::{FutureExt, StreamExt}; +use std::{collections::HashMap, sync::mpsc, thread::JoinHandle, time::Duration}; +use zbus::{Connection, Proxy, zvariant::{OwnedObjectPath, OwnedValue, Type, Value}}; + +const INTERFACE: &str = "org.freedesktop.portal.GlobalShortcuts"; +const RPC_TIMEOUT: Duration = Duration::from_secs(5); +const CONSENT_TIMEOUT: Duration = Duration::from_secs(120); +type Reply = mpsc::SyncSender<Result<(), ShortcutError>>; +enum Command { Register(ShortcutId, Shortcut, Reply), Unregister(ShortcutId, Reply) } +pub(super) struct Native { commands: Option<Sender<Command>>, worker: Option<JoinHandle<()>> } + +fn dbus_error(e: zbus::Error) -> ShortcutError { + if portal::is_unavailable(&e) { + return ShortcutError::Unsupported; + } + if let zbus::Error::MethodError(name, _, _) = &e { + return match name.as_str() { + "org.freedesktop.portal.Error.Exist" => ShortcutError::Conflict, + "org.freedesktop.portal.Error.NotAllowed" | "org.freedesktop.portal.Error.Cancelled" => ShortcutError::PermissionDenied, + "org.freedesktop.portal.Error.InvalidArgument" => ShortcutError::InvalidAccelerator(e.to_string()), + _ => ShortcutError::Backend(e.to_string()), + }; + } + ShortcutError::Backend(e.to_string()) +} +fn response_status(status: u32) -> Result<(), ShortcutError> { + match status { 0 => Ok(()), 1 => Err(ShortcutError::PermissionDenied), n => Err(ShortcutError::Backend(format!("portal response {n}"))) } +} +fn timed_out() -> ShortcutError { ShortcutError::Backend("portal request timed out".into()) } + +async fn request<B: serde::Serialize + Type>(conn: &Connection, portal_proxy: &Proxy<'_>, token: &str, + method: &str, body: &B) -> Result<HashMap<String, OwnedValue>, ShortcutError> { + let (status, values) = portal::request( + conn, + portal_proxy, + token, + method, + body, + RequestTimeouts { rpc: RPC_TIMEOUT, response: Some(CONSENT_TIMEOUT) }, + std::future::pending(), + ).await.map_err(|err| match err { + RequestError::Dbus(e) => dbus_error(e), + RequestError::Unavailable => ShortcutError::Unsupported, + RequestError::TimedOut => timed_out(), + RequestError::Disconnected | RequestError::Cancelled => ShortcutError::Backend("portal disconnected".into()), + })?; + response_status(status)?; + Ok(values) +} + +async fn close(conn: &Connection, session: &OwnedObjectPath) -> Result<(), ShortcutError> { + portal::timeout(RPC_TIMEOUT, async { + let proxy = Proxy::new(conn, DEST, session.as_str(), "org.freedesktop.portal.Session").await.map_err(dbus_error)?; + proxy.call::<_, _, ()>("Close", &()).await.map_err(dbus_error) + }).await.unwrap_or_else(|| Err(timed_out())) +} + +async fn bind(conn: &Connection, portal_proxy: &Proxy<'_>, id: ShortcutId, shortcut: &Shortcut) -> Result<OwnedObjectPath, ShortcutError> { + let create = portal::next_token("shortcuts_create"); + let session_token = portal::next_token("shortcuts_session"); + let options = HashMap::from([("handle_token", Value::from(create.as_str())), ("session_handle_token", Value::from(session_token.as_str()))]); + let response = request(conn, portal_proxy, &create, "CreateSession", &(options,)).await?; + let value = response.get("session_handle").ok_or_else(|| ShortcutError::Backend("portal omitted session_handle".into()))?; + let session = if let Ok(path) = <&str>::try_from(value) { + OwnedObjectPath::try_from(path.to_owned()).map_err(|e| ShortcutError::Backend(e.to_string()))? + } else { OwnedObjectPath::try_from(value.try_clone().map_err(|e| ShortcutError::Backend(e.to_string()))?) + .map_err(|e| ShortcutError::Backend(e.to_string()))? }; + let bind_token = portal::next_token("shortcuts_bind"); + let options = HashMap::from([("handle_token", Value::from(bind_token.as_str()))]); + let trigger = shortcut.portal_trigger(); + let description = format!("Shortcut {shortcut}"); + let info = HashMap::from([("description", Value::from(description.as_str())), ("preferred_trigger", Value::from(trigger.as_str()))]); + let shortcuts = vec![(id.0.to_string(), info)]; + match request(conn, portal_proxy, &bind_token, "BindShortcuts", &(&session, shortcuts, "", options)).await { + Ok(response) => { + // Success with no matching binding is not a registration. The compositor chooses + // the actual trigger; a preferred-trigger conflict is not standardized by the portal. + let bindings = response.get("shortcuts").and_then(|v| v.try_clone().ok()) + .and_then(|v| Vec::<(String, HashMap<String, OwnedValue>)>::try_from(v).ok()); + if bindings.as_ref().is_some_and(|v| v.iter().any(|(key, _)| key == &id.0.to_string())) { Ok(session) } + else { close(conn, &session).await.ok(); Err(ShortcutError::PermissionDenied) } + } + Err(e) => { close(conn, &session).await.ok(); Err(e) } + } +} + +impl Native { + pub(super) fn new(sink: Sink) -> Result<Self, ShortcutError> { + let (commands, receiver) = unbounded(); + let (ready, result) = mpsc::sync_channel(1); + let worker = std::thread::Builder::new().name("rune-shortcuts-portal".into()).spawn(move || { + async_io::block_on(async move { + let setup = portal::timeout(RPC_TIMEOUT, async { + // No session bus means this desktop cannot supply the portal. + let conn = Connection::session().await.map_err(|_| ShortcutError::Unsupported)?; + let portal = Proxy::new(&conn, DEST, PATH, INTERFACE).await.map_err(dbus_error)?; + // Some portal frontends report InvalidArgs rather than UnknownInterface + // when a backend for this interface is absent. The property is fixed here. + let _: u32 = portal.get_property("version").await.map_err(|_| ShortcutError::Unsupported)?; + let events = portal.receive_signal("Activated").await.map_err(dbus_error)?; + Ok::<_, ShortcutError>((conn, portal, events)) + }).await.unwrap_or(Err(ShortcutError::Unsupported)); + let (conn, portal, mut events) = match setup { + Ok(v) => { ready.send(Ok(())).ok(); v }, + Err(e) => { ready.send(Err(e)).ok(); return; } + }; + let mut sessions: HashMap<ShortcutId, OwnedObjectPath> = HashMap::new(); + enum Wake { + Command(Option<Command>), + Event(Option<zbus::Message>), + } + loop { + let next = async { Wake::Command(receiver.recv().await.ok()) } + .or(async { Wake::Event(events.next().await) }) + .await; + match next { + Wake::Command(Some(Command::Register(id, shortcut, reply))) => { + let result = bind(&conn, &portal, id, &shortcut).await.map(|session| { sessions.insert(id, session); }); + reply.send(result).ok(); + } + Wake::Command(Some(Command::Unregister(id, reply))) => { + let result = match sessions.get(&id) { + Some(session) => close(&conn, session).await, + None => Err(ShortcutError::UnknownId), + }; + if result.is_ok() { sessions.remove(&id); } + reply.send(result).ok(); + } + Wake::Command(None) | Wake::Event(None) => break, + Wake::Event(Some(event)) => { + if let Ok((session, key, _, options)) = event.body().deserialize::<(OwnedObjectPath, String, u64, HashMap<String, OwnedValue>)>() + && let Ok(id) = key.parse::<u32>().map(ShortcutId) + && sessions.get(&id) == Some(&session) { + let token = options.get("activation_token").and_then(|v| <&str>::try_from(v).ok()).map(str::to_owned); + sink(id, token); + } + } + } + } + for session in sessions.values() { close(&conn, session).await.ok(); } + conn.close().await.ok(); + }); + }).map_err(|e| ShortcutError::Backend(e.to_string()))?; + let mut native = Self { commands: Some(commands), worker: Some(worker) }; + if let Err(e) = result.recv().unwrap_or(Err(ShortcutError::Unsupported)) { + native.commands.take(); + return Err(e); + } + Ok(native) + } + fn send(&self, command: impl FnOnce(Reply) -> Command) -> Result<(), ShortcutError> { + let (reply, result) = mpsc::sync_channel(1); + self.commands.as_ref().ok_or(ShortcutError::NotRunning)?.try_send(command(reply)).map_err(|_| ShortcutError::Backend("portal disconnected".into()))?; + result.recv().unwrap_or_else(|_| Err(ShortcutError::Backend("portal disconnected".into()))) + } +} +impl Backend for Native { + fn register(&mut self, id: ShortcutId, shortcut: &Shortcut) -> Result<(), ShortcutError> { self.send(|reply| Command::Register(id, shortcut.clone(), reply)) } + fn unregister(&mut self, id: ShortcutId) -> Result<(), ShortcutError> { self.send(|reply| Command::Unregister(id, reply)) } +} +impl Drop for Native { + fn drop(&mut self) { + self.commands.take(); + if let Some(worker) = self.worker.take() { worker.join().ok(); } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use zbus::fdo; + #[test] + fn portal_cancellation_is_not_a_conflict() { + assert_eq!(response_status(1), Err(ShortcutError::PermissionDenied)); + assert!(matches!(response_status(2), Err(ShortcutError::Backend(_)))); + } + #[test] + fn missing_portal_is_unsupported() { + let fdo = |e| zbus::Error::FDO(Box::new(e)); + assert_eq!(dbus_error(fdo(fdo::Error::ServiceUnknown("portal".into()))), ShortcutError::Unsupported); + assert_eq!(dbus_error(fdo(fdo::Error::UnknownMethod("BindShortcuts".into()))), ShortcutError::Unsupported); + assert_eq!(dbus_error(fdo(fdo::Error::SpawnChildExited("portal".into()))), ShortcutError::Unsupported); + assert!(matches!(dbus_error(fdo(fdo::Error::Failed("x".into()))), ShortcutError::Backend(_))); + } +} diff --git a/app/vendor/rune/crates/rune/src/shortcuts/windows.rs b/app/vendor/rune/crates/rune/src/shortcuts/windows.rs new file mode 100644 index 0000000..56b6ca7 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/shortcuts/windows.rs @@ -0,0 +1,93 @@ +//! A message-only window receives WM_HOTKEY inside winit's event-loop thread. + +#![allow(unsafe_code)] + +use super::{Backend, Shortcut, ShortcutError, ShortcutId, Sink, native_status, parse::*}; +use std::{cell::RefCell, collections::HashMap, ptr}; +use winit::platform::scancode::PhysicalKeyExtScancode; +use windows_sys::Win32::{Foundation::*, System::LibraryLoader::GetModuleHandleW, UI::{WindowsAndMessaging::*, Input::KeyboardAndMouse::*}}; + +struct Context { sink: Sink, ids: RefCell<HashMap<i32, ShortcutId>> } +pub(super) struct Native { window: HWND, context: Box<Context> } + +unsafe extern "system" fn procedure(hwnd: HWND, message: u32, w: WPARAM, l: LPARAM) -> LRESULT { + // SAFETY: Windows owns the message parameters. The context outlives the window and is + // only accessed on its creating thread; it is cleared before destruction completes. + unsafe { + if message == WM_NCCREATE { + let create = &*(l as *const CREATESTRUCTW); + SetWindowLongPtrW(hwnd, GWLP_USERDATA, create.lpCreateParams as isize); + } + if message == WM_HOTKEY { + let p = GetWindowLongPtrW(hwnd, GWLP_USERDATA) as *const Context; + if let Some(context) = p.as_ref() { + let id = context.ids.borrow().get(&(w as i32)).copied(); + if let Some(id) = id { + std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| (context.sink)(id, None))).ok(); + } + } + return 0; + } + if message == WM_NCDESTROY { SetWindowLongPtrW(hwnd, GWLP_USERDATA, 0); } + DefWindowProcW(hwnd, message, w, l) + } +} + +fn last_error() -> ShortcutError { + // SAFETY: Reads this thread's last Win32 status immediately after a failed call. + native_status(unsafe { GetLastError() }.into(), ERROR_HOTKEY_ALREADY_REGISTERED.into()).unwrap_err() +} + +impl Native { + pub(super) fn new(sink: Sink) -> Result<Self, ShortcutError> { + let class: Vec<u16> = "RuneGlobalShortcuts\0".encode_utf16().collect(); + let mut context = Box::new(Context { sink, ids: RefCell::default() }); + // SAFETY: Class name is NUL-terminated; the box is stable until after DestroyWindow. + unsafe { + let instance = GetModuleHandleW(ptr::null()); + let wc = WNDCLASSW { lpfnWndProc: Some(procedure), hInstance: instance, lpszClassName: class.as_ptr(), ..std::mem::zeroed() }; + if RegisterClassW(&wc) == 0 && GetLastError() != ERROR_CLASS_ALREADY_EXISTS { return Err(last_error()); } + let window = CreateWindowExW(0, class.as_ptr(), ptr::null(), 0, 0, 0, 0, 0, HWND_MESSAGE, + ptr::null_mut(), instance, (&mut *context as *mut Context).cast()); + if window.is_null() { return Err(last_error()); } + Ok(Self { window, context }) + } + } +} + +impl Backend for Native { + fn register(&mut self, id: ShortcutId, shortcut: &Shortcut) -> Result<(), ShortcutError> { + let local = (1..=0xbfff).find(|id| !self.context.ids.borrow().contains_key(id)) + .ok_or_else(|| ShortcutError::Backend("Win32 hotkey id space exhausted".into()))?; + let mut mods = MOD_NOREPEAT; + for (bit, native) in [(CTRL, MOD_CONTROL), (ALT, MOD_ALT), (SHIFT, MOD_SHIFT), (SUPER, MOD_WIN)] { + if shortcut.mods & bit != 0 { mods |= native; } + } + let scan = shortcut.physical_key().to_scancode().ok_or_else(|| ShortcutError::InvalidAccelerator(shortcut.to_string()))?; + // RegisterHotKey takes a virtual key. Resolve the physical scan code in the + // current layout rather than assuming US letters. Re-register on layout changes. + // SAFETY: `MapVirtualKeyW` takes integer values only and reads the active keyboard layout. + let key = unsafe { MapVirtualKeyW(scan, MAPVK_VSC_TO_VK_EX) }; + if key == 0 { return Err(ShortcutError::InvalidAccelerator(shortcut.to_string())); } + // SAFETY: RegisterHotKey and its window run on the event-loop thread. + if unsafe { RegisterHotKey(self.window, local, mods, key) } == 0 { return Err(last_error()); } + self.context.ids.borrow_mut().insert(local, id); + Ok(()) + } + fn unregister(&mut self, id: ShortcutId) -> Result<(), ShortcutError> { + let local = self.context.ids.borrow().iter().find(|(_, v)| **v == id).map(|(k, _)| *k).ok_or(ShortcutError::UnknownId)?; + // SAFETY: The hotkey belongs to this window and thread. + if unsafe { UnregisterHotKey(self.window, local) } == 0 { return Err(last_error()); } + self.context.ids.borrow_mut().remove(&local); + Ok(()) + } +} +impl Drop for Native { + fn drop(&mut self) { + // SAFETY: Context remains alive throughout destruction. The host drops on this thread. + unsafe { + for (id, _) in self.context.ids.get_mut().drain() { UnregisterHotKey(self.window, id); } + DestroyWindow(self.window); + } + } +} diff --git a/app/vendor/rune/crates/rune/src/shortcuts/x11.rs b/app/vendor/rune/crates/rune/src/shortcuts/x11.rs new file mode 100644 index 0000000..38f9402 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/shortcuts/x11.rs @@ -0,0 +1,151 @@ +//! Checked XGrabKey requests on a private connection, with lock-modifier variants. A held +//! chord fires once (`x11_repeat`). +use super::{Backend, Shortcut, ShortcutError, ShortcutId, Sink, parse::*, x11_repeat}; +use std::{collections::HashMap, io::{Read, Write}, os::{fd::AsRawFd, unix::net::UnixStream}, sync::{Arc, Mutex}, thread::JoinHandle}; +use x11rb::{connection::Connection, errors::ReplyError, protocol::{ErrorKind, Event, xproto::*}, rust_connection::RustConnection}; +use winit::platform::scancode::PhysicalKeyExtScancode; + +#[derive(Clone, Copy)] +struct Grab { root: u32, code: u8, mods: u16 } +type Registrations = Arc<Mutex<HashMap<ShortcutId, Vec<Grab>>>>; +pub(super) struct Native { + connection: Arc<RustConnection>, + registrations: Registrations, + stop: UnixStream, + listener: Option<JoinHandle<()>>, +} +fn error(e: impl std::fmt::Display) -> ShortcutError { ShortcutError::Backend(e.to_string()) } +fn reply_error(e: ReplyError) -> ShortcutError { + match e { + ReplyError::X11Error(e) if e.error_kind == ErrorKind::Access => ShortcutError::Conflict, + e => error(e), + } +} + +impl Native { + #[allow(unsafe_code)] + pub(super) fn new(sink: Sink) -> Result<Self, ShortcutError> { + let (connection, _) = x11rb::connect(None).map_err(|_| ShortcutError::Unsupported)?; + let connection = Arc::new(connection); + let registrations: Registrations = Arc::default(); + let (stop, mut wake) = UnixStream::pair().map_err(error)?; + let conn = connection.clone(); + let keys = registrations.clone(); + let listener = std::thread::Builder::new().name("rune-shortcuts-x11".into()).spawn(move || { + let mut fds = [libc::pollfd { fd: conn.stream().as_raw_fd(), events: libc::POLLIN, revents: 0 }, + libc::pollfd { fd: wake.as_raw_fd(), events: libc::POLLIN, revents: 0 }]; + let mut repeats = x11_repeat::Held::default(); + loop { + loop { + match conn.poll_for_event() { + Ok(Some(Event::KeyRelease(event))) => { + let _ = x11_repeat::step(&mut repeats, + x11_repeat::Event::Release { code: event.detail, time: event.time }); + } + Ok(Some(Event::KeyPress(event))) if x11_repeat::step(&mut repeats, + x11_repeat::Event::Press { code: event.detail, time: event.time }).is_empty() => {} + Ok(Some(Event::KeyPress(event))) => { + let id = keys.lock().unwrap().iter().find(|(_, grabs)| grabs.iter().any(|g| + g.root == event.root && g.code == event.detail && g.mods == u16::from(event.state) & 0xff)).map(|(id, _)| *id); + if let Some(id) = id { sink(id, None); } + } + Ok(Some(_)) => {}, Ok(None) => break, Err(_) => return, + } + } + // SAFETY: Both descriptors stay open for this thread's lifetime; poll only writes revents. + if unsafe { libc::poll(fds.as_mut_ptr(), 2, -1) } < 0 { + if std::io::Error::last_os_error().kind() == std::io::ErrorKind::Interrupted { continue; } + return; + } + if fds[1].revents != 0 { + let mut byte = [0]; + if wake.read_exact(&mut byte).is_err() || byte[0] == 0 { return; } + } + if fds[0].revents & (libc::POLLERR | libc::POLLHUP | libc::POLLNVAL) != 0 { return; } + } + }).map_err(error)?; + Ok(Self { connection, registrations, stop, listener: Some(listener) }) + } + + fn release(&self, grabs: &[Grab]) -> Result<(), ShortcutError> { + let mut result = Ok(()); + for g in grabs { + if let Err(error) = self.connection.ungrab_key(g.code, g.root, ModMask::from(g.mods)) + .map_err(error).and_then(|cookie| cookie.check().map_err(reply_error)) { + result = Err(error); + } + } + result + } +} + +impl Backend for Native { + fn register(&mut self, id: ShortcutId, shortcut: &Shortcut) -> Result<(), ShortcutError> { + let conn = &self.connection; + let setup = conn.setup(); + let mapping = conn.get_keyboard_mapping(setup.min_keycode, setup.max_keycode - setup.min_keycode + 1) + .map_err(error)?.reply().map_err(reply_error)?; + let code = shortcut.physical_key().to_scancode().and_then(|c| u8::try_from(c + 8).ok()) + .filter(|c| (setup.min_keycode..=setup.max_keycode).contains(c)) + .ok_or_else(|| ShortcutError::InvalidAccelerator(shortcut.to_string()))?; + let mut numcodes = Vec::new(); + for (index, syms) in mapping.keysyms.chunks(mapping.keysyms_per_keycode as usize).enumerate() { + let code = setup.min_keycode + index as u8; + if syms.contains(&0xff7f) { numcodes.push(code); } // XK_Num_Lock + } + let modifiers = conn.get_modifier_mapping().map_err(error)?.reply().map_err(reply_error)?; + let mut numlock = 0; + if modifiers.keycodes_per_modifier() != 0 { + for (index, keys) in modifiers.keycodes.chunks(modifiers.keycodes_per_modifier() as usize).enumerate() { + if keys.iter().any(|k| numcodes.contains(k)) { numlock |= 1 << index; } + } + } + let mut base = 0; + for (bit, x) in [(CTRL, 4), (ALT, 8), (SHIFT, 1), (SUPER, 64)] { if shortcut.mods & bit != 0 { base |= x; } } + let mut variants = vec![base, base | 2, base | numlock, base | numlock | 2]; + variants.sort_unstable(); variants.dedup(); + let mut grabbed = Vec::new(); + for screen in &setup.roots { + for &mods in &variants { + let result = conn.grab_key(false, screen.root, ModMask::from(mods), code, GrabMode::ASYNC, GrabMode::ASYNC) + .map_err(error).and_then(|cookie| cookie.check().map_err(reply_error)); + if let Err(e) = result { + if let Err(rollback) = self.release(&grabbed) { eprintln!("rune: shortcut rollback: {rollback}"); } + return Err(e); + } + grabbed.push(Grab { root: screen.root, code, mods }); + } + } + self.registrations.lock().unwrap().insert(id, grabbed); + if let Err(e) = self.stop.write_all(&[1]) { + let grabbed = self.registrations.lock().unwrap().remove(&id).unwrap(); + if let Err(rollback) = self.release(&grabbed) { eprintln!("rune: shortcut rollback: {rollback}"); } + return Err(error(e)); + } + Ok(()) + } + fn unregister(&mut self, id: ShortcutId) -> Result<(), ShortcutError> { + let grabs = self.registrations.lock().unwrap().get(&id).cloned().ok_or(ShortcutError::UnknownId)?; + self.release(&grabs)?; + self.registrations.lock().unwrap().remove(&id); + Ok(()) + } +} +impl Drop for Native { + fn drop(&mut self) { + self.stop.write_all(&[0]).ok(); + if let Some(listener) = self.listener.take() { listener.join().ok(); } + // Closing this dedicated connection releases every passive grab, including a partial failure. + } +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn bad_access_is_a_conflict() { + let native = x11rb::x11_utils::X11Error { error_kind: ErrorKind::Access, error_code: 10, + sequence: 1, bad_value: 0, minor_opcode: 0, major_opcode: 33, extension_name: None, request_name: None }; + assert_eq!(reply_error(ReplyError::X11Error(native)), ShortcutError::Conflict); + } +} diff --git a/app/vendor/rune/crates/rune/src/shortcuts/x11_repeat.rs b/app/vendor/rune/crates/rune/src/shortcuts/x11_repeat.rs new file mode 100644 index 0000000..a189481 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/shortcuts/x11_repeat.rs @@ -0,0 +1,120 @@ +//! X11 autorepeat filter for grabbed shortcuts. Without detectable autorepeat the server sends +//! each repeat as a KeyRelease and a KeyPress with the same timestamp; with it, as KeyPresses +//! with no release between. Either way only the first press of a hold fires, as on macOS and +//! Windows. A release is held back until the next event shows whether a repeat follows it. + +use crate::machine::Effects; + +/// The keys a hold has down, and the release waiting to see whether a repeat follows it. +#[derive(Default)] +pub(super) enum Held { + /// No key is down and no release waits. + #[default] + Up, + /// These keys are down, the first one having started the active grab. + Down { keys: Vec<u8> }, + /// `code` was released at `time`; the next event says whether a repeat follows it. + AwaitingRepeat { keys: Vec<u8>, code: u8, time: u32 }, +} + +/// A grabbed key the server reported. +#[derive(Clone, Copy, Debug)] +pub(super) enum Event { + Press { code: u8, time: u32 }, + Release { code: u8, time: u32 }, +} + +/// What a transition asks its caller to do. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum Effect { + /// This press starts a hold, so the shortcut fires. + Fire, +} + +/// The hold after `event`, and what the caller carries out. +pub(super) fn step(state: &mut Held, event: Event) -> Effects<Effect> { + match event { + Event::Press { code, time } => { + let mut keys = match std::mem::take(state) { + Held::Up => Vec::new(), + Held::Down { keys } => keys, + // A release with this press's own timestamp is the repeat itself: the key stayed + // down, and the release is spent rather than replayed. + Held::AwaitingRepeat { keys, code: released, time: released_at } if (released, released_at) == (code, time) => { + *state = held(keys); + return Effects::none(); + } + Held::AwaitingRepeat { keys, code: released, .. } => forget(keys, released), + }; + if keys.contains(&code) { + *state = held(keys); + return Effects::none(); + } + keys.push(code); + *state = Held::Down { keys }; + Effects::one(Effect::Fire) + } + Event::Release { code, time } => { + let keys = match std::mem::take(state) { + Held::Up => Vec::new(), + Held::Down { keys } => keys, + Held::AwaitingRepeat { keys, code: released, .. } => forget(keys, released), + }; + *state = Held::AwaitingRepeat { keys, code, time }; + Effects::none() + } + } +} + +/// A hold with these keys down, or `Up` when there are none. +fn held(keys: Vec<u8>) -> Held { + if keys.is_empty() { Held::Up } else { Held::Down { keys } } +} + +/// The first key down started the active grab, which ends with its release; keys pressed +/// during the grab send their releases elsewhere, so they are forgotten with it. +fn forget(mut keys: Vec<u8>, released: u8) -> Vec<u8> { + if keys.first() == Some(&released) { keys.clear(); } else { keys.retain(|&c| c != released); } + keys +} + +#[cfg(test)] +mod tests { + use super::{Event, Held, step}; + + /// Whether a press fires. + fn press(r: &mut Held, code: u8, time: u32) -> bool { + !step(r, Event::Press { code, time }).is_empty() + } + + fn release(r: &mut Held, code: u8, time: u32) { + assert!(step(r, Event::Release { code, time }).is_empty(), "a release never fires"); + } + + #[test] + fn a_held_key_fires_once_in_either_autorepeat_mode() { + let mut r = Held::default(); + // Release/press pairs with matching timestamps. + assert!(press(&mut r, 38, 10)); + release(&mut r, 38, 40); assert!(!press(&mut r, 38, 40)); + release(&mut r, 38, 70); assert!(!press(&mut r, 38, 70)); + release(&mut r, 38, 90); + assert!(press(&mut r, 38, 300), "a new press after a real release fires"); + // Detectable autorepeat: presses without releases. + assert!(!press(&mut r, 38, 330)); + assert!(!press(&mut r, 38, 360)); + release(&mut r, 38, 400); + assert!(press(&mut r, 39, 410), "another key fires and settles the earlier release"); + assert!(press(&mut r, 38, 420)); + } + + #[test] + fn keys_pressed_during_a_grab_are_forgotten_when_the_grab_key_is_released() { + let mut r = Held::default(); + assert!(press(&mut r, 65, 10)); // the grabbed chord's key starts the active grab + assert!(press(&mut r, 38, 20)); // another key arrives through the grab + release(&mut r, 65, 30); // the grab ends; 38's release goes to the focused window instead + assert!(press(&mut r, 38, 400), "a later fresh press of the other key still fires"); + assert!(press(&mut r, 65, 410)); + } +} diff --git a/app/vendor/rune/crates/rune/src/states.rs b/app/vendor/rune/crates/rune/src/states.rs new file mode 100644 index 0000000..34c5c25 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/states.rs @@ -0,0 +1,63 @@ +//! What an element's handler is handed. Handlers are stored type-erased and take the state of +//! the type they were built for: the app's, or, while the playground shows a stage, the stage's +//! (a fresh scene state or a page's own), beside the playground's own controls. + +use std::any::Any; + +/// The states one handler call can reach; [`States::cast`] picks the handler's own. +pub(crate) struct States<'a> { + app: &'a mut dyn Any, + extra: Option<&'a mut dyn Any>, +} + +impl<'a> States<'a> { + pub(crate) fn one(app: &'a mut dyn Any) -> Self { + States { app, extra: None } + } + + pub(crate) fn two(app: &'a mut dyn Any, extra: &'a mut dyn Any) -> Self { + States { app, extra: Some(extra) } + } + + /// None when neither is an `S`: a deferred callback whose stage the playground has dropped. + pub(crate) fn cast<S: 'static>(self) -> Option<&'a mut S> { + if self.app.is::<S>() { + return self.app.downcast_mut(); + } + self.extra?.downcast_mut() + } + + pub(crate) fn reborrow(&mut self) -> States<'_> { + States { app: &mut *self.app, extra: self.extra.as_deref_mut() } + } +} + +/// [`States`] for reads (index-built rows, drag-out items). +#[derive(Clone, Copy)] +pub(crate) struct StatesRef<'a> { + app: &'a dyn Any, + extra: Option<&'a dyn Any>, +} + +impl<'a> StatesRef<'a> { + pub(crate) fn one(app: &'a dyn Any) -> Self { + StatesRef { app, extra: None } + } + + pub(crate) fn two(app: &'a dyn Any, extra: &'a dyn Any) -> Self { + StatesRef { app, extra: Some(extra) } + } + + pub(crate) fn cast<S: 'static>(self) -> Option<&'a S> { + self.app.downcast_ref().or_else(|| self.extra?.downcast_ref()) + } +} + +pub(crate) fn downcast<S: 'static>(s: States<'_>) -> &mut S { + s.cast::<S>().expect("handler registered for a different state type than the app's") +} + +/// Pins an edit-access closure's signature, so Rust ties the returned borrow to the states. +pub(crate) fn edit_fn<F: for<'a> Fn(States<'a>) -> &'a mut crate::edit::TextEdit>(f: F) -> F { + f +} diff --git a/app/vendor/rune/crates/rune/src/system_material/macos.rs b/app/vendor/rune/crates/rune/src/system_material/macos.rs new file mode 100644 index 0000000..b11c99b --- /dev/null +++ b/app/vendor/rune/crates/rune/src/system_material/macos.rs @@ -0,0 +1,356 @@ +//! Native material views behind a window's Metal layer, moved in the drawable's transaction. +//! +//! winit's content view is layer-backed and wgpu draws into a CAMetalLayer that is a sublayer +//! of the view's layer. Material views live in a flipped host view added under that layer, +//! which never takes clicks, so winit's view still receives every event. With +//! `presentsWithTransaction` on the Metal layer, wgpu presents the drawable into the current +//! Core Animation transaction; the shell opens one around the present and sets every view's +//! frame, corner radius and alpha inside it, so the WindowServer composites the material, the +//! shadow around it and the content on top from the same commit. + +#![allow(unsafe_code)] + +use super::{assign, MaterialDraw, Mode, PresentFlag, SystemMaterial, MAX_NATIVE_MATERIALS}; +use rune_motion::NodeId; +use objc2_core_foundation::{CGPoint, CGRect, CGSize}; +use objc2::rc::Retained; +use objc2::runtime::{AnyClass, AnyObject, Bool, ClassBuilder, Sel}; +use objc2::{msg_send, sel}; +use std::{cell::Cell, rc::Rc}; + +/// The host view: flipped, so frames come straight from Rune's top-left points, and never hit, +/// so clicks fall through to winit's view behind it in the hit-test order. +fn host_class() -> Option<&'static AnyClass> { + const NAME: &std::ffi::CStr = c"RuneMaterialHost"; + if let Some(class) = AnyClass::get(NAME) { return Some(class); } + let mut builder = ClassBuilder::new(NAME, AnyClass::get(c"NSView")?)?; + unsafe extern "C-unwind" fn flipped(_: &AnyObject, _: Sel) -> Bool { Bool::YES } + unsafe extern "C-unwind" fn hit_test(_: &AnyObject, _: Sel, _: CGPoint) -> *mut AnyObject { std::ptr::null_mut() } + // SAFETY: the signatures match -[NSView isFlipped] and -[NSView hitTest:]. + unsafe { + builder.add_method(sel!(isFlipped), flipped as unsafe extern "C-unwind" fn(_, _) -> _); + builder.add_method(sel!(hitTest:), hit_test as unsafe extern "C-unwind" fn(_, _, _) -> _); + } + Some(builder.register()) +} + +fn rect(x: f64, y: f64, w: f64, h: f64) -> CGRect { + CGRect { origin: CGPoint { x, y }, size: CGSize { width: w, height: h } } +} + +struct Slot { + view: Retained<AnyObject>, + material: SystemMaterial, + /// `NSGlassEffectView`, which rounds itself; the effect views round their layer. + glass: bool, + /// The element it showed last, which keeps it while it stays mounted. + owner: Option<NodeId>, + /// Frame, corner radius and curve last set, and the alpha (`None` once hidden). + shape: Option<([f64; 4], f64, bool)>, + shown: Option<f64>, +} + +#[link(name = "QuartzCore", kind = "framework")] +unsafe extern "C" { + static kCACornerCurveContinuous: &'static AnyObject; + static kCACornerCurveCircular: &'static AnyObject; +} + +/// One window's material views. +pub(crate) struct Materials { + mode: Mode, + /// Native views are on: elements skip their fill, and in synced modes the Metal layer + /// presents with transactions. + active: bool, + view: Option<Retained<AnyObject>>, + host: Option<Retained<AnyObject>>, + metal: Option<Retained<AnyObject>>, + flag: Rc<Cell<PresentFlag>>, + live_end: Option<Retained<AnyObject>>, + slots: Vec<Slot>, +} + +impl Materials { + pub(crate) fn new() -> Self { + Materials { mode: Mode::from_env(), active: false, view: None, host: None, metal: None, flag: Rc::default(), live_end: None, slots: Vec::new() } + } + + /// Whether this frame's elements should leave their interior to native views. + pub(crate) fn native(&self) -> bool { self.active } + + /// Whether `present` would only present: no material views to move with the drawable, and + /// the layer presents without transactions, so the present can happen on another thread. + pub(crate) fn presents_plainly(&self) -> bool { + !self.active && self.slots.iter().all(|s| s.shown.is_none()) && !self.flag.get().written() + } + + fn update_flag(&self, f: impl FnOnce(&mut PresentFlag) -> Option<bool>) -> Option<bool> { + let mut flag = self.flag.get(); + let out = f(&mut flag); + self.flag.set(flag); + out + } + + /// A window frame animation started or stopped: it presents with transactions while it + /// moves, and native materials keep them on after it lands. + pub(crate) fn set_moving(&mut self, surface: &wgpu::Surface<'_>, on: bool) { + if let Some(on) = self.update_flag(|f| f.moving(on)) { crate::platform::macos::present_with_transaction(surface, on); } + } + + /// The user started or stopped dragging the window's edge: each frame of the drag presents + /// in the transaction that resizes the window, and `NSWindowDidEndLiveResizeNotification` + /// turns it off as soon as they let go even if the window is idle afterwards. + pub(crate) fn set_live(&mut self, window: &winit::window::Window, surface: &wgpu::Surface<'_>, on: bool) { + if on && self.live_end.is_none() + && let (Some(win), Some(metal)) = (crate::platform::macos::ns_window(window), metal_layer(surface)) + { + self.live_end = watch_live_end(&win, &metal, self.flag.clone()); + } + if let Some(on) = self.update_flag(|f| f.live(on)) { crate::platform::macos::present_with_transaction(surface, on); } + } + + /// After a build: switches native views on when a transparent window's frame found material + /// elements, and off when it found none. True when it switched them on, so the caller + /// drops this frame's drawable, builds again natively and acquires another: wgpu reads + /// `presentsWithTransaction` when it acquires a drawable, and this one is already out. + pub(crate) fn update(&mut self, transparent: bool, found: bool, window: &winit::window::Window, surface: &wgpu::Surface<'_>) -> bool { + if self.active && !found { + // `present` hides the views in this frame's transaction; they stay for the next activation. + self.active = false; + if let Some(on) = self.update_flag(|f| f.materials(false)) { crate::platform::macos::present_with_transaction(surface, on); } + return false; + } + if self.active || !found || !transparent || self.mode == Mode::Off { return false; } + let Some(view) = crate::platform::macos::content_view(window) else { return false }; + // SAFETY: winit's content view outlives this retain, which only adds a reference. + let Some(view) = (unsafe { Retained::retain(Retained::as_ptr(&view).cast::<AnyObject>().cast_mut()) }) else { return false }; + let Some(metal) = metal_layer(surface) else { return false }; + if self.mode != Mode::Unsynced && let Some(on) = self.update_flag(|f| f.materials(true)) { + crate::platform::macos::present_with_transaction(surface, on); + } + self.view = Some(view); + self.metal = Some(metal); + self.active = true; + true + } + + /// Presents the frame with the material views matching `draws`: in one transaction with + /// the drawable when synced, or just before it otherwise. + pub(crate) fn present(&mut self, draws: &[MaterialDraw], scale: f32, present: impl FnOnce()) { + if !self.active && self.slots.iter().all(|s| s.shown.is_none()) { return present(); } + let draws = if self.active { draws } else { &[] }; + let transaction = AnyClass::get(c"CATransaction"); + let synced = self.mode != Mode::Unsynced && transaction.is_some(); + if let Some(t) = transaction { + // SAFETY: CATransaction class methods on the main thread, balanced below. + unsafe { let _: () = msg_send![t, begin]; let _: () = msg_send![t, setDisableActions: true]; } + } + self.sync(draws, scale); + if !synced && let Some(t) = transaction { + // SAFETY: closes the transaction opened above. + unsafe { let _: () = msg_send![t, commit]; } + } + present(); + if synced && let Some(t) = transaction { + // SAFETY: closes the transaction opened above, with the drawable inside it. + unsafe { let _: () = msg_send![t, commit]; } + } + } + + fn sync(&mut self, draws: &[MaterialDraw], scale: f32) { + let draws = &draws[..draws.len().min(MAX_NATIVE_MATERIALS)]; + if draws.is_empty() && self.slots.iter().all(|s| s.shown.is_none()) { return; } + let Some(host) = self.host() else { return }; + let mode = self.mode; + let wanted: Vec<_> = draws.iter().map(|d| (mode.resolve(d.material), d.id)).collect(); + let views: Vec<_> = self.slots.iter().map(|s| (s.material, s.owner)).collect(); + let mut taken = vec![false; self.slots.len()]; + for (draw, (at, &(material, id))) in draws.iter().zip(assign(&views, &wanted).into_iter().zip(&wanted)) { + let k = match at { + Some(k) => k, + None => { + let Some(slot) = make_view(material, &host) else { continue }; + self.slots.push(slot); + taken.push(false); + self.slots.len() - 1 + } + }; + taken[k] = true; + let slot = &mut self.slots[k]; + slot.owner = Some(id); + let (frame, radius) = draw.points(scale); + let shape = (frame, radius, draw.continuous); + let alpha = f64::from(draw.opacity.clamp(0.0, 1.0)); + let view = &*slot.view; + // SAFETY: NSView and NSGlassEffectView setters and CALayer properties on the main thread. + unsafe { + if slot.shown != Some(alpha) { let _: () = msg_send![view, setAlphaValue: alpha]; } + if slot.shape != Some(shape) { + let _: () = msg_send![view, setFrame: rect(frame[0], frame[1], frame[2], frame[3])]; + if slot.glass { + let _: () = msg_send![view, setCornerRadius: radius]; + } else { + let layer: *mut AnyObject = msg_send![view, layer]; + if let Some(layer) = layer.as_ref() { + let _: () = msg_send![layer, setCornerRadius: radius]; + let curve: &AnyObject = if draw.continuous { kCACornerCurveContinuous } else { kCACornerCurveCircular }; + let _: () = msg_send![layer, setCornerCurve: curve]; + } + } + let _: () = msg_send![view, layoutSubtreeIfNeeded]; + let _: () = msg_send![view, displayIfNeeded]; + } + } + slot.shape = Some(shape); + slot.shown = Some(alpha); + } + for (slot, _) in self.slots.iter_mut().zip(taken).filter(|(s, taken)| !taken && s.shown.is_some()) { + // SAFETY: an NSView setter on the main thread. Zero alpha rather than hidden keeps + // the view's backdrop layers, as at creation. + unsafe { let _: () = msg_send![&*slot.view, setAlphaValue: 0.0f64]; } + slot.shown = None; + slot.owner = None; + } + // At most one spare view per material: unmounting a few elements needn't keep their views. + let mut k = self.slots.len(); + while k > 0 { + k -= 1; + let spare = |s: &Slot| s.shown.is_none(); + if spare(&self.slots[k]) && self.slots[..k].iter().any(|s| spare(s) && s.material == self.slots[k].material) { + // SAFETY: removes a view this struct added to the host. + unsafe { let _: () = msg_send![&*self.slots.remove(k).view, removeFromSuperview]; } + } + } + } + + /// The host view, added under the Metal layer on first use and kept there. + fn host(&mut self) -> Option<Retained<AnyObject>> { + let view = self.view.clone()?; + if self.host.is_none() { + // SAFETY: AppKit calls on the main thread; `host` is retained here and added to + // winit's content view below every other subview. + unsafe { + let bounds: CGRect = msg_send![&*view, bounds]; + let alloc: *mut AnyObject = msg_send![host_class()?, alloc]; + let host: *mut AnyObject = msg_send![alloc, initWithFrame: bounds]; + let host = Retained::from_raw(host)?; + // Width and height sizable. + let _: () = msg_send![&*host, setAutoresizingMask: 18usize]; + let _: () = msg_send![&*host, setWantsLayer: true]; + let _: () = msg_send![&*view, addSubview: &*host, positioned: -1isize, relativeTo: std::ptr::null::<AnyObject>()]; + self.host = Some(host); + } + } + let host = self.host.clone()?; + // SAFETY: CALayer reads and an insert within the content view's own layer. + unsafe { + let root: *mut AnyObject = msg_send![&*view, layer]; + let host_layer: *mut AnyObject = msg_send![&*host, layer]; + if let (Some(root), Some(host_layer), Some(metal)) = (root.as_ref(), host_layer.as_ref(), self.metal.as_deref()) { + let layers: *mut AnyObject = msg_send![root, sublayers]; + if let Some(layers) = layers.as_ref() { + let at = |layer: &AnyObject| -> usize { msg_send![layers, indexOfObjectIdenticalTo: layer] }; + if at(metal) == usize::MAX { + let _: () = msg_send![root, insertSublayer: metal, above: host_layer]; + } + // AppKit re-sorts the sublayers to its subviews' order whenever it updates + // the layer tree, such as when a hidden window is shown, which would leave + // the drawn frame under the material until the next frame. Siblings + // composite by zPosition first. + let _: () = msg_send![metal, setZPosition: 1.0f64]; + } + } + } + Some(host) + } +} + +impl Drop for Materials { + fn drop(&mut self) { + if let Some(token) = &self.live_end { + unwatch_live_end(token); + } + if let Some(host) = &self.host { + // SAFETY: removes the host this struct added; drop runs on the main thread with the window. + unsafe { let _: () = msg_send![&**host, removeFromSuperview]; } + } + } +} + +/// Turns `presentsWithTransaction` off when AppKit ends the user's live resize: winit sends +/// no event for `windowDidEndLiveResize:`, so an idle window draws no frame after mouse-up. +pub(super) fn watch_live_end(window: &AnyObject, layer: &Retained<AnyObject>, flag: Rc<Cell<PresentFlag>>) -> Option<Retained<AnyObject>> { + let center = AnyClass::get(c"NSNotificationCenter")?; + let weak = objc2::rc::Weak::from_retained(layer); + let block = block2::RcBlock::new(move |_: *mut AnyObject| { + let mut f = flag.get(); + let change = f.live(false); + flag.set(f); + if let (Some(on), Some(layer)) = (change, weak.load()) { + // SAFETY: a live CAMetalLayer on the main thread. + unsafe { let _: () = msg_send![&*layer, setPresentsWithTransaction: Bool::new(on)]; } + } + }); + let name = objc2_foundation::NSString::from_str("NSWindowDidEndLiveResizeNotification"); + // SAFETY: main thread; `Materials::drop` removes the returned observer token. + unsafe { + let center: Retained<AnyObject> = msg_send![center, defaultCenter]; + msg_send![&*center, addObserverForName: &*name, object: window, + queue: std::ptr::null::<AnyObject>(), usingBlock: &*block] + } +} + +pub(super) fn unwatch_live_end(token: &AnyObject) { + let Some(center) = AnyClass::get(c"NSNotificationCenter") else { return }; + // SAFETY: removes an observer `watch_live_end` added on the main thread. + unsafe { + let center: Retained<AnyObject> = msg_send![center, defaultCenter]; + let _: () = msg_send![&*center, removeObserver: token]; + } +} + +impl Mode { + /// The material actually shown: `Glass` falls back to the popover effect view before + /// macOS 26 and in legacy mode. + fn resolve(self, material: SystemMaterial) -> SystemMaterial { + match material { + SystemMaterial::Glass if self == Mode::Legacy || AnyClass::get(c"NSGlassEffectView").is_none() => SystemMaterial::Popover, + other => other, + } + } +} + +/// A transparent material view in `host`. +fn make_view(material: SystemMaterial, host: &AnyObject) -> Option<Slot> { + let glass = material == SystemMaterial::Glass; + let class = AnyClass::get(if glass { c"NSGlassEffectView" } else { c"NSVisualEffectView" })?; + // SAFETY: AppKit initializers and setters on the main thread; the view is retained by its slot. + unsafe { + let alloc: *mut AnyObject = msg_send![class, alloc]; + let view: *mut AnyObject = msg_send![alloc, initWithFrame: rect(0.0, 0.0, 0.0, 0.0)]; + let view = Retained::from_raw(view)?; + let _: () = msg_send![&*view, setWantsLayer: true]; + if glass { + // NSGlassEffectViewStyleRegular. + let _: () = msg_send![&*view, setStyle: 0isize]; + } else { + // NSVisualEffectMaterialPopover, behind window, always active. + let _: () = msg_send![&*view, setMaterial: 6isize]; + let _: () = msg_send![&*view, setBlendingMode: 0isize]; + let _: () = msg_send![&*view, setState: 1isize]; + let layer: *mut AnyObject = msg_send![&*view, layer]; + if let Some(layer) = layer.as_ref() { let _: () = msg_send![layer, setMasksToBounds: true]; } + } + // Built visible at zero alpha: AppKit skips a hidden glass view's backdrop layers until + // its first visible frame, which then shows unrefracted. + let _: () = msg_send![&*view, setAlphaValue: 0.0f64]; + let _: () = msg_send![host, addSubview: &*view]; + let _: () = msg_send![&*view, displayIfNeeded]; + Some(Slot { view, material, glass, owner: None, shape: None, shown: None }) + } +} + +/// The surface's CAMetalLayer, when it is one on Metal. +fn metal_layer(surface: &wgpu::Surface<'_>) -> Option<Retained<AnyObject>> { + crate::gpu::with_layer(surface, |layer| objc2::Message::retain(layer)) +} diff --git a/app/vendor/rune/crates/rune/src/system_material/mod.rs b/app/vendor/rune/crates/rune/src/system_material/mod.rs new file mode 100644 index 0000000..3b50b68 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/system_material/mod.rs @@ -0,0 +1,157 @@ +//! System backdrop materials (`El::system_material`): the platform blurs what is behind the +//! window under an element's rounded rect. On macOS a native view per material sits under the +//! transparent Metal layer and moves in the same Core Animation transaction as the drawable, +//! so the material, Rune's shadow and the content on top present together. Everywhere else, +//! in opaque windows and in headless renders, the element's fill (or a neutral tint) stands in. + +#[cfg(target_os = "macos")] +pub(crate) mod macos; +#[cfg(test)] +mod tests; + +use crate::Color; +use rune_motion::NodeId; + +/// A backdrop material the system composites behind a window. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +#[non_exhaustive] +pub enum SystemMaterial { + /// Liquid Glass (`NSGlassEffectView`, regular style) on macOS 26 and later; the popover + /// material on earlier macOS. + Glass, + /// The popover vibrancy material (`NSVisualEffectView`, `.popover`, behind window). + Popover, +} + +/// Native material views per window. Elements past this many draw their fallback instead. +pub const MAX_NATIVE_MATERIALS: usize = 4; + +/// One material element as built this frame, in physical pixels like the instances. +#[derive(Clone, Copy, Debug, PartialEq)] +pub(crate) struct MaterialDraw { + pub id: NodeId, + pub material: SystemMaterial, + /// x, y, width, height. + pub rect: [f32; 4], + /// Corner radius, already clamped to half the shorter side. + pub radius: f32, + /// Continuous corners (`El::continuous_corners`). + pub continuous: bool, + /// The element's effective opacity, ancestors included. + pub opacity: f32, +} + +impl MaterialDraw { + /// The native view's frame (x, y, width, height from the top left) and corner radius, in points. + #[cfg_attr(not(target_os = "macos"), allow(dead_code))] + pub(crate) fn points(&self, scale: f32) -> ([f64; 4], f64) { + let s = f64::from(scale.max(1e-3)); + (self.rect.map(|v| f64::from(v) / s), f64::from(self.radius) / s) + } +} + +/// Which existing view each draw takes: the view that showed the same element, else a free view +/// of the same material, else none (the caller makes one). `views` holds each view's material +/// and the element it showed last; `draws` each draw's material and element. +#[cfg_attr(not(target_os = "macos"), allow(dead_code))] +pub(crate) fn assign(views: &[(SystemMaterial, Option<NodeId>)], draws: &[(SystemMaterial, NodeId)]) -> Vec<Option<usize>> { + let mut taken = vec![false; views.len()]; + let mut out = vec![None; draws.len()]; + for (slot, &(material, id)) in out.iter_mut().zip(draws) { + if let Some(v) = (0..views.len()).find(|&v| !taken[v] && views[v] == (material, Some(id))) { + taken[v] = true; + *slot = Some(v); + } + } + for (slot, &(material, _)) in out.iter_mut().zip(draws) { + if slot.is_some() { continue; } + if let Some(v) = (0..views.len()).find(|&v| !taken[v] && views[v].0 == material) { + taken[v] = true; + *slot = Some(v); + } + } + out +} + +/// The Metal layer's `presentsWithTransaction`, which native materials, a moving window frame +/// and a live resize all need. One owner, so none turns it off under another. +#[cfg_attr(not(target_os = "macos"), allow(dead_code))] +#[derive(Clone, Copy, Debug, Default)] +pub(crate) struct PresentFlag { + moving: bool, + materials: bool, + live: bool, + written: bool, +} + +#[cfg_attr(not(target_os = "macos"), allow(dead_code))] +impl PresentFlag { + /// Whether the layer presents with transactions. + pub(crate) fn written(&self) -> bool { + self.written + } + + /// A window frame animation started or stopped. The value to write, when it changed. + pub(crate) fn moving(&mut self, on: bool) -> Option<bool> { + self.moving = on; + self.write() + } + + /// Native materials synced with the drawable switched on or off. The value to write, when it changed. + pub(crate) fn materials(&mut self, on: bool) -> Option<bool> { + self.materials = on; + self.write() + } + + /// The user started or stopped dragging the window's edge. The value to write, when it changed. + pub(crate) fn live(&mut self, on: bool) -> Option<bool> { + self.live = on; + self.write() + } + + fn write(&mut self) -> Option<bool> { + let on = self.moving || self.materials || self.live; + (on != self.written).then(|| { self.written = on; on }) + } +} + +/// One corner radius for a rect: native materials take a single radius, so this uses the +/// largest corner, clamped to half the shorter side as Rune's own rounded rects are. +pub(crate) fn clamp_radius(radii: [f32; 4], width: f32, height: f32) -> f32 { + radii.into_iter().fold(0.0f32, f32::max).min(width.min(height) * 0.5).max(0.0) +} + +/// What a material element paints in Rune's own surface when no native view backs it: its +/// fill, or a neutral tint close to the material's average look when it has none. +pub(crate) fn fallback_fill(fill: Color, dark: bool) -> Color { + if fill.a > 0.0 { return fill; } + if dark { Color { r: 0.16, g: 0.16, b: 0.17, a: 0.94 } } else { Color { r: 0.96, g: 0.96, b: 0.97, a: 0.94 } } +} + +/// How the shell hosts materials, from `RUNE_SYSTEM_MATERIAL`: unset for native views synced +/// with the drawable; `legacy` forces the pre-26 `NSVisualEffectView` path; `unsynced` moves +/// native views outside the drawable's transaction (to compare); `off` draws the fallback. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(crate) enum Mode { + #[default] + Synced, + Legacy, + Unsynced, + Off, +} + +impl Mode { + pub(crate) fn parse(value: Option<&str>) -> Mode { + match value.map(str::trim) { + Some("legacy") => Mode::Legacy, + Some("unsynced") => Mode::Unsynced, + Some("off" | "0") => Mode::Off, + _ => Mode::Synced, + } + } + + #[cfg_attr(not(target_os = "macos"), allow(dead_code))] + pub(crate) fn from_env() -> Mode { + Mode::parse(rune_core::env::var("RUNE_SYSTEM_MATERIAL").as_deref()) + } +} diff --git a/app/vendor/rune/crates/rune/src/system_material/tests.rs b/app/vendor/rune/crates/rune/src/system_material/tests.rs new file mode 100644 index 0000000..7df7b4d --- /dev/null +++ b/app/vendor/rune/crates/rune/src/system_material/tests.rs @@ -0,0 +1,322 @@ +#![allow(unsafe_code)] + +use super::*; +use crate::render::{Gpu, Instance, KIND_RECT, KIND_SHADOW, NO_CLIP, Offscreen, Renderer}; +use crate::{Color, Cx, El, Env, Runtime, el}; +use bytemuck::Zeroable; + +#[test] +fn native_frames_are_points_from_the_top_left() { + let draw = MaterialDraw { id: NodeId(1), material: SystemMaterial::Glass, rect: [20.0, 40.0, 200.0, 100.0], radius: 24.0, continuous: false, opacity: 1.0 }; + assert_eq!(draw.points(2.0), ([10.0, 20.0, 100.0, 50.0], 12.0)); + assert_eq!(draw.points(1.0), ([20.0, 40.0, 200.0, 100.0], 24.0)); +} + +#[test] +fn one_radius_is_the_largest_corner_within_half_the_shorter_side() { + assert_eq!(clamp_radius([8.0, 6.0, 4.0, 0.0], 100.0, 40.0), 8.0); + assert_eq!(clamp_radius([8.0, 30.0, 4.0, 0.0], 100.0, 40.0), 20.0); + assert_eq!(clamp_radius([500.0; 4], 30.0, 90.0), 15.0); + assert_eq!(clamp_radius([-4.0; 4], 30.0, 90.0), 0.0); + assert_eq!(clamp_radius([12.0; 4], 0.0, 90.0), 0.0); +} + +#[test] +fn fallback_keeps_a_fill_and_tints_without_one() { + let red = Color { r: 1.0, g: 0.0, b: 0.0, a: 0.5 }; + assert_eq!(fallback_fill(red, true), red); + let dark = fallback_fill(Color { a: 0.0, ..red }, true); + let light = fallback_fill(Color { a: 0.0, ..red }, false); + assert!(dark.a > 0.9 && light.a > 0.9); + assert!(dark.r < 0.3 && light.r > 0.9); +} + +#[test] +fn mode_reads_the_environment_value() { + assert_eq!(Mode::parse(None), Mode::Synced); + assert_eq!(Mode::parse(Some("legacy")), Mode::Legacy); + assert_eq!(Mode::parse(Some(" unsynced ")), Mode::Unsynced); + assert_eq!(Mode::parse(Some("off")), Mode::Off); + assert_eq!(Mode::parse(Some("0")), Mode::Off); + assert_eq!(Mode::parse(Some("anything")), Mode::Synced); +} + +const SHADOW: Color = Color { r: 0.0, g: 0.0, b: 0.0, a: 0.4 }; + +fn card() -> El { + el().absolute(30.0, 20.0).size(120.0, 60.0).radius(18.0).shadow(8.0, 24.0, SHADOW) + .system_material(SystemMaterial::Glass) +} + +fn one_card(_: &u8, _: &mut Cx<u8>) -> El { + el().size(200.0, 120.0).child(card()) +} + +fn runtime(view: fn(&u8, &mut Cx<u8>) -> El, native: bool) -> Runtime<u8> { + let mut rt = Runtime::new(0, view, (200.0, 120.0), Env { scale: 2.0, system_dark: true }); + rt.paint.set_native_materials(native); + rt.frame(0.0); + rt +} + +fn kind(rt: &Runtime<u8>, kind: f32) -> Vec<Instance> { + rt.instances.iter().filter(|q| q.params[1] == kind).copied().collect() +} + +#[test] +fn material_elements_report_physical_rects_and_clamped_radii() { + let rt = runtime(one_card, false); + assert_eq!(rt.paint.materials().len(), 1); + let m = rt.paint.materials()[0]; + assert_eq!(m.material, SystemMaterial::Glass); + assert_eq!(m.rect, [60.0, 40.0, 240.0, 120.0]); + assert_eq!(m.radius, 36.0); + assert_eq!(m.opacity, 1.0); + assert_eq!(m.points(2.0), ([30.0, 20.0, 120.0, 60.0], 18.0)); +} + +#[test] +fn without_native_views_the_element_draws_its_fallback_and_a_full_shadow() { + let rt = runtime(one_card, false); + let fills = kind(&rt, KIND_RECT); + let tint = fallback_fill(Color { r: 0.0, g: 0.0, b: 0.0, a: 0.0 }, true).premul(1.0); + assert!(fills.iter().any(|q| q.rect == [60.0, 40.0, 240.0, 120.0] && q.fill == tint), "{fills:?}"); + let shadows = kind(&rt, KIND_SHADOW); + assert_eq!(shadows.len(), 1); + assert_eq!(shadows[0].uv, [0.0; 4]); +} + +#[test] +fn over_native_views_the_fill_goes_and_the_shadow_is_cut_out() { + let rt = runtime(one_card, true); + assert!(!rt.instances.iter().any(|q| q.params[1] == KIND_RECT && q.rect == [60.0, 40.0, 240.0, 120.0] && q.fill[3] > 0.0)); + let shadows = kind(&rt, KIND_SHADOW); + assert_eq!(shadows.len(), 1); + let s = shadows[0]; + // The hole is the element's own rect, relative to the shadow's grown and offset rect. + assert_eq!([s.rect[0] + s.uv[0], s.rect[1] + s.uv[1], s.uv[2], s.uv[3]], [60.0, 40.0, 240.0, 120.0]); + // Glass draws only continuous corners, so the hole is continuous too (a negative radius). + assert_eq!(s.radii[3], -36.0); +} + +#[test] +fn glass_rounds_continuously_and_popover_follows_the_flag() { + fn cards(_: &u8, _: &mut Cx<u8>) -> El { + let popover = |x: f32| el().absolute(x, 20.0).size(40.0, 40.0).radius(10.0).system_material(SystemMaterial::Popover); + el().size(200.0, 120.0) + .child(el().absolute(10.0, 20.0).size(40.0, 40.0).radius(10.0).system_material(SystemMaterial::Glass)) + .child(popover(60.0)) + .child(popover(110.0).continuous_corners()) + } + let rt = runtime(cards, false); + assert_eq!(rt.paint.materials().iter().map(|m| m.continuous).collect::<Vec<_>>(), [true, false, true]); + // The fallback fills take the same curve: negative radii draw continuous corners. + let fill = |x: f32| kind(&rt, KIND_RECT).into_iter().find(|q| q.rect[0] == x * 2.0).unwrap().radii[0]; + assert_eq!([fill(10.0), fill(60.0), fill(110.0)], [-20.0, 20.0, -20.0]); +} + +#[test] +fn a_dimmed_out_material_takes_no_native_view() { + fn dimmed(_: &u8, _: &mut Cx<u8>) -> El { + let card = |k: usize| el().absolute(k as f32 * 30.0, 0.0).size(20.0, 20.0).system_material(SystemMaterial::Popover); + el().size(200.0, 120.0) + .children((0..MAX_NATIVE_MATERIALS).map(|k| card(k).dim(0.0))) + .child(card(MAX_NATIVE_MATERIALS)) + } + let rt = runtime(dimmed, true); + assert_eq!(rt.paint.materials().len(), 1, "only the visible element takes a view"); + assert_eq!(rt.paint.materials()[0].rect[0], MAX_NATIVE_MATERIALS as f32 * 60.0); +} + +#[test] +fn views_follow_their_element_across_insertions_and_unmounts() { + use SystemMaterial::{Glass, Popover}; + let (a, b, c) = (NodeId(1), NodeId(2), NodeId(3)); + // A popover inserted before the glass leaves the glass on its view and gets a new one. + assert_eq!(assign(&[(Glass, Some(a))], &[(Popover, b), (Glass, a)]), [None, Some(0)]); + // Unmounting the first of two leaves the second on its own view. + assert_eq!(assign(&[(Glass, Some(a)), (Glass, Some(b))], &[(Glass, b)]), [Some(1)]); + // A new element reuses a spare view of its material, or one freed this frame, never another material's. + assert_eq!(assign(&[(Glass, None), (Popover, None)], &[(Popover, c)]), [Some(1)]); + assert_eq!(assign(&[(Glass, Some(a))], &[(Glass, c)]), [Some(0)]); + assert_eq!(assign(&[(Glass, Some(a))], &[(Popover, a)]), [None]); + // An element's own view wins over an earlier draw that could also take it. + assert_eq!(assign(&[(Glass, Some(a)), (Glass, Some(b))], &[(Glass, c), (Glass, a)]), [Some(1), Some(0)]); +} + +#[test] +fn a_window_move_never_turns_off_transactions_materials_need() { + let mut flag = PresentFlag::default(); + assert_eq!(flag.materials(true), Some(true)); + // A resize animation starts and lands while materials are native: the layer stays on. + assert_eq!(flag.moving(true), None); + assert_eq!(flag.moving(false), None); + // The last material unmounts: off. + assert_eq!(flag.materials(false), Some(false)); + // A move alone turns it on and, landing, off again. + assert_eq!(flag.moving(true), Some(true)); + assert_eq!(flag.materials(true), None); + assert_eq!(flag.materials(false), None); + assert_eq!(flag.moving(false), Some(false)); + assert_eq!(flag.moving(false), None); +} + +#[test] +fn a_live_resize_keeps_transactions_on_until_it_ends() { + let mut flag = PresentFlag::default(); + assert_eq!(flag.live(true), Some(true)); + // Frames during the drag land no window animation, which would turn the flag off. + assert_eq!(flag.moving(false), None); + assert_eq!(flag.materials(false), None); + assert_eq!(flag.live(true), None); + // The drag ends: later frames present on their own again. + assert_eq!(flag.live(false), Some(false)); + // Materials keep it on past the drag. + assert_eq!(flag.materials(true), Some(true)); + assert_eq!(flag.live(true), None); + assert_eq!(flag.live(false), None); +} + +#[cfg(target_os = "macos")] +#[test] +fn live_resize_end_notification_turns_off_transactions_unless_materials_or_move_need_them() { + use objc2::{msg_send, rc::Retained, runtime::{AnyClass, AnyObject, Bool}}; + use std::{cell::Cell, rc::Rc}; + // SAFETY: `NSObject` and `CAMetalLayer` are standard classes whose `+new` returns a retained instance. + let (window, layer): (Retained<AnyObject>, Retained<AnyObject>) = unsafe { + (msg_send![AnyClass::get(c"NSObject").unwrap(), new], msg_send![AnyClass::get(c"CAMetalLayer").expect("QuartzCore"), new]) + }; + let flag = Rc::new(Cell::new(PresentFlag::default())); + let token = macos::watch_live_end(&window, &layer, flag.clone()).expect("observer"); + let sync = || -> bool { + // SAFETY: `layer` is a live `CAMetalLayer` owned by this test; `presentsWithTransaction` returns `BOOL`. + unsafe { let b: Bool = msg_send![&*layer, presentsWithTransaction]; b.as_bool() } + }; + let post_end = || { + // SAFETY: posts `NSWindowDidEndLiveResizeNotification` to the default notification center for the live test `window`. + unsafe { + let center: Retained<AnyObject> = msg_send![AnyClass::get(c"NSNotificationCenter").unwrap(), defaultCenter]; + let name = objc2_foundation::NSString::from_str("NSWindowDidEndLiveResizeNotification"); + let _: () = msg_send![&*center, postNotificationName: &*name, object: &*window]; + } + }; + let mut f = flag.get(); + assert_eq!(f.live(true), Some(true)); + flag.set(f); + // SAFETY: `layer` is a live `CAMetalLayer` owned by this test; `setPresentsWithTransaction:` takes `BOOL`. + unsafe { let _: () = msg_send![&*layer, setPresentsWithTransaction: Bool::YES]; } + assert!(sync()); + post_end(); + assert!(!sync(), "NSWindowDidEndLiveResizeNotification turns off transactions when idle"); + + // When materials also need transactions, ending live resize keeps the layer synced until materials stop. + let mut f = flag.get(); + assert_eq!(f.materials(true), Some(true)); + assert_eq!(f.live(true), None); + flag.set(f); + // SAFETY: `layer` is a live `CAMetalLayer` owned by this test; `setPresentsWithTransaction:` takes `BOOL`. + unsafe { let _: () = msg_send![&*layer, setPresentsWithTransaction: Bool::YES]; } + post_end(); + assert!(sync(), "materials keep transactions on after live resize ends"); + let mut f = flag.get(); + assert_eq!(f.materials(false), Some(false)); + flag.set(f); + macos::unwatch_live_end(&token); +} + +#[test] +fn materials_past_the_limit_draw_their_fallback() { + fn many(_: &u8, _: &mut Cx<u8>) -> El { + el().size(200.0, 120.0).children((0..MAX_NATIVE_MATERIALS + 1).map(|k| { + el().absolute(k as f32 * 30.0, 0.0).size(20.0, 20.0).fill(Color::WHITE).system_material(SystemMaterial::Popover) + })) + } + let rt = runtime(many, true); + assert_eq!(rt.paint.materials().len(), MAX_NATIVE_MATERIALS); + let white = kind(&rt, KIND_RECT).into_iter().filter(|q| q.fill[3] > 0.99).count(); + assert_eq!(white, 1, "only the element past the limit paints its fill"); +} + +#[test] +fn material_opacity_includes_ancestors() { + fn faded(_: &u8, _: &mut Cx<u8>) -> El { + el().size(200.0, 120.0).child(el().size(200.0, 120.0).opacity(0.5).child(card().opacity(0.5))) + } + let rt = runtime(faded, true); + assert!((rt.paint.materials()[0].opacity - 0.25).abs() < 1e-6); +} + +#[test] +fn headless_runtimes_never_host_native_views_and_build_identically() { + let a = Runtime::new(0u8, one_card, (200.0, 120.0), Env { scale: 2.0, system_dark: true }); + assert!(!a.paint.native_materials()); + let (a, b) = (runtime(one_card, false), runtime(one_card, false)); + assert_eq!(bytemuck::cast_slice::<Instance, u8>(&a.instances), bytemuck::cast_slice::<Instance, u8>(&b.instances)); +} + +/// The shader leaves a shadow's hole clear and the rest as it was. +#[test] +fn shadow_hole_clears_the_interior_on_the_gpu() { + let gpu = Gpu::headless(); + let mut renderer = Renderer::new(&gpu.device, crate::render::OFFSCREEN_FORMAT); + let target = Offscreen::new(&gpu.device, 64, 64); + let mut atlas = crate::text::TextSystem::default().atlas; + let shadow = Instance { + rect: [8.0, 8.0, 48.0, 48.0], radii: [10.0; 4], fill: [0.0, 0.0, 0.0, 0.8], + params: [0.0, KIND_SHADOW, 4.0, 1.0], clip: NO_CLIP, ..Instance::zeroed() + }; + let mut read = |renderer: &mut Renderer, q: Instance| { + renderer.prepare(&gpu.device, &gpu.queue, &mut atlas, &[q], (64, 64)); + let mut enc = gpu.device.create_command_encoder(&Default::default()); + renderer.draw(&mut enc, &target.view, [0.0; 4]); + target.copy(&mut enc); + renderer.submit(&gpu.queue, enc); + target.read(&gpu.device) + }; + let full = read(&mut renderer, shadow); + let cut = read(&mut renderer, Instance { radii: [10.0, 10.0, 10.0, 8.0], uv: [8.0, 8.0, 32.0, 32.0], ..shadow }); + let alpha = |px: &[u8], x: usize, y: usize| px[(y * 64 + x) * 4 + 3]; + assert!(alpha(&full, 32, 32) > 150); + assert_eq!(alpha(&cut, 32, 32), 0, "the interior is clear"); + assert_eq!(alpha(&cut, 20, 20), 0); + assert_eq!(alpha(&cut, 4, 32), alpha(&full, 4, 32), "outside the hole the shadow is unchanged"); + assert!(alpha(&cut, 10, 32) > 0); + // The hole's own corner: rounded, so its very corner keeps some shadow. + assert!(alpha(&cut, 16, 16) > 0); +} + +/// With `srgb_blend`, a 62% white frost over the material reaches the window as Core Animation +/// would composite the same CALayer: 158 over black (linear blending gives 206), and +/// premultiplied 158 over nothing for the window server to blend. The shadow's hole stays clear. +#[test] +fn srgb_blend_frost_over_a_native_material_reads_as_core_animation() { + fn frosted(frost: &u8, _: &mut Cx<u8>) -> El { + let white = Color::WHITE.alpha(0.62 * f32::from(*frost)); + el().size(200.0, 120.0).child(card().continuous_corners().child(el().size(120.0, 60.0).fill(white))) + } + let gpu = Gpu::headless(); + let read = |srgb: bool, frost: u8, clear: [f32; 4]| { + let mut rt = Runtime::new(frost, frosted, (200.0, 120.0), Env { scale: 2.0, system_dark: true }); + rt.paint.set_native_materials(true); + rt.set_srgb_blend(srgb); + rt.frame(0.0); + let format = if srgb { crate::render::OFFSCREEN_FORMAT.remove_srgb_suffix() } else { crate::render::OFFSCREEN_FORMAT }; + let mut renderer = Renderer::new(&gpu.device, format); + renderer.set_srgb_blend(srgb); + let target = Offscreen::with_format(&gpu.device, 400, 240, format); + renderer.prepare(&gpu.device, &gpu.queue, &mut rt.text.atlas, &rt.instances, (400, 240)); + let mut enc = gpu.device.create_command_encoder(&Default::default()); + renderer.draw(&mut enc, &target.view, clear); + target.copy(&mut enc); + renderer.submit(&gpu.queue, enc); + let px = target.read(&gpu.device); + let at = (100 * 400 + 180) * 4; + [px[at], px[at + 1], px[at + 2], px[at + 3]] + }; + let black = [0.0, 0.0, 0.0, 1.0]; + let near = |got: [u8; 4], want: [u8; 4]| assert!(got.iter().zip(want).all(|(g, w)| g.abs_diff(w) <= 1), "{got:?} != {want:?}"); + near(read(false, 1, black), [206, 206, 206, 255]); + near(read(true, 1, black), [158, 158, 158, 255]); + near(read(true, 1, [0.0; 4]), [158, 158, 158, 158]); + near(read(true, 0, [0.0; 4]), [0, 0, 0, 0]); +} diff --git a/app/vendor/rune/crates/rune/src/taskbar.rs b/app/vendor/rune/crates/rune/src/taskbar.rs new file mode 100644 index 0000000..181f3a4 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/taskbar.rs @@ -0,0 +1,55 @@ +//! What a window's taskbar button says about the work behind it: a progress state and a count +//! badge, set with [`crate::WindowHandle::set_taskbar`], and a bounded flash for something that +//! needs the person ([`crate::WindowHandle::flash`]). +//! +//! Windows draws both on the window's taskbar button (`ITaskbarList3`): the progress bar under it, +//! and the badge as an overlay icon over its corner. Explorer animates an indeterminate bar +//! itself, so a window showing work wakes no more than one showing nothing. Nothing is made +//! until the first call that shows something: a window that never sets a state never starts +//! the taskbar's COM object. Explorer restarting gives every window a new button; each gets +//! its state again. +//! +//! macOS shows the badge on the Dock icon, for the app as a whole: the sum of its windows' +//! counts (`NSDockTile.badgeLabel`); the Dock has no progress bar, so progress shows nothing there. +//! Linux's counterpart, Unity's `LauncherEntry` over D-Bus, isn't built: the calls do nothing. + +/// The bar under a window's taskbar button. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum TaskbarProgress { + /// No bar. + #[default] + None, + /// Work runs with no known end: Windows' indeterminate bar. + Busy, + /// Work waits on the person: a full amber bar. + Paused, + /// Work failed: a full red bar. + Error, +} + +/// A window's taskbar state. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct Taskbar { + pub(crate) progress: TaskbarProgress, + /// The count shown, 0 for none, and what a screen reader says for it. + pub(crate) badge: (u32, String), +} + +impl Taskbar { + pub fn new() -> Self { Self::default() } + + pub fn progress(mut self, progress: TaskbarProgress) -> Self { + self.progress = progress; + self + } + + /// A count over the button's corner (above 9 it reads "9+"); 0 shows none. `description` is + /// what the taskbar tells a screen reader, such as "2 sessions need you". + pub fn badge(mut self, count: u32, description: impl Into<String>) -> Self { + self.badge = (count, if count == 0 { String::new() } else { description.into() }); + self + } + + pub fn count(&self) -> u32 { self.badge.0 } + pub fn shown_progress(&self) -> TaskbarProgress { self.progress } +} diff --git a/app/vendor/rune/crates/rune/src/text.rs b/app/vendor/rune/crates/rune/src/text.rs new file mode 100644 index 0000000..6b7c4c0 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/text.rs @@ -0,0 +1,11 @@ +//! Text shaping, layout, glyph rasterization and icon rendering, re-exported from [`rune_text`], +//! plus the GPU-backed CoreText pixel comparison harness (`pixel_compare`). + +pub use rune_text::*; + +#[cfg(not(target_arch = "wasm32"))] +#[doc(hidden)] +pub mod pixel_compare; + +#[cfg(test)] +mod runtime_tests; diff --git a/app/vendor/rune/crates/rune/src/text/pixel_compare.rs b/app/vendor/rune/crates/rune/src/text/pixel_compare.rs new file mode 100644 index 0000000..7088434 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/text/pixel_compare.rs @@ -0,0 +1,669 @@ +//! Rune's text against CoreText, pixel for pixel. Fixed cases (four ink/paper pairs; Inter +//! Regular and Bold at seven sizes and the Rune vs macOS report's paragraph, or San Francisco +//! body and heading sizes, or SF Mono at code sizes; 1× and 2×) are drawn through Rune's real glyph rasteriser, atlas and +//! GPU blend, read back, and compared with CoreText reference sheets that +//! `scripts/coretext-reference.sh` draws on a Mac, with font smoothing on and off. +//! +//! The Inter sheets are committed in `crates/rune/tests/coretext/`. San Francisco can't be +//! redistributed, so its sheets (and SF Mono's) are drawn from the system's fonts into +//! `tests/coretext/sf/` and `tests/coretext/mono/` (ignored by git) and their comparisons are skipped where they're missing. +//! `cargo run -p rune --example coretext_compare` prints the table; the macOS-only test +//! `text::pixel_compare::tests` holds it to loose bounds. + +use std::fmt::Write as _; +use std::path::{Path, PathBuf}; + +use parley::PositionedLayoutItem; + +use crate::color::{hex, srgb_encode}; +use crate::render::{Gpu, NO_CLIP, OFFSCREEN_FORMAT, Offscreen, Renderer}; +use crate::text::{FontSmoothing, GlyphQuad, TextSystem}; +use crate::tok::{Family, TextStyle}; + +/// A text colour on a page colour, sRGB hex. +#[derive(Clone, Copy, Debug)] +pub struct Pair { + pub name: &'static str, + pub fg: &'static str, + pub bg: &'static str, +} + +/// Dark ink on paper; light grey (macOS's q = 0.75 smoothing bucket) and near-white (q = 1) on +/// a dark page; a mid blue (q = 0.25). +pub const PAIRS: [Pair; 4] = [ + Pair { name: "light", fg: "#1d1e22", bg: "#fcfcfb" }, + Pair { name: "dark", fg: "#e6e6e6", bg: "#1d1e22" }, + Pair { name: "white", fg: "#fcfcfb", bg: "#1d1e22" }, + Pair { name: "blue", fg: "#296d9a", bg: "#fcfcfb" }, +]; +pub const SCALES: [f32; 2] = [1.0, 2.0]; +/// Inter sizes, in points (device px at 1×). +pub const SIZES: [f32; 7] = [9.0, 11.0, 13.0, 16.0, 20.0, 24.0, 32.0]; +/// The smoothing study's glyphs (straight stems, diagonals, round tops and bottoms) and a word. +pub const SAMPLE: &str = "IHT\u{2014}/AVSog@8 Hamburgefonstiv"; +/// The paragraph of the Rune vs macOS text report: 16/26 pt, wrapped at 567 pt, at (49, 40) pt, +/// measured over the band 30–120 pt of a 640 pt canvas, as the report did. +/// SF Mono's glyphs: thin stems on a fixed grid (i, l, 1, t), wide ones (m), punctuation. +pub const MONO_SAMPLE: &str = "It doesn't look like it; illicit 1111 mmmm @@ -33,3 +33,4 @@"; +/// A diff, as the History drawer's view shows it, in a code block's 13.5/22 pt. +pub const MONO_PARAGRAPH: &str = "diff --git a/Welcome.md b/Welcome.md --- a/Welcome.md +++ b/Welcome.md @@ -33,3 +33,4 @@ $1 + 1$ It doesn't look like it +*Italics work though!* iiiiiiii llllllll mmmmmmmm"; +pub const PARAGRAPH: &str = "The quick brown fox jumps over the lazy dog. AV To Wa Ty Yo LT fi fl ffi office flour 0123456789 ($4.50, 87%) \u{2014} \"quoted\" & semicolons; colons: question? Incomprehensibilities and HYPERVENTILATION."; +pub const SHEET_WIDTH: f32 = 640.0; +const ROW_X: f32 = 16.0; +const PARAGRAPH_HEIGHT: f32 = 130.0; +/// The family Rune names the macOS system font by. +const SYSTEM_FONT: &str = "System Font"; + +/// Which font's cases. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Set { + /// Inter 4.1 Regular and Bold; references committed. + Inter, + /// San Francisco (the system font, SFNS) at its `opsz` for each size; references local. + Sf, + /// SF Mono (`Family::SystemMono`, SFNSMono) at inline-code and code-block sizes; references local. + Mono, +} + +/// Which CoreText rendering a sheet holds. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Reference { + /// Font smoothing on, macOS's default (compare `FontSmoothing::On`). + Smoothed, + /// Font smoothing off, as `-webkit-font-smoothing: antialiased` draws (compare `Off`). + Unsmoothed, +} + +impl Reference { + /// The reference a mode is meant to match. + pub fn for_mode(mode: FontSmoothing) -> Reference { + match mode { + FontSmoothing::On | FontSmoothing::Windfoil => Reference::Smoothed, + _ => Reference::Unsmoothed, + } + } + fn prefix(self) -> &'static str { + match self { Reference::Smoothed => "", Reference::Unsmoothed => "flat-" } + } + /// Unsmoothed sheets cover the light and dark pairs: without dilation, ink colour changes + /// only the blend. + pub fn pairs(self) -> &'static [Pair] { + match self { Reference::Smoothed => &PAIRS, Reference::Unsmoothed => &PAIRS[..2] } + } +} + +/// One case on a sheet; every length in points. +#[derive(Clone, Debug)] +pub struct Case { + pub name: String, + pub family: Family, + pub weight: f32, + pub size: f32, + pub line_height: f32, + pub wrap: Option<f32>, + pub text: &'static str, + pub origin: [f32; 2], + /// The region compared: `[x, y, w, h]`. Rows compare the ink bounds inside it (plus a pixel); + /// the paragraph compares all of it, so its numbers line up with the report's band. + pub region: [f32; 4], + pub whole_region: bool, +} + +impl Case { + /// The font the reference draws it with: "regular", "bold" or "system". + fn font(&self) -> &'static str { + match (self.family, self.weight >= 700.0) { + (Family::Named(SYSTEM_FONT), _) => "system", + (Family::SystemMono, _) => "mono", + (_, true) => "bold", + _ => "regular", + } + } +} + +/// The cases of `set`, top to bottom. +pub fn cases(set: Set) -> Vec<Case> { + let text = if set == Set::Mono { MONO_SAMPLE } else { SAMPLE }; + let (family, rows): (Family, Vec<(&str, f32, f32)>) = match set { + Set::Inter => { + let mut rows = Vec::new(); + for (weight, font) in [(400.0, "regular"), (700.0, "bold")] { + rows.extend(SIZES.iter().map(|&size| (font, weight, size))); + } + (Family::Sans, rows) + } + Set::Sf => (Family::Named(SYSTEM_FONT), vec![("sf regular", 400.0, 16.0), ("sf bold", 700.0, 16.0), ("sf bold", 700.0, 28.0), ("sf bold", 700.0, 32.0)]), + Set::Mono => (Family::SystemMono, [11.0, 12.0, 13.0, 13.5, 14.0, 16.0].iter().map(|&size| ("mono", 400.0, size)).collect()), + }; + let mut out = Vec::new(); + let mut y = 4.0f32; + for (font, weight, size) in rows { + let height = (size * 1.25).ceil() + 6.0; + out.push(Case { + name: format!("{font} {size}"), + family, + weight, + size, + line_height: 0.0, + wrap: None, + text, + origin: [ROW_X, y + 3.0], + region: [0.0, y, SHEET_WIDTH, height], + whole_region: false, + }); + y += height; + } + let top = y.ceil() + 4.0; + out.push(paragraph_case(family, top)); + out +} + +fn paragraph_case(family: Family, top: f32) -> Case { + if family == Family::SystemMono { + return Case { + name: "mono paragraph 13.5/22".into(), + family, + weight: 400.0, + size: 13.5, + line_height: 22.0, + wrap: Some(567.0), + text: MONO_PARAGRAPH, + origin: [49.0, top + 40.0], + region: [0.0, top + 30.0, SHEET_WIDTH, 90.0], + whole_region: true, + }; + } + Case { + name: if family == Family::Sans { "paragraph 16/26".into() } else { "sf paragraph 16/26".into() }, + family, + weight: 400.0, + size: 16.0, + line_height: 26.0, + wrap: Some(567.0), + text: PARAGRAPH, + origin: [49.0, top + 40.0], + region: [0.0, top + 30.0, SHEET_WIDTH, 90.0], + whole_region: true, + } +} + +pub fn sheet_height(set: Set) -> f32 { + let last = cases(set).pop().expect("cases"); + last.region[1] - 30.0 + PARAGRAPH_HEIGHT +} + +/// Where the committed references, the Bold subset and `layout.txt` live. +pub fn refs_dir() -> PathBuf { + Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/coretext") +} + +impl Set { + /// Where this set's sheets and `layout.txt` live. + pub fn dir(self) -> PathBuf { + match self { Set::Inter => refs_dir(), Set::Sf => refs_dir().join("sf"), Set::Mono => refs_dir().join("mono") } + } + pub fn name(self) -> &'static str { + match self { Set::Inter => "Inter", Set::Sf => "San Francisco", Set::Mono => "SF Mono" } + } +} + +/// The font files: Rune's own Inter Regular and an ASCII subset of Inter 4.1 Bold. +pub fn font_paths() -> [PathBuf; 2] { + let root = Path::new(env!("CARGO_MANIFEST_DIR")); + [root.join("assets/Inter-Regular.ttf"), refs_dir().join("Inter-Bold-subset.ttf")] +} + +/// The system font file Rune loads for "System Font", when this machine has one. +pub fn system_font_path() -> Option<PathBuf> { + if !cfg!(target_os = "macos") { return None; } + crate::text::fonts::system_fonts::system_font_files(&["sfnsttf"]).into_iter().next() +} + +/// The SF Mono file `Family::SystemMono` loads, when this machine has one. +pub fn system_mono_path() -> Option<PathBuf> { + if !cfg!(target_os = "macos") { return None; } + crate::text::fonts::system_fonts::system_font_files(&["sfnsmono"]).into_iter().find(|p| !p.to_string_lossy().to_lowercase().contains("italic")) +} + +fn text_system() -> Result<TextSystem, String> { + let mut fonts: Vec<&'static [u8]> = Vec::new(); + for path in font_paths() { + let bytes = std::fs::read(&path).map_err(|e| format!("{}: {e}", path.display()))?; + fonts.push(Box::leak(bytes.into_boxed_slice())); + } + Ok(TextSystem::new(&fonts, ("Inter", "Inter"))) +} + +fn style(case: &Case) -> TextStyle { + TextStyle { line_height: case.line_height, ..TextStyle::new(case.size, case.weight).family(case.family) } +} + +/// Each case's glyphs as `(id, x, baseline)` in device px: the pen x before any quantisation +/// and the whole-pixel baseline, as `TextSystem::glyphs_for_layout` computes them. +fn positions(text: &mut TextSystem, case: &Case, scale: f32) -> Vec<(u32, f32, f32)> { + let layout = text.layout_rich(case.text, &[], style(case), scale, case.wrap.map(|w| w * scale)); + let origin = case.origin.map(|v| v * scale); + let mut out = Vec::new(); + for line in layout.lines() { + for item in line.items() { + let PositionedLayoutItem::GlyphRun(run) = item else { continue }; + let baseline = (origin[1] + run.baseline()).round(); + let mut rel = run.offset(); + for g in run.glyphs() { + out.push((g.id, origin[0] + rel + g.x, baseline + g.y)); + rel += g.advance; + } + } + } + out +} + +/// Whether `set` can be compared here: its font and its sheets exist. +pub fn available(set: Set) -> Result<(), String> { + if set == Set::Sf && system_font_path().is_none() { + return Err("no system font (SFNS) on this machine".into()); + } + if set == Set::Mono && system_mono_path().is_none() { + return Err("no SF Mono (SFNSMono) on this machine".into()); + } + let have = std::fs::read_to_string(set.dir().join("layout.txt")).map_err(|_| { + format!("no {} references in {}: run scripts/coretext-reference.sh", set.name(), set.dir().display()) + })?; + let want = layout_file(set)?; + if have != want { + return Err(format!("{} references are stale (layout.txt {have:?}, now {want:?}): run scripts/coretext-reference.sh", set.name())); + } + Ok(()) +} + +/// The layout the CoreText references are drawn from, for `scripts/coretext-reference.swift`. +pub fn export(set: Set, scale: f32) -> Result<serde_json::Value, String> { + let mut text = text_system()?; + let [regular, bold] = font_paths().map(|p| p.display().to_string()); + let system = system_font_path().map(|p| p.display().to_string()); + let mono = system_mono_path().map(|p| p.display().to_string()); + if set == Set::Sf && system.is_none() { + return Err("no system font (SFNS) on this machine".into()); + } + if set == Set::Mono && mono.is_none() { + return Err("no SF Mono (SFNSMono) on this machine".into()); + } + let mut rows = Vec::new(); + for case in cases(set) { + let glyphs: Vec<_> = positions(&mut text, &case, scale).into_iter().map(|(id, x, y)| serde_json::json!([id, x, y])).collect(); + rows.push(serde_json::json!({ + "name": case.name, "font": case.font(), "size": case.size, "weight": case.weight, "opsz": case.size, "glyphs": glyphs, + })); + } + let sheets: Vec<_> = [Reference::Smoothed, Reference::Unsmoothed] + .iter() + .flat_map(|r| r.pairs().iter().map(move |p| serde_json::json!({ + "file": format!("{}{}-{scale}x.png", r.prefix(), p.name), "smooth": *r == Reference::Smoothed, "fg": p.fg, "bg": p.bg, + }))) + .collect(); + Ok(serde_json::json!({ + "scale": scale, + "width": (SHEET_WIDTH * scale) as u32, + "height": (sheet_height(set) * scale) as u32, + "fonts": { "regular": regular, "bold": bold, "system": system, "mono": mono }, + "sheets": sheets, + "cases": rows, + })) +} + +/// A digest of every case's glyph ids and positions at `scale`. The references are stale when +/// it differs from the one in `layout.txt`. +pub fn layout_digest(set: Set, scale: f32) -> Result<String, String> { + let mut text = text_system()?; + let mut h = blake3::Hasher::new(); + for case in cases(set) { + for (id, x, y) in positions(&mut text, &case, scale) { + h.update(&id.to_le_bytes()); + h.update(&x.to_le_bytes()); + h.update(&y.to_le_bytes()); + } + } + Ok(h.finalize().to_hex()[..16].to_string()) +} + +/// `layout.txt`'s contents for the current layout of `set`. +pub fn layout_file(set: Set) -> Result<String, String> { + let mut out = String::new(); + for scale in SCALES { + writeln!(out, "{scale}x {}", layout_digest(set, scale)?).ok(); + } + Ok(out) +} + +/// An opaque RGB image. +pub struct Image { + pub width: u32, + pub height: u32, + pub rgb: Vec<u8>, +} + +impl Image { + fn px(&self, x: u32, y: u32) -> [u8; 3] { + let i = ((y * self.width + x) * 3) as usize; + [self.rgb[i], self.rgb[i + 1], self.rgb[i + 2]] + } + + fn green(&self, x: i64, y: i64) -> Option<u8> { + (x >= 0 && y >= 0 && x < self.width as i64 && y < self.height as i64).then(|| self.px(x as u32, y as u32)[1]) + } + + pub fn read_png(path: &Path) -> Result<Image, String> { + let file = std::fs::File::open(path).map_err(|e| format!("{}: {e}", path.display()))?; + let mut decoder = png::Decoder::new(std::io::BufReader::new(file)); + decoder.set_transformations(png::Transformations::EXPAND | png::Transformations::STRIP_16); + let mut reader = decoder.read_info().map_err(|e| e.to_string())?; + let mut buf = vec![0; reader.output_buffer_size().ok_or("png too large")?]; + let info = reader.next_frame(&mut buf).map_err(|e| e.to_string())?; + let channels = info.color_type.samples(); + let rgb = buf[..info.buffer_size()] + .chunks_exact(channels) + .flat_map(|p| if channels >= 3 { [p[0], p[1], p[2]] } else { [p[0]; 3] }) + .collect(); + Ok(Image { width: info.width, height: info.height, rgb }) + } + + pub fn write_png(&self, path: &Path) -> std::io::Result<()> { + let rgba: Vec<u8> = self.rgb.chunks_exact(3).flat_map(|p| [p[0], p[1], p[2], 255]).collect(); + crate::render::write_png(path, self.width, self.height, &rgba) + } + + /// The green channel as a greyscale PNG, compressed hard: how the reference sheets are kept. + pub fn write_green_png(&self, path: &Path) -> Result<(), String> { + let file = std::fs::File::create(path).map_err(|e| format!("{}: {e}", path.display()))?; + let mut enc = png::Encoder::new(std::io::BufWriter::new(file), self.width, self.height); + enc.set_color(png::ColorType::Grayscale); + enc.set_depth(png::BitDepth::Eight); + enc.set_compression(png::Compression::High); + enc.set_filter(png::Filter::Adaptive); + let green: Vec<u8> = self.rgb.chunks_exact(3).map(|p| p[1]).collect(); + enc.write_header().and_then(|mut w| w.write_image_data(&green)).map_err(|e| e.to_string()) + } +} + +/// Draws sheets of cases through the glyph instances the runtime builds, blended as a window +/// with `srgb_blend` blends. +pub struct Harness { + gpu: Gpu, + text: TextSystem, + /// One renderer, since it holds the atlas pages uploaded so far. + renderer: Option<Renderer>, +} + +impl Harness { + pub fn new() -> Result<Harness, String> { + Ok(Harness { gpu: Gpu::try_new(Gpu::instance(), None)?, text: text_system()?, renderer: None }) + } + + /// `cases` in `pair`'s colours on a `size` (points) canvas at `scale`. + pub fn render(&mut self, pair: Pair, scale: f32, srgb_blend: bool, smoothing: FontSmoothing, cases: &[Case], size: [f32; 2]) -> Image { + self.text.set_font_smoothing(smoothing); + let (fg, bg) = (hex(pair.fg).expect("fg"), hex(pair.bg).expect("bg")); + let (w, h) = ((size[0] * scale) as u32, (size[1] * scale) as u32); + let mut quads: Vec<GlyphQuad> = Vec::new(); + self.text.set_glyph_inks(fg, &[]); + for case in cases { + let layout = self.text.layout_rich(case.text, &[], style(case), scale, case.wrap.map(|w| w * scale)); + self.text.glyphs_for_layout(&layout, scale, case.origin.map(|v| v * scale), false, &mut quads); + } + let fill = crate::runtime::premul(fg, 1.0, srgb_blend); + // The coverage exponent a window's paint applies, so the sheets are what an app draws. + let exponent = self.text.coverage_exponent(fill); + let instances: Vec<_> = quads.iter().map(|q| { let mut g = crate::runtime::glyph(q, fill, NO_CLIP, [0.0; 4]); g.params[3] = exponent; g }).collect(); + let format = if srgb_blend { OFFSCREEN_FORMAT.remove_srgb_suffix() } else { OFFSCREEN_FORMAT }; + let renderer = self.renderer.get_or_insert_with(|| Renderer::new(&self.gpu.device, format)); + renderer.set_format(&self.gpu.device, format); + renderer.set_srgb_blend(srgb_blend); + let target = Offscreen::with_format(&self.gpu.device, w, h, format); + renderer.prepare(&self.gpu.device, &self.gpu.queue, &mut self.text.atlas, &instances, (w, h)); + let clear = if srgb_blend { [srgb_encode(bg.r), srgb_encode(bg.g), srgb_encode(bg.b), 1.0] } else { [bg.r, bg.g, bg.b, 1.0] }; + let mut encoder = self.gpu.device.create_command_encoder(&Default::default()); + renderer.draw(&mut encoder, &target.view, clear); + target.copy(&mut encoder); + renderer.submit(&self.gpu.queue, encoder); + let rgba = target.read(&self.gpu.device); + Image { width: w, height: h, rgb: rgba.chunks_exact(4).flat_map(|p| [p[0], p[1], p[2]]).collect() } + } +} + +/// Differences in the green channel over a region (the references keep only green), on 0–255. +/// "Ink" is the summed distance from the page, so it works for light on dark too. +#[derive(Clone, Copy, Debug, Default)] +pub struct Stats { + pub pixels: u64, + pub differing: u64, + pub over8: u64, + pub max: u8, + pub abs_sum: f64, + pub ink_rune: f64, + pub ink_ref: f64, +} + +impl Stats { + pub fn add(&mut self, o: &Stats) { + self.pixels += o.pixels; + self.differing += o.differing; + self.over8 += o.over8; + self.max = self.max.max(o.max); + self.abs_sum += o.abs_sum; + self.ink_rune += o.ink_rune; + self.ink_ref += o.ink_ref; + } + /// Mean |difference|. + pub fn meanabs(&self) -> f64 { self.abs_sum / self.pixels.max(1) as f64 } + /// Rune's ink over CoreText's. + pub fn ink_ratio(&self) -> f64 { self.ink_rune / self.ink_ref.max(1.0) } + pub fn differing_share(&self) -> f64 { self.differing as f64 / self.pixels.max(1) as f64 } + /// Share of pixels off by more than 8. + pub fn over8_share(&self) -> f64 { self.over8 as f64 / self.pixels.max(1) as f64 } +} + +/// Stats over `[x0, y0, x1, y1)` (px of `reference`), with Rune's image read `shift` px away. +fn stats_in(rune: &Image, reference: &Image, [x0, y0, x1, y1]: [u32; 4], shift: [i64; 2]) -> Stats { + let (paper_rune, paper_ref) = (rune.px(0, 0)[1], reference.px(0, 0)[1]); + let mut s = Stats::default(); + for y in y0..y1 { + for x in x0..x1 { + let a = rune.green(x as i64 - shift[0], y as i64 - shift[1]).unwrap_or(paper_rune); + let b = reference.px(x, y)[1]; + let d = a.abs_diff(b); + s.pixels += 1; + s.differing += (d > 0) as u64; + s.over8 += (d > 8) as u64; + s.max = s.max.max(d); + s.abs_sum += d as f64; + s.ink_rune += a.abs_diff(paper_rune) as f64; + s.ink_ref += b.abs_diff(paper_ref) as f64; + } + } + s +} + +/// The ink bounds of either image inside `[x0, y0, x1, y1)`, grown by a pixel. +fn ink_bounds(images: [&Image; 2], [x0, y0, x1, y1]: [u32; 4]) -> Option<[u32; 4]> { + let (mut lo, mut hi) = ((u32::MAX, u32::MAX), (0, 0)); + for image in images { + let paper = image.px(0, 0)[1]; + for y in y0..y1.min(image.height) { + for x in x0..x1.min(image.width) { + if image.px(x, y)[1] != paper { + lo = (lo.0.min(x), lo.1.min(y)); + hi = (hi.0.max(x + 1), hi.1.max(y + 1)); + } + } + } + } + (hi.0 > 0).then(|| [lo.0.saturating_sub(1).max(x0), lo.1.saturating_sub(1).max(y0), (hi.0 + 1).min(x1), (hi.1 + 1).min(y1)]) +} + +/// Compares `case`'s region of two sheets of the same size. +pub fn compare(rune: &Image, reference: &Image, case: &Case, scale: f32) -> Stats { + let [x, y, w, h] = case.region.map(|v| (v * scale).round() as u32); + let region = [x, y, (x + w).min(rune.width), (y + h).min(rune.height)]; + let rect = if case.whole_region { Some(region) } else { ink_bounds([rune, reference], region) }; + rect.map_or_else(Stats::default, |r| stats_in(rune, reference, r, [0, 0])) +} + +pub fn reference_path(set: Set, reference: Reference, pair: Pair, scale: f32) -> PathBuf { + set.dir().join(format!("{}{}-{scale}x.png", reference.prefix(), pair.name)) +} + +/// One table row. +pub struct Row { + pub pair: Pair, + pub scale: f32, + pub case: Case, + pub stats: Stats, +} + +/// What [`run`] draws and what it compares with. +#[derive(Clone, Copy, Debug)] +pub struct Options { + pub set: Set, + /// None: the platform's default. + pub smoothing: Option<FontSmoothing>, + /// None: as a window blends by default (sRGB). + pub srgb_blend: Option<bool>, + /// None: the reference the mode is meant to match. + pub reference: Option<Reference>, +} + +impl Options { + pub fn new(set: Set) -> Options { + Options { set, smoothing: None, srgb_blend: None, reference: None } + } + pub fn smoothing(&self) -> FontSmoothing { self.smoothing.unwrap_or_default() } + pub fn srgb_blend(&self) -> bool { self.srgb_blend.unwrap_or(true) } + pub fn reference(&self) -> Reference { self.reference.unwrap_or(Reference::for_mode(self.smoothing())) } +} + +/// Every case of every pair at every scale. Errs when the set can't be compared here +/// ([`available`]). +pub fn run(o: Options, mut keep: impl FnMut(Pair, f32, &Image, &Image)) -> Result<Vec<Row>, String> { + available(o.set)?; + let cases = cases(o.set); + let mut harness = Harness::new()?; + let mut rows = Vec::new(); + for scale in SCALES { + for &pair in o.reference().pairs() { + let reference = Image::read_png(&reference_path(o.set, o.reference(), pair, scale))?; + let rune = harness.render(pair, scale, o.srgb_blend(), o.smoothing(), &cases, [SHEET_WIDTH, sheet_height(o.set)]); + if (rune.width, rune.height) != (reference.width, reference.height) { + return Err(format!("{} {scale}x: reference is {}x{}, Rune {}x{}", pair.name, reference.width, reference.height, rune.width, rune.height)); + } + keep(pair, scale, &rune, &reference); + for case in &cases { + let stats = compare(&rune, &reference, case, scale); + rows.push(Row { pair, scale, case: case.clone(), stats }); + } + } + } + Ok(rows) +} + +fn line(out: &mut String, label: &str, s: &Stats) { + writeln!( + out, + "{label:<28} {:>7.2}% {:>7.2}% {:>4} {:>8.3} {:>7.3}", + 100.0 * s.differing_share(), + 100.0 * s.over8_share(), + s.max, + s.meanabs(), + s.ink_ratio() + ).ok(); +} + +/// The paragraph's stats for `pair` at `scale`, the report's headline numbers. +pub fn paragraph(rows: &[Row], pair: &str, scale: f32) -> Option<Stats> { + rows.iter().find(|r| r.pair.name == pair && r.scale == scale && r.case.whole_region).map(|r| r.stats) +} + +/// All rows of `pair` at `scale` but the paragraph, pooled by pixel. +pub fn pooled(rows: &[Row], pair: &str, scale: f32) -> Stats { + let mut s = Stats::default(); + for r in rows.iter().filter(|r| r.pair.name == pair && r.scale == scale && !r.case.whole_region) { + s.add(&r.stats); + } + s +} + +const HEAD: &str = "case differ >8 max meanabs ink\n"; + +/// The full table, then a summary per pair and scale. +pub fn table(o: &Options, rows: &[Row]) -> String { + let mut out = String::new(); + let against = match o.reference() { Reference::Smoothed => "smoothing on", Reference::Unsmoothed => "smoothing off" }; + writeln!(out, "{}: Rune {:?} ({} blending) vs CoreText with {against}", o.set.name(), o.smoothing(), if o.srgb_blend() { "sRGB" } else { "linear" }).ok(); + for scale in SCALES { + for pair in o.reference().pairs() { + writeln!(out, "\n{} ({} on {}), {scale}x", pair.name, pair.fg, pair.bg).ok(); + out += HEAD; + for r in rows.iter().filter(|r| r.pair.name == pair.name && r.scale == scale) { + line(&mut out, &r.case.name, &r.stats); + } + } + } + writeln!(out, "\nsummary: paragraph (report band) and all sample rows pooled").ok(); + out += HEAD; + for scale in SCALES.iter().rev() { + for pair in o.reference().pairs() { + if let Some(p) = paragraph(rows, pair.name, *scale) { + line(&mut out, &format!("{} {scale}x paragraph", pair.name), &p); + } + line(&mut out, &format!("{} {scale}x rows", pair.name), &pooled(rows, pair.name, *scale)); + } + } + out +} + +/// Rune's Inter paragraph against a 2× browser screenshot of the same page (text at x = 49 pt, +/// Inter 16/26, wrapped at 567 pt). CSS places the line box differently from Rune, so Rune's +/// render is moved by the whole-pixel offset (within ±120 px down, ±4 px across) that minimises +/// the mean difference over the shot's ink bounds; returns that offset and the stats there. +pub fn compare_shot(shot: &Image, pair: Pair, smoothing: FontSmoothing, srgb_blend: bool) -> Result<([i64; 2], Stats), String> { + let scale = 2.0; + let mut harness = Harness::new()?; + let case = paragraph_case(Family::Sans, 0.0); + let rune = harness.render(pair, scale, srgb_blend, smoothing, &[case], [shot.width as f32 / scale, shot.height as f32 / scale]); + let all = [0, 0, shot.width, shot.height]; + let bounds = ink_bounds([shot, shot], all).ok_or("no ink in the screenshot")?; + let band = [0, bounds[1], shot.width, bounds[3]]; + let mut best: Option<([i64; 2], Stats)> = None; + for dy in -120..=120 { + for dx in -4..=4 { + let s = stats_in(&rune, shot, band, [dx, dy]); + if best.as_ref().is_none_or(|b| s.meanabs() < b.1.meanabs()) { + best = Some(([dx, dy], s)); + } + } + } + best.ok_or_else(|| "nothing compared".into()) +} + +/// Heatmap of `rune` against `reference`: grey where equal, red where Rune has less ink, blue +/// where it has more (differences amplified four times). +pub fn heatmap(rune: &Image, reference: &Image) -> Image { + let (paper_rune, paper_ref) = (rune.px(0, 0)[1] as i32, reference.px(0, 0)[1] as i32); + let mut rgb = Vec::with_capacity(rune.rgb.len()); + for (a, b) in rune.rgb.chunks_exact(3).zip(reference.rgb.chunks_exact(3)) { + let (ia, ib) = ((a[1] as i32 - paper_rune).abs(), (b[1] as i32 - paper_ref).abs()); + let k = ((ib - ia).abs() * 4).min(255) as u8; + rgb.extend_from_slice(&if a[1] == b[1] { + let g = (252 - ia / 4) as u8; + [g, g, g] + } else if ib > ia { + [255, 255 - k, 255 - k] + } else { + [255 - k, 255 - k, 255] + }); + } + Image { width: rune.width, height: rune.height, rgb } +} + +#[cfg(all(test, target_os = "macos"))] +#[path = "pixel_compare_tests.rs"] +mod tests; diff --git a/app/vendor/rune/crates/rune/src/text/pixel_compare_tests.rs b/app/vendor/rune/crates/rune/src/text/pixel_compare_tests.rs new file mode 100644 index 0000000..86df699 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/text/pixel_compare_tests.rs @@ -0,0 +1,35 @@ +use super::*; + +/// Loose bounds for now: they catch a broken pipeline (missing glyphs, wrong blend, shifted +/// rows), not the remaining distance to CoreText. Tighten as the text path converges. +fn check(o: Options, ink: std::ops::RangeInclusive<f64>) { + let rows = match run(o, |_, _, _, _| {}) { + Ok(rows) => rows, + Err(e) if o.set == Set::Sf || e.contains("adapter") || e.contains("GPU") => return eprintln!("skipped: {e}"), + Err(e) => panic!("{e}"), + }; + eprintln!("{}", table(&o, &rows)); + for r in &rows { + let s = &r.stats; + let what = format!("{} {}x {}", r.pair.name, r.scale, r.case.name); + assert!(s.pixels > 0, "{what}: no ink in either image"); + assert!(ink.contains(&s.ink_ratio()), "{what}: ink ratio {:.3}", s.ink_ratio()); + let (over8, meanabs) = if r.case.whole_region { (0.2, 8.0) } else { (0.45, 25.0) }; + assert!(s.over8_share() < over8, "{what}: {:.1}% of pixels off by more than 8", 100.0 * s.over8_share()); + assert!(s.meanabs() < meanabs, "{what}: meanabs {:.2}", s.meanabs()); + } +} + +#[test] +fn macos_smoothing_stays_near_smoothed_coretext() { + for set in [Set::Inter, Set::Sf] { + check(Options { smoothing: Some(FontSmoothing::On), ..Options::new(set) }, 0.75..=1.25); + } +} + +#[test] +fn smoothing_off_stays_near_unsmoothed_coretext() { + for set in [Set::Inter, Set::Sf] { + check(Options { smoothing: Some(FontSmoothing::Off), ..Options::new(set) }, 0.9..=1.1); + } +} diff --git a/app/vendor/rune/crates/rune/src/text/runtime_tests.rs b/app/vendor/rune/crates/rune/src/text/runtime_tests.rs new file mode 100644 index 0000000..96b5321 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/text/runtime_tests.rs @@ -0,0 +1,368 @@ +//! Text integration tests that exercise `Runtime`, `El`, and the GPU renderer alongside `rune-text`. + +use crate::color::Color; +use crate::text::{FontSmoothing, Run, Span}; +use crate::tok::TextStyle; + +#[test] +fn advance_in_off_grapheme_draws_as_plain_text() { + use crate::{Cx, El, Env, Runtime}; + fn view(_: &(), _: &mut Cx<()>) -> El { + crate::el::row() + .child(crate::el::text("y").advance_in(&Run::new("x\u{301}y"), 2)) + .child(crate::el::text("y").advance_in(&Run::new("y"), 99)) + } + let mut rt = Runtime::new((), view, (200.0, 100.0), Env::new(true, 2.0)); + rt.frame(0.0); + assert_eq!(rt.instances.iter().filter(|i| i.params[1] == crate::render::KIND_GLYPH).count(), 2); +} + +/// A window narrowing re-breaks its wrapped texts without shaping them, and draws what a +/// window opened at that width draws. +#[test] +fn resizing_a_window_rebreaks_wrapped_text_and_draws_as_a_fresh_one() { + use crate::{Cx, El, Env, Runtime, col}; + fn view(_: &(), _: &mut Cx<()>) -> El { + let para = "Paragraph text long enough to wrap over several lines as the window narrows, with words of varied length."; + col().w_full().padding(12.0).gap(8.0).children((0..6).map(|i| { + let t = crate::el::text(format!("{i}. {para}")).w_full().wrap(); + if i % 2 == 0 { t.align(crate::Align::Center) } else { t } + })) + } + let glyphs = |rt: &Runtime<()>| { + rt.instances.iter().filter(|i| i.params[1] == crate::render::KIND_GLYPH).map(|i| i.rect.map(f32::to_bits)).collect::<Vec<_>>() + }; + let mut rt = Runtime::new((), view, (700.0, 900.0), Env::new(true, 2.0)); + rt.frame(0.0); + for w in [640.0, 517.5, 380.0, 700.0, 233.0] { + rt.set_viewport((w, 900.0), 2.0); + rt.frame(1.0 / 120.0); + assert_eq!(rt.stats.shaped, 0, "at {w}"); + let mut fresh = Runtime::new((), view, (w, 900.0), Env::new(true, 2.0)); + fresh.frame(0.0); + assert_eq!(glyphs(&rt), glyphs(&fresh), "at {w}"); + } +} + +/// `Tx::set_font_smoothing` switches a running window: the next frame rasterises the new +/// mode's glyphs and draws them; asking for the current mode asks for no frame. +#[test] +fn a_handler_switches_font_smoothing_at_run_time() { + use crate::{Cx, El, Env, Runtime}; + fn view(_: &(), _: &mut Cx<()>) -> El { crate::el::text("Hamburgefonstiv").size(13.0, 400.0) } + let mut rt = Runtime::new((), view, (300.0, 100.0), Env::new(false, 2.0)); + rt.set_font_smoothing(FontSmoothing::On); + rt.frame(0.0); + let glyphs = |rt: &Runtime<()>| rt.instances.iter().filter(|i| i.params[1] == crate::render::KIND_GLYPH).map(|i| (i.rect, i.uv)).collect::<Vec<_>>(); + let before = (glyphs(&rt), rt.text.atlas.rasterized()); + assert!(!rt.update_if(|_, tx| { tx.set_font_smoothing(FontSmoothing::On); false }), "the current mode asks for no frame"); + assert!(rt.update_if(|_, tx| { tx.set_font_smoothing(FontSmoothing::Off); false }), "a new mode asks for a frame"); + rt.frame(1.0 / 60.0); + assert_eq!(rt.font_smoothing(), FontSmoothing::Off); + assert_eq!(rt.text.apple_pipeline(), crate::text::ApplePipeline::UNSMOOTHED); + assert!(rt.text.atlas.rasterized() > before.1, "Off rasterises its own glyphs"); + assert_ne!(glyphs(&rt), before.0, "and draws them"); + let srgb = rt.srgb_blend(); + assert!(rt.update_if(|_, tx| { tx.set_font_smoothing(FontSmoothing::On); false })); + assert_eq!(rt.srgb_blend(), srgb, "blending is separate from the mode"); +} + +/// Glyph extents per drawn line, in device pixels, for one text element 300 pt wide at 2×. +fn line_spans(content: &str, align: crate::Align, justify: bool) -> Vec<(f32, f32)> { + use crate::{Cx, El, Env, Runtime}; + type S = (String, crate::Align, bool); + fn view(s: &S, _: &mut Cx<S>) -> El { + let t = crate::el::text(s.0.clone()).w(300.0).wrap().align(s.1); + if s.2 { t.justify() } else { t } + } + let mut rt = Runtime::new((content.to_string(), align, justify), view, (300.0, 400.0), Env::new(true, 2.0)); + rt.frame(0.0); + let mut quads: Vec<[f32; 4]> = + rt.instances.iter().filter(|i| i.params[1] == crate::render::KIND_GLYPH).map(|i| i.rect).collect(); + quads.sort_by(|a, b| (a[1] + a[3] / 2.0).total_cmp(&(b[1] + b[3] / 2.0))); + let mut lines: Vec<(f32, f32, f32)> = Vec::new(); + for q in quads { + let cy = q[1] + q[3] / 2.0; + match lines.last_mut() { + Some(l) if cy - l.0 < 16.0 => { l.1 = l.1.min(q[0]); l.2 = l.2.max(q[0] + q[2]); } + _ => lines.push((cy, q[0], q[0] + q[2])), + } + } + lines.into_iter().map(|(_, l, r)| (l, r)).collect() +} + +#[test] +fn justified_text_fills_each_wrapped_line_but_the_last() { + use crate::Align; + let content = "the quick brown fox jumps over the lazy dog while five boxing wizards jump quickly and pack my box with five dozen liquor jugs"; + let justified = line_spans(content, Align::Start, true); + assert!(justified.len() >= 3, "{justified:?}"); + for &(l, r) in &justified[..justified.len() - 1] { + assert!(l < 8.0 && r > 592.0, "justified line spans {l}..{r}"); + } + let start = line_spans(content, Align::Start, false); + assert_eq!(start.len(), justified.len(), "justifying never rewraps"); + assert!(start[..start.len() - 1].iter().any(|&(_, r)| r < 592.0), "start lines stay ragged: {start:?}"); +} + +#[test] +fn wrapped_right_to_left_text_aligns_and_justifies_from_the_right() { + use crate::Align; + let hebrew = "שלום עולם זהו טקסט ארוך שנשבר לכמה שורות כדי לבדוק יישור מימין לשמאל בתוך רוחב קבוע של האלמנט"; + let start = line_spans(hebrew, Align::Start, false); + if start.is_empty() { + eprintln!("skipping: no Hebrew glyphs"); + return; + } + assert!(start.len() >= 2, "{start:?}"); + assert!(start.iter().all(|&(_, r)| r > 592.0), "wrapped RTL start hugs the right edge: {start:?}"); + let end = line_spans(hebrew, Align::End, false); + assert!(end.iter().all(|&(l, _)| l < 8.0), "wrapped RTL end hugs the left edge: {end:?}"); + let justified = line_spans(hebrew, Align::Start, true); + let last = justified.len() - 1; + assert!(justified[..last].iter().all(|&(l, r)| l < 8.0 && r > 592.0), "{justified:?}"); + assert!(justified[last].1 > 592.0, "justified RTL last line starts at the right: {justified:?}"); +} + +#[test] +fn span_ring_subranges_case_elision_and_cache_changes() { + use crate::{Cx, El, Env, Link, LinkPaint, Runtime, TextCase, col, rich}; + use crate::render::KIND_RECT; + + fn view(color: &Color, _: &mut Cx<Color>) -> El { + col().child(rich("aa Straße zz", vec![Span::new(0, 13).bg(Color::WHITE, 3.0)]) + .span_ring(3, 10, *color, 1.0).text_case(TextCase::Uppercase) + .link(Link::new(0..13, "whole").hover(LinkPaint::new().bg(Color::BLACK))) + .on_link(|_: &mut Color, _, _| {})) + } + let mut rt = Runtime::new(Color::BLACK, view, (300.0, 80.0), Env::new(false, 1.0)); + rt.frame(0.0); + let ring = *rt.instances.iter().find(|i| i.params[1] == KIND_RECT && i.params[0] == 1.0).unwrap(); + let rects: Vec<_> = rt.instances.iter().filter(|i| i.params[1] == KIND_RECT).collect(); + assert_eq!(rects.len(), 3, "ring boundaries split one background into three pieces"); + assert!(ring.rect[0] > rects[0].rect[0] && ring.rect[2] < rects.iter().map(|i| i.rect[2]).sum()); + let bounds = rt.elements().into_iter().find(|e| e.key.as_deref() == Some("whole")).unwrap().rect; + rt.pointer_move(bounds[0] + 2.0, bounds[1] + 2.0); + rt.frame(0.01); + let hovered: Vec<_> = rt.instances.iter().filter(|i| i.params[1] == KIND_RECT).collect(); + assert_eq!(hovered.len(), 3, "hover recolors split backgrounds in place"); + assert_eq!(hovered.iter().filter(|i| i.params[0] == 1.0).count(), 1, "hover does not extend the ring outside its range"); + assert_eq!(hovered.iter().find(|i| i.params[0] == 1.0).unwrap().rect, ring.rect); + assert!(hovered.iter().all(|i| i.fill == Color::BLACK.premul(1.0))); + rt.pointer_move(299.0, 79.0); + rt.state = Color::WHITE; + rt.invalidate(); + rt.settle_all(); + rt.frame(0.0); + let changed = rt.instances.iter().find(|i| i.params[1] == KIND_RECT && i.params[0] == 1.0).unwrap(); + assert_eq!(changed.border, Color::WHITE.premul(1.0), "ring color invalidates cached paint"); + assert_eq!(changed.rect, ring.rect); + + let mut cased = rich("İ xy", vec![Span::new(0, 5).bg(Color::WHITE, 2.0)]) + .span_ring(3, 5, Color::BLACK, 1.0).text_case(TextCase::Lowercase).text.unwrap(); + cased.apply_case(); + assert_eq!(cased.content, "i\u{307} xy"); + assert_eq!((cased.cold.rings[0].0, cased.cold.rings[0].1), (4, 6)); + assert_eq!((cased.spans[1].start, cased.spans[1].end), (4, 6)); + + fn truncated(_: &(), _: &mut Cx<()>) -> El { + col().w(60.0).child(rich("prefix middle suffix", vec![Span::new(14, 20).bg(Color::WHITE, 2.0)]) + .w(60.0).truncate_head().span_ring(14, 20, Color::BLACK, 1.0)) + } + let mut cut = Runtime::new((), truncated, (60.0, 40.0), Env::new(false, 1.0)); + cut.frame(0.0); + let rings: Vec<_> = cut.instances.iter().filter(|i| i.params[1] == KIND_RECT && i.params[0] == 1.0).collect(); + assert_eq!(rings.len(), 1, "head truncation remaps the suffix ring"); + assert!(rings[0].rect[0] >= 0.0 && rings[0].rect[2] <= 64.0); +} + +#[test] +fn span_ring_without_background_is_empty_and_reveal_fades_the_chip() { + use crate::{Cx, El, Env, Runtime, col, rich, text}; + use crate::render::KIND_RECT; + fn plain(_: &(), _: &mut Cx<()>) -> El { text("plain").span_ring(0, 5, Color::BLACK, 1.0) } + let mut plain = Runtime::new((), plain, (100.0, 40.0), Env::new(false, 1.0)); + plain.frame(0.0); + assert!(!plain.instances.iter().any(|i| i.params[1] == KIND_RECT && i.params[0] > 0.0)); + + fn view(s: &String, _: &mut Cx<String>) -> El { + col().key("root").streaming(true).child(rich(s, vec![Span::new(0, s.len()).bg(Color::WHITE, 3.0)]) + .key("body").span_ring(0, s.len(), Color::BLACK, 1.0).reveal(0.2)) + } + let mut rt = Runtime::new("one".to_string(), view, (300.0, 80.0), Env::new(false, 1.0)); + rt.frame(0.0); + rt.state.push_str(" two"); + rt.invalidate(); + rt.frame(0.01); + let initial = rt.instances.iter().find(|i| i.params[1] == KIND_RECT && i.params[0] == 1.0).unwrap().border[3]; + assert!(initial < 0.2, "new chip is not opaque before its final word: {initial}"); + rt.frame(0.11); + let middle = rt.instances.iter().find(|i| i.params[1] == KIND_RECT && i.params[0] == 1.0).unwrap(); + assert!(middle.border[3] > initial && middle.border[3] < 1.0); + assert_eq!(middle.border[3], middle.fill[3]); + rt.frame(1.0); + assert_eq!(rt.instances.iter().find(|i| i.params[1] == KIND_RECT && i.params[0] == 1.0).unwrap().border[3], 1.0); +} + +#[test] +fn span_ring_draws_inset_border_on_light_page_merges_runs_wraps_and_stays_on_hover() { + use crate::render::{Gpu, KIND_RECT, OFFSCREEN_FORMAT, Offscreen, Renderer}; + use crate::{Cx, El, Env, Link, LinkPaint, Runtime, col, rich}; + + const PAGE: Color = Color { r: 0.96, g: 0.96, b: 0.97, a: 1.0 }; + const FILL: Color = Color { r: 0.95, g: 0.95, b: 0.96, a: 1.0 }; + const HOVER: Color = Color { r: 0.88, g: 0.90, b: 0.96, a: 1.0 }; + const RING: Color = Color { r: 0.12, g: 0.38, b: 0.88, a: 1.0 }; + + fn view(alpha: &f32, _: &mut Cx<f32>) -> El { + let content = " Try bold code now"; + let (a, b) = (1, content.find(" now").unwrap()); + let bold_a = content.find("bold").unwrap(); + let code_a = content.find("code").unwrap(); + let spans = vec![ + Span::new(a, b).bg(FILL, 6.0), + Span::new(bold_a, bold_a + 4).bold(), + Span::new(code_a, code_a + 4).mono(), + ]; + col() + .size(200.0, 44.0) + .fill(PAGE) + .padding(8.0) + .child( + rich(content, spans) + .font(TextStyle::new(14.0, 400.0)) + .color(Color::BLACK) + .opacity(*alpha) + .span_ring(a, b, RING, 1.0) + .link(Link::new(a..b, "chip").hover(LinkPaint::new().bg(HOVER))) + .on_link(|_: &mut f32, _, _| {}), + ) + } + + let mut rt = Runtime::new(1.0f32, view, (200.0, 44.0), Env::new(false, 2.0)); + rt.frame(0.0); + let chips: Vec<_> = rt.instances.iter().filter(|i| i.params[1] == KIND_RECT && i.params[0] > 0.0).copied().collect(); + assert_eq!(chips.len(), 1, "plain, bold and mono runs merge into one ringed chip: {chips:?}"); + let chip = chips[0]; + assert_eq!((chip.radii, chip.params[0]), ([8.0; 4], 2.0), "4 pt radius and 1 pt ring at 2x"); + assert_eq!((chip.fill, chip.border), (FILL.premul(1.0), RING.premul(1.0))); + + // Offscreen GPU readback in a light theme where fill ≈ page colour: the ring is visible + // at the inset edge while the interior shows the fill. + let gpu = Gpu::headless(); + let size = (400u32, 88u32); + let mut renderer = Renderer::new(&gpu.device, OFFSCREEN_FORMAT); + let target = Offscreen::new(&gpu.device, size.0, size.1); + renderer.prepare(&gpu.device, &gpu.queue, &mut rt.text.atlas, &rt.instances, size); + let mut encoder = gpu.device.create_command_encoder(&Default::default()); + renderer.draw(&mut encoder, &target.view, [0.0; 4]); + target.copy(&mut encoder); + gpu.queue.submit([encoder.finish()]); + let out = target.read(&gpu.device); + let px = |x: usize, y: usize| -> [u8; 4] { out[(y * size.0 as usize + x) * 4..][..4].try_into().unwrap() }; + + let [x0, y0, w, h] = chip.rect.map(|v| v as usize); + let mid_x = x0 + w / 2; + let mid_y = y0 + h / 2; + let outside = px(mid_x, y0 - 2); + let top_ring = px(mid_x, y0 + 1); + let bot_ring = px(mid_x, y0 + h - 2); + let left_ring = px(x0 + 1, mid_y); + // Inside the left padding (past the 2 px ring, before the first glyph): fill ≈ page, not ring. + let inside_fill = px(x0 + 5, mid_y); + assert!(outside[0] > 235 && outside[2] > 235 && (outside[0] as i32 - outside[2] as i32).abs() <= 5, "page outside: {outside:?}"); + for (edge, p) in [("top", top_ring), ("bottom", bot_ring), ("left", left_ring)] { + assert!( + (p[0] as i32 - 97).abs() <= 2 && (p[1] as i32 - 166).abs() <= 2 && (p[2] as i32 - 241).abs() <= 2 && p[3] == 255, + "{edge} inset ring pixel is ring-coloured: {p:?}" + ); + } + assert!(inside_fill[0] > 230 && inside_fill[2] > 230 && (inside_fill[2] as i32 - inside_fill[0] as i32) < 10, "interior pixel is fill, not ring: {inside_fill:?}"); + // Outside the 8 px rounded corner radius, the corner pixel stays on the page background. + let corner_out = px(x0, y0); + assert!(corner_out[0] > 235 && (corner_out[0] as i32 - corner_out[2] as i32).abs() <= 5, "rounded corner cuts outside pixel: {corner_out:?}"); + + // A partial-range ring at fractional scale keeps its right edge even though the + // following unringed background overlaps it by bg_pad. + fn partial(_: &(), _: &mut Cx<()>) -> El { + col().fill(PAGE).padding(8.0).child( + rich("aa ring zz", vec![Span::new(0, 10).bg(FILL, 6.0)]) + .span_ring(3, 7, RING, 1.0), + ) + } + let mut partial_rt = Runtime::new((), partial, (200.0, 44.0), Env::new(false, 1.5)); + partial_rt.frame(0.0); + let partial_chip = partial_rt.instances.iter().find(|i| i.params[1] == KIND_RECT && i.params[0] > 0.0).unwrap(); + renderer.prepare(&gpu.device, &gpu.queue, &mut partial_rt.text.atlas, &partial_rt.instances, size); + let mut encoder = gpu.device.create_command_encoder(&Default::default()); + renderer.draw(&mut encoder, &target.view, [0.0; 4]); + target.copy(&mut encoder); + gpu.queue.submit([encoder.finish()]); + let partial_out = target.read(&gpu.device); + let x = (partial_chip.rect[0] + partial_chip.rect[2] - 1.0) as usize; + let y = (partial_chip.rect[1] + partial_chip.rect[3] * 0.5) as usize; + let edge = &partial_out[(y * size.0 as usize + x) * 4..][..4]; + assert!(edge[2] as i32 - edge[0] as i32 > 50, "fractional right ring survives adjacent fill: {edge:?}"); + + // Hover replaces the fill with HOVER while keeping the resting ring on the same rect. + let link_el = rt.elements().into_iter().find(|e| e.key.as_deref() == Some("chip")).unwrap(); + rt.pointer_move(link_el.rect[0] + 4.0, link_el.rect[1] + 4.0); + rt.frame(1.0 / 60.0); + let hovered = rt.instances.iter().find(|i| i.params[1] == KIND_RECT && i.params[0] > 0.0).unwrap(); + assert_eq!((hovered.rect, hovered.fill, hovered.border, hovered.params[0]), (chip.rect, HOVER.premul(1.0), RING.premul(1.0), 2.0)); + + // Fading the text element scales both the fill and the ring border alpha. + rt.pointer_move(0.0, 0.0); + rt.state = 0.5; + rt.invalidate(); + rt.settle_all(); + rt.frame(0.0); + let faded = rt.instances.iter().find(|i| i.params[1] == KIND_RECT && i.params[0] > 0.0).unwrap(); + assert!((faded.fill[3] - FILL.premul(0.5)[3]).abs() < 1e-3 && (faded.border[3] - RING.premul(0.5)[3]).abs() < 1e-3); + + // Fractional scale (1.5x) and wrapping across lines: each wrapped line gets its own ringed chip. + fn wrapped(_: &(), _: &mut Cx<()>) -> El { + let s = "one long ringed link that wraps across lines"; + col().w(90.0).child( + rich(s, vec![Span::new(4, s.len() - 13).bg(FILL, 3.0)]) + .font(TextStyle::new(14.0, 400.0)) + .span_rings([(4, s.len() - 13, RING, 1.0)]), + ) + } + let mut wrap_rt = Runtime::new((), wrapped, (90.0, 120.0), Env::new(false, 1.5)); + wrap_rt.frame(0.0); + let lines: Vec<_> = wrap_rt.instances.iter().filter(|i| i.params[1] == KIND_RECT && i.params[0] > 0.0).collect(); + assert!(lines.len() >= 2, "wrapped span splits into one ringed rect per line: {lines:?}"); + for d in &lines { + assert_eq!((d.radii, d.params[0], d.border), ([6.0; 4], 1.5, RING.premul(1.0))); + } +} + +/// Underline rects drawn at 2× for `words`, each its own underlined text element side by side +/// in a row; device px `(left, right)`, left to right. +fn underlines(words: &[&str]) -> Vec<(f32, f32)> { + use crate::{Cx, El, Env, Runtime}; + fn view(s: &Vec<String>, _: &mut Cx<Vec<String>>) -> El { + let line = crate::oklcha(0.6, 0.15, 260.0, 0.4); + crate::row().children(s.iter().map(|w| crate::el::rich(w.clone(), vec![Span::new(0, w.len()).underline(line)]))) + } + let mut rt = Runtime::new(words.iter().map(|w| w.to_string()).collect(), view, (600.0, 100.0), Env::new(true, 2.0)); + rt.frame(0.0); + let mut out: Vec<(f32, f32)> = rt.instances.iter() + .filter(|i| i.params[1] == crate::render::KIND_RECT && i.rect[3] == 2.0) + .map(|i| (i.rect[0], i.rect[0] + i.rect[2])) + .collect(); + out.sort_by(|a, b| a.0.total_cmp(&b.0)); + out +} + +/// A link flowed a word an element underlines as one line: each word's line +/// meets the next one's at the space, with no gap where an element's width rounds up (t942). +#[test] +fn underlined_words_in_a_row_meet_without_gaps() { + let lines = underlines(&["Watch ", "Kaizen ", "× ", "OpenCode ", "(4:12, ", "1080p60) ", "→"]); + assert_eq!(lines.len(), 7, "{lines:?}"); + for w in lines.windows(2) { + assert_eq!(w[0].1, w[1].0, "each line meets the next: {lines:?}"); + } +} diff --git a/app/vendor/rune/crates/rune/src/tooling.rs b/app/vendor/rune/crates/rune/src/tooling.rs new file mode 100644 index 0000000..0e35bfc --- /dev/null +++ b/app/vendor/rune/crates/rune/src/tooling.rs @@ -0,0 +1,601 @@ +//! Agent tooling: headless deterministic rendering, synthetic input scripts, element-tree dumps, +//! motion-lint traces and frame strips. Same renderer as the window, fixed virtual clock. + +use std::path::PathBuf; + +use serde_json::{Value, json}; + +use crate::compose::Compositor; +use crate::edit::{Key, KeyEvent, Mods}; +use crate::el::{El, Tx}; +use crate::render::write_png; +use crate::runtime::{Cx, Env, Runtime, RuntimeCore, Waker}; +use crate::text::TextSystem; + +pub use crate::tooling::headless_run::{HeadlessRun, PointerAction, ScriptEvent, ScriptPoint, TimedEvent, WindowFrame, headless_run}; + +pub struct AppSpec<S: 'static> { + pub title: &'static str, + pub size: (f32, f32), + /// The smallest window the user can resize to, in points (None: 420×400). + pub min_size: Option<(f32, f32)>, + pub init: fn() -> S, + pub view: fn(&S, &mut Cx<S>) -> El, + /// Named states for snapshots: each modifies the initial state. + pub scenes: &'static [(&'static str, fn(&mut S))], + /// Font files replacing the built-in Inter (empty keeps it), and the sans/mono family names + /// (CSS lists; `ui-monospace` stands for [`Family::SystemMono`](crate::Family::SystemMono)'s + /// families, so mono spans can be SF Mono). + pub fonts: &'static [&'static [u8]], + pub families: (&'static str, &'static str), + /// Called once with a waker other threads use when new data arrives. + pub setup: Option<fn(&mut S, Waker)>, + /// Called at the start of every frame with seconds since start (virtual when headless); + /// true when state changed. + pub poll: Option<fn(&mut S, f64, &mut Tx) -> bool>, + /// Keys unhandled by the focused control, or every key while nothing has focus + /// (`Tx::focused` tells which); true consumes the key. The rune README's "Key routing" + /// lists the whole order. + pub on_key: Option<fn(&mut S, &KeyEvent, &mut Tx) -> bool>, +} + +impl<S: 'static> AppSpec<S> { + /// The required parts; everything else at its default. Literals that set a few more fields + /// end with `..AppSpec::new(..)`, so new fields don't break them. + pub fn new(title: &'static str, size: (f32, f32), init: fn() -> S, view: fn(&S, &mut Cx<S>) -> El) -> Self { + AppSpec { + title, + size, + min_size: None, + init, + view, + scenes: &[], + fonts: &[], + families: ("Inter", "Inter"), + setup: None, + poll: None, + on_key: None, + } + } +} + +/// Window frame options. Elements marked `.window_drag()` move the window on every platform; +/// a double press there zooms (macOS follows System Settings' titlebar double-click action; +/// elsewhere it toggles maximised). +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Chrome { + /// macOS: the content view fills the window under a transparent, title-less titlebar (the + /// app draws its own titlebar area). Off: a standard titled window. Other platforms keep + /// their native frame either way. + pub full_size_content: bool, + /// macOS: the close button's top-left, in points from the window's top-left, kept there + /// across resizes and full screen (Electron's `trafficLightPosition`). `None` leaves + /// AppKit's placement. The three buttons keep AppKit's own size and spacing. + pub traffic_lights: Option<(f32, f32)>, + /// macOS: only `.window_drag()` regions move the window, so content under a full-size + /// titlebar stays clickable (Electron's app regions). Off: AppKit's titlebar band drags too. + /// Applies only to this window's content view when borderless or full-size-content. + /// Ordinary titled windows and NSPanel overlays keep their native behaviour. + pub drag_regions: bool, +} + +impl Chrome { + pub const DEFAULT: Chrome = Chrome { full_size_content: true, traffic_lights: None, drag_regions: false }; + /// Headless `--chrome` overlay and checks: macOS 26 draws 14 pt buttons on a 23 pt pitch. + pub const TRAFFIC_LIGHT: f32 = 14.0; + pub const TRAFFIC_PITCH: f32 = 23.0; + + /// Where macOS will draw the three buttons (x, y, w, h in points), assuming macOS 26 metrics + /// and AppKit's default origin (7, 6) when unpositioned. + pub fn traffic_light_rects(&self) -> Option<[[f32; 4]; 3]> { + if !self.full_size_content && self.traffic_lights.is_none() { + return None; + } + let (x, y) = self.traffic_lights.unwrap_or((7.0, 6.0)); + Some(std::array::from_fn(|i| [x + i as f32 * Self::TRAFFIC_PITCH, y, Self::TRAFFIC_LIGHT, Self::TRAFFIC_LIGHT])) + } + + /// The trailing edge of [`Chrome::traffic_light_rects`]' zoom button, or 0 without them: + /// what [`Cx::titlebar_inset`](crate::Cx::titlebar_inset) reports in a headless run. + pub fn titlebar_inset(&self) -> f32 { + self.traffic_light_rects().map_or(0.0, |r| r[2][0] + r[2][2]) + } +} + +impl Default for Chrome { + fn default() -> Self { + Chrome::DEFAULT + } +} + +static EXTRA: std::sync::OnceLock<Vec<String>> = std::sync::OnceLock::new(); +static APP_ID: std::sync::OnceLock<&'static str> = std::sync::OnceLock::new(); + +/// The application id the window reports to the desktop (Wayland `app_id`, X11 `WM_CLASS`), so +/// compositors match it to the app's `.desktop` entry, icon and window rules. Call before `run`. +pub fn set_app_id(id: &'static str) { + APP_ID.set(id).ok(); +} + +#[cfg_attr(not(target_os = "linux"), allow(dead_code))] +pub(crate) fn app_id() -> Option<&'static str> { + APP_ID.get().copied() +} + +/// Command-line arguments Rune didn't recognise, in order, for the app to interpret. Ready +/// before any window: called before `run` (to pick the file a window opens, say), it reads +/// Rune's flags from the process's arguments as `run` will, `--help` and a malformed flag +/// included. The first read wins, so an app that passes `App::args` reads this after `run` +/// starts. +pub fn extra_args() -> &'static [String] { + if EXTRA.get().is_none() { Args::parse(); } + EXTRA.get().map_or(&[], |v| v.as_slice()) +} + +pub(crate) fn runtime_for<S: 'static>(spec: &AppSpec<S>, state: S, size: (f32, f32), env: Env, waker: Waker) -> Runtime<S> { + crate::marks::mark("text.begin"); + let text = TextSystem::for_window(spec.fonts, spec.families); + crate::marks::mark("text.fonts"); + let mut rt = Runtime::with_text(state, spec.view, size, env, text); + rt.poll = spec.poll; + rt.on_key = spec.on_key; + rt.motion.enable_motion_needs_cause(); + rt.host.window_title.start(spec.title); + // The capture presets (`RUNE_CONTRAST`, `RUNE_INCREASE_CONTRAST`), never the machine's own + // settings, so a headless snap shows an app in a contrast theme or under Increase Contrast. + rt.set_system_contrast(crate::platform::preferences::contrast_preset()); + rt.set_system_increased_contrast(crate::platform::preferences::increased_contrast_preset()); + rt.set_live_waker(waker.clone()); + #[cfg(feature = "hot")] + if crate::hot::enabled() { + rt.frame.set_hot(crate::hot::Session::connect(waker.clone())); + } + if let Some(f) = spec.setup { + crate::marks::mark("app.setup"); + f(&mut rt.state, waker); + crate::marks::mark("app.setup.done"); + } + rt +} + +#[path = "tooling/args.rs"] +mod args; +#[path = "tooling/crop.rs"] +mod crop; +#[path = "tooling/eased_input.rs"] +mod eased_input; +pub(crate) use eased_input::step_resize; +#[path = "tooling/headless.rs"] +mod headless; +#[path = "tooling/loop_check.rs"] +mod loop_check; +#[path = "tooling/html.rs"] +pub(crate) mod html; +#[path = "tooling/key_names.rs"] +mod key_names; +#[path = "tooling/script.rs"] +mod script; +#[path = "tooling/strip.rs"] +mod strip; +#[path = "tooling/trace.rs"] +mod trace; + +pub use args::{Args, is_headless}; +pub(crate) use args::*; +pub use headless::headless; +pub(crate) use headless::*; +pub(crate) use key_names::{key_named, script_key_base, script_mods}; +use script::parse_script; +pub(crate) use strip::*; +#[cfg(test)] +pub(crate) use trace::tree_json; +pub(crate) use trace::{FrameTiming, Trace, tree_json_core}; +use trace::r2; + +/// Opens the app's window and quits when it closes (`App` for other lifetimes), or renders +/// headless for the tooling arguments. +pub fn run<S: 'static>(spec: AppSpec<S>) { + #[cfg(feature = "hot")] + crate::hot::run(spec, Args::parse()); + #[cfg(not(feature = "hot"))] + crate::app::App::new(spec).run(); +} + +/// Create independent windows from a display-aware factory. Headless tools invoke the same +/// factory with one virtual display and select one retained tree using `--window KEY`. +/// Windows may have different state types: return `AnyWindowSpec`s (`WindowSpec::boxed`). +pub fn run_windows<I: IntoIterator<Item: Into<crate::AnyWindowSpec>>>(factory: impl FnOnce(&[crate::Display]) -> I + 'static) { + run_windows_with(crate::RunOptions::default(), factory); +} + +/// Run a window factory with process-level options, such as macOS accessory activation. +pub fn run_windows_with<I: IntoIterator<Item: Into<crate::AnyWindowSpec>>>(options: crate::RunOptions, factory: impl FnOnce(&[crate::Display]) -> I + 'static) { + started(try_run_windows_with(options, factory)); +} + +/// `run_windows_with`, returning an error instead of exiting when the event loop can't start +/// (no display over ssh or in CI, no Wayland or X11 server) or fails. +pub fn try_run_windows_with<I: IntoIterator<Item: Into<crate::AnyWindowSpec>>>(options: crate::RunOptions, factory: impl FnOnce(&[crate::Display]) -> I + 'static) -> Result<(), String> { + run_window_factory(options, window_args(None, Args::parse), erase(factory)) +} + +/// Run a window factory with explicit Rune arguments, without reading the host CLI. +/// Pass `[]` to isolate an embedding application's flags before display discovery. +pub fn run_windows_with_args<I: IntoIterator<Item: Into<crate::AnyWindowSpec>>>(options: crate::RunOptions, args: impl IntoIterator<Item = String>, factory: impl FnOnce(&[crate::Display]) -> I + 'static) { + started(try_run_windows_with_args(options, args, factory)); +} + +/// `run_windows_with_args`, returning an error instead of exiting when the event loop can't +/// start or fails. +pub fn try_run_windows_with_args<I: IntoIterator<Item: Into<crate::AnyWindowSpec>>>(options: crate::RunOptions, args: impl IntoIterator<Item = String>, factory: impl FnOnce(&[crate::Display]) -> I + 'static) -> Result<(), String> { + run_window_factory(options, window_args(Some(args.into_iter().collect()), Args::parse), erase(factory)) +} + +/// What `run` says to a release build without the `tooling` feature asked for a headless run. +#[cfg(not(any(feature = "tooling", debug_assertions)))] +pub(crate) const WITHOUT_TOOLING: &str = "this build has no agent tooling (--snap, --tree, --script, --trace, --strip, --video, ...): \ + a release build has it with Rune's `tooling` feature (rune = { ..., features = [\"tooling\"] }); debug builds always do"; + +/// Reports a failed startup and exits the process on native targets. wasm32 has no process +/// exit, so there it panics. +#[cfg(not(target_arch = "wasm32"))] +pub(crate) fn started(result: Result<(), String>) { + if let Err(error) = result { + eprintln!("{error}"); + std::process::exit(1); + } +} + +#[cfg(target_arch = "wasm32")] +pub(crate) fn started(result: Result<(), String>) { + if let Err(error) = result { panic!("{error}"); } +} + +type Factory = Box<dyn FnOnce(&[crate::Display]) -> Vec<crate::AnyWindowSpec>>; + +fn erase<I: IntoIterator<Item: Into<crate::AnyWindowSpec>>>(factory: impl FnOnce(&[crate::Display]) -> I + 'static) -> Factory { + Box::new(move |displays| factory(displays).into_iter().map(Into::into).collect()) +} + +pub(crate) fn window_args(args: Option<Vec<String>>, process: impl FnOnce() -> Args) -> Args { + args.map_or_else(process, Args::parse_from) +} + +fn run_window_factory(options: crate::RunOptions, args: Args, factory: Factory) -> Result<(), String> { + if args.headless() { + #[cfg(any(feature = "tooling", debug_assertions))] + { + crate::render::discard_prewarm(); + let displays = desktop(&args, read_script(&args).as_ref()).displays(); + headless_window(factory(&displays), &displays, args, options) + } + #[cfg(not(any(feature = "tooling", debug_assertions)))] + Err(WITHOUT_TOOLING.into()) + } else { + crate::window::run_windows(factory, args, options) + } +} + +/// Lists the windows, or renders the one `--window KEY` selects (the first by default) with its +/// own state. Windows that apps added with `App::window` are selectable too. +fn headless_window(windows: Vec<crate::AnyWindowSpec>, displays: &[crate::Display], args: Args, options: crate::RunOptions) -> Result<(), String> { + let mut windows = crate::windows::flatten(windows); + crate::windows::validate(&windows).unwrap_or_else(|e| die(&e)); + if args.list_windows { + for window in windows { println!("{}", window.key()); } + return Ok(()); + } + let index = match args.window.as_deref() { + Some(key) => windows.iter().position(|w| w.key() == key).unwrap_or_else(|| die(&format!("no window {key:?}; use --list-windows"))), + None if !windows.is_empty() => 0, + None => die("the app created no windows"), + }; + if args.desktop.is_some() { + crate::tooling::interaction::gate::headless(); + crate::desktop::run(windows, index, args, options.accessory); + return Ok(()); + } + let mut window = windows.remove(index); + let args = window.resolve_args(args); + if !args.headless() { + return crate::window::run_windows(Box::new(move |_| vec![window]), args, options); + } + let scale = displays.iter().find(|d| d.primary).unwrap_or(&displays[0]).scale; + window.headless(args, scale as f32); + Ok(()) +} + +/// `run` with a compositor drawing every frame (see `compose`); `App::compositor` for other lifetimes. +pub fn run_with<S: 'static>(spec: AppSpec<S>, compositor: impl Compositor<S>) { + crate::app::App::new(spec).compositor(compositor).run(); +} + +pub fn initial_state<S: 'static>(spec: &AppSpec<S>, scene: Option<&str>) -> S { + with_scene(spec, (spec.init)(), scene) +} + +/// `state` with the named scene applied. +pub(crate) fn with_scene<S: 'static>(spec: &AppSpec<S>, mut s: S, scene: Option<&str>) -> S { + if let Some(name) = scene { + let Some((_, f)) = spec.scenes.iter().find(|(n, _)| *n == name) else { + let names: Vec<_> = spec.scenes.iter().map(|(n, _)| *n).collect(); + die(&format!("no scene {name:?}; scenes: {}", names.join(", "))); + }; + f(&mut s); + } + s +} + +// ------------------------------------------------------------------------------------------- +// Scripts + +#[derive(Clone, Debug)] +pub(crate) enum Pos { + Xy(f32, f32), + Key(String), + /// Relative to the last pointer-down position. + Rel(f32, f32), +} + +#[derive(Clone, Debug)] +pub(crate) enum Kind { + /// A named time with no input effect. + Mark(String), + Focus(bool), + /// The app reopened (macOS: its Dock icon clicked). + Reopen, + /// A link the system opened with the app (`App::on_open_url`). + OpenUrl(String), + Menu(String), + /// Answers the open pop-up menu: an item's id, or `None` to dismiss it. + PopupMenu(Option<String>), + /// Answers the open file dialog: the chosen path, or `None` to cancel it. + FileDialog(Option<PathBuf>), + Physical(crate::PhysicalInput), + /// A registered global shortcut, delivered only to its handler. + Shortcut(crate::Shortcut), + Move, + Down, + Up, + SecondaryDown, + SecondaryUp, + /// The key and whether it is an auto-repeat. + Key(KeyEvent, bool), + /// A key press with its physical code (`{"type": "key", "code": …}`), as a native host sends it. + PhysicalKey(crate::PhysicalInput, KeyEvent, Option<char>), + Paste(crate::ClipboardContent), + /// An input method's composition or commit. + Ime(crate::Ime), + /// A wheel delta (dx, dy) in points. + Wheel(f32, f32), + /// A release velocity (vx, vy) in points per second. + Fling(f32, f32), + /// A file drag from another app (`drag_files`, `drop_files`). + Files(FileStep), + /// `{"type": "wheel"}`: one delta with modifiers and a phase, at the pointer. + WheelEvent(crate::WheelEvent), + Magnify(crate::MagnifyEvent), + Rotate(crate::RotateEvent), + SmartMagnify, + /// A button besides the primary and secondary (`"button": "middle"`). + ButtonDown(crate::PointerButton), + ButtonUp(crate::PointerButton), + KeyUp(KeyEvent), + /// A person dragging the window's corner, (dw, dh) from the size where (0, 0) started. + Resize(f32, f32), +} + +impl Kind { + /// A press that later `Rel` positions are relative to. + pub(crate) fn is_down(&self) -> bool { matches!(self, Kind::Down | Kind::SecondaryDown | Kind::ButtonDown(_)) } + pub(crate) fn is_up(&self) -> bool { matches!(self, Kind::Up | Kind::SecondaryUp | Kind::ButtonUp(_)) } + /// Without a position it lands where the pointer is, not at the last press. + pub(crate) fn at_pointer(&self) -> bool { + matches!(self, Kind::Wheel(..) | Kind::Fling(..) | Kind::WheelEvent(_) | Kind::Magnify(_) | Kind::Rotate(_) | Kind::SmartMagnify) + } +} + +/// Shared script input translation for both headless (`headless.rs`) and virtual-desktop +/// (`virtual_desktop`) hosts. `(x, y)` is in view points; scroll/wheel/fling deltas are in +/// window points and divided by `core.zoom()`, matching the desktop window host. Returns false +/// for orchestration-only kinds (`Mark`, `Reopen`, `OpenUrl`, `Shortcut`, `Menu`, `PopupMenu`, +/// `FileDialog`, `Resize`). +pub(crate) fn script_input( + core: &mut crate::runtime::RuntimeCore, + app: &mut dyn crate::runtime::AppDriver, + kind: &Kind, + (x, y): (f32, f32), +) -> bool { + match kind { + Kind::Focus(focused) => core.window_focus(app, *focused), + Kind::Move => core.pointer_move(app, x, y), + Kind::Down => core.pointer_down(app, x, y), + Kind::Up => core.pointer_up(app, x, y), + Kind::SecondaryDown => core.secondary_down(x, y), + Kind::SecondaryUp => core.secondary_up(app, x, y), + Kind::Key(k, false) => core.key(k.clone()), + Kind::Key(k, true) => core.repeat_key(k.clone()), + Kind::Physical(event) => core.physical_input(*event), + Kind::Paste(content) => core.paste_content(content.clone()), + Kind::Ime(ime) => core.ime(ime.clone()), + Kind::Wheel(dx, dy) => { let z = core.zoom(); wheel(core, (x, y), *dx / z, *dy / z); } + Kind::Fling(vx, vy) => { let z = core.zoom(); fling(core, (x, y), *vx / z, *vy / z); } + Kind::Files(step) => file_input(core, step, (x, y)), + Kind::WheelEvent(ev) => { + let z = core.zoom(); + let mut ev = ev.at(x, y); + ev.dx /= z; + ev.dy /= z; + core.wheel_event(ev); + } + Kind::Magnify(ev) => core.magnify_event(ev.at(x, y)), + Kind::Rotate(ev) => core.rotate_event(ev.at(x, y)), + Kind::SmartMagnify => core.smart_magnify(x, y), + Kind::ButtonDown(b) => core.button_down(app, x, y, *b), + Kind::ButtonUp(b) => core.button_up(app, x, y, *b), + Kind::KeyUp(k) => { core.key_up(app, k.clone()); } + Kind::PhysicalKey(event, k, base) => core.physical_key_input(app, *event, k.clone(), *base), + Kind::Mark(_) | Kind::Reopen | Kind::OpenUrl(_) | Kind::Menu(_) | Kind::PopupMenu(_) + | Kind::FileDialog(_) | Kind::Shortcut(_) | Kind::Resize(..) => return false, + } + true +} + +/// The canvas input of a script (`canvas_input.rs`) at window point (x, y); false for any +/// other kind. +#[cfg(test)] +pub(crate) fn canvas_input( + core: &mut crate::runtime::RuntimeCore, + app: &mut dyn crate::runtime::AppDriver, + kind: &Kind, + (x, y): (f32, f32), +) -> bool { + match kind { + Kind::WheelEvent(_) | Kind::Magnify(_) | Kind::Rotate(_) | Kind::SmartMagnify + | Kind::ButtonDown(_) | Kind::ButtonUp(_) | Kind::KeyUp(_) | Kind::PhysicalKey(..) => { + script_input(core, app, kind, (x, y)) + } + _ => false, + } +} + +#[derive(Clone, Debug)] +pub(crate) enum FileStep { + Hover(Vec<PathBuf>), + Drop(Vec<PathBuf>), + Leave, +} + +/// A scripted wheel delta: vertical-only ones take the plain vertical path, unless an +/// `on_wheel` handler may take them. +pub(crate) fn wheel(rt: &mut RuntimeCore, (x, y): (f32, f32), dx: f32, dy: f32) { + if dx == 0.0 && !rt.hears_wheel() { rt.wheel(x, y, dy) } else { rt.wheel_xy(x, y, dx, dy) } +} + +fn script_phase(e: &Value) -> crate::GesturePhase { + match e["phase"].as_str().unwrap_or("moved") { + "began" => crate::GesturePhase::Began, + "moved" => crate::GesturePhase::Moved, + "ended" => crate::GesturePhase::Ended, + other => die(&format!("unknown gesture phase {other}; use began, moved or ended")), + } +} + +/// A scripted release velocity: vertical-only ones take the plain vertical path. +pub(crate) fn fling(rt: &mut RuntimeCore, (x, y): (f32, f32), vx: f32, vy: f32) { + if vx == 0.0 { rt.fling(x, y, vy) } else { rt.fling_xy(x, y, vx, vy) } +} + +#[derive(Clone, Debug)] +pub(crate) struct Ev { + pub t: f64, + pub kind: Kind, + pub pos: Pos, +} + +impl Ev { + /// The event as apps read it through `headless_run`. + pub(crate) fn public(&self) -> TimedEvent { + let at = || match &self.pos { + Pos::Xy(x, y) => ScriptPoint::At(*x, *y), + Pos::Key(key) => ScriptPoint::Element(key.clone()), + Pos::Rel(dx, dy) => ScriptPoint::FromDown(*dx, *dy), + }; + let pointer = |action| ScriptEvent::Pointer { action, at: at() }; + let event = match &self.kind { + Kind::Mark(name) => ScriptEvent::Mark(name.clone()), + Kind::Focus(focused) => ScriptEvent::Focus(*focused), + Kind::Reopen => ScriptEvent::Reopen, + Kind::OpenUrl(url) => ScriptEvent::OpenUrl(url.clone()), + Kind::Menu(item) => ScriptEvent::Menu(item.clone()), + Kind::PopupMenu(picked) => ScriptEvent::PopupMenu(picked.clone()), + Kind::FileDialog(path) => ScriptEvent::FileDialog(path.clone()), + Kind::Physical(input) => ScriptEvent::Physical(*input), + Kind::Shortcut(chord) => ScriptEvent::Shortcut(chord.clone()), + Kind::Move => pointer(PointerAction::Move), + Kind::Down => pointer(PointerAction::Down), + Kind::Up => pointer(PointerAction::Up), + Kind::SecondaryDown => pointer(PointerAction::SecondaryDown), + Kind::SecondaryUp => pointer(PointerAction::SecondaryUp), + Kind::Key(key, repeat) => ScriptEvent::Key { key: key.clone(), repeat: *repeat }, + Kind::PhysicalKey(event, key, _) => ScriptEvent::Key { + key: key.clone(), repeat: matches!(event, crate::PhysicalInput::Key { repeat: true, .. }), + }, + Kind::Paste(content) if content.is_rich() => ScriptEvent::PasteContent(content.clone()), + Kind::Paste(content) => ScriptEvent::Paste(content.text().to_owned()), + Kind::Ime(ime) => ScriptEvent::Ime(ime.clone()), + Kind::Wheel(0.0, dy) => pointer(PointerAction::Scroll(*dy)), + Kind::Wheel(dx, dy) => pointer(PointerAction::ScrollXy(*dx, *dy)), + Kind::Fling(0.0, v) => pointer(PointerAction::Fling(*v)), + Kind::Fling(vx, vy) => pointer(PointerAction::FlingXy(*vx, *vy)), + Kind::Files(FileStep::Hover(paths)) => ScriptEvent::DragFiles { paths: paths.clone(), at: at() }, + Kind::Files(FileStep::Drop(paths)) => ScriptEvent::DropFiles { paths: paths.clone(), at: at() }, + Kind::Files(FileStep::Leave) => ScriptEvent::DragFilesLeave, + Kind::WheelEvent(ev) => pointer(PointerAction::Wheel(*ev)), + Kind::Magnify(ev) => pointer(PointerAction::Magnify(*ev)), + Kind::Rotate(ev) => pointer(PointerAction::Rotate(*ev)), + Kind::SmartMagnify => pointer(PointerAction::SmartMagnify), + Kind::ButtonDown(b) => pointer(PointerAction::ButtonDown(*b)), + Kind::ButtonUp(b) => pointer(PointerAction::ButtonUp(*b)), + Kind::KeyUp(key) => ScriptEvent::KeyUp(key.clone()), + Kind::Resize(dw, dh) => ScriptEvent::Resize { dw: *dw, dh: *dh }, + }; + TimedEvent { t: self.t, event } + } +} + +pub(crate) fn read_script(args: &Args) -> Option<Value> { + args.script.as_ref().map(|path| { + let text = std::fs::read_to_string(path).unwrap_or_else(|e| die(&format!("{}: {e}", path.display()))); + serde_json::from_str(&text).unwrap_or_else(|e| die(&format!("{}: {e}", path.display()))) + }) +} + +pub(crate) fn load_script(script: &Value) -> Vec<Ev> { + let list = match script { Value::Object(o) => o.get("events").cloned().unwrap_or_else(|| json!([])), v => v.clone() }; + parse_script(list) +} + +/// The script's displays and pointer, which headless `place()` resolves against. Without +/// scripted displays, a `--desktop` run has one display the size of its output: `--size`, else +/// the backdrop's pixels at `--scale`. +pub(crate) fn desktop(args: &Args, script: Option<&Value>) -> crate::desktop::displays::VirtualDesktop { + let scale = f64::from(args.scale.unwrap_or(2.0)); + let size = args.desktop.as_ref().map(|path| match args.size { + Some((w, h)) => (f64::from(w), f64::from(h)), + None => { + let (w, h) = ::image::image_dimensions(path).unwrap_or_else(|e| die(&format!("{}: {e}", path.display()))); + (f64::from(w) / scale, f64::from(h) / scale) + } + }); + crate::desktop::displays::VirtualDesktop::from_script_sized(script, scale, size).unwrap_or_else(|e| die(&e)) +} + +/// Feeds a script's file drag step to `rt`, at `at` in window points. +pub(crate) fn file_input(core: &mut crate::runtime::RuntimeCore, step: &FileStep, at: (f32, f32)) { + match step { + FileStep::Hover(paths) => core.drag_files(paths.clone(), Some(at)), + FileStep::Drop(paths) => core.drop_files(paths.clone(), Some(at)), + FileStep::Leave => core.drag_files_leave(), + } +} + +#[cfg(test)] +include!("tooling/parser_tests.rs"); + +pub(crate) mod headless_run; +pub(crate) mod interaction; +pub(crate) mod perf_warn; +pub(crate) mod record; +// Only headless runs use it; a release build without `tooling` keeps the module but not its callers. +#[cfg_attr(not(any(feature = "tooling", debug_assertions)), allow(dead_code, unused_imports))] +pub(crate) mod virtual_desktop; +#[cfg(test)] +pub(crate) mod test_alloc; +#[cfg(test)] +#[path = "tooling/window_tests.rs"] +mod window_tests; + +#[cfg(test)] +#[path = "tooling/tests.rs"] +mod tests; diff --git a/app/vendor/rune/crates/rune/src/tooling/args.rs b/app/vendor/rune/crates/rune/src/tooling/args.rs new file mode 100644 index 0000000..fc84a3b --- /dev/null +++ b/app/vendor/rune/crates/rune/src/tooling/args.rs @@ -0,0 +1,337 @@ +//! The tooling arguments: `Args` and its parser. + +use super::*; + +#[derive(Clone, Default, Debug)] +pub struct Args { + #[cfg(feature = "hot")] + pub(crate) snap_on_patch: Option<PathBuf>, + #[cfg(feature = "hot")] + pub(crate) hot_control: Option<PathBuf>, + pub snap: Option<PathBuf>, + pub scene: Option<String>, + pub at: Option<f64>, + pub size: Option<(f32, f32)>, + pub scale: Option<f32>, + pub theme: Option<String>, + pub scroll_bars: Option<crate::ScrollBars>, + pub script: Option<PathBuf>, + pub frames: Option<usize>, + pub start: f64, + pub fps: f64, + pub out: Option<PathBuf>, + pub tree: Option<PathBuf>, + pub trace: Option<PathBuf>, + /// Trace the native window's submission clock instead of a virtual headless clock. + pub native: bool, + /// Trace every element, keyed or not (paths name the unkeyed ones). + pub trace_all: bool, + pub strip: Option<PathBuf>, + pub crops: Vec<[f32; 4]>, + pub every: usize, + pub cols: usize, + pub list_scenes: bool, + pub first_pixels: bool, + pub window: Option<String>, + pub list_windows: bool, + /// Draw where macOS will put the traffic lights over headless frames, and report elements + /// that overlap them. + pub chrome_overlay: bool, + /// Stream the dumped frames into ffmpeg, which writes this video. + pub(crate) video: Option<PathBuf>, + /// How long to dump frames for, when `frames` isn't given. + pub(crate) duration: Option<Length>, + /// `--at mark:NAME±S` and `--start mark:NAME±S`: a script mark's time plus an offset. + pub(crate) at_mark: Option<String>, + pub(crate) start_mark: Option<String>, + /// `--keys [CORNER]`: keycaps for script keys and chords over dumped frames. + pub(crate) keys: Option<crate::input::keycaps::Corner>, + /// `--keys-theme light|dark`; None (`auto`) follows the app's theme. + pub(crate) keys_theme: Option<bool>, + /// `--pointer`: a ripple where the script presses. + pub(crate) pointer: bool, + /// `--desktop BACKDROP`: every visible window composited at its frame over this image. + pub(crate) desktop: Option<PathBuf>, + /// `--playground [NAME]`: open the playground at launch, at the story named. + pub(crate) playground: Option<Option<String>>, + /// `--variant N|NAME`: the variant `--playground` opens its story on. + pub(crate) variant: Option<String>, + /// `--crop KEY`: crop `--snap` to the element with this key or path; with `--playground`, + /// on the stage unless `whole_window`. + pub(crate) crop_key: Option<String>, + /// `--whole-window`: `--snap` with `--playground` takes the whole window, not just the stage. + pub(crate) whole_window: bool, + /// `--html OUT.html`: write the scene as a static page (`tooling::html`). + pub(crate) html: Option<PathBuf>, + /// `--html-widths 360,640,1000`: the widths `--html` lays the page out at, each the + /// narrowest its `@media` rules apply to. + pub(crate) html_widths: Vec<f32>, + /// `--html-template FILE`: the page `--html` fills at `<!-- rune:css -->` and `<!-- rune:body -->`. + pub(crate) html_template: Option<PathBuf>, + /// `--realtime`: a headless run waits for the wall clock to reach each frame's time and + /// prints `rune-mark NAME T` as the script passes each mark, so a live server's replies and a + /// harness's actions keep pace with its script. It stands in for a window, so `App::on_ready` + /// runs after its first frame. + pub(crate) realtime: bool, + /// `--cpu-boot DIR`: also paint the `--snap` frame on the CPU (`render::cpu_boot`), on + /// `--cpu-boot-threads N` threads (6 by default). + pub(crate) cpu_boot: Option<PathBuf>, + pub(crate) cpu_boot_threads: usize, +} + +#[derive(Clone, Copy, Debug, PartialEq)] +pub(crate) enum Length { + Seconds(f64), + /// To the script's `end` mark, or one second after its last event. + Auto, +} + +/// Retain the whole expression until the script is loaded: a mark's name can end in `-1`. +pub(crate) fn mark_time(v: &str) -> Option<String> { + v.strip_prefix("mark:").map(str::to_owned) +} + +impl Args { + pub fn parse() -> Args { + #[cfg(target_arch = "wasm32")] + return Args::parse_from(Vec::new()); + #[cfg(not(target_arch = "wasm32"))] + Args::parse_from(std::env::args().skip(1).collect()) + } + + /// Parses `argv` (without the program name); unrecognised arguments become `extra_args`. + pub fn parse_from(argv: Vec<String>) -> Args { + let (args, extra) = Args::parse_split(argv); + EXTRA.set(extra).ok(); + args + } + + /// The process's arguments, leaving `extra_args` unset so an app's own `App::args` can still + /// set it. + fn parse_process() -> Args { + #[cfg(target_arch = "wasm32")] + return Args::parse_split(Vec::new()).0; + #[cfg(not(target_arch = "wasm32"))] + Args::parse_split(std::env::args().skip(1).collect()).0 + } + + fn parse_split(argv: Vec<String>) -> (Args, Vec<String>) { + #[cfg(feature = "hot")] + crate::hot::enable_from_env(); + let mut a = Args { fps: 60.0, every: 1, cols: 10, cpu_boot_threads: 6, ..Default::default() }; + let mut extra = Vec::new(); + let mut i = 0; + let val = |i: &mut usize| -> String { + *i += 1; + argv.get(*i).cloned().unwrap_or_else(|| die(&format!("{} needs a value", argv[*i - 1]))) + }; + while i < argv.len() { + match argv[i].as_str() { + #[cfg(feature = "hot")] + "--hot" => crate::hot::enable(), + #[cfg(feature = "hot")] + "--snap-on-patch" => a.snap_on_patch = Some(val(&mut i).into()), + #[cfg(feature = "hot")] + "--hot-control" => a.hot_control = Some(val(&mut i).into()), + #[cfg(not(feature = "hot"))] + "--hot" | "--snap-on-patch" | "--hot-control" => die("live editing requires the rune/hot feature; use scripts/rune-dev"), + "--snap" => a.snap = Some(val(&mut i).into()), + "--scene" => a.scene = Some(val(&mut i)), + "--playground" => a.playground = Some(crate::playground::arg(&argv, &mut i)), + "--variant" => a.variant = Some(val(&mut i)), + "--whole-window" => a.whole_window = true, + "--at" => { + let v = val(&mut i); + a.at_mark = mark_time(&v); + a.at = a.at_mark.is_none().then(|| num(&v)); + } + "--size" => a.size = Some(parse_size(&val(&mut i)).unwrap_or_else(|e| die(&e))), + "--scale" => a.scale = Some(parse_scale(&val(&mut i)).unwrap_or_else(|e| die(&e))), + "--theme" => a.theme = Some(val(&mut i)), + "--scroll-bars" => a.scroll_bars = Some(parse_scroll_bars(&val(&mut i)).unwrap_or_else(|e| die(&e))), + "--script" => a.script = Some(val(&mut i).into()), + "--frames" => a.frames = Some(num(&val(&mut i)) as usize), + "--start" => { + let v = val(&mut i); + a.start_mark = mark_time(&v); + if a.start_mark.is_none() { a.start = num(&v); } + } + "--fps" => a.fps = num(&val(&mut i)), + "--out" => a.out = Some(val(&mut i).into()), + "--video" => a.video = Some(val(&mut i).into()), + "--duration" => { + let v = val(&mut i); + a.duration = Some(if v == "auto" { Length::Auto } else { Length::Seconds(num(&v)) }); + } + "--keys" => { + let corner = argv.get(i + 1).and_then(|v| crate::input::keycaps::Corner::parse(v)); + if corner.is_some() { i += 1; } + a.keys = Some(corner.unwrap_or_default()); + } + "--keys-theme" => { + let v = val(&mut i); + a.keys_theme = crate::input::keycaps::parse_theme(&v).unwrap_or_else(|| die("--keys-theme is auto, light or dark")); + } + "--pointer" => a.pointer = true, + "--desktop" => a.desktop = Some(val(&mut i).into()), + "--tree" => a.tree = Some(val(&mut i).into()), + "--html" => a.html = Some(val(&mut i).into()), + "--html-template" => a.html_template = Some(val(&mut i).into()), + "--html-widths" => { + let v = val(&mut i); + a.html_widths = v.split(',').map(|w| positive(w).unwrap_or_else(|| die(&format!("--html-widths is a list of widths above 0: {v}")))).collect(); + } + "--trace" => a.trace = Some(val(&mut i).into()), + "--native" => a.native = true, + "--realtime" => a.realtime = true, + "--trace-all" => a.trace_all = true, + "--strip" => a.strip = Some(val(&mut i).into()), + "--crop" => { + let v = val(&mut i); + match v.split(',').map(|s| s.trim().parse::<f32>()).collect::<Result<Vec<_>, _>>() { + Ok(r) if r.len() == 4 => a.crops.push([r[0], r[1], r[2], r[3]]), + _ if v.contains(',') => die("--crop is x,y,w,h in points, or an element's key or path"), + _ => a.crop_key = Some(v), + } + } + "--cols" => a.cols = (num(&val(&mut i)) as usize).max(1), + "--every" => a.every = (num(&val(&mut i)) as usize).max(1), + "--list-scenes" => a.list_scenes = true, + "--first-pixels" => a.first_pixels = true, + "--window" => a.window = Some(val(&mut i)), + "--list-windows" => a.list_windows = true, + "--chrome" => a.chrome_overlay = true, + "--cpu-boot" => a.cpu_boot = Some(val(&mut i).into()), + "--cpu-boot-threads" => a.cpu_boot_threads = (num(&val(&mut i)) as usize).max(1), + "-h" | "--help" => { + eprintln!("{HELP}"); + std::process::exit(0); + } + other => extra.push(other.to_owned()), + } + i += 1; + } + if a.variant.is_some() && a.playground.is_none() { die("--variant needs --playground"); } + if a.crop_key.is_some() && a.snap.is_none() { die("--crop KEY needs --snap"); } + if a.whole_window && (a.playground.is_none() || a.snap.is_none()) { die("--whole-window needs --playground and --snap"); } + if a.cpu_boot.is_some() && a.snap.is_none() { die("--cpu-boot needs --snap"); } + (a, extra) + } + + pub fn headless(&self) -> bool { + #[cfg(feature = "hot")] + if self.snap_on_patch.is_some() { return true; } + self.snap.is_some() + || self.tree.is_some() + || self.html.is_some() + || (!self.native + && (self.script.is_some() || self.trace.is_some() || self.frames.is_some() || self.duration.is_some() || self.out.is_some())) + || self.video.is_some() + || self.strip.is_some() + || self.list_scenes + || self.first_pixels + || self.list_windows + || self.desktop.is_some() + } +} + +/// Whether this process runs headless: its arguments ask for an offscreen render, a scripted +/// run, a trace or a listing rather than a window, as `Args::headless` decides. Parsed from the +/// process's arguments once, so it answers before `run` (to skip a tray, global shortcuts or +/// network work in a scripted run, say), with `--help` and a malformed flag handled as `run` +/// handles them. An app that passes `App::args` asks `Args::parse_from(..).headless()` instead. +pub fn is_headless() -> bool { + static HEADLESS: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + *HEADLESS.get_or_init(|| Args::parse_process().headless()) +} + +const HELP: &str = "usage: <app> [window] + --snap out.png render offscreen (no window) at --at seconds + --scene NAME start from a named scene (--list-scenes) + --playground [NAME] open App::playground at launch, at a story; headless too + --variant N|NAME open --playground's story on a variant (1 is the first) + (--snap with --playground takes only the story's stage by default; + --out, --video and --strip frames are the whole window) + --whole-window --snap with --playground takes the whole window: list, stage and side + --crop KEY crop --snap to the element with that key or path (with --playground, + one on the stage, or anywhere in the window with --whole-window) + --at SECONDS virtual time of the snapshot/tree (default: end of frames or script); + mark:NAME or mark:NAME+0.5 for a script mark's time (also --start) + --size WxH viewport in points --scale N device scale (default 2) + --theme dark|light system appearance + --scroll-bars MODE scroll bars: when-scrolling (headless default), always, automatic + --script FILE.json timestamped input, replayed headless (move/down/up/tap/drag, keys, + {\"focus\":false}); a key with \"repeat\":true is a held key's auto-repeat; + {\"type\":\"mark\",\"name\":N} marks a time; + {\"type\":\"shortcut\",\"chord\":\"cmd+space\"} presses a chord through its + registered global shortcut handler, never on_key; + an object adds \"displays\" and \"pointer\" for place() (rune-placed, --tree) + menu-pick with an \"id\" and menu-cancel answer a pop-up menu; + file-dialog with a \"path\" and file-dialog-cancel a file dialog + --frames N --fps 60 --start S --out DIR dump N frames from S seconds + --video out.mp4 stream frames into ffmpeg (.mp4 H.264, .mov ProRes 4444, .webm VP9); + --frames N or --duration SECONDS|auto long (default auto: to the + script's \"end\" mark, or 1 s after its last event) + --keys [CORNER] draw keycaps for script keys and chords on frames (bottom-left default; + bottom, bottom-right, top-left, top, top-right); never in --tree + --keys-theme auto|light|dark cap colours (default auto: match the app's background) + --pointer draw a ripple where the script presses + --desktop BACKDROP.png draw every visible window at its placed frame, with corners and + shadows, over the backdrop (scaled to fill). The output is --size + points, else the script's primary display, else the backdrop's pixels + at --scale; script x/y are output points, keys go to the key window; + --window KEY picks the window --scene and --tree describe + --strip out.png --crop x,y,w,h --every K tile dumped frames into one image + (repeat --crop to stack several regions per frame; --cols N per row) + --tree out.json element tree with animated values + --html out.html the page as static HTML and CSS, at rest, for a web app's first paint + (no GPU); --html-widths 360,640,1000 lays it out at each width and + folds them into @media rules; --html-template FILE fills + <!-- rune:css --> and <!-- rune:body --> in FILE + --trace out.jsonl per-frame rects/opacity in motion-lint JSONL, with the tracks each frame + sampled (tk) and why it was animating (quality.why) + --trace-all trace unkeyed elements too, by path + --native trace native submissions; --frames N stops after N frames + --realtime headless: hold each frame until the wall clock reaches its time, and + print \"rune-mark NAME T\" as the script passes each mark, + and run on_ready after the first frame, as a window does + --first-pixels report when the first GPU-complete offscreen pixels are readable + --window KEY select a window for headless tools (run_windows, App::window) + --list-windows list window keys using a deterministic virtual display + --chrome draw where macOS puts the traffic lights; list elements overlapping them + --cpu-boot DIR also paint the --snap frame on the CPU, as a window's first frame before + its GPU: DIR gets draw.bin, cpu.png and gpu.png, and the run prints + rune-cpu-boot {json} (stage times, drift); --cpu-boot-threads N (6) + other arguments are passed to the app (rune::tooling::extra_args)"; + +pub(crate) fn die(msg: &str) -> ! { + eprintln!("{msg}"); + std::process::exit(2) +} + +pub(crate) fn num(s: &str) -> f64 { + s.trim().parse().unwrap_or_else(|_| die(&format!("not a number: {s}"))) +} + +fn positive(s: &str) -> Option<f32> { + s.trim().parse::<f32>().ok().filter(|v| v.is_finite() && *v > 0.0) +} + +/// `--size WxH`, in points. +pub(crate) fn parse_size(v: &str) -> Result<(f32, f32), String> { + v.split_once('x').and_then(|(w, h)| Some((positive(w)?, positive(h)?))) + .ok_or_else(|| format!("--size is WxH, both above 0: {v}")) +} + +pub(crate) fn parse_scale(v: &str) -> Result<f32, String> { + positive(v).ok_or_else(|| format!("--scale is a number above 0: {v}")) +} + +pub(crate) fn parse_scroll_bars(v: &str) -> Result<crate::ScrollBars, String> { + match v.trim() { + "always" => Ok(crate::ScrollBars::Always), + "when-scrolling" => Ok(crate::ScrollBars::WhenScrolling), + "automatic" | "auto" => Ok(crate::ScrollBars::Automatic), + _ => Err(format!("--scroll-bars is when-scrolling, always or automatic: {v}")), + } +} diff --git a/app/vendor/rune/crates/rune/src/tooling/crop.rs b/app/vendor/rune/crates/rune/src/tooling/crop.rs new file mode 100644 index 0000000..50bb856 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/tooling/crop.rs @@ -0,0 +1,45 @@ +//! `--crop KEY` and `--playground`'s stage: a `--snap` cropped to one element's rect. + +use super::*; + +/// The pixel rect `[x, y, w, h]` `--snap` keeps, or None for the whole frame: `--crop KEY`'s +/// element, else the playground's stage when `--playground` opened it without +/// `--whole-window`. On the stage, `KEY` is looked up there only. Rounded out to whole pixels +/// and clipped to the `w` by `h` frame. +pub(crate) fn snap_rect(rt: &crate::runtime::RuntimeCore, args: &Args, scale: f32, (w, h): (u32, u32)) -> Option<[u32; 4]> { + let all = rt.elements(); + let stage = if args.playground.is_some() && !args.whole_window { + all.iter().position(|e| !e.exiting && e.key.as_deref().is_some_and(crate::playground::is_stage)) + } else { + None + }; + let pixels = |i: usize| { + let [x, y, rw, rh] = all[i].rect; + let px = |v: f32, max: u32, round: fn(f32) -> f32| (round(v * scale).max(0.0) as u32).min(max); + let (x0, y0, x1, y1) = (px(x, w, f32::floor), px(y, h, f32::floor), px(x + rw, w, f32::ceil), px(y + rh, h, f32::ceil)); + (x1 > x0 && y1 > y0).then(|| [x0, y0, x1 - x0, y1 - y0]) + }; + let Some(key) = &args.crop_key else { + // A window too narrow for a stage snaps whole. + return stage.and_then(pixels); + }; + let found = match stage { + Some(_) => crate::playground::stage_element(&all, key).unwrap_or_else(|| { + die(&format!("--crop {key}: no element on the playground's stage has that key or path; --whole-window searches the whole window")) + }), + None => { + let named = |i: &usize| !all[*i].exiting && (all[*i].key.as_deref() == Some(key.as_str()) || all[*i].path == *key); + (0..all.len()).find(named).unwrap_or_else(|| die(&format!("--crop {key}: no element has that key or path"))) + } + }; + Some(pixels(found).unwrap_or_else(|| die(&format!("--crop {key}: the element is empty or outside the frame")))) +} + +/// The `rect` of an RGBA frame `w` pixels wide. +pub(crate) fn crop(px: &[u8], w: u32, [x, y, cw, ch]: [u32; 4]) -> Vec<u8> { + let row = |r: u32| { + let start = ((y + r) * w + x) as usize * 4; + &px[start..start + cw as usize * 4] + }; + (0..ch).flat_map(row).copied().collect() +} diff --git a/app/vendor/rune/crates/rune/src/tooling/eased_input.rs b/app/vendor/rune/crates/rune/src/tooling/eased_input.rs new file mode 100644 index 0000000..8f3bc1d --- /dev/null +++ b/app/vendor/rune/crates/rune/src/tooling/eased_input.rs @@ -0,0 +1,44 @@ +//! Script inputs a hand eases over a duration, one step a frame. +use super::{Ev, Kind, Pos}; +use crate::runtime::RuntimeCore; +use serde_json::Value; + +/// `{"type": "scroll"}`: a trackpad swipe, deltas eased over `dur`, then (with "fling") the +/// release velocity. +pub(super) fn swipe(out: &mut Vec<Ev>, e: &Value, t: f64, pos: Pos) { + let dx = e["dx"].as_f64().unwrap_or(0.0) as f32; + let dy = e["dy"].as_f64().unwrap_or(0.0) as f32; + let dur = e["dur"].as_f64().unwrap_or(0.2).max(0.01); + out.push(Ev { t, kind: Kind::Move, pos: pos.clone() }); + let steps = (dur * 120.0).ceil() as usize; + let mut prev = (0.0, 0.0); + for s in 1..=steps { + let f = s as f32 / steps as f32; + let f = f * (2.0 - f); + out.push(Ev { t: t + dur * s as f64 / steps as f64, kind: Kind::Wheel(dx * f - prev.0, dy * f - prev.1), pos: pos.clone() }); + prev = (dx * f, dy * f); + } + if e["fling"].as_bool().unwrap_or(false) { + let v = |d: f32| 2.0 * d / dur as f32 * 0.25; + out.push(Ev { t: t + dur + 1e-4, kind: Kind::Fling(v(dx), v(dy)), pos }); + } +} + +/// `{"type": "resize", "dw": …, "dh": …, "dur": …}`: a person dragging the window's corner, one +/// viewport step a frame on a smoothstep hand, as a live resize delivers it. +pub(super) fn resize(out: &mut Vec<Ev>, e: &Value, t: f64) { + let d = |k: &str| e[k].as_f64().unwrap_or(0.0) as f32; + let dur = e["dur"].as_f64().unwrap_or(0.3).max(0.01); + let steps = (dur * 120.0).ceil() as usize; + for s in 0..=steps { + let f = s as f32 / steps as f32; + let f = f * f * (3.0 - 2.0 * f); + out.push(Ev { t: t + dur * s as f64 / steps as f64, kind: Kind::Resize(d("dw") * f, d("dh") * f), pos: Pos::Rel(0.0, 0.0) }); + } +} + +/// One step of a scripted resize: (0, 0) marks where it starts, and content follows at once. +pub(crate) fn step_resize(rt: &mut RuntimeCore, from: &mut (f32, f32), (dw, dh): (f32, f32), scale: f32) { + if (dw, dh) == (0.0, 0.0) { *from = rt.window_viewport(); } + rt.set_viewport(((from.0 + dw).max(1.0), (from.1 + dh).max(1.0)), scale); +} diff --git a/app/vendor/rune/crates/rune/src/tooling/headless.rs b/app/vendor/rune/crates/rune/src/tooling/headless.rs new file mode 100644 index 0000000..f6d0356 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/tooling/headless.rs @@ -0,0 +1,594 @@ +//! Offscreen deterministic frame loop, timeline resolution and `--chrome` traffic-light checks. + +use std::sync::Arc; + +use crate::app::SharedCore; +use crate::render::{Gpu, OFFSCREEN_FORMAT, Offscreen, Renderer}; +use crate::runtime::RuntimeCore; +use crate::time::Instant; + +use super::*; + +#[path = "headless/app.rs"] +mod app; +#[path = "headless/frame.rs"] +mod frame; +use app::{HeadlessApp, TypedHeadlessApp}; +pub(in crate::tooling) use frame::{step_window_frame, take_window_frame}; +use frame::{HeadlessFrame, HeadlessLoop}; + +#[cfg(test)] +pub(crate) use crate::render::surface_alpha::straight_alpha; + +struct HeadlessPrep { + source: Option<Value>, + script: Vec<Ev>, + timeline: Timeline, + scale: f32, + size: (f32, f32), + dark: bool, + writer: crate::tooling::record::Writer, +} + +impl HeadlessPrep { + fn begin(args: &Args, spec_size: (f32, f32)) -> Self { + crate::tooling::interaction::gate::headless(); + let source = read_script(args); + let script = source.as_ref().map(load_script).unwrap_or_default(); + let timeline = Timeline::of(args, &script).unwrap_or_else(|e| die(&e)); + let scale = args.scale.unwrap_or(2.0); + let size = args.size.unwrap_or(spec_size); + // Check the encoder before app initialization or GPU work. + let mut writer = crate::tooling::record::Writer::new(((size.0 * scale).round() as u32, (size.1 * scale).round() as u32)); + if let Some(path) = &args.video { + writer.video(path, timeline.fps).unwrap_or_else(|e| die(&e)); + } + crate::tooling::headless_run::publish(crate::tooling::headless_run::HeadlessRun { + script: args.script.clone(), + events: script.iter().map(Ev::public).collect(), + scale, + fps: timeline.fps, + size, + start: timeline.start_frame as f64 * timeline.dt, + frames: timeline.frames, + end: timeline.last_frame as f64 * timeline.dt, + desktop: None, + windows: Default::default(), + }); + let dark = args.theme.as_deref() != Some("light"); + Self { source, script, timeline, scale, size, dark, writer } + } +} + +struct HeadlessConfig { + launched: Instant, + state_ms: f64, + args: Args, + transparent: bool, + chrome: Chrome, + titlebar: Option<crate::Titlebar>, + fit_height: bool, + app_options: crate::WindowOptions, + min_size: Option<(f32, f32)>, + on_ready: Option<crate::app::OnWindow>, + on_frame_encoded: Option<crate::frame::encoded::OnFrameEncoded>, + shared_core: Arc<SharedCore>, + shortcuts_core: Arc<crate::shortcuts::HubCore>, + shortcuts: crate::shortcuts::Guard, + menus: crate::native_menu::MenuGuard, +} + +fn wait_for_profiler() -> Instant { + // RUNE_HEADLESS_WAIT=SECS holds the run before it starts, so a sampling profiler can attach. + #[cfg(not(target_arch = "wasm32"))] + if let Some(secs) = rune_core::env::var("RUNE_HEADLESS_WAIT").and_then(|s| s.parse::<f64>().ok()) { + std::thread::sleep(std::time::Duration::from_secs_f64(secs)); + } + crate::time::now() +} + +fn single_window_list_only(args: &Args) -> bool { + if args.list_windows { println!("main"); return true; } + if args.window.as_deref().is_some_and(|key| key != "main") { + die("no such window; this app has only 'main'"); + } + false +} + +fn try_headless_multi(main: crate::AnyWindowSpec, windows: Vec<crate::AnyWindowSpec>, args: Args, accessory: bool) -> Result<(), String> { + let displays = desktop(&args, read_script(&args).as_ref()).displays(); + headless_window(std::iter::once(main).chain(windows).collect(), &displays, args, crate::RunOptions { accessory }) +} + +pub fn headless<S: 'static>(app: crate::app::App<S>, args: Args) { + started(try_headless(app, args)); +} + +/// `headless`, returning the error when a window whose own arguments aren't headless can't open. +pub(crate) fn try_headless<S: 'static>(mut app: crate::app::App<S>, args: Args) -> Result<(), String> { + crate::render::discard_prewarm(); + if args.html.is_some() { return crate::tooling::html::export(app, &args); } + if app.windows.is_empty() && args.desktop.is_none() { + if single_window_list_only(&args) { return Ok(()); } + let scale = args.scale.unwrap_or(2.0); + let options = app.window_options.clone(); + headless_window_spec(app, options, args, scale); + return Ok(()); + } + let windows = std::mem::take(&mut app.windows); + let accessory = app.accessory; + let main = crate::WindowSpec::from_app("main", app).into(); + try_headless_multi(main, windows, args, accessory) +} + +pub(crate) fn headless_window_spec<S: 'static>(mut app: crate::app::App<S>, options: crate::WindowOptions, args: Args, scale: f32) { + if let Some((w, h)) = options.physical_size { + app.spec.size = (w as f32 / scale, h as f32 / scale); + } + let transparent = options.transparent; + app.window_options = options; + headless_configured(app, args, transparent); +} + +pub(crate) fn headless_configured<S: 'static>(mut app: crate::app::App<S>, args: Args, transparent: bool) { + let launched = wait_for_profiler(); + if args.list_scenes { + for (n, _) in app.spec.scenes { println!("{n}"); } + return; + } + #[cfg(feature = "hot")] + if args.snap_on_patch.is_some() { + return crate::hot::snap_window(app, args); + } + let prep = HeadlessPrep::begin(&args, app.spec.size); + let (chrome, titlebar, fit_height) = (app.chrome, app.titlebar, app.fit_content_height); + let app_options = app.window_options.clone(); + let comp = app.compositor.take(); + let (on_reopen, on_open_url) = (app.on_reopen, app.on_open_url); + let on_ready = app.on_ready.take(); + let on_frame_encoded = app.on_frame_encoded.take(); + let (playground, attach_playground) = (app.playground.take(), app.attach_playground); + let (spec, state, shared, runtime) = app.into_parts(args.scene.as_deref()); + let shortcuts = crate::shortcuts::Guard::attach(&shared, Arc::new(|| {}), true, false); + let menus = crate::native_menu::MenuGuard::attach(&shared, true); + let state_ms = launched.elapsed().as_secs_f64() * 1000.0; + let mut rt = runtime_for(&spec, state, prep.size, Env::new(prep.dark, prep.scale), Arc::new(|| {})); + if let Some(attach) = attach_playground { + attach(&mut rt, playground, &spec, args.playground.clone(), args.variant.clone(), false); + } + rt.configure(runtime); + let config = HeadlessConfig { + launched, state_ms, args, transparent, chrome, titlebar, fit_height, app_options, + min_size: spec.min_size, on_ready, on_frame_encoded, + shared_core: shared.core.clone(), shortcuts_core: shared.shortcuts.core.clone(), shortcuts, menus, + }; + let mut typed = TypedHeadlessApp { rt, shared, comp, on_reopen, on_open_url }; + run_headless(prep, config, &mut typed); +} + +fn run_headless(prep: HeadlessPrep, config: HeadlessConfig, app: &mut dyn HeadlessApp) { + let HeadlessPrep { source, script, timeline, scale, size, dark, mut writer } = prep; + let HeadlessConfig { + launched, state_ms, args, transparent, chrome, titlebar, fit_height, app_options, + min_size, on_ready, on_frame_encoded, shared_core, shortcuts_core, shortcuts, mut menus, + } = config; + // A `--realtime` run stands in for a window, so it starts the app's live work as one does. + let mut on_ready = on_ready.filter(|_| args.realtime); + let mut reports = crate::frame::encoded::FrameReports::new(on_frame_encoded, Some("main")); + let chrome = app.rt_mut().headless_chrome(chrome, titlebar, app_options.borderless); + app.rt_mut().transparent = transparent; + app.rt_mut().host.fit_height = fit_height; + if let Some(bars) = args.scroll_bars { app.rt_mut().set_system_scroll_bars(bars); } + // Only limits the app set: the canvas opens at any size, below the default minimum too. + let limits = (app_options.min_size.or(min_size).unwrap_or((0.0, 0.0)), app_options.max_size); + if fit_height { + let height = crate::window::frame::clamp_size((size.0, app.content_height()), limits.0, limits.1).1; + app.rt_mut().set_viewport((size.0, height), scale); + } + if args.tree.is_some() { app.rt_mut().commit.enable_key_warnings(); } + let has_comp = app.has_compositor(); + app.rt_mut().track_marks = has_comp; + let runtime_ms = launched.elapsed().as_secs_f64() * 1000.0 - state_ms; + + let desktop = desktop(&args, source.as_ref()); + let opened = desktop.open_at(app_options.position, size); + app.rt_mut().set_window_origin((opened[0], opened[1])); + let Timeline { fps, dt, start_frame, frames, snap_frame, last_frame } = timeline; + reports.set_refresh(Some(fps)); + + let t0 = crate::time::now(); + let features = app.compositor_features(); + let gpu = Gpu::try_with_features(Gpu::instance_for(features), None, features).unwrap_or_else(|e| die(&e)); + let srgb_blend = app.rt().srgb_blend(); + let target_format = if srgb_blend { OFFSCREEN_FORMAT.remove_srgb_suffix() } else { OFFSCREEN_FORMAT }; + let mut renderer = Renderer::new(&gpu.device, target_format); + renderer.set_srgb_blend(srgb_blend); + renderer.attach_text(&mut app.rt_mut().text.atlas); + let (wp, hp) = ((size.0 * scale).round() as u32, (size.1 * scale).round() as u32); + let target = Offscreen::with_format(&gpu.device, wp, hp, target_format); + let readback = crate::tooling::record::Readback::new(&gpu.device, &target, crate::tooling::record::DEPTH); + let alpha = transparent.then(|| crate::render::surface_alpha::AlphaSurface::new(&gpu.device, target_format, (wp, hp))); + let overlay = (args.keys.is_some() || args.pointer).then(|| { + let mut ov = crate::input::keycaps::Overlay::new(size, scale, args.keys, args.keys_theme, args.pointer); + ov.set_srgb_blend(srgb_blend); + let mut ui = Renderer::new(&gpu.device, target_format); + ui.set_srgb_blend(srgb_blend); + (ov, ui) + }); + let init_ms = t0.elapsed().as_secs_f64() * 1000.0; + + let trace = args.trace.as_ref().map(|p| { + let mut trace = Trace::open(p, size, fps, scale); + trace.all = args.trace_all; + trace + }); + app.rt_mut().frame.enable_trace_channels(trace.is_some()); + let gate_out = std::env::var_os("RUNE_MOTION_GATE").map(std::path::PathBuf::from); + let gate = gate_out.as_ref().map(|_| app.new_gate(fps as f64)); + app.rt_mut().scene.store_mut().audit_retargets(trace.is_some()); + let mut strip: Vec<Vec<u8>> = Vec::new(); + let crops_px: Vec<[u32; 4]> = args.crops.iter().map(|c| c.map(|v| (v * scale).round() as u32)).collect(); + let gap = (4.0 * scale) as u32; + let wall = crate::time::now(); + let mut next_ev = 0; + let mut last_down = (0.0f32, 0.0f32); + // Events at t = 0 find keys and hit elements in a laid-out first frame, as input reaches a + // real window only once it has drawn. That frame mounts the initial state with any queued + // updates; frame 0 then draws the events' effects. + let take_requests = |app: &mut dyn HeadlessApp, menus: &mut crate::native_menu::MenuGuard| { + shortcuts.drain(); + let requests = shared_core.take_window(); + menus.drain(); + let _receiving = shortcuts.receiving(); + app.drain_updates(menus); + if let Some(p) = requests.position { app.rt_mut().set_window_origin(desktop.to_points(p)); } + requests.place + }; + let mut frames_written = 0usize; + let has_video = writer.has_video(); + let snap_crop = std::cell::Cell::new(None::<[u32; 4]>); + let cpu_boot = std::cell::RefCell::new(args.cpu_boot.clone().map(|dir| crate::render::cpu_boot::tool::Tool::new(dir, args.cpu_boot_threads, gpu.adapter.get_info().vendor))); + // Finished readbacks, in frame order. + let mut deliver = |shot: Shot, mut px: Vec<u8>| { + if shot.snap && let Some(tool) = cpu_boot.borrow_mut().as_mut() { tool.gpu(&px, (wp, hp)); } + if args.chrome_overlay + && let Some(lights) = chrome.traffic_light_rects() + { + paint_traffic_lights(&mut px, wp, hp, scale, &lights); + } + if shot.dump { + if args.strip.is_some() { + strip.push(tile(&px, wp, hp, &crops_px, gap)); + } + if let Some(dir) = &args.out { + writer.png(dir.join(format!("frame_{:04}.png", shot.k - start_frame)), px.clone()).unwrap_or_else(|e| die(&e)); + } + } + if shot.snap && let (Some(path), Some(r)) = (&args.snap, snap_crop.get()) { + write_png(path, r[2], r[3], &crop::crop(&px, wp, r)).unwrap_or_else(|e| die(&format!("{}: {e}", path.display()))); + } else if shot.snap { + writer.png(args.snap.clone().unwrap(), px.clone()).unwrap_or_else(|e| die(&e)); + } + if shot.video { + frames_written += 1; + writer.frame(px).unwrap_or_else(|e| die(&e)); + } + }; + let mut state = HeadlessLoop { + launched, + state_ms, + runtime_ms, + init_ms, + args: &args, + chrome, + dark, + scale, + size, + wp, + hp, + limits, + has_comp, + has_video, + start_frame, + frames, + snap_frame, + dt, + shared_core: &shared_core, + desktop: &desktop, + gpu: &gpu, + target_format, + renderer, + target, + readback, + alpha, + overlay, + reports, + trace, + gate, + frame_anim: None, + // As on macOS, a frame change asked for while nothing moves waits a frame to start. + idle: true, + early_place: None, + placed: None, + snap_crop: &snap_crop, + cpu_boot: &cpu_boot, + loop_check: super::loop_check::Tally::default(), + cpu_ms: Vec::new(), + anim_ms: Vec::new(), + rest_ms: Vec::new(), + #[cfg(feature = "frame-profile")] + profile: crate::frame::profile::Log::new(last_frame + 1), + }; + let mut resize_from = app.rt().window_viewport(); + if script.iter().find(|e| !matches!(e.kind, Kind::Mark(_))).is_some_and(|e| e.t <= 1e-9) { + state.early_place = take_requests(app, &mut menus); + app.frame(0.0); + app.open_popup_headless(); + } + + for k in 0..=last_frame { + #[cfg(feature = "frame-profile")] + let (alloc0, commits0, cpu0) = { + crate::frame::profile::take(); + (procwatch::alloc::thread_allocations(), app.rt().stats.commits, crate::frame::profile::cpu_ms()) + }; + let real_t = k as f64 * dt; + #[cfg(not(target_arch = "wasm32"))] + if args.realtime { + let ahead = real_t - wall.elapsed().as_secs_f64(); + if ahead > 0.0 { std::thread::sleep(std::time::Duration::from_secs_f64(ahead)); } + } + let frame_start = crate::time::now(); + let script_before = next_ev; + #[cfg(feature = "frame-profile")] + let events0 = next_ev; + while next_ev < script.len() && script[next_ev].t <= real_t + 1e-9 { + let e = &script[next_ev]; + next_ev += 1; + if let Some(g) = state.gate.as_mut() && !matches!(e.kind, Kind::Mark(_)) { g.input("script"); } + let (x, y) = match &e.pos { + // A script's points are the window's; the view's are over its zoom. + Pos::Xy(x, y) => (*x / app.rt().zoom(), *y / app.rt().zoom()), + Pos::Key(key) => app.rt().find(key).unwrap_or_else(|| die(&format!("script: no element with key {key:?}"))), + Pos::Rel(_, _) if e.kind.at_pointer() => app.rt().pointer().unwrap_or((0.0, 0.0)), + Pos::Rel(dx, dy) => (last_down.0 + dx, last_down.1 + dy), + }; + match &e.kind { + Kind::Mark(name) if args.realtime => { + use std::io::Write as _; + println!("rune-mark {name} {}", e.t); + std::io::stdout().flush().ok(); + } + Kind::Mark(_) => {} + // The one window always shows here. + Kind::Reopen => app.run_reopen(), + Kind::OpenUrl(url) => app.run_open_url(url), + Kind::Shortcut(shortcut) => shortcuts_core.fire(shortcut).unwrap_or_else(|e| die(&format!("script shortcut: {e}"))), + Kind::Menu(item) => menus.fire(item).unwrap_or_else(|e| die(&format!("script menu: {e}"))), + Kind::PopupMenu(picked) => app.resolve_popup(picked.as_deref()).unwrap_or_else(|e| die(&format!("script pop-up menu: {e}"))), + Kind::FileDialog(path) => app.rt_mut().resolve_file_dialog(path.clone()).unwrap_or_else(|e| die(&format!("script file dialog: {e}"))), + &Kind::Resize(dw, dh) => eased_input::step_resize(app.rt_mut(), &mut resize_from, (dw, dh), scale), + kind => { + if kind.is_down() { last_down = (x, y); } + app.script_input(kind, (x, y)); + } + } + if let Some((ov, _)) = state.overlay.as_mut() { + match &e.kind { + Kind::Key(key, _) | Kind::PhysicalKey(_, key, _) => ov.key(e.t, key), + Kind::Shortcut(chord) => ov.chord(e.t, chord), + &Kind::Physical(crate::PhysicalInput::Key { key, mods, pressed: true, .. }) => { + if let Ok(chord) = crate::Shortcut::from_physical_key(key, mods) { ov.chord(e.t, &chord) } + } + Kind::Down => ov.press(e.t, x, y), + _ => {} + } + } + } + // Frame 0 has drawn: a window runs `on_ready` after its first frame. + if k == 1 && let Some(mut ready) = on_ready.take() { ready(&crate::WindowHandle::new("main")); } + let requested_place = take_requests(app, &mut menus); + let mut host = HeadlessFrame { + state: &mut state, + app, + deliver: &mut deliver, + k, + real_t, + frame_start, + script_had_events: next_ev != script_before, + requested_place, + want_pixels: false, + first_pixels: false, + encoded_stamp: None, + #[cfg(feature = "frame-profile")] + fp_alloc0: alloc0, + #[cfg(feature = "frame-profile")] + fp_commits0: commits0, + #[cfg(feature = "frame-profile")] + fp_cpu0: cpu0, + #[cfg(feature = "frame-profile")] + fp_events: next_ev - events0, + }; + crate::frame::host_step::run(&mut host); + } + for (shot, px) in state.readback.finish(&gpu.device) { deliver(shot, px); } + app.rt_mut().interaction_flush(); + drop(deliver); + let written = frames_written; + if let Some(video) = writer.finish().unwrap_or_else(|e| die(&e)) { + eprintln!("rune: wrote {} ({written} frames at {fps} fps)", video.display()); + } + rune_gpu::health::poll(&gpu.device, wgpu::PollType::wait_indefinitely()).ok(); + + if let Some(p) = &args.strip { write_strip(p, &strip, (wp, hp), &crops_px, gap, args.cols); } + if let (Some(g), Some(p)) = (state.gate, &gate_out) { + crate::motion_gate::evidence("", &g.rec, Some(p.display().to_string())); + let text: String = crate::motion_gate::check(&g.rec).iter().map(|f| format!("{f}\n")).collect(); + std::fs::write(p, text).unwrap_or_else(|e| die(&format!("{}: {e}", p.display()))); + } + + if frames > 0 { + let wall = wall.elapsed().as_secs_f64(); + eprintln!("rune: {} frames in {wall:.2} s wall ({:.1} frames/s)", last_frame + 1, (last_frame + 1) as f64 / wall); + } + let loop_checked = state.loop_check.report(); + let q = |v: &mut Vec<f64>, p: f64| { + v.sort_by(f64::total_cmp); + if v.is_empty() { 0.0 } else { v[((v.len() - 1) as f64 * p).round() as usize] } + }; + let mut sorted = state.cpu_ms.clone(); + #[cfg(feature = "frame-profile")] + state.profile.report(); + let steady: Vec<f64> = state.cpu_ms.iter().skip(1).copied().collect(); + let mean = if steady.is_empty() { state.cpu_ms[0] } else { steady.iter().sum::<f64>() / steady.len() as f64 }; + eprintln!( + "rune: {} frames at {fps} fps, gpu init {init_ms:.1} ms, first frame {:.2} ms, frame cpu mean {mean:.3} ms p50 {:.3} p95 {:.3} max {:.3}, {} instances", + state.cpu_ms.len(), + state.cpu_ms[0], + q(&mut sorted, 0.5), + q(&mut sorted, 0.95), + q(&mut sorted, 1.0), + app.rt().instances.len() + ); + let (a50, a95) = (q(&mut state.anim_ms, 0.5), q(&mut state.anim_ms, 0.95)); + let (r50, r95) = (q(&mut state.rest_ms, 0.5), q(&mut state.rest_ms, 0.95)); + eprintln!( + "rune: animating frames {} (cpu p50 {a50:.3} p95 {a95:.3} ms), at-rest frames {} (the window draws none; forced cpu p50 {r50:.3} p95 {r95:.3} ms), layout nodes {}, glyphs {}", + state.anim_ms.len(), + state.rest_ms.len(), + app.rt().stats.layout_nodes, + app.rt().stats.glyphs + ); + if let Some(s) = app.compositor_summary(&gpu.device) { + eprintln!("{s}"); + } + // A headless run opens no links (`Tx::open_url`): say which its handlers asked for. + for url in app.rt_mut().host.take_url_requests() { + eprintln!("rune: open_url {url} (headless: not opened)"); + } + if !loop_checked { std::process::exit(3); } +} + +/// Which frames a headless run renders and dumps. +#[derive(Clone, Copy, Debug, PartialEq)] +pub(crate) struct Timeline { + pub fps: f64, + pub dt: f64, + pub start_frame: usize, + /// Frames dumped from `start_frame` (0 when nothing is dumped). + pub frames: usize, + pub snap_frame: usize, + pub last_frame: usize, +} + +impl Timeline { + pub(crate) fn of(args: &Args, script: &[Ev]) -> Result<Timeline, String> { + let mark = |name: &str| script.iter().find_map(|e| matches!(&e.kind, Kind::Mark(n) if n == name).then_some(e.t)); + let resolve = |spec: &String| { + // Exact names win over offsets, including names such as "step-1" or "end+0.5". + if let Some(t) = mark(spec) { return Ok(t); } + let names: Vec<_> = script.iter().filter_map(|e| match &e.kind { Kind::Mark(n) => Some(n.as_str()), _ => None }).collect(); + let known = if names.is_empty() { "none".into() } else { names.join(", ") }; + // Only a complete numeric suffix is an offset. Starting at the first valid sign + // keeps a scientific exponent's sign inside the number (end-1e-3). + for (i, _) in spec.char_indices().skip(1).filter(|&(_, c)| c == '+' || c == '-') { + if let Ok(offset) = spec[i..].parse::<f64>() && offset.is_finite() { + let name = &spec[..i]; + return mark(name).map(|t| (t + offset).max(0.0)) + .ok_or_else(|| format!("no mark {name:?} in the script (marks: {known})")); + } + } + if spec.contains(['+', '-']) { + Err(format!("invalid mark time {spec:?}: expected an exact mark name or NAME+SECONDS/NAME-SECONDS (marks: {known})")) + } else { + Err(format!("no mark {spec:?} in the script (marks: {known})")) + } + }; + let fps = args.fps.max(1.0); + let dt = 1.0 / fps; + let start = args.start_mark.as_ref().map_or(Ok(args.start), resolve)?; + let at = args.at_mark.as_ref().map(resolve).transpose()?.or(args.at); + let start_frame = (start * fps).round() as usize; + let script_end = script.last().map_or(0.0, |e| e.t); + // Output without a length runs to the `end` mark, or one second after the script. + let until = |t: f64| ((t * fps).round() as usize).saturating_sub(start_frame) + 1; + let auto = || until(mark("end").unwrap_or(script_end + 1.0)); + let frames = args.frames.unwrap_or_else(|| match (args.duration, args.video.is_some() || args.out.is_some()) { + (Some(Length::Seconds(d)), _) => (d * fps).round().max(1.0) as usize, + (Some(Length::Auto), _) | (None, true) => auto(), + (None, false) => 0, + }); + let snap_t = at.unwrap_or(if frames > 0 { + (start_frame + frames - 1) as f64 * dt + } else if script.is_empty() { + 0.0 + } else { + script_end + 1.0 + }); + let snap_frame = (snap_t * fps).round() as usize; + let last_frame = snap_frame.max(start_frame + frames.max(1) - 1); + Ok(Timeline { fps, dt, start_frame, frames, snap_frame, last_frame }) + } +} + +/// A frame whose pixels are being read back, and where they go. +#[derive(Clone, Copy, Debug, PartialEq)] +pub(crate) struct Shot { + pub k: usize, + pub dump: bool, + pub video: bool, + pub snap: bool, +} + +/// Antialiased discs where macOS draws close, minimise and zoom, plus a hairline box 4 pt +/// around them (the clearance an app should keep). +fn paint_traffic_lights(px: &mut [u8], w: u32, h: u32, scale: f32, lights: &[[f32; 4]; 3]) { + const COLORS: [[f32; 3]; 3] = [[255.0, 95.0, 87.0], [254.0, 188.0, 46.0], [40.0, 200.0, 64.0]]; + let mut blend = |x: i64, y: i64, c: [f32; 3], a: f32| { + if x < 0 || y < 0 || x >= i64::from(w) || y >= i64::from(h) || a <= 0.0 { + return; + } + let i = ((y as u32 * w + x as u32) * 4) as usize; + for k in 0..3 { + px[i + k] = (f32::from(px[i + k]) * (1.0 - a) + c[k] * a).round() as u8; + } + }; + for (r, c) in lights.iter().zip(COLORS) { + let (cx, cy, rad) = ((r[0] + r[2] / 2.0) * scale, (r[1] + r[3] / 2.0) * scale, r[2] / 2.0 * scale); + for y in (cy - rad - 1.0) as i64..=(cy + rad + 1.0) as i64 { + for x in (cx - rad - 1.0) as i64..=(cx + rad + 1.0) as i64 { + let d = ((x as f32 + 0.5 - cx).powi(2) + (y as f32 + 0.5 - cy).powi(2)).sqrt(); + blend(x, y, c, (rad - d + 0.5).clamp(0.0, 1.0)); + } + } + } + let m = 4.0; + let (x0, y0) = ((lights[0][0] - m) * scale, (lights[0][1] - m) * scale); + let (x1, y1) = ((lights[2][0] + lights[2][2] + m) * scale, (lights[2][1] + lights[2][3] + m) * scale); + let cyan = [0.0, 200.0, 255.0]; + for x in x0 as i64..=x1 as i64 { + blend(x, y0 as i64, cyan, 0.8); + blend(x, y1 as i64, cyan, 0.8); + } + for y in y0 as i64..=y1 as i64 { + blend(x0 as i64, y, cyan, 0.8); + blend(x1 as i64, y, cyan, 0.8); + } +} + +/// Lists visible text, icons and controls whose drawn rect comes within 4 pt of a traffic light. +fn report_traffic_light_overlaps(rt: &RuntimeCore, lights: &[[f32; 4]; 3]) { + let m = 4.0; + let zone = [lights[0][0] - m, lights[0][1] - m, lights[2][0] + lights[2][2] + m, lights[2][1] + lights[2][3] + m]; + let mut n = 0; + for e in rt.elements() { + let drawn = e.text.is_some() || matches!(e.role, "icon" | "button" | "textbox"); + let v = e.visible; + let (x1, y1) = (v[0] + v[2], v[1] + v[3]); + if drawn && e.opacity > 0.01 && v[2] > 0.0 && v[3] > 0.0 && v[0] < zone[2] && x1 > zone[0] && v[1] < zone[3] && y1 > zone[1] { + eprintln!("rune: chrome: {} overlaps the traffic lights at {:?}", e.path, e.visible.map(r2)); + n += 1; + } + } + eprintln!("rune: chrome: traffic lights at {:?}, {n} overlapping elements", lights[0].map(r2)); +} diff --git a/app/vendor/rune/crates/rune/src/tooling/headless/app.rs b/app/vendor/rune/crates/rune/src/tooling/headless/app.rs new file mode 100644 index 0000000..a634097 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/tooling/headless/app.rs @@ -0,0 +1,122 @@ +//! Non-generic boundary between the headless frame loop and the typed `Runtime<S>`, +//! `Shared<S>`, `Compositor<S>` and lifecycle hooks. + +use std::sync::Arc; + +use crate::app::Shared; +use crate::compose::{Compositor, Frame}; +use crate::el::Tx; +use crate::render::Renderer; +use crate::runtime::{AppDriver, Runtime, RuntimeCore}; +use crate::tooling::{Kind, script_input}; + +pub(super) struct HeadlessRenderArgs<'a> { + pub device: &'a wgpu::Device, + pub queue: &'a wgpu::Queue, + pub encoder: &'a mut wgpu::CommandEncoder, + pub target: &'a wgpu::TextureView, + pub format: wgpu::TextureFormat, + pub size: (u32, u32), + pub dt: f64, + pub update_ms: f64, + pub ui: &'a mut Renderer, +} + +pub(super) trait HeadlessApp { + fn rt(&self) -> &RuntimeCore; + fn rt_mut(&mut self) -> &mut RuntimeCore; + fn with_driver(&mut self, f: &mut dyn FnMut(&mut RuntimeCore, &mut dyn AppDriver)); + fn run_reopen(&mut self); + fn run_open_url(&mut self, url: &str); + fn drain_updates(&mut self, menus: &mut crate::native_menu::MenuGuard); + fn has_compositor(&self) -> bool; + fn compositor_features(&self) -> wgpu::Features; + fn render_compositor(&mut self, args: HeadlessRenderArgs<'_>) -> bool; + fn compositor_summary(&mut self, device: &wgpu::Device) -> Option<String>; + fn new_gate(&mut self, hz: f64) -> crate::motion_gate::Sampler; + fn gate_before(&mut self, gate: &mut crate::motion_gate::Sampler); + fn gate_frame(&mut self, gate: &mut crate::motion_gate::Sampler, awake: bool); +} + +impl dyn HeadlessApp + '_ { + fn driver<R>(&mut self, f: impl FnOnce(&mut RuntimeCore, &mut dyn AppDriver) -> R) -> R { + let mut f = Some(f); + let mut out = None; + self.with_driver(&mut |core, app| { + out = Some(f.take().unwrap()(core, app)); + }); + out.unwrap() + } + + pub(super) fn content_height(&mut self) -> f32 { self.driver(|rt, app| rt.content_height(app)) } + pub(super) fn frame(&mut self, dt: f64) -> bool { self.driver(|rt, app| rt.frame(app, dt)) } + pub(super) fn open_popup_headless(&mut self) { self.driver(|rt, app| rt.open_popup_headless(app)); } + pub(super) fn resolve_popup(&mut self, picked: Option<&str>) -> Result<(), crate::PopupMenuError> { + self.driver(|rt, app| rt.resolve_popup(app, picked)) + } + pub(super) fn script_input(&mut self, kind: &Kind, at: (f32, f32)) { + self.driver(|rt, app| { script_input(rt, app, kind, at); }); + } +} + +pub(super) struct TypedHeadlessApp<S: 'static> { + pub(super) rt: Runtime<S>, + pub(super) shared: Arc<Shared<S>>, + pub(super) comp: Option<Box<dyn Compositor<S>>>, + pub(super) on_reopen: Option<fn(&mut S, bool, &mut Tx) -> bool>, + pub(super) on_open_url: Option<crate::open_url::incoming::OnOpenUrl<S>>, +} + +impl<S: 'static> HeadlessApp for TypedHeadlessApp<S> { + fn rt(&self) -> &RuntimeCore { self.rt.core() } + fn rt_mut(&mut self) -> &mut RuntimeCore { self.rt.core_mut() } + fn with_driver(&mut self, f: &mut dyn FnMut(&mut RuntimeCore, &mut dyn AppDriver)) { + let (core, mut driver) = self.rt.split_mut(); + f(core, &mut driver); + } + fn run_reopen(&mut self) { + if let Some(f) = self.on_reopen { self.rt.update(|s, tx| { f(s, true, tx); }); } + } + fn run_open_url(&mut self, url: &str) { + if let Some(f) = self.on_open_url { self.rt.update(|s, tx| f(s, url, tx)); } + } + fn drain_updates(&mut self, menus: &mut crate::native_menu::MenuGuard) { + for f in self.shared.take_updates() { + self.rt.update_if(f); + menus.drain(); + } + } + fn has_compositor(&self) -> bool { self.comp.is_some() } + fn compositor_features(&self) -> wgpu::Features { + self.comp.as_ref().map_or(wgpu::Features::empty(), |c| c.features()) + } + fn render_compositor(&mut self, args: HeadlessRenderArgs<'_>) -> bool { + let Some(c) = self.comp.as_mut() else { return false }; + let mut f = Frame { + device: args.device, + queue: args.queue, + encoder: args.encoder, + target: args.target, + format: args.format, + size: args.size, + dt: args.dt, + update_ms: args.update_ms, + rt: &mut self.rt, + ui: args.ui, + }; + c.render(&mut f); + c.animating() + } + fn compositor_summary(&mut self, device: &wgpu::Device) -> Option<String> { + self.comp.as_mut().and_then(|c| c.summary(device)) + } + fn new_gate(&mut self, hz: f64) -> crate::motion_gate::Sampler { + crate::motion_gate::Sampler::new(&mut self.rt, hz) + } + fn gate_before(&mut self, gate: &mut crate::motion_gate::Sampler) { + gate.before(&mut self.rt); + } + fn gate_frame(&mut self, gate: &mut crate::motion_gate::Sampler, awake: bool) { + gate.frame(&mut self.rt, awake); + } +} diff --git a/app/vendor/rune/crates/rune/src/tooling/headless/frame.rs b/app/vendor/rune/crates/rune/src/tooling/headless/frame.rs new file mode 100644 index 0000000..da0698c --- /dev/null +++ b/app/vendor/rune/crates/rune/src/tooling/headless/frame.rs @@ -0,0 +1,392 @@ +//! [`crate::frame::host_step::FrameHost`] adapter for the offscreen headless driver, plus the +//! shared `Tx::resize_window` frame-animation helpers used by both single-window headless runs +//! and the multi-window virtual desktop. + +use std::cell::{Cell, RefCell}; +use std::io::Write; +use std::sync::Arc; + +use serde_json::{Value, json}; + +use crate::app::SharedCore; +use crate::frame::clock::FrameClock; +use crate::frame::host_step::{ + Acquire, FrameHost, Gate, PostStepCheck, ReacquireReason, RenderPrep, StepInfo, + draw_ui, prepare_gpu_resources, +}; +use crate::render::{Gpu, OFFSCREEN_FORMAT, Offscreen, Renderer}; +use crate::runtime::RuntimeCore; +use crate::time::Instant; +use crate::tooling::{ + Args, Chrome, FrameTiming, Shot, Trace, crop, die, loop_check, tree_json_core, +}; + +use super::app::{HeadlessApp, HeadlessRenderArgs}; +use super::report_traffic_light_overlaps; + +pub(super) struct PreparedHeadlessFrame { + encoder: wgpu::CommandEncoder, + shot: Shot, +} + +/// Persistent offscreen rendering resources and frame-to-frame state owned by `run_headless`. +pub(super) struct HeadlessLoop<'a> { + pub(super) launched: Instant, + pub(super) state_ms: f64, + pub(super) runtime_ms: f64, + pub(super) init_ms: f64, + pub(super) args: &'a Args, + pub(super) chrome: Chrome, + pub(super) dark: bool, + pub(super) scale: f32, + pub(super) size: (f32, f32), + pub(super) wp: u32, + pub(super) hp: u32, + pub(super) limits: ((f32, f32), Option<(f32, f32)>), + pub(super) has_comp: bool, + pub(super) has_video: bool, + pub(super) start_frame: usize, + pub(super) frames: usize, + pub(super) snap_frame: usize, + pub(super) dt: f64, + pub(super) shared_core: &'a Arc<SharedCore>, + pub(super) desktop: &'a crate::desktop::displays::VirtualDesktop, + pub(super) gpu: &'a Gpu, + pub(super) target_format: wgpu::TextureFormat, + pub(super) renderer: Renderer, + pub(super) target: Offscreen, + pub(super) readback: crate::tooling::record::Readback<Shot>, + pub(super) alpha: Option<crate::render::surface_alpha::AlphaSurface>, + pub(super) overlay: Option<(crate::input::keycaps::Overlay, Renderer)>, + pub(super) reports: crate::frame::encoded::FrameReports, + pub(super) trace: Option<Trace>, + pub(super) gate: Option<crate::motion_gate::Sampler>, + pub(super) frame_anim: Option<crate::window::frame::FrameAnim>, + pub(super) idle: bool, + pub(super) early_place: Option<crate::windows::PlaceRequest>, + pub(super) placed: Option<Value>, + pub(super) snap_crop: &'a Cell<Option<[u32; 4]>>, + pub(super) cpu_boot: &'a RefCell<Option<crate::render::cpu_boot::tool::Tool>>, + pub(super) loop_check: loop_check::Tally, + pub(super) cpu_ms: Vec<f64>, + pub(super) anim_ms: Vec<f64>, + pub(super) rest_ms: Vec<f64>, + #[cfg(feature = "frame-profile")] + pub(super) profile: crate::frame::profile::Log, +} + +impl HeadlessLoop<'_> { + #[inline] + fn reblend_offscreen(&mut self, rt: &mut RuntimeCore) { + let rt_srgb = rt.srgb_blend(); + self.target_format = if rt_srgb { OFFSCREEN_FORMAT.remove_srgb_suffix() } else { OFFSCREEN_FORMAT }; + crate::window::rebuild_renderer_core(&self.gpu.device, &mut self.renderer, self.target_format, rt); + self.target = Offscreen::with_format(&self.gpu.device, self.wp, self.hp, self.target_format); + if self.alpha.is_some() { + self.alpha = Some(crate::render::surface_alpha::AlphaSurface::new(&self.gpu.device, self.target_format, (self.wp, self.hp))); + } + if let Some((ov, ui)) = self.overlay.as_mut() { + ov.set_srgb_blend(rt_srgb); + ui.set_format(&self.gpu.device, self.target_format); + } + } +} + +/// Per-frame borrow view driving one headless iteration through [`crate::frame::host_step::run`]. +pub(super) struct HeadlessFrame<'a, 'b, F> { + pub(super) state: &'a mut HeadlessLoop<'b>, + pub(super) app: &'a mut dyn HeadlessApp, + pub(super) deliver: &'a mut F, + pub(super) k: usize, + pub(super) real_t: f64, + pub(super) frame_start: Instant, + pub(super) script_had_events: bool, + pub(super) requested_place: Option<crate::windows::PlaceRequest>, + pub(super) want_pixels: bool, + pub(super) first_pixels: bool, + pub(super) encoded_stamp: Option<Instant>, + #[cfg(feature = "frame-profile")] + pub(super) fp_alloc0: u64, + #[cfg(feature = "frame-profile")] + pub(super) fp_commits0: u64, + #[cfg(feature = "frame-profile")] + pub(super) fp_cpu0: Option<f64>, + #[cfg(feature = "frame-profile")] + pub(super) fp_events: usize, +} + +impl<F: FnMut(Shot, Vec<u8>)> FrameHost for HeadlessFrame<'_, '_, F> { + type Drawable = (); + type Prepared = PreparedHeadlessFrame; + + #[inline] + fn gate(&mut self) -> Gate { Gate::Draw } + + #[inline] + fn before_acquire(&mut self) { + let s = &mut *self.state; + take_window_frame(self.app.rt_mut(), &mut s.frame_anim, self.real_t, s.limits); + if !s.idle { + step_window_frame(self.app.rt_mut(), &mut s.frame_anim, self.real_t, s.scale); + } + { + let rt = self.app.rt_mut(); + rt.host.window_resting = s.frame_anim.is_none() && rt.host.window_frame.is_none(); + } + if let Some(g) = s.gate.as_mut() { self.app.gate_before(g); } + } + + #[inline] + fn needs_reblend(&self) -> bool { + self.state.renderer.srgb_blend() != self.app.rt().srgb_blend() + } + + #[inline] + fn reblend(&mut self) -> bool { + self.state.reblend_offscreen(self.app.rt_mut()); + true + } + + #[inline] + fn acquire(&mut self) -> Acquire<()> { Acquire::Ready(()) } + + #[inline] + fn step_runtime(&mut self) -> StepInfo { + let s = &mut *self.state; + let step = if self.k == 0 { 0.0 } else { s.dt }; + // `RUNE_LOOP_CHECK=1`: every frame asks for a loop-only step first, and the step is + // compared with the ordinary frame that runs instead, or says why it wouldn't run. A + // window never asks after a script's kind of event (`LoopFrame::touched`); here the + // step's own refusal shows for those too, counted apart. + let asked = (self.app.rt().loop_check_on() && self.k > 0 && s.frame_anim.is_none()) + .then(|| self.app.rt_mut().loop_step(step)); + let animating = self.app.frame(step); + if let Some(asked) = asked { + s.loop_check.add(self.real_t, self.script_had_events, asked, self.app.rt_mut().loop_checked()); + } + StepInfo { + runtime_animating: animating, + animating, + dt: step, + update_ms: 0.0, + presents_at: None, + } + } + + #[inline] + fn post_step_check(&mut self, _info: &mut StepInfo) -> PostStepCheck { + if self.state.renderer.srgb_blend() != self.app.rt().srgb_blend() { + PostStepCheck::Reacquire(ReacquireReason::Reblend) + } else { + PostStepCheck::Keep + } + } + + #[inline] + fn prepare_reacquire(&mut self, reason: ReacquireReason, _info: &mut StepInfo) -> bool { + match reason { + ReacquireReason::Reblend => { + // `Tx::set_srgb_blend`: the same bytes (sRGB-encoded) reach the readback either way. + self.state.reblend_offscreen(self.app.rt_mut()); + true + } + #[cfg(any(test, target_os = "macos"))] + ReacquireReason::NativeMaterials => true, + } + } + + #[inline] + fn sync_after_step(&mut self, info: &mut StepInfo) { + let s = &mut *self.state; + self.app.open_popup_headless(); + // As on macOS, a frame change this commit asked for starts with the springs it + // started, which have shown a step unless they held for the window. + if self.app.rt().host.window_frame.is_some() { + let shown = if self.app.rt_mut().host.fit.take_held() { 0.0 } else { info.dt }; + take_window_frame(self.app.rt_mut(), &mut s.frame_anim, self.real_t - shown, s.limits); + } + s.idle = !info.runtime_animating && s.frame_anim.is_none(); + // Updates, poll and input handlers place too; the latest request this frame wins. + if let Some(place) = s.shared_core.take_place().or(self.requested_place.take()).or(s.early_place.take()) { + let (display, frame) = s.desktop.place(&place, s.size); + self.app.rt_mut().set_window_origin((frame[0], frame[1])); + let record = json!({ "t": self.real_t, "display": display, "frame": frame }); + println!("rune-placed {record}"); + s.placed = Some(record); + } + info.update_ms = self.frame_start.elapsed().as_secs_f64() * 1000.0; + if let Some(tool) = s.cpu_boot.borrow_mut().as_mut() { + tool.frame(self.app.rt_mut(), (s.wp, s.hp), self.k, (info.update_ms * 1e6) as u64, self.k == s.snap_frame); + } + } + + #[inline] + fn prepare_render(&mut self, _drawable: (), _info: &mut StepInfo) -> RenderPrep<PreparedHeadlessFrame> { + let s = &mut *self.state; + prepare_gpu_resources(&mut s.renderer, s.gpu, self.app.rt_mut(), (s.wp, s.hp), false); + let encoder = s.gpu.device.create_command_encoder(&Default::default()); + let in_range = self.k >= s.start_frame && self.k < s.start_frame + s.frames; + let shot = Shot { + k: self.k, + dump: in_range && (s.args.out.is_some() || s.args.strip.is_some()) && (self.k - s.start_frame).is_multiple_of(s.args.every), + video: in_range && s.has_video, + snap: self.k == s.snap_frame && s.args.snap.is_some(), + }; + let first_pixels = s.args.first_pixels && self.k == 0; + let want_pixels = shot.dump || shot.video || shot.snap || first_pixels; + self.want_pixels = want_pixels; + self.first_pixels = first_pixels; + RenderPrep::Ready(PreparedHeadlessFrame { encoder, shot }) + } + + #[inline] + fn render(&mut self, prepared: &mut PreparedHeadlessFrame, info: &StepInfo) -> bool { + let s = &mut *self.state; + let view = s.alpha.as_ref().map_or(&s.target.view, |a| &a.view); + let comp_animating = if s.has_comp { + self.app.render_compositor(HeadlessRenderArgs { + device: &s.gpu.device, + queue: &s.gpu.queue, + encoder: &mut prepared.encoder, + target: view, + format: s.target_format, + size: (s.wp, s.hp), + dt: info.dt, + update_ms: info.update_ms, + ui: &mut s.renderer, + }) + } else { + let rt = self.app.rt_mut(); + let clear = rt.clear_color(); + draw_ui(&mut s.renderer, s.gpu, &mut prepared.encoder, view, rt, (s.wp, s.hp), clear); + false + }; + if let Some((ov, ui)) = s.overlay.as_mut() { + let ort = ov.frame(self.real_t, info.dt, self.app.rt().backdrop_dark().unwrap_or(s.dark)); + if !ort.instances.is_empty() { + ui.set_fade_stops(ort.fade_stops()); + ui.prepare_ui(&s.gpu.device, &s.gpu.queue, &mut ort.text.atlas, &ort.instances, (s.wp, s.hp)); + ui.draw_over(&mut prepared.encoder, view); + } + } + if let Some(alpha) = &s.alpha { + alpha.draw(&mut prepared.encoder, &s.target.view); + } + if prepared.shot.snap { + s.snap_crop.set(crop::snap_rect(self.app.rt(), s.args, s.scale, (s.wp, s.hp))); + } + if self.want_pixels { + for (shot, px) in s.readback.make_room(&s.gpu.device) { (self.deliver)(shot, px); } + s.readback.copy(&mut prepared.encoder, &s.target, prepared.shot); + } + comp_animating + } + + #[inline] + fn submit_and_present(&mut self, prepared: PreparedHeadlessFrame, _info: &StepInfo) -> Instant { + let s = &mut *self.state; + s.renderer.submit(&s.gpu.queue, prepared.encoder); + self.encoded_stamp = s.reports.stamp(); + if self.want_pixels { s.readback.submitted(); } + crate::time::now() + } + + #[inline] + fn present_targets(&mut self) -> (Option<&mut FrameClock>, &mut RuntimeCore) { + (None, self.app.rt_mut()) + } + + #[inline] + fn settle(&mut self, _submitted: Instant, info: &StepInfo) { + let s = &mut *self.state; + s.reports.drawn(self.encoded_stamp, None, self.frame_start, info.update_ms); + let ms = self.frame_start.elapsed().as_secs_f64() * 1000.0; + #[cfg(feature = "frame-profile")] + { + let rt = self.app.rt_mut(); + s.profile.push(crate::frame::profile::Row { + phases: crate::frame::profile::take(), + update_ms: info.update_ms, + encode_ms: ms - info.update_ms, + events: self.fp_events, + allocations: procwatch::alloc::thread_allocations() - self.fp_alloc0, + commits: rt.stats.commits - self.fp_commits0, + why: rt.commit.take_commit_why(), + shaped: rt.stats.shaped, + animating: info.animating, + cpu_ms: self.fp_cpu0.map(|start| crate::frame::profile::cpu_ms().unwrap() - start), + }); + } + s.cpu_ms.push(ms); + if self.k > 0 { + if info.animating { s.anim_ms.push(ms) } else { s.rest_ms.push(ms) } + } + if s.has_comp { + // Pace like a display link so a compositor's async readbacks (GPU timers) land between frames. + rune_gpu::health::poll(&s.gpu.device, wgpu::PollType::wait_indefinitely()).ok(); + } + if let Some(tr) = s.trace.as_mut() { + tr.frame_timed_core(self.app.rt_mut(), self.real_t * 1000.0, ms, FrameTiming::default()); + } + if let Some(g) = s.gate.as_mut() { self.app.gate_frame(g, info.animating); } + if self.first_pixels { + let wait = crate::time::now(); + let done = s.readback.finish(&s.gpu.device); + let marker = json!({ + "headless_ms": s.launched.elapsed().as_secs_f64() * 1000.0, + "state_ms": s.state_ms, "runtime_ms": s.runtime_ms, "gpu_init_ms": s.init_ms, + "frame_cpu_ms": ms, "readback_ms": wait.elapsed().as_secs_f64() * 1000.0, + "pixel_bytes": done.last().map_or(0, |(_, px)| px.len()), + }); + println!("rune-first-pixels {marker}"); + std::io::stdout().flush().unwrap(); + for (shot, px) in done { (self.deliver)(shot, px); } + } else if self.want_pixels { + for (shot, px) in s.readback.ready(&s.gpu.device) { (self.deliver)(shot, px); } + } + if self.k == s.snap_frame + && s.args.chrome_overlay + && let Some(lights) = s.chrome.traffic_light_rects() + { + report_traffic_light_overlaps(self.app.rt(), &lights); + } + if self.k == s.snap_frame + && let Some(p) = &s.args.tree + { + let mut tree = tree_json_core(self.app.rt(), self.real_t); + if let Some(placed) = &s.placed { tree["placed"] = placed.clone(); } + let text = serde_json::to_string_pretty(&tree).unwrap(); + std::fs::write(p, text).unwrap_or_else(|e| die(&format!("{}: {e}", p.display()))); + } + } +} + +/// Takes the size handlers asked for a headless window, inside the limits the app set; its +/// viewport moves there on the virtual clock from `start`. Centring has nothing to centre on. +pub(in crate::tooling) fn take_window_frame( + rt: &mut RuntimeCore, + anim: &mut Option<crate::window::frame::FrameAnim>, + start: f64, + (min, max): ((f32, f32), Option<(f32, f32)>), +) { + use crate::window::frame::{FrameAnim, clamp_size}; + rt.host.fit.take_held(); + let Some(request) = rt.host.window_frame.take() else { return }; + let Some(size) = request.size else { return }; + let (w, h) = clamp_size(size, min, max); + let from = [0.0, 0.0, rt.window_viewport().0, rt.window_viewport().1]; + *anim = Some(FrameAnim::retarget(anim.as_ref(), request.spring, start, from, [0.0, 0.0, w, h])); +} + +/// Moves a headless window's viewport one frame along, before the frame lays out. +pub(in crate::tooling) fn step_window_frame( + rt: &mut RuntimeCore, + anim: &mut Option<crate::window::frame::FrameAnim>, + now: f64, + scale: f32, +) { + let Some(moving) = *anim else { return }; + let [_, _, w, h] = crate::window::frame::snap(moving.sample(now).0, scale); + rt.step_viewport((w, h), scale); + if moving.done(now) { *anim = None; } +} diff --git a/app/vendor/rune/crates/rune/src/tooling/headless_run.rs b/app/vendor/rune/crates/rune/src/tooling/headless_run.rs new file mode 100644 index 0000000..325c5e4 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/tooling/headless_run.rs @@ -0,0 +1,240 @@ +//! What a headless run was asked to do, for the app to read (`tooling::headless_run`). + +use std::path::{Path, PathBuf}; +use std::sync::RwLock; + +use crate::edit::KeyEvent; + +/// The headless run this process is rendering: its script, timing and output. One per run, +/// shared by every window, so a multi-window run reads the same timeline from each. +#[non_exhaustive] +#[derive(Clone, Debug)] +pub struct HeadlessRun { + pub(crate) script: Option<PathBuf>, + pub(crate) events: Vec<TimedEvent>, + pub(crate) scale: f32, + pub(crate) fps: f64, + pub(crate) size: (f32, f32), + pub(crate) start: f64, + pub(crate) frames: usize, + pub(crate) end: f64, + pub(crate) desktop: Option<PathBuf>, + pub(crate) windows: std::sync::Arc<std::sync::Mutex<Vec<WindowFrame>>>, +} + +/// Where a `--desktop` run drew one window from time `t` on. +#[non_exhaustive] +#[derive(Clone, Debug, PartialEq)] +pub struct WindowFrame { + pub t: f64, + pub key: String, + /// x, y, width, height in output points (script coordinates). + pub frame: [f32; 4], + pub visible: bool, + /// The key window, which script keys reach. + pub focused: bool, +} + +impl HeadlessRun { + /// The `--desktop` backdrop, when the run composites every window over it. + pub fn desktop(&self) -> Option<&Path> { self.desktop.as_deref() } + + /// A `--desktop` run's window frames so far: each window at the start, then one entry + /// whenever one moves, resizes, shows, hides or takes keys. Empty otherwise. + pub fn window_frames(&self) -> Vec<WindowFrame> { self.windows.lock().unwrap().clone() } + + /// Each window as it stands at time `t` in a `--desktop` run, in the order the app made them. + pub fn windows_at(&self, t: f64) -> Vec<WindowFrame> { + let frames = self.windows.lock().unwrap(); + let mut out: Vec<WindowFrame> = Vec::new(); + for f in frames.iter().filter(|f| f.t <= t + 1e-9) { + match out.iter_mut().find(|o| o.key == f.key) { + Some(o) => *o = f.clone(), + None => out.push(f.clone()), + } + } + out + } + + /// The `--script` file. + pub fn script(&self) -> Option<&Path> { self.script.as_deref() } + + /// The script's events in time order, expanded as Rune feeds them: a `tap` is a move, a + /// down and an up; `type` is one key per character at its `every` interval. + pub fn events(&self) -> &[TimedEvent] { &self.events } + + /// The script's `mark` events, in time order: (name, seconds). + pub fn marks(&self) -> impl Iterator<Item = (&str, f64)> { + self.events.iter().filter_map(|e| match &e.event { ScriptEvent::Mark(name) => Some((name.as_str(), e.t)), _ => None }) + } + + /// The time of the first mark called `name`. + pub fn mark(&self, name: &str) -> Option<f64> { self.marks().find(|(n, _)| *n == name).map(|(_, t)| t) } + + /// The time of the script's last event (marks included), or 0 without one. + pub fn script_end(&self) -> f64 { self.events.last().map_or(0.0, |e| e.t) } + + /// Device pixels per point (`--scale`, default 2). + pub fn scale(&self) -> f32 { self.scale } + + /// Frames per virtual second (`--fps`, default 60). + pub fn fps(&self) -> f64 { self.fps } + + /// The rendered window's viewport in points (`--size`, or the window's own size); the whole + /// output with `--desktop`. + pub fn size(&self) -> (f32, f32) { self.size } + + /// Seconds of virtual time at the first dumped frame (`--start`, marks resolved). + pub fn start(&self) -> f64 { self.start } + + /// Frames written to `--video` or `--out` (0 for a `--snap` or `--tree` run). + pub fn frames(&self) -> usize { self.frames } + + /// Seconds of virtual time at the last frame the run renders. + pub fn end(&self) -> f64 { self.end } +} + +/// A script event at its time in seconds. +#[non_exhaustive] +#[derive(Clone, Debug)] +pub struct TimedEvent { + pub t: f64, + pub event: ScriptEvent, +} + +/// One input (or marker) a script feeds the app. +#[non_exhaustive] +#[derive(Clone, Debug)] +pub enum ScriptEvent { + /// `{"type": "mark", "name": …}`: a named point in time with no input effect. + Mark(String), + /// A logical key; `repeat` is a held key's auto-repeat. + Key { key: KeyEvent, repeat: bool }, + /// `{"type": "key-up"}`: a logical key's release. + KeyUp(KeyEvent), + Paste(String), + /// `{"type": "ime", "preedit": ., "cursor": [a, b]}` or `{"type": "ime", "commit": .}`: what an input + /// method composes or commits, as the platform's IME hands it over. + Ime(crate::Ime), + /// A paste with HTML or RTF beside the text (`{"paste": {"text": …, "html": …}}`). + PasteContent(crate::ClipboardContent), + /// A registered global shortcut chord. Only its handler runs; it never reaches `on_key`. + Shortcut(crate::Shortcut), + /// A hardware key or modifier change (`{"physical": …}`). + Physical(crate::PhysicalInput), + Pointer { action: PointerAction, at: ScriptPoint }, + /// The window gaining (true) or losing focus. + Focus(bool), + /// `{"reopen": true}`: the app reopened, as a click on its macOS Dock icon does. + Reopen, + /// `{"open_url": …}`: a link the system opened with the app (`App::on_open_url`). + OpenUrl(String), + /// `{"type": "resize", "dw": …, "dh": …, "dur": …}`: a person resizing the window, one step + /// a frame, (dw, dh) points from its size when the resize began. + Resize { dw: f32, dh: f32 }, + /// A native menu item fired by name. + Menu(String), + /// A pop-up menu's picked item id, or None when the script dismisses it. + PopupMenu(Option<String>), + /// `{"type": "file-dialog", "path": …}`: the file chosen in the open file dialog, or None + /// for `{"type": "file-dialog-cancel"}`. + FileDialog(Option<std::path::PathBuf>), + /// `{"drag_files": …}`: a file drag from another app moved over the window. + DragFiles { paths: Vec<std::path::PathBuf>, at: ScriptPoint }, + /// `{"drop_files": …}`: files dropped on the window. + DropFiles { paths: Vec<std::path::PathBuf>, at: ScriptPoint }, + /// `{"drag_files": "leave"}`: the file drag left the window. + DragFilesLeave, +} + +#[non_exhaustive] +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum PointerAction { + Move, + Down, + Up, + SecondaryDown, + SecondaryUp, + /// A wheel or trackpad delta in points. + Scroll(f32), + /// A trackpad release velocity in points per second. + Fling(f32), + /// A wheel or trackpad delta (dx, dy) in points with a horizontal part. + ScrollXy(f32, f32), + /// A release velocity (vx, vy) in points per second with a horizontal part. + FlingXy(f32, f32), + /// `{"type": "wheel"}`: one wheel delta with its modifiers and phase. + Wheel(crate::WheelEvent), + /// `{"type": "magnify"}`: a trackpad pinch. + Magnify(crate::MagnifyEvent), + /// `{"type": "rotate"}`: a two-finger rotation. + Rotate(crate::RotateEvent), + /// `{"type": "smart-magnify"}`: a two-finger double tap. + SmartMagnify, + /// A press of a button besides the primary and secondary (`"button": "middle"`). + ButtonDown(crate::PointerButton), + ButtonUp(crate::PointerButton), +} + +/// Where a pointer event lands, as the script wrote it. +#[non_exhaustive] +#[derive(Clone, Debug, PartialEq)] +pub enum ScriptPoint { + /// Points from the window's top-left. + At(f32, f32), + /// The centre of the element with this key (or path suffix), found when the event runs. + Element(String), + /// An offset from the last pointer-down position (drags, the release of a tap). + FromDown(f32, f32), +} + +static RUN: RwLock<Option<&'static HeadlessRun>> = RwLock::new(None); + +/// The headless run this process is rendering, or None in a window. Set before the app's +/// state is created, so `init`, `setup`, views and handlers can read it; a `run_windows` +/// factory runs too early to see it. +pub fn headless_run() -> Option<&'static HeadlessRun> { + *RUN.read().unwrap_or_else(|e| e.into_inner()) +} + +/// Makes `run` the process's headless run. Each run leaks its small description so earlier +/// references stay valid; a process renders one run, or a few in tests. +pub(crate) fn publish(run: HeadlessRun) { + *RUN.write().unwrap_or_else(|e| e.into_inner()) = Some(Box::leak(Box::new(run))); +} + +#[cfg(test)] +mod tests { + use super::*; + + fn sample_run(scale: f32, fps: f64, size: (f32, f32)) -> HeadlessRun { + HeadlessRun { + script: None, + events: Vec::new(), + scale, + fps, + size, + start: 0.0, + frames: 0, + end: 0.0, + desktop: None, + windows: std::sync::Arc::new(std::sync::Mutex::new(Vec::new())), + } + } + + #[test] + fn publish_replaces_current_run_while_earlier_references_stay_valid() { + let _turn = crate::tooling::tests::HEADLESS.lock().unwrap_or_else(|e| e.into_inner()); + let prev = headless_run(); + publish(sample_run(1.0, 30.0, (320.0, 200.0))); + let first: &'static HeadlessRun = headless_run().expect("first run published"); + assert_eq!((first.scale(), first.fps(), first.size()), (1.0, 30.0, (320.0, 200.0))); + + publish(sample_run(2.0, 60.0, (640.0, 480.0))); + let second: &'static HeadlessRun = headless_run().expect("second run published"); + assert_eq!((second.scale(), second.fps(), second.size()), (2.0, 60.0, (640.0, 480.0))); + assert_eq!((first.scale(), first.fps(), first.size()), (1.0, 30.0, (320.0, 200.0))); + + *RUN.write().unwrap_or_else(|e| e.into_inner()) = prev; + } +} diff --git a/app/vendor/rune/crates/rune/src/tooling/html.rs b/app/vendor/rune/crates/rune/src/tooling/html.rs new file mode 100644 index 0000000..7c26aec --- /dev/null +++ b/app/vendor/rune/crates/rune/src/tooling/html.rs @@ -0,0 +1,103 @@ +//! `--html`: the app's page as static HTML and CSS, laid out without a GPU, for a web app's +//! first paint and for readers that never run its wasm. + +use super::*; +use crate::runtime::web_export::{ExportNode, page}; + +/// How long the scene may animate before it is taken as it stands, in frames at 60 Hz. +const SETTLE_FRAMES: usize = 240; + +struct ExportPlan { + out: PathBuf, + widths: Vec<f32>, + height: f32, + scale: f32, + dark: bool, + template: String, +} + +fn prepare_export(spec_size: (f32, f32), args: &Args) -> Result<ExportPlan, String> { + let out = args.html.clone().expect("--html"); + let mut widths = if args.html_widths.is_empty() { vec![args.size.unwrap_or(spec_size).0] } else { args.html_widths.clone() }; + widths.sort_by(f32::total_cmp); + widths.dedup(); + let height = args.size.unwrap_or(spec_size).1; + let scale = args.scale.unwrap_or(2.0); + let dark = args.theme.as_deref() != Some("light"); + let template = match &args.html_template { + Some(path) => std::fs::read_to_string(path).map_err(|e| format!("--html-template {}: {e}", path.display()))?, + None => DEFAULT_TEMPLATE.to_owned(), + }; + Ok(ExportPlan { out, widths, height, scale, dark, template }) +} + +#[inline] +pub(crate) fn export<S: 'static>(app: crate::app::App<S>, args: &Args) -> Result<(), String> { + let plan = prepare_export(app.spec.size, args)?; + let (fit_height, document) = (app.fit_content_height, app.web_document); + let (spec, state, _shared, runtime) = app.into_parts(args.scene.as_deref()); + let mut rt = runtime_for(&spec, state, (plan.widths[0], plan.height), Env::new(plan.dark, plan.scale), std::sync::Arc::new(|| {})); + rt.configure(runtime); + let (core, mut driver) = rt.split_mut(); + export_core(core, &mut driver, fit_height, document, plan) +} + +fn export_core( + core: &mut crate::runtime::RuntimeCore, + app: &mut dyn crate::runtime::AppDriver, + fit_height: bool, + document: bool, + plan: ExportPlan, +) -> Result<(), String> { + core.host.fit_height = fit_height; + if document { core.page_mode(); } + let mut taken: Vec<(f32, Vec<ExportNode>)> = Vec::with_capacity(plan.widths.len()); + for &w in &plan.widths { + core.set_viewport((w, plan.height), plan.scale); + settle_core(core, app); + taken.push((w, core.export_nodes())); + } + let (body, css) = page(&taken); + std::fs::write(&plan.out, fill(&plan.template, &css, &body)).map_err(|e| format!("--html {}: {e}", plan.out.display()))?; + eprintln!("rune: wrote {} ({} elements, widths {:?})", plan.out.display(), taken[0].1.len(), plan.widths); + Ok(()) +} + +/// Lands entrance motion and anything the first frames start, then steps until the scene is at +/// rest or `SETTLE_FRAMES` pass (a looping animation is taken where it is). +fn settle_core(core: &mut crate::runtime::RuntimeCore, app: &mut dyn crate::runtime::AppDriver) { + core.settle_all(); + core.frame(app, 0.0); + for _ in 0..SETTLE_FRAMES { + if !core.animating && !core.stale() { break; } + core.frame(app, 1.0 / 60.0); + } +} + +/// Puts the stylesheet and the body into `template` at `<!-- rune:css -->` and +/// `<!-- rune:body -->`; without those markers, before `</head>` and after `<body…>`. +pub(crate) fn fill(template: &str, css: &str, body: &str) -> String { + let style = format!("<style data-rune-static>{css}</style>"); + let with_css = if template.contains(CSS_MARK) { + template.replacen(CSS_MARK, &style, 1) + } else if let Some(at) = template.find("</head>") { + format!("{}{style}{}", &template[..at], &template[at..]) + } else { + format!("{style}{template}") + }; + if with_css.contains(BODY_MARK) { return with_css.replacen(BODY_MARK, body, 1); } + let at = with_css.find("<body").and_then(|b| with_css[b..].find('>').map(|e| b + e + 1)); + match at { + Some(at) => format!("{}{body}{}", &with_css[..at], &with_css[at..]), + None => format!("{with_css}{body}"), + } +} + +const CSS_MARK: &str = "<!-- rune:css -->"; +const BODY_MARK: &str = "<!-- rune:body -->"; + +const DEFAULT_TEMPLATE: &str = "<!doctype html><html lang=\"en\"><head><meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width,initial-scale=1\"><style>:root{--rune-sans:system-ui,sans-serif;--rune-mono:ui-monospace,monospace}body{margin:0}</style><!-- rune:css --></head><body><!-- rune:body --></body></html>"; + +#[cfg(test)] +#[path = "html_tests.rs"] +mod tests; diff --git a/app/vendor/rune/crates/rune/src/tooling/html_tests.rs b/app/vendor/rune/crates/rune/src/tooling/html_tests.rs new file mode 100644 index 0000000..0555b38 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/tooling/html_tests.rs @@ -0,0 +1,17 @@ +use super::*; + +#[test] +fn fills_the_markers_or_the_head_and_body() { + let marked = "<head><!-- rune:css --></head><body><nav></nav><!-- rune:body --></body>"; + assert_eq!(fill(marked, ".a{}", "<main></main>"), "<head><style data-rune-static>.a{}</style></head><body><nav></nav><main></main></body>"); + let plain = "<html><head><title>x</title></head><body class=\"k\"></body></html>"; + assert_eq!( + fill(plain, ".a{}", "<main></main>"), + "<html><head><title>x</title><style data-rune-static>.a{}</style></head><body class=\"k\"><main></main></body></html>", + ); +} + +#[test] +fn the_default_page_has_both_markers() { + assert!(DEFAULT_TEMPLATE.contains(CSS_MARK) && DEFAULT_TEMPLATE.contains(BODY_MARK)); +} diff --git a/app/vendor/rune/crates/rune/src/tooling/interaction.rs b/app/vendor/rune/crates/rune/src/tooling/interaction.rs new file mode 100644 index 0000000..b40d4ba --- /dev/null +++ b/app/vendor/rune/crates/rune/src/tooling/interaction.rs @@ -0,0 +1,347 @@ +//! Interaction timing: how long each input took to reach the screen, which page and control it +//! was, and where the frame's time went, sent to a developer's local OpenTelemetry collector. +//! +//! Off unless `RUNE_PERF=1` or `OTEL_EXPORTER_OTLP_ENDPOINT` points at loopback (`gate`). Off, +//! a frame checks one cached flag and nothing else runs: no clocks, threads or files. +//! +//! On, a frame whose input ran a handler (a press, key, edit, paste, wheel, drag, hover) is timed +//! from the input's arrival to its present: `queue_wait` until the frame starts, `update` (the +//! handlers, view, layout, text, paint and apply phases), `encode`, and `present_wait` until the +//! display refresh it aims at. Its signature is a route (the page-sized keyed element around the +//! control, and any open modal), the control's normalized path, and the action. Every timed +//! interaction counts toward a per-signature histogram sent each minute (`ui.rollup`); one over +//! [`SLOW_MS`] (`RUNE_PERF_SLOW_MS`) is sent at once as a `ui.interaction` trace with its phase +//! split, commit reasons and the keyed subtrees its commits rebuilt. Key presses in a text field +//! say `key_edit`, never which key. +//! +//! While a frame runs long, the `watchdog` samples the UI thread's stack, so a slow interaction +//! names the functions its time went to (`rune.hot`, `rune.stack`), and a slow frame no input +//! caused (a timer, a poll, an animation) goes as `ui.frame`. Each slow one says whose time it +//! took (`cause`): a frame that waited for a core on a busy machine is `scheduler_wait`, not the +//! app's. + +mod cause; +#[cfg(not(target_arch = "wasm32"))] +mod export; +#[cfg(target_arch = "wasm32")] +mod export { + use super::*; + #[allow(dead_code)] + pub(crate) enum Message { + Slow(Box<Slow>), + Frame(Box<SlowFrame>), + Rollup { rolls: Vec<rollup::Roll>, from: Instant, to: Instant }, + } + pub(crate) fn send(_: Message) -> bool { false } + pub(crate) fn flush(_: Duration) {} +} +mod frame; +pub(crate) mod gate; +mod names; +mod rollup; +mod stack; +mod watchdog; + +use std::cell::Cell; +use std::sync::{Arc, OnceLock}; +use std::time::Duration; + +use crate::frame::profile::{PHASES, Phase}; +use crate::time::Instant; +use crate::machine::Effects; +use frame::{Built, Effect, Event, Frame, step}; + +pub(crate) use cause::Cause; +pub(crate) use names::{Name, Names}; +use rollup::Rollup; +pub(crate) use watchdog::{Stacks, hurry}; + +/// An interaction slower than this, input to present, or with this much work, is sent at once. +pub(crate) const SLOW_MS: f64 = 1000.0 / 60.0; +/// How often the histograms go out. +const ROLLUP_EVERY: Duration = Duration::from_secs(60); +/// Slow interactions sent per second at most; the rest still count in the rollup. +const SLOW_PER_SECOND: u32 = 10; + +/// The `update` span's attribute for each [`Phase`]. +pub(crate) const PHASE_NAMES: [&str; PHASES] = ["rune.view_ms", "rune.commit_ms", "rune.layout_ms", "rune.text_ms", "rune.paint_ms", "rune.apply_ms"]; + +thread_local! { + /// A timed frame is underway on this thread: phases time themselves into `TIMES`. + static ACTIVE: Cell<bool> = const { Cell::new(false) }; + static TIMES: Cell<[f64; PHASES]> = const { Cell::new([0.0; PHASES]) }; +} + +/// Whether timing is on in this process. +#[inline(always)] +pub(crate) fn on() -> bool { gate::on() } + +/// Whether a timed frame is underway on this thread, so phases should time themselves. +#[inline(always)] +pub(crate) fn active() -> bool { ACTIVE.get() } + +/// Phase `phase` of the timed frame took `ms`. +pub(crate) fn add(phase: Phase, ms: f64) { + let mut row = TIMES.get(); + row[phase as usize] += ms; + TIMES.set(row); +} + +#[cfg(test)] +thread_local! { + /// A fixed threshold for tests that drive the real runtime: a local `RUNE_PERF_SLOW_MS` + /// must not change what they measure. Per thread, so tests running in parallel can't see + /// each other's. + static SLOW_MS_OVERRIDE: Cell<Option<f64>> = const { Cell::new(None) }; +} + +/// Fix the slow threshold for the tests on this thread. Production reads the environment. +#[cfg(test)] +pub(super) fn force_slow_ms(ms: f64) { SLOW_MS_OVERRIDE.set(Some(ms)); } + +fn slow_ms() -> f64 { + #[cfg(test)] + if let Some(ms) = SLOW_MS_OVERRIDE.get() { return ms; } + static MS: OnceLock<f64> = OnceLock::new(); + *MS.get_or_init(|| rune_core::env::var("RUNE_PERF_SLOW_MS").and_then(|v| v.trim().parse().ok()).filter(|ms: &f64| *ms > 0.0).unwrap_or(SLOW_MS)) +} + +/// What one input action was, before the frame it lands in is built. +pub(crate) struct Note { + pub route: Name, + pub control: Name, + pub action: &'static str, + /// Which of a frame's actions names it: a press or key over a scroll over a hover. + pub rank: u8, +} + +/// A slow interaction, as sent. +pub(crate) struct Slow { + pub route: Arc<str>, + pub control: Arc<str>, + pub action: &'static str, + pub arrived: Instant, + pub frame_start: Instant, + pub built: Instant, + pub submitted: Instant, + pub present: Instant, + pub handler_ms: f64, + pub phases: [f64; PHASES], + pub why: u16, + pub commits: u32, + pub shaped: u32, + pub nodes: usize, + pub reused: usize, + /// The keyed subtrees the frame's last commit rebuilt most nodes of, largest first. + pub rebuilt: Vec<(Arc<str>, usize)>, + pub cpu_ms: Option<f64>, + pub cause: Cause, + pub stacks: Option<Stacks>, +} + +/// A slow frame no input caused, as sent. +pub(crate) struct SlowFrame { + pub start: Instant, + pub built: Instant, + pub why: u16, + pub nodes: usize, + pub cause: Cause, + pub stacks: Stacks, +} + +/// One timed frame, from its first input handler until it presents. +pub(crate) struct Timed { + pub arrived: Instant, + pub frame_start: Instant, + pub handler_ms: f64, + pub note: Note, + pub why: u16, + pub commits: u32, +} + +/// A window's interaction timing. Lives in the runtime's `perf_warn::Watch`. +#[derive(Default)] +pub(crate) struct Tracker { + pub names: Names, + rollup: Rollup, + rolled_since: Option<Instant>, + frame: Frame, + /// Signatures that were slow by the app's doing this session: the watchdog samples them sooner. + breached: rustc_hash::FxHashSet<u64>, + /// The last commit's memo-reused node ranges (start, len), while a frame is timed. + pub reused: Vec<(usize, usize)>, + sent: (Option<Instant>, u32), +} + + +/// What finishing a timed frame decided. +pub(crate) struct Finished { + pub timed: Timed, + pub cpu_ms: Option<f64>, + pub stacks: Option<Stacks>, + pub built: Instant, + pub phases: [f64; PHASES], + pub shaped: u32, + pub submitted: Instant, + pub present: Instant, + /// Whose time it took, when it was slow. + pub cause: Option<Cause>, + /// Send it as a slow interaction. + pub slow: bool, +} + +impl Tracker { + /// A frame starts; `queued` when input waits for it. A built frame no host presented + /// (a bare `Runtime`, a window that skipped drawing) ends at its build. + pub(crate) fn frame_begins(&mut self, queued: bool) -> Option<Finished> { + self.begin_with(queued, slow_ms(), crate::time::now, crate::frame::profile::cpu_ms) + } + + fn begin_with(&mut self, queued: bool, slow_ms: f64, now: impl FnOnce() -> Instant, cpu: impl FnOnce() -> Option<f64>) -> Option<Finished> { + let finished = match &self.frame { + Frame::Built(b) => self.finish_with(b.at, None, slow_ms), + _ => None, + }; + let now = now(); + let cpu = if queued { cpu() } else { None }; + step(&mut self.frame, Event::Begin { at: now, queued, cpu }); + watchdog::arm(); + finished + } + + /// Whether `note`'s signature was slow before, so its frame should be sampled sooner. + pub(crate) fn breached(&self, note: &Note) -> bool { + !self.breached.is_empty() && self.breached.contains(&rollup::signature(&note.route, &note.control, note.action)) + } + + /// An input action ran its handlers: `at` is when its input arrived, `handler` how long + /// they took from `started`. + pub(crate) fn noted(&mut self, note: Note, at: Option<Instant>, started: Instant, handler: Duration) { + if let Effects::One(Effect::StartPhases) = step(&mut self.frame, Event::Note { note, at, started, handler }) { + TIMES.set([0.0; PHASES]); + ACTIVE.set(true); + } + } + + /// A commit ran, for `why` (`CommitWhy` bits). + pub(crate) fn committed(&mut self, why: u16) { + step(&mut self.frame, Event::Commit(why)); + } + + /// The frame, of `nodes` nodes, is built; `shaped` text runs it shaped. A slow frame no + /// input caused comes back to send. + pub(crate) fn built(&mut self, shaped: u32, nodes: usize) -> Option<SlowFrame> { + self.build_with(shaped, nodes, watchdog::disarm(), slow_ms(), crate::time::now, crate::frame::profile::cpu_ms) + } + + fn build_with(&mut self, shaped: u32, nodes: usize, stacks: Option<Stacks>, slow_ms: f64, now: impl FnOnce() -> Instant, cpu: impl FnOnce() -> Option<f64>) -> Option<SlowFrame> { + if !matches!(self.frame, Frame::Open { .. }) { + let Effects::One(Effect::CheckFrame { start, why }) = step(&mut self.frame, Event::BuildUntimed) else { return None }; + let stacks = stacks?; + let built = now(); + let work = built.saturating_duration_since(start).as_secs_f64() * 1000.0; + let cause = cause::cause(work, slow_ms, None, Some(&stacks), overloaded()); + return (work > slow_ms).then_some(SlowFrame { start, built, why, nodes, cause, stacks }); + } + let event = Event::BuildTimed { at: now(), phases: TIMES.replace([0.0; PHASES]), shaped, cpu: cpu(), stacks }; + if let Effects::One(Effect::StopPhases) = step(&mut self.frame, event) { ACTIVE.set(false); } + None + } + + /// The built frame was submitted at `submitted`, to show at `presents_at` when a display + /// link paced it. Counts it, and says whether to send it as slow. + pub(crate) fn finish(&mut self, submitted: Instant, presents_at: Option<Instant>) -> Option<Finished> { + self.finish_with(submitted, presents_at, slow_ms()) + } + + fn finish_with(&mut self, submitted: Instant, presents_at: Option<Instant>, slow_ms: f64) -> Option<Finished> { + let Effects::One(Effect::Count(Built { timed, at: built, phases, shaped, cpu_ms, stacks })) = step(&mut self.frame, Event::Finish) else { return None }; + let submitted = submitted.max(built); + let present = presents_at.map_or(submitted, |p| p.max(submitted)); + let total = present.saturating_duration_since(timed.arrived).as_secs_f64() * 1000.0; + let work = submitted.saturating_duration_since(timed.frame_start).as_secs_f64() * 1000.0; + let over = total > slow_ms || work > slow_ms; + let cause = over.then(|| cause::cause(work, slow_ms, cpu_ms, stacks.as_ref(), overloaded())); + let contended = cause == Some(Cause::SchedulerWait); + let note = &timed.note; + self.rollup.add(&note.route, &note.control, note.action, total, over && !contended, contended); + if over && !contended { self.breached.insert(rollup::signature(&note.route, &note.control, note.action)); } + let slow = over && self.allow(present); + self.rolled_since.get_or_insert(timed.arrived); + Some(Finished { timed, built, phases, shaped, submitted, present, cause, slow, cpu_ms, stacks }) + } + + fn allow(&mut self, now: Instant) -> bool { + match self.sent { + (Some(at), n) if now.saturating_duration_since(at) < Duration::from_secs(1) => { + self.sent.1 = n + 1; + n < SLOW_PER_SECOND + } + _ => { + self.sent = (Some(now), 1); + true + } + } + } + + /// Sends the histograms when a minute has passed since the last, or `now` regardless. + pub(crate) fn roll(&mut self, force: bool) { + let Some(from) = self.rolled_since else { return }; + let to = crate::time::now(); + if self.rollup.is_empty() || (!force && to.saturating_duration_since(from) < ROLLUP_EVERY) { return; } + export::send(export::Message::Rollup { rolls: self.rollup.take(), from, to }); + self.rolled_since = None; + } +} + +impl Drop for Tracker { + /// A window closing, or the app quitting, sends what it counted since the last rollup. It + /// doesn't wait for it to go: a closing window would freeze the app's other windows, and + /// macOS runs a main thread that just slept on a slower core for its next frames. The app's + /// event loop [`flush`]es once, as it exits. + fn drop(&mut self) { + if self.rolled_since.is_none() { return; } + self.roll(true); + } +} + +/// Whether the machine has no core to spare. +fn overloaded() -> bool { + #[cfg(test)] + return tests::OVERLOADED.get(); + #[cfg(not(test))] + crate::tooling::perf_warn::runq::overloaded() +} + +/// Sends a slow frame no input caused. +pub(crate) fn send_frame(frame: SlowFrame) { + #[cfg(test)] + return tests::FRAMES.with_borrow_mut(|sent| sent.push(frame)); + #[cfg(not(test))] + export::send(export::Message::Frame(Box::new(frame))); +} + +/// Sends a slow interaction. +pub(crate) fn send(slow: Slow) { + #[cfg(test)] + return tests::SENT.with_borrow_mut(|sent| sent.push(slow)); + #[cfg(not(test))] + export::send(export::Message::Slow(Box::new(slow))); +} + +/// Waits up to a second for everything queued to reach the collector, before the process exits. +/// Returns at once when nothing was ever sent. +pub(crate) fn flush() { + if on() { export::flush(Duration::from_secs(1)); } +} + +#[cfg(test)] +#[path = "interaction/tests.rs"] +mod tests; +#[cfg(test)] +#[path = "interaction/sampler_tests.rs"] +mod sampler_tests; + +#[cfg(test)] +#[path = "interaction/frame_tests.rs"] +mod frame_tests; diff --git a/app/vendor/rune/crates/rune/src/tooling/interaction/cause.rs b/app/vendor/rune/crates/rune/src/tooling/interaction/cause.rs new file mode 100644 index 0000000..4587469 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/tooling/interaction/cause.rs @@ -0,0 +1,42 @@ +//! Whose time a slow frame took. A frame can be slow because the app computed (`cpu`), because +//! it waited on IO, a lock or a sleep (`blocked`), or because a busy machine left it waiting for +//! a core (`scheduler_wait`): the last isn't the app's to fix, so it's flagged, kept out of the +//! rollup's slow count, and never marks a signature as slow before. An interaction whose frame +//! was quick but reached the screen late waited outside it (`queued`). + +use super::watchdog::Stacks; + +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub(crate) enum Cause { + Cpu, + Blocked, + SchedulerWait, + Queued, +} + +impl Cause { + pub(crate) fn name(self) -> &'static str { + match self { + Cause::Cpu => "cpu", + Cause::Blocked => "blocked", + Cause::SchedulerWait => "scheduler_wait", + Cause::Queued => "queued", + } + } +} + +/// Of a slow frame that worked `work_ms`, using `cpu_ms` of the thread's CPU when measured, the +/// watchdog's samples, and whether the machine is `overloaded` (load average at its core count). +pub(crate) fn cause(work_ms: f64, slow_ms: f64, cpu_ms: Option<f64>, stacks: Option<&Stacks>, overloaded: bool) -> Cause { + if work_ms <= slow_ms { return Cause::Queued; } + let sampled = stacks.filter(|s| s.taken > 0); + if sampled.is_some_and(|s| 2 * s.waiting > s.taken) { return Cause::Blocked; } + let share = cpu_ms.map(|cpu| cpu / work_ms).or_else(|| sampled.and_then(|s| s.cpu_share)); + match share { + Some(share) if share >= 0.5 => Cause::Cpu, + None if !overloaded => Cause::Cpu, + // Little CPU, yet the samples found it running or ready to run: it waited for a core. + _ if overloaded || sampled.is_some_and(|s| s.taken >= 2) => Cause::SchedulerWait, + _ => Cause::Blocked, + } +} diff --git a/app/vendor/rune/crates/rune/src/tooling/interaction/export.rs b/app/vendor/rune/crates/rune/src/tooling/interaction/export.rs new file mode 100644 index 0000000..5302a2e --- /dev/null +++ b/app/vendor/rune/crates/rune/src/tooling/interaction/export.rs @@ -0,0 +1,228 @@ +//! Sends timed interactions to the local collector as OTLP/HTTP JSON traces, from one +//! background thread started with the first message. The UI thread only moves a finished +//! record onto a channel; JSON, sockets and retries happen here. A refused or slow connection +//! drops the batch. + +use std::net::SocketAddr; +use std::sync::OnceLock; +use std::sync::mpsc::{Sender, SyncSender, channel}; +use std::time::{Duration, UNIX_EPOCH}; + +use serde_json::{Value, json}; + +use super::rollup::Roll; +use super::{PHASE_NAMES, Slow, SlowFrame, Stacks}; +use crate::time::Instant; + +pub(crate) enum Message { + /// Unit tests keep slow interactions (`tests::SENT`) rather than send them. + #[cfg_attr(test, allow(dead_code))] + Slow(Box<Slow>), + /// Unit tests keep slow frames (`tests::FRAMES`) rather than send them. + #[cfg_attr(test, allow(dead_code))] + Frame(Box<SlowFrame>), + /// Every signature's counts over `[from, to]`. + Rollup { rolls: Vec<Roll>, from: Instant, to: Instant }, + /// Answers once everything sent before it is posted. + Flush(SyncSender<()>), +} + +/// Queues `message` for the collector; false when there's none. +pub(crate) fn send(message: Message) -> bool { + sender().is_some_and(|out| out.send(message).is_ok()) +} + +/// Waits up to `limit` for everything queued to be posted, for a process about to exit. +pub(crate) fn flush(limit: Duration) { + let Some(Some(out)) = OUT.get() else { return }; + let (done, wait) = std::sync::mpsc::sync_channel(1); + if out.send(Message::Flush(done)).is_ok() { wait.recv_timeout(limit).ok(); } +} + +/// The posting thread's queue, made by the first send. +static OUT: OnceLock<Option<Sender<Message>>> = OnceLock::new(); + +fn sender() -> Option<&'static Sender<Message>> { + OUT.get_or_init(|| { + let to = super::gate::collector()?; + let (out, messages) = channel::<Message>(); + let resource = resource(); + std::thread::Builder::new().name("rune-interactions".into()).spawn(move || { + while let Ok(first) = messages.recv() { + // A short wait gathers a burst into one request. + if !matches!(first, Message::Flush(_)) { std::thread::sleep(Duration::from_millis(100)); } + let mut spans = Vec::new(); + let mut flushed = Vec::new(); + for m in std::iter::once(first).chain(messages.try_iter()) { + match m { + Message::Slow(slow) => spans.extend(slow_spans(&slow)), + Message::Frame(frame) => spans.push(frame_span(&frame)), + Message::Rollup { rolls, from, to } => spans.extend(rolls.iter().map(|r| roll_span(r, from, to))), + Message::Flush(done) => flushed.push(done), + } + } + if !spans.is_empty() { post(to, &body(&resource, spans)); } + for done in flushed { done.send(()).ok(); } + } + }).ok()?; + Some(out) + }).as_ref() +} + +fn resource() -> Value { + let service = rune_core::env::var("OTEL_SERVICE_NAME").filter(|s| !s.trim().is_empty()).unwrap_or_else(|| { + std::env::current_exe().ok().and_then(|p| p.file_stem().map(|s| s.to_string_lossy().into_owned())).unwrap_or_else(|| "rune-app".into()) + }); + json!({"attributes": [ + kv("service.name", service.into()), + kv("process.pid", u64::from(std::process::id()).into()), + kv("rune.version", env!("CARGO_PKG_VERSION").into()), + ]}) +} + +pub(crate) fn body(resource: &Value, spans: Vec<Value>) -> String { + json!({"resourceSpans": [{ + "resource": resource, + "scopeSpans": [{"scope": {"name": "rune.interaction"}, "spans": spans}], + }]}).to_string() +} + +/// A slow interaction as a trace: `ui.interaction` from input to present, with its stretches +/// (`queue_wait`, `update`, `encode`, `present_wait`) as children and the update's phases on +/// the `update` span. +pub(crate) fn slow_spans(s: &Slow) -> Vec<Value> { + let trace = (u128::from(id()) << 64) | u128::from(id()); + let root = id(); + let mut attrs = vec![ + kv("rune.route", s.route.as_ref().into()), + kv("rune.control", s.control.as_ref().into()), + kv("rune.action", s.action.into()), + kv("rune.signature", format!("{} {} {}", s.route, s.control, s.action).into()), + kv("rune.input_to_present_ms", ms(s.arrived, s.present).into()), + kv("rune.work_ms", ms(s.frame_start, s.submitted).into()), + kv("rune.nodes", (s.nodes as u64).into()), + kv("rune.reused_nodes", (s.reused as u64).into()), + kv("rune.commits", u64::from(s.commits).into()), + kv("rune.shaped", u64::from(s.shaped).into()), + ]; + let why = crate::runtime::CommitWhy::names(s.why); + if !why.is_empty() { attrs.push(kv("rune.commit_why", why.join(",").into())); } + for (i, (key, n)) in s.rebuilt.iter().enumerate().take(3) { + attrs.push(kv(["rune.rebuilt.0", "rune.rebuilt.1", "rune.rebuilt.2"][i], format!("{key} ({n})").into())); + } + attrs.push(kv("rune.cause", s.cause.name().into())); + if let Some(cpu) = s.cpu_ms { attrs.push(kv("rune.cpu_ms", round(cpu).into())); } + if let Some(stacks) = &s.stacks { stack_attrs(stacks, &mut attrs); } + let mut out = vec![span(trace, root, None, "ui.interaction", s.arrived, s.present, attrs)]; + let mut update = vec![kv("rune.handler_ms", round(s.handler_ms).into())]; + for (name, ms) in PHASE_NAMES.iter().zip(s.phases) { + if ms > 0.0 { update.push(kv(name, round(ms).into())); } + } + for (name, from, to, attrs) in [ + ("queue_wait", s.arrived, s.frame_start, vec![]), + ("update", s.frame_start, s.built, update), + ("encode", s.built, s.submitted, vec![]), + ("present_wait", s.submitted, s.present, vec![]), + ] { + if to > from { out.push(span(trace, id(), Some(root), name, from, to, attrs)); } + } + out +} + +/// A slow frame no input caused: its work, why it committed, and where its time went. +pub(crate) fn frame_span(f: &SlowFrame) -> Value { + let trace = (u128::from(id()) << 64) | u128::from(id()); + let mut attrs = vec![ + kv("rune.work_ms", ms(f.start, f.built).into()), + kv("rune.nodes", (f.nodes as u64).into()), + kv("rune.cause", f.cause.name().into()), + ]; + let why = crate::runtime::CommitWhy::names(f.why); + if !why.is_empty() { attrs.push(kv("rune.commit_why", why.join(",").into())); } + stack_attrs(&f.stacks, &mut attrs); + span(trace, id(), None, "ui.frame", f.start, f.built, attrs) +} + +/// The watchdog's samples: how many, how many found the thread waiting, the functions they +/// were in (`fn (n/N)`), and one sample's stack, innermost first, a line a frame. +fn stack_attrs(s: &Stacks, attrs: &mut Vec<Value>) { + attrs.push(kv("rune.samples", u64::from(s.taken).into())); + attrs.push(kv("rune.samples_waiting", u64::from(s.waiting).into())); + let names = s.names(super::stack::frames); + for (i, (name, n)) in names.hot.iter().enumerate().take(3) { + attrs.push(kv(["rune.hot.0", "rune.hot.1", "rune.hot.2"][i], format!("{name} ({n}/{})", s.taken).into())); + } + if !names.stack.is_empty() { attrs.push(kv("rune.stack", names.stack.join("\n").into())); } +} + +pub(crate) fn roll_span(r: &Roll, from: Instant, to: Instant) -> Value { + let trace = (u128::from(id()) << 64) | u128::from(id()); + span(trace, id(), None, "ui.rollup", from, to, vec![ + kv("rune.route", r.route.text.as_ref().into()), + kv("rune.control", r.control.text.as_ref().into()), + kv("rune.action", r.action.into()), + kv("rune.count", u64::from(r.count).into()), + kv("rune.slow", u64::from(r.slow).into()), + kv("rune.scheduler_wait", u64::from(r.contended).into()), + kv("rune.p50_ms", round(r.quantile(0.5)).into()), + kv("rune.p98_ms", round(r.quantile(0.98)).into()), + kv("rune.max_ms", round(r.max_ms).into()), + ]) +} + +fn span(trace: u128, id: u64, parent: Option<u64>, name: &str, start: Instant, end: Instant, attrs: Vec<Value>) -> Value { + let mut span = json!({ + "traceId": format!("{trace:032x}"), "spanId": format!("{id:016x}"), + "name": name, "kind": 1, + "startTimeUnixNano": unix_nanos(start).to_string(), "endTimeUnixNano": unix_nanos(end.max(start)).to_string(), + "attributes": attrs, + }); + if let Some(p) = parent { span["parentSpanId"] = format!("{p:016x}").into(); } + span +} + +fn kv(key: &str, value: Value) -> Value { + let value = match value { + Value::Bool(b) => json!({"boolValue": b}), + Value::Number(n) if n.is_i64() || n.is_u64() => json!({"intValue": n.to_string()}), + Value::Number(n) => json!({"doubleValue": n.as_f64()}), + Value::String(s) => json!({"stringValue": s}), + other => json!({"stringValue": other.to_string()}), + }; + json!({"key": key, "value": value}) +} + +fn ms(from: Instant, to: Instant) -> f64 { round(to.saturating_duration_since(from).as_secs_f64() * 1000.0) } + +fn round(ms: f64) -> f64 { (ms * 1000.0).round() / 1000.0 } + +fn id() -> u64 { + use std::hash::{BuildHasher, Hasher}; + use std::sync::atomic::{AtomicU64, Ordering}; + static N: AtomicU64 = AtomicU64::new(0); + static SEED: OnceLock<std::collections::hash_map::RandomState> = OnceLock::new(); + let mut h = SEED.get_or_init(Default::default).build_hasher(); + h.write_u64(N.fetch_add(1, Ordering::Relaxed)); + h.finish().max(1) +} + +fn unix_nanos(t: Instant) -> u128 { + static ANCHOR: OnceLock<(Instant, u128)> = OnceLock::new(); + let (at, unix) = *ANCHOR.get_or_init(|| (crate::time::now(), crate::time::system_now().duration_since(UNIX_EPOCH).map_or(0, |d| d.as_nanos()))); + match t.checked_duration_since(at) { + Some(d) => unix + d.as_nanos(), + None => unix.saturating_sub(at.duration_since(t).as_nanos()), + } +} + +/// One HTTP/1.1 POST on loopback. +fn post(to: SocketAddr, body: &str) { + use std::io::{Read as _, Write as _}; + let Ok(mut s) = std::net::TcpStream::connect_timeout(&to, Duration::from_millis(250)) else { return }; + s.set_write_timeout(Some(Duration::from_secs(2))).ok(); + s.set_read_timeout(Some(Duration::from_secs(2))).ok(); + let head = format!("POST /v1/traces HTTP/1.1\r\nHost: {to}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", body.len()); + if s.write_all(head.as_bytes()).and_then(|()| s.write_all(body.as_bytes())).is_ok() { + let _bytes = s.read(&mut [0; 256]).unwrap_or(0); + } +} diff --git a/app/vendor/rune/crates/rune/src/tooling/interaction/frame.rs b/app/vendor/rune/crates/rune/src/tooling/interaction/frame.rs new file mode 100644 index 0000000..b179845 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/tooling/interaction/frame.rs @@ -0,0 +1,80 @@ +use super::{Duration, Instant, Note, PHASES, Stacks, Timed}; +use crate::machine::Effects; + +#[derive(Default)] +pub(super) enum Frame { + #[default] + Idle, + Begun { at: Instant, queued: bool, cpu: Option<f64>, why: u16 }, + Open { timed: Timed, input_start: Option<Instant>, cpu: Option<f64> }, + Built(Built), +} + +pub(super) struct Built { + pub timed: Timed, + pub at: Instant, + pub phases: [f64; PHASES], + pub shaped: u32, + pub cpu_ms: Option<f64>, + pub stacks: Option<Stacks>, +} + +pub(super) enum Event { + Begin { at: Instant, queued: bool, cpu: Option<f64> }, + Note { note: Note, at: Option<Instant>, started: Instant, handler: Duration }, + Commit(u16), + BuildUntimed, + BuildTimed { at: Instant, phases: [f64; PHASES], shaped: u32, cpu: Option<f64>, stacks: Option<Stacks> }, + Finish, +} + +pub(super) enum Effect { StartPhases, StopPhases, CheckFrame { start: Instant, why: u16 }, Count(Built) } + +#[inline] +pub(super) fn step(frame: &mut Frame, event: Event) -> Effects<Effect> { + match event { + Event::Begin { at, queued, cpu } => match frame { + // A second begin without a build leaves the first interaction open. + Frame::Open { input_start, .. } => *input_start = queued.then_some(at), + _ => *frame = Frame::Begun { at, queued, cpu, why: 0 }, + }, + Event::Note { note, at, started, handler } => { + let handler_ms = handler.as_secs_f64() * 1000.0; + if let Frame::Open { timed, input_start, .. } = frame { + let start = *input_start.get_or_insert(started); + timed.arrived = timed.arrived.min(at.unwrap_or(start).min(start)); + timed.handler_ms += handler_ms; + if note.rank > timed.note.rank { timed.note = note; } + } else { + let (frame_start, cpu) = match *frame { + Frame::Begun { at, queued, cpu, .. } => (if queued { at } else { started }, cpu), + _ => (started, None), + }; + let arrived = at.unwrap_or(frame_start).min(frame_start); + let timed = Timed { arrived, frame_start, handler_ms, note, why: 0, commits: 0 }; + *frame = Frame::Open { timed, input_start: Some(frame_start), cpu }; + return Effects::one(Effect::StartPhases); + } + } + Event::Commit(bits) => match frame { + Frame::Begun { why, .. } => *why |= bits, + Frame::Open { timed, .. } => { timed.why |= bits; timed.commits += 1; } + _ => (), + }, + Event::BuildUntimed => if let Frame::Begun { at: start, why, .. } = *frame { + *frame = Frame::Idle; + return Effects::one(Effect::CheckFrame { start, why }); + }, + Event::BuildTimed { at, phases, shaped, cpu, stacks } => { + let Frame::Open { timed, cpu: from, .. } = std::mem::take(frame) else { unreachable!() }; + let cpu_ms = from.zip(cpu).map(|(from, to)| to - from); + *frame = Frame::Built(Built { timed, at, phases, shaped, cpu_ms, stacks }); + return Effects::one(Effect::StopPhases); + } + Event::Finish => if matches!(frame, Frame::Built(_)) { + let Frame::Built(built) = std::mem::take(frame) else { unreachable!() }; + return Effects::one(Effect::Count(built)); + }, + } + Effects::none() +} diff --git a/app/vendor/rune/crates/rune/src/tooling/interaction/frame_tests.rs b/app/vendor/rune/crates/rune/src/tooling/interaction/frame_tests.rs new file mode 100644 index 0000000..01fc0f2 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/tooling/interaction/frame_tests.rs @@ -0,0 +1,166 @@ +use super::*; + +// The old tracker's fields and branches, with readings supplied by the walk's clock. +#[derive(Default)] +struct Old { + frame_start: Option<Instant>, + began: Option<(Instant, Option<f64>)>, + frame_why: u16, + timed: Option<OldTimed>, + times: [f64; PHASES], + active: bool, +} + +#[derive(Debug, PartialEq)] +struct OldTimed { + arrived: Instant, frame_start: Instant, handler_ms: f64, rank: u8, why: u16, commits: u32, + built: Option<(Instant, [f64; PHASES], u32)>, cpu: (Option<f64>, Option<f64>), stacks: Option<u32>, +} + +type Report = (OldTimed, Instant, Instant); +impl Old { + fn begin(&mut self, queued: bool, now: Instant, cpu: Option<f64>) -> Option<Report> { + let left = self.timed.as_ref().and_then(|t| t.built).map(|(built, ..)| built); + let finished = left.and_then(|built| self.finish(built, None)); + self.frame_start = queued.then_some(now); + self.began = Some((now, if queued { cpu } else { None })); + self.frame_why = 0; + finished + } + + fn noted(&mut self, rank: u8, at: Option<Instant>, started: Instant, handler: Duration) { + let frame_start = *self.frame_start.get_or_insert(started); + let arrived = at.unwrap_or(frame_start).min(frame_start); + match &mut self.timed { + Some(t) if t.built.is_none() => { + t.arrived = t.arrived.min(arrived); + t.handler_ms += handler.as_secs_f64() * 1000.0; + if rank > t.rank { t.rank = rank; } + } + _ => { + let cpu = (self.began.and_then(|b| b.1), None); + self.timed = Some(OldTimed { arrived, frame_start, handler_ms: handler.as_secs_f64() * 1000.0, + rank, why: 0, commits: 0, built: None, cpu, stacks: None }); + self.times = [0.0; PHASES]; + self.active = true; + } + } + } + + fn committed(&mut self, why: u16) { + self.frame_why |= why; + if let Some(t) = self.timed.as_mut().filter(|t| t.built.is_none()) { + t.why |= why; + t.commits += 1; + } + } + + fn build(&mut self, shaped: u32, now: Instant, cpu: Option<f64>, stacks: Option<u32>, slow_ms: f64) -> Option<(Instant, Instant, u16, u32)> { + let why = self.frame_why; + self.frame_start = None; + let began = self.began.take(); + let Some(t) = self.timed.as_mut().filter(|t| t.built.is_none()) else { + let (start, stacks) = (began?.0, stacks?); + let work = now.saturating_duration_since(start).as_secs_f64() * 1000.0; + return (work > slow_ms).then_some((start, now, why, stacks)); + }; + t.built = Some((now, std::mem::take(&mut self.times), shaped)); + t.cpu.1 = t.cpu.0.zip(cpu).map(|(from, to)| to - from); + t.stacks = stacks; + self.active = false; + None + } + + fn finish(&mut self, submitted: Instant, presents_at: Option<Instant>) -> Option<Report> { + let timed = self.timed.take_if(|t| t.built.is_some())?; + let (built, ..) = timed.built?; + let submitted = submitted.max(built); + let present = presents_at.map_or(submitted, |p| p.max(submitted)); + Some((timed, submitted, present)) + } +} + +fn compare(got: Option<Finished>, expected: Option<Report>) { + assert_eq!(got.is_some(), expected.is_some()); + if let (Some(f), Some((t, submitted, present))) = (got, expected) { + assert_eq!((f.submitted, f.present), (submitted, present)); + assert_eq!(Some((f.built, f.phases, f.shaped)), t.built); + assert_eq!((f.cpu_ms, f.stacks.map(|s| s.taken)), (t.cpu.1, t.stacks)); + let g = f.timed; + assert_eq!((g.arrived, g.frame_start, g.handler_ms, g.note.rank, g.why, g.commits), + (t.arrived, t.frame_start, t.handler_ms, t.rank, t.why, t.commits)); + } +} + +#[test] +fn frame_phase_walk() { + // A fixed threshold: the walk never reads `RUNE_PERF_SLOW_MS` from the environment. It sits + // between the walk's 30 ms steps so both a slow and a quick untimed frame come up. + const SLOW_MS: f64 = 75.0; + let base = crate::time::now(); + let (mut slow, mut quick) = (0, 0); + for mut path in 0..8usize.pow(5) { + let mut tracker = Tracker::default(); + let mut old = Old::default(); + TIMES.set([0.0; PHASES]); + ACTIVE.set(false); + for i in 1..=5 { + let e = path % 8; + path /= 8; + let now = base + Duration::from_millis(i * 30); + let cpu = (i % 3 != 0).then_some(i as f64); + match e { + 0 | 1 => compare(tracker.begin_with(e == 1, SLOW_MS, || now, || cpu), old.begin(e == 1, now, cpu)), + 2 | 3 => { + let rank = e as u8; + let at = (e == 3).then_some(base); + let handler = Duration::from_micros(i); + old.noted(rank, at, now, handler); + let note = Note { rank, route: tracker.names.fixed("page"), control: tracker.names.fixed("button"), action: "press" }; + tracker.noted(note, at, now, handler); + } + 4 => { + old.committed(1 << i); + tracker.committed(1 << i); + } + 5 => { + let taken = (i % 3 != 0).then_some(i as u32); + let untimed = !matches!(tracker.frame, Frame::Open { .. }); + let expected = old.build(i as u32, now, cpu, taken, SLOW_MS); + let stacks = taken.map(|taken| Stacks { taken, waiting: taken, cpu_share: None, raw: vec![] }); + let got = tracker.build_with(i as u32, 99, stacks, SLOW_MS, || now, || cpu); + assert_eq!(got.map(|f| (f.start, f.built, f.why, f.stacks.taken)), expected); + match (untimed, expected.is_some()) { + (true, true) => slow += 1, + (true, false) if taken.is_some() => quick += 1, + _ => (), + } + } + 6 | 7 => { + let (sub, present) = if e == 6 { (base, Some(now)) } else { (now, Some(base)) }; + compare(tracker.finish_with(sub, present, SLOW_MS), old.finish(sub, present)); + } + _ => unreachable!(), + } + if old.active { old.times[Phase::Paint as usize] += i as f64; } + if active() { add(Phase::Paint, i as f64); } + assert_eq!((active(), TIMES.get()), (old.active, old.times)); + match (&tracker.frame, &old.timed) { + (Frame::Idle, None) => assert!(old.began.is_none()), + (Frame::Begun { at, queued, cpu, why }, None) => { + assert_eq!(Some((*at, *cpu)), old.began); + assert_eq!((queued.then_some(*at), *why), (old.frame_start, old.frame_why)); + } + (Frame::Open { timed, input_start, cpu }, Some(t)) => { + assert!(t.built.is_none()); + assert_eq!((*input_start, *cpu, timed.arrived, timed.frame_start, timed.note.rank, timed.handler_ms, timed.why, timed.commits), + (old.frame_start, t.cpu.0, t.arrived, t.frame_start, t.rank, t.handler_ms, t.why, t.commits)); + } + (Frame::Built(b), Some(t)) => assert_eq!((Some((b.at, b.phases, b.shaped)), b.cpu_ms, b.stacks.as_ref().map(|s| s.taken)), (t.built, t.cpu.1, t.stacks)), + _ => panic!("phase mismatch"), + } + } + tracker.rolled_since = None; // Don't export the walk's synthetic samples at drop. + } + assert!(slow > 0 && quick > 0, "the walk covers a slow untimed frame ({slow}) and a quick one ({quick})"); +} diff --git a/app/vendor/rune/crates/rune/src/tooling/interaction/gate.rs b/app/vendor/rune/crates/rune/src/tooling/interaction/gate.rs new file mode 100644 index 0000000..5f6f409 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/tooling/interaction/gate.rs @@ -0,0 +1,79 @@ +//! Whether interaction timing runs, read once from the environment, and where it sends. +//! +//! On when `RUNE_PERF=1`, or when `OTEL_EXPORTER_OTLP_ENDPOINT` names a loopback address (a +//! developer's local collector). `RUNE_PERF=0` turns it off over either. A headless run turns on +//! only for `RUNE_PERF=1`, so agents' snapshots and tests don't send. Shipped builds on a user's +//! Mac have neither variable: every check is one load of a cached byte. + +use std::net::SocketAddr; +use std::sync::atomic::{AtomicU8, Ordering}; +use std::sync::OnceLock; + +/// Where `RUNE_PERF=1` sends when no loopback endpoint is set: a local OTLP/HTTP collector. +pub(crate) const DEFAULT_ENDPOINT: &str = "127.0.0.1:27686"; + +const UNKNOWN: u8 = 0; +const OFF: u8 = 1; +const ON: u8 = 2; + +static STATE: AtomicU8 = AtomicU8::new(UNKNOWN); +static ENDPOINT: OnceLock<Option<SocketAddr>> = OnceLock::new(); + +#[inline(always)] +pub(crate) fn on() -> bool { + #[cfg(test)] + return FORCED.get(); + #[cfg(not(test))] + match STATE.load(Ordering::Relaxed) { + ON => true, + OFF => false, + _ => decide(false), + } +} + +/// A headless run: on only for an explicit `RUNE_PERF=1`. +pub(crate) fn headless() { decide(true); } + +#[cold] +fn decide(headless: bool) -> bool { + let perf = rune_core::env::var("RUNE_PERF"); + let otel = rune_core::env::var("OTEL_EXPORTER_OTLP_ENDPOINT"); + let on = !cfg!(test) && !cfg!(target_arch = "wasm32") && wanted(perf.as_deref(), otel.as_deref(), headless); + if on { ENDPOINT.set(endpoint(otel.as_deref())).ok(); } + STATE.store(if on { ON } else { OFF }, Ordering::Relaxed); + on +} + +/// Whether the settings turn timing on. +pub(crate) fn wanted(perf: Option<&str>, otel: Option<&str>, headless: bool) -> bool { + match perf.map(str::trim) { + Some("0") => false, + Some("1") => true, + _ => !headless && otel.and_then(loopback).is_some(), + } +} + +/// Where spans go: the loopback endpoint set, else [`DEFAULT_ENDPOINT`]. +pub(crate) fn endpoint(otel: Option<&str>) -> Option<SocketAddr> { + otel.and_then(loopback).or_else(|| DEFAULT_ENDPOINT.parse().ok()) +} + +/// `http://host:port[/path]` or `host:port` on loopback; anything else is `None`. +pub(crate) fn loopback(setting: &str) -> Option<SocketAddr> { + let rest = setting.trim(); + let rest = rest.strip_prefix("http://").unwrap_or(rest); + let host = rest.split('/').next()?.replace("localhost", "127.0.0.1"); + host.parse::<SocketAddr>().ok().filter(|a| a.ip().is_loopback()) +} + +/// The collector, once timing is on. +pub(crate) fn collector() -> Option<SocketAddr> { ENDPOINT.get().copied().flatten() } + +#[cfg(test)] +thread_local! { + static FORCED: std::cell::Cell<bool> = const { std::cell::Cell::new(false) }; +} + +/// Turns timing on for this test thread, sending nowhere. +#[cfg(test)] +pub(crate) fn force_on() { FORCED.set(true); } diff --git a/app/vendor/rune/crates/rune/src/tooling/interaction/names.rs b/app/vendor/rune/crates/rune/src/tooling/interaction/names.rs new file mode 100644 index 0000000..98b3e76 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/tooling/interaction/names.rs @@ -0,0 +1,117 @@ +//! Names for where an interaction happened, made from element paths: `#0/sidebar/row-x1208` +//! reads `sidebar/row-x*`. Unkeyed segments drop out, digit runs and ids become `*`, and a +//! segment with spaces (prose someone passed as a key) becomes `~`, so the same control on any +//! row shares one name and no user text gets through. Names are interned: after a name's first +//! sighting, naming it again allocates nothing. + +use std::hash::Hasher; +use std::sync::Arc; + +use rustc_hash::{FxHashMap, FxHasher}; + +/// Segments a control name keeps, from the end. +const CONTROL_SEGMENTS: usize = 4; +/// Segments a page name keeps, from the end. +const PAGE_SEGMENTS: usize = 3; +/// Characters a segment keeps. +const SEGMENT_CHARS: usize = 32; + +/// Interned names, by hash. +#[derive(Default)] +pub(crate) struct Names { + names: FxHashMap<u64, Arc<str>>, + scratch: String, +} + +/// A name's hash and its text. +#[derive(Clone)] +pub(crate) struct Name { + pub hash: u64, + pub text: Arc<str>, +} + +impl Names { + /// The control name for `path`. + pub(crate) fn control(&mut self, path: &str) -> Name { self.intern(|out| normalize(path, CONTROL_SEGMENTS, out)) } + + /// A route: a page, and the modal open over it. + pub(crate) fn route(&mut self, page: Option<&str>, modal: Option<&str>) -> Name { + self.intern(|out| { + match page { + Some(page) => normalize(page, PAGE_SEGMENTS, out), + None => out.push_str("root"), + } + if out.is_empty() { out.push_str("root"); } + if let Some(modal) = modal { + out.push_str("+modal:"); + let at = out.len(); + normalize(modal, 1, out); + if out.len() == at { out.push('*'); } + } + }) + } + + /// A fixed name (`window` for a key nothing focused took). + pub(crate) fn fixed(&mut self, name: &str) -> Name { self.intern(|out| out.push_str(name)) } + + fn intern(&mut self, write: impl FnOnce(&mut String)) -> Name { + let mut scratch = std::mem::take(&mut self.scratch); + scratch.clear(); + write(&mut scratch); + let mut h = FxHasher::default(); + h.write(scratch.as_bytes()); + let hash = h.finish(); + let text = self.names.entry(hash).or_insert_with(|| Arc::from(scratch.as_str())).clone(); + self.scratch = scratch; + Name { hash, text } + } +} + +/// Writes `path`'s last `keep` keyed segments, normalized, joined by `/`. +pub(crate) fn normalize(path: &str, keep: usize, out: &mut String) { + let keyed = path.split('/').filter(|s| !s.is_empty() && !s.starts_with('#')); + let skip = keyed.clone().count().saturating_sub(keep); + for (i, seg) in keyed.skip(skip).enumerate() { + if i > 0 { out.push('/'); } + segment(seg, out); + } +} + +fn segment(seg: &str, out: &mut String) { + if seg.chars().any(char::is_whitespace) { + out.push('~'); + return; + } + let start = out.len(); + let mut rest = seg; + while let Some(c) = rest.chars().next() { + if c.is_ascii_alphanumeric() { + let end = rest.find(|c: char| !c.is_ascii_alphanumeric()).unwrap_or(rest.len()); + word(&rest[..end], out); + rest = &rest[end..]; + } else { + out.push(if matches!(c, '-' | '_' | '.' | ':') { c } else { '_' }); + rest = &rest[c.len_utf8()..]; + } + if out.len() - start >= SEGMENT_CHARS { + out.truncate(start + SEGMENT_CHARS); + return; + } + } +} + +/// An alphanumeric run: an id (8 or more characters with a digit) is `*`; otherwise each digit run is. +fn word(w: &str, out: &mut String) { + let digits = w.bytes().any(|b| b.is_ascii_digit()); + if digits && w.len() >= 8 { + star(out); + return; + } + for c in w.chars() { + if c.is_ascii_digit() { star(out) } else { out.push(c) } + } +} + +fn star(out: &mut String) { + if !out.ends_with('*') { out.push('*'); } +} diff --git a/app/vendor/rune/crates/rune/src/tooling/interaction/rollup.rs b/app/vendor/rune/crates/rune/src/tooling/interaction/rollup.rs new file mode 100644 index 0000000..1cd3323 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/tooling/interaction/rollup.rs @@ -0,0 +1,82 @@ +//! Every timed interaction, fast or slow, counted per signature in a fixed histogram, so the +//! collector learns the baseline and which controls people use, not only the slow frames. + +use rustc_hash::FxHashMap; + +use super::names::Name; + +/// Histogram buckets, each [`STEP`] times wider than the last from [`FIRST_MS`]: 0.1 ms to +/// about 750 ms at 15% resolution. +const BUCKETS: usize = 64; +const FIRST_MS: f64 = 0.1; +const STEP: f64 = 1.15; + +/// One signature's counts since the last flush. +pub(crate) struct Roll { + pub route: Name, + pub control: Name, + pub action: &'static str, + pub count: u32, + pub slow: u32, + /// Slow only because the machine was too busy to run it (`Cause::SchedulerWait`). + pub contended: u32, + pub max_ms: f64, + buckets: [u32; BUCKETS], +} + +impl Roll { + /// The value at quantile `q`, as its bucket's upper edge, never above the largest seen. + pub(crate) fn quantile(&self, q: f64) -> f64 { + let rank = ((q * self.count as f64).ceil() as u32).clamp(1, self.count.max(1)); + let mut seen = 0; + for (i, n) in self.buckets.iter().enumerate() { + seen += n; + if seen >= rank { return upper(i).min(self.max_ms); } + } + self.max_ms + } +} + +fn bucket(ms: f64) -> usize { + if ms <= FIRST_MS { return 0; } + ((ms / FIRST_MS).ln() / STEP.ln()).ceil().clamp(0.0, (BUCKETS - 1) as f64) as usize +} + +fn fx(s: &str) -> u64 { + use std::hash::Hasher; + let mut h = rustc_hash::FxHasher::default(); + h.write(s.as_bytes()); + h.finish() +} + +/// A hash of an interaction's signature. +pub(crate) fn signature(route: &Name, control: &Name, action: &str) -> u64 { + route.hash ^ control.hash.rotate_left(21) ^ fx(action).rotate_left(42) +} + +fn upper(i: usize) -> f64 { FIRST_MS * STEP.powi(i as i32) } + +#[derive(Default)] +pub(crate) struct Rollup { + rolls: FxHashMap<u64, Roll>, +} + +impl Rollup { + /// Counts one interaction taking `ms`, `slow` by the app's doing or `contended` by the + /// machine's. + pub(crate) fn add(&mut self, route: &Name, control: &Name, action: &'static str, ms: f64, slow: bool, contended: bool) { + let roll = self.rolls.entry(signature(route, control, action)).or_insert_with(|| Roll { + route: route.clone(), control: control.clone(), action, count: 0, slow: 0, contended: 0, max_ms: 0.0, buckets: [0; BUCKETS], + }); + roll.count += 1; + roll.slow += u32::from(slow); + roll.contended += u32::from(contended); + roll.max_ms = roll.max_ms.max(ms); + roll.buckets[bucket(ms)] += 1; + } + + pub(crate) fn is_empty(&self) -> bool { self.rolls.is_empty() } + + /// Everything counted, emptied. + pub(crate) fn take(&mut self) -> Vec<Roll> { self.rolls.drain().map(|(_, r)| r).collect() } +} diff --git a/app/vendor/rune/crates/rune/src/tooling/interaction/sampler_tests.rs b/app/vendor/rune/crates/rune/src/tooling/interaction/sampler_tests.rs new file mode 100644 index 0000000..e33f041 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/tooling/interaction/sampler_tests.rs @@ -0,0 +1,150 @@ +use super::cause::{Cause, cause}; +use super::stack::{DEPTH, Frame, Raw}; +use super::watchdog::{Sampled, Stacks}; + +fn frame(name: &str, app: bool) -> Frame { Frame { name: name.into(), app } } + +fn sampled(id: usize, waiting: bool, cpu_us: u64, at_ms: u64) -> Sampled { + let mut pcs = [0; DEPTH]; + pcs[0] = id; + Sampled { raw: Raw { pcs, len: 1, waiting, cpu_us, images: 0 }, at_ns: at_ms * 1_000_000 } +} + +#[test] +fn stacks_name_the_innermost_app_frame_most_samples_were_in() { + let sleep = [("__semwait_signal (libsystem_kernel)", false), ("std::thread::sleep", false), ("app::save", true), ("app::main", true)]; + let layout = [("taffy::compute", true), ("app::view", true)]; + let s = Stacks::of(vec![sampled(0, true, 0, 0), sampled(1, false, 1000, 4), sampled(0, true, 1000, 8), sampled(0, true, 2000, 12)]).unwrap(); + assert_eq!((s.taken, s.waiting), (4, 3)); + let names = s.names(|raw| if raw.pcs[0] == 0 { sleep.iter().map(|&(n, a)| frame(n, a)).collect() } else { layout.iter().map(|&(n, a)| frame(n, a)).collect() }); + let hot: Vec<(&str, u32)> = names.hot.iter().map(|(n, c)| (&**n, *c)).collect(); + assert_eq!(hot, [("app::save", 3), ("taffy::compute", 1)]); + assert_eq!(names.stack.first().map(|f| &**f), Some("__semwait_signal (libsystem_kernel)"), "the hottest sample's stack, innermost first"); + assert!((s.cpu_share.unwrap() - 2.0 / 12.0).abs() < 1e-9); + assert!(Stacks::of(Vec::new()).is_none()); + assert_eq!(Stacks::of(vec![sampled(1, false, 0, 0)]).unwrap().cpu_share, None, "one sample has no stretch"); +} + +fn stacks(taken: u32, waiting: u32, cpu_share: Option<f64>) -> Stacks { + Stacks { taken, waiting, cpu_share, raw: Vec::new() } +} + +#[test] +fn a_busy_machine_takes_the_blame_only_when_the_app_was_ready_to_run() { + let slow = 16.7; + assert_eq!(cause(10.0, slow, Some(9.0), None, false), Cause::Queued, "a quick frame that reached the screen late waited outside it"); + assert_eq!(cause(40.0, slow, Some(36.0), None, true), Cause::Cpu, "computing is the app's, busy machine or not"); + assert_eq!(cause(40.0, slow, Some(1.0), Some(&stacks(7, 6, None)), true), Cause::Blocked, "sleeping is the app's, busy machine or not"); + assert_eq!(cause(40.0, slow, Some(1.0), None, false), Cause::Blocked, "little CPU on an idle machine: it waited on something"); + assert_eq!(cause(40.0, slow, Some(1.0), None, true), Cause::SchedulerWait, "little CPU on a busy machine"); + assert_eq!(cause(40.0, slow, Some(4.0), Some(&stacks(7, 0, None)), false), Cause::SchedulerWait, "ready to run all along, yet hardly ran"); + assert_eq!(cause(40.0, slow, None, Some(&stacks(7, 1, Some(0.9))), false), Cause::Cpu, "the samples' CPU share stands in for the clock"); + assert_eq!(cause(40.0, slow, None, None, false), Cause::Cpu); + assert_eq!(cause(40.0, slow, None, None, true), Cause::SchedulerWait); +} + +#[cfg(all(target_os = "macos", target_arch = "aarch64"))] +mod mac { + use std::sync::atomic::{AtomicBool, Ordering}; + use std::sync::{Arc, mpsc}; + + use super::super::stack::{Raw, Target, demangled, frames, library}; + + #[inline(never)] + fn spin_here_for_the_sampler(stop: &AtomicBool) { + while !stop.load(Ordering::Relaxed) { std::hint::spin_loop(); } + } + + /// Runs `body` on a thread, samples it from this one, and stops it. + fn sample_a_thread(body: impl FnOnce(Arc<AtomicBool>, mpsc::Receiver<()>) + Send + 'static) -> (Raw, Vec<String>, Vec<bool>) { + let stop = Arc::new(AtomicBool::new(false)); + let (ready, target) = mpsc::channel(); + let (release, wait) = mpsc::channel(); + let flag = stop.clone(); + let worker = std::thread::spawn(move || { + ready.send(Target::current().unwrap()).unwrap(); + body(flag, wait); + }); + let target: Target = target.recv().unwrap(); + std::thread::sleep(std::time::Duration::from_millis(30)); + let raw = target.sample(|| true, |_| {}).expect("sampled"); + stop.store(true, Ordering::Relaxed); + release.send(()).ok(); + worker.join().unwrap(); + let frames = frames(&raw); + let names = frames.iter().map(|f| f.name.to_string()).collect(); + let app = frames.iter().map(|f| f.app).collect(); + (raw, names, app) + } + + #[test] + fn the_sampler_names_the_function_a_running_thread_is_in() { + let (raw, names, app) = sample_a_thread(|stop, _| spin_here_for_the_sampler(&stop)); + assert!(!raw.waiting, "a spinning thread is running"); + assert!(raw.cpu_us >= 10_000, "it spun for 30 ms before the sample: {} µs", raw.cpu_us); + let at = names.iter().position(|n| n.contains("spin_here_for_the_sampler")).unwrap_or_else(|| panic!("{names:#?}")); + assert!(app[at], "the test binary's own function is app code"); + assert!(raw.len > at + 1, "the walk goes on past it to its callers: {names:#?}"); + } + + #[test] + fn the_sampler_sees_a_waiting_thread_wait() { + let (raw, names, _) = sample_a_thread(|_, wait| { wait.recv().ok(); }); + assert!(raw.waiting, "a thread in recv waits: {names:#?}"); + } + + #[test] + fn a_sample_that_no_longer_applies_is_dropped() { + let stop = Arc::new(AtomicBool::new(false)); + let (ready, got) = mpsc::channel(); + let flag = stop.clone(); + let worker = std::thread::spawn(move || { + ready.send(Target::current().unwrap()).unwrap(); + spin_here_for_the_sampler(&flag); + }); + let target = got.recv().unwrap(); + let caught = std::cell::Cell::new(false); + assert!(target.sample(|| false, |_| caught.set(true)).is_none()); + assert!(!caught.get(), "nothing was caught"); + stop.store(true, Ordering::Relaxed); + worker.join().unwrap(); + } + + #[test] + fn a_caught_sample_is_announced_while_the_thread_is_still_stopped() { + use std::sync::atomic::AtomicU64; + use std::time::Duration; + + let stop = Arc::new(AtomicBool::new(false)); + let count = Arc::new(AtomicU64::new(0)); + let (ready, got) = mpsc::channel(); + let (flag, counting) = (stop.clone(), count.clone()); + let worker = std::thread::spawn(move || { + ready.send(Target::current().unwrap()).unwrap(); + while !flag.load(Ordering::Relaxed) { counting.fetch_add(1, Ordering::Relaxed); } + }); + let target: Target = got.recv().unwrap(); + while count.load(Ordering::Relaxed) == 0 { std::hint::spin_loop(); } + let frozen = std::cell::Cell::new(false); + target.sample(|| true, |_| { + let before = count.load(Ordering::Relaxed); + let until = crate::time::now() + Duration::from_millis(2); + while crate::time::now() < until { std::hint::spin_loop(); } + frozen.set(count.load(Ordering::Relaxed) == before); + }).expect("sampled"); + assert!(frozen.get(), "the thread ran during the announcement"); + let after = count.load(Ordering::Relaxed); + while count.load(Ordering::Relaxed) == after { std::hint::spin_loop(); } + stop.store(true, Ordering::Relaxed); + worker.join().unwrap(); + } + + #[test] + fn names_are_demangled_and_the_standard_library_isnt_the_app() { + assert_eq!(demangled("__RNvCs1mieHSqJ4qC_1m11local_thing"), "m::local_thing"); + assert_eq!(demangled("__ZN3std6thread5sleep17h0123456789abcdefE"), "std::thread::sleep"); + assert_eq!(demangled("__semwait_signal"), "__semwait_signal"); + assert!(library("std::thread::sleep") && library("<core::ops::Range<usize> as Iterator>::next")); + assert!(!library("<app::Save as core::ops::FnOnce>::call_once")); + } +} diff --git a/app/vendor/rune/crates/rune/src/tooling/interaction/stack.rs b/app/vendor/rune/crates/rune/src/tooling/interaction/stack.rs new file mode 100644 index 0000000..e64af32 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/tooling/interaction/stack.rs @@ -0,0 +1,274 @@ +//! Reading another thread's call stack from outside it, for the watchdog (`watchdog`): suspend +//! the thread for a few microseconds, copy its return addresses by following frame pointers +//! inside its stack, resume it, and only then name them. Nothing between suspend and resume +//! allocates or takes a lock, so a thread stopped inside `malloc` can't deadlock the sampler. +//! Names are function symbols only: never stack memory, arguments, paths or environment. +//! +//! Apple Silicon Macs only (their ABI keeps frame pointers in every frame); elsewhere a +//! [`Target`] is never made and the watchdog doesn't start. +#![cfg_attr(not(all(target_os = "macos", target_arch = "aarch64")), allow(dead_code))] +#![allow(unsafe_code)] + +use std::sync::Arc; + +use rustc_hash::FxHashMap; + +/// Return addresses kept per sample, innermost first. +pub(crate) const DEPTH: usize = 32; + +/// One look at a thread's stack. +pub(crate) struct Raw { + pub pcs: [usize; DEPTH], + pub len: usize, + /// The thread was waiting (on IO, a lock, a sleep), not running or ready to run. + pub waiting: bool, + /// The thread's CPU time so far, in µs. + pub cpu_us: u64, + /// How many images had been unloaded just before the sample, for naming it later. + pub images: u64, +} + +/// A named frame: the function, and whether it's the app's own code (in the main executable, +/// outside `std`, `core` and `alloc`). +#[derive(Clone)] +pub(crate) struct Frame { + pub name: Arc<str>, + pub app: bool, +} + +/// Function names for return addresses, remembered for as long as no image is unloaded. +#[derive(Default)] +pub(crate) struct Symbols { + generation: u64, + known: FxHashMap<usize, Frame>, +} + +impl Symbols { + /// `raw`'s frames, innermost first, `lookup` naming each address not yet known (the innermost + /// is the instruction itself rather than a return address after a call). `generation` counts + /// unloaded images: once it has moved since the sample, an address may hold another image's + /// code, so the sample stays bare addresses rather than risk a wrong name. + pub(crate) fn frames(&mut self, raw: &Raw, generation: impl Fn() -> u64, mut lookup: impl FnMut(usize) -> Frame) -> Vec<Frame> { + let now = generation(); + if now != self.generation { + self.known.clear(); + self.generation = now; + } + if now != raw.images { return unresolved(raw); } + let frames = raw.pcs[..raw.len].iter().enumerate().map(|(i, &pc)| { + let at = if i == 0 { pc } else { pc.saturating_sub(1) }; + self.known.entry(at).or_insert_with(|| lookup(at)).clone() + }).collect(); + // An unload during the lookups could have named the wrong image; the next call forgets them. + if generation() != now { return unresolved(raw); } + frames + } +} + +fn unresolved(raw: &Raw) -> Vec<Frame> { + raw.pcs[..raw.len].iter().map(|pc| Frame { name: format!("{pc:#x}").into(), app: false }).collect() +} + +#[cfg(all(target_os = "macos", target_arch = "aarch64"))] +#[cfg_attr(test, allow(unused_imports))] +pub(crate) use mac::{Target, watch_unloads}; + +#[cfg(all(target_os = "macos", target_arch = "aarch64"))] +mod mac { + use std::ffi::{CStr, c_void}; + use std::sync::atomic::{AtomicU64, Ordering}; + + use super::{DEPTH, Frame, Raw}; + + type Port = u32; + + #[repr(C)] + #[derive(Default)] + struct ThreadState { + x: [u64; 29], + fp: u64, + lr: u64, + sp: u64, + pc: u64, + cpsr: u32, + pad: u32, + } + const ARM_THREAD_STATE64: i32 = 6; + const ARM_THREAD_STATE64_COUNT: u32 = (size_of::<ThreadState>() / 4) as u32; + + #[repr(C)] + #[derive(Default)] + struct BasicInfo { + user: [i32; 2], + system: [i32; 2], + cpu_usage: i32, + policy: i32, + run_state: i32, + flags: i32, + suspend_count: i32, + sleep_time: i32, + } + const THREAD_BASIC_INFO: u32 = 3; + const THREAD_BASIC_INFO_COUNT: u32 = (size_of::<BasicInfo>() / 4) as u32; + const TH_STATE_RUNNING: i32 = 1; + + // Pointer authentication signs return addresses in system frameworks; addresses fit in 47 bits. + const ADDRESS_MASK: usize = (1 << 47) - 1; + + unsafe extern "C" { + fn mach_thread_self() -> Port; + fn thread_suspend(thread: Port) -> i32; + fn thread_resume(thread: Port) -> i32; + fn thread_get_state(thread: Port, flavor: i32, state: *mut u32, count: *mut u32) -> i32; + fn thread_info(thread: Port, flavor: u32, info: *mut i32, count: *mut u32) -> i32; + fn pthread_get_stackaddr_np(thread: libc::pthread_t) -> *mut c_void; + fn pthread_get_stacksize_np(thread: libc::pthread_t) -> usize; + fn _dyld_get_image_header(index: u32) -> *const c_void; + fn _dyld_register_func_for_remove_image(callback: extern "C" fn(*const c_void, isize)); + } + + /// Images unloaded since [`watch_unloads`]. dyld reports an unload before unmapping it. + static UNLOADS: AtomicU64 = AtomicU64::new(0); + + #[cfg_attr(test, allow(dead_code))] + extern "C" fn unloaded(_: *const c_void, _: isize) { UNLOADS.fetch_add(1, Ordering::SeqCst); } + + /// Starts counting unloaded images, for the life of the process. Call once, before sampling. + #[cfg_attr(test, allow(dead_code))] + pub(crate) fn watch_unloads() { + // SAFETY: `unloaded` lives for the process and touches only an atomic. + unsafe { _dyld_register_func_for_remove_image(unloaded) }; + } + + pub(super) fn generation() -> u64 { UNLOADS.load(Ordering::SeqCst) } + + /// A thread that can be sampled from another: its Mach port and stack range. + #[derive(Clone, Copy)] + pub(crate) struct Target { + port: Port, + low: usize, + high: usize, + } + + impl Target { + /// The calling thread. + pub(crate) fn current() -> Option<Self> { + // SAFETY: plain queries of the calling thread; the port reference is kept for the + // process's life (the watchdog samples it until exit). + unsafe { + let me = libc::pthread_self(); + let high = pthread_get_stackaddr_np(me) as usize; + let size = pthread_get_stacksize_np(me); + (high > size && size > 0).then(|| Self { port: mach_thread_self(), low: high - size, high }) + } + } + + /// Samples the thread if `still()` holds once it's stopped, handing the sample to + /// `caught` before resuming it: `None` when it doesn't hold, or the thread can't be + /// stopped or read. + pub(crate) fn sample(&self, still: impl Fn() -> bool, caught: impl Fn(&Raw)) -> Option<Raw> { + let mut info = BasicInfo::default(); + let mut count = THREAD_BASIC_INFO_COUNT; + // SAFETY: `info` is a live buffer of `count` 32-bit words, as the flavor needs. + if unsafe { thread_info(self.port, THREAD_BASIC_INFO, (&raw mut info).cast(), &mut count) } != 0 { return None; } + let cpu_us = [info.user, info.system].iter().map(|t| t[0] as u64 * 1_000_000 + t[1] as u64).sum(); + let mut raw = Raw { pcs: [0; DEPTH], len: 0, waiting: info.run_state != TH_STATE_RUNNING, cpu_us, images: generation() }; + // SAFETY: suspending a thread of this process that isn't the caller (`watchdog` + // samples only the UI thread from its own thread). It's resumed below on every path. + if unsafe { thread_suspend(self.port) } != 0 { return None; } + let walked = still() && self.walk(&mut raw); + if walked { caught(&raw); } + // SAFETY: resumes the suspension above. + unsafe { thread_resume(self.port) }; + walked.then_some(raw) + } + + /// Copies the stopped thread's return addresses. No allocation, no locks. + fn walk(&self, raw: &mut Raw) -> bool { + let mut state = ThreadState::default(); + let mut count = ARM_THREAD_STATE64_COUNT; + // SAFETY: `state` is a live buffer of `count` 32-bit words, as the flavor needs. + if unsafe { thread_get_state(self.port, ARM_THREAD_STATE64, (&raw mut state).cast(), &mut count) } != 0 { return false; } + fn push(raw: &mut Raw, pc: usize) { + let pc = pc & ADDRESS_MASK; + if pc != 0 && raw.len < DEPTH && (raw.len == 0 || raw.pcs[raw.len - 1] != pc) { + raw.pcs[raw.len] = pc; + raw.len += 1; + } + } + push(raw, state.pc as usize); + // A leaf that saved no frame record (a syscall stub) returns through `lr`; one that + // did has also saved it at `fp + 8`, where the walk below finds it. + let mut fp = state.fp as usize; + let saved = |fp: usize| (fp >= self.low && fp.is_multiple_of(8) && fp + 16 <= self.high).then(|| { + // SAFETY: `fp` and `fp + 8` lie inside the stopped thread's own stack. + unsafe { (*(fp as *const usize), *((fp + 8) as *const usize)) } + }); + if saved(fp).is_some_and(|(_, ret)| ret & ADDRESS_MASK != state.lr as usize & ADDRESS_MASK) { push(raw, state.lr as usize); } + while let Some((next, ret)) = saved(fp) { + if ret & ADDRESS_MASK == 0 || raw.len == DEPTH { break; } + push(raw, ret); + if next <= fp { break; } + fp = next; + } + true + } + } + + /// The function at `at`: `dladdr` over the loaded images' symbol tables, Rust names demangled + /// without their hashes. + pub(super) fn name(at: usize) -> Frame { + // SAFETY: `Dl_info` is plain pointers, for which all zeroes is valid (null). + let mut info: libc::Dl_info = unsafe { std::mem::zeroed() }; + // SAFETY: `info` is a live, writable `Dl_info`; dladdr only reads loaded images. + if unsafe { libc::dladdr(at as *const c_void, &mut info) } == 0 || info.dli_sname.is_null() { + return Frame { name: format!("{at:#x}").into(), app: false }; + } + // SAFETY: dladdr returned a NUL-terminated symbol name that lives as long as its image. + let symbol = unsafe { CStr::from_ptr(info.dli_sname) }.to_string_lossy(); + let mut name = super::demangled(&symbol); + // SAFETY: image 0 is the main executable, loaded for the process's life. + let main = unsafe { _dyld_get_image_header(0) }; + let app = std::ptr::eq(info.dli_fbase.cast_const(), main) && !super::library(&name); + if !std::ptr::eq(info.dli_fbase.cast_const(), main) && !info.dli_fname.is_null() { + // SAFETY: as above, the image's NUL-terminated path. + let path = unsafe { CStr::from_ptr(info.dli_fname) }.to_string_lossy(); + let image = path.rsplit('/').next().unwrap_or("").trim_end_matches(".dylib"); + if !image.is_empty() { name = format!("{name} ({image})"); } + } + Frame { name: name.into(), app } + } +} + +/// A sample's frames, innermost first, from this thread's memory of names. +#[cfg(all(target_os = "macos", target_arch = "aarch64"))] +pub(crate) fn frames(raw: &Raw) -> Vec<Frame> { + thread_local! { + static SYMBOLS: std::cell::RefCell<Symbols> = std::cell::RefCell::default(); + } + SYMBOLS.with_borrow_mut(|symbols| symbols.frames(raw, mac::generation, mac::name)) +} + +/// Without a sampler there are no samples to name. +#[cfg(not(all(target_os = "macos", target_arch = "aarch64")))] +pub(crate) fn frames(_: &Raw) -> Vec<Frame> { Vec::new() } + +/// `symbol` demangled, without its hash, cut to 160 characters. +#[cfg(all(target_os = "macos", target_arch = "aarch64"))] +pub(crate) fn demangled(symbol: &str) -> String { + let mut name = format!("{:#}", rustc_demangle::demangle(symbol.strip_prefix('_').filter(|s| s.starts_with("_ZN") || s.starts_with("_R")).unwrap_or(symbol))); + if name.len() > 160 { + let mut cut = 157; + while !name.is_char_boundary(cut) { cut -= 1; } + name.truncate(cut); + name.push_str("..."); + } + name +} + +/// Whether `name` is the standard library's, so never the place an app spent its time. +#[cfg(all(target_os = "macos", target_arch = "aarch64"))] +pub(crate) fn library(name: &str) -> bool { + let name = name.trim_start_matches('<'); + ["std::", "core::", "alloc::", "__rust", "rust_"].iter().any(|p| name.starts_with(p)) +} diff --git a/app/vendor/rune/crates/rune/src/tooling/interaction/tests.rs b/app/vendor/rune/crates/rune/src/tooling/interaction/tests.rs new file mode 100644 index 0000000..7f62e8d --- /dev/null +++ b/app/vendor/rune/crates/rune/src/tooling/interaction/tests.rs @@ -0,0 +1,214 @@ +use std::cell::RefCell; +use std::time::Duration; + +use super::names::normalize; +use super::rollup::Rollup; +use super::*; +use crate::{Cx, El, Env, Ime, Runtime, TextEdit, TextStyle, col, el, text_input}; + +thread_local! { + pub(super) static SENT: RefCell<Vec<Slow>> = const { RefCell::new(Vec::new()) }; + pub(super) static FRAMES: RefCell<Vec<SlowFrame>> = const { RefCell::new(Vec::new()) }; + pub(super) static OVERLOADED: std::cell::Cell<bool> = const { std::cell::Cell::new(false) }; +} + +fn norm(path: &str, keep: usize) -> String { + let mut out = String::new(); + normalize(path, keep, &mut out); + out +} + +#[test] +fn names_drop_unkeyed_segments_ids_and_prose() { + assert_eq!(norm("#0/sidebar/row-x1208", 4), "sidebar/row-x*"); + assert_eq!(norm("#0/#2/list/item-3f9a2c41d7e0/open", 4), "list/item-*/open"); + assert_eq!(norm("#0/a/b/c/d/e", 4), "b/c/d/e"); + assert_eq!(norm("#0/notes/Buy milk tomorrow", 4), "notes/~"); + assert_eq!(norm("#0/k-palette", 4), "k-palette"); + assert_eq!(norm("#0/a\u{e9}b", 4), "a_b"); + assert_eq!(norm(&format!("#0/{}", "x".repeat(50)), 4).len(), 32); +} + +#[test] +fn names_are_interned() { + let mut names = Names::default(); + let a = names.control("#0/list/row-1/open"); + let b = names.control("#0/list/row-22/open"); + assert_eq!(a.hash, b.hash); + assert!(Arc::ptr_eq(&a.text, &b.text), "the second sighting reuses the first's text"); + assert_eq!(&*names.route(Some("#0/settings"), Some("#0/settings/confirm-7")).text, "settings+modal:confirm-*"); + assert_eq!(&*names.route(None, None).text, "root"); +} + +#[test] +fn the_gate_wants_perf_or_a_loopback_collector() { + use gate::{loopback, wanted}; + assert!(wanted(Some("1"), None, true), "RUNE_PERF=1 turns it on, headless too"); + assert!(!wanted(Some("0"), Some("http://127.0.0.1:27686"), false), "RUNE_PERF=0 wins"); + assert!(wanted(None, Some("http://127.0.0.1:27686"), false)); + assert!(wanted(None, Some("http://localhost:4318/"), false)); + assert!(!wanted(None, Some("http://127.0.0.1:27686"), true), "a headless run needs RUNE_PERF=1"); + assert!(!wanted(None, Some("https://otel.example.com:4318"), false), "a remote collector isn't a dev Mac"); + assert!(!wanted(None, None, false), "a user's Mac has neither"); + assert_eq!(loopback("[::1]:4318").map(|a| a.port()), Some(4318)); + assert_eq!(gate::endpoint(None).map(|a| a.to_string()).as_deref(), Some(gate::DEFAULT_ENDPOINT)); +} + +#[test] +fn rollup_quantiles_land_within_a_bucket() { + let mut names = Names::default(); + let (route, control) = (names.fixed("root"), names.fixed("save")); + let mut rollup = Rollup::default(); + for i in 1..=100 { rollup.add(&route, &control, "on_press", i as f64, i > 98, false); } + let rolls = rollup.take(); + assert_eq!(rolls.len(), 1); + let r = &rolls[0]; + assert_eq!((r.count, r.slow, r.max_ms), (100, 2, 100.0)); + assert!((r.quantile(0.5) - 50.0).abs() / 50.0 < 0.16, "p50 {}", r.quantile(0.5)); + assert!((r.quantile(0.98) - 98.0).abs() / 98.0 < 0.16, "p98 {}", r.quantile(0.98)); + assert!(rollup.is_empty()); +} + +#[derive(Default)] +struct App { + note: TextEdit, + presses: u32, + slow: bool, +} + +fn view(s: &App, _: &mut Cx<App>) -> El { + let list = (0..30).fold(col().key("list"), |c, i| c.child(el().key(format!("row-{i}")).h(4.0))); + col().key("settings").w_full().h_full() + .child(el().key("save-42").size(80.0, 30.0).on_press(|s: &mut App| { + s.presses += 1; + if s.slow { std::thread::sleep(Duration::from_millis(25)); } + })) + .child(text_input(&s.note, TextStyle::new(14.0, 400.0)).single_line().key("note").size(200.0, 24.0).on_edit(|s: &mut App| &mut s.note)) + .child(el().key("count").child(crate::text(format!("{}", s.presses)))) + .child(list) +} + +fn runtime(slow: bool) -> Runtime<App> { + force_on(); + // A fixed threshold: the slow-click tests never read `RUNE_PERF_SLOW_MS` from the environment. + super::force_slow_ms(SLOW_MS); + SENT.take(); + let mut rt = Runtime::new(App { slow, ..App::default() }, view, (400.0, 300.0), Env::new(true, 1.0)); + rt.frame(0.0); + rt +} + +fn force_on() { gate::force_on(); } + +fn s_route(rt: &mut Runtime<App>) -> Name { rt.interaction_tracker().names.route(Some("#0/settings"), None) } +fn s_control(rt: &mut Runtime<App>) -> Name { rt.interaction_tracker().names.control("#0/settings/save-42") } + +fn click(rt: &mut Runtime<App>, key: &str) { + let (x, y) = rt.find(key).unwrap(); + rt.pointer_down(x, y); + rt.pointer_up(x, y); + rt.frame(1.0 / 60.0); + rt.interaction_presented(crate::time::now(), None); +} + +#[test] +fn a_slow_click_names_its_page_and_control() { + let mut rt = runtime(true); + click(&mut rt, "save-42"); + let sent = SENT.take(); + assert_eq!(sent.len(), 1, "one slow interaction"); + let s = &sent[0]; + assert_eq!((&*s.route, &*s.control, s.action), ("settings", "settings/save-*", "on_press")); + assert!(s.handler_ms >= 25.0, "the handler's sleep is its time: {}", s.handler_ms); + let note = Note { route: s_route(&mut rt), control: s_control(&mut rt), action: "on_press", rank: 3 }; + assert!(rt.interaction_tracker().breached(&note), "a slow signature is sampled sooner next time"); + assert!(s.commits >= 1 && s.why & crate::runtime::CommitWhy::INPUT != 0); + assert!(s.phases[Phase::View as usize] > 0.0, "the view phase timed itself"); + assert!(s.present >= s.submitted && s.submitted >= s.built && s.built >= s.frame_start && s.frame_start >= s.arrived); + assert_eq!(s.rebuilt.first().map(|r| &*r.0), Some("settings"), "nothing is memoized: the whole page rebuilt"); + assert!(!active(), "phases stop timing once the frame is built"); +} + +#[test] +fn a_slow_click_says_whose_time_it_took() { + let mut rt = runtime(true); + click(&mut rt, "save-42"); + let s = SENT.take().pop().unwrap(); + assert_eq!(s.cause, Cause::Blocked, "the handler slept: little CPU on an idle machine"); + assert!(s.cpu_ms.is_some_and(|cpu| cpu < 25.0), "the frame's CPU, without the sleep: {:?}", s.cpu_ms); + let rolls = rt.interaction_tracker().rollup.take(); + assert_eq!((rolls[0].slow, rolls[0].contended), (1, 0)); + + OVERLOADED.set(true); + let mut rt = runtime(true); + click(&mut rt, "save-42"); + OVERLOADED.set(false); + assert_eq!(SENT.take().pop().unwrap().cause, Cause::SchedulerWait, "on a busy machine, the same frame is the machine's"); + let tracker = rt.interaction_tracker(); + let rolls = tracker.rollup.take(); + assert_eq!((rolls[0].slow, rolls[0].contended), (0, 1), "not counted against the app"); + assert!(tracker.breached.is_empty(), "nor sampled sooner next time"); +} + +#[test] +fn a_fast_click_only_counts() { + let mut rt = runtime(false); + click(&mut rt, "save-42"); + assert!(SENT.take().is_empty()); + let rolls = rt.interaction_tracker().rollup.take(); + assert_eq!(rolls.len(), 1); + assert_eq!((&*rolls[0].control.text, rolls[0].count), ("settings/save-*", 1)); +} + +#[test] +fn typing_in_a_field_says_key_edit_never_the_text() { + let mut rt = runtime(false); + click(&mut rt, "note"); + rt.interaction_tracker().rollup.take(); + rt.ime(Ime::Commit("secret".into())); + rt.frame(1.0 / 60.0); + rt.interaction_presented(crate::time::now(), None); + let rolls = rt.interaction_tracker().rollup.take(); + assert_eq!(rolls.iter().map(|r| (&*r.control.text, r.action)).collect::<Vec<_>>(), [("settings/note", "key_edit")]); +} + +#[test] +fn a_frame_no_host_presents_ends_at_its_build() { + let mut rt = runtime(true); + let (x, y) = rt.find("save-42").unwrap(); + rt.pointer_down(x, y); + rt.pointer_up(x, y); + rt.frame(1.0 / 60.0); + assert!(SENT.take().is_empty(), "waits for the host"); + rt.frame(1.0 / 60.0); + let sent = SENT.take(); + assert_eq!(sent.len(), 1); + assert_eq!(sent[0].present, sent[0].built); +} + +#[test] +fn off_nothing_is_timed() { + SENT.take(); + let mut rt = Runtime::new(App { slow: true, ..App::default() }, view, (400.0, 300.0), Env::new(true, 1.0)); + rt.frame(0.0); + click(&mut rt, "save-42"); + assert!(SENT.take().is_empty()); + let tracker = rt.interaction_tracker(); + assert!(tracker.rollup.is_empty() && matches!(tracker.frame, Frame::Idle)); +} + +#[test] +fn slow_spans_carry_the_signature_and_stretches() { + let mut rt = runtime(true); + click(&mut rt, "save-42"); + let slow = SENT.take().pop().unwrap(); + let spans = export::slow_spans(&slow); + let names: Vec<_> = spans.iter().map(|s| s["name"].as_str().unwrap()).collect(); + assert_eq!(names[0], "ui.interaction"); + assert!(names.contains(&"update")); + let attr = |key: &str| spans[0]["attributes"].as_array().unwrap().iter().find(|a| a["key"] == key).map(|a| a["value"].clone()); + assert_eq!(attr("rune.route").unwrap()["stringValue"], "settings"); + assert_eq!(attr("rune.control").unwrap()["stringValue"], "settings/save-*"); + let root = spans[0]["spanId"].clone(); + assert!(spans[1..].iter().all(|s| s["parentSpanId"] == root && s["traceId"] == spans[0]["traceId"])); +} diff --git a/app/vendor/rune/crates/rune/src/tooling/interaction/watchdog.rs b/app/vendor/rune/crates/rune/src/tooling/interaction/watchdog.rs new file mode 100644 index 0000000..7eac3b2 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/tooling/interaction/watchdog.rs @@ -0,0 +1,442 @@ +//! The watchdog: a thread that looks at the UI thread's stack while a frame is still running +//! long, so a slow interaction says which functions its time went to. Sampling after the frame +//! is too late; the hitch is over by then. +//! +//! A frame arms it ([`arm`]) with a sequentially consistent store of its start, so it and a +//! parking watchdog can't miss each other, and [`disarm`] clears it. The watchdog sleeps until the frame is [`AFTER_MS`] old ([`HURRY_MS`] for a signature that was +//! slow before), then samples every [`EVERY`] until the frame ends. Between frames it checks +//! every [`IDLE_POLL`], and after a second with no frame it parks, so a resting app wakes it +//! never and the UI thread unparks it only for the first frame after a rest. +//! +//! The thread decodes what it reads once (`look`), and its decisions are one machine ([`Watch`], +//! [`step`]). The atomics are only how a frame gets across. A sample stays raw addresses until +//! the report is written, on the exporter's thread, so `disarm` never waits for names. +//! +//! Started by the first armed frame, on the thread that armed it; frames on other threads (a +//! second runtime on a worker) aren't watched. Apple Silicon Macs only (`stack`). +#![cfg_attr(not(all(target_os = "macos", target_arch = "aarch64", not(test))), allow(dead_code))] + +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering}; +use std::time::Duration; + +use super::stack::{DEPTH, Frame, Raw}; +use crate::machine::Effects; + +/// A frame this old is sampled. +pub(crate) const AFTER_MS: u32 = 12; +/// A frame whose interaction was slow before is sampled from this age. +pub(crate) const HURRY_MS: u32 = 4; +/// Samples per frame at most. +const MOST: usize = 64; +/// Between samples of one long frame. +const EVERY: Duration = Duration::from_millis(4); +/// Between looks for a new frame while frames are coming. +const IDLE_POLL: Duration = Duration::from_millis(8); +/// No frame for this long and the watchdog parks until the next one unparks it. +const REST: Duration = Duration::from_secs(1); + +/// What a look read of the running frame. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +struct Running { + seq: u64, + /// In ns on the watchdog's clock. + start: u64, + after_us: u32, +} + +/// How far the watchdog got with frame `seq`: `taken` samples tried, the next at `due`. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +struct Progress { + seq: u64, + taken: usize, + due: u64, +} + +/// What the watchdog's thread is doing. Clock values are ns. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Watch { + /// It hasn't looked yet. + Unarmed, + /// Frame `seq` runs, not yet sampled; old enough at `due`. + Waiting { seq: u64, due: u64 }, + Sampling(Progress), + /// No frame since `since`. `left` is the frame it was sampling: a look can land inside + /// `arm`, after the number moved and before the start did, so that number can come back. + Quiet { since: u64, left: Option<Progress> }, + /// No frame for [`REST`]: asleep until a frame unparks it. + Parked { left: Option<Progress> }, +} + +impl Watch { + /// How far it got with frame `seq`, if it has tried to sample it. + fn progress(self, seq: u64) -> Option<Progress> { + match self { + Watch::Sampling(p) | Watch::Quiet { left: Some(p), .. } | Watch::Parked { left: Some(p) } if p.seq == seq => Some(p), + _ => None, + } + } +} + +#[derive(Clone, Copy, Debug)] +enum Event { + /// The thread looked at what's running. + Look { frame: Option<Running>, now: u64 }, + /// A sample of frame `seq` was tried, and ended at `now`. + Taken { seq: u64, now: u64 }, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Effect { + /// Sleep this long, or until unparked, then look again. + Sleep(Duration), + /// Sleep until unparked, then look again. + Park, + /// Try a sample of frame `seq`, if it still runs from `start`, stamped `at`; then report + /// [`Event::Taken`]. + Sample { seq: u64, start: u64, at: u64 }, +} + +fn step(watch: &mut Watch, event: Event) -> Effects<Effect> { + match event { + Event::Look { frame: None, now } => { + let (since, left) = match *watch { + Watch::Parked { .. } => return Effects::one(Effect::Park), + Watch::Quiet { since, left } => (since, left), + Watch::Sampling(progress) => (now, Some(progress)), + Watch::Unarmed | Watch::Waiting { .. } => (now, None), + }; + if now.saturating_sub(since) < REST.as_nanos() as u64 { + *watch = Watch::Quiet { since, left }; + Effects::one(Effect::Sleep(IDLE_POLL)) + } else { + *watch = Watch::Parked { left }; + Effects::one(Effect::Park) + } + } + Event::Look { frame: Some(Running { seq, start, after_us }), now } => { + // Unsampled, the due time follows `after_us`, which `hurry` can bring forward. + let progress = watch.progress(seq).unwrap_or(Progress { seq, taken: 0, due: start + u64::from(after_us) * 1000 }); + let Progress { taken, due, .. } = progress; + *watch = if taken == 0 { Watch::Waiting { seq, due } } else { Watch::Sampling(progress) }; + Effects::one(if taken >= MOST { + Effect::Sleep(IDLE_POLL) + } else if now < due { + Effect::Sleep(Duration::from_nanos(due - now)) + } else { + Effect::Sample { seq, start, at: now } + }) + } + Event::Taken { seq, now } => { + let taken = match *watch { + Watch::Waiting { seq: held, .. } if held == seq => 0, + Watch::Sampling(Progress { seq: held, taken, .. }) if held == seq => taken, + _ => return Effects::none(), + }; + *watch = Watch::Sampling(Progress { seq, taken: taken + 1, due: now + EVERY.as_nanos() as u64 }); + Effects::none() + } + } +} + +/// The samples a slow frame took, summarized. +pub(crate) struct Stacks { + pub taken: u32, + /// Samples that found the thread waiting (IO, a lock, a sleep) rather than running. + pub waiting: u32, + /// The thread's CPU time over the sampled stretch as a share of its wall time, from two or + /// more samples. + pub cpu_share: Option<f64>, + /// The samples' addresses, for [`Stacks::names`]. + pub raw: Vec<Raw>, +} + +/// What a slow frame's samples say once named. +pub(crate) struct Names { + /// The functions samples were in, by count: each sample's innermost app frame, else its + /// innermost frame. + pub hot: Vec<(Arc<str>, u32)>, + /// A sample at the hottest function, innermost frame first. + pub stack: Vec<Arc<str>>, +} + +/// One sample. +pub(crate) struct Sampled { + pub raw: Raw, + pub at_ns: u64, +} + +impl Stacks { + pub(crate) fn of(samples: Vec<Sampled>) -> Option<Self> { + let first = samples.first()?; + let last = samples.last()?; + let wall_us = last.at_ns.saturating_sub(first.at_ns) / 1000; + let cpu_share = (samples.len() >= 2 && wall_us > 0).then(|| last.raw.cpu_us.saturating_sub(first.raw.cpu_us) as f64 / wall_us as f64); + Some(Stacks { + taken: samples.len() as u32, + waiting: samples.iter().filter(|s| s.raw.waiting).count() as u32, + cpu_share, + raw: samples.into_iter().map(|s| s.raw).collect(), + }) + } + + /// Names the samples with `frames`. Slow: never on the UI thread. + pub(crate) fn names(&self, frames: impl FnMut(&Raw) -> Vec<Frame>) -> Names { + let named: Vec<Vec<Frame>> = self.raw.iter().map(frames).collect(); + let spot = |s: &Vec<Frame>| s.iter().find(|f| f.app).or(s.first()).map(|f| f.name.clone()); + let mut hot: Vec<(Arc<str>, u32)> = Vec::new(); + for name in named.iter().filter_map(spot) { + match hot.iter_mut().find(|(n, _)| *n == name) { + Some((_, count)) => *count += 1, + None => hot.push((name, 1)), + } + } + hot.sort_by_key(|h| std::cmp::Reverse(h.1)); + let top = hot.first().map(|h| h.0.clone()); + let stack = named.iter().find(|s| spot(s) == top).map(|s| s.iter().take(16).map(|f| f.name.clone()).collect()).unwrap_or_default(); + hot.truncate(3); + Names { hot, stack } + } +} + +/// The frame atomics, one call per atomic, so a test can land writes between any two. +trait Frames { + fn start(&self) -> u64; + fn seq(&self) -> u64; + fn after_us(&self) -> u32; + fn next_seq(&self); + fn set_after_us(&self, us: u32); + fn set_start(&self, ns: u64); +} + +/// Reads what's running and decodes it. Past here, no frame is `None`, not a zero. +fn look(frames: &impl Frames) -> Option<Running> { + let start = frames.start(); + if start == 0 { return None; } + let seq = frames.seq(); + Some(Running { seq, start, after_us: frames.after_us() }) +} + +/// A frame's writes when it starts. +fn begin(frames: &impl Frames, now: impl FnOnce() -> u64) { + frames.next_seq(); + frames.set_after_us(AFTER_MS * 1000); + frames.set_start(now()); +} + +/// Tries one sample of frame `seq`. `sample` stops the thread, calls its argument with the +/// sample while it's stopped, and resumes it: a `disarm` right after must find the sample. +fn capture(samples: &Caught, taken: &AtomicBool, seq: u64, at: u64, sample: impl FnOnce(&dyn Fn(&Raw)) -> Option<Raw>) { + sample(&|raw| samples.publish(taken, seq, at, raw)); +} + +/// What was caught of the frame that just ended; `seq` reads its number if anything was. +fn collected(samples: &Caught, taken: &AtomicBool, seq: impl FnOnce() -> u64) -> Option<Stacks> { + if !taken.swap(false, Ordering::Acquire) { return None; } + samples.collect(seq()) +} + +/// One stored sample. +struct Slot { + pcs: [AtomicUsize; DEPTH], + len: AtomicUsize, + waiting: AtomicBool, + cpu_us: AtomicU64, + at_ns: AtomicU64, + images: AtomicU64, +} + +impl Slot { + const fn new() -> Self { + Self { pcs: [const { AtomicUsize::new(0) }; DEPTH], len: AtomicUsize::new(0), waiting: AtomicBool::new(false), cpu_us: AtomicU64::new(0), at_ns: AtomicU64::new(0), images: AtomicU64::new(0) } + } + + fn write(&self, raw: &Raw, at: u64) { + for (slot, &pc) in self.pcs.iter().zip(&raw.pcs[..raw.len]) { slot.store(pc, Ordering::Relaxed); } + self.len.store(raw.len, Ordering::Relaxed); + self.waiting.store(raw.waiting, Ordering::Relaxed); + self.cpu_us.store(raw.cpu_us, Ordering::Relaxed); + self.at_ns.store(at, Ordering::Relaxed); + self.images.store(raw.images, Ordering::Relaxed); + } + + fn read(&self) -> Sampled { + let len = self.len.load(Ordering::Relaxed); + let mut pcs = [0; DEPTH]; + for (pc, slot) in pcs.iter_mut().zip(&self.pcs[..len]) { *pc = slot.load(Ordering::Relaxed); } + Sampled { raw: Raw { pcs, len, waiting: self.waiting.load(Ordering::Relaxed), cpu_us: self.cpu_us.load(Ordering::Relaxed), images: self.images.load(Ordering::Relaxed) }, at_ns: self.at_ns.load(Ordering::Relaxed) } + } +} + +/// One frame's samples, in storage made ahead of time. `publish` runs only while the UI thread +/// is stopped inside its frame and `collect` only on that thread after it has ended the frame, +/// so the two never overlap and neither takes a lock. A new frame's first sample replaces the +/// last frame's. +struct Caught { + seq: AtomicU64, + count: AtomicUsize, + slots: [Slot; MOST], +} + +impl Caught { + const fn new() -> Self { Self { seq: AtomicU64::new(0), count: AtomicUsize::new(0), slots: [const { Slot::new() }; MOST] } } + + /// Stores a sample of frame `seq` and says one was caught, before the thread resumes: a + /// `disarm` right after must find it. No lock or allocation. + fn publish(&self, taken: &AtomicBool, seq: u64, at: u64, raw: &Raw) { + let count = if self.seq.load(Ordering::Relaxed) == seq { self.count.load(Ordering::Relaxed) } else { 0 }; + let Some(slot) = self.slots.get(count) else { return }; + slot.write(raw, at); + self.seq.store(seq, Ordering::Relaxed); + self.count.store(count + 1, Ordering::Relaxed); + taken.store(true, Ordering::Release); + } + + /// Frame `seq`'s samples, summarized. Other frames' are left behind. + fn collect(&self, seq: u64) -> Option<Stacks> { + if self.seq.load(Ordering::Relaxed) != seq { return None; } + Stacks::of(self.slots[..self.count.load(Ordering::Relaxed)].iter().map(Slot::read).collect()) + } +} + +#[cfg(all(target_os = "macos", target_arch = "aarch64", not(test)))] +pub(crate) use mac::{arm, disarm, hurry}; + +/// Without a sampler (other systems, unit tests), frames aren't watched. +#[cfg(not(all(target_os = "macos", target_arch = "aarch64", not(test))))] +mod none { + pub(crate) fn arm() {} + pub(crate) fn hurry() {} + pub(crate) fn disarm() -> Option<super::Stacks> { None } +} +#[cfg(not(all(target_os = "macos", target_arch = "aarch64", not(test))))] +pub(crate) use none::{arm, disarm, hurry}; + +#[cfg(all(target_os = "macos", target_arch = "aarch64", not(test)))] +mod mac { + use std::cell::Cell; + use std::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, Ordering}; + use std::sync::OnceLock; + use std::thread::{Thread, ThreadId}; + use std::time::Instant; + + use super::super::stack::{Target, watch_unloads}; + use super::{AFTER_MS, Caught, Effect, Event, Frames, HURRY_MS, Stacks, Watch, begin, capture, collected, look, step}; + + /// Bumped by each frame, so a sample can tell its frame is the one still running. + static SEQ: AtomicU64 = AtomicU64::new(0); + /// The running frame's start in ns since `epoch` (plus one), or 0 between frames. + static START: AtomicU64 = AtomicU64::new(0); + static AFTER_US: AtomicU32 = AtomicU32::new(AFTER_MS * 1000); + static PARKED: AtomicBool = AtomicBool::new(false); + static TAKEN: AtomicBool = AtomicBool::new(false); + static SAMPLES: Caught = Caught::new(); + + /// The statics, as [`Frames`]. + struct Statics; + + impl Frames for Statics { + #[inline(always)] + fn start(&self) -> u64 { START.load(Ordering::SeqCst) } + #[inline(always)] + fn seq(&self) -> u64 { SEQ.load(Ordering::SeqCst) } + #[inline(always)] + fn after_us(&self) -> u32 { AFTER_US.load(Ordering::Relaxed) } + #[inline(always)] + fn next_seq(&self) { SEQ.fetch_add(1, Ordering::Relaxed); } + #[inline(always)] + fn set_after_us(&self, us: u32) { AFTER_US.store(us, Ordering::Relaxed); } + #[inline(always)] + fn set_start(&self, ns: u64) { START.store(ns, Ordering::SeqCst); } + } + + /// Whether a thread's frames are watched. + #[derive(Clone, Copy, PartialEq, Eq)] + enum Watched { + NotAsked, + Yes, + No, + } + + thread_local! { + static WATCHED: Cell<Watched> = const { Cell::new(Watched::NotAsked) }; + } + + fn epoch() -> Instant { + static AT: OnceLock<Instant> = OnceLock::new(); + *AT.get_or_init(crate::time::now) + } + + fn now_ns() -> u64 { epoch().elapsed().as_nanos() as u64 + 1 } + + /// The watchdog's thread, started on the first call, watching the calling thread. + fn watchdog() -> Option<&'static (Thread, ThreadId)> { + static ONE: OnceLock<Option<(Thread, ThreadId)>> = OnceLock::new(); + ONE.get_or_init(|| { + let target = Target::current()?; + epoch(); + let thread = std::thread::Builder::new().name("rune-watchdog".into()).spawn(move || run(target)).ok()?; + Some((thread.thread().clone(), std::thread::current().id())) + }).as_ref() + } + + /// A frame starts on this thread. + pub(crate) fn arm() { + let watched = match WATCHED.get() { + Watched::NotAsked => { + let yes = watchdog().is_some_and(|w| w.1 == std::thread::current().id()); + WATCHED.set(if yes { Watched::Yes } else { Watched::No }); + yes + } + w => w == Watched::Yes, + }; + if !watched { return; } + begin(&Statics, now_ns); + if PARKED.load(Ordering::SeqCst) { wake(); } + } + + /// The running frame's interaction was slow before: sample it sooner. + pub(crate) fn hurry() { + if WATCHED.get() != Watched::Yes { return; } + AFTER_US.fetch_min(HURRY_MS * 1000, Ordering::Relaxed); + wake(); + } + + fn wake() { + PARKED.store(false, Ordering::SeqCst); + if let Some((thread, _)) = watchdog() { thread.unpark(); } + } + + /// The frame on this thread ended: what the watchdog saw of it, if it ran long. + pub(crate) fn disarm() -> Option<Stacks> { + if WATCHED.get() != Watched::Yes { return None; } + START.store(0, Ordering::SeqCst); + collected(&SAMPLES, &TAKEN, || SEQ.load(Ordering::Relaxed)) + } + + fn run(target: Target) { + watch_unloads(); + let mut watch = Watch::Unarmed; + loop { + for effect in step(&mut watch, Event::Look { frame: look(&Statics), now: now_ns() }) { + match effect { + Effect::Sleep(wait) => std::thread::park_timeout(wait), + Effect::Park => { + PARKED.store(true, Ordering::SeqCst); + if START.load(Ordering::SeqCst) == 0 { std::thread::park(); } + PARKED.store(false, Ordering::SeqCst); + } + Effect::Sample { seq, start, at } => { + let still = || SEQ.load(Ordering::SeqCst) == seq && START.load(Ordering::SeqCst) == start; + capture(&SAMPLES, &TAKEN, seq, at, |caught| target.sample(still, caught)); + step(&mut watch, Event::Taken { seq, now: now_ns() }); + } + } + } + } + } +} + +#[cfg(test)] +#[path = "watchdog_tests.rs"] +mod tests; diff --git a/app/vendor/rune/crates/rune/src/tooling/interaction/watchdog_tests.rs b/app/vendor/rune/crates/rune/src/tooling/interaction/watchdog_tests.rs new file mode 100644 index 0000000..ceeaf93 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/tooling/interaction/watchdog_tests.rs @@ -0,0 +1,704 @@ +use std::cell::{Cell, RefCell}; +use std::sync::mpsc; + +use super::super::stack::{DEPTH, Symbols}; +use super::*; + +const MS: u64 = 1_000_000; +const EVERY_NS: u64 = EVERY.as_nanos() as u64; +const REST_NS: u64 = REST.as_nanos() as u64; +const AFTER_US: u32 = AFTER_MS * 1000; +const HURRY_US: u32 = HURRY_MS * 1000; + +fn running(seq: u64, start: u64) -> Option<Running> { Some(Running { seq, start, after_us: AFTER_US }) } + +fn look(watch: &mut Watch, frame: Option<Running>, now: u64) -> Effect { + match step(watch, Event::Look { frame, now }) { + Effects::One(effect) => effect, + other => panic!("a look decides one thing, got {other:?}"), + } +} + +fn taken(watch: &mut Watch, seq: u64, now: u64) { assert!(step(watch, Event::Taken { seq, now }).is_empty()); } + +fn sampling(seq: u64, taken: usize, due: u64) -> Watch { Watch::Sampling(Progress { seq, taken, due }) } + +#[test] +fn a_frame_is_sampled_once_old_enough_and_then_every_few_ms() { + let mut watch = Watch::Unarmed; + assert_eq!(look(&mut watch, running(1, 100 * MS), 103 * MS), Effect::Sleep(Duration::from_millis(9))); + assert_eq!(watch, Watch::Waiting { seq: 1, due: 112 * MS }); + assert_eq!(look(&mut watch, running(1, 100 * MS), 112 * MS), Effect::Sample { seq: 1, start: 100 * MS, at: 112 * MS }); + taken(&mut watch, 1, 113 * MS); + assert_eq!(watch, sampling(1, 1, 113 * MS + EVERY_NS)); + assert_eq!(look(&mut watch, running(1, 100 * MS), 114 * MS), Effect::Sleep(Duration::from_millis(3))); + assert_eq!(look(&mut watch, running(1, 100 * MS), 117 * MS), Effect::Sample { seq: 1, start: 100 * MS, at: 117 * MS }); +} + +#[test] +fn hurry_brings_a_waiting_frame_forward_but_not_a_sampling_one() { + let mut watch = Watch::Unarmed; + let hurried = Some(Running { seq: 1, start: 100 * MS, after_us: HURRY_US }); + look(&mut watch, running(1, 100 * MS), 101 * MS); + assert_eq!(look(&mut watch, hurried, 104 * MS), Effect::Sample { seq: 1, start: 100 * MS, at: 104 * MS }); + taken(&mut watch, 1, 104 * MS); + assert_eq!(look(&mut watch, hurried, 105 * MS), Effect::Sleep(Duration::from_millis(3)), "sampling keeps its own pace"); +} + +#[test] +fn a_frame_armed_while_sampling_waits_its_own_age() { + let mut watch = Watch::Unarmed; + assert_eq!(look(&mut watch, running(1, 100 * MS), 120 * MS), Effect::Sample { seq: 1, start: 100 * MS, at: 120 * MS }); + // Frame 2 starts while frame 1's sample is in flight; the sample still lands on frame 1. + taken(&mut watch, 1, 121 * MS); + assert_eq!(look(&mut watch, running(2, 121 * MS), 122 * MS), Effect::Sleep(Duration::from_millis(11))); + assert_eq!(watch, Watch::Waiting { seq: 2, due: 133 * MS }); +} + +#[test] +fn a_sample_answering_an_older_frame_changes_nothing() { + for mut watch in [Watch::Unarmed, Watch::Waiting { seq: 3, due: 9 }, sampling(3, 2, 9), Watch::Quiet { since: 9, left: None }, Watch::Parked { left: None }] { + let before = watch; + taken(&mut watch, 1, 100 * MS); + assert_eq!(watch, before); + } +} + +#[test] +fn disarm_while_waiting_goes_quiet_without_a_sample() { + let mut watch = Watch::Unarmed; + look(&mut watch, running(1, 100 * MS), 101 * MS); + assert_eq!(look(&mut watch, None, 105 * MS), Effect::Sleep(IDLE_POLL)); + assert_eq!(watch, Watch::Quiet { since: 105 * MS, left: None }); +} + +#[test] +fn going_idle_mid_sample_rests_from_the_next_look_and_then_parks() { + let mut watch = Watch::Unarmed; + look(&mut watch, running(1, 100 * MS), 120 * MS); + taken(&mut watch, 1, 121 * MS); + assert_eq!(look(&mut watch, None, 122 * MS), Effect::Sleep(IDLE_POLL)); + assert_eq!(look(&mut watch, None, 122 * MS + REST_NS - 1), Effect::Sleep(IDLE_POLL)); + assert_eq!(look(&mut watch, None, 122 * MS + REST_NS), Effect::Park); + assert!(matches!(watch, Watch::Parked { .. })); +} + +#[test] +fn parked_stays_parked_through_a_wake_with_no_frame_and_watches_the_next_frame() { + let mut watch = Watch::Parked { left: None }; + assert_eq!(look(&mut watch, None, 5000 * MS), Effect::Park); + assert_eq!(watch, Watch::Parked { left: None }); + assert_eq!(look(&mut watch, running(9, 5000 * MS), 5001 * MS), Effect::Sleep(Duration::from_millis(11))); + assert_eq!(watch, Watch::Waiting { seq: 9, due: 5012 * MS }); +} + +#[test] +fn a_full_frame_stops_sampling_and_polls() { + let mut watch = sampling(1, MOST - 1, 100 * MS); + assert_eq!(look(&mut watch, running(1, 0), 100 * MS), Effect::Sample { seq: 1, start: 0, at: 100 * MS }); + taken(&mut watch, 1, 100 * MS); + assert_eq!(look(&mut watch, running(1, 0), 500 * MS), Effect::Sleep(IDLE_POLL)); +} + +const A: u64 = 100 * MS; +const B: u64 = 1000 * MS; + +/// A look that read the old start and the new number tries a sample the thread's `still` check +/// will refuse (`START` has moved on from `start`), and comes back 4 ms later. +fn refused_at_13_ms(watch: &mut Watch) { + assert_eq!(look(watch, running(2, A), B + 13 * MS), Effect::Sample { seq: 2, start: A, at: B + 13 * MS }); + taken(watch, 2, B + 13 * MS); +} + +#[test] +fn a_frame_change_between_reads_never_sleeps_on_the_older_frames_cap() { + let mut watch = sampling(1, MOST, 0); + refused_at_13_ms(&mut watch); + assert_eq!(look(&mut watch, running(2, B), B + 13 * MS), Effect::Sleep(Duration::from_millis(4))); + assert_eq!(look(&mut watch, running(2, B), B + 17 * MS), Effect::Sample { seq: 2, start: B, at: B + 17 * MS }); +} + +#[test] +fn a_frame_replaced_mid_look_is_sampled_at_17_ms_of_a_20_ms_stall() { + let mut watch = sampling(1, 3, 0); + refused_at_13_ms(&mut watch); + assert_eq!(look(&mut watch, running(2, B), B + 13 * MS), Effect::Sleep(Duration::from_millis(4)), "not the 8 ms idle poll, to 21 ms"); + assert_eq!(look(&mut watch, running(2, B), B + 17 * MS), Effect::Sample { seq: 2, start: B, at: B + 17 * MS }, "before the stall ends at 20 ms"); +} + +#[test] +fn a_sample_taken_while_the_ui_stalls_in_arm_is_filed_under_the_new_frame() { + // `arm` has moved `SEQ` to 2 and stalled before storing `START`: `still` holds for A's start. + let mut watch = sampling(1, 3, 0); + assert_eq!(look(&mut watch, running(2, A), B + 17 * MS), Effect::Sample { seq: 2, start: A, at: B + 17 * MS }, "under the number `disarm` will collect"); + taken(&mut watch, 2, B + 17 * MS); + // `arm` finishes at 19 ms; the frame ends at 20 ms and collects sequence 2. + assert_eq!(look(&mut watch, running(2, B + 19 * MS), B + 19 * MS), Effect::Sleep(Duration::from_millis(2))); + assert_eq!(watch, sampling(2, 1, B + 21 * MS)); +} + +#[test] +fn a_number_read_before_its_start_lands_keeps_its_progress_through_a_quiet_look() { + // A ended and `arm` moved `SEQ`, so a look can pair A's start with 2, and the next read 0. + let mut watch = sampling(1, 3, 0); + refused_at_13_ms(&mut watch); + assert_eq!(look(&mut watch, None, B + 13 * MS), Effect::Sleep(IDLE_POLL)); + assert_eq!(look(&mut watch, running(2, B + 14 * MS), B + 21 * MS), Effect::Sample { seq: 2, start: B + 14 * MS, at: B + 21 * MS }, "the 4 ms retry is already due"); +} + +/// The loop on `dev` before the machine, line for line, given the values it read. +#[derive(Clone, Copy)] +struct Dev { + seen: u64, + taken: usize, + next: u64, + quiet_since: Option<u64>, +} + +impl Dev { + fn look(&mut self, start: u64, seq: u64, after_us: u32, now: u64) -> Effect { + if start == 0 { + let quiet = *self.quiet_since.get_or_insert(now); + return if now - quiet < REST_NS { Effect::Sleep(IDLE_POLL) } else { Effect::Park }; + } + self.quiet_since = None; + if seq != self.seen { (self.seen, self.taken) = (seq, 0); } + if self.taken == 0 { self.next = start + u64::from(after_us) * 1000; } + if now < self.next || self.taken >= MOST { + return Effect::Sleep(if self.taken >= MOST { IDLE_POLL } else { Duration::from_nanos(self.next - now) }); + } + Effect::Sample { seq, start, at: now } + } + + fn sampled(&mut self, now: u64) { + self.taken += 1; + self.next = now + EVERY_NS; + } +} + +#[derive(Clone, Copy, Debug)] +enum Letter { + /// A look read these values, in any combination two frames could leave. No frame is 0. + See { start: u64, seq: u64, after_us: u32 }, + Pass(u64), + /// The sample in flight ended. + Finish, +} + +const OLD: u64 = 1000; +const NEW: u64 = 20 * MS; +const NONE: Letter = Letter::See { start: 0, seq: 1, after_us: AFTER_US }; +const SEE_1: Letter = Letter::See { start: OLD, seq: 1, after_us: AFTER_US }; +const ALPHABET: [Letter; 13] = [ + NONE, + SEE_1, + Letter::See { start: OLD, seq: 1, after_us: HURRY_US }, + Letter::See { start: OLD, seq: 2, after_us: AFTER_US }, + Letter::See { start: OLD, seq: 2, after_us: HURRY_US }, + Letter::See { start: NEW, seq: 1, after_us: AFTER_US }, + Letter::See { start: NEW, seq: 1, after_us: HURRY_US }, + Letter::See { start: NEW, seq: 2, after_us: AFTER_US }, + Letter::See { start: NEW, seq: 2, after_us: HURRY_US }, + Letter::Pass(5 * MS), + Letter::Pass(13 * MS), + Letter::Pass(REST_NS + 100 * MS), + Letter::Finish, +]; + +/// What the walk reached, so it can't pass by never getting anywhere. +#[derive(Default)] +struct Reached { + waiting: bool, + sampling: bool, + quiet: bool, + parked: bool, + full: bool, + sampled: bool, + resumed: bool, +} + +#[derive(Clone, Copy)] +struct World { + watch: Watch, + dev: Dev, + now: u64, + in_flight: Option<u64>, +} + +impl World { + fn new() -> Self { Self { watch: Watch::Unarmed, dev: Dev { seen: 0, taken: 0, next: 0, quiet_since: None }, now: 1000, in_flight: None } } + + fn after(letters: &[Letter]) -> Self { + let mut world = Self::new(); + for &letter in letters { world.apply(letter, letters, &mut Reached::default()); } + world + } + + fn apply(&mut self, letter: Letter, path: &[Letter], reached: &mut Reached) { + match letter { + Letter::Pass(ns) => self.now += ns, + Letter::Finish => { + let seq = self.in_flight.take().expect("a sample is in flight"); + taken(&mut self.watch, seq, self.now); + self.dev.sampled(self.now); + } + Letter::See { start, seq, after_us } => self.see(start, seq, after_us, path, reached), + } + let progress = self.watch.progress(self.dev.seen); + assert_eq!(progress.map_or(0, |p| p.taken), self.dev.taken, "taken differs after {path:?}"); + if let Some(progress) = progress { assert_eq!(progress.due, self.dev.next, "next differs after {path:?}"); } + } + + fn see(&mut self, start: u64, seq: u64, after_us: u32, path: &[Letter], reached: &mut Reached) { + let frame = (start != 0).then_some(Running { seq, start, after_us }); + if frame.is_some() && matches!(self.watch, Watch::Quiet { .. } | Watch::Parked { .. }) && self.watch.progress(seq).is_some() { reached.resumed = true; } + let effect = look(&mut self.watch, frame, self.now); + assert_eq!(effect, self.dev.look(start, seq, after_us, self.now), "the old loop decided otherwise after {path:?}"); + match effect { + Effect::Sample { seq, .. } => { + assert!(frame.is_some(), "sampled with no frame after {path:?}"); + self.in_flight = Some(seq); + reached.sampled = true; + } + Effect::Park => assert!(frame.is_none(), "parked through a running frame after {path:?}"), + Effect::Sleep(wait) => { + assert!(wait > Duration::ZERO, "a zero sleep spins, after {path:?}"); + if self.dev.taken >= MOST { reached.full = true; } + } + } + assert!(self.dev.taken <= MOST, "too many samples after {path:?}"); + match self.watch { + Watch::Waiting { .. } => reached.waiting = true, + Watch::Sampling(_) => reached.sampling = true, + Watch::Quiet { .. } => { + assert_eq!(effect, Effect::Sleep(IDLE_POLL), "after {path:?}"); + reached.quiet = true; + } + Watch::Parked { .. } => { + assert_eq!(effect, Effect::Park, "a parked watchdog has no timer, after {path:?}"); + reached.parked = true; + } + Watch::Unarmed => panic!("a look left it unarmed after {path:?}"), + } + } +} + +fn walk(world: World, depth: usize, path: &mut Vec<Letter>, reached: &mut Reached) { + for letter in ALPHABET { + // The thread is one thread: it finishes a sample before it looks again. + let allowed = match letter { + Letter::Finish => world.in_flight.is_some(), + Letter::See { .. } => world.in_flight.is_none(), + Letter::Pass(_) => true, + }; + if !allowed { continue; } + path.push(letter); + let mut next = world; + next.apply(letter, path, reached); + if depth > 1 { walk(next, depth - 1, path, reached); } + path.pop(); + } +} + +#[test] +fn every_short_sequence_of_reads_matches_the_old_loop() { + let mut reached = Reached::default(); + walk(World::new(), 7, &mut Vec::new(), &mut reached); + assert!(reached.waiting && reached.sampling && reached.quiet && reached.parked && reached.sampled && reached.resumed); +} + +#[test] +fn every_sequence_from_a_parked_watchdog_that_was_sampling_matches_the_old_loop() { + let world = World::after(&[Letter::Pass(13 * MS), SEE_1, Letter::Finish, NONE, Letter::Pass(REST_NS), NONE]); + assert!(matches!(world.watch, Watch::Parked { left: Some(_) })); + let mut reached = Reached::default(); + walk(world, 6, &mut Vec::new(), &mut reached); + assert!(reached.waiting && reached.sampling && reached.parked && reached.resumed); +} + +#[test] +fn every_sequence_from_a_sample_in_flight_matches_the_old_loop() { + let world = World::after(&[Letter::Pass(13 * MS), SEE_1]); + assert!(world.in_flight.is_some()); + let mut reached = Reached::default(); + walk(world, 6, &mut Vec::new(), &mut reached); + assert!(reached.waiting && reached.sampling && reached.quiet && reached.resumed); +} + +#[test] +fn every_sequence_from_a_nearly_full_frame_matches_the_old_loop() { + let mut letters = vec![Letter::Pass(13 * MS)]; + for _ in 0..MOST - 1 { letters.extend([SEE_1, Letter::Finish, Letter::Pass(5 * MS)]); } + let world = World::after(&letters); + assert!(matches!(world.watch, Watch::Sampling(Progress { taken, .. }) if taken == MOST - 1)); + let mut reached = Reached::default(); + walk(world, 6, &mut Vec::new(), &mut reached); + assert!(reached.full && reached.sampling && reached.quiet && reached.resumed); +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +struct Memory { + seq: u64, + start: u64, + after_us: u32, +} + +/// One atomic write of the protocol. +#[derive(Clone, Copy, Debug)] +enum Write { + NextSeq, + AfterUs(u32), + Start(u64), + Hurry, +} + +impl Memory { + fn apply(&mut self, write: Write) { + match write { + Write::NextSeq => self.seq += 1, + Write::AfterUs(us) => self.after_us = us, + Write::Start(ns) => self.start = ns, + Write::Hurry => self.after_us = self.after_us.min(HURRY_US), + } + } +} + +/// Records the real `begin`'s writes. +#[derive(Default)] +struct Recorder(RefCell<Vec<Write>>); + +impl Frames for Recorder { + fn start(&self) -> u64 { unreachable!("begin only writes") } + fn seq(&self) -> u64 { unreachable!("begin only writes") } + fn after_us(&self) -> u32 { unreachable!("begin only writes") } + fn next_seq(&self) { self.0.borrow_mut().push(Write::NextSeq); } + fn set_after_us(&self, us: u32) { self.0.borrow_mut().push(Write::AfterUs(us)); } + fn set_start(&self, ns: u64) { self.0.borrow_mut().push(Write::Start(ns)); } +} + +/// Memory where the writes scheduled before each read land as that read happens. +struct Scripted<'a> { + memory: Cell<Memory>, + writes: &'a [Write], + landed_by: [usize; 3], + landed: Cell<usize>, + reads: Cell<usize>, +} + +impl Scripted<'_> { + fn read(&self) -> Memory { + let mut memory = self.memory.get(); + let upto = self.landed_by[self.reads.get()]; + for &write in &self.writes[self.landed.get()..upto] { memory.apply(write); } + self.landed.set(upto); + self.reads.set(self.reads.get() + 1); + self.memory.set(memory); + memory + } +} + +impl Frames for Scripted<'_> { + fn start(&self) -> u64 { self.read().start } + fn seq(&self) -> u64 { self.read().seq } + fn after_us(&self) -> u32 { self.read().after_us } + fn next_seq(&self) { unreachable!("a look only reads") } + fn set_after_us(&self, _: u32) { unreachable!("a look only reads") } + fn set_start(&self, _: u64) { unreachable!("a look only reads") } +} + +/// `arm`'s stores on `dev`, in its order. +fn dev_arm(now: u64) -> [Write; 3] { [Write::NextSeq, Write::AfterUs(AFTER_US), Write::Start(now)] } + +/// The loop's reads on `dev`, in its order, each after the writes scheduled before it. +fn dev_reads(mut memory: Memory, writes: &[Write], landed_by: [usize; 3]) -> (u64, u64, u32) { + let mut landed = 0; + let mut land = |memory: &mut Memory, upto: usize| { + for &write in &writes[landed..upto] { memory.apply(write); } + landed = upto; + }; + land(&mut memory, landed_by[0]); + let start = memory.start; + if start == 0 { return (0, 0, 0); } + land(&mut memory, landed_by[1]); + let seq = memory.seq; + land(&mut memory, landed_by[2]); + (start, seq, memory.after_us) +} + +#[derive(Clone, Copy, Debug)] +enum Program { + Arm, + Disarm, + Hurry, +} + +fn writes_of(program: &[Program], arm: &[Write]) -> Vec<Write> { + program.iter().flat_map(|step| match step { + Program::Arm => arm.to_vec(), + Program::Disarm => vec![Write::Start(0)], + Program::Hurry => vec![Write::Hurry], + }).collect() +} + +#[test] +fn every_write_landing_between_a_looks_reads_matches_the_old_reads() { + let recorder = Recorder::default(); + begin(&recorder, || NEW); + let real_arm = recorder.0.into_inner(); + let reference_arm = dev_arm(NEW); + let programs: [&[Program]; 6] = [ + &[Program::Arm], + &[Program::Disarm, Program::Arm], + &[Program::Hurry, Program::Arm], + &[Program::Hurry, Program::Disarm, Program::Arm, Program::Hurry], + &[Program::Arm, Program::Disarm], + &[Program::Arm, Program::Hurry], + ]; + let memories = [Memory { seq: 1, start: OLD, after_us: AFTER_US }, Memory { seq: 1, start: OLD, after_us: HURRY_US }, Memory { seq: 1, start: 0, after_us: AFTER_US }]; + let now = NEW + 13 * MS; + let seeds = [ + (Watch::Unarmed, Dev { seen: 0, taken: 0, next: 0, quiet_since: None }), + (sampling(1, 3, now - MS), Dev { seen: 1, taken: 3, next: now - MS, quiet_since: None }), + (sampling(1, MOST, 0), Dev { seen: 1, taken: MOST, next: 0, quiet_since: None }), + (sampling(2, 3, now + MS), Dev { seen: 2, taken: 3, next: now + MS, quiet_since: None }), + ]; + let mut mixed = false; + for memory in memories { + for program in programs { + let (real, reference) = (writes_of(program, &real_arm), writes_of(program, &reference_arm)); + assert_eq!(real.len(), reference.len(), "arm's writes changed"); + for first in 0..=real.len() { + for second in first..=real.len() { + for third in second..=real.len() { + let landed_by = [first, second, third]; + let scripted = Scripted { memory: Cell::new(memory), writes: &real, landed_by, landed: Cell::new(0), reads: Cell::new(0) }; + let frame = super::look(&scripted); + let (start, seq, after_us) = dev_reads(memory, &reference, landed_by); + let context = format!("{memory:?} {program:?} {landed_by:?}"); + assert_eq!(frame, (start != 0).then_some(Running { seq, start, after_us }), "the reads differ: {context}"); + if start == OLD && seq == 2 { mixed = true; } + for (mut watch, mut dev) in seeds { + assert_eq!(look(&mut watch, frame, now), dev.look(start, seq, after_us, now), "the decision differs: {context}"); + } + } + } + } + } + } + assert!(mixed, "the walk never read one frame's start with the next frame's number"); +} + +/// A sample whose CPU time says which one it is. +fn raw(id: u64) -> Raw { + let mut pcs = [0; DEPTH]; + pcs[0] = id as usize; + Raw { pcs, len: 1, waiting: false, cpu_us: id, images: 0 } +} + +fn ids(stacks: &Stacks) -> Vec<u64> { stacks.raw.iter().map(|r| r.cpu_us).collect() } + +fn was_taken(taken: &AtomicBool) -> bool { taken.load(Ordering::Acquire) } + +/// The real capture path, over a stop that finds `sample`. +fn captured(caught: &Caught, taken: &AtomicBool, seq: u64, at: u64, sample: Raw) { + capture(caught, taken, seq, at, |stopped| { + stopped(&sample); + Some(sample) + }); +} + +#[test] +fn a_disarm_at_the_resume_boundary_finds_the_stack_of_its_frame() { + let (caught, taken) = (Caught::new(), AtomicBool::new(false)); + let mut found = None; + capture(&caught, &taken, 7, 1, |stopped| { + let sample = raw(42); + stopped(&sample); + // The thread has resumed and ends its frame before the watchdog runs another line. + found = collected(&caught, &taken, || 7); + Some(sample) + }); + assert_eq!(found.as_ref().map(ids), Some(vec![42]), "the frame gets its one sample"); + assert!(collected(&caught, &taken, || 9).is_none(), "the next frame gets none"); +} + +#[cfg(all(target_os = "macos", target_arch = "aarch64"))] +#[test] +fn a_real_thread_ending_its_frame_as_it_resumes_finds_the_stack() { + use super::super::stack::Target; + let (caught, taken, end) = (Caught::new(), AtomicBool::new(false), AtomicBool::new(false)); + let (caught, taken, end) = (&caught, &taken, &end); + let (ready, got) = mpsc::channel(); + let (finished, on_finished) = mpsc::channel(); + std::thread::scope(|scope| { + scope.spawn(move || { + ready.send(Target::current().unwrap()).unwrap(); + while !end.load(Ordering::Acquire) { std::hint::spin_loop(); } + finished.send(collected(caught, taken, || 7).as_ref().map(ids)).unwrap(); + }); + let target: Target = got.recv().unwrap(); + let mut found = None; + capture(caught, taken, 7, 1, |stopped| { + // `end` is set while the thread is stopped, so it ends the frame the moment it resumes. + let sample = target.sample(|| { end.store(true, Ordering::Release); true }, stopped); + found = Some(on_finished.recv_timeout(Duration::from_secs(30)).expect("the thread ended its frame")); + sample + }); + assert_eq!(found.flatten().map(|samples| samples.len()), Some(1), "the frame gets its one sample"); + }); +} + +#[test] +fn a_disarm_finishes_while_naming_is_paused() { + // differs from dev: naming happens after `disarm`, on the exporter's thread. Dev named on + // the watchdog before storing the sample, so a `disarm` during naming lost it. + let (caught, taken) = (Caught::new(), AtomicBool::new(false)); + let (caught, taken) = (&caught, &taken); + captured(caught, taken, 1, 1, raw(11)); + let earlier = collected(caught, taken, || 1).expect("frame 1's stack"); + let (entered, on_entered) = mpsc::channel(); + let (release, on_release) = mpsc::channel::<()>(); + let (done, on_done) = mpsc::channel(); + std::thread::scope(|scope| { + let namer = scope.spawn(move || { + earlier.names(|sample| { + entered.send(()).unwrap(); + on_release.recv().unwrap(); + vec![Frame { name: format!("app::{}", sample.pcs[0]).into(), app: true }] + }) + }); + on_entered.recv().unwrap(); + scope.spawn(move || { + captured(caught, taken, 3, 2, raw(33)); + done.send(collected(caught, taken, || 3).map(|s| ids(&s))).unwrap(); + }); + let finished = on_done.recv_timeout(Duration::from_secs(30)); + // Released before any assert, so a failure fails rather than hangs. + release.send(()).unwrap(); + let names = namer.join().unwrap(); + assert_eq!(finished.expect("disarm waited on naming"), Some(vec![33]), "the raw sample belongs to its own frame"); + assert_eq!(names.stack.first().map(|n| &**n), Some("app::11")); + }); +} + +fn frame_named(name: &str) -> Frame { Frame { name: name.into(), app: true } } + +fn names_of(frames: &[Frame]) -> Vec<&str> { frames.iter().map(|f| &*f.name).collect() } + +#[test] +fn a_sample_is_named_while_its_images_are_still_loaded() { + let mut symbols = Symbols::default(); + let mut lookups = 0; + let frames = symbols.frames(&raw(0x40), || 0, |_| { lookups += 1; frame_named("app::work") }); + assert_eq!(names_of(&frames), ["app::work"]); + let frames = symbols.frames(&raw(0x40), || 0, |_| { lookups += 1; frame_named("app::work") }); + assert_eq!((names_of(&frames), lookups), (vec!["app::work"], 1), "remembered"); +} + +#[test] +fn an_address_whose_image_was_unloaded_since_the_sample_stays_unresolved() { + // differs from dev: dev named a sample straight after taking it. Named at export, an address + // can by then hold another image's code, so it stays bare once any image has been unloaded. + let mut symbols = Symbols::default(); + let frames = symbols.frames(&raw(0x40), || 1, |_| panic!("no lookup for a sample older than the images")); + assert_eq!(names_of(&frames), ["0x40"]); + assert!(!frames[0].app); +} + +#[test] +fn an_unload_during_the_lookups_leaves_the_sample_unresolved() { + let (mut symbols, generation) = (Symbols::default(), Cell::new(0)); + let frames = symbols.frames(&raw(0x40), || generation.get(), |_| { generation.set(1); frame_named("app::replaced") }); + assert_eq!(names_of(&frames), ["0x40"]); +} + +#[test] +fn an_unload_forgets_remembered_names() { + let mut symbols = Symbols::default(); + symbols.frames(&raw(0x40), || 0, |_| frame_named("app::old")); + let mut newer = raw(0x40); + newer.images = 1; + let frames = symbols.frames(&newer, || 1, |_| frame_named("app::new")); + assert_eq!(names_of(&frames), ["app::new"], "the old image's name isn't reused for the address"); +} + +#[test] +fn a_frame_keeps_every_sample_up_to_the_cap_and_a_new_frame_replaces_them() { + let (caught, taken) = (Caught::new(), AtomicBool::new(false)); + for id in 0..MOST as u64 + 1 { captured(&caught, &taken, 1, id, raw(id)); } + assert_eq!(ids(&caught.collect(1).unwrap()), (0..MOST as u64).collect::<Vec<_>>()); + captured(&caught, &taken, 2, 9, raw(9)); + assert_eq!(ids(&caught.collect(2).unwrap()), [9]); + assert!(caught.collect(1).is_none(), "the older frame's are gone"); +} + +#[test] +fn a_sample_round_trips_through_the_store() { + let (caught, taken) = (Caught::new(), AtomicBool::new(false)); + let mut pcs = [0; DEPTH]; + pcs[..3].copy_from_slice(&[10, 20, 30]); + captured(&caught, &taken, 1, 77, Raw { pcs, len: 3, waiting: true, cpu_us: 5, images: 4 }); + let stacks = caught.collect(1).unwrap(); + assert_eq!((stacks.raw[0].pcs, stacks.raw[0].len, stacks.raw[0].waiting, stacks.raw[0].cpu_us, stacks.raw[0].images), (pcs, 3, true, 5, 4)); + captured(&caught, &taken, 1, 90_077, raw(6)); + assert_eq!(caught.collect(1).unwrap().cpu_share, Some(1.0 / 90.0), "stamped with each look's clock"); + assert!(was_taken(&taken)); +} + +/// `SAMPLES` and `TAKEN` on dev, one capture at a time. +#[derive(Default)] +struct DevSamples { + samples: Vec<(u64, u64)>, + taken: bool, +} + +impl DevSamples { + // differs from dev: `taken` is set as the sample lands, while the thread is stopped. Dev set + // it after naming, so a `disarm` in between found nothing and the next frame's filtered the + // sample out. And there's no clear at 4 * MOST: storage holds one frame's samples. + fn captured(&mut self, seq: u64, id: u64) { + self.samples.push((seq, id)); + self.taken = true; + } + + fn disarm(&mut self, seq: u64) -> Option<Vec<u64>> { + if !std::mem::take(&mut self.taken) { return None; } + let samples: Vec<u64> = self.samples.drain(..).filter(|(s, _)| *s == seq).map(|(_, s)| s).collect(); + (!samples.is_empty()).then_some(samples) + } +} + +#[test] +fn every_short_run_of_frames_collects_what_the_old_store_did() { + #[derive(Clone, Copy, Debug)] + enum Move { Arm, Capture, Disarm } + const MOVES: [Move; 3] = [Move::Arm, Move::Capture, Move::Disarm]; + let (mut kept, mut empty) = (false, false); + for length in 1..=8u32 { + for number in 0..3usize.pow(length) { + let path: Vec<Move> = (0..length).map(|i| MOVES[number / 3usize.pow(i) % 3]).collect(); + let (caught, taken, mut dev) = (Caught::new(), AtomicBool::new(false), DevSamples::default()); + let (mut seq, mut running, mut id) = (0, false, 0); + for &step in &path { + match step { + Move::Arm => (seq, running) = (seq + 1, true), + // A stopped thread between frames fails `still`: nothing is stored. + Move::Capture if running => { + id += 1; + captured(&caught, &taken, seq, id, raw(id)); + dev.captured(seq, id); + } + Move::Capture => {} + Move::Disarm => { + running = false; + let got = collected(&caught, &taken, || seq).map(|s| ids(&s)); + kept |= got.is_some(); + empty |= got.is_none() && id > 0; + assert_eq!(got, dev.disarm(seq), "after {path:?}"); + } + } + } + } + } + assert!(kept && empty); +} diff --git a/app/vendor/rune/crates/rune/src/tooling/key_names.rs b/app/vendor/rune/crates/rune/src/tooling/key_names.rs new file mode 100644 index 0000000..ce60d75 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/tooling/key_names.rs @@ -0,0 +1,27 @@ +//! Key names, modifiers and unmodified characters in headless scripts and `--keys`. +use crate::edit::Key; +use crate::input::key_table; + +pub(crate) fn key_named(name: &str) -> Option<Key> { + key_table::named_key_from_str(name).or_else(|| { + (name.chars().count() == 1).then(|| Key::Text(name.to_owned())) + }) +} + +/// A script step's modifier flags. `"cmd"` is the primary shortcut modifier, held as the shell +/// reports it: with Super on macOS and with Ctrl elsewhere, so a script's "mod+k" works on every +/// platform. +pub(crate) fn script_mods(e: &serde_json::Value) -> crate::Mods { + let flag = |k: &str| e[k].as_bool().unwrap_or(false); + key_table::mods_from_script(flag("shift"), flag("ctrl"), flag("alt"), flag("logo"), flag("cmd")) +} + +/// A script key's `Tx::key_base`: its `"base"`, else a one-character name typed without Shift +/// or Option (which change the character the key types), lowercased. +pub(crate) fn script_key_base(e: &serde_json::Value, name: &str, mods: crate::Mods) -> Option<char> { + let one = |s: &str| { let mut c = s.chars(); c.next().filter(|_| c.next().is_none()) }; + match e["base"].as_str() { + Some(base) => one(base), + None => one(name).filter(|_| !mods.shift && !mods.alt).map(|c| c.to_ascii_lowercase()), + } +} diff --git a/app/vendor/rune/crates/rune/src/tooling/loop_check.rs b/app/vendor/rune/crates/rune/src/tooling/loop_check.rs new file mode 100644 index 0000000..033d5e0 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/tooling/loop_check.rs @@ -0,0 +1,62 @@ +//! `RUNE_LOOP_CHECK=1` in a headless run: every frame no script event reached asks for a +//! loop-only step (`Runtime::loop_step`) before the ordinary frame, on the virtual clock, on any +//! platform. A step that could run is compared with the ordinary frame that runs instead +//! (`Runtime::loop_checked`: the instances that differ and by how much at most); a step that +//! couldn't says why. The run ends with the tally on stderr, and fails (exit 3) when it compared no step or any +//! step differed. `RUNE_LOOP_CHECK_LOG=<file>` +//! writes one line per frame asked (`{"t", "input", "why", "differ", "worst"}`). + +use std::collections::BTreeMap; +use std::io::Write as _; + +#[derive(Default)] +pub(super) struct Tally { + checked: usize, + differ: usize, + most: usize, + worst: f32, + why: BTreeMap<(bool, &'static str), usize>, + log: Option<std::io::BufWriter<std::fs::File>>, + opened: bool, +} + +impl Tally { + /// The step asked before the frame at `t` (seconds), after a script's event or not, and what + /// `loop_checked` found after it. + pub(super) fn add(&mut self, t: f64, input: bool, asked: Result<Vec<u32>, &'static str>, checked: Option<(usize, f32)>) { + if !self.opened { + self.opened = true; + self.log = std::env::var_os("RUNE_LOOP_CHECK_LOG").and_then(|p| std::fs::File::create(p).ok()).map(std::io::BufWriter::new); + } + let why = match asked { Ok(_) => "stepped", Err(why) => why }; + *self.why.entry((input, why)).or_default() += 1; + if let Some((n, d)) = checked { + self.checked += 1; + if n > 0 { self.differ += 1; } + self.most = self.most.max(n); + self.worst = self.worst.max(d); + } + if let Some(log) = self.log.as_mut() { + let (n, d) = checked.map_or((serde_json::Value::Null, serde_json::Value::Null), |(n, d)| (n.into(), if d.is_finite() { f64::from(d).into() } else { "inf".into() })); + writeln!(log, "{}", serde_json::json!({ "t": t, "input": input, "why": why, "differ": n, "worst": d })).ok(); + } + } + + /// Prints the tally, and whether the check passed: it compared at least one step and none + /// differed. A run whose every frame was refused passes nothing. False when it failed (the + /// run then exits non-zero); true when nothing asked (`RUNE_LOOP_CHECK` unset). + pub(super) fn report(&mut self) -> bool { + if !self.opened { return true; } + if let Some(log) = self.log.as_mut() { log.flush().ok(); } + let why: Vec<String> = self.why.iter().map(|((input, w), n)| format!("{}{w}: {n}", if *input { "after an event, " } else { "" })).collect(); + eprintln!("rune: loop check: {} steps checked against ordinary frames, {} differ (at most {} instances, largest difference {}); asked: {}", + self.checked, self.differ, self.most, self.worst, why.join(", ")); + let fail = if self.checked == 0 { Some("no step was checked (every frame was refused: see why above)".to_owned()) } + else if self.differ > 0 { Some(format!("{} steps differ from the ordinary frame", self.differ)) } else { None }; + match &fail { + Some(why) => eprintln!("rune: loop check FAILED: {why}"), + None => eprintln!("rune: loop check passed"), + } + fail.is_none() + } +} diff --git a/app/vendor/rune/crates/rune/src/tooling/parser_tests.rs b/app/vendor/rune/crates/rune/src/tooling/parser_tests.rs new file mode 100644 index 0000000..5416890 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/tooling/parser_tests.rs @@ -0,0 +1,197 @@ +#[test] +fn a_file_drop_hovers_then_drops_at_its_point() { + let steps: Vec<_> = parse_script(json!([ + {"drag_files": {"paths": ["a.png"], "key": "zone"}}, + {"t": 0.5, "drop_files": {"paths": ["a.png", "b.png"], "at": [10, 20], "hover": 0.25}}, + {"t": 1.0, "drag_files": "leave"}, + ])).into_iter().map(|e| (e.t, format!("{:?}", e.kind), format!("{:?}", e.pos))).collect(); + let expected = [ + (0.0, r#"Files(Hover(["a.png"]))"#, r#"Key("zone")"#), + (0.5, r#"Files(Hover(["a.png", "b.png"]))"#, "Xy(10.0, 20.0)"), + (0.75, r#"Files(Drop(["a.png", "b.png"]))"#, "Xy(10.0, 20.0)"), + (1.0, "Files(Leave)", "Rel(0.0, 0.0)"), + ].map(|(t, k, p)| (t, k.to_owned(), p.to_owned())); + assert_eq!(steps, expected); +} + +#[test] +fn a_physical_chord_releases_its_modifiers_after_the_key() { + use crate::PhysicalInput; + let kinds: Vec<_> = parse_script(json!([{"physical": "alt+super+space"}, {"t": 0.1, "physical": "f5"}])) + .into_iter().map(|e| match e.kind { Kind::Physical(event) => event, _ => panic!("physical parsed as another event") }).collect(); + let mods = "alt+super+space".parse::<crate::Shortcut>().unwrap().modifiers(); + let key = |key, mods, pressed| PhysicalInput::Key { key, mods, pressed, repeat: false }; + use crate::PhysicalKeyCode::{F5, Space}; + let expected = [key(Space, mods, true), key(Space, mods, false), PhysicalInput::Modifiers(Mods::default()), + key(F5, Mods::default(), true), key(F5, Mods::default(), false)]; + assert_eq!(format!("{kinds:?}"), format!("{expected:?}")); +} + +#[test] +fn script_events_answer_a_file_dialog() { + let kinds: Vec<_> = parse_script(json!([{"t": 0.1, "type": "file-dialog", "path": "/exports/a.json"}, {"t": 0.2, "type": "file-dialog-cancel"}])) + .into_iter().map(|e| { + let ScriptEvent::FileDialog(public) = e.public().event else { panic!("public event lost the dialog answer") }; + let Kind::FileDialog(path) = e.kind else { panic!("parsed as another event") }; + assert_eq!(public, path); + path + }).collect(); + assert_eq!(kinds, [Some("/exports/a.json".into()), None]); +} + +#[test] +fn script_events_answer_a_pop_up_menu() { + let kinds: Vec<_> = parse_script(json!([{"t": 0.2, "type": "menu-cancel"}, {"t": 0.1, "type": "menu-pick", "id": "dark"}])) + .into_iter().map(|e| { + let ScriptEvent::PopupMenu(public) = e.public().event else { panic!("public event lost the pop-up answer") }; + let Kind::PopupMenu(picked) = e.kind else { panic!("parsed as another event") }; + assert_eq!(public, picked); + picked + }).collect(); + assert_eq!(kinds, [Some("dark".to_owned()), None]); +} + +#[test] +fn a_script_paste_can_carry_html_rtf_and_an_image() { + let png = std::env::temp_dir().join(format!("rune-script-paste-{}.png", std::process::id())); + std::fs::write(&png, crate::drag_out::encode_png(1, 2, &[9; 8]).unwrap()).unwrap(); + let script = parse_script(json!([ + {"type": "paste", "text": "plain"}, + {"paste": "short"}, + {"paste": {"text": "Hi", "html": "<b>Hi</b><img src=x onerror=y>", "rtf": "{\\rtf1 Hi}"}}, + {"paste": {"png": png.to_str().unwrap()}}, + ])); + let public: Vec<_> = script.iter().map(|e| format!("{:?}", e.public().event)).collect(); + assert_eq!(public[..2], [r#"Paste("plain")"#, r#"Paste("short")"#]); + assert!(public[2].starts_with("PasteContent("), "{}", public[2]); + let mut rt = Runtime::new(Vec::new(), |_: &Vec<crate::ClipboardContent>, _: &mut crate::Cx<Vec<crate::ClipboardContent>>| { + crate::el().on_paste_content(|s: &mut Vec<crate::ClipboardContent>, content, _| s.push(content.clone())) + }, (100.0, 100.0), Env::default()); + rt.frame(0.0); + for event in script { + let Kind::Paste(content) = event.kind else { panic!("paste parsed as another event") }; + rt.paste_content(content); + } + rt.frame(0.0); + std::fs::remove_file(&png).ok(); + let texts: Vec<_> = rt.state.iter().map(|c| (c.text(), c.html(), c.rtf(), c.image().map(crate::ClipboardImage::size))).collect(); + assert_eq!(texts, [ + ("plain", None, None, None), ("short", None, None, None), + ("Hi", Some(r#"<b>Hi</b><img src="x">"#), Some("{\\rtf1 Hi}"), None), ("", None, None, Some((1, 2))), + ]); +} + +#[test] +fn a_script_key_with_a_code_reaches_handlers_with_its_physical_key() { + let script = parse_script(json!([ + {"type": "key", "name": "&", "cmd": true, "shift": true, "code": "7"}, + {"t": 0.1, "type": "key", "name": "&", "cmd": true, "shift": true}, + ])); + type Seen = Vec<(Key, Option<crate::PhysicalKeyCode>)>; + let mut rt = Runtime::new(Seen::new(), |_: &Seen, _: &mut crate::Cx<Seen>| crate::el(), (100.0, 100.0), Env::default()); + rt.on_key = Some(|s, ev, tx| { s.push((ev.key.clone(), tx.physical_key())); true }); + for event in script { + match event.kind { + Kind::Key(k, _) => rt.key(k), + Kind::Physical(input) => rt.physical_input(input), + kind => { + let (core, mut app) = rt.split_mut(); + assert!(canvas_input(core, &mut app, &kind, (0.0, 0.0)), "unexpected {kind:?}"); + } + } + rt.frame(0.0); + } + assert_eq!(rt.state, [(Key::Command('&'), Some(crate::PhysicalKeyCode::Digit7)), (Key::Command('&'), None)]); +} + +#[test] +fn a_script_key_with_a_code_reaches_handlers_with_its_unmodified_character() { + let script = parse_script(json!([ + {"type": "key", "name": "å", "alt": true, "code": "a", "base": "a"}, + {"t": 0.1, "type": "key", "name": "k", "cmd": true, "code": "k"}, + {"t": 0.2, "type": "key", "name": "&", "cmd": true, "shift": true, "code": "7"}, + {"t": 0.3, "type": "key", "name": "k", "cmd": true}, + {"t": 0.4, "type": "key-up", "name": "q", "code": "a"}, + ])); + type Seen = Vec<(Key, Option<char>)>; + let view = |_: &Seen, _: &mut crate::Cx<Seen>| crate::el() + .on_key_up(|s: &mut Seen, ev, tx| { s.push((ev.key.clone(), tx.key_base())); true }); + let mut rt = Runtime::new(Seen::new(), view, (100.0, 100.0), Env::default()); + rt.on_key = Some(|s, ev, tx| { s.push((ev.key.clone(), tx.key_base())); true }); + for event in script { + match event.kind { + Kind::Key(k, _) => rt.key(k), + Kind::Physical(input) => rt.physical_input(input), + kind => { + let (core, mut app) = rt.split_mut(); + assert!(canvas_input(core, &mut app, &kind, (0.0, 0.0)), "unexpected {kind:?}"); + } + } + rt.frame(0.0); + } + assert_eq!(rt.state, [ + (Key::Text("å".into()), Some('a')), + (Key::Command('k'), Some('k')), + (Key::Command('&'), None), + (Key::Command('k'), None), + (Key::Text("q".into()), Some('q')), + ]); +} + +#[test] +fn a_script_key_can_be_a_held_keys_repeat() { + let script = parse_script(json!([ + {"type": "key", "name": "Enter"}, + {"t": 0.1, "type": "key", "name": "Enter", "repeat": true}, + {"t": 0.2, "physical": "f5", "repeat": true}, + ])); + let mut rt = Runtime::new(Vec::new(), |_: &Vec<bool>, _: &mut crate::Cx<Vec<bool>>| crate::el(), (100.0, 100.0), Env::default()); + rt.on_key = Some(|s, _, tx| { s.push(tx.key_repeat()); true }); + let mut physical = Vec::new(); + for event in script { + match event.kind { + Kind::Key(k, false) => rt.key(k), + Kind::Key(k, true) => rt.repeat_key(k), + Kind::Physical(crate::PhysicalInput::Key { pressed, repeat, .. }) => physical.push((pressed, repeat)), + other => panic!("unexpected {other:?}"), + } + } + rt.frame(0.0); + assert_eq!(rt.state, [false, true]); + assert_eq!(physical, [(true, true), (false, false)], "the release that ends a hold is not a repeat"); +} + +#[test] +fn window_panel_headless_focus_steps_preserve_false_and_event_order() { + let script = parse_script(serde_json::json!([{"focus":true}, {"t":0.1,"focus":false}, {"t":0.2,"focus":false}])); + let mut rt = Runtime::new(Vec::new(), |_: &Vec<bool>, _: &mut crate::Cx<Vec<bool>>| crate::el(), (100.0, 100.0), Env::default()); + rt.hooks.on_focus = Some(|s, focused, _| s.push(focused)); + assert_eq!(script.len(), 3); + for event in script { + let Kind::Focus(focused) = event.kind else { panic!("focus parsed as pointer action") }; + rt.window_focus(focused); + } + assert_eq!(rt.state, [true, false]); +} + +#[test] +fn scripts_drive_wheels_pinches_other_buttons_and_key_releases() { + use crate::{GesturePhase, PointerButton}; + let script = parse_script(json!([ + {"type": "wheel", "x": 10, "y": 20, "dx": -4, "dy": 6, "cmd": true, "phase": "began"}, + {"t": 0.1, "type": "magnify", "delta": 0.2}, + {"t": 0.2, "type": "drag", "button": "middle", "key": "canvas", "dx": 30, "dur": 0.01}, + {"t": 0.3, "type": "key-up", "name": " "}, + ])); + let kinds: Vec<_> = script.iter().map(|e| format!("{:?}", e.kind)).collect(); + assert!(matches!(script[0].kind, Kind::Move), "a wheel at a point moves the pointer there: {kinds:?}"); + let Kind::WheelEvent(w) = script[1].kind else { panic!("{kinds:?}") }; + assert_eq!((w.dx, w.dy, w.mods.cmd, w.phase, w.precise), (-4.0, 6.0, true, GesturePhase::Began, true)); + assert!(matches!(script[2].kind, Kind::Magnify(m) if m.delta == 0.2) && matches!(script[2].pos, Pos::Rel(..))); + assert!(matches!(script[4].kind, Kind::ButtonDown(PointerButton::Middle)), "{kinds:?}"); + assert!(script.iter().any(|e| matches!(e.kind, Kind::ButtonUp(PointerButton::Middle)))); + let last = script.last().unwrap(); + assert!(matches!(&last.kind, Kind::KeyUp(k) if k.key == Key::Text(" ".into()))); + assert!(matches!(last.public().event, ScriptEvent::KeyUp(_))); + assert!(matches!(script[1].public().event, ScriptEvent::Pointer { action: PointerAction::Wheel(_), .. })); +} diff --git a/app/vendor/rune/crates/rune/src/tooling/perf_warn.rs b/app/vendor/rune/crates/rune/src/tooling/perf_warn.rs new file mode 100644 index 0000000..2c7b94b --- /dev/null +++ b/app/vendor/rune/crates/rune/src/tooling/perf_warn.rs @@ -0,0 +1,200 @@ +//! Debug-only warnings for app code that works but runs slow: a `virtualize` list that builds +//! every row to mount a few, a callback that blocks the main thread, a `poll` that says it +//! changed what shows when nothing did, a window that keeps drawing while idle, a slow first +//! frame, something that commits the view on most frames of a scroll, an app stepping its own +//! scroll glide, and (a mistake rather than slowness) a `memo` whose root already had another +//! key. Each warns once per site, on stderr; `RUNE_PERF_WARN=0` silences them. Release builds +//! contain none of it. `budget` is the exception: an opt-in line per slow commit, in any build. + +pub(crate) mod budget; +mod commits; +mod idle; +pub(crate) mod launch; +pub(crate) mod runq; + +#[cfg(debug_assertions)] +pub(crate) use idle::Drawn; +pub(crate) use idle::IdleMeter; +pub(crate) use commits::CommitMeter; + +/// A window's commit watch: what the commit underway is for (`RUNE_COMMIT_BUDGET_MS` prints +/// it), and the commit warnings' meters. +#[derive(Default)] +pub(crate) struct Watch { + /// `CommitWhy` bits for the commit underway; 0 for one outside a frame's checks. + pub cause: u16, + pub meter: CommitMeter, + /// Interaction timing (`tooling::interaction`), when it's on. + pub interaction: crate::tooling::interaction::Tracker, +} + +#[cfg(debug_assertions)] +use crate::time::Instant; +#[cfg(debug_assertions)] +use std::{collections::HashSet, sync::{Mutex, OnceLock}}; + +/// Blocked wall time (ms; time waiting for a core doesn't count) a callback may take before it warns, and how many times its CPU time +/// that wall time must also be. A callback that computes for 50 ms is slow but not blocked. +#[cfg(debug_assertions)] +const STALL_MS: f64 = 8.0; +#[cfg(debug_assertions)] +const STALL_CPU_RATIO: f64 = 4.0; + +/// Rows a `virtualize` list must build, and how many times what it mounts, before it warns. +#[cfg(debug_assertions)] +const OVERBUILD_ROWS: usize = 200; +#[cfg(debug_assertions)] +const OVERBUILD_RATIO: usize = 4; + +#[cfg(debug_assertions)] +fn enabled() -> bool { + static ON: OnceLock<bool> = OnceLock::new(); + *ON.get_or_init(|| rune_core::env::var_os("RUNE_PERF_WARN").is_none_or(|v| v != "0")) +} + +/// Initializes the cached `RUNE_PERF_WARN` flag up front so the first timed callback does not +/// heap-allocate while reading the environment variable. +#[inline(always)] +pub(crate) fn warm() { + #[cfg(debug_assertions)] + { + let _ = enabled(); + } +} + +/// Prints `message` the first time `site` warns. +#[cfg(debug_assertions)] +#[inline] +fn warn_once(site: String, message: impl FnOnce() -> String) { + let mut message = Some(message); + warn_once_dyn(site, &mut || message.take().expect("warn_once message runs once")()); +} + +#[cfg(debug_assertions)] +fn warn_once_dyn(site: String, message: &mut dyn FnMut() -> String) { + static WARNED: Mutex<Option<HashSet<String>>> = Mutex::new(None); + #[cfg(test)] + let site = format!("{:?} {site}", std::thread::current().id()); + if !enabled() || !WARNED.lock().unwrap().get_or_insert_default().insert(site) { return } + let message = format!("rune: {}. (debug builds only; RUNE_PERF_WARN=0 silences)", message()); + #[cfg(test)] + LOG.with_borrow_mut(|log| log.push(message.clone())); + eprintln!("{message}"); +} + +#[cfg(all(test, debug_assertions))] +thread_local! { + static LOG: std::cell::RefCell<Vec<String>> = const { std::cell::RefCell::new(Vec::new()) }; +} + +/// The warnings this thread printed since the last call. +#[cfg(all(test, debug_assertions))] +pub(crate) fn take_log() -> Vec<String> { LOG.take() } + +/// A `virtualize` list at `path`, set up at `site`, was handed `built` rows and mounts +/// `mounted` of them. +#[cfg(debug_assertions)] +pub(crate) fn overbuilt(path: &str, site: Option<&std::panic::Location>, built: usize, mounted: usize) { + if built <= OVERBUILD_ROWS || built <= OVERBUILD_RATIO * mounted { return } + let site = site.map_or_else(String::new, |s| format!(" (.virtualize at {s})")); + warn_once(format!("overbuild {path}"), || format!( + "virtualized list {path:?}{site} built {built} rows to mount {mounted}: build only the \ + mounted rows with `.virtual_rows(count, estimated_row_height, key, build)`" + )); +} + +/// `memo(id, ..)`, called at `site`, built a root already keyed `existing` and renamed it `id`. +#[cfg(debug_assertions)] +pub(crate) fn memo_key_replaced(id: &str, existing: &str, site: &std::panic::Location) { + if existing == id { return } + warn_once(format!("memo key {site}"), || format!( + "`memo({id:?}, ..)` at {site} replaced its root's key {existing:?} with {id:?}: look it up \ + by {id:?}, or key the memo with the id you want" + )); +} + +/// Times one app callback on the main thread: [`Stall::end`] warns when it spent most of its +/// time blocked rather than computing. +pub(crate) struct Stall { + #[cfg(debug_assertions)] + start: Option<(Instant, f64, Option<f64>)>, +} + +impl Stall { + #[cfg_attr(not(debug_assertions), inline(always))] + pub(crate) fn start() -> Self { + Stall { + #[cfg(debug_assertions)] + start: if enabled() { crate::frame::profile::cpu_ms().map(|cpu| (crate::time::now(), cpu, runq::wait_ms())) } else { None }, + } + } + + /// `what` names the callback in the message, as "`poll`" or "`on_press` on \"#0/save\""; + /// it warns once per `site`. + #[inline(always)] + #[cfg_attr(not(debug_assertions), allow(unused_variables))] + pub(crate) fn end(self, what: impl FnOnce() -> (String, String)) { + #[cfg(debug_assertions)] + if let Some((wall, cpu, wait)) = self.start { + let wall = wall.elapsed().as_secs_f64() * 1000.0; + if wall > STALL_MS { + let mut what = Some(what); + end_slow(wall, cpu, wait, &mut || what.take().expect("stall description runs once")()); + } + } + } + + /// Non-generic [`Self::end`] for a callback identified by a static `name`. + #[cfg_attr(not(debug_assertions), inline(always))] + pub(crate) fn end_named(self, name: &'static str) { + #[cfg(not(debug_assertions))] + let _ = name; + #[cfg(debug_assertions)] + if let Some((wall, cpu, wait)) = self.start { + let wall = wall.elapsed().as_secs_f64() * 1000.0; + if wall > STALL_MS { + end_slow(wall, cpu, wait, &mut || { + (name.to_owned(), if name.contains(' ') { name.to_owned() } else { format!("`{name}`") }) + }); + } + } + } +} + +#[cfg(debug_assertions)] +#[cold] +#[inline(never)] +fn end_slow(wall: f64, cpu: f64, wait: Option<f64>, what: &mut dyn FnMut() -> (String, String)) { + let cpu = crate::frame::profile::cpu_ms().map_or(0.0, |now| now - cpu); + let waited = wait.and_then(|start| runq::wait_ms().map(|now| now - start)); + let Some(blocked) = runq::blocked_ms(wall, cpu, waited, waited.is_none() && runq::overloaded()) else { return }; + let (site, name) = what(); + warn_once(format!("stall {site}"), || { + let queued = waited.filter(|w| *w >= 1.0).map_or_else(String::new, |w| format!(", waited {w:.0} ms for a core")); + format!( + "{name} blocked {blocked:.0} ms (CPU {cpu:.0} ms{queued}) on the main thread: move IO off it \ + with `rune::Latest` or a thread" + ) + }); +} + +/// Runs `f`, an app callback named `name` (a call site of its own), under a [`Stall`]. +#[inline(always)] +pub(crate) fn timed<T>(name: &'static str, f: impl FnOnce() -> T) -> T { + let stall = Stall::start(); + let out = f(); + stall.end_named(name); + out +} + +/// A handler's site: its name and the element's path with the digits taken out, so the rows of +/// one list share it. +#[cfg(debug_assertions)] +pub(crate) fn handler_site(name: &str, path: &str) -> String { + format!("{name} {}", path.chars().filter(|c| !c.is_ascii_digit()).collect::<String>()) +} + +#[cfg(all(test, debug_assertions))] +mod commits_tests; +#[cfg(all(test, debug_assertions))] +mod tests; diff --git a/app/vendor/rune/crates/rune/src/tooling/perf_warn/budget.rs b/app/vendor/rune/crates/rune/src/tooling/perf_warn/budget.rs new file mode 100644 index 0000000..761a99a --- /dev/null +++ b/app/vendor/rune/crates/rune/src/tooling/perf_warn/budget.rs @@ -0,0 +1,84 @@ +//! `RUNE_COMMIT_BUDGET_MS=N`: a line on stderr when a commit takes longer than `N` ms, with +//! where its time went (view, layout, text, apply) and what made the frame commit. Off unless +//! set, in any build, so it can watch a release build; while off, each phase checks one cached +//! flag. At most one line a second, counting the commits it left out. +use std::cell::Cell; +use std::sync::OnceLock; + +use crate::frame::profile::{PHASES, Phase}; +use crate::time::Instant; + +/// The budget in ms, when `RUNE_COMMIT_BUDGET_MS` sets one. +fn budget() -> Option<f64> { + static BUDGET: OnceLock<Option<f64>> = OnceLock::new(); + *BUDGET.get_or_init(|| rune_core::env::var("RUNE_COMMIT_BUDGET_MS")?.trim().parse::<f64>().ok().filter(|ms| *ms > 0.0)) +} + +#[inline(always)] +pub(crate) fn on() -> bool { budget().is_some() } + +thread_local! { + static TIMES: Cell<[f64; PHASES]> = const { Cell::new([0.0; PHASES]) }; + /// Commits underway on this thread: one inside another counts toward the outer one. + static DEPTH: Cell<u32> = const { Cell::new(0) }; + /// When the last line printed, and the commits over budget since that it left out. + static PRINTED: Cell<Option<(Instant, u32)>> = const { Cell::new(None) }; +} + +/// Phase `phase` took `ms`. +pub(crate) fn add(phase: Phase, ms: f64) { + TIMES.with(|t| { + let mut row = t.get(); + row[phase as usize] += ms; + t.set(row); + }); +} + +/// Times one commit, from [`Commit::start`] to [`Commit::end`]. +pub(crate) struct Commit(Option<(Instant, bool)>); + +impl Commit { + #[inline(always)] + pub(crate) fn start() -> Commit { + if !on() { return Commit(None); } + let outer = DEPTH.replace(DEPTH.get() + 1) == 0; + if outer { TIMES.set([0.0; PHASES]); } + Commit(Some((crate::time::now(), outer))) + } + + /// The commit is done; `why` is what made the frame commit, as `CommitWhy` bits. + #[inline(always)] + pub(crate) fn end(self, why: u16) { + let Some((start, outer)) = self.0 else { return }; + DEPTH.set(DEPTH.get() - 1); + let Some(budget) = budget().filter(|_| outer) else { return }; + let total = start.elapsed().as_secs_f64() * 1000.0; + if total <= budget { return; } + let now = crate::time::now(); + let left_out = match PRINTED.get() { + Some((at, n)) if now.duration_since(at).as_secs_f64() < 1.0 => { + PRINTED.set(Some((at, n + 1))); + return; + } + Some((_, n)) => n, + None => 0, + }; + PRINTED.set(Some((now, 0))); + eprintln!("{}", report(total, budget, TIMES.get(), why, left_out)); + } +} + +/// The line for a commit that took `total` ms against `budget`, its phases timed in `times`. +pub(crate) fn report(total: f64, budget: f64, times: [f64; PHASES], why: u16, left_out: u32) -> String { + let [view, _, layout, text, _, apply] = times; + let parts = [("the view", view), ("layout", (layout - text).max(0.0)), ("text", text), ("apply", apply)]; + let top = parts.iter().copied().max_by(|a, b| a.1.total_cmp(&b.1)).filter(|p| p.1 > 0.0); + let why = crate::runtime::CommitWhy::names(why); + let mut line = format!( + "rune: commit took {total:.1} ms, over RUNE_COMMIT_BUDGET_MS={budget}: view {view:.1}, layout {layout:.1} (text {text:.1}), apply {apply:.1} ms" + ); + if let Some((name, ms)) = top { line += &format!("; most in {name} ({:.0}%)", 100.0 * ms / total); } + if !why.is_empty() { line += &format!("; committed for {}", why.join(", ")); } + if left_out > 0 { line += &format!(" ({left_out} more over budget since the last line)"); } + line +} diff --git a/app/vendor/rune/crates/rune/src/tooling/perf_warn/commits.rs b/app/vendor/rune/crates/rune/src/tooling/perf_warn/commits.rs new file mode 100644 index 0000000..b783891 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/tooling/perf_warn/commits.rs @@ -0,0 +1,196 @@ +//! The commit warnings: something in the app that commits the view on most frames of a scroll, +//! which a scroll itself never needs (Rune moves the content, mounts virtual rows and paints +//! hover without one); an app stepping its own scroll glide with an instant scroll every +//! frame; and hover kept in state on many rows, so each row the pointer crosses commits. Each +//! names its source: `poll`, a handler with its element and where it was set, or the layout +//! read that moved. + +#[cfg(debug_assertions)] +use std::collections::HashMap; + +/// Committing frames one source may take in a scroll, and the share of the scroll's frames +/// (one in this many), before it warns. A list loading its next page commits a few times. +#[cfg(debug_assertions)] +const COMMITS: u32 = 6; +#[cfg(debug_assertions)] +const SHARE: u32 = 4; +/// Frames in a row that commit and ask for an instant scroll before it warns. +#[cfg(debug_assertions)] +const INSTANT_FRAMES: u32 = 8; +/// Elements one hover handler (by where it was set) commits for before it warns. +#[cfg(debug_assertions)] +const HOVER_ROWS: usize = 8; + +/// What made a commit, as far as the app goes. +#[cfg(debug_assertions)] +#[derive(Clone, Copy, Debug, PartialEq)] +pub(crate) enum Cause { + Poll, + /// A handler, by the name the docs give it (`on_hover_change`). + Handler(&'static str), + /// A view's layout read (`Cx::layout`, `Cx::window_layout`) moved. + Read, +} + +/// One source that asked this frame for a commit. +#[cfg(debug_assertions)] +struct Source { + /// What it warns once per: the handler's registration site, else its element's path + /// without digits, so one list's rows count as one source. + site: String, + cause: Cause, + /// The element's path or the read's key. + subject: Option<String>, + at: Option<&'static std::panic::Location<'static>>, +} + +/// One window's commit meters. Release builds hold nothing. +#[derive(Default)] +pub(crate) struct CommitMeter { + #[cfg(debug_assertions)] + meter: Meter, +} + +#[cfg(debug_assertions)] +#[derive(Default)] +struct Meter { + sources: Vec<Source>, + /// Frames of the scroll underway, and how many of them each site committed. + frames: u32, + counts: HashMap<String, u32>, + /// Frames in a row that committed and asked for an instant scroll. + instant: u32, + /// The elements each hover handler committed for, by where it was set, until it warns. + hover_rows: HashMap<&'static std::panic::Location<'static>, Vec<String>>, +} + +impl CommitMeter { + /// `poll` returned true. + #[inline(always)] + pub(crate) fn poll(&mut self) { + #[cfg(debug_assertions)] + self.meter.sources.push(Source { site: "poll".into(), cause: Cause::Poll, subject: None, at: None }); + } + + /// Handler `name` on the element at `path`, set at `at`, asked for a commit. + #[inline(always)] + #[cfg_attr(not(debug_assertions), allow(unused_variables))] + pub(crate) fn handler(&mut self, name: &'static str, path: Option<&str>, at: Option<&'static std::panic::Location<'static>>) { + #[cfg(debug_assertions)] + { + let site = match (at, path) { + (Some(at), _) => format!("{name} {at}"), + (None, Some(path)) => super::handler_site(name, path), + (None, None) => name.to_owned(), + }; + if let (Some(at), Some(path), "on_hover" | "on_hover_change") = (at, path, name) { self.hover_row(name, at, path); } + self.meter.sources.push(Source { site, cause: Cause::Handler(name), subject: path.map(str::to_owned), at }); + } + } + + #[cfg(debug_assertions)] + fn hover_row(&mut self, name: &'static str, at: &'static std::panic::Location<'static>, path: &str) { + let rows = self.meter.hover_rows.entry(at).or_default(); + if rows.len() >= HOVER_ROWS || rows.iter().any(|p| p == path) { return; } + rows.push(path.to_owned()); + if rows.len() < HOVER_ROWS { return; } + let example = rows[0].clone(); + super::warn_once(format!("hover rows {at}"), || format!( + "`{name}` set at {at} committed the view for {HOVER_ROWS} elements (as {example:?}): each one the pointer crosses \ + runs the whole view; {}", handler_fix(name) + )); + } + + /// A view's layout read of `key`, made at `at`, moved, so the view runs again. + #[cfg(debug_assertions)] + pub(crate) fn read(&mut self, key: &str, at: Option<&'static std::panic::Location<'static>>) { + self.meter.sources.push(Source { site: format!("read {key}"), cause: Cause::Read, subject: Some(key.to_owned()), at }); + } + + /// The frame's commits are done. `scrolling`: a hand, momentum or a glide moves a viewport; + /// `committed`: the frame committed; `instant`: the viewport an instant scroll this frame + /// asked to move, if any. + #[inline(always)] + #[cfg_attr(not(debug_assertions), allow(unused_variables))] + pub(crate) fn frame_ends(&mut self, scrolling: bool, committed: bool, instant: Option<&str>) { + #[cfg(debug_assertions)] + { + let m = &mut self.meter; + let sources = std::mem::take(&mut m.sources); + match instant.filter(|_| committed) { + Some(key) => { + m.instant += 1; + if m.instant == INSTANT_FRAMES { super::warn_once(format!("instant scroll {key}"), || instant_message(key)); } + } + None => m.instant = 0, + } + if !scrolling { + m.frames = 0; + m.counts.clear(); + return; + } + m.frames += 1; + if !committed { return; } + let mut seen: Vec<&str> = Vec::new(); + for s in &sources { + if seen.contains(&s.site.as_str()) { continue; } + seen.push(&s.site); + let count = m.counts.entry(s.site.clone()).or_default(); + *count += 1; + if *count >= COMMITS && *count * SHARE >= m.frames { + let (count, frames) = (*count, m.frames); + super::warn_once(format!("scroll commit {}", s.site), || message(s, count, frames)); + } + } + } + } +} + +/// The warning for source `s`, which committed `count` of a scroll's `frames` frames. +#[cfg(debug_assertions)] +fn message(s: &Source, count: u32, frames: u32) -> String { + let at = s.at.map_or_else(String::new, |at| format!(" (set at {at})")); + let subject = s.subject.as_deref().unwrap_or(""); + let (who, fix) = match s.cause { + Cause::Poll => ("`poll` returned true and".to_owned(), + "return true only when visible state changed; to act on where a scroll stops, wait until it \ + has been still a moment (`Tx::wake_after`), and follow it frame by frame with \ + `El::on_scroll_offset` and live values"), + Cause::Read => { + let window = crate::runtime::window_read_key(subject); + let at = s.at.map_or_else(String::new, |at| format!(" at {at}")); + let read = match window { + Some(key) => format!("the view's `Cx::window_layout` read of {key:?}{at}"), + None => format!("the view's layout read of {subject:?}{at}"), + }; + (format!("{read} moved and"), + if window.is_some() { "read `Cx::layout_size` or `Cx::layout` (unscrolled) unless the view needs where the \ + element is in the window, and then only through `window_layout_with` and what it computes" } + else { "read only what the view needs (`Cx::layout_size`, `Cx::layout_with`), or follow it with \ + `El::on_layout_tx` and a live value" }) + } + Cause::Handler(name) => (format!("`{name}` on {subject:?}{at}"), handler_fix(name)), + }; + format!("{who} committed the view on {count} of {frames} frames of a scroll: {fix}") +} + +#[cfg(debug_assertions)] +fn handler_fix(name: &str) -> &'static str { + match name { + "on_hover" | "on_hover_change" => "paint hover with `El::hover`, `hover_group` and `group_*` styles (`hover_alone` for a \ + target inside a lit row) instead of state, or say `Tx::live_only` when the handler only sets live values", + "on_layout_tx" | "on_drawn_layout_tx" | "on_pointer_move_local" | "on_wheel" => "when the handler only moves live values \ + or bookkeeping, say `Tx::live_only` (`on_layout` and `on_drawn_layout` take one in their `_tx` forms)", + "on_visible_rows" => "return true only when the visible range changed what the view shows", + _ => "say `Tx::live_only` when the handler changes nothing the view reads", + } +} + +#[cfg(debug_assertions)] +fn instant_message(key: &str) -> String { + format!( + "an instant scroll (`Tx::scroll_to_instant`, `scroll_to_y`, `scroll_key_to`) moved {key:?} on {INSTANT_FRAMES} frames \ + in a row, each with a commit: an app stepping its own glide this way runs the view every frame; glide with `Tx::scroll_to_with(key, x, y, spring)`, \ + which runs on Rune's clock with no commits" + ) +} diff --git a/app/vendor/rune/crates/rune/src/tooling/perf_warn/commits_tests.rs b/app/vendor/rune/crates/rune/src/tooling/perf_warn/commits_tests.rs new file mode 100644 index 0000000..7866fc9 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/tooling/perf_warn/commits_tests.rs @@ -0,0 +1,139 @@ +use super::*; +use crate::el::{col, row}; +use crate::runtime::Runtime; +use crate::{Color, Cx, El, Env, ScrollSpec, Tx}; + +/// Forty 20-point rows in a 200-point viewport keyed `scroll`, each watched by `watch`. +fn rows(watch: impl Fn(El, usize) -> El) -> El { + let list = col().key("rows").w_full().children((0..40).map(|k| watch(row().key(format!("r{k}")).w_full().h(20.0).fill(Color::WHITE), k))); + col().size(200.0, 200.0).child(col().key("scroll").size(200.0, 200.0).scroll(ScrollSpec { stick_bottom: false }).child(list)) +} + +fn runtime<S: 'static>(state: S, view: fn(&S, &mut Cx<S>) -> El) -> Runtime<S> { + let mut rt = Runtime::new(state, view, (200.0, 200.0), Env::new(true, 1.0)); + rt.frame(0.0); + rt.frame(1.0 / 120.0); + rt +} + +/// Wheels the viewport 4 points a frame for `frames` frames. +fn scroll<S: 'static>(rt: &mut Runtime<S>, frames: usize) { + for _ in 0..frames { + rt.wheel(100.0, 100.0, -4.0); + rt.frame(1.0 / 120.0); + } +} + +#[test] +fn a_poll_that_commits_every_scroll_frame_warns_once_naming_poll() { + take_log(); + fn view(_: &u32, _: &mut Cx<u32>) -> El { rows(|r, _| r) } + let mut rt = runtime(0u32, view); + rt.poll = Some(|n, _, _| { *n += 1; true }); + scroll(&mut rt, 20); + let log: Vec<_> = take_log().into_iter().filter(|l| l.contains("of a scroll")).collect(); + assert_eq!(log.len(), 1, "{log:?}"); + assert!(log[0].starts_with("rune: `poll` returned true and committed the view on 6 of "), "{}", log[0]); +} + +#[test] +fn an_on_layout_tx_that_commits_through_a_scroll_names_its_element_and_where_it_was_set() { + take_log(); + fn view(_: &u32, _: &mut Cx<u32>) -> El { + rows(|r, k| if k == 3 { r.on_layout_tx(|n: &mut u32, _, _: &mut Tx| *n += 1) } else { r }) + } + let mut rt = runtime(0u32, view); + scroll(&mut rt, 20); + let log: Vec<_> = take_log().into_iter().filter(|l| l.contains("of a scroll")).collect(); + assert_eq!(log.len(), 1, "{log:?}"); + assert!(log[0].contains("`on_layout_tx` on ") && log[0].contains("r3") && log[0].contains("commits_tests.rs:") + && log[0].contains("say `Tx::live_only`"), "{}", log[0]); +} + +#[test] +fn a_live_only_on_layout_tx_stays_quiet_through_a_scroll() { + take_log(); + fn view(_: &u32, _: &mut Cx<u32>) -> El { + rows(|r, k| if k == 4 { r.on_layout_tx(|n: &mut u32, _, tx: &mut Tx| { *n += 1; tx.live_only(); }) } else { r }) + } + let mut rt = runtime(0u32, view); + scroll(&mut rt, 20); + let log: Vec<_> = take_log().into_iter().filter(|l| l.contains("of a scroll")).collect(); + assert_eq!(log, Vec::<String>::new()); +} + +#[test] +fn a_window_layout_read_through_a_scroll_names_the_read() { + take_log(); + fn view(_: &u32, cx: &mut Cx<u32>) -> El { + let _ = cx.window_layout("r5"); + rows(|r, _| r) + } + let mut rt = runtime(0u32, view); + scroll(&mut rt, 20); + let log: Vec<_> = take_log().into_iter().filter(|l| l.contains("of a scroll")).collect(); + assert_eq!(log.len(), 1, "{log:?}"); + assert!(log[0].contains("`Cx::window_layout` read of \"r5\" at ") && log[0].contains("commits_tests.rs:") && log[0].contains("`Cx::layout_size`"), "{}", log[0]); +} + +#[test] +fn hover_kept_in_state_on_many_rows_warns_once_with_where_it_was_set() { + take_log(); + fn view(_: &Option<usize>, _: &mut Cx<Option<usize>>) -> El { + rows(|r, k| r.on_hover_change(move |s: &mut Option<usize>, inside, _: &mut Tx| *s = inside.then_some(k))) + } + let mut rt = runtime(None, view); + for y in 0..10 { + rt.pointer_move(100.0, 10.0 + 20.0 * y as f32); + rt.frame(1.0 / 120.0); + } + let log: Vec<_> = take_log().into_iter().filter(|l| l.contains("for 8 elements")).collect(); + assert_eq!(log.len(), 1, "{log:?}"); + assert!(log[0].contains("`on_hover_change` set at ") && log[0].contains("commits_tests.rs:") && log[0].contains("`El::hover`"), "{}", log[0]); +} + +#[test] +fn an_app_stepping_its_own_glide_with_instant_scrolls_warns() { + take_log(); + fn view(_: &f32, _: &mut Cx<f32>) -> El { rows(|r, _| r) } + let mut rt = runtime(0.0f32, view); + rt.poll = Some(|y, _, tx| { + if *y < 300.0 { + *y += 10.0; + tx.scroll_to_instant("scroll", 0.0, *y); + tx.wake_after(std::time::Duration::ZERO); + return true; + } + false + }); + for _ in 0..12 { rt.frame(1.0 / 120.0); } + let log: Vec<_> = take_log().into_iter().filter(|l| l.contains("an instant scroll")).collect(); + assert_eq!(log.len(), 1, "{log:?}"); + assert!(log[0].contains("\"scroll\"") && log[0].contains("scroll_to_with"), "{}", log[0]); +} + +#[test] +fn instant_scrolls_with_no_commit_stay_quiet() { + take_log(); + fn view(_: &f32, _: &mut Cx<f32>) -> El { rows(|r, _| r) } + let mut rt = runtime(0.0f32, view); + rt.poll = Some(|y, _, tx| { + if *y < 300.0 { + *y += 10.0; + tx.scroll_to_instant("scroll", 0.0, *y); + tx.wake_after(std::time::Duration::ZERO); + } + false + }); + for _ in 0..12 { rt.frame(1.0 / 120.0); } + let log: Vec<_> = take_log().into_iter().filter(|l| l.contains("an instant scroll")).collect(); + assert_eq!(log, Vec::<String>::new()); +} + +#[test] +fn a_budget_line_names_the_phase_that_took_most_and_why_the_frame_committed() { + let times = [9.0, 14.0, 3.0, 1.0, 0.0, 1.5]; + let line = budget::report(14.2, 8.0, times, crate::runtime::CommitWhy::POLL, 3); + assert_eq!(line, "rune: commit took 14.2 ms, over RUNE_COMMIT_BUDGET_MS=8: view 9.0, layout 3.0 (text 1.0), apply 1.5 ms; \ + most in the view (63%); committed for poll (3 more over budget since the last line)"); +} diff --git a/app/vendor/rune/crates/rune/src/tooling/perf_warn/idle.rs b/app/vendor/rune/crates/rune/src/tooling/perf_warn/idle.rs new file mode 100644 index 0000000..5a27829 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/tooling/perf_warn/idle.rs @@ -0,0 +1,167 @@ +//! The idle meters: a `poll` that says it changed what shows when nothing did, and a window that +//! keeps drawing the same frame while nothing asks it to. "Nothing changed" is the test the +//! native host uses to skip a present: the same instance bytes and surface, with nothing drawn +//! outside the instances. Only frames with no input and no motion are compared, so a busy +//! frame costs one flag and release builds hold nothing at all. + +/// Quiet frames in a row `poll` may say it changed something before nothing changing warns. +#[cfg(debug_assertions)] +const POLL_FRAMES: u32 = 30; +/// Self-woken frames that draw nothing new, and within how many seconds, before a window warns. +#[cfg(debug_assertions)] +const IDLE_FRAMES: u32 = 120; +#[cfg(debug_assertions)] +const IDLE_SECS: f64 = 2.0; + +/// One window's idle meters. +#[derive(Default)] +pub(crate) struct IdleMeter { + #[cfg(debug_assertions)] + meter: Meter, +} + +/// What a frame drew, as far as telling the next one apart goes. +#[cfg(debug_assertions)] +pub(crate) struct Drawn<'a> { + pub instances: &'a [u8], + /// The surface it drew into and the image copies so far, hashed. + pub key: u64, + /// It drew something the instances don't hold (`SurfaceDraw`, native materials, video), so + /// the same instances may not mean the same pixels. + pub opaque: bool, +} + +#[cfg(debug_assertions)] +#[derive(Clone, Copy)] +struct Start { quiet: bool, timer: bool, live: bool } + +#[cfg(debug_assertions)] +#[derive(Default)] +struct Meter { + frame: Option<Start>, + /// `poll` returned true since the last frame ended. + polled: bool, + /// The last quiet frame's instances and key; none after a frame with input or motion. + last: Option<(Vec<u8>, u64)>, + poll_streak: u32, + idle: Streak, +} + +#[cfg(debug_assertions)] +#[derive(Clone, Copy)] +enum Woke { Live { polled: bool }, Timer, TimerLive, TimerPoll } + +#[cfg(debug_assertions)] +impl Woke { + fn label(self) -> &'static str { + match self { + Self::TimerPoll => "a `wake_after` loop whose `poll` returns true", + Self::Timer => "a `wake_after` loop", + Self::TimerLive => "a `wake_after` loop and a live value", + Self::Live { .. } => "a live value", + } + } +} + +#[cfg(debug_assertions)] +#[derive(Clone, Copy, Default)] +enum Streak { #[default] Watching, Counting { from: f64, frames: u32, woke: Woke } } + +#[cfg(debug_assertions)] +#[derive(Clone, Copy)] +struct Reading { clock: f64, quiet: bool, animating: bool, same: Option<bool>, timer: bool, live: bool, polled: bool } + +#[cfg(debug_assertions)] +#[inline] +fn step(streak: &mut Streak, r: Reading) -> crate::machine::Effects<(Woke, f64)> { + use crate::machine::Effects; + if !r.quiet || r.animating || r.same == Some(false) { + *streak = Streak::Watching; + return Effects::none(); + } + if r.same.is_none() || !(r.timer || r.live) { return Effects::none(); } + let (from, frames, previous) = match *streak { + Streak::Counting { from, frames, woke } if !(r.clock - from > IDLE_SECS) => (from, frames, Some(woke)), + _ => (r.clock, 0, None), + }; + let timer = r.timer || matches!(previous, Some(Woke::Timer | Woke::TimerLive | Woke::TimerPoll)); + let live = r.live || matches!(previous, Some(Woke::Live { .. } | Woke::TimerLive)); + let polled = r.polled || matches!(previous, Some(Woke::Live { polled: true } | Woke::TimerPoll)); + let woke = match (timer, live, polled) { + (true, _, true) => Woke::TimerPoll, + (true, false, false) => Woke::Timer, + (true, true, false) => Woke::TimerLive, + (false, ..) => Woke::Live { polled }, + }; + let frames = frames + 1; + *streak = Streak::Counting { from, frames, woke }; + if frames == IDLE_FRAMES { Effects::one((woke, r.clock - from)) } else { Effects::none() } +} + +#[cfg(all(test, debug_assertions))] +#[path = "idle_tests.rs"] +mod tests; + +impl IdleMeter { + /// Passes `changed`, `poll`'s answer, through. + #[inline(always)] + pub(crate) fn polled(&mut self, changed: bool) -> bool { + #[cfg(debug_assertions)] + { self.meter.polled |= changed; } + changed + } + + /// A frame starts. `quiet`: no input waits and nothing moves; `timer`: a due `wake_after` + /// woke it; `live`: a live value did. + #[cfg(debug_assertions)] + pub(crate) fn begins(&mut self, quiet: bool, timer: bool, live: bool) { + self.meter.frame = Some(Start { quiet, timer, live }); + } + + /// The frame drew `drawn` at `clock` seconds, leaving motion running if `animating`. `name` + /// names the window, when it has a title. + #[cfg(debug_assertions)] + #[inline] + pub(crate) fn ends(&mut self, clock: f64, animating: bool, drawn: Drawn, name: impl Fn() -> Option<String>) { + self.ends_dyn(clock, animating, drawn, &name); + } + + #[cfg(debug_assertions)] + fn ends_dyn(&mut self, clock: f64, animating: bool, drawn: Drawn, name: &dyn Fn() -> Option<String>) { + let m = &mut self.meter; + let Some(start) = m.frame.take() else { return }; + let polled = std::mem::take(&mut m.polled); + let quiet = start.quiet && !drawn.opaque; + // Whether it drew what the last frame did: unknown unless that one was quiet too. + let same = quiet.then(|| m.last.as_ref().map(|(bytes, key)| *key == drawn.key && bytes[..] == *drawn.instances)).flatten(); + if quiet { + let (bytes, key) = m.last.get_or_insert_default(); + bytes.clear(); + bytes.extend_from_slice(drawn.instances); + *key = drawn.key; + } else { + m.last = None; + } + let same = same.map(|same| same && !animating); + let site = || name().map_or_else(String::new, |name| format!(" {name:?}")); + // Frames in a row: a frame that doesn't say it changed something, or that changed what + // shows, breaks the run. + m.poll_streak = if polled && same == Some(true) { m.poll_streak + 1 } else { 0 }; + if m.poll_streak == POLL_FRAMES { + let window = site(); + super::warn_once(format!("idle-poll{window}"), || format!( + "`poll`{} returned true but nothing changed ({POLL_FRAMES} frames in a row); return \ + true only when visible state changed", if window.is_empty() { String::new() } else { format!(" of window{window}") } + )); + } + let reading = Reading { clock, quiet, animating, same, timer: start.timer, live: start.live, polled }; + if let crate::machine::Effects::One((woke, secs)) = step(&mut m.idle, reading) { + let window = site(); + let by = woke.label(); + super::warn_once(format!("idle-draw{window}"), || format!( + "idle window{window} still drawing: check `wake_after` loops ({IDLE_FRAMES} frames in {secs:.1} s \ + with no input, motion or visible change, woken by {by})" + )); + } + } +} diff --git a/app/vendor/rune/crates/rune/src/tooling/perf_warn/idle_tests.rs b/app/vendor/rune/crates/rune/src/tooling/perf_warn/idle_tests.rs new file mode 100644 index 0000000..2b14e7d --- /dev/null +++ b/app/vendor/rune/crates/rune/src/tooling/perf_warn/idle_tests.rs @@ -0,0 +1,86 @@ +use super::*; +use crate::machine::Effects; + +#[derive(Clone, Copy, Default)] +struct Old { idle_from: f64, idle_frames: u32, woken: [bool; 3] } + +impl Old { + fn label(&self) -> &'static str { + match self.woken { + [true, _, true] => "a `wake_after` loop whose `poll` returns true", + [true, false, false] => "a `wake_after` loop", + [true, true, false] => "a `wake_after` loop and a live value", + [false, ..] => "a live value", + } + } + + fn end(&mut self, r: Reading) -> Option<(&'static str, f64)> { + if !r.quiet || r.animating || r.same == Some(false) { + self.idle_frames = 0; + return None; + } + if r.same.is_none() || !(r.timer || r.live) { return None; } + if self.idle_frames == 0 || r.clock - self.idle_from > 2.0 { + (self.idle_from, self.idle_frames, self.woken) = (r.clock, 0, [false; 3]); + } + self.idle_frames += 1; + for (woke, by) in self.woken.iter_mut().zip([r.timer, r.live, r.polled]) { *woke |= by; } + if self.idle_frames == 120 { Some((self.label(), r.clock - self.idle_from)) } else { None } + } +} + +fn check(s: &mut Streak, old: &mut Old, r: Reading) -> Option<&'static str> { + let expected = old.end(r); + let got = match step(s, r) { + Effects::None => None, + Effects::One((woke, secs)) => Some((woke.label(), secs)), + _ => panic!("extra warning"), + }; + assert_eq!(got, expected); + match *s { + Streak::Watching => assert_eq!(old.idle_frames, 0), + Streak::Counting { from, frames, woke } => assert_eq!((from, frames, woke.label()), (old.idle_from, old.idle_frames, old.label())), + } + got.map(|(label, _)| label) +} + +#[test] +fn idle_readings_walk() { + let live = Reading { clock: 0.0, quiet: true, animating: false, same: Some(true), timer: false, live: true, polled: false }; + let events = [live, Reading { live: false, timer: true, ..live }, Reading { polled: true, ..live }, + // A timer wake whose poll returns true: the only reading that names both. + Reading { live: false, timer: true, polled: true, ..live }, + Reading { live: false, polled: true, ..live }, Reading { quiet: false, ..live }, Reading { animating: true, ..live }, + Reading { same: None, ..live }, Reading { same: Some(false), ..live }, Reading { clock: 2.0, ..live }, + Reading { clock: 2.01, ..live }, Reading { live: true, timer: true, ..live }]; + fn walk(s: Streak, old: Old, events: &[Reading], depth: u8, seen: &mut [bool; 4]) { + if depth == 0 { return; } + for &r in events { + let (mut s, mut old) = (s, old); + if let Some(label) = check(&mut s, &mut old, r) { + let labels = ["a `wake_after` loop whose `poll` returns true", "a `wake_after` loop", + "a `wake_after` loop and a live value", "a live value"]; + seen[labels.iter().position(|l| *l == label).unwrap()] = true; + } + walk(s, old, events, depth - 1, seen); + } + } + let mut seen = [false; 4]; + let (mut s, mut old) = (Streak::Watching, Old::default()); + walk(s, old, &events, 5, &mut seen); + // Start just below the real threshold too; don't substitute a smaller test limit. + for seed in [live, Reading { live: false, timer: true, ..live }] { + check(&mut s, &mut old, Reading { quiet: false, ..live }); + for _ in 0..118 { check(&mut s, &mut old, seed); } + walk(s, old, &events, 5, &mut seen); + } + let labels = ["a live value", "a `wake_after` loop", "a `wake_after` loop and a live value", + "a `wake_after` loop whose `poll` returns true"]; + for (i, (timer, live, polled)) in [(false, true, false), (true, false, false), (true, true, false), (true, false, true)].into_iter().enumerate() { + check(&mut s, &mut old, Reading { quiet: false, ..events[0] }); + let r = Reading { clock: 0.0, quiet: true, animating: false, same: Some(true), timer, live, polled }; + for _ in 0..119 { assert_eq!(check(&mut s, &mut old, r), None); } + assert_eq!(check(&mut s, &mut old, r), Some(labels[i]), "a 120-frame timer {timer} live {live} polled {polled} streak names its wake"); + } + assert!(seen.iter().all(|seen| *seen), "the walk reaches every wake label: {seen:?}"); +} diff --git a/app/vendor/rune/crates/rune/src/tooling/perf_warn/launch.rs b/app/vendor/rune/crates/rune/src/tooling/perf_warn/launch.rs new file mode 100644 index 0000000..ea20099 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/tooling/perf_warn/launch.rs @@ -0,0 +1,152 @@ +//! How long launch took to put the first frame up, split into the app's parts (`main` before +//! `run`, `init` and the first view build) and Rune's (window, GPU and drawing). Warns once +//! when the app's parts pass 100 ms: they are what `on_ready` can take off the first frame. +//! Rune's own time doesn't count toward it, so a debug build's slow GPU setup stays quiet. + +#[cfg(all(debug_assertions, not(target_arch = "wasm32")))] +use std::{sync::Mutex, time::{Duration, Instant}}; + +/// The app's share of the first frame, in ms, before it warns. +#[cfg(all(debug_assertions, not(target_arch = "wasm32")))] +const APP_MS: f64 = 100.0; + +#[cfg(all(debug_assertions, not(target_arch = "wasm32")))] +#[derive(Default)] +struct Launch { + /// When `run` started, and how long the process had run by then. + run: Option<(Instant, Option<Duration>)>, + init: Option<Duration>, + view: Option<Duration>, + done: bool, +} + +#[cfg(all(debug_assertions, not(target_arch = "wasm32")))] +static LAUNCH: Mutex<Launch> = Mutex::new(Launch { run: None, init: None, view: None, done: false }); + +/// `App::run` starts a window. +#[inline(always)] +#[cfg_attr(target_arch = "wasm32", allow(dead_code))] +pub(crate) fn run_starts() { + #[cfg(all(debug_assertions, not(target_arch = "wasm32")))] + { + let age = process_age(); + LAUNCH.lock().unwrap().run.get_or_insert((crate::time::now(), age)); + } +} + +/// Runs the app's `init`. +#[inline(always)] +pub(crate) fn init<T>(f: impl FnOnce() -> T) -> T { + #[cfg(all(debug_assertions, not(target_arch = "wasm32")))] + let start = crate::time::now(); + let out = super::timed("init", f); + #[cfg(all(debug_assertions, not(target_arch = "wasm32")))] + { + let mut launch = LAUNCH.lock().unwrap(); + if launch.run.is_some() && launch.init.is_none() { launch.init = Some(start.elapsed()); } + } + out +} + +/// Times a commit while it lives; the first after `run` starts is the first view build. +pub(crate) struct FirstView { + #[cfg(all(debug_assertions, not(target_arch = "wasm32")))] + start: Option<Instant>, +} + +impl FirstView { + #[inline(always)] + #[cfg_attr(not(all(debug_assertions, not(target_arch = "wasm32"))), allow(unused_variables))] + pub(crate) fn start(first: bool) -> Self { + FirstView { + #[cfg(all(debug_assertions, not(target_arch = "wasm32")))] + start: first.then(crate::time::now), + } + } +} + +#[cfg(all(debug_assertions, not(target_arch = "wasm32")))] +impl Drop for FirstView { + fn drop(&mut self) { + let Some(start) = self.start else { return }; + let mut launch = LAUNCH.lock().unwrap(); + if launch.run.is_some() && launch.view.is_none() { launch.view = Some(start.elapsed()); } + } +} + +/// The first window's first frame is ready. +#[inline(always)] +#[cfg_attr(target_arch = "wasm32", allow(dead_code))] +pub(crate) fn first_frame() { + #[cfg(all(debug_assertions, not(target_arch = "wasm32")))] + { + let mut launch = LAUNCH.lock().unwrap(); + let Some((run, age)) = launch.run.filter(|_| !launch.done) else { return }; + launch.done = true; + let ms = |d: Option<Duration>| d.map_or(0.0, |d| d.as_secs_f64() * 1000.0); + let (setup, init, view) = (ms(age), ms(launch.init), ms(launch.view)); + let total = setup + ms(Some(run.elapsed())); + drop(launch); + if let Some(message) = report(setup, init, view, total) { super::warn_once("first frame".into(), || message); } + } +} + +/// The warning for a first frame `total` ms after the process started, `setup` ms of it in +/// `main` before `run`, `init` in `init` and `view` in the first view build; none while the +/// app's parts stay under `APP_MS`. +#[cfg(all(debug_assertions, not(target_arch = "wasm32")))] +pub(crate) fn report(setup: f64, init: f64, view: f64, total: f64) -> Option<String> { + if setup + init + view <= APP_MS { return None } + let rune = (total - setup - init - view).max(0.0); + let parts = [(setup, "setup in `main` before `run`"), (init, "`init`"), (view, "the first `view`")]; + let slowest = parts.iter().max_by(|a, b| a.0.total_cmp(&b.0)).map_or("", |p| p.1); + Some(format!( + "first frame took {total:.0} ms (setup {setup:.0} ms, init {init:.0} ms, first view {view:.0} ms, window and \ + GPU {rune:.0} ms); the slowest is {slowest}: start slow work from `on_ready`" + )) +} + +/// How long this process has run, from the system's record of its start. +#[cfg(not(target_arch = "wasm32"))] +#[allow(unsafe_code)] +pub(crate) fn process_age() -> Option<std::time::Duration> { + #[cfg(any(target_os = "macos", target_os = "linux", windows))] + use std::time::Duration; + #[cfg(target_os = "macos")] + { + // SAFETY: `libc::proc_bsdinfo` is a plain C struct for which all zeroes is valid. + let mut info: libc::proc_bsdinfo = unsafe { std::mem::zeroed() }; + let size = std::mem::size_of::<libc::proc_bsdinfo>() as libc::c_int; + // SAFETY: `info` is a live, writable `proc_bsdinfo` of `size` bytes; `getpid` has no preconditions. + let got = unsafe { libc::proc_pidinfo(libc::getpid(), libc::PROC_PIDTBSDINFO, 0, (&raw mut info).cast(), size) }; + if got != size { return None } + let start = std::time::UNIX_EPOCH + Duration::new(info.pbi_start_tvsec, info.pbi_start_tvusec as u32 * 1000); + crate::time::system_now().duration_since(start).ok() + } + #[cfg(target_os = "linux")] + { + // Field 22 of /proc/self/stat is the start in clock ticks since boot; fields after the + // command's closing parenthesis start at field 3. + let stat = std::fs::read_to_string("/proc/self/stat").ok()?; + let start: f64 = stat[stat.rfind(')')? + 1..].split_whitespace().nth(19)?.parse().ok()?; + // SAFETY: sysconf reads a configuration value and takes no pointers. + let ticks = unsafe { libc::sysconf(libc::_SC_CLK_TCK) } as f64; + let up: f64 = std::fs::read_to_string("/proc/uptime").ok()?.split_whitespace().next()?.parse().ok()?; + (ticks > 0.0).then(|| Duration::from_secs_f64((up - start / ticks).max(0.0))) + } + #[cfg(windows)] + { + use windows_sys::Win32::{Foundation::FILETIME, System::Threading::{GetCurrentProcess, GetProcessTimes}}; + let mut created = FILETIME { dwLowDateTime: 0, dwHighDateTime: 0 }; + let (mut exited, mut kernel, mut user) = (created, created, created); + // SAFETY: the current-process pseudo-handle is valid and all four outputs are live, + // writable FILETIMEs. The pseudo-handle is borrowed, not closed. + if unsafe { GetProcessTimes(GetCurrentProcess(), &mut created, &mut exited, &mut kernel, &mut user) } == 0 { return None } + // FILETIME counts 100 ns ticks from 1601. + let ticks = ((u64::from(created.dwHighDateTime) << 32) | u64::from(created.dwLowDateTime)).checked_sub(116_444_736_000_000_000)?; + let start = std::time::UNIX_EPOCH + Duration::from_nanos(ticks * 100); + crate::time::system_now().duration_since(start).ok() + } + #[cfg(not(any(target_os = "macos", target_os = "linux", windows)))] + { None } +} diff --git a/app/vendor/rune/crates/rune/src/tooling/perf_warn/runq.rs b/app/vendor/rune/crates/rune/src/tooling/perf_warn/runq.rs new file mode 100644 index 0000000..1fedaa0 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/tooling/perf_warn/runq.rs @@ -0,0 +1,84 @@ +//! Time a thread spent runnable but waiting for a core. A callback that was descheduled on a +//! busy machine isn't blocked, so `Stall` takes that time out before it judges. Interaction +//! timing (`tooling::interaction`) asks [`overloaded`] in any build. + +#[cfg(debug_assertions)] +use super::{STALL_CPU_RATIO, STALL_MS}; + +/// How long the calling thread has waited in a run queue, in ms, since it started. Linux reads +/// the scheduler's own count; other systems don't expose it per thread, so they get `None`. +#[cfg(debug_assertions)] +pub(crate) fn wait_ms() -> Option<f64> { + #[cfg(any(target_os = "linux", target_os = "android"))] + { + let stats = std::fs::read_to_string("/proc/thread-self/schedstat").ok()?; + let ns: f64 = stats.split_whitespace().nth(1)?.parse().ok()?; + Some(ns / 1e6) + } + #[cfg(not(any(target_os = "linux", target_os = "android")))] + { None } +} + +/// Whether the machine has no core to spare: the 1-minute load average is at or above the core +/// count. Read at most every few seconds. Always false where there's no load average. +#[allow(unsafe_code)] +pub(crate) fn overloaded() -> bool { + #[cfg(unix)] + { + use std::{sync::Mutex, time::{Duration, Instant}}; + static CACHE: Mutex<Option<(Instant, bool)>> = Mutex::new(None); + let mut cache = CACHE.lock().unwrap(); + if let Some((at, busy)) = *cache && at.elapsed() < Duration::from_secs(5) { return busy } + let mut load = [0f64; 1]; + // SAFETY: `load` is a live, writable array of the one sample asked for. + let got = unsafe { libc::getloadavg(load.as_mut_ptr(), 1) }; + let cores = std::thread::available_parallelism().map_or(1, usize::from) as f64; + let busy = got == 1 && load[0] >= cores; + *cache = Some((crate::time::now(), busy)); + busy + } + #[cfg(not(unix))] + { false } +} + +/// The wall ms a callback was blocked, or `None` when it wasn't. `wait` is the run-queue time +/// it spent when known; without it, a `loaded` machine gets the benefit of the doubt. +#[cfg(debug_assertions)] +pub(crate) fn blocked_ms(wall: f64, cpu: f64, wait: Option<f64>, loaded: bool) -> Option<f64> { + if wait.is_none() && loaded { return None } + let blocked = wall - wait.unwrap_or(0.0).clamp(0.0, wall); + (blocked > STALL_MS && blocked > STALL_CPU_RATIO * cpu).then_some(blocked) +} + +#[cfg(all(test, debug_assertions))] +mod tests { + use super::*; + + #[test] + fn a_wait_for_a_core_is_not_blocking() { + assert_eq!(blocked_ms(36.0, 0.5, Some(35.0), false), None); + assert_eq!(blocked_ms(36.0, 0.5, Some(10.0), false), Some(26.0)); + } + + #[test] + fn real_blocking_still_warns() { + assert_eq!(blocked_ms(30.0, 0.0, Some(0.0), false), Some(30.0)); + assert_eq!(blocked_ms(30.0, 0.0, None, false), Some(30.0)); + } + + #[test] + fn computing_is_not_blocking() { + assert_eq!(blocked_ms(50.0, 40.0, Some(0.0), false), None); + } + + #[test] + fn without_a_wait_a_loaded_machine_is_forgiven() { + assert_eq!(blocked_ms(36.0, 0.5, None, true), None); + assert_eq!(blocked_ms(36.0, 0.5, Some(0.0), true), Some(36.0)); + } + + #[test] + fn the_wait_never_exceeds_the_wall() { + assert_eq!(blocked_ms(20.0, 0.0, Some(99.0), false), None); + } +} diff --git a/app/vendor/rune/crates/rune/src/tooling/perf_warn/tests.rs b/app/vendor/rune/crates/rune/src/tooling/perf_warn/tests.rs new file mode 100644 index 0000000..ae55187 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/tooling/perf_warn/tests.rs @@ -0,0 +1,247 @@ +use std::time::Duration; + +use super::*; +use crate::el::{col, row}; +use crate::runtime::Runtime; +use crate::{Cx, El, Env, GrowthSpec, ScrollSpec}; + +fn list(key: &'static str, rows: usize) -> El { + col().size(200.0, 200.0).scroll(ScrollSpec { stick_bottom: false }).child( + col().key(key).w_full().growth(GrowthSpec::default()).virtualize(20.0) + .children((0..rows).map(|i| row().key(format!("r{i}")).w_full().h(20.0))), + ) +} + +#[test] +fn a_virtualize_list_that_builds_far_more_rows_than_it_mounts_warns_once() { + take_log(); + fn view(_: &u32, _: &mut Cx<u32>) -> El { list("overbuilt-rows", 1000) } + let mut rt = Runtime::new(0u32, view, (200.0, 200.0), Env::new(true, 1.0)); + rt.frame(0.0); + rt.update(|n, _| *n += 1); + rt.frame(1.0 / 60.0); + let log = take_log(); + assert_eq!(log.len(), 1, "{log:?}"); + assert!(log[0].contains("overbuilt-rows") && log[0].contains("virtual_rows") && log[0].contains("built 1000 rows"), "{}", log[0]); +} + +#[test] +fn a_short_virtualize_list_stays_quiet() { + take_log(); + fn view(_: &u32, _: &mut Cx<u32>) -> El { list("short-rows", 150) } + let mut rt = Runtime::new(0u32, view, (200.0, 200.0), Env::new(true, 1.0)); + rt.frame(0.0); + assert_eq!(take_log(), Vec::<String>::new()); +} + +#[test] +fn a_callback_blocked_past_its_cpu_time_warns_once_per_site() { + if super::runq::wait_ms().is_none() && super::runq::overloaded() { + return eprintln!("skipped: the machine has no core to spare, so a sleep can't be told from a wait"); + } + take_log(); + for _ in 0..2 { + let stall = Stall::start(); + std::thread::sleep(Duration::from_millis(30)); + stall.end(|| ("test-blocked".into(), "`poll`".into())); + } + let log = take_log(); + assert_eq!(log.len(), 1, "{log:?}"); + assert!(log[0].starts_with("rune: `poll` blocked ") && log[0].contains("on the main thread: move IO off it with `rune::Latest` or a thread"), "{}", log[0]); +} + +/// Computes 30 ms of this thread's CPU time. A machine too loaded to give the thread a quarter of +/// a core makes that look blocked, as it would in an app, so the test skips then. +#[test] +fn a_callback_that_computes_is_not_a_stall() { + take_log(); + let (wall, cpu) = (crate::time::now(), crate::frame::profile::cpu_ms().unwrap()); + let stall = Stall::start(); + let mut n = 0u64; + while crate::frame::profile::cpu_ms().unwrap() - cpu < 30.0 { n = std::hint::black_box(n.wrapping_add(1)); } + if wall.elapsed() > Duration::from_millis(30 * STALL_CPU_RATIO as u64 / 2) { + return eprintln!("skipped: the thread got too little CPU to compute in time"); + } + stall.end(|| ("test-computing".into(), "`poll`".into())); + let quick = Stall::start(); + quick.end(|| ("test-quick".into(), "`poll`".into())); + assert_eq!(take_log(), Vec::<String>::new()); +} + +#[test] +fn a_blocking_poll_names_poll() { + if super::runq::wait_ms().is_none() && super::runq::overloaded() { + return eprintln!("skipped: the machine has no core to spare, so a sleep can't be told from a wait"); + } + take_log(); + fn view(_: &u32, _: &mut Cx<u32>) -> El { col() } + let mut rt = Runtime::new(0u32, view, (100.0, 100.0), Env::new(true, 1.0)); + rt.poll = Some(|_, _, _| { std::thread::sleep(Duration::from_millis(30)); false }); + rt.frame(0.0); + rt.frame(1.0 / 60.0); + let log = take_log(); + assert!(log.len() == 1 && log[0].starts_with("rune: `poll` blocked "), "{log:?}"); +} + +#[test] +fn a_blocking_update_names_update() { + if super::runq::wait_ms().is_none() && super::runq::overloaded() { + return eprintln!("skipped: the machine has no core to spare, so a sleep can't be told from a wait"); + } + take_log(); + fn view(_: &u32, _: &mut Cx<u32>) -> El { col() } + let mut rt = Runtime::new(0u32, view, (100.0, 100.0), Env::new(true, 1.0)); + rt.update(|_, _| std::thread::sleep(Duration::from_millis(30))); + rt.update(|_, _| std::thread::sleep(Duration::from_millis(30))); + let log = take_log(); + assert!(log.len() == 1 && log[0].starts_with("rune: an `update` closure blocked "), "{log:?}"); +} + +#[test] +fn rows_of_one_list_share_a_handler_site() { + assert_eq!(handler_site("on_press", "#0/list/r12"), handler_site("on_press", "#0/list/r7")); + assert_ne!(handler_site("on_press", "#0/list/r12"), handler_site("on_hover", "#0/list/r12")); +} + +fn titled<S: 'static>(state: S, view: fn(&S, &mut Cx<S>) -> El, title: &str, poll: fn(&mut S, f64, &mut crate::Tx) -> bool) -> Runtime<S> { + let mut rt = Runtime::new(state, view, (200.0, 200.0), Env::new(true, 1.0)); + rt.host.window_title.start(title); + rt.poll = Some(poll); + rt +} + +fn still(_: &u32, _: &mut Cx<u32>) -> El { + col().size(200.0, 200.0).child(row().size(20.0, 20.0).fill(crate::Color::WHITE)) +} + +#[test] +fn a_poll_that_always_says_changed_but_changes_nothing_warns_after_30_frames() { + take_log(); + let mut rt = titled(0u32, still, "poll-noop", |n, _, _| { *n += 1; true }); + for _ in 0..29 { rt.frame(1.0 / 60.0); } + assert_eq!(take_log(), Vec::<String>::new(), "not before 30 frames that change nothing"); + for _ in 0..40 { rt.frame(1.0 / 60.0); } + let log = take_log(); + assert_eq!(log.len(), 1, "{log:?}"); + assert!(log[0].starts_with("rune: `poll` of window \"poll-noop\" returned true but nothing changed") + && log[0].contains("return true only when visible state changed"), "{}", log[0]); +} + +#[test] +fn a_frame_whose_poll_does_not_say_changed_breaks_the_run() { + take_log(); + // 29 quiet identical frames whose `poll` returns true, one whose `poll` returns false, one + // more that returns true: the false frame ends the run, so 30 in a row never happened. + let mut rt = titled(0u32, still, "poll-gap", |n, _, _| { *n += 1; *n != 31 }); + for _ in 0..32 { rt.frame(1.0 / 60.0); } + assert_eq!(take_log(), Vec::<String>::new(), "a frame whose `poll` returned false breaks the run"); + // The run starts over on the other side of the gap: 29 more true frames stay quiet, the + // 30th warns as before. + for _ in 0..28 { rt.frame(1.0 / 60.0); } + assert_eq!(take_log(), Vec::<String>::new(), "not before 30 frames in a row after the gap"); + rt.frame(1.0 / 60.0); + let log = take_log(); + assert_eq!(log.len(), 1, "{log:?}"); + assert!(log[0].contains("returned true but nothing changed (30 frames in a row)"), "{}", log[0]); +} + +#[test] +fn a_poll_that_changes_what_shows_stays_quiet() { + take_log(); + fn view(n: &u32, _: &mut Cx<u32>) -> El { + col().size(200.0, 200.0).child(crate::el::text(format!("tick {n}"))) + } + let mut rt = titled(0u32, view, "poll-real", |n, _, tx| { *n += 1; tx.wake_after(Duration::from_millis(16)); true }); + for _ in 0..300 { rt.frame(1.0 / 60.0); } + assert_eq!(take_log(), Vec::<String>::new()); +} + +#[test] +fn an_endless_16_ms_wake_after_loop_on_an_idle_window_warns() { + take_log(); + let mut rt = titled(0u32, still, "idle-loop", |_, _, tx| { tx.wake_after(Duration::from_millis(16)); false }); + for _ in 0..100 { rt.frame(1.0 / 60.0); } + assert_eq!(take_log(), Vec::<String>::new(), "not before 120 frames"); + for _ in 0..100 { rt.frame(1.0 / 60.0); } + let log = take_log(); + assert_eq!(log.len(), 1, "{log:?}"); + assert!(log[0].starts_with("rune: idle window \"idle-loop\" still drawing: check `wake_after` loops (120 frames in ") + && log[0].contains("woken by a `wake_after` loop)"), "{}", log[0]); +} + +#[test] +fn a_wake_after_loop_that_always_says_changed_names_poll_too() { + take_log(); + let mut rt = titled(0u32, still, "idle-poll-loop", |_, _, tx| { tx.wake_after(Duration::from_millis(16)); true }); + for _ in 0..200 { rt.frame(1.0 / 60.0); } + let log = take_log(); + assert_eq!(log.len(), 2, "{log:?}"); + assert!(log[0].contains("`poll` of window \"idle-poll-loop\" returned true"), "{}", log[0]); + assert!(log[1].contains("woken by a `wake_after` loop whose `poll` returns true"), "{}", log[1]); +} + +#[test] +fn a_wake_after_loop_that_stops_stays_quiet() { + take_log(); + let mut rt = titled(0u32, still, "loop-stops", |n, _, tx| { + *n += 1; + if *n < 100 { tx.wake_after(Duration::from_millis(16)); } + false + }); + for _ in 0..400 { rt.frame(1.0 / 60.0); } + assert_eq!(take_log(), Vec::<String>::new()); +} + +#[test] +fn a_wake_after_loop_under_running_motion_stays_quiet() { + take_log(); + fn view(_: &u32, _: &mut Cx<u32>) -> El { + col().size(200.0, 200.0).child(row().size(20.0, 20.0).fill(crate::Color::WHITE) + .looping(rune_motion::LoopSpec::opacity(1.0, 0.0, 0.2, 1.0))) + } + let mut rt = titled(0u32, view, "loop-moving", |_, _, tx| { tx.wake_after(Duration::from_millis(16)); false }); + for _ in 0..300 { rt.frame(1.0 / 60.0); } + assert_eq!(take_log(), Vec::<String>::new()); + + fn spring(x: &f32, _: &mut Cx<f32>) -> El { + col().size(200.0, 200.0).child(row().key("box").size(20.0, 20.0).absolute(*x, 0.0).fill(crate::Color::WHITE) + .motion(rune_motion::Spring::new(3.0, 0.0))) + } + let mut rt = titled(0.0f32, spring, "spring-moving", |_, clock, tx| { + if clock < 2.5 { tx.wake_after(Duration::from_millis(16)); } + false + }); + rt.frame(0.0); + rt.update(|x, _| *x = 150.0); + let moving = (0..150).filter(|_| rt.frame(1.0 / 60.0)).count(); + assert!(moving >= 140, "the spring runs through the loop: {moving}"); + for _ in 0..100 { rt.frame(1.0 / 60.0); } + assert_eq!(take_log(), Vec::<String>::new()); +} + +#[test] +fn a_slow_launch_names_its_slowest_part_and_rune_s_own_time_stays_quiet() { + assert_eq!(launch::report(5.0, 40.0, 20.0, 400.0), None, "Rune's own window and GPU time doesn't count"); + let message = launch::report(10.0, 180.0, 12.0, 260.0).unwrap(); + assert_eq!(message, "first frame took 260 ms (setup 10 ms, init 180 ms, first view 12 ms, window and GPU 58 ms); \ + the slowest is `init`: start slow work from `on_ready`"); + assert!(launch::report(150.0, 0.0, 0.0, 200.0).unwrap().contains("the slowest is setup in `main` before `run`")); +} + +#[test] +fn a_memo_over_a_differently_keyed_root_warns_once_per_site() { + take_log(); + fn view(_: &u32, _: &mut Cx<u32>) -> El { + let same = crate::memo("same", 0, || col().key("same")); + let renamed = crate::memo("outer", 0, || col().key("inner")); + col().child(same).child(renamed) + } + let mut rt = Runtime::new(0u32, view, (200.0, 200.0), Env::new(true, 1.0)); + rt.frame(0.0); + rt.update(|n, _| *n += 1); + rt.frame(1.0 / 60.0); + let log = take_log(); + assert_eq!(log.len(), 1, "{log:?}"); + assert!(log[0].contains("\"outer\"") && log[0].contains("\"inner\""), "{}", log[0]); + assert!(rt.find("outer").is_some() && rt.find("inner").is_none()); +} diff --git a/app/vendor/rune/crates/rune/src/tooling/playground_cli_tests.rs b/app/vendor/rune/crates/rune/src/tooling/playground_cli_tests.rs new file mode 100644 index 0000000..5e8ed23 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/tooling/playground_cli_tests.rs @@ -0,0 +1,120 @@ +//! `--playground NAME` with `--snap`, `--out`, `--video`, `--script`, `--variant` and +//! `--crop KEY`, headless and the same every run. + +use super::*; + +#[derive(Default)] +struct Pad { + x: f32, + size: f32, + green: bool, +} + +fn pad(p: &Pad, _: &mut Cx<Pad>) -> crate::El { + let fill = if p.green { crate::oklch(0.7, 0.2, 145.0) } else { crate::oklch(0.6, 0.2, 30.0) }; + crate::el().w_full().h_full().child(crate::el().key("puck").absolute(p.x, 10.0).size(p.size, p.size).fill(fill)) +} + +static SCENES: &[(&str, fn(&mut Pad))] = &[("Motion/Slide", |p| p.size = 20.0)]; + +fn app() -> crate::App<Pad> { + let playground = crate::Playground::<Pad>::new() + .enabled(true) + .trigger("Slide", 'r', "Slide", |_, play| play.after(0.3, |p, _| p.x = 60.0)) + .trigger("Slide", 'g', "Green", |p, _| p.green = true) + .variant("Slide", "Small", |p| p.size = 20.0) + .variant("Slide", "Big", |p| p.size = 40.0); + let mut spec = AppSpec::new("pad", (960.0, 240.0), Pad::default, pad); + spec.scenes = SCENES; + crate::App::new(spec).playground(playground) +} + +fn run(dir: &std::path::Path, name: &str, args: &[&str]) -> std::path::PathBuf { + let out = dir.join(name); + std::fs::create_dir_all(&out).unwrap(); + let snap = out.join("snap.png"); + let mut argv: Vec<String> = ["--playground", "Motion/Slide", "--scale", "2", "--fps", "30", "--snap", snap.to_str().unwrap()].map(String::from).into(); + argv.extend(args.iter().map(|a| a.replace("{out}", out.to_str().unwrap()))); + headless(app(), Args::parse_from(argv)); + out +} + +fn bytes(dir: &std::path::Path) -> Vec<(String, Vec<u8>)> { + let mut files: Vec<_> = std::fs::read_dir(dir).unwrap().map(|e| e.unwrap().path()).collect(); + files.sort(); + files.into_iter().flat_map(|p| if p.is_dir() { bytes(&p) } else { vec![(p.file_name().unwrap().to_string_lossy().into(), std::fs::read(&p).unwrap())] }).collect() +} + +fn png_size(path: &std::path::Path) -> (u32, u32) { + let b = std::fs::read(path).unwrap(); + let be = |i: usize| u32::from_be_bytes([b[i], b[i + 1], b[i + 2], b[i + 3]]); + (be(16), be(20)) +} + +#[test] +fn a_playground_scene_renders_its_script_the_same_every_run() { + let _turn = HEADLESS.lock().unwrap_or_else(|e| e.into_inner()); + let dir = std::env::temp_dir().join(format!("rune-playground-cli-{}", std::process::id())); + let script = dir.join("script.json"); + std::fs::create_dir_all(&dir).unwrap(); + // G's trigger runs at 0.5 s on the logical clock, after the slide 'r' started on choosing. + std::fs::write(&script, r#"[{"t": 0.5, "type": "type", "text": "g"}, {"t": 1.2, "type": "mark", "name": "end"}]"#).unwrap(); + let video = std::process::Command::new("ffprobe").arg("-version").output().is_ok(); + let mut args = vec!["--script", script.to_str().unwrap(), "--at", "1.0", "--out", "{out}/frames", "--every", "6"]; + if video { args.extend(["--video", "{out}/clip.mp4"]); } + let first = bytes(&run(&dir, "first", &args)); + let second = bytes(&run(&dir, "second", &args)); + assert!(first.iter().any(|(n, _)| n == "snap.png") && first.iter().any(|(n, _)| n.starts_with("frame_"))); + assert_eq!(first.iter().any(|(n, _)| n == "clip.mp4"), video); + for ((name, a), (_, b)) in first.iter().zip(&second) { + assert!(a == b, "{name} differs between runs"); + } + assert_eq!(first.len(), second.len()); + let still = bytes(&run(&dir, "still", &["--at", "1.0"])); + let start = bytes(&run(&dir, "start", &["--at", "0"])); + let snap = |files: &[(String, Vec<u8>)]| files.iter().find(|(n, _)| n == "snap.png").unwrap().1.clone(); + assert!(snap(&first) != snap(&still), "the script's trigger key changed the scene"); + assert!(snap(&still) != snap(&start), "choosing the scene played its 'r' motion"); + std::fs::remove_dir_all(dir).unwrap(); +} + +#[test] +fn variant_and_crop_pick_a_storys_variant_and_crop_the_snap_to_an_element() { + let _turn = HEADLESS.lock().unwrap_or_else(|e| e.into_inner()); + let dir = std::env::temp_dir().join(format!("rune-playground-crop-{}", std::process::id())); + let parsed = Args::parse_from(["--playground", "--snap", "s.png", "--crop", "1,2,3,4", "--crop", "puck", "--variant", "Big"].map(String::from).into()); + assert_eq!((parsed.crops, parsed.crop_key.as_deref(), parsed.variant.as_deref()), (vec![[1.0, 2.0, 3.0, 4.0]], Some("puck"), Some("Big"))); + let small = run(&dir, "small", &["--variant", "1", "--crop", "puck"]); + let big = run(&dir, "big", &["--variant", "Big", "--crop", "puck"]); + let again = run(&dir, "again", &["--variant", "big", "--crop", "puck"]); + assert_eq!(png_size(&small.join("snap.png")), (40, 40), "the puck's 20 pt at 2x"); + assert_eq!(png_size(&big.join("snap.png")), (80, 80), "--variant, by name"); + assert!(bytes(&big) == bytes(&again), "the same every run"); + std::fs::remove_dir_all(dir).unwrap(); +} + +#[test] +fn whole_window_snaps_the_list_and_side_column_and_crops_to_their_keys() { + let _turn = HEADLESS.lock().unwrap_or_else(|e| e.into_inner()); + let dir = std::env::temp_dir().join(format!("rune-playground-whole-{}", std::process::id())); + let stage = run(&dir, "stage", &["--at", "0"]); + let whole = run(&dir, "whole", &["--at", "0", "--whole-window"]); + let again = run(&dir, "again", &["--at", "0", "--whole-window"]); + let group = run(&dir, "group", &["--at", "0", "--whole-window", "--crop", "playground-group-0"]); + let side = run(&dir, "side", &["--at", "0", "--whole-window", "--crop", "playground-side"]); + let rgba = |d: &std::path::Path| image::open(d.join("snap.png")).unwrap().to_rgba8(); + let (stage_px, whole_px) = (rgba(&stage), rgba(&whole)); + assert_eq!(stage_px.dimensions(), (988, 480), "by default the stage only: 960 - 200 - 264 - 2 pt, at 2x"); + assert_eq!(whole_px.dimensions(), (1920, 480), "--whole-window: the whole window"); + // The stage sits after the 200 pt list and its 1 pt separator. + assert!(image::imageops::crop_imm(&whole_px, 402, 0, 988, 480).to_image() == stage_px, "the same stage inside the whole window"); + let varied = |x: u32, w: u32| { + let region = image::imageops::crop_imm(&whole_px, x, 0, w, 480).to_image(); + region.pixels().any(|p| p != region.get_pixel(0, 0)) + }; + assert!(varied(0, 400) && varied(1392, 528), "the list and the side column are drawn"); + assert!(bytes(&whole) == bytes(&again), "the same every run"); + assert_eq!(png_size(&group.join("snap.png")), (368, 48), "a group header: the list's 184 pt by 24 pt, at 2x"); + assert_eq!(png_size(&side.join("snap.png")), (528, 480), "the side column's 264 pt"); + std::fs::remove_dir_all(dir).unwrap(); +} diff --git a/app/vendor/rune/crates/rune/src/tooling/record.rs b/app/vendor/rune/crates/rune/src/tooling/record.rs new file mode 100644 index 0000000..979a81f --- /dev/null +++ b/app/vendor/rune/crates/rune/src/tooling/record.rs @@ -0,0 +1,393 @@ +//! Headless frame output: a ring of staging buffers so the GPU renders the next frame while the +//! last one is read back, and writer threads that stream frames to ffmpeg or PNG files. + +use std::collections::VecDeque; +use std::io::Write; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::{Arc, Mutex, mpsc}; + +use crate::render::Offscreen; + +/// Readbacks in flight: rendering frame n + 1 and n + 2 overlaps mapping frame n. +pub(crate) const DEPTH: usize = 3; + +struct Slot { + readback: rune_staging::Readback, + ready: Arc<AtomicBool>, +} + +/// Staging buffers for an offscreen target, used in order. `T` tags each frame. +pub(crate) struct Readback<T> { + slots: Vec<Slot>, + next: usize, + /// Copied frames, oldest first: slot, tag, and whether `map_async` was called. + pending: VecDeque<(usize, T, bool)>, +} + +impl<T> Readback<T> { + pub(crate) fn new(device: &wgpu::Device, target: &Offscreen, depth: usize) -> Self { + let slots = (0..depth.max(1)).map(|_| Slot { + readback: rune_staging::Readback::new(device, "readback ring", target.width, target.height, 4), + ready: Arc::new(AtomicBool::new(false)), + }).collect(); + Readback { slots, next: 0, pending: VecDeque::new() } + } + + /// Frames that must finish before the next `copy` has a free buffer (waits for the oldest + /// when every buffer is in flight). + pub(crate) fn make_room(&mut self, device: &wgpu::Device) -> Vec<(T, Vec<u8>)> { + let mut done = Vec::new(); + if self.pending.len() >= self.slots.len() { + done.extend(self.pop(device, true)); + } + done + } + + /// Records a copy of `target` into the next free buffer. Call `submitted` after the encoder + /// is submitted. + pub(crate) fn copy(&mut self, encoder: &mut wgpu::CommandEncoder, target: &Offscreen, tag: T) { + assert!(self.pending.len() < self.slots.len(), "Readback::make_room first"); + let slot = self.next; + self.next = (self.next + 1) % self.slots.len(); + self.slots[slot].readback.copy_from(encoder, target.texture()); + self.pending.push_back((slot, tag, false)); + } + + /// Starts mapping every copied buffer whose commands were submitted. + pub(crate) fn submitted(&mut self) { + for (slot, _, mapping) in self.pending.iter_mut().filter(|p| !p.2) { + let ready = self.slots[*slot].ready.clone(); + ready.store(false, Ordering::Release); + // A lost device's map fails: the frame stays unready and `pop`'s wait says why. + self.slots[*slot].readback.buffer().slice(..).map_async(wgpu::MapMode::Read, move |r| { + if r.is_ok() { ready.store(true, Ordering::Release); } + }); + *mapping = true; + } + } + + /// Finished frames in submission order, without waiting. + pub(crate) fn ready(&mut self, device: &wgpu::Device) -> Vec<(T, Vec<u8>)> { + rune_gpu::health::poll(device, wgpu::PollType::Poll).ok(); + let mut done = Vec::new(); + while let Some(frame) = self.pop(device, false) { done.push(frame); } + done + } + + /// Waits for every frame in flight. + pub(crate) fn finish(&mut self, device: &wgpu::Device) -> Vec<(T, Vec<u8>)> { + let mut done = Vec::new(); + while let Some(frame) = self.pop(device, true) { done.push(frame); } + done + } + + fn pop(&mut self, device: &wgpu::Device, wait: bool) -> Option<(T, Vec<u8>)> { + let &(slot, _, mapping) = self.pending.front()?; + assert!(mapping, "Readback::submitted after submitting the copy"); + let ready = &self.slots[slot].ready; + if !ready.load(Ordering::Acquire) { + if !wait { return None; } + while !ready.load(Ordering::Acquire) { + match rune_gpu::health::poll(device, wgpu::PollType::wait_indefinitely()) { + Err(error) => crate::tooling::args::die(&format!("{error} while a frame was read back; no image was written")), + // Nothing left to wait for, and the map failed. + Ok(wgpu::PollStatus::QueueEmpty) if !ready.load(Ordering::Acquire) => crate::tooling::args::die("a frame's readback failed; no image was written"), + Ok(_) => {} + } + } + } + let (slot, tag, _) = self.pending.pop_front().unwrap(); + let pixels = self.slots[slot].readback.take_mapped(); + Some((tag, pixels)) + } +} + +/// Rows of `width` RGBA pixels from a buffer whose rows are `padded_row` bytes apart. +#[cfg(test)] +pub(crate) fn unpad(data: &[u8], width: u32, height: u32, padded_row: u32) -> Vec<u8> { + rune_staging::unpad_rows(data, (width * 4) as usize, height, padded_row) +} + +// ------------------------------------------------------------------------------------------- +// Video + +/// The container and codec `--video` picks from the file extension. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum Container { + /// H.264, yuv420p, `+faststart`: plays everywhere. + Mp4, + /// ProRes 4444 with alpha, for editing. + Mov, + /// VP9, yuv420p. + Webm, +} + +impl Container { + pub(crate) fn of(path: &Path) -> Result<Container, String> { + match path.extension().and_then(|e| e.to_str()).map(str::to_ascii_lowercase).as_deref() { + Some("mp4") => Ok(Container::Mp4), + Some("mov") => Ok(Container::Mov), + Some("webm") => Ok(Container::Webm), + _ => Err(format!("--video {}: use a .mp4, .mov or .webm file", path.display())), + } + } + + fn codec(self) -> &'static [&'static str] { + // yuv420p needs even sizes; pad odd ones by a pixel. Rune renders sRGB; tag it BT.709 + // like screen recorders do, and convert with the matching matrix. + const EVEN: &str = "pad=ceil(iw/2)*2:ceil(ih/2)*2,scale=out_color_matrix=bt709:out_range=tv,format=yuv420p"; + const TAGS: [&str; 6] = ["-colorspace", "bt709", "-color_primaries", "bt709", "-color_trc", "bt709"]; + match self { + Container::Mp4 => &["-c:v", "libx264", "-preset", "medium", "-crf", "18", "-vf", EVEN, + TAGS[0], TAGS[1], TAGS[2], TAGS[3], TAGS[4], TAGS[5], "-movflags", "+faststart"], + Container::Mov => &["-c:v", "prores_ks", "-profile:v", "4444", "-pix_fmt", "yuva444p10le", + "-vf", "scale=out_color_matrix=bt709:out_range=tv", + "-vendor", "apl0", TAGS[0], TAGS[1], TAGS[2], TAGS[3], TAGS[4], TAGS[5]], + Container::Webm => &["-c:v", "libvpx-vp9", "-crf", "30", "-b:v", "0", "-row-mt", "1", "-deadline", "good", + "-cpu-used", "4", "-vf", EVEN, TAGS[0], TAGS[1], TAGS[2], TAGS[3], TAGS[4], TAGS[5]], + } + } +} + +/// The ffmpeg arguments for raw RGBA frames on stdin. +pub(crate) fn ffmpeg_args(path: &Path, size: (u32, u32), fps: f64) -> Result<Vec<String>, String> { + let container = Container::of(path)?; + let mut args: Vec<String> = ["-hide_banner", "-loglevel", "error", "-nostdin", "-y", "-f", "rawvideo", "-pix_fmt", "rgba", + "-s", &format!("{}x{}", size.0, size.1), "-r", &fps.to_string(), "-i", "-"].map(String::from).into(); + args.extend(container.codec().iter().map(|s| (*s).to_owned())); + let output = path.display().to_string(); + args.push(if path.is_relative() && output.starts_with('-') { format!("./{output}") } else { output }); + Ok(args) +} + +/// Where finished frames go, off the render thread: ffmpeg's stdin, PNG files, or both. +pub(crate) struct Writer { + video: Option<(mpsc::SyncSender<Vec<u8>>, std::thread::JoinHandle<Result<(), String>>, PathBuf)>, + pngs: Option<(mpsc::SyncSender<(PathBuf, Vec<u8>)>, Vec<std::thread::JoinHandle<Result<(), String>>>)>, + size: (u32, u32), +} + +/// Reap the encoder even if spawning its writer thread fails or the thread panics. +struct Encoder(std::process::Child); + +impl Drop for Encoder { + fn drop(&mut self) { + if !matches!(self.0.try_wait(), Ok(Some(_))) { + self.0.kill().ok(); + self.0.wait().ok(); + } + } +} + +impl Writer { + pub(crate) fn new(size: (u32, u32)) -> Writer { + Writer { video: None, pngs: None, size } + } + + /// Starts ffmpeg; fails when it isn't installed or the extension is unknown. + pub(crate) fn video(&mut self, path: &Path, fps: f64) -> Result<(), String> { + let args = ffmpeg_args(path, self.size, fps)?; + if let Some(dir) = path.parent().filter(|d| !d.as_os_str().is_empty()) { + std::fs::create_dir_all(dir).map_err(|e| format!("{}: {e}", dir.display()))?; + } + let child = std::process::Command::new("ffmpeg").args(&args) + .stdin(std::process::Stdio::piped()).stdout(std::process::Stdio::null()) + .spawn().map_err(|e| match e.kind() { + std::io::ErrorKind::NotFound => "--video needs ffmpeg on PATH (macOS: brew install ffmpeg; Debian/Ubuntu: apt install ffmpeg)".to_owned(), + _ => format!("ffmpeg: {e}"), + })?; + self.encode(child, path) + } + + fn encode(&mut self, mut child: std::process::Child, path: &Path) -> Result<(), String> { + let mut stdin = child.stdin.take().unwrap(); + let mut child = Encoder(child); + let (tx, rx) = mpsc::sync_channel::<Vec<u8>>(DEPTH); + let out = path.to_owned(); + let thread = std::thread::Builder::new().name("rune-video".into()).spawn(move || { + let mut failed = None; + for frame in rx { + if let Err(e) = stdin.write_all(&frame) { + failed = Some(e); + break; + } + } + drop(stdin); + let status = child.0.wait().map_err(|e| format!("ffmpeg: {e}"))?; + match (status.success(), failed) { + (true, None) => Ok(()), + (_, Some(e)) => Err(format!("ffmpeg stopped reading frames ({e}; {status}); see its message above")), + (false, None) => Err(format!("ffmpeg failed writing {} ({status})", out.display())), + } + }).map_err(|e| e.to_string())?; + self.video = Some((tx, thread, path.to_owned())); + Ok(()) + } + + pub(crate) fn has_video(&self) -> bool { self.video.is_some() } + + pub(crate) fn frame(&mut self, pixels: Vec<u8>) -> Result<(), String> { + if let Some((tx, ..)) = &self.video && tx.send(pixels).is_err() { + self.finish_inner()?; + return Err("video writer disconnected".into()); + } + Ok(()) + } + + /// Encodes `pixels` as a PNG at `path` on a worker thread. + pub(crate) fn png(&mut self, path: PathBuf, pixels: Vec<u8>) -> Result<(), String> { + let size = self.size; + let (tx, _) = self.pngs.get_or_insert_with(|| { + let (tx, rx) = mpsc::sync_channel::<(PathBuf, Vec<u8>)>(DEPTH * 2); + let rx = Arc::new(Mutex::new(rx)); + let workers = std::thread::available_parallelism().map_or(2, |n| n.get().clamp(1, 4)); + let threads = (0..workers).map(|_| { + let rx = rx.clone(); + std::thread::spawn(move || { + loop { + let job = rx.lock().unwrap().recv(); + let Ok((path, px)) = job else { return Ok(()) }; + crate::render::write_png(&path, size.0, size.1, &px).map_err(|e| format!("{}: {e}", path.display()))?; + } + }) + }).collect(); + (tx, threads) + }); + if tx.send((path, pixels)).is_err() { + self.finish_inner()?; + return Err("PNG writers disconnected".into()); + } + Ok(()) + } + + /// Waits for every frame to be written; the video path when one was made. + pub(crate) fn finish(mut self) -> Result<Option<PathBuf>, String> { self.finish_inner() } + + fn finish_inner(&mut self) -> Result<Option<PathBuf>, String> { + // Close both queues before joining, and always join every writer even if one failed. + let pngs = self.pngs.take().map(|(tx, threads)| { drop(tx); threads }); + let video = self.video.take().map(|(tx, thread, path)| { drop(tx); (thread, path) }); + let mut result = Ok(None); + if let Some(threads) = pngs { + for t in threads { + if let Err(e) = t.join().unwrap_or_else(|_| Err("PNG writer panicked".into())) { result = Err(e); } + } + } + if let Some((thread, path)) = video { + let encoded = thread.join().unwrap_or_else(|_| Err("video writer panicked".into())); + result = result.and(encoded.map(|()| Some(path))); + } + result + } +} + +impl Drop for Writer { + fn drop(&mut self) { + if let Err(e) = self.finish_inner() { eprintln!("rune: {e}"); } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn video_containers_follow_the_extension() { + assert_eq!(Container::of(Path::new("a/b.MP4")), Ok(Container::Mp4)); + assert_eq!(Container::of(Path::new("b.mov")), Ok(Container::Mov)); + assert_eq!(Container::of(Path::new("b.webm")), Ok(Container::Webm)); + assert!(Container::of(Path::new("b.gif")).is_err()); + let args = ffmpeg_args(Path::new("out.mp4"), (1920, 1200), 60.0).unwrap(); + let joined = args.join(" "); + assert!(joined.contains("-f rawvideo -pix_fmt rgba -s 1920x1200 -r 60 -i -"), "{joined}"); + assert!(joined.contains("libx264") && joined.contains("+faststart") && joined.ends_with("out.mp4"), "{joined}"); + for (path, output) in [("-out.mp4", "./-out.mp4"), ("-dir/out.mov", "./-dir/out.mov"), ("dir/-out.webm", "dir/-out.webm")] { + assert_eq!(ffmpeg_args(Path::new(path), (2, 2), 60.0).unwrap().last().unwrap(), output); + } + } + + #[test] + fn unpad_drops_row_padding() { + let data = [1, 2, 3, 4, 9, 9, 9, 9, 5, 6, 7, 8, 9, 9, 9, 9]; + assert_eq!(unpad(&data, 1, 2, 8), [1, 2, 3, 4, 5, 6, 7, 8]); + } + + #[cfg(unix)] + #[test] + fn encoder_errors_close_stdin_and_report_the_exit_status() { + let start = |command| { + let child = std::process::Command::new("sh").args(["-c", command]) + .stdin(std::process::Stdio::piped()).spawn().unwrap(); + let mut writer = Writer::new((64, 64)); + writer.encode(child, Path::new("test.mp4")).unwrap(); + writer + }; + let mut early = start("exit 17"); + let error = (0..20).find_map(|_| early.frame(vec![0; 64 * 64 * 4]).err()) + .expect("an early exit must stop accepting frames"); + assert!(error.contains("17") && error.contains("stopped reading"), "{error}"); + + // This child cannot exit until finish closes stdin, and fails only after consuming it. + let mut late = start("cat >/dev/null; exit 23"); + late.frame(vec![0; 64 * 64 * 4]).unwrap(); + let error = late.finish().unwrap_err(); + assert!(error.contains("23") && error.contains("failed writing"), "{error}"); + + let mut success = start("cat >/dev/null"); + success.frame(vec![0; 64 * 64 * 4]).unwrap(); + assert_eq!(success.finish().unwrap(), Some(PathBuf::from("test.mp4"))); + } + + #[test] + fn pipelined_readbacks_match_serial_pixels_in_order_across_wraps() { + let gpu = crate::render::Gpu::headless(); + // An odd width exercises row-padding removal as well as ring reuse and final draining. + let target = Offscreen::new(&gpu.device, 37, 23); + let mut ring = Readback::new(&gpu.device, &target, DEPTH); + let mut actual = Vec::new(); + let mut expected = Vec::new(); + for i in 0..11 { + actual.extend(ring.make_room(&gpu.device)); + let mut encoder = gpu.device.create_command_encoder(&Default::default()); + { + let _pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { + color_attachments: &[Some(wgpu::RenderPassColorAttachment { + view: &target.view, depth_slice: None, resolve_target: None, + ops: wgpu::Operations { + load: wgpu::LoadOp::Clear(wgpu::Color { r: i as f64 / 12.0, g: 0.1, b: 0.3, a: 1.0 }), + store: wgpu::StoreOp::Store, + }, + })], + ..Default::default() + }); + } + ring.copy(&mut encoder, &target, i); + gpu.queue.submit([encoder.finish()]); + ring.submitted(); + // Let full rings exercise blocking make_room; others exercise nonblocking ready. + if i % 4 == 0 { actual.extend(ring.ready(&gpu.device)); } + } + actual.extend(ring.finish(&gpu.device)); + // Independent serial reference, rendered after the pipelined run so it cannot pace it. + for i in 0..11 { + let mut encoder = gpu.device.create_command_encoder(&Default::default()); + { + let _pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { + color_attachments: &[Some(wgpu::RenderPassColorAttachment { + view: &target.view, depth_slice: None, resolve_target: None, + ops: wgpu::Operations { + load: wgpu::LoadOp::Clear(wgpu::Color { r: i as f64 / 12.0, g: 0.1, b: 0.3, a: 1.0 }), + store: wgpu::StoreOp::Store, + }, + })], + ..Default::default() + }); + } + target.copy(&mut encoder); + gpu.queue.submit([encoder.finish()]); + expected.push((i, target.read(&gpu.device))); + } + assert_eq!(actual, expected, "no drops, duplicates, reordering or stale slot contents"); + } +} diff --git a/app/vendor/rune/crates/rune/src/tooling/script.rs b/app/vendor/rune/crates/rune/src/tooling/script.rs new file mode 100644 index 0000000..aaf4fca --- /dev/null +++ b/app/vendor/rune/crates/rune/src/tooling/script.rs @@ -0,0 +1,324 @@ +//! Parsing a `--script`'s JSON into input events. + +use super::*; + +/// `{"text": …, "html": …, "rtf": …, "png": "path/to/image.png"}`, each optional, as another +/// app's clipboard would hold. +pub(crate) fn paste_content(e: &Value) -> crate::ClipboardContent { + let mut content = crate::ClipboardContent::new(e["text"].as_str().unwrap_or("")); + if let Some(html) = e["html"].as_str() { content = content.with_html(html); } + if let Some(rtf) = e["rtf"].as_str() { content = content.with_rtf(rtf); } + if let Some(path) = e["png"].as_str() { + let bytes = std::fs::read(path).unwrap_or_else(|err| die(&format!("paste png {path}: {err}"))); + let image = crate::ClipboardImage::from_png(bytes).unwrap_or_else(|| die(&format!("paste png {path}: not a PNG, or over clipboard::MAX_IMAGE_BYTES"))); + content = content.with_image(image); + } + content +} + +pub(crate) fn parse_script(list: Value) -> Vec<Ev> { + let Value::Array(items) = list else { die("script must be an array of events or {\"events\": [...]}") }; + let mut out = Vec::new(); + for e in items { + let t = e["t"].as_f64().unwrap_or(0.0); + if let Some(focused) = e["focus"].as_bool() { + out.push(Ev { t, kind: Kind::Focus(focused), pos: Pos::Rel(0.0, 0.0) }); + continue; + } + if let Some(item) = e["menu"].as_str() { + out.push(Ev { t, kind: Kind::Menu(item.into()), pos: Pos::Rel(0.0, 0.0) }); + continue; + } + if e["reopen"].as_bool() == Some(true) { + out.push(Ev { t, kind: Kind::Reopen, pos: Pos::Rel(0.0, 0.0) }); + continue; + } + if let Some(url) = e["open_url"].as_str() { + out.push(Ev { t, kind: Kind::OpenUrl(url.into()), pos: Pos::Rel(0.0, 0.0) }); + continue; + } + if let Some(chord) = e["physical"].as_str() { + let chord: crate::Shortcut = chord.parse().unwrap_or_else(|e: crate::ShortcutError| die(&e.to_string())); + let repeat = e["repeat"].as_bool().unwrap_or(false); + for pressed in [true, false] { + out.push(Ev { t, kind: Kind::Physical(crate::PhysicalInput::Key { + key: chord.physical_key(), mods: chord.modifiers(), pressed, repeat: repeat && pressed, + }), pos: Pos::Rel(0.0, 0.0) }); + } + // Then the modifiers come up, as on a real keyboard, so nothing stays held. + if chord.modifiers() != Mods::default() { + out.push(Ev { t, kind: Kind::Physical(crate::PhysicalInput::Modifiers(Mods::default())), pos: Pos::Rel(0.0, 0.0) }); + } + continue; + } + // `{"modifier": "ShiftRight", "down": true, "mods": "ctrl+shift"}`: one modifier key going + // down or up on its own, with the flags after it (Ctrl+Right Shift's direction chord). + if let Some(name) = e["modifier"].as_str() { + use crate::PhysicalKeyCode as Code; + let key = match name { + "ShiftLeft" => Code::ShiftLeft, + "ShiftRight" => Code::ShiftRight, + "ControlLeft" => Code::ControlLeft, + "ControlRight" => Code::ControlRight, + "AltLeft" => Code::AltLeft, + "AltRight" => Code::AltRight, + other => die(&format!("unknown modifier key {other:?}")), + }; + let mut mods = Mods::default(); + for part in e["mods"].as_str().unwrap_or("").split('+').filter(|p| !p.is_empty()) { + match part { + "shift" => mods.shift = true, + "ctrl" | "control" => { mods.ctrl = true; if !cfg!(target_os = "macos") { mods.cmd = true; } } + "alt" => mods.alt = true, + other => die(&format!("unknown modifier {other:?} in mods")), + } + } + let pressed = e["down"].as_bool().unwrap_or(true); + out.push(Ev { t, kind: Kind::Physical(crate::PhysicalInput::Key { key, mods, pressed, repeat: false }), pos: Pos::Rel(0.0, 0.0) }); + out.push(Ev { t, kind: Kind::Physical(crate::PhysicalInput::Modifiers(mods)), pos: Pos::Rel(0.0, 0.0) }); + continue; + } + // `{"hold": "alt"}` holds modifiers down until `{"hold": ""}` lets them go, as the window + // reports them (`App::on_modifiers`): an Alt-hold reveal. + if let Some(held) = e["hold"].as_str() { + let mut mods = Mods::default(); + for part in held.split('+').filter(|p| !p.is_empty()) { + match part { + "shift" => mods.shift = true, + "ctrl" | "control" => mods.ctrl = true, + "alt" | "option" => mods.alt = true, + "super" | "logo" | "win" => mods.logo = true, + "cmd" => mods.cmd = true, + other => die(&format!("unknown modifier {other:?} in hold")), + } + } + out.push(Ev { t, kind: Kind::Physical(crate::PhysicalInput::Modifiers(mods)), pos: Pos::Rel(0.0, 0.0) }); + continue; + } + if let Some(shortcut) = e["shortcut"].as_str() { + let shortcut = shortcut.parse().unwrap_or_else(|e: crate::ShortcutError| die(&e.to_string())); + out.push(Ev { t, kind: Kind::Shortcut(shortcut), pos: Pos::Rel(0.0, 0.0) }); + continue; + } + if !e["paste"].is_null() { + let paste = if e["paste"].is_string() { serde_json::json!({ "text": e["paste"] }) } else { e["paste"].clone() }; + out.push(Ev { t, kind: Kind::Paste(paste_content(&paste)), pos: Pos::Rel(0.0, 0.0) }); + continue; + } + if parse_files(&e, t, &mut out) { continue; } + if e["type"] == "shortcut" { + let chord = e["chord"].as_str().unwrap_or_else(|| die("a \"shortcut\" event needs a \"chord\", like \"cmd+space\"")); + let chord = chord.parse().unwrap_or_else(|e: crate::ShortcutError| die(&e.to_string())); + out.push(Ev { t, kind: Kind::Shortcut(chord), pos: Pos::Rel(0.0, 0.0) }); + continue; + } + let pos = if let Some(k) = e["key"].as_str() { + Pos::Key(k.to_owned()) + } else if let (Some(x), Some(y)) = (e["x"].as_f64(), e["y"].as_f64()) { + Pos::Xy(x as f32, y as f32) + } else { + Pos::Rel(0.0, 0.0) + }; + let ty = e["type"].as_str().unwrap_or("tap"); + // `"button": "middle"` (or "back", "forward", "secondary") presses with another button. + let button = match e["button"].as_str().unwrap_or("primary") { + "primary" => crate::PointerButton::Primary, + "secondary" => crate::PointerButton::Secondary, + "middle" => crate::PointerButton::Middle, + "back" => crate::PointerButton::Back, + "forward" => crate::PointerButton::Forward, + other => die(&format!("unknown button {other}")), + }; + let (down, up) = match button { + crate::PointerButton::Primary => (Kind::Down, Kind::Up), + crate::PointerButton::Secondary => (Kind::SecondaryDown, Kind::SecondaryUp), + b => (Kind::ButtonDown(b), Kind::ButtonUp(b)), + }; + // A gesture at an element or point moves the pointer there first. + let gesture_at = |out: &mut Vec<Ev>, pos: &Pos| if !matches!(pos, Pos::Rel(..)) { out.push(Ev { t, kind: Kind::Move, pos: pos.clone() }) }; + match ty { + "move" => out.push(Ev { t, kind: Kind::Move, pos }), + "down" => { + out.push(Ev { t, kind: Kind::Move, pos: pos.clone() }); + out.push(Ev { t, kind: down, pos }); + } + "up" => out.push(Ev { t, kind: up, pos }), + "secondary-down" => out.push(Ev { t, kind: Kind::SecondaryDown, pos }), + "secondary-up" => out.push(Ev { t, kind: Kind::SecondaryUp, pos }), + "secondary-click" => { + out.push(Ev { t, kind: Kind::SecondaryDown, pos: pos.clone() }); + out.push(Ev { t: t + e["hold"].as_f64().unwrap_or(0.08), kind: Kind::SecondaryUp, pos }); + } + "tap" | "click" => { + out.push(Ev { t, kind: Kind::Move, pos: pos.clone() }); + out.push(Ev { t, kind: down, pos }); + out.push(Ev { t: t + e["hold"].as_f64().unwrap_or(0.08), kind: up, pos: Pos::Rel(0.0, 0.0) }); + } + "double-click" | "double-tap" | "triple-click" => { + // Two (three) presses `gap` apart (default 0.15 s), inside the default double-click interval. + let hold = e["hold"].as_f64().unwrap_or(0.06); + let gap = e["gap"].as_f64().unwrap_or(0.15).max(hold + 0.01); + let presses = if ty == "triple-click" { 3 } else { 2 }; + for start in (0..presses).map(|k| t + gap * k as f64) { + out.push(Ev { t: start, kind: Kind::Move, pos: pos.clone() }); + out.push(Ev { t: start, kind: Kind::Down, pos: pos.clone() }); + out.push(Ev { t: start + hold, kind: Kind::Up, pos: Pos::Rel(0.0, 0.0) }); + } + } + "drag" => { + let dx = e["dx"].as_f64().unwrap_or(0.0) as f32; + let dy = e["dy"].as_f64().unwrap_or(0.0) as f32; + let dur = e["dur"].as_f64().unwrap_or(0.3).max(0.01); + out.push(Ev { t, kind: Kind::Move, pos: pos.clone() }); + out.push(Ev { t, kind: down, pos }); + let steps = (dur * 120.0).ceil() as usize; + for s in 1..=steps { + let f = s as f32 / steps as f32; + // Ease in-out so the hand starts and stops gently. + let f = f * f * (3.0 - 2.0 * f); + out.push(Ev { + t: t + dur * s as f64 / steps as f64, + kind: Kind::Move, + pos: Pos::Rel(dx * f, dy * f), + }); + } + out.push(Ev { t: t + dur + 0.02, kind: up, pos: Pos::Rel(dx, dy) }); + } + "type" => { + let text = e["text"].as_str().unwrap_or(""); + let every = e["every"].as_f64().unwrap_or(0.035); + for (k, c) in text.chars().enumerate() { + let ev = KeyEvent { key: Key::Text(c.to_string()), mods: Mods::default() }; + out.push(Ev { t: t + every * k as f64, kind: Kind::Key(ev, false), pos: Pos::Rel(0.0, 0.0) }); + } + } + "key" | "key-up" => { + let name = e["name"].as_str().unwrap_or(""); + let mods = script_mods(&e); + let key = if mods.cmd && name.len() == 1 { + Key::Command(name.chars().next().unwrap().to_ascii_lowercase()) + } else { + key_named(name).unwrap_or_else(|| die(&format!("unknown key {name}"))) + }; + let repeat = e["repeat"].as_bool().unwrap_or(false); + // `"code"` names a press's physical key (`"7"` for `⌘⇧7`), with a `Tx::key_base`; it comes back up straight after. + if let Some(code) = e["code"].as_str() { + let code = code.parse::<crate::Shortcut>().unwrap_or_else(|e| die(&e.to_string())).physical_key(); + let base = script_key_base(&e, name, mods); + let press = |pressed| crate::PhysicalInput::Key { key: code, mods, pressed, repeat: repeat && pressed }; + if ty == "key-up" { + out.push(Ev { t, kind: Kind::PhysicalKey(press(false), KeyEvent { key, mods }, base), pos: Pos::Rel(0.0, 0.0) }); + } else { + out.push(Ev { t, kind: Kind::PhysicalKey(press(true), KeyEvent { key, mods }, base), pos: Pos::Rel(0.0, 0.0) }); + out.push(Ev { t, kind: Kind::Physical(press(false)), pos: Pos::Rel(0.0, 0.0) }); + } + continue; + } + let kind = if ty == "key-up" { Kind::KeyUp(KeyEvent { key, mods }) } else { Kind::Key(KeyEvent { key, mods }, repeat) }; + out.push(Ev { t, kind, pos: Pos::Rel(0.0, 0.0) }); + } + "wheel" => { + // One delta, unlike "scroll"'s eased swipe, with modifiers and a phase. + let d = |k: &str| e[k].as_f64().unwrap_or(0.0) as f32; + gesture_at(&mut out, &pos); + let ev = crate::WheelEvent::new(d("dx"), d("dy")).mods(script_mods(&e)).phase(script_phase(&e)) + .precise(e["precise"].as_bool().unwrap_or(true)).notch(e["notch"].as_bool().unwrap_or(false)); + out.push(Ev { t, kind: Kind::WheelEvent(ev), pos }); + } + "magnify" => { + gesture_at(&mut out, &pos); + let ev = crate::MagnifyEvent::new(e["delta"].as_f64().unwrap_or(0.0) as f32).phase(script_phase(&e)); + out.push(Ev { t, kind: Kind::Magnify(ev), pos }); + } + "rotate" => { + gesture_at(&mut out, &pos); + let ev = crate::RotateEvent::new(e["degrees"].as_f64().unwrap_or(0.0) as f32).phase(script_phase(&e)); + out.push(Ev { t, kind: Kind::Rotate(ev), pos }); + } + "smart-magnify" => { + gesture_at(&mut out, &pos); + out.push(Ev { t, kind: Kind::SmartMagnify, pos }); + } + "paste" => out.push(Ev { t, kind: Kind::Paste(paste_content(&e)), pos: Pos::Rel(0.0, 0.0) }), + // What an input method composes (`preedit`, its caret or selection as a byte range in + // `cursor`), commits, or takes back to convert again (`select`, a byte range of the + // field's text), as the platform's IME hands it to the focused field or caret. + "ime" => { + let ime = match (e["commit"].as_str(), e["preedit"].as_str()) { + _ if e["select"].is_array() => { + let at = |i: usize| e["select"][i].as_u64().unwrap_or(0) as usize; + crate::Ime::Select(at(0)..at(1)) + } + (Some(text), _) => crate::Ime::Commit(text.to_owned()), + (None, Some(text)) => { + let at = |i: usize| e["cursor"][i].as_u64().map(|n| n as usize); + // `clauses`: `[[start, end], [start, end, true]]`, byte ranges, `true` for the one being converted. + let clauses = e["clauses"].as_array().into_iter().flatten().filter_map(|c| { + let (a, b) = (c[0].as_u64()? as usize, c[1].as_u64()? as usize); + let clause = crate::Clause::new(a..b); + Some(if c[2].as_bool() == Some(true) { clause.target() } else { clause }) + }).collect(); + crate::Ime::Preedit(text.to_owned(), at(0).zip(at(1)), clauses) + } + (None, None) => die("an ime event needs a \"commit\", a \"preedit\" (\"\" ends a composition) or a \"select\""), + }; + out.push(Ev { t, kind: Kind::Ime(ime), pos: Pos::Rel(0.0, 0.0) }); + } + "scroll" => eased_input::swipe(&mut out, &e, t, pos), + "resize" => eased_input::resize(&mut out, &e, t), + "fling" => { + let v = |k: &str| e[k].as_f64().unwrap_or(0.0) as f32; + out.push(Ev { t, kind: Kind::Fling(v("vx"), v("v")), pos }); + } + "menu-pick" => { + let id = e["id"].as_str().unwrap_or_else(|| die("menu-pick needs an \"id\"")); + out.push(Ev { t, kind: Kind::PopupMenu(Some(id.into())), pos: Pos::Rel(0.0, 0.0) }); + } + "menu-cancel" => out.push(Ev { t, kind: Kind::PopupMenu(None), pos: Pos::Rel(0.0, 0.0) }), + "file-dialog" => { + let path = e["path"].as_str().unwrap_or_else(|| die("file-dialog needs a \"path\" (file-dialog-cancel cancels)")); + out.push(Ev { t, kind: Kind::FileDialog(Some(path.into())), pos: Pos::Rel(0.0, 0.0) }); + } + "file-dialog-cancel" => out.push(Ev { t, kind: Kind::FileDialog(None), pos: Pos::Rel(0.0, 0.0) }), + "mark" => { + let name = e["name"].as_str().filter(|n| !n.is_empty()).unwrap_or_else(|| die("a mark needs a \"name\"")); + out.push(Ev { t, kind: Kind::Mark(name.to_owned()), pos }); + } + other => die(&format!("unknown event type {other}")), + } + } + out.sort_by(|a, b| a.t.total_cmp(&b.t)); + out +} + +/// `{"drag_files": {"paths": […], "at": [x, y]}}` (or `"key": …` for an element's centre) moves a +/// file drag from another app over the window; `{"drag_files": "leave"}` takes it away. +/// `{"drop_files": {…, "hover": s}}` drags the files there for `s` seconds (default 0), then +/// drops them. Whether `e` was one. +pub(crate) fn parse_files(e: &Value, t: f64, out: &mut Vec<Ev>) -> bool { + let (spec, drop) = match (e.get("drag_files"), e.get("drop_files")) { + (Some(spec), _) => (spec, false), + (None, Some(spec)) => (spec, true), + (None, None) => return false, + }; + if !drop && spec == "leave" { + out.push(Ev { t, kind: Kind::Files(FileStep::Leave), pos: Pos::Rel(0.0, 0.0) }); + return true; + } + let name = if drop { "drop_files" } else { "drag_files" }; + let paths: Vec<std::path::PathBuf> = spec["paths"].as_array() + .unwrap_or_else(|| die(&format!("{name} needs \"paths\": [\"a file\", …]"))) + .iter().map(|p| p.as_str().unwrap_or_else(|| die(&format!("{name}: paths are strings"))).into()).collect(); + let pos = match (spec["at"].as_array(), spec["key"].as_str()) { + (Some(at), _) if at.len() == 2 && at.iter().all(Value::is_number) => + Pos::Xy(at[0].as_f64().unwrap_or(0.0) as f32, at[1].as_f64().unwrap_or(0.0) as f32), + (None, Some(key)) => Pos::Key(key.to_owned()), + _ => die(&format!("{name} needs \"at\": [x, y] or \"key\"")), + }; + out.push(Ev { t, kind: Kind::Files(FileStep::Hover(paths.clone())), pos: pos.clone() }); + if drop { + let hover = spec["hover"].as_f64().unwrap_or(0.0).max(0.0); + out.push(Ev { t: t + hover, kind: Kind::Files(FileStep::Drop(paths)), pos }); + } + true +} diff --git a/app/vendor/rune/crates/rune/src/tooling/strip.rs b/app/vendor/rune/crates/rune/src/tooling/strip.rs new file mode 100644 index 0000000..2c33175 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/tooling/strip.rs @@ -0,0 +1,51 @@ +//! `--strip`: frames, or their `--crop` rects, tiled into one image. + +use super::*; + +/// Tiles `--strip`'s frames, `cols` to a row, into one PNG. +pub(crate) fn write_strip(p: &std::path::Path, strip: &[Vec<u8>], (wp, hp): (u32, u32), crops_px: &[[u32; 4]], gap: u32, cols: usize) { + if strip.is_empty() { return; } + let (cw, ch) = tile_size(wp, hp, crops_px, gap); + let cols = strip.len().min(cols) as u32; + let rows = (strip.len() as u32).div_ceil(cols); + let (sw, sh) = (cols * cw + (cols - 1) * gap, rows * ch + (rows - 1) * gap); + let mut img: Vec<u8> = [128, 128, 128, 255].repeat((sw * sh) as usize); + for (i, f) in strip.iter().enumerate() { + let (cx, cy) = ((i as u32 % cols) * (cw + gap), (i as u32 / cols) * (ch + gap)); + for y in 0..ch { + let dst = (((cy + y) * sw + cx) * 4) as usize; + let src = (y * cw * 4) as usize; + img[dst..dst + (cw * 4) as usize].copy_from_slice(&f[src..src + (cw * 4) as usize]); + } + } + write_png(p, sw, sh, &img).unwrap_or_else(|e| die(&format!("{}: {e}", p.display()))); +} + +pub(crate) fn tile_size(w: u32, h: u32, crops: &[[u32; 4]], gap: u32) -> (u32, u32) { + if crops.is_empty() { + return (w, h); + } + let cw = crops.iter().map(|c| c[2]).max().unwrap_or(w); + let ch = crops.iter().map(|c| c[3]).sum::<u32>() + gap * (crops.len() as u32 - 1); + (cw, ch) +} + +/// The crops of one frame stacked vertically (the whole frame when there are none). +pub(crate) fn tile(px: &[u8], w: u32, h: u32, crops: &[[u32; 4]], gap: u32) -> Vec<u8> { + if crops.is_empty() { + return px.to_vec(); + } + let (tw, th) = tile_size(w, h, crops, gap); + let mut out: Vec<u8> = [128, 128, 128, 255].repeat((tw * th) as usize); + let mut oy = 0; + for &[x, y, cw, ch] in crops { + assert!(x + cw <= w && y + ch <= h, "--crop outside the frame"); + for row in 0..ch { + let s = (((y + row) * w + x) * 4) as usize; + let d = (((oy + row) * tw) * 4) as usize; + out[d..d + (cw * 4) as usize].copy_from_slice(&px[s..s + (cw * 4) as usize]); + } + oy += ch + gap; + } + out +} diff --git a/app/vendor/rune/crates/rune/src/tooling/test_alloc.rs b/app/vendor/rune/crates/rune/src/tooling/test_alloc.rs new file mode 100644 index 0000000..fd715cd --- /dev/null +++ b/app/vendor/rune/crates/rune/src/tooling/test_alloc.rs @@ -0,0 +1,54 @@ +//! The lib test binary's allocator: the system one, counting this thread's allocations and +//! its live and peak bytes, so a test can assert what a call allocates. + +#![allow(unsafe_code)] + +use std::alloc::{GlobalAlloc, Layout, System}; +use std::cell::Cell; + +struct Counting; +thread_local! { + static ALLOCS: Cell<usize> = const { Cell::new(0) }; + static LIVE: Cell<isize> = const { Cell::new(0) }; + static PEAK: Cell<isize> = const { Cell::new(0) }; +} +fn track(allocs: usize, bytes: isize) { + ALLOCS.try_with(|c| c.set(c.get() + allocs)).ok(); + LIVE.try_with(|live| { + live.set(live.get() + bytes); + PEAK.try_with(|peak| peak.set(peak.get().max(live.get()))).ok(); + }).ok(); +} +// SAFETY: forwards to the system allocator, counting calls and bytes on this thread. +unsafe impl GlobalAlloc for Counting { + unsafe fn alloc(&self, l: Layout) -> *mut u8 { + track(1, l.size() as isize); + // SAFETY: caller upholds `GlobalAlloc::alloc` preconditions (`l` has non-zero size). + unsafe { System.alloc(l) } + } + unsafe fn dealloc(&self, p: *mut u8, l: Layout) { + track(0, -(l.size() as isize)); + // SAFETY: caller upholds `GlobalAlloc::dealloc` preconditions (`p` came from `alloc` with `l`). + unsafe { System.dealloc(p, l) } + } + unsafe fn realloc(&self, p: *mut u8, l: Layout, n: usize) -> *mut u8 { + track(1, n as isize - l.size() as isize); + // SAFETY: caller upholds `GlobalAlloc::realloc` preconditions (`p`/`l` live, `n` non-zero). + unsafe { System.realloc(p, l, n) } + } +} +#[global_allocator] +static COUNTING: Counting = Counting; + +/// Allocations made on this thread so far. +pub(crate) fn allocs() -> usize { ALLOCS.with(Cell::get) } + +/// Runs `f`, returning its result and the most bytes it held allocated at once on this thread +/// beyond what was live when it started. +#[allow(dead_code)] +pub(crate) fn peak<T>(f: impl FnOnce() -> T) -> (T, usize) { + let start = LIVE.with(Cell::get); + PEAK.with(|p| p.set(start)); + let out = f(); + (out, (PEAK.with(Cell::get) - start).max(0) as usize) +} diff --git a/app/vendor/rune/crates/rune/src/tooling/tests.rs b/app/vendor/rune/crates/rune/src/tooling/tests.rs new file mode 100644 index 0000000..e022259 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/tooling/tests.rs @@ -0,0 +1,977 @@ +use super::*; + +#[test] +fn trace_annotations_from_hidden_poll_survive_idle_catch_up_once() { + let mut rt = Runtime::new(false, |_, _: &mut Cx<bool>| crate::el(), (100.0, 100.0), Env::default()); + let (trace, buffer) = rune_motion::MotionTrace::in_memory(&rune_motion::TraceHeader { + launch: "hidden".into(), width: 100.0, height: 100.0, hz: 60.0, scale: 1.0, + }); + rt.scene.set_trace(Some(trace)); + rt.frame.enable_trace_channels(true); + rt.poll = Some(|pending, _, tx| { + if !std::mem::take(pending) { return false; } + tx.trace_event("hidden:ready"); + tx.trace_channel("shell.width", "position", 40.0); + true + }); + rt.frame(0.0); + rt.state = true; + let commits = rt.stats.commits; + rt.poll_hidden(); + assert_eq!(rt.stats.commits, commits, "hidden polling must not lay out or render"); + rt.frame_split(1.0, 0.0); + rt.frame(0.02); + assert_eq!(rt.events, ["hidden:ready"]); + assert_eq!(rt.frame.trace_channels().unwrap()["shell.width"], ("position", 40.0)); + rt.scene.take_trace().unwrap().flush().unwrap(); + let lines: Vec<Value> = buffer.contents().lines().map(|s| serde_json::from_str(s).unwrap()).collect(); + assert_eq!(lines.iter().filter(|line| line["ev"] == json!(["hidden:ready"])).count(), 1); +} + +#[test] +fn trace_annotations_reach_both_writers_once() { + fn view(changed: &bool, _: &mut Cx<bool>) -> El { + let (class, host) = if *changed { ("other", "other-host") } else { ("gpui", "pill") }; + crate::el().key("root").trace_namespace(class, host) + .child(crate::el().key("generation-7").trace_name("chip:Area").size(30.0, 20.0)) + .child(crate::el().key("fixed").trace_name("fixed").trace_namespace("gpui", "pill")) + } + let mut rt = Runtime::new(false, view, (100.0, 100.0), Env { scale: 1.0, system_dark: true }); + let (trace, buffer) = rune_motion::MotionTrace::in_memory(&rune_motion::TraceHeader { + launch: "pill".into(), width: 100.0, height: 100.0, hz: 60.0, scale: 1.0, + }); + rt.scene.set_trace(Some(trace)); + rt.frame.enable_trace_channels(true); + let path = std::env::temp_dir().join(format!("rune-annotations-{}.jsonl", std::process::id())); + { + let mut trace = Trace::open(&path, rt.viewport, 60.0, 1.0); + rt.update(|_, tx| { + assert!(tx.tracing()); + tx.trace_event(format_args!("lab:{}", "Start")); + tx.trace_channel("shell.width", "position", 30.0); + }); + // A second transaction before the frame must retain the first event. + rt.update(|_, tx| { + tx.trace_event("lab:Ready"); + tx.trace_channel("shell.width", "position", 40.0); + }); + rt.frame(0.0); + trace.frame(&mut rt, 0.0, 0.0); + rt.frame(0.02); + trace.frame(&mut rt, 20.0, 0.0); + rt.update(|s, _| *s = true); + rt.frame(0.02); + trace.frame(&mut rt, 40.0, 0.0); + } + rt.scene.take_trace().unwrap().flush().unwrap(); + let tooling = std::fs::read_to_string(&path).unwrap(); + std::fs::remove_file(path).unwrap(); + for text in [tooling, buffer.contents()] { + let lines: Vec<Value> = text.lines().map(|s| serde_json::from_str(s).unwrap()).collect(); + let chip = lines[1]["m"].as_array().unwrap().iter().find(|m| m["nm"] == "chip:Area").unwrap(); + assert_eq!(chip["cls"], "gpui"); + assert_eq!(chip["host"], "pill"); + assert_eq!(lines[1]["ev"], json!(["lab:Start", "lab:Ready"])); + let channel = lines[1]["cm"].as_array().unwrap().iter().find(|m| m["name"] == "shell.width").unwrap(); + assert_eq!(channel["kind"], "position"); + assert!(lines[1]["c"].as_array().unwrap().iter().any(|c| c[0] == channel["id"] && c[1].as_f64() == Some(40.0))); + for field in ["cm", "c", "ev"] { assert!(lines[2][field].is_null(), "duplicate {field}"); } + let updated = lines[3]["m"].as_array().unwrap(); + let renamed = updated.iter().find(|m| m["nm"] == "chip:Area").unwrap(); + assert_eq!(renamed["id"], chip["id"]); + assert_eq!(renamed["cls"], "other"); + assert_eq!(renamed["host"], "other-host"); + assert!(!updated.iter().any(|m| m["nm"] == "fixed"), "descendant override must survive parent namespace changes"); + } +} + +#[test] +fn native_traces_add_target_and_present_times_without_changing_other_fields() { + struct Presents(std::sync::Mutex<Vec<crate::frame::present_time::Presented>>); + impl crate::frame::present_time::Source for Presents { + fn take(&self, out: &mut Vec<crate::frame::present_time::Presented>) { out.append(&mut self.0.lock().unwrap()); } + } + let view = |_: &bool, _: &mut Cx<bool>| crate::el().key("box").size(20.0, 20.0); + let run = |name: &str, timed: bool| { + let mut rt = Runtime::new(false, view, (100.0, 100.0), Env { scale: 1.0, system_dark: true }); + let path = std::env::temp_dir().join(format!("rune-present-{name}-{}.jsonl", std::process::id())); + let start = crate::time::now(); + let source = std::sync::Arc::new(Presents(Default::default())); + { + let mut trace = Trace::open_clock(&path, rt.viewport, 120.0, 1.0, "wall"); + if timed { trace.record_presents(source.clone(), start); } + for k in 0..3u64 { + rt.frame(1.0 / 120.0); + let timing = FrameTiming { target_ms: timed.then_some(k as f64 * 8.333), drawable: timed.then_some(k + 1), continuous: k > 0 }; + trace.frame_timed(&mut rt, k as f64 * 8.0, 0.0, timing); + let at = start + std::time::Duration::from_micros(20_000 + k * 8_333); + source.0.lock().unwrap().push((k + 1, Some(at))); + } + } + let text = std::fs::read_to_string(&path).unwrap(); + std::fs::remove_file(path).unwrap(); + text + }; + let plain = run("plain", false); + let timed = run("timed", true); + let strip = |text: &str| -> Vec<Value> { + text.lines().map(|l| { + let mut v: Value = serde_json::from_str(l).unwrap(); + for key in ["target_ms", "present_ms", "present_dt_ms"] { v.as_object_mut().unwrap().remove(key); } + if let Some(q) = v.get_mut("quality") { q["cpu_ms"] = 0.into(); } + v + }).collect() + }; + assert_eq!(strip(&plain), strip(&timed), "present timing only adds fields"); + assert!(!plain.contains("present_ms") && !plain.contains("target_ms"), "untimed frames keep the old format"); + let frames: Vec<Value> = timed.lines().skip(1).map(|l| serde_json::from_str(l).unwrap()).collect(); + assert_eq!(frames.len(), 3, "every held line is written when the trace ends"); + assert_eq!(frames[1]["target_ms"], 8.333); + assert_eq!(frames[1]["present_ms"], 28.333); + assert_eq!(frames[1]["present_dt_ms"], 8.333); + let summary = crate::frame::present_time::Summary::of_trace(&timed).unwrap(); + assert_eq!((summary.frames, summary.presented, summary.bunched, summary.missed), (3, 3, 0, 0)); + assert!(crate::frame::present_time::Summary::of_trace(&plain).is_none()); +} + +#[test] +fn marks_are_inert_events_that_times_can_name() { + let script = parse_script(json!([ + {"t": 0.5, "type": "tap", "x": 1, "y": 1}, + {"t": 3.2, "type": "mark", "name": "end"}, + {"t": 1.0, "type": "mark", "name": "end-card"}, + ])); + let marks: Vec<_> = script.iter().filter_map(|e| match &e.kind { Kind::Mark(n) => Some((n.as_str(), e.t)), _ => None }).collect(); + assert_eq!(marks, [("end-card", 1.0), ("end", 3.2)]); + assert!(matches!(script[4].public().event, ScriptEvent::Mark(ref n) if n == "end")); + + assert_eq!(mark_time("mark:end"), Some("end".into())); + assert_eq!(mark_time("mark:end+0.5"), Some("end+0.5".into())); + assert_eq!(mark_time("1.5"), None); + + let args = |v: &[&str]| Args::parse_from(v.iter().map(|s| (*s).into()).collect()); + let timeline = |v: &[&str]| Timeline::of(&args(v), &script); + let snap = timeline(&["--snap", "a.png", "--at", "mark:end+0.5"]).unwrap(); + assert_eq!((snap.snap_frame, snap.frames), (222, 0)); + let video = timeline(&["--video", "a.mp4", "--start", "mark:end-card"]).unwrap(); + assert_eq!((video.start_frame, video.frames, video.last_frame), (60, 133, 192), "auto runs to the end mark"); + let auto = timeline(&["--frames", "1", "--duration", "auto"]).unwrap(); + assert_eq!(auto.frames, 1, "--frames wins over --duration"); + let seconds = timeline(&["--video", "a.mp4", "--duration", "2", "--fps", "30"]).unwrap(); + assert_eq!((seconds.frames, seconds.last_frame), (60, 59)); + let err = timeline(&["--snap", "a.png", "--at", "mark:intro"]).unwrap_err(); + assert_eq!(err, "no mark \"intro\" in the script (marks: end-card, end)"); + let unmarked = Timeline::of(&args(&["--video", "a.mp4"]), &parse_script(json!([{"t": 0.5, "type": "tap", "x": 1, "y": 1}]))).unwrap(); + assert_eq!(unmarked.frames, 96, "without an end mark, one second after the last event (the tap's release at 0.58 s)"); +} + +/// Headless runs publish the process's `headless_run`, so tests that render one take turns. +pub(super) static HEADLESS: std::sync::Mutex<()> = std::sync::Mutex::new(()); + +#[test] +fn mark_names_win_over_offsets_and_offsets_must_be_complete() { + let script = parse_script(json!([ + {"t": 2.0, "type": "mark", "name": "step-1"}, + {"t": 4.0, "type": "mark", "name": "end-card"}, + {"t": 6.0, "type": "mark", "name": "end+0.5"}, + {"t": 8.0, "type": "mark", "name": "step"}, + {"t": 10.0, "type": "mark", "name": "end"}, + ])); + let resolve = |flag: &str, value: &str| { + let args = Args::parse_from(["--snap", "a.png", "--fps", "1000", flag, value].map(String::from).into()); + Timeline::of(&args, &script) + }; + for (value, frame) in [("mark:step-1", 2000), ("mark:step-1+0.25", 2250), + ("mark:step-1-0.5", 1500), ("mark:end+0.5", 6000), ("mark:end-card-0.25", 3750), + ("mark:end-1e-3", 9999), ("mark:end+1e-3", 10001)] { + assert_eq!(resolve("--at", value).unwrap().snap_frame, frame, "{value}"); + assert_eq!(resolve("--start", value).unwrap().start_frame, frame, "{value}"); + } + for value in ["mark:end+0.5s", "mark:end-", "mark:end+NaN", "mark:end+inf", "mark:end+1e999"] { + let error = resolve("--at", value).unwrap_err(); + assert!(error.contains("invalid mark time") && error.contains("marks: step-1, end-card, end+0.5, step, end"), "{error}"); + } + let args = Args::parse_from(["--at", "mark:end", "--at", "1", "--start", "mark:step", "--start", "0"].map(String::from).into()); + let timeline = Timeline::of(&args, &script).unwrap(); + assert_eq!((timeline.snap_frame, timeline.start_frame), (60, 0), "the last flag wins"); +} + +#[test] +fn duration_and_out_select_headless_png_output_unless_native() { + let _turn = HEADLESS.lock().unwrap_or_else(|e| e.into_inner()); + let args = |v: &[&str]| Args::parse_from(v.iter().map(|s| (*s).into()).collect()); + for flags in [vec!["--out", "frames"], vec!["--duration", "auto"], vec!["--duration", "auto", "--out", "frames"]] { + assert!(args(&flags).headless()); + let mut native = flags; + native.push("--native"); + assert!(!args(&native).headless()); + } + let dir = std::env::temp_dir().join(format!("rune-duration-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let script = dir.join("script.json"); + std::fs::write(&script, r#"[{"t": 0.1, "type": "mark", "name": "end"}]"#).unwrap(); + let spec = || AppSpec::new("duration", (8.0, 8.0), || (), |_, _| crate::el()); + for automatic in [false, true] { + let out = dir.join(if automatic { "explicit" } else { "default" }); + let mut flags = vec!["--script", script.to_str().unwrap(), "--out", out.to_str().unwrap(), "--fps", "30", "--scale", "1"]; + if automatic { flags.extend(["--duration", "auto"]); } + let args = args(&flags); + assert!(args.headless()); + headless(crate::App::new(spec()), args); + let mut files: Vec<_> = std::fs::read_dir(out).unwrap().map(|e| e.unwrap().file_name()).collect(); + files.sort(); + assert_eq!(files, ["frame_0000.png", "frame_0001.png", "frame_0002.png", "frame_0003.png"]); + } + std::fs::remove_dir_all(dir).unwrap(); +} + +#[test] +fn headless_runs_report_each_frame_to_on_frame_encoded() { + let _turn = HEADLESS.lock().unwrap_or_else(|e| e.into_inner()); + let snap = std::env::temp_dir().join(format!("rune-encoded-{}.png", std::process::id())); + let seen = std::rc::Rc::new(std::cell::RefCell::new(Vec::new())); + let log = seen.clone(); + let app = crate::App::new(AppSpec::new("encoded", (8.0, 8.0), || (), |_, _| crate::el())).on_frame_encoded(move |f| { + log.borrow_mut().push((f.seq(), f.outcome(), f.window().map(str::to_owned), f.refresh_hz(), f.started().is_some(), f.update_ms(), f.encode_ms())); + }); + headless(app, Args { snap: Some(snap.clone()), at: Some(0.1), fps: 30.0, scale: Some(1.0), ..Default::default() }); + std::fs::remove_file(snap).unwrap(); + let seen = seen.borrow(); + assert_eq!(seen.len(), 4, "frames 0 to 3 at 30 fps: {seen:?}"); + for (i, (seq, outcome, window, hz, started, update, encode)) in seen.iter().enumerate() { + assert_eq!((*seq, *outcome, window.as_deref(), *hz, *started), (i as u64, crate::FrameOutcome::Drawn, Some("main"), Some(30.0), true)); + assert!(update.is_some_and(|ms| ms >= 0.0) && encode.is_some_and(|ms| ms >= 0.0)); + } +} + +#[test] +fn single_window_snapshots_honor_transparency_and_physical_size() { + let _turn = HEADLESS.lock().unwrap_or_else(|e| e.into_inner()); + let dir = std::env::temp_dir().join(format!("rune-window-options-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let render = |name: &str, options: crate::WindowOptions, size: Option<(f32, f32)>, legacy: bool| { + let spec = AppSpec::new("options", (20.0, 12.0), || (), |_, _| crate::el().w_full().h_full() + .child(crate::el().absolute(2.0, 2.0).size(8.0, 8.0).fill(crate::oklcha(0.6, 0.2, 30.0, 0.5)))); + let app = crate::App::new(spec).window_options(options); + let snap = dir.join(format!("{name}.png")); + let args = Args { snap: Some(snap.clone()), scale: Some(2.0), size, ..Default::default() }; + if legacy { headless_configured(app, args, false); } else { headless(app, args); } + (std::fs::read(&snap).unwrap(), image::open(snap).unwrap().into_rgba8()) + }; + let plain = render("plain", crate::WindowOptions::default(), None, false); + let legacy = render("legacy", crate::WindowOptions::default(), None, true); + assert_eq!(plain.0, legacy.0, "default windows retain byte-identical PNG output"); + assert_eq!(plain.1.dimensions(), (40, 24)); + assert!(plain.1.pixels().all(|p| p[3] == 255)); + let options = crate::WindowOptions { transparent: true, physical_size: Some((80, 60)), ..Default::default() }; + let transparent = render("transparent", options.clone(), None, false).1; + assert_eq!(transparent.dimensions(), (80, 60)); + assert_eq!(transparent.get_pixel(0, 0)[3], 0); + assert!((127..=128).contains(&transparent.get_pixel(8, 8)[3])); + let overridden = render("override", options, Some((16.0, 10.0)), false).1; + assert_eq!(overridden.dimensions(), (32, 20), "--size overrides the physical-size option"); + std::fs::remove_dir_all(dir).unwrap(); +} + +#[test] +fn window_resizes_move_the_headless_viewport_on_the_virtual_clock() { + let _turn = HEADLESS.lock().unwrap_or_else(|e| e.into_inner()); + let dir = std::env::temp_dir().join(format!("rune-window-resize-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let script = dir.join("script.json"); + std::fs::write(&script, r#"[{"t": 0.1, "type": "tap", "key": "grow"}]"#).unwrap(); + let viewport = |name: &str, instant: bool, at: &str| { + let spec = AppSpec::new("resize", (300.0, 400.0), || false, |_, _| crate::el().key("root").w_full().h_full() + .child(crate::el().key("grow").size(50.0, 50.0).on_press_tx(|instant: &mut bool, tx| { + if *instant { tx.resize_window_instant((300.0, 600.0)) } else { tx.resize_window((300.0, 600.0)) } + }))); + let tree = dir.join(format!("{name}.json")); + let args = ["--script", script.to_str().unwrap(), "--scale", "1", "--fps", "60", "--at", at, "--tree", tree.to_str().unwrap()]; + headless(crate::App::new(spec).init(move || instant), Args::parse_from(args.map(String::from).into())); + let tree: Value = serde_json::from_str(&std::fs::read_to_string(tree).unwrap()).unwrap(); + let size = tree["viewport"].as_array().unwrap().iter().map(|v| v.as_f64().unwrap()).collect::<Vec<_>>(); + (size[0], size[1]) + }; + assert_eq!(viewport("before", false, "0.1"), (300.0, 400.0)); + // The press lands with the release at 0.18 s, on frame 11; as on macOS, frame 12 moves. + assert_eq!(viewport("released", false, "0.1834"), (300.0, 400.0)); + let (_, first) = viewport("first", false, "0.2"); + assert!(first > 400.0, "moves the frame after the press: {first}"); + let (w, h) = viewport("moving", false, "0.3"); + assert!(w == 300.0 && h > 400.0 && h < 600.0, "mid-spring at 0.3 s: {h}"); + assert_eq!(viewport("moving-again", false, "0.3"), (w, h), "the virtual clock is deterministic"); + assert_eq!(viewport("landed", false, "2"), (300.0, 600.0)); + assert_eq!(viewport("instant", true, "0.3"), (300.0, 600.0)); + std::fs::remove_dir_all(dir).unwrap(); +} + +#[test] +fn a_scripted_resize_steps_the_viewport_with_the_hand() { + let _turn = HEADLESS.lock().unwrap_or_else(|e| e.into_inner()); + let dir = std::env::temp_dir().join(format!("rune-script-resize-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let script = dir.join("script.json"); + std::fs::write(&script, r#"[{"t": 0.1, "type": "resize", "dw": -100, "dh": -40, "dur": 0.5}]"#).unwrap(); + let viewport = |at: &str| { + let spec = AppSpec::new("resize", (300.0, 400.0), || (), |_, _| crate::el().key("root").w_full().h_full()); + let tree = dir.join(format!("{at}.json")); + let args = ["--script", script.to_str().unwrap(), "--scale", "1", "--fps", "60", "--at", at, "--tree", tree.to_str().unwrap()]; + headless(crate::App::new(spec), Args::parse_from(args.map(String::from).into())); + let tree: Value = serde_json::from_str(&std::fs::read_to_string(tree).unwrap()).unwrap(); + let size = tree["viewport"].as_array().unwrap().iter().map(|v| v.as_f64().unwrap()).collect::<Vec<_>>(); + (size[0], size[1]) + }; + assert_eq!(viewport("0.05"), (300.0, 400.0)); + let (w, h) = viewport("0.35"); + assert!(w < 300.0 && w > 200.0 && h < 400.0 && h > 360.0, "mid-resize: {w}x{h}"); + assert_eq!(viewport("1"), (200.0, 360.0)); + std::fs::remove_dir_all(dir).unwrap(); +} + +#[test] +fn fit_content_height_follows_the_content() { + let _turn = HEADLESS.lock().unwrap_or_else(|e| e.into_inner()); + let dir = std::env::temp_dir().join(format!("rune-fit-content-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let script = dir.join("script.json"); + std::fs::write(&script, r#"[{"t": 0.1, "type": "tap", "key": "more"}]"#).unwrap(); + let viewport = |name: &str, at: &str| { + let spec = AppSpec::new("fit", (300.0, 400.0), || 1usize, |rows, _| crate::col().key("root").w_full() + .child(crate::el().key("more").size(50.0, 50.0).on_press(|rows: &mut usize| *rows += 1)) + .children((0..*rows).map(|i| crate::el().key(format!("row{i}")).size(100.0, 40.0)))); + let tree = dir.join(format!("{name}.json")); + let args = ["--script", script.to_str().unwrap(), "--scale", "2", "--fps", "60", "--at", at, "--tree", tree.to_str().unwrap()]; + headless(crate::App::new(spec).fit_content_height(), Args::parse_from(args.map(String::from).into())); + let tree: Value = serde_json::from_str(&std::fs::read_to_string(tree).unwrap()).unwrap(); + let size = tree["viewport"].as_array().unwrap().iter().map(|v| v.as_f64().unwrap()).collect::<Vec<_>>(); + (size[0], size[1]) + }; + assert_eq!(viewport("open", "0"), (300.0, 90.0), "opens at the content's height"); + let (_, h) = viewport("moving", "0.3"); + assert!(h > 90.0 && h < 130.0, "follows on the change's spring: {h}"); + assert_eq!(viewport("landed", "2"), (300.0, 130.0)); + std::fs::remove_dir_all(dir).unwrap(); +} + +#[test] +fn snapshots_leave_the_playground_out_unless_asked() { + let _turn = HEADLESS.lock().unwrap_or_else(|e| e.into_inner()); + let dir = std::env::temp_dir().join(format!("rune-playground-snap-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + fn view(n: &u32, _: &mut Cx<u32>) -> crate::El { + crate::col().w_full().h_full().padding(8.0).child(crate::text(format!("count {n}"))) + } + let render = |name: &str, playground: bool, open: Option<Option<String>>| { + let spec = AppSpec::new("snap", (240.0, 160.0), || 3, view); + let mut app = crate::App::new(spec); + if playground { app = app.playground(crate::Playground::new().enabled(true).bar(true)); } + let snap = dir.join(format!("{name}.png")); + headless(app, Args { snap: Some(snap.clone()), scale: Some(2.0), playground: open, ..Default::default() }); + std::fs::read(&snap).unwrap() + }; + let plain = render("plain", false, None); + assert!(plain == render("with", true, None), "a playground with a bar snapshots as the app alone"); + assert!(plain != render("open", true, Some(None)), "--playground shows it"); + std::fs::remove_dir_all(dir).unwrap(); +} + +#[test] +fn apps_read_the_headless_run_from_init() { + let _turn = HEADLESS.lock().unwrap_or_else(|e| e.into_inner()); + let dir = std::env::temp_dir().join(format!("rune-run-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let script = dir.join("script.json"); + std::fs::write(&script, r#"[{"t": 0.5, "type": "tap", "x": 4, "y": 5}, {"t": 0.25, "type": "type", "text": "hi", "every": 0.1}]"#).unwrap(); + fn init() -> usize { + let run = headless_run().expect("published before init"); + assert_eq!((run.size(), run.scale(), run.fps()), ((37.0, 23.0), 1.0, 30.0)); + run.events().len() + } + let spec = AppSpec::new("run", (37.0, 23.0), init, |_, _| crate::el()); + let tree = dir.join("tree.json"); + let args = ["--script", script.to_str().unwrap(), "--scale", "1", "--fps", "30", "--tree", tree.to_str().unwrap()]; + headless(crate::App::new(spec), Args::parse_from(args.map(String::from).into())); + let run = headless_run().unwrap(); + std::fs::remove_dir_all(&dir).unwrap(); + assert_eq!(run.script(), Some(script.as_path())); + let summary: Vec<String> = run.events().iter().map(|e| match &e.event { + ScriptEvent::Key { key: KeyEvent { key: Key::Text(c), .. }, repeat: false } => format!("{} key {c}", e.t), + ScriptEvent::Pointer { action, at } => format!("{} {action:?} {at:?}", e.t), + other => panic!("unexpected {other:?}"), + }).collect(); + assert_eq!(summary, ["0.25 key h", "0.35 key i", "0.5 Move At(4.0, 5.0)", "0.5 Down At(4.0, 5.0)", "0.58 Up FromDown(0.0, 0.0)"]); + assert_eq!((run.script_end(), run.frames(), run.start()), (0.58, 0, 0.0)); + // A tree is taken one second after the script, at the nearest frame. + assert!((run.end() - 47.0 / 30.0).abs() < 1e-9, "{}", run.end()); +} + +#[test] +fn video_streams_every_frame_into_ffmpeg() { + let _turn = HEADLESS.lock().unwrap_or_else(|e| e.into_inner()); + if std::process::Command::new("ffprobe").arg("-version").output().is_err() { + eprintln!("skipped: ffmpeg and ffprobe aren't installed"); + return; + } + let dir = std::env::temp_dir().join(format!("rune-video-{}", std::process::id())); + for (extension, codec, width) in [("mp4", "h264", 32), ("mov", "prores", 31), ("webm", "vp9", 32)] { + let path = dir.join(format!("tiny.{extension}")); + let out = dir.join(format!("{extension}-frames")); + let snap = dir.join(format!("{extension}-last.png")); + let spec = AppSpec::new("video", (31.0, 20.0), || (), |_, _| crate::el().w_full().h_full() + .child(crate::el().absolute(0.0, 0.0).size(10.0, 10.0).fill(crate::oklch(0.6, 0.2, 30.0)))); + let args = ["--video", path.to_str().unwrap(), "--frames", "12", "--scale", "1", "--fps", "30", + "--out", out.to_str().unwrap(), "--every", "3", "--snap", snap.to_str().unwrap(), "--at", "0.3"]; + let app = crate::App::new(spec).window_options(crate::WindowOptions { + transparent: extension == "mov", ..Default::default() + }); + headless(app, Args::parse_from(args.map(String::from).into())); + let probe = std::process::Command::new("ffprobe") + .args(["-v", "error", "-count_frames", "-select_streams", "v:0", + "-show_entries", "stream=codec_name,width,height,nb_read_frames,r_frame_rate", "-of", "json"]) + .arg(&path).output().unwrap(); + assert!(probe.status.success(), "{}", String::from_utf8_lossy(&probe.stderr)); + let probe: Value = serde_json::from_slice(&probe.stdout).unwrap(); + let stream = &probe["streams"][0]; + assert_eq!(stream["codec_name"], codec); + assert_eq!(stream["width"], width, "420 formats pad odd sizes; ProRes does not"); + assert_eq!(stream["height"], 20); + assert_eq!(stream["r_frame_rate"], "30/1"); + assert_eq!(stream["nb_read_frames"], "12", "--every must not sample video"); + if extension == "mov" { + let decoded = std::process::Command::new("ffmpeg") + .args(["-v", "error", "-i"]).arg(&path) + .args(["-frames:v", "1", "-f", "rawvideo", "-pix_fmt", "rgba", "-"]).output().unwrap(); + assert!(decoded.status.success(), "{}", String::from_utf8_lossy(&decoded.stderr)); + assert_eq!(decoded.stdout.len(), 31 * 20 * 4); + assert_eq!(decoded.stdout[(15 * 31 + 20) * 4 + 3], 0, "transparent background survives ProRes encoding"); + assert_eq!(decoded.stdout[(5 * 31 + 5) * 4 + 3], 255); + } + let mut files: Vec<_> = std::fs::read_dir(&out).unwrap().map(|e| e.unwrap().file_name()).collect(); + files.sort(); + assert_eq!(files, ["frame_0000.png", "frame_0003.png", "frame_0006.png", "frame_0009.png"]); + assert_eq!(std::fs::read(snap).unwrap(), std::fs::read(out.join("frame_0009.png")).unwrap()); + } + std::fs::remove_dir_all(&dir).unwrap(); +} + +#[test] +fn desktop_composites_each_window_at_its_frame_with_a_shadow() { + let _turn = HEADLESS.lock().unwrap_or_else(|e| e.into_inner()); + let dir = std::env::temp_dir().join(format!("rune-desktop-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let backdrop = dir.join("backdrop.png"); + ::image::RgbaImage::from_pixel(240, 160, ::image::Rgba([128, 128, 128, 255])).save(&backdrop).unwrap(); + let script = dir.join("script.json"); + // A click on the back window gives it the keyboard and brings it to the front. + std::fs::write(&script, r#"[{"t": 0.1, "type": "tap", "x": 45, "y": 35}]"#).unwrap(); + let fill = || AppSpec::new("fill", (1.0, 1.0), || crate::Color::TRANSPARENT, |c, _| crate::el().w_full().h_full().fill(*c)); + let red = crate::Color { r: 1.0, g: 0.0, b: 0.0, a: 1.0 }; + let blue = crate::Color { r: 0.0, g: 0.0, b: 1.0, a: 1.0 }; + let render = |name: &str| { + let snap = dir.join(name); + let args = ["--desktop", backdrop.to_str().unwrap(), "--script", script.to_str().unwrap(), + "--scale", "2", "--at", "0.5", "--snap", snap.to_str().unwrap()]; + crate::run_windows_with_args(crate::RunOptions::default(), args.map(String::from), move |displays| { + assert_eq!(displays[0].size, (240, 160), "one display the backdrop's size"); + [crate::WindowSpec::new("back", fill()).state(red).options(crate::WindowOptions { + position: Some((40, 40)), physical_size: Some((100, 60)), ..Default::default() + }), crate::WindowSpec::new("panel", fill()).state(blue).configured_options(crate::WindowOptions { + borderless: true, position: Some((160, 100)), physical_size: Some((40, 40)), ..Default::default() + }.macos(crate::MacWindowOptions::default().shadow(false)))] + }); + std::fs::read(snap).unwrap() + }; + let bytes = render("a.png"); + assert_eq!(bytes, render("b.png"), "byte-identical across runs"); + let png = ::image::load_from_memory(&bytes).unwrap().into_rgba8(); + let px = |x: u32, y: u32| png.get_pixel(x, y).0; + assert_eq!(png.dimensions(), (240, 160)); + // The back window covers points (20, 20) to (70, 50); the panel (80, 50) to (100, 70). + let (red, blue) = (|p: [u8; 4]| p[0] > 245 && p[1] < 10 && p[2] < 10, |p: [u8; 4]| p[2] > 245 && p[0] < 10 && p[1] < 10); + assert!(red(px(90, 70)) && red(px(40, 70)) && red(px(139, 70)) && red(px(90, 40)) && red(px(90, 99)), "the window's pixels land at its frame"); + assert!(!red(px(39, 70)) && !red(px(140, 70)) && !red(px(90, 100)), "and stop at its edges"); + assert!(blue(px(160, 100)) && blue(px(199, 139)) && blue(px(180, 120))); + assert!(!red(px(40, 40)), "a titled window's corners are rounded"); + let below = px(90, 106); + assert!(below[0] < 112 && below[0] == below[2], "a soft shadow under the window: {below:?}"); + assert_eq!(px(180, 146), [128, 128, 128, 255], "no shadow when the window asks for none"); + assert_eq!(px(4, 156), [128, 128, 128, 255], "the backdrop elsewhere"); + let run = headless_run().unwrap(); + assert_eq!(run.desktop(), Some(backdrop.as_path())); + let frames = run.windows_at(0.5); + let back = frames.iter().find(|f| f.key == "back").unwrap(); + assert_eq!((back.frame, back.visible, back.focused), ([20.0, 20.0, 50.0, 30.0], true, true)); + assert!(run.window_frames().iter().any(|f| f.key == "panel" && f.focused && f.t == 0.0), "the topmost window starts with the keyboard"); + std::fs::remove_dir_all(&dir).unwrap(); +} + +/// A `--desktop` window whose key handler does `act` to another window. +struct Pair { name: &'static str, color: crate::Color, other: Option<crate::AppHandle<Pair>>, act: fn(&crate::AppHandle<Pair>, &mut crate::Tx) } +/// The windows `Pair`'s key handler ran in, in order. +static KEYED: std::sync::Mutex<Vec<&'static str>> = std::sync::Mutex::new(Vec::new()); +const RED: crate::Color = crate::Color { r: 1.0, g: 0.0, b: 0.0, a: 1.0 }; +const GREEN: crate::Color = crate::Color { r: 0.0, g: 1.0, b: 0.0, a: 1.0 }; +const BLUE: crate::Color = crate::Color { r: 0.0, g: 0.0, b: 1.0, a: 1.0 }; + +fn pair(name: &'static str, color: crate::Color, other: Option<crate::AppHandle<Pair>>, act: fn(&crate::AppHandle<Pair>, &mut crate::Tx), options: crate::WindowOptions) -> (crate::WindowSpec<Pair>, crate::AppHandle<Pair>) { + let spec = AppSpec { + on_key: Some(|p: &mut Pair, _: &crate::KeyEvent, tx: &mut crate::Tx| { + KEYED.lock().unwrap().push(p.name); + if let Some(other) = &p.other { (p.act)(other, tx); } + true + }), + ..AppSpec::new("pair", (1.0, 1.0), || Pair { name: "", color: crate::Color::TRANSPARENT, other: None, act: |_, _| {} }, + |p, _| crate::el().w_full().h_full().fill(p.color)) + }; + let app = crate::App::new(spec).init(move || Pair { name, color, other, act }); + let handle = app.handle(); + (crate::WindowSpec::from_app(name, app).options(options), handle) +} + +/// Runs `windows` over a grey 120x80-point backdrop at scale 2: the snap at `at`, and the run. +fn desktop_case(name: &str, script: &str, at: f64, extra: &[&str], windows: impl FnOnce() -> Vec<crate::AnyWindowSpec> + 'static) -> (::image::RgbaImage, &'static HeadlessRun) { + let dir = std::env::temp_dir().join(format!("rune-desktop-{name}-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let backdrop = dir.join("backdrop.png"); + ::image::RgbaImage::from_pixel(240, 160, ::image::Rgba([128, 128, 128, 255])).save(&backdrop).unwrap(); + let (script_path, snap) = (dir.join("script.json"), dir.join("snap.png")); + std::fs::write(&script_path, script).unwrap(); + KEYED.lock().unwrap().clear(); + let at = at.to_string(); + let mut args = vec!["--desktop", backdrop.to_str().unwrap(), "--script", script_path.to_str().unwrap(), + "--scale", "2", "--fps", "10", "--at", &at, "--snap", snap.to_str().unwrap()]; + args.extend_from_slice(extra); + crate::run_windows_with_args(crate::RunOptions::default(), args.into_iter().map(String::from).collect::<Vec<_>>(), move |_| windows()); + let png = ::image::open(&snap).unwrap().into_rgba8(); + std::fs::remove_dir_all(&dir).unwrap(); + (png, headless_run().unwrap()) +} + +/// Window pixels at (20, 20) to (120, 80) of the output, and at (160, 40) to (220, 100). +fn left() -> crate::WindowOptions { crate::WindowOptions { position: Some((20, 20)), physical_size: Some((100, 60)), ..Default::default() } } +fn right() -> crate::WindowOptions { crate::WindowOptions { position: Some((160, 40)), physical_size: Some((60, 60)), ..Default::default() } } +fn focus_of(run: &HeadlessRun, t: f64, key: &str) -> (bool, bool) { + let f = run.windows_at(t).into_iter().find(|f| f.key == key).unwrap(); + (f.visible, f.focused) +} + +#[test] +fn desktop_frame_shows_what_a_handler_did_to_another_window_that_frame() { + let _turn = HEADLESS.lock().unwrap_or_else(|e| e.into_inner()); + // The launcher's Return updates and focuses the notes window and closes the launcher; + // the frame of that key shows the new note in the focused window. + let (png, run) = desktop_case("stale", r#"[{"t": 0.1, "type": "key", "name": "Enter"}]"#, 0.1, &[], || { + let (notes, handle) = pair("notes", RED, None, |_, _| {}, left()); + let (launcher, _) = pair("launcher", BLUE, Some(handle), |notes, tx| { + notes.update(|p, tx| { p.color = GREEN; tx.instant(); }); + notes.focus(); + tx.close_window(); + }, right()); + vec![notes.boxed(), launcher.boxed()] + }); + assert_eq!(*KEYED.lock().unwrap(), ["launcher"]); + let p = png.get_pixel(70, 50).0; + assert!(p[1] > 245 && p[0] < 10, "the note changed in this frame: {p:?}"); + assert_eq!((focus_of(&run, 0.1, "notes"), focus_of(&run, 0.1, "launcher")), ((true, true), (false, false))); +} + +#[test] +fn desktop_window_closing_itself_on_blur_closes_in_that_frame() { + let _turn = HEADLESS.lock().unwrap_or_else(|e| e.into_inner()); + // Return in `a` focuses `b`, which blurs `a`, whose on_focus closes it. + let script = r#"[{"t": 0.1, "type": "tap", "x": 30, "y": 25}, {"t": 0.2, "type": "key", "name": "Enter"}]"#; + let (png, run) = desktop_case("blur", script, 0.2, &[], || { + let (b, handle) = pair("b", BLUE, None, |_, _| {}, right()); + let (a, _) = pair("a", RED, Some(handle), |b, _| b.focus(), left()); + vec![a.on_focus(|_, focused, tx| if !focused { tx.close_window() }).boxed(), b.boxed()] + }); + assert_eq!(focus_of(&run, 0.1, "a"), (true, true)); + assert_eq!((focus_of(&run, 0.2, "a"), focus_of(&run, 0.2, "b")), ((false, false), (true, true))); + assert_eq!(png.get_pixel(40, 50).0, [128, 128, 128, 255], "a is gone from the frame"); + + // The last shown window closes; losing the keyboard, it opens `c`, which shows at once. + let (png, run) = desktop_case("blur-open", r#"[{"t": 0.1, "type": "key", "name": "Enter"}]"#, 0.1, &[], || { + let (c, handle) = pair("c", BLUE, None, |_, _| {}, crate::WindowOptions { visible: false, ..right() }); + let (a, _) = pair("a", RED, Some(handle), |_, tx| tx.close_window(), left()); + let a = a.on_focus(|p, focused, _| if !focused && let Some(c) = &p.other { c.open() }); + vec![c.boxed(), a.boxed()] + }); + assert_eq!((focus_of(&run, 0.1, "a"), focus_of(&run, 0.1, "c")), ((false, false), (true, true))); + let p = png.get_pixel(190, 70).0; + assert!(p[2] > 245 && p[0] < 10, "c draws in that frame: {p:?}"); +} + +#[test] +fn desktop_click_on_the_backdrop_deactivates_the_app_until_it_refocuses() { + let _turn = HEADLESS.lock().unwrap_or_else(|e| e.into_inner()); + // As on macOS, a click on the desktop activates another app: no window has focus and + // keys go nowhere until the app is active again. + let script = r#"[{"t": 0.1, "type": "tap", "x": 110, "y": 75}, {"t": 0.2, "type": "key", "name": "Enter"}, + {"t": 0.3, "focus": true}, {"t": 0.4, "type": "key", "name": "Enter"}]"#; + let dir = std::env::temp_dir().join(format!("rune-desktop-tree-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let tree = dir.join("tree.json"); + let (_, run) = desktop_case("inactive", script, 0.2, &["--tree", tree.to_str().unwrap()], || { + vec![pair("a", RED, None, |_, _| {}, left()).0.boxed()] + }); + let tree: Value = serde_json::from_str(&std::fs::read_to_string(&tree).unwrap()).unwrap(); + std::fs::remove_dir_all(&dir).unwrap(); + assert_eq!(tree["windows"][0]["focused"], json!(false), "--tree reports no focus while inactive"); + assert_eq!(focus_of(&run, 0.0, "a"), (true, true)); + assert_eq!(focus_of(&run, 0.2, "a"), (true, false)); + assert!(KEYED.lock().unwrap().is_empty(), "keys while inactive go to another app"); + + let (_, run) = desktop_case("inactive", script, 0.5, &[], || vec![pair("a", RED, None, |_, _| {}, left()).0.boxed()]); + assert_eq!(focus_of(&run, 0.3, "a"), (true, true)); + assert_eq!(*KEYED.lock().unwrap(), ["a"], "only the key after refocusing lands"); +} + +#[test] +fn desktop_click_through_window_never_takes_the_keyboard() { + let _turn = HEADLESS.lock().unwrap_or_else(|e| e.into_inner()); + // `a` opens and focuses a click-through HUD; `a` keeps the keyboard. + let script = r#"[{"t": 0.1, "type": "key", "name": "Enter"}, {"t": 0.2, "type": "key", "name": "Enter"}]"#; + let (_, run) = desktop_case("hud", script, 0.3, &[], || { + let hud = crate::WindowOptions { visible: false, click_through: true, borderless: true, ..right() }; + let (hud, handle) = pair("hud", BLUE, None, |_, _| {}, hud); + let (a, _) = pair("a", RED, Some(handle), |hud, _| { hud.open(); hud.focus(); }, left()); + vec![a.boxed(), hud.boxed()] + }); + assert_eq!((focus_of(&run, 0.1, "a"), focus_of(&run, 0.1, "hud")), ((true, true), (true, false))); + assert_eq!(*KEYED.lock().unwrap(), ["a", "a"]); +} + +/// The reopen hooks that ran: window, `has_visible_windows`. +static REOPENED: std::sync::Mutex<Vec<(&'static str, bool)>> = std::sync::Mutex::new(Vec::new()); + +/// Reopen hooks for `closer`: each records the reopen. +fn record(p: &mut Pair, visible: bool, _: &mut crate::Tx) -> bool { REOPENED.lock().unwrap().push((p.name, visible)); false } +fn handle(p: &mut Pair, visible: bool, tx: &mut crate::Tx) -> bool { record(p, visible, tx); true } +/// Opens the other window and leaves the rest to the default. +fn open_other(p: &mut Pair, visible: bool, tx: &mut crate::Tx) -> bool { + if let Some(other) = &p.other { other.open(); } + record(p, visible, tx) +} + +/// A `keep_running` window that closes on any key, with `hook` as its `on_reopen`. +fn closer_with(name: &'static str, color: crate::Color, other: Option<crate::AppHandle<Pair>>, + hook: fn(&mut Pair, bool, &mut crate::Tx) -> bool, options: crate::ConfiguredWindowOptions) -> (crate::AnyWindowSpec, crate::AppHandle<Pair>) { + let spec = AppSpec { + on_key: Some(|_: &mut Pair, _: &crate::KeyEvent, tx: &mut crate::Tx| { tx.close_window(); true }), + ..AppSpec::new("closer", (1.0, 1.0), || Pair { name: "", color: crate::Color::TRANSPARENT, other: None, act: |_, _| {} }, + |p, _| crate::el().w_full().h_full().fill(p.color)) + }; + let app = crate::App::new(spec).init(move || Pair { name, color, other, act: |_, _| {} }).keep_running().on_reopen(hook); + let handle = app.handle(); + (crate::WindowSpec::from_app(name, app).configured_options(options).boxed(), handle) +} + +/// `closer_with` that records reopens, handling them when `handles`. +fn closer(name: &'static str, color: crate::Color, handles: bool, options: crate::ConfiguredWindowOptions) -> crate::AnyWindowSpec { + closer_with(name, color, None, if handles { handle } else { record }, options).0 +} + +/// Runs `windows` on a headless desktop with `script`, as `desktop_case` does. +fn reopen_case(script: &str, accessory: bool, windows: impl FnOnce() -> Vec<crate::AnyWindowSpec> + 'static) -> &'static HeadlessRun { + REOPENED.lock().unwrap().clear(); + let dir = std::env::temp_dir().join(format!("rune-reopen-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let backdrop = dir.join("backdrop.png"); + ::image::RgbaImage::from_pixel(240, 160, ::image::Rgba([128, 128, 128, 255])).save(&backdrop).unwrap(); + let (script_path, tree) = (dir.join("script.json"), dir.join("tree.json")); + std::fs::write(&script_path, script).unwrap(); + let args = ["--desktop", backdrop.to_str().unwrap(), "--script", script_path.to_str().unwrap(), + "--scale", "2", "--fps", "10", "--tree", tree.to_str().unwrap()]; + let options = crate::RunOptions { accessory, ..Default::default() }; + crate::run_windows_with_args(options, args.map(String::from), move |_| windows()); + std::fs::remove_dir_all(&dir).unwrap(); + headless_run().unwrap() +} + +#[test] +fn desktop_reopen_shows_the_window_closed_last_with_the_keyboard() { + let _turn = HEADLESS.lock().unwrap_or_else(|e| e.into_inner()); + // Enter closes `b` (on top, with the keyboard), then `a`; reopening brings back `a`. + let script = r#"[{"t": 0.1, "type": "key", "name": "Enter"}, {"t": 0.2, "type": "key", "name": "Enter"}, + {"t": 0.3, "reopen": true}]"#; + let run = reopen_case(script, false, || vec![closer("a", RED, false, left().macos(Default::default())), + closer("b", BLUE, false, right().macos(Default::default()))]); + assert_eq!((focus_of(run, 0.2, "a"), focus_of(run, 0.2, "b")), ((false, false), (false, false))); + assert_eq!((focus_of(run, 0.3, "a"), focus_of(run, 0.3, "b")), ((true, true), (false, false))); + assert_eq!(*REOPENED.lock().unwrap(), [("a", false), ("b", false)], "every hook runs, before the default"); + assert!(run.events().iter().any(|e| matches!(e.event, ScriptEvent::Reopen))); +} + +#[test] +fn desktop_reopen_with_a_window_showing_changes_nothing() { + let _turn = HEADLESS.lock().unwrap_or_else(|e| e.into_inner()); + let script = r#"[{"t": 0.1, "type": "key", "name": "Enter"}, {"t": 0.2, "reopen": true}]"#; + let run = reopen_case(script, false, || vec![closer("a", RED, false, left().macos(Default::default())), + closer("b", BLUE, false, right().macos(Default::default()))]); + assert_eq!((focus_of(run, 0.2, "a"), focus_of(run, 0.2, "b")), ((true, true), (false, false))); + assert_eq!(*REOPENED.lock().unwrap(), [("a", true), ("b", true)]); +} + +#[test] +fn desktop_reopen_default_sees_what_the_hooks_did() { + let _turn = HEADLESS.lock().unwrap_or_else(|e| e.into_inner()); + // `a` closes, then `b`, so `b` would come back; but `b`'s hook opens `a` and leaves + // the rest to the default, which then finds a window showing. + let script = r#"[{"t": 0.1, "type": "tap", "x": 30, "y": 25}, {"t": 0.2, "type": "key", "name": "Enter"}, + {"t": 0.3, "type": "key", "name": "Enter"}, {"t": 0.4, "reopen": true}]"#; + let run = reopen_case(script, false, || { + let (a, handle) = closer_with("a", RED, None, record, left().macos(Default::default())); + let (b, _) = closer_with("b", BLUE, Some(handle), open_other, right().macos(Default::default())); + vec![a, b] + }); + assert_eq!((focus_of(run, 0.3, "a"), focus_of(run, 0.3, "b")), ((false, false), (false, false)), "both closed"); + assert_eq!((focus_of(run, 0.4, "a"), focus_of(run, 0.4, "b")), ((true, true), (false, false))); + assert_eq!(*REOPENED.lock().unwrap(), [("a", false), ("b", false)]); +} + +#[test] +fn desktop_reopen_hook_that_handles_it_skips_the_default() { + let _turn = HEADLESS.lock().unwrap_or_else(|e| e.into_inner()); + let script = r#"[{"t": 0.1, "type": "key", "name": "Enter"}, {"t": 0.2, "reopen": true}]"#; + let run = reopen_case(script, false, || vec![closer("a", RED, true, left().macos(Default::default()))]); + assert_eq!(focus_of(run, 0.2, "a"), (false, false)); + assert_eq!(*REOPENED.lock().unwrap(), [("a", false)]); +} + +#[test] +fn desktop_reopen_never_brings_back_a_launcher_or_an_accessory_app_window() { + let _turn = HEADLESS.lock().unwrap_or_else(|e| e.into_inner()); + // The launcher closes last, so a launcher-blind rule would pick it; `a` comes back. + let launcher = || { + let mut options = crate::WindowOptions::launcher_panel(); + let (position, physical_size) = (right().position, right().physical_size); + options.options = crate::WindowOptions { visible: true, position, physical_size, ..options.options }; + closer("launcher", BLUE, false, options) + }; + let script = r#"[{"t": 0.1, "type": "tap", "x": 30, "y": 25}, {"t": 0.2, "type": "key", "name": "Enter"}, + {"t": 0.3, "type": "tap", "x": 95, "y": 35}, {"t": 0.4, "type": "key", "name": "Enter"}, {"t": 0.5, "reopen": true}]"#; + let run = reopen_case(script, false, move || vec![closer("a", RED, false, left().macos(Default::default())), launcher()]); + assert_eq!((focus_of(run, 0.4, "a"), focus_of(run, 0.4, "launcher")), ((false, false), (false, false)), "both closed"); + assert_eq!((focus_of(run, 0.5, "a"), focus_of(run, 0.5, "launcher")), ((true, true), (false, false))); + + // A launcher alone stays hidden. + let run = reopen_case(r#"[{"t": 0.1, "type": "tap", "x": 95, "y": 35}, {"t": 0.2, "type": "key", "name": "Enter"}, + {"t": 0.3, "reopen": true}]"#, false, move || vec![launcher()]); + assert_eq!(focus_of(run, 0.3, "launcher"), (false, false)); + + // An accessory app's hooks run, but nothing comes back. + let script = r#"[{"t": 0.1, "type": "key", "name": "Enter"}, {"t": 0.2, "reopen": true}]"#; + let run = reopen_case(script, true, || vec![closer("a", RED, false, left().macos(Default::default()))]); + assert_eq!(focus_of(run, 0.2, "a"), (false, false)); + assert_eq!(*REOPENED.lock().unwrap(), [("a", false)]); +} + +#[test] +fn size_and_scale_must_be_positive() { + assert_eq!(parse_size("400x300.5"), Ok((400.0, 300.5))); + assert_eq!(parse_scale("1.5"), Ok(1.5)); + for bad in ["0x0", "400x0", "-1x10", "NaNx10", "infx10", "400", "ax3"] { assert!(parse_size(bad).is_err(), "{bad}"); } + for bad in ["0", "-2", "NaN", "inf", "x"] { assert!(parse_scale(bad).is_err(), "{bad}"); } +} + +#[test] +fn keycaps_draw_over_frames_but_never_enter_the_tree() { + let _turn = HEADLESS.lock().unwrap_or_else(|e| e.into_inner()); + let dir = std::env::temp_dir().join(format!("rune-keys-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let script = dir.join("script.json"); + std::fs::write(&script, r#"[{"t": 0.1, "type": "type", "text": "hi"}, {"t": 0.3, "type": "tap", "x": 150, "y": 30}]"#).unwrap(); + let run = |name: &str, extra: &[&str]| { + let spec = AppSpec::new("keys", (200.0, 120.0), || (), |_, _| crate::el().key("root").w_full().h_full().fill(crate::oklch(0.9, 0.0, 0.0))); + let (snap, tree) = (dir.join(format!("{name}.png")), dir.join(format!("{name}.json"))); + let mut args = vec!["--script", script.to_str().unwrap(), "--scale", "1", "--at", "0.5", + "--snap", snap.to_str().unwrap(), "--tree", tree.to_str().unwrap()]; + args.extend_from_slice(extra); + headless(crate::App::new(spec), Args::parse_from(args.into_iter().map(String::from).collect())); + (std::fs::read(snap).unwrap(), std::fs::read_to_string(tree).unwrap()) + }; + let plain = run("plain", &[]); + let keys = run("keys", &["--keys", "top-left", "--pointer"]); + let light = run("light", &["--keys", "top-left", "--pointer", "--keys-theme", "light"]); + let dark = run("dark", &["--keys", "top-left", "--pointer", "--keys-theme", "dark"]); + std::fs::remove_dir_all(&dir).unwrap(); + assert_eq!(plain.1, keys.1, "the overlay never enters the tree"); + assert_ne!(plain.0, keys.0, "but it draws over the frame"); + assert_eq!(keys.0, light.0, "auto caps follow the app's light background"); + assert_ne!(light.0, dark.0); + + use crate::input::keycaps::Corner; + let args = |v: &[&str]| Args::parse_from(v.iter().map(|s| (*s).into()).collect()); + assert_eq!(args(&["--keys", "--snap", "a.png"]).keys, Some(Corner::BottomLeft), "the corner is optional"); + assert_eq!(args(&["--keys", "top"]).keys, Some(Corner::Top)); + assert_eq!(args(&["--snap", "a.png"]).keys, None); +} + +#[test] +fn script_chords_only_fire_global_handlers_even_when_the_window_is_key() { + let script = parse_script(json!([{"t": 0.1, "type": "shortcut", "chord": "cmd+space"}, {"t": 0.2, "shortcut": "cmd+k"}])); + assert!(matches!(&script[0].kind, Kind::Shortcut(c) if *c == "cmd+space".parse().unwrap())); + assert!(matches!(&script[1].kind, Kind::Shortcut(c) if *c == "cmd+k".parse().unwrap())); + + let _turn = HEADLESS.lock().unwrap_or_else(|e| e.into_inner()); + static SEEN: std::sync::Mutex<Vec<String>> = std::sync::Mutex::new(Vec::new()); + let dir = std::env::temp_dir().join(format!("rune-chords-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("script.json"); + SEEN.lock().unwrap().clear(); + std::fs::write(&path, r#"[{"focus": true}, {"t": 0.1, "type": "shortcut", "chord": "cmd+k"}, + {"t": 0.2, "type": "shortcut", "chord": "cmd+space"}, {"t": 0.3, "shortcut": "cmd+k"}, + {"t": 0.4, "focus": false}, {"t": 0.5, "type": "shortcut", "chord": "cmd+space"}, + {"t": 0.6, "type": "key", "name": "Escape"}]"#).unwrap(); + let spec = AppSpec { + on_key: Some(|_, ev, _| { SEEN.lock().unwrap().push(format!("on_key {:?}", ev.key)); true }), + ..AppSpec::new("chords", (40.0, 30.0), || (), |_, _| crate::el()) + }; + let app = crate::App::new(spec) + .global_shortcut("cmd+k", |_, _| SEEN.lock().unwrap().push("global cmd+k".into())) + .global_shortcut("cmd+space", |_, _| SEEN.lock().unwrap().push("global cmd+space".into())); + let tree = dir.join("tree.json"); + headless(app, Args::parse_from(["--script", path.to_str().unwrap(), "--tree", tree.to_str().unwrap()].map(String::from).into())); + std::fs::remove_dir_all(&dir).unwrap(); + assert_eq!(*SEEN.lock().unwrap(), ["global cmd+k", "global cmd+space", "global cmd+k", "global cmd+space", "on_key Escape"]); +} + +#[test] +fn native_trace_does_not_select_virtual_rendering() { + let args = |v: &[&str]| Args::parse_from(v.iter().map(|s| (*s).into()).collect()); + assert!(args(&["--trace", "trace.jsonl", "--frames", "120"]).headless()); + assert!(!args(&["--native", "--trace", "trace.jsonl", "--frames", "120"]).headless()); + assert!(args(&["--native", "--snap", "snap.png"]).headless()); +} + +#[test] +fn a_script_alone_replays_headless_unless_native() { + // A window never replays a script, so `--script` alone renders offscreen like `--frames`. + let args = |v: &[&str]| Args::parse_from(v.iter().map(|s| (*s).into()).collect()); + assert!(args(&["--script", "s.json"]).headless()); + assert!(!args(&["--native", "--script", "s.json"]).headless()); + assert!(!args(&["--theme", "light"]).headless()); +} + +#[test] +fn tree_and_trace_serialize_effects_and_remove_channels() { + fn view(show: &bool, _: &mut Cx<bool>) -> El { + crate::el().key("root").size(100.0, 100.0).children(show.then(|| + crate::el().key("pill").size(40.0, 40.0).opacity(0.5) + .live_scale(&crate::live::Live::new(0.8)) + .transition(crate::Transition::blur(4.0)))) + } + let mut rt = Runtime::new(true, view, (100.0, 100.0), Env { scale: 1.0, system_dark: true }); + rt.frame(0.0); + let tree = tree_json(&rt, 0.0); + let pill = tree["elements"].as_array().unwrap().iter().find(|e| e["key"] == "pill").unwrap(); + assert_eq!(pill["opacity"], 0.5); + assert!((pill["scale"].as_f64().unwrap() - 0.8).abs() < 1e-6); + assert_eq!(pill["blur"], 0.0); + let path = std::env::temp_dir().join(format!("rune-effects-{}.jsonl", std::process::id())); + { + let mut trace = Trace::open(&path, rt.viewport, 60.0, 1.0); + trace.frame(&mut rt, 0.0, 0.0); + rt.state = false; rt.invalidate(); rt.frame(0.0); rt.frame(0.05); + let tree = tree_json(&rt, 0.05); + let pill = tree["elements"].as_array().unwrap().iter().find(|e| e["key"] == "pill").unwrap(); + assert_eq!(pill["exiting"], true); + assert!(tree["elements"].as_array().unwrap().iter().filter(|e| e["key"] != "pill").all(|e| e.get("exiting").is_none())); + trace.frame(&mut rt, 50.0, 0.0); + rt.frame(3.0); + trace.frame(&mut rt, 3050.0, 0.0); + } + let text = std::fs::read_to_string(&path).unwrap(); + std::fs::remove_file(path).unwrap(); + let lines: Vec<Value> = text.lines().map(|line| serde_json::from_str(line).unwrap()).collect(); + let blur = lines[1]["cm"].as_array().unwrap().iter() + .find(|m| m["name"].as_str().unwrap().ends_with("pill.blur")).unwrap()["id"].as_u64().unwrap(); + let values = lines[2]["c"].as_array().unwrap(); + assert!(values.iter().any(|v| v[0] == blur && v[1].as_f64().unwrap() > 0.0)); + assert!(lines[3]["cg"].as_array().unwrap().contains(&json!(blur))); + assert_eq!(lines[1]["e"][0].as_array().unwrap().len(), 8, "element row schema stays compatible"); +} + +#[test] +fn trace_all_names_unkeyed_elements_and_reports_what_animated() { + fn view(wide: &bool, _: &mut Cx<bool>) -> El { + crate::el().key("root").size(100.0, 100.0) + .children([crate::el().size(if *wide { 80.0 } else { 20.0 }, 20.0)]) + } + assert!(Args::parse_from(["--trace-all"].map(String::from).into()).trace_all); + let lines = |all: bool| { + let mut rt = Runtime::new(false, view, (100.0, 100.0), Env { scale: 1.0, system_dark: true }); + rt.frame(0.0); + let path = std::env::temp_dir().join(format!("rune-trace-all-{all}-{}.jsonl", std::process::id())); + { + let mut trace = Trace::open(&path, rt.viewport, 60.0, 1.0); + trace.all = all; + trace.frame(&mut rt, 0.0, 0.0); + rt.state = true; rt.invalidate(); rt.frame(0.0); rt.frame(0.05); + trace.frame(&mut rt, 50.0, 0.0); + } + let text = std::fs::read_to_string(&path).unwrap(); + std::fs::remove_file(path).unwrap(); + text.lines().map(|line| serde_json::from_str(line).unwrap()).collect::<Vec<Value>>() + }; + let keyed = lines(false); + assert_eq!(keyed[1]["m"].as_array().unwrap().len(), 1, "only the keyed root without --trace-all"); + let all = lines(true); + let metas = all[1]["m"].as_array().unwrap(); + let root = metas.iter().find(|m| m["nm"] == "root").unwrap(); + let child = metas.iter().find(|m| m["nm"] != "root").expect("unkeyed child traced"); + assert_eq!(child["pv"], root["id"], "parent link to the root"); + assert_eq!(all[2]["quality"]["why"], json!(["tracks"])); + let tk = all[2]["tk"].as_array().unwrap(); + assert!(tk.iter().any(|t| t[0] == child["id"] && t[1] == "frame" && t[2] == 1), "{tk:?}"); +} + +#[test] +fn the_window_title_starts_from_the_spec_and_follows_set_title() { + fn view(_: &u32, _: &mut Cx<u32>) -> El { + crate::el().size(100.0, 100.0).on_press_tx(|n: &mut u32, tx| { *n += 1; tx.set_title(format!("Notes {}", *n % 2)); }) + } + let spec = AppSpec::new("Notes", (100.0, 100.0), || 0, view); + let mut rt = runtime_for(&spec, 0, (100.0, 100.0), Env { scale: 1.0, system_dark: true }, std::sync::Arc::new(|| {})); + rt.frame(0.0); + assert_eq!(tree_json(&rt, 0.0)["title"], "Notes"); + assert_eq!(rt.host.window_title.take_change(), None, "the window opens with the spec's title"); + let press = |rt: &mut Runtime<u32>, t| { rt.pointer_down(50.0, 50.0); rt.pointer_up(50.0, 50.0); rt.frame(t); }; + press(&mut rt, 0.1); + assert_eq!(tree_json(&rt, 0.1)["title"], "Notes 1"); + assert_eq!(rt.host.window_title.take_change(), Some("Notes 1")); + assert_eq!(rt.host.window_title.take_change(), None); + rt.update(|_, tx| tx.set_title("Notes 1")); + assert_eq!(rt.host.window_title.take_change(), None, "the same title again is no change"); + assert!(!rt.update_if(|_, tx| { tx.set_title("Draft"); false }), "the shell shows a title without a frame"); + assert_eq!(rt.host.window_title.take_change(), Some("Draft")); +} + +#[path = "playground_cli_tests.rs"] +mod playground_cli; + +#[test] +fn a_trace_says_how_far_scrolling_carries_an_element_when_that_changes() { + fn view(_: &(), _: &mut Cx<()>) -> El { + crate::col().key("scroll").size(100.0, 100.0).scroll(crate::ScrollSpec { stick_bottom: false }) + .child(crate::el().key("row").w_full().h(400.0)) + } + let mut rt = Runtime::new((), view, (100.0, 100.0), Env { scale: 1.0, system_dark: true }); + rt.frame(0.0); + let path = std::env::temp_dir().join(format!("rune-trace-scrolled-{}.jsonl", std::process::id())); + { + let mut trace = Trace::open(&path, rt.viewport, 60.0, 1.0); + trace.frame(&mut rt, 0.0, 0.0); + rt.update(|_, tx| tx.scroll_to_instant("scroll", 0.0, 30.0)); + rt.frame(0.02); + trace.frame(&mut rt, 20.0, 0.0); + trace.frame(&mut rt, 40.0, 0.0); + } + let text = std::fs::read_to_string(&path).unwrap(); + std::fs::remove_file(path).unwrap(); + let lines: Vec<Value> = text.lines().map(|line| serde_json::from_str(line).unwrap()).collect(); + let row = lines[1]["m"].as_array().unwrap().iter().find(|m| m["nm"].as_str().unwrap().ends_with("row")).unwrap()["id"].clone(); + assert!(lines[1].get("sc").is_none(), "nothing scrolled yet"); + assert_eq!(lines[2]["sc"], json!([[row, 0.0, 30.0]])); + assert!(lines[3].get("sc").is_none(), "only when it changes"); +} diff --git a/app/vendor/rune/crates/rune/src/tooling/trace.rs b/app/vendor/rune/crates/rune/src/tooling/trace.rs new file mode 100644 index 0000000..faa1fc5 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/tooling/trace.rs @@ -0,0 +1,438 @@ +//! Motion-lint JSONL trace writer and headless element-tree JSON snapshots. + +use std::collections::{HashMap, HashSet}; +use std::io::Write; + +use crate::time::Instant; + +use super::*; + +pub(crate) struct Trace { + out: std::io::BufWriter<std::fs::File>, + ids: HashMap<String, u32>, + described: HashMap<u32, (String, &'static str, &'static str)>, + states: HashMap<u32, ([i64; 6], u32, [i64; 4])>, + /// Each element's `ElementInfo::scrolled` last written, in hundredths of a point (none: 0). + scrolled: HashMap<u32, [i64; 2]>, + effects: HashMap<u32, [String; 2]>, + goals: HashMap<u32, [i64; 7]>, + channels: rune_motion::TraceChannels, + path: PathBuf, + /// Trace every element, not only keyed and named ones (`--trace-all`). + pub(crate) all: bool, + /// Lines waiting for present times; `None` writes each frame at once. + presents: Option<crate::frame::present_time::Presents>, + /// The native surface's frame counts and `App::dev_stats`, printed when the trace closes. + surface: Option<(std::sync::Arc<std::sync::Mutex<crate::SurfaceStats>>, Option<fn() -> String>)>, +} + +/// A native frame's timing beyond its submission time. +#[derive(Clone, Copy, Debug, Default)] +pub(crate) struct FrameTiming { + /// The display link's target, ms on the trace's clock. + pub target_ms: Option<f64>, + /// The drawable the frame presented, when present times are recorded. + pub drawable: Option<u64>, + /// The previous frame asked for this one right away (it wasn't idle). + pub continuous: bool, +} + +pub(super) fn r2(v: f32) -> f64 { + (f64::from(v) * 100.0).round() / 100.0 +} + +impl Trace { + pub(crate) fn open(path: &PathBuf, size: (f32, f32), fps: f64, scale: f32) -> Trace { + Self::open_clock(path, size, fps, scale, "virtual") + } + + pub(crate) fn open_clock(path: &PathBuf, size: (f32, f32), fps: f64, scale: f32, clock: &str) -> Trace { + if let Some(d) = path.parent() { + std::fs::create_dir_all(d).ok(); + } + let file = std::fs::File::create(path).unwrap_or_else(|e| die(&format!("{}: {e}", path.display()))); + let mut out = std::io::BufWriter::new(file); + let mut header = json!({ + "type": "header", "launch": "rune", "width": size.0, "height": size.1, + "hz": fps, "scale": scale, "platform": "rune", "units": "pt", "clock": clock, + }); + if clock == "wall" { header["timestamp"] = "cpu-submit".into(); } + writeln!(out, "{header}").ok(); + Trace { out, ids: HashMap::new(), described: HashMap::new(), states: HashMap::new(), scrolled: HashMap::new(), effects: HashMap::new(), + goals: HashMap::new(), channels: Default::default(), path: path.clone(), all: false, presents: None, surface: None } + } + + /// Holds each frame's line until its present time arrives from `source`, then writes + /// it with `present_ms` and `present_dt_ms`. `start` is the trace clock's zero. + #[cfg_attr(not(target_os = "macos"), allow(dead_code))] + pub(crate) fn record_presents(&mut self, source: std::sync::Arc<dyn crate::frame::present_time::Source>, start: Instant) { + self.presents = Some(crate::frame::present_time::Presents::new(source, start)); + } + + /// Prints the surface's frame counts, and the app's own, when the trace closes. + pub(crate) fn record_surface(&mut self, stats: std::sync::Arc<std::sync::Mutex<crate::SurfaceStats>>, app: Option<fn() -> String>) { + self.surface = Some((stats, app)); + } + + /// Waits up to `wait` for the last frames' present times, then writes every held line. + pub(crate) fn settle_presents(&mut self, wait: std::time::Duration) { + #[cfg(target_arch = "wasm32")] + let _ = wait; + let Some(presents) = self.presents.as_mut() else { return }; + #[cfg(not(target_arch = "wasm32"))] + { + let until = crate::time::now() + wait; + while presents.waiting() && crate::time::now() < until { + std::thread::sleep(std::time::Duration::from_millis(2)); + } + } + presents.flush(&mut self.out); + } + + fn id(&mut self, key: &str) -> u32 { + let next = self.ids.len() as u32 + 1; + *self.ids.entry(key.to_owned()).or_insert(next) + } + + #[cfg(test)] + #[inline(always)] + pub(crate) fn frame<S>(&mut self, rt: &mut Runtime<S>, t_ms: f64, cpu_ms: f64) { + self.frame_timed_core(rt.core_mut(), t_ms, cpu_ms, FrameTiming::default()); + } + + #[cfg(test)] + #[inline(always)] + pub(crate) fn frame_timed<S>(&mut self, rt: &mut Runtime<S>, t_ms: f64, cpu_ms: f64, timing: FrameTiming) { + self.frame_timed_core(rt.core_mut(), t_ms, cpu_ms, timing); + } + + pub(crate) fn frame_timed_core(&mut self, rt: &mut crate::runtime::RuntimeCore, t_ms: f64, cpu_ms: f64, timing: FrameTiming) { + let els = rt.elements(); + let settled = rt.settled; + let mut metas = Vec::new(); + let mut changed = Vec::new(); + let mut scrolled = Vec::new(); + let mut seen = HashSet::new(); + // A virtual list's invisible estimated extent changes when rows are measured or the + // window rebases. Record the actual row surfaces, not that bookkeeping rectangle. + let all = self.all; + let traced = |e: &crate::runtime::ElementInfo| (all || e.key.is_some() || e.trace_name.is_some()) && !e.virtual_extent; + let blank = rt.tree.blank_leaves(); + for e in els.iter().filter(|e| traced(e)) { + let id = self.id(&e.path); + let name = e.trace_name.unwrap_or(&e.path); + let (class, host) = e.trace_namespace.unwrap_or(("rune", "rune")); + seen.insert(id); + if self.described.get(&id).is_none_or(|old| old.0 != name || old.1 != class || old.2 != host) { + self.described.insert(id, (name.to_owned(), class, host)); + let mut meta = json!({ "id": id, "cls": class, "nm": name, "host": host, "role": e.role }); + if let Some(p) = e.parent.and_then(|p| els.get(p)).filter(|p| traced(p)) { + meta["pv"] = self.id(&p.path).into(); + } + metas.push(meta); + } + let effects = [format!("{name}.scale"), format!("{name}.blur")]; + for (name, value, unit) in [(&effects[0], e.scale, "ratio"), (&effects[1], e.blur, "pt")] { + self.channels.sample(name, "position", value); + self.channels.owner(name, id, unit); + } + if let Some(old) = self.effects.insert(id, effects.clone()) { + for name in old.iter().filter(|n| !effects.contains(n)) { self.channels.remove(name); } + } + let [x, y, w, h] = e.rect; + // A settle commit is a deliberate cut (everything lands at once); a growth row reveals + // its content by growing; reveals fade words in. + use rune_motion::{Intent as I, flags as F}; + let clipped = e.rect.iter().zip(e.visible.iter()).any(|(a, b)| (a - b).abs() > 0.5); + let mut intent = e.live_intent; + if settled { + intent |= I::POSITION | I::SIZE | I::TRANSITION | I::REVEAL; + } + // Reduced motion deliberately cuts geometry. Opacity still needs to fade; + // do not declare transition/opacity intent for the whole reduced-motion tree. + if rt.reduced_motion { + intent |= I::POSITION | I::SIZE; + } + if e.revealing { + intent |= I::REVEAL; + } + if e.in_growing_row { + intent |= I::SIZE | I::REVEAL; + } + let flags = if e.moving || e.in_growing_row { F::ANIMATED } else { 0 } + | if e.scrolling { F::SCROLLING } else { 0 } + | if clipped { F::CLIPPED } else { 0 } + | if blank.contains(e.path.as_str()) { F::BLANK } else { 0 } + | if e.loop_phase.is_some() { F::LOOPING } else { 0 } + | intent << 8; + let q = [ + (f64::from(x) * 100.0).round() as i64, + (f64::from(y) * 100.0).round() as i64, + (f64::from(w) * 100.0).round() as i64, + (f64::from(h) * 100.0).round() as i64, + (f64::from(e.opacity) * 1000.0).round() as i64, + (f64::from(e.radius) * 100.0).round() as i64, + ]; + let sc = e.scrolled.map(|v| (f64::from(v) * 100.0).round() as i64); + if self.scrolled.get(&id).copied().unwrap_or_default() != sc { + scrolled.push(json!([id, r2(e.scrolled[0]), r2(e.scrolled[1])])); + if sc == [0; 2] { self.scrolled.remove(&id); } else { self.scrolled.insert(id, sc); } + } + let state = (q, flags, e.visible.map(|v| (v * 100.0).round() as i64)); + if self.states.get(&id) != Some(&state) { + self.states.insert(id, state); + let mut row = vec![ + json!(id), + json!(r2(x)), + json!(r2(y)), + json!(r2(w)), + json!(r2(h)), + json!((f64::from(e.opacity) * 1000.0).round() / 1000.0), + json!(r2(e.radius)), + json!(flags), + ]; + if clipped { + row.extend(e.visible.map(|v| json!(r2(v)))); + } + changed.push(Value::Array(row)); + } + } + let gone: Vec<u32> = self.states.keys().copied().filter(|id| !seen.contains(id)).collect(); + // A settle unmounts what it replaces at once: a cut (transition | opacity) at its last place. + let mut cuts = Vec::new(); + for id in &gone { + self.scrolled.remove(id); + if let Some(names) = self.effects.remove(id) { + for name in names { self.channels.remove(&name); } + } + if let Some((q, ..)) = self.states.remove(id) + && settled + { + let [x, y, w, h] = [q[0], q[1], q[2], q[3]].map(|v| v as f64 / 100.0); + cuts.push(json!([id, x, y, w, h, rune_motion::Intent::TRANSITION | rune_motion::Intent::OPACITY, 0])); + } + } + + let mut line = json!({ "t": (t_ms * 1000.0).round() / 1000.0, "n": 1 }); + // A fresh destination ends a trajectory, even when it came from streamed data rather + // than a key. Keep this separate from input: it never excuses a jump or lost velocity. + let mut goals = Vec::new(); + for (path, goal) in rt.tree.trace_goals() { + let Some(&id) = self.ids.get(path) else { continue }; + let q = goal.map(|v| (f64::from(v) * 10000.0).round() as i64); + if let Some(old) = self.goals.insert(id, q) { + let scale = u8::from(old[6] != q[6]) * 15; + let position = u8::from(old[0] != q[0] || old[4] != q[4]) + | u8::from(old[1] != q[1] || old[5] != q[5]) * 2; + let own = position | scale | u8::from(old[2] != q[2]) * 4 | u8::from(old[3] != q[3]) * 8; + if own != 0 { goals.push(json!([id, own, position | scale])); } + } + } + self.goals.retain(|id, _| seen.contains(id)); + if !goals.is_empty() { line["retarget"] = goals.into(); } + // motion-lint's touch count: motion under a held press follows the hand. + if rt.pressing() { + line["k"] = 1.into(); + } + let (edges, position_error) = rt.scene.sampling_error(); + let retarget = rt.scene.store_mut().take_retarget_audit(); + line["quality"] = json!({ + "cpu_ms": cpu_ms, "scene_edges": edges, "position_error_px": position_error, + "retarget_lanes": retarget.lanes, "velocity_error_pt_s": retarget.max_velocity_error, + "animating": rt.animating, + "why": crate::runtime::AnimSource::names(if rt.animating { rt.motion.anim_sources() } else { 0 }), + }); + // What the motion store spent this frame on, by traced element id (or path when untraced). + let touched = rt.touched_tracks(); + if !touched.is_empty() { + line["tk"] = touched.into_iter().map(|(path, prop, active)| { + let who = self.ids.get(&path).map_or_else(|| json!(path), |&id| json!(id)); + json!([who, prop, u8::from(active)]) + }).collect::<Vec<_>>().into(); + } + let events = std::mem::take(&mut rt.events); + if !events.is_empty() { + line["ev"] = events.into(); + } + if !metas.is_empty() { + line["m"] = metas.into(); + } + if !changed.is_empty() { + line["e"] = changed.into(); + } + if !gone.is_empty() { + line["g"] = gone.into(); + } + // How far scrolling carries each element, when that changed: [id, x, y] in points. + if !scrolled.is_empty() { + line["sc"] = scrolled.into(); + } + if !cuts.is_empty() { + line["ai"] = cuts.into(); + } + if let Some(channels) = rt.frame.trace_channels() { + for (&name, &(kind, value)) in channels { self.channels.sample(name, kind, value); } + } + let mut line = line.to_string(); + line.pop(); // Append scalar fields to the same frame object. + self.channels.write_json(&mut line); + if let Some(target) = timing.target_ms { + line.push_str(&format!(r#","target_ms":{target}"#)); + } + if let Some(presents) = self.presents.as_mut() { + presents.push(line, timing.drawable, timing.continuous, &mut self.out); + return; + } + line.push('}'); + writeln!(self.out, "{line}").ok(); + } +} + +impl Drop for Trace { + fn drop(&mut self) { + if let Some((stats, app)) = &self.surface { + eprintln!("rune: frames {}", crate::frame::surface_stats::read(stats).summary()); + if let Some(app) = app { eprintln!("rune: app {}", app()); } + } + if self.presents.is_none() { return; } + self.settle_presents(crate::frame::present_time::SETTLE); + self.out.flush().ok(); + if let Some(summary) = std::fs::read_to_string(&self.path).ok().as_deref().and_then(crate::frame::present_time::Summary::of_trace) { + eprintln!("{summary}"); + } + } +} + +#[cfg(any(test, feature = "hot"))] +#[inline(always)] +pub(crate) fn tree_json<S>(rt: &Runtime<S>, real_t: f64) -> Value { + tree_json_core(rt.core(), real_t) +} + +pub(crate) fn tree_json_core(rt: &crate::runtime::RuntimeCore, real_t: f64) -> Value { + let videos = rt.tree.videos(); + let els: Vec<Value> = rt + .elements() + .iter() + .map(|e| { + let mut v = json!({ + "path": e.path, + "role": e.role, + "rect": e.rect.map(r2), + "opacity": (e.opacity * 1000.0).round() / 1000.0, + "scale": (e.scale * 10000.0).round() / 10000.0, + "blur": r2(e.blur), + "focusable": e.focusable, "focused": e.focused, + "focusVisible": e.focus_visible, "inert": e.inert, + "loopPhase": e.loop_phase, + "fill": e.fill.hex(), + }); + if let Some(k) = &e.key { + v["key"] = k.clone().into(); + } + if let Some(l) = &e.label { + v["label"] = l.clone().into(); + } + if let Some(t) = &e.text { + v["text"] = t.clone().into(); + } + if let Some(c) = e.text_color { + v["color"] = c.hex().into(); + } + if let Some(h) = &e.help { + v["help"] = h.clone().into(); + } + if let Some(s) = &e.selected { + v["selected"] = s.clone().into(); + } + if let Some(l) = e.level { + v["level"] = l.into(); + } + if let Some(x) = e.expanded { + v["expanded"] = x.into(); + } + if e.item_selected { + v["itemSelected"] = true.into(); + } + if rt.tree.element_is_secure(&e.path) { + v["secure"] = true.into(); + } + if e.rect.iter().zip(e.target.iter()).any(|(a, b)| (a - b).abs() > 0.01) { + v["target"] = e.target.map(r2).to_vec().into(); + } + if e.moving { + v["moving"] = true.into(); + } + if e.exiting { + v["exiting"] = true.into(); + } + if e.hover > 0.001 { + v["hover"] = r2(e.hover).into(); + } + if e.press > 0.001 { + v["press"] = r2(e.press).into(); + } + if e.drag_out { + v["dragOut"] = true.into(); + } + if let Some(c) = e.caret { + v["caret"] = c.map(r2).to_vec().into(); + } + if let Some(r) = e.edit_range { + v["selection"] = r.to_vec().into(); + } + if let Some(video) = videos.get(&e.path) { + v["video"] = video_json(video); + } + v + }) + .collect(); + let mut tree = json!({ + "t": real_t, + "anim_t": rt.t, + "viewport": [rt.viewport.0, rt.viewport.1], + "scale": rt.env.scale, + "dark_system": rt.env.system_dark, + "reduced_motion": rt.reduced_motion, + "time_scale": rt.time_scale, + "animating": rt.animating, + "elements": els, + "warnings": rt.commit.key_warnings().unwrap_or_default(), + }); + if let Some(menu) = rt.popup_json() { tree["popupMenu"] = menu; } + if let Some(dialog) = rt.file_dialog_json() { tree["fileDialog"] = dialog; } + // Where the input method's candidate window opens: the window's IME area, in view points. + if let Some(area) = rt.ime_area { tree["imeArea"] = area.map(r2).to_vec().into(); } + // The focused field's open composition, not yet part of its text. + if let Some((text, cursor)) = rt.focused_preedit() { + tree["preedit"] = json!({ "text": text, "cursor": cursor.map(|(a, b)| [a, b]) }); + } + if let Some(title) = rt.host.window_title.current() { tree["title"] = title.into(); } + if let Some((text, rect)) = rt.help_tooltip() { tree["tooltip"] = json!({ "text": text, "rect": rect.map(r2) }); } + tree["accessibility"] = crate::a11y::dump::json(&rt.accessibility_tree(), false); + tree +} + +fn video_json(v: &crate::video::Snapshot) -> Value { + use crate::PlayerState; + let (state, error) = match &v.state { + PlayerState::Loading => ("loading", None), + PlayerState::Ready => ("ready", None), + PlayerState::Playing => ("playing", None), + PlayerState::Ended => ("ended", None), + PlayerState::Failed(e) => ("failed", Some(e.clone())), + _ => ("unknown", None), + }; + let mut out = json!({ + "kind": match v.kind { crate::video::Kind::Video => "video", crate::video::Kind::Audio => "audio" }, + "state": state, + "time": (v.time * 1000.0).round() / 1000.0, + "duration": v.duration.map(|d| (d * 1000.0).round() / 1000.0), + "size": v.size.map(|(w, h)| [w, h]), + "rate": v.rate, + "looping": v.looping, + "muted": v.muted, + }); + if let Some(e) = error { out["error"] = e.into(); } + out +} diff --git a/app/vendor/rune/crates/rune/src/tooling/virtual_desktop.rs b/app/vendor/rune/crates/rune/src/tooling/virtual_desktop.rs new file mode 100644 index 0000000..fc9da48 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/tooling/virtual_desktop.rs @@ -0,0 +1,596 @@ +//! `--desktop BACKDROP.png`: a headless run of every window an app makes, each drawn at its +//! placed frame with rounded corners and a soft shadow over a backdrop, as a screen recording of +//! the app would show them. Each window renders into its own texture with its own state; one +//! pass composites them in z-order. + + +use std::sync::Arc; + +use serde_json::json; + +use crate::AnyWindowSpec; +use crate::desktop::displays::VirtualDesktop; +use crate::render::{Gpu, OFFSCREEN_FORMAT, Offscreen, Renderer}; +use crate::tooling::headless_run::WindowFrame; +use crate::tooling::{Args, Ev, Kind, Pos, Shot, Timeline, Trace, die}; + +mod composite; +pub(crate) mod displays; +#[cfg(test)] +mod tests; +mod window; + +use composite::{Composite, DOWN, KEY_SHADOW, SHADOW, Slot, Uniform, pixels}; +pub(crate) use window::{Changes, Member, Window}; + +/// Bound on rounds of windows asking things of each other within one frame. +const PASSES: usize = 8; + +/// The windows, back to front, and which has the keyboard. +struct Desk { + members: Vec<Box<dyn Member>>, + /// Indices into `members`, bottom first. + z: Vec<usize>, + focus: Focus, + pointer: Pointer, + files: Files, + /// Output origin in global points, and points to pixels. + origin: (f32, f32), + scale: f32, +} + +/// Which window has the keyboard. Only the key window of a frontmost app has focus, and the +/// key window is kept while the app is behind, so the window it comes back with still knows. +#[derive(Clone, Copy, Debug, PartialEq)] +enum Focus { + /// No window is key; `active` says the app is still frontmost, so the next window to take + /// the keyboard knows whether it has focus. + None { active: bool }, + Key { i: usize, active: bool }, +} + +impl Focus { + fn of(key: Option<usize>, active: bool) -> Self { + match key { + Some(i) => Focus::Key { i, active }, + None => Focus::None { active }, + } + } + + /// The window the app makes key again when it comes back, and which a pop-up menu, a file + /// dialog and a shortcut try first. + fn key(self) -> Option<usize> { + match self { + Focus::None { .. } => None, + Focus::Key { i, .. } => Some(i), + } + } + + /// The window that has the keyboard now: the key window while the app is frontmost. + fn focused(self) -> Option<usize> { + match self { + Focus::Key { i, active: true } => Some(i), + Focus::None { .. } | Focus::Key { active: false, .. } => None, + } + } + + fn active(self) -> bool { + match self { + Focus::None { active } | Focus::Key { active, .. } => active, + } + } +} + +/// The window a script's file drag is over. +#[derive(Clone, Copy, Debug, PartialEq)] +enum Files { + None, + Over(usize), +} + +impl Files { + fn of(window: Option<usize>) -> Self { + match window { + Some(i) => Files::Over(i), + None => Files::None, + } + } + + fn window(self) -> Option<usize> { + match self { + Files::None => None, + Files::Over(i) => Some(i), + } + } +} + +/// Which window the pointer is over. +#[derive(Clone, Copy, Debug, PartialEq)] +enum Pointer { + /// Over the backdrop, or no window yet. + Out, + Over(usize), + /// A press on the window captured the pointer: moves and the release go to it, wherever + /// the pointer is, until the release. + Pressed(usize), +} + +impl Pointer { + fn window(self) -> Option<usize> { + match self { + Pointer::Out => None, + Pointer::Over(i) | Pointer::Pressed(i) => Some(i), + } + } +} + +impl Desk { + fn focus(&mut self, key: Option<usize>, active: bool) { + let next = Focus::of(key, active); + let before = self.focus.focused(); + let after = next.focused(); + if before != after { + if let Some(i) = before { + if self.pointer == Pointer::Pressed(i) { self.pointer = Pointer::Over(i); } + self.members[i].focus(false); + } + if let Some(i) = after { self.members[i].focus(true); } + } + self.focus = next; + } + + /// The app comes back to the front or goes behind another app: the same window stays key. + fn set_active(&mut self, active: bool) { self.focus(self.focus.key(), active); } + + /// Brings `i` to the front of its level; always-on-top windows stay above the rest. + fn front(&mut self, i: usize) { + self.z.retain(|&j| j != i); + self.z.push(i); + let members = &self.members; + self.z.sort_by_key(|&j| members[j].on_top()); + } + + /// The window that gets the keyboard when no window asks for it: the topmost visible one + /// that takes clicks. + fn topmost_visible(&self) -> Option<usize> { + self.z.iter().rev().copied().find(|&i| self.can_key(i)) + } + + /// Whether window `i` can have the keyboard: it shows and takes clicks. + fn can_key(&self, i: usize) -> bool { + self.members[i].visible() && !self.members[i].click_through() + } + + fn apply(&mut self, i: usize, changes: Changes) { + if changes.front && self.members[i].visible() { self.front(i); } + if changes.keys && self.can_key(i) { self.focus(Some(i), true); } + } + + /// A hidden window lets go of the pointer, and a hidden key window hands the keyboard to + /// the topmost visible one. + fn settle_key(&mut self) { + if self.pointer.window().is_some_and(|i| !self.members[i].visible()) { self.pointer = Pointer::Out; } + if self.focus.key().is_some_and(|k| self.can_key(k)) { return; } + let next = self.topmost_visible(); + if next != self.focus.key() { self.focus(next, self.focus.active()); } + } + + /// Applies what every window asked, again while draining one window makes requests of + /// another (a focus change runs `on_focus`, which may close its window or update others). + fn drain(&mut self, desktop: &VirtualDesktop, t: f64) { + for _ in 0..PASSES { + for i in 0..self.members.len() { + let changes = self.members[i].drain(desktop, t); + self.apply(i, changes); + } + self.settle_key(); + if !self.members.iter().any(|m| m.pending()) { return; } + } + eprintln!("rune: windows still made requests of each other after {PASSES} passes at t = {t:.3}; the rest wait a frame"); + } + + /// Steps, without time passing, each shown window whose frame no longer shows what this + /// frame's handlers asked of it, so the frame draws their result rather than a frame later. + fn catch_up(&mut self, desktop: &VirtualDesktop, t: f64) { + for _ in 0..PASSES { + let mut stepped = false; + for m in &mut self.members { + if m.visible() && m.stale() { m.advance(0.0); stepped = true; } + } + if !stepped { return; } + self.drain(desktop, t); + } + } + + /// Top-left in output pixels, rounded so window pixels land on output pixels. + fn origin_px(&self, i: usize) -> (f32, f32) { + let f = self.members[i].frame(); + (((f[0] - self.origin.0) * self.scale).round(), ((f[1] - self.origin.1) * self.scale).round()) + } + + fn origin_pt(&self, i: usize) -> (f32, f32) { + let (x, y) = self.origin_px(i); + (x / self.scale, y / self.scale) + } + + fn hit(&self, (x, y): (f32, f32)) -> Option<usize> { + self.z.iter().rev().copied().find(|&i| { + let m = &self.members[i]; + let (ox, oy) = self.origin_pt(i); + let f = m.frame(); + m.visible() && !m.click_through() && x >= ox && y >= oy && x < ox + f[2] && y < oy + f[3] + }) + } + + /// The element's centre in output points: the key window first, then front to back. + fn find(&self, key: &str) -> Option<(f32, f32)> { + let order = self.focus.key().into_iter().chain(self.z.iter().rev().copied().filter(|&i| Some(i) != self.focus.key())); + order.filter(|&i| self.members[i].visible()).find_map(|i| { + let (x, y) = self.members[i].find(key)?; + let (ox, oy) = self.origin_pt(i); + Some((x + ox, y + oy)) + }) + } + + fn pointer(&self) -> Option<(f32, f32)> { + let i = self.pointer.window()?; + let (x, y) = self.members[i].pointer()?; + let (ox, oy) = self.origin_pt(i); + Some((x + ox, y + oy)) + } + + /// Pointer input at `at` in output points: to the window a press captured, else the one under it. + fn pointer_input(&mut self, kind: &Kind, at: (f32, f32)) { + let captured = match self.pointer { + Pointer::Pressed(i) if matches!(kind, Kind::Move) || kind.is_up() => Some(i), + _ => None, + }; + let target = captured.or_else(|| self.hit(at)); + if (matches!(kind, Kind::Move) || kind.is_down()) && self.pointer.window() != target && captured.is_none() { + if let Some(h) = self.pointer.window() { self.members[h].leave(); } + self.pointer = target.map_or(Pointer::Out, Pointer::Over); + } + if kind.is_down() { + self.pointer = target.map_or(Pointer::Out, Pointer::Pressed); + match target { + // A click brings its window to the front with the keyboard, activating the app. + Some(i) => { self.front(i); self.focus(Some(i), true); } + // A click on the backdrop activates another app. + None => self.set_active(false), + } + } + if kind.is_up() && let Pointer::Pressed(i) = self.pointer { self.pointer = Pointer::Over(i); } + if let Some(i) = target { + let (ox, oy) = self.origin_pt(i); + self.members[i].input(kind, (at.0 - ox, at.1 - oy)); + } + } + + /// A script's file drag goes to the window under it, whether or not that window is key; a + /// drag that moves off a window leaves it. + fn file_input(&mut self, step: &crate::tooling::FileStep, at: (f32, f32)) { + use crate::tooling::FileStep; + let target = if matches!(step, FileStep::Leave) { self.files.window() } else { self.hit(at) }; + if let Some(old) = self.files.window().filter(|&old| Some(old) != target) { + self.members[old].input(&Kind::Files(FileStep::Leave), (0.0, 0.0)); + } + self.files = Files::of(target.filter(|_| matches!(step, FileStep::Hover(_)))); + if let Some(i) = target { + let (ox, oy) = self.origin_pt(i); + self.members[i].input(&Kind::Files(step.clone()), (at.0 - ox, at.1 - oy)); + } + } + + /// The app reopened: every window's `on_reopen` runs, then, unless one handled it or the app + /// is an accessory, the default shows a window when none does (`reopen::target`) and + /// activates the app with it in front. + fn reopen(&mut self, accessory: bool, desktop: &VirtualDesktop, t: f64) { + let candidates = |desk: &Self| -> Vec<_> { desk.members.iter().map(|m| m.reopen_candidate()).collect() }; + let has_visible = crate::platform::reopen::has_visible(&candidates(self)); + let mut handled = false; + for m in &mut self.members { handled |= m.reopen_hook(has_visible); } + if handled || accessory { return; } + // The default sees what the hooks did. + self.drain(desktop, t); + if let Some(i) = crate::platform::reopen::target(&candidates(self)) { + let changes = self.members[i].reopen(); + self.apply(i, changes); + } + } + + /// Window `i`'s frame in output points, whether it shows, and whether it has the keyboard + /// (never while another app is active). + fn state(&self, i: usize) -> ([f32; 4], bool, bool) { + let m = &self.members[i]; + let f = m.frame(); + ([f[0] - self.origin.0, f[1] - self.origin.1, f[2], f[3]], m.visible(), self.focus.focused() == Some(i)) + } + + fn snapshot(&self, i: usize, t: f64) -> WindowFrame { + let (frame, visible, focused) = self.state(i); + WindowFrame { t, key: self.members[i].key().to_owned(), frame, visible, focused } + } +} + +/// Renders `windows` composited over the `--desktop` backdrop. `selected` is the window +/// `--scene`, `--tree` and `--trace` describe. +/// `accessory` is `RunOptions::accessory`: reopening brings back no window. +pub(crate) fn run(windows: Vec<AnyWindowSpec>, selected: usize, args: Args, accessory: bool) { + let launched = crate::time::now(); + let backdrop = args.desktop.clone().expect("--desktop"); + if args.list_scenes { die("--list-scenes lists one window's scenes; drop --desktop"); } + let source = crate::tooling::read_script(&args); + let script = source.as_ref().map(crate::tooling::load_script).unwrap_or_default(); + let timeline = Timeline::of(&args, &script).unwrap_or_else(|e| die(&e)); + let scale = args.scale.unwrap_or(2.0); + let desktop = crate::tooling::desktop(&args, source.as_ref()); + let primary = desktop.primary().frame.map(|v| v as f32); + let size = args.size.unwrap_or((primary[2], primary[3])); + let frames_log = Arc::new(std::sync::Mutex::new(Vec::new())); + crate::tooling::headless_run::publish(crate::tooling::headless_run::HeadlessRun { + script: args.script.clone(), + events: script.iter().map(Ev::public).collect(), + scale, + fps: timeline.fps, + size, + start: timeline.start_frame as f64 * timeline.dt, + frames: timeline.frames, + end: timeline.last_frame as f64 * timeline.dt, + desktop: Some(backdrop.clone()), + windows: frames_log.clone(), + }); + + let mut members: Vec<Box<dyn Member>> = windows.into_iter().enumerate() + .map(|(i, w)| w.desktop(&args, i == selected, scale)).collect(); + for m in &mut members { m.start(&desktop); } + let Timeline { fps, dt, start_frame, frames, snap_frame, last_frame } = timeline; + let mut trace = args.trace.as_ref().map(|p| { + let f = members[selected].frame(); + members[selected].trace_on(); + let mut trace = Trace::open(p, (f[2], f[3]), fps, scale); + trace.all = args.trace_all; + trace + }); + let n = members.len(); + let mut desk = Desk { + members, z: (0..n).collect(), focus: Focus::of(None, true), pointer: Pointer::Out, files: Files::None, + origin: (primary[0], primary[1]), scale, + }; + let members = &desk.members; + desk.z.sort_by_key(|&i| members[i].on_top()); + let initial = desk.topmost_visible(); + desk.focus(initial, true); + + let t0 = crate::time::now(); + let features = desk.members.iter().fold(wgpu::Features::empty(), |f, m| f | m.features()); + let gpu = Gpu::try_with_features(Gpu::instance_for(features), None, features).unwrap_or_else(|e| die(&e)); + let max = gpu.device.limits().max_texture_dimension_2d; + let (wp, hp) = pixels(size, scale, max).unwrap_or_else(|| die(&format!( + "--desktop: the output, {}x{} points at --scale {scale}, must be 1 to {max} pixels a side", size.0, size.1))); + let comp = Composite::new(&gpu, &backdrop, (wp, hp)); + let mut writer = crate::tooling::record::Writer::new((wp, hp)); + if let Some(path) = &args.video { + writer.video(path, fps).unwrap_or_else(|e| die(&e)); + } + let target = Offscreen::new(&gpu.device, wp, hp); + let mut readback = crate::tooling::record::Readback::new(&gpu.device, &target, crate::tooling::record::DEPTH); + let mut slots: Vec<Option<Slot>> = (0..n).map(|_| None).collect(); + let mut overlay = (args.keys.is_some() || args.pointer) + .then(|| (crate::input::keycaps::Overlay::new(size, scale, args.keys, args.keys_theme, args.pointer), Renderer::new(&gpu.device, OFFSCREEN_FORMAT))); + let dark = args.theme.as_deref() != Some("light"); + let init_ms = t0.elapsed().as_secs_f64() * 1000.0; + + let mut strip: Vec<Vec<u8>> = Vec::new(); + let crops_px: Vec<[u32; 4]> = args.crops.iter().map(|c| c.map(|v| (v * scale).round() as u32)).collect(); + let gap = (4.0 * scale) as u32; + let mut frames_written = 0usize; + let has_video = writer.has_video(); + let mut deliver = |shot: Shot, px: Vec<u8>| { + if shot.dump { + if args.strip.is_some() { strip.push(crate::tooling::tile(&px, wp, hp, &crops_px, gap)); } + if let Some(dir) = &args.out { + writer.png(dir.join(format!("frame_{:04}.png", shot.k - start_frame)), px.clone()).unwrap_or_else(|e| die(&e)); + } + } + if shot.snap { writer.png(args.snap.clone().unwrap(), px.clone()).unwrap_or_else(|e| die(&e)); } + if shot.video { + frames_written += 1; + writer.frame(px).unwrap_or_else(|e| die(&e)); + } + }; + + // Logs a window's frame when it moves, shows, hides or takes or loses the keyboard. + let mut recorded = vec![None; n]; + let mut record = |desk: &Desk, t: f64| { + let mut log = frames_log.lock().unwrap(); + for (i, last) in recorded.iter_mut().enumerate() { + let now = desk.state(i); + if *last != Some(now) { + log.push(desk.snapshot(i, t)); + *last = Some(now); + } + } + }; + + // Events at t = 0 find keys and hit elements in a laid-out first frame (see `headless_configured`). + if script.iter().find(|e| !matches!(e.kind, Kind::Mark(_))).is_some_and(|e| e.t <= 1e-9) { + desk.drain(&desktop, 0.0); + for m in &mut desk.members { m.advance(0.0); } + desk.drain(&desktop, 0.0); + } + + let wall = crate::time::now(); + let mut cpu_ms = Vec::new(); + let mut next_ev = 0; + let mut last_down = (0.0f32, 0.0f32); + let mut drawn: Vec<(usize, bool)> = Vec::with_capacity(n); + for k in 0..=last_frame { + let real_t = k as f64 * dt; + let frame_start = crate::time::now(); + while next_ev < script.len() && script[next_ev].t <= real_t + 1e-9 { + let e = &script[next_ev]; + next_ev += 1; + let at = || match &e.pos { + Pos::Xy(x, y) => (*x, *y), + Pos::Key(key) => desk.find(key).unwrap_or_else(|| die(&format!("script: no element with key {key:?} in a visible window"))), + Pos::Rel(_, _) if e.kind.at_pointer() => desk.pointer().unwrap_or((0.0, 0.0)), + Pos::Rel(dx, dy) => (last_down.0 + dx, last_down.1 + dy), + }; + let (x, y) = at(); + match &e.kind { + Kind::Mark(_) => {} + Kind::Focus(focused) => desk.set_active(*focused), + Kind::Reopen => desk.reopen(accessory, &desktop, real_t), + Kind::Shortcut(shortcut) => fire(&desk, |m| m.shortcut(shortcut)).unwrap_or_else(|e| die(&format!("script shortcut: {e}"))), + Kind::Menu(item) => fire(&desk, |m| m.menu(item)).unwrap_or_else(|e| die(&format!("script menu: {e}"))), + Kind::PopupMenu(picked) => { + let open = desk.focus.key().into_iter().chain(desk.z.iter().rev().copied()).find(|&i| desk.members[i].popup_open()); + let i = open.or(desk.focus.key()).unwrap_or(selected); + desk.members[i].resolve_popup(picked.as_deref()).unwrap_or_else(|e| die(&format!("script pop-up menu: {e}"))); + } + Kind::FileDialog(path) => { + let open = desk.focus.key().into_iter().chain(desk.z.iter().rev().copied()).find(|&i| desk.members[i].file_dialog_open()); + let i = open.or(desk.focus.key()).unwrap_or(selected); + desk.members[i].resolve_file_dialog(path.clone()).unwrap_or_else(|e| die(&format!("script file dialog: {e}"))); + } + // While another app is active, as after a click on the backdrop, keys go to it. + Kind::Key(..) | Kind::KeyUp(_) | Kind::Physical(_) | Kind::PhysicalKey(..) | Kind::Paste(_) | Kind::Ime(_) => { + if let Some(i) = desk.focus.focused() { desk.members[i].input(&e.kind, (x, y)); } + } + Kind::Files(step) => desk.file_input(step, (x, y)), + &Kind::Resize(dw, dh) => { + let i = desk.focus.key().unwrap_or(selected); + desk.members[i].resize_by(dw, dh); + } + Kind::OpenUrl(_) => die("script open_url: a link opens in a single window's run (`--script` without a desktop)"), + // The rest are pointer input. + kind => { + if kind.is_down() { last_down = (x, y); } + desk.pointer_input(&e.kind, (x, y)); + } + } + if let Some((ov, _)) = overlay.as_mut() { + match &e.kind { + Kind::Key(key, _) | Kind::PhysicalKey(_, key, _) => ov.key(e.t, key), + Kind::Shortcut(chord) => ov.chord(e.t, chord), + &Kind::Physical(crate::PhysicalInput::Key { key, mods, pressed: true, .. }) => { + if let Ok(chord) = crate::Shortcut::from_physical_key(key, mods) { ov.chord(e.t, &chord) } + } + Kind::Down => ov.press(e.t, x, y), + _ => {} + } + } + } + desk.drain(&desktop, real_t); + let step = if k == 0 { 0.0 } else { dt }; + for m in &mut desk.members { m.advance(step); } + // Handlers that ran this frame may show, hide, place, focus or close windows, or update + // a window that already stepped. + desk.drain(&desktop, real_t); + desk.catch_up(&desktop, real_t); + record(&desk, real_t); + let update_ms = frame_start.elapsed().as_secs_f64() * 1000.0; + + let key = desk.focus.focused(); + drawn.clear(); + for &i in &desk.z { + let m = &mut desk.members[i]; + if !m.visible() { continue; } + let f = m.frame(); + let px = (((f[2] * scale).round() as u32).max(1), ((f[3] * scale).round() as u32).max(1)); + if px.0.max(px.1) > max { + die(&format!("--desktop: window {:?} is {}x{} pixels, over the GPU's {max} a side", m.key(), px.0, px.1)); + } + if slots[i].as_ref().is_none_or(|s| s.px != px) { slots[i] = Some(Slot::new(&gpu.device, &comp, px, scale)); } + let slot = slots[i].as_ref().unwrap(); + m.render(&gpu, slot, px, step, update_ms, frame_start); + let (ox, oy) = desk.origin_px(i); + let (sigma, offset, opacity) = if key == Some(i) { KEY_SHADOW } else { SHADOW }; + slot.write(&gpu.queue, Uniform { + origin: [ox, oy], size: [px.0 as f32, px.1 as f32], out_size: [wp as f32, hp as f32], + shadow_offset: [0.0, offset * scale], mask_size: [slot.mask.0 as f32, slot.mask.1 as f32], + radius: desk.members[i].radius() * scale, pad: slot.pad as f32, sigma: sigma * scale / DOWN as f32, + opacity, _unused: [0.0; 2], + }); + drawn.push((i, desk.members[i].shadow())); + } + let mut enc = gpu.device.create_command_encoder(&Default::default()); + comp.draw(&mut enc, &target.view, drawn.iter().map(|&(i, shadow)| (slots[i].as_ref().unwrap(), shadow))); + if let Some((ov, ui)) = overlay.as_mut() { + let app_dark = key.and_then(|i| desk.members[i].backdrop_dark()).unwrap_or(dark); + let ort = ov.frame(real_t, step, app_dark); + if !ort.instances.is_empty() { + ui.set_fade_stops(ort.fade_stops()); + ui.prepare_ui(&gpu.device, &gpu.queue, &mut ort.text.atlas, &ort.instances, (wp, hp)); + ui.draw_over(&mut enc, &target.view); + } + } + let in_range = k >= start_frame && k < start_frame + frames; + let shot = Shot { + k, + dump: in_range && (args.out.is_some() || args.strip.is_some()) && (k - start_frame).is_multiple_of(args.every), + video: in_range && has_video, + snap: k == snap_frame && args.snap.is_some(), + }; + let first_pixels = args.first_pixels && k == 0; + let want_pixels = shot.dump || shot.video || shot.snap || first_pixels; + if want_pixels { + for (shot, px) in readback.make_room(&gpu.device) { deliver(shot, px); } + readback.copy(&mut enc, &target, shot); + } + gpu.queue.submit([enc.finish()]); + if want_pixels { readback.submitted(); } + let ms = frame_start.elapsed().as_secs_f64() * 1000.0; + cpu_ms.push(ms); + if let Some(tr) = trace.as_mut() { desk.members[selected].trace(tr, real_t * 1000.0, ms); } + if first_pixels { + let done = readback.finish(&gpu.device); + let marker = json!({ + "headless_ms": launched.elapsed().as_secs_f64() * 1000.0, "gpu_init_ms": init_ms, "frame_cpu_ms": ms, + "pixel_bytes": done.last().map_or(0, |(_, px)| px.len()), + }); + println!("rune-first-pixels {marker}"); + for (shot, px) in done { deliver(shot, px); } + } else if want_pixels { + for (shot, px) in readback.ready(&gpu.device) { deliver(shot, px); } + } + if k == snap_frame && let Some(p) = &args.tree { + let mut tree = desk.members[selected].tree(real_t); + tree["windows"] = (0..n).map(|i| { + let f = desk.snapshot(i, real_t); + json!({ "key": f.key, "frame": f.frame, "visible": f.visible, "focused": f.focused }) + }).collect(); + let text = serde_json::to_string_pretty(&tree).unwrap(); + std::fs::write(p, text).unwrap_or_else(|e| die(&format!("{}: {e}", p.display()))); + } + } + for (shot, px) in readback.finish(&gpu.device) { deliver(shot, px); } + for m in &mut desk.members { m.flush_interaction(); } + drop(deliver); + if let Some(video) = writer.finish().unwrap_or_else(|e| die(&e)) { + eprintln!("rune: wrote {} ({frames_written} frames at {fps} fps)", video.display()); + } + rune_gpu::health::poll(&gpu.device, wgpu::PollType::wait_indefinitely()).ok(); + if let Some(p) = &args.strip { crate::tooling::write_strip(p, &strip, (wp, hp), &crops_px, gap, args.cols); } + let wall = wall.elapsed().as_secs_f64(); + let mean = cpu_ms.iter().sum::<f64>() / cpu_ms.len() as f64; + eprintln!("rune: desktop of {n} windows, {} frames in {wall:.2} s wall, gpu init {init_ms:.1} ms, frame cpu mean {mean:.3} ms", last_frame + 1); + for m in &mut desk.members { + if let Some(s) = m.summary(&gpu.device) { eprintln!("{s}"); } + } +} + +/// Sends a shortcut or menu pick to the key window's app, else the first other app that knows it. +fn fire<E>(desk: &Desk, f: impl Fn(&dyn Member) -> Result<(), E>) -> Result<(), E> { + let key = desk.focus.key(); + let order = key.into_iter().chain(desk.z.iter().rev().copied().filter(|&i| Some(i) != key)); + let mut first = None; + for i in order { + match f(desk.members[i].as_ref()) { + Ok(()) => return Ok(()), + Err(e) => { first.get_or_insert(e); } + } + } + first.map_or(Ok(()), Err) +} + diff --git a/app/vendor/rune/crates/rune/src/tooling/virtual_desktop/composite.rs b/app/vendor/rune/crates/rune/src/tooling/virtual_desktop/composite.rs new file mode 100644 index 0000000..75b827b --- /dev/null +++ b/app/vendor/rune/crates/rune/src/tooling/virtual_desktop/composite.rs @@ -0,0 +1,374 @@ +//! GPU backdrop, rounded-window, and blurred-shadow compositing for `--desktop`. + +use std::path::Path; + +use crate::render::{Gpu, OFFSCREEN_FORMAT}; +use crate::tooling::die; + +/// Shadows of the key window and of the others: blur sigma, downward offset (points), opacity. +pub(super) const KEY_SHADOW: (f32, f32, f32) = (14.0, 14.0, 0.5); +pub(super) const SHADOW: (f32, f32, f32) = (6.0, 5.0, 0.32); +/// Shadow masks are this many window pixels to a texel. +pub(super) const DOWN: u32 = 4; +/// Largest backdrop image, in pixels per side, decoded. +pub(super) const MAX_BACKDROP: u32 = 16384; + +#[repr(C)] +#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)] +pub(super) struct Uniform { + /// Window top-left and size, in output pixels. + pub(super) origin: [f32; 2], + pub(super) size: [f32; 2], + pub(super) out_size: [f32; 2], + pub(super) shadow_offset: [f32; 2], + pub(super) mask_size: [f32; 2], + pub(super) radius: f32, + /// Window pixels of shadow mask around the window. + pub(super) pad: f32, + /// Blur sigma in mask texels. + pub(super) sigma: f32, + pub(super) opacity: f32, + pub(super) _unused: [f32; 2], +} + +const _: () = { + use std::mem::{offset_of, size_of}; + assert!(size_of::<Uniform>() == 64); + assert!(offset_of!(Uniform, origin) == 0); + assert!(offset_of!(Uniform, size) == 8); + assert!(offset_of!(Uniform, out_size) == 16); + assert!(offset_of!(Uniform, shadow_offset) == 24); + assert!(offset_of!(Uniform, mask_size) == 32); + assert!(offset_of!(Uniform, radius) == 40); + assert!(offset_of!(Uniform, pad) == 44); + assert!(offset_of!(Uniform, sigma) == 48); + assert!(offset_of!(Uniform, opacity) == 52); + assert!(offset_of!(Uniform, _unused) == 56); +}; + +pub(super) const SHADER: &str = r#" +struct W { + origin: vec2<f32>, + size: vec2<f32>, + out_size: vec2<f32>, + shadow_offset: vec2<f32>, + mask_size: vec2<f32>, + radius: f32, + pad: f32, + sigma: f32, + opacity: f32, + unused: vec2<f32>, +}; +@group(0) @binding(0) var<uniform> w: W; +@group(0) @binding(1) var tex: texture_2d<f32>; +@group(0) @binding(2) var samp: sampler; + +const DOWN: f32 = 4.0; + +fn corner(i: u32) -> vec2<f32> { + let c = array(vec2(0.0, 0.0), vec2(1.0, 0.0), vec2(0.0, 1.0), vec2(0.0, 1.0), vec2(1.0, 0.0), vec2(1.0, 1.0)); + return c[i]; +} +fn clip(p: vec2<f32>) -> vec4<f32> { + return vec4(p.x / w.out_size.x * 2.0 - 1.0, 1.0 - p.y / w.out_size.y * 2.0, 0.0, 1.0); +} +@vertex fn vs_full(@builtin(vertex_index) i: u32) -> @builtin(position) vec4<f32> { + let points = array(vec2(-1.0, -1.0), vec2(3.0, -1.0), vec2(-1.0, 3.0)); + return vec4(points[i], 0.0, 1.0); +} +@vertex fn vs_window(@builtin(vertex_index) i: u32) -> @builtin(position) vec4<f32> { + return clip(w.origin + corner(i) * w.size); +} +@vertex fn vs_shadow(@builtin(vertex_index) i: u32) -> @builtin(position) vec4<f32> { + return clip(w.origin + w.shadow_offset - vec2(w.pad) + corner(i) * (w.size + 2.0 * w.pad)); +} + +// Signed distance to the window's rounded rect; p in window pixels. +fn rounded(p: vec2<f32>) -> f32 { + let half = w.size * 0.5; + let r = min(w.radius, min(half.x, half.y)); + let q = abs(p - half) - half + vec2(r); + return length(max(q, vec2(0.0))) + min(max(q.x, q.y), 0.0) - r; +} + +@fragment fn fs_backdrop(@builtin(position) p: vec4<f32>) -> @location(0) vec4<f32> { + return textureLoad(tex, vec2<i32>(p.xy), 0); +} + +// Premultiplied window pixels, cut to the rounded rect. +@fragment fn fs_window(@builtin(position) p: vec4<f32>) -> @location(0) vec4<f32> { + let local = p.xy - w.origin; + let color = textureLoad(tex, vec2<i32>(floor(local)), 0); + return color * clamp(0.5 - rounded(local), 0.0, 1.0); +} + +// The window's alpha inside its corners, DOWN x DOWN pixels to a texel. +@fragment fn fs_mask(@builtin(position) p: vec4<f32>) -> @location(0) vec4<f32> { + let base = floor(p.xy) * DOWN - vec2(w.pad); + var sum = 0.0; + for (var y = 0; y < 4; y++) { + for (var x = 0; x < 4; x++) { + let q = base + vec2(f32(x), f32(y)); + if all(q >= vec2(0.0)) && all(q < w.size) { + sum += textureLoad(tex, vec2<i32>(q), 0).a * clamp(0.5 - rounded(q + 0.5), 0.0, 1.0); + } + } + } + return vec4(sum / 16.0, 0.0, 0.0, 1.0); +} + +fn blur(p: vec2<f32>, axis: vec2<i32>) -> vec4<f32> { + let c = vec2<i32>(p); + let dims = vec2<i32>(textureDimensions(tex)); + let sigma = max(w.sigma, 0.5); + let r = i32(ceil(sigma * 3.0)); + var sum = 0.0; + var total = 0.0; + for (var k = -r; k <= r; k++) { + let q = c + axis * k; + let weight = exp(-f32(k * k) / (2.0 * sigma * sigma)); + total += weight; + if all(q >= vec2(0)) && all(q < dims) { + sum += weight * textureLoad(tex, q, 0).r; + } + } + return vec4(sum / total, 0.0, 0.0, 1.0); +} +@fragment fn fs_blur_x(@builtin(position) p: vec4<f32>) -> @location(0) vec4<f32> { return blur(p.xy, vec2(1, 0)); } +@fragment fn fs_blur_y(@builtin(position) p: vec4<f32>) -> @location(0) vec4<f32> { return blur(p.xy, vec2(0, 1)); } + +@fragment fn fs_shadow(@builtin(position) p: vec4<f32>) -> @location(0) vec4<f32> { + let m = (p.xy - w.origin - w.shadow_offset + vec2(w.pad)) / DOWN; + let a = textureSample(tex, samp, m / w.mask_size).r * w.opacity; + return vec4(0.0, 0.0, 0.0, a); +} +"#; + +const MASK_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::R16Float; + +/// The backdrop and the pipelines that draw windows and their shadows over it. +pub(super) struct Composite { + layout: wgpu::BindGroupLayout, + sampler: wgpu::Sampler, + backdrop: wgpu::BindGroup, + full: wgpu::RenderPipeline, + window: wgpu::RenderPipeline, + shadow: wgpu::RenderPipeline, + mask: wgpu::RenderPipeline, + blur: [wgpu::RenderPipeline; 2], +} + +impl Composite { + pub(super) fn new(gpu: &Gpu, backdrop: &Path, size: (u32, u32)) -> Composite { + let device = &gpu.device; + let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor { + label: Some("desktop"), source: wgpu::ShaderSource::Wgsl(SHADER.into()), + }); + let fragment = wgpu::ShaderStages::FRAGMENT; + let layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + label: Some("desktop"), + entries: &[ + wgpu::BindGroupLayoutEntry { + binding: 0, visibility: wgpu::ShaderStages::VERTEX | fragment, count: None, + ty: wgpu::BindingType::Buffer { ty: wgpu::BufferBindingType::Uniform, has_dynamic_offset: false, min_binding_size: None }, + }, + wgpu::BindGroupLayoutEntry { + binding: 1, visibility: fragment, count: None, + ty: wgpu::BindingType::Texture { sample_type: wgpu::TextureSampleType::Float { filterable: true }, + view_dimension: wgpu::TextureViewDimension::D2, multisampled: false }, + }, + wgpu::BindGroupLayoutEntry { binding: 2, visibility: fragment, count: None, ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering) }, + ], + }); + let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + label: Some("desktop"), bind_group_layouts: &[Some(&layout)], immediate_size: 0, + }); + let pipeline = |vs: &str, fs: &str, format: wgpu::TextureFormat, blend: Option<wgpu::BlendState>| { + device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { + label: Some(fs), layout: Some(&pipeline_layout), + vertex: wgpu::VertexState { module: &shader, entry_point: Some(vs), compilation_options: Default::default(), buffers: &[] }, + primitive: Default::default(), depth_stencil: None, multisample: Default::default(), + fragment: Some(wgpu::FragmentState { module: &shader, entry_point: Some(fs), compilation_options: Default::default(), + targets: &[Some(wgpu::ColorTargetState { format, blend, write_mask: wgpu::ColorWrites::ALL })] }), + multiview_mask: None, cache: None, + }) + }; + let over = Some(wgpu::BlendState::PREMULTIPLIED_ALPHA_BLENDING); + let sampler = device.create_sampler(&wgpu::SamplerDescriptor { + label: Some("desktop shadow"), mag_filter: wgpu::FilterMode::Linear, min_filter: wgpu::FilterMode::Linear, ..Default::default() + }); + let pixels = fit_backdrop(backdrop, size).unwrap_or_else(|e| die(&e)); + let (texture, view) = new_texture(device, "desktop backdrop", size, OFFSCREEN_FORMAT, wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST); + gpu.queue.write_texture( + wgpu::TexelCopyTextureInfo { texture: &texture, mip_level: 0, origin: wgpu::Origin3d::ZERO, aspect: wgpu::TextureAspect::All }, + &pixels, + wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(size.0 * 4), rows_per_image: Some(size.1) }, + wgpu::Extent3d { width: size.0, height: size.1, depth_or_array_layers: 1 }, + ); + let uniform = uniform_buffer(device); + let backdrop = bind(device, &layout, &uniform, &view, &sampler); + Composite { + full: pipeline("vs_full", "fs_backdrop", OFFSCREEN_FORMAT, None), + window: pipeline("vs_window", "fs_window", OFFSCREEN_FORMAT, over), + shadow: pipeline("vs_shadow", "fs_shadow", OFFSCREEN_FORMAT, over), + mask: pipeline("vs_full", "fs_mask", MASK_FORMAT, None), + blur: [pipeline("vs_full", "fs_blur_x", MASK_FORMAT, None), pipeline("vs_full", "fs_blur_y", MASK_FORMAT, None)], + layout, sampler, backdrop, + } + } + + /// The backdrop, then each window's shadow and pixels, bottom first. + pub(super) fn draw<'a>(&self, enc: &mut wgpu::CommandEncoder, target: &wgpu::TextureView, windows: impl Iterator<Item = (&'a Slot, bool)> + Clone) { + for (slot, _) in windows.clone().filter(|(_, shadow)| *shadow) { + let passes = [(&self.mask, &slot.window, 0), (&self.blur[0], &slot.masks[0].2, 1), (&self.blur[1], &slot.masks[1].2, 0)]; + for (pipeline, source, into) in passes { + let mut pass = begin(enc, &slot.masks[into].1, wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT)); + pass.set_pipeline(pipeline); + pass.set_bind_group(0, source, &[]); + pass.draw(0..3, 0..1); + } + } + let mut pass = begin(enc, target, wgpu::LoadOp::Clear(wgpu::Color::BLACK)); + pass.set_pipeline(&self.full); + pass.set_bind_group(0, &self.backdrop, &[]); + pass.draw(0..3, 0..1); + for (slot, shadow) in windows { + if shadow { + pass.set_pipeline(&self.shadow); + pass.set_bind_group(0, &slot.masks[0].2, &[]); + pass.draw(0..6, 0..1); + } + pass.set_pipeline(&self.window); + pass.set_bind_group(0, &slot.window, &[]); + pass.draw(0..6, 0..1); + } + } +} + +/// One window's texture, its shadow masks and what binds them. +pub(crate) struct Slot { + pub(super) px: (u32, u32), + pub(super) view: wgpu::TextureView, + pub(super) srgb_blend_view: wgpu::TextureView, + _texture: wgpu::Texture, + /// Ping-pong masks: texture, view, and a bind group that reads it. + masks: [(wgpu::Texture, wgpu::TextureView, wgpu::BindGroup); 2], + pub(super) mask: (u32, u32), + pub(super) pad: u32, + uniform: wgpu::Buffer, + window: wgpu::BindGroup, +} + +impl Slot { + pub(super) fn new(device: &wgpu::Device, comp: &Composite, px: (u32, u32), scale: f32) -> Slot { + let usage = wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING; + let non_srgb = OFFSCREEN_FORMAT.remove_srgb_suffix(); + let texture = device.create_texture(&wgpu::TextureDescriptor { + label: Some("desktop window"), + size: wgpu::Extent3d { width: px.0.max(1), height: px.1.max(1), depth_or_array_layers: 1 }, + mip_level_count: 1, sample_count: 1, dimension: wgpu::TextureDimension::D2, + format: OFFSCREEN_FORMAT, usage, view_formats: &[non_srgb], + }); + let view = texture.create_view(&Default::default()); + let srgb_blend_view = texture.create_view(&wgpu::TextureViewDescriptor { + format: Some(non_srgb), + ..Default::default() + }); + // Room for the key window's blur, whole mask texels on each side. + let pad = ((KEY_SHADOW.0 * scale * 3.0) / DOWN as f32).ceil() as u32 * DOWN; + let mask = ((px.0 + 2 * pad).div_ceil(DOWN), (px.1 + 2 * pad).div_ceil(DOWN)); + let uniform = uniform_buffer(device); + let masks = [0, 1].map(|_| { + let (t, v) = new_texture(device, "desktop shadow", mask, MASK_FORMAT, usage); + let b = bind(device, &comp.layout, &uniform, &v, &comp.sampler); + (t, v, b) + }); + let window = bind(device, &comp.layout, &uniform, &view, &comp.sampler); + Slot { px, view, srgb_blend_view, _texture: texture, masks, mask, pad, uniform, window } + } + + pub(super) fn write(&self, queue: &wgpu::Queue, uniform: Uniform) { + queue.write_buffer(&self.uniform, 0, bytemuck::bytes_of(&uniform)); + } +} + +fn begin<'e>(enc: &'e mut wgpu::CommandEncoder, view: &wgpu::TextureView, load: wgpu::LoadOp<wgpu::Color>) -> wgpu::RenderPass<'e> { + enc.begin_render_pass(&wgpu::RenderPassDescriptor { + label: Some("desktop"), + color_attachments: &[Some(wgpu::RenderPassColorAttachment { + view, depth_slice: None, resolve_target: None, ops: wgpu::Operations { load, store: wgpu::StoreOp::Store }, + })], + depth_stencil_attachment: None, timestamp_writes: None, occlusion_query_set: None, multiview_mask: None, + }) +} + +fn new_texture(device: &wgpu::Device, label: &str, size: (u32, u32), format: wgpu::TextureFormat, usage: wgpu::TextureUsages) -> (wgpu::Texture, wgpu::TextureView) { + let texture = device.create_texture(&wgpu::TextureDescriptor { + label: Some(label), size: wgpu::Extent3d { width: size.0.max(1), height: size.1.max(1), depth_or_array_layers: 1 }, + mip_level_count: 1, sample_count: 1, dimension: wgpu::TextureDimension::D2, format, usage, view_formats: &[], + }); + let view = texture.create_view(&Default::default()); + (texture, view) +} + +fn uniform_buffer(device: &wgpu::Device) -> wgpu::Buffer { + device.create_buffer(&wgpu::BufferDescriptor { + label: Some("desktop window"), size: std::mem::size_of::<Uniform>() as u64, + usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, mapped_at_creation: false, + }) +} + +fn bind(device: &wgpu::Device, layout: &wgpu::BindGroupLayout, uniform: &wgpu::Buffer, view: &wgpu::TextureView, sampler: &wgpu::Sampler) -> wgpu::BindGroup { + device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("desktop"), layout, + entries: &[ + wgpu::BindGroupEntry { binding: 0, resource: uniform.as_entire_binding() }, + wgpu::BindGroupEntry { binding: 1, resource: wgpu::BindingResource::TextureView(view) }, + wgpu::BindGroupEntry { binding: 2, resource: wgpu::BindingResource::Sampler(sampler) }, + ], + }) +} + +/// The backdrop scaled to cover `size` pixels, centred and cropped, as opaque sRGB RGBA. +pub(super) fn fit_backdrop(path: &Path, (w, h): (u32, u32)) -> Result<Vec<u8>, String> { + let fail = |e: ::image::ImageError| format!("{}: {e}", path.display()); + let (iw, ih) = ::image::image_dimensions(path).map_err(fail)?; + if iw.max(ih) > MAX_BACKDROP { + return Err(format!("{}: {iw}x{ih} pixels; a backdrop is at most {MAX_BACKDROP} pixels a side", path.display())); + } + let image = ::image::open(path).map_err(fail)?.into_rgba8(); + let (iw, ih) = image.dimensions(); + // The centred part of the source with the output's aspect, then scaled to the output. + let (cw, ch) = if u64::from(iw) * u64::from(h) > u64::from(ih) * u64::from(w) { + (((f64::from(ih) * f64::from(w) / f64::from(h)).round() as u32).clamp(1, iw), ih) + } else { + (iw, ((f64::from(iw) * f64::from(h) / f64::from(w)).round() as u32).clamp(1, ih)) + }; + let crop = ::image::imageops::crop_imm(&image, (iw - cw) / 2, (ih - ch) / 2, cw, ch); + let image = if (cw, ch) == (w, h) { crop.to_image() } else { ::image::imageops::resize(&*crop, w, h, ::image::imageops::FilterType::CatmullRom) }; + let len = (w as usize).checked_mul(h as usize).and_then(|n| n.checked_mul(4)).ok_or_else(|| format!("{w}x{h} pixels is too large"))?; + let mut out = Vec::with_capacity(len); + for p in image.pixels() { + let [r, g, b, a] = p.0; + if a == 255 { + out.extend([r, g, b, 255]); + } else if a == 0 { + out.extend([0, 0, 0, 255]); + } else { + let alpha = f32::from(a) / 255.0; + let over = |c: u8| (crate::color::srgb_encode(crate::color::srgb_decode(f32::from(c) / 255.0) * alpha) * 255.0).round() as u8; + out.extend([over(r), over(g), over(b), 255]); + } + } + Ok(out) +} + +/// `size` points at `scale` in whole pixels, when a texture of at most `max` a side holds them. +pub(super) fn pixels(size: (f32, f32), scale: f32, max: u32) -> Option<(u32, u32)> { + let side = |v: f32| { + let px = (v * scale).round(); + (px >= 1.0 && px <= max as f32).then_some(px as u32) + }; + Some((side(size.0)?, side(size.1)?)) +} + diff --git a/app/vendor/rune/crates/rune/src/tooling/virtual_desktop/displays.rs b/app/vendor/rune/crates/rune/src/tooling/virtual_desktop/displays.rs new file mode 100644 index 0000000..0fba18a --- /dev/null +++ b/app/vendor/rune/crates/rune/src/tooling/virtual_desktop/displays.rs @@ -0,0 +1,184 @@ +//! The displays and pointer a headless run pretends to have, so `place()` resolves there. +//! A `--script` object may set them next to its events: +//! `{"displays":[{"id":1,"frame":[0,0,1512,982],"scale":2,"primary":true}],"pointer":[800,400],"events":[]}`. +//! Frames and the pointer are points in one global, top-left space (macOS display bounds). + +use serde_json::Value; + +use crate::{DisplayTarget, NativeDisplayId, windows::PlaceRequest}; + +#[derive(Clone, Debug, PartialEq)] +pub(crate) struct VirtualDisplay { pub id: u32, pub frame: [f64; 4], pub scale: f64, pub primary: bool } + +#[derive(Clone, Debug, PartialEq)] +pub(crate) struct VirtualDesktop { pub displays: Vec<VirtualDisplay>, pub pointer: Option<(f64, f64)> } + +impl VirtualDesktop { + /// The single 1920x1080-pixel display headless window factories have always received. + pub fn single(scale: f64) -> Self { + let frame = [0.0, 0.0, 1920.0 / scale, 1080.0 / scale]; + Self { displays: vec![VirtualDisplay { id: 1, frame, scale, primary: true }], pointer: None } + } + + /// The script's desktop; `single` where it sets no displays. + #[cfg(test)] + pub fn from_script(script: Option<&Value>, scale: f64) -> Result<Self, String> { + Self::from_script_sized(script, scale, None) + } + + /// `from_script`, with one display of `size` points where the script sets none. + pub fn from_script_sized(script: Option<&Value>, scale: f64, size: Option<(f64, f64)>) -> Result<Self, String> { + let mut desktop = Self::single(scale); + if let Some((w, h)) = size { desktop.displays[0].frame = [0.0, 0.0, w, h]; } + let Some(Value::Object(script)) = script else { return Ok(desktop) }; + if let Some(list) = script.get("displays") { + let Value::Array(list) = list else { return Err("script: \"displays\" must be an array".into()) }; + desktop.displays = list.iter().enumerate().map(|(i, d)| { + let frame = d["frame"].as_array().filter(|f| f.len() == 4) + .and_then(|f| Some([f[0].as_f64()?, f[1].as_f64()?, f[2].as_f64()?, f[3].as_f64()?])) + .filter(|f| f[2] > 0.0 && f[3] > 0.0) + .ok_or_else(|| format!("script: display {i} needs \"frame\": [x, y, width, height]"))?; + let scale = match &d["scale"] { + Value::Null => scale, + s => s.as_f64().filter(|s| s.is_finite() && *s > 0.0) + .ok_or_else(|| format!("script: display {i} \"scale\" must be a number above 0"))?, + }; + Ok(VirtualDisplay { + id: d["id"].as_u64().map_or(i as u32 + 1, |id| id as u32), frame, scale, + primary: d["primary"].as_bool().unwrap_or(false), + }) + }).collect::<Result<_, String>>()?; + if desktop.displays.is_empty() { return Err("script: \"displays\" is empty".into()); } + } + if let Some(p) = script.get("pointer") { + desktop.pointer = Some(p.as_array().filter(|p| p.len() == 2).and_then(|p| Some((p[0].as_f64()?, p[1].as_f64()?))) + .ok_or("script: \"pointer\" must be [x, y]")?); + } + Ok(desktop) + } + + /// The primary display (the first when none is marked). + pub fn primary(&self) -> &VirtualDisplay { + self.displays.iter().find(|d| d.primary).unwrap_or(&self.displays[0]) + } + + /// A point in desktop pixels (`WindowOptions::position`) in global points, by the scale of + /// the display it lies on, else the primary display's. + pub fn to_points(&self, (x, y): (i32, i32)) -> (f32, f32) { + let d = self.display_at(Some((x, y))); + let (x, y) = (f64::from(x), f64::from(y)); + ((d.frame[0] + (x - d.frame[0] * d.scale) / d.scale) as f32, (d.frame[1] + (y - d.frame[1] * d.scale) / d.scale) as f32) + } + + /// The display a point in desktop pixels lies on, else the primary display. Each display's + /// pixels start at its point origin times its scale (as `displays` reports), so with mixed + /// scales those boxes overlap: there the display whose point frame holds the point wins. + pub fn display_at(&self, at: Option<(i32, i32)>) -> &VirtualDisplay { + let Some((x, y)) = at else { return self.primary() }; + let (x, y) = (f64::from(x), f64::from(y)); + let inside = |[dx, dy, w, h]: [f64; 4]| x >= dx && y >= dy && x < dx + w && y < dy + h; + let mut owners = self.displays.iter().filter(|d| inside(d.frame.map(|v| v * d.scale))); + let first = owners.clone().next(); + owners.find(|d| inside(d.frame)).or(first).unwrap_or_else(|| self.primary()) + } + + /// The global frame a window of `size` points opens at: at `position` (desktop pixels), + /// else centred on the primary display. + pub fn open_at(&self, position: Option<(i32, i32)>, (w, h): (f32, f32)) -> [f32; 4] { + match position { + Some(p) => { let (x, y) = self.to_points(p); [x, y, w, h] } + None => { + let d = self.display_at(None).frame.map(|v| v as f32); + [d[0] + ((d[2] - w) / 2.0).round(), d[1] + ((d[3] - h) / 2.0).round(), w, h] + } + } + } + + /// What a window factory sees: desktop pixels, like native displays. + pub fn displays(&self) -> Vec<crate::Display> { + self.displays.iter().map(|d| crate::Display { + id: None, name: Some("headless".into()), + position: ((d.frame[0] * d.scale).round() as i32, (d.frame[1] * d.scale).round() as i32), + size: ((d.frame[2] * d.scale).round() as u32, (d.frame[3] * d.scale).round() as u32), + scale: d.scale, primary: d.primary, + }).collect() + } + + /// The display and global frame `request` gives a window of `size` points. Unknown + /// displays fall back to primary, as natively. + pub fn place(&self, request: &PlaceRequest, size: (f32, f32)) -> (u32, [f32; 4]) { + let id = match &request.requested { + DisplayTarget::Id(id) => id.native_id(), + DisplayTarget::Native(id) => Some(*id), + DisplayTarget::Primary | DisplayTarget::UnderPointer => None, + }.map(|id| match id { + NativeDisplayId::MacOS(n) | NativeDisplayId::X11Crtc(n) | NativeDisplayId::X11Output(n) | NativeDisplayId::Wayland(n) => i64::from(n), + NativeDisplayId::Windows(n) => n as i64, + }); + let bounds: Vec<_> = self.displays.iter().map(|d| [d.frame[0], d.frame[1], d.frame[0] + d.frame[2], d.frame[1] + d.frame[3]]).collect(); + let primary = self.displays.iter().position(|d| d.primary); + let requested = id.and_then(|id| self.displays.iter().position(|d| i64::from(d.id) == id)); + let pointer = self.pointer.filter(|_| request.requested == DisplayTarget::UnderPointer); + let d = &self.displays[crate::overlay::options::choose_display(&bounds, primary, requested, pointer).unwrap_or(0)]; + let local = crate::overlay::options::local_rect(PlaceRequest::at(size), Some(request.placement), (d.frame[2] as f32, d.frame[3] as f32)); + (d.id, [d.frame[0] as f32 + local[0], d.frame[1] as f32 + local[1], local[2], local[3]]) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + use crate::{Align, OverlayPlacement, ScreenEdge}; + + #[test] + fn headless_place_resolves_against_the_scripted_desktop() { + let script = json!({ + "displays": [{"id": 1, "frame": [0, 0, 1512, 982], "scale": 2, "primary": true}, + {"id": 7, "frame": [1512, -100, 1920, 1080], "scale": 1}], + "pointer": [2000, 300], "events": [], + }); + let desktop = VirtualDesktop::from_script(Some(&script), 2.0).unwrap(); + let top = OverlayPlacement::Edge { edge: ScreenEdge::Top, margin: 160.0, align: Align::Center, inset: 0.0 }; + let request = |display| PlaceRequest { requested: display, ..PlaceRequest::new(DisplayTarget::Primary, top) }; + assert_eq!(desktop.place(&request(DisplayTarget::Primary), (600.0, 80.0)), (1, [456.0, 160.0, 600.0, 80.0])); + assert_eq!(desktop.place(&request(DisplayTarget::UnderPointer), (600.0, 80.0)), (7, [2172.0, 60.0, 600.0, 80.0])); + assert_eq!(desktop.place(&request(DisplayTarget::Native(NativeDisplayId::MacOS(7))), (600.0, 80.0)).0, 7); + assert_eq!(desktop.place(&request(DisplayTarget::Native(NativeDisplayId::MacOS(9))), (600.0, 80.0)).0, 1, "unknown ids fall back to primary"); + let full = PlaceRequest::new(DisplayTarget::Native(NativeDisplayId::MacOS(7)), OverlayPlacement::FullScreen); + assert_eq!(desktop.place(&full, (600.0, 80.0)), (7, [1512.0, -100.0, 1920.0, 1080.0])); + assert_eq!(desktop.displays()[1].position, (1512, -100)); + assert_eq!(desktop.displays()[0].size, (3024, 1964)); + + let default = VirtualDesktop::from_script(None, 2.0).unwrap(); + assert_eq!(default.displays(), vec![crate::Display { id: None, name: Some("headless".into()), + position: (0, 0), size: (1920, 1080), scale: 2.0, primary: true }], "unchanged factory display"); + assert!(VirtualDesktop::from_script(Some(&json!({"displays": [{"frame": [0, 0]}]})), 2.0).is_err()); + assert!(VirtualDesktop::from_script(Some(&json!({"displays": [{"frame": [0, 0, 10, 10], "scale": 0}]})), 2.0).is_err()); + } + + #[test] + fn positions_on_mixed_scale_displays_convert_by_the_display_they_land_on() { + // A Retina laptop with a 1x monitor to its right: their pixel boxes overlap from x = 1512. + let script = json!({"displays": [{"id": 1, "frame": [0, 0, 1512, 982], "scale": 2, "primary": true}, + {"id": 2, "frame": [1512, 0, 1920, 1080], "scale": 1}]}); + let desktop = VirtualDesktop::from_script(Some(&script), 2.0).unwrap(); + let on = |p: (i32, i32)| (desktop.display_at(Some(p)).id, desktop.to_points(p)); + assert_eq!(on((200, 100)), (1, (100.0, 50.0))); + assert_eq!(on((1300, 1800)), (1, (650.0, 900.0))); + assert_eq!(on(desktop.displays()[1].position), (2, (1512.0, 0.0)), "the monitor's origin is on the monitor"); + assert_eq!(on((1612, 100)), (2, (1612.0, 100.0))); + assert_eq!(on((-50, 0)).0, 1, "off every display: the primary"); + // Where a window opens, which its `El::on_screen_layout` rects start from. + assert_eq!(desktop.open_at(None, (400.0, 300.0)), [556.0, 341.0, 400.0, 300.0], "centred on the primary"); + assert_eq!(desktop.open_at(Some((1612, 100)), (400.0, 300.0)), [1612.0, 100.0, 400.0, 300.0]); + + // The 2x display second and to the right: its pixels don't overlap the primary's. + let script = json!({"displays": [{"id": 1, "frame": [0, 0, 1920, 1080], "scale": 1, "primary": true}, + {"id": 2, "frame": [1920, 0, 1512, 982], "scale": 2}]}); + let desktop = VirtualDesktop::from_script(Some(&script), 2.0).unwrap(); + let on = |p: (i32, i32)| (desktop.display_at(Some(p)).id, desktop.to_points(p)); + assert_eq!(on((3840 + 200, 1500)), (2, (2020.0, 750.0))); + assert_eq!(on((100, 100)), (1, (100.0, 100.0))); + } +} diff --git a/app/vendor/rune/crates/rune/src/tooling/virtual_desktop/tests.rs b/app/vendor/rune/crates/rune/src/tooling/virtual_desktop/tests.rs new file mode 100644 index 0000000..0b50561 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/tooling/virtual_desktop/tests.rs @@ -0,0 +1,345 @@ +use super::composite::{MAX_BACKDROP, fit_backdrop, pixels}; +use super::*; +use crate::time::Instant; + +#[test] +fn backdrop_is_cropped_to_the_output_aspect_then_scaled() { + let dir = std::env::temp_dir().join(format!("rune-backdrop-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + // Red, green and blue thirds side by side: a square output keeps the green middle. + let wide = dir.join("wide.png"); + ::image::RgbaImage::from_fn(300, 100, |x, _| ::image::Rgba([if x < 100 { 255 } else { 0 }, if (100..200).contains(&x) { 255 } else { 0 }, if x >= 200 { 255 } else { 0 }, 255])) + .save(&wide).unwrap(); + let px = fit_backdrop(&wide, (50, 50)).unwrap(); + assert_eq!(px.len(), 50 * 50 * 4); + assert!(px.chunks(4).all(|p| p[1] > 200 && p[0] < 40 && p[2] < 40), "only the centre survives"); + assert_eq!(fit_backdrop(&wide, (300, 100)).unwrap()[..4], [255, 0, 0, 255], "same size: pixels as they are"); + + let huge = dir.join("huge.png"); + ::image::GrayImage::new(MAX_BACKDROP + 1, 1).save(&huge).unwrap(); + let error = fit_backdrop(&huge, (10, 10)).unwrap_err(); + assert!(error.contains("16385x1"), "refused before decoding: {error}"); + std::fs::remove_dir_all(&dir).unwrap(); +} + +#[test] +fn translucent_backdrop_premultiplies_in_linear_light() { + let dir = std::env::temp_dir().join(format!("rune-backdrop-alpha-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("alpha.png"); + let pixels_in = [ + [255u8, 255, 255, 128], // 50% white -> srgb_encode(1.0 * 128/255) = 188 + [188, 188, 188, 128], // 50% of ~0.5 linear -> srgb_encode(0.5 * 0.5) = 137 + [12, 34, 56, 255], // opaque: unchanged + [255, 0, 0, 0], // transparent: black + ]; + ::image::RgbaImage::from_fn(4, 1, |x, _| ::image::Rgba(pixels_in[x as usize])) + .save(&path).unwrap(); + let px = fit_backdrop(&path, (4, 1)).unwrap(); + std::fs::remove_dir_all(&dir).unwrap(); + assert_eq!(&px[0..4], &[188, 188, 188, 255], "half white over black in linear light"); + assert!((px[4] as i32 - 137).abs() <= 1 && px[4] == px[5] && px[5] == px[6] && px[7] == 255, "half mid-grey: {:?}", &px[4..8]); + assert_eq!(&px[8..12], &[12, 34, 56, 255], "opaque pixel stays exact"); + assert_eq!(&px[12..16], &[0, 0, 0, 255], "transparent pixel becomes black"); +} + +/// Each window of a headless multi-window run takes its own Tab opt-in and titlebar inset, +/// and a borderless window has no traffic lights to inset for. +#[test] +fn each_window_takes_its_tab_opt_in_and_titlebar_inset() { + use crate::{AppSpec, Cx, El, Key, KeyEvent, col, el, row}; + use crate::WindowSpec; + fn view(_: &(), cx: &mut Cx<()>) -> El { + col().size(300.0, 100.0) + .child(row().child(el().key("inset").size(cx.titlebar_inset().max(1.0), 10.0))) + .child(el().key("button").size(30.0, 30.0).focusable(true).role("button")) + } + let window = |tab: bool, borderless: bool| { + let spec = WindowSpec::new("w", AppSpec::new("W", (300.0, 100.0), || (), view)).tab_visits_controls(tab); + let spec = WindowSpec { options: crate::WindowOptions { borderless, ..Default::default() }, ..spec }; + let mut w = Window::new(spec, None, &Args::default(), true, true, 1.0); + let rt = w.rt_mut::<()>(); + rt.frame(0.0); + rt.set_full_keyboard_access(false); + rt.key(KeyEvent { key: Key::Tab, mods: Default::default() }); + rt.frame(0.1); + let focused = rt.elements().into_iter().find(|e| e.focused).and_then(|e| e.key); + (focused, rt.presented("inset").unwrap().0[2]) + }; + assert_eq!(window(true, false), (Some("button".into()), 67.0)); + assert_eq!(window(false, false).0, None, "keyboard navigation off skips buttons"); + assert_eq!(window(true, true).1, 1.0, "borderless: no inset"); +} + +type Log = std::rc::Rc<std::cell::RefCell<Vec<(usize, String)>>>; + +/// A window that only has a frame and visibility, and logs the pointer input it gets. +struct Fake { i: usize, frame: [f32; 4], visible: bool, log: Log } + +impl Member for Fake { + fn key(&self) -> &str { "fake" } + fn frame(&self) -> [f32; 4] { self.frame } + fn visible(&self) -> bool { self.visible } + fn click_through(&self) -> bool { false } + fn on_top(&self) -> bool { false } + fn radius(&self) -> f32 { 0.0 } + fn shadow(&self) -> bool { false } + fn features(&self) -> wgpu::Features { wgpu::Features::empty() } + fn start(&mut self, _: &VirtualDesktop) {} + fn trace_on(&mut self) {} + fn drain(&mut self, _: &VirtualDesktop, _: f64) -> Changes { Changes::default() } + fn pending(&self) -> bool { false } + fn stale(&self) -> bool { false } + fn advance(&mut self, _: f64) {} + fn focus(&mut self, _: bool) {} + fn resize_by(&mut self, _: f32, _: f32) {} + fn input(&mut self, kind: &Kind, _: (f32, f32)) { self.log.borrow_mut().push((self.i, format!("{kind:?}"))); } + fn leave(&mut self) { self.log.borrow_mut().push((self.i, "Leave".into())); } + fn find(&self, _: &str) -> Option<(f32, f32)> { None } + fn pointer(&self) -> Option<(f32, f32)> { None } + fn shortcut(&self, _: &crate::Shortcut) -> Result<(), crate::ShortcutError> { Ok(()) } + fn reopen_candidate(&self) -> crate::platform::reopen::Candidate { unimplemented!() } + fn reopen_hook(&mut self, _: bool) -> bool { false } + fn reopen(&mut self) -> Changes { Changes::default() } + fn menu(&self, _: &str) -> Result<(), crate::MenuError> { Ok(()) } + fn popup_open(&self) -> bool { false } + fn resolve_popup(&mut self, _: Option<&str>) -> Result<(), crate::PopupMenuError> { Ok(()) } + fn file_dialog_open(&self) -> bool { false } + fn resolve_file_dialog(&mut self, _: Option<std::path::PathBuf>) -> Result<(), crate::FileDialogError> { Ok(()) } + fn render(&mut self, _: &Gpu, _: &Slot, _: (u32, u32), _: f64, _: f64, _: Instant) {} + fn flush_interaction(&mut self) {} + fn backdrop_dark(&self) -> Option<bool> { None } + fn tree(&self, _: f64) -> serde_json::Value { serde_json::Value::Null } + fn trace(&mut self, _: &mut Trace, _: f64, _: f64) {} + fn summary(&mut self, _: &wgpu::Device) -> Option<String> { None } +} + +/// Two 100-point windows side by side, the right one in front. +fn two_windows() -> (Desk, Log) { + let log = Log::default(); + let members: Vec<Box<dyn Member>> = (0..2) + .map(|i| Box::new(Fake { i, frame: [i as f32 * 100.0, 0.0, 100.0, 100.0], visible: true, log: log.clone() }) as Box<dyn Member>) + .collect(); + let desk = Desk { members, z: vec![0, 1], focus: Focus::of(Some(1), true), pointer: Pointer::Out, files: Files::None, origin: (0.0, 0.0), scale: 1.0 }; + (desk, log) +} + +fn hide(desk: &mut Desk, i: usize) { + let fake = Fake { i, frame: desk.members[i].frame(), visible: false, log: Log::default() }; + desk.members[i] = Box::new(fake); +} + +/// A press holds the pointer until it lifts; a window that hides meanwhile lets go of it even +/// when it no longer had the keyboard, so the pointer goes to the window under it again. +#[test] +fn a_hidden_window_lets_go_of_a_captured_pointer() { + let (mut desk, log) = two_windows(); + desk.pointer_input(&Kind::Down, (150.0, 50.0)); + assert_eq!(desk.pointer, Pointer::Pressed(1)); + desk.pointer_input(&Kind::Move, (50.0, 50.0)); + assert_eq!(log.borrow().last(), Some(&(1, "Move".into())), "a drag stays with the window it pressed"); + // Another window takes the keyboard, then the pressed one hides. + desk.focus(Some(0), true); + hide(&mut desk, 1); + desk.settle_key(); + assert_eq!(desk.pointer, Pointer::Out); + desk.pointer_input(&Kind::Move, (50.0, 50.0)); + assert_eq!(log.borrow().last(), Some(&(0, "Move".into())), "the window under the pointer gets it"); + assert_eq!(desk.pointer, Pointer::Over(0)); +} + +#[test] +fn a_release_keeps_the_pointer_over_the_window_it_pressed() { + let (mut desk, log) = two_windows(); + desk.pointer_input(&Kind::Move, (50.0, 50.0)); + desk.pointer_input(&Kind::Down, (50.0, 50.0)); + assert_eq!((desk.pointer, desk.focus.key()), (Pointer::Pressed(0), Some(0)), "a press takes the keyboard"); + desk.pointer_input(&Kind::Up, (150.0, 50.0)); + assert_eq!(desk.pointer, Pointer::Over(0), "until the pointer next moves"); + desk.pointer_input(&Kind::Move, (150.0, 50.0)); + assert_eq!(desk.pointer, Pointer::Over(1)); + let log = log.borrow(); + assert_eq!(log[log.len() - 2..], [(0, "Leave".into()), (1, "Move".into())]); +} + +#[test] +fn a_click_on_the_backdrop_deactivates_the_app_but_keeps_its_key_window() { + let (mut desk, _) = two_windows(); + desk.pointer_input(&Kind::Down, (150.0, 50.0)); + assert_eq!(desk.focus.focused(), Some(1)); + desk.pointer_input(&Kind::Down, (500.0, 500.0)); + assert_eq!(desk.pointer, Pointer::Out, "the backdrop takes the press"); + assert_eq!((desk.focus.key(), desk.focus.focused()), (Some(1), None), "no focus while the app is behind"); + desk.set_active(true); + assert_eq!(desk.focus.focused(), Some(1), "the window it comes back with has focus again"); +} + +#[test] +fn output_pixels_fit_a_texture() { + assert_eq!(pixels((1512.0, 982.0), 2.0, 8192), Some((3024, 1964))); + assert_eq!(pixels((0.2, 10.0), 2.0, 8192), None, "under a pixel"); + assert_eq!(pixels((5000.0, 10.0), 2.0, 8192), None, "over the GPU's limit"); + assert_eq!(pixels((f32::NAN, 10.0), 2.0, 8192), None); + assert_eq!(pixels((10.0, 10.0), f32::INFINITY, 8192), None); +} + +/// A window closed for good runs no more close hooks, even when its own `on_close` asks to +/// close again. +#[test] +fn a_finished_window_runs_its_close_hook_once() { + use crate::{App, AppSpec, El, Tx, WindowSpec, el}; + fn close(closes: &mut u32, tx: &mut Tx) { *closes += 1; tx.close_window(); } + let app = App::new(AppSpec::new("W", (100.0, 100.0), || 0u32, |_: &u32, _: &mut crate::Cx<u32>| -> El { el() })).on_close(close); + let mut w = Window::new(WindowSpec::from_app("w", app), None, &Args::default(), true, true, 1.0); + let desktop = VirtualDesktop::from_script(None, 2.0).unwrap(); + w.rt_mut::<u32>().update(|_, tx| tx.close_window()); + w.drain(&desktop, 0.0); + assert_eq!(w.rt_mut::<u32>().state, 1); + assert!(!w.visible() && !w.reopen_candidate().reopenable); +} + +#[test] +fn virtual_desktop_window_scales_input_by_zoom_and_releases_keys_on_hide() { + use crate::{App, AppSpec, El, PhysicalInput, WindowSpec, el}; + #[derive(Default)] + struct S { wheel_dy: Vec<f32>, focus_lost: u32 } + fn view(_: &S, cx: &mut crate::Cx<S>) -> El { + cx.zoom(2.0); + el().key("root").size(200.0, 100.0).focusable(true) + .child( + el().key("btn") + .absolute(20.0, 10.0) + .size(40.0, 20.0) + .hit() + .on_wheel(|s: &mut S, ev, _| { s.wheel_dy.push(ev.dy); true }), + ) + .on_physical_input(|s: &mut S, ev, _| { + if matches!(ev, PhysicalInput::FocusLost) { s.focus_lost += 1; } + true + }) + } + let app = App::new(AppSpec::new("Z", (200.0, 100.0), S::default, view)).keep_running(); + let mut w = Window::new(WindowSpec::from_app("z", app), None, &Args::default(), true, true, 1.0); + let desktop = VirtualDesktop::from_script(None, 1.0).unwrap(); + w.start(&desktop); + w.advance(0.0); + w.rt_mut::<S>().update(|_, tx| tx.focus("root", false)); + w.advance(0.0); + + // Element at view (20..60, 10..30) -> centre at view (40, 20) -> window (80, 40) at 2x zoom. + assert_eq!(w.find("btn"), Some((80.0, 40.0)), "find reports window points, scaled by zoom"); + + // Pointer move and wheel arrive in window points; runtime must receive view points and zoomed delta. + w.input(&Kind::Move, (80.0, 40.0)); + assert_eq!(w.rt_mut::<S>().pointer(), Some((40.0, 20.0)), "pointer in view points"); + assert_eq!(w.pointer(), Some((80.0, 40.0)), "Window::pointer reports window points"); + w.input(&Kind::Wheel(0.0, -40.0), (80.0, 40.0)); + w.advance(0.0); + assert_eq!(w.rt_mut::<S>().state.wheel_dy, [-20.0], "wheel delta divides by zoom like window and headless hosts"); + + // Hiding releases keys via FocusLost, matching window/host::wind_down. + w.focus(true); + w.advance(0.0); + w.rt_mut::<S>().update(|_, tx| tx.close_window()); + w.drain(&desktop, 0.0); + w.advance(0.0); + assert_eq!(w.rt_mut::<S>().state.focus_lost, 1, "hiding a virtual desktop window must emit keys_lost"); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn uniform_layout_matches_wgsl() { + use std::mem::{offset_of, size_of}; + use wgpu::naga::{TypeInner, front::wgsl, proc::Layouter, valid::{Capabilities, ValidationFlags, Validator}}; + use super::composite::{SHADER, Uniform}; + + let module = wgsl::parse_str(SHADER).unwrap_or_else(|e| panic!("virtual_desktop: {}", e.emit_to_string(SHADER))); + Validator::new(ValidationFlags::all(), Capabilities::default()) + .validate(&module) + .unwrap_or_else(|e| panic!("virtual_desktop: {e}")); + let mut layouter = Layouter::default(); + layouter.update(module.to_ctx()).unwrap_or_else(|e| panic!("virtual_desktop: {e}")); + + let (handle, ty) = module + .types + .iter() + .find(|(_, t)| t.name.as_deref() == Some("W")) + .expect("WGSL struct W not found"); + assert_eq!(layouter[handle].size as usize, size_of::<Uniform>(), "W size"); + let TypeInner::Struct { members, span } = &ty.inner else { panic!("W is not a struct") }; + assert_eq!(*span as usize, size_of::<Uniform>(), "W span"); + let expected: &[(&str, usize)] = &[ + ("origin", offset_of!(Uniform, origin)), + ("size", offset_of!(Uniform, size)), + ("out_size", offset_of!(Uniform, out_size)), + ("shadow_offset", offset_of!(Uniform, shadow_offset)), + ("mask_size", offset_of!(Uniform, mask_size)), + ("radius", offset_of!(Uniform, radius)), + ("pad", offset_of!(Uniform, pad)), + ("sigma", offset_of!(Uniform, sigma)), + ("opacity", offset_of!(Uniform, opacity)), + ("unused", offset_of!(Uniform, _unused)), + ]; + assert_eq!(members.len(), expected.len(), "W member count"); + for (member, &(field, offset)) in members.iter().zip(expected) { + assert_eq!(member.name.as_deref(), Some(field), "W.{field} name"); + assert_eq!(member.offset as usize, offset, "W.{field} offset"); + } +} + +#[test] +fn virtual_desktop_window_follows_fit_content_height_and_resize_window() { + use crate::{App, AppSpec, El, WindowSpec, col, el}; + fn view(rows: &usize, _: &mut crate::Cx<usize>) -> El { + col().key("root").w_full() + .child(el().key("head").size(50.0, 50.0)) + .children((0..*rows).map(|i| el().key(format!("row{i}")).size(100.0, 40.0))) + } + let app = App::new(AppSpec::new("fit", (300.0, 400.0), || 1usize, view)).fit_content_height(); + let mut w = Window::new(WindowSpec::from_app("fit", app), None, &Args::default(), true, true, 1.0); + let desktop = VirtualDesktop::from_script(None, 1.0).unwrap(); + w.start(&desktop); + assert_eq!(w.frame()[2..4], [300.0, 90.0], "opens at content height"); + + w.advance(0.0); + w.rt_mut::<usize>().update(|rows, _| *rows = 2); + // Run 2 seconds of virtual time so the fit-height spring settles. + for _ in 0..120 { + w.advance(1.0 / 60.0); + } + assert_eq!(w.frame()[2..4], [300.0, 130.0], "grows to match new content height"); + + // Explicit Tx::resize_window_instant updates the window frame too. + w.rt_mut::<usize>().update(|_, tx| tx.resize_window_instant((360.0, 130.0))); + w.advance(1.0 / 60.0); + w.advance(1.0 / 60.0); + assert_eq!(w.frame()[2..4], [360.0, 130.0], "Tx::resize_window_instant resizes virtual desktop window"); +} + +#[test] +fn virtual_desktop_reports_frames_to_on_frame_encoded() { + let dir = std::env::temp_dir().join(format!("rune-desktop-encoded-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let backdrop = dir.join("backdrop.png"); + ::image::RgbaImage::from_pixel(64, 64, ::image::Rgba([64, 64, 64, 255])).save(&backdrop).unwrap(); + let snap = dir.join("out.png"); + let seen = std::rc::Rc::new(std::cell::RefCell::new(Vec::new())); + let log = seen.clone(); + let app = crate::App::new(crate::AppSpec::new("enc", (20.0, 20.0), || (), |_, _| crate::el())) + .on_frame_encoded(move |f| { + log.borrow_mut().push((f.seq(), f.outcome(), f.window().map(str::to_owned), f.refresh_hz())); + }); + let args = [ + "--desktop", backdrop.to_str().unwrap(), + "--at", "0.1", "--fps", "30", "--scale", "1", + "--snap", snap.to_str().unwrap(), + ]; + crate::tooling::headless(app, Args::parse_from(args.map(String::from).into())); + std::fs::remove_dir_all(&dir).unwrap(); + let seen = seen.borrow(); + assert_eq!(seen.len(), 4, "frames 0..=3 at 30 fps must report to on_frame_encoded: {seen:?}"); + for (i, (seq, outcome, window, hz)) in seen.iter().enumerate() { + assert_eq!((*seq, *outcome, window.as_deref(), *hz), (i as u64, crate::FrameOutcome::Drawn, Some("main"), Some(30.0))); + } +} + diff --git a/app/vendor/rune/crates/rune/src/tooling/virtual_desktop/window.rs b/app/vendor/rune/crates/rune/src/tooling/virtual_desktop/window.rs new file mode 100644 index 0000000..8533a7b --- /dev/null +++ b/app/vendor/rune/crates/rune/src/tooling/virtual_desktop/window.rs @@ -0,0 +1,750 @@ +//! One headless window in a `--desktop` run and its [`Member`] implementation. + +use std::sync::Arc; + +use serde_json::{Value, json}; + +use crate::app::{Shared, SharedCore, WindowRequest, WindowRequests}; +use crate::compose::{Compositor, Frame}; +use crate::desktop::Slot; +use crate::desktop::displays::VirtualDesktop; +use crate::el::Shell; +use crate::frame::clock::FrameClock; +use crate::frame::encoded::{FrameReports, OnFrameEncoded}; +use crate::frame::host_step::{self, Acquire, FrameHost, Gate, RenderPrep, StepInfo, draw_ui, prepare_gpu_resources}; +use crate::render::{Gpu, OFFSCREEN_FORMAT, Renderer}; +use crate::runtime::{AppDriver, Env, Runtime, RuntimeCore}; +use crate::time::Instant; +use crate::tooling::{Args, FrameTiming, Kind, Trace, headless::{step_window_frame, take_window_frame}}; +use crate::window::{Life, WakeEvent}; +use crate::{WindowHandle, WindowSpec}; + +/// Corner radius of a titled window, in points. +const RADIUS: f32 = 10.0; + +/// What a window asked of the desktop while it drained its requests. +#[derive(Default)] +pub(crate) struct Changes { + /// Shown or ordered in front: it goes to the top. + pub(super) front: bool, + /// It takes the keyboard. + pub(super) keys: bool, +} + +/// One window of a `--desktop` run, whatever its state type. +pub(crate) trait Member { + fn key(&self) -> &str; + /// x, y, width, height in global points. + fn frame(&self) -> [f32; 4]; + fn visible(&self) -> bool; + fn click_through(&self) -> bool; + fn on_top(&self) -> bool; + /// Corner radius in points. + fn radius(&self) -> f32; + fn shadow(&self) -> bool; + fn features(&self) -> wgpu::Features; + /// Its first frame: where it opens on `desktop` when it has no position. + fn start(&mut self, desktop: &VirtualDesktop); + fn trace_on(&mut self); + /// Applies what the app asked since the last call (updates, show/hide, place, close). + fn drain(&mut self, desktop: &VirtualDesktop, t: f64) -> Changes; + /// Something asked of it since `drain`, such as by a focus change another window's drain made. + fn pending(&self) -> bool; + /// Its last frame no longer shows its state, size or input. + fn stale(&self) -> bool; + fn advance(&mut self, dt: f64); + fn focus(&mut self, focused: bool); + /// Resizes the window by `(dw, dh)` from the size where `(0, 0)` started. + fn resize_by(&mut self, dw: f32, dh: f32); + /// Pointer and keyboard input; pointer kinds at `at`, in window points. + fn input(&mut self, kind: &Kind, at: (f32, f32)); + fn leave(&mut self); + fn find(&self, key: &str) -> Option<(f32, f32)>; + fn pointer(&self) -> Option<(f32, f32)>; + fn shortcut(&self, shortcut: &crate::Shortcut) -> Result<(), crate::ShortcutError>; + /// How reopening the app sees it. + fn reopen_candidate(&self) -> crate::platform::reopen::Candidate; + /// Runs `App::on_reopen`; true when it handled the reopen. + fn reopen_hook(&mut self, has_visible_windows: bool) -> bool; + /// Shows it in front with the keyboard, as the default reopen. + fn reopen(&mut self) -> Changes; + fn menu(&self, item: &str) -> Result<(), crate::MenuError>; + fn popup_open(&self) -> bool; + fn resolve_popup(&mut self, picked: Option<&str>) -> Result<(), crate::PopupMenuError>; + fn file_dialog_open(&self) -> bool; + fn resolve_file_dialog(&mut self, path: Option<std::path::PathBuf>) -> Result<(), crate::FileDialogError>; + /// Draws its frame into `slot`, `px` device pixels. + fn render(&mut self, gpu: &Gpu, slot: &Slot, px: (u32, u32), dt: f64, update_ms: f64, frame_start: Instant); + fn flush_interaction(&mut self); + fn backdrop_dark(&self) -> Option<bool>; + fn tree(&self, t: f64) -> Value; + fn trace(&mut self, trace: &mut Trace, t_ms: f64, cpu_ms: f64); + fn summary(&mut self, device: &wgpu::Device) -> Option<String>; +} + +struct DesktopRenderArgs<'a> { + device: &'a wgpu::Device, + queue: &'a wgpu::Queue, + encoder: &'a mut wgpu::CommandEncoder, + target: &'a wgpu::TextureView, + format: wgpu::TextureFormat, + size: (u32, u32), + dt: f64, + update_ms: f64, + ui: &'a mut Renderer, +} + +trait DesktopApp { + fn rt(&self) -> &RuntimeCore; + fn rt_mut(&mut self) -> &mut RuntimeCore; + fn with_driver(&mut self, f: &mut dyn FnMut(&mut RuntimeCore, &mut dyn AppDriver)); + fn run_on_close(&mut self); + fn run_on_reopen(&mut self, has_visible_windows: bool) -> bool; + fn drain_updates(&mut self, menus: &mut crate::native_menu::MenuGuard) -> WindowRequests; + fn has_updates(&self) -> bool; + fn has_compositor(&self) -> bool; + fn compositor_features(&self) -> wgpu::Features; + fn render_compositor(&mut self, args: DesktopRenderArgs<'_>) -> bool; + fn compositor_summary(&mut self, device: &wgpu::Device) -> Option<String>; + #[cfg(test)] + fn as_any_mut(&mut self) -> &mut dyn std::any::Any; +} + +impl dyn DesktopApp + '_ { + fn driver<R>(&mut self, f: impl FnOnce(&mut RuntimeCore, &mut dyn AppDriver) -> R) -> R { + let mut f = Some(f); + let mut out = None; + self.with_driver(&mut |core, app| { + out = Some(f.take().unwrap()(core, app)); + }); + out.unwrap() + } + + fn content_height(&mut self) -> f32 { self.driver(|rt, app| rt.content_height(app)) } + fn set_live_visible(&mut self, visible: bool) { self.driver(|rt, app| rt.set_live_visible(app, visible)); } + fn cancel_popups(&mut self) { self.driver(|rt, app| rt.cancel_popups(app)); } + fn cancel_file_dialogs(&mut self) { self.driver(|rt, app| rt.cancel_file_dialogs(app)); } + fn open_popup_headless(&mut self) { self.driver(|rt, app| rt.open_popup_headless(app)); } + fn resolve_popup(&mut self, picked: Option<&str>) -> Result<(), crate::PopupMenuError> { + self.driver(|rt, app| rt.resolve_popup(app, picked)) + } + fn frame(&mut self, dt: f64) -> bool { self.driver(|rt, app| rt.frame(app, dt)) } + fn window_focus(&mut self, focused: bool) { self.driver(|rt, app| rt.window_focus(app, focused)); } + fn script_input(&mut self, kind: &Kind, at: (f32, f32)) { + self.driver(|rt, app| { crate::tooling::script_input(rt, app, kind, at); }); + } +} + +struct TypedDesktopApp<S: 'static> { + rt: Runtime<S>, + shared: Arc<Shared<S>>, + comp: Option<Box<dyn Compositor<S>>>, + on_close: Option<fn(&mut S, &mut crate::Tx)>, + on_reopen: Option<fn(&mut S, bool, &mut crate::Tx) -> bool>, +} + +impl<S: 'static> DesktopApp for TypedDesktopApp<S> { + fn rt(&self) -> &RuntimeCore { self.rt.core() } + fn rt_mut(&mut self) -> &mut RuntimeCore { self.rt.core_mut() } + fn with_driver(&mut self, f: &mut dyn FnMut(&mut RuntimeCore, &mut dyn AppDriver)) { + let (core, mut driver) = self.rt.split_mut(); + f(core, &mut driver); + } + fn run_on_close(&mut self) { + if let Some(f) = self.on_close { self.rt.update(f); } + } + fn run_on_reopen(&mut self, has_visible_windows: bool) -> bool { + let Some(f) = self.on_reopen else { return false }; + let mut handled = false; + self.rt.update(|s, tx| handled = f(s, has_visible_windows, tx)); + handled + } + fn drain_updates(&mut self, menus: &mut crate::native_menu::MenuGuard) -> WindowRequests { + self.shared.drain(|f| { + self.rt.update_if(f); + menus.drain(); + }) + } + fn has_updates(&self) -> bool { self.shared.has_updates() } + fn has_compositor(&self) -> bool { self.comp.is_some() } + fn compositor_features(&self) -> wgpu::Features { + self.comp.as_ref().map_or(wgpu::Features::empty(), |c| c.features()) + } + fn render_compositor(&mut self, args: DesktopRenderArgs<'_>) -> bool { + let Some(c) = self.comp.as_mut() else { return false }; + let mut f = Frame { + device: args.device, + queue: args.queue, + encoder: args.encoder, + target: args.target, + format: args.format, + size: args.size, + dt: args.dt, + update_ms: args.update_ms, + rt: &mut self.rt, + ui: args.ui, + }; + c.render(&mut f); + c.animating() + } + fn compositor_summary(&mut self, device: &wgpu::Device) -> Option<String> { + self.comp.as_mut().and_then(|c| c.summary(device)) + } + #[cfg(test)] + fn as_any_mut(&mut self) -> &mut dyn std::any::Any { self } +} + +fn inherited_window_args(args: &Args, selected: bool) -> Args { + // --size is the whole output here; each window keeps its own size. + let mut inherited = args.clone(); + inherited.size = None; + if !selected { inherited.scene = None; inherited.playground = None; inherited.variant = None; } + inherited +} + +struct WindowInit { + key: String, + shared_core: Arc<SharedCore>, + shortcuts_core: Arc<crate::shortcuts::HubCore>, + shortcuts: crate::shortcuts::Guard, + menus: crate::native_menu::MenuGuard, + handle: Option<WindowHandle>, + options: crate::WindowOptions, + native: crate::MacWindowOptions, + chrome: crate::Chrome, + titlebar: Option<crate::Titlebar>, + fit_height: bool, + min_size: Option<(f32, f32)>, + on_frame_encoded: Option<OnFrameEncoded>, + fps: f64, + scroll_bars: Option<crate::platform::scroll_bars::ScrollBars>, + key_warnings: bool, + open: bool, + keep_running: bool, + main: bool, + size: (f32, f32), +} + +pub(crate) struct Window { + key: String, + app: Box<dyn DesktopApp>, + shared_core: Arc<SharedCore>, + shortcuts_core: Arc<crate::shortcuts::HubCore>, + shortcuts: crate::shortcuts::Guard, + menus: crate::native_menu::MenuGuard, + handle: Option<WindowHandle>, + renderer: Option<Renderer>, + reports: FrameReports, + keep_running: bool, + launcher: bool, + /// A nonactivating panel, launcher or not: reopening never brings it back. + panel: bool, + /// The app's own window, not one `App::window` added. + main: bool, + fit_height: bool, + limits: ((f32, f32), Option<(f32, f32)>), + frame_anim: Option<crate::window::frame::FrameAnim>, + idle: bool, + virtual_t: f64, + shadow: bool, + click_through: bool, + on_top: bool, + radius: f32, + position: Option<(i32, i32)>, + /// `WindowOptions::physical_size`, in pixels of the display the window opens on. + physical: Option<(u32, u32)>, + frame: [f32; 4], + resize_from: (f32, f32), + life: Life, + placed: Option<Value>, +} + +impl Window { + pub(crate) fn new<S: 'static>(spec: WindowSpec<S>, handle: Option<WindowHandle>, args: &Args, selected: bool, main: bool, scale: f32) -> Self { + let WindowSpec { key, mut app, options, .. } = spec; + let own = app.resolve_args(inherited_window_args(args, selected)); + let comp = app.compositor.take(); + let on_frame_encoded = app.on_frame_encoded.take(); + let (open, keep_running, fit_height, on_close, on_reopen) = ( + app.open, app.keep_running, app.fit_content_height, app.on_close, app.on_reopen, + ); + let native = std::mem::take(&mut app.macos_window); + let (chrome, titlebar) = (app.chrome, app.titlebar); + let (playground, attach_playground) = (app.playground.take(), app.attach_playground); + let (spec, state, shared, runtime) = app.into_parts(own.scene.as_deref()); + let shortcuts = crate::shortcuts::Guard::attach(&shared, Arc::new(|| {}), true, false); + let menus = crate::native_menu::MenuGuard::attach(&shared, true); + let size = own.size.unwrap_or(spec.size); + let min_size = spec.min_size; + let dark = own.theme.as_deref() != Some("light"); + let mut rt = crate::tooling::runtime_for(&spec, state, size, Env::new(dark, scale), Arc::new(|| {})); + if let Some(attach) = attach_playground { + attach(&mut rt, playground, &spec, own.playground.clone(), own.variant.clone(), false); + } + rt.configure(runtime); + let (shared_core, shortcuts_core) = (shared.core.clone(), shared.shortcuts.core.clone()); + let typed = Box::new(TypedDesktopApp { rt, shared, comp, on_close, on_reopen }); + Self::from_app(typed, WindowInit { + key, + shared_core, + shortcuts_core, + shortcuts, + menus, + handle, + options, + native, + chrome, + titlebar, + fit_height, + min_size, + on_frame_encoded, + fps: args.fps.max(1.0), + scroll_bars: own.scroll_bars.or(args.scroll_bars), + key_warnings: selected && args.tree.is_some(), + open, + keep_running, + main, + size, + }) + } + + fn from_app(mut app: Box<dyn DesktopApp>, init: WindowInit) -> Self { + let WindowInit { + key, shared_core, shortcuts_core, shortcuts, menus, handle, options, native, + chrome, titlebar, fit_height, min_size, on_frame_encoded, fps, scroll_bars, + key_warnings, open, keep_running, main, size, + } = init; + let has_comp = app.has_compositor(); + { + let rt = app.rt_mut(); + if let Some(bars) = scroll_bars { rt.set_system_scroll_bars(bars); } + rt.headless_chrome(chrome, titlebar, options.borderless); + rt.transparent = options.transparent; + rt.host.fit_height = fit_height; + rt.track_marks = has_comp; + if key_warnings { rt.commit.enable_key_warnings(); } + } + let mut reports = FrameReports::new(on_frame_encoded, Some(&key)); + reports.set_refresh(Some(fps)); + let limits = (options.min_size.or(min_size).unwrap_or((0.0, 0.0)), options.max_size); + let visible = options.visible && open; + app.set_live_visible(visible); + shared_core.set_visible(visible); + let decorated = !options.borderless && !options.transparent; + Window { + key, + app, + shared_core, + shortcuts_core, + shortcuts, + menus, + handle, + renderer: None, + reports, + keep_running, + launcher: native.launcher, + panel: native.nonactivating_panel, + main, + fit_height, + limits, + frame_anim: None, + idle: true, + virtual_t: 0.0, + shadow: native.shadow != Some(false), + click_through: options.click_through, + on_top: options.always_on_top, + radius: if decorated { RADIUS } else { 0.0 }, + position: options.position, + physical: options.physical_size, + frame: [0.0, 0.0, size.0, size.1], + resize_from: size, + life: if visible { Life::Shown { sight: crate::window::Sight::Seen } } else { Life::Unopened }, + placed: None, + } + } + + #[cfg(test)] + pub(super) fn rt_mut<S: 'static>(&mut self) -> &mut Runtime<S> { + &mut self.app.as_any_mut().downcast_mut::<TypedDesktopApp<S>>().expect("desktop window state type").rt + } + + fn publish(&mut self) { + let visible = self.life.shown(); + self.app.set_live_visible(visible); + self.shared_core.set_visible(visible); + } + + fn request(&mut self, request: WindowRequest, changes: &mut Changes) { + match request { + WindowRequest::Open(_) | WindowRequest::Show if self.life.finished() => {} + WindowRequest::Open(_) => { + self.show(); + changes.front = true; + changes.keys = true; + } + WindowRequest::Show => { + self.show(); + changes.front = true; + // A launcher takes keys when it shows. + changes.keys |= self.launcher; + } + WindowRequest::Hide => self.hide(), + WindowRequest::Close => self.close(), + } + } + + fn show(&mut self) { + if self.life.shown() || !self.life.show() { return; } + // A launcher reveals the frame it kept up to date while hidden; others land their motion. + if !self.launcher { self.app.rt_mut().settle_all(); } + self.publish(); + } + + fn hide(&mut self) { + if !self.life.shown() { return; } + self.life.hide(crate::platform::reopen::stamp); + self.app.rt_mut().keys_lost(); + self.app.cancel_popups(); + self.app.cancel_file_dialogs(); + self.app.rt_mut().cancel_pointer(); + self.publish(); + } + + /// As the native host closes (`Life::closes`): a headless window always exists. + fn close(&mut self) { + if !self.life.closes(self.keep_running, true) { return; } + self.app.run_on_close(); + self.hide(); + if !self.keep_running { + self.app.cancel_popups(); + self.app.cancel_file_dialogs(); + self.life.finish(); + } + } + + fn place(&mut self, desktop: &VirtualDesktop, request: &crate::windows::PlaceRequest, t: f64) { + let size = (self.frame[2], self.frame[3]); + let (display, frame) = desktop.place(request, size); + let record = json!({ "t": t, "window": self.key, "display": display, "frame": frame }); + println!("rune-placed {record}"); + self.placed = Some(record); + self.position = None; + self.resize(frame); + } + + fn move_to(&mut self, (x, y): (f32, f32)) { + self.frame[0] = x; + self.frame[1] = y; + self.app.rt_mut().set_window_origin((x, y)); + } + + fn resize(&mut self, frame: [f32; 4]) { + self.frame = frame; + self.resize_from = (frame[2], frame[3]); + let rt = self.app.rt_mut(); + let scale = rt.window_scale(); + rt.set_viewport((frame[2], frame[3]), scale); + rt.set_window_origin((frame[0], frame[1])); + } +} + +impl Member for Window { + fn key(&self) -> &str { &self.key } + fn frame(&self) -> [f32; 4] { self.frame } + fn visible(&self) -> bool { self.life.shown() } + fn click_through(&self) -> bool { self.click_through } + fn on_top(&self) -> bool { self.on_top } + fn radius(&self) -> f32 { self.radius } + fn shadow(&self) -> bool { self.shadow } + fn features(&self) -> wgpu::Features { self.app.compositor_features() } + + fn start(&mut self, desktop: &VirtualDesktop) { + let display = desktop.display_at(self.position); + let (w, mut h) = match self.physical { + Some((w, h)) => ((f64::from(w) / display.scale) as f32, (f64::from(h) / display.scale) as f32), + None => (self.frame[2], self.frame[3]), + }; + if self.fit_height { + let scale = self.app.rt().window_scale(); + self.app.rt_mut().set_viewport((w, h), scale); + h = crate::window::frame::clamp_size((w, self.app.content_height()), self.limits.0, self.limits.1).1; + } + self.resize(desktop.open_at(self.position, (w, h))); + } + + fn trace_on(&mut self) { + let rt = self.app.rt_mut(); + rt.frame.enable_trace_channels(true); + rt.scene.store_mut().audit_retargets(true); + } + + fn drain(&mut self, desktop: &VirtualDesktop, t: f64) -> Changes { + let mut changes = Changes::default(); + self.shortcuts.drain(); + self.menus.drain(); + let _receiving = self.shortcuts.receiving(); + let requests = self.app.drain_updates(&mut self.menus); + if let Some(p) = requests.position { self.move_to(desktop.to_points(p)); } + if let Some(place) = &requests.place { self.place(desktop, place, t); } + if let Some(request) = requests.window { self.request(request, &mut changes); } + if requests.activation == Some(crate::app::Activation::Focus) && self.life.shown() { changes.front = true; changes.keys = true; } + // `quit` ends a native app; a recording runs to the end of its timeline. + let queued = self.handle.as_ref().map(WindowHandle::take_headless).unwrap_or_default(); + for event in queued { + match event { + WakeEvent::Window(_, request) => self.request(request, &mut changes), + WakeEvent::Place(_, place) => self.place(desktop, &place, t), + WakeEvent::Position(_, p) => self.move_to(desktop.to_points(p)), + WakeEvent::Focus(_) if self.life.shown() => { changes.front = true; changes.keys = true; } + WakeEvent::Frame(_, mut request) => { + let rt = self.app.rt_mut(); + request.spring = (request.animate && !rt.reduced_motion).then_some(crate::tok::motion::DEFAULT); + rt.host.window_frame = Some(rt.host.window_frame.unwrap_or_default().merge(request)); + } + _ => {} + } + } + for _ in 0..8 { + // A headless desktop draws no Dock to minimize into (`Activation::Minimize` too). + self.app.rt_mut().minimize_step(crate::window::MinimizeEvent::Lost); + match self.app.rt_mut().shell_request.take() { + Some(Shell::Close) => self.close(), + Some(Shell::Quit | Shell::Relaunch) | None => {} + } + if self.life.shown() { + self.app.open_popup_headless(); + } else { + self.app.cancel_popups(); + self.app.rt_mut().refuse_file_dialog("cannot open a file dialog while the window is hidden"); + } + if self.app.rt().shell_request.is_none() { break; } + } + changes + } + + fn pending(&self) -> bool { + self.shared_core.asks_window() || self.app.has_updates() || self.app.rt().shell_request.is_some() + || self.handle.as_ref().is_some_and(WindowHandle::headless_pending) + } + + fn stale(&self) -> bool { self.app.rt().stale() || self.app.rt().text.families_behind() } + fn advance(&mut self, dt: f64) { + self.virtual_t += dt; + take_window_frame(self.app.rt_mut(), &mut self.frame_anim, self.virtual_t, self.limits); + if !self.idle { + let scale = self.app.rt().window_scale(); + step_window_frame(self.app.rt_mut(), &mut self.frame_anim, self.virtual_t, scale); + let (w, h) = self.app.rt().window_viewport(); + if (self.frame[2], self.frame[3]) != (w, h) { + self.frame[2] = w; + self.frame[3] = h; + self.resize_from = (w, h); + } + } + { + let rt = self.app.rt_mut(); + rt.host.window_resting = self.frame_anim.is_none() && rt.host.window_frame.is_none(); + } + let animating = self.app.frame(dt); + if self.app.rt().host.window_frame.is_some() { + let shown = if self.app.rt_mut().host.fit.take_held() { 0.0 } else { dt }; + take_window_frame(self.app.rt_mut(), &mut self.frame_anim, self.virtual_t - shown, self.limits); + } + self.idle = !animating && self.frame_anim.is_none(); + } + fn focus(&mut self, focused: bool) { self.app.window_focus(focused); } + + fn resize_by(&mut self, dw: f32, dh: f32) { + let rt = self.app.rt_mut(); + let scale = rt.window_scale(); + crate::tooling::step_resize(rt, &mut self.resize_from, (dw, dh), scale); + let (w, h) = rt.window_viewport(); + self.frame[2] = w; + self.frame[3] = h; + } + + fn input(&mut self, kind: &Kind, (x, y): (f32, f32)) { + let zoom = self.app.rt().zoom(); + self.app.script_input(kind, (x / zoom, y / zoom)); + } + + fn leave(&mut self) { self.app.rt_mut().pointer_leave(); } + fn find(&self, key: &str) -> Option<(f32, f32)> { + let rt = self.app.rt(); + let zoom = rt.zoom(); + rt.find(key).map(|(x, y)| (x * zoom, y * zoom)) + } + fn pointer(&self) -> Option<(f32, f32)> { + let rt = self.app.rt(); + let zoom = rt.zoom(); + rt.pointer().map(|(x, y)| (x * zoom, y * zoom)) + } + fn shortcut(&self, shortcut: &crate::Shortcut) -> Result<(), crate::ShortcutError> { self.shortcuts_core.fire(shortcut) } + + fn reopen_candidate(&self) -> crate::platform::reopen::Candidate { + crate::platform::reopen::Candidate { + reopenable: !self.life.finished() && !self.panel, + visible: self.life.shown(), + // A headless desktop has no Dock to minimize into. + minimized: false, + hidden_at: self.life.hidden_at(), + main: self.main, + } + } + + fn reopen_hook(&mut self, has_visible_windows: bool) -> bool { + if self.life.finished() { return false; } + self.app.run_on_reopen(has_visible_windows) + } + + fn reopen(&mut self) -> Changes { + let mut changes = Changes::default(); + self.request(WindowRequest::Open(None), &mut changes); + changes + } + fn menu(&self, item: &str) -> Result<(), crate::MenuError> { self.menus.fire(item) } + fn popup_open(&self) -> bool { self.app.rt().popup_menu().is_some() } + fn resolve_popup(&mut self, picked: Option<&str>) -> Result<(), crate::PopupMenuError> { self.app.resolve_popup(picked) } + fn file_dialog_open(&self) -> bool { self.app.rt().file_dialog().is_some() } + fn resolve_file_dialog(&mut self, path: Option<std::path::PathBuf>) -> Result<(), crate::FileDialogError> { self.app.rt_mut().resolve_file_dialog(path) } + + fn render(&mut self, gpu: &Gpu, slot: &Slot, px: (u32, u32), dt: f64, update_ms: f64, frame_start: Instant) { + let mut frame = DesktopFrame { + window: self, + gpu, + slot, + px, + dt, + update_ms, + frame_start, + encoded_stamp: None, + }; + host_step::run(&mut frame); + } + + fn flush_interaction(&mut self) { self.app.rt_mut().interaction_flush(); } + + fn backdrop_dark(&self) -> Option<bool> { self.app.rt().backdrop_dark() } + + fn tree(&self, t: f64) -> Value { + let mut tree = crate::tooling::tree_json_core(self.app.rt(), t); + if let Some(placed) = &self.placed { tree["placed"] = placed.clone(); } + tree + } + + fn trace(&mut self, trace: &mut Trace, t_ms: f64, cpu_ms: f64) { + trace.frame_timed_core(self.app.rt_mut(), t_ms, cpu_ms, FrameTiming::default()); + } + fn summary(&mut self, device: &wgpu::Device) -> Option<String> { self.app.compositor_summary(device) } +} + +struct DesktopFrame<'a> { + window: &'a mut Window, + gpu: &'a Gpu, + slot: &'a Slot, + px: (u32, u32), + dt: f64, + update_ms: f64, + frame_start: Instant, + encoded_stamp: Option<Instant>, +} + +impl DesktopFrame<'_> { + #[inline] + fn target_format(&self) -> wgpu::TextureFormat { + if self.window.app.rt().srgb_blend() { OFFSCREEN_FORMAT.remove_srgb_suffix() } else { OFFSCREEN_FORMAT } + } +} + +impl FrameHost for DesktopFrame<'_> { + type Drawable = (); + type Prepared = wgpu::CommandEncoder; + + #[inline] + fn gate(&mut self) -> Gate { + let animating = self.window.app.rt().animating; + Gate::PreStepped(StepInfo { + runtime_animating: animating, + animating, + dt: self.dt, + update_ms: self.update_ms, + presents_at: None, + }) + } + + #[inline] + fn needs_reblend(&self) -> bool { + let srgb = self.window.app.rt().srgb_blend(); + let format = self.target_format(); + self.window.renderer.as_ref().is_none_or(|r| r.srgb_blend() != srgb || r.format() != format) + } + + #[inline] + fn reblend(&mut self) -> bool { + let format = self.target_format(); + let renderer = self.window.renderer.get_or_insert_with(|| Renderer::new(&self.gpu.device, format)); + crate::window::rebuild_renderer_core(&self.gpu.device, renderer, format, self.window.app.rt_mut()); + true + } + + #[inline] + fn acquire(&mut self) -> Acquire<()> { Acquire::Ready(()) } + + #[inline] + fn step_runtime(&mut self) -> StepInfo { + unreachable!("virtual desktop renders through Gate::PreStepped") + } + + #[inline] + fn prepare_render(&mut self, _drawable: (), _info: &mut StepInfo) -> RenderPrep<wgpu::CommandEncoder> { + let renderer = self.window.renderer.as_mut().expect("renderer ensured by pre-reblend"); + prepare_gpu_resources(renderer, self.gpu, self.window.app.rt_mut(), self.px, false); + RenderPrep::Ready(self.gpu.device.create_command_encoder(&Default::default())) + } + + #[inline] + fn render(&mut self, encoder: &mut wgpu::CommandEncoder, info: &StepInfo) -> bool { + let srgb = self.window.app.rt().srgb_blend(); + let format = self.target_format(); + let view = if srgb { &self.slot.srgb_blend_view } else { &self.slot.view }; + let renderer = self.window.renderer.as_mut().expect("renderer ensured by pre-reblend"); + if self.window.app.has_compositor() { + self.window.app.render_compositor(DesktopRenderArgs { + device: &self.gpu.device, + queue: &self.gpu.queue, + encoder, + target: view, + format, + size: self.px, + dt: info.dt, + update_ms: info.update_ms, + ui: renderer, + }) + } else { + let rt = self.window.app.rt_mut(); + let clear = rt.clear_color(); + draw_ui(renderer, self.gpu, encoder, view, rt, self.px, clear); + false + } + } + + #[inline] + fn submit_and_present(&mut self, encoder: wgpu::CommandEncoder, _info: &StepInfo) -> Instant { + let renderer = self.window.renderer.as_mut().expect("renderer ensured by pre-reblend"); + renderer.submit(&self.gpu.queue, encoder); + self.encoded_stamp = self.window.reports.stamp(); + crate::time::now() + } + + #[inline] + fn present_targets(&mut self) -> (Option<&mut FrameClock>, &mut RuntimeCore) { + (None, self.window.app.rt_mut()) + } + + #[inline] + fn settle(&mut self, _submitted: Instant, info: &StepInfo) { + self.window.reports.drawn(self.encoded_stamp, None, self.frame_start, info.update_ms); + } +} + + diff --git a/app/vendor/rune/crates/rune/src/tooling/window_tests.rs b/app/vendor/rune/crates/rune/src/tooling/window_tests.rs new file mode 100644 index 0000000..e15afe1 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/tooling/window_tests.rs @@ -0,0 +1,6 @@ +#[test] +fn transparent_png_unpremultiplies_in_linear_space() { + let mut pixels = [188, 0, 0, 128, 255, 255, 255, 0, 12, 34, 56, 255]; + super::straight_alpha(&mut pixels); + assert_eq!(pixels, [255, 0, 0, 128, 0, 0, 0, 0, 12, 34, 56, 255]); +} diff --git a/app/vendor/rune/crates/rune/src/tray.rs b/app/vendor/rune/crates/rune/src/tray.rs new file mode 100644 index 0000000..a914c33 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/tray.rs @@ -0,0 +1,226 @@ +//! A system tray icon with a flat menu: StatusNotifierItem and `com.canonical.dbusmenu` over +//! zbus on Linux, `Shell_NotifyIcon` on its own message-only window on Windows. Each tray runs +//! on its own thread, so it needs no event loop of the app's and answers while the app's window +//! is closed. A primary click sends [`TrayEvent::Activate`]; a secondary click opens the menu, +//! whose picks send [`TrayEvent::Menu`]. Dropping the [`Tray`] removes the icon. +//! +//! Linux shows the icon only where a tray host runs (KDE, waybar, most bars; GNOME needs an +//! extension). Without one, [`Tray::new`] still succeeds and the icon appears once a host +//! starts. The Linux backend needs the default `dbus` feature. macOS isn't supported yet. +#[cfg(any(all(target_os = "linux", feature = "dbus"), target_os = "windows"))] +use std::sync::Arc; + +#[cfg(all(target_os = "linux", feature = "dbus"))] +#[path = "tray/sni.rs"] +mod native; +#[cfg(target_os = "windows")] +#[path = "tray/win32.rs"] +mod native; + +/// The icon as straight (not premultiplied) RGBA rows, `width × height × 4` bytes. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct TrayIcon { pub(crate) width: u32, pub(crate) height: u32, pub(crate) rgba: Vec<u8> } +impl TrayIcon { + pub fn rgba(width: u32, height: u32, pixels: Vec<u8>) -> Self { Self { width, height, rgba: pixels } } +} + +#[derive(Clone, Debug, PartialEq, Eq)] +#[non_exhaustive] +pub enum TrayItem { + /// `id` comes back in [`TrayEvent::Menu`] when it's picked. + Action { id: String, label: String, enabled: bool }, + Separator, +} +impl TrayItem { + pub fn action(id: impl Into<String>, label: impl Into<String>) -> Self { + Self::Action { id: id.into(), label: label.into(), enabled: true } + } + pub fn enabled(self, enabled: bool) -> Self { + match self { Self::Action { id, label, .. } => Self::Action { id, label, enabled }, separator => separator } + } +} + +#[derive(Clone, Debug, PartialEq, Eq)] +#[non_exhaustive] +pub enum TrayEvent { + /// The icon's primary click. `token` is the XDG activation token a Wayland tray host hands + /// over with it, for showing a window with focus. + Activate { token: Option<String> }, + /// A menu item's `id`. + Menu(String), +} + +#[derive(Clone, Debug)] +#[cfg_attr(not(all(target_os = "linux", feature = "dbus")), allow(dead_code))] +pub struct TraySpec { + /// A stable application id (Linux `Id`). + pub(crate) id: String, + pub(crate) title: String, + pub(crate) tooltip: String, + pub(crate) icon_name: String, + pub(crate) icon: TrayIcon, + pub(crate) menu: Vec<TrayItem>, +} +impl TraySpec { + pub fn new(id: impl Into<String>, title: impl Into<String>, icon: TrayIcon) -> Self { + Self { id: id.into(), title: title.into(), tooltip: String::new(), icon_name: String::new(), icon, menu: Vec::new() } + } + pub fn tooltip(mut self, tooltip: impl Into<String>) -> Self { self.tooltip = tooltip.into(); self } + /// A freedesktop icon theme name (Linux `IconName`) a host may draw instead of the pixels. + pub fn icon_name(mut self, name: impl Into<String>) -> Self { self.icon_name = name.into(); self } + pub fn menu(mut self, menu: Vec<TrayItem>) -> Self { self.menu = menu; self } +} + +#[derive(Clone, Debug, PartialEq, Eq)] +#[non_exhaustive] +pub enum TrayError { Unsupported, Backend(String) } +impl std::fmt::Display for TrayError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { Self::Unsupported => f.write_str("no system tray on this platform"), Self::Backend(e) => f.write_str(e) } + } +} +impl std::error::Error for TrayError {} + +/// Runs on the tray's thread; keep it short and hand work to the app. +#[cfg(any(all(target_os = "linux", feature = "dbus"), target_os = "windows"))] +pub(crate) type Handler = Arc<dyn Fn(TrayEvent) + Send + Sync>; + +pub struct Tray { + #[cfg(any(all(target_os = "linux", feature = "dbus"), target_os = "windows"))] + native: native::Native, +} + +/// Takes every tray icon off the notification area now, before a fast exit ends the process +/// (`crate::fast_exit`). Elsewhere the icon goes with the process: its D-Bus name (Linux) or +/// status item (macOS) ends when the connection does. +#[cfg(not(target_arch = "wasm32"))] +pub(crate) fn remove_all() { + #[cfg(target_os = "windows")] + native::remove_all(); +} + +impl Tray { + pub fn new(spec: TraySpec, on_event: impl Fn(TrayEvent) + Send + Sync + 'static) -> Result<Self, TrayError> { + if spec.icon.rgba.len() != spec.icon.width as usize * spec.icon.height as usize * 4 { + return Err(TrayError::Backend("tray icon size doesn't match its pixels".into())); + } + #[cfg(any(all(target_os = "linux", feature = "dbus"), target_os = "windows"))] + { native::Native::new(spec, Arc::new(on_event)).map(|native| Self { native }) } + #[cfg(not(any(all(target_os = "linux", feature = "dbus"), target_os = "windows")))] + { let _ = (spec, on_event); Err(TrayError::Unsupported) } + } + pub fn set_menu(&self, menu: Vec<TrayItem>) { + #[cfg(any(all(target_os = "linux", feature = "dbus"), target_os = "windows"))] + self.native.set_menu(menu); + #[cfg(not(any(all(target_os = "linux", feature = "dbus"), target_os = "windows")))] + let _ = menu; + } + pub fn set_tooltip(&self, tooltip: impl Into<String>) { + #[cfg(any(all(target_os = "linux", feature = "dbus"), target_os = "windows"))] + self.native.set_tooltip(tooltip.into()); + #[cfg(not(any(all(target_os = "linux", feature = "dbus"), target_os = "windows")))] + let _ = tooltip; + } +} + +/// Escapes a tray menu label so Win32 `AppendMenuW` shows it literally: `&` would underline the +/// next character as a mnemonic, `\t` would start a right-aligned shortcut column, and `\0` +/// would truncate the wide string. +#[cfg_attr(not(any(target_os = "windows", test)), allow(dead_code))] +pub(super) fn win32_menu_label(label: &str) -> String { + let mut out = String::with_capacity(label.len()); + for c in label.chars() { + match c { + '&' => out.push_str("&&"), + '\t' => out.push(' '), + '\0' => {} + _ => out.push(c), + } + } + out +} + +/// Escapes a tray menu label so `com.canonical.dbusmenu` shows it literally: a single `_` marks +/// a keyboard mnemonic and is stripped by tray hosts unless doubled. +#[cfg_attr(not(any(all(target_os = "linux", feature = "dbus"), test)), allow(dead_code))] +pub(super) fn dbusmenu_label(label: &str) -> String { + let mut out = String::with_capacity(label.len()); + for c in label.chars() { + match c { + '_' => out.push_str("__"), + '\0' => {} + _ => out.push(c), + } + } + out +} + +/// Encodes `text` as UTF-16 code units fitting in `max_units` without splitting a surrogate pair +/// or embedding interior NULs. +#[cfg_attr(not(any(target_os = "windows", test)), allow(dead_code))] +pub(super) fn truncate_utf16(text: &str, max_units: usize) -> Vec<u16> { + let mut out = Vec::with_capacity(text.len().min(max_units)); + let mut buf = [0u16; 2]; + for c in text.chars() { + if c == '\0' { continue; } + let encoded = c.encode_utf16(&mut buf); + if out.len() + encoded.len() > max_units { break; } + out.extend_from_slice(encoded); + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn enabled_leaves_separators_alone() { + assert_eq!(TrayItem::Separator.enabled(false), TrayItem::Separator); + assert_eq!(TrayItem::action("q", "Quit").enabled(false), TrayItem::Action { id: "q".into(), label: "Quit".into(), enabled: false }); + } + + #[test] + fn a_short_icon_is_refused() { + let spec = TraySpec::new("t", "T", TrayIcon::rgba(2, 2, vec![0; 3])); + assert!(matches!(Tray::new(spec, |_| {}), Err(TrayError::Backend(_)))); + } + + #[test] + fn tray_menu_labels_escape_platform_mnemonics_and_control_markers() { + assert_eq!(win32_menu_label("Save & Quit"), "Save && Quit"); + assert_eq!(win32_menu_label("A\tB\0C"), "A BC"); + assert_eq!(win32_menu_label("open_file"), "open_file"); + assert_eq!(win32_menu_label(""), ""); + + assert_eq!(dbusmenu_label("open_file"), "open__file"); + assert_eq!(dbusmenu_label("Save & Quit"), "Save & Quit"); + assert_eq!(dbusmenu_label("A\0B"), "AB"); + assert_eq!(dbusmenu_label(""), ""); + } + + #[test] + fn utf16_truncation_never_splits_a_surrogate_pair() { + let tip = format!("{}\u{1F600}", "a".repeat(126)); + let units = truncate_utf16(&tip, 127); + assert_eq!(units.len(), 126); + assert_eq!(String::from_utf16(&units).unwrap(), "a".repeat(126)); + + let fits = format!("{}\u{1F600}", "a".repeat(125)); + let units = truncate_utf16(&fits, 127); + assert_eq!(units.len(), 127); + assert_eq!(String::from_utf16(&units).unwrap(), fits); + } + + #[cfg(target_os = "windows")] + #[test] + fn windows_tooltip_truncation_keeps_utf16_surrogate_pairs_intact() { + // 126 ASCII chars (126 UTF-16 units) + 1 emoji (2 UTF-16 units = 128 > 127 max). + let tip = format!("{}\u{1F600}", "a".repeat(126)); + let mut d = native::data(std::ptr::null_mut(), 0); + native::set_tip(&mut d, &tip); + let len = d.szTip.iter().position(|&c| c == 0).unwrap(); + assert!(String::from_utf16(&d.szTip[..len]).is_ok(), "tooltip split a UTF-16 surrogate pair: {:?}", &d.szTip[len.saturating_sub(2)..len]); + assert_eq!(len, 126); + } +} diff --git a/app/vendor/rune/crates/rune/src/tray/sni.rs b/app/vendor/rune/crates/rune/src/tray/sni.rs new file mode 100644 index 0000000..4d91f4d --- /dev/null +++ b/app/vendor/rune/crates/rune/src/tray/sni.rs @@ -0,0 +1,280 @@ +//! StatusNotifierItem (`org.kde.StatusNotifierItem`) with a `com.canonical.dbusmenu` menu, on +//! its own session-bus connection and thread. The watcher is asked to show the item, again +//! whenever a new watcher takes the name (a bar that starts later or restarts). +use super::{Handler, TrayError, TrayEvent, TrayItem, TraySpec}; +use crate::platform::portal; +use async_channel::{Sender, unbounded}; +use futures_lite::{FutureExt, StreamExt}; +use std::{collections::HashMap, sync::{Arc, Mutex, mpsc}, thread::JoinHandle, time::Duration}; +use zbus::{ + Connection, Proxy, + object_server::SignalEmitter, + zvariant::{OwnedObjectPath, OwnedValue, Str, Value}, +}; + +const ITEM_PATH: &str = "/StatusNotifierItem"; +const MENU_PATH: &str = "/MenuBar"; +const WATCHER: &str = "org.kde.StatusNotifierWatcher"; +const WATCHER_PATH: &str = "/StatusNotifierWatcher"; +const RPC_TIMEOUT: Duration = Duration::from_secs(5); +const ROOT: i32 = 0; + +type Pixmaps = Vec<(i32, i32, Vec<u8>)>; +/// One dbusmenu node, `(ia{sv}av)`; children are variants holding the same shape. +type Layout = (i32, HashMap<String, OwnedValue>, Vec<OwnedValue>); + +struct Model { id: String, title: String, tooltip: String, icon_name: String, pixmaps: Pixmaps, menu: Vec<TrayItem>, revision: u32, token: Option<String> } +type Shared = Arc<Mutex<Model>>; + +enum Command { Menu(Vec<TrayItem>), Tooltip(String) } +pub(super) struct Native { commands: Option<Sender<Command>>, worker: Option<JoinHandle<()>> } + +fn backend(e: impl std::fmt::Display) -> TrayError { TrayError::Backend(e.to_string()) } + +/// ARGB32 in network byte order, as the spec's `IconPixmap` wants. +fn pixmaps(spec: &TraySpec) -> Pixmaps { + let argb = spec.icon.rgba.chunks_exact(4).flat_map(|p| [p[3], p[0], p[1], p[2]]).collect(); + vec![(spec.icon.width as i32, spec.icon.height as i32, argb)] +} + +/// Menu ids are the item's position plus one; 0 is the root. +fn properties(menu: &[TrayItem], id: i32) -> HashMap<String, OwnedValue> { + let mut map = HashMap::new(); + if id == ROOT { map.insert("children-display".into(), OwnedValue::from(Str::from_static("submenu"))); return map; } + match menu.get(id as usize - 1) { + Some(TrayItem::Action { label, enabled, .. }) => { + map.insert("label".into(), OwnedValue::from(Str::from(super::dbusmenu_label(label)))); + if !enabled { map.insert("enabled".into(), OwnedValue::from(false)); } + } + Some(TrayItem::Separator) => { map.insert("type".into(), OwnedValue::from(Str::from_static("separator"))); } + None => {} + } + map +} +fn layout(menu: &[TrayItem], id: i32) -> Layout { + let children = if id == ROOT { + (1..=menu.len() as i32).filter_map(|child| OwnedValue::try_from(Value::from(layout(menu, child))).ok()).collect() + } else { Vec::new() }; + (id, properties(menu, id), children) +} + +struct Item { model: Shared, on_event: Handler } + +#[zbus::interface(name = "org.kde.StatusNotifierItem")] +impl Item { + fn activate(&self, _x: i32, _y: i32) { + let token = self.model.lock().unwrap().token.take(); + (self.on_event)(TrayEvent::Activate { token }); + } + fn secondary_activate(&self, _x: i32, _y: i32) {} + /// The host draws the menu from `Menu`. + fn context_menu(&self, _x: i32, _y: i32) {} + fn scroll(&self, _delta: i32, _orientation: &str) {} + fn provide_xdg_activation_token(&self, token: String) { self.model.lock().unwrap().token = Some(token); } + #[zbus(property)] + fn category(&self) -> &str { "ApplicationStatus" } + #[zbus(property)] + fn id(&self) -> String { self.model.lock().unwrap().id.clone() } + #[zbus(property)] + fn title(&self) -> String { self.model.lock().unwrap().title.clone() } + #[zbus(property)] + fn status(&self) -> &str { "Active" } + #[zbus(property)] + fn window_id(&self) -> i32 { 0 } + /// A host that resolves the name draws that icon, and may recolour a symbolic one to fit its + /// panel; one that can't, or gets no name, draws `IconPixmap`. + #[zbus(property)] + fn icon_name(&self) -> String { self.model.lock().unwrap().icon_name.clone() } + #[zbus(property)] + fn icon_pixmap(&self) -> Pixmaps { self.model.lock().unwrap().pixmaps.clone() } + #[zbus(property)] + fn tool_tip(&self) -> (String, Pixmaps, String, String) { + (String::new(), Vec::new(), self.model.lock().unwrap().tooltip.clone(), String::new()) + } + #[zbus(property)] + fn item_is_menu(&self) -> bool { false } + #[zbus(property)] + fn menu(&self) -> OwnedObjectPath { OwnedObjectPath::try_from(MENU_PATH).expect("MENU_PATH is an object path") } + #[zbus(signal)] + async fn new_tool_tip(emitter: &SignalEmitter<'_>) -> zbus::Result<()>; +} + +struct Menu { model: Shared, on_event: Handler } +impl Menu { + fn clicked(&self, id: i32, event: &str) { + if event != "clicked" || id <= ROOT { return; } + let picked = match self.model.lock().unwrap().menu.get(id as usize - 1) { + Some(TrayItem::Action { id, enabled: true, .. }) => id.clone(), + _ => return, + }; + (self.on_event)(TrayEvent::Menu(picked)); + } +} + +#[zbus::interface(name = "com.canonical.dbusmenu")] +impl Menu { + fn get_layout(&self, parent_id: i32, _recursion_depth: i32, _property_names: Vec<String>) -> (u32, Layout) { + let model = self.model.lock().unwrap(); + (model.revision, layout(&model.menu, parent_id)) + } + fn get_group_properties(&self, ids: Vec<i32>, _property_names: Vec<String>) -> Vec<(i32, HashMap<String, OwnedValue>)> { + let model = self.model.lock().unwrap(); + // No ids asks for every item. + let ids = if ids.is_empty() { (1..=model.menu.len() as i32).collect() } else { ids }; + ids.into_iter().map(|id| (id, properties(&model.menu, id))).collect() + } + fn get_property(&self, id: i32, name: String) -> zbus::fdo::Result<OwnedValue> { + properties(&self.model.lock().unwrap().menu, id).remove(&name) + .ok_or_else(|| zbus::fdo::Error::InvalidArgs("no such menu property".into())) + } + fn event(&self, id: i32, event_id: String, _data: OwnedValue, _timestamp: u32) { self.clicked(id, &event_id); } + fn event_group(&self, events: Vec<(i32, String, OwnedValue, u32)>) -> Vec<i32> { + for (id, event, _, _) in events { self.clicked(id, &event); } + Vec::new() + } + fn about_to_show(&self, _id: i32) -> bool { false } + fn about_to_show_group(&self, _ids: Vec<i32>) -> (Vec<i32>, Vec<i32>) { (Vec::new(), Vec::new()) } + #[zbus(property)] + fn version(&self) -> u32 { 3 } + #[zbus(property)] + fn text_direction(&self) -> &str { "ltr" } + #[zbus(property)] + fn status(&self) -> &str { "normal" } + #[zbus(property)] + fn icon_theme_path(&self) -> Vec<String> { Vec::new() } + #[zbus(signal)] + async fn layout_updated(emitter: &SignalEmitter<'_>, revision: u32, parent: i32) -> zbus::Result<()>; +} + +/// Asks the watcher to show the item, named by this connection's unique name so the host +/// finds it at `/StatusNotifierItem`. No watcher means no tray host yet. +async fn register(conn: &Connection) { + let Some(name) = conn.unique_name().map(|n| n.to_string()) else { return }; + let call = async { + let watcher = Proxy::new(conn, WATCHER, WATCHER_PATH, WATCHER).await?; + watcher.call::<_, _, ()>("RegisterStatusNotifierItem", &(name.as_str(),)).await + }; + let _ = portal::timeout(RPC_TIMEOUT, call).await; +} + +impl Native { + pub(super) fn new(spec: TraySpec, on_event: Handler) -> Result<Self, TrayError> { + let model = Arc::new(Mutex::new(Model { pixmaps: pixmaps(&spec), id: spec.id, title: spec.title, tooltip: spec.tooltip, + icon_name: spec.icon_name, menu: spec.menu, revision: 1, token: None })); + let (commands, receiver) = unbounded(); + let (ready, result) = mpsc::sync_channel(1); + let worker = std::thread::Builder::new().name("rune-tray".into()).spawn(move || { + async_io::block_on(async move { + let setup = async { + let conn = zbus::connection::Builder::session()? + .serve_at(ITEM_PATH, Item { model: model.clone(), on_event: on_event.clone() })? + .serve_at(MENU_PATH, Menu { model: model.clone(), on_event })? + .build().await?; + let bus = Proxy::new(&conn, "org.freedesktop.DBus", "/org/freedesktop/DBus", "org.freedesktop.DBus").await?; + let owners = bus.receive_signal_with_args("NameOwnerChanged", &[(0, WATCHER)]).await?; + Ok::<_, zbus::Error>((conn, owners)) + }; + let (conn, mut owners) = match portal::timeout(RPC_TIMEOUT, setup).await { + Some(Ok(v)) => { ready.send(Ok(())).ok(); v } + Some(Err(e)) => { ready.send(Err(backend(e))).ok(); return; } + None => { ready.send(Err(backend("session bus timed out"))).ok(); return; } + }; + register(&conn).await; + enum Wake { + Command(Option<Command>), + Owner(Option<zbus::Message>), + } + loop { + let next = async { Wake::Command(receiver.recv().await.ok()) } + .or(async { Wake::Owner(owners.next().await) }) + .await; + match next { + Wake::Command(Some(Command::Menu(menu))) => { + let revision = { let mut m = model.lock().unwrap(); m.menu = menu; m.revision += 1; m.revision }; + if let Ok(emitter) = SignalEmitter::new(&conn, MENU_PATH) { Menu::layout_updated(&emitter, revision, ROOT).await.ok(); } + } + Wake::Command(Some(Command::Tooltip(tooltip))) => { + model.lock().unwrap().tooltip = tooltip; + if let Ok(emitter) = SignalEmitter::new(&conn, ITEM_PATH) { Item::new_tool_tip(&emitter).await.ok(); } + } + Wake::Command(None) | Wake::Owner(None) => break, + Wake::Owner(Some(changed)) => { + let owner = changed.body().deserialize::<(String, String, String)>().map(|(_, _, new)| new); + if owner.is_ok_and(|new| !new.is_empty()) { register(&conn).await; } + } + } + } + // Closing the connection removes the icon at once. + conn.close().await.ok(); + }); + }).map_err(backend)?; + match result.recv() { + Ok(Ok(())) => Ok(Self { commands: Some(commands), worker: Some(worker) }), + Ok(Err(e)) => { worker.join().ok(); Err(e) } + Err(_) => { worker.join().ok(); Err(backend("tray thread exited")) } + } + } + pub(super) fn set_menu(&self, menu: Vec<TrayItem>) { + if let Some(c) = &self.commands { c.try_send(Command::Menu(menu)).ok(); } + } + pub(super) fn set_tooltip(&self, tooltip: String) { + if let Some(c) = &self.commands { c.try_send(Command::Tooltip(tooltip)).ok(); } + } +} + +impl Drop for Native { + fn drop(&mut self) { + self.commands.take(); + if let Some(worker) = self.worker.take() { worker.join().ok(); } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use zbus::zvariant::Type; + + fn menu() -> Vec<TrayItem> { vec![TrayItem::action("show", "Show"), TrayItem::Separator, TrayItem::action("quit", "Quit").enabled(false)] } + + #[test] + fn the_layout_has_the_dbusmenu_shape() { + assert_eq!(<(u32, Layout)>::SIGNATURE.to_string(), "(u(ia{sv}av))"); + let (id, props, children) = layout(&menu(), ROOT); + assert_eq!(id, ROOT); + assert!(props.contains_key("children-display")); + assert_eq!(children.len(), 3); + } + + #[test] + fn items_carry_label_type_and_enabled() { + let menu = menu(); + assert!(properties(&menu, 1).contains_key("label")); + assert!(properties(&menu, 2).contains_key("type")); + assert!(properties(&menu, 3).contains_key("enabled")); + assert!(properties(&menu, 9).is_empty()); + let underscored = vec![TrayItem::action("open", "open_file")]; + let props = properties(&underscored, 1); + assert_eq!(<&str>::try_from(props.get("label").unwrap()).ok(), Some("open__file")); + } + + #[test] + fn the_icon_is_argb_in_network_order() { + let spec = TraySpec::new("t", "T", super::super::TrayIcon::rgba(1, 1, vec![1, 2, 3, 4])); + assert_eq!(pixmaps(&spec), vec![(1, 1, vec![4, 1, 2, 3])]); + } + + fn item(icon_name: &str) -> Item { + let spec = TraySpec::new("t", "T", super::super::TrayIcon::rgba(1, 1, vec![1, 2, 3, 4])).icon_name(icon_name); + let pixmaps = pixmaps(&spec); + let model = Model { id: spec.id, title: spec.title, tooltip: spec.tooltip, icon_name: spec.icon_name, + pixmaps, menu: spec.menu, revision: 1, token: None }; + Item { model: Arc::new(Mutex::new(model)), on_event: Arc::new(|_| {}) } + } + + #[test] + fn the_icon_name_is_served_and_empty_until_set() { + assert_eq!(item("").icon_name(), ""); + assert_eq!(item("my-app-symbolic").icon_name(), "my-app-symbolic"); + assert_eq!(item("my-app-symbolic").icon_pixmap(), vec![(1, 1, vec![4, 1, 2, 3])]); + } +} diff --git a/app/vendor/rune/crates/rune/src/tray/win32.rs b/app/vendor/rune/crates/rune/src/tray/win32.rs new file mode 100644 index 0000000..0683f9b --- /dev/null +++ b/app/vendor/rune/crates/rune/src/tray/win32.rs @@ -0,0 +1,202 @@ +//! `Shell_NotifyIcon` on a message-only window that owns its thread and message loop. A left +//! click activates; a right click opens a `TrackPopupMenu` menu. The icon comes back when +//! Explorer restarts (`TaskbarCreated`). + +#![allow(unsafe_code)] + +use super::{Handler, TrayError, TrayEvent, TrayItem, TraySpec}; +use std::{ptr, sync::{Arc, Mutex, mpsc}, thread::JoinHandle}; +use windows_sys::Win32::{Foundation::*, System::LibraryLoader::GetModuleHandleW, UI::{Shell::*, WindowsAndMessaging::*}}; + +const CALLBACK: u32 = WM_APP + 1; +const UPDATE: u32 = WM_APP + 2; +const ICON_ID: u32 = 1; + +struct Model { tooltip: String, menu: Vec<TrayItem> } +struct Context { model: Arc<Mutex<Model>>, on_event: Handler, icon: HICON, taskbar_created: u32 } +pub(super) struct Native { window: isize, model: Arc<Mutex<Model>>, worker: Option<JoinHandle<()>> } + +fn wide(s: &str) -> Vec<u16> { s.encode_utf16().chain(Some(0)).collect() } +fn last_error(what: &str) -> TrayError { + // SAFETY: Reads this thread's last Win32 status immediately after a failed call. + TrayError::Backend(format!("{what} failed: Win32 error {}", unsafe { GetLastError() })) +} + +/// A 32-bit BGRA icon; the AND mask is the inverted alpha, which Windows ignores beside alpha. +fn create_icon(spec: &TraySpec) -> HICON { + let mut bgra = spec.icon.rgba.clone(); + let mut mask = Vec::with_capacity(bgra.len() / 4); + for p in bgra.chunks_exact_mut(4) { p.swap(0, 2); mask.push(p[3].wrapping_sub(u8::MAX)); } + // SAFETY: Both buffers hold width × height pixels and outlive the call, which copies them. + unsafe { CreateIcon(ptr::null_mut(), spec.icon.width as i32, spec.icon.height as i32, 1, 32, mask.as_ptr(), bgra.as_ptr()) } +} + +pub(super) fn data(hwnd: HWND, flags: u32) -> NOTIFYICONDATAW { + // SAFETY: NOTIFYICONDATAW is plain data; zero is its documented empty value. + let mut data: NOTIFYICONDATAW = unsafe { std::mem::zeroed() }; + data.cbSize = size_of::<NOTIFYICONDATAW>() as u32; + data.hWnd = hwnd; + data.uID = ICON_ID; + data.uFlags = flags; + data +} +pub(super) fn set_tip(data: &mut NOTIFYICONDATAW, tooltip: &str) { + let tip = super::truncate_utf16(tooltip, data.szTip.len() - 1); + data.szTip[..tip.len()].copy_from_slice(&tip); + data.szTip[tip.len()] = 0; +} +fn notify(hwnd: HWND, context: &Context, message: NOTIFY_ICON_MESSAGE) -> bool { + let mut data = data(hwnd, NIF_MESSAGE | NIF_ICON | NIF_TIP); + data.uCallbackMessage = CALLBACK; + data.hIcon = context.icon; + set_tip(&mut data, &context.model.lock().unwrap().tooltip); + // SAFETY: `data` is fully initialized for this window's icon. + unsafe { Shell_NotifyIconW(message, &data) != 0 } +} + +/// Shows the menu at the cursor and returns the picked item's id. +fn pick(hwnd: HWND, context: &Context) -> Option<String> { + let menu = context.model.lock().unwrap().menu.clone(); + // SAFETY: The menu is created, shown and destroyed on this window's thread. + unsafe { + let popup = CreatePopupMenu(); + if popup.is_null() { return None; } + for (index, item) in menu.iter().enumerate() { + match item { + TrayItem::Action { label, enabled, .. } => { + let Ok(command) = u16::try_from(index + 1) else { break }; + let flags = if *enabled { MF_STRING } else { MF_STRING | MF_GRAYED }; + AppendMenuW(popup, flags, usize::from(command), wide(&super::win32_menu_label(label)).as_ptr()); + } + TrayItem::Separator => { AppendMenuW(popup, MF_SEPARATOR, 0, ptr::null()); } + } + } + let mut at = POINT { x: 0, y: 0 }; + GetCursorPos(&mut at); + // Without the foreground, the menu doesn't close when the user clicks elsewhere. + SetForegroundWindow(hwnd); + let flags = TPM_RETURNCMD | TPM_NONOTIFY | TPM_RIGHTBUTTON | crate::popup_menu::layout(); + let picked = TrackPopupMenu(popup, flags, at.x, at.y, 0, hwnd, ptr::null()); + PostMessageW(hwnd, WM_NULL, 0, 0); + DestroyMenu(popup); + match menu.get((picked as usize).checked_sub(1)?) { Some(TrayItem::Action { id, .. }) => Some(id.clone()), _ => None } + } +} + +unsafe extern "system" fn procedure(hwnd: HWND, message: u32, w: WPARAM, l: LPARAM) -> LRESULT { + // SAFETY: Windows owns the message parameters. The context outlives the window and is only + // used on its thread; it is cleared before destruction completes. + unsafe { + if message == WM_NCCREATE { + let create = &*(l as *const CREATESTRUCTW); + SetWindowLongPtrW(hwnd, GWLP_USERDATA, create.lpCreateParams as isize); + } + let Some(context) = (GetWindowLongPtrW(hwnd, GWLP_USERDATA) as *const Context).as_ref() else { + return DefWindowProcW(hwnd, message, w, l); + }; + match message { + CALLBACK => { + let event = match l as u32 { + WM_LBUTTONUP => Some(TrayEvent::Activate { token: None }), + WM_RBUTTONUP => pick(hwnd, context).map(TrayEvent::Menu), + _ => None, + }; + if let Some(event) = event { + std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| (context.on_event)(event))).ok(); + } + 0 + } + UPDATE => { notify(hwnd, context, NIM_MODIFY); 0 } + WM_DESTROY => { + Shell_NotifyIconW(NIM_DELETE, &data(hwnd, 0)); + PostQuitMessage(0); + 0 + } + WM_NCDESTROY => { SetWindowLongPtrW(hwnd, GWLP_USERDATA, 0); DefWindowProcW(hwnd, message, w, l) } + m if m == context.taskbar_created => { notify(hwnd, context, NIM_ADD); 0 } + _ => DefWindowProcW(hwnd, message, w, l), + } + } +} + +/// Creates the window and icon on this thread; the context lives as long as the window. +fn create(context: &mut Context) -> Result<HWND, TrayError> { + let class = wide("RuneTray"); + // SAFETY: Class name is NUL-terminated; the context is stable until the loop ends. + unsafe { + let instance = GetModuleHandleW(ptr::null()); + let wc = WNDCLASSW { lpfnWndProc: Some(procedure), hInstance: instance, lpszClassName: class.as_ptr(), ..std::mem::zeroed() }; + if RegisterClassW(&wc) == 0 && GetLastError() != ERROR_CLASS_ALREADY_EXISTS { return Err(last_error("RegisterClassW")); } + let hwnd = CreateWindowExW(0, class.as_ptr(), ptr::null(), 0, 0, 0, 0, 0, HWND_MESSAGE, ptr::null_mut(), instance, + (context as *mut Context).cast()); + if hwnd.is_null() { return Err(last_error("CreateWindowExW")); } + if !notify(hwnd, context, NIM_ADD) { DestroyWindow(hwnd); return Err(last_error("Shell_NotifyIconW")); } + Ok(hwnd) + } +} + +impl Native { + pub(super) fn new(spec: TraySpec, on_event: Handler) -> Result<Self, TrayError> { + let model = Arc::new(Mutex::new(Model { tooltip: spec.tooltip.clone(), menu: spec.menu.clone() })); + let shared = model.clone(); + let (ready, result) = mpsc::sync_channel(1); + let worker = std::thread::Builder::new().name("rune-tray".into()).spawn(move || { + let icon = create_icon(&spec); + // SAFETY: The name is NUL-terminated. + let taskbar_created = unsafe { RegisterWindowMessageW(wide("TaskbarCreated").as_ptr()) }; + let mut context = Box::new(Context { model: shared, on_event, icon, taskbar_created }); + match create(&mut context) { + Ok(hwnd) => { ready.send(Ok(hwnd as isize)).ok(); } + Err(e) => { + // SAFETY: The icon was created above and nothing else holds it. + if !icon.is_null() { unsafe { DestroyIcon(icon) }; } + ready.send(Err(e)).ok(); + return; + } + } + // SAFETY: A plain message loop for this thread's window; it ends with WM_QUIT. + unsafe { + let mut msg: MSG = std::mem::zeroed(); + while GetMessageW(&mut msg, ptr::null_mut(), 0, 0) > 0 { TranslateMessage(&msg); DispatchMessageW(&msg); } + if !icon.is_null() { DestroyIcon(icon); } + } + drop(context); + }).map_err(|e| TrayError::Backend(e.to_string()))?; + match result.recv() { + Ok(Ok(window)) => { + LIVE.lock().unwrap_or_else(|e| e.into_inner()).push(window); + Ok(Self { window, model, worker: Some(worker) }) + } + Ok(Err(e)) => { worker.join().ok(); Err(e) } + Err(_) => { worker.join().ok(); Err(TrayError::Backend("tray thread exited".into())) } + } + } + fn update(&self) { + // SAFETY: Posting to a window owned by the tray thread; a gone window drops the message. + unsafe { PostMessageW(self.window as HWND, UPDATE, 0, 0) }; + } + pub(super) fn set_menu(&self, menu: Vec<TrayItem>) { self.model.lock().unwrap().menu = menu; } + pub(super) fn set_tooltip(&self, tooltip: String) { self.model.lock().unwrap().tooltip = tooltip; self.update(); } +} + +/// The windows of the trays alive now, so a fast exit can take their icons off the +/// notification area (an icon a process leaves behind stays until the pointer passes over it). +static LIVE: Mutex<Vec<isize>> = Mutex::new(Vec::new()); + +/// Removes every tray icon at once, from whatever thread (`NIM_DELETE` names the icon by its +/// window and id); their threads and windows go with the process. +pub(super) fn remove_all() { + for &window in LIVE.lock().unwrap_or_else(|e| e.into_inner()).iter() { + // SAFETY: `data` names an icon this process added; a removed one fails harmlessly. + unsafe { Shell_NotifyIconW(NIM_DELETE, &data(window as HWND, 0)) }; + } +} + +impl Drop for Native { + fn drop(&mut self) { + LIVE.lock().unwrap_or_else(|e| e.into_inner()).retain(|&w| w != self.window); + // SAFETY: WM_CLOSE destroys the window on its own thread, which then quits its loop. + unsafe { PostMessageW(self.window as HWND, WM_CLOSE, 0, 0) }; + if let Some(worker) = self.worker.take() { worker.join().ok(); } + } +} diff --git a/app/vendor/rune/crates/rune/src/window.rs b/app/vendor/rune/crates/rune/src/window.rs new file mode 100644 index 0000000..e324479 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/window.rs @@ -0,0 +1,508 @@ +//! One event loop, independent window lifetime hosts. App/AppHandle and multi-window +//! factories share the same input, rendering, activation and close/reopen paths. + +use std::sync::{Arc, Mutex, Weak, atomic::{AtomicBool, AtomicU32, Ordering}}; +use std::{cell::RefCell, rc::Rc}; +#[cfg(test)] +use std::time::Duration; +use crate::time::Instant; + +use winit::application::ApplicationHandler; +use winit::event::{MouseButton, StartCause, TouchPhase, WindowEvent}; +use winit::event_loop::{ActiveEventLoop, ControlFlow, EventLoopProxy}; +use winit::window::{Window, WindowId}; +use winit::raw_window_handle::HasWindowHandle; + +use crate::app::WindowRequest; +use crate::frame::surface_stats::SurfaceStats; +#[cfg(all(test, target_os = "linux"))] +use crate::frame::surface_stats::SurfaceMeter; +use crate::render::Gpu; +use crate::runtime::{AppDriver, Runtime, RuntimeCore}; +use crate::tooling::Args; +use crate::windows::{AnyWindowSpec, Display, WindowSpec}; +#[cfg(test)] +use crate::el::Tx; +#[cfg(test)] +use crate::tooling::Chrome; + +mod app_events; +mod chrome; +mod event_loop; +mod file_drop; +mod handle; +mod host; +mod keys; +pub mod spec; +mod state; +mod surface; +pub(crate) mod titlebar; +#[cfg(target_os = "windows")] +mod win32; + +pub use handle::WindowHandle; +#[cfg(not(target_arch = "wasm32"))] +pub use event_loop::run; +pub(crate) use event_loop::run_windows; +#[cfg(any(target_os = "macos", target_os = "windows"))] +pub(crate) use file_drop::FileStep; +pub(crate) use keys::{key_base, map_key_event, map_mods}; +pub(crate) use state::frame; +pub(crate) use state::{Life, Minimize, MinimizeEvent, Sight}; +pub(crate) use surface::{ + Backoff, BackoffEffect, BackoffEvent, HiddenPace, Missed, Presented, TIMER_FRAME, + acquire_checked, configure, reblend_core, rebuild_renderer_core, + surface_config, timer_deadline_core, timer_wants_frame_core, +}; +#[cfg(test)] +pub(crate) use surface::{ + HIDDEN_REFRESH, OCCLUDED_MAX, OCCLUDED_RETRY, TIMEOUT_RETRY, TIMER_FRAME_STALL, TimerFrame, + timer_deadline, timer_wants_frame, wall_wake_deadline, +}; +#[cfg(all(test, target_os = "linux"))] +use surface::acquire; +#[cfg(target_os = "windows")] +pub(crate) use win32::slot; + +use host::Host; +#[cfg(test)] +use chrome::uses_drag_regions; +#[cfg(test)] +use host::setup_waker; +#[cfg(test)] +use state::{WakeFacts, WakeWork}; +#[cfg(all(test, target_os = "macos"))] +use surface::LaunchDrawables; +#[cfg(test)] +use surface::{SurfaceRetries, composing}; + +/// Records a presented frame and wakes Windows' deferred ICU word segmenter on the first one. +pub(super) fn frame_presented() { + if crate::marks::presented() { + #[cfg(all(target_os = "windows", not(feature = "segmenter-dictionaries")))] + crate::platform::win32::segmenter::first_frame_presented(); + } +} + +#[cfg(test)] +mod tests; + +pub(crate) enum WakeEvent { + DisplayTick(usize), + App(usize), Live(usize), Window(usize, WindowRequest), Focus(usize), + Position(usize, (i32, i32)), Level(usize, bool), + Place(usize, crate::windows::PlaceRequest), + Frame(usize, crate::window::frame::FrameRequest), + /// Windows: the window's or an overlay's swap chain can take the frame it waits for (`slot`). + #[cfg_attr(not(target_os = "windows"), allow(dead_code))] + FrameSlot(usize), + /// The app was reopened (macOS: its Dock icon clicked; Windows: launched again while it + /// runs, see `single_instance`); for `Windows`, not one host. + #[cfg_attr(not(any(target_os = "macos", target_os = "windows")), allow(dead_code))] + Reopen, + /// The system asks the app to quit (`crate::quit`): every window's `App::on_quit` runs; + /// with `true` the session ends now and the windows close. + #[cfg_attr(not(target_os = "windows"), allow(dead_code))] + Quit(bool), + /// An assistive client asked something of a surface's accessibility tree (`crate::a11y`): + /// the host answers at the end of the turn this wakes. + #[cfg_attr(not(feature = "accessibility"), allow(dead_code))] + A11y(usize), + /// A native menu's modal loop holds the event loop: run its idle turn (`Windows::turn`). + #[cfg_attr(not(target_os = "windows"), allow(dead_code))] + Turn, + /// Windows: the GPU a CPU-drawn window was waiting for is made, or failed (`cpu_frame`). + #[cfg_attr(not(target_os = "windows"), allow(dead_code))] + GpuReady(usize), +} + +/// What `Windows` needs of a host, whatever its state type: an app window or an overlay. +pub(crate) trait AnyHost { + fn new_events(&mut self, _event_loop: &ActiveEventLoop, _cause: StartCause) {} + fn wake_deadline(&self) -> Option<Instant> { None } + fn resumed(&mut self, event_loop: &ActiveEventLoop); + fn user_event(&mut self, event_loop: &ActiveEventLoop, event: WakeEvent); + fn owns(&self, id: WindowId) -> bool; + fn window_event(&mut self, event_loop: &ActiveEventLoop, id: WindowId, event: WindowEvent); + /// Draws what has no redraw event (a layer surface); true while it needs more frames. + fn about_to_wait(&mut self, _event_loop: &ActiveEventLoop) -> bool { false } + /// The turn ends: the next frame it wants is asked for, or a paint put off runs (`redraw`). + fn turn_ends(&mut self, _event_loop: &ActiveEventLoop, _now: Instant) {} + fn finished(&self) -> bool { false } + /// The OS is ending the app without Rune asking: run close hooks before the hosts drop. + fn terminate(&mut self) {} + /// The app starts to quit: runs `App::on_quit`, unless the window already closed. + fn quit_hook(&mut self) {} + /// The app quits: off the screen now, before any hook runs. + fn vanish(&mut self) {} + /// The close about to come ends the app (`Host::close`). + fn closing_ends_app(&mut self) {} + /// Ends a tracking pop-up menu and answers waiting ones `None`, before the host drops or + /// the loop exits. + fn cancel_menus(&mut self) {} + /// False for hosts that must not keep the loop running alone (overlays). + fn keeps_loop(&self) -> bool { true } + /// An app window's key; overlays have none. + fn key(&self) -> Option<&str> { None } + /// How reopening the app sees it; overlays never come back. + fn reopen_candidate(&self) -> crate::platform::reopen::Candidate { Default::default() } + /// Runs `App::on_reopen` as an update; true when it handled the reopen. + fn reopen_hook(&mut self, _event_loop: &ActiveEventLoop, _has_visible_windows: bool) -> bool { false } + /// Applies what was asked of it through its handle since the last wake, now rather than + /// when that wake arrives. + fn apply_pending(&mut self, _event_loop: &ActiveEventLoop) {} + /// Shows, restores and activates it as the default reopen. + fn reopen(&mut self, _event_loop: &ActiveEventLoop) {} +} + +/// Builds every host, attaching its shortcut and menu guards, before any resumes: a window's +/// first updates drain on resume and may register on a later window. +fn start_all<T, H>(items: Vec<T>, mut build: impl FnMut(usize, T) -> Option<H>, resume: impl FnMut(&mut H)) -> Vec<Option<H>> { + let mut hosts: Vec<_> = items.into_iter().enumerate().map(|(slot, item)| build(slot, item)).collect(); + hosts.iter_mut().flatten().for_each(resume); + hosts +} + +type Factory = Box<dyn FnOnce(&[Display]) -> Vec<AnyWindowSpec>>; + +struct Windows { + factory: Option<Factory>, + args: Args, + proxy: EventLoopProxy<WakeEvent>, + hosts: Vec<Option<Box<dyn AnyHost>>>, + // Weak pool preserves release_gpu_when_closed when the last GPU owner closes. + gpu: Rc<RefCell<Weak<Gpu>>>, +} +impl Windows { + /// Starts the windows `crate::open_window` asked for this turn, in fresh slots, each like + /// a window the factory returned but without `--scene` or `--size`, which describe the + /// launch's windows. + fn open_requested(&mut self, event_loop: &ActiveEventLoop) { + if self.factory.is_some() { return; } + loop { + let specs = crate::windows::flatten(crate::windows::take_opened()); + if specs.is_empty() { return; } + let wayland = is_wayland(event_loop); + for spec in specs { + if self.hosts.iter().flatten().any(|h| h.key() == Some(spec.key())) { + eprintln!("rune: a window keyed {:?} is already open", spec.key()); + continue; + } + let mut args = self.args.clone(); + (args.scene, args.size) = (None, None); + let mut overlays = Vec::new(); + let slot = self.hosts.len(); + let host = spec.start(args, Start { proxy: self.proxy.clone(), slot, gpu: self.gpu.clone(), wayland, traced: false, overlays: &mut overlays }); + self.hosts.push(host); + if let Some(Some(host)) = self.hosts.get_mut(slot) { host.resumed(event_loop); } + self.connect_overlays(overlays, event_loop); + } + } + } + + fn connect_overlays(&mut self, overlays: Vec<Box<dyn crate::overlay::PendingOverlay>>, event_loop: &ActiveEventLoop) { + for mut overlay in overlays { + let (slot, proxy) = (self.hosts.len(), self.proxy.clone()); + let frame_proxy = proxy.clone(); + let slot_proxy = proxy.clone(); + overlay.connect(Arc::new(move || { proxy.send_event(WakeEvent::App(slot)).ok(); }), + Arc::new(move || { frame_proxy.send_event(WakeEvent::DisplayTick(slot)).ok(); }), + Arc::new(move || { slot_proxy.send_event(WakeEvent::FrameSlot(slot)).ok(); }), self.gpu.clone()); + overlay.resumed(event_loop); + self.hosts.push(Some(overlay)); + } + } + + fn cleanup(&mut self, event_loop: &ActiveEventLoop) { + if !event_loop.exiting() { self.open_requested(event_loop); } + // The last window closing ends a fast-exiting app: its host isn't dropped first, which + // tore down its window, swap chain and device (~37 ms) before the process ended anyway. + #[cfg(not(target_arch = "wasm32"))] + let ending = crate::quit::fast_exit_hook().is_some() && !self.hosts.iter().flatten().any(|h| !h.finished() && h.keeps_loop()); + #[cfg(target_arch = "wasm32")] + let ending = false; + for host in &mut self.hosts { + if let Some(h) = host.as_mut().filter(|h| h.finished()) { + h.cancel_menus(); + if !ending { *host = None; } + } + } + // Another window's quit: a menu still tracking would hold the loop open. + if event_loop.exiting() { + for host in self.hosts.iter_mut().flatten() { host.cancel_menus(); } + } + if !self.hosts.iter().flatten().any(|h| h.keeps_loop() && !h.finished()) { + // The app ends with its last main window: windows still open close as their close + // button would, once the quit's hooks ran. A quit already asked to exit and skips + // their close hooks. + if !event_loop.exiting() { + self.quit(event_loop, false, true); + for host in self.hosts.iter_mut().flatten() { host.terminate(); } + } + event_loop.exit(); + } + } +} + +/// What a window needs from the shell to start, whatever its state type. +pub(crate) struct Start<'a> { + proxy: EventLoopProxy<WakeEvent>, + slot: usize, + gpu: Rc<RefCell<Weak<Gpu>>>, + wayland: bool, + /// Whether this window records `--native` traces. + traced: bool, + overlays: &'a mut Vec<Box<dyn crate::overlay::PendingOverlay>>, +} + +impl Start<'_> { + fn inherit_args(&self, mut inherited: Args) -> Args { + if inherited.native && !self.traced { + inherited.trace = None; + inherited.frames = None; + } + inherited + } +} + +/// Starts one window's host, or renders it headless when its own arguments ask for that. +pub(crate) fn start<S: 'static>(mut spec: WindowSpec<S>, handle: Option<WindowHandle>, keeps_loop: bool, inherited: Args, cx: Start<'_>) -> Option<Box<dyn AnyHost>> { + let args = spec.app.resolve_args(cx.inherit_args(inherited)); + #[cfg(not(any(feature = "tooling", debug_assertions)))] + if args.headless() { crate::tooling::die(crate::tooling::WITHOUT_TOOLING); } + #[cfg(any(feature = "tooling", debug_assertions))] + if args.headless() { + let scale = args.scale.unwrap_or(2.0); + crate::tooling::headless_window_spec(spec.app, spec.options, args, scale); + return None; + } + let open_urls = crate::open_url::incoming::listen(&spec.app); + Some(Box::new(Host::new(spec, handle, args, cx, keeps_loop, open_urls))) +} + +impl ApplicationHandler<WakeEvent> for Windows { + fn new_events(&mut self, event_loop: &ActiveEventLoop, cause: StartCause) { + let _handling = crate::quit::handling(); + for host in self.hosts.iter_mut().flatten() { host.new_events(event_loop, cause); } + // Before resumed there are no hosts to clean up. + if self.factory.is_none() { self.cleanup(event_loop); } + } + fn resumed(&mut self, event_loop: &ActiveEventLoop) { + let _handling = crate::quit::handling(); + let Some(factory) = self.factory.take() else { return }; + crate::marks::mark("loop.resumed"); + let primary = event_loop.primary_monitor(); + let displays: Vec<_> = event_loop.available_monitors().map(|m| Display { + id: Some(crate::DisplayId::from_monitor(m.clone(), is_wayland(event_loop))), + name: m.name(), position: (m.position().x, m.position().y), + size: (m.size().width, m.size().height), scale: m.scale_factor(), primary: primary.as_ref() == Some(&m), + }).collect(); + let specs = crate::windows::flatten(factory(&displays)); + crate::windows::validate(&specs).expect("window keys"); + let trace_window = self.args.window.clone().or_else(|| specs.first().map(|s| s.key().to_owned())); + let mut overlays = Vec::new(); + let wayland = is_wayland(event_loop); + self.hosts = start_all(specs, |slot, spec| { + let traced = trace_window.as_deref() == Some(spec.key()); + spec.start(self.args.clone(), Start { proxy: self.proxy.clone(), slot, gpu: self.gpu.clone(), wayland, traced, overlays: &mut overlays }) + }, |host| host.resumed(event_loop)); + self.connect_overlays(overlays, event_loop); + #[cfg(target_os = "macos")] + { + let proxy = self.proxy.clone(); + crate::platform::reopen::install(move || proxy.send_event(WakeEvent::Reopen).is_ok()); + } + #[cfg(any(target_os = "windows", target_os = "linux"))] + { + let proxy = self.proxy.clone(); + crate::open_url::instance::on_relaunch(move || proxy.send_event(WakeEvent::Reopen).is_ok()); + } + let proxy = self.proxy.clone(); + crate::quit::install(move |ending| proxy.send_event(WakeEvent::Quit(ending)).is_ok()); + crate::open_url::incoming::settle(); + // A window opened at launch took it; a GPU kept for a later one would sit idle until then. + crate::render::discard_prewarm(); + self.cleanup(event_loop); + } + fn user_event(&mut self, event_loop: &ActiveEventLoop, event: WakeEvent) { + let _handling = crate::quit::handling(); + let slot = match &event { + WakeEvent::DisplayTick(i) | WakeEvent::App(i) | WakeEvent::Live(i) | WakeEvent::Window(i, _) | WakeEvent::Focus(i) + | WakeEvent::Position(i, _) | WakeEvent::Level(i, _) | WakeEvent::Place(i, _) | WakeEvent::Frame(i, _) + | WakeEvent::A11y(i) | WakeEvent::FrameSlot(i) | WakeEvent::GpuReady(i) => *i, + WakeEvent::Reopen => { + self.reopen(event_loop); + self.cleanup(event_loop); + return; + } + // A session query (`ending: false`) can still be cancelled: the windows stay up. + WakeEvent::Quit(ending) => { + self.quit(event_loop, *ending, *ending); + self.cleanup(event_loop); + return; + } + WakeEvent::Turn => { #[cfg(not(target_arch = "wasm32"))] self.turn(event_loop); return; } + }; + if let Some(Some(host)) = self.hosts.get_mut(slot) { + host.user_event(event_loop, event); + } + self.cleanup(event_loop); + } + fn window_event(&mut self, event_loop: &ActiveEventLoop, id: WindowId, event: WindowEvent) { + let _handling = crate::quit::handling(); + // The last window's close ends a fast-exiting app: the window can go at once. + #[cfg(not(target_arch = "wasm32"))] + if matches!(event, WindowEvent::CloseRequested) && crate::quit::fast_exit_hook().is_some() + && !self.hosts.iter().flatten().any(|h| !h.owns(id) && !h.finished() && h.keeps_loop()) + && let Some(host) = self.hosts.iter_mut().flatten().find(|h| h.owns(id) && h.keeps_loop()) + { + host.closing_ends_app(); + } + if let Some(host) = self.hosts.iter_mut().flatten().find(|h| h.owns(id)) { + let _input = crate::input::time::arrived(&event); + host.window_event(event_loop, id, event); + } + self.cleanup(event_loop); + } + fn about_to_wait(&mut self, event_loop: &ActiveEventLoop) { + let _handling = crate::quit::handling(); + // Windows, Linux: a later launch handed to this loop (`single_instance`) is served once + // the app goes on with a window shown. One that came as the app ended (its last window + // already closing, the quit not started) isn't: the process starts the app again for it. + #[cfg(any(target_os = "windows", target_os = "linux"))] + if crate::open_url::instance::launches_waiting() && !event_loop.exiting() { + let windows: Vec<_> = self.hosts.iter().map(|h| h.as_ref().map(|h| h.reopen_candidate()).unwrap_or_default()).collect(); + if crate::platform::reopen::has_visible(&windows) { + crate::open_url::instance::served(); + } + } + crate::marks::loop_waits(); + crate::cursor::os::make_pending(event_loop); + let mut animating = false; + for host in self.hosts.iter_mut().flatten() { + animating |= host.about_to_wait(event_loop); + } + // The frames windows want next (`redraw`), and on Windows the paints the system keeps + // putting off behind another window's. + let now = crate::time::now(); + for host in self.hosts.iter_mut().flatten() { host.turn_ends(event_loop, now); } + // Layer surfaces have no redraw events: keep turning while one animates (its vsync + // paces the loop). Hosts whose only motion is an ambient loop sleep until its next step. + let deadline = self.hosts.iter().flatten().filter_map(|host| host.wake_deadline()).min(); + event_loop.set_control_flow(if animating { ControlFlow::Poll } + else { deadline.map_or(ControlFlow::Wait, |at| ControlFlow::WaitUntil(crate::time::for_winit(at))) }); + } + fn exiting(&mut self, event_loop: &ActiveEventLoop) { + let _handling = crate::quit::handling(); + crate::marks::mark("loop.exiting"); + // Every quit ends here, so the windows still open run `App::on_quit` first, unless the + // quit's hooks already ran (a Windows logoff, the last window closing). + self.quit(event_loop, false, true); + // Rune didn't ask to exit, so the OS is ending the app: macOS Quit, Cmd-Q, the Dock's + // Quit, logout. Windows close as their close button would, before the clipboard stops. + if !event_loop.exiting() { + for host in self.hosts.iter_mut().flatten() { host.terminate(); } + } + for host in self.hosts.iter_mut().flatten() { host.cancel_menus(); } + #[cfg(not(target_arch = "wasm32"))] + if let Some(last) = crate::quit::fast_exit_hook() { crate::quit::end_fast(last); } + // Surfaces go while winit's display connection is still open (layer surfaces live on it). + self.hosts.clear(); + crate::marks::mark("windows.dropped"); + crate::clipboard::shutdown(); + if crate::quit::send(crate::quit::Event::Exited).contains(&crate::quit::Effect::Relaunch) { + crate::relaunch::spawn(); + } + #[cfg(any(target_os = "windows", target_os = "linux"))] + crate::open_url::instance::exited(); + } +} + +/// What a shown window that can't draw runs for an update, a wake, a due timer or a redraw: +/// covered (an occlusion event, or a drawable refused as occluded), minimised, or waiting out +/// a missed frame. `poll`, due timers and queued input run now, as for a hidden window +/// (`Runtime::hidden_wake`); the view and layout wait, dirty, for the frame that uncovers it, +/// unless an assistive client reads the window (`Runtime::covered_wake`). +/// Uncovering settles first, so that frame builds once and paints motion where it would have +/// ended, as Core Animation's time-based motion has by the time a covered window shows again. +#[cfg_attr(not(test), allow(dead_code))] +#[inline(always)] +pub(crate) fn covered_step<S: 'static>(rt: &mut Runtime<S>) { rt.covered_wake(); } + +pub(crate) fn is_wayland(event_loop: &ActiveEventLoop) -> bool { + #[cfg(all(unix, not(target_os = "macos"), not(target_os = "ios"), not(target_os = "android")))] + return winit::platform::wayland::ActiveEventLoopExtWayland::is_wayland(event_loop); + #[cfg(not(all(unix, not(target_os = "macos"), not(target_os = "ios"), not(target_os = "android"))))] + { + let _ = event_loop; + false + } +} + +/// A window's content top-left in points from the primary display's top-left (see +/// `El::on_screen_layout`), the space an overlay's `OverlayPlacement::Rect` on +/// `DisplayTarget::Primary` is in. Elsewhere than macOS that's desktop pixels from the +/// primary's origin over the window's scale, as `overlay::position` converts the other way. +/// Wayland hides it. +pub(crate) fn screen_origin(window: &Window) -> Option<(f32, f32)> { + #[cfg(target_os = "macos")] + return crate::platform::macos::content_origin(window); + #[cfg(not(target_os = "macos"))] + { + let p = window.inner_position().ok()?; + let o = window.primary_monitor().map_or(winit::dpi::PhysicalPosition::new(0, 0), |m| m.position()); + let scale = window.scale_factor(); + Some(((f64::from(p.x - o.x) / scale) as f32, (f64::from(p.y - o.y) / scale) as f32)) + } +} + +/// Tells `rt` where `window`'s content is on screen: in points for `El::on_screen_layout` +/// ([`screen_origin`]), and in desktop pixels for `Drag::screen_point`. True when that moved +/// an `El::on_screen_layout` element. +pub(crate) fn sync_screen_origin_core(rt: &mut RuntimeCore, window: &Window) -> bool { + rt.set_window_pixels(window.inner_position().ok().map(|p| (p.x, p.y))); + screen_origin(window).is_some_and(|o| rt.set_window_origin(o)) +} + +/// The scale an overlay draws at. On macOS, read from the panel AppKit shows, and before it's +/// ordered in from the display holding most of its frame, where it will appear. +pub(crate) fn backing_scale(window: &Window) -> f32 { + #[cfg(target_os = "macos")] + if let Some(scale) = crate::platform::macos::backing_scale(window) { return scale; } + window.scale_factor() as f32 +} + +pub(crate) fn pointer_button(button: MouseButton) -> crate::PointerButton { + match button { + MouseButton::Left => crate::PointerButton::Primary, + MouseButton::Right => crate::PointerButton::Secondary, + MouseButton::Middle => crate::PointerButton::Middle, + MouseButton::Back => crate::PointerButton::Back, + MouseButton::Forward => crate::PointerButton::Forward, + MouseButton::Other(n) => crate::PointerButton::Other(n), + } +} + +#[cfg_attr(target_arch = "wasm32", allow(dead_code))] +fn gesture_phase(phase: TouchPhase) -> crate::GesturePhase { + match phase { + TouchPhase::Started => crate::GesturePhase::Began, + TouchPhase::Moved => crate::GesturePhase::Moved, + TouchPhase::Ended | TouchPhase::Cancelled => crate::GesturePhase::Ended, + } +} + +/// Hands a winit touch (a finger, or a pen where the system reports it as one) to the runtime +/// in the view's points, timed on a clock that starts with the first touch. +pub(crate) fn touch_core(rt: &mut RuntimeCore, app: &mut dyn AppDriver, touch: &winit::event::Touch) { + let scale = rt.input_scale(); + static START: std::sync::OnceLock<crate::time::Instant> = std::sync::OnceLock::new(); + let phase = match touch.phase { + TouchPhase::Started => crate::TouchPhase::Started, + TouchPhase::Moved => crate::TouchPhase::Moved, + TouchPhase::Ended => crate::TouchPhase::Ended, + TouchPhase::Cancelled => crate::TouchPhase::Cancelled, + }; + let time = START.get_or_init(crate::time::now).elapsed().as_secs_f64(); + rt.touch(app, touch.id, phase, touch.location.x as f32 / scale, touch.location.y as f32 / scale, time); +} diff --git a/app/vendor/rune/crates/rune/src/window/app_events.rs b/app/vendor/rune/crates/rune/src/window/app_events.rs new file mode 100644 index 0000000..299601f --- /dev/null +++ b/app/vendor/rune/crates/rune/src/window/app_events.rs @@ -0,0 +1,64 @@ +//! What the whole app hears, not one window: a quit (`crate::quit`) and a reopen. + +use super::*; + +impl Windows { + /// The app starts to quit (`crate::quit`): every window still open runs `App::on_quit`, once + /// per quit. A session ending now (`ending`) then closes the windows as their close buttons + /// would, before the loop ends, as a macOS logout does: the OS may end the process next. + /// With `hide`, every window leaves the screen first, so the quit looks done the moment it + /// starts and the hooks run unseen. + pub(super) fn quit(&mut self, event_loop: &ActiveEventLoop, ending: bool, hide: bool) { + use crate::quit::{After, Effect, Event}; + if hide { + for host in self.hosts.iter_mut().flatten() { host.vanish(); } + crate::marks::mark("quit.hidden"); + } + for effect in crate::quit::send(Event::Start { ending, after: After::Exit }) { + match effect { + Effect::RunHooks => { + for host in self.hosts.iter_mut().flatten() { host.quit_hook(); } + crate::marks::mark("quit.hooks"); + crate::quit::send(Event::HooksRan); + } + Effect::CloseAndExit => { + if !event_loop.exiting() { + for host in self.hosts.iter_mut().flatten() { host.terminate(); } + event_loop.exit(); + } + crate::quit::send(Event::WindowsClosed); + } + // Only the loop's end relaunches. + Effect::Relaunch => {} + } + } + } + + /// The app was reopened: every `on_reopen` hook runs, then, unless one handled it or the + /// app is an accessory, the default brings back a window when none shows (`reopen::target`). + pub(super) fn reopen(&mut self, event_loop: &ActiveEventLoop) { + let candidates = |hosts: &[Option<Box<dyn AnyHost>>]| -> Vec<_> { + hosts.iter().map(|h| h.as_ref().map(|h| h.reopen_candidate()).unwrap_or_default()).collect() + }; + let has_visible = crate::platform::reopen::has_visible(&candidates(&self.hosts)); + let mut handled = false; + for host in self.hosts.iter_mut().flatten() { + handled |= host.reopen_hook(event_loop, has_visible); + } + if handled || event_loop.exiting() { return; } + #[cfg(target_os = "macos")] + if crate::platform::reopen::accessory() { return; } + // The default sees what the hooks did, to other windows too. + for host in self.hosts.iter_mut().flatten() { host.apply_pending(event_loop); } + if event_loop.exiting() { return; } + #[cfg(target_os = "macos")] + crate::platform::reopen::unhide(); + if let Some(Some(host)) = crate::platform::reopen::target(&candidates(&self.hosts)).and_then(|i| self.hosts.get_mut(i)) { + host.reopen(event_loop); + } + // Windows: a launch while the app runs brings its front window forward, restored, as + // AppKit's activation does on macOS; the launch let this process take the foreground. + #[cfg(target_os = "windows")] + crate::open_url::instance::raise_front(); + } +} diff --git a/app/vendor/rune/crates/rune/src/window/chrome.rs b/app/vendor/rune/crates/rune/src/window/chrome.rs new file mode 100644 index 0000000..12c9222 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/window/chrome.rs @@ -0,0 +1,163 @@ +//! The window's controls over the app's titlebar: the macOS traffic lights and the Windows +//! custom frame (`App::titlebar`), and what they take of it (`Cx::titlebar_inset`, +//! `Cx::chrome_insets`, the caption buttons drawn over the view). +#![cfg_attr(target_arch = "wasm32", allow(dead_code))] + +#[cfg(not(target_os = "macos"))] +use winit::dpi::LogicalSize; +use winit::window::Window; + +use crate::runtime::RuntimeCore; +use crate::tooling::Chrome; +use crate::window::surface::Win; + +#[cfg(all(unix, not(target_os = "macos"), not(target_os = "ios"), not(target_os = "android")))] +pub(in crate::window) mod float_on_open; +#[cfg(target_os = "macos")] +pub(in crate::window) mod mac; +pub(in crate::window) mod platform_sync; + +pub(in crate::window) use platform_sync::sync_platform_core; + +/// Native titlebar behaviour the framework owns: traffic-light placement, drag regions and the +/// double-click action. Elsewhere only the portable parts apply. +#[cfg_attr(not(any(test, target_os = "macos")), allow(dead_code))] +pub(in crate::window) fn uses_drag_regions(chrome: Chrome, borderless: bool, panel: bool) -> bool { + chrome.drag_regions && (borderless || chrome.full_size_content) && !panel +} + +/// Places the traffic lights and returns `Cx::titlebar_inset`. +pub(in crate::window) fn place_chrome(window: &Window, chrome: Chrome) -> f32 { + #[cfg(target_os = "macos")] + { + if let Some(p) = chrome.traffic_lights { + crate::platform::macos::traffic_lights::place(window, p); + } + mac::titlebar_inset(window) + } + #[cfg(not(target_os = "macos"))] + { + let _ = (window, chrome); + 0.0 + } +} + +/// The frame the window draws for the app's `chrome` and `titlebar` as the view `set` it +/// (`Cx::set_titlebar`, `Cx::titlebar_height`): on macOS a titlebar is a full-size content +/// view with the traffic lights where the titlebar or the app placed them, else in the band's +/// middle. +pub(in crate::window) fn frame_chrome(chrome: Chrome, titlebar: Option<crate::Titlebar>, set: crate::titlebar::TitlebarSet) -> Chrome { + #[cfg(target_os = "macos")] + return titlebar.map(|t| set.over(t)).map_or(chrome, |t| t.mac_chrome(chrome)); + #[cfg(not(target_os = "macos"))] + { let _ = (titlebar, set); chrome } +} + +/// Places the traffic lights, and tells the runtime what the window's controls take of the +/// titlebar and which caption buttons to draw over it. A change re-runs the view. +pub(in crate::window) fn sync_chrome_core(rt: &mut RuntimeCore, w: &Win, chrome: Chrome, titlebar: Option<crate::Titlebar>) { + let leading = place_chrome(&w.window, frame_chrome(chrome, titlebar, rt.titlebar_set())); + rt.set_titlebar_inset(leading); + let height = titlebar.map(|t| rt.titlebar_set().over(t).height()); + let caption = caption(w, height); + let scale = w.window.scale_factor() as f32; + let height = height.filter(|_| custom_frame(w)).unwrap_or(0.0); + let buttons = caption.map_or(0.0, |c| c.width(scale)); + // The traffic lights' room is on the right in a right-to-left app on macOS, as the caption + // buttons' is on the left on Windows. + let (left, right) = if lights_right(w) { (0.0, leading) } else { (leading, 0.0) }; + let (left, right) = if caption.is_some_and(|c| c.mirrored) { (left + buttons, right) } else { (left, right + buttons) }; + rt.set_chrome_insets(crate::ChromeInsets::new(left, right, height)); + rt.set_caption(caption); +} + +/// The traffic lights sit at the window's right: a right-to-left app on macOS. +fn lights_right(w: &Win) -> bool { + #[cfg(target_os = "macos")] + return mac::traffic_lights_right(&w.window); + #[cfg(not(target_os = "macos"))] + { let _ = w; false } +} + +/// Whether Rune replaced the native title bar: macOS draws the app's titlebar under its +/// transparent one; Windows has the custom frame. +fn custom_frame(w: &Win) -> bool { + #[cfg(target_os = "windows")] + return w.native.frame.is_some(); + #[cfg(target_os = "macos")] + { let _ = w; true } + #[cfg(not(any(target_os = "macos", target_os = "windows")))] + { let _ = w; false } +} + +/// The caption buttons a custom frame draws `height` points tall; none in full screen. +fn caption(w: &Win, height: Option<f32>) -> Option<crate::titlebar::Caption> { + #[cfg(target_os = "windows")] + return w.native.frame.as_ref().map(|f| { + if let Some(h) = height { f.set_height(h); } + f.caption(&w.window) + }); + #[cfg(not(target_os = "windows"))] + { let _ = (w, height); None } +} + +/// A double click on a titlebar: AppKit's action on macOS, else maximize or restore, as the +/// maximize button would. +pub(in crate::window) fn titlebar_double_click(window: &Window) { + #[cfg(target_os = "macos")] + mac::titlebar_double_click(window); + #[cfg(not(target_os = "macos"))] + toggle_maximized(window); +} + +/// Maximizes the window, or restores it when it is maximized. A window without a maximize +/// button (one that isn't resizable) only restores. +pub(in crate::window) fn toggle_maximized(window: &Window) { + let maximized = window.is_maximized(); + if maximized || window.enabled_buttons().contains(winit::window::WindowButtons::MAXIMIZE) { + window.set_maximized(!maximized); + } +} + +/// Shows a window that opens maximized or full screen that way (`App::maximized`, +/// `App::full_screen`): maximized first, so leaving full screen returns to it. +#[cfg(target_os = "windows")] +pub(in crate::window) fn open_as(window: &Window, open_as: crate::windows::OpenAs) { + if open_as.maximizes() { window.set_maximized(true); } + if open_as.full_screens() { window.set_fullscreen(Some(winit::window::Fullscreen::Borderless(None))); } +} + +/// Takes the window full screen, borderless over its display, or brings it back. +pub(in crate::window) fn toggle_full_screen(window: &Window) { + let full = window.fullscreen().is_some(); + window.set_fullscreen((!full).then_some(winit::window::Fullscreen::Borderless(None))); +} + +/// The window menu, where a custom titlebar (at `at`, the click's point in window points, else +/// the pointer) or the keyboard opens it. +pub(in crate::window) fn window_menu(window: &Window, menu: crate::runtime::WindowMenu, at: Option<(f32, f32)>) { + #[cfg(target_os = "windows")] + { + let scale = window.scale_factor(); + let at = at.zip(window.inner_position().ok()).map(|((x, y), o)| (o.x + (f64::from(x) * scale).round() as i32, o.y + (f64::from(y) * scale).round() as i32)); + crate::platform::win32::window_menu(window, menu, at); + } + #[cfg(not(target_os = "windows"))] + let _ = (window, menu, at); +} + +/// Whether Alt+Space opens this window's window menu when no handler takes it. +pub(in crate::window) fn has_window_menu(window: &Window) -> bool { + #[cfg(target_os = "windows")] + return crate::platform::win32::has_window_menu(window); + #[cfg(not(target_os = "windows"))] + { let _ = window; false } +} + +/// Sizes the window's content to `size` points. +#[cfg(not(target_os = "macos"))] +pub(in crate::window) fn request_inner_size(window: &Window, size: (f32, f32)) { + #[cfg(target_os = "windows")] + if crate::platform::win32::request_inner_size(window, size) { return; } + let _size = window.request_inner_size(LogicalSize::new(size.0, size.1)); +} diff --git a/app/vendor/rune/crates/rune/src/window/chrome/float_on_open.rs b/app/vendor/rune/crates/rune/src/window/chrome/float_on_open.rs new file mode 100644 index 0000000..e570266 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/window/chrome/float_on_open.rs @@ -0,0 +1,24 @@ +//! `App::float_on_open`: tiling window managers float a toplevel that maps at a fixed size, so +//! the window maps with its minimum equal to its maximum and takes its own limits once its +//! first frame is shown. + +use winit::dpi::{LogicalSize, PhysicalSize, Size}; +use winit::window::{Window, WindowAttributes}; + +use crate::windows::WindowOptions; + +/// `attrs` with the window's size as both its minimum and its maximum. +pub(in crate::window) fn fixed(attrs: WindowAttributes, options: &WindowOptions, size: (f32, f32)) -> WindowAttributes { + let fixed: Size = match options.physical_size { + Some((w, h)) => PhysicalSize::new(w, h).into(), + None => LogicalSize::new(size.0, size.1).into(), + }; + attrs.with_min_inner_size(fixed).with_max_inner_size(fixed) +} + +/// Mapped at a fixed size, so a tiling window manager floated it: now the user can resize it. +pub(in crate::window) fn release(window: &Window, options: &WindowOptions, app_min: Option<(f32, f32)>) { + let (min, max) = options.size_limits(app_min); + window.set_min_inner_size(Some(LogicalSize::new(min.0, min.1))); + window.set_max_inner_size(max.map(|(w, h)| LogicalSize::new(w, h))); +} diff --git a/app/vendor/rune/crates/rune/src/window/chrome/mac.rs b/app/vendor/rune/crates/rune/src/window/chrome/mac.rs new file mode 100644 index 0000000..2c2e91a --- /dev/null +++ b/app/vendor/rune/crates/rune/src/window/chrome/mac.rs @@ -0,0 +1,163 @@ +//! macOS titlebar behaviour: drag regions, the full-screen watch, the titlebar inset and the +//! double-click action. + +#![allow(unsafe_code)] + +use objc2::runtime::{AnyClass, AnyObject, Bool, ClassBuilder, Sel}; +use objc2::{msg_send, sel, ClassType}; +use objc2_app_kit::{NSEvent, NSPanel, NSWindowButton, NSWindowStyleMask}; +use objc2_foundation::{NSString, NSUserDefaults}; +use winit::window::Window; +use crate::platform::macos::{content_view, ns_window}; + +#[cfg(test)] +#[path = "mac_tests.rs"] +mod tests; + +unsafe extern "C" fn cannot_move_window(_: &AnyObject, _: Sel) -> Bool { + Bool::NO +} + +/// The content view stops AppKit from moving the window when the titlebar band is pressed; +/// only `.window_drag()` regions move it. Install an equal-sized subclass on this instance, +/// never a method on winit's shared class. Other windows keep their original class. +pub fn own_window_dragging(window: &Window) { + let Some(view) = content_view(window) else { return }; + let Some(win) = view.window() else { return }; + // SAFETY: `win` is a live `NSWindow` on the main thread; `isKindOfClass:` takes a `Class` and returns `BOOL`. + let panel: Bool = unsafe { msg_send![&*win, isKindOfClass: NSPanel::class()] }; + let full_size = win.styleMask().contains(NSWindowStyleMask::FullSizeContentView); + let borderless = !win.styleMask().contains(NSWindowStyleMask::Titled); + let chrome = crate::Chrome { full_size_content: full_size, drag_regions: true, ..crate::Chrome::DEFAULT }; + if !super::uses_drag_regions(chrome, borderless, panel.as_bool()) { return; } + // SAFETY: `view` is a live winit content view on the main thread, as `scope_drag_regions` requires. + unsafe { scope_drag_regions(&view) }; +} + +/// Main-thread native views only. The subclass adds no ivars, preserving winit's layout, +/// methods and deallocation. Registered classes live for the process lifetime. +unsafe fn scope_drag_regions(view: &AnyObject) { + let base = view.class(); + if base.name().to_bytes().starts_with(b"RuneDragRegions_") { return; } + let Ok(name) = std::ffi::CString::new(format!("RuneDragRegions_{}", base.name().to_string_lossy())) else { return }; + let class = match ClassBuilder::new(&name, base) { + Some(mut builder) => { + // SAFETY: the signature matches -[NSView mouseDownCanMoveWindow]. + unsafe { builder.add_method(sel!(mouseDownCanMoveWindow), cannot_move_window as unsafe extern "C" fn(_, _) -> _) }; + builder.register() + } + None => AnyClass::get(&name).expect("register Rune drag-region view"), + }; + // SAFETY: called on a live view on the main thread. Only its isa changes, to a subclass + // without ivars; the original class is never modified. + unsafe { AnyObject::set_class(view, class) }; +} + +/// Redraws the window once it has entered or left full screen, so the redraw can place the +/// traffic lights and read the new `titlebar_inset`: winit sends no event for either, and +/// resizes during the transition arrive while the style mask still says full screen. +pub struct FullScreenWatch { + observers: Vec<objc2::rc::Retained<objc2_foundation::NSObject>>, + changed: std::rc::Rc<std::cell::Cell<bool>>, +} + +impl FullScreenWatch { + pub fn new(window: &Window) -> Self { + use objc2::rc::{Retained, Weak}; + use objc2_foundation::NSObject; + let changed = std::rc::Rc::new(std::cell::Cell::new(false)); + let none = || Self { observers: Vec::new(), changed: changed.clone() }; + let (Some(win), Some(view)) = (ns_window(window), content_view(window)) else { return none() }; + let Some(center) = AnyClass::get(c"NSNotificationCenter") else { return none() }; + let weak = Weak::from_retained(&view); + let flag = changed.clone(); + let block = block2::RcBlock::new(move |_: *mut AnyObject| { + flag.set(true); + if let Some(view) = weak.load() { view.setNeedsDisplay(true); } + }); + let names = ["NSWindowDidEnterFullScreenNotification", "NSWindowDidExitFullScreenNotification"]; + // SAFETY: main thread; the block outlives the observers, which `Drop` removes. + let observers = names.into_iter().filter_map(|name| unsafe { + let center: Retained<AnyObject> = msg_send![center, defaultCenter]; + let name = NSString::from_str(name); + let token: Option<Retained<NSObject>> = msg_send![&*center, addObserverForName: &*name, object: &*win, + queue: std::ptr::null::<AnyObject>(), usingBlock: &*block]; + token + }).collect(); + Self { observers, changed } + } + + /// Whether full screen started or ended since the last call. + pub fn take(&self) -> bool { + self.changed.replace(false) + } +} + +impl Drop for FullScreenWatch { + fn drop(&mut self) { + let Some(center) = AnyClass::get(c"NSNotificationCenter") else { return }; + for token in &self.observers { + // SAFETY: removes an observer this watch added. + unsafe { + let center: objc2::rc::Retained<AnyObject> = msg_send![center, defaultCenter]; + let _: () = msg_send![&*center, removeObserver: &**token]; + } + } + } +} + +/// Whether the traffic lights sit at the window's right: a right-to-left app's titlebar +/// (`traffic_lights::place`). +pub fn traffic_lights_right(window: &Window) -> bool { + let Some(win) = ns_window(window) else { return false }; + let Some(close) = win.standardWindowButton(NSWindowButton::CloseButton) else { return false }; + let r = close.convertRect_toView(close.bounds(), None); + r.origin.x > win.frame().size.width * 0.5 +} + +/// How far in from their edge the traffic lights reach, in window points: the zoom button's +/// trailing edge from the left, or its leading edge from the right where they sit at the right +/// (`traffic_lights_right`); 0 when the buttons don't sit over the content: full screen, a +/// standard titlebar, or hidden buttons. +pub fn titlebar_inset(window: &Window) -> f32 { + let Some(win) = ns_window(window) else { return 0.0 }; + let mask = win.styleMask(); + if mask.contains(NSWindowStyleMask::FullScreen) || !mask.contains(NSWindowStyleMask::FullSizeContentView) { + return 0.0; + } + let Some(zoom) = win.standardWindowButton(NSWindowButton::ZoomButton) else { return 0.0 }; + if zoom.isHiddenOrHasHiddenAncestor() { return 0.0; } + let r = zoom.convertRect_toView(zoom.bounds(), None); + if traffic_lights_right(window) { + return (win.frame().size.width - r.origin.x) as f32; + } + (r.origin.x + r.size.width) as f32 +} + +/// How far down, in window points, AppKit moves the window itself from presses on the content +/// view: a full-size-content titlebar the app didn't take over with drag regions. 0 in full +/// screen and for standard titled, borderless and drag-region windows. +pub fn native_titlebar_band(window: &Window) -> f32 { + let Some(win) = ns_window(window) else { return 0.0 }; + let mask = win.styleMask(); + if !mask.contains(NSWindowStyleMask::Titled | NSWindowStyleMask::FullSizeContentView) || mask.contains(NSWindowStyleMask::FullScreen) { + return 0.0; + } + if content_view(window).is_some_and(|v| v.class().name().to_bytes().starts_with(b"RuneDragRegions_")) { return 0.0; } + let content = win.contentLayoutRect(); + (win.frame().size.height - content.size.height).max(0.0) as f32 +} + +pub fn double_click_interval() -> f64 { + NSEvent::doubleClickInterval() +} + +/// System Settings › Desktop & Dock › "Double-click a window's title bar to". +pub fn titlebar_double_click(window: &Window) { + let action = NSUserDefaults::standardUserDefaults().stringForKey(&NSString::from_str("AppleActionOnDoubleClick")); + match action.map(|s| s.to_string()).as_deref() { + Some("Minimize") => window.set_minimized(true), + Some("None") => {} + _ => window.set_maximized(!window.is_maximized()), + } +} diff --git a/app/vendor/rune/crates/rune/src/window/chrome/mac_tests.rs b/app/vendor/rune/crates/rune/src/window/chrome/mac_tests.rs new file mode 100644 index 0000000..550a0c6 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/window/chrome/mac_tests.rs @@ -0,0 +1,31 @@ +use super::*; + +#[test] +#[allow(unsafe_code)] +fn drag_subclass_changes_only_the_selected_instance() { + // NSObject exercises the Objective-C class operation without constructing a window + // or requiring an AppKit event loop on the test thread. + use objc2::{ffi, rc::Retained}; + let selected = objc2_foundation::NSObject::new(); + let sibling = objc2_foundation::NSObject::new(); + // SAFETY: `selected` and `sibling` are live `NSObject` instances owned by this test; ObjC runtime + // class queries and `mouseDownCanMoveWindow` match the dynamic subclass installed by `scope_drag_regions`. + unsafe { + let selected_ptr = Retained::as_ptr(&selected).cast_mut().cast(); + let sibling_ptr = Retained::as_ptr(&sibling).cast_mut().cast(); + let base = ffi::object_getClass(selected_ptr); + let selector = sel!(mouseDownCanMoveWindow); + let original = ffi::class_getInstanceMethod(base, selector); + scope_drag_regions(&selected); + let scoped = ffi::object_getClass(selected_ptr); + assert_ne!(scoped, base); + assert_eq!(ffi::class_getSuperclass(scoped), base); + assert_eq!(ffi::class_getInstanceSize(scoped), ffi::class_getInstanceSize(base)); + assert_eq!(ffi::object_getClass(sibling_ptr), base); + assert_eq!(ffi::class_getInstanceMethod(base, selector), original); + let moves: Bool = msg_send![&*selected, mouseDownCanMoveWindow]; + assert!(!moves.as_bool()); + scope_drag_regions(&selected); + assert_eq!(ffi::object_getClass(selected_ptr), scoped); + } +} diff --git a/app/vendor/rune/crates/rune/src/window/chrome/platform_sync.rs b/app/vendor/rune/crates/rune/src/window/chrome/platform_sync.rs new file mode 100644 index 0000000..11141ff --- /dev/null +++ b/app/vendor/rune/crates/rune/src/window/chrome/platform_sync.rs @@ -0,0 +1,34 @@ +use crate::input::host_events; +use crate::runtime::RuntimeCore; +use crate::window::surface::Win; + +/// What a built frame hands the window besides its pixels: secure input, the IME, the cursor, +/// help tags and the clipboard. +pub(in crate::window) fn sync_platform_core(l: &mut Win, rt: &mut RuntimeCore, secure_input: &mut crate::input::secure_input::SecureInput, + ime: &mut bool, clipboard: &crate::clipboard::Client) { + let focused = l.window.has_focus(); + secure_input.set(rt.has_secure_focus() && focused); + l.apply_cursor_core(rt, focused); + #[cfg(target_os = "macos")] + if rt.zoom() == 1.0 { + l.native.help.sync(&l.window, rt.help_regions()); + } else { + // Window points: the view's times its zoom. + let regions: Vec<([f32; 4], String)> = rt.help_regions().iter().map(|(r, t)| (rt.to_window(*r), t.clone())).collect(); + l.native.help.sync(&l.window, &regions); + } + // The process has one menu theme: the active window's, so its window menu matches it. + #[cfg(target_os = "windows")] + if focused { crate::platform::win32::dark_mode::menus(rt.backdrop_dark().unwrap_or(rt.env.system_dark)); } + clipboard.flush_core(rt); + host_events::sync_ime(&l.window, rt, ime, focused); +} + +impl Win { + /// The runtime's cursor while the pointer is in the window, the arrow once it leaves. + /// `Hidden` needs focus, so it can't outlive the window being active. + pub(in crate::window) fn apply_cursor_core(&mut self, rt: &RuntimeCore, focused: bool) { + let want = match rt.cursor() { crate::el::Cursor::Hidden if !focused => crate::el::Cursor::Default, c => c }; + self.cursor.apply(&self.window, want, rt.pointer().is_some()); + } +} diff --git a/app/vendor/rune/crates/rune/src/window/event_loop.rs b/app/vendor/rune/crates/rune/src/window/event_loop.rs new file mode 100644 index 0000000..bd5cec0 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/window/event_loop.rs @@ -0,0 +1,163 @@ +//! Building and running the event loop every native window shares. +#[cfg(not(target_arch = "wasm32"))] +use std::rc::Rc; +#[cfg(not(target_arch = "wasm32"))] +use winit::event_loop::{ControlFlow, EventLoop}; + +use crate::app::App; +use crate::tooling::Args; +use crate::windows::WindowSpec; +#[cfg(not(target_arch = "wasm32"))] +use super::{WakeEvent, Windows}; +use super::Factory; + +pub fn run<S: 'static>(app: App<S>, args: Args) -> Result<(), String> { + let accessory = app.accessory; + run_configured(Box::new(move |_| vec![WindowSpec::from_app("main", app).into()]), args, accessory) +} + +pub(crate) fn run_windows(factory: Factory, args: Args, options: crate::RunOptions) -> Result<(), String> { + run_configured(factory, args, options.accessory) +} + +/// Without a display (no `WAYLAND_DISPLAY` or `DISPLAY`, a refused X11 connection) the event +/// loop can't be built. +fn event_loop_error(error: winit::error::EventLoopError) -> String { + format!("event loop: {error}") +} + +/// Whether this process can reach the window server. Over ssh to a Mac no one is logged in to, +/// AppKit starts but never finishes launching, so the app would wait forever. +#[cfg(target_os = "macos")] +#[allow(unsafe_code)] +fn window_server_session() -> bool { + use std::ffi::c_void; + #[link(name = "CoreGraphics", kind = "framework")] + unsafe extern "C" { fn CGSessionCopyCurrentDictionary() -> *const c_void; } + #[link(name = "CoreFoundation", kind = "framework")] + unsafe extern "C" { fn CFRelease(cf: *const c_void); } + // SAFETY: a Copy-rule CF function; a non-null result is released exactly once. + unsafe { + let session = CGSessionCopyCurrentDictionary(); + if session.is_null() { return false; } + CFRelease(session); + } + true +} + +#[cfg(target_arch = "wasm32")] +fn run_configured(_: Factory, _: Args, _: bool) -> Result<(), String> { + Err("native window factories are unsupported on web; use App::run for one canvas".into()) +} + +#[cfg(not(target_arch = "wasm32"))] +#[allow(unsafe_code)] +fn run_configured(factory: Factory, args: Args, accessory: bool) -> Result<(), String> { + let _ = accessory; + // A relaunch goes on once the app it restarts has exited. + crate::relaunch::wait_for_previous(); + crate::tooling::perf_warn::launch::run_starts(); + crate::platform::ready_signal::run_starts(); + #[cfg(target_os = "macos")] + if !window_server_session() { + crate::render::discard_prewarm(); + return Err("event loop: no window server session (no one is logged in to this Mac)".into()); + } + // While AppKit starts up. + crate::render::prewarm_gpu(); + #[allow(unused_mut)] + let mut builder = EventLoop::<WakeEvent>::with_user_event(); + #[cfg(target_os = "macos")] + // `RUNE_OPEN_INACTIVE` (a tool's launch): the app doesn't take activation at launch either. + if accessory || std::env::var_os("RUNE_OPEN_INACTIVE").is_some() { + use winit::platform::macos::{ActivationPolicy, EventLoopBuilderExtMacOS}; + if accessory { + builder.with_activation_policy(ActivationPolicy::Accessory).with_default_menu(false); + } + builder.with_activate_ignoring_other_apps(false); + } + let event_loop = builder.build().inspect_err(|_| crate::render::discard_prewarm()).map_err(event_loop_error)?; + crate::marks::mark("loop.built"); + // While the app sets up, after winit's first window: the first CPU frame's rounding needs it. + // Beside `EventLoop::new` it waited on the window manager's lock that window takes, and made + // it 1,134 µs slower. + #[cfg(target_os = "windows")] + crate::gpu::pick::find_display_vendor_soon(); + // winit's table for the keyboard layout, which the first key or mouse message would build on + // this thread (8-10 ms, every virtual key through `ToUnicodeEx`): built beside the launch. + #[cfg(target_os = "windows")] + { + // SAFETY: no arguments; this thread runs the loop. + let thread = unsafe { windows_sys::Win32::System::Threading::GetCurrentThreadId() }; + std::thread::Builder::new().name("rune-keyboard-layout".into()).spawn(move || winit::platform::windows::warm_keyboard_layout(thread)).ok(); + } + event_loop.set_control_flow(ControlFlow::Wait); + #[cfg(target_os = "macos")] + crate::platform::app_icon::launched(); + let proxy = event_loop.create_proxy(); + let turn = proxy.clone(); + crate::popup_menu::start(std::sync::Arc::new(move || { + // Coalesce pending turns while a modal loop's timer fires so at most one `WakeEvent::Turn` + // waits in the queue at a time. + if !TURN_QUEUED.swap(true, std::sync::atomic::Ordering::AcqRel) + && turn.send_event(WakeEvent::Turn).is_err() + { + TURN_QUEUED.store(false, std::sync::atomic::Ordering::Release); + } + })); + let mut windows = Windows { factory: Some(factory), args, proxy, hosts: Vec::new(), gpu: Rc::default() }; + crate::open_url::incoming::prepare(); + crate::marks::mark("loop.run"); + let result = event_loop.run_app(&mut windows); + crate::marks::mark("loop.exited"); + // The windows' interaction timing queued its last rollups as they closed. + crate::tooling::interaction::flush(); + crate::render::discard_prewarm(); + crate::clipboard::shutdown(); // Also cover an event-loop error before `exiting`. + crate::platform::ready_signal::clear(); + // An orderly exit: the windows and their renderers go here. `RUNE_LOOP_CHECK=2` found a + // differing picture: the process ends with 3, as a fast exit does (`quit::end_process`). + drop(windows); + if crate::render::loop_pixel_check_failed() { std::process::exit(3); } + result.map_err(|error| format!("run: {error}")) +} + +#[cfg(not(target_arch = "wasm32"))] +static TURN_QUEUED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + +#[cfg(not(target_arch = "wasm32"))] +impl Windows { + /// The idle turn winit runs between its message loops, run while a native menu's modal + /// loop holds winit's (`WakeEvent::Turn`): hosts whose timers are due resume, then + /// `about_to_wait` draws overlays, answers assistive clients and sets the next wake. + pub(super) fn turn(&mut self, event_loop: &winit::event_loop::ActiveEventLoop) { + use std::cell::Cell; + use winit::application::ApplicationHandler; + thread_local! { + static RUNNING: Cell<bool> = const { Cell::new(false) }; + } + struct Reset; + impl Drop for Reset { + fn drop(&mut self) { RUNNING.with(|r| r.set(false)); } + } + TURN_QUEUED.store(false, std::sync::atomic::Ordering::Release); + if RUNNING.with(|r| r.replace(true)) { + return; + } + let _reset = Reset; + let now = crate::time::now(); + for host in self.hosts.iter_mut().flatten() { + if let Some(due) = host.wake_deadline().filter(|&due| due <= now) { + host.new_events(event_loop, winit::event::StartCause::ResumeTimeReached { start: due, requested_resume: due }); + } + } + self.about_to_wait(event_loop); + self.cleanup(event_loop); + } +} + +#[test] +fn an_event_loop_that_cant_start_is_an_error_naming_the_event_loop() { + let error = event_loop_error(winit::error::EventLoopError::RecreationAttempt); + assert!(error.starts_with("event loop: ") && error.contains("recreated"), "{error}"); +} diff --git a/app/vendor/rune/crates/rune/src/window/file_drop.rs b/app/vendor/rune/crates/rune/src/window/file_drop.rs new file mode 100644 index 0000000..21472da --- /dev/null +++ b/app/vendor/rune/crates/rune/src/window/file_drop.rs @@ -0,0 +1,62 @@ +//! A file drag from another app: what the host gathers between passes. + +use std::path::PathBuf; +use std::time::Duration; + +/// A file drag from another app over the window. winit reports one event per file; the host +/// gathers them and hands the runtime one drag and one drop (`Host::flush_files`). +#[derive(Default)] +pub(super) struct FileDrop { + /// What winit reported since the last pass, in order. + pub(super) steps: Vec<FileStep>, + /// Samples the pointer while the drag is over the window, and where it last was. + pub(super) pointer: Option<crate::input::drop_pointer::DropPointer>, + pub(super) at: Option<(f32, f32)>, +} + +/// One step of a file drag over a window. Native drop targets (AppKit, Win32 OLE) supply the +/// pointer's place in window points (`Some(at)`); winit's fallback events (`HoveredFile`, +/// `DroppedFile`) omit it (`None`), so the host samples the pointer. +#[derive(Debug, PartialEq)] +pub(crate) enum FileStep { + Enter(Vec<PathBuf>, Option<(f32, f32)>), + #[cfg_attr(not(any(target_os = "macos", target_os = "windows")), allow(dead_code))] + Move((f32, f32)), + Drop(Vec<PathBuf>, Option<(f32, f32)>), + Leave, +} + +impl FileDrop { + /// One file of a drag that entered (`drop` false) or dropped: the run of files it belongs + /// to grows, or a new run starts. + pub(super) fn file(&mut self, path: PathBuf, drop: bool) { + match self.steps.last_mut() { + Some(FileStep::Enter(files, None)) if !drop => files.push(path), + Some(FileStep::Drop(files, None)) if drop => files.push(path), + _ => self.steps.push(if drop { FileStep::Drop(vec![path], None) } else { FileStep::Enter(vec![path], None) }), + } + } +} + +/// How often a file drag's position is sampled while it's over the window. +pub(super) const DROP_SAMPLE: Duration = Duration::from_millis(16); + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn consecutive_winit_files_coalesce_per_phase() { + let mut drop = FileDrop::default(); + drop.file("a.txt".into(), false); + drop.file("b.txt".into(), false); + drop.file("a.txt".into(), true); + drop.file("b.txt".into(), true); + drop.steps.push(FileStep::Leave); + assert_eq!(drop.steps, [ + FileStep::Enter(vec!["a.txt".into(), "b.txt".into()], None), + FileStep::Drop(vec!["a.txt".into(), "b.txt".into()], None), + FileStep::Leave, + ]); + } +} diff --git a/app/vendor/rune/crates/rune/src/window/handle.rs b/app/vendor/rune/crates/rune/src/window/handle.rs new file mode 100644 index 0000000..3d8bfb2 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/window/handle.rs @@ -0,0 +1,194 @@ +//! `WindowHandle`: a window's native reference that outlives any one host, and the requests +//! made through it before the host exists. + +use super::*; + +pub(super) type Request = Box<dyn FnOnce(usize) -> WakeEvent + Send>; + +#[derive(Default)] +pub(super) struct NativeWindow { + pub(super) window: Mutex<Weak<Window>>, + pub(super) number: AtomicU32, + pub(super) ready: AtomicBool, + /// What the host's meter last published. + pub(super) stats: Arc<Mutex<SurfaceStats>>, + pub(super) route: Mutex<Route>, +} + +/// Where a window's requests go. +pub(super) enum Route { + /// No host yet, or a headless run, which takes them each turn (`take_headless`). + Unbound { queued: Vec<Request> }, + /// The host's event loop and slot. + Bound { proxy: EventLoopProxy<WakeEvent>, slot: usize }, +} + +impl Default for Route { + fn default() -> Self { Route::Unbound { queued: Vec::new() } } +} + +/// A window's native reference, refreshed across App close/reopen without owning the window. +#[derive(Clone)] +pub struct WindowHandle { + pub(super) native: Arc<NativeWindow>, + pub(super) key: Arc<str>, +} +impl WindowHandle { + pub(crate) fn new(key: &str) -> Self { Self { native: Arc::default(), key: key.into() } } + + /// Routes requests to the window's host, starting with those queued before it existed. + pub(super) fn bind(&self, proxy: EventLoopProxy<WakeEvent>, slot: usize) { + let mut route = self.native.route.lock().unwrap(); + if let Route::Unbound { queued } = &mut *route { + for request in std::mem::take(queued) { proxy.send_event(request(slot)).ok(); } + } + *route = Route::Bound { proxy, slot }; + } + + /// A headless run never binds a host; it takes the queued requests instead. + #[cfg_attr(not(any(feature = "tooling", debug_assertions)), allow(dead_code))] + pub(crate) fn take_headless(&self) -> Vec<WakeEvent> { + let queued = match &mut *self.native.route.lock().unwrap() { + Route::Unbound { queued } => std::mem::take(queued), + Route::Bound { .. } => Vec::new(), + }; + queued.into_iter().map(|request| request(0)).collect() + } + + #[cfg_attr(not(any(feature = "tooling", debug_assertions)), allow(dead_code))] + pub(crate) fn headless_pending(&self) -> bool { + matches!(&*self.native.route.lock().unwrap(), Route::Unbound { queued } if !queued.is_empty()) + } + + pub(super) fn send(&self, request: impl FnOnce(usize) -> WakeEvent + Send + 'static) { + match &mut *self.native.route.lock().unwrap() { + Route::Bound { proxy, slot } => { proxy.send_event(request(*slot)).ok(); } + Route::Unbound { queued } => queued.push(Box::new(request)), + } + } + + /// The first frame has completed for the current native lifetime. For a launcher + /// this confirms GPU completion of an alpha-zero frame before reveal. False after destruction. + pub fn is_ready(&self) -> bool { self.window().is_ok() && self.native.ready.load(Ordering::Acquire) } + pub fn key(&self) -> &str { &self.key } + /// The window's frame counts: redraws, presents, failed drawable acquisitions, loop turns + /// and pacing: current totals, and per-second rates updated once a second while it draws. + pub fn surface_stats(&self) -> SurfaceStats { crate::frame::surface_stats::read(&self.native.stats) } + pub(super) fn window(&self) -> Result<Arc<Window>, String> { + self.native.window.lock().unwrap().upgrade().ok_or_else(|| "window is closed".into()) + } + /// macOS CGWindowID for ScreenCaptureKit exclusion; None before registration or after destruction. + pub fn window_number(&self) -> Option<u32> { + let _window = self.window().ok()?; + let number = self.native.number.load(Ordering::Acquire); + (number != 0).then_some(number) + } + /// Where the window is on the desktop and whether it's maximized, minimized or full screen, + /// to save and reopen it there. None while it's closed, and on Wayland, which hides window + /// positions. Call it on the UI thread. + pub fn placement(&self) -> Option<crate::windows::WindowPlacement> { + let window = self.window().ok()?; + let (outer, inner) = (window.outer_position().ok()?, window.inner_position().ok()?); + let size = window.inner_size(); + let (maximized, minimized, full_screen) = (window.is_maximized(), window.is_minimized().unwrap_or(false), window.fullscreen().is_some()); + #[cfg(target_os = "windows")] + let restore = ((maximized || minimized) && !full_screen).then(|| crate::platform::win32::restore_frame(&window)).flatten(); + #[cfg(not(target_os = "windows"))] + let restore = None; + Some(crate::windows::WindowPlacement { + position: (outer.x, outer.y), + content_position: (inner.x, inner.y), + content_size: (size.width, size.height), + scale: window.scale_factor(), + maximized, + minimized, + full_screen, + restore, + display: window.current_monitor().map(|m| ((m.position().x, m.position().y), (m.size().width, m.size().height))), + }) + } + /// Shows `state` on the window's taskbar button: a progress bar and a count badge (see + /// [`crate::Taskbar`]). macOS shows the count on the Dock icon, summed over the app's windows + /// (the Dock has no progress bar of its own). Call it on the UI thread. + pub fn set_taskbar(&self, state: crate::Taskbar) { + #[cfg(target_os = "windows")] + if let Ok(window) = self.window() { crate::platform::win32::taskbar::set(&window, state); } + #[cfg(target_os = "macos")] + if let Ok(window) = self.window() { crate::platform::macos::dock_badge(&window, state.count()); } + #[cfg(not(any(target_os = "windows", target_os = "macos")))] + let _ = state; + } + /// Flashes the window's taskbar button twice and leaves it lit until the window comes to the + /// front, for something that needs the person; `false` stops it once that's handled. A + /// window in front, or Focus Assist holding notifications back, flashes nothing. Windows + /// only for now. Call it on the UI thread. + pub fn flash(&self, on: bool) { + #[cfg(target_os = "windows")] + if let Ok(window) = self.window() { crate::platform::win32::taskbar::flash(&window, on); } + #[cfg(not(target_os = "windows"))] + let _ = on; + } + pub fn set_click_through(&self, click_through: bool) -> Result<(), String> { + self.window()?.set_cursor_hittest(!click_through).map_err(|e| e.to_string()) + } + pub fn set_always_on_top(&self, on: bool) { + self.send(move |slot| WakeEvent::Level(slot, on)); + } + /// Physical desktop pixels; retained across recreation. Unsupported on Wayland. + pub fn set_position(&self, position: (i32, i32)) { + self.send(move |slot| WakeEvent::Position(slot, position)); + } + pub fn place(&self, display: crate::DisplayTarget, placement: crate::OverlayPlacement) { + let place = crate::windows::PlaceRequest::new(display, placement); + self.send(move |slot| WakeEvent::Place(slot, place)); + } + /// [`Tx::resize_window`] from outside a handler, on `tok::motion::DEFAULT`. + pub fn resize(&self, size: (f32, f32)) { + self.frame(crate::window::frame::FrameRequest { size: Some(size), animate: true, ..Default::default() }); + } + /// [`Tx::resize_window_instant`] from outside a handler. + pub fn resize_instant(&self, size: (f32, f32)) { + self.frame(crate::window::frame::FrameRequest { size: Some(size), ..Default::default() }); + } + /// [`Tx::center_window`] from outside a handler. + pub fn center(&self) { + self.frame(crate::window::frame::FrameRequest { center: true, ..Default::default() }); + } + pub(super) fn frame(&self, request: crate::window::frame::FrameRequest) { + self.send(move |slot| WakeEvent::Frame(slot, request)); + } + /// Show/recreate, or hide while keeping state. A launcher takes keys and reveals cached + /// pixels; an ordinary window shows without requesting focus. + pub fn set_visible(&self, visible: bool) { + let request = if visible { WindowRequest::Show } else { WindowRequest::Hide }; + self.send(move |slot| WakeEvent::Window(slot, request)); + } + pub fn show(&self) { self.set_visible(true); } + pub fn hide(&self) { self.set_visible(false); } + /// Focus/activate an already-visible window, restoring it if minimized. Wayland requests attention. + pub fn focus(&self) { self.send(WakeEvent::Focus); } + /// Show, restore and activate, creating the window if needed (see `AppHandle::open`). + /// A default close destroys its host; use App::keep_running to reopen. + /// Windows added with `App::window` always reopen. Requests made before the loop runs + /// apply once the window's host starts. + pub fn open(&self) { self.send(|slot| WakeEvent::Window(slot, WindowRequest::Open(None))); } + pub fn close(&self) { self.send(|slot| WakeEvent::Window(slot, WindowRequest::Close)); } + /// Borrow a raw native handle while alive. Platform thread restrictions still apply; + /// do not retain an extracted pointer beyond the callback. + pub fn with_raw_handle<R>(&self, f: impl for<'a> FnOnce(winit::raw_window_handle::WindowHandle<'a>) -> R) -> Result<R, String> { + let window = self.window()?; + let handle = window.window_handle().map_err(|e| e.to_string())?; + Ok(f(handle)) + } +} + +#[cfg(target_os = "macos")] +pub(super) fn native_window_number(window: &Window) -> Option<u32> { + u32::try_from(crate::platform::macos::ns_window(window)?.windowNumber()).ok().filter(|n| *n != 0) +} +#[cfg(not(target_os = "macos"))] +pub(super) fn native_window_number(_: &Window) -> Option<u32> { None } + +#[cfg(test)] +#[path = "handle_tests.rs"] +mod tests; diff --git a/app/vendor/rune/crates/rune/src/window/handle_tests.rs b/app/vendor/rune/crates/rune/src/window/handle_tests.rs new file mode 100644 index 0000000..8e7b21d --- /dev/null +++ b/app/vendor/rune/crates/rune/src/window/handle_tests.rs @@ -0,0 +1,17 @@ +use super::*; + +/// Before a host binds it, a handle keeps its requests in order; a headless run takes them +/// each turn and the handle goes on keeping later ones. +#[test] +fn an_unbound_handle_queues_its_requests_for_the_host_or_a_headless_run() { + let handle = WindowHandle::new("w"); + assert!(!handle.headless_pending()); + handle.focus(); + handle.set_position((3, 4)); + assert!(handle.headless_pending()); + let taken = handle.take_headless(); + assert!(matches!(taken[..], [WakeEvent::Focus(0), WakeEvent::Position(0, (3, 4))])); + assert!(!handle.headless_pending() && handle.take_headless().is_empty()); + handle.hide(); + assert!(matches!(handle.take_headless()[..], [WakeEvent::Window(0, WindowRequest::Hide)])); +} diff --git a/app/vendor/rune/crates/rune/src/window/host.rs b/app/vendor/rune/crates/rune/src/window/host.rs new file mode 100644 index 0000000..2d230a7 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/window/host.rs @@ -0,0 +1,442 @@ +//! Non-generic native window host, wrapping a type-erased [`WindowApp`]. + +use std::cell::RefCell; +use std::rc::Rc; +use std::sync::{Arc, Weak, atomic::{AtomicBool, Ordering}}; + +use winit::event_loop::EventLoopProxy; +use winit::keyboard::ModifiersState; + +use super::file_drop::FileDrop; +use super::handle::WindowHandle; +use super::state::{Life, Rest}; +use super::surface::Win; +use super::{WakeEvent, sync_screen_origin_core}; +use crate::frame::clock::FrameClock; +use crate::frame::surface_stats::SurfaceMeter; +use crate::render::{Gpu, Renderer}; +use crate::runtime::{Env, Waker}; +use crate::time::Instant; +use crate::tooling::{Args, Chrome, runtime_for}; +use crate::windows::{WindowOptions, WindowSpec}; + +pub(in crate::window) mod any_host; +pub(in crate::window) mod app; +pub(in crate::window) mod create; +pub(in crate::window) mod draw; +pub(in crate::window) mod events; +pub(in crate::window) mod lifecycle; +mod render; +pub(in crate::window) mod shell_requests; +pub(in crate::window) mod stepping; + +#[cfg(test)] +#[path = "host/frame_move_tests.rs"] +mod frame_move_tests; + +pub(in crate::window) use app::{CompositorFrame, WindowApp}; +use app::TypedWindowApp; + +/// The only parts of `AppSpec<S>` the window host reads after construction. +#[derive(Clone, Copy, Debug)] +pub(in crate::window) struct WindowGeometry { + pub title: &'static str, + pub size: (f32, f32), + pub min_size: Option<(f32, f32)>, +} + +pub(in crate::window) struct Host { + /// The app's waker ran and its event isn't handled yet (`WakeEvent::App`): work it brought (a + /// streamed token, a tool's result) may already be readable, so no frame is loop-only until + /// the event's `drain` has polled it. + pub(in crate::window) app_woken: Arc<AtomicBool>, + /// `App::chrome`, as the app set it (`chrome::frame_chrome` lays a titlebar over it). + pub(in crate::window) chrome: Chrome, + /// `App::titlebar`, unless the window is borderless. + pub(in crate::window) titlebar: Option<crate::Titlebar>, + pub(in crate::window) options: WindowOptions, + pub(in crate::window) placement: Option<crate::windows::PlaceRequest>, + #[cfg_attr(not(target_os = "macos"), allow(dead_code))] + pub(in crate::window) macos_window: crate::MacWindowOptions, + pub(in crate::window) native_handle: WindowHandle, + pub(in crate::window) on_created: Option<Box<dyn FnOnce(WindowHandle)>>, + pub(in crate::window) on_window: Option<crate::app::OnWindow>, + pub(in crate::window) on_ready: Option<crate::app::OnWindow>, + pub(in crate::window) frame_reports: crate::frame::encoded::FrameReports, + /// Shown, hidden or closed for good; `win` holds the window while it has one. + pub(in crate::window) life: Life, + /// False for windows `App::window` added: they live as long as the loop, never keep it. + pub(in crate::window) keeps_loop: bool, + pub(in crate::window) geometry: WindowGeometry, + pub(in crate::window) args: Args, + pub(in crate::window) keep_running: bool, + /// What the window still owes after its first frame (`post_frame`). + #[cfg(target_os = "windows")] + pub(in crate::window) chores: super::win32::post_frame::Chores, + /// Its close ends the app (`Windows::window_event`): the last window of a fast-exiting app. + pub(in crate::window) ends_app: bool, + /// Whether a turn is inside `App::turn_scope` now. + pub(in crate::window) turn: any_host::Turn, + /// Its place among the windows receiving links (`App::on_open_url`). + pub(in crate::window) _open_urls: Option<crate::open_url::incoming::Listening>, + pub(in crate::window) release_gpu: bool, + pub(in crate::window) open_at_start: bool, + /// `App::float_on_open`: each window maps at a fixed size, then takes its own limits. + #[cfg_attr(not(all(unix, not(target_os = "macos"), not(target_os = "ios"), not(target_os = "android"))), allow(dead_code))] + pub(in crate::window) float_on_open: bool, + /// `App::open_inactive`: the first open leaves focus where it is. + pub(in crate::window) open_inactive: bool, + /// `App::maximized`, `App::full_screen`. + pub(in crate::window) open_as: crate::windows::OpenAs, + pub(in crate::window) shared: Arc<crate::app::SharedCore>, + pub(in crate::window) shortcuts: crate::shortcuts::Guard, + pub(in crate::window) menus: crate::native_menu::MenuGuard, + pub(in crate::window) popup: crate::popup_menu::Presenter, + pub(in crate::window) file_dialog: crate::file_dialog::Presenter, + pub(in crate::window) app: Box<dyn WindowApp>, + /// Before `win` and `gpu`: fields drop in order, and the trace waits for the window's last + /// present times. + pub(in crate::window) trace: Option<crate::tooling::Trace>, + pub(in crate::window) trace_start: Option<Instant>, + pub(in crate::window) trace_frames: usize, + pub(in crate::window) meter: SurfaceMeter, + pub(in crate::window) win: Option<Win>, + pub(in crate::window) gpu: Option<(Arc<Gpu>, Renderer)>, + pub(in crate::window) gpu_pool: Rc<RefCell<Weak<Gpu>>>, + /// A window has shown before: the next one opens settled. + pub(in crate::window) shown: bool, + pub(in crate::window) started: bool, + pub(in crate::window) clock: FrameClock, + pub(in crate::window) idle: bool, + /// Whether the renderer holds what it gives back at rest (`rest`). + pub(in crate::window) rest: Rest, + pub(in crate::window) mods: ModifiersState, + pub(in crate::window) control_click: bool, + pub(in crate::window) files: FileDrop, + pub(in crate::window) clipboard: crate::clipboard::Client, + pub(in crate::window) secure_input: crate::input::secure_input::SecureInput, + pub(in crate::window) ime_allowed: bool, + #[cfg_attr(target_os = "macos", allow(dead_code))] + pub(in crate::window) wayland: bool, + /// The frame moving or jumping to where a handler asked (`stepping::FrameMove`). + pub(in crate::window) frame_move: Option<stepping::FrameMove>, + /// Present times of every window this host opens while tracing. + #[cfg(target_os = "macos")] + pub(in crate::window) present_log: Option<Arc<crate::frame::present_time::metal::Log>>, + #[cfg(target_os = "macos")] + pub(in crate::window) frame_wake: Waker, +} + +struct HostWaker { + app_woken: Arc<AtomicBool>, + waker: Waker, + live_proxy: EventLoopProxy<WakeEvent>, + #[cfg(target_os = "macos")] + frame_proxy: EventLoopProxy<WakeEvent>, +} + +impl HostWaker { + fn prepare( + key: &str, + handle: Option<WindowHandle>, + overlays: &mut Vec<Box<dyn crate::overlay::PendingOverlay>>, + cx: super::Start<'_>, + standard_menus: bool, + ) -> (Self, WindowHandle, usize, Rc<RefCell<Weak<Gpu>>>, bool) { + crate::video::enable_playback(); + cx.overlays.append(overlays); + let native_handle = handle.unwrap_or_else(|| WindowHandle::new(key)); + let super::Start { proxy, slot, gpu: gpu_pool, wayland, .. } = cx; + // Before the menu guard, so custom items in Edit or Window join these menus. + #[cfg(target_os = "macos")] + crate::native_menu::install_standard_menus(standard_menus); + #[cfg(not(target_os = "macos"))] + let _ = standard_menus; + native_handle.bind(proxy.clone(), slot); + let live_proxy = proxy.clone(); + #[cfg(target_os = "macos")] + let frame_proxy = proxy.clone(); + let app_woken = Arc::new(AtomicBool::new(false)); + let woken = app_woken.clone(); + let waker: Waker = Arc::new(move || { + woken.store(true, Ordering::Release); + proxy.send_event(WakeEvent::App(slot)).ok(); + }); + let prepared = Self { + app_woken, + waker, + live_proxy, + #[cfg(target_os = "macos")] + frame_proxy, + }; + (prepared, native_handle, slot, gpu_pool, wayland) + } +} + +struct HostInit { + prepared: HostWaker, + shared: Arc<crate::app::SharedCore>, + chrome: Chrome, + titlebar: Option<crate::Titlebar>, + options: WindowOptions, + macos_window: crate::MacWindowOptions, + native_handle: WindowHandle, + on_created: Option<Box<dyn FnOnce(WindowHandle)>>, + on_window: Option<crate::app::OnWindow>, + on_ready: Option<crate::app::OnWindow>, + on_frame_encoded: Option<crate::frame::encoded::OnFrameEncoded>, + geometry: WindowGeometry, + args: Args, + keep_running: bool, + release_gpu: bool, + open_at_start: bool, + fit_height: bool, + float_on_open: bool, + open_inactive: bool, + open_as: crate::windows::OpenAs, + shortcuts: crate::shortcuts::Guard, + menus: crate::native_menu::MenuGuard, + slot: usize, + gpu_pool: Rc<RefCell<Weak<Gpu>>>, + wayland: bool, + keeps_loop: bool, + open_urls: Option<crate::open_url::incoming::Listening>, +} + +impl Host { + pub(in crate::window) fn new<S: 'static>( + window_spec: WindowSpec<S>, + handle: Option<WindowHandle>, + args: Args, + cx: super::Start<'_>, + keeps_loop: bool, + open_urls: Option<crate::open_url::incoming::Listening>, + ) -> Self { + let WindowSpec { mut app, options, key, on_created } = window_spec; + let args = app.resolve_args(args); + let (prepared, native_handle, slot, gpu_pool, wayland) = + HostWaker::prepare(&key, handle, &mut app.overlays, cx, app.standard_menus); + let (on_window, on_ready, on_frame_encoded, on_frame_drawn) = ( + app.on_window.take(), + app.on_ready.take(), + app.on_frame_encoded.take(), + app.on_frame_drawn.take(), + ); + let macos_window = std::mem::take(&mut app.macos_window); + let (open, keep_running, release_gpu, fit_height, float_on_open) = ( + app.open, app.keep_running, app.release_gpu, app.fit_content_height, app.float_on_open, + ); + let (open_inactive, open_as, chrome, titlebar) = (app.open_inactive, app.open_as, app.chrome, app.titlebar); + let (on_close, on_rest, on_reopen, on_quit, turn_scope) = (app.on_close, app.on_rest, app.on_reopen, app.on_quit, app.turn_scope); + let comp = app.compositor.take(); + let (playground, attach_playground) = (app.playground.take(), app.attach_playground); + let (spec, state, shared, runtime) = app.into_parts(args.scene.as_deref()); + let size = args.size.unwrap_or(spec.size); + // The window reports the system appearance and scale when it opens. + let env = Env::new(args.theme.as_deref() != Some("light"), 1.0); + let mut rt = runtime_for(&spec, state, size, env, setup_waker(&shared.core)); + if let Some(attach) = attach_playground { attach(&mut rt, playground, &spec, args.playground.clone(), args.variant.clone(), true); } + rt.configure(runtime); + shared.core.connect(prepared.waker.clone()); + let shortcuts = crate::shortcuts::Guard::attach(&shared, prepared.waker.clone(), false, wayland); + let menus = crate::native_menu::MenuGuard::attach(&shared, false); + let shared_core = shared.core.clone(); + let geometry = WindowGeometry { title: spec.title, size: spec.size, min_size: spec.min_size }; + let typed = Box::new(TypedWindowApp { + rt, shared, comp, on_frame_drawn, on_close, on_rest, on_quit, on_reopen, turn_scope, + }); + Self::from_app(typed, HostInit { + prepared, + shared: shared_core, + chrome, + titlebar, + options, + macos_window, + native_handle, + on_created, + on_window, + on_ready, + on_frame_encoded, + geometry, + args, + keep_running, + release_gpu, + open_at_start: open, + fit_height, + float_on_open, + open_inactive, + open_as, + shortcuts, + menus, + slot, + gpu_pool, + wayland, + keeps_loop, + open_urls, + }) + } + + fn from_app(mut app: Box<dyn WindowApp>, init: HostInit) -> Self { + let HostInit { + prepared: HostWaker { + app_woken, + waker, + live_proxy, + #[cfg(target_os = "macos")] + frame_proxy, + }, + shared, + chrome, + titlebar, + options, + macos_window, + native_handle, + on_created, + on_window, + on_ready, + on_frame_encoded, + mut geometry, + mut args, + keep_running, + release_gpu, + open_at_start, + fit_height, + float_on_open, + open_inactive, + open_as, + shortcuts, + menus, + slot, + gpu_pool, + wayland, + keeps_loop, + open_urls, + } = init; + let titlebar = titlebar.filter(|_| !options.borderless); + // `RUNE_OPEN_INACTIVE`: a tool's launch (an accessibility probe, a capture) leaves the user's + // focus and keyboard where they are, as `App::open_inactive` does. + let open_inactive = open_inactive || std::env::var_os("RUNE_OPEN_INACTIVE").is_some(); + let frame_reports = crate::frame::encoded::FrameReports::new(on_frame_encoded, Some(native_handle.key())); + if fit_height { + let size = args.size.unwrap_or(geometry.size); + geometry.min_size = options.fit_min_size(geometry.min_size); + // Opens at the content's height; the first frame corrects any difference its + // real scale makes. + app.rt_mut().host.fit_height = true; + let (min, max) = options.size_limits(geometry.min_size); + let fitted = crate::window::frame::clamp_size((size.0, app.content_height()), min, max); + app.rt_mut().set_viewport(fitted, 1.0); + geometry.size = fitted; + args.size = None; + } + #[cfg(target_os = "macos")] + let present_log = args.trace.as_ref().map(|_| Arc::default()); + let has_comp = app.has_compositor(); + let meter = SurfaceMeter::new(native_handle.key(), native_handle.native.stats.clone()); + { + let rt = app.rt_mut(); + rt.set_system_reduced_motion(crate::platform::preferences::reduced_motion()); + rt.set_system_contrast(crate::platform::preferences::contrast()); + rt.set_system_increased_contrast(crate::platform::preferences::increased_contrast()); + rt.set_full_keyboard_access(crate::platform::preferences::full_keyboard_access()); + crate::platform::accent::watch(); + rt.set_system_accent(crate::system_accent()); + crate::platform::scroll_bars::watch(); + rt.set_system_scroll_bars_state(crate::platform::scroll_bars::current().with_override(args.scroll_bars)); + rt.frame.enable_trace_channels(args.trace.is_some()); + rt.set_live_waker(Arc::new(move || { live_proxy.send_event(WakeEvent::Live(slot)).ok(); })); + rt.set_os_drag(crate::drag_out::SUPPORTED); + rt.transparent = options.transparent; + rt.track_marks = has_comp; + rt.wall_start = Some(crate::time::now()); + rt.host.open_urls_natively = args.script.is_none() && args.trace.is_none() && args.frames.is_none(); + rt.frame.set_record_events(false); + rt.host.surface_stats = Some(meter.shared()); + } + app.set_live_visible(false); + let mut clipboard = crate::clipboard::Client::default(); + clipboard.connect(waker.clone()); + let popup = crate::popup_menu::Presenter::new(waker.clone()); + let file_dialog = crate::file_dialog::Presenter::new(waker); + Host { + app_woken, + chrome, + titlebar, + options, + placement: None, + macos_window, + native_handle, + on_created, + on_window, + on_ready, + frame_reports, + life: Life::Unopened, + keeps_loop, + geometry, + args, + keep_running, + #[cfg(target_os = "windows")] + chores: Default::default(), + ends_app: false, + turn: any_host::Turn::Between, + _open_urls: open_urls, + release_gpu, + open_at_start, + float_on_open, + open_inactive, + open_as, + shared, + shortcuts, + menus, + popup, + file_dialog, + app, + win: None, + gpu: None, + gpu_pool, + shown: false, + started: false, + clock: FrameClock::new(crate::time::now()), + idle: true, + rest: Rest::default(), + mods: ModifiersState::empty(), + control_click: false, + files: FileDrop::default(), + clipboard, + secure_input: Default::default(), + ime_allowed: false, + wayland, + frame_move: None, + trace: None, + trace_start: None, + trace_frames: 0, + meter, + #[cfg(target_os = "macos")] + present_log, + #[cfg(target_os = "macos")] + frame_wake: Arc::new(move || { frame_proxy.send_event(WakeEvent::DisplayTick(slot)).ok(); }), + } + } + + /// Tells the runtime where the window's content is on screen, drawing a frame when that + /// moves an `El::on_screen_layout` element. + pub(in crate::window) fn sync_origin(&mut self) { + let Some(w) = &self.win else { return }; + if sync_screen_origin_core(self.app.rt_mut(), &w.window) { + w.request_redraw(); + } + } + + /// Publishes what `AppHandle::is_visible` reports. + pub(in crate::window) fn publish(&self) { + let visible = self.life.shown() && self.win.is_some(); + self.shared.set_visible(visible); + } +} + +/// `setup`'s waker: `AppHandle::wake`, so a drain that also holds updates that changed nothing +/// still polls and redraws for it. +pub(in crate::window) fn setup_waker(shared: &Arc<crate::app::SharedCore>) -> Waker { + let shared = shared.clone(); + Arc::new(move || shared.wake_app()) +} diff --git a/app/vendor/rune/crates/rune/src/window/host/any_host.rs b/app/vendor/rune/crates/rune/src/window/host/any_host.rs new file mode 100644 index 0000000..48bb2a1 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/window/host/any_host.rs @@ -0,0 +1,341 @@ +//! The event loop's view of a host, whatever its state type. + +use std::sync::atomic::Ordering; +use std::time::Duration; + +use winit::event::{StartCause, WindowEvent}; +use winit::event_loop::ActiveEventLoop; +use winit::window::WindowId; + +use super::Host; +use crate::time::Instant; +use crate::window::file_drop::DROP_SAMPLE; +use crate::window::state::{Cover, RestEvent, Reveal}; +use crate::window::surface::{BackoffEvent, RedrawEffect, RedrawEvent, Win, timer_deadline_core}; +#[cfg(target_os = "windows")] +use crate::window::win32::covered_draw::CoveredDrawEvent; +use crate::window::{AnyHost, WakeEvent}; + +impl AnyHost for Host { + fn owns(&self, id: WindowId) -> bool { + self.win.as_ref().is_some_and(|w| w.window.id() == id) + } + fn finished(&self) -> bool { self.life.finished() } + fn keeps_loop(&self) -> bool { self.keeps_loop } + fn closing_ends_app(&mut self) { self.ends_app = true; } + fn key(&self) -> Option<&str> { Some(self.native_handle.key()) } + fn reopen_candidate(&self) -> crate::platform::reopen::Candidate { + let shown = self.shown_win(); + let minimized = shown.is_some_and(|w| w.window.is_minimized() == Some(true)); + crate::platform::reopen::Candidate { + reopenable: !self.life.finished() && !self.macos_window.nonactivating_panel, + visible: shown.is_some() && !minimized, + minimized, + hidden_at: self.life.hidden_at(), + main: self.keeps_loop, + } + } + + fn wake_deadline(&self) -> Option<Instant> { + // The next display tick consumes due timers too. Leaving an overdue timer + // armed while its redraw waits for that tick would spin the event loop. Without a + // running link, a timer due sooner than a frame waits a frame (`timer_deadline`). + let now = crate::time::now(); + let win = self.win.as_ref(); + // A frame waiting for room in the swap chain comes when there is (`slot`): its timers + // would turn the loop at once until then. + let runtime = timer_deadline_core(self.app.rt()).filter(|_| !win.is_some_and(|w| w.paced() || w.waits_for_slot())); + // A due timer whose frame is still on its way takes the frame's bound instead + // (`TimerFrame`), so the loop sleeps rather than waking at once for a frame that can't + // come. + let shown = self.shown_win(); + let runtime = shown.map_or(runtime, |w| w.timer_frame.wait(runtime, now)); + #[cfg(target_os = "windows")] + let handover = win.and_then(|w| w.handover_deadline(now)); + #[cfg(not(target_os = "windows"))] + let handover = None; + #[cfg(target_os = "windows")] + let covered_draw = win.and_then(|w| w.covered_draw.deadline()); + #[cfg(not(target_os = "windows"))] + let covered_draw = None; + runtime.into_iter() + .chain(handover) + .chain(covered_draw) + .chain(win.and_then(|w| w.first_frame.deadline().map(|(retry, _)| retry))) + .chain(win.and_then(|w| w.first_frame.ready_deadline())) + .chain(win.and_then(Win::cloak_deadline)) + .chain(win.and_then(|w| w.backoff.deadline())) + .chain(win.filter(|_| shown.is_none()).and_then(|w| w.hidden_pace.deadline())) + .chain(look_deadline(win)) + .chain(self.files.pointer.as_ref().filter(|_| shown.is_some()).map(|_| now + DROP_SAMPLE)) + .chain(shown.and_then(|w| w.cursor.reassert_at(now))) + .chain(self.rest.deadline()) + .min() + } + + fn turn_ends(&mut self, event_loop: &ActiveEventLoop, now: Instant) { self.in_turn(|h| h.turn_ends_in_turn(event_loop, now)) } + + // What reaches the app's state runs in its turn scope (`App::turn_scope`). + fn terminate(&mut self) { self.in_turn(Self::terminate_in_turn) } + fn quit_hook(&mut self) { self.in_turn(Self::quit_hook_in_turn) } + fn vanish(&mut self) { + if let Some(w) = self.shown_win() { w.hide(); } + } + fn cancel_menus(&mut self) { self.in_turn(Self::cancel_menus_in_turn) } + fn reopen_hook(&mut self, event_loop: &ActiveEventLoop, has_visible_windows: bool) -> bool { + self.in_turn(|h| h.reopen_hook_in_turn(event_loop, has_visible_windows)) + } + fn apply_pending(&mut self, event_loop: &ActiveEventLoop) { self.in_turn(|h| h.apply_pending_in_turn(event_loop)) } + fn reopen(&mut self, event_loop: &ActiveEventLoop) { self.in_turn(|h| h.reopen_in_turn(event_loop)) } + fn new_events(&mut self, event_loop: &ActiveEventLoop, cause: StartCause) { self.in_turn(|h| h.new_events_in_turn(event_loop, cause)) } + fn about_to_wait(&mut self, event_loop: &ActiveEventLoop) -> bool { self.in_turn(|h| h.about_to_wait_in_turn(event_loop)) } + fn resumed(&mut self, event_loop: &ActiveEventLoop) { self.in_turn(|h| h.resumed_in_turn(event_loop)) } + fn user_event(&mut self, event_loop: &ActiveEventLoop, event: WakeEvent) { self.in_turn(|h| h.user_event_in_turn(event_loop, event)) } + fn window_event(&mut self, event_loop: &ActiveEventLoop, id: WindowId, event: WindowEvent) { + self.in_turn(|h| h.window_event_in_turn(event_loop, id, event)) + } +} + +/// Whether a host's turn is inside its app's turn scope now. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(in crate::window) enum Turn { + Between, + Within, +} + +impl Host { + /// The loop's turn ends: the frame the window wants next is asked for, and on Windows a + /// window whose paint the system keeps putting off behind another's paints now (`Redraw`). + fn turn_ends_in_turn(&mut self, event_loop: &ActiveEventLoop, now: Instant) { + let Some(w) = &self.win else { return }; + let paints = cfg!(target_os = "windows") && self.life.uncovered() && !w.minimized(); + let (next, effect) = w.redraw.get().step(RedrawEvent::TurnEnds { now, paints }); + w.redraw.set(next); + match effect { + RedrawEffect::None => {} + RedrawEffect::Request => w.window.request_redraw(), + RedrawEffect::PaintNow => { + #[cfg(target_os = "windows")] + crate::platform::win32::drop_paint(&w.window); + self.paint(event_loop); + } + } + } + + /// Runs `f` inside the app's turn scope, entered once however deep the turn's calls go. + fn in_turn<R>(&mut self, f: impl FnOnce(&mut Self) -> R) -> R { + if self.turn != Turn::Between || !self.app.enter_turn() { return f(self); } + self.turn = Turn::Within; + let result = f(self); + self.app.leave_turn(); + self.turn = Turn::Between; + result + } + + fn terminate_in_turn(&mut self) { + // Once: a window that already closed ran its hook then. + if !self.closes() { return; } + self.life.finish(); + self.close_hook(); + self.app.popup_cancel(&mut self.popup); + self.app.file_dialog_cancel(&mut self.file_dialog); + } + + fn quit_hook_in_turn(&mut self) { + if self.life.finished() || !self.app.run_on_quit() { return; } + // Before the loop ends or the session does: a lock or clear must reach the worker. + self.clipboard.flush_core(self.app.rt_mut()); + if let Some(w) = self.shown_win() { w.request_redraw(); } + } + + fn cancel_menus_in_turn(&mut self) { + self.app.popup_cancel(&mut self.popup); + self.app.file_dialog_cancel(&mut self.file_dialog); + } + + fn reopen_hook_in_turn(&mut self, event_loop: &ActiveEventLoop, has_visible_windows: bool) -> bool { + if !self.started || self.life.finished() { return false; } + // As an update, so its frame, wakes, window requests and quit go as an update's do. + let Some(handled) = self.app.queue_on_reopen(has_visible_windows) else { return false }; + self.drain(event_loop, false); + self.publish(); + handled.load(Ordering::Relaxed) + } + + fn apply_pending_in_turn(&mut self, event_loop: &ActiveEventLoop) { + if !self.started || self.life.finished() || (!self.shared.asks_window() && !self.app.has_updates()) { return; } + self.drain(event_loop, false); + self.publish(); + } + + fn reopen_in_turn(&mut self, event_loop: &ActiveEventLoop) { + if !self.started || self.life.finished() { return; } + self.open(event_loop, None); + self.shell(event_loop); + // winit's focus does nothing while the window is still deminiaturizing. + #[cfg(target_os = "macos")] + if let Some(w) = self.shown_win() { crate::platform::reopen::front(&w.window); } + self.publish(); + } + + fn new_events_in_turn(&mut self, event_loop: &ActiveEventLoop, cause: StartCause) { + #[cfg(target_os = "macos")] + if let Some(shadow) = self.win.as_ref().and_then(|w| w.native.shadow.as_ref()) { shadow.turn(); } + self.meter.turn(matches!(cause, StartCause::ResumeTimeReached { .. } | StartCause::Poll), crate::frame::surface_stats::slept(cause)); + if matches!(cause, StartCause::ResumeTimeReached { .. }) && let Some(w) = &self.win { w.cursor.reassert(); } + #[cfg(target_os = "windows")] + if let Some(w) = &self.win { w.native.cloak.lift_if_due(&w.window, crate::time::now()); } + #[cfg(target_os = "windows")] + self.watch_handover(crate::time::now()); + #[cfg(target_os = "windows")] + if let Some(w) = &mut self.win && w.covered_draw.due(crate::time::now()) { + w.covered_draw = w.covered_draw.step(CoveredDrawEvent::Due); + w.request_redraw(); + } + if let Some(w) = &mut self.win && let Some((retry, until)) = w.first_frame.deadline() && retry <= crate::time::now() { + if until <= crate::time::now() { + let notified = w.first_frame.notified(); + if w.first_frame.expire() { + self.reveal(event_loop, Reveal::Cached, None); + self.shell(event_loop); + if let Some(w) = &self.win { w.request_redraw(); } + self.publish(); + } else if !notified { + self.shared.set_window_error(Some("launcher first frame was not ready within two seconds".into())); + } + } else { + // Bounded retries while the frame prepares, whatever stops each one (occlusion, + // no drawable). A retry left due would turn the loop at once until it gives up. + w.first_frame.retry_at(crate::time::now() + Duration::from_millis(16)); + w.request_redraw(); + } + } + let launcher = self.launcher(); + if let Some(w) = &mut self.win && w.backoff.deadline().is_some_and(|at| at <= crate::time::now()) { + w.backoff_step(BackoffEvent::Lapsed); + // A missed frame marked it occluded; look at the surface again. + self.life.cover(Cover::Surface, false); + if launcher || self.life.shown() { w.request_redraw(); } + } + self.rest_step(RestEvent::Woke { now: crate::time::now() }); + if let Some(w) = &mut self.win && !self.life.shown() && w.hidden_pace.take_due(crate::time::now()) { + w.request_redraw(); + } + // A covered window with motion on screen looks again whether it's still covered (`look`), + // without a frame: asked for while covered, one would draw (`CoveredDraw`) for no one. + #[cfg(target_os = "windows")] + if self.win.as_ref().is_some_and(|w| look_deadline(Some(w)).is_some_and(|at| at <= crate::time::now())) && self.life.covered() { + self.look(); + } + if matches!(cause, StartCause::ResumeTimeReached { .. } | StartCause::Poll) + && timer_deadline_core(self.app.rt()).is_some_and(|deadline| deadline <= crate::time::now()) + && !self.win.as_ref().is_some_and(Win::waits_for_slot) + { + let hidden = self.shown_win().is_none(); + if hidden && !(launcher && self.hidden_launcher_renders()) { + // Hidden or windowless: poll and due timers run, and the view waits for the + // frame that shows the window. A launcher's cached frame follows, paced. + let changed = self.app.hidden_wake(); + self.clipboard.flush_core(self.app.rt_mut()); + self.shell(event_loop); + if changed && launcher { self.refresh_hidden(); } + // A redraw while the window backs off would draw nothing and leave the timer due. + } else if self.win.as_ref().is_some_and(|w| (launcher || self.life.uncovered()) && !w.minimized() + && !w.backing_off(crate::time::now())) { + let now = crate::time::now(); + // A frame the due timer asked for that the window never drew (a Wayland surface + // covered before its frame callback fires) would come back here for the same + // overdue timer and turn the loop at once. Let the timer run covered, and give + // the next frame it asks for the stall bound afresh. + if self.win.as_ref().is_some_and(|w| w.timer_frame.stalled(now)) { + if let Some(w) = &mut self.win { + w.timer_frame.stalled_again(now); + } + self.app.covered_wake(); + self.clipboard.flush_core(self.app.rt_mut()); + self.shell(event_loop); + } else { + // A resting window polls first and draws only for what that changed. + let rests = self.idle && !self.app.compositor_animating() && self.win.as_ref().is_some_and(Win::rests); + let frame = match rests.then(|| self.app.resting_wake()).flatten() { + Some(stale) => { + self.clipboard.flush_core(self.app.rt_mut()); + self.shell(event_loop); + // A close the poll asked for may have hidden the window. + let frame = (stale || self.app.rt().stale()) && self.shown_win().is_some(); + self.app.rt_mut().resting_wake_frame(frame); + frame + } + None => true, + }; + if frame && let Some(w) = &mut self.win { + w.timer_frame.asked_quiet(now); + w.request_redraw(); + } + } + } else { + self.app.covered_wake(); + self.clipboard.flush_core(self.app.rt_mut()); + self.shell(event_loop); + } + } + } + + fn about_to_wait_in_turn(&mut self, event_loop: &ActiveEventLoop) -> bool { + #[cfg(target_os = "macos")] + self.fn_key(); + self.flush_files(event_loop); + // Another window switched the font families (`Tx::set_font_families`). + if self.app.rt_mut().follow_font_families() && let Some(w) = &mut self.win { + w.loop_frame.touched(); + w.request_redraw(); + } + // Process queued hide/close requests before completing a pending first reveal. + self.first_frame_ready(event_loop); + if !self.win.as_ref().is_some_and(|w| self.life.shown() || w.first_frame.revealing()) { + self.app.rt_mut().refuse_file_dialog("cannot open a file dialog while the window is hidden"); + } + self.hidden_input(event_loop); + self.a11y_turn(); + // After the first frame: its on_ready, hooks, the GPU's start and the accessibility + // adapter, one a turn, none while input waits; the loop turns again while some are owed. + #[cfg(target_os = "windows")] + return self.post_frame_turn(); + // Elsewhere `on_ready` ran with the first frame; a view asked to be prepared since runs now. + #[cfg(not(target_os = "windows"))] + { !crate::marks::counting() && self.app.text_idle_owed() && self.app.text_idle_turn() } + } + + fn resumed_in_turn(&mut self, event_loop: &ActiveEventLoop) { + self.resume(event_loop); + self.publish(); + } + + fn user_event_in_turn(&mut self, event_loop: &ActiveEventLoop, event: WakeEvent) { + #[cfg(feature = "frame-profile")] + let logged = Some(crate::frame::live_log::now()); + self.meter.waited(); + self.handle_user_event(event_loop, event); + self.publish(); + #[cfg(feature = "frame-profile")] + if let Some(start) = logged { crate::frame::live_log::wake(start); } + } + + fn window_event_in_turn(&mut self, event_loop: &ActiveEventLoop, id: WindowId, event: WindowEvent) { + #[cfg(feature = "frame-profile")] + let logged = (!matches!(event, WindowEvent::RedrawRequested)).then(crate::frame::live_log::now); + if !matches!(event, WindowEvent::RedrawRequested) { self.meter.waited(); } + self.handle_window_event(event_loop, id, event); + self.publish(); + #[cfg(feature = "frame-profile")] + if let Some(start) = logged { crate::frame::live_log::input(start); } + } +} + +/// When a covered window looks again whether it's still covered (`look`). +fn look_deadline(win: Option<&Win>) -> Option<Instant> { + #[cfg(target_os = "windows")] + return win.and_then(|w| w.native.look.deadline()); + #[cfg(not(target_os = "windows"))] + { let _ = win; None } +} diff --git a/app/vendor/rune/crates/rune/src/window/host/app.rs b/app/vendor/rune/crates/rune/src/window/host/app.rs new file mode 100644 index 0000000..34e7a0b --- /dev/null +++ b/app/vendor/rune/crates/rune/src/window/host/app.rs @@ -0,0 +1,301 @@ +//! Non-generic boundary between [`super::Host`] and the typed `Runtime<S>`, `Shared<S>`, +//! `Compositor<S>`, native menus and lifecycle hooks. + +use std::sync::{Arc, atomic::{AtomicBool, Ordering}}; + +use winit::window::Window; + +use crate::app::{Shared, TurnScope, WindowRequests}; +use crate::compose::{Compositor, Frame}; +use crate::el::Tx; +use crate::frame::clock::FrameClock; +use crate::frame::encoded::OnFrameDrawn; +use crate::render::Renderer; +use crate::runtime::{AppDriver, Runtime, RuntimeCore}; +use crate::time::Instant; + +/// Non-generic arguments passed to [`WindowApp::render_compositor`], which constructs +/// [`Frame<'_, S>`] in place. +pub(in crate::window) struct CompositorFrame<'a> { + pub device: &'a wgpu::Device, + pub queue: &'a wgpu::Queue, + pub encoder: &'a mut wgpu::CommandEncoder, + pub target: &'a wgpu::TextureView, + pub format: wgpu::TextureFormat, + pub size: (u32, u32), + pub dt: f64, + pub update_ms: f64, + pub ui: &'a mut Renderer, +} + +/// Everything the non-generic window host needs of its typed app state `S`. +pub(in crate::window) trait WindowApp { + fn rt(&self) -> &RuntimeCore; + fn rt_mut(&mut self) -> &mut RuntimeCore; + fn with_driver(&mut self, f: &mut dyn FnMut(&mut RuntimeCore, &mut dyn AppDriver)); + + fn enter_turn(&mut self) -> bool; + fn leave_turn(&mut self); + fn run_on_close(&mut self); + fn run_on_quit(&mut self) -> bool; + fn run_on_rest(&mut self); + fn queue_on_reopen(&mut self, has_visible_windows: bool) -> Option<Arc<AtomicBool>>; + fn drain_startup(&mut self, shortcuts: &crate::shortcuts::Guard, menus: &mut crate::native_menu::MenuGuard); + fn drain_window(&mut self, shortcuts: &crate::shortcuts::Guard, menus: &mut crate::native_menu::MenuGuard) -> (WindowRequests, bool, bool); + fn has_updates(&self) -> bool; + fn has_compositor(&self) -> bool; + fn compositor_features(&self) -> wgpu::Features; + fn compositor_animating(&self) -> bool; + fn compositor_draws_own(&self) -> bool; + fn render_compositor(&mut self, args: CompositorFrame<'_>) -> bool; + fn inspect_frame(&mut self); + fn text_idle_owed(&self) -> bool; + fn text_idle_turn(&mut self) -> bool; +} + +impl dyn WindowApp + '_ { + fn driver<R>(&mut self, f: impl FnOnce(&mut RuntimeCore, &mut dyn AppDriver) -> R) -> R { + let mut f = Some(f); + let mut out = None; + self.with_driver(&mut |core, app| { + out = Some(f.take().unwrap()(core, app)); + }); + out.unwrap() + } + + pub(in crate::window) fn frame(&mut self, dt: f64) -> bool { + self.driver(|rt, app| rt.frame(app, dt)) + } + + pub(in crate::window) fn clock_advance(&mut self, clock: &mut FrameClock, at: Instant, compositing: bool) -> (bool, f64) { + self.driver(|rt, app| clock.advance_core(rt, app, at, compositing)) + } + + pub(in crate::window) fn covered_wake(&mut self) { + self.driver(|rt, app| { rt.covered_wake(app); }); + } + + pub(in crate::window) fn hidden_wake(&mut self) -> bool { + self.driver(|rt, app| rt.hidden_wake(app)) + } + + pub(in crate::window) fn hidden_timer_frame(&mut self) { + self.driver(|rt, app| rt.hidden_timer_frame(app)); + } + + pub(in crate::window) fn build_for_show(&mut self) -> bool { + self.driver(|rt, app| rt.build_for_show(app)) + } + + pub(in crate::window) fn content_height(&mut self) -> f32 { + self.driver(|rt, app| rt.content_height(app)) + } + + pub(in crate::window) fn poll_hidden(&mut self) -> bool { + self.driver(|rt, app| rt.poll_hidden(app)) + } + + pub(in crate::window) fn resting_wake(&mut self) -> Option<bool> { + self.driver(|rt, app| rt.resting_wake(app)) + } + + pub(in crate::window) fn window_focus(&mut self, focused: bool) { + self.driver(|rt, app| rt.window_focus(app, focused)); + } + + pub(in crate::window) fn set_live_visible(&mut self, visible: bool) { + self.driver(|rt, app| rt.set_live_visible(app, visible)); + } + + pub(in crate::window) fn popup_answer(&mut self, popup: &mut crate::popup_menu::Presenter) -> bool { + self.driver(|rt, app| popup.answer_core(rt, app)) + } + + pub(in crate::window) fn popup_open(&mut self, popup: &mut crate::popup_menu::Presenter, window: Option<&Arc<Window>>, paints: bool) -> bool { + self.driver(|rt, app| popup.open_core(rt, app, window, paints)) + } + + pub(in crate::window) fn popup_cancel(&mut self, popup: &mut crate::popup_menu::Presenter) { + self.driver(|rt, app| popup.cancel_core(rt, app)); + } + + pub(in crate::window) fn file_dialog_cancel(&mut self, file_dialog: &mut crate::file_dialog::Presenter) { + self.driver(|rt, app| file_dialog.cancel_core(rt, app)); + } + + pub(in crate::window) fn pointer_move(&mut self, x: f32, y: f32) { + self.driver(|rt, app| rt.pointer_move(app, x, y)); + } + + pub(in crate::window) fn pointer_down(&mut self, x: f32, y: f32) { + self.driver(|rt, app| rt.pointer_down(app, x, y)); + } + + pub(in crate::window) fn pointer_up(&mut self, x: f32, y: f32) { + self.driver(|rt, app| rt.pointer_up(app, x, y)); + } + + pub(in crate::window) fn secondary_up(&mut self, x: f32, y: f32) { + self.driver(|rt, app| rt.secondary_up(app, x, y)); + } + + pub(in crate::window) fn button_down(&mut self, x: f32, y: f32, button: crate::PointerButton) { + self.driver(|rt, app| rt.button_down(app, x, y, button)); + } + + pub(in crate::window) fn button_up(&mut self, x: f32, y: f32, button: crate::PointerButton) { + self.driver(|rt, app| rt.button_up(app, x, y, button)); + } + + pub(in crate::window) fn touch(&mut self, touch: &winit::event::Touch) { + self.driver(|rt, app| crate::window::touch_core(rt, app, touch)); + } + + pub(in crate::window) fn modifiers(&mut self, mods: &mut winit::keyboard::ModifiersState, next: winit::keyboard::ModifiersState) -> bool { + self.driver(|rt, app| crate::input::host_events::modifiers(rt, app, mods, next)) + } + + pub(in crate::window) fn keyboard( + &mut self, + clipboard: &crate::clipboard::Client, + event: &winit::event::KeyEvent, + mods: winit::keyboard::ModifiersState, + unhandled: Option<crate::runtime::Unhandled>, + ) -> bool { + self.driver(|rt, app| crate::input::host_events::keyboard(rt, app, clipboard, event, mods, unhandled)) + } + + #[cfg(target_os = "macos")] + pub(in crate::window) fn physical_with_fallback(&mut self, event: crate::PhysicalInput, key: Option<crate::KeyEvent>) -> bool { + self.driver(|rt, app| rt.physical_with_fallback(app, event, key)) + } +} + +/// The only per-state-type structure owned by a native window host. +pub(super) struct TypedWindowApp<S: 'static> { + pub(super) rt: Runtime<S>, + pub(super) shared: Arc<Shared<S>>, + pub(super) comp: Option<Box<dyn Compositor<S>>>, + pub(super) on_frame_drawn: Option<OnFrameDrawn<S>>, + pub(super) on_close: Option<fn(&mut S, &mut Tx)>, + pub(super) on_rest: Option<fn(&mut S, &mut Tx) -> bool>, + pub(super) on_quit: Option<fn(&mut S, &mut Tx)>, + pub(super) on_reopen: Option<fn(&mut S, bool, &mut Tx) -> bool>, + pub(super) turn_scope: Option<TurnScope<S>>, +} + +impl<S: 'static> WindowApp for TypedWindowApp<S> { + fn rt(&self) -> &RuntimeCore { self.rt.core() } + + fn rt_mut(&mut self) -> &mut RuntimeCore { self.rt.core_mut() } + + fn with_driver(&mut self, f: &mut dyn FnMut(&mut RuntimeCore, &mut dyn AppDriver)) { + let (core, mut driver) = self.rt.split_mut(); + f(core, &mut driver); + } + + fn enter_turn(&mut self) -> bool { + let Some(scope) = self.turn_scope else { return false }; + (scope.enter)(&mut self.rt.state); + true + } + + fn leave_turn(&mut self) { + if let Some(scope) = self.turn_scope { + (scope.leave)(&mut self.rt.state); + } + } + + fn run_on_close(&mut self) { + if let Some(f) = self.on_close { + self.rt.update(f); + } + } + + fn run_on_quit(&mut self) -> bool { + let Some(f) = self.on_quit else { return false }; + self.rt.update(f); + true + } + + fn run_on_rest(&mut self) { + if let Some(f) = self.on_rest { + self.rt.update_if(f); + } + } + + fn queue_on_reopen(&mut self, has_visible_windows: bool) -> Option<Arc<AtomicBool>> { + let f = self.on_reopen?; + let handled = Arc::new(AtomicBool::new(false)); + let answer = handled.clone(); + self.shared.queue_update(Box::new(move |s, tx| { + answer.store(f(s, has_visible_windows, tx), Ordering::Relaxed); + true + })); + Some(handled) + } + + fn drain_startup(&mut self, shortcuts: &crate::shortcuts::Guard, menus: &mut crate::native_menu::MenuGuard) { + super::events::startup_updates(&self.shared, shortcuts, |f| { + self.rt.update_if(f); + menus.drain(); + }); + } + + fn drain_window(&mut self, shortcuts: &crate::shortcuts::Guard, menus: &mut crate::native_menu::MenuGuard) -> (WindowRequests, bool, bool) { + shortcuts.drain(); + menus.drain(); + let (mut had_updates, mut updated) = (false, false); + let _receiving = shortcuts.receiving(); + let requests = self.shared.drain_window(&mut self.rt, |changed| { + had_updates = true; + updated |= changed; + menus.drain(); + }); + (requests, had_updates, updated) + } + + fn has_updates(&self) -> bool { self.shared.has_updates() } + + fn has_compositor(&self) -> bool { self.comp.is_some() } + + fn compositor_features(&self) -> wgpu::Features { + self.comp.as_ref().map_or(wgpu::Features::empty(), |c| c.features()) + } + + fn compositor_animating(&self) -> bool { + self.comp.as_ref().is_some_and(|c| c.animating()) + } + + fn compositor_draws_own(&self) -> bool { + self.comp.as_ref().is_some_and(|c| c.draws_own()) + } + + fn render_compositor(&mut self, args: CompositorFrame<'_>) -> bool { + let Some(c) = self.comp.as_mut() else { return false }; + let mut f = Frame { + device: args.device, + queue: args.queue, + encoder: args.encoder, + target: args.target, + format: args.format, + size: args.size, + dt: args.dt, + update_ms: args.update_ms, + rt: &mut self.rt, + ui: args.ui, + }; + c.render(&mut f); + c.animating() + } + + fn inspect_frame(&mut self) { + if let Some(hook) = self.on_frame_drawn.as_mut() { + hook(&self.rt); + } + } + + fn text_idle_owed(&self) -> bool { self.rt.text_idle_owed() } + + fn text_idle_turn(&mut self) -> bool { self.rt.text_idle_turn() } +} diff --git a/app/vendor/rune/crates/rune/src/window/host/create.rs b/app/vendor/rune/crates/rune/src/window/host/create.rs new file mode 100644 index 0000000..3dc7d67 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/window/host/create.rs @@ -0,0 +1,591 @@ +//! Creating the native window: its attributes, frame, surface and GPU, accessibility adapter +//! and platform pieces, and the first frame it comes on screen with. + +use std::sync::{Arc, Weak, atomic::Ordering}; + +use winit::event_loop::ActiveEventLoop; +use winit::window::Window; + +use super::Host; +use crate::render::{Gpu, Renderer}; +#[cfg(target_os = "windows")] +use crate::window::chrome; +use crate::window::chrome::{frame_chrome, place_chrome, sync_chrome_core}; +#[cfg(all(unix, not(target_os = "macos"), not(target_os = "ios"), not(target_os = "android")))] +use crate::window::chrome::float_on_open; +#[cfg(target_os = "macos")] +use crate::window::chrome::{mac, uses_drag_regions}; +use crate::window::handle::native_window_number; +use crate::window::state::FirstFrame; +#[cfg(target_os = "macos")] +use crate::window::surface::LaunchDrawables; +#[cfg(any(target_os = "macos", target_os = "windows"))] +use crate::window::surface::native; +#[cfg(target_os = "windows")] +use crate::window::surface::win; +use crate::window::surface::{ + Backoff, BackoffEvent, HiddenPace, LoopFrame, Native, Redraw, SurfaceRetries, SurfaceStep, + SURFACE_TRIES, TimerFrame, Win, configure, rebuild_renderer_core, surface_config, +}; +#[cfg(target_os = "windows")] +use crate::window::win32::{covered_draw::CoveredDraw, cpu_frame, handover}; +use crate::window::{WakeEvent, sync_screen_origin_core}; + +impl Host { + #[cfg_attr(not(all(unix, not(target_os = "macos"), not(target_os = "ios"), not(target_os = "android"))), allow(unused_variables))] + pub(in crate::window) fn try_create(&mut self, event_loop: &ActiveEventLoop, token: Option<String>, focus: bool) -> Result<(), String> { + // A released window reopens at the height its content reached while it was gone. + crate::marks::mark("window.create"); + let built = self.shown && self.build_for_show(); + let size = self.args.size.unwrap_or(self.geometry.size); + let launcher = self.launcher(); + let visible = !launcher && (self.started || self.options.visible); + #[allow(unused_mut)] + let mut attrs = self.options.attributes(self.app.rt().host.window_title.current().unwrap_or(self.geometry.title), size, self.geometry.min_size, visible).with_active(focus); + #[cfg(target_os = "macos")] + if self.macos_window.nonactivating_panel { attrs = attrs.with_visible(false).with_active(false); } + #[cfg(all(unix, not(target_os = "macos"), not(target_os = "ios"), not(target_os = "android")))] + { + if let Some(id) = crate::tooling::app_id() { + attrs = winit::platform::wayland::WindowAttributesExtWayland::with_name(attrs, id, id); + attrs = winit::platform::x11::WindowAttributesExtX11::with_name(attrs, id, id); + } + if self.float_on_open { attrs = float_on_open::fixed(attrs, &self.options, size); } + if let Some(token) = token { + let token = winit::window::ActivationToken::from_raw(token); + attrs = winit::platform::startup_notify::WindowAttributesExtStartupNotify::with_activation_token(attrs, token); + } + } + let open_as = if !self.shown && self.options.resizable { self.open_as } else { crate::windows::OpenAs::Normal }; + // Windows maximizes it once cloaked: maximizing shows a window. + #[cfg(not(target_os = "windows"))] + { + attrs = attrs.with_maximized(open_as.maximizes()); + if open_as.full_screens() { attrs = attrs.with_fullscreen(Some(winit::window::Fullscreen::Borderless(None))); } + } + let chrome = frame_chrome(self.chrome, self.titlebar, self.app.rt().titlebar_set()); + #[cfg(target_os = "macos")] + if !self.options.borderless && chrome.full_size_content { + use winit::platform::macos::WindowAttributesExtMacOS; + attrs = attrs.with_titlebar_transparent(true).with_title_hidden(true).with_fullsize_content_view(true); + } + // Windows opens it hidden, then shows it cloaked until its first frame lands + // (`Cloak`), so it never comes on screen empty. The show doesn't activate it: the cloak + // does as it lifts, so the text services' start-up follows the frame. + #[cfg(target_os = "windows")] + let attrs = crate::platform::app_icon::with_icon(winit::platform::windows::WindowAttributesExtWindows::with_drag_and_drop(attrs.with_visible(false).with_active(false), false)); + let window = Arc::new(event_loop.create_window(attrs).map_err(|e| e.to_string())?); + crate::marks::mark("window.native"); + #[cfg(target_os = "windows")] + crate::platform::win32::follow_suggested_rect(&window); + #[cfg(target_os = "windows")] + crate::platform::win32::press_point::install(&window); + // Before it shows, so the title bar never appears. + #[cfg(target_os = "windows")] + let frame = self.titlebar.and_then(|t| crate::platform::win32::CustomFrame::install(&window, t.height())); + crate::marks::mark("window.frame_installed"); + #[cfg(target_os = "windows")] + let cloak = crate::platform::win32::Cloak::default(); + // Its first frame on the CPU renderer, painted before it shows (`cpu_frame`). + #[cfg(target_os = "windows")] + let cpu_first = visible && !launcher && cpu_frame::opens_on_cpu(self); + #[cfg(target_os = "windows")] + if visible && !cpu_first { + // Unfocused (`App::open_inactive`), it never activates. + cloak.hold(&window, crate::time::now() + win::READY_FALLBACK, focus); + window.set_visible(true); + chrome::open_as(&window, open_as); + } + crate::marks::mark("window.framed"); + // First, before anything observes the view (macOS) or an assistive client asks. On Windows, + // with no screen reader running, UI Automation's adapter (about 7,500 µs) waits for the + // loop's first idle turn after the first frame: it subclasses the window, which works at + // any time (`a11y_after_frame`). + #[cfg(target_os = "windows")] + let a11y_start = if crate::platform::win32::screen_reader() { native::A11yStart::Made } else { native::A11yStart::AfterFirstFrame }; + #[cfg(target_os = "windows")] + let a11y = if a11y_start == native::A11yStart::Made { self.a11y_adapter(&window) } else { None }; + #[cfg(not(target_os = "windows"))] + let a11y = self.a11y_adapter(&window); + #[cfg(target_os = "macos")] + crate::native_menu::adopt_standard_view(); + #[cfg(target_os = "macos")] + let panel = if self.macos_window.nonactivating_panel { + Some(crate::platform::macos::Panel::adopt_window(&window, size, &self.macos_window).ok_or("could not create nonactivating panel")?) + } else { None }; + #[cfg(target_os = "macos")] + crate::platform::macos::configure_window(&window, &self.macos_window); + #[cfg(target_os = "macos")] + crate::platform::macos::drop::install(&window); + if self.options.click_through && let Err(error) = window.set_cursor_hittest(false) { + eprintln!("click-through unavailable for {}: {error}", self.native_handle.key()); + } + window.set_ime_allowed(false); + self.app.rt_mut().edit.ime_reset = true; + #[cfg(target_os = "macos")] + if uses_drag_regions(chrome, self.options.borderless, false) { + mac::own_window_dragging(&window); + } + self.app.rt_mut().set_titlebar_inset(place_chrome(&window, chrome)); + #[cfg(target_os = "macos")] + { + let rt = self.app.rt_mut(); + rt.double_click_interval = mac::double_click_interval(); + rt.set_native_help(true); + } + #[cfg(windows)] + #[allow(unsafe_code)] + { + // SAFETY: `GetDoubleClickTime` takes no arguments and reads the system setting. + let ms = unsafe { windows_sys::Win32::UI::Input::KeyboardAndMouse::GetDoubleClickTime() }; + let rt = self.app.rt_mut(); + rt.double_click_interval = f64::from(ms) / 1000.0; + // A tooltip control's initial delay is the double-click time. + rt.help_delay = rt.double_click_interval; + } + #[cfg(target_os = "windows")] + if cpu_first { return self.open_on_cpu(event_loop, window, a11y, a11y_start, frame, cloak, focus, open_as, built); } + let mut prewarmed = None; + crate::marks::mark("gpu.begin"); + // A device that died while this window was closed draws nothing: make another. + let (gpu, surface) = match self.gpu.take().filter(|(gpu, _)| !gpu.is_lost()) { + Some((gpu, renderer)) => { + let surface = gpu.instance.create_surface(window.clone()); + self.gpu = Some((gpu, renderer)); + (None, surface.map_err(|e| e.to_string())?) + } + None => { + let features = self.app.compositor_features(); + let transparent = self.options.transparent; + // A shared device that can't composite this window's translucent pixels gets its own. + let cached = self.gpu_pool.borrow().upgrade().filter(|gpu| !gpu.is_lost()).and_then(|gpu| { + let surface = gpu.instance.create_surface(window.clone()).ok()?; + crate::render::translucency::serves(&gpu, &surface, features, transparent).then_some((gpu, surface)) + }); + let (gpu, surface) = if let Some(cached) = cached { + cached + } else { + let (gpu, surface, renderer) = Gpu::for_surface(features, transparent, |instance| instance.create_surface(window.clone()).map_err(|e| e.to_string()))?; + prewarmed = renderer; + let gpu = Arc::new(gpu); + *self.gpu_pool.borrow_mut() = Arc::downgrade(&gpu); + crate::render::surface_gpu(&gpu); + (gpu, surface) + }; + (Some(gpu), surface) + } + }; + let adapter = &gpu.as_ref().or(self.gpu.as_ref().map(|g| &g.0)).unwrap().adapter; + let phys = window.inner_size(); + let srgb_blend = self.app.rt().srgb_blend(); + let (mut config, translucent) = surface_config(&surface, adapter, (phys.width, phys.height), srgb_blend) + .ok_or("the GPU adapter can't present to this window")?; + #[cfg(target_os = "macos")] + let launch_drawables = LaunchDrawables::cap(&mut config); + // A window with a client-side frame keeps its pixels' alpha for the frame's corner arcs; + // one under a compositor that draws the decorations itself keeps the surface it always had. + let client_frame = self.client_frame(&window); + if self.options.transparent || client_frame { + config.alpha_mode = alpha_mode(self.options.transparent, client_frame, translucent); + } + if self.options.transparent { + if config.alpha_mode == wgpu::CompositeAlphaMode::Opaque { + eprintln!("transparency unavailable for {}; using an opaque window", self.native_handle.key()); + } + self.app.rt_mut().transparent = config.alpha_mode != wgpu::CompositeAlphaMode::Opaque; + } + let target_format = if srgb_blend { config.format.remove_srgb_suffix() } else { config.format }; + if let Some(gpu) = gpu { + crate::marks::mark("renderer.begin"); + let mut renderer = prewarmed.unwrap_or_else(|| Renderer::new(&gpu.device, target_format)); + crate::marks::note("uber", renderer.uber_shader()); + crate::marks::mark("renderer.ready"); + renderer.set_srgb_blend(srgb_blend); + self.gpu = Some((gpu, renderer)); + } + let (gpu, renderer) = self.gpu.as_mut().unwrap(); + rebuild_renderer_core(&gpu.device, renderer, target_format, self.app.rt_mut()); + // A refused configuration (the driver's, or a device that is gone) leaves a surface + // wgpu panics on its next drawable: the window closes, and the next open makes both. + let refused = configure(&surface, gpu, &config).err().map(|error| (gpu.is_lost(), error)); + if let Some((lost, error)) = refused { + if lost { + self.gpu = None; + *self.gpu_pool.borrow_mut() = Weak::default(); + } + return Err(format!("the window's GPU surface refused its configuration: {error}")); + } + crate::marks::mark("gpu.surface"); + #[cfg(target_os = "macos")] + crate::platform::macos::pin_contents_top_left(&surface); + #[cfg(target_os = "macos")] + crate::platform::macos::window_shape::apply_corners(&window, &self.macos_window, self.options.transparent, self.options.borderless); + // Metal's PostMultiplied mode only makes CAMetalLayer non-opaque; Core Animation + // still composites premultiplied pixels. Other backends follow wgpu's straight-alpha contract. + let alpha = alpha_pass(gpu, self.options.transparent, &config, target_format); + let scale = window.scale_factor() as f32; + { + let rt = self.app.rt_mut(); + rt.set_system_dark(crate::platform::preferences::window_dark(&window, self.args.theme.as_deref())); + rt.set_viewport((phys.width as f32 / scale, phys.height as f32 / scale), scale); + if (self.shown || launcher) && !built { + // Reopening paints the settled state in the first frame (guarantee 8). + rt.settle_all(); + } + } + self.shown = true; + if visible { self.life.show(); } + self.idle = true; + self.app.set_live_visible(visible); + *self.native_handle.native.window.lock().unwrap() = Arc::downgrade(&window); + self.native_handle.native.number.store(native_window_number(&window).unwrap_or(0), Ordering::Release); + #[cfg(target_os = "macos")] + let resamples = crate::platform::macos::window_shape::resamples(&window, self.options.transparent); + #[cfg(target_os = "macos")] + let hook_log = self.present_log.clone() + .or_else(|| resamples.then(|| Arc::new(crate::frame::present_time::metal::Log::untraced()))); + #[cfg(target_os = "macos")] + let present = hook_log.clone().and_then(|log| crate::frame::present_time::metal::LayerHook::attach(&surface, log)); + #[cfg(target_os = "macos")] + let shadow = hook_log.clone().filter(|_| resamples && present.is_some()) + .and_then(|log| crate::platform::macos::window_shape::Shadow::new(&window, log, visible || launcher)); + #[cfg(target_os = "macos")] + if self.present_log.is_some() && present.is_none() { eprintln!("rune: trace: this surface reports no present times"); } + #[cfg(target_os = "macos")] + let fn_key = if self.app.rt().modifier_keys() { crate::input::fn_key::FnKey::new(&window) } else { None }; + #[cfg(target_os = "macos")] + let full_screen = mac::FullScreenWatch::new(&window); + #[cfg(target_os = "macos")] + let prime = if visible && panel.is_none() { native::Prime::launching() } else { native::Prime::Steady }; + #[cfg(target_os = "macos")] + let native = Native { + pacing: crate::platform::display_link::DisplayLink::new(&window, self.frame_wake.clone()), + present, + present_log: hook_log, + shadow, + panel, + materials: crate::system_material::macos::Materials::new(), + help: Default::default(), + full_screen, + fn_key, + prime, + launch_drawables, + _spot: crate::platform::macos::traffic_lights::Spot::new(&window), + }; + // Making the GPU and surface took part of the cloak's wait; the frame gets all of it. + #[cfg(target_os = "windows")] + cloak.extend(crate::time::now() + win::READY_FALLBACK); + #[cfg(target_os = "windows")] + let native = { + Native { cloak, frame, a11y_start, ..Default::default() } + }; + #[cfg(not(any(target_os = "macos", target_os = "windows")))] + let native = Native::default(); + self.win = Some(Win { + a11y, + native, + first_frame: FirstFrame::opened(crate::time::now()), + surface: Some(surface), + config, + surface_ok: true, + surface_retries: SurfaceRetries::default(), + window, + backoff: Backoff::default(), + hidden_pace: HiddenPace::default(), + cursor: crate::cursor::os::OsCursor::new(), + alpha, + corners: None, + timer_frame: TimerFrame::default(), + loop_frame: LoopFrame::default(), + presented: None, + #[cfg(target_os = "windows")] + covered_draw: CoveredDraw::Current, + redraw: std::cell::Cell::new(Redraw::Idle), + }); + if launcher { self.win.as_mut().unwrap().first_frame.prepare(crate::time::now()); } + self.apply_placement(event_loop); + #[cfg(target_os = "macos")] + if visible && let Some(w) = &self.win && w.native.panel.is_some() { w.show(focus); } + crate::marks::mark("window.created"); + if let Some(created) = self.on_created.take() { created(self.native_handle.clone()); } + if let Some(on_window) = self.on_window.as_mut() { on_window(&self.native_handle); } + if let (Some(w), Some((gpu, ..))) = (self.win.as_mut(), self.gpu.as_ref()) { + #[cfg(target_os = "macos")] + if let Some(pacing) = &mut w.native.pacing { pacing.update_display(&w.window); } + let size = w.window.inner_size(); + let scale = w.window.scale_factor() as f32; + if size.width > 0 && size.height > 0 { + w.resize_surface(Some(&**gpu), size); + self.app.rt_mut().set_viewport((size.width as f32 / scale, size.height as f32 / scale), scale); + } + sync_chrome_core(self.app.rt_mut(), w, self.chrome, self.titlebar); + sync_screen_origin_core(self.app.rt_mut(), &w.window); + if w.window.has_focus() { + self.app.window_focus(true); + } + } + // The first frame, now, so the window comes on screen with it instead of empty for a + // frame or two. AppKit has ordered the window in, but it reaches the screen with this + // turn's Core Animation commit, so nothing reports it visible yet. + #[cfg_attr(not(target_os = "macos"), allow(unused_mut))] + let mut drew = false; + #[cfg(target_os = "macos")] + if visible && !self.app.rt().host.minimize.field() && !self.life.finished() && !event_loop.exiting() + && self.win.as_ref().is_some_and(|w| w.native.panel.is_none() && w.window.is_minimized() != Some(true)) + { + let presents = self.meter.totals().presents; + self.redraw(); + drew = self.meter.totals().presents > presents; + self.shell(event_loop); + } + if !drew && (visible || launcher) && let Some(w) = &self.win { + w.request_redraw(); + } + Ok(()) + } + + /// UI Automation's (or the platform's) accessibility adapter for the window. + pub(in crate::window) fn a11y_adapter(&self, window: &Window) -> Option<crate::a11y::Adapter> { + let handle = self.native_handle.clone(); + crate::a11y::Adapter::new(window, Arc::new(move || handle.send(WakeEvent::A11y))) + } + + /// Whether the window opened without its accessibility adapter and its first frame is up. + #[cfg(target_os = "windows")] + pub(in crate::window) fn a11y_owed(&self) -> bool { + self.win.as_ref().is_some_and(|w| w.native.a11y_start == native::A11yStart::AfterFirstFrame && w.first_frame.ready()) + } + + /// Windows: the accessibility adapter a window opened without, in a turn after its first + /// frame (`post_frame`); assistive clients hear the window's content change so they ask again. + #[cfg(target_os = "windows")] + pub(in crate::window) fn a11y_after_frame(&mut self) { + if !self.a11y_owed() { return; } + let Some(w) = self.win.as_ref() else { return }; + let adapter = self.a11y_adapter(&w.window); + crate::marks::mark("window.a11y"); + let Some(w) = self.win.as_mut() else { return }; + w.native.a11y_start = native::A11yStart::Made; + w.a11y = adapter; + if let Some(a) = &w.a11y { a.notify_structure(); } + } + + /// Replaces the window's surface and the device it draws with, keeping the window, its size + /// and its place. A lost GPU configures nothing, and under it wgpu drops the error + /// `Surface::configure` returns without recording the surface's error sink: the surface has + /// no presentation, and its next `get_current_texture` panics ("Surface is not configured + /// for presentation"). The same goes for a surface whose configuration a driver refused. + /// The next frame draws with what this makes; `replace_lost_surface` gives the window up if + /// this keeps failing. + #[allow(unsafe_code)] + pub(in crate::window) fn reattach(&mut self) -> Result<(), String> { + let Some(w) = self.win.as_mut() else { return Err("there is no window to draw into".into()) }; + let window = w.window.clone(); + // The old surface goes before the device that made it and before the new surface is + // made: a DX12 surface takes the window's one DirectComposition target + // (`Dx12SwapchainKind::DxgiFromVisual`), so the replacement can only be configured once + // the old swapchain has let go of it. + w.alpha = None; + // A pass made on the device that went with it draws nothing: it goes too. + w.corners = None; + w.presented = None; + // Unregister any swap-chain wait before dropping the surface, even if replacement fails. + #[cfg(target_os = "windows")] + { w.native.slot.reset(); w.native.damage.reset(); } + drop(w.surface.take()); + self.gpu = None; + { + let rt = self.app.rt_mut(); + rt.text.atlas.invalidate(); + rt.images.invalidate(); + } + let features = self.app.compositor_features(); + let transparent = self.options.transparent; + // A window the CPU handed to the GPU keeps its DirectComposition target: the new swap + // chain goes on the same visual, committed once it has presented (`SurfaceMode::rebind`). + // wgpu has the composition-visual target only on Windows. + #[cfg(target_os = "windows")] + let visual = w.native.mode.visual(); + let (gpu, surface, prewarmed) = Gpu::for_surface(features, transparent, |instance| { + #[cfg(target_os = "windows")] + if let Some(visual) = visual { + // SAFETY: the window keeps the visual's `Handover` as long as it keeps this surface. + return unsafe { instance.create_surface_unsafe(wgpu::SurfaceTargetUnsafe::CompositionVisual(visual)) }.map_err(|e| e.to_string()); + } + instance.create_surface(window.clone()).map_err(|e| e.to_string()) + })?; + let gpu = Arc::new(gpu); + let size = window.inner_size(); + let srgb_blend = self.app.rt().srgb_blend(); + let (mut config, translucent) = surface_config(&surface, &gpu.adapter, (size.width, size.height), srgb_blend) + .ok_or("the GPU adapter can't present to this window")?; + let client_frame = self.client_frame(&window); + if transparent || client_frame { + config.alpha_mode = alpha_mode(transparent, client_frame, translucent); + } + // A surface that fell back to opaque draws an opaque window, as the first one did. + self.app.rt_mut().transparent = transparent && config.alpha_mode != wgpu::CompositeAlphaMode::Opaque; + if let Err(error) = configure(&surface, &gpu, &config) { + return Err(format!("the new GPU surface refused its configuration: {error}")); + } + let target_format = if srgb_blend { config.format.remove_srgb_suffix() } else { config.format }; + let mut renderer = prewarmed.unwrap_or_else(|| Renderer::new(&gpu.device, target_format)); + renderer.set_srgb_blend(srgb_blend); + rebuild_renderer_core(&gpu.device, &mut renderer, target_format, self.app.rt_mut()); + let alpha = alpha_pass(&gpu, transparent, &config, target_format); + #[cfg(target_os = "macos")] + crate::platform::macos::pin_contents_top_left(&surface); + // The new surface reports presents where the old one did, to the log the window kept + // (`try_create`): the shadow built on that log keeps re-sampling. + #[cfg(target_os = "macos")] + let present = self.win.as_ref() + .and_then(|w| w.native.present_log.clone()) + .and_then(|log| crate::frame::present_time::metal::LayerHook::attach(&surface, log)); + let Some(w) = self.win.as_mut() else { return Err("the window closed while it made a new surface".into()) }; + w.surface = Some(surface); + w.config = config; + w.surface_ok = true; + w.alpha = alpha; + #[cfg(target_os = "windows")] + { w.native.slot.reset(); w.native.damage.reset(); } + #[cfg(target_os = "windows")] + w.native.mode.rebind(); + #[cfg(target_os = "macos")] + { + w.native.present = present; + w.native.prime.stop(); + } + *self.gpu_pool.borrow_mut() = Arc::downgrade(&gpu); + crate::render::surface_gpu(&gpu); + self.gpu = Some((gpu, renderer)); + Ok(()) + } + + /// Makes a handed-over window's swap chain again with premultiplied alpha (a playing clip's + /// own layer shows under the UI, `video_layer`) or opaque (none does): a new surface on the + /// same visual, committed once its first frame has presented (`SurfaceMode::rebind`), as for + /// a lost device. Premultiplied costs DWM a blend of every region the UI presents, so it lasts + /// only while a layer shows. Ok(false) when there's nothing to do. + #[cfg(target_os = "windows")] + #[allow(unsafe_code)] + pub(in crate::window) fn rebind_alpha(&mut self, premultiplied: bool) -> Result<bool, String> { + let Some((gpu, _)) = self.gpu.as_ref() else { return Ok(false) }; + let Some(w) = self.win.as_mut() else { return Ok(false) }; + let Some(visual) = w.native.mode.visual() else { return Ok(false) }; + if self.options.transparent || matches!(w.native.mode, handover::SurfaceMode::Rebinding { .. }) { + return Ok(false); + } + let alpha = if premultiplied { wgpu::CompositeAlphaMode::PreMultiplied } else { wgpu::CompositeAlphaMode::Opaque }; + if w.config.alpha_mode == alpha { + return Ok(false); + } + if premultiplied && w.surface.as_ref().is_none_or(|s| crate::render::translucency::mode(s, &gpu.adapter) != Some(alpha)) { + return Err("this adapter can't composite a premultiplied swap chain".into()); + } + // The old surface goes first: a DX12 surface takes the visual's content, and the + // committed tree keeps showing its last frame until the new one commits. + w.native.slot.reset(); + w.native.damage.reset(); + drop(w.surface.take()); + // SAFETY: the window keeps the visual's `Handover` as long as it keeps this surface. + let surface = unsafe { gpu.instance.create_surface_unsafe(wgpu::SurfaceTargetUnsafe::CompositionVisual(visual)) }.map_err(|e| e.to_string())?; + let mut config = w.config.clone(); + config.alpha_mode = alpha; + configure(&surface, gpu, &config)?; + w.surface = Some(surface); + w.config = config; + w.surface_ok = true; + w.presented = None; + w.native.slot.reset(); + w.native.damage.reset(); + w.native.mode.rebind(); + Ok(true) + } + + /// Replaces the window's surface and device when either can't draw a frame: a device that is + /// gone, or a surface whose last configuration failed (`Win::surface_ok`). Every replacement + /// counts against `SURFACE_TRIES` (`SurfaceRetries`), whether it worked or not: only a frame + /// that presents starts the count over (`Host::draw`), so a surface replaced and lost again + /// before it presents still ends in the window being given up. A failed replacement waits a + /// backoff before the next try. + /// + /// Giving the window up leaves it hidden (`Life::Hidden`, as `hide` does), gives back its + /// device and surface, and records why (`AppHandle::window_error`); opening it again makes a + /// window, a device and a surface. False when there is nothing to draw with this frame. + pub(in crate::window) fn replace_lost_surface(&mut self) -> bool { + let lost = self.gpu.as_ref().is_none_or(|(gpu, _)| gpu.is_lost()); + let surface_missing = self.win.as_ref().is_some_and(|w| !w.surface_ok || w.surface.is_none()); + if !lost && !surface_missing { return true; } + let now = crate::time::now(); + let Some(step) = self.win.as_mut().map(|w| w.surface_retries.attempt()) else { return false }; + if step == SurfaceStep::GiveUp { + return self.give_up_surface(format!("the window's GPU surface was replaced {SURFACE_TRIES} times without a frame reaching the screen")); + } + match self.reattach() { + Ok(()) => { + if let Some(w) = self.win.as_mut() { w.backoff_step(BackoffEvent::Lapsed); } + true + } + Err(error) => match self.win.as_ref().and_then(|w| w.surface_retries.retry(now)) { + Some(at) => { + eprintln!("rune: could not replace the window's GPU surface, trying again: {error}"); + if let Some(w) = self.win.as_mut() { + w.surface_ok = false; + w.backoff_step(BackoffEvent::At(at)); + } + false + } + None => self.give_up_surface(format!("the window's GPU surface could not be replaced: {error}")), + }, + } + } + + /// Gives up the window and the device and surface it drew with, as `hide` does for an app + /// that releases its GPU when closed: it leaves the screen as `hide` leaves it, stops input + /// and hides the native window (`stop_showing`, `wind_down`), then the window, device and + /// surface go. An app sees `window_error` and can `open` the window again. + fn give_up_surface(&mut self, reason: String) -> bool { + eprintln!("rune: {reason}"); + self.stop_showing(); + self.wind_down(); + self.release(); + self.idle = true; + self.shared.set_window_error(Some(reason)); + false + } +} + +/// The surface alpha mode for a window that asked for `transparent`, and/or has a client-side frame +/// whose corner arcs the content fades out of, given the modes the surface `supports` (the first +/// that composites translucent pixels, or none). +/// +/// An app that asked for a translucent window takes whatever the surface offers, straight alpha +/// included: that is the mode it had before the frame existed, and Metal offers only +/// `PostMultiplied`, which `alpha_pass` converts. A window that only needs its corner pixels +/// transparent takes `PreMultiplied` alone, the one mode the in-place fade can scale, and is +/// `Opaque` — square corners — when the surface has nothing else. +pub(crate) fn alpha_mode( + transparent: bool, + client_frame: bool, + supports: Option<wgpu::CompositeAlphaMode>, +) -> wgpu::CompositeAlphaMode { + if transparent { + return supports.unwrap_or(wgpu::CompositeAlphaMode::Opaque); + } + if !client_frame { + return wgpu::CompositeAlphaMode::Opaque; + } + match supports { + Some(wgpu::CompositeAlphaMode::PreMultiplied) => wgpu::CompositeAlphaMode::PreMultiplied, + _ => wgpu::CompositeAlphaMode::Opaque, + } +} + +/// The pass that turns premultiplied pixels into straight alpha for a `PostMultiplied` surface on +/// a backend that composites premultiplied pixels (all but Metal). +fn alpha_pass(gpu: &Gpu, transparent: bool, config: &wgpu::SurfaceConfiguration, format: wgpu::TextureFormat) + -> Option<crate::render::surface_alpha::AlphaSurface> { + (transparent && config.alpha_mode == wgpu::CompositeAlphaMode::PostMultiplied + && gpu.adapter.get_info().backend != wgpu::Backend::Metal) + .then(|| crate::render::surface_alpha::AlphaSurface::new(&gpu.device, format, (config.width, config.height))) +} diff --git a/app/vendor/rune/crates/rune/src/window/host/draw.rs b/app/vendor/rune/crates/rune/src/window/host/draw.rs new file mode 100644 index 0000000..31bf39b --- /dev/null +++ b/app/vendor/rune/crates/rune/src/window/host/draw.rs @@ -0,0 +1,682 @@ +//! Drawing a window's frame: the drawable, the quiet timer frame that draws nothing new, and +//! the frames a covered or occluded window steps without drawing. + +use std::sync::atomic::Ordering; + +use super::Host; +use super::render::{ + FrameProfile, PreparedWindowFrame, open_trace_if_needed, prepare_window_render, + record_trace_frame, render_window_frame, submit_and_present_window, +}; +use super::stepping::FrameMove; +use crate::frame::clock::FrameClock; +use crate::frame::host_step::{ + self, Acquire, FrameHost, Gate, PostStepCheck, ReacquireReason, RenderPrep, StepInfo, +}; +use crate::runtime::RuntimeCore; +use crate::time::Instant; +use crate::window::chrome::sync_platform_core; +use crate::window::handle::native_window_number; +use crate::window::state::{Cover, RestEvent, rest}; +use crate::window::surface::{ + Backoff, BackoffEffect, BackoffEvent, Missed, Presented, Win, acquire, reblend_core, +}; +#[cfg(target_os = "macos")] +use crate::window::surface::{TIMER_FRAME, configure}; +#[cfg(target_os = "windows")] +use crate::window::win32::{covered_draw::CoveredDrawEvent, slot}; +#[cfg(target_os = "windows")] +use crate::window::WakeEvent; + +/// The first frame's marks (`crate::marks`), for the first window to draw. +static FIRST_BUILD: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); +/// The first frame the swap chain called occluded (a window DXGI won't present, as on a desktop +/// no one sees): the window then waits `OCCLUDED_RETRY` before it tries again. +static FIRST_OCCLUDED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + +/// Window-neutral miss state passed to [`apply_missed_core`] by [`Host::missed_frame`] and +/// unit tests. +struct MissState<'a> { + app: &'a mut dyn super::WindowApp, + clipboard: &'a crate::clipboard::Client, + reports: &'a mut crate::frame::encoded::FrameReports, + presented: &'a mut Option<Presented>, + backoff: &'a mut Backoff, + surface_ok: &'a mut bool, +} + +/// Window-neutral miss accounting shared by [`Host::missed_frame`] and unit tests: clears the +/// cached presented frame, marks the surface unconfigured when needed, advances backoff, steps +/// `covered_wake` iff this frame has not already stepped, flushes the clipboard, and reports a +/// skipped frame. +fn apply_missed_core( + state: MissState<'_>, + missed: Missed, + paced: bool, + stepped: bool, + now: Instant, +) -> crate::machine::Effects<BackoffEffect> { + if missed == Missed::Unconfigured { *state.surface_ok = false; } + *state.presented = None; + let effects = state.backoff.step(BackoffEvent::Missed { missed, paced, now }); + // What this frame would have run still runs, without drawing (`covered_step`). Misses + // come at the retry's pace, not the display's. + if !stepped { state.app.covered_wake(); } + state.clipboard.flush_core(state.app.rt_mut()); + state.reports.skipped(); + effects +} + +impl Host { + /// A shown frame with no drawable. Asking for a redraw here would turn the loop at once, for + /// as long as the window is occluded or its displays sleep, so it waits out a backoff + /// (`Backoff`), with its display link stopped so no tick redraws sooner. `stepped` when this + /// frame already ran the runtime. + pub(in crate::window) fn missed_frame(&mut self, missed: Missed, stepped: bool) { + #[cfg(feature = "frame-profile")] + crate::frame::live_log::missed(match missed { Missed::Occluded => 0, Missed::Timeout => 1, Missed::Outdated => 2, Missed::Unconfigured => 3 }); + let Some(l) = self.win.as_mut() else { return }; + l.timer_frame.drawn(); + let now = crate::time::now(); + let occluded = missed == Missed::Occluded; + if occluded { + crate::marks::mark_once(&FIRST_OCCLUDED, "frame.occluded"); + // Covered or asleep with no notification yet: rest as if one came, and look + // again when the backoff is up. + self.life.cover(Cover::Surface, true); + l.first_frame.skipped(now); + #[cfg(target_os = "macos")] + l.set_live_resize(false); + self.secure_input.set(false); + self.idle = true; + } + let paced = l.paced(); + let effects = apply_missed_core( + MissState { + app: &mut *self.app, + clipboard: &self.clipboard, + reports: &mut self.frame_reports, + presented: &mut l.presented, + backoff: &mut l.backoff, + surface_ok: &mut l.surface_ok, + }, + missed, + paced, + stepped, + now, + ); + for effect in effects { + match effect { + BackoffEffect::StopPacing => l.stop_pacing(), + } + } + self.meter.set_pacing(l.pacing_state(!occluded)); + if occluded { self.app.set_live_visible(false); } + } + + /// A frame for a window that's hidden, covered, asleep or minimised: while shown, what it + /// would have run runs without drawing (`covered_step`). It isn't live: a minimize X11 + /// reports with no event lands here first, and the frame that next draws settles. + pub(in crate::window) fn covered_frame(&mut self) { + let Some(l) = self.win.as_mut() else { return }; + l.timer_frame.drawn(); + l.presented = None; + l.stop_pacing(); + let shown = self.life.shown(); + l.first_frame.skipped(crate::time::now()); + // Covered by other windows, it still draws what changed, later (`CoveredDraw`). + #[cfg(target_os = "windows")] + if shown && self.life.covered() && !l.minimized() { l.covered_draw = l.covered_draw.step(CoveredDrawEvent::Asked(crate::time::now())); } + self.land_frame(); + if shown { + self.app.set_live_visible(false); + self.app.covered_wake(); + self.clipboard.flush_core(self.app.rt_mut()); + self.frame_reports.skipped(); + } + } + + pub(in crate::window) fn redraw(&mut self) { self.draw(false) } + + /// Draws a frame. `resizing` draws one for a size the user just dragged the window to, at + /// once: AppKit shows the new size when the event returns, with or without it. + pub(in crate::window) fn draw(&mut self, resizing: bool) { + // Windows: a window still on the CPU renderer draws there (`cpu_frame`). + #[cfg(target_os = "windows")] + { + self.look(); + self.hand_over_if_done(); + if self.win.as_ref().is_some_and(|w| w.native.mode.cpu_draws()) { return self.draw_cpu(resizing); } + } + let mut frame = WindowFrame { host: self, resizing, state: FrameState::default() }; + host_step::run(&mut frame); + } +} + +#[derive(Default)] +struct FrameState { + hidden: bool, + live_resize: bool, + corners: f32, + target: Option<Instant>, + #[cfg(target_os = "macos")] + prewarm: Option<crate::platform::macos::Prewarm>, + #[cfg(target_os = "macos")] + deferred: bool, + #[cfg(target_os = "macos")] + shown: Option<crate::platform::macos::PresumeShown>, + #[cfg(target_os = "macos")] + drawable: Option<u64>, + #[cfg(target_os = "macos")] + materials_checked: bool, + #[cfg(target_os = "macos")] + frame_time: Option<Instant>, + only_loops: bool, + looped: Option<Vec<u32>>, + profile: FrameProfile, + post_acquire_done: bool, + now: Option<Instant>, + encoded: Option<Instant>, +} + +struct WindowFrame<'a> { + host: &'a mut Host, + resizing: bool, + state: FrameState, +} + +impl WindowFrame<'_> { + fn reblend_surface(&mut self) -> bool { + let (Some(l), Some((gpu, renderer))) = (self.host.win.as_mut(), self.host.gpu.as_mut()) else { return false }; + let Some(surface) = l.surface.as_ref() else { return false }; + #[cfg(target_os = "windows")] + l.native.slot.reset(); + reblend_core(surface, gpu, &mut l.config, renderer, &mut l.alpha, self.host.app.rt_mut()) + } +} + +impl FrameHost for WindowFrame<'_> { + type Drawable = wgpu::SurfaceTexture; + type Prepared = PreparedWindowFrame; + + fn gate(&mut self) -> Gate { + let launcher = self.host.launcher(); + let Some(l) = self.host.win.as_ref() else { return Gate::Skip }; + let hidden = launcher && !self.host.life.shown(); + let covered = (!launcher && !self.host.life.uncovered()) || l.minimized(); + #[cfg(target_os = "windows")] + let owed = covered && !l.minimized() && l.covered_draw.drawing(); + #[cfg(not(target_os = "windows"))] + let owed = false; + if covered && !owed { + // A covered window's clips stop presenting on their layers, as they stop being pulled. + #[cfg(target_os = "windows")] + if let Some(w) = self.host.win.as_mut() { + let native = &mut w.native; + native.video_layers.release(native.mode.handover()); + } + self.host.covered_frame(); + return Gate::Skip; + } + // A covered window's owed frame shows the settled state, as its first one uncovered does. + if owed { self.host.app.rt_mut().settle_all(); } + // A missed frame's retry, or the timer pacing unpaced motion: input waits for it, and + // `new_events` runs due timers meanwhile. + if !self.resizing && l.backing_off(crate::time::now()) { return Gate::Skip; } + // A device that died (a driver reset, a GPU removed, a resume from Modern Standby) and a + // surface that refused its configuration can draw nothing: the window makes both again + // before this frame, or waits out a retry of its own (`SurfaceRetries`) and then gives + // them up. Neither can give a drawable, and wgpu panics asking one for it. + if !self.host.replace_lost_surface() { return Gate::Skip; } + // The radius a client-side frame rounds this window's bottom corners to, in device + // pixels: zero unless it draws one, now and with a surface that composites alpha + // (`corners`). Asked every frame, so a maximize or a tile that arrives with a configure + // squares the next one. + self.state.corners = self.host.win.as_ref().map_or(0., |l| self.host.corner_radius(l)); + // A clip's layer began or stopped showing: the UI's swap chain composites premultiplied + // only while one does (`video_layer`), made again before this frame draws. + #[cfg(target_os = "windows")] + if let Some(premultiplied) = self.host.win.as_mut().and_then(|w| w.native.video_layers.take_alpha()) + && let Err(error) = self.host.rebind_alpha(premultiplied) + { + eprintln!("rune: the window's swap chain couldn't change its alpha for a clip's layer: {error}"); + } + // The swap chain still holds a frame the compositor hasn't shown: this one draws when it + // has room, built from the input that came by then (`slot`). + #[cfg(target_os = "windows")] + if !hidden && let Some(l) = self.host.win.as_mut() && let Some(surface) = l.surface.as_ref() { + let handle = self.host.native_handle.clone(); + if l.native.slot.take_surface(surface, move || handle.send(WakeEvent::FrameSlot)) == slot::Take::Later { return Gate::Skip; } + } + let Some(l) = self.host.win.as_mut() else { return Gate::Skip }; + #[cfg(target_os = "windows")] + if owed { l.covered_draw = l.covered_draw.step(CoveredDrawEvent::Drawn); } + // The frame a due timer asked for is here, drawing or running covered below. + l.timer_frame.drawn(); + // Starting the display link for a window that isn't on screen would wait for a tick that + // sleeping displays never send, and a running link holds back its timers (`wake_deadline`). + #[cfg(target_os = "macos")] + if !hidden { + if !l.natively_occluded() { + l.native.prime.stop(); + } else if !l.native.prime.presumes() { + self.host.meter.skipped(); + self.host.missed_frame(Missed::Occluded, false); + return Gate::Skip; + } + } + #[cfg(target_os = "macos")] + if hidden { self.state.prewarm = l.native.panel.as_ref().map(|p| p.prewarm()); } + // Only a timer woke the resting window, so its frame may draw what's on screen. It + // decides that before starting the display link, which would draw it at once anyway. + #[cfg(target_os = "macos")] + let deferred = l.timer_frame.quiet() && !hidden && !self.resizing && !l.native.prime.presumes() + && l.native.pacing.as_ref().is_some_and(|p| p.defers_start(crate::time::now())); + #[cfg(not(target_os = "macos"))] + let deferred = false; + #[cfg(target_os = "macos")] + let target = if hidden || self.resizing || deferred { None } else if let Some(pacing) = &mut l.native.pacing { + if l.native.prime.presumes() && !pacing.running() { + None + } else { + let Some(target) = pacing.next_frame().target() else { return Gate::Skip }; + target + } + } else { None }; + #[cfg(target_os = "macos")] + let shown = if !hidden && l.native.prime.presumes() { + l.native.prime.spend(); + if let Some(surface) = l.surface.as_ref() + && let Some(shown) = crate::platform::macos::PresumeShown::new(surface) { + Some(shown) + } else { + self.host.meter.skipped(); + self.host.missed_frame(Missed::Occluded, false); + return Gate::Skip; + } + } else { + None + }; + if self.host.native_handle.native.number.load(Ordering::Relaxed) == 0 { + self.host.native_handle.native.number.store(native_window_number(&l.window).unwrap_or(0), Ordering::Release); + } + #[cfg(not(target_os = "macos"))] + let target: Option<Instant> = None; + if !hidden { self.host.meter.redraw(l.paced_for_stats() || deferred); } + #[cfg(target_os = "macos")] + let live_resize = !hidden && (self.resizing || crate::platform::macos::in_live_resize(&l.window)); + #[cfg(not(target_os = "macos"))] + let live_resize = self.resizing; + self.state.hidden = hidden; + self.state.live_resize = live_resize; + self.state.target = target; + #[cfg(target_os = "macos")] + { + self.state.deferred = deferred; + self.state.shown = shown; + } + if self.host.gpu.is_none() { return Gate::Skip; } + self.state.profile.mark_entry(); + let (Some(l), Some((_, renderer))) = (self.host.win.as_mut(), self.host.gpu.as_ref()) else { return Gate::Skip }; + // Only the window's loops asked for this frame (`LoopFrame`): a step of them may stand + // for the whole of it (`Runtime::loop_step`), drawn only where they draw (`arm_loop`). + let only_loops = l.loop_frame.only_loops(); + if !only_loops { self.state.profile.set_loop_why("something reached the window"); } + // The app's waker ran and its event is still on its way: what it brought may be readable now. + let only_loops = only_loops && !self.host.app_woken.load(Ordering::Acquire); + if !only_loops { self.state.profile.set_loop_why_if_none("an app wake on its way"); } + #[cfg(target_os = "windows")] + let only_loops = only_loops && !hidden && !live_resize && self.host.trace.is_none() && self.host.args.trace.is_none() + && self.host.app.rt().host.window_frame.is_none() && !FrameMove::moving(&self.host.frame_move) && !self.host.app.compositor_animating(); + #[cfg(not(target_os = "windows"))] + let only_loops = only_loops && false; + self.state.only_loops = only_loops; + // Only a timer woke the resting window: build the frame first, and take no drawable + // when it draws what's on screen. + let quiet = l.timer_frame.take_quiet() && !hidden && !live_resize && l.presented.is_some() + && !self.host.app.compositor_draws_own() + && self.host.trace.is_none() && self.host.args.trace.is_none() + && self.host.app.rt().live_visible() + && self.host.app.rt().host.window_frame.is_none() && !FrameMove::moving(&self.host.frame_move) + && renderer.srgb_blend() == self.host.app.rt().srgb_blend(); + #[cfg(target_os = "macos")] + let quiet = quiet && self.state.shown.is_none() && !l.native.materials.native(); + if quiet { + #[cfg(target_os = "macos")] + l.set_live_resize(false); + l.backoff_step(BackoffEvent::Lapsed); + #[cfg(target_os = "macos")] + { self.host.app.rt_mut().paint.set_native_materials(l.native.materials.native()); } + if self.host.frame_reports.wanted() { self.host.frame_reports.set_refresh(display_hz(l)); } + Gate::QuietTimer + } else { + #[cfg(target_os = "macos")] + if self.state.deferred && let Some(pacing) = &mut l.native.pacing { let _ = pacing.next_frame(); } + Gate::Draw + } + } + + fn before_acquire(&mut self) { + // The frame moves before the drawable is acquired, so it has the new size; never while + // the user holds the window's edge in a live resize. + if !self.state.hidden && !self.state.live_resize { + self.host.step_frame(self.state.target.unwrap_or_else(crate::time::now)); + } + let Some(l) = self.host.win.as_mut() else { return }; + #[cfg(target_os = "macos")] + l.set_live_resize(self.resizing && self.state.live_resize); + // Acquire before latching live values so a drawable wait cannot age the input. + l.backoff_step(BackoffEvent::Lapsed); + #[cfg(target_os = "macos")] + { self.host.app.rt_mut().paint.set_native_materials(l.native.materials.native()); } + if self.host.frame_reports.wanted() { self.host.frame_reports.set_refresh(display_hz(l)); } + } + + fn needs_reblend(&self) -> bool { + self.host.gpu.as_ref().is_some_and(|(_, renderer)| renderer.srgb_blend() != self.host.app.rt().srgb_blend()) + } + + fn reblend(&mut self) -> bool { self.reblend_surface() } + + fn step_quiet(&mut self) -> StepInfo { + let now = crate::time::now(); + self.state.now = Some(now); + self.host.app.rt_mut().host.window_resting = true; + let at = self.state.target.unwrap_or(now); + #[cfg(target_os = "macos")] + { self.state.frame_time = Some(at); } + let step = if self.state.only_loops { loop_step(&mut self.host.clock, self.host.app.rt_mut(), at) } else { Err("") }; + let (animating, dt) = match step { + Ok((patched, dt)) => { + if !patched.is_empty() { + self.state.looped = Some(patched); + } + (self.host.app.rt().animating, dt) + } + Err(why) => { + if !why.is_empty() { self.state.profile.set_loop_why(why); } + self.host.app.clock_advance(&mut self.host.clock, at, false) + } + }; + self.state.profile.take_loop_check(self.host.app.rt_mut()); + StepInfo { runtime_animating: animating, animating, dt, update_ms: 0.0, presents_at: self.state.target } + } + + fn is_unchanged(&mut self, info: &StepInfo) -> bool { + let (Some(l), Some((_, renderer))) = (self.host.win.as_ref(), self.host.gpu.as_ref()) else { return false }; + let now = self.state.now.unwrap_or_else(crate::time::now); + #[cfg(target_os = "macos")] + let next_tick = if self.state.deferred { l.native.pacing.as_ref().map(|p| p.tick_after(now)) } else { l.next_tick(now) }; + #[cfg(not(target_os = "macos"))] + let next_tick = l.next_tick(now); + self.state.looped.is_none() + && renderer.srgb_blend() == self.host.app.rt().srgb_blend() + && l.presented.as_ref().is_some_and(|p| p.unchanged_core(self.host.app.rt(), &l.config, info.animating, next_tick)) + } + + fn on_unchanged(&mut self, _info: &StepInfo) { + let Some(l) = self.host.win.as_mut() else { return }; + sync_platform_core(l, self.host.app.rt_mut(), &mut self.host.secure_input, &mut self.host.ime_allowed, &self.host.clipboard); + l.stop_pacing(); + self.host.meter.set_pacing(l.pacing_state(false)); + self.host.frame_reports.unchanged(self.state.target); + } + + fn on_quiet_will_draw(&mut self) { + // It draws: the link starts, and still says draw at once. + #[cfg(target_os = "macos")] + if self.state.deferred && let Some(l) = self.host.win.as_mut() && let Some(pacing) = &mut l.native.pacing { + let _ = pacing.next_frame(); + } + crate::marks::mark_once(&FIRST_BUILD, "frame.first.build"); + } + + fn acquire(&mut self) -> Acquire<wgpu::SurfaceTexture> { + self.state.profile.mark_start(); + let (Some(l), Some((gpu, _))) = (self.host.win.as_mut(), self.host.gpu.as_ref()) else { + return Acquire::Missed(Missed::Unconfigured); + }; + let Some(surface) = l.surface.as_ref() else { return Acquire::Missed(Missed::Unconfigured) }; + let frame = match acquire(surface, gpu, &l.config, l.surface_ok, 1, &mut self.host.meter) { + Ok(frame) => frame, + Err(missed) => return Acquire::Missed(missed), + }; + self.state.profile.mark_acquired(); + if !self.state.post_acquire_done { + self.state.post_acquire_done = true; + // A covered window's owed frame (`CoveredDraw`) draws settled and stays covered: live, its + // loops would ask for frames no one sees. + if !self.state.hidden && !self.host.life.covered() && !self.host.app.rt().live_visible() + && { let size = l.window.inner_size(); size.width > 0 && size.height > 0 } + { + // Uncovered after a missed frame said it was occluded. + self.host.app.set_live_visible(true); + self.host.app.rt_mut().settle_all(); + #[cfg(target_os = "macos")] + if l.native.pacing.is_none() { + l.native.pacing = crate::platform::display_link::DisplayLink::new(&l.window, self.host.frame_wake.clone()); + } + } + let now = *self.state.now.get_or_insert_with(crate::time::now); + open_trace_if_needed(self.host, now); + } + #[cfg(target_os = "macos")] + if let Some(l) = self.host.win.as_ref() { + self.state.drawable = l.native.present.as_ref().and(self.host.present_log.as_ref()).and_then(|log| log.acquired()); + } + Acquire::Ready(frame) + } + + fn step_runtime(&mut self) -> StepInfo { + let now = *self.state.now.get_or_insert_with(crate::time::now); + let frame_time = self.state.target.unwrap_or(now); + #[cfg(target_os = "macos")] + { self.state.frame_time = Some(frame_time); } + self.host.app.rt_mut().host.window_resting = !FrameMove::moving(&self.host.frame_move) && self.host.app.rt().host.window_frame.is_none(); + crate::marks::mark_once(&FIRST_BUILD, "frame.first.build"); + if self.state.hidden && self.host.win.as_ref().is_some_and(|l| l.first_frame.settles()) { + self.host.app.rt_mut().settle_all(); + } + let stepped = if self.state.only_loops { loop_step(&mut self.host.clock, self.host.app.rt_mut(), frame_time) } else { Err("") }; + if let Err(why) = stepped && !why.is_empty() { self.state.profile.set_loop_why(why); } + let (animating, dt) = if self.state.hidden { + self.host.clock.hold(frame_time); + (self.host.app.frame(0.0), 0.0) + } else if let Ok((patched, dt)) = stepped { + if !patched.is_empty() { + self.state.looped = Some(patched); + } + (self.host.app.rt().animating, dt) + } else { + let compositing = self.host.app.compositor_animating(); + self.host.app.clock_advance(&mut self.host.clock, frame_time, compositing) + }; + // `RUNE_LOOP_CHECK=1`: how the loop-only step this frame stood in for compares with it. + self.state.profile.take_loop_check(self.host.app.rt_mut()); + StepInfo { runtime_animating: animating, animating, dt, update_ms: 0.0, presents_at: self.state.target } + } + + fn post_step_check(&mut self, _info: &mut StepInfo) -> PostStepCheck { + // frame-profile, `RUNE_MISS_LOOP_FRAMES=<n>`: every nth loop-only frame ends here as if its + // drawable never came, after the step: what the next frame redraws (with + // `RUNE_LOOP_CHECK=2`, whether its picture is right). + #[cfg(feature = "frame-profile")] + if !self.state.profile.forced_miss_checked { + self.state.profile.forced_miss_checked = true; + if self.state.looped.is_some() && crate::window::surface::loop_frame::forced_miss() { + return PostStepCheck::Missed(Missed::Timeout); + } + } + #[cfg(target_os = "macos")] + if !self.state.materials_checked { + self.state.materials_checked = true; + if let Some(l) = self.host.win.as_mut() + && l.surface.as_ref().is_some_and(|surface| l.native.materials.update(self.host.app.rt().transparent, !self.host.app.rt().paint.materials().is_empty(), &l.window, surface)) + { + return PostStepCheck::Reacquire(ReacquireReason::NativeMaterials); + } + } + if self.needs_reblend() { + return PostStepCheck::Reacquire(ReacquireReason::Reblend); + } + PostStepCheck::Keep + } + + fn prepare_reacquire(&mut self, reason: ReacquireReason, info: &mut StepInfo) -> bool { + match reason { + #[cfg(any(test, target_os = "macos"))] + ReacquireReason::NativeMaterials => { + // This drawable presents without the views: build again natively into a new one. + self.host.app.rt_mut().paint.set_native_materials(true); + let more = self.host.app.frame(0.0); + info.runtime_animating |= more; + info.animating |= more; + true + } + ReacquireReason::Reblend => { + let _ = info; + self.reblend_surface() + } + } + } + + fn on_missed(&mut self, missed: Missed, stepped: bool) { + if missed == Missed::Unconfigured { + self.host.missed_frame(Missed::Unconfigured, stepped); + return; + } + if self.state.hidden { + if let Some(l) = self.host.win.as_mut() { + l.first_frame.missed(); + l.backoff_step(BackoffEvent::HiddenMissed { + preparing: l.first_frame.deadline().is_some(), + now: crate::time::now(), + }); + } + self.host.frame_reports.skipped(); + return; + } + self.host.missed_frame(missed, stepped); + } + + fn sync_after_step(&mut self, info: &mut StepInfo) { + #[cfg(target_os = "macos")] + self.state.shown.take(); + let now = self.state.now.unwrap_or_else(crate::time::now); + let Some(l) = self.host.win.as_mut() else { return }; + l.backoff_step(BackoffEvent::Presented); + if self.state.hidden { l.hidden_pace.rendered(now); } + info.update_ms = now.elapsed().as_secs_f64() * 1000.0; + self.state.profile.mark_built(); + sync_platform_core(l, self.host.app.rt_mut(), &mut self.host.secure_input, &mut self.host.ime_allowed, &self.host.clipboard); + } + + fn prepare_render(&mut self, drawable: wgpu::SurfaceTexture, info: &mut StepInfo) -> RenderPrep<PreparedWindowFrame> { + prepare_window_render(self.host, drawable, self.state.corners, self.state.looped.as_ref(), &mut self.state.profile, info) + } + + fn render(&mut self, prepared: &mut PreparedWindowFrame, info: &StepInfo) -> bool { + render_window_frame(self.host, prepared, self.state.corners, &mut self.state.profile, info) + } + + fn submit_and_present(&mut self, prepared: PreparedWindowFrame, info: &StepInfo) -> Instant { + submit_and_present_window(self.host, prepared, self.state.looped.as_ref(), &mut self.state.profile, &mut self.state.encoded, info) + } + + fn present_targets(&mut self) -> (Option<&mut FrameClock>, &mut RuntimeCore) { + (Some(&mut self.host.clock), self.host.app.rt_mut()) + } + + fn settle(&mut self, submitted: Instant, info: &StepInfo) { + let now = self.state.now.unwrap_or(submitted); + self.host.meter.presented(); + #[cfg(target_os = "macos")] + if let Some(l) = self.host.win.as_mut() { + if let Some(pacing) = &mut l.native.pacing { pacing.presented(submitted); } + // A display link that couldn't be made while the displays slept: they're back. + if !self.state.hidden && l.native.pacing.is_none() { + l.native.pacing = crate::platform::display_link::DisplayLink::retry(&l.window, self.host.frame_wake.clone()); + } + } + self.host.frame_reports.drawn(self.state.encoded, info.presents_at, now, info.update_ms); + self.host.app.inspect_frame(); + #[cfg(target_os = "macos")] + let drawable = self.state.drawable; + #[cfg(not(target_os = "macos"))] + let drawable = None; + if record_trace_frame(self.host, now, submitted, self.state.target, drawable) { + return; + } + let Some(l) = self.host.win.as_mut() else { return }; + // A poll asking for the next frame (`wake_after(Duration::ZERO)`) keeps a running display + // link going; without one its timer waits a frame in `wake_deadline`. + let next_tick = l.next_tick(now).filter(|_| !self.state.hidden); + let rests = !self.state.hidden && !(self.host.trace.is_some() && self.host.args.frames.is_some()); + self.host.idle = Presented::settle_core( + &mut l.presented, + self.host.app.rt(), + &l.config, + info.animating || FrameMove::moving(&self.host.frame_move), + next_tick, + rests, + self.host.app.compositor_draws_own(), + ); + // A drawn frame asks for nothing: it only puts the rest off. + if !self.state.hidden { let _ = rest::step(&mut self.host.rest, RestEvent::Drew { now, low: rest::low_memory() }); } + #[cfg(target_os = "macos")] + if !self.state.hidden && let Some(latency) = l.native.launch_drawables.settle(self.host.idle, now) { + l.config.desired_maximum_frame_latency = latency; + if let (Some(surface), Some((gpu, _))) = (l.surface.as_ref(), self.host.gpu.as_ref()) + && let Err(error) = configure(surface, gpu, &l.config) + { + eprintln!("rune: a window's surface refused its frame latency: {error}"); + l.surface_ok = false; + } + } + if !self.state.hidden && (!self.host.idle || (self.host.trace.is_some() && self.host.args.frames.is_some())) { + // Without a running display link, macOS hands out drawables faster than the + // display shows them, so a timer paces the next frame instead of the loop. + #[cfg(target_os = "macos")] + if !l.native.pacing.as_mut().is_some_and(|p| p.start()) { l.backoff_step(BackoffEvent::At(now + TIMER_FRAME)); } + #[cfg(not(target_os = "macos"))] + l.request_redraw(); + self.host.meter.set_pacing(l.pacing_state(true)); + } else { + l.stop_pacing(); + self.host.meter.set_pacing(l.pacing_state(false)); + } + self.state.profile.flush(self.host, info.animating, next_tick); + // A frame change this frame's commit asked for starts with the layout springs it + // started, which have shown a step unless they held for the window; the next frame + // moves it. While the user drags the edge, it waits until they let go. + #[cfg(target_os = "macos")] + if !self.state.hidden && !self.state.live_resize && self.host.app.rt().host.window_frame.is_some() { + let frame_time = self.state.frame_time.unwrap_or(now); + let shown = if self.host.app.rt_mut().host.fit.take_held() { 0.0 } else { crate::frame::clock::RESUME_STEP }; + let start = self.host.frame_secs(frame_time) - shown; + self.host.take_frame_request(start, true); + } + } +} + +/// A loop-only step for the frame presented at `at` (`Runtime::loop_step`): the instances it +/// wrote and the seconds it stepped, or why it takes an ordinary frame. The frame clock takes +/// the step only when the runtime does. +fn loop_step(clock: &mut FrameClock, rt: &mut RuntimeCore, at: Instant) -> Result<(Vec<u32>, f64), &'static str> { + let dt = at.saturating_duration_since(clock.last()).as_secs_f64(); + let patched = rt.loop_step(dt)?; + clock.frame_step(at, true); + rt.frame.set_frame_target(at); + Ok((patched, dt)) +} + +/// The window's display refresh: its display link's on macOS, else the monitor's. +fn display_hz(l: &Win) -> Option<f64> { + #[cfg(target_os = "macos")] + if let Some(pacing) = &l.native.pacing { return Some(pacing.refresh_hz()); } + l.window.current_monitor().and_then(|m| m.refresh_rate_millihertz()).map(|hz| hz as f64 / 1000.0) +} + +#[cfg(test)] +#[path = "draw_tests.rs"] +mod tests; diff --git a/app/vendor/rune/crates/rune/src/window/host/draw_tests.rs b/app/vendor/rune/crates/rune/src/window/host/draw_tests.rs new file mode 100644 index 0000000..73d9f93 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/window/host/draw_tests.rs @@ -0,0 +1,232 @@ +use std::cell::RefCell; +use std::rc::Rc; +use std::sync::Arc; + +use super::{MissState, apply_missed_core}; +use crate::app::Shared; +use crate::frame::clock::FrameClock; +use crate::frame::encoded::FrameReports; +use crate::frame::host_step::{ + self, Acquire, FrameHost, Gate, Outcome, PostStepCheck, ReacquireReason, RenderPrep, StepInfo, +}; +use crate::runtime::{Env, Runtime, RuntimeCore}; +use crate::time::Instant; +use crate::window::host::app::{TypedWindowApp, WindowApp}; +use crate::window::surface::{Backoff, Missed, Presented}; +use crate::{Cx, El, FrameOutcome, Tx, el}; + +#[derive(Default)] +struct State { + polls: u32, + switch_blend: bool, + copy_on_poll: bool, +} + +fn view(_: &State, _: &mut Cx<State>) -> El { + el().size(40.0, 20.0) +} + +fn poll(s: &mut State, _: f64, tx: &mut Tx) -> bool { + s.polls += 1; + if std::mem::take(&mut s.switch_blend) { + tx.set_srgb_blend(false); + } + if std::mem::take(&mut s.copy_on_poll) { + tx.copy("copied-before-reblend-miss"); + } + true +} + +fn surface_config() -> wgpu::SurfaceConfiguration { + wgpu::SurfaceConfiguration { + usage: wgpu::TextureUsages::RENDER_ATTACHMENT, + format: wgpu::TextureFormat::Bgra8UnormSrgb, + width: 80, + height: 40, + present_mode: wgpu::PresentMode::AutoVsync, + desired_maximum_frame_latency: 2, + alpha_mode: wgpu::CompositeAlphaMode::Opaque, + view_formats: vec![], + color_space: Default::default(), + } +} + +/// Window-host-shaped adapter running through `host_step::run` and `apply_missed_core` without a +/// native `winit::Window`. +struct MockWindowFrame { + app: TypedWindowApp<State>, + clock: FrameClock, + clipboard: crate::clipboard::Client, + clipboard_memory: crate::clipboard::MemoryClipboard, + reports: FrameReports, + presented: Option<Presented>, + backoff: Backoff, + surface_ok: bool, + renderer_srgb: bool, + reblend_succeeds: bool, + now: Instant, +} + +impl MockWindowFrame { + fn new(now: Instant, outcomes: Rc<RefCell<Vec<FrameOutcome>>>) -> Self { + let mut rt = Runtime::new(State::default(), view, (40.0, 20.0), Env::default()); + rt.poll = Some(poll); + rt.wall_start = Some(now); + rt.set_srgb_blend(true); + rt.frame(0.0); + let config = surface_config(); + let mut presented = None; + Presented::record(&mut presented, &rt, &config, false); + let shared = Arc::new(Shared::default()); + let app = TypedWindowApp { + rt, + shared, + comp: None, + on_frame_drawn: None, + on_close: None, + on_rest: None, + on_quit: None, + on_reopen: None, + turn_scope: None, + }; + let reports = FrameReports::new( + Some(Box::new(move |f| outcomes.borrow_mut().push(f.outcome()))), + Some("main"), + ); + let clipboard_memory = crate::clipboard::memory(); + let mut clipboard = crate::clipboard::Client::default(); + clipboard.use_memory(&clipboard_memory); + Self { + app, + clock: FrameClock::new(now), + clipboard, + clipboard_memory, + reports, + presented, + backoff: Backoff::default(), + surface_ok: true, + renderer_srgb: true, + reblend_succeeds: false, + now, + } + } +} + +impl FrameHost for MockWindowFrame { + type Drawable = (); + type Prepared = (); + + fn gate(&mut self) -> Gate { Gate::Draw } + + fn needs_reblend(&self) -> bool { + self.renderer_srgb != self.app.rt().srgb_blend() + } + + fn reblend(&mut self) -> bool { + if self.reblend_succeeds { + self.renderer_srgb = self.app.rt().srgb_blend(); + true + } else { + false + } + } + + fn acquire(&mut self) -> Acquire<()> { Acquire::Ready(()) } + + fn step_runtime(&mut self) -> StepInfo { + let (core, mut driver) = self.app.rt.split_mut(); + let (animating, dt) = self.clock.advance_core(core, &mut driver, self.now, false); + StepInfo { runtime_animating: animating, animating, dt, update_ms: 0.0, presents_at: None } + } + + fn post_step_check(&mut self, _info: &mut StepInfo) -> PostStepCheck { + if self.needs_reblend() { + PostStepCheck::Reacquire(ReacquireReason::Reblend) + } else { + PostStepCheck::Keep + } + } + + fn prepare_reacquire(&mut self, reason: ReacquireReason, _info: &mut StepInfo) -> bool { + match reason { + ReacquireReason::Reblend => self.reblend(), + #[cfg(any(test, target_os = "macos"))] + ReacquireReason::NativeMaterials => true, + } + } + + fn on_missed(&mut self, missed: Missed, stepped: bool) { + let _ = apply_missed_core( + MissState { + app: &mut self.app, + clipboard: &self.clipboard, + reports: &mut self.reports, + presented: &mut self.presented, + backoff: &mut self.backoff, + surface_ok: &mut self.surface_ok, + }, + missed, + false, + stepped, + self.now, + ); + } + + fn prepare_render(&mut self, _drawable: (), _info: &mut StepInfo) -> RenderPrep<()> { + RenderPrep::Ready(()) + } + + fn render(&mut self, _prepared: &mut (), _info: &StepInfo) -> bool { false } + + fn submit_and_present(&mut self, _prepared: (), _info: &StepInfo) -> Instant { self.now } + + fn present_targets(&mut self) -> (Option<&mut FrameClock>, &mut RuntimeCore) { + (Some(&mut self.clock), self.app.rt_mut()) + } +} + +#[test] +fn post_step_reblend_failure_runs_missed_frame_cleanup_without_double_stepping() { + let now = crate::time::now(); + let outcomes = Rc::new(RefCell::new(Vec::new())); + let mut host = MockWindowFrame::new(now, outcomes.clone()); + let polls_before = host.app.rt.state.polls; + host.app.rt.state.switch_blend = true; + host.app.rt.state.copy_on_poll = true; + + assert_eq!(host_step::run(&mut host), Outcome::Missed); + assert!(!host.surface_ok, "failed reblend marks surface unconfigured for replacement"); + assert!(host.presented.is_none(), "failed reblend drops cached presented frame"); + assert!(host.backoff.deadline().is_some(), "failed reblend schedules retry backoff"); + assert_eq!(host.app.rt.state.polls, polls_before + 1, "post-step reblend failure must not step poll twice"); + assert!(host.app.rt.copy_request.is_none(), "clipboard request from the stepped frame must be flushed"); + assert_eq!( + host.clipboard_memory.text().as_deref().map(String::as_str), + Some("copied-before-reblend-miss"), + "clipboard request from the stepped frame must reach the clipboard" + ); + assert_eq!(*outcomes.borrow(), [FrameOutcome::Skipped], "failed reblend reports a skipped frame"); +} + +#[test] +fn pre_step_reblend_failure_runs_covered_wake_once_and_schedules_backoff() { + let now = crate::time::now(); + let outcomes = Rc::new(RefCell::new(Vec::new())); + let mut host = MockWindowFrame::new(now, outcomes.clone()); + let polls_before = host.app.rt.state.polls; + host.app.rt.set_srgb_blend(false); + host.app.rt.state.copy_on_poll = true; + + assert_eq!(host_step::run(&mut host), Outcome::Missed); + assert!(!host.surface_ok, "pre-step reblend failure marks surface unconfigured"); + assert!(host.presented.is_none(), "pre-step reblend failure clears cached presented frame"); + assert!(host.backoff.deadline().is_some(), "pre-step reblend failure schedules retry backoff"); + assert_eq!(host.app.rt.state.polls, polls_before + 1, "pre-step miss runs covered_wake once"); + assert!(host.app.rt.copy_request.is_none(), "clipboard request from covered_wake must be flushed"); + assert_eq!( + host.clipboard_memory.text().as_deref().map(String::as_str), + Some("copied-before-reblend-miss"), + "clipboard request from covered_wake must reach the clipboard" + ); + assert_eq!(*outcomes.borrow(), [FrameOutcome::Skipped]); +} diff --git a/app/vendor/rune/crates/rune/src/window/host/events.rs b/app/vendor/rune/crates/rune/src/window/host/events.rs new file mode 100644 index 0000000..efa73d8 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/window/host/events.rs @@ -0,0 +1,603 @@ +//! Events a host handles: resuming, input while hidden, the fn key, file drops, and user and +//! window events. + +use std::sync::atomic::Ordering; + +use winit::dpi::{LogicalPosition, LogicalSize}; +use winit::event::{ElementState, MouseButton, WindowEvent}; +use winit::event_loop::ActiveEventLoop; +use winit::window::{Theme, Window, WindowId}; + +use super::stepping::FrameMove; +use super::{Host, WindowApp}; +use crate::app::Shared; +use crate::input::host_events; +use crate::runtime::TitlebarAction; +use crate::window::chrome::{self, sync_chrome_core, titlebar_double_click}; +#[cfg(target_os = "macos")] +use crate::window::chrome::mac; +use crate::window::file_drop::{FileDrop, FileStep}; +use crate::window::keys::{map_key_event, map_mods}; +use crate::window::state::{Cover, RestEvent}; +#[cfg(not(target_os = "macos"))] +use crate::window::surface::RedrawEvent; +use crate::window::surface::Win; +use crate::window::{WakeEvent, gesture_phase, pointer_button, sync_screen_origin_core}; + +impl Host { + pub(in crate::window) fn resume(&mut self, event_loop: &ActiveEventLoop) { + if self.started { + return; + } + // Updates queued before launch (the link that launched the app) show in the first frame. + self.app.drain_startup(&self.shortcuts, &mut self.menus); + if self.launcher() { + self.create(event_loop, None, false); + if self.open_at_start && self.options.visible { self.reveal_launcher(event_loop); } + } else if self.open_at_start { + self.open(event_loop, None); + } + self.started = true; + self.drain(event_loop, false); + } + + /// A hidden window delivers queued input without drawing, such as the releases of the + /// modifier keys held when it hid, rather than when it next shows. A shown window's + /// redraw delivers it, as does a hidden launcher's. + pub(in crate::window) fn hidden_input(&mut self, event_loop: &ActiveEventLoop) { + if !self.started || self.life.finished() || self.win.as_ref().is_some_and(|_| self.life.shown() || self.launcher()) { return; } + if !self.app.rt().keys_queued() { return; } + self.app.hidden_timer_frame(); + self.clipboard.flush_core(self.app.rt_mut()); + self.shell(event_loop); + } + + #[cfg(target_os = "macos")] + pub(in crate::window) fn fn_key(&mut self) { + let Some(l) = &self.win else { return }; + let Some(changes) = l.native.fn_key.as_ref().map(|f| f.take()) else { return }; + let mut redraw = false; + for pressed in changes { + redraw |= self.app.physical_with_fallback(crate::PhysicalInput::Key { + key: winit::keyboard::KeyCode::Fn, mods: map_mods(self.mods), pressed, repeat: false, + }, None); + } + if redraw { l.request_redraw(); } + } + + /// Hands the runtime the file drag winit reported since the last pass, in order: the files + /// that entered, as one drag, and those dropped, as one drop, each at a fresh pointer + /// sample; and, while the drag is over the window, a new sample, which redraws only when it + /// changes the drop target. Runs even while the window is covered, as queued input does. + pub(in crate::window) fn flush_files(&mut self, event_loop: &ActiveEventLoop) { + #[cfg(target_os = "macos")] + let native = self.win.as_ref().map(|l| crate::platform::macos::drop::take(&l.window)).unwrap_or_default(); + #[cfg(target_os = "windows")] + let native = self.win.as_ref().map(|l| crate::platform::win32::drop_target::take(&l.window)).unwrap_or_default(); + #[cfg(not(any(target_os = "macos", target_os = "windows")))] + let native: Vec<FileStep> = Vec::new(); + let Some(l) = self.win.as_ref().filter(|_| self.life.shown()) else { + self.files = FileDrop::default(); + return; + }; + let f = &mut self.files; + let rt = self.app.rt_mut(); + let zoom = rt.zoom(); + let view_at = |(x, y): (f32, f32)| (x / zoom, y / zoom); + let mut queued = false; + // Native drop targets (AppKit, Win32 OLE) report each step in window points; winit's + // fallback events omit the position, so the host samples the pointer for them. + for step in native.into_iter().chain(std::mem::take(&mut f.steps)) { + queued |= match step { + FileStep::Enter(paths, Some(p)) => { rt.drag_files(paths, Some(view_at(p))); true } + FileStep::Enter(paths, None) => { + let pointer = crate::input::drop_pointer::DropPointer::new(); + f.at = pointer.sample(&l.window, zoom).or_else(|| rt.pointer()); + f.pointer = Some(pointer); + rt.drag_files(paths, f.at); + true + } + FileStep::Move(p) => rt.drag_files_to(Some(view_at(p))), + FileStep::Drop(paths, Some(p)) => { rt.drop_files(paths, Some(view_at(p))); true } + FileStep::Drop(paths, None) => { + // A drop with no drag before it (Windows' WM_DROPFILES) samples too. + let pointer = f.pointer.take().unwrap_or_else(crate::input::drop_pointer::DropPointer::new); + let at = pointer.sample(&l.window, zoom).or(f.at.take()).or_else(|| rt.pointer()); + rt.drop_files(paths, at); + true + } + FileStep::Leave => { + f.pointer = None; + f.at = None; + rt.drag_files_leave(); + true + } + }; + } + // Sampled even when still, which also notices a target that unmounted under the drag. + if !queued && let Some(at) = f.pointer.as_ref().and_then(|p| p.sample(&l.window, zoom)) { + f.at = Some(at); + queued = rt.drag_files_to(Some(at)); + } + if !queued { return; } + if !self.life.covered() && !l.minimized() { l.request_redraw(); } else { + self.covered_frame(); + self.shell(event_loop); + } + } + + pub(in crate::window) fn handle_user_event(&mut self, event_loop: &ActiveEventLoop, event: WakeEvent) { + if !self.started { return; } + // The display tick a timer's frame waits for draws that frame. + if !matches!(event, WakeEvent::DisplayTick(_)) && let Some(w) = &mut self.win { w.timer_frame.no_longer_quiet(); } + if !matches!(event, WakeEvent::DisplayTick(_) | WakeEvent::FrameSlot(_)) && let Some(w) = &mut self.win { w.loop_frame.touched(); } + match event { + WakeEvent::App(_) => { + self.app_woken.store(false, Ordering::Relaxed); + self.drain(event_loop, true); + } + WakeEvent::DisplayTick(_) => { + if self.win.as_ref().is_some_and(Win::paced) { + self.redraw(); + self.shell(event_loop); + } + } + WakeEvent::Live(_) => { + if self.app.rt().live_pending() && let Some(w) = self.win.as_ref().filter(|_| self.life.uncovered()) { + w.request_redraw(); + } + } + WakeEvent::Window(_, request) => { + self.window_request(event_loop, request); + self.shell(event_loop); + } + WakeEvent::Focus(_) => self.focus(event_loop), + WakeEvent::Position(_, position) => self.set_position(event_loop, position), + WakeEvent::Place(_, place) => self.place(event_loop, place), + WakeEvent::Level(_, on) => self.set_always_on_top(event_loop, on), + WakeEvent::Frame(_, mut request) => { + let rt = self.app.rt_mut(); + request.spring = (request.animate && !rt.reduced_motion).then_some(crate::tok::motion::DEFAULT); + rt.host.window_frame = Some(rt.host.window_frame.unwrap_or_default().merge(request)); + if let Some(w) = self.shown_win() { w.request_redraw(); } + self.shell(event_loop); + } + WakeEvent::A11y(_) => self.a11y_receive(), + #[cfg(target_os = "windows")] + WakeEvent::FrameSlot(_) => { + // The frame that waited for room in the swap chain draws now, after the input + // that came meanwhile. + if let Some(w) = &mut self.win && w.native.slot.waiting() { + w.native.slot.came_back(); + w.request_redraw(); + } + } + #[cfg(not(target_os = "windows"))] + WakeEvent::FrameSlot(_) => {} + #[cfg(target_os = "windows")] + WakeEvent::GpuReady(_) => self.gpu_ready(), + #[cfg(not(target_os = "windows"))] + WakeEvent::GpuReady(_) => {} + WakeEvent::Reopen | WakeEvent::Turn | WakeEvent::Quit(_) => {} + } + } + + /// Runs what assistive clients asked; an action draws the frame that runs it. + fn a11y_receive(&mut self) { + let Some(w) = self.win.as_mut() else { return }; + let Some(adapter) = w.a11y.as_mut() else { return }; + if adapter.receive_core(self.app.rt_mut(), self.geometry.title) { w.request_redraw(); } + } + + /// Sends the tree's changes at the end of the turn, after its frames. + pub(in crate::window) fn a11y_turn(&mut self) { + let Some(adapter) = self.win.as_mut().and_then(|w| w.a11y.as_mut()) else { return }; + adapter.sync_core(self.app.rt_mut()); + } + + /// The window's focus and place, which the accessibility adapter reports. + fn a11y_window_event(&mut self, event: &WindowEvent) { + let Some(w) = self.win.as_mut() else { return }; + let Some(adapter) = w.a11y.as_mut() else { return }; + match event { + WindowEvent::Focused(focused) => adapter.focus(*focused), + WindowEvent::Moved(_) | WindowEvent::Resized(_) => { + let rect = |p: winit::dpi::PhysicalPosition<i32>, s: winit::dpi::PhysicalSize<u32>| [f64::from(p.x), f64::from(p.y), f64::from(s.width), f64::from(s.height)]; + let (Ok(outer), Ok(inner)) = (w.window.outer_position(), w.window.inner_position()) else { return }; + adapter.bounds(rect(outer, w.window.outer_size()), rect(inner, w.window.inner_size())); + } + _ => {} + } + } + + pub(in crate::window) fn handle_window_event(&mut self, event_loop: &ActiveEventLoop, id: WindowId, event: WindowEvent) { + if self.win.as_ref().is_none_or(|w| w.window.id() != id) { + return; + } + self.a11y_window_event(&event); + // What says whether other windows cover it (`look`): the pointer reaching it shows some + // of it; its own move, size or focus makes the next frame look. + #[cfg(target_os = "windows")] + match &event { + WindowEvent::CursorMoved { .. } | WindowEvent::CursorEntered { .. } | WindowEvent::MouseInput { .. } | WindowEvent::MouseWheel { .. } => self.sighted(), + WindowEvent::Focused(true) | WindowEvent::Moved(_) | WindowEvent::Resized(_) | WindowEvent::ScaleFactorChanged { .. } => self.look_stale(), + _ => {} + } + if !matches!(event, WindowEvent::RedrawRequested) && let Some(w) = &mut self.win { + w.timer_frame.no_longer_quiet(); + w.loop_frame.touched(); + } + #[cfg(target_os = "macos")] + if matches!(event, WindowEvent::Moved(_) | WindowEvent::Resized(_) | WindowEvent::ScaleFactorChanged { .. } | WindowEvent::Occluded(_)) + && let Some(w) = &mut self.win && let Some(pacing) = &mut w.native.pacing { + pacing.update_display(&w.window); + } + if matches!(&event, WindowEvent::ScaleFactorChanged { .. }) { self.apply_placement(event_loop); } + match event { + WindowEvent::Focused(focused) => { + // winit queues an initial false from its hidden source window before + // adoption. It must not dismiss an already-key panel on first open. + #[cfg(target_os = "macos")] + let stale = self.win.as_ref().and_then(|w| w.native.panel.as_ref()).is_some_and(|p| p.is_key() != focused); + #[cfg(not(target_os = "macos"))] + let stale = false; + // Before any return below: a window that goes to the background (deactivated, + // hidden or another window made key) must not keep blocking other apps' keys. + if !stale { self.secure_input.window_focus(focused); } + if self.launcher() && self.win.as_ref().is_some_and(|w| !w.first_frame.notified()) { return; } + if stale { return; } + #[cfg(all(feature = "native-file-dialog", target_os = "linux"))] + if let Some(w) = &self.win { crate::file_dialog::window_focus(&w.window, focused && self.life.shown()); } + // Deliver independently of drawable availability, including hide/occlusion. + self.app.window_focus(focused); + // The key window's App takes the menu bar, so its items act in this window. + if focused { self.menus.claim(); } + self.shell(event_loop); + if self.life.finished() || self.win.is_none() { return; } + } + WindowEvent::CloseRequested => { + self.close(event_loop); + return; + } + WindowEvent::HoveredFile(path) => { self.files.file(path, false); return; } + WindowEvent::DroppedFile(path) => { self.files.file(path, true); return; } + WindowEvent::HoveredFileCancelled => { self.files.steps.push(FileStep::Leave); return; } + WindowEvent::RedrawRequested => { + self.paint(event_loop); + return; + } + _ => {} + } + // Occluded or minimised mid-move: land, so the window comes back at its new size. + let stops = match &event { + WindowEvent::Occluded(occluded) => *occluded && !(self.macos_window.launcher && cfg!(target_os = "macos")), + WindowEvent::Resized(size) => size.width == 0 || size.height == 0, + _ => false, + }; + if stops { self.land_frame(); } + // Minimised on Windows, where no occlusion event need say so. + if matches!(event, WindowEvent::Resized(size) if size.width == 0 || size.height == 0) { self.rest_step(RestEvent::Unseen); } + if let WindowEvent::Occluded(occluded) = event { + // Alpha-zero launcher panels remain renderable on explicit invalidation. + // Their native occlusion transitions must not settle or redraw a reveal. + if !(self.macos_window.launcher && cfg!(target_os = "macos")) { self.set_cover(Cover::System, occluded); } + return; + } + if matches!(event, WindowEvent::Moved(_) | WindowEvent::ScaleFactorChanged { .. }) { self.sync_origin(); } + // A window the CPU renderer draws has no GPU yet; its input goes on all the same. + let Some(l) = self.win.as_mut() else { return }; + let gpu = self.gpu.as_ref().map(|(gpu, _)| &**gpu); + let app = &mut *self.app; + let scale = l.window.scale_factor() as f32; + let (chrome, titlebar) = (self.chrome, self.titlebar); + // A finger presses through `WindowEvent::Touch`; the mouse events a system makes up + // from it (Windows promotes touches) would press a second time. + if matches!(event, WindowEvent::CursorMoved { .. } | WindowEvent::CursorLeft { .. } | WindowEvent::MouseInput { .. }) + && (app.rt().touching() || host_events::touch_promoted()) { return; } + match event { + WindowEvent::Moved(_) => { + // winit queues `ScaleFactorChanged` in `kCFRunLoopDefaultMode`, which waits + // until a window drag ends; resize the surface now when a drag crosses displays + // so top-left gravity never shows the old scale's drawable at half or double size. + if (scale - app.rt().window_scale()).abs() > f32::EPSILON { + let size = l.window.inner_size(); + if size.width > 0 && size.height > 0 { + l.resize_surface(gpu, size); + let rt = app.rt_mut(); + rt.set_viewport((size.width as f32 / scale, size.height as f32 / scale), scale); + sync_chrome_core(rt, l, chrome, titlebar); + l.request_redraw(); + } + } + } + WindowEvent::Resized(size) => { + sync_chrome_core(app.rt_mut(), l, chrome, titlebar); + let was_live = app.rt().live_visible(); + let now_live = self.life.uncovered() && size.width > 0 && size.height > 0 && !l.minimized(); + app.set_live_visible(now_live); + // Restored where no occlusion event says so (Windows): as uncovering does, the + // first frame paints the settled state of what changed meanwhile. + let restored = !was_live && app.rt().live_visible(); + if restored { app.rt_mut().settle_all(); } + if size.width == 0 || size.height == 0 { + self.secure_input.set(false); + l.stop_pacing(); + l.presented = None; + app.rt_mut().cancel_timer_frame(); + self.idle = true; return; + } + let origin_moved = sync_screen_origin_core(app.rt_mut(), &l.window); + // A frame Rune moved itself has its drawable and viewport already. + let resized = l.resize_surface(gpu, size); + let viewport = (size.width as f32 / scale, size.height as f32 / scale); + if !resized && viewport == app.rt().window_viewport() && scale == app.rt().window_scale() { + if restored || origin_moved { l.request_redraw(); } + return; + } + let asked = FrameMove::take_jump(&mut self.frame_move, viewport); + if asked { app.rt_mut().step_viewport(viewport, scale) } else { app.rt_mut().set_viewport(viewport, scale) } + // The user is dragging the edge. AppKit commits the new size when this returns, + // and a frame drawn later would leave the old one stretched to it until then. + #[cfg(target_os = "macos")] + if crate::platform::macos::in_live_resize(&l.window) { + if FrameMove::take_moving(&mut self.frame_move).is_some() { l.present_with_transaction(false); } + self.draw(true); + self.shell(event_loop); + return; + } + // Windows sizes the window in its own loop and shows the new size at once: the + // swap chain just took it, so a frame drawn later would leave the old pixels + // stretched over it until then. + #[cfg(target_os = "windows")] + if crate::platform::win32::in_size_move(&l.window) { + self.draw(true); + self.shell(event_loop); + return; + } + l.request_redraw(); + } + WindowEvent::ScaleFactorChanged { scale_factor, .. } => { + #[cfg(target_os = "macos")] + if let Some(shadow) = &l.native.shadow { shadow.redraw(); } + let scale = scale_factor as f32; + let size = l.window.inner_size(); + // Still the old scale's size: Windows resizes the window after this event. + #[cfg(target_os = "windows")] + let size = { + let (width, height) = crate::window::frame::rescaled((size.width, size.height), f64::from(app.rt().window_scale()), scale_factor); + winit::dpi::PhysicalSize::new(width, height) + }; + if size.width > 0 && size.height > 0 { + let resized = l.resize_surface(gpu, size); + let viewport = (size.width as f32 / scale, size.height as f32 / scale); + let rt = app.rt_mut(); + if resized || viewport != rt.window_viewport() || scale != rt.window_scale() { + rt.set_viewport(viewport, scale); + sync_chrome_core(rt, l, chrome, titlebar); + l.request_redraw(); + } + } + } + WindowEvent::ThemeChanged(theme) => { + if self.args.theme.is_none() { + app.rt_mut().set_system_dark(theme == Theme::Dark); + l.request_redraw(); + } + } + WindowEvent::ModifiersChanged(m) => { + if app.modifiers(&mut self.mods, m.state()) { + l.request_redraw(); + } + } + WindowEvent::Focused(focused) => { + let rt = app.rt_mut(); + host_events::refresh_focus_preferences(rt, self.args.scroll_bars); + self.secure_input.set(focused && self.life.uncovered() && rt.has_secure_focus()); + sync_chrome_core(rt, l, chrome, titlebar); + if !focused { + // `window_focus` wrote the composition into its field: the input method drops its copy. + crate::platform::ime::cancel(&l.window); + l.window.set_ime_allowed(false); + self.ime_allowed = false; + // A minimized or occluded window skips redraw. + l.apply_cursor_core(rt, false); + } else if rt.stale() { + rt.edit.ime_reset = true; + } else { + let ime_allowed = rt.ime_area.is_some() && !rt.has_secure_focus(); + if std::mem::take(&mut rt.edit.ime_reset) || ime_allowed != self.ime_allowed { + l.window.set_ime_allowed(false); + l.window.set_ime_allowed(ime_allowed); + self.ime_allowed = ime_allowed; + } + if let Some(a) = rt.ime_area.map(|a| rt.to_window(a)) { + l.window.set_ime_cursor_area( + LogicalPosition::new(a[0] as f64, a[1] as f64), + LogicalSize::new(a[2] as f64, a[3] as f64), + ); + } + l.apply_cursor_core(rt, true); + } + if rt.stale() { l.request_redraw(); } + } + WindowEvent::KeyboardInput { event, is_synthetic: false, .. } => { + let pressed = event.state == ElementState::Pressed; + if pressed { crate::marks::input_arrived(true); } + // A menu item handing Rune its key: it acts after, if no handler takes it. So does + // the window menu's Alt+Space, posted rather than run inside the key's message. + let logical = pressed.then(|| map_key_event(&event, self.mods)).flatten(); + let unhandled = crate::native_menu::take_unhandled(logical.as_ref()).or_else(|| { + logical.as_ref().filter(|ev| ev.is_window_menu_chord() && chrome::has_window_menu(&l.window)) + .map(|_| crate::runtime::Unhandled::WindowMenu) + }); + if app.keyboard(&self.clipboard, &event, self.mods, unhandled) { + l.request_redraw(); + } + } + WindowEvent::Ime(ime) => { + host_events::ime(app.rt_mut(), &l.window, ime); + l.request_redraw(); + } + WindowEvent::MouseWheel { delta, phase, .. } => { + host_events::wheel(app.rt_mut(), delta, gesture_phase(phase), scale, self.mods); + l.request_redraw(); + } + WindowEvent::PinchGesture { delta, phase, .. } => { + if host_events::magnify(app.rt_mut(), delta, gesture_phase(phase)) { + l.request_redraw(); + } + } + WindowEvent::RotationGesture { delta, phase, .. } => { + if host_events::rotate(app.rt_mut(), delta, gesture_phase(phase)) { + l.request_redraw(); + } + } + WindowEvent::DoubleTapGesture { .. } => { + if host_events::smart_magnify(app.rt_mut()) { + l.request_redraw(); + } + } + WindowEvent::CursorMoved { position, .. } => { + let input_scale = app.rt().input_scale(); + app.pointer_move(position.x as f32 / input_scale, position.y as f32 / input_scale); + // AppKit needs the drag session started inside this mouse-dragged event. + if let Some(start) = app.rt_mut().take_drag_out() { + let rt = app.rt(); + let image = self.gpu.as_ref().filter(|_| start.item.drag_image().is_none()).and_then(|(gpu, renderer)| + crate::drag_out::snapshot(gpu, renderer, (l.config.width, l.config.height), scale, rt.clear_color(), start.rect)); + let (sink, path) = (rt.drag_end_sink(), start.path.clone()); + let handle = self.native_handle.clone(); + crate::drag_out::begin(&l.window, start, image, Box::new(move |outcome| { + sink.borrow_mut().push((path, outcome)); + handle.send(WakeEvent::App); + })); + l.apply_cursor_core(rt, false); + } + l.request_redraw(); + } + WindowEvent::CursorLeft { .. } => { + app.rt_mut().pointer_leave(); + l.request_redraw(); + } + WindowEvent::Touch(touch) => { + app.touch(&touch); + l.request_redraw(); + } + WindowEvent::MouseInput { state, button: MouseButton::Left, .. } => { + if state == ElementState::Pressed { + crate::marks::input_arrived(false); + self.control_click = cfg!(target_os = "macos") && self.mods.control_key(); + } + if let Some((x, y)) = button_at(app, &l.window) { + match (state, self.control_click) { + (ElementState::Pressed, true) => app.rt_mut().secondary_down(x, y), + (ElementState::Released, true) => app.secondary_up(x, y), + (ElementState::Pressed, false) => { + #[cfg(target_os = "macos")] + app.rt_mut().set_native_titlebar_band(mac::native_titlebar_band(&l.window)); + app.pointer_down(x, y); + crate::marks::input_handled(false); + app.rt_mut().physical_input(crate::PhysicalInput::Modifiers(map_mods(self.mods))); + // AppKit needs the drag started inside this mouse-down. + match app.rt_mut().take_titlebar_action() { + Some(TitlebarAction::Drag) => { + l.window.drag_window().ok(); + } + Some(TitlebarAction::DoubleClick) => titlebar_double_click(&l.window), + None => {} + } + } + (ElementState::Released, false) => app.pointer_up(x, y), + } + } + if state == ElementState::Released { self.control_click = false; } + l.request_redraw(); + } + WindowEvent::MouseInput { state, button: MouseButton::Right, .. } => { + if let Some((x, y)) = button_at(app, &l.window) { + match state { + ElementState::Pressed => app.rt_mut().secondary_down(x, y), + ElementState::Released => { + app.secondary_up(x, y); + // At the pointer, while it's still where the click was. + let rt = app.rt_mut(); + if let Some(menu) = rt.take_window_menu() { chrome::window_menu(&l.window, menu, Some((x * rt.zoom(), y * rt.zoom()))); } + } + } + } + l.request_redraw(); + } + WindowEvent::MouseInput { state, button, .. } => { + if let Some((x, y)) = button_at(app, &l.window) { + match state { + ElementState::Pressed => app.button_down(x, y, pointer_button(button)), + ElementState::Released => app.button_up(x, y, pointer_button(button)), + } + } + l.request_redraw(); + } + _ => {} + } + } +} + +/// Runs the updates queued before launch with `run`, as the host `shortcuts` guards, as every +/// later drain does, so an activation queued before launch runs in its place among them. +pub(in crate::window) fn startup_updates<S: 'static>(shared: &Shared<S>, shortcuts: &crate::shortcuts::Guard, run: impl FnMut(crate::app::Update<S>)) { + let _receiving = shortcuts.receiving(); + shared.take_updates().into_iter().for_each(run); +} + +/// Where a mouse button acts. On Windows, the point its message carries +/// (`platform::win32::press_point`). Elsewhere, where the runtime last saw the pointer, else +/// where the system says it is: a menu that took the mouse (`release_pointer_for_popup`) leaves +/// the runtime no pointer, and winit reports no move for a cursor that hasn't moved since, so a +/// click at the same spot after the menu closes would otherwise be lost. The pointer moves +/// there first, so hover is under it as the press lands. +fn button_at(app: &mut dyn WindowApp, window: &Window) -> Option<(f32, f32)> { + #[cfg(target_os = "windows")] + if let Some((x, y)) = crate::platform::win32::press_point::current(window) { + let input_scale = app.rt().input_scale(); + let at = (x as f32 / input_scale, y as f32 / input_scale); + if app.rt().pointer() != Some(at) { app.pointer_move(at.0, at.1); } + return Some(at); + } + if let Some(at) = app.rt().pointer() { return Some(at); } + let (x, y) = crate::input::drop_pointer::DropPointer::new().sample(window, app.rt().zoom())?; + app.pointer_move(x, y); + Some((x, y)) +} + +impl Host { + /// The system's paint (`RedrawRequested`), or one the loop runs for a window whose paint + /// the system keeps putting off (`Redraw`). + pub(in crate::window) fn paint(&mut self, event_loop: &ActiveEventLoop) { + // The frame a due timer asked for drew, or ran covered in `draw`. + if let Some(l) = &mut self.win { l.timer_frame.drawn(); } + // AppKit paints off its own display link; elsewhere a paint holds what it asks for. + #[cfg(not(target_os = "macos"))] + if let Some(l) = &self.win { l.redraw_step(RedrawEvent::Paint); } + // A new accent, scroller style or light/dark preference asks every window to redraw. + { + let rt = self.app.rt_mut(); + rt.set_system_accent(crate::system_accent()); + rt.set_system_scroll_bars_state(crate::platform::scroll_bars::current().with_override(self.args.scroll_bars)); + if self.args.theme.is_none() && let Some(dark) = self.win.as_ref().and_then(|l| crate::platform::preferences::desktop_dark(&l.window)) { + rt.set_system_dark(dark); + } + } + #[cfg(target_os = "macos")] + if let Some(l) = self.win.as_ref().filter(|l| l.native.full_screen.take()) { + sync_chrome_core(self.app.rt_mut(), l, self.chrome, self.titlebar); + } + // The window procedure asks for this paint when a caption button's hover or + // press changes. + #[cfg(target_os = "windows")] + if let Some(l) = &self.win { sync_chrome_core(self.app.rt_mut(), l, self.chrome, self.titlebar); } + self.redraw(); + self.shell(event_loop); + // What asked for a frame while it painted waits for the turn's end. + #[cfg(not(target_os = "macos"))] + if let Some(l) = &self.win { l.redraw_step(RedrawEvent::Painted); } + } +} diff --git a/app/vendor/rune/crates/rune/src/window/host/frame_move_tests.rs b/app/vendor/rune/crates/rune/src/window/host/frame_move_tests.rs new file mode 100644 index 0000000..3ca2bf5 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/window/host/frame_move_tests.rs @@ -0,0 +1,174 @@ +//! A frame jump is one coupon inside `FrameMove`: the content size a resize request jumps to, +//! spent by the one `Resized` it causes, never read as motion, and never left for a later move. +//! The reference keeps the two fields this replaced apart exactly as dev had them. + +use super::stepping::FrameMove; +use crate::window::frame::FrameAnim; + +/// The anim a walk's `Animate` requests start, and the origin it is taken from. +fn animation() -> FrameAnim { + FrameAnim::new(None, 0.0, [10.0, 20.0, 300.0, 200.0], [0.0; 4], [30.0, 40.0, 300.0, 200.0]) +} +const ORIGIN: [f32; 2] = [10.0, 20.0]; +const JUMP: (f32, f32) = (300.0, 200.0); +const OTHER_JUMP: (f32, f32) = (420.0, 260.0); +/// The viewport `JUMP` announces, one within the pixel the window rounds by, and a user's. +const HIS: (f32, f32) = (300.0, 200.0); +const NEAR: (f32, f32) = (300.9, 200.9); +const USER: (f32, f32) = (7.0, 7.0); + +/// What a step leaves to be seen: whether the frame animates (draw scheduling counts that as +/// motion), and whether the `Resized` says this window asked for the size. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +struct Observed { + moving: bool, + asked: bool, +} + +/// The events that start, spend or end a frame move, as the host feeds them. +#[derive(Clone, Copy, Debug)] +enum Step { + /// `take_frame_request` where macOS paints the move. + Animate, + /// `take_frame_request` where the frame is set at once. + Cancel, + /// `take_frame_request` elsewhere, with a size the frame jumps to. + Jump((f32, f32)), + /// `WindowEvent::Resized`, laid out at this viewport. + Resized((f32, f32)), + /// `land_frame`: a window that stops painting mid-move. + Land, +} + +/// The host's own writes, one event at a time. +fn feed(slot: &mut Option<FrameMove>, step: Step) -> Observed { + let asked = match step { + Step::Animate => { + *slot = Some(FrameMove::animating(animation(), ORIGIN)); + false + } + Step::Cancel => { + *slot = None; + false + } + Step::Jump(size) => { + *slot = Some(FrameMove::jumped(size)); + false + } + Step::Resized(viewport) => FrameMove::take_jump(slot, viewport), + Step::Land => { + FrameMove::take_moving(slot); + false + } + }; + Observed { moving: FrameMove::moving(slot), asked } +} + +/// The fields this replaced, kept apart exactly as they were: `Host::frame_move` (its anim and +/// origin don't change here, so only its presence shows) and the loose `Host::frame_jump` beside +/// it. The branches are dev's, copied literally, so a change to the branch can't move both sides. +#[derive(Clone, Copy, Debug, Default)] +struct Apart { + frame_move: Option<()>, + frame_jump: Option<(f32, f32)>, +} + +impl Apart { + fn step(&mut self, step: Step) -> Observed { + let mut asked = false; + match step { + // take_frame_request, painting: `self.frame_move = Some(FrameMove { anim, origin })`. + Step::Animate => self.frame_move = Some(()), + // take_frame_request, not painting: `self.frame_move = None`, and the frame is set. + Step::Cancel => self.frame_move = None, + // take_frame_request, elsewhere: `self.frame_jump = Some((width, height))`. + Step::Jump(size) => self.frame_jump = Some(size), + // WindowEvent::Resized: `frame_jump.take().is_some_and(|(w, h)| …)`. + Step::Resized(viewport) => { + asked = self.frame_jump.take().is_some_and(|(w, h)| (w - viewport.0).abs() < 1.0 && (h - viewport.1).abs() < 1.0); + } + // land_frame: `frame_move.take()`, which leaves the loose jump alone. + Step::Land => self.frame_move = None, + } + Observed { moving: self.frame_move.is_some(), asked } + } +} + +fn every_sequence(alphabet: &[Step], max: usize, mut f: impl FnMut(&[Step])) { + fn walk(alphabet: &[Step], seq: &mut Vec<Step>, max: usize, f: &mut impl FnMut(&[Step])) { + f(seq); + if seq.len() == max { return; } + for step in alphabet { + seq.push(*step); + walk(alphabet, seq, max, f); + seq.pop(); + } + } + walk(alphabet, &mut Vec::new(), max, &mut f); +} + +/// Both sides fed every sequence, compared after every event: what the window sees (motion and +/// whether it asked for the size) and what the move holds. +fn holds_up(seq: &[Step]) { + let (mut slot, mut apart) = (None, Apart::default()); + for (k, step) in seq.iter().enumerate() { + let seen = feed(&mut slot, *step); + let expected = apart.step(*step); + assert_eq!(seen, expected, "{seq:?} at {k}"); + // A platform's events never leave both of dev's fields set; the one value can't hold both. + assert!(!(apart.frame_move.is_some() && apart.frame_jump.is_some()), "{seq:?} at {k}"); + let left = match (apart.frame_move, apart.frame_jump) { + (Some(()), _) => Some(FrameMove::animating(animation(), ORIGIN)), + (None, Some(size)) => Some(FrameMove::jumped(size)), + (None, None) => None, + }; + assert_eq!(slot, left, "the move after {seq:?} at {k}"); + } +} + +/// A jump request, its `Resized` and a landing in every order: the coupon is spent by exactly +/// the event it announced, once, and is never motion. +#[test] +fn every_order_of_jumps_spends_one_coupon() { + let all = [Step::Jump(JUMP), Step::Jump(OTHER_JUMP), Step::Resized(HIS), Step::Resized(NEAR), Step::Resized(USER), Step::Land]; + every_sequence(&all, 6, holds_up); +} + +/// macOS's moving frames and their cancels in every order with the events that arrive beside +/// them: each sequence leaves the frame moving or still as dev did. +#[test] +fn every_order_of_animations_leaves_the_same_frame_moving() { + let all = [Step::Animate, Step::Cancel, Step::Resized(HIS), Step::Land]; + every_sequence(&all, 7, holds_up); +} + +/// The coupon's rules, named. +#[test] +fn a_jump_is_spent_by_the_resize_it_announced_once() { + let mut slot = None; + assert!(!feed(&mut slot, Step::Resized(HIS)).asked, "no request, no coupon"); + let requested = feed(&mut slot, Step::Jump(JUMP)); + assert!(!requested.moving, "a jump names one event, it isn't motion"); + assert!(!feed(&mut slot, Step::Resized(USER)).asked, "another size is the user's"); + assert!(!feed(&mut slot, Step::Resized(HIS)).asked, "and the coupon is spent, so it's the user's too"); + feed(&mut slot, Step::Jump(JUMP)); + assert!(feed(&mut slot, Step::Resized(HIS)).asked, "its own size lays out as a step"); + assert!(!feed(&mut slot, Step::Resized(HIS)).asked, "once"); +} + +/// A later request replaces the coupon, a landing leaves it, and an animation moving beside it +/// is never read as the jump. +#[test] +fn a_later_request_or_landing_keeps_the_rules() { + let mut slot = None; + feed(&mut slot, Step::Jump(JUMP)); + feed(&mut slot, Step::Jump(OTHER_JUMP)); + assert!(!feed(&mut slot, Step::Resized(HIS)).asked, "the earlier size is gone"); + feed(&mut slot, Step::Jump(JUMP)); + feed(&mut slot, Step::Land); + assert!(feed(&mut slot, Step::Resized(HIS)).asked, "a landing mid-move leaves the coupon for its Resized"); + assert!(feed(&mut slot, Step::Animate).moving, "an animation is motion"); + feed(&mut slot, Step::Animate); + assert!(feed(&mut slot, Step::Resized(HIS)).moving, "and no Resized spends it"); + assert!(!feed(&mut slot, Step::Land).moving, "landing stops it"); +} diff --git a/app/vendor/rune/crates/rune/src/window/host/lifecycle.rs b/app/vendor/rune/crates/rune/src/window/host/lifecycle.rs new file mode 100644 index 0000000..e0dbafc --- /dev/null +++ b/app/vendor/rune/crates/rune/src/window/host/lifecycle.rs @@ -0,0 +1,564 @@ +//! A window's lifecycle: requests from other threads, showing, focusing, draining updates, +//! polling while hidden, closing, hiding, opening, creating, sight cover transitions and rest. + +use std::sync::atomic::Ordering; + +use winit::dpi::PhysicalPosition; +use winit::event_loop::ActiveEventLoop; +use winit::keyboard::ModifiersState; +use winit::window::WindowLevel; + +use super::Host; +use crate::app::{Activation, WindowRequest}; +use crate::el::Shell; +use crate::window::chrome::{self, sync_chrome_core}; +use crate::window::file_drop::FileDrop; +use crate::window::handle::native_window_number; +use crate::window::is_wayland; +use crate::window::state::minimize::{HiddenPoll, shell_take_core}; +use crate::window::state::{ + Cover, Found, Life, MinimizeEvent, RestEffect, RestEvent, Reveal, RevealEffect, WakeFacts, + WakeWork, rest, +}; +use crate::window::surface::{BackoffEvent, Win}; +#[cfg(target_os = "windows")] +use crate::window::win32::covered_draw::CoveredDrawEvent; + +impl Host { + pub(in crate::window) fn window_request(&mut self, event_loop: &ActiveEventLoop, request: WindowRequest) { + match request { + WindowRequest::Open(token) => self.open(event_loop, token), + WindowRequest::Show => self.show(event_loop), + WindowRequest::Hide => self.hide(event_loop), + WindowRequest::Close => self.close(event_loop), + } + } + + pub(in crate::window) fn set_position(&mut self, event_loop: &ActiveEventLoop, position: (i32, i32)) { + self.placement = None; + self.options.position = Some(position); + if !is_wayland(event_loop) && let Some(w) = &self.win { + w.window.set_outer_position(PhysicalPosition::new(position.0, position.1)); + } + self.sync_origin(); + } + + pub(in crate::window) fn set_always_on_top(&mut self, event_loop: &ActiveEventLoop, on: bool) { + self.options.always_on_top = on; + self.macos_window.level = None; + if !is_wayland(event_loop) && let Some(w) = &self.win { + w.window.set_window_level(if on { WindowLevel::AlwaysOnTop } else { WindowLevel::Normal }); + } + } + + pub(in crate::window) fn show(&mut self, event_loop: &ActiveEventLoop) { + if self.launcher() { self.reveal_launcher(event_loop); return; } + self.reveal(event_loop, Reveal::Show, None); + } + + pub(in crate::window) fn open(&mut self, event_loop: &ActiveEventLoop, token: Option<String>) { + if self.launcher() { self.reveal_launcher(event_loop); return; } + // The launcher's startup token belongs to the first window only. + let token = token.or_else(|| self.startup_token(event_loop)); + self.reveal(event_loop, Reveal::Open, token); + } + + /// The window shown, or not, so far: the shown one, and nothing while it's hidden. + pub(in crate::window) fn shown_win(&self) -> Option<&Win> { self.win.as_ref().filter(|_| self.life.shown()) } + + /// The window as a reveal finds it. + fn found(&self) -> Found { + let Some(w) = &self.win else { return Found::Missing }; + let minimized = w.window.is_minimized() == Some(true); + match self.life { + Life::Shown { sight } => Found::Shown { covered: sight.covered(), minimized }, + _ => Found::Hidden { minimized }, + } + } + + /// Brings the window on screen (`Reveal`); a window closed for good stays closed. + pub(in crate::window) fn reveal(&mut self, event_loop: &ActiveEventLoop, reveal: Reveal, mut token: Option<String>) { + if self.life.finished() { return; } + let mut built = false; + for effect in reveal.effects(self.found()) { + match effect { + RevealEffect::ReadSystem => { + let rt = self.app.rt_mut(); + rt.set_system_accent(crate::system_accent()); + rt.set_system_scroll_bars_state(crate::platform::scroll_bars::current().with_override(self.args.scroll_bars)); + } + RevealEffect::Build => built = self.build_for_show(), + RevealEffect::Place => self.apply_placement(event_loop), + RevealEffect::Create => { + // `App::open_inactive`: the first open leaves focus where it is. + let focus = reveal == Reveal::Open && !(self.open_inactive && !self.shown); + self.create(event_loop, token.take(), focus); + // On macOS a new window becomes key without activating the app, so activate + // it like a reopen does. The launch open leaves activation to the platform. + #[cfg(target_os = "macos")] + if focus && self.started && let Some(w) = self.shown_win() { w.focus(); } + } + RevealEffect::OrderIn { focus } => if let Some(w) = &self.win { w.show(focus) }, + RevealEffect::Unminimize => if let Some(w) = &self.win { w.window.set_minimized(false) }, + RevealEffect::Settle => { + if !built { self.app.rt_mut().settle_all(); } + self.idle = true; + } + RevealEffect::Shown { live } => { + self.life.show(); + self.app.set_live_visible(live); + } + RevealEffect::CancelTimerFrame => self.app.rt_mut().cancel_timer_frame(), + RevealEffect::Number => if let Some(w) = &self.win { + self.native_handle.native.number.store(native_window_number(&w.window).unwrap_or(0), Ordering::Release); + }, + RevealEffect::Focus => self.activate(event_loop, token.take()), + RevealEffect::Redraw => if let Some(w) = &self.win { w.request_redraw() }, + // No settle, frame, surface configure or acquisition on a cached reveal, unless + // the refreshed frame left motion running. + RevealEffect::RedrawIfMoving => if !self.idle && let Some(w) = &self.win { w.request_redraw() }, + } + } + } + + /// The first window's startup token (`XDG_ACTIVATION_TOKEN`, `DESKTOP_STARTUP_ID`), which + /// later windows don't inherit. + fn startup_token(&self, event_loop: &ActiveEventLoop) -> Option<String> { + #[cfg(all(unix, not(target_os = "macos"), not(target_os = "ios"), not(target_os = "android")))] + if !self.shown { + use winit::platform::startup_notify::{EventLoopExtStartupNotify, reset_activation_token_env}; + let token = event_loop.read_token_from_env().map(|t| t.into_raw()); + reset_activation_token_env(); + return token; + } + let _ = event_loop; + None + } + + /// Focuses a shown window; Wayland's compositor wants the open's token for that. + fn activate(&mut self, event_loop: &ActiveEventLoop, token: Option<String>) { + let Some(w) = self.win.as_mut() else { return }; + #[cfg(all(unix, not(target_os = "macos"), not(target_os = "ios"), not(target_os = "android")))] + if is_wayland(event_loop) { + match token { + Some(token) => { + if w.native.activator.is_none() { + w.native.activator = crate::platform::activation::Activator::new(&w.window); + } + if let Some(a) = w.native.activator.as_mut() { + a.activate(&token); + } + } + // Without a token the compositor may only mark the window urgent. + None => w.window.request_user_attention(Some(winit::window::UserAttentionType::Informational)), + } + return; + } + let _ = (event_loop, token); + w.focus(); + } + + /// A hidden or released window that fits its content builds what changed while it was + /// away and takes its new height before it is ordered in (`Runtime::build_for_show`). + /// Returns whether it built, settled. + pub(in crate::window) fn build_for_show(&mut self) -> bool { + if !self.app.build_for_show() { return false; } + self.clipboard.flush_core(self.app.rt_mut()); + self.take_frame_request(0.0, false); + // macOS sets the frame at once: the first drawable and layout take the new size. + // Elsewhere the window's `Resized` brings it. + #[cfg(target_os = "macos")] + if let (Some(w), Some((gpu, ..))) = (self.win.as_mut(), self.gpu.as_ref()) { + let size = w.window.inner_size(); + w.resize_surface(Some(&**gpu), size); + let scale = w.window.scale_factor() as f32; + self.app.rt_mut().set_viewport((size.width as f32 / scale, size.height as f32 / scale), scale); + } + true + } + + pub(in crate::window) fn focus(&self, event_loop: &ActiveEventLoop) { + let Some(w) = self.shown_win() else { return }; + if w.window.is_minimized() == Some(true) { w.window.set_minimized(false); } + if is_wayland(event_loop) { + w.window.request_user_attention(Some(winit::window::UserAttentionType::Informational)); + return; + } + w.focus(); + } + + /// Applies everything other threads asked for since the last wake-up. A `wake` polls a + /// hidden window first, so a reveal in the same turn sees what `poll` changed. + pub(in crate::window) fn drain(&mut self, event_loop: &ActiveEventLoop, wake: bool) { + let shown = self.shown_win().is_some(); + let stale_before = self.app.rt().needs_commit(); + let clipboard = self.clipboard.receive_core(self.app.rt_mut()); + let answered = self.app.popup_answer(&mut self.popup) | self.file_dialog.answer_core(self.app.rt_mut()); + let (requests, had_updates, updated) = self.app.drain_window(&self.shortcuts, &mut self.menus); + let changed = clipboard || answered || updated || self.app.rt().drag_ends_pending(); + // Only updates that changed nothing (`AppHandle::update_if`), or an empty startup drain + // after `try_create` already drew the first frame, ran: no poll, no frame. + let quiet = (had_updates || (!wake && !stale_before)) && !changed && requests.only_updates() + && !self.app.rt().patch_pending() && (stale_before || !self.app.rt().needs_commit()) && !self.app.compositor_animating(); + self.clipboard.flush_core(self.app.rt_mut()); + // The next frame polls for the wake. + if wake && !quiet { self.app.rt_mut().cancel_timer_frame(); } + if let Some(after) = requests.quit { + // Quitting from now on: a close later in this turn closes for the quit. + // `Windows::exiting` carries out its effects. + let _ = crate::quit::send(crate::quit::Event::Start { ending: false, after }); + // A tracking menu holds the event loop until it ends. + self.app.popup_cancel(&mut self.popup); + self.app.file_dialog_cancel(&mut self.file_dialog); + event_loop.exit(); + return; + } + #[cfg(target_os = "macos")] + if let Some(visible) = requests.dock { + crate::platform::macos::set_dock_icon(visible); + } + let shows = matches!(requests.window, Some(WindowRequest::Show | WindowRequest::Open(_))); + let polled = wake && !quiet && self.poll_hidden(event_loop, shows); + if let Some(position) = requests.position { self.set_position(event_loop, position); } + if let Some(place) = requests.place { self.place(event_loop, place); } + if let Some(request) = requests.window { self.window_request(event_loop, request); } + if requests.activation == Some(Activation::Focus) { self.focus(event_loop); } + // After the show it may follow; `focus` and `minimize` are last-wins (`AppHandle`). + if requests.activation == Some(Activation::Minimize) { self.app.rt_mut().minimize_step(MinimizeEvent::Asked); } + self.shell(event_loop); + // A pop-up or file dialog a quiet update asked for may have been answered at once. + let answered = quiet && ((!stale_before && self.app.rt().needs_commit()) || self.app.rt().has_pending_input()); + if quiet { self.clipboard.flush_core(self.app.rt_mut()); } + let (changed, quiet) = (changed || answered, quiet && !answered); + // A launcher's cached reveal draws nothing; a hidden one renders its changes hidden, + // paced (`refresh_hidden`). A covered or minimised one runs them without asking for a + // frame it wouldn't draw. + let work = WakeWork::of( + WakeFacts { + window: self.win.is_some(), + launcher: self.launcher(), + visible: self.life.shown(), + was_shown: shown, + changed, + quiet, + covered: self.life.covered(), + }, + || self.win.as_ref().is_some_and(Win::minimized), + ); + let framed = match work { + WakeWork::Nothing => false, + WakeWork::HiddenFrame => self.refresh_hidden(), + WakeWork::CoveredFrame => { + self.covered_frame(); + self.shell(event_loop); + true + } + WakeWork::Paint => { + if let Some(w) = &self.win { w.request_redraw(); } + true + } + }; + // Neither a poll nor a frame comes to schedule the updates' `wake_after`s. + if !polled && !framed { self.app.rt_mut().schedule_pending_wakes(); } + } + + /// A hidden, keep-running or windowless window still reads its inbox when woken: `poll` runs + /// with no drawable, present or animation, and its changes render when the window is next + /// shown. A hidden launcher renders poll's changes hidden, paced, keeping its cached frame + /// fresh. A minimize waits for a show in the same turn (`Minimize`). Returns whether it + /// polled. + pub(in crate::window) fn poll_hidden(&mut self, event_loop: &ActiveEventLoop, shows: bool) -> bool { + if event_loop.exiting() || self.shown_win().is_some() { return false; } + let changed = self.app.poll_hidden(); + self.clipboard.flush_core(self.app.rt_mut()); + // A show this turn minimizes after it: this poll holds the ask across its own shell, and + // a callback's ask during that shell is the one it takes first. + let poll = HiddenPoll::new(shows); + poll.enter_core(self.app.rt_mut()); + self.shell(event_loop); + poll.leave_core(self.app.rt_mut()); + if changed && self.launcher() { self.refresh_hidden(); } + true + } + + /// A hidden launcher renders what changed into its cached frame: at once after a quiet + /// spell, then at most every `HIDDEN_REFRESH` (`HiddenPace`). A show of state newer than + /// that frame renders it hidden first (`reveal_launcher`), as for an update in the same + /// turn. A frame being prepared, or one a reveal waits on, renders at once. Returns whether + /// it asked for a frame. + pub(in crate::window) fn refresh_hidden(&mut self) -> bool { + let now_due = self.hidden_launcher_renders(); + let Some(w) = &mut self.win else { return false }; + let render = now_due || w.first_frame.deadline().is_some() || w.hidden_pace.changed(crate::time::now()); + if render { w.request_redraw(); } + render + } + + /// What a hidden launcher's frame must render as it commits: queued input and drag ends. + /// Committed without a render, they'd leave a cached frame that looks fresh. + pub(in crate::window) fn hidden_launcher_renders(&self) -> bool { + self.app.rt().has_pending_input() || self.app.rt().drag_ends_pending() + } + + /// Carries out what a handler or update asked with `Tx::close_window` / `Tx::quit`, then + /// opens the pop-up menu it asked for, if the window is still there to open it over. + pub(in crate::window) fn shell(&mut self, event_loop: &ActiveEventLoop) { + self.show_title(); + if self.app.rt_mut().take_toggle_maximized() && let Some(w) = self.shown_win() { + chrome::toggle_maximized(&w.window); + } + if self.app.rt_mut().take_toggle_full_screen() && let Some(w) = self.shown_win() { + chrome::toggle_full_screen(&w.window); + } + if let Some(menu) = self.app.rt_mut().take_window_menu() && let Some(w) = self.shown_win() { + chrome::window_menu(&w.window, menu, None); + } + // A new `Cx::set_titlebar` or `Cx::titlebar_height` resizes the caption buttons and the band + // the frame hit-tests, and moves the traffic lights. + if self.app.rt_mut().take_titlebar_changed() && let Some(w) = &self.win { + sync_chrome_core(self.app.rt_mut(), w, self.chrome, self.titlebar); + if self.app.rt().stale() { w.request_redraw(); } + } + for _ in 0..8 { + let minimize = shell_take_core(self.app.rt_mut()); + match self.app.rt_mut().shell_request.take() { + Some(shell @ (Shell::Quit | Shell::Relaunch)) => { + let after = shell.after().unwrap_or(crate::quit::After::Exit); + let _ = crate::quit::send(crate::quit::Event::Start { ending: false, after }); + self.app.popup_cancel(&mut self.popup); + self.app.file_dialog_cancel(&mut self.file_dialog); + event_loop.exit(); + } + Some(Shell::Close) => self.close(event_loop), + None if minimize => self.minimize(), + None => {} + } + if self.life.finished() || event_loop.exiting() { + self.app.popup_cancel(&mut self.popup); + self.app.file_dialog_cancel(&mut self.file_dialog); + return; + } + let paints = self.shown_win().is_some_and(|w| !self.life.covered() && !w.minimized()); + // A painting macOS window moves its frame over its next frames (`redraw`). + if self.app.rt().host.window_frame.is_some() && !(paints && cfg!(target_os = "macos")) { + self.take_frame_request(self.frame_secs(crate::time::now()), false); + } + let shown = self.win.as_ref().filter(|_| self.life.shown()); + let window = shown.map(|w| &w.window); + if self.app.popup_open(&mut self.popup, window, paints) && let Some(w) = shown { w.request_redraw(); } + if self.file_dialog.open_core(self.app.rt_mut(), window.map(|w| &**w)) && let Some(w) = shown { w.request_redraw(); } + // A callback that ran (a menu that couldn't open) may have asked to close, quit or + // minimize. + if self.app.rt().shell_request.is_none() && !self.app.rt().host.minimize.field() { return; } + } + } + + pub(in crate::window) fn close(&mut self, event_loop: &ActiveEventLoop) { + self.app.rt_mut().minimize_step(MinimizeEvent::Lost); + if let Some(w) = &mut self.win { + w.first_frame.hide(); + #[cfg(target_os = "macos")] + { w.native.prime.stop(); } + } + self.secure_input.set(false); + if !self.closes() { return; } + crate::marks::mark("window.close"); + // The last window of an app that ends fast goes as a bare window's close does: its hook, + // then the window destroyed at once, with no hide before it. The quit runs after it and + // the process ends without dropping the window. + let ends = std::mem::take(&mut self.ends_app) && !self.keep_running && cfg!(target_os = "windows"); + // Off the screen first: the close looks done at once and `on_close` runs unseen. + if !ends && let Some(w) = self.shown_win() { w.hide(); } + crate::marks::mark("window.close.hidden"); + self.close_hook(); + crate::marks::mark("window.close.hooked"); + #[cfg(target_os = "windows")] + if ends && let Some(w) = &self.win { + crate::platform::win32::destroy_window_now(&w.window); + crate::marks::mark("window.destroyed"); + } + self.app.set_live_visible(false); + // While the window still shows its last frames. + if let Some(trace) = &mut self.trace { trace.settle_presents(crate::frame::present_time::SETTLE); } + if let Some(after) = self.app.rt_mut().shell_request.take().and_then(Shell::after) { + if after == crate::quit::After::Relaunch { + let _ = crate::quit::send(crate::quit::Event::Start { ending: false, after }); + } + self.app.popup_cancel(&mut self.popup); + self.app.file_dialog_cancel(&mut self.file_dialog); + event_loop.exit(); + return; + } + if !self.keep_running { + self.app.popup_cancel(&mut self.popup); + self.app.file_dialog_cancel(&mut self.file_dialog); + self.app.rt_mut().cancel_pointer(); + self.files = FileDrop::default(); + if !ends && let Some(w) = &mut self.win { w.apply_cursor_core(self.app.rt(), false); w.hide(); } + crate::marks::mark("window.hidden"); + self.life.finish(); + return; + } + self.hide(event_loop); + } + + /// Whether a close runs `on_close` (`Life::closes`). + pub(in crate::window) fn closes(&self) -> bool { self.life.closes(self.keep_running, self.win.is_some()) } + + pub(in crate::window) fn close_hook(&mut self) { + self.app.run_on_close(); + // Before the window hides or the app exits: a lock or clear must reach the worker. + self.clipboard.flush_core(self.app.rt_mut()); + } + + pub(in crate::window) fn hide(&mut self, event_loop: &ActiveEventLoop) { + self.rest_step(RestEvent::Unseen); + self.stop_showing(); + self.wind_down(); + let launcher = self.launcher(); + if self.release_gpu && !launcher { + self.release(); + } else if is_wayland(event_loop) { + // Wayland has no hidden toplevel: unmap by destroying, recreate on open. + self.win = None; + self.native_handle.native.ready.store(false, Ordering::Release); + self.native_handle.native.number.store(0, Ordering::Release); + } else if let Some(w) = self.win.as_mut() { + w.stop_pacing(); + w.backoff_step(BackoffEvent::Lapsed); + w.presented = None; + // Its hidden frame delivers the focus loss. + if launcher { w.request_redraw(); } + } + } + + /// What a window does just before it stops drawing: it leaves `Life` (a window that hid can + /// be reopened), drops a pending minimize, lands a frame move where it was going, and (macOS) + /// delivers the Fn key change a hide need not report. No event loop is needed, so a window + /// whose surface can't be replaced does the same before `wind_down` + /// (`Host::replace_lost_surface`). + pub(in crate::window) fn stop_showing(&mut self) { + self.life.hide(crate::platform::reopen::stamp); + self.app.rt_mut().minimize_step(MinimizeEvent::Lost); + self.land_frame(); + // Before the window can go: a hide need not report a blur. `about_to_wait` delivers it, + // after any Fn change the monitor saw first. + #[cfg(target_os = "macos")] + self.fn_key(); + } + + /// What a window stops doing when it hides: keys released, secure input and IME off, popups + /// and file dialogs cancelled, the pointer cancelled, drops dropped, modifiers reset, the + /// cursor back to normal, and the native window hidden. No event loop is needed, so a window + /// that loses its surface does the same from `draw` (`Host::replace_lost_surface`). + pub(in crate::window) fn wind_down(&mut self) { + self.app.rt_mut().keys_lost(); + if let Some(w) = &mut self.win { + w.first_frame.hide(); + #[cfg(target_os = "macos")] + { w.native.prime.stop(); } + } + self.secure_input.set(false); + self.ime_allowed = false; + if let Some(w) = &self.win { w.window.set_ime_allowed(false); } + self.app.set_live_visible(false); + self.app.rt_mut().cancel_timer_frame(); + self.app.popup_cancel(&mut self.popup); + self.app.file_dialog_cancel(&mut self.file_dialog); + self.app.rt_mut().cancel_pointer(); + self.files = FileDrop::default(); + if let Some(w) = &mut self.win { w.apply_cursor_core(self.app.rt(), false); } + self.mods = ModifiersState::empty(); + if let Some(w) = &self.win { w.hide(); } + } + + /// Gives up the window and the device and surface it drew with, as `hide` does for an app + /// that releases its GPU when closed. The next `open` makes a window, a device and a surface + /// (an app that sees `AppHandle::window_error` and the window gone can ask for one). + pub(in crate::window) fn release(&mut self) { + self.win = None; + self.native_handle.native.ready.store(false, Ordering::Release); + self.native_handle.native.number.store(0, Ordering::Release); + self.gpu = None; + let rt = self.app.rt_mut(); + rt.text.atlas.invalidate(); + rt.images.invalidate(); + } + + /// Creates the window, or records why it can't be and leaves the app windowless; a later + /// open tries again. + pub(in crate::window) fn create(&mut self, event_loop: &ActiveEventLoop, token: Option<String>, focus: bool) { + let result = self.try_create(event_loop, token, focus); + if let Err(error) = &result { + eprintln!("rune: could not create the window {}: {error}", self.native_handle.key()); + } + self.shared.set_window_error(result.err()); + } + + /// `cover` starts or stops covering the window. Covered, it stops pacing and rests, and is + /// no longer live; uncovered, its first frame paints the settled state of what changed + /// meanwhile (guarantee 8). + pub(in crate::window) fn set_cover(&mut self, cover: Cover, on: bool) { + let Some(l) = self.win.as_mut() else { return }; + #[cfg(target_os = "macos")] + { l.native.prime.stop(); } + let was = self.life.cover(cover, on); + l.backoff_step(BackoffEvent::Uncovered); + l.presented = None; + let live = self.life.uncovered() && !l.minimized(); + if self.life.covered() { + self.secure_input.set(false); + l.stop_pacing(); + self.idle = true; + self.app.set_live_visible(live); + self.app.rt_mut().cancel_timer_frame(); + self.rest_step(RestEvent::Unseen); + return; + } + // Its first frame uncovered draws what a covered one owed. + #[cfg(target_os = "windows")] + { l.covered_draw = l.covered_draw.step(CoveredDrawEvent::Drawn); } + self.app.set_live_visible(live); + let Some(l) = self.win.as_mut() else { return }; + sync_chrome_core(self.app.rt_mut(), l, self.chrome, self.titlebar); + // A window opened while the displays slept has no display link yet. + #[cfg(target_os = "macos")] + if l.native.pacing.is_none() { l.native.pacing = crate::platform::display_link::DisplayLink::new(&l.window, self.frame_wake.clone()); } + if was { + self.app.rt_mut().settle_all(); + l.request_redraw(); + } else if self.app.rt().stale() { + l.request_redraw(); + } + } + + pub(in crate::window) fn rest_step(&mut self, event: RestEvent) { + for effect in rest::step(&mut self.rest, event) { + match effect { + RestEffect::GiveBackUnused => self.give_back(false), + RestEffect::GiveBackAll => self.give_back(true), + } + } + } + + fn give_back(&mut self, all: bool) { + { + let rt = self.app.rt_mut(); + rt.text.rest(); + rt.images.rest(); + if let Some(rewind) = rt.motion.rewind() { rewind.rest(); } + } + self.app.run_on_rest(); + if let Some((gpu, renderer)) = &mut self.gpu { + renderer.give_back(all, &mut self.app.rt_mut().text.atlas.resident_caches); + // Out of sight, what the last frame used goes too, and the staging chunks: an empty + // submission and a wait land those frees now. At an idle rest the device isn't + // polled: a poll costs the next two frames' submits 4-9 ms each on an Iris Xe. + if all { + gpu.queue.submit(std::iter::empty()); + rune_gpu::health::poll(&gpu.device, wgpu::PollType::wait_indefinitely()).ok(); + renderer.trim_uploads(); + } + } + } +} diff --git a/app/vendor/rune/crates/rune/src/window/host/render.rs b/app/vendor/rune/crates/rune/src/window/host/render.rs new file mode 100644 index 0000000..7f0f276 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/window/host/render.rs @@ -0,0 +1,475 @@ +//! GPU resource preparation, Windows partial damage planning, compositor/UI encoding, +//! presentation and `frame-profile` live-log stamping for [`super::Host`]. + +#[cfg(any(target_os = "macos", feature = "frame-profile"))] +use super::stepping::FrameMove; +use super::{CompositorFrame, Host}; +use crate::frame::host_step::{RenderPrep, StepInfo, draw_ui, prepare_gpu_resources_with}; +use crate::time::Instant; +#[cfg(target_os = "windows")] +use crate::window::win32::{damage, handover}; + +/// First frame encoded mark (`crate::marks`). +static FIRST_ENCODED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + +pub(super) struct PreparedWindowFrame { + pub(super) frame: wgpu::SurfaceTexture, + pub(super) view: wgpu::TextureView, + pub(super) encoder: wgpu::CommandEncoder, + pub(super) target_format: wgpu::TextureFormat, + pub(super) size: (u32, u32), + #[cfg(target_os = "windows")] + pub(super) part: Option<Vec<[i32; 4]>>, + #[cfg(target_os = "windows")] + pub(super) present_rect: Option<Vec<[i32; 4]>>, +} + +/// Optional `frame-profile` timestamps and diagnostics carried across one window frame. +#[derive(Default)] +pub(super) struct FrameProfile { + #[cfg(feature = "frame-profile")] + pub(super) loop_why: Option<&'static str>, + #[cfg(feature = "frame-profile")] + pub(super) whole_why: Option<&'static str>, + #[cfg(feature = "frame-profile")] + pub(super) loop_check: Option<(usize, f32)>, + #[cfg(feature = "frame-profile")] + pub(super) forced_miss_checked: bool, + #[cfg(feature = "frame-profile")] + pub(super) entry: Option<crate::frame::live_log::Stamp>, + #[cfg(feature = "frame-profile")] + pub(super) start: Option<crate::frame::live_log::Stamp>, + #[cfg(feature = "frame-profile")] + pub(super) acquired: Option<crate::frame::live_log::Stamp>, + #[cfg(feature = "frame-profile")] + pub(super) built: Option<crate::frame::live_log::Stamp>, + #[cfg(feature = "frame-profile")] + pub(super) uploaded: Option<crate::frame::live_log::Stamp>, + #[cfg(feature = "frame-profile")] + pub(super) encoded: Option<crate::frame::live_log::Stamp>, + #[cfg(feature = "frame-profile")] + pub(super) submitted: Option<crate::frame::live_log::Stamp>, + #[cfg(feature = "frame-profile")] + pub(super) frame: Option<crate::frame::live_log::Frame>, +} + +impl FrameProfile { + #[inline] + pub(super) fn mark_entry(&mut self) { + #[cfg(feature = "frame-profile")] + { self.entry = crate::frame::live_log::on().then(crate::frame::live_log::Stamp::now); } + } + + #[inline] + pub(super) fn mark_start(&mut self) { + #[cfg(feature = "frame-profile")] + if self.start.is_none() { + self.start = crate::frame::live_log::on().then(crate::frame::live_log::Stamp::now); + } + } + + #[inline] + pub(super) fn mark_acquired(&mut self) { + #[cfg(feature = "frame-profile")] + if self.acquired.is_none() { + self.acquired = self.start.map(|_| crate::frame::live_log::Stamp::now()); + } + } + + #[inline] + pub(super) fn mark_built(&mut self) { + #[cfg(feature = "frame-profile")] + { self.built = self.start.map(|_| crate::frame::live_log::Stamp::now()); } + } + + #[inline] + pub(super) fn mark_uploaded(&mut self) { + #[cfg(feature = "frame-profile")] + { self.uploaded = self.start.map(|_| crate::frame::live_log::Stamp::now()); } + } + + #[inline] + pub(super) fn mark_encoded(&mut self) { + #[cfg(feature = "frame-profile")] + { self.encoded = self.start.map(|_| crate::frame::live_log::Stamp::now()); } + } + + #[inline] + pub(super) fn mark_submitted(&mut self) { + #[cfg(feature = "frame-profile")] + { self.submitted = self.start.map(|_| crate::frame::live_log::Stamp::now()); } + } + + #[inline] + pub(super) fn set_loop_why(&mut self, why: &'static str) { + #[cfg(feature = "frame-profile")] + { self.loop_why = Some(why); } + #[cfg(not(feature = "frame-profile"))] + let _ = why; + } + + #[inline] + pub(super) fn set_loop_why_if_none(&mut self, why: &'static str) { + #[cfg(feature = "frame-profile")] + if self.loop_why.is_none() { self.loop_why = Some(why); } + #[cfg(not(feature = "frame-profile"))] + let _ = why; + } + + #[inline] + pub(super) fn set_whole_why(&mut self, why: &'static str) { + #[cfg(feature = "frame-profile")] + { self.whole_why = Some(why); } + #[cfg(not(feature = "frame-profile"))] + let _ = why; + } + + #[inline] + pub(super) fn take_loop_check(&mut self, rt: &mut crate::runtime::RuntimeCore) { + #[cfg(feature = "frame-profile")] + { self.loop_check = rt.loop_checked(); } + #[cfg(not(feature = "frame-profile"))] + { let _ = rt.loop_checked(); } + } + + #[cfg(feature = "frame-profile")] + pub(super) fn build_frame( + &mut self, + host: &mut Host, + animating: bool, + looped: Option<&Vec<u32>>, + #[cfg(target_os = "windows")] + damage: Option<Vec<[i32; 4]>>, + ) { + self.frame = match (self.start, self.acquired, self.built, self.uploaded, self.encoded, self.submitted) { + (Some(start), Some(acquired), Some(built), Some(uploaded), Some(encoded), Some(submitted)) => { + let rt = host.app.rt_mut(); + Some(crate::frame::live_log::Frame { + entry: self.entry.unwrap_or(start), + start, acquired, built, uploaded, encoded, submitted, + presented: crate::frame::live_log::Stamp::now(), + phases: crate::frame::profile::take(), + nodes: rt.tree.nodes.len(), + shaped: rt.stats.shaped, + instances: rt.instances.len(), + animating, + why: rt.commit.take_commit_why(), + next: 0, + poll_due: None, + loop_due: None, + loops: Vec::new(), + #[cfg(target_os = "windows")] + damage, + #[cfg(not(target_os = "windows"))] + damage: None, + whole: self.whole_why, + #[cfg(target_os = "windows")] + change: host.win.as_ref().and_then(|l| l.native.damage.seen), + #[cfg(not(target_os = "windows"))] + change: None, + looped: looped.map(Vec::len), + loop_why: self.loop_why, + loop_check: self.loop_check.take(), + }) + } + _ => None, + }; + } + + #[inline] + pub(super) fn flush(&mut self, host: &Host, animating: bool, next_tick: Option<Instant>) { + #[cfg(feature = "frame-profile")] + if let Some(mut f) = self.frame.take() { + let rt = host.app.rt(); + f.next = [ + animating, + FrameMove::moving(&host.frame_move), + rt.needs_commit(), + rt.stale() && !rt.needs_commit(), + rt.has_pending_input(), + rt.live_pending(), + rt.host.window_frame.is_some(), + crate::window::surface::timer_wants_frame_core(rt, next_tick), + ] + .iter() + .enumerate() + .fold(0u16, |bits, (i, on)| bits | (u16::from(*on) << i)); + f.poll_due = rt.poll_wake_deadline().map(|d| d - rt.polled_at()); + f.loop_due = rt.motion_wake_deadline().map(|d| d - rt.polled_at()); + if f.loop_due.is_some() { f.loops = rt.fp_loops(); } + crate::frame::live_log::frame(f); + } + #[cfg(not(feature = "frame-profile"))] + let _ = (host, animating, next_tick); + } +} + +pub(super) fn prepare_window_render( + host: &mut Host, + drawable: wgpu::SurfaceTexture, + corners: f32, + looped: Option<&Vec<u32>>, + profile: &mut FrameProfile, + info: &mut StepInfo, +) -> RenderPrep<PreparedWindowFrame> { + let (Some(l), Some((gpu, renderer))) = (host.win.as_mut(), host.gpu.as_mut()) else { + unreachable!("window and gpu live across frame"); + }; + let target_format = if host.app.rt().srgb_blend() { l.config.format.remove_srgb_suffix() } else { l.config.format }; + let view = drawable.texture.create_view(&wgpu::TextureViewDescriptor { + format: (target_format != l.config.format).then_some(target_format), + ..Default::default() + }); + let size = (l.config.width, l.config.height); + // A client-side frame's rounded bottom corners: the content outside them is cleared off + // this drawable, right after everything else that draws there. + if corners > 0. { + crate::window::surface::corners::prepare(&mut l.corners, &gpu.device, &gpu.queue, size, target_format, corners); + } + // An image's pixels changed where its instances didn't: the whole frame draws (`damage`). + #[cfg(target_os = "windows")] + let images_changed = host.app.rt().images.pages.iter().any(|p| p.dirty.is_some()); + { + let rt = host.app.rt_mut(); + #[cfg(target_os = "windows")] + let mut layers_again = false; + prepare_gpu_resources_with(renderer, gpu, rt, size, true, |renderer, rt| { + // Playing clips on their own layer (`video_layer`): the surfaces this frame punches out. + #[cfg(target_os = "windows")] + { + let premultiplied = l.config.alpha_mode == wgpu::CompositeAlphaMode::PreMultiplied; + let punch_ready = renderer.surface_punch_ready(); + let native = &mut l.native; + let layers = native.video_layers.frame(&rt.surfaces, native.mode.handover(), premultiplied, punch_ready); + renderer.set_punched_surfaces(layers.punched); + layers_again = layers.again; + } + #[cfg(not(target_os = "windows"))] + let _ = (renderer, rt); + }); + #[cfg(target_os = "windows")] + { info.animating |= layers_again; } + #[cfg(not(target_os = "windows"))] + let _ = info; + // The paint the instances come from, and on a loop-only frame the only ones it changed. + renderer.next_instances(rt.paint_count(), looped.cloned()); + } + profile.mark_uploaded(); + let encoder = gpu.device.create_command_encoder(&Default::default()); + // Only what changed is redrawn and presented (`damage`): the renderer's `draw` takes the + // armed rectangles when nothing but the instances draws there, a compositor's + // `Frame::draw_ui` included. A loop-only frame knows what changed. + #[cfg(target_os = "windows")] + let part = { + let rt = host.app.rt(); + let whole = if l.alpha.is_some() { Some("alpha") } else if images_changed { Some("image") } + else if !l.config.usage.contains(wgpu::TextureUsages::COPY_DST) { Some("no copies") } else { None }; + // A new swap chain (`rebind_alpha`, a replaced surface, any configure: a resize, a blend + // switch, `acquire` retrying an outdated surface) draws its first frame whole, through + // `plan`, even when only a loop asked for it (the step has run; the frame draws it whole). + let swap = l.surface.as_ref().map_or(0, crate::window::surface::configure::generation); + let fresh = !l.native.damage.current(size, rt.clear_color(), swap); + if fresh && looped.is_some() { profile.set_loop_why("a new swap chain"); } + let armed = looped.map(Vec::as_slice).filter(|_| whole.is_none() && !fresh).and_then(|p| { + match renderer.arm_loop(&gpu.device, &gpu.queue, rt.paint_count(), &rt.instances, p, rt.clear_color(), size, l.config.format) { + Ok(rects) => Some((p, rects)), + Err(why) => { profile.set_loop_why(why); None } + } + }); + if let Some((p, present)) = armed { + l.native.damage.patched(&rt.instances, p); + Some(present) + } else { + match l.native.damage.plan(&rt.instances, size, rt.clear_color(), swap, whole.is_none()) { + damage::Plan::All(why) => { profile.set_whole_why(whole.unwrap_or(why)); None } + damage::Plan::Part { draw, present } => { + renderer.arm_damage(&gpu.device, &gpu.queue, &draw, rt.clear_color(), size, l.config.format); + Some(present) + } + } + } + }; + RenderPrep::Ready(PreparedWindowFrame { + frame: drawable, + view, + encoder, + target_format, + size, + #[cfg(target_os = "windows")] + part, + #[cfg(target_os = "windows")] + present_rect: None, + }) +} + +pub(super) fn render_window_frame( + host: &mut Host, + prepared: &mut PreparedWindowFrame, + corners: f32, + profile: &mut FrameProfile, + info: &StepInfo, +) -> bool { + let (Some(l), Some((gpu, renderer))) = (host.win.as_mut(), host.gpu.as_mut()) else { return false }; + let target = l.alpha.as_ref().map_or(&prepared.view, |a| &a.view); + let comp_animating = if host.app.has_compositor() { + host.app.render_compositor(CompositorFrame { + device: &gpu.device, + queue: &gpu.queue, + encoder: &mut prepared.encoder, + target, + format: prepared.target_format, + size: prepared.size, + dt: info.dt, + update_ms: info.update_ms, + ui: &mut *renderer, + }) + } else { + let rt = host.app.rt_mut(); + let clear = rt.clear_color(); + draw_ui(renderer, gpu, &mut prepared.encoder, target, rt, prepared.size, clear); + false + }; + // Every frame, so a frame drawn whole leaves the renderer's kept frame behind. + #[cfg(target_os = "windows")] + match (renderer.damage_drawn(), prepared.part.take()) { + (Ok(()), part) => prepared.present_rect = part, + (Err(why), Some(_)) => profile.set_whole_why(why), + (Err(_), None) => {} + } + // A client-side frame's rounded bottom corners: faded off the premultiplied composition, + // before a surface that takes straight alpha converts it. + crate::window::surface::corners::draw(l.corners.as_ref(), &mut prepared.encoder, target, corners); + if let Some(alpha) = &l.alpha { alpha.draw(&mut prepared.encoder, &prepared.view); } + profile.mark_encoded(); + comp_animating +} + +#[allow(unsafe_code)] +pub(super) fn submit_and_present_window( + host: &mut Host, + prepared: PreparedWindowFrame, + looped: Option<&Vec<u32>>, + profile: &mut FrameProfile, + encoded: &mut Option<Instant>, + info: &StepInfo, +) -> Instant { + let (Some(l), Some((gpu, renderer))) = (host.win.as_mut(), host.gpu.as_mut()) else { + return crate::time::now(); + }; + renderer.submit(&gpu.queue, prepared.encoder); + profile.mark_submitted(); + crate::marks::mark_once(&FIRST_ENCODED, "frame.first.encoded"); + *encoded = host.frame_reports.stamp(); + l.window.pre_present_notify(); + #[cfg(target_os = "macos")] + { + let rt = host.app.rt(); + l.native.materials.present(rt.paint.materials(), rt.env.scale, || gpu.queue.present(prepared.frame)); + } + #[cfg(target_os = "windows")] + if let (Some(rects), Some(surface)) = (&prepared.present_rect, l.surface.as_ref()) + // SAFETY: only names the rectangles the next present changed. + && let Some(hal) = unsafe { surface.as_hal::<wgpu::hal::api::Dx12>() } { + let rects: Vec<_> = rects.iter().map(|&[left, top, right, bottom]| windows::Win32::Foundation::RECT { left, top, right, bottom }).collect(); + hal.set_present_rects(&rects); + } + #[cfg(not(target_os = "macos"))] + gpu.queue.present(prepared.frame); + #[cfg(target_os = "windows")] + if let Some(surface) = l.surface.as_ref() { + l.native.slot.presented_surface(surface); + } + // A swap chain made again on a handed-over window's visual takes over now (`cpu_frame`). + #[cfg(target_os = "windows")] + if matches!(l.native.mode, handover::SurfaceMode::Rebinding { .. }) { + rune_gpu::health::poll(&gpu.device, wgpu::PollType::wait_indefinitely()).ok(); + if let handover::SurfaceMode::Rebinding { handover } = std::mem::take(&mut l.native.mode) { + if let Err(error) = handover.commit() { eprintln!("rune: the window's new swap chain couldn't take over: {error}"); } + l.native.mode = handover::SurfaceMode::Handed { handover }; + } + } + #[cfg(target_os = "windows")] + l.native.video_layers.drawn(|key| renderer.surface_drew_isolated(key)); + crate::window::frame_presented(); + crate::render::gpu_events::presented(); + // The frame reached the screen: a surface replaced by `replace_lost_surface` works, and + // the next loss starts its retries over. + l.surface_retries.worked(); + #[cfg(target_os = "macos")] + if let Some(shadow) = &l.native.shadow { shadow.presented(); } + // The frame landed with this present; later ones needn't wait for a transaction. + #[cfg(target_os = "macos")] + if !FrameMove::moving(&host.frame_move) { l.present_with_transaction(false); } + if !l.first_frame.ready() + && rune_gpu::health::poll(&gpu.device, wgpu::PollType::wait_indefinitely()).is_ok() { + l.first_frame.gpu_done(); + crate::marks::mark("frame.first.gpu_done"); + #[cfg(target_os = "windows")] + crate::platform::win32::unidle_d3d_threads_soon(); + } + // The window shows once the GPU has finished the frame it presents. + #[cfg(target_os = "windows")] + if l.native.cloak.held() { + rune_gpu::health::poll(&gpu.device, wgpu::PollType::wait_indefinitely()).ok(); + l.native.cloak.lift(&l.window); + crate::marks::mark("window.shown"); + } + #[cfg(feature = "frame-profile")] + profile.build_frame( + host, + info.animating, + looped, + #[cfg(target_os = "windows")] + prepared.present_rect, + ); + #[cfg(not(feature = "frame-profile"))] + let _ = (looped, info); + crate::time::now() +} + +pub(super) fn open_trace_if_needed(host: &mut Host, now: Instant) { + let Some(path) = &host.args.trace else { return }; + if host.trace.is_some() { return; } + let Some(l) = host.win.as_ref() else { return }; + let hz = l.window.current_monitor().and_then(|m| m.refresh_rate_millihertz()).map_or(60.0, |hz| hz as f64 / 1000.0); + #[cfg(target_os = "macos")] + let hz = l.native.pacing.as_ref().map_or(hz, |pacing| pacing.refresh_hz()); + let rt = host.app.rt_mut(); + let mut trace = crate::tooling::Trace::open_clock(path, rt.viewport, hz, rt.env.scale, "wall"); + trace.all = host.args.trace_all; + #[cfg(target_os = "macos")] + if let Some(log) = host.present_log.clone() && l.native.present.is_some() { trace.record_presents(log, now); } + trace.record_surface(host.meter.shared(), rt.host.app_stats); + host.trace = Some(trace); + host.trace_start = Some(now); + rt.scene.store_mut().audit_retargets(true); +} + +/// Records one traced frame; returns `true` when `--frames` finished the run. +pub(super) fn record_trace_frame( + host: &mut Host, + now: Instant, + submitted: Instant, + target: Option<Instant>, + drawable: Option<u64>, +) -> bool { + let Some(trace) = host.trace.as_mut() else { return false }; + let target_ms = target.zip(host.trace_start).map(|(target, start)| crate::frame::present_time::ms_since(start, target)); + // A frame count keeps the trace redrawing while idle, as below. + let continuous = !host.idle || host.args.frames.is_some(); + let timing = crate::tooling::FrameTiming { target_ms, drawable, continuous }; + trace.frame_timed_core( + host.app.rt_mut(), + (submitted - host.trace_start.unwrap()).as_secs_f64() * 1000.0, + now.elapsed().as_secs_f64() * 1000.0, + timing, + ); + host.trace_frames += 1; + if host.args.frames.is_some_and(|n| host.trace_frames >= n) { + // While the window still shows its last frames. + trace.settle_presents(crate::frame::present_time::SETTLE); + host.life.finish(); + return true; + } + false +} diff --git a/app/vendor/rune/crates/rune/src/window/host/shell_requests.rs b/app/vendor/rune/crates/rune/src/window/host/shell_requests.rs new file mode 100644 index 0000000..457809a --- /dev/null +++ b/app/vendor/rune/crates/rune/src/window/host/shell_requests.rs @@ -0,0 +1,34 @@ +//! What handlers and updates ask of the window itself, carried out by `Host::shell`: +//! minimizing it and showing the title they set. + +use super::Host; + +fn minimize_ignored(what: &str) { + if cfg!(debug_assertions) { eprintln!("rune: minimize ignored: {what} can't minimize"); } +} + +impl Host { + /// `Tx::minimize` and `AppHandle::minimize`: miniaturize on macOS, `set_minimized` + /// elsewhere. A hidden window, a panel or launcher, and a window that can't minimize + /// ignore it. + pub(in crate::window) fn minimize(&mut self) { + #[cfg(target_os = "macos")] + let launcher = self.launcher(); + let Some(w) = self.win.as_mut().filter(|_| self.life.shown()) else { return minimize_ignored("a hidden window") }; + #[cfg(target_os = "macos")] + if w.native.panel.is_some() || launcher { return minimize_ignored("a panel"); } + // Off macOS winit reports a minimize button on a borderless window too. + if self.options.borderless || !w.window.enabled_buttons().contains(winit::window::WindowButtons::MINIMIZE) { + return minimize_ignored("a window without a minimize button"); + } + #[cfg(target_os = "macos")] + { w.native.prime.stop(); } + w.window.set_minimized(true); + } + + /// `Tx::set_title`: shows a title set since the window last showed one, hidden or covered + /// as it may be. A window created later opens with the current title (`try_create`). + pub(in crate::window) fn show_title(&mut self) { + if let Some(title) = self.app.rt_mut().host.window_title.take_change() && let Some(w) = &self.win { w.window.set_title(title); } + } +} diff --git a/app/vendor/rune/crates/rune/src/window/host/stepping.rs b/app/vendor/rune/crates/rune/src/window/host/stepping.rs new file mode 100644 index 0000000..4339c4c --- /dev/null +++ b/app/vendor/rune/crates/rune/src/window/host/stepping.rs @@ -0,0 +1,307 @@ +//! Revealing a launcher's first frame, placing the window, and asking for, stepping and +//! landing its frames. + +use std::sync::atomic::Ordering; + +#[cfg(not(target_os = "macos"))] +use winit::dpi::PhysicalPosition; +use winit::event_loop::ActiveEventLoop; + +use super::Host; +use crate::time::Instant; +#[cfg(not(target_os = "macos"))] +use crate::window::chrome; +#[cfg(all(unix, not(target_os = "macos"), not(target_os = "ios"), not(target_os = "android")))] +use crate::window::chrome::float_on_open; +#[cfg(target_os = "macos")] +use crate::window::chrome::sync_chrome_core; +use crate::window::is_wayland; +use crate::window::state::Reveal; +#[cfg(target_os = "macos")] +use crate::window::sync_screen_origin_core; +#[cfg(target_os = "windows")] +use crate::window::win32::post_frame; + +/// The window's frame moving to where a handler asked (`Tx::resize_window`): a spring animation +/// over the frames macOS paints, or the size a jump lands at once elsewhere. One value, so a +/// jump can't sit loose beside an animation. +#[derive(Clone, Copy, Debug, PartialEq)] +pub(in crate::window) enum FrameMove { + /// The frame in flight: its animation on the host's frame clock, and the origin it last set, + /// to notice a drag mid-flight. macOS only; elsewhere frames change at once. + #[cfg_attr(not(target_os = "macos"), allow(dead_code))] + Moving { anim: crate::window::frame::FrameAnim, origin: [f32; 2] }, + /// Elsewhere, a size a resize request jumps to: the coupon for the one `Resized` it causes, + /// so that event lays out like a step of a resize animation rather than the user's drag. + #[cfg_attr(target_os = "macos", allow(dead_code))] + Jumped { size: (f32, f32) }, +} + +impl FrameMove { + /// The frame animating to a new size (macOS). + #[cfg_attr(not(target_os = "macos"), allow(dead_code))] + pub(in crate::window) fn animating(anim: crate::window::frame::FrameAnim, origin: [f32; 2]) -> Self { + FrameMove::Moving { anim, origin } + } + + /// The frame jumping to `size` at once (elsewhere), which its `Resized` announces. + #[cfg_attr(target_os = "macos", allow(dead_code))] + pub(in crate::window) fn jumped(size: (f32, f32)) -> Self { FrameMove::Jumped { size } } + + /// Whether the frame is animating to a new frame. A jump names the one `Resized` it causes, + /// which the draw schedules like any other event, not as motion. + pub(in crate::window) fn moving(slot: &Option<Self>) -> bool { + matches!(slot, Some(FrameMove::Moving { .. })) + } + + /// Takes the jump a `Resized` laid out at `viewport` announces: spent by that event whether + /// or not it matches, so a later resize is the user's again. `true` when this window asked + /// for the size. + pub(in crate::window) fn take_jump(slot: &mut Option<Self>, viewport: (f32, f32)) -> bool { + let Some(FrameMove::Jumped { size }) = *slot else { return false }; + *slot = None; + (size.0 - viewport.0).abs() < 1.0 && (size.1 - viewport.1).abs() < 1.0 + } + + /// Takes the animation in flight, for a window that stops painting mid-move. A jump coupon + /// outlives it: its `Resized` still comes. + pub(in crate::window) fn take_moving(slot: &mut Option<Self>) -> Option<crate::window::frame::FrameAnim> { + let Some(FrameMove::Moving { anim, .. }) = *slot else { return None }; + *slot = None; + Some(anim) + } +} + +impl Host { + pub(in crate::window) fn launcher(&self) -> bool { cfg!(target_os = "macos") && self.macos_window.launcher } + + pub(in crate::window) fn reveal_launcher(&mut self, event_loop: &ActiveEventLoop) { + self.apply_placement(event_loop); + if self.win.is_none() { self.create(event_loop, None, false); } + let stale = self.app.rt().needs_commit(); + let visible = self.life.shown(); + let Some(w) = &mut self.win else { return }; + w.hidden_pace.reset(); + if !w.first_frame.request_reveal(stale, visible, crate::time::now()) { + w.request_redraw(); + return; + } + // Already showing: its next frame draws the new state, or a covered one's retry does. + if visible && stale { w.request_redraw(); } + self.reveal(event_loop, Reveal::Cached, None); + } + + pub(in crate::window) fn first_frame_ready(&mut self, event_loop: &ActiveEventLoop) { + let Some(w) = &mut self.win else { return }; + if !w.first_frame.pending() { + // No first frame to wait for (`FirstFrame::skipped`, `READY_FALLBACK`): the app's live + // work starts anyway. The window isn't ready (`is_ready`) until it draws. + if w.first_frame.ready_due(crate::time::now()) && w.first_frame.take_ready() { self.ready_owed(); } + return; + } + let reveal = w.first_frame.complete(); + #[cfg(all(unix, not(target_os = "macos"), not(target_os = "ios"), not(target_os = "android")))] + if self.float_on_open && !w.first_frame.notified() { float_on_open::release(&w.window, &self.options, self.geometry.min_size); } + self.native_handle.native.ready.store(true, Ordering::Release); + self.shared.set_window_error(None); + crate::tooling::perf_warn::launch::first_frame(); + w.first_frame.notify(); + if w.first_frame.take_ready() { self.ready_owed(); } + if reveal { + self.reveal_launcher(event_loop); + self.shell(event_loop); + } + self.publish(); + } + + /// The window is ready: on Windows its `on_ready` and hooks run in the turns after it, one + /// piece a turn and none while input waits (`post_frame`); elsewhere now. + fn ready_owed(&mut self) { + #[cfg(target_os = "windows")] + { self.chores = post_frame::Chores::Ready; } + #[cfg(not(target_os = "windows"))] + self.run_on_ready(); + } + + pub(in crate::window) fn run_on_ready(&mut self) { + if let Some(ready) = self.on_ready.as_mut() { + crate::tooling::perf_warn::timed("on_ready", || ready(&self.native_handle)); + } + #[cfg(not(target_arch = "wasm32"))] + crate::platform::ready_signal::ready(); + } + + /// Windows: the hooks a shown window takes once it's ready. + #[cfg(target_os = "windows")] + pub(in crate::window) fn run_ready_hooks(&mut self) { + // After the first frame: files can only be dragged onto a window a person has seen. + if let Some(w) = &self.win { + crate::platform::win32::drop_target::install(&w.window); + // Win+L wipes a secret left on the clipboard. + crate::platform::win32::session_lock::install(&w.window); + } + } + + pub(in crate::window) fn place(&mut self, event_loop: &ActiveEventLoop, request: crate::windows::PlaceRequest) { + self.options.position = None; + self.placement = Some(request); + self.apply_placement(event_loop); + } + + pub(in crate::window) fn apply_placement(&mut self, event_loop: &ActiveEventLoop) { + let (Some(request), Some(w)) = (&self.placement, &self.win) else { return }; + if is_wayland(event_loop) { return; } + #[cfg(target_os = "macos")] + { + let _ = request.pointer; + crate::platform::macos::place_window(&w.window, self.app.rt().window_viewport(), request); + } + #[cfg(not(target_os = "macos"))] + if let Some(monitor) = crate::overlay::monitor_at(event_loop, &request.display, request.pointer) { + let scale = monitor.scale_factor(); + let area = monitor.size(); + let rect = crate::overlay::options::local_rect(crate::windows::PlaceRequest::at(self.app.rt().window_viewport()), Some(request.placement), + (area.width as f32 / scale as f32, area.height as f32 / scale as f32)); + let origin = monitor.position(); + chrome::request_inner_size(&w.window, (rect[2], rect[3])); + w.window.set_outer_position(PhysicalPosition::new(origin.x + (f64::from(rect[0]) * scale).round() as i32, + origin.y + (f64::from(rect[1]) * scale).round() as i32)); + } + self.sync_origin(); + } + + /// Seconds on the host's frame clock, which frame animations sample. + pub(in crate::window) fn frame_secs(&self, at: Instant) -> f64 { + self.app.rt().wall_start.map_or(0.0, |start| at.saturating_duration_since(start).as_secs_f64()) + } + + /// Takes the frame change handlers asked for. A painting macOS window moves over its next + /// frames on the request's spring, from `start`; anywhere else the frame jumps. Sizes stay + /// inside the window's minimum and maximum. A size outlives the window: one created later + /// opens at it. + pub(in crate::window) fn take_frame_request(&mut self, start: f64, painting: bool) { + let rt = self.app.rt_mut(); + rt.host.fit.take_held(); + let Some(mut request) = rt.host.window_frame.take() else { return }; + let (min, max) = self.options.size_limits(self.geometry.min_size); + request.size = request.size.map(|size| crate::window::frame::clamp_size(size, min, max)); + if let Some(size) = request.size { + self.geometry.size = size; + self.args.size = None; + } + let Some(w) = &self.win else { return }; + #[cfg(target_os = "macos")] + { + use crate::window::frame::{FrameAnim, snap, target}; + let Some((frame, visible, scale)) = crate::platform::macos::window_geometry(&w.window) else { return }; + // Resizing again mid-flight keeps the edge the first resize keeps. + let base = match &self.frame_move { + Some(FrameMove::Moving { anim, .. }) => anim.to, + _ => frame, + }; + let outer = request.size.and_then(|size| crate::platform::macos::outer_size(&w.window, size)); + let to = snap(target(base, outer, request.center, visible), scale); + // Centring alone carries on with a resize already moving. + let spring = request.spring + .or(match &self.frame_move { + Some(FrameMove::Moving { anim, .. }) => anim.spring, + _ => None, + }.filter(|_| request.size.is_none())); + if painting { + let previous = match &self.frame_move { + Some(FrameMove::Moving { anim, .. }) => Some(anim), + _ => None, + }; + let anim = FrameAnim::retarget(previous, spring, start, frame, to); + self.frame_move = Some(FrameMove::animating(anim, [frame[0], frame[1]])); + } else { + self.frame_move = None; + crate::platform::macos::set_window_frame(&w.window, to); + self.sync_origin(); + } + } + #[cfg(not(target_os = "macos"))] + { + let _ = (start, painting); + let window = &w.window; + // Read before the resize request, which may apply at once. + let geometry = (window.current_monitor(), window.outer_position(), window.outer_size(), window.inner_size()); + if let Some((width, height)) = request.size { + self.frame_move = Some(FrameMove::jumped((width, height))); + chrome::request_inner_size(window, (width, height)); + } + // Wayland windows can't see or set their position. + if self.wayland { return; } + let (Some(monitor), Ok(position), outer, inner) = geometry else { return }; + let scale = window.scale_factor() as f32; + let size = request.size.map(|(width, height)| ( + width * scale + outer.width.saturating_sub(inner.width) as f32, + height * scale + outer.height.saturating_sub(inner.height) as f32, + )); + let current = [position.x as f32, position.y as f32, outer.width as f32, outer.height as f32]; + let (origin, area) = (monitor.position(), monitor.size()); + let visible = [origin.x as f32, origin.y as f32, area.width as f32, area.height as f32]; + let [x, y, ..] = crate::window::frame::target(current, size, request.center, visible); + if [x, y] != [current[0], current[1]] { + window.set_outer_position(PhysicalPosition::new(x.round() as i32, y.round() as i32)); + self.sync_origin(); + } + } + } + + /// Moves the frame one display frame along, before the frame's drawable is acquired, and + /// lays the content out at the new size: content follows the edge in the same frame, with + /// no stretched or blank strip. + pub(in crate::window) fn step_frame(&mut self, at: Instant) { + let now = self.frame_secs(at); + self.take_frame_request(now, true); + #[cfg(target_os = "macos")] + { + use crate::window::frame::snap; + // The window server shows a move on the first frame after an idle spell before the + // frame drawn for it, leaving a stale strip. A request taken then starts here and + // moves from the next frame. + let resting = self.idle; + let moving = FrameMove::moving(&self.frame_move); + let (Some(w), Some((gpu, ..))) = (self.win.as_mut(), self.gpu.as_ref()) else { return }; + w.present_with_transaction(moving); + if resting { return; } + let Some(FrameMove::Moving { anim, origin }) = self.frame_move.as_mut() else { return }; + let Some((frame, _, scale)) = crate::platform::macos::window_geometry(&w.window) else { return }; + // Someone dragged the window mid-flight: the drag wins. The window stays where they + // put it and the size carries on from there. + let [x, y] = *origin; + if (frame[0] - x).abs() > 0.5 || (frame[1] - y).abs() > 0.5 { + anim.shift(frame[0] - x, frame[1] - y); + } + let rect = snap(anim.sample(now).0, scale); + crate::platform::macos::set_window_frame(&w.window, rect); + *origin = [rect[0], rect[1]]; + if anim.done(now) { self.frame_move = None; } + let rt = self.app.rt_mut(); + sync_chrome_core(rt, w, self.chrome, self.titlebar); + let size = w.window.inner_size(); + w.resize_surface(Some(&**gpu), size); + let scale = w.window.scale_factor() as f32; + rt.step_viewport((size.width as f32 / scale, size.height as f32 / scale), scale); + // In this frame's layout, not the next one when `Moved` arrives. + sync_screen_origin_core(rt, &w.window); + } + } + + /// A window that stops painting mid-move lands where it was going. A jump coupon outlives + /// it: its `Resized` still comes. + pub(in crate::window) fn land_frame(&mut self) { + let moving = FrameMove::take_moving(&mut self.frame_move); + #[cfg(target_os = "macos")] + if let Some(w) = &mut self.win { + w.present_with_transaction(false); + w.set_live_resize(false); + if let Some(anim) = moving { crate::platform::macos::set_window_frame(&w.window, anim.to); } + } + #[cfg(target_os = "macos")] + self.sync_origin(); + #[cfg(not(target_os = "macos"))] + let _ = moving; + } +} diff --git a/app/vendor/rune/crates/rune/src/window/keys.rs b/app/vendor/rune/crates/rune/src/window/keys.rs new file mode 100644 index 0000000..26712dd --- /dev/null +++ b/app/vendor/rune/crates/rune/src/window/keys.rs @@ -0,0 +1,172 @@ +//! winit keys and modifiers as Rune's. +use winit::keyboard::{Key as WKey, ModifiersState, NativeKeyCode, PhysicalKey}; + +use crate::edit::{Key, KeyEvent, Mods}; + +pub(crate) fn map_mods(m: ModifiersState) -> Mods { + crate::input::key_table::mods_from_keys(m.shift_key(), m.control_key(), m.alt_key(), m.super_key()) +} + +pub(crate) fn map_key(key: &WKey, m: ModifiersState) -> Option<KeyEvent> { + let mods = map_mods(m); + let key = match key { + WKey::Named(n) => crate::input::key_table::key_from_winit(*n)?, + // Windows treats Left Ctrl + Left Alt as AltGr: a character typed with both is text + // ("@" on a German layout's Q), not a chord. A chord that types nothing comes through + // `map_key_event`'s fallback instead. + WKey::Character(c) if mods.cmd && c != " " && c.chars().count() == 1 && !(cfg!(target_os = "windows") && mods.ctrl && mods.alt) => { + Key::Command(c.chars().next()?.to_ascii_lowercase()) + } + WKey::Character(c) => Key::Text(c.to_string()), + _ => return None, + }; + Some(KeyEvent { key, mods }) +} + +/// `map_key` for a window's key event. Windows names no logical key for a chord whose +/// modifiers type nothing on the layout, such as Ctrl+Alt+B on US English (Ctrl+Alt is AltGr +/// there); it still arrives as a chord on the character the key types unmodified. Off macOS, a +/// chord on a key that types a non-ASCII character (Ctrl+М on a Russian layout, Ctrl+Ü on a +/// German one) arrives as the US key in its place, `Command('v')`, as Windows' own shortcuts +/// follow the key's Latin virtual key and macOS's switch to a Latin layout under ⌘: Ctrl+V +/// pastes on every layout. +pub(crate) fn map_key_event(event: &winit::event::KeyEvent, m: ModifiersState) -> Option<KeyEvent> { + let mut ev = map_parts(cfg!(target_os = "windows"), event.physical_key, &event.logical_key, event.text.as_deref(), m) + .or_else(|| unidentified(event, m))?; + if !cfg!(target_os = "macos") + && let Key::Command(c) = ev.key + && !c.is_ascii() + && let winit::keyboard::PhysicalKey::Code(code) = event.physical_key + && let Some(us) = crate::shortcuts::us_char(code) + { + ev.key = Key::Command(us); + } + Some(ev) +} + +fn unidentified(event: &winit::event::KeyEvent, m: ModifiersState) -> Option<KeyEvent> { + let WKey::Unidentified(_) = event.logical_key else { return None }; + let mods = map_mods(m); + // Ctrl+Pause is Break, which Windows names `VK_CANCEL` and winit leaves unnamed: it arrives as + // Ctrl+Pause, so a terminal can send Ctrl+Break. + if event.physical_key == winit::keyboard::PhysicalKey::Code(winit::keyboard::KeyCode::Pause) { + return Some(KeyEvent { key: Key::Pause, mods }); + } + if !(mods.cmd || mods.ctrl) { return None; } + let c = key_base(event).filter(|c| !c.is_control() && *c != ' ')?; + let key = if mods.cmd { Key::Command(c.to_ascii_lowercase()) } else { Key::Text(c.to_string()) }; + Some(KeyEvent { key, mods }) +} + +/// The physical key Rune's winit patch gives text that arrived with no key behind it on Windows: +/// a bare `WM_CHAR`, or a `VK_PACKET` from `SendInput(KEYEVENTF_UNICODE)` (the emoji panel, voice +/// typing, the on-screen keyboard, text expanders, password managers). Windows never names a real +/// key this way: one with an unknown scan code is `NativeKeyCode::Windows(_)`. +const NO_KEY: PhysicalKey = PhysicalKey::Unidentified(NativeKeyCode::Unidentified); + +/// `map_key`, except that on Windows text with no key behind it (`NO_KEY`) types as itself with +/// no modifiers, even while a hotkey's modifier is still held. Anything else, including such +/// text that is a control character, is `map_key`'s, as before. +fn map_parts(windows: bool, physical: PhysicalKey, logical: &WKey, text: Option<&str>, m: ModifiersState) -> Option<KeyEvent> { + if windows + && physical == NO_KEY + && matches!(logical, WKey::Character(_) | WKey::Unidentified(_)) + && let Some(text) = text.filter(|t| !t.is_empty() && !t.chars().any(char::is_control)) + { + return Some(KeyEvent { key: Key::Text(text.to_owned()), mods: Mods::default() }); + } + map_key(logical, m) +} + +/// The character `event`'s key types under the current layout with no modifiers, for +/// `Tx::key_base`. +pub(crate) fn key_base(event: &winit::event::KeyEvent) -> Option<char> { + #[cfg(any(target_os = "macos", target_os = "windows", target_os = "linux"))] + { + use winit::keyboard::NamedKey; + use winit::platform::modifier_supplement::KeyEventExtModifierSupplement; + match event.key_without_modifiers() { + WKey::Character(s) => { let mut c = s.chars(); c.next().filter(|_| c.next().is_none()) } + WKey::Named(NamedKey::Space) => Some(' '), + _ => None, + } + } + #[cfg(not(any(target_os = "macos", target_os = "windows", target_os = "linux")))] + { let _ = event; None } +} + +#[cfg(test)] +#[path = "keys_tests.rs"] +mod layout_tests; + +#[cfg(test)] +mod tests { + use super::*; + use winit::keyboard::NamedKey; + + #[test] + fn keys_that_type_nothing_reach_handlers() { + for (named, key) in [ + (NamedKey::ScrollLock, Key::ScrollLock), (NamedKey::Pause, Key::Pause), (NamedKey::ContextMenu, Key::ContextMenu), + (NamedKey::PrintScreen, Key::PrintScreen), (NamedKey::Insert, Key::Insert), + ] { + assert_eq!(map_key(&WKey::Named(named), ModifiersState::empty()).map(|ev| ev.key.clone()), Some(key)); + } + } + + /// A real key Windows sent with scan code 0 that winit could not name (an automation script's + /// `keybd_event(vk, 0, …)`, some remote-control and accessibility tools). + const SCAN_ZERO: PhysicalKey = PhysicalKey::Unidentified(NativeKeyCode::Windows(0)); + + fn ch(s: &str) -> WKey { + WKey::Character(s.into()) + } + + #[test] + fn text_with_no_key_types_itself_without_modifiers() { + for text in ["a", "é", "日本", "😀", "e\u{301}"] { + for m in [ModifiersState::empty(), ModifiersState::CONTROL, ModifiersState::ALT, ModifiersState::CONTROL | ModifiersState::SHIFT] { + let ev = map_parts(true, NO_KEY, &ch(text), Some(text), m); + assert_eq!(ev, Some(KeyEvent { key: Key::Text(text.into()), mods: Mods::default() }), "{text:?} {m:?}"); + } + } + } + + #[test] + fn a_control_character_with_no_key_falls_through_to_the_old_path() { + // winit names such a VK_PACKET's key `Unidentified`, as before this change; a bare WM_CHAR + // control character makes no event at all. + for text in ["\u{8}", "\t", "\n", "\r", "\u{1b}", "\u{7f}", "\u{85}", "a\r"] { + for logical in [WKey::Unidentified(winit::keyboard::NativeKey::Windows(0xe7)), ch(text)] { + for m in [ModifiersState::empty(), ModifiersState::CONTROL] { + assert_eq!(map_parts(true, NO_KEY, &logical, Some(text), m), map_key(&logical, m), "{text:?} {logical:?} {m:?}"); + } + } + } + assert_eq!(map_parts(true, NO_KEY, &ch("a"), None, ModifiersState::empty()), map_key(&ch("a"), ModifiersState::empty())); + } + + #[test] + fn real_keys_with_scan_code_zero_keep_the_old_path() { + // Ctrl+C: the logical key is the character, the text is ETX. + let copy = map_parts(true, SCAN_ZERO, &ch("c"), Some("\u{3}"), ModifiersState::CONTROL); + assert_eq!(copy, map_key(&ch("c"), ModifiersState::CONTROL)); + // Alt+F: WM_SYSKEYDOWN + WM_SYSCHAR, the text is "f". + let alt_f = map_parts(true, SCAN_ZERO, &ch("f"), Some("f"), ModifiersState::ALT); + assert_eq!(alt_f, map_key(&ch("f"), ModifiersState::ALT)); + // A plain "a". + let a = map_parts(true, SCAN_ZERO, &ch("a"), Some("a"), ModifiersState::empty()); + assert_eq!(a, map_key(&ch("a"), ModifiersState::empty())); + if cfg!(target_os = "windows") { + assert_eq!(copy, Some(KeyEvent { key: Key::Command('c'), mods: map_mods(ModifiersState::CONTROL) })); + assert_eq!(alt_f, Some(KeyEvent { key: Key::Text("f".into()), mods: map_mods(ModifiersState::ALT) })); + assert_eq!(a, Some(KeyEvent { key: Key::Text("a".into()), mods: Mods::default() })); + } + } + + #[test] + fn text_with_no_key_is_only_special_on_windows() { + let m = ModifiersState::CONTROL; + assert_eq!(map_parts(false, NO_KEY, &ch("a"), Some("a"), m), map_key(&ch("a"), m)); + } +} diff --git a/app/vendor/rune/crates/rune/src/window/keys_tests.rs b/app/vendor/rune/crates/rune/src/window/keys_tests.rs new file mode 100644 index 0000000..0a0f318 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/window/keys_tests.rs @@ -0,0 +1,59 @@ +use super::*; +use crate::{Cx, El, Env, PhysicalInput, PhysicalKeyCode, Runtime, TextEdit, TextStyle, text_input}; + +#[derive(Default)] +struct Field { edit: TextEdit, opened: bool } + +fn field(s: &Field, _: &mut Cx<Field>) -> El { + text_input(&s.edit, TextStyle::new(14.0, 400.0)).key("reply").size(200.0, 40.0) + .on_edit(|s: &mut Field| &mut s.edit) +} + +#[test] +fn dvorak_shift_command_o_reaches_the_app_with_a_field_focused() { + let mut rt = Runtime::new(Field::default(), field, (200.0, 40.0), Env::new(true, 1.0)); + rt.on_key = Some(|s, ev, _| { + if ev.key == Key::Command('o') && ev.mods.shift { + s.opened = true; + return true; + } + false + }); + rt.frame(0.0); + let (x, y) = rt.find("reply").unwrap(); + rt.pointer_down(x, y); + rt.pointer_up(x, y); + rt.frame(0.0); + // Dvorak O lives on ANSI S; the logical chord must win over that position. + let command = if cfg!(target_os = "macos") { ModifiersState::SUPER } else { ModifiersState::CONTROL }; + let logical = map_key(&WKey::Character("O".into()), command | ModifiersState::SHIFT).unwrap(); + rt.physical_with_fallback(PhysicalInput::Key { + key: PhysicalKeyCode::KeyS, mods: logical.mods, pressed: true, repeat: false, + }, Some(logical)); + rt.frame(0.0); + assert!(rt.state.opened); + assert!(rt.state.edit.text.is_empty(), "the chord did not type into the field"); +} + +#[test] +fn dvorak_paste_uses_the_logical_character_not_the_physical_period() { + let mut rt = Runtime::new(Field::default(), field, (200.0, 40.0), Env::new(true, 1.0)); + rt.frame(0.0); + let (x, y) = rt.find("reply").unwrap(); + rt.pointer_down(x, y); + rt.pointer_up(x, y); + rt.frame(0.0); + // macOS supplies charactersIgnoringModifiers="v" at ANSI Period (47) + // on Dvorak, including a synthesized Command-V from a dictation app. + let command = if cfg!(target_os = "macos") { ModifiersState::SUPER } else { ModifiersState::CONTROL }; + let logical = map_key(&WKey::Character("v".into()), command).unwrap(); + assert_eq!(logical.key, Key::Command('v')); + rt.physical_with_fallback(PhysicalInput::Key { + key: PhysicalKeyCode::Period, mods: logical.mods, pressed: true, repeat: false, + }, Some(logical)); + rt.frame(0.0); + let target = rt.edit.paste_request.take().expect("Dvorak Command-V requests the clipboard"); + rt.paste_result(target, crate::ClipboardContent::new("Dictated reply")); + rt.frame(0.0); + assert_eq!(rt.state.edit.text, "Dictated reply"); +} diff --git a/app/vendor/rune/crates/rune/src/window/spec.rs b/app/vendor/rune/crates/rune/src/window/spec.rs new file mode 100644 index 0000000..46f7db6 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/window/spec.rs @@ -0,0 +1,547 @@ +//! Window descriptions shared by the native shell and deterministic headless selection. +use crate::{App, AppSpec}; + +#[derive(Clone, Debug)] +pub(crate) struct PlaceRequest { + pub display: crate::DisplayTarget, + pub placement: crate::OverlayPlacement, + pub pointer: Option<(i32, i32)>, + /// The caller's target, before sampling the pointer; headless runs resolve this. + pub requested: crate::DisplayTarget, +} + +impl PlaceRequest { + pub fn new(display: crate::DisplayTarget, placement: crate::OverlayPlacement) -> Self { + #[allow(unused_mut)] // Only desktop hosts can sample a pointer's display. + let mut request = Self { requested: display.clone(), display, placement, pointer: None }; + if request.display == crate::DisplayTarget::UnderPointer { + #[cfg(target_os = "macos")] + { request.display = crate::platform::macos::pointer_display().map_or(crate::DisplayTarget::Primary, + |id| crate::DisplayTarget::Native(crate::NativeDisplayId::MacOS(id))); } + #[cfg(target_os = "windows")] + { request.pointer = crate::platform::win32::pointer_position(); } + #[cfg(all(unix, not(target_os = "macos"), not(target_os = "ios"), not(target_os = "android")))] + { request.pointer = crate::platform::x11::overlay::pointer_position(); } + } + request + } + + pub fn at(size: (f32, f32)) -> crate::overlay::Placement { + crate::overlay::Placement { size, edge: crate::ScreenEdge::Top, margin: 0.0, align: crate::Align::Center, inset: 0.0 } + } +} + +/// Process-level settings applied once, before constructing the native event loop. +#[derive(Clone, Copy, Debug, Default)] +pub struct RunOptions { + /// macOS: no Dock icon/default menu and no activation at launch. Ignored elsewhere. + pub accessory: bool, +} + +/// A display in desktop physical-pixel coordinates (origins may be negative). +/// Headless runs provide one deterministic virtual display. +#[derive(Clone, Debug, PartialEq)] +pub struct Display { + /// Native identity for overlay targeting; absent for the headless virtual display. + pub id: Option<crate::DisplayId>, + pub name: Option<String>, + pub position: (i32, i32), + pub size: (u32, u32), + pub scale: f64, + pub primary: bool, +} + +impl Display { + pub fn native_id(&self) -> Option<crate::NativeDisplayId> { self.id.as_ref().and_then(|id| id.native_id()) } + + /// (x, y, width, height) in the native global, top-left coordinate space. macOS uses + /// CGDisplayBounds points; Windows/X11 use desktop pixels; Wayland uses compositor + /// logical coordinates. Keep the origin in this space; scale only local offsets. + pub fn native_bounds(&self) -> [f64; 4] { + #[cfg(target_os = "macos")] + if let Some(crate::NativeDisplayId::MacOS(id)) = self.native_id() { return crate::platform::macos::display_bounds(id); } + let divisor = if matches!(self.native_id(), Some(crate::NativeDisplayId::Wayland(_))) { self.scale } else { 1.0 }; + [f64::from(self.position.0), f64::from(self.position.1), f64::from(self.size.0) / divisor, f64::from(self.size.1) / divisor] + } +} + +/// A window's minimum content size when neither `WindowOptions` nor `AppSpec` sets one. +pub(crate) const DEFAULT_MIN_SIZE: (f32, f32) = (420.0, 400.0); + +#[derive(Clone, Debug)] +pub struct WindowOptions { + pub transparent: bool, + pub borderless: bool, + /// Clicks, and so hover, pass to whatever is below. + pub click_through: bool, + pub always_on_top: bool, + pub visible: bool, + /// Physical desktop coordinates, not points. Use a display's position unchanged. + pub position: Option<(i32, i32)>, + /// Physical content size; overrides AppSpec's logical size when set. + pub physical_size: Option<(u32, u32)>, + /// Logical minimum; None inherits AppSpec's minimum, Some((0, 0)) removes the floor. + /// Requested sizes (`Tx::resize_window`) stay inside the minimum and maximum. + pub min_size: Option<(f32, f32)>, + /// Logical maximum content size. None leaves it unconstrained. + pub max_size: Option<(f32, f32)>, + /// Whether the user can resize the window. Programmatic sizing is unaffected. A window + /// that isn't resizable doesn't maximize either: its maximize (zoom) button is disabled. + pub resizable: bool, +} + +impl Default for WindowOptions { + fn default() -> Self { + Self { + transparent: false, borderless: false, click_through: false, + always_on_top: false, visible: true, position: None, physical_size: None, + min_size: None, max_size: None, resizable: true, + } + } +} + +impl WindowOptions { + /// A hidden, retained launcher. On macOS, prepares its first frame at alpha zero; + /// show/open takes keys without activating the app. Use `on_ready` to register a shortcut. + /// Other platforms use an ordinary initially hidden window. + pub fn launcher_panel() -> ConfiguredWindowOptions { + let mut native = MacWindowOptions::default().nonactivating_panel(true); + native.launcher = true; + Self { visible: false, borderless: true, transparent: true, resizable: false, + min_size: Some((0.0, 0.0)), ..Default::default() }.macos(native) + } + /// Optional AppKit settings without adding fields to existing WindowOptions literals. + /// Ignored on other platforms. + pub fn macos(self, native: MacWindowOptions) -> ConfiguredWindowOptions { + ConfiguredWindowOptions { options: self, native } + } + /// One transparent, borderless, topmost, click-through overlay covering this display. + pub fn overlay(display: &Display) -> Self { + Self { + transparent: true, borderless: true, click_through: true, always_on_top: true, + visible: true, position: Some(display.position), physical_size: Some(display.size), + min_size: Some((0.0, 0.0)), max_size: None, resizable: true, + } + } + + /// The window's minimum and maximum content sizes, with `AppSpec::min_size` as the + /// fallback minimum. + pub(crate) fn size_limits(&self, app_min: Option<(f32, f32)>) -> ((f32, f32), Option<(f32, f32)>) { + let mut min = self.min_size.or(app_min).unwrap_or(DEFAULT_MIN_SIZE); + if let Some(max) = self.max_size { min = (min.0.min(max.0), min.1.min(max.1)); } + (min, self.max_size) + } + + /// The minimum a window that fits its content height opens with: the content sets the + /// height, so the default minimum height doesn't apply. + pub(crate) fn fit_min_size(&self, app_min: Option<(f32, f32)>) -> Option<(f32, f32)> { + if app_min.is_none() && self.min_size.is_none() { Some((DEFAULT_MIN_SIZE.0, 0.0)) } else { app_min } + } + + pub(crate) fn attributes(&self, title: &str, size: (f32, f32), app_min: Option<(f32, f32)>, visible: bool) -> winit::window::WindowAttributes { + use winit::dpi::{LogicalSize, PhysicalPosition, PhysicalSize}; + use winit::window::{Window, WindowButtons, WindowLevel}; + let (min, _) = self.size_limits(app_min); + let buttons = if self.resizable { WindowButtons::all() } else { WindowButtons::all() - WindowButtons::MAXIMIZE }; + let mut attrs = Window::default_attributes() + .with_title(title) + .with_inner_size(LogicalSize::new(size.0, size.1)) + .with_min_inner_size(LogicalSize::new(min.0, min.1)) + .with_resizable(self.resizable) + .with_enabled_buttons(buttons) + .with_transparent(self.transparent) + .with_decorations(!self.borderless) + .with_visible(visible) + .with_window_level(if self.always_on_top { WindowLevel::AlwaysOnTop } else { WindowLevel::Normal }); + if let Some((w, h)) = self.max_size { attrs = attrs.with_max_inner_size(LogicalSize::new(w, h)); } + if let Some((x, y)) = self.position { attrs = attrs.with_position(PhysicalPosition::new(x, y)); } + if let Some((w, h)) = self.physical_size { attrs = attrs.with_inner_size(PhysicalSize::new(w, h)); } + attrs + } +} + +/// AppKit properties for an ordinary window, reapplied on native recreation. +/// Omitted properties keep winit's defaults. +#[derive(Clone, Debug, Default)] +pub struct MacWindowOptions { + pub(crate) shadow: Option<bool>, + pub(crate) level: Option<isize>, + pub(crate) collection_behavior: Option<usize>, + pub(crate) exclude_from_capture: Option<bool>, + pub(crate) nonactivating_panel: bool, + pub(crate) launcher: bool, + pub(crate) corner_radius: Option<f32>, + pub(crate) corner_curve_circular: bool, +} + +impl MacWindowOptions { + /// Use a key-taking NSPanel. Open/focus never activates the app or its other windows. + pub fn nonactivating_panel(mut self, enabled: bool) -> Self { + self.nonactivating_panel = enabled; + if !enabled { self.launcher = false; } + self + } + pub fn shadow(mut self, enabled: bool) -> Self { self.shadow = Some(enabled); self } + /// AppKit NSWindow.Level value (normal 0, floating 3, status 25). + pub fn level(mut self, level: isize) -> Self { self.level = Some(level); self } + /// AppKit NSWindow.CollectionBehavior bit mask. Replaces the existing mask. + pub fn collection_behavior(mut self, bits: usize) -> Self { self.collection_behavior = Some(bits); self } + /// Requests NSWindowSharingNone; capture clients should also filter window_number(). + /// false restores NSWindowSharingReadOnly. This is not a capture guarantee. A nonactivating + /// panel applies it only while shown (see `OverlayOptions::exclude_from_capture`). + pub fn exclude_from_capture(mut self, exclude: bool) -> Self { self.exclude_from_capture = Some(exclude); self } + /// Rounds a transparent, borderless window or panel to `radius` points with a continuous + /// (squircle) curve. The window's root layer clips everything it shows, Rune's drawing and + /// native material views alike, so the root view needn't clip itself to the radius. A + /// border drawn inside the edge is still the app's. The system shadow, when on, follows + /// the rounded shape. Ignored for opaque or bordered windows, where AppKit owns the frame, + /// and on other platforms. + pub fn corner_radius(mut self, radius: f32) -> Self { self.corner_radius = Some(radius.max(0.0)); self } + /// Use a circular corner arc instead of the continuous curve for `corner_radius`. + pub fn corner_curve_circular(mut self) -> Self { self.corner_curve_circular = true; self } +} + +/// Ordinary options plus native builders, accepted by WindowSpec::configured_options. +#[derive(Clone, Debug)] +pub struct ConfiguredWindowOptions { + pub(crate) options: WindowOptions, + pub(crate) native: MacWindowOptions, +} + +impl From<WindowOptions> for ConfiguredWindowOptions { + fn from(options: WindowOptions) -> Self { Self { options, native: MacWindowOptions::default() } } +} + +impl ConfiguredWindowOptions { + /// Amends the AppKit settings in place, keeping what a preset already set: + /// `WindowOptions::launcher_panel().macos(|native| native.corner_radius(16.0))` stays a + /// launcher. Ignored on other platforms. + pub fn macos(mut self, amend: impl FnOnce(MacWindowOptions) -> MacWindowOptions) -> Self { + self.native = amend(self.native); + self + } +} + +/// Forward per-window `App<S>` builder methods onto `WindowSpec<S>` so new builders don't drift. +macro_rules! forward_app_builders { + ($( + $(#[$meta:meta])* + $name:ident $(=> $target:ident)? ($($arg:ident : $ty:ty),* $(,)?) + );* $(;)?) => { + $( + $(#[$meta])* + pub fn $name(mut self, $($arg: $ty),*) -> Self { + self.app = forward_app_builders!(@call self.app, $name $(, $target)?, ($($arg),*)); + self + } + )* + }; + (@call $app:expr, $name:ident, ($($arg:ident),*)) => { $app.$name($($arg),*) }; + (@call $app:expr, $_name:ident, $target:ident, ($($arg:ident),*)) => { $app.$target($($arg),*) }; +} + +/// One independent retained tree and app state. Share Live handles or application services +/// between states; events, focus, animation clocks and redraws remain window-local. +pub struct WindowSpec<S: 'static> { + pub key: String, + pub app: App<S>, + pub options: WindowOptions, + /// Runs on the event thread after native creation. Not called by headless tooling. + pub on_created: Option<Box<dyn FnOnce(crate::window::WindowHandle)>>, +} + +impl<S: 'static> WindowSpec<S> { + pub fn new(key: impl Into<String>, app: AppSpec<S>) -> Self { + Self::from_app(key, App::new(app)) + } + /// Preserve AppHandle, windowless, keep-running and GPU-release behavior for this window. + /// Closing a default window removes only it; quitting any app exits the whole event loop. + /// RunOptions controls factory display discovery and tooling/window selection. App::args + /// replaces the selected window's arguments (including native/headless mode). Isolate a + /// host CLI before factory discovery with run_windows_with_args(options, [], factory). + /// App::accessory is process-level: use run_windows_with(RunOptions, factory) instead. + /// AppHandle::set_dock_icon remains global. + pub fn from_app(key: impl Into<String>, app: App<S>) -> Self { + Self { key: key.into(), options: app.window_options.clone(), app, on_created: None } + } + forward_app_builders! { + /// Configure this window's frame, including headless traffic-light placement. + chrome(chrome: crate::Chrome); + /// This window draws its own titlebar, like `App::titlebar`. + titlebar(titlebar: crate::Titlebar); + /// Composite this window's translucent fills, blurs, shadows, images and video in sRGB + /// (gamma) space instead of linear light, matching CSS and Core Animation. With a + /// `Compositor`, `Frame::srgb_blend` says which encoding its passes must match. + srgb_blend(enabled: bool); + /// This window's font smoothing (`App::font_smoothing`). + font_smoothing(mode: crate::FontSmoothing); + /// Size this window's height to its content, like `App::fit_content_height`. + fit_content_height(); + /// Ask a tiling window manager to float this window when it opens, like `App::float_on_open`. + float_on_open(); + /// Open this window without taking focus from the window that has it, such as a window a + /// tab is dragged into while the press stays with its strip. A later `open` or `focus` + /// activates it. + inactive => open_inactive(); + /// Open this window maximized, like `App::maximized`. + maximized(maximized: bool); + /// Open this window full screen, like `App::full_screen`. + full_screen(full_screen: bool); + /// Send `Key::Modifier` presses and releases to this window, like `App::modifier_keys`. + modifier_keys(); + /// Tab visits every focusable control in this window, like `App::tab_visits_controls`. + tab_visits_controls(on: bool); + /// Release this window's GPU device and renderer when it closes, like `App::release_gpu_when_closed`. + release_gpu_when_closed(); + on_focus(f: fn(&mut S, bool, &mut crate::Tx)); + on_modifiers(f: fn(&mut S, crate::Mods, &mut crate::Tx)); + /// This window going off screen and back, like `App::on_visibility`. + on_visibility(f: fn(&mut S, bool, &mut crate::Tx)); + /// Runs when this window rests, like `App::on_rest`. + on_rest(f: fn(&mut S, &mut crate::Tx) -> bool); + /// This window's editor's input method events, like `App::on_ime`. + on_ime(f: fn(&mut S, &crate::Ime, &mut crate::Tx) -> bool); + /// Runs whenever this window closes, like `App::on_close`. + on_close(f: fn(&mut S, &mut crate::Tx)); + /// Runs in this window when the app starts to quit, like `App::on_quit`. + on_quit(f: fn(&mut S, &mut crate::Tx)); + /// Runs `enter` before and `leave` after each event-handling turn of this window, like `App::turn_scope`. + turn_scope(enter: fn(&mut S), leave: fn(&mut S)); + /// Runs when the app is reopened, like `App::on_reopen`. + on_reopen(f: fn(&mut S, bool, &mut crate::Tx) -> bool); + /// Receives links opened with the app, like `App::on_open_url`. + on_open_url(f: fn(&mut S, &str, &mut crate::Tx)); + /// Runs on the UI thread each time the native window is created, like `App::on_window`. + on_window(f: impl FnMut(&crate::WindowHandle) + 'static); + /// Called on the event thread after the first frame is ready, once per native creation. + on_ready(f: impl FnMut(&crate::WindowHandle) + 'static); + /// Reports each of this window's frames, like `App::on_frame_encoded`. A spec made with + /// `WindowSpec::from_app` keeps its app's hook unless this replaces it; windows `App::window` + /// adds have their own. + on_frame_encoded(f: impl FnMut(&crate::FrameEncoded) + 'static); + /// Runs on the UI thread after each drawn frame of this window with its runtime, like `App::on_frame_drawn`. + on_frame_drawn(f: impl FnMut(&crate::Runtime<S>) + 'static); + /// Draw every frame of this window through `compositor`, like `App::compositor`. + compositor(compositor: impl crate::compose::Compositor<S>); + /// This window's own counters for native trace summaries, like `App::dev_stats`. + dev_stats(stats: fn() -> String); + /// This window's playground, like `App::playground`. + playground(playground: crate::Playground<S>); + } + /// Configure the underlying `App` directly for any per-window builder not forwarded here. + pub fn map_app(mut self, f: impl FnOnce(App<S>) -> App<S>) -> Self { + self.app = f(self.app); + self + } + pub fn options(mut self, options: WindowOptions) -> Self { + self.options = options; + self.app.macos_window = MacWindowOptions::default(); + self + } + pub fn configured_options(mut self, options: ConfiguredWindowOptions) -> Self { + let ConfiguredWindowOptions { options, native } = options; + self.options = options; + self.app.macos_window = native; + self + } + pub fn state(mut self, state: S) -> Self { self.app = self.app.init(move || state); self } + pub fn on_created(mut self, callback: impl FnOnce(crate::window::WindowHandle) + 'static) -> Self { + self.on_created = Some(Box::new(callback)); + self + } + /// Erase the state type, so one factory can return windows of different state types. + pub fn boxed(self) -> AnyWindowSpec { self.into() } +} + +thread_local! { + /// Windows [`open_window`] asked for, which the event loop starts at the end of its turn. + static OPENED: std::cell::RefCell<Vec<AnyWindowSpec>> = const { std::cell::RefCell::new(Vec::new()) }; +} + +/// Opens another window in the running app's event loop, with its own state, retained tree, +/// focus and clocks, as the windows a `run_windows` factory returns do: a second document +/// window, or a tab dragged out of its strip. Call it on the UI thread (a handler, an update, +/// `on_ready`); the window starts at the end of the turn. It keeps the app running as the +/// factory's windows do, so the app ends when the last of them closes. Its key must differ +/// from every open window's; a window with a key already open isn't opened. The handle places, +/// focuses and closes it, and its requests wait for it to start. Headless runs open nothing. +pub fn open_window<S: 'static>(spec: WindowSpec<S>) -> crate::WindowHandle { + let handle = crate::WindowHandle::new(&spec.key); + if !crate::is_headless() { + let opened = AnyWindowSpec(Box::new(Erased { spec, handle: Some(handle.clone()), secondary: false })); + OPENED.with(|o| o.borrow_mut().push(opened)); + } + handle +} + +/// The windows `open_window` queued since the last call. +pub(crate) fn take_opened() -> Vec<AnyWindowSpec> { + OPENED.with(|o| std::mem::take(&mut *o.borrow_mut())) +} + +/// A window's place on the desktop, in physical pixels: what to save to reopen it there. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub struct WindowPlacement { + /// The frame's top-left, the space `WindowOptions::position` takes. + pub position: (i32, i32), + /// The content's top-left. + pub content_position: (i32, i32), + /// The content's size, the space `WindowOptions::physical_size` takes. + pub content_size: (u32, u32), + /// Physical pixels per point on the window's display. + pub scale: f64, + pub maximized: bool, + pub minimized: bool, + pub full_screen: bool, + /// While the window is maximized or minimized, the frame restoring it returns to, as + /// `position` and `content_size` give a frame: the system's own record on Windows + /// (`GetWindowPlacement`), which follows the window to another display (Win+Shift+Arrow). + /// None otherwise, and where the system keeps no such record (macOS, Linux). + pub restore: Option<((i32, i32), (u32, u32))>, + /// The display the window is on (the one with the most of it): its position and size, as + /// `Display::position` and `Display::size` give them. + pub display: Option<((i32, i32), (u32, u32))>, +} + +/// How a window's first open shows it (`App::maximized`, `App::full_screen`). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(crate) enum OpenAs { + #[default] + Normal, + Maximized, + /// Full screen; leaving it returns to the frame, `maximized` or not. + FullScreen { maximized: bool }, +} + +impl OpenAs { + pub(crate) fn maximized(self, on: bool) -> OpenAs { + match (self, on) { + (OpenAs::FullScreen { .. }, maximized) => OpenAs::FullScreen { maximized }, + (_, true) => OpenAs::Maximized, + (_, false) => OpenAs::Normal, + } + } + + pub(crate) fn full_screen(self, on: bool) -> OpenAs { + match (self, on) { + (OpenAs::FullScreen { maximized: true }, false) => OpenAs::Maximized, + (OpenAs::FullScreen { maximized: false }, false) => OpenAs::Normal, + (OpenAs::Normal, true) => OpenAs::FullScreen { maximized: false }, + (OpenAs::Maximized, true) => OpenAs::FullScreen { maximized: true }, + (state, _) => state, + } + } + + pub(crate) fn maximizes(self) -> bool { + matches!(self, OpenAs::Maximized | OpenAs::FullScreen { maximized: true }) + } + + pub(crate) fn full_screens(self) -> bool { + matches!(self, OpenAs::FullScreen { .. }) + } +} + +/// A `WindowSpec` of any state type, for factories that mix them: +/// `vec![review.boxed(), settings.into()]`. +pub struct AnyWindowSpec(Box<dyn ErasedWindow>); + +impl AnyWindowSpec { + pub fn key(&self) -> &str { self.0.key() } + + /// A window `App::window` added: it closes by hiding and never keeps the loop running alone. + pub(crate) fn secondary<T: 'static>(mut spec: WindowSpec<T>, handle: crate::WindowHandle) -> Self { + spec.app.keep_running = true; + Self(Box::new(Erased { spec, handle: Some(handle), secondary: true })) + } + + pub(crate) fn resolve_args(&mut self, inherited: crate::tooling::Args) -> crate::tooling::Args { self.0.resolve_args(inherited) } + + /// Render this window headless; `scale` converts a physical size option to points. + pub(crate) fn headless(self, args: crate::tooling::Args, scale: f32) { self.0.headless(args, scale) } + + /// This window as one member of a `--desktop` composite; `selected` takes `--scene`. + pub(crate) fn desktop(self, args: &crate::tooling::Args, selected: bool, scale: f32) -> Box<dyn crate::desktop::Member> { + self.0.desktop(args, selected, scale) + } + + pub(crate) fn start(self, inherited: crate::tooling::Args, cx: crate::window::Start<'_>) -> Option<Box<dyn crate::window::AnyHost>> { + self.0.start(inherited, cx) + } +} + +impl<S: 'static> From<WindowSpec<S>> for AnyWindowSpec { + fn from(spec: WindowSpec<S>) -> Self { Self(Box::new(Erased { spec, handle: None, secondary: false })) } +} + +trait ErasedWindow { + fn key(&self) -> &str; + fn take_windows(&mut self) -> Vec<AnyWindowSpec>; + fn resolve_args(&mut self, inherited: crate::tooling::Args) -> crate::tooling::Args; + fn headless(self: Box<Self>, args: crate::tooling::Args, scale: f32); + fn desktop(self: Box<Self>, args: &crate::tooling::Args, selected: bool, scale: f32) -> Box<dyn crate::desktop::Member>; + fn start(self: Box<Self>, inherited: crate::tooling::Args, cx: crate::window::Start<'_>) -> Option<Box<dyn crate::window::AnyHost>>; +} + +struct Erased<S: 'static> { + spec: WindowSpec<S>, + handle: Option<crate::WindowHandle>, + secondary: bool, +} + +impl<S: 'static> ErasedWindow for Erased<S> { + fn key(&self) -> &str { &self.spec.key } + fn take_windows(&mut self) -> Vec<AnyWindowSpec> { std::mem::take(&mut self.spec.app.windows) } + fn resolve_args(&mut self, inherited: crate::tooling::Args) -> crate::tooling::Args { self.spec.app.resolve_args(inherited) } + // A trait object's methods are all linked with it: without the `tooling` feature these + // bodies (never called then: `run` refuses a headless run first) keep headless rendering + // out of a release app. + #[cfg(not(any(feature = "tooling", debug_assertions)))] + fn headless(self: Box<Self>, _: crate::tooling::Args, _: f32) { unreachable!("{}", crate::tooling::WITHOUT_TOOLING) } + #[cfg(not(any(feature = "tooling", debug_assertions)))] + fn desktop(self: Box<Self>, _: &crate::tooling::Args, _: bool, _: f32) -> Box<dyn crate::desktop::Member> { unreachable!("{}", crate::tooling::WITHOUT_TOOLING) } + #[cfg(any(feature = "tooling", debug_assertions))] + fn headless(self: Box<Self>, args: crate::tooling::Args, scale: f32) { + crate::tooling::headless_window_spec(self.spec.app, self.spec.options, args, scale); + } + #[cfg(any(feature = "tooling", debug_assertions))] + fn desktop(self: Box<Self>, args: &crate::tooling::Args, selected: bool, scale: f32) -> Box<dyn crate::desktop::Member> { + let Erased { spec, handle, secondary } = *self; + Box::new(crate::desktop::Window::new(spec, handle, args, selected, !secondary, scale)) + } + fn start(self: Box<Self>, inherited: crate::tooling::Args, cx: crate::window::Start<'_>) -> Option<Box<dyn crate::window::AnyHost>> { + let inherited = secondary_args(self.secondary, &self.spec.key, inherited); + crate::window::start(self.spec, self.handle, !self.secondary, inherited, cx) + } +} + +fn secondary_args(secondary: bool, key: &str, mut inherited: crate::tooling::Args) -> crate::tooling::Args { + // A secondary window is not what --scene or --size describe unless --window selects it. + if secondary && inherited.window.as_deref() != Some(key) { + inherited.scene = None; + inherited.size = None; + } + inherited +} + +/// Each window followed by those its app added with `App::window`, depth first. +pub(crate) fn flatten(windows: impl IntoIterator<Item = AnyWindowSpec>) -> Vec<AnyWindowSpec> { + let mut out = Vec::new(); + for mut window in windows { + let children = window.0.take_windows(); + out.push(window); + out.extend(flatten(children)); + } + out +} + +pub(crate) fn validate(windows: &[AnyWindowSpec]) -> Result<(), String> { + let mut keys = std::collections::HashSet::new(); + for window in windows { + if window.key().is_empty() || !keys.insert(window.key()) { return Err(format!("empty or duplicate window key: {:?}", window.key())); } + } + Ok(()) +} + +#[cfg(test)] +#[path = "spec_tests.rs"] +mod tests; diff --git a/app/vendor/rune/crates/rune/src/window/spec_tests.rs b/app/vendor/rune/crates/rune/src/window/spec_tests.rs new file mode 100644 index 0000000..b2fbc28 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/window/spec_tests.rs @@ -0,0 +1,178 @@ +use super::*; +use winit::dpi::{LogicalSize, Size}; + +#[test] +fn launcher_preset_is_hidden_and_preserves_ordinary_defaults() { + let preset = WindowOptions::launcher_panel(); + assert!(preset.native.nonactivating_panel && preset.native.launcher); + assert!(!preset.options.visible && preset.options.borderless && preset.options.transparent); + assert!(!MacWindowOptions::default().nonactivating_panel(true).launcher); + assert!(!preset.native.nonactivating_panel(false).launcher); + assert!(WindowOptions::default().visible); + let spec = AppSpec::new("launcher", (300.0, 100.0), || (), |_, _| crate::el()); + let app = App::new(spec).configured_options(WindowOptions::launcher_panel()); + assert!(app.macos_window.launcher); + assert!(!app.window_options.visible); + let window = WindowSpec::from_app("launcher", app); + assert!(!window.options.visible && window.options.transparent); +} + +#[test] +fn amending_a_preset_keeps_its_launcher_behaviour() { + let preset = WindowOptions::launcher_panel().macos(|native| native.corner_radius(16.0).shadow(true)); + assert!(preset.native.launcher && preset.native.nonactivating_panel); + assert_eq!((preset.native.corner_radius, preset.native.shadow), (Some(16.0), Some(true))); + assert!(!preset.options.visible && preset.options.transparent); + let spec = AppSpec::new("launcher", (300.0, 100.0), || (), |_, _| crate::el()); + let app = App::new(spec).configured_options(preset); + assert!(app.macos_window.launcher); + assert_eq!(app.macos_window.corner_radius, Some(16.0)); +} + +#[test] +fn app_windows_follow_their_app_and_share_its_key_space() { + let mut main = App::new(AppSpec::new("main", (100.0, 100.0), || 0u32, |_, _| crate::el())); + let settings = || WindowSpec::new("settings", AppSpec::new("settings", (100.0, 100.0), String::new, |_, _| crate::el())); + let (_, handle) = main.window(settings()); + assert_eq!(handle.key(), "settings"); + let other = WindowSpec::new("other", AppSpec::new("other", (100.0, 100.0), || (), |_, _| crate::el())); + let flat = flatten([WindowSpec::from_app("main", main).boxed(), other.into()]); + assert_eq!(flat.iter().map(AnyWindowSpec::key).collect::<Vec<_>>(), ["main", "settings", "other"]); + assert!(validate(&flat).is_ok()); + let mut clash = App::new(AppSpec::new("main", (100.0, 100.0), || 0u32, |_, _| crate::el())); + clash.window(settings()); + assert!(validate(&flatten([WindowSpec::from_app("settings", clash).boxed()])).is_err()); +} + +#[test] +fn default_window_options_remain_inferable_at_existing_call_sites() { + // This fails to compile if options becomes generic over Into<...>. + let _configure: fn(WindowSpec<()>) -> WindowSpec<()> = |spec| spec.options(Default::default()); +} + +#[test] +fn explicit_empty_args_never_read_the_host_cli() { + let options = RunOptions { accessory: true }; + let copied = options; + assert!(options.accessory && copied.accessory); + let args = crate::tooling::window_args(Some(vec![]), || panic!("must not inspect host --trace/--snap flags")); + assert!(!args.headless()); + assert!(args.scene.is_none() && args.size.is_none()); + let inherited = crate::tooling::window_args(None, || crate::tooling::Args::parse_from( + vec!["--trace".into(), "out.jsonl".into()])); + assert!(inherited.headless()); +} + +#[test] +fn window_app_args_override_inherited_scene_and_size() { + fn spec() -> AppSpec<()> { AppSpec::new("test", (100.0, 100.0), || (), |_, _| crate::el()) } + let inherited = crate::tooling::Args::parse_from(vec!["--scene".into(), "host-scene".into()]); + let mut window = WindowSpec::from_app("pill", App::new(spec()).args(vec!["--size".into(), "320x80".into()])); + let resolved = window.app.resolve_args(inherited.clone()); + assert_eq!(resolved.size, Some((320.0, 80.0))); + assert!(resolved.scene.is_none()); + let mut plain = WindowSpec::new("plain", spec()); + assert_eq!(plain.app.resolve_args(inherited).scene.as_deref(), Some("host-scene")); + let trace = crate::tooling::Args::parse_from(vec!["--trace".into(), "host.jsonl".into()]); + let mut isolated = WindowSpec::from_app("isolated", App::new(spec()).args(vec![])); + assert!(!isolated.app.resolve_args(trace).headless()); + let mut traced = WindowSpec::from_app("traced", App::new(spec()).args(vec!["--trace".into(), "window.jsonl".into()])); + assert!(traced.app.resolve_args(crate::tooling::Args::default()).headless()); +} + +#[test] +fn compact_window_overrides_the_legacy_minimum_without_changing_defaults() { + let defaults = WindowOptions::default().attributes("app", (560.0, 440.0), None, true); + assert_eq!(defaults.min_inner_size, Some(Size::Logical(LogicalSize::new(420.0, 400.0)))); + assert!(defaults.resizable && defaults.decorations && defaults.visible); + assert_eq!(defaults.max_inner_size, None); + + let compact = WindowOptions { + min_size: Some((280.0, 80.0)), max_size: Some((320.0, 120.0)), + resizable: false, borderless: true, ..Default::default() + }.attributes("compact", (300.0, 100.0), Some((860.0, 560.0)), false); + assert_eq!(compact.inner_size, Some(Size::Logical(LogicalSize::new(300.0, 100.0)))); + assert_eq!(compact.min_inner_size, Some(Size::Logical(LogicalSize::new(280.0, 80.0)))); + assert_eq!(compact.max_inner_size, Some(Size::Logical(LogicalSize::new(320.0, 120.0)))); + assert!(!compact.resizable && !compact.decorations && !compact.visible); +} + +#[test] +fn maximum_alone_caps_the_inherited_minimum_per_axis() { + let options = WindowOptions { max_size: Some((320.0, 120.0)), ..Default::default() }; + for (app_min, expected) in [ + (None, (320.0, 120.0)), + (Some((860.0, 80.0)), (320.0, 80.0)), + ] { + let attrs = options.attributes("compact", (300.0, 100.0), app_min, true); + assert_eq!(attrs.min_inner_size, Some(Size::Logical(LogicalSize::new(expected.0, expected.1)))); + assert_eq!(attrs.max_inner_size, Some(Size::Logical(LogicalSize::new(320.0, 120.0)))); + } +} + +#[test] +fn default_options_inherit_the_app_minimum() { + let attrs = WindowOptions::default().attributes("app", (900.0, 600.0), Some((860.0, 560.0)), true); + assert_eq!(attrs.min_inner_size, Some(Size::Logical(LogicalSize::new(860.0, 560.0)))); +} + +#[test] +fn a_window_that_fits_its_content_has_no_default_minimum_height() { + let fit = WindowOptions::default().fit_min_size(None); + assert_eq!(WindowOptions::default().size_limits(fit), ((420.0, 0.0), None)); + assert_eq!(WindowOptions::default().fit_min_size(Some((300.0, 200.0))), Some((300.0, 200.0))); + let options = WindowOptions { min_size: Some((300.0, 500.0)), ..Default::default() }; + assert_eq!(options.size_limits(options.fit_min_size(None)), ((300.0, 500.0), None)); +} + +#[test] +fn forwarded_window_spec_builders_and_map_app_configure_the_inner_app() { + struct DummyCompositor; + impl crate::compose::Compositor<()> for DummyCompositor { + fn render(&mut self, f: &mut crate::compose::Frame<'_, ()>) { f.draw_ui(); } + } + fn stats() -> String { "stats".into() } + let spec = AppSpec::new("secondary", (300.0, 200.0), || (), |_, _| crate::el()); + let window = WindowSpec::new("secondary", spec) + .srgb_blend(false) + .font_smoothing(crate::FontSmoothing::Off) + .fit_content_height() + .float_on_open() + .inactive() + .maximized(true) + .full_screen(true) + .modifier_keys() + .tab_visits_controls(true) + .release_gpu_when_closed() + .on_focus(|_, _, _| {}) + .on_modifiers(|_, _, _| {}) + .on_visibility(|_, _, _| {}) + .on_rest(|_, _| false) + .on_ime(|_, _, _| false) + .on_close(|_, _| {}) + .on_quit(|_, _| {}) + .turn_scope(|_| {}, |_| {}) + .on_reopen(|_, _, _| false) + .on_open_url(|_, _, _| {}) + .on_window(|_| {}) + .on_ready(|_| {}) + .on_frame_encoded(|_| {}) + .on_frame_drawn(|_| {}) + .compositor(DummyCompositor) + .dev_stats(stats) + .map_app(|app| app.keep_running()); + assert!(!window.app.runtime.srgb_blend); + assert_eq!(window.app.runtime.font_smoothing, crate::FontSmoothing::Off); + assert!(window.app.runtime.modifier_keys && window.app.runtime.tab_visits_controls); + assert!(window.app.runtime.on_focus.is_some() && window.app.runtime.on_mods.is_some()); + assert!(window.app.runtime.on_visibility.is_some() && window.app.runtime.on_ime.is_some()); + assert_eq!(window.app.runtime.dev_stats.map(|f| f()).as_deref(), Some("stats")); + assert!(window.app.fit_content_height && window.app.float_on_open && window.app.open_inactive); + assert!(window.app.open_as.maximizes() && window.app.open_as.full_screens()); + assert!(window.app.release_gpu && window.app.keep_running); + assert!(window.app.on_rest.is_some() && window.app.on_close.is_some() && window.app.on_quit.is_some()); + assert!(window.app.turn_scope.is_some() && window.app.on_reopen.is_some() && window.app.on_open_url.is_some()); + assert!(window.app.on_window.is_some() && window.app.on_ready.is_some()); + assert!(window.app.on_frame_encoded.is_some() && window.app.on_frame_drawn.is_some()); + assert!(window.app.compositor.is_some()); +} diff --git a/app/vendor/rune/crates/rune/src/window/state.rs b/app/vendor/rune/crates/rune/src/window/state.rs new file mode 100644 index 0000000..f858454 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/window/state.rs @@ -0,0 +1,26 @@ +//! Pure state machines for a window's lifetime, sight, reveal, minimize, rest, first frame, wake +//! work and frame geometry. + +pub(in crate::window) mod first_frame; +pub(crate) mod frame; +pub(in crate::window) mod life; +pub(in crate::window) mod minimize; +pub(in crate::window) mod rest; +pub(in crate::window) mod reveal; +pub(in crate::window) mod sight; +pub(in crate::window) mod wake; + +pub(in crate::window) use first_frame::FirstFrame; +pub(crate) use life::Life; +pub(crate) use minimize::{Minimize, MinimizeEvent}; +pub(in crate::window) use rest::{Rest, RestEffect, RestEvent}; +pub(in crate::window) use reveal::{Found, Reveal, RevealEffect}; +pub(crate) use sight::{Cover, Sight}; +pub(in crate::window) use wake::{WakeFacts, WakeWork}; + +#[cfg(test)] +#[path = "state/covered_tests.rs"] +mod covered_tests; +#[cfg(test)] +#[path = "state/wake_tests.rs"] +mod wake_tests; diff --git a/app/vendor/rune/crates/rune/src/window/state/covered_tests.rs b/app/vendor/rune/crates/rune/src/window/state/covered_tests.rs new file mode 100644 index 0000000..8f842be --- /dev/null +++ b/app/vendor/rune/crates/rune/src/window/state/covered_tests.rs @@ -0,0 +1,98 @@ +use std::cell::Cell; +use std::time::Duration; + +use crate::runtime::Runtime; +use crate::window::covered_step; +use crate::{Cx, El, Env, Spring, el, text}; + +thread_local! { static BUILDS: Cell<u32> = const { Cell::new(0) }; } + +#[derive(Default)] +struct Chat { messages: u32, read: u32, polls: u32 } + +fn view(chat: &Chat, _: &mut Cx<Chat>) -> El { + BUILDS.set(BUILDS.get() + 1); + el().child(text(format!("{} {}", chat.messages, chat.read)).key("n")) +} + +fn shown_text(rt: &Runtime<Chat>) -> Option<String> { + rt.elements().into_iter().find(|e| e.key.as_deref() == Some("n")).and_then(|e| e.text) +} + +/// A covered window whose state changes 100 times, from updates, their timers and a poll +/// that reads an inbox, builds no view and lays nothing out, while `poll` and the timers +/// still run. Uncovering builds once, with the latest state. +#[test] +fn a_covered_window_builds_nothing_until_it_uncovers() { + let mut rt = Runtime::new(Chat::default(), view, (200.0, 50.0), Env { system_dark: true, scale: 1.0 }); + rt.poll = Some(|chat, _, _| { chat.polls += 1; let unread = chat.read < chat.messages; chat.read = chat.messages; unread }); + let start = crate::time::now(); + rt.wall_start = Some(start); + rt.frame(0.0); + assert_eq!(shown_text(&rt).as_deref(), Some("0 0")); + // As the host does for `WindowEvent::Occluded(true)`. + rt.set_live_visible(false); + let (builds, commits, polls) = (BUILDS.get(), rt.stats.commits, rt.state.polls); + for k in 1..=100 { + rt.update(|chat, tx| { chat.messages += 1; tx.wake_after(Duration::from_millis(10)); }); + covered_step(&mut rt); + // Its timer comes due before the next message. + rt.wall_start = Some(start - k * Duration::from_millis(20)); + covered_step(&mut rt); + } + assert_eq!((rt.state.messages, rt.state.read), (100, 100), "updates and poll ran"); + assert_eq!(rt.state.polls - polls, 200, "poll runs for every update and timer"); + assert_eq!(rt.wake_deadline(), None, "due timers are spent on time"); + assert_eq!(BUILDS.get() - builds, 0, "no view builds while covered"); + assert_eq!(rt.stats.commits, commits, "no layout while covered"); + assert!(rt.stale(), "the window is marked out of date"); + + // As the host does for `WindowEvent::Occluded(false)`, then its first frame. + rt.set_live_visible(true); + rt.settle_all(); + rt.frame(1.0 / 120.0); + assert_eq!(BUILDS.get() - builds, 1, "uncovering builds once"); + assert_eq!(shown_text(&rt).as_deref(), Some("100 100"), "with the latest state"); +} + +/// Queued input still runs its handlers while covered (a key into a covered window that's +/// still key), which takes a frame without drawing. +#[test] +fn a_covered_window_still_hears_queued_input() { + let mut rt = Runtime::new(Chat::default(), view, (200.0, 50.0), Env { system_dark: true, scale: 1.0 }); + rt.frame(0.0); + rt.set_live_visible(false); + rt.window_focus(false); + assert!(rt.keys_queued()); + covered_step(&mut rt); + assert!(!rt.has_pending_input(), "the focus change was delivered"); +} + +/// Motion running when the window is covered, and motion asked for while it's covered, +/// neither advances nor builds while covered; uncovering lands both in one frame, so +/// nothing plays out after. +#[test] +fn a_covered_window_lands_its_motion_when_it_uncovers() { + fn view(x: &f32, _: &mut Cx<f32>) -> El { + crate::col().child(el().key("box").absolute(*x, 0.0).size(10.0, 10.0)) + } + let x = |rt: &Runtime<f32>| rt.presented("box").unwrap().0[0]; + let mut rt = Runtime::new(0.0_f32, view, (100.0, 100.0), Env { system_dark: true, scale: 1.0 }); + rt.frame(0.0); + rt.update(|x, tx| { *x = 80.0; tx.motion(Spring::new(0.3, 0.0)); }); + rt.frame(1.0 / 120.0); + rt.frame(0.05); + let mid = x(&rt); + assert!(mid > 0.0 && mid < 80.0 && rt.animating, "in flight: {mid}"); + rt.set_live_visible(false); + let commits = rt.stats.commits; + rt.update(|x, tx| { *x = 40.0; tx.motion(Spring::new(0.3, 0.0)); }); + covered_step(&mut rt); + assert_eq!(x(&rt), mid, "nothing moves while covered"); + assert_eq!(rt.stats.commits, commits, "or builds"); + rt.set_live_visible(true); + rt.settle_all(); + rt.frame(1.0 / 120.0); + assert_eq!(x(&rt), 40.0, "uncovering paints where the motion ends"); + assert!(!rt.animating, "with nothing left to play"); +} diff --git a/app/vendor/rune/crates/rune/src/window/state/first_frame.rs b/app/vendor/rune/crates/rune/src/window/state/first_frame.rs new file mode 100644 index 0000000..aba22df --- /dev/null +++ b/app/vendor/rune/crates/rune/src/window/state/first_frame.rs @@ -0,0 +1,260 @@ +//! A window's first frame and its reveals, as one machine: whether the last completed frame holds +//! the current state, the reveal that waits on one, whether the first frame has been reported, +//! and when `on_ready` runs. OpenCode Desktop keeps a new window hidden until its content is +//! ready, or a timeout shows it anyway (`packages/desktop/src/main/windows/reveal-machine.ts`: +//! `loading` → `content-ready` → `shown`, `REVEAL_TIMEOUT_MS`). +//! +//! A reveal requested before the hidden frame completes is held behind the fence, as is a +//! reveal of cached pixels older than the state. Hiding cancels that intent, including when the +//! GPU frame completes later. `on_ready` runs at the first frame, or at its fallback when there is +//! none to wait for: the window is covered, occluded or hidden, or no frame came within +//! `READY_FALLBACK` of opening. + +use std::time::Duration; + +use crate::machine::Effects; +use crate::time::Instant; + +/// How long a hidden frame may prepare before the reveal shows the cached one (a launcher's +/// first frame reports instead). +const PREPARE_FOR: Duration = Duration::from_secs(2); + +/// Whether a completed frame holds the window's current state. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum Frame { + /// No completed frame holds the current state. + Stale, + /// A hidden frame is being prepared: tried again at `retry`, given up at `until`. + Preparing { retry: Instant, until: Instant }, + /// The GPU finished a frame of the current state. `preparing` is the preparation it ended, + /// until the host lands the frame (`Complete`). + Drawn { preparing: Option<(Instant, Instant)> }, +} + +/// Whether a reveal waits for the frame. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum Reveal { + Idle, + Wanted, +} + +/// Whether the window's first frame has been reported (`WindowHandle::is_ready`). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum Notice { + Owed, + Sent, +} + +/// When `on_ready` runs, once per native window. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum OnReady { + /// It waits for the first frame, or for `fallback` when no frame may come. + Waiting { fallback: Option<Instant> }, + Ran, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(in crate::window) struct FirstFrame { + frame: Frame, + reveal: Reveal, + notice: Notice, + on_ready: OnReady, +} + +impl Default for FirstFrame { + fn default() -> Self { + FirstFrame { frame: Frame::Stale, reveal: Reveal::Idle, notice: Notice::Owed, on_ready: OnReady::Waiting { fallback: None } } + } +} + +#[derive(Clone, Copy, Debug)] +pub(super) enum FirstFrameEvent { + /// A hidden frame starts preparing at `now` (a launcher's first, or a reveal's refresh). + Prepare { now: Instant }, + /// The host brings the next try forward to `retry` while the frame prepares. + Retry { retry: Instant }, + /// A reveal: the state changed since the cached frame (`stale`), and whether it shows + /// already. + RequestReveal { stale: bool, visible: bool, now: Instant }, + Hide, + /// The preparation's give-up time passed. + Expire, + /// The GPU finished a frame. + GpuDone, + /// The host lands the finished frame. + Complete, + /// The first frame was reported. + Notified, + /// A frame went by undrawn at `now` because the window isn't on screen. + Skipped { now: Instant }, + /// `on_ready` is taken. + TakeReady, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum FirstFrameEffect { + /// Show the frame now (the cached one, or the one just landed). + Show, + /// Run `on_ready`. + RunOnReady, +} + +impl FirstFrame { + /// A window opened at `now`. + pub(in crate::window) fn opened(now: Instant) -> Self { + FirstFrame { on_ready: OnReady::Waiting { fallback: Some(now + crate::window::surface::win::READY_FALLBACK) }, ..FirstFrame::default() } + } + + pub(super) fn step(&mut self, event: FirstFrameEvent) -> Effects<FirstFrameEffect> { + use FirstFrameEffect::*; + match event { + FirstFrameEvent::Prepare { now } => { + let preparing = (now, now + PREPARE_FOR); + self.frame = match self.frame { + Frame::Drawn { .. } => Frame::Drawn { preparing: Some(preparing) }, + Frame::Stale | Frame::Preparing { .. } => Frame::Preparing { retry: preparing.0, until: preparing.1 }, + }; + Effects::none() + } + FirstFrameEvent::Retry { retry } => { + self.frame = match self.frame { + Frame::Preparing { until, .. } => Frame::Preparing { retry, until }, + Frame::Drawn { preparing: Some((_, until)) } => Frame::Drawn { preparing: Some((retry, until)) }, + frame => frame, + }; + Effects::none() + } + FirstFrameEvent::RequestReveal { visible: true, .. } => Effects::one(Show), + FirstFrameEvent::RequestReveal { stale, visible: false, now } => { + if stale { self.unready(); } + if self.ready() { return Effects::one(Show); } + self.reveal = Reveal::Wanted; + if self.deadline().is_none() { self.step(FirstFrameEvent::Prepare { now }); } + Effects::none() + } + FirstFrameEvent::Hide => { + // After readiness, a cancelled refresh keeps the cached frame and stops retrying. + self.reveal = Reveal::Idle; + if self.notice == Notice::Sent { self.frame = Frame::Drawn { preparing: None }; } + Effects::none() + } + FirstFrameEvent::Expire => { + // The first frame stays hidden (the host reports it); a refresh reveals the + // cached frame rather than nothing. + self.frame = match self.frame { + Frame::Preparing { .. } => Frame::Stale, + Frame::Drawn { .. } => Frame::Drawn { preparing: None }, + Frame::Stale => Frame::Stale, + }; + if self.notice == Notice::Owed { return Effects::none(); } + self.frame = Frame::Drawn { preparing: None }; + self.take_reveal() + } + FirstFrameEvent::GpuDone => { + self.frame = match self.frame { + Frame::Stale => Frame::Drawn { preparing: None }, + Frame::Preparing { retry, until } => Frame::Drawn { preparing: Some((retry, until)) }, + drawn => drawn, + }; + Effects::none() + } + FirstFrameEvent::Complete => { + self.frame = Frame::Drawn { preparing: None }; + self.take_reveal() + } + FirstFrameEvent::Notified => { + self.notice = Notice::Sent; + Effects::none() + } + FirstFrameEvent::Skipped { now } => { + if let OnReady::Waiting { fallback } = &mut self.on_ready { + *fallback = Some(fallback.map_or(now, |at| at.min(now))); + } + Effects::none() + } + FirstFrameEvent::TakeReady => match std::mem::replace(&mut self.on_ready, OnReady::Ran) { + OnReady::Waiting { .. } => Effects::one(RunOnReady), + OnReady::Ran => Effects::none(), + }, + } + } + + fn unready(&mut self) { + self.frame = match self.frame { + Frame::Drawn { preparing: Some((retry, until)) } => Frame::Preparing { retry, until }, + Frame::Drawn { preparing: None } => Frame::Stale, + frame => frame, + }; + } + + fn take_reveal(&mut self) -> Effects<FirstFrameEffect> { + match std::mem::replace(&mut self.reveal, Reveal::Idle) { + Reveal::Wanted => Effects::one(FirstFrameEffect::Show), + Reveal::Idle => Effects::none(), + } + } + + fn shows(effects: Effects<FirstFrameEffect>) -> bool { effects.into_iter().any(|e| e == FirstFrameEffect::Show) } + + /// A completed frame holds the current state. + pub(in crate::window) fn ready(&self) -> bool { matches!(self.frame, Frame::Drawn { .. }) } + /// (next retry, give up) while a hidden frame prepares. + pub(in crate::window) fn deadline(&self) -> Option<(Instant, Instant)> { + match self.frame { + Frame::Stale => None, + Frame::Preparing { retry, until } => Some((retry, until)), + Frame::Drawn { preparing } => preparing, + } + } + /// A reveal waits for the frame. + pub(in crate::window) fn revealing(&self) -> bool { self.reveal == Reveal::Wanted } + /// The first frame has been reported. + pub(in crate::window) fn notified(&self) -> bool { self.notice == Notice::Sent } + + /// A frame went by undrawn because the window isn't on screen, which may last until it is + /// uncovered: `on_ready` stops waiting for a drawn one. + pub(in crate::window) fn skipped(&mut self, now: Instant) { self.step(FirstFrameEvent::Skipped { now }); } + /// When `on_ready` runs without a first frame, until it has run. + pub(in crate::window) fn ready_deadline(&self) -> Option<Instant> { + match self.on_ready { + OnReady::Waiting { fallback } => fallback, + OnReady::Ran => None, + } + } + /// `on_ready` is owed without a first frame. + pub(in crate::window) fn ready_due(&self, now: Instant) -> bool { self.ready_deadline().is_some_and(|at| at <= now) } + /// Takes the first `on_ready`: true once per native window. + pub(in crate::window) fn take_ready(&mut self) -> bool { !self.step(FirstFrameEvent::TakeReady).is_empty() } + /// Whether to show the cached frame now. One already on screen shows at once; its next + /// frame (or retry) draws a stale state, with no first-frame deadline. + pub(in crate::window) fn request_reveal(&mut self, stale: bool, visible: bool, now: Instant) -> bool { + Self::shows(self.step(FirstFrameEvent::RequestReveal { stale, visible, now })) + } + /// After readiness, a canceled refresh keeps the cached frame and stops retrying. + pub(in crate::window) fn hide(&mut self) { self.step(FirstFrameEvent::Hide); } + /// The drawable deadline passed. The first frame stays hidden (the host reports it); a + /// refresh returns whether to reveal the cached frame rather than nothing. + pub(in crate::window) fn expire(&mut self) -> bool { Self::shows(self.step(FirstFrameEvent::Expire)) } + /// A hidden frame that got no drawable leaves the cached one stale. A preparation's deadline + /// retries it; otherwise the host waits, and backs off (`Backoff`). + pub(in crate::window) fn missed(&mut self) { self.unready(); } + /// A hidden frame is prepared from `now`. + pub(in crate::window) fn prepare(&mut self, now: Instant) { self.step(FirstFrameEvent::Prepare { now }); } + /// The host brings the next try forward while the frame prepares. + pub(in crate::window) fn retry_at(&mut self, retry: Instant) { self.step(FirstFrameEvent::Retry { retry }); } + /// The GPU finished the frame it presents. + pub(in crate::window) fn gpu_done(&mut self) { self.step(FirstFrameEvent::GpuDone); } + /// The first frame was reported. + pub(in crate::window) fn notify(&mut self) { self.step(FirstFrameEvent::Notified); } + /// Hidden frames settle, except the refresh a reveal waits on: its new motion runs on. + pub(in crate::window) fn settles(&self) -> bool { !(self.revealing() && self.notified()) } + /// A finished frame still owes the first readiness, or a refresh owes its reveal. + pub(in crate::window) fn pending(&self) -> bool { self.ready() && (!self.notified() || self.revealing()) } + pub(in crate::window) fn complete(&mut self) -> bool { Self::shows(self.step(FirstFrameEvent::Complete)) } + + /// A launcher whose first frame has completed and been reported. + #[cfg(test)] + pub(in crate::window) fn drawn_notified() -> Self { + FirstFrame { frame: Frame::Drawn { preparing: None }, notice: Notice::Sent, ..FirstFrame::default() } + } +} diff --git a/app/vendor/rune/crates/rune/src/window/state/frame.rs b/app/vendor/rune/crates/rune/src/window/state/frame.rs new file mode 100644 index 0000000..23dcd24 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/window/state/frame.rs @@ -0,0 +1,206 @@ +//! Window frame changes app code asks for (`Tx::resize_window`, `Tx::center_window`): where +//! the frame lands, and the spring that carries it there one display frame at a time. + +use rune_motion::Spring; + +/// What handlers asked of their window's frame, merged across a commit. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub(crate) struct FrameRequest { + /// Content size in points. + pub size: Option<(f32, f32)>, + /// Asked with `Tx::resize_window` rather than its `_instant` form. + pub animate: bool, + /// The spring the frame moves on; `None` jumps. Resolved when the runtime latches the + /// request (`Tx::instant`, `Tx::motion`, reduced motion). + pub spring: Option<Spring>, + pub center: bool, +} + +impl FrameRequest { + /// A later request's size replaces an earlier one's; centring sticks. + pub fn merge(self, later: FrameRequest) -> FrameRequest { + let (size, animate, spring) = if later.size.is_some() { (later.size, later.animate, later.spring) } else { (self.size, self.animate, self.spring) }; + FrameRequest { size, animate, spring, center: self.center || later.center } + } +} + +/// Where a frame request lands, in top-down screen points `[x, y, w, h]`. `current` is the +/// window's outer frame, `outer` the outer size for the requested content size, `visible` the +/// usable area of its screen. The top edge stays put, as an AppKit window grows downward; +/// centring follows AppKit's `center` (centred across, a quarter of the spare height above). +/// A frame never moves further off the visible area than it already was. +pub(crate) fn target(current: [f32; 4], outer: Option<(f32, f32)>, center: bool, visible: [f32; 4]) -> [f32; 4] { + let (w, h) = outer.unwrap_or((current[2], current[3])); + let [vx, vy, vw, vh] = visible; + let (mut x, mut y) = (current[0], current[1]); + if center { + x = vx + ((vw - w) / 2.0).floor(); + y = vy + ((vh - h) / 4.0).floor(); + } + let (left, top) = if center { (vx, vy) } else { (current[0].min(vx), current[1].min(vy)) }; + let right = if center { vx + vw } else { (current[0] + current[2]).max(vx + vw) }; + let bottom = if center { vy + vh } else { (current[1] + current[3]).max(vy + vh) }; + x = x.min(right - w).max(left); + y = y.min(bottom - h).max(top); + [x, y, w, h] +} + +/// A frame moving to `to` on a spring, sampled on the host's clock (seconds). Each component +/// is its own closed-form track, so a retarget keeps position and velocity. +#[derive(Clone, Copy, Debug, PartialEq)] +pub(crate) struct FrameAnim { + pub spring: Option<Spring>, + start: f64, + from: [f32; 4], + velocity: [f32; 4], + pub to: [f32; 4], + end: f64, +} + +/// Half a device pixel at 2x: the frame rounds to whole pixels, so closer is landed. +const EPSILON: f32 = 0.25; + +impl FrameAnim { + pub fn new(spring: Option<Spring>, now: f64, from: [f32; 4], velocity: [f32; 4], to: [f32; 4]) -> FrameAnim { + let end = spring.map_or(0.0, |s| (0..4).map(|i| s.settling_duration_from(from[i], velocity[i], to[i], EPSILON)).fold(0.0f32, f32::max)); + FrameAnim { spring, start: now, from, velocity, to, end: now + f64::from(end) } + } + + /// Starts from where an earlier animation is now, at its speed, or from rest at `from`. + pub fn retarget(previous: Option<&FrameAnim>, spring: Option<Spring>, now: f64, from: [f32; 4], to: [f32; 4]) -> FrameAnim { + let (from, velocity) = previous.map_or((from, [0.0; 4]), |p| p.sample(now)); + FrameAnim::new(spring, now, from, if spring.is_some() { velocity } else { [0.0; 4] }, to) + } + + pub fn sample(&self, now: f64) -> ([f32; 4], [f32; 4]) { + let Some(spring) = self.spring.filter(|_| now < self.end) else { return (self.to, [0.0; 4]) }; + let t = (now - self.start).max(0.0) as f32; + let mut at = [0.0; 4]; + let mut velocity = [0.0; 4]; + for i in 0..4 { + (at[i], velocity[i]) = spring.sample(self.from[i], self.velocity[i], self.to[i], t); + } + (at, velocity) + } + + pub fn done(&self, now: f64) -> bool { self.spring.is_none() || now >= self.end } + + /// Moves the whole path by `(dx, dy)`: someone dragged the window mid-flight, and the + /// size carries on from where they put it. + #[cfg_attr(not(target_os = "macos"), allow(dead_code))] + pub fn shift(&mut self, dx: f32, dy: f32) { + for rect in [&mut self.from, &mut self.to] { + rect[0] += dx; + rect[1] += dy; + } + } +} + +/// A requested content size inside the window's minimum and maximum sizes. +pub(crate) fn clamp_size(size: (f32, f32), min: (f32, f32), max: Option<(f32, f32)>) -> (f32, f32) { + let (max_w, max_h) = max.unwrap_or((f32::INFINITY, f32::INFINITY)); + (size.0.max(min.0).min(max_w), size.1.max(min.1).min(max_h)) +} + +/// Rounds a frame to whole device pixels, so content and drawable sizes agree. +pub(crate) fn snap(rect: [f32; 4], scale: f32) -> [f32; 4] { + rect.map(|v| (v * scale).round() / scale) +} + +/// The drawable size a window takes when its scale changes from `from` to `to` and it keeps its +/// logical size, rounded as winit rounds it. Windows sends `ScaleFactorChanged` before it resizes +/// the window, so its `inner_size` is still the old scale's then. +#[cfg_attr(not(target_os = "windows"), allow(dead_code))] +pub(crate) fn rescaled(size: (u32, u32), from: f64, to: f64) -> (u32, u32) { + let scale = |v: u32| (f64::from(v) / from * to).round() as u32; + (scale(size.0), scale(size.1)) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_scale_change_keeps_the_logical_size() { + // 980 x 760 points, dragged from a 150% laptop to a 100% display and back. + assert_eq!(rescaled((1470, 1140), 1.5, 1.0), (980, 760)); + assert_eq!(rescaled((980, 760), 1.0, 1.5), (1470, 1140)); + // Odd scales round to the nearest pixel, and a round trip lands where it began. + assert_eq!(rescaled((1225, 950), 1.25, 1.75), (1715, 1330)); + assert_eq!(rescaled(rescaled((1225, 950), 1.25, 1.75), 1.75, 1.25), (1225, 950)); + assert_eq!(rescaled((1001, 777), 1.0, 1.25), (1251, 971)); + } + + const SCREEN: [f32; 4] = [0.0, 33.0, 1728.0, 1084.0]; + + #[test] + fn a_resize_keeps_the_top_edge_and_stays_on_screen() { + let window = [100.0, 200.0, 400.0, 432.0]; + assert_eq!(target(window, Some((400.0, 632.0)), false, SCREEN), [100.0, 200.0, 400.0, 632.0]); + // Growing past the bottom of the screen lifts the window just enough. + assert_eq!(target(window, Some((400.0, 1000.0)), false, SCREEN), [100.0, 117.0, 400.0, 1000.0]); + // Taller than the screen: the top pins to the visible top. + assert_eq!(target(window, Some((400.0, 2000.0)), false, SCREEN), [100.0, 33.0, 400.0, 2000.0]); + } + + #[test] + fn a_window_already_off_screen_is_not_pulled_back() { + let window = [-200.0, 900.0, 400.0, 400.0]; + // Shrinking leaves it where the user put it. + assert_eq!(target(window, Some((400.0, 300.0)), false, SCREEN), [-200.0, 900.0, 400.0, 300.0]); + // Growing may go no further off than it already was. + assert_eq!(target(window, Some((400.0, 600.0)), false, SCREEN), [-200.0, 700.0, 400.0, 600.0]); + } + + #[test] + fn centring_matches_appkit() { + // Measured from NSWindow.center on a 1728 x 1084 visible frame: a quarter of the spare + // height above, three quarters below. + assert_eq!(target([0.0, 0.0, 400.0, 100.0], Some((400.0, 332.0)), true, [0.0, 0.0, 1728.0, 1084.0]), [664.0, 188.0, 400.0, 332.0]); + assert_eq!(target([0.0, 0.0, 400.0, 100.0], Some((300.0, 932.0)), true, [0.0, 0.0, 1728.0, 1084.0]), [714.0, 38.0, 300.0, 932.0]); + assert_eq!(target([5.0, 5.0, 800.0, 132.0], None, true, SCREEN), [464.0, 33.0 + 238.0, 800.0, 132.0]); + } + + #[test] + fn the_spring_lands_on_the_target_and_retargets_with_its_speed() { + let spring = Some(Spring::new(0.3, 0.0)); + let anim = FrameAnim::new(spring, 1.0, [0.0, 0.0, 400.0, 400.0], [0.0; 4], [0.0, 0.0, 400.0, 600.0]); + let (mid, v) = anim.sample(1.1); + assert!(mid[3] > 400.0 && mid[3] < 600.0 && v[3] > 0.0, "{mid:?} {v:?}"); + assert_eq!(mid[0..3], [0.0, 0.0, 400.0]); + assert!(!anim.done(1.1)); + assert!(anim.done(2.0)); + assert_eq!(anim.sample(2.0).0, anim.to); + let back = FrameAnim::retarget(Some(&anim), spring, 1.1, [9.0; 4], [0.0, 0.0, 400.0, 400.0]); + assert_eq!(back.sample(1.1).0, mid); + assert!(back.sample(1.11).0[3] > mid[3], "keeps moving the way it was going for a moment"); + let jump = FrameAnim::retarget(Some(&anim), None, 1.1, [9.0; 4], [1.0; 4]); + assert!(jump.done(1.1)); + assert_eq!(jump.sample(1.1).0, [1.0; 4]); + } + + #[test] + fn a_drag_mid_flight_keeps_the_new_origin_and_the_size_carries_on() { + let spring = Some(Spring::new(0.3, 0.0)); + let mut anim = FrameAnim::new(spring, 0.0, [10.0, 20.0, 400.0, 400.0], [0.0; 4], [10.0, 20.0, 400.0, 600.0]); + let before = anim.sample(0.1).0; + anim.shift(50.0, -5.0); + let after = anim.sample(0.1).0; + assert_eq!(after, [before[0] + 50.0, before[1] - 5.0, before[2], before[3]]); + assert_eq!(anim.to, [60.0, 15.0, 400.0, 600.0]); + } + + #[test] + fn requested_sizes_stay_inside_the_window_limits() { + assert_eq!(clamp_size((300.0, 900.0), (420.0, 0.0), Some((800.0, 700.0))), (420.0, 700.0)); + assert_eq!(clamp_size((500.0, 100.0), (420.0, 200.0), None), (500.0, 200.0)); + } + + #[test] + fn later_sizes_win_and_centring_sticks() { + let a = FrameRequest { size: Some((1.0, 2.0)), animate: true, spring: None, center: true }; + let b = FrameRequest { size: Some((3.0, 4.0)), animate: false, spring: None, center: false }; + assert_eq!(a.merge(b), FrameRequest { size: Some((3.0, 4.0)), animate: false, spring: None, center: true }); + assert_eq!(b.merge(FrameRequest { center: true, ..Default::default() }), FrameRequest { center: true, ..b }); + } +} diff --git a/app/vendor/rune/crates/rune/src/window/state/life.rs b/app/vendor/rune/crates/rune/src/window/state/life.rs new file mode 100644 index 0000000..b4f1cd4 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/window/state/life.rs @@ -0,0 +1,82 @@ +//! Where a window is in its life: not shown yet, on screen, hidden, or closed for good. The +//! native host and a `--desktop` run's headless window share it, so a close or a show means the +//! same in both. The native host's `Win` holds the window's resources while it has them: a +//! hidden window may have let them go (`App::release_gpu_when_hidden`, Wayland's unmapping). + +use super::sight::{Cover, Sight}; + +/// A window's life. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(crate) enum Life { + /// Not shown yet: created hidden, not created, or its creation failed. + #[default] + Unopened, + /// On screen, possibly minimised, and whether anything says none of it shows (`Sight`). + Shown { sight: Sight }, + /// Hidden after it showed, `at` in `reopen::stamp` order. + Hidden { at: u64 }, + /// Closed without `keep_running`, or its `--frames` trace ended: it never shows again. + Finished, +} + +impl Life { + pub(crate) fn shown(self) -> bool { matches!(self, Life::Shown { .. }) } + + /// Shown, and on screen as far as anything says. + pub(crate) fn uncovered(self) -> bool { self == Life::Shown { sight: Sight::Seen } } + + pub(crate) fn covered(self) -> bool { matches!(self, Life::Shown { sight: Sight::Covered(_) }) } + + /// Shown, and `cover` says none of it shows. + #[cfg_attr(not(target_os = "windows"), allow(dead_code))] + pub(crate) fn covered_by(self, cover: Cover) -> bool { matches!(self, Life::Shown { sight } if sight.has(cover)) } + + pub(crate) fn finished(self) -> bool { self == Life::Finished } + + /// When it last hid, for reopening. + pub(crate) fn hidden_at(self) -> Option<u64> { + match self { + Life::Hidden { at } => Some(at), + _ => None, + } + } + + /// Comes on screen, uncovered. False for a window closed for good, which stays closed. + pub(crate) fn show(&mut self) -> bool { + if self.finished() { return false; } + *self = Life::Shown { sight: Sight::Seen }; + true + } + + /// Leaves the screen; a window that wasn't shown keeps its state and stamp. + pub(crate) fn hide(&mut self, stamp: impl FnOnce() -> u64) { + if self.shown() { *self = Life::Hidden { at: stamp() }; } + } + + /// `cover` starts or stops saying a shown window can't be seen. Returns whether it was + /// covered. A window off screen has nothing to cover: showing uncovers it. + pub(crate) fn cover(&mut self, cover: Cover, on: bool) -> bool { + let Life::Shown { sight } = self else { return false }; + let was = sight.covered(); + *sight = sight.step(cover, on); + was + } + + pub(crate) fn finish(&mut self) { *self = Life::Finished; } + + /// Whether a close runs `App::on_close`: the window is shown, or it isn't and + /// `keep_running` doesn't keep it. A window hidden without its native window closes as + /// one that kept it does; one never created (`exists`) has nothing to close. + pub(crate) fn closes(self, keep_running: bool, exists: bool) -> bool { + match self { + Life::Shown { .. } => true, + Life::Hidden { .. } => !keep_running, + Life::Unopened => exists && !keep_running, + Life::Finished => false, + } + } +} + +#[cfg(test)] +#[path = "life_tests.rs"] +mod tests; diff --git a/app/vendor/rune/crates/rune/src/window/state/life_tests.rs b/app/vendor/rune/crates/rune/src/window/state/life_tests.rs new file mode 100644 index 0000000..3a6fe96 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/window/state/life_tests.rs @@ -0,0 +1,39 @@ +use super::Life; +use super::super::sight::{Cover, Sight}; + +#[test] +fn showing_uncovers_and_hiding_stamps_only_a_shown_window() { + let mut life = Life::Unopened; + life.hide(|| panic!("a window that never showed has no hide to stamp")); + assert_eq!(life, Life::Unopened); + assert!(life.show() && life.uncovered()); + assert!(!life.cover(Cover::System, true) && life.covered()); + life.hide(|| 7); + assert_eq!(life.hidden_at(), Some(7)); + life.hide(|| panic!("hiding again keeps the first stamp")); + assert!(!life.cover(Cover::System, true), "a hidden window has nothing to cover"); + assert_eq!(life, Life::Hidden { at: 7 }); + assert!(life.show() && life.uncovered(), "showing uncovers"); +} + +#[test] +fn a_finished_window_never_shows_or_closes_again() { + let mut life = Life::Shown { sight: Sight::Seen }; + life.finish(); + assert!(!life.show() && life.finished()); + assert!(!life.closes(false, true), "its close hook ran once"); + assert!(!life.cover(Cover::System, false)); +} + +#[test] +fn a_hidden_window_closes_alike_whether_or_not_it_kept_its_window() { + let hidden = Life::Hidden { at: 1 }; + // Released while hidden (`release_gpu_when_hidden`, or Wayland unmapping it): without + // `keep_running` a close still runs `on_close` and ends the window. + assert!(hidden.closes(false, false)); + assert!(hidden.closes(false, true)); + assert!(!hidden.closes(true, false) && !hidden.closes(true, true)); + assert!(Life::Shown { sight: Sight::Seen.step(Cover::System, true) }.closes(true, true)); + assert!(!Life::Unopened.closes(false, false), "nothing to close"); + assert!(Life::Unopened.closes(false, true) && !Life::Unopened.closes(true, true)); +} diff --git a/app/vendor/rune/crates/rune/src/window/state/minimize.rs b/app/vendor/rune/crates/rune/src/window/state/minimize.rs new file mode 100644 index 0000000..1f0ea2c --- /dev/null +++ b/app/vendor/rune/crates/rune/src/window/state/minimize.rs @@ -0,0 +1,137 @@ +//! A minimize the app asked for: one state, and one step saying when a shell carries it out. + +use crate::machine::Effects; +#[cfg(test)] +use crate::runtime::Runtime; +use crate::runtime::RuntimeCore; + +/// A minimize the app asked for, and one a hidden poll holds for the show in the same turn. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(crate) enum Minimize { + /// Nothing asked. + #[default] + None, + /// Asked; a shell minimizes at its next step. + Asked, + /// A hidden poll in a show turn took the ask out of the shell's hands for its own shell, and + /// holds it for after. `field` is what is in the field meanwhile: an ask that arrived while + /// that shell ran (a pop-up's callback, say), which the shell takes first. + Held { field: bool }, +} + +/// What became of a minimize. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum MinimizeEvent { + /// `Tx::minimize`, `AppHandle::minimize`, or the standard minimize key. + Asked, + /// A poll of a hidden window, in a turn that shows it: it holds the ask for after its shell. + HeldForShow, + /// That poll's shell is done: the ask it held is due again. + Returned, + /// A shell took what waits. + Taken, + /// The window hid or closed: it takes what waits back out. + Lost, +} + +/// What a transition asks for. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum MinimizeEffect { + /// Minimize the window now (`Host::minimize`). + Minimize, +} + +impl Minimize { + /// Whether an ask waits at all, held or not. + pub(crate) fn latched(self) -> bool { !matches!(self, Minimize::None) } + + /// What waits for a shell now, dev's `minimize_request`. An ask a hidden poll holds is out + /// of it until that poll's shell is done. + pub(crate) fn field(self) -> bool { + match self { + Minimize::None => false, + Minimize::Asked => true, + Minimize::Held { field } => field, + } + } +} + +/// The one transition. An ask latches in the field. A hidden poll in a show turn takes it and +/// holds it across its own shell, so that shell takes only what arrives meanwhile; when it +/// returns the held ask is due again, and the shell after the show takes it once. Hiding or +/// closing takes what waits back out. +pub(crate) fn step(state: &mut Minimize, event: MinimizeEvent) -> Effects<MinimizeEffect> { + use Minimize as M; + use MinimizeEvent as E; + match (*state, event) { + (M::None, E::Asked) => { *state = M::Asked; Effects::none() } + (M::None, _) => Effects::none(), + (M::Asked, E::Asked) => Effects::none(), + (M::Asked, E::HeldForShow) => { *state = M::Held { field: false }; Effects::none() } + // A second poll in the turn would take the field again, and hold what it finds. + (M::Held { field: true }, E::HeldForShow) => { *state = M::Held { field: false }; Effects::none() } + (M::Held { field: false }, E::HeldForShow) => { *state = M::None; Effects::none() } + (M::Held { field }, E::Asked) => { *state = M::Held { field: true }; Effects::none() } + (M::Asked, E::Taken) => { *state = M::None; Effects::one(MinimizeEffect::Minimize) } + (M::Held { field: true }, E::Taken) => { *state = M::Held { field: false }; Effects::one(MinimizeEffect::Minimize) } + (M::Held { field: false }, E::Taken) => Effects::none(), + (M::Held { .. }, E::Returned) => { *state = M::Asked; Effects::none() } + (M::Asked | M::None, E::Returned) => Effects::none(), + (M::Asked, E::Lost) => { *state = M::None; Effects::none() } + (M::Held { .. }, E::Lost) => { *state = M::Held { field: false }; Effects::none() } + } +} + +impl crate::runtime::RuntimeCore { + /// Steps the minimize the app asked for, saying whether this shell carries it out now. The + /// one effect is a minimize, run once the window is as the turn leaves it. + pub(crate) fn minimize_step(&mut self, event: MinimizeEvent) -> bool { + let mut state = self.host.minimize; + let effects = step(&mut state, event); + self.host.minimize = state; + effects.into_iter().any(|effect| effect == MinimizeEffect::Minimize) + } +} + +/// A hidden poll's ask held across its own shell, without the window or event loop the shell +/// runs in: `Host` steps it around the shell, and a test drives exactly the same steps. +#[derive(Clone, Copy, Debug)] +pub(crate) struct HiddenPoll { + /// The poll runs in a turn that shows the window, so it holds the ask across its shell. + shows: bool, +} + +impl HiddenPoll { + pub(crate) fn new(shows: bool) -> Self { Self { shows } } + + /// Before its shell: the ask is out of the shell's hands; only an ask that arrives during + /// the shell (a pop-up's callback) is in them. + #[cfg(test)] + pub(crate) fn enter<S: 'static>(&self, rt: &mut Runtime<S>) { + self.enter_core(rt.core_mut()); + } + + pub(crate) fn enter_core(&self, rt: &mut RuntimeCore) { + if self.shows { rt.minimize_step(MinimizeEvent::HeldForShow); } + } + + /// After it: the held ask is due again, so the shell after the show takes it. + #[cfg(test)] + pub(crate) fn leave<S: 'static>(&self, rt: &mut Runtime<S>) { + self.leave_core(rt.core_mut()); + } + + pub(crate) fn leave_core(&self, rt: &mut RuntimeCore) { + if self.shows { rt.minimize_step(MinimizeEvent::Returned); } + } +} + +/// A shell step: take what waits, saying whether the window minimizes now. +#[cfg(test)] +pub(crate) fn shell_take<S: 'static>(rt: &mut Runtime<S>) -> bool { + shell_take_core(rt.core_mut()) +} + +pub(crate) fn shell_take_core(rt: &mut RuntimeCore) -> bool { + rt.minimize_step(MinimizeEvent::Taken) +} diff --git a/app/vendor/rune/crates/rune/src/window/state/rest.rs b/app/vendor/rune/crates/rune/src/window/state/rest.rs new file mode 100644 index 0000000..ddcec3f --- /dev/null +++ b/app/vendor/rune/crates/rune/src/window/state/rest.rs @@ -0,0 +1,101 @@ +//! A window's memory at rest. Between frames the renderer keeps what the next one may reuse: +//! spare layer targets (`render::layers`, up to 32 MiB) and `El::cache` textures no layer drew +//! last frame (up to the cache budget), which the screen on show doesn't use; and the scratch +//! targets of its layers, its backdrop copies and blur pyramid, and returned staging chunks (up to +//! 4 MiB), which each of its frames uses again. +//! +//! A window that has drawn nothing for [`REST_AFTER`] (or [`PRESSED_AFTER`] while the system says +//! memory is low) gives back the first kind, keeping the most recently used 8 MiB of spare targets +//! for the menus and hovers of the screen on show: making a target costs the frame that takes it a +//! few ms on an integrated GPU. +//! +//! A window that can't be seen (hidden, minimised, covered whole) gives back both: the frame that +//! shows it again makes its targets afresh. +//! +//! Either way the runtime's caches go back to what the screen on show uses: text layouts the last +//! two commits didn't use and their glyph runs (`TextSystem::rest`), images no element showed in +//! the last frame and the CPU copies of pages left empty (`ImageAtlas::rest`). Then the app's +//! `App::on_rest` runs, for its own caches. + +use std::time::Duration; + +use crate::machine::Effects; +use crate::time::Instant; + +/// How long a window draws nothing before it gives back what its screen doesn't use. +pub(in crate::window) const REST_AFTER: Duration = Duration::from_secs(10); +/// The same while the system says memory is low. +pub(in crate::window) const PRESSED_AFTER: Duration = Duration::from_secs(1); + +/// What the renderer may hold that a rest gives back. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(in crate::window) enum Rest { + /// Nothing: nothing drawn since the window opened, or since it went out of sight. + #[default] + Rested, + /// Drew; gives back what the screen doesn't use at `due`, unless it draws again first. + Drawing { due: Instant }, + /// Gave that back; holds only what the screen on show draws into. + Idle, +} + +/// What happened to the window. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(in crate::window) enum RestEvent { + /// A frame reached the screen at `now`; `low` is the system saying memory is low. + Drew { now: Instant, low: bool }, + /// Hidden, minimised, or covered whole. + Unseen, + /// The loop woke at `now`. + Woke { now: Instant }, +} + +/// What a transition asks for (`Host::give_back`). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(in crate::window) enum RestEffect { + /// What the screen on show doesn't use. + GiveBackUnused, + /// Everything the renderer keeps between frames. + GiveBackAll, +} + +impl Rest { + /// When the loop must wake to give back. + pub(in crate::window) fn deadline(self) -> Option<Instant> { + match self { + Rest::Drawing { due } => Some(due), + Rest::Rested | Rest::Idle => None, + } + } +} + +/// The one transition. A drawn frame sets the deadline afresh; the deadline passing gives back +/// what the screen doesn't use, once; going out of sight gives back everything, once. +pub(in crate::window) fn step(state: &mut Rest, event: RestEvent) -> Effects<RestEffect> { + use RestEvent as E; + match (*state, event) { + (_, E::Drew { now, low }) => { + *state = Rest::Drawing { due: now + if low { PRESSED_AFTER } else { REST_AFTER } }; + Effects::none() + } + (Rest::Drawing { due }, E::Woke { now }) if now >= due => { *state = Rest::Idle; Effects::one(RestEffect::GiveBackUnused) } + (Rest::Drawing { .. } | Rest::Idle, E::Unseen) => { *state = Rest::Rested; Effects::one(RestEffect::GiveBackAll) } + (Rest::Drawing { .. } | Rest::Idle | Rest::Rested, E::Woke { .. }) | (Rest::Rested, E::Unseen) => Effects::none(), + } +} + +/// Whether the system says memory is low (Windows' low-memory resource notification). +#[cfg(target_os = "windows")] +#[allow(unsafe_code)] +pub(in crate::window) fn low_memory() -> bool { + use windows_sys::Win32::System::Memory::{CreateMemoryResourceNotification, LowMemoryResourceNotification, QueryMemoryResourceNotification}; + static EVENT: std::sync::OnceLock<usize> = std::sync::OnceLock::new(); + // SAFETY: the notification handle is made once and never closed; the query writes one BOOL. + let event = *EVENT.get_or_init(|| unsafe { CreateMemoryResourceNotification(LowMemoryResourceNotification) } as usize); + let mut low = 0; + // SAFETY: as above. + event != 0 && unsafe { QueryMemoryResourceNotification(event as _, &mut low) } != 0 && low != 0 +} + +#[cfg(not(target_os = "windows"))] +pub(in crate::window) fn low_memory() -> bool { false } diff --git a/app/vendor/rune/crates/rune/src/window/state/reveal.rs b/app/vendor/rune/crates/rune/src/window/state/reveal.rs new file mode 100644 index 0000000..a55f5a5 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/window/state/reveal.rs @@ -0,0 +1,93 @@ +//! Bringing a window on screen. `AppHandle::show`, `AppHandle::open` (and `activate`) and a +//! launcher's cached reveal are one transition that differs only in what each asks for: focus, +//! restoring a minimised window, and whether the frame shown is already drawn. + +use crate::machine::Effects; + +/// What brings the window on screen. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(in crate::window) enum Reveal { + /// `AppHandle::show`: no focus, and a minimised window stays minimised. + Show, + /// `AppHandle::open` or `activate`: restores a minimised window and focuses it. + Open, + /// A launcher shows the frame it kept rendering while hidden, and takes the keys. + Cached, +} + +/// The window as a reveal finds it. `minimized` is the platform's answer, which on macOS +/// stays true into a deminiaturize (`Win::minimized`). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(in crate::window) enum Found { + /// No native window: never created, released while hidden, or unmapped (Wayland). + Missing, + /// A window off screen: hidden, or not shown yet. + Hidden { minimized: bool }, + Shown { covered: bool, minimized: bool }, +} + +/// What a reveal does, in order. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(in crate::window) enum RevealEffect { + /// Re-reads the accent and scroller style, whose redraw a hidden window may have missed. + ReadSystem, + /// Builds what changed while the window was away and takes its new height before it is + /// ordered in (`Host::build_for_show`). + Build, + /// Applies a placement request. + Place, + /// Creates the window, which comes on screen as it opens. + Create, + OrderIn { focus: bool }, + Unminimize, + /// Paints the settled state of what moved while the window was away in its first frame + /// (guarantee 8), unless `Build` already did. + Settle, + /// It's on screen and uncovered; `live` unless it stays minimised (`Runtime::set_live_visible`). + Shown { live: bool }, + /// The frame a resting wake asked for won't stand for its poll. + CancelTimerFrame, + /// Publishes the native window number. + Number, + /// Focuses it, or on Wayland activates it with the open's token. + Focus, + Redraw, + /// Asks for a frame only when the frame it reveals left motion running. + RedrawIfMoving, +} + +impl Reveal { + pub(in crate::window) fn effects(self, found: Found) -> Effects<RevealEffect> { + use RevealEffect::*; + let mut out = Effects::none(); + let (hidden, covered, minimized) = match found { + Found::Missing => { + if self != Reveal::Cached { out.extend([ReadSystem, Create]); } + return out; + } + Found::Hidden { minimized } => (true, false, minimized), + Found::Shown { covered, minimized } => (false, covered, minimized), + }; + if self == Reveal::Cached { + out.extend([OrderIn { focus: true }, Shown { live: true }, CancelTimerFrame, Number, RedrawIfMoving]); + return out; + } + let restores = self == Reveal::Open && minimized; + out.push(ReadSystem); + if hidden || restores { out.push(Build); } + out.push(Place); + if hidden { out.push(OrderIn { focus: false }); } + if restores { out.push(Unminimize); } + if hidden || covered || restores { out.push(Settle); } + // A minimised window doesn't draw (on macOS occlusion says so instead). + let stays_minimized = minimized && !restores && !cfg!(target_os = "macos"); + out.extend([Shown { live: !stays_minimized }, CancelTimerFrame, Number]); + if self == Reveal::Open { out.push(Focus); } + out.push(Redraw); + out + } +} + +#[cfg(test)] +#[path = "reveal_tests.rs"] +mod tests; diff --git a/app/vendor/rune/crates/rune/src/window/state/reveal_tests.rs b/app/vendor/rune/crates/rune/src/window/state/reveal_tests.rs new file mode 100644 index 0000000..517fd93 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/window/state/reveal_tests.rs @@ -0,0 +1,67 @@ +use super::{Found, Reveal, RevealEffect::*}; + +fn effects(reveal: Reveal, found: Found) -> Vec<super::RevealEffect> { reveal.effects(found).into_iter().collect() } + +const HIDDEN: Found = Found::Hidden { minimized: false }; +const SHOWN: Found = Found::Shown { covered: false, minimized: false }; +const COVERED: Found = Found::Shown { covered: true, minimized: false }; +const MINIMIZED: Found = Found::Shown { covered: false, minimized: true }; + +#[test] +fn show_and_open_bring_a_hidden_window_back_alike_but_for_focus() { + let common = [ReadSystem, Build, Place, OrderIn { focus: false }, Settle, Shown { live: true }, CancelTimerFrame, Number]; + assert_eq!(effects(Reveal::Show, HIDDEN), [&common[..], &[Redraw]].concat()); + assert_eq!(effects(Reveal::Open, HIDDEN), [&common[..], &[Focus, Redraw]].concat()); +} + +#[test] +fn an_open_reads_the_system_style_before_it_builds() { + // A hidden window may have missed a new accent's or scroller style's redraw. `show` re-read + // them before building what changed; `open` built with the stale ones. + for found in [HIDDEN, MINIMIZED, Found::Missing] { + let steps = effects(Reveal::Open, found); + assert_eq!(steps.first(), Some(&ReadSystem), "{found:?}"); + } +} + +#[test] +fn a_cached_reveal_cancels_the_timer_frame_as_every_show_does() { + for found in [HIDDEN, SHOWN] { + assert_eq!(effects(Reveal::Cached, found), [OrderIn { focus: true }, Shown { live: true }, CancelTimerFrame, Number, RedrawIfMoving]); + } + for reveal in [Reveal::Show, Reveal::Open] { + assert!(effects(reveal, SHOWN).contains(&CancelTimerFrame), "{reveal:?}"); + } + assert!(effects(Reveal::Cached, Found::Missing).is_empty(), "a launcher reveal never creates"); +} + +#[test] +fn showing_a_covered_window_settles_however_it_is_asked() { + // Its occlusion event then finds it uncovered already and doesn't settle. + for reveal in [Reveal::Show, Reveal::Open] { + assert!(effects(reveal, COVERED).contains(&Settle), "{reveal:?}"); + } +} + +#[test] +fn showing_a_window_already_on_screen_lands_no_motion() { + for reveal in [Reveal::Show, Reveal::Open] { + let steps = effects(reveal, SHOWN); + assert!(!steps.contains(&Settle) && !steps.contains(&Build) && !steps.iter().any(|e| matches!(e, OrderIn { .. })), "{reveal:?}"); + } +} + +#[test] +fn only_open_restores_a_minimized_window() { + assert_eq!(effects(Reveal::Open, MINIMIZED), + [ReadSystem, Build, Place, Unminimize, Settle, Shown { live: true }, CancelTimerFrame, Number, Focus, Redraw]); + let show = effects(Reveal::Show, MINIMIZED); + assert!(!show.contains(&Unminimize) && !show.contains(&Settle)); + assert!(show.contains(&Shown { live: cfg!(target_os = "macos") }), "it stays minimised, and isn't live but on macOS"); +} + +#[test] +fn a_missing_window_is_created() { + assert_eq!(effects(Reveal::Show, Found::Missing), [ReadSystem, Create]); + assert_eq!(effects(Reveal::Open, Found::Missing), [ReadSystem, Create]); +} diff --git a/app/vendor/rune/crates/rune/src/window/state/sight.rs b/app/vendor/rune/crates/rune/src/window/state/sight.rs new file mode 100644 index 0000000..cad7a4b --- /dev/null +++ b/app/vendor/rune/crates/rune/src/window/state/sight.rs @@ -0,0 +1,49 @@ +//! Whether a shown window can be seen. The system says so (macOS's occlusion state, which +//! winit sends as `WindowEvent::Occluded`); a drawable refused as occluded says it until its +//! retry looks again; on Windows, other windows over the whole of it, minimising it or another +//! virtual desktop say it (`platform::win32::occlusion`, after Chromium's occlusion tracker). +//! Any one covers it, and it shows again once none does. A covered window draws nothing and +//! runs no motion: `poll`, due timers and queued input still run (`covered_step`), and +//! `App::on_visibility` hears it go and come back, as a page's `visibilitychange` does. + +use std::num::NonZeroU8; + +/// What says a shown window can't be seen. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum Cover { + /// The system's occlusion notification. + System = 1, + /// A drawable refused as occluded, before any notification said so. + Surface = 2, + /// Windows: other windows cover it whole, it's minimised, or it's on another virtual desktop. + #[cfg_attr(not(target_os = "windows"), allow(dead_code))] + Windows = 4, +} + +/// A shown window's sight. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum Sight { + Seen, + /// What covers it: a set of `Cover`s, never empty. + Covered(NonZeroU8), +} + +impl Sight { + pub(crate) fn covered(self) -> bool { matches!(self, Sight::Covered(_)) } + + /// Whether `cover` is among what covers it. + #[cfg_attr(not(target_os = "windows"), allow(dead_code))] + pub(crate) fn has(self, cover: Cover) -> bool { matches!(self, Sight::Covered(set) if set.get() & cover as u8 != 0) } + + /// `cover` starts (`on`) or stops covering the window. A notification, either way, + /// supersedes a refused drawable's guess, which only stood in for one. + pub(crate) fn step(self, cover: Cover, on: bool) -> Sight { + let mut bits = match self { + Sight::Seen => 0, + Sight::Covered(set) => set.get(), + }; + if cover != Cover::Surface { bits &= !(Cover::Surface as u8); } + bits = if on { bits | cover as u8 } else { bits & !(cover as u8) }; + NonZeroU8::new(bits).map_or(Sight::Seen, Sight::Covered) + } +} diff --git a/app/vendor/rune/crates/rune/src/window/state/wake.rs b/app/vendor/rune/crates/rune/src/window/state/wake.rs new file mode 100644 index 0000000..690c9a3 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/window/state/wake.rs @@ -0,0 +1,54 @@ +//! What a drain of other threads' requests asks of the window: one decision, `WakeWork`, from +//! the window as the drain finds it and what its updates found. + +/// What a drain asks of the window. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum WakeWork { + /// Nothing: the drain neither polls nor draws. + Nothing, + /// A hidden launcher renders what changed into its cached frame, paced (`refresh_hidden`). + HiddenFrame, + /// A shown window that can't draw — covered, or minimised — runs its turn without a + /// drawable (`covered_frame`). + CoveredFrame, + /// A shown window draws. + Paint, +} + +/// The window as a drain finds it, and what its updates found. +#[derive(Clone, Copy, Debug, Default)] +pub(crate) struct WakeFacts { + /// The window exists to be asked. + pub(crate) window: bool, + /// A macOS launcher, which keeps a cached frame while hidden. + pub(crate) launcher: bool, + /// It shows now (`Life::shown`). + pub(crate) visible: bool, + /// It showed when the drain began, before this turn's requests. + pub(crate) was_shown: bool, + /// An update changed state the view reads. + pub(crate) changed: bool, + /// Only updates that changed nothing woke it. + pub(crate) quiet: bool, + /// The shown window is covered (`Life::covered`). + pub(crate) covered: bool, +} + +impl WakeWork { + /// What this drain asks of the window, decided once. A hidden launcher renders a change into + /// its cached frame however quiet the turn; any other window draws only for a turn that is + /// not quiet. A window that can't draw — covered, or minimised — runs its turn without a + /// drawable, and a launcher's cached frame is paced. `minimized` is asked only when the + /// answer could be a frame, so a quiet turn reads nothing of the window. + pub(crate) fn of(f: WakeFacts, minimized: impl FnOnce() -> bool) -> WakeWork { + if !f.window { return WakeWork::Nothing; } + if f.launcher && !f.visible { + return if f.changed { WakeWork::HiddenFrame } else { WakeWork::Nothing }; + } + if f.quiet { return WakeWork::Nothing; } + // A shown launcher also draws as it shows; any other window draws because it shows. + let asked = if f.launcher { f.changed || (f.was_shown && f.visible) } else { f.visible }; + if !asked { return WakeWork::Nothing; } + if (!f.launcher && f.covered) || minimized() { WakeWork::CoveredFrame } else { WakeWork::Paint } + } +} diff --git a/app/vendor/rune/crates/rune/src/window/state/wake_tests.rs b/app/vendor/rune/crates/rune/src/window/state/wake_tests.rs new file mode 100644 index 0000000..5a57e2f --- /dev/null +++ b/app/vendor/rune/crates/rune/src/window/state/wake_tests.rs @@ -0,0 +1,239 @@ +//! What a drain asks of the window (`WakeWork`) and what a minimize asked for (`Minimize`), +//! each checked against a literal transcription of the fields and branches they replaced: every +//! combination of the facts for the first, every short sequence of events for the second. + +use super::minimize::{HiddenPoll, MinimizeEffect, MinimizeEvent, shell_take, step}; +use super::{Minimize, WakeFacts, WakeWork}; +use crate::Cx; +use crate::el::Tx; +use crate::popup_menu::{PopupAnchor, PopupItem, PopupMenu, Presenter}; +use crate::runtime::Runtime; + +/// Every sequence of `alphabet` up to `len` long that `allowed` lets be extended, prefixes first. +fn walk<E: Copy>(alphabet: &[E], len: usize, mut allowed: impl FnMut(&[E], E) -> bool, mut run: impl FnMut(&[E])) { + let mut seq = Vec::new(); + fn go<E: Copy>(alphabet: &[E], len: usize, seq: &mut Vec<E>, allowed: &mut impl FnMut(&[E], E) -> bool, run: &mut impl FnMut(&[E])) { + run(seq); + if seq.len() == len { return; } + for &e in alphabet { + if !allowed(seq, e) { continue; } + seq.push(e); + go(alphabet, len, seq, allowed, run); + seq.pop(); + } + } + go(alphabet, len, &mut seq, &mut allowed, &mut run); +} + +/// `drain_frame` and the `match` it filtered, as dev had them: a hidden launcher draws a change +/// into its cached frame, a shown window draws unless only a quiet turn woke it, and a window +/// that can't draw — covered, or minimised — runs its turn without one. +fn dev_work(launcher: bool, visible: bool, was_shown: bool, changed: bool, quiet: bool, covered: bool, minimized: bool, window: bool) -> WakeWork { + let framed = if launcher && !visible { changed } else { !quiet && if launcher { changed || was_shown && visible } else { visible } }; + if !window || !framed { return WakeWork::Nothing; } + if launcher && !visible { return WakeWork::HiddenFrame; } + if (!launcher && covered) || minimized { WakeWork::CoveredFrame } else { WakeWork::Paint } +} + +#[test] +fn a_drain_asks_the_window_for_the_same_work_as_dev_for_every_fact() { + let mut cases = 0; + for bits in 0u32..256 { + let fact = |n: u32| bits & (1 << n) != 0; + let (launcher, visible, was_shown, changed, quiet, covered, minimized, window) = + (fact(0), fact(1), fact(2), fact(3), fact(4), fact(5), fact(6), fact(7)); + let work = WakeWork::of(WakeFacts { window, launcher, visible, was_shown, changed, quiet, covered }, || minimized); + assert_eq!(work, dev_work(launcher, visible, was_shown, changed, quiet, covered, minimized, window), "{bits:#010b}"); + cases += 1; + } + assert_eq!(cases, 256, "every combination of the facts"); +} + +/// Every event a minimize meets as the window's call sites send it. +#[derive(Clone, Copy, Debug)] +enum Op { + /// `Tx::minimize`, `AppHandle::minimize`, or the standard key. + Asked, + /// `poll_hidden` in a turn that shows the window: `let minimize = shows && take(...)`. + PollEnter, + /// A shell's minimize step. + Taken, + /// The poll's shell is done: `minimize_request |= minimize`. + PollReturn, + /// `close` or `stop_showing`: `minimize_request = false`. + Lost, +} + +/// dev's minimize latch, `Runtime::minimize_request`, and the local `poll_hidden` kept across +/// its own shell, as dev's call sites left them. +#[derive(Default)] +struct DevMinimize { + /// `minimize_request`. + latch: bool, + /// `let minimize = shows && std::mem::take(&mut self.rt.minimize_request);`, the local the + /// whole shell ran under, callbacks included. + saved: Option<bool>, +} + +impl DevMinimize { + /// The call site as dev wrote it, saying whether it called `minimize()`. + fn apply(&mut self, op: Op) -> bool { + match op { + // `latch_requests`, `AppHandle::minimize`, the standard key: `latch = true`. + Op::Asked => { + self.latch = true; + false + } + // `poll_hidden`, before its shell. + Op::PollEnter => { + self.saved = Some(std::mem::take(&mut self.latch)); + false + } + // `shell`: `let minimize = std::mem::take(&mut self.minimize_request);` then + // `None if minimize => self.minimize()`. + Op::Taken => std::mem::take(&mut self.latch), + // `poll_hidden`, after its shell: `self.rt.minimize_request |= minimize;`. + Op::PollReturn => { + self.latch |= self.saved.take().unwrap_or(false); + false + } + // `close` and `stop_showing`: `minimize_request = false`. + Op::Lost => { + self.latch = false; + false + } + } + } + + /// The ask waiting: in the field, or in the local this poll took out of it. + fn latched(&self) -> bool { self.latch || self.saved.unwrap_or(false) } + + /// What a shell would take now. + fn field(&self) -> bool { self.latch } +} + +fn apply_event(state: &mut Minimize, event: MinimizeEvent) -> bool { + step(state, event).into_iter().any(|effect| effect == MinimizeEffect::Minimize) +} + +fn apply_minimize(state: &mut Minimize, op: Op) -> bool { + let event = match op { + Op::Asked => MinimizeEvent::Asked, + Op::PollEnter => MinimizeEvent::HeldForShow, + Op::Taken => MinimizeEvent::Taken, + Op::PollReturn => MinimizeEvent::Returned, + Op::Lost => MinimizeEvent::Lost, + }; + apply_event(state, event) +} + +#[test] +fn a_shell_minimizes_once_exactly_where_dev_did_for_every_sequence() { + let alphabet = [Op::Asked, Op::PollEnter, Op::Taken, Op::PollReturn, Op::Lost]; + // A poll's shell can't re-enter `Host::poll_hidden`, so no poll starts inside another's + // shell and none returns that never started. A sequence may end with a poll still open: the + // shell after the show runs it later, which is the case r274 is about. + let allowed = |seq: &[Op], op: Op| { + let mut dev = DevMinimize::default(); + for &o in seq { + dev.apply(o); + } + match op { + Op::PollEnter => dev.saved.is_none(), + Op::PollReturn => dev.saved.is_some(), + _ => true, + } + }; + let mut cases = 0; + walk(&alphabet, 6, allowed, |seq| { + cases += 1; + let (mut dev, mut state) = (DevMinimize::default(), Minimize::None); + for (i, &op) in seq.iter().enumerate() { + assert_eq!(apply_minimize(&mut state, op), dev.apply(op), "{seq:?} at {i}"); + assert_eq!(state.latched(), dev.latched(), "{seq:?} at {i}"); + assert_eq!(state.field(), dev.field(), "{seq:?} at {i}"); + } + }); + // Both a closed and an open poll allow four of the five ops to come next. + assert_eq!(cases, (0..=6).map(|k| 4usize.pow(k)).sum::<usize>()); +} + +#[test] +fn a_poll_that_holds_a_minimize_lets_the_shell_after_the_show_take_it() { + // The turn's own order: the poll saves its ask, its shell leaves it, then the show's shell + // takes it, and the window is minimized once — after it is shown. + let mut rt = Runtime::new(0u32, |_: &u32, _: &mut Cx<u32>| crate::el(), (100.0, 100.0), crate::Env::default()); + rt.update(|_, tx| tx.minimize()); + assert!(!rt.minimize_step(MinimizeEvent::HeldForShow), "the poll's shell doesn't take it"); + assert!(!rt.minimize_step(MinimizeEvent::Taken)); + assert!(!rt.minimize_step(MinimizeEvent::Returned), "nothing to carry out at the return"); + assert!(rt.minimize_step(MinimizeEvent::Taken), "the shell after the show takes it"); + assert_eq!(rt.host.minimize, Minimize::None); +} + +#[test] +fn a_hidden_polls_minimize_survives_its_popup_callback_asking_again() { + // The turn a hidden window is woken by Show: its poll asks to minimize and opens a pop-up. + // With no shown window the pop-up answers `None` at once and its callback asks again, so + // the hidden shell's retry takes the callback's ask and the poll's own is still due after + // the show. Drives the real poll, the real pop-up callback and the shell's take/return + // wiring, so a shell that drops the return loses the final minimize here. + let mut rt = Runtime::new(0u32, |_: &u32, _: &mut Cx<u32>| crate::el(), (100.0, 100.0), crate::Env::default()); + rt.poll = Some(|asked: &mut u32, _, tx: &mut Tx| { + if *asked > 0 { return false; } + *asked += 1; + tx.minimize(); + tx.popup_menu( + PopupMenu::new().item(PopupItem::new("ok", "OK")), + PopupAnchor::Point(10.0, 20.0), + |_: &mut u32, picked, tx: &mut Tx| { + assert_eq!(picked, None, "a pop-up with no window answers None"); + tx.minimize(); + }, + ); + true + }); + let poll = HiddenPoll::new(true); + assert!(rt.poll_hidden(), "the hidden poll asked for a change"); + poll.enter(&mut rt); + + // The hidden shell: take, open the waiting pop-up (which asks again), retry. + let mut popup = Presenter::default(); + let mut took = Vec::new(); + loop { + took.push(shell_take(&mut rt)); + let opened = popup.open(&mut rt, None, false); + if !opened && !rt.host.minimize.field() { break; } + } + // The show happens, and the shell after it takes what the poll held. + poll.leave(&mut rt); + took.push(shell_take(&mut rt)); + + assert_eq!(took, [false, true, true], "the retry takes the callback's ask, the show's shell the poll's"); + assert_eq!(rt.host.minimize, Minimize::None); +} + +#[test] +fn a_second_ask_during_a_hidden_poll_is_due_before_the_show() { + let (mut state, mut took) = (Minimize::None, Vec::new()); + for event in [MinimizeEvent::Asked, MinimizeEvent::HeldForShow, MinimizeEvent::Asked, MinimizeEvent::Taken] { + took.push(apply_event(&mut state, event)); + } + assert_eq!(took, [false, false, false, true]); + assert!(!state.field()); +} + +#[test] +fn hiding_and_closing_take_a_minimize_back_out_but_not_one_a_poll_holds() { + let mut state = Minimize::Asked; + assert!(!apply_event(&mut state, MinimizeEvent::Lost)); + assert_eq!(state, Minimize::None); + // dev's local outlived a close inside the poll's shell, and was restored after it. + let mut state = Minimize::None; + assert!(!apply_event(&mut state, MinimizeEvent::Asked)); + assert!(!apply_event(&mut state, MinimizeEvent::HeldForShow)); + assert!(!apply_event(&mut state, MinimizeEvent::Lost)); + assert!(state.latched(), "the held ask is not the field's to take"); + assert!(!apply_event(&mut state, MinimizeEvent::Returned)); + assert_eq!(state, Minimize::Asked); +} diff --git a/app/vendor/rune/crates/rune/src/window/surface.rs b/app/vendor/rune/crates/rune/src/window/surface.rs new file mode 100644 index 0000000..2c3fc0b --- /dev/null +++ b/app/vendor/rune/crates/rune/src/window/surface.rs @@ -0,0 +1,112 @@ +//! Window GPU surface configuration, pacing, backoff, presentation tracking and platform handles. + +use crate::render::{Gpu, Renderer}; +use crate::runtime::RuntimeCore; + +pub(in crate::window) mod backoff; +pub(in crate::window) mod configure; +pub(in crate::window) mod corners; +#[cfg(target_os = "macos")] +pub(in crate::window) mod launch_drawables; +pub(in crate::window) mod loop_frame; +pub(in crate::window) mod native; +pub(in crate::window) mod pacing; +pub(in crate::window) mod presented; +pub(in crate::window) mod redraw; +pub(in crate::window) mod win; + +pub(crate) use backoff::{Backoff, BackoffEffect, BackoffEvent}; +pub(crate) use configure::configure; +#[cfg(target_os = "macos")] +pub(in crate::window) use launch_drawables::LaunchDrawables; +pub(in crate::window) use loop_frame::LoopFrame; +pub(in crate::window) use native::Native; +pub(crate) use pacing::{ + HiddenPace, Missed, TimerFrame, TIMER_FRAME, acquire, acquire_checked, timer_deadline_core, + timer_wants_frame_core, +}; +#[cfg(test)] +pub(crate) use pacing::{ + HIDDEN_REFRESH, OCCLUDED_MAX, OCCLUDED_RETRY, TIMEOUT_RETRY, TIMER_FRAME_STALL, timer_deadline, + timer_wants_frame, wall_wake_deadline, +}; +pub(crate) use presented::Presented; +#[cfg(test)] +pub(in crate::window) use presented::composing; +pub(in crate::window) use redraw::{Redraw, RedrawEffect, RedrawEvent}; +pub(in crate::window) use win::{SurfaceRetries, SurfaceStep, SURFACE_TRIES, Win}; + +#[cfg(test)] +#[path = "surface/backoff_tests.rs"] +mod backoff_tests; +#[cfg(all(test, target_os = "macos"))] +#[path = "surface/occluded_surface_tests.rs"] +mod occluded_surface_tests; + +/// Frames a window's swap chain may hold that the compositor hasn't shown. Windows: one, so a +/// frame shows at the first composition after it's done, and the window waits for room itself +/// (`slot`) rather than in `acquire`. Elsewhere two. +pub(crate) const FRAME_LATENCY: u32 = if cfg!(target_os = "windows") { 1 } else { 2 }; + +/// A vsynced sRGB (or non-sRGB when `srgb_blend` is set) configuration for the surface, and the +/// first alpha mode it supports that composites translucent pixels. +pub(crate) fn surface_config(surface: &wgpu::Surface, adapter: &wgpu::Adapter, (width, height): (u32, u32), srgb_blend: bool) + -> Option<(wgpu::SurfaceConfiguration, Option<wgpu::CompositeAlphaMode>)> { + let mut config = surface.get_default_config(adapter, width.max(1), height.max(1))?; + let caps = surface.get_capabilities(adapter); + let srgb = caps.formats.iter().copied().find(|f| f.is_srgb()).unwrap_or(config.format); + config.format = if srgb_blend { + let non_srgb = srgb.remove_srgb_suffix(); + if caps.formats.contains(&non_srgb) { + non_srgb + } else { + config.view_formats = vec![non_srgb]; + srgb + } + } else { + srgb + }; + // Backdrop copies read the drawable mid-frame (`ActivePass::split`: backdrop blur, effect + // backdrops, rune-fx blend modes). On Metal it costs `framebufferOnly`, but without it they + // quietly fall back. + config.usage |= caps.usages & wgpu::TextureUsages::COPY_SRC; + // A frame that redrew part of itself is copied in whole from the one the renderer keeps + // (`render::damaged`). + config.usage |= caps.usages & wgpu::TextureUsages::COPY_DST; + config.present_mode = wgpu::PresentMode::AutoVsync; + config.desired_maximum_frame_latency = FRAME_LATENCY; + Some((config, crate::render::translucency::mode(surface, adapter))) +} + +/// Follows a blend switch (`Tx::set_srgb_blend`) on a configured surface: reconfigures it for +/// `rt`'s mode at its size and alpha mode, rebuilds `renderer` when its target format changes, +/// and rebuilds the `alpha` pass (when there is one) for the new format. Returns false when the +/// surface can't be configured. +#[cfg_attr(target_arch = "wasm32", allow(dead_code))] +pub(crate) fn reblend_core(surface: &wgpu::Surface, gpu: &Gpu, config: &mut wgpu::SurfaceConfiguration, + renderer: &mut Renderer, alpha: &mut Option<crate::render::surface_alpha::AlphaSurface>, rt: &mut RuntimeCore) -> bool { + let srgb = rt.srgb_blend(); + let Some((next, _)) = surface_config(surface, &gpu.adapter, (config.width, config.height), srgb) else { return false }; + if (config.format, &config.view_formats) != (next.format, &next.view_formats) { + (config.format, config.view_formats) = (next.format, next.view_formats); + if let Err(error) = configure(surface, gpu, config) { + eprintln!("rune: could not reconfigure a surface for a blend switch: {error}"); + return false; + } + } + let target = if srgb { config.format.remove_srgb_suffix() } else { config.format }; + rebuild_renderer_core(&gpu.device, renderer, target, rt); + if alpha.is_some() { + *alpha = Some(crate::render::surface_alpha::AlphaSurface::new(&gpu.device, target, (config.width, config.height))); + } + true +} + +/// Switches `renderer` to `target` when its format changed, keeping its atlases, layer targets +/// and extra pipelines, and sets its blend mode to `rt`'s. +pub(crate) fn rebuild_renderer_core(device: &wgpu::Device, renderer: &mut Renderer, target: wgpu::TextureFormat, rt: &mut RuntimeCore) { + renderer.set_format(device, target); + renderer.set_srgb_blend(rt.srgb_blend()); + // Before the first frame, so its glyph masks go to the GPU fill when the renderer has one. + renderer.attach_text(&mut rt.text.atlas); +} diff --git a/app/vendor/rune/crates/rune/src/window/surface/backoff.rs b/app/vendor/rune/crates/rune/src/window/surface/backoff.rs new file mode 100644 index 0000000..81ed738 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/window/surface/backoff.rs @@ -0,0 +1,116 @@ +//! The window's wait after a frame it couldn't draw: when it may try again, and how long a miss +//! of each kind waits. An occluded surface re-checks on a wait that doubles while it stays +//! covered, so a window nobody sees costs a few failed frames a second instead of a spinning +//! core; a hidden launcher's refresh backs off likewise. A timer pacing motion no display link +//! drives, and a surface being replaced after a failed attempt, wait too, but with no backoff of +//! their own. A frame that presents starts both over. +//! +//! One `step` takes every event that moves them, so the doubling and the resets sit in one place +//! instead of in the draw, the event handlers and the surface replacement. + +use std::time::Duration; + +use super::pacing::{Missed, OCCLUDED_MAX, OCCLUDED_RETRY, TIMEOUT_RETRY}; +use crate::machine::Effects; +use crate::time::Instant; + +/// When the window may draw next, and the waits a miss of each kind gets. One miss is one +/// `step`; the waits behind `at` are its only state that the deadline does not show. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct Backoff { + /// When the window may draw again; `None` when nothing waits. + at: Option<Instant>, + /// The wait an occluded surface's miss gets, held to `OCCLUDED_RETRY..=OCCLUDED_MAX`. + occluded: Duration, + /// The wait a hidden launcher's refresh takes after no drawable, doubling likewise. + hidden: Duration, +} + +impl Default for Backoff { + fn default() -> Self { Backoff { at: None, occluded: OCCLUDED_RETRY, hidden: TIMEOUT_RETRY } } +} + +/// What happened to the window's next frame. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum BackoffEvent { + /// A shown frame got no drawable at `now`. `paced` is a running display link, whose next tick + /// draws the frame itself. + Missed { missed: Missed, paced: bool, now: Instant }, + /// A hidden launcher's refresh got no drawable at `now`. `preparing` is a first frame whose + /// own deadline retries it, which the window waits on once rather than twice. + HiddenMissed { preparing: bool, now: Instant }, + /// The window is tried again at `at` for a reason with no backoff of its own: a surface being + /// replaced, or a timer pacing motion no display link drives (macOS). + At(Instant), + /// The wait ran out, or the window takes the frame anyway: nothing waits now. Both waits keep + /// their backoff: nothing has shown that the surface can draw. + Lapsed, + /// The window's occlusion changed: nothing waits, and the occluded wait starts over. + Uncovered, + /// An overlay is shown or uncovered with a wait still set. It stands, so a covered frame's + /// re-check runs on time, and the occluded wait starts over. + Revealed, + /// A frame presented: nothing waits, and both waits start over. + Presented, +} + +/// What a transition asks the host to do. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum BackoffEffect { + /// No display tick may draw sooner than the wait (`Win::stop_pacing`). + StopPacing, +} + +impl Backoff { + pub(crate) fn step(&mut self, event: BackoffEvent) -> Effects<BackoffEffect> { + match event { + BackoffEvent::Missed { missed, paced, now } => { + self.at = missed.retry(paced, now, &mut self.occluded); + match self.at { + Some(_) => Effects::one(BackoffEffect::StopPacing), + None => Effects::none(), + } + } + BackoffEvent::HiddenMissed { preparing, now } => { + // A first frame's deadline owns its retries; the window waits for none of its own. + self.at = (!preparing).then(|| now + self.hidden); + if !preparing { self.hidden = (self.hidden * 2).min(OCCLUDED_MAX); } + Effects::none() + } + BackoffEvent::At(at) => { + self.at = Some(at); + Effects::none() + } + BackoffEvent::Lapsed => { + self.at = None; + Effects::none() + } + BackoffEvent::Uncovered => { + self.at = None; + self.occluded = OCCLUDED_RETRY; + Effects::none() + } + BackoffEvent::Revealed => { + self.occluded = OCCLUDED_RETRY; + Effects::none() + } + BackoffEvent::Presented => { + self.at = None; + self.occluded = OCCLUDED_RETRY; + self.hidden = TIMEOUT_RETRY; + Effects::none() + } + } + } + + /// When the window may draw again, until it does. + pub(crate) fn deadline(&self) -> Option<Instant> { self.at } + + /// Whether the window is still waiting out a frame it couldn't draw at `now`. + pub(crate) fn waiting(&self, now: Instant) -> bool { self.at.is_some_and(|at| at > now) } + + /// A window whose occluded and hidden waits start at `occluded` and `hidden`, as a long + /// occluded spell or a test leaves them. + #[cfg(test)] + pub(crate) fn seeded(occluded: Duration, hidden: Duration) -> Self { Backoff { at: None, occluded, hidden } } +} diff --git a/app/vendor/rune/crates/rune/src/window/surface/backoff_tests.rs b/app/vendor/rune/crates/rune/src/window/surface/backoff_tests.rs new file mode 100644 index 0000000..443b5c7 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/window/surface/backoff_tests.rs @@ -0,0 +1,264 @@ +use std::time::Duration; + +use super::*; +use crate::time::Instant; + +const MS: Duration = Duration::from_millis(1); + +#[test] +fn an_occluded_miss_backs_off_until_a_frame_presents() { + let t0 = crate::time::now(); + let mut backoff = Backoff::default(); + assert_eq!(backoff.deadline(), None, "nothing waits"); + let miss = |backoff: &mut Backoff, missed, now| { + let effect = backoff.step(BackoffEvent::Missed { missed, paced: false, now }); + (backoff.deadline(), effect.is_empty()) + }; + assert_eq!(miss(&mut backoff, Missed::Occluded, t0), (Some(t0 + OCCLUDED_RETRY), false), "an occluded frame re-checks after the first wait"); + assert!(backoff.waiting(t0) && !backoff.waiting(t0 + OCCLUDED_RETRY), "until it is due"); + assert_eq!(miss(&mut backoff, Missed::Occluded, t0), (Some(t0 + OCCLUDED_RETRY * 2), false), "each miss doubles it"); + for _ in 0..8 { miss(&mut backoff, Missed::Occluded, t0); } + assert_eq!(backoff.deadline(), Some(t0 + OCCLUDED_MAX), "up to a re-check every two seconds"); + backoff.step(BackoffEvent::Lapsed); // The draw clears the wait before it acquires. + backoff.step(BackoffEvent::Presented); + assert_eq!(backoff.deadline(), None, "a frame that presents waits for nothing"); + assert_eq!(miss(&mut backoff, Missed::Occluded, t0).0, Some(t0 + OCCLUDED_RETRY), "and the wait starts over"); +} + +#[test] +fn a_display_link_draws_a_timeout_on_its_next_tick() { + let now = crate::time::now(); + let mut backoff = Backoff::default(); + assert!(backoff.step(BackoffEvent::Missed { missed: Missed::Timeout, paced: true, now }).is_empty()); + assert_eq!(backoff.deadline(), None, "a running link retries on its tick"); + backoff.step(BackoffEvent::Missed { missed: Missed::Timeout, paced: false, now }); + assert_eq!(backoff.deadline(), Some(now + TIMEOUT_RETRY), "an unpaced one waits about a frame"); + backoff.step(BackoffEvent::Missed { missed: Missed::Outdated, paced: false, now }); + assert_eq!(backoff.deadline(), Some(now + OCCLUDED_RETRY), "a lost surface is reconfigured on a slow retry"); +} + +#[test] +fn a_wait_that_lapses_keeps_its_backoff_until_a_frame_presents() { + let now = crate::time::now(); + let mut backoff = Backoff::default(); + backoff.step(BackoffEvent::Missed { missed: Missed::Occluded, paced: false, now }); + backoff.step(BackoffEvent::Missed { missed: Missed::Occluded, paced: false, now }); + backoff.step(BackoffEvent::Lapsed); + assert_eq!(backoff.deadline(), None, "the retry came due"); + backoff.step(BackoffEvent::Missed { missed: Missed::Occluded, paced: false, now }); + assert_eq!(backoff.deadline(), Some(now + OCCLUDED_RETRY * 4), "nothing showed the surface can draw, so it carries on"); +} + +#[test] +fn an_uncovered_window_starts_the_occluded_wait_over_but_keeps_the_hidden_one() { + let now = crate::time::now(); + let mut backoff = Backoff::seeded(OCCLUDED_RETRY * 4, TIMEOUT_RETRY * 4); + backoff.step(BackoffEvent::At(now + TIMER_FRAME)); + assert_eq!(backoff.deadline(), Some(now + TIMER_FRAME), "a timer paces the next frame"); + backoff.step(BackoffEvent::Uncovered); + assert_eq!(backoff.deadline(), None, "an occlusion change waits for nothing"); + backoff.step(BackoffEvent::Missed { missed: Missed::Occluded, paced: false, now }); + assert_eq!(backoff.deadline(), Some(now + OCCLUDED_RETRY), "the occluded wait starts over"); + backoff.step(BackoffEvent::HiddenMissed { preparing: false, now }); + assert_eq!(backoff.deadline(), Some(now + TIMEOUT_RETRY * 4), "the hidden one carries on"); +} + +#[test] +fn a_hidden_refresh_backs_off_but_leaves_its_retry_to_the_first_frame_deadline() { + let now = crate::time::now(); + let mut backoff = Backoff::default(); + backoff.step(BackoffEvent::HiddenMissed { preparing: true, now }); + assert_eq!(backoff.deadline(), None, "a prepared first frame retries it itself"); + backoff.step(BackoffEvent::HiddenMissed { preparing: false, now }); + assert_eq!(backoff.deadline(), Some(now + TIMEOUT_RETRY)); + backoff.step(BackoffEvent::HiddenMissed { preparing: false, now }); + assert_eq!(backoff.deadline(), Some(now + TIMEOUT_RETRY * 2), "and doubles"); + for _ in 0..10 { backoff.step(BackoffEvent::HiddenMissed { preparing: false, now }); } + assert_eq!(backoff.deadline(), Some(now + OCCLUDED_MAX), "up to the same cap"); + backoff.step(BackoffEvent::Presented); + backoff.step(BackoffEvent::HiddenMissed { preparing: false, now }); + assert_eq!(backoff.deadline(), Some(now + TIMEOUT_RETRY), "a presented frame starts it over"); +} + +#[test] +fn only_a_timer_asking_leaves_a_quiet_frame() { + let now = crate::time::now(); + let mut frame = TimerFrame::default(); + assert!(!frame.quiet() && !frame.stalled(now)); + frame.asked_quiet(now); + assert!(frame.quiet(), "only a timer asked for the frame"); + frame.drawn(); + assert!(frame.quiet(), "a draw that returns before its decision leaves it"); + assert!(frame.take_quiet() && !frame.quiet(), "the draw takes it once"); + frame.asked_quiet(now); + frame.no_longer_quiet(); + assert!(!frame.quiet(), "a window event says something else asked"); + frame.asked_quiet(now + MS); + assert!(frame.take_quiet(), "a later timer asks quietly again"); +} + +#[test] +fn a_stalled_frame_is_asked_for_again_from_now_and_stays_quiet() { + let now = crate::time::now(); + let mut frame = TimerFrame::default(); + frame.asked_quiet(now); + assert!(!frame.stalled(now + TIMER_FRAME_STALL - MS) && frame.stalled(now + TIMER_FRAME_STALL)); + frame.stalled_again(now + TIMER_FRAME_STALL); + assert!(!frame.stalled(now + TIMER_FRAME_STALL), "the next ask starts its bound over"); + assert!(frame.quiet(), "and only a timer asked"); + assert_eq!(frame.wait(Some(now), now + TIMER_FRAME_STALL), Some(now + 2 * TIMER_FRAME_STALL)); +} + +/// The fields this machine replaced, kept apart exactly as they were: `Win::retry`, +/// `occluded_wait` and `hidden_wait`, and `quiet` beside the frame a timer owed. Every sequence of +/// events fed to both must leave the same deadline, the same waits, and the same quiet frame. +#[derive(Clone, Copy, Debug)] +struct Apart { + retry: Option<Instant>, + occluded: Duration, + hidden: Duration, + quiet: bool, + owed: Option<Instant>, +} + +/// The retry rule as the window had it before this machine, copied here literally: the reference +/// must not call the production code it checks, or a change to the doubling would move both sides. +fn retry(missed: Missed, paced: bool, now: Instant, occluded_wait: &mut Duration) -> Option<Instant> { + match missed { + Missed::Occluded => { + let at = now + (*occluded_wait).clamp(OCCLUDED_RETRY, OCCLUDED_MAX); + *occluded_wait = (*occluded_wait * 2).min(OCCLUDED_MAX); + Some(at) + } + Missed::Timeout if paced => None, + Missed::Timeout => Some(now + TIMEOUT_RETRY), + Missed::Outdated | Missed::Unconfigured => Some(now + OCCLUDED_RETRY), + } +} + +impl Apart { + fn new() -> Self { Apart { retry: None, occluded: OCCLUDED_RETRY, hidden: TIMEOUT_RETRY, quiet: false, owed: None } } + + fn step(&mut self, step: Step, now: Instant) { + match step { + Step::Occluded => self.retry = retry(Missed::Occluded, false, now, &mut self.occluded), + Step::Timeout => self.retry = retry(Missed::Timeout, false, now, &mut self.occluded), + Step::PacedTimeout => self.retry = retry(Missed::Timeout, true, now, &mut self.occluded), + Step::Outdated => self.retry = retry(Missed::Outdated, false, now, &mut self.occluded), + Step::Unconfigured => self.retry = retry(Missed::Unconfigured, false, now, &mut self.occluded), + Step::Hidden => { + self.retry = Some(now + self.hidden); + self.hidden = (self.hidden * 2).min(OCCLUDED_MAX); + } + Step::HiddenPreparing => self.retry = None, + Step::At => self.retry = Some(now + TIMER_FRAME), + Step::Lapsed => self.retry = None, + Step::Uncovered => { + self.retry = None; + self.occluded = OCCLUDED_RETRY; + } + // A frame drawn: `draw` clears the wait before it takes its drawable. + Step::Present => { + self.retry = None; + self.occluded = OCCLUDED_RETRY; + self.hidden = TIMEOUT_RETRY; + } + Step::TimerAsk => { + self.owed.get_or_insert(now); + self.quiet = true; + } + Step::TimerStallAgain => self.owed = Some(now), + Step::TimerDrawn => self.owed = None, + Step::QuietCleared | Step::TakeQuiet => self.quiet = false, + } + } +} + +/// A frame timer, a window event and a present arrive in any order; every sequence of these +/// steps through both the machine and the fields it replaced, checked at each one. +#[derive(Clone, Copy, Debug)] +enum Step { + Occluded, + Timeout, + PacedTimeout, + Outdated, + Unconfigured, + Hidden, + HiddenPreparing, + At, + Lapsed, + Uncovered, + Present, + TimerAsk, + TimerStallAgain, + TimerDrawn, + QuietCleared, + TakeQuiet, +} + +fn every_sequence(alphabet: &[Step], max: usize, mut f: impl FnMut(&[Step])) { + fn walk(alphabet: &[Step], seq: &mut Vec<Step>, max: usize, f: &mut impl FnMut(&[Step])) { + f(seq); + if seq.len() == max { return; } + for step in alphabet { + seq.push(*step); + walk(alphabet, seq, max, f); + seq.pop(); + } + } + walk(alphabet, &mut Vec::new(), max, &mut f); +} + +fn holds_up(seq: &[Step]) { + let t0 = crate::time::now(); + let (mut backoff, mut frame, mut apart) = (Backoff::default(), TimerFrame::default(), Apart::new()); + for (k, step) in seq.iter().enumerate() { + let now = t0 + MS * (11 * k as u32); + match *step { + Step::Occluded => { backoff.step(BackoffEvent::Missed { missed: Missed::Occluded, paced: false, now }); } + Step::Timeout => { backoff.step(BackoffEvent::Missed { missed: Missed::Timeout, paced: false, now }); } + Step::PacedTimeout => { backoff.step(BackoffEvent::Missed { missed: Missed::Timeout, paced: true, now }); } + Step::Outdated => { backoff.step(BackoffEvent::Missed { missed: Missed::Outdated, paced: false, now }); } + Step::Unconfigured => { backoff.step(BackoffEvent::Missed { missed: Missed::Unconfigured, paced: false, now }); } + Step::Hidden => { backoff.step(BackoffEvent::HiddenMissed { preparing: false, now }); } + Step::HiddenPreparing => { backoff.step(BackoffEvent::HiddenMissed { preparing: true, now }); } + Step::At => { backoff.step(BackoffEvent::At(now + TIMER_FRAME)); } + Step::Lapsed => { backoff.step(BackoffEvent::Lapsed); } + Step::Uncovered => { backoff.step(BackoffEvent::Uncovered); } + Step::Present => { + backoff.step(BackoffEvent::Lapsed); + backoff.step(BackoffEvent::Presented); + } + Step::TimerAsk => frame.asked_quiet(now), + Step::TimerStallAgain => frame.stalled_again(now), + Step::TimerDrawn => frame.drawn(), + Step::QuietCleared => frame.no_longer_quiet(), + Step::TakeQuiet => { frame.take_quiet(); } + } + apart.step(*step, now); + assert_eq!(backoff.deadline(), apart.retry, "{seq:?} at {k}"); + assert_eq!(backoff.waiting(now), apart.retry.is_some_and(|at| at > now), "{seq:?} at {k}"); + // The waits behind the deadline, which no query shows: a miss of each kind now, on both. + let mut missed = backoff; + missed.step(BackoffEvent::Missed { missed: Missed::Occluded, paced: false, now }); + let mut wait = apart.occluded; + assert_eq!(missed.deadline(), retry(Missed::Occluded, false, now, &mut wait), "the occluded wait after {seq:?} at {k}"); + let mut hidden = backoff; + hidden.step(BackoffEvent::HiddenMissed { preparing: false, now }); + assert_eq!(hidden.deadline(), Some(now + apart.hidden), "the hidden wait after {seq:?} at {k}"); + // The quiet timer frame, as the loop waits on it. + assert_eq!(frame.quiet(), apart.quiet, "quiet after {seq:?} at {k}"); + assert_eq!(frame.stalled(now), apart.owed.is_some_and(|at| now >= at + TIMER_FRAME_STALL), "{seq:?} at {k}"); + assert_eq!(frame.wait(Some(now), now), Some(apart.owed.map_or(now, |at| at + TIMER_FRAME_STALL)), "{seq:?} at {k}"); + } +} + +#[test] +fn every_order_of_events_leaves_the_same_deadline_and_waits() { + let all = [Step::Occluded, Step::Timeout, Step::PacedTimeout, Step::Outdated, Step::Unconfigured, Step::Hidden, Step::HiddenPreparing, Step::At, + Step::Lapsed, Step::Uncovered, Step::Present, Step::TimerAsk, Step::TimerStallAgain, Step::TimerDrawn, Step::QuietCleared, Step::TakeQuiet]; + every_sequence(&all, 3, holds_up); + let common = [Step::Occluded, Step::Unconfigured, Step::Hidden, Step::Present, Step::Uncovered, Step::TimerAsk, Step::TimerStallAgain, + Step::QuietCleared, Step::TakeQuiet]; + every_sequence(&common, 6, holds_up); +} diff --git a/app/vendor/rune/crates/rune/src/window/surface/configure.rs b/app/vendor/rune/crates/rune/src/window/surface/configure.rs new file mode 100644 index 0000000..ad878b9 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/window/surface/configure.rs @@ -0,0 +1,78 @@ +//! Configuring a window's or overlay's surface, and saying so when it can't. + +use crate::render::Gpu; + +/// Configures `surface`, returning wgpu's error instead of panicking in its default handler, +/// so a surface the driver refuses (an overlay's XWayland window on NVIDIA, hex#979) costs +/// only its owner. The message names the configuration for logs. +/// +/// A lost device fails here even when wgpu reports nothing: it drops the `DeviceLost` that +/// `Surface::configure` returns (wgpu-30.0.1 `handle_error_inner`, "will be surfaced via +/// callback") without recording the surface's error sink, so the surface has no presentation +/// and the next `get_current_texture` panics ("Surface is not configured for presentation"). +#[cfg(not(target_arch = "wasm32"))] +pub(crate) fn configure(surface: &wgpu::Surface, gpu: &Gpu, config: &wgpu::SurfaceConfiguration) -> Result<(), String> { + if gpu.is_lost() { return Err(lost_device(config)); } + let validation = gpu.device.push_error_scope(wgpu::ErrorFilter::Validation); + let internal = gpu.device.push_error_scope(wgpu::ErrorFilter::Internal); + surface.configure(&gpu.device, config); + // `Device::destroy` only marks the device invalid: its lost callback runs when the device + // next maintains itself, at the soonest a poll. Without this, a device destroyed before it + // reported itself configures nothing while `is_lost` still reads false, and the drawable + // its surface is asked for panics. + rune_gpu::health::poll(&gpu.device, wgpu::PollType::Poll).ok(); + let error = pollster::block_on(internal.pop()).or(pollster::block_on(validation.pop())); + if gpu.is_lost() { return Err(lost_device(config)); } + match error { + None => { configured(surface); Ok(()) } + Some(error) => { + let text = error.to_string(); + let cause = text.lines().map(str::trim).filter(|line| !line.is_empty() && *line != "Caused by:").collect::<Vec<_>>().join(": "); + Err(format!("{cause} ({}x{}, {:?}, {:?}, {:?})", config.width, config.height, config.format, config.alpha_mode, config.present_mode)) + } + } +} + +/// Each surface's last successful configuration, numbered across all of them: a configure makes a +/// new swap chain (new back buffers), so a frame that drew partly into the last one must draw +/// whole into this one (`Damage`). Wherever the configure came from: a resize, a blend switch, +/// a frame-latency change, or `acquire` retrying an outdated surface inside a frame. +#[cfg(not(target_arch = "wasm32"))] +static CONFIGURED: std::sync::Mutex<Vec<(usize, u64)>> = std::sync::Mutex::new(Vec::new()); +#[cfg(not(target_arch = "wasm32"))] +static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1); + +#[cfg(not(target_arch = "wasm32"))] +fn configured(surface: &wgpu::Surface) { + let key = std::ptr::from_ref(surface) as usize; + let n = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + let mut all = CONFIGURED.lock().unwrap(); + match all.iter_mut().find(|(k, _)| *k == key) { + Some(e) => e.1 = n, + None => all.push((key, n)), + } + // Surfaces long gone: their numbers are never read again. + if all.len() > 64 { all.remove(0); } +} + +/// The number of `surface`'s last successful configuration (0 before any). A surface dropped and +/// another made at its address configures before it draws, so it never reads the old number. +#[cfg(not(target_arch = "wasm32"))] +#[cfg_attr(not(target_os = "windows"), allow(dead_code))] +pub(crate) fn generation(surface: &wgpu::Surface) -> u64 { + let key = std::ptr::from_ref(surface) as usize; + CONFIGURED.lock().unwrap().iter().find(|(k, _)| *k == key).map_or(0, |e| e.1) +} + +/// A configuration that never reached the surface because its device is gone. +#[cfg(not(target_arch = "wasm32"))] +fn lost_device(config: &wgpu::SurfaceConfiguration) -> String { + format!("the GPU device was lost ({}x{}, {:?}, {:?}, {:?})", config.width, config.height, config.format, config.alpha_mode, config.present_mode) +} + +/// The browser reports surface errors asynchronously; there is nothing to catch here. +#[cfg(target_arch = "wasm32")] +pub(crate) fn configure(surface: &wgpu::Surface, gpu: &Gpu, config: &wgpu::SurfaceConfiguration) -> Result<(), String> { + surface.configure(&gpu.device, config); + Ok(()) +} diff --git a/app/vendor/rune/crates/rune/src/window/surface/corners.rs b/app/vendor/rune/crates/rune/src/window/surface/corners.rs new file mode 100644 index 0000000..7c23fe7 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/window/surface/corners.rs @@ -0,0 +1,92 @@ +//! A Wayland client-side frame's rounded corners: whether this window has any, at what radius, +//! and the pass that clears the content outside them (`render::csd_corners`). +//! +//! Under `sctk-adwaita` a decorated window's frame rounds the window's four corners while it +//! floats, and squares them when the window is maximized or tiled. The frame's own subsurfaces +//! carry the headerbar above the content and the shadow and one-point border around it, so the +//! content only has to leave the bottom two corners: outside the arc the frame's border covers, +//! the surface must composite nothing rather than its background. + +use super::Win; +use crate::window::host::Host; + +impl Host { + /// Whether a client-side frame draws this window's decorations, whatever state the frame is in + /// (a maximized, tiled or fullscreen window keeps its frame), asked of winit after the window's + /// first configure: a compositor that draws the decorations itself (server side, the default on + /// KDE, sway and Hyprland) never has one, and its windows keep exactly the surface they had. + /// + /// A frame's window keeps its surface's pixels' alpha for the corner arcs the content clears + /// (`window/host/create.rs`), and is still opaque to Rune: its clear colour, its root fill and its + /// device are an opaque window's, and only those corner pixels are transparent (`winit` keeps + /// the rest of the window an opaque region). + #[cfg_attr(not(all(unix, not(target_os = "macos"), not(target_os = "ios"), not(target_os = "android"))), allow(unused_variables))] + pub(in crate::window) fn client_frame(&self, window: &winit::window::Window) -> bool { + #[cfg(all(unix, not(target_os = "macos"), not(target_os = "ios"), not(target_os = "android")))] + if self.wayland { + return winit::platform::wayland::WindowExtWayland::has_client_side_frame(window); + } + false + } + + /// Whether this window is decorated at all on Wayland, and so may have a client-side frame: + /// what the surface is asked for, without asking winit which decorations the compositor + /// settled on (`client_frame`). + pub(in crate::window) fn rounds_corners(&self) -> bool { + #[cfg(all(unix, not(target_os = "macos"), not(target_os = "ios"), not(target_os = "android")))] + return self.wayland && !self.options.borderless; + #[cfg(not(all(unix, not(target_os = "macos"), not(target_os = "ios"), not(target_os = "android"))))] + false + } + + /// The radius, in device pixels, the window's client-side frame leaves the content's bottom + /// corners at. Zero when it leaves them square (the window is maximized or tiled), when no + /// such frame draws it, and when its surface can't composite translucent pixels: the content + /// then paints as it always did, square to its edges. + #[cfg_attr( + not(all(unix, not(target_os = "macos"), not(target_os = "ios"), not(target_os = "android"))), + allow(unused_variables) + )] + pub(in crate::window) fn corner_radius(&self, window: &Win) -> f32 { + #[cfg(all(unix, not(target_os = "macos"), not(target_os = "ios"), not(target_os = "android")))] + if self.rounds_corners() && window.config.alpha_mode != wgpu::CompositeAlphaMode::Opaque { + let radius = winit::platform::wayland::WindowExtWayland::content_corner_radius(&*window.window); + return radius * self.app.rt().env.scale; + } + 0. + } +} + +/// Prepares `pass` to clear `size` at `radius` device pixels, making it (or another for a surface +/// that changed its format) when it must. +pub(in crate::window) fn prepare( + pass: &mut Option<crate::render::csd_corners::CsdCorners>, + device: &wgpu::Device, + queue: &wgpu::Queue, + size: (u32, u32), + format: wgpu::TextureFormat, + radius: f32, +) { + let stale = pass.as_ref().is_some_and(|pass| pass.format() != format); + if stale { + *pass = None; + } + let pass = pass.get_or_insert_with(|| crate::render::csd_corners::CsdCorners::new(device, format)); + pass.prepare(queue, size, radius); +} + +/// Clears outside a window's rounded bottom corners, after everything else that drew into +/// `target`. +pub(in crate::window) fn draw( + pass: Option<&crate::render::csd_corners::CsdCorners>, + encoder: &mut wgpu::CommandEncoder, + target: &wgpu::TextureView, + radius: f32, +) { + if radius <= 0. { + return; + } + if let Some(pass) = pass { + pass.draw(encoder, target); + } +} diff --git a/app/vendor/rune/crates/rune/src/window/surface/launch_drawables.rs b/app/vendor/rune/crates/rune/src/window/surface/launch_drawables.rs new file mode 100644 index 0000000..fbfbd17 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/window/surface/launch_drawables.rs @@ -0,0 +1,35 @@ +use std::time::Duration; +use crate::time::Instant; + +/// A new window's surface keeps two drawables until the window first rests on screen, or for +/// its first second there, then its configured three. CAMetalLayer makes another window-sized +/// drawable whenever a frame is acquired while the others are still held, and keeps it. Launch +/// frames overlap that way, presented before the window server shows the window or while their +/// shaders compile, which left a settled window one drawable (about 12 MB at 980x760) heavier. +/// Raising the count later makes no drawable until a frame needs it. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(in crate::window) enum LaunchDrawables { + Capped { steady: u32, since: Option<Instant> }, + Steady, +} + +impl LaunchDrawables { + pub(in crate::window) const LAUNCH: Duration = Duration::from_secs(1); + + /// Caps a new surface's `config` at two drawables. + pub(in crate::window) fn cap(config: &mut wgpu::SurfaceConfiguration) -> Self { + if config.desired_maximum_frame_latency <= 1 { return Self::Steady; } + let steady = std::mem::replace(&mut config.desired_maximum_frame_latency, 1); + Self::Capped { steady, since: None } + } + + /// After a frame on screen: the frame latency to configure, once, when launch ends. + pub(in crate::window) fn settle(&mut self, idle: bool, now: Instant) -> Option<u32> { + let Self::Capped { steady, since } = self else { return None }; + let since = *since.get_or_insert(now); + if !idle && now.duration_since(since) < Self::LAUNCH { return None; } + let steady = *steady; + *self = Self::Steady; + Some(steady) + } +} diff --git a/app/vendor/rune/crates/rune/src/window/surface/loop_frame.rs b/app/vendor/rune/crates/rune/src/window/surface/loop_frame.rs new file mode 100644 index 0000000..5fdf0d1 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/window/surface/loop_frame.rs @@ -0,0 +1,30 @@ +//! A frame only a loop asked for: a spinner's next dot, a shimmer's next step. The runtime +//! samples the loops into the instances they drew and nothing else runs (`Runtime::loop_step`: +//! no poll, view, layout or paint), and the window redraws and presents only where they draw +//! (`Renderer::arm_loop`). Anything that reached the window since its last frame (input, a +//! wake, a request, an assistive client's action) makes the next one an ordinary frame, so +//! nothing waits behind a loop. + +#[derive(Default)] +pub(in crate::window) struct LoopFrame { + touched: bool, +} + +impl LoopFrame { + /// Something other than the window's own frames reached it. + pub(in crate::window) fn touched(&mut self) { self.touched = true; } + + /// A frame begins: whether only its loops asked for it since the last. Counts afresh. + pub(in crate::window) fn only_loops(&mut self) -> bool { !std::mem::replace(&mut self.touched, false) } +} + +/// frame-profile, `RUNE_MISS_LOOP_FRAMES=<n>`: this loop-only frame is the nth since the last +/// forced miss, and acts as if its drawable never came (a diagnostic). +#[cfg(feature = "frame-profile")] +pub(in crate::window) fn forced_miss() -> bool { + use std::sync::atomic::{AtomicU64, Ordering}; + static EVERY: std::sync::OnceLock<u64> = std::sync::OnceLock::new(); + static SEEN: AtomicU64 = AtomicU64::new(0); + let every = *EVERY.get_or_init(|| rune_core::env::var("RUNE_MISS_LOOP_FRAMES").and_then(|v| v.parse().ok()).unwrap_or(0)); + every > 0 && SEEN.fetch_add(1, Ordering::Relaxed) % every == every - 1 +} diff --git a/app/vendor/rune/crates/rune/src/window/surface/native.rs b/app/vendor/rune/crates/rune/src/window/surface/native.rs new file mode 100644 index 0000000..f10232f --- /dev/null +++ b/app/vendor/rune/crates/rune/src/window/surface/native.rs @@ -0,0 +1,105 @@ +//! What a window holds per OS: on macOS its display link, present hook, panel and native +//! views; on Linux desktops its activation helper; on Windows its first-frame cloak; elsewhere +//! nothing. + +#[cfg(target_os = "macos")] +use std::sync::Arc; + +/// Dropped before the surface and the window, so its AppKit observers and views go while both +/// still exist. +#[cfg(target_os = "macos")] +pub(in crate::window) struct Native { + pub(in crate::window) pacing: Option<crate::platform::display_link::DisplayLink>, + /// Reports when each drawable reached the screen, while tracing or for `shadow`. + pub(in crate::window) present: Option<crate::frame::present_time::metal::LayerHook>, + /// The log `present` and `shadow` report to (traced, or an untraced one that only re-samples + /// the shadow), kept for the window's life: a surface replaced after a device loss attaches + /// the new hook to the same log, so the shadow keeps re-sampling. + pub(in crate::window) present_log: Option<Arc<crate::frame::present_time::metal::Log>>, + /// Re-samples a transparent window's system shadow once its new pixels land. + pub(in crate::window) shadow: Option<crate::platform::macos::window_shape::Shadow>, + pub(in crate::window) panel: Option<crate::platform::macos::Panel>, + /// `El::system_material` views behind the Metal layer. + pub(in crate::window) materials: crate::system_material::macos::Materials, + pub(in crate::window) help: crate::platform::macos::help::NativeHelp, + /// Redraws on full screen changes. + pub(in crate::window) full_screen: crate::window::chrome::mac::FullScreenWatch, + /// Fn presses, which winit doesn't send, while the app wants modifier keys. + pub(in crate::window) fn_key: Option<crate::input::fn_key::FnKey>, + /// The new window's first frames, which may draw before AppKit reports it on screen. + pub(in crate::window) prime: Prime, + pub(in crate::window) launch_drawables: super::LaunchDrawables, + /// Forgets the window's traffic-light spot. + pub(in crate::window) _spot: crate::platform::macos::traffic_lights::Spot, +} + +/// Whether a frame may presume the window on screen before AppKit says so: `Host::try_create`'s +/// frame and one follow-up do, since the window reaches the screen with that turn's Core +/// Animation commit. Once AppKit answers, or the window leaves the screen, none does. +#[cfg(target_os = "macos")] +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(in crate::window) enum Prime { + Launching { left: u8 }, + Steady, +} + +#[cfg(target_os = "macos")] +impl Prime { + pub(in crate::window) fn launching() -> Self { Prime::Launching { left: 2 } } + + pub(in crate::window) fn presumes(self) -> bool { matches!(self, Prime::Launching { .. }) } + + /// A frame drew presuming it shown. + pub(in crate::window) fn spend(&mut self) { + if let Prime::Launching { left } = *self { + *self = if left > 1 { Prime::Launching { left: left - 1 } } else { Prime::Steady }; + } + } + + pub(in crate::window) fn stop(&mut self) { *self = Prime::Steady; } +} + +#[cfg(all(test, target_os = "macos"))] +#[path = "native_tests.rs"] +mod tests; + +#[cfg(all(unix, not(target_os = "macos"), not(target_os = "ios"), not(target_os = "android")))] +#[derive(Default)] +pub(in crate::window) struct Native { + pub(in crate::window) activator: Option<crate::platform::activation::Activator>, +} + +#[cfg(target_os = "windows")] +#[derive(Default)] +pub(in crate::window) struct Native { + /// Holds a window that's just been shown off screen until its frame lands. + pub(in crate::window) cloak: crate::platform::win32::Cloak, + /// The frame without a title bar a window with `App::titlebar` has. + pub(in crate::window) frame: Option<crate::platform::win32::CustomFrame>, + /// Whether other windows cover it whole, as the last frame that looked found (`look`). + pub(in crate::window) look: crate::window::win32::look::Look, + /// Whether its swap chain can take the next frame (`slot`). + pub(in crate::window) slot: crate::window::win32::slot::Slot, + /// What its last frames changed, so the next redraws only that (`damage`). + pub(in crate::window) damage: crate::window::win32::damage::Damage, + /// Whether the CPU renderer or the GPU draws its frames (`cpu_frame`). + pub(in crate::window) mode: crate::window::win32::handover::SurfaceMode, + /// Whether its accessibility adapter waits for the first frame (`Host::a11y_after_frame`). + pub(in crate::window) a11y_start: A11yStart, + /// Playing clips shown on their own layer under the UI (`video_layer`). + pub(in crate::window) video_layers: crate::window::win32::video_layer::VideoLayers, +} + +/// When a window's UI Automation adapter is made: with the window (a screen reader is running), +/// or on the loop's first idle turn after the first frame. +#[cfg(target_os = "windows")] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(in crate::window) enum A11yStart { + #[default] + Made, + AfterFirstFrame, +} + +#[cfg(not(any(target_os = "macos", target_os = "windows", all(unix, not(target_os = "ios"), not(target_os = "android")))))] +#[derive(Default)] +pub(in crate::window) struct Native; diff --git a/app/vendor/rune/crates/rune/src/window/surface/native_tests.rs b/app/vendor/rune/crates/rune/src/window/surface/native_tests.rs new file mode 100644 index 0000000..7933879 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/window/surface/native_tests.rs @@ -0,0 +1,16 @@ +use super::Prime; + +#[test] +fn a_new_window_presumes_itself_shown_for_two_frames_or_until_stopped() { + let mut prime = Prime::launching(); + assert!(prime.presumes()); + prime.spend(); + assert!(prime.presumes(), "the follow-up frame still presumes"); + prime.spend(); + assert_eq!(prime, Prime::Steady); + prime.spend(); + assert_eq!(prime, Prime::Steady); + let mut stopped = Prime::launching(); + stopped.stop(); + assert!(!stopped.presumes()); +} diff --git a/app/vendor/rune/crates/rune/src/window/surface/occluded_surface_tests.rs b/app/vendor/rune/crates/rune/src/window/surface/occluded_surface_tests.rs new file mode 100644 index 0000000..d6d9a54 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/window/surface/occluded_surface_tests.rs @@ -0,0 +1,145 @@ +//! A Metal surface whose window reports itself covered, with no window server needed: the layer's +//! delegate stands in for the backing view, and is its own window. + +#![allow(unsafe_code)] + +use std::sync::{Arc, atomic::{AtomicUsize, Ordering}}; +use std::time::Duration; + +use super::*; +use crate::frame::surface_stats::SurfaceMeter; +use crate::render::Gpu; +use objc2::{ClassType, define_class, msg_send, rc::Retained, runtime::{AnyClass, AnyObject, NSObject}}; + +/// The fake window's `occlusionState`: 0 covered, 2 (`NSWindowOcclusionStateVisible`) shown. +static OCCLUSION: AtomicUsize = AtomicUsize::new(0); + +define_class!( + #[unsafe(super(NSObject))] + #[name = "RuneFakeOccludedView"] + struct FakeView; + + impl FakeView { + #[unsafe(method(window))] + fn window(&self) -> *const Self { self } + + #[unsafe(method(occlusionState))] + fn occlusion_state(&self) -> usize { OCCLUSION.load(Ordering::Relaxed) } + } +); + +/// An hour covered costs no failed `get_current_texture` (each leaks a texture id in +/// wgpu-core 30.0.1) and a re-check at most every two seconds; uncovered, it draws. +#[test] +fn an_occluded_surface_never_asks_wgpu_and_draws_once_visible() { + // SAFETY: `FakeView` is a registered `NSObject` subclass; `+new` returns a retained instance. + let view: Retained<FakeView> = unsafe { msg_send![FakeView::class(), new] }; + // SAFETY: `+[CAMetalLayer new]` allocates and returns a retained `CAMetalLayer`. + let layer: Retained<AnyObject> = unsafe { msg_send![AnyClass::get(c"CAMetalLayer").expect("QuartzCore"), new] }; + // SAFETY: `layer` and `view` are live ObjC objects owned by this test; `view` outlives `layer`. + let _: () = unsafe { msg_send![&*layer, setDelegate: &*view] }; + let instance = Gpu::instance(); + let target = wgpu::SurfaceTargetUnsafe::CoreAnimationLayer(Retained::as_ptr(&layer) as *mut std::ffi::c_void); + // SAFETY: `layer` is a live `CAMetalLayer` that outlives `surface` in this test. + let surface = unsafe { instance.create_surface_unsafe(target) }.expect("a Metal layer surface"); + let gpu = match Gpu::try_new(instance, Some(&surface)) { + Ok(gpu) => gpu, + Err(error) => return eprintln!("skipped: {error}"), + }; + let Some((config, _)) = surface_config(&surface, &gpu.adapter, (64, 64), false) else { + return eprintln!("skipped: the adapter can't present to a Metal layer"); + }; + surface.configure(&gpu.device, &config); + + OCCLUSION.store(0, Ordering::Relaxed); + // SAFETY: `layer` is a live `CAMetalLayer` whose delegate is the live `FakeView` above. + assert!(unsafe { crate::platform::macos::layer_occluded(&layer) }); + let mut meter = SurfaceMeter::new("occluded", Arc::default()); + let start = crate::time::now(); + let (mut at, mut backoff, mut checks) = (start, Backoff::default(), 0u64); + while at < start + Duration::from_secs(3600) { + if let Ok(_frame) = acquire(&surface, &gpu, &config, true, 1, &mut meter) { panic!("an occluded surface got a drawable"); } + checks += 1; + backoff.step(BackoffEvent::Missed { missed: Missed::Occluded, paced: false, now: at }); + at = backoff.deadline().expect("occlusion re-checks on a deadline"); + } + let totals = meter.totals(); + assert_eq!(totals.failed(), 0, "wgpu was asked for drawables it refuses as occluded"); + assert_eq!(totals.skipped, checks); + assert!(checks <= 3600 / 2 + 3, "{checks} re-checks in an hour occluded"); + + OCCLUSION.store(2, Ordering::Relaxed); + let frame = acquire(&surface, &gpu, &config, true, 1, &mut meter).expect("a visible surface gets a drawable"); + let target = frame.texture.create_view(&Default::default()); + let mut encoder = gpu.device.create_command_encoder(&Default::default()); + encoder.begin_render_pass(&wgpu::RenderPassDescriptor { + color_attachments: &[Some(wgpu::RenderPassColorAttachment { + view: &target, depth_slice: None, resolve_target: None, + ops: wgpu::Operations { load: wgpu::LoadOp::Clear(wgpu::Color::BLACK), store: wgpu::StoreOp::Store }, + })], + ..Default::default() + }); + gpu.queue.submit([encoder.finish()]); + gpu.queue.present(frame); + meter.presented(); + assert_eq!((meter.totals().presents, meter.totals().failed()), (1, 0)); +} + +define_class!( + #[unsafe(super(NSObject))] + #[name = "RuneFakeCoveredView"] + struct CoveredView; + + impl CoveredView { + #[unsafe(method(window))] + fn window(&self) -> *const Self { self } + + #[unsafe(method(occlusionState))] + fn occlusion_state(&self) -> usize { 0 } + } +); + +/// A window's first frame draws before the window server reports the window on screen: +/// `PresumeShown` gets it a drawable from wgpu, and puts the layer's own delegate back. +#[test] +fn a_presumed_shown_surface_gets_its_first_drawable_while_reported_covered() { + // SAFETY: `CoveredView` is a registered `NSObject` subclass; `+new` returns a retained instance. + let view: Retained<CoveredView> = unsafe { msg_send![CoveredView::class(), new] }; + // SAFETY: `+[CAMetalLayer new]` allocates and returns a retained `CAMetalLayer`. + let layer: Retained<AnyObject> = unsafe { msg_send![AnyClass::get(c"CAMetalLayer").expect("QuartzCore"), new] }; + // SAFETY: `layer` and `view` are live ObjC objects owned by this test; `view` outlives `layer`. + let _: () = unsafe { msg_send![&*layer, setDelegate: &*view] }; + let instance = Gpu::instance(); + let target = wgpu::SurfaceTargetUnsafe::CoreAnimationLayer(Retained::as_ptr(&layer) as *mut std::ffi::c_void); + // SAFETY: `layer` is a live `CAMetalLayer` that outlives `surface` in this test. + let surface = unsafe { instance.create_surface_unsafe(target) }.expect("a Metal layer surface"); + let gpu = match Gpu::try_new(instance, Some(&surface)) { + Ok(gpu) => gpu, + Err(error) => return eprintln!("skipped: {error}"), + }; + let Some((config, _)) = surface_config(&surface, &gpu.adapter, (64, 64), false) else { + return eprintln!("skipped: the adapter can't present to a Metal layer"); + }; + surface.configure(&gpu.device, &config); + let mut meter = SurfaceMeter::new("first", Arc::default()); + assert!(acquire(&surface, &gpu, &config, true, 1, &mut meter).is_err(), "a covered window gets no drawable"); + + let shown = crate::platform::macos::PresumeShown::new(&surface).expect("a Metal surface"); + assert!(!crate::platform::macos::surface_occluded(&surface)); + // SAFETY: `layer` is a live `CAMetalLayer` while `shown` holds its stand-in delegate alive. + let stand_in: *const AnyObject = unsafe { msg_send![&*layer, delegate] }; + // SAFETY: `+[NSNull null]` returns the process-lifetime singleton pointer. + let null: *const AnyObject = unsafe { msg_send![AnyClass::get(c"NSNull").expect("Foundation"), null] }; + // SAFETY: `stand_in` is the live `ShownWindow` delegate installed by `PresumeShown::new`. + let action: *const AnyObject = unsafe { msg_send![stand_in, actionForLayer: &*layer, forKey: std::ptr::null::<AnyObject>()] }; + assert_eq!(action, null, "PresumeShown suppresses implicit Core Animation actions"); + let frame = acquire(&surface, &gpu, &config, true, 1, &mut meter).expect("the first frame's drawable"); + drop(frame); + drop(shown); + + // SAFETY: `layer` is still alive and `PresumeShown::drop` restored its previous delegate. + let delegate: *const AnyObject = unsafe { msg_send![&*layer, delegate] }; + assert!(std::ptr::eq(delegate, Retained::as_ptr(&view).cast()), "the layer's delegate is back"); + assert!(crate::platform::macos::surface_occluded(&surface)); + assert_eq!(meter.totals().failed(), 0, "wgpu was never asked while covered"); +} diff --git a/app/vendor/rune/crates/rune/src/window/surface/pacing.rs b/app/vendor/rune/crates/rune/src/window/surface/pacing.rs new file mode 100644 index 0000000..5d0c4f4 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/window/surface/pacing.rs @@ -0,0 +1,304 @@ +//! Pacing for frames no display tick drives: timer deadlines, a hidden host's refresh pace, +//! and what follows a frame whose drawable never came. + +use std::time::Duration; + +use crate::frame::surface_stats::SurfaceMeter; +use crate::render::Gpu; +use crate::runtime::{Runtime, RuntimeCore}; +use crate::time::Instant; + +/// The runtime's next timer, on the wall clock that started with the host. +#[cfg(test)] +#[inline(always)] +pub(crate) fn wall_wake_deadline<S>(rt: &Runtime<S>) -> Option<Instant> { + wall_wake_deadline_core(rt.core()) +} + +fn wall_wake_deadline_core(rt: &RuntimeCore) -> Option<Instant> { + rt.wall_start?.checked_add(Duration::try_from_secs_f64(rt.wake_deadline()?).ok()?) +} + +/// The runtime's next timer as a host with no display link to take it waits for it: hidden, +/// covered, faded out or unpaced. A timer due within a frame interval of the last poll +/// (`Tx::wake_after(Duration::ZERO)` asks for the next frame) waits for that interval, so a +/// poll that keeps asking steps at most once per `TIMER_FRAME` and never spins the loop. +/// Motion's own frames (a loop's step, a video's next picture) come when due: held a frame +/// after each poll, they'd drift later every frame and drop one every half second. +#[cfg_attr(not(test), allow(dead_code))] +#[inline(always)] +pub(crate) fn timer_deadline<S>(rt: &Runtime<S>) -> Option<Instant> { + timer_deadline_core(rt.core()) +} + +pub(crate) fn timer_deadline_core(rt: &RuntimeCore) -> Option<Instant> { + let wall = |t: f64| rt.wall_start?.checked_add(Duration::try_from_secs_f64(t).ok()?); + let polled = wall(rt.polled_at()); + let timer = rt.poll_wake_deadline().and_then(wall).map(|due| polled.map_or(due, |polled| due.max(polled + TIMER_FRAME))); + timer.into_iter().chain(rt.motion_wake_deadline().and_then(wall)).min() +} + +/// Paces the frame a hidden host keeps ready to show (a launcher's cached pixels, a retained +/// overlay's commit). A change after a quiet spell renders at once; later ones wait until +/// `HIDDEN_REFRESH` has passed since the last render, so state that changes many times a +/// second costs a few builds a second while nobody sees them. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(crate) enum HiddenPace { + /// Nothing rendered since it was hidden: a change renders at once. + #[default] + Fresh, + /// The last hidden render was `at`, and nothing waits. + Rendered { at: Instant }, + /// A change waits for `HIDDEN_REFRESH` after the render at `at`. + Waiting { at: Instant }, +} + +pub(crate) const HIDDEN_REFRESH: Duration = Duration::from_millis(250); + +/// What happens to a hidden host's pace. +#[derive(Clone, Copy, Debug)] +pub(crate) enum PaceEvent { + /// Its state changed at `now`. + Changed(Instant), + /// It checks, at `now`, whether the change that waits is due. + Due(Instant), + /// A hidden frame rendered what had changed, at `now`. + Rendered(Instant), + /// It showed, or hid again: the host draws its own frames until the next change. + Reset, +} + +impl HiddenPace { + /// The pace after `event`, and whether a change renders now. + pub(crate) fn step(self, event: PaceEvent) -> (HiddenPace, bool) { + match (self, event) { + (pace, PaceEvent::Changed(now)) if pace.ready(now) => (pace.settled(), true), + (HiddenPace::Rendered { at } | HiddenPace::Waiting { at }, PaceEvent::Changed(_)) => (HiddenPace::Waiting { at }, false), + (HiddenPace::Waiting { at }, PaceEvent::Due(now)) if at + HIDDEN_REFRESH <= now => (HiddenPace::Rendered { at }, true), + (_, PaceEvent::Rendered(now)) => (HiddenPace::Rendered { at: now }, false), + (_, PaceEvent::Reset) => (HiddenPace::Fresh, false), + (pace, PaceEvent::Changed(_) | PaceEvent::Due(_)) => (pace, false), + } + } + + /// A change that renders now stops any waiting. + fn settled(self) -> HiddenPace { + match self { + HiddenPace::Waiting { at } => HiddenPace::Rendered { at }, + pace => pace, + } + } + + /// Whether a change at `now` renders now. Otherwise it waits for `deadline`. + pub(crate) fn changed(&mut self, now: Instant) -> bool { self.apply(PaceEvent::Changed(now)) } + /// Whether a change at `now` would render at once. + pub(crate) fn ready(&self, now: Instant) -> bool { + match *self { + HiddenPace::Fresh => true, + HiddenPace::Rendered { at } | HiddenPace::Waiting { at } => now >= at + HIDDEN_REFRESH, + } + } + /// When the change that waits renders. + pub(crate) fn deadline(&self) -> Option<Instant> { + match *self { + HiddenPace::Waiting { at } => Some(at + HIDDEN_REFRESH), + _ => None, + } + } + /// Whether the change that waits is due at `now`; it stops waiting either way it renders. + pub(crate) fn take_due(&mut self, now: Instant) -> bool { self.apply(PaceEvent::Due(now)) } + /// A hidden frame rendered what had changed. + pub(crate) fn rendered(&mut self, now: Instant) { self.apply(PaceEvent::Rendered(now)); } + /// Shown, the host draws its own frames; hidden again, the first change renders at once. + pub(crate) fn reset(&mut self) { self.apply(PaceEvent::Reset); } + + fn apply(&mut self, event: PaceEvent) -> bool { + let (next, render) = self.step(event); + *self = next; + render + } +} + +/// Whether a timer asks for the frame after one just presented. Only a surface whose display +/// link paces it (`next_frame` is its next tick) takes a timer due by then as a frame request; +/// anywhere else the timer waits in `timer_deadline`, so it never turns the loop by itself. +#[cfg_attr(not(test), allow(dead_code))] +#[inline(always)] +pub(crate) fn timer_wants_frame<S>(rt: &Runtime<S>, next_frame: Option<Instant>) -> bool { + timer_wants_frame_core(rt.core(), next_frame) +} + +pub(crate) fn timer_wants_frame_core(rt: &RuntimeCore, next_frame: Option<Instant>) -> bool { + next_frame.is_some_and(|next| wall_wake_deadline_core(rt).is_some_and(|due| due <= next)) +} + +/// How long a frame a due timer asked for may wait for the window to draw it. Wayland withholds +/// `RedrawRequested` while a surface frame callback is outstanding, and a compositor may not send +/// one for a fully covered surface for a long time; the wait is an occluded surface's first +/// re-check. +pub(crate) const TIMER_FRAME_STALL: Duration = OCCLUDED_RETRY; + +/// The frame a due timer asked a shown window for, until it draws it, and whether only that timer +/// asked for it. An overdue timer whose frame never comes would otherwise keep turning the loop +/// (`new_events` asks again, no frame arrives, and `wake_deadline` returns the past timer), so +/// after `TIMER_FRAME_STALL` the timer runs covered instead and the next ask starts over. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(crate) struct TimerFrame { + /// When a due timer asked for a frame the window hasn't drawn yet. + owed: Option<Instant>, + /// Only a timer asked for it, so the frame may draw what is already on screen instead of + /// taking a drawable. A window event, or any wake but the display tick, says otherwise. It + /// outlives `drawn`: a draw that returns before its decision leaves the frame for a later one. + quiet: bool, +} + +impl TimerFrame { + /// A due timer asked for a frame: only it did, if nothing else has since the last frame. + pub(crate) fn asked_quiet(&mut self, now: Instant) { + self.owed.get_or_insert(now); + self.quiet = true; + } + + /// The frame asked for at the stall bound ran covered in its place, and the next is asked for + /// from `now`; only a timer asking still holds. + pub(crate) fn stalled_again(&mut self, now: Instant) { self.owed = Some(now); } + + /// The frame came, or ran covered in its place: nothing waits for it now. + pub(crate) fn drawn(&mut self) { self.owed = None; } + + /// Something other than a timer asked for a frame: the one that follows draws in full. + pub(crate) fn no_longer_quiet(&mut self) { self.quiet = false; } + + /// Only a timer asked for the frame that is next to draw. + #[cfg_attr(not(target_os = "macos"), allow(dead_code))] + pub(crate) fn quiet(&self) -> bool { self.quiet } + + /// The frame reaches its draw decision: whether only a timer asked for it. + pub(crate) fn take_quiet(&mut self) -> bool { std::mem::take(&mut self.quiet) } + + /// Whether the frame asked for is still outstanding after the stall bound. + pub(crate) fn stalled(&self, now: Instant) -> bool { + self.owed.is_some_and(|asked| now >= asked + TIMER_FRAME_STALL) + } + + /// The runtime's next timer as the host waits for it: one already due while its frame is + /// outstanding waits out the stall instead, so the loop sleeps rather than waking at once + /// for a frame that can't come. + pub(crate) fn wait(&self, due: Option<Instant>, now: Instant) -> Option<Instant> { + match (due, self.owed) { + (Some(due), Some(asked)) if due <= now => Some(asked + TIMER_FRAME_STALL), + (due, _) => due, + } + } +} + +/// Why a surface gave no drawable this frame. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum Missed { + /// Nothing of the window is on screen (covered, or its displays asleep). + Occluded, + /// No drawable was free, or acquisition failed some other passing way. + Timeout, + /// Outdated or lost, and reconfiguring didn't bring it back. + Outdated, + /// The surface refused its configuration. wgpu panics on its next drawable, so its owner + /// must drop it. + Unconfigured, +} + +/// The first re-check of an occluded surface. Its occlusion notification usually redraws it +/// first; this catches one that never arrives. Consecutive misses back off to `OCCLUDED_MAX`. +pub(crate) const OCCLUDED_RETRY: Duration = Duration::from_millis(250); +pub(crate) const OCCLUDED_MAX: Duration = Duration::from_secs(2); +/// An unpaced surface's retry after a drawable timeout: about one frame. +pub(crate) const TIMEOUT_RETRY: Duration = Duration::from_millis(16); +/// Motion's frame interval when no display link paces a surface. +pub(crate) const TIMER_FRAME: Duration = Duration::from_micros(16_667); + +impl Missed { + pub(in crate::window) fn of(status: wgpu::CurrentSurfaceTexture) -> Result<wgpu::SurfaceTexture, Missed> { + use wgpu::CurrentSurfaceTexture as S; + match status { + S::Success(f) | S::Suboptimal(f) => Ok(f), + S::Occluded => Err(Missed::Occluded), + S::Outdated | S::Lost => Err(Missed::Outdated), + S::Timeout | S::Validation => Err(Missed::Timeout), + } + } + + /// When to try again after a frame this surface couldn't draw, or `None` to sleep until an + /// event (a display tick, a notification, input or a timer). There is no `ControlFlow::Poll` + /// here: retrying at once is what spins a core while a window is occluded or its displays + /// sleep. A display link that is still running retries a timeout on its next tick. + /// `occluded_wait` is the caller's backoff (`Backoff`), held to + /// `OCCLUDED_RETRY..=OCCLUDED_MAX`; an occluded miss waits it out, then doubles it. + pub(crate) fn retry(self, paced: bool, now: Instant, occluded_wait: &mut Duration) -> Option<Instant> { + match self { + Missed::Occluded => { + let at = now + (*occluded_wait).clamp(OCCLUDED_RETRY, OCCLUDED_MAX); + *occluded_wait = (*occluded_wait * 2).min(OCCLUDED_MAX); + Some(at) + } + Missed::Timeout if paced => None, + Missed::Timeout => Some(now + TIMEOUT_RETRY), + Missed::Outdated | Missed::Unconfigured => Some(now + OCCLUDED_RETRY), + } + } +} + +/// The next drawable. An outdated or lost surface is reconfigured and tried again, up to +/// `reconfigures` times, synchronously; every other miss returns at once. On macOS a surface +/// wgpu would call occluded is never asked: each failed `get_current_texture` leaks a texture +/// id in wgpu-core 30.0.1. +pub(crate) fn acquire(surface: &wgpu::Surface, gpu: &Gpu, config: &wgpu::SurfaceConfiguration, configured: bool, reconfigures: u32, + meter: &mut SurfaceMeter) -> Result<wgpu::SurfaceTexture, Missed> { + acquire_checked(surface, gpu, config, configured, reconfigures, meter, true) +} + +/// `acquire`, skipping the occlusion check when the caller has just read the window hosting +/// the surface as visible (`check_occlusion` false). `configured` is whether the surface's last +/// configuration took: one that didn't has no presentation, and wgpu panics on its next +/// drawable (`Missed::Unconfigured`), so it is never asked. +pub(crate) fn acquire_checked(surface: &wgpu::Surface, gpu: &Gpu, config: &wgpu::SurfaceConfiguration, configured: bool, mut reconfigures: u32, + meter: &mut SurfaceMeter, check_occlusion: bool) -> Result<wgpu::SurfaceTexture, Missed> { + #[cfg(not(target_os = "macos"))] + let _ = check_occlusion; + // A lost device configures nothing, and wgpu drops the error that says so: like a surface + // whose configuration failed, it has no presentation to take a drawable from. + if gpu.is_lost() || !configured { + meter.failed(Missed::Unconfigured); + return Err(Missed::Unconfigured); + } + #[cfg(target_os = "macos")] + if check_occlusion && crate::platform::macos::surface_occluded(surface) { + meter.skipped(); + return Err(Missed::Occluded); + } + loop { + let status = Missed::of(surface.get_current_texture()); + if let Err(missed) = status { meter.failed(missed); } + match status { + // A surface that won't take its configuration again is reported rather than + // panicking in wgpu's default error handler. + Err(Missed::Outdated) if reconfigures > 0 => { + if let Err(error) = super::configure(surface, gpu, config) { + eprintln!("rune: a surface refused its configuration: {error}"); + return Err(Missed::Unconfigured); + } + reconfigures -= 1; + #[cfg(feature = "frame-profile")] + crate::frame::live_log::reconfigured(); + } + Err(Missed::Outdated) => { + return Err(match super::configure(surface, gpu, config) { + Ok(()) => Missed::Outdated, + Err(error) => { + eprintln!("rune: a surface refused its configuration: {error}"); + Missed::Unconfigured + } + }); + } + other => return other, + } + } +} diff --git a/app/vendor/rune/crates/rune/src/window/surface/presented.rs b/app/vendor/rune/crates/rune/src/window/surface/presented.rs new file mode 100644 index 0000000..83cdcac --- /dev/null +++ b/app/vendor/rune/crates/rune/src/window/surface/presented.rs @@ -0,0 +1,104 @@ +#[cfg(test)] +use crate::compose::Compositor; +use crate::runtime::{Runtime, RuntimeCore}; + +/// Whether a compositor draws motion of its own (`Compositor::animating`): its window never +/// rests, and a due timer draws. +#[cfg(test)] +pub(in crate::window) fn composing<S: 'static>(comp: Option<&dyn Compositor<S>>) -> bool { + comp.is_some_and(|c| c.animating()) +} + +/// Whether a compositor drew anything of its own last frame (`Compositor::draws_own`): only then +/// does its frame never count as the same as the one before. +#[cfg(test)] +#[allow(dead_code)] +pub(in crate::window) fn composed<S: 'static>(comp: Option<&dyn Compositor<S>>) -> bool { + comp.is_some_and(|c| c.draws_own()) +} +/// What an idle window's last frame drew. A timer that wakes the window builds a frame before +/// taking a drawable; when it would draw these same pixels, nothing is acquired or presented. +/// A compositor's frame lets the window rest but never counts as the same: it may draw +/// differently from the same instances. +pub(crate) struct Presented { + instances: Vec<crate::render::Instance>, + clear: [f32; 4], + size: (u32, u32), + format: wgpu::TextureFormat, + srgb: bool, + scale: f32, + transparent: bool, + composed: bool, +} + +impl Presented { + /// After a frame: whether the window goes idle, and the frame it rests on until anything + /// asks for another. `moving`: motion, a compositor or a window frame in flight; `next_tick`: + /// the running display link's next tick; `rests`: the window may rest on this frame (shown, + /// and no trace counting frames). A frame that left work for the next one doesn't settle: + /// a compositor may update or invalidate the state while it draws. + #[cfg(test)] + #[inline(always)] + pub(in crate::window) fn settle<S: 'static>(this: &mut Option<Self>, rt: &Runtime<S>, config: &wgpu::SurfaceConfiguration, + moving: bool, next_tick: Option<crate::time::Instant>, rests: bool, composed: bool) -> bool { + Self::settle_core(this, rt.core(), config, moving, next_tick, rests, composed) + } + + pub(crate) fn settle_core(this: &mut Option<Self>, rt: &RuntimeCore, config: &wgpu::SurfaceConfiguration, + moving: bool, next_tick: Option<crate::time::Instant>, rests: bool, composed: bool) -> bool { + let idle = !(moving || rt.stale() || rt.live_pending() || rt.host.window_frame.is_some() + || super::pacing::timer_wants_frame_core(rt, next_tick)); + if idle && rests { Self::record_core(this, rt, config, composed) } else { *this = None } + idle + } + + #[cfg_attr(not(test), allow(dead_code))] + #[inline(always)] + pub(crate) fn record<S: 'static>(this: &mut Option<Self>, rt: &Runtime<S>, config: &wgpu::SurfaceConfiguration, composed: bool) { + Self::record_core(this, rt.core(), config, composed); + } + + pub(crate) fn record_core(this: &mut Option<Self>, rt: &RuntimeCore, config: &wgpu::SurfaceConfiguration, composed: bool) { + let (clear, size, srgb, scale, transparent) = (rt.clear_color(), (config.width, config.height), rt.srgb_blend(), rt.env.scale, rt.transparent); + let p = this.get_or_insert_with(|| Self { + instances: Vec::new(), clear, size, format: config.format, srgb, scale, transparent, composed, + }); + if composed { p.instances.clear() } else { p.instances.clone_from(&rt.instances) } + (p.clear, p.size, p.format, p.srgb, p.scale, p.transparent, p.composed) = (clear, size, config.format, srgb, scale, transparent, composed); + } + + /// Whether a timer frame `rt` built before taking a drawable can go without one: nothing + /// moves or waits, no timer wants the display link's next tick (`next_tick`), and it draws + /// what this frame did. + #[cfg_attr(not(test), allow(dead_code))] + #[inline(always)] + pub(crate) fn unchanged<S: 'static>(&self, rt: &Runtime<S>, config: &wgpu::SurfaceConfiguration, animating: bool, + next_tick: Option<crate::time::Instant>) -> bool { + self.unchanged_core(rt.core(), config, animating, next_tick) + } + + pub(crate) fn unchanged_core(&self, rt: &RuntimeCore, config: &wgpu::SurfaceConfiguration, animating: bool, + next_tick: Option<crate::time::Instant>) -> bool { + !animating && !rt.has_pending_input() && !rt.live_pending() && rt.host.window_frame.is_none() + && !super::pacing::timer_wants_frame_core(rt, next_tick) && self.same_core(rt, config) + } + + /// Whether `rt`'s built frame draws what this one did: the same instances into the same + /// surface, with no glyph or image upload waiting, and nothing drawn outside the instances + /// (a compositor, `SurfaceDraw` content, native materials). + #[cfg(test)] + #[inline(always)] + pub(in crate::window) fn same<S: 'static>(&self, rt: &Runtime<S>, config: &wgpu::SurfaceConfiguration) -> bool { + self.same_core(rt.core(), config) + } + + fn same_core(&self, rt: &RuntimeCore, config: &wgpu::SurfaceConfiguration) -> bool { + let atlas = &rt.text.atlas; + !self.composed && self.size == (config.width, config.height) && self.format == config.format && self.srgb == rt.srgb_blend() + && self.scale == rt.env.scale && self.clear == rt.clear_color() && self.transparent == rt.transparent + && rt.surfaces.is_empty() && rt.paint.materials().is_empty() + && atlas.dirty.is_none() && atlas.pages.iter().all(|p| p.dirty.is_none()) + && rt.images.pages.iter().all(|p| p.dirty.is_none()) + && bytemuck::cast_slice::<_, u8>(&self.instances) == bytemuck::cast_slice::<_, u8>(&rt.instances) + } +} diff --git a/app/vendor/rune/crates/rune/src/window/surface/redraw.rs b/app/vendor/rune/crates/rune/src/window/surface/redraw.rs new file mode 100644 index 0000000..edb420b --- /dev/null +++ b/app/vendor/rune/crates/rune/src/window/surface/redraw.rs @@ -0,0 +1,75 @@ +//! When each window's next frame is asked for, and painted. A frame a window asks for while it +//! paints is asked for at the end of the loop's turn (`Windows::about_to_wait`); on Windows a +//! window whose asked-for paint the system keeps putting off is painted there. +//! +//! Windows makes up a `WM_PAINT` for one window at a time, the top one first, and winit ends its +//! message pass after each paint. A window in front that asks again inside its paint, or from a +//! timer or a wake each turn, is painted every turn, and one behind it, its frame asked for by +//! the same stream event, waited until the front one rested: a second and a half after a short +//! reply, the whole reply while one streams. + +use crate::time::Instant; +use std::time::Duration; + +/// How long a window's asked-for paint may wait while the loop turns before the loop paints it +/// itself: about a frame. +#[cfg_attr(not(target_os = "windows"), allow(dead_code))] +pub(in crate::window) const STARVE: Duration = Duration::from_millis(16); + +/// One window's next frame. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(in crate::window) enum Redraw { + /// No frame is on its way, and none is wanted. + Idle, + /// The system was asked for a paint at `at`, which hasn't come yet. + Asked { at: Instant }, + /// The window paints, and nothing has asked for another frame since it started. + Painting, + /// The window paints, and wants the next frame. + PaintingAgain, + /// The window painted and wants the next frame, which the turn's end asks for. + Wants, +} + +#[derive(Clone, Copy, Debug)] +pub(in crate::window) enum RedrawEvent { + /// Something asks for a frame: an input, a wake, a timer, the frame that just drew. + Ask(Instant), + /// A paint starts. + Paint, + /// The paint ends. + Painted, + /// The loop's turn ends. `paints`: the window is on screen, and Windows puts its paint off + /// behind the others'. + TurnEnds { now: Instant, paints: bool }, +} + +/// What the window does for a step. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(in crate::window) enum RedrawEffect { + None, + /// `Window::request_redraw`. + Request, + /// Paint now, and drop the system's paint still on its way. + PaintNow, +} + +impl Redraw { + pub(in crate::window) fn step(self, event: RedrawEvent) -> (Redraw, RedrawEffect) { + use {Redraw::*, RedrawEffect as E, RedrawEvent::*}; + match (self, event) { + // Asked inside the paint: winit would ask the system again before the paint returns. + (Painting | PaintingAgain, Ask(_)) => (PaintingAgain, E::None), + // The first ask's time is how long it has waited. + (Asked { at }, Ask(_)) => (Asked { at }, E::Request), + (Idle | Wants, Ask(now)) => (Asked { at: now }, E::Request), + (_, Paint) => (Painting, E::None), + (Painting, Painted) => (Idle, E::None), + (PaintingAgain, Painted) => (Wants, E::None), + (state, Painted) => (state, E::None), + (Wants, TurnEnds { now, .. }) => (Asked { at: now }, E::Request), + (Asked { at }, TurnEnds { now, paints: true }) if now >= at + STARVE => (Painting, E::PaintNow), + (state, TurnEnds { .. }) => (state, E::None), + } + } +} diff --git a/app/vendor/rune/crates/rune/src/window/surface/win.rs b/app/vendor/rune/crates/rune/src/window/surface/win.rs new file mode 100644 index 0000000..ef3d7e0 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/window/surface/win.rs @@ -0,0 +1,398 @@ +//! The open window: its surface, native handles, pacing and first-frame state. + +use std::sync::Arc; +use std::time::Duration; + +use winit::window::Window; + +use super::*; +use crate::frame::surface_stats::Pacing; +use crate::render::Gpu; +use crate::time::Instant; +use crate::window::state::FirstFrame; +#[cfg(target_os = "windows")] +use crate::window::win32::covered_draw::CoveredDraw; + +/// How long `on_ready` waits for a first frame that never comes, as when the window opens +/// hidden or its drawable never arrives. A covered or occluded window doesn't wait for it. +pub(in crate::window) const READY_FALLBACK: Duration = Duration::from_secs(1); + +/// What a frame does about a surface that can't draw (`Host::replace_lost_surface`). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(in crate::window) enum SurfaceStep { + /// Try a replacement now. + Replace, + /// `SURFACE_TRIES` replacements in a row and no frame presented between them: give the + /// window up. + GiveUp, +} + +/// How many replacements in a row a window may make before it gives the window up, and how long +/// it waits between ones that failed (`Host::replace_lost_surface`). Every replacement counts, +/// whether or not it worked: only a frame that presents starts the count over (`Host::draw`). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(in crate::window) struct SurfaceRetries { + replacements: u8, +} + +/// Replacements in a row without a presented frame before the window gives up. +pub(in crate::window) const SURFACE_TRIES: u8 = 3; +/// The first wait between replacements; each one after waits a further `SURFACE_BACKOFF`. +pub(in crate::window) const SURFACE_BACKOFF: Duration = Duration::from_millis(100); + +impl SurfaceRetries { + /// Counts this replacement and says whether it may happen. One that worked counts too: a + /// surface replaced and lost again before its frame presents has still used it up. + pub(in crate::window) fn attempt(&mut self) -> SurfaceStep { + if self.replacements >= SURFACE_TRIES { return SurfaceStep::GiveUp; } + self.replacements = self.replacements.saturating_add(1); + SurfaceStep::Replace + } + + /// When to try again after a replacement that failed at `now`, or None when that was the + /// last one `attempt` allows. + pub(in crate::window) fn retry(&self, now: Instant) -> Option<Instant> { + (self.replacements < SURFACE_TRIES).then(|| now + SURFACE_BACKOFF * u32::from(self.replacements)) + } + + /// A frame presented: the next loss starts its replacements over. + pub(in crate::window) fn worked(&mut self) { self.replacements = 0; } + + #[cfg(test)] + pub(in crate::window) fn failures(&self) -> u8 { self.replacements } +} + +/// The open window. Fields drop in order: what's native to the OS, then the surface before its +/// window. +pub(in crate::window) struct Win { + /// The OS accessibility adapter, which goes before the window it answers for. + pub(in crate::window) a11y: Option<crate::a11y::Adapter>, + #[cfg_attr(not(any(target_os = "macos", all(unix, not(target_os = "ios"), not(target_os = "android")))), allow(dead_code))] + pub(in crate::window) native: Native, + pub(in crate::window) first_frame: FirstFrame, + /// The surface it draws into. None only while `Host::reattach` replaces it: the old surface + /// has to go before the new one is made (a DX12 surface takes the window's one + /// DirectComposition target, `Dx12SwapchainKind::DxgiFromVisual`) and before the device it + /// drew with. + pub(in crate::window) surface: Option<wgpu::Surface<'static>>, + pub(in crate::window) config: wgpu::SurfaceConfiguration, + /// Whether the surface's last configuration took. False after a refused one, and for a lost + /// device: no drawable can be taken from it (`acquire`), and its next frame replaces the + /// surface and the device it drew with (`Host::reattach`). + pub(in crate::window) surface_ok: bool, + /// How many times in a row a frame tried to replace that surface and device, and the wait + /// between tries (`SurfaceRetries`). + pub(in crate::window) surface_retries: SurfaceRetries, + pub(in crate::window) window: Arc<Window>, + /// When to redraw after a frame that had no drawable, or the next frame of motion when no + /// display link paces it (macOS) (`Backoff`). + pub(in crate::window) backoff: Backoff, + /// When a hidden launcher renders the changes it hasn't yet. + pub(in crate::window) hidden_pace: HiddenPace, + pub(in crate::window) cursor: crate::cursor::os::OsCursor, + pub(in crate::window) alpha: Option<crate::render::surface_alpha::AlphaSurface>, + /// The pass that fades the content outside the arcs a Wayland client-side frame leaves its + /// bottom corners (`surface::corners`), once a surface here composites alpha. + pub(in crate::window) corners: Option<crate::render::csd_corners::CsdCorners>, + /// The frame a due timer asked for, until the window draws it, and whether only it asked + /// (`TimerFrame`). + pub(in crate::window) timer_frame: TimerFrame, + /// Whether only its loops asked for the next frame (`LoopFrame`). + pub(in crate::window) loop_frame: LoopFrame, + /// The last frame presented, while the window rests. + pub(in crate::window) presented: Option<Presented>, + /// A frame asked for while other windows covered it, still to draw (`CoveredDraw`). + #[cfg(target_os = "windows")] + pub(in crate::window) covered_draw: CoveredDraw, + /// Its next frame (`redraw`). + pub(in crate::window) redraw: std::cell::Cell<Redraw>, +} + +impl Win { + /// Windows: its next frame waits for room in the swap chain, and comes when there is (`slot`). + pub(in crate::window) fn waits_for_slot(&self) -> bool { + #[cfg(target_os = "windows")] + return self.native.slot.waiting(); + #[cfg(not(target_os = "windows"))] + false + } + + /// Asks for a frame: now, or at the turn's end while the window paints (`Redraw`). + #[cfg_attr(feature = "frame-profile", track_caller)] + pub(in crate::window) fn request_redraw(&self) { self.redraw_step(RedrawEvent::Ask(crate::time::now())); } + + #[cfg_attr(feature = "frame-profile", track_caller)] + pub(in crate::window) fn redraw_step(&self, event: RedrawEvent) { + let (next, effect) = self.redraw.get().step(event); + self.redraw.set(next); + #[cfg(feature = "frame-profile")] + if matches!(event, RedrawEvent::Ask(_)) || effect != RedrawEffect::None { crate::frame::live_log::asked(std::panic::Location::caller()); } + if effect == RedrawEffect::Request { self.window.request_redraw(); } + } + + /// Matches the drawable to the window's size; false when it already did. A surface that + /// refuses the new size is marked so its next frame replaces it (`Host::reattach`) rather + /// than drawing into a surface wgpu has no presentation for. + pub(in crate::window) fn resize_surface(&mut self, gpu: Option<&Gpu>, size: winit::dpi::PhysicalSize<u32>) -> bool { + let (width, height) = (size.width.max(1), size.height.max(1)); + if (self.config.width, self.config.height) == (width, height) { return false; } + self.config.width = width; + self.config.height = height; + // No surface: `Host::reattach` is between the old one and the new, and takes this size + // from the window itself; or the CPU renderer draws it, whose buffer follows this size. + let (Some(surface), Some(gpu)) = (&self.surface, gpu) else { return true }; + // `configure` drains the present queue and reconfigures the swap chain; unregister any + // outstanding wait before it touches the swap chain. + #[cfg(target_os = "windows")] + self.native.slot.reset(); + if let Err(error) = super::configure(surface, gpu, &self.config) { + eprintln!("rune: a window's surface refused its new size: {error}"); + self.surface_ok = false; + } + if let Some(alpha) = &mut self.alpha { alpha.resize(&gpu.device, (width, height)); } + #[cfg(target_os = "macos")] + if let Some(shadow) = &self.native.shadow { shadow.redraw(); } + true + } +} + +#[test] +fn launcher_first_frame_holds_reveal_and_hide_cancels_late_completion() { + let now = crate::time::now(); + let mut frame = FirstFrame::default(); + frame.prepare(now); + assert!(!frame.request_reveal(false, false, now)); + assert!(!frame.ready()); + assert!(frame.complete()); + assert!(frame.ready() && frame.deadline().is_none()); + assert!(!frame.complete(), "a second callback must not reopen a hidden panel"); + let mut canceled = FirstFrame::default(); + canceled.prepare(now); + assert!(!canceled.request_reveal(false, false, now)); + canceled.hide(); + assert!(!canceled.complete(), "hide before readiness cancels the pending show"); + assert!(canceled.ready()); + assert!(canceled.request_reveal(false, false, now), "the prepared frame can be revealed without another preparation"); + assert!(canceled.deadline().is_none()); +} + +#[test] +fn launcher_stale_reveal_waits_for_an_unsettled_hidden_frame() { + let now = crate::time::now(); + let mut frame = FirstFrame::drawn_notified(); + assert!(!frame.complete()); + assert!(frame.request_reveal(false, false, now), "unchanged state reveals the cached frame at once"); + assert!(!frame.pending() && frame.settles()); + assert!(!frame.request_reveal(true, false, now), "changed state renders hidden first"); + assert!(frame.deadline().is_some() && !frame.settles(), "the refresh keeps its new motion"); + frame.gpu_done(); // The hidden frame's fence completed. + assert!(frame.pending() && frame.complete()); + assert!(!frame.pending() && frame.settles()); + assert!(!frame.request_reveal(true, false, now)); + frame.hide(); + assert!(frame.settles(), "a canceled refresh is an ordinary hidden frame"); + assert!(frame.ready() && frame.deadline().is_none(), "hide stops the refresh retries"); + assert!(!frame.pending() && !frame.complete(), "a late frame does not reveal"); + + assert!(!frame.request_reveal(true, false, now)); + assert!(frame.expire(), "a refresh with no drawable reveals the cached frame"); + assert!(frame.ready() && !frame.pending() && frame.deadline().is_none()); + let mut first = FirstFrame::default(); + first.prepare(now); + assert!(!first.request_reveal(true, false, now)); + assert!(!first.expire() && !first.ready(), "the first frame stays hidden and reports instead"); + first.gpu_done(); + assert!(first.pending() && first.complete(), "a late first frame still reveals"); +} + +#[test] +fn launcher_refresh_with_no_drawable_retries_and_never_reveals_stale_pixels() { + let now = crate::time::now(); + let mut frame = FirstFrame::drawn_notified(); + let mut backoff = Backoff::default(); + let missed = |frame: &mut FirstFrame, backoff: &mut Backoff| { + frame.missed(); + backoff.step(BackoffEvent::HiddenMissed { preparing: frame.deadline().is_some(), now }); + backoff.deadline() + }; + assert_eq!(missed(&mut frame, &mut backoff), Some(now + TIMEOUT_RETRY), "a hidden refresh that got no drawable tries again"); + assert!(!frame.ready(), "its cached frame no longer counts as ready"); + assert_eq!(missed(&mut frame, &mut backoff), Some(now + TIMEOUT_RETRY * 2), "and backs off"); + for _ in 0..10 { missed(&mut frame, &mut backoff); } + assert_eq!(backoff.deadline(), Some(now + OCCLUDED_MAX), "up to a re-check every two seconds"); + assert!(!frame.request_reveal(false, false, now), "a reveal waits for the refresh even with nothing new to commit"); + assert!(frame.deadline().is_some()); + assert_eq!(missed(&mut frame, &mut backoff), None, "the first-frame deadline owns its retries"); + + // One already on screen shows at once and redraws, rather than retrying a first frame. + let mut shown = FirstFrame::drawn_notified(); + assert!(shown.request_reveal(true, true, now)); + assert!(shown.deadline().is_none() && shown.ready()); +} + +impl Win { + pub(in crate::window) fn show(&self, focus: bool) { + #[cfg(target_os = "macos")] + { + if let Some(shadow) = &self.native.shadow { shadow.shown(); } + if let Some(panel) = &self.native.panel { + panel.show(std::time::Duration::ZERO); + if focus { panel.request_keys(); } + return; + } + if !focus { crate::platform::macos::show_without_focus(&self.window); return; } + } + // What it presented before it was hidden is gone, or never was: cloaked until it draws. + #[cfg(target_os = "windows")] + { + self.native.cloak.hold(&self.window, crate::time::now() + READY_FALLBACK, false); + self.request_redraw(); + } + self.window.set_visible(true); + if focus { self.window.focus_window(); } + } + + /// When a cloaked window shows without its frame. + pub(in crate::window) fn cloak_deadline(&self) -> Option<Instant> { + #[cfg(target_os = "windows")] + return self.native.cloak.deadline(); + #[cfg(not(target_os = "windows"))] + None + } + + pub(in crate::window) fn hide(&self) { + #[cfg(all(feature = "native-file-dialog", target_os = "linux"))] + crate::file_dialog::window_focus(&self.window, false); + #[cfg(target_os = "macos")] + if let Some(shadow) = &self.native.shadow { shadow.hidden(); } + #[cfg(target_os = "macos")] + if let Some(panel) = &self.native.panel { panel.hide(std::time::Duration::ZERO); return; } + self.window.set_visible(false); + // Hidden before its frame: the next show cloaks it again. + #[cfg(target_os = "windows")] + self.native.cloak.hidden(&self.window); + } + + /// Its last frame is on screen and nothing has asked for another since. + pub(in crate::window) fn rests(&self) -> bool { + #[cfg(target_os = "macos")] + if self.native.prime.presumes() { return false; } + self.presented.is_some() + } + + /// The display link's next tick after `now`, while it runs. + pub(in crate::window) fn next_tick(&self, now: Instant) -> Option<Instant> { + #[cfg(target_os = "macos")] + return self.native.pacing.as_ref().filter(|p| p.running()).map(|p| now + Duration::from_secs_f64(1.0 / p.refresh_hz())); + #[cfg(not(target_os = "macos"))] + { let _ = now; None } + } + + /// Whether the display link drives redraws. Other platforms redraw on request. + pub(in crate::window) fn paced(&self) -> bool { + #[cfg(target_os = "macos")] + return self.native.pacing.as_ref().is_some_and(|p| p.running()); + #[cfg(not(target_os = "macos"))] + false + } + + /// Whether something other than events paces the window's redraws: the display link on + /// macOS, the present queue's vsync elsewhere. + pub(in crate::window) fn paced_for_stats(&self) -> bool { !cfg!(target_os = "macos") || self.paced() } + + /// Steps the window's wait after a frame it couldn't draw, and carries out what that asks: a + /// display link that would draw sooner than the wait stops. + pub(in crate::window) fn backoff_step(&mut self, event: BackoffEvent) { + for effect in self.backoff.step(event) { + match effect { BackoffEffect::StopPacing => self.stop_pacing() } + } + } + + /// Waiting for a missed frame's retry, or for the timer pacing unpaced motion. A hidden + /// launcher's first-frame deadline owns its own retries, so a wait it leaves behind doesn't + /// hold the frame back. + pub(in crate::window) fn backing_off(&self, now: Instant) -> bool { + self.backoff.waiting(now) && self.first_frame.deadline().is_none() + } + + /// What paces the window's frames, for its stats. + pub(in crate::window) fn pacing_state(&self, moving: bool) -> Pacing { + #[cfg(target_os = "macos")] + return crate::platform::display_link::pacing(self.native.pacing.as_ref(), moving); + #[cfg(not(target_os = "macos"))] + if moving { Pacing::Vsync } else { Pacing::Idle } + } + + /// Minimized, as far as drawing goes. On macOS occlusion says it instead (the `Occluded` + /// event, `natively_occluded`): `isMiniaturized` stays true into a deminiaturize whose + /// occlusion change and first redraws would otherwise draw nothing, with no event after. + pub(in crate::window) fn minimized(&self) -> bool { + !cfg!(target_os = "macos") && self.window.is_minimized().unwrap_or(false) + } + + /// Whether none of the window is on screen, read from AppKit (a prewarm acquisition reads + /// as visible). + #[cfg(target_os = "macos")] + pub(in crate::window) fn natively_occluded(&self) -> bool { + match &self.native.panel { + Some(panel) => panel.occluded(), + None => crate::platform::macos::window_occluded(&self.window), + } + } + + pub(in crate::window) fn stop_pacing(&mut self) { + #[cfg(target_os = "macos")] + if let Some(pacing) = &mut self.native.pacing { pacing.stop(); } + #[cfg(target_os = "macos")] + self.present_with_transaction(false); + } + + /// Presents drawables inside Core Animation transactions, while the frame moves. + #[cfg(target_os = "macos")] + pub(in crate::window) fn present_with_transaction(&mut self, on: bool) { + if let Some(surface) = &self.surface { self.native.materials.set_moving(surface, on); } + } + + /// Presents the frame in the transaction that resizes the window while the user drags its + /// edge. Before the drawable is acquired: wgpu reads `presentsWithTransaction` then. + #[cfg(target_os = "macos")] + pub(in crate::window) fn set_live_resize(&mut self, on: bool) { + if let Some(surface) = &self.surface { self.native.materials.set_live(&self.window, surface, on); } + } + + pub(in crate::window) fn focus(&self) { + #[cfg(target_os = "macos")] + if let Some(panel) = &self.native.panel { panel.request_keys(); return; } + self.window.focus_window(); + } +} + +/// `on_ready` starts an app's live work, so it can't wait on a drawable: a window launched +/// covered, occluded or hidden by the system may not draw for as long as it stays that way. +/// It runs at the first frame skipped for being off screen, or `READY_FALLBACK` after opening +/// when no frame comes at all; a window on screen still runs it after its first frame. +#[test] +fn on_ready_runs_for_a_window_launched_occluded_or_hidden() { + let now = crate::time::now(); + let ms = Duration::from_millis; + let mut shown = FirstFrame::opened(now); + assert!(!shown.ready_due(now + ms(16)), "a window on screen waits for its first frame"); + shown.gpu_done(); + assert!(shown.pending() && !shown.complete()); + assert!(shown.take_ready(), "its first frame runs on_ready"); + assert!(!shown.take_ready() && shown.ready_deadline().is_none(), "once"); + + let mut covered = FirstFrame::opened(now); + covered.skipped(now + ms(30)); + assert!(covered.ready_due(now + ms(30)) && covered.take_ready(), "the first covered frame runs on_ready"); + assert!(!covered.ready() && !covered.pending(), "the window isn't ready until it draws"); + covered.skipped(now + ms(60)); + assert_eq!(covered.ready_deadline(), None, "and skipping again doesn't run it again"); + covered.gpu_done(); // Uncovered. + assert!(covered.pending() && !covered.complete() && !covered.take_ready(), "drawing at last doesn't either"); + + let mut hidden = FirstFrame::opened(now); + assert_eq!(hidden.ready_deadline(), Some(now + READY_FALLBACK), "the event loop wakes for it"); + assert!(!hidden.ready_due(now + READY_FALLBACK - ms(1))); + assert!(hidden.ready_due(now + READY_FALLBACK) && hidden.take_ready(), "a window that never draws runs it after the fallback"); +} diff --git a/app/vendor/rune/crates/rune/src/window/tests.rs b/app/vendor/rune/crates/rune/src/window/tests.rs new file mode 100644 index 0000000..58ec1eb --- /dev/null +++ b/app/vendor/rune/crates/rune/src/window/tests.rs @@ -0,0 +1,802 @@ +use super::*; + +#[test] +fn updates_that_change_nothing_ask_no_window_for_a_frame() { + use crate::{App, AppSpec, el}; + let app = App::new(AppSpec::new("t", (10.0, 10.0), || 0u32, |_, _| el())); + let (handle, shared) = (app.handle(), app.shared.clone()); + let mut rt = Runtime::new(0u32, |_, _| el(), (10.0, 10.0), crate::Env::default()); + rt.frame(0.0); + // As `Host::drain`, for 100 timer ticks that found nothing new. + for _ in 0..100 { + handle.update_if(|_, _| false); + let mut requests = shared.take(); + let mut updated = false; + for f in std::mem::take(&mut requests.updates) { updated |= rt.update_if(f); } + let quiet = !updated && requests.only_updates() && !rt.patch_pending() && !rt.needs_commit(); + for (launcher, visible) in [(false, true), (true, true), (true, false), (false, false)] { + let work = WakeWork::of(WakeFacts { window: true, launcher, visible, was_shown: visible, changed: updated, quiet, ..WakeFacts::default() }, || false); + assert_eq!(work, WakeWork::Nothing, "launcher {launcher} visible {visible}"); + } + } + handle.update_if(|_, _| false); + handle.wake(); + assert!(!shared.take().only_updates(), "`wake` still runs a shown window's poll"); + handle.update_if(|_, _| false); + setup_waker(&shared.core)(); + assert!(!shared.take().only_updates(), "so does `setup`'s waker"); + assert_eq!(WakeWork::of(WakeFacts { window: true, visible: true, was_shown: true, ..WakeFacts::default() }, || false), WakeWork::Paint); + assert_eq!(WakeWork::of(WakeFacts { window: true, launcher: true, changed: true, ..WakeFacts::default() }, || false), WakeWork::HiddenFrame); +} + +/// A stream of updates that change nothing, faster than a frame, on a host that neither polls +/// nor draws for them, doesn't push back a due timer, and one's own `wake_after(ZERO)` after +/// idle is due at once. +#[test] +fn updates_that_change_nothing_do_not_delay_due_timers() { + let mut rt = Runtime::new(0u32, |_, _| crate::el(), (10.0, 10.0), crate::Env::default()); + rt.wall_start = Some(crate::time::now()); + rt.frame(0.0); + // A second idle since that frame. + rt.wall_start = rt.wall_start.map(|t| t - Duration::from_secs(1)); + let polled = rt.polled_at(); + rt.update_if(|_, tx| { tx.wake_after(Duration::ZERO); false }); + rt.schedule_pending_wakes(); + let due = timer_deadline(&rt).expect("armed"); + assert!(due <= crate::time::now(), "due now, not a frame interval from now"); + for _ in 0..20 { + std::thread::sleep(Duration::from_millis(2)); + rt.update_if(|_, _| false); + rt.schedule_pending_wakes(); + assert_eq!(timer_deadline(&rt), Some(due)); + } + assert_eq!(rt.polled_at(), polled, "the clock stays at the last poll"); +} + +/// `wake_after(Duration::ZERO)` from the poll: a running display link takes it as the next +/// frame; any host without one waits a frame interval from the poll, never `now`. +#[test] +fn a_timer_asking_for_the_next_frame_waits_a_frame_without_a_display_link() { + fn poll(polls: &mut u32, _: f64, tx: &mut Tx) -> bool { *polls += 1; tx.wake_after(Duration::ZERO); false } + let mut rt = Runtime::new(0u32, |_, _| crate::el(), (10.0, 10.0), crate::Env::default()); + rt.poll = Some(poll); + let start = crate::time::now() - Duration::from_secs(1); + rt.wall_start = Some(start); + rt.frame(0.0); + assert_eq!(rt.state, 1); + let due = wall_wake_deadline(&rt).expect("armed"); + let polled = start + Duration::from_secs_f64(rt.polled_at()); + assert!(due <= polled + Duration::from_micros(1), "due at once on the runtime's clock"); + let wait = timer_deadline(&rt).expect("armed"); + assert!(wait >= polled + TIMER_FRAME - Duration::from_micros(1) && wait <= polled + TIMER_FRAME + Duration::from_micros(1)); + assert!(timer_wants_frame(&rt, Some(polled + Duration::from_millis(8))), "a paced surface draws it next tick"); + assert!(!timer_wants_frame(&rt, None), "an unpaced one doesn't keep the loop turning"); + // A timer longer than a frame keeps its own time. + let mut rt = Runtime::new(0u32, |_, _| crate::el(), (10.0, 10.0), crate::Env::default()); + rt.wall_start = Some(start); + rt.update(|_, tx| tx.wake_after(Duration::from_millis(100))); + rt.frame(0.0); + assert_eq!(timer_deadline(&rt), wall_wake_deadline(&rt)); +} + +#[test] +fn a_frame_that_draws_the_same_pixels_is_the_same() { + use crate::{Color, el}; + fn view(n: &u32, _: &mut crate::Cx<u32>) -> crate::El { + el().key("root").size(200.0, 100.0).child(el().key("box").size(40.0 + *n as f32, 40.0).fill(Color { r: 0.3, g: 0.5, b: 0.9, a: 1.0 })) + } + let mut rt = Runtime::new(0u32, view, (200.0, 100.0), crate::Env::new(false, 2.0)); + rt.frame(0.0); + let config = wgpu::SurfaceConfiguration { + usage: wgpu::TextureUsages::RENDER_ATTACHMENT, + format: wgpu::TextureFormat::Bgra8UnormSrgb, + width: 400, + height: 200, + present_mode: wgpu::PresentMode::AutoVsync, + desired_maximum_frame_latency: 2, + alpha_mode: wgpu::CompositeAlphaMode::Opaque, + view_formats: vec![], + color_space: Default::default(), + }; + let mut presented = None; + Presented::record(&mut presented, &rt, &config, false); + let p = presented.as_ref().unwrap(); + + // A poll that says it changed state, but the view draws the same. + rt.update(|_, _| {}); + rt.frame(0.0); + assert!(p.same(&rt, &config), "a rebuild that draws the same pixels presents nothing"); + + let resized = wgpu::SurfaceConfiguration { width: 402, ..config.clone() }; + assert!(!p.same(&rt, &resized), "a resized surface draws again"); + rt.text.atlas.dirty = Some((0, 1)); + assert!(!p.same(&rt, &config), "a glyph upload draws again"); + rt.text.atlas.dirty = None; + + rt.update(|n, _| *n = 8); + rt.settle_all(); + rt.frame(0.0); + assert!(!p.same(&rt, &config), "a change on screen draws again"); +} + +/// A timer frame that draws the same pixels still takes its drawable while a poll steps on the +/// display link (`wake_after(ZERO)`): skipping it would stop the link and the steps with it. +#[test] +fn a_timer_frame_that_draws_the_same_still_draws_while_a_poll_steps() { + fn poll(step: &mut bool, _: f64, tx: &mut Tx) -> bool { + tx.wake_after(if *step { Duration::ZERO } else { Duration::from_secs(5) }); + false + } + let mut rt = Runtime::new(false, |_, _| crate::el().size(20.0, 20.0), (20.0, 20.0), crate::Env::default()); + rt.poll = Some(poll); + rt.wall_start = Some(crate::time::now()); + rt.frame(0.0); + let config = wgpu::SurfaceConfiguration { + usage: wgpu::TextureUsages::RENDER_ATTACHMENT, + format: wgpu::TextureFormat::Bgra8UnormSrgb, + width: 20, + height: 20, + present_mode: wgpu::PresentMode::AutoVsync, + desired_maximum_frame_latency: 2, + alpha_mode: wgpu::CompositeAlphaMode::Opaque, + view_formats: vec![], + color_space: Default::default(), + }; + let mut presented = None; + Presented::record(&mut presented, &rt, &config, false); + let p = presented.as_ref().unwrap(); + let next_tick = Some(crate::time::now() + Duration::from_millis(8)); + assert!(p.unchanged(&rt, &config, false, next_tick), "a slow timer leaves the drawable"); + rt.state = true; + rt.frame(0.0); + assert!(p.same(&rt, &config)); + assert!(!p.unchanged(&rt, &config, false, next_tick), "a step due by the next tick draws"); + assert!(p.unchanged(&rt, &config, false, None), "without a running link the timer paces it"); +} + +#[cfg(target_os = "macos")] +#[test] +fn launch_frames_hold_two_drawables_until_the_window_rests() { + let mut config = wgpu::SurfaceConfiguration { + usage: wgpu::TextureUsages::RENDER_ATTACHMENT, + format: wgpu::TextureFormat::Bgra8UnormSrgb, + width: 1960, + height: 1520, + present_mode: wgpu::PresentMode::AutoVsync, + desired_maximum_frame_latency: 2, + alpha_mode: wgpu::CompositeAlphaMode::Opaque, + view_formats: vec![], + color_space: Default::default(), + }; + let t0 = crate::time::now(); + let mut launch = LaunchDrawables::cap(&mut config); + assert_eq!(config.desired_maximum_frame_latency, 1, "Metal makes latency + 1 drawables"); + assert_eq!(launch.settle(false, t0), None); + assert_eq!(launch.settle(false, t0 + Duration::from_millis(500)), None, "frames back to back stay capped"); + assert_eq!(launch.settle(true, t0 + Duration::from_millis(600)), Some(2), "resting restores the configured latency"); + assert_eq!(launch.settle(true, t0 + Duration::from_millis(700)), None, "once"); + assert_eq!(launch.settle(false, t0 + Duration::from_secs(5)), None); + + // A window that never rests gets its third drawable after its first second on screen. + config.desired_maximum_frame_latency = 2; + let mut launch = LaunchDrawables::cap(&mut config); + let shown = t0 + Duration::from_secs(3); + assert_eq!(launch.settle(false, shown), None, "the second counts from the first frame on screen"); + assert_eq!(launch.settle(false, shown + Duration::from_millis(999)), None); + assert_eq!(launch.settle(false, shown + LaunchDrawables::LAUNCH), Some(2)); + + // Nothing to restore when the configuration already asks for two. + config.desired_maximum_frame_latency = 1; + let mut launch = LaunchDrawables::cap(&mut config); + assert_eq!(config.desired_maximum_frame_latency, 1); + assert_eq!(launch.settle(true, t0), None); +} + +/// The poll's timer on the runtime's logical clock. +const COMP_PERIOD: Duration = Duration::from_secs(5); + +fn still(polls: &mut u32, _: f64, tx: &mut Tx) -> bool { *polls += 1; tx.wake_after(COMP_PERIOD); false } +fn every_third(polls: &mut u32, _: f64, tx: &mut Tx) -> bool { *polls += 1; tx.wake_after(COMP_PERIOD); *polls % 3 == 0 } +fn changed(polls: &mut u32, _: f64, tx: &mut Tx) -> bool { *polls += 1; tx.wake_after(COMP_PERIOD); true } + +/// A compositor whose `animating` follows a shared flag, as one driven by app state. +struct FlagComp(std::rc::Rc<std::cell::Cell<bool>>); + +impl crate::Compositor<u32> for FlagComp { + fn render(&mut self, f: &mut crate::Frame<'_, u32>) { f.draw_ui(); } + fn animating(&self) -> bool { self.0.get() } +} + +/// A window as the host runs it, with or without a compositor, counting its frames. +struct CompHost { + rt: Runtime<u32>, + presented: Option<Presented>, + config: wgpu::SurfaceConfiguration, + idle: bool, + comp: Option<Box<dyn crate::Compositor<u32>>>, + /// Whether `comp` animates. + comp_animates: std::rc::Rc<std::cell::Cell<bool>>, + frames: u32, + /// Called where `draw` calls it. + reports: crate::frame::encoded::FrameReports, +} + +impl CompHost { + /// The first frame draws before `poll` is set, so one timer is armed at a time. + fn new(comp: Option<bool>, poll: fn(&mut u32, f64, &mut Tx) -> bool) -> Self { + fn view(_: &u32, _: &mut crate::Cx<u32>) -> crate::El { crate::el().key("box").size(20.0, 20.0).fill(crate::Color::WHITE) } + let mut rt = Runtime::new(0u32, view, (20.0, 20.0), crate::Env::default()); + rt.frame.set_test_clock(crate::Clock::manual(1.0 / crate::frame::clock::RESUME_STEP)); + let config = wgpu::SurfaceConfiguration { + usage: wgpu::TextureUsages::RENDER_ATTACHMENT, + format: wgpu::TextureFormat::Bgra8UnormSrgb, + width: 20, + height: 20, + present_mode: wgpu::PresentMode::AutoVsync, + desired_maximum_frame_latency: 2, + alpha_mode: wgpu::CompositeAlphaMode::Opaque, + view_formats: vec![], + color_space: Default::default(), + }; + let comp_animates = std::rc::Rc::new(std::cell::Cell::new(comp == Some(true))); + let comp = comp.map(|_| Box::new(FlagComp(comp_animates.clone())) as Box<dyn crate::Compositor<u32>>); + let mut host = Self { rt, presented: None, config, idle: false, comp, comp_animates, frames: 0, reports: Default::default() }; + host.frame(false); + host.rt.poll = Some(poll); + host.frame(false); + host + } + + /// As `draw`: a quiet frame (only a timer asked for it) that draws what's on screen presents + /// nothing, unless a compositor draws it. Returns whether it presented. + fn frame(&mut self, quiet: bool) -> bool { + let started = crate::time::now(); + self.rt.frame.test_clock_mut().unwrap().step(); + let animating = self.rt.frame(crate::frame::clock::RESUME_STEP); + let update_ms = started.elapsed().as_secs_f64() * 1000.0; + if quiet && self.comp.is_none() && self.presented.as_ref().is_some_and(|p| p.unchanged(&self.rt, &self.config, animating, None)) { + self.reports.unchanged(None); + return false; + } + let moving = animating || composing(self.comp.as_deref()); + let encoded = self.reports.stamp(); + self.idle = Presented::settle(&mut self.presented, &self.rt, &self.config, moving, None, true, self.comp.is_some()); + self.frames += 1; + self.reports.drawn(encoded, None, started, update_ms); + true + } + + /// As `new_events` at a due timer: a resting window polls first and asks for a frame only + /// when that poll changed something. Returns whether it presented. + fn timer_wake(&mut self) -> bool { + let due = self.rt.wake_deadline().expect("a timer is armed"); + // Advance host time, not rt.clock: rests() still examines the last poll's time. + let clock = self.rt.frame.test_clock_mut().unwrap(); + clock.seek(clock.now().max(due)); + let rests = self.idle && !composing(self.comp.as_deref()) && self.presented.is_some(); + let frame = match rests.then(|| self.rt.resting_wake()).flatten() { + Some(stale) => { + let frame = stale || self.rt.stale(); + self.rt.resting_wake_frame(frame); + frame + } + None => true, + }; + frame && self.frame(true) + } +} + +#[test] +fn a_still_compositor_s_window_rests_and_polls_its_timers_first() { + let mut host = CompHost::new(Some(false), still); + assert!(host.idle && host.presented.is_some(), "a still compositor lets the window rest"); + let (frames, commits, polls) = (host.frames, host.rt.stats.commits, host.rt.state); + for _ in 0..8 { assert!(!host.timer_wake(), "a poll that returns false builds and presents nothing"); } + assert_eq!(host.frames, frames); + assert_eq!(host.rt.stats.commits, commits, "and runs no view"); + assert_eq!(host.rt.state, polls + 8, "each timer still polls"); +} + +#[test] +fn a_still_compositor_s_poll_that_changes_something_gets_one_frame() { + let mut host = CompHost::new(Some(false), every_third); + let (frames, polls) = (host.frames, host.rt.state); + let drew = (0..6).filter(|_| host.timer_wake()).count(); + let changes = (polls + 1..=polls + 6).filter(|p| p % 3 == 0).count(); + assert_eq!(drew, changes, "one frame for each poll that returns true"); + assert_eq!(host.frames - frames, changes as u32); + assert_eq!(host.rt.state, polls + 6, "one poll a wake: the frame doesn't poll again"); +} + +#[test] +fn an_animating_compositor_draws_every_frame() { + let mut host = CompHost::new(Some(true), still); + assert!(!host.idle && host.presented.is_none(), "an animating compositor never rests"); + let (frames, polls) = (host.frames, host.rt.state); + for _ in 0..5 { assert!(host.timer_wake()); } + assert_eq!(host.frames - frames, 5); + assert_eq!(host.rt.state, polls + 5, "the frames poll"); +} + +#[test] +fn a_compositor_s_frame_never_counts_as_unchanged() { + let mut host = CompHost::new(Some(false), still); + host.rt.update(|_, _| {}); + host.rt.frame(crate::frame::clock::RESUME_STEP); + let p = host.presented.as_ref().unwrap(); + assert!(!p.same(&host.rt, &host.config), "the same instances may composite differently"); + assert!(!p.unchanged(&host.rt, &host.config, false, None)); + // A changed poll's quiet frame presents. + let mut host = CompHost::new(Some(false), changed); + assert!(host.idle && host.presented.is_some()); + assert!(host.timer_wake(), "a poll that changed nothing on screen still presents a compositor's frame"); + + // Without a compositor, the same frame presents nothing. + let mut host = CompHost::new(None, still); + host.rt.poll = Some(changed); + let frames = host.frames; + assert!(!host.timer_wake()); + assert_eq!(host.frames, frames); +} + +#[test] +fn a_compositor_that_starts_animating_while_the_window_rests_draws_its_next_timer() { + let mut host = CompHost::new(Some(false), still); + assert!(!host.timer_wake()); + host.comp_animates.set(true); + assert!(host.timer_wake(), "a due timer draws once the compositor animates"); + assert!(!host.idle && host.presented.is_none(), "and the window stops resting"); + host.comp_animates.set(false); + assert!(host.timer_wake()); + assert!(!host.timer_wake(), "still again, it rests"); +} + +#[test] +fn a_frame_that_leaves_work_for_the_next_does_not_settle() { + let mut host = CompHost::new(Some(false), still); + assert!(host.idle); + // The compositor invalidated the view while drawing, as one ending its own motion may. + host.rt.invalidate(); + let idle = Presented::settle(&mut host.presented, &host.rt, &host.config, false, None, true, true); + assert!(!idle && host.presented.is_none(), "a frame with a commit pending isn't idle"); + host.frame(false); + assert!(host.idle && host.presented.is_some(), "the frame that commits it settles"); + // A frame the window may not rest on (hidden, or a trace counting frames) records nothing. + let idle = Presented::settle(&mut host.presented, &host.rt, &host.config, false, None, false, true); + assert!(idle && host.presented.is_none()); +} + +/// The same frames, timers and settling with `App::on_frame_encoded` as without: a window +/// reports what it decided and nothing it decides reads the reports. +#[test] +fn reporting_frames_changes_no_frame_skip_or_redraw() { + fn run(hook: bool) -> (Vec<(bool, bool, bool, bool, u32)>, u64, u32, Vec<crate::FrameOutcome>) { + let log = std::rc::Rc::new(std::cell::RefCell::new(Vec::new())); + let sink = log.clone(); + let mut host = CompHost::new(None, every_third); + let hook = hook.then(|| Box::new(move |f: &crate::FrameEncoded| sink.borrow_mut().push(f.outcome())) as crate::frame::encoded::OnFrameEncoded); + host.reports = crate::frame::encoded::FrameReports::new(hook, Some("main")); + let mut steps = Vec::new(); + for i in 0..12 { + let presented = if i % 5 == 0 { host.frame(false) } else { host.timer_wake() }; + steps.push((presented, host.idle, host.rt.stale(), host.rt.wake_deadline().is_some(), host.frames)); + } + let outcomes = log.borrow().clone(); + (steps, host.rt.stats.commits, host.rt.state, outcomes) + } + let (plain, plain_commits, plain_polls, none) = run(false); + let (hooked, hooked_commits, hooked_polls, outcomes) = run(true); + assert_eq!(plain, hooked); + assert_eq!((plain_commits, plain_polls), (hooked_commits, hooked_polls)); + assert!(none.is_empty()); + assert!(outcomes.contains(&crate::FrameOutcome::Drawn) && outcomes.contains(&crate::FrameOutcome::Unchanged), "{outcomes:?}"); + let drawn = outcomes.iter().filter(|o| **o == crate::FrameOutcome::Drawn).count() as u32; + assert_eq!(drawn, hooked.last().unwrap().4 - 2, "one Drawn per presented frame after the two `new` drew"); +} + +#[test] +fn hidden_pace_renders_a_change_at_once_then_at_most_every_refresh() { + let t0 = crate::time::now(); + let mut pace = HiddenPace::default(); + assert!(pace.changed(t0), "the first change renders at once"); + pace.rendered(t0); + assert_eq!(pace.deadline(), None); + assert!(!pace.changed(t0 + Duration::from_millis(100))); + assert!(!pace.changed(t0 + Duration::from_millis(200))); + assert_eq!(pace.deadline(), Some(t0 + HIDDEN_REFRESH), "later ones wait for one render"); + assert!(!pace.take_due(t0 + Duration::from_millis(249))); + assert!(pace.take_due(t0 + HIDDEN_REFRESH)); + assert_eq!(pace.deadline(), None, "a due render asked for doesn't wake the loop again"); + assert!(pace.changed(t0 + HIDDEN_REFRESH)); + pace.rendered(t0 + HIDDEN_REFRESH); + assert_eq!(pace.deadline(), None); + assert!(pace.changed(t0 + Duration::from_secs(5)), "after a quiet spell, at once again"); + pace.reset(); + assert!(pace.changed(t0 + Duration::from_secs(5))); +} + +#[test] +fn missed_frames_never_poll() { + use wgpu::CurrentSurfaceTexture as S; + let now = crate::time::now(); + for status in [S::Occluded, S::Timeout, S::Outdated, S::Lost, S::Validation] { + let missed = Missed::of(status).err().expect("a miss"); + for paced in [false, true] { + for wait in [Duration::ZERO, OCCLUDED_RETRY, Duration::from_secs(60)] { + let mut backoff = Backoff::seeded(wait, TIMEOUT_RETRY); + backoff.step(BackoffEvent::Missed { missed, paced, now }); + // A retry deadline at or before now would spin like a poll. + let flow = match backoff.deadline() { + Some(at) => { assert!(at > now, "{missed:?} retries later, not now"); ControlFlow::WaitUntil(at) } + None => ControlFlow::Wait, + }; + assert_ne!(flow, ControlFlow::Poll, "{missed:?} (paced: {paced}) must not poll"); + } + } + } + let occluded = |wait| { + let mut backoff = Backoff::seeded(wait, TIMEOUT_RETRY); + backoff.step(BackoffEvent::Missed { missed: Missed::Occluded, paced: true, now }); + backoff.deadline() + }; + assert_eq!(occluded(Duration::ZERO), Some(now + OCCLUDED_RETRY), "the safety net is slow"); + assert_eq!(occluded(Duration::from_secs(60)), Some(now + OCCLUDED_MAX)); + let miss = |backoff: &mut Backoff, missed| { + backoff.step(BackoffEvent::Missed { missed, paced: true, now }); + backoff.deadline() + }; + let mut backoff = Backoff::default(); + assert_eq!(miss(&mut backoff, Missed::Timeout), None, "a running display link retries on its tick"); + assert_eq!(miss(&mut backoff, Missed::Outdated), Some(now + OCCLUDED_RETRY)); + assert_eq!(miss(&mut backoff, Missed::Occluded), Some(now + OCCLUDED_RETRY), "an occluded miss waits its backoff"); + assert_eq!(miss(&mut backoff, Missed::Occluded), Some(now + OCCLUDED_RETRY * 2), "and backs off"); + assert_eq!(miss(&mut backoff, Missed::Outdated), Some(now + OCCLUDED_RETRY), "other misses leave the backoff"); + assert_eq!(miss(&mut backoff, Missed::Occluded), Some(now + OCCLUDED_RETRY * 4), "which carries on"); +} + +/// A shown window's due timer asks for a frame. On Wayland a surface that is covered before its +/// frame callback fires withholds `RedrawRequested`, and the same overdue timer would turn the +/// loop at once for a frame that can't come. The host waits out the bound, then runs the timer +/// covered; its next one is ahead, so the loop sleeps. +#[test] +fn a_timer_frame_that_never_comes_runs_its_timer_covered_instead_of_spinning() { + #[derive(Default)] + struct Due { polls: u32 } + fn poll(app: &mut Due, _: f64, tx: &mut Tx) -> bool { + app.polls += 1; + tx.wake_after(Duration::from_millis(100)); + true + } + let mut rt = Runtime::new(Due::default(), |_, _| crate::el().size(20.0, 20.0), (20.0, 20.0), crate::Env::default()); + rt.poll = Some(poll); + rt.wall_start = Some(crate::time::now()); + rt.frame(0.0); + // A change since that frame, as a `wake` whose poll it hasn't drawn leaves it. + rt.invalidate(); + assert!(rt.stale() && !rt.rests(), "the window doesn't rest: its frame is still to come"); + // As `new_events` at the timer, which is due by the time the loop runs for it. + let due = timer_deadline(&rt).expect("a timer is armed"); + rt.wall_start = rt.wall_start.map(|t| t - due.saturating_duration_since(crate::time::now()) - Duration::from_millis(1)); + let now = crate::time::now(); + assert!(timer_deadline(&rt).expect("armed") <= now, "the timer is due: this is what turned the loop"); + + let mut frame = TimerFrame::default(); + frame.asked_quiet(now); + assert_eq!(frame.wait(timer_deadline(&rt), now), Some(now + TIMER_FRAME_STALL), + "the frame the timer asked for keeps the loop asleep until the bound"); + assert!(!frame.stalled(now + TIMER_FRAME_STALL - Duration::from_millis(1))); + assert!(frame.stalled(now + TIMER_FRAME_STALL), "after the bound the timer runs covered"); + + let polls = rt.state.polls; + covered_step(&mut rt); + assert_eq!(rt.state.polls, polls + 1, "the due timer polled"); + let next = timer_deadline(&rt).expect("its next timer is armed"); + assert!(next > crate::time::now(), "the next timer is ahead: {next:?}"); + // The covered step takes the frame's place, and a timer still ahead keeps its own time. + frame.drawn(); + frame.asked_quiet(crate::time::now()); + assert_eq!(frame.wait(timer_deadline(&rt), crate::time::now()), Some(next), "the loop sleeps until its next timer"); + frame.drawn(); + assert!(!frame.stalled(now + TIMER_FRAME_STALL), "a frame that comes clears it"); +} + +#[test] +fn a_window_s_first_updates_can_register_on_a_later_window() { + use crate::{App, AppSpec, MenuItem, el}; + type S = Vec<String>; + let apps: Vec<App<S>> = ["first", "second"].map(|title| App::new(AppSpec::new(title, (10.0, 10.0), Vec::new, |_, _| el()))).into(); + let second = apps[1].handle(); + apps[0].handle().update(move |s: &mut S, _| { + s.push(format!("{:?}", second.register_shortcut("ctrl+alt+shift+f18".parse().unwrap(), |_, _| {}).map(|_| ()))); + s.push(format!("{:?}", second.set_menu([MenuItem::new("Item", |_: &mut S, _| {})]))); + }); + // As Host::new and Host::resumed: attach the guards, then drain the first updates. + let hosts = start_all(apps.into(), |_, app| { + let shortcuts = crate::shortcuts::Guard::attach(&app.shared, Arc::new(|| {}), true, false); + let menus = crate::native_menu::MenuGuard::attach(&app.shared, true); + Some((app, shortcuts, menus, S::new())) + }, |(app, _, _, state)| for f in app.shared.take().updates { f(state, &mut Tx::default()); }); + assert_eq!(hosts[0].as_ref().unwrap().3, ["Ok(())", "Ok(())"]); +} + +/// A chord pressed before launch, then another thread's update that reads what the press did: +/// the startup batch runs the press first, on this host's state. +#[test] +fn a_shortcut_pressed_before_launch_runs_before_the_updates_queued_after_it() { + use crate::{App, AppSpec, el}; + type S = Vec<String>; + const CHORD: &str = "ctrl+alt+shift+f19"; + let app: App<S> = App::new(AppSpec::new("startup", (10.0, 10.0), Vec::new, |_, _| el())) + .global_shortcut(CHORD, |s: &mut S, _| s.push("pressed".into())); + // As Host::new: the guard attaches and registers the App's shortcuts. + let shortcuts = crate::shortcuts::Guard::attach(&app.shared, Arc::new(|| {}), true, false); + // The press, queued as the backend's sink queues it, on the thread that owns the engine. + app.shared.shortcuts.fire(&CHORD.parse().unwrap()).unwrap(); + let handle = app.handle(); + std::thread::spawn(move || handle.update(|s: &mut S, _| { let seen = s.len(); s.push(format!("saw {seen}")); })).join().unwrap(); + // As Host::resume. + let mut state = S::new(); + host::events::startup_updates(&app.shared, &shortcuts, |f| { f(&mut state, &mut Tx::default()); }); + assert_eq!(state, ["pressed", "saw 1"], "the press ran first, in the startup batch"); + assert!(app.shared.take().updates.is_empty(), "nothing waits for a later drain"); +} + +#[test] +fn drag_region_policy_preserves_titled_windows_and_panels() { + for enabled in [false, true] { + for full_size in [false, true] { + let chrome = Chrome { drag_regions: enabled, full_size_content: full_size, ..Chrome::DEFAULT }; + assert_eq!(uses_drag_regions(chrome, false, false), enabled && full_size); + assert_eq!(uses_drag_regions(chrome, true, false), enabled); + assert!(!uses_drag_regions(chrome, false, true)); + assert!(!uses_drag_regions(chrome, true, true)); + } + } +} + +/// A GPU-free wgpu instance. +#[cfg(all(target_os = "linux", feature = "test-gpu-noop"))] +fn noop_instance() -> wgpu::Instance { + let mut descriptor = wgpu::InstanceDescriptor::new_without_display_handle(); + descriptor.backends = wgpu::Backends::NOOP; + descriptor.backend_options.noop.enable = true; + wgpu::Instance::new(descriptor) +} + +/// A GPU on wgpu's noop backend: its device takes anything and refuses every surface. +#[cfg(all(target_os = "linux", feature = "test-gpu-noop"))] +#[allow(unsafe_code)] +fn noop_gpu(instance: &wgpu::Instance) -> (Gpu, wgpu::Surface<'static>) { + use std::num::NonZeroU32; + use std::ptr::NonNull; + use winit::raw_window_handle::{RawDisplayHandle, RawWindowHandle, XcbDisplayHandle, XcbWindowHandle}; + // SAFETY: `instance` uses only wgpu's NOOP backend, which never dereferences the raw handles. + let surface = unsafe { + instance.create_surface_unsafe(wgpu::SurfaceTargetUnsafe::RawHandle { + raw_display_handle: Some(RawDisplayHandle::Xcb(XcbDisplayHandle::new(Some(NonNull::dangling()), 0))), + raw_window_handle: RawWindowHandle::Xcb(XcbWindowHandle::new(NonZeroU32::new(1).unwrap())), + }) + } + .unwrap(); + let adapter = pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions::default())).unwrap(); + let (device, queue) = pollster::block_on(adapter.request_device(&wgpu::DeviceDescriptor::default())).unwrap(); + (Gpu::from_device(instance.clone(), adapter, device, queue), surface) +} + +/// What the noop backend takes for a surface: the format the test configures it in. +#[cfg(all(target_os = "linux", feature = "test-gpu-noop"))] +fn noop_config() -> wgpu::SurfaceConfiguration { + wgpu::SurfaceConfiguration { + usage: wgpu::TextureUsages::RENDER_ATTACHMENT, + format: wgpu::TextureFormat::Bgra8UnormSrgb, + width: 200, + height: 80, + present_mode: wgpu::PresentMode::AutoVsync, + desired_maximum_frame_latency: 2, + alpha_mode: wgpu::CompositeAlphaMode::PreMultiplied, + view_formats: vec![], + color_space: Default::default(), + } +} + +/// A surface that refuses its configuration reports it as an error its owner can drop, not a +/// panic in wgpu's default handler that takes the app's every window with it (hex#979). +#[cfg(all(target_os = "linux", feature = "test-gpu-noop"))] +#[test] +fn a_refused_surface_configuration_is_an_error_not_a_panic() { + let instance = noop_instance(); + let (gpu, surface) = noop_gpu(&instance); + let config = noop_config(); + let error = configure(&surface, &gpu, &config).unwrap_err(); + assert!(error.starts_with("Validation Error: In Surface::configure"), "{error}"); + assert!(error.ends_with("(200x80, Bgra8UnormSrgb, PreMultiplied, AutoVsync)"), "{error}"); +} + +/// A surface whose configuration failed has no presentation, and wgpu panics +/// ("Surface is not configured for presentation") on the drawable Rune would ask it for. The +/// acquire reports the miss instead, and the window makes a surface and device before its next +/// frame (hex's Modern Standby panic). +#[cfg(all(target_os = "linux", feature = "test-gpu-noop"))] +#[test] +fn a_surface_with_no_presentation_is_never_asked_for_a_drawable() { + let instance = noop_instance(); + let (gpu, surface) = noop_gpu(&instance); + let config = noop_config(); + configure(&surface, &gpu, &config).expect_err("the noop surface refuses its configuration"); + let mut meter = SurfaceMeter::new("unconfigured", Arc::default()); + assert_eq!(acquire(&surface, &gpu, &config, false, 1, &mut meter), Err(Missed::Unconfigured)); + assert_eq!(meter.totals().failed(), 1, "the miss is counted"); +} + +/// `Device::destroy` only marks the device invalid: its lost callback runs when the device next +/// maintains itself, which `configure` does with a poll. Without that poll the surface gets no +/// presentation while `is_lost` still reads false, `configure` says Ok, and the drawable the next +/// frame asks for panics ("Surface is not configured for presentation"). +#[cfg(all(target_os = "linux", feature = "test-gpu-noop"))] +#[test] +fn a_destroyed_device_that_has_not_reported_its_loss_is_not_configured() { + let instance = noop_instance(); + let (gpu, surface) = noop_gpu(&instance); + let config = noop_config(); + gpu.device.destroy(); + assert!(!gpu.is_lost(), "the callback waits for the device's next maintain"); + let error = configure(&surface, &gpu, &config).unwrap_err(); + assert!(error.starts_with("the GPU device was lost"), "{error}"); + assert!(gpu.is_lost()); + let mut meter = SurfaceMeter::new("destroyed", Arc::default()); + assert_eq!(acquire(&surface, &gpu, &config, true, 1, &mut meter), Err(Missed::Unconfigured)); +} + +/// A surface that won't come back is replaced a bounded number of times, waiting longer after +/// each failure, and then the window gives it up: a lost device can never be replaced, and a +/// frame must not ask again forever. +#[test] +fn surface_replacements_give_up_after_a_bounded_number_of_tries() { + use super::surface::win::{SurfaceStep, SURFACE_TRIES}; + let now = crate::time::now(); + let mut retries = SurfaceRetries::default(); + let mut waits = Vec::new(); + loop { + assert_eq!(retries.attempt(), SurfaceStep::Replace); + match retries.retry(now) { + Some(at) => waits.push(at - now), + None => break, + } + assert!(waits.len() < 100, "a replacement that keeps failing never gives up"); + } + assert_eq!(waits.len() as u8, SURFACE_TRIES - 1, "one try, then bounded retries"); + assert!(waits.windows(2).all(|pair| pair[1] > pair[0]), "each wait is longer: {waits:?}"); + assert_eq!(retries.failures(), SURFACE_TRIES); + assert_eq!(retries.attempt(), SurfaceStep::GiveUp); + + // A frame that reached the screen starts over. + retries.worked(); + assert_eq!(retries.failures(), 0); + assert_eq!(retries.attempt(), SurfaceStep::Replace); +} + +/// A replacement that works still counts: a surface replaced and lost again before its frame +/// presents gives the window up after `SURFACE_TRIES` replacements instead of making one +/// forever. This is the shape `Host::replace_lost_surface` runs, where only `draw`'s present +/// calls `worked`. +#[test] +fn a_surface_lost_after_every_replacement_gives_up_after_the_tries() { + use super::surface::win::{SurfaceStep, SURFACE_TRIES}; + let mut retries = SurfaceRetries::default(); + let mut replaced = 0; + while retries.attempt() == SurfaceStep::Replace { + // The replacement worked, and the frame it made was lost before it presented. + replaced += 1; + assert!(replaced < 100, "a surface lost before it presents never stops being replaced"); + } + assert_eq!(replaced, SURFACE_TRIES, "the window gives up after a bounded number of replacements"); + + // One frame reaches the screen: the next loss starts over. + retries.worked(); + assert_eq!(retries.attempt(), SurfaceStep::Replace); +} + +/// A device that went away (a driver reset, a GPU removed, Windows' Modern Standby) configures +/// nothing, and wgpu drops the `DeviceLost` that would say so: `configure` reports the lost +/// device itself, and no drawable is ever asked of it. +#[cfg(all(target_os = "linux", feature = "test-gpu-noop"))] +#[test] +fn a_lost_device_is_reported_and_never_drawn_with() { + let instance = noop_instance(); + let (gpu, surface) = noop_gpu(&instance); + let config = noop_config(); + assert!(!gpu.is_lost()); + gpu.device.destroy(); + // wgpu loses a destroyed device once its queues drain, when the device next maintains itself. + gpu.device.poll(wgpu::PollType::wait_indefinitely()).ok(); + assert!(gpu.is_lost(), "the device's lost callback marks it"); + let error = configure(&surface, &gpu, &config).unwrap_err(); + assert!(error.starts_with("the GPU device was lost"), "{error}"); + let mut meter = SurfaceMeter::new("lost", Arc::default()); + assert_eq!(acquire(&surface, &gpu, &config, true, 1, &mut meter), Err(Missed::Unconfigured)); + assert_eq!(meter.totals().failed(), 1, "a lost device is a miss, not a panic"); +} + +/// Each Rune GPU has its own wgpu instance, and wgpu compares devices by an id each instance +/// numbers from the start, so a new GPU's device equals the old one's. A renderer's device key +/// tells them apart, so a compositor keeping resources by it remakes them (hex#982). +#[cfg(all(target_os = "linux", feature = "test-gpu-noop"))] +#[test] +fn a_new_gpus_device_equals_the_old_one_but_its_key_differs() { + let device = || { + let adapter = pollster::block_on(noop_instance().request_adapter(&wgpu::RequestAdapterOptions::default())).unwrap(); + pollster::block_on(adapter.request_device(&wgpu::DeviceDescriptor::default())).unwrap().0 + }; + let (old, new) = (device(), device()); + assert!(old == new, "wgpu tells devices of separate instances apart by now: device equality may do"); + let format = wgpu::TextureFormat::Bgra8Unorm; + let (old, new) = (crate::render::Renderer::new(&old, format), crate::render::Renderer::new(&new, format)); + assert_ne!(old.device_key(), new.device_key()); +} + +/// The surface alpha mode is the one a window had before the frame existed, unless only a frame's +/// corner pixels need it: then it takes premultiplied alpha alone, or stays opaque. +#[test] +fn the_surface_alpha_mode_follows_what_the_window_asked_for() { + use crate::window::host::create::alpha_mode; + use wgpu::CompositeAlphaMode::{Inherit, Opaque, PostMultiplied, PreMultiplied}; + + // An app that asked for a translucent window keeps every mode it always had, straight alpha + // included — Metal offers only `PostMultiplied` — and a surface with none draws it opaque. + for (supports, want) in [ + (Some(PreMultiplied), PreMultiplied), + (Some(PostMultiplied), PostMultiplied), + (Some(Inherit), Inherit), + (None, Opaque), + ] { + assert_eq!(alpha_mode(true, false, supports), want, "transparent, {supports:?}"); + assert_eq!(alpha_mode(true, true, supports), want, "transparent with a frame, {supports:?}"); + } + + // A window that only needs its frame's corner pixels transparent takes premultiplied alpha, + // and is square rather than straight-alpha when the surface has nothing else. + assert_eq!(alpha_mode(false, true, Some(PreMultiplied)), PreMultiplied); + for supports in [Some(PostMultiplied), Some(Inherit), Some(Opaque), None] { + assert_eq!(alpha_mode(false, true, supports), Opaque, "corners only, {supports:?}"); + } + + // No frame and no transparency: nothing to keep alpha for. + for supports in [Some(PreMultiplied), Some(PostMultiplied), None] { + assert_eq!(alpha_mode(false, false, supports), Opaque, "opaque window, {supports:?}"); + } +} + +/// A square window (maximized, tiled or fullscreen) never asks the corner pass to draw, whatever +/// state the pass is in. +#[test] +fn a_square_window_never_fades_its_corners() { + use crate::render::{Gpu, Offscreen, OFFSCREEN_FORMAT}; + let gpu = Gpu::new(Gpu::instance(), None); + let size = (8, 8); + let target = Offscreen::new(&gpu.device, size.0, size.1); + let mut enc = gpu.device.create_command_encoder(&Default::default()); + { + let _clear = enc.begin_render_pass(&wgpu::RenderPassDescriptor { + label: None, + color_attachments: &[Some(wgpu::RenderPassColorAttachment { + view: &target.view, + depth_slice: None, + resolve_target: None, + ops: wgpu::Operations { load: wgpu::LoadOp::Clear(wgpu::Color::RED), store: wgpu::StoreOp::Store }, + })], + depth_stencil_attachment: None, + timestamp_writes: None, + occlusion_query_set: None, + multiview_mask: None, + }); + } + let mut pass = crate::render::csd_corners::CsdCorners::new(&gpu.device, OFFSCREEN_FORMAT); + pass.prepare(&gpu.queue, size, 0.); + surface::corners::draw(Some(&pass), &mut enc, &target.view, 0.); + target.copy(&mut enc); + gpu.queue.submit([enc.finish()]); + let pixels = target.read(&gpu.device); + for (i, pixel) in pixels.chunks_exact(4).enumerate() { + assert_eq!(pixel[3], 255, "pixel {i} faded with no radius"); + } +} diff --git a/app/vendor/rune/crates/rune/src/window/titlebar.rs b/app/vendor/rune/crates/rune/src/window/titlebar.rs new file mode 100644 index 0000000..cb8368f --- /dev/null +++ b/app/vendor/rune/crates/rune/src/window/titlebar.rs @@ -0,0 +1,220 @@ +//! A titlebar the app draws itself (`App::titlebar`), and where the window's own controls sit +//! over it (`Cx::chrome_insets`). +//! +//! The app declares how tall its titlebar is; Rune takes the native one away and keeps the +//! window's controls over the app's: AppKit's traffic lights at the leading edge on macOS, and +//! the minimize, maximize and close buttons at the trailing edge on Windows, which Rune draws +//! as elements over the view. The app keeps clear of [`ChromeInsets`] and marks the parts +//! that move the window with `.window_drag()`; hit targets inside them keep their presses. + +use crate::Chrome; + +mod caption; + +pub(crate) use caption::{BUTTONS_KEY, FRAME_KEY, frame}; + +/// The app draws its own titlebar across the top of the window, `height` points tall +/// (`App::titlebar`, `WindowSpec::titlebar`). Plain data, the same on every platform: +/// +/// - **macOS:** a full-size content view under a transparent titlebar, `.window_drag()` +/// regions only (`Chrome::drag_regions`), and the traffic lights centred in the band unless +/// `Chrome::traffic_lights` places them. +/// - **Windows:** no native title bar. The window keeps its resize edges, Aero Snap, the snap +/// layouts flyout over maximize (Windows 11), the window menu (Alt+Space, or a right-click on +/// a `.window_drag()` region) and its animations; Rune draws the three caption buttons over +/// the trailing edge at the band's height, as Electron's `titleBarOverlay` does. +/// - **Elsewhere:** the native frame stays and [`ChromeInsets`] is zero. +/// +/// `Cx::titlebar_height` changes the height while the app runs, as a UI zoom does, and +/// `Cx::set_titlebar` the whole titlebar, as a switch between layouts does. A borderless window +/// has no titlebar to replace, and ignores it. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Titlebar { + height: f32, + traffic_lights: Option<(f32, f32)>, +} + +impl Titlebar { + /// A caption button's width in points: Windows' and Electron's 46. + pub const CAPTION_BUTTON_WIDTH: f32 = 46.0; + + pub const fn new(height: f32) -> Self { + Self { height, traffic_lights: None } + } + + /// macOS: the close button's top-left, in points from the window's top-left, for this + /// titlebar (Electron's `trafficLightPosition`), in place of `Chrome::traffic_lights` and + /// the band's middle. Ignored elsewhere and in full screen. + pub const fn traffic_lights(mut self, x: f32, y: f32) -> Self { + self.traffic_lights = Some((x, y)); + self + } + + pub fn height(&self) -> f32 { + self.height + } + + /// Where [`Self::traffic_lights`] put the close button, if it did. + pub fn traffic_lights_origin(&self) -> Option<(f32, f32)> { + self.traffic_lights + } + + /// The frame macOS draws for this titlebar over `chrome`: full-size content, drag regions + /// only, and the traffic lights where this titlebar or the app placed them, else in the + /// band's middle. + pub(crate) fn mac_chrome(&self, chrome: Chrome) -> Chrome { + let y = ((self.height - Chrome::TRAFFIC_LIGHT) / 2.0).max(0.0).round(); + let lights = self.traffic_lights.or(chrome.traffic_lights).or(Some((16.0, y))); + Chrome { full_size_content: true, drag_regions: true, traffic_lights: lights } + } +} + +/// What the view set of the window's titlebar on its last run: `Cx::set_titlebar`, then +/// `Cx::titlebar_height` over it. Empty keeps `App::titlebar`'s. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub(crate) struct TitlebarSet { + pub titlebar: Option<Titlebar>, + pub height: Option<f32>, +} + +impl TitlebarSet { + /// The titlebar the window draws in place of the app's `base`. + pub(crate) fn over(self, base: Titlebar) -> Titlebar { + let titlebar = self.titlebar.unwrap_or(base); + self.height.map_or(titlebar, |height| Titlebar { height, ..titlebar }) + } +} + +/// What the window's own controls take of the app's titlebar, in points +/// (`Cx::chrome_insets`). The view re-runs when it changes: entering or leaving full screen, +/// a scale change, `Cx::titlebar_height`, `Cx::set_titlebar`. Memos rebuild with it too, so a +/// `memo` closure that reads it needs nothing in its version. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +#[non_exhaustive] +pub struct ChromeInsets { + /// From the window's left edge to the end of the controls there: the macOS traffic lights + /// (`Cx::titlebar_inset`), or the Windows caption buttons when the app's language reads right + /// to left (`labels::set_direction`), where the traffic lights move to the right instead. 0 in full + /// screen and elsewhere. + pub leading: f32, + /// From the window's right edge to the start of the controls there: the Windows caption + /// buttons, unless they're mirrored to the left, or the macOS traffic lights in a right-to-left + /// app. 0 in full screen and elsewhere. + pub trailing: f32, + /// The titlebar's height as the window draws it: [`Titlebar::height`] where Rune replaced + /// the native titlebar, 0 where the native frame stays (no `App::titlebar`, Linux, a + /// borderless window). + pub height: f32, +} + +impl ChromeInsets { + pub(crate) fn new(leading: f32, trailing: f32, height: f32) -> Self { + Self { leading, trailing, height } + } + + /// The insets, in window points, in the points of a view zoomed `k` times (`Cx::zoom`). + pub(crate) fn zoomed(self, k: f32) -> Self { + Self { leading: self.leading / k, trailing: self.trailing / k, height: self.height / k } + } + + /// The bits a memo scope hashes, so memos rebuild when the insets change. + pub(crate) fn bits(&self) -> [u32; 3] { + [self.leading, self.trailing, self.height].map(f32::to_bits) + } +} + +/// One of the Windows caption buttons. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum CaptionButton { + Minimize, + Maximize, + Close, +} + +impl CaptionButton { + const ALL: [CaptionButton; 3] = [CaptionButton::Minimize, CaptionButton::Maximize, CaptionButton::Close]; +} + +/// Where the pointer is with the caption buttons. The system answers presses on them as +/// non-client hits, so the buttons see neither hover nor press as pointer events: the window +/// procedure keeps this, and the buttons draw from it. +#[cfg_attr(not(target_os = "windows"), allow(dead_code))] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(crate) enum CaptionState { + #[default] + Idle, + /// Over `button` with no press. + Hovered(CaptionButton), + /// A press began on `button`; `over` while the pointer is still on it. Releasing there acts. + Pressed { button: CaptionButton, over: bool }, +} + +/// The caption buttons Rune draws over a custom titlebar on Windows. +#[derive(Clone, Copy, Debug, PartialEq)] +pub(crate) struct Caption { + pub height: f32, + pub state: CaptionState, + pub maximized: bool, + /// The window has a minimize box (`WS_MINIMIZEBOX`); without one, the button is dimmed. + pub minimizable: bool, + /// The window has a maximize box (`WS_MAXIMIZEBOX`); a window without one, a window that + /// isn't resizable, never maximizes, and the button is dimmed. + pub maximizable: bool, + /// Full screen: the window draws no buttons, but keeps the frame that hosts them. + pub hidden: bool, + /// The app's language reads right to left (`labels::set_direction`): the buttons sit at the + /// window's top-left, Close first, as Windows mirrors a right-to-left window's caption and + /// Chrome and Edge draw theirs in Arabic or Hebrew. + pub mirrored: bool, +} + +impl Caption { + pub(crate) fn new(height: f32) -> Self { + Self { height, state: CaptionState::Idle, maximized: false, minimizable: true, maximizable: true, hidden: false, mirrored: crate::labels::rtl() } + } + + /// The buttons drawn, left to right. A window that can neither minimize nor maximize shows + /// only Close, as Windows draws its native caption. + pub(crate) fn buttons(&self) -> &'static [CaptionButton] { + match (self.hidden, self.minimizable || self.maximizable) { + (true, _) => &[], + (false, true) => &CaptionButton::ALL, + (false, false) => &[CaptionButton::Close], + } + } + + /// Whether `button` does anything: a press on a dimmed button doesn't. + pub(crate) fn enabled(&self, button: CaptionButton) -> bool { + match button { + CaptionButton::Minimize => self.minimizable, + CaptionButton::Maximize => self.maximizable, + CaptionButton::Close => true, + } + } + + /// The buttons' rects, in [`Caption::buttons`]' order, in points from the window's top-left for + /// a window `width` points wide at `scale`: each a whole number of pixels, flush with the right + /// edge, or the left one mirrored (Close leftmost). + #[cfg_attr(not(target_os = "windows"), allow(dead_code))] + pub(crate) fn rects(&self, width: f32, scale: f32) -> impl Iterator<Item = (CaptionButton, [f32; 4])> + use<> { + let (w, h) = caption::size(self.height, scale); + let buttons = self.buttons(); + let (n, mirrored) = (buttons.len(), self.mirrored); + buttons.iter().enumerate().map(move |(i, &b)| (b, [if mirrored { w * (n - 1 - i) as f32 } else { width - w * (n - i) as f32 }, 0.0, w, h])) + } + + /// The enabled button at (x, y), in points from the window's top-left, in a window `width` + /// points wide at `scale`. + #[cfg_attr(not(target_os = "windows"), allow(dead_code))] + pub(crate) fn hit(&self, width: f32, scale: f32, (x, y): (f32, f32)) -> Option<CaptionButton> { + self.rects(width, scale) + .find(|(_, [rx, ry, rw, rh])| x >= *rx && x < rx + rw && y >= *ry && y < ry + rh) + .map(|(button, _)| button) + .filter(|&b| self.enabled(b)) + } + + /// Points the buttons take from their edge at `scale`: the right, or the left mirrored. + pub(crate) fn width(&self, scale: f32) -> f32 { + caption::size(self.height, scale).0 * self.buttons().len() as f32 + } +} diff --git a/app/vendor/rune/crates/rune/src/window/titlebar/caption.rs b/app/vendor/rune/crates/rune/src/window/titlebar/caption.rs new file mode 100644 index 0000000..4820ba1 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/window/titlebar/caption.rs @@ -0,0 +1,161 @@ +//! The Windows caption buttons as elements, drawn as Electron's `titleBarOverlay` draws them +//! (Chromium's Windows 11 icon painter): a 10 px symbol with a stroke of one device pixel, +//! hover and press washes of the symbol colour, and a red close button. + +use std::rc::Rc; + +use crate::el::{el, row}; +use crate::{Color, El, LineCap, Shape}; + +use super::{Caption, CaptionButton, CaptionState, Titlebar}; + +/// The close button's hover fill, Windows' own red. +const CLOSE_RED: Color = Color { r: 0.807_5, g: 0.005_8, b: 0.016_9, a: 1.0 }; +/// Washes over the other buttons, as fractions of the symbol colour's alpha. +const HOVER_ALPHA: f32 = 0x1A as f32 / 255.0; +const PRESSED_ALPHA: f32 = 0x33 as f32 / 255.0; +/// The close button's red while pressed. +const CLOSE_PRESSED_ALPHA: f32 = 0x98 as f32 / 255.0; +/// A disabled button's symbol, as a fraction of the symbol colour's alpha: Windows 11's +/// disabled text. +const DISABLED_ALPHA: f32 = 0x5C as f32 / 255.0; + +/// A button's width and height in points at `scale`, each a whole number of pixels. +pub(super) fn size(height: f32, scale: f32) -> (f32, f32) { + let snap = |pt: f32| (pt * scale).round().max(1.0) / scale; + (snap(Titlebar::CAPTION_BUTTON_WIDTH), snap(height)) +} + +/// The view's root under the caption buttons, in a frame of Rune's own the window's size: the +/// buttons sit at the window's top-right corner whatever the root's border, clip or transform, +/// and stay in reach of the pointer and assistive technology while the view holds a modal +/// (`Runtime::refresh_modal_index`). `symbol` is the glyph colour (`Cx::caption_color`). A +/// full-screen window keeps the frame with no buttons in it, so the view's paths stay. `scale` +/// is the view's (device pixels per view point) and `zoom` its `Cx::zoom`: the buttons keep the +/// window's size at every zoom, as Electron's `titleBarOverlay` does. +pub(crate) fn frame(root: El, caption: &Caption, symbol: Color, (scale, zoom): (f32, f32), fit_height: bool) -> El { + let root = if fit_height { root.w_full() } else { root.w_full().h_full() }; + el().key(FRAME_KEY).child(root).children((!caption.hidden).then(|| buttons(caption, symbol, scale, zoom))) +} + +/// The frame `frame` puts around the view's root. +pub(crate) const FRAME_KEY: &str = "rune-frame"; +/// The row of caption buttons in it. +pub(crate) const BUTTONS_KEY: &str = "rune-caption"; + +/// The buttons pinned to the frame's top-right corner (top-left mirrored), over everything the +/// view drew. +fn buttons(caption: &Caption, symbol: Color, scale: f32, zoom: f32) -> El { + // Sized in window points at the window's scale, then drawn in the view's points. + let window = scale / zoom; + let (w, h) = size(caption.height, window); + let (w, h) = (w / zoom, h / zoom); + // Mirrored, the row sits at the top-left with Close first (`Caption::rects`). + let (left, right) = if caption.mirrored { (Some(0.0), None) } else { (None, Some(0.0)) }; + let buttons: Vec<El> = caption.buttons().iter().map(|&button| caption_button(caption, button, symbol, (w, h), (scale, window))).collect(); + let buttons = if caption.mirrored { buttons.into_iter().rev().collect() } else { buttons }; + row().key(BUTTONS_KEY).dir(crate::Direction::Ltr).pin(left, Some(0.0), right, None).children(buttons) +} + +fn caption_button(caption: &Caption, button: CaptionButton, symbol: Color, (w, h): (f32, f32), scales: (f32, f32)) -> El { + let enabled = caption.enabled(button); + let (hovered, pressed) = match caption.state { + CaptionState::Pressed { button: b, over: true } if b == button => (true, true), + CaptionState::Hovered(b) if b == button => (true, false), + _ => (false, false), + }; + let (fill, ink) = match button { + _ if !enabled => (Color::TRANSPARENT, symbol.alpha(symbol.a * DISABLED_ALPHA)), + CaptionButton::Close if pressed => (CLOSE_RED.alpha(CLOSE_PRESSED_ALPHA), Color::WHITE), + CaptionButton::Close if hovered => (CLOSE_RED, Color::WHITE), + _ if pressed => (symbol.alpha(symbol.a * PRESSED_ALPHA), symbol), + _ if hovered => (symbol.alpha(symbol.a * HOVER_ALPHA), symbol), + _ => (Color::TRANSPARENT, symbol), + }; + let (key, label) = match button { + CaptionButton::Minimize => ("rune-caption-minimize", "Minimize"), + CaptionButton::Maximize if caption.maximized => ("rune-caption-maximize", "Restore"), + CaptionButton::Maximize => ("rune-caption-maximize", "Maximize"), + CaptionButton::Close => ("rune-caption-close", "Close"), + }; + let mut e = el().key(key).role("button").label(label).focusable(false).disabled(!enabled).size(w, h).fill(fill) + .child(symbol_el(button, caption.maximized, ink, (w, h), scales)); + // The mouse presses them through the window procedure; assistive technology invokes these. + // A dimmed button has nothing to invoke. + if enabled { + e.handlers.on_press = Some(Rc::new(move |_, tx: &mut crate::Tx| match button { + CaptionButton::Minimize => tx.minimize(), + CaptionButton::Maximize => tx.toggle_maximized(), + CaptionButton::Close => tx.close_window(), + })); + } + e +} + +/// The symbol, laid out in device pixels so its strokes land on whole pixels: `scale` is device +/// pixels per view point, `window` per window point, which sizes the glyph. +fn symbol_el(button: CaptionButton, maximized: bool, ink: Color, (w, h): (f32, f32), (scale, window): (f32, f32)) -> El { + let g = (10.0 * window).round(); + let s = window.round().max(1.0); + let (bw, bh) = ((w * scale).round(), (h * scale).round()); + let (x, y) = (((bw - g) / 2.0).floor(), ((bh - g) / 2.0).floor()); + let pt = 1.0 / scale; + let shape = match button { + CaptionButton::Minimize => { + let top = (g / 2.0).floor(); + Shape::new().fill(quad(0.0, top, g, s, pt), ink) + } + CaptionButton::Maximize if maximized => restore(g, s, (scale, window), ink), + CaptionButton::Maximize => { + let r = (1.5 * window).floor(); + Shape::new().stroke_with(rounded([s / 2.0, s / 2.0, g - s / 2.0, g - s / 2.0], [r; 4], pt), true, s * pt, LineCap::Round, ink) + } + CaptionButton::Close => { + let scaled = |p: [f32; 2]| [p[0] * pt, p[1] * pt]; + Shape::new() + .line(scaled([0.0, 0.0]), scaled([g, g]), s * pt * 1.05, LineCap::Butt, ink) + .line(scaled([g, 0.0]), scaled([0.0, g]), s * pt * 1.05, LineCap::Butt, ink) + } + }; + el().absolute(x * pt, y * pt).size(g * pt, g * pt).shape(shape).a11y_hidden() +} + +/// Two rounded squares: the front one at the bottom left, and the top and right edges of the +/// one behind it. +fn restore(g: f32, s: f32, (scale, window): (f32, f32), ink: Color) -> Shape { + let pt = 1.0 / scale; + let sep = 2.0 * window; + let r = (1.5 * window).floor(); + let half = s / 2.0; + let front = [half, sep + half, g - sep - half, g - half]; + let behind = [front[0] + sep, front[1] - sep, front[2] + sep, front[3] - sep]; + // Only the part of the square behind that clears the front one: from its top-left corner + // over the top and down the right side, stopping above the front square's top. + let back = rounded(behind, [r, 2.0 * r, r, r], pt); + let clear = |p: &[f32; 2]| p[1] < (front[1] - half) * pt || p[0] > (front[2] + half) * pt; + let visible: Vec<[f32; 2]> = back.into_iter().filter(clear).collect(); + Shape::new() + .stroke_with(rounded(front, [r; 4], pt), true, s * pt, LineCap::Round, ink) + .stroke_with(visible, false, s * pt, LineCap::Round, ink) +} + +/// A filled rectangle at pixel coordinates, as points. +fn quad(x: f32, y: f32, w: f32, h: f32, pt: f32) -> Vec<[f32; 2]> { + vec![[x * pt, y * pt], [(x + w) * pt, y * pt], [(x + w) * pt, (y + h) * pt], [x * pt, (y + h) * pt]] +} + +/// The outline of the rectangle `[left, top, right, bottom]` (pixels) with corner radii +/// `[top-left, top-right, bottom-right, bottom-left]`, clockwise from the top-left corner's +/// start, as points. +fn rounded([l, t, r, b]: [f32; 4], radii: [f32; 4], pt: f32) -> Vec<[f32; 2]> { + let corners = [([l, t], radii[0], 180.0), ([r, t], radii[1], 270.0), ([r, b], radii[2], 0.0), ([l, b], radii[3], 90.0)]; + corners.iter().flat_map(|&([x, y], radius, start)| { + let (dx, dy) = match start as i32 { 180 => (1.0, 1.0), 270 => (-1.0, 1.0), 0 => (-1.0, -1.0), _ => (1.0, -1.0) }; + let centre = [x + dx * radius, y + dy * radius]; + let steps = if radius > 0.0 { 4 } else { 0 }; + (0..=steps).map(move |i| { + let a = (start + 90.0 * i as f32 / steps.max(1) as f32).to_radians(); + [(centre[0] + radius * a.cos()) * pt, (centre[1] + radius * a.sin()) * pt] + }) + }).collect() +} diff --git a/app/vendor/rune/crates/rune/src/window/win32.rs b/app/vendor/rune/crates/rune/src/window/win32.rs new file mode 100644 index 0000000..83c1aa8 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/window/win32.rs @@ -0,0 +1,12 @@ +//! Windows-specific window host pieces: CPU first-frame rendering and GPU hand-over, +//! deferred post-frame chores, occlusion look, covered redraws, damage planning, swap-chain +//! waitable slots and DirectComposition video layers. + +pub(in crate::window) mod covered_draw; +pub(in crate::window) mod cpu_frame; +pub(in crate::window) mod damage; +pub(in crate::window) mod handover; +pub(in crate::window) mod look; +pub(in crate::window) mod post_frame; +pub(crate) mod slot; +pub(in crate::window) mod video_layer; diff --git a/app/vendor/rune/crates/rune/src/window/win32/covered_draw.rs b/app/vendor/rune/crates/rune/src/window/win32/covered_draw.rs new file mode 100644 index 0000000..539f10a --- /dev/null +++ b/app/vendor/rune/crates/rune/src/window/win32/covered_draw.rs @@ -0,0 +1,65 @@ +//! A covered window's last frame, kept current. Windows' compositor shows a window the moment +//! nothing covers it any more, with the last frame it presented, before the occlusion tracker +//! tells the window (`platform::win32::occlusion`, 60-95 ms on blade): a change made while it +//! was covered showed stale until then (a reply's footer arriving behind another window). So a +//! covered window that was asked for a frame still draws one, settled, once the changes go quiet +//! (`QUIET`) and no later than `LONGEST` after the first: motion that runs on while it's covered +//! draws at most once a second. + +use std::time::Duration; + +use crate::time::Instant; + +/// How long a covered window's changes must stop before it draws them. +const QUIET: Duration = Duration::from_millis(250); +/// The longest a covered window's change waits to be drawn. +const LONGEST: Duration = Duration::from_millis(1000); + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(in crate::window) enum CoveredDraw { + /// The last frame presented shows the window as it is. + #[default] + Current, + /// A frame was asked for while covered: drawn at `at`. + Owed { first: Instant, at: Instant }, + /// Its time came: the next frame draws, covered or not. + Drawing, +} + +#[derive(Clone, Copy, Debug)] +pub(in crate::window) enum CoveredDrawEvent { + /// A frame was asked for while the window was covered. + Asked(Instant), + /// The owed frame's time came. + Due, + /// The owed frame is drawing, or the window was uncovered (its first frame then draws). + Drawn, +} + +impl CoveredDraw { + pub(in crate::window) fn step(self, event: CoveredDrawEvent) -> CoveredDraw { + match (self, event) { + (CoveredDraw::Current, CoveredDrawEvent::Asked(now)) => CoveredDraw::Owed { first: now, at: now + QUIET }, + (CoveredDraw::Owed { first, .. }, CoveredDrawEvent::Asked(now)) => CoveredDraw::Owed { first, at: (now + QUIET).min(first + LONGEST) }, + (CoveredDraw::Owed { .. }, CoveredDrawEvent::Due) => CoveredDraw::Drawing, + (CoveredDraw::Drawing, CoveredDrawEvent::Asked(_)) | (CoveredDraw::Current | CoveredDraw::Drawing, CoveredDrawEvent::Due) => self, + (_, CoveredDrawEvent::Drawn) => CoveredDraw::Current, + } + } + + /// When the owed frame draws. + pub(in crate::window) fn deadline(self) -> Option<Instant> { + match self { + CoveredDraw::Current | CoveredDraw::Drawing => None, + CoveredDraw::Owed { at, .. } => Some(at), + } + } + + pub(in crate::window) fn due(self, now: Instant) -> bool { + self.deadline().is_some_and(|at| at <= now) + } + + pub(in crate::window) fn drawing(self) -> bool { + self == CoveredDraw::Drawing + } +} diff --git a/app/vendor/rune/crates/rune/src/window/win32/cpu_frame.rs b/app/vendor/rune/crates/rune/src/window/win32/cpu_frame.rs new file mode 100644 index 0000000..030c866 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/window/win32/cpu_frame.rs @@ -0,0 +1,501 @@ +//! Windows: a window that is live on the CPU from its first frame, and hands its frames to the GPU +//! once one is ready, without a seam (`handover`). +//! +//! The window opens with no GPU: the CPU renderer (`render::cpu_boot`) paints the real view into a +//! DIB section, the changed rectangles are copied to the window with GDI, and the window shows +//! with that frame in it. Input, hover, typing and animation run as on any frame. The view's text +//! and images stay where the CPU frames put them: masks the CPU filled upload on the GPU's first +//! frame, so the swap repaints nothing. + +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, Ordering}; + +use winit::event_loop::ActiveEventLoop; +use winit::window::Window; + +use super::covered_draw::{CoveredDraw, CoveredDrawEvent}; +use super::handover::{GpuJob, SurfaceMode, warm_instances}; +use crate::frame::clock::FrameClock; +use crate::frame::host_step::{self, Acquire, FrameHost, Gate, RenderPrep, StepInfo}; +use crate::platform::win32::dib::{Blit, Dib, Prefault}; +use crate::render::cpu_boot::{CpuPainter, HalfRounding, Scene, Target}; +use crate::runtime::RuntimeCore; +use crate::time::Instant; +use crate::window::chrome::{self, sync_chrome_core, sync_platform_core}; +use crate::window::handle::native_window_number; +use crate::window::host::Host; +use crate::window::host::stepping::FrameMove; +use crate::window::state::FirstFrame; +use crate::window::surface::{ + Backoff, BackoffEvent, FRAME_LATENCY, HiddenPace, LoopFrame, Native, Presented, Redraw, + SurfaceRetries, TIMER_FRAME, TimerFrame, Win, native, win, +}; +use crate::window::{WakeEvent, sync_screen_origin_core}; + +/// The CPU renderer's side of a window: the buffer it paints in place and the painter that +/// knows what the buffer last held. +pub(in crate::window) struct Cpu { + buffer: Buffer, + painter: CpuPainter, + /// How the GPU that takes over rounds half floats: the primary display's GPU's until that GPU + /// exists, then its own. + pub(super) half: HalfRounding, + /// What the window has of the buffer. + pub(super) shown: Shown, + /// Until the first frame is painted: the window shows with it, then, activating when `true`. + show: Option<bool>, +} + +/// What a CPU window has of its buffer. GDI draws nothing into a hidden window, so the first +/// frame waits in the buffer until the window shows (cloaked: DWM composes it only once it's in). +pub(super) enum Shown { + /// Nothing painted yet. + Nothing, + /// The first frame is painted; the window gets all of it when it shows. + Waiting, + /// The last frame copied was `size` big. + Copied((u32, u32)), +} + +/// A window's frame buffer, as big as the window's display (or the window, if larger): a new one +/// has the first frame's rows touched on a worker while that frame is laid out, then it's the +/// window's for every size that fits, with one row length. +enum Buffer { + /// Being touched; `capacity` is its size. + Touching(Prefault, (u32, u32)), + Ready(Dib), + /// GDI had no memory for one: the next frame tries again. + Missing, +} + +/// The buffer for a client area of `size`: the one there is while it fits; a bigger one (the +/// painter then repaints every tile) when the window outgrew it. +fn ready<'a>(buffer: &'a mut Buffer, painter: &mut CpuPainter, size: (u32, u32)) -> Option<&'a mut Dib> { + let was = std::mem::replace(buffer, Buffer::Missing); + let grown = |at: (u32, u32), painter: &mut CpuPainter| { + painter.forget(); + Dib::new(size.0.max(at.0), size.1.max(at.1)).map_or(Buffer::Missing, Buffer::Ready) + }; + *buffer = match was { + Buffer::Ready(dib) if dib.fits(size) => Buffer::Ready(dib), + Buffer::Ready(dib) => grown((dib.stride() as u32 / 4, 0), painter), + Buffer::Touching(prefault, at) if size.0 <= at.0 && size.1 <= at.1 => match prefault.take() { + Some(dib) => Buffer::Ready(dib), + None => grown(at, painter), + }, + Buffer::Touching(_, at) => grown(at, painter), + Buffer::Missing => grown((0, 0), painter), + }; + match buffer { + Buffer::Ready(dib) => Some(dib), + Buffer::Touching(..) | Buffer::Missing => None, + } +} + +impl Cpu { + pub(super) fn into_dib(self) -> Option<Dib> { + match self.buffer { + Buffer::Ready(dib) => Some(dib), + Buffer::Touching(prefault, _) => prefault.take(), + Buffer::Missing => None, + } + } +} + +/// The last frame copied to the window, whole, again (`draw_cpu`). +fn copy_last(cpu: &Cpu, window: &Window) { + let (Shown::Copied(size), Buffer::Ready(dib)) = (&cpu.shown, &cpu.buffer) else { return }; + if let Some(hwnd) = crate::platform::win32::hwnd(window) { dib.present(hwnd, *size, Blit::All); } +} + +/// The first frame, painted while the window was hidden, into the window that now shows, whole +/// (nothing composes the window before its cloak lifts). +fn copy_first(cpu: &mut Cpu, window: &Window, size: (u32, u32)) { + let (Shown::Waiting, Buffer::Ready(dib)) = (&cpu.shown, &cpu.buffer) else { return }; + let Some(hwnd) = crate::platform::win32::hwnd(window) else { return }; + dib.present(hwnd, size, Blit::All); + cpu.shown = Shown::Copied(size); + crate::marks::mark("frame.first.copied"); +} + +/// Threads the CPU renderer paints on: the UI thread and up to five workers that park between +/// frames. +fn painter_threads() -> usize { + std::thread::available_parallelism().map_or(4, |n| n.get()).clamp(1, 6) +} + +/// Whether a window opens on the CPU: an opaque window while no window has a GPU yet (with one, +/// a new window's swap chain is ready in a few milliseconds), unless turned off +/// (`RUNE_CPU_FIRST=0`). +pub(in crate::window) fn opens_on_cpu(host: &Host) -> bool { + !host.options.transparent && host.gpu.is_none() + && host.gpu_pool.borrow().upgrade().is_none_or(|gpu| gpu.is_lost()) + && std::env::var_os("RUNE_CPU_FIRST").is_none_or(|v| v != "0") +} + +impl Host { + /// The CPU side for a new window of `size` physical pixels on a display of `display`: a + /// buffer as big as the larger, whose first frame's rows a worker touches while that frame is + /// laid out, and a painter. The text system queues glyph masks for the painter's fill from + /// now on. Returns the buffer's size with it. + pub(in crate::window) fn cpu_side(&mut self, size: (u32, u32), display: (u32, u32)) -> Option<(Prefault, (u32, u32), CpuPainter)> { + let capacity = (size.0.max(display.0), size.1.max(display.1)); + let dib = Dib::new(capacity.0, capacity.1)?; + crate::render::cpu_boot::attach_text(&mut self.app.rt_mut().text.atlas); + Some((Prefault::start(dib, size.1), capacity, CpuPainter::new(painter_threads()))) + } + + /// The rest of `try_create` for a window that opens on the CPU: no GPU, no surface. Its first + /// frame paints into the buffer and the window shows with it, activating when it should + /// (`focus`); a first frame only the GPU can draw shows cloaked until the GPU has drawn it. + #[allow(clippy::too_many_arguments)] + pub(in crate::window) fn open_on_cpu(&mut self, event_loop: &ActiveEventLoop, window: Arc<Window>, a11y: Option<crate::a11y::Adapter>, a11y_start: native::A11yStart, + frame: Option<crate::platform::win32::CustomFrame>, cloak: crate::platform::win32::Cloak, focus: bool, open_as: crate::windows::OpenAs, built: bool) -> Result<(), String> { + // Maximizing (or full screen) shows a window: cloaked, so it shows only with its frame. + if open_as != crate::windows::OpenAs::Normal { + cloak.hold(&window, crate::time::now() + win::READY_FALLBACK, focus); + window.set_visible(true); + chrome::open_as(&window, open_as); + } + let phys = window.inner_size(); + let size = (phys.width.max(1), phys.height.max(1)); + let display = window.current_monitor().map_or((0, 0), |m| (m.size().width, m.size().height)); + let Some((prefault, capacity, painter)) = self.cpu_side(size, display) else { return Err("no memory for the window's frame buffer".into()) }; + let half = HalfRounding::of_vendor(crate::gpu::pick::display_vendor().unwrap_or(0)); + crate::marks::mark("cpu.side"); + let config = wgpu::SurfaceConfiguration { + usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_DST, + format: wgpu::TextureFormat::Bgra8Unorm, + width: size.0, + height: size.1, + present_mode: wgpu::PresentMode::AutoVsync, + desired_maximum_frame_latency: FRAME_LATENCY, + alpha_mode: wgpu::CompositeAlphaMode::Opaque, + view_formats: vec![], + color_space: Default::default(), + }; + let scale = window.scale_factor() as f32; + { + let rt = self.app.rt_mut(); + rt.set_system_dark(crate::platform::preferences::window_dark(&window, self.args.theme.as_deref())); + rt.set_viewport((size.0 as f32 / scale, size.1 as f32 / scale), scale); + // Reopening paints the settled state in the first frame (guarantee 8). + if self.shown && !built { rt.settle_all(); } + } + self.shown = true; + self.life.show(); + self.idle = true; + self.app.set_live_visible(true); + *self.native_handle.native.window.lock().unwrap() = Arc::downgrade(&window); + self.native_handle.native.number.store(native_window_number(&window).unwrap_or(0), Ordering::Release); + let native = { + let mode = SurfaceMode::Cpu { cpu: Cpu { buffer: Buffer::Touching(prefault, capacity), painter, half, shown: Shown::Nothing, show: Some(focus) }, job: GpuJob::Waiting { tries: 0, retry_at: None } }; + Native { cloak, frame, mode, a11y_start, ..Default::default() } + }; + self.win = Some(Win { + a11y, + native, + first_frame: FirstFrame::opened(crate::time::now()), + surface: None, + config, + surface_ok: true, + surface_retries: SurfaceRetries::default(), + window, + backoff: Backoff::default(), + hidden_pace: HiddenPace::default(), + cursor: crate::cursor::os::OsCursor::new(), + alpha: None, + corners: None, + timer_frame: TimerFrame::default(), + loop_frame: LoopFrame::default(), + presented: None, + covered_draw: CoveredDraw::Current, + redraw: std::cell::Cell::new(Redraw::Idle), + }); + self.apply_placement(event_loop); + crate::marks::mark("window.created"); + if let Some(created) = self.on_created.take() { created(self.native_handle.clone()); } + if let Some(on_window) = self.on_window.as_mut() { on_window(&self.native_handle); } + if let Some(w) = self.win.as_mut() { + let size = w.window.inner_size(); + let scale = w.window.scale_factor() as f32; + let rt = self.app.rt_mut(); + if size.width > 0 && size.height > 0 { + w.resize_surface(None, size); + rt.set_viewport((size.width as f32 / scale, size.height as f32 / scale), scale); + } + sync_chrome_core(rt, w, self.chrome, self.titlebar); + sync_screen_origin_core(rt, &w.window); + } + // The first frame, into the hidden window, then the window with it. + crate::marks::mark("frame.first.begin"); + self.draw_cpu(false); + crate::marks::mark("frame.first.done"); + let Some(w) = self.win.as_mut() else { return Ok(()) }; + if !w.first_frame.ready() { + // Only the GPU draws this frame (`start_gpu` began it): shown cloaked until it has. + if let SurfaceMode::Cpu { cpu, .. } = &mut w.native.mode { cpu.show = None; } + w.native.cloak.hold(&w.window, crate::time::now() + win::READY_FALLBACK, focus); + w.window.set_visible(true); + return Ok(()); + } + // `draw_cpu` showed it with the frame. + if w.window.has_focus() { self.app.window_focus(true); } + Ok(()) + } + + /// A frame drawn by the CPU renderer: the runtime steps, the painter repaints the tiles that + /// changed, and only those rectangles go to the window. While handing over, the GPU draws the + /// same instances too. + pub(in crate::window) fn draw_cpu(&mut self, resizing: bool) { + let mut frame = CpuWindowFrame { + host: self, + resizing, + owed: false, + hidden: false, + now: None, + encoded: None, + }; + host_step::run(&mut frame); + } +} + +struct CpuWindowFrame<'a> { + host: &'a mut Host, + resizing: bool, + owed: bool, + hidden: bool, + now: Option<Instant>, + encoded: Option<Instant>, +} + +impl FrameHost for CpuWindowFrame<'_> { + type Drawable = (); + type Prepared = Option<Vec<[u32; 4]>>; + + fn gate(&mut self) -> Gate { + // The system threw away what the window showed (it was covered whole, then came back) and + // asks for it again: the window is in sight, whatever the occlusion tracker said last, so + // this frame is drawn and copied whole. Skipped, the system would count it painted, and the + // window would show what's behind it until something changed. + let owed = self.host.win.as_ref().is_some_and(|w| crate::platform::win32::repaint_owed(&w.window)); + // Handing over: input that comes gives way to nothing. The CPU draws it now and the + // hand-over waits for a frame at rest; otherwise, with the GPU's frame not finished yet, + // nothing new until it is (a repaint the system asks for meanwhile gets the last frame). + if let Some(w) = self.host.win.as_mut() && let SurfaceMode::HandingOver { cpu, done, paused, since, readback, .. } = &mut w.native.mode { + if self.host.app.rt().has_pending_input() { + if !*paused { crate::marks::mark("gpu.window.paused"); } + (*done, *readback, *paused, *since) = (None, None, true, crate::time::now()); + } else if done.is_some() { + if owed { copy_last(cpu, &w.window); } + return Gate::Skip; + } + } + let launcher = self.host.launcher(); + let Some(l) = self.host.win.as_ref() else { return Gate::Skip }; + let hidden = launcher && !self.host.life.shown(); + // The frame both renderers draw to hand over draws in sight or not: covered, the window + // would stay on the CPU until it showed again. + let handing = matches!(l.native.mode, SurfaceMode::HandingOver { done: None, .. }); + // A covered window's owed frame (`CoveredDraw`) draws, settled. + let cover_owed = !l.minimized() && l.covered_draw.drawing(); + let covered = !owed && !handing && !cover_owed && ((!launcher && !self.host.life.uncovered()) || l.minimized()); + if covered { + self.host.covered_frame(); + return Gate::Skip; + } + if cover_owed { + self.host.app.rt_mut().settle_all(); + if let Some(w) = self.host.win.as_mut() { w.covered_draw = w.covered_draw.step(CoveredDrawEvent::Drawn); } + } + let Some(l) = self.host.win.as_ref() else { return Gate::Skip }; + if !owed && !handing && !self.resizing && l.backing_off(crate::time::now()) { return Gate::Skip; } + let Some(l) = self.host.win.as_mut() else { return Gate::Skip }; + l.timer_frame.drawn(); + if self.host.native_handle.native.number.load(Ordering::Relaxed) == 0 { + self.host.native_handle.native.number.store(native_window_number(&l.window).unwrap_or(0), Ordering::Release); + } + if !hidden { self.host.meter.redraw(l.paced_for_stats()); } + self.owed = owed; + self.hidden = hidden; + Gate::Draw + } + + fn before_acquire(&mut self) { + if !self.hidden && !self.resizing { self.host.step_frame(crate::time::now()); } + let Some(l) = self.host.win.as_mut() else { return }; + l.backoff_step(BackoffEvent::Lapsed); + l.backoff_step(BackoffEvent::Presented); + if self.host.frame_reports.wanted() { + self.host.frame_reports.set_refresh(l.window.current_monitor().and_then(|m| m.refresh_rate_millihertz()).map(|hz| hz as f64 / 1000.0)); + } + } + + fn acquire(&mut self) -> Acquire<()> { Acquire::Ready(()) } + + fn step_runtime(&mut self) -> StepInfo { + let now = crate::time::now(); + self.now = Some(now); + if self.hidden && self.host.win.as_ref().is_some_and(|l| l.first_frame.settles()) { + self.host.app.rt_mut().settle_all(); + } + let (animating, dt) = if self.hidden { + self.host.clock.hold(now); + (self.host.app.frame(0.0), 0.0) + } else { + self.host.app.clock_advance(&mut self.host.clock, now, false) + }; + if self.hidden && let Some(l) = self.host.win.as_mut() { l.hidden_pace.rendered(now); } + crate::marks::mark_once(&FIRST_LAYOUT, "frame.first.layout"); + StepInfo { runtime_animating: animating, animating, dt, update_ms: 0.0, presents_at: None } + } + + fn sync_after_step(&mut self, info: &mut StepInfo) { + let now = self.now.unwrap_or_else(crate::time::now); + info.update_ms = now.elapsed().as_secs_f64() * 1000.0; + let Some(l) = self.host.win.as_mut() else { return }; + let rt = self.host.app.rt_mut(); + sync_platform_core(l, rt, &mut self.host.secure_input, &mut self.host.ime_allowed, &self.host.clipboard); + let mut quiet_now = false; + if let SurfaceMode::Cpu { job: GpuJob::Building { latest, animating: moving, ready, .. }, .. } = &mut l.native.mode { + *latest.lock().unwrap_or_else(|e| e.into_inner()) = warm_instances(&rt.instances); + *moving = info.animating; + // The GPU waited for this: a frame at rest, which the hand-over frame draws again. + quiet_now = !info.animating && ready.is_some(); + } + if quiet_now { self.host.native_handle.send(WakeEvent::GpuReady); } + } + + fn prepare_render(&mut self, _drawable: (), _info: &mut StepInfo) -> RenderPrep<Option<Vec<[u32; 4]>>> { + let has_comp = self.host.app.has_compositor(); + let Some(l) = self.host.win.as_mut() else { return RenderPrep::Abort }; + let (width, height) = (l.config.width, l.config.height); + let rt = self.host.app.rt_mut(); + let (SurfaceMode::Cpu { cpu, .. } | SurfaceMode::HandingOver { cpu, .. }) = &mut l.native.mode else { return RenderPrep::Abort }; + cpu.painter.fill_masks(&mut rt.text.atlas); + crate::marks::mark_once(&FIRST_MASKS, "frame.first.masks"); + let scene = Scene::new(&rt.instances, &rt.text.atlas, &rt.images, (width, height), rt.clear_color()) + .srgb_blend(rt.srgb_blend()) + .fade_stops(rt.fade_stops()) + .native_surfaces(!rt.surfaces.is_empty()) + .compositor(has_comp) + .half_rounding(cpu.half) + .font_smoothing(rt.font_smoothing()); + let Cpu { buffer, painter, .. } = &mut *cpu; + let Some(dib) = ready(buffer, painter, (width, height)) else { + eprintln!("rune: no memory for a {width} x {height} frame buffer"); + l.backoff_step(BackoffEvent::At(crate::time::now() + TIMER_FRAME)); + return RenderPrep::Abort; + }; + let stride = dib.stride(); + match painter.paint(&scene, &mut Target::with_stride(dib.bytes(), width, height, stride)) { + Ok(painted) => { + crate::marks::mark_once(&FIRST_PAINT, "frame.first.painted"); + RenderPrep::Ready(Some(painted.rects)) + } + Err(_why) => { + // The frame needs what only the GPU draws (a native surface, a compositor's scene): + // the GPU starts now if it hasn't, and the window keeps its last frame until then. + if !matches!(self.host.win.as_ref().map(|w| &w.native.mode), Some(SurfaceMode::HandingOver { .. })) { + crate::marks::mark("cpu_first.needs_gpu"); + self.host.start_gpu(false); + self.host.idle = false; + if let Some(l) = self.host.win.as_mut() { l.backoff_step(BackoffEvent::At(crate::time::now() + TIMER_FRAME)); } + return RenderPrep::Abort; + } + RenderPrep::Ready(None) + } + } + } + + fn render(&mut self, prepared: &mut Option<Vec<[u32; 4]>>, _info: &StepInfo) -> bool { + let Some(rects) = prepared.as_deref() else { return false }; + let Some(l) = self.host.win.as_mut() else { return false }; + let (width, height) = (l.config.width, l.config.height); + let (SurfaceMode::Cpu { cpu, .. } | SurfaceMode::HandingOver { cpu, .. }) = &mut l.native.mode else { return false }; + if let Buffer::Ready(dib) = &cpu.buffer { + cpu.shown = match std::mem::replace(&mut cpu.shown, Shown::Nothing) { + Shown::Copied(size) => { + let blit = if size == (width, height) && !self.owed { Blit::Bounds(rects) } else { Blit::All }; + if let Some(hwnd) = crate::platform::win32::hwnd(&l.window) { dib.present(hwnd, (width, height), blit); } + Shown::Copied((width, height)) + } + Shown::Waiting | Shown::Nothing => Shown::Waiting, + }; + } + if let Some(focus) = cpu.show.take() { + // The window shows with its first frame, before the frame's hooks run + // (`App::on_frame_drawn`). GDI draws nothing into a hidden window, and DWM + // composes a window that just showed with whatever its surface holds (white): + // it shows cloaked, takes the frame, then comes on screen, activating as the + // cloak lifts. + if !l.native.cloak.held() { + l.native.cloak.hold(&l.window, crate::time::now() + win::READY_FALLBACK, focus); + crate::marks::mark("window.cloaked"); + l.window.set_visible(true); + crate::marks::mark("window.visible"); + } + copy_first(cpu, &l.window, (width, height)); + l.native.cloak.lift(&l.window); + crate::marks::mark("window.shown"); + } else if l.window.is_visible() == Some(true) { + // A frame after the show that came before the first copy. + copy_first(cpu, &l.window, (width, height)); + } + false + } + + fn submit_and_present(&mut self, prepared: Option<Vec<[u32; 4]>>, info: &StepInfo) -> Instant { + self.encoded = self.host.frame_reports.stamp(); + crate::window::frame_presented(); + if prepared.is_some() && let Some(l) = self.host.win.as_mut() { + crate::marks::mark_once(&FIRST_CPU, "frame.first.cpu"); + if !l.first_frame.ready() { l.first_frame.gpu_done(); } + } + self.host.gpu_draws_same_frame(); + // The input the hand-over paused for is drawn: the next frame at rest hands over. + if let Some(l) = self.host.win.as_mut() + && let SurfaceMode::HandingOver { paused, since, .. } = &mut l.native.mode + && *paused && !info.animating && !self.host.app.rt().has_pending_input() + { + (*paused, *since) = (false, crate::time::now()); + } + crate::time::now() + } + + fn present_targets(&mut self) -> (Option<&mut FrameClock>, &mut RuntimeCore) { + (Some(&mut self.host.clock), self.host.app.rt_mut()) + } + + fn settle(&mut self, submitted: Instant, info: &StepInfo) { + let now = self.now.unwrap_or(submitted); + self.host.meter.presented(); + self.host.frame_reports.drawn(self.encoded, None, now, info.update_ms); + self.host.app.inspect_frame(); + let Some(l) = self.host.win.as_mut() else { return }; + let next_tick = l.next_tick(now).filter(|_| !self.hidden); + self.host.idle = Presented::settle_core( + &mut l.presented, + self.host.app.rt(), + &l.config, + info.animating || FrameMove::moving(&self.host.frame_move), + next_tick, + !self.hidden, + false, + ); + // Motion's next frame comes at the display's next refresh: a CPU frame presents at once, + // so nothing else paces it. + if !self.hidden && !self.host.idle { + l.backoff_step(BackoffEvent::At(crate::platform::win32::next_vblank(crate::time::now()))); + self.host.meter.set_pacing(l.pacing_state(true)); + } else { + l.stop_pacing(); + self.host.meter.set_pacing(l.pacing_state(false)); + } + } +} + +static FIRST_CPU: AtomicBool = AtomicBool::new(false); +static FIRST_LAYOUT: AtomicBool = AtomicBool::new(false); +static FIRST_MASKS: AtomicBool = AtomicBool::new(false); +static FIRST_PAINT: AtomicBool = AtomicBool::new(false); diff --git a/app/vendor/rune/crates/rune/src/window/win32/damage.rs b/app/vendor/rune/crates/rune/src/window/win32/damage.rs new file mode 100644 index 0000000..9f7b4f9 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/window/win32/damage.rs @@ -0,0 +1,233 @@ +//! Windows: what part of a window a frame redraws and presents. The renderer redraws only what +//! changed into the frame it keeps (`render::damaged`), and the window presents only that +//! (`Present1` dirty rectangles), which is all DWM composes again. +//! +//! What changed is the instances that differ from the last frame's. The lists' common start and +//! end are skipped; in what's left, an instance whose bytes are in both lists didn't change (its +//! place is in its bytes), so a typed glyph that pushes the rest of the list along changes only +//! itself and the caret. The bounds of the instances only one list has are the change, gathered +//! into at most `RECTS` rectangles. If the instances both lists have were drawn in another order, +//! everything changed. +//! +//! The whole window is drawn when anything else could have moved pixels (`Renderer:: +//! redraws_in_place`), when the size or clear colour changed, after a new swap chain, and when +//! the change is most of the window anyway. + +use std::collections::HashMap; +use std::hash::{BuildHasherDefault, Hasher}; + +use crate::render::{INSTANCE_WORDS, Instance}; + +/// Above this share of the window, a frame draws all of it. +const MOST: f32 = 0.6; +/// Past this many instances the new list has that the old doesn't, a frame draws all of it without +/// looking for where they are: a scroll moves every row, and checking the order of thousands of +/// instances and bounding them only to find they cover the window costs a list's frame hundreds of +/// microseconds. A typed glyph, a streamed line or a hover changes far fewer. +const MANY: usize = 256; +/// Rectangles a change is gathered into, at most. +pub(super) const RECTS: usize = crate::render::MAX_RECTS; + +/// The last frames' changes. +#[derive(Default)] +pub(in crate::window) struct Damage { + /// The last frame's instances, and its size, clear colour and swap chain (the surface's + /// configuration, `configure::generation`). + last: Vec<Instance>, + shape: Option<((u32, u32), [f32; 4], u64)>, + scratch: Scratch, + /// The last change seen, however much was drawn (frame-profile). + #[cfg_attr(not(feature = "frame-profile"), allow(dead_code))] + pub(in crate::window) seen: Option<[u32; 4]>, +} + +/// Rectangles `[x0, y0, x1, y1]` in the window's pixels. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub(super) enum Area { + /// Everything (or not known). + #[default] + All, + /// More than `MANY` instances. + Many, + Rects(Vec<[u32; 4]>), +} + +/// What a frame draws. +#[derive(Clone, Debug, PartialEq, Eq)] +pub(in crate::window) enum Plan { + /// Everything, and why. + All(&'static str), + /// Redraw `draw` (`[x, y, width, height]` each), present `present` (`[x0, y0, x1, y1]` each). + Part { draw: Vec<[u32; 4]>, present: Vec<[i32; 4]> }, +} + +impl Damage { + /// The frame about to draw `instances` into a `size` target cleared to `clear`, on swap chain + /// `swap`; `in_place` when nothing but its instances draws there. + pub(in crate::window) fn plan(&mut self, instances: &[Instance], size: (u32, u32), clear: [f32; 4], swap: u64, in_place: bool) -> Plan { + let (now, why) = match (in_place && !whole_frames(), self.shape == Some((size, clear, swap))) { + (false, _) => (Area::All, "not in place"), + (_, false) => (Area::All, "new size, colour or swap chain"), + _ => { + let now = changed(&self.last, instances, size, &mut self.scratch); + self.seen = match &now { Area::Rects(r) => r.iter().copied().reduce(join), Area::All | Area::Many => None }; + match now { + Area::Rects(r) if r.iter().map(|r| area(*r)).sum::<u32>() as f32 > MOST * (size.0 * size.1) as f32 => (Area::All, "most of it changed"), + Area::All => (Area::All, "reordered"), + Area::Many => (Area::All, "many changed"), + other => (other, ""), + } + } + }; + self.last.clear(); + self.last.extend_from_slice(instances); + self.shape = Some((size, clear, swap)); + match now { + Area::All | Area::Many => Plan::All(why), + // Nothing changed: one pixel keeps the present, which DWM composes again as is. + Area::Rects(r) if r.is_empty() => Plan::Part { draw: vec![[0, 0, 1, 1]], present: vec![[0, 0, 1, 1]] }, + Area::Rects(r) => Plan::Part { + draw: r.iter().map(|r| [r[0], r[1], r[2] - r[0], r[3] - r[1]]).collect(), + present: r.iter().map(|r| r.map(|v| v as i32)).collect(), + }, + } + } + + /// A new swap chain: the next frame draws whole. + pub(in crate::window) fn reset(&mut self) { self.shape = None; } + + /// The last frame drew into swap chain `swap` at this size and clear colour: a frame may draw + /// and present only part of it. False after `reset` or a configure (a new swap chain), so its + /// first frame, loop-only or not, goes through `plan` and draws whole. + pub(in crate::window) fn current(&self, size: (u32, u32), clear: [f32; 4], swap: u64) -> bool { self.shape == Some((size, clear, swap)) } + + /// A loop-only frame changed only `patched` (ascending) and drew them where they were and + /// are (`Renderer::arm_loop`): the next frame compares with them. + pub(in crate::window) fn patched(&mut self, instances: &[Instance], patched: &[u32]) { + if self.last.len() != instances.len() { self.shape = None; return; } + for &i in patched { self.last[i as usize] = instances[i as usize]; } + } +} +/// `RUNE_WHOLE_FRAMES=1`: every frame draws whole, to check partial frames against. +fn whole_frames() -> bool { + static WHOLE: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + *WHOLE.get_or_init(|| std::env::var_os("RUNE_WHOLE_FRAMES").is_some_and(|v| v == "1")) +} + +type Counts = HashMap<u64, (i32, usize), BuildHasherDefault<Hashed>>; + +/// The map's keys are hashes already, mixed once more: FNV's multiply carries only upward, so its +/// low bits, which pick the bucket, come from the words' low bits alone, and most instances share +/// those (whole-pixel rects and clips). Unmixed, a scrolled list's thousands of instances fell in +/// a few long probe chains. +#[derive(Default)] +struct Hashed(u64); + +impl Hasher for Hashed { + fn finish(&self) -> u64 { self.0 } + fn write(&mut self, _: &[u8]) { unreachable!("keys are u64") } + fn write_u64(&mut self, v: u64) { + // MurmurHash3's 64-bit finaliser. + let mut h = v ^ (v >> 33); + h = h.wrapping_mul(0xff51_afd7_ed55_8ccd); + h ^= h >> 33; + h = h.wrapping_mul(0xc4ce_b9fe_1a85_ec53); + self.0 = h ^ (h >> 33); + } +} + +/// FNV-1a over an instance's 32 words: a few ns, against SipHash's ~100. +fn hash(i: &Instance) -> u64 { + bytemuck::cast_ref::<Instance, [u32; INSTANCE_WORDS]>(i).iter().fold(0xcbf2_9ce4_8422_2325u64, |h, w| (h ^ u64::from(*w)).wrapping_mul(0x0100_0000_01b3)) +} + +/// What differs between `old` and `new`. +/// What `changed` keeps between frames so it allocates nothing. +#[derive(Default)] +pub(super) struct Scratch { + old: Vec<u64>, + new: Vec<u64>, + counts: Counts, + each: Vec<[u32; 4]>, +} + +fn changed(old: &[Instance], new: &[Instance], size: (u32, u32), s: &mut Scratch) -> Area { + fn bytes(i: &Instance) -> &[u8] { bytemuck::bytes_of(i) } + let start = old.iter().zip(new).take_while(|(a, b)| bytes(a) == bytes(b)).count(); + let end = old[start..].iter().rev().zip(new[start..].iter().rev()).take_while(|(a, b)| bytes(a) == bytes(b)).count(); + let (old, new) = (&old[start..old.len() - end], &new[start..new.len() - end]); + // Per distinct instance: how many more the old list has than the new, and one of them. + s.counts.clear(); + s.old.clear(); + s.old.extend(old.iter().map(hash)); + s.new.clear(); + s.new.extend(new.iter().map(hash)); + for (i, h) in s.old.iter().enumerate() { s.counts.entry(*h).or_insert((0, i)).0 += 1; } + let mut added = 0; + for (i, h) in s.new.iter().enumerate() { + let count = &mut s.counts.entry(*h).or_insert((0, old.len() + i)).0; + *count -= 1; + if *count < 0 { added += 1; } + if added > MANY { return Area::Many; } + } + // The instances both lists have, in order: drawn in another order, anything may have changed. + let counts = &s.counts; + let mut j = 0; + for &h in &s.old { + if counts[&h].0 != 0 { continue; } + if j < s.new.len() && s.new[j] == h { j += 1; continue; } + while j < s.new.len() && counts[&s.new[j]].0 != 0 { j += 1; } + if j >= s.new.len() || s.new[j] != h { return Area::All; } + j += 1; + } + if s.new[j..].iter().any(|h| counts[h].0 == 0) { return Area::All; } + // In reading order, so neighbours gather before rectangles run out. + s.each.clear(); + s.each.extend(counts.values().filter(|(n, _)| *n != 0) + .filter_map(|(_, at)| bounds(if *at < old.len() { &old[*at] } else { &new[*at - old.len()] }, size))); + // A scrolled list changes thousands of instances over most of the window: their union says + // so (the plan draws whole above `MOST`) without gathering them into rectangles. + if s.each.len() > 256 && let Some(all) = s.each.iter().copied().reduce(join) && area(all) as f32 > MOST * (size.0 * size.1) as f32 { + return Area::Rects(vec![all]); + } + s.each.sort_unstable_by_key(|r| (r[1], r[0])); + let mut rects = Vec::new(); + for r in s.each.iter().copied() { add(&mut rects, r); } + Area::Rects(rects) +} +/// Adds `r` to `rects`: into one it touches, or as its own until there are `RECTS`, then into +/// the one it grows least. +fn add(rects: &mut Vec<[u32; 4]>, r: [u32; 4]) { + if let Some(i) = rects.iter().position(|q| near(*q, r)) { + let merged = join(rects.swap_remove(i), r); + return add(rects, merged); + } + if rects.len() < RECTS { rects.push(r); return; } + let grow = |q: [u32; 4]| area(join(q, r)) - area(q); + let i = (0..rects.len()).min_by_key(|&i| grow(rects[i])).unwrap_or(0); + let merged = join(rects.swap_remove(i), r); + add(rects, merged); +} + +/// Whether two rectangles overlap or lie within 16 pixels of each other. +fn near(a: [u32; 4], b: [u32; 4]) -> bool { + a[0] <= b[2] + 16 && b[0] <= a[2] + 16 && a[1] <= b[3] + 16 && b[1] <= a[3] + 16 +} + +fn join(a: [u32; 4], b: [u32; 4]) -> [u32; 4] { [a[0].min(b[0]), a[1].min(b[1]), a[2].max(b[2]), a[3].max(b[3])] } + +/// The pixels an instance can touch: its quad as the shader grows it, inside its clip. +fn bounds(i: &Instance, size: (u32, u32)) -> Option<[u32; 4]> { + let (x0, y0, x1, y1) = i.damage_quad_bounds()?; + if x1 <= x0 || y1 <= y0 { return None; } + let c = i.clip; + let (x0, y0) = ((x0.max(c[0]) - 1.0).floor().max(0.0), (y0.max(c[1]) - 1.0).floor().max(0.0)); + let (x1, y1) = ((x1.min(c[2]) + 1.0).ceil().min(size.0 as f32), (y1.min(c[3]) + 1.0).ceil().min(size.1 as f32)); + (x1 > x0 && y1 > y0).then(|| [x0 as u32, y0 as u32, x1 as u32, y1 as u32]) +} + +fn area(r: [u32; 4]) -> u32 { (r[2] - r[0]) * (r[3] - r[1]) } + +#[cfg(test)] +#[path = "damage_tests.rs"] +mod tests; diff --git a/app/vendor/rune/crates/rune/src/window/win32/damage_tests.rs b/app/vendor/rune/crates/rune/src/window/win32/damage_tests.rs new file mode 100644 index 0000000..67cc1ce --- /dev/null +++ b/app/vendor/rune/crates/rune/src/window/win32/damage_tests.rs @@ -0,0 +1,147 @@ +use bytemuck::Zeroable; + +use super::*; +use crate::render::{KIND_BACKDROP_BLUR, KIND_DASHED, KIND_EFFECT, KIND_GLYPH, KIND_GRADIENT, KIND_IMAGE, KIND_INSET, KIND_RADIAL, KIND_RECT, KIND_SEGMENT, KIND_SHADOW, KIND_TRIANGLE, Kind, LayerSpec, NO_CLIP, cpu_boot}; + +fn old_bounds(i: &Instance, size: (u32, u32)) -> Option<[u32; 4]> { + let kind = i.params[1]; + if (8.5..9.5).contains(&kind) { return None; } + let grow = match kind { + k if (0.5..1.5).contains(&k) => i.params[2] * 3.0 + 1.0, + k if (1.5..2.5).contains(&k) => 0.0, + k if (2.5..3.5).contains(&k) || (4.5..9.5).contains(&k) => 1.0, + _ => 1.0 + i.params[2] * 2.0, + }; + let [x, y, w, h] = i.rect; + let (mut x0, mut y0, mut x1, mut y1) = (x - grow, y - grow, x + w + grow, y + h + grow); + if (1.5..2.5).contains(&kind) && i.params[0] != 0.0 { + let (cx, cy, r) = (x + w * 0.5, y + h * 0.5, (w * w + h * h).sqrt() * 0.5); + (x0, y0, x1, y1) = (cx - r, cy - r, cx + r, cy + r); + } + let c = i.clip; + let (x0, y0) = ((x0.max(c[0]) - 1.0).floor().max(0.0), (y0.max(c[1]) - 1.0).floor().max(0.0)); + let (x1, y1) = ((x1.min(c[2]) + 1.0).ceil().min(size.0 as f32), (y1.min(c[3]) + 1.0).ceil().min(size.1 as f32)); + (x1 > x0 && y1 > y0).then(|| [x0 as u32, y0 as u32, x1 as u32, y1 as u32]) +} + +fn contains(outer: [i32; 4], inner: [i32; 4]) -> bool { + if inner[2] <= inner[0] || inner[3] <= inner[1] { return true; } + outer[2] > outer[0] && outer[3] > outer[1] + && outer[0] <= inner[0] && outer[1] <= inner[1] + && outer[2] >= inner[2] && outer[3] >= inner[3] +} + +#[test] +fn damage_bounds_contain_exact_drawn_pixels_and_tighten_overestimates() { + let size = (256u32, 256u32); + let (w, h) = (size.0 as i32, size.1 as i32); + let mut atlas = crate::text::Atlas::new(); + atlas.data.resize((crate::text::ATLAS_SIZE * crate::text::ATLAS_SIZE) as usize, 0); + for y in 0..16usize { + for x in 0..16usize { + atlas.data[y * crate::text::ATLAS_SIZE as usize + x] = 255; + } + } + let mut images = crate::pixels::ImageAtlas::default(); + let px = crate::Pixels::new(); + px.set(16, 16, vec![255u8; 16 * 16 * 4]); + let placed = images.place(&px, [16.0, 16.0]).expect("place test image"); + let base = |kind: Kind, rect: [f32; 4]| Instance { + rect, + fill: [1.0, 0.4, 0.2, 1.0], + border: [0.2, 0.8, 1.0, 1.0], + params: [0.0, kind.as_f32(), 0.0, 1.0], + clip: NO_CLIP, + ..Instance::zeroed() + }; + let cases: Vec<(&str, Instance, bool)> = vec![ + ("rect_plain", base(Kind::Rect, [30.3, 40.7, 50.0, 30.0]), true), + ("rect_border_soft", Instance { params: [3.0, KIND_RECT, 2.0, 1.0], radii: [8.0; 4], ..base(Kind::Rect, [40.0, 40.0, 60.0, 40.0]) }, true), + ("rect_clipped", Instance { clip: [45.2, 48.6, 82.4, 70.1], ..base(Kind::Rect, [30.0, 40.0, 80.0, 50.0]) }, true), + ("rect_banded", Instance { params: [2.0, KIND_RECT, 0.0, 1.0], uv: [-1.0, -1.0, -101.0, 6.0], ..base(Kind::Rect, [50.0, 60.0, 100.0, 80.0]) }, true), + ("shadow_plain", Instance { params: [0.0, KIND_SHADOW, 6.0, 1.0], radii: [8.0; 4], ..base(Kind::Shadow, [60.0, 60.0, 80.0, 50.0]) }, true), + ("shadow_banded", Instance { params: [0.0, KIND_SHADOW, 6.0, 1.0], uv: [90.0, -19.0, -119.0, 99.0], ..base(Kind::Shadow, [40.0, 50.0, 100.0, 80.0]) }, true), + ("glyph_upright", base(Kind::Glyph, [70.0, 70.0, 16.0, 16.0]), true), + ("glyph_rot_15deg", Instance { params: [0.26, KIND_GLYPH, 0.0, 1.0], uv: [0.0, 0.0, 16.0, 16.0], ..base(Kind::Glyph, [80.0, 80.0, 40.0, 12.0]) }, true), + ("glyph_rot_45deg", Instance { params: [std::f32::consts::FRAC_PI_4, KIND_GLYPH, 0.0, 1.0], uv: [0.0, 0.0, 16.0, 16.0], ..base(Kind::Glyph, [80.0, 80.0, 40.0, 12.0]) }, true), + ("glyph_rot_90deg", Instance { params: [std::f32::consts::FRAC_PI_2, KIND_GLYPH, 0.0, 1.0], uv: [0.0, 0.0, 16.0, 16.0], ..base(Kind::Glyph, [80.0, 80.0, 40.0, 12.0]) }, true), + ("inset", Instance { params: [2.0, KIND_INSET, 4.0, 1.0], uv: [2.0, 2.0, 0.0, 0.0], ..base(Kind::Inset, [50.0, 50.0, 60.0, 40.0]) }, true), + ("gradient", Instance { uv: [0.1, 0.2, 0.9, 1.0], params: [0.0, KIND_GRADIENT, 1.5, 1.0], ..base(Kind::Gradient, [30.0, 30.0, 50.0, 50.0]) }, true), + ("segment", Instance { radii: [40.0, 40.0, 110.0, 85.0], params: [3.0, KIND_SEGMENT, 1.0, 1.0], ..base(Kind::Segment, [36.0, 36.0, 78.0, 53.0]) }, true), + ("triangle", Instance { radii: [50.0, 40.0, 120.0, 60.0], uv: [70.0, 110.0, 0.0, 0.0], params: [7.0, KIND_TRIANGLE, 0.0, 1.0], ..base(Kind::Triangle, [50.0, 40.0, 70.0, 70.0]) }, true), + ("image", Instance { params: [placed.page as f32, KIND_IMAGE, 0.0, 1.0], uv: [placed.rect[0] as f32, placed.rect[1] as f32, placed.rect[2] as f32, placed.rect[3] as f32], ..base(Kind::Image, [80.0, 80.0, 24.0, 24.0]) }, true), + ("layer_plain", Instance::begin_layer([40.0, 50.0, 80.0, 60.0], NO_CLIP, LayerSpec::default()), false), + ("layer_turned", Instance::begin_layer([60.0, 60.0, 80.0, 40.0], NO_CLIP, LayerSpec::default()).turned(0.6, [100.0, 80.0]), false), + ("layer_end", Instance::end_layer(), false), + ("dashed", Instance { params: [3.0, KIND_DASHED, 0.5, 1.0], uv: [6.0, 4.0, 0.0, 0.0], ..base(Kind::Dashed, [40.0, 40.0, 80.0, 60.0]) }, true), + ("radial", Instance { params: [0.0, KIND_RADIAL, 1.0, 1.0], uv: [40.0, 30.0, 40.0, 30.0], ..base(Kind::Radial, [40.0, 40.0, 80.0, 60.0]) }, true), + ("effect_bleed16", Instance { params: [0.0, KIND_EFFECT, 16.0, 1.0], ..base(Kind::Effect, [60.0, 60.0, 40.0, 30.0]) }, false), + ("backdrop_blur", Instance { params: [12.0, KIND_BACKDROP_BLUR, 0.0, 1.0], ..base(Kind::BackdropBlur, [50.0, 50.0, 70.0, 50.0]) }, false), + ]; + let mut tighter = Vec::new(); + for (name, inst, paintable) in &cases { + let new_r = bounds(inst, size).map_or([0; 4], |r| r.map(|v| v as i32)); + let old_r = old_bounds(inst, size).map_or([0; 4], |r| r.map(|v| v as i32)); + let pb = inst.pixel_bounds(w, h); + assert!(contains(new_r, pb), "{name}: damage {new_r:?} missed pixel_bounds {pb:?}"); + if *paintable { + let mut buf = vec![0u8; (w * h * 4) as usize]; + let scene = cpu_boot::Scene::new(std::slice::from_ref(inst), &atlas, &images, size, [0.0; 4]); + cpu_boot::paint(&scene, &mut cpu_boot::Target::new(&mut buf, size.0, size.1), 1).expect("paint"); + let (mut x0, mut y0, mut x1, mut y1) = (w, h, 0, 0); + for y in 0..h { + for x in 0..w { + let at = ((y * w + x) * 4) as usize; + if buf[at..at + 4] != [0, 0, 0, 0] { + x0 = x0.min(x); y0 = y0.min(y); x1 = x1.max(x + 1); y1 = y1.max(y + 1); + } + } + } + let painted = if x1 > x0 && y1 > y0 { [x0, y0, x1, y1] } else { [0; 4] }; + assert!(contains(new_r, painted), "{name}: damage {new_r:?} missed CPU-painted {painted:?}"); + } + if matches!(inst.kind(), Some(Kind::Effect | Kind::BackdropBlur)) { + let lb = inst.layer_bounds(); + let lb_px = [lb[0].max(0.0).floor() as i32, lb[1].max(0.0).floor() as i32, lb[2].min(w as f32).ceil() as i32, lb[3].min(h as f32).ceil() as i32]; + assert!(contains(new_r, lb_px), "{name}: damage {new_r:?} missed layer_bounds {lb_px:?}"); + } + let new_a = i64::from((new_r[2] - new_r[0]).max(0)) * i64::from((new_r[3] - new_r[1]).max(0)); + let old_a = i64::from((old_r[2] - old_r[0]).max(0)) * i64::from((old_r[3] - old_r[1]).max(0)); + if new_a < old_a { + assert!(contains(old_r, new_r), "{name}: tighter damage must be subset of old"); + tighter.push(*name); + } + } + assert!(tighter.contains(&"rect_banded"), "tighter: {tighter:?}"); + assert!(tighter.contains(&"shadow_banded"), "tighter: {tighter:?}"); + assert!(tighter.contains(&"glyph_rot_15deg"), "tighter: {tighter:?}"); + assert!(tighter.contains(&"effect_bleed16"), "tighter: {tighter:?}"); +} + +#[test] +fn changed_order_check_handles_inserts_deletes_duplicates_and_reorders() { + let r = |x: f32| Instance { + rect: [x, 10.0, 20.0, 20.0], + fill: [1.0; 4], + params: [0.0, KIND_RECT, 0.0, 1.0], + clip: NO_CLIP, + ..Instance::zeroed() + }; + let mut s = Scratch::default(); + let size = (256, 256); + + // Partial in-place update keeps order. + let old = [r(0.0), r(30.0), r(60.0), r(90.0)]; + let mut new = old; + new[2] = r(65.0); + assert!(matches!(changed(&old, &new, size, &mut s), Area::Rects(ref rs) if !rs.is_empty())); + + // Insert and delete with duplicates preserve order of remaining items. + let old_dup = [r(0.0), r(30.0), r(30.0), r(60.0), r(90.0)]; + let new_dup = [r(0.0), r(15.0), r(30.0), r(30.0), r(90.0)]; + assert!(matches!(changed(&old_dup, &new_dup, size, &mut s), Area::Rects(ref rs) if !rs.is_empty())); + + // Swapping two unchanged instances triggers full redraw (`Area::All`). + let swapped = [r(0.0), r(60.0), r(30.0), r(90.0)]; + assert_eq!(changed(&old, &swapped, size, &mut s), Area::All); +} diff --git a/app/vendor/rune/crates/rune/src/window/win32/handover.rs b/app/vendor/rune/crates/rune/src/window/win32/handover.rs new file mode 100644 index 0000000..908b767 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/window/win32/handover.rs @@ -0,0 +1,546 @@ +//! Windows: background GPU creation and seamless DirectComposition hand-over from a CPU-opened +//! window (`cpu_frame`) to the GPU renderer. +//! +//! After the first CPU frame, on the loop's first idle turn, a thread at below-normal priority +//! makes the GPU device, Rune's renderer, an uncommitted DirectComposition visual on the window +//! and a swap chain on it (`platform::win32::dcomp_handover`), so none of that competes with the +//! first frame. When it's ready both renderers draw every frame from the same instances; on the +//! first turn that starts with the GPU's previous frame finished, the visual is committed and DWM +//! shows the GPU's swap chain from its next composition, the same pose the CPU last showed or the +//! one after. The CPU's buffer goes on a worker a turn later. A GPU that can't be made leaves the +//! window on the CPU, fully live. + +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::{Arc, Mutex}; +use std::time::Duration; + +use super::cpu_frame::{Cpu, Shown}; +use crate::platform::win32::dcomp_handover::Handover; +use crate::platform::win32::dib::{Dib, free_later}; +use crate::render::cpu_boot::HalfRounding; +use crate::render::{Gpu, Renderer}; +use crate::time::Instant; +use crate::window::WakeEvent; +use crate::window::host::{CompositorFrame, Host}; +use crate::window::surface::{Win, acquire, configure, reblend_core, rebuild_renderer_core, surface_config}; + +/// Where a window's frames go. Windows that need the GPU from their first frame (a compositor, +/// a translucent window, an overlay) are `Gpu` from the start, as on every other platform. +#[derive(Default)] +pub(in crate::window) enum SurfaceMode { + #[default] + Gpu, + /// The CPU renderer draws; `job` is the GPU being made for it. + Cpu { cpu: Cpu, job: GpuJob }, + /// The GPU's swap chain is on the window's visual, uncommitted. The next frame is drawn by + /// both renderers, and then nothing is drawn until the GPU has finished it (`done`): a + /// window that animates would otherwise replace it every frame and never hand over. The turn + /// that finds it done commits. `readback` is that frame's pixels on their way back, to count + /// how many differ from the CPU's. + /// `since`: when the GPU came; `nudged`: when a frame was last asked for, while none has been + /// drawn by both (`Host::watch_handover`); `done`'s instant: when that frame was submitted. + /// `paused`: input came while handing over, so the CPU draws it and the hand-over waits for a + /// frame at rest (the visual is uncommitted: DWM goes on showing the CPU's frames). + HandingOver { cpu: Cpu, handover: Handover, done: Option<(Arc<AtomicBool>, Instant)>, readback: Option<Readback>, since: Instant, nudged: Option<Instant>, tries: u8, paused: bool }, + /// The GPU draws through the committed visual, which lives as long as the window's surface. + Handed { handover: Handover }, + /// The GPU's swap chain was made again (a lost device) on the same visual: committed once its + /// first frame has presented and finished (`Host::draw`). + Rebinding { handover: Handover }, +} + +/// A GPU frame copied into a buffer the CPU can read: rows `row` bytes apart, `size` pixels. +pub(in crate::window) struct Readback { + buffer: wgpu::Buffer, + row: u32, + size: (u32, u32), +} + +/// The GPU a CPU window is waiting for. Every step has a deadline (`Host::watch_handover`), and +/// every way it ends is logged: handed over (`gpu.window.handed`), or failed with a reason +/// (`gpu.window.failed`, note `gpu.window.why`) and tried again after `RETRY_AFTER`, `TRIES` +/// times in all, then the CPU for good. +pub(in crate::window) enum GpuJob { + /// Not started: the first frame isn't out yet, or a failed try (`tries` so far) waits for + /// `retry_at`. + Waiting { tries: u8, retry_at: Option<Instant> }, + /// Being made on `thread` since `since`; it reports through `slot`. `raised`: the thread runs + /// at normal priority now (`RAISE_AFTER`). `latest`: the last CPU frame's instances, which the + /// thread draws once before it reports (`warm_frame`). `animating`: the last CPU frame moved + /// something. `ready`: since when the GPU has waited for a frame that doesn't (`gpu_ready`). + Building { slot: Arc<Mutex<Option<Result<Prepared, String>>>>, latest: Arc<Mutex<Vec<crate::render::Instance>>>, thread: std::thread::JoinHandle<()>, since: Instant, raised: bool, tries: u8, animating: bool, ready: Option<Instant> }, + /// It failed `TRIES` times: the window stays on the CPU. + Failed, +} + +/// A GPU thread that hasn't made the GPU after this long runs at normal priority: below normal, +/// a busy machine's other work can hold it off for seconds. +const RAISE_AFTER: Duration = Duration::from_millis(500); +/// Past this, a GPU thread still making the GPU is logged as slow (it can't be stopped). +const BUILD_SLOW: Duration = Duration::from_secs(20); +/// While no frame has been drawn by both renderers, one is asked for this often, in sight or not. +const NUDGE_EVERY: Duration = Duration::from_millis(100); +/// The longest the GPU may take to finish the frame both drew: then the hand-over fails. +const FINISH_LIMIT: Duration = Duration::from_secs(5); +/// The longest a GPU that's ready waits for a CPU frame that moves nothing to hand over at: an +/// animation that doesn't end (a spinner) hands over within it. +const QUIET_WAIT: Duration = Duration::from_secs(1); +/// A failed try is made again after this long. +const RETRY_AFTER: Duration = Duration::from_secs(30); +/// Tries in all before the window stays on the CPU. +const TRIES: u8 = 3; + +/// What the GPU thread makes for a window. +pub(in crate::window) struct Prepared { + gpu: Gpu, + renderer: Renderer, + surface: wgpu::Surface<'static>, + config: wgpu::SurfaceConfiguration, + handover: Handover, +} + +// SAFETY: wgpu's objects are `Send`; a new `Renderer` has no native surface renderer (the one +// part that isn't), and `Handover` is used by one thread at a time. +#[allow(unsafe_code)] +unsafe impl Send for Prepared {} + +impl SurfaceMode { + /// Whether the CPU renderer draws this window's frames now. + pub(in crate::window) fn cpu_draws(&self) -> bool { matches!(self, SurfaceMode::Cpu { .. } | SurfaceMode::HandingOver { .. }) } + + /// The visual a handed-over window's swap chain goes on. + pub(in crate::window) fn visual(&self) -> Option<*mut std::ffi::c_void> { + match self { + SurfaceMode::Handed { handover } | SurfaceMode::Rebinding { handover } => Some(handover.visual()), + SurfaceMode::Gpu | SurfaceMode::Cpu { .. } | SurfaceMode::HandingOver { .. } => None, + } + } + + /// The DirectComposition tree of a handed-over window, for a playing clip's own layer + /// (`video_layer`). + pub(in crate::window) fn handover(&self) -> Option<&Handover> { + match self { + SurfaceMode::Handed { handover } | SurfaceMode::Rebinding { handover } => Some(handover), + SurfaceMode::Gpu | SurfaceMode::Cpu { .. } | SurfaceMode::HandingOver { .. } => None, + } + } + + /// A new swap chain went on the handed-over window's visual (`Host::reattach`). + pub(in crate::window) fn rebind(&mut self) { + if let SurfaceMode::Handed { .. } = self { + let SurfaceMode::Handed { handover } = std::mem::take(self) else { unreachable!() }; + *self = SurfaceMode::Rebinding { handover }; + } + } +} + +impl Host { + /// The first idle turn after the window's first CPU frame: the GPU starts on its thread + /// (`RUNE_CPU_FIRST=only`: not until a frame needs it, for checking the CPU window alone). + pub(in crate::window) fn cpu_idle(&mut self) { + if self.gpu_owed() { self.start_gpu(true); } + } + + /// Whether the GPU is due to start now (`cpu_idle`). + pub(in crate::window) fn gpu_owed(&self) -> bool { + if std::env::var_os("RUNE_CPU_FIRST").is_some_and(|v| v == "only") { return false; } + let now = crate::time::now(); + self.win.as_ref().is_some_and(|w| matches!(w.native.mode, SurfaceMode::Cpu { job: GpuJob::Waiting { retry_at, .. }, .. } if retry_at.is_none_or(|at| at <= now)) && w.first_frame.ready()) + } + + /// Starts making the GPU for this window on a thread (`below`: at below-normal priority, as + /// after the first frame; a frame that needs the GPU makes it at normal priority). + pub(super) fn start_gpu(&mut self, below: bool) { + let Some(w) = self.win.as_mut() else { return }; + let SurfaceMode::Cpu { job, .. } = &mut w.native.mode else { return }; + let GpuJob::Waiting { tries, retry_at } = *job else { return }; + if retry_at.is_some() { crate::marks::mark("gpu.window.retry"); } + let Some(hwnd) = crate::platform::win32::hwnd(&w.window) else { *job = GpuJob::Failed; return }; + let slot = Arc::new(Mutex::new(None)); + let (out, handle, srgb, size) = (slot.clone(), self.native_handle.clone(), self.app.rt().srgb_blend(), (w.config.width, w.config.height)); + // What the window draws, for the GPU thread's first frame of its own (`warm_frame`): each CPU + // frame until then replaces it. + let latest = Arc::new(Mutex::new(warm_instances(&self.app.rt().instances))); + let instances = latest.clone(); + let features = self.app.compositor_features(); + let hwnd = hwnd as isize; + let spawned = std::thread::Builder::new().name("rune-gpu-window".into()).spawn(move || { + if below { lower_priority(); } + let made = prepare(hwnd, size, srgb, features, &instances); + *out.lock().unwrap_or_else(|e| e.into_inner()) = Some(made); + handle.send(WakeEvent::GpuReady); + }); + match spawned { + Ok(thread) => { crate::marks::mark("gpu.window.start"); *job = GpuJob::Building { slot, latest, thread, since: crate::time::now(), raised: !below, tries: tries + 1, animating: false, ready: None }; } + Err(error) => self.fail_gpu(format!("its thread couldn't start: {error}"), tries + 1), + } + } + + /// The GPU thread finished: attach its device, renderer and surface and start handing over, + /// or stay on the CPU if it failed. While handing over: the GPU finished a frame. + pub(in crate::window) fn gpu_ready(&mut self) { + if self.win.as_ref().is_some_and(|w| matches!(w.native.mode, SurfaceMode::HandingOver { .. })) { return self.hand_over_if_done(); } + let Some(w) = self.win.as_mut() else { return }; + let SurfaceMode::Cpu { job: GpuJob::Building { slot, tries, animating, ready, .. }, .. } = &mut w.native.mode else { return }; + let tries = *tries; + let mut slot = slot.lock().unwrap_or_else(|e| e.into_inner()); + // Ready while the CPU frames move something (a view fading in): the hand-over waits for a + // frame at rest, so the frame both renderers draw is one that costs what a frame at rest + // does, not the first of the GPU's frames to draw every layer of an entrance. + let now = crate::time::now(); + if slot.as_ref().is_some_and(Result::is_ok) && *animating && now < *ready.get_or_insert(now) + QUIET_WAIT { + crate::marks::mark("gpu.window.deferred"); + return; + } + let Some(made) = slot.take() else { return }; + drop(slot); + let prepared = match made { + Ok(prepared) => prepared, + Err(error) => return self.fail_gpu(error, tries), + }; + crate::marks::mark("gpu.window.ready"); + let Prepared { gpu, mut renderer, surface, mut config, handover } = prepared; + let gpu = Arc::new(gpu); + if renderer.srgb_blend() != self.app.rt().srgb_blend() { + if !reblend_core(&surface, &gpu, &mut config, &mut renderer, &mut w.alpha, self.app.rt_mut()) { + return self.fail_gpu("couldn't reconfigure the surface for the window's blend mode".into(), tries); + } + } else { + let target_format = if self.app.rt().srgb_blend() { config.format.remove_srgb_suffix() } else { config.format }; + rebuild_renderer_core(&gpu.device, &mut renderer, target_format, self.app.rt_mut()); + } + *self.gpu_pool.borrow_mut() = Arc::downgrade(&gpu); + crate::render::surface_gpu(&gpu); + let size = w.window.inner_size(); + let SurfaceMode::Cpu { mut cpu, .. } = std::mem::replace(&mut w.native.mode, SurfaceMode::Gpu) else { unreachable!() }; + cpu.half = HalfRounding::of_vendor(gpu.adapter.get_info().vendor); + w.native.video_layers.hold_premultiplied(vrr_guard(gpu.adapter.get_info().vendor)); + w.native.mode = SurfaceMode::HandingOver { cpu, handover, done: None, readback: None, since: crate::time::now(), nudged: None, tries, paused: false }; + w.native.slot.reset(); + w.native.damage.reset(); + // D3D12's idle-priority threads compile the first frame's shaders: on a busy machine they + // would hold the hand-over frame off. + crate::platform::win32::unidle_d3d_threads_soon(); + w.surface = Some(surface); + w.config = config; + w.surface_ok = true; + // The window changed size while the GPU was made. + if size.width > 0 && size.height > 0 { w.resize_surface(Some(&*gpu), size); } + self.gpu = Some((gpu, renderer)); + w.request_redraw(); + } + + /// While handing over: the GPU draws the instances the CPU just painted, into its swap chain + /// on the uncommitted visual. + pub(super) fn gpu_draws_same_frame(&mut self) { + let (Some(l), Some((gpu, renderer))) = (self.win.as_mut(), self.gpu.as_mut()) else { return }; + if !matches!(l.native.mode, SurfaceMode::HandingOver { paused: false, .. }) { return; } + if renderer.srgb_blend() != self.app.rt().srgb_blend() { + let Some(surface) = l.surface.as_ref() else { return }; + l.native.slot.reset(); + if !reblend_core(surface, gpu, &mut l.config, renderer, &mut l.alpha, self.app.rt_mut()) { + l.surface_ok = false; + return; + } + } + let SurfaceMode::HandingOver { done, readback, paused: false, .. } = &mut l.native.mode else { return }; + let Some(surface) = l.surface.as_ref() else { return }; + let Ok(frame) = acquire(surface, gpu, &l.config, l.surface_ok, 1, &mut self.meter) else { return }; + let target_format = if self.app.rt().srgb_blend() { l.config.format.remove_srgb_suffix() } else { l.config.format }; + debug_assert_eq!(renderer.format(), target_format); + let view = frame.texture.create_view(&wgpu::TextureViewDescriptor { format: (target_format != l.config.format).then_some(target_format), ..Default::default() }); + { + let rt = self.app.rt_mut(); + renderer.upload_images(&gpu.device, &gpu.queue, &mut rt.images); + renderer.build_surfaces(&gpu.device, &rt.surfaces, rt.live_notifier()); + renderer.prepare_surfaces(&gpu.device, &gpu.queue, &rt.surfaces, (l.config.width, l.config.height)); + renderer.set_frame_wake(rt.live_wake()); + } + let mut enc = gpu.device.create_command_encoder(&Default::default()); + // The app's compositor draws the same instances the CPU painted (the CPU frame drew none of + // its effect slots, or it would have asked for the GPU). + let size = (l.config.width, l.config.height); + if self.app.has_compositor() { + let _ = self.app.render_compositor(CompositorFrame { + device: &gpu.device, + queue: &gpu.queue, + encoder: &mut enc, + target: &view, + format: target_format, + size, + dt: 0.0, + update_ms: 0.0, + ui: &mut *renderer, + }); + } else { + let rt = self.app.rt_mut(); + renderer.set_fade_stops(rt.fade_stops()); + renderer.prepare_ui(&gpu.device, &gpu.queue, &mut rt.text.atlas, &rt.instances, size); + renderer.draw(&mut enc, &view, rt.clear_color()); + } + // A copy of the frame, for the drift count once it's the one the window commits to: only + // when it's asked for (`RUNE_CPU_BOOT_DRIFT`), as the count is a diagnostic. + *readback = (crate::render::cpu_boot::drift_wanted() && l.config.usage.contains(wgpu::TextureUsages::COPY_SRC)).then(|| { + let (width, height) = size; + let row = (width * 4).div_ceil(wgpu::COPY_BYTES_PER_ROW_ALIGNMENT) * wgpu::COPY_BYTES_PER_ROW_ALIGNMENT; + let buffer = gpu.device.create_buffer(&wgpu::BufferDescriptor { label: Some("rune hand-over readback"), size: u64::from(row) * u64::from(height), usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ, mapped_at_creation: false }); + enc.copy_texture_to_buffer(frame.texture.as_image_copy(), wgpu::TexelCopyBufferInfo { buffer: &buffer, layout: wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(row), rows_per_image: Some(height) } }, + wgpu::Extent3d { width, height, depth_or_array_layers: 1 }); + Readback { buffer, row, size: (width, height) } + }); + renderer.submit(&gpu.queue, enc); + gpu.queue.present(frame); + if let Some(surface) = l.surface.as_ref() { + l.native.slot.presented_surface(surface); + } + let flag = Arc::new(AtomicBool::new(false)); + let set = flag.clone(); + gpu.queue.on_submitted_work_done(move || set.store(true, Ordering::Release)); + *done = Some((flag, crate::time::now())); + // A thread waits for the GPU and wakes the loop, which commits (`hand_over_if_done`). + let (waiting, handle) = (gpu.clone(), self.native_handle.clone()); + let spawned = std::thread::Builder::new().name("rune-gpu-wait".into()).spawn(move || { + rune_gpu::health::poll(&waiting.device, wgpu::PollType::wait_indefinitely()).ok(); + handle.send(WakeEvent::GpuReady); + }); + if let Err(error) = spawned { eprintln!("rune: could not wait for the GPU's frame: {error}"); } + crate::marks::mark_once(&FIRST_GPU, "frame.first.gpu"); + // A first frame only the GPU could draw. + if !l.first_frame.ready() { l.first_frame.gpu_done(); } + } + + /// At the start of a turn while handing over: when the GPU's last frame is done, commit the + /// visual (DWM shows the GPU from its next composition) and leave the CPU behind; the CPU's + /// buffer goes on a worker after counting the frame's drift. + pub(in crate::window) fn hand_over_if_done(&mut self) { + let (Some(w), Some((gpu, _))) = (self.win.as_mut(), self.gpu.as_ref()) else { return }; + match &mut w.native.mode { + SurfaceMode::HandingOver { done: Some((done, _)), tries, .. } => { + let tries = *tries; + rune_gpu::health::poll(&gpu.device, wgpu::PollType::Poll).ok(); + let lost = gpu.is_lost(); + if !lost && !done.load(Ordering::Acquire) { return; } + let committed = if lost { Err("its device was lost".to_owned()) } else if let SurfaceMode::HandingOver { handover, .. } = &w.native.mode { handover.commit() } else { unreachable!() }; + if let Err(error) = committed { return self.fail_gpu(format!("the GPU couldn't take over the window: {error}"), tries); } + let SurfaceMode::HandingOver { cpu, handover, readback, .. } = std::mem::replace(&mut w.native.mode, SurfaceMode::Gpu) else { unreachable!() }; + crate::marks::mark("gpu.window.handed"); + crate::platform::win32::unidle_d3d_threads_soon(); + // A first frame only the GPU could draw showed cloaked: it comes on screen now. + if w.native.cloak.held() { + w.native.cloak.lift(&w.window); + crate::marks::mark("window.shown"); + } + // What DWM shows is in the window's own surface now, not in the buffer: it goes on a + // worker, after counting how many of its pixels the GPU's same frame drew otherwise. + // A frame only the GPU draws (Slug's text, a native surface) never showed a CPU + // frame: its buffer holds nothing to count against. + let shown = matches!(cpu.shown, Shown::Copied(_)); + if let Some(dib) = cpu.into_dib() { + match readback { + Some(r) if shown => count_drift(gpu.clone(), r, dib), + Some(_) => { + eprintln!("rune: cpu boot drift: none to count, the CPU showed no frame (the first needed the GPU)"); + free_later(dib); + } + None => free_later(dib), + } + } + w.native.mode = SurfaceMode::Handed { handover }; + w.presented = None; + // What was asked for while the GPU finished its frame draws now, on the GPU. + w.request_redraw(); + } + SurfaceMode::HandingOver { done: None, .. } | SurfaceMode::Gpu | SurfaceMode::Cpu { .. } | SurfaceMode::Handed { .. } | SurfaceMode::Rebinding { .. } => {} + } + } + + /// The GPU couldn't take over (`why`), on its `tries`th try: the window goes on, or back, to + /// the CPU renderer, and tries again after `RETRY_AFTER`, or stays there after `TRIES` tries. + fn fail_gpu(&mut self, why: String, tries: u8) { + eprintln!("rune: the window stays on the CPU renderer for now (try {tries} of {TRIES}): {why}"); + crate::marks::mark("gpu.window.failed"); + if !crate::marks::noted("gpu.window.why") { crate::marks::note("gpu.window.why", Box::leak(why.into_boxed_str())); } + let Some(w) = self.win.as_mut() else { return }; + let job = if tries < TRIES { GpuJob::Waiting { tries, retry_at: Some(crate::time::now() + RETRY_AFTER) } } else { GpuJob::Failed }; + let (SurfaceMode::Cpu { cpu, .. } | SurfaceMode::HandingOver { cpu, .. }) = std::mem::replace(&mut w.native.mode, SurfaceMode::Gpu) else { unreachable!("only a CPU window hands over") }; + w.native.mode = SurfaceMode::Cpu { cpu, job }; + // From a hand-over: its swap chain and GPU go. DWM kept the window's own content, which + // the CPU goes on drawing. + w.native.slot.reset(); + w.surface = None; + self.gpu = None; + w.request_redraw(); + } + + /// The hand-over's deadlines, at the start of a turn (`Win::handover_deadline` wakes the loop + /// for them): a GPU thread still making the GPU is raised to normal priority, then logged as + /// slow; a frame both renderers draw is asked for until one is, in sight or not; a GPU that + /// doesn't finish that frame fails; a failed try is made again. + pub(in crate::window) fn watch_handover(&mut self, now: Instant) { + let Some(w) = self.win.as_mut() else { return }; + match &mut w.native.mode { + SurfaceMode::Cpu { job: GpuJob::Building { thread, since, raised, ready, .. }, .. } => { + if ready.is_some_and(|at| now >= at + QUIET_WAIT) { return self.gpu_ready(); } + if !*raised && now >= *since + RAISE_AFTER { + *raised = true; + raise_priority(thread); + crate::marks::mark("gpu.window.raised"); + } + if now >= *since + BUILD_SLOW { crate::marks::mark("gpu.window.slow"); } + } + SurfaceMode::HandingOver { done: None, since, nudged, tries, .. } => { + if now >= *since + FINISH_LIMIT { + let tries = *tries; + return self.fail_gpu(format!("no frame could be drawn by both renderers in {} s", FINISH_LIMIT.as_secs()), tries); + } + if now < nudged.unwrap_or(*since) + NUDGE_EVERY { return; } + *nudged = Some(now); + crate::marks::mark("gpu.window.nudged"); + w.request_redraw(); + } + SurfaceMode::HandingOver { done: Some((_, at)), tries, .. } => { + if now < *at + FINISH_LIMIT { return; } + let tries = *tries; + self.fail_gpu(format!("the GPU didn't finish the hand-over frame in {} s", FINISH_LIMIT.as_secs()), tries); + } + SurfaceMode::Cpu { job: GpuJob::Waiting { retry_at: Some(at), .. }, .. } => { + if now >= *at && w.first_frame.ready() { self.start_gpu(true); } + } + SurfaceMode::Cpu { job: GpuJob::Waiting { retry_at: None, .. } | GpuJob::Failed, .. } + | SurfaceMode::Gpu | SurfaceMode::Handed { .. } | SurfaceMode::Rebinding { .. } => {} + } + } +} + +impl Win { + /// When the hand-over next has something to do (`Host::watch_handover`). + pub(in crate::window) fn handover_deadline(&self, now: Instant) -> Option<Instant> { + match &self.native.mode { + SurfaceMode::Cpu { job: GpuJob::Building { ready: Some(at), .. }, .. } => Some(*at + QUIET_WAIT), + SurfaceMode::Cpu { job: GpuJob::Building { since, raised: false, .. }, .. } => Some(*since + RAISE_AFTER), + SurfaceMode::Cpu { job: GpuJob::Building { since, .. }, .. } => Some(*since + BUILD_SLOW).filter(|&at| at > now), + SurfaceMode::HandingOver { done: None, since, nudged, .. } => Some(nudged.unwrap_or(*since) + NUDGE_EVERY), + SurfaceMode::HandingOver { done: Some((_, at)), .. } => Some(*at + FINISH_LIMIT), + SurfaceMode::Cpu { job: GpuJob::Waiting { retry_at, .. }, .. } => retry_at.filter(|&at| at > now), + SurfaceMode::Cpu { job: GpuJob::Failed, .. } | SurfaceMode::Gpu | SurfaceMode::Handed { .. } | SurfaceMode::Rebinding { .. } => None, + } + } +} + +/// Runs the GPU thread at normal priority (`RAISE_AFTER`). +#[allow(unsafe_code)] +fn raise_priority(thread: &std::thread::JoinHandle<()>) { + use std::os::windows::io::AsRawHandle; + use windows_sys::Win32::System::Threading::{SetThreadPriority, THREAD_PRIORITY_NORMAL}; + // SAFETY: the GPU thread's own handle, open as long as `thread` is. + unsafe { SetThreadPriority(thread.as_raw_handle(), THREAD_PRIORITY_NORMAL) }; +} + +static FIRST_GPU: AtomicBool = AtomicBool::new(false); + +/// On the GPU thread: the device (the one `warm_gpu` made, if it did), the renderer, the +/// uncommitted visual and a swap chain on it, configured for `size`. +#[allow(unsafe_code)] +fn prepare(hwnd: isize, size: (u32, u32), srgb: bool, features: wgpu::Features, latest: &Mutex<Vec<crate::render::Instance>>) -> Result<Prepared, String> { + let handover = Handover::new(hwnd)?; + let visual = handover.visual(); + // SAFETY: the visual stays alive while the surface does: the surface takes its own reference + // to it, and the window keeps the `Handover` as long as it keeps the surface. + let (gpu, surface, renderer) = Gpu::for_surface(features, false, + |instance| unsafe { instance.create_surface_unsafe(wgpu::SurfaceTargetUnsafe::CompositionVisual(visual)) }.map_err(|e| e.to_string()))?; + let (config, _) = surface_config(&surface, &gpu.adapter, (size.0.max(1), size.1.max(1)), srgb).ok_or("the GPU can't present to this window")?; + configure(&surface, &gpu, &config)?; + let target_format = if srgb { config.format.remove_srgb_suffix() } else { config.format }; + let mut renderer = renderer.unwrap_or_else(|| Renderer::new(&gpu.device, target_format)); + let instances = std::mem::take(&mut *latest.lock().unwrap_or_else(|e| e.into_inner())); + warm_frame(&gpu, &mut renderer, target_format, srgb, (config.width, config.height), &instances); + crate::marks::mark("gpu.window.warmed"); + Ok(Prepared { gpu, renderer, surface, config, handover }) +} + +/// On the GPU thread, before the hand-over: the renderer draws the window's latest CPU frame once, +/// into a target of the swap chain's format, and waits for the GPU. Its first frame's costs are +/// paid here, so the hand-over frame on the app's thread costs what a frame does: the pipelines +/// its layers' formats need, its layers' targets (the hand-over frame's layers are the latest +/// frame's, or nearly), the staging space and the instance buffer. Its own target goes as soon as +/// the GPU is done with it. The atlas is an empty one: the glyphs land with the hand-over frame's +/// own prepare. +fn warm_frame(gpu: &Gpu, renderer: &mut Renderer, format: wgpu::TextureFormat, srgb: bool, size: (u32, u32), instances: &[crate::render::Instance]) { + renderer.set_format(&gpu.device, format); + renderer.set_srgb_blend(srgb); + debug_assert_eq!(renderer.format(), format); + let target = gpu.device.create_texture(&wgpu::TextureDescriptor { + label: Some("rune warm frame"), + size: wgpu::Extent3d { width: size.0.max(1), height: size.1.max(1), depth_or_array_layers: 1 }, + mip_level_count: 1, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + format, + usage: wgpu::TextureUsages::RENDER_ATTACHMENT, + view_formats: &[], + }); + let view = target.create_view(&Default::default()); + let mut atlas = crate::text::Atlas::new(); + let mut enc = gpu.device.create_command_encoder(&Default::default()); + renderer.prepare_ui(&gpu.device, &gpu.queue, &mut atlas, instances, size); + renderer.draw(&mut enc, &view, [0.0; 4]); + renderer.submit(&gpu.queue, enc); + rune_gpu::health::poll(&gpu.device, wgpu::PollType::wait_indefinitely()).ok(); + target.destroy(); + rune_gpu::health::poll(&gpu.device, wgpu::PollType::Poll).ok(); +} + +/// A CPU frame's instances as the warm frame draws them: what reads the app's own state (an +/// image's slot, a glyph's atlas page, a compositor's effect) draws as a plain box, so the frame +/// needs nothing but the renderer. +pub(super) fn warm_instances(instances: &[crate::render::Instance]) -> Vec<crate::render::Instance> { + use crate::render::{KIND_RECT, Kind}; + instances + .iter() + .map(|i| { + let mut i = *i; + match i.kind() { + Some(Kind::Image | Kind::Effect) => i.params[1] = KIND_RECT, + Some(Kind::Glyph) => i.params[2] = 0.0, + _ => {} + } + i + }) + .collect() +} + +/// On a worker: maps the GPU frame's copy, counts the pixels that differ from the CPU's buffer +/// (`cpu_boot::drift` logs one line and keeps `last_drift`), and frees both. +fn count_drift(gpu: Arc<Gpu>, readback: Readback, mut dib: Dib) { + let spawned = std::thread::Builder::new().name("rune-drift".into()).spawn(move || { + let slice = readback.buffer.slice(..); + slice.map_async(wgpu::MapMode::Read, |_| {}); + if rune_gpu::health::poll(&gpu.device, wgpu::PollType::wait_indefinitely()).is_err() { return; } + let (width, height) = readback.size; + let stride = dib.stride(); + let Ok(gpu_px) = slice.get_mapped_range() else { return }; + crate::render::cpu_boot::drift(crate::render::cpu_boot::Pixels::bgra(dib.bytes(), width, height, stride), crate::render::cpu_boot::Pixels::bgra(&gpu_px, width, height, readback.row as usize)); + }); + if let Err(error) = spawned { eprintln!("rune: could not count the hand-over's drift: {error}"); } +} + +#[allow(unsafe_code)] +fn lower_priority() { + use windows_sys::Win32::System::Threading::{GetCurrentThread, SetThreadPriority, THREAD_PRIORITY_BELOW_NORMAL}; + // SAFETY: this thread's pseudo-handle. + unsafe { SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_BELOW_NORMAL) }; +} + +/// Whether the window's swap chain composites premultiplied for good, so the display's refresh +/// rate doesn't follow its presents. With G-SYNC in windowed mode (NVIDIA's, off by default) the +/// display refreshes when the focused window presents an opaque flip-model or DirectComposition +/// swap chain, so lone presents (a hover) swing the rate, and many OLED panels' brightness with it +/// (hex#689). A premultiplied DirectComposition swap chain keeps G-SYNC off (measured on that +/// hardware, as reported there). It costs DWM a blend of the regions the window +/// presents, and nothing while it rests. A fixed-rate display (blade's Iris panel) needs nothing: +/// its refresh doesn't depend on who presents. +fn vrr_guard(vendor: u32) -> bool { vendor == 0x10DE } + +#[cfg(test)] +#[path = "handover_tests.rs"] +mod tests; diff --git a/app/vendor/rune/crates/rune/src/window/win32/handover_tests.rs b/app/vendor/rune/crates/rune/src/window/win32/handover_tests.rs new file mode 100644 index 0000000..ee217d6 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/window/win32/handover_tests.rs @@ -0,0 +1,40 @@ +use super::warm_frame; +use crate::render::{Gpu, Instance, KIND_RECT, NO_CLIP, Renderer}; + +fn rect_instance() -> Instance { + Instance { + rect: [0.0, 0.0, 16.0, 16.0], + radii: [0.0; 4], + fill: [0.5, 0.25, 0.125, 1.0], + border: [0.0; 4], + params: [0.0, KIND_RECT, 0.0, 1.0], + uv: [0.0; 4], + clip: NO_CLIP, + fade: [0; 4], + } +} + +/// A pre-warmed `Bgra8Unorm` renderer (`render/warm.rs` `FORMAT`) handed to a window whose swap +/// chain target is `Bgra8UnormSrgb` (`srgb_blend == false`) must switch its pipeline format +/// before `warm_frame` draws, or wgpu rejects the render pass with a validation error; likewise +/// for a parked `Bgra8UnormSrgb` renderer handed to a `Bgra8Unorm` (`srgb_blend == true`) window, +/// and `srgb_blend` must match the window's mode even when the format already agrees. +#[test] +fn warm_frame_rebuilds_renderer_for_target_format() { + let gpu = Gpu::headless(); + let instances = [rect_instance()]; + for (initial, target, srgb) in [ + (wgpu::TextureFormat::Bgra8Unorm, wgpu::TextureFormat::Bgra8UnormSrgb, false), + (wgpu::TextureFormat::Bgra8UnormSrgb, wgpu::TextureFormat::Bgra8Unorm, true), + (wgpu::TextureFormat::Bgra8Unorm, wgpu::TextureFormat::Bgra8Unorm, true), + (wgpu::TextureFormat::Bgra8UnormSrgb, wgpu::TextureFormat::Bgra8UnormSrgb, false), + ] { + let mut renderer = Renderer::new(&gpu.device, initial); + let scope = gpu.device.push_error_scope(wgpu::ErrorFilter::Validation); + warm_frame(&gpu, &mut renderer, target, srgb, (32, 32), &instances); + let error = pollster::block_on(scope.pop()); + assert!(error.is_none(), "warm_frame({initial:?} -> {target:?}, srgb={srgb}) hit validation error: {error:?}"); + assert_eq!(renderer.format(), target); + assert_eq!(renderer.srgb_blend(), srgb); + } +} diff --git a/app/vendor/rune/crates/rune/src/window/win32/look.rs b/app/vendor/rune/crates/rune/src/window/win32/look.rs new file mode 100644 index 0000000..27b9a59 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/window/win32/look.rs @@ -0,0 +1,111 @@ +//! Windows: whether other windows cover a window, found when it's about to draw +//! (`platform::win32::occlusion::look`) rather than heard from every app's window events. A +//! frame looks when the last look is older than `FRESH`, or the window's own move, size, show, +//! focus or input made it stale; the pointer reaching it counts as seen. Covered, it runs no motion +//! (`Cover::Windows`), and a frame asked for draws settled once the changes go quiet +//! (`CoveredDraw`), so what the window shows the moment it's uncovered is current. Only motion +//! falls behind, so only a covered window with a loop on screen looks again, after `AGAIN` and then +//! less often (`AGAIN_MAX`), until it's seen. Idle, covered or not, nothing wakes it. + +use std::time::Duration; + +use crate::time::Instant; + +/// How long a look holds while the window draws. +pub(super) const FRESH: Duration = Duration::from_millis(250); +/// How soon a covered window with motion on screen first looks again; each look that finds it +/// still covered doubles the wait, up to `AGAIN_MAX`. Windows says nothing when a window is +/// uncovered (no message, and on an Iris Xe DXGI's occlusion status stays clear for a windowed +/// flip-model swap chain, covered whole or minimised: a test present returns `S_OK`, the +/// occlusion-status event doesn't fire), so a spinner that +/// comes back into view resumes within that wait; what else it shows is current (`CoveredDraw`). +pub(super) const AGAIN: Duration = Duration::from_millis(250); +pub(super) const AGAIN_MAX: Duration = Duration::from_secs(1); + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(in crate::window) enum Look { + /// Nothing known since the window last moved, showed, took focus or heard input. + #[default] + Due, + /// Seen at `at`. + Seen { at: Instant }, + /// Covered. `again`: when to look again, and the wait it came after, while motion on screen + /// would be out of date. + Covered { again: Option<(Instant, Duration)> }, +} + +#[derive(Clone, Copy, Debug)] +pub(in crate::window) enum LookEvent { + /// A frame is about to draw, or a covered window's look again is due. + Frame { now: Instant }, + /// A look found the window seen or not; `moving`: motion is on screen. + Found { seen: bool, moving: bool, now: Instant }, + /// The window's own event: the next frame looks. + Stale, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(in crate::window) enum LookEffect { + None, + /// Look now (`occlusion::look`), then step `Found`. + Look, +} + +impl Look { + pub(in crate::window) fn step(self, event: LookEvent) -> (Look, LookEffect) { + match (self, event) { + (Look::Seen { at }, LookEvent::Frame { now }) if now < at + FRESH => (self, LookEffect::None), + (_, LookEvent::Frame { .. }) => (self, LookEffect::Look), + (_, LookEvent::Found { seen: true, now, .. }) => (Look::Seen { at: now }, LookEffect::None), + (state, LookEvent::Found { seen: false, moving, now }) => { + let wait = match state { Look::Covered { again: Some((_, wait)) } => (wait * 2).min(AGAIN_MAX), _ => AGAIN }; + (Look::Covered { again: moving.then(|| (now + wait, wait)) }, LookEffect::None) + } + (_, LookEvent::Stale) => (Look::Due, LookEffect::None), + } + } + + /// When a covered window looks again. + pub(in crate::window) fn deadline(self) -> Option<Instant> { + match self { + Look::Covered { again } => again.map(|(at, _)| at), + Look::Due | Look::Seen { .. } => None, + } + } + +} + +impl crate::window::host::Host { + /// Before a frame draws: looks whether other windows cover the window when the last look is + /// stale, and covers or uncovers it (`Cover::Windows`). + pub(in crate::window) fn look(&mut self) { + let Some(w) = self.win.as_mut() else { return }; + let now = crate::time::now(); + let (look, effect) = w.native.look.step(LookEvent::Frame { now }); + w.native.look = look; + if effect == LookEffect::None { return; } + let seen = crate::platform::win32::occlusion::look(&w.window) == crate::platform::win32::occlusion::Found::Seen; + let moving = self.app.rt().loops_shown(); + self.look_found(seen, moving, now); + } + + /// The window's own event: its next frame looks. + pub(in crate::window) fn look_stale(&mut self) { + if let Some(w) = self.win.as_mut() { w.native.look = w.native.look.step(LookEvent::Stale).0; } + } + + /// The pointer reached the window, so some of it shows: no look needed. + pub(in crate::window) fn sighted(&mut self) { + if self.win.is_none() { return; } + self.look_found(true, false, crate::time::now()); + } + + fn look_found(&mut self, seen: bool, moving: bool, now: Instant) { + let Some(w) = self.win.as_mut() else { return }; + w.native.look = w.native.look.step(LookEvent::Found { seen, moving, now }).0; + if self.life.covered_by(crate::window::state::Cover::Windows) != seen { return; } + // Covered mid-move: land, so the window comes back at its new place. + if !seen { self.land_frame(); } + self.set_cover(crate::window::state::Cover::Windows, !seen); + } +} diff --git a/app/vendor/rune/crates/rune/src/window/win32/post_frame.rs b/app/vendor/rune/crates/rune/src/window/win32/post_frame.rs new file mode 100644 index 0000000..44d7aa9 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/window/win32/post_frame.rs @@ -0,0 +1,63 @@ +//! Windows: what a window does once its first frame is up runs one piece a turn, and none while +//! input waits. The pieces: the app's `on_ready`, the drop target and session-lock hooks, the GPU's +//! start, the accessibility adapter, then any view the app asked to have its text laid out ahead +//! (`Tx::prepare_text`). Run together, in the first idle turn, they held the UI +//! thread for 30-50 ms, so a click or key that came as the first frame showed waited behind all of +//! them. Between pieces winit takes what's in the queue, and the frame it asks for comes first. + +#![allow(unsafe_code)] + +use crate::window::host::Host; + +/// The window's own pieces still owed: the app's `on_ready`, then the window's hooks, then none. +/// The GPU's start and the adapter are owed while their own states say so (`GpuJob::Waiting`, +/// `A11yStart::AfterFirstFrame`). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(in crate::window) enum Chores { + #[default] + Done, + Ready, + Hooks, +} + +/// Whether a key or mouse message is waiting in this thread's queue, so the next piece waits for +/// the turn after winit has taken it: the user's input, or one another app posted (an assistive +/// tool, a test). winit's own wakes are posted messages outside those ranges, and they keep +/// coming while the app starts, so they don't count. Sent messages aren't dispatched here. +pub(in crate::window) fn input_waiting() -> bool { + use windows_sys::Win32::UI::WindowsAndMessaging::{MSG, PM_NOREMOVE, PM_QS_INPUT, PM_QS_POSTMESSAGE, PeekMessageW, WM_KEYFIRST, WM_KEYLAST, WM_MOUSEFIRST, WM_MOUSELAST}; + [(WM_KEYFIRST, WM_KEYLAST), (WM_MOUSEFIRST, WM_MOUSELAST)].into_iter().any(|(first, last)| { + // SAFETY: `msg` is written only; PM_NOREMOVE leaves the message in the queue, and the + // PM_QS_* flags keep sent messages from being dispatched. + unsafe { + let mut msg: MSG = std::mem::zeroed(); + PeekMessageW(&mut msg, std::ptr::null_mut(), first, last, PM_NOREMOVE | PM_QS_INPUT | PM_QS_POSTMESSAGE) != 0 + } + }) +} + +impl Host { + /// One owed piece, unless input waits; true while more are owed, so the loop turns again. + pub(in crate::window) fn post_frame_turn(&mut self) -> bool { + if !self.post_frame_owed() { return false; } + if input_waiting() { return true; } + match self.chores { + Chores::Ready => { + self.chores = Chores::Hooks; + self.run_on_ready(); + } + Chores::Hooks => { + self.chores = Chores::Done; + self.run_ready_hooks(); + } + Chores::Done if self.gpu_owed() => self.cpu_idle(), + Chores::Done if self.a11y_owed() => self.a11y_after_frame(), + Chores::Done => { self.app.text_idle_turn(); } + } + self.post_frame_owed() + } + + fn post_frame_owed(&self) -> bool { + self.chores != Chores::Done || self.gpu_owed() || self.a11y_owed() || self.app.text_idle_owed() + } +} diff --git a/app/vendor/rune/crates/rune/src/window/win32/slot.rs b/app/vendor/rune/crates/rune/src/window/win32/slot.rs new file mode 100644 index 0000000..c82c513 --- /dev/null +++ b/app/vendor/rune/crates/rune/src/window/win32/slot.rs @@ -0,0 +1,167 @@ +//! Windows: when a window's or an overlay's swap chain can take its next frame. It holds at most +//! one frame the compositor hasn't shown (`FRAME_LATENCY`), and its waitable object is signalled +//! when it can take another. wgpu doesn't wait on it +//! (`Dx12UseFrameLatencyWaitableObject::DontWait`): a frame that blocked in `acquire` would be +//! built from the input that came before the wait, and the input that came during it would wait a +//! frame more. Instead a surface that wants a frame while the swap chain is full asks a +//! thread-pool wait to wake the loop when it isn't; the loop then handles every input that came +//! meanwhile, and the frame is built from all of it. Nothing waits, and no thread runs, while the +//! surface draws nothing. + +#![allow(unsafe_code)] + +use std::ffi::c_void; + +use windows_sys::Win32::Foundation::{CloseHandle, DUPLICATE_SAME_ACCESS, DuplicateHandle, HANDLE, INVALID_HANDLE_VALUE, WAIT_OBJECT_0}; +use windows_sys::Win32::System::Threading::{ + GetCurrentProcess, RegisterWaitForSingleObject, UnregisterWaitEx, WT_EXECUTEINWAITTHREAD, WT_EXECUTEONLYONCE, WaitForSingleObject, +}; + +/// How long a registered wait waits before it gives the frame anyway: a swap chain that was +/// made again or lost never signals the object the wait holds. +const GIVE_UP_MS: u32 = 100; + +/// One surface's swap chain, as the next frame sees it: an app window's or an overlay's. +#[derive(Default)] +pub(crate) enum Slot { + /// No frame of ours is queued (none yet, or the swap chain was made again). + #[default] + Free, + /// A frame was presented on swap chain `generation`: the next one waits until the object says + /// the queue has room. + Owed { generation: u64 }, + /// Owed on `generation` and `source`, and the wait that asks for the next frame is registered + /// (dropping it unregisters it). + Waiting { #[allow(dead_code)] wait: Wait, generation: u64, source: usize }, +} + +/// What the surface's next frame does (`Slot::take`). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum Take { + /// Draw now. + Draw, + /// Don't: the registered wait asks for the frame (`WakeEvent::FrameSlot`). + Later, +} + +impl Slot { + /// Whether a thread-pool wait is currently registered for swap-chain room. + pub(crate) fn waiting(&self) -> bool { + matches!(self, Slot::Waiting { .. }) + } + + /// Takes room on `surface`'s swap chain, using its configure generation and DX12 waitable + /// handle so any reconfiguration or replacement automatically invalidates stale state. + pub(crate) fn take_surface(&mut self, surface: &wgpu::Surface, wake: impl Fn() + Send + 'static) -> Take { + let generation = crate::window::surface::configure::generation(surface); + // SAFETY: the object is the live swap chain's; `Slot` waits on its own duplicated copy. + let waitable = unsafe { surface.as_hal::<wgpu::hal::api::Dx12>().and_then(|h| h.waitable_handle()) }; + self.take(generation, waitable.map(|h| h.0), wake) + } + + /// The frame about to draw takes the swap chain's room, or waits for it. `generation` is the + /// surface's last successful configure number; `waitable` is the swap chain's object; `wake` + /// asks the loop for the frame from the thread-pool thread. + pub(crate) fn take(&mut self, generation: u64, waitable: Option<HANDLE>, wake: impl Fn() + Send + 'static) -> Take { + match *self { + Slot::Free => Take::Draw, + Slot::Waiting { generation: waited, source, .. } => { + if waited == generation && waitable.is_some_and(|h| h as usize == source) { + Take::Later + } else { + // The swap chain was reconfigured, replaced, or lost since the wait started. + *self = Slot::Free; + Take::Draw + } + } + Slot::Owed { generation: owed } => { + if owed != generation { + *self = Slot::Free; + return Take::Draw; + } + let Some(object) = waitable else { *self = Slot::Free; return Take::Draw }; + // SAFETY: the swap chain's live object; a zero timeout only polls it (and takes its + // count when it's signalled). + if unsafe { WaitForSingleObject(object, 0) } == WAIT_OBJECT_0 { + *self = Slot::Free; + return Take::Draw; + } + match Wait::register(object, Box::new(wake)) { + Some(wait) => { + *self = Slot::Waiting { wait, generation, source: object as usize }; + Take::Later + } + // No thread-pool wait: draw, and let `acquire` find what it finds. + None => { *self = Slot::Free; Take::Draw } + } + } + } + } + + /// The registered wait came back: the swap chain has room (its count is ours now). + pub(crate) fn came_back(&mut self) { + if matches!(self, Slot::Waiting { .. }) { *self = Slot::Free; } + } + + /// A frame was presented on `surface`. + pub(crate) fn presented_surface(&mut self, surface: &wgpu::Surface) { + self.presented(crate::window::surface::configure::generation(surface)); + } + + /// A frame was presented on swap chain `generation`. + pub(crate) fn presented(&mut self, generation: u64) { + *self = Slot::Owed { generation }; + } + + /// The swap chain was configured again or replaced: nothing of ours is queued on it. + pub(crate) fn reset(&mut self) { *self = Slot::Free; } +} + +/// A one-shot thread-pool wait on a copy of the swap chain's object, so wgpu closing its handle +/// (a reconfigure makes a new one) never leaves the wait on a closed handle. +pub(crate) struct Wait { + wait: HANDLE, + object: HANDLE, + wake: *mut Box<dyn Fn() + Send>, +} + +impl Wait { + fn register(object: HANDLE, wake: Box<dyn Fn() + Send>) -> Option<Wait> { + let mut copy: HANDLE = std::ptr::null_mut(); + // SAFETY: duplicates a live handle of this process into this process. + let ok = unsafe { DuplicateHandle(GetCurrentProcess(), object, GetCurrentProcess(), &mut copy, 0, 0, DUPLICATE_SAME_ACCESS) }; + if ok == 0 { return None; } + let wake = Box::into_raw(Box::new(wake)); + let mut wait: HANDLE = std::ptr::null_mut(); + // SAFETY: `wake` lives until `drop` has unregistered the wait and its callback is done; + // the callback only calls it. + let ok = unsafe { RegisterWaitForSingleObject(&mut wait, copy, Some(came), wake.cast(), GIVE_UP_MS, WT_EXECUTEONLYONCE | WT_EXECUTEINWAITTHREAD) }; + if ok == 0 { + // SAFETY: both are ours and unused. + unsafe { drop(Box::from_raw(wake)); CloseHandle(copy); } + return None; + } + Some(Wait { wait, object: copy, wake }) + } +} + +impl Drop for Wait { + fn drop(&mut self) { + // SAFETY: waits for a running callback to finish, so `wake` is no longer in use. + unsafe { + UnregisterWaitEx(self.wait, INVALID_HANDLE_VALUE); + drop(Box::from_raw(self.wake)); + CloseHandle(self.object); + } + } +} + +unsafe extern "system" fn came(context: *mut c_void, _timed_out: bool) { + // SAFETY: the `Box` `register` made, alive until the wait is unregistered. + let wake = unsafe { &*(context as *const Box<dyn Fn() + Send>) }; + wake(); +} + +#[cfg(test)] +#[path = "slot_tests.rs"] +mod tests; diff --git a/app/vendor/rune/crates/rune/src/window/win32/slot_tests.rs b/app/vendor/rune/crates/rune/src/window/win32/slot_tests.rs new file mode 100644 index 0000000..c6dd7be --- /dev/null +++ b/app/vendor/rune/crates/rune/src/window/win32/slot_tests.rs @@ -0,0 +1,93 @@ +#![allow(unsafe_code)] + +use windows_sys::Win32::Foundation::{CloseHandle, HANDLE}; +use windows_sys::Win32::System::Threading::CreateEventW; + +use super::{Slot, Take}; + +struct Event(HANDLE); + +impl Event { + fn new(signalled: bool) -> Self { + // SAFETY: anonymous manual-reset event owned by this guard. + let handle = unsafe { CreateEventW(std::ptr::null(), 1, i32::from(signalled), std::ptr::null()) }; + assert!(!handle.is_null()); + Self(handle) + } +} + +impl Drop for Event { + fn drop(&mut self) { + // SAFETY: closes the handle created in `Event::new`. + unsafe { CloseHandle(self.0); } + } +} + +#[test] +fn slot_resets_when_swap_chain_waitable_changes_or_disappears() { + let old_waitable = Event::new(false); + let new_waitable = Event::new(true); + + let mut slot = Slot::default(); + slot.presented(1); + assert_eq!(slot.take(1, Some(old_waitable.0), || {}), Take::Later, "unsignalled swap chain waits"); + assert!(slot.waiting()); + + // Swap chain was reconfigured or replaced (new waitable object, or surface lost/none). + assert_eq!( + slot.take(1, Some(new_waitable.0), || {}), + Take::Draw, + "a new swap chain must not stay blocked on the replaced swap chain's wait" + ); + assert!(!slot.waiting()); + + slot.presented(2); + assert_eq!(slot.take(2, Some(old_waitable.0), || {}), Take::Later); + assert_eq!( + slot.take(2, None, || {}), + Take::Draw, + "losing the waitable handle must clear the stale wait" + ); + assert!(!slot.waiting()); +} + +#[test] +fn slot_resets_when_surface_configure_generation_advances() { + let waitable = Event::new(false); + let mut slot = Slot::default(); + + // Waiting on generation 1, then swap chain reconfigured (generation 2) with the same handle. + slot.presented(1); + assert_eq!(slot.take(1, Some(waitable.0), || {}), Take::Later); + assert!(slot.waiting()); + assert_eq!(slot.take(2, Some(waitable.0), || {}), Take::Draw); + assert!(!slot.waiting()); + + // Owed on generation 2, then swap chain reconfigured (generation 3) before next take. + slot.presented(2); + assert_eq!(slot.take(3, Some(waitable.0), || {}), Take::Draw); + assert!(!slot.waiting()); + + // Explicit reset clears both Owed and Waiting immediately. + slot.presented(3); + assert_eq!(slot.take(3, Some(waitable.0), || {}), Take::Later); + slot.reset(); + assert!(!slot.waiting()); + assert_eq!(slot.take(3, Some(waitable.0), || {}), Take::Draw); +} + +#[test] +fn slot_draws_immediately_when_signalled_or_after_wait_completes() { + let signalled = Event::new(true); + let unsignalled = Event::new(false); + let mut slot = Slot::default(); + + slot.presented(1); + assert_eq!(slot.take(1, Some(signalled.0), || {}), Take::Draw); + + slot.presented(1); + assert_eq!(slot.take(1, Some(unsignalled.0), || {}), Take::Later); + slot.came_back(); + assert!(!slot.waiting()); + assert_eq!(slot.take(1, Some(unsignalled.0), || {}), Take::Draw); +} diff --git a/app/vendor/rune/crates/rune/src/window/win32/video_layer.rs b/app/vendor/rune/crates/rune/src/window/win32/video_layer.rs new file mode 100644 index 0000000..624ecba --- /dev/null +++ b/app/vendor/rune/crates/rune/src/window/win32/video_layer.rs @@ -0,0 +1,306 @@ +//! Windows: a playing clip shown on its own layer under the window's UI +//! (`video::windows::layer`), so playing draws no UI frame per picture. +//! +//! The layer is a DirectComposition visual under the UI's; the UI punches the video's place out of +//! its pixels, so corners, clips, opacity and anything drawn over the video stay the UI's own. A +//! swap chain's present and a DirectComposition commit land on different compositions, so the +//! layer only shows while the video's place is still: while it moves (scrolling, a resize, a +//! fade), the UI draws the pictures, as it does without a layer. Once it has held still for a +//! frame, the decoder presents on the layer at its size; once a picture is there, the visual is +//! moved, committed and waited for, and the UI punches from that frame on. +//! +//! The UI's swap chain composites premultiplied only while a layer shows: DWM then blends every +//! region the UI presents, which costs nothing while it's still but 12-15% of an integrated GPU +//! while it animates (`proof\video-win\layer`). + +use crate::native_surface::{SurfaceDraw, place}; +use crate::platform::win32::dcomp_handover::Handover; +use crate::time::Instant; +use std::sync::Arc; +use std::time::Duration; +use windows::Win32::Graphics::DirectComposition::IDCompositionVisual; + +/// How long no layer shows before the UI's swap chain goes back to opaque. +const OPAQUE_AFTER: Duration = Duration::from_secs(2); + +/// Who shows one clip's pictures. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum Phase { + /// The UI draws them: the first, a paused clip's, one whose place moves, one in an isolated + /// layer, one the decoder can't layer. + Drawn, + /// Its place held still for a frame: the decoder presents on the layer at `size`. + Placing { size: (u32, u32) }, + /// The layer at `at` shows them under the UI, which punches their place out. + Layered { size: (u32, u32), at: (i32, i32) }, +} + +/// What one frame saw of a clip. +#[derive(Clone, Copy, Debug)] +pub(super) struct Seen { + /// Its place is the last frame's. + pub still: bool, + /// It could go on a layer: playing, layerable, drawn in the window's own pass, and the + /// window composites a layer (premultiplied, handed over, the punch compiled). + pub ready: bool, + /// The decoder presented a picture on the layer at the asked size. + pub showing: bool, + pub size: (u32, u32), + pub at: (i32, i32), +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum Effect { + /// The decoder presents on the layer at this size, or (None) leaves the pictures to the UI. + Ask(Option<(u32, u32)>), + /// Move the layer's visual to `at`, commit, and wait for DWM to take it. + Show { at: (i32, i32) }, + /// Punch the clip's place out this frame. + Punch, +} + +pub(super) fn step(phase: &mut Phase, seen: Seen) -> Effect { + match *phase { + Phase::Drawn if seen.still && seen.ready => { + *phase = Phase::Placing { size: seen.size }; + Effect::Ask(Some(seen.size)) + } + Phase::Drawn => Effect::Ask(None), + Phase::Placing { size } if !seen.still || !seen.ready || seen.size != size => { + *phase = Phase::Drawn; + Effect::Ask(None) + } + Phase::Placing { size } if seen.showing => { + *phase = Phase::Layered { size, at: seen.at }; + Effect::Show { at: seen.at } + } + Phase::Placing { size } => Effect::Ask(Some(size)), + Phase::Layered { size, at } if seen.still && seen.ready && seen.showing && seen.size == size && seen.at == at => Effect::Punch, + Phase::Layered { .. } => { + *phase = Phase::Drawn; + Effect::Ask(None) + } + } +} + +/// The place a clip's frame was drawn at; equal two frames running means it held still. +#[derive(Clone, Copy, Debug, PartialEq)] +struct Place { + image: [f32; 4], + node: [f32; 4], + radii: [f32; 4], + clip: [f32; 4], + fade: [u32; 4], + opacity: f32, +} + +struct Entry { + key: usize, + video: Arc<crate::video::Shared>, + phase: Phase, + last: Option<Place>, + /// The last frame drew it inside an isolated layer, where a punch can't reach the window. + isolated: bool, + /// Its layer's visual, and the decoder's surface handle it shows: a decoder opened again (a + /// replaced GPU device) makes a new layer with a new handle. + visual: Option<(IDCompositionVisual, usize)>, + /// What `RUNE_VIDEO_LOG` last printed about it. + logged: Option<(bool, bool, bool, bool, bool, bool, bool, bool)>, +} + +/// What a frame does about the window's layers. +#[derive(Default)] +pub(in crate::window) struct Frame { + /// The surfaces to punch out (`Renderer::set_punched_surfaces`). + pub punched: Vec<usize>, + /// A clip is on its way to its layer: draw again. + pub again: bool, +} + +#[derive(Default)] +pub(in crate::window) struct VideoLayers { + entries: Vec<Entry>, + /// The UI's swap chain should composite premultiplied (Some(true)) or opaque (Some(false)); + /// `Host::draw` makes it so before its next frame. + pending_alpha: Option<bool>, + /// Since when no clip has wanted a layer. + unused_since: Option<Instant>, + /// The swap chain stays premultiplied whether a clip wants a layer or not: its display may + /// follow an opaque swap chain's presents with its refresh rate (`vrr_guard`). + hold: bool, +} + +impl VideoLayers { + /// Before a frame's surfaces are prepared: steps each drawn clip and carries out its effect. + pub(in crate::window) fn frame(&mut self, draws: &[SurfaceDraw], handover: Option<&Handover>, premultiplied: bool, punch_ready: bool) -> Frame { + let mut out = Frame::default(); + let window_ready = handover.is_some() && premultiplied && punch_ready && enabled(); + let mut wanted = false; + let mut kept = Vec::with_capacity(draws.len()); + for d in draws { + let (Some(video), Some(frame)) = (d.surface.video(), d.surface.latest()) else { continue }; + let key = d.surface.key(); + if kept.contains(&key) { + // Drawn twice in one frame: a layer can be in one place only. + continue; + } + kept.push(key); + let upright = frame.orient.upright(frame.size); + let image = place::image_rect(d.rect, upright, d.fit, d.surface.place()); + let here = Place { image, node: d.rect, radii: d.radii, clip: d.clip, fade: d.fade, opacity: d.opacity }; + let entry = match self.entries.iter().position(|e| e.key == key) { + Some(i) => &mut self.entries[i], + None => { + self.entries.push(Entry { key, video, phase: Phase::Drawn, last: None, isolated: false, visual: None, logged: None }); + self.entries.last_mut().unwrap() + } + }; + let size = (image[2].round().max(1.0) as u32, image[3].round().max(1.0) as u32); + let at = (image[0].round() as i32, image[1].round() as i32); + let still = entry.last == Some(here); + entry.last = Some(here); + let ask = match entry.phase { + Phase::Placing { size } | Phase::Layered { size, .. } => Some(size), + Phase::Drawn => None, + }; + let status = crate::video::layer(&entry.video, ask); + let layerable = status.running && !status.refused && !entry.isolated && d.opacity > 0.0; + wanted |= layerable && still && enabled(); + let seen = Seen { still, ready: layerable && window_ready, showing: status.showing, size, at }; + let before = entry.phase; + let effect = step(&mut entry.phase, seen); + if logging() { + let why = (status.running, status.refused, entry.isolated, handover.is_some(), premultiplied, punch_ready, still, status.showing); + if entry.phase != before || entry.logged != Some(why) { + entry.logged = Some(why); + eprintln!( + "rune video layer: {before:?} -> {:?} (running {}, refused {}, isolated {}, handed {}, premultiplied {}, punch {}, still {}, showing {}) at {at:?} size {size:?}", + entry.phase, why.0, why.1, why.2, why.3, why.4, why.5, why.6, why.7 + ); + } + } + match effect { + Effect::Ask(next) => { + if next != ask { + crate::video::layer(&entry.video, next); + } + // Back from the layer: this frame draws the picture for now, not the one + // the surface held when the layer took over. + if matches!(before, Phase::Layered { .. }) { + crate::video::unlayer(&entry.video, &d.surface); + } + out.again |= next.is_some(); + } + Effect::Show { at } => match show(handover, entry, status.handle, at) { + Ok(()) => out.punched.push(key), + Err(e) => { + eprintln!("rune: a clip's layer couldn't show, the window draws it: {e}"); + entry.phase = Phase::Drawn; + crate::video::layer(&entry.video, None); + } + }, + Effect::Punch => out.punched.push(key), + } + } + // Clips no longer drawn leave their layers. + let before = self.entries.len(); + self.entries.retain(|e| { + let drawn = kept.contains(&e.key); + if !drawn { + release(handover, e); + } + drawn + }); + if self.entries.len() != before + && let Some(h) = handover + { + h.commit().ok(); + } + self.follow_alpha(wanted || self.hold, premultiplied, handover.is_some()); + out + } + + /// After a frame was drawn: which clips it drew inside an isolated layer. + pub(in crate::window) fn drawn(&mut self, isolated: impl Fn(usize) -> Option<bool>) { + for e in &mut self.entries { + e.isolated = isolated(e.key).unwrap_or(false); + } + } + + /// The window is covered, minimised or goes: every clip's pictures go back to the UI, which + /// draws them when it next draws, and the decoders stop presenting. + pub(in crate::window) fn release(&mut self, handover: Option<&Handover>) { + for e in self.entries.drain(..) { + release(handover, &e); + } + if let Some(h) = handover { + h.commit().ok(); + } + } + + /// Keeps the swap chain premultiplied (`hold`). + pub(in crate::window) fn hold_premultiplied(&mut self, on: bool) { self.hold = on; } + + /// The alpha the UI's swap chain should switch to before the next frame, once. + pub(in crate::window) fn take_alpha(&mut self) -> Option<bool> { + self.pending_alpha.take() + } + + fn follow_alpha(&mut self, wanted: bool, premultiplied: bool, handed: bool) { + if !handed { + return; + } + let now = crate::time::now(); + if wanted { + self.unused_since = None; + if !premultiplied { + self.pending_alpha = Some(true); + } + return; + } + let since = *self.unused_since.get_or_insert(now); + if premultiplied && now.saturating_duration_since(since) >= OPAQUE_AFTER { + self.pending_alpha = Some(false); + } + } +} + +/// Puts the clip's visual at `at`, made from the layer's surface handle the first time, and waits +/// for DWM to take it, so the frame that punches lands over it. +#[allow(unsafe_code)] +fn show(handover: Option<&Handover>, entry: &mut Entry, handle: Option<usize>, at: (i32, i32)) -> Result<(), String> { + let handover = handover.ok_or("the window isn't on DirectComposition")?; + let handle = handle.ok_or("the layer has no surface yet")?; + if entry.visual.as_ref().is_none_or(|(_, shown)| *shown != handle) { + if let Some((old, _)) = entry.visual.take() { + handover.remove(&old); + } + entry.visual = Some((handover.add_under(handle)?, handle)); + } + let (visual, _) = entry.visual.as_ref().unwrap(); + // SAFETY: COM calls on a visual of the window's DirectComposition device. + unsafe { + visual.SetOffsetX2(at.0 as f32).map_err(|e| format!("SetOffsetX: {e}"))?; + visual.SetOffsetY2(at.1 as f32).map_err(|e| format!("SetOffsetY: {e}"))?; + } + handover.commit_and_wait() +} + +/// `RUNE_VIDEO_LAYER=0` keeps every clip's pictures in the UI, as without layers. +fn enabled() -> bool { + static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("RUNE_VIDEO_LAYER").is_none_or(|v| v != "0")) +} + +/// `RUNE_VIDEO_LOG` set: each clip's way to its layer. +fn logging() -> bool { + static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("RUNE_VIDEO_LOG").is_some_and(|v| v != "0")) +} + +fn release(handover: Option<&Handover>, e: &Entry) { + crate::video::layer(&e.video, None); + if let (Some(h), Some((v, _))) = (handover, &e.visual) { + h.remove(v); + } +} diff --git a/app/vendor/rune/crates/rune/tests/accessibility_macos.rs b/app/vendor/rune/crates/rune/tests/accessibility_macos.rs new file mode 100644 index 0000000..5cf3c50 --- /dev/null +++ b/app/vendor/rune/crates/rune/tests/accessibility_macos.rs @@ -0,0 +1,154 @@ +//! A window's accessibility tree through AppKit itself: asks the content view for its +//! `accessibilityChildren`, as VoiceOver and the Accessibility Inspector do, walks the +//! elements AccessKit answers with (role, label, identifier, value), and presses a button with +//! `accessibilityPerformPress`. Opens a native window, so it only runs with RUNE_GUI_TESTS=1 +//! in a logged-in macOS GUI session. + +#![allow(unsafe_code)] + +#[cfg(not(target_os = "macos"))] +fn main() {} + +#[cfg(target_os = "macos")] +fn main() { mac::main() } + +#[cfg(target_os = "macos")] +mod mac { + use objc2::msg_send; + use objc2::runtime::{AnyObject, Bool}; + use rune::*; + use std::sync::{Mutex, OnceLock, mpsc}; + use std::time::Duration; + + #[derive(Default)] + struct State { presses: u32, name: TextEdit } + + static WINDOW: OnceLock<WindowHandle> = OnceLock::new(); + + fn view(s: &State, _: &mut Cx<State>) -> El { + col().w_full().gap(8.0).padding(12.0) + .child(text("Account").key("title").role("heading").level(1)) + .child(row().key("save").role("button").focusable(true).on_press(|s: &mut State| s.presses += 1).child(text("Save"))) + .child(text_input(&s.name, rune::tok::type_::BODY).key("name").label("Name").single_line().w(200.0).on_edit(|s: &mut State| &mut s.name)) + .child(text(format!("Pressed {} times", s.presses)).key("count")) + } + + /// One AX element as a line, and its children below it. + #[derive(Debug, Clone)] + struct Ax { role: String, label: String, id: String, value: String, children: Vec<Ax> } + + fn string(obj: *mut AnyObject) -> String { + if obj.is_null() { return String::new(); } + // SAFETY: AX getters return NSString or nil; `description` works on any object. + unsafe { + let s: *mut AnyObject = msg_send![obj, description]; + let utf8: *const std::ffi::c_char = msg_send![s, UTF8String]; + if utf8.is_null() { String::new() } else { std::ffi::CStr::from_ptr(utf8).to_string_lossy().into_owned() } + } + } + + fn walk(el: *mut AnyObject, depth: usize, presses: &mut Vec<*mut AnyObject>) -> Ax { + // SAFETY: NSAccessibility getters on AccessKit's elements, on the main thread. + unsafe { + let role: *mut AnyObject = msg_send![el, accessibilityRole]; + let label: *mut AnyObject = msg_send![el, accessibilityLabel]; + let title: *mut AnyObject = msg_send![el, accessibilityTitle]; + let id: *mut AnyObject = msg_send![el, accessibilityIdentifier]; + let value: *mut AnyObject = msg_send![el, accessibilityValue]; + let label = if label.is_null() { string(title) } else { string(label) }; + let id = string(id); + if id == "save" { presses.push(el); } + let mut children = Vec::new(); + if depth < 12 { + let kids: *mut AnyObject = msg_send![el, accessibilityChildren]; + if !kids.is_null() { + let n: usize = msg_send![kids, count]; + for i in 0..n { + let kid: *mut AnyObject = msg_send![kids, objectAtIndex: i]; + children.push(walk(kid, depth + 1, presses)); + } + } + } + Ax { role: string(role), label, id, value: string(value), children } + } + } + + fn view_ptr(window: &WindowHandle) -> *mut AnyObject { + use winit::raw_window_handle::RawWindowHandle; + window.with_raw_handle(|raw| { + let RawWindowHandle::AppKit(handle) = raw.as_raw() else { panic!("not AppKit") }; + handle.ns_view.as_ptr().cast::<AnyObject>() + }).expect("window handle") + } + + fn print(ax: &Ax, indent: usize, out: &mut String) { + out.push_str(&format!("{}{} label={:?} id={:?} value={:?}\n", " ".repeat(indent), ax.role, ax.label, ax.id, ax.value)); + for c in &ax.children { print(c, indent + 1, out); } + } + + fn find<'a>(ax: &'a Ax, id: &str) -> Option<&'a Ax> { + if ax.id == id { return Some(ax); } + ax.children.iter().find_map(|c| find(c, id)) + } + + pub fn main() { + if std::env::var_os("RUNE_GUI_TESTS").is_none() { + println!("accessibility_macos: skipped (set RUNE_GUI_TESTS=1 in a GUI session)"); + return; + } + std::thread::spawn(|| { std::thread::sleep(Duration::from_secs(60)); eprintln!("timeout"); std::process::exit(2) }); + let spec = AppSpec::new("Accessible", (360.0, 240.0), State::default, view); + let (ready_tx, ready_rx) = mpsc::channel(); + let window = &WINDOW; + let app = App::new(spec).args(Vec::new()).keep_running().on_ready(move |w| { window.set(w.clone()).ok(); ready_tx.send(()).ok(); }); + let handle = app.handle(); + let result = std::sync::Arc::new(Mutex::new(None)); + let out = result.clone(); + std::thread::spawn(move || { + let run = std::panic::catch_unwind(|| { + ready_rx.recv_timeout(Duration::from_secs(10)).expect("window ready"); + let read = |press: bool| { + let (tx, rx) = mpsc::channel(); + handle.update(move |_, _| { + let view = view_ptr(window.get().unwrap()); + let mut presses = Vec::new(); + let tree = walk(view, 0, &mut presses); + if press { + // SAFETY: AccessKit's element for the button, on the main thread. + let ok: Bool = unsafe { msg_send![presses[0], accessibilityPerformPress] }; + assert!(ok.as_bool(), "accessibilityPerformPress"); + } + tx.send(tree).ok(); + }); + rx.recv_timeout(Duration::from_secs(5)).expect("tree") + }; + // The first question activates the tree; the answer after a turn holds it. + let _ = read(false); + std::thread::sleep(Duration::from_millis(300)); + let tree = read(false); + let mut dump = String::new(); + print(&tree, 0, &mut dump); + println!("accessibility_macos: tree\n{dump}"); + let save = find(&tree, "save").expect("the button"); + assert_eq!((save.role.as_str(), save.label.as_str()), ("AXButton", "Save"), "{dump}"); + let title = find(&tree, "title").expect("the heading"); + // AccessKit's role for a heading, which VoiceOver reads as "heading". + assert_eq!((title.role.as_str(), title.label.as_str()), ("Heading", "Account"), "{dump}"); + let name = find(&tree, "name").expect("the field"); + assert_eq!((name.role.as_str(), name.label.as_str()), ("AXTextField", "Name"), "{dump}"); + let _ = read(true); + std::thread::sleep(Duration::from_millis(300)); + let (tx, rx) = mpsc::channel(); + handle.update(move |s, _| { tx.send(s.presses).ok(); }); + assert_eq!(rx.recv_timeout(Duration::from_secs(5)).unwrap(), 1, "the press ran on_press"); + let tree = read(false); + assert_eq!(find(&tree, "count").map(|c| c.value.as_str()), Some("Pressed 1 times")); + }); + *out.lock().unwrap() = Some(run.is_ok()); + handle.quit(); + }); + app.run(); + assert_eq!(*result.lock().unwrap(), Some(true), "accessibility_macos failed"); + println!("accessibility_macos: ok"); + } +} diff --git a/app/vendor/rune/crates/rune/tests/accessibility_windows.rs b/app/vendor/rune/crates/rune/tests/accessibility_windows.rs new file mode 100644 index 0000000..e6665e0 --- /dev/null +++ b/app/vendor/rune/crates/rune/tests/accessibility_windows.rs @@ -0,0 +1,127 @@ +//! A window's accessibility tree through UI Automation, as Narrator and automation tools see +//! it: a UIA client on another thread finds the window's elements by AutomationId, reads their +//! names, control types and values, invokes a button and sets a field's value, and checks the +//! app saw both through its own handlers. Opens a native window, so it only runs with +//! RUNE_GUI_TESTS=1 in a desktop session (a locked one works: nothing here needs a frame on +//! screen). + +#![allow(unsafe_code)] + +#[cfg(not(target_os = "windows"))] +fn main() {} + +#[cfg(target_os = "windows")] +fn main() { win::main() } + +#[cfg(target_os = "windows")] +mod win { + use rune::*; + use std::sync::{Mutex, OnceLock, mpsc}; + use std::time::Duration; + use ::windows::Win32::Foundation::HWND; + use ::windows::Win32::System::Com::{CLSCTX_INPROC_SERVER, COINIT_MULTITHREADED, CoCreateInstance, CoInitializeEx}; + use ::windows::Win32::UI::Accessibility::*; + use ::windows::core::BSTR; + + #[derive(Default)] + struct State { presses: u32, name: TextEdit } + + static WINDOW: OnceLock<WindowHandle> = OnceLock::new(); + + fn view(s: &State, _: &mut Cx<State>) -> El { + col().w_full().gap(8.0).padding(12.0) + .child(text("Account").key("title").role("heading").level(1)) + .child(row().key("save").role("button").focusable(true).on_press(|s: &mut State| s.presses += 1).child(text("Save"))) + .child(row().key("close").role("button").label("Close").focusable(true).on_press(|s: &mut State| s.presses += 10) + .child(el().size(12.0, 12.0))) + .child(text_input(&s.name, rune::tok::type_::BODY).key("name").label("Name").single_line().w(200.0).on_edit(|s: &mut State| &mut s.name)) + .child(text(format!("Pressed {} times", s.presses)).key("count")) + } + + struct Found { name: String, id: String, control: i32, element: IUIAutomationElement } + + fn all(uia: &IUIAutomation, hwnd: isize) -> ::windows::core::Result<Vec<Found>> { + // SAFETY: COM calls on interfaces this thread created. + unsafe { + let root = uia.ElementFromHandle(HWND(hwnd as _))?; + let found = root.FindAll(TreeScope_Descendants, &uia.CreateTrueCondition()?)?; + let mut out = Vec::new(); + for i in 0..found.Length()? { + let e = found.GetElement(i)?; + out.push(Found { name: e.CurrentName()?.to_string(), id: e.CurrentAutomationId()?.to_string(), control: e.CurrentControlType()?.0, element: e }); + } + Ok(out) + } + } + + fn wait<T>(what: &str, mut f: impl FnMut() -> Option<T>) -> T { + let start = rune::time::now(); + loop { + if let Some(v) = f() { return v; } + assert!(start.elapsed() < Duration::from_secs(10), "timed out waiting for {what}"); + std::thread::sleep(Duration::from_millis(20)); + } + } + + pub fn main() { + if std::env::var_os("RUNE_GUI_TESTS").is_none() { + println!("accessibility_windows: skipped (set RUNE_GUI_TESTS=1 in a desktop session)"); + return; + } + std::thread::spawn(|| { std::thread::sleep(Duration::from_secs(60)); eprintln!("timeout"); std::process::exit(2) }); + let spec = AppSpec::new("Accessible", (360.0, 240.0), State::default, view); + let (ready_tx, ready_rx) = mpsc::channel(); + let window = &WINDOW; + let app = App::new(spec).args(Vec::new()).keep_running().on_ready(move |w| { window.set(w.clone()).ok(); ready_tx.send(()).ok(); }); + let handle = app.handle(); + let result = std::sync::Arc::new(Mutex::new(None)); + let out = result.clone(); + std::thread::spawn(move || { + let run = std::panic::catch_unwind(|| { + ready_rx.recv_timeout(Duration::from_secs(10)).expect("window ready"); + // The handle reads on the window's thread. + let (tx, rx) = mpsc::channel(); + handle.update(move |_, _| { + tx.send(window.get().unwrap().with_raw_handle(|raw| match raw.as_raw() { + rune::raw_window_handle::RawWindowHandle::Win32(h) => h.hwnd.get(), + _ => panic!("not Win32"), + }).expect("window handle")).ok(); + }); + let hwnd = rx.recv_timeout(Duration::from_secs(5)).expect("hwnd"); + // SAFETY: COM on this worker thread, multithreaded. + let uia: IUIAutomation = unsafe { + CoInitializeEx(None, COINIT_MULTITHREADED).ok().ok(); + CoCreateInstance(&CUIAutomation, None, CLSCTX_INPROC_SERVER).expect("CUIAutomation") + }; + // The first query activates the tree; it fills in within a turn. + let found = wait("the tree", || all(&uia, hwnd).ok().filter(|f| f.iter().any(|e| e.id == "save"))); + for f in &found { println!("accessibility_windows: {:>6} {:?} id={:?}", f.control, f.name, f.id); } + let by = |id: &str| found.iter().find(|f| f.id == id).unwrap_or_else(|| panic!("no element {id}")); + assert_eq!((by("save").control, by("save").name.as_str()), (UIA_ButtonControlTypeId.0, "Save")); + assert_eq!(by("close").name, "Close", "an icon-only button takes its label"); + assert_eq!(by("title").name, "Account"); + assert_eq!((by("name").control, by("name").name.as_str()), (UIA_EditControlTypeId.0, "Name")); + // SAFETY: COM calls on interfaces this thread created. + unsafe { + let invoke: IUIAutomationInvokePattern = by("save").element.GetCurrentPatternAs(UIA_InvokePatternId).expect("Invoke"); + invoke.Invoke().expect("invoke"); + let value: IUIAutomationValuePattern = by("name").element.GetCurrentPatternAs(UIA_ValuePatternId).expect("Value"); + value.SetValue(&BSTR::from("Ada")).expect("set value"); + } + let state = wait("the app to see the press and the value", || { + let (tx, rx) = mpsc::channel(); + handle.update(move |s, _| { tx.send((s.presses, s.name.text.clone())).ok(); }); + rx.recv_timeout(Duration::from_secs(5)).ok().filter(|(p, n)| *p == 1 && n == "Ada") + }); + println!("accessibility_windows: presses {} name {:?}", state.0, state.1); + let count = wait("the label to follow", || all(&uia, hwnd).ok()?.into_iter().find(|f| f.id == "count" && f.name == "Pressed 1 times")); + println!("accessibility_windows: {:?}", count.name); + }); + *out.lock().unwrap() = Some(run.is_ok()); + handle.quit(); + }); + app.run(); + assert_eq!(*result.lock().unwrap(), Some(true), "accessibility_windows failed"); + println!("accessibility_windows: ok"); + } +} diff --git a/app/vendor/rune/crates/rune/tests/alloc.rs b/app/vendor/rune/crates/rune/tests/alloc.rs new file mode 100644 index 0000000..285e7ae --- /dev/null +++ b/app/vendor/rune/crates/rune/tests/alloc.rs @@ -0,0 +1,186 @@ +#![allow(unsafe_code)] +//! Count the whole runtime frame, not only the spring evaluator. No GPU/driver allocations. +use std::alloc::{GlobalAlloc, Layout, System}; +use std::cell::Cell; +use rune::{Cx, El, Env, GrowthSpec, Runtime, ScrollSpec, col, text}; + +struct Counting; +thread_local! { static ALLOCS: Cell<usize> = const { Cell::new(0) }; } +fn bump() { ALLOCS.try_with(|c| c.set(c.get() + 1)).ok(); } +// SAFETY: forwards every allocation call to `System`, only counting allocations on this thread. +unsafe impl GlobalAlloc for Counting { + unsafe fn alloc(&self, l: Layout) -> *mut u8 { + bump(); + // SAFETY: delegates allocation with the caller's layout to `System`. + unsafe { System.alloc(l) } + } + unsafe fn alloc_zeroed(&self, l: Layout) -> *mut u8 { + bump(); + // SAFETY: delegates zeroed allocation with the caller's layout to `System`. + unsafe { System.alloc_zeroed(l) } + } + unsafe fn dealloc(&self, p: *mut u8, l: Layout) { + // SAFETY: delegates deallocation of `p` and `l` to `System`. + unsafe { System.dealloc(p, l) } + } + unsafe fn realloc(&self, p: *mut u8, l: Layout, n: usize) -> *mut u8 { + bump(); + // SAFETY: delegates reallocation of `p`, `l` and `n` to `System`. + unsafe { System.realloc(p, l, n) } + } +} +#[global_allocator] +static A: Counting = Counting; +fn allocs() -> usize { ALLOCS.with(Cell::get) } + +#[test] +fn disabled_trace_hooks_neither_format_nor_allocate() { + struct Unformatted; + impl std::fmt::Display for Unformatted { + fn fmt(&self, _: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { panic!("disabled trace formatted an event") } + } + fn view(_: &(), _: &mut Cx<()>) -> El { rune::el().trace_name("shell") } + let mut rt = Runtime::new((), view, (100.0, 100.0), Env { system_dark: true, scale: 1.0 }); + rt.frame(0.0); + let element = rune::el(); + let before = allocs(); + let _named = element.trace_name("chip:Area").trace_namespace("gpui", "pill"); + assert!(allocs() - before <= 1, "trace labels share the element's cold storage"); + let before = allocs(); + for _ in 0..100 { + rt.update(|_, tx| { + assert!(!tx.tracing()); + tx.trace_event(Unformatted); + tx.trace_channel("phase:recording", "phase", 1.0); + }); + rt.trace_event(Unformatted); + rt.trace_channel("shell.width", "position", 100.0); + } + assert_eq!(allocs() - before, 0); +} + +#[test] +fn static_faded_container_planning_allocates_nothing() { + use rune::{Color, Live, el}; + fn view(offset: &Live<[f32; 2]>, _: &mut Cx<Live<[f32; 2]>>) -> El { + el().size(200.0, 200.0).opacity(0.5) + .child(el().size(100.0, 100.0).fill(Color::WHITE)) + .child(el().size(100.0, 100.0).live_offset(offset).fill(Color::WHITE)) + } + let mut rt = Runtime::new(Live::new([0.0; 2]), view, (200.0, 200.0), Env { system_dark: true, scale: 2.0 }); + rt.frame(0.0); + rt.state.set([1.0; 2]); + rt.frame(0.0); + let before = allocs(); + for i in 0..60 { + // Force presentation without rebuilding the static-opacity ancestor. + rt.state.set([i as f32; 2]); + rt.frame(1.0 / 60.0); + } + assert_eq!(allocs() - before, 0, "static faded ancestor scope planning"); +} + +fn view(body: &String, _: &mut Cx<String>) -> El { + col().w_full().h(400.0).scroll(ScrollSpec { stick_bottom: true }).child( + col().w_full().virtualize(80.0).growth(GrowthSpec::default()).child( + col().key("row").w_full().streaming(true).child(text(body.clone()).key("body").wrap().w_full().reveal(0.18)) + ) + ) +} + +#[test] +fn streaming_presentation_allocates_nothing() { + let mut rt = Runtime::new("hello ".repeat(120), view, (400.0, 400.0), Env::new(true, 2.0)); + rt.frame(0.0); + rt.state.truncate(360); + rt.settle_all(); + rt.frame(0.0); + rt.state.push_str(&"hello ".repeat(60)); + rt.invalidate(); + // Commit/shaping is separately budgeted; warm glyphs and scratch capacity before measuring. + for _ in 0..4 { rt.frame(1.0 / 120.0); } + let before = allocs(); + for _ in 0..30 { assert!(rt.frame(1.0 / 120.0)); } + let count = allocs() - before; + assert_eq!(count, 0, "presentation allocations across 30 streaming frames"); +} + +#[test] +fn live_publication_and_presentation_allocate_nothing() { + use rune::{Color, Live, el}; + type State = (Live<f32>, Live<[f32; 2]>, Live<Color>); + fn view(s: &State, _: &mut Cx<State>) -> El { + el().size(200.0, 200.0).child(el().size(20.0, 20.0) + .live_opacity(&s.0).live_offset(&s.1).live_fill(&s.2)) + } + let state = (Live::new(1.0), Live::new([0.0, 0.0]), Live::new(Color::WHITE)); + let mut rt = Runtime::new(state, view, (200.0, 200.0), Env::new(true, 2.0)); + rt.frame(0.0); + let producer = (rt.state.0.clone(), rt.state.1.clone(), rt.state.2.clone()); + // Includes the very first publication on a new producer thread, not only warmed sets. + std::thread::spawn(move || { + let before = allocs(); + for i in 0..120 { + producer.0.set(0.3 + i as f32 / 240.0); + producer.1.set([i as f32, i as f32]); + producer.2.set(Color { r: i as f32 / 120.0, ..Color::WHITE }); + } + assert_eq!(allocs() - before, 0, "producer allocations"); + }).join().unwrap(); + rt.frame(0.0); + let before = allocs(); + for i in 0..120 { + rt.state.0.set(0.5 + i as f32 / 240.0); + rt.state.1.set([i as f32, i as f32]); + rt.state.2.set(Color { r: i as f32 / 120.0, ..Color::WHITE }); + rt.frame(1.0 / 120.0); + } + assert_eq!(allocs() - before, 0, "live CPU presentation allocations"); +} + +#[test] +fn scroll_edge_fades_allocate_nothing_per_frame() { + use rune::{Color, el}; + fn view(faded: &bool, _: &mut Cx<bool>) -> El { + let rows = (0..40).map(|i| el().key(format!("row{i}")).w_full().h(20.0).fill(Color::WHITE)); + let scroll = col().w_full().h(200.0).scroll(ScrollSpec { stick_bottom: false }).child(col().w_full().children(rows)); + if *faded { scroll.scroll_edge_fade(24.0) } else { scroll } + } + let gliding = |faded| { + let mut rt = Runtime::new(faded, view, (200.0, 300.0), Env::new(true, 2.0)); + rt.frame(0.0); + rt.fling(100.0, 100.0, -1500.0); + for _ in 0..4 { rt.frame(1.0 / 120.0); } + let before = allocs(); + for _ in 0..30 { assert!(rt.frame(1.0 / 120.0), "still gliding"); } + allocs() - before + }; + assert_eq!(gliding(true), gliding(false), "edge fades add no per-frame allocations while scrolling"); +} + +#[test] +fn a_cached_ink_probe_allocates_nothing() { + // Initialize fonts before ink records its cache epoch, and keep other test threads' + // text systems from invalidating that epoch while we measure cache hits. + let _families = rune::text::with_families("Inter", "IBM Plex Mono"); + let style = rune::TextStyle::new(12.0, 400.0); + let first = rune::text::ink("⌘K", style); + assert!(first.is_some()); + let before = allocs(); + for _ in 0..100 { + assert_eq!(rune::text::ink("⌘K", style), first); + } + assert_eq!(allocs() - before, 0); +} + +#[test] +fn text_lend_allocates_nothing() { + let mut text = rune::text::TextSystem::default(); + // Warm thread-local LENT slot initialization once before counting. + rune::text::lend(&mut text, || {}); + let before = allocs(); + for _ in 0..100 { + rune::text::lend(&mut text, || {}); + } + assert_eq!(allocs() - before, 0, "lend must not heap-allocate when swapping placeholder"); +} diff --git a/app/vendor/rune/crates/rune/tests/coretext/.gitignore b/app/vendor/rune/crates/rune/tests/coretext/.gitignore new file mode 100644 index 0000000..daa5618 --- /dev/null +++ b/app/vendor/rune/crates/rune/tests/coretext/.gitignore @@ -0,0 +1,2 @@ +sf/ +mono/ diff --git a/app/vendor/rune/crates/rune/tests/coretext/Inter-Bold-subset.ttf b/app/vendor/rune/crates/rune/tests/coretext/Inter-Bold-subset.ttf new file mode 100644 index 0000000..ccbca2d Binary files /dev/null and b/app/vendor/rune/crates/rune/tests/coretext/Inter-Bold-subset.ttf differ diff --git a/app/vendor/rune/crates/rune/tests/coretext/README.md b/app/vendor/rune/crates/rune/tests/coretext/README.md new file mode 100644 index 0000000..aa31c42 --- /dev/null +++ b/app/vendor/rune/crates/rune/tests/coretext/README.md @@ -0,0 +1,27 @@ +# CoreText references + +Reference sheets for `rune::text::pixel_compare`: what CoreText draws for each case (Rune's +glyphs and pen positions, macOS's default antialiasing and subpixel quantisation, into an +opaque sRGB bitmap), with font smoothing on (`<pair>-<scale>x.png`, compared with +`FontSmoothing::On`) and off (`flat-<pair>-<scale>x.png`, light and dark, compared with +`FontSmoothing::Off`). Each greyscale PNG holds the green channel. `layout.txt` is a digest of +the layout they were drawn from; when Rune's layout of the cases changes, the comparison +refuses to run until the sheets are regenerated. + +`sf/` holds the same for San Francisco, drawn from the Mac's own system font. It is ignored by +git (Apple's font can't be redistributed): regenerate it locally, and its comparisons are +skipped where it is missing. `mono/` is SF Mono (`Family::SystemMono`) at 11–16 pt and a +13.5/22 pt diff paragraph, drawn with AppKit's `NSFont.monospacedSystemFont` (the instance +native apps draw code in), kept the same way. + +- Regenerate (macOS): `scripts/coretext-reference.sh`. Drawn on macOS 15.3 (24D60). +- Compare: `cargo run -p rune --example coretext_compare -- [--set inter|sf|mono] + [--smoothing on|off] [--blend srgb|linear] [--against smoothed|unsmoothed] + [--out DIR]`, or `-- shot SHOT.png --pair light|dark` for a 2× browser screenshot of the + report paragraph. +- Test (macOS): `cargo test -p rune pixel_compare`. + +`Inter-Bold-subset.ttf` is Inter 4.1 Bold (SHA-256 `288316099b1e0a47…`) cut to printable +ASCII, the em dash and curly double quotes with fontTools (`pyftsubset --no-hinting`), under the +SIL Open Font License in `../../assets/Inter-LICENSE.txt`. Inter Regular is Rune's own +`assets/Inter-Regular.ttf`. diff --git a/app/vendor/rune/crates/rune/tests/coretext/blue-1x.png b/app/vendor/rune/crates/rune/tests/coretext/blue-1x.png new file mode 100644 index 0000000..777218f Binary files /dev/null and b/app/vendor/rune/crates/rune/tests/coretext/blue-1x.png differ diff --git a/app/vendor/rune/crates/rune/tests/coretext/blue-2x.png b/app/vendor/rune/crates/rune/tests/coretext/blue-2x.png new file mode 100644 index 0000000..e0e7a95 Binary files /dev/null and b/app/vendor/rune/crates/rune/tests/coretext/blue-2x.png differ diff --git a/app/vendor/rune/crates/rune/tests/coretext/dark-1x.png b/app/vendor/rune/crates/rune/tests/coretext/dark-1x.png new file mode 100644 index 0000000..54d8f5b Binary files /dev/null and b/app/vendor/rune/crates/rune/tests/coretext/dark-1x.png differ diff --git a/app/vendor/rune/crates/rune/tests/coretext/dark-2x.png b/app/vendor/rune/crates/rune/tests/coretext/dark-2x.png new file mode 100644 index 0000000..09330b8 Binary files /dev/null and b/app/vendor/rune/crates/rune/tests/coretext/dark-2x.png differ diff --git a/app/vendor/rune/crates/rune/tests/coretext/flat-dark-1x.png b/app/vendor/rune/crates/rune/tests/coretext/flat-dark-1x.png new file mode 100644 index 0000000..5f49f08 Binary files /dev/null and b/app/vendor/rune/crates/rune/tests/coretext/flat-dark-1x.png differ diff --git a/app/vendor/rune/crates/rune/tests/coretext/flat-dark-2x.png b/app/vendor/rune/crates/rune/tests/coretext/flat-dark-2x.png new file mode 100644 index 0000000..564389c Binary files /dev/null and b/app/vendor/rune/crates/rune/tests/coretext/flat-dark-2x.png differ diff --git a/app/vendor/rune/crates/rune/tests/coretext/flat-light-1x.png b/app/vendor/rune/crates/rune/tests/coretext/flat-light-1x.png new file mode 100644 index 0000000..7698c55 Binary files /dev/null and b/app/vendor/rune/crates/rune/tests/coretext/flat-light-1x.png differ diff --git a/app/vendor/rune/crates/rune/tests/coretext/flat-light-2x.png b/app/vendor/rune/crates/rune/tests/coretext/flat-light-2x.png new file mode 100644 index 0000000..e6a2f67 Binary files /dev/null and b/app/vendor/rune/crates/rune/tests/coretext/flat-light-2x.png differ diff --git a/app/vendor/rune/crates/rune/tests/coretext/layout.txt b/app/vendor/rune/crates/rune/tests/coretext/layout.txt new file mode 100644 index 0000000..4b8fc59 --- /dev/null +++ b/app/vendor/rune/crates/rune/tests/coretext/layout.txt @@ -0,0 +1,2 @@ +1x 82b87e60043ea6e4 +2x 9ea86591f560030a diff --git a/app/vendor/rune/crates/rune/tests/coretext/light-1x.png b/app/vendor/rune/crates/rune/tests/coretext/light-1x.png new file mode 100644 index 0000000..fd95c33 Binary files /dev/null and b/app/vendor/rune/crates/rune/tests/coretext/light-1x.png differ diff --git a/app/vendor/rune/crates/rune/tests/coretext/light-2x.png b/app/vendor/rune/crates/rune/tests/coretext/light-2x.png new file mode 100644 index 0000000..ae97d4b Binary files /dev/null and b/app/vendor/rune/crates/rune/tests/coretext/light-2x.png differ diff --git a/app/vendor/rune/crates/rune/tests/coretext/white-1x.png b/app/vendor/rune/crates/rune/tests/coretext/white-1x.png new file mode 100644 index 0000000..5c8a58b Binary files /dev/null and b/app/vendor/rune/crates/rune/tests/coretext/white-1x.png differ diff --git a/app/vendor/rune/crates/rune/tests/coretext/white-2x.png b/app/vendor/rune/crates/rune/tests/coretext/white-2x.png new file mode 100644 index 0000000..f9f2224 Binary files /dev/null and b/app/vendor/rune/crates/rune/tests/coretext/white-2x.png differ diff --git a/app/vendor/rune/crates/rune/tests/default_menu_macos.rs b/app/vendor/rune/crates/rune/tests/default_menu_macos.rs new file mode 100644 index 0000000..fcb50b6 --- /dev/null +++ b/app/vendor/rune/crates/rune/tests/default_menu_macos.rs @@ -0,0 +1,196 @@ +//! Main-thread AppKit menu assertions, without opening a window or running an event loop. +#[cfg(target_os = "macos")] +#[allow(dead_code)] +#[path = "../src/native_menu/default_macos.rs"] +mod default_macos; +#[cfg(target_os = "macos")] +#[allow(dead_code)] +#[path = "../src/labels.rs"] +mod labels; +#[cfg(target_os = "macos")] +use labels::Label; +#[cfg(target_os = "macos")] +use rune::Direction; +#[cfg(target_os = "macos")] +#[allow(dead_code)] +#[path = "../src/native_menu/standard.rs"] +mod standard; + +#[cfg(not(target_os = "macos"))] +fn main() {} + +#[cfg(target_os = "macos")] +#[allow(unsafe_code)] +fn main() { + use objc2::{MainThreadMarker, sel, rc::Retained}; + use objc2_app_kit::{NSApplication, NSApplicationActivationPolicy, NSEventModifierFlags as Flags, NSMenu, NSMenuItem}; + use objc2_foundation::{NSProcessInfo, NSString}; + let mtm = MainThreadMarker::new().unwrap(); + let app = NSApplication::sharedApplication(mtm); + app.setActivationPolicy(NSApplicationActivationPolicy::Accessory); + // SAFETY: This dedicated main-thread process owns every menu. It never opens a + // window, activates, or dispatches any menu selector. + unsafe { + app.setMainMenu(None); + let root = default_macos::ensure(&app); + let menu = root.itemAtIndex(0).unwrap().submenu().unwrap(); + let name = NSProcessInfo::processInfo().processName().to_string(); + let titles: Vec<_> = (0..menu.numberOfItems()).map(|i| menu.itemAtIndex(i).unwrap().title().to_string()).collect(); + assert_eq!(titles, [format!("About {name}"), "".into(), "Services".into(), format!("Hide {name}"), + "Hide Others".into(), "Show All".into(), "".into(), format!("Quit {name}")]); + let command = Flags::Command; + for (index, selector, key, modifiers) in [ + (0, sel!(orderFrontStandardAboutPanel:), "", command), + (3, sel!(hide:), "h", command), + (4, sel!(hideOtherApplications:), "h", command | Flags::Option), + (5, sel!(unhideAllApplications:), "", command), + (7, sel!(terminate:), "q", command), + ] { + let item = menu.itemAtIndex(index).unwrap(); + assert_eq!(item.action(), Some(selector)); + assert_eq!(item.keyEquivalent().to_string(), key); + assert_eq!(item.keyEquivalentModifierMask(), modifiers); + } + let services = app.servicesMenu().unwrap(); + assert!(std::ptr::eq(&*services, &*menu.itemAtIndex(2).unwrap().submenu().unwrap())); + assert_eq!(root.numberOfItems(), 1, "no Edit menu intercepts Rune text commands"); + assert_eq!(app.activationPolicy(), NSApplicationActivationPolicy::Accessory); + + // Repeated promotion preserves the root and any custom items added after it. + let custom = NSMenuItem::new(mtm); + custom.setTitle(&NSString::from_str("Custom action")); + menu.insertItem_atIndex(&custom, 0); + for _ in 0..2 { + let current = default_macos::ensure(&app); + assert!(std::ptr::eq(&*current, &*root)); + assert_eq!(menu.numberOfItems(), 9); + assert!(std::ptr::eq(&*menu.itemAtIndex(0).unwrap(), &*custom)); + } + // An app's preexisting menu always wins, including an intentionally empty one. + let supplied: Retained<NSMenu> = NSMenu::new(mtm); + app.setMainMenu(Some(&supplied)); + assert!(std::ptr::eq(&*default_macos::ensure(&app), &*supplied)); + assert_eq!(supplied.numberOfItems(), 0); + let top = NSMenuItem::new(mtm); + top.setTitle(&NSString::from_str("App-owned menu")); + supplied.addItem(&top); + assert!(std::ptr::eq(&*default_macos::ensure(&app), &*supplied)); + assert_eq!(supplied.numberOfItems(), 1); + assert!(std::ptr::eq(&*app.servicesMenu().unwrap(), &*services)); + assert!(!default_macos::is_winit_default(&app), "an app-owned menu bar gets no standard items"); + + // A regular app's default menu bar takes the standard Edit and Window items. + app.setMainMenu(None); + let root = default_macos::ensure(&app); + assert!(default_macos::is_winit_default(&app)); + default_macos::add_standard(&app); + let s = |t: &str| t.to_owned(); + let tops = |root: &NSMenu| (0..root.numberOfItems()).map(|i| root.itemAtIndex(i).unwrap().title().to_string()).collect::<Vec<_>>(); + let plan = |menu: &NSMenu| (0..menu.numberOfItems()).map(|i| { + let item = menu.itemAtIndex(i).unwrap(); + if item.isSeparatorItem() { return (s("-"), None, s(""), command, true); } + (item.title().to_string(), item.action().map(|a| a.name().to_string_lossy().into_owned()), item.keyEquivalent().to_string(), + item.keyEquivalentModifierMask(), item.target().is_none()) + }).collect::<Vec<_>>(); + assert_eq!(&tops(&root)[1..], ["Edit", "Window"]); + let shift = command | Flags::Shift; + assert_eq!(plan(&root.itemAtIndex(1).unwrap().submenu().unwrap()), [ + (s("Undo"), Some(s("undo:")), s("z"), command, true), + (s("Redo"), Some(s("redo:")), s("z"), shift, true), + (s("-"), None, s(""), command, true), + (s("Cut"), Some(s("cut:")), s("x"), command, true), + (s("Copy"), Some(s("copy:")), s("c"), command, true), + (s("Paste"), Some(s("paste:")), s("v"), command, true), + (s("Select All"), Some(s("selectAll:")), s("a"), command, true), + ]); + assert_eq!(plan(&root.itemAtIndex(2).unwrap().submenu().unwrap()), [ + (s("Minimize"), Some(s("performMiniaturize:")), s("m"), command, true), + (s("Close"), Some(s("performClose:")), s("w"), command, true), + ]); + assert_eq!(root.itemAtIndex(0).unwrap().submenu().unwrap().numberOfItems(), 8, "the app menu is untouched"); + default_macos::add_standard(&app); + assert_eq!(tops(&root).len(), 3, "adding twice changes nothing"); + assert_eq!(root.itemAtIndex(2).unwrap().submenu().unwrap().numberOfItems(), 2); + + // An app's custom menus take the Mac order around the standard ones, and an item of + // its own with a standard equivalent takes it from the standard item, set before or after. + let key_of = |root: &NSMenu, menu: &str, title: &str| { + let menu = (0..root.numberOfItems()).filter_map(|i| root.itemAtIndex(i)).find(|i| i.title().to_string() == menu).unwrap().submenu().unwrap(); + (0..menu.numberOfItems()).filter_map(|i| menu.itemAtIndex(i)).find(|i| i.title().to_string() == title).unwrap().keyEquivalent().to_string() + }; + let (file_top, file) = default_macos::add_top(mtm, &root, "File"); + let (view_top, _) = default_macos::add_top(mtm, &root, "View"); + let (help_top, _) = default_macos::add_top(mtm, &root, "Help"); + assert_eq!(&tops(&root)[1..], ["File", "Edit", "View", "Window", "Help"]); + let close_tab = NSMenuItem::initWithTitle_action_keyEquivalent(mtm.alloc(), &NSString::from_str("Close Tab"), + Some(sel!(runeMenuAction:)), &NSString::from_str("w")); + default_macos::adding(&app, || file.addItem(&close_tab)); + assert_eq!(close_tab.keyEquivalent().to_string(), "w", "AppKit keeps the custom item's ⌘W"); + assert_eq!(key_of(&root, "Window", "Close"), "", "Close Tab ⌘W wins"); + assert_eq!(key_of(&root, "Window", "Minimize"), "m"); + let paste_plain = NSMenuItem::initWithTitle_action_keyEquivalent(mtm.alloc(), &NSString::from_str("Paste Plain"), + Some(sel!(runeMenuAction:)), &NSString::from_str("V")); + paste_plain.setKeyEquivalentModifierMask(command | Flags::Option); + default_macos::adding(&app, || file.addItem(&paste_plain)); + assert_eq!(key_of(&root, "Edit", "Paste"), "v", "⌥⇧⌘V isn't ⌘V"); + file.removeItem(&close_tab); + file.removeItem(&paste_plain); + for top in [&file_top, &view_top, &help_top] { default_macos::remove_top_if_empty(&root, top); } + default_macos::sync_standard(&app); + assert_eq!(&tops(&root)[1..], ["Edit", "Window"]); + assert_eq!(key_of(&root, "Window", "Close"), "w", "Close gets ⌘W back"); + // Set before the standard items: the custom item still wins, and its menu, shared + // with them, outlives it. + app.setMainMenu(None); + let root = default_macos::ensure(&app); + let (window_top, window) = default_macos::add_top(mtm, &root, "Window"); + let close_all = NSMenuItem::initWithTitle_action_keyEquivalent(mtm.alloc(), &NSString::from_str("Close All"), + Some(sel!(runeMenuAction:)), &NSString::from_str("w")); + default_macos::adding(&app, || window.addItem(&close_all)); + default_macos::add_standard(&app); + assert_eq!(&tops(&root)[1..], ["Edit", "Window"]); + assert_eq!(close_all.keyEquivalent().to_string(), "w"); + assert_eq!(key_of(&root, "Window", "Close"), ""); + window.removeItem(&close_all); + default_macos::remove_top_if_empty(&root, &window_top); + default_macos::sync_standard(&app); + assert_eq!(&tops(&root)[1..], ["Edit", "Window"], "the shared menu stays for the standard items"); + assert_eq!(plan(&window).into_iter().map(|e| (e.0, e.2)).collect::<Vec<_>>(), [(s("Minimize"), s("m")), (s("Close"), s("w"))]); + + // An app's own Edit menu keeps its items; only missing actions join it. + app.setMainMenu(None); + let supplied: Retained<NSMenu> = NSMenu::new(mtm); + let edit_top = NSMenuItem::new(mtm); + edit_top.setTitle(&NSString::from_str("Edit")); + let edit = NSMenu::new(mtm); + let own_copy = NSMenuItem::initWithTitle_action_keyEquivalent(mtm.alloc(), &NSString::from_str("Copy Link"), Some(sel!(copy:)), &NSString::from_str("c")); + edit.addItem(&own_copy); + edit_top.setSubmenu(Some(&edit)); + supplied.addItem(&edit_top); + app.setMainMenu(Some(&supplied)); + default_macos::add_standard(&app); + assert_eq!(tops(&supplied), ["Edit", "Window"]); + let edit_titles: Vec<_> = plan(&edit).into_iter().map(|e| e.0).collect(); + assert_eq!(edit_titles, ["Copy Link", "Undo", "Redo", "-", "Cut", "Paste", "Select All"]); + + // An accessory app's standard items wait without Quit until its Dock icon shows. + app.setMainMenu(None); + default_macos::add_standard(&app); + let root = app.mainMenu().unwrap(); + let app_menu = root.itemAtIndex(0).unwrap().submenu().unwrap(); + assert_eq!(app_menu.numberOfItems(), 0, "no Quit or terminate: for an accessory app"); + assert!(!default_macos::is_winit_default(&app)); + let terminate = |root: &NSMenu| (0..root.numberOfItems()).filter_map(|i| root.itemAtIndex(i).unwrap().submenu()) + .any(|m| (0..m.numberOfItems()).any(|i| m.itemAtIndex(i).unwrap().action() == Some(sel!(terminate:)))); + assert!(!terminate(&root)); + for _ in 0..2 { + default_macos::promote(&app); + assert!(std::ptr::eq(&*app.mainMenu().unwrap(), &*root)); + assert_eq!(app_menu.numberOfItems(), 8, "showing the Dock icon adds winit's app menu, once"); + } + assert!(terminate(&root)); + assert_eq!(app.activationPolicy(), NSApplicationActivationPolicy::Accessory); + app.setMainMenu(None); + } + println!("PASS: default titles/selectors/keys, Services, idempotence, custom and empty menus preserved; standard Edit/Window items, nil targets, Mac menu order, custom equivalents win, shared menus kept, no Quit until promoted"); +} diff --git a/app/vendor/rune/crates/rune/tests/extra_args.rs b/app/vendor/rune/crates/rune/tests/extra_args.rs new file mode 100644 index 0000000..def4221 --- /dev/null +++ b/app/vendor/rune/crates/rune/tests/extra_args.rs @@ -0,0 +1,23 @@ +//! `rune::extra_args()` is ready before any `App` or window exists. + +const CHILD: &str = "RUNE_EXTRA_ARGS_CHILD"; + +/// Runs in a child process with Rune and app flags after libtest's own: nothing has parsed +/// the arguments yet when it asks for its extras. +#[test] +fn child_reads_extras_before_run() { + if std::env::var_os(CHILD).is_none() { return; } + let extra = rune::extra_args(); + assert!(extra.ends_with(&["--doc".to_string(), "a.txt".to_string()]), "{extra:?}"); + assert!(!extra.iter().any(|a| a == "--scale" || a == "2"), "Rune's own flags are not extras: {extra:?}"); +} + +#[test] +fn extra_args_are_ready_before_any_window() { + let status = std::process::Command::new(std::env::current_exe().unwrap()) + .args(["child_reads_extras_before_run", "--exact", "--", "--scale", "2", "--doc", "a.txt"]) + .env(CHILD, "1") + .status() + .unwrap(); + assert!(status.success(), "the child read its extras before run"); +} diff --git a/app/vendor/rune/crates/rune/tests/fixtures/quadrants-rot90.mp4 b/app/vendor/rune/crates/rune/tests/fixtures/quadrants-rot90.mp4 new file mode 100644 index 0000000..5506e36 Binary files /dev/null and b/app/vendor/rune/crates/rune/tests/fixtures/quadrants-rot90.mp4 differ diff --git a/app/vendor/rune/crates/rune/tests/fixtures/rgbw.mp4 b/app/vendor/rune/crates/rune/tests/fixtures/rgbw.mp4 new file mode 100644 index 0000000..88c8b20 Binary files /dev/null and b/app/vendor/rune/crates/rune/tests/fixtures/rgbw.mp4 differ diff --git a/app/vendor/rune/crates/rune/tests/fixtures/silence.m4a b/app/vendor/rune/crates/rune/tests/fixtures/silence.m4a new file mode 100644 index 0000000..0c8bf80 Binary files /dev/null and b/app/vendor/rune/crates/rune/tests/fixtures/silence.m4a differ diff --git a/app/vendor/rune/crates/rune/tests/fixtures/silence.wav b/app/vendor/rune/crates/rune/tests/fixtures/silence.wav new file mode 100644 index 0000000..0110084 Binary files /dev/null and b/app/vendor/rune/crates/rune/tests/fixtures/silence.wav differ diff --git a/app/vendor/rune/crates/rune/tests/fixtures/sine-opus.ogg b/app/vendor/rune/crates/rune/tests/fixtures/sine-opus.ogg new file mode 100644 index 0000000..cfaf34f Binary files /dev/null and b/app/vendor/rune/crates/rune/tests/fixtures/sine-opus.ogg differ diff --git a/app/vendor/rune/crates/rune/tests/fixtures/sine-opus.webm b/app/vendor/rune/crates/rune/tests/fixtures/sine-opus.webm new file mode 100644 index 0000000..e0b9364 Binary files /dev/null and b/app/vendor/rune/crates/rune/tests/fixtures/sine-opus.webm differ diff --git a/app/vendor/rune/crates/rune/tests/fixtures/sine-vorbis.ogg b/app/vendor/rune/crates/rune/tests/fixtures/sine-vorbis.ogg new file mode 100644 index 0000000..673d0fd Binary files /dev/null and b/app/vendor/rune/crates/rune/tests/fixtures/sine-vorbis.ogg differ diff --git a/app/vendor/rune/crates/rune/tests/help_macos.rs b/app/vendor/rune/crates/rune/tests/help_macos.rs new file mode 100644 index 0000000..3d06eab --- /dev/null +++ b/app/vendor/rune/crates/rune/tests/help_macos.rs @@ -0,0 +1,167 @@ +//! In a macOS window, `El::help` is AppKit's own tooltip: the pointer resting on the element +//! shows a system tooltip window, Rune still sees the hover, and a press hides the tooltip. +//! Mouse events are synthetic NSEvents on the app's own queue. Opens a window, so it only runs +//! with RUNE_GUI_TESTS=1 in a logged-in GUI session. With RUNE_HELP_HOLD=<seconds> it keeps the +//! tooltip up that long after printing `TOOLTIP`, for an outside screenshot. + +#![allow(unsafe_code)] + +#[cfg(not(target_os = "macos"))] +fn main() {} + +#[cfg(target_os = "macos")] +fn main() { mac::main() } + +#[cfg(target_os = "macos")] +mod mac { + use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; + use std::sync::mpsc; + use std::time::Duration; + + use objc2::{class, msg_send, runtime::AnyObject}; + use objc2_foundation::{NSPoint, NSRect}; + use rune::*; + + static HOVERED: AtomicBool = AtomicBool::new(false); + static PRESSES: AtomicUsize = AtomicUsize::new(0); + + const ICON: (f64, f64) = (54.0, 54.0); + + #[repr(C)] + struct CGPoint { x: f64, y: f64 } + + #[link(name = "CoreGraphics", kind = "framework")] + unsafe extern "C" { + fn CGWarpMouseCursorPosition(point: CGPoint) -> i32; + } + + fn view(_: &(), _: &mut Cx<()>) -> El { + el().fill(Color::WHITE) + .child(el().key("copy").size(28.0, 28.0).pin(Some(40.0), Some(40.0), None, None) + .fill(oklch(0.45, 0.02, 260.0)).radius(6.0) + .help("Copy command") + .on_hover_change(|_: &mut (), on, _| HOVERED.store(on, Ordering::SeqCst)) + .on_press(|_: &mut ()| { PRESSES.fetch_add(1, Ordering::SeqCst); })) + } + + fn wait(limit: Duration, f: impl Fn() -> bool) -> bool { + let start = rune::time::now(); + while !f() { + if start.elapsed() > limit { return false; } + std::thread::sleep(Duration::from_millis(10)); + } + true + } + + fn on_main<T: Send + 'static>(handle: &AppHandle<()>, f: impl FnOnce() -> T + Send + 'static) -> T { + let (tx, rx) = mpsc::channel(); + handle.update(move |_, _| { tx.send(f()).ok(); }); + rx.recv_timeout(Duration::from_secs(5)).expect("an update runs on the main thread") + } + + /// Posts a mouse event of `kind` at view point (x, y) (top-left origin) on the app's queue. + fn mouse(handle: &AppHandle<()>, kind: usize, (x, y): (f64, f64)) { + on_main(handle, move || { + // SAFETY: main thread (an update); the app's only window. postEvent:atStart: retains + // the autoreleased event. + unsafe { + let app: *mut AnyObject = msg_send![class!(NSApplication), sharedApplication]; + let windows: *mut AnyObject = msg_send![app, windows]; + let window: *mut AnyObject = msg_send![windows, firstObject]; + let view: *mut AnyObject = msg_send![window, contentView]; + let at: NSPoint = msg_send![view, convertPoint: NSPoint::new(x, y), toView: std::ptr::null::<AnyObject>()]; + if kind == 5 { + // AppKit's tooltip timer follows the real cursor, so move it there too. + let s: NSPoint = msg_send![window, convertPointToScreen: at]; + let screen: *mut AnyObject = msg_send![window, screen]; + let frame: NSRect = msg_send![screen, frame]; + CGWarpMouseCursorPosition(CGPoint { x: s.x, y: frame.size.height - s.y }); + } + let number: isize = msg_send![window, windowNumber]; + let info: *mut AnyObject = msg_send![class!(NSProcessInfo), processInfo]; + let now: f64 = msg_send![info, systemUptime]; + let event: *mut AnyObject = msg_send![class!(NSEvent), mouseEventWithType: kind, location: at, + modifierFlags: 0usize, timestamp: now, windowNumber: number, context: std::ptr::null::<AnyObject>(), + eventNumber: 0isize, clickCount: 1isize, pressure: if kind == 1 { 1.0f32 } else { 0.0f32 }]; + assert!(!event.is_null()); + let _: () = msg_send![app, postEvent: event, atStart: false]; + } + }); + } + + /// The screen frame of a visible AppKit tooltip window, if one shows. + fn tooltip(handle: &AppHandle<()>) -> Option<[f64; 4]> { + on_main(handle, || { + // SAFETY: main thread; read-only queries on the app's windows. + unsafe { + let app: *mut AnyObject = msg_send![class!(NSApplication), sharedApplication]; + let windows: *mut AnyObject = msg_send![app, windows]; + let count: usize = msg_send![windows, count]; + for i in 0..count { + let w: *mut AnyObject = msg_send![windows, objectAtIndex: i]; + let name = (*w).class().name().to_string_lossy(); + let visible: bool = msg_send![w, isVisible]; + if visible && name.contains("ToolTip") { + let f: NSRect = msg_send![w, frame]; + return Some([f.origin.x, f.origin.y, f.size.width, f.size.height]); + } + } + None + } + }) + } + + fn rest_on_icon(handle: &AppHandle<()>) { + for k in (0..=6).rev() { + mouse(handle, 5, (ICON.0 - 4.0 * k as f64, ICON.1 + 3.0 * k as f64)); + std::thread::sleep(Duration::from_millis(16)); + } + } + + pub fn main() { + if std::env::var_os("RUNE_GUI_TESTS").is_none() { + println!("help_macos: skipped (set RUNE_GUI_TESTS=1 in a GUI session)"); + return; + } + std::thread::spawn(|| { std::thread::sleep(Duration::from_secs(120)); eprintln!("timeout"); std::process::exit(2) }); + let hold = rune::env::var("RUNE_HELP_HOLD").and_then(|s| s.parse::<f64>().ok()).unwrap_or(0.0); + let (ready_tx, ready_rx) = mpsc::channel(); + let app = App::new(AppSpec::new("help", (320.0, 160.0), || (), view)).args(Vec::new()).on_ready(move |_| { ready_tx.send(()).ok(); }); + let handle = app.handle(); + let worker = std::thread::spawn(move || { + let run = std::panic::catch_unwind(|| { + ready_rx.recv_timeout(Duration::from_secs(60)).expect("window ready"); + on_main(&handle, || { + // SAFETY: runs on the AppKit main thread (`on_main`) to activate and position the test window. + unsafe { + let app: *mut AnyObject = msg_send![class!(NSApplication), sharedApplication]; + let _: () = msg_send![app, activateIgnoringOtherApps: true]; + // Lower left, clear of anything centred on screen. + let windows: *mut AnyObject = msg_send![app, windows]; + let window: *mut AnyObject = msg_send![windows, firstObject]; + let _: () = msg_send![window, setFrameTopLeftPoint: NSPoint::new(40.0, 400.0)]; + let _: () = msg_send![window, makeKeyAndOrderFront: std::ptr::null::<AnyObject>()]; + } + }); + std::thread::sleep(Duration::from_millis(500)); + assert!(tooltip(&handle).is_none(), "no tooltip before the pointer arrives"); + + rest_on_icon(&handle); + assert!(wait(Duration::from_secs(2), || HOVERED.load(Ordering::SeqCst)), "Rune sees the hover under the tooltip rect"); + assert!(wait(Duration::from_secs(5), || tooltip(&handle).is_some()), "AppKit shows the tooltip"); + println!("TOOLTIP {:?}", tooltip(&handle).unwrap()); + if hold > 0.0 { std::thread::sleep(Duration::from_secs_f64(hold)); } + + mouse(&handle, 1, ICON); + mouse(&handle, 2, ICON); + assert!(wait(Duration::from_secs(2), || PRESSES.load(Ordering::SeqCst) == 1), "the press reaches the element"); + assert!(wait(Duration::from_secs(2), || tooltip(&handle).is_none()), "a press hides the tooltip"); + }); + handle.quit(); + run.is_ok() + }); + app.run(); + assert!(worker.join().unwrap(), "help_macos failed"); + println!("help_macos: ok"); + } +} diff --git a/app/vendor/rune/crates/rune/tests/integration/absolute_frac.rs b/app/vendor/rune/crates/rune/tests/integration/absolute_frac.rs new file mode 100644 index 0000000..255efab --- /dev/null +++ b/app/vendor/rune/crates/rune/tests/integration/absolute_frac.rs @@ -0,0 +1,49 @@ +//! `w_frac` on an absolute child resolves against its own parent's padding box: not a padded +//! ancestor's (which made it 12 pt too wide under a 6 pt padded grandparent), not the parent's +//! content box, and with no scrollbar gutter in a scroll viewport. +use rune::runtime::ElementInfo; +use rune::{Color, Cx, El, Env, Runtime, ScrollSpec, col, el, row}; + +struct S; + +fn bar(key: &str) -> El { + el().key(key).absolute(0.0, 0.0).w_frac(1.0).h(4.0) +} + +fn view(_: &S, _: &mut Cx<S>) -> El { + col().w_full().h_full().padding(6.0).gap(10.0) + // Rooms' case: a padded card inside a padded column; the bar spans the card. + .child(col().key("card").w_full().h(60.0).padding(6.0).border(1.0, Color::BLACK).child(bar("card-bar"))) + // Half and full widths in a row cell with its own padding. + .child(row().w_full().h(40.0).child( + col().key("cell").w(200.0).h_full().px(12.0) + .child(bar("cell-bar")) + .child(el().key("cell-half").absolute(0.0, 10.0).w_frac(0.5).h(4.0)), + )) + // Inside a padded scroll viewport's content: no gutter, no viewport padding added. + .child(col().key("scroll").w(240.0).h(100.0).padding(6.0).scroll(ScrollSpec { stick_bottom: false }) + .child(col().key("content").w_full().h(300.0).child(bar("content-bar")))) +} + +fn rect(rt: &Runtime<S>, key: &str) -> [f32; 4] { + let e: ElementInfo = rt.elements().into_iter().find(|e| e.key.as_deref() == Some(key)).unwrap_or_else(|| panic!("{key}")); + e.rect +} + +#[test] +fn absolute_fractions_span_the_parents_padding_box() { + let mut rt = Runtime::new(S, view, (400.0, 400.0), Env::new(true, 2.0)); + rt.frame(0.0); + let card = rect(&rt, "card"); + assert_eq!(card[2], 388.0); + assert_eq!(rect(&rt, "card-bar"), [card[0], card[1], card[2], 4.0], "the card's padding box (its border paints inside)"); + + let cell = rect(&rt, "cell"); + assert_eq!(rect(&rt, "cell-bar"), [cell[0], cell[1], 200.0, 4.0], "padding box, not the 176 pt content box"); + assert_eq!(rect(&rt, "cell-half"), [cell[0], cell[1] + 10.0, 100.0, 4.0]); + + let (scroll, content) = (rect(&rt, "scroll"), rect(&rt, "content")); + assert_eq!(content[2], 228.0, "content fills the viewport inside its padding, with no gutter"); + assert_eq!(rect(&rt, "content-bar"), [content[0], content[1], 228.0, 4.0]); + assert_eq!(content[0], scroll[0] + 6.0); +} diff --git a/app/vendor/rune/crates/rune/tests/integration/absolute_in_rows.rs b/app/vendor/rune/crates/rune/tests/integration/absolute_in_rows.rs new file mode 100644 index 0000000..a443cb7 --- /dev/null +++ b/app/vendor/rune/crates/rune/tests/integration/absolute_in_rows.rs @@ -0,0 +1,54 @@ +//! Absolute children size and pin against their parent's padding box, wherever the parent sits: +//! plain columns, growth stacks and virtual lists inside a scroll viewport. Root overlays +//! (scrims, anchored popovers) keep sizing against the window. +use rune::{Align, Cx, El, Env, GrowthSpec, Runtime, ScrollSpec, Side, col, el, row, text}; + +fn view(case: &u8, _: &mut Cx<u8>) -> El { + let r = |i: usize| { + row().key(format!("row{i}")).w_full().h(40.0).padding(4.0) + .child(text("hello")) + .child(el().key(format!("cover{i}")).pin(Some(0.0), Some(0.0), Some(0.0), Some(0.0))) + .child(el().key(format!("full{i}")).absolute(0.0, 0.0).w_full().h_full()) + .child(el().key(format!("half{i}")).absolute(10.0, 2.0).w_frac(0.5).h(4.0)) + .child(el().key(format!("badge{i}")).pin(None, None, Some(6.0), Some(5.0)).size(10.0, 10.0)) + .child(row().key(format!("nest{i}")).absolute(0.0, 0.0).w(100.0).h(20.0) + .child(el().key(format!("inner{i}")).pin(Some(0.0), None, Some(0.0), None).h(2.0))) + }; + let mut stack = col().key("stack").w_full(); + match case { + 0 => {} + 1 => stack = stack.growth(GrowthSpec::default()), + _ => stack = stack.growth(GrowthSpec::default()).virtualize(40.0), + } + for i in 0..3 { stack = stack.child(r(i)); } + col().w_full().h_full().padding(20.0) + .child(col().key("scroll").w_full().h(200.0).scroll(ScrollSpec { stick_bottom: true }).child(stack)) + .child(el().key("scrim").absolute(0.0, 0.0).w_full().h_full()) + .child(col().key("pop").w_frac(0.25).h(30.0).anchored("row1", Side::Bottom, Align::End, 4.0)) +} + +fn target(rt: &Runtime<u8>, key: &str) -> [f32; 4] { + rt.elements().into_iter().find(|e| e.key.as_deref() == Some(key)).unwrap_or_else(|| panic!("{key}")).target +} + +#[test] +fn absolute_children_of_rows_size_against_the_row() { + for (case, name) in ["column", "growth stack", "virtual list"].into_iter().enumerate() { + let mut rt = Runtime::new(case as u8, view, (400.0, 300.0), Env::new(true, 1.0)); + rt.frame(0.0); + rt.frame(0.5); + for i in 0..3 { + let y = 20.0 + 40.0 * i as f32; + let at = |key: &str| target(&rt, &format!("{key}{i}")); + // The padding box includes the row's padding. + assert_eq!(at("row"), [20.0, y, 360.0, 40.0], "{name}: row{i}"); + assert_eq!(at("cover"), [20.0, y, 360.0, 40.0], "{name}: pinned to all four edges"); + assert_eq!(at("full"), [20.0, y, 360.0, 40.0], "{name}: w_full / h_full"); + assert_eq!(at("half"), [30.0, y + 2.0, 180.0, 4.0], "{name}: w_frac(0.5)"); + assert_eq!(at("badge"), [380.0 - 6.0 - 10.0, y + 40.0 - 5.0 - 10.0, 10.0, 10.0], "{name}: right/bottom pin"); + assert_eq!(at("inner"), [20.0, y, 100.0, 2.0], "{name}: nested absolute"); + } + assert_eq!(target(&rt, "scrim"), [0.0, 0.0, 400.0, 300.0], "{name}: a root scrim still fills the window"); + assert_eq!(target(&rt, "pop"), [380.0 - 100.0, 60.0 + 40.0 + 4.0, 100.0, 30.0], "{name}: anchored popover"); + } +} diff --git a/app/vendor/rune/crates/rune/tests/integration/alignment.rs b/app/vendor/rune/crates/rune/tests/integration/alignment.rs new file mode 100644 index 0000000..ea2249e --- /dev/null +++ b/app/vendor/rune/crates/rune/tests/integration/alignment.rs @@ -0,0 +1,43 @@ +//! Flex alignment builders place children where CSS would. +use rune::{Cx, El, Env, Runtime, col, el, row}; + +fn rect(rt: &Runtime<u8>, key: &str) -> [f32; 4] { + rt.elements().into_iter().find(|e| e.key.as_deref() == Some(key)).unwrap().target +} + +fn view(case: &u8, _: &mut Cx<u8>) -> El { + let kids = || [el().key("a").size(20.0, 10.0), el().key("b").size(20.0, 30.0)]; + let parent = row().key("parent").size(200.0, 60.0); + match case { + 0 => parent.items_end().children(kids()), + 1 => parent.items_center().children(kids()), + 2 => parent.children([el().key("a").size(20.0, 10.0).self_end(), el().key("b").w(20.0).self_stretch()]), + 3 => parent.justify_center().children(kids()), + 4 => parent.justify_around().children(kids()), + 5 => parent.justify_evenly().children(kids()), + 6 => col().key("parent").size(200.0, 60.0).items_end().justify_center().justify_start().children(kids()), + _ => unreachable!(), + } +} + +#[test] +fn alignment_builders_match_css() { + let expect: [(&str, [f32; 2], [f32; 2]); 7] = [ + ("items_end", [0.0, 50.0], [20.0, 30.0]), + ("items_center", [0.0, 25.0], [20.0, 15.0]), + ("self_end / self_stretch", [0.0, 50.0], [20.0, 0.0]), + ("justify_center", [80.0, 0.0], [100.0, 0.0]), + ("justify_around", [40.0, 0.0], [140.0, 0.0]), + ("justify_evenly", [53.333, 0.0], [126.667, 0.0]), + ("column items_end + justify_start", [180.0, 0.0], [180.0, 10.0]), + ]; + for (case, (name, a, b)) in expect.into_iter().enumerate() { + let mut rt = Runtime::new(case as u8, view, (200.0, 60.0), Env::new(true, 1.0)); + rt.frame(0.0); + for (key, at) in [("a", a), ("b", b)] { + let r = rect(&rt, key); + assert!((r[0] - at[0]).abs() < 0.01 && (r[1] - at[1]).abs() < 0.01, "{name}: {key} at {r:?}, want {at:?}"); + } + if case == 2 { assert_eq!(rect(&rt, "b")[3], 60.0, "self_stretch fills the cross axis"); } + } +} diff --git a/app/vendor/rune/crates/rune/tests/integration/app_spec_compat.rs b/app/vendor/rune/crates/rune/tests/integration/app_spec_compat.rs new file mode 100644 index 0000000..6766053 --- /dev/null +++ b/app/vendor/rune/crates/rune/tests/integration/app_spec_compat.rs @@ -0,0 +1,25 @@ +use rune::{App, AppSpec, Chrome, Cx, El, WindowSpec}; + +// Exactly the public field set at 32a1715. Deliberately exhaustive: adding a required field +// must fail compilation here rather than first in a downstream Hex or Rooms checkout. +fn legacy_spec() -> AppSpec<()> { + AppSpec { + title: "Legacy consumer", + size: (640.0, 480.0), + min_size: None, + init: || (), + view: |_: &(), _: &mut Cx<()>| -> El { rune::el() }, + scenes: &[], + fonts: &[], + families: ("Inter", "Inter"), + setup: None, + poll: None, + on_key: None, + } +} + +#[test] +fn legacy_exhaustive_literal_and_chrome_builders_compile() { + let _ = App::new(legacy_spec()).chrome(Chrome::DEFAULT); + let _ = WindowSpec::new("legacy", legacy_spec()).chrome(Chrome::DEFAULT); +} diff --git a/app/vendor/rune/crates/rune/tests/integration/auto_grow.rs b/app/vendor/rune/crates/rune/tests/integration/auto_grow.rs new file mode 100644 index 0000000..8b92ed3 --- /dev/null +++ b/app/vendor/rune/crates/rune/tests/integration/auto_grow.rs @@ -0,0 +1,50 @@ +//! `auto_grow` fits a plain `text_input` to its lines between a minimum and maximum, springs +//! between heights, then scrolls inside with the caret in view. +use rune::runtime::ElementInfo; +use rune::{Cx, El, Env, Ime, Key, KeyEvent, Mods, Runtime, TextEdit, TextStyle, auto_grow, col, text_input}; + +const LINE: f32 = 20.0; + +struct S { draft: TextEdit } + +fn view(s: &S, _: &mut Cx<S>) -> El { + let field = text_input(&s.draft, TextStyle::new(14.0, 400.0).lh(LINE)).key("input").w_full().on_edit(|s: &mut S| &mut s.draft); + col().w_full().h_full().padding(20.0).child(col().key("composer").w_full().child(auto_grow(field, 2, 4))) +} + +fn find(rt: &Runtime<S>, key: &str) -> ElementInfo { + rt.elements().into_iter().find(|e| e.key.as_deref() == Some(key)).unwrap() +} + +fn newline(rt: &mut Runtime<S>, text: &str) { + rt.key(KeyEvent { key: Key::Enter, mods: Mods { shift: true, ..Mods::default() } }); + rt.ime(Ime::Commit(text.into())); + rt.frame(1.0 / 60.0); +} + +fn settle(rt: &mut Runtime<S>) { + for _ in 0..90 { rt.frame(1.0 / 60.0); } +} + +#[test] +fn a_plain_field_fits_its_lines_springs_and_then_scrolls() { + let mut draft = TextEdit::new("one"); + draft.focused = true; + let mut rt = Runtime::new(S { draft }, view, (400.0, 400.0), Env::new(true, 2.0)); + settle(&mut rt); + assert_eq!(find(&rt, "composer").rect[3], 2.0 * LINE, "at least two lines"); + + newline(&mut rt, "two"); + newline(&mut rt, "three"); + let shell = find(&rt, "composer"); + assert_eq!(shell.target[3], 3.0 * LINE, "targets three lines"); + assert!(shell.rect[3] > 2.0 * LINE + 0.5 && shell.rect[3] < 3.0 * LINE - 0.5, "mid-spring: {:?}", shell.rect); + + for n in 4..=7 { newline(&mut rt, &format!("line {n}")); } + settle(&mut rt); + assert_eq!(find(&rt, "composer").rect[3], 4.0 * LINE, "capped at four lines"); + let (viewport, input) = (find(&rt, "scroll"), find(&rt, "input")); + let caret = input.caret.expect("caret"); + assert!(caret[1] >= viewport.rect[1] - 0.01 && caret[1] + caret[3] <= viewport.rect[1] + viewport.rect[3] + 0.01, + "caret {caret:?} inside {:?}", viewport.rect); +} diff --git a/app/vendor/rune/crates/rune/tests/integration/backdrop_blur.rs b/app/vendor/rune/crates/rune/tests/integration/backdrop_blur.rs new file mode 100644 index 0000000..f5b4d58 --- /dev/null +++ b/app/vendor/rune/crates/rune/tests/integration/backdrop_blur.rs @@ -0,0 +1,252 @@ +//! `El::backdrop_blur`: an element blurs what is drawn behind it in the same window, inside its +//! rounded rect and clip, under its fill. +use rune::render::{Gpu, KIND_BACKDROP_BLUR, KIND_LAYER, OFFSCREEN_FORMAT, Offscreen, Renderer}; +use rune::{Color, Cx, El, Env, Runtime, ScrollSpec, col, el, row}; + +const RED: Color = Color { r: 1.0, g: 0.0, b: 0.0, a: 1.0 }; +const BLUE: Color = Color { r: 0.0, g: 0.0, b: 1.0, a: 1.0 }; + +fn pixels<S: 'static>(gpu: &Gpu, rt: &mut Runtime<S>, size: (u32, u32)) -> Vec<u8> { + let mut renderer = Renderer::new(&gpu.device, OFFSCREEN_FORMAT); + let target = Offscreen::new(&gpu.device, size.0, size.1); + renderer.prepare(&gpu.device, &gpu.queue, &mut rt.text.atlas, &rt.instances, size); + let mut encoder = gpu.device.create_command_encoder(&Default::default()); + renderer.draw(&mut encoder, &target.view, [0.0, 0.0, 0.0, 1.0]); + target.copy(&mut encoder); + gpu.queue.submit([encoder.finish()]); + target.read(&gpu.device) +} + +fn at(px: &[u8], width: u32, x: u32, y: u32) -> [u8; 4] { + let i = ((y * width + x) * 4) as usize; + [px[i], px[i + 1], px[i + 2], px[i + 3]] +} + +/// Largest minus smallest red value along row `y` from `x0` to `x1`. +fn spread(px: &[u8], width: u32, y: u32, x0: u32, x1: u32) -> i32 { + let reds: Vec<i32> = (x0..x1).map(|x| at(px, width, x, y)[0] as i32).collect(); + reds.iter().max().unwrap() - reds.iter().min().unwrap() +} + +#[derive(Clone, Copy)] +struct Bar { + rect: [f32; 4], + blur: f32, + fill: Color, + opacity: f32, +} + +const BAR: Bar = Bar { rect: [40.0, 30.0, 120.0, 60.0], blur: 8.0, fill: Color::TRANSPARENT, opacity: 1.0 }; + +#[derive(Clone)] +struct Scene { + bars: Vec<Bar>, + /// Calls `backdrop_blur` with each bar's sigma; false leaves it unset. + blur: bool, +} + +/// 4 pt black and white stripes under each bar. +fn stripes(s: &Scene, _: &mut Cx<Scene>) -> El { + let stripes = row().size(200.0, 120.0).absolute(0.0, 0.0) + .children((0..50).map(|i| el().size(4.0, 120.0).fill(if i % 2 == 0 { Color::BLACK } else { Color::WHITE }))); + el().size(200.0, 120.0).child(stripes).children(s.bars.iter().map(|b| { + let bar = el().absolute(b.rect[0], b.rect[1]).size(b.rect[2], b.rect[3]).radius(16.0).fill(b.fill).opacity(b.opacity) + .child(el().size(10.0, 10.0).fill(Color::WHITE)); + if s.blur { bar.backdrop_blur(b.blur) } else { bar } + })) +} + +fn render(scene: Scene, scale: f32) -> (Runtime<Scene>, Vec<u8>) { + let gpu = Gpu::headless(); + let mut rt = Runtime::new(scene, stripes, (200.0, 120.0), Env::new(false, scale)); + rt.frame(0.0); + let size = ((200.0 * scale) as u32, (120.0 * scale) as u32); + let px = pixels(&gpu, &mut rt, size); + (rt, px) +} + +fn records<S>(rt: &Runtime<S>) -> usize { + rt.instances.iter().filter(|i| i.params[1] == KIND_BACKDROP_BLUR).count() +} + +#[test] +fn stripes_blur_inside_the_rounded_rect_and_nowhere_else() { + let (rt, blurred) = render(Scene { bars: vec![BAR], blur: true }, 1.0); + let (_, plain) = render(Scene { bars: vec![BAR], blur: false }, 1.0); + assert_eq!(records(&rt), 1); + let w = 200; + assert!(spread(&plain, w, 60, 60, 140) > 200, "stripes under a plain bar"); + assert!(spread(&blurred, w, 60, 60, 140) <= 3, "blurred flat inside: {}", spread(&blurred, w, 60, 60, 140)); + // Half black, half white, averaged in linear light and encoded back to sRGB. + let mid = at(&blurred, w, 100, 60)[0] as i32; + assert!((mid - 188).abs() <= 8, "linear mid grey, got {mid}"); + for y in 0..120 { + for x in 0..200 { + let inside = (39..=160).contains(&x) && (29..=90).contains(&y); + if !inside { assert_eq!(at(&blurred, w, x, y), at(&plain, w, x, y), "untouched at {x},{y}"); } + } + } + // Past the rounded corner, inside the rect's bounds. + assert_eq!(at(&blurred, w, 41, 31), at(&plain, w, 41, 31)); + assert_eq!(at(&blurred, w, 158, 88), at(&plain, w, 158, 88)); +} + +#[test] +fn the_fill_tints_over_the_blur() { + let tinted = Bar { fill: RED.alpha(0.5), ..BAR }; + let (_, px) = render(Scene { bars: vec![tinted], blur: true }, 1.0); + let [r, g, b, _] = at(&px, 200, 100, 60); + // Linear: grey 0.5 under red at 0.5 gives (0.75, 0.25, 0.25). + assert!((r as i32 - 225).abs() <= 8 && (g as i32 - 137).abs() <= 8 && (b as i32 - 137).abs() <= 8, "{r} {g} {b}"); +} + +#[test] +fn without_backdrop_blur_the_frame_is_unchanged() { + let off = Bar { blur: 0.0, ..BAR }; + let (rt, zero) = render(Scene { bars: vec![off], blur: true }, 1.0); + let (plain_rt, plain) = render(Scene { bars: vec![off], blur: false }, 1.0); + assert_eq!(records(&rt), 0); + assert_eq!(bytemuck::cast_slice::<_, u8>(&rt.instances), bytemuck::cast_slice::<_, u8>(&plain_rt.instances)); + assert_eq!(zero, plain); +} + +#[test] +fn two_bars_each_blur_their_own_backdrop() { + let left = Bar { rect: [10.0, 30.0, 70.0, 60.0], ..BAR }; + let right = Bar { rect: [120.0, 30.0, 70.0, 60.0], fill: RED.alpha(0.5), ..BAR }; + let (rt, px) = render(Scene { bars: vec![left, right], blur: true }, 1.0); + assert_eq!(records(&rt), 2); + assert!(spread(&px, 200, 60, 25, 65) <= 3); + assert!(spread(&px, 200, 60, 135, 175) <= 3); + assert!(spread(&px, 200, 60, 85, 115) > 200, "stripes between the bars"); + let [r, g, _, _] = at(&px, 200, 155, 60); + assert!(r > g + 60, "the right bar is tinted over its own blur"); +} + +#[test] +fn bars_past_the_cap_draw_only_their_fill() { + let bars = (0..rune::MAX_BACKDROP_BLURS + 1).map(|i| Bar { rect: [i as f32 * 40.0, 30.0, 36.0, 60.0], ..BAR }).collect(); + let (rt, px) = render(Scene { bars, blur: true }, 1.0); + assert_eq!(records(&rt), rune::MAX_BACKDROP_BLURS); + // Near the window edge the clamped taps lean towards the edge stripe. + assert!(spread(&px, 200, 60, 8, 28) <= 12, "the first bar blurs: {}", spread(&px, 200, 60, 8, 28)); + assert!(spread(&px, 200, 60, 168, 188) > 200, "the last bar shows what is under it"); +} + +#[test] +fn a_faded_bar_blurs_the_window_not_its_own_layer() { + let faded = Bar { opacity: 0.5, fill: Color::WHITE.alpha(0.2), ..BAR }; + let (rt, px) = render(Scene { bars: vec![faded], blur: true }, 1.0); + let record = rt.instances.iter().position(|i| i.params[1] == KIND_BACKDROP_BLUR).expect("a record"); + let layer = rt.instances.iter().position(|i| i.params[1] == KIND_LAYER).expect("the faded bar's layer"); + assert!(record < layer, "the record sits ahead of the bar's layer"); + assert_eq!(rt.instances[record].fill[3], 0.5); + // Half the blur over the stripes: still striped, at half the contrast. + let s = spread(&px, 200, 60, 60, 140); + assert!((40..200).contains(&s), "half-faded spread {s}"); +} + +#[test] +fn hidpi_blurs_in_device_pixels() { + let (rt, px) = render(Scene { bars: vec![BAR], blur: true }, 2.0); + let record = rt.instances.iter().find(|i| i.params[1] == KIND_BACKDROP_BLUR).unwrap(); + assert_eq!(record.params[0], 16.0); + assert_eq!(record.rect, [80.0, 60.0, 240.0, 120.0]); + assert!(spread(&px, 400, 120, 120, 280) <= 3); + let (_, plain) = render(Scene { bars: vec![BAR], blur: false }, 2.0); + assert_eq!(at(&px, 400, 20, 120), at(&plain, 400, 20, 120)); +} + +#[derive(Default)] +struct Edge; + +fn white_corners(_: &Edge, _: &mut Cx<Edge>) -> El { + el().size(100.0, 100.0).fill(Color::WHITE) + .child(el().absolute(0.0, 0.0).size(60.0, 40.0).backdrop_blur(10.0)) + .child(el().absolute(55.0, 70.0).size(45.0, 30.0).backdrop_blur(10.0)) +} + +#[test] +fn window_edges_do_not_darken() { + let gpu = Gpu::headless(); + let mut rt = Runtime::new(Edge, white_corners, (100.0, 100.0), Env::new(false, 1.0)); + rt.frame(0.0); + let px = pixels(&gpu, &mut rt, (100, 100)); + for (x, y) in [(0, 0), (1, 1), (30, 0), (0, 20), (59, 39), (99, 99), (56, 71), (99, 70), (70, 99)] { + assert!(at(&px, 100, x, y)[..3].iter().all(|&c| c >= 254), "white at {x},{y}: {:?}", at(&px, 100, x, y)); + } +} + +#[derive(Default)] +struct Scroll; + +/// 30 pt red and blue rows scrolling under a frosted bar over the bottom 30 pt. +fn scrolling(_: &Scroll, _: &mut Cx<Scroll>) -> El { + let rows = (0..12).map(|i| el().size(100.0, 30.0).fill(if i % 2 == 0 { RED } else { BLUE })); + el().size(100.0, 120.0) + .child(col().key("list").size(100.0, 120.0).scroll(ScrollSpec { stick_bottom: false }).child(col().w_full().children(rows))) + .child(el().absolute(0.0, 90.0).size(100.0, 30.0).backdrop_blur(4.0)) +} + +#[test] +fn scrolled_content_changes_the_blur_and_a_still_frame_stays_idle() { + let gpu = Gpu::headless(); + let mut rt = Runtime::new(Scroll, scrolling, (100.0, 120.0), Env::new(false, 1.0)); + rt.frame(0.0); + for _ in 0..3 { rt.frame(1.0 / 60.0); } + assert!(!rt.frame(1.0 / 60.0), "a still frame with a backdrop blur asks for no redraw"); + let before = at(&pixels(&gpu, &mut rt, (100, 120)), 100, 50, 105); + assert!(before[2] as i32 > before[0] as i32 + 100, "blue row under the bar: {before:?}"); + rt.wheel(50.0, 60.0, -30.0); + rt.frame(1.0 / 120.0); + let px = pixels(&gpu, &mut rt, (100, 120)); + let after = at(&px, 100, 50, 105); + assert!(after[0] as i32 > after[2] as i32 + 100, "red row under the bar after scrolling: {after:?}"); +} + +#[derive(Default)] +struct Clipped; + +/// A bar half outside a clipping box: the blur stops at the clip. +fn clipped(_: &Clipped, _: &mut Cx<Clipped>) -> El { + let stripes = row().size(200.0, 120.0).absolute(0.0, 0.0) + .children((0..50).map(|i| el().size(4.0, 120.0).fill(if i % 2 == 0 { Color::BLACK } else { Color::WHITE }))); + el().size(200.0, 120.0).child(stripes) + .child(el().absolute(0.0, 0.0).size(200.0, 60.0).clip_rounded(0.0) + .child(el().absolute(40.0, 30.0).size(120.0, 60.0).backdrop_blur(8.0))) +} + +#[test] +fn the_blur_stops_at_an_ancestor_clip() { + let gpu = Gpu::headless(); + let mut rt = Runtime::new(Clipped, clipped, (200.0, 120.0), Env::new(false, 1.0)); + rt.frame(0.0); + let px = pixels(&gpu, &mut rt, (200, 120)); + assert!(spread(&px, 200, 50, 60, 140) <= 3, "blurred inside the clip"); + assert!(spread(&px, 200, 70, 60, 140) > 200, "stripes below the clip"); +} + +#[derive(Default)] +struct Grouped; + +/// The bar inside a half-faded group: the group draws as one layer, which the bar blurs. +fn grouped(_: &Grouped, _: &mut Cx<Grouped>) -> El { + let stripes = row().size(200.0, 120.0) + .children((0..50).map(|i| el().size(4.0, 120.0).fill(if i % 2 == 0 { Color::BLACK } else { Color::WHITE }))); + el().size(200.0, 120.0).fill(Color::WHITE) + .child(el().absolute(0.0, 0.0).size(200.0, 120.0).group_opacity(0.5, 0.5) + .child(stripes) + .child(el().absolute(40.0, 30.0).size(120.0, 60.0).backdrop_blur(8.0).child(el().size(10.0, 10.0).fill(Color::WHITE)))) +} + +#[test] +fn inside_a_layer_the_blur_reads_the_layer() { + let gpu = Gpu::headless(); + let mut rt = Runtime::new(Grouped, grouped, (200.0, 120.0), Env::new(false, 1.0)); + rt.frame(0.0); + assert_eq!(records(&rt), 1); + assert!(rt.instances.iter().any(|i| i.params[1] == KIND_LAYER), "the group is a layer"); + let px = pixels(&gpu, &mut rt, (200, 120)); + assert!(spread(&px, 200, 60, 60, 140) <= 3, "blurred inside: {}", spread(&px, 200, 60, 60, 140)); + assert!(spread(&px, 200, 10, 60, 140) > 60, "faded stripes outside"); +} diff --git a/app/vendor/rune/crates/rune/tests/integration/backdrop_blur_cost.rs b/app/vendor/rune/crates/rune/tests/integration/backdrop_blur_cost.rs new file mode 100644 index 0000000..93128fe --- /dev/null +++ b/app/vendor/rune/crates/rune/tests/integration/backdrop_blur_cost.rs @@ -0,0 +1,91 @@ +//! Manual cost fixture for `El::backdrop_blur`: a full-width 60 pt frosted bar at 2x over a +//! scrolling list, against the same bar with a plain fill. +//! +//! `cargo test -p rune --profile perf --test integration backdrop_blur_cost:: -- --ignored --nocapture` + +use rune::render::{Gpu, OFFSCREEN_FORMAT, Offscreen, Renderer}; +use rune::{Color, Cx, El, Env, Runtime, ScrollSpec, col, el, oklch, row}; + +#[derive(Default)] +struct Bar { + blur: bool, +} + +fn view(s: &Bar, _: &mut Cx<Bar>) -> El { + let rows = (0..200).map(|i| row().w_full().h(56.0).px(16.0).gap(12.0).center_y() + .child(el().size(40.0, 40.0).radius(12.0).fill(oklch(0.7, 0.16, (i as f32 * 47.0) % 360.0))) + .child(el().size(180.0, 12.0).radius(6.0).fill(oklch(0.4, 0.0, 0.0)))); + let bar = el().pin(Some(0.0), None, Some(0.0), Some(0.0)).h(60.0).fill(Color::WHITE.alpha(0.6)); + el().w_full().h_full().fill(Color::WHITE) + .child(col().key("list").w_full().h_full().scroll(ScrollSpec { stick_bottom: false }).child(col().w_full().children(rows))) + .child(if s.blur { bar.backdrop_blur(20.0) } else { bar }) +} + +/// GPU milliseconds per frame: `K` frames encoded into one submission, timed on the wall +/// clock from submit to completion, so the GPU stays busy and clocked up and the encode isn't +/// counted. +fn gpu_time(gpu: &Gpu, mut draw: impl FnMut(&mut wgpu::CommandEncoder)) -> f64 { + const K: u32 = 24; + let mut enc = gpu.device.create_command_encoder(&Default::default()); + for _ in 0..K { draw(&mut enc); } + let commands = enc.finish(); + gpu.device.poll(wgpu::PollType::wait_indefinitely()).unwrap(); + let t0 = rune::time::now(); + gpu.queue.submit([commands]); + gpu.device.poll(wgpu::PollType::wait_indefinitely()).unwrap(); + t0.elapsed().as_secs_f64() * 1000.0 / f64::from(K) +} + +fn median(mut v: Vec<f64>) -> f64 { + v.sort_by(f64::total_cmp); + v[v.len() / 2] +} + +#[test] +#[ignore = "manual GPU and CPU cost of a full-width 60 pt frosted bar at 2x"] +fn frosted_bar_cost() { + let gpu = Gpu::headless(); + eprintln!("adapter: {:?}", gpu.adapter.get_info().name); + for (w, h) in [(390.0f32, 844.0f32), (1280.0, 800.0)] { + let size = ((w * 2.0) as u32, (h * 2.0) as u32); + let target = Offscreen::new(&gpu.device, size.0, size.1); + let mut sides: Vec<_> = [false, true].into_iter().map(|blur| { + let mut rt = Runtime::new(Bar { blur }, view, (w, h), Env::new(false, 2.0)); + rt.frame(0.0); + for _ in 0..4 { rt.frame(1.0 / 120.0); } + let idle = !rt.frame(1.0 / 120.0); + let mut renderer = Renderer::new(&gpu.device, OFFSCREEN_FORMAT); + renderer.prepare(&gpu.device, &gpu.queue, &mut rt.text.atlas, &rt.instances, size); + (blur, rt, renderer, idle, Vec::new(), Vec::new(), Vec::new(), Vec::new()) + }).collect(); + // Alternate the two sides so clock and thermal drift hit both alike. + for round in 0..12 { + for (_, rt, renderer, _, still, scroll, frame_ms, encode_ms) in &mut sides { + renderer.prepare(&gpu.device, &gpu.queue, &mut rt.text.atlas, &rt.instances, size); + let ms = gpu_time(&gpu, |enc| renderer.draw(enc, &target.view, [1.0; 4])); + // Scrolling: a 3 pt wheel step each 120 Hz frame, rebuilt, prepared and encoded. + let dir = if round % 2 == 0 { -3.0 } else { 3.0 }; + let mut frames = Vec::new(); + let ms_scroll = gpu_time(&gpu, |enc| { + rt.wheel(w * 0.5, h * 0.5, dir); + let t0 = rune::time::now(); + rt.frame(1.0 / 120.0); + let t1 = rune::time::now(); + renderer.prepare(&gpu.device, &gpu.queue, &mut rt.text.atlas, &rt.instances, size); + renderer.draw(enc, &target.view, [1.0; 4]); + frames.push(((t1 - t0).as_secs_f64() * 1000.0, t1.elapsed().as_secs_f64() * 1000.0)); + }); + if round > 1 { + still.push(ms); + scroll.push(ms_scroll); + frame_ms.extend(frames.iter().map(|f| f.0)); + encode_ms.extend(frames.iter().map(|f| f.1)); + } + } + } + for (blur, _, _, idle, still, scroll, frame_ms, encode_ms) in sides { + eprintln!("{w}x{h} pt @2x blur={blur}: idle frame asks for redraw: {}; gpu still {:.4} ms, scrolling {:.4} ms; cpu frame {:.4} ms, prepare+encode {:.4} ms", + !idle, median(still), median(scroll), median(frame_ms), median(encode_ms)); + } + } +} diff --git a/app/vendor/rune/crates/rune/tests/integration/batch_c.rs b/app/vendor/rune/crates/rune/tests/integration/batch_c.rs new file mode 100644 index 0000000..bde9951 --- /dev/null +++ b/app/vendor/rune/crates/rune/tests/integration/batch_c.rs @@ -0,0 +1,197 @@ +use std::sync::{Arc, atomic::{AtomicUsize, Ordering}}; +use rune::{Cx, El, Env, LiveText, Runtime, TextStyle, el, row, text}; + +struct State { value: LiveText, views: AtomicUsize, bound: bool } +fn view(s: &State, _: &mut Cx<State>) -> El { + s.views.fetch_add(1, Ordering::Relaxed); + row().child(if s.bound { text("00:00").key("clock").live_text(&s.value) } else { el().key("empty") }) + .child(text("untouched sibling").key("sibling")) +} +fn info(rt: &Runtime<State>, key: &str) -> rune::runtime::ElementInfo { + rt.elements().into_iter().find(|e| e.key.as_deref() == Some(key)).unwrap() +} + +#[test] +fn live_text_shapes_only_changed_run_without_layout_and_coalesces_visible_wakes() { + let value = LiveText::new("00:00"); + let mut a = Runtime::new(State { value: value.clone(), views: AtomicUsize::new(0), bound: true }, view, (400.0, 80.0), Env::default()); + let mut b = Runtime::new(State { value: value.clone(), views: AtomicUsize::new(0), bound: true }, view, (400.0, 80.0), Env::default()); + let wakes = Arc::new(AtomicUsize::new(0)); + for rt in [&mut a, &mut b] { + let wakes = wakes.clone(); + rt.set_live_waker(Arc::new(move || { wakes.fetch_add(1, Ordering::Relaxed); })); + rt.frame(0.0); + } + let rect = info(&a, "clock").rect; + let sibling = info(&a, "sibling").rect; + let commits = a.stats.commits; + b.set_live_visible(false); + assert!(!value.set("00:00")); + assert!(!a.live_pending()); + value.set("00:01"); value.set("00:02"); + assert_eq!(wakes.load(Ordering::Relaxed), 1); + a.frame(0.0); b.frame(0.0); + assert_eq!(a.stats.shaped, 1); + assert_eq!(b.stats.shaped, 0); + assert_eq!(info(&a, "clock").text.as_deref(), Some("00:02")); + assert_eq!(info(&b, "clock").text.as_deref(), Some("00:00")); + assert_eq!(a.stats.commits, commits); + assert_eq!(a.state.views.load(Ordering::Relaxed), 1); + b.set_live_visible(true); + assert_eq!(wakes.load(Ordering::Relaxed), 2); + b.frame(0.0); + assert_eq!(info(&b, "clock").text.as_deref(), Some("00:02")); + value.set("a much longer clock value"); a.frame(0.0); + assert_eq!(info(&a, "clock").rect, rect); + assert_eq!(info(&a, "sibling").rect, sibling); + a.frame(0.0); + assert_eq!(a.stats.shaped, 0); + a.invalidate(); a.frame(0.0); + assert_eq!(info(&a, "clock").rect, rect, "placeholder still reserves the same box on rebuild"); + assert_eq!(info(&a, "clock").text.as_deref(), Some("a much longer clock value")); + a.state.bound = false; a.invalidate(); a.frame(0.0); + // The clock still draws while it fades out; once it's gone it stops waking. + for _ in 0..240 { if !a.frame(1.0 / 120.0) { break; } } + b.set_live_visible(false); + let before = wakes.load(Ordering::Relaxed); + value.set("00:03"); + assert_eq!(wakes.load(Ordering::Relaxed), before, "unmounted and hidden hosts don't wake"); + a.state.bound = true; a.invalidate(); a.frame(0.0); + assert_eq!(info(&a, "clock").text.as_deref(), Some("00:03")); +} + +#[test] +fn features_affect_shaping_and_have_separate_cache_entries() { + let mut system = rune::text::TextSystem::default(); + let style = TextStyle::new(24.0, 400.0); + let plain = system.layout_rich("111111", &[], style, 1.0, None); + let tabular = system.layout_rich("111111", &[], style.features("'tnum' 1"), 1.0, None); + assert!(!std::rc::Rc::ptr_eq(&plain, &tabular)); + let again = system.layout_rich("111111", &[], style, 1.0, None); + assert!(std::rc::Rc::ptr_eq(&plain, &again)); + let tnum = style.features("'tnum' 1"); + assert_eq!(system.measure("111111", tnum, 1.0).0, system.measure("000000", tnum, 1.0).0); + let pnum = style.features("'pnum' 1"); + assert_ne!(system.measure("111111", pnum, 1.0).0, system.measure("000000", pnum, 1.0).0); + assert_ne!(rune::text::text_hash("0", &[], style.features("'ss01' 1"), 1.0, None), rune::text::text_hash("0", &[], style, 1.0, None)); +} + +#[cfg(target_os = "macos")] +#[test] +fn optical_size_uses_points_and_variations_reach_parley_and_raster_cache() { + let data: &'static [u8] = Box::leak(std::fs::read("/System/Library/Fonts/SFNS.ttf").unwrap().into_boxed_slice()); + let mut system = rune::text::TextSystem::new(&[data], ("System Font", "System Font")); + let style = TextStyle::new(13.0, 400.0); + let point1 = system.layout_rich("Hello 0123", &[], style.optical_size(13.0), 1.0, None); + let point2 = system.layout_rich("Hello 0123", &[], style.optical_size(13.0), 2.0, None); + let device = system.layout_rich("Hello 0123", &[], style.optical_sizing(rune::OpticalSize::FontDefault), 2.0, None); + let auto = system.layout_rich("Hello 0123", &[], style, 2.0, None); + let explicit = system.layout_rich("Hello 0123", &[], style.variations("'opsz' 13"), 2.0, None); + let coords = |l: &parley::Layout<rune::text::Ink>| l.lines().next().unwrap().runs().next().unwrap().normalized_coords().to_vec(); + assert_eq!(coords(&point1), coords(&point2)); + assert_eq!(coords(&explicit), coords(&point2)); + assert_eq!(coords(&auto), coords(&point2)); + assert_ne!(coords(&device), coords(&point2)); + let mut a = Vec::new(); let mut b = Vec::new(); + system.glyphs_for_layout(&point2, 2.0, [0.0, 0.0], false, &mut a); + system.glyphs_for_layout(&device, 2.0, [0.0, 0.0], false, &mut b); + assert_ne!(a[0].uv, b[0].uv, "different variation outlines must not share atlas entries"); +} + +#[test] +fn os_motion_preference_updates_and_view_can_override_it() { + fn view(override_: &Option<bool>, cx: &mut Cx<Option<bool>>) -> El { + if let Some(value) = override_ { cx.reduced_motion(*value); } + text(cx.system_reduced_motion().to_string()) + } + let mut rt = Runtime::new(None, view, (100.0, 100.0), Env::default()); + assert!(!rt.system_reduced_motion()); + rt.set_system_reduced_motion(true); + rt.frame(0.0); assert!(rt.reduced_motion); + rt.set_system_reduced_motion(false); rt.frame(0.0); assert!(!rt.reduced_motion); + rt.set_system_reduced_motion(true); rt.frame(0.0); assert!(rt.reduced_motion); + rt.update(|s, _| *s = Some(false)); rt.frame(0.0); assert!(!rt.reduced_motion); + assert!(rt.system_reduced_motion(), "a commit override doesn't change the OS preference"); + assert_eq!(rt.elements()[0].text.as_deref(), Some("true")); + rt.update(|s, _| *s = None); rt.frame(0.0); assert!(rt.reduced_motion); +} + +#[test] +fn window_focus_delivers_ordered_transitions_including_before_first_frame() { + fn view(_: &Vec<bool>, _: &mut Cx<Vec<bool>>) -> El { + el().on_window_focus(|s: &mut Vec<bool>, focused, tx| { s.push(focused); tx.copy("focus"); }) + } + let mut rt = Runtime::new(Vec::new(), view, (100.0, 100.0), Env::default()); + rt.window_focus(true); rt.window_focus(true); rt.window_focus(false); rt.frame(0.0); + assert_eq!(rt.state, vec![true, false]); + assert_eq!(rt.copy_request.as_deref(), Some("focus")); + let commits = rt.stats.commits; + rt.window_focus(false); rt.frame(0.0); + assert_eq!(rt.stats.commits, commits); + rt.window_focus(true); rt.frame(0.0); + assert_eq!(rt.state, vec![true, false, true]); +} + +#[test] +fn fade_truncation_keeps_full_text_and_only_fades_overflowing_glyphs() { + fn view(width: &f32, _: &mut Cx<f32>) -> El { + row().child(text("this is much too long").key("label").w(*width).font(TextStyle::new(14.0, 400.0)).truncate_fade()) + } + for scale in [1.0, 2.0] { + let mut rt = Runtime::new(60.0, view, (600.0, 100.0), Env::new(true, scale)); + rt.frame(0.0); + assert_eq!(rt.elements().into_iter().find(|e| e.key.as_deref() == Some("label")).unwrap().text.as_deref(), Some("this is much too long")); + let glyphs: Vec<_> = rt.instances.iter().filter(|i| i.params[1] == rune::render::KIND_GLYPH).collect(); + assert!(!glyphs.is_empty()); + for glyph in glyphs { + assert_eq!(glyph.clip[2], 60.0 * scale); + assert_eq!(rune::render::unpack_fade(glyph.fade).0[2], 1.5 * 14.0 * scale, "1.5 em by default"); + } + rt.update(|s, tx| { *s = 500.0; tx.settle(); }); rt.frame(0.0); + assert!(rt.instances.iter().all(|i| rune::render::unpack_fade(i.fade).0 == [0.0; 4])); + } +} + +#[test] +fn fade_truncation_overflow_is_independent_of_element_and_display_scale() { + const LABEL: &str = "clock 0123456789"; + fn view(s: &(f32, rune::Live<f32>), _: &mut Cx<(f32, rune::Live<f32>)>) -> El { + row().padding(80.0).child(text(LABEL).w(s.0).font(TextStyle::new(14.0, 400.0)) + .live_scale(&s.1).truncate_fade()) + } + let mut text_system = rune::text::TextSystem::default(); + for display_scale in [1.0, 2.0] { + let width = text_system.layout_rich(LABEL, &[], TextStyle::new(14.0, 400.0), display_scale, None) + .full_width() / display_scale; + for element_scale in [0.5, 1.0, 2.0] { + for (fraction, overflowing) in [(0.75, true), (1.25, false)] { + let mut rt = Runtime::new((width * fraction, rune::Live::new(element_scale)), view, + (600.0, 300.0), Env::new(true, display_scale)); + rt.frame(0.0); + let fades: Vec<_> = rt.instances.iter().filter(|i| i.params[1] == rune::render::KIND_GLYPH) + .map(|i| rune::render::unpack_fade(i.fade).0[2]).collect(); + assert!(!fades.is_empty()); + let expected = if overflowing { 1.5 * 14.0 * display_scale * element_scale } else { 0.0 }; + assert!(fades.iter().all(|fade| *fade == expected), + "display={display_scale}, element={element_scale}, overflowing={overflowing}: {fades:?}"); + } + } + } +} + +#[test] +fn fade_truncation_width_is_settable() { + fn view(s: &(f32, f32), _: &mut Cx<(f32, f32)>) -> El { + row().child(text("this is much too long").w(s.0).font(TextStyle::new(14.0, 400.0)).truncate_fade_width(s.1)) + } + for scale in [1.0, 2.0] { + for (width, em, expected) in [(60.0, 3.0, 42.0), (60.0, 0.5, 7.0)] { + let mut rt = Runtime::new((width, em), view, (600.0, 100.0), Env::new(true, scale)); + rt.frame(0.0); + let fades: Vec<_> = rt.instances.iter().filter(|i| i.params[1] == rune::render::KIND_GLYPH) + .map(|i| rune::render::unpack_fade(i.fade).0[2]).collect(); + assert!(!fades.is_empty()); + assert!(fades.iter().all(|f| *f == expected * scale), "width {width}, {em} em at {scale}x: {fades:?}"); + } + } +} diff --git a/app/vendor/rune/crates/rune/tests/integration/border_dash.rs b/app/vendor/rune/crates/rune/tests/integration/border_dash.rs new file mode 100644 index 0000000..25c3c95 --- /dev/null +++ b/app/vendor/rune/crates/rune/tests/integration/border_dash.rs @@ -0,0 +1,89 @@ +use rune::render::{Gpu, KIND_DASHED, KIND_RECT, OFFSCREEN_FORMAT, Offscreen, Renderer}; +use rune::{Color, Cx, El, Env, Runtime, el}; + +const TOP: Color = Color { r: 1.0, g: 0.0, b: 0.0, a: 1.0 }; +const BOTTOM: Color = Color { r: 0.0, g: 0.0, b: 1.0, a: 1.0 }; +const RIM: Color = Color { r: 1.0, g: 1.0, b: 1.0, a: 1.0 }; +const DARK: Color = Color { r: 0.1, g: 0.1, b: 0.12, a: 1.0 }; + +/// A 60×14 capsule at (4, 4) with a 1 pt border; the window is 68×22 points. +#[derive(Clone, Copy)] +enum Mode { + Solid, + Dashed, + FilledDashed, + GradientDashed, +} + +fn view(mode: &Mode, _: &mut Cx<Mode>) -> El { + let capsule = el().absolute(4.0, 4.0).size(60.0, 14.0).radius(7.0); + let capsule = match mode { + Mode::Solid => capsule.border(1.0, RIM), + Mode::Dashed => capsule.border(1.0, RIM).border_dash(8.0, 4.0), + Mode::FilledDashed => capsule.fill(DARK).border_dash(8.0, 4.0).border_dash_phase(2.0).border(1.0, RIM), + Mode::GradientDashed => capsule.border_gradient(1.0, TOP, BOTTOM).border_dash(8.0, 4.0), + }; + el().size(68.0, 22.0).child(capsule) +} + +fn frame(mode: Mode) -> Runtime<Mode> { + let mut rt = Runtime::new(mode, view, (68.0, 22.0), Env::new(true, 2.0)); + rt.frame(0.0); + rt +} + +fn pixels(gpu: &Gpu, rt: &mut Runtime<Mode>) -> Vec<u8> { + let size = (136, 44); + let mut renderer = Renderer::new(&gpu.device, OFFSCREEN_FORMAT); + let target = Offscreen::new(&gpu.device, size.0, size.1); + renderer.prepare(&gpu.device, &gpu.queue, &mut rt.text.atlas, &rt.instances, size); + let mut encoder = gpu.device.create_command_encoder(&Default::default()); + renderer.draw(&mut encoder, &target.view, [0.0; 4]); + target.copy(&mut encoder); + gpu.queue.submit([encoder.finish()]); + target.read(&gpu.device) +} + +#[test] +fn a_dashed_border_is_its_own_ring_over_the_fill() { + let rt = frame(Mode::FilledDashed); + let [fill, ring] = rt.instances.as_slice() else { panic!("fill and ring: {:?}", rt.instances) }; + assert_eq!((fill.params[0], fill.params[1], fill.fill), (0.0, KIND_RECT, DARK.premul(1.0)), "the fill has no ring"); + assert_eq!((ring.params[0], ring.params[1]), (2.0, KIND_DASHED), "1 pt at 2x"); + assert_eq!((ring.rect, ring.radii), ([8.0, 8.0, 120.0, 28.0], [14.0; 4])); + assert_eq!((ring.fill, ring.border), (RIM.premul(1.0), RIM.premul(1.0))); + assert_eq!(ring.uv, [16.0, 8.0, 4.0, 0.0], "dash, gap, phase in device pixels"); + + let rt = frame(Mode::GradientDashed); + let [ring] = rt.instances.as_slice() else { panic!("only the ring: {:?}", rt.instances) }; + assert_eq!((ring.params[1], ring.fill, ring.border), (KIND_DASHED, TOP.premul(1.0), BOTTOM.premul(1.0))); +} + +#[test] +fn dashes_antialias_like_the_solid_border_and_show_the_fill_between() { + let gpu = Gpu::headless(); + let px = |out: &[u8], x: usize, y: usize| -> [u8; 4] { out[(y * 136 + x) * 4..][..4].try_into().unwrap() }; + let solid = pixels(&gpu, &mut frame(Mode::Solid)); + let dashed = pixels(&gpu, &mut frame(Mode::Dashed)); + // The centre line runs 265.7 px, so 11 periods of 24.15 px: the first dash covers the top + // edge from x = 22 to 38.1 and the first gap from 38.1 to 46.2. + for y in 6..12 { + assert_eq!(px(&dashed, 30, y), px(&solid, 30, y), "row {y} across a dash"); + assert_eq!(px(&dashed, 42, y)[3], 0, "row {y} across a gap"); + } + assert!(px(&solid, 30, 8)[3] > 250 && px(&solid, 30, 9)[3] > 250); + // Round the top-right corner (centre line radius 13 about (114, 22)) the pattern goes on: + // the gap that started on the top edge, then a dash. + let corner: Vec<u8> = (0..=16).map(|n| { + let a = n as f32 / 16.0 * std::f32::consts::FRAC_PI_2; + px(&dashed, (114.0 + 13.0 * a.sin()) as usize, (22.0 - 13.0 * a.cos()) as usize)[3] + }).collect(); + assert!(corner[..2].iter().all(|a| *a == 0) && corner[6..14].iter().all(|a| *a > 150), "{corner:?}"); + + let filled = pixels(&gpu, &mut frame(Mode::FilledDashed)); + let dark = px(&filled, 68, 20); + assert!(dark[3] > 250 && dark[0] < 100, "inside is the fill: {dark:?}"); + // Phase 2 pt (4 px) moves the gap 4 px back along the top edge. + assert_eq!(px(&filled, 38, 8), dark, "the fill shows through a gap"); + assert!(px(&filled, 26, 8)[0] > 250, "a dash draws over the fill"); +} diff --git a/app/vendor/rune/crates/rune/tests/integration/border_gradient.rs b/app/vendor/rune/crates/rune/tests/integration/border_gradient.rs new file mode 100644 index 0000000..53e935d --- /dev/null +++ b/app/vendor/rune/crates/rune/tests/integration/border_gradient.rs @@ -0,0 +1,125 @@ +use rune::render::{Gpu, Instance, KIND_GRADIENT, KIND_RECT, OFFSCREEN_FORMAT, Offscreen, Renderer}; +use rune::{Color, Cx, El, Env, Runtime, el}; + +const TOP: Color = Color { r: 1.0, g: 0.0, b: 0.0, a: 1.0 }; +const BOTTOM: Color = Color { r: 0.0, g: 0.0, b: 1.0, a: 1.0 }; +const RIM: Color = Color { r: 1.0, g: 1.0, b: 1.0, a: 0.15 }; +const DARK: Color = Color { r: 0.1, g: 0.1, b: 0.12, a: 1.0 }; + +/// A 60×14 capsule at (4, 4); the window is 68×22 points. +#[derive(Clone, Copy)] +enum Mode { + Gradient, + BorderThenGradient, + GradientThenBorder, + RimGradient, + RimBorder, + SolidBottom, +} + +fn view(mode: &Mode, _: &mut Cx<Mode>) -> El { + let capsule = el().absolute(4.0, 4.0).size(60.0, 14.0).radius(7.0); + let capsule = match mode { + Mode::Gradient => capsule.border_gradient(0.5, TOP, BOTTOM), + Mode::BorderThenGradient => capsule.border(1.0, RIM).border_gradient(0.5, TOP, BOTTOM), + Mode::GradientThenBorder => capsule.border_gradient(0.5, TOP, BOTTOM).border(1.0, RIM), + Mode::RimGradient => capsule.fill(DARK).border_gradient(0.5, RIM, RIM), + Mode::RimBorder => capsule.fill(DARK).border(0.5, RIM), + Mode::SolidBottom => capsule.border(0.5, BOTTOM), + }; + el().size(68.0, 22.0).child(capsule) +} + +fn frame(mode: Mode) -> Runtime<Mode> { + let mut rt = Runtime::new(mode, view, (68.0, 22.0), Env::new(true, 2.0)); + rt.frame(0.0); + rt +} + +fn ring(rt: &Runtime<Mode>) -> Instance { + *rt.instances.iter().find(|i| i.params[0] > 0.0).expect("a border instance") +} + +fn pixels(gpu: &Gpu, rt: &mut Runtime<Mode>) -> Vec<u8> { + let size = (136, 44); + let mut renderer = Renderer::new(&gpu.device, OFFSCREEN_FORMAT); + let target = Offscreen::new(&gpu.device, size.0, size.1); + renderer.prepare(&gpu.device, &gpu.queue, &mut rt.text.atlas, &rt.instances, size); + let mut encoder = gpu.device.create_command_encoder(&Default::default()); + renderer.draw(&mut encoder, &target.view, [0.0; 4]); + target.copy(&mut encoder); + gpu.queue.submit([encoder.finish()]); + target.read(&gpu.device) +} + +#[test] +fn border_gradient_is_a_gradient_ring_instance() { + let i = ring(&frame(Mode::Gradient)); + assert_eq!(i.params[1], KIND_GRADIENT); + assert_eq!(i.params[0], 1.0, "0.5 pt at 2x"); + assert_eq!(i.rect, [8.0, 8.0, 120.0, 28.0]); + assert_eq!(i.radii, [14.0; 4]); + assert_eq!(i.fill, [0.0; 4]); + assert_eq!(i.border, TOP.premul(1.0), "top colour"); + assert_eq!(i.uv, BOTTOM.premul(1.0), "bottom colour"); +} + +#[test] +fn border_and_border_gradient_replace_each_other() { + let i = ring(&frame(Mode::BorderThenGradient)); + assert_eq!((i.params[1], i.params[0], i.border, i.uv), (KIND_GRADIENT, 1.0, TOP.premul(1.0), BOTTOM.premul(1.0))); + let i = ring(&frame(Mode::GradientThenBorder)); + assert_eq!((i.params[1], i.params[0], i.border, i.uv), (KIND_RECT, 2.0, RIM.premul(1.0), [0.0; 4])); +} + +#[test] +fn border_gradient_springs_from_a_solid_border() { + let mut rt = frame(Mode::RimBorder); + rt.update(|s, _| *s = Mode::Gradient); + rt.frame(0.03); + let i = ring(&rt); + assert_eq!(i.params[1], KIND_GRADIENT); + let (rim, bottom) = (RIM.premul(1.0), BOTTOM.premul(1.0)); + assert!(i.uv[3] > rim[3] && i.uv[3] < bottom[3] && i.uv[2] < bottom[2], "bottom mid-spring: {:?}", i.uv); + rt.frame(5.0); + assert_eq!(ring(&rt).uv, bottom); +} + +#[test] +fn solid_border_springs_from_a_gradient_without_moving_a_settled_bottom() { + // The new solid colour equals the old bottom stop, so only the top edge has anywhere to go. + let mut rt = frame(Mode::Gradient); + rt.update(|s, _| *s = Mode::SolidBottom); + let bottom = BOTTOM.premul(1.0); + let mut kinds = Vec::new(); + for step in 1..=120 { + rt.frame(1.0 / 60.0); + let i = ring(&rt); + let edge = if i.params[1] == KIND_GRADIENT { i.uv } else { i.border }; + assert_eq!(edge, bottom, "frame {step}: the bottom edge left `bottom` ({:?})", i); + kinds.push(i.params[1]); + } + assert_eq!(kinds[0], KIND_GRADIENT, "the top edge springs rather than jumping"); + rt.frame(5.0); + let i = ring(&rt); + assert_eq!((i.params[1], i.border, i.uv), (KIND_RECT, bottom, [0.0; 4])); +} + +#[test] +fn border_gradient_pixels_run_top_to_bottom_with_border_coverage() { + let gpu = Gpu::headless(); + let px = |out: &[u8], x: usize, y: usize| -> [u8; 4] { out[(y * 136 + x) * 4..][..4].try_into().unwrap() }; + let out = pixels(&gpu, &mut frame(Mode::Gradient)); + // The 1 px ring's top row is y = 8 and its bottom row y = 35, at the capsule's centre column. + let top = px(&out, 68, 8); + let bottom = px(&out, 68, 35); + assert!(top[0] > 240 && top[2] < 70 && top[3] > 250, "top edge is `top`: {top:?}"); + assert!(bottom[2] > 240 && bottom[0] < 70 && bottom[3] > 250, "bottom edge is `bottom`: {bottom:?}"); + assert_eq!(px(&out, 68, 20)[3], 0, "the ring leaves the inside clear"); + + // A gradient with equal stops antialiases exactly like `border`, at 0.5 pt on 2x. + let a = pixels(&gpu, &mut frame(Mode::RimGradient)); + let b = pixels(&gpu, &mut frame(Mode::RimBorder)); + assert!(a.chunks_exact(4).zip(b.chunks_exact(4)).all(|(a, b)| a.iter().zip(b).all(|(a, b)| a.abs_diff(*b) <= 1))); + assert_ne!(px(&a, 68, 8), px(&a, 68, 20), "the rim shows over the fill"); +} diff --git a/app/vendor/rune/crates/rune/tests/integration/canvas_input.rs b/app/vendor/rune/crates/rune/tests/integration/canvas_input.rs new file mode 100644 index 0000000..6a81597 --- /dev/null +++ b/app/vendor/rune/crates/rune/tests/integration/canvas_input.rs @@ -0,0 +1,244 @@ +//! Canvas input: `on_wheel` ahead of scroll views, pinch, rotation and smart magnify in the +//! handler's own points, the middle button pressing and dragging elements that opt in, and key +//! releases. +use rune::{Cx, El, Env, GesturePhase, Ime, Key, KeyEvent, MagnifyEvent, Mods, Phase, PointerButton, RotateEvent, Runtime, ScrollSpec, TextEdit, TextStyle, WheelEvent, col, el, text_input}; + +#[derive(Default)] +struct S { + /// The canvas takes wheel deltas (else it declines them). + takes: bool, + pan: (f32, f32), + wheels: Vec<WheelEvent>, + zoom: Vec<(f32, f32, f32)>, + turns: Vec<f32>, + smart: Vec<(f32, f32)>, + drags: Vec<(Phase, PointerButton, f32, f32)>, + presses: Vec<PointerButton>, + plain_drags: usize, + plain_presses: usize, + ups: Vec<(&'static str, Key, Mods)>, + space: bool, + edit: TextEdit, +} + +/// A 300 pt page that scrolls, holding a 200 pt canvas at (50, 50) and 600 pt of rows below. +fn view(s: &S, _: &mut Cx<S>) -> El { + let canvas = el().key("canvas").w(200.0).h(200.0).ml(50.0).mt(50.0) + .on_wheel(|s: &mut S, e, _| { + s.wheels.push(e); + if s.takes { s.pan.0 += e.dx; s.pan.1 += e.dy; } + s.takes + }) + .on_magnify(|s: &mut S, e, _| { s.zoom.push((e.delta, e.x, e.y)); true }) + .on_rotate(|s: &mut S, e, _| { s.turns.push(e.degrees); true }) + .on_smart_magnify(|s: &mut S, x, y, _| { s.smart.push((x, y)); true }) + .pointer_buttons([PointerButton::Middle, PointerButton::Back, PointerButton::Forward]) + .on_drag(|s: &mut S, d, tx| s.drags.push((d.phase, tx.button(), d.dx, d.dy))) + .on_press_tx(|s: &mut S, tx| s.presses.push(tx.button())) + .child(el().key("shape").w(40.0).h(40.0).focusable(true) + .on_key_up(|s: &mut S, e, _| { s.ups.push(("shape", e.key.clone(), e.mods)); false })) + .child(text_input(&s.edit, TextStyle::new(14.0, 400.0)).single_line().key("field").w(100.0).h(32.0) + .on_edit(|s: &mut S| &mut s.edit)); + let plain = el().key("plain").w(100.0).h(40.0) + .on_drag(|s: &mut S, _, _| s.plain_drags += 1) + .on_press(|s: &mut S| s.plain_presses += 1); + let rows = (0..15).fold(col().w_full().child(canvas).child(plain), |c, i| c.child(el().key(format!("row{i}")).w_full().h(40.0))); + col().w_full().h_full() + .on_key_up(|s: &mut S, e, _| { + s.ups.push(("root", e.key.clone(), e.mods)); + let space = e.key == Key::Text(" ".into()); + if space { s.space = false; } + space + }) + .child(col().key("page").w_full().h(300.0).scroll(ScrollSpec { stick_bottom: false }).child(rows)) +} + +fn app(s: S) -> Runtime<S> { + let mut rt = Runtime::new(s, view, (300.0, 300.0), Env::new(true, 1.0)); + rt.frame(0.0); + rt +} + +fn y_of(rt: &Runtime<S>, key: &str) -> f32 { + rt.elements().into_iter().find(|e| e.key.as_deref() == Some(key)).unwrap_or_else(|| panic!("{key}")).rect[1] +} + +/// A pause long enough that the next delta starts a new gesture. +fn new_gesture(rt: &mut Runtime<S>) { rt.frame(0.15); } + +#[test] +fn a_wheel_handler_hears_deltas_before_the_scroll_view_around_it() { + let mut rt = app(S { takes: true, ..S::default() }); + let cmd = Mods { cmd: true, ..Mods::default() }; + rt.wheel_event(WheelEvent::new(-10.0, -20.0).at(80.0, 90.0).mods(cmd).precise(true)); + rt.frame(1.0 / 60.0); + assert_eq!(rt.state.pan, (-10.0, -20.0)); + let e = rt.state.wheels[0]; + assert_eq!((e.x, e.y, e.mods, e.precise), (30.0, 40.0, cmd, true), "the pointer in the canvas's own points"); + assert_eq!(y_of(&rt, "canvas"), 50.0, "the page didn't scroll"); + + // The gesture stays the canvas's when the pointer leaves it, as a scroll keeps its axis. + rt.wheel_xy(150.0, 280.0, 0.0, -30.0); + rt.frame(1.0 / 60.0); + assert_eq!((rt.state.pan.1, y_of(&rt, "canvas")), (-50.0, 50.0)); + + // Off the canvas a new gesture scrolls the page, which the canvas never hears. + new_gesture(&mut rt); + let heard = rt.state.wheels.len(); + rt.wheel_xy(150.0, 280.0, 0.0, -30.0); + rt.frame(1.0 / 60.0); + assert_eq!((rt.state.wheels.len(), y_of(&rt, "canvas")), (heard, 20.0)); +} + +#[test] +fn a_declined_delta_scrolls_and_the_gesture_stays_a_scroll() { + let mut rt = app(S::default()); + rt.wheel_xy(150.0, 150.0, 0.0, -30.0); + rt.frame(1.0 / 60.0); + assert_eq!(y_of(&rt, "canvas"), 20.0, "the canvas declined it, so the page scrolled"); + assert_eq!(rt.state.wheels.len(), 1); + // The page has the gesture now: the canvas, taking deltas again, doesn't hear the rest. + rt.state.takes = true; + rt.wheel_xy(150.0, 150.0, 0.0, -10.0); + rt.frame(1.0 / 60.0); + assert_eq!((rt.state.wheels.len(), y_of(&rt, "canvas")), (1, 10.0)); + // Without phases, a delta wholly on the other axis (Shift + wheel) starts a new gesture. + rt.wheel_xy(150.0, 150.0, -15.0, 0.0); + rt.frame(1.0 / 60.0); + assert_eq!((rt.state.wheels.len(), rt.state.pan.0), (2, -15.0)); +} + +#[test] +fn momentum_follows_the_handler_that_took_the_gesture() { + let mut rt = app(S { takes: true, ..S::default() }); + rt.wheel_event(WheelEvent::new(0.0, -10.0).at(150.0, 150.0).phase(GesturePhase::Began)); + rt.wheel_event(WheelEvent::new(0.0, 0.0).at(150.0, 150.0).phase(GesturePhase::Ended)); + // Momentum begins at once, after the pointer moved off the canvas. + rt.wheel_event(WheelEvent::new(0.0, -5.0).at(150.0, 280.0).phase(GesturePhase::Began)); + rt.frame(1.0 / 60.0); + let phases: Vec<_> = rt.state.wheels.iter().map(|e| (e.phase, e.momentum, e.dy)).collect(); + assert_eq!(phases, [(GesturePhase::Began, false, -10.0), (GesturePhase::Ended, false, 0.0), (GesturePhase::Began, true, -5.0)]); + assert_eq!((rt.state.pan.1, y_of(&rt, "canvas")), (-15.0, 50.0)); +} + +#[test] +fn pinch_rotation_and_smart_magnify_arrive_in_the_handlers_points() { + let mut rt = app(S::default()); + rt.magnify_event(MagnifyEvent::new(0.25).at(70.0, 80.0)); + rt.rotate_event(RotateEvent::new(15.0).at(70.0, 80.0)); + rt.smart_magnify(100.0, 60.0); + // Off the canvas nothing hears them. + rt.magnify_event(MagnifyEvent::new(0.5).at(20.0, 20.0)); + rt.frame(1.0 / 60.0); + assert_eq!(rt.state.zoom, [(0.25, 20.0, 30.0)]); + assert_eq!(rt.state.turns, [15.0]); + assert_eq!(rt.state.smart, [(50.0, 10.0)]); +} + +#[test] +fn the_middle_button_drags_only_elements_that_take_it() { + let mut rt = app(S::default()); + // Over the canvas's child, the canvas takes the middle button. + rt.pointer_move(70.0, 70.0); + rt.button_down(70.0, 70.0, PointerButton::Middle); + rt.pointer_move(90.0, 100.0); + rt.button_up(90.0, 100.0, PointerButton::Middle); + rt.frame(1.0 / 60.0); + let drags = &rt.state.drags; + assert_eq!(drags.first(), Some(&(Phase::Down, PointerButton::Middle, 0.0, 0.0))); + assert!(drags.contains(&(Phase::Move, PointerButton::Middle, 20.0, 30.0))); + assert_eq!(drags.last(), Some(&(Phase::Up, PointerButton::Middle, 20.0, 30.0))); + assert!(drags.iter().all(|d| d.1 == PointerButton::Middle)); + assert_eq!(rt.state.presses, [PointerButton::Middle], "released over it, as a primary drag would be"); + + // A middle click outside it presses nothing (on Windows/Linux it latches page autoscroll, + // which a key dismisses before the next press reaches the canvas). + rt.button_down(20.0, 20.0, PointerButton::Middle); + rt.button_up(20.0, 20.0, PointerButton::Middle); + rt.frame(1.0 / 60.0); + assert_eq!(rt.state.presses.len(), 1); + if cfg!(any(target_os = "windows", target_os = "linux")) { + rt.key(KeyEvent { key: Key::Escape, mods: Mods::default() }); + rt.frame(1.0 / 60.0); + } + + // The primary button presses it as before, as the primary. + rt.pointer_down(150.0, 150.0); + rt.pointer_up(150.0, 150.0); + rt.frame(1.0 / 60.0); + assert_eq!(rt.state.presses, [PointerButton::Middle, PointerButton::Primary]); + + // An element that didn't opt in never hears the middle, back or forward buttons. + let (x, y) = rt.find("plain").unwrap(); + for button in [PointerButton::Middle, PointerButton::Back, PointerButton::Forward] { + rt.button_down(x, y, button); + rt.pointer_move(x + 20.0, y); + rt.button_up(x + 20.0, y, button); + rt.button_down(x, y, button); + rt.button_up(x, y, button); + } + rt.frame(1.0 / 60.0); + assert_eq!((rt.state.plain_drags, rt.state.plain_presses), (0, 0)); + + // Back and forward buttons press elements that opted in. + for button in [PointerButton::Back, PointerButton::Forward] { + rt.button_down(150.0, 150.0, button); + rt.button_up(150.0, 150.0, button); + } + rt.frame(1.0 / 60.0); + assert_eq!(rt.state.presses, [PointerButton::Middle, PointerButton::Primary, PointerButton::Back, PointerButton::Forward]); +} + +#[test] +fn a_key_release_goes_to_the_focused_element_then_up_to_the_root() { + let mut rt = app(S::default()); + let space = KeyEvent { key: Key::Text(" ".into()), mods: Mods::default() }; + rt.state.space = true; + assert!(rt.key_up(space.clone())); + rt.frame(1.0 / 60.0); + assert_eq!(rt.state.ups, [("shape", Key::Text(" ".into()), Mods::default()), ("root", Key::Text(" ".into()), Mods::default())], "with nothing focused, every handler hears it, the deepest first"); + assert!(!rt.state.space); + + let (x, y) = rt.find("shape").unwrap(); + rt.pointer_down(x, y); + rt.pointer_up(x, y); + rt.frame(1.0 / 60.0); + rt.state.ups.clear(); + let shift = Mods { shift: true, ..Mods::default() }; + rt.key_up(KeyEvent { key: Key::Escape, mods: shift }); + rt.frame(1.0 / 60.0); + assert_eq!(rt.state.ups, [("shape", Key::Escape, shift), ("root", Key::Escape, shift)], "the focused element first, then its ancestors"); + + // A key pressed while `shape` had focus still delivers its release to `shape` after a + // canvas click blurs `shape`. + rt.state.ups.clear(); + rt.key(space.clone()); + rt.pointer_down(150.0, 150.0); + rt.pointer_up(150.0, 150.0); + rt.key_up(space.clone()); + rt.frame(1.0 / 60.0); + assert_eq!(rt.state.ups, [("shape", Key::Text(" ".into()), Mods::default()), ("root", Key::Text(" ".into()), Mods::default())]); + + // IME composition (and the Enter or Escape release that ends it) never leaks to `on_key_up`. + let (fx, fy) = rt.find("field").unwrap(); + rt.pointer_down(fx, fy); + rt.pointer_up(fx, fy); + rt.frame(1.0 / 60.0); + rt.state.ups.clear(); + rt.ime(Ime::Preedit("ni".into(), Some((2, 2)), Vec::new())); + rt.key_up(KeyEvent { key: Key::Text("i".into()), mods: Mods::default() }); + rt.key(KeyEvent { key: Key::Enter, mods: Mods::default() }); + rt.ime(Ime::Commit("你".into())); + rt.key_up(KeyEvent { key: Key::Enter, mods: Mods::default() }); + rt.frame(1.0 / 60.0); + assert!(rt.state.ups.is_empty(), "IME key releases must not leak: {:?}", rt.state.ups); + assert_eq!(rt.state.edit.text, "你"); +} + +#[test] +fn without_key_up_handlers_a_release_needs_no_frame() { + let mut rt = Runtime::new((), |_: &(), _: &mut Cx<()>| el().w(10.0).h(10.0), (100.0, 100.0), Env::new(true, 1.0)); + rt.frame(0.0); + assert!(!rt.key_up(KeyEvent { key: Key::Escape, mods: Mods::default() })); + assert!(!rt.frame(1.0 / 60.0)); +} diff --git a/app/vendor/rune/crates/rune/tests/integration/caret.rs b/app/vendor/rune/crates/rune/tests/integration/caret.rs new file mode 100644 index 0000000..348e0e4 --- /dev/null +++ b/app/vendor/rune/crates/rune/tests/integration/caret.rs @@ -0,0 +1,108 @@ +//! The focused field's caret is readable from the view (`Cx::caret`) and tools +//! (`ElementInfo::caret`) in window points, after scrolling and inside an IME composition. +use rune::runtime::ElementInfo; +use rune::{Cx, El, Env, Ime, Key, KeyEvent, Runtime, ScrollSpec, TextEdit, TextStyle, col, el, text_input}; + +struct S { draft: TextEdit } + +fn view(s: &S, cx: &mut Cx<S>) -> El { + let field = col().key("composer").w_full().padding(6.0) + .child(text_input(&s.draft, TextStyle::new(14.0, 400.0)).key("input").w_full().on_edit(|s: &mut S| &mut s.draft)); + let mut root = col().w_full().h_full() + .child(col().key("scroll").w_full().h(120.0).scroll(ScrollSpec { stick_bottom: false }) + .child(col().w_full().child(el().h(60.0)).child(field).child(el().h(200.0)))); + // An @mention popup hangs from the caret line. + if let Some([x, y, _, h]) = cx.caret("composer") { + root = root.child(el().key("popup").absolute(x, y + h).size(80.0, 30.0)); + } + root +} + +fn find(rt: &Runtime<S>, key: &str) -> Option<ElementInfo> { + rt.elements().into_iter().find(|e| e.key.as_deref() == Some(key)) +} + +fn caret(rt: &Runtime<S>) -> [f32; 4] { + find(rt, "input").and_then(|e| e.caret).expect("the focused field reports its caret") +} + +/// The popup sits under the caret line in the same frame the caret moved. +fn popup_follows(rt: &mut Runtime<S>, what: &str) -> [f32; 4] { + rt.frame(1.0 / 60.0); + let c = caret(rt); + let p = find(rt, "popup").unwrap_or_else(|| panic!("{what}: popup")).target; + assert_eq!([p[0], p[1]], [c[0], c[1] + c[3]], "{what}: popup under the caret"); + let drawn = rt.ime_area.expect("the drawn caret's IME area"); + assert!((drawn[0] - c[0]).abs() < 0.01 && (drawn[1] - c[1]).abs() < 0.01 && (drawn[3] - c[3]).abs() < 0.01, + "{what}: matches the drawn caret {drawn:?} vs {c:?}"); + c +} + +#[test] +fn caret_follows_typing_scrolling_and_composition() { + let mut draft = TextEdit::new("hi"); + draft.focused = true; + let mut rt = Runtime::new(S { draft }, view, (300.0, 300.0), Env::new(true, 2.0)); + rt.frame(0.0); + let start = popup_follows(&mut rt, "first frame"); + let input = find(&rt, "input").unwrap(); + assert!(start[0] > input.rect[0] + 5.0 && start[0] < input.rect[0] + 30.0, "after \"hi\": {start:?} in {:?}", input.rect); + assert!(start[1] >= input.rect[1] && start[1] + start[3] <= input.rect[1] + input.rect[3] + 0.01, "on the field's line"); + assert!(start[3] > 10.0 && start[2] > 0.0, "a caret line, not a point: {start:?}"); + + rt.ime(Ime::Commit(" there".into())); + let typed = popup_follows(&mut rt, "typing"); + assert!(typed[0] > start[0] + 20.0, "moves right as text is typed"); + assert_eq!(typed[1], start[1]); + + rt.wheel(150.0, 60.0, -40.0); + let scrolled = popup_follows(&mut rt, "scrolling"); + assert_eq!(scrolled[0], typed[0]); + assert!((scrolled[1] - (typed[1] - 40.0)).abs() < 0.01, "rides the scroll: {scrolled:?}"); + + // Composing あい with the IME cursor after あ: the caret sits inside the composition. + rt.ime(Ime::Preedit("あい".into(), Some((3, 3)), Vec::new())); + let mid = popup_follows(&mut rt, "composition"); + rt.ime(Ime::Preedit("あい".into(), Some((6, 6)), Vec::new())); + let end = popup_follows(&mut rt, "composition end"); + assert!(mid[0] > scrolled[0] + 5.0 && end[0] > mid[0] + 5.0, "{scrolled:?} {mid:?} {end:?}"); + + rt.update(|s, _| s.draft.focused = false); + for _ in 0..60 { rt.frame(1.0 / 60.0); } + assert!(find(&rt, "input").unwrap().caret.is_none(), "no caret without focus"); + assert!(find(&rt, "popup").is_none(), "the view sees it go"); +} + +/// Arrow keys step whole grapheme clusters; the reported caret lands where the caret is drawn. +#[test] +fn caret_rect_tracks_grapheme_steps() { + let clusters = ["a", "👨‍👩‍👧", "🇯🇵", "👋🏽", "❤️", "b"]; + let mut draft = TextEdit::new(clusters.concat()); + draft.focused = true; + let mut rt = Runtime::new(S { draft }, view, (300.0, 300.0), Env::new(true, 2.0)); + rt.frame(0.0); + let key = |rt: &mut Runtime<S>, key| rt.key(KeyEvent { key, mods: Default::default() }); + + let mut xs = vec![popup_follows(&mut rt, "end")[0]]; + for i in (0..clusters.len()).rev() { + key(&mut rt, Key::Left); + let c = popup_follows(&mut rt, &format!("before cluster {i}")); + assert_eq!(rt.state.draft.focus, clusters[..i].concat().len(), "Left lands before cluster {i}"); + assert!(c[0] < xs.last().unwrap() - 2.0, "cluster {i} moves the caret left: {c:?} after {xs:?}"); + xs.push(c[0]); + } + xs.reverse(); + for i in 1..=clusters.len() { + key(&mut rt, Key::Right); + let c = popup_follows(&mut rt, &format!("after cluster {i}")); + assert_eq!(rt.state.draft.focus, clusters[..i].concat().len(), "Right lands after cluster {i}"); + assert!((c[0] - xs[i]).abs() < 0.01, "Right retraces Left at {i}: {} vs {}", c[0], xs[i]); + } + + // Backspace from just after the family removes the whole cluster and the caret follows. + for _ in 0..4 { key(&mut rt, Key::Left); } + key(&mut rt, Key::Backspace); + let c = popup_follows(&mut rt, "after backspace"); + assert_eq!(rt.state.draft.text, ["a", "🇯🇵", "👋🏽", "❤️", "b"].concat()); + assert!((c[0] - xs[1]).abs() < 0.01, "back after \"a\": {} vs {}", c[0], xs[1]); +} diff --git a/app/vendor/rune/crates/rune/tests/integration/caret_follow.rs b/app/vendor/rune/crates/rune/tests/integration/caret_follow.rs new file mode 100644 index 0000000..73a9eaa --- /dev/null +++ b/app/vendor/rune/crates/rune/tests/integration/caret_follow.rs @@ -0,0 +1,123 @@ +//! Editing keeps the caret line inside the field's nearest scroll viewport, as a browser +//! textarea does. +use rune::runtime::ElementInfo; +use rune::{Color, El, Env, Ime, Key, KeyEvent, Runtime, ScrollSpec, TextEdit, TextStyle, col, el, text_input}; + +struct S { draft: TextEdit } + +fn view(s: &S) -> El { + col().w_full().h_full().padding(20.0).child( + col().key("viewport").w_full().h(60.0).scroll(ScrollSpec { stick_bottom: false }) + .child(text_input(&s.draft, TextStyle::new(14.0, 400.0).lh(20.0)).key("input").w_full().on_edit(|s: &mut S| &mut s.draft)), + ) +} + +fn find(rt: &Runtime<S>, key: &str) -> ElementInfo { + rt.elements().into_iter().find(|e| e.key.as_deref() == Some(key)).unwrap() +} + +fn assert_visible(rt: &Runtime<S>, what: &str) -> [f32; 4] { + let c = find(rt, "input").caret.expect("caret"); + let v = find(rt, "viewport").rect; + assert!(c[1] >= v[1] - 0.01 && c[1] + c[3] <= v[1] + v[3] + 0.01, "{what}: caret {c:?} inside viewport {v:?}"); + c +} + +fn key(rt: &mut Runtime<S>, key: Key) { + rt.key(KeyEvent { key, mods: Default::default() }); + rt.frame(1.0 / 60.0); +} + +#[test] +fn editing_scrolls_the_caret_into_its_viewport() { + let mut draft = TextEdit::new(""); + draft.focused = true; + let mut rt = Runtime::new(S { draft }, |s: &S, _: &mut rune::Cx<S>| view(s), (300.0, 300.0), Env::new(true, 2.0)); + rt.frame(0.0); + assert_visible(&rt, "empty"); + let mut last = 0.0; + for n in 1..8 { + rt.ime(Ime::Commit(format!("\nline {n}"))); + rt.frame(1.0 / 60.0); + let c = assert_visible(&rt, &format!("line {n}")); + if n > 3 { assert!((c[1] - last).abs() < 0.01, "pinned to the bottom edge once it overflows"); } + last = c[1]; + } + assert!(find(&rt, "input").rect[1] < find(&rt, "viewport").rect[1] - 60.0, "the field scrolled up"); + + // Walking the caret back up scrolls just far enough to show each line. + for n in 0..7 { + key(&mut rt, Key::Up); + assert_visible(&rt, &format!("up {n}")); + } + let top = find(&rt, "input").rect[1]; + assert!((top - find(&rt, "viewport").rect[1]).abs() < 1.0, "back at the first line: {top}"); + + // A wheel scroll away is left alone until the next edit brings the caret back. + rt.wheel(150.0, 40.0, -100.0); + rt.frame(1.0 / 60.0); + assert!(find(&rt, "input").rect[1] < top - 50.0, "the wheel moved the field"); + rt.ime(Ime::Commit("x".into())); + rt.frame(1.0 / 60.0); + assert_visible(&rt, "typing after a wheel"); +} + +fn caret_ink() -> Color { rune::color::hex("#ff0077").unwrap() } + +fn single_line_view(s: &S) -> El { + col().w_full().h_full().padding(20.0).child( + col().key("viewport").w_full().h(60.0).scroll(ScrollSpec { stick_bottom: false }) + .child(col().child(el().h(100.0)) + .child(text_input(&s.draft, TextStyle::new(14.0, 400.0).lh(20.0)).key("input").w(120.0) + .single_line().caret(caret_ink(), caret_ink().alpha(0.3)).on_edit(|s: &mut S| &mut s.draft))), + ) +} + +#[test] +fn single_line_fields_follow_the_caret_both_ways() { + let mut draft = TextEdit::new(""); + draft.focused = true; + let mut rt = Runtime::new(S { draft }, |s: &S, _: &mut rune::Cx<S>| single_line_view(s), (300.0, 300.0), Env::new(true, 2.0)); + rt.frame(0.0); + for word in ["a long single line ", "that runs well past ", "the field's width"] { + rt.ime(Ime::Commit(word.into())); + rt.frame(1.0 / 60.0); + } + // Down into view vertically, and sideways inside the field. + let c = assert_visible(&rt, "below the fold"); + let field = find(&rt, "input").rect; + assert_eq!(field[3], 20.0, "still one line: {field:?}"); + assert!(c[0] > field[0] + 60.0 && c[0] + c[2] <= field[0] + field[2] + 0.01, "caret {c:?} at the field's end {field:?}"); + // The reported caret is the drawn one. + let want = caret_ink().premul(1.0); + let drawn = rt.instances.iter().find(|i| i.fill.iter().zip(want).all(|(a, b)| (a - b).abs() < 1e-3)).expect("drawn caret").rect; + assert!((drawn[0] / 2.0 - c[0]).abs() < 1.0, "drawn {drawn:?} vs {c:?}"); + assert!(drawn[1] / 2.0 >= c[1] && (drawn[1] + drawn[3]) / 2.0 <= c[1] + c[3], "drawn {drawn:?} inside the caret line {c:?}"); + // Home shifts back to the start. + key(&mut rt, Key::Home); + let c = assert_visible(&rt, "home"); + assert!((c[0] - field[0]).abs() < 4.0, "caret {c:?} back at the start of {field:?}"); +} + +fn popup_view(s: &S, cx: &mut rune::Cx<S>) -> El { + let mut root = view(s); + if let Some([x, y, _, h]) = cx.caret("input") { + root = root.child(el().key("popup").absolute(x, y + h).size(80.0, 30.0)); + } + root +} + +#[test] +fn a_caret_popup_lands_where_following_scrolled_the_caret() { + let mut draft = TextEdit::new(""); + draft.focused = true; + let mut rt = Runtime::new(S { draft }, popup_view, (300.0, 300.0), Env::new(true, 2.0)); + rt.frame(0.0); + for n in 1..8 { + rt.ime(Ime::Commit(format!("\nline {n}"))); + rt.frame(1.0 / 60.0); + let c = assert_visible(&rt, &format!("line {n}")); + let p = find(&rt, "popup").target; + assert_eq!([p[0], p[1]], [c[0], c[1] + c[3]], "line {n}: popup under the scrolled caret"); + } +} diff --git a/app/vendor/rune/crates/rune/tests/integration/clip.rs b/app/vendor/rune/crates/rune/tests/integration/clip.rs new file mode 100644 index 0000000..3ea8f62 --- /dev/null +++ b/app/vendor/rune/crates/rune/tests/integration/clip.rs @@ -0,0 +1,225 @@ +use rune::render::{Gpu, OFFSCREEN_FORMAT, Offscreen, Renderer}; +use rune::{Color, Cx, El, Env, Runtime, ScrollSpec, col, el, text}; + +fn pixels<S: 'static>(gpu: &Gpu, rt: &mut Runtime<S>, size: (u32, u32)) -> Vec<u8> { + let mut renderer = Renderer::new(&gpu.device, OFFSCREEN_FORMAT); + let target = Offscreen::new(&gpu.device, size.0, size.1); + renderer.prepare(&gpu.device, &gpu.queue, &mut rt.text.atlas, &rt.instances, size); + let mut encoder = gpu.device.create_command_encoder(&Default::default()); + renderer.draw(&mut encoder, &target.view, [0.0; 4]); + target.copy(&mut encoder); + gpu.queue.submit([encoder.finish()]); + target.read(&gpu.device) +} + +fn alpha(px: &[u8], width: u32, x: u32, y: u32) -> u8 { + px[((y * width + x) * 4 + 3) as usize] +} + +#[derive(Default)] +struct S { + pressed: bool, + stick: bool, + soft: bool, +} + +/// A 100×100 viewport at y 40 whose 140 pt of content overflows it by 40 pt. +fn view(s: &S, _: &mut Cx<S>) -> El { + let mut scroll = col().key("scroll").size(100.0, 100.0).scroll(ScrollSpec { stick_bottom: s.stick }) + .child(el().size(100.0, 60.0).fill(Color::WHITE)) + .child(el().key("under").size(100.0, 80.0).fill(Color::WHITE).on_press(|s: &mut S| s.pressed = true)); + if s.soft { + scroll = scroll.clip_fade(0.0, 0.0, 0.0, 16.0); + } + col().size(100.0, 200.0).child(el().h(40.0)).child(scroll) +} + +#[test] +fn overflowing_scroll_content_stays_inside_the_box_as_it_scrolls() { + let gpu = Gpu::headless(); + let size = (100, 200); + let mut rt = Runtime::new(S::default(), view, (100.0, 200.0), Env::new(true, 1.0)); + rt.frame(0.0); + let px = pixels(&gpu, &mut rt, size); + assert_eq!(alpha(&px, 100, 50, 130), 255, "inside the box"); + assert_eq!(alpha(&px, 100, 50, 160), 0, "overflow below the box isn't drawn"); + assert!(rt.instances.iter().all(|i| i.fade[3] == 0), "clip-radius lane stays reserved"); + + // Scrolled to the end, the content moves under a clip that stays put. + rt.wheel(50.0, 90.0, -40.0); + rt.frame(1.0 / 120.0); + let px = pixels(&gpu, &mut rt, size); + assert_eq!(alpha(&px, 100, 50, 45), 255, "top of the box"); + assert_eq!(alpha(&px, 100, 50, 135), 255, "bottom of the box"); + assert_eq!(alpha(&px, 100, 50, 20), 0, "content scrolled above the box isn't drawn"); + + // Opened at the bottom, the top of the content is clipped too. + let mut rt = Runtime::new(S { stick: true, ..S::default() }, view, (100.0, 200.0), Env::new(true, 1.0)); + rt.frame(0.0); + let px = pixels(&gpu, &mut rt, size); + assert_eq!(alpha(&px, 100, 50, 45), 255); + assert_eq!(alpha(&px, 100, 50, 20), 0, "stick_bottom content above the box isn't drawn"); +} + +#[test] +fn a_press_outside_the_box_misses_clipped_content() { + let mut rt = Runtime::new(S::default(), view, (100.0, 200.0), Env::new(true, 1.0)); + rt.frame(0.0); + rt.pointer_down(50.0, 160.0); + rt.pointer_up(50.0, 160.0); + rt.frame(1.0 / 120.0); + assert!(!rt.state.pressed, "the overflowing part of the child isn't hit"); + rt.pointer_down(50.0, 130.0); + rt.pointer_up(50.0, 130.0); + rt.frame(1.0 / 120.0); + assert!(rt.state.pressed, "the visible part still is"); +} + +#[test] +fn an_explicit_soft_clip_still_wins() { + let gpu = Gpu::headless(); + let mut rt = Runtime::new(S { soft: true, ..S::default() }, view, (100.0, 200.0), Env::new(true, 1.0)); + rt.frame(0.0); + let px = pixels(&gpu, &mut rt, (100, 200)); + let edge = alpha(&px, 100, 50, 136); + assert!(edge > 0 && edge < 128, "16 pt fade at the bottom edge: {edge}"); + assert_eq!(alpha(&px, 100, 50, 160), 0); + assert!(rt.instances.iter().all(|i| i.fade[3] == 0)); +} + +#[test] +fn packed_fades_survive_group_layer_projection_without_double_application() { + fn layered(state: &(f32, bool), _: &mut Cx<(f32, bool)>) -> El { + let mut group = col().size(80.0, 64.0).opacity(state.0) + .child(el().size(80.0, 32.0).fill(Color::WHITE)) + .child(el().size(80.0, 32.0).fill(Color::WHITE)); + if state.1 { group = group.clip_rounded(16.0); } + el().size(128.0, 128.0).child(col().absolute(16.0, 16.0).size(80.0, 80.0) + .clip_fade(0.0, 16.0, 0.0, 0.0) + // Intersect before isolation: the composite must decode a nonzero origin offset. + .child(col().absolute(0.0, 8.0).size(80.0, 64.0).clip_soft(0.0).child(group))) + } + let gpu = Gpu::headless(); + for (scale, rounded) in [(1.0, false), (2.0, false), (1.0, true), (2.0, true)] { + let size = ((128.0 * scale) as u32, (128.0 * scale) as u32); + let env = Env::new(true, scale); + let mut plain = Runtime::new((1.0, rounded), layered, (128.0, 128.0), env); + let mut isolated = Runtime::new((0.5, rounded), layered, (128.0, 128.0), env); + plain.frame(0.0); isolated.frame(0.0); + assert!(isolated.instances.iter().any(|i| i.params[1] == rune::render::KIND_LAYER)); + assert!(isolated.instances.iter().any(|i| i.fade[2] != 0), "exercise inherited origin offsets"); + assert_eq!(isolated.instances.iter().any(|i| i.fade[3] != 0), rounded); + let a = pixels(&gpu, &mut plain, size); + let b = pixels(&gpu, &mut isolated, size); + assert!(a.chunks_exact(4).any(|p| p[3] > 0 && p[3] < 255)); + for (direct, group) in a.chunks_exact(4).zip(b.chunks_exact(4)) { + let expected = (f32::from(direct[3]) * 0.5).round() as u8; + assert!(group[3].abs_diff(expected) <= 1, "layer changed fade coverage: {direct:?} / {group:?}"); + } + } +} + +#[test] +fn narrower_nested_edge_and_streaming_mask_survive_outer_fades() { + use rune::render::unpack_fade; + let gpu = Gpu::headless(); + for scale in [1.0, 2.0] { + fn nested(outer: &bool, _: &mut Cx<bool>) -> El { + col().size(80.0, 200.0).clip_fade(0.0, if *outer { 24.0 } else { 0.0 }, 0.0, 0.0) + .child(el().h(40.0)) + .child(col().size(80.0, 80.0).clip_fade(0.0, 8.0, 0.0, 0.0) + .child(el().size(80.0, 80.0).fill(Color::WHITE))) + } + let size = ((80.0 * scale) as u32, (200.0 * scale) as u32); + let env = Env::new(true, scale); + let mut plain = Runtime::new(false, nested, (80.0, 200.0), env); + let mut outer = Runtime::new(true, nested, (80.0, 200.0), env); + plain.frame(0.0); outer.frame(0.0); + let a = pixels(&gpu, &mut plain, size); + let b = pixels(&gpu, &mut outer, size); + assert_eq!(a, b, "8px inner edge remains inside the finished 24px ancestor ramp"); + assert!(b[(((40.0 * scale) as u32 * size.0 + 20) * 4 + 3) as usize] < 30); + + fn streaming(s: &(bool, f32), _: &mut Cx<(bool, f32)>) -> El { + col().size(80.0, 200.0).clip_fade(0.0, 0.0, 0.0, if s.0 { 24.0 } else { 0.0 }) + .child(col().w_full().growth(rune::el::GrowthSpec { edge: rune::growth::edge::FAST_FEATHER, ..Default::default() }) + .child(col().key("row").w_full().streaming(true) + .child(el().size(80.0, s.1).fill(Color::WHITE)))) + } + let render = |faded| { + let mut rt = Runtime::new((faded, 20.0), streaming, (80.0, 200.0), env); + rt.frame(0.0); + rt.update(|s, _| s.1 = 80.0); + rt.frame(1.0 / 60.0); + let instance = rt.instances.iter().find(|i| i.fill[3] == 1.0).unwrap(); + let (width, offset) = unpack_fade(instance.fade); + assert!(width[3] > 0.0 && width[3] < 24.0 * scale); + assert_eq!(offset[3], 0.0, "row_mask belongs to the growing row's bottom"); + pixels(&gpu, &mut rt, size) + }; + assert_eq!(render(false), render(true), "streaming row mask survives a transcript's larger bottom fade"); + } +} + +fn faded_rows(faded: &bool, _: &mut Cx<bool>) -> El { + let row = || col().size(120.0, 20.0).clip_fade(0.0, 0.0, 8.0, 0.0) + .child(text("MMMMMMMMMMMMMM").color(Color::WHITE)); + col().size(120.0, 100.0).clip_fade(0.0, if *faded { 16.0 } else { 0.0 }, 0.0, if *faded { 16.0 } else { 0.0 }) + .child(row()).child(el().h(20.0)).child(row()).child(el().h(20.0)).child(row()) +} + +#[test] +fn nested_row_text_keeps_full_alpha_in_the_middle_of_a_faded_list() { + let gpu = Gpu::headless(); + let mut renderer = Renderer::new(&gpu.device, OFFSCREEN_FORMAT); + for scale in [1.0, 2.0] { + let (w, h) = ((120.0 * scale) as u32, (100.0 * scale) as u32); + let target = Offscreen::new(&gpu.device, w, h); + let mut render = |faded, old_bug| { + let mut rt = Runtime::new(faded, faded_rows, (120.0, 100.0), Env::new(true, scale)); + rt.frame(0.0); + if old_bug { + for instance in &mut rt.instances { instance.fade[2] = 0; } + } + renderer.prepare(&gpu.device, &gpu.queue, &mut rt.text.atlas, &rt.instances, (w, h)); + let mut encoder = gpu.device.create_command_encoder(&Default::default()); + renderer.draw(&mut encoder, &target.view, [0.0; 4]); + target.copy(&mut encoder); + gpu.queue.submit([encoder.finish()]); + target.read(&gpu.device) + }; + let plain = render(false, false); + let faded = render(true, false); + let broken = render(true, true); + let middle = ((40.0 * scale) as usize * w as usize * 4)..((60.0 * scale) as usize * w as usize * 4); + assert_eq!(plain[middle.clone()], faded[middle.clone()], "the row's own right fade must not restart top/bottom fades"); + let alpha = |pixels: &[u8]| pixels.chunks_exact(4).map(|p| u64::from(p[3])).sum::<u64>(); + assert!(alpha(&faded[middle.clone()]) > 0); + assert!(alpha(&broken[middle.clone()]) < alpha(&faded[middle]) / 2, "fixture must catch the old washout"); + let top = 0..(20.0 * scale) as usize * w as usize * 4; + assert!(alpha(&faded[top.clone()]) < alpha(&plain[top]), "the ancestor fade still acts at the list edge"); + } +} + +#[test] +fn a_linear_fade_falls_in_proportion_to_distance_from_the_edge() { + fn faded(linear: &bool, _: &mut Cx<bool>) -> El { + let content = el().size(100.0, 100.0).fill(Color::WHITE); + let clip = col().size(100.0, 100.0); + if *linear { clip.clip_fade_linear(0.0, 0.0, 0.0, 40.0) } else { clip.clip_fade(0.0, 0.0, 0.0, 40.0) }.child(content) + } + let gpu = Gpu::headless(); + let mut linear = Runtime::new(true, faded, (100.0, 100.0), Env::new(true, 1.0)); + let mut smooth = Runtime::new(false, faded, (100.0, 100.0), Env::new(true, 1.0)); + linear.frame(0.0); smooth.frame(0.0); + let bottom = |rt: &Runtime<bool>| rt.instances.iter().map(|i| rune::render::unpack_fade(i.fade).0[3]).find(|&w| w != 0.0); + assert_eq!((bottom(&linear), bottom(&smooth)), (Some(-40.0), Some(40.0)), "a linear width packs negative"); + let (lin, eased) = (pixels(&gpu, &mut linear, (100, 100)), pixels(&gpu, &mut smooth, (100, 100))); + // Row `y` has its centre 99.5 - y in from the bottom edge. + for (y, x) in [(89, 0.2625), (79, 0.5125), (69, 0.7625)] { + let a = alpha(&lin, 100, 50, y); + assert!((f32::from(a) - x * 255.0).abs() <= 2.0, "row {y}: {a}, want {}", x * 255.0); + } + assert!(alpha(&eased, 100, 50, 89) < alpha(&lin, 100, 50, 89) - 20, "smoothstep stays lower near the edge"); + assert_eq!(alpha(&lin, 100, 50, 50), 255, "whole above the ramp"); +} diff --git a/app/vendor/rune/crates/rune/tests/integration/deco_api.rs b/app/vendor/rune/crates/rune/tests/integration/deco_api.rs new file mode 100644 index 0000000..bfd014c --- /dev/null +++ b/app/vendor/rune/crates/rune/tests/integration/deco_api.rs @@ -0,0 +1,7 @@ +use rune::{Color, text::Deco}; + +#[test] +fn decoration_literal_remains_source_compatible() { + let d = Deco { rect: [0.0; 4], color: Color::BLACK, radius: 4.0 }; + assert_eq!(d.radius, 4.0); +} diff --git a/app/vendor/rune/crates/rune/tests/integration/dim_browser.rs b/app/vendor/rune/crates/rune/tests/integration/dim_browser.rs new file mode 100644 index 0000000..63cfa99 --- /dev/null +++ b/app/vendor/rune/crates/rune/tests/integration/dim_browser.rs @@ -0,0 +1,94 @@ +//! What CSS gives these boxes, in sRGB bytes: `El::dim` fades a solid box as `opacity` would, +//! with its outer shadows outside it and its fill and gradient fading as one, and an outer +//! shadow paints at its authored alpha over a transparent window or an opaque page. +use rune::color::{srgb_decode, srgb_encode}; +use rune::render::{Gpu, OFFSCREEN_FORMAT, Offscreen, Renderer}; +use rune::{Color, Cx, El, Env, Runtime, Shadow, el}; + +const W: u32 = 120; +const H: u32 = 140; + +fn render(gpu: &Gpu, view: fn(&(), &mut Cx<()>) -> El, srgb: bool, transparent: bool) -> Vec<u8> { + let mut rt = Runtime::new((), view, (W as f32, H as f32), Env::new(false, 1.0)); + rt.set_srgb_blend(srgb); + rt.transparent = transparent; + rt.frame(0.0); + let format = if srgb { OFFSCREEN_FORMAT.remove_srgb_suffix() } else { OFFSCREEN_FORMAT }; + let mut renderer = Renderer::new(&gpu.device, format); + renderer.set_srgb_blend(srgb); + let target = Offscreen::with_format(&gpu.device, W, H, format); + renderer.prepare(&gpu.device, &gpu.queue, &mut rt.text.atlas, &rt.instances, (W, H)); + let mut encoder = gpu.device.create_command_encoder(&Default::default()); + renderer.draw(&mut encoder, &target.view, rt.clear_color()); + target.copy(&mut encoder); + renderer.submit(&gpu.queue, encoder); + target.read(&gpu.device) +} + +fn pixel(rgba: &[u8], x: u32, y: u32) -> [u8; 4] { + let at = ((y * W + x) * 4) as usize; + rgba[at..at + 4].try_into().unwrap() +} + +fn byte(v: u8) -> Color { + let c = srgb_decode(v as f32 / 255.0); + Color { r: c, g: c, b: c, a: 1.0 } +} + +/// CSS source-over in sRGB bytes. +fn mix(fg: f32, bg: f32, a: f32) -> f32 { + a * fg + (1.0 - a) * bg +} + +/// A contrast button's skin, 100 points tall: #242424 under white fading from 20% to 0, over a +/// 20%-black drop shadow and a crisp 30%-white edge half a point up, at `dim` on `page`. +fn button(page: u8, dim: f32, sheen: bool) -> El { + let mut b = el().size(100.0, 100.0).radius(8.0).fill(byte(0x24)) + .box_shadow(Shadow { y: 1.0, blur: 1.5, color: Color::BLACK.alpha(0.2), ..Shadow::default() }) + .box_shadow(Shadow { y: -0.5, color: Color::WHITE.alpha(0.3), ..Shadow::default() }); + if sheen { + b = b.gradient(Color::WHITE.alpha(0.2), Color::WHITE.alpha(0.0)); + } + el().size(W as f32, H as f32).fill(byte(page)).padding(10.0).child(b.dim(dim)) +} + +#[test] +fn a_dimmed_button_fades_as_css_opacity_does() { + let gpu = Gpu::headless(); + fn plain_light(_: &(), _: &mut Cx<()>) -> El { button(0xff, 0.4, false) } + fn plain_dark(_: &(), _: &mut Cx<()>) -> El { button(0x16, 0.4, false) } + fn sheened(_: &(), _: &mut Cx<()>) -> El { button(0xff, 0.4, true) } + for (view, page) in [(plain_light as fn(&(), &mut Cx<()>) -> El, 255.0), (plain_dark, 22.0)] { + for srgb in [true, false] { + // No shadow shows through the faded fill, in either blend mode. + let got = pixel(&render(&gpu, view, srgb, false), 60, 60)[0] as f32; + let fill = if srgb { mix(36.0, page, 0.4) } else { + srgb_encode(mix(srgb_decode(36.0 / 255.0), srgb_decode(page / 255.0), 0.4)) * 255.0 + }; + assert!((got - fill).abs() <= 1.0, "page {page}, sRGB blending {srgb}: {got} vs {fill}"); + } + } + // The fill and its sheen fade together: 40% of the sheened fill over white. + let px = render(&gpu, sheened, true, false); + for y in [30u32, 60, 90] { + let t = (y as f32 + 0.5 - 10.0) / 100.0; + let want = mix(mix(255.0, 36.0, 0.2 * (1.0 - t)), 255.0, 0.4); + let got = pixel(&px, 60, y)[0] as f32; + assert!((got - want).abs() <= 1.0, "row {y}: {got} vs {want}"); + } +} + +#[test] +fn a_shadow_paints_its_authored_alpha() { + // A card with a shadow 40 points down: well below the card the shadow is at full strength. + fn card(_: &(), _: &mut Cx<()>) -> El { + el().size(W as f32, H as f32).padding(10.0).child(el().size(100.0, 60.0).fill(Color::WHITE) + .box_shadow(Shadow { y: 40.0, blur: 4.0, color: Color::BLACK.alpha(31.0 / 255.0), ..Shadow::default() })) + } + fn page(_: &(), cx: &mut Cx<()>) -> El { card(&(), cx).fill(Color::WHITE) } + let gpu = Gpu::headless(); + let over_window = pixel(&render(&gpu, card, true, true), 60, 85); + assert!(over_window[..3] == [0, 0, 0] && over_window[3].abs_diff(31) <= 1, "over a transparent window, the authored #0000001f: {over_window:?}"); + let over_page = pixel(&render(&gpu, page, true, false), 60, 85)[0] as f32; + assert!((over_page - mix(0.0, 255.0, 31.0 / 255.0)).abs() <= 1.0, "over white: {over_page}"); +} diff --git a/app/vendor/rune/crates/rune/tests/integration/drag_cancel.rs b/app/vendor/rune/crates/rune/tests/integration/drag_cancel.rs new file mode 100644 index 0000000..244cc64 --- /dev/null +++ b/app/vendor/rune/crates/rune/tests/integration/drag_cancel.rs @@ -0,0 +1,82 @@ +//! A held drag ends cancelled, with `Phase::Up` and `Drag::cancelled`, when Escape is pressed or +//! the window loses focus. The release that follows does nothing, and other keys pass through. +use rune::{Cx, El, Env, Key, KeyEvent, Mods, Phase, Runtime, col, el}; + +#[derive(Default)] +struct S { + drags: Vec<(Phase, bool, f32)>, + keys: Vec<Key>, + presses: usize, +} + +fn view(_: &S, _: &mut Cx<S>) -> El { + col().w_full().h_full() + .child(el().key("handle").w(100.0).h(40.0) + .on_drag(|s: &mut S, d, _| s.drags.push((d.phase, d.cancelled(), d.dx))) + .on_press(|s: &mut S| s.presses += 1)) +} + +fn held() -> Runtime<S> { + let mut rt = Runtime::new(S::default(), view, (300.0, 300.0), Env::new(true, 1.0)); + rt.on_key = Some(|s, ev, _| { s.keys.push(ev.key.clone()); true }); + rt.frame(0.0); + rt.pointer_down(10.0, 10.0); + rt.pointer_move(40.0, 10.0); + rt.frame(0.0); + rt +} + +fn esc() -> KeyEvent { + KeyEvent { key: Key::Escape, mods: Mods::default() } +} + +#[test] +fn escape_cancels_a_held_drag_and_the_release_does_nothing() { + let mut rt = held(); + rt.key(esc()); + rt.frame(0.0); + assert_eq!(rt.state.drags.last(), Some(&(Phase::Up, true, 30.0))); + assert!(rt.state.keys.is_empty(), "the cancel took the Escape"); + rt.pointer_move(60.0, 10.0); + rt.pointer_up(60.0, 10.0); + rt.frame(0.0); + assert_eq!(rt.state.drags.iter().filter(|d| d.0 == Phase::Up).count(), 1, "exactly one end"); + assert_eq!(rt.state.presses, 0); +} + +#[test] +fn losing_window_focus_cancels_a_held_drag() { + let mut rt = held(); + rt.window_focus(true); + rt.window_focus(false); + rt.frame(0.0); + assert_eq!(rt.state.drags.last(), Some(&(Phase::Up, true, 30.0))); + rt.pointer_up(40.0, 10.0); + rt.frame(0.0); + assert_eq!(rt.state.drags.iter().filter(|d| d.0 == Phase::Up).count(), 1); +} + +#[test] +fn physical_escape_cancels_a_held_drag_too() { + let mut rt = held(); + rt.physical_input(rune::PhysicalInput::Key { + key: rune::PhysicalKeyCode::Escape, mods: Mods::default(), pressed: true, repeat: false, + }); + rt.frame(0.0); + assert_eq!(rt.state.drags.last(), Some(&(Phase::Up, true, 30.0))); + assert!(rt.state.keys.is_empty()); + rt.pointer_up(40.0, 10.0); + rt.frame(0.0); + assert_eq!(rt.state.drags.iter().filter(|d| d.0 == Phase::Up).count(), 1); +} + +#[test] +fn a_release_ends_uncancelled_and_escape_without_a_drag_passes_through() { + let mut rt = held(); + rt.pointer_up(40.0, 10.0); + rt.frame(0.0); + assert_eq!(rt.state.drags.last(), Some(&(Phase::Up, false, 30.0))); + rt.key(esc()); + rt.frame(0.0); + assert_eq!(rt.state.keys, [Key::Escape]); +} diff --git a/app/vendor/rune/crates/rune/tests/integration/drag_release.rs b/app/vendor/rune/crates/rune/tests/integration/drag_release.rs new file mode 100644 index 0000000..79b4d5b --- /dev/null +++ b/app/vendor/rune/crates/rune/tests/integration/drag_release.rs @@ -0,0 +1,74 @@ +//! A release where the pointer last was is not a drag move. A tap on a slider track animates +//! the knob there on `Phase::Down`; an extra `Phase::Move` on the release would run as an +//! instant transaction and snap the knob the rest of the way mid-spring. +use rune::runtime::ElementInfo; +use rune::{Drag, El, Env, Phase, Runtime, Spring, el}; + +#[derive(Default)] +struct S { value: f32, phases: Vec<Phase> } + +fn view(s: &S, _: &mut rune::Cx<S>) -> El { + el().key("root").size(400.0, 100.0) + .child(el().key("slider").size(300.0, 20.0).motion(Spring::new(0.25, 0.0)) + .on_drag(|s: &mut S, d: &mut Drag, tx| { + s.phases.push(d.phase); + match d.phase { + Phase::Down => s.value = d.x, + Phase::Move => { s.value = d.x; tx.instant(); } + Phase::Up => {} + } + }) + .child(el().key("knob").size(20.0, 20.0).absolute(s.value, 0.0))) +} + +fn knob(rt: &Runtime<S>) -> ElementInfo { + rt.elements().into_iter().find(|e| e.key.as_deref() == Some("knob")).expect("knob") +} + +fn runtime() -> Runtime<S> { + let mut rt = Runtime::new(S::default(), view, (400.0, 100.0), Env::new(true, 2.0)); + rt.frame(0.0); + rt +} + +#[test] +fn a_tap_animates_through_its_release() { + let mut rt = runtime(); + rt.pointer_move(250.0, 10.0); + rt.pointer_down(250.0, 10.0); + for _ in 0..3 { rt.frame(1.0 / 120.0); } + let before = knob(&rt).rect[0]; + rt.pointer_up(250.0, 10.0); + rt.frame(1.0 / 120.0); + let after = knob(&rt).rect[0]; + assert_eq!(rt.state.phases, [Phase::Down, Phase::Up]); + assert!(after > before && after < 249.0, "knob keeps springing after the release: {before} -> {after}"); + rt.frame(1.0); + assert_eq!(knob(&rt).rect[0], 250.0); +} + +#[test] +fn a_release_somewhere_new_still_moves() { + let mut rt = runtime(); + rt.pointer_move(50.0, 10.0); + rt.pointer_down(50.0, 10.0); + rt.frame(1.0); + rt.pointer_up(120.0, 10.0); + rt.frame(1.0 / 120.0); + assert_eq!(rt.state.phases, [Phase::Down, Phase::Move, Phase::Up]); + assert_eq!(knob(&rt).rect[0], 120.0, "a move on release applies instantly"); +} + +#[test] +fn a_drag_that_comes_to_rest_releases_without_a_move() { + let mut rt = runtime(); + rt.pointer_move(50.0, 10.0); + rt.pointer_down(50.0, 10.0); + rt.frame(1.0); + rt.pointer_move(90.0, 10.0); + rt.frame(1.0 / 120.0); + rt.pointer_up(90.0, 10.0); + rt.frame(1.0 / 120.0); + assert_eq!(rt.state.phases, [Phase::Down, Phase::Move, Phase::Up]); + assert_eq!(knob(&rt).rect[0], 90.0); +} diff --git a/app/vendor/rune/crates/rune/tests/integration/drawn_layout.rs b/app/vendor/rune/crates/rune/tests/integration/drawn_layout.rs new file mode 100644 index 0000000..b9dafac --- /dev/null +++ b/app/vendor/rune/crates/rune/tests/integration/drawn_layout.rs @@ -0,0 +1,147 @@ +//! Rects under live transforms: `El::on_drawn_layout` reports where an element on a zoomed, +//! panned canvas shows, hit tests and `ElementInfo::rect` agree with it, and `on_layout` keeps +//! the laid-out rect. +use rune::{Cx, Drag, El, Env, Live, Runtime, el}; + +struct S { + pan: Live<[f32; 2]>, + zoom: Live<f32>, + drawn: Vec<[f32; 4]>, + laid: Vec<[f32; 4]>, + pressed: Vec<&'static str>, + drags: Vec<(f32, f32)>, + /// The node grows by 20 pt each time it reports its drawn width: layout feedback that must fall quiet. + chase: bool, + chase_scale: bool, + width: f32, + scale: f32, +} + +fn new() -> S { + S { pan: Live::new([0.0, 0.0]), zoom: Live::new(1.0), drawn: Vec::new(), laid: Vec::new(), pressed: Vec::new(), drags: Vec::new(), chase: false, chase_scale: false, width: 20.0, scale: 1.0 } +} + +/// A 200 pt world under the camera, with a node at (100, 100) and one at (20, 20). +fn view(s: &S, _: &mut Cx<S>) -> El { + let node = el().key("node").pin(Some(100.0), Some(100.0), None, None).size(s.width, 20.0).scale(s.scale) + .on_drawn_layout(|s: &mut S, r| { + s.drawn.push(r); + if s.chase { s.width = 20.0 + r[2]; } + if s.chase_scale { s.scale += 0.25; } + }) + .on_layout(|s: &mut S, r| s.laid.push(r)) + .on_press(|s: &mut S| s.pressed.push("node")) + .on_drag(|s: &mut S, d: &mut Drag, _| s.drags.push((d.x, d.y))); + let other = el().key("other").pin(Some(20.0), Some(20.0), None, None).size(20.0, 20.0) + .on_press(|s: &mut S| s.pressed.push("other")); + let world = el().key("world").size(200.0, 200.0).live_offset(&s.pan).live_scale(&s.zoom).child(node).child(other); + el().size(300.0, 300.0).child(world) +} + +fn app() -> Runtime<S> { + let mut rt = Runtime::new(new(), view, (300.0, 300.0), Env::new(true, 1.0)); + rt.frame(0.0); + rt.frame(0.0); + rt +} + +fn rect(rt: &Runtime<S>, key: &str) -> [f32; 4] { + rt.elements().into_iter().find(|e| e.key.as_deref() == Some(key)).unwrap_or_else(|| panic!("{key}")).rect +} + +#[test] +fn a_camera_pan_and_zoom_report_the_drawn_rect_without_a_commit() { + let mut rt = app(); + assert_eq!(rt.state.drawn, [[100.0, 100.0, 20.0, 20.0]], "reported once after it is first drawn"); + assert_eq!(rt.state.laid, [[100.0, 100.0, 20.0, 20.0]]); + + // Half size about the world's centre (100, 100), then 10 right. + rt.state.zoom.set(0.5); + rt.state.pan.set([10.0, 0.0]); + rt.frame(0.0); + rt.frame(0.0); + assert_eq!(rt.state.drawn.last(), Some(&[110.0, 100.0, 10.0, 10.0])); + assert_eq!(rect(&rt, "node"), [110.0, 100.0, 10.0, 10.0], "ElementInfo::rect agrees"); + assert_eq!(rt.state.laid.len(), 1, "on_layout keeps the laid-out rect, which didn't move"); + + // A long pan keeps reporting: live moves are outside layout feedback. + for k in 1..=30 { + rt.state.pan.set([10.0 + k as f32, 0.0]); + rt.frame(1.0 / 60.0); + } + rt.frame(0.0); + assert_eq!(rt.state.drawn.last(), Some(&[140.0, 100.0, 10.0, 10.0])); + assert!(rt.state.drawn.len() >= 30, "every frame of the pan reported: {}", rt.state.drawn.len()); + let n = rt.state.drawn.len(); + for _ in 0..5 { rt.frame(1.0 / 60.0); } + assert_eq!(rt.state.drawn.len(), n, "nothing moved, nothing reported"); + assert!(!rt.has_pending_input()); +} + +#[test] +fn hit_tests_and_drags_follow_the_live_zoom_and_pan() { + let mut rt = app(); + rt.state.zoom.set(0.5); + rt.state.pan.set([10.0, 0.0]); + rt.frame(0.0); + // At rest the node covers (100..120, 100..120); drawn it covers (110..120, 100..110). + rt.pointer_down(112.0, 105.0); + rt.pointer_up(112.0, 105.0); + rt.frame(0.0); + assert_eq!(rt.state.pressed, ["node"]); + rt.pointer_down(105.0, 115.0); + rt.pointer_up(105.0, 115.0); + rt.frame(0.0); + assert_eq!(rt.state.pressed, ["node"], "inside its layout box but outside where it is drawn"); + // `other` at rest (20..40, 20..40) is drawn at (70..80, 60..70). + rt.pointer_down(72.0, 62.0); + rt.pointer_up(72.0, 62.0); + rt.frame(0.0); + assert_eq!(rt.state.pressed, ["node", "other"]); + + rt.state.drags.clear(); + rt.pointer_down(112.0, 104.0); + rt.pointer_move(118.0, 108.0); + rt.pointer_up(118.0, 108.0); + rt.frame(0.0); + let drags = &rt.state.drags; + assert_eq!((drags[0], drags[drags.len() - 1]), ((4.0, 8.0), (16.0, 16.0)), "drag points are in the node's own points at half size: {drags:?}"); +} + +#[test] +fn a_handler_that_moves_its_own_element_falls_quiet() { + let mut rt = app(); + rt.update(|s, _| s.chase = true); + rt.state.pan.set([5.0, 0.0]); + let mut frames = 0; + while (rt.frame(1.0 / 60.0) || rt.has_pending_input()) && frames < 2_000 { frames += 1; } + assert!(frames < 2_000, "layout feedback stops"); + assert!(rt.state.drawn.len() <= 8, "a few reports, then quiet: {:?}", rt.state.drawn); + + let mut rt = app(); + rt.set_system_reduced_motion(true); + rt.update(|s, _| s.chase_scale = true); + rt.state.pan.set([5.0, 0.0]); + let mut frames = 0; + while (rt.frame(1.0 / 60.0) || rt.has_pending_input()) && frames < 2_000 { frames += 1; } + assert!(frames < 2_000, "static scale feedback stops too"); + assert!(rt.state.drawn.len() <= 8, "a few reports, then quiet: {:?}", rt.state.drawn); +} + +#[test] +fn drag_points_in_a_scrolled_list_are_from_where_the_row_is_drawn() { + fn list(_: &Vec<(f32, f32)>, _: &mut Cx<Vec<(f32, f32)>>) -> El { + let rows = (0..20).fold(rune::col().w_full(), |c, i| c.child(el().key(format!("row{i}")).w_full().h(40.0) + .on_drag(|s: &mut Vec<(f32, f32)>, d: &mut Drag, _| s.push((d.x, d.y))))); + rune::col().w_full().h_full().child(rune::col().key("list").w_full().h(200.0).scroll(rune::ScrollSpec { stick_bottom: false }).child(rows)) + } + let mut rt = Runtime::new(Vec::new(), list, (300.0, 300.0), Env::new(true, 1.0)); + rt.frame(0.0); + rt.update(|_, tx| tx.scroll_to_y("list", 100.0)); + rt.frame(0.0); + // Row 5 (laid out at 200) is drawn at 100. + rt.pointer_down(10.0, 110.0); + rt.pointer_up(10.0, 110.0); + rt.frame(0.0); + assert_eq!(rt.state.first(), Some(&(10.0, 10.0)), "{:?}", rt.state); +} diff --git a/app/vendor/rune/crates/rune/tests/integration/drawn_rect.rs b/app/vendor/rune/crates/rune/tests/integration/drawn_rect.rs new file mode 100644 index 0000000..10c3d41 --- /dev/null +++ b/app/vendor/rune/crates/rune/tests/integration/drawn_rect.rs @@ -0,0 +1,61 @@ +//! `El::drawn_rect_into`: where each frame draws an element, written to a live value with no +//! commit, through a wheel scroll and a glide, and followed by a live rect a frame behind. +use rune::{Color, Cx, El, Env, Live, Runtime, ScrollSpec, col, el}; + +struct S { + ring: Live<[f32; 4]>, +} + +fn view(s: &S, _: &mut Cx<S>) -> El { + let rows = (0..30).fold(col().w_full(), |c, i| { + let row = el().key(format!("row{i}")).w_full().h(40.0).fill(Color::BLACK); + c.child(if i == 3 { row.drawn_rect_into(&s.ring) } else { row }) + }); + col().w_full().h_full() + .child(col().key("scroll").w(300.0).h(400.0).mt(50.0).scroll(ScrollSpec { stick_bottom: false }).child(rows)) + .child(el().key("ring").pin(Some(0.0), Some(0.0), None, None).live_rect(&s.ring).fill(Color::WHITE)) +} + +fn rect(rt: &Runtime<S>, key: &str) -> [f32; 4] { + rt.elements().into_iter().find(|e| e.key.as_deref() == Some(key)).unwrap_or_else(|| panic!("no {key}")).rect +} + +fn near(a: [f32; 4], b: [f32; 4]) -> bool { + a.iter().zip(&b).all(|(a, b)| (a - b).abs() < 0.01) +} + +/// Frames `n`, checking each that the live value holds where row 3 drew, and the ring bound +/// to it where row 3 drew the frame before. Returns the frames row 3 moved on. +fn follow(rt: &mut Runtime<S>, n: usize, each: impl Fn(&mut Runtime<S>)) -> usize { + let mut moved = 0; + let mut last = rect(rt, "row3"); + for f in 0..n { + each(rt); + rt.frame(1.0 / 120.0); + let row = rect(rt, "row3"); + let ring = rt.state.ring.get(); + assert!(near(ring, row), "frame {f}: the value {ring:?} is where row 3 drew, {row:?}"); + assert!(near(rect(rt, "ring"), last), "frame {f}: the ring {:?} follows row 3 a frame behind, {last:?}", rect(rt, "ring")); + if (row[1] - last[1]).abs() > 0.01 { moved += 1; } + last = row; + } + moved +} + +#[test] +fn a_drawn_rect_follows_a_scroll_and_a_glide_with_no_commit() { + let mut rt = Runtime::new(S { ring: Live::new([0.0; 4]) }, view, (400.0, 600.0), Env::new(true, 2.0)); + rt.frame(0.0); + rt.frame(1.0 / 120.0); + assert!(near(rt.state.ring.get(), [0.0, 170.0, 300.0, 40.0]), "{:?}", rt.state.ring.get()); + let commits = rt.stats.commits; + let wheeled = follow(&mut rt, 30, |rt| rt.wheel(150.0, 200.0, -8.0)); + assert!(wheeled > 20, "the wheel scrolled it ({wheeled} frames)"); + assert!(rect(&rt, "row3")[1] < 120.0); + rt.update_if(|_, tx| { tx.scroll_to("scroll", 0.0, 0.0); false }); + let glided = follow(&mut rt, 120, |_| {}); + assert!(glided > 5, "the glide carried it ({glided} frames)"); + assert!(near(rt.state.ring.get(), [0.0, 170.0, 300.0, 40.0]), "it lands back at the top"); + assert!(near(rect(&rt, "ring"), [0.0, 170.0, 300.0, 40.0]), "and the ring with it"); + assert_eq!(rt.stats.commits, commits, "a scroll and a glide run no view"); +} diff --git a/app/vendor/rune/crates/rune/tests/integration/effect_data.rs b/app/vendor/rune/crates/rune/tests/integration/effect_data.rs new file mode 100644 index 0000000..03ae279 --- /dev/null +++ b/app/vendor/rune/crates/rune/tests/integration/effect_data.rs @@ -0,0 +1,241 @@ +//! What a compositor's hook learns about each effect slot: its `El::effect` tag +//! (`EffectSite::mark`), its `El::effect_data` payload (`EffectSite::data`) frozen with the +//! element through its exit, and where the presented element is, transforms included. +use rune::render::{EffectSite, Gpu, Instance, KIND_LAYER, KIND_LAYER_END, OFFSCREEN_FORMAT, Offscreen, Renderer}; +use rune::runtime::ElementInfo; +use rune::{Cx, El, Env, Runtime, Transition, effect, el, memo}; + +#[derive(Clone, Copy, Debug)] +struct Seen { + mark: u32, + data: [f32; 4], + rect: [f32; 4], + scale: f32, + in_layer: bool, + /// Product of the opacities of the isolated layers open around the slot. + opacity: f32, + /// Turn of the innermost turned layer around the slot, in radians. + turn: f32, +} + +/// Draws the frame through `Renderer::draw_with` and records every slot the hook sees. +fn draw<S: 'static>(gpu: &Gpu, renderer: &mut Renderer, rt: &mut Runtime<S>, size: (u32, u32)) -> Vec<Seen> { + let target = Offscreen::new(&gpu.device, size.0, size.1); + renderer.prepare(&gpu.device, &gpu.queue, &mut rt.text.atlas, &rt.instances, size); + let instances: &[Instance] = &rt.instances; + let mut seen = Vec::new(); + let mut encoder = gpu.device.create_command_encoder(&Default::default()); + renderer.draw_with(&mut encoder, &target.view, [0.0; 4], &mut |_, s: &EffectSite<'_>| { + let mut open = Vec::new(); + for i in &instances[..s.index as usize] { + if i.params[1] == KIND_LAYER { open.push(*i); } + if i.params[1] == KIND_LAYER_END { open.pop(); } + } + seen.push(Seen { + mark: s.mark, + data: s.data, + rect: s.instance.rect, + scale: s.scale, + in_layer: s.in_layer, + opacity: open.iter().map(|l| l.fill[3]).product(), + turn: open.iter().rev().map(|l| l.border[1]).find(|t| *t != 0.0).unwrap_or(0.0), + }); + }); + gpu.queue.submit([encoder.finish()]); + seen +} + +fn bits(data: [f32; 4]) -> [u32; 4] { + data.map(f32::to_bits) +} + +fn one(seen: &[Seen], mark: u32) -> Seen { + let hits: Vec<_> = seen.iter().filter(|s| s.mark == mark).collect(); + assert_eq!(hits.len(), 1, "mark {mark} in {seen:?}"); + *hits[0] +} + +fn find<S: 'static>(rt: &Runtime<S>, key: &str) -> ElementInfo { + rt.elements().into_iter().find(|e| e.key.as_deref() == Some(key)).unwrap_or_else(|| panic!("missing {key:?}")) +} + +fn near(a: [f32; 4], b: [f32; 4], what: &str) { + assert!(a.iter().zip(b).all(|(a, b)| (a - b).abs() < 0.01), "{what}: {a:?} vs {b:?}"); +} + +/// Within a device pixel: slot rects snap to the pixel grid like the rest of the paint. +fn snapped(a: [f32; 4], b: [f32; 4], what: &str) { + assert!(a.iter().zip(b).all(|(a, b)| (a - b).abs() <= 1.0), "{what}: {a:?} vs {b:?}"); +} + +const ID: f32 = f32::from_bits(0xDEAD_BEEF); +const NAN: f32 = f32::from_bits(0x7FC0_1234); + +struct Pair { version: u32, other: u32 } + +fn pair_slots(version: u32) -> El { + el().size(96.0, 40.0) + .child(effect(7).absolute(8.0, 8.0).size(16.0, 16.0).effect_data([1.0, 2.0, 3.0, version as f32])) + .child(effect(70_000).absolute(40.0, 8.0).size(16.0, 16.0).effect_data([ID, -0.5, NAN, 0.0])) +} + +fn pair(s: &Pair, _: &mut Cx<Pair>) -> El { + let v = s.version; + el().size(96.0, 96.0) + .child(el().key("plain").child(pair_slots(0))) + .child(el().key("cached").absolute(0.0, 48.0).cache().child(memo("slots", v, move || pair_slots(v)))) + .child(el().key("tick").size(s.other as f32, 1.0)) +} + +#[test] +fn sibling_slots_each_hand_the_hook_their_own_mark_and_payload() { + let gpu = Gpu::headless(); + let mut renderer = Renderer::new(&gpu.device, OFFSCREEN_FORMAT); + let mut rt = Runtime::new(Pair { version: 1, other: 1 }, pair, (96.0, 96.0), Env::new(true, 1.0)); + rt.frame(0.0); + let check = |seen: &[Seen], version: f32| { + let marks: Vec<u32> = seen.iter().map(|s| s.mark).collect(); + assert_eq!(marks, [7, 70_000, 7, 70_000], "painter order, in and out of a memo under .cache()"); + for (k, s) in seen.iter().enumerate() { + let want = if s.mark == 7 { [1.0, 2.0, 3.0, if k < 2 { 0.0 } else { version }] } else { [ID, -0.5, NAN, 0.0] }; + assert_eq!(bits(s.data), bits(want), "slot {k} payload, bit for bit"); + assert!(!s.in_layer && s.opacity == 1.0, "slot {k}: {s:?}"); + } + }; + check(&draw(&gpu, &mut renderer, &mut rt, (96, 96)), 1.0); + // A rebuild that reuses the memoized slots keeps their payload. + rt.update(|s, _| s.other = 2); + rt.frame(1.0 / 60.0); + check(&draw(&gpu, &mut renderer, &mut rt, (96, 96)), 1.0); + // A new version rebuilds them with the new payload. + rt.update(|s, _| s.version = 5); + rt.frame(1.0 / 60.0); + check(&draw(&gpu, &mut renderer, &mut rt, (96, 96)), 5.0); +} + +struct Pages { page: u32, phase: f32 } + +fn pages(s: &Pages, _: &mut Cx<Pages>) -> El { + let x = if s.page % 2 == 0 { 48.0 } else { 8.0 }; + el().size(96.0, 96.0).child( + effect(100 + s.page).key(format!("hud{}", s.page)).absolute(x, 8.0).size(32.0, 32.0) + .effect_data([s.page as f32, s.phase, 0.0, 0.0]).transition(Transition::opacity()), + ) +} + +#[test] +fn an_exiting_slot_keeps_its_mark_and_payload_while_its_replacement_enters() { + let gpu = Gpu::headless(); + let mut renderer = Renderer::new(&gpu.device, OFFSCREEN_FORMAT); + let mut rt = Runtime::new(Pages { page: 1, phase: 0.25 }, pages, (96.0, 96.0), Env::new(true, 1.0)); + rt.frame(0.0); + let seen = draw(&gpu, &mut renderer, &mut rt, (96, 96)); + assert_eq!(seen.len(), 1); + assert_eq!((seen[0].mark, seen[0].data, seen[0].in_layer), (101, [1.0, 0.25, 0.0, 0.0], false)); + + rt.update(|s, _| { + s.page = 2; + s.phase = 0.75; + }); + let mut both = 0; + for frame in 0..60 { + rt.frame(1.0 / 60.0); + let seen = draw(&gpu, &mut renderer, &mut rt, (96, 96)); + let new = one(&seen, 102); + assert_eq!(new.data, [2.0, 0.75, 0.0, 0.0], "frame {frame}: the new slot's payload"); + let Some(old) = seen.iter().find(|s| s.mark == 101) else { continue }; + both += 1; + assert_eq!(old.data, [1.0, 0.25, 0.0, 0.0], "frame {frame}: the exiting slot keeps the payload it left with"); + assert!(find(&rt, "hud1").exiting, "frame {frame}"); + assert!(old.in_layer && old.opacity < 1.0, "frame {frame}: the exit fade applies through the slot's layer: {old:?}"); + assert!((old.opacity - find(&rt, "hud1").opacity).abs() < 1e-4, "frame {frame}: at the presented opacity"); + assert_eq!(old.rect, [8.0, 8.0, 32.0, 32.0], "frame {frame}: where it was"); + assert_eq!(new.rect, [48.0, 8.0, 32.0, 32.0], "frame {frame}: beside it"); + if frame == 0 { + assert!(new.in_layer && new.opacity < 1.0, "the new slot fades in: {new:?}"); + } + } + assert!(both >= 3, "the exit played over {both} frames"); + let seen = draw(&gpu, &mut renderer, &mut rt, (96, 96)); + assert_eq!(seen.len(), 1, "the exited slot is gone: {seen:?}"); + assert!(!seen[0].in_layer && seen[0].opacity == 1.0); +} + +struct Moves { extra: bool } + +fn moves(s: &Moves, _: &mut Cx<Moves>) -> El { + let mut root = el().size(160.0, 160.0) + .child(effect(1).key("scaled").absolute(8.0, 8.0).size(16.0, 16.0).scale(1.5)) + .child(effect(2).key("offset").absolute(40.0, 8.0).size(16.0, 16.0).offset(5.0, 3.0)) + .child(effect(3).key("rotated").absolute(8.0, 40.0).size(16.0, 16.0).rotate(0.5)) + .child(el().key("parent").absolute(40.0, 40.0).size(32.0, 32.0).scale(2.0) + .child(effect(4).key("child").absolute(8.0, 8.0).size(8.0, 8.0))); + if s.extra { + root = root.child(effect(5).key("moving").absolute(96.0, 96.0).size(32.0, 32.0) + .transition(Transition::scale(0.5).combined(Transition::offset(0.0, 24.0)))); + } + root +} + +/// The slot's rect and `scale` are the presented element's, in device pixels. +fn presented(seen: &Seen, e: &ElementInfo, k: f32, what: &str) { + snapped(seen.rect, e.rect.map(|v| v * k), what); + assert!((seen.scale - e.scale * k).abs() < 1e-4, "{what}: scale {} vs {}", seen.scale, e.scale * k); +} + +#[test] +fn slots_follow_scale_offset_and_transitions_and_turn_in_a_layer() { + let k = 2.0; + let gpu = Gpu::headless(); + let mut renderer = Renderer::new(&gpu.device, OFFSCREEN_FORMAT); + let mut rt = Runtime::new(Moves { extra: false }, moves, (160.0, 160.0), Env::new(true, k)); + let size = (320, 320); + rt.frame(0.0); + let seen = draw(&gpu, &mut renderer, &mut rt, size); + + let scaled = one(&seen, 1); + near(scaled.rect, [4.0 * k, 4.0 * k, 24.0 * k, 24.0 * k], "El::scale grows the rect about its centre"); + assert_eq!(scaled.scale, 1.5 * k); + presented(&scaled, &find(&rt, "scaled"), k, "scaled"); + let offset = one(&seen, 2); + near(offset.rect, [45.0 * k, 11.0 * k, 16.0 * k, 16.0 * k], "El::offset moves the rect"); + assert_eq!(offset.scale, k); + let child = one(&seen, 4); + assert_eq!(child.scale, 2.0 * k, "an ancestor's scale reaches the slot"); + presented(&child, &find(&rt, "child"), k, "child of a scaled parent"); + + // Rotation isn't in the slot's record: the slot stays upright inside a turned layer. + let rotated = one(&seen, 3); + near(rotated.rect, [8.0 * k, 40.0 * k, 16.0 * k, 16.0 * k], "upright rect"); + assert_eq!(rotated.scale, k); + assert!(rotated.in_layer && (rotated.turn - 0.5).abs() < 1e-4, "{rotated:?}"); + + rt.update(|s, _| s.extra = true); + let mut entering = 0; + for _ in 0..60 { + rt.frame(1.0 / 60.0); + let seen = draw(&gpu, &mut renderer, &mut rt, size); + let slot = one(&seen, 5); + let e = find(&rt, "moving"); + presented(&slot, &e, k, "entering"); + if e.scale < 0.999 { + entering += 1; + assert!(slot.rect[1] > 96.0 * k, "slides in from below: {slot:?}"); + assert!(slot.in_layer && (slot.opacity - e.opacity).abs() < 1e-4, "fades in through its layer: {slot:?}"); + } + } + assert!(entering >= 3, "the entrance played over {entering} frames"); + + rt.update(|s, _| s.extra = false); + let mut exiting = 0; + for _ in 0..60 { + rt.frame(1.0 / 60.0); + let seen = draw(&gpu, &mut renderer, &mut rt, size); + let Some(slot) = seen.iter().find(|s| s.mark == 5) else { continue }; + let e = find(&rt, "moving"); + assert!(e.exiting); + presented(slot, &e, k, "exiting"); + if e.scale < 0.999 { exiting += 1; } + } + assert!(exiting >= 3, "the exit played over {exiting} frames"); +} diff --git a/app/vendor/rune/crates/rune/tests/integration/effect_slot.rs b/app/vendor/rune/crates/rune/tests/integration/effect_slot.rs new file mode 100644 index 0000000..321e8d6 --- /dev/null +++ b/app/vendor/rune/crates/rune/tests/integration/effect_slot.rs @@ -0,0 +1,511 @@ +//! Effect slots (`El::effect`) and the compositor hooks around them: a compositor draws its own +//! pass at the slot, inside isolated layers, clipped like the primitives around it, in either +//! blend mode and in every format it is handed. + +use std::sync::{Arc, Mutex}; + +use rune::color::{hex, srgb_decode, srgb_encode}; +use rune::compose::{Compositor, Frame}; +use rune::render::{CLIP_WGSL, EffectSite, KIND_EFFECT}; +use rune::{App, AppSpec, Cx, El, effect, el}; + +const SHADER: &str = " +struct U { rect: vec4f, clip: vec4f, fade: vec4<u32>, frame: vec4f, color: vec4f, flags: vec4f } +@group(0) @binding(0) var<uniform> u: U; +struct V { @builtin(position) pos: vec4f } +@vertex fn vs(@builtin(vertex_index) vi: u32) -> V { + let c = vec2f(f32(vi & 1u), f32(vi >> 1u)); + let l = (u.rect.xy + c * u.rect.zw - u.frame.xy) / u.frame.zw; + return V(vec4f(l.x * 2.0 - 1.0, 1.0 - l.y * 2.0, 0.0, 1.0)); +} +fn enc(x: vec3f) -> vec3f { + return select(1.055 * pow(x, vec3f(1.0 / 2.4)) - 0.055, x * 12.92, x <= vec3f(0.0031308)); +} +@fragment fn fs(v: V) -> @location(0) vec4f { + let a = u.color.a * clip_alpha(v.pos.xy + u.frame.xy, u.clip, u.fade); + var rgb = u.color.rgb; + if (u.flags.x > 0.5) { rgb = enc(rgb); } + return vec4f(rgb * a, a); +} +"; + +/// Paints every effect slot and its bleed solid red, clipped like the instance asks (or not at +/// all, with `ignore_clip`), with one pipeline per target format. It never applies an opacity: +/// Rune must. +struct Flat { + pipes: Vec<(wgpu::TextureFormat, wgpu::RenderPipeline)>, + bgl: Option<wgpu::BindGroupLayout>, + formats: Arc<Mutex<Vec<wgpu::TextureFormat>>>, + ignore_clip: bool, +} + +impl Flat { + fn new(formats: Arc<Mutex<Vec<wgpu::TextureFormat>>>) -> Self { + Flat { pipes: Vec::new(), bgl: None, formats, ignore_clip: false } + } + + fn draw(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, pass: &mut wgpu::RenderPass<'_>, s: &EffectSite<'_>) { + let bgl = self.bgl.get_or_insert_with(|| device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + label: None, + entries: &[wgpu::BindGroupLayoutEntry { + binding: 0, + visibility: wgpu::ShaderStages::VERTEX_FRAGMENT, + ty: wgpu::BindingType::Buffer { ty: wgpu::BufferBindingType::Uniform, has_dynamic_offset: false, min_binding_size: None }, + count: None, + }], + })); + if !self.pipes.iter().any(|(f, _)| *f == s.format) { + self.formats.lock().unwrap().push(s.format); + let module = device.create_shader_module(wgpu::ShaderModuleDescriptor { + label: None, + source: wgpu::ShaderSource::Wgsl(format!("{CLIP_WGSL}\n{SHADER}").into()), + }); + let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + label: None, bind_group_layouts: &[Some(bgl)], immediate_size: 0, + }); + let pipe = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { + label: None, + layout: Some(&layout), + vertex: wgpu::VertexState { module: &module, entry_point: Some("vs"), compilation_options: Default::default(), buffers: &[] }, + primitive: wgpu::PrimitiveState { topology: wgpu::PrimitiveTopology::TriangleStrip, ..Default::default() }, + depth_stencil: None, + multisample: Default::default(), + fragment: Some(wgpu::FragmentState { + module: &module, + entry_point: Some("fs"), + compilation_options: Default::default(), + targets: &[Some(wgpu::ColorTargetState { + format: s.format, + blend: Some(wgpu::BlendState::PREMULTIPLIED_ALPHA_BLENDING), + write_mask: wgpu::ColorWrites::ALL, + })], + }), + multiview_mask: None, + cache: None, + }); + self.pipes.push((s.format, pipe)); + } + let i = s.instance; + assert_eq!(i.fill[3], 1.0, "a slot's opacity is Rune's to apply"); + assert_eq!(s.scale, i.params[3], "EffectSite::scale matches the slot's params[3]"); + let bleed = i.params[2]; + let mut data = [0.0f32; 24]; + data[0..4].copy_from_slice(&[i.rect[0] - bleed, i.rect[1] - bleed, i.rect[2] + 2.0 * bleed, i.rect[3] + 2.0 * bleed]); + if self.ignore_clip { + data[4..8].copy_from_slice(&rune::render::NO_CLIP); + } else { + data[4..8].copy_from_slice(&i.clip); + for k in 0..4 { data[8 + k] = f32::from_bits(i.fade[k]); } + } + data[12..14].copy_from_slice(&s.origin); + data[14] = s.size[0] as f32; + data[15] = s.size[1] as f32; + data[16..20].copy_from_slice(&[1.0, 0.0, 0.0, 1.0]); + data[20] = if s.srgb_blend { 1.0 } else { 0.0 }; + let buffer = device.create_buffer(&wgpu::BufferDescriptor { + label: None, size: 96, usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, mapped_at_creation: false, + }); + queue.write_buffer(&buffer, 0, bytemuck::cast_slice(&data)); + let group = device.create_bind_group(&wgpu::BindGroupDescriptor { + label: None, layout: bgl, entries: &[wgpu::BindGroupEntry { binding: 0, resource: buffer.as_entire_binding() }], + }); + pass.set_pipeline(&self.pipes.iter().find(|(f, _)| *f == s.format).unwrap().1); + pass.set_bind_group(0, &group, &[]); + pass.draw(0..4, 0..1); + } +} + +impl Compositor<()> for Flat { + fn render(&mut self, f: &mut Frame<'_, ()>) { + let (device, queue, size) = (f.device, f.queue, f.size); + let clear = f.rt.clear_color(); + let count = f.rt.instances.len() as u32; + f.ui.prepare(device, queue, &mut f.rt.text.atlas, &f.rt.instances, size); + let mut hook = |pass: &mut wgpu::RenderPass<'_>, s: &EffectSite<'_>| self.draw(device, queue, pass, s); + f.ui.encode_layers_with(f.encoder, &mut hook); + let mut pass = f.encoder.begin_render_pass(&wgpu::RenderPassDescriptor { + label: Some("frame"), + color_attachments: &[Some(wgpu::RenderPassColorAttachment { + view: f.target, + depth_slice: None, + resolve_target: None, + ops: wgpu::Operations { + load: wgpu::LoadOp::Clear(wgpu::Color { r: clear[0] as f64, g: clear[1] as f64, b: clear[2] as f64, a: clear[3] as f64 }), + store: wgpu::StoreOp::Store, + }, + })], + depth_stencil_attachment: None, + timestamp_writes: None, + occlusion_query_set: None, + multiview_mask: None, + }); + f.ui.draw_range_with(&mut pass, f.format, 0..count, &mut hook); + } +} + +/// Counts effect slots in the stream and draws the default frame, so nothing paints them. +struct Plain(Arc<Mutex<usize>>); + +impl Compositor<()> for Plain { + fn render(&mut self, f: &mut Frame<'_, ()>) { + *self.0.lock().unwrap() = f.rt.instances.iter().filter(|i| i.params[1] == KIND_EFFECT).count(); + f.draw_ui(); + } +} + +fn snap(name: &'static str, view: fn(&(), &mut Cx<()>) -> El, srgb: bool, comp: impl Compositor<()>) -> (u32, Vec<u8>) { + let dir = std::env::temp_dir().join(format!("rune-effect-slot-{name}-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("snap.png"); + App::new(AppSpec::new(name, (96.0, 96.0), || (), view)) + .compositor(comp) + .srgb_blend(srgb) + .args(["--snap".to_string(), path.to_str().unwrap().to_string(), "--scale".to_string(), "1".to_string()]) + .run(); + let mut reader = png::Decoder::new(std::io::BufReader::new(std::fs::File::open(&path).unwrap())).read_info().unwrap(); + let mut buf = vec![0u8; reader.output_buffer_size().unwrap()]; + let info = reader.next_frame(&mut buf).unwrap(); + buf.truncate(info.buffer_size()); + std::fs::remove_dir_all(&dir).unwrap(); + (info.width, buf) +} + +fn px(rgba: &[u8], width: u32, x: u32, y: u32) -> [u8; 3] { + let at = ((y * width + x) * 4) as usize; + [rgba[at], rgba[at + 1], rgba[at + 2]] +} + +/// What `top` at `alpha` over the grey background reads as, in the blend mode's own arithmetic. +fn over(top: [f32; 3], alpha: f32, srgb: bool) -> [u8; 3] { + let bg = 32.0 / 255.0; + std::array::from_fn(|c| { + let v = if srgb { top[c] * alpha + bg * (1.0 - alpha) } + else { srgb_encode(srgb_decode(top[c]) * alpha + srgb_decode(bg) * (1.0 - alpha)) }; + (v * 255.0).round() as u8 + }) +} + +fn near(a: [u8; 3], b: [u8; 3], what: &str) { + assert!(a.iter().zip(b).all(|(a, b)| a.abs_diff(b) <= 3), "{what}: got {a:?}, expected {b:?}"); +} + +const RED: [f32; 3] = [1.0, 0.0, 0.0]; +const BLUE: [f32; 3] = [0.0, 0.0, 1.0]; + +fn background() -> El { + el().size(96.0, 96.0).fill(hex("#202020").unwrap()) +} + +fn faded(_: &(), _: &mut Cx<()>) -> El { + background().child( + el().size(64.0, 64.0).absolute(16.0, 16.0).opacity(0.5) + .child(effect(1).absolute(0.0, 0.0).size(64.0, 64.0)) + .child(el().absolute(40.0, 40.0).size(24.0, 24.0).fill(hex("#0000ff").unwrap())), + ) + .child(effect(2).absolute(84.0, 84.0).size(8.0, 8.0)) +} + +fn faded_rounded(_: &(), _: &mut Cx<()>) -> El { + background().child( + el().size(64.0, 64.0).absolute(16.0, 16.0).opacity(0.5).clip_rounded(24.0) + .child(effect(1).absolute(0.0, 0.0).size(64.0, 64.0)) + .child(el().absolute(40.0, 40.0).size(24.0, 24.0).fill(hex("#0000ff").unwrap())), + ) +} + +fn rounded(_: &(), _: &mut Cx<()>) -> El { + background().child(el().size(64.0, 64.0).absolute(16.0, 16.0).clip_rounded(24.0).child(effect(1).size(64.0, 64.0))) +} + +fn opaque(_: &(), _: &mut Cx<()>) -> El { + background().child(effect(1).absolute(16.0, 16.0).size(64.0, 64.0)) +} + +#[test] +fn effect_in_a_faded_layer_is_faded_and_under_later_content() { + for srgb in [false, true] { + let formats = Arc::default(); + let (w, rgba) = snap("faded", faded, srgb, Flat::new(Arc::clone(&formats))); + near(px(&rgba, w, 24, 24), over(RED, 0.5, srgb), "effect alone, half faded"); + near(px(&rgba, w, 68, 68), over(BLUE, 0.5, srgb), "later content covers the effect inside the layer"); + near(px(&rgba, w, 8, 8), over([32.0 / 255.0; 3], 1.0, srgb), "outside the card"); + near(px(&rgba, w, 88, 88), over(RED, 1.0, srgb), "a slot outside any layer"); + // One compositor drew into the layer's float target and the frame target. + let formats = formats.lock().unwrap(); + assert_eq!(formats.len(), 2, "{formats:?}"); + assert!(formats.contains(&wgpu::TextureFormat::Rgba16Float)); + } +} + +#[test] +fn rounded_clip_cuts_the_effect_corner() { + for srgb in [false, true] { + let (w, rgba) = snap("rounded", rounded, srgb, Flat::new(Arc::default())); + near(px(&rgba, w, 17, 17), over([32.0 / 255.0; 3], 1.0, srgb), "corner is clipped away"); + near(px(&rgba, w, 48, 48), over(RED, 1.0, srgb), "centre"); + near(px(&rgba, w, 48, 17), over(RED, 1.0, srgb), "straight edge is not cut"); + let (w, rgba) = snap("faded-rounded", faded_rounded, srgb, Flat::new(Arc::default())); + near(px(&rgba, w, 17, 17), over([32.0 / 255.0; 3], 1.0, srgb), "layer corner is clipped away"); + near(px(&rgba, w, 24, 48), over(RED, 0.5, srgb), "layer centre-left, half faded"); + } +} + +#[test] +fn opaque_effects_match_across_blend_modes() { + let (w, linear) = snap("opaque-linear", opaque, false, Flat::new(Arc::default())); + let (_, gamma) = snap("opaque-gamma", opaque, true, Flat::new(Arc::default())); + assert_eq!(linear.len(), gamma.len()); + let worst = linear.chunks(4).zip(gamma.chunks(4)).flat_map(|(a, b)| a.iter().zip(b).map(|(a, b)| a.abs_diff(*b))).max().unwrap(); + assert!(worst <= 2, "modes differ by {worst}"); + near(px(&linear, w, 48, 48), [255, 0, 0], "effect covers its rect"); +} + +fn faded_leaf(_: &(), _: &mut Cx<()>) -> El { + background().child(effect(1).absolute(16.0, 16.0).size(64.0, 64.0).opacity(0.5)) +} + +fn faded_only_child(_: &(), _: &mut Cx<()>) -> El { + background().child(el().absolute(16.0, 16.0).size(64.0, 64.0).opacity(0.5).child(effect(1).size(64.0, 64.0))) +} + +fn dimmed(_: &(), _: &mut Cx<()>) -> El { + background().child(effect(1).absolute(16.0, 16.0).size(64.0, 64.0).dim(0.5)) +} + +fn faded_rounded_leaf(_: &(), _: &mut Cx<()>) -> El { + background().child(el().size(64.0, 64.0).absolute(16.0, 16.0).clip_rounded(24.0) + .child(effect(1).size(64.0, 64.0).opacity(0.5))) +} + +/// A faded slot gets a layer that applies its opacity, whichever way it was faded, so a +/// compositor that paints at full strength is still faded. +#[test] +fn a_faded_slot_is_faded_for_the_compositor() { + for srgb in [false, true] { + for (name, view) in [("leaf", faded_leaf as fn(&(), &mut Cx<()>) -> El), ("only-child", faded_only_child), ("dimmed", dimmed)] { + let (w, rgba) = snap(name, view, srgb, Flat::new(Arc::default())); + near(px(&rgba, w, 48, 48), over(RED, 0.5, srgb), name); + near(px(&rgba, w, 8, 8), over([32.0 / 255.0; 3], 1.0, srgb), name); + } + let (w, rgba) = snap("faded-rounded-leaf", faded_rounded_leaf, srgb, Flat::new(Arc::default())); + near(px(&rgba, w, 17, 17), over([32.0 / 255.0; 3], 1.0, srgb), "faded slot keeps its rounded clip"); + near(px(&rgba, w, 48, 48), over(RED, 0.5, srgb), "faded slot under a rounded clip"); + } +} + +fn bleeding(_: &(), _: &mut Cx<()>) -> El { + background().child(el().absolute(16.0, 16.0).size(64.0, 64.0).clip_fade(0.0, 0.0, 0.0, 0.0) + .child(effect(1).effect_bleed(16.0).absolute(-12.0, 0.0).size(8.0, 8.0))) +} + +/// A slot whose rect lies outside its clip still paints the bleed that reaches in, and a +/// compositor that ignores the clip is held to it by the scissor. +#[test] +fn bleed_reaches_in_and_the_scissor_holds_the_clip() { + let (w, rgba) = snap("bleeding", bleeding, false, Flat { ignore_clip: true, ..Flat::new(Arc::default()) }); + near(px(&rgba, w, 20, 20), over(RED, 1.0, false), "bleed inside the clip"); + near(px(&rgba, w, 10, 20), over([32.0 / 255.0; 3], 1.0, false), "bleed outside the clip"); + near(px(&rgba, w, 20, 44), over([32.0 / 255.0; 3], 1.0, false), "past the bleed"); +} + +#[test] +fn an_unpainted_effect_slot_draws_nothing() { + let slots = Arc::default(); + let (w, rgba) = snap("unpainted", opaque, false, Plain(Arc::clone(&slots))); + assert_eq!(*slots.lock().unwrap(), 1); + let grey = px(&rgba, w, 8, 8); + for (x, y) in [(16, 16), (48, 48), (79, 79)] { + assert_eq!(px(&rgba, w, x, y), grey, "({x}, {y})"); + } +} + +struct ScaleProbe(Arc<Mutex<Vec<(u32, f32, f32)>>>); + +impl Compositor<()> for ScaleProbe { + fn render(&mut self, f: &mut Frame<'_, ()>) { + let (device, queue, size) = (f.device, f.queue, f.size); + let clear = f.rt.clear_color(); + let count = f.rt.instances.len() as u32; + let marks = f.rt.marks.clone(); + f.ui.prepare(device, queue, &mut f.rt.text.atlas, &f.rt.instances, size); + let log = &self.0; + let mut hook = |_: &mut wgpu::RenderPass<'_>, s: &EffectSite<'_>| { + assert_eq!(s.scale, s.instance.params[3]); + log.lock().unwrap().push((marks[s.index as usize], s.scale, s.instance.params[2])); + }; + f.ui.encode_layers_with(f.encoder, &mut hook); + let mut pass = f.encoder.begin_render_pass(&wgpu::RenderPassDescriptor { + label: Some("frame"), + color_attachments: &[Some(wgpu::RenderPassColorAttachment { + view: f.target, + depth_slice: None, + resolve_target: None, + ops: wgpu::Operations { + load: wgpu::LoadOp::Clear(wgpu::Color { r: clear[0] as f64, g: clear[1] as f64, b: clear[2] as f64, a: clear[3] as f64 }), + store: wgpu::StoreOp::Store, + }, + })], + depth_stencil_attachment: None, + timestamp_writes: None, + occlusion_query_set: None, + multiview_mask: None, + }); + f.ui.draw_range_with(&mut pass, f.format, 0..count, &mut hook); + } +} + +fn scaled_slots(_: &(), _: &mut Cx<()>) -> El { + background() + .child(effect(1).absolute(8.0, 8.0).size(16.0, 16.0)) + .child( + el().absolute(32.0, 32.0).size(32.0, 32.0).scale(1.5).child( + el().size(16.0, 16.0).live_scale(&rune::Live::new(2.0)).child(effect(2).size(16.0, 16.0)), + ), + ) +} + +#[test] +fn slot_reports_device_pixels_per_point_without_bleed() { + let seen = Arc::default(); + let dir = std::env::temp_dir().join(format!("rune-effect-slot-scale-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("snap.png"); + App::new(AppSpec::new("slot-scale", (96.0, 96.0), || (), scaled_slots)) + .compositor(ScaleProbe(Arc::clone(&seen))) + .args(["--snap".to_string(), path.to_str().unwrap().to_string(), "--scale".to_string(), "2".to_string()]) + .run(); + std::fs::remove_dir_all(&dir).unwrap(); + let got = seen.lock().unwrap().clone(); + assert_eq!(got, vec![(1, 2.0, 0.0), (2, 6.0, 0.0)]); +} + +struct BackdropProbe(Arc<Mutex<Vec<(u32, &'static str, bool, bool)>>>); + +impl Compositor<()> for BackdropProbe { + fn render(&mut self, f: &mut Frame<'_, ()>) { + let (device, queue, size) = (f.device, f.queue, f.size); + let clear = f.rt.clear_color(); + let marks = f.rt.marks.clone(); + f.ui.prepare(device, queue, &mut f.rt.text.atlas, &f.rt.instances, size); + let log = &self.0; + f.ui.draw_with_backdrop(f.encoder, f.target, clear, &mut |phase, s| { + let phase_name = match phase { + rune::render::EffectPhase::Backdrop(_) => "backdrop", + rune::render::EffectPhase::Draw(_) => "draw", + }; + log.lock().unwrap().push((marks[s.index as usize], phase_name, s.backdrop.is_some(), s.in_layer)); + }); + } +} + +fn mixed_backdrop_slots(_: &(), _: &mut Cx<()>) -> El { + background() + .child(effect(1).absolute(8.0, 8.0).size(16.0, 16.0)) + .child(effect(2).effect_backdrop(true).absolute(32.0, 8.0).size(16.0, 16.0)) + .child( + el().absolute(8.0, 40.0).size(48.0, 32.0).opacity(0.5) + .child(el().size(16.0, 16.0).fill(hex("#00ff00").unwrap())) + .child(effect(3).effect_backdrop(true).size(16.0, 16.0)), + ) +} + +#[test] +fn only_backdrop_slots_split_the_pass_and_receive_a_backdrop_view() { + let seen = Arc::default(); + let _ = snap("backdrop-probe", mixed_backdrop_slots, false, BackdropProbe(Arc::clone(&seen))); + let got = seen.lock().unwrap().clone(); + assert_eq!( + got, + vec![ + (3, "backdrop", true, true), + (3, "draw", true, true), + (1, "draw", false, false), + (2, "backdrop", true, false), + (2, "draw", true, false), + ], + ); +} + +#[test] +fn inert_backdrop_slots_draw_but_hidden_and_offscreen_subtrees_do_not() { + let seen = Arc::default(); + let _ = snap("backdrop-visibility", |_, _| background() + .child(el().inert().absolute(8.0, 8.0).size(24.0, 24.0) + .child(effect(1).effect_backdrop(true).size(24.0, 24.0))) + .child(el().absolute(200.0, 200.0).size(24.0, 24.0) + .child(effect(2).effect_backdrop(true).size(24.0, 24.0))) + .child(el().opacity(0.0).absolute(40.0, 8.0).size(24.0, 24.0) + .child(effect(3).effect_backdrop(true).size(24.0, 24.0))), + false, BackdropProbe(Arc::clone(&seen))); + assert_eq!(*seen.lock().unwrap(), vec![(1, "backdrop", true, false), (1, "draw", true, false)]); +} + +struct CacheSlotProbe { + frame_no: u32, + flat: Flat, + log: Arc<Mutex<Vec<(u32, usize, bool, bool)>>>, +} + +impl Compositor<()> for CacheSlotProbe { + fn render(&mut self, f: &mut Frame<'_, ()>) { + self.frame_no += 1; + let frame_no = self.frame_no; + let (device, queue, size) = (f.device, f.queue, f.size); + let clear = f.rt.clear_color(); + f.ui.prepare(device, queue, &mut f.rt.text.atlas, &f.rt.instances, size); + let stats = f.ui.layer_stats(); + let flat = &mut self.flat; + let log = &self.log; + f.ui.draw_with_backdrop(f.encoder, f.target, clear, &mut |phase, s| { + if let rune::render::EffectPhase::Draw(pass) = phase { + log.lock().unwrap().push((frame_no, stats.targets, s.backdrop.is_some(), s.in_layer)); + // Frame 1 leaves the slot unpainted; frame 2 paints solid red, proving the + // `.cache()` subtree was not frozen on frame 1's raster. + if frame_no >= 2 { + flat.draw(device, queue, pass, s); + } + } + }); + } + fn animating(&self) -> bool { + self.frame_no < 2 + } +} + +fn cached_subtree_with_effect(_: &(), _: &mut Cx<()>) -> El { + background().child( + el().key("cached-card").cache().absolute(16.0, 16.0).size(64.0, 64.0) + .fill(hex("#282828").unwrap()) + .child(effect(1).effect_backdrop(true).absolute(8.0, 8.0).size(48.0, 48.0)), + ) +} + +#[test] +fn effect_slot_in_cached_subtree_draws_live_and_never_caches() { + let dir = std::env::temp_dir().join(format!("rune-effect-slot-cache-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let log = Arc::default(); + App::new(AppSpec::new("slot-in-cache", (96.0, 96.0), || (), cached_subtree_with_effect)) + .compositor(CacheSlotProbe { frame_no: 0, flat: Flat::new(Arc::default()), log: Arc::clone(&log) }) + .args([ + "--frames".to_string(), + "2".to_string(), + "--out".to_string(), + dir.to_str().unwrap().to_string(), + "--scale".to_string(), + "1".to_string(), + ]) + .run(); + let frame2 = dir.join("frame_0001.png"); + let mut reader = png::Decoder::new(std::io::BufReader::new(std::fs::File::open(&frame2).unwrap())).read_info().unwrap(); + let mut buf = vec![0u8; reader.output_buffer_size().unwrap()]; + let info = reader.next_frame(&mut buf).unwrap(); + buf.truncate(info.buffer_size()); + std::fs::remove_dir_all(&dir).unwrap(); + + let got = log.lock().unwrap().clone(); + assert_eq!(got, vec![(1, 0, true, false), (2, 0, true, false)], "cached subtree with effect slot stays live with 0 cache targets"); + // Frame 2 must show the red paint from frame 2, not frame 1's unpainted #282828. + let center = px(&buf, info.width, 40, 40); + assert!(center[0] > 240 && center[1] < 15 && center[2] < 15, "frame 2 drew live red at (40, 40): {center:?}"); +} diff --git a/app/vendor/rune/crates/rune/tests/integration/enter_delay.rs b/app/vendor/rune/crates/rune/tests/integration/enter_delay.rs new file mode 100644 index 0000000..26b174d --- /dev/null +++ b/app/vendor/rune/crates/rune/tests/integration/enter_delay.rs @@ -0,0 +1,168 @@ +//! `El::enter_delay`: a new element holds its whole insertion effect, then offset and opacity +//! play on one progress. Waiting draws nothing and asks for one wake; an entrance nobody would +//! see ignores the delay. +use rune::{Cx, El, Env, Runtime, Stagger, Transition, col, el}; + +const RISE: f32 = 12.0; +const HZ: f64 = 120.0; + +#[derive(Default)] +struct S { + rows: usize, + delay: f32, + own_scale: f32, + window_scale: f32, +} + +fn view(s: &S, cx: &mut Cx<S>) -> El { + if s.window_scale > 0.0 { cx.time_scale(s.window_scale); } + let stagger = Stagger::new(s.delay); + let rows = (0..s.rows).map(|i| { + let mut row = el() + .key(format!("row{i}")) + .size(100.0, 20.0) + .fill(rune::Color::BLACK) + .transition(Transition::offset(0.0, RISE).combined(Transition::opacity())) + .enter_delay(stagger.start(s.delay).delay(i, s.rows)); + if s.own_scale > 0.0 { row = row.time_scale(s.own_scale); } + row + }); + col().w_full().h_full().children(rows) +} + +fn app(s: S) -> Runtime<S> { + let mut rt = Runtime::new(s, view, (200.0, 200.0), Env::new(true, 1.0)); + rt.frame(0.0); + rt +} + +/// (offset progress, opacity) of row `i`, or None once it's gone. +fn row(rt: &Runtime<S>, i: usize) -> Option<(f32, f32)> { + let key = format!("row{i}"); + let e = rt.elements().into_iter().find(|e| e.key.as_deref() == Some(key.as_str()))?; + Some((1.0 - (e.rect[1] - e.target[1]) / RISE, e.opacity)) +} + +#[test] +fn waits_whole_then_moves_offset_and_opacity_in_lockstep() { + let mut rt = app(S { delay: 0.2, ..S::default() }); + rt.update(|s, _| s.rows = 1); + let mut t = 0.0; + let mut moved = false; + while t < 1.5 { + rt.frame(1.0 / HZ); + t += 1.0 / HZ; + let (offset, opacity) = row(&rt, 0).unwrap(); + if t < 0.2 - 1e-6 { + assert_eq!((offset, opacity), (0.0, 0.0), "t={t:.3}: waits at the insertion effect"); + } else { + assert!((offset - opacity).abs() < 0.02, "t={t:.3}: offset {offset} and opacity {opacity}"); + moved |= opacity > 0.5; + } + } + assert!(moved); + assert_eq!(row(&rt, 0), Some((1.0, 1.0))); +} + +#[test] +fn waiting_sleeps_until_the_start() { + let mut rt = app(S { delay: 0.5, ..S::default() }); + rt.update(|s, _| s.rows = 1); + assert!(!rt.frame(1.0 / HZ), "waiting draws nothing new"); + let wake = rt.wake_deadline().expect("a wake for the start"); + assert!((wake - 0.5).abs() < 1.5 / HZ, "wakes when it starts: {wake}"); + // A host that sleeps until then gets one frame there, the start. + rt.frame(wake - 1.0 / HZ); + assert_eq!(row(&rt, 0).unwrap().1, 0.0); + assert!(rt.frame(0.1), "the entrance runs"); + assert!(row(&rt, 0).unwrap().1 > 0.0); +} + +#[test] +fn time_scales_stretch_the_delay() { + for (own_scale, window_scale) in [(0.5, 0.0), (0.0, 0.5)] { + let mut rt = app(S { delay: 0.2, own_scale, window_scale, ..S::default() }); + rt.update(|s, _| s.rows = 1); + rt.frame(0.38); + assert_eq!(row(&rt, 0).unwrap().1, 0.0, "{own_scale} {window_scale}: still waits at 0.38 s"); + rt.frame(0.1); + assert!(row(&rt, 0).unwrap().1 > 0.0, "{own_scale} {window_scale}: enters after 0.4 s"); + } +} + +#[test] +fn removed_while_waiting_doesnt_flash() { + let mut rt = app(S { delay: 0.3, ..S::default() }); + rt.update(|s, _| s.rows = 1); + rt.frame(0.1); + rt.update(|s, _| s.rows = 0); + for _ in 0..120 { + rt.frame(1.0 / HZ); + let Some((_, opacity)) = row(&rt, 0) else { return }; + assert_eq!(opacity, 0.0, "no flash"); + } + panic!("never left"); +} + +#[test] +fn unseen_entrances_ignore_the_delay() { + // The first frame. + let rt = app(S { rows: 1, delay: 0.3, ..S::default() }); + assert_eq!(row(&rt, 0), Some((1.0, 1.0))); + // An instant commit. + let mut rt = app(S { delay: 0.3, ..S::default() }); + rt.update(|s, tx| { + s.rows = 1; + tx.instant(); + }); + rt.frame(1.0 / HZ); + assert_eq!(row(&rt, 0), Some((1.0, 1.0))); + // A settle while it waits. + let mut rt = app(S { delay: 0.3, ..S::default() }); + rt.update(|s, _| s.rows = 1); + rt.frame(0.1); + rt.settle_all(); + assert!(!rt.frame(1.0 / HZ)); + assert_eq!(row(&rt, 0), Some((1.0, 1.0))); +} + +#[test] +fn reduce_motion_keeps_the_delay_and_only_fades() { + let mut rt = app(S { delay: 0.3, ..S::default() }); + rt.set_system_reduced_motion(true); + rt.frame(0.0); + rt.update(|s, _| s.rows = 1); + let mut t = 0.0; + let mut shown = None; + while t < 1.0 { + rt.frame(1.0 / HZ); + t += 1.0 / HZ; + let (offset, opacity) = row(&rt, 0).unwrap(); + assert_eq!(offset, 1.0, "t={t:.3}: nothing travels"); + if t < 0.3 - 1e-6 { assert_eq!(opacity, 0.0, "t={t:.3}: the fade waits"); } + if opacity >= 1.0 && shown.is_none() { shown = Some(t); } + } + let shown = shown.unwrap(); + assert!(shown > 0.3 && shown < 0.6, "the short fade, after the delay: {shown}"); +} + +#[test] +fn a_staggered_list_of_five_enters_in_order() { + let mut rt = app(S { delay: 0.05, ..S::default() }); + rt.update(|s, _| s.rows = 5); + let mut starts = [None; 5]; + let mut t = 0.0; + while t < 1.5 { + rt.frame(1.0 / HZ); + t += 1.0 / HZ; + for (i, start) in starts.iter_mut().enumerate() { + let (offset, opacity) = row(&rt, i).unwrap(); + assert!((offset - opacity).abs() < 0.02, "row {i} t={t:.3}: offset {offset}, opacity {opacity}"); + if opacity > 0.0 && start.is_none() { *start = Some(t); } + } + } + let starts = starts.map(Option::unwrap); + for (i, w) in starts.windows(2).enumerate() { + assert!((w[1] - w[0] - 0.05).abs() < 1.5 / HZ, "row {} starts 50 ms after row {i}: {starts:?}", i + 1); + } +} diff --git a/app/vendor/rune/crates/rune/tests/integration/env_compat.rs b/app/vendor/rune/crates/rune/tests/integration/env_compat.rs new file mode 100644 index 0000000..8260275 --- /dev/null +++ b/app/vendor/rune/crates/rune/tests/integration/env_compat.rs @@ -0,0 +1,12 @@ +use rune::Env; + +// External consumers construct and exhaustively destructure this exact two-field API. +// Adding even a private field must fail this integration test's compilation. +const ENV: Env = Env { system_dark: true, scale: 2.0 }; + +#[test] +fn env_keeps_its_exhaustive_literal_api() { + let Env { system_dark, scale } = ENV; + assert!(system_dark); + assert_eq!(scale, 2.0); +} diff --git a/app/vendor/rune/crates/rune/tests/integration/expressive_motion.rs b/app/vendor/rune/crates/rune/tests/integration/expressive_motion.rs new file mode 100644 index 0000000..3ebc3ba --- /dev/null +++ b/app/vendor/rune/crates/rune/tests/integration/expressive_motion.rs @@ -0,0 +1,393 @@ +//! Expressive presses: `El::scale` springs, `El::origin` pins the pivot, `El::rotate` turns a +//! subtree (and its hit tests), and shadow geometry springs with the element. +use rune::{Color, Cx, El, Env, Runtime, Spring, col, el}; + +#[derive(Default)] +struct S { + k: f32, + pressed: Vec<&'static str>, +} + +fn view(s: &S, _: &mut Cx<S>) -> El { + let k = if s.k == 0.0 { 1.0 } else { s.k }; + col().w_full().h_full().items_start().padding(50.0).child( + el().key("a") + .size(100.0, 40.0) + .fill(Color::WHITE) + .motion(Spring::new(0.3, 0.0)) + .scale(k) + .on_press(|s: &mut S| s.pressed.push("a")), + ) +} + +fn app() -> Runtime<S> { + let mut rt = Runtime::new(S::default(), view, (200.0, 200.0), Env::new(true, 1.0)); + rt.frame(0.0); + rt +} + +fn rect<T>(rt: &Runtime<T>, key: &str) -> [f32; 4] { + rt.elements().into_iter().find(|e| e.key.as_deref() == Some(key)).unwrap().rect +} + +fn settle<T>(rt: &mut Runtime<T>) { + for _ in 0..90 { + rt.frame(1.0 / 60.0); + } +} + +fn click(rt: &mut Runtime<S>, x: f32, y: f32) { + rt.pointer_move(x, y); + rt.pointer_down(x, y); + rt.pointer_up(x, y); + rt.frame(0.0); +} + +#[test] +fn a_scale_change_springs_to_rest_and_hits_follow_it() { + let mut rt = app(); + assert_eq!(rect(&rt, "a"), [50.0, 50.0, 100.0, 40.0]); + rt.update(|s, _| s.k = 0.5); + rt.frame(1.0 / 60.0); + let w = rect(&rt, "a")[2]; + assert!(w > 50.0 && w < 100.0, "mid-spring: {w}"); + settle(&mut rt); + assert_eq!(rect(&rt, "a"), [75.0, 60.0, 50.0, 20.0], "rests at half size about the centre"); + click(&mut rt, 60.0, 55.0); + assert!(rt.state.pressed.is_empty(), "outside the drawn rect"); + click(&mut rt, 80.0, 65.0); + assert_eq!(rt.state.pressed, ["a"]); +} + +#[test] +fn a_scale_change_lands_at_once_under_reduce_motion_and_in_an_instant_transaction() { + let mut rt = app(); + rt.set_system_reduced_motion(true); + rt.update(|s, _| s.k = 0.5); + rt.frame(1.0 / 60.0); + assert_eq!(rect(&rt, "a")[2], 50.0, "Reduce Motion"); + + let mut rt = app(); + rt.update(|s, tx| { + s.k = 2.0; + tx.instant(); + }); + rt.frame(1.0 / 60.0); + assert_eq!(rect(&rt, "a")[2], 200.0, "instant transaction"); +} + +#[test] +fn a_sprung_scale_multiplies_with_live_scale_and_press_scale() { + struct M { + k: f32, + live: rune::Live<f32>, + } + fn view(m: &M, _: &mut Cx<M>) -> El { + col().w_full().h_full().items_start().padding(50.0).child( + el().key("a").size(100.0, 40.0).fill(Color::WHITE).scale(m.k).live_scale(&m.live).press_scale(0.5).on_press(|_: &mut M| {}), + ) + } + let live = rune::Live::new(0.5f32); + let mut rt = Runtime::new(M { k: 1.0, live: live.clone() }, view, (200.0, 200.0), Env::new(true, 1.0)); + rt.frame(0.0); + rt.update(|m, _| m.k = 2.0); + settle(&mut rt); + assert_eq!(rect(&rt, "a")[2], 100.0, "2 x 0.5"); + rt.pointer_move(100.0, 70.0); + rt.pointer_down(100.0, 70.0); + settle(&mut rt); + assert_eq!(rect(&rt, "a")[2], 50.0, "2 x 0.5 x 0.5 while pressed"); + rt.pointer_up(100.0, 70.0); + live.set(1.0); + settle(&mut rt); + assert_eq!(rect(&rt, "a")[2], 200.0); +} + +#[test] +fn an_origin_at_the_bottom_edge_keeps_it_fixed_while_the_scale_springs() { + struct M { + k: f32, + live: rune::Live<f32>, + } + fn view(m: &M, _: &mut Cx<M>) -> El { + col().w_full().h_full().items_start().padding(50.0).child( + el().key("a").size(100.0, 40.0).fill(Color::WHITE).motion(Spring::new(0.3, 0.0)) + .origin(0.5, 1.0).scale(m.k).live_scale(&m.live).press_scale(0.5).on_press(|_: &mut M| {}), + ) + } + let live = rune::Live::new(1.0f32); + let mut rt = Runtime::new(M { k: 1.0, live: live.clone() }, view, (200.0, 200.0), Env::new(true, 1.0)); + rt.frame(0.0); + rt.update(|m, _| m.k = 0.5); + for f in 0..60 { + rt.frame(1.0 / 60.0); + let r = rect(&rt, "a"); + assert!((r[1] + r[3] - 90.0).abs() < 0.01, "frame {f}: bottom edge moved: {r:?}"); + assert!((r[0] + r[2] / 2.0 - 100.0).abs() < 0.01, "frame {f}: stays centred across: {r:?}"); + } + assert_eq!(rect(&rt, "a"), [75.0, 70.0, 50.0, 20.0]); + + // `live_scale` and `press_scale` pivot there too. + live.set(2.0); + rt.frame(0.0); + assert_eq!(rect(&rt, "a"), [50.0, 50.0, 100.0, 40.0]); + rt.pointer_move(100.0, 70.0); + rt.pointer_down(100.0, 70.0); + settle(&mut rt); + assert_eq!(rect(&rt, "a"), [75.0, 70.0, 50.0, 20.0]); +} + +#[test] +fn a_transition_scales_about_the_origin() { + fn view(show: &bool, _: &mut Cx<bool>) -> El { + let mut root = col().w_full().h_full().items_start().padding(50.0); + if *show { + root = root.child(el().key("a").size(100.0, 40.0).fill(Color::WHITE).origin(0.0, 0.0) + .transition(rune::Transition::scale(0.5))); + } + root + } + let mut rt = Runtime::new(false, view, (200.0, 200.0), Env::new(true, 1.0)); + rt.frame(0.0); + rt.update(|s, _| *s = true); + rt.frame(1.0 / 60.0); + let r = rect(&rt, "a"); + assert!(r[2] < 100.0, "entering: {r:?}"); + assert_eq!([r[0], r[1]], [50.0, 50.0], "grows from its top-left corner"); +} + +#[test] +fn shadow_geometry_springs_with_the_element() { + fn view(pressed: &bool, _: &mut Cx<bool>) -> El { + let sh = if *pressed { + rune::Shadow { x: 0.0, y: 2.0, blur: 4.0, spread: 0.0, color: Color::BLACK.alpha(0.3), inset: false } + } else { + rune::Shadow { x: 4.0, y: 10.0, blur: 20.0, spread: 2.0, color: Color::BLACK.alpha(0.3), inset: false } + }; + col().w_full().h_full().items_start().padding(50.0).child( + el().key("a").size(100.0, 40.0).fill(Color::WHITE).motion(Spring::new(0.3, 0.0)).box_shadow(sh), + ) + } + fn shadow(rt: &Runtime<bool>) -> ([f32; 4], f32) { + let q = rt.instances.iter().find(|q| q.params[1] == rune::render::KIND_SHADOW).expect("a shadow"); + (q.rect, q.params[2]) + } + let mut rt = Runtime::new(false, view, (200.0, 200.0), Env::new(true, 1.0)); + rt.frame(0.0); + let (rest, rest_sigma) = shadow(&rt); + assert_eq!(rest, [52.0, 58.0, 104.0, 44.0], "x 4, y 10, spread 2"); + rt.update(|s, _| *s = true); + rt.frame(1.0 / 60.0); + let (mid, mid_sigma) = shadow(&rt); + assert!(mid[1] > 52.0 && mid[1] < 58.0, "y between: {mid:?}"); + assert!(mid[0] > 50.0 && mid[0] < 52.0, "x between: {mid:?}"); + assert!(mid[2] > 100.0 && mid[2] < 104.0, "spread between: {mid:?}"); + assert!(mid_sigma < rest_sigma && mid_sigma > 2.0, "blur between: {mid_sigma}"); + settle(&mut rt); + assert_eq!(shadow(&rt), ([50.0, 52.0, 100.0, 40.0], 2.0)); + + let mut rt = Runtime::new(false, view, (200.0, 200.0), Env::new(true, 1.0)); + rt.frame(0.0); + rt.set_system_reduced_motion(true); + rt.update(|s, _| *s = true); + rt.frame(1.0 / 60.0); + assert_eq!(shadow(&rt).0, [50.0, 52.0, 100.0, 40.0], "lands at once under Reduce Motion"); +} + +#[test] +fn rotate_springs_turns_the_subtree_in_a_layer_and_hits_where_it_shows() { + fn view(turned: &bool, _: &mut Cx<bool>) -> El { + col().w_full().h_full().items_start().padding(50.0).child( + el().key("bar").size(100.0, 20.0).fill(Color::WHITE).motion(Spring::new(0.3, 0.0)) + .rotate(if *turned { std::f32::consts::FRAC_PI_2 } else { 0.0 }) + .on_press(|s: &mut bool| *s = !*s) + .child(el().key("dot").size(10.0, 10.0).fill(Color::BLACK)), + ) + } + fn turn(rt: &Runtime<bool>) -> Option<f32> { + rt.instances.iter().find(|q| q.params[1] == rune::render::KIND_LAYER).map(|q| q.border[1]) + } + let mut rt = Runtime::new(false, view, (200.0, 200.0), Env::new(true, 1.0)); + rt.frame(0.0); + assert_eq!(turn(&rt), None, "no layer while upright"); + // A press on its right end turns it a quarter, about its centre (100, 60). + rt.pointer_move(145.0, 60.0); + rt.pointer_down(145.0, 60.0); + rt.pointer_up(145.0, 60.0); + rt.frame(1.0 / 60.0); + let mid = turn(&rt).expect("a turned layer"); + assert!(mid > 0.0 && mid < std::f32::consts::FRAC_PI_2, "mid-spring: {mid}"); + settle(&mut rt); + assert!((turn(&rt).unwrap() - std::f32::consts::FRAC_PI_2).abs() < 1e-4); + let r = rect(&rt, "bar"); + assert!(r.iter().zip([90.0, 10.0, 20.0, 100.0]).all(|(a, b)| (a - b).abs() < 0.01), "upright bounds of the turned bar: {r:?}"); + let d = rect(&rt, "dot"); + assert!(d.iter().zip([100.0, 10.0, 10.0, 10.0]).all(|(a, b)| (a - b).abs() < 0.01), "the child turns with it: {d:?}"); + // Its right end no longer shows there; its new top end does. + rt.pointer_move(145.0, 60.0); + rt.pointer_down(145.0, 60.0); + rt.pointer_up(145.0, 60.0); + rt.frame(0.0); + assert!(rt.state, "missed the old right end"); + rt.pointer_move(100.0, 15.0); + rt.pointer_down(100.0, 15.0); + rt.pointer_up(100.0, 15.0); + rt.frame(0.0); + assert!(!rt.state, "hit the turned top end"); + + let mut rt = Runtime::new(false, view, (200.0, 200.0), Env::new(true, 1.0)); + rt.frame(0.0); + rt.set_system_reduced_motion(true); + rt.update(|s, _| *s = true); + rt.frame(1.0 / 60.0); + assert!((turn(&rt).unwrap() - std::f32::consts::FRAC_PI_2).abs() < 1e-4, "lands at once under Reduce Motion"); +} + +#[test] +fn rotate_and_scale_share_the_origin() { + fn view(_: &(), _: &mut Cx<()>) -> El { + col().w_full().h_full().items_start().padding(50.0).child( + el().key("a").size(100.0, 20.0).fill(Color::WHITE).origin(0.0, 0.0) + .rotate(std::f32::consts::FRAC_PI_2).scale(0.5), + ) + } + let mut rt = Runtime::new((), view, (200.0, 200.0), Env::new(true, 1.0)); + rt.frame(0.0); + let r = rect(&rt, "a"); + // Half size about its top-left (50, 50), then a quarter turn clockwise about the same point. + assert!(r.iter().zip([40.0, 50.0, 10.0, 50.0]).all(|(a, b)| (a - b).abs() < 0.01), "{r:?}"); +} + +#[test] +fn rotated_hit_test_uses_turned_box_not_upright_bounds() { + fn view(_: &Vec<&'static str>, _: &mut Cx<Vec<&'static str>>) -> El { + col().w_full().h_full().items_start().padding(50.0) + .on_press(|s: &mut Vec<&'static str>| s.push("bg")) + .child( + // Centre at (100, 60), 100x20 turned 45° clockwise. + // Upright bbox is ~[57.6, 17.6]..[142.4, 102.4], but (130, 30) is in the empty top-right corner. + el().key("bar").size(100.0, 20.0).fill(Color::WHITE) + .rotate(std::f32::consts::FRAC_PI_4) + .on_press(|s: &mut Vec<&'static str>| s.push("bar")), + ) + } + let mut rt = Runtime::new(Vec::new(), view, (200.0, 200.0), Env::new(true, 1.0)); + rt.frame(0.0); + // (130, 30) is well inside the upright bbox [57.6..142.4, 17.6..102.4], but 42 pt off the 45° diagonal. + rt.pointer_move(130.0, 30.0); + rt.pointer_down(130.0, 30.0); + rt.pointer_up(130.0, 30.0); + rt.frame(0.0); + assert_eq!(rt.state, ["bg"], "empty corner of upright bbox must not steal presses from behind"); + + // (120, 80) lies right along the +45° diagonal from (100, 60). + rt.pointer_move(120.0, 80.0); + rt.pointer_down(120.0, 80.0); + rt.pointer_up(120.0, 80.0); + rt.frame(0.0); + assert_eq!(rt.state, ["bg", "bar"]); +} + +#[test] +fn clip_inside_rotated_element_and_rotated_element_inside_rounded_clip() { + fn view(_: &Vec<&'static str>, _: &mut Cx<Vec<&'static str>>) -> El { + col().w_full().h_full().items_start().padding(50.0).gap(20.0) + .child( + // Rotated 90° clockwise about its centre (80, 70): upright 60x40 becomes screen [60..100, 40..100]. + // Child is 120x40 (sticks out 60pt past the right edge of the 60x40 clip, which turns to y = 100..160). + el().key("rot_clip").size(60.0, 40.0).clip_soft(0.0).rotate(std::f32::consts::FRAC_PI_2).child( + el().key("inner").size(120.0, 40.0).fill(Color::WHITE) + .on_press(|s: &mut Vec<&'static str>| s.push("inner")), + ), + ) + .child( + el().key("outer_round").size(80.0, 40.0).radius(12.0).clip_rounded(12.0).child( + el().key("turned_in_round").size(80.0, 20.0).fill(Color::WHITE).rotate(0.4), + ), + ) + } + let mut rt = Runtime::new(Vec::new(), view, (240.0, 240.0), Env::new(true, 1.0)); + rt.frame(0.0); + // Inside the rotated clip (80, 80): hits `inner`. + rt.pointer_move(80.0, 80.0); + rt.pointer_down(80.0, 80.0); + rt.pointer_up(80.0, 80.0); + rt.frame(0.0); + assert_eq!(rt.state, ["inner"]); + + // In the protruding part of `inner` clipped away by `rot_clip` (80, 120): must not hit. + rt.pointer_move(80.0, 120.0); + rt.pointer_down(80.0, 120.0); + rt.pointer_up(80.0, 120.0); + rt.frame(0.0); + assert_eq!(rt.state, ["inner"], "protruding part of child is clipped by rotated parent"); + + // The turned layer inside `outer_round` carries both the turn (`border[1] != 0`) and the packed rounded clip (`fade[3] != 0`). + let turned_layer = rt.instances.iter() + .find(|q| q.params[1] == rune::render::KIND_LAYER && (q.border[1] - 0.4).abs() < 1e-4) + .expect("turned layer inside rounded clip"); + assert_ne!(turned_layer.fade[3], 0, "turned layer composite preserves ancestor per-corner rounded clip"); +} + +#[test] +fn shadow_list_length_changes_and_instant_transactions_settle_cleanly() { + fn view(mode: &u8, _: &mut Cx<u8>) -> El { + let s1 = rune::Shadow { x: 0.0, y: if *mode == 1 { 2.0 } else { 10.0 }, blur: 12.0, spread: 0.0, color: Color::BLACK.alpha(0.3), inset: false }; + let s2 = rune::Shadow { x: 0.0, y: if *mode == 3 { 4.0 } else { 24.0 }, blur: 20.0, spread: 2.0, color: Color::BLACK.alpha(0.2), inset: false }; + let mut e = el().key("a").size(100.0, 40.0).fill(Color::WHITE).motion(Spring::new(0.3, 0.0)).box_shadow(s1); + if *mode == 0 || *mode == 3 { + e = e.box_shadow(s2); + } + col().w_full().h_full().items_start().padding(50.0).child(e) + } + let mut rt = Runtime::new(0u8, view, (200.0, 200.0), Env::new(true, 1.0)); + rt.frame(0.0); + // Start springing shadow 1 and remove shadow 2 at the same time. + rt.update(|m, _| *m = 1); + rt.frame(1.0 / 60.0); + // Land mid-spring with `tx.settle()` on the same target (`mode = 1`). + rt.update(|_, tx| tx.settle()); + assert!(!rt.frame(1.0 / 60.0), "settling lands in-flight shadow geometry immediately"); + + // Re-adding a second shadow (`mode = 3`) mounts at its new geometry (y = 4, spread = 2 -> rect y = 50 + 4 - 2 = 52) + // instead of springing from the old removed second shadow (y = 24). + rt.update(|m, _| *m = 3); + rt.frame(1.0 / 60.0); + let shadows: Vec<_> = rt.instances.iter().filter(|q| q.params[1] == rune::render::KIND_SHADOW).collect(); + assert_eq!(shadows.len(), 2); + assert_eq!(shadows[1].rect, [48.0, 52.0, 104.0, 44.0], "re-added second shadow mounts at its own geometry"); +} + +#[test] +fn press_scale_and_exiting_child_inside_rotated_element_stay_turned() { + fn view(show_child: &bool, _: &mut Cx<bool>) -> El { + let mut bar = el().key("bar").size(100.0, 20.0).fill(Color::WHITE) + .origin(0.0, 0.0) + .rotate(std::f32::consts::FRAC_PI_2) + .press_scale(0.5) + .on_press(|_: &mut bool| {}); + if *show_child { + bar = bar.child(el().key("chip").size(20.0, 10.0).fill(Color::BLACK).transition(rune::Transition::opacity())); + } + col().w_full().h_full().items_start().padding(50.0).child(bar) + } + let mut rt = Runtime::new(true, view, (200.0, 200.0), Env::new(true, 1.0)); + rt.frame(0.0); + assert!(rect(&rt, "bar").iter().zip([30.0, 50.0, 20.0, 100.0]).all(|(a, b)| (a - b).abs() < 0.01)); + + // Press the rotated bar at (40, 80): `press_scale(0.5)` about origin (0, 0) = (50, 50) + // shrinks the rotated bar to [40.0, 50.0, 10.0, 50.0] without its top-right pivot drifting. + rt.pointer_move(40.0, 80.0); + rt.pointer_down(40.0, 80.0); + settle(&mut rt); + let pressed_r = rect(&rt, "bar"); + assert!(pressed_r.iter().zip([40.0, 50.0, 10.0, 50.0]).all(|(a, b)| (a - b).abs() < 0.01), "{pressed_r:?}"); + rt.pointer_up(40.0, 80.0); + settle(&mut rt); + + // Remove `chip`: while exiting, it must still draw inside `bar`'s turned layer. + rt.update(|s, _| *s = false); + rt.frame(1.0 / 60.0); + let end_idx = rt.instances.iter().position(|q| q.params[1] == rune::render::KIND_LAYER_END).expect("turned layer end"); + assert_eq!(end_idx, rt.instances.len() - 1, "exiting child paints before the turned layer closes"); +} diff --git a/app/vendor/rune/crates/rune/tests/integration/fly_text_extent.rs b/app/vendor/rune/crates/rune/tests/integration/fly_text_extent.rs new file mode 100644 index 0000000..7989d32 --- /dev/null +++ b/app/vendor/rune/crates/rune/tests/integration/fly_text_extent.rs @@ -0,0 +1,68 @@ +//! `fly_text` measures its landing spot by the destination's laid-out text, as it does the +//! source, so a body stretched across a column doesn't scale the flight. +use rune::{Cx, El, Env, Key, KeyEvent, Runtime, TextEdit, TextStyle, Tx, col, text, text_input}; + +const STYLE: TextStyle = TextStyle::new(14.0, 400.0); +const MESSAGE: &str = "hello there, world"; + +struct State { draft: TextEdit, sent: bool } + +fn view(s: &State, _: &mut Cx<State>) -> El { + let mut page = col().w_full().h_full(); + if s.sent { page = page.child(text(MESSAGE).font(STYLE).key("body").w(600.0).wrap()); } + page.child(text_input(&s.draft, STYLE).key("composer").w(400.0).h(60.0) + .on_edit(|s: &mut State| &mut s.draft) + .on_submit(|s: &mut State, tx: &mut Tx| { + s.sent = true; + s.draft.clear(); + tx.fly_text("composer", "body"); + })) +} + +#[test] +fn a_wide_destination_lands_on_its_text_at_rest_scale() { + let mut draft = TextEdit::new(MESSAGE); + draft.focused = true; + let mut rt = Runtime::new(State { draft, sent: false }, view, (800.0, 300.0), Env::new(true, 2.0)); + rt.frame(0.0); + rt.key(KeyEvent { key: Key::Enter, mods: Default::default() }); + rt.frame(1.0 / 120.0); + let flight = |rt: &Runtime<State>| rt.elements().into_iter().find(|e| e.key.as_deref() == Some("flight-source/body")); + let start = flight(&rt).expect("the composer's text flies"); + let source_w = start.rect[2]; + let body = rt.elements().into_iter().find(|e| e.key.as_deref() == Some("body")).unwrap(); + assert_eq!(body.target[2], 600.0, "the destination box is the full 600"); + let text_w = start.target[2]; + assert!(text_w > 60.0 && text_w < 200.0, "the landing spot is the text's extent, not the box: {text_w}"); + assert!((text_w - source_w).abs() < 2.0, "the same text at the same style is the same size: {source_w} vs {text_w}"); + assert_eq!(start.target[0], body.target[0], "a start-aligned text starts at its box"); + for _ in 0..30 { + rt.frame(1.0 / 120.0); + let Some(f) = flight(&rt) else { break }; + assert!((f.rect[2] / source_w - 1.0).abs() < 0.02, "the flight stays at rest scale: {} vs {source_w}", f.rect[2]); + assert_eq!(f.target, start.target, "the landing spot holds still"); + } + for _ in 0..120 { rt.frame(1.0 / 120.0); } + assert!(flight(&rt).is_none(), "the flight lands and ends"); +} + +#[test] +fn the_destination_lands_on_its_own_box() { + let mut draft = TextEdit::new(MESSAGE); + draft.focused = true; + let mut rt = Runtime::new(State { draft, sent: false }, view, (800.0, 300.0), Env::new(true, 2.0)); + rt.frame(0.0); + rt.key(KeyEvent { key: Key::Enter, mods: Default::default() }); + let body = |rt: &Runtime<State>| rt.elements().into_iter().find(|e| e.key.as_deref() == Some("body")).unwrap().rect; + let mut last = None; + for _ in 0..150 { + rt.frame(1.0 / 120.0); + let r = body(&rt); + if let Some(l) = last { + let l: [f32; 4] = l; + assert!((r[2] - l[2]).abs() < 2.0 && (r[0] - l[0]).abs() < 2.0, "the body's frame jumped: {l:?} → {r:?}"); + } + last = Some(r); + } + assert_eq!(last.unwrap()[2], 600.0, "at rest it is its box"); +} diff --git a/app/vendor/rune/crates/rune/tests/integration/fly_text_scoped.rs b/app/vendor/rune/crates/rune/tests/integration/fly_text_scoped.rs new file mode 100644 index 0000000..b34adfb --- /dev/null +++ b/app/vendor/rune/crates/rune/tests/integration/fly_text_scoped.rs @@ -0,0 +1,56 @@ +//! `fly_text` destinations can be row-scoped key paths, so every message row can key its text +//! `body` and the flight still lands on the new row's. +use rune::{Cx, El, Env, GrowthSpec, Key, KeyEvent, Runtime, ScrollSpec, TextEdit, TextStyle, Tx, col, text, text_input}; + +struct State { draft: TextEdit, sent: Vec<String>, destination: &'static str } + +fn view(s: &State, _: &mut Cx<State>) -> El { + let mut rows = col().w_full().growth(GrowthSpec::default()); + for (i, m) in s.sent.iter().enumerate() { + rows = rows.child(col().key(format!("msg-{i}")).w_full().py(8.0).child(col().child(text(m.clone()).key("body").wrap()))); + } + col().w_full().h_full() + .child(col().key("scroll").w_full().grow(1.0).shrink().scroll(ScrollSpec { stick_bottom: true }).child(rows)) + .child(text_input(&s.draft, TextStyle::new(14.0, 400.0)).key("composer").w_full().h(60.0) + .on_edit(|s: &mut State| &mut s.draft) + .on_submit(|s: &mut State, tx: &mut Tx| { + s.sent.push(s.draft.text.clone()); + s.draft.clear(); + tx.fly_text("composer", s.destination); + })) +} + +fn flight(rt: &Runtime<State>, key: &str) -> Option<[f32; 4]> { + rt.elements().into_iter().find(|e| e.key.as_deref() == Some(key)).map(|e| e.target) +} + +#[test] +fn a_scoped_destination_lands_on_its_own_row() { + for (destination, lands) in [("msg-2/body", true), ("msg-0/body", true), ("msg-9/body", false)] { + let mut draft = TextEdit::new("third"); + draft.focused = true; + let sent = vec!["first".to_string(), "second".to_string()]; + let mut rt = Runtime::new(State { draft, sent, destination }, view, (400.0, 300.0), Env::new(true, 2.0)); + rt.frame(0.0); + rt.key(KeyEvent { key: Key::Enter, mods: Default::default() }); + rt.frame(1.0 / 120.0); + rt.frame(1.0 / 120.0); + let key = format!("flight-source/{destination}"); + let Some(target) = flight(&rt, &key) else { + assert!(!lands, "{destination}: no row has it, so nothing flies"); + continue; + }; + assert!(lands, "{destination}"); + // Every row's body shares the key; the flight's destination is the named row's. + let row = match destination { "msg-2/body" => 2, _ => 0 }; + let bodies: Vec<_> = rt.elements().into_iter().filter(|e| e.key.as_deref() == Some("body")).collect(); + let body = bodies[row].target; + assert_eq!(target[..2], body[..2], "{destination}: lands on msg-{row}'s text"); + assert!(target[2] <= body[2] && target[3] <= body[3], "{destination}: within msg-{row}'s text box"); + for (i, b) in bodies.iter().enumerate() { + assert_eq!(b.rect != b.target, i == row, "{destination}: only msg-{row}'s text rides the flight"); + } + for _ in 0..120 { rt.frame(1.0 / 120.0); } + assert!(flight(&rt, &key).is_none(), "{destination}: lands and ends"); + } +} diff --git a/app/vendor/rune/crates/rune/tests/integration/font_families.rs b/app/vendor/rune/crates/rune/tests/integration/font_families.rs new file mode 100644 index 0000000..acd62a7 --- /dev/null +++ b/app/vendor/rune/crates/rune/tests/integration/font_families.rs @@ -0,0 +1,95 @@ +use std::hash::{Hash, Hasher}; +use rune::{Family, OpticalSize, TextStyle, text::{Span, TextSystem}}; + +const INTER: &[u8] = include_bytes!("../../assets/Inter-Regular.ttf"); +const PLEX: &[u8] = include_bytes!("../../../../themes/opencode/assets/fonts/IBMPlexMono-Regular.ttf"); +const DISPLAY: TextStyle = TextStyle::new(13.0, 400.0).family(Family::Named("IBM Plex Mono")); + +// Exactly TextStyle's public fields. Deliberately exhaustive: alignment is an element builder, +// not a style field. Consumers build styles with `TextStyle::new` and `..` (checked for `italic`). +const _: TextStyle = TextStyle { + size: 13.0, + weight: 400.0, + family: Family::Sans, + line_height: 0.0, + tracking: 0.0, + variations: "", + features: "", + optical_size: OpticalSize::Auto, + italic: false, +}; + +#[test] +fn registered_family_is_independent_of_slots_and_cache_entries() { + // Plex is registered but occupies neither slot, just like a display wordmark family. + let mut system = TextSystem::new(&[INTER, PLEX], ("Inter", "Inter")); + let default = TextStyle::new(13.0, 400.0); + let sans = system.layout_rich("Hello 0123", &[], default, 2.0, None); + let named = system.layout_rich("Hello 0123", &[], DISPLAY, 2.0, None); + assert!(!std::rc::Rc::ptr_eq(&sans, &named)); + assert_ne!(sans.full_width(), named.full_width()); + for run in named.lines().flat_map(|l| l.runs()) { + assert_eq!(run.font().data.as_ref(), PLEX); + } + let again = system.layout_rich("Hello 0123", &[], DISPLAY, 2.0, None); + assert!(std::rc::Rc::ptr_eq(&named, &again)); + let other = system.layout_rich("Hello 0123", &[], default.family(Family::Named("Inter")), 2.0, None); + assert!(!std::rc::Rc::ptr_eq(&named, &other), "the family name must participate in the cache key"); + for style in [DISPLAY.mono(), DISPLAY.family(Family::Sans)] { + let layout = system.layout_rich("Hello 0123", &[], style, 2.0, None); + for run in layout.lines().flat_map(|l| l.runs()) { + assert_eq!(run.font().data.as_ref(), INTER); + } + } + let spans = [Span { mono: true, ..Span::new(6, 10) }]; + let rich = system.layout_rich("Hello 0123", &spans, DISPLAY, 2.0, None); + assert!(rich.lines().flat_map(|l| l.runs()).any(|r| r.font().data.as_ref() == PLEX)); + assert!(rich.lines().flat_map(|l| l.runs()).any(|r| r.font().data.as_ref() == INTER), + "mono spans still select the mono slot"); +} + +#[test] +fn missing_named_family_falls_back_to_sans_pixels() { + // Use distinct slots to prove missing families choose sans, not mono. + for scale in [1.0, 2.0] { + let mut sans = TextSystem::new(&[INTER, PLEX], ("Inter", "IBM Plex Mono")); + let mut missing = TextSystem::new(&[INTER, PLEX], ("Inter", "IBM Plex Mono")); + let style = TextStyle::new(13.0, 400.0); + let mut a = Vec::new(); let mut b = Vec::new(); + sans.glyphs("Hello 0123 ffi", style, scale, [0.0, 0.0], &mut a); + missing.glyphs("Hello 0123 ffi", style.family(Family::Named("Rune Missing Family")), + scale, [0.0, 0.0], &mut b); + assert_eq!(a.iter().map(|q| (q.rect, q.uv)).collect::<Vec<_>>(), b.iter().map(|q| (q.rect, q.uv)).collect::<Vec<_>>()); + assert_eq!(sans.atlas.data, missing.atlas.data); + } +} + +#[test] +fn default_faces_keep_batch_c_pixels() { + // Capture the existing sans/mono paths, including mono rich spans, at both densities. + for scale in [1.0, 2.0] { + let mut system = TextSystem::new(&[INTER, PLEX], ("Inter", "IBM Plex Mono")); + system.set_font_smoothing(rune::FontSmoothing::On); + let mut hash = std::collections::hash_map::DefaultHasher::new(); + for style in [TextStyle::new(13.0, 400.0), TextStyle::new(13.0, 400.0).mono()] { + let spans = [Span { mono: true, ..Span::new(6, 10) }]; + let layout = system.layout_rich("Hello 0123 ffi", &spans, style, scale, None); + layout.full_width().to_bits().hash(&mut hash); + let mut quads = Vec::new(); + system.glyphs_for_layout(&layout, scale, [0.0, 0.0], false, &mut quads); + for q in quads { + q.rect.map(f32::to_bits).hash(&mut hash); + q.uv.map(f32::to_bits).hash(&mut hash); + } + } + system.atlas.data.hash(&mut hash); + // At 2× the inline Plex span grows the line, as Chromium's does (#983): each font's box + // has its ascent and descent rounded to device px and its half-leading floored, and the + // line is the largest reach above the baseline plus the largest below. Plex reaches a + // pixel further under the baseline than Inter, so a 13/16 table cell with inline code is + // 17 tall at 1× in official OpenCode, not 16. This is the hash from before #448 cut the + // span's box to fit (Kit's 70909822 followed that); 1× doesn't change. + let expected = if scale == 1.0 { 17045220814369067823 } else { 10933675232581112092 }; + assert_eq!(hash.finish(), expected, "sans/mono pixels changed at {scale}×"); + } +} diff --git a/app/vendor/rune/crates/rune/tests/integration/font_swap.rs b/app/vendor/rune/crates/rune/tests/integration/font_swap.rs new file mode 100644 index 0000000..b3319e7 --- /dev/null +++ b/app/vendor/rune/crates/rune/tests/integration/font_swap.rs @@ -0,0 +1,139 @@ +//! `Tx::set_font_families` swaps the families behind the sans and mono slots while the app +//! runs: text measures as a fresh launch with those families would, memoized subtrees build +//! again, and asking for the families already there rebuilds nothing. +use std::cell::Cell; + +use rune::text::TextSystem; +use rune::{App, AppSpec, El, Env, Runtime, TextStyle, col, memo, row, text}; + +const INTER: &[u8] = include_bytes!("../../assets/Inter-Regular.ttf"); +const PLEX: &[u8] = include_bytes!("../../../../themes/opencode/assets/fonts/IBMPlexMono-Regular.ttf"); +const LAUNCH: (&str, &str) = ("Inter", "IBM Plex Mono"); +static APP_FONTS: &[&[u8]] = &[INTER, PLEX]; + +thread_local! { + static MEMO_BUILDS: Cell<u32> = const { Cell::new(0) }; +} + +const STYLE: TextStyle = TextStyle::new(14.0, 400.0); + +fn view(_: &(), _: &mut rune::Cx<()>) -> El { + let style = STYLE; + col().children([ + row().child(text("Hamburgefonstiv 0123").key("label").font(style)), + row().child(memo("card", 0, || { + MEMO_BUILDS.set(MEMO_BUILDS.get() + 1); + row().child(text("Memoized card title").key("memo-label").font(style)) + })), + row().child(text("let mono = 42;").key("code").font(style.mono())), + ]) +} + +fn launch(families: (&str, &str)) -> Runtime<()> { + let text = TextSystem::new(&[INTER, PLEX], families); + let mut rt = Runtime::with_text((), view, (600.0, 400.0), Env::new(true, 2.0), text); + rt.frame(0.0); + rt +} + +fn widths(rt: &Runtime<()>) -> [f32; 3] { + let elements = rt.elements(); + ["label", "memo-label", "code"].map(|key| { + elements.iter().find(|e| e.key.as_deref() == Some(key)).unwrap_or_else(|| panic!("{key}")).target[2] + }) +} + +fn switch(rt: &mut Runtime<()>, sans: &str, mono: &str) -> bool { + let stale = rt.update_if(|_, tx| { + tx.set_font_families(sans, mono); + false + }); + rt.frame(1.0 / 120.0); + stale +} + +#[test] +fn a_switch_measures_like_a_fresh_launch_and_rebuilds_memoized_subtrees() { + let _g = rune::text::with_families(LAUNCH.0, LAUNCH.1); + let fresh = widths(&launch(("IBM Plex Mono", "Inter"))); + let mut rt = launch(LAUNCH); + let before = widths(&rt); + let builds = MEMO_BUILDS.get(); + assert!(switch(&mut rt, "IBM Plex Mono", "Inter"), "a switch asks for a frame"); + let after = widths(&rt); + assert_eq!(rt.font_families(), ("IBM Plex Mono", "Inter")); + for i in 0..3 { + assert!((after[i] - before[i]).abs() > 1.0, "width {i} changed: {before:?} -> {after:?}"); + } + assert_eq!(after, fresh, "matches a fresh launch with those families"); + assert_eq!(MEMO_BUILDS.get(), builds + 1, "the memoized subtree built again, once"); + assert!(rt.stats.shaped > 0, "text shaped again in the new families"); + let (w, _) = rune::text::measure("Hamburgefonstiv 0123", &[], STYLE, None); + assert!((w - after[0]).abs() < 0.51, "measure follows: {w} vs {}", after[0]); + + // And back again. + switch(&mut rt, LAUNCH.0, LAUNCH.1); + assert_eq!(widths(&rt), before); +} + +#[test] +fn asking_for_the_families_already_there_rebuilds_nothing() { + let _g = rune::text::with_families(LAUNCH.0, LAUNCH.1); + let mut rt = launch(LAUNCH); + rt.frame(1.0 / 120.0); + let (builds, commits) = (MEMO_BUILDS.get(), rt.stats.commits); + assert!(!switch(&mut rt, LAUNCH.0, LAUNCH.1), "no frame asked for"); + assert_eq!(rt.stats.commits, commits, "no commit"); + assert_eq!(MEMO_BUILDS.get(), builds, "no memo rebuild"); + assert_eq!(rt.stats.shaped, 0, "nothing shaped"); +} + +#[test] +fn every_runtime_on_the_thread_follows() { + let _g = rune::text::with_families(LAUNCH.0, LAUNCH.1); + let mut a = launch(LAUNCH); + let mut b = launch(LAUNCH); + let fresh = widths(&launch(("IBM Plex Mono", "IBM Plex Mono"))); + switch(&mut a, "IBM Plex Mono", "IBM Plex Mono"); + b.frame(1.0 / 120.0); + assert_eq!(widths(&a), fresh); + assert_eq!(widths(&b), fresh, "another window follows on its next frame"); +} + +#[test] +fn a_missing_family_falls_back_as_at_launch() { + let _g = rune::text::with_families(LAUNCH.0, LAUNCH.1); + let fresh = widths(&launch(("Rune Missing Family", "Rune Missing Mono"))); + let mut rt = launch(LAUNCH); + switch(&mut rt, "Rune Missing Family", "Rune Missing Mono"); + assert_eq!(widths(&rt), fresh); + assert!(widths(&rt).iter().all(|w| *w > 0.0)); +} + +/// A window of an app launched in `LAUNCH`, as a window opens it, before its first frame. +fn open_window() -> Runtime<()> { + let mut spec = AppSpec::new("fonts", (600.0, 400.0), || (), view); + spec.fonts = APP_FONTS; + spec.families = LAUNCH; + App::new(spec).headless_runtime((600.0, 400.0), Env::new(true, 2.0)) +} + +#[test] +fn a_window_opened_after_a_switch_starts_in_the_new_families() { + let _g = rune::text::with_families(LAUNCH.0, LAUNCH.1); + let switched = ("IBM Plex Mono", "Inter"); + let fresh = widths(&launch(switched)); + let switched_width = rune::text::measure("Hamburgefonstiv 0123", &[], STYLE, None).0; + let mut first = open_window(); + first.frame(0.0); + let launch_width = rune::text::measure("Hamburgefonstiv 0123", &[], STYLE, None).0; + assert!((launch_width - switched_width).abs() > 1.0, "the families measure apart"); + switch(&mut first, switched.0, switched.1); + let mut second = open_window(); + let (w, _) = rune::text::measure("Hamburgefonstiv 0123", &[], STYLE, None); + assert_eq!(w, switched_width, "measure stays in the chosen families before its first frame"); + assert_eq!(second.font_families(), switched, "the new window starts in the chosen families"); + second.frame(0.0); + assert_eq!(widths(&second), fresh); + assert_eq!(rune::text::measure("Hamburgefonstiv 0123", &[], STYLE, None).0, switched_width); +} diff --git a/app/vendor/rune/crates/rune/tests/integration/growth_whole.rs b/app/vendor/rune/crates/rune/tests/integration/growth_whole.rs new file mode 100644 index 0000000..5a9122a --- /dev/null +++ b/app/vendor/rune/crates/rune/tests/integration/growth_whole.rs @@ -0,0 +1,23 @@ +//! A growth row's public kind switch, as an app uses it: `whole` asks for the spring alone, with +//! none of the stack's speed caps. + +use rune::growth::GrowTrack; +use rune::{GROWTH, edge}; + +/// A whole row takes the spring's own speed, so it opens far past the carrying-tail cap that +/// holds a capped row back, and still lands exactly. +#[test] +fn an_app_asks_for_an_uncapped_whole_glide() { + let mut t = GrowTrack::settled(0.0); + t.whole = true; + t.retarget(900.0); + let (mut prev, mut fastest) = (0.0, 0.0f32); + for _ in 0..(2.0 / rune::growth::SUBSTEP) as usize { + t.step(GROWTH, &edge::FEATHER, true); + fastest = fastest.max((t.h - prev) / rune::growth::SUBSTEP); + prev = t.h; + } + // A capped row carrying a tail is held to 7.5 × 60 pt/s; a whole glide peaks far above it. + assert!(fastest > 7.5 * 60.0, "the whole glide keeps the spring's speed: {fastest} pt/s at peak"); + assert!(!t.moving() && (t.h - 900.0).abs() < 1e-3, "and lands on its target: {} pt", t.h); +} diff --git a/app/vendor/rune/crates/rune/tests/integration/headless_place.rs b/app/vendor/rune/crates/rune/tests/integration/headless_place.rs new file mode 100644 index 0000000..97709c0 --- /dev/null +++ b/app/vendor/rune/crates/rune/tests/integration/headless_place.rs @@ -0,0 +1,37 @@ +use rune::*; + +static HANDLE: std::sync::OnceLock<AppHandle<()>> = std::sync::OnceLock::new(); + +fn view(_: &(), _: &mut Cx<()>) -> El { el() } + +fn placed(app: App<()>, name: &str) -> serde_json::Value { + let dir = std::env::temp_dir().join(format!("rune-headless-place-{name}-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let (script, tree) = (dir.join("desktop.json"), dir.join("tree.json")); + std::fs::write(&script, r#"{ + "displays": [{"id": 1, "frame": [0, 0, 1512, 982], "scale": 2, "primary": true}, + {"id": 2, "frame": [1512, 0, 1920, 1080], "scale": 1}], + "pointer": [2000, 400] + }"#).unwrap(); + app.args(["--script", script.to_str().unwrap(), "--tree", tree.to_str().unwrap()].map(String::from)).run(); + let tree: serde_json::Value = serde_json::from_str(&std::fs::read_to_string(&tree).unwrap()).unwrap(); + std::fs::remove_dir_all(&dir).unwrap(); + tree["placed"].clone() +} + +#[test] +fn headless_place_resolves_against_scripted_displays() { + let app = App::new(AppSpec::new("place", (600.0, 80.0), || (), view)); + app.handle().place(DisplayTarget::UnderPointer, + OverlayPlacement::Edge { edge: ScreenEdge::Top, margin: 160.0, align: Align::Center, inset: 0.0 }); + assert_eq!(placed(app, "handle"), serde_json::json!({"t": 0.0, "display": 2, "frame": [2172.0, 160.0, 600.0, 80.0]})); + + // poll runs inside the snapshot frame; its placement must still be recorded. + fn poll(_: &mut (), _: f64, _: &mut Tx) -> bool { + HANDLE.get().unwrap().place(DisplayTarget::Primary, OverlayPlacement::FullScreen); + false + } + let app = App::new(AppSpec { poll: Some(poll), ..AppSpec::new("poll", (600.0, 80.0), || (), view) }); + HANDLE.set(app.handle()).ok().unwrap(); + assert_eq!(placed(app, "poll"), serde_json::json!({"t": 0.0, "display": 1, "frame": [0.0, 0.0, 1512.0, 982.0]})); +} diff --git a/app/vendor/rune/crates/rune/tests/integration/headless_screen_layout.rs b/app/vendor/rune/crates/rune/tests/integration/headless_screen_layout.rs new file mode 100644 index 0000000..b0e452b --- /dev/null +++ b/app/vendor/rune/crates/rune/tests/integration/headless_screen_layout.rs @@ -0,0 +1,41 @@ +//! Headless `El::on_screen_layout`: a window opens on the script's virtual desktop, and moving +//! it with `place()` reports its elements' new global rects without a relayout. +use rune::*; +use std::sync::{Mutex, OnceLock}; + +static HANDLE: OnceLock<AppHandle<()>> = OnceLock::new(); +static RECTS: Mutex<Vec<[f32; 4]>> = Mutex::new(Vec::new()); + +fn view(_: &(), _: &mut Cx<()>) -> El { + col().w_full().h_full().padding(10.0).child( + el().key("card").w(100.0).h(20.0) + .on_press(|_: &mut ()| { + HANDLE.get().unwrap().place(DisplayTarget::UnderPointer, + OverlayPlacement::Edge { edge: ScreenEdge::Top, margin: 160.0, align: Align::Center, inset: 0.0 }); + }) + .on_screen_layout(|_: &mut (), r| RECTS.lock().unwrap().push(r)), + ) +} + +#[test] +fn screen_rects_follow_the_window_on_the_virtual_desktop() { + let dir = std::env::temp_dir().join(format!("rune-headless-screen-layout-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let (script, tree) = (dir.join("desktop.json"), dir.join("tree.json")); + std::fs::write(&script, r#"{ + "displays": [{"id": 1, "frame": [0, 0, 1512, 982], "scale": 2, "primary": true}, + {"id": 2, "frame": [1512, 0, 1920, 1080], "scale": 1}], + "pointer": [2000, 400], + "events": [{"t": 0.1, "type": "tap", "key": "card"}, {"t": 0.5, "type": "move", "x": 1, "y": 1}] + }"#).unwrap(); + let app = App::new(AppSpec::new("screen-layout", (600.0, 80.0), || (), view)); + HANDLE.set(app.handle()).ok().unwrap(); + app.args(["--script", script.to_str().unwrap(), "--tree", tree.to_str().unwrap()].map(String::from)).run(); + std::fs::remove_dir_all(&dir).unwrap(); + assert_eq!(*RECTS.lock().unwrap(), [ + // Opened centred on the primary display, the card 10 points in. + [466.0, 461.0, 100.0, 20.0], + // Placed at the top of the display under the pointer. + [2182.0, 170.0, 100.0, 20.0], + ]); +} diff --git a/app/vendor/rune/crates/rune/tests/integration/help_tooltip.rs b/app/vendor/rune/crates/rune/tests/integration/help_tooltip.rs new file mode 100644 index 0000000..08573ca --- /dev/null +++ b/app/vendor/rune/crates/rune/tests/integration/help_tooltip.rs @@ -0,0 +1,129 @@ +//! `El::help` tooltips where Rune draws them: the pointer resting on an element for +//! `help_delay` shows its tooltip under it; a press, scroll or key hides it until the pointer +//! leaves; leaving hides it; it follows its element; and it takes no hover or press. + +use rune::{Cx, El, Env, Key, KeyEvent, Mods, Runtime, col, el, row}; +use crate::support::{self, find}; + +#[derive(Default)] +struct S { presses: u32, hovered: bool, inset: f32 } + +fn view(s: &S, _: &mut Cx<S>) -> El { + col().w_full().h_full().padding(20.0).gap(10.0) + .child(row().pl(s.inset) + .child(el().key("copy").size(28.0, 28.0) + .help("Copy the command") + .on_press(|s: &mut S| s.presses += 1) + .on_hover_change(|s: &mut S, on, _| s.hovered = on))) + .child(el().key("plain").size(100.0, 28.0)) + // Help at the window's bottom edge flips its tooltip above it. + .child(el().w_full().grow(1.0)) + .child(el().key("low").size(60.0, 24.0).help("Near the bottom")) +} + +fn runtime() -> Runtime<S> { + let mut rt = Runtime::new(S::default(), view, (400.0, 300.0), Env::new(true, 2.0)); + rt.frame(0.0); + rt +} + +fn centre(rt: &Runtime<S>, key: &str) -> (f32, f32) { + support::centre(&find(rt, key)) +} + +fn hover(rt: &mut Runtime<S>, key: &str) { + let (x, y) = centre(rt, key); + rt.pointer_move(x, y); + rt.frame(1.0 / 60.0); +} + +fn tip(rt: &Runtime<S>) -> Option<String> { rt.help_tooltip().map(|(t, _)| t.to_owned()) } + +#[test] +fn shows_after_the_delay_and_hides_on_exit() { + let mut rt = runtime(); + assert_eq!(find(&rt, "copy").help.as_deref(), Some("Copy the command"), "tools read the help text"); + hover(&mut rt, "copy"); + assert!(rt.state.hovered, "the element keeps its own hover"); + rt.frame(rt.help_delay - 0.1); + assert_eq!(tip(&rt), None, "not before the delay"); + rt.frame(0.15); + assert_eq!(tip(&rt).as_deref(), Some("Copy the command")); + + // Under the element, centred on it, inside the window. + let (_, r) = rt.help_tooltip().unwrap(); + let e = find(&rt, "copy"); + assert!(r[1] >= e.rect[1] + e.rect[3], "below: {r:?} {e:?}"); + assert!(r[0] >= 4.0 && r[0] + r[2] <= 396.0, "{r:?}"); + assert!(((r[0] + r[2] / 2.0) - (e.rect[0] + e.rect[2] / 2.0)).abs() < 1.0 || r[0] == 4.0, "centred: {r:?}"); + + // Moving within the element keeps it; leaving hides it. + rt.pointer_move(e.rect[0] + 3.0, e.rect[1] + 3.0); + rt.frame(1.0 / 60.0); + assert!(tip(&rt).is_some()); + hover(&mut rt, "plain"); + assert_eq!(tip(&rt), None); + rt.frame(1.0); + assert_eq!(tip(&rt), None, "no help on plain"); + + // Leaving the window hides it too, and coming back waits the delay again. + hover(&mut rt, "copy"); + rt.frame(1.0); + assert!(tip(&rt).is_some()); + rt.pointer_leave(); + rt.frame(1.0 / 60.0); + assert_eq!(tip(&rt), None); + hover(&mut rt, "copy"); + assert_eq!(tip(&rt), None); + + // The tree reports it. + rt.frame(1.0); + let tree = rt.elements(); + assert!(tree.iter().any(|e| e.help.is_some())); +} + +#[test] +fn press_scroll_and_key_hide_it_until_the_pointer_leaves() { + let mut rt = runtime(); + for hide in 0..3 { + hover(&mut rt, "copy"); + rt.frame(1.0); + assert!(tip(&rt).is_some(), "shown ({hide})"); + let (x, y) = centre(&rt, "copy"); + match hide { + 0 => { rt.pointer_down(x, y); rt.pointer_up(x, y); } + 1 => rt.wheel(x, y, 10.0), + _ => rt.key(KeyEvent { key: Key::Escape, mods: Mods::default() }), + } + rt.frame(1.0 / 60.0); + assert_eq!(tip(&rt), None, "hidden ({hide})"); + rt.frame(2.0); + assert_eq!(tip(&rt), None, "stays hidden while the pointer rests ({hide})"); + hover(&mut rt, "plain"); + } + assert_eq!(rt.state.presses, 1, "the press went to the element, not the tooltip"); + hover(&mut rt, "copy"); + rt.frame(1.0); + assert!(tip(&rt).is_some(), "back after leaving"); +} + +#[test] +fn follows_its_element_and_flips_above_at_the_bottom() { + let mut rt = runtime(); + hover(&mut rt, "copy"); + rt.frame(1.0); + let x0 = rt.help_tooltip().unwrap().1[0]; + // The element moves a little under the resting pointer: the tooltip goes with it. + rt.state.inset = 6.0; + rt.invalidate(); + rt.frame(1.0 / 60.0); + let (_, r) = rt.help_tooltip().expect("still shown"); + assert!((r[0] - (x0 + 6.0)).abs() < 1.0 || x0 == 4.0, "{x0} -> {r:?}"); + + hover(&mut rt, "low"); + rt.frame(1.0); + let (text, r) = rt.help_tooltip().unwrap(); + let e = find(&rt, "low"); + assert_eq!(text, "Near the bottom"); + assert!(r[1] + r[3] <= e.rect[1], "above: {r:?} {e:?}"); +} diff --git a/app/vendor/rune/crates/rune/tests/integration/hover_delays.rs b/app/vendor/rune/crates/rune/tests/integration/hover_delays.rs new file mode 100644 index 0000000..9e3a96a --- /dev/null +++ b/app/vendor/rune/crates/rune/tests/integration/hover_delays.rs @@ -0,0 +1,164 @@ +//! `hover_delays`: `on_hover_change` hears an enter only after the pointer rests inside, and a +//! leave only after it stays out; shorter passes report nothing, and a press cancels the wait. +use std::time::Duration; + +use rune::{Cx, El, Env, Runtime, col, el}; + +fn view(_: &Vec<bool>, _: &mut Cx<Vec<bool>>) -> El { + col().w_full().h_full().child( + el().key("zone").w(16.0).h(100.0) + .on_hover_change(|s: &mut Vec<bool>, inside, _| s.push(inside)) + .hover_delays(Duration::from_millis(40), Duration::from_millis(100)), + ) +} + +fn app() -> Runtime<Vec<bool>> { + let mut rt = Runtime::new(Vec::new(), view, (200.0, 200.0), Env::new(true, 1.0)); + rt.frame(0.0); + rt.pointer_move(100.0, 50.0); + rt.frame(0.0); + rt +} + +#[test] +fn an_enter_waits_for_the_pointer_to_rest() { + let mut rt = app(); + rt.pointer_move(8.0, 50.0); + rt.frame(0.03); + assert!(rt.state.is_empty(), "not yet"); + assert!(rt.wake_deadline().is_some(), "the wait asks for a frame"); + rt.frame(0.015); + assert_eq!(rt.state, [true]); + // Moving within it reports nothing more. + rt.pointer_move(10.0, 60.0); + rt.frame(0.1); + assert_eq!(rt.state, [true]); +} + +#[test] +fn a_pass_shorter_than_the_delay_reports_nothing() { + let mut rt = app(); + rt.pointer_move(8.0, 50.0); + rt.frame(0.02); + rt.pointer_move(100.0, 50.0); + rt.frame(0.1); + assert!(rt.state.is_empty()); +} + +#[test] +fn a_leave_waits_out_its_grace_and_a_return_keeps_it() { + let mut rt = app(); + rt.pointer_move(8.0, 50.0); + rt.frame(0.05); + assert_eq!(rt.state, [true]); + rt.pointer_move(100.0, 50.0); + rt.frame(0.05); + rt.pointer_move(8.0, 50.0); + rt.frame(0.2); + assert_eq!(rt.state, [true], "back within the grace"); + rt.pointer_move(100.0, 50.0); + rt.frame(0.09); + assert_eq!(rt.state, [true]); + rt.frame(0.02); + assert_eq!(rt.state, [true, false]); +} + +#[test] +fn a_press_cancels_the_wait_and_the_next_move_starts_it_again() { + let mut rt = app(); + rt.pointer_move(8.0, 50.0); + rt.frame(0.02); + rt.pointer_down(8.0, 50.0); + rt.frame(0.1); + assert!(rt.state.is_empty()); + rt.pointer_up(8.0, 50.0); + rt.pointer_move(9.0, 50.0); + rt.frame(0.03); + assert!(rt.state.is_empty()); + rt.frame(0.02); + assert_eq!(rt.state, [true]); +} + +#[test] +fn blur_cancels_pending_enters_and_ends_shown_hover_without_a_grace() { + let mut rt = app(); + rt.window_focus(true); + rt.pointer_move(8.0, 50.0); + rt.frame(0.02); + rt.window_focus(false); + rt.frame(0.2); + assert!(rt.state.is_empty(), "a pending enter cannot open under a still pointer once blurred"); + rt.window_focus(true); + rt.pointer_move(8.0, 50.0); + rt.frame(0.05); + assert_eq!(rt.state, [true]); + rt.window_focus(false); + rt.frame(0.0); + assert_eq!(rt.state, [true, false], "blur ends even a hover with exit grace"); +} + +/// A window behind another still hears the pointer (macOS sends it moves too), so a tooltip +/// or hover card opens there without a click first. +#[test] +fn a_move_over_a_window_that_isnt_key_starts_the_wait() { + let mut rt = app(); + rt.window_focus(true); + rt.window_focus(false); + rt.pointer_move(8.0, 50.0); + rt.frame(0.03); + assert!(rt.state.is_empty(), "not yet"); + rt.frame(0.015); + assert_eq!(rt.state, [true]); + rt.window_focus(true); + rt.window_focus(false); + rt.frame(0.0); + assert_eq!(rt.state, [true, false]); + rt.frame(0.2); + assert_eq!(rt.state, [true, false], "a still pointer doesn't reopen it"); + rt.pointer_move(9.0, 50.0); + rt.frame(0.05); + assert_eq!(rt.state, [true, false, true], "the next move does"); +} + +#[test] +fn leaving_the_window_cancels_a_pending_enter() { + let mut rt = app(); + rt.pointer_move(8.0, 50.0); + rt.frame(0.02); + rt.pointer_leave(); + rt.frame(0.2); + assert!(rt.state.is_empty()); +} + +/// `gone`: `None` keeps the zone; `Some(instant)` removes it, at once when `instant`, else +/// through its exit. +struct Leaving { gone: Option<bool>, heard: Vec<bool> } + +fn leaving_view(s: &Leaving, _: &mut Cx<Leaving>) -> El { + let zone = el().key("zone").w(16.0).h(100.0) + .on_hover_change(|s: &mut Leaving, inside, _| s.heard.push(inside)) + .hover_delays(Duration::from_millis(40), Duration::from_millis(100)); + col().w_full().h_full().children(s.gone.is_none().then_some(zone)) +} + +fn leaving(rest: f64, instant: bool) -> Vec<bool> { + let mut rt = Runtime::new(Leaving { gone: None, heard: Vec::new() }, leaving_view, (200.0, 200.0), Env::new(true, 1.0)); + rt.frame(0.0); + rt.pointer_move(8.0, 50.0); + rt.frame(rest); + rt.update(move |s, tx| { s.gone = Some(instant); if instant { tx.instant(); } }); + for _ in 0..60 { rt.frame(1.0 / 60.0); } + rt.state.heard +} + +#[test] +fn a_zone_leaving_before_its_enter_reports_nothing() { + assert_eq!(leaving(0.02, false), Vec::<bool>::new(), "through its exit"); + assert_eq!(leaving(0.02, true), Vec::<bool>::new(), "at once"); +} + +#[test] +fn a_shown_zone_leaving_hears_its_leave() { + assert_eq!(leaving(0.05, false), [true, false], "through its exit"); + assert_eq!(leaving(0.05, true), [true, false], "at once"); +} diff --git a/app/vendor/rune/crates/rune/tests/integration/inert.rs b/app/vendor/rune/crates/rune/tests/integration/inert.rs new file mode 100644 index 0000000..ce25266 --- /dev/null +++ b/app/vendor/rune/crates/rune/tests/integration/inert.rs @@ -0,0 +1,161 @@ +//! `El::inert`: a subtree that draws and lays out while the pointer and keyboard pass through. + +use rune::tok::TextStyle; +use rune::{Color, Cursor, Cx, El, Env, Key, KeyEvent, Mods, Runtime, TextEdit, el, text_input}; +use crate::support::{click, find as info}; + +#[derive(Default)] +struct S { + inert: bool, + log: Vec<&'static str>, + hover: Vec<(&'static str, bool)>, + rects: Vec<[f32; 4]>, + field: TextEdit, +} + +/// A canvas that takes presses and shows a crosshair, with a document drawn over it whose +/// own elements would take presses, hovers and focus. +fn view(s: &S, _: &mut Cx<S>) -> El { + let doc = el().key("doc").absolute(0.0, 0.0).size(100.0, 100.0).fill(Color::WHITE) + .on_layout(|s: &mut S, r| s.rects.push(r)) + .child(el().key("button").size(40.0, 40.0).fill(Color::BLACK).cursor(Cursor::Pointer) + .focusable(true) + .on_press(|s: &mut S| s.log.push("button")) + .on_hover_change(|s: &mut S, inside, _| s.hover.push(("button", inside)))) + .child(text_input(&s.field, TextStyle::new(14.0, 400.0)).key("field").w(60.0) + .on_edit(|s: &mut S| &mut s.field)); + el().key("canvas").size(200.0, 200.0).cursor(Cursor::Crosshair) + .on_press(|s: &mut S| s.log.push("canvas")) + .on_hover_change(|s: &mut S, inside, _| s.hover.push(("canvas", inside))) + .child(if s.inert { doc.inert() } else { doc }) +} + +fn runtime(inert: bool) -> Runtime<S> { + let mut rt = Runtime::new(S { inert, ..S::default() }, view, (200.0, 200.0), Env::default()); + rt.frame(0.0); + rt +} + +fn tab(rt: &mut Runtime<S>) { + rt.key(KeyEvent { key: Key::Tab, mods: Mods::default() }); + rt.frame(1.0 / 60.0); +} + +#[test] +fn presses_hovers_and_cursors_fall_through_to_what_is_under() { + let mut rt = runtime(false); + click(&mut rt, (20.0, 20.0)); + assert_eq!(rt.state.log, ["button"], "without inert, the document takes the press"); + assert_eq!(rt.cursor(), Cursor::Pointer); + + let mut rt = runtime(true); + click(&mut rt, (20.0, 20.0)); + assert_eq!(rt.state.log, ["canvas"], "the press goes to the canvas under the document"); + assert_eq!(rt.cursor(), Cursor::Crosshair, "with the canvas's cursor"); + assert!(rt.state.hover.contains(&("canvas", true))); + assert!(!rt.state.hover.iter().any(|(k, _)| *k == "button"), "the document never hovers"); + assert_eq!(info(&rt, "button").hover, 0.0); +} + +#[test] +fn it_still_draws_and_lays_out() { + let mut rt = runtime(true); + rt.frame(1.0 / 60.0); + let doc = info(&rt, "doc"); + assert_eq!(doc.rect, [0.0, 0.0, 100.0, 100.0]); + assert!(doc.opacity > 0.99); + assert!(rt.instances.iter().any(|i| i.rect[2] == 100.0 && i.rect[3] == 100.0), "the document's fill draws"); + assert_eq!(rt.state.rects.last(), Some(&[0.0, 0.0, 100.0, 100.0]), "on_layout still hears its rect"); + assert!(doc.inert && info(&rt, "button").inert, "accessibility reports the subtree inert"); + assert!(!info(&runtime(false), "button").inert); +} + +#[test] +fn nothing_inside_takes_or_keeps_focus() { + let mut rt = runtime(false); + tab(&mut rt); + tab(&mut rt); + assert!(info(&rt, "field").focused || info(&rt, "button").focused, "the document is focusable"); + + let mut rt = runtime(true); + rt.set_full_keyboard_access(true); + tab(&mut rt); + assert!(!info(&rt, "button").focused && !info(&rt, "field").focused, "Tab skips the inert subtree"); + + // A field inside asking for focus doesn't get it. + let mut rt = runtime(true); + rt.update(|s, _| s.field.focused = true); + rt.frame(1.0 / 60.0); + assert!(!info(&rt, "field").focused); + assert!(!rt.state.field.focused, "and the model hears it didn't"); + + // Focus inside drops when the subtree turns inert. + let mut rt = runtime(false); + rt.update(|s, _| s.field.focused = true); + rt.frame(1.0 / 60.0); + assert!(info(&rt, "field").focused); + rt.update(|s, _| s.inert = true); + rt.frame(1.0 / 60.0); + assert!(!info(&rt, "field").focused); + assert!(!rt.state.field.focused); +} + +#[test] +fn canvas_gestures_help_selection_and_held_hover_respect_inert() { + use rune::{MagnifyEvent, PointerButton, WheelEvent, col, text}; + + #[derive(Default)] + struct Canvas { + inert: bool, + wheels: Vec<&'static str>, + pinches: Vec<&'static str>, + middle: Vec<&'static str>, + } + + fn canvas_view(s: &Canvas, _: &mut Cx<Canvas>) -> El { + let doc = col().key("doc").absolute(0.0, 0.0).size(100.0, 100.0) + .hover(Color::WHITE.alpha(0.2)) + .press(Color::WHITE.alpha(0.4)) + .press_scale(0.95) + .help("Document tooltip") + .pointer_buttons([PointerButton::Middle]) + .on_press(|s: &mut Canvas| s.middle.push("doc")) + .on_wheel(|s: &mut Canvas, _, _| { s.wheels.push("doc"); true }) + .on_magnify(|s: &mut Canvas, _, _| { s.pinches.push("doc"); true }) + .child(text("selectable copy").key("copy").selectable(true)); + el().key("canvas").size(200.0, 200.0) + .pointer_buttons([PointerButton::Middle]) + .on_press(|s: &mut Canvas| s.middle.push("canvas")) + .on_wheel(|s: &mut Canvas, _, _| { s.wheels.push("canvas"); true }) + .on_magnify(|s: &mut Canvas, _, _| { s.pinches.push("canvas"); true }) + .child(if s.inert { doc.inert() } else { doc }) + } + + let mut rt = Runtime::new(Canvas { inert: true, ..Canvas::default() }, canvas_view, (200.0, 200.0), Env::default()); + rt.frame(0.0); + rt.wheel_event(WheelEvent::new(0.0, -10.0).at(20.0, 20.0)); + rt.magnify_event(MagnifyEvent::new(0.1).at(20.0, 20.0)); + rt.button_down(20.0, 20.0, PointerButton::Middle); + rt.button_up(20.0, 20.0, PointerButton::Middle); + rt.pointer_move(20.0, 20.0); + rt.frame(1.0); + assert_eq!(rt.state.wheels, ["canvas"], "on_wheel passes through inert"); + assert_eq!(rt.state.pinches, ["canvas"], "on_magnify passes through inert"); + assert_eq!(rt.state.middle, ["canvas"], "middle-button press passes through inert"); + assert!(rt.help_tooltip().is_none(), "inert element shows no tooltip"); + + // Turning inert while hovered/pressed/selected drops the visual hover, press and selection. + let mut rt = Runtime::new(Canvas::default(), canvas_view, (200.0, 200.0), Env::default()); + rt.frame(0.0); + rt.pointer_move(10.0, 5.0); + rt.pointer_down(10.0, 5.0); + rt.pointer_up(10.0, 5.0); + rt.pointer_down(10.0, 5.0); + rt.frame(1.0 / 60.0); + let doc = rt.elements().into_iter().find(|e| e.key.as_deref() == Some("doc")).unwrap(); + assert!(doc.hover > 0.0 && doc.press > 0.0); + rt.update(|s, _| s.inert = true); + for _ in 0..30 { rt.frame(1.0 / 60.0); } + let doc = rt.elements().into_iter().find(|e| e.key.as_deref() == Some("doc")).unwrap(); + assert_eq!((doc.hover, doc.press), (0.0, 0.0), "turning inert clears hover and press tracks"); +} diff --git a/app/vendor/rune/crates/rune/tests/integration/instant_keeps_flight.rs b/app/vendor/rune/crates/rune/tests/integration/instant_keeps_flight.rs new file mode 100644 index 0000000..0268736 --- /dev/null +++ b/app/vendor/rune/crates/rune/tests/integration/instant_keeps_flight.rs @@ -0,0 +1,79 @@ +//! An instant commit lands what it changes and leaves motion an earlier commit started: a key +//! pressed while a width springs doesn't land that width mid-flight. `Tx::settle` still lands it. +use rune::{Cx, El, Env, Runtime, Spring, el, row, text}; + +#[derive(Default)] +struct S { + wide: bool, + dim: bool, + label: &'static str, +} + +fn view(s: &S, _: &mut Cx<S>) -> El { + let grow = el().key("grow").h(40.0).w(if s.wide { 200.0 } else { 100.0 }).motion(Spring::new(0.3, 0.0)) + .opacity(if s.dim { 0.2 } else { 1.0 }); + row().w_full().h_full().child(grow).child(text(s.label).key("label")) +} + +fn app() -> Runtime<S> { + let mut rt = Runtime::new(S { label: "a", ..Default::default() }, view, (400.0, 200.0), Env::new(true, 1.0)); + rt.frame(0.0); + rt +} + +fn width(rt: &Runtime<S>) -> f32 { + rt.elements().into_iter().find(|e| e.key.as_deref() == Some("grow")).unwrap().rect[2] +} + +fn mid_flight() -> Runtime<S> { + let mut rt = app(); + rt.update(|s, tx| { + tx.animated(); + s.wide = true; + s.dim = true; + }); + for _ in 0..4 { + rt.frame(1.0 / 60.0); + } + rt +} + +#[test] +fn an_instant_commit_leaves_a_width_already_springing() { + let mut rt = mid_flight(); + let before = width(&rt); + assert!(before > 100.0 && before < 190.0, "mid-spring: {before}"); + rt.update(|s, tx| { + tx.instant(); + s.label = "b"; + }); + rt.frame(1.0 / 60.0); + let after = width(&rt); + assert!(after > before && after < 195.0, "still springing, not landed: {before} → {after}"); + for _ in 0..90 { + rt.frame(1.0 / 60.0); + } + assert!((width(&rt) - 200.0).abs() < 0.5, "it gets there"); +} + +#[test] +fn an_instant_commit_still_lands_what_it_changes() { + let mut rt = mid_flight(); + rt.update(|s, tx| { + tx.instant(); + s.wide = false; + }); + rt.frame(1.0 / 60.0); + assert_eq!(width(&rt), 100.0); +} + +#[test] +fn settle_lands_motion_already_running() { + let mut rt = mid_flight(); + rt.update(|s, tx| { + tx.settle(); + s.label = "b"; + }); + rt.frame(1.0 / 60.0); + assert_eq!(width(&rt), 200.0); +} diff --git a/app/vendor/rune/crates/rune/tests/integration/keep_stuck.rs b/app/vendor/rune/crates/rune/tests/integration/keep_stuck.rs new file mode 100644 index 0000000..331228f --- /dev/null +++ b/app/vendor/rune/crates/rune/tests/integration/keep_stuck.rs @@ -0,0 +1,176 @@ +//! `Tx::keep_on_screen` on a header stuck to the top of a `stick_bottom` timeline: shutting +//! its group holds the header where it's drawn, and the fold and the scroll agree each frame. +use rune::runtime::ElementInfo; +use rune::{Cx, El, Env, GrowthSpec, Runtime, ScrollSpec, col, el}; + +const STEPS: usize = 40; +const STEP_H: f32 = 28.0; +const HDR_H: f32 = 28.0; +/// Where the group starts in the timeline's content. +const GROUP_TOP: f32 = 200.0; + +#[derive(Clone, Copy, Debug)] +struct Fold { + open: bool, + /// Steps still shown once shut. + left: usize, + /// The header stays sticky once shut (else, like a disclosure, only while open). + sticky_shut: bool, + /// Hidden steps leave the tree when shut (else they stay laid out under a box that ends at + /// the last step still shown). + drop_steps: bool, + virtualized: bool, +} + +impl Fold { + fn new(sticky_shut: bool, drop_steps: bool, virtualized: bool) -> Self { + Fold { open: true, left: 0, sticky_shut, drop_steps, virtualized } + } +} + +fn group(s: &Fold) -> El { + let shown = if s.open { STEPS } else { s.left }; + let mut hdr = el().key("hdr").w_full().h(HDR_H); + if shown > 0 || s.sticky_shut { + hdr = hdr.sticky_top(0.0); + } + let mut g = col().key("group").w_full().child(hdr); + let laid = if s.drop_steps { shown } else { STEPS }; + if laid > 0 { + let steps = col().key("steps").w_full() + .children((0..laid).map(|k| el().key(format!("step-{k}")).w_full().h(STEP_H))); + let held = col().key("steps-box").w_full(); + g = g.child(if shown == laid { held } else { held.h(shown as f32 * STEP_H) }.child(steps)); + } + g +} + +fn row(s: &Fold, i: usize) -> El { + match i { + 0 => el().key("before").w_full().h(GROUP_TOP), + 1 => col().key("turn").w_full().child(group(s)), + 2 => el().key("after").w_full().h(100.0), + _ => el().key("tail").w_full().h(100.0), + } +} + +fn view(s: &Fold, _: &mut Cx<Fold>) -> El { + let mut stack = col().key("stack").w_full().growth(GrowthSpec::default()); + if s.virtualized { + let keys = ["before", "turn", "after", "tail"]; + stack = stack.virtual_rows(4, 100.0, move |_: &Fold, i| keys[i].into(), row); + } else { + for i in 0..4 { stack = stack.child(row(s, i)); } + } + col().key("scroll").size(300.0, 200.0).scroll(ScrollSpec { stick_bottom: true }).child(stack) +} + +fn find(els: &[ElementInfo], key: &str) -> Option<ElementInfo> { + els.iter().find(|e| e.key.as_deref() == Some(key) && !e.exiting).cloned() +} + +/// How much of `e` shows between the header's bottom and the next row's top (both paint over +/// the steps), inside the viewport. +fn shows(e: &ElementInfo, from: f32, to: f32) -> f32 { + let [_, y, _, h] = e.visible; + ((y + h).min(to).min(200.0) - y.max(from)).max(0.0) +} + +/// One frame: the header's top, the next row's top, and the steps that show with their tops. +type Frame = (f32, Option<f32>, Vec<(usize, f32)>); + +/// Opens the group, scrolls `into` points past its header's place (so it sticks when that's +/// above the top), shuts the group down to `left` steps with `keep_on_screen("hdr")`, and +/// samples each frame for two seconds. +fn shut(init: Fold, into: f32, left: usize) -> Vec<Frame> { + let mut rt = Runtime::new(init, view, (300.0, 200.0), Env::new(true, 1.0)); + rt.frame(0.0); + rt.update(move |_, tx| tx.scroll_to_instant("scroll", 0.0, GROUP_TOP + into)); + for _ in 0..4 { rt.frame(1.0 / 120.0); } + let hdr = find(&rt.elements(), "hdr").unwrap(); + assert_eq!(hdr.rect[1], (-into).max(0.0), "{init:?}"); + assert!((hdr.stuck - into.max(0.0)).abs() < 0.5, "{init:?}: stuck {}", hdr.stuck); + let sample = |rt: &Runtime<Fold>| -> Frame { + let els = rt.elements(); + let hdr = find(&els, "hdr").map_or(f32::NAN, |h| h.rect[1]); + let after = find(&els, "after").map(|a| a.rect[1]); + let to = after.unwrap_or(f32::INFINITY); + let steps = (0..STEPS) + .filter_map(|k| find(&els, &format!("step-{k}")).filter(|e| shows(e, hdr + HDR_H, to) > 0.5).map(|e| (k, e.rect[1]))) + .collect(); + (hdr, after, steps) + }; + let mut frames = vec![sample(&rt)]; + rt.update(move |s, tx| { s.open = false; s.left = left; tx.keep_on_screen("hdr"); }); + for _ in 0..240 { + rt.frame(1.0 / 120.0); + frames.push(sample(&rt)); + } + frames +} + +/// The first way `frames` breaks the hold of a header drawn at `at` whose group ends with the +/// next row at `after`, if any. +fn first_break(frames: &[Frame], at: f32, after: f32) -> Option<String> { + for (f, w) in frames.windows(2).enumerate() { + let ((h0, a0, s0), (h1, a1, s1)) = (&w[0], &w[1]); + if (h1 - at).abs() >= 0.5 { return Some(format!("frame {f}: the header moved from {h0} to {h1}")); } + // The steps under the header stay put while the fold covers them: none flashes in. + for (k, y) in s1 { + let was = s0.iter().find(|(j, _)| j == k).map(|s| s.1); + if !was.is_some_and(|was| (y - was).abs() < 0.5) { + return Some(format!("frame {f}: step {k} showed at {y} (was {was:?}; first step before {:?})", s0.first())); + } + } + // The rows below only rise, at the growth spring's pace, never dipping first. + if let (Some(a0), Some(a1)) = (a0, a1) && !(-12.0..0.5).contains(&(a1 - a0)) { + return Some(format!("frame {f}: the row below went from {a0} to {a1}")); + } + } + let (h, a, _) = frames.last().unwrap(); + if (*h, *a) != (at, Some(after)) { + return Some(format!("lands with the header at {h} and the row below at {a:?}")); + } + None +} + +fn check(into: f32, left: usize) { + let mut breaks = vec![]; + for sticky_shut in [false, true] { + for drop_steps in [false, true] { + for virtualized in [false, true] { + let init = Fold::new(sticky_shut, drop_steps, virtualized); + let frames = shut(init, into, left); + if std::env::var_os("KEEP_STUCK_TRACE").is_some() { + for (f, (h, a, s)) in frames.iter().enumerate() { + eprintln!("{init:?} {f}: hdr {h:.2} after {a:?} steps {:?}", s.first()); + } + } + let at = (-into).max(0.0); + let bottom = GROUP_TOP + HDR_H + left as f32 * STEP_H; + let after = (bottom - GROUP_TOP - into).max(at + HDR_H); + if let Some(b) = first_break(&frames, at, after) { breaks.push(format!("{init:?}: {b}")); } + } + } + } + assert!(breaks.is_empty(), "{}", breaks.join("\n")); +} + +#[test] +fn shutting_from_a_stuck_header_holds_it_and_folds_the_rows_under_it() { + // Stuck 500 points into the group, which ends 420 above the top once shut: the header + // unsticks as its group shrinks, and the rows below rise to it before the scroll follows. + check(500.0, 0); +} + +#[test] +fn shutting_part_of_a_group_leaves_its_header_stuck() { + // Twenty steps still reach 88 points below the header: it stays stuck and the scroll + // doesn't move. + check(500.0, 20); +} + +#[test] +fn shutting_from_a_header_that_is_not_stuck_holds_it_as_before() { + check(-40.0, 0); +} diff --git a/app/vendor/rune/crates/rune/tests/integration/key_paths.rs b/app/vendor/rune/crates/rune/tests/integration/key_paths.rs new file mode 100644 index 0000000..0535aa7 --- /dev/null +++ b/app/vendor/rune/crates/rune/tests/integration/key_paths.rs @@ -0,0 +1,73 @@ +//! The scroll requests on `Tx` name elements as `Cx::layout` does, key paths included, so an +//! app can tell apart two elements that share a key (its own `label` and a component's). +use rune::{Cx, El, Env, Runtime, ScrollSpec, col, el, row}; + +/// One of two lists side by side, each with a `label` far down. +fn list(key: &str) -> El { + let rows = (0..30).fold(col().w_full(), |c, _| c.child(el().w_full().h(30.0))); + col().key(key).w(100.0).h(200.0).scroll(ScrollSpec { stick_bottom: false }) + .child(rows.child(el().key("label").w_full().h(30.0))) +} + +fn view(_: &(), _: &mut Cx<()>) -> El { + row().w_full().h_full().child(list("a")).child(list("b")) +} + +fn label_y(rt: &Runtime<()>, nth: usize) -> f32 { + rt.elements().into_iter().filter(|e| e.key.as_deref() == Some("label")).nth(nth).unwrap().rect[1] +} + +fn settled(f: impl FnOnce(&mut rune::Tx)) -> Runtime<()> { + let mut rt = Runtime::new((), view, (200.0, 200.0), Env::default()); + rt.frame(0.0); + assert_eq!((label_y(&rt, 0), label_y(&rt, 1)), (900.0, 900.0)); + rt.update(|_, tx| f(tx)); + for _ in 0..120 { rt.frame(1.0 / 60.0); } + rt +} + +#[test] +fn scroll_into_view_takes_a_key_path() { + let rt = settled(|tx| tx.scroll_into_view("b/label")); + assert!(label_y(&rt, 1) < 200.0, "list b revealed its label: {}", label_y(&rt, 1)); + assert_eq!(label_y(&rt, 0), 900.0, "list a didn't move"); + let rt = settled(|tx| tx.scroll_into_view("label")); + assert!(label_y(&rt, 0) < 200.0 && label_y(&rt, 1) == 900.0, "a bare key still takes the first"); +} + +#[test] +fn scroll_to_bottom_takes_a_key_path() { + let rt = settled(|tx| tx.scroll_to_bottom_instant("b/label")); + assert!(label_y(&rt, 1) < 200.0); + assert_eq!(label_y(&rt, 0), 900.0); +} + +#[test] +fn scroll_to_offset_takes_a_key_path() { + let rt = settled(|tx| tx.scroll_to_instant("b/label", 0.0, 400.0)); + assert_eq!(label_y(&rt, 1), 500.0, "list b scrolled to 400"); + assert_eq!(label_y(&rt, 0), 900.0, "list a didn't move"); +} + +#[test] +fn scroll_into_view_reaches_an_offscreen_virtual_row_by_key_path() { + use rune::GrowthSpec; + + fn vlist(key: &str) -> El { + col().w(100.0).h(100.0).scroll(ScrollSpec { stick_bottom: false }).child( + col().key(key).w_full().growth(GrowthSpec::default()) + .virtual_rows(40, 20.0, |_: &(), i| format!("r{i}").into(), |_, _| el().w_full().h(20.0)), + ) + } + + fn vview(_: &(), _: &mut Cx<()>) -> El { + row().w_full().h_full().child(vlist("a")).child(vlist("b")) + } + + let mut rt = Runtime::new((), vview, (200.0, 100.0), Env::default()); + rt.frame(0.0); + rt.update(|_, tx| tx.scroll_into_view("b/r35")); + for _ in 0..60 { rt.frame(1.0 / 60.0); } + assert!(rt.elements().iter().any(|e| e.path.ends_with("b/r35")), "list b realized row r35"); + assert!(!rt.elements().iter().any(|e| e.path.ends_with("a/r35")), "list a stayed at the top"); +} diff --git a/app/vendor/rune/crates/rune/tests/integration/latest.rs b/app/vendor/rune/crates/rune/tests/integration/latest.rs new file mode 100644 index 0000000..de623d6 --- /dev/null +++ b/app/vendor/rune/crates/rune/tests/integration/latest.rs @@ -0,0 +1,37 @@ +use std::sync::Arc; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::time::Duration; + +use rune::{Cx, El, Env, Latest, Runtime, el, text}; + +/// A window's `poll` that takes the answer commits once per landed answer and stays idle +/// between them. +#[test] +fn poll_changes_state_once_per_answer() { + struct Search { hits: String, results: Latest<String> } + fn view(s: &Search, _: &mut Cx<Search>) -> El { el().child(text(s.hits.clone())) } + let wakes = Arc::new(AtomicUsize::new(0)); + let count = wakes.clone(); + let waker = Arc::new(move || { count.fetch_add(1, Ordering::SeqCst); }); + let state = Search { hits: String::new(), results: Latest::new(waker) }; + let mut rt = Runtime::new(state, view, (200.0, 100.0), Env::default()); + rt.poll = Some(|s, _, _| { + let Some(hits) = s.results.take() else { return false }; + s.hits = hits; + true + }); + rt.frame(0.0); + let commits = rt.stats.commits; + rt.state.results.request("rune".to_owned(), |q| format!("{q}.md")); + let deadline = rune::time::now() + Duration::from_secs(5); + while wakes.load(Ordering::SeqCst) != 1 { + assert!(rune::time::now() < deadline, "timed out waiting until the answer lands"); + std::thread::sleep(Duration::from_millis(1)); + } + rt.frame(1.0 / 60.0); + assert_eq!(rt.state.hits, "rune.md"); + assert_eq!(rt.stats.commits, commits + 1, "the landed answer commits"); + rt.frame(2.0 / 60.0); + rt.frame(3.0 / 60.0); + assert_eq!(rt.stats.commits, commits + 1, "and nothing after it"); +} diff --git a/app/vendor/rune/crates/rune/tests/integration/launch.rs b/app/vendor/rune/crates/rune/tests/integration/launch.rs new file mode 100644 index 0000000..64056e8 --- /dev/null +++ b/app/vendor/rune/crates/rune/tests/integration/launch.rs @@ -0,0 +1,304 @@ +//! `Tx::launch`: a sent message's new row starts on the composer's text at its own size and +//! travels one smooth path into its slot in the scroll view. +use rune::{Cx, El, Env, GrowthSpec, Key, KeyEvent, Runtime, ScrollSpec, TextEdit, TextStyle, Transition, Tx, col, text, text_input}; + +struct State { draft: TextEdit, sent: Vec<String>, relaunch: bool, zoom: f32, ticks: u32, tray: bool, swap: bool, into_body: bool, tail: bool, gap: bool } + +fn view(s: &State, _: &mut Cx<State>) -> El { + let mut rows = col().w_full().growth(GrowthSpec::default()); + let mut order: Vec<usize> = (0..s.sent.len()).collect(); + if s.swap && order.len() > 1 { let n = order.len(); order.swap(n - 2, n - 1); } + for i in order { + let m = &s.sent[i]; + let row = col().key(format!("msg-{i}")).w_full().py(8.0).items_end().child(text(m.clone()).key("body")); + // The last row stops joining the one above: the gap over its text grows, and it with it. + let row = if s.gap && i + 1 == s.sent.len() { row.pt(20.0) } else { row }; + // A new row's container entering with it, as a queue appears with its first prompt. + let tray = || col().key("tray").w_full().transition(Transition::scale(0.9).combined(Transition::opacity())); + rows = rows.child(if s.tray && i == 2 { tray().child(row) } else { row }); + } + rows = rows.child(text(if s.tail { format!("{}\nand\nthe\nrest", s.ticks) } else { format!("{}", s.ticks) }).key("ticks")); + let page = col().w_full().h_full() + .child(col().key("scroll").w_full().grow(1.0).shrink().scroll(ScrollSpec { stick_bottom: true }).child(rows)) + .child(text_input(&s.draft, TextStyle::new(14.0, 400.0)).key("composer").w_full().h(60.0) + .on_edit(|s: &mut State| &mut s.draft) + .on_submit(|s: &mut State, tx: &mut Tx| { + let last = if s.relaunch { s.sent.len() - 1 } else { s.sent.len() }; + if !s.relaunch { s.sent.push(s.draft.text.clone()); } + s.draft.clear(); + tx.launch("composer", if s.into_body { format!("msg-{last}/body") } else { format!("msg-{last}") }); + })); + if s.zoom == 1.0 { return page; } + // An app-wide zoom, as a whole window scaled about its centre. + col().w_full().h_full().center().child(col().w(400.0 / s.zoom).h(300.0 / s.zoom).scale(s.zoom).child(page)) +} + +fn app(relaunch: bool) -> Runtime<State> { + app_at(relaunch, 1.0) +} + +fn app_at(relaunch: bool, zoom: f32) -> Runtime<State> { + let mut draft = TextEdit::new("third"); + draft.focused = true; + let sent = vec!["first".to_string(), "second".to_string()]; + let mut rt = Runtime::new(State { draft, sent, relaunch, zoom, ticks: 0, tray: false, swap: false, into_body: false, tail: false, gap: false }, view, (400.0, 300.0), Env::new(true, 2.0)); + rt.frame(0.0); + rt +} + +fn rect(rt: &Runtime<State>, key: &str, text: Option<&str>) -> ([f32; 4], [f32; 4]) { + let e = rt.elements().into_iter().find(|e| e.key.as_deref() == Some(key) && (text.is_none() || e.text.as_deref() == text)).unwrap(); + (e.rect, e.target) +} + +fn send(rt: &mut Runtime<State>) -> Vec<([f32; 4], [f32; 4])> { + rt.key(KeyEvent { key: Key::Enter, mods: Default::default() }); + (0..120).map(|_| { + rt.frame(1.0 / 120.0); + rect(rt, "body", Some("third")) + }).collect() +} + +#[test] +fn a_launched_row_leaves_from_the_source_text_and_glides_into_place() { + let mut rt = app(false); + let composer = rect(&rt, "composer", None).0; + let frames = send(&mut rt); + let (first, target) = frames[0]; + assert!((first[0] - composer[0]).abs() < 6.0 && first[1] >= composer[1] - 3.0 && first[1] + first[3] <= composer[1] + composer[3] + 3.0, + "the first frame's text sits on the composer's: {first:?} in {composer:?}"); + assert!(target[1] + target[3] < composer[1], "its place is up in the scroll view: {target:?}"); + for (r, t) in &frames { + assert_eq!((r[2], r[3]), (t[2], t[3]), "full size throughout"); + } + let (last, end) = frames[frames.len() - 1]; + assert_eq!(last, end, "lands on its place"); + let land = frames.iter().position(|(r, _)| (r[0] - last[0]).abs() < 0.5 && (r[1] - last[1]).abs() < 0.5).unwrap(); + assert!((24..72).contains(&land), "glides over about 0.2-0.6 s: {land} frames"); + // One monotonic path per axis that slows into its slot: past its fastest frame no step + // outgrows the one before, so it never ends short and snaps the rest. + for axis in 0..2 { + let at: Vec<f32> = frames.iter().map(|(r, _)| r[axis]).collect(); + let total = at[at.len() - 1] - at[0]; + let steps: Vec<f32> = at.windows(2).map(|w| w[1] - w[0]).collect(); + assert!(steps.iter().all(|s| s * total.signum() >= -0.01), "axis {axis} turns back: {at:?}"); + let peak = (0..steps.len()).max_by(|&a, &b| steps[a].abs().total_cmp(&steps[b].abs())).unwrap(); + for k in peak + 1..steps.len() { + assert!(steps[k].abs() <= steps[k - 1].abs() * 1.5 + 0.25, "axis {axis} snaps at frame {k}: {at:?}"); + } + } +} + +#[test] +fn reduced_motion_or_a_mounted_destination_does_not_launch() { + let mut rt = app(false); + rt.set_system_reduced_motion(true); + let frames = send(&mut rt); + assert!(frames.iter().all(|(r, t)| r == t), "Reduce Motion puts it in place"); + + let mut rt = app(true); + rt.key(KeyEvent { key: Key::Enter, mods: Default::default() }); + let frames: Vec<_> = (0..30).map(|_| { rt.frame(1.0 / 120.0); rect(&rt, "body", Some("second")) }).collect(); + assert!(frames.iter().all(|(r, t)| r == t), "an already mounted row stays put"); +} + +#[test] +fn a_launch_whose_slot_moves_mid_flight_lands_there_without_a_lurch() { + let mut rt = app(false); + rt.key(KeyEvent { key: Key::Enter, mods: Default::default() }); + let frames: Vec<_> = (0..120).map(|f| { + // A row above grows while the message is in the air, as a prompt does when the steer + // under it stops joining its run. + if f == 4 { rt.update(|s, _| s.sent[1] = "second\nand a line\nand another".into()); } + rt.frame(1.0 / 120.0); + rect(&rt, "body", Some("third")) + }).collect(); + let (last, end) = frames[frames.len() - 1]; + assert_eq!(last, end, "lands on its moved place"); + for axis in 0..2 { + let at: Vec<f32> = frames.iter().map(|(r, _)| r[axis]).collect(); + let steps: Vec<f32> = at.windows(2).map(|w| w[1] - w[0]).collect(); + for (k, w) in steps.windows(2).enumerate() { + assert!((w[1] - w[0]).abs() <= 10.0, "axis {axis} lurches {} pt at frame {}: {at:?}", w[1] - w[0], k + 1); + } + } +} + +#[test] +fn a_launch_under_a_scaled_ancestor_flies_at_its_drawn_size() { + let zoom = 1.6; + let mut rt = app_at(false, zoom); + let composer = rect(&rt, "composer", None).0; + let frames = send(&mut rt); + let (first, _) = frames[0]; + assert!((first[0] - composer[0]).abs() < 6.0 * zoom && first[1] >= composer[1] - 3.0 && first[1] + first[3] <= composer[1] + composer[3] + 3.0, + "the first frame's text sits on the composer's: {first:?} in {composer:?}"); + for (f, (r, t)) in frames.iter().enumerate() { + assert!((r[2] - t[2] * zoom).abs() < 0.01 && (r[3] - t[3] * zoom).abs() < 0.01, "frame {f}: drawn at the zoom: {r:?} vs {t:?}"); + } + let (last, _) = frames[frames.len() - 1]; + for _ in 0..30 { rt.frame(1.0 / 120.0); } + assert_eq!(rect(&rt, "body", Some("third")).0, last, "landed where it rests"); + for axis in 0..2 { + let at: Vec<f32> = frames.iter().map(|(r, _)| r[axis]).collect(); + let total = at[at.len() - 1] - at[0]; + for w in at.windows(2) { + assert!((w[1] - w[0]) * total.signum() >= -0.01, "axis {axis} turns back: {at:?}"); + assert!((w[1] - w[0]).abs() <= total.abs().max(20.0) / 10.0, "axis {axis} snaps: {at:?}"); + } + } +} + +#[test] +fn a_launch_after_another_commit_in_its_frame_still_leaves_from_the_source() { + // Something else changes state in the frame Enter lands in, as a server event or a cleared + // attachment does: that commit comes first, and the launch must still map through the zoom. + let zoom = 1.6; + let mut rt = app_at(false, zoom); + let composer = rect(&rt, "composer", None).0; + rt.update(|s, _| s.ticks += 1); + let frames = send(&mut rt); + let (first, _) = frames[0]; + assert!((first[0] - composer[0]).abs() < 6.0 * zoom && first[1] >= composer[1] - 3.0 && first[1] + first[3] <= composer[1] + composer[3] + 3.0, + "the first frame's text sits on the composer's: {first:?} in {composer:?}"); + for axis in 0..2 { + let at: Vec<f32> = frames.iter().map(|(r, _)| r[axis]).collect(); + let total = at[at.len() - 1] - at[0]; + assert!(at.windows(2).all(|w| (w[1] - w[0]) * total.signum() >= -0.01), "axis {axis} turns back: {at:?}"); + } +} + +#[test] +fn a_launch_into_an_entering_container_keeps_the_zoom_above_it() { + // The container's entrance scale is dropped while the row flies; the app's still zoom above + // it is not, so the row flies at the size it lands at and doesn't snap when the entrance ends. + let zoom = 1.6; + let mut rt = app_at(false, zoom); + rt.update(|s, _| s.tray = true); + rt.frame(0.0); + let mut frames = send(&mut rt); + frames.extend((0..120).map(|_| { rt.frame(1.0 / 120.0); rect(&rt, "body", Some("third")) })); + for (f, (r, t)) in frames.iter().enumerate() { + assert!((r[2] - t[2] * zoom).abs() < 0.01 && (r[3] - t[3] * zoom).abs() < 0.01, "frame {f}: drawn at the zoom: {r:?} vs {t:?}"); + } + for axis in 0..2 { + let at: Vec<f32> = frames.iter().map(|(r, _)| r[axis]).collect(); + let total = at[at.len() - 1] - at[0]; + for w in at.windows(2) { + assert!((w[1] - w[0]) * total.signum() >= -0.01, "axis {axis} turns back: {at:?}"); + assert!((w[1] - w[0]).abs() <= total.abs().max(20.0) / 10.0, "axis {axis} snaps: {at:?}"); + } + } +} + +#[test] +fn a_launch_whose_row_reorders_mid_flight_slides_and_lands_without_a_lurch() { + // 0.13 s into the flight the new row moves above the one before it, as a steer the server + // takes up moves above the Working row. The launch targets the row, or a text inside it. + for into_body in [false, true] { + let mut rt = app(false); + rt.update(|s, _| s.into_body = into_body); + rt.frame(0.0); + rt.key(KeyEvent { key: Key::Enter, mods: Default::default() }); + let frames: Vec<_> = (0..180).map(|f| { + if f == 16 { rt.update(|s, _| s.swap = true); } + rt.frame(1.0 / 120.0); + let passed = rt.elements().into_iter().find(|e| e.key.as_deref() == Some("msg-1")).unwrap().rect; + (rect(&rt, "body", Some("third")), passed) + }).collect(); + let ((last, end), _) = frames[frames.len() - 1]; + assert_eq!(last, end, "into_body {into_body}: lands on its slid place"); + let body: Vec<[f32; 4]> = frames.iter().map(|f| f.0.0).collect(); + let passed: Vec<[f32; 4]> = frames.iter().map(|f| f.1).collect(); + for (name, at, axes) in [("body", &body, 0..2), ("the passed row", &passed, 1..2)] { + for axis in axes { + let at: Vec<f32> = at.iter().map(|r| r[axis]).collect(); + let steps: Vec<f32> = at.windows(2).map(|w| w[1] - w[0]).collect(); + for (k, w) in steps.windows(2).enumerate() { + assert!((w[1] - w[0]).abs() <= 4.0, "into_body {into_body}: {name} axis {axis} lurches {} pt at frame {}: {at:?}", w[1] - w[0], k + 1); + } + } + } + } +} + +#[test] +fn a_launch_reaimed_while_the_scroll_view_corrects_under_it_keeps_its_speed() { + // The rows below grow while it flies, so sticking to the bottom scrolls it: part of its + // speed comes from offsets outside the scene, which the re-aimed path has to carry on. + for (at, into_body) in [(6, false), (8, false), (12, false), (16, false), (8, true)] { + let mut rt = app(false); + rt.update(|s, _| { s.into_body = into_body; for k in 0..12 { s.sent.insert(0, format!("earlier {k}")); } }); + for _ in 0..60 { rt.frame(1.0 / 120.0); } + rt.key(KeyEvent { key: Key::Enter, mods: Default::default() }); + let body: Vec<[f32; 4]> = (0..40).map(|f| { + if f == 1 { rt.update(|s, _| s.tail = true); } + if f == at { rt.update(|s, _| s.swap = true); } + rt.frame(1.0 / 120.0); + rect(&rt, "body", Some("third")).0 + }).collect(); + for axis in 0..2 { + let steps: Vec<f32> = body.windows(2).map(|w| w[1][axis] - w[0][axis]).collect(); + // How much its per-frame step changes: on the re-aim frame, between what the spring + // does on the frames either side, as a spring retargeted at its own speed would. + let change: Vec<f32> = steps.windows(2).map(|w| w[1] - w[0]).collect(); + let (before, reaim, after) = (change[at - 3], change[at - 2], change[at - 1]); + assert!(reaim >= before.min(after) - 0.1 && reaim <= before.max(after) + 0.1, + "re-aimed at {at}, into_body {into_body}: axis {axis} step changes {before} then {reaim} then {after}: {steps:?}"); + } + } +} + +#[test] +fn a_landed_launch_whose_row_grows_a_gap_over_it_at_a_pinned_end_holds_still() { + // The row stops joining the one above: the gap over its text and its height grow by 12 pt, + // so the list scrolls 12 pt and the text keeps its place. Whether its flight has as good as + // landed (its springs settling) or ended, it doesn't sink and come back. + for at in [80, 100, 160] { + for into_body in [false, true] { + let mut rt = app(false); + rt.update(|s, _| { s.into_body = into_body; for k in 0..12 { s.sent.insert(0, format!("earlier {k}")); } }); + for _ in 0..60 { rt.frame(1.0 / 120.0); } + rt.key(KeyEvent { key: Key::Enter, mods: Default::default() }); + for _ in 0..at { rt.frame(1.0 / 120.0); } + let (y0, row0) = (rect(&rt, "body", Some("third")).0[1], rect(&rt, "msg-2", None).0[1]); + rt.update(|s, _| s.gap = true); + let ys: Vec<f32> = (0..120).map(|_| { rt.frame(1.0 / 120.0); rect(&rt, "body", Some("third")).0[1] }).collect(); + assert!(ys.iter().all(|y| (y - y0).abs() <= 1.0 / 64.0), "at {at}, into_body {into_body}: the text moves from {y0}: {ys:?}"); + assert!((rect(&rt, "msg-2", None).0[1] - (row0 - 12.0)).abs() < 0.01, "at {at}: the row rises by its gap"); + } + } +} + +#[test] +fn a_launch_is_judged_against_the_scroll_it_rides() { + // The rows below grow while it flies, so the pinned end scrolls under it. It leaves under + // the offsets it launched against and takes on the scroll as it lands, so against what it + // rides it makes one motion up into its slot, however the scroll adds to it on screen. + // Re-aimed mid-flight, its path takes over what the flight added to the offsets, and how + // much of the scroll it rides doesn't step. + for reaim in [None, Some(8)] { + let mut rt = app(false); + rt.update(|s, _| { for k in 0..12 { s.sent.insert(0, format!("earlier {k}")); } }); + for _ in 0..60 { rt.frame(1.0 / 120.0); } + rt.key(KeyEvent { key: Key::Enter, mods: Default::default() }); + let body = |rt: &Runtime<State>| rt.elements().into_iter().find(|e| e.key.as_deref() == Some("body") && e.text.as_deref() == Some("third")).unwrap(); + let ys: Vec<f32> = (0..120).map(|f| { + if f == 1 { rt.update(|s, _| s.tail = true); } + if Some(f) == reaim { rt.update(|s, _| s.swap = true); } + rt.frame(1.0 / 120.0); + let e = body(&rt); + e.rect[1] + e.scrolled[1] + }).collect(); + let scroll = rt.elements().into_iter().find(|e| e.key.as_deref() == Some("scroll")).unwrap(); + assert!(scroll.rect[1] + 1.0 < ys[0], "it starts below the list"); + let steps: Vec<f32> = ys.windows(2).map(|w| w[1] - w[0]).collect(); + assert!(steps.iter().all(|d| *d <= 0.01), "re-aimed at {reaim:?}, it never heads down: {ys:?}"); + // Its slot a row up, the re-aim pulls it on 2 to 3 pt a frame faster; the offsets its + // flight added, folded into its path, would have stepped it 12 pt back. + assert!(steps.windows(2).all(|w| (w[1] - w[0]).abs() < 3.0), "re-aimed at {reaim:?}, no step in what it rides: {steps:?}"); + assert!(ys[0] - ys[119] > 4.0, "it rises into its slot: {ys:?}"); + let landed = body(&rt); + assert!(landed.scrolled[1] > 0.0, "landed, it rides the whole scroll: {:?}", landed.scrolled); + } +} diff --git a/app/vendor/rune/crates/rune/tests/integration/launch_ancestor_spring.rs b/app/vendor/rune/crates/rune/tests/integration/launch_ancestor_spring.rs new file mode 100644 index 0000000..47f5bf1 --- /dev/null +++ b/app/vendor/rune/crates/rune/tests/integration/launch_ancestor_spring.rs @@ -0,0 +1,66 @@ +//! `Tx::launch` into a panel pinned to the bottom of the window: each new row grows the panel, +//! which springs up, and the rows already there go up with it. +use rune::{Cx, El, Env, Key, KeyEvent, Runtime, TextEdit, TextStyle, Tx, col, el, text_input}; + +struct State { draft: TextEdit, rows: usize } + +fn view(s: &State, _: &mut Cx<State>) -> El { + let mut list = col().key("list").w_full(); + for i in 0..s.rows { + list = list.child(el().key(format!("row-{i}")).w_full().h(32.0)); + } + col().w_full().h_full() + .child(el().grow(1.0)) + .child(col().key("panel").w_full().pt(6.0).child(list)) + .child(text_input(&s.draft, TextStyle::new(14.0, 400.0)).key("composer").w_full().h(60.0) + .on_edit(|s: &mut State| &mut s.draft) + .on_submit(|s: &mut State, tx: &mut Tx| { + s.draft.clear(); + tx.launch("composer", format!("row-{}", s.rows)); + s.rows += 1; + })) +} + +fn y(rt: &Runtime<State>, key: &str) -> f32 { + rt.elements().into_iter().find(|e| e.key.as_deref() == Some(key)).unwrap().rect[1] +} + +fn send(rt: &mut Runtime<State>) { + rt.update(|s, _| s.draft = TextEdit::new("next")); + rt.update(|s, _| s.draft.focused = true); + rt.key(KeyEvent { key: Key::Enter, mods: Default::default() }); +} + +/// Sends a first row, then a second `after` frames later, and returns the first row's drawn +/// top on the frame before the second send and every frame from it on, with the list's. +fn second_send(after: usize) -> Vec<(f32, f32)> { + let mut rt = Runtime::new(State { draft: TextEdit::new(""), rows: 0 }, view, (400.0, 300.0), Env::new(true, 2.0)); + rt.frame(0.0); + send(&mut rt); + for _ in 0..after { rt.frame(1.0 / 120.0); } + let before = (y(&rt, "row-0"), y(&rt, "list")); + send(&mut rt); + std::iter::once(before).chain((0..120).map(|_| { rt.frame(1.0 / 120.0); (y(&rt, "row-0"), y(&rt, "list")) })).collect() +} + +#[test] +fn a_launched_row_goes_up_with_its_springing_panel_without_a_jump() { + for after in [20, 90] { + let frames = second_send(after); + let at: Vec<f32> = frames.iter().map(|f| f.0).collect(); + let steps: Vec<f32> = at.windows(2).map(|w| w[1] - w[0]).collect(); + let worst = steps.iter().copied().fold(0.0f32, |a, s| if s.abs() > a.abs() { s } else { a }); + assert!(worst.abs() < 4.0, "second send {after} frames on: the first row steps {worst} pt in a frame: {at:?}"); + let (row, list) = frames[frames.len() - 1]; + assert_eq!(row, list, "it lands at the top of the list"); + } +} + +#[test] +fn a_landed_launch_rides_its_springing_panel() { + let frames = second_send(90); + for (f, (row, list)) in frames.iter().enumerate() { + assert!((row - list).abs() < 0.25, "frame {f}: the first row sits on the list's top: {row} vs {list}"); + } +} + diff --git a/app/vendor/rune/crates/rune/tests/integration/layout_read.rs b/app/vendor/rune/crates/rune/tests/integration/layout_read.rs new file mode 100644 index 0000000..f49040d --- /dev/null +++ b/app/vendor/rune/crates/rune/tests/integration/layout_read.rs @@ -0,0 +1,586 @@ +//! Views read another element's laid-out rect (`Cx::layout`) and handlers hear about it +//! (`El::on_layout`), re-running only when it moves, and settling when a view reads +//! something its own output resizes. +use rune::runtime::ElementInfo; +use rune::{Cx, El, Env, Runtime, ScrollSpec, col, el, row, text}; +use std::cell::Cell; + +#[derive(Default)] +struct S { + banner: bool, + views: Cell<u32>, + rects: Vec<[f32; 4]>, + grow_by: f32, + width: f32, +} + +fn find(rt: &Runtime<S>, key: &str) -> ElementInfo { + rt.elements().into_iter().find(|e| e.key.as_deref() == Some(key)).unwrap_or_else(|| panic!("{key}")) +} + +fn frames(rt: &mut Runtime<S>, n: usize) { + for _ in 0..n { rt.frame(1.0 / 120.0); } +} + +/// A timeline below a banner; a badge hangs from the banner's bottom by reading its rect. +fn banner_view(s: &S, cx: &mut Cx<S>) -> El { + s.views.set(s.views.get() + 1); + assert_eq!(cx.layout("no-such-key"), None); + let mut root = col().w_full().h_full().padding(10.0) + .child(el().key("banner").w_full().h(if s.banner { 55.0 } else { 20.0 }) + .on_layout(|s: &mut S, r| s.rects.push(r))) + .child(col().key("timeline").w_full().grow(1.0).shrink()); + if let Some([x, y, w, h]) = cx.layout("banner") { + root = root.child(el().key("badge").absolute(x + w - 30.0, y + h).size(30.0, 10.0)); + } + root +} + +#[test] +fn a_view_places_from_another_elements_rect_in_the_same_commit() { + let mut rt = Runtime::new(S::default(), banner_view, (300.0, 400.0), Env::new(true, 2.0)); + rt.frame(0.0); + assert_eq!(find(&rt, "badge").target, [260.0, 30.0, 30.0, 10.0], "placed on the first frame"); + rt.state.banner = true; + rt.invalidate(); + rt.frame(1.0 / 120.0); + assert_eq!(find(&rt, "badge").target, [260.0, 65.0, 30.0, 10.0], "moved in the commit that grew the banner"); + + // Animation frames re-run nothing and report nothing; settled, nothing re-runs. + let views = rt.state.views.get(); + frames(&mut rt, 120); + assert_eq!(rt.state.views.get(), views + 1, "one re-run, for on_layout's state change"); + assert_eq!(rt.state.rects, [[10.0, 10.0, 280.0, 20.0], [10.0, 10.0, 280.0, 55.0]], "once on layout, once on change"); + let commits = rt.stats.commits; + frames(&mut rt, 10); + assert_eq!(rt.stats.commits, commits); +} + +/// Rows in a scroll; a marker outside it follows row 10 as it scrolls. +fn scroll_view(s: &S, cx: &mut Cx<S>) -> El { + s.views.set(s.views.get() + 1); + let rows = (0..40).fold(col().w_full(), |c, i| c.child(el().key(format!("r{i}")).w_full().h(30.0))); + let mut root = col().w_full().h_full() + .child(col().key("scroll").w_full().h(300.0).scroll(ScrollSpec { stick_bottom: false }).child(rows)); + if let Some([_, y, _, _]) = cx.window_layout("r10") { + root = root.child(el().key("marker").absolute(0.0, y).size(10.0, 10.0)); + } + root +} + +#[test] +fn scrolling_moves_a_read_rect_and_re_runs_its_reader() { + let mut rt = Runtime::new(S::default(), scroll_view, (300.0, 400.0), Env::new(true, 2.0)); + rt.frame(0.0); + assert_eq!(find(&rt, "marker").target[1], 300.0); + rt.wheel(100.0, 100.0, -120.0); + frames(&mut rt, 60); + let row = find(&rt, "r10").rect[1]; + assert!(row < 250.0, "scrolled: {row}"); + assert_eq!(find(&rt, "marker").target[1], row, "the marker follows the row"); + let views = rt.state.views.get(); + frames(&mut rt, 10); + assert_eq!(rt.state.views.get(), views, "still once scrolling stops"); +} + +/// A card reads its own width to pick a layout: two columns when wide, one when narrow. +fn responsive(s: &S, cx: &mut Cx<S>) -> El { + s.views.set(s.views.get() + 1); + let wide = cx.layout("card").is_some_and(|r| r[2] >= 400.0); + let body = if wide { row().key("body").gap(10.0) } else { col().key("body").gap(10.0) }; + col().w_full().padding(10.0).child( + col().key("card").w_full().child(body.child(el().key("a").w(150.0).h(40.0)).child(el().key("b").w(150.0).h(40.0))), + ) +} + +#[test] +fn a_view_reading_its_own_size_settles() { + let mut rt = Runtime::new(S::default(), responsive, (600.0, 400.0), Env::new(true, 2.0)); + rt.frame(0.0); + assert_eq!(find(&rt, "b").target[1], find(&rt, "a").target[1], "wide: side by side on the first frame"); + rt.set_viewport((300.0, 400.0), 2.0); + frames(&mut rt, 2); + assert!(find(&rt, "b").target[1] > find(&rt, "a").target[1], "narrow: stacked"); + frames(&mut rt, 60); + let (views, commits) = (rt.state.views.get(), rt.stats.commits); + frames(&mut rt, 30); + assert_eq!((rt.state.views.get(), rt.stats.commits), (views, commits), "settled"); +} + +/// A chip that reads its own width and swaps to the label that flips it back: no fixed point. +fn flip_flop(s: &S, cx: &mut Cx<S>) -> El { + s.views.set(s.views.get() + 1); + let wide = cx.layout("chip").is_some_and(|r| r[2] > 100.0); + let label = if wide { "short" } else { "a much longer label than that" }; + col().w_full().items_start().child(row().key("chip").child(text(label))) +} + +#[test] +fn a_view_without_a_fixed_point_stops_instead_of_oscillating() { + let mut rt = Runtime::new(S::default(), flip_flop, (600.0, 400.0), Env::new(true, 2.0)); + rt.frame(0.0); + let first = rt.state.views.get(); + assert!(first <= 4, "one commit re-runs the view at most twice more ({first} runs)"); + frames(&mut rt, 120); + let (views, commits) = (rt.state.views.get(), rt.stats.commits); + frames(&mut rt, 60); + assert_eq!((rt.state.views.get(), rt.stats.commits), (views, commits), "no commits of its own"); +} + +/// A handler feeding an element's width back into it, growing forever if allowed. +fn runaway(s: &S, _: &mut Cx<S>) -> El { + let grow_by = s.grow_by; + col().w_full().child(el().key("bar").w(s.width.max(10.0)).h(10.0).on_layout(move |s: &mut S, r| { + s.rects.push(r); + s.width = r[2] + grow_by; + })) +} + +#[test] +fn on_layout_feedback_settles() { + // A handler that reaches a fixed point: once to lay out, once for the change it caused. + let mut rt = Runtime::new(S { grow_by: 0.0, width: 50.0, ..S::default() }, runaway, (600.0, 400.0), Env::new(true, 2.0)); + rt.frame(0.0); + frames(&mut rt, 30); + assert_eq!(rt.state.rects.len(), 1, "{:?}", rt.state.rects); + + // One that never would: it stops after a few commits, then nothing re-runs. + let mut rt = Runtime::new(S { grow_by: 10.0, width: 50.0, ..S::default() }, runaway, (600.0, 400.0), Env::new(true, 2.0)); + rt.frame(0.0); + frames(&mut rt, 60); + let reports = rt.state.rects.len(); + assert!((2..=6).contains(&reports), "{:?}", rt.state.rects); + let commits = rt.stats.commits; + frames(&mut rt, 60); + assert_eq!((rt.state.rects.len(), rt.stats.commits), (reports, commits)); + + // Changes it missed meanwhile are not replayed; the next change from anywhere else is + // reported, and feedback may run again. + rt.invalidate(); + frames(&mut rt, 10); + assert_eq!(rt.state.rects.len(), reports); + rt.state.width = 200.0; + rt.invalidate(); + frames(&mut rt, 60); + assert_eq!(rt.state.rects[reports], [0.0, 0.0, 200.0, 10.0], "{:?}", rt.state.rects); + assert!(rt.state.rects.len() > reports + 1, "{:?}", rt.state.rects); +} + +#[derive(Default)] +struct Editor { + editing: bool, + field: rune::TextEdit, +} + +/// An inline editor placed over a node by reading its rect, so it first appears on the +/// commit's re-run, never on its first measure. +fn editor_view(s: &Editor, cx: &mut Cx<Editor>) -> El { + let mut root = col().w_full().h_full().padding(10.0).child(el().key("node").size(120.0, 30.0)); + if s.editing && let Some([x, y, w, _]) = cx.layout("node") { + root = root.child(rune::text_input(&s.field, rune::tok::TextStyle::new(14.0, 400.0)) + .key("editor").absolute(x, y).w(w).on_edit(|s: &mut Editor| &mut s.field)); + } + root +} + +#[test] +fn a_field_that_appears_on_the_re_run_takes_the_focus_it_asks_for() { + let mut rt = Runtime::new(Editor::default(), editor_view, (300.0, 200.0), Env::new(true, 2.0)); + rt.frame(0.0); + rt.update(|s, _| { s.editing = true; s.field.focused = true; }); + rt.frame(1.0 / 120.0); + let editor = rt.elements().into_iter().find(|e| e.key.as_deref() == Some("editor")).expect("placed in this commit"); + assert_eq!(editor.target[..2], [10.0, 10.0]); + assert!(editor.focused, "focused in the commit that placed it"); + rt.key(rune::KeyEvent { key: rune::Key::Text("a".into()), mods: Default::default() }); + rt.frame(1.0 / 120.0); + assert_eq!(rt.state.field.text, "a", "typing reaches it"); +} + +#[test] +fn a_focused_field_remounting_after_a_layout_read_does_not_steal_newer_focus() { + #[derive(Default)] + struct Two { + step: u8, + first: rune::TextEdit, + second: rune::TextEdit, + } + + fn two_view(s: &Two, cx: &mut Cx<Two>) -> El { + let mut root = col().w_full().h_full() + .child(el().key("anchor").size(100.0, 20.0)) + .child(rune::text_input(&s.second, rune::tok::TextStyle::new(14.0, 400.0)) + .key("second").w(100.0).on_edit(|s: &mut Two| &mut s.second)); + if s.step == 0 { + root = root.child(el().key("early").child( + rune::text_input(&s.first, rune::tok::TextStyle::new(14.0, 400.0)) + .key("first").w(100.0).on_edit(|s: &mut Two| &mut s.first), + )); + } else if s.step == 2 && cx.layout("anchor").is_some() { + root = root.child(el().key("late").child( + rune::text_input(&s.first, rune::tok::TextStyle::new(14.0, 400.0)) + .key("first").w(100.0).on_edit(|s: &mut Two| &mut s.first), + )); + } + root + } + + let mut rt = Runtime::new(Two::default(), two_view, (300.0, 200.0), Env::new(true, 2.0)); + rt.update(|s, _| s.first.focused = true); + rt.frame(0.0); + // Unmount `first` while it still has `first.focused = true`, and focus `second`. + rt.update(|s, _| { s.step = 1; s.second.focused = true; }); + rt.frame(1.0 / 60.0); + // Remount `first` under a new path on a layout-read re-run: `second` keeps focus. + rt.update(|s, _| s.step = 2); + rt.frame(1.0 / 60.0); + let focused: Vec<_> = rt.elements().into_iter().filter(|e| e.focused).filter_map(|e| e.key).collect(); + assert_eq!(focused, ["second"], "remounted field must not steal focus from the newer field"); + assert!(rt.state.second.focused && !rt.state.first.focused); +} + +/// How `sized_view` reads row 10. +#[derive(Clone, Copy, Debug, Default)] +enum Read { + #[default] + Size, + Rect, + Window, +} + +#[derive(Default)] +struct SizeRead { + read: Read, + tall: bool, + views: Cell<u32>, +} + +/// Rows in a scroll; a bar below it echoes row 10's size, read with `layout_size`, `layout` +/// or `window_layout`. +fn sized_view(s: &SizeRead, cx: &mut Cx<SizeRead>) -> El { + s.views.set(s.views.get() + 1); + let rows = (0..40).fold(col().w_full(), |c, i| { + c.child(el().key(format!("r{i}")).w_full().h(if i == 10 && s.tall { 50.0 } else { 30.0 })) + }); + let size = match s.read { + Read::Size => cx.layout_size("r10"), + Read::Rect => cx.layout("r10").map(|r| [r[2], r[3]]), + Read::Window => cx.window_layout("r10").map(|r| [r[2], r[3]]), + }; + let mut root = col().w_full().h_full() + .child(col().key("scroll").w_full().h(300.0).scroll(ScrollSpec { stick_bottom: false }).child(rows)); + if let Some([w, h]) = size { + root = root.child(el().key("echo").w(w).h(h)); + } + root +} + +fn echo(rt: &Runtime<SizeRead>) -> [f32; 4] { + rt.elements().into_iter().find(|e| e.key.as_deref() == Some("echo")).expect("echo").target +} + +/// View runs and commits over 60 frames of a trackpad-like scroll, a wheel event a frame. +fn scroll_runs(read: Read) -> (u32, u64) { + let mut rt = Runtime::new(SizeRead { read, ..SizeRead::default() }, sized_view, (300.0, 400.0), Env::new(true, 2.0)); + rt.frame(0.0); + for _ in 0..10 { rt.frame(1.0 / 120.0); } + let (views, commits) = (rt.state.views.get(), rt.stats.commits); + let before = rt.elements().into_iter().find(|e| e.key.as_deref() == Some("r10")).unwrap().rect[1]; + for _ in 0..60 { + rt.wheel(100.0, 100.0, -3.0); + rt.frame(1.0 / 120.0); + } + let after = rt.elements().into_iter().find(|e| e.key.as_deref() == Some("r10")).unwrap().rect[1]; + assert!(after < before - 50.0, "scrolled: {before} -> {after}"); + (rt.state.views.get() - views, rt.stats.commits - commits) +} + +#[test] +fn only_a_window_read_re_runs_its_view_while_the_element_scrolls() { + let size = scroll_runs(Read::Size); + let rect = scroll_runs(Read::Rect); + let window = scroll_runs(Read::Window); + eprintln!("60 scroll frames (views, commits): layout_size {size:?}; layout {rect:?}; window_layout {window:?}"); + assert_eq!(size, (0, 0), "position moves alone don't re-run a size read"); + assert_eq!(rect, (0, 0), "a whole-rect read is unscrolled: a scroll doesn't move it"); + assert!(window.0 >= 50 && window.1 >= 50, "a window read follows the scroll ({window:?})"); +} + +#[test] +fn a_size_read_re_runs_its_view_when_the_element_resizes() { + let mut rt = Runtime::new(SizeRead::default(), sized_view, (300.0, 400.0), Env::new(true, 2.0)); + rt.frame(0.0); + assert_eq!(echo(&rt)[2..], [300.0, 30.0], "settled on the first frame"); + + // Its own height, in the commit that changed it. + rt.update(|s, _| s.tall = true); + rt.frame(1.0 / 120.0); + assert_eq!(echo(&rt)[2..], [300.0, 50.0]); + + // Its width, from a parent resize. + rt.set_viewport((420.0, 400.0), 2.0); + rt.frame(1.0 / 120.0); + assert_eq!(echo(&rt)[2..], [420.0, 50.0]); + + let views = rt.state.views.get(); + for _ in 0..30 { rt.frame(1.0 / 120.0); } + assert_eq!(rt.state.views.get(), views, "settled"); +} + +/// A card reads its own width with `layout_size` to pick two columns or one. +fn responsive_size(s: &S, cx: &mut Cx<S>) -> El { + s.views.set(s.views.get() + 1); + let wide = cx.layout_size("card").is_some_and(|[w, _]| w >= 400.0); + let body = if wide { row().key("body").gap(10.0) } else { col().key("body").gap(10.0) }; + col().w_full().padding(10.0).child( + col().key("card").w_full().child(body.child(el().key("a").w(150.0).h(40.0)).child(el().key("b").w(150.0).h(40.0))), + ) +} + +#[test] +fn a_view_reading_its_own_size_with_layout_size_settles_on_the_first_frame() { + let mut rt = Runtime::new(S::default(), responsive_size, (600.0, 400.0), Env::new(true, 2.0)); + rt.frame(0.0); + assert_eq!(find(&rt, "b").target[1], find(&rt, "a").target[1], "wide: side by side on the first frame"); + rt.set_viewport((300.0, 400.0), 2.0); + rt.frame(1.0 / 120.0); + assert!(find(&rt, "b").target[1] > find(&rt, "a").target[1], "narrow in the commit that resized it"); + frames(&mut rt, 60); + let (views, commits) = (rt.state.views.get(), rt.stats.commits); + frames(&mut rt, 30); + assert_eq!((rt.state.views.get(), rt.stats.commits), (views, commits), "settled"); +} + +#[derive(Default)] +struct Header { + /// What each view run read: whether row 1 has scrolled past the top. + seen: std::cell::RefCell<Vec<Option<bool>>>, +} + +/// A header that turns solid once row 1 scrolls past the top of the window. +fn header_view(s: &Header, cx: &mut Cx<Header>) -> El { + let past = cx.window_layout_with("r1", |r| r[1] < 0.0); + s.seen.borrow_mut().push(past); + let rows = (0..40).fold(col().w_full(), |c, i| c.child(el().key(format!("r{i}")).w_full().h(30.0))); + let header = el().key(if past == Some(true) { "solid" } else { "clear" }).w_full().h(20.0); + col().w_full().h_full() + .child(col().key("scroll").w_full().h(300.0).scroll(ScrollSpec { stick_bottom: false }).child(rows)) + .child(header) +} + +#[test] +fn a_layout_with_read_settles_on_the_first_layout() { + let mut rt = Runtime::new(Header::default(), header_view, (300.0, 400.0), Env::new(true, 2.0)); + rt.frame(0.0); + assert_eq!(rt.state.seen.borrow().last(), Some(&Some(false)), "{:?}", rt.state.seen.borrow()); + assert!(rt.elements().iter().any(|e| e.key.as_deref() == Some("clear"))); +} + +#[test] +fn a_layout_with_read_re_runs_its_view_only_when_its_value_flips() { + let mut rt = Runtime::new(Header::default(), header_view, (300.0, 400.0), Env::new(true, 2.0)); + rt.frame(0.0); + for _ in 0..10 { rt.frame(1.0 / 120.0); } + rt.state.seen.borrow_mut().clear(); + let r1 = |rt: &Runtime<Header>| rt.elements().into_iter().find(|e| e.key.as_deref() == Some("r1")).unwrap().rect[1]; + + // Down past the top: one run, on the frame it flips. + let commits = rt.stats.commits; + let mut flipped_at = None; + for frame in 0..20 { + rt.wheel(100.0, 100.0, -3.0); + rt.frame(1.0 / 120.0); + if flipped_at.is_none() && r1(&rt) < 0.0 { flipped_at = Some(frame); } + assert_eq!(rt.state.seen.borrow().len(), usize::from(flipped_at.is_some()), "frame {frame}: y {}", r1(&rt)); + } + assert!(r1(&rt) < -20.0, "scrolled past: {}", r1(&rt)); + assert_eq!(*rt.state.seen.borrow(), [Some(true)]); + assert!(rt.elements().iter().any(|e| e.key.as_deref() == Some("solid")), "solid in the frame it flipped"); + assert_eq!(rt.stats.commits - commits, 1, "one commit over 20 scrolled frames"); + + // And back: one more. + for frame in 0..20 { + rt.wheel(100.0, 100.0, 3.0); + rt.frame(1.0 / 120.0); + let back = r1(&rt) >= 0.0; + assert_eq!(rt.state.seen.borrow().len(), 1 + usize::from(back), "frame {frame}: y {}", r1(&rt)); + if back { break; } + } + for _ in 0..20 { + rt.wheel(100.0, 100.0, 3.0); + rt.frame(1.0 / 120.0); + } + assert_eq!(*rt.state.seen.borrow(), [Some(true), Some(false)]); + assert!(rt.elements().iter().any(|e| e.key.as_deref() == Some("clear"))); + assert_eq!(rt.stats.commits - commits, 2); +} + +#[derive(Default)] +struct Bar { + width: f32, + top: f32, + views: Cell<u32>, +} + +/// Reads one bar's whole rect and its size: the size check must not be lost under the rect read. +fn both_view(s: &Bar, cx: &mut Cx<Bar>) -> El { + s.views.set(s.views.get() + 1); + let _ = cx.layout("bar"); + let w = cx.layout_size("bar").map_or(0.0, |[w, _]| w); + col().w_full().items_start().child(el().key("bar").w(s.width).h(10.0)).child(el().key("echo").w(w).h(10.0)) +} + +#[test] +fn a_whole_rect_read_keeps_a_size_read_of_the_same_key_exact() { + let mut rt = Runtime::new(Bar { width: 100.0, ..Bar::default() }, both_view, (300.0, 200.0), Env::new(true, 2.0)); + rt.frame(0.0); + rt.update(|s, _| s.width = 100.4); + rt.frame(1.0 / 120.0); + let echo = rt.elements().into_iter().find(|e| e.key.as_deref() == Some("echo")).unwrap().target[2]; + assert!((echo - 100.4).abs() < 1e-3, "a 0.4 pt resize reaches the size read: {echo}"); +} + +#[test] +fn drift_below_the_threshold_adds_up_until_a_whole_rect_read_re_runs() { + let mut rt = Runtime::new(S::default(), scroll_view, (300.0, 400.0), Env::new(true, 2.0)); + rt.frame(0.0); + for _ in 0..100 { + rt.wheel(100.0, 100.0, -0.4); + rt.frame(1.0 / 120.0); + } + let (row, marker) = (find(&rt, "r10").rect[1], find(&rt, "marker").target[1]); + assert!(row < 270.0, "scrolled 40 pt: {row}"); + assert!((marker - row).abs() <= 0.5, "the marker follows within half a point: marker {marker}, row {row}"); +} + +#[derive(Default)] +struct Gate { + width: f32, + views: Cell<u32>, +} + +/// Reads `b` only once `a`'s rect matches the state, so `b` goes unread on a commit's first pass. +fn gate_view(s: &Gate, cx: &mut Cx<Gate>) -> El { + s.views.set(s.views.get() + 1); + let ready = cx.layout("a").is_some_and(|r| (r[2] - s.width).abs() < 0.01); + let b = if ready { cx.layout("b") } else { None }; + col().w_full().items_start() + .child(el().key("a").w(s.width).h(10.0)) + .child(el().key("b").w(50.0).h(10.0)) + .child(el().key("echo").w(b.map_or(0.0, |r| r[2])).h(5.0)) +} + +#[test] +fn a_key_unread_on_one_settling_pass_keeps_its_rect_for_the_next() { + let mut rt = Runtime::new(Gate { width: 100.0, ..Gate::default() }, gate_view, (300.0, 200.0), Env::new(true, 2.0)); + rt.frame(0.0); + for _ in 0..10 { rt.frame(1.0 / 120.0); } + let views = rt.state.views.get(); + rt.update(|s, _| s.width = 200.0); + rt.frame(1.0 / 120.0); + let echo = rt.elements().into_iter().find(|e| e.key.as_deref() == Some("echo")).unwrap().target[2]; + assert_eq!(echo, 50.0); + assert_eq!(rt.state.views.get() - views, 2, "one pass with a stale, one to settle"); +} + +/// Echoes the size of an element a third of 100 tall, below a gap the state sets. +fn third_view(s: &Bar, cx: &mut Cx<Bar>) -> El { + s.views.set(s.views.get() + 1); + let h = cx.layout_size("third").map_or(0.0, |[_, h]| h); + col().w_full().items_start() + .child(el().key("gap").w(10.0).h(s.top)) + .child(el().key("third").w(10.0).h(100.0 / 3.0)) + .child(el().key("echo").w(10.0).h(h)) +} + +#[test] +fn moving_an_element_does_not_change_the_size_a_read_sees() { + let mut rt = Runtime::new(Bar::default(), third_view, (300.0, 400.0), Env::new(true, 2.0)); + rt.frame(0.0); + for top in [33.4, 50.0, 31.0, 64.1] { + let views = rt.state.views.get(); + rt.update(|s, _| s.top = top); + rt.frame(1.0 / 120.0); + assert_eq!(rt.state.views.get() - views, 1, "a move to {top} re-ran the size read"); + } +} + +/// A marker follows row 10 through a scroll, beside a bar whose `on_layout` grows it forever. +fn capped_view(s: &S, cx: &mut Cx<S>) -> El { + s.views.set(s.views.get() + 1); + let rows = (0..40).fold(col().w_full(), |c, i| c.child(el().key(format!("r{i}")).w_full().h(30.0))); + let grow_by = s.grow_by; + let mut root = col().w_full().h_full().items_start() + .child(col().key("scroll").w_full().h(300.0).scroll(ScrollSpec { stick_bottom: false }).child(rows)) + .child(el().key("bar").w(s.width.max(10.0)).h(10.0).on_layout(move |s: &mut S, r| s.width = r[2] + grow_by)); + if let Some([_, y, _, _]) = cx.window_layout("r10") { + root = root.child(el().key("marker").absolute(0.0, y).size(10.0, 10.0)); + } + root +} + +#[test] +fn the_first_scroll_frame_after_feedback_stops_still_moves_a_read() { + let mut rt = Runtime::new(S { grow_by: 10.0, width: 50.0, ..S::default() }, capped_view, (600.0, 400.0), Env::new(true, 2.0)); + rt.frame(0.0); + frames(&mut rt, 60); + let commits = rt.stats.commits; + frames(&mut rt, 10); + assert_eq!(rt.stats.commits, commits, "feedback stopped"); + rt.wheel(100.0, 100.0, -30.0); + rt.frame(1.0 / 120.0); + assert_eq!(find(&rt, "marker").target[1], find(&rt, "r10").rect[1], "followed on the first scroll frame"); +} + +#[derive(Default)] +struct Board { + tall: bool, + builds: Cell<u32>, +} + +/// A memo below a scrolling list shows `memo::layout` of row 10 inside it. +fn board_view(s: &Board, _: &mut Cx<Board>) -> El { + let rows = (0..40).fold(col().w_full(), |c, i| { + c.child(el().key(format!("r{i}")).w_full().h(if i == 10 && s.tall { 50.0 } else { 30.0 })) + }); + col().w_full().h_full() + .child(col().key("scroll").w_full().h(300.0).scroll(ScrollSpec { stick_bottom: false }).child(rows)) + .child(rune::memo::memo("label", 0, || { + s.builds.set(s.builds.get() + 1); + text(format!("{:?}", rune::memo::layout("r10"))).key("label") + })) +} + +#[test] +fn a_memo_layout_read_inside_a_scrolled_viewport_commits_nothing_while_it_scrolls() { + let mut rt = Runtime::new(Board::default(), board_view, (300.0, 400.0), Env::new(true, 2.0)); + rt.frame(0.0); + frames_of(&mut rt, 10); + let label = |rt: &Runtime<Board>| rt.elements().into_iter().find(|e| e.key.as_deref() == Some("label")).and_then(|e| e.text); + let r10 = |rt: &Runtime<Board>| rt.elements().into_iter().find(|e| e.key.as_deref() == Some("r10")).unwrap().rect; + assert_eq!(label(&rt).as_deref(), Some("Some([0.0, 300.0, 300.0, 30.0])")); + let (commits, builds) = (rt.stats.commits, rt.state.builds.get()); + + // A programmatic, animated scroll, then a wheel scroll. + rt.update_if(|_, tx| { tx.scroll_to_y("scroll", 200.0); false }); + frames_of(&mut rt, 60); + assert_eq!(r10(&rt)[1], 100.0, "scrolled 200"); + for _ in 0..60 { + rt.wheel(100.0, 100.0, -3.0); + rt.frame(1.0 / 120.0); + } + frames_of(&mut rt, 60); + assert!(r10(&rt)[1] < 0.0, "scrolled on: {:?}", r10(&rt)); + assert_eq!((rt.stats.commits, rt.state.builds.get()), (commits, builds), "no commits, no builds"); + assert_eq!(label(&rt).as_deref(), Some("Some([0.0, 300.0, 300.0, 30.0])"), "unscrolled"); + + // A real size change still rebuilds, in the commit that made it. + rt.update(|s, _| s.tall = true); + rt.frame(1.0 / 120.0); + assert_eq!(label(&rt).as_deref(), Some("Some([0.0, 300.0, 300.0, 50.0])")); + assert!(rt.state.builds.get() > builds); +} + +fn frames_of<S: 'static>(rt: &mut Runtime<S>, n: usize) { + for _ in 0..n { rt.frame(1.0 / 120.0); } +} diff --git a/app/vendor/rune/crates/rune/tests/integration/layout_read_highlights.rs b/app/vendor/rune/crates/rune/tests/integration/layout_read_highlights.rs new file mode 100644 index 0000000..9d6cd4e --- /dev/null +++ b/app/vendor/rune/crates/rune/tests/integration/layout_read_highlights.rs @@ -0,0 +1,94 @@ +//! Layout reads of text highlights and keyed elements stay right while a list scrolls (frames +//! that reuse what a lookup found before) and after a commit moves what a key names. +use std::cell::RefCell; + +use rune::{Color, Cx, El, Env, Runtime, ScrollSpec, TextHighlight, TextStyle, col, text}; + +struct S { + hit_row: usize, + /// Element keys read besides the highlight, so lookups go through an index. + extra_reads: usize, + seen: RefCell<Option<[f32; 4]>>, + seen_rows: RefCell<Vec<Option<[f32; 4]>>>, +} + +fn view(s: &S, cx: &mut Cx<S>) -> El { + *s.seen.borrow_mut() = cx.window_layout(&format!("row{}/mark", s.hit_row)); + *s.seen_rows.borrow_mut() = (0..s.extra_reads).map(|i| cx.window_layout(&format!("row{i}"))).collect(); + let rows = (0..30).fold(col().w_full(), |c, i| { + // Every row's text has a highlight keyed `mark`: the scoped read picks one row's. + let body = text(format!("row {i} text with a mark in it")) + .font(TextStyle::new(14.0, 400.0).lh(20.0)) + .text_highlight(TextHighlight::new(18..22, Color::WHITE).key("mark")); + c.child(col().key(format!("row{i}")).w_full().h(40.0).py(10.0).child(body)) + }); + col().w_full().h_full().child(col().key("list").w_full().h(200.0).scroll(ScrollSpec { stick_bottom: false }).child(rows)) +} + +fn settle(rt: &mut Runtime<S>) { + for _ in 0..600 { if !rt.frame(1.0 / 60.0) { return; } } + panic!("never settled"); +} + +/// The highlight `mark` in row `row` as `[x, y, w, h]`, and row `i`s rect, from the tree. +fn mark_of(rt: &Runtime<S>, row: usize) -> [f32; 4] { + let scope = format!("/row{row}/"); + let e = rt.elements().into_iter() + .find(|e| e.key.as_deref() == Some("mark") && e.path.contains(&scope)) + .unwrap_or_else(|| panic!("mark in row {row}")); + e.rect +} + +fn row_of(rt: &Runtime<S>, i: usize) -> [f32; 4] { + let key = format!("row{i}"); + rt.elements().into_iter().find(|e| e.key.as_deref() == Some(key.as_str())).expect("row").rect +} + +fn close(a: [f32; 4], b: [f32; 4]) -> bool { + a.iter().zip(b).all(|(x, y)| (x - y).abs() < 0.75) +} + +fn check(rt: &Runtime<S>, when: &str) { + let seen = rt.state.seen.borrow().unwrap_or_else(|| panic!("{when}: read saw nothing")); + let mark = mark_of(rt, rt.state.hit_row); + assert!(close(seen, mark), "{when}: read {seen:?}, mark at {mark:?}"); + for (i, seen) in rt.state.seen_rows.borrow().iter().enumerate() { + let seen = seen.unwrap_or_else(|| panic!("{when}: row{i} read saw nothing")); + let row = row_of(rt, i); + assert!(close(seen, row), "{when}: row{i} read {seen:?}, row at {row:?}"); + } +} + +fn reads_follow_scrolls_and_commits(extra_reads: usize) { + let s = S { hit_row: 6, extra_reads, seen: RefCell::new(None), seen_rows: RefCell::new(Vec::new()) }; + let mut rt = Runtime::new(s, view, (300.0, 300.0), Env::new(true, 1.0)); + rt.frame(0.0); + settle(&mut rt); + check(&rt, "first layout"); + + for dy in [-120.0, -160.0, 200.0] { + let before = mark_of(&rt, rt.state.hit_row)[1]; + rt.wheel(100.0, 100.0, dy); + settle(&mut rt); + assert_ne!(mark_of(&rt, rt.state.hit_row)[1], before, "the wheel scrolled"); + check(&rt, &format!("wheeled {dy}")); + } + + // A commit names another row's highlight; frames after it look it up in the new tree. + rt.update(|s, _| s.hit_row = 2); + settle(&mut rt); + check(&rt, "after the commit"); + rt.wheel(100.0, 100.0, 400.0); + settle(&mut rt); + check(&rt, "wheeled back after the commit"); +} + +#[test] +fn a_scoped_highlight_read_follows_scrolls_and_commits() { + reads_follow_scrolls_and_commits(0); +} + +#[test] +fn many_reads_follow_scrolls_and_commits() { + reads_follow_scrolls_and_commits(12); +} diff --git a/app/vendor/rune/crates/rune/tests/integration/links.rs b/app/vendor/rune/crates/rune/tests/integration/links.rs new file mode 100644 index 0000000..e681bf1 --- /dev/null +++ b/app/vendor/rune/crates/rune/tests/integration/links.rs @@ -0,0 +1,221 @@ +//! Pressable spans in rich text: only a link's shaped glyph boxes take the pointer; it shows a +//! hand, paints its hover and pressed looks, is a Tab stop pressed by Enter or Space, and is +//! reported to tools with its role. + +use rune::runtime::ElementInfo; +use rune::{Color, Cursor, Cx, El, Env, Key, KeyEvent, Link, LinkPaint, Mods, Runtime, Span, TextEdit, TextStyle, col, rich, text_input}; +use crate::support::{centre, click, find}; + +const TEXT: &str = "Hi @kit see docs and notes.md ok"; +const WRAPS: &str = "go to a very long link that wraps"; + +struct S { draft: TextEdit, opened: Vec<String> } + +fn at(s: &str, part: &str) -> std::ops::Range<usize> { + let i = s.find(part).unwrap(); + i..i + part.len() +} + +fn hover_bg() -> Color { rune::color::hex("#ff0055").unwrap() } +fn pressed_bg() -> Color { rune::color::hex("#00ff55").unwrap() } + +fn view(s: &S, _: &mut Cx<S>) -> El { + let style = TextStyle::new(14.0, 400.0).lh(20.0); + let accent = rune::color::hex("#3080ff").unwrap(); + let spans = ["@kit", "docs", "notes.md"].map(|p| { let r = at(TEXT, p); Span { color: Some(accent), ..Span::new(r.start, r.end) } }).to_vec(); + let paint = LinkPaint::new().bg(hover_bg()).underline(accent); + col().w_full().h_full().padding(10.0).gap(10.0) + .child(text_input(&s.draft, style).key("composer").w_full().on_edit(|s: &mut S| &mut s.draft)) + .child(rich(TEXT, spans).key("message").font(style).w(400.0) + .link(Link::new(at(TEXT, "@kit"), "user:kit").label("Kit").hover(paint).pressed(LinkPaint::new().bg(pressed_bg()))) + .link(Link::new(at(TEXT, "docs"), "https://docs").hover(paint)) + .link(Link::new(at(TEXT, "notes.md"), "file:notes.md").role("button").hover(paint)) + .on_link(|s: &mut S, id, _| s.opened.push(id.to_owned()))) + .child(rich(WRAPS, Vec::new()).key("wrapped").font(style).w(90.0) + .link(Link::new(at(WRAPS, "a very long link"), "long")) + .on_link(|s: &mut S, id, _| s.opened.push(id.to_owned()))) +} + +fn key(rt: &mut Runtime<S>, key: Key, shift: bool) { + rt.key(KeyEvent { key, mods: Mods { shift, ..Mods::default() } }); + rt.frame(1.0 / 60.0); +} + +fn painted(rt: &Runtime<S>, c: Color) -> bool { + let want = c.premul(1.0); + rt.instances.iter().any(|i| i.fill.iter().zip(want).all(|(a, b)| (a - b).abs() < 1e-3)) +} + +fn focused_link(rt: &Runtime<S>) -> Option<String> { + rt.elements().into_iter().find(|e| e.focused && e.path.contains("#link-")).and_then(|e| e.key) +} + +#[test] +fn links_hit_by_their_glyphs_press_and_take_keyboard_focus() { + let mut draft = TextEdit::new(""); + draft.focused = true; + let mut rt = Runtime::new(S { draft, opened: Vec::new() }, view, (500.0, 300.0), Env::new(true, 2.0)); + rt.frame(0.0); + + // Tools see each link with its role and name, inside its text. + let message = find(&rt, "message"); + let (kit, docs, notes) = (find(&rt, "user:kit"), find(&rt, "https://docs"), find(&rt, "file:notes.md")); + assert_eq!((kit.role, kit.label.as_deref(), kit.text.as_deref()), ("link", Some("Kit"), Some("@kit"))); + assert_eq!((notes.role, notes.label.as_deref()), ("button", Some("notes.md"))); + for l in [&kit, &docs, &notes] { + assert!(l.focusable && l.rect[2] > 10.0 && l.rect[3] > 10.0, "{l:?}"); + assert!(l.rect[0] >= message.rect[0] && l.rect[0] + l.rect[2] <= message.rect[0] + message.rect[2], "{l:?} in {:?}", message.rect); + } + assert!(kit.rect[0] + kit.rect[2] < docs.rect[0] && docs.rect[0] + docs.rect[2] < notes.rect[0], "in text order"); + assert!(!message.focusable, "the links are the stops, not the paragraph"); + + // Hover: a hand and the hover paint over the link only. + assert!(!painted(&rt, hover_bg())); + let (x, y) = centre(&docs); + rt.pointer_move(x, y); + rt.frame(1.0 / 60.0); + assert_eq!(rt.cursor(), Cursor::Pointer); + assert_eq!(find(&rt, "https://docs").hover, 1.0); + assert!(painted(&rt, hover_bg()), "hover background"); + let between = (kit.rect[0] + kit.rect[2] + docs.rect[0]) / 2.0; + rt.pointer_move(between, y); + rt.frame(1.0 / 60.0); + assert_eq!(rt.cursor(), Cursor::Default, "plain text between links"); + assert_eq!(find(&rt, "https://docs").hover, 0.0); + assert!(!painted(&rt, hover_bg())); + + // Pressed look while held; a click opens it and leaves the composer focused. + let (x, y) = centre(&kit); + rt.pointer_move(x, y); + rt.pointer_down(x, y); + rt.frame(1.0 / 60.0); + assert!(painted(&rt, pressed_bg()) && find(&rt, "user:kit").press == 1.0, "pressed look"); + rt.pointer_up(x, y); + rt.frame(1.0 / 60.0); + assert_eq!(rt.state.opened, ["user:kit"]); + assert!(rt.state.draft.focused, "clicking a link keeps the composer's focus"); + + // Plain text takes no press; a press dragged to another link opens nothing. + click(&mut rt, (between, y)); + let (dx, dy) = centre(&docs); + rt.pointer_move(x, y); + rt.pointer_down(x, y); + rt.pointer_move(dx, dy); + rt.pointer_up(dx, dy); + rt.frame(1.0 / 60.0); + assert_eq!(rt.state.opened, ["user:kit"]); + + // A wrapped link takes its second line but not the plain words beside its first. + let long = find(&rt, "long"); + assert!(long.rect[3] > 30.0, "two lines: {long:?}"); + click(&mut rt, (long.rect[0] + 3.0, long.rect[1] + 3.0)); + assert_eq!(rt.state.opened, ["user:kit"], "\"go to\" sits inside the link's bounding box but is not the link"); + click(&mut rt, (long.rect[0] + 3.0, long.rect[1] + long.rect[3] - 3.0)); + assert_eq!(rt.state.opened, ["user:kit", "long"]); + + // Keyboard: each link is a Tab stop after the composer; Enter and Space press it; + // Shift+Tab walks back. (The click on plain text blurred the composer.) + key(&mut rt, Key::Tab, false); + assert!(rt.state.draft.focused); + key(&mut rt, Key::Tab, false); + assert_eq!(focused_link(&rt).as_deref(), Some("user:kit")); + assert!(find(&rt, "user:kit").focus_visible); + assert!(!rt.state.draft.focused); + key(&mut rt, Key::Tab, false); + key(&mut rt, Key::Tab, false); + assert_eq!(focused_link(&rt).as_deref(), Some("file:notes.md")); + key(&mut rt, Key::Enter, false); + key(&mut rt, Key::Tab, true); + assert_eq!(focused_link(&rt).as_deref(), Some("https://docs")); + key(&mut rt, Key::Text(" ".into()), false); + assert_eq!(rt.state.opened, ["user:kit", "long", "file:notes.md", "https://docs"]); + assert!(painted(&rt, hover_bg()), "the focused link shows its hover look"); + key(&mut rt, Key::Tab, false); + key(&mut rt, Key::Tab, false); + assert_eq!(focused_link(&rt).as_deref(), Some("long"), "on to the next text's link"); + key(&mut rt, Key::Tab, false); + assert_eq!(focused_link(&rt), None); + assert!(rt.state.draft.focused, "and round to the composer"); +} + +const EMOJI: &str = "😀😀 @kit 🎉 docs"; +const CENTRED: &str = "go to a very long link that wraps"; + +fn link_ink() -> Color { rune::color::hex("#ff8800").unwrap() } + +fn emoji_view(_: &S, _: &mut Cx<S>) -> El { + let style = TextStyle::new(14.0, 400.0).lh(20.0); + let paint = LinkPaint::new().color(link_ink()); + col().w_full().h_full().padding(10.0).gap(10.0) + .child(rich(EMOJI, Vec::new()).key("emoji").font(style).w(300.0) + .link(Link::new(at(EMOJI, "@kit"), "user:kit").hover(paint)) + .link(Link::new(at(EMOJI, "🎉 docs"), "party").hover(paint)) + .on_link(|s: &mut S, id, _| s.opened.push(id.to_owned()))) + .child(rich(CENTRED, Vec::new()).key("centred").font(style).w(120.0).align(rune::Align::Center) + .link(Link::new(at(CENTRED, "a very long link"), "long").hover(paint)) + .on_link(|s: &mut S, id, _| s.opened.push(id.to_owned()))) +} + +/// Device-px rects `[x, y, w, h]` of glyphs drawn in `c`, and of colour emoji images. +fn drawn(rt: &Runtime<S>, c: Color) -> (Vec<[f32; 4]>, Vec<[f32; 4]>) { + let want = c.premul(1.0); + let glyphs = rt.instances.iter().filter(|i| i.params[1] == rune::render::KIND_GLYPH + && i.fill.iter().zip(want).all(|(a, b)| (a - b).abs() < 1e-3)).map(|i| i.rect).collect(); + let images = rt.instances.iter().filter(|i| i.params[1] == rune::render::KIND_IMAGE).map(|i| i.rect).collect(); + (glyphs, images) +} + +fn mid(r: [f32; 4], s: f32) -> (f32, f32) { ((r[0] + r[2] / 2.0) / s, (r[1] + r[3] / 2.0) / s) } + +fn inside((x, y): (f32, f32), e: &ElementInfo) -> bool { + x >= e.rect[0] && x <= e.rect[0] + e.rect[2] && y >= e.rect[1] && y <= e.rect[1] + e.rect[3] +} + +fn hovers(rt: &mut Runtime<S>, (x, y): (f32, f32)) -> bool { + rt.pointer_move(x, y); + rt.frame(1.0 / 60.0); + rt.cursor() == Cursor::Pointer +} + +#[test] +fn link_boxes_match_drawn_glyphs_beside_emoji_and_in_centred_lines() { + let mut rt = Runtime::new(S { draft: TextEdit::new(""), opened: Vec::new() }, emoji_view, (500.0, 300.0), Env::new(true, 2.0)); + rt.frame(0.0); + let s = 2.0; + + // Each link's recoloured glyphs, drawn while hovered, sit inside its hit box, and each + // glyph's centre takes the pointer. + for (key, glyph_count) in [("user:kit", 4), ("party", 4), ("long", 13)] { + let link = find(&rt, key); + // Where a script aims: the centre of the link's first line box. The centre of a wrapped + // link's union can sit on the edge between its lines, which hits neither. + let aim = rt.find(key).unwrap(); + assert!(hovers(&mut rt, aim), "{key} centre"); + let (glyphs, _) = drawn(&rt, link_ink()); + assert_eq!(glyphs.len(), glyph_count, "{key}: {glyphs:?}"); + for g in glyphs { + assert!(inside(mid(g, s), &link), "{key} glyph {g:?} outside {:?}", link.rect); + assert!(hovers(&mut rt, mid(g, s)), "{key} glyph {g:?} misses"); + } + } + + // Emoji: the two before @kit take no press, the one inside "🎉 docs" opens it. + let (_, images) = drawn(&rt, link_ink()); + if images.is_empty() { + eprintln!("skipping emoji hit checks: no colour emoji font installed"); + return; + } + assert_eq!(images.len(), 3, "{images:?}"); + let (kit, party) = (find(&rt, "user:kit"), find(&rt, "party")); + let mut images = images; + images.sort_by(|a, b| a[0].total_cmp(&b[0])); + for e in &images[..2] { + assert!(!inside(mid(*e, s), &kit) && !hovers(&mut rt, mid(*e, s)), "leading emoji {e:?}"); + } + assert!(kit.rect[0] * s > images[1][0] + images[1][2] - 1.0, "@kit starts after the emoji"); + assert!(inside(mid(images[2], s), &party) && hovers(&mut rt, mid(images[2], s)), "🎉 is part of its link"); + rt.pointer_down(mid(images[2], s).0, mid(images[2], s).1); + rt.pointer_up(mid(images[2], s).0, mid(images[2], s).1); + rt.frame(1.0 / 60.0); + assert_eq!(rt.state.opened, ["party"]); +} diff --git a/app/vendor/rune/crates/rune/tests/integration/live.rs b/app/vendor/rune/crates/rune/tests/integration/live.rs new file mode 100644 index 0000000..8875a3b --- /dev/null +++ b/app/vendor/rune/crates/rune/tests/integration/live.rs @@ -0,0 +1,286 @@ +use std::sync::{Arc, atomic::{AtomicUsize, Ordering}}; +use rune::{Color, Cx, El, Env, Live, Runtime, Spring, el}; +use rune::Tween; + +struct State { + opacity: Live<f32>, offset: Live<[f32; 2]>, scale: Live<f32>, fill: Live<Color>, + bound: bool, smooth: bool, +} +fn state() -> State { + State { opacity: Live::new(0.8), offset: Live::new([10.0, 20.0]), scale: Live::new(1.0), + fill: Live::new(Color::WHITE), bound: true, smooth: false } +} +fn view(s: &State, _: &mut Cx<State>) -> El { + let mut child = el().key("live").size(40.0, 20.0).fill(Color::BLACK); + if s.bound { + child = child.live_opacity(&s.opacity).live_scale(&s.scale).live_fill(&s.fill); + child = if s.smooth { child.live_offset(s.offset.smooth(Spring::new(0.25, 0.0))) } + else { child.live_offset(&s.offset) }; + } + el().size(300.0, 300.0).child(child) +} +fn runtime(s: State) -> Runtime<State> { + Runtime::new(s, view, (300.0, 300.0), Env::new(true, 2.0)) +} + +#[test] +fn properties_change_without_view_layout_or_shaping_and_stop_at_rest() { + let mut rt = runtime(state()); + rt.frame(0.0); + let commits = rt.stats.commits; + rt.state.offset.set([60.0, 80.0]); + rt.state.opacity.set(0.4); + rt.state.scale.set(1.5); + rt.state.fill.set(Color { r: 0.2, g: 0.4, b: 0.6, a: 1.0 }); + assert!(rt.live_pending()); + assert!(!rt.frame(1.0 / 120.0)); + assert!(!rt.live_pending()); + assert_eq!(rt.stats.commits, commits); + assert_eq!(rt.stats.shaped, 0); + let n = rt.elements().into_iter().find(|e| e.key.as_deref() == Some("live")).unwrap(); + assert_eq!(n.rect, [50.0, 75.0, 60.0, 30.0]); + assert!((n.opacity - 0.4).abs() < 0.001); + assert!((n.fill.r - 0.2).abs() < 0.001); + rt.invalidate(); rt.frame(0.0); + let n = rt.elements().into_iter().find(|e| e.key.as_deref() == Some("live")).unwrap(); + assert!((n.fill.r - 0.2).abs() < 0.001, "live fill survives an unrelated view rebuild"); + assert!(!rt.state.opacity.set(0.4)); + assert!(!rt.live_pending()); +} + +#[test] +fn one_source_wakes_two_windows_independently_and_unbinding_stops_wakes() { + let mut a = runtime(state()); + let mut b_state = state(); + b_state.opacity = a.state.opacity.clone(); + let mut b = runtime(b_state); + let count = Arc::new(AtomicUsize::new(0)); + for rt in [&mut a, &mut b] { + let count = count.clone(); + rt.set_live_waker(Arc::new(move || { count.fetch_add(1, Ordering::Relaxed); })); + rt.frame(0.0); + } + a.state.opacity.set(0.2); + assert_eq!(count.load(Ordering::Relaxed), 2); + a.frame(0.01); b.frame(0.01); + b.set_live_visible(false); + a.state.opacity.set(0.3); + assert_eq!(count.load(Ordering::Relaxed), 3); + a.frame(0.01); + b.set_live_visible(true); + assert_eq!(count.load(Ordering::Relaxed), 4); + b.frame(0.01); + b.state.bound = false; + b.invalidate(); b.frame(0.01); + a.state.opacity.set(0.4); + assert_eq!(count.load(Ordering::Relaxed), 5); + assert!(!b.live_pending()); +} + +#[test] +fn smoothing_survives_rebuild_and_retargets_then_settles() { + let mut s = state(); s.smooth = true; + let mut rt = runtime(s); + assert!(!rt.frame(0.0)); + rt.state.offset.set([160.0, 20.0]); + assert!(rt.frame(0.05)); + let x = |rt: &Runtime<State>| rt.elements().into_iter().find(|e| e.key.as_deref() == Some("live")).unwrap().rect[0]; + let before = x(&rt); + assert!(before > 10.0 && before < 160.0); + rt.invalidate(); rt.frame(0.0); + assert_eq!(x(&rt), before); + rt.state.offset.set([80.0, 20.0]); + rt.frame(0.01); + for _ in 0..240 { rt.frame(1.0 / 120.0); } + assert_eq!(x(&rt), 80.0); + assert!(!rt.animating); +} + +#[test] +fn removing_last_binding_consumes_an_already_pending_wake() { + let mut rt = runtime(state()); rt.frame(0.0); + rt.state.opacity.set(0.3); + assert!(rt.live_pending()); + rt.state.bound = false; + rt.invalidate(); rt.frame(0.0); + assert!(!rt.live_pending()); + rt.state.offset.set([200.0, 200.0]); + assert!(!rt.live_pending()); +} + +#[test] +fn connecting_a_waker_to_a_hidden_runtime_keeps_publications_asleep() { + let mut rt = runtime(state()); + rt.set_live_visible(false); + let count = Arc::new(AtomicUsize::new(0)); + let wakes = count.clone(); + rt.set_live_waker(Arc::new(move || { wakes.fetch_add(1, Ordering::Relaxed); })); + rt.frame(0.0); + rt.state.opacity.set(0.2); + assert_eq!(count.load(Ordering::Relaxed), 0); + assert!(!rt.live_pending()); + rt.set_live_visible(true); + assert_eq!(count.load(Ordering::Relaxed), 1); + rt.frame(0.0); + assert!(!rt.live_pending()); +} + +#[test] +fn live_rect_changes_presentation_without_reflow_and_unbinding_restores_layout() { + type State = (Live<[f32; 4]>, bool); + fn view(s: &State, _: &mut Cx<State>) -> El { + let box_ = el().key("box").size(40.0, 20.0).fill(Color::WHITE); + el().size(300.0, 300.0).child(if s.1 { box_.live_rect(&s.0) } else { box_ }) + .child(el().key("sibling").size(20.0, 20.0)) + } + let mut rt = Runtime::new((Live::new([10.0, 20.0, 80.0, 40.0]), true), view, + (300.0, 300.0), Env::new(true, 2.0)); + let rect = |rt: &Runtime<State>, key: &str| rt.elements().into_iter().find(|n| n.key.as_deref() == Some(key)).unwrap().rect; + rt.frame(0.0); + assert_eq!(rect(&rt, "box"), [10.0, 20.0, 80.0, 40.0]); + assert_eq!(rect(&rt, "sibling")[0], 40.0); + rt.state.0.set([20.0, 30.0, 60.0, 50.0]); rt.frame(0.01); + assert_eq!(rt.stats.commits, 1); + rt.invalidate(); rt.frame(0.0); + assert_eq!(rect(&rt, "box"), [20.0, 30.0, 60.0, 50.0]); + rt.state.1 = false; rt.settle_all(); rt.frame(0.0); + assert_eq!(rect(&rt, "box"), [0.0, 0.0, 40.0, 20.0]); +} + +#[test] +fn linear_countdown_uses_render_time_without_commits_wakes_or_hidden_samples() { + use std::time::Duration; + type State = Tween<[f32; 4]>; + fn view(s: &State, _: &mut Cx<State>) -> El { + el().key("bar").size(272.0, 4.0).fill(Color::WHITE).live_rect(s) + } + let tween = || Tween::linear([0.0, 0.0, 272.0, 4.0], [0.0, 0.0, 0.0, 4.0], Duration::from_secs(30)); + let mut rt = Runtime::new(tween(), view, (300.0, 20.0), Env::new(true, 1.0)); + let wakes = Arc::new(AtomicUsize::new(0)); + let count = wakes.clone(); + rt.set_live_waker(Arc::new(move || { count.fetch_add(1, Ordering::Relaxed); })); + let width = |rt: &Runtime<State>| rt.elements().into_iter().find(|n| n.key.as_deref() == Some("bar")).unwrap().rect[2]; + assert!(rt.frame(0.0)); + assert_eq!(width(&rt), 272.0); + for _ in 0..120 { assert!(rt.frame(0.1)); } + assert!((width(&rt) - 163.2).abs() < 0.01); + assert_eq!(rt.stats.commits, 1); + assert_eq!(rt.stats.shaped, 0); + assert_eq!(wakes.load(Ordering::Relaxed), 0); + assert!(rt.wake_deadline().is_none()); + rt.invalidate(); rt.frame(0.0); + assert!((width(&rt) - 163.2).abs() < 0.01, "rebuild must not restart the track"); + rt.set_live_visible(false); + let before = width(&rt); + assert!(!rt.frame(10.0)); + assert_eq!(width(&rt), before, "hidden track is not sampled"); + assert!(!rt.live_pending()); + rt.set_live_visible(true); + assert!(rt.frame(0.0)); + assert!((width(&rt) - 272.0 * 8.0 / 30.0).abs() < 0.01, "resume uses elapsed real time"); + assert!(!rt.frame(8.01)); + assert_eq!(width(&rt), 0.0); + assert!(!rt.live_pending()); + rt.update(|s, _| *s = tween()); + assert!(rt.frame(0.0)); + assert_eq!(width(&rt), 272.0, "a new tween restarts explicitly"); + assert_eq!(wakes.load(Ordering::Relaxed), 0); +} + +type PixelsState = (rune::Pixels, bool); +fn pixels_view(s: &PixelsState, _: &mut Cx<PixelsState>) -> El { + let root = el().size(8.0, 8.0); + if s.1 { root.child(el().key("picture").size(4.0, 4.0).pixels(&s.0)) } else { root } +} +fn pixels_runtime(pixels: &rune::Pixels, shown: bool) -> (Runtime<PixelsState>, Arc<AtomicUsize>) { + let mut rt = Runtime::new((pixels.clone(), shown), pixels_view, (8.0, 8.0), Env::new(true, 1.0)); + let wakes = Arc::new(AtomicUsize::new(0)); + let count = wakes.clone(); + rt.set_live_waker(Arc::new(move || { count.fetch_add(1, Ordering::Relaxed); })); + rt.frame(0.0); + (rt, wakes) +} + +#[test] +fn pixels_set_wakes_only_the_runtime_showing_it() { + let pixels = rune::Pixels::new(); + let (mut shown, shown_wakes) = pixels_runtime(&pixels, true); + let (mut other, other_wakes) = pixels_runtime(&pixels, false); + std::thread::scope(|s| { s.spawn(|| pixels.set(1, 1, vec![255; 4])); }); + assert_eq!(shown_wakes.load(Ordering::Relaxed), 1, "a set on another thread wakes the window showing it"); + assert!(shown.live_pending()); + assert_eq!(other_wakes.load(Ordering::Relaxed), 0, "a window that doesn't show it stays asleep"); + assert!(!other.live_pending()); + shown.frame(0.01); other.frame(0.01); + assert!(!shown.live_pending()); + // Hidden or covered: no wake until it shows again, then one. + shown.set_live_visible(false); + pixels.set(1, 1, vec![0; 4]); + assert_eq!(shown_wakes.load(Ordering::Relaxed), 1); + assert!(!shown.frame(0.01), "a hidden window doesn't spin"); + shown.set_live_visible(true); + assert_eq!(shown_wakes.load(Ordering::Relaxed), 2); + shown.frame(0.01); + assert_eq!(&shown.images.pages[0].data[..4], &[0; 4], "it draws the latest image once it shows again"); +} + +#[test] +fn repeated_pixel_sets_coalesce_into_one_wake_and_one_upload() { + let pixels = rune::Pixels::new(); + pixels.set(2, 1, vec![1; 8]); + let (mut rt, wakes) = pixels_runtime(&pixels, true); + rt.images.pages[0].dirty = None; + for n in 0..50u8 { pixels.set(2, 1, vec![n; 8]); } + assert_eq!(wakes.load(Ordering::Relaxed), 1, "fifty sets between frames wake once"); + rt.frame(0.01); + assert_eq!(rt.images.pages[0].dirty, Some((0, 1)), "one row upload"); + assert_eq!(&rt.images.pages[0].data[..8], &[49; 8], "of the latest image"); + assert!(!rt.live_pending()); + rt.images.pages[0].dirty = None; + rt.frame(0.01); + assert_eq!(rt.images.pages[0].dirty, None, "no new image, no upload"); + pixels.set(2, 1, vec![50; 8]); + assert_eq!(wakes.load(Ordering::Relaxed), 2, "the next frame's set wakes again"); +} + +#[test] +fn a_removed_pixels_element_or_closed_window_stops_waking() { + let pixels = rune::Pixels::new(); + let (mut rt, wakes) = pixels_runtime(&pixels, true); + rt.update(|s, tx| { s.1 = false; tx.settle(); }); + rt.frame(0.0); + assert!(!rt.elements().iter().any(|e| e.key.as_deref() == Some("picture"))); + pixels.set(1, 1, vec![255; 4]); + assert_eq!(wakes.load(Ordering::Relaxed), 0, "the element is gone"); + assert!(!rt.live_pending()); + rt.update(|s, _| s.1 = true); + rt.frame(0.0); + pixels.set(1, 1, vec![0; 4]); + assert_eq!(wakes.load(Ordering::Relaxed), 1, "shown again, it wakes again"); + rt.frame(0.01); + drop(rt); + pixels.set(1, 1, vec![9; 4]); + assert_eq!(wakes.load(Ordering::Relaxed), 1, "a closed window's runtime is never woken"); +} + +#[test] +fn tween_handle_keeps_its_start_across_unmount_and_remount() { + type State = (Tween<f32>, bool); + fn view(s: &State, _: &mut Cx<State>) -> El { + let root = el().size(100.0, 100.0); + if s.1 { root.child(el().key("countdown").size(20.0, 20.0).live_opacity(&s.0)) } else { root } + } + let tween = Tween::linear(1.0, 0.0, std::time::Duration::from_secs(10)); + let mut rt = Runtime::new((tween.clone(), true), view, (100.0, 100.0), Env::new(true, 1.0)); + rt.frame(0.0); rt.frame(2.0); + rt.update(|s, tx| { s.1 = false; tx.settle(); }); rt.frame(0.0); + assert!(!rt.elements().iter().any(|e| e.key.as_deref() == Some("countdown"))); + rt.frame(3.0); + rt.update(|s, tx| { s.1 = true; tx.settle(); }); rt.frame(0.0); + let opacity = rt.elements().into_iter().find(|e| e.key.as_deref() == Some("countdown")).unwrap().opacity; + assert!((opacity - 0.5).abs() < 0.001, "remount must resume the original countdown"); + // Sharing the handle must not mix independent runtime/virtual clocks. + let mut other = Runtime::new((tween, true), view, (100.0, 100.0), Env::new(true, 1.0)); + other.frame(0.0); + assert_eq!(other.elements().into_iter().find(|e| e.key.as_deref() == Some("countdown")).unwrap().opacity, 1.0); +} diff --git a/app/vendor/rune/crates/rune/tests/integration/live_only.rs b/app/vendor/rune/crates/rune/tests/integration/live_only.rs new file mode 100644 index 0000000..e62123f --- /dev/null +++ b/app/vendor/rune/crates/rune/tests/integration/live_only.rs @@ -0,0 +1,350 @@ +//! `Tx::live_only`: a handler that moves only live values (a canvas camera) draws its frame, +//! hit tests and reports `on_drawn_layout` without re-running the view. And the element-local +//! points `on_pointer_move_local` and `on_secondary_press_local` give. +use rune::{Cx, Drag, El, Env, Key, KeyEvent, Live, MagnifyEvent, Mods, Phase, PointerButton, PointerEvent, PointerPress, RotateEvent, Runtime, Tx, WheelEvent, el}; + +struct S { + /// Handlers say `Tx::live_only`. + live: bool, + pan: [f32; 2], + zoom: f32, + cam_pan: Live<[f32; 2]>, + cam_zoom: Live<f32>, + pan_at_press: [f32; 2], + pressed: Vec<usize>, + /// `on_drawn_layout_tx` reports for node 0, which a toolbar follows by its own live offset. + drawn: Vec<[f32; 4]>, + toolbar: Live<[f32; 2]>, + moves: Vec<PointerEvent>, + crosshair: Live<[f32; 2]>, + menus: Vec<PointerEvent>, + windows: Vec<PointerPress>, + ups: usize, +} + +impl S { + fn new(live: bool) -> Self { + S { + live, pan: [0.0, 0.0], zoom: 1.0, cam_pan: Live::new([0.0, 0.0]), cam_zoom: Live::new(1.0), + pan_at_press: [0.0, 0.0], pressed: Vec::new(), drawn: Vec::new(), toolbar: Live::new([0.0, 0.0]), + moves: Vec::new(), crosshair: Live::new([0.0, 0.0]), menus: Vec::new(), windows: Vec::new(), ups: 0, + } + } + /// The camera lives in fields the view never reads, and in the live values it binds. + fn camera(&mut self, pan: [f32; 2], zoom: f32, tx: &mut Tx) { + (self.pan, self.zoom) = (pan, zoom); + self.cam_pan.set(pan); + self.cam_zoom.set(zoom); + if self.live { tx.live_only(); } + } +} + +/// A 400 pt canvas: a world of four 40 pt nodes under the camera, and a toolbar over node 0. +fn view(s: &S, _: &mut Cx<S>) -> El { + let world = (0..4).fold(el().key("world").size(400.0, 400.0).live_offset(&s.cam_pan).live_scale(&s.cam_zoom), |w, i| { + let node = el().key(format!("node{i}")).pin(Some(20.0 + 100.0 * i as f32), Some(100.0), None, None).size(40.0, 40.0) + .on_press(move |s: &mut S| s.pressed.push(i)); + w.child(if i == 0 { + node.on_drawn_layout_tx(|s: &mut S, r, tx| { + s.drawn.push(r); + s.toolbar.set([r[0], r[1] - 30.0]); + if s.live { tx.live_only(); } + }) + } else { node }) + }); + el().key("canvas").size(400.0, 400.0) + .child(world) + .child(el().key("toolbar").pin(Some(0.0), Some(0.0), None, None).size(60.0, 24.0).live_offset(&s.toolbar)) + .child(el().key("crosshair").pin(Some(0.0), Some(0.0), None, None).size(1.0, 1.0).live_offset(&s.crosshair)) + .on_wheel(|s: &mut S, e: WheelEvent, tx| { s.camera([s.pan[0] + e.dx, s.pan[1] + e.dy], s.zoom, tx); true }) + .on_magnify(|s: &mut S, e: MagnifyEvent, tx| { s.camera(s.pan, s.zoom * (1.0 + e.delta), tx); true }) + .on_rotate(|s: &mut S, e: RotateEvent, tx| { s.camera([s.pan[0] + e.degrees, s.pan[1]], s.zoom, tx); true }) + .pointer_buttons([PointerButton::Middle]) + .on_drag(|s: &mut S, d: &mut Drag, tx| { + if d.phase == Phase::Down { s.pan_at_press = s.pan; } + s.camera([s.pan_at_press[0] + d.dx, s.pan_at_press[1] + d.dy], s.zoom, tx); + }) + .on_pointer_move_local(|s: &mut S, p, tx| { + s.moves.push(p); + s.crosshair.set([p.x, p.y]); + if s.live { tx.live_only(); } + }) + .on_key_up(|s: &mut S, _, tx| { s.ups += 1; s.camera([s.pan[0], s.pan[1] + 5.0], s.zoom, tx); true }) +} + +fn app(live: bool) -> Runtime<S> { + let mut rt = Runtime::new(S::new(live), view, (400.0, 400.0), Env::new(true, 1.0)); + rt.on_key = Some(|s, e, tx| { + let dx = match e.key { Key::Left => -10.0, Key::Right => 10.0, _ => return false }; + s.camera([s.pan[0] + dx, s.pan[1]], s.zoom, tx); + true + }); + // These tests count commits; debug builds' spot check would add one. + rt.check_live_only(false); + settle(&mut rt); + rt +} + +fn settle(rt: &mut Runtime<S>) { + for _ in 0..600 { if !rt.frame(1.0 / 120.0) && !rt.has_pending_input() { return; } } + panic!("never settled"); +} + +fn rect(rt: &Runtime<S>, key: &str) -> [f32; 4] { + rt.elements().into_iter().find(|e| e.key.as_deref() == Some(key)).unwrap_or_else(|| panic!("{key}")).rect +} + +fn near(a: [f32; 4], b: [f32; 4]) -> bool { a.iter().zip(b).all(|(a, b)| (a - b).abs() < 0.01) } + +/// Runs `event` and the frames after it; returns the commits they took. +fn commits(rt: &mut Runtime<S>, event: impl FnOnce(&mut Runtime<S>)) -> u64 { + let before = rt.stats.commits; + event(rt); + settle(rt); + rt.stats.commits - before +} + +/// Every kind of canvas handler moves the camera: a wheel, a pinch, a rotation, a middle-button +/// drag, a key and a key release. +fn every_event(rt: &mut Runtime<S>) -> Vec<(&'static str, u64)> { + let mut out = Vec::new(); + out.push(("wheel", commits(rt, |rt| rt.wheel_event(WheelEvent::new(-30.0, -20.0).at(200.0, 300.0).precise(true))))); + out.push(("magnify", commits(rt, |rt| rt.magnify_event(MagnifyEvent::new(0.5).at(200.0, 300.0))))); + out.push(("rotate", commits(rt, |rt| rt.rotate_event(RotateEvent::new(15.0).at(200.0, 300.0))))); + rt.button_down(200.0, 300.0, PointerButton::Middle); + settle(rt); + out.push(("drag", commits(rt, |rt| { + for i in 1..=4 { rt.pointer_move(200.0 + 5.0 * i as f32, 300.0); rt.frame(1.0 / 120.0); } + }))); + rt.button_up(220.0, 300.0, PointerButton::Middle); + settle(rt); + out.push(("key", commits(rt, |rt| rt.key(KeyEvent { key: Key::Right, mods: Mods::default() })))); + out.push(("key up", commits(rt, |rt| { rt.key_up(KeyEvent { key: Key::Right, mods: Mods::default() }); }))); + out +} + +#[test] +fn live_only_handlers_move_the_canvas_without_re_running_the_view() { + let mut rt = app(true); + let start = rect(&rt, "node0"); + let ran = every_event(&mut rt); + assert!(ran.iter().all(|&(_, n)| n == 0), "no event re-ran the view: {ran:?}"); + assert!(rt.live_only_events() >= 6, "{}", rt.live_only_events()); + + // The camera moved what's drawn: node 0 shows where the camera puts it. + let [px, py] = rt.state.pan; + let z = rt.state.zoom; + let at = |x: f32, y: f32| [200.0 + (x - 200.0) * z + px, 200.0 + (y - 200.0) * z + py]; + let [x, y] = at(20.0, 100.0); + let node = rect(&rt, "node0"); + assert!(near(node, [x, y, 40.0 * z, 40.0 * z]), "node0 {node:?}, from {start:?}"); + + // `on_drawn_layout_tx` reported where it shows, and its live-only toolbar followed it. + assert!(near(*rt.state.drawn.last().unwrap(), node), "{:?}", rt.state.drawn.last()); + let toolbar = rect(&rt, "toolbar"); + assert!(near(toolbar, [node[0], node[1] - 30.0, 60.0, 24.0]), "toolbar {toolbar:?}"); + + // Hit tests follow the camera: a press where node 1 now shows presses it, and where it was + // before presses nothing. + let [x1, y1] = at(140.0, 120.0); + rt.pointer_down(x1, y1); + rt.pointer_up(x1, y1); + rt.pointer_down(140.0, 120.0); + rt.pointer_up(140.0, 120.0); + settle(&mut rt); + assert_eq!(rt.state.pressed, [1]); +} + +#[test] +fn without_live_only_each_event_re_runs_the_view() { + let mut rt = app(false); + let ran = every_event(&mut rt); + assert!(ran.iter().all(|&(_, n)| n >= 1), "each event committed: {ran:?}"); + assert_eq!(rt.live_only_events(), 0); +} + +#[test] +fn a_declined_event_takes_back_its_live_only() { + // The inner handler says live_only but declines the pinch; the outer one takes it without + // saying so, which commits. + fn view(_: &u32, _: &mut Cx<u32>) -> El { + el().size(100.0, 100.0) + .child(el().key("inner").size(100.0, 100.0).on_magnify(|_: &mut u32, _, tx| { tx.live_only(); false })) + .on_magnify(|s: &mut u32, _, _| { *s += 1; true }) + } + let mut rt = Runtime::new(0u32, view, (100.0, 100.0), Env::new(true, 1.0)); + rt.check_live_only(false); + rt.frame(0.0); + let before = rt.stats.commits; + rt.magnify_event(MagnifyEvent::new(0.5).at(50.0, 50.0)); + rt.frame(1.0 / 120.0); + assert_eq!((rt.state, rt.stats.commits - before, rt.live_only_events()), (1, 1, 0), "the outer handler took it and committed"); +} + +#[test] +fn pointer_move_and_secondary_press_give_local_points_on_a_zoomed_canvas() { + // A 200 pt canvas at (50, 50), drawn at twice its size about its centre: its top-left shows + // at (-50, -50) and a window point maps to (p + 50) / 2 in its own points. + fn view(_: &S, _: &mut Cx<S>) -> El { + el().size(300.0, 300.0) + .child(el().key("canvas").pin(Some(50.0), Some(50.0), None, None).size(200.0, 200.0).scale(2.0) + .on_pointer_move_local(|s: &mut S, p, _| s.moves.push(p)) + .on_secondary_press_local(|s: &mut S, p, _| s.menus.push(p))) + .child(el().key("old").pin(Some(100.0), Some(250.0), None, None).size(100.0, 50.0) + .on_pointer_move(|s: &mut S, p| s.windows.push(p)) + .on_secondary_press(|s: &mut S, p, _| s.windows.push(p))) + } + let mut rt = Runtime::new(S::new(false), view, (300.0, 300.0), Env::new(true, 1.0)); + rt.frame(0.0); + let canvas = rect(&rt, "canvas"); + assert!(near(canvas, [-50.0, -50.0, 400.0, 400.0]), "drawn at twice its size: {canvas:?}"); + rt.pointer_move(110.0, 30.0); + rt.frame(1.0 / 120.0); + rt.secondary_down(110.0, 30.0); + rt.secondary_up(110.0, 30.0); + rt.frame(1.0 / 120.0); + let p = rt.state.moves[0]; + assert_eq!((p.x, p.y, p.window_x, p.window_y), (80.0, 40.0, 110.0, 30.0)); + assert_eq!(p.window(), PointerPress { x: 110.0, y: 30.0 }); + let m = rt.state.menus[0]; + assert_eq!((m.x, m.y, m.window()), (80.0, 40.0, PointerPress { x: 110.0, y: 30.0 })); + + // The original builders still give window points. + rt.state.windows.clear(); + rt.pointer_move(150.0, 270.0); + rt.frame(1.0 / 120.0); + rt.secondary_down(150.0, 270.0); + rt.secondary_up(150.0, 270.0); + rt.frame(1.0 / 120.0); + assert_eq!(rt.state.windows, [PointerPress { x: 150.0, y: 270.0 }, PointerPress { x: 150.0, y: 270.0 }]); +} + +#[test] +fn pointer_move_local_can_be_live_only() { + let mut rt = app(true); + let ran = commits(&mut rt, |rt| { rt.pointer_move(120.0, 80.0); rt.frame(1.0 / 120.0); rt.pointer_move(130.0, 90.0); }); + assert_eq!(ran, 0); + let last = *rt.state.moves.last().unwrap(); + assert_eq!((last.x, last.y), (130.0, 90.0), "the canvas sits at the window's origin"); + let c = rect(&rt, "crosshair"); + assert!(near(c, [130.0, 90.0, 1.0, 1.0]), "the crosshair drew where the pointer is: {c:?}"); +} + +#[test] +fn live_transform_refreshes_hover_under_a_stationary_pointer() { + struct Hover { pan: Live<[f32; 2]>, changes: Vec<bool>, enters: usize } + fn view(s: &Hover, _: &mut Cx<Hover>) -> El { + el().child(el().key("moving").size(40.0, 40.0).live_offset(&s.pan) + .on_hover(|s: &mut Hover| s.enters += 1) + .on_hover_change(|s: &mut Hover, inside, _| s.changes.push(inside))) + } + let mut rt = Runtime::new(Hover { pan: Live::new([100.0, 0.0]), changes: Vec::new(), enters: 0 }, view, + (200.0, 200.0), Env::new(true, 1.0)); + rt.frame(0.0); + rt.pointer_move(20.0, 20.0); rt.frame(0.0); + rt.state.pan.set([0.0, 0.0]); + assert!(rt.frame(0.0), "hover reports need another frame even for an immediate live transform"); + rt.frame(0.0); + assert_eq!(rt.state.changes, [true]); + assert_eq!(rt.state.enters, 1); + rt.state.pan.set([100.0, 0.0]); + assert!(rt.frame(0.0)); rt.frame(0.0); + assert_eq!(rt.state.changes, [true, false]); +} + +#[test] +fn nested_live_and_static_scales_keep_local_points_per_runtime() { + fn view(s: &S, _: &mut Cx<S>) -> El { + el().child(el().size(300.0, 300.0).scale(2.0).live_offset(&s.cam_pan) + .child(el().key("inner").pin(Some(60.0), Some(60.0), None, None).size(100.0, 100.0) + .live_scale(&s.cam_zoom).on_pointer_move_local(|s: &mut S, p, _| s.moves.push(p)) + .on_secondary_press_local(|s: &mut S, p, _| s.menus.push(p)))) + } + for scale in [1.0, 2.0] { + let state = S::new(false); + state.cam_pan.set([30.0, 20.0]); state.cam_zoom.set(0.5); + let mut rt = Runtime::new(state, view, (500.0, 500.0), Env::new(true, scale)); + rt.frame(0.0); + let r = rect(&rt, "inner"); + // Nested scales multiply to one, but both anchors still move the origin. + let (x, y) = (r[0] + 25.0, r[1] + 35.0); + rt.pointer_move(x, y); rt.secondary_down(x, y); rt.secondary_up(x, y); rt.frame(0.0); + for p in [rt.state.moves[0], rt.state.menus[0]] { + assert!((p.x - 25.0).abs() < 0.01 && (p.y - 35.0).abs() < 0.01, "{p:?}"); + assert_eq!((p.window_x, p.window_y), (x, y)); + } + } +} + +#[test] +fn live_only_drag_keeps_capture_outside_the_moving_element() { + struct Held { pan: Live<[f32; 2]>, phases: Vec<Phase> } + fn view(s: &Held, _: &mut Cx<Held>) -> El { + el().child(el().size(40.0, 40.0).live_offset(&s.pan).on_drag(|s: &mut Held, d, tx| { + s.phases.push(d.phase); + if d.phase == Phase::Move { s.pan.set([d.dx, d.dy]); } + tx.live_only(); + })) + } + let mut rt = Runtime::new(Held { pan: Live::new([0.0, 0.0]), phases: Vec::new() }, view, + (200.0, 200.0), Env::new(true, 1.0)); + rt.check_live_only(false); rt.frame(0.0); + let before = rt.stats.commits; + rt.pointer_down(20.0, 20.0); rt.frame(0.0); + rt.pointer_move(300.0, 300.0); rt.frame(0.0); + assert!(rt.pressing()); + rt.pointer_up(350.0, 350.0); rt.frame(0.0); + assert!(!rt.pressing()); + assert_eq!(rt.state.phases, [Phase::Down, Phase::Move, Phase::Move, Phase::Up]); + assert_eq!(rt.stats.commits, before); +} + +/// A marker beside a scrolling list follows row 10 by its own live offset, set from +/// `on_layout_tx`. +struct Follow { + live: bool, + marker: Live<[f32; 2]>, + heard: usize, +} + +fn follow_view(s: &Follow, _: &mut Cx<Follow>) -> El { + let rows = (0..40).fold(rune::col().w_full(), |c, i| { + let row = el().key(format!("r{i}")).w_full().h(30.0); + c.child(if i == 10 { + row.on_layout_tx(|s: &mut Follow, r, tx| { + s.heard += 1; + s.marker.set([0.0, r[1]]); + if s.live { tx.live_only(); } + }) + } else { row }) + }); + rune::col().w_full().h_full() + .child(rune::col().key("list").w_full().h(300.0).scroll(rune::ScrollSpec { stick_bottom: false }).child(rows)) + .child(el().key("marker").pin(Some(0.0), Some(0.0), None, None).size(10.0, 10.0).live_offset(&s.marker)) +} + +fn follow(live: bool) -> (u64, usize, Runtime<Follow>) { + let mut rt = Runtime::new(Follow { live, marker: Live::new([0.0, 0.0]), heard: 0 }, follow_view, (300.0, 400.0), Env::new(true, 1.0)); + rt.check_live_only(false); + for _ in 0..10 { rt.frame(1.0 / 120.0); } + let (commits, heard) = (rt.stats.commits, rt.state.heard); + for _ in 0..30 { + rt.wheel(100.0, 100.0, -3.0); + rt.frame(1.0 / 120.0); + } + rt.frame(1.0 / 120.0); + (rt.stats.commits - commits, rt.state.heard - heard, rt) +} + +#[test] +fn a_live_only_on_layout_tx_follows_a_scroll_without_re_running_the_view() { + let (commits, heard, rt) = follow(true); + assert!(heard >= 30, "heard every frame of the scroll: {heard}"); + assert_eq!(commits, 0); + let row = rt.elements().into_iter().find(|e| e.key.as_deref() == Some("r10")).unwrap().rect; + let marker = rt.elements().into_iter().find(|e| e.key.as_deref() == Some("marker")).unwrap().rect; + assert_eq!(row[1], 210.0, "scrolled 90"); + assert_eq!(marker[1], row[1], "the marker follows the row"); + let (commits, heard, _) = follow(false); + assert!(commits >= 30 && heard >= 30, "without live_only each report re-runs the view: {commits}"); +} diff --git a/app/vendor/rune/crates/rune/tests/integration/main.rs b/app/vendor/rune/crates/rune/tests/integration/main.rs new file mode 100644 index 0000000..fb18e11 --- /dev/null +++ b/app/vendor/rune/crates/rune/tests/integration/main.rs @@ -0,0 +1,102 @@ +#[path = "../support/mod.rs"] +mod support; + +mod absolute_frac; +mod absolute_in_rows; +mod alignment; +mod app_spec_compat; +mod auto_grow; +mod backdrop_blur; +mod backdrop_blur_cost; +mod batch_c; +mod border_dash; +mod border_gradient; +mod canvas_input; +mod caret; +mod caret_follow; +mod clip; +mod deco_api; +mod dim_browser; +mod drag_cancel; +mod drag_release; +mod drawn_layout; +mod drawn_rect; +mod effect_data; +mod effect_slot; +mod enter_delay; +mod env_compat; +mod expressive_motion; +mod fly_text_extent; +mod fly_text_scoped; +mod font_families; +mod font_swap; +mod growth_whole; +mod headless_place; +mod headless_screen_layout; +mod help_tooltip; +mod hover_delays; +mod inert; +mod instant_keeps_flight; +mod keep_stuck; +mod key_paths; +mod latest; +mod launch; +mod launch_ancestor_spring; +mod layout_read; +mod layout_read_highlights; +mod links; +mod live; +mod live_only; +mod margin_axes; +mod matched; +mod motion_elements; +mod motion_exports; +mod motion_trace; +mod multi_state_windows; +mod offset_raise; +mod opacity_motion; +mod pinned_scroll; +mod pixel_scale; +mod playground_deep; +mod playground_folds; +mod playground_keys; +mod playground_links; +mod playground_replay; +mod playground_side_keys; +mod playground_stage; +mod playground_table; +mod playground_testing; +mod playground_tree; +mod pose_hit; +mod radial_srgb; +mod reveal_insert; +mod revive_settle; +mod row_enter; +mod script_double_click; +mod script_links; +mod script_t0; +mod script_text_selection; +mod scroll_anchor; +mod scroll_edge_fade; +mod scroll_to; +mod scroll_x; +mod selectable_text; +mod selectable_text_edges; +mod selection_api; +mod selection_copy_breaks; +mod selection_group; +mod selection_hidden; +mod selection_rects_memo; +mod selection_run; +mod selection_toolbar; +mod shape_fade; +mod srgb_blend_runtime; +mod stick_fit; +mod stick_resize; +mod sticky; +mod sticky_paint; +mod sticky_showing; +mod text_case; +mod theme_blend; +mod tx_blur; +mod window_panel_compat; diff --git a/app/vendor/rune/crates/rune/tests/integration/margin_axes.rs b/app/vendor/rune/crates/rune/tests/integration/margin_axes.rs new file mode 100644 index 0000000..c20a38c --- /dev/null +++ b/app/vendor/rune/crates/rune/tests/integration/margin_axes.rs @@ -0,0 +1,26 @@ +//! `mx` and `my` set both margins of an axis, as `px` and `py` do for padding. +use rune::{Cx, El, Env, Runtime, col, el, row}; + +struct S; + +fn view(_: &S, _: &mut Cx<S>) -> El { + col().w(200.0).h(200.0).items_start() + .child(row().child(el().key("x").size(20.0, 10.0).mx(7.0)).child(el().key("after_x").size(10.0, 10.0))) + .child(el().key("y").size(20.0, 10.0).my(5.0)) + .child(el().key("after_y").size(10.0, 10.0)) +} + +fn rect(rt: &Runtime<S>, key: &str) -> [f32; 4] { + rt.elements().into_iter().find(|e| e.key.as_deref() == Some(key)).unwrap().rect +} + +#[test] +fn mx_and_my_apply_to_both_sides() { + let mut rt = Runtime::new(S, view, (200.0, 200.0), Env::new(true, 1.0)); + rt.frame(0.0); + let (x, after_x, y, after_y) = (rect(&rt, "x"), rect(&rt, "after_x"), rect(&rt, "y"), rect(&rt, "after_y")); + assert_eq!((x[0], x[1]), (7.0, 0.0)); + assert_eq!(after_x[0], 7.0 + 20.0 + 7.0); + assert_eq!((y[0], y[1]), (0.0, 10.0 + 5.0)); + assert_eq!(after_y[1], 10.0 + 5.0 + 10.0 + 5.0); +} diff --git a/app/vendor/rune/crates/rune/tests/integration/matched.rs b/app/vendor/rune/crates/rune/tests/integration/matched.rs new file mode 100644 index 0000000..efc451d --- /dev/null +++ b/app/vendor/rune/crates/rune/tests/integration/matched.rs @@ -0,0 +1,299 @@ +use rune::{Color, Cx, El, Env, Runtime, Spring, Transition, col, el, row}; + +/// A tile that lives in the left box (40 pt) or, zoomed, in the right box (160 pt). +fn view(zoomed: &bool, _: &mut Cx<bool>) -> El { + let tile = |size: f32| el().key("tile").matched("tile").size(size, size).fill(Color::WHITE).radius(4.0); + let mut left = el().key("left").size(100.0, 200.0); + let mut right = el().key("right").size(200.0, 200.0); + if *zoomed { right = right.child(tile(160.0)) } else { left = left.child(tile(40.0)) } + row().size(300.0, 200.0).child(left).child(right) +} + +const GRID: [f32; 4] = [0.0, 0.0, 40.0, 40.0]; +const ONE: [f32; 4] = [100.0, 0.0, 160.0, 160.0]; + +fn rt() -> Runtime<bool> { + let mut rt = Runtime::new(false, view, (300.0, 200.0), Env::new(true, 1.0)); + rt.frame(0.0); + rt +} + +fn tile(rt: &Runtime<bool>) -> [f32; 4] { + rt.presented("tile").expect("tile").0 +} + +fn moving(rt: &Runtime<bool>) -> bool { + rt.elements().iter().any(|e| e.key.as_deref() == Some("tile") && e.moving) +} + +fn jump(a: [f32; 4], b: [f32; 4]) -> f32 { + (0..4).map(|k| (a[k] - b[k]).abs()).fold(0.0, f32::max) +} + +#[test] +fn a_matched_element_moving_between_parents_flies_from_where_it_was() { + let mut rt = rt(); + assert_eq!(tile(&rt), GRID); + rt.update(|zoomed, _| *zoomed = true); + rt.frame(1.0 / 120.0); + let first = tile(&rt); + assert!(jump(first, GRID) < 8.0, "starts at the old rect: {first:?}"); + assert!(moving(&rt), "a flight reports `moving`"); + let mut last = first; + for _ in 0..240 { + rt.frame(1.0 / 120.0); + let r = tile(&rt); + assert!(jump(r, last) < 12.0, "continuous: {last:?} -> {r:?}"); + last = r; + } + assert_eq!(tile(&rt), ONE); + assert!(!moving(&rt)); +} + +#[test] +fn toggling_mid_flight_turns_around_without_a_jump() { + let mut rt = rt(); + let mut last = tile(&rt); + let mut worst = 0.0f32; + for round in 0..4 { + rt.update(|zoomed, _| *zoomed = !*zoomed); + for _ in 0..12 + round * 5 { + rt.frame(1.0 / 120.0); + let r = tile(&rt); + worst = worst.max(jump(r, last)); + last = r; + } + assert!(moving(&rt), "still in flight when toggled again"); + } + assert!(worst < 12.0, "no rect jumps between frames: {worst}"); + for _ in 0..240 { + rt.frame(1.0 / 120.0); + } + assert_eq!(tile(&rt), GRID, "an even number of toggles lands back in the grid"); +} + +#[test] +fn reduced_motion_swaps_in_place() { + let mut rt = rt(); + rt.set_system_reduced_motion(true); + rt.update(|zoomed, _| *zoomed = true); + rt.frame(1.0 / 120.0); + assert_eq!(tile(&rt), ONE); + for _ in 0..60 { + rt.frame(1.0 / 120.0); + assert_eq!(tile(&rt), ONE); + } +} + +#[test] +fn children_scale_with_the_flight() { + fn view(zoomed: &bool, _: &mut Cx<bool>) -> El { + let tile = |size: f32| el().key("tile").matched("tile").size(size, size).fill(Color::WHITE) + .child(el().key("dot").size(size / 4.0, size / 4.0).fill(Color::BLACK)); + let mut left = el().key("left").size(100.0, 200.0); + let mut right = el().key("right").size(200.0, 200.0); + if *zoomed { right = right.child(tile(160.0)) } else { left = left.child(tile(40.0)) } + row().size(300.0, 200.0).child(left).child(right) + } + let mut rt = Runtime::new(false, view, (300.0, 200.0), Env::new(true, 1.0)); + rt.frame(0.0); + rt.update(|zoomed, _| *zoomed = true); + for _ in 0..10 { + rt.frame(1.0 / 120.0); + } + let (t, _) = rt.presented("tile").unwrap(); + let (d, _) = rt.presented("dot").unwrap(); + assert!(t[2] > 50.0 && t[2] < 150.0, "mid-flight: {t:?}"); + assert!((d[0] - t[0]).abs() < 1.0 && (d[1] - t[1]).abs() < 1.0, "rides the tile's origin: {t:?} {d:?}"); + assert!((d[2] - t[2] / 4.0).abs() < 1.0 && (d[3] - t[3] / 4.0).abs() < 1.0, "a quarter of the tile: {t:?} {d:?}"); +} + +#[test] +fn unmatched_elements_are_untouched() { + fn plain(zoomed: &bool, _: &mut Cx<bool>) -> El { + let tile = |size: f32| el().key("tile").size(size, size).fill(Color::WHITE); + let mut left = el().key("left").size(100.0, 200.0); + let mut right = el().key("right").size(200.0, 200.0); + if *zoomed { right = right.child(tile(160.0)) } else { left = left.child(tile(40.0)) } + row().size(300.0, 200.0).child(left).child(right) + } + let mut rt = Runtime::new(false, plain, (300.0, 200.0), Env::new(true, 1.0)); + rt.frame(0.0); + rt.update(|zoomed, _| *zoomed = true); + rt.frame(1.0 / 120.0); + let (r, _) = rt.presented("tile").unwrap(); + assert_eq!([r[0], r[1]], [ONE[0], ONE[1]], "a plain remount enters at its own place"); +} + +fn moving_key(rt: &Runtime<bool>, key: &str) -> bool { + rt.elements().iter().any(|e| e.key.as_deref() == Some(key) && e.moving) +} + +#[test] +fn a_matched_element_inside_a_matched_one_flies_its_own_straight_path() { + // The badge sits at the card's top-left in the grid and below a gap when zoomed, in a card + // whose aspect changes, so riding the card's cover would bend or offset its path. + fn view(zoomed: &bool, _: &mut Cx<bool>) -> El { + let badge = |size: f32| el().key("badge").matched("badge").size(size, size).fill(Color::BLACK); + let mut left = el().key("left").size(100.0, 200.0); + let mut right = el().key("right").size(200.0, 200.0); + if *zoomed { + right = right.child(col().key("card").matched("card").size(160.0, 80.0).fill(Color::WHITE) + .child(el().key("gap").size(10.0, 40.0)).child(badge(40.0))); + } else { + left = left.child(col().key("card").matched("card").size(40.0, 40.0).fill(Color::WHITE).child(badge(10.0))); + } + row().size(300.0, 200.0).child(left).child(right) + } + let mut rt = Runtime::new(false, view, (300.0, 200.0), Env::new(true, 1.0)); + rt.frame(0.0); + let start = rt.presented("badge").unwrap().0; + assert_eq!(start, [0.0, 0.0, 10.0, 10.0]); + rt.update(|zoomed, _| *zoomed = true); + rt.frame(1.0 / 120.0); + let first = rt.presented("badge").unwrap().0; + assert!(jump(first, start) < 3.0, "starts where the old badge was: {first:?}"); + assert!(moving_key(&rt, "badge") && moving_key(&rt, "card"), "both fly"); + let mut mid = false; + for _ in 0..240 { + rt.frame(1.0 / 120.0); + let b = rt.presented("badge").unwrap().0; + let t = b[0] / 100.0; + mid |= t > 0.3 && t < 0.7; + assert!((b[1] - 40.0 * t).abs() < 1.0, "on the straight path from its start to its end: {b:?}"); + assert!((b[2] - (10.0 + 30.0 * t)).abs() < 1.5, "grows with its own progress: {b:?}"); + } + assert!(mid, "sampled mid-flight"); + assert_eq!(rt.presented("badge").unwrap().0, [100.0, 40.0, 40.0, 40.0]); + assert_eq!(rt.presented("card").unwrap().0, [100.0, 0.0, 160.0, 80.0]); +} + +/// 0: the tile in the left box, 1: in the right box, 2: gone, 3: the right box gone with it. +fn removable(state: &u8, _: &mut Cx<u8>) -> El { + let tile = |size: f32| el().key("tile").matched("tile").size(size, size).fill(Color::WHITE) + .child(el().key("dot").size(size / 4.0, size / 4.0).fill(Color::BLACK)); + let mut left = el().key("left").size(100.0, 200.0); + let mut right = el().key("right").size(200.0, 200.0); + match state { + 0 => left = left.child(tile(40.0)), + 1 => right = right.child(tile(160.0)), + _ => {} + } + let r = row().size(300.0, 200.0).child(left); + if *state == 3 { r } else { r.child(right) } +} + +#[test] +fn a_flight_removed_mid_way_exits_without_a_pop() { + for gone in [2u8, 3] { + let mut rt = Runtime::new(0u8, removable, (300.0, 200.0), Env::new(true, 1.0)); + rt.frame(0.0); + rt.update(|s, _| *s = 1); + for _ in 0..10 { + rt.frame(1.0 / 120.0); + } + let mut last = rt.presented("tile").unwrap(); + assert!(last.0[2] > 50.0 && last.0[2] < 150.0, "mid-flight: {last:?}"); + rt.update(move |s, _| *s = gone); + let mut faded = false; + for _ in 0..120 { + rt.frame(1.0 / 120.0); + let Some(now) = rt.presented("tile") else { break }; + let dot = rt.presented("dot").unwrap().0; + assert!((dot[2] - now.0[2] / 4.0).abs() < 1.5, "children stay scaled with the flight ({gone}): {now:?} {dot:?}"); + assert!(jump(now.0, last.0) < 12.0, "continuous ({gone}): {last:?} -> {now:?}"); + assert!(now.1 <= last.1 + 1e-3, "fades out ({gone}): {} -> {}", last.1, now.1); + faded |= now.1 > 0.2 && now.1 < 0.8; + last = now; + } + assert!(faded, "an exit fade was sampled ({gone})"); + assert!(rt.presented("tile").is_none(), "gone once faded ({gone})"); + } +} + +#[test] +fn a_fast_flight_waits_for_its_entering_parent() { + // The flight lands well before the right box finishes entering with a scale and fade. + fn view(zoomed: &bool, _: &mut Cx<bool>) -> El { + let tile = |size: f32| el().key("tile").matched("tile").size(size, size).fill(Color::WHITE) + .motion(Spring::new(0.08, 0.0)); + let r = row().size(300.0, 200.0); + if *zoomed { + r.child(el().key("left").size(100.0, 200.0)) + .child(el().key("right").size(200.0, 200.0).transition(Transition::scale(0.9)).child(tile(160.0))) + } else { + r.child(el().key("left").size(100.0, 200.0).child(tile(40.0))) + } + } + let mut rt = Runtime::new(false, view, (300.0, 200.0), Env::new(true, 1.0)); + rt.frame(0.0); + rt.update(|zoomed, _| *zoomed = true); + let mut landed = None; + for frame in 0..120 { + rt.frame(1.0 / 120.0); + let (r, opacity) = rt.presented("tile").unwrap(); + assert!(opacity > 0.99, "keeps its own opacity at frame {frame}: {opacity}"); + if landed.is_some() { + assert!(jump(r, ONE) < 0.5, "stays where it landed at frame {frame}: {r:?}"); + } else if jump(r, ONE) < 0.5 { + landed = Some(rt.presented("right").unwrap().1); + } + } + let parent = landed.expect("landed"); + assert!(parent < 0.9, "landed while the parent was still entering: its opacity {parent}"); +} + +#[test] +fn reduced_motion_fades_the_old_one_with_the_parent_it_leaves_with() { + fn view(zoomed: &bool, _: &mut Cx<bool>) -> El { + let r = row().size(300.0, 200.0); + if *zoomed { + r.child(el().key("spacer").size(100.0, 200.0)).child(el().key("right").size(200.0, 200.0) + .child(el().key("new").matched("tile").size(160.0, 160.0).fill(Color::WHITE))) + } else { + r.child(col().key("left").size(100.0, 200.0) + .child(el().key("old").matched("tile").size(40.0, 40.0).fill(Color::WHITE)) + .child(el().key("peer").size(40.0, 40.0).fill(Color::WHITE))) + } + } + let mut rt = Runtime::new(false, view, (300.0, 200.0), Env::new(true, 1.0)); + rt.set_system_reduced_motion(true); + rt.frame(0.0); + rt.update(|zoomed, _| *zoomed = true); + let mut sampled = false; + for _ in 0..60 { + rt.frame(1.0 / 120.0); + let (Some(old), Some(peer)) = (rt.presented("old"), rt.presented("peer")) else { break }; + assert!((old.1 - peer.1).abs() < 0.02, "fades with its sibling: {} vs {}", old.1, peer.1); + sampled |= peer.1 > 0.2 && peer.1 < 0.8; + assert_eq!(rt.presented("new").unwrap().0, ONE, "the new one is in place"); + } + assert!(sampled, "the fade was sampled"); +} + +/// A tile two parents deep in content, in the left box or, zoomed, in the right box. +fn nested(zoomed: &bool, _: &mut Cx<bool>) -> El { + let tile = |size: f32| { + el().key("tile").matched("tile").size(size, size).fill(Color::WHITE) + .child(row().key("pill").w_full().h(20.0).child(el().key("mark").size(8.0, 8.0).child(el().key("dot").size(4.0, 4.0).fill(Color::BLACK)))) + }; + let mut left = el().key("left").size(100.0, 200.0); + let mut right = el().key("right").size(200.0, 200.0); + if *zoomed { right = right.child(tile(160.0)) } else { left = left.child(tile(40.0)) } + row().size(300.0, 200.0).child(left).child(right) +} + +#[test] +fn a_flights_content_flies_with_it_without_fading_in() { + let mut rt = Runtime::new(false, nested, (300.0, 200.0), Env::new(true, 1.0)); + rt.frame(0.0); + rt.update(|zoomed, _| *zoomed = true); + for frame in 0..12 { + rt.frame(1.0 / 120.0); + assert!(moving(&rt), "still in flight"); + for key in ["tile", "pill", "mark", "dot"] { + let o = rt.elements().iter().find(|e| e.key.as_deref() == Some(key)).map_or(0.0, |e| e.opacity); + assert!(o > 0.999, "frame {frame}: {key} drawn at {o:.3}"); + } + } +} diff --git a/app/vendor/rune/crates/rune/tests/integration/motion_elements.rs b/app/vendor/rune/crates/rune/tests/integration/motion_elements.rs new file mode 100644 index 0000000..db42465 --- /dev/null +++ b/app/vendor/rune/crates/rune/tests/integration/motion_elements.rs @@ -0,0 +1,104 @@ +//! `Runtime::motion_elements` agrees with `Runtime::elements` on what a motion watcher reads, +//! frame by frame, through a wheel scroll and a fade. +use rune::{Cx, El, Env, MotionElement, Runtime, ScrollSpec, col, el, text}; + +struct S { + words: bool, +} + +fn secret(_: &S, _: &mut Cx<S>) -> El { + col().child(text("hunter2").key("plain")).child(text("hunter2").key("secret").secure()) +} + +fn view(s: &S, _: &mut Cx<S>) -> El { + let rows = (0..30).fold(col().w_full(), |c, i| c.child(el().key(format!("row{i}")).w_full().h(40.0).child(text(format!("row {i}"))))); + col().w_full().h_full() + .child(col().key("scroll").w(300.0).h(400.0).scroll(ScrollSpec { stick_bottom: false }).child(rows)) + .child(if s.words { text("a much longer line of words").key("words") } else { el().key("words").w(10.0).h(10.0).fill(rune::Color::BLACK) }) +} + +fn agree(rt: &Runtime<S>, out: &mut Vec<MotionElement>) { + rt.motion_elements(out); + let els = rt.elements(); + assert_eq!(out.len(), els.len()); + for (m, e) in out.iter().zip(&els) { + assert_eq!(rt.element_path(m.id), Some((e.path.as_str(), e.key.as_deref()))); + assert_eq!((m.rect, m.visible, m.opacity, m.scale), (e.rect, e.visible, e.opacity, e.scale), "{}", e.path); + assert_eq!(m.parent.map(|p| els[p as usize].path.as_str()), e.parent.map(|p| els[p].path.as_str()), "{}", e.path); + let flags = [ + (MotionElement::EXITING, e.exiting), + (MotionElement::SCROLLING, e.scrolling), + (MotionElement::GROWING, e.in_growing_row || e.revealing), + (MotionElement::LIVE, e.live_intent != 0), + (MotionElement::VIRTUAL, e.virtual_extent), + (MotionElement::TEXT, e.role == "text"), + (MotionElement::LOOP, e.loop_phase.is_some()), + (MotionElement::PAINTS, e.fill.a > 0.01 || e.text.as_deref().is_some_and(|t| !t.is_empty())), + ]; + for (flag, want) in flags { + assert_eq!(m.is(flag), want, "{} flag {flag}", e.path); + } + assert_eq!(m.text_hash != 0, e.text.as_deref().is_some_and(|t| !t.is_empty()), "{}", e.path); + } +} + +#[test] +fn motion_elements_match_elements_through_a_scroll() { + let mut rt = Runtime::new(S { words: false }, view, (600.0, 900.0), Env::new(true, 2.0)); + let mut out = Vec::new(); + rt.frame(0.0); + agree(&rt, &mut out); + rt.wheel(100.0, 200.0, -120.0); + let mut scrolled = false; + for _ in 0..30 { + rt.frame(1.0 / 60.0); + agree(&rt, &mut out); + scrolled |= out.iter().any(|m| m.is(MotionElement::SCROLLING)); + } + assert!(scrolled, "the rows were marked scrolling while the wheel moved them"); + let row = |rt: &Runtime<S>, out: &[MotionElement], k: &str| *out.iter().find(|m| rt.element_path(m.id).and_then(|p| p.1) == Some(k)).unwrap(); + let before = row(&rt, &out, "words"); + rt.update(|s, _| s.words = true); + for _ in 0..30 { + rt.frame(1.0 / 60.0); + agree(&rt, &mut out); + } + let after = row(&rt, &out, "words"); + assert_ne!(before.text_hash, after.text_hash); + assert!(out.iter().filter(|m| m.is(MotionElement::TEXT)).all(|m| m.text_hash != 0)); +} + +#[test] +fn a_glide_marks_the_content_it_carries_scrolling() { + let mut rt = Runtime::new(S { words: false }, view, (600.0, 900.0), Env::new(true, 2.0)); + let mut out = Vec::new(); + rt.frame(0.0); + rt.update(|_, tx| tx.scroll_to("scroll", 0.0, 400.0)); + let y = |rt: &Runtime<S>| rt.elements().iter().find(|e| e.key.as_deref() == Some("row3")).map(|e| e.rect[1]).unwrap(); + let (mut moved, mut last) = (0, y(&rt)); + for f in 0..120 { + rt.frame(1.0 / 60.0); + agree(&rt, &mut out); + let now = y(&rt); + if (now - last).abs() > 0.01 { + moved += 1; + let row = rt.elements().into_iter().find(|e| e.key.as_deref() == Some("row3")).unwrap(); + // The frame it lands may close the last fraction of a point after the glide ends. + assert!(row.scrolling || (now - last).abs() < 0.5, "frame {f}: a row the glide carries {:.2} pt is scrolling", now - last); + } + last = now; + } + assert!(moved > 5, "it glided"); + assert!(rt.elements().iter().all(|e| !e.scrolling), "and stops scrolling when it lands"); +} + +#[test] +fn secure_text_hashes_to_zero() { + let mut rt = Runtime::new(S { words: false }, secret, (300.0, 200.0), Env::new(true, 2.0)); + rt.frame(0.0); + let mut out = Vec::new(); + rt.motion_elements(&mut out); + let hash = |k: &str| out.iter().find(|m| rt.element_path(m.id).and_then(|p| p.1) == Some(k)).unwrap().text_hash; + assert_ne!(hash("plain"), 0); + assert_eq!(hash("secret"), 0); +} diff --git a/app/vendor/rune/crates/rune/tests/integration/motion_exports.rs b/app/vendor/rune/crates/rune/tests/integration/motion_exports.rs new file mode 100644 index 0000000..5b317d9 --- /dev/null +++ b/app/vendor/rune/crates/rune/tests/integration/motion_exports.rs @@ -0,0 +1,15 @@ +//! Every type the re-exported motion API takes or returns can be named through `rune`. +use rune::{AnimExt, Blend, CubicBezier, Decay, Easing, Edge, Effect, Reveal, Spring, StepPosition, Transition, Vec2, Velocity}; + +#[test] +fn transition_and_anim_arguments_are_nameable_from_rune() { + let anchored = Transition::scale_anchor(0.96, Vec2::new(0.5, 0.0)); + assert_eq!(anchored.insertion.anchor, Vec2::new(0.5, 0.0)); + let _: Vec2 = Edge::Top.direction(); + let _: Effect = Effect::scale(0.9).combined(Effect::opacity(0.0)); + let _ = Reveal { edge: Edge::Bottom, feather: 4.0 }; + let _ = Easing::CubicBezier(CubicBezier::new(0.2, 0.0, 0.0, 1.0)); + let _ = Easing::Steps(4, StepPosition::End); + let _ = Decay::IOS_NORMAL; + let _ = Spring::from_response(0.3, 1.0).blend(Blend::Additive).velocity(Velocity::Zero); +} diff --git a/app/vendor/rune/crates/rune/tests/integration/motion_trace.rs b/app/vendor/rune/crates/rune/tests/integration/motion_trace.rs new file mode 100644 index 0000000..d2a2e28 --- /dev/null +++ b/app/vendor/rune/crates/rune/tests/integration/motion_trace.rs @@ -0,0 +1,49 @@ +use rune_motion::{MotionTrace, Mount, NodeId, NodeSpec, Rect, Scene, TraceHeader}; +use serde_json::{Value, json}; + +#[test] +fn trace_names_channels_and_events_match_motion_lint() { + let header = TraceHeader { launch: "pill".into(), width: 200.0, height: 80.0, hz: 120.0, scale: 2.0 }; + let (trace, buffer) = MotionTrace::in_memory(&header); + let mut scene = Scene::new(); + // Attaching to an already settled scene must describe its nodes too. + scene.insert(NodeId(40), NodeSpec::new(Rect::new(0.0, 0.0, 100.0, 40.0)), Mount::Initial); + scene.insert(NodeId(90), NodeSpec::new(Rect::new(10.0, 0.0, 20.0, 20.0)), Mount::Initial); + scene.frame_at(0.0); + scene.set_trace(Some(trace.class("gpui").host("pill"))); + scene.trace_name(NodeId(40), Some("chip:\"Area\"")); + let trace = scene.trace_mut().unwrap(); + trace.channel("shell.width", "position", 100.12345); + trace.channel("phase:recording", "phase", 1.0); + trace.event(format_args!("lab:{:?}", "Start\n")); + scene.frame_at(0.01); + scene.frame_at(0.02); + scene.trace_name(NodeId(40), Some("chip:Region")); + scene.trace_mut().unwrap().channel("shell.width", "position", 120.0); + scene.trace_mut().unwrap().remove_channel("phase:recording"); + scene.frame_at(0.03); + scene.trace_name(NodeId(40), None); + scene.trace_mut().unwrap().channel("phase:recording", "phase", 1.0); + scene.trace_mut().unwrap().channel("shell.width", "position", f32::NAN); + scene.frame_at(0.04); + scene.take_trace().unwrap().flush().unwrap(); + let lines: Vec<Value> = buffer.contents().lines().map(|s| serde_json::from_str(s).unwrap()).collect(); + let named = lines[1]["m"].as_array().unwrap().iter().find(|m| m["nm"] == "chip:\"Area\"").unwrap(); + let id = named["id"].clone(); + assert_eq!(named["host"], "pill"); + assert_eq!(named["cls"], "gpui"); + assert!(lines[1]["m"].as_array().unwrap().iter().any(|m| m["nm"] == "90")); + assert_eq!(lines[1]["cm"], json!([ + {"id": 1, "name": "shell.width", "kind": "position"}, + {"id": 2, "name": "phase:recording", "kind": "phase"}, + ])); + assert_eq!(lines[1]["c"], json!([[1, 100.1235], [2, 1]])); + assert_eq!(lines[1]["ev"], json!(["lab:\"Start\\n\""])); + for field in ["m", "cm", "c", "ev"] { assert!(lines[2][field].is_null(), "duplicate {field}"); } + assert_eq!(lines[3]["m"][0]["id"], id); + assert_eq!(lines[3]["m"][0]["nm"], "chip:Region"); + assert_eq!(lines[3]["c"], json!([[1, 120]])); + assert_eq!(lines[3]["cg"], json!([2])); + assert_eq!(lines[4]["m"][0]["nm"], "40"); + assert_eq!(lines[4]["c"], json!([[2, 1]])); +} diff --git a/app/vendor/rune/crates/rune/tests/integration/multi_state_windows.rs b/app/vendor/rune/crates/rune/tests/integration/multi_state_windows.rs new file mode 100644 index 0000000..ca5b21e --- /dev/null +++ b/app/vendor/rune/crates/rune/tests/integration/multi_state_windows.rs @@ -0,0 +1,82 @@ +//! Windows with different state types share one app; headless tools select one by key and +//! render it with its own state. +use rune::*; + +struct Review { count: u32 } +struct Settings { name: String } + +fn review_view(s: &Review, _: &mut Cx<Review>) -> El { text(format!("review {}", s.count)).key("out") } +fn settings_view(s: &Settings, _: &mut Cx<Settings>) -> El { text(format!("settings {}", s.name)).key("out") } + +fn review() -> App<Review> { + App::new(AppSpec::new("Review", (400.0, 300.0), || Review { count: 0 }, review_view)) +} + +fn settings() -> WindowSpec<Settings> { + WindowSpec::new("settings", AppSpec::new("Settings", (320.0, 200.0), || Settings { name: "default".into() }, settings_view)) +} + +/// The text and viewport of the window `run` renders with `--tree`. +fn rendered(name: &str, run: impl FnOnce(Vec<String>)) -> (String, serde_json::Value) { + let dir = std::env::temp_dir().join(format!("rune-multi-state-{name}-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let tree = dir.join("tree.json"); + run(vec!["--tree".into(), tree.to_str().unwrap().into()]); + let tree: serde_json::Value = serde_json::from_str(&std::fs::read_to_string(&tree).unwrap()).unwrap(); + std::fs::remove_dir_all(&dir).unwrap(); + let out = tree["elements"].as_array().unwrap().iter().find(|e| e["key"] == "out").unwrap(); + (out["text"].as_str().unwrap().to_owned(), tree["viewport"].clone()) +} + +#[test] +fn a_factory_mixes_state_types_and_tools_render_the_selected_one() { + for (key, text, viewport) in [("review", "review 7", [400.0, 300.0]), ("settings", "settings Kit", [320.0, 200.0])] { + let (out, size) = rendered(&format!("factory-{key}"), |mut args| { + args.extend(["--window".into(), key.into()]); + run_windows_with_args(RunOptions::default(), args, |_| { + let review = review(); + review.handle().update(|s, _| s.count = 7); + let settings = settings(); + settings.app.handle().update(|s, _| s.name = "Kit".into()); + vec![WindowSpec::from_app("review", review).boxed(), settings.into()] + }); + }); + assert_eq!(out, text); + assert_eq!(size, serde_json::json!(viewport)); + } +} + +#[test] +fn app_window_is_selectable_with_its_own_state_and_hidden_until_opened() { + for (key, text, viewport) in [("main", "review 7", [400.0, 300.0]), ("settings", "settings Kit", [320.0, 200.0])] { + let (out, size) = rendered(&format!("app-{key}"), |mut args| { + args.extend(["--window".into(), key.into()]); + let mut app = review(); + let hidden = WindowOptions { visible: false, ..Default::default() }; + let (settings, window) = app.window(settings().options(hidden)); + assert_eq!(window.key(), "settings"); + assert!(!settings.is_visible() && !window.is_ready()); + // Before the loop runs, both handles queue their requests. + window.open(); + settings.update(|s, _| s.name = "Kit".into()); + app.handle().update(|s, _| s.count = 7); + app.args(args).run(); + }); + assert_eq!(out, text); + assert_eq!(size, serde_json::json!(viewport)); + } +} + +#[test] +fn factory_windows_can_add_their_own_secondary_windows() { + let (out, _) = rendered("nested", |mut args| { + args.extend(["--window".into(), "settings".into()]); + run_windows_with_args(RunOptions::default(), args, |_| { + let mut review = review(); + let (settings, _) = review.window(settings()); + settings.update(|s, _| s.name = "nested".into()); + vec![WindowSpec::from_app("review", review)] + }); + }); + assert_eq!(out, "settings nested"); +} diff --git a/app/vendor/rune/crates/rune/tests/integration/offset_raise.rs b/app/vendor/rune/crates/rune/tests/integration/offset_raise.rs new file mode 100644 index 0000000..da261c3 --- /dev/null +++ b/app/vendor/rune/crates/rune/tests/integration/offset_raise.rs @@ -0,0 +1,292 @@ +//! `El::offset` shifts an element without moving its siblings and springs between shifts; +//! `El::raise` paints and hits an element above later siblings; `on_hover_change` hears an +//! element that appears under a still pointer. +use rune::{Cx, El, Env, Runtime, Spring, col, el}; + +#[derive(Default)] +struct S { + shift: f32, + raise: bool, + pressed: Vec<&'static str>, + show: bool, + hover: Vec<bool>, +} + +fn view(s: &S, _: &mut Cx<S>) -> El { + let mut a = el() + .key("a") + .size(100.0, 40.0) + .motion(Spring::new(0.3, 0.0)) + .offset(0.0, s.shift) + .on_press(|s: &mut S| s.pressed.push("a")); + if s.raise { + a = a.raise(); + } + let b = el().key("b").size(100.0, 40.0).on_press(|s: &mut S| s.pressed.push("b")); + let mut root = col().w_full().h_full().child(a).child(b); + if s.show { + root = root.child( + el().key("zone").size(200.0, 200.0).absolute(0.0, 0.0).on_hover_change(|s: &mut S, inside, _| s.hover.push(inside)), + ); + } + root +} + +fn app() -> Runtime<S> { + let mut rt = Runtime::new(S::default(), view, (200.0, 200.0), Env::new(true, 1.0)); + rt.frame(0.0); + rt +} + +fn rect(rt: &Runtime<S>, key: &str) -> [f32; 4] { + rt.elements().into_iter().find(|e| e.key.as_deref() == Some(key)).unwrap().rect +} + +fn click(rt: &mut Runtime<S>, x: f32, y: f32) { + rt.pointer_move(x, y); + rt.pointer_down(x, y); + rt.pointer_up(x, y); + rt.frame(0.0); +} + +#[test] +fn an_offset_springs_without_moving_siblings_and_hits_follow_it() { + let mut rt = app(); + rt.update(|s, _| s.shift = 40.0); + rt.frame(1.0 / 60.0); + let y = rect(&rt, "a")[1]; + assert!(y > 0.0 && y < 40.0, "mid-spring: {y}"); + assert_eq!(rect(&rt, "b")[1], 40.0, "the sibling stays in place"); + for _ in 0..60 { + rt.frame(1.0 / 60.0); + } + assert_eq!(rect(&rt, "a")[1], 40.0); + // `b` comes later in the tree, so it takes the press where they overlap. + click(&mut rt, 50.0, 60.0); + assert_eq!(rt.state.pressed, ["b"]); + click(&mut rt, 50.0, 10.0); + assert_eq!(rt.state.pressed, ["b"], "nothing is left where `a` was"); + + rt.set_system_reduced_motion(true); + rt.update(|s, _| s.shift = 0.0); + rt.frame(1.0 / 60.0); + assert_eq!(rect(&rt, "a")[1], 0.0, "Reduce Motion lands it at once"); +} + +#[test] +fn a_raised_element_paints_and_takes_presses_above_later_siblings() { + let mut rt = app(); + rt.update(|s, _| { + s.shift = 20.0; + s.raise = true; + }); + rt.set_system_reduced_motion(true); + rt.frame(0.0); + click(&mut rt, 50.0, 50.0); + assert_eq!(rt.state.pressed, ["a"], "the raised element is on top where they overlap"); + let order: Vec<_> = rt.elements().into_iter().filter_map(|e| e.key).collect(); + assert_eq!(&order[..2], ["a", "b"], "tree order is unchanged"); + + rt.update(|s, _| s.raise = false); + rt.frame(0.0); + click(&mut rt, 50.0, 50.0); + assert_eq!(rt.state.pressed, ["a", "b"]); +} + +#[test] +fn hover_change_hears_an_element_that_appears_under_a_still_pointer() { + let mut rt = app(); + rt.pointer_move(150.0, 150.0); + rt.frame(0.0); + rt.update(|s, _| s.show = true); + for _ in 0..30 { + rt.frame(1.0 / 60.0); + } + assert_eq!(rt.state.hover, [true], "the pointer is inside without moving"); +} + +mod reorder { + use std::borrow::Cow; + + use rune::{Cx, El, Env, GrowthSpec, Runtime, ScrollSpec, Spring, col, el}; + + struct S { + order: Vec<usize>, + shift: Vec<f32>, + list: u8, + } + + fn row(s: &S, slot: usize) -> El { + el().key(format!("r{}", s.order[slot])).w_full().h(40.0).motion(Spring::new(0.3, 0.0)).offset(0.0, s.shift[slot]) + } + + fn view(s: &S, _: &mut Cx<S>) -> El { + let list = col().key("list").w_full(); + let list = match s.list { + 0 => list.children((0..s.order.len()).map(|i| row(s, i))), + 1 => list.growth(GrowthSpec::default()).children((0..s.order.len()).map(|i| row(s, i))), + _ => list.growth(GrowthSpec::default()).virtual_rows( + s.order.len(), + 40.0, + |s: &S, i| Cow::Owned(format!("r{}", s.order[i])), + |s: &S, i| row(s, i), + ), + }; + col().w_full().h_full().child(col().w_full().h_full().scroll(ScrollSpec { stick_bottom: false }).child(list)) + } + + fn y(rt: &Runtime<S>, k: &str) -> f32 { + rt.elements().into_iter().find(|e| e.key.as_deref() == Some(k)).unwrap().rect[1] + } + + /// Drag `r0` 50 points down past `r1`, which steps up, then drop it in slot 1. + fn drop_reordered(list: u8) { + let mut rt = Runtime::new(S { order: vec![0, 1, 2, 3], shift: vec![0.0; 4], list }, view, (200.0, 400.0), Env::new(true, 1.0)); + rt.frame(0.0); + rt.update(|s, tx| { + tx.instant(); + s.shift = vec![50.0, -40.0, 0.0, 0.0]; + }); + rt.frame(1.0 / 60.0); + assert_eq!((y(&rt, "r0"), y(&rt, "r1")), (50.0, 0.0)); + rt.update(|s, _| { + s.order = vec![1, 0, 2, 3]; + s.shift = vec![0.0; 4]; + }); + let mut last = 50.0; + for _ in 0..90 { + rt.frame(1.0 / 60.0); + let (r0, r1) = (y(&rt, "r0"), y(&rt, "r1")); + assert!(r0 <= last + 0.01 && r0 >= 39.99, "list {list}: r0 slides from 50 to 40, at {r0}"); + assert!(r1.abs() < 0.01, "list {list}: r1 stays where it was drawn, at {r1}"); + last = r0; + } + assert!((last - 40.0).abs() < 0.01); + } + + #[test] + fn a_reordered_row_that_drops_its_offset_slides_from_where_it_was_drawn() { + drop_reordered(0); + drop_reordered(1); + drop_reordered(2); + } + + #[test] + fn a_drop_mid_spring_in_five_thousand_virtual_rows_preserves_the_drawn_position() { + let mut rt = Runtime::new(S { order: (0..5000).collect(), shift: vec![0.0; 5000], list: 2 }, view, (200.0, 400.0), Env::new(true, 1.0)); + rt.frame(0.0); + rt.update(|s, _| { s.shift[0] = 85.0; s.shift[1] = -40.0; s.shift[2] = -40.0; }); + rt.frame(1.0 / 120.0); + rt.frame(1.0 / 120.0); + let before: Vec<_> = ["r0", "r1", "r2"].map(|k| y(&rt, k)).into(); + rt.update(|s, _| { s.order.remove(0); s.order.insert(2, 0); s.shift.fill(0.0); }); + rt.frame(0.0); + for (i, key) in ["r0", "r1", "r2"].iter().enumerate() { + assert!((y(&rt, key) - before[i]).abs() < 0.1, "{key} jumped on drop: {} -> {}", before[i], y(&rt, key)); + } + for _ in 0..120 { rt.frame(1.0 / 120.0); } + assert_eq!([y(&rt, "r0"), y(&rt, "r1"), y(&rt, "r2")], [80.0, 0.0, 40.0]); + } +} + +mod drag_animated { + use rune::{Cx, Drag, El, Env, Phase, Runtime, Spring, Tx, col, el}; + + struct S { + animated: bool, + shift: f32, + } + + fn view(s: &S, _: &mut Cx<S>) -> El { + let handle = el().key("handle").size(100.0, 40.0).on_drag(|s: &mut S, d: &mut Drag, tx: &mut Tx| { + if d.phase == Phase::Move { + if s.animated { + tx.animated(); + } + s.shift = 40.0; + } + }); + let other = el().key("other").size(100.0, 40.0).motion(Spring::new(0.3, 0.0)).offset(0.0, s.shift); + col().w_full().h_full().child(handle).child(other) + } + + fn moved_after_a_drag(animated: bool) -> f32 { + let mut rt = Runtime::new(S { animated, shift: 0.0 }, view, (200.0, 200.0), Env::new(true, 1.0)); + rt.frame(0.0); + rt.pointer_move(50.0, 20.0); + rt.pointer_down(50.0, 20.0); + rt.pointer_move(50.0, 60.0); + rt.frame(1.0 / 60.0); + rt.frame(1.0 / 60.0); + rt.pointer_up(50.0, 60.0); + rt.elements().into_iter().find(|e| e.key.as_deref() == Some("other")).unwrap().rect[1] - 40.0 + } + + #[test] + fn a_drag_move_lands_at_once_unless_the_handler_animates_it() { + assert_eq!(moved_after_a_drag(false), 40.0, "direct manipulation"); + let y = moved_after_a_drag(true); + assert!(y > 0.0 && y < 40.0, "on its spring: {y}"); + } + + #[test] + fn a_live_only_drag_cannot_make_another_handlers_commit_instant() { + fn live_view(s: &S, _: &mut Cx<S>) -> El { + col().w_full().h_full() + .child(el().size(100.0, 40.0).on_drag(|_: &mut S, d, tx| { + if d.phase == Phase::Move { tx.live_only(); } + })) + .child(el().key("other").size(100.0, 40.0).offset(0.0, s.shift).motion(Spring::new(0.3, 0.0))) + } + let mut rt = Runtime::new(S { animated: false, shift: 0.0 }, live_view, (200.0, 200.0), Env::new(true, 1.0)); + rt.check_live_only(false); + rt.on_key = Some(|s, _, tx| { s.shift = 40.0; tx.motion(Spring::new(0.6, 0.0)); true }); + rt.frame(0.0); + rt.pointer_down(20.0, 20.0); + rt.frame(0.0); + rt.pointer_move(20.0, 30.0); + rt.key(rune::KeyEvent { key: rune::Key::Enter, mods: rune::Mods::default() }); + rt.frame(1.0 / 60.0); + let shift = rt.elements().into_iter().find(|e| e.key.as_deref() == Some("other")).unwrap().rect[1] - 40.0; + assert!(shift > 0.0 && shift < 10.0, "the key's spring must survive a live-only Move: {shift}"); + assert_eq!(rt.live_only_events(), 1); + } +} + +mod double_press_on_a_drag { + use rune::{Cx, Drag, El, Env, Phase, Runtime, Spring, Tx, col, el}; + + #[derive(Default)] + struct S { + wide: bool, + } + + fn view(s: &S, _: &mut Cx<S>) -> El { + let grip = el() + .key("grip") + .size(100.0, 40.0) + .on_drag(|_: &mut S, d: &mut Drag, tx: &mut Tx| { + if d.phase == Phase::Move { + tx.instant(); + } + }) + .on_double_press(|s: &mut S| s.wide = true); + let pane = el().key("pane").h(40.0).w(if s.wide { 200.0 } else { 100.0 }).motion(Spring::new(0.3, 0.0)); + col().w_full().h_full().child(grip).child(pane) + } + + #[test] + fn a_double_click_on_a_draggable_element_animates_what_it_changes() { + let mut rt = Runtime::new(S::default(), view, (300.0, 200.0), Env::new(true, 1.0)); + rt.frame(0.0); + rt.pointer_move(50.0, 20.0); + for _ in 0..2 { + rt.pointer_down(50.0, 20.0); + rt.pointer_up(50.0, 20.0); + } + rt.frame(1.0 / 60.0); + assert!(rt.state.wide, "double pressed"); + let w = rt.elements().into_iter().find(|e| e.key.as_deref() == Some("pane")).unwrap().rect[2]; + assert!(w > 100.0 && w < 200.0, "on its spring, not at once: {w}"); + } +} diff --git a/app/vendor/rune/crates/rune/tests/integration/opacity_motion.rs b/app/vendor/rune/crates/rune/tests/integration/opacity_motion.rs new file mode 100644 index 0000000..0f86019 --- /dev/null +++ b/app/vendor/rune/crates/rune/tests/integration/opacity_motion.rs @@ -0,0 +1,53 @@ +//! An `opacity_motion` with its own delay and start velocity keeps running across commits that +//! leave the opacity alone, instead of starting over (and waiting out its delay) at each one. +use rune::{Anim, Curve, Cx, El, Env, Runtime, Spring, Velocity, col, el}; + +struct S { + shown: bool, + tick: u32, +} + +fn view(s: &S, _: &mut Cx<S>) -> El { + let mut fade = Anim::new(Curve::Spring(Spring::new(0.3, 0.0))); + fade.delay = 0.1; + fade.velocity = Velocity::Uniform(-2.0); + let e = el().key("e").size(50.0, 50.0).fill(rune::Color::BLACK).opacity(if s.shown { 1.0 } else { 0.0 }).opacity_motion(fade); + col().w_full().h_full().child(e).child(el().key(format!("tick{}", s.tick)).size(1.0, 1.0)) +} + +#[test] +fn an_unrelated_commit_doesnt_restart_a_fade() { + let mut rt = Runtime::new(S { shown: true, tick: 0 }, view, (100.0, 100.0), Env::new(true, 1.0)); + rt.frame(0.0); + rt.update(|s, _| s.shown = false); + let opacity = |rt: &Runtime<S>| rt.elements().into_iter().find(|e| e.key.as_deref() == Some("e")).unwrap().opacity; + let mut last = 1.0; + for i in 0..40 { + rt.update(|s, _| s.tick = i); + rt.frame(1.0 / 60.0); + let now = opacity(&rt); + assert!(now <= last + 1e-4, "frame {i}: the fade went back from {last} to {now}"); + last = now; + } + assert!(last < 0.05, "it finished: {last}"); +} + +fn hidden(s: &S, _: &mut Cx<S>) -> El { + let mut fade = Anim::new(Curve::Spring(Spring::new(0.3, 0.0))); + fade.velocity = Velocity::Uniform(-2.0); + let e = el().key("e").size(50.0, 50.0).fill(rune::Color::BLACK).opacity(0.0).opacity_motion(fade); + col().w_full().h_full().label(format!("tick {}", s.tick)).child(e) +} + +#[test] +fn a_hidden_element_stays_still_across_commits() { + let mut rt = Runtime::new(S { shown: false, tick: 0 }, hidden, (100.0, 100.0), Env::new(true, 1.0)); + rt.frame(0.0); + for _ in 0..60 { + rt.frame(1.0 / 60.0); + } + rt.update(|s, _| s.tick = 1); + for i in 0..3 { + assert!(!rt.frame(1.0 / 60.0), "frame {i}: nothing to animate"); + } +} diff --git a/app/vendor/rune/crates/rune/tests/integration/pinned_scroll.rs b/app/vendor/rune/crates/rune/tests/integration/pinned_scroll.rs new file mode 100644 index 0000000..507ceff --- /dev/null +++ b/app/vendor/rune/crates/rune/tests/integration/pinned_scroll.rs @@ -0,0 +1,62 @@ +//! A scroll pinned to all four edges of its parent takes its size from those insets, not from +//! its content, so its rows scroll inside it. +use rune::runtime::ElementInfo; +use rune::{Cx, El, Env, Runtime, ScrollSpec, col, el}; + +struct S; + +fn rows(prefix: &str) -> El { + (0..30).fold(col().w_full(), |c, i| c.child(el().key(format!("{prefix}{i}")).w_full().h(40.0))) +} + +fn view(_: &S, _: &mut Cx<S>) -> El { + col().w_full().h_full() + // Pinned in a padded parent near the root. + .child(col().key("panel").w(300.0).h(400.0).padding(10.0) + .child(col().key("scroll").pin(Some(0.0), Some(40.0), Some(0.0), Some(0.0)).scroll(ScrollSpec { stick_bottom: false }).child(rows("a")))) + // The same, nested in a row of a column. + .child(col().w_full().padding(20.0).child( + col().key("sidebar").w(200.0).h(300.0).px(8.0).py(12.0).border(1.0, rune::Color::BLACK) + .child(col().key("nested").pin(Some(0.0), Some(0.0), Some(0.0), Some(30.0)).scroll(ScrollSpec { stick_bottom: false }).child(rows("b"))), + )) +} + +fn find(rt: &Runtime<S>, key: &str) -> ElementInfo { + rt.elements().into_iter().find(|e| e.key.as_deref() == Some(key)).unwrap_or_else(|| panic!("{key}")) +} + +#[test] +fn a_pinned_scroll_fills_its_insets_and_scrolls() { + let mut rt = Runtime::new(S, view, (600.0, 900.0), Env::new(true, 2.0)); + rt.frame(0.0); + let (panel, scroll) = (find(&rt, "panel"), find(&rt, "scroll")); + // Insets measure from the padding box (CSS): the padding doesn't push a pinned child in. + assert_eq!(scroll.rect, [panel.rect[0], panel.rect[1] + 40.0, 300.0, 360.0], "fills the panel's padding box below 40"); + let (sidebar, nested) = (find(&rt, "sidebar"), find(&rt, "nested")); + // Rune borders paint inside the box and take no layout space: the padding box is the box. + assert_eq!(nested.rect, [sidebar.rect[0], sidebar.rect[1], 200.0, 300.0 - 30.0]); + + // Its rows overflow and scroll inside it. + let before = find(&rt, "a5").rect[1]; + rt.wheel(100.0, 200.0, -120.0); + for _ in 0..30 { rt.frame(1.0 / 60.0); } + assert!(find(&rt, "a5").rect[1] < before - 100.0, "the rows scrolled"); + assert_eq!(find(&rt, "scroll").rect, scroll.rect, "the viewport stayed put"); +} + +fn grown(_: &S, _: &mut Cx<S>) -> El { + col().w_full().h_full() + .child(el().key("header").w_full().h(50.0)) + .child(col().key("body").w_full().grow(1.0).shrink() + .child(col().key("scroll").pin(Some(0.0), Some(0.0), Some(0.0), Some(0.0)).scroll(ScrollSpec { stick_bottom: true }).child(rows("c")))) +} + +#[test] +fn a_pinned_scroll_in_a_flex_grown_parent_neither_grows_it_nor_itself() { + let mut rt = Runtime::new(S, grown, (400.0, 600.0), Env::new(true, 2.0)); + rt.frame(0.0); + assert_eq!(find(&rt, "body").rect, [0.0, 50.0, 400.0, 550.0]); + assert_eq!(find(&rt, "scroll").rect, [0.0, 50.0, 400.0, 550.0]); + let last = find(&rt, "c29").rect; + assert!((last[1] + last[3] - 600.0).abs() < 0.05, "stuck to its bottom: {last:?}"); +} diff --git a/app/vendor/rune/crates/rune/tests/integration/pixel_scale.rs b/app/vendor/rune/crates/rune/tests/integration/pixel_scale.rs new file mode 100644 index 0000000..069afc4 --- /dev/null +++ b/app/vendor/rune/crates/rune/tests/integration/pixel_scale.rs @@ -0,0 +1,25 @@ +use rune::{Color, Cx, El, Env, Runtime, col, el}; + +fn view(_: &(), _: &mut Cx<()>) -> El { + col().w_full().h_full().child( + el().key("row").absolute(0.123, 0.137).size(30.123, 20.137) + .fill(Color::WHITE).hover(Color::BLACK).on_press(|_: &mut ()| {}), + ) +} + +#[test] +fn pixel_scale_change_matches_instances_from_a_fresh_runtime() { + let make = |scale| { + let mut rt = Runtime::new((), view, (240.0, 150.0), Env::new(true, scale)); + rt.frame(0.0); + rt + }; + let mut rt = make(1.0); + for scale in [2.0, 1.5, 1.0] { + rt.set_viewport((240.0, 150.0), scale); + rt.frame(0.0); + let fresh = make(scale); + assert_eq!(bytemuck::cast_slice::<_, u8>(&rt.instances), bytemuck::cast_slice::<_, u8>(&fresh.instances), + "settled hover rows resnap at scale {scale}"); + } +} diff --git a/app/vendor/rune/crates/rune/tests/integration/playground_deep.rs b/app/vendor/rune/crates/rune/tests/integration/playground_deep.rs new file mode 100644 index 0000000..0b17917 --- /dev/null +++ b/app/vendor/rune/crates/rune/tests/integration/playground_deep.rs @@ -0,0 +1,229 @@ +//! Deep story paths: groups at any depth, a list that starts folded, folds kept across runs, +//! the filter's keys, and top-level groups in the order the app names. +use std::cell::RefCell; +use std::rc::Rc; + +use rune::{App, AppSpec, Cx, El, ElementInfo, Env, Key, KeyEvent, Mods, Playground, Runtime, Story, text}; + +#[derive(Default)] +struct Real; + +fn real(_: &Real, _: &mut Cx<Real>) -> El { + text("the app") +} + +#[derive(Default)] +struct Card; + +fn card(_: &Card, _: &mut Cx<Card>) -> El { + text("card").key("card") +} + +/// Stories 0 and 1 are scenes; the rest are stories, 2 onwards, declared out of list order. +fn playground() -> Playground<Real> { + Playground::<Real>::new() + .story(Story::new("Fixtures/Linux & Windows/General/Portal", Card::default, card)) + .story(Story::new("Settings panes/General/Microphone missing", Card::default, card)) + .story(Story::new("Settings panes/General/Portal", Card::default, card)) + .story(Story::new("Prototypes/HUD/Processing", Card::default, card)) + .story(Story::new("Prototypes/Onboarding/Option · Pill", Card::default, card)) + .story(Story::new("Toasts/Sync", Card::default, card)) +} + +const SCENES: &[(&str, fn(&mut Real))] = &[("Launch", |_| {}), ("Fixtures/Empty", |_| {})]; + +fn runtime(playground: Playground<Real>) -> Runtime<Real> { + let spec = AppSpec { scenes: SCENES, ..AppSpec::new("deep", (900.0, 700.0), Real::default, real) }; + App::new(spec).playground(playground).headless_runtime((900.0, 700.0), Env::new(false, 1.0)) +} + +fn ordered() -> Playground<Real> { + playground().group_order(&["Prototypes", "Settings panes", "Not a group", "Fixtures"]) +} + +fn press_with(rt: &mut Runtime<Real>, key: Key, mods: Mods) { + rt.key(KeyEvent { key, mods }); + rt.frame(1.0 / 60.0); +} + +fn press(rt: &mut Runtime<Real>, key: Key) { + press_with(rt, key, Mods::default()); +} + +fn typed(rt: &mut Runtime<Real>, s: &str) { + press(rt, Key::Text(s.into())); +} + +fn element(rt: &Runtime<Real>, key: &str) -> Option<ElementInfo> { + rt.elements().into_iter().find(|e| e.key.as_deref() == Some(key) && !e.exiting) +} + +fn shown(rt: &Runtime<Real>, key: &str) -> bool { + element(rt, key).is_some() +} + +/// The first text inside the element keyed `key`. +fn label(rt: &Runtime<Real>, key: &str) -> String { + let all = rt.elements(); + let at = all.iter().position(|e| e.key.as_deref() == Some(key) && !e.exiting).unwrap_or_else(|| panic!("no {key}")); + let inside = |e: &ElementInfo| std::iter::successors(e.parent, |&p| all[p].parent).any(|p| p == at); + all.iter().find(|e| e.text.is_some() && inside(e)).and_then(|e| e.text.clone()).expect("a label") +} + +/// The open story's group path and name, as the side column titles it. +fn open(rt: &Runtime<Real>) -> String { + let all = rt.elements(); + let at = all.iter().position(|e| e.key.as_deref() == Some("playground-title")).expect("a title"); + let parts: Vec<String> = all.iter().filter(|e| e.parent == Some(at)).filter_map(|e| e.text.clone()).collect(); + parts.join(" › ") +} + +/// The list's rows top to bottom, by key: headers and stories. +fn rows(rt: &Runtime<Real>) -> Vec<String> { + let mut rows: Vec<(f32, String)> = rt.elements().into_iter() + .filter(|e| !e.exiting) + .filter_map(|e| e.key.filter(|k| k.starts_with("playground-item-") || k.starts_with("playground-group-")).map(|k| (e.rect[1], k))) + .collect(); + rows.sort_by(|a, b| a.0.total_cmp(&b.0)); + rows.into_iter().map(|(_, k)| k.replace("playground-", "")).collect() +} + +fn focused(rt: &Runtime<Real>) -> Option<String> { + rt.elements().into_iter().find(|e| e.focused).and_then(|e| e.key) +} + +fn tap(rt: &mut Runtime<Real>, key: &str) { + let (x, y) = rt.find(key).unwrap_or_else(|| panic!("no {key}")); + rt.pointer_move(x, y); + rt.pointer_down(x, y); + rt.pointer_up(x, y); + rt.frame(1.0 / 60.0); +} + +fn reopen(rt: &mut Runtime<Real>) { + rt.update(|_, tx| tx.close_playground()); + rt.frame(1.0 / 60.0); + rt.update(|_, tx| tx.open_playground()); + rt.frame(1.0 / 60.0); +} + +#[test] +fn a_path_nests_as_deep_as_it_goes_and_every_lookup_finds_it() { + let mut rt = runtime(playground()); + rt.open_playground("Fixtures/Linux & Windows/General/Portal", None); + assert_eq!(open(&rt), "Fixtures › Linux & Windows › General › Portal"); + let deep = ["group-1", "item-1", "group-2-1", "group-2-2", "item-2"]; + assert!(deep.iter().all(|k| rows(&rt).contains(&k.to_string())), "a header at each level: {:?}", rows(&rt)); + assert_eq!([label(&rt, "playground-group-2-1"), label(&rt, "playground-group-2-2")], ["Linux & Windows", "General"]); + rt.open_playground("prototypes-onboarding-option-pill", None); + assert_eq!(open(&rt), "Prototypes › Onboarding › Option · Pill", "by slug"); + rt.open_playground("Microphone missing", None); + assert_eq!(open(&rt), "Settings panes › General › Microphone missing", "by name"); + rt.open_playground("Launch", None); + assert_eq!(open(&rt), "Scenes › Launch", "a one-level path as before"); + rt.open_playground("toasts-sync", None); + assert_eq!(open(&rt), "Toasts › Sync"); +} + +#[test] +fn group_order_lists_the_named_groups_first_scenes_and_stories_alike() { + let mut rt = runtime(ordered()); + rt.update(|_, tx| tx.open_playground()); + rt.frame(0.0); + assert_eq!(open(&rt), "Prototypes › HUD › Processing", "the first story in the list opens first"); + let order = ["group-5", "group-5-1", "item-5", "group-6-1", "item-6", "group-3", "group-3-1", "item-3", "item-4", "group-1", "item-1", "group-2-1", "group-2-2", "item-2", "group-0", "item-0", "group-7", "item-7"]; + assert_eq!(rows(&rt), order, "named groups first, in their order; then the rest as they first appear"); + rt.update(|_, tx| tx.open_playground_at("Portal", None)); + rt.frame(0.0); + assert_eq!(open(&rt), "Settings panes › General › Portal", "a name two stories have finds the first in the list"); + rt.update(|_, tx| tx.open_playground_at("Processing", None)); + rt.frame(0.0); + typed(&mut rt, "j"); + assert_eq!(open(&rt), "Prototypes › Onboarding › Option · Pill"); + typed(&mut rt, "j"); + assert_eq!(open(&rt), "Settings panes › General › Microphone missing", "J goes down the list, past its headers"); + press(&mut rt, Key::Down); + assert_eq!(open(&rt), "Settings panes › General › Portal", "and so does ↓"); + typed(&mut rt, "/"); + typed(&mut rt, "general"); + press(&mut rt, Key::Down); + assert_eq!(open(&rt), "Settings panes › General › Microphone missing", "the filter's matches are in list order too"); +} + +#[test] +fn without_group_order_scenes_come_first_as_before() { + let mut rt = runtime(playground()); + rt.update(|_, tx| tx.open_playground()); + rt.frame(0.0); + assert_eq!(open(&rt), "Scenes › Launch"); + assert_eq!(rows(&rt)[..4], ["group-0", "item-0", "group-1", "item-1"]); +} + +#[test] +fn start_folded_folds_everything_but_the_open_storys_groups() { + let mut rt = runtime(ordered().start_folded(true)); + // As a link at launch delivers it: an update before the first frame. + rt.update(|_, tx| tx.open_playground_at("prototypes-onboarding-option-pill", None)); + rt.frame(0.0); + assert_eq!(rows(&rt), ["group-5", "group-5-1", "group-6-1", "item-6", "group-3", "group-1", "group-0", "group-7"]); + tap(&mut rt, "playground-group-3"); + assert!(shown(&rt, "playground-group-3-1") && !shown(&rt, "playground-item-3"), "a group unfolds one level, the ones inside it still folded"); + reopen(&mut rt); + assert!(shown(&rt, "playground-group-3-1"), "and stays unfolded while the app runs"); + assert!(shown(&rt, "playground-item-6"), "the open story's groups unfold as it opens"); +} + +#[test] +fn start_folded_saves_the_unfolded_groups_and_loads_them_next_run() { + let saved: Rc<RefCell<Vec<String>>> = Rc::default(); + let saves = saved.clone(); + let mut rt = runtime(ordered().start_folded(true).folds(Vec::new, move |groups| *saves.borrow_mut() = groups.to_vec())); + rt.open_playground("Processing", None); + tap(&mut rt, "playground-group-1"); + tap(&mut rt, "playground-group-2-1"); + assert_eq!(*saved.borrow(), ["Prototypes", "Prototypes/HUD", "Fixtures", "Fixtures/Linux & Windows"], "full paths of the groups left open"); + let names = saved.borrow().clone(); + let mut next = runtime(ordered().start_folded(true).folds(move || names.clone(), |_| {})); + next.update(|_, tx| tx.open_playground_at("Toasts/Sync", None)); + next.frame(0.0); + assert!(shown(&next, "playground-group-2-2") && !shown(&next, "playground-item-2"), "next run, the same groups open"); + assert!(shown(&next, "playground-item-5") && !shown(&next, "playground-group-3-1"), "and the rest folded"); + assert!(shown(&next, "playground-item-7"), "with the open story's"); +} + +#[test] +fn folds_save_full_paths_and_load_old_one_level_names() { + let saved: Rc<RefCell<Vec<String>>> = Rc::default(); + let saves = saved.clone(); + let load = || vec!["Toasts".to_owned(), "Fixtures/Linux & Windows/General".to_owned(), "Gone".to_owned()]; + let mut rt = runtime(ordered().folds(load, move |groups| *saves.borrow_mut() = groups.to_vec())); + rt.open_playground("Processing", None); + assert!(!shown(&rt, "playground-item-7") && !shown(&rt, "playground-item-2") && shown(&rt, "playground-group-2-2"), "an old name and a deep path both load"); + tap(&mut rt, "playground-group-6-1"); + assert_eq!(*saved.borrow(), ["Fixtures/Linux & Windows/General", "Toasts", "Prototypes/Onboarding"]); +} + +#[test] +fn the_filter_edits_like_a_field_and_down_goes_into_its_matches() { + let mut rt = runtime(ordered()); + rt.open_playground("Toasts/Sync", None); + tap(&mut rt, "playground-filter"); + assert_eq!(focused(&rt).as_deref(), Some("playground-filter"), "a click focuses it"); + typed(&mut rt, "hud"); + press_with(&mut rt, Key::Command('a'), Mods { cmd: true, ..Mods::default() }); + typed(&mut rt, "portal"); + assert_eq!(rows(&rt), ["group-3", "group-3-1", "item-4", "group-1", "group-2-1", "group-2-2", "item-2"], "⌘A selects what's typed, which typing replaces"); + press(&mut rt, Key::Down); + assert_eq!((open(&rt), focused(&rt)), ("Settings panes › General › Portal".to_owned(), None), "↓ goes to the first match, and the list has the keyboard"); + typed(&mut rt, "j"); + assert_eq!(open(&rt), "Fixtures › Linux & Windows › General › Portal"); + typed(&mut rt, "k"); + press(&mut rt, Key::Up); + assert_eq!(focused(&rt).as_deref(), Some("playground-filter"), "↑ from the first match goes back up to the field"); + press(&mut rt, Key::Escape); + assert_eq!(focused(&rt).as_deref(), Some("playground-filter"), "Esc empties it first"); + assert!(shown(&rt, "playground-item-5")); + press(&mut rt, Key::Escape); + assert_eq!(focused(&rt), None, "then leaves"); + assert!(rt.playground_state::<Card>().is_some(), "with the playground still open"); +} diff --git a/app/vendor/rune/crates/rune/tests/integration/playground_folds.rs b/app/vendor/rune/crates/rune/tests/integration/playground_folds.rs new file mode 100644 index 0000000..287c03a --- /dev/null +++ b/app/vendor/rune/crates/rune/tests/integration/playground_folds.rs @@ -0,0 +1,88 @@ +//! Folded groups: kept while the app runs, and through `Playground::folds` from one run to the +//! next. +use std::cell::RefCell; +use std::rc::Rc; + +use rune::{App, AppSpec, Cx, El, Env, Playground, Runtime, Story, text}; + +#[derive(Default)] +struct Real; + +fn real(_: &Real, _: &mut Cx<Real>) -> El { + text("the app") +} + +#[derive(Default)] +struct Card; + +fn card(_: &Card, _: &mut Cx<Card>) -> El { + text("card").key("card") +} + +fn playground() -> Playground<Real> { + Playground::<Real>::new() + .story(Story::new("Cards/Plain", Card::default, card)) + .story(Story::new("Cards/Raised", Card::default, card)) + .story(Story::new("Lists/Short", Card::default, card)) +} + +fn runtime(playground: Playground<Real>) -> Runtime<Real> { + App::new(AppSpec::new("folds", (800.0, 500.0), Real::default, real)).playground(playground).headless_runtime((800.0, 500.0), Env::new(false, 1.0)) +} + +/// Whether the list shows a row keyed `key`. +fn shown(rt: &Runtime<Real>, key: &str) -> bool { + rt.elements().iter().any(|e| e.key.as_deref() == Some(key) && !e.exiting) +} + +fn tap(rt: &mut Runtime<Real>, key: &str) { + let (x, y) = rt.find(key).unwrap_or_else(|| panic!("no {key}")); + rt.pointer_move(x, y); + rt.pointer_down(x, y); + rt.pointer_up(x, y); + rt.frame(1.0 / 60.0); +} + +fn reopen(rt: &mut Runtime<Real>) { + rt.update(|_, tx| tx.close_playground()); + rt.frame(1.0 / 60.0); + rt.update(|_, tx| tx.open_playground()); + rt.frame(1.0 / 60.0); +} + +#[test] +fn a_folded_group_stays_folded_after_the_playground_closes() { + let mut rt = runtime(playground()); + rt.open_playground("Lists/Short", None); + assert!(shown(&rt, "playground-item-1")); + tap(&mut rt, "playground-group-0"); + assert!(!shown(&rt, "playground-item-1"), "Cards folded"); + reopen(&mut rt); + assert!(!shown(&rt, "playground-item-1"), "and still folded, reopened"); + assert!(shown(&rt, "playground-item-2"), "Lists isn't"); +} + +#[test] +fn folds_loads_once_and_saves_each_change() { + let saved: Rc<RefCell<Vec<Vec<String>>>> = Rc::default(); + let loads = Rc::new(RefCell::new(0)); + let (saves, count) = (saved.clone(), loads.clone()); + let playground = playground().folds( + move || { + *count.borrow_mut() += 1; + vec!["Cards".to_owned(), "Gone".to_owned()] + }, + move |groups| saves.borrow_mut().push(groups.to_vec()), + ); + let mut rt = runtime(playground); + assert_eq!(*loads.borrow(), 0, "nothing loads until the playground opens"); + rt.open_playground("Lists/Short", None); + assert!(!shown(&rt, "playground-item-0") && shown(&rt, "playground-item-2"), "Cards loads folded"); + tap(&mut rt, "playground-group-2"); + tap(&mut rt, "playground-group-0"); + assert_eq!(*saved.borrow(), [vec!["Cards".to_owned(), "Lists".to_owned()], vec!["Lists".to_owned()]], "a group it doesn't have is dropped"); + reopen(&mut rt); + assert_eq!(*loads.borrow(), 1, "loaded once"); + rt.open_playground("Lists/Short", None); + assert_eq!(saved.borrow().last().map(Vec::len), Some(0), "opening a story in a folded group unfolds it, and saves that"); +} diff --git a/app/vendor/rune/crates/rune/tests/integration/playground_keys.rs b/app/vendor/rune/crates/rune/tests/integration/playground_keys.rs new file mode 100644 index 0000000..51ca5e3 --- /dev/null +++ b/app/vendor/rune/crates/rune/tests/integration/playground_keys.rs @@ -0,0 +1,113 @@ +//! Keys the playground's list doesn't use reach the open story: its `AppSpec::on_key` hears ⌘K +//! and digits while the list has the keyboard, and the list keeps its arrows, J K, Esc and the +//! filter. +use rune::{App, AppSpec, Cx, El, Env, Key, KeyEvent, Mods, Playground, Runtime, text}; + +#[derive(Default)] +struct Real { + scene: &'static str, + palette: bool, + typed: String, +} + +fn real(s: &Real, _: &mut Cx<Real>) -> El { + text(format!("{} {} {}", s.scene, s.palette, s.typed)).key("real") +} + +/// ⌘K opens a palette, Esc closes it, and every typed key is noted. +fn on_key(s: &mut Real, ev: &KeyEvent, _: &mut rune::Tx) -> bool { + match &ev.key { + Key::Command('k') if ev.mods.cmd => s.palette = !s.palette, + Key::Escape if s.palette => s.palette = false, + Key::Text(t) => s.typed.push_str(t), + _ => return false, + } + true +} + +const SCENES: &[(&str, fn(&mut Real))] = &[("Launch", |s| s.scene = "launch"), ("Palette/Search", |s| s.scene = "search")]; + +fn runtime() -> Runtime<Real> { + let spec = AppSpec { scenes: SCENES, on_key: Some(on_key), ..AppSpec::new("keys", (900.0, 600.0), Real::default, real) }; + let mut rt = App::new(spec).playground(Playground::<Real>::new()).headless_runtime((900.0, 600.0), Env::new(false, 1.0)); + rt.open_playground("Launch", None); + rt +} + +fn press_with(rt: &mut Runtime<Real>, key: Key, mods: Mods) { + rt.key(KeyEvent { key, mods }); + rt.frame(1.0 / 60.0); +} + +fn press(rt: &mut Runtime<Real>, key: Key) { + press_with(rt, key, Mods::default()); +} + +fn typed(rt: &mut Runtime<Real>, s: &str) { + press(rt, Key::Text(s.into())); +} + +fn command_k(rt: &mut Runtime<Real>) { + press_with(rt, Key::Command('k'), Mods { cmd: true, ..Mods::default() }); +} + +fn stage(rt: &Runtime<Real>) -> (&'static str, bool, String) { + let s = rt.playground_state::<Real>().expect("a scene on the stage"); + (s.scene, s.palette, s.typed.clone()) +} + +fn shown(rt: &Runtime<Real>, key: &str) -> bool { + rt.elements().into_iter().any(|e| e.key.as_deref() == Some(key) && !e.exiting) +} + +fn hint(rt: &Runtime<Real>) -> String { + rt.elements().into_iter().find(|e| e.key.as_deref() == Some("playground-hint")).and_then(|e| e.text).unwrap_or_default().replace('\u{a0}', " ") +} + +#[test] +fn a_story_opened_from_the_list_hears_the_keys_the_list_leaves() { + let mut rt = runtime(); + press(&mut rt, Key::Down); + press(&mut rt, Key::Down); + assert_eq!(stage(&rt).0, "search", "↓ opens the next story, the keyboard still on the list"); + assert!(hint(&rt).starts_with("↑↓ stories")); + command_k(&mut rt); + assert!(stage(&rt).1, "⌘K reaches the story's on_key"); + typed(&mut rt, "3"); + assert_eq!(stage(&rt).2, "3", "and so does a digit"); + assert!(!rt.state.palette && rt.state.typed.is_empty(), "the stage's state, not the app's"); + press(&mut rt, Key::Escape); + assert_eq!(stage(&rt).1, false, "Esc goes to the story first"); + typed(&mut rt, "k"); + assert_eq!(stage(&rt), ("launch", false, String::new()), "K is the list's: it moves to the story above"); + press(&mut rt, Key::Down); + press(&mut rt, Key::Down); + press(&mut rt, Key::Up); + press(&mut rt, Key::Up); + assert_eq!(stage(&rt), ("launch", false, String::new()), "so are the arrows, and none reach the story"); + press(&mut rt, Key::Tab); + command_k(&mut rt); + assert!(stage(&rt).1, "from the side column too"); + press(&mut rt, Key::Escape); + assert!(stage(&rt).1 && hint(&rt).starts_with("↑↓ stories"), "Esc there goes back to the list"); + press(&mut rt, Key::Escape); + assert!(!stage(&rt).1, "where Esc closes the story's palette"); + press(&mut rt, Key::Escape); + assert!(rt.playground_state::<Real>().is_none(), "then leaves"); +} + +#[test] +fn typing_in_the_filter_filters() { + let mut rt = runtime(); + typed(&mut rt, "/"); + typed(&mut rt, "sea"); + typed(&mut rt, "2"); + assert!(!shown(&rt, "playground-item-0") && !shown(&rt, "playground-item-1"), "nothing matches \"sea2\""); + assert_eq!(stage(&rt), ("launch", false, String::new()), "the field keeps what's typed"); + press(&mut rt, Key::Backspace); + assert!(shown(&rt, "playground-item-1") && !shown(&rt, "playground-item-0")); + command_k(&mut rt); + assert!(stage(&rt).1, "a chord the field doesn't use reaches the story"); + press(&mut rt, Key::Enter); + assert_eq!(stage(&rt).0, "search", "Return opens the first match"); +} diff --git a/app/vendor/rune/crates/rune/tests/integration/playground_links.rs b/app/vendor/rune/crates/rune/tests/integration/playground_links.rs new file mode 100644 index 0000000..7cfe65e --- /dev/null +++ b/app/vendor/rune/crates/rune/tests/integration/playground_links.rs @@ -0,0 +1,93 @@ +//! Opening a playground story from the app: `Tx::open_playground_at` by path, name or slug, +//! as a link through `App::on_open_url` does at launch. +use std::cell::Cell; + +use rune::playground::slug; +use rune::{App, AppSpec, Cx, El, Env, Playground, Runtime, Story, text}; + +thread_local! { + /// How many times the app's own view ran, on this test's thread. + static APP_VIEWS: Cell<usize> = const { Cell::new(0) }; +} + +#[derive(Default)] +struct Real; + +fn app_view(_: &Real, _: &mut Cx<Real>) -> El { + APP_VIEWS.with(|n| n.set(n.get() + 1)); + text("the app").key("app") +} + +#[derive(Default)] +struct Upload { + bytes: u32, +} + +fn upload(u: &Upload, _: &mut Cx<Upload>) -> El { + text(format!("{} bytes", u.bytes)).key("upload") +} + +fn runtime() -> Runtime<Real> { + let playground = Playground::<Real>::new() + .story(Story::new("Timeline/Send", Upload::default, upload).variant("Small", |u| u.bytes = 10).variant("Large", |u| u.bytes = 1_000_000)) + .story(Story::new("Lists/Many devices", Upload::default, upload)); + App::new(AppSpec::new("links", (800.0, 500.0), Real::default, app_view)).playground(playground).headless_runtime((800.0, 500.0), Env::new(false, 1.0)) +} + +fn bytes(rt: &Runtime<Real>) -> Option<u32> { + rt.playground_state::<Upload>().map(|u| u.bytes) +} + +#[test] +fn a_slug_is_the_path_lowercased_with_dashes() { + assert_eq!(slug("Timeline/Send"), "timeline-send"); + assert_eq!(slug("Lists/Many devices"), "lists-many-devices"); + assert_eq!(slug(" Toasts / Sync -- toast! "), "toasts-sync-toast"); + assert_eq!(slug("Café/Crème brûlée"), "café-crème-brûlée"); + assert_eq!(slug("Motion/Fade 2"), "motion-fade-2"); +} + +#[test] +fn every_lookup_takes_a_slug() { + let mut rt = runtime(); + rt.open_playground("lists-many-devices", None); + assert_eq!(bytes(&rt), Some(0)); + rt.open_playground("timeline-send", Some("Large")); + assert_eq!(bytes(&rt), Some(1_000_000)); +} + +#[test] +fn a_link_before_the_first_frame_opens_straight_onto_the_story() { + let mut rt = runtime(); + // As App::on_open_url delivers the link that launched the app: an update before frame 1. + rt.update(|_, tx| tx.open_playground_at("timeline-send", Some("Large"))); + rt.frame(0.0); + assert_eq!(rt.playground_element("upload").and_then(|e| e.text).as_deref(), Some("1000000 bytes"), "the first frame shows the story"); + assert_eq!(APP_VIEWS.with(Cell::get), 0, "and the app's view never ran"); +} + +#[test] +fn from_a_handler_it_moves_an_open_playground_to_the_story() { + let mut rt = runtime(); + rt.open_playground("Lists/Many devices", None); + rt.update(|_, tx| tx.open_playground_at("Send", Some("2"))); + rt.frame(0.0); + assert_eq!(bytes(&rt), Some(1_000_000), "by name, on the variant by number"); +} + +#[test] +fn an_unknown_story_opens_the_list_instead_of_stopping_the_app() { + let mut rt = runtime(); + rt.update(|_, tx| tx.open_playground_at("timeline-nope", None)); + rt.frame(0.0); + assert!(rt.find("playground-list").is_some(), "the playground is open, on its list"); + assert_eq!(bytes(&rt), Some(10), "on the first story, as it would open without a name"); +} + +#[test] +fn an_unknown_variant_opens_the_story_as_it_would_without_one() { + let mut rt = runtime(); + rt.update(|_, tx| tx.open_playground_at("Timeline/Send", Some("Huge"))); + rt.frame(0.0); + assert_eq!(bytes(&rt), Some(10), "its first variant"); +} diff --git a/app/vendor/rune/crates/rune/tests/integration/playground_replay.rs b/app/vendor/rune/crates/rune/tests/integration/playground_replay.rs new file mode 100644 index 0000000..a605d03 --- /dev/null +++ b/app/vendor/rune/crates/rune/tests/integration/playground_replay.rs @@ -0,0 +1,68 @@ +//! Replaying and triggering the open story from a handler: `Tx::replay_playground` and +//! `Tx::playground_trigger`, as a deep link does after `Tx::open_playground_at`. +use rune::{App, AppSpec, Cx, El, Env, Playground, Runtime, Story, text}; + +#[derive(Default)] +struct Real; + +#[derive(Default)] +struct Count { + n: u32, +} + +fn count(c: &Count, _: &mut Cx<Count>) -> El { + text(format!("{}", c.n)).key("count") +} + +fn runtime() -> Runtime<Real> { + let story = Story::new("Motion/Count", Count::default, count) + .trigger('r', "Replay", |c: &mut Count, _| c.n += 1) + .trigger('s', "Step", |c: &mut Count, _| c.n += 100); + App::new(AppSpec::new("replay", (400.0, 300.0), Real::default, |_: &Real, _: &mut Cx<Real>| text("app"))) + .playground(Playground::<Real>::new().story(story)) + .headless_runtime((400.0, 300.0), Env::new(false, 1.0)) +} + +fn n(rt: &Runtime<Real>) -> Option<u32> { + rt.playground_state::<Count>().map(|c| c.n) +} + +fn handler(rt: &mut Runtime<Real>, f: impl Fn(&mut rune::Tx) + 'static) { + rt.update(move |_, tx| f(tx)); + rt.frame(0.0); + rt.frame(0.0); +} + +#[test] +fn a_handler_triggers_and_replays_the_open_story() { + let mut rt = runtime(); + rt.open_playground("motion-count", None); + assert_eq!(n(&rt), Some(1), "opening runs 'r' once"); + handler(&mut rt, |tx| tx.playground_trigger('s')); + assert_eq!(n(&rt), Some(101)); + handler(&mut rt, |tx| tx.replay_playground()); + assert_eq!(n(&rt), Some(1), "replay makes the stage again, then runs 'r'"); + handler(&mut rt, |tx| tx.playground_trigger('S')); + handler(&mut rt, |tx| tx.playground_trigger('R')); + assert_eq!(n(&rt), Some(1), "'r' is replay"); + handler(&mut rt, |tx| tx.playground_trigger('x')); + assert_eq!(n(&rt), Some(1), "an unknown key does nothing"); +} + +#[test] +fn a_link_opens_then_replays_in_one_handler() { + let mut rt = runtime(); + handler(&mut rt, |tx| { + tx.open_playground_at("motion-count", None); + tx.playground_trigger('s'); + tx.replay_playground(); + }); + assert_eq!(n(&rt), Some(1), "the replay applies to the story the link opened"); +} + +#[test] +fn closed_it_does_nothing() { + let mut rt = runtime(); + handler(&mut rt, |tx| { tx.replay_playground(); tx.playground_trigger('s'); }); + assert_eq!(n(&rt), None); +} diff --git a/app/vendor/rune/crates/rune/tests/integration/playground_side_keys.rs b/app/vendor/rune/crates/rune/tests/integration/playground_side_keys.rs new file mode 100644 index 0000000..c8ff96a --- /dev/null +++ b/app/vendor/rune/crates/rune/tests/integration/playground_side_keys.rs @@ -0,0 +1,414 @@ +//! A story's side controls that take keys (`Story::side_keys`, `Playground::side_keys`): the +//! keyboard goes onto them from the list, their hook gets keys first, and Esc or Tab leave. +use rune::{App, AppSpec, Cx, El, Env, Key, KeyEvent, Link, Mods, Playground, Runtime, Story, Tx, rich, text}; + +#[derive(Default)] +struct Real { + level: i32, +} + +fn real(s: &Real, _: &mut Cx<Real>) -> El { + text(format!("level {}", s.level)).key("level") +} + +static SCENES: &[(&str, fn(&mut Real))] = &[("Meter/High", |s| s.level = 50)]; + +#[derive(Default)] +struct Dial { + value: i32, + failed: bool, + opened: bool, +} + +fn dial(d: &Dial, _: &mut Cx<Dial>) -> El { + text(format!("dial {}", d.value)).key("dial") +} + +/// A stage whose link, like any link, leaves focus where it is when clicked. +fn linked(_: &Dial, _: &mut Cx<Dial>) -> El { + rich("open the docs", Vec::new()).key("stage-link").w(200.0).link(Link::new(0..13, "docs")).on_link(|d: &mut Dial, _, _| d.opened = true) +} + +/// ↑ and ↓ turn the dial; everything else it leaves. +fn dial_key(d: &mut Dial, ev: &KeyEvent, _: &mut Tx) -> bool { + match ev.key { + Key::Up => d.value += 1, + Key::Down => d.value -= 1, + _ => return false, + } + true +} + +fn runtime() -> Runtime<Real> { + let playground = Playground::<Real>::new() + .story( + Story::new("Dials/Dial", Dial::default, dial) + .side_keys(|d, active, _| text(format!("{} {}", if active { "active" } else { "idle" }, d.value)).key("dial-side"), dial_key) + .trigger('f', "Fail", |d, _| d.failed = true), + ) + .story(Story::new("Dials/Plain", Dial::default, dial).side(|d, _| text(format!("plain {}", d.value)).key("plain-side"))) + .story(Story::new("Dials/Linked", Dial::default, linked).side_keys(|d, active, _| text(format!("{} {}", if active { "active" } else { "idle" }, d.value)).key("linked-side"), dial_key).trigger('e', "Press Esc", |_, play| play.press(Key::Escape))) + .side_keys( + "Meter/High", + |s, active, _| text(format!("{} {}", if active { "active" } else { "idle" }, s.level)).key("meter-side"), + |s, ev, _| (ev.key == Key::Up).then(|| s.level += 5).is_some(), + ); + let mut spec = AppSpec::new("dials", (800.0, 500.0), Real::default, real); + spec.scenes = SCENES; + App::new(spec).playground(playground).headless_runtime((800.0, 500.0), Env::new(false, 1.0)) +} + +fn press(rt: &mut Runtime<Real>, key: Key) { + rt.key(KeyEvent { key, mods: Mods::default() }); + rt.frame(1.0 / 60.0); +} + +/// What the side column's element keyed `key` says. +fn says(rt: &Runtime<Real>, key: &str) -> String { + rt.elements().into_iter().find(|e| e.key.as_deref() == Some(key)).and_then(|e| e.text).unwrap_or_default() +} + +fn dial_state(rt: &Runtime<Real>) -> (i32, bool) { + rt.playground_state::<Dial>().map(|d| (d.value, d.failed)).expect("a dial story's state") +} + +#[test] +fn the_side_view_knows_when_the_keyboard_is_on_it() { + let mut rt = runtime(); + rt.open_playground("Dials/Dial", None); + assert_eq!(says(&rt, "dial-side"), "idle 0"); + press(&mut rt, Key::Right); + assert_eq!(says(&rt, "dial-side"), "active 0", "→ puts the keyboard on it"); + press(&mut rt, Key::Escape); + assert_eq!(says(&rt, "dial-side"), "idle 0", "Esc leaves"); + assert!(rt.playground_state::<Dial>().is_some(), "and the playground stays open"); + press(&mut rt, Key::Tab); + assert_eq!(says(&rt, "dial-side"), "active 0", "so does Tab"); + press(&mut rt, Key::Tab); + assert_eq!(says(&rt, "dial-side"), "idle 0", "and Tab leaves again"); +} + +#[test] +fn its_hook_gets_keys_first_and_left_no_longer_leaves() { + let mut rt = runtime(); + rt.open_playground("dials-dial", None); + press(&mut rt, Key::Right); + press(&mut rt, Key::Up); + press(&mut rt, Key::Up); + press(&mut rt, Key::Down); + assert_eq!(dial_state(&rt), (1, false), "↑↓ are the hook's, not the side column's"); + press(&mut rt, Key::Left); + assert_eq!(says(&rt, "dial-side"), "active 1", "← stays"); + press(&mut rt, Key::Text("f".into())); + // The step it queued runs on the frame after. + rt.frame(1.0 / 60.0); + assert_eq!(dial_state(&rt), (1, true), "a key it leaves runs the trigger it's on"); +} + +/// Clicks the stage's link, which leaves focus where it is; false when it isn't showing. +fn click_link(rt: &mut Runtime<Real>) -> bool { + let Some(link) = rt.elements().into_iter().find(|e| e.key.as_deref() == Some("docs")) else { return false }; + let (x, y) = (link.rect[0] + link.rect[2] / 2.0, link.rect[1] + link.rect[3] / 2.0); + rt.pointer_move(x, y); + rt.frame(1.0 / 60.0); + rt.pointer_down(x, y); + rt.pointer_up(x, y); + rt.frame(1.0 / 60.0); + true +} + +fn on_slot(rt: &Runtime<Real>) -> bool { + rt.elements().into_iter().find(|e| e.focused).and_then(|e| e.key).is_some_and(|k| k.starts_with("playground-slot-")) +} + +#[test] +fn a_stage_link_that_keeps_the_slots_focus_leaves_it_the_keys_and_the_mark() { + let mut rt = runtime(); + rt.open_playground("Dials/Linked", None); + press(&mut rt, Key::Right); + assert_eq!(says(&rt, "linked-side"), "active 0", "→ puts the keyboard on the dial"); + assert!(click_link(&mut rt)); + assert!(rt.playground_state::<Dial>().is_some_and(|d| d.opened), "the click lands on the link"); + assert!(on_slot(&rt), "and focus stays on the slot"); + assert_eq!(says(&rt, "linked-side"), "active 0", "so the dial still looks active"); + press(&mut rt, Key::Up); + assert_eq!(dial_state(&rt).0, 1, "and ↑ turns it"); + assert_eq!(says(&rt, "linked-side"), "active 1"); +} + +#[test] +fn a_steps_key_that_blurs_the_slot_it_puts_back_keeps_the_mark() { + let mut rt = runtime(); + rt.open_playground("Dials/Linked", None); + press(&mut rt, Key::Right); + press(&mut rt, Key::Text("e".into())); + // The step it queued runs on the frame after, and its key on the one after that. + rt.frame(1.0 / 60.0); + rt.frame(1.0 / 60.0); + assert!(on_slot(&rt), "focus came back to the slot"); + assert_eq!(says(&rt, "linked-side"), "active 0", "and so did its mark"); +} + +/// What has focus, by key. +fn focused(rt: &Runtime<Real>) -> Option<String> { + rt.elements().into_iter().find(|e| e.focused).and_then(|e| e.key) +} + +/// Every sequence of real input up to `LENGTH` on "Dials/Linked", through the real dispatch, +/// checked after every event against [`dev`]: what has focus, the dial, the side's text, and +/// whether the story is still the one shown. +#[test] +fn every_input_sequence_routes_as_dev_routes_it() { + use dev::Step; + const LENGTH: u32 = 5; + const STEPS: [Step; 5] = [Step::Right, Step::Link, Step::Up, Step::Escape, Step::Tab]; + for n in 0..STEPS.len().pow(LENGTH) { + let trail: Vec<Step> = (0..LENGTH).map(|at| STEPS[n / STEPS.len().pow(at) % STEPS.len()]).collect(); + // A sequence that goes on after dev leaves the story repeats a shorter one: only the + // first of them runs, so each prefix that leaves is still checked. + let mut want = dev::Dev::new(); + let left = trail.iter().position(|&step| { + want.step(step); + !want.open + }); + if left.is_some_and(|at| trail[at + 1..].iter().any(|&s| s != STEPS[0])) { continue; } + let mut rt = runtime(); + rt.open_playground("Dials/Linked", None); + let mut want = dev::Dev::new(); + for (at, &step) in trail.iter().enumerate() { + let trail = &trail[..=at]; + match step { + Step::Right => press(&mut rt, Key::Right), + Step::Up => press(&mut rt, Key::Up), + Step::Escape => press(&mut rt, Key::Escape), + Step::Tab => press(&mut rt, Key::Tab), + Step::Link => assert!(click_link(&mut rt), "{trail:?}: the link is showing"), + } + want.step(step); + let open = rt.playground_state::<Dial>().is_some() && !says(&rt, "linked-side").is_empty(); + assert_eq!(open, want.open, "{trail:?}: whether the story is still shown"); + if !open { break; } + assert_eq!(focused(&rt).as_deref(), want.focus.key(), "{trail:?}: what has focus"); + assert_eq!(dial_state(&rt).0, want.dial, "{trail:?}: the dial"); + assert_eq!(says(&rt, "linked-side"), want.side(), "{trail:?}: the side's text"); + } + } +} + +/// origin/dev's playground focus and key routing, transcribed for the input the walk sends to +/// "Dials/Linked": `Runtime::route_key`, `playground_nav`, `filter_key`, `playground_key`, +/// `to_list`, `give_region`, `sync_region`, `sync_side_focus` and `playground_pointer_down`, +/// `Live::nav`, `Live::side_key` and `Keyboard::step`, and Tab along this playground's tab +/// order. It calls nothing in Rune. +mod dev { + #[derive(Clone, Copy, Debug, PartialEq, Eq)] + pub enum Step { + Right, + Link, + Up, + Escape, + Tab, + } + + /// What has focus: nothing, the list's filter field, the stage's link, or the story's slot. + #[derive(Clone, Copy, Debug, PartialEq, Eq)] + pub enum Focus { + None, + Filter, + Docs, + Slot, + } + + impl Focus { + pub fn key(self) -> Option<&'static str> { + match self { + Focus::None => None, + Focus::Filter => Some("playground-filter"), + Focus::Docs => Some("docs"), + Focus::Slot => Some("playground-slot-3"), + } + } + + /// The column focus is in: `sync_region`'s `under` checks. + fn region(self) -> Option<Region> { + match self { + Focus::None => None, + Focus::Filter => Some(Region::List), + Focus::Docs => Some(Region::Stage), + Focus::Slot => Some(Region::Side), + } + } + } + + #[derive(Clone, Copy, Debug, PartialEq, Eq)] + enum Region { + List, + Stage, + Side, + } + + /// `tab_order` with full keyboard access, the runtime's default: every focusable control in + /// tree order, from the filter field through the stage's link to the slot. The side's + /// controls after the slot never come up: the slot takes Tab itself. + const TAB_ORDER: [Focus; 3] = [Focus::Filter, Focus::Docs, Focus::Slot]; + + /// `Keyboard`'s fields, the runtime's focus, the dial, and whether the story is still shown. + pub struct Dev { + pub open: bool, + pub focus: Focus, + pub dial: i32, + region: Region, + slot_focused: bool, + seen: Focus, + } + + impl Dev { + pub fn new() -> Self { + Dev { open: true, focus: Focus::None, dial: 0, region: Region::List, slot_focused: false, seen: Focus::None } + } + + /// The side view: active while `Keyboard::slot_focused`. + pub fn side(&self) -> String { + format!("{} {}", if self.slot_focused { "active" } else { "idle" }, self.dial) + } + + pub fn step(&mut self, step: Step) { + match step { + // `playground_pointer_down`: a press in the stage gives it the keyboard. The + // link's click leaves focus where it is. + Step::Link => self.give_region(Region::Stage), + key => self.route_key(key), + } + // The frame after: `apply_playground` looks at focus. + self.sync_region(); + } + + /// `route_key`: `playground_nav`, then `focus_key` (Tab along the tab order), the + /// focused field's editing (the filter keeps its arrows), then `playground_key`. + fn route_key(&mut self, key: Step) { + if self.playground_nav(key) { return; } + match key { + Step::Tab => self.tab(), + Step::Escape => self.playground_key(), + _ => {} + } + } + + fn playground_nav(&mut self, key: Step) -> bool { + self.sync_region(); + if self.focus == Focus::Filter { return self.filter_key(key); } + if self.on_side_keys() { + if matches!(key, Step::Escape | Step::Tab) { + self.to_list(); + return true; + } + // `Live::side_key`: the story's hook takes ↑ (and ← stays). + if key == Step::Up { + self.dial += 1; + return true; + } + } + match (self.region, key) { + // The stage's keys are its own. + (Region::Stage, _) => false, + // `Nav::OutOfSide`. + (Region::Side, Step::Tab | Step::Escape) => { + self.to_list(); + true + } + // Here the side column has the keyboard only with focus on the slot, whose hook + // took ↑ above. + (Region::Side, Step::Up) => unreachable!("Nav::SideStep off the slot"), + (Region::Side, _) => false, + // `Nav::IntoSide`: onto the side column's first control, the slot. + (Region::List, Step::Tab | Step::Right) => { + self.set_focus(Focus::Slot); + self.give_region(Region::Side); + true + } + // `Request::Select` of the story above, "Dials/Plain". + (Region::List, Step::Up) => { + self.open = false; + true + } + // The list leaves Esc. + (Region::List, _) => false, + } + } + + /// `filter_key` with the filter empty: Esc leaves the field for the list, selecting + /// nothing; it leaves every other key here. + fn filter_key(&mut self, key: Step) -> bool { + if key != Step::Escape { return false; } + self.set_focus(Focus::None); + true + } + + /// `playground_key`: Esc nothing took gives the list the keyboard, or from the list + /// closes the playground. + fn playground_key(&mut self) { + self.sync_region(); + if self.region != Region::List { self.to_list() } else { self.open = false } + } + + /// `focus_key`'s Tab: the link text's one link is its last, so Tab leaves it. + fn tab(&mut self) { + let next = match TAB_ORDER.iter().position(|&f| f == self.focus) { + Some(i) if i + 1 < TAB_ORDER.len() => i + 1, + Some(_) => unreachable!("Tab along the tab order from the slot"), + None => 0, + }; + self.set_focus(TAB_ORDER[next]); + } + + fn on_side_keys(&self) -> bool { + self.focus == Focus::Slot + } + + /// `set_focus`, which ends in `sync_side_focus`. + fn set_focus(&mut self, focus: Focus) { + self.focus = focus; + self.slot_focused = self.on_side_keys(); + } + + fn to_list(&mut self) { + self.set_focus(Focus::None); + self.give_region(Region::List); + } + + /// `give_region`: `Moved::Give`. + fn give_region(&mut self, region: Region) { + self.region = region; + self.seen = self.focus; + } + + /// `sync_region`: `Moved::Focus` when focus moved since the last look. Focus leaving + /// every column keeps the column. + fn sync_region(&mut self) { + if self.seen == self.focus { return; } + self.seen = self.focus; + if let Some(region) = self.focus.region() { self.region = region; } + } + } +} + +#[test] +fn a_side_without_keys_keeps_the_old_keys() { + let mut rt = runtime(); + rt.open_playground("Dials/Plain", None); + press(&mut rt, Key::Right); + let focused = |rt: &Runtime<Real>| rt.elements().into_iter().find(|e| e.focused).and_then(|e| e.key); + assert!(focused(&rt).is_some_and(|k| k.starts_with("playground-trigger")), "→ goes to its first control"); + press(&mut rt, Key::Left); + assert_eq!(focused(&rt), None, "← leaves"); +} + +#[test] +fn a_scene_takes_keys_on_its_stage_state() { + let mut rt = runtime(); + rt.open_playground("meter-high", None); + press(&mut rt, Key::Right); + press(&mut rt, Key::Up); + assert_eq!(says(&rt, "meter-side"), "active 55"); + assert_eq!(rt.state.level, 0, "the real state is untouched"); +} diff --git a/app/vendor/rune/crates/rune/tests/integration/playground_stage.rs b/app/vendor/rune/crates/rune/tests/integration/playground_stage.rs new file mode 100644 index 0000000..7c16a40 --- /dev/null +++ b/app/vendor/rune/crates/rune/tests/integration/playground_stage.rs @@ -0,0 +1,138 @@ +//! The story list's counts and motion marks, and how a stage lays a story out: centred, a +//! scrolling page, or edge to edge. +use rune::{App, AppSpec, Cx, El, Env, Playground, Runtime, Stage, Story, col, el, text}; + +const SIZE: (f32, f32) = (1200.0, 700.0); +/// The stage's width: the window less the sidebar, the side column and their hairlines. +const STAGE_W: f32 = 1200.0 - 200.0 - 264.0 - 2.0; + +#[derive(Default)] +struct Pad { + rows: usize, +} + +fn pad(s: &Pad, _: &mut Cx<Pad>) -> El { + col().key("pad").w_full().children((0..s.rows).map(|_| el().h(40.0))) +} + +static SCENES: &[(&str, fn(&mut Pad))] = &[("Pad/Empty", |_| {}), ("Pad/Full", |s| s.rows = 3), ("Long/Scene", |s| s.rows = 40)]; + +#[derive(Default)] +struct Card; + +fn card(_: &Card, _: &mut Cx<Card>) -> El { + text("card").key("card") +} + +fn tall(_: &Card, _: &mut Cx<Card>) -> El { + col().key("tall").w_full().children((0..40).map(|_| el().h(40.0))) +} + +fn screen(_: &Card, _: &mut Cx<Card>) -> El { + el().key("screen") +} + +/// Scenes 0 to 2, then stories 3 to 6. +fn playground() -> Playground<Pad> { + Playground::<Pad>::new() + .trigger("Full", 'd', "Double", |s, _| s.rows *= 2) + .stage("Long/Scene", Stage::Scroll) + .story(Story::new("Cards/Plain", Card::default, card)) + .story(Story::new("Cards/Raised", Card::default, card).trigger('p', "Pop", |_, _| {})) + .story(Story::new("Cards/Tall", Card::default, tall).stage(Stage::Scroll)) + .story(Story::new("Screens/Window", Card::default, screen).stage(Stage::Fill)) +} + +fn runtime() -> Runtime<Pad> { + let mut spec = AppSpec::new("stage", SIZE, Pad::default, pad); + spec.scenes = SCENES; + App::new(spec).playground(playground()).headless_runtime(SIZE, Env::new(false, 1.0)) +} + +fn element(rt: &Runtime<Pad>, key: &str) -> Option<rune::ElementInfo> { + rt.elements().into_iter().find(|e| e.key.as_deref() == Some(key) && !e.exiting) +} + +fn rect(rt: &Runtime<Pad>, key: &str) -> [f32; 4] { + element(rt, key).unwrap_or_else(|| panic!("no {key}")).rect +} + +/// The stage's rect: the element keyed `playground-stage-<generation>`. +fn stage(rt: &Runtime<Pad>) -> [f32; 4] { + rt.elements().into_iter() + .find(|e| !e.exiting && e.key.as_deref().and_then(|k| k.strip_prefix("playground-stage-")).is_some_and(|g| g.parse::<u32>().is_ok())) + .expect("a stage") + .rect +} + +fn close(a: [f32; 4], b: [f32; 4]) -> bool { + a.iter().zip(b).all(|(a, b)| (a - b).abs() < 0.5) +} + +#[test] +fn each_header_counts_its_stories() { + let mut rt = runtime(); + rt.open_playground("Cards/Plain", None); + let count = |key: &str| element(&rt, key).and_then(|e| e.text).unwrap_or_else(|| panic!("no {key}")); + assert_eq!(count("playground-count-0"), "2", "Pad"); + assert_eq!(count("playground-count-2"), "1", "Long"); + assert_eq!(count("playground-count-3"), "3", "Cards"); + assert_eq!(count("playground-count-6"), "1", "Screens"); +} + +#[test] +fn a_folded_group_still_counts_its_stories() { + let mut rt = runtime(); + rt.open_playground("Pad/Empty", None); + let (x, y) = rt.find("playground-group-3").expect("the Cards header"); + rt.pointer_move(x, y); + rt.pointer_down(x, y); + rt.pointer_up(x, y); + rt.frame(1.0 / 60.0); + assert!(element(&rt, "playground-item-3").is_none(), "Cards folded"); + assert_eq!(element(&rt, "playground-count-3").and_then(|e| e.text).as_deref(), Some("3")); +} + +#[test] +fn only_stories_with_triggers_have_a_motion_mark() { + let mut rt = runtime(); + rt.open_playground("Cards/Plain", None); + let marked: Vec<usize> = (0..7).filter(|i| element(&rt, &format!("playground-motion-{i}")).is_some()).collect(); + assert_eq!(marked, [1, 4], "the scene with a trigger and the story with one"); +} + +#[test] +fn a_scroll_stage_starts_its_content_at_the_top_and_scrolls() { + let mut rt = runtime(); + rt.open_playground("Cards/Tall", None); + let stage = stage(&rt); + assert!(close([stage[0], stage[1], stage[2], stage[3]], [201.0, 0.0, STAGE_W, SIZE.1]), "the stage fills its room: {stage:?}"); + let top = rect(&rt, "tall"); + assert!(close(top, [stage[0] + 24.0, stage[1] + 24.0, stage[2] - 48.0, 1600.0]), "inside the margin, at its own height: {top:?}"); + // A viewport learns how far it scrolls on a frame that moves the clock. + rt.frame(1.0 / 60.0); + rt.wheel(stage[0] + stage[2] / 2.0, stage[1] + stage[3] / 2.0, -300.0); + rt.frame(1.0 / 60.0); + let scrolled = rect(&rt, "tall"); + assert!((scrolled[1] - (top[1] - 300.0)).abs() < 0.5, "the stage scrolled: {scrolled:?}"); +} + +#[test] +fn a_scene_takes_its_stage_from_the_playground() { + let mut rt = runtime(); + rt.open_playground("Long/Scene", None); + let stage = stage(&rt); + let top = rect(&rt, "pad"); + assert!((top[1] - (stage[1] + 24.0)).abs() < 0.5 && (top[3] - 1600.0).abs() < 0.5, "a scrolling page: {top:?}"); + rt.open_playground("Pad/Full", None); + assert!(close(rect(&rt, "pad"), stage), "the others stay centred, the size of the stage"); +} + +#[test] +fn a_fill_stage_gives_the_root_the_whole_stage() { + let mut rt = runtime(); + rt.open_playground("Screens/Window", None); + let stage = stage(&rt); + assert!(close(stage, [201.0, 0.0, STAGE_W, SIZE.1]), "the stage fills its room: {stage:?}"); + assert!(close(rect(&rt, "screen"), stage)); +} diff --git a/app/vendor/rune/crates/rune/tests/integration/playground_table.rs b/app/vendor/rune/crates/rune/tests/integration/playground_table.rs new file mode 100644 index 0000000..156521d --- /dev/null +++ b/app/vendor/rune/crates/rune/tests/integration/playground_table.rs @@ -0,0 +1,74 @@ +//! A story table made in a loop: each story's init, view, triggers and variants are closures +//! that capture their row, and a story opens by its slug. +use rune::playground::slug; +use rune::{App, AppSpec, Cx, El, Env, Playground, Runtime, Story, Tx, text}; + +#[derive(Default)] +struct Real; + +fn real(_: &Real, _: &mut Cx<Real>) -> El { + text("the app") +} + +struct Counter { + n: u32, +} + +/// A row of the app's story table. +struct Row { + path: &'static str, + start: u32, + step: u32, + label: String, +} + +fn table() -> Vec<Row> { + (0..50u32) + .map(|i| Row { + path: Box::leak(format!("Group {}/Story {i}", i / 10).into_boxed_str()), + start: i * 10, + step: i + 1, + label: format!("row {i}"), + }) + .collect() +} + +fn runtime() -> Runtime<Real> { + let mut playground = Playground::<Real>::new(); + for Row { path, start, step, label } in table() { + let story = Story::new(path, move || Counter { n: start }, move |c, _| text(format!("{label} {}", c.n)).key("counter")) + .trigger('a', "Add", move |c, _| c.n += step) + .trigger('l', "Add later", move |_, play| play.after(0.5, move |c: &mut Counter, _| c.n += step)) + .trigger_tx('z', "Zero", |c: &mut Counter, tx: &mut Tx| { + c.n = 0; + tx.instant(); + }) + .variant("As listed", |_| {}) + .variant("Doubled", move |c| c.n = start * 2); + playground = playground.story(story); + } + App::new(AppSpec::new("table", (800.0, 500.0), Real::default, real)).playground(playground).headless_runtime((800.0, 500.0), Env::new(false, 1.0)) +} + +fn shows(rt: &Runtime<Real>) -> String { + rt.playground_element("counter").and_then(|e| e.text).unwrap_or_default() +} + +#[test] +fn fifty_stories_from_a_table_each_with_its_own_row() { + let mut rt = runtime(); + assert_eq!(slug("Group 3/Story 37"), "group-3-story-37"); + rt.open_playground("group-3-story-37", None); + assert_eq!(shows(&rt), "row 37 370", "its init and view captured its row"); + rt.playground_trigger('a'); + assert_eq!(rt.playground_state::<Counter>().map(|c| c.n), Some(408), "and its trigger, the row's step"); + rt.playground_trigger('l'); + for _ in 0..40 { + rt.frame(1.0 / 60.0); + } + assert_eq!(rt.playground_state::<Counter>().map(|c| c.n), Some(446), "a step it queued captured the row too"); + rt.playground_trigger('z'); + assert_eq!(rt.playground_state::<Counter>().map(|c| c.n), Some(0), "a trigger that takes just the Tx"); + rt.open_playground("group-0-story-4", Some("Doubled")); + assert_eq!(shows(&rt), "row 4 80", "a variant that captured its row"); +} diff --git a/app/vendor/rune/crates/rune/tests/integration/playground_testing.rs b/app/vendor/rune/crates/rune/tests/integration/playground_testing.rs new file mode 100644 index 0000000..ac22638 --- /dev/null +++ b/app/vendor/rune/crates/rune/tests/integration/playground_testing.rs @@ -0,0 +1,248 @@ +//! An app's tests driving its playground headless: open a story, run its triggers and their +//! `Play::after` steps on the logical clock, and read the stage's state and elements. +use rune::{App, AppSpec, Cx, El, Env, Play, Playground, Runtime, Story, Tx, col, el, text}; + +const DT: f64 = 1.0 / 60.0; + +#[derive(Default)] +struct Pad { + count: u32, +} + +fn pad(s: &Pad, _: &mut Cx<Pad>) -> El { + col().w_full().h_full() + .child(text(format!("count {}", s.count)).key("count")) + .child(el().key("inc").size(40.0, 20.0).on_press(|s: &mut Pad| s.count += 1)) +} + +static SCENES: &[(&str, fn(&mut Pad))] = &[("Pad/Empty", |_| {}), ("Pad/Full", |s| s.count = 10)]; + +#[derive(Default)] +struct Upload { + bytes: u32, + phase: &'static str, +} + +fn upload(u: &Upload, _: &mut Cx<Upload>) -> El { + text(format!("{} {}", u.phase, u.bytes)).key("upload") +} + +fn upload_story() -> Story<Upload> { + Story::new("Progress/Upload", Upload::default, upload) + .trigger('r', "Run", |u, play| { + u.phase = "sending"; + play.after(0.5, |u, play| { + u.phase = "sent"; + play.after(0.25, |u, _| u.phase = "done"); + }); + }) + .trigger('f', "Fail", |u, _| u.phase = "failed") + .variant("Small", |u| u.bytes = 10) + .variant("Large", |u| u.bytes = 1_000_000) +} + +fn playground() -> Playground<Pad> { + Playground::<Pad>::new() + .story(upload_story()) + .story(Story::from_real("Progress/Mine", |real: &Pad| Upload { bytes: real.count, phase: "mine" }, upload)) + .trigger("Full", 'd', "Double", |s, _| s.count *= 2) + .variant("Full", "Few", |s| s.count = 3) + .variant("Full", "Many", |s| s.count = 99) +} + +fn runtime(playground: Playground<Pad>) -> Runtime<Pad> { + let mut spec = AppSpec::new("pad", (800.0, 500.0), Pad::default, pad); + spec.scenes = SCENES; + App::new(spec).playground(playground).headless_runtime((800.0, 500.0), Env::new(false, 1.0)) +} + +/// Frames of `DT` until `secs` more have passed on the logical clock. +fn advance(rt: &mut Runtime<Pad>, secs: f64) { + for _ in 0..(secs / DT).round() as usize { + rt.frame(DT); + } +} + +fn phase(rt: &Runtime<Pad>) -> &'static str { + rt.playground_state::<Upload>().expect("the upload story's state").phase +} + +#[test] +fn a_story_opens_by_path_and_its_r_trigger_runs_at_once() { + let mut rt = runtime(playground()); + assert!(rt.playground_state::<Upload>().is_none(), "closed until opened"); + rt.open_playground("Progress/Upload", None); + assert_eq!(phase(&rt), "sending"); + assert_eq!(rt.playground_element("upload").and_then(|e| e.text).as_deref(), Some("sending 10"), "on its first variant"); + assert!(rt.playground_state::<Pad>().is_none(), "the stage's type is the story's own"); +} + +#[test] +fn play_after_steps_run_on_the_logical_clock() { + let mut rt = runtime(playground()); + rt.open_playground("Upload", None); + advance(&mut rt, 0.4); + assert_eq!(phase(&rt), "sending"); + advance(&mut rt, 0.2); + assert_eq!(phase(&rt), "sent", "half a second after the trigger"); + advance(&mut rt, 0.1); + assert_eq!(phase(&rt), "sent"); + advance(&mut rt, 0.1); + assert_eq!(phase(&rt), "done", "a quarter second after the step that queued it"); +} + +#[test] +fn a_trigger_runs_by_its_key_and_r_replays() { + let mut rt = runtime(playground()); + rt.open_playground("Progress/Upload", None); + advance(&mut rt, 1.0); + assert_eq!(phase(&rt), "done"); + rt.playground_trigger('f'); + assert_eq!(phase(&rt), "failed"); + rt.playground_trigger('r'); + assert_eq!(phase(&rt), "sending", "the stage made again, its 'r' run"); + advance(&mut rt, 0.6); + assert_eq!(phase(&rt), "sent", "and its steps queued again"); +} + +#[test] +fn a_scene_trigger_acts_on_the_stage_and_never_the_real_state() { + let mut rt = runtime(playground()); + rt.state.count = 4; + rt.open_playground("Pad/Full", None); + rt.playground_trigger('d'); + assert_eq!(rt.playground_state::<Pad>().map(|s| s.count), Some(6), "on its first variant, Few"); + assert_eq!(rt.playground_element("count").and_then(|e| e.text).as_deref(), Some("count 6")); + assert_eq!(rt.state.count, 4, "the real state is untouched"); +} + +#[test] +fn a_variant_opens_with_its_own_setup() { + let mut rt = runtime(playground()); + rt.open_playground("Progress/Upload", Some("Large")); + assert_eq!(rt.playground_state::<Upload>().map(|u| u.bytes), Some(1_000_000)); + rt.open_playground("Progress/Upload", Some("1")); + assert_eq!(rt.playground_state::<Upload>().map(|u| u.bytes), Some(10), "by number, and made again"); + rt.open_playground("Full", Some("many")); + assert_eq!(rt.playground_state::<Pad>().map(|s| s.count), Some(99), "the scene fn, then the variant's"); +} + +#[test] +fn a_story_from_real_reads_the_real_state_and_leaves_it() { + let mut rt = runtime(playground()); + rt.state.count = 7; + rt.open_playground("Progress/Mine", None); + assert_eq!(rt.playground_state::<Upload>().map(|u| u.bytes), Some(7)); + assert_eq!(rt.state.count, 7); +} + +fn compare(stage: &Pad, real: &Pad, _: &mut Cx<Pad>) -> El { + col() + .child(text(format!("stage {} real {}", stage.count, real.count)).key("compare")) + .child(el().key("keep").size(40.0, 20.0).on_press_tx(|_: &mut Pad, tx: &mut Tx| tx.keep_playground())) +} + +#[test] +fn only_keep_from_a_side_real_control_writes_the_real_state() { + let playground = playground().keep(|stage, real| real.count = stage.count).side_real("Full", compare); + let mut rt = runtime(playground); + rt.open_playground("Full", None); + rt.playground_trigger('d'); + rt.frame(DT); + assert_eq!(rt.state.count, 0, "the trigger changed the stage only"); + assert!(rt.playground_element("compare").is_none(), "the side column isn't the stage"); + let (x, y) = rt.find("keep").expect("the side column's control"); + rt.pointer_down(x, y); + rt.pointer_up(x, y); + rt.frame(DT); + assert_eq!(rt.state.count, 6, "kept"); + let compare = rt.elements().into_iter().find(|e| e.key.as_deref() == Some("compare")).and_then(|e| e.text); + assert_eq!(compare.as_deref(), Some("stage 6 real 6")); +} + +#[derive(Default)] +struct Pulse { + beats: u32, + settled: bool, +} + +fn pulse_view(p: &Pulse, _: &mut Cx<Pulse>) -> El { + text(format!("beats {}", p.beats)).key("pulse") +} + +/// A loop: each beat queues the next. +fn beat(p: &mut Pulse, play: &mut Play<'_, Pulse>) { + p.beats += 1; + play.after(0.25, beat); +} + +fn pulse() -> Story<Pulse> { + Story::new("Motion/Pulse", Pulse::default, pulse_view) + .trigger('r', "Pulse", beat) + .trigger('s', "Settle", |_, play| { + play.clear(); + play.after(0.2, |p, _| p.settled = true); + }) +} + +#[test] +fn a_trigger_that_clears_stops_the_loop_and_runs_only_its_own_steps() { + let mut rt = runtime(playground().story(pulse())); + rt.open_playground("Pulse", None); + advance(&mut rt, 1.1); + let beats = |rt: &Runtime<Pad>| rt.playground_state::<Pulse>().map(|p| (p.beats, p.settled)); + assert_eq!(beats(&rt), Some((5, false)), "a beat every quarter second from the open"); + rt.playground_trigger('s'); + assert_eq!(beats(&rt), Some((5, false)), "clearing leaves the state alone"); + advance(&mut rt, 0.1); + assert_eq!(beats(&rt), Some((5, false)), "the loop's next beat is gone"); + advance(&mut rt, 0.15); + assert_eq!(beats(&rt), Some((5, true)), "the step queued after the clear ran"); + advance(&mut rt, 1.0); + assert_eq!(beats(&rt), Some((5, true))); + assert_eq!(rt.playground_element("pulse").and_then(|e| e.text).as_deref(), Some("beats 5")); +} + +#[derive(Default)] +struct Glow { + lit: bool, +} + +#[test] +fn replays_land_their_steps_on_the_same_frame_every_time() { + let glow = Story::new("Motion/Glow", Glow::default, |g: &Glow, _: &mut Cx<Glow>| text(if g.lit { "lit" } else { "dark" }).key("glow")) + .trigger('r', "Glow", |g, play| { + g.lit = false; + play.after(0.4, |g, _| g.lit = true); + }); + let mut rt = runtime(playground().story(glow)); + rt.open_playground("Motion/Glow", None); + let dt = 1.0 / 120.0; + let mut frames = Vec::new(); + for _ in 0..3 { + rt.playground_trigger('r'); + let lit_on = (1..=120).find(|_| { + rt.frame(dt); + rt.playground_state::<Glow>().is_some_and(|g| g.lit) + }); + frames.push(lit_on); + for _ in 0..(120 - lit_on.unwrap_or(120)) { + rt.frame(dt); + } + } + assert_eq!(frames, vec![Some(48); 3], "0.4 s at 120 Hz is frame 48 on every replay"); +} + +#[test] +#[should_panic(expected = "no story \"Nope\" in the playground")] +fn an_unknown_story_panics_with_the_list() { + runtime(playground()).open_playground("Nope", None); +} + +#[test] +#[should_panic(expected = "has no trigger on 'z'")] +fn an_unknown_trigger_panics_with_the_keys() { + let mut rt = runtime(playground()); + rt.open_playground("Progress/Upload", None); + rt.playground_trigger('z'); +} diff --git a/app/vendor/rune/crates/rune/tests/integration/playground_tree.rs b/app/vendor/rune/crates/rune/tests/integration/playground_tree.rs new file mode 100644 index 0000000..2212313 --- /dev/null +++ b/app/vendor/rune/crates/rune/tests/integration/playground_tree.rs @@ -0,0 +1,247 @@ +//! The story list as a tree, nested by each story's path, and the keyboard in one column at a +//! time: the list, the stage or the side column. +use std::cell::RefCell; +use std::rc::Rc; + +use rune::{App, AppSpec, Cx, El, ElementInfo, Env, Key, KeyEvent, Mods, Playground, Runtime, Story, Tx, text}; + +#[derive(Default)] +struct Real; + +fn real(_: &Real, _: &mut Cx<Real>) -> El { + text("the app") +} + +#[derive(Default)] +struct Card { + variant: u8, + knob: String, +} + +fn card(c: &Card, _: &mut Cx<Card>) -> El { + text(format!("card {}", c.variant)).key("card").on_press(|_: &mut Card| {}) +} + +/// Digits turn the knob; it leaves everything else. +fn knob_key(c: &mut Card, ev: &KeyEvent, _: &mut Tx) -> bool { + match &ev.key { + Key::Text(t) if t.chars().all(|c| c.is_ascii_digit()) => c.knob.push_str(t), + _ => return false, + } + true +} + +fn playground() -> Playground<Real> { + Playground::<Real>::new() + .story(Story::new("Sidebar/Rows/Plain", Card::default, card).variant("One", |c| c.variant = 1).variant("Two", |c| c.variant = 2)) + .story(Story::new("Sidebar/Rows/Pinned", Card::default, card)) + .story(Story::new("Sidebar/Filter buttons/Compact", Card::default, card)) + .story(Story::new("Sidebar/Filter buttons/Wide", Card::default, card)) + .story(Story::new("Sidebar/Header", Card::default, card)) + .story(Story::new("Dock/Icons", Card::default, card).side_keys(|c, active, _| text(format!("{} {}", if active { "on" } else { "off" }, c.knob)).key("knob"), knob_key)) +} + +fn runtime(playground: Playground<Real>, open: &str) -> Runtime<Real> { + let mut rt = App::new(AppSpec::new("tree", (900.0, 600.0), Real::default, real)).playground(playground).headless_runtime((900.0, 600.0), Env::new(false, 1.0)); + rt.open_playground(open, None); + rt +} + +fn press(rt: &mut Runtime<Real>, key: Key) { + rt.key(KeyEvent { key, mods: Mods::default() }); + rt.frame(1.0 / 60.0); +} + +fn typed(rt: &mut Runtime<Real>, s: &str) { + press(rt, Key::Text(s.into())); +} + +fn element(rt: &Runtime<Real>, key: &str) -> Option<ElementInfo> { + rt.elements().into_iter().find(|e| e.key.as_deref() == Some(key) && !e.exiting) +} + +fn shown(rt: &Runtime<Real>, key: &str) -> bool { + element(rt, key).is_some() +} + +fn says(rt: &Runtime<Real>, key: &str) -> String { + element(rt, key).and_then(|e| e.text).unwrap_or_else(|| panic!("no {key}")).replace('\u{a0}', " ") +} + +/// The first text inside the element keyed `key`, and where it starts. +fn label(rt: &Runtime<Real>, key: &str) -> (String, f32) { + let all = rt.elements(); + let at = all.iter().position(|e| e.key.as_deref() == Some(key) && !e.exiting).unwrap_or_else(|| panic!("no {key}")); + let inside = |e: &ElementInfo| std::iter::successors(e.parent, |&p| all[p].parent).any(|p| p == at); + let e = all.iter().find(|e| e.text.is_some() && inside(e)).expect("a label"); + (e.text.clone().unwrap(), e.rect[0]) +} + +/// The open story's name, as the side column titles it. +fn title(rt: &Runtime<Real>) -> String { + let all = rt.elements(); + let at = all.iter().position(|e| e.key.as_deref() == Some("playground-title")).expect("a title"); + all.iter().filter(|e| e.parent == Some(at)).filter_map(|e| e.text.clone()).nth(1).unwrap_or_default() +} + +fn tap(rt: &mut Runtime<Real>, key: &str) { + let (x, y) = rt.find(key).unwrap_or_else(|| panic!("no {key}")); + tap_at(rt, x, y); +} + +fn tap_at(rt: &mut Runtime<Real>, x: f32, y: f32) { + rt.pointer_move(x, y); + rt.pointer_down(x, y); + rt.pointer_up(x, y); + rt.frame(1.0 / 60.0); +} + +fn focused(rt: &Runtime<Real>) -> Option<String> { + rt.elements().into_iter().find(|e| e.focused).and_then(|e| e.key) +} + +fn card_state(rt: &Runtime<Real>) -> (u8, String) { + rt.playground_state::<Card>().map(|c| (c.variant, c.knob.clone())).expect("a card story") +} + +const LIST_HINT: &str = "↑↓ stories · ←→ groups · / filter · Tab controls · Esc back"; + +#[test] +fn a_path_nests_groups_one_level_per_slash() { + let rt = runtime(playground(), "Sidebar/Filter buttons/Compact"); + let order = ["playground-group-0", "playground-group-0-1", "playground-item-0", "playground-item-1", "playground-group-2-1", "playground-item-2", "playground-item-3", "playground-item-4", "playground-group-5", "playground-item-5"]; + let ys: Vec<f32> = order.iter().map(|k| element(&rt, k).unwrap_or_else(|| panic!("no {k}")).rect[1]).collect(); + assert!(ys.windows(2).all(|w| w[0] < w[1]), "rows in tree order: {ys:?}"); + assert_eq!(label(&rt, "playground-group-2-1").0, "Filter buttons", "a group inside another shows its own name"); + let (sidebar, rows, compact, header) = (label(&rt, "playground-group-0").1, label(&rt, "playground-group-0-1").1, label(&rt, "playground-item-2").1, label(&rt, "playground-item-4").1); + assert_eq!(header, sidebar, "a story lines up with its group's name"); + assert_eq!((rows - sidebar, compact - header), (12.0, 12.0), "each level indents 12 pt"); + assert_eq!([says(&rt, "playground-count-0"), says(&rt, "playground-count-0-1"), says(&rt, "playground-count-2-1"), says(&rt, "playground-count-5")], ["5", "2", "2", "1"], "a header counts every story inside it"); + assert_eq!(label(&rt, "playground-title").0, "Sidebar › Filter buttons"); + assert_eq!(title(&rt), "Compact"); +} + +#[test] +fn every_level_folds_and_a_fold_inside_one_outlasts_its_parents() { + let mut rt = runtime(playground(), "Dock/Icons"); + tap(&mut rt, "playground-group-2-1"); + assert!(!shown(&rt, "playground-item-2") && !shown(&rt, "playground-item-3"), "Filter buttons folds"); + assert!(shown(&rt, "playground-item-0") && shown(&rt, "playground-item-4"), "the rest of Sidebar doesn't"); + tap(&mut rt, "playground-group-0"); + assert!(!shown(&rt, "playground-group-0-1") && !shown(&rt, "playground-group-2-1") && !shown(&rt, "playground-item-4"), "Sidebar folds what's inside it"); + assert!(shown(&rt, "playground-item-5"), "Dock stays"); + tap(&mut rt, "playground-group-0"); + assert!(shown(&rt, "playground-item-0") && shown(&rt, "playground-group-2-1")); + assert!(!shown(&rt, "playground-item-2"), "Filter buttons is still folded"); +} + +#[test] +fn folds_keep_groups_at_any_level_by_their_path() { + let saved: Rc<RefCell<Vec<Vec<String>>>> = Rc::default(); + let saves = saved.clone(); + let playground = playground().folds(|| vec!["Sidebar/Filter buttons".to_owned(), "Dock".to_owned()], move |groups| saves.borrow_mut().push(groups.to_vec())); + let mut rt = runtime(playground, "Sidebar/Header"); + assert!(!shown(&rt, "playground-item-2") && shown(&rt, "playground-group-2-1"), "a nested group loads folded"); + assert!(!shown(&rt, "playground-item-5"), "and a top one, by name as before"); + tap(&mut rt, "playground-group-0-1"); + assert_eq!(saved.borrow().last().cloned(), Some(vec!["Sidebar/Filter buttons".to_owned(), "Dock".to_owned(), "Sidebar/Rows".to_owned()])); + rt.open_playground("Sidebar/Filter buttons/Wide", None); + assert!(shown(&rt, "playground-item-3"), "opening a story unfolds the groups around it"); + assert_eq!(saved.borrow().last().cloned(), Some(vec!["Dock".to_owned(), "Sidebar/Rows".to_owned()])); +} + +#[test] +fn arrows_walk_into_and_out_of_nested_groups() { + let mut rt = runtime(playground(), "Sidebar/Filter buttons/Compact"); + press(&mut rt, Key::Left); + press(&mut rt, Key::Left); + assert!(!shown(&rt, "playground-item-2"), "← goes to the story's group, then folds it"); + press(&mut rt, Key::Left); + press(&mut rt, Key::Left); + assert!(!shown(&rt, "playground-group-0-1"), "then up to the group around it, and folds that"); + press(&mut rt, Key::Left); + assert!(!shown(&rt, "playground-group-0-1"), "at the top, ← stays"); + press(&mut rt, Key::Right); + assert!(shown(&rt, "playground-group-0-1") && !shown(&rt, "playground-item-2"), "→ unfolds one level"); + press(&mut rt, Key::Right); + press(&mut rt, Key::Down); + assert_eq!(title(&rt), "Plain", "→ steps into the group: Rows, then its first story"); + press(&mut rt, Key::Down); + press(&mut rt, Key::Down); + press(&mut rt, Key::Right); + assert!(shown(&rt, "playground-item-2"), "→ on a folded header unfolds it"); + press(&mut rt, Key::Down); + assert_eq!(title(&rt), "Compact"); + press(&mut rt, Key::Down); + press(&mut rt, Key::Down); + assert_eq!(title(&rt), "Header", "down past a subgroup to the stories beside it"); +} + +#[test] +fn the_filter_keeps_matches_and_the_groups_above_them() { + let mut rt = runtime(playground(), "Sidebar/Rows/Plain"); + typed(&mut rt, "/"); + assert_eq!(focused(&rt).as_deref(), Some("playground-filter"), "/ focuses the filter"); + typed(&mut rt, "filter wi"); + assert!(shown(&rt, "playground-group-0") && shown(&rt, "playground-group-2-1") && shown(&rt, "playground-item-3")); + assert!(!shown(&rt, "playground-item-0") && !shown(&rt, "playground-item-2") && !shown(&rt, "playground-group-5"), "the rest goes"); + assert_eq!(says(&rt, "playground-count-0"), "1", "counts count matches"); + press(&mut rt, Key::Enter); + assert_eq!((title(&rt), focused(&rt)), ("Wide".to_owned(), None), "Return opens the first match and gives the list the keyboard"); + typed(&mut rt, "/"); + press(&mut rt, Key::Escape); + assert!(shown(&rt, "playground-item-0"), "Esc empties it"); +} + +#[test] +fn the_keyboard_moves_from_the_list_to_the_side_column_and_back() { + let mut rt = runtime(playground(), "Sidebar/Rows/Plain"); + assert_eq!(says(&rt, "playground-hint"), LIST_HINT); + typed(&mut rt, "2"); + assert_eq!(card_state(&rt).0, 1, "from the list, a digit isn't a variant"); + press(&mut rt, Key::Tab); + assert_eq!(says(&rt, "playground-hint"), "↑↓ controls · 1–2 variants · Esc stories"); + assert_eq!(focused(&rt).as_deref(), Some("playground-variant-0")); + typed(&mut rt, "2"); + assert_eq!(card_state(&rt).0, 2, "in the side column it is"); + press(&mut rt, Key::Escape); + assert_eq!((says(&rt, "playground-hint"), focused(&rt)), (LIST_HINT.to_owned(), None), "Esc goes back to the list"); + press(&mut rt, Key::Down); + assert_eq!(title(&rt), "Pinned", "whose arrows work again"); + press(&mut rt, Key::Right); + assert!(says(&rt, "playground-hint").starts_with("↑↓ controls"), "→ from a story goes over too"); +} + +#[test] +fn side_keys_hear_only_the_side_column() { + let mut rt = runtime(playground(), "Dock/Icons"); + typed(&mut rt, "3"); + assert_eq!(card_state(&rt).1, "", "the list has the keyboard, so the knob hears nothing"); + press(&mut rt, Key::Right); + typed(&mut rt, "3"); + assert_eq!(says(&rt, "knob"), "on 3"); + press(&mut rt, Key::Escape); + typed(&mut rt, "4"); + assert_eq!(says(&rt, "knob"), "off 3"); +} + +#[test] +fn a_click_gives_its_column_the_keyboard() { + let mut rt = runtime(playground(), "Sidebar/Rows/Plain"); + tap(&mut rt, "card"); + assert_eq!(says(&rt, "playground-hint"), "Keys go to the story · Esc stories"); + assert!(shown(&rt, "playground-stage-ring"), "a ring shows the stage has it"); + press(&mut rt, Key::Down); + typed(&mut rt, "j"); + assert_eq!(title(&rt), "Plain", "the list's keys aren't the stage's"); + let side = element(&rt, "playground-side").unwrap().rect; + tap_at(&mut rt, side[0] + side[2] * 0.5, side[1] + side[3] * 0.6); + assert!(says(&rt, "playground-hint").starts_with("↑↓ controls"), "a click on the side column's background takes it there"); + assert!(!shown(&rt, "playground-stage-ring")); + typed(&mut rt, "2"); + assert_eq!(card_state(&rt).0, 2); + tap(&mut rt, "playground-item-1"); + assert_eq!((says(&rt, "playground-hint"), title(&rt)), (LIST_HINT.to_owned(), "Pinned".to_owned())); + press(&mut rt, Key::Escape); + assert!(rt.playground_state::<Card>().is_none(), "Esc from the list goes back to the app"); +} diff --git a/app/vendor/rune/crates/rune/tests/integration/pose_hit.rs b/app/vendor/rune/crates/rune/tests/integration/pose_hit.rs new file mode 100644 index 0000000..a4a93ea --- /dev/null +++ b/app/vendor/rune/crates/rune/tests/integration/pose_hit.rs @@ -0,0 +1,321 @@ +//! `Runtime::presented_pose` and the moving flag cover shadow and rotation springs; +//! Picking shares press geometry, but also finds elements without handlers. +use rune::{Color, Cx, El, Env, Runtime, Shadow, Spring, col, el}; +use std::f32::consts::FRAC_PI_4; + +fn moving<T>(rt: &Runtime<T>, key: &str) -> bool { + rt.elements().into_iter().find(|e| e.key.as_deref() == Some(key)).unwrap().moving +} + +fn settle<T>(rt: &mut Runtime<T>) { + for _ in 0..120 { + rt.frame(1.0 / 60.0); + } +} + +fn sh(y: f32) -> Shadow { + Shadow { x: 0.0, y, blur: 8.0, spread: 0.0, color: Color::BLACK.alpha(0.3), inset: false } +} + +fn card(on: &bool, _: &mut Cx<bool>) -> El { + let shadow = sh(if *on { 12.0 } else { 2.0 }); + col().w_full().h_full().items_start().padding(50.0).child( + el().key("a").size(100.0, 40.0).fill(Color::WHITE).motion(Spring::new(0.3, 0.0)).box_shadow(shadow), + ) +} + +#[test] +fn a_shadow_only_step_reports_moving_until_it_lands() { + let mut rt = Runtime::new(false, card, (200.0, 200.0), Env::new(true, 1.0)); + rt.frame(0.0); + assert!(!moving(&rt, "a")); + assert_eq!(rt.presented_pose("a").unwrap().shadows()[0].y, 2.0); + rt.update(|s, _| *s = true); + rt.frame(1.0 / 60.0); + assert!(moving(&rt, "a"), "the shadow's y is springing"); + let pose = rt.presented_pose("a").unwrap(); + assert!(pose.moving()); + let y = pose.shadows()[0].y; + assert!(y > 2.0 && y < 12.0, "mid-spring y: {y}"); + settle(&mut rt); + assert!(!moving(&rt, "a")); + let pose = rt.presented_pose("a").unwrap(); + assert!(!pose.moving()); + assert_eq!(pose.shadows()[0].y, 12.0); +} + +#[test] +fn a_rotation_only_step_reports_moving_until_it_lands() { + fn view(on: &bool, _: &mut Cx<bool>) -> El { + col().w_full().h_full().items_start().padding(50.0).child( + el().key("a").size(100.0, 40.0).fill(Color::WHITE).motion(Spring::new(0.3, 0.0)) + .rotate(if *on { 1.0 } else { 0.0 }), + ) + } + let mut rt = Runtime::new(false, view, (200.0, 200.0), Env::new(true, 1.0)); + rt.frame(0.0); + assert!(!moving(&rt, "a")); + rt.update(|s, _| *s = true); + rt.frame(1.0 / 60.0); + assert!(moving(&rt, "a")); + let r = rt.presented_pose("a").unwrap().rotation(); + assert!(r > 0.0 && r < 1.0, "mid-spring rotation: {r}"); + settle(&mut rt); + assert!(!moving(&rt, "a")); + let pose = rt.presented_pose("a").unwrap(); + assert!((pose.rotation() - 1.0).abs() < 1e-3); + assert!(!pose.moving()); +} + +#[derive(Default)] +struct Hits(Vec<&'static str>); + +fn bar(_: &Hits, _: &mut Cx<Hits>) -> El { + col().w_full().h_full().items_start().padding(50.0) + .on_press(|s: &mut Hits| s.0.push("bg")) + .child( + // 100x20 about (100, 60), turned 45°. + el().key("bar").size(100.0, 20.0).fill(Color::WHITE).rotate(FRAC_PI_4) + .on_press(|s: &mut Hits| s.0.push("bar")) + .child(el().key("inner").size(10.0, 10.0)), + ) +} + +fn key_at(rt: &Runtime<Hits>, x: f32, y: f32) -> Option<String> { + rt.element_at(x, y).and_then(|p| p.key().map(str::to_owned)) +} + +#[test] +fn element_at_follows_the_turned_box_and_agrees_with_presses() { + let mut rt = Runtime::new(Hits::default(), bar, (200.0, 200.0), Env::new(true, 1.0)); + rt.frame(0.0); + // In the upright layout box [50..150, 50..70]; off the 45° diagonal. + assert_ne!(key_at(&rt, 60.0, 52.0).as_deref(), Some("bar")); + assert!(!rt.contains("bar", 60.0, 52.0)); + // On the diagonal, outside the upright box. + assert_eq!(key_at(&rt, 120.0, 80.0).as_deref(), Some("bar")); + assert!(rt.contains("bar", 120.0, 80.0)); + // In the upright bounding box, outside the turned rect. + assert!(!rt.contains("bar", 130.0, 30.0)); + assert!(rt.element_at(130.0, 30.0).unwrap().key().is_none(), "the background column"); + // A child with no handlers is found. + assert_eq!(key_at(&rt, 71.7, 24.6).as_deref(), Some("inner")); + assert_eq!(rt.element_at(500.0, 500.0), None); + + for (x, y) in [(60.0, 52.0), (120.0, 80.0), (130.0, 30.0), (80.0, 40.0), (140.0, 90.0), (71.7, 24.6)] { + let picked_bar = matches!(key_at(&rt, x, y).as_deref(), Some("bar" | "inner")); + rt.state.0.clear(); + rt.pointer_move(x, y); + rt.pointer_down(x, y); + rt.pointer_up(x, y); + rt.frame(0.0); + assert_eq!(rt.state.0 == ["bar"], picked_bar, "({x}, {y}): press {:?}", rt.state.0); + } +} + +#[test] +fn a_canvas_handler_picks_its_last_presented_children_before_rebuilding() { + #[derive(Default)] + struct Canvas { point: (f32, f32), picked: Option<String>, hide: bool } + fn view(s: &Canvas, _: &mut Cx<Canvas>) -> El { + el().w_full().h_full() + .child(col().key("canvas").w_full().h_full().items_start().padding(50.0) + .on_pointer_move_local(|s: &mut Canvas, p, _| s.point = (p.window_x, p.window_y)) + .on_press_tx(|s: &mut Canvas, tx| { + s.hide = true; + tx.element_at_in("canvas", s.point.0, s.point.1, |s: &mut Canvas, p, tx| { + s.picked = p.and_then(|p| p.key().map(str::to_owned)); + tx.instant(); + }); + }) + .children((!s.hide).then(|| el().key("bar").size(100.0, 20.0).rotate(FRAC_PI_4)))) + // This paints last, but has no input handlers. Scoped picking ignores it. + .child(el().key("overlay").w_full().h_full().absolute(0.0, 0.0)) + } + let mut rt = Runtime::new(Canvas::default(), view, (200.0, 200.0), Env::new(true, 1.0)); + rt.frame(0.0); + assert_eq!(rt.element_at(120.0, 80.0).unwrap().key(), Some("overlay")); + assert!(rt.element_at_in("absent", 120.0, 80.0).is_none()); + rt.pointer_move(120.0, 80.0); + rt.frame(0.0); + rt.pointer_down(120.0, 80.0); + rt.pointer_up(120.0, 80.0); + rt.frame(0.0); + assert_eq!(rt.state.picked.as_deref(), Some("bar")); + assert!(!rt.contains("canvas/bar", 120.0, 80.0)); +} + +#[test] +fn picking_uses_raise_cache_scale_origin_offset_and_ancestor_clip() { + fn view(_: &(), _: &mut Cx<()>) -> El { + el().w_full().h_full() + .child(col().key("clip").size(100.0, 100.0).items_start().clip_rounded(0.0) + .child(el().key("raised").size(80.0, 40.0).scale(2.0).origin(0.0, 0.0) + .offset(20.0, 20.0).raise().cache())) + .child(el().key("later").size(100.0, 100.0).absolute(0.0, 0.0)) + .child(el().key("hidden").w_full().h_full().opacity(0.0).absolute(0.0, 0.0)) + } + let mut rt = Runtime::new((), view, (300.0, 300.0), Env::new(true, 2.0)); + rt.frame(0.0); + assert_eq!(rt.element_at(90.0, 50.0).unwrap().key(), Some("raised")); + assert!(!rt.contains("raised", 110.0, 50.0), "ancestor clip cuts the scaled child"); + assert!(!rt.contains("hidden", 50.0, 50.0)); + assert!(rt.contains("raised", 30.0, 30.0), "no fill is still pickable geometry"); +} + +#[test] +fn a_shadow_colour_only_step_settles() { + fn view(on: &bool, _: &mut Cx<bool>) -> El { + el().key("a").size(40.0, 40.0).motion(Spring::new(0.3, 0.0)) + .box_shadow(Shadow { color: if *on { Color::WHITE } else { Color::BLACK }, ..sh(2.0) }) + } + let mut rt = Runtime::new(false, view, (100.0, 100.0), Env::new(true, 1.0)); + rt.frame(0.0); + rt.update(|s, _| *s = true); + rt.frame(1.0 / 60.0); + assert!(moving(&rt, "a")); + assert_ne!(rt.presented_pose("a").unwrap().shadows()[0].color, Color::WHITE); + settle(&mut rt); + assert!(!moving(&rt, "a")); + assert!(!rt.presented_pose("a").unwrap().moving()); +} + +#[test] +fn an_icon_turn_only_step_settles() { + fn view(on: &bool, _: &mut Cx<bool>) -> El { + static DOT: rune::Icon = rune::Icon { name: "dot", view: 24.0, body: "<circle cx=\"12\" cy=\"12\" r=\"8\"/>" }; + rune::icon(&DOT, 40.0).key("a").motion(Spring::new(0.3, 0.0)) + .icon_rotation(if *on { 1.0 } else { 0.0 }) + } + let mut rt = Runtime::new(false, view, (100.0, 100.0), Env::new(true, 1.0)); + rt.frame(0.0); + rt.update(|s, _| *s = true); + rt.frame(1.0 / 60.0); + assert!(moving(&rt, "a")); + assert!(rt.presented_pose("a").unwrap().moving()); + settle(&mut rt); + assert!(!moving(&rt, "a")); + assert!(!rt.presented_pose("a").unwrap().moving()); +} + +#[test] +fn pose_and_element_moving_agree_for_loops_and_an_anchors_shadow() { + fn view(on: &bool, _: &mut Cx<bool>) -> El { + col().w_full().h_full() + .child(el().key("anchor").size(40.0, 40.0).motion(Spring::new(0.3, 0.0)) + .box_shadow(sh(if *on { 12.0 } else { 2.0 }))) + .child(el().key("popup").size(20.0, 20.0).above("anchor", 0.0)) + .child(el().key("loop").size(20.0, 20.0).looping(rune::LoopSpec::rotation(1.0))) + } + let mut rt = Runtime::new(false, view, (200.0, 200.0), Env::new(true, 1.0)); + rt.frame(0.0); + rt.update(|s, _| *s = true); + rt.frame(1.0 / 60.0); + assert!(moving(&rt, "popup")); + assert!(rt.presented_pose("popup").unwrap().moving()); + settle(&mut rt); + assert!(!moving(&rt, "popup")); + assert!(!rt.presented_pose("popup").unwrap().moving()); + assert!(moving(&rt, "loop")); + assert!(rt.presented_pose("loop").unwrap().moving()); +} + +#[test] +fn a_turned_ancestor_clips_its_child_in_layer_coordinates() { + fn view(_: &(), _: &mut Cx<()>) -> El { + col().w_full().h_full().padding(50.0).items_start().child( + el().key("clip").size(100.0, 100.0).rotate(FRAC_PI_4).clip_rounded(0.0) + .child(el().key("child").size(200.0, 100.0).absolute(0.0, 0.0)), + ) + } + let mut rt = Runtime::new((), view, (300.0, 300.0), Env::new(true, 2.0)); + rt.frame(0.0); + assert!(rt.contains("child", 100.0, 100.0)); + assert!(!rt.contains("child", 149.5, 149.5), "inside child but outside the turned parent clip"); + assert_eq!(rt.element_at(100.0, 100.0).unwrap().key(), Some("child")); + assert_ne!(rt.element_at(149.5, 149.5).unwrap().key(), Some("child")); +} + +#[test] +fn sticky_and_anchored_elements_pick_in_paint_order_after_scrolling() { + fn view(_: &Hits, _: &mut Cx<Hits>) -> El { + col().w_full().h_full().child( + col().key("scroll").size(100.0, 100.0).scroll(rune::ScrollSpec { stick_bottom: false }) + .child(col().w_full().h(300.0) + .child(el().key("header").w_full().h(30.0).sticky_top(0.0) + .on_press(|s: &mut Hits| s.0.push("header"))) + .child(el().key("row").w_full().h(270.0) + .on_press(|s: &mut Hits| s.0.push("row"))) + .child(el().key("popup").size(60.0, 20.0) + .anchored("header", rune::Side::Bottom, rune::Align::Start, 0.0) + .on_press(|s: &mut Hits| s.0.push("popup")))), + ) + } + let mut rt = Runtime::new(Hits::default(), view, (200.0, 200.0), Env::new(true, 1.0)); + rt.frame(0.0); + rt.update(|_, tx| tx.scroll_to_y("scroll", 20.0)); + rt.frame(0.0); + for (y, expected) in [(15.0, "header"), (35.0, "popup"), (65.0, "row")] { + assert_eq!(rt.element_at(20.0, y).unwrap().key(), Some(expected)); + rt.state.0.clear(); + rt.pointer_down(20.0, y); + rt.pointer_up(20.0, y); + rt.frame(0.0); + assert_eq!(rt.state.0, [expected]); + } +} + +#[test] +fn pick_transparent_finds_opacity_zero_elements_but_not_exiting_ones() { + #[derive(Default)] + struct S { plain: Option<String>, with: Option<String>, gone: bool } + fn view(s: &S, _: &mut Cx<S>) -> El { + el().w_full().h_full().child( + col().key("canvas").w_full().h_full().items_start() + .child(el().key("clear").size(50.0, 50.0).opacity(0.0)) + .child(el().key("parent").size(50.0, 50.0).opacity(0.0) + .child(el().key("kid").size(20.0, 20.0))) + .children((!s.gone).then(|| el().key("leaver").size(50.0, 50.0).fill(Color::WHITE) + .transition(rune::Transition::opacity()))), + ) + } + let mut rt = Runtime::new(S::default(), view, (200.0, 200.0), Env::new(true, 1.0)); + rt.frame(0.0); + let on = rune::Pick::new().transparent(true); + let key = |p: Option<rune::Picked>| p.and_then(|p| p.key().map(str::to_owned)); + // `clear` is at y 0..50, `parent` (and `kid`) at 50..100. + assert_ne!(key(rt.element_at(10.0, 10.0)).as_deref(), Some("clear")); + assert_eq!(key(rt.element_at_with(10.0, 10.0, rune::Pick::default())).as_deref(), key(rt.element_at(10.0, 10.0)).as_deref()); + assert_eq!(key(rt.element_at_with(10.0, 10.0, on)).as_deref(), Some("clear")); + assert_eq!(key(rt.element_at_in_with("canvas", 10.0, 10.0, on)).as_deref(), Some("clear")); + assert_ne!(key(rt.element_at_in("canvas", 10.0, 10.0)).as_deref(), Some("clear")); + assert!(!rt.contains("clear", 10.0, 10.0)); + assert!(rt.contains_with("clear", 10.0, 10.0, on)); + // A child of an opacity-0 parent inherits 0. + assert_ne!(key(rt.element_at(10.0, 60.0)).as_deref(), Some("kid")); + assert_eq!(key(rt.element_at_with(10.0, 60.0, on)).as_deref(), Some("kid")); + assert!(rt.contains_with("kid", 10.0, 60.0, on) && !rt.contains("kid", 10.0, 60.0)); + + // The Tx path. + fn read(s: &mut S, with: bool, tx: &mut rune::Tx) { + let on = rune::Pick::new().transparent(with); + let f = move |s: &mut S, p: Option<rune::Picked>, _: &mut rune::Tx| { + let k = p.and_then(|p| p.key().map(str::to_owned)); + if with { s.with = k } else { s.plain = k } + }; + let _ = s; + tx.element_at_in_with("canvas", 10.0, 10.0, on, f); + } + rt.update(|s, tx| { read(s, false, tx); read(s, true, tx); }); + rt.frame(0.0); + assert_ne!(rt.state.plain.as_deref(), Some("clear")); + assert_eq!(rt.state.with.as_deref(), Some("clear")); + + // An exiting element is skipped even with the option. + let (x, y) = (10.0, 110.0); + assert_eq!(key(rt.element_at_with(x, y, on)).as_deref(), Some("leaver")); + rt.update(|s, _| s.gone = true); + rt.frame(1.0 / 60.0); + assert_ne!(key(rt.element_at_with(x, y, on)).as_deref(), Some("leaver")); + assert!(!rt.contains_with("leaver", x, y, on)); +} diff --git a/app/vendor/rune/crates/rune/tests/integration/radial_srgb.rs b/app/vendor/rune/crates/rune/tests/integration/radial_srgb.rs new file mode 100644 index 0000000..c02667f --- /dev/null +++ b/app/vendor/rune/crates/rune/tests/integration/radial_srgb.rs @@ -0,0 +1,484 @@ +use std::f32::consts::{FRAC_PI_4, PI}; +use std::sync::Arc; + +use rune::color::{hex, srgb_encode}; +use rune::compose::{Compositor, Frame}; +use rune::native_surface::{ByteFrame, ColorInfo, Format}; +use rune::render::{Gpu, KIND_RADIAL, OFFSCREEN_FORMAT, Offscreen, Renderer}; +use rune::{ + App, AppSpec, Color, Cx, El, Env, Image, ImageCache, + NativeSurface, Pixels, Runtime, SurfaceFit, el, +}; + +fn render_rt<S: 'static>(gpu: &Gpu, rt: &mut Runtime<S>, size: (u32, u32)) -> Vec<u8> { + let format = if rt.srgb_blend() { + OFFSCREEN_FORMAT.remove_srgb_suffix() + } else { + OFFSCREEN_FORMAT + }; + let mut renderer = Renderer::new(&gpu.device, format); + renderer.set_srgb_blend(rt.srgb_blend()); + let target = Offscreen::with_format(&gpu.device, size.0, size.1, format); + renderer.upload_images(&gpu.device, &gpu.queue, &mut rt.images); + renderer.prepare_surfaces(&gpu.device, &gpu.queue, &rt.surfaces, size); + renderer.prepare(&gpu.device, &gpu.queue, &mut rt.text.atlas, &rt.instances, size); + let mut encoder = gpu.device.create_command_encoder(&Default::default()); + renderer.draw(&mut encoder, &target.view, rt.clear_color()); + target.copy(&mut encoder); + renderer.submit(&gpu.queue, encoder); + target.read(&gpu.device) +} + +fn snap_app<S: 'static>(app: App<S>, name: &str, extra_args: &[&str]) -> (u32, u32, Vec<u8>) { + let dir = std::env::temp_dir().join(format!("rune-radial-srgb-{name}-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let png_path = dir.join("snap.png"); + let mut args = vec![ + "--snap".to_string(), + png_path.to_str().unwrap().to_string(), + "--scale".to_string(), + "1".to_string(), + ]; + for a in extra_args { + args.push((*a).to_string()); + } + app.args(args).run(); + let file = std::fs::File::open(&png_path).unwrap(); + let decoder = png::Decoder::new(std::io::BufReader::new(file)); + let mut reader = decoder.read_info().unwrap(); + let mut buf = vec![0u8; reader.output_buffer_size().unwrap()]; + let info = reader.next_frame(&mut buf).unwrap(); + buf.truncate(info.buffer_size()); + std::fs::remove_dir_all(&dir).unwrap(); + (info.width, info.height, buf) +} + +fn pixel(rgba: &[u8], width: u32, x: u32, y: u32) -> [u8; 4] { + let at = ((y * width + x) * 4) as usize; + rgba[at..at + 4].try_into().unwrap() +} + +#[test] +fn radial_gradient_centre_edge_and_monotonic_falloff() { + fn view(_: &(), _: &mut Cx<()>) -> El { + el().size(120.0, 120.0).radial_gradient( + [0.5, 0.5], + 50.0, + [(0.0, Color::WHITE), (1.0, Color::BLACK)], + ) + } + + let mut rt = Runtime::new((), view, (120.0, 120.0), Env::new(true, 1.0)); + rt.frame(0.0); + assert_eq!(rt.instances.len(), 1); + let inst = rt.instances[0]; + assert_eq!(inst.params[1], KIND_RADIAL); + assert_eq!(inst.uv, [60.0, 60.0, 50.0, 50.0]); + + let gpu = Gpu::headless(); + let out = render_rt(&gpu, &mut rt, (120, 120)); + + let center = pixel(&out, 120, 60, 60); + let edge = pixel(&out, 120, 115, 60); + assert!(center[0] >= 253 && center[1] >= 253 && center[2] >= 253 && center[3] == 255, "centre: {center:?}"); + assert_eq!(edge, [0, 0, 0, 255], "outside radius clamps to outer stop"); + + let mut prev = center[0]; + for x in 60..115 { + let p = pixel(&out, 120, x, 60)[0]; + assert!(p <= prev, "non-monotonic at x={x}: {p} > {prev}"); + prev = p; + } + assert!(pixel(&out, 120, 85, 60)[0] > 80 && pixel(&out, 120, 85, 60)[0] < 220); +} + +#[test] +fn radial_gradient_multi_stop_elliptical_quad_shrinking_and_validation() { + fn multi_view(swap: &bool, _: &mut Cx<bool>) -> El { + let mid = if *swap { + Color { r: 1.0, g: 1.0, b: 0.0, a: 1.0 } + } else { + Color { r: 0.0, g: 1.0, b: 0.0, a: 1.0 } + }; + el().size(140.0, 100.0).child( + el() + .absolute(10.0, 10.0) + .size(120.0, 80.0) + .radius(20.0) + .fill(Color { r: 0.1, g: 0.1, b: 0.1, a: 1.0 }) + .radial_gradient( + [0.5, 0.5], + [50.0, 25.0], + [ + (0.0, Color { r: 1.0, g: 0.0, b: 0.0, a: 1.0 }), + (0.5, mid), + (1.0, Color { r: 0.0, g: 0.0, b: 1.0, a: 1.0 }), + ], + ) + .border(2.0, Color::WHITE) + .opacity(0.9), + ) + } + + let mut rt = Runtime::new(false, multi_view, (140.0, 100.0), Env::new(true, 1.0)); + rt.transparent = true; + rt.frame(0.0); + + // Verify inner radial band's quad is shrunk to the bbox of centre ± t1*r (52×27 vs full 120×80). + let radial_insts: Vec<_> = rt.instances.iter().filter(|i| i.params[1] == KIND_RADIAL).collect(); + assert_eq!(radial_insts.len(), 2); + assert!( + radial_insts[0].rect[2] <= 54.0 && radial_insts[0].rect[3] <= 28.0, + "inner radial band quad should shrink to its stop bbox: {:?}", + radial_insts[0].rect + ); + assert_eq!(radial_insts[1].rect, [10.0, 10.0, 120.0, 80.0]); + + let gpu = Gpu::headless(); + let out = render_rt(&gpu, &mut rt, (140, 100)); + + // Rounded corner outside the 20pt radius at (11, 11) is clipped transparent. + assert_eq!(pixel(&out, 140, 11, 11)[3], 0); + // Centre (70, 50) is dominated by the inner red stop. + let c_center = pixel(&out, 140, 70, 50); + assert!(c_center[0] > 200 && c_center[1] < 70 && c_center[2] < 40, "centre: {c_center:?}"); + // Halfway horizontally (70 + 25 = 95, 50) and vertically (70, 50 + 12 = 62) hit the mid green stop (t ≈ 0.5). + let c_mid_x = pixel(&out, 140, 95, 50); + let c_mid_y = pixel(&out, 140, 70, 62); + assert!(c_mid_x[1] > 200 && c_mid_x[0] < 90 && c_mid_x[2] < 90, "mid x: {c_mid_x:?}"); + assert!(c_mid_y[1] > 200 && c_mid_y[0] < 90 && c_mid_y[2] < 90, "mid y: {c_mid_y:?}"); + // At dx = 50 (120, 50) we are at t = 1.0 (blue stop). + let c_outer = pixel(&out, 140, 120, 50); + assert!(c_outer[2] > 200 && c_outer[0] < 40 && c_outer[1] < 40, "outer: {c_outer:?}"); + // Border at (70, 11) is white. + let c_border = pixel(&out, 140, 70, 11); + assert!(c_border[0] > 210 && c_border[1] > 210 && c_border[2] > 210, "border: {c_border:?}"); + + // Stop colours animate via Oklab springs when state updates. + rt.update(|s, _| *s = true); + rt.frame(0.04); + let mid_anim = render_rt(&gpu, &mut rt, (140, 100)); + let p_anim = pixel(&mid_anim, 140, 95, 50); + assert!(p_anim[0] > c_mid_x[0] + 20 && p_anim[0] < 245, "mid-spring stop colour: {p_anim:?}"); + + // Half-valid radii (e.g. [10.0, 0.0]) are dropped and never fall through to linear_gradient; + // Stops beyond the sixteenth do not add segments. + fn edge_cases(_: &(), _: &mut Cx<()>) -> El { + let stops: Vec<(f32, Color)> = (0..18) + .map(|i| (i as f32 / 17.0, Color::WHITE)) + .collect(); + el().size(100.0, 100.0) + .child(el().size(50.0, 50.0).radial_gradient([0.5, 0.5], [10.0, 0.0], [(0.0, Color::WHITE), (1.0, Color::BLACK)])) + .child(el().size(50.0, 50.0).radial_gradient([0.5, 0.5], 25.0, stops)) + } + let mut rt_edge = Runtime::new((), edge_cases, (100.0, 100.0), Env::new(true, 1.0)); + rt_edge.frame(0.0); + let edge_radials: Vec<_> = rt_edge.instances.iter().filter(|i| i.params[1] == KIND_RADIAL).collect(); + assert_eq!(edge_radials.len(), 15, "18 stops capped at 16 stops (15 segments), invalid [10, 0] dropped"); + assert!(edge_radials.iter().all(|i| i.uv[2] > 0.0 && i.uv[3] > 0.0)); + + // Angled linear_gradient(PI, ..) matches vertical El::gradient(..), and 45° runs corner-to-corner. + fn linear_pair(angled: &bool, _: &mut Cx<bool>) -> El { + let a = Color { r: 1.0, g: 0.0, b: 0.0, a: 1.0 }; + let b = Color { r: 0.0, g: 0.0, b: 1.0, a: 1.0 }; + let card = el().size(80.0, 60.0).radius(8.0); + if *angled { + card.linear_gradient(PI, [(0.0, a), (1.0, b)]) + } else { + card.gradient(a, b) + } + } + let mut rt_v = Runtime::new(false, linear_pair, (80.0, 60.0), Env::new(true, 1.0)); + let mut rt_l = Runtime::new(true, linear_pair, (80.0, 60.0), Env::new(true, 1.0)); + rt_v.frame(0.0); + rt_l.frame(0.0); + let px_v = render_rt(&gpu, &mut rt_v, (80, 60)); + let px_l = render_rt(&gpu, &mut rt_l, (80, 60)); + assert!( + px_v.iter().zip(&px_l).all(|(a, b)| a.abs_diff(*b) <= 1), + "linear_gradient(PI) matches gradient()" + ); + + fn diag_blurred(_: &(), _: &mut Cx<()>) -> El { + el().size(80.0, 80.0).child( + el() + .absolute(10.0, 10.0) + .size(60.0, 60.0) + .linear_gradient(FRAC_PI_4, [(0.0, Color::WHITE), (1.0, Color::BLACK)]) + .blur(2.0), + ) + } + let mut rt_d = Runtime::new((), diag_blurred, (80.0, 80.0), Env::new(true, 1.0)); + rt_d.frame(0.0); + let px_d = render_rt(&gpu, &mut rt_d, (80, 80)); + assert!(pixel(&px_d, 80, 20, 60)[0] > pixel(&px_d, 80, 60, 20)[0] + 100); +} + +#[test] +fn srgb_blend_matches_css_and_core_animation_glow_reference() { + let bg = hex("#100e11").unwrap(); + let glow = hex("#40bf80").unwrap().alpha(0.16); + + // Analytical CSS / Core Animation sRGB reference for #40bf80 @ 0.16 over #100e11 with blur 30 (sigma = 15). + let bg_srgb = [bg.r, bg.g, bg.b].map(srgb_encode); + let glow_srgb = [glow.r, glow.g, glow.b].map(srgb_encode); + + fn shadow_glow_view(_: &(), _: &mut Cx<()>) -> El { + let bg = hex("#100e11").unwrap(); + let glow = hex("#40bf80").unwrap().alpha(0.16); + el().size(240.0, 240.0).fill(bg).child( + el() + .absolute(60.0, 60.0) + .size(120.0, 120.0) + .radius(24.0) + .shadow(0.0, 30.0, glow), + ) + } + + let (_, _, px_linear) = snap_app( + App::new(AppSpec::new("glow-lin", (240.0, 240.0), || (), shadow_glow_view)).srgb_blend(false), + "glow-lin", + &[], + ); + let (_, _, px_srgb) = snap_app( + App::new(AppSpec::new("glow-srgb", (240.0, 240.0), || (), shadow_glow_view)).srgb_blend(true), + "glow-srgb", + &[], + ); + + // At the centre (120, 120), the shadow weight is ~1.0 so effective alpha is 0.16. + let expected_center: [u8; 3] = std::array::from_fn(|c| { + ((glow_srgb[c] * 0.16 + bg_srgb[c] * (1.0 - 0.16)) * 255.0).round() as u8 + }); + assert_eq!(expected_center, [24, 42, 35]); + + let linear_center = pixel(&px_linear, 240, 120, 120); + let srgb_center = pixel(&px_srgb, 240, 120, 120); + + // Default linear mode stays unchanged (green channel is 83 vs 42 in sRGB reference). + assert_eq!(linear_center, [29, 83, 56, 255]); + // NVIDIA quantizes the UNORM8 source before blending, so the centre may sit 1 LSB off per channel. + assert!( + (0..3).all(|c| srgb_center[c].abs_diff(expected_center[c]) <= 1), + "srgb_blend centre within 1 LSB: got {srgb_center:?}, expected {expected_center:?}" + ); + + // Check the Gaussian falloff across the left edge (x = 15..120 at y = 120, where sigma = 15 px). + let erf = |x: f32| -> f32 { + let s = x.signum(); + let a = x.abs(); + let r = 1.0 + (0.278393 + (0.230389 + 0.078108 * a * a) * a) * a; + let r2 = r * r; + s - s / (r2 * r2) + }; + let sigma = 15.0f32; + let mut max_err_linear = 0u8; + let mut max_err_srgb = 0u8; + for x in 15..=120 { + let px = x as f32 + 0.5 - 120.0; + let scale = 0.5f32.sqrt() / sigma; + let w = 0.5 * (erf((px + 60.0) * scale) - erf((px - 60.0) * scale)); + let a = 0.16 * w; + let ref_rgb: [u8; 3] = std::array::from_fn(|c| { + ((glow_srgb[c] * a + bg_srgb[c] * (1.0 - a)) * 255.0).round() as u8 + }); + let p_lin = pixel(&px_linear, 240, x, 120); + let p_srgb = pixel(&px_srgb, 240, x, 120); + for c in 0..3 { + max_err_linear = max_err_linear.max(p_lin[c].abs_diff(ref_rgb[c])); + max_err_srgb = max_err_srgb.max(p_srgb[c].abs_diff(ref_rgb[c])); + } + } + assert!(max_err_linear >= 40, "linear error should be large (~41 LSB): {max_err_linear}"); + assert!(max_err_srgb <= 1, "srgb_blend falloff error within 1 LSB: {max_err_srgb}"); + + // Also verify layer blur (`.fill(glow).blur(15.0)`) in srgb_blend mode matches the centre and falloff. + fn blur_glow_view(_: &(), _: &mut Cx<()>) -> El { + let bg = hex("#100e11").unwrap(); + let glow = hex("#40bf80").unwrap().alpha(0.16); + el().size(240.0, 240.0).fill(bg).child( + el() + .absolute(60.0, 60.0) + .size(120.0, 120.0) + .radius(24.0) + .fill(glow) + .blur(15.0), + ) + } + let (_, _, px_blur_srgb) = snap_app( + App::new(AppSpec::new("blur-srgb", (240.0, 240.0), || (), blur_glow_view)).srgb_blend(true), + "blur-srgb", + &[], + ); + let blur_center = pixel(&px_blur_srgb, 240, 120, 120); + for c in 0..3 { + assert!( + blur_center[c].abs_diff(expected_center[c]) <= 1, + "layer blur srgb centre channel {c}: got {blur_center:?}, expected {expected_center:?}" + ); + } +} + +#[test] +fn srgb_blend_images_surfaces_keycaps_and_compositor() { + #[derive(Clone)] + struct MediaState { + premul_img: Image, + straight_px: Pixels, + bgra_surface: NativeSurface, + nv12_surface: NativeSurface, + } + + fn init_media() -> MediaState { + let cache = ImageCache::new(Arc::new(|| {})); + // White at alpha 128/255 (~0.502): ImageCache stores sRGB-encoded premultiplied (188, 188, 188, 128). + let premul_img = cache.rgba(16, 16, [255u8, 255, 255, 128].repeat(16 * 16)); + premul_img.wait().unwrap(); + + let straight_px = Pixels::new(); + straight_px.set(16, 16, [255u8, 255, 255, 128].repeat(16 * 16)); + + let bgra_surface = NativeSurface::new(); + bgra_surface + .push_bytes( + ByteFrame { + width: 16, + height: 16, + format: Format::Bgra, + color: ColorInfo::default(), + planes: [[128u8, 128, 128, 255].repeat(16 * 16), Vec::new()], + }, + 1, + ) + .unwrap(); + + let nv12_surface = NativeSurface::new(); + nv12_surface + .push_bytes( + ByteFrame { + width: 16, + height: 16, + format: Format::Nv12Full, + color: ColorInfo::default(), + planes: [vec![128u8; 16 * 16], vec![128u8; 8 * 8 * 2]], + }, + 1, + ) + .unwrap(); + + MediaState { + premul_img, + straight_px, + bgra_surface, + nv12_surface, + } + } + + fn media_view(s: &MediaState, _: &mut Cx<MediaState>) -> El { + el().size(120.0, 40.0) + .fill(hex("#808080").unwrap()) + .child(el().absolute(4.0, 4.0).size(16.0, 16.0).pixels(s.premul_img.pixels())) + .child(el().absolute(24.0, 4.0).size(16.0, 16.0).pixels(&s.straight_px)) + .child(el().absolute(44.0, 4.0).size(16.0, 16.0).native_surface(&s.bgra_surface, SurfaceFit::Fill)) + .child(el().absolute(64.0, 4.0).size(16.0, 16.0).native_surface(&s.nv12_surface, SurfaceFit::Fill)) + .child( + el().absolute(84.0, 4.0) + .size(16.0, 16.0) + .native_surface(&s.bgra_surface, SurfaceFit::Fill) + .blur(0.5), + ) + } + + let (_, _, px_srgb) = snap_app( + App::new(AppSpec::new("media-srgb", (120.0, 40.0), init_media, media_view)).srgb_blend(true), + "media-srgb", + &[], + ); + + // 1. Premultiplied image: white @ alpha 128/255 over mid-grey 128/255 => 128 + 127 * (128/255) ≈ 191. + let p_premul = pixel(&px_srgb, 120, 12, 12); + assert!( + p_premul[0].abs_diff(191) <= 1 && p_premul[1].abs_diff(191) <= 1 && p_premul[2].abs_diff(191) <= 1, + "premultiplied image edge texel in srgb_blend should be 191 ± 1, got {p_premul:?}" + ); + + // 2. Straight-alpha Pixels: white @ alpha 128/255 over mid-grey 128/255 => 191 ± 1. + let p_straight = pixel(&px_srgb, 120, 32, 12); + assert!( + p_straight[0].abs_diff(191) <= 1 && p_straight[1].abs_diff(191) <= 1 && p_straight[2].abs_diff(191) <= 1, + "straight-alpha pixels in srgb_blend should be 191 ± 1, got {p_straight:?}" + ); + + // 3. BGRA and NV12 video/native surfaces at 50% grey (128/255) in srgb_blend => 128 ± 1 (not ~55). + let p_bgra = pixel(&px_srgb, 120, 52, 12); + let p_nv12 = pixel(&px_srgb, 120, 72, 12); + let p_layer_surface = pixel(&px_srgb, 120, 92, 12); + assert!( + p_bgra[0].abs_diff(128) <= 1 && p_bgra[1].abs_diff(128) <= 1 && p_bgra[2].abs_diff(128) <= 1, + "BGRA surface 50% grey in srgb_blend should be 128 ± 1, got {p_bgra:?}" + ); + assert!( + p_nv12[0].abs_diff(128) <= 1 && p_nv12[1].abs_diff(128) <= 1 && p_nv12[2].abs_diff(128) <= 1, + "NV12 surface 50% grey in srgb_blend should be 128 ± 1, got {p_nv12:?}" + ); + assert!( + p_layer_surface[0].abs_diff(128) <= 1 && p_layer_surface[1].abs_diff(128) <= 1 && p_layer_surface[2].abs_diff(128) <= 1, + "Blurred Rgba16Float layer surface 50% grey in srgb_blend should be 128 ± 1, got {p_layer_surface:?}" + ); + + // 4. Secondary runtime (`--keys` and `--pointer` overlay) propagates srgb_blend. + let dir = std::env::temp_dir().join(format!("rune-keys-srgb-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let script_path = dir.join("script.json"); + std::fs::write( + &script_path, + r#"[{"t": 0.0, "type": "key", "name": "a"}, {"t": 0.0, "type": "click", "x": 90, "y": 20}]"#, + ) + .unwrap(); + let (_, _, px_keys_srgb) = snap_app( + App::new(AppSpec::new("keys-srgb", (160.0, 80.0), || (), |_, _| el().size(160.0, 80.0).fill(hex("#808080").unwrap()))) + .srgb_blend(true), + "keys-srgb", + &[ + "--script", + script_path.to_str().unwrap(), + "--keys", + "bottom-left", + "--keys-theme", + "dark", + "--pointer", + "--at", + "0.25", + ], + ); + std::fs::remove_dir_all(&dir).unwrap(); + // Dark keycap at bottom-left (x=30, y=45) has fill oklcha(0.22, 0, 0, 0.96): + // sRGB-encoded fill is ~24/255 (blended ~26), whereas unpropagated linear fill into non-sRGB was ~4/255. + let p_cap = pixel(&px_keys_srgb, 160, 30, 45); + assert!( + p_cap[0] >= 20 && p_cap[0] <= 35, + "keycaps overlay runtime should encode cap fill in sRGB space (~26, not ~4), got {p_cap:?}" + ); + + // 5. A Compositor sees the blend mode and the matching non-sRGB target format. + static COMP_STATE: std::sync::OnceLock<(bool, wgpu::TextureFormat)> = std::sync::OnceLock::new(); + struct CheckComp; + impl Compositor<()> for CheckComp { + fn render(&mut self, f: &mut Frame<'_, ()>) { + COMP_STATE.set((f.srgb_blend(), f.format)).ok(); + f.draw_ui(); + } + } + let _ = snap_app( + App::new(AppSpec::new("comp-srgb", (64.0, 64.0), || (), |_, _| el().size(64.0, 64.0).fill(hex("#808080").unwrap()))) + .compositor(CheckComp) + .srgb_blend(true), + "comp-srgb", + &[], + ); + assert_eq!( + COMP_STATE.get().copied(), + Some((true, OFFSCREEN_FORMAT.remove_srgb_suffix())), + "a compositor must see srgb_blend and the non-sRGB target format" + ); +} diff --git a/app/vendor/rune/crates/rune/tests/integration/reveal_insert.rs b/app/vendor/rune/crates/rune/tests/integration/reveal_insert.rs new file mode 100644 index 0000000..7af436e --- /dev/null +++ b/app/vendor/rune/crates/rune/tests/integration/reveal_insert.rs @@ -0,0 +1,67 @@ +//! A commit that inserts rows above the first one of a reader's virtual growth stack and +//! reveals the new first row in the same `Tx` shows that row at full height from the first +//! frame, as rows entering under a reveal from an earlier commit do. +use rune::runtime::ElementInfo; +use rune::{Cx, El, Env, GrowthSpec, Runtime, ScrollSpec, col, el, memo, text}; + +struct S { items: Vec<u32> } + +fn key(id: u32) -> String { format!("item{id}") } + +fn view(s: &S, _: &mut Cx<S>) -> El { + let rows = col().key("rows").w_full().px(8.0).py(6.0).growth(GrowthSpec::default()).virtual_rows( + s.items.len(), + 44.0, + |s: &S, i| key(s.items[i]).into(), + |s: &S, i| { + let id = s.items[i]; + // The first row carries its section's header, as a search list's first result does. + memo(&key(id), (id, i == 0), || { + let mut row = col().w_full(); + if i == 0 { row = row.child(el().key("section").w_full().h(30.0)); } + row.child(el().key(key(id)).w_full().h(44.0).child(text(format!("Row {id}")))) + }) + }, + ); + col().w_full().h_full().child( + col().key("list").w_full().h(300.0).scroll(ScrollSpec { stick_bottom: false }).scroll_margin(6.0).child(rows), + ) +} + +fn find(rt: &Runtime<S>, key: &str) -> Option<ElementInfo> { + rt.elements().into_iter().find(|e| e.key.as_deref() == Some(key)) +} + +fn shown(rt: &Runtime<S>, key: &str) -> f32 { find(rt, key).map_or(0.0, |e| e.visible[3]) } + +fn scrolled_away_and_back() -> Runtime<S> { + let mut rt = Runtime::new(S { items: (0..1000).collect() }, view, (400.0, 300.0), Env::new(true, 1.0)); + for _ in 0..10 { rt.frame(1.0 / 120.0); } + rt.settle_all(); + for row in [40, 0] { + rt.update(|_, tx| tx.scroll_into_view(key(row))); + for _ in 0..3 { rt.frame(1.0 / 120.0); } + } + rt +} + +#[test] +fn rows_inserted_above_the_top_and_revealed_in_the_same_commit_land_in_view() { + for inserted in [1, 2] { + let mut rt = scrolled_away_and_back(); + rt.update(|s, tx| { + for n in 0..inserted { s.items.insert(0, 1001 + n); } + tx.scroll_into_view(key(s.items[0])); + }); + let first = key(1000 + inserted); + rt.frame(1.0 / 120.0); + let h = shown(&rt, &first); + assert!(h > 43.5, "{inserted} inserted: the first frame shows the new first row whole, not {h}"); + for _ in 0..3 { rt.frame(1.0 / 120.0); } + assert!(shown(&rt, &first) > 43.5, "{inserted} inserted: and keeps showing it"); + rt.settle_all(); + assert!(shown(&rt, &first) > 43.5, "{inserted} inserted: settled"); + let section = rt.elements().into_iter().find(|e| e.key.as_deref() == Some("section") && !e.exiting).unwrap(); + assert!(section.visible[3] > 29.5 && section.rect[1] >= -0.05, "{inserted} inserted: at the top: {section:?}"); + } +} diff --git a/app/vendor/rune/crates/rune/tests/integration/revive_settle.rs b/app/vendor/rune/crates/rune/tests/integration/revive_settle.rs new file mode 100644 index 0000000..7fa001e --- /dev/null +++ b/app/vendor/rune/crates/rune/tests/integration/revive_settle.rs @@ -0,0 +1,51 @@ +use rune::{Color, Cx, El, Env, Runtime, Transition, col, el}; + +fn view(shown: &(bool, f32), _: &mut Cx<(bool, f32)>) -> El { + let mut c = col().size(200.0, 200.0).child(el().h(shown.1)); + if shown.0 { + c = c.child(el().key("card").size(80.0, 40.0).fill(Color::WHITE).transition(Transition::opacity())); + } + c +} + +/// Removes the card, runs most of its fade, then brings it back (moved down by 20 pt). +fn return_mid_exit(settle: bool) -> Runtime<(bool, f32)> { + let mut rt = Runtime::new((true, 0.0), view, (200.0, 200.0), Env::new(true, 1.0)); + rt.frame(0.0); + rt.update(|s, _| s.0 = false); + for _ in 0..24 { + rt.frame(1.0 / 120.0); + } + let (_, o) = rt.presented("card").expect("still fading out"); + assert!(o > 0.0 && o < 0.5, "in the exit tail: {o}"); + rt.update(|s, tx| { + *s = (true, 20.0); + if settle { + tx.settle(); + } + }); + rt.frame(1.0 / 120.0); + rt +} + +#[test] +fn a_settled_return_mid_exit_appears_at_rest() { + let mut rt = return_mid_exit(true); + let (r, o) = rt.presented("card").unwrap(); + assert_eq!((r, o), ([0.0, 20.0, 80.0, 40.0], 1.0)); + for _ in 0..120 { + rt.frame(1.0 / 120.0); + assert_eq!(rt.presented("card").unwrap(), ([0.0, 20.0, 80.0, 40.0], 1.0)); + } +} + +#[test] +fn an_animated_return_mid_exit_still_reverses_from_where_it_is() { + let mut rt = return_mid_exit(false); + let (_, o) = rt.presented("card").unwrap(); + assert!(o > 0.0 && o < 0.5, "reverses from the faded look: {o}"); + for _ in 0..240 { + rt.frame(1.0 / 120.0); + } + assert_eq!(rt.presented("card").unwrap(), ([0.0, 20.0, 80.0, 40.0], 1.0)); +} diff --git a/app/vendor/rune/crates/rune/tests/integration/row_enter.rs b/app/vendor/rune/crates/rune/tests/integration/row_enter.rs new file mode 100644 index 0000000..16e9769 --- /dev/null +++ b/app/vendor/rune/crates/rune/tests/integration/row_enter.rs @@ -0,0 +1,135 @@ +//! Rows inserted into a growth stack play an explicit `.transition` on top of growing open, in +//! plain and virtual stacks under a stick-to-bottom scroll. Rows without one only grow; the +//! first frame and rows a virtual list remounts on scroll never replay an entrance. +use rune::runtime::ElementInfo; +use rune::{Cx, El, Env, GrowthSpec, Runtime, ScrollSpec, Transition, col, text}; + +struct S { virtual_list: bool, explicit: bool, n: usize } + +fn view(s: &S, _: &mut Cx<S>) -> El { + let mut stack = col().key("stack").w_full().growth(GrowthSpec::default()); + if s.virtual_list { stack = stack.virtualize(40.0); } + for i in 0..s.n { + let mut r = col().key(format!("r{i}")).w_full().h(40.0).child(text(format!("row {i}")).key(format!("t{i}"))); + if s.explicit { r = r.transition(Transition::offset(0.0, 12.0).combined(Transition::opacity())); } + stack = stack.child(r); + } + col().w_full().h_full().child(col().key("scroll").w_full().h(200.0).scroll(ScrollSpec { stick_bottom: true }).child(stack)) +} + +fn find(rt: &Runtime<S>, key: &str) -> Option<ElementInfo> { + rt.elements().into_iter().find(|e| e.key.as_deref() == Some(key)) +} + +#[test] +fn inserted_rows_play_their_explicit_transition() { + for virtual_list in [false, true] { + for explicit in [false, true] { + let name = format!("virtual {virtual_list}, explicit {explicit}"); + let mut rt = Runtime::new(S { virtual_list, explicit, n: 40 }, view, (300.0, 300.0), Env::new(true, 1.0)); + rt.frame(0.0); + let last = find(&rt, "r39").unwrap(); + assert_eq!(last.opacity, 1.0, "{name}: the first frame mounts settled"); + + rt.update(|s, _| s.n = 41); + rt.frame(1.0 / 60.0); + let row = find(&rt, "r40").unwrap(); + let label = find(&rt, "t40").unwrap(); + if explicit { + assert!(row.opacity < 0.5 && label.opacity < 0.5, "{name}: fades in, at {}", row.opacity); + assert!(row.rect[1] + row.rect[3] > 205.0, "{name}: slides up from below the bottom edge"); + } else { + assert_eq!((row.opacity, label.opacity), (1.0, 1.0), "{name}: growth alone"); + assert!((row.rect[1] + row.rect[3] - 200.0).abs() < 0.01, "{name}: sits on the bottom edge"); + } + assert!(row.rect[3] < 40.0, "{name}: still grows open"); + for _ in 0..90 { rt.frame(1.0 / 60.0); } + let row = find(&rt, "r40").unwrap(); + assert_eq!(row.opacity, 1.0, "{name}: settles"); + assert_eq!(row.rect, [0.0, 160.0, 300.0, 40.0], "{name}: lands at the bottom"); + + if virtual_list { + assert!(find(&rt, "r0").is_none(), "{name}: the top row is culled"); + for _ in 0..4 { + rt.wheel(150.0, 100.0, 1000.0); + rt.frame(1.0 / 60.0); + } + let top = find(&rt, "r0").expect("scrolled back to the top"); + assert_eq!(top.opacity, 1.0, "{name}: a remounted row doesn't replay its entrance"); + assert_eq!(top.rect, top.target, "{name}: nor slide"); + } + } + } +} + +struct Chips { virtual_list: bool, copied: bool } + +fn chips(s: &Chips, _: &mut Cx<Chips>) -> El { + let mut stack = col().key("stack").w_full().growth(GrowthSpec::default()); + if s.virtual_list { stack = stack.virtualize(40.0); } + for i in 0..40 { + let mut r = col().key(format!("r{i}")).w_full().h(40.0).child(text(format!("row {i}")).key(format!("t{i}"))); + if s.copied && (i == 0 || i == 39) { r = r.child(text("Copied").key(format!("chip{i}")).transition(Transition::opacity())); } + stack = stack.child(r); + } + col().w_full().h_full().child(col().key("scroll").w_full().h(200.0).scroll(ScrollSpec { stick_bottom: true }).child(stack)) +} + +#[test] +fn late_children_of_a_shown_row_play_their_transition() { + for virtual_list in [false, true] { + let name = format!("virtual {virtual_list}"); + let mut rt = Runtime::new(Chips { virtual_list, copied: false }, chips, (300.0, 300.0), Env::new(true, 1.0)); + rt.frame(0.0); + rt.update(|s, _| s.copied = true); + rt.frame(1.0 / 60.0); + let chip = rt.elements().into_iter().find(|e| e.key.as_deref() == Some("chip39")).unwrap(); + assert!(chip.opacity < 0.5, "{name}: the chip fades in, at {}", chip.opacity); + for _ in 0..90 { rt.frame(1.0 / 60.0); } + let chip = rt.elements().into_iter().find(|e| e.key.as_deref() == Some("chip39")).unwrap(); + assert_eq!(chip.opacity, 1.0, "{name}: settles"); + + if virtual_list { + for _ in 0..4 { + rt.wheel(150.0, 100.0, 1000.0); + rt.frame(1.0 / 60.0); + } + let chip = rt.elements().into_iter().find(|e| e.key.as_deref() == Some("chip0")).expect("scrolled back to the top"); + assert_eq!(chip.opacity, 1.0, "{name}: a remounted row's chip doesn't replay its entrance"); + } + } +} + +fn nested(_: &(), _: &mut Cx<()>) -> El { + let mut inner = col().key("inner-stack").w_full().growth(GrowthSpec::default()).virtualize(40.0); + for i in 0..80 { + inner = inner.child(col().key(format!("i{i}")).w_full().h(40.0) + .transition(Transition::offset(0.0, 12.0).combined(Transition::opacity())) + .child(text(format!("inner {i}")))); + } + let inner = col().key("inner").w_full().h(150.0).scroll(ScrollSpec { stick_bottom: true }).child(inner); + let outer = col().key("outer-stack").w_full().growth(GrowthSpec::default()).virtualize(100.0) + .child(col().key("o0").w_full().h(100.0)) + .child(col().key("o1").w_full().h(100.0)) + .child(col().key("o2").w_full().child(inner)); + col().w_full().h_full().child(col().key("outer").w_full().h(300.0).scroll(ScrollSpec { stick_bottom: true }).child(outer)) +} + +#[test] +fn rows_scrolled_into_a_nested_virtual_list_mount_settled() { + let mut rt = Runtime::new((), nested, (300.0, 300.0), Env::new(true, 1.0)); + rt.frame(0.0); + for _ in 0..30 { rt.frame(1.0 / 60.0); } + let get = |rt: &Runtime<()>, key: &str| rt.elements().into_iter().find(|e| e.key.as_deref() == Some(key)); + assert!(get(&rt, "i0").is_none(), "the inner list's top row starts culled"); + let inner = get(&rt, "inner").unwrap(); + let (x, y) = (inner.rect[0] + inner.rect[2] / 2.0, inner.rect[1] + inner.rect[3] / 2.0); + for _ in 0..6 { + rt.wheel(x, y, 1000.0); + rt.frame(1.0 / 60.0); + } + let top = get(&rt, "i0").expect("scrolled the inner list to its top"); + assert_eq!(top.opacity, 1.0, "a remounted inner row doesn't replay its entrance"); + let stack = get(&rt, "inner-stack").unwrap(); + assert_eq!((top.rect[1], top.rect[3]), (stack.rect[1], 40.0), "nor slide or grow: {:?} in {:?}", top.rect, stack.rect); +} diff --git a/app/vendor/rune/crates/rune/tests/integration/script_double_click.rs b/app/vendor/rune/crates/rune/tests/integration/script_double_click.rs new file mode 100644 index 0000000..33d1803 --- /dev/null +++ b/app/vendor/rune/crates/rune/tests/integration/script_double_click.rs @@ -0,0 +1,34 @@ +//! A `double-click` script event drives `on_double_press` on the virtual clock, and `on_press` +//! still runs for each of its presses. +use rune::*; + +#[derive(Default)] +struct State { presses: u32, doubles: u32 } + +fn view(s: &State, _: &mut Cx<State>) -> El { + col().w_full().h_full() + .child(el().key("row").size(100.0, 40.0) + .on_press(|s: &mut State| s.presses += 1) + .on_double_press(|s: &mut State| s.doubles += 1)) + .child(text(format!("presses {} doubles {}", s.presses, s.doubles)).key("out")) +} + +#[test] +fn a_double_click_event_runs_on_double_press() { + let dir = std::env::temp_dir().join(format!("rune-script-double-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let (script, tree) = (dir.join("script.json"), dir.join("tree.json")); + std::fs::write(&script, r#"[ + {"t": 0.1, "type": "double-click", "key": "row"}, + {"t": 1.0, "type": "click", "key": "row"}, + {"t": 2.0, "type": "click", "key": "row"} + ]"#).unwrap(); + App::new(AppSpec::new("double", (200.0, 200.0), State::default, view)) + .args(["--script", script.to_str().unwrap(), "--tree", tree.to_str().unwrap()].map(String::from)) + .run(); + let tree: serde_json::Value = serde_json::from_str(&std::fs::read_to_string(&tree).unwrap()).unwrap(); + std::fs::remove_dir_all(&dir).unwrap(); + let out = tree["elements"].as_array().unwrap().iter().find(|e| e["key"] == "out").unwrap(); + // Two separate clicks a second apart are not a pair. + assert_eq!(out["text"], "presses 4 doubles 1"); +} diff --git a/app/vendor/rune/crates/rune/tests/integration/script_links.rs b/app/vendor/rune/crates/rune/tests/integration/script_links.rs new file mode 100644 index 0000000..aa8d217 --- /dev/null +++ b/app/vendor/rune/crates/rune/tests/integration/script_links.rs @@ -0,0 +1,37 @@ +//! `--script` taps a link (`El::link`) by its id, as it taps an element by key. A wrapped link +//! is tapped on its first line. +use rune::*; + +const TEXT: &str = "see docs or a very long link that wraps"; + +fn at(part: &str) -> std::ops::Range<usize> { + let i = TEXT.find(part).unwrap(); + i..i + part.len() +} + +fn view(opened: &Vec<String>, _: &mut Cx<Vec<String>>) -> El { + col().w_full().h_full().padding(10.0).gap(10.0) + .child(rich(TEXT, Vec::new()).key("message").font(TextStyle::new(14.0, 400.0).lh(20.0)).w(120.0) + .link(Link::new(at("docs"), "https://docs.dev/a")) + .link(Link::new(at("a very long link"), "long")) + .on_link(|s: &mut Vec<String>, id, _| s.push(id.to_owned()))) + .child(text(format!("opened {}", opened.join(","))).key("opened")) +} + +#[test] +fn script_taps_links_by_id() { + let dir = std::env::temp_dir().join(format!("rune-script-links-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let (script, tree) = (dir.join("script.json"), dir.join("tree.json")); + std::fs::write(&script, r#"[ + {"t": 0.1, "type": "tap", "key": "https://docs.dev/a"}, + {"t": 0.3, "type": "tap", "key": "long"} + ]"#).unwrap(); + App::new(AppSpec::new("links", (300.0, 200.0), Vec::new, view)) + .args(["--script", script.to_str().unwrap(), "--tree", tree.to_str().unwrap()].map(String::from)) + .run(); + let tree: serde_json::Value = serde_json::from_str(&std::fs::read_to_string(&tree).unwrap()).unwrap(); + std::fs::remove_dir_all(&dir).unwrap(); + let opened = tree["elements"].as_array().unwrap().iter().find(|e| e["key"] == "opened").unwrap(); + assert_eq!(opened["text"], "opened https://docs.dev/a,long"); +} diff --git a/app/vendor/rune/crates/rune/tests/integration/script_t0.rs b/app/vendor/rune/crates/rune/tests/integration/script_t0.rs new file mode 100644 index 0000000..857c53a --- /dev/null +++ b/app/vendor/rune/crates/rune/tests/integration/script_t0.rs @@ -0,0 +1,39 @@ +//! `--script` events at t = 0 run once the first frame is laid out, so they find elements by +//! key and hit them by position like later events. +use rune::*; + +#[derive(Default)] +struct State { taps: Vec<&'static str>, typed: String } + +fn view(s: &State, _: &mut Cx<State>) -> El { + col().w_full().h_full() + .child(el().key("a").size(100.0, 40.0).on_press(|s: &mut State| s.taps.push("a"))) + .child(el().key("b").size(100.0, 40.0).on_press(|s: &mut State| s.taps.push("b"))) + .child(text(format!("taps {} typed {}", s.taps.join(","), s.typed)).key("out")) +} + +fn on_key(s: &mut State, k: &KeyEvent, _: &mut Tx) -> bool { + if let Key::Text(t) = &k.key { s.typed.push_str(t); } + true +} + +#[test] +fn script_events_at_t_zero_see_the_first_layout() { + let dir = std::env::temp_dir().join(format!("rune-script-t0-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let (script, tree) = (dir.join("script.json"), dir.join("tree.json")); + // An event without "t" is at 0 too. + std::fs::write(&script, r#"[ + {"t": 0.0, "type": "click", "key": "a"}, + {"type": "type", "text": "x"}, + {"t": 0.2, "type": "tap", "x": 50, "y": 60} + ]"#).unwrap(); + let spec = AppSpec { on_key: Some(on_key), ..AppSpec::new("t0", (200.0, 200.0), State::default, view) }; + App::new(spec) + .args(["--script", script.to_str().unwrap(), "--tree", tree.to_str().unwrap()].map(String::from)) + .run(); + let tree: serde_json::Value = serde_json::from_str(&std::fs::read_to_string(&tree).unwrap()).unwrap(); + std::fs::remove_dir_all(&dir).unwrap(); + let out = tree["elements"].as_array().unwrap().iter().find(|e| e["key"] == "out").unwrap(); + assert_eq!(out["text"], "taps a,b typed x"); +} diff --git a/app/vendor/rune/crates/rune/tests/integration/script_text_selection.rs b/app/vendor/rune/crates/rune/tests/integration/script_text_selection.rs new file mode 100644 index 0000000..b4080cf --- /dev/null +++ b/app/vendor/rune/crates/rune/tests/integration/script_text_selection.rs @@ -0,0 +1,42 @@ +//! `--script` drags, double-clicks and triple-clicks selectable text, and `--tree` reports each +//! element's selected text. +use rune::*; + +const CMD: &str = "opencode serve --port 4096"; +const PARA: &str = "first line\nsecond line\nthird"; + +fn view(_: &(), _: &mut Cx<()>) -> El { + let style = TextStyle::new(14.0, 400.0).lh(20.0); + col().w_full().h_full().padding(10.0).gap(10.0) + .child(text(CMD).key("cmd").font(style.mono()).self_start().selectable(true)) + .child(text(PARA).key("para").font(style).self_start().selectable(true)) +} + +/// Runs `events` and returns each keyed element's selected text. +fn run(events: &str, name: &str) -> Vec<(String, String)> { + let dir = std::env::temp_dir().join(format!("rune-script-select-{name}-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let (script, tree) = (dir.join("script.json"), dir.join("tree.json")); + std::fs::write(&script, events).unwrap(); + App::new(AppSpec::new("select", (300.0, 200.0), || (), view)) + .args(["--script", script.to_str().unwrap(), "--tree", tree.to_str().unwrap()].map(String::from)) + .run(); + let tree: serde_json::Value = serde_json::from_str(&std::fs::read_to_string(&tree).unwrap()).unwrap(); + std::fs::remove_dir_all(&dir).unwrap(); + tree["elements"].as_array().unwrap().iter() + .filter_map(|e| Some((e["key"].as_str()?.to_owned(), e["selected"].as_str()?.to_owned()))) + .collect() +} + +fn selected(key: &str, text: &str) -> Vec<(String, String)> { vec![(key.to_owned(), text.to_owned())] } + +#[test] +fn script_events_select_text() { + // Events aim at the element's centre: inside "serve", and on the middle line. + // A drag from there past the end selects the rest of the line. + let dragged = run(r#"[{"t": 0.1, "type": "drag", "key": "cmd", "dx": 150, "dy": 0}]"#, "drag"); + let [(key, text)] = &dragged[..] else { panic!("{dragged:?}") }; + assert!(key == "cmd" && text.ends_with("e --port 4096") && CMD[9..].ends_with(text.as_str()), "{text:?}"); + assert_eq!(run(r#"[{"t": 0.1, "type": "double-click", "key": "cmd"}]"#, "double"), selected("cmd", "serve")); + assert_eq!(run(r#"[{"t": 0.1, "type": "triple-click", "key": "para"}]"#, "triple"), selected("para", "second line\n")); +} diff --git a/app/vendor/rune/crates/rune/tests/integration/scroll_anchor.rs b/app/vendor/rune/crates/rune/tests/integration/scroll_anchor.rs new file mode 100644 index 0000000..9f06564 --- /dev/null +++ b/app/vendor/rune/crates/rune/tests/integration/scroll_anchor.rs @@ -0,0 +1,74 @@ +//! `El::scroll_anchor`: rows inserted or grown above the view leave the row at its top where +//! it was; without it, or at the very top, the content moves, and a viewport stuck to its +//! bottom keeps following it. +use rune::{Cx, El, Env, Runtime, ScrollSpec, col, el}; + +#[derive(Clone, Copy)] +struct Feed { + /// Rows added above the first. + above: usize, + /// Height of the first row. + first_h: f32, + /// Rows added below the last. + below: usize, + anchor: bool, + stick_bottom: bool, +} + +fn view(s: &Feed, _: &mut Cx<Feed>) -> El { + let rows = (0..s.above).map(|k| el().key(format!("new{k}")).w_full().h(30.0)) + .chain(std::iter::once(el().key("r0").w_full().h(s.first_h))) + .chain((1..30 + s.below).map(|k| el().key(format!("r{k}")).w_full().h(40.0))); + let list = col().key("list").w_full().children(rows.collect::<Vec<_>>()); + let viewport = col().key("scroll").size(300.0, 200.0).scroll(ScrollSpec { stick_bottom: s.stick_bottom }).child(list); + if s.anchor { viewport.scroll_anchor() } else { viewport } +} + +fn top_of(rt: &Runtime<Feed>, key: &str) -> f32 { + rt.elements().into_iter().find(|e| e.key.as_deref() == Some(key) && !e.exiting).unwrap().rect[1] +} + +/// Scrolls to `at`, applies `change`, and returns where row 5's top was and is. +fn shift(feed: Feed, at: f32, change: impl FnOnce(&mut Feed) + 'static) -> (f32, f32) { + let mut rt = Runtime::new(feed, view, (300.0, 200.0), Env::new(true, 1.0)); + rt.frame(0.0); + rt.update(move |_, tx| tx.scroll_to_instant("scroll", 0.0, at)); + for _ in 0..4 { rt.frame(1.0 / 120.0); } + let before = top_of(&rt, "r5"); + rt.update(move |s, _| change(s)); + for _ in 0..60 { rt.frame(1.0 / 120.0); } + (before, top_of(&rt, "r5")) +} + +const FEED: Feed = Feed { above: 0, first_h: 40.0, below: 0, anchor: true, stick_bottom: false }; + +#[test] +fn rows_inserted_above_leave_the_top_row_in_place() { + let (before, after) = shift(FEED, 150.0, |s| s.above = 3); + assert!((after - before).abs() < 0.5, "r5 moved from {before} to {after}"); +} + +#[test] +fn a_row_above_that_grows_leaves_the_top_row_in_place() { + let (before, after) = shift(FEED, 150.0, |s| s.first_h = 140.0); + assert!((after - before).abs() < 0.5, "r5 moved from {before} to {after}"); +} + +#[test] +fn without_the_anchor_the_rows_move_down() { + let (before, after) = shift(Feed { anchor: false, ..FEED }, 150.0, |s| s.above = 3); + assert!((after - before - 90.0).abs() < 0.5, "r5 moved from {before} to {after}"); +} + +#[test] +fn at_the_very_top_new_rows_show() { + let (before, after) = shift(FEED, 0.0, |s| s.above = 3); + assert!((after - before - 90.0).abs() < 0.5, "r5 moved from {before} to {after}"); +} + +#[test] +fn a_viewport_following_its_bottom_keeps_following_it() { + let (before, after) = shift(Feed { stick_bottom: true, ..FEED }, 10_000.0, |s| s.below = 3); + assert!((after - before + 120.0).abs() < 0.5, "r5 moved from {before} to {after}"); +} + diff --git a/app/vendor/rune/crates/rune/tests/integration/scroll_edge_fade.rs b/app/vendor/rune/crates/rune/tests/integration/scroll_edge_fade.rs new file mode 100644 index 0000000..512cc99 --- /dev/null +++ b/app/vendor/rune/crates/rune/tests/integration/scroll_edge_fade.rs @@ -0,0 +1,131 @@ +//! `El::scroll_edge_fade`: each edge fades only while content is hidden under it, at strength +//! hidden / 15 pt. `El::scroll_margin`: revealed rows stop clear of the fade. +use rune::render::{Gpu, OFFSCREEN_FORMAT, Offscreen, Renderer, unpack_fade}; +use rune::{Color, Cx, El, Env, GrowthSpec, Runtime, ScrollSpec, col, el}; + +const SCALE: f32 = 2.0; +const FADE: f32 = 24.0; + +#[derive(Default)] +struct List { rows: usize, selected: usize, stick: bool, virtual_list: bool, margin: f32 } + +fn view(s: &List, _: &mut Cx<List>) -> El { + let mut stack = col().w_full(); + if s.virtual_list { stack = stack.growth(GrowthSpec::default()).virtualize(20.0); } + for i in 0..s.rows { + let fill = if i == s.selected { Color::WHITE } else { Color::WHITE.alpha(0.999) }; + stack = stack.child(el().key(format!("row{i}")).w_full().h(20.0).fill(fill)); + } + col().w_full().h_full().child(col().key("scroll").w_full().h(200.0) + .scroll(ScrollSpec { stick_bottom: s.stick }) + .scroll_edge_fade(FADE).scroll_margin(s.margin) + .child(stack)) +} + +fn list(s: List) -> Runtime<List> { + let mut rt = Runtime::new(s, view, (200.0, 300.0), Env::new(true, SCALE)); + rt.frame(0.0); + rt +} + +/// The (top, bottom) fade widths in device px and their ramp offsets on the rows' fill. +fn edges(rt: &Runtime<List>) -> ([f32; 2], [f32; 2]) { + let row = rt.instances.iter().find(|i| i.fill[3] > 0.99).expect("a row"); + assert!(rt.instances.iter().all(|i| i.fade[3] == 0), "fade[3] stays reserved for the layer clip radius"); + let (w, o) = unpack_fade(row.fade); + ([w[1], w[3]], [o[1], o[3]]) +} + +fn settle(rt: &mut Runtime<List>) { + for _ in 0..120 { if !rt.frame(1.0 / 60.0) { return; } } + panic!("never settled"); +} + +#[test] +fn each_edge_fades_only_once_content_is_hidden_under_it() { + let mut rt = list(List { rows: 40, ..Default::default() }); + let (w, o) = edges(&rt); + assert_eq!(w[0], 0.0, "nothing above: a hard top edge"); + assert_eq!((w[1], o[1]), (FADE * SCALE, 0.0), "rows below: the full bottom fade"); + + // 7.5 pt hidden is half strength: the ramp starts halfway in and ends a full width in. + rt.wheel(100.0, 100.0, -7.5); + rt.frame(1.0 / 60.0); + let (w, o) = edges(&rt); + assert!((o[0] - 0.5).abs() < 0.01 && ((1.0 - o[0]) * w[0] - FADE * SCALE).abs() < 0.5, "half strength: {w:?} {o:?}"); + rt.wheel(100.0, 100.0, -7.5); + rt.frame(1.0 / 60.0); + assert_eq!(edges(&rt), ([FADE * SCALE; 2], [0.0; 2]), "15 pt hidden: full strength"); + + rt.wheel(100.0, 100.0, -10_000.0); + rt.frame(1.0 / 60.0); + assert_eq!(edges(&rt).0, [FADE * SCALE, 0.0], "at the bottom: a hard bottom edge"); + assert!(!rt.frame(1.0 / 60.0), "no extra frames at rest"); +} + +#[test] +fn stuck_and_virtual_lists_follow_their_bottom() { + let rt = list(List { rows: 40, stick: true, ..Default::default() }); + assert_eq!(edges(&rt).0, [FADE * SCALE, 0.0], "stick-to-bottom opens with a hard bottom edge"); + + // A virtual list fades against its estimated extent before the tail is ever measured. + let mut rt = list(List { rows: 400, virtual_list: true, ..Default::default() }); + assert_eq!(edges(&rt).0, [0.0, FADE * SCALE]); + rt.update(|_, tx| tx.scroll_to_bottom_instant("scroll")); + settle(&mut rt); + assert_eq!(edges(&rt).0, [FADE * SCALE, 0.0]); +} + +#[test] +fn keyboard_selection_stops_clear_of_the_fade() { + let mut rt = list(List { rows: 40, margin: FADE, ..Default::default() }); + let viewport = rt.elements().into_iter().find(|e| e.key.as_deref() == Some("scroll")).unwrap().rect; + let row = |rt: &Runtime<List>, i: usize| rt.elements().into_iter().find(|e| e.key.as_deref() == Some(&*format!("row{i}"))).unwrap().rect; + // What an arrow-key handler does: move the selection and reveal it. + let step = |rt: &mut Runtime<List>, down: bool| { + rt.update(|s, tx| { + s.selected = if down { s.selected + 1 } else { s.selected - 1 }; + tx.scroll_into_view(format!("row{}", s.selected)); + }); + rt.frame(1.0 / 60.0); + }; + for _ in 0..12 { step(&mut rt, true); } + settle(&mut rt); + let r = row(&rt, 12); + assert!((viewport[1] + viewport[3] - (r[1] + r[3]) - FADE).abs() < 0.01, "row 12 stops {FADE} pt above the bottom: {r:?} in {viewport:?}"); + for _ in 0..8 { step(&mut rt, false); } + settle(&mut rt); + let r = row(&rt, 4); + assert!((r[1] - viewport[1] - FADE).abs() < 0.01, "row 4 stops {FADE} pt below the top: {r:?}"); + for _ in 0..4 { step(&mut rt, false); } + settle(&mut rt); + assert_eq!(row(&rt, 0)[1], viewport[1], "the first row still lands flush, where nothing is hidden"); + assert_eq!(edges(&rt).0[0], 0.0, "so the top edge is hard and the selection unfaded"); +} + +#[test] +fn edge_pixels_fade_by_the_hidden_extent() { + let gpu = Gpu::headless(); + let mut renderer = Renderer::new(&gpu.device, OFFSCREEN_FORMAT); + let size = ((200.0 * SCALE) as u32, (300.0 * SCALE) as u32); + let target = Offscreen::new(&gpu.device, size.0, size.1); + let mut alpha_at = |rt: &mut Runtime<List>, y: f32| { + renderer.prepare(&gpu.device, &gpu.queue, &mut rt.text.atlas, &rt.instances, size); + let mut encoder = gpu.device.create_command_encoder(&Default::default()); + renderer.draw(&mut encoder, &target.view, [0.0; 4]); + target.copy(&mut encoder); + gpu.queue.submit([encoder.finish()]); + let px = target.read(&gpu.device); + let row = (y * SCALE) as usize; + px[(row * size.0 as usize + 40) * 4 + 3] + }; + // The selected first row: fully opaque at the top edge until something scrolls under it. + let mut rt = list(List { rows: 40, ..Default::default() }); + assert_eq!(alpha_at(&mut rt, 0.25), 255, "nothing hidden above: the top row is untouched"); + assert!(alpha_at(&mut rt, 199.75) < 10, "rows hidden below: the bottom edge is faded out"); + rt.wheel(100.0, 100.0, -7.5); + rt.frame(1.0 / 60.0); + let half = alpha_at(&mut rt, 0.25); + assert!((110..=145).contains(&half), "half strength leaves about half alpha at the edge: {half}"); + assert_eq!(alpha_at(&mut rt, FADE + 0.5), 255, "and is done a full fade width in"); +} diff --git a/app/vendor/rune/crates/rune/tests/integration/scroll_to.rs b/app/vendor/rune/crates/rune/tests/integration/scroll_to.rs new file mode 100644 index 0000000..aad620a --- /dev/null +++ b/app/vendor/rune/crates/rune/tests/integration/scroll_to.rs @@ -0,0 +1,179 @@ +//! `Tx::scroll_to`, `Tx::scroll_to_instant` and `Tx::scroll_to_y`: moving a viewport to an +//! offset the app picked, gliding or at once, clamped, on virtual rows too; and +//! `Tx::scroll_key_to`, landing a row at a height in its viewport. +use rune::{Cx, El, Env, GrowthSpec, Runtime, ScrollSpec, col, el, row}; + +#[derive(Default)] +struct S { list: bool, virtual_rows: bool, rows: usize } + +fn view(s: &S, _: &mut Cx<S>) -> El { + if s.virtual_rows { + let rows = col().key("rows").growth(GrowthSpec::default()) + .virtual_rows(100, 40.0, |_: &S, i| format!("r{i}").into(), |_: &S, _| el().w_full().h(40.0)); + return col().w_full().h_full().child(col().key("list").w_full().h(200.0).scroll(ScrollSpec { stick_bottom: false }).child(rows)); + } + if s.list { + let rows = (0..s.rows).fold(col().w_full(), |c, i| c.child(el().key(format!("row{i}")).w_full().h(40.0))); + return col().w_full().h_full().child(col().key("list").w_full().h(200.0).scroll(ScrollSpec { stick_bottom: true }).child(rows)); + } + // A 600 x 600 pt board in a 300 x 200 pt viewport: 300 across and 400 down to scroll. + let board = (0..6).fold(col(), |c, r| c.child( + (0..6).fold(row(), |row, i| row.child(el().key(format!("cell{r}-{i}")).w(100.0).h(100.0))))); + col().w_full().h_full().child(col().key("board").w_full().h(200.0).scroll_xy().child(board)) +} + +fn app(s: S) -> Runtime<S> { + let mut rt = Runtime::new(s, view, (300.0, 300.0), Env::new(true, 1.0)); + rt.frame(0.0); + rt +} + +fn at(rt: &Runtime<S>, key: &str) -> (f32, f32) { + let e = rt.elements().into_iter().find(|e| e.key.as_deref() == Some(key)).unwrap_or_else(|| panic!("{key}")); + (e.rect[0], e.rect[1]) +} + +fn settle(rt: &mut Runtime<S>) -> usize { + for n in 0..600 { if !rt.frame(1.0 / 60.0) { return n; } } + panic!("never settled"); +} + +#[test] +fn scroll_to_glides_both_axes_and_lands_clamped() { + let mut rt = app(S::default()); + rt.update(|_, tx| tx.scroll_to("board", 150.0, 250.0)); + rt.frame(1.0 / 60.0); + let (x, y) = at(&rt, "cell0-0"); + assert!(x < 0.0 && x > -150.0 && y < 0.0 && y > -250.0, "on its way, not there: {x}, {y}"); + assert!(settle(&mut rt) > 5, "a glide, not a jump"); + assert_eq!(at(&rt, "cell0-0"), (-150.0, -250.0)); + + rt.update(|_, tx| tx.scroll_to("cell2-2", 9_999.0, -50.0)); + settle(&mut rt); + assert_eq!(at(&rt, "cell0-0"), (-300.0, 0.0), "a key inside finds its viewport; each axis clamps"); +} + +#[test] +fn scroll_to_instant_jumps_and_a_wheel_takes_over_a_glide() { + let mut rt = app(S::default()); + rt.update(|_, tx| tx.scroll_to_instant("board", 100.0, 120.0)); + rt.frame(1.0 / 60.0); + assert_eq!(at(&rt, "cell0-0"), (-100.0, -120.0)); + + rt.update(|_, tx| tx.scroll_to("board", 0.0, 400.0)); + for _ in 0..3 { rt.frame(1.0 / 60.0); } + let (_, y) = at(&rt, "cell0-0"); + rt.wheel_xy(150.0, 100.0, 0.0, 30.0); + rt.frame(1.0 / 60.0); + settle(&mut rt); + let (_, landed) = at(&rt, "cell0-0"); + assert!(landed > -400.0 && (landed - (y + 30.0)).abs() < 1.0, "the wheel stopped the glide where it was: {y} then {landed}"); +} + +#[test] +fn a_vertical_list_takes_y_alone_and_follows_its_end_again_once_sent_there() { + let mut rt = app(S { list: true, rows: 20, ..S::default() }); + assert_eq!(at(&rt, "row19").1, 160.0, "stick_bottom opens at the end"); + rt.update(|_, tx| tx.scroll_to_y("list", 80.0)); + rt.frame(1.0 / 60.0); + assert_eq!(at(&rt, "row0").1, -80.0); + rt.update(|s, _| s.rows = 21); + rt.frame(1.0 / 60.0); + assert_eq!(at(&rt, "row0").1, -80.0, "off the end it stays put as rows arrive"); + + rt.update(|_, tx| tx.scroll_to("row3", 500.0, 9_999.0)); + settle(&mut rt); + assert_eq!(at(&rt, "row20").1, 160.0, "x ignored, y clamped to the end"); + rt.update(|s, _| s.rows = 22); + rt.frame(1.0 / 60.0); + assert_eq!(at(&rt, "row21").1, 160.0, "and the end is followed again"); +} + +#[test] +fn scroll_to_lands_on_virtual_rows_it_mounts() { + let mut rt = app(S { virtual_rows: true, ..S::default() }); + rt.update(|_, tx| tx.scroll_to_instant("list", 0.0, 2_000.0)); + rt.frame(1.0 / 60.0); + assert_eq!(at(&rt, "r50").1, 0.0, "row 50 mounted at the top"); + + rt.update(|_, tx| tx.scroll_to("list", 0.0, 3_000.0)); + settle(&mut rt); + assert_eq!(at(&rt, "r75").1, 0.0); + rt.update(|_, tx| tx.scroll_to("list", 0.0, 99_999.0)); + settle(&mut rt); + assert_eq!(at(&rt, "r99").1, 160.0, "clamped to the end the rows measure"); +} + +#[test] +fn scroll_key_to_lands_a_row_where_asked_in_the_frame_that_builds_it() { + let mut rt = app(S { list: true, rows: 20, ..S::default() }); + rt.update(|s, tx| { + s.rows = 30; + tx.scroll_key_to("row12", 30.0); + }); + rt.frame(1.0 / 60.0); + assert_eq!(at(&rt, "row12").1, 30.0, "placed from the new rows, on the first frame"); + rt.frame(1.0 / 60.0); + assert_eq!(at(&rt, "row12").1, 30.0, "and it stays"); + + rt.update(|_, tx| tx.scroll_key_to("row29", 0.0)); + rt.frame(1.0 / 60.0); + assert_eq!(at(&rt, "row29").1, 160.0, "clamped to the end"); + rt.update(|_, tx| tx.scroll_key_to("row0", 50.0)); + rt.frame(1.0 / 60.0); + assert_eq!(at(&rt, "row0").1, 0.0, "and to the top"); +} + +#[test] +fn scroll_center_mounts_virtual_rows_and_centres_elements_and_text_highlights() { + use rune::{Color, TextHighlight, TextStyle, text}; + + #[derive(Default)] + struct FindS { hit_row: usize } + + fn find_view(_: &FindS, _: &mut Cx<FindS>) -> El { + let rows = col().key("rows").w_full().growth(GrowthSpec::default()) + .virtual_rows(80, 40.0, |_: &FindS, i| format!("r{i}").into(), |s: &FindS, i| { + let mut body = text(format!("line a\nline b\nhit in row {i}\nline d")) + .font(TextStyle::new(14.0, 400.0).lh(20.0)); + if i == s.hit_row { + body = body.text_highlight(TextHighlight::new(14..17, Color::WHITE).key("active-hit")); + } + col().w_full().py(10.0).child(body) + }); + col().w_full().h_full().child(col().key("list").w_full().h(200.0).scroll(ScrollSpec { stick_bottom: false }).child(rows)) + } + + let mut rt = Runtime::new(FindS { hit_row: 40 }, find_view, (300.0, 300.0), Env::new(true, 1.0)); + rt.frame(0.0); + + // `"r40/active-hit"` mounts virtual row `r40` and glides the highlight's 20pt line to the + // middle of the 200pt viewport (y ≈ 90). + rt.update(|_, tx| tx.scroll_center_in("list", "r40/active-hit")); + rt.frame(1.0 / 60.0); + let mut frames = 0; + while rt.frame(1.0 / 60.0) { + frames += 1; + assert!(frames < 600, "glide settled"); + } + assert!(frames > 4, "glided to the match ({frames} frames)"); + let mark = rt.elements().into_iter().find(|e| e.key.as_deref() == Some("active-hit")).expect("active-hit mounted"); + let mid = mark.rect[1] + mark.rect[3] * 0.5; + assert!((mid - 100.0).abs() < 2.0, "highlight centred in 200pt viewport: {mark:?}"); + + // Instant variant lands centred in one frame. + rt.update(|s, tx| { + s.hit_row = 15; + tx.scroll_center_in_instant("list", "r15/active-hit"); + }); + rt.frame(1.0 / 60.0); + let mark = rt.elements().into_iter().find(|e| e.key.as_deref() == Some("active-hit")).expect("r15 active-hit"); + let mid = mark.rect[1] + mark.rect[3] * 0.5; + assert!((mid - 100.0).abs() < 2.0, "instant centre in one frame: {mark:?}"); + + // `scroll_key_to` also resolves `TextHighlight` keys once mounted. + rt.update(|_, tx| tx.scroll_key_to("active-hit", 24.0)); + rt.frame(1.0 / 60.0); + let mark = rt.elements().into_iter().find(|e| e.key.as_deref() == Some("active-hit")).unwrap(); + assert!((mark.rect[1] - 24.0).abs() < 2.0, "scroll_key_to placed TextHighlight at 24pt: {mark:?}"); +} diff --git a/app/vendor/rune/crates/rune/tests/integration/scroll_x.rs b/app/vendor/rune/crates/rune/tests/integration/scroll_x.rs new file mode 100644 index 0000000..cf5422e --- /dev/null +++ b/app/vendor/rune/crates/rune/tests/integration/scroll_x.rs @@ -0,0 +1,333 @@ +//! `El::scroll_x` and `El::scroll_xy`: horizontal offsets, clamping, momentum, the axis a wheel +//! gesture locks to in nested viewports, `Tx::scroll_into_view` and `Tx::scroll_to_x` on x, and +//! left and right edge fades. +use rune::render::{KIND_GLYPH, unpack_fade}; +use rune::{Color, Cx, El, Env, GrowthSpec, Runtime, ScrollSpec, col, el, row, text}; + +const FADE: f32 = 24.0; + +#[derive(Default)] +struct S { nested: bool, xy: bool, prose: bool, widths: bool, virtual_rows: bool } + +/// Ten 100 pt tiles in a 300 pt viewport: 700 pt to scroll. +fn strip() -> El { + let tiles = (0..10).fold(row(), |r, i| r.child(el().key(format!("tile{i}")).w(100.0).h(100.0).fill(Color::WHITE))); + col().key("strip").w_full().h(100.0).scroll_x().scroll_edge_fade(FADE).child(tiles) +} + +fn view(s: &S, _: &mut Cx<S>) -> El { + if s.xy { + let grid = (0..6).fold(col(), |c, r| c.child( + (0..6).fold(row(), |row, i| row.child(el().key(format!("cell{r}-{i}")).w(100.0).h(100.0))))); + return col().w_full().h_full().child(col().key("grid").w_full().h(200.0).scroll_xy().child(grid)); + } + if s.prose { + let line = text("Wrapping text in a horizontal viewport keeps to one line and scrolls instead.").wrap(); + return col().w_full().h_full().child(col().key("line").w(200.0).scroll_x().child(line.key("text"))); + } + if s.widths { + // A set width narrower than the viewport stays; `w_full` content grows past it. + let narrow = col().key("narrow").w_full().h(60.0).scroll_x().child(el().key("small").w(120.0).h(50.0)); + let full = col().key("full").w_full().h(100.0).scroll_xy() + .child(col().key("filled").w_full().child(el().key("wide").w(900.0).h(400.0))); + return col().w_full().h_full().child(narrow).child(full); + } + if s.virtual_rows { + // Virtual rows in a viewport scrolling both ways; row 80 alone reaches far to the right. + let rows = col().key("rows").growth(GrowthSpec::default()).virtual_rows(100, 40.0, |_: &S, i| format!("r{i}").into(), + |_: &S, i| el().w(if i == 80 { 100.0 } else { 400.0 }).ml(if i == 80 { 800.0 } else { 0.0 }).h(40.0)); + return col().w_full().h_full().child(col().key("table").w_full().h(200.0).scroll_xy().child(rows)); + } + if !s.nested { return col().w_full().h_full().child(strip()); } + let rows = (0..20).fold(col().w_full().child(el().key("head").w_full().h(100.0)).child(strip()), + |c, i| c.child(el().key(format!("row{i}")).w_full().h(40.0))); + col().w_full().h_full().child(col().key("page").w_full().h(300.0).scroll(ScrollSpec { stick_bottom: false }).child(rows)) +} + +fn app(s: S) -> Runtime<S> { + let mut rt = Runtime::new(s, view, (300.0, 300.0), Env::new(true, 1.0)); + rt.frame(0.0); + rt +} + +fn x_of(rt: &Runtime<S>, key: &str) -> f32 { + rt.elements().into_iter().find(|e| e.key.as_deref() == Some(key)).unwrap_or_else(|| panic!("{key}")).rect[0] +} + +fn y_of(rt: &Runtime<S>, key: &str) -> f32 { + rt.elements().into_iter().find(|e| e.key.as_deref() == Some(key)).unwrap_or_else(|| panic!("{key}")).rect[1] +} + +fn settle(rt: &mut Runtime<S>) { + for _ in 0..600 { if !rt.frame(1.0 / 60.0) { return; } } + panic!("never settled"); +} + +/// A pause long enough that the next delta starts a new gesture (the headless clock is virtual). +fn new_gesture(rt: &mut Runtime<S>) { rt.frame(0.15); } + +#[test] +fn the_content_takes_its_natural_width_and_scrolls_clamped() { + let mut rt = app(S::default()); + assert_eq!((x_of(&rt, "tile0"), x_of(&rt, "tile9")), (0.0, 900.0), "tiles keep their widths past the viewport"); + + rt.wheel_xy(150.0, 50.0, -50.0, 0.0); + rt.frame(1.0 / 60.0); + assert_eq!(x_of(&rt, "tile0"), -50.0); + + new_gesture(&mut rt); + rt.wheel_xy(150.0, 50.0, -10_000.0, 0.0); + rt.frame(1.0 / 60.0); + assert_eq!(x_of(&rt, "tile9"), 200.0, "clamped at the right end"); + new_gesture(&mut rt); + rt.wheel_xy(150.0, 50.0, 10_000.0, 0.0); + rt.frame(1.0 / 60.0); + assert_eq!(x_of(&rt, "tile0"), 0.0, "clamped at the left end"); + assert!(!rt.frame(1.0 / 60.0), "no extra frames at rest"); +} + +#[test] +fn a_vertical_wheel_over_a_horizontal_only_viewport_does_not_move_it() { + let mut rt = app(S::default()); + rt.wheel(150.0, 50.0, -50.0); + rt.wheel_xy(150.0, 50.0, 0.0, -50.0); + rt.frame(1.0 / 60.0); + assert_eq!(x_of(&rt, "tile0"), 0.0); +} + +#[test] +fn a_gesture_locks_to_its_first_axis_in_nested_viewports() { + let mut rt = app(S { nested: true, ..S::default() }); + let (tile, head) = (x_of(&rt, "tile0"), y_of(&rt, "head")); + + // Mostly vertical over the filmstrip: the page scrolls, the strip stays, and the rest of + // the gesture stays vertical even once it turns sideways. + rt.wheel_began(); + rt.wheel_xy(150.0, 150.0, -3.0, -20.0); + rt.wheel_xy(150.0, 150.0, -40.0, -1.0); + rt.wheel_ended(); + rt.frame(1.0 / 60.0); + assert_eq!((x_of(&rt, "tile0"), y_of(&rt, "head")), (tile, head - 21.0)); + + // Mostly horizontal: the strip scrolls and the page stays, through the gesture's momentum + // (a phase that begins as the touch ends), even once the pointer leaves the strip. + new_gesture(&mut rt); + rt.wheel_began(); + let strip_at = y_of(&rt, "tile0") + 50.0; + rt.wheel_xy(150.0, strip_at, -20.0, -3.0); + rt.wheel_xy(150.0, 280.0, -1.0, -30.0); + rt.wheel_ended(); + rt.wheel_began(); + rt.wheel_xy(150.0, 280.0, -10.0, -10.0); + rt.wheel_ended(); + rt.frame(1.0 / 60.0); + assert_eq!((x_of(&rt, "tile0"), y_of(&rt, "head")), (tile - 31.0, head - 21.0)); + + // Without phases (a mouse wheel), a pause ends the gesture. + new_gesture(&mut rt); + rt.wheel_xy(150.0, strip_at, 0.0, -10.0); + rt.frame(1.0 / 60.0); + assert_eq!((x_of(&rt, "tile0"), y_of(&rt, "head")), (tile - 31.0, head - 31.0)); +} + +#[test] +fn a_horizontal_gesture_outside_any_horizontal_viewport_scrolls_vertically() { + let mut rt = app(S { nested: true, ..S::default() }); + let head = y_of(&rt, "head"); + rt.wheel_xy(150.0, 280.0, -30.0, -5.0); + rt.frame(1.0 / 60.0); + assert_eq!(y_of(&rt, "head"), head - 5.0, "the vertical part moves the page"); +} + +#[test] +fn a_horizontal_fling_decays_and_clamps() { + let mut rt = app(S::default()); + rt.fling_xy(150.0, 50.0, -1200.0, 100.0); + rt.frame(1.0 / 60.0); + let early = x_of(&rt, "tile0"); + assert!(early < 0.0, "{early}"); + settle(&mut rt); + let rest = x_of(&rt, "tile0"); + assert!(rest < early && rest >= -700.0, "{early} {rest}"); + + rt.fling_xy(150.0, 50.0, -20_000.0, 0.0); + settle(&mut rt); + assert_eq!(x_of(&rt, "tile9"), 200.0, "momentum stops at the end"); + assert!(rt.events.iter().any(|e| e.starts_with("fling-x")), "{:?}", rt.events); +} + +#[test] +fn scroll_into_view_and_scroll_to_x_move_the_horizontal_offset() { + let mut rt = app(S::default()); + rt.update(|_, tx| tx.scroll_into_view("tile6")); + rt.frame(1.0 / 60.0); + assert_eq!(x_of(&rt, "tile6"), 200.0, "just far enough to show it at the right edge"); + rt.update(|_, tx| tx.scroll_into_view("tile1")); + rt.frame(1.0 / 60.0); + assert_eq!(x_of(&rt, "tile1"), 0.0, "back to its left edge"); + + rt.update(|_, tx| tx.scroll_to_x("strip", 250.0)); + rt.frame(1.0 / 60.0); + assert_eq!(x_of(&rt, "tile0"), -250.0); + rt.update(|_, tx| tx.scroll_to_x("tile3", 9_999.0)); + rt.frame(1.0 / 60.0); + assert_eq!(x_of(&rt, "tile0"), -700.0, "a key inside finds its viewport; clamped"); +} + +#[test] +fn scroll_xy_scrolls_both_axes_one_gesture_at_a_time() { + let mut rt = app(S { xy: true, ..S::default() }); + rt.wheel_xy(150.0, 100.0, -40.0, -10.0); + rt.frame(1.0 / 60.0); + assert_eq!((x_of(&rt, "cell0-0"), y_of(&rt, "cell0-0")), (-40.0, 0.0)); + new_gesture(&mut rt); + rt.wheel_xy(150.0, 100.0, -10.0, -60.0); + rt.frame(1.0 / 60.0); + assert_eq!((x_of(&rt, "cell0-0"), y_of(&rt, "cell0-0")), (-40.0, -60.0)); + rt.update(|_, tx| tx.scroll_into_view("cell5-5")); + rt.frame(1.0 / 60.0); + assert_eq!((x_of(&rt, "cell5-5"), y_of(&rt, "cell5-5")), (200.0, 100.0)); +} + +/// The (left, right) fade widths in device px of the tiles' fill. +fn sides(rt: &Runtime<S>) -> [f32; 2] { + let tile = rt.instances.iter().find(|i| i.fill[3] > 0.99).expect("a tile"); + let (w, _) = unpack_fade(tile.fade); + assert_eq!((w[1], w[3]), (0.0, 0.0), "no top or bottom fade on a horizontal-only viewport"); + [w[0], w[2]] +} + +#[test] +fn left_and_right_edges_fade_only_over_hidden_content() { + let mut rt = app(S::default()); + assert_eq!(sides(&rt), [0.0, FADE]); + rt.wheel_xy(150.0, 50.0, -15.0, 0.0); + rt.frame(1.0 / 60.0); + assert_eq!(sides(&rt), [FADE, FADE]); + rt.update(|_, tx| tx.scroll_to_x("strip", 700.0)); + rt.frame(1.0 / 60.0); + assert_eq!(sides(&rt), [FADE, 0.0]); +} + +#[test] +fn wrapping_text_inside_keeps_to_one_line_and_the_viewport_fits_it() { + let rt = app(S { prose: true, ..S::default() }); + let find = |key: &str| rt.elements().into_iter().find(|e| e.key.as_deref() == Some(key)).unwrap().rect; + let (line, text) = (find("line"), find("text")); + assert!(text[2] > 300.0 && text[3] < 30.0, "one unwrapped line: {text:?}"); + assert_eq!(line[3], text[3], "the viewport is one line tall, not the wrapped text's height"); +} + +#[test] +fn a_set_width_stays_and_w_full_content_grows_past_the_viewport() { + let mut rt = app(S { widths: true, ..S::default() }); + let find = |rt: &Runtime<S>, key: &str| rt.elements().into_iter().find(|e| e.key.as_deref() == Some(key)).unwrap().rect; + assert_eq!(find(&rt, "small")[2], 120.0, "not stretched to the viewport's 300"); + assert_eq!(find(&rt, "filled")[2], 900.0, "w_full content takes the width of what it holds"); + let y = find(&rt, "full")[1] + 50.0; + rt.wheel_xy(150.0, y, -40.0, 0.0); + rt.frame(1.0 / 60.0); + assert_eq!(x_of(&rt, "wide"), -40.0); +} + +#[test] +fn scroll_into_view_of_a_virtual_row_reaches_past_the_width_before_it_mounted() { + let mut rt = app(S { virtual_rows: true, ..S::default() }); + rt.update(|_, tx| tx.scroll_into_view("r80")); + rt.frame(1.0 / 60.0); + let row = rt.elements().into_iter().find(|e| e.key.as_deref() == Some("r80")).expect("r80 mounted").rect; + assert_eq!(row[0] + row[2], 300.0, "its right edge shows: {row:?}"); + assert!(row[1] >= 0.0 && row[1] + row[3] <= 200.5, "and it shows vertically: {row:?}"); +} + +/// The strip in the nested view, at (150, y). +fn strip_y(rt: &Runtime<S>) -> f32 { y_of(rt, "tile0") + 50.0 } + +#[test] +fn shift_wheel_then_the_plain_wheel_each_scroll_at_once() { + let mut rt = app(S { nested: true, ..S::default() }); + let (y, tile, head) = (strip_y(&rt), x_of(&rt, "tile0"), y_of(&rt, "head")); + // A mouse wheel: no phases, ticks wholly on one axis, no pause between them. + rt.wheel_xy(150.0, y, -40.0, 0.0); + rt.wheel_xy(150.0, y, 0.0, -10.0); + rt.wheel_xy(150.0, y, 0.0, -10.0); + rt.frame(1.0 / 60.0); + assert_eq!((x_of(&rt, "tile0"), y_of(&rt, "head")), (tile - 40.0, head - 20.0), "Shift let go: the next tick scrolls the page"); + let y = strip_y(&rt); + rt.wheel_xy(150.0, y, -40.0, 0.0); + rt.frame(1.0 / 60.0); + assert_eq!((x_of(&rt, "tile0"), y_of(&rt, "head")), (tile - 80.0, head - 20.0), "Shift held again: the strip at once"); +} + +#[test] +fn a_gesture_whose_end_never_comes_lets_go() { + let mut rt = app(S { nested: true, ..S::default() }); + let (y, head) = (strip_y(&rt), y_of(&rt, "head")); + rt.wheel_began(); + rt.wheel_xy(150.0, y, -30.0, 0.0); + rt.window_focus(false); + rt.wheel_xy(150.0, y, 0.0, -10.0); + rt.frame(1.0 / 60.0); + assert_eq!(y_of(&rt, "head"), head - 10.0, "focus lost mid-gesture"); + + let y = strip_y(&rt); + rt.wheel_began(); + rt.wheel_xy(150.0, y, -30.0, 0.0); + rt.pointer_leave(); + rt.wheel_xy(150.0, y, 0.0, -10.0); + rt.frame(1.0 / 60.0); + assert_eq!(y_of(&rt, "head"), head - 20.0, "the pointer left mid-gesture"); + + let y = strip_y(&rt); + rt.wheel_began(); + rt.wheel_xy(150.0, y, -30.0, 0.0); + rt.frame(1.5); + rt.wheel_xy(150.0, y, 0.0, -10.0); + rt.frame(1.0 / 60.0); + assert_eq!(y_of(&rt, "head"), head - 30.0, "no delta for a second"); +} + +#[test] +fn a_touch_that_stops_momentum_starts_a_new_gesture() { + let mut rt = app(S { nested: true, ..S::default() }); + let (y, tile, head) = (strip_y(&rt), x_of(&rt, "tile0"), y_of(&rt, "head")); + rt.wheel_began(); + rt.wheel_xy(150.0, y, -20.0, 0.0); + rt.wheel_ended(); + rt.wheel_began(); // momentum + rt.wheel_xy(150.0, y, -10.0, -2.0); + rt.wheel_ended(); // a finger caught it + rt.wheel_began(); + rt.wheel_xy(150.0, y, -1.0, -15.0); + rt.wheel_ended(); + rt.frame(1.0 / 60.0); + assert_eq!((x_of(&rt, "tile0"), y_of(&rt, "head")), (tile - 30.0, head - 15.0)); +} + +#[test] +fn a_gesture_begun_outside_the_strip_stays_vertical_over_it() { + // As AppKit latches a gesture to the view it began on. + let mut rt = app(S { nested: true, ..S::default() }); + let (tile, head) = (x_of(&rt, "tile0"), y_of(&rt, "head")); + rt.wheel_began(); + rt.wheel_xy(150.0, 280.0, -30.0, 0.0); + rt.wheel_xy(150.0, strip_y(&rt), -30.0, -1.0); + rt.wheel_ended(); + rt.frame(1.0 / 60.0); + assert_eq!((x_of(&rt, "tile0"), y_of(&rt, "head")), (tile, head - 1.0)); +} + +#[test] +fn glyphs_scrolled_out_of_sight_are_not_drawn() { + let mut rt = app(S { prose: true, ..S::default() }); + let drawn = |rt: &Runtime<S>| rt.instances.iter().filter(|i| i.params[1] == KIND_GLYPH) + .map(|i| (i.rect[0], i.rect[0] + i.rect[2])).collect::<Vec<_>>(); + let all = "Wrapping text in a horizontal viewport keeps to one line and scrolls instead.".chars().filter(|c| !c.is_whitespace()).count(); + for _ in 0..2 { + let glyphs = drawn(&rt); + assert!(!glyphs.is_empty() && glyphs.len() < all * 2 / 3, "{} of {all}", glyphs.len()); + assert!(glyphs.iter().all(|&(a, b)| b >= 0.0 && a <= 200.0), "each draws inside the 200 pt viewport: {glyphs:?}"); + rt.update(|_, tx| tx.scroll_to_x("line", 10_000.0)); + rt.frame(1.0 / 60.0); + } +} diff --git a/app/vendor/rune/crates/rune/tests/integration/selectable_text.rs b/app/vendor/rune/crates/rune/tests/integration/selectable_text.rs new file mode 100644 index 0000000..c059891 --- /dev/null +++ b/app/vendor/rune/crates/rune/tests/integration/selectable_text.rs @@ -0,0 +1,224 @@ +//! Selectable read-only text (`El::selectable`): a drag selects, a double-click takes a word, a +//! triple-click a paragraph and Shift extends; Cmd+C copies, Cmd+A selects all and a right-click +//! offers Copy. Selecting never moves layout, a press elsewhere clears it, links still open, and +//! the highlight is drawn exactly as a text field's. + +use rune::{Color, Cursor, Cx, El, Env, Link, Mods, PhysicalInput, Runtime, Span, TextEdit, TextStyle, col, el, rich, text, text_input}; +use crate::support::{centre, click, command, drag, find, glyphs, tick, wait}; + +const CMD: &str = "opencode --port 4096"; +const PARA: &str = "first line\nsecond line that wraps around"; +const LINKED: &str = "read the docs today"; +const BIDI: &str = "abc שלום def"; + +struct S { field: TextEdit, presses: u32, opened: Vec<String> } + +fn highlight() -> Color { rune::color::hex("#3080ff").unwrap().alpha(0.3) } + +fn view(s: &S, _: &mut Cx<S>) -> El { + let style = TextStyle::new(14.0, 400.0).lh(20.0); + let docs = LINKED.find("docs").unwrap(); + col().w_full().h_full().padding(10.0).gap(10.0) + .child(text(CMD).key("cmd").font(style.mono()).selectable(true).selection_color(highlight())) + .child(rich(PARA, vec![Span { color: Some(Color::WHITE), ..Span::new(0, 5) }]).key("para").font(style).w(140.0) + .selectable(true).selection_color(highlight())) + .child(rich(LINKED, Vec::new()).key("linked").font(style).selectable(true) + .link(Link::new(docs..docs + 4, "docs")) + .on_link(|s: &mut S, id, _| s.opened.push(id.to_owned()))) + .child(text(BIDI).key("bidi").font(style).selectable(true)) + .child(text_input(&s.field, style).key("field").w(200.0).selection_color(highlight()).on_edit(|s: &mut S| &mut s.field)) + .child(el().key("other").size(80.0, 30.0).on_press(|s: &mut S| s.presses += 1)) +} + +fn runtime() -> Runtime<S> { + let mut rt = Runtime::new(S { field: TextEdit::new("field text"), presses: 0, opened: Vec::new() }, view, (500.0, 400.0), Env::new(true, 2.0)); + rt.frame(0.0); + rt +} + +fn rects(rt: &Runtime<S>) -> Vec<(Option<String>, [f32; 4])> { + rt.elements().into_iter().map(|e| (e.key, e.rect)).collect() +} + +/// Instances filled with `c` (the selection boxes): their rect heights and corner radii. +fn boxes(rt: &Runtime<S>, c: Color) -> Vec<(f32, f32)> { + let want = c.premul(1.0); + rt.instances.iter().filter(|i| i.fill.iter().zip(want).all(|(a, b)| (a - b).abs() < 1e-3)).map(|i| (i.rect[3], i.radii[0])).collect() +} + +#[test] +fn drag_double_and_triple_click_select_without_moving_layout() { + let mut rt = runtime(); + let before = rects(&rt); + let g = glyphs(&rt, "cmd"); + assert_eq!(g.len(), CMD.chars().filter(|c| *c != ' ').count(), "one glyph per letter: {g:?}"); + + // The I-beam over selectable text; the text isn't a Tab stop. + rt.pointer_move(g[3].0, g[3].1); + tick(&mut rt); + assert_eq!(rt.cursor(), Cursor::Text); + assert!(!find(&rt, "cmd").focusable); + + // A drag from the left edge of "o" into "port" selects up to the pointer. + let left = find(&rt, "cmd").rect[0] + 0.5; + drag(&mut rt, (left, g[0].1), (g[12].0 + 2.0, g[12].1)); + assert_eq!(rt.selected_text().as_deref(), Some("opencode --por")); + assert_eq!(find(&rt, "cmd").selected.as_deref(), Some("opencode --por"), "tools see the selection"); + assert_eq!(boxes(&rt, highlight()).len(), 1, "one highlight box"); + assert_eq!(rects(&rt), before, "selecting never moves anything"); + wait(&mut rt); + + // Double-click takes the word, triple-click the whole line. + click(&mut rt, g[11]); + click(&mut rt, g[11]); + assert_eq!(rt.selected_text().as_deref(), Some("port")); + click(&mut rt, g[11]); + assert_eq!(rt.selected_text().as_deref(), Some(CMD)); + wait(&mut rt); + + // A double-click drag extends by whole words. + rt.pointer_move(g[1].0, g[1].1); + rt.pointer_down(g[1].0, g[1].1); + rt.pointer_up(g[1].0, g[1].1); + tick(&mut rt); + rt.pointer_down(g[1].0, g[1].1); + tick(&mut rt); + rt.pointer_move(g[11].0, g[11].1); + tick(&mut rt); + rt.pointer_up(g[11].0, g[11].1); + tick(&mut rt); + assert_eq!(rt.selected_text().as_deref(), Some("opencode --port")); + wait(&mut rt); + + // Shift-click extends from the anchor. + click(&mut rt, (left, g[0].1)); + assert_eq!(rt.text_selection().map(|(_, r)| r), Some(0..0)); + assert_eq!(rt.selected_text(), None, "a single click selects nothing"); + rt.physical_input(PhysicalInput::Modifiers(Mods { shift: true, ..Mods::default() })); + click(&mut rt, (g[7].0 + 3.0, g[7].1)); + rt.physical_input(PhysicalInput::Modifiers(Mods::default())); + assert_eq!(rt.selected_text().as_deref(), Some("opencode")); + wait(&mut rt); + + // Triple-click in a wrapped paragraph takes its paragraph, line break included; a drag + // across the wrapped second paragraph highlights each line. + let p = glyphs(&rt, "para"); + click(&mut rt, p[2]); + click(&mut rt, p[2]); + click(&mut rt, p[2]); + assert_eq!(rt.selected_text().as_deref(), Some("first line\n")); + wait(&mut rt); + let second = PARA.find("second").unwrap(); + let last = *p.last().unwrap(); + let start = find(&rt, "para").rect[0] + 0.5; + drag(&mut rt, (start, p[9].1), (last.0 + 4.0, last.1)); + let got = rt.selected_text().unwrap(); + assert!(got.starts_with("second") && got.ends_with("around"), "{got:?}"); + assert!(boxes(&rt, highlight()).len() >= 2, "a box per wrapped line"); + assert_eq!(rt.text_selection().map(|(k, r)| (k.to_owned(), r.start)).unwrap().1, second); + assert_eq!(rects(&rt), before); + + // A press elsewhere clears it, and still presses. + let other = centre(&find(&rt, "other")); + click(&mut rt, other); + assert_eq!(rt.text_selection(), None); + assert_eq!(rt.state.presses, 1); + assert!(boxes(&rt, highlight()).is_empty()); +} + +#[test] +fn copy_select_all_and_the_context_menu() { + let mut rt = runtime(); + let clipboard = rune::clipboard::memory(); + rt.use_clipboard(&clipboard); + let g = glyphs(&rt, "cmd"); + + // Cmd+C copies the selection; with nothing selected the key falls through. + command(&mut rt, 'c'); + assert!(clipboard.text().is_none()); + click(&mut rt, g[11]); + click(&mut rt, g[11]); + command(&mut rt, 'c'); + assert_eq!(clipboard.text().as_deref().map(String::as_str), Some("port")); + + // Cmd+A selects all of the text holding the selection. + command(&mut rt, 'a'); + assert_eq!(rt.selected_text().as_deref(), Some(CMD)); + command(&mut rt, 'c'); + assert_eq!(clipboard.text().as_deref().map(String::as_str), Some(CMD)); + wait(&mut rt); + + // A right-click outside the selection selects the word there on macOS (AppKit) and keeps + // the current selection elsewhere (Chromium), then offers Copy. + clipboard.set_text("stale"); + let p = glyphs(&rt, "para"); + rt.pointer_move(p[1].0, p[1].1); + rt.secondary_down(p[1].0, p[1].1); + rt.secondary_up(p[1].0, p[1].1); + tick(&mut rt); + let expected = if cfg!(target_os = "macos") { "first" } else { CMD }; + assert_eq!(rt.selected_text().as_deref(), Some(expected)); + let copy = rt.popup_menu().and_then(|m| m.find("copy")).expect("a Copy menu"); + assert!(copy.title() == "Copy" && copy.is_enabled()); + rt.resolve_popup(Some("copy")).unwrap(); + tick(&mut rt); + assert_eq!(clipboard.text().as_deref().map(String::as_str), Some(expected)); + assert_eq!(rt.selected_text().as_deref(), Some(expected), "picking Copy keeps the selection"); +} + +#[test] +fn links_open_and_plain_words_select() { + let mut rt = runtime(); + let docs = find(&rt, "docs"); + assert_eq!(docs.role, "link"); + rt.pointer_move(centre(&docs).0, centre(&docs).1); + tick(&mut rt); + assert_eq!(rt.cursor(), Cursor::Pointer, "a hand over the link"); + click(&mut rt, centre(&docs)); + assert_eq!(rt.state.opened, ["docs"]); + assert_eq!(rt.selected_text(), None, "clicking a link selects nothing"); + wait(&mut rt); + + let g = glyphs(&rt, "linked"); + click(&mut rt, g[0]); + click(&mut rt, g[0]); + assert_eq!(rt.selected_text().as_deref(), Some("read")); + assert_eq!(rt.state.opened, ["docs"]); +} + +#[test] +fn bidi_text_selects_by_logical_words() { + let mut rt = runtime(); + let g = glyphs(&rt, "bidi"); + if g.len() != 10 { + eprintln!("skipping bidi checks: no Hebrew font ({} glyphs)", g.len()); + return; + } + // Visual order: a b c, the Hebrew word (drawn right to left), d e f. + click(&mut rt, g[5]); + click(&mut rt, g[5]); + assert_eq!(rt.selected_text().as_deref(), Some("שלום")); + wait(&mut rt); + let e = find(&rt, "bidi"); + drag(&mut rt, (e.rect[0] + 0.5, g[0].1), (g[9].0 + 6.0, g[9].1)); + assert_eq!(rt.selected_text().as_deref(), Some(BIDI)); +} + +#[test] +fn the_highlight_matches_a_text_fields() { + let mut rt = runtime(); + rt.state.field.focused = true; + rt.state.field.anchor = 0; + rt.state.field.focus = 5; + rt.invalidate(); + tick(&mut rt); + let field = boxes(&rt, highlight()); + assert_eq!(field.len(), 1, "the field's selection box"); + + let g = glyphs(&rt, "cmd"); + click(&mut rt, g[1]); + click(&mut rt, g[1]); + let selectable = boxes(&rt, highlight()); + assert_eq!(rt.selected_text().as_deref(), Some("opencode")); + assert_eq!(selectable, field, "same fill, height and corners"); +} diff --git a/app/vendor/rune/crates/rune/tests/integration/selectable_text_edges.rs b/app/vendor/rune/crates/rune/tests/integration/selectable_text_edges.rs new file mode 100644 index 0000000..0f2662f --- /dev/null +++ b/app/vendor/rune/crates/rune/tests/integration/selectable_text_edges.rs @@ -0,0 +1,277 @@ +//! Selectable text in the places it meets the rest of the app: inside a clickable, draggable or +//! context-menu row, with links beside a focused field, under app shortcuts, at line ends, and +//! when the view changes the text under a live selection. + +use std::cell::Cell; + +use rune::{Color, Cursor, Cx, Drag, El, Env, Key, KeyEvent, Link, Mods, Runtime, TextEdit, TextStyle, col, rich, row, text, text_input}; +use crate::support::{click, drag, find, glyphs, tick, wait}; + +const ROW: &str = "open the project"; +const DRAG: &str = "drag this card"; +const OWN: &str = "pressable words"; +const LINKED: &str = "read the docs today"; +const LINES: &str = "first line\nsecond"; + +#[derive(Default)] +struct S { + field: TextEdit, + row_presses: u32, + row_doubles: u32, + row_hovers: u32, + row_menus: u32, + drags: u32, + own_presses: u32, + keys: Vec<String>, + stale: String, + stale_selectable: bool, + stale_shown: bool, +} + +thread_local! { static VIEWS: Cell<u32> = const { Cell::new(0) }; } + +fn shade() -> Color { Color::WHITE.alpha(0.1) } + +fn view(s: &S, _: &mut Cx<S>) -> El { + VIEWS.with(|v| v.set(v.get() + 1)); + let style = TextStyle::new(14.0, 400.0).lh(20.0); + let docs = LINKED.find("docs").unwrap(); + let mut root = col().w_full().h_full().padding(10.0).gap(10.0) + .child(row().key("row").w(300.0).h(30.0).hover(shade()).press(shade()) + .on_press(|s: &mut S| s.row_presses += 1) + .on_double_press(|s: &mut S| s.row_doubles += 1) + .on_hover(|s: &mut S| s.row_hovers += 1) + .on_secondary_press(|s: &mut S, _, _| s.row_menus += 1) + .child(text(ROW).key("rowtext").font(style).selectable(true))) + .child(row().key("dragrow").w(300.0).h(30.0) + .on_drag(|s: &mut S, _: &mut Drag, _| s.drags += 1) + .child(text(DRAG).key("dragtext").font(style).selectable(true))) + .child(text(OWN).key("own").font(style).selectable(true).on_press(|s: &mut S| s.own_presses += 1)) + .child(rich(LINKED, Vec::new()).key("linked").font(style).selectable(true) + .link(Link::new(docs..docs + 4, "docs"))) + .child(text_input(&s.field, style).key("field").w(200.0).on_edit(|s: &mut S| &mut s.field)) + .child(text(LINES).key("lines").font(style).w(200.0).selectable(true)); + if s.stale_shown { + root = root.child(text(s.stale.clone()).key("stale").font(style).w(200.0).selectable(s.stale_selectable)); + } + root +} + +fn runtime() -> Runtime<S> { + let s = S { field: TextEdit::new("field text"), stale: "— a".into(), stale_selectable: true, stale_shown: true, ..S::default() }; + let mut rt = Runtime::new(s, view, (500.0, 400.0), Env::new(true, 2.0)); + // The app sees every key first and takes all but plain Cmd+A and Cmd+C, which it leaves to + // the selection. + rt.on_key = Some(|s, ev, _| { + s.keys.push(format!("{:?} shift={} alt={}", ev.key, ev.mods.shift, ev.mods.alt)); + let m = ev.mods; + !(matches!(ev.key, Key::Command('a' | 'c')) && !m.shift && !m.alt && !m.ctrl) + }); + rt.frame(0.0); + rt +} + +fn chord(rt: &mut Runtime<S>, c: char, mods: Mods) { + rt.key(KeyEvent { key: Key::Command(c), mods: Mods { cmd: true, ..mods } }); + tick(rt); +} + +#[test] +fn a_clickable_row_keeps_its_clicks_hover_press_and_menu() { + let mut rt = runtime(); + let g = glyphs(&rt, "rowtext"); + + // Hovering the text hovers the row (its handler and its paint) and still shows the I-beam. + rt.pointer_move(g[2].0, g[2].1); + tick(&mut rt); + assert_eq!(rt.state.row_hovers, 1); + assert_eq!(find(&rt, "row").hover, 1.0); + assert_eq!(rt.cursor(), Cursor::Text); + + // A held press on the text presses the row; an unmoved click presses it. + rt.pointer_down(g[2].0, g[2].1); + tick(&mut rt); + assert!(find(&rt, "row").press > 0.0, "the row shows pressed"); + rt.pointer_up(g[2].0, g[2].1); + tick(&mut rt); + assert_eq!(rt.state.row_presses, 1); + wait(&mut rt); + + // A double-click is the row's double press and selects the word. + click(&mut rt, g[0]); + click(&mut rt, g[0]); + assert_eq!((rt.state.row_presses, rt.state.row_doubles), (3, 1)); + assert_eq!(rt.selected_text().as_deref(), Some("open")); + wait(&mut rt); + + // A drag that selects text is a selection, not a press. + let left = find(&rt, "rowtext").rect[0] + 0.5; + drag(&mut rt, (left, g[0].1), (g[6].0 + 3.0, g[6].1)); + assert_eq!(rt.selected_text().as_deref(), Some("open the")); + assert_eq!(rt.state.row_presses, 3); + + // The row's own context menu wins over the text's Copy menu. + rt.secondary_down(g[2].0, g[2].1); + rt.secondary_up(g[2].0, g[2].1); + tick(&mut rt); + assert_eq!(rt.state.row_menus, 1); + assert!(rt.popup_menu().is_none()); +} + +#[test] +fn dragging_a_draggable_row_drags_it_and_clicks_still_select() { + let mut rt = runtime(); + let g = glyphs(&rt, "dragtext"); + drag(&mut rt, g[0], (g[0].0 + 60.0, g[0].1 + 40.0)); + assert!(rt.state.drags >= 3, "down, moves and up reach the row: {}", rt.state.drags); + assert_eq!(rt.selected_text(), None, "the drag moved the row, not a selection"); + wait(&mut rt); + click(&mut rt, g[0]); + click(&mut rt, g[0]); + assert_eq!(rt.selected_text().as_deref(), Some("drag")); +} + +#[test] +fn a_drag_select_on_text_with_its_own_press_doesnt_press() { + let mut rt = runtime(); + let g = glyphs(&rt, "own"); + let left = find(&rt, "own").rect[0] + 0.5; + drag(&mut rt, (left, g[0].1), (g[4].0 + 3.0, g[4].1)); + assert_eq!(rt.selected_text().as_deref(), Some("press")); + assert_eq!(rt.state.own_presses, 0); + wait(&mut rt); + click(&mut rt, g[1]); + assert_eq!(rt.state.own_presses, 1, "a click still presses it"); +} + +#[test] +fn pressing_plain_words_beside_a_link_neither_focuses_nor_rebuilds() { + let mut rt = runtime(); + let g = glyphs(&rt, "linked"); + let before = VIEWS.with(Cell::get); + click(&mut rt, g[0]); + click(&mut rt, g[0]); + assert_eq!(rt.selected_text().as_deref(), Some("read")); + assert_eq!(VIEWS.with(Cell::get), before, "selecting never re-runs the view"); + assert!(!find(&rt, "linked").focused); + wait(&mut rt); + + // With a field focused, the press blurs it, as a click on other content does. + let f = find(&rt, "field"); + click(&mut rt, (f.rect[0] + 10.0, f.rect[1] + f.rect[3] / 2.0)); + assert!(rt.state.field.focused); + wait(&mut rt); + click(&mut rt, g[1]); + assert!(!rt.state.field.focused, "the field lets go"); + assert!(!find(&rt, "linked").focused, "and the text doesn't take focus"); +} + +#[test] +fn only_the_plain_chords_belong_to_the_selection() { + let mut rt = runtime(); + let clipboard = rune::clipboard::memory(); + rt.use_clipboard(&clipboard); + let g = glyphs(&rt, "rowtext"); + click(&mut rt, g[0]); + click(&mut rt, g[0]); + assert_eq!(rt.selected_text().as_deref(), Some("open")); + + // Shift or Option added: the app's shortcut, the selection untouched. + chord(&mut rt, 'c', Mods { shift: true, ..Mods::default() }); + chord(&mut rt, 'a', Mods { alt: true, ..Mods::default() }); + assert_eq!(rt.state.keys.len(), 2, "{:?}", rt.state.keys); + assert!(clipboard.text().is_none()); + assert_eq!(rt.selected_text().as_deref(), Some("open")); + if cfg!(target_os = "macos") { + chord(&mut rt, 'a', Mods { ctrl: true, ..Mods::default() }); + assert_eq!(rt.state.keys.len(), 3, "Cmd+Ctrl+A is the app's"); + } + let app = rt.state.keys.len(); + wait(&mut rt); + + // A single click makes the text the holder: Cmd+C has nothing to copy; Cmd+A, which the + // app passed on, selects all of it. + click(&mut rt, g[5]); + chord(&mut rt, 'c', Mods::default()); + assert!(clipboard.text().is_none(), "an empty selection copies nothing"); + chord(&mut rt, 'a', Mods::default()); + assert_eq!(rt.selected_text().as_deref(), Some(ROW)); + assert_eq!(rt.state.keys.len(), app + 2, "the app saw both first"); + + // A click on nothing clears it; Cmd+A then goes back to the text last clicked. + click(&mut rt, (480.0, 390.0)); + assert_eq!(rt.text_selection(), None); + chord(&mut rt, 'a', Mods::default()); + assert_eq!(rt.selected_text().as_deref(), Some(ROW)); +} + +#[test] +fn line_ends_take_the_lines_last_word_and_paragraph() { + let mut rt = runtime(); + let g = glyphs(&rt, "lines"); + // "first line" is 9 glyphs; right of its last one is the line's end. + let end = (g[8].0 + 30.0, g[8].1); + click(&mut rt, end); + click(&mut rt, end); + assert_eq!(rt.selected_text().as_deref(), Some("line")); + click(&mut rt, end); + assert_eq!(rt.selected_text().as_deref(), Some("first line\n")); + wait(&mut rt); + let last = *g.last().unwrap(); + let past = (last.0 + 40.0, last.1); + click(&mut rt, past); + click(&mut rt, past); + assert_eq!(rt.selected_text().as_deref(), Some("second")); + click(&mut rt, past); + assert_eq!(rt.selected_text().as_deref(), Some("second")); +} + +#[test] +fn a_selection_drops_when_its_text_changes_or_goes() { + let mut rt = runtime(); + let g = glyphs(&rt, "stale"); + // Triple-click and hold on "— a", then the view changes it to "a —" mid-drag. + click(&mut rt, g[1]); + click(&mut rt, g[1]); + rt.pointer_down(g[1].0, g[1].1); + tick(&mut rt); + assert_eq!(rt.selected_text().as_deref(), Some("— a")); + rt.state.stale = "a —".into(); + rt.invalidate(); + tick(&mut rt); + let e = find(&rt, "stale"); + for k in 0..6 { + rt.pointer_move(e.rect[0] + 2.0 + k as f32 * 3.0, g[1].1); + tick(&mut rt); + } + rt.pointer_up(e.rect[0] + 20.0, g[1].1); + tick(&mut rt); + assert_eq!(rt.text_selection(), None, "a content change drops the selection"); + assert_eq!(rt.selected_text(), None); + wait(&mut rt); + + // Selected, then no longer selectable: gone, and Cmd+A is the app's. + let g = glyphs(&rt, "stale"); + click(&mut rt, g[0]); + click(&mut rt, g[0]); + assert!(rt.selected_text().is_some()); + rt.state.stale_selectable = false; + rt.invalidate(); + tick(&mut rt); + assert_eq!(rt.text_selection(), None); + chord(&mut rt, 'a', Mods::default()); + assert_eq!(rt.text_selection(), None); + wait(&mut rt); + + // Selected, then removed. + rt.state.stale_selectable = true; + rt.invalidate(); + tick(&mut rt); + click(&mut rt, g[0]); + click(&mut rt, g[0]); + assert!(rt.selected_text().is_some()); + rt.state.stale_shown = false; + rt.invalidate(); + tick(&mut rt); + assert_eq!(rt.text_selection(), None); +} diff --git a/app/vendor/rune/crates/rune/tests/integration/selection_api.rs b/app/vendor/rune/crates/rune/tests/integration/selection_api.rs new file mode 100644 index 0000000..c3516e4 --- /dev/null +++ b/app/vendor/rune/crates/rune/tests/integration/selection_api.rs @@ -0,0 +1,412 @@ +//! The text selection from code: `Tx::select_text`, `Tx::select_all_text` and +//! `Tx::clear_text_selection` set it after the handler's commit (in time for a key in the same +//! frame), `Tx::text_selection` reads it, `El::selection_copy` decides what copying takes and +//! `El::on_selection_change` hears it change. +use std::cell::RefCell; +use std::ops::Range; + +use rune::{Cx, El, Env, Key, KeyEvent, Mods, Runtime, TextEdit, TextSelection, TextStyle, col, row, text, text_input}; + +#[derive(Default)] +struct S { extra: bool, seen: Option<TextSelection>, field: TextEdit, app_keys: Vec<char>, heard: Vec<Heard> } + +/// One `on_selection_change` call: started, cleared, and the selection's text. +#[derive(Debug, PartialEq)] +struct Heard(bool, bool, Option<String>); + +thread_local! { + /// What the `selection_copy` provider saw last: (path, range, whole). + static ASKED: RefCell<Vec<(String, Range<usize>, bool)>> = const { RefCell::new(Vec::new()) }; +} + +fn view(s: &S, _: &mut Cx<S>) -> El { + let style = TextStyle::new(14.0, 400.0).lh(20.0); + let t = |content: &str, key: &str| text(content.to_owned()).key(key).font(style).w_full().selectable(true); + col().w_full().h_full().padding(10.0).gap(12.0) + .child(col().key("doc").w(400.0).gap(12.0).selection_group(true) + .on_selection_change(|s: &mut S, c, _| s.heard.push(Heard(c.started(), c.cleared(), c.selection().map(|t| t.text().to_owned())))) + .selection_copy(|sel| { + ASKED.with_borrow_mut(|a| *a = sel.texts().iter().map(|t| (t.path().to_owned(), t.range(), t.is_whole())).collect()); + sel.texts().iter().all(|t| t.is_whole()).then(|| "SOURCE".to_owned()) + }) + .child(t("first paragraph", "a")) + .child(row().key("r").w_full().child(text("•").font(style).w(20.0)).child(t("second", "b").grow(1.0).shrink()))) + .child(t("lone text here", "lone").w(300.0)) + .child(t("café ok", "cafe").w(300.0)) + .children(s.extra.then(|| t("extra words", "extra").w(300.0))) + .child(text_input(&s.field, style).single_line().key("field").w(300.0).on_edit(|s: &mut S| &mut s.field)) +} + +fn runtime() -> Runtime<S> { + let mut rt = Runtime::new(S::default(), view, (500.0, 500.0), Env::new(true, 2.0)); + rt.frame(0.0); + rt +} + +fn tick(rt: &mut Runtime<S>) { rt.frame(1.0 / 60.0); } + +fn command(rt: &mut Runtime<S>, c: char) { + rt.key(KeyEvent { key: Key::Command(c), mods: Mods { cmd: true, ..Mods::default() } }); + tick(rt); +} + +fn act(rt: &mut Runtime<S>, f: impl FnOnce(&mut rune::Tx)) { + rt.update(|_, tx| f(tx)); + tick(rt); +} + +#[test] +fn code_selects_a_range_reads_it_and_clears_it() { + let mut rt = runtime(); + act(&mut rt, |tx| tx.select_text("lone", 5..9)); + assert_eq!(rt.selected_text().as_deref(), Some("text")); + rt.update(|s, tx| s.seen = tx.text_selection().cloned()); + let seen = rt.state.seen.take().expect("a handler reads the selection"); + assert_eq!(seen.text(), "text"); + let [t] = seen.texts() else { panic!("{seen:?}") }; + assert!(t.path().ends_with("/lone") && t.key() == Some("lone"), "{t:?}"); + assert_eq!((t.range(), t.len(), t.text(), t.is_whole()), (5..9, 14, "text", false)); + + // Clamped to the text and its character boundaries. + act(&mut rt, |tx| tx.select_text("lone", 10..999)); + assert_eq!(rt.selected_text().as_deref(), Some("here")); + act(&mut rt, |tx| tx.select_text("cafe", 0..4)); + assert_eq!(rt.selected_text().as_deref(), Some("caf"), "byte 4 is inside the é"); + // A key that names no selectable text leaves it be. + act(&mut rt, |tx| tx.select_text("r", 0..2)); + act(&mut rt, |tx| tx.select_text("nothing", 0..2)); + assert_eq!(rt.selected_text().as_deref(), Some("caf")); + + act(&mut rt, |tx| tx.clear_text_selection()); + assert_eq!(rt.selected_text(), None); + rt.update(|s, tx| s.seen = tx.text_selection().cloned()); + assert_eq!(rt.state.seen, None); +} + +#[test] +fn select_all_takes_a_group_a_part_of_one_or_a_text() { + let mut rt = runtime(); + act(&mut rt, |tx| tx.select_all_text("doc")); + assert_eq!(rt.selected_text().as_deref(), Some("first paragraph\nsecond")); + act(&mut rt, |tx| tx.select_all_text("r")); + assert_eq!(rt.selected_text().as_deref(), Some("second"), "the texts inside a part of the group"); + act(&mut rt, |tx| tx.select_all_text("lone")); + assert_eq!(rt.selected_text().as_deref(), Some("lone text here")); + // Then Cmd+A widens a text's selection to its group, as after a click. + act(&mut rt, |tx| tx.select_text("a", 0..5)); + command(&mut rt, 'a'); + assert_eq!(rt.selected_text().as_deref(), Some("first paragraph\nsecond")); +} + +#[test] +fn a_text_the_same_change_builds_selects_and_keeps_its_selection_across_rebuilds() { + let mut rt = runtime(); + rt.update(|s, tx| { + s.extra = true; + tx.select_all_text("extra"); + }); + tick(&mut rt); + assert_eq!(rt.selected_text().as_deref(), Some("extra words")); + for _ in 0..3 { + rt.invalidate(); + tick(&mut rt); + } + assert_eq!(rt.selected_text().as_deref(), Some("extra words")); +} + +#[test] +fn a_key_in_the_same_frame_copies_what_code_selected() { + let mut rt = runtime(); + let clipboard = rune::clipboard::memory(); + rt.use_clipboard(&clipboard); + rt.update(|_, tx| tx.select_text("lone", 0..4)); + command(&mut rt, 'c'); + assert_eq!(clipboard.text().as_deref().map(String::as_str), Some("lone")); +} + +#[test] +fn selection_copy_says_what_copying_takes() { + let mut rt = runtime(); + let clipboard = rune::clipboard::memory(); + rt.use_clipboard(&clipboard); + act(&mut rt, |tx| tx.select_all_text("doc")); + command(&mut rt, 'c'); + assert_eq!(clipboard.text().as_deref().map(String::as_str), Some("SOURCE")); + assert_eq!(ASKED.take(), [("a".to_owned(), 0..15, true), ("r/b".to_owned(), 0..6, true)], "paths relative to the element"); + rt.update(|s, tx| s.seen = tx.text_selection().cloned()); + assert_eq!(rt.state.seen.as_ref().map(TextSelection::text), Some("first paragraph\nsecond"), "reading is as drawn"); + + // It returns None for part of the group: the drawn text, and it sees what isn't selected. + act(&mut rt, |tx| tx.select_text("b", 0..3)); + command(&mut rt, 'c'); + assert_eq!(clipboard.text().as_deref().map(String::as_str), Some("sec")); + assert_eq!(ASKED.take(), [("a".to_owned(), 0..0, false), ("r/b".to_owned(), 0..3, false)]); + + // The Copy menu asks it too. + act(&mut rt, |tx| tx.select_all_text("doc")); + let a = rt.elements().into_iter().find(|e| e.key.as_deref() == Some("a")).unwrap(); + let (x, y) = (a.rect[0] + 20.0, a.rect[1] + a.rect[3] / 2.0); + rt.pointer_move(x, y); + rt.secondary_down(x, y); + rt.secondary_up(x, y); + tick(&mut rt); + rt.resolve_popup(Some("copy")).unwrap(); + tick(&mut rt); + assert_eq!(clipboard.text().as_deref().map(String::as_str), Some("SOURCE")); + + // A text outside it copies as drawn. + ASKED.take(); + act(&mut rt, |tx| tx.select_all_text("lone")); + command(&mut rt, 'c'); + assert_eq!(clipboard.text().as_deref().map(String::as_str), Some("lone text here")); + assert!(ASKED.take().is_empty()); +} + +/// An app's `on_key` that takes Cmd+A and Cmd+C copies the note its own way. +fn app_takes_copy_keys(rt: &mut Runtime<S>) { + rt.on_key = Some(|s, ev, tx| match ev.key { + Key::Command(c @ ('a' | 'c')) => { + s.app_keys.push(c); + if c == 'c' { tx.copy("APP"); } + true + } + _ => false, + }); +} + +#[test] +fn an_apps_on_key_takes_the_copy_keys_before_the_selection() { + let mut rt = runtime(); + let clipboard = rune::clipboard::memory(); + rt.use_clipboard(&clipboard); + app_takes_copy_keys(&mut rt); + act(&mut rt, |tx| tx.select_text("lone", 0..4)); + command(&mut rt, 'c'); + assert_eq!(clipboard.text().as_deref().map(String::as_str), Some("APP")); + command(&mut rt, 'a'); + assert_eq!(rt.selected_text().as_deref(), Some("lone"), "Cmd+A was the app's"); + assert_eq!(rt.state.app_keys, ['c', 'a']); + + // An app that passes them on leaves them to the selection. + rt.on_key = Some(|s, ev, _| { if let Key::Command(c) = ev.key { s.app_keys.push(c); } false }); + command(&mut rt, 'a'); + assert_eq!(rt.selected_text().as_deref(), Some("lone text here")); + command(&mut rt, 'c'); + assert_eq!(clipboard.text().as_deref().map(String::as_str), Some("lone text here")); + assert_eq!(rt.state.app_keys, ['c', 'a', 'a', 'c'], "the app saw them first"); +} + +#[test] +fn a_focused_field_keeps_its_copy_keys_from_the_app() { + let mut rt = runtime(); + let clipboard = rune::clipboard::memory(); + rt.use_clipboard(&clipboard); + app_takes_copy_keys(&mut rt); + rt.state.field = TextEdit::new("field words"); + rt.state.field.focused = true; + rt.invalidate(); + tick(&mut rt); + command(&mut rt, 'a'); + command(&mut rt, 'c'); + assert_eq!(clipboard.text().as_deref().map(String::as_str), Some("field words")); + assert!(rt.state.app_keys.is_empty(), "{:?}", rt.state.app_keys); +} + +fn heard(rt: &mut Runtime<S>) -> Vec<Heard> { std::mem::take(&mut rt.state.heard) } + +#[test] +fn on_selection_change_hears_a_drag_start_change_and_clear_once_a_frame() { + let mut rt = runtime(); + let a = rt.elements().into_iter().find(|e| e.key.as_deref() == Some("a")).unwrap(); + let (x0, y) = (a.rect[0] + 1.0, a.rect[1] + a.rect[3] / 2.0); + rt.pointer_move(x0, y); + rt.pointer_down(x0, y); + tick(&mut rt); + assert_eq!(heard(&mut rt), [], "a press leaves only a caret"); + // Three moves a frame, heard once a frame: started, then changed. + let mut frames = 0; + for step in 1..=3 { + for k in 1..=3 { + let x = x0 + (step * 3 + k - 3) as f32 * 6.0; + rt.pointer_move(x, y); + } + tick(&mut rt); + frames += 1; + } + let calls = heard(&mut rt); + assert_eq!(calls.len(), frames, "{calls:?}"); + assert!(calls[0].0 && !calls[0].1, "the first is the start: {calls:?}"); + assert!(calls[1..].iter().all(|c| !c.0 && !c.1 && c.2.as_ref().is_some_and(|t| "first paragraph".starts_with(t.as_str()))), "{calls:?}"); + let last = calls.last().and_then(|c| c.2.clone()); + rt.pointer_up(x0 + 54.0, y); + tick(&mut rt); + assert_eq!(heard(&mut rt), [Heard(false, false, last)], "the release is heard once, with the same selection"); + + // Cmd+A widens it; a click outside the group clears it. + command(&mut rt, 'a'); + assert_eq!(heard(&mut rt), [Heard(false, false, Some("first paragraph\nsecond".into()))]); + let lone = rt.elements().into_iter().find(|e| e.key.as_deref() == Some("lone")).unwrap(); + let (x, y) = (lone.rect[0] + 5.0, lone.rect[1] + lone.rect[3] / 2.0); + rt.pointer_move(x, y); + rt.pointer_down(x, y); + rt.pointer_up(x, y); + tick(&mut rt); + assert_eq!(heard(&mut rt), [Heard(false, true, None)]); +} + +#[test] +fn on_selection_change_hears_code_and_selections_elsewhere_dont_reach_it() { + let mut rt = runtime(); + act(&mut rt, |tx| tx.select_text("b", 0..3)); + tick(&mut rt); + assert_eq!(heard(&mut rt), [Heard(true, false, Some("sec".into()))]); + act(&mut rt, |tx| tx.select_all_text("doc")); + tick(&mut rt); + assert_eq!(heard(&mut rt), [Heard(false, false, Some("first paragraph\nsecond".into()))]); + // The same selection again is no change. + act(&mut rt, |tx| tx.select_all_text("doc")); + tick(&mut rt); + assert_eq!(heard(&mut rt), []); + // Moving to a text outside it leaves it: cleared, and nothing more while it's elsewhere. + act(&mut rt, |tx| tx.select_all_text("lone")); + tick(&mut rt); + assert_eq!(heard(&mut rt), [Heard(false, true, None)]); + act(&mut rt, |tx| tx.select_text("lone", 0..4)); + tick(&mut rt); + assert_eq!(heard(&mut rt), []); + act(&mut rt, |tx| tx.select_all_text("a")); + act(&mut rt, |tx| tx.clear_text_selection()); + tick(&mut rt); + assert_eq!(heard(&mut rt), [Heard(true, false, Some("first paragraph".into())), Heard(false, true, None)]); +} + +#[test] +fn a_focused_field_keeps_a_static_selection_across_commits() { + let mut rt = runtime(); + rt.state.field = TextEdit::new("field words"); + rt.state.field.focused = true; + rt.invalidate(); + tick(&mut rt); + act(&mut rt, |tx| tx.select_text("lone", 0..4)); + assert_eq!(rt.selected_text().as_deref(), Some("lone")); + for _ in 0..3 { + rt.invalidate(); + tick(&mut rt); + } + assert_eq!(rt.selected_text().as_deref(), Some("lone"), "staying focused on the field keeps the static selection"); +} + +#[test] +fn scroll_into_view_and_select_text_in_one_handler_selects_a_culled_row() { + #[derive(Default)] + struct V; + fn vview(_: &V, _: &mut Cx<V>) -> El { + let style = TextStyle::new(14.0, 400.0).lh(20.0); + col().w(300.0).h(80.0).scroll(rune::ScrollSpec { stick_bottom: false }).child( + col() + .key("list") + .w_full() + .growth(rune::GrowthSpec::default()) + .virtual_rows( + 100, + 24.0, + |_: &V, i| format!("r{i}").into(), + move |_: &V, i| { + row().key(format!("r{i}")).w_full().h(24.0).child( + text(format!("row {i} content")) + .key(format!("t{i}")) + .font(style) + .w_full() + .selectable(true), + ) + }, + ), + ) + } + let mut rt = Runtime::new(V, vview, (320.0, 100.0), Env::new(true, 2.0)); + rt.frame(0.0); + assert!(rt.elements().iter().all(|e| e.key.as_deref() != Some("t80")), "row 80 starts culled"); + rt.update(|_, tx| { + tx.scroll_into_view("r80"); + tx.select_text("t80", 0..6); + }); + rt.frame(1.0 / 60.0); + assert_eq!(rt.selected_text().as_deref(), Some("row 80")); +} + +#[test] +fn on_selection_change_calling_select_does_not_loop() { + #[derive(Default)] + struct LoopState { calls: Vec<Option<String>> } + fn lview(_: &LoopState, _: &mut Cx<LoopState>) -> El { + let style = TextStyle::new(14.0, 400.0).lh(20.0); + col().key("doc").w(300.0).selection_group(true) + .on_selection_change(|s: &mut LoopState, c, tx| { + s.calls.push(c.selection().map(|sel| sel.text().to_owned())); + if c.selection().is_some_and(|sel| sel.text() == "hello") { + tx.select_all_text("doc"); + } + }) + .child(text("hello world").key("a").font(style).w_full().selectable(true)) + } + let mut rt = Runtime::new(LoopState::default(), lview, (320.0, 100.0), Env::new(true, 2.0)); + rt.frame(0.0); + rt.update(|_, tx| tx.select_text("a", 0..5)); + for _ in 0..5 { + rt.frame(1.0 / 60.0); + } + assert_eq!(rt.state.calls, [Some("hello".to_owned())], "widening inside on_selection_change does not re-trigger it"); + assert_eq!(rt.selected_text().as_deref(), Some("hello world")); +} + +#[test] +fn keyed_selection_survives_when_an_unkeyed_ancestor_shifts_index() { + #[derive(Default)] + struct Shift { banner: bool, heard: Vec<Heard> } + fn sview(s: &Shift, _: &mut Cx<Shift>) -> El { + let style = TextStyle::new(14.0, 400.0).lh(20.0); + col().w(300.0).gap(8.0) + .children(s.banner.then(|| row().w_full().child(text("banner").font(style)))) + .child( + col().w_full().selection_group(true) + .on_selection_change(|s: &mut Shift, c, _| { + s.heard.push(Heard(c.started(), c.cleared(), c.selection().map(|t| t.text().to_owned()))); + }) + .child(text("alpha beta").key("msg").font(style).w_full().selectable(true)), + ) + } + let mut rt = Runtime::new(Shift::default(), sview, (320.0, 120.0), Env::new(true, 2.0)); + rt.frame(0.0); + rt.update(|_, tx| tx.select_text("msg", 0..5)); + rt.frame(1.0 / 60.0); + rt.frame(1.0 / 60.0); + assert_eq!(rt.selected_text().as_deref(), Some("alpha")); + assert_eq!(std::mem::take(&mut rt.state.heard), [Heard(true, false, Some("alpha".into()))]); + + // Inserting an unkeyed sibling before the unkeyed wrapper shifts `#0/msg` to `#1/msg`. + rt.update(|s, _| s.banner = true); + rt.frame(1.0 / 60.0); + rt.frame(1.0 / 60.0); + assert_eq!(rt.selected_text().as_deref(), Some("alpha"), "keyed text keeps its selection across unkeyed wrapper shift"); + assert_eq!(rt.state.heard, [], "no bogus clear/start when the selection did not change"); +} + +#[test] +fn secure_text_is_never_selectable_or_copied() { + #[derive(Default)] + struct Sec; + fn sec_view(_: &Sec, _: &mut Cx<Sec>) -> El { + let style = TextStyle::new(14.0, 400.0).lh(20.0); + col().key("doc").w(300.0).selection_group(true) + .child(text("public").key("pub").font(style).w_full().selectable(true)) + .child(text("top-secret").key("sec").font(style).w_full().selectable(true).secure()) + } + let mut rt = Runtime::new(Sec, sec_view, (320.0, 120.0), Env::new(true, 2.0)); + rt.frame(0.0); + rt.update(|_, tx| tx.select_all_text("sec")); + rt.frame(1.0 / 60.0); + assert_eq!(rt.selected_text(), None); + rt.update(|_, tx| tx.select_all_text("doc")); + rt.frame(1.0 / 60.0); + assert_eq!(rt.selected_text().as_deref(), Some("public")); +} diff --git a/app/vendor/rune/crates/rune/tests/integration/selection_copy_breaks.rs b/app/vendor/rune/crates/rune/tests/integration/selection_copy_breaks.rs new file mode 100644 index 0000000..a83694d --- /dev/null +++ b/app/vendor/rune/crates/rune/tests/integration/selection_copy_breaks.rs @@ -0,0 +1,54 @@ +//! `El::copy_breaks` and `El::copy_prefix`: a group's copy leaves the newlines its texts ask for +//! between them, the larger of the two, and puts a text's prefix before it when the copy takes it +//! from its start along with other texts. A copy of one text alone goes without its prefix. + +use rune::{Cx, El, Env, Runtime, TextStyle, col, text}; +use crate::support::{command, drag, glyphs, wait}; + +fn view(_: &(), _: &mut Cx<()>) -> El { + let style = TextStyle::new(14.0, 400.0).lh(20.0); + let t = |content: &str, key: &str| text(content.to_owned()).key(key).font(style).w_full().selectable(true); + col().w_full().h_full().padding(10.0) + .child(col().key("group").w(400.0).gap(12.0).selection_group(true) + .child(t("first para", "a").copy_breaks(2, 2)) + .child(t("one", "i0").copy_prefix("- ")) + .child(t("two", "i1").copy_prefix("- ")) + .child(t("plain", "p"))) +} + +fn runtime() -> (Runtime<()>, rune::clipboard::MemoryClipboard) { + let mut rt = Runtime::new((), view, (500.0, 500.0), Env::new(true, 2.0)); + rt.frame(0.0); + let clipboard = rune::clipboard::memory(); + rt.use_clipboard(&clipboard); + (rt, clipboard) +} + +fn before(g: (f32, f32)) -> (f32, f32) { (g.0 - 3.0, g.1) } +fn after(g: (f32, f32)) -> (f32, f32) { (g.0 + 3.0, g.1) } + +#[test] +fn copy_leaves_the_breaks_and_prefixes_texts_ask_for() { + let (mut rt, clipboard) = runtime(); + let a = glyphs(&rt, "a"); + let p = glyphs(&rt, "p"); + // Glyphs skip spaces: a[5] is the "p" of "para". + drag(&mut rt, before(a[5]), after(p[1])); + assert_eq!(rt.selected_text().as_deref(), Some("para\n\n- one\n- two\npl")); + command(&mut rt, 'c'); + assert_eq!(clipboard.text().as_deref().map(String::as_str), Some("para\n\n- one\n- two\npl")); +} + +#[test] +fn a_text_taken_from_inside_or_alone_goes_without_its_prefix() { + let (mut rt, _) = runtime(); + let one = glyphs(&rt, "i0"); + let two = glyphs(&rt, "i1"); + // Just inside the text, which starts at the padding's edge. + drag(&mut rt, (two[0].0 - 1.0, two[0].1), after(two[2])); + assert_eq!(rt.selected_text().as_deref(), Some("two")); + wait(&mut rt); + drag(&mut rt, before(one[1]), after(two[2])); + assert_eq!(rt.selected_text().as_deref(), Some("ne\n- two")); +} + diff --git a/app/vendor/rune/crates/rune/tests/integration/selection_group.rs b/app/vendor/rune/crates/rune/tests/integration/selection_group.rs new file mode 100644 index 0000000..b0f64cc --- /dev/null +++ b/app/vendor/rune/crates/rune/tests/integration/selection_group.rs @@ -0,0 +1,405 @@ +//! `El::selection_group`: the selectable texts inside one element select as one flow in tree +//! order. A drag crosses from one into the next, Shift-click extends into any of them, Cmd+A +//! takes them all and Cmd+C joins them with newlines (tabs between texts side by side). +//! Double- and triple-clicks stay inside one text, links still open, a draggable row still +//! drags, and text appended after the selection keeps it. A drag into a gap reaches no +//! further than the pointer, table rows select by band, inner groups stay their own, and a +//! change to a text between the ends drops the selection. Elided texts select through their +//! ellipsis, and a virtual row scrolling out drops the selection it holds. + +use rune::{Cursor, Cx, Drag, El, Env, GrowthSpec, Link, Mods, PhysicalInput, Runtime, ScrollSpec, TextStyle, col, rich, row, text}; +use crate::support::{click, command, drag, find, glyphs, glyphs_at, tick, wait}; + +const A: &str = "first paragraph here"; +const ITEM: &str = "list item"; +const CODE: &str = "let x = 1;\nlet y = 2;"; +const LINKED: &str = "see docs now"; + +#[derive(Default)] +struct S { tail: String, opened: Vec<String>, drags: u32, hide_item: bool, edited: bool, code_changed: bool } + +fn view(s: &S, _: &mut Cx<S>) -> El { + let style = TextStyle::new(14.0, 400.0).lh(20.0); + let docs = LINKED.find("docs").unwrap(); + let t = |content: &str, key: &str| text(content.to_owned()).key(key).font(style).w_full().selectable(true); + let item = if s.edited { "edited item" } else { ITEM }; + let code = if s.code_changed { "fn other() {}" } else { CODE }; + col().w_full().h_full().padding(10.0) + .child(col().key("group").w(400.0).gap(12.0).selection_group(true) + .child(t(A, "a")) + .children((!s.hide_item).then(|| row().key("li").w_full().child(text("•").key("marker").font(style).w(20.0)).child(t(item, "item").grow(1.0).shrink()))) + .child(col().key("block").w_full().padding(8.0).child(t(code, "code"))) + .child(row().key("cells").w_full().child(t("left", "c0").w(120.0)).child(t("right", "c1").w(120.0))) + .child(rich(format!("{LINKED}{}", s.tail), Vec::new()).key("linked").font(style).w_full().selectable(true) + .link(Link::new(docs..docs + 4, "docs")) + .on_link(|s: &mut S, id, _| s.opened.push(id.to_owned())))) + .child(t("outside text", "out").w(200.0).mt(12.0)) + .child(row().key("dragrow").w(400.0).h(30.0).mt(12.0).selection_group(true) + .on_drag(|s: &mut S, _: &mut Drag, _| s.drags += 1) + .child(t("drag one", "d0").w(150.0)).child(t("drag two", "d1").w(150.0))) +} + +fn runtime() -> Runtime<S> { + let mut rt = Runtime::new(S::default(), view, (500.0, 500.0), Env::new(true, 2.0)); + rt.frame(0.0); + rt +} + +/// A double-click at `from`, held and dragged to `to`: selects by words. +fn word_drag(rt: &mut Runtime<S>, (x0, y0): (f32, f32), (x1, y1): (f32, f32)) { + click(rt, (x0, y0)); + drag(rt, (x0, y0), (x1, y1)); +} + +/// Just left of glyph `g`: a drag ending there stops before it. +fn before(g: (f32, f32)) -> (f32, f32) { (g.0 - 3.0, g.1) } + +#[test] +fn a_drag_crosses_texts_and_copy_joins_them() { + let mut rt = runtime(); + let clipboard = rune::clipboard::memory(); + rt.use_clipboard(&clipboard); + let a = glyphs(&rt, "a"); + let code = glyphs(&rt, "code"); + // From "paragraph" down into the code block, stopping before "x". + drag(&mut rt, before(a[5]), before(code[3])); + assert_eq!(rt.selected_text().as_deref(), Some("paragraph here\nlist item\nlet "), "the marker isn't selectable"); + assert_eq!(find(&rt, "a").selected.as_deref(), Some("paragraph here")); + assert_eq!(find(&rt, "item").selected.as_deref(), Some(ITEM), "texts between are selected whole"); + assert_eq!(find(&rt, "code").selected.as_deref(), Some("let ")); + assert_eq!(find(&rt, "c0").selected, None); + assert_eq!(rt.text_selection().map(|(p, r)| (p.ends_with("/a"), r)), Some((true, 6..A.len())), "the anchor's text"); + rt.events.clear(); + command(&mut rt, 'c'); + assert_eq!(clipboard.text().as_deref().map(String::as_str), Some("paragraph here\nlist item\nlet ")); + // The Edit menu's Copy hands Rune this one key: one copy, not one per text. + assert_eq!(rt.events.iter().filter(|e| e.starts_with("copy ")).count(), 1, "{:?}", rt.events); + + // Upward from the cells into the item: the anchor stays put. + wait(&mut rt); + let c1 = glyphs(&rt, "c1"); + let item = glyphs(&rt, "item"); + drag(&mut rt, before(c1[2]), before(item[4])); + assert_eq!(rt.selected_text().as_deref(), Some("item\nlet x = 1;\nlet y = 2;\nleft\tri"), "cells side by side are tab-separated"); + + // Cmd+A takes the whole group, and stops at it. + rt.events.clear(); + command(&mut rt, 'a'); + assert_eq!(rt.events.iter().filter(|e| e.starts_with("select all ")).count(), 1, "{:?}", rt.events); + assert_eq!(rt.selected_text().as_deref(), Some(format!("{A}\n{ITEM}\n{CODE}\nleft\tright\n{LINKED}").as_str())); + assert_eq!(find(&rt, "out").selected, None); +} + +#[test] +fn gaps_and_the_outside_clamp_to_the_group() { + let mut rt = runtime(); + let a = glyphs(&rt, "a"); + let item = find(&rt, "li"); + // Released in the gap above the list item: up to the item's start. + drag(&mut rt, before(a[5]), (a[5].0, item.rect[1] - 4.0)); + assert_eq!(rt.selected_text().as_deref(), Some("paragraph here")); + wait(&mut rt); + // Past the group into a text outside it: the group's end, not the outside text. + let out = glyphs(&rt, "out"); + drag(&mut rt, before(a[5]), out[3]); + let got = rt.selected_text().unwrap(); + assert!(got.starts_with("paragraph here") && got.ends_with(LINKED), "{got:?}"); + assert_eq!(find(&rt, "out").selected, None); +} + +#[test] +fn shift_click_extends_into_another_text() { + let mut rt = runtime(); + let a = glyphs(&rt, "a"); + let c0 = glyphs(&rt, "c0"); + click(&mut rt, before(a[6])); + rt.physical_input(PhysicalInput::Modifiers(Mods { shift: true, ..Mods::default() })); + click(&mut rt, before(c0[2])); + assert_eq!(rt.selected_text().as_deref(), Some(format!("aragraph here\n{ITEM}\n{CODE}\nle").as_str())); + // And back into the anchor's own text. + click(&mut rt, before(a[9])); + rt.physical_input(PhysicalInput::Modifiers(Mods::default())); + assert_eq!(rt.selected_text().as_deref(), Some("ara")); +} + +#[test] +fn double_and_triple_clicks_stay_in_one_text() { + let mut rt = runtime(); + let code = glyphs(&rt, "code"); + let x = (code[3].0 - 1.0, code[3].1); + click(&mut rt, x); + click(&mut rt, x); + assert_eq!(rt.selected_text().as_deref(), Some("x")); + click(&mut rt, x); + assert_eq!(rt.selected_text().as_deref(), Some("let x = 1;\n")); + wait(&mut rt); + // A double-click drag across texts extends by whole words. + let a = glyphs(&rt, "a"); + let item = glyphs(&rt, "item"); + rt.pointer_move(a[7].0, a[7].1); + rt.pointer_down(a[7].0, a[7].1); + rt.pointer_up(a[7].0, a[7].1); + tick(&mut rt); + rt.pointer_down(a[7].0, a[7].1); + tick(&mut rt); + rt.pointer_move(item[1].0, item[1].1); + tick(&mut rt); + rt.pointer_up(item[1].0, item[1].1); + tick(&mut rt); + assert_eq!(rt.selected_text().as_deref(), Some("paragraph here\nlist")); +} + +#[test] +fn links_open_and_show_the_hand_over_selectable_text() { + let mut rt = runtime(); + let a = glyphs(&rt, "a"); + rt.pointer_move(a[2].0, a[2].1); + tick(&mut rt); + assert_eq!(rt.cursor(), Cursor::Text); + let docs = find(&rt, "docs"); + let at = (docs.rect[0] + docs.rect[2] / 2.0, docs.rect[1] + docs.rect[3] / 2.0); + rt.pointer_move(at.0, at.1); + tick(&mut rt); + assert_eq!(rt.cursor(), Cursor::Pointer); + click(&mut rt, at); + assert_eq!(rt.state.opened, ["docs"]); + assert_eq!(rt.selected_text(), None); + // A drag through the link still selects. + wait(&mut rt); + let l = glyphs(&rt, "linked"); + drag(&mut rt, before(a[15]), before(l[5])); + assert_eq!(rt.selected_text().as_deref(), Some(format!("ere\n{ITEM}\n{CODE}\nleft\tright\nsee do").as_str())); + assert_eq!(rt.state.opened, ["docs"]); +} + +#[test] +fn appended_text_keeps_the_selection_and_a_changed_one_drops_it() { + let mut rt = runtime(); + let a = glyphs(&rt, "a"); + let l = glyphs(&rt, "linked"); + drag(&mut rt, before(a[15]), before(l[5])); + let selected = rt.selected_text().unwrap(); + for word in [" and", " more", " words"] { + rt.state.tail.push_str(word); + rt.invalidate(); + tick(&mut rt); + assert_eq!(rt.selected_text().as_deref(), Some(selected.as_str()), "streaming after the selection keeps it"); + } + assert_eq!(find(&rt, "linked").selected.as_deref(), Some("see do")); + // Shift-click past the old end reaches the new text. + let l = glyphs(&rt, "linked"); + rt.physical_input(PhysicalInput::Modifiers(Mods { shift: true, ..Mods::default() })); + click(&mut rt, (l.last().unwrap().0 + 6.0, l.last().unwrap().1)); + rt.physical_input(PhysicalInput::Modifiers(Mods::default())); + assert!(rt.selected_text().unwrap().ends_with("see docs now and more words")); + // A change inside what's selected drops it. + rt.state.tail = String::new(); + rt.invalidate(); + tick(&mut rt); + assert_eq!(rt.selected_text(), None); +} + +#[test] +fn a_draggable_row_drags_and_clicks_still_select() { + let mut rt = runtime(); + let d0 = glyphs(&rt, "d0"); + let d1 = glyphs(&rt, "d1"); + drag(&mut rt, d0[0], d1[3]); + assert!(rt.state.drags >= 3, "the row drags: {}", rt.state.drags); + assert_eq!(rt.selected_text(), None); + wait(&mut rt); + click(&mut rt, d1[5]); + click(&mut rt, d1[5]); + assert_eq!(rt.selected_text().as_deref(), Some("two")); + command(&mut rt, 'a'); + assert_eq!(rt.selected_text().as_deref(), Some("drag one\tdrag two")); +} + +#[test] +fn a_drag_into_a_gap_reaches_no_further_than_the_pointer() { + let mut rt = runtime(); + let a = glyphs(&rt, "a"); + let li = find(&rt, "li"); + // Down into the gap above the item, by words: the paragraph's end, not the item's first word. + word_drag(&mut rt, a[7], (a[7].0, li.rect[1] - 4.0)); + assert_eq!(rt.selected_text().as_deref(), Some("paragraph here")); + // Released there, it doesn't hang on the block below: that block going keeps it. + rt.state.hide_item = true; + rt.invalidate(); + wait(&mut rt); + assert_eq!(rt.selected_text().as_deref(), Some("paragraph here")); + // Up into a gap: the start of the block below. + let code = glyphs(&rt, "code"); + let block = find(&rt, "block"); + word_drag(&mut rt, code[5], (code[5].0, block.rect[1] - 4.0)); + assert_eq!(rt.selected_text().as_deref(), Some("let x = 1")); +} + +#[test] +fn a_change_between_the_ends_drops_the_selection() { + let changes: [fn(&mut S); 2] = [|s| s.edited = true, |s| s.hide_item = true]; + for change in changes { + let mut rt = runtime(); + let a = glyphs(&rt, "a"); + let code = glyphs(&rt, "code"); + drag(&mut rt, before(a[5]), before(code[3])); + assert_eq!(rt.selected_text().as_deref(), Some("paragraph here\nlist item\nlet ")); + change(&mut rt.state); + rt.invalidate(); + tick(&mut rt); + assert_eq!(rt.selected_text(), None, "a text between rewritten or removed"); + } + // An end with nothing selected in it keeps the selection only while text is appended to it. + let mut rt = runtime(); + let a = glyphs(&rt, "a"); + let code = glyphs(&rt, "code"); + drag(&mut rt, before(a[5]), before(code[0])); + assert_eq!(rt.selected_text().as_deref(), Some("paragraph here\nlist item")); + rt.state.code_changed = true; + rt.invalidate(); + tick(&mut rt); + assert_eq!(rt.selected_text(), None); +} + +/// A table whose first row has a short cell beside a tall one, and an inner group. +fn table_view(_: &S, _: &mut Cx<S>) -> El { + let style = TextStyle::new(14.0, 400.0).lh(20.0); + let t = |content: &str, key: &str| text(content.to_owned()).key(key).font(style).w_full().selectable(true); + let cell = |content: &str, key: &str| col().w(100.0).padding(6.0).child(t(content, key).wrap()); + col().w_full().h_full().padding(10.0) + .child(col().key("doc").w(400.0).selection_group(true) + .child(t("intro words", "intro").mb(12.0)) + .child(row().key("r0").child(cell("short", "s")).child(cell("a tall cell that wraps onto lines", "tall"))) + .child(row().key("r1").child(cell("next row", "n0")).child(cell("more", "n1"))) + .child(col().key("inner").mt(12.0).selection_group(true).child(t("inner one", "i1")).child(t("inner two", "i2"))) + .child(t("outro words", "outro").mt(12.0))) +} + +fn table_runtime() -> Runtime<S> { + let mut rt = Runtime::new(S::default(), table_view, (500.0, 500.0), Env::new(true, 2.0)); + rt.frame(0.0); + rt +} + +const TABLE: &str = "short\ta tall cell that wraps onto lines\nnext row\tmore"; + +#[test] +fn table_rows_select_by_band() { + let mut rt = table_runtime(); + let intro = glyphs(&rt, "intro"); + let (s, tall) = (find(&rt, "s"), find(&rt, "tall")); + assert!(tall.rect[3] > s.rect[3] * 2.0, "the tall cell wraps: {tall:?}"); + // Below the short cell's text but beside the tall one's: still the short cell. + let low = tall.rect[1] + tall.rect[3] - 4.0; + drag(&mut rt, (intro[0].0 - 1.5, intro[0].1), (s.rect[0] + s.rect[2] - 1.0, low)); + assert_eq!(rt.selected_text().as_deref(), Some("intro words\nshort")); + // Into the padding below the row, by words: the row's end, not the next row's first word. + wait(&mut rt); + word_drag(&mut rt, intro[1], (s.rect[0] + 4.0, tall.rect[1] + tall.rect[3] + 3.0)); + assert_eq!(rt.selected_text().as_deref(), Some("intro words\nshort\ta tall cell that wraps onto lines")); +} + +#[test] +fn an_inner_group_is_its_own() { + let mut rt = table_runtime(); + let intro = glyphs(&rt, "intro"); + click(&mut rt, intro[1]); + command(&mut rt, 'a'); + assert_eq!(rt.selected_text().as_deref(), Some(format!("intro words\n{TABLE}\noutro words").as_str())); + assert_eq!(find(&rt, "i1").selected, None); + // A drag across it skips it too. + wait(&mut rt); + let outro = glyphs(&rt, "outro"); + drag(&mut rt, (intro[0].0 - 1.5, intro[0].1), before(outro[5])); + assert_eq!(rt.selected_text().as_deref(), Some(format!("intro words\n{TABLE}\noutro ").as_str())); + // And inside, Cmd+A takes only its texts. + wait(&mut rt); + let i1 = glyphs(&rt, "i1"); + click(&mut rt, i1[1]); + command(&mut rt, 'a'); + assert_eq!(rt.selected_text().as_deref(), Some("inner one\ninner two")); +} + +const CUT: &str = "a line far too long to fit in its box"; +const CLAMPED: &str = "a paragraph clamped to one line though it wraps onto three lines here"; + +fn elided_view(_: &S, _: &mut Cx<S>) -> El { + let style = TextStyle::new(14.0, 400.0).lh(20.0); + let t = |content: &str, key: &str| text(content.to_owned()).key(key).font(style).selectable(true); + col().w_full().h_full().padding(10.0) + .child(col().key("doc").w(160.0).gap(12.0).selection_group(true) + .child(t("top", "top").w_full()) + .child(t(CUT, "cut").w_full().truncate()) + .child(t(CLAMPED, "clamped").w_full().max_lines(1)) + .child(t("end", "end").w_full())) +} + +#[test] +fn elided_texts_select_through_their_ellipsis_and_copy_whole() { + let mut rt = Runtime::new(S::default(), elided_view, (500.0, 500.0), Env::new(true, 2.0)); + rt.frame(0.0); + let (cut, clamped) = (find(&rt, "cut"), find(&rt, "clamped")); + assert!(clamped.rect[3] < 30.0, "clamped to a line: {clamped:?}"); + let top = glyphs(&rt, "top"); + // Into the ellipsis of the cut text: through what it hides. + drag(&mut rt, (top[0].0 - 1.5, top[0].1), (cut.rect[0] + cut.rect[2] - 1.0, cut.rect[1] + cut.rect[3] / 2.0)); + assert_eq!(rt.selected_text().as_deref(), Some(format!("top\n{CUT}").as_str())); + // Across both: each whole, as copying an elided text gives. + wait(&mut rt); + let end = glyphs(&rt, "end"); + drag(&mut rt, (top[0].0 - 1.5, top[0].1), (end[2].0 + 3.0, end[2].1)); + assert_eq!(rt.selected_text().as_deref(), Some(format!("top\n{CUT}\n{CLAMPED}\nend").as_str())); + assert_eq!(find(&rt, "clamped").selected.as_deref(), Some(CLAMPED)); + // Inside the drawn part of the clamped text, by words: only what it covers. + wait(&mut rt); + let y = clamped.rect[1] + clamped.rect[3] / 2.0; + word_drag(&mut rt, (clamped.rect[0] + 3.0, y), (clamped.rect[0] + 40.0, y)); + assert_eq!(rt.selected_text().as_deref(), Some("a paragraph")); +} + +fn rows_view(_: &S, _: &mut Cx<S>) -> El { + let style = TextStyle::new(14.0, 400.0).lh(20.0); + col().w_full().h_full().child( + col().key("scroll").w_full().grow(1.0).scroll(ScrollSpec { stick_bottom: false }).child( + col().key("rows").w_full().growth(GrowthSpec::default()).virtual_rows(400, 60.0, + |_: &S, i| format!("r{i}").into(), + move |_: &S, i| col().w_full().h(60.0).padding(6.0).selection_group(true).children([ + text(format!("row {i} title")).key("a").font(style).w_full().selectable(true), + text(format!("row {i} body")).key("b").font(style).w_full().selectable(true), + ])))) +} + +#[test] +fn a_selection_in_a_virtual_row_scrolled_out_drops_without_panicking() { + let mut rt = Runtime::new(S::default(), rows_view, (400.0, 400.0), Env::new(true, 2.0)); + rt.frame(0.0); + let a = glyphs_at(&rt, "#0/scroll/rows/r0/a"); + let b = glyphs_at(&rt, "#0/scroll/rows/r0/b"); + drag(&mut rt, (a[0].0 - 1.5, a[0].1), (b[b.len() - 1].0 + 3.0, b[0].1)); + assert_eq!(rt.selected_text().as_deref(), Some("row 0 title\nrow 0 body")); + // Mid-drag, the row scrolls out under the held press. + wait(&mut rt); + rt.pointer_move(a[0].0 - 1.5, a[0].1); + rt.pointer_down(a[0].0 - 1.5, a[0].1); + tick(&mut rt); + for _ in 0..40 { + rt.wheel(200.0, 200.0, -400.0); + rt.pointer_move(200.0, 300.0); + tick(&mut rt); + } + rt.pointer_up(200.0, 300.0); + tick(&mut rt); + assert!(!rt.elements().iter().any(|e| e.path == "#0/scroll/rows/r0/a"), "row 0 scrolled out"); + assert_eq!(rt.selected_text().as_deref(), Some("row 0 title\nrow 0 body")); + command(&mut rt, 'c'); + command(&mut rt, 'a'); + // Back up: the pinned row's selection is preserved when it mounts again. + for _ in 0..40 { + rt.wheel(200.0, 200.0, 400.0); + tick(&mut rt); + } + wait(&mut rt); + assert!(rt.elements().iter().any(|e| e.path == "#0/scroll/rows/r0/a")); + assert_eq!(rt.selected_text().as_deref(), Some("row 0 title\nrow 0 body")); +} + diff --git a/app/vendor/rune/crates/rune/tests/integration/selection_hidden.rs b/app/vendor/rune/crates/rune/tests/integration/selection_hidden.rs new file mode 100644 index 0000000..2e9f11b --- /dev/null +++ b/app/vendor/rune/crates/rune/tests/integration/selection_hidden.rs @@ -0,0 +1,88 @@ +//! A drag in a selection group reaches only text that shows. Text clipped out of sight but +//! laid out under the words (a folded part above them) took a drag in a paragraph to its hidden +//! text and selected everything between, in a zoomed page (t973). +use rune::{Cx, El, Env, Runtime, TextStyle, col, text}; + +const SEEN: &str = "the words you can see and drag across"; + +struct S { + zoom: f32, +} + +fn view(s: &S, _: &mut Cx<S>) -> El { + let style = TextStyle::new(14.0, 400.0).lh(20.0); + let t = |content: &str, key: &str| text(content.to_owned()).key(key).font(style).w_full().selectable(true); + let folded = col().key("folded").w_full().h(0.0).clip_rounded(0.0) + .child(t("hidden earlier note one", "h0")) + .child(t("hidden earlier note two", "h1")) + .child(t("hidden earlier note three", "h2")); + col().w_full().h_full().padding(10.0).child( + col().key("page").w(400.0).scale(s.zoom).selection_group(true) + .child(folded) + .child(t("first line above", "a")) + .child(t(SEEN, "seen")) + .child(t("last line below", "b")), + ) +} + +fn drag_in_seen(zoom: f32) -> Option<String> { + let mut rt = Runtime::new(S { zoom }, view, (600.0, 400.0), Env::new(true, 2.0)); + rt.frame(0.0); + let e = rt.elements().into_iter().find(|e| e.key.as_deref() == Some("seen")).unwrap(); + let y = e.rect[1] + e.rect[3] / 2.0; + let (x0, x1) = (e.rect[0] + e.rect[2] * 0.2, e.rect[0] + e.rect[2] * 0.5); + rt.pointer_move(x0, y); + rt.pointer_down(x0, y); + rt.frame(1.0 / 60.0); + for k in 1..=4 { + rt.pointer_move(x0 + (x1 - x0) * k as f32 / 4.0, y + 2.0); + rt.frame(1.0 / 60.0); + } + rt.pointer_up(x1, y + 2.0); + rt.frame(1.0 / 60.0); + rt.selected_text() +} + +#[test] +fn a_drag_skips_text_clipped_out_of_sight() { + for zoom in [1.0, 1.3] { + let sel = drag_in_seen(zoom).expect("the drag selects"); + assert!(!sel.contains("hidden") && !sel.contains('\n') && SEEN.contains(sel.as_str()), "at {zoom}: only the words dragged over: {sel:?}"); + } +} + +const LONG: &str = "a long note folded to its first lines, whose hidden lines run on far below the fold and under the words that come after it, as a long prompt folded in a chat does, line after line after line after line after line after line after line after line after line after line after line after line after line after line after line after line after line"; + +fn partly_folded(_: &S, _: &mut Cx<S>) -> El { + let style = TextStyle::new(14.0, 400.0).lh(20.0); + let t = |content: &str, key: &str| text(content.to_owned()).key(key).font(style).w_full().selectable(true); + col().w_full().h_full().padding(10.0).child( + col().key("page").w(400.0).selection_group(true) + .child(col().key("fold").w_full().h(40.0).clip_rounded(0.0).child(t(LONG, "long").wrap())) + .child(t("first line above", "a")) + .child(t(SEEN, "seen")) + .child(t("last line below", "b")), + ) +} + +#[test] +fn a_drag_skips_the_hidden_lines_of_partly_clipped_text() { + let mut rt = Runtime::new(S { zoom: 1.0 }, partly_folded, (600.0, 600.0), Env::new(true, 2.0)); + rt.frame(0.0); + let e = rt.elements().into_iter().find(|e| e.key.as_deref() == Some("seen")).unwrap(); + let long = rt.elements().into_iter().find(|e| e.key.as_deref() == Some("long")).unwrap(); + assert!(long.rect[1] + long.rect[3] > e.rect[1] + e.rect[3], "the folded text runs on under the words: {:?} {:?}", long.rect, e.rect); + let y = e.rect[1] + e.rect[3] / 2.0; + let (x0, x1) = (e.rect[0] + e.rect[2] * 0.2, e.rect[0] + e.rect[2] * 0.5); + rt.pointer_move(x0, y); + rt.pointer_down(x0, y); + rt.frame(1.0 / 60.0); + for k in 1..=4 { + rt.pointer_move(x0 + (x1 - x0) * k as f32 / 4.0, y + 2.0); + rt.frame(1.0 / 60.0); + } + rt.pointer_up(x1, y + 2.0); + rt.frame(1.0 / 60.0); + let sel = rt.selected_text().expect("the drag selects"); + assert!(!sel.contains('\n') && SEEN.contains(sel.as_str()), "only the words dragged over: {sel:?}"); +} diff --git a/app/vendor/rune/crates/rune/tests/integration/selection_rects_memo.rs b/app/vendor/rune/crates/rune/tests/integration/selection_rects_memo.rs new file mode 100644 index 0000000..0368540 --- /dev/null +++ b/app/vendor/rune/crates/rune/tests/integration/selection_rects_memo.rs @@ -0,0 +1,58 @@ +//! `Cx::selection_rects` when the selected text sits in a `memo` the commit reuses: the +//! reused subtree moves out of the last build while the view's reads settle, and the boxes +//! must still be found. +use std::cell::RefCell; + +use rune::{Anim, Cx, El, Env, Runtime, TextStyle, col, memo, text}; + +#[derive(Default)] +struct S { within: bool, other: u32 } + +thread_local! { + /// What each view run read from `Cx::selection_rects`. + static RECTS: RefCell<Vec<Vec<[f32; 4]>>> = const { RefCell::new(Vec::new()) }; +} + +fn doc() -> El { + let style = TextStyle::new(14.0, 400.0).lh(20.0); + let t = |content: &str, key: &str| text(content.to_owned()).key(key).font(style).w_full().wrap().selectable(true); + col().key("doc").w(280.0).gap(12.0).selection_group(true) + .child(t("first paragraph", "a")) + .child(t("second paragraph", "b")) +} + +fn view(s: &S, cx: &mut Cx<S>) -> El { + RECTS.with_borrow_mut(|r| r.push(cx.selection_rects())); + let root = col().key("root").w_full().h_full().padding(10.0).gap(12.0) + .child(memo("doc", 0, doc)) + .child(text(format!("{}", s.other)).key("other")); + // A view builds a new pair each run, as an app's root does. + if s.within { root.hover_motion_within(Anim::INSTANT, Anim::INSTANT) } else { root } +} + +fn last_rects() -> Vec<[f32; 4]> { RECTS.with_borrow(|r| r.last().cloned().unwrap_or_default()) } + +fn selected_then_recommitted(within: bool) { + let mut rt = Runtime::new(S { within, other: 0 }, view, (400.0, 300.0), Env::new(true, 2.0)); + let mut t = 0.0; + let mut tick = |rt: &mut Runtime<S>| { t += 1.0 / 60.0; rt.frame(t); }; + tick(&mut rt); + rt.update(|_, tx| tx.select_text("a", 0..5)); + tick(&mut rt); + tick(&mut rt); + assert_eq!(last_rects().len(), 1, "after the commit that selects: {:?}", last_rects()); + rt.update(|s, _| s.other += 1); + tick(&mut rt); + tick(&mut rt); + assert_eq!(last_rects().len(), 1, "after a later commit: {:?}", last_rects()); +} + +#[test] +fn selection_rects_find_text_in_a_reused_memo() { + selected_then_recommitted(false); +} + +#[test] +fn selection_rects_find_text_in_a_reused_memo_under_hover_motion_within() { + selected_then_recommitted(true); +} diff --git a/app/vendor/rune/crates/rune/tests/integration/selection_run.rs b/app/vendor/rune/crates/rune/tests/integration/selection_run.rs new file mode 100644 index 0000000..ea0cbb8 --- /dev/null +++ b/app/vendor/rune/crates/rune/tests/integration/selection_run.rs @@ -0,0 +1,43 @@ +//! Words flowed as separate selectable texts draw one continuous highlight per line. + +use rune::{Cx, El, Env, Key, KeyEvent, Mods, Runtime, TextStyle, row, text}; + +fn view(_: &(), _: &mut Cx<()>) -> El { + let style = TextStyle::new(14.0, 400.0).lh(20.0); + let hl = rune::color::hex("#3080ff").unwrap().alpha(0.3); + let words = ["one ", "two ", "three ", "four"].map(|w| text(w).font(style).selectable(true).selection_color(hl)); + row().w_full().padding(10.0).selection_group(true).children(words) +} + +#[test] +fn a_run_of_words_is_one_rect() { + let mut rt = Runtime::new((), view, (400.0, 100.0), Env::new(true, 2.0)); + rt.frame(0.0); + rt.key(KeyEvent { key: Key::Command('a'), mods: Mods { cmd: true, ..Mods::default() } }); + rt.frame(1.0 / 60.0); + let want = rune::color::hex("#3080ff").unwrap().alpha(0.3).premul(1.0); + let n = rt.instances.iter().filter(|i| i.fill.iter().zip(want).all(|(a, b)| (a - b).abs() < 1e-3)).count(); + assert_eq!(n, 1, "four words, one highlight"); +} + +fn chipped(_: &(), _: &mut Cx<()>) -> El { + let style = TextStyle::new(14.0, 400.0).lh(20.0); + let big = TextStyle::new(11.0, 400.0).lh(14.0); + let hl = rune::color::hex("#3080ff").unwrap().alpha(0.3); + let chip = row().padding(6.0).child(text("abc").font(big).selectable(true).selection_color(hl)); + row().w_full().padding(10.0).selection_group(true) + .child(text("one ").font(style).selectable(true).selection_color(hl)) + .child(chip) + .child(text(" two").font(style).selectable(true).selection_color(hl)) +} + +#[test] +fn a_chip_does_not_break_the_run() { + let mut rt = Runtime::new((), chipped, (400.0, 100.0), Env::new(true, 2.0)); + rt.frame(0.0); + rt.key(KeyEvent { key: Key::Command('a'), mods: Mods { cmd: true, ..Mods::default() } }); + rt.frame(1.0 / 60.0); + let want = rune::color::hex("#3080ff").unwrap().alpha(0.3).premul(1.0); + let n = rt.instances.iter().filter(|i| i.fill.iter().zip(want).all(|(a, b)| (a - b).abs() < 1e-3)).count(); + assert_eq!(n, 1, "words and the chip between them, one highlight"); +} diff --git a/app/vendor/rune/crates/rune/tests/integration/selection_toolbar.rs b/app/vendor/rune/crates/rune/tests/integration/selection_toolbar.rs new file mode 100644 index 0000000..d210f46 --- /dev/null +++ b/app/vendor/rune/crates/rune/tests/integration/selection_toolbar.rs @@ -0,0 +1,258 @@ +//! What a toolbar floating over a text selection reads: `Cx::selection_rects` for where its +//! lines are, `TextSelection::backward` for which end the pointer is at, +//! `SelectionChange::dragging` to wait for the release, and `El::keeps_text_selection` so a +//! press on the toolbar leaves the selection and the focus alone. +use std::cell::RefCell; + +use rune::{Cx, El, ElementInfo, Env, Mods, PhysicalInput, Runtime, ScrollSpec, TextEdit, TextStyle, col, text, text_input}; + +#[derive(Default)] +struct S { heard: Vec<Heard>, presses: u32, read_rects: bool, field: TextEdit, backward: Option<bool> } + +/// One `on_selection_change` call: the selection's text, and whether a press is making it. +#[derive(Debug, PartialEq)] +struct Heard(Option<String>, bool); + +thread_local! { + /// What each view run read from `Cx::selection_rects`. + static RECTS: RefCell<Vec<Vec<[f32; 4]>>> = const { RefCell::new(Vec::new()) }; +} + +const LONG: &str = "alpha beta gamma delta epsilon zeta eta theta iota kappa lambda mu"; + +fn view(s: &S, cx: &mut Cx<S>) -> El { + if s.read_rects { RECTS.with_borrow_mut(|r| r.push(cx.selection_rects())); } + let style = TextStyle::new(14.0, 400.0).lh(20.0); + let t = |content: &str, key: &str| text(content.to_owned()).key(key).font(style).w_full().wrap().selectable(true); + col().w_full().h_full().padding(10.0).gap(12.0) + .child(col().key("scroller").w(300.0).h(200.0).scroll(ScrollSpec { stick_bottom: false }).child( + col().key("doc").w(280.0).gap(12.0).selection_group(true) + .on_selection_change(|s: &mut S, c, _| { + s.heard.push(Heard(c.selection().map(|t| t.text().to_owned()), c.dragging())); + s.backward = c.selection().map(|t| t.backward()); + }) + .child(t("first paragraph", "a")) + .child(t(LONG, "b")) + .child(col().w_full().h(400.0)), + )) + .child(col().key("toolbar").w(80.0).h(24.0).keeps_text_selection().focusable(true) + .on_press(|s: &mut S| s.presses += 1)) + .child(text_input(&s.field, style).single_line().key("field").w(300.0).on_edit(|s: &mut S| &mut s.field)) +} + +fn runtime() -> Runtime<S> { + let mut rt = Runtime::new(S::default(), view, (500.0, 500.0), Env::new(true, 2.0)); + rt.frame(0.0); + rt +} + +fn tick(rt: &mut Runtime<S>) { rt.frame(1.0 / 60.0); } + +fn el(rt: &Runtime<S>, key: &str) -> ElementInfo { + rt.elements().into_iter().find(|e| e.key.as_deref() == Some(key)).unwrap() +} + +fn heard(rt: &mut Runtime<S>) -> Vec<Heard> { std::mem::take(&mut rt.state.heard) } + +/// Code's selection is heard, and read, the frame after the handler's commit. +fn act(rt: &mut Runtime<S>, f: impl FnOnce(&mut rune::Tx)) { + rt.update(|_, tx| f(tx)); + tick(rt); + tick(rt); +} + +fn last_rects() -> Vec<[f32; 4]> { RECTS.with_borrow(|r| r.last().cloned().unwrap_or_default()) } + +/// Drags across text "a" from `from` to `to` (fractions of its width), a frame per step. +fn drag_a(rt: &mut Runtime<S>, from: f32, to: f32) { + let a = el(rt, "a"); + let y = a.rect[1] + a.rect[3] / 2.0; + let x = |f: f32| a.rect[0] + a.rect[2] * f; + rt.pointer_move(x(from), y); + rt.pointer_down(x(from), y); + tick(rt); + for k in 1..=4 { + rt.pointer_move(x(from + (to - from) * k as f32 / 4.0), y); + tick(rt); + } +} + +#[test] +fn selection_rects_are_the_selected_lines_and_follow_scrolling() { + let mut rt = runtime(); + rt.update(|s, _| s.read_rects = true); + tick(&mut rt); + assert!(last_rects().is_empty(), "nothing selected"); + + act(&mut rt, |tx| tx.select_text("a", 0..5)); + let a = el(&rt, "a"); + let [r] = last_rects()[..] else { panic!("one line: {:?}", last_rects()) }; + assert!((r[0] - a.rect[0]).abs() < 1.0 && r[2] > 10.0 && r[2] < a.rect[2], "{r:?} in {:?}", a.rect); + assert!(r[1] >= a.rect[1] - 0.5 && r[1] + r[3] <= a.rect[1] + a.rect[3] + 0.5, "{r:?} in {:?}", a.rect); + + // Across texts: a box per line, in reading order. + act(&mut rt, |tx| tx.select_all_text("doc")); + let boxes = last_rects(); + let b = el(&rt, "b"); + assert!(boxes.len() >= 3, "a's line and b's wrapped lines: {boxes:?}"); + assert!(boxes.windows(2).all(|w| w[0][1] <= w[1][1]), "{boxes:?}"); + assert!(boxes.last().is_some_and(|r| r[1] + r[3] <= b.rect[1] + b.rect[3] + 0.5), "{boxes:?}"); + + // Scrolling moves them, and re-runs the view. + let before = last_rects(); + let (sx, sy) = { let s = el(&rt, "scroller"); (s.rect[0] + 10.0, s.rect[1] + 10.0) }; + rt.wheel(sx, sy, -40.0); + for _ in 0..30 { tick(&mut rt); } + let after = last_rects(); + assert_eq!(after.len(), before.len()); + let dy = before[0][1] - after[0][1]; + assert!(dy.abs() > 5.0 && after.iter().zip(&before).all(|(a, b)| (b[1] - a[1] - dy).abs() < 0.5), "{before:?} -> {after:?}"); + + // Clearing empties them. + act(&mut rt, |tx| tx.clear_text_selection()); + assert!(last_rects().is_empty()); +} + +#[test] +fn a_view_not_reading_selection_rects_does_not_rerun_as_a_drag_moves() { + let mut rt = runtime(); + RECTS.with_borrow_mut(Vec::clear); + drag_a(&mut rt, 0.1, 0.9); + assert!(RECTS.with_borrow(Vec::is_empty)); +} + +#[test] +fn backward_says_which_way_the_selection_was_made() { + let mut rt = runtime(); + drag_a(&mut rt, 0.1, 0.9); + assert_eq!(rt.state.backward, Some(false)); + let a = el(&rt, "a"); + rt.pointer_up(a.rect[0] + a.rect[2] * 0.9, a.rect[1] + 5.0); + tick(&mut rt); + drag_a(&mut rt, 0.9, 0.1); + assert_eq!(rt.state.backward, Some(true), "dragged to the left"); + // Into another text of the group, upward. + let (a, b) = (el(&rt, "a"), el(&rt, "b")); + rt.pointer_up(a.rect[0] + 5.0, a.rect[1] + 5.0); + tick(&mut rt); + rt.pointer_move(b.rect[0] + 40.0, b.rect[1] + 5.0); + rt.pointer_down(b.rect[0] + 40.0, b.rect[1] + 5.0); + tick(&mut rt); + rt.pointer_move(a.rect[0] + 20.0, a.rect[1] + 5.0); + tick(&mut rt); + assert_eq!(rt.state.backward, Some(true), "dragged up into the text above"); + act(&mut rt, |tx| tx.select_text("b", 3..9)); + assert_eq!(rt.state.backward, Some(false), "code selects forward"); +} + +#[test] +fn a_drag_is_heard_dragging_then_once_more_when_it_releases() { + let mut rt = runtime(); + drag_a(&mut rt, 0.05, 0.6); + let calls = heard(&mut rt); + assert!(!calls.is_empty() && calls.iter().all(|c| c.1 && c.0.is_some()), "{calls:?}"); + let text = calls.last().unwrap().0.clone(); + let a = el(&rt, "a"); + rt.pointer_up(a.rect[0] + a.rect[2] * 0.6, a.rect[1] + a.rect[3] / 2.0); + tick(&mut rt); + assert_eq!(heard(&mut rt), [Heard(text, false)], "the release, with the same selection"); + tick(&mut rt); + assert_eq!(heard(&mut rt), [], "once"); +} + +#[test] +fn a_click_without_moving_is_not_heard_on_release() { + let mut rt = runtime(); + act(&mut rt, |tx| tx.select_text("a", 0..5)); + assert_eq!(heard(&mut rt), [Heard(Some("first".into()), false)], "code isn't dragging"); + let a = el(&rt, "a"); + let (x, y) = (a.rect[0] + a.rect[2] * 0.7, a.rect[1] + a.rect[3] / 2.0); + rt.pointer_move(x, y); + rt.pointer_down(x, y); + tick(&mut rt); + assert_eq!(heard(&mut rt), [Heard(None, true)], "the press clears it"); + rt.pointer_up(x, y); + tick(&mut rt); + assert_eq!(heard(&mut rt), [], "a caret has nothing to release"); +} + +#[test] +fn a_double_click_drag_by_words_is_dragging_until_it_releases() { + let mut rt = runtime(); + let b = el(&rt, "b"); + let (x, y) = (b.rect[0] + 3.0, b.rect[1] + 8.0); + rt.pointer_move(x, y); + rt.pointer_down(x, y); + rt.pointer_up(x, y); + rt.pointer_down(x, y); + tick(&mut rt); + assert_eq!(heard(&mut rt), [Heard(Some("alpha".into()), true)], "the second press selects a word"); + rt.pointer_move(x + 60.0, y); + tick(&mut rt); + let calls = heard(&mut rt); + let [Heard(Some(words), true)] = &calls[..] else { panic!("{calls:?}") }; + assert!(words.starts_with("alpha ") && words.split(' ').count() >= 2, "whole words: {words:?}"); + rt.pointer_up(x + 60.0, y); + tick(&mut rt); + assert_eq!(heard(&mut rt), [Heard(Some(words.clone()), false)]); +} + +#[test] +fn a_press_on_a_keeps_text_selection_element_keeps_the_selection_and_focus() { + let mut rt = runtime(); + rt.update(|s, _| { + s.field = TextEdit::new("typed"); + s.field.focused = true; + }); + tick(&mut rt); + act(&mut rt, |tx| tx.select_text("a", 0..5)); + heard(&mut rt); + assert!(el(&rt, "field").focused); + + let bar = el(&rt, "toolbar"); + let (x, y) = (bar.rect[0] + 10.0, bar.rect[1] + 10.0); + rt.pointer_move(x, y); + rt.pointer_down(x, y); + tick(&mut rt); + rt.pointer_up(x, y); + tick(&mut rt); + assert_eq!(rt.state.presses, 1, "the press still lands"); + assert_eq!(rt.selected_text().as_deref(), Some("first"), "the selection survives"); + assert!(el(&rt, "field").focused, "focus stays put"); + assert!(!el(&rt, "toolbar").focused, "a focusable toolbar doesn't take it"); + assert_eq!(heard(&mut rt), []); + + // A drag that starts on it doesn't start a selection, even over the text. + let a = el(&rt, "a"); + rt.pointer_down(x, y); + tick(&mut rt); + rt.pointer_move(a.rect[0] + 30.0, a.rect[1] + 5.0); + tick(&mut rt); + rt.pointer_move(a.rect[0] + 90.0, a.rect[1] + 5.0); + tick(&mut rt); + rt.pointer_up(a.rect[0] + 90.0, a.rect[1] + 5.0); + tick(&mut rt); + assert_eq!(rt.selected_text().as_deref(), Some("first")); + assert_eq!(heard(&mut rt), []); +} + +#[test] +fn a_shift_click_extension_is_dragging_until_it_releases() { + // Selectable text has no Shift+arrow; Shift+click is how the keyboard extends it. + let mut rt = runtime(); + act(&mut rt, |tx| tx.select_text("a", 0..5)); + heard(&mut rt); + rt.physical_input(PhysicalInput::Modifiers(Mods { shift: true, ..Mods::default() })); + let b = el(&rt, "b"); + let (x, y) = (b.rect[0] + 40.0, b.rect[1] + 8.0); + rt.pointer_move(x, y); + rt.pointer_down(x, y); + tick(&mut rt); + let calls = heard(&mut rt); + let [Heard(Some(text), true)] = &calls[..] else { panic!("{calls:?}") }; + assert!(text.starts_with("first paragraph\nalpha"), "{text:?}"); + rt.pointer_up(x, y); + tick(&mut rt); + rt.physical_input(PhysicalInput::Modifiers(Mods::default())); + assert_eq!(heard(&mut rt), [Heard(Some(text.clone()), false)]); +} diff --git a/app/vendor/rune/crates/rune/tests/integration/shape_fade.rs b/app/vendor/rune/crates/rune/tests/integration/shape_fade.rs new file mode 100644 index 0000000..b8bff57 --- /dev/null +++ b/app/vendor/rune/crates/rune/tests/integration/shape_fade.rs @@ -0,0 +1,73 @@ +//! A fading canvas whose pieces overlap takes its opacity once, through a layer: where two +//! strokes cross or a polyline turns it is no darker than one stroke alone. At rest, and for a +//! shape of one piece, it paints straight to the window as before. + +use rune::render::{Gpu, Instance, KIND_LAYER, OFFSCREEN_FORMAT, Offscreen, Renderer}; +use rune::{Color, Cx, El, Env, Runtime, Shape, canvas, el}; + +const SIZE: (u32, u32) = (80, 80); + +type State = (Shape, f32); + +/// The shape on a 40 pt canvas at an opacity, in a window of the same size, at 2x. +fn view(s: &State, _: &mut Cx<State>) -> El { + el().size(40.0, 40.0).child(canvas(s.0.clone()).size(40.0, 40.0).opacity(s.1)) +} + +fn frame(shape: Shape, opacity: f32) -> Runtime<State> { + let mut rt = Runtime::new((shape, opacity), view, (40.0, 40.0), Env::new(true, 2.0)); + rt.frame(0.0); + rt +} + +fn layered(instances: &[Instance]) -> bool { + instances.iter().any(|i| i.params[1] == KIND_LAYER) +} + +fn pixels(gpu: &Gpu, rt: &mut Runtime<State>) -> Vec<u8> { + let mut renderer = Renderer::new(&gpu.device, OFFSCREEN_FORMAT); + let target = Offscreen::new(&gpu.device, SIZE.0, SIZE.1); + renderer.prepare(&gpu.device, &gpu.queue, &mut rt.text.atlas, &rt.instances, SIZE); + let mut encoder = gpu.device.create_command_encoder(&Default::default()); + renderer.draw(&mut encoder, &target.view, [0.0; 4]); + target.copy(&mut encoder); + gpu.queue.submit([encoder.finish()]); + target.read(&gpu.device) +} + +fn px(out: &[u8], x: usize, y: usize) -> [u8; 4] { + out[(y * SIZE.0 as usize + x) * 4..][..4].try_into().unwrap() +} + +fn cross() -> Shape { + Shape::new().stroke(vec![[0.0, 20.0], [40.0, 20.0]], 8.0, Color::WHITE).stroke(vec![[20.0, 0.0], [20.0, 40.0]], 8.0, Color::WHITE) +} + +fn corner() -> Shape { + Shape::new().stroke(vec![[4.0, 20.0], [20.0, 20.0], [20.0, 36.0]], 8.0, Color::WHITE) +} + +#[test] +fn only_a_fading_shape_of_several_pieces_paints_through_a_layer() { + for shape in [cross(), corner()] { + assert!(!layered(&frame(shape.clone(), 1.0).instances), "at rest it paints straight to the window"); + assert!(layered(&frame(shape.clone(), 0.5).instances), "mid-fade it takes its opacity once"); + assert!(!layered(&frame(shape, 0.0).instances), "faded out"); + } + let line = Shape::new().line([0.0, 20.0], [40.0, 20.0], 8.0, rune::LineCap::Round, Color::WHITE); + assert!(!layered(&frame(line, 0.5).instances), "one segment can't overlap itself"); +} + +#[test] +fn where_faded_pieces_meet_is_no_darker_than_one() { + let gpu = Gpu::headless(); + // (40, 40) px is where the cross's strokes and the corner's segments meet; (8, 40) and + // (16, 40) are on one stroke alone. + for (shape, alone) in [(cross(), (8, 40)), (corner(), (16, 40))] { + let half = pixels(&gpu, &mut frame(shape.clone(), 0.5)); + assert_eq!(px(&half, 40, 40), px(&half, alone.0, alone.1), "the joint at 50%"); + assert!((120..=136).contains(&px(&half, 40, 40)[3]), "half covered: {:?}", px(&half, 40, 40)); + let full = pixels(&gpu, &mut frame(shape, 1.0)); + assert_eq!(px(&full, 40, 40), px(&full, alone.0, alone.1), "the joint at rest"); + } +} diff --git a/app/vendor/rune/crates/rune/tests/integration/srgb_blend_runtime.rs b/app/vendor/rune/crates/rune/tests/integration/srgb_blend_runtime.rs new file mode 100644 index 0000000..7f01de3 --- /dev/null +++ b/app/vendor/rune/crates/rune/tests/integration/srgb_blend_runtime.rs @@ -0,0 +1,171 @@ +//! A runtime the app draws itself (`Runtime::with_text`, a headless snapshot) can blend in sRGB +//! with `Runtime::set_srgb_blend`, hover and press tints included, as an `App::srgb_blend` +//! window does. +use rune::color::over; +use rune::render::{Gpu, OFFSCREEN_FORMAT, Offscreen, Renderer}; +use rune::text::TextSystem; +use rune::{Color, Cx, El, Env, Runtime, el}; + +const RED: Color = Color { r: 1.0, g: 0.0, b: 0.0, a: 1.0 }; + +fn view(_: &(), _: &mut Cx<()>) -> El { + el().size(40.0, 40.0).fill(Color::BLACK) + .child(el().size(20.0, 20.0).fill(RED).hover(Color::WHITE.alpha(0.5)).on_press(|_: &mut ()| {})) +} + +fn hovered(srgb: bool) -> Runtime<()> { + let text = TextSystem::new(&[], ("Inter", "Inter")); + let mut rt = Runtime::with_text((), view, (40.0, 40.0), Env::new(true, 1.0), text); + rt.set_srgb_blend(srgb); + rt.frame(0.0); + rt.pointer_move(10.0, 10.0); + rt.frame(1.0 / 60.0); + rt +} + +/// The child's fill, with the hover tint composited over it. +fn tinted(rt: &Runtime<()>) -> [f32; 4] { + rt.instances.iter().find(|i| i.rect[2] == 20.0 && i.rect[3] == 20.0).expect("the child's box").fill +} + +fn pixel(gpu: &Gpu, rt: &mut Runtime<()>) -> [u8; 4] { + let format = if rt.srgb_blend() { OFFSCREEN_FORMAT.remove_srgb_suffix() } else { OFFSCREEN_FORMAT }; + let mut renderer = Renderer::new(&gpu.device, format); + renderer.set_srgb_blend(rt.srgb_blend()); + let target = Offscreen::with_format(&gpu.device, 40, 40, format); + renderer.prepare(&gpu.device, &gpu.queue, &mut rt.text.atlas, &rt.instances, (40, 40)); + let mut encoder = gpu.device.create_command_encoder(&Default::default()); + renderer.draw(&mut encoder, &target.view, rt.clear_color()); + target.copy(&mut encoder); + renderer.submit(&gpu.queue, encoder); + let px = target.read(&gpu.device); + let at = (10 * 40 + 10) * 4; + [px[at], px[at + 1], px[at + 2], px[at + 3]] +} + +#[test] +fn hover_tints_follow_the_runtime_blend_mode() { + let tint = Color::WHITE.alpha(0.5); + let srgb = hovered(true); + assert!(srgb.srgb_blend()); + assert_eq!(tinted(&srgb), over(tint.premul_srgb(1.0), RED.premul_srgb(1.0)), "composited in sRGB encoding"); + let linear = hovered(false); + assert_eq!(tinted(&linear), over(tint.premul(1.0), RED.premul(1.0)), "composited linearly"); +} + +#[test] +fn a_self_drawn_runtime_renders_gamma_blended_pixels() { + let gpu = Gpu::headless(); + let near = |got: [u8; 4], want: [u8; 4]| assert!(got.iter().zip(want).all(|(g, w)| g.abs_diff(w) <= 1), "{got:?} != {want:?}"); + // Half white over red: 128 in sRGB space, as CSS draws it; linear light reads 188. + near(pixel(&gpu, &mut hovered(true)), [255, 128, 128, 255]); + near(pixel(&gpu, &mut hovered(false)), [255, 188, 188, 255]); +} + +#[test] +fn switching_blend_mode_redraws() { + let mut rt = hovered(false); + rt.frame(1.0); + let commits = rt.stats.commits; + rt.set_srgb_blend(true); + rt.frame(1.0 / 60.0); + assert!(rt.stats.commits > commits, "a change asks for a frame"); + assert_eq!(tinted(&rt), over(Color::WHITE.alpha(0.5).premul_srgb(1.0), RED.premul_srgb(1.0))); + let commits = rt.stats.commits; + rt.set_srgb_blend(true); + rt.frame(1.0 / 60.0); + assert_eq!(rt.stats.commits, commits, "the same mode is no change"); +} + +#[test] +fn a_handler_switches_blend_mode_live() { + let mut rt = hovered(false); + rt.update(|_, tx| tx.set_srgb_blend(true)); + assert!(rt.srgb_blend()); + rt.frame(1.0 / 60.0); + assert_eq!(tinted(&rt), over(Color::WHITE.alpha(0.5).premul_srgb(1.0), RED.premul_srgb(1.0))); + rt.update(|_, tx| { tx.set_srgb_blend(true); tx.set_srgb_blend(false); }); + assert!(!rt.srgb_blend(), "the last request wins"); +} + +/// A headless run follows a switch made by a handler: the renderer, its target and the +/// compositor's `Frame` change format on the frame that switches. +#[test] +fn a_headless_run_follows_a_live_switch() { + use rune::compose::{Compositor, Frame}; + use rune::{App, AppSpec}; + use std::sync::Mutex; + + static SEEN: Mutex<Vec<(bool, wgpu::TextureFormat)>> = Mutex::new(Vec::new()); + struct Watch; + impl Compositor<()> for Watch { + fn render(&mut self, f: &mut Frame<'_, ()>) { + SEEN.lock().unwrap().push((f.srgb_blend(), f.format)); + f.draw_ui(); + } + } + let dir = std::env::temp_dir().join(format!("rune-srgb-live-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let (script, png) = (dir.join("script.json"), dir.join("snap.png")); + std::fs::write(&script, r#"[{"t": 0.1, "type": "click", "x": 20, "y": 20}]"#).unwrap(); + let view = |_: &(), _: &mut Cx<()>| { + el().size(40.0, 40.0).fill(RED) + .child(el().size(40.0, 40.0).fill(Color::WHITE.alpha(0.5))) + .on_press_tx(|_: &mut (), tx| tx.set_srgb_blend(true)) + }; + App::new(AppSpec::new("srgb-live", (40.0, 40.0), || (), view)).srgb_blend(false).compositor(Watch) + .args(["--snap", png.to_str().unwrap(), "--scale", "1", "--script", script.to_str().unwrap(), "--at", "0.5"].map(String::from)) + .run(); + let decoder = png::Decoder::new(std::io::BufReader::new(std::fs::File::open(&png).unwrap())); + let mut reader = decoder.read_info().unwrap(); + let mut buf = vec![0u8; reader.output_buffer_size().unwrap()]; + reader.next_frame(&mut buf).unwrap(); + std::fs::remove_dir_all(&dir).unwrap(); + let at = (20 * 40 + 20) * 4; + let px = &buf[at..at + 4]; + // Half white over red reads 128 blended in sRGB, 188 in linear light. + assert!(px[1].abs_diff(128) <= 1 && px[0] == 255, "gamma-blended after the switch, got {px:?}"); + let seen = SEEN.lock().unwrap(); + assert_eq!(seen.first(), Some(&(false, OFFSCREEN_FORMAT)), "starts linear"); + assert_eq!(seen.last(), Some(&(true, OFFSCREEN_FORMAT.remove_srgb_suffix())), "ends gamma-space"); +} + +#[test] +fn switching_format_keeps_the_glyph_atlas_and_extra_pipelines() { + let gpu = Gpu::headless(); + let text = TextSystem::new(&[], ("Inter", "Inter")); + let view = |_: &(), _: &mut Cx<()>| { + el().size(80.0, 40.0).fill(RED) + .child(rune::text("hello")) + }; + let mut rt = Runtime::with_text((), view, (80.0, 40.0), Env::new(true, 1.0), text); + rt.frame(0.0); + let mut renderer = Renderer::new(&gpu.device, OFFSCREEN_FORMAT); + renderer.add_format(&gpu.device, wgpu::TextureFormat::Rgba16Float); + renderer.prepare(&gpu.device, &gpu.queue, &mut rt.text.atlas, &rt.instances, (80, 40)); + assert!(rt.text.atlas.dirty.is_none(), "initial prepare drained the atlas"); + + rt.set_srgb_blend(true); + rt.frame(1.0 / 60.0); + let non_srgb = OFFSCREEN_FORMAT.remove_srgb_suffix(); + renderer.set_format(&gpu.device, non_srgb); + renderer.set_srgb_blend(true); + assert_eq!(renderer.format(), non_srgb); + assert!(rt.text.atlas.dirty.is_none(), "switching blend format keeps the uploaded glyph atlas"); + + let layer = Offscreen::with_format(&gpu.device, 80, 40, wgpu::TextureFormat::Rgba16Float); + renderer.prepare(&gpu.device, &gpu.queue, &mut rt.text.atlas, &rt.instances, (80, 40)); + let mut encoder = gpu.device.create_command_encoder(&Default::default()); + { + let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { + label: None, + color_attachments: &[Some(wgpu::RenderPassColorAttachment { + view: &layer.view, depth_slice: None, resolve_target: None, + ops: wgpu::Operations { load: wgpu::LoadOp::Clear(wgpu::Color::BLACK), store: wgpu::StoreOp::Store }, + })], + depth_stencil_attachment: None, timestamp_writes: None, occlusion_query_set: None, multiview_mask: None, + }); + renderer.draw_range(&mut pass, wgpu::TextureFormat::Rgba16Float, 0..rt.instances.len() as u32); + } + renderer.submit(&gpu.queue, encoder); +} diff --git a/app/vendor/rune/crates/rune/tests/integration/stick_fit.rs b/app/vendor/rune/crates/rune/tests/integration/stick_fit.rs new file mode 100644 index 0000000..c9adaf1 --- /dev/null +++ b/app/vendor/rune/crates/rune/tests/integration/stick_fit.rs @@ -0,0 +1,80 @@ +//! A stuck-to-bottom scroll whose content crosses between overflowing and fitting while the +//! viewport resizes (a banner above it opening or closing) keeps its rows in place: no jump +//! and slide back, in either direction, for bottom-aligned and top-aligned content alike. +use rune::{Cx, El, Env, GrowthSpec, Runtime, ScrollSpec, col, el}; + +#[derive(Default)] +struct S { banner: bool, rows: usize, end: bool, virtualized: bool, pad: f32 } + +fn view(s: &S, _: &mut Cx<S>) -> El { + let mut stack = col().key("stack").w_full().pb(s.pad).growth(GrowthSpec::default()); + if s.end { stack = stack.grow(1.0).justify_end(); } + if s.virtualized { stack = stack.virtualize(50.0); } + for i in 0..s.rows { + stack = stack.child(el().key(format!("r{i}")).w_full().h(50.0)); + } + col().w_full().h_full() + .child(el().key("banner").w_full().h(if s.banner { 55.0 } else { 0.0 })) + .child(col().key("scroll").w_full().grow(1.0).shrink().min_h(0.0).scroll(ScrollSpec { stick_bottom: true }).child(stack)) +} + +/// The drawn bottom edge of row `key`. +fn bottom(rt: &Runtime<S>, key: &str) -> f32 { + let e = rt.elements().into_iter().find(|e| e.key.as_deref() == Some(key)).unwrap_or_else(|| panic!("{key}")); + e.rect[1] + e.rect[3] +} + +/// The first row's drawn bottom and the last row's, every frame after `change`. +fn run(state: S, change: fn(&mut S)) -> Vec<(f32, f32)> { + let mut rt = Runtime::new(state, view, (300.0, 400.0), Env::new(true, 2.0)); + rt.frame(0.0); + for _ in 0..60 { rt.frame(1.0 / 120.0); } + let sample = |rt: &Runtime<S>| (bottom(rt, "r0"), bottom(rt, &format!("r{}", rt.state.rows - 1))); + let mut out = vec![sample(&rt)]; + change(&mut rt.state); + rt.invalidate(); + for _ in 0..120 { + rt.frame(1.0 / 120.0); + out.push(sample(&rt)); + } + out +} + +/// Largest move of the last row between frames. +fn largest_step(frames: &[(f32, f32)]) -> f32 { + frames.windows(2).fold(0.0f32, |m, w| m.max((w[1].1 - w[0].1).abs())) +} + +#[test] +fn rows_stay_put_across_the_fit_overflow_boundary() { + // 7 rows x 50 = 350 (+12 bottom padding): overflows a 345pt viewport (banner open), fits a + // 400pt one. Padded rows rest the padding above the bottom. + for (virtualized, pad) in [(false, 0.0), (true, 0.0), (false, 12.0), (true, 12.0)] { + let closes = |s: &mut S| s.banner = false; + let opens = |s: &mut S| s.banner = true; + for (what, banner, change) in [("closes", true, closes as fn(&mut S)), ("opens", false, opens)] { + // Bottom-aligned rows (a chat that fills from the bottom) hold the bottom edge. + let frames = run(S { rows: 7, banner, end: true, virtualized, pad }, change); + let worst = frames.iter().fold(0.0f32, |m, f| m.max((f.1 - (400.0 - pad)).abs())); + assert!(worst < 0.6, "end, virtual {virtualized}, pad {pad}, banner {what}: the last row left the bottom by {worst}: {frames:?}"); + + // Top-aligned rows move between the top and the bottom, but glide there. + let frames = run(S { rows: 7, banner, end: false, virtualized, pad }, change); + let step = largest_step(&frames); + assert!(step < 4.0, "top, virtual {virtualized}, pad {pad}, banner {what}: rows jumped {step}: {frames:?}"); + let last = frames.last().unwrap().1; + let rest = if banner { 350.0 } else { 400.0 - pad }; + assert!((last - rest).abs() < 0.05, "top, virtual {virtualized}, pad {pad}, banner {what}: lands at {last}"); + } + } +} + +#[test] +fn a_new_row_in_a_bottom_aligned_list_pushes_the_others_up() { + let frames = run(S { rows: 5, end: true, ..S::default() }, |s| s.rows += 1); + let first = frames.iter().map(|f| f.0).collect::<Vec<_>>(); + let step = first.windows(2).fold(0.0f32, |m, w| m.max((w[1] - w[0]).abs())); + assert!(step < 4.0, "the older rows glide up as the new one grows: {first:?}"); + assert!((first.last().unwrap() - 150.0).abs() < 0.05, "{first:?}"); + assert!(frames.iter().all(|f| (f.1 - 400.0).abs() < 0.6), "the new row grows from the bottom: {frames:?}"); +} diff --git a/app/vendor/rune/crates/rune/tests/integration/stick_resize.rs b/app/vendor/rune/crates/rune/tests/integration/stick_resize.rs new file mode 100644 index 0000000..381fa15 --- /dev/null +++ b/app/vendor/rune/crates/rune/tests/integration/stick_resize.rs @@ -0,0 +1,99 @@ +//! A stuck-to-bottom scroll keeps its last row on its bottom edge while its own height +//! animates (a banner opening above the timeline), on every frame. +use rune::runtime::ElementInfo; +use rune::{Cx, El, Env, GrowthSpec, Runtime, ScrollSpec, col, el}; + +#[derive(Default)] +struct S { banner: bool, rows: usize, virtualized: bool, footer: bool, reports: Vec<bool> } + +fn view(s: &S, _: &mut Cx<S>) -> El { + let mut stack = col().key("stack").w_full().growth(GrowthSpec::default()); + if s.virtualized { stack = stack.virtualize(60.0); } + for i in 0..s.rows { + stack = stack.child(el().key(format!("r{i}")).w_full().h(40.0 + (i % 3) as f32 * 10.0)); + } + col().w_full().h_full() + .child(el().key("banner").w_full().h(if s.banner { 55.0 } else { 0.0 })) + .child(col().key("scroll").w_full().grow(1.0).shrink().scroll(ScrollSpec { stick_bottom: true }) + .on_at_bottom(|s: &mut S, at| s.reports.push(at)) + .child(stack)) + .child(el().key("footer").w_full().h(if s.footer { 55.0 } else { 0.0 })) + .child(el().key("jump").absolute(0.0, 0.0).size(10.0, 10.0).on_press_tx(|_: &mut S, tx| tx.scroll_to_bottom("scroll"))) +} + +fn find(rt: &Runtime<S>, key: &str) -> ElementInfo { + rt.elements().into_iter().find(|e| e.key.as_deref() == Some(key)).unwrap_or_else(|| panic!("{key}")) +} + +/// Last row's bottom minus the viewport's drawn bottom. +fn gap(rt: &Runtime<S>) -> f32 { + let (last, view) = (find(rt, &format!("r{}", rt.state.rows - 1)), find(rt, "scroll")); + (view.rect[1] + view.rect[3]) - (last.rect[1] + last.rect[3]) +} + +type Case = (&'static str, S, fn(&mut S)); + +fn run(state: S, toggle: fn(&mut S)) -> (Vec<f32>, Runtime<S>) { + let mut rt = Runtime::new(state, view, (300.0, 400.0), Env::new(true, 2.0)); + rt.frame(0.0); + for _ in 0..10 { rt.frame(1.0 / 120.0); } + assert!(gap(&rt).abs() < 0.05, "starts at the bottom: {}", gap(&rt)); + toggle(&mut rt.state); + rt.invalidate(); + let mut gaps = Vec::new(); + for _ in 0..120 { + rt.frame(1.0 / 120.0); + gaps.push(gap(&rt)); + } + (gaps, rt) +} + +#[test] +fn stays_on_the_bottom_while_the_viewport_resizes() { + let cases: [Case; 4] = [ + ("banner opens", S { rows: 40, ..S::default() }, |s| s.banner = true), + ("banner closes", S { rows: 40, banner: true, ..S::default() }, |s| s.banner = false), + ("footer opens", S { rows: 40, ..S::default() }, |s| s.footer = true), + ("virtual", S { rows: 400, virtualized: true, ..S::default() }, |s| s.banner = true), + ]; + for (what, state, toggle) in cases { + let (gaps, rt) = run(state, toggle); + let worst = gaps.iter().fold(0.0f32, |m, g| m.max(g.abs())); + assert!(worst < 0.6, "{what}: the last row left the bottom by {worst}: {gaps:?}"); + assert_eq!(rt.state.reports, [true], "{what}: stays at the bottom throughout"); + } +} + +#[test] +fn a_glide_lands_through_a_resize_and_then_holds_the_bottom() { + let mut rt = Runtime::new(S { rows: 40, ..S::default() }, view, (300.0, 400.0), Env::new(true, 2.0)); + rt.frame(0.0); + for _ in 0..3 { + rt.wheel(100.0, 200.0, 300.0); + rt.frame(1.0 / 120.0); + } + for _ in 0..30 { rt.frame(1.0 / 120.0); } + assert!(gap(&rt) < -300.0, "reading up: {}", gap(&rt)); + rt.pointer_down(5.0, 5.0); + rt.pointer_up(5.0, 5.0); + for _ in 0..4 { rt.frame(1.0 / 120.0); } + // The banner opens mid-glide; the glide still lands on the bottom. + rt.state.banner = true; + rt.invalidate(); + for _ in 0..240 { rt.frame(1.0 / 120.0); } + assert!(gap(&rt).abs() < 0.05, "landed: {}", gap(&rt)); + assert_eq!(rt.state.reports, [true, false, true]); + // Stuck again, so closing it holds the bottom every frame. + rt.state.banner = false; + rt.invalidate(); + for n in 0..120 { + rt.frame(1.0 / 120.0); + assert!(gap(&rt).abs() < 0.6, "frame {n}: {}", gap(&rt)); + } + // A wheel away unsticks: the viewport then resizes from its top like any other. + rt.wheel(100.0, 200.0, 100.0); + for _ in 0..30 { rt.frame(1.0 / 120.0); } + let away = gap(&rt); + assert!(away < -50.0, "{away}"); + assert_eq!(rt.state.reports, [true, false, true, false]); +} diff --git a/app/vendor/rune/crates/rune/tests/integration/sticky.rs b/app/vendor/rune/crates/rune/tests/integration/sticky.rs new file mode 100644 index 0000000..ace6f43 --- /dev/null +++ b/app/vendor/rune/crates/rune/tests/integration/sticky.rs @@ -0,0 +1,780 @@ +//! Headless tests for `El::sticky_top`, `El::sticky_bottom`, `El::stuck_shadow`, +//! `ElementInfo::stuck`, and `Tx::keep_on_screen`. +use rune::runtime::ElementInfo; +use rune::{Align, Color, Cx, El, Env, GrowthSpec, Runtime, ScrollSpec, Shadow, Side, Tx, col, el, oklch, text}; + +fn find<S: 'static>(rt: &Runtime<S>, key: &str) -> ElementInfo { + rt.elements() + .into_iter() + .find(|e| e.key.as_deref() == Some(key)) + .unwrap_or_else(|| panic!("missing element {key:?}")) +} + +#[derive(Default)] +struct Basic { + drawn_y: f32, + hits: Vec<&'static str>, +} + +fn basic_view(_: &Basic, _: &mut Cx<Basic>) -> El { + let shadow = Shadow { y: 1.0, color: Color::BLACK.alpha(0.75), ..Default::default() }; + col() + .w_full() + .h_full() + .child( + col() + .key("scroll") + .w(300.0) + .h(200.0) + .scroll(ScrollSpec { stick_bottom: false }) + .child( + col() + .w_full() + .child(el().key("lead").w_full().h(12.0)) + // Section 0: 12..272, bottom padding 10 so content box ends at 262. + .child( + col() + .key("sec-0") + .w_full() + .pb(10.0) + .child( + col() + .key("hdr-0") + .w_full() + .h(30.0) + .fill(oklch(0.24, 0.02, 260.0)) + .sticky_top(8.0) + .stuck_shadow(shadow) + .on_drawn_layout(|s: &mut Basic, r| s.drawn_y = r[1]) + .on_press(|s: &mut Basic| s.hits.push("hdr-0")) + .child( + el().key("hdr-0-btn") + .w(60.0) + .h(20.0) + .on_press(|s: &mut Basic| s.hits.push("hdr-0-btn")), + ), + ) + .child( + el().key("row-0") + .w_full() + .h(220.0) + .on_press(|s: &mut Basic| s.hits.push("row-0")), + ), + ) + // Section 1: 260..554, with both a top sticky header and a bottom sticky footer. + .child( + col() + .key("sec-1") + .w_full() + .child( + el().key("hdr-1") + .w_full() + .h(30.0) + .fill(oklch(0.28, 0.02, 260.0)) + .sticky_top(8.0), + ) + .child(el().key("row-1").w_full().h(240.0)) + .child( + el().key("ftr-1") + .w_full() + .h(24.0) + .fill(oklch(0.28, 0.02, 260.0)) + .sticky_bottom(6.0), + ), + ) + .child(el().key("tail").w_full().h(300.0)), + ), + ) +} + +#[test] +fn sticky_top_and_bottom_hold_push_out_hit_above_siblings_and_report_drawn_layout() { + let mut rt = Runtime::new(Basic::default(), basic_view, (300.0, 200.0), Env::new(true, 1.0)); + rt.frame(0.0); + + // At offset 0, hdr-0 sits at y=12 (below its 8pt inset), so it is not stuck yet. + // Run one more frame so the initial `on_drawn_layout` action dispatches. + rt.frame(1.0 / 120.0); + let h0 = find(&rt, "hdr-0"); + assert_eq!(h0.rect, [0.0, 12.0, 300.0, 30.0]); + assert_eq!(h0.stuck, 0.0); + assert_eq!(rt.state.drawn_y, 12.0); + let base_instances = rt.instances.len(); + + // Fractional scroll at 120 Hz: offset = 16.5, natural top = -4.5 < 8.0, so it sticks at 8.0 + // with shift = 12.5 in the same frame as wheel(). + rt.wheel(100.0, 100.0, -16.5); + rt.frame(1.0 / 120.0); + let h0 = find(&rt, "hdr-0"); + assert!((h0.rect[1] - 8.0).abs() < 1e-3, "held at inset 8: {:?}", h0.rect); + assert!((h0.stuck - 12.5).abs() < 1e-3, "stuck shift is 12.5: {}", h0.stuck); + assert!(rt.instances.len() > base_instances, "stuck_shadow draws while stuck"); + rt.frame(1.0 / 120.0); + assert!((rt.state.drawn_y - 8.0).abs() < 1e-3, "on_drawn_layout sees the stuck y"); + + // Scroll to offset = 92: row-0 now spans -50..170, directly under hdr-0 at y=8..38. + rt.wheel(100.0, 100.0, -75.5); + rt.frame(1.0 / 120.0); + let h0 = find(&rt, "hdr-0"); + let btn = find(&rt, "hdr-0-btn"); + assert_eq!(h0.rect[1], 8.0); + assert_eq!(h0.stuck, 88.0); + assert_eq!(btn.rect[1], 8.0, "children inside the header move with it"); + + // Clicking the button and the header body over row-0 hits the header subtree, not row-0. + rt.pointer_down(20.0, 15.0); + rt.pointer_up(20.0, 15.0); + rt.frame(1.0 / 120.0); + assert_eq!(rt.state.hits, vec!["hdr-0-btn"]); + + rt.pointer_down(200.0, 20.0); + rt.pointer_up(200.0, 20.0); + rt.frame(1.0 / 120.0); + assert_eq!(rt.state.hits, vec!["hdr-0-btn", "hdr-0"]); + + // sec-0's content box ends at 262 (272 - 10pt bottom padding). Once offset > 262 - 8 - 30 = 224, + // sec-0's bottom edge pushes hdr-0 up. At offset = 242, hdr-0's bottom is at 262 - 242 = 20, so y = -10. + rt.wheel(100.0, 100.0, -150.0); + rt.frame(1.0 / 120.0); + let h0 = find(&rt, "hdr-0"); + assert_eq!(h0.rect[1], -10.0, "pushed up by sec-0's padded bottom edge"); + assert_eq!(h0.stuck, 220.0); + + // At offset = 242, sec-1 spans 30..324 (height 294). Its footer (24pt tall, sticky_bottom(6.0)) + // naturally sits at 300..324, which is below 200 - 6 = 194, so it sticks at y = 170 (194 - 24). + let f1 = find(&rt, "ftr-1"); + assert_eq!(f1.rect[1], 170.0, "footer held 6pt above viewport bottom"); + assert_eq!(f1.stuck, -130.0, "upward sticky shift is negative"); +} + +#[test] +fn nested_scroll_viewports_stick_each_header_to_its_nearest_viewport() { + fn view(_: &(), _: &mut Cx<()>) -> El { + col().w_full().h_full().child( + col() + .key("outer") + .w(300.0) + .h(240.0) + .scroll(ScrollSpec { stick_bottom: false }) + .child( + col() + .w_full() + .child( + col() + .key("outer-sec") + .w_full() + .child(el().key("outer-hdr").w_full().h(28.0).sticky_top(0.0)) + .child(el().w_full().h(60.0)) + .child( + col() + .key("inner") + .w_full() + .h(120.0) + .scroll(ScrollSpec { stick_bottom: false }) + .child( + col() + .w_full() + .child( + col() + .w_full() + .child(el().key("inner-hdr").w_full().h(20.0).sticky_top(4.0)) + .child(el().w_full().h(260.0)), + ), + ), + ) + .child(el().w_full().h(300.0)), + ), + ), + ) + } + + let mut rt = Runtime::new((), view, (300.0, 240.0), Env::new(true, 1.0)); + rt.frame(0.0); + assert_eq!(find(&rt, "outer-hdr").rect[1], 0.0); + assert_eq!(find(&rt, "inner").rect[1], 88.0); + assert_eq!(find(&rt, "inner-hdr").rect[1], 92.0); + + // Scroll inner viewport (at y=120): inner-hdr sticks at inner.top + 4 = 92. + rt.wheel(150.0, 120.0, -50.0); + rt.frame(1.0 / 120.0); + assert_eq!(find(&rt, "inner-hdr").rect[1], 92.0); + assert_eq!(find(&rt, "inner-hdr").stuck, 54.0); + assert_eq!(find(&rt, "outer-hdr").stuck, 0.0); + + // Scroll outer viewport (at y=10, outside inner): outer-hdr sticks at 0, inner moves up by 30, + // and inner-hdr stays stuck to inner's new top + 4 = 62. + rt.wheel(150.0, 10.0, -30.0); + rt.frame(1.0 / 120.0); + assert_eq!(find(&rt, "outer-hdr").rect[1], 0.0); + assert_eq!(find(&rt, "outer-hdr").stuck, 30.0); + assert_eq!(find(&rt, "inner").rect[1], 58.0); + assert_eq!(find(&rt, "inner-hdr").rect[1], 62.0); +} + +#[derive(Default)] +struct CollapseApp { + collapsed: [bool; 8], +} + +fn virtual_sections(_: &CollapseApp, _: &mut Cx<CollapseApp>) -> El { + col().w_full().h_full().child( + col() + .key("scroll") + .w(320.0) + .h(200.0) + .scroll(ScrollSpec { stick_bottom: false }) + .child( + col() + .key("list") + .w_full() + .growth(GrowthSpec::default()) + .virtual_rows( + 8, + 160.0, + |_: &CollapseApp, i| format!("sec-{i}").into(), + |s: &CollapseApp, i| { + let collapsed = s.collapsed[i]; + let hdr_key = format!("hdr-{i}"); + let keep_key = hdr_key.clone(); + let mut sec = col().w_full().child( + el().key(hdr_key) + .w_full() + .h(32.0) + .fill(oklch(0.25, 0.02, 260.0)) + .sticky_top(0.0) + .on_press_tx(move |s: &mut CollapseApp, tx: &mut Tx| { + s.collapsed[i] = !s.collapsed[i]; + tx.keep_on_screen(&keep_key); + }), + ); + if !collapsed { + sec = sec.child(el().key(format!("body-{i}")).w_full().h(600.0)); + } + sec + }, + ), + ), + ) +} + +#[test] +fn virtual_rows_keep_stuck_header_on_screen_across_collapse_and_expand() { + let mut rt = Runtime::new(CollapseApp::default(), virtual_sections, (320.0, 200.0), Env::new(true, 1.0)); + rt.frame(0.0); + + // Scroll deep into sec-1 (starts at 632, ends at 1264): offset = 1050 puts us 418pt into sec-1. + rt.wheel(160.0, 100.0, -1050.0); + for _ in 0..4 { + rt.frame(1.0 / 120.0); + } + let h1 = find(&rt, "hdr-1"); + assert_eq!(h1.rect[1], 0.0, "hdr-1 is stuck at the top of the viewport"); + assert!((h1.stuck - 418.0).abs() < 0.5, "hdr-1 stuck shift: {}", h1.stuck); + + // Click hdr-1 (at y=16) to collapse sec-1 from 632pt tall to 32pt tall. + // Without keep_on_screen, sec-1 (632..664) would end 386pt above offset 1050 and be culled. + rt.pointer_down(100.0, 16.0); + rt.pointer_up(100.0, 16.0); + for step in 0..10 { + rt.frame(1.0 / 120.0); + let h1 = find(&rt, "hdr-1"); + assert!((h1.rect[1] - 0.0).abs() < 0.5, "frame {step}: hdr-1 stayed at y=0 after collapse: {:?}", h1.rect); + } + for _ in 0..120 { rt.frame(1.0 / 120.0); } + assert_eq!(find(&rt, "hdr-2").rect[1], 32.0, "sec-2 sits immediately below collapsed sec-1"); + + // Click hdr-1 again to expand sec-1: hdr-1 stays at y=0 while its body opens below it. + rt.pointer_down(100.0, 16.0); + rt.pointer_up(100.0, 16.0); + for step in 0..10 { + rt.frame(1.0 / 120.0); + let h1 = find(&rt, "hdr-1"); + assert!((h1.rect[1] - 0.0).abs() < 0.5, "frame {step}: hdr-1 stayed at y=0 after expand: {:?}", h1.rect); + } +} + +#[derive(Default)] +struct Timeline { + collapsed: bool, + extra_rows: usize, + menu_open: bool, +} + +fn timeline_view(s: &Timeline, _: &mut Cx<Timeline>) -> El { + let mut group = col().key("group").w_full().child( + el().key("group-hdr") + .w_full() + .h(30.0) + .fill(oklch(0.24, 0.02, 260.0)) + .sticky_top(0.0) + .on_press_tx(|s: &mut Timeline, tx: &mut Tx| { + s.collapsed = !s.collapsed; + tx.keep_on_screen("group-hdr"); + }), + ); + if !s.collapsed { + group = group.child(el().key("group-body").w_full().h(400.0)); + } + let mut stack = col() + .key("stack") + .w_full() + .growth(GrowthSpec::default()) + .child(el().key("row-a").w_full().h(200.0)) + .child(group) + .child(el().key("row-b").w_full().h(120.0)); + for i in 0..s.extra_rows { + stack = stack.child(text(format!("line {i}")).key(format!("extra-{i}")).w_full().h(50.0)); + } + let mut root = col().w_full().h_full().child( + col() + .key("scroll") + .w(300.0) + .h(200.0) + .scroll(ScrollSpec { stick_bottom: true }) + .child(stack), + ); + if s.menu_open { + root = root.child( + el().key("popover") + .w(100.0) + .h(40.0) + .anchored("group-hdr", Side::Bottom, Align::Start, 4.0), + ); + } + root +} + +#[test] +fn stick_bottom_growth_reveal_and_anchored_overlay_work_with_sticky_headers() { + let init = Timeline { collapsed: false, extra_rows: 2, menu_open: false }; + let mut rt = Runtime::new(init, timeline_view, (300.0, 200.0), Env::new(true, 1.0)); + rt.frame(0.0); + + // Opens pinned at the bottom (total height = 200 + 430 + 120 + 100 = 850, viewport = 200 -> offset = 650). + // Scroll back into `group` (200..630) at offset = 450 so `group-hdr` is stuck at y=0, and open an + // anchored overlay on `group-hdr`. + rt.wheel(150.0, 100.0, 200.0); + rt.update(|s, _| s.menu_open = true); + rt.frame(1.0 / 120.0); + assert_eq!(find(&rt, "group-hdr").rect[1], 0.0); + assert_eq!(find(&rt, "popover").rect[1], 34.0, "anchored overlay sits 4pt below the stuck header"); + + // Scrolling further while the overlay is open keeps the overlay attached to the stuck header, + // and once the header is pushed up (at offset = 610, group ends at 630 -> hdr at -10), the + // overlay moves with it (to -10 + 30 + 4 = 24). + rt.wheel(150.0, 100.0, -160.0); + rt.frame(1.0 / 120.0); + assert_eq!(find(&rt, "group-hdr").rect[1], -10.0); + assert_eq!(find(&rt, "popover").rect[1], 24.0, "anchored overlay tracks the header as it pushes out"); + + // At offset = 400 (with extra_rows cleared), `group-hdr` is stuck at y=0..30. Collapse `group` + // (height 430 -> 30): total content becomes 200 + 30 + 120 = 350, max offset = 150. + // `keep_on_screen("group-hdr")` wants offset 200 - 0 = 200, which clamps to max offset 150 + // and re-pins `stick_bottom`! + rt.update(|s, tx| { + s.menu_open = false; + s.extra_rows = 0; + tx.scroll_to_y("scroll", 400.0); + }); + for _ in 0..40 { + rt.frame(1.0 / 60.0); + } + assert_eq!(find(&rt, "group-hdr").rect[1], 0.0); + rt.pointer_down(100.0, 15.0); + rt.pointer_up(100.0, 15.0); + rt.frame(1.0 / 120.0); + + // The collapse now keeps its spring; let the end clamp land before appending. + for _ in 0..120 { rt.frame(1.0 / 120.0); } + // Because collapsing brought the scroll offset to `max` (10.0), `stick_bottom` is re-pinned: + // appending new growth rows keeps the bottom in view! + rt.update(|s, _| s.extra_rows = 2); + for _ in 0..60 { + rt.frame(1.0 / 60.0); + } + let last = find(&rt, "extra-1"); + assert!((last.rect[1] + last.rect[3] - 200.0).abs() < 1.0, "stick_bottom followed new growth rows: {:?}", last.rect); +} + +#[test] +fn scroll_into_view_lands_row_clear_of_stuck_header() { + fn view(_: &(), _: &mut Cx<()>) -> El { + col().w_full().h_full().child( + col() + .key("scroll") + .w(300.0) + .h(200.0) + .scroll(ScrollSpec { stick_bottom: false }) + .child( + col() + .w_full() + .child( + col() + .w_full() + .child(el().key("hdr").w_full().h(40.0).sticky_top(0.0)) + .child(el().key("r0").w_full().h(80.0)) + .child(el().key("r1").w_full().h(80.0)) + .child(el().key("r2").w_full().h(80.0)) + .child(el().key("r3").w_full().h(80.0)), + ), + ), + ) + } + + let mut rt = Runtime::new((), view, (300.0, 200.0), Env::new(true, 1.0)); + rt.frame(0.0); + // Scroll down to offset = 150: `hdr` is stuck at y=0..40, and `r1` (120..200) sits at y=-30..50 + // (its top is hidden behind `hdr` and above the viewport). + rt.update(|_, tx| tx.scroll_to_y("scroll", 150.0)); + rt.frame(1.0 / 120.0); + assert_eq!(find(&rt, "hdr").rect[1], 0.0); + assert_eq!(find(&rt, "r1").rect[1], -30.0); + + // Revealing `r1` scrolls far enough that `r1`'s top clears the 40pt stuck `hdr` (landing at y=40). + rt.update(|_, tx| tx.scroll_into_view("r1")); + rt.frame(1.0 / 120.0); + assert_eq!(find(&rt, "hdr").rect[1], 0.0); + assert_eq!(find(&rt, "r1").rect[1], 40.0, "r1 lands clear of the 40pt stuck header"); +} + +#[test] +fn keep_follows_drawn_motion_without_snapping_other_rows_and_scroll_cancels_it() { + fn view(s: &bool, _: &mut Cx<bool>) -> El { + col().key("scroll").size(300.0, 200.0).scroll(ScrollSpec { stick_bottom: false }) + .child(col().key("stack").w_full().growth(GrowthSpec::default()) + .child(el().key("before").w_full().h(if *s { 120.0 } else { 240.0 })) + .child(el().key("kept").w_full().h(30.0)) + .child(el().key("other").w_full().h(if *s { 220.0 } else { 120.0 })) + .child(el().w_full().h(600.0))) + } + let mut rt = Runtime::new(false, view, (300.0, 200.0), Env::default()); + rt.frame(0.0); + rt.update(|_, tx| tx.scroll_to_instant("scroll", 0.0, 220.0)); + rt.frame(0.0); + let y = find(&rt, "kept").rect[1]; + rt.update(|s, tx| { *s = true; tx.keep_on_screen("stack/kept"); }); + rt.frame(1.0 / 120.0); + let h = find(&rt, "other").rect[3]; + assert!(h > 120.0 && h < 220.0, "unrelated growth keeps its spring: {h}"); + for _ in 0..12 { + rt.frame(1.0 / 120.0); + assert!((find(&rt, "kept").rect[1] - y).abs() < 0.05); + } + rt.wheel(100.0, 100.0, -20.0); + rt.frame(1.0 / 120.0); + assert!(find(&rt, "kept").rect[1] < y - 19.0, "wheel wins over the keep"); + rt.update(|s, tx| { + *s = false; + tx.keep_on_screen("stack/kept"); + tx.scroll_to_instant("scroll", 0.0, 50.0); + }); + rt.frame(1.0 / 120.0); + assert_eq!(find(&rt, "before").rect[1], -50.0, "explicit scroll in the same handler wins"); +} + +#[test] +fn live_viewport_and_ancestor_transforms_keep_header_and_overlay_together() { + struct S { offset: rune::Live<[f32; 2]>, scale: rune::Live<f32> } + fn view(s: &S, _: &mut Cx<S>) -> El { + col().w_full().h_full() + .child(col().key("ancestor").size(300.0, 200.0).live_offset(&s.offset).live_scale(&s.scale) + .child(col().key("scroll").size(300.0, 200.0).live_offset(&s.offset).live_scale(&s.scale).scroll(ScrollSpec { stick_bottom: false }) + .child(col().w_full() + .child(el().key("hdr").w_full().h(30.0).sticky_top(8.0)) + .child(el().w_full().h(600.0))))) + .child(el().key("tip").size(60.0, 20.0).anchored("hdr", Side::Bottom, Align::Start, 4.0)) + } + let mut rt = Runtime::new(S { offset: rune::Live::new([0.0, 0.0]), scale: rune::Live::new(1.0) }, view, (500.0, 400.0), Env::default()); + rt.frame(0.0); + rt.wheel(100.0, 100.0, -100.0); + rt.frame(0.0); + rt.state.offset.set([30.0, 40.0]); + rt.state.scale.set(0.8); + rt.frame(1.0 / 120.0); + let (h, v, tip) = (find(&rt, "hdr"), find(&rt, "scroll"), find(&rt, "tip")); + assert!((h.rect[1] - v.rect[1] - 8.0 * 0.8 * 0.8).abs() < 0.05, "{h:?} {v:?}"); + assert!((tip.rect[1] - h.rect[1] - h.rect[3] - 4.0).abs() < 0.05, "overlay tracks drawn header: {:?} {:?}", tip.rect, h.rect); +} + +#[test] +fn inert_sticky_passes_input_and_focus_through_and_tooltips_follow_drawn_rect() { + fn view(_: &(), _: &mut Cx<()>) -> El { + col().key("scroll").size(300.0, 200.0).scroll(ScrollSpec { stick_bottom: false }) + .child(col().w_full() + .child(el().key("hdr").w_full().h(30.0).sticky_top(0.0).help("header").focusable(true)) + .child(el().key("inert").absolute(0.0, 0.0).size(300.0, 30.0).sticky_top(0.0).inert().focusable(true)) + .child(el().w_full().h(600.0))) + } + let mut rt = Runtime::new((), view, (300.0, 200.0), Env::default()); + rt.frame(0.0); + rt.wheel(100.0, 100.0, -100.0); + rt.frame(0.0); + rt.set_full_keyboard_access(true); + rt.key(rune::KeyEvent { key: rune::Key::Tab, mods: rune::Mods::default() }); + rt.frame(0.0); + assert!(find(&rt, "hdr").focused); + assert!(!find(&rt, "inert").focused); + rt.pointer_move(100.0, 15.0); + rt.frame(0.0); + rt.frame(0.6); + assert_eq!(rt.help_tooltip().map(|t| t.0), Some("header")); + let tip = rt.help_tooltip().unwrap().1; + assert!((tip[1] - find(&rt, "hdr").rect[3] - 6.0).abs() < 0.05, "tooltip follows stuck header: {tip:?}"); +} + +#[test] +fn sticky_without_vertical_viewport_is_a_no_op() { + fn view(_: &(), _: &mut Cx<()>) -> El { + col().size(300.0, 200.0).scroll_x() + .child(col().w(600.0) + .child(el().key("top").size(50.0, 30.0).sticky_top(20.0)) + .child(el().key("bottom").size(50.0, 30.0).sticky_bottom(20.0))) + } + let mut rt = Runtime::new((), view, (300.0, 200.0), Env::default()); + rt.frame(0.0); + rt.wheel_xy(100.0, 100.0, -50.0, 0.0); + rt.frame(0.0); + assert_eq!(find(&rt, "top").stuck, 0.0); + assert_eq!(find(&rt, "bottom").stuck, 0.0); +} + +#[derive(Clone, Copy, Debug)] +struct RevealGrowth { + expanded: bool, + stick_bottom: bool, + virtualized: bool, + keep: Option<&'static str>, + instant: bool, +} + +fn reveal_growth_view(s: &RevealGrowth, _: &mut Cx<RevealGrowth>) -> El { + let build_row = |s: &RevealGrowth, i: usize| -> El { + let key = format!("r{i}"); + let h = if i == 3 { + if s.expanded { 130.0 } else { 37.0 } + } else if i < 3 { + 80.0 + } else { + 35.0 + }; + let mut row = el().key(key).w_full().h(h); + if i == 3 { + row = row.on_press_tx(|s: &mut RevealGrowth, tx: &mut Tx| { + s.expanded = true; + if s.instant { + tx.instant(); + } + if let Some(target) = s.keep { + tx.keep_on_screen(target); + } else { + tx.scroll_into_view("r3"); + } + }); + } + row + }; + let mut stack = col().key("stack").w_full().growth(GrowthSpec::default()); + if s.virtualized { + stack = stack.virtual_rows( + 6, + 60.0, + |_: &RevealGrowth, i| format!("r{i}").into(), + move |s: &RevealGrowth, i| build_row(s, i), + ); + } else { + for i in 0..6 { + stack = stack.child(build_row(s, i)); + } + } + col().w_full().h_full().child( + col() + .key("scroll") + .w(300.0) + .h(200.0) + .scroll(ScrollSpec { stick_bottom: s.stick_bottom }) + .child(stack), + ) +} + +fn run_reveal_growth(init: RevealGrowth) { + let mut rt = Runtime::new(init, reveal_growth_view, (300.0, 200.0), Env::new(true, 1.0)); + rt.frame(0.0); + if !init.stick_bottom { + rt.update(|_, tx| tx.scroll_to_instant("scroll", 0.0, 120.0)); + rt.frame(0.0); + } + let kept_was = init.keep.map(|k| find(&rt, k).rect[1]); + let snapshot = |rt: &Runtime<RevealGrowth>| -> Vec<(String, [f32; 4])> { + (0..6) + .filter_map(|i| { + let key = format!("r{i}"); + rt.elements().into_iter().find(|e| e.key.as_deref() == Some(&key)).map(|e| (key, e.rect)) + }) + .collect() + }; + let mut prev = snapshot(&rt); + let r3 = find(&rt, "r3").rect; + let press_y = r3[1] + r3[3] * 0.5; + rt.pointer_down(150.0, press_y); + rt.pointer_up(150.0, press_y); + + if init.instant { + rt.frame(1.0 / 120.0); + let r3 = find(&rt, "r3").rect; + assert!((r3[3] - 130.0).abs() < 0.05, "instant snaps growth in one frame: {init:?} {r3:?}"); + if let (Some(k), Some(was)) = (init.keep, kept_was) { + assert!((find(&rt, k).rect[1] - was).abs() < 0.05, "instant keep lands in one frame: {init:?}"); + } else { + assert!(r3[1] >= -0.05 && (r3[1] + r3[3] - 200.0).abs() < 0.05, "instant reveal lands in one frame: {init:?} {r3:?}"); + } + // An instant scroll holds hover for two frames at 60 Hz, as dev's countdown did, without + // drawing anything: the hold asks for one frame when it ends. + assert!(!rt.animating, "instant leaves nothing animating: {init:?}"); + return; + } + + let mut max_move = 0.0f32; + let mut growth_frames = 0usize; + for step in 1..=120 { + rt.frame(1.0 / 120.0); + let cur = snapshot(&rt); + for (key, rect) in &cur { + if let Some((_, old)) = prev.iter().find(|(k, _)| k == key) { + let dy_top = (rect[1] - old[1]).abs(); + let dy_bot = ((rect[1] + rect[3]) - (old[1] + old[3])).abs(); + let dh = (rect[3] - old[3]).abs(); + let m = dy_top.max(dy_bot).max(dh); + max_move = max_move.max(m); + assert!( + m <= 12.0, + "frame {step} ({:?}): {key} moved {m:.2}pt in one frame ({old:?} -> {rect:?})", + (init.stick_bottom, init.virtualized, init.keep) + ); + } + } + if let (Some(k), Some(was)) = (init.keep, kept_was) { + let y = find(&rt, k).rect[1]; + assert!( + (y - was).abs() < 0.5, + "frame {step} ({:?}): kept {k} moved from {was:.2} to {y:.2}", + (init.stick_bottom, init.virtualized, init.keep) + ); + } + if (find(&rt, "r3").rect[3] - 130.0).abs() >= 0.5 { + growth_frames = step; + } + prev = cur; + } + let duration = growth_frames as f32 / 120.0; + assert!( + (0.20..=0.50).contains(&duration), + "growth took {duration:.3}s ({growth_frames} frames, max step {max_move:.2}pt) for {:?}", + (init.stick_bottom, init.virtualized, init.keep) + ); + let r3 = find(&rt, "r3").rect; + assert!((r3[3] - 130.0).abs() < 0.05, "r3 settled at 130pt: {r3:?}"); + if let (Some(k), Some(was)) = (init.keep, kept_was) { + assert!((find(&rt, k).rect[1] - was).abs() < 0.5, "kept {k} stayed at {was}: {:?}", find(&rt, k).rect); + } else { + assert!( + r3[1] >= -0.05 && (r3[1] + r3[3] - 200.0).abs() < 0.5, + "final scroll reveals grown r3: {r3:?}" + ); + } +} + +#[test] +fn scroll_into_view_keeps_growth_springing_and_snaps_when_instant() { + for stick_bottom in [false, true] { + for virtualized in [false, true] { + for instant in [false, true] { + run_reveal_growth(RevealGrowth { expanded: false, stick_bottom, virtualized, keep: None, instant }); + } + } + } +} + +#[test] +fn keep_on_screen_keeps_growth_springing_and_snaps_when_instant() { + for stick_bottom in [false, true] { + for virtualized in [false, true] { + for keep in [Some("r4"), Some("r3")] { + for instant in [false, true] { + run_reveal_growth(RevealGrowth { expanded: false, stick_bottom, virtualized, keep, instant }); + } + } + } + } +} + +#[derive(Clone, Copy)] +struct RevealThenInsert { + rows: usize, + expanded: bool, + stick_bottom: bool, +} + +fn reveal_then_insert_view(s: &RevealThenInsert, _: &mut Cx<RevealThenInsert>) -> El { + let mut stack = col().key("stack").w_full().growth(GrowthSpec::default()).virtualize(40.0); + if s.stick_bottom { + stack = stack.child(el().key("lead").w_full().h(320.0)); + } + for i in 0..s.rows { + let h = if i == 1 && s.expanded { 120.0 } else { 40.0 }; + stack = stack.child(el().key(format!("r{i}")).w_full().h(h).streaming(s.stick_bottom && i + 1 == s.rows)); + } + col().w_full().h_full().child( + col().key("scroll").w(300.0).h(400.0).scroll(ScrollSpec { stick_bottom: s.stick_bottom }).child(stack), + ) +} + +#[test] +fn rows_entering_while_a_reveal_follows_its_row_land_at_full_height() { + // A reveal outlives its commit while the viewport's springs run. A later commit's new rows + // land at full height, as they do in a reader's virtual list with no reveal, while the row + // the reveal follows keeps growing. + let mut rt = Runtime::new(RevealThenInsert { rows: 3, expanded: false, stick_bottom: false }, reveal_then_insert_view, (300.0, 400.0), Env::new(true, 1.0)); + rt.frame(0.0); + rt.update(|s, tx| { + s.expanded = true; + tx.scroll_into_view("r1"); + }); + for _ in 0..6 { + rt.frame(1.0 / 120.0); + } + let growing = find(&rt, "r1").rect[3]; + assert!(growing > 40.5 && growing < 119.5, "r1 grows: {growing}"); + rt.update(|s, _| s.rows = 4); + rt.frame(1.0 / 120.0); + let r1 = find(&rt, "r1").rect[3]; + assert!(r1 > growing && r1 < 119.5, "r1 keeps growing: {growing} -> {r1}"); + let r3 = find(&rt, "r3").rect; + assert!((r3[3] - 40.0).abs() < 0.05, "the new row lands at full height: {r3:?}"); + assert!((r3[1] - (80.0 + r1)).abs() < 0.05, "below the growing row: {r3:?}"); + + // A `stick_bottom` timeline whose reveal is at the tail stays pinned across a later commit: + // a new row appended while an earlier row still grows springs from zero and carries the end. + let mut rt = Runtime::new(RevealThenInsert { rows: 3, expanded: false, stick_bottom: true }, reveal_then_insert_view, (300.0, 400.0), Env::new(true, 1.0)); + rt.frame(0.0); + rt.update(|s, tx| { + s.expanded = true; + tx.scroll_into_view("r2"); + }); + for _ in 0..6 { + rt.frame(1.0 / 120.0); + } + let growing = find(&rt, "r1").rect[3]; + assert!(growing > 40.5 && growing < 119.5, "r1 grows: {growing}"); + rt.update(|s, _| s.rows = 4); + rt.frame(1.0 / 120.0); + let r1 = find(&rt, "r1").rect[3]; + let r3 = find(&rt, "r3").rect; + assert!(r1 > growing && r1 < 119.5, "r1 keeps growing: {growing} -> {r1}"); + assert!(r3[3] > 0.1 && r3[3] < 20.0, "new tail row grows from zero on its spring: {r3:?}"); + assert!((r3[1] + r3[3] - 400.0).abs() < 0.5, "the timeline follows the new tail row: {r3:?}"); + for _ in 0..120 { + rt.frame(1.0 / 120.0); + } + let r3 = find(&rt, "r3").rect; + assert!((r3[3] - 40.0).abs() < 0.05 && (r3[1] + r3[3] - 400.0).abs() < 0.5, "settled at the bottom: {r3:?}"); +} diff --git a/app/vendor/rune/crates/rune/tests/integration/sticky_paint.rs b/app/vendor/rune/crates/rune/tests/integration/sticky_paint.rs new file mode 100644 index 0000000..c0ec672 --- /dev/null +++ b/app/vendor/rune/crates/rune/tests/integration/sticky_paint.rs @@ -0,0 +1,403 @@ +//! Headless paint, occlusion, edge-fade, and memo-replay tests for sticky elements. + +use rune::render::{Gpu, OFFSCREEN_FORMAT, Offscreen, Renderer}; +use rune::runtime::ElementInfo; +use rune::{Color, Cx, El, Env, GrowthSpec, Runtime, ScrollSpec, Shadow, col, el, memo, row, text}; + +fn find<S: 'static>(rt: &Runtime<S>, key: &str) -> ElementInfo { + rt.elements() + .into_iter() + .find(|e| e.key.as_deref() == Some(key)) + .unwrap_or_else(|| panic!("missing element {key:?}")) +} + +fn pixels<S: 'static>(gpu: &Gpu, renderer: &mut Renderer, rt: &mut Runtime<S>, size: (u32, u32)) -> Vec<u8> { + let target = Offscreen::new(&gpu.device, size.0, size.1); + renderer.prepare(&gpu.device, &gpu.queue, &mut rt.text.atlas, &rt.instances, size); + let mut encoder = gpu.device.create_command_encoder(&Default::default()); + renderer.draw(&mut encoder, &target.view, [0.0; 4]); + target.copy(&mut encoder); + gpu.queue.submit([encoder.finish()]); + target.read(&gpu.device) +} + +#[derive(Clone, Copy)] +struct OccludeState { + memoized: bool, + open: bool, +} + +fn occlude_view(s: &OccludeState, _: &mut Cx<OccludeState>) -> El { + let build_group = |open: bool| { + let mut head = row() + .key("head") + .w_full() + .h(24.0) + .animate_layout() + .child(text("Used 3 tools").color(Color::WHITE)); + if open { + head = head + .sticky_top(0.0) + .fill(Color { r: 0.86, g: 0.2, b: 0.2, a: 1.0 }) + .stuck_shadow(Shadow { + y: 8.0, + blur: 8.0, + color: Color::BLACK, + ..Default::default() + }); + } + let mut g = col().key("group").w_full().pb(12.0).child(head); + if open { + let mut items = col().key("items").w_full().pt(4.0); + for j in 0..16 { + // Bright green rows that scroll directly under the red stuck header. + items = items.child( + el().key(format!("item-{j}")) + .w_full() + .h(22.0) + .fill(Color { r: 0.0, g: 0.94, b: 0.16, a: 1.0 }), + ); + } + g = g.child(items); + } + g + }; + let open = s.open; + let memoized = s.memoized; + let stack = col() + .key("timeline") + .w_full() + .growth(GrowthSpec::default()) + .virtual_rows( + 4, + 72.0, + |_: &OccludeState, i| format!("row-{i}").into(), + move |_: &OccludeState, i| { + if i != 1 { + return el().key(format!("spacer-{i}")).w_full().h(60.0); + } + if memoized { + memo("row-1", open, move || { + col() + .w_full() + .max_w(200.0) + .streaming(false) + .child(build_group(open)) + }) + } else { + col() + .w_full() + .max_w(200.0) + .streaming(false) + .child(build_group(open)) + } + }, + ); + col() + .w_full() + .h_full() + .fill(Color { r: 0.12, g: 0.125, b: 0.14, a: 1.0 }) + .child( + col() + .key("scroll") + .w(200.0) + .h(200.0) + .scroll(ScrollSpec { stick_bottom: false }) + .scroll_edge_fade(16.0) + .child(stack), + ) +} + +#[test] +fn sticky_header_stays_opaque_and_occludes_scrolled_rows_under_edge_fade_and_memo() { + let scale = 2.0; + let gpu = Gpu::headless(); + let mut renderer = Renderer::new(&gpu.device, OFFSCREEN_FORMAT); + let size = ((200.0 * scale) as u32, (200.0 * scale) as u32); + let mut render_pixels = |memoized: bool| -> Vec<u8> { + let mut rt = Runtime::new( + OccludeState { memoized, open: false }, + occlude_view, + (200.0, 200.0), + Env::new(true, scale), + ); + rt.frame(0.0); + // Expand the group (matching a chat timeline's collapsible tool group inside `memo`) + // and settle the growth animation. + rt.update(|s, _| s.open = true); + for _ in 0..120 { + rt.frame(1.0 / 60.0); + } + // Scroll 135 pt so `head` sticks at y=0..24 and bright green items sit at y=-3..19 + // directly behind the top edge-fade band (y=0..16). + rt.update(|_, tx| tx.scroll_to_instant("scroll", 0.0, 135.0)); + for _ in 0..120 { + rt.frame(1.0 / 60.0); + } + let head = find(&rt, "head"); + assert_eq!(head.rect, [0.0, 0.0, 200.0, 24.0]); + assert!((head.stuck - 75.0).abs() < 0.5, "stuck shift: {}", head.stuck); + + let before = pixels(&gpu, &mut renderer, &mut rt, size); + // Rebuild with an unchanged memo version, then scroll away and back. A memo hit + // must not replay paint geometry, clips or shadow state captured on an earlier frame. + rt.update(|_, tx| tx.scroll_to_instant("scroll", 0.0, 80.0)); + rt.frame(0.0); + rt.update(|_, tx| tx.scroll_to_instant("scroll", 0.0, 135.0)); + rt.frame(0.0); + let after = pixels(&gpu, &mut renderer, &mut rt, size); + assert_eq!(before, after, "unchanged memo replay changed sticky fill/shadow pixels"); + after + }; + + let plain = render_pixels(false); + let memoed = render_pixels(true); + let px = |buf: &[u8], x_pt: f32, y_pt: f32| -> [u8; 4] { + let x = (x_pt * scale) as usize; + let y = (y_pt * scale) as usize; + let idx = (y * size.0 as usize + x) * 4; + [buf[idx], buf[idx + 1], buf[idx + 2], buf[idx + 3]] + }; + + for (label, buf) in [("plain", &plain), ("memo", &memoed)] { + // Sample at x=160pt (to the right of the header's "Used 3 tools" text). + let top_row = px(buf, 160.0, 1.5); + let mid_row = px(buf, 160.0, 8.0); + let bot_row = px(buf, 160.0, 20.0); + // Problem 2: the top pixels of the stuck header (y = 1..2) must not be faded by + // `scroll_edge_fade(16.0)`; they match the unfaded bottom of the header. + assert_eq!( + top_row, bot_row, + "{label}: top of stuck header at y=1.5pt was faded ({top_row:?} vs {bot_row:?})" + ); + assert_eq!(mid_row, bot_row, "{label}: middle of stuck header at y=8pt ({mid_row:?} vs {bot_row:?})"); + // Problem 1: the bright green scrolled-under row must not bleed through the red header fill + // (whose g and b channels are equal). + assert!( + top_row[0] > 200 && top_row[1] == top_row[2] && top_row[3] == 255, + "{label}: scrolled green row bled through stuck header: {top_row:?}" + ); + // `stuck_shadow` darkens the row immediately below the 24pt header (y=26pt vs y=38pt). + let under_shadow = px(buf, 160.0, 26.0); + let clear_of_shadow = px(buf, 160.0, 38.0); + assert!( + under_shadow[1] < clear_of_shadow[1].saturating_sub(25), + "{label}: stuck_shadow did not darken below header ({under_shadow:?} vs {clear_of_shadow:?})" + ); + } + // Problem 3: wrapping the row in `memo` produces identical pixels for the stuck header and shadow. + assert_eq!(plain, memoed, "memoized sticky header pixels differ from unmemoized row"); +} + +#[test] +fn sticky_header_inside_memo_growth_row_respects_animated_row_height() { + let mut rt = Runtime::new( + OccludeState { memoized: true, open: true }, + occlude_view, + (200.0, 200.0), + Env::new(true, 1.0), + ); + rt.frame(0.0); + // Scroll to 380pt so the bottom of the expanded group pushes the header near the top. + rt.update(|_, tx| tx.scroll_to_instant("scroll", 0.0, 380.0)); + rt.frame(0.0); + // Collapse the group inside `memo`; on the first animation frame the outer `memo` wrapper row's + // growth height `g.h` is shrinking, and the nested group's sticky bound must follow it. + rt.update(|s, _| s.open = false); + rt.frame(1.0 / 120.0); + rt.update(|s, _| s.open = true); + rt.frame(1.0 / 120.0); + let wrapper = rt.elements().into_iter().find(|e| e.key.as_deref() == Some("row-1")).unwrap(); + let head = find(&rt, "head"); + assert!( + head.rect[1] + head.rect[3] <= wrapper.rect[1] + wrapper.rect[3] + 0.5, + "sticky header bottom ({:?}) exceeded animated memo row bottom ({:?})", + head.rect, + wrapper.rect + ); +} + +#[derive(Clone, Copy)] +struct ThreeColumns { rows: bool, alpha: f32 } + +fn three_columns(s: &ThreeColumns, _: &mut Cx<ThreeColumns>) -> El { + let mut root = row().size(700.0, 320.0).padding(20.0).gap(20.0).fill(Color::BLACK); + for column in 0..3 { + let state = *s; + let section = move || { + let mut section = col().key("section").w_full().child( + row().key("header").w_full().h(24.0) + .fill(Color { r: 1.0, g: 0.0, b: 0.0, a: state.alpha }) + .sticky_top(0.0).child(text("header").color(Color::WHITE)), + ); + for i in 0..20 { + section = section.child(row().h(24.0).child( + text(if state.rows { format!("row {i}") } else { String::new() }) + .color(Color { r: 0.0, g: 1.0, b: 0.0, a: 1.0 }), + )); + } + section + }; + let build = move |_: &ThreeColumns, i| match i { + 0 => el().w_full().h(10.0), + 1 if column == 0 => col().key("section-row").w_full().child(section()), + 1 => memo("section-row", 0, move || col().w_full().child(section())), + _ => el().w_full().h(400.0), + }; + let mut stack = col().w_full().pt(40.0).growth(GrowthSpec::default()); + if column != 1 { + stack = stack.virtual_rows(3, 72.0, |_: &ThreeColumns, i| format!("r{i}").into(), build); + } else { + for i in 0..3 { stack = stack.child(build(s, i)); } + } + root = root.child(col().key(format!("scroll-{column}")).size(200.0, 280.0) + .scroll(ScrollSpec { stick_bottom: false }) + .scroll_edge_fade(if column == 2 { 0.0 } else { 16.0 }).child(stack)); + } + root +} + +#[test] +fn sticky_three_column_repro_orders_rows_before_opaque_or_translucent_headers() { + let gpu = Gpu::headless(); + let mut renderer = Renderer::new(&gpu.device, OFFSCREEN_FORMAT); + let mut differences = Vec::new(); + for alpha in [1.0, 0.5] { + let mut snapshots = Vec::new(); + for rows in [false, true] { + let mut rt = Runtime::new(ThreeColumns { rows, alpha }, three_columns, (700.0, 320.0), Env::default()); + rt.frame(0.0); + rt.update(|_, tx| { + for column in 0..3 { tx.scroll_to_instant(format!("scroll-{column}"), 0.0, 150.0); } + }); + for _ in 0..120 { rt.frame(1.0 / 120.0); } + // Verify the stream itself, not just an opaque fill hiding a bad ordering. + for column in 0..3 { + let x = 20.0 + column as f32 * 220.0; + let header = rt.instances.iter().position(|p| p.rect[0] == x && p.fill[0] > 0.0 + && p.fill[1] == 0.0 && p.fill[2] == 0.0).unwrap(); + for (index, p) in rt.instances.iter().enumerate() { + if p.rect[0] >= x && p.rect[0] < x + 200.0 && p.fill[1] > 0.0 && p.fill[0] == 0.0 { + assert!(index < header, "column {column}, alpha {alpha}: row primitive {index} follows header {header}"); + } + } + } + snapshots.push(pixels(&gpu, &mut renderer, &mut rt, (700, 320))); + } + for column in 0..3 { + let mut changed = 0; + for y in 20..44 { + for x in (20 + column * 220)..(220 + column * 220) { + let at = (y * 700 + x) * 4; + changed += usize::from(snapshots[0][at..at + 4] != snapshots[1][at..at + 4]); + } + } + eprintln!("column {column}, alpha {alpha}: {changed} header pixels affected by underlying text"); + if alpha == 1.0 { differences.push(changed); } + } + } + assert_eq!(differences, vec![0; 3], "opaque headers must occlude all three columns"); +} + +#[derive(Clone, Copy)] +struct FadeEdges { edge: usize, fade: f32, explicit: bool } + +fn fade_edges(s: &FadeEdges, _: &mut Cx<FadeEdges>) -> El { + let header = el().key("header").size(24.0, 24.0).fill(Color { r: 1.0, g: 0.0, b: 0.0, a: 1.0 }); + let header = match s.edge { + 0 => header.absolute(40.0, 40.0).sticky_top(0.0), + 1 => header.absolute(40.0, 536.0).sticky_bottom(0.0), + _ => header.absolute(40.0, 40.0).sticky_left(0.0), + }; + let clip = if s.explicit { [12.0; 4] } else { [0.0; 4] }; + col().size(200.0, 200.0).fill(Color::BLACK).clip_fade(clip[0], clip[1], clip[2], clip[3]).child( + col().key("scroll").size(200.0, 200.0) + .scroll(ScrollSpec { stick_bottom: false }).scroll_xy().scroll_edge_fade(s.fade) + .child(col().size(600.0, 600.0).child(header)), + ) +} + +#[test] +fn sticky_fade_exemption_is_continuous_on_each_axis_and_preserves_explicit_clips() { + let gpu = Gpu::headless(); + let mut renderer = Renderer::new(&gpu.device, OFFSCREEN_FORMAT); + for edge in 0..3 { + for fade in [0.0, 16.0] { + for explicit in [false, true] { + let mut rt = Runtime::new(FadeEdges { edge, fade, explicit }, fade_edges, (200.0, 200.0), Env::default()); + rt.frame(0.0); + // Approach, reach, then pass the sticky threshold in each direction. The + // exemption is declarative, not gated on shift != 0: no opacity pop at 0. + for distance in [20.0, 10.0, 1.0, 0.0, -1.0, -20.0] { + rt.update(move |_, tx| { + let offset = if edge == 1 { 360.0 + distance } else { 40.0 - distance }; + tx.scroll_to_instant("scroll", if edge == 2 { offset } else { 0.0 }, if edge == 2 { 0.0 } else { offset }); + }); + rt.frame(0.0); + let header = find(&rt, "header"); + if fade > 0.0 && !explicit { + let fill = rt.instances.iter().find(|p| p.fill[0] == 1.0 && p.fill[1] == 0.0).unwrap(); + let widths = rune::render::unpack_fade(fill.fade).0; + let (sticking, opposite) = match edge { 0 => (1, 3), 1 => (3, 1), _ => (0, 2) }; + assert_eq!(widths[sticking], 0.0); + assert_eq!(widths[opposite], 16.0, "only the sticking edge is exempt"); + } + let (x, y) = match edge { + 0 => (50, header.rect[1] as usize + 1), + 1 => (50, header.rect[1] as usize + 22), + _ => (header.rect[0] as usize + 1, 50), + }; + let image = pixels(&gpu, &mut renderer, &mut rt, (200, 200)); + let red = image[(y * 200 + x) * 4]; + if explicit && distance <= 1.0 { + assert!(red < 100, "explicit clip was erased: edge {edge}, fade {fade}, distance {distance}: {red}"); + } else if !explicit { + assert_eq!(red, 255, "sticky edge faded or popped: edge {edge}, fade {fade}, distance {distance}"); + } + } + } + } + } +} + +#[test] +fn sticky_scroll_fade_preserves_an_intervening_explicit_clip() { + fn view(_: &(), _: &mut Cx<()>) -> El { + col().key("scroll").size(200.0, 200.0).scroll(ScrollSpec { stick_bottom: false }).scroll_edge_fade(16.0) + .child(col().w_full().clip_fade(0.0, 8.0, 0.0, 0.0) + .child(el().key("header").w_full().h(24.0).fill(Color::WHITE).sticky_top(0.0)) + .child(el().w_full().h(600.0))) + } + let mut rt = Runtime::new((), view, (200.0, 200.0), Env::default()); + rt.frame(0.0); + rt.update(|_, tx| tx.scroll_to_instant("scroll", 0.0, 100.0)); + rt.frame(0.0); + let fill = rt.instances.iter().find(|p| p.fill == [1.0; 4]).unwrap(); + assert_eq!(rune::render::unpack_fade(fill.fade).0[1], 8.0, "remove the scroll fade, not the explicit inner clip"); +} + +#[test] +fn sticky_header_taller_than_a_new_growth_row_keeps_its_natural_size() { + fn view(s: &bool, _: &mut Cx<bool>) -> El { + let mut stack = col().key("stack").w_full().growth(GrowthSpec::default()) + .child(el().key("lead").w_full().h(200.0)); + if *s { + stack = stack.child(memo("new-row", 0, || col().w_full() + .child(col().w_full().child(el().key("header").w_full().h(48.0).fill(Color::WHITE).sticky_top(0.0)) + .child(el().w_full().h(200.0))))); + } + col().key("scroll").size(200.0, 200.0).scroll(ScrollSpec { stick_bottom: false }) + .child(stack.child(el().key("tail").w_full().h(400.0))) + } + let mut rt = Runtime::new(false, view, (200.0, 200.0), Env::default()); + rt.frame(0.0); + rt.update(|s, tx| { *s = true; tx.scroll_to_instant("scroll", 0.0, 200.0); }); + rt.frame(1.0 / 120.0); + let wrapper = find(&rt, "new-row"); + let header = find(&rt, "header"); + assert!(wrapper.rect[3] < header.rect[3], "exercise a row shorter than its header: {wrapper:?} {header:?}"); + assert_eq!(header.rect[3], 48.0, "bounds do not resize the header"); + assert_eq!(header.rect[1], wrapper.rect[1], "the growing row reveals the header in place rather than lifting it outside the row"); + let fill = rt.instances.iter().find(|p| p.fill == [1.0; 4]).unwrap(); + assert_eq!(fill.rect[3], 48.0, "paint keeps the header size; the existing growth mask owns its reveal"); +} diff --git a/app/vendor/rune/crates/rune/tests/integration/sticky_showing.rs b/app/vendor/rune/crates/rune/tests/integration/sticky_showing.rs new file mode 100644 index 0000000..e4cfbf7 --- /dev/null +++ b/app/vendor/rune/crates/rune/tests/integration/sticky_showing.rs @@ -0,0 +1,51 @@ +//! `El::sticky_top_showing`: a header that scrolls up until only its bottom shows, then stays, +//! wherever its height puts that, from the frame that lays it out. +use rune::{Cx, El, Env, Runtime, ScrollSpec, col, el}; + +struct S { + head: f32, +} + +fn view(s: &S, _: &mut Cx<S>) -> El { + let page = col() + .w_full() + .child(el().key("head").w_full().h(s.head).sticky_top_showing(20.0)) + .child(el().key("body").w_full().h(1000.0)); + col().w_full().h_full().child(col().key("scroll").w(300.0).h(200.0).scroll(ScrollSpec { stick_bottom: false }).child(page)) +} + +fn head(rt: &Runtime<S>) -> [f32; 4] { + rt.elements().into_iter().find(|e| e.key.as_deref() == Some("head")).expect("head").rect +} + +fn head_y(rt: &Runtime<S>) -> f32 { + head(rt)[1] +} + +#[test] +fn it_scrolls_away_until_its_bottom_shows_and_follows_a_new_height_on_its_first_frame() { + let mut rt = Runtime::new(S { head: 100.0 }, view, (300.0, 300.0), Env::new(true, 1.0)); + rt.frame(0.0); + rt.update(|_, tx| tx.scroll_to_y("scroll", 50.0)); + rt.frame(1.0 / 60.0); + assert_eq!(head_y(&rt), -50.0, "scrolls with the page while more than 20 shows"); + rt.update(|_, tx| tx.scroll_to_y("scroll", 300.0)); + rt.frame(2.0 / 60.0); + assert_eq!(head_y(&rt), -80.0, "then holds with its last 20 in view"); + + rt.update(|s, tx| { + s.head = 140.0; + tx.instant(); + }); + rt.frame(3.0 / 60.0); + assert_eq!(head_y(&rt), -120.0, "a taller one holds its last 20 in view on the frame it grows"); + + // Shrinking on its spring, its bottom stays put every frame. + rt.update(|s, _| s.head = 60.0); + for n in 4..40 { + rt.frame(n as f64 / 60.0); + let r = head(&rt); + assert!((r[1] + r[3] - 20.0).abs() < 0.01, "frame {n}: bottom at {}", r[1] + r[3]); + } + assert_eq!(head_y(&rt), -40.0); +} diff --git a/app/vendor/rune/crates/rune/tests/integration/text_case.rs b/app/vendor/rune/crates/rune/tests/integration/text_case.rs new file mode 100644 index 0000000..894a406 --- /dev/null +++ b/app/vendor/rune/crates/rune/tests/integration/text_case.rs @@ -0,0 +1,46 @@ +//! `El::text_case` draws cased glyphs while tools, spans and links keep the authored string. +use rune::runtime::ElementInfo; +use rune::{Cx, El, Env, Link, Runtime, Span, TextCase, TextEdit, TextStyle, col, rich, text, text_input}; + +struct S { edit: TextEdit } + +fn view(s: &S, _: &mut Cx<S>) -> El { + let style = TextStyle::new(14.0, 400.0).lh(20.0); + let red = rune::color::hex("#ff0000").unwrap(); + col().w_full().h_full().gap(10.0) + .child(text("Straße").key("cased").font(style).text_case(TextCase::Uppercase)) + .child(text("STRASSE").key("typed").font(style)) + .child(rich("ß link", vec![Span { color: Some(red), ..Span::new(3, 7) }]).key("rich").font(style).w(200.0) + .text_case(TextCase::Uppercase).link(Link::new(3..7, "go"))) + .child(rich("SS LINK", Vec::new()).key("rich-typed").font(style).w(200.0).link(Link::new(3..7, "go-typed"))) + .child(text_input(&s.edit, style).key("field").w(200.0).text_case(TextCase::Uppercase).on_edit(|s: &mut S| &mut s.edit)) +} + +fn find(rt: &Runtime<S>, key: &str) -> ElementInfo { + rt.elements().into_iter().find(|e| e.key.as_deref() == Some(key)).unwrap_or_else(|| panic!("{key}")) +} + +fn runtime() -> Runtime<S> { + let mut rt = Runtime::new(S { edit: TextEdit::new("straße") }, view, (300.0, 300.0), Env::new(true, 2.0)); + rt.frame(0.0); + rt +} + +#[test] +fn cased_text_draws_capitals_and_reports_its_authored_string() { + let rt = runtime(); + let (cased, typed) = (find(&rt, "cased"), find(&rt, "typed")); + assert_eq!(cased.text.as_deref(), Some("Straße"), "tools read the authored string"); + assert_eq!(cased.rect[2], typed.rect[2], "ß draws SS: the same width as typed capitals"); + assert_eq!(find(&rt, "field").text.as_deref(), Some("straße"), "fields draw what is typed"); +} + +#[test] +fn spans_and_links_keep_their_authored_byte_ranges() { + let rt = runtime(); + let (link, typed) = (find(&rt, "go"), find(&rt, "go-typed")); + assert_eq!(link.text.as_deref(), Some("link"), "the link reports its authored words"); + assert_eq!(link.rect[0], typed.rect[0], "the link sits over LINK after the expanded SS"); + assert_eq!(link.rect[2], typed.rect[2]); + assert_eq!(find(&rt, "rich").text.as_deref(), Some("ß link")); +} diff --git a/app/vendor/rune/crates/rune/tests/integration/theme_blend.rs b/app/vendor/rune/crates/rune/tests/integration/theme_blend.rs new file mode 100644 index 0000000..4521269 --- /dev/null +++ b/app/vendor/rune/crates/rune/tests/integration/theme_blend.rs @@ -0,0 +1,79 @@ +//! A theme's translucent tokens are authored for a browser's sRGB blending. Composited over +//! their backdrop they give the browser's pixel in a window of either blend mode, and follow a +//! live switch, memoised rows included. +use rune::color::{over, srgb_encode}; +use rune::text::TextSystem; +use rune::{Cx, El, Env, Runtime, Theme, el, memo}; + +const THEME: &str = r##"{ "name": "Test", "blend": { "mode": "srgb", "over": "bg" }, + "light": { "bg": "#f8f8f8", "border": "#0000001f" }, + "dark": { "bg": "#161616", "border": "#ffffff1a" } }"##; + +fn view(t: &Theme, _: &mut Cx<Theme>) -> El { + el().size(40.0, 40.0).fill(t.color("bg")) + .child(el().size(20.0, 20.0).fill(t.color("border"))) + .child(memo("row", (), || el().size(10.0, 10.0).fill(t.color("border")))) +} + +fn runtime(dark: bool, srgb: bool) -> Runtime<Theme> { + let theme = Theme::from_json(THEME, dark).unwrap(); + let text = TextSystem::new(&[], ("Inter", "Inter")); + let mut rt = Runtime::with_text(theme, view, (40.0, 40.0), Env::new(dark, 1.0), text); + rt.set_srgb_blend(srgb); + rt.frame(0.0); + rt +} + +/// The token in the `side`-point box composited over the backdrop, as sRGB bytes. +fn composited(rt: &Runtime<Theme>, side: f32) -> [f32; 3] { + let fill = |w: f32| rt.instances.iter().find(|i| i.rect[2] == w && i.fill[3] > 0.0).unwrap_or_else(|| panic!("a {w}-point box")).fill; + let px = over(fill(side), fill(40.0)); + let encode = |v: f32| if rt.srgb_blend() { v } else { srgb_encode(v) }; + [0, 1, 2].map(|i| encode(px[i]) * 255.0) +} + +/// CSS source-over in sRGB bytes: `a·fg + (1 − a)·bg`. +fn browser(fg: u8, bg: u8, a: u8) -> f32 { + let a = a as f32 / 255.0; + a * fg as f32 + (1.0 - a) * bg as f32 +} + +fn assert_browser(rt: &Runtime<Theme>, want: f32, what: &str) { + for side in [20.0, 10.0] { + let got = composited(rt, side); + assert!(got.iter().all(|v| (v - want).abs() < 0.5), "{what}, {side}-point box: {got:?} vs {want}"); + } +} + +#[test] +fn a_translucent_token_composites_to_the_browser_pixel_in_both_blend_modes() { + for (dark, want) in [(true, browser(0xff, 0x16, 0x1a)), (false, browser(0x00, 0xf8, 0x1f))] { + for srgb in [true, false] { + assert_browser(&runtime(dark, srgb), want, &format!("dark {dark}, sRGB blending {srgb}")); + } + } +} + +/// The view runs again with the new mode, memoised rows included; the fills then ease to their +/// new values as any colour change does. +#[test] +fn a_live_switch_resolves_tokens_again() { + let want = browser(0xff, 0x16, 0x1a); + let mut rt = runtime(true, false); + for srgb in [true, false] { + rt.update(|_, tx| tx.set_srgb_blend(srgb)); + rt.frame(1.0 / 60.0); + rt.frame(1.0); + assert_browser(&rt, want, &format!("switched to sRGB blending {srgb}")); + } +} + +#[test] +fn outside_a_runtime_tokens_resolve_as_authored() { + let t = Theme::from_json(THEME, true).unwrap(); + assert!(rune::theme::blends_srgb()); + assert_eq!(t.color("border").a, 0x1a as f32 / 255.0); + let linear = rune::theme::with_blend(false, || t.color("border")); + assert!(linear.a < t.color("border").a, "linear light needs less alpha over a dark backdrop: {}", linear.a); + assert!(rune::theme::blends_srgb(), "with_blend restores the mode"); +} diff --git a/app/vendor/rune/crates/rune/tests/integration/tx_blur.rs b/app/vendor/rune/crates/rune/tests/integration/tx_blur.rs new file mode 100644 index 0000000..77c9232 --- /dev/null +++ b/app/vendor/rune/crates/rune/tests/integration/tx_blur.rs @@ -0,0 +1,60 @@ +//! `Tx::blur` drops keyboard focus from a handler. +use rune::tok::TextStyle; +use rune::{Cx, El, Env, Key, KeyEvent, Mods, Runtime, TextEdit, col, text_input}; + +#[derive(Default)] +struct S { + field: TextEdit, + submits: u32, + keys: u32, +} + +fn view(s: &S, _: &mut Cx<S>) -> El { + col().size(200.0, 100.0).child( + text_input(&s.field, TextStyle::new(14.0, 400.0)).key("field").w(150.0) + .on_edit(|s: &mut S| &mut s.field) + .on_submit(|s: &mut S, tx| { s.submits += 1; tx.blur(); }), + ) +} + +fn focused(rt: &Runtime<S>) -> bool { + rt.elements().iter().any(|e| e.key.as_deref() == Some("field") && e.focused) +} + +fn runtime() -> Runtime<S> { + let mut s = S::default(); + s.field.focused = true; + let mut rt = Runtime::new(s, view, (200.0, 100.0), Env::default()); + rt.on_key = Some(|s, _, _| { s.keys += 1; true }); + rt.frame(0.0); + assert!(focused(&rt), "the model asked for focus"); + rt +} + +fn press(rt: &mut Runtime<S>, key: Key) { + rt.key(KeyEvent { key, mods: Mods::default() }); + rt.frame(1.0 / 60.0); +} + +#[test] +fn a_submit_handler_blurs_its_field() { + let mut rt = runtime(); + press(&mut rt, Key::Enter); + assert_eq!(rt.state.submits, 1); + assert!(!focused(&rt), "nothing has focus"); + assert!(!rt.state.field.focused, "the model hears it through on_edit"); + rt.frame(1.0 / 60.0); + assert!(!focused(&rt), "and focus stays dropped"); + press(&mut rt, Key::Text("z".into())); + assert_eq!(rt.state.field.text.as_str(), "", "typing no longer reaches the field"); + assert_eq!(rt.state.keys, 1, "keys go to the window"); +} + +#[test] +fn an_update_blurs_and_asks_for_a_frame() { + let mut rt = runtime(); + assert!(rt.update_if(|_, tx| { tx.blur(); false }), "a blur that drops focus is frame work"); + rt.frame(1.0 / 60.0); + assert!(!focused(&rt)); + assert!(!rt.update_if(|_, tx| { tx.blur(); false }), "with nothing focused it's nothing"); +} diff --git a/app/vendor/rune/crates/rune/tests/integration/window_panel_compat.rs b/app/vendor/rune/crates/rune/tests/integration/window_panel_compat.rs new file mode 100644 index 0000000..265da19 --- /dev/null +++ b/app/vendor/rune/crates/rune/tests/integration/window_panel_compat.rs @@ -0,0 +1,31 @@ +use rune::*; + +#[test] +fn window_panel_builders_preserve_exhaustive_literals_and_default_inference() { + fn view(_: &(), _: &mut Cx<()>) -> El { el() } + let spec = AppSpec { + title: "compat", size: (300.0, 100.0), min_size: None, init: || (), view, + scenes: &[("scene", |_| {})], fonts: &[], families: ("Inter", "Inter"), + setup: None, poll: Some(|_, _, _| false), on_key: Some(|_, _, _| false), + }; + let options = WindowOptions { + transparent: true, borderless: true, click_through: false, always_on_top: false, + visible: false, position: None, physical_size: None, min_size: None, max_size: None, + resizable: false, + }; + let app = App::new(spec).on_focus(|_, _, _| {}).macos_window(MacWindowOptions::default().nonactivating_panel(true)); + let handle = app.handle(); + // Existing WindowSpec literals remain exhaustive too. + let window = WindowSpec { key: "quick".into(), app, options, on_created: None } + .on_focus(|_, _, _| {}).options(Default::default()); + let _ = window.configured_options(WindowOptions::default().macos(MacWindowOptions::default().nonactivating_panel(true) + .corner_radius(16.0).corner_curve_circular())); + handle.place(DisplayTarget::Primary, OverlayPlacement::FullScreen); + let overlay = OverlaySpec { name: "compat", size: (50.0, 50.0), edge: ScreenEdge::Top, + margin: 0.0, align: Align::Center, inset: 0.0, interactive: true, view }; + let _ = overlay.options(Default::default()).on_focus(|_, _, _| {}); + let _ = WindowSpec::new("launcher", AppSpec::new("launcher", (300.0, 100.0), || (), view)) + .configured_options(WindowOptions::launcher_panel()).on_ready(|w| { assert!(w.is_ready()); }); + let _ = App::new(AppSpec::new("launcher", (300.0, 100.0), || (), view)) + .configured_options(WindowOptions::launcher_panel()).on_ready(|_| {}).window_options(Default::default()); +} diff --git a/app/vendor/rune/crates/rune/tests/launcher_wakes.rs b/app/vendor/rune/crates/rune/tests/launcher_wakes.rs new file mode 100644 index 0000000..970b484 --- /dev/null +++ b/app/vendor/rune/crates/rune/tests/launcher_wakes.rs @@ -0,0 +1,164 @@ +//! A retained launcher panel (`WindowOptions::launcher_panel`) runs `poll` on a plain +//! `AppHandle::wake`, hidden or shown, and never reveals cached pixels older than an update +//! in the same turn. With RUNE_LATENCY=1 it repeats 12 times and prints the median reveal +//! latency of both paths. Opens a native panel, so it only runs with RUNE_GUI_TESTS=1 in a +//! logged-in macOS GUI session. + +#[cfg(not(target_os = "macos"))] +fn main() {} + +#[cfg(target_os = "macos")] +fn main() { mac::main() } + +#[cfg(target_os = "macos")] +mod mac { + use std::sync::{Mutex, OnceLock, atomic::{AtomicUsize, Ordering}}; + use std::time::{Duration, Instant}; + use rune::*; + + struct State { label: String } + + static POLLS: AtomicUsize = AtomicUsize::new(0); + static INBOX: Mutex<Vec<String>> = Mutex::new(Vec::new()); + /// Each rendered label, with whether the window was already revealed when it rendered. + static RENDERS: Mutex<Vec<(String, bool)>> = Mutex::new(Vec::new()); + static HANDLE: OnceLock<AppHandle<State>> = OnceLock::new(); + + fn view(s: &State, _: &mut Cx<State>) -> El { + let visible = HANDLE.get().is_some_and(|h| h.is_visible()); + RENDERS.lock().unwrap().push((s.label.clone(), visible)); + text(&s.label) + } + + fn poll(s: &mut State, _: f64, _: &mut Tx) -> bool { + if BLOCK.swap(false, Ordering::SeqCst) { + std::thread::sleep(Duration::from_millis(100)); + *UNBLOCKED.lock().unwrap() = Some(rune::time::now()); + return false; + } + POLLS.fetch_add(1, Ordering::SeqCst); + let Some(label) = INBOX.lock().unwrap().pop() else { return false }; + s.label = label; + true + } + + fn wait(what: &str, f: impl Fn() -> bool) { + let start = rune::time::now(); + while !f() { + assert!(start.elapsed() < Duration::from_secs(5), "timed out waiting for {what}"); + std::thread::sleep(Duration::from_millis(2)); + } + } + + fn rendered(label: &str) -> Option<bool> { + RENDERS.lock().unwrap().iter().find(|(l, _)| l == label).map(|(_, visible)| *visible) + } + + fn wake_with(handle: &AppHandle<State>, label: &str) { + let before = POLLS.load(Ordering::SeqCst); + INBOX.lock().unwrap().push(label.into()); + handle.wake(); + wait(&format!("poll for {label}"), || POLLS.load(Ordering::SeqCst) > before); + wait(&format!("a render of {label}"), || rendered(label).is_some()); + } + + pub fn main() { + if std::env::var_os("RUNE_GUI_TESTS").is_none() { + println!("launcher_wakes: skipped (set RUNE_GUI_TESTS=1 in a GUI session)"); + return; + } + std::thread::spawn(|| { std::thread::sleep(Duration::from_secs(60)); eprintln!("timeout"); std::process::exit(2) }); + let spec = AppSpec { poll: Some(poll), ..AppSpec::new("launcher wakes", (240.0, 80.0), || State { label: "initial".into() }, view) }; + let (ready_tx, ready_rx) = std::sync::mpsc::channel(); + let app = App::new(spec).args(Vec::new()).keep_running() + .configured_options(WindowOptions::launcher_panel()) + .on_ready(move |_| { ready_tx.send(()).ok(); }); + let handle = app.handle(); + HANDLE.set(handle.clone()).ok(); + let result = std::sync::Arc::new(Mutex::new(None)); + let out = result.clone(); + std::thread::spawn(move || { + let run = std::panic::catch_unwind(|| { + ready_rx.recv_timeout(Duration::from_secs(10)).expect("launcher ready"); + hidden_and_shown_wakes(&handle); + reveal_after_update(&handle); + }); + *out.lock().unwrap() = Some(run.is_ok()); + handle.quit(); + }); + app.run(); + assert_eq!(*result.lock().unwrap(), Some(true), "launcher_wakes failed"); + println!("launcher_wakes: ok"); + } + + fn hidden_and_shown_wakes(handle: &AppHandle<State>) { + assert!(!handle.is_visible()); + wake_with(handle, "hidden"); + assert_eq!(rendered("hidden"), Some(false), "a hidden poll change renders the cached frame hidden"); + let polls = POLLS.load(Ordering::SeqCst); + std::thread::sleep(Duration::from_millis(300)); + // A loop would poll every frame; AppKit may still ask for a stray hidden redraw. + assert!(POLLS.load(Ordering::SeqCst) <= polls + 2, "a hidden launcher must not run a frame loop"); + assert!(!handle.is_visible()); + + handle.open(); + wait("reveal", || handle.is_visible()); + std::thread::sleep(Duration::from_millis(100)); + wake_with(handle, "shown"); + assert_eq!(rendered("shown"), Some(true)); + handle.hide(); + wait("hide", || !handle.is_visible()); + } + + static BLOCK: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + static UNBLOCKED: Mutex<Option<Instant>> = Mutex::new(None); + + /// Queues `requests` while the event thread is busy in a hidden poll, so one drain takes + /// them all, and returns the time from that drain's start until the window is shown. + fn reveal_in_one_drain(handle: &AppHandle<State>, requests: impl FnOnce()) -> Duration { + BLOCK.store(true, Ordering::SeqCst); + handle.wake(); + std::thread::sleep(Duration::from_millis(30)); + requests(); + let start = rune::time::now(); + while !handle.is_visible() { assert!(start.elapsed() < Duration::from_secs(5), "timed out waiting for reveal"); } + let shown = rune::time::now(); + shown - UNBLOCKED.lock().unwrap().take().expect("blocking update ran") + } + + fn hide(handle: &AppHandle<State>) { + handle.hide(); + wait("hide", || !handle.is_visible()); + std::thread::sleep(Duration::from_millis(150)); + } + + fn reveal_after_update(handle: &AppHandle<State>) { + let latency = rune::env::var("RUNE_LATENCY").as_deref() == Some("1"); + let (mut cached, mut fresh) = (Vec::new(), Vec::new()); + for i in 0..if latency { 12 } else { 1 } { + cached.push(reveal_in_one_drain(handle, || handle.open())); + hide(handle); + let label = format!("fresh {i}"); + let update = label.clone(); + fresh.push(reveal_in_one_drain(handle, || { + handle.update(move |s, _| s.label = update); + handle.open(); + })); + assert_eq!(rendered(&label), Some(false), "the update rendered hidden before the reveal"); + hide(handle); + } + INBOX.lock().unwrap().clear(); + reveal_in_one_drain(handle, || { + INBOX.lock().unwrap().push("polled".into()); + handle.wake(); + handle.open(); + }); + assert_eq!(rendered("polled"), Some(false), "a wake's poll ran and rendered before the reveal"); + hide(handle); + if latency { + let median = |v: &mut Vec<Duration>| { v.sort(); v[v.len() / 2].as_secs_f64() * 1000.0 }; + let (cached, fresh) = (median(&mut cached), median(&mut fresh)); + println!("launcher_wakes: reveal median {cached:.2} ms cached, {fresh:.2} ms after an update (+{:.2} ms)", fresh - cached); + } + } +} diff --git a/app/vendor/rune/crates/rune/tests/macos_appearance_kvo.rs b/app/vendor/rune/crates/rune/tests/macos_appearance_kvo.rs new file mode 100644 index 0000000..0ae5116 --- /dev/null +++ b/app/vendor/rune/crates/rune/tests/macos_appearance_kvo.rs @@ -0,0 +1,210 @@ +//! winit's `effectiveAppearance` observer receives `NSNull` when ReplayKit/ScreenCaptureKit +//! calls `setStyleMask:` on app windows. Opens windows, so it only runs with RUNE_GUI_TESTS=1 +//! in a logged-in GUI session. Each case runs in a child process because the bug aborts. + +#![allow(unsafe_code)] + +#[cfg(not(target_os = "macos"))] +fn main() {} + +#[cfg(target_os = "macos")] +fn main() { mac::main() } + +#[cfg(target_os = "macos")] +mod mac { + use std::{os::unix::process::ExitStatusExt, process::Command, sync::atomic::{AtomicBool, Ordering}, time::Duration}; + use objc2::{class, msg_send, runtime::AnyObject}; + use objc2_foundation::{NSString, ns_string}; + use winit::{application::ApplicationHandler, event::WindowEvent, event_loop::{ActiveEventLoop, ControlFlow, EventLoop}, window::{Theme, Window, WindowId}}; + use winit::raw_window_handle::{HasWindowHandle, RawWindowHandle}; + + const CASE: &str = "RUNE_APPEARANCE_CASE"; + const SIGABRT: i32 = 6; + + #[link(name = "Foundation", kind = "framework")] + unsafe extern "C" { + static NSKeyValueChangeOldKey: *mut AnyObject; + static NSKeyValueChangeNewKey: *mut AnyObject; + } + + pub fn main() { + if std::env::var_os(CASE).is_some() { + std::thread::spawn(|| { std::thread::sleep(Duration::from_secs(60)); eprintln!("timeout"); std::process::exit(2) }); + } + match rune::env::var(CASE).as_deref() { + Some("unguarded") => winit_case(false), + Some("guarded") => winit_case(true), + Some("rune") => rune_case(), + _ => parent(), + } + } + + fn parent() { + if std::env::var_os("RUNE_GUI_TESTS").is_none() { + println!("macos_appearance_kvo: skipped (set RUNE_GUI_TESTS=1 in a GUI session)"); + return; + } + let run = |case: &str| { + let out = Command::new(std::env::current_exe().unwrap()).env(CASE, case).env("RUST_BACKTRACE", "0").output().unwrap(); + let log = format!("{}{}", String::from_utf8_lossy(&out.stdout), String::from_utf8_lossy(&out.stderr)); + let lines: Vec<&str> = log.lines().filter(|l| !l.starts_with(' ')).collect(); + println!("--- {case}: {:?}\n{}", out.status, lines[lines.len().saturating_sub(4)..].join("\n")); + (out.status, log) + }; + let (status, log) = run("unguarded"); + assert_eq!(status.signal(), Some(SIGABRT), "plain winit must abort on an NSNull appearance"); + assert!(log.contains("NSNull"), "the abort should be winit messaging NSNull"); + let (status, log) = run("guarded"); + assert!(status.success() && log.contains("guarded ok"), "guarded winit window must survive and keep ThemeChanged"); + let (status, log) = run("rune"); + assert!(status.success() && log.contains("rune ok"), "Rune window and overlay panel must survive"); + println!("macos_appearance_kvo: ok"); + } + + fn appearance(name: &str) -> *mut AnyObject { + let name = NSString::from_str(name); + // SAFETY: `NSAppearance +appearanceNamed:` is called on the main thread with a live `NSString`. + unsafe { msg_send![class!(NSAppearance), appearanceNamed: &*name] } + } + + fn null() -> *mut AnyObject { + // SAFETY: `+[NSNull null]` returns the process-lifetime singleton pointer. + unsafe { msg_send![class!(NSNull), null] } + } + + /// Exactly what AppKit's KVO delivers to winit: `old`/`new` may be `NSNull`. + fn notify(window: *mut AnyObject, old: *mut AnyObject, new: *mut AnyObject) { + // SAFETY: called on the AppKit main thread with a live `NSWindow` and non-null `NSAppearance`/`NSNull` pointers. + unsafe { + let delegate: *mut AnyObject = msg_send![window, delegate]; + let change: *mut AnyObject = msg_send![class!(NSMutableDictionary), dictionary]; + let _: () = msg_send![change, setObject: old, forKey: NSKeyValueChangeOldKey]; + let _: () = msg_send![change, setObject: new, forKey: NSKeyValueChangeNewKey]; + let key: &AnyObject = ns_string!("effectiveAppearance"); + let _: () = msg_send![delegate, observeValueForKeyPath: key, ofObject: window, change: change, context: std::ptr::null_mut::<std::ffi::c_void>()]; + } + } + + fn toggle_style_mask(window: *mut AnyObject, times: usize) { + const RESIZABLE: usize = 1 << 3; + // SAFETY: called on the AppKit main thread with a live `NSWindow`. + unsafe { + let mask: usize = msg_send![window, styleMask]; + for i in 0..times { + let _: () = msg_send![window, setStyleMask: if i % 2 == 0 { mask ^ RESIZABLE } else { mask }]; + } + let _: () = msg_send![window, setStyleMask: mask]; + } + } + + fn ns_window(window: &Window) -> *mut AnyObject { + let RawWindowHandle::AppKit(handle) = window.window_handle().unwrap().as_raw() else { unreachable!() }; + // SAFETY: `handle.ns_view` is a live `NSView` owned by `window` on the AppKit main thread. + unsafe { msg_send![handle.ns_view.as_ptr().cast::<AnyObject>(), window] } + } + + struct Probe { guarded: bool, window: Option<Window>, themes: Vec<Theme>, step: u32 } + + impl ApplicationHandler for Probe { + fn resumed(&mut self, event_loop: &ActiveEventLoop) { + if self.window.is_some() { return; } + self.window = Some(event_loop.create_window(Window::default_attributes().with_visible(false)).unwrap()); + if self.guarded { rune::macos_appearance::install(); } + event_loop.set_control_flow(ControlFlow::WaitUntil(rune::time::now() + Duration::from_millis(20))); + } + fn window_event(&mut self, _: &ActiveEventLoop, _: WindowId, event: WindowEvent) { + if let WindowEvent::ThemeChanged(theme) = event { self.themes.push(theme); } + } + fn about_to_wait(&mut self, event_loop: &ActiveEventLoop) { + let Some(window) = &self.window else { return }; + let window = ns_window(window); + let (aqua, dark) = (appearance("NSAppearanceNameAqua"), appearance("NSAppearanceNameDarkAqua")); + self.step += 1; + match self.step { + 1 => { + notify(window, null(), null()); + println!("survived NSNull -> NSNull"); + // A transient nil between equal appearances is not a theme change. + notify(window, aqua, null()); + notify(window, null(), aqua); + toggle_style_mask(window, 100); + } + // A real change that straddles a nil transition still reaches winit. + 2 => { notify(window, aqua, null()); notify(window, null(), dark); } + // Ordinary appearance changes pass through untouched. + 3 => notify(window, dark, aqua), + 5 => { + assert_eq!(self.themes, [Theme::Dark, Theme::Light]); + println!("guarded ok themes={:?}", self.themes); + event_loop.exit(); + return; + } + _ => {} + } + event_loop.set_control_flow(ControlFlow::WaitUntil(rune::time::now() + Duration::from_millis(20))); + } + } + + fn winit_case(guarded: bool) { + let event_loop = EventLoop::new().unwrap(); + event_loop.run_app(&mut Probe { guarded, window: None, themes: Vec::new(), step: 0 }).unwrap(); + } + + static OVERLAY_CREATED: AtomicBool = AtomicBool::new(false); + + fn view<T>(_: &T, _: &mut rune::Cx<T>) -> rune::El { rune::el().w_full().h_full() } + + fn stress() { + let (aqua, dark) = (appearance("NSAppearanceNameAqua"), appearance("NSAppearanceNameDarkAqua")); + let mut observed = Vec::new(); + // SAFETY: invoked on the AppKit main thread (`handle.update`); every `i` is `< count` + // and `delegate` is checked non-null before dereferencing. + unsafe { + let app: *mut AnyObject = msg_send![class!(NSApplication), sharedApplication]; + let windows: *mut AnyObject = msg_send![app, windows]; + let count: usize = msg_send![windows, count]; + for i in 0..count { + let window: *mut AnyObject = msg_send![windows, objectAtIndex: i]; + let delegate: *mut AnyObject = msg_send![window, delegate]; + // The real isa, which KVO subclasses at runtime. + let class = (*window).class().name().to_string_lossy().into_owned(); + let winit = !delegate.is_null() && (*delegate).class().name() == c"WinitWindowDelegate"; + for _ in 0..50 { + toggle_style_mask(window, 2); + if winit { + notify(window, null(), null()); + notify(window, aqua, null()); + notify(window, null(), dark); + notify(window, dark, aqua); + } + } + if winit { observed.push(class); } + } + } + observed.sort(); + println!("rune ok winit windows={observed:?}"); + assert!(observed.iter().any(|c| c == "RuneOverlayPanel"), "overlay panel missing"); + // The ordinary window and the overlay's hidden source keep winit's (KVO) class. + assert_eq!(observed.iter().filter(|c| c.ends_with("WinitWindow")).count(), 2, "ordinary or overlay source window missing"); + std::process::exit(0); + } + + fn rune_case() { + let spec = rune::AppSpec::new("appearance-kvo", (320.0, 200.0), || (), view::<()>); + let mut app = rune::App::new(spec).args(["appearance-kvo".to_string()]); + let handle = app.handle(); + // Launch can take seconds on a busy machine: stress once the overlay's panel exists. + std::thread::spawn(move || { + let deadline = rune::time::now() + Duration::from_secs(45); + while !OVERLAY_CREATED.load(Ordering::Acquire) { + if rune::time::now() > deadline { eprintln!("overlay was not created within 45 s"); std::process::exit(3) } + std::thread::sleep(Duration::from_millis(20)); + } + handle.update(|_, _| stress()); + }); + let overlay = app.overlay(rune::OverlaySpec::new("appearance-kvo overlay", (200.0, 80.0), view::<()>).options(rune::OverlayOptions::default()) + .on_created(|_| OVERLAY_CREATED.store(true, Ordering::Release)), ()); + overlay.show(); + app.run(); + } +} diff --git a/app/vendor/rune/crates/rune/tests/macos_drag_out.rs b/app/vendor/rune/crates/rune/tests/macos_drag_out.rs new file mode 100644 index 0000000..0730603 --- /dev/null +++ b/app/vendor/rune/crates/rune/tests/macos_drag_out.rs @@ -0,0 +1,130 @@ +//! An `El::drag_out` element starts an AppKit drag session from inside the mouse-dragged +//! event and writes the file to the drag pasteboard the way Finder and System Settings read it. +//! The press and drag are synthesized with `postEvent:`, but AppKit tracks a live session from +//! the window server, so ending it takes a real button release: with Accessibility access the +//! test posts one where the pointer already is, then checks the end callback ran once and the +//! next click is an ordinary press. Without it, it checks the session start and pasteboard only. +//! Opens a window, so it only runs with RUNE_GUI_TESTS=1 in a logged-in GUI session. + +#[cfg(not(target_os = "macos"))] +fn main() {} + +#[cfg(target_os = "macos")] +mod macos_support; + +#[cfg(target_os = "macos")] +fn main() { mac::main() } + +#[cfg(target_os = "macos")] +#[allow(unsafe_code)] +mod mac { + use std::sync::{Mutex, atomic::{AtomicUsize, Ordering}}; + use std::time::Duration; + use objc2::{class, msg_send, rc::Retained, runtime::{AnyObject, Bool}}; + use objc2_foundation::{NSArray, NSPoint, NSRect}; + use rune::*; + use crate::macos_support::{can_post_events, drag_pasteboard, on_main, release_real_button, wait}; + + static PRESSES: AtomicUsize = AtomicUsize::new(0); + static ENDED: Mutex<Vec<DragOutcome>> = Mutex::new(Vec::new()); + static FILE: Mutex<Option<std::path::PathBuf>> = Mutex::new(None); + + fn view(_: &(), _: &mut Cx<()>) -> El { + el().w_full().h_full().fill(rune::color::oklch(0.6, 0.18, 255.0)) + .on_press(|_: &mut ()| { PRESSES.fetch_add(1, Ordering::SeqCst); }) + .drag_out(|_: &()| FILE.lock().unwrap().clone().map(|f| DragItem::new().file(f))) + .on_drag_end(|_: &mut (), outcome, _| ENDED.lock().unwrap().push(outcome)) + } + + /// Posts mouse events to the app's visible window: (NSEventType, x, y) in points from the + /// window's top-left. + fn post(events: &[(usize, f64, f64)]) { + // SAFETY: invoked on the AppKit main thread (`on_main`); queries the app's live windows + // and posts synthetic `NSEvent`s to `NSApplication`. + unsafe { + let app: *mut AnyObject = msg_send![class!(NSApplication), sharedApplication]; + let windows: Retained<NSArray<AnyObject>> = msg_send![app, windows]; + let window = windows.iter().find(|w| { let v: Bool = msg_send![&**w, isVisible]; v.as_bool() }).expect("a visible window"); + let number: isize = msg_send![&*window, windowNumber]; + let content: NSRect = msg_send![&*window, contentLayoutRect]; + let info: *mut AnyObject = msg_send![class!(NSProcessInfo), processInfo]; + let now: f64 = msg_send![info, systemUptime]; + for &(kind, x, y) in events { + let at = NSPoint::new(content.origin.x + x, content.origin.y + content.size.height - y); + let event: *mut AnyObject = msg_send![class!(NSEvent), mouseEventWithType: kind, location: at, modifierFlags: 0usize, + timestamp: now, windowNumber: number, context: std::ptr::null_mut::<AnyObject>(), eventNumber: 0isize, clickCount: 1isize, pressure: 1.0f32]; + let _: () = msg_send![app, postEvent: event, atStart: Bool::NO]; + } + } + } + + const DOWN: usize = 1; + const UP: usize = 2; + const DRAGGED: usize = 6; + + /// Whether the session ended (it can't without Accessibility access to post a release). + fn drive(handle: AppHandle<()>, file: std::path::PathBuf) -> bool { + std::thread::sleep(Duration::from_millis(500)); + on_main(&handle, || post(&[(DOWN, 40.0, 40.0), (DRAGGED, 42.0, 40.0), (DRAGGED, 52.0, 40.0), (DRAGGED, 80.0, 40.0), (UP, 80.0, 40.0)])); + let name = file.file_name().unwrap().to_str().unwrap().to_owned(); + let mut board = (None, None); + for _ in 0..50 { + std::thread::sleep(Duration::from_millis(100)); + board = on_main(&handle, drag_pasteboard); + if board.0.as_deref().is_some_and(|u| u.ends_with(&name)) { break; } + } + let (url, names) = board; + let url = url.expect("the session started and wrote the drag pasteboard"); + assert!(url.starts_with("file://") && url.ends_with(file.file_name().unwrap().to_str().unwrap()), "file URL {url}"); + assert_eq!(names.as_deref(), Some(&*file.to_string_lossy()), "AppKit derives the path list Finder reads"); + assert_eq!(PRESSES.load(Ordering::SeqCst), 0, "a drag-out isn't a press"); + if ENDED.lock().unwrap().is_empty() { + if !can_post_events() { + println!("macos_drag_out: session started, pasteboard {url}; ending it needs a real button release, which this process may not post (no Accessibility access)"); + return false; + } + release_real_button(); + } + wait("the drag to end", || !ENDED.lock().unwrap().is_empty()); + assert_eq!(ENDED.lock().unwrap().len(), 1, "on_drag_end runs once"); + on_main(&handle, || post(&[(DOWN, 40.0, 40.0), (UP, 40.0, 40.0)])); + wait("a click after the drag to press", || PRESSES.load(Ordering::SeqCst) == 1); + println!("macos_drag_out: session ended {:?}, pasteboard {url}", ENDED.lock().unwrap()[0]); + true + } + + pub fn main() { + if std::env::var_os("RUNE_GUI_TESTS").is_none() { + println!("macos_drag_out: skipped (set RUNE_GUI_TESTS=1 in a GUI session)"); + return; + } + std::thread::spawn(|| { std::thread::sleep(Duration::from_secs(60)); eprintln!("timeout"); std::process::exit(2) }); + let file = std::env::temp_dir().join(format!("rune-drag-out-{}.txt", std::process::id())); + std::fs::write(&file, "dragged out of a Rune window\n").unwrap(); + *FILE.lock().unwrap() = Some(file.clone()); + let (ready_tx, ready_rx) = std::sync::mpsc::channel(); + let app = App::new(AppSpec::new("drag out", (240.0, 120.0), || (), view)).args(Vec::new()) + .on_ready(move |_| { ready_tx.send(()).ok(); }); + let handle = app.handle(); + let result = std::sync::Arc::new(Mutex::new(None)); + let out = result.clone(); + let f = file.clone(); + std::thread::spawn(move || { + let run = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + ready_rx.recv_timeout(Duration::from_secs(30)).expect("window ready"); + if !drive(handle.clone(), f.clone()) { + // The live session's tracking loop holds the event loop, so quit can't land. + std::fs::remove_file(&f).ok(); + println!("macos_drag_out: ok (session start and pasteboard only)"); + std::process::exit(0); + } + })); + *out.lock().unwrap() = Some(run.is_ok()); + handle.quit(); + }); + app.run(); + std::fs::remove_file(&file).ok(); + assert_eq!(*result.lock().unwrap(), Some(true), "macos_drag_out failed"); + println!("macos_drag_out: ok"); + } +} diff --git a/app/vendor/rune/crates/rune/tests/macos_overlay_cursor.rs b/app/vendor/rune/crates/rune/tests/macos_overlay_cursor.rs new file mode 100644 index 0000000..b01acd3 --- /dev/null +++ b/app/vendor/rune/crates/rune/tests/macos_overlay_cursor.rs @@ -0,0 +1,201 @@ +//! `Cursor::Grab` over an overlay's hit region shows the open hand while another app is +//! frontmost and the overlay isn't key, with the `macos-background-cursor` feature. The overlay +//! takes input only on its hit regions (`OverlayInput::Regions`); a helper app holds the focus +//! (handed to it with CuaDriver when nothing yields). The overlay polls the real pointer, so the +//! test warps it (which moves the cursor but posts no events) and reads the window server's +//! cursor with `[NSCursor currentSystemCursor]`. Off the hit region it is the arrow again. +//! Fading out, the panel clicks through at once, for the whole fade. +//! Opens windows, so it only runs with RUNE_GUI_TESTS=1 in a logged-in GUI session. + +#[cfg(not(target_os = "macos"))] +fn main() {} + +#[cfg(target_os = "macos")] +mod macos_support; + +#[cfg(target_os = "macos")] +fn main() { mac::main() } + +#[cfg(target_os = "macos")] +#[allow(unsafe_code)] +mod mac { + use std::process::Command; + use std::sync::Mutex; + use std::time::Duration; + use objc2::{class, msg_send, rc::Retained, runtime::{AnyObject, Bool}}; + use objc2_foundation::{NSArray, NSPoint, NSSize}; + use rune::*; + use crate::macos_support::{activate_helper, app_active, frontmost_pid, on_main, wait, warp}; + + const HELPER: &str = "RUNE_OVERLAY_CURSOR_HELPER"; + /// Where the overlay goes, in points from the primary display's top-left. + const PANEL: [f32; 4] = [300.0, 300.0, 240.0, 120.0]; + /// The grabbable card inside it; the rest of the panel clicks through. + const CARD: [f32; 4] = [20.0, 20.0, 120.0, 80.0]; + + fn view<S>(_: &S, _: &mut Cx<S>) -> El { text("overlay cursor helper") } + + fn overlay_view(_: &(), _: &mut Cx<()>) -> El { + let [x, y, w, h] = CARD; + el().w_full().h_full().fill(Color::WHITE.alpha(0.3)).child( + el().key("card").absolute(x, y).size(w, h).radius(10.0) + .fill(rune::color::oklch(0.6, 0.18, 255.0)) + .hit() + .cursor(Cursor::Grab), + ) + } + + /// The panel with CGWindowID `number`: (key, ignores mouse events). + fn panel(number: u32) -> Option<(bool, bool)> { + // SAFETY: invoked on the AppKit main thread (`on_main`); queries live `NSWindow` properties. + unsafe { + let app: *mut AnyObject = msg_send![class!(NSApplication), sharedApplication]; + let windows: Retained<NSArray<AnyObject>> = msg_send![app, windows]; + windows.iter().find(|w| { let n: isize = msg_send![&**w, windowNumber]; n == number as isize }).map(|w| { + let key: Bool = msg_send![&*w, isKeyWindow]; + let ignores: Bool = msg_send![&*w, ignoresMouseEvents]; + (key.as_bool(), ignores.as_bool()) + }) + } + } + + /// A cursor's shape as far as the window server tells: (hot spot, image size). + type Shape = ((f64, f64), (f64, f64)); + + fn shape(cursor: *mut AnyObject) -> Option<Shape> { + if cursor.is_null() { return None } + // SAFETY: `cursor` is checked non-null and is a live `NSCursor` on the main thread; `image` is checked non-null before messaging. + unsafe { + let hot: NSPoint = msg_send![cursor, hotSpot]; + let image: *mut AnyObject = msg_send![cursor, image]; + if image.is_null() { return None } + let size: NSSize = msg_send![image, size]; + Some(((hot.x, hot.y), (size.width, size.height))) + } + } + + /// (the window server's current cursor, the open hand, the arrow). + fn shapes() -> (Option<Shape>, Shape, Shape) { + // SAFETY: standard `NSCursor` class getters called on the AppKit main thread (`on_main`). + unsafe { + let current: *mut AnyObject = msg_send![class!(NSCursor), currentSystemCursor]; + let hand: *mut AnyObject = msg_send![class!(NSCursor), openHandCursor]; + let arrow: *mut AnyObject = msg_send![class!(NSCursor), arrowCursor]; + (shape(current), shape(hand).expect("openHandCursor"), shape(arrow).expect("arrowCursor")) + } + } + + /// Waits for the window server's cursor to take `want`'s shape. + fn expect_cursor(handle: &AppHandle<()>, what: &str, want: impl Fn(Shape, Shape) -> Shape + Send + Copy + 'static) { + let start = rune::time::now(); + loop { + let (current, hand, arrow) = on_main(handle, shapes); + let want = want(hand, arrow); + if current == Some(want) { return } + assert!(start.elapsed() < Duration::from_secs(3), "{what}: the cursor is {current:?}, want {want:?} (open hand {hand:?}, arrow {arrow:?})"); + std::thread::sleep(Duration::from_millis(20)); + } + } + + fn drive(handle: &AppHandle<()>, overlay: &OverlayHandle<()>, pid: i32) { + let (_, hand, arrow) = on_main(handle, shapes); + assert_ne!(hand, arrow, "the open hand and the arrow need different shapes to tell them apart"); + wait("the overlay's panel", || overlay.window_number().is_some()); + let number = overlay.window_number().unwrap(); + activate_helper(handle, pid); + assert!(!on_main(handle, app_active), "the helper holds the focus"); + + let card = (f64::from(PANEL[0] + CARD[0] + CARD[2] / 2.0), f64::from(PANEL[1] + CARD[1] + CARD[3] / 2.0)); + let click_through = (f64::from(PANEL[0] + PANEL[2] - 20.0), f64::from(PANEL[1] + PANEL[3] - 10.0)); + let away = (f64::from(PANEL[0] + PANEL[2] + 200.0), f64::from(PANEL[1] + PANEL[3] + 200.0)); + + on_main(handle, move || warp(away)); + std::thread::sleep(Duration::from_millis(300)); + let (before, _, _) = on_main(handle, shapes); + assert_ne!(before, Some(hand), "the open hand before the pointer reaches the overlay"); + + on_main(handle, move || warp(card)); + expect_cursor(handle, "over the card", |hand, _| hand); + let (key, ignores) = on_main(handle, move || panel(number)).expect("the overlay panel is one of the app's windows"); + assert!(!key, "the overlay isn't key"); + assert!(!ignores, "the panel takes the pointer over its hit region"); + assert_eq!(on_main(handle, frontmost_pid), pid, "the helper is still frontmost"); + std::thread::sleep(Duration::from_millis(300)); + expect_cursor(handle, "still over the card", |hand, _| hand); + + on_main(handle, move || warp(click_through)); + expect_cursor(handle, "over the panel off its hit region", |_, arrow| arrow); + on_main(handle, move || warp(card)); + expect_cursor(handle, "back over the card", |hand, _| hand); + on_main(handle, move || warp(away)); + expect_cursor(handle, "off the overlay", |_, arrow| arrow); + assert_eq!(on_main(handle, frontmost_pid), pid, "the helper kept the front throughout"); + + // Fading out, the panel stops taking clicks at once, though it's still on screen. + on_main(handle, move || warp(card)); + expect_cursor(handle, "over the card before the fade", |hand, _| hand); + overlay.fade_out(Duration::from_secs(2)); + wait("the fading panel to click through", || on_main(handle, move || panel(number).is_some_and(|(_, ignores)| ignores))); + assert!(on_main(handle, move || ordered_in(number)), "checked while the fade runs, before the panel orders out"); + overlay.show(); + wait("the shown panel to take the pointer again", || on_main(handle, move || panel(number).is_some_and(|(_, ignores)| !ignores))); + } + + /// Whether the panel with CGWindowID `number` is still ordered in (a fade-out orders it out + /// when it ends). + fn ordered_in(number: u32) -> bool { + // SAFETY: invoked on the AppKit main thread (`on_main`); queries live `NSWindow` properties. + unsafe { + let app: *mut AnyObject = msg_send![class!(NSApplication), sharedApplication]; + let windows: Retained<NSArray<AnyObject>> = msg_send![app, windows]; + windows.iter().any(|w| { + let n: isize = msg_send![&*w, windowNumber]; + let visible: Bool = msg_send![&*w, isVisible]; + n == number as isize && visible.as_bool() + }) + } + } + + fn helper() { + std::thread::spawn(|| { std::thread::sleep(Duration::from_secs(60)); std::process::exit(0) }); + App::new(AppSpec::new("overlay cursor helper", (240.0, 80.0), || (), view)).args(Vec::new()).run(); + } + + pub fn main() { + if std::env::var_os(HELPER).is_some() { return helper() } + if std::env::var_os("RUNE_GUI_TESTS").is_none() { + println!("macos_overlay_cursor: skipped (set RUNE_GUI_TESTS=1 in a GUI session)"); + return; + } + std::thread::spawn(|| { std::thread::sleep(Duration::from_secs(60)); eprintln!("timeout"); std::process::exit(2) }); + let mut child = Command::new(std::env::current_exe().unwrap()).env(HELPER, "1").spawn().expect("helper"); + let pid = child.id() as i32; + let mut app = App::new(AppSpec::new("overlay cursor", (200.0, 100.0), || (), view)).args(Vec::new()) + .accessory().windowless(); + let [x, y, width, height] = PANEL; + let options = OverlayOptions { + placement: Some(OverlayPlacement::Rect { x, y, width, height }), + display: DisplayTarget::Primary, + input: OverlayInput::Regions, + ..Default::default() + }; + let overlay = app.overlay(OverlaySpec::new("overlay cursor", (width, height), overlay_view).options(options).macos_level(3), ()); + overlay.show(); + let handle = app.handle(); + let result = std::sync::Arc::new(Mutex::new(None)); + let out = result.clone(); + std::thread::spawn(move || { + let run = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + std::thread::sleep(Duration::from_millis(500)); + drive(&handle, &overlay, pid); + })); + *out.lock().unwrap() = Some(run.is_ok()); + handle.quit(); + }); + app.run(); + child.kill().ok(); + child.wait().ok(); + assert_eq!(*result.lock().unwrap(), Some(true), "macos_overlay_cursor failed"); + println!("macos_overlay_cursor: ok"); + } +} diff --git a/app/vendor/rune/crates/rune/tests/macos_overlay_drag_out.rs b/app/vendor/rune/crates/rune/tests/macos_overlay_drag_out.rs new file mode 100644 index 0000000..303088f --- /dev/null +++ b/app/vendor/rune/crates/rune/tests/macos_overlay_drag_out.rs @@ -0,0 +1,259 @@ +//! An `El::drag_out` element in an overlay starts an AppKit drag session: the overlay takes +//! input only on its hit regions (`OverlayInput::Regions`), never activates the app, and sits +//! at window level 3 (`.floating`). A press in the region and a drag past the threshold start +//! the session, write the file to the drag pasteboard, and show the drag image over the element +//! (its window-server window, read with `CGWindowListCopyWindowInfo`, where +//! `El::on_screen_layout` says the element is). With Accessibility access the test then posts a +//! real button release where the pointer is, over the panel: the app's own windows take no +//! drops, so the end arrives once, `Cancelled`, and the next click is an ordinary press. +//! Without it, it checks the session start, pasteboard and image only. +//! +//! The press and drag are `postEvent:` NSEvents. The overlay also polls the real pointer, so the +//! test warps it to where the drag goes; that moves the cursor but posts no events. Opens +//! windows, so it only runs with RUNE_GUI_TESTS=1 in a logged-in GUI session. + +#[cfg(not(target_os = "macos"))] +fn main() {} + +#[cfg(target_os = "macos")] +mod macos_support; + +#[cfg(target_os = "macos")] +fn main() { mac::main() } + +#[cfg(target_os = "macos")] +#[allow(unsafe_code)] +mod mac { + use std::sync::{Mutex, atomic::{AtomicUsize, Ordering}}; + use std::time::Duration; + use objc2::{class, msg_send, rc::Retained, runtime::{AnyObject, Bool}}; + use objc2_foundation::{NSArray, NSPoint, NSRect, NSString}; + use rune::*; + use crate::macos_support::{can_post_events, drag_pasteboard, on_main, release_real_button, wait, warp}; + + static PRESSES: AtomicUsize = AtomicUsize::new(0); + static STARTED: AtomicUsize = AtomicUsize::new(0); + static ENDED: Mutex<Vec<DragOutcome>> = Mutex::new(Vec::new()); + static FILE: Mutex<Option<std::path::PathBuf>> = Mutex::new(None); + /// The card's rect in global top-left points, from `on_screen_layout`. + static CARD: Mutex<Option<[f32; 4]>> = Mutex::new(None); + + /// Where the overlay goes, in points from the primary display's top-left. + const PANEL: [f32; 4] = [300.0, 300.0, 240.0, 120.0]; + /// The draggable card inside it. + const CARD_LOCAL: [f32; 4] = [20.0, 20.0, 120.0, 80.0]; + /// Where the press lands, in the card's points. + const PRESS: (f64, f64) = (40.0, 40.0); + /// Past the 4-point default threshold. + const TRAVEL: f64 = 6.0; + + fn window_view(_: &(), _: &mut Cx<()>) -> El { + el().w_full().h_full().fill(Color::WHITE) + } + + fn overlay_view(_: &(), _: &mut Cx<()>) -> El { + let [x, y, w, h] = CARD_LOCAL; + el().w_full().h_full().child( + el().key("card").absolute(x, y).size(w, h).radius(10.0) + .fill(rune::color::oklch(0.6, 0.18, 255.0)) + .hit() + .on_press(|_: &mut ()| { PRESSES.fetch_add(1, Ordering::SeqCst); }) + .drag_out(|_: &()| FILE.lock().unwrap().clone().map(|f| DragItem::new().file(f))) + .on_drag_start(|_: &mut (), _| { STARTED.fetch_add(1, Ordering::SeqCst); }) + .on_drag_end(|_: &mut (), outcome, _| ENDED.lock().unwrap().push(outcome)) + .on_screen_layout(|_: &mut (), r| *CARD.lock().unwrap() = Some(r)), + ) + } + + #[link(name = "CoreGraphics", kind = "framework")] + unsafe extern "C" { + fn CGWindowListCopyWindowInfo(option: u32, relative_to: u32) -> *mut std::ffi::c_void; + fn CGWindowLevelForKey(key: i32) -> i32; + fn CFRelease(object: *mut std::ffi::c_void); + } + + const DOWN: usize = 1; + const UP: usize = 2; + const DRAGGED: usize = 6; + const NONACTIVATING_PANEL: usize = 1 << 7; + const DRAGGING_LEVEL_KEY: i32 = 12; + const ON_SCREEN_ONLY: u32 = 1; + + /// The panel with CGWindowID `number`: (level, style mask, key, frame in AppKit points). + fn panel(number: u32) -> Option<(isize, usize, bool, NSRect)> { + // SAFETY: invoked on the AppKit main thread (`on_main`); queries live `NSWindow` properties. + unsafe { + let app: *mut AnyObject = msg_send![class!(NSApplication), sharedApplication]; + let windows: Retained<NSArray<AnyObject>> = msg_send![app, windows]; + windows.iter().find(|w| { let n: isize = msg_send![&**w, windowNumber]; n == number as isize }).map(|w| { + let key: Bool = msg_send![&*w, isKeyWindow]; + (msg_send![&*w, level], msg_send![&*w, styleMask], key.as_bool(), msg_send![&*w, frame]) + }) + } + } + + fn primary_height() -> f64 { + // SAFETY: called on the AppKit main thread; queries `NSScreen.screens` and the first screen's `frame`. + unsafe { + let screens: Retained<NSArray<AnyObject>> = msg_send![class!(NSScreen), screens]; + let frame: NSRect = msg_send![&*screens.iter().next().expect("a screen"), frame]; + frame.size.height + } + } + + /// Posts mouse events to window `number`: (NSEventType, global top-left point). + fn post(number: u32, events: &[(usize, (f64, f64))]) { + // SAFETY: invoked on the AppKit main thread (`on_main`); builds synthetic `NSEvent`s and posts them to `NSApplication`. + unsafe { + let app: *mut AnyObject = msg_send![class!(NSApplication), sharedApplication]; + let (_, _, _, frame) = panel(number).expect("the overlay panel"); + let flipped = primary_height(); + let info: *mut AnyObject = msg_send![class!(NSProcessInfo), processInfo]; + let now: f64 = msg_send![info, systemUptime]; + for &(kind, (x, y)) in events { + let at = NSPoint::new(x - frame.origin.x, flipped - y - frame.origin.y); + let event: *mut AnyObject = msg_send![class!(NSEvent), mouseEventWithType: kind, location: at, modifierFlags: 0usize, + timestamp: now, windowNumber: number as isize, context: std::ptr::null_mut::<AnyObject>(), eventNumber: 0isize, clickCount: 1isize, pressure: 1.0f32]; + let _: () = msg_send![app, postEvent: event, atStart: Bool::NO]; + } + } + } + + /// On-screen windows at the dragging level, `[x, y, w, h]` in global top-left points. + fn drag_windows() -> Vec<[f64; 4]> { + // SAFETY: `CGWindowListCopyWindowInfo` returns a newly retained `CFArray` (checked non-null + // and released with `CFRelease`); each element index is `< count` and dictionary values are null-checked. + unsafe { + let level = CGWindowLevelForKey(DRAGGING_LEVEL_KEY); + let list = CGWindowListCopyWindowInfo(ON_SCREEN_ONLY, 0); + if list.is_null() { return Vec::new(); } + let array = list.cast::<AnyObject>(); + let key = |s: &str| NSString::from_str(s); + let count: usize = msg_send![array, count]; + let mut out = Vec::new(); + for i in 0..count { + let info: *mut AnyObject = msg_send![array, objectAtIndex: i]; + let layer: *mut AnyObject = msg_send![info, objectForKey: &*key("kCGWindowLayer")]; + if layer.is_null() { continue; } + let layer: i32 = msg_send![layer, intValue]; + if layer != level { continue; } + let bounds: *mut AnyObject = msg_send![info, objectForKey: &*key("kCGWindowBounds")]; + if bounds.is_null() { continue; } + let get = |k: &str| -> f64 { + let n: *mut AnyObject = msg_send![bounds, objectForKey: &*key(k)]; + if n.is_null() { f64::NAN } else { msg_send![n, doubleValue] } + }; + out.push([get("X"), get("Y"), get("Width"), get("Height")]); + } + CFRelease(list); + out + } + } + + /// Whether the session ended (it can't without Accessibility access to post a release). + fn drive(handle: AppHandle<()>, overlay: OverlayHandle<()>, file: std::path::PathBuf) -> bool { + wait("the overlay's panel", || overlay.window_number().is_some()); + let number = overlay.window_number().unwrap(); + let expected = [PANEL[0] + CARD_LOCAL[0], PANEL[1] + CARD_LOCAL[1], CARD_LOCAL[2], CARD_LOCAL[3]]; + wait("the card's screen rect", || *CARD.lock().unwrap() == Some(expected)); + std::thread::sleep(Duration::from_millis(300)); + let (level, style, key, _) = on_main(&handle, move || panel(number)).expect("the overlay panel is one of the app's windows"); + assert_eq!(level, 3, "the overlay sits at the floating level"); + assert!(style & NONACTIVATING_PANEL != 0, "a non-activating panel"); + assert!(!key, "showing the overlay didn't make it key"); + + let [cx, cy, cw, ch] = expected.map(f64::from); + let press = (cx + PRESS.0, cy + PRESS.1); + let past = (press.0 + TRAVEL, press.1); + on_main(&handle, move || { + // The polled pointer agrees with the posted drag; the session follows it. + warp(past); + post(number, &[(DOWN, press), (DRAGGED, (press.0 + TRAVEL / 2.0, press.1)), (DRAGGED, past)]); + }); + wait("on_drag_start", || STARTED.load(Ordering::SeqCst) == 1); + + let name = file.file_name().unwrap().to_str().unwrap().to_owned(); + let mut url = None; + for _ in 0..50 { + url = on_main(&handle, || drag_pasteboard().0); + if url.as_deref().is_some_and(|u| u.ends_with(&name)) { break; } + std::thread::sleep(Duration::from_millis(100)); + } + let url = url.expect("the session started and wrote the drag pasteboard"); + assert!(url.starts_with("file://") && url.ends_with(&name), "file URL {url}"); + + // The image is the card's snapshot, laid exactly over the card when the session starts; + // it then follows the pointer from the event that started it, at most `TRAVEL` away. + let mut image = None; + for _ in 0..100 { + let windows = drag_windows(); + image = windows.into_iter().find(|w| (w[2] - cw).abs() <= 2.0 && (w[3] - ch).abs() <= 2.0); + if image.is_some() { break; } + std::thread::sleep(Duration::from_millis(20)); + } + let image = image.unwrap_or_else(|| panic!("no card-sized window at the dragging level: {:?}", drag_windows())); + assert!((image[0] - cx).abs() <= TRAVEL + 1.0 && (image[1] - cy).abs() <= 1.0, + "the drag image {image:?} sits over the card {expected:?}"); + assert_eq!(PRESSES.load(Ordering::SeqCst), 0, "a drag-out isn't a press"); + + if ENDED.lock().unwrap().is_empty() { + if !can_post_events() { + println!("macos_overlay_drag_out: session started, image {image:?}, pasteboard {url}; ending it needs a real button release, which this process may not post (no Accessibility access)"); + return false; + } + release_real_button(); + } + // A drop the app refuses slides the image back before the session ends. + wait("the drag to end", || !ENDED.lock().unwrap().is_empty()); + std::thread::sleep(Duration::from_millis(200)); + assert_eq!(*ENDED.lock().unwrap(), [DragOutcome::Cancelled], "dropped back on the panel: cancelled, reported once"); + on_main(&handle, move || post(number, &[(DOWN, press), (UP, press)])); + wait("a click after the drag to press", || PRESSES.load(Ordering::SeqCst) == 1); + println!("macos_overlay_drag_out: session ended {:?}, image {image:?}, pasteboard {url}", ENDED.lock().unwrap()[0]); + true + } + + pub fn main() { + if std::env::var_os("RUNE_GUI_TESTS").is_none() { + println!("macos_overlay_drag_out: skipped (set RUNE_GUI_TESTS=1 in a GUI session)"); + return; + } + std::thread::spawn(|| { std::thread::sleep(Duration::from_secs(60)); eprintln!("timeout"); std::process::exit(2) }); + let file = std::env::temp_dir().join(format!("rune-overlay-drag-out-{}.txt", std::process::id())); + std::fs::write(&file, "dragged out of a Rune overlay\n").unwrap(); + *FILE.lock().unwrap() = Some(file.clone()); + let (ready_tx, ready_rx) = std::sync::mpsc::channel(); + let mut app = App::new(AppSpec::new("overlay drag out", (200.0, 100.0), || (), window_view)).args(Vec::new()) + .on_ready(move |_| { ready_tx.send(()).ok(); }); + let [x, y, width, height] = PANEL; + let options = OverlayOptions { + placement: Some(OverlayPlacement::Rect { x, y, width, height }), + display: DisplayTarget::Primary, + input: OverlayInput::Regions, + ..Default::default() + }; + let overlay = app.overlay(OverlaySpec::new("overlay drag out", (width, height), overlay_view).options(options).macos_level(3), ()); + overlay.show(); + let handle = app.handle(); + let result = std::sync::Arc::new(Mutex::new(None)); + let out = result.clone(); + let f = file.clone(); + std::thread::spawn(move || { + let run = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + ready_rx.recv_timeout(Duration::from_secs(30)).expect("window ready"); + if !drive(handle.clone(), overlay.clone(), f.clone()) { + // The live session's tracking loop holds the event loop, so quit can't land. + std::fs::remove_file(&f).ok(); + println!("macos_overlay_drag_out: ok (session start, image and pasteboard only)"); + std::process::exit(0); + } + })); + *out.lock().unwrap() = Some(run.is_ok()); + handle.quit(); + }); + app.run(); + std::fs::remove_file(&file).ok(); + assert_eq!(*result.lock().unwrap(), Some(true), "macos_overlay_drag_out failed"); + println!("macos_overlay_drag_out: ok"); + } +} diff --git a/app/vendor/rune/crates/rune/tests/macos_overlay_source.rs b/app/vendor/rune/crates/rune/tests/macos_overlay_source.rs new file mode 100644 index 0000000..f581464 --- /dev/null +++ b/app/vendor/rune/crates/rune/tests/macos_overlay_source.rs @@ -0,0 +1,452 @@ +//! An overlay or launcher panel keeps winit's view, and its clicks, when AppKit or another +//! framework restyles the hidden winit window behind it. ScreenCaptureKit does exactly that: +//! ReplayKit's `setWindowRotationLocked:` calls `setStyleMask:` on the first window in +//! `NSApp.windows`. Also checks that restyling leaves the launcher panel's frame and level +//! alone, that the source keeps its KVO class, and that a panel whose view was taken anyway +//! gets it back. Opens windows, so it only runs with RUNE_GUI_TESTS=1 in a +//! logged-in GUI session. Clicks are synthesized with `postEvent:`; the real pointer never moves. + +#![allow(unsafe_code)] + +#[cfg(not(target_os = "macos"))] +fn main() {} + +#[cfg(target_os = "macos")] +fn main() { mac::main() } + +#[cfg(target_os = "macos")] +mod mac { + use std::sync::{Mutex, atomic::{AtomicBool, AtomicUsize, Ordering}}; + use std::time::Duration; + use objc2::{class, msg_send, sel, runtime::{AnyClass, AnyObject, Bool, ClassBuilder, Sel}}; + use objc2_foundation::{NSPoint, NSRect, NSSize}; + + #[link(name = "ReplayKit", kind = "framework")] + unsafe extern "C" {} + unsafe extern "C" { + fn object_getClass(object: *const AnyObject) -> *const AnyClass; + fn class_getSuperclass(class: *const AnyClass) -> *const AnyClass; + fn class_copyMethodList(class: *const AnyClass, count: *mut u32) -> *mut *const std::ffi::c_void; + fn method_getName(method: *const std::ffi::c_void) -> objc2::runtime::Sel; + fn free(pointer: *mut std::ffi::c_void); + } + + static CLICKS: AtomicUsize = AtomicUsize::new(0); + static CREATED: AtomicBool = AtomicBool::new(false); + static TITLE_CHANGES: AtomicUsize = AtomicUsize::new(0); + static FAILURES: Mutex<Vec<String>> = Mutex::new(Vec::new()); + + const TITLED: usize = 1 << 0; + const RESIZABLE: usize = 1 << 3; + const FULL_SIZE_CONTENT: usize = 1 << 15; + + #[derive(Clone, Copy)] + struct Pair { source: usize, panel: usize, view: usize, overlay: bool } + + fn fail(message: String) { + eprintln!("FAIL {message}"); + FAILURES.lock().unwrap().push(message); + } + + fn class_name(class: *const AnyClass) -> String { + if class.is_null() { + "NULL".into() + } else { + // SAFETY: `class` is checked non-null and points to a valid Objective-C class metadata object. + unsafe { (*class).name().to_string_lossy().into_owned() } + } + } + + fn windows() -> Vec<*mut AnyObject> { + // SAFETY: invoked on the AppKit main thread; each `i` is `< count` in `NSApp.windows`. + unsafe { + let app: *mut AnyObject = msg_send![class!(NSApplication), sharedApplication]; + let windows: *mut AnyObject = msg_send![app, windows]; + let count: usize = msg_send![windows, count]; + (0..count).map(|i| msg_send![windows, objectAtIndex: i]).collect() + } + } + + /// Hidden winit windows whose view Rune moved into a panel, found through winit's + /// delegate (which owns the view) rather than any Rune internals. + fn pairs() -> Vec<Pair> { + let mut pairs = Vec::new(); + for window in windows() { + // SAFETY: invoked on the AppKit main thread; `window` is a live `NSWindow` from `NSApp.windows`. + unsafe { + let name = class_name(object_getClass(window)); + let reported: *const AnyClass = msg_send![window, class]; + let mask: usize = msg_send![window, styleMask]; + let real: *mut AnyObject = msg_send![super(window, class!(NSWindow)), contentView]; + println!("window isa={name} class={} mask={mask:#x} realContentView={real:?}", class_name(reported)); + if reported.is_null() { fail(format!("-[{name} class] returned NULL")); } + if name != "RuneOverlayPanel" { continue; } + let view: *mut AnyObject = msg_send![window, contentView]; + let delegate: *mut AnyObject = msg_send![window, delegate]; + let source = windows().into_iter().find(|w| { + let d: *mut AnyObject = msg_send![*w, delegate]; + *w != window && d == delegate + }); + let Some(source) = source else { fail("panel without a winit source window".into()); continue }; + let level: isize = msg_send![window, level]; + pairs.push(Pair { source: source as usize, panel: window as usize, view: view as usize, overlay: level >= 25 }); + } + } + pairs + } + + fn kvo_report(source: *mut AnyObject) { + // SAFETY: `source` is a live `NSWindow` on the main thread; `class_copyMethodList` allocates + // `count` entries that are read within bounds and freed once with `free`. + unsafe { + let mut class = object_getClass(source); + while !class.is_null() { + let name = class_name(class); + if name.starts_with("NSKVONotifying_") { + let mut count = 0; + let list = class_copyMethodList(class, &mut count); + let methods: Vec<String> = (0..count as usize).map(|i| method_getName(*list.add(i)).name().to_string_lossy().into_owned()).collect(); + free(list.cast()); + println!("kvo class {name} overrides {methods:?}"); + } + if name == "NSWindow" { break; } + class = class_getSuperclass(class); + } + } + } + + fn check(pair: Pair, path: &str) { + // SAFETY: invoked on the AppKit main thread; `pair.panel` and `pair.view` are live AppKit objects from `pairs()`. + unsafe { + let (panel, view) = (pair.panel as *mut AnyObject, pair.view as *mut AnyObject); + let content: *mut AnyObject = msg_send![panel, contentView]; + let window: *mut AnyObject = msg_send![view, window]; + if content != view || window != panel { + fail(format!("{path}: {} panel lost its view (contentView={content:?} view.window={window:?})", if pair.overlay { "overlay" } else { "launcher" })); + } + } + } + + fn click(panel: *mut AnyObject) { + // SAFETY: invoked on the AppKit main thread; `panel` is a live `NSWindow` and synthetic `NSEvent`s are posted to `NSApplication`. + unsafe { + let frame: NSRect = msg_send![panel, frame]; + let at = NSPoint::new(frame.size.width / 2.0, frame.size.height / 2.0); + let number: isize = msg_send![panel, windowNumber]; + let info: *mut AnyObject = msg_send![class!(NSProcessInfo), processInfo]; + let now: f64 = msg_send![info, systemUptime]; + let app: *mut AnyObject = msg_send![class!(NSApplication), sharedApplication]; + for kind in [1usize, 2] { + let event: *mut AnyObject = msg_send![class!(NSEvent), mouseEventWithType: kind, location: at, modifierFlags: 0usize, + timestamp: now, windowNumber: number, context: std::ptr::null_mut::<AnyObject>(), eventNumber: 0isize, clickCount: 1isize, pressure: 1.0f32]; + let _: () = msg_send![app, postEvent: event, atStart: Bool::NO]; + } + } + } + + /// AppKit calls that restyle a window or replace its content, made on the hidden source + /// window the way an unrelated framework would. + fn paths() -> Vec<(&'static str, Box<dyn Fn(*mut AnyObject)>)> { + unsafe fn mask(w: *mut AnyObject) -> usize { + // SAFETY: caller passes a live `NSWindow` on the AppKit main thread. + unsafe { msg_send![w, styleMask] } + } + unsafe fn set(w: *mut AnyObject, m: usize) { + // SAFETY: caller passes a live `NSWindow` on the AppKit main thread. + unsafe { let _: () = msg_send![w, setStyleMask: m]; } + } + vec![ + ("setStyleMask: (same)", Box::new(|w| { + // SAFETY: called on the AppKit main thread with a live source `NSWindow`. + unsafe { set(w, mask(w)) } + })), + ("setStyleMask: (resizable)", Box::new(|w| { + // SAFETY: called on the AppKit main thread with a live source `NSWindow`. + unsafe { let m = mask(w); set(w, m ^ RESIZABLE); set(w, m) } + })), + ("setStyleMask: (titled)", Box::new(|w| { + // SAFETY: called on the AppKit main thread with a live source `NSWindow`. + unsafe { let m = mask(w); set(w, m ^ TITLED); set(w, m) } + })), + ("setStyleMask: (full size content)", Box::new(|w| { + // SAFETY: called on the AppKit main thread with a live source `NSWindow`. + unsafe { let m = mask(w); set(w, m ^ FULL_SIZE_CONTENT); set(w, m) } + })), + ("setTitlebarAppearsTransparent:", Box::new(|w| { + // SAFETY: called on the AppKit main thread with a live source `NSWindow`. + unsafe { + let t: Bool = msg_send![w, titlebarAppearsTransparent]; + let _: () = msg_send![w, setTitlebarAppearsTransparent: Bool::new(!t.as_bool())]; + let _: () = msg_send![w, setTitlebarAppearsTransparent: t]; + } + })), + ("setTitleVisibility:", Box::new(|w| { + // SAFETY: called on the AppKit main thread with a live source `NSWindow`. + unsafe { + let v: isize = msg_send![w, titleVisibility]; + let _: () = msg_send![w, setTitleVisibility: 1 - v]; + let _: () = msg_send![w, setTitleVisibility: v]; + } + })), + ("setToolbar:", Box::new(|w| { + // SAFETY: called on the AppKit main thread with a live source `NSWindow`; releases the temporary `NSToolbar`. + unsafe { + let toolbar: *mut AnyObject = msg_send![class!(NSToolbar), new]; + let _: () = msg_send![w, setToolbar: toolbar]; + let _: () = msg_send![w, setToolbar: std::ptr::null_mut::<AnyObject>()]; + let _: () = msg_send![toolbar, release]; + } + })), + ("setContentSize:", Box::new(|w| { + // SAFETY: called on the AppKit main thread with a live source `NSWindow`. + unsafe { + let frame: NSRect = msg_send![w, frame]; + let _: () = msg_send![w, setContentSize: NSSize::new(frame.size.width + 7.0, frame.size.height + 5.0)]; + let _: () = msg_send![w, setContentSize: frame.size]; + } + })), + ("setFrame:display:", Box::new(|w| { + // SAFETY: called on the AppKit main thread with a live source `NSWindow`. + unsafe { + let frame: NSRect = msg_send![w, frame]; + let _: () = msg_send![w, setFrame: NSRect::new(frame.origin, NSSize::new(frame.size.width + 9.0, frame.size.height + 3.0)), display: Bool::YES]; + let _: () = msg_send![w, setFrame: frame, display: Bool::YES]; + } + })), + ("setContentView:", Box::new(|w| { + // SAFETY: called on the AppKit main thread with a live source `NSWindow`; releases the temporary `NSView`. + unsafe { + let view: *mut AnyObject = msg_send![class!(NSView), new]; + let _: () = msg_send![w, setContentView: view]; + let _: () = msg_send![w, setContentView: std::ptr::null_mut::<AnyObject>()]; + let _: () = msg_send![view, release]; + } + })), + ("setAppearance:", Box::new(|w| { + // SAFETY: called on the AppKit main thread with a live source `NSWindow`. + unsafe { + let name = objc2_foundation::NSString::from_str("NSAppearanceNameDarkAqua"); + let dark: *mut AnyObject = msg_send![class!(NSAppearance), appearanceNamed: &*name]; + let _: () = msg_send![w, setAppearance: dark]; + let _: () = msg_send![w, setAppearance: std::ptr::null_mut::<AnyObject>()]; + } + })), + ("displayIfNeeded", Box::new(|w| { + // SAFETY: called on the AppKit main thread with a live source `NSWindow`. + unsafe { let _: () = msg_send![w, displayIfNeeded]; let _: () = msg_send![w, layoutIfNeeded]; } + })), + ] + } + + /// An NSObject that counts KVO notifications. + fn observer_class() -> &'static AnyClass { + static CLASS: std::sync::OnceLock<usize> = std::sync::OnceLock::new(); + extern "C" fn observe(_: *mut AnyObject, _: Sel, _: *mut AnyObject, _: *mut AnyObject, _: *mut AnyObject, _: *mut std::ffi::c_void) { + TITLE_CHANGES.fetch_add(1, Ordering::SeqCst); + } + let class = *CLASS.get_or_init(|| { + let mut builder = ClassBuilder::new(c"RuneOverlaySourceTitleObserver", class!(NSObject)).unwrap(); + // SAFETY: `observe` matches the Objective-C ABI for `observeValueForKeyPath:ofObject:change:context:`. + unsafe { + builder.add_method(sel!(observeValueForKeyPath:ofObject:change:context:), + observe as extern "C" fn(*mut AnyObject, Sel, *mut AnyObject, *mut AnyObject, *mut AnyObject, *mut std::ffi::c_void)); + } + builder.register() as *const AnyClass as usize + }); + // SAFETY: `class` is the `'static` Objective-C class returned by `ClassBuilder::register`. + unsafe { &*(class as *const AnyClass) } + } + + fn rotation_lock(lock: bool) -> bool { + // SAFETY: invoked on the AppKit main thread; guards `setWindowRotationLocked:` with `respondsToSelector:`. + unsafe { + let recorder: *mut AnyObject = msg_send![class!(RPScreenRecorder), sharedRecorder]; + let responds: Bool = msg_send![recorder, respondsToSelector: sel!(setWindowRotationLocked:)]; + if responds.as_bool() { let _: () = msg_send![recorder, setWindowRotationLocked: Bool::new(lock)]; } + responds.as_bool() + } + } + + fn view(_: &(), _: &mut rune::Cx<()>) -> rune::El { + rune::el().w_full().h_full().hit().on_press(|_: &mut ()| { CLICKS.fetch_add(1, Ordering::SeqCst); }) + } + + fn on_main(handle: &rune::AppHandle<()>, f: impl FnOnce() + Send + 'static) { + let (tx, rx) = std::sync::mpsc::channel(); + handle.update(move |_, _| { f(); tx.send(()).ok(); }); + rx.recv_timeout(Duration::from_secs(10)).expect("event thread stalled"); + } + + fn expect_click(handle: &rune::AppHandle<()>, overlay: Pair, path: &str) { + let before = CLICKS.load(Ordering::SeqCst); + on_main(handle, move || click(overlay.panel as *mut AnyObject)); + for _ in 0..100 { + if CLICKS.load(Ordering::SeqCst) > before { return; } + std::thread::sleep(Duration::from_millis(10)); + } + fail(format!("{path}: overlay click was dropped")); + } + + fn drive(handle: rune::AppHandle<()>) { + for _ in 0..200 { + if CREATED.load(Ordering::SeqCst) { break; } + std::thread::sleep(Duration::from_millis(100)); + } + assert!(CREATED.load(Ordering::SeqCst), "overlay was not created"); + std::thread::sleep(Duration::from_millis(500)); + let (tx, rx) = std::sync::mpsc::channel(); + handle.update(move |_, _| { tx.send(pairs()).ok(); }); + let pairs = rx.recv_timeout(Duration::from_secs(10)).unwrap(); + assert!(pairs.iter().any(|p| p.overlay) && pairs.iter().any(|p| !p.overlay), "expected an overlay and a launcher panel"); + let overlay = *pairs.iter().find(|p| p.overlay).unwrap(); + on_main(&handle, move || kvo_report(overlay.source as *mut AnyObject)); + expect_click(&handle, overlay, "baseline"); + // None of the restyles below may take the view: a panel quietly taking it back would + // hide that. + let reattached = rune::macos_panel_bridge::reattach_count(); + + for (index, (path, _)) in paths().into_iter().enumerate() { + let (pairs, again) = (pairs.clone(), pairs.clone()); + on_main(&handle, move || { + let apply = &paths()[index].1; + // These two are this binary resizing a launcher, which winit's calls do. + let resizes = matches!(path, "setContentSize:" | "setFrame:display:"); + for pair in &pairs { + let panel = pair.panel as *mut AnyObject; + // SAFETY: invoked on the AppKit main thread (`on_main`); `panel` is a live `NSWindow`. + let (frame, level): (NSRect, isize) = unsafe { (msg_send![panel, frame], msg_send![panel, level]) }; + apply(pair.source as *mut AnyObject); + check(*pair, path); + // SAFETY: invoked on the AppKit main thread (`on_main`); `panel` is still a live `NSWindow`. + let (after, after_level): (NSRect, isize) = unsafe { (msg_send![panel, frame], msg_send![panel, level]) }; + if !resizes && (after != frame || after_level != level) { + fail(format!("{path}: restyling the source moved the panel ({frame:?} level {level} -> {after:?} level {after_level})")); + } + } + }); + expect_click(&handle, overlay, path); + on_main(&handle, move || { + // Reattach for the next path so each failure is reported on its own. + // SAFETY: invoked on the AppKit main thread (`on_main`); each `pair.panel` and `pair.view` is live. + unsafe { + for pair in &again { + let content: *mut AnyObject = msg_send![pair.panel as *mut AnyObject, contentView]; + if content != pair.view as *mut AnyObject { let _: () = msg_send![pair.panel as *mut AnyObject, setContentView: pair.view as *mut AnyObject]; } + } + } + }); + } + + let (tx, rx) = std::sync::mpsc::channel(); + handle.update(move |_, _| { tx.send(rotation_lock(true)).ok(); }); + if rx.recv_timeout(Duration::from_secs(10)).unwrap() { + // ReplayKit restyles on a later main-queue turn. + std::thread::sleep(Duration::from_millis(300)); + on_main(&handle, move || { rotation_lock(false); }); + std::thread::sleep(Duration::from_millis(300)); + let pairs = pairs.clone(); + on_main(&handle, move || for pair in &pairs { check(*pair, "RPScreenRecorder setWindowRotationLocked:"); }); + expect_click(&handle, overlay, "RPScreenRecorder setWindowRotationLocked:"); + } else { + println!("RPScreenRecorder has no setWindowRotationLocked: on this macOS"); + } + let taken = rune::macos_panel_bridge::reattach_count() - reattached; + if taken != 0 { fail(format!("restyles took the view {taken} times; the panels took it back")); } + + // KVO keeps working on the source: with a title observer attached, `-class` still + // reports winit's class, and the setter override KVO adds still reaches the panel + // and keeps the source's own title, which winit's `title()` reads. + let pairs_kvo = pairs.clone(); + on_main(&handle, move || { + // SAFETY: invoked on the AppKit main thread (`on_main`); adds and removes a KVO observer + // on live source windows and releases the observer before returning. + unsafe { + let observer: *mut AnyObject = msg_send![observer_class(), new]; + let key = objc2_foundation::NSString::from_str("title"); + for pair in &pairs_kvo { + let _: () = msg_send![pair.source as *mut AnyObject, addObserver: observer, forKeyPath: &*key, options: 0usize, context: std::ptr::null_mut::<std::ffi::c_void>()]; + } + for pair in &pairs_kvo { + let source = pair.source as *mut AnyObject; + let reported: *const AnyClass = msg_send![source, class]; + if class_name(reported) != "WinitWindow" { fail(format!("-class with a KVO observer: {}", class_name(reported))); } + if !pair.overlay { + let before = TITLE_CHANGES.load(Ordering::SeqCst); + let title = objc2_foundation::NSString::from_str("retitled"); + let _: () = msg_send![source, setTitle: &*title]; + for (window, name) in [(pair.panel as *mut AnyObject, "panel"), (source, "source")] { + let shown: *mut AnyObject = msg_send![window, title]; + let equal: Bool = msg_send![shown, isEqualToString: &*title]; + if !equal.as_bool() { fail(format!("launcher setTitle: under KVO didn't reach the {name}")); } + } + if TITLE_CHANGES.load(Ordering::SeqCst) == before { fail("the title observer was never notified".into()); } + } + } + for pair in &pairs_kvo { + let _: () = msg_send![pair.source as *mut AnyObject, removeObserver: observer, forKeyPath: &*key]; + } + let _: () = msg_send![observer, release]; + } + }); + + // Anything else that takes the view: the panel takes it back on the next event-loop + // turn or input, and the click still lands. + let before = CLICKS.load(Ordering::SeqCst); + on_main(&handle, move || { + // SAFETY: invoked on the AppKit main thread (`on_main`); detaches the live overlay view before posting a click. + unsafe { + let _: () = msg_send![overlay.view as *mut AnyObject, removeFromSuperview]; + click(overlay.panel as *mut AnyObject); + } + }); + for _ in 0..100 { + if CLICKS.load(Ordering::SeqCst) > before { break; } + std::thread::sleep(Duration::from_millis(10)); + } + if CLICKS.load(Ordering::SeqCst) == before { fail("detached view: overlay click was dropped".into()); } + on_main(&handle, move || check(overlay, "detached view")); + expect_click(&handle, overlay, "after reattaching"); + let launcher = *pairs.iter().find(|p| !p.overlay).unwrap(); + on_main(&handle, move || { + // SAFETY: invoked on the AppKit main thread (`on_main`); `launcher.view` is a live `NSView`. + unsafe { let _: () = msg_send![launcher.view as *mut AnyObject, removeFromSuperview]; } + }); + handle.open(); + std::thread::sleep(Duration::from_millis(300)); + on_main(&handle, move || check(launcher, "detached launcher view, then open")); + // Synthesized clicks don't reach a launcher's view here, so only check that input + // brings the view back. + on_main(&handle, move || { + // SAFETY: invoked on the AppKit main thread (`on_main`); detaches the live launcher view before posting a click. + unsafe { + let _: () = msg_send![launcher.view as *mut AnyObject, removeFromSuperview]; + click(launcher.panel as *mut AnyObject); + } + }); + std::thread::sleep(Duration::from_millis(200)); + on_main(&handle, move || check(launcher, "detached launcher view, then click")); + handle.hide(); + + let failures = FAILURES.lock().unwrap(); + println!("clicks={} failures={}", CLICKS.load(Ordering::SeqCst), failures.len()); + std::process::exit(if failures.is_empty() { 0 } else { 1 }); + } + + pub fn main() { + if std::env::var_os("RUNE_GUI_TESTS").is_none() { + println!("macos_overlay_source: skipped (set RUNE_GUI_TESTS=1 in a GUI session)"); + return; + } + std::thread::spawn(|| { std::thread::sleep(Duration::from_secs(60)); eprintln!("timeout"); std::process::exit(2) }); + let spec = rune::AppSpec::new("overlay source", (240.0, 80.0), || (), view); + let mut app = rune::App::new(spec).args(Vec::new()).keep_running() + .configured_options(rune::WindowOptions::launcher_panel()); + let handle = app.handle(); + let options = rune::OverlayOptions { input: rune::OverlayInput::Regions, ..Default::default() }; + let overlay = app.overlay(rune::OverlaySpec::new("overlay source overlay", (200.0, 80.0), view).options(options) + .on_created(|_| CREATED.store(true, Ordering::SeqCst)), ()); + overlay.show(); + std::thread::spawn(move || drive(handle)); + app.run(); + } +} diff --git a/app/vendor/rune/crates/rune/tests/macos_support/mod.rs b/app/vendor/rune/crates/rune/tests/macos_support/mod.rs new file mode 100644 index 0000000..9423495 --- /dev/null +++ b/app/vendor/rune/crates/rune/tests/macos_support/mod.rs @@ -0,0 +1,141 @@ +#![allow(dead_code)] +#![allow(unsafe_code)] + +use std::process::Command; +use std::time::Duration; +use objc2::{class, msg_send, rc::Retained, runtime::{AnyObject, Bool}}; +use objc2_foundation::{NSArray, NSPoint, NSString}; +use rune::AppHandle; + +pub const CUA_DRIVER: &str = "/Applications/CuaDriver.app/Contents/MacOS/cua-driver"; + +#[link(name = "CoreGraphics", kind = "framework")] +unsafe extern "C" { + fn CGWarpMouseCursorPosition(point: NSPoint) -> i32; + fn CGEventCreate(source: *const std::ffi::c_void) -> *mut std::ffi::c_void; + fn CGEventGetLocation(event: *mut std::ffi::c_void) -> NSPoint; + fn CGEventCreateMouseEvent( + source: *const std::ffi::c_void, + kind: u32, + at: NSPoint, + button: u32, + ) -> *mut std::ffi::c_void; + fn CGEventPost(tap: u32, event: *mut std::ffi::c_void); + fn CGPreflightPostEventAccess() -> bool; + fn CFRelease(object: *mut std::ffi::c_void); +} + +pub fn on_main<S: 'static, T: Send + 'static>(handle: &AppHandle<S>, f: impl FnOnce() -> T + Send + 'static) -> T { + let (tx, rx) = std::sync::mpsc::channel(); + handle.update(move |_, _| { + tx.send(f()).ok(); + }); + rx.recv_timeout(Duration::from_secs(10)).expect("event thread stalled") +} + +pub fn wait(what: &str, f: impl Fn() -> bool) { + let start = rune::time::now(); + while !f() { + assert!(start.elapsed() < Duration::from_secs(10), "timed out waiting for {what}"); + std::thread::sleep(Duration::from_millis(10)); + } +} + +pub fn warp((x, y): (f64, f64)) { + // SAFETY: `CGWarpMouseCursorPosition` takes a plain `NSPoint` by value. + unsafe { + CGWarpMouseCursorPosition(NSPoint::new(x, y)); + } +} + +pub fn can_post_events() -> bool { + // SAFETY: `CGPreflightPostEventAccess` takes no arguments and has no preconditions. + unsafe { CGPreflightPostEventAccess() } +} + +/// AppKit tracks a running session from the window server, which never saw the posted press; a +/// real left-button release where the pointer is ends it. +pub fn release_real_button() { + // SAFETY: creates temporary CoreGraphics events with null source, reads/posts them, and releases each once. + unsafe { + let here = CGEventCreate(std::ptr::null()); + let at = CGEventGetLocation(here); + CFRelease(here); + let up = CGEventCreateMouseEvent(std::ptr::null(), 2, at, 0); + CGEventPost(0, up); + CFRelease(up); + } +} + +/// The drag pasteboard's first item: its file URL, and the path list Finder also reads. +pub fn drag_pasteboard() -> (Option<String>, Option<String>) { + // SAFETY: invoked on the AppKit main thread (`on_main`); reads standard drag pasteboard types. + unsafe { + let name = NSString::from_str("Apple CFPasteboard drag"); + let board: *mut AnyObject = msg_send![class!(NSPasteboard), pasteboardWithName: &*name]; + let url: Option<Retained<NSString>> = msg_send![board, stringForType: &*NSString::from_str("public.file-url")]; + let names: Option<Retained<NSArray<NSString>>> = + msg_send![board, propertyListForType: &*NSString::from_str("NSFilenamesPboardType")]; + (url.map(|u| u.to_string()), names.and_then(|n| n.iter().next().map(|s| s.to_string()))) + } +} + +pub fn app_active() -> bool { + // SAFETY: invoked on the AppKit main thread (`on_main`); queries `NSApplication.isActive`. + unsafe { + let app: *mut AnyObject = msg_send![class!(NSApplication), sharedApplication]; + let active: Bool = msg_send![app, isActive]; + active.as_bool() + } +} + +pub fn frontmost_pid() -> i32 { + // SAFETY: invoked on the AppKit main thread (`on_main`); `app` is checked non-null before querying `processIdentifier`. + unsafe { + let workspace: *mut AnyObject = msg_send![class!(NSWorkspace), sharedWorkspace]; + let app: *mut AnyObject = msg_send![workspace, frontmostApplication]; + if app.is_null() { + return 0; + } + msg_send![app, processIdentifier] + } +} + +/// Hands the focus to the helper. macOS only lets the active app pass activation on, so when +/// nobody yields this falls back to CuaDriver's `bring_to_front`. +pub fn activate_helper(handle: &AppHandle<()>, pid: i32) { + wait("the helper to launch", || { + on_main(handle, move || { + // SAFETY: invoked on the AppKit main thread (`on_main`); `app` is checked non-null before querying `isFinishedLaunching`. + unsafe { + let app: *mut AnyObject = msg_send![class!(NSRunningApplication), runningApplicationWithProcessIdentifier: pid]; + !app.is_null() && { + let done: Bool = msg_send![app, isFinishedLaunching]; + done.as_bool() + } + } + }) + }); + on_main(handle, move || { + // SAFETY: invoked on the AppKit main thread (`on_main`); ObjC safely ignores messaging nil if the helper already exited. + unsafe { + let app: *mut AnyObject = msg_send![class!(NSRunningApplication), runningApplicationWithProcessIdentifier: pid]; + // NSApplicationActivateIgnoringOtherApps + let _: Bool = msg_send![app, activateWithOptions: 1usize << 1]; + } + }); + let helper_front = || on_main(handle, move || frontmost_pid() == pid); + let start = rune::time::now(); + while !helper_front() && start.elapsed() < Duration::from_secs(1) { + std::thread::sleep(Duration::from_millis(20)); + } + if !helper_front() { + let status = Command::new(CUA_DRIVER) + .arg("bring_to_front") + .arg(format!(r#"{{"pid":{pid}}}"#)) + .stdout(std::process::Stdio::null()) + .status(); + assert!(status.is_ok_and(|s| s.success()), "couldn't hand the focus to the helper (needs {CUA_DRIVER})"); + } + wait("the helper to be frontmost", helper_front); +} diff --git a/app/vendor/rune/crates/rune/tests/macos_window_corners.rs b/app/vendor/rune/crates/rune/tests/macos_window_corners.rs new file mode 100644 index 0000000..448409d --- /dev/null +++ b/app/vendor/rune/crates/rune/tests/macos_window_corners.rs @@ -0,0 +1,150 @@ +//! A transparent, borderless window with `MacWindowOptions::corner_radius(16)` rounds its +//! content layer with a continuous curve and keeps its system shadow, and re-samples that +//! shadow once after each show and resize, never on ordinary frames. Reads the layer and +//! counts `-[NSWindow invalidateShadow]` calls without looking at the screen. Opens a native +//! window, so it only runs with RUNE_GUI_TESTS=1 in a logged-in macOS GUI session. + +#![allow(unsafe_code)] + +#[cfg(not(target_os = "macos"))] +fn main() {} + +#[cfg(target_os = "macos")] +fn main() { mac::main() } + +#[cfg(target_os = "macos")] +mod mac { + use objc2::runtime::{AnyClass, AnyObject, Bool, Imp, Sel}; + use objc2::{msg_send, sel}; + use rune::*; + use std::sync::atomic::{AtomicUsize, Ordering}; + use std::sync::{mpsc, Mutex, OnceLock}; + use std::time::Duration; + + struct State { frame: u32 } + + static INVALIDATIONS: AtomicUsize = AtomicUsize::new(0); + static ORIGINAL: OnceLock<usize> = OnceLock::new(); + static WINDOW: OnceLock<WindowHandle> = OnceLock::new(); + + #[link(name = "QuartzCore", kind = "framework")] + unsafe extern "C" { + static kCACornerCurveContinuous: &'static AnyObject; + } + + unsafe extern "C" fn counted(this: *mut AnyObject, sel: Sel) { + INVALIDATIONS.fetch_add(1, Ordering::SeqCst); + // SAFETY: the original -[NSWindow invalidateShadow] implementation. + let original: unsafe extern "C" fn(*mut AnyObject, Sel) = unsafe { std::mem::transmute(*ORIGINAL.get().unwrap()) }; + // SAFETY: forwards the exact `this` and `sel` received by the swizzled `invalidateShadow` IMP. + unsafe { original(this, sel) } + } + + /// Counts every `invalidateShadow` on any window that doesn't override it. + fn count_invalidations() { + let method = AnyClass::get(c"NSWindow").and_then(|c| c.instance_method(sel!(invalidateShadow))).expect("NSWindow.invalidateShadow"); + // SAFETY: the replacement has the method's signature and calls through to the original. + let original = unsafe { method.set_implementation(std::mem::transmute::<unsafe extern "C" fn(*mut AnyObject, Sel), Imp>(counted)) }; + ORIGINAL.set(original as usize).ok(); + } + + fn view(s: &State, _: &mut Cx<State>) -> El { + el().fill(Color { r: 0.2, g: 0.3, b: 0.5, a: 1.0 }).grow(1.0).child(text(format!("frame {}", s.frame))) + } + + fn wait(what: &str, f: impl Fn() -> bool) { + let start = rune::time::now(); + while !f() { + assert!(start.elapsed() < Duration::from_secs(5), "timed out waiting for {what}"); + std::thread::sleep(Duration::from_millis(5)); + } + } + + fn count() -> usize { INVALIDATIONS.load(Ordering::SeqCst) } + + /// Waits for a resample beyond `before`, then for things to settle, and returns the count. + fn resampled(what: &str, before: usize) -> usize { + wait(what, || count() > before); + std::thread::sleep(Duration::from_millis(400)); + count() + } + + #[derive(Debug)] + struct Readback { radius: f64, continuous: bool, masks: bool, shadow: bool } + + fn read(window: &WindowHandle) -> Readback { + use winit::raw_window_handle::RawWindowHandle; + window.with_raw_handle(|raw| { + let RawWindowHandle::AppKit(handle) = raw.as_raw() else { panic!("not AppKit") }; + let view = handle.ns_view.as_ptr().cast::<AnyObject>(); + // SAFETY: readbacks on the main thread from a live view. + unsafe { + let layer: *mut AnyObject = msg_send![view, layer]; + let window: *mut AnyObject = msg_send![view, window]; + let curve: *mut AnyObject = msg_send![layer, cornerCurve]; + let continuous: Bool = msg_send![curve, isEqualToString: kCACornerCurveContinuous]; + let masks: Bool = msg_send![layer, masksToBounds]; + let shadow: Bool = msg_send![window, hasShadow]; + Readback { radius: msg_send![layer, cornerRadius], continuous: continuous.as_bool(), masks: masks.as_bool(), shadow: shadow.as_bool() } + } + }).expect("window handle") + } + + pub fn main() { + if std::env::var_os("RUNE_GUI_TESTS").is_none() { + println!("macos_window_corners: skipped (set RUNE_GUI_TESTS=1 in a GUI session)"); + return; + } + std::thread::spawn(|| { std::thread::sleep(Duration::from_secs(60)); eprintln!("timeout"); std::process::exit(2) }); + count_invalidations(); + let spec = AppSpec::new("corners", (240.0, 160.0), || State { frame: 0 }, view); + let options = WindowOptions { transparent: true, borderless: true, min_size: Some((0.0, 0.0)), ..Default::default() } + .macos(MacWindowOptions::default().shadow(true).corner_radius(16.0)); + let window = &WINDOW; + let (ready_tx, ready_rx) = mpsc::channel(); + let app = App::new(spec).args(Vec::new()).keep_running().configured_options(options) + .on_ready(move |w| { window.set(w.clone()).ok(); ready_tx.send(()).ok(); }); + let handle = app.handle(); + let result = std::sync::Arc::new(Mutex::new(None)); + let out = result.clone(); + std::thread::spawn(move || { + let run = std::panic::catch_unwind(|| { + ready_rx.recv_timeout(Duration::from_secs(10)).expect("window ready"); + let (tx, rx) = mpsc::channel(); + handle.update(move |_, _| { tx.send(read(window.get().unwrap())).ok(); }); + let readback = rx.recv_timeout(Duration::from_secs(5)).expect("readback"); + println!("macos_window_corners: layer {readback:?}"); + assert_eq!(readback.radius, 16.0); + assert!(readback.continuous && readback.masks && readback.shadow, "{readback:?}"); + + let shown = resampled("a resample after the first frame", 0); + println!("macos_window_corners: show -> frame: {shown} invalidateShadow"); + for _ in 0..8 { + handle.update(|s, _| s.frame += 1); + std::thread::sleep(Duration::from_millis(30)); + } + std::thread::sleep(Duration::from_millis(300)); + assert_eq!(count(), shown, "ordinary frames must not resample"); + + window.get().unwrap().resize_instant((320.0, 200.0)); + let resized = resampled("a resample after the resize", shown); + println!("macos_window_corners: resize -> frame: {resized} invalidateShadow"); + assert_eq!(resized, shown + 1, "one resample per resize"); + + handle.hide(); + wait("hide", || !handle.is_visible()); + std::thread::sleep(Duration::from_millis(200)); + let hidden = count(); + handle.show(); + let reshown = resampled("a resample after showing again", hidden); + println!("macos_window_corners: hide, show -> frame: {reshown} invalidateShadow"); + assert_eq!(reshown, hidden + 1, "one resample per show"); + }); + *out.lock().unwrap() = Some(run.is_ok()); + handle.quit(); + }); + app.run(); + assert_eq!(*result.lock().unwrap(), Some(true), "macos_window_corners failed"); + println!("macos_window_corners: ok"); + } +} diff --git a/app/vendor/rune/crates/rune/tests/measure_scope.rs b/app/vendor/rune/crates/rune/tests/measure_scope.rs new file mode 100644 index 0000000..5584bef --- /dev/null +++ b/app/vendor/rune/crates/rune/tests/measure_scope.rs @@ -0,0 +1,91 @@ +//! `rune::text::with_families` scopes `measure` to one thread, so tests that switch families +//! run in parallel. +use std::sync::Once; + +use rune::text::{TextSystem, font_epoch, measure, with_families}; +use rune::{Env, Runtime, TextStyle, col, text}; + +const INTER: &[u8] = include_bytes!("../assets/Inter-Regular.ttf"); +const PLEX: &[u8] = include_bytes!("../../../themes/opencode/assets/fonts/IBMPlexMono-Regular.ttf"); +const STYLE: TextStyle = TextStyle::new(14.0, 400.0); +const CODE: &str = "let mono = 42; // iiiiiiiiii"; + +/// The process-wide families every test here starts from: Inter in both slots. +fn process() { + static ONCE: Once = Once::new(); + ONCE.call_once(|| { + TextSystem::new(&[INTER, PLEX], ("Inter", "Inter")); + }); +} + +fn mono_width() -> f32 { + measure(CODE, &[], STYLE.mono(), None).0 +} + +#[test] +fn threads_keep_their_own_families() { + process(); + let run = |scoped: bool| { + std::thread::spawn(move || { + process(); + let _g = scoped.then(|| with_families("Inter", "IBM Plex Mono")); + let widths: Vec<f32> = (0..100).map(|_| mono_width()).collect(); + assert!(widths.iter().all(|w| *w == widths[0]), "stable on one thread"); + widths[0] + }) + }; + let (a, b) = (run(true), run(false)); + let (plex, inter) = (a.join().unwrap(), b.join().unwrap()); + assert_ne!(plex, inter, "the guard's mono is wider than the process's"); +} + +#[test] +fn nests_and_restores_on_drop() { + process(); + let outside = mono_width(); + let epoch = font_epoch(); + { + let _outer = with_families("Inter", "IBM Plex Mono"); + let plex = mono_width(); + let outer_epoch = font_epoch(); + assert_ne!(plex, outside); + assert_ne!(outer_epoch, epoch, "caches keyed on the epoch keep scoped sizes apart"); + { + let _inner = with_families("Inter", "Inter"); + assert_eq!(mono_width(), outside); + assert_ne!(font_epoch(), outer_epoch); + assert_ne!(font_epoch(), epoch); + } + assert_eq!(mono_width(), plex); + assert_eq!(font_epoch(), outer_epoch); + } + assert_eq!(mono_width(), outside); + assert_eq!(font_epoch(), epoch); +} + +#[test] +fn a_window_switch_in_a_guard_stays_on_the_thread() { + process(); + let outside = mono_width(); + let other = std::thread::spawn(|| { + process(); + mono_width() + }); + let _g = with_families("Inter", "Inter"); + let mut rt = Runtime::with_text( + (), + |_: &(), _: &mut rune::Cx<()>| col().child(text(CODE).font(STYLE.mono())), + (600.0, 400.0), + Env::new(true, 2.0), + TextSystem::new(&[INTER, PLEX], ("Inter", "Inter")), + ); + rt.update_if(|_, tx| { + tx.set_font_families("Inter", "IBM Plex Mono"); + false + }); + rt.frame(0.0); + assert_ne!(mono_width(), outside, "this thread's measure followed the switch"); + assert_eq!(other.join().unwrap(), outside, "no other thread's did"); + drop(_g); + assert_eq!(mono_width(), outside, "and it ended with the guard"); +} diff --git a/app/vendor/rune/crates/rune/tests/menu_key_equivalent_macos.rs b/app/vendor/rune/crates/rune/tests/menu_key_equivalent_macos.rs new file mode 100644 index 0000000..c5d7737 --- /dev/null +++ b/app/vendor/rune/crates/rune/tests/menu_key_equivalent_macos.rs @@ -0,0 +1,145 @@ +//! Main-thread AppKit check of menu key equivalents, without a window or an event loop: what +//! each item holds, what it shows, and that the key typing its character fires it on the +//! machine's own layout. Key events are built from key codes and handed to the menu, never +//! posted. +#[cfg(target_os = "macos")] +#[allow(dead_code)] +#[path = "../src/native_menu/key_equivalent.rs"] +mod key_equivalent; +#[cfg(target_os = "macos")] +use rune::{PhysicalKeyCode, Shortcut}; + +#[cfg(not(target_os = "macos"))] +fn main() {} + +#[cfg(target_os = "macos")] +#[allow(unsafe_code)] +mod target { + use objc2::{MainThreadOnly, define_class}; + use objc2_app_kit::NSMenuItem; + use objc2_foundation::NSObject; + use std::cell::RefCell; + + thread_local! { pub static HITS: RefCell<Vec<String>> = const { RefCell::new(Vec::new()) }; } + define_class!( + #[unsafe(super(NSObject))] + #[thread_kind = MainThreadOnly] + #[name = "RuneKeyEquivalentTestTarget"] + pub struct Target; + + impl Target { + #[unsafe(method(hit:))] + fn hit(&self, sender: &NSMenuItem) { + let title = sender.title().to_string(); + HITS.with(|hits| hits.borrow_mut().push(title)); + } + } + ); +} + +#[cfg(target_os = "macos")] +#[allow(unsafe_code)] +mod cg { + use objc2::encode::{Encoding, RefEncode}; + use std::ffi::c_void; + #[repr(C)] + pub struct CGEvent { _private: [u8; 0] } + // SAFETY: `CGEvent` is CoreGraphics' opaque `struct __CGEvent`, passed by pointer as `CGEventRef`. + unsafe impl RefEncode for CGEvent { const ENCODING_REF: Encoding = Encoding::Pointer(&Encoding::Struct("__CGEvent", &[])); } + #[link(name = "CoreGraphics", kind = "framework")] + unsafe extern "C" { + pub fn CGEventCreateKeyboardEvent(source: *const c_void, key: u16, down: bool) -> *mut CGEvent; + pub fn CGEventSetFlags(event: *mut CGEvent, flags: u64); + } + #[link(name = "CoreFoundation", kind = "framework")] + unsafe extern "C" { pub fn CFRelease(value: *const c_void); } +} + +#[cfg(target_os = "macos")] +#[allow(unsafe_code)] +fn main() { + use key_equivalent::{COMMAND, CONTROL, KeyEquivalent, OPTION, SHIFT, set_key_equivalent}; + use objc2::{ClassType, MainThreadMarker, msg_send, rc::Retained, runtime::AnyObject, sel}; + use objc2_app_kit::{NSApplication, NSApplicationActivationPolicy, NSEvent, NSMenu, NSMenuItem}; + use objc2_foundation::NSString; + let mtm = MainThreadMarker::new().unwrap(); + let app = NSApplication::sharedApplication(mtm); + app.setActivationPolicy(NSApplicationActivationPolicy::Accessory); + + // A key-down from a key code under `flags`, its characters from the current layout. + let event = |code: u16, flags: usize| -> Retained<NSEvent> { + // SAFETY: the CGEvent is created, converted (NSEvent retains what it needs) and released. + unsafe { + let cg = cg::CGEventCreateKeyboardEvent(std::ptr::null(), code, true); + assert!(!cg.is_null()); + cg::CGEventSetFlags(cg, flags as u64); + let event: Option<Retained<NSEvent>> = msg_send![NSEvent::class(), eventWithCGEvent: cg]; + cg::CFRelease(cg.cast()); + event.unwrap() + } + }; + // The key code that types `c` under ⌘ on this machine's layout, if any. + let code_typing = |c: &str| (0..128u16).find(|&code| event(code, COMMAND).charactersIgnoringModifiers() + .is_some_and(|s| s.to_string() == c)); + + // SAFETY: initializes a freshly allocated `Target` subclass of `NSObject` on the main thread. + let target: Retained<target::Target> = unsafe { msg_send![super(mtm.alloc().set_ivars(())), init] }; + let cases: [(&str, &str, usize); 8] = [ + ("cmd+b", "b", COMMAND), ("cmd+=", "=", COMMAND), ("ctrl+cmd+f", "f", CONTROL | COMMAND), + ("cmd+shift+z", "z", SHIFT | COMMAND), ("alt+cmd+k", "k", OPTION | COMMAND), + ("cmd+left", "\u{f702}", COMMAND), ("f5", "\u{f708}", 0), ("cmd+backspace", "\u{8}", COMMAND), + ]; + // SAFETY: this dedicated main-thread process owns every menu. It never opens a window or + // activates; the only action the menu sends is the test target's `hit:`. + unsafe { + let root = NSMenu::new(mtm); + let view = NSMenu::initWithTitle(mtm.alloc(), &NSString::from_str("View")); + let top = NSMenuItem::new(mtm); + top.setTitle(&NSString::from_str("View")); + top.setSubmenu(Some(&view)); + root.addItem(&top); + let mut items = Vec::new(); + for (accelerator, _, _) in cases { + let item = NSMenuItem::initWithTitle_action_keyEquivalent(mtm.alloc(), &NSString::from_str(accelerator), + Some(sel!(hit:)), &NSString::from_str("")); + item.setTarget(Some(&target)); + set_key_equivalent(&item, Some(&accelerator.parse::<Shortcut>().unwrap())); + view.addItem(&item); + items.push(item); + } + app.setMainMenu(Some(&root)); + + for ((accelerator, key, mask), item) in cases.iter().zip(&items) { + assert_eq!(KeyEquivalent::new(&accelerator.parse().unwrap()), KeyEquivalent { key: key.to_string(), mask: *mask }); + assert_eq!(item.keyEquivalent().to_string(), *key, "{accelerator}"); + assert_eq!(item.keyEquivalentModifierMask().0, *mask, "{accelerator}"); + } + // What the menu draws, as accessibility reads it: ⌃⌘F is Control (4) with Command and + // a plain F, not the Globe key (16). + let ax = |item: &NSMenuItem, attribute: &str| -> Option<String> { + let value: Option<Retained<AnyObject>> = msg_send![item, accessibilityAttributeValue: &*NSString::from_str(attribute)]; + value.map(|v| { let d: Retained<NSString> = msg_send![&v, description]; d.to_string() }) + }; + assert_eq!(ax(&items[0], "AXMenuItemCmdChar").as_deref(), Some("B")); + assert_eq!(ax(&items[2], "AXMenuItemCmdChar").as_deref(), Some("F")); + assert_eq!(ax(&items[2], "AXMenuItemCmdModifiers").as_deref(), Some("4")); + + // The key that types each character here fires its item, wherever that key sits. + let fires = |code: u16, flags: usize| { + target::HITS.with(|hits| hits.borrow_mut().clear()); + let handled: bool = msg_send![&root, performKeyEquivalent: &*event(code, flags)]; + let hits = target::HITS.with(|hits| hits.borrow().clone()); + handled.then(|| hits.join(",")) + }; + for (accelerator, key, mask) in [("cmd+b", "b", COMMAND), ("cmd+=", "=", COMMAND), ("ctrl+cmd+f", "f", CONTROL | COMMAND), + ("cmd+shift+z", "z", SHIFT | COMMAND)] { + let Some(code) = code_typing(key) else { println!("SKIP: no key types {key:?} under ⌘ here"); continue }; + assert_eq!(fires(code, mask).as_deref(), Some(accelerator), "{accelerator} from key code {code}"); + } + // QWERTY's B position fires ⌘B only where it types "b" (on Dvorak it types "x"). + const QWERTY_B: u16 = 11; + let b_here = code_typing("b") == Some(QWERTY_B); + assert_eq!(fires(QWERTY_B, COMMAND).is_some(), b_here); + println!("PASS: key equivalents hold the accelerators' characters; QWERTY B types b here: {b_here}"); + } +} diff --git a/app/vendor/rune/crates/rune/tests/open_activates.rs b/app/vendor/rune/crates/rune/tests/open_activates.rs new file mode 100644 index 0000000..090c1a2 --- /dev/null +++ b/app/vendor/rune/crates/rune/tests/open_activates.rs @@ -0,0 +1,130 @@ +//! `open()` activates an accessory app and makes its window key while another app is +//! frontmost: the first open of a window that doesn't exist yet, a reopen after hiding, and a +//! hidden `App::window` window. A launcher panel's open and an overlay's show stay +//! nonactivating. Starts a helper app to hold the focus (handed to it with CuaDriver when +//! nothing yields), so it only runs with RUNE_GUI_TESTS=1 in a logged-in macOS GUI session. + +#[cfg(not(target_os = "macos"))] +fn main() {} + +#[cfg(target_os = "macos")] +mod macos_support; + +#[cfg(target_os = "macos")] +fn main() { mac::main() } + +#[cfg(target_os = "macos")] +#[allow(unsafe_code)] +mod mac { + use std::process::Command; + use std::sync::Mutex; + use std::time::Duration; + use objc2::{class, msg_send, runtime::AnyObject}; + use objc2_foundation::NSString; + use rune::*; + use crate::macos_support::{activate_helper, app_active, frontmost_pid, on_main, wait}; + + const HELPER: &str = "RUNE_OPEN_ACTIVATES_HELPER"; + const MAIN_TITLE: &str = "open activates main"; + const SETTINGS_TITLE: &str = "open activates settings"; + + fn view<S>(_: &S, _: &mut Cx<S>) -> El { text("open activates") } + + /// The key window's title, if this app has a key window. + fn key_title() -> Option<String> { + // SAFETY: invoked on the AppKit main thread (`on_main`); `window` and `title` are checked non-null before use. + unsafe { + let app: *mut AnyObject = msg_send![class!(NSApplication), sharedApplication]; + let window: *mut AnyObject = msg_send![app, keyWindow]; + if window.is_null() { return None } + let title: *mut NSString = msg_send![window, title]; + (!title.is_null()).then(|| (*title).to_string()) + } + } + + /// The helper keeps the front. A key nonactivating panel can still make `isActive` report + /// true, so that isn't checked. + fn expect_inactive(handle: &AppHandle<()>, pid: i32, what: &str) { + std::thread::sleep(Duration::from_millis(400)); + let front = on_main(handle, frontmost_pid); + assert_eq!(front, pid, "{what} took the front from the helper"); + } + + fn expect_active(handle: &AppHandle<()>, title: &'static str, what: &str) { + let me = std::process::id() as i32; + let start = rune::time::now(); + loop { + let (active, front, key) = on_main(handle, || (app_active(), frontmost_pid(), key_title())); + if active && front == me && key.as_deref() == Some(title) { return } + assert!(start.elapsed() < Duration::from_secs(5), + "{what}: active={active}, frontmost={front} (this app {me}), key window {key:?}, want {title:?}"); + std::thread::sleep(Duration::from_millis(20)); + } + } + + fn helper() { + std::thread::spawn(|| { std::thread::sleep(Duration::from_secs(60)); std::process::exit(0) }); + App::new(AppSpec::new("open activates helper", (240.0, 80.0), || (), view)).args(Vec::new()).run(); + } + + pub fn main() { + if std::env::var_os(HELPER).is_some() { return helper() } + if std::env::var_os("RUNE_GUI_TESTS").is_none() { + println!("open_activates: skipped (set RUNE_GUI_TESTS=1 in a GUI session)"); + return; + } + std::thread::spawn(|| { std::thread::sleep(Duration::from_secs(90)); eprintln!("timeout"); std::process::exit(2) }); + let mut child = Command::new(std::env::current_exe().unwrap()).env(HELPER, "1").spawn().expect("helper"); + let pid = child.id() as i32; + let mut app = App::new(AppSpec::new(MAIN_TITLE, (240.0, 120.0), || (), view)).args(Vec::new()) + .accessory().windowless(); + let main = app.handle(); + let (_, settings) = app.window(WindowSpec::new("settings", AppSpec::new(SETTINGS_TITLE, (240.0, 120.0), || (), view)) + .options(WindowOptions { visible: false, ..Default::default() })); + let (_, launcher) = app.window(WindowSpec::new("launcher", AppSpec::new("open activates launcher", (240.0, 80.0), || (), view)) + .configured_options(WindowOptions::launcher_panel())); + let overlay = app.overlay(OverlaySpec::new("open activates overlay", (200.0, 60.0), view), ()); + let result = std::sync::Arc::new(Mutex::new(None)); + let out = result.clone(); + std::thread::spawn(move || { + let run = std::panic::catch_unwind(|| { + std::thread::sleep(Duration::from_millis(500)); + assert!(!on_main(&main, app_active), "an accessory app doesn't activate at launch"); + activate_helper(&main, pid); + assert!(!main.is_visible(), "windowless starts without a window"); + + overlay.show(); + expect_inactive(&main, pid, "overlay show"); + overlay.hide(); + launcher.open(); + expect_inactive(&main, pid, "launcher open"); + launcher.hide(); + std::thread::sleep(Duration::from_millis(200)); + activate_helper(&main, pid); + + main.open(); + expect_active(&main, MAIN_TITLE, "the first open of a new window"); + println!("first open: active and key"); + + main.hide(); + wait("hide", || !main.is_visible()); + activate_helper(&main, pid); + main.open(); + expect_active(&main, MAIN_TITLE, "a reopen after hiding"); + println!("reopen: active and key"); + + activate_helper(&main, pid); + settings.open(); + expect_active(&main, SETTINGS_TITLE, "opening a hidden App::window window"); + println!("App::window open: active and key"); + }); + *out.lock().unwrap() = Some(run.is_ok()); + main.quit(); + }); + app.run(); + child.kill().ok(); + child.wait().ok(); + assert_eq!(*result.lock().unwrap(), Some(true), "open_activates failed"); + println!("open_activates: ok"); + } +} diff --git a/app/vendor/rune/crates/rune/tests/overlay_gpu_lifecycle.rs b/app/vendor/rune/crates/rune/tests/overlay_gpu_lifecycle.rs new file mode 100644 index 0000000..c79b6d1 --- /dev/null +++ b/app/vendor/rune/crates/rune/tests/overlay_gpu_lifecycle.rs @@ -0,0 +1,166 @@ +//! A prewarmed overlay with `release_gpu_when_hidden` makes its window at startup on X11, and +//! nothing on Windows, and no GPU surface, nor device, until it shows; each hide gives the +//! surface back (and on Windows the window), and `release_gpu_after` does so once the overlay +//! stayed hidden that long. The device waits for the next show, which takes it rather than +//! making another (hex#1268). Prints +//! how long each show waits for its first present, and the process's private memory along the +//! way. Opens overlays, so it only runs with RUNE_GUI_TESTS=1 in a desktop session. + +#[cfg(target_os = "macos")] +fn main() {} + +#[cfg(not(target_os = "macos"))] +fn main() { lazy::main() } + +#[cfg(not(target_os = "macos"))] +mod lazy { + use std::sync::atomic::{AtomicUsize, Ordering}; + use std::sync::{Arc, Mutex}; + use std::time::Duration; + use rune::*; + + static STARTS: AtomicUsize = AtomicUsize::new(0); + + fn view(_: &(), _: &mut Cx<()>) -> El { el().w_full().h_full().fill(oklcha(0.6, 0.2, 250.0, 0.2)) } + fn hud(_: &(), _: &mut Cx<()>) -> El { el().size(200.0, 40.0).fill(oklcha(0.2, 0.0, 0.0, 0.6)).radius(20.0) } + + fn wait(limit: Duration, f: impl Fn() -> bool) -> Option<Duration> { + let start = rune::time::now(); + while !f() { + if start.elapsed() > limit { return None; } + std::thread::sleep(Duration::from_micros(200)); + } + Some(start.elapsed()) + } + + /// The time from `show` to the overlay's first present; a locked session may present + /// nothing, and then the surface is what's checked. + fn show<T>(name: &str, overlay: &OverlayHandle<T>, results: &mut Vec<(String, Option<f64>)>) { + let presents = overlay.surface_stats().totals.presents; + overlay.show(); + let presented = wait(Duration::from_secs(5), || overlay.surface_stats().totals.presents > presents); + assert!(wait(Duration::from_secs(5), || overlay.surface_description().is_some()).is_some(), "{name} made no surface: {:?}", overlay.failure()); + let ms = presented.map(|d| d.as_secs_f64() * 1000.0); + println!("{name}: first present {}", ms.map_or("none".into(), |ms| format!("{ms:.1} ms"))); + results.push((name.to_owned(), ms)); + } + + fn hide<T>(name: &str, overlay: &OverlayHandle<T>, released: bool) { + overlay.hide(); + if released { + assert!(wait(Duration::from_secs(2), || overlay.surface_description().is_none()).is_some(), "{name}: hidden, its surface is released"); + } else { + std::thread::sleep(Duration::from_millis(100)); + assert!(overlay.surface_description().is_some(), "{name}: hidden, its surface is kept"); + } + } + + #[cfg(target_os = "windows")] + #[allow(unsafe_code)] + fn private_mb() -> f64 { + #[repr(C)] + #[derive(Default)] + struct Counters { cb: u32, faults: u32, peak_ws: usize, ws: usize, qpp: usize, qp: usize, qnpp: usize, qnp: usize, pagefile: usize, peak_pagefile: usize, private: usize } + #[link(name = "kernel32")] + unsafe extern "system" { + fn GetCurrentProcess() -> isize; + fn K32GetProcessMemoryInfo(process: isize, counters: *mut Counters, cb: u32) -> i32; + } + let mut c = Counters { cb: std::mem::size_of::<Counters>() as u32, ..Default::default() }; + // SAFETY: fills `c`, whose `cb` names PROCESS_MEMORY_COUNTERS_EX. + unsafe { K32GetProcessMemoryInfo(GetCurrentProcess(), &mut c, c.cb) }; + c.private as f64 / 1e6 + } + + #[cfg(not(target_os = "windows"))] + fn private_mb() -> f64 { 0.0 } + + pub fn main() { + if std::env::var_os("RUNE_GUI_TESTS").is_none() { + println!("overlay_gpu_lifecycle: skipped (set RUNE_GUI_TESTS=1 in a desktop session)"); + return; + } + std::thread::spawn(|| { std::thread::sleep(Duration::from_secs(120)); eprintln!("timeout"); std::process::exit(2) }); + on_gpu(|event| if event == GpuEvent::Starting { STARTS.fetch_add(1, Ordering::SeqCst); }); + let mut app = App::new(AppSpec::new("overlay gpu lifecycle", (100.0, 100.0), || (), view)).args(Vec::new()).windowless(); + let created = Arc::new(AtomicUsize::new(0)); + let seen = created.clone(); + let full = app.overlay(OverlaySpec::new("lazy full screen", (100.0, 100.0), view) + .options(OverlayOptions { placement: Some(OverlayPlacement::FullScreen), prewarm: true, ..Default::default() }) + .release_gpu_when_hidden() + .on_created(move |_| { seen.fetch_add(1, Ordering::SeqCst); }), ()); + let idle_release = Duration::from_millis(800); + let small = app.overlay(OverlaySpec::new("hud", (200.0, 40.0), hud).options(OverlayOptions { prewarm: true, ..Default::default() }).release_gpu_after(idle_release), ()); + let handle = app.handle(); + let result = Arc::new(Mutex::new(None)); + let out = result.clone(); + std::thread::spawn(move || { + let run = std::panic::catch_unwind(move || { + let mut r = Vec::new(); + if cfg!(target_os = "windows") { + std::thread::sleep(Duration::from_millis(1500)); + assert_eq!(created.load(Ordering::SeqCst), 0, "a hidden overlay has no window on Windows"); + } else { + wait(Duration::from_secs(10), || full.availability() == Availability::Available).expect("the prewarmed window"); + // Let startup make the prewarmed window. + std::thread::sleep(Duration::from_millis(1500)); + assert_eq!(created.load(Ordering::SeqCst), 1, "on_created runs at startup"); + } + assert!(full.surface_description().is_none(), "a hidden prewarmed overlay has no surface"); + assert_eq!(STARTS.load(Ordering::SeqCst), 0, "nothing shown, no GPU device"); + let idle = private_mb(); + + show("full screen, first show of the process", &full, &mut r); + assert_eq!(STARTS.load(Ordering::SeqCst), 1); + println!(" {}", full.surface_description().unwrap()); + let shown = private_mb(); + hide("full screen", &full, true); + std::thread::sleep(Duration::from_millis(500)); + let released = private_mb(); + + show("full screen, on the parked device", &full, &mut r); + assert_eq!(STARTS.load(Ordering::SeqCst), 1, "the next show takes the parked device"); + hide("full screen", &full, true); + std::thread::sleep(Duration::from_millis(300)); + + warm_gpu(wgpu::Features::empty()); + std::thread::sleep(Duration::from_millis(800)); + show("full screen, warmed 800 ms ahead", &full, &mut r); + assert_eq!(STARTS.load(Ordering::SeqCst), 1, "warm_gpu makes nothing while a device waits"); + hide("full screen", &full, true); + std::thread::sleep(Duration::from_millis(300)); + + warm_gpu(wgpu::Features::empty()); + show("full screen, warmed at the show", &full, &mut r); + assert_eq!(STARTS.load(Ordering::SeqCst), 1); + hide("full screen", &full, true); + std::thread::sleep(Duration::from_millis(300)); + + show("hud, no device", &small, &mut r); + hide("hud", &small, false); + show("hud, shown again within release_gpu_after", &small, &mut r); + hide("hud", &small, false); + warm_gpu(wgpu::Features::empty()); + assert_eq!(STARTS.load(Ordering::SeqCst), 1, "warm_gpu makes nothing while the hud holds the device"); + show("full screen, on the hud's device", &full, &mut r); + assert_eq!(STARTS.load(Ordering::SeqCst), 1, "the full-screen overlay shares the hud's device"); + hide("full screen", &full, true); + std::thread::sleep(idle_release + Duration::from_millis(500)); + assert!(small.surface_description().is_none(), "the hud gave its surface back after release_gpu_after"); + show("hud, after release_gpu_after", &small, &mut r); + assert_eq!(STARTS.load(Ordering::SeqCst), 1, "the hud takes the device it parked"); + hide("hud", &small, false); + assert!(full.failure().is_none() && small.failure().is_none(), "{:?} {:?}", full.failure(), small.failure()); + println!("private memory: hidden at startup {idle:.0} MB, full screen shown {shown:.0} MB, hidden again {released:.0} MB"); + println!("| show | first present |"); + println!("| --- | --- |"); + for (name, ms) in r { println!("| {name} | {} |", ms.map_or("none".into(), |ms| format!("{ms:.0} ms"))); } + }); + *out.lock().unwrap() = Some(run.is_ok()); + handle.quit(); + }); + app.run(); + assert_eq!(*result.lock().unwrap(), Some(true), "overlay_gpu_lifecycle failed"); + println!("overlay_gpu_lifecycle: ok"); + } +} diff --git a/app/vendor/rune/crates/rune/tests/overlay_soak.rs b/app/vendor/rune/crates/rune/tests/overlay_soak.rs new file mode 100644 index 0000000..e2ffbc4 --- /dev/null +++ b/app/vendor/rune/crates/rune/tests/overlay_soak.rs @@ -0,0 +1,121 @@ +//! Shows and hides two overlays that give their surface back while hidden (a HUD and a live-text +//! plate, as Hex shows on every dictation) a few thousand times, and checks that the process's +//! memory stays flat and that every show draws on the one GPU device the first show made +//! (hex#1268: memory grew by gigabytes over an hour of dictation on a hybrid laptop). Prints the +//! memory every few hundred cycles. Opens overlays, so it only runs with RUNE_GUI_TESTS=1 in a +//! desktop session; `RUNE_SOAK_CYCLES` sets the count (2000 by default). + +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::{Arc, Mutex}; +use std::time::Duration; +use rune::*; + +static STARTS: AtomicUsize = AtomicUsize::new(0); + +/// Memory may grow this much from the warmed-up baseline to the last cycle. +const ALLOWED_GROWTH_MB: f64 = 48.0; +/// Cycles before the baseline: allocators, caches and the driver settle. +const WARM_UP: usize = 100; + +fn hud(_: &(), _: &mut Cx<()>) -> El { el().size(200.0, 40.0).fill(oklcha(0.2, 0.0, 0.0, 0.6)).radius(20.0) } +fn plate(_: &(), _: &mut Cx<()>) -> El { + el().w_full().h_full().fill(oklcha(0.25, 0.0, 0.0, 0.8)).radius(12.0).child(text("live words")) +} + +fn wait(limit: Duration, f: impl Fn() -> bool) -> bool { + let start = rune::time::now(); + while !f() { + if start.elapsed() > limit { return false; } + std::thread::sleep(Duration::from_micros(200)); + } + true +} + +/// Shows `overlay` until it has presented a frame. +fn show<T>(name: &str, overlay: &OverlayHandle<T>) { + let presents = overlay.surface_stats().totals.presents; + overlay.show(); + assert!(wait(Duration::from_secs(5), || overlay.surface_stats().totals.presents > presents && overlay.surface_description().is_some()), + "{name} presented nothing: {:?}", overlay.failure()); +} + +/// Hides `overlay` until its surface is gone. +fn hide<T>(name: &str, overlay: &OverlayHandle<T>) { + overlay.hide(); + assert!(wait(Duration::from_secs(5), || overlay.surface_description().is_none()), "{name} kept its surface"); +} + +#[cfg(target_os = "windows")] +#[allow(unsafe_code)] +fn memory_mb() -> f64 { + #[repr(C)] + #[derive(Default)] + struct Counters { cb: u32, faults: u32, peak_ws: usize, ws: usize, qpp: usize, qp: usize, qnpp: usize, qnp: usize, pagefile: usize, peak_pagefile: usize, private: usize } + #[link(name = "kernel32")] + unsafe extern "system" { + fn GetCurrentProcess() -> isize; + fn K32GetProcessMemoryInfo(process: isize, counters: *mut Counters, cb: u32) -> i32; + } + let mut c = Counters { cb: std::mem::size_of::<Counters>() as u32, ..Default::default() }; + // SAFETY: fills `c`, whose `cb` names PROCESS_MEMORY_COUNTERS_EX. + unsafe { K32GetProcessMemoryInfo(GetCurrentProcess(), &mut c, c.cb) }; + c.private as f64 / 1e6 +} + +/// Resident memory, from `/proc/self/statm` (pages). +#[cfg(target_os = "linux")] +fn memory_mb() -> f64 { + let statm = std::fs::read_to_string("/proc/self/statm").unwrap_or_default(); + let pages: f64 = statm.split_whitespace().nth(1).and_then(|p| p.parse().ok()).unwrap_or(0.0); + pages * 4096.0 / 1e6 +} + +#[cfg(not(any(target_os = "windows", target_os = "linux")))] +fn memory_mb() -> f64 { 0.0 } + +fn main() { + if std::env::var_os("RUNE_GUI_TESTS").is_none() { + println!("overlay_soak: skipped (set RUNE_GUI_TESTS=1 in a desktop session)"); + return; + } + let cycles: usize = rune::env::var("RUNE_SOAK_CYCLES").and_then(|n| n.parse().ok()).unwrap_or(2000).max(WARM_UP + 1); + std::thread::spawn(|| { std::thread::sleep(Duration::from_secs(3600)); eprintln!("timeout"); std::process::exit(2) }); + on_gpu(|event| if event == GpuEvent::Starting { STARTS.fetch_add(1, Ordering::SeqCst); }); + let mut app = App::new(AppSpec::new("overlay soak", (100.0, 100.0), || (), hud)).args(Vec::new()).windowless(); + let hud = app.overlay(OverlaySpec::new("soak hud", (200.0, 40.0), hud) + .options(OverlayOptions { prewarm: true, ..Default::default() }) + .release_gpu_when_hidden(), ()); + let plate = app.overlay(OverlaySpec::new("soak live text", (420.0, 44.0), plate) + .options(OverlayOptions { placement: Some(OverlayPlacement::Edge { edge: ScreenEdge::Top, margin: 60.0, align: Align::Center, inset: 0.0 }), ..Default::default() }) + .release_gpu_when_hidden(), ()); + let handle = app.handle(); + let result = Arc::new(Mutex::new(None)); + let out = result.clone(); + std::thread::spawn(move || { + let run = std::panic::catch_unwind(move || { + let started = rune::time::now(); + let mut baseline = 0.0; + for cycle in 0..cycles { + show("hud", &hud); + show("live text", &plate); + hide("live text", &plate); + hide("hud", &hud); + if cycle + 1 == WARM_UP { baseline = memory_mb(); } + if (cycle + 1) % 250 == 0 { + println!("cycle {:>5}: {:.0} MB, {} GPU device(s) made, {:.0} s", cycle + 1, memory_mb(), STARTS.load(Ordering::SeqCst), started.elapsed().as_secs_f64()); + } + } + let end = memory_mb(); + let starts = STARTS.load(Ordering::SeqCst); + println!("overlay_soak: {cycles} cycles, {baseline:.0} MB after {WARM_UP}, {end:.0} MB at the end, {starts} GPU device(s) made"); + assert!(hud.failure().is_none() && plate.failure().is_none(), "{:?} {:?}", hud.failure(), plate.failure()); + assert_eq!(starts, 1, "every show draws on the first show's device"); + assert!(end - baseline < ALLOWED_GROWTH_MB, "memory grew {:.0} MB over {} cycles", end - baseline, cycles - WARM_UP); + }); + *out.lock().unwrap() = Some(run.is_ok()); + handle.quit(); + }); + app.run(); + assert_eq!(*result.lock().unwrap(), Some(true), "overlay_soak failed"); + println!("overlay_soak: ok"); +} diff --git a/app/vendor/rune/crates/rune/tests/pixels_streaming.rs b/app/vendor/rune/crates/rune/tests/pixels_streaming.rs new file mode 100644 index 0000000..3e0af27 --- /dev/null +++ b/app/vendor/rune/crates/rune/tests/pixels_streaming.rs @@ -0,0 +1,64 @@ +//! The producer supplies its buffer; replacing and staging a warm stream allocates nothing. + +#![allow(unsafe_code)] + +use std::alloc::{GlobalAlloc, Layout, System}; +use std::cell::Cell; + +thread_local! { + static COUNT: Cell<Option<usize>> = const { Cell::new(None) }; +} +struct Allocator; +fn allocated() { + COUNT.try_with(|count| { + if let Some(n) = count.get() { count.set(Some(n + 1)); } + }).ok(); +} +// SAFETY: forwards every allocation call to `System`, only counting allocations on this thread. +unsafe impl GlobalAlloc for Allocator { + unsafe fn alloc(&self, layout: Layout) -> *mut u8 { + allocated(); + // SAFETY: delegates allocation with the caller's layout to `System`. + unsafe { System.alloc(layout) } + } + unsafe fn alloc_zeroed(&self, layout: Layout) -> *mut u8 { + allocated(); + // SAFETY: delegates zeroed allocation with the caller's layout to `System`. + unsafe { System.alloc_zeroed(layout) } + } + unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, size: usize) -> *mut u8 { + allocated(); + // SAFETY: delegates reallocation of `ptr`, `layout` and `size` to `System`. + unsafe { System.realloc(ptr, layout, size) } + } + unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) { + // SAFETY: delegates deallocation of `ptr` and `layout` to `System`. + unsafe { System.dealloc(ptr, layout) } + } +} +#[global_allocator] +static ALLOCATOR: Allocator = Allocator; + +#[test] +fn sixty_hud_updates_allocate_nothing_and_keep_the_same_slot() { + use rune::{Cx, El, Env, Pixels, Runtime, el}; + fn view(p: &Pixels, _: &mut Cx<Pixels>) -> El { el().size(112.0, 64.0).pixels(p) } + let pixels = Pixels::new(); + pixels.set(224, 128, vec![0; 224 * 128 * 4]); + let mut rt = Runtime::new(pixels.clone(), view, (112.0, 64.0), Env::new(true, 2.0)); + rt.frame(0.0); + let slot = rt.images.place(&pixels, [224.0, 128.0]).unwrap(); + let page = rt.images.pages[0].data.as_ptr(); + let buffers: Vec<_> = (0..60).map(|n| vec![n; 224 * 128 * 4]).collect(); + let mut stable = true; + COUNT.set(Some(0)); + for buffer in buffers { + pixels.set(224, 128, buffer); + stable &= rt.images.place(&pixels, [224.0, 128.0]) == Some(slot); + rt.images.end_frame(); + } + let allocations = COUNT.replace(None).unwrap(); + assert_eq!(allocations, 0); + assert!(stable && !slot.premultiplied, "streaming never selects a mip"); + assert_eq!(rt.images.pages[0].data.as_ptr(), page); +} diff --git a/app/vendor/rune/crates/rune/tests/popup_menu_macos.rs b/app/vendor/rune/crates/rune/tests/popup_menu_macos.rs new file mode 100644 index 0000000..f45f169 --- /dev/null +++ b/app/vendor/rune/crates/rune/tests/popup_menu_macos.rs @@ -0,0 +1,299 @@ +//! A native pop-up menu opens from a press or an update, Rune keeps drawing while it tracks, +//! and its pick or dismissal reaches the callback exactly once. Clicks and keys are synthetic +//! NSEvents on the app's own queue. Where the menu ignores them, it says so and drives the open +//! menu through AppKit instead. Opens a window, so it only runs with RUNE_GUI_TESTS=1 in a +//! logged-in GUI session. + +#![allow(unsafe_code)] + +#[cfg(not(target_os = "macos"))] +fn main() {} + +#[cfg(target_os = "macos")] +fn main() { mac::main() } + +#[cfg(target_os = "macos")] +mod mac { + use std::cell::RefCell; + use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; + use std::sync::{Mutex, mpsc}; + use std::time::Duration; + + use objc2::{class, msg_send, rc::Retained, runtime::AnyObject}; + use objc2_foundation::{NSPoint, NSString}; + use rune::*; + + #[derive(Default)] + struct State { theme: String } + + /// Frames drawn: `poll` runs once a frame, and the spinner keeps frames coming. + static FRAMES: AtomicUsize = AtomicUsize::new(0); + static PRESSES: AtomicUsize = AtomicUsize::new(0); + static TRACKING: AtomicBool = AtomicBool::new(false); + static PICKS: Mutex<Vec<Option<String>>> = Mutex::new(Vec::new()); + + thread_local! { + static MENU: RefCell<Option<Retained<AnyObject>>> = const { RefCell::new(None) }; + static OBSERVERS: RefCell<Vec<Retained<AnyObject>>> = const { RefCell::new(Vec::new()) }; + } + + fn menu() -> PopupMenu { + PopupMenu::picker([("system", "System"), ("light", "Light"), ("dark", "Dark")], "system") + } + + fn record(s: &mut State, picked: Option<&str>, _: &mut Tx) { + PICKS.lock().unwrap().push(picked.map(str::to_owned)); + if let Some(id) = picked { s.theme = id.into(); } + } + + fn view(_: &State, _: &mut Cx<State>) -> El { + el() + .child(el().key("theme").size(120.0, 24.0).pin(Some(40.0), Some(40.0), None, None) + .fill(oklch(0.45, 0.02, 260.0)).radius(6.0) + .on_press_tx(|_: &mut State, tx: &mut Tx| { + PRESSES.fetch_add(1, Ordering::SeqCst); + tx.popup_menu(menu(), "theme", record); + })) + .child(el().key("spinner").size(24.0, 24.0).pin(Some(40.0), Some(100.0), None, None) + .fill(oklch(0.7, 0.15, 50.0)).looping(LoopSpec::rotation(1.0))) + } + + fn poll(_: &mut State, _: f64, _: &mut Tx) -> bool { + FRAMES.fetch_add(1, Ordering::SeqCst); + false + } + + fn wait(what: &str, limit: Duration, f: impl Fn() -> bool) -> bool { + let start = rune::time::now(); + while !f() { + if start.elapsed() > limit { println!("popup_menu_macos: no {what} within {limit:?}"); return false; } + std::thread::sleep(Duration::from_millis(5)); + } + true + } + + /// Runs `f` on the main thread through an update and waits for it. + fn on_main<T: Send + 'static>(handle: &AppHandle<State>, f: impl FnOnce(&mut State, &mut Tx) -> T + Send + 'static) -> T { + let (tx, rx) = mpsc::channel(); + handle.update(move |s, t| { tx.send(f(s, t)).ok(); }); + rx.recv_timeout(Duration::from_secs(5)).expect("an update runs on the main thread") + } + + /// The app's window, its number, and a view point (top-left origin) in window coordinates. + unsafe fn window_point(x: f64, y: f64) -> (*mut AnyObject, isize, NSPoint) { + // SAFETY: caller invokes on the AppKit main thread; queries the app's only live window. + unsafe { + let app: *mut AnyObject = msg_send![class!(NSApplication), sharedApplication]; + let windows: *mut AnyObject = msg_send![app, windows]; + let window: *mut AnyObject = msg_send![windows, firstObject]; + let view: *mut AnyObject = msg_send![window, contentView]; + let at: NSPoint = msg_send![view, convertPoint: NSPoint::new(x, y), toView: std::ptr::null::<AnyObject>()]; + let number: isize = msg_send![window, windowNumber]; + (window, number, at) + } + } + + unsafe fn now() -> f64 { + // SAFETY: caller invokes on the AppKit main thread; `NSProcessInfo.processInfo.systemUptime` is a plain getter. + unsafe { + let info: *mut AnyObject = msg_send![class!(NSProcessInfo), processInfo]; + msg_send![info, systemUptime] + } + } + + /// Queues synthetic events on the app's own event queue, as the window server would + /// deliver them: no Accessibility permission, and the real AppKit and winit dispatch. + fn post(handle: &AppHandle<State>, events: Vec<Synthetic>) { + on_main(handle, move |_, _| { + // SAFETY: main thread (an update). The NSEvent factories return autoreleased events + // that postEvent:atStart: retains. + unsafe { + let app: *mut AnyObject = msg_send![class!(NSApplication), sharedApplication]; + for event in events { + let (_, number, at) = window_point(event.at.0, event.at.1); + let made: *mut AnyObject = match event.kind { + Kind::Mouse(kind) => msg_send![class!(NSEvent), mouseEventWithType: kind, location: at, + modifierFlags: 0usize, timestamp: now(), windowNumber: number, context: std::ptr::null::<AnyObject>(), + eventNumber: 0isize, clickCount: 1isize, pressure: if kind == 1 { 1.0f32 } else { 0.0f32 }], + Kind::Key(kind, chars, code) => { + let chars = NSString::from_str(chars); + msg_send![class!(NSEvent), keyEventWithType: kind, location: at, modifierFlags: 0usize, + timestamp: now(), windowNumber: number, context: std::ptr::null::<AnyObject>(), + characters: &*chars, charactersIgnoringModifiers: &*chars, isARepeat: false, keyCode: code] + } + }; + assert!(!made.is_null(), "NSEvent made the synthetic event"); + let _: () = msg_send![app, postEvent: made, atStart: false]; + } + } + }); + } + + #[derive(Clone, Copy)] + enum Kind { Mouse(usize), Key(usize, &'static str, u16) } + #[derive(Clone, Copy)] + struct Synthetic { kind: Kind, at: (f64, f64) } + + const BUTTON: (f64, f64) = (100.0, 52.0); + + fn click(handle: &AppHandle<State>) { + post(handle, vec![Synthetic { kind: Kind::Mouse(1), at: BUTTON }, Synthetic { kind: Kind::Mouse(2), at: BUTTON }]); + } + + fn key(handle: &AppHandle<State>, chars: &'static str, code: u16) { + post(handle, vec![Synthetic { kind: Kind::Key(10, chars, code), at: BUTTON }, Synthetic { kind: Kind::Key(11, chars, code), at: BUTTON }]); + } + + /// Notes when a menu starts and stops tracking, keeping the open one for `drive`. + fn observe_menus() { + // SAFETY: main thread; the observer tokens are kept for the process. + unsafe { + let center: *mut AnyObject = msg_send![class!(NSNotificationCenter), defaultCenter]; + for (name, begin) in [("NSMenuDidBeginTrackingNotification", true), ("NSMenuDidEndTrackingNotification", false)] { + let block = block2::RcBlock::new(move |note: *mut AnyObject| { + let menu: *mut AnyObject = msg_send![note, object]; + MENU.with(|slot| *slot.borrow_mut() = if begin { Retained::retain(menu) } else { None }); + TRACKING.store(begin, Ordering::SeqCst); + }); + let token: Option<Retained<AnyObject>> = msg_send![center, addObserverForName: &*NSString::from_str(name), + object: std::ptr::null::<AnyObject>(), queue: std::ptr::null::<AnyObject>(), usingBlock: &*block]; + OBSERVERS.with(|o| o.borrow_mut().extend(token)); + } + } + } + + /// Picks item `index` of the tracking menu (or dismisses it) through AppKit, from an update + /// that runs while the menu tracks. + fn drive(handle: &AppHandle<State>, index: Option<isize>) { + on_main(handle, move |_, _| MENU.with(|slot| { + let Some(menu) = slot.borrow().clone() else { return }; + // SAFETY: the tracking NSMenu, on the main thread. + unsafe { + if let Some(index) = index { let _: () = msg_send![&*menu, performActionForItemAtIndex: index]; } + let _: () = msg_send![&*menu, cancelTracking]; + } + })); + } + + fn picks() -> Vec<Option<String>> { PICKS.lock().unwrap().clone() } + + pub fn main() { + if std::env::var_os("RUNE_GUI_TESTS").is_none() { + println!("popup_menu_macos: skipped (set RUNE_GUI_TESTS=1 in a GUI session)"); + return; + } + std::thread::spawn(|| { std::thread::sleep(Duration::from_secs(150)); eprintln!("timeout"); std::process::exit(2) }); + assert!(popup_menu_supported()); + let spec = AppSpec { poll: Some(poll), ..AppSpec::new("popup menu", (320.0, 160.0), || State { theme: "system".into() }, view) }; + let (ready_tx, ready_rx) = mpsc::channel(); + let app = App::new(spec).args(Vec::new()).on_ready(move |_| { ready_tx.send(()).ok(); }); + let handle = app.handle(); + let worker = std::thread::spawn(move || { + let run = std::panic::catch_unwind(|| { + let started = rune::time::now(); + ready_rx.recv_timeout(Duration::from_secs(60)).expect("window ready"); + println!("popup_menu_macos: ready after {:?}", started.elapsed()); + std::thread::sleep(Duration::from_millis(300)); + run(&handle); + }); + handle.quit(); + run.is_ok() + }); + app.run(); + // The last step closes the window while its menu tracks: `run` returning means the + // tracking loop ended with it. + assert!(!TRACKING.load(Ordering::SeqCst), "the menu still tracked after the app ended"); + assert!(worker.join().unwrap(), "popup_menu_macos failed"); + assert_eq!(picks().len(), 4, "every menu answered once: {:?}", picks()); + println!("popup_menu_macos: ok"); + } + + /// Opens the menu over the button, by a click if clicks reach the window. + fn open_menu(handle: &AppHandle<State>, clicks: bool) { + if clicks { click(handle); } else { handle.update(|_, tx| tx.popup_menu(menu(), "theme", record)); } + assert!(wait("the menu", Duration::from_secs(3), || TRACKING.load(Ordering::SeqCst)), "the menu never opened"); + } + + fn run(handle: &AppHandle<State>) { + on_main(handle, |_, _| observe_menus()); + let before = FRAMES.load(Ordering::SeqCst); + std::thread::sleep(Duration::from_millis(500)); + println!("popup_menu_macos: {} frames in 500 ms before the menu", FRAMES.load(Ordering::SeqCst) - before); + + // 1. A click on the button opens the menu over it. + click(handle); + let clicked = wait("menu from a synthetic click", Duration::from_secs(2), || TRACKING.load(Ordering::SeqCst)); + if !clicked { + println!("popup_menu_macos: the synthetic click didn't reach the window; opening from an update"); + handle.update(|_, tx| tx.popup_menu(menu(), "theme", record)); + assert!(wait("menu from an update", Duration::from_secs(3), || TRACKING.load(Ordering::SeqCst)), "the menu never opened"); + } else { + assert_eq!(PRESSES.load(Ordering::SeqCst), 1, "one press, one menu"); + } + + // 2. Rune keeps drawing, and updates still land, while the menu tracks. + let before = FRAMES.load(Ordering::SeqCst); + std::thread::sleep(Duration::from_millis(500)); + let during = FRAMES.load(Ordering::SeqCst) - before; + println!("popup_menu_macos: {during} frames in 500 ms while the menu tracked"); + assert!(during >= 10, "frames stalled while the menu tracked ({during} in 500 ms)"); + let theme = on_main(handle, |s, _| s.theme.clone()); + assert_eq!(theme, "system", "an update runs mid-tracking and nothing is picked yet"); + assert!(TRACKING.load(Ordering::SeqCst)); + + // 3. Type-select "Dark" and pick it with Return. + key(handle, "d", 2); + key(handle, "\r", 36); + let typed = wait("pick from synthetic keys", Duration::from_secs(2), || !picks().is_empty()); + if !typed { + println!("popup_menu_macos: synthetic keys didn't reach the menu; picking through AppKit"); + drive(handle, Some(2)); + } + assert!(wait("the pick", Duration::from_secs(3), || !picks().is_empty()), "the pick never arrived"); + std::thread::sleep(Duration::from_millis(200)); + assert_eq!(picks(), [Some("dark".to_owned())], "the pick reaches the callback once"); + assert_eq!(on_main(handle, |s, _| s.theme.clone()), "dark"); + assert!(!TRACKING.load(Ordering::SeqCst)); + if clicked { assert_eq!(PRESSES.load(Ordering::SeqCst), 1, "the menu's mouse-up doesn't press the button again"); } + + // 4. The button presses again (no pointer capture left behind), and Escape dismisses. + if clicked { + click(handle); + assert!(wait("a second menu from a click", Duration::from_secs(2), || TRACKING.load(Ordering::SeqCst)), "the button didn't press after the menu"); + assert_eq!(PRESSES.load(Ordering::SeqCst), 2); + } else { + handle.update(|_, tx| tx.popup_menu(menu(), "theme", record)); + assert!(wait("a second menu", Duration::from_secs(3), || TRACKING.load(Ordering::SeqCst)), "the second menu never opened"); + } + key(handle, "\u{1b}", 53); + if !wait("dismissal from Escape", Duration::from_secs(2), || picks().len() == 2) { + println!("popup_menu_macos: Escape didn't reach the menu; dismissing through AppKit"); + drive(handle, None); + } + assert!(wait("the dismissal", Duration::from_secs(3), || picks().len() == 2), "the dismissal never arrived"); + std::thread::sleep(Duration::from_millis(200)); + assert_eq!(picks(), [Some("dark".to_owned()), None]); + let before = FRAMES.load(Ordering::SeqCst); + std::thread::sleep(Duration::from_millis(200)); + assert!(FRAMES.load(Ordering::SeqCst) > before, "frames keep running after the menu"); + println!("popup_menu_macos: click {}, keys {}", if clicked { "delivered" } else { "dropped" }, if typed { "delivered" } else { "dropped" }); + + // 5. Hiding the window while its menu tracks ends the menu and answers None. + open_menu(handle, clicked); + handle.hide(); + assert!(wait("the menu to end with the hide", Duration::from_secs(3), || !TRACKING.load(Ordering::SeqCst)), "the menu outlived its hidden window"); + assert!(wait("the hide's answer", Duration::from_secs(3), || picks().len() == 3)); + assert_eq!(picks()[2], None); + assert!(!handle.is_visible()); + handle.open(); + assert!(wait("the window back", Duration::from_secs(3), || handle.is_visible())); + std::thread::sleep(Duration::from_millis(300)); + + // 6. Closing it while its menu tracks answers None while the state lives, and the app + // (which doesn't keep running) ends; `main` checks the rest. + open_menu(handle, clicked); + handle.close(); + assert!(wait("the close's answer", Duration::from_secs(3), || picks().len() == 4)); + assert_eq!(picks()[3], None); + } +} diff --git a/app/vendor/rune/crates/rune/tests/secondary_window.rs b/app/vendor/rune/crates/rune/tests/secondary_window.rs new file mode 100644 index 0000000..cfb54c2 --- /dev/null +++ b/app/vendor/rune/crates/rune/tests/secondary_window.rs @@ -0,0 +1,82 @@ +//! A window added with `App::window` starts hidden, opens later with its own state, closes +//! by hiding without quitting the app, reopens with that state, and never keeps the app +//! running once the main window closes, closing with it. Opens native windows, so it only runs with +//! RUNE_GUI_TESTS=1 in a logged-in GUI session. + +use std::sync::{Mutex, atomic::{AtomicUsize, Ordering}}; +use std::time::Duration; +use rune::*; + +struct Main; +struct Settings { label: String } + +static RENDERS: Mutex<Vec<String>> = Mutex::new(Vec::new()); +static CLOSES: AtomicUsize = AtomicUsize::new(0); + +fn main_view(_: &Main, _: &mut Cx<Main>) -> El { text("main") } + +fn settings_view(s: &Settings, _: &mut Cx<Settings>) -> El { + RENDERS.lock().unwrap().push(s.label.clone()); + text(&s.label) +} + +fn wait(what: &str, f: impl Fn() -> bool) { + let start = rune::time::now(); + while !f() { + assert!(start.elapsed() < Duration::from_secs(5), "timed out waiting for {what}"); + std::thread::sleep(Duration::from_millis(5)); + } +} + +fn state<T: Send + 'static>(handle: &AppHandle<Settings>, f: impl FnOnce(&Settings) -> T + Send + 'static) -> T { + let (tx, rx) = std::sync::mpsc::channel(); + handle.update(move |s, _| { tx.send(f(s)).ok(); }); + rx.recv_timeout(Duration::from_secs(5)).expect("update ran") +} + +fn main() { + if std::env::var_os("RUNE_GUI_TESTS").is_none() { + println!("secondary_window: skipped (set RUNE_GUI_TESTS=1 in a GUI session)"); + return; + } + std::thread::spawn(|| { std::thread::sleep(Duration::from_secs(60)); eprintln!("timeout"); std::process::exit(2) }); + let mut app = App::new(AppSpec::new("secondary main", (240.0, 120.0), || Main, main_view)).args(Vec::new()); + let main = app.handle(); + let settings = App::new(AppSpec::new("secondary settings", (240.0, 120.0), || Settings { label: "initial".into() }, settings_view)) + .on_close(|_, _| { CLOSES.fetch_add(1, Ordering::SeqCst); }); + let (settings, window) = app.window(WindowSpec::from_app("settings", settings) + .options(WindowOptions { visible: false, ..Default::default() })); + let result = std::sync::Arc::new(Mutex::new(None)); + let out = result.clone(); + std::thread::spawn(move || { + let run = std::panic::catch_unwind(|| { + wait("main window", || main.is_visible()); + std::thread::sleep(Duration::from_millis(200)); + assert!(!settings.is_visible(), "visible: false starts hidden"); + + window.open(); + wait("settings open", || settings.is_visible()); + assert!(main.is_visible()); + settings.update(|s, _| s.label = "opened".into()); + wait("settings render", || RENDERS.lock().unwrap().iter().any(|l| l == "opened")); + + window.close(); + wait("settings close", || !settings.is_visible()); + std::thread::sleep(Duration::from_millis(200)); + assert_eq!(CLOSES.load(Ordering::SeqCst), 1, "close runs on_close once"); + assert!(main.is_visible(), "closing the secondary window keeps the app and main window"); + + settings.open(); + wait("settings reopen", || settings.is_visible()); + assert_eq!(state(&settings, |s| s.label.clone()), "opened", "reopening keeps the state"); + assert!(window.is_ready()); + }); + *out.lock().unwrap() = Some(run.is_ok()); + // The settings window is open and retained, yet the app ends with its main window. + main.close(); + }); + app.run(); + assert_eq!(*result.lock().unwrap(), Some(true), "secondary_window failed"); + assert_eq!(CLOSES.load(Ordering::SeqCst), 2, "the open settings window closes with the app"); + println!("secondary_window: ok"); +} diff --git a/app/vendor/rune/crates/rune/tests/shortcut_layout_macos.rs b/app/vendor/rune/crates/rune/tests/shortcut_layout_macos.rs new file mode 100644 index 0000000..3d1658e --- /dev/null +++ b/app/vendor/rune/crates/rune/tests/shortcut_layout_macos.rs @@ -0,0 +1,104 @@ +//! Main-thread native test: read installed layouts' data without selecting one or changing +//! user settings. +#[cfg(target_os = "macos")] +#[path = "../src/shortcuts/layout_macos.rs"] +mod layout_macos; + +#[cfg(target_os = "macos")] +#[allow(unsafe_code)] +mod tis { + use std::ffi::{CString, c_void}; + #[link(name = "Carbon", kind = "framework")] + unsafe extern "C" { + fn TISCreateInputSourceList(filter: *const c_void, all: u8) -> *const c_void; + fn TISGetInputSourceProperty(source: *const c_void, key: *const c_void) -> *const c_void; + static kTISPropertyInputSourceID: *const c_void; + static kTISPropertyUnicodeKeyLayoutData: *const c_void; + } + #[link(name = "CoreFoundation", kind = "framework")] + unsafe extern "C" { + static kCFTypeDictionaryKeyCallBacks: c_void; + static kCFTypeDictionaryValueCallBacks: c_void; + fn CFStringCreateWithCString(alloc: *const c_void, s: *const i8, encoding: u32) -> *const c_void; + fn CFDictionaryCreate(alloc: *const c_void, keys: *const *const c_void, values: *const *const c_void, + count: isize, key_callbacks: *const c_void, value_callbacks: *const c_void) -> *const c_void; + fn CFArrayGetCount(array: *const c_void) -> isize; + fn CFArrayGetValueAtIndex(array: *const c_void, index: isize) -> *const c_void; + fn CFDataGetBytePtr(data: *const c_void) -> *const u8; + fn CFRelease(value: *const c_void); + } + + /// Runs `f` with the installed layout `id`'s Unicode data, or returns None if it isn't installed. + pub fn with_layout<T>(id: &str, f: impl FnOnce(*const c_void) -> T) -> Option<T> { + let id = CString::new(id).unwrap(); + // SAFETY: called on the main thread; every CoreFoundation object created here is released once, + // `list` and `data` are checked non-null, and `data` stays alive for the duration of `f`. + unsafe { + let value = CFStringCreateWithCString(std::ptr::null(), id.as_ptr(), 0x0800_0100); + let key = kTISPropertyInputSourceID; + let filter = CFDictionaryCreate(std::ptr::null(), &key, &value, 1, + &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); + let list = TISCreateInputSourceList(filter, 1); + CFRelease(filter); + CFRelease(value); + if list.is_null() { return None; } + let found = (CFArrayGetCount(list) > 0).then(|| { + let data = TISGetInputSourceProperty(CFArrayGetValueAtIndex(list, 0), kTISPropertyUnicodeKeyLayoutData); + assert!(!data.is_null(), "{id:?} has no Unicode layout data"); + f(CFDataGetBytePtr(data).cast()) + }); + CFRelease(list); + found + } + } +} + +#[cfg(target_os = "macos")] +#[allow(unsafe_code)] +fn main() { + const CMD: u32 = 1 << 8; + const SHIFT: u32 = 1 << 9; + const OPTION: u32 = 1 << 11; + const CONTROL: u32 = 1 << 12; + const Q: u32 = 12; + const W: u32 = 13; + const K: u32 = 40; + + let shortcut: rune::Shortcut = "super+q".parse().unwrap(); + let current = layout_macos::label(Q, CMD).expect("current keyboard layout has Unicode data"); + assert_eq!(shortcut.keycaps().last(), Some(&current.to_uppercase())); + + let label = |layout, key, mods| { + // SAFETY: `layout` is a live `UCKeyboardLayout` pointer borrowed from `tis::with_layout`. + unsafe { layout_macos::chord_label(layout, key, mods) } + }; + let mut checked = Vec::new(); + let mut check = |id: &str, f: &dyn Fn(*const std::ffi::c_void)| match tis::with_layout(id, f) { + Some(()) => checked.push(id.to_owned()), + None => println!("SKIP: {id} isn't installed"), + }; + check("com.apple.keylayout.US", &|layout| { + assert_eq!(label(layout, K, CMD).as_deref(), Some("k")); + // ⌥ and ⇧ never substitute a character; ⌃'s control character falls back. + assert_eq!(label(layout, K, CMD | OPTION | SHIFT).as_deref(), Some("k")); + assert_eq!(label(layout, K, CONTROL).as_deref(), Some("k")); + }); + check("com.apple.keylayout.Dvorak", &|layout| { + assert_eq!(label(layout, Q, 0).as_deref(), Some("'")); + assert_eq!(label(layout, W, 0).as_deref(), Some(",")); + assert_eq!(label(layout, K, CMD).as_deref(), Some("t")); + assert_eq!(label(layout, K, CONTROL).as_deref(), Some("t")); + }); + check("com.apple.keylayout.DVORAK-QWERTYCMD", &|layout| { + assert_eq!(label(layout, K, 0).as_deref(), Some("t")); + assert_eq!(label(layout, K, CMD).as_deref(), Some("k")); + assert_eq!(label(layout, K, CMD | SHIFT | OPTION | CONTROL).as_deref(), Some("k")); + assert_eq!(label(layout, K, OPTION).as_deref(), Some("t")); + }); + assert_eq!(shortcut.physical_key(), rune::PhysicalKeyCode::KeyQ); + assert_eq!(shortcut.to_string(), "super+q"); + println!("PASS: current layout ⌘Q={current:?}; checked {checked:?}; stored binding super+q"); +} + +#[cfg(not(target_os = "macos"))] +fn main() {} diff --git a/app/vendor/rune/crates/rune/tests/support/mod.rs b/app/vendor/rune/crates/rune/tests/support/mod.rs new file mode 100644 index 0000000..ab3d16b --- /dev/null +++ b/app/vendor/rune/crates/rune/tests/support/mod.rs @@ -0,0 +1,77 @@ +#![allow(dead_code)] + +use rune::runtime::ElementInfo; +use rune::{Key, KeyEvent, Mods, Runtime}; + +pub fn find<S: 'static>(rt: &Runtime<S>, key: &str) -> ElementInfo { + rt.elements().into_iter().find(|e| e.key.as_deref() == Some(key)).unwrap_or_else(|| panic!("{key}")) +} + +pub fn centre(e: &ElementInfo) -> (f32, f32) { + (e.rect[0] + e.rect[2] / 2.0, e.rect[1] + e.rect[3] / 2.0) +} + +pub fn tick<S: 'static>(rt: &mut Runtime<S>) { + rt.frame(1.0 / 60.0); +} + +pub fn wait<S: 'static>(rt: &mut Runtime<S>) { + rt.frame(1.0); +} + +pub fn click<S: 'static>(rt: &mut Runtime<S>, (x, y): (f32, f32)) { + rt.pointer_move(x, y); + rt.pointer_down(x, y); + rt.pointer_up(x, y); + tick(rt); +} + +pub fn drag<S: 'static>(rt: &mut Runtime<S>, (x0, y0): (f32, f32), (x1, y1): (f32, f32)) { + rt.pointer_move(x0, y0); + rt.pointer_down(x0, y0); + tick(rt); + for k in 1..=6 { + let f = k as f32 / 6.0; + rt.pointer_move(x0 + (x1 - x0) * f, y0 + (y1 - y0) * f); + tick(rt); + } + rt.pointer_up(x1, y1); + tick(rt); +} + +pub fn command<S: 'static>(rt: &mut Runtime<S>, c: char) { + rt.key(KeyEvent { key: Key::Command(c), mods: Mods { cmd: true, ..Mods::default() } }); + tick(rt); +} + +/// Centres (points) of the glyphs drawn inside element `key`, in reading order by line. +pub fn glyphs<S: 'static>(rt: &Runtime<S>, key: &str) -> Vec<(f32, f32)> { + glyphs_at(rt, &find(rt, key).path) +} + +/// [`glyphs`] for the element at `path`. +pub fn glyphs_at<S: 'static>(rt: &Runtime<S>, path: &str) -> Vec<(f32, f32)> { + let e = rt.elements().into_iter().find(|e| e.path == path).unwrap_or_else(|| panic!("{path}")); + let mut out: Vec<(f32, f32)> = rt + .instances + .iter() + .filter(|i| i.params[1] == rune::render::KIND_GLYPH) + .map(|i| ((i.rect[0] + i.rect[2] / 2.0) / 2.0, (i.rect[1] + i.rect[3] / 2.0) / 2.0)) + .filter(|&(x, y)| x >= e.rect[0] && x <= e.rect[0] + e.rect[2] && y >= e.rect[1] && y <= e.rect[1] + e.rect[3]) + .collect(); + // Rows by ink centre, a new row when the centre jumps by more than a third of a line: a + // tall glyph's centre sits a little higher than a short one's in every rasterizer. + out.sort_by(|a, b| a.1.total_cmp(&b.1)); + let mut row = (0, f32::NEG_INFINITY); + let mut rows: Vec<(usize, (f32, f32))> = out + .into_iter() + .map(|g| { + if g.1 - row.1 > 6.0 { + row = (row.0 + 1, g.1); + } + (row.0, g) + }) + .collect(); + rows.sort_by(|a, b| (a.0, a.1.0).partial_cmp(&(b.0, b.1.0)).unwrap()); + rows.into_iter().map(|r| r.1).collect() +} diff --git a/app/vendor/rune/crates/rune/tests/video_gui.rs b/app/vendor/rune/crates/rune/tests/video_gui.rs new file mode 100644 index 0000000..6d99e49 --- /dev/null +++ b/app/vendor/rune/crates/rune/tests/video_gui.rs @@ -0,0 +1,177 @@ +//! A window plays a short clip muted through AVPlayer: the poster arrives before play, frames +//! advance and present while playing, the clip ends, nothing redraws while stopped, and +//! looping keeps frames coming. Then an audio clip with no element loads, plays, advances and +//! ends. The audio is silent and muted, so nothing is ever heard. Opens a native window, so it +//! only runs with RUNE_GUI_TESTS=1 in a logged-in GUI session on macOS. + +use rune::*; +use std::collections::BTreeSet; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::{Arc, Mutex, OnceLock}; +use std::time::Duration; + +struct Gui; + +static CLIP: OnceLock<Video> = OnceLock::new(); +static FRAMES: Mutex<BTreeSet<u64>> = Mutex::new(BTreeSet::new()); + +fn clip() -> &'static Video { + CLIP.get_or_init(|| Video::file(concat!(env!("CARGO_MANIFEST_DIR"), "/tests/fixtures/rgbw.mp4"))) +} + +fn view(_: &Gui, _: &mut Cx<Gui>) -> El { + el().key("video").w(320.0).h(180.0).video(clip(), SurfaceFit::Fit) +} + +fn wait(what: &str, limit: Duration, f: impl Fn() -> bool) { + let start = rune::time::now(); + while !f() { + assert!( + start.elapsed() < limit, + "timed out waiting for {what}: {:?}, draws {:?}, frames {}, error {:?}", + clip(), + clip().surface().counts(), + frames(), + clip().surface().last_error() + ); + std::thread::sleep(Duration::from_millis(5)); + } +} + +fn wait_for(what: &str, limit: Duration, f: impl Fn() -> bool) { + let start = rune::time::now(); + while !f() { + assert!(start.elapsed() < limit, "timed out waiting for {what}"); + std::thread::sleep(Duration::from_millis(5)); + } +} + +fn frames() -> usize { + FRAMES.lock().unwrap().len() +} + +fn main() { + if std::env::var_os("RUNE_GUI_TESTS").is_none() || !cfg!(target_os = "macos") { + println!("video_gui: skipped (set RUNE_GUI_TESTS=1 in a macOS GUI session)"); + return; + } + std::thread::spawn(|| { + std::thread::sleep(Duration::from_secs(60)); + eprintln!("timeout"); + std::process::exit(2) + }); + clip().surface().set_observer(Arc::new(|t| { + // Runs in wgpu's work-done callback: no panic there, even on a poisoned lock. + FRAMES.lock().unwrap_or_else(|e| e.into_inner()).insert(t.frame_id); + })); + let app = App::new(AppSpec::new("video gui", (320.0, 180.0), || Gui, view)).args(Vec::new()); + let main = app.handle(); + let result = Arc::new(Mutex::new(None)); + let out = result.clone(); + std::thread::spawn(move || { + let run = std::panic::catch_unwind(|| { + let clip = clip(); + let secs = Duration::from_secs; + wait("main window", secs(5), || main.is_visible()); + wait("poster", secs(5), || clip.state() == PlayerState::Ready && frames() >= 1); + assert_eq!(clip.natural_size(), Some((64, 36))); + assert!((clip.duration().unwrap() - 1.0).abs() < 0.01, "{:?}", clip.duration()); + assert!(clip.muted(), "videos start muted"); + + // The load re-runs the view once; after that the window goes idle. + std::thread::sleep(Duration::from_millis(300)); + let quiet = clip.surface().counts(); + std::thread::sleep(Duration::from_millis(400)); + assert_eq!(clip.surface().counts(), quiet, "a loaded, paused video requests no frames"); + + let before = frames(); + let presented = clip.surface().counts().1; + clip.play(); + wait("playing", secs(5), || clip.state() == PlayerState::Playing); + wait("ended", secs(5), || clip.state() == PlayerState::Ended); + let played = frames() - before; + assert!(played >= 3, "the four-frame clip presented {played} new frames"); + assert!(clip.surface().counts().1 > presented, "draws completed while playing"); + assert!((clip.time() - 1.0).abs() < 0.1, "ends at the end: {}", clip.time()); + + std::thread::sleep(Duration::from_millis(300)); + let quiet = clip.surface().counts(); + std::thread::sleep(Duration::from_millis(600)); + assert_eq!(clip.surface().counts(), quiet, "an ended video requests no frames"); + + let before = frames(); + clip.set_looping(true); + clip.play(); + wait("playing again", secs(5), || clip.state() == PlayerState::Playing); + std::thread::sleep(Duration::from_millis(2500)); + assert_eq!(clip.state(), PlayerState::Playing, "looping keeps playing"); + let looped = frames() - before; + assert!(looped >= 6, "two and a half loops presented {looped} new frames"); + + clip.pause(); + wait("paused", secs(5), || clip.state() == PlayerState::Ready); + // The frame that applies the pause reads where the player stopped. + std::thread::sleep(Duration::from_millis(200)); + let at = clip.time(); + let quiet = clip.surface().counts(); + std::thread::sleep(Duration::from_millis(300)); + assert_eq!(clip.time(), at, "paused time holds"); + assert_eq!(clip.surface().counts(), quiet, "a paused video requests no frames"); + + // Two of the four 0.25 s frames on from where it paused, so a new frame shows. + let target = ((at / 0.25).floor() + 2.0) % 4.0 * 0.25 + 0.1; + let before = frames(); + clip.seek(target); + wait("seek frame", secs(3), || frames() > before); + std::thread::sleep(Duration::from_millis(300)); + assert!((clip.time() - target).abs() < 0.01, "a paused seek lands: {} for {target}", clip.time()); + assert_eq!(clip.state(), PlayerState::Ready); + // A paused seek within the frame on screen has no frame to wait for: no redraws. + clip.seek(target + 0.05); + std::thread::sleep(Duration::from_millis(200)); + let quiet = clip.surface().counts(); + std::thread::sleep(Duration::from_millis(300)); + assert_eq!(clip.surface().counts(), quiet, "a same-frame paused seek requests no frames"); + assert!((clip.time() - target - 0.05).abs() < 0.01, "{}", clip.time()); + println!("video_gui: {played} frames in one play, {looped} while looping"); + + let wakes = Arc::new(AtomicUsize::new(0)); + let heard = wakes.clone(); + let tap = Player::audio(concat!(env!("CARGO_MANIFEST_DIR"), "/tests/fixtures/silence.m4a")); + assert!(!tap.muted(), "audio starts audible"); + tap.set_muted(true); + tap.set_waker(Arc::new(move || { + heard.fetch_add(1, Ordering::Relaxed); + })); + wait_for("audio duration", secs(5), || tap.state() == PlayerState::Ready); + let duration = tap.duration().unwrap(); + assert!((duration - 1.0).abs() < 0.1, "{duration}"); + assert_eq!(tap.natural_size(), None); + let draws = clip.surface().counts(); + tap.play(); + wait_for("audio playing", secs(5), || tap.state() == PlayerState::Playing); + wait_for("audio time advancing", secs(5), || tap.time() > 0.2); + assert_eq!(tap.state(), PlayerState::Playing); + wait_for("audio ended", secs(5), || tap.state() == PlayerState::Ended); + assert!((tap.time() - duration).abs() < 0.1, "ends at the end: {}", tap.time()); + assert!(tap.muted(), "stayed muted"); + assert!(wakes.load(Ordering::Relaxed) >= 2, "the waker heard the load and the end"); + assert_eq!(clip.surface().counts(), draws, "audio drew nothing"); + + // AVFoundation reads no Ogg video, whatever the features. + let ogv = Player::audio("https://example.com/clip.ogv"); + assert!(matches!(ogv.state(), PlayerState::Failed(e) if e.contains(".ogv")), "{:?}", ogv.state()); + #[cfg(feature = "ogg-audio")] + { + let ogg = Player::audio(concat!(env!("CARGO_MANIFEST_DIR"), "/tests/fixtures/sine-vorbis.ogg")); + wait_for("ogg audio opens", secs(5), || ogg.state() == PlayerState::Ready); + } + println!("video_gui: audio played {duration:.2} s to the end, muted"); + }); + *out.lock().unwrap() = Some(run.is_ok()); + main.close(); + }); + app.run(); + assert_eq!(*result.lock().unwrap(), Some(true), "video_gui failed"); + println!("video_gui: ok"); +} diff --git a/app/vendor/rune/demo/fx/blend.png b/app/vendor/rune/demo/fx/blend.png new file mode 100644 index 0000000..5ff2a2b Binary files /dev/null and b/app/vendor/rune/demo/fx/blend.png differ diff --git a/app/vendor/rune/demo/fx/distort-reduced.png b/app/vendor/rune/demo/fx/distort-reduced.png new file mode 100644 index 0000000..4ffe115 Binary files /dev/null and b/app/vendor/rune/demo/fx/distort-reduced.png differ diff --git a/app/vendor/rune/demo/fx/distort.png b/app/vendor/rune/demo/fx/distort.png new file mode 100644 index 0000000..42d1e09 Binary files /dev/null and b/app/vendor/rune/demo/fx/distort.png differ diff --git a/app/vendor/rune/demo/fx/dither-reduced.png b/app/vendor/rune/demo/fx/dither-reduced.png new file mode 100644 index 0000000..fc97800 Binary files /dev/null and b/app/vendor/rune/demo/fx/dither-reduced.png differ diff --git a/app/vendor/rune/demo/fx/dither.png b/app/vendor/rune/demo/fx/dither.png new file mode 100644 index 0000000..a4255bf Binary files /dev/null and b/app/vendor/rune/demo/fx/dither.png differ diff --git a/app/vendor/rune/demo/fx/electric-reduced.png b/app/vendor/rune/demo/fx/electric-reduced.png new file mode 100644 index 0000000..2c53bd2 Binary files /dev/null and b/app/vendor/rune/demo/fx/electric-reduced.png differ diff --git a/app/vendor/rune/demo/fx/electric.png b/app/vendor/rune/demo/fx/electric.png new file mode 100644 index 0000000..90f1537 Binary files /dev/null and b/app/vendor/rune/demo/fx/electric.png differ diff --git a/app/vendor/rune/demo/fx/extras-reduced.png b/app/vendor/rune/demo/fx/extras-reduced.png new file mode 100644 index 0000000..71a8d74 Binary files /dev/null and b/app/vendor/rune/demo/fx/extras-reduced.png differ diff --git a/app/vendor/rune/demo/fx/extras.png b/app/vendor/rune/demo/fx/extras.png new file mode 100644 index 0000000..d066cdc Binary files /dev/null and b/app/vendor/rune/demo/fx/extras.png differ diff --git a/app/vendor/rune/demo/fx/fill-presets-reduced.png b/app/vendor/rune/demo/fx/fill-presets-reduced.png new file mode 100644 index 0000000..95dd4ef Binary files /dev/null and b/app/vendor/rune/demo/fx/fill-presets-reduced.png differ diff --git a/app/vendor/rune/demo/fx/fill-presets.png b/app/vendor/rune/demo/fx/fill-presets.png new file mode 100644 index 0000000..7d40b21 Binary files /dev/null and b/app/vendor/rune/demo/fx/fill-presets.png differ diff --git a/app/vendor/rune/demo/fx/fills-reduced.png b/app/vendor/rune/demo/fx/fills-reduced.png new file mode 100644 index 0000000..0dd2b23 Binary files /dev/null and b/app/vendor/rune/demo/fx/fills-reduced.png differ diff --git a/app/vendor/rune/demo/fx/fills.png b/app/vendor/rune/demo/fx/fills.png new file mode 100644 index 0000000..fd06159 Binary files /dev/null and b/app/vendor/rune/demo/fx/fills.png differ diff --git a/app/vendor/rune/demo/fx/fire-reduced.png b/app/vendor/rune/demo/fx/fire-reduced.png new file mode 100644 index 0000000..78939db Binary files /dev/null and b/app/vendor/rune/demo/fx/fire-reduced.png differ diff --git a/app/vendor/rune/demo/fx/fire.png b/app/vendor/rune/demo/fx/fire.png new file mode 100644 index 0000000..8103a6f Binary files /dev/null and b/app/vendor/rune/demo/fx/fire.png differ diff --git a/app/vendor/rune/demo/fx/fluted-glass-reduced.png b/app/vendor/rune/demo/fx/fluted-glass-reduced.png new file mode 100644 index 0000000..8fe3f98 Binary files /dev/null and b/app/vendor/rune/demo/fx/fluted-glass-reduced.png differ diff --git a/app/vendor/rune/demo/fx/fluted-glass.png b/app/vendor/rune/demo/fx/fluted-glass.png new file mode 100644 index 0000000..c4bb23e Binary files /dev/null and b/app/vendor/rune/demo/fx/fluted-glass.png differ diff --git a/app/vendor/rune/demo/fx/glow-reduced.png b/app/vendor/rune/demo/fx/glow-reduced.png new file mode 100644 index 0000000..803c2ba Binary files /dev/null and b/app/vendor/rune/demo/fx/glow-reduced.png differ diff --git a/app/vendor/rune/demo/fx/glow-strip.png b/app/vendor/rune/demo/fx/glow-strip.png new file mode 100644 index 0000000..865c215 Binary files /dev/null and b/app/vendor/rune/demo/fx/glow-strip.png differ diff --git a/app/vendor/rune/demo/fx/glow.png b/app/vendor/rune/demo/fx/glow.png new file mode 100644 index 0000000..857dc0f Binary files /dev/null and b/app/vendor/rune/demo/fx/glow.png differ diff --git a/app/vendor/rune/demo/fx/grain-gradient-reduced.png b/app/vendor/rune/demo/fx/grain-gradient-reduced.png new file mode 100644 index 0000000..f5cac9b Binary files /dev/null and b/app/vendor/rune/demo/fx/grain-gradient-reduced.png differ diff --git a/app/vendor/rune/demo/fx/grain-gradient.png b/app/vendor/rune/demo/fx/grain-gradient.png new file mode 100644 index 0000000..093732f Binary files /dev/null and b/app/vendor/rune/demo/fx/grain-gradient.png differ diff --git a/app/vendor/rune/demo/fx/in-layer.png b/app/vendor/rune/demo/fx/in-layer.png new file mode 100644 index 0000000..91c0652 Binary files /dev/null and b/app/vendor/rune/demo/fx/in-layer.png differ diff --git a/app/vendor/rune/demo/fx/liquid-metal-reduced.png b/app/vendor/rune/demo/fx/liquid-metal-reduced.png new file mode 100644 index 0000000..6f731e4 Binary files /dev/null and b/app/vendor/rune/demo/fx/liquid-metal-reduced.png differ diff --git a/app/vendor/rune/demo/fx/liquid-metal.png b/app/vendor/rune/demo/fx/liquid-metal.png new file mode 100644 index 0000000..584b2e7 Binary files /dev/null and b/app/vendor/rune/demo/fx/liquid-metal.png differ diff --git a/app/vendor/rune/demo/fx/mesh-gradient-reduced.png b/app/vendor/rune/demo/fx/mesh-gradient-reduced.png new file mode 100644 index 0000000..5743650 Binary files /dev/null and b/app/vendor/rune/demo/fx/mesh-gradient-reduced.png differ diff --git a/app/vendor/rune/demo/fx/mesh-gradient.png b/app/vendor/rune/demo/fx/mesh-gradient.png new file mode 100644 index 0000000..31ffae2 Binary files /dev/null and b/app/vendor/rune/demo/fx/mesh-gradient.png differ diff --git a/app/vendor/rune/demo/fx/motion-quarter-speed.mp4 b/app/vendor/rune/demo/fx/motion-quarter-speed.mp4 new file mode 100644 index 0000000..f70c5c3 Binary files /dev/null and b/app/vendor/rune/demo/fx/motion-quarter-speed.mp4 differ diff --git a/app/vendor/rune/demo/fx/motion-reduced.png b/app/vendor/rune/demo/fx/motion-reduced.png new file mode 100644 index 0000000..62bfab5 Binary files /dev/null and b/app/vendor/rune/demo/fx/motion-reduced.png differ diff --git a/app/vendor/rune/demo/fx/motion.png b/app/vendor/rune/demo/fx/motion.png new file mode 100644 index 0000000..217cfa9 Binary files /dev/null and b/app/vendor/rune/demo/fx/motion.png differ diff --git a/app/vendor/rune/demo/fx/plastic.png b/app/vendor/rune/demo/fx/plastic.png new file mode 100644 index 0000000..29c1a1e Binary files /dev/null and b/app/vendor/rune/demo/fx/plastic.png differ diff --git a/app/vendor/rune/demo/fx/pulse-reduced.png b/app/vendor/rune/demo/fx/pulse-reduced.png new file mode 100644 index 0000000..87b8da1 Binary files /dev/null and b/app/vendor/rune/demo/fx/pulse-reduced.png differ diff --git a/app/vendor/rune/demo/fx/pulse.png b/app/vendor/rune/demo/fx/pulse.png new file mode 100644 index 0000000..8e0699a Binary files /dev/null and b/app/vendor/rune/demo/fx/pulse.png differ diff --git a/app/vendor/rune/demo/fx/timings.md b/app/vendor/rune/demo/fx/timings.md new file mode 100644 index 0000000..380c76a --- /dev/null +++ b/app/vendor/rune/demo/fx/timings.md @@ -0,0 +1,50 @@ +| effect | covered px (2x) | reads/px | noise/px | backdrop | GPU ms per draw (median; 10 draws/pass) | +|---|---:|---:|---:|:-:|---:| +| glow soft | 960000 | 0 | 0 | | 0.229 | +| glow neon | 960000 | 0 | 0 | | 0.205 | +| glow aura | 960000 | 0 | 1 | | 0.398 | +| glow mask (text) | 960000 | 13 | 0 | | 0.343 | +| pulse radar | 960000 | 0 | 0 | | 0.276 | +| pulse breathe | 960000 | 0 | 0 | | 0.134 | +| pulse heartbeat | 960000 | 0 | 0 | | 0.322 | +| pulse ripple | 543696 | 0 | 0 | | 0.086 | +| electric arc (3 strands) | 960000 | 37 | 0 | | 0.707 | +| electric border | 960000 | 43 | 0 | | 0.682 | +| electric charged | 960000 | 37 | 0 | | 0.470 | +| fire top + 16 embers | 644480 | 32 | 8 | | 1.839 | +| fire plasma border | 960000 | 0 | 3 | | 1.045 | +| fire heat (UI) | 634752 | 8 | 8 | | 1.217 | +| distort heat haze | 960000 | 1 | 6 | yes | 1.153 | +| distort shockwave | 960000 | 3 | 0 | yes | 0.155 | +| distort lens | 960000 | 12 | 0 | yes | 0.381 | +| distort lens + frost | 960000 | 12 | 0 | yes | 0.650 | +| distort CRT | 960000 | 7 | 0 | yes | 0.199 | +| distort chroma split | 960000 | 3 | 0 | yes | 0.118 | +| shimmer (shape) | 960000 | 0 | 0 | | 0.148 | +| sparkles x9 | 960000 | 12 | 0 | | 0.270 | +| aurora | 960000 | 12 | 3 | | 0.781 | +| grain | 960000 | 0 | 0 | | 0.150 | +| fill liquid metal | 543696 | 0 | 8 | | 0.951 | +| fill liquid metal, still | 543696 | 0 | 0 | | 0.217 | +| fill liquid metal border 8 | 543696 | 0 | 8 | | 0.191 | +| fill liquid metal, element anchor | 543696 | 0 | 8 | | 0.937 | +| fill plastic glossy | 543696 | 0 | 0 | | 0.150 | +| fill plastic matte | 543696 | 0 | 0 | | 0.150 | +| fill plastic border 8 | 543696 | 0 | 0 | | 0.062 | +| fill mesh gradient (5 colours) | 543696 | 10 | 2 | | 0.382 | +| fill dither bayer (ramp) | 543696 | 1 | 0 | | 0.158 | +| fill dither blue noise (radial) | 543696 | 2 | 0 | | 0.152 | +| fill dither palette (noise) | 543696 | 1 | 3 | | 0.458 | +| fill dither backdrop | 543696 | 2 | 0 | yes | 0.158 | +| fill grain gradient | 543696 | 2 | 0 | | 0.186 | +| fill grain gradient conic, colour | 543696 | 2 | 0 | | 0.265 | +| fill fluted glass | 543696 | 3 | 0 | yes | 0.129 | +| fill fluted glass + frost | 543696 | 6 | 0 | yes | 0.249 | +| fill metaballs x6 | 543696 | 12 | 0 | | 0.289 | +| fill swirl | 543696 | 2 | 9 | | 1.055 | +| fill voronoi | 543696 | 1 | 0 | | 1.177 | +| fill waves (5 bands) | 543696 | 5 | 0 | | 0.305 | +| fill halftone (radial) | 543696 | 0 | 0 | | 0.306 | +| fill halftone backdrop | 543696 | 4 | 0 | yes | 0.344 | +| motion shutter (fling peak) | 467190 | 48 | 0 | | 1.091 | +| motion directional | 468234 | 32 | 0 | | 0.893 | diff --git a/app/vendor/rune/demo/kit/diff-split-dark.png b/app/vendor/rune/demo/kit/diff-split-dark.png new file mode 100644 index 0000000..b345be5 Binary files /dev/null and b/app/vendor/rune/demo/kit/diff-split-dark.png differ diff --git a/app/vendor/rune/demo/kit/diff-split-light.png b/app/vendor/rune/demo/kit/diff-split-light.png new file mode 100644 index 0000000..c111164 Binary files /dev/null and b/app/vendor/rune/demo/kit/diff-split-light.png differ diff --git a/app/vendor/rune/demo/kit/diff-unified-dark.png b/app/vendor/rune/demo/kit/diff-unified-dark.png new file mode 100644 index 0000000..bb226de Binary files /dev/null and b/app/vendor/rune/demo/kit/diff-unified-dark.png differ diff --git a/app/vendor/rune/demo/kit/diff-unified-light.png b/app/vendor/rune/demo/kit/diff-unified-light.png new file mode 100644 index 0000000..dcf663d Binary files /dev/null and b/app/vendor/rune/demo/kit/diff-unified-light.png differ diff --git a/app/vendor/rune/demo/kit/diff-unified-scrolled.png b/app/vendor/rune/demo/kit/diff-unified-scrolled.png new file mode 100644 index 0000000..27c2db4 Binary files /dev/null and b/app/vendor/rune/demo/kit/diff-unified-scrolled.png differ diff --git a/app/vendor/rune/demo/kit/glyphs.png b/app/vendor/rune/demo/kit/glyphs.png new file mode 100644 index 0000000..595aba9 Binary files /dev/null and b/app/vendor/rune/demo/kit/glyphs.png differ diff --git a/app/vendor/rune/demo/kit/index-dark.png b/app/vendor/rune/demo/kit/index-dark.png new file mode 100644 index 0000000..4599ff1 Binary files /dev/null and b/app/vendor/rune/demo/kit/index-dark.png differ diff --git a/app/vendor/rune/demo/kit/index-light.png b/app/vendor/rune/demo/kit/index-light.png new file mode 100644 index 0000000..27de265 Binary files /dev/null and b/app/vendor/rune/demo/kit/index-light.png differ diff --git a/app/vendor/rune/demo/kit/markdown-code-dark.png b/app/vendor/rune/demo/kit/markdown-code-dark.png new file mode 100644 index 0000000..c05691a Binary files /dev/null and b/app/vendor/rune/demo/kit/markdown-code-dark.png differ diff --git a/app/vendor/rune/demo/kit/markdown-code-light.png b/app/vendor/rune/demo/kit/markdown-code-light.png new file mode 100644 index 0000000..baa00a3 Binary files /dev/null and b/app/vendor/rune/demo/kit/markdown-code-light.png differ diff --git a/app/vendor/rune/demo/kit/pills-styled.png b/app/vendor/rune/demo/kit/pills-styled.png new file mode 100644 index 0000000..ed5846c Binary files /dev/null and b/app/vendor/rune/demo/kit/pills-styled.png differ diff --git a/app/vendor/rune/demo/kit/popup-list.png b/app/vendor/rune/demo/kit/popup-list.png new file mode 100644 index 0000000..082ba49 Binary files /dev/null and b/app/vendor/rune/demo/kit/popup-list.png differ diff --git a/app/vendor/rune/demo/kit/rich-editor.png b/app/vendor/rune/demo/kit/rich-editor.png new file mode 100644 index 0000000..9872335 Binary files /dev/null and b/app/vendor/rune/demo/kit/rich-editor.png differ diff --git a/app/vendor/rune/demo/kit/scroll-x.png b/app/vendor/rune/demo/kit/scroll-x.png new file mode 100644 index 0000000..09e510b Binary files /dev/null and b/app/vendor/rune/demo/kit/scroll-x.png differ diff --git a/app/vendor/rune/demo/kit/shell-dark.png b/app/vendor/rune/demo/kit/shell-dark.png new file mode 100644 index 0000000..bd94508 Binary files /dev/null and b/app/vendor/rune/demo/kit/shell-dark.png differ diff --git a/app/vendor/rune/demo/kit/shell-light.png b/app/vendor/rune/demo/kit/shell-light.png new file mode 100644 index 0000000..60f4162 Binary files /dev/null and b/app/vendor/rune/demo/kit/shell-light.png differ diff --git a/app/vendor/rune/demo/kit/shell-page.png b/app/vendor/rune/demo/kit/shell-page.png new file mode 100644 index 0000000..ea61b0a Binary files /dev/null and b/app/vendor/rune/demo/kit/shell-page.png differ diff --git a/app/vendor/rune/demo/kit/shell-peek.png b/app/vendor/rune/demo/kit/shell-peek.png new file mode 100644 index 0000000..3935320 Binary files /dev/null and b/app/vendor/rune/demo/kit/shell-peek.png differ diff --git a/app/vendor/rune/demo/kit/side-components-card--warning-dark.png b/app/vendor/rune/demo/kit/side-components-card--warning-dark.png new file mode 100644 index 0000000..ac96de0 Binary files /dev/null and b/app/vendor/rune/demo/kit/side-components-card--warning-dark.png differ diff --git a/app/vendor/rune/demo/kit/side-components-card--warning-light.png b/app/vendor/rune/demo/kit/side-components-card--warning-light.png new file mode 100644 index 0000000..90133f4 Binary files /dev/null and b/app/vendor/rune/demo/kit/side-components-card--warning-light.png differ diff --git a/app/vendor/rune/demo/kit/side-ui-button--all-states-dark.png b/app/vendor/rune/demo/kit/side-ui-button--all-states-dark.png new file mode 100644 index 0000000..2fb5910 Binary files /dev/null and b/app/vendor/rune/demo/kit/side-ui-button--all-states-dark.png differ diff --git a/app/vendor/rune/demo/kit/side-ui-button--all-states-light.png b/app/vendor/rune/demo/kit/side-ui-button--all-states-light.png new file mode 100644 index 0000000..9b08dba Binary files /dev/null and b/app/vendor/rune/demo/kit/side-ui-button--all-states-light.png differ diff --git a/app/vendor/rune/demo/kit/side-ui-menu--rich-dark.png b/app/vendor/rune/demo/kit/side-ui-menu--rich-dark.png new file mode 100644 index 0000000..085fbcd Binary files /dev/null and b/app/vendor/rune/demo/kit/side-ui-menu--rich-dark.png differ diff --git a/app/vendor/rune/demo/kit/side-ui-menu--rich-light.png b/app/vendor/rune/demo/kit/side-ui-menu--rich-light.png new file mode 100644 index 0000000..6b24b89 Binary files /dev/null and b/app/vendor/rune/demo/kit/side-ui-menu--rich-light.png differ diff --git a/app/vendor/rune/demo/kit/side-ui-select--grouped-dark.png b/app/vendor/rune/demo/kit/side-ui-select--grouped-dark.png new file mode 100644 index 0000000..a5cea01 Binary files /dev/null and b/app/vendor/rune/demo/kit/side-ui-select--grouped-dark.png differ diff --git a/app/vendor/rune/demo/kit/side-ui-select--grouped-light.png b/app/vendor/rune/demo/kit/side-ui-select--grouped-light.png new file mode 100644 index 0000000..e36b508 Binary files /dev/null and b/app/vendor/rune/demo/kit/side-ui-select--grouped-light.png differ diff --git a/app/vendor/rune/demo/kit/side-ui-text-input--states-dark.png b/app/vendor/rune/demo/kit/side-ui-text-input--states-dark.png new file mode 100644 index 0000000..b61461d Binary files /dev/null and b/app/vendor/rune/demo/kit/side-ui-text-input--states-dark.png differ diff --git a/app/vendor/rune/demo/kit/side-ui-text-input--states-light.png b/app/vendor/rune/demo/kit/side-ui-text-input--states-light.png new file mode 100644 index 0000000..5cd3bd1 Binary files /dev/null and b/app/vendor/rune/demo/kit/side-ui-text-input--states-light.png differ diff --git a/app/vendor/rune/demo/kit/side-ui-toast--all-examples-dark.png b/app/vendor/rune/demo/kit/side-ui-toast--all-examples-dark.png new file mode 100644 index 0000000..11edb47 Binary files /dev/null and b/app/vendor/rune/demo/kit/side-ui-toast--all-examples-dark.png differ diff --git a/app/vendor/rune/demo/kit/side-ui-toast--all-examples-light.png b/app/vendor/rune/demo/kit/side-ui-toast--all-examples-light.png new file mode 100644 index 0000000..168961d Binary files /dev/null and b/app/vendor/rune/demo/kit/side-ui-toast--all-examples-light.png differ diff --git a/app/vendor/rune/demo/kit/table-dark.png b/app/vendor/rune/demo/kit/table-dark.png new file mode 100644 index 0000000..5d720c4 Binary files /dev/null and b/app/vendor/rune/demo/kit/table-dark.png differ diff --git a/app/vendor/rune/demo/kit/table-light.png b/app/vendor/rune/demo/kit/table-light.png new file mode 100644 index 0000000..b719c1e Binary files /dev/null and b/app/vendor/rune/demo/kit/table-light.png differ diff --git a/app/vendor/rune/demo/kit/tree-dark.png b/app/vendor/rune/demo/kit/tree-dark.png new file mode 100644 index 0000000..49262ba Binary files /dev/null and b/app/vendor/rune/demo/kit/tree-dark.png differ diff --git a/app/vendor/rune/demo/kit/tree-light.png b/app/vendor/rune/demo/kit/tree-light.png new file mode 100644 index 0000000..0f37420 Binary files /dev/null and b/app/vendor/rune/demo/kit/tree-light.png differ diff --git a/app/vendor/rune/demo/lab/flashlight.png b/app/vendor/rune/demo/lab/flashlight.png new file mode 100644 index 0000000..622acb6 Binary files /dev/null and b/app/vendor/rune/demo/lab/flashlight.png differ diff --git a/app/vendor/rune/demo/lab/keys.png b/app/vendor/rune/demo/lab/keys.png new file mode 100644 index 0000000..ef0bf36 Binary files /dev/null and b/app/vendor/rune/demo/lab/keys.png differ diff --git a/app/vendor/rune/demo/lab/lens.png b/app/vendor/rune/demo/lab/lens.png new file mode 100644 index 0000000..01093b9 Binary files /dev/null and b/app/vendor/rune/demo/lab/lens.png differ diff --git a/app/vendor/rune/demo/lab/pulses.png b/app/vendor/rune/demo/lab/pulses.png new file mode 100644 index 0000000..3d3d807 Binary files /dev/null and b/app/vendor/rune/demo/lab/pulses.png differ diff --git a/app/vendor/rune/demo/light/bench.json b/app/vendor/rune/demo/light/bench.json new file mode 100644 index 0000000..abcc4c3 --- /dev/null +++ b/app/vendor/rune/demo/light/bench.json @@ -0,0 +1,8 @@ +{ + "1 light": {"field": 0.1561, "shadows": 0.1748, "gi": 0.0067, "frame_wall": 0.9417}, + "4 lights": {"field": 0.0670, "shadows": 0.3078, "gi": 0.0037, "frame_wall": 1.0391}, + "8 lights": {"field": 0.0627, "shadows": 0.5711, "gi": 0.0036, "frame_wall": 1.6493}, + "4 lights + shafts": {"field": 0.0632, "shadows": 1.3841, "gi": 0.0036, "frame_wall": 2.1980}, + "GI only (emitters)": {"field": 0.0651, "shadows": 0.0193, "gi": 2.2657, "frame_wall": 2.6903}, + "4 lights + GI bounce": {"field": 0.0629, "shadows": 0.2975, "gi": 2.4869, "frame_wall": 3.4413} +} diff --git a/app/vendor/rune/demo/light/chat.png b/app/vendor/rune/demo/light/chat.png new file mode 100644 index 0000000..84b7c2a Binary files /dev/null and b/app/vendor/rune/demo/light/chat.png differ diff --git a/app/vendor/rune/demo/light/emissive.png b/app/vendor/rune/demo/light/emissive.png new file mode 100644 index 0000000..a7296b4 Binary files /dev/null and b/app/vendor/rune/demo/light/emissive.png differ diff --git a/app/vendor/rune/demo/light/flashlight.png b/app/vendor/rune/demo/light/flashlight.png new file mode 100644 index 0000000..6e2ae10 Binary files /dev/null and b/app/vendor/rune/demo/light/flashlight.png differ diff --git a/app/vendor/rune/demo/light/godrays.png b/app/vendor/rune/demo/light/godrays.png new file mode 100644 index 0000000..263921c Binary files /dev/null and b/app/vendor/rune/demo/light/godrays.png differ diff --git a/app/vendor/rune/demo/light/raised.png b/app/vendor/rune/demo/light/raised.png new file mode 100644 index 0000000..1bbb022 Binary files /dev/null and b/app/vendor/rune/demo/light/raised.png differ diff --git a/app/vendor/rune/demo/motion/curves.png b/app/vendor/rune/demo/motion/curves.png new file mode 100644 index 0000000..0af2e06 Binary files /dev/null and b/app/vendor/rune/demo/motion/curves.png differ diff --git a/app/vendor/rune/demo/motion/curves.svg b/app/vendor/rune/demo/motion/curves.svg new file mode 100644 index 0000000..b8d624c --- /dev/null +++ b/app/vendor/rune/demo/motion/curves.svg @@ -0,0 +1 @@ +<svg xmlns="http://www.w3.org/2000/svg" width="1200" height="1200" viewBox="0 0 1200 1200" font-family="-apple-system, Helvetica, sans-serif"><rect width="100%" height="100%" fill="white"/><text x="16" y="26" font-size="16" font-weight="600" fill="#222">Tweens, decay and keyframes</text><rect x="44" y="68" width="242" height="116" fill="#fafbfc" stroke="#e3e6ea"/><text x="44" y="59" font-size="12" font-weight="600" fill="#333">CSS ease</text><line x1="44" x2="286" y1="153.29411" y2="153.29411" stroke="#d5d9de" stroke-dasharray="3 3"/><text x="40" y="156.29411" font-size="9" fill="#888" text-anchor="end">0</text><line x1="44" x2="286" y1="85.05882" y2="85.05882" stroke="#d5d9de" stroke-dasharray="3 3"/><text x="40" y="88.05882" font-size="9" fill="#888" text-anchor="end">1</text><text x="286" y="198" font-size="9" fill="#888" text-anchor="end">0.80 s</text><path d="M44.00,153.29 L44.81,153.17 L45.61,153.03 L46.42,152.87 L47.23,152.70 L48.03,152.52 L48.84,152.32 L49.65,152.11 L50.45,151.89 L51.26,151.64 L52.07,151.39 L52.87,151.12 L53.68,150.83 L54.49,150.52 L55.29,150.20 L56.10,149.87 L56.91,149.52 L57.71,149.15 L58.52,148.76 L59.33,148.36 L60.13,147.94 L60.94,147.51 L61.75,147.06 L62.55,146.59 L63.36,146.11 L64.17,145.61 L64.97,145.09 L65.78,144.57 L66.59,144.02 L67.39,143.46 L68.20,142.89 L69.01,142.31 L69.81,141.71 L70.62,141.10 L71.43,140.48 L72.23,139.85 L73.04,139.21 L73.85,138.56 L74.65,137.91 L75.46,137.24 L76.27,136.57 L77.07,135.89 L77.88,135.21 L78.69,134.53 L79.49,133.84 L80.30,133.15 L81.11,132.46 L81.91,131.76 L82.72,131.07 L83.53,130.37 L84.33,129.68 L85.14,128.99 L85.95,128.30 L86.75,127.62 L87.56,126.94 L88.37,126.26 L89.17,125.59 L89.98,124.92 L90.79,124.26 L91.59,123.60 L92.40,122.95 L93.21,122.30 L94.01,121.66 L94.82,121.03 L95.63,120.40 L96.43,119.78 L97.24,119.17 L98.05,118.57 L98.85,117.97 L99.66,117.38 L100.47,116.80 L101.27,116.22 L102.08,115.66 L102.89,115.10 L103.69,114.54 L104.50,114.00 L105.31,113.46 L106.11,112.93 L106.92,112.41 L107.73,111.90 L108.53,111.39 L109.34,110.89 L110.15,110.40 L110.95,109.92 L111.76,109.44 L112.57,108.97 L113.37,108.50 L114.18,108.05 L114.99,107.60 L115.79,107.16 L116.60,106.72 L117.41,106.29 L118.21,105.87 L119.02,105.45 L119.83,105.04 L120.63,104.64 L121.44,104.25 L122.25,103.86 L123.05,103.47 L123.86,103.09 L124.67,102.72 L125.47,102.35 L126.28,101.99 L127.09,101.64 L127.89,101.29 L128.70,100.95 L129.51,100.61 L130.31,100.28 L131.12,99.95 L131.93,99.63 L132.73,99.31 L133.54,99.00 L134.35,98.69 L135.15,98.39 L135.96,98.10 L136.77,97.80 L137.57,97.52 L138.38,97.23 L139.19,96.96 L139.99,96.68 L140.80,96.42 L141.61,96.15 L142.41,95.89 L143.22,95.64 L144.03,95.39 L144.83,95.14 L145.64,94.90 L146.45,94.66 L147.25,94.42 L148.06,94.19 L148.87,93.97 L149.67,93.74 L150.48,93.52 L151.29,93.31 L152.09,93.10 L152.90,92.89 L153.71,92.69 L154.51,92.49 L155.32,92.29 L156.13,92.10 L156.93,91.91 L157.74,91.72 L158.55,91.54 L159.35,91.36 L160.16,91.18 L160.97,91.01 L161.77,90.84 L162.58,90.67 L163.39,90.51 L164.19,90.35 L165.00,90.19 L165.81,90.03 L166.61,89.88 L167.42,89.73 L168.23,89.59 L169.03,89.45 L169.84,89.31 L170.65,89.17 L171.45,89.03 L172.26,88.90 L173.07,88.77 L173.87,88.65 L174.68,88.52 L175.49,88.40 L176.29,88.28 L177.10,88.17 L177.91,88.06 L178.71,87.94 L179.52,87.84 L180.33,87.73 L181.13,87.63 L181.94,87.53 L182.75,87.43 L183.55,87.33 L184.36,87.24 L185.17,87.15 L185.97,87.06 L186.78,86.97 L187.59,86.89 L188.39,86.80 L189.20,86.72 L190.01,86.64 L190.81,86.57 L191.62,86.49 L192.43,86.42 L193.23,86.35 L194.04,86.28 L194.85,86.22 L195.65,86.15 L196.46,86.09 L197.27,86.03 L198.07,85.98 L198.88,85.92 L199.69,85.87 L200.49,85.81 L201.30,85.76 L202.11,85.72 L202.91,85.67 L203.72,85.62 L204.53,85.58 L205.33,85.54 L206.14,85.50 L206.95,85.46 L207.75,85.43 L208.56,85.40 L209.37,85.36 L210.17,85.33 L210.98,85.30 L211.79,85.28 L212.59,85.25 L213.40,85.23 L214.21,85.21 L215.01,85.18 L215.82,85.17 L216.63,85.15 L217.43,85.13 L218.24,85.12 L219.05,85.11 L219.85,85.09 L220.66,85.09 L221.47,85.08 L222.27,85.07 L223.08,85.07 L223.89,85.06 L224.69,85.06 L225.50,85.06 L226.31,85.06 L227.11,85.06 L227.92,85.06 L228.73,85.06 L229.53,85.06 L230.34,85.06 L231.15,85.06 L231.95,85.06 L232.76,85.06 L233.57,85.06 L234.37,85.06 L235.18,85.06 L235.99,85.06 L236.79,85.06 L237.60,85.06 L238.41,85.06 L239.21,85.06 L240.02,85.06 L240.83,85.06 L241.63,85.06 L242.44,85.06 L243.25,85.06 L244.05,85.06 L244.86,85.06 L245.67,85.06 L246.47,85.06 L247.28,85.06 L248.09,85.06 L248.89,85.06 L249.70,85.06 L250.51,85.06 L251.31,85.06 L252.12,85.06 L252.93,85.06 L253.73,85.06 L254.54,85.06 L255.35,85.06 L256.15,85.06 L256.96,85.06 L257.77,85.06 L258.57,85.06 L259.38,85.06 L260.19,85.06 L260.99,85.06 L261.80,85.06 L262.61,85.06 L263.41,85.06 L264.22,85.06 L265.03,85.06 L265.83,85.06 L266.64,85.06 L267.45,85.06 L268.25,85.06 L269.06,85.06 L269.87,85.06 L270.67,85.06 L271.48,85.06 L272.29,85.06 L273.09,85.06 L273.90,85.06 L274.71,85.06 L275.51,85.06 L276.32,85.06 L277.13,85.06 L277.93,85.06 L278.74,85.06 L279.55,85.06 L280.35,85.06 L281.16,85.06 L281.97,85.06 L282.77,85.06 L283.58,85.06 L284.39,85.06 L285.19,85.06 L286.00,85.06 " fill="none" stroke="#2f6fec" stroke-width="1.8"/><text x="282" y="80" font-size="9" fill="#2f6fec" text-anchor="end">position</text><path d="M44.00,141.36 L44.81,140.08 L45.61,138.76 L46.42,137.42 L47.23,136.05 L48.03,134.66 L48.84,133.24 L49.65,131.79 L50.45,130.32 L51.26,128.82 L52.07,127.31 L52.87,125.77 L53.68,124.21 L54.49,122.64 L55.29,121.05 L56.10,119.45 L56.91,117.84 L57.71,116.22 L58.52,114.60 L59.33,112.98 L60.13,111.36 L60.94,109.76 L61.75,108.16 L62.55,106.59 L63.36,105.03 L64.17,103.51 L64.97,102.01 L65.78,100.56 L66.59,99.14 L67.39,97.77 L68.20,96.46 L69.01,95.20 L69.81,94.00 L70.62,92.87 L71.43,91.80 L72.23,90.81 L73.04,89.90 L73.85,89.06 L74.65,88.30 L75.46,87.62 L76.27,87.02 L77.07,86.50 L77.88,86.07 L78.69,85.71 L79.49,85.44 L80.30,85.24 L81.11,85.11 L81.91,85.06 L82.72,85.08 L83.53,85.16 L84.33,85.31 L85.14,85.52 L85.95,85.78 L86.75,86.10 L87.56,86.46 L88.37,86.87 L89.17,87.33 L89.98,87.82 L90.79,88.35 L91.59,88.91 L92.40,89.50 L93.21,90.11 L94.01,90.75 L94.82,91.41 L95.63,92.09 L96.43,92.78 L97.24,93.48 L98.05,94.20 L98.85,94.93 L99.66,95.66 L100.47,96.40 L101.27,97.14 L102.08,97.89 L102.89,98.63 L103.69,99.38 L104.50,100.13 L105.31,100.87 L106.11,101.62 L106.92,102.36 L107.73,103.09 L108.53,103.82 L109.34,104.55 L110.15,105.27 L110.95,105.99 L111.76,106.69 L112.57,107.39 L113.37,108.09 L114.18,108.78 L114.99,109.46 L115.79,110.13 L116.60,110.79 L117.41,111.45 L118.21,112.10 L119.02,112.74 L119.83,113.37 L120.63,113.99 L121.44,114.61 L122.25,115.22 L123.05,115.82 L123.86,116.41 L124.67,116.99 L125.47,117.57 L126.28,118.14 L127.09,118.70 L127.89,119.25 L128.70,119.79 L129.51,120.33 L130.31,120.86 L131.12,121.38 L131.93,121.90 L132.73,122.41 L133.54,122.91 L134.35,123.40 L135.15,123.89 L135.96,124.37 L136.77,124.84 L137.57,125.31 L138.38,125.77 L139.19,126.22 L139.99,126.67 L140.80,127.11 L141.61,127.55 L142.41,127.98 L143.22,128.40 L144.03,128.82 L144.83,129.23 L145.64,129.64 L146.45,130.04 L147.25,130.43 L148.06,130.82 L148.87,131.21 L149.67,131.59 L150.48,131.96 L151.29,132.33 L152.09,132.70 L152.90,133.06 L153.71,133.41 L154.51,133.77 L155.32,134.11 L156.13,134.46 L156.93,134.79 L157.74,135.13 L158.55,135.46 L159.35,135.78 L160.16,136.10 L160.97,136.42 L161.77,136.73 L162.58,137.04 L163.39,137.35 L164.19,137.65 L165.00,137.95 L165.81,138.25 L166.61,138.54 L167.42,138.83 L168.23,139.11 L169.03,139.39 L169.84,139.67 L170.65,139.95 L171.45,140.22 L172.26,140.49 L173.07,140.75 L173.87,141.01 L174.68,141.27 L175.49,141.53 L176.29,141.78 L177.10,142.04 L177.91,142.28 L178.71,142.53 L179.52,142.77 L180.33,143.01 L181.13,143.25 L181.94,143.49 L182.75,143.72 L183.55,143.95 L184.36,144.18 L185.17,144.40 L185.97,144.62 L186.78,144.84 L187.59,145.06 L188.39,145.28 L189.20,145.49 L190.01,145.71 L190.81,145.91 L191.62,146.12 L192.43,146.33 L193.23,146.53 L194.04,146.73 L194.85,146.93 L195.65,147.13 L196.46,147.33 L197.27,147.52 L198.07,147.71 L198.88,147.90 L199.69,148.09 L200.49,148.28 L201.30,148.46 L202.11,148.64 L202.91,148.82 L203.72,149.00 L204.53,149.18 L205.33,149.36 L206.14,149.53 L206.95,149.71 L207.75,149.88 L208.56,150.05 L209.37,150.22 L210.17,150.38 L210.98,150.55 L211.79,150.71 L212.59,150.87 L213.40,151.04 L214.21,151.20 L215.01,151.35 L215.82,151.51 L216.63,151.67 L217.43,151.82 L218.24,151.97 L219.05,152.12 L219.85,152.28 L220.66,152.42 L221.47,152.57 L222.27,152.72 L223.08,152.86 L223.89,153.01 L224.69,153.15 L225.50,153.29 L226.31,153.29 L227.11,153.29 L227.92,153.29 L228.73,153.29 L229.53,153.29 L230.34,153.29 L231.15,153.29 L231.95,153.29 L232.76,153.29 L233.57,153.29 L234.37,153.29 L235.18,153.29 L235.99,153.29 L236.79,153.29 L237.60,153.29 L238.41,153.29 L239.21,153.29 L240.02,153.29 L240.83,153.29 L241.63,153.29 L242.44,153.29 L243.25,153.29 L244.05,153.29 L244.86,153.29 L245.67,153.29 L246.47,153.29 L247.28,153.29 L248.09,153.29 L248.89,153.29 L249.70,153.29 L250.51,153.29 L251.31,153.29 L252.12,153.29 L252.93,153.29 L253.73,153.29 L254.54,153.29 L255.35,153.29 L256.15,153.29 L256.96,153.29 L257.77,153.29 L258.57,153.29 L259.38,153.29 L260.19,153.29 L260.99,153.29 L261.80,153.29 L262.61,153.29 L263.41,153.29 L264.22,153.29 L265.03,153.29 L265.83,153.29 L266.64,153.29 L267.45,153.29 L268.25,153.29 L269.06,153.29 L269.87,153.29 L270.67,153.29 L271.48,153.29 L272.29,153.29 L273.09,153.29 L273.90,153.29 L274.71,153.29 L275.51,153.29 L276.32,153.29 L277.13,153.29 L277.93,153.29 L278.74,153.29 L279.55,153.29 L280.35,153.29 L281.16,153.29 L281.97,153.29 L282.77,153.29 L283.58,153.29 L284.39,153.29 L285.19,153.29 L286.00,153.29 " fill="none" stroke="#e8833a" stroke-width="1.8" stroke-dasharray="4 3"/><text x="282" y="92" font-size="9" fill="#e8833a" text-anchor="end">velocity (norm.)</text><rect x="344" y="68" width="242" height="116" fill="#fafbfc" stroke="#e3e6ea"/><text x="344" y="59" font-size="12" font-weight="600" fill="#333">Kit CSS enter 150 ms</text><line x1="344" x2="586" y1="153.29411" y2="153.29411" stroke="#d5d9de" stroke-dasharray="3 3"/><text x="340" y="156.29411" font-size="9" fill="#888" text-anchor="end">0</text><line x1="344" x2="586" y1="85.05882" y2="85.05882" stroke="#d5d9de" stroke-dasharray="3 3"/><text x="340" y="88.05882" font-size="9" fill="#888" text-anchor="end">1</text><text x="586" y="198" font-size="9" fill="#888" text-anchor="end">0.30 s</text><path d="M344.00,153.29 L344.81,151.47 L345.61,149.64 L346.42,147.80 L347.23,145.95 L348.03,144.10 L348.84,142.26 L349.65,140.41 L350.45,138.58 L351.26,136.75 L352.07,134.94 L352.87,133.14 L353.68,131.37 L354.49,129.62 L355.29,127.91 L356.10,126.23 L356.91,124.58 L357.71,122.98 L358.52,121.43 L359.33,119.93 L360.13,118.47 L360.94,117.07 L361.75,115.72 L362.55,114.42 L363.36,113.17 L364.17,111.98 L364.97,110.84 L365.78,109.75 L366.59,108.71 L367.39,107.72 L368.20,106.77 L369.01,105.87 L369.81,105.01 L370.62,104.19 L371.43,103.40 L372.23,102.66 L373.04,101.95 L373.85,101.27 L374.65,100.62 L375.46,100.00 L376.27,99.41 L377.07,98.84 L377.88,98.30 L378.69,97.79 L379.49,97.29 L380.30,96.82 L381.11,96.37 L381.91,95.93 L382.72,95.52 L383.53,95.12 L384.33,94.74 L385.14,94.37 L385.95,94.02 L386.75,93.68 L387.56,93.36 L388.37,93.04 L389.17,92.74 L389.98,92.46 L390.79,92.18 L391.59,91.91 L392.40,91.65 L393.21,91.40 L394.01,91.17 L394.82,90.94 L395.63,90.71 L396.43,90.50 L397.24,90.30 L398.05,90.10 L398.85,89.90 L399.66,89.72 L400.47,89.54 L401.27,89.37 L402.08,89.20 L402.89,89.04 L403.69,88.89 L404.50,88.74 L405.31,88.59 L406.11,88.45 L406.92,88.32 L407.73,88.19 L408.53,88.06 L409.34,87.94 L410.15,87.82 L410.95,87.71 L411.76,87.60 L412.57,87.50 L413.37,87.39 L414.18,87.29 L414.99,87.20 L415.79,87.11 L416.60,87.02 L417.41,86.93 L418.21,86.85 L419.02,86.77 L419.83,86.69 L420.63,86.62 L421.44,86.54 L422.25,86.47 L423.05,86.41 L423.86,86.34 L424.67,86.28 L425.47,86.22 L426.28,86.16 L427.09,86.10 L427.89,86.05 L428.70,86.00 L429.51,85.95 L430.31,85.90 L431.12,85.85 L431.93,85.81 L432.73,85.77 L433.54,85.72 L434.35,85.68 L435.15,85.65 L435.96,85.61 L436.77,85.58 L437.57,85.54 L438.38,85.51 L439.19,85.48 L439.99,85.45 L440.80,85.42 L441.61,85.39 L442.41,85.37 L443.22,85.34 L444.03,85.32 L444.83,85.30 L445.64,85.28 L446.45,85.26 L447.25,85.24 L448.06,85.22 L448.87,85.21 L449.67,85.19 L450.48,85.18 L451.29,85.16 L452.09,85.15 L452.90,85.14 L453.71,85.13 L454.51,85.12 L455.32,85.11 L456.13,85.10 L456.93,85.09 L457.74,85.09 L458.55,85.08 L459.35,85.08 L460.16,85.07 L460.97,85.07 L461.77,85.06 L462.58,85.06 L463.39,85.06 L464.19,85.06 L465.00,85.06 L465.81,85.06 L466.61,85.06 L467.42,85.06 L468.23,85.06 L469.03,85.06 L469.84,85.06 L470.65,85.06 L471.45,85.06 L472.26,85.06 L473.07,85.06 L473.87,85.06 L474.68,85.06 L475.49,85.06 L476.29,85.06 L477.10,85.06 L477.91,85.06 L478.71,85.06 L479.52,85.06 L480.33,85.06 L481.13,85.06 L481.94,85.06 L482.75,85.06 L483.55,85.06 L484.36,85.06 L485.17,85.06 L485.97,85.06 L486.78,85.06 L487.59,85.06 L488.39,85.06 L489.20,85.06 L490.01,85.06 L490.81,85.06 L491.62,85.06 L492.43,85.06 L493.23,85.06 L494.04,85.06 L494.85,85.06 L495.65,85.06 L496.46,85.06 L497.27,85.06 L498.07,85.06 L498.88,85.06 L499.69,85.06 L500.49,85.06 L501.30,85.06 L502.11,85.06 L502.91,85.06 L503.72,85.06 L504.53,85.06 L505.33,85.06 L506.14,85.06 L506.95,85.06 L507.75,85.06 L508.56,85.06 L509.37,85.06 L510.17,85.06 L510.98,85.06 L511.79,85.06 L512.59,85.06 L513.40,85.06 L514.21,85.06 L515.01,85.06 L515.82,85.06 L516.63,85.06 L517.43,85.06 L518.24,85.06 L519.05,85.06 L519.85,85.06 L520.66,85.06 L521.47,85.06 L522.27,85.06 L523.08,85.06 L523.89,85.06 L524.69,85.06 L525.50,85.06 L526.31,85.06 L527.11,85.06 L527.92,85.06 L528.73,85.06 L529.53,85.06 L530.34,85.06 L531.15,85.06 L531.95,85.06 L532.76,85.06 L533.57,85.06 L534.37,85.06 L535.18,85.06 L535.99,85.06 L536.79,85.06 L537.60,85.06 L538.41,85.06 L539.21,85.06 L540.02,85.06 L540.83,85.06 L541.63,85.06 L542.44,85.06 L543.25,85.06 L544.05,85.06 L544.86,85.06 L545.67,85.06 L546.47,85.06 L547.28,85.06 L548.09,85.06 L548.89,85.06 L549.70,85.06 L550.51,85.06 L551.31,85.06 L552.12,85.06 L552.93,85.06 L553.73,85.06 L554.54,85.06 L555.35,85.06 L556.15,85.06 L556.96,85.06 L557.77,85.06 L558.57,85.06 L559.38,85.06 L560.19,85.06 L560.99,85.06 L561.80,85.06 L562.61,85.06 L563.41,85.06 L564.22,85.06 L565.03,85.06 L565.83,85.06 L566.64,85.06 L567.45,85.06 L568.25,85.06 L569.06,85.06 L569.87,85.06 L570.67,85.06 L571.48,85.06 L572.29,85.06 L573.09,85.06 L573.90,85.06 L574.71,85.06 L575.51,85.06 L576.32,85.06 L577.13,85.06 L577.93,85.06 L578.74,85.06 L579.55,85.06 L580.35,85.06 L581.16,85.06 L581.97,85.06 L582.77,85.06 L583.58,85.06 L584.39,85.06 L585.19,85.06 L586.00,85.06 " fill="none" stroke="#2f6fec" stroke-width="1.8"/><text x="582" y="80" font-size="9" fill="#2f6fec" text-anchor="end">position</text><path d="M344.00,86.09 L344.81,85.75 L345.61,85.46 L346.42,85.24 L347.23,85.10 L348.03,85.06 L348.84,85.12 L349.65,85.30 L350.45,85.60 L351.26,86.04 L352.07,86.63 L352.87,87.38 L353.68,88.28 L354.49,89.34 L355.29,90.56 L356.10,91.93 L356.91,93.43 L357.71,95.06 L358.52,96.79 L359.33,98.61 L360.13,100.49 L360.94,102.43 L361.75,104.39 L362.55,106.35 L363.36,108.31 L364.17,110.24 L364.97,112.13 L365.78,113.97 L366.59,115.76 L367.39,117.48 L368.20,119.14 L369.01,120.73 L369.81,122.25 L370.62,123.69 L371.43,125.07 L372.23,126.37 L373.04,127.61 L373.85,128.79 L374.65,129.90 L375.46,130.96 L376.27,131.96 L377.07,132.91 L377.88,133.80 L378.69,134.65 L379.49,135.45 L380.30,136.21 L381.11,136.94 L381.91,137.62 L382.72,138.27 L383.53,138.88 L384.33,139.47 L385.14,140.02 L385.95,140.55 L386.75,141.06 L387.56,141.53 L388.37,141.99 L389.17,142.42 L389.98,142.84 L390.79,143.23 L391.59,143.61 L392.40,143.97 L393.21,144.31 L394.01,144.64 L394.82,144.96 L395.63,145.26 L396.43,145.55 L397.24,145.82 L398.05,146.09 L398.85,146.34 L399.66,146.59 L400.47,146.82 L401.27,147.05 L402.08,147.26 L402.89,147.47 L403.69,147.67 L404.50,147.87 L405.31,148.05 L406.11,148.23 L406.92,148.40 L407.73,148.57 L408.53,148.73 L409.34,148.88 L410.15,149.03 L410.95,149.18 L411.76,149.32 L412.57,149.45 L413.37,149.58 L414.18,149.71 L414.99,149.83 L415.79,149.95 L416.60,150.06 L417.41,150.17 L418.21,150.28 L419.02,150.38 L419.83,150.48 L420.63,150.58 L421.44,150.67 L422.25,150.76 L423.05,150.85 L423.86,150.94 L424.67,151.02 L425.47,151.10 L426.28,151.18 L427.09,151.26 L427.89,151.33 L428.70,151.41 L429.51,151.48 L430.31,151.54 L431.12,151.61 L431.93,151.68 L432.73,151.74 L433.54,151.80 L434.35,151.86 L435.15,151.92 L435.96,151.97 L436.77,152.03 L437.57,152.08 L438.38,152.13 L439.19,152.18 L439.99,152.23 L440.80,152.28 L441.61,152.33 L442.41,152.37 L443.22,152.42 L444.03,152.46 L444.83,152.51 L445.64,152.55 L446.45,152.59 L447.25,152.63 L448.06,152.67 L448.87,152.70 L449.67,152.74 L450.48,152.77 L451.29,152.81 L452.09,152.84 L452.90,152.88 L453.71,152.91 L454.51,152.94 L455.32,152.97 L456.13,153.00 L456.93,153.03 L457.74,153.06 L458.55,153.09 L459.35,153.12 L460.16,153.14 L460.97,153.17 L461.77,153.20 L462.58,153.22 L463.39,153.25 L464.19,153.27 L465.00,153.29 L465.81,153.29 L466.61,153.29 L467.42,153.29 L468.23,153.29 L469.03,153.29 L469.84,153.29 L470.65,153.29 L471.45,153.29 L472.26,153.29 L473.07,153.29 L473.87,153.29 L474.68,153.29 L475.49,153.29 L476.29,153.29 L477.10,153.29 L477.91,153.29 L478.71,153.29 L479.52,153.29 L480.33,153.29 L481.13,153.29 L481.94,153.29 L482.75,153.29 L483.55,153.29 L484.36,153.29 L485.17,153.29 L485.97,153.29 L486.78,153.29 L487.59,153.29 L488.39,153.29 L489.20,153.29 L490.01,153.29 L490.81,153.29 L491.62,153.29 L492.43,153.29 L493.23,153.29 L494.04,153.29 L494.85,153.29 L495.65,153.29 L496.46,153.29 L497.27,153.29 L498.07,153.29 L498.88,153.29 L499.69,153.29 L500.49,153.29 L501.30,153.29 L502.11,153.29 L502.91,153.29 L503.72,153.29 L504.53,153.29 L505.33,153.29 L506.14,153.29 L506.95,153.29 L507.75,153.29 L508.56,153.29 L509.37,153.29 L510.17,153.29 L510.98,153.29 L511.79,153.29 L512.59,153.29 L513.40,153.29 L514.21,153.29 L515.01,153.29 L515.82,153.29 L516.63,153.29 L517.43,153.29 L518.24,153.29 L519.05,153.29 L519.85,153.29 L520.66,153.29 L521.47,153.29 L522.27,153.29 L523.08,153.29 L523.89,153.29 L524.69,153.29 L525.50,153.29 L526.31,153.29 L527.11,153.29 L527.92,153.29 L528.73,153.29 L529.53,153.29 L530.34,153.29 L531.15,153.29 L531.95,153.29 L532.76,153.29 L533.57,153.29 L534.37,153.29 L535.18,153.29 L535.99,153.29 L536.79,153.29 L537.60,153.29 L538.41,153.29 L539.21,153.29 L540.02,153.29 L540.83,153.29 L541.63,153.29 L542.44,153.29 L543.25,153.29 L544.05,153.29 L544.86,153.29 L545.67,153.29 L546.47,153.29 L547.28,153.29 L548.09,153.29 L548.89,153.29 L549.70,153.29 L550.51,153.29 L551.31,153.29 L552.12,153.29 L552.93,153.29 L553.73,153.29 L554.54,153.29 L555.35,153.29 L556.15,153.29 L556.96,153.29 L557.77,153.29 L558.57,153.29 L559.38,153.29 L560.19,153.29 L560.99,153.29 L561.80,153.29 L562.61,153.29 L563.41,153.29 L564.22,153.29 L565.03,153.29 L565.83,153.29 L566.64,153.29 L567.45,153.29 L568.25,153.29 L569.06,153.29 L569.87,153.29 L570.67,153.29 L571.48,153.29 L572.29,153.29 L573.09,153.29 L573.90,153.29 L574.71,153.29 L575.51,153.29 L576.32,153.29 L577.13,153.29 L577.93,153.29 L578.74,153.29 L579.55,153.29 L580.35,153.29 L581.16,153.29 L581.97,153.29 L582.77,153.29 L583.58,153.29 L584.39,153.29 L585.19,153.29 L586.00,153.29 " fill="none" stroke="#e8833a" stroke-width="1.8" stroke-dasharray="4 3"/><text x="582" y="92" font-size="9" fill="#e8833a" text-anchor="end">velocity (norm.)</text><rect x="644" y="68" width="242" height="116" fill="#fafbfc" stroke="#e3e6ea"/><text x="644" y="59" font-size="12" font-weight="600" fill="#333">Kit CSS exit 110 ms</text><line x1="644" x2="886" y1="153.29411" y2="153.29411" stroke="#d5d9de" stroke-dasharray="3 3"/><text x="640" y="156.29411" font-size="9" fill="#888" text-anchor="end">0</text><line x1="644" x2="886" y1="85.05882" y2="85.05882" stroke="#d5d9de" stroke-dasharray="3 3"/><text x="640" y="88.05882" font-size="9" fill="#888" text-anchor="end">1</text><text x="886" y="198" font-size="9" fill="#888" text-anchor="end">0.30 s</text><path d="M644.00,153.29 L644.81,153.28 L645.61,153.25 L646.42,153.19 L647.23,153.12 L648.03,153.02 L648.84,152.90 L649.65,152.76 L650.45,152.61 L651.26,152.44 L652.07,152.25 L652.87,152.04 L653.68,151.82 L654.49,151.58 L655.29,151.32 L656.10,151.05 L656.91,150.77 L657.71,150.47 L658.52,150.16 L659.33,149.84 L660.13,149.50 L660.94,149.14 L661.75,148.78 L662.55,148.40 L663.36,148.02 L664.17,147.61 L664.97,147.20 L665.78,146.78 L666.59,146.35 L667.39,145.90 L668.20,145.45 L669.01,144.98 L669.81,144.50 L670.62,144.02 L671.43,143.52 L672.23,143.02 L673.04,142.50 L673.85,141.98 L674.65,141.45 L675.46,140.90 L676.27,140.35 L677.07,139.79 L677.88,139.23 L678.69,138.65 L679.49,138.07 L680.30,137.47 L681.11,136.87 L681.91,136.27 L682.72,135.65 L683.53,135.03 L684.33,134.39 L685.14,133.76 L685.95,133.11 L686.75,132.46 L687.56,131.80 L688.37,131.13 L689.17,130.46 L689.98,129.78 L690.79,129.09 L691.59,128.39 L692.40,127.69 L693.21,126.98 L694.01,126.27 L694.82,125.55 L695.63,124.82 L696.43,124.09 L697.24,123.35 L698.05,122.61 L698.85,121.85 L699.66,121.10 L700.47,120.33 L701.27,119.56 L702.08,118.79 L702.89,118.01 L703.69,117.22 L704.50,116.43 L705.31,115.63 L706.11,114.82 L706.92,114.01 L707.73,113.20 L708.53,112.38 L709.34,111.55 L710.15,110.72 L710.95,109.88 L711.76,109.04 L712.57,108.19 L713.37,107.33 L714.18,106.47 L714.99,105.61 L715.79,104.74 L716.60,103.86 L717.41,102.98 L718.21,102.09 L719.02,101.20 L719.83,100.30 L720.63,99.40 L721.44,98.49 L722.25,97.57 L723.05,96.65 L723.86,95.72 L724.67,94.79 L725.47,93.85 L726.28,92.90 L727.09,91.95 L727.89,90.99 L728.70,90.02 L729.51,89.05 L730.31,88.07 L731.12,87.08 L731.93,86.08 L732.73,85.06 L733.54,85.06 L734.35,85.06 L735.15,85.06 L735.96,85.06 L736.77,85.06 L737.57,85.06 L738.38,85.06 L739.19,85.06 L739.99,85.06 L740.80,85.06 L741.61,85.06 L742.41,85.06 L743.22,85.06 L744.03,85.06 L744.83,85.06 L745.64,85.06 L746.45,85.06 L747.25,85.06 L748.06,85.06 L748.87,85.06 L749.67,85.06 L750.48,85.06 L751.29,85.06 L752.09,85.06 L752.90,85.06 L753.71,85.06 L754.51,85.06 L755.32,85.06 L756.13,85.06 L756.93,85.06 L757.74,85.06 L758.55,85.06 L759.35,85.06 L760.16,85.06 L760.97,85.06 L761.77,85.06 L762.58,85.06 L763.39,85.06 L764.19,85.06 L765.00,85.06 L765.81,85.06 L766.61,85.06 L767.42,85.06 L768.23,85.06 L769.03,85.06 L769.84,85.06 L770.65,85.06 L771.45,85.06 L772.26,85.06 L773.07,85.06 L773.87,85.06 L774.68,85.06 L775.49,85.06 L776.29,85.06 L777.10,85.06 L777.91,85.06 L778.71,85.06 L779.52,85.06 L780.33,85.06 L781.13,85.06 L781.94,85.06 L782.75,85.06 L783.55,85.06 L784.36,85.06 L785.17,85.06 L785.97,85.06 L786.78,85.06 L787.59,85.06 L788.39,85.06 L789.20,85.06 L790.01,85.06 L790.81,85.06 L791.62,85.06 L792.43,85.06 L793.23,85.06 L794.04,85.06 L794.85,85.06 L795.65,85.06 L796.46,85.06 L797.27,85.06 L798.07,85.06 L798.88,85.06 L799.69,85.06 L800.49,85.06 L801.30,85.06 L802.11,85.06 L802.91,85.06 L803.72,85.06 L804.53,85.06 L805.33,85.06 L806.14,85.06 L806.95,85.06 L807.75,85.06 L808.56,85.06 L809.37,85.06 L810.17,85.06 L810.98,85.06 L811.79,85.06 L812.59,85.06 L813.40,85.06 L814.21,85.06 L815.01,85.06 L815.82,85.06 L816.63,85.06 L817.43,85.06 L818.24,85.06 L819.05,85.06 L819.85,85.06 L820.66,85.06 L821.47,85.06 L822.27,85.06 L823.08,85.06 L823.89,85.06 L824.69,85.06 L825.50,85.06 L826.31,85.06 L827.11,85.06 L827.92,85.06 L828.73,85.06 L829.53,85.06 L830.34,85.06 L831.15,85.06 L831.95,85.06 L832.76,85.06 L833.57,85.06 L834.37,85.06 L835.18,85.06 L835.99,85.06 L836.79,85.06 L837.60,85.06 L838.41,85.06 L839.21,85.06 L840.02,85.06 L840.83,85.06 L841.63,85.06 L842.44,85.06 L843.25,85.06 L844.05,85.06 L844.86,85.06 L845.67,85.06 L846.47,85.06 L847.28,85.06 L848.09,85.06 L848.89,85.06 L849.70,85.06 L850.51,85.06 L851.31,85.06 L852.12,85.06 L852.93,85.06 L853.73,85.06 L854.54,85.06 L855.35,85.06 L856.15,85.06 L856.96,85.06 L857.77,85.06 L858.57,85.06 L859.38,85.06 L860.19,85.06 L860.99,85.06 L861.80,85.06 L862.61,85.06 L863.41,85.06 L864.22,85.06 L865.03,85.06 L865.83,85.06 L866.64,85.06 L867.45,85.06 L868.25,85.06 L869.06,85.06 L869.87,85.06 L870.67,85.06 L871.48,85.06 L872.29,85.06 L873.09,85.06 L873.90,85.06 L874.71,85.06 L875.51,85.06 L876.32,85.06 L877.13,85.06 L877.93,85.06 L878.74,85.06 L879.55,85.06 L880.35,85.06 L881.16,85.06 L881.97,85.06 L882.77,85.06 L883.58,85.06 L884.39,85.06 L885.19,85.06 L886.00,85.06 " fill="none" stroke="#2f6fec" stroke-width="1.8"/><text x="882" y="80" font-size="9" fill="#2f6fec" text-anchor="end">position</text><path d="M644.00,153.29 L644.81,151.73 L645.61,150.23 L646.42,148.78 L647.23,147.37 L648.03,146.02 L648.84,144.71 L649.65,143.44 L650.45,142.21 L651.26,141.02 L652.07,139.86 L652.87,138.74 L653.68,137.65 L654.49,136.59 L655.29,135.56 L656.10,134.56 L656.91,133.58 L657.71,132.63 L658.52,131.70 L659.33,130.80 L660.13,129.91 L660.94,129.05 L661.75,128.21 L662.55,127.39 L663.36,126.58 L664.17,125.80 L664.97,125.03 L665.78,124.27 L666.59,123.54 L667.39,122.81 L668.20,122.11 L669.01,121.41 L669.81,120.73 L670.62,120.06 L671.43,119.41 L672.23,118.77 L673.04,118.13 L673.85,117.51 L674.65,116.90 L675.46,116.31 L676.27,115.72 L677.07,115.14 L677.88,114.57 L678.69,114.01 L679.49,113.45 L680.30,112.91 L681.11,112.38 L681.91,111.85 L682.72,111.33 L683.53,110.82 L684.33,110.31 L685.14,109.81 L685.95,109.32 L686.75,108.84 L687.56,108.36 L688.37,107.88 L689.17,107.42 L689.98,106.96 L690.79,106.50 L691.59,106.05 L692.40,105.60 L693.21,105.16 L694.01,104.73 L694.82,104.30 L695.63,103.87 L696.43,103.45 L697.24,103.03 L698.05,102.61 L698.85,102.20 L699.66,101.79 L700.47,101.39 L701.27,100.99 L702.08,100.59 L702.89,100.20 L703.69,99.80 L704.50,99.41 L705.31,99.03 L706.11,98.64 L706.92,98.26 L707.73,97.88 L708.53,97.50 L709.34,97.12 L710.15,96.75 L710.95,96.37 L711.76,96.00 L712.57,95.63 L713.37,95.25 L714.18,94.88 L714.99,94.51 L715.79,94.13 L716.60,93.76 L717.41,93.39 L718.21,93.01 L719.02,92.63 L719.83,92.25 L720.63,91.87 L721.44,91.48 L722.25,91.09 L723.05,90.69 L723.86,90.29 L724.67,89.88 L725.47,89.46 L726.28,89.02 L727.09,88.57 L727.89,88.11 L728.70,87.62 L729.51,87.09 L730.31,86.52 L731.12,85.87 L731.93,85.06 L732.73,153.29 L733.54,153.29 L734.35,153.29 L735.15,153.29 L735.96,153.29 L736.77,153.29 L737.57,153.29 L738.38,153.29 L739.19,153.29 L739.99,153.29 L740.80,153.29 L741.61,153.29 L742.41,153.29 L743.22,153.29 L744.03,153.29 L744.83,153.29 L745.64,153.29 L746.45,153.29 L747.25,153.29 L748.06,153.29 L748.87,153.29 L749.67,153.29 L750.48,153.29 L751.29,153.29 L752.09,153.29 L752.90,153.29 L753.71,153.29 L754.51,153.29 L755.32,153.29 L756.13,153.29 L756.93,153.29 L757.74,153.29 L758.55,153.29 L759.35,153.29 L760.16,153.29 L760.97,153.29 L761.77,153.29 L762.58,153.29 L763.39,153.29 L764.19,153.29 L765.00,153.29 L765.81,153.29 L766.61,153.29 L767.42,153.29 L768.23,153.29 L769.03,153.29 L769.84,153.29 L770.65,153.29 L771.45,153.29 L772.26,153.29 L773.07,153.29 L773.87,153.29 L774.68,153.29 L775.49,153.29 L776.29,153.29 L777.10,153.29 L777.91,153.29 L778.71,153.29 L779.52,153.29 L780.33,153.29 L781.13,153.29 L781.94,153.29 L782.75,153.29 L783.55,153.29 L784.36,153.29 L785.17,153.29 L785.97,153.29 L786.78,153.29 L787.59,153.29 L788.39,153.29 L789.20,153.29 L790.01,153.29 L790.81,153.29 L791.62,153.29 L792.43,153.29 L793.23,153.29 L794.04,153.29 L794.85,153.29 L795.65,153.29 L796.46,153.29 L797.27,153.29 L798.07,153.29 L798.88,153.29 L799.69,153.29 L800.49,153.29 L801.30,153.29 L802.11,153.29 L802.91,153.29 L803.72,153.29 L804.53,153.29 L805.33,153.29 L806.14,153.29 L806.95,153.29 L807.75,153.29 L808.56,153.29 L809.37,153.29 L810.17,153.29 L810.98,153.29 L811.79,153.29 L812.59,153.29 L813.40,153.29 L814.21,153.29 L815.01,153.29 L815.82,153.29 L816.63,153.29 L817.43,153.29 L818.24,153.29 L819.05,153.29 L819.85,153.29 L820.66,153.29 L821.47,153.29 L822.27,153.29 L823.08,153.29 L823.89,153.29 L824.69,153.29 L825.50,153.29 L826.31,153.29 L827.11,153.29 L827.92,153.29 L828.73,153.29 L829.53,153.29 L830.34,153.29 L831.15,153.29 L831.95,153.29 L832.76,153.29 L833.57,153.29 L834.37,153.29 L835.18,153.29 L835.99,153.29 L836.79,153.29 L837.60,153.29 L838.41,153.29 L839.21,153.29 L840.02,153.29 L840.83,153.29 L841.63,153.29 L842.44,153.29 L843.25,153.29 L844.05,153.29 L844.86,153.29 L845.67,153.29 L846.47,153.29 L847.28,153.29 L848.09,153.29 L848.89,153.29 L849.70,153.29 L850.51,153.29 L851.31,153.29 L852.12,153.29 L852.93,153.29 L853.73,153.29 L854.54,153.29 L855.35,153.29 L856.15,153.29 L856.96,153.29 L857.77,153.29 L858.57,153.29 L859.38,153.29 L860.19,153.29 L860.99,153.29 L861.80,153.29 L862.61,153.29 L863.41,153.29 L864.22,153.29 L865.03,153.29 L865.83,153.29 L866.64,153.29 L867.45,153.29 L868.25,153.29 L869.06,153.29 L869.87,153.29 L870.67,153.29 L871.48,153.29 L872.29,153.29 L873.09,153.29 L873.90,153.29 L874.71,153.29 L875.51,153.29 L876.32,153.29 L877.13,153.29 L877.93,153.29 L878.74,153.29 L879.55,153.29 L880.35,153.29 L881.16,153.29 L881.97,153.29 L882.77,153.29 L883.58,153.29 L884.39,153.29 L885.19,153.29 L886.00,153.29 " fill="none" stroke="#e8833a" stroke-width="1.8" stroke-dasharray="4 3"/><text x="882" y="92" font-size="9" fill="#e8833a" text-anchor="end">velocity (norm.)</text><rect x="944" y="68" width="242" height="116" fill="#fafbfc" stroke="#e3e6ea"/><text x="944" y="59" font-size="12" font-weight="600" fill="#333">overshoot bezier</text><line x1="944" x2="1186" y1="153.29411" y2="153.29411" stroke="#d5d9de" stroke-dasharray="3 3"/><text x="940" y="156.29411" font-size="9" fill="#888" text-anchor="end">0</text><line x1="944" x2="1186" y1="85.05882" y2="85.05882" stroke="#d5d9de" stroke-dasharray="3 3"/><text x="940" y="88.05882" font-size="9" fill="#888" text-anchor="end">1</text><text x="1186" y="198" font-size="9" fill="#888" text-anchor="end">0.70 s</text><path d="M944.00,153.29 L944.81,151.94 L945.61,150.61 L946.42,149.29 L947.23,147.98 L948.03,146.69 L948.84,145.41 L949.65,144.15 L950.45,142.90 L951.26,141.67 L952.07,140.45 L952.87,139.25 L953.68,138.06 L954.49,136.88 L955.29,135.72 L956.10,134.57 L956.91,133.44 L957.71,132.32 L958.52,131.22 L959.33,130.13 L960.13,129.05 L960.94,127.99 L961.75,126.95 L962.55,125.91 L963.36,124.89 L964.17,123.89 L964.97,122.90 L965.78,121.92 L966.59,120.95 L967.39,120.00 L968.20,119.07 L969.01,118.14 L969.81,117.23 L970.62,116.34 L971.43,115.45 L972.23,114.58 L973.04,113.73 L973.85,112.88 L974.65,112.05 L975.46,111.24 L976.27,110.43 L977.07,109.64 L977.88,108.86 L978.69,108.10 L979.49,107.34 L980.30,106.60 L981.11,105.87 L981.91,105.16 L982.72,104.46 L983.53,103.77 L984.33,103.09 L985.14,102.42 L985.95,101.77 L986.75,101.13 L987.56,100.50 L988.37,99.88 L989.17,99.27 L989.98,98.68 L990.79,98.10 L991.59,97.52 L992.40,96.96 L993.21,96.42 L994.01,95.88 L994.82,95.35 L995.63,94.84 L996.43,94.33 L997.24,93.84 L998.05,93.36 L998.85,92.89 L999.66,92.43 L1000.47,91.98 L1001.27,91.54 L1002.08,91.11 L1002.89,90.69 L1003.69,90.28 L1004.50,89.89 L1005.31,89.50 L1006.11,89.12 L1006.92,88.75 L1007.73,88.39 L1008.53,88.04 L1009.34,87.70 L1010.15,87.37 L1010.95,87.05 L1011.76,86.74 L1012.57,86.44 L1013.37,86.15 L1014.18,85.86 L1014.99,85.59 L1015.79,85.32 L1016.60,85.06 L1017.41,84.81 L1018.21,84.57 L1019.02,84.34 L1019.83,84.11 L1020.63,83.89 L1021.44,83.68 L1022.25,83.48 L1023.05,83.29 L1023.86,83.11 L1024.67,82.93 L1025.47,82.76 L1026.28,82.59 L1027.09,82.44 L1027.89,82.29 L1028.70,82.15 L1029.51,82.01 L1030.31,81.88 L1031.12,81.76 L1031.93,81.65 L1032.73,81.54 L1033.54,81.44 L1034.35,81.34 L1035.15,81.25 L1035.96,81.17 L1036.77,81.09 L1037.57,81.02 L1038.38,80.95 L1039.19,80.89 L1039.99,80.83 L1040.80,80.78 L1041.61,80.74 L1042.41,80.70 L1043.22,80.67 L1044.03,80.64 L1044.83,80.61 L1045.64,80.59 L1046.45,80.58 L1047.25,80.56 L1048.06,80.56 L1048.87,80.56 L1049.67,80.56 L1050.48,80.56 L1051.29,80.57 L1052.09,80.59 L1052.90,80.60 L1053.71,80.62 L1054.51,80.65 L1055.32,80.67 L1056.13,80.71 L1056.93,80.74 L1057.74,80.78 L1058.55,80.82 L1059.35,80.86 L1060.16,80.90 L1060.97,80.95 L1061.77,81.00 L1062.58,81.06 L1063.39,81.11 L1064.19,81.17 L1065.00,81.23 L1065.81,81.29 L1066.61,81.35 L1067.42,81.42 L1068.23,81.49 L1069.03,81.56 L1069.84,81.63 L1070.65,81.70 L1071.45,81.77 L1072.26,81.84 L1073.07,81.92 L1073.87,81.99 L1074.68,82.07 L1075.49,82.15 L1076.29,82.23 L1077.10,82.31 L1077.91,82.39 L1078.71,82.47 L1079.52,82.55 L1080.33,82.63 L1081.13,82.71 L1081.94,82.79 L1082.75,82.87 L1083.55,82.95 L1084.36,83.03 L1085.17,83.11 L1085.97,83.19 L1086.78,83.27 L1087.59,83.35 L1088.39,83.42 L1089.20,83.50 L1090.01,83.58 L1090.81,83.65 L1091.62,83.72 L1092.43,83.80 L1093.23,83.87 L1094.04,83.94 L1094.85,84.01 L1095.65,84.07 L1096.46,84.14 L1097.27,84.20 L1098.07,84.27 L1098.88,84.33 L1099.69,84.39 L1100.49,84.44 L1101.30,84.50 L1102.11,84.55 L1102.91,84.60 L1103.72,84.65 L1104.53,84.70 L1105.33,84.74 L1106.14,84.78 L1106.95,84.82 L1107.75,84.86 L1108.56,84.89 L1109.37,84.92 L1110.17,84.95 L1110.98,84.97 L1111.79,84.99 L1112.59,85.01 L1113.40,85.03 L1114.21,85.04 L1115.01,85.05 L1115.82,85.06 L1116.63,85.06 L1117.43,85.06 L1118.24,85.06 L1119.05,85.06 L1119.85,85.06 L1120.66,85.06 L1121.47,85.06 L1122.27,85.06 L1123.08,85.06 L1123.89,85.06 L1124.69,85.06 L1125.50,85.06 L1126.31,85.06 L1127.11,85.06 L1127.92,85.06 L1128.73,85.06 L1129.53,85.06 L1130.34,85.06 L1131.15,85.06 L1131.95,85.06 L1132.76,85.06 L1133.57,85.06 L1134.37,85.06 L1135.18,85.06 L1135.99,85.06 L1136.79,85.06 L1137.60,85.06 L1138.41,85.06 L1139.21,85.06 L1140.02,85.06 L1140.83,85.06 L1141.63,85.06 L1142.44,85.06 L1143.25,85.06 L1144.05,85.06 L1144.86,85.06 L1145.67,85.06 L1146.47,85.06 L1147.28,85.06 L1148.09,85.06 L1148.89,85.06 L1149.70,85.06 L1150.51,85.06 L1151.31,85.06 L1152.12,85.06 L1152.93,85.06 L1153.73,85.06 L1154.54,85.06 L1155.35,85.06 L1156.15,85.06 L1156.96,85.06 L1157.77,85.06 L1158.57,85.06 L1159.38,85.06 L1160.19,85.06 L1160.99,85.06 L1161.80,85.06 L1162.61,85.06 L1163.41,85.06 L1164.22,85.06 L1165.03,85.06 L1165.83,85.06 L1166.64,85.06 L1167.45,85.06 L1168.25,85.06 L1169.06,85.06 L1169.87,85.06 L1170.67,85.06 L1171.48,85.06 L1172.29,85.06 L1173.09,85.06 L1173.90,85.06 L1174.71,85.06 L1175.51,85.06 L1176.32,85.06 L1177.13,85.06 L1177.93,85.06 L1178.74,85.06 L1179.55,85.06 L1180.35,85.06 L1181.16,85.06 L1181.97,85.06 L1182.77,85.06 L1183.58,85.06 L1184.39,85.06 L1185.19,85.06 L1186.00,85.06 " fill="none" stroke="#2f6fec" stroke-width="1.8"/><text x="1182" y="80" font-size="9" fill="#2f6fec" text-anchor="end">position</text><path d="M944.00,85.06 L944.81,85.80 L945.61,86.55 L946.42,87.29 L947.23,88.03 L948.03,88.76 L948.84,89.50 L949.65,90.23 L950.45,90.97 L951.26,91.70 L952.07,92.43 L952.87,93.16 L953.68,93.88 L954.49,94.60 L955.29,95.33 L956.10,96.05 L956.91,96.76 L957.71,97.48 L958.52,98.19 L959.33,98.90 L960.13,99.61 L960.94,100.32 L961.75,101.02 L962.55,101.72 L963.36,102.42 L964.17,103.11 L964.97,103.81 L965.78,104.50 L966.59,105.19 L967.39,105.87 L968.20,106.55 L969.01,107.23 L969.81,107.91 L970.62,108.58 L971.43,109.25 L972.23,109.92 L973.04,110.58 L973.85,111.25 L974.65,111.90 L975.46,112.56 L976.27,113.21 L977.07,113.86 L977.88,114.50 L978.69,115.14 L979.49,115.78 L980.30,116.41 L981.11,117.04 L981.91,117.67 L982.72,118.29 L983.53,118.91 L984.33,119.53 L985.14,120.14 L985.95,120.74 L986.75,121.35 L987.56,121.95 L988.37,122.54 L989.17,123.13 L989.98,123.72 L990.79,124.30 L991.59,124.88 L992.40,125.46 L993.21,126.03 L994.01,126.59 L994.82,127.15 L995.63,127.71 L996.43,128.26 L997.24,128.81 L998.05,129.36 L998.85,129.89 L999.66,130.43 L1000.47,130.96 L1001.27,131.48 L1002.08,132.00 L1002.89,132.52 L1003.69,133.03 L1004.50,133.54 L1005.31,134.04 L1006.11,134.53 L1006.92,135.03 L1007.73,135.51 L1008.53,135.99 L1009.34,136.47 L1010.15,136.94 L1010.95,137.41 L1011.76,137.87 L1012.57,138.33 L1013.37,138.78 L1014.18,139.22 L1014.99,139.66 L1015.79,140.10 L1016.60,140.53 L1017.41,140.95 L1018.21,141.37 L1019.02,141.79 L1019.83,142.20 L1020.63,142.60 L1021.44,143.00 L1022.25,143.39 L1023.05,143.78 L1023.86,144.16 L1024.67,144.54 L1025.47,144.91 L1026.28,145.28 L1027.09,145.64 L1027.89,145.99 L1028.70,146.34 L1029.51,146.68 L1030.31,147.02 L1031.12,147.36 L1031.93,147.68 L1032.73,148.00 L1033.54,148.32 L1034.35,148.63 L1035.15,148.94 L1035.96,149.24 L1036.77,149.53 L1037.57,149.82 L1038.38,150.10 L1039.19,150.38 L1039.99,150.65 L1040.80,150.92 L1041.61,151.18 L1042.41,151.43 L1043.22,151.68 L1044.03,151.92 L1044.83,152.16 L1045.64,152.40 L1046.45,152.62 L1047.25,152.85 L1048.06,153.06 L1048.87,153.27 L1049.67,153.48 L1050.48,153.68 L1051.29,153.87 L1052.09,154.06 L1052.90,154.24 L1053.71,154.42 L1054.51,154.59 L1055.32,154.76 L1056.13,154.92 L1056.93,155.08 L1057.74,155.23 L1058.55,155.37 L1059.35,155.51 L1060.16,155.65 L1060.97,155.78 L1061.77,155.90 L1062.58,156.02 L1063.39,156.13 L1064.19,156.24 L1065.00,156.34 L1065.81,156.44 L1066.61,156.53 L1067.42,156.62 L1068.23,156.70 L1069.03,156.78 L1069.84,156.85 L1070.65,156.92 L1071.45,156.98 L1072.26,157.04 L1073.07,157.09 L1073.87,157.14 L1074.68,157.18 L1075.49,157.22 L1076.29,157.25 L1077.10,157.28 L1077.91,157.30 L1078.71,157.32 L1079.52,157.33 L1080.33,157.34 L1081.13,157.34 L1081.94,157.34 L1082.75,157.34 L1083.55,157.33 L1084.36,157.31 L1085.17,157.29 L1085.97,157.27 L1086.78,157.24 L1087.59,157.21 L1088.39,157.17 L1089.20,157.13 L1090.01,157.08 L1090.81,157.03 L1091.62,156.98 L1092.43,156.92 L1093.23,156.85 L1094.04,156.79 L1094.85,156.72 L1095.65,156.64 L1096.46,156.56 L1097.27,156.48 L1098.07,156.39 L1098.88,156.30 L1099.69,156.20 L1100.49,156.10 L1101.30,156.00 L1102.11,155.89 L1102.91,155.78 L1103.72,155.67 L1104.53,155.55 L1105.33,155.42 L1106.14,155.30 L1106.95,155.17 L1107.75,155.04 L1108.56,154.90 L1109.37,154.76 L1110.17,154.61 L1110.98,154.47 L1111.79,154.32 L1112.59,154.16 L1113.40,154.01 L1114.21,153.84 L1115.01,153.68 L1115.82,153.51 L1116.63,153.34 L1117.43,153.29 L1118.24,153.29 L1119.05,153.29 L1119.85,153.29 L1120.66,153.29 L1121.47,153.29 L1122.27,153.29 L1123.08,153.29 L1123.89,153.29 L1124.69,153.29 L1125.50,153.29 L1126.31,153.29 L1127.11,153.29 L1127.92,153.29 L1128.73,153.29 L1129.53,153.29 L1130.34,153.29 L1131.15,153.29 L1131.95,153.29 L1132.76,153.29 L1133.57,153.29 L1134.37,153.29 L1135.18,153.29 L1135.99,153.29 L1136.79,153.29 L1137.60,153.29 L1138.41,153.29 L1139.21,153.29 L1140.02,153.29 L1140.83,153.29 L1141.63,153.29 L1142.44,153.29 L1143.25,153.29 L1144.05,153.29 L1144.86,153.29 L1145.67,153.29 L1146.47,153.29 L1147.28,153.29 L1148.09,153.29 L1148.89,153.29 L1149.70,153.29 L1150.51,153.29 L1151.31,153.29 L1152.12,153.29 L1152.93,153.29 L1153.73,153.29 L1154.54,153.29 L1155.35,153.29 L1156.15,153.29 L1156.96,153.29 L1157.77,153.29 L1158.57,153.29 L1159.38,153.29 L1160.19,153.29 L1160.99,153.29 L1161.80,153.29 L1162.61,153.29 L1163.41,153.29 L1164.22,153.29 L1165.03,153.29 L1165.83,153.29 L1166.64,153.29 L1167.45,153.29 L1168.25,153.29 L1169.06,153.29 L1169.87,153.29 L1170.67,153.29 L1171.48,153.29 L1172.29,153.29 L1173.09,153.29 L1173.90,153.29 L1174.71,153.29 L1175.51,153.29 L1176.32,153.29 L1177.13,153.29 L1177.93,153.29 L1178.74,153.29 L1179.55,153.29 L1180.35,153.29 L1181.16,153.29 L1181.97,153.29 L1182.77,153.29 L1183.58,153.29 L1184.39,153.29 L1185.19,153.29 L1186.00,153.29 " fill="none" stroke="#e8833a" stroke-width="1.8" stroke-dasharray="4 3"/><text x="1182" y="92" font-size="9" fill="#e8833a" text-anchor="end">velocity (norm.)</text><rect x="44" y="238" width="242" height="116" fill="#fafbfc" stroke="#e3e6ea"/><text x="44" y="229" font-size="12" font-weight="600" fill="#333">steps(4)</text><line x1="44" x2="286" y1="323.29413" y2="323.29413" stroke="#d5d9de" stroke-dasharray="3 3"/><text x="40" y="326.29413" font-size="9" fill="#888" text-anchor="end">0</text><line x1="44" x2="286" y1="255.05882" y2="255.05882" stroke="#d5d9de" stroke-dasharray="3 3"/><text x="40" y="258.05884" font-size="9" fill="#888" text-anchor="end">1</text><text x="286" y="368" font-size="9" fill="#888" text-anchor="end">0.80 s</text><path d="M44.00,323.29 L44.81,323.29 L45.61,323.29 L46.42,323.29 L47.23,323.29 L48.03,323.29 L48.84,323.29 L49.65,323.29 L50.45,323.29 L51.26,323.29 L52.07,323.29 L52.87,323.29 L53.68,323.29 L54.49,323.29 L55.29,323.29 L56.10,323.29 L56.91,323.29 L57.71,323.29 L58.52,323.29 L59.33,323.29 L60.13,323.29 L60.94,323.29 L61.75,323.29 L62.55,323.29 L63.36,323.29 L64.17,323.29 L64.97,323.29 L65.78,323.29 L66.59,323.29 L67.39,323.29 L68.20,323.29 L69.01,323.29 L69.81,323.29 L70.62,323.29 L71.43,323.29 L72.23,323.29 L73.04,323.29 L73.85,323.29 L74.65,323.29 L75.46,323.29 L76.27,323.29 L77.07,323.29 L77.88,323.29 L78.69,323.29 L79.49,323.29 L80.30,323.29 L81.11,323.29 L81.91,323.29 L82.72,323.29 L83.53,323.29 L84.33,323.29 L85.14,323.29 L85.95,323.29 L86.75,323.29 L87.56,323.29 L88.37,323.29 L89.17,323.29 L89.98,306.24 L90.79,306.24 L91.59,306.24 L92.40,306.24 L93.21,306.24 L94.01,306.24 L94.82,306.24 L95.63,306.24 L96.43,306.24 L97.24,306.24 L98.05,306.24 L98.85,306.24 L99.66,306.24 L100.47,306.24 L101.27,306.24 L102.08,306.24 L102.89,306.24 L103.69,306.24 L104.50,306.24 L105.31,306.24 L106.11,306.24 L106.92,306.24 L107.73,306.24 L108.53,306.24 L109.34,306.24 L110.15,306.24 L110.95,306.24 L111.76,306.24 L112.57,306.24 L113.37,306.24 L114.18,306.24 L114.99,306.24 L115.79,306.24 L116.60,306.24 L117.41,306.24 L118.21,306.24 L119.02,306.24 L119.83,306.24 L120.63,306.24 L121.44,306.24 L122.25,306.24 L123.05,306.24 L123.86,306.24 L124.67,306.24 L125.47,306.24 L126.28,306.24 L127.09,306.24 L127.89,306.24 L128.70,306.24 L129.51,306.24 L130.31,306.24 L131.12,306.24 L131.93,306.24 L132.73,306.24 L133.54,306.24 L134.35,306.24 L135.15,289.18 L135.96,289.18 L136.77,289.18 L137.57,289.18 L138.38,289.18 L139.19,289.18 L139.99,289.18 L140.80,289.18 L141.61,289.18 L142.41,289.18 L143.22,289.18 L144.03,289.18 L144.83,289.18 L145.64,289.18 L146.45,289.18 L147.25,289.18 L148.06,289.18 L148.87,289.18 L149.67,289.18 L150.48,289.18 L151.29,289.18 L152.09,289.18 L152.90,289.18 L153.71,289.18 L154.51,289.18 L155.32,289.18 L156.13,289.18 L156.93,289.18 L157.74,289.18 L158.55,289.18 L159.35,289.18 L160.16,289.18 L160.97,289.18 L161.77,289.18 L162.58,289.18 L163.39,289.18 L164.19,289.18 L165.00,289.18 L165.81,289.18 L166.61,289.18 L167.42,289.18 L168.23,289.18 L169.03,289.18 L169.84,289.18 L170.65,289.18 L171.45,289.18 L172.26,289.18 L173.07,289.18 L173.87,289.18 L174.68,289.18 L175.49,289.18 L176.29,289.18 L177.10,289.18 L177.91,289.18 L178.71,289.18 L179.52,289.18 L180.33,272.12 L181.13,272.12 L181.94,272.12 L182.75,272.12 L183.55,272.12 L184.36,272.12 L185.17,272.12 L185.97,272.12 L186.78,272.12 L187.59,272.12 L188.39,272.12 L189.20,272.12 L190.01,272.12 L190.81,272.12 L191.62,272.12 L192.43,272.12 L193.23,272.12 L194.04,272.12 L194.85,272.12 L195.65,272.12 L196.46,272.12 L197.27,272.12 L198.07,272.12 L198.88,272.12 L199.69,272.12 L200.49,272.12 L201.30,272.12 L202.11,272.12 L202.91,272.12 L203.72,272.12 L204.53,272.12 L205.33,272.12 L206.14,272.12 L206.95,272.12 L207.75,272.12 L208.56,272.12 L209.37,272.12 L210.17,272.12 L210.98,272.12 L211.79,272.12 L212.59,272.12 L213.40,272.12 L214.21,272.12 L215.01,272.12 L215.82,272.12 L216.63,272.12 L217.43,272.12 L218.24,272.12 L219.05,272.12 L219.85,272.12 L220.66,272.12 L221.47,272.12 L222.27,272.12 L223.08,272.12 L223.89,272.12 L224.69,272.12 L225.50,255.06 L226.31,255.06 L227.11,255.06 L227.92,255.06 L228.73,255.06 L229.53,255.06 L230.34,255.06 L231.15,255.06 L231.95,255.06 L232.76,255.06 L233.57,255.06 L234.37,255.06 L235.18,255.06 L235.99,255.06 L236.79,255.06 L237.60,255.06 L238.41,255.06 L239.21,255.06 L240.02,255.06 L240.83,255.06 L241.63,255.06 L242.44,255.06 L243.25,255.06 L244.05,255.06 L244.86,255.06 L245.67,255.06 L246.47,255.06 L247.28,255.06 L248.09,255.06 L248.89,255.06 L249.70,255.06 L250.51,255.06 L251.31,255.06 L252.12,255.06 L252.93,255.06 L253.73,255.06 L254.54,255.06 L255.35,255.06 L256.15,255.06 L256.96,255.06 L257.77,255.06 L258.57,255.06 L259.38,255.06 L260.19,255.06 L260.99,255.06 L261.80,255.06 L262.61,255.06 L263.41,255.06 L264.22,255.06 L265.03,255.06 L265.83,255.06 L266.64,255.06 L267.45,255.06 L268.25,255.06 L269.06,255.06 L269.87,255.06 L270.67,255.06 L271.48,255.06 L272.29,255.06 L273.09,255.06 L273.90,255.06 L274.71,255.06 L275.51,255.06 L276.32,255.06 L277.13,255.06 L277.93,255.06 L278.74,255.06 L279.55,255.06 L280.35,255.06 L281.16,255.06 L281.97,255.06 L282.77,255.06 L283.58,255.06 L284.39,255.06 L285.19,255.06 L286.00,255.06 " fill="none" stroke="#2f6fec" stroke-width="1.8"/><text x="282" y="250" font-size="9" fill="#2f6fec" text-anchor="end">position</text><path d="M44.00,323.29 L44.81,323.29 L45.61,323.29 L46.42,323.29 L47.23,323.29 L48.03,323.29 L48.84,323.29 L49.65,323.29 L50.45,323.29 L51.26,323.29 L52.07,323.29 L52.87,323.29 L53.68,323.29 L54.49,323.29 L55.29,323.29 L56.10,323.29 L56.91,323.29 L57.71,323.29 L58.52,323.29 L59.33,323.29 L60.13,323.29 L60.94,323.29 L61.75,323.29 L62.55,323.29 L63.36,323.29 L64.17,323.29 L64.97,323.29 L65.78,323.29 L66.59,323.29 L67.39,323.29 L68.20,323.29 L69.01,323.29 L69.81,323.29 L70.62,323.29 L71.43,323.29 L72.23,323.29 L73.04,323.29 L73.85,323.29 L74.65,323.29 L75.46,323.29 L76.27,323.29 L77.07,323.29 L77.88,323.29 L78.69,323.29 L79.49,323.29 L80.30,323.29 L81.11,323.29 L81.91,323.29 L82.72,323.29 L83.53,323.29 L84.33,323.29 L85.14,323.29 L85.95,323.29 L86.75,323.29 L87.56,323.29 L88.37,323.29 L89.17,323.29 L89.98,323.29 L90.79,323.29 L91.59,323.29 L92.40,323.29 L93.21,323.29 L94.01,323.29 L94.82,323.29 L95.63,323.29 L96.43,323.29 L97.24,323.29 L98.05,323.29 L98.85,323.29 L99.66,323.29 L100.47,323.29 L101.27,323.29 L102.08,323.29 L102.89,323.29 L103.69,323.29 L104.50,323.29 L105.31,323.29 L106.11,323.29 L106.92,323.29 L107.73,323.29 L108.53,323.29 L109.34,323.29 L110.15,323.29 L110.95,323.29 L111.76,323.29 L112.57,323.29 L113.37,323.29 L114.18,323.29 L114.99,323.29 L115.79,323.29 L116.60,323.29 L117.41,323.29 L118.21,323.29 L119.02,323.29 L119.83,323.29 L120.63,323.29 L121.44,323.29 L122.25,323.29 L123.05,323.29 L123.86,323.29 L124.67,323.29 L125.47,323.29 L126.28,323.29 L127.09,323.29 L127.89,323.29 L128.70,323.29 L129.51,323.29 L130.31,323.29 L131.12,323.29 L131.93,323.29 L132.73,323.29 L133.54,323.29 L134.35,323.29 L135.15,323.29 L135.96,323.29 L136.77,323.29 L137.57,323.29 L138.38,323.29 L139.19,323.29 L139.99,323.29 L140.80,323.29 L141.61,323.29 L142.41,323.29 L143.22,323.29 L144.03,323.29 L144.83,323.29 L145.64,323.29 L146.45,323.29 L147.25,323.29 L148.06,323.29 L148.87,323.29 L149.67,323.29 L150.48,323.29 L151.29,323.29 L152.09,323.29 L152.90,323.29 L153.71,323.29 L154.51,323.29 L155.32,323.29 L156.13,323.29 L156.93,323.29 L157.74,323.29 L158.55,323.29 L159.35,323.29 L160.16,323.29 L160.97,323.29 L161.77,323.29 L162.58,323.29 L163.39,323.29 L164.19,323.29 L165.00,323.29 L165.81,323.29 L166.61,323.29 L167.42,323.29 L168.23,323.29 L169.03,323.29 L169.84,323.29 L170.65,323.29 L171.45,323.29 L172.26,323.29 L173.07,323.29 L173.87,323.29 L174.68,323.29 L175.49,323.29 L176.29,323.29 L177.10,323.29 L177.91,323.29 L178.71,323.29 L179.52,323.29 L180.33,323.29 L181.13,323.29 L181.94,323.29 L182.75,323.29 L183.55,323.29 L184.36,323.29 L185.17,323.29 L185.97,323.29 L186.78,323.29 L187.59,323.29 L188.39,323.29 L189.20,323.29 L190.01,323.29 L190.81,323.29 L191.62,323.29 L192.43,323.29 L193.23,323.29 L194.04,323.29 L194.85,323.29 L195.65,323.29 L196.46,323.29 L197.27,323.29 L198.07,323.29 L198.88,323.29 L199.69,323.29 L200.49,323.29 L201.30,323.29 L202.11,323.29 L202.91,323.29 L203.72,323.29 L204.53,323.29 L205.33,323.29 L206.14,323.29 L206.95,323.29 L207.75,323.29 L208.56,323.29 L209.37,323.29 L210.17,323.29 L210.98,323.29 L211.79,323.29 L212.59,323.29 L213.40,323.29 L214.21,323.29 L215.01,323.29 L215.82,323.29 L216.63,323.29 L217.43,323.29 L218.24,323.29 L219.05,323.29 L219.85,323.29 L220.66,323.29 L221.47,323.29 L222.27,323.29 L223.08,323.29 L223.89,323.29 L224.69,323.29 L225.50,323.29 L226.31,323.29 L227.11,323.29 L227.92,323.29 L228.73,323.29 L229.53,323.29 L230.34,323.29 L231.15,323.29 L231.95,323.29 L232.76,323.29 L233.57,323.29 L234.37,323.29 L235.18,323.29 L235.99,323.29 L236.79,323.29 L237.60,323.29 L238.41,323.29 L239.21,323.29 L240.02,323.29 L240.83,323.29 L241.63,323.29 L242.44,323.29 L243.25,323.29 L244.05,323.29 L244.86,323.29 L245.67,323.29 L246.47,323.29 L247.28,323.29 L248.09,323.29 L248.89,323.29 L249.70,323.29 L250.51,323.29 L251.31,323.29 L252.12,323.29 L252.93,323.29 L253.73,323.29 L254.54,323.29 L255.35,323.29 L256.15,323.29 L256.96,323.29 L257.77,323.29 L258.57,323.29 L259.38,323.29 L260.19,323.29 L260.99,323.29 L261.80,323.29 L262.61,323.29 L263.41,323.29 L264.22,323.29 L265.03,323.29 L265.83,323.29 L266.64,323.29 L267.45,323.29 L268.25,323.29 L269.06,323.29 L269.87,323.29 L270.67,323.29 L271.48,323.29 L272.29,323.29 L273.09,323.29 L273.90,323.29 L274.71,323.29 L275.51,323.29 L276.32,323.29 L277.13,323.29 L277.93,323.29 L278.74,323.29 L279.55,323.29 L280.35,323.29 L281.16,323.29 L281.97,323.29 L282.77,323.29 L283.58,323.29 L284.39,323.29 L285.19,323.29 L286.00,323.29 " fill="none" stroke="#e8833a" stroke-width="1.8" stroke-dasharray="4 3"/><text x="282" y="262" font-size="9" fill="#e8833a" text-anchor="end">velocity (norm.)</text><rect x="344" y="238" width="242" height="116" fill="#fafbfc" stroke="#e3e6ea"/><text x="344" y="229" font-size="12" font-weight="600" fill="#333">linear() piecewise</text><line x1="344" x2="586" y1="323.29413" y2="323.29413" stroke="#d5d9de" stroke-dasharray="3 3"/><text x="340" y="326.29413" font-size="9" fill="#888" text-anchor="end">0</text><line x1="344" x2="586" y1="255.05882" y2="255.05882" stroke="#d5d9de" stroke-dasharray="3 3"/><text x="340" y="258.05884" font-size="9" fill="#888" text-anchor="end">1</text><text x="586" y="368" font-size="9" fill="#888" text-anchor="end">0.80 s</text><path d="M344.00,323.29 L344.81,322.59 L345.61,321.88 L346.42,321.17 L347.23,320.46 L348.03,319.76 L348.84,319.05 L349.65,318.34 L350.45,317.63 L351.26,316.93 L352.07,316.22 L352.87,315.51 L353.68,314.80 L354.49,314.10 L355.29,313.39 L356.10,312.68 L356.91,311.97 L357.71,311.26 L358.52,310.56 L359.33,309.85 L360.13,309.14 L360.94,308.43 L361.75,307.73 L362.55,307.02 L363.36,306.31 L364.17,305.60 L364.97,304.90 L365.78,304.19 L366.59,303.48 L367.39,302.77 L368.20,302.07 L369.01,301.36 L369.81,300.65 L370.62,299.94 L371.43,299.23 L372.23,298.53 L373.04,297.82 L373.85,297.11 L374.65,296.40 L375.46,295.70 L376.27,294.99 L377.07,294.28 L377.88,293.57 L378.69,292.87 L379.49,292.16 L380.30,291.45 L381.11,290.74 L381.91,290.04 L382.72,289.33 L383.53,288.62 L384.33,287.91 L385.14,287.21 L385.95,286.50 L386.75,285.79 L387.56,285.08 L388.37,284.37 L389.17,283.67 L389.98,282.96 L390.79,282.25 L391.59,281.54 L392.40,280.84 L393.21,280.13 L394.01,279.42 L394.82,278.71 L395.63,278.01 L396.43,277.30 L397.24,276.59 L398.05,275.88 L398.85,275.43 L399.66,275.23 L400.47,275.02 L401.27,274.82 L402.08,274.62 L402.89,274.42 L403.69,274.22 L404.50,274.01 L405.31,273.81 L406.11,273.61 L406.92,273.41 L407.73,273.20 L408.53,273.00 L409.34,272.80 L410.15,272.60 L410.95,272.40 L411.76,272.19 L412.57,271.99 L413.37,271.79 L414.18,271.59 L414.99,271.38 L415.79,271.18 L416.60,270.98 L417.41,270.78 L418.21,270.58 L419.02,270.37 L419.83,270.17 L420.63,269.97 L421.44,269.77 L422.25,269.57 L423.05,269.36 L423.86,269.16 L424.67,268.96 L425.47,268.76 L426.28,268.55 L427.09,268.35 L427.89,268.15 L428.70,267.95 L429.51,267.75 L430.31,267.54 L431.12,267.34 L431.93,267.14 L432.73,266.94 L433.54,266.73 L434.35,266.53 L435.15,266.33 L435.96,266.13 L436.77,265.93 L437.57,265.72 L438.38,265.52 L439.19,265.32 L439.99,265.12 L440.80,264.92 L441.61,264.71 L442.41,264.51 L443.22,264.31 L444.03,264.11 L444.83,263.90 L445.64,263.70 L446.45,263.50 L447.25,263.30 L448.06,263.10 L448.87,262.89 L449.67,262.69 L450.48,262.49 L451.29,262.29 L452.09,262.08 L452.90,261.88 L453.71,261.81 L454.51,261.73 L455.32,261.65 L456.13,261.58 L456.93,261.50 L457.74,261.43 L458.55,261.35 L459.35,261.28 L460.16,261.20 L460.97,261.12 L461.77,261.05 L462.58,260.97 L463.39,260.90 L464.19,260.82 L465.00,260.75 L465.81,260.67 L466.61,260.59 L467.42,260.52 L468.23,260.44 L469.03,260.37 L469.84,260.29 L470.65,260.21 L471.45,260.14 L472.26,260.06 L473.07,259.99 L473.87,259.91 L474.68,259.84 L475.49,259.76 L476.29,259.68 L477.10,259.61 L477.91,259.53 L478.71,259.46 L479.52,259.38 L480.33,259.30 L481.13,259.23 L481.94,259.15 L482.75,259.08 L483.55,259.00 L484.36,258.93 L485.17,258.85 L485.97,258.77 L486.78,258.70 L487.59,258.62 L488.39,258.55 L489.20,258.47 L490.01,258.39 L490.81,258.32 L491.62,258.24 L492.43,258.17 L493.23,258.09 L494.04,258.02 L494.85,257.94 L495.65,257.86 L496.46,257.79 L497.27,257.71 L498.07,257.64 L498.88,257.56 L499.69,257.48 L500.49,257.41 L501.30,257.33 L502.11,257.26 L502.91,257.18 L503.72,257.11 L504.53,257.03 L505.33,256.95 L506.14,256.88 L506.95,256.80 L507.75,256.73 L508.56,256.65 L509.37,256.58 L510.17,256.50 L510.98,256.42 L511.79,256.35 L512.59,256.27 L513.40,256.20 L514.21,256.12 L515.01,256.04 L515.82,255.97 L516.63,255.89 L517.43,255.82 L518.24,255.74 L519.05,255.67 L519.85,255.59 L520.66,255.51 L521.47,255.44 L522.27,255.36 L523.08,255.29 L523.89,255.21 L524.69,255.13 L525.50,255.06 L526.31,255.06 L527.11,255.06 L527.92,255.06 L528.73,255.06 L529.53,255.06 L530.34,255.06 L531.15,255.06 L531.95,255.06 L532.76,255.06 L533.57,255.06 L534.37,255.06 L535.18,255.06 L535.99,255.06 L536.79,255.06 L537.60,255.06 L538.41,255.06 L539.21,255.06 L540.02,255.06 L540.83,255.06 L541.63,255.06 L542.44,255.06 L543.25,255.06 L544.05,255.06 L544.86,255.06 L545.67,255.06 L546.47,255.06 L547.28,255.06 L548.09,255.06 L548.89,255.06 L549.70,255.06 L550.51,255.06 L551.31,255.06 L552.12,255.06 L552.93,255.06 L553.73,255.06 L554.54,255.06 L555.35,255.06 L556.15,255.06 L556.96,255.06 L557.77,255.06 L558.57,255.06 L559.38,255.06 L560.19,255.06 L560.99,255.06 L561.80,255.06 L562.61,255.06 L563.41,255.06 L564.22,255.06 L565.03,255.06 L565.83,255.06 L566.64,255.06 L567.45,255.06 L568.25,255.06 L569.06,255.06 L569.87,255.06 L570.67,255.06 L571.48,255.06 L572.29,255.06 L573.09,255.06 L573.90,255.06 L574.71,255.06 L575.51,255.06 L576.32,255.06 L577.13,255.06 L577.93,255.06 L578.74,255.06 L579.55,255.06 L580.35,255.06 L581.16,255.06 L581.97,255.06 L582.77,255.06 L583.58,255.06 L584.39,255.06 L585.19,255.06 L586.00,255.06 " fill="none" stroke="#2f6fec" stroke-width="1.8"/><text x="582" y="250" font-size="9" fill="#2f6fec" text-anchor="end">position</text><path d="M344.00,255.06 L344.81,255.06 L345.61,255.06 L346.42,255.06 L347.23,255.06 L348.03,255.06 L348.84,255.06 L349.65,255.06 L350.45,255.06 L351.26,255.06 L352.07,255.06 L352.87,255.06 L353.68,255.06 L354.49,255.06 L355.29,255.06 L356.10,255.06 L356.91,255.06 L357.71,255.06 L358.52,255.06 L359.33,255.06 L360.13,255.06 L360.94,255.06 L361.75,255.06 L362.55,255.06 L363.36,255.06 L364.17,255.06 L364.97,255.06 L365.78,255.06 L366.59,255.06 L367.39,255.06 L368.20,255.06 L369.01,255.06 L369.81,255.06 L370.62,255.06 L371.43,255.06 L372.23,255.06 L373.04,255.06 L373.85,255.06 L374.65,255.06 L375.46,255.06 L376.27,255.06 L377.07,255.06 L377.88,255.06 L378.69,255.06 L379.49,255.06 L380.30,255.06 L381.11,255.06 L381.91,255.06 L382.72,255.06 L383.53,255.06 L384.33,255.06 L385.14,255.06 L385.95,255.06 L386.75,255.06 L387.56,255.06 L388.37,255.06 L389.17,255.06 L389.98,255.06 L390.79,255.06 L391.59,255.06 L392.40,255.06 L393.21,255.06 L394.01,255.06 L394.82,255.06 L395.63,255.06 L396.43,255.06 L397.24,255.06 L398.05,255.06 L398.85,303.80 L399.66,303.80 L400.47,303.80 L401.27,303.80 L402.08,303.80 L402.89,303.80 L403.69,303.80 L404.50,303.80 L405.31,303.80 L406.11,303.80 L406.92,303.80 L407.73,303.80 L408.53,303.80 L409.34,303.80 L410.15,303.80 L410.95,303.80 L411.76,303.80 L412.57,303.80 L413.37,303.80 L414.18,303.80 L414.99,303.80 L415.79,303.80 L416.60,303.80 L417.41,303.80 L418.21,303.80 L419.02,303.80 L419.83,303.80 L420.63,303.80 L421.44,303.80 L422.25,303.80 L423.05,303.80 L423.86,303.80 L424.67,303.80 L425.47,303.80 L426.28,303.80 L427.09,303.80 L427.89,303.80 L428.70,303.80 L429.51,303.80 L430.31,303.80 L431.12,303.80 L431.93,303.80 L432.73,303.80 L433.54,303.80 L434.35,303.80 L435.15,303.80 L435.96,303.80 L436.77,303.80 L437.57,303.80 L438.38,303.80 L439.19,303.80 L439.99,303.80 L440.80,303.80 L441.61,303.80 L442.41,303.80 L443.22,303.80 L444.03,303.80 L444.83,303.80 L445.64,303.80 L446.45,303.80 L447.25,303.80 L448.06,303.80 L448.87,303.80 L449.67,303.80 L450.48,303.80 L451.29,303.80 L452.09,303.80 L452.90,315.98 L453.71,315.98 L454.51,315.98 L455.32,315.98 L456.13,315.98 L456.93,315.98 L457.74,315.98 L458.55,315.98 L459.35,315.98 L460.16,315.98 L460.97,315.98 L461.77,315.98 L462.58,315.98 L463.39,315.98 L464.19,315.98 L465.00,315.98 L465.81,315.98 L466.61,315.98 L467.42,315.98 L468.23,315.98 L469.03,315.98 L469.84,315.98 L470.65,315.98 L471.45,315.98 L472.26,315.98 L473.07,315.98 L473.87,315.98 L474.68,315.98 L475.49,315.98 L476.29,315.98 L477.10,315.98 L477.91,315.98 L478.71,315.98 L479.52,315.98 L480.33,315.98 L481.13,315.98 L481.94,315.98 L482.75,315.98 L483.55,315.98 L484.36,315.98 L485.17,315.98 L485.97,315.98 L486.78,315.98 L487.59,315.98 L488.39,315.98 L489.20,315.98 L490.01,315.98 L490.81,315.98 L491.62,315.98 L492.43,315.98 L493.23,315.98 L494.04,315.98 L494.85,315.98 L495.65,315.98 L496.46,315.98 L497.27,315.98 L498.07,315.98 L498.88,315.98 L499.69,315.98 L500.49,315.98 L501.30,315.98 L502.11,315.98 L502.91,315.98 L503.72,315.98 L504.53,315.98 L505.33,315.98 L506.14,315.98 L506.95,315.98 L507.75,315.98 L508.56,315.98 L509.37,315.98 L510.17,315.98 L510.98,315.98 L511.79,315.98 L512.59,315.98 L513.40,315.98 L514.21,315.98 L515.01,315.98 L515.82,315.98 L516.63,315.98 L517.43,315.98 L518.24,315.98 L519.05,315.98 L519.85,315.98 L520.66,315.98 L521.47,315.98 L522.27,315.98 L523.08,315.98 L523.89,315.98 L524.69,315.98 L525.50,315.98 L526.31,315.98 L527.11,315.98 L527.92,315.98 L528.73,315.98 L529.53,315.98 L530.34,315.98 L531.15,315.98 L531.95,315.98 L532.76,315.98 L533.57,315.98 L534.37,315.98 L535.18,315.98 L535.99,315.98 L536.79,315.98 L537.60,315.98 L538.41,315.98 L539.21,315.98 L540.02,315.98 L540.83,315.98 L541.63,315.98 L542.44,315.98 L543.25,315.98 L544.05,315.98 L544.86,315.98 L545.67,315.98 L546.47,315.98 L547.28,315.98 L548.09,315.98 L548.89,315.98 L549.70,315.98 L550.51,315.98 L551.31,315.98 L552.12,315.98 L552.93,315.98 L553.73,315.98 L554.54,315.98 L555.35,315.98 L556.15,315.98 L556.96,315.98 L557.77,315.98 L558.57,315.98 L559.38,315.98 L560.19,315.98 L560.99,315.98 L561.80,315.98 L562.61,315.98 L563.41,315.98 L564.22,315.98 L565.03,315.98 L565.83,315.98 L566.64,315.98 L567.45,315.98 L568.25,315.98 L569.06,315.98 L569.87,315.98 L570.67,315.98 L571.48,315.98 L572.29,315.98 L573.09,315.98 L573.90,315.98 L574.71,315.98 L575.51,315.98 L576.32,315.98 L577.13,315.98 L577.93,315.98 L578.74,315.98 L579.55,315.98 L580.35,315.98 L581.16,315.98 L581.97,315.98 L582.77,315.98 L583.58,315.98 L584.39,315.98 L585.19,315.98 L586.00,315.98 " fill="none" stroke="#e8833a" stroke-width="1.8" stroke-dasharray="4 3"/><text x="582" y="262" font-size="9" fill="#e8833a" text-anchor="end">velocity (norm.)</text><rect x="644" y="238" width="242" height="116" fill="#fafbfc" stroke="#e3e6ea"/><text x="644" y="229" font-size="12" font-weight="600" fill="#333">decay 0.998/ms (fling v=2)</text><line x1="644" x2="886" y1="345.4074" y2="345.4074" stroke="#d5d9de" stroke-dasharray="3 3"/><text x="640" y="348.4074" font-size="9" fill="#888" text-anchor="end">0</text><line x1="644" x2="886" y1="259.48148" y2="259.48148" stroke="#d5d9de" stroke-dasharray="3 3"/><text x="640" y="262.48148" font-size="9" fill="#888" text-anchor="end">1</text><text x="886" y="368" font-size="9" fill="#888" text-anchor="end">3.00 s</text><path d="M644.00,345.41 L644.81,343.71 L645.61,342.04 L646.42,340.40 L647.23,338.80 L648.03,337.23 L648.84,335.69 L649.65,334.18 L650.45,332.70 L651.26,331.25 L652.07,329.83 L652.87,328.44 L653.68,327.08 L654.49,325.74 L655.29,324.43 L656.10,323.14 L656.91,321.88 L657.71,320.64 L658.52,319.43 L659.33,318.25 L660.13,317.08 L660.94,315.94 L661.75,314.83 L662.55,313.73 L663.36,312.66 L664.17,311.61 L664.97,310.57 L665.78,309.56 L666.59,308.57 L667.39,307.60 L668.20,306.65 L669.01,305.72 L669.81,304.80 L670.62,303.90 L671.43,303.03 L672.23,302.16 L673.04,301.32 L673.85,300.49 L674.65,299.68 L675.46,298.89 L676.27,298.11 L677.07,297.34 L677.88,296.59 L678.69,295.86 L679.49,295.14 L680.30,294.44 L681.11,293.74 L681.91,293.07 L682.72,292.40 L683.53,291.75 L684.33,291.11 L685.14,290.49 L685.95,289.88 L686.75,289.28 L687.56,288.69 L688.37,288.11 L689.17,287.54 L689.98,286.99 L690.79,286.45 L691.59,285.91 L692.40,285.39 L693.21,284.88 L694.01,284.38 L694.82,283.89 L695.63,283.40 L696.43,282.93 L697.24,282.47 L698.05,282.01 L698.85,281.57 L699.66,281.13 L700.47,280.71 L701.27,280.29 L702.08,279.88 L702.89,279.47 L703.69,279.08 L704.50,278.69 L705.31,278.31 L706.11,277.94 L706.92,277.58 L707.73,277.22 L708.53,276.87 L709.34,276.53 L710.15,276.19 L710.95,275.86 L711.76,275.54 L712.57,275.22 L713.37,274.91 L714.18,274.61 L714.99,274.31 L715.79,274.02 L716.60,273.73 L717.41,273.45 L718.21,273.18 L719.02,272.91 L719.83,272.64 L720.63,272.38 L721.44,272.13 L722.25,271.88 L723.05,271.63 L723.86,271.40 L724.67,271.16 L725.47,270.93 L726.28,270.71 L727.09,270.49 L727.89,270.27 L728.70,270.06 L729.51,269.85 L730.31,269.65 L731.12,269.45 L731.93,269.25 L732.73,269.06 L733.54,268.87 L734.35,268.69 L735.15,268.50 L735.96,268.33 L736.77,268.15 L737.57,267.98 L738.38,267.82 L739.19,267.65 L739.99,267.49 L740.80,267.34 L741.61,267.18 L742.41,267.03 L743.22,266.88 L744.03,266.74 L744.83,266.60 L745.64,266.46 L746.45,266.32 L747.25,266.19 L748.06,266.06 L748.87,265.93 L749.67,265.80 L750.48,265.68 L751.29,265.56 L752.09,265.44 L752.90,265.32 L753.71,265.21 L754.51,265.09 L755.32,264.99 L756.13,264.88 L756.93,264.77 L757.74,264.67 L758.55,264.57 L759.35,264.47 L760.16,264.37 L760.97,264.28 L761.77,264.18 L762.58,264.09 L763.39,264.00 L764.19,263.91 L765.00,263.83 L765.81,263.74 L766.61,263.66 L767.42,263.58 L768.23,263.50 L769.03,263.42 L769.84,263.35 L770.65,263.27 L771.45,263.20 L772.26,263.13 L773.07,263.06 L773.87,262.99 L774.68,262.92 L775.49,262.85 L776.29,262.79 L777.10,262.72 L777.91,262.66 L778.71,262.60 L779.52,262.54 L780.33,262.48 L781.13,262.42 L781.94,262.37 L782.75,262.31 L783.55,262.26 L784.36,262.20 L785.17,262.15 L785.97,262.10 L786.78,262.05 L787.59,262.00 L788.39,261.95 L789.20,261.90 L790.01,261.86 L790.81,261.81 L791.62,261.77 L792.43,261.72 L793.23,261.68 L794.04,261.64 L794.85,261.60 L795.65,261.56 L796.46,261.52 L797.27,261.48 L798.07,261.44 L798.88,261.41 L799.69,261.37 L800.49,261.33 L801.30,261.30 L802.11,261.26 L802.91,261.23 L803.72,261.20 L804.53,261.17 L805.33,261.13 L806.14,261.10 L806.95,261.07 L807.75,261.04 L808.56,261.01 L809.37,260.98 L810.17,260.96 L810.98,260.93 L811.79,260.90 L812.59,260.88 L813.40,260.85 L814.21,260.82 L815.01,260.80 L815.82,260.77 L816.63,260.75 L817.43,260.73 L818.24,260.70 L819.05,260.68 L819.85,260.66 L820.66,260.64 L821.47,260.62 L822.27,260.60 L823.08,260.58 L823.89,260.56 L824.69,260.54 L825.50,260.52 L826.31,260.50 L827.11,260.48 L827.92,260.46 L828.73,260.44 L829.53,260.43 L830.34,260.41 L831.15,260.39 L831.95,260.38 L832.76,260.36 L833.57,260.34 L834.37,260.33 L835.18,260.31 L835.99,260.30 L836.79,260.28 L837.60,260.27 L838.41,260.26 L839.21,260.24 L840.02,260.23 L840.83,260.22 L841.63,260.20 L842.44,260.19 L843.25,260.18 L844.05,260.17 L844.86,260.15 L845.67,260.14 L846.47,260.13 L847.28,260.12 L848.09,260.11 L848.89,260.10 L849.70,260.09 L850.51,260.08 L851.31,260.07 L852.12,260.06 L852.93,260.05 L853.73,260.04 L854.54,260.03 L855.35,260.02 L856.15,260.01 L856.96,260.00 L857.77,259.99 L858.57,259.99 L859.38,259.98 L860.19,259.97 L860.99,259.96 L861.80,259.95 L862.61,259.95 L863.41,259.94 L864.22,259.93 L865.03,259.92 L865.83,259.92 L866.64,259.91 L867.45,259.57 L868.25,259.57 L869.06,259.57 L869.87,259.57 L870.67,259.57 L871.48,259.57 L872.29,259.57 L873.09,259.57 L873.90,259.57 L874.71,259.57 L875.51,259.57 L876.32,259.57 L877.13,259.57 L877.93,259.57 L878.74,259.57 L879.55,259.57 L880.35,259.57 L881.16,259.57 L881.97,259.57 L882.77,259.57 L883.58,259.57 L884.39,259.57 L885.19,259.57 L886.00,259.57 " fill="none" stroke="#2f6fec" stroke-width="1.8"/><text x="882" y="250" font-size="9" fill="#2f6fec" text-anchor="end">position</text><path d="M644.00,259.48 L644.81,261.18 L645.61,262.85 L646.42,264.49 L647.23,266.09 L648.03,267.67 L648.84,269.21 L649.65,270.72 L650.45,272.20 L651.26,273.65 L652.07,275.07 L652.87,276.47 L653.68,277.83 L654.49,279.17 L655.29,280.48 L656.10,281.77 L656.91,283.03 L657.71,284.27 L658.52,285.48 L659.33,286.67 L660.13,287.83 L660.94,288.97 L661.75,290.09 L662.55,291.19 L663.36,292.26 L664.17,293.32 L664.97,294.35 L665.78,295.36 L666.59,296.35 L667.39,297.33 L668.20,298.28 L669.01,299.21 L669.81,300.13 L670.62,301.03 L671.43,301.91 L672.23,302.77 L673.04,303.61 L673.85,304.44 L674.65,305.25 L675.46,306.05 L676.27,306.83 L677.07,307.59 L677.88,308.34 L678.69,309.08 L679.49,309.80 L680.30,310.50 L681.11,311.20 L681.91,311.87 L682.72,312.54 L683.53,313.19 L684.33,313.83 L685.14,314.45 L685.95,315.07 L686.75,315.67 L687.56,316.26 L688.37,316.84 L689.17,317.40 L689.98,317.96 L690.79,318.50 L691.59,319.04 L692.40,319.56 L693.21,320.07 L694.01,320.57 L694.82,321.06 L695.63,321.55 L696.43,322.02 L697.24,322.48 L698.05,322.94 L698.85,323.38 L699.66,323.82 L700.47,324.25 L701.27,324.67 L702.08,325.08 L702.89,325.48 L703.69,325.88 L704.50,326.26 L705.31,326.64 L706.11,327.01 L706.92,327.38 L707.73,327.74 L708.53,328.09 L709.34,328.43 L710.15,328.77 L710.95,329.10 L711.76,329.42 L712.57,329.74 L713.37,330.05 L714.18,330.35 L714.99,330.65 L715.79,330.94 L716.60,331.23 L717.41,331.51 L718.21,331.79 L719.02,332.06 L719.83,332.32 L720.63,332.58 L721.44,332.83 L722.25,333.08 L723.05,333.33 L723.86,333.57 L724.67,333.80 L725.47,334.03 L726.28,334.26 L727.09,334.48 L727.89,334.69 L728.70,334.91 L729.51,335.12 L730.31,335.32 L731.12,335.52 L731.93,335.72 L732.73,335.91 L733.54,336.10 L734.35,336.28 L735.15,336.46 L735.96,336.64 L736.77,336.81 L737.57,336.98 L738.38,337.15 L739.19,337.31 L739.99,337.47 L740.80,337.63 L741.61,337.79 L742.41,337.94 L743.22,338.08 L744.03,338.23 L744.83,338.37 L745.64,338.51 L746.45,338.65 L747.25,338.78 L748.06,338.91 L748.87,339.04 L749.67,339.17 L750.48,339.29 L751.29,339.41 L752.09,339.53 L752.90,339.65 L753.71,339.76 L754.51,339.87 L755.32,339.98 L756.13,340.09 L756.93,340.20 L757.74,340.30 L758.55,340.40 L759.35,340.50 L760.16,340.60 L760.97,340.69 L761.77,340.79 L762.58,340.88 L763.39,340.97 L764.19,341.06 L765.00,341.14 L765.81,341.23 L766.61,341.31 L767.42,341.39 L768.23,341.47 L769.03,341.55 L769.84,341.62 L770.65,341.70 L771.45,341.77 L772.26,341.85 L773.07,341.92 L773.87,341.99 L774.68,342.05 L775.49,342.12 L776.29,342.18 L777.10,342.25 L777.91,342.31 L778.71,342.37 L779.52,342.43 L780.33,342.49 L781.13,342.55 L781.94,342.61 L782.75,342.66 L783.55,342.72 L784.36,342.77 L785.17,342.82 L785.97,342.87 L786.78,342.92 L787.59,342.97 L788.39,343.02 L789.20,343.07 L790.01,343.11 L790.81,343.16 L791.62,343.20 L792.43,343.25 L793.23,343.29 L794.04,343.33 L794.85,343.37 L795.65,343.41 L796.46,343.45 L797.27,343.49 L798.07,343.53 L798.88,343.57 L799.69,343.60 L800.49,343.64 L801.30,343.67 L802.11,343.71 L802.91,343.74 L803.72,343.78 L804.53,343.81 L805.33,343.84 L806.14,343.87 L806.95,343.90 L807.75,343.93 L808.56,343.96 L809.37,343.99 L810.17,344.02 L810.98,344.04 L811.79,344.07 L812.59,344.10 L813.40,344.12 L814.21,344.15 L815.01,344.17 L815.82,344.20 L816.63,344.22 L817.43,344.25 L818.24,344.27 L819.05,344.29 L819.85,344.31 L820.66,344.34 L821.47,344.36 L822.27,344.38 L823.08,344.40 L823.89,344.42 L824.69,344.44 L825.50,344.46 L826.31,344.48 L827.11,344.49 L827.92,344.51 L828.73,344.53 L829.53,344.55 L830.34,344.56 L831.15,344.58 L831.95,344.60 L832.76,344.61 L833.57,344.63 L834.37,344.64 L835.18,344.66 L835.99,344.67 L836.79,344.69 L837.60,344.70 L838.41,344.72 L839.21,344.73 L840.02,344.74 L840.83,344.76 L841.63,344.77 L842.44,344.78 L843.25,344.80 L844.05,344.81 L844.86,344.82 L845.67,344.83 L846.47,344.84 L847.28,344.85 L848.09,344.86 L848.89,344.88 L849.70,344.89 L850.51,344.90 L851.31,344.91 L852.12,344.92 L852.93,344.93 L853.73,344.94 L854.54,344.95 L855.35,344.95 L856.15,344.96 L856.96,344.97 L857.77,344.98 L858.57,344.99 L859.38,345.00 L860.19,345.01 L860.99,345.01 L861.80,345.02 L862.61,345.03 L863.41,345.04 L864.22,345.04 L865.03,345.05 L865.83,345.06 L866.64,345.07 L867.45,345.41 L868.25,345.41 L869.06,345.41 L869.87,345.41 L870.67,345.41 L871.48,345.41 L872.29,345.41 L873.09,345.41 L873.90,345.41 L874.71,345.41 L875.51,345.41 L876.32,345.41 L877.13,345.41 L877.93,345.41 L878.74,345.41 L879.55,345.41 L880.35,345.41 L881.16,345.41 L881.97,345.41 L882.77,345.41 L883.58,345.41 L884.39,345.41 L885.19,345.41 L886.00,345.41 " fill="none" stroke="#e8833a" stroke-width="1.8" stroke-dasharray="4 3"/><text x="882" y="262" font-size="9" fill="#e8833a" text-anchor="end">velocity</text><rect x="944" y="238" width="242" height="116" fill="#fafbfc" stroke="#e3e6ea"/><text x="944" y="229" font-size="12" font-weight="600" fill="#333">keyframes: linear, cubic, cubic, spring</text><line x1="944" x2="1186" y1="323.29413" y2="323.29413" stroke="#d5d9de" stroke-dasharray="3 3"/><text x="940" y="326.29413" font-size="9" fill="#888" text-anchor="end">0</text><line x1="944" x2="1186" y1="255.05882" y2="255.05882" stroke="#d5d9de" stroke-dasharray="3 3"/><text x="940" y="258.05884" font-size="9" fill="#888" text-anchor="end">1</text><text x="1186" y="368" font-size="9" fill="#888" text-anchor="end">1.00 s</text><line x1="980.3" x2="980.3" y1="238" y2="354" stroke="#d64545" stroke-width="1" stroke-dasharray="2 3"/><line x1="1028.7" x2="1028.7" y1="238" y2="354" stroke="#d64545" stroke-width="1" stroke-dasharray="2 3"/><line x1="1065" x2="1065" y1="238" y2="354" stroke="#d64545" stroke-width="1" stroke-dasharray="2 3"/><path d="M944.00,323.29 L944.81,322.69 L945.61,322.08 L946.42,321.47 L947.23,320.87 L948.03,320.26 L948.84,319.65 L949.65,319.05 L950.45,318.44 L951.26,317.84 L952.07,317.23 L952.87,316.62 L953.68,316.02 L954.49,315.41 L955.29,314.80 L956.10,314.20 L956.91,313.59 L957.71,312.98 L958.52,312.38 L959.33,311.77 L960.13,311.16 L960.94,310.56 L961.75,309.95 L962.55,309.34 L963.36,308.74 L964.17,308.13 L964.97,307.52 L965.78,306.92 L966.59,306.31 L967.39,305.70 L968.20,305.10 L969.01,304.49 L969.81,303.88 L970.62,303.28 L971.43,302.67 L972.23,302.07 L973.04,301.46 L973.85,300.85 L974.65,300.25 L975.46,299.64 L976.27,299.03 L977.07,298.43 L977.88,297.82 L978.69,297.21 L979.49,296.61 L980.30,296.00 L981.11,295.38 L981.91,294.73 L982.72,294.05 L983.53,293.34 L984.33,292.61 L985.14,291.86 L985.95,291.08 L986.75,290.27 L987.56,289.45 L988.37,288.61 L989.17,287.75 L989.98,286.87 L990.79,285.98 L991.59,285.07 L992.40,284.15 L993.21,283.22 L994.01,282.27 L994.82,281.32 L995.63,280.35 L996.43,279.38 L997.24,278.40 L998.05,277.42 L998.85,276.43 L999.66,275.44 L1000.47,274.45 L1001.27,273.46 L1002.08,272.47 L1002.89,271.48 L1003.69,270.50 L1004.50,269.52 L1005.31,268.54 L1006.11,267.58 L1006.92,266.62 L1007.73,265.67 L1008.53,264.73 L1009.34,263.80 L1010.15,262.89 L1010.95,261.99 L1011.76,261.10 L1012.57,260.23 L1013.37,259.38 L1014.18,258.55 L1014.99,257.74 L1015.79,256.95 L1016.60,256.19 L1017.41,255.44 L1018.21,254.73 L1019.02,254.03 L1019.83,253.37 L1020.63,252.74 L1021.44,252.13 L1022.25,251.56 L1023.05,251.02 L1023.86,250.51 L1024.67,250.04 L1025.47,249.60 L1026.28,249.20 L1027.09,248.84 L1027.89,248.52 L1028.70,248.24 L1029.51,248.02 L1030.31,247.88 L1031.12,247.82 L1031.93,247.83 L1032.73,247.91 L1033.54,248.06 L1034.35,248.27 L1035.15,248.54 L1035.96,248.87 L1036.77,249.25 L1037.57,249.67 L1038.38,250.15 L1039.19,250.66 L1039.99,251.22 L1040.80,251.81 L1041.61,252.43 L1042.41,253.08 L1043.22,253.76 L1044.03,254.45 L1044.83,255.17 L1045.64,255.90 L1046.45,256.64 L1047.25,257.38 L1048.06,258.13 L1048.87,258.89 L1049.67,259.63 L1050.48,260.38 L1051.29,261.11 L1052.09,261.83 L1052.90,262.53 L1053.71,263.21 L1054.51,263.87 L1055.32,264.51 L1056.13,265.11 L1056.93,265.67 L1057.74,266.20 L1058.55,266.69 L1059.35,267.13 L1060.16,267.53 L1060.97,267.88 L1061.77,268.17 L1062.58,268.40 L1063.39,268.57 L1064.19,268.67 L1065.00,268.71 L1065.81,268.66 L1066.61,268.53 L1067.42,268.33 L1068.23,268.07 L1069.03,267.76 L1069.84,267.41 L1070.65,267.02 L1071.45,266.61 L1072.26,266.18 L1073.07,265.73 L1073.87,265.27 L1074.68,264.80 L1075.49,264.34 L1076.29,263.87 L1077.10,263.41 L1077.91,262.95 L1078.71,262.51 L1079.52,262.07 L1080.33,261.65 L1081.13,261.24 L1081.94,260.84 L1082.75,260.46 L1083.55,260.10 L1084.36,259.74 L1085.17,259.41 L1085.97,259.09 L1086.78,258.79 L1087.59,258.50 L1088.39,258.23 L1089.20,257.97 L1090.01,257.73 L1090.81,257.51 L1091.62,257.29 L1092.43,257.10 L1093.23,256.91 L1094.04,256.74 L1094.85,256.57 L1095.65,256.42 L1096.46,256.29 L1097.27,256.16 L1098.07,256.04 L1098.88,255.93 L1099.69,255.83 L1100.49,255.74 L1101.30,255.65 L1102.11,255.58 L1102.91,255.51 L1103.72,255.44 L1104.53,255.38 L1105.33,255.33 L1106.14,255.28 L1106.95,255.24 L1107.75,255.20 L1108.56,255.17 L1109.37,255.14 L1110.17,255.11 L1110.98,255.09 L1111.79,255.07 L1112.59,255.05 L1113.40,255.04 L1114.21,255.02 L1115.01,255.01 L1115.82,255.00 L1116.63,254.99 L1117.43,254.99 L1118.24,254.98 L1119.05,254.98 L1119.85,254.98 L1120.66,254.97 L1121.47,254.97 L1122.27,254.97 L1123.08,254.97 L1123.89,254.97 L1124.69,254.98 L1125.50,254.98 L1126.31,254.98 L1127.11,254.98 L1127.92,254.98 L1128.73,254.99 L1129.53,254.99 L1130.34,254.99 L1131.15,254.99 L1131.95,255.00 L1132.76,255.00 L1133.57,255.00 L1134.37,255.01 L1135.18,255.01 L1135.99,255.01 L1136.79,255.01 L1137.60,255.02 L1138.41,255.02 L1139.21,255.02 L1140.02,255.02 L1140.83,255.03 L1141.63,255.03 L1142.44,255.03 L1143.25,255.03 L1144.05,255.04 L1144.86,255.04 L1145.67,255.04 L1146.47,255.04 L1147.28,255.04 L1148.09,255.04 L1148.89,255.04 L1149.70,255.05 L1150.51,255.05 L1151.31,255.05 L1152.12,255.05 L1152.93,255.05 L1153.73,255.05 L1154.54,255.05 L1155.35,255.05 L1156.15,255.05 L1156.96,255.05 L1157.77,255.05 L1158.57,255.05 L1159.38,255.06 L1160.19,255.06 L1160.99,255.06 L1161.80,255.06 L1162.61,255.06 L1163.41,255.06 L1164.22,255.06 L1165.03,255.06 L1165.83,255.06 L1166.64,255.06 L1167.45,255.06 L1168.25,255.06 L1169.06,255.06 L1169.87,255.06 L1170.67,255.06 L1171.48,255.06 L1172.29,255.06 L1173.09,255.06 L1173.90,255.06 L1174.71,255.06 L1175.51,255.06 L1176.32,255.06 L1177.13,255.06 L1177.93,255.06 L1178.74,255.06 L1179.55,255.06 L1180.35,255.06 L1181.16,255.06 L1181.97,255.06 L1182.77,255.06 L1183.58,255.06 L1184.39,255.06 L1185.19,255.06 L1186.00,255.06 " fill="none" stroke="#2f6fec" stroke-width="1.8"/><text x="1182" y="250" font-size="9" fill="#2f6fec" text-anchor="end">position</text><path d="M944.00,281.54 L944.81,281.54 L945.61,281.54 L946.42,281.54 L947.23,281.54 L948.03,281.54 L948.84,281.54 L949.65,281.54 L950.45,281.54 L951.26,281.54 L952.07,281.54 L952.87,281.54 L953.68,281.54 L954.49,281.54 L955.29,281.54 L956.10,281.54 L956.91,281.54 L957.71,281.54 L958.52,281.54 L959.33,281.54 L960.13,281.54 L960.94,281.54 L961.75,281.54 L962.55,281.54 L963.36,281.54 L964.17,281.54 L964.97,281.54 L965.78,281.54 L966.59,281.54 L967.39,281.54 L968.20,281.54 L969.01,281.54 L969.81,281.54 L970.62,281.54 L971.43,281.54 L972.23,281.54 L973.04,281.54 L973.85,281.54 L974.65,281.54 L975.46,281.54 L976.27,281.54 L977.07,281.54 L977.88,281.54 L978.69,281.54 L979.49,281.54 L980.30,281.54 L981.11,279.48 L981.91,277.51 L982.72,275.62 L983.53,273.81 L984.33,272.08 L985.14,270.44 L985.95,268.88 L986.75,267.41 L987.56,266.01 L988.37,264.70 L989.17,263.48 L989.98,262.34 L990.79,261.28 L991.59,260.30 L992.40,259.41 L993.21,258.60 L994.01,257.87 L994.82,257.23 L995.63,256.67 L996.43,256.19 L997.24,255.80 L998.05,255.49 L998.85,255.26 L999.66,255.12 L1000.47,255.06 L1001.27,255.08 L1002.08,255.19 L1002.89,255.38 L1003.69,255.65 L1004.50,256.01 L1005.31,256.45 L1006.11,256.97 L1006.92,257.57 L1007.73,258.26 L1008.53,259.04 L1009.34,259.89 L1010.15,260.83 L1010.95,261.85 L1011.76,262.96 L1012.57,264.15 L1013.37,265.42 L1014.18,266.77 L1014.99,268.21 L1015.79,269.73 L1016.60,271.34 L1017.41,273.03 L1018.21,274.80 L1019.02,276.65 L1019.83,278.59 L1020.63,280.61 L1021.44,282.71 L1022.25,284.90 L1023.05,287.17 L1023.86,289.53 L1024.67,291.96 L1025.47,294.49 L1026.28,297.09 L1027.09,299.78 L1027.89,302.55 L1028.70,305.40 L1029.51,311.05 L1030.31,316.45 L1031.12,321.62 L1031.93,326.55 L1032.73,331.25 L1033.54,335.70 L1034.35,339.92 L1035.15,343.89 L1035.96,347.63 L1036.77,351.13 L1037.57,354.39 L1038.38,357.41 L1039.19,360.19 L1039.99,362.74 L1040.80,365.05 L1041.61,367.11 L1042.41,368.94 L1043.22,370.53 L1044.03,371.89 L1044.83,373.00 L1045.64,373.87 L1046.45,374.51 L1047.25,374.91 L1048.06,375.07 L1048.87,374.99 L1049.67,374.67 L1050.48,374.11 L1051.29,373.32 L1052.09,372.28 L1052.90,371.01 L1053.71,369.50 L1054.51,367.75 L1055.32,365.76 L1056.13,363.54 L1056.93,361.07 L1057.74,358.37 L1058.55,355.42 L1059.35,352.24 L1060.16,348.82 L1060.97,345.16 L1061.77,341.27 L1062.58,337.13 L1063.39,332.76 L1064.19,328.15 L1065.00,323.29 L1065.81,317.16 L1066.61,311.87 L1067.42,307.37 L1068.23,303.56 L1069.03,300.39 L1069.84,297.79 L1070.65,295.70 L1071.45,294.07 L1072.26,292.85 L1073.07,291.99 L1073.87,291.44 L1074.68,291.18 L1075.49,291.16 L1076.29,291.36 L1077.10,291.74 L1077.91,292.27 L1078.71,292.94 L1079.52,293.71 L1080.33,294.58 L1081.13,295.52 L1081.94,296.51 L1082.75,297.55 L1083.55,298.62 L1084.36,299.71 L1085.17,300.81 L1085.97,301.91 L1086.78,303.00 L1087.59,304.08 L1088.39,305.15 L1089.20,306.19 L1090.01,307.20 L1090.81,308.19 L1091.62,309.14 L1092.43,310.06 L1093.23,310.94 L1094.04,311.79 L1094.85,312.60 L1095.65,313.37 L1096.46,314.10 L1097.27,314.80 L1098.07,315.46 L1098.88,316.09 L1099.69,316.67 L1100.49,317.23 L1101.30,317.75 L1102.11,318.23 L1102.91,318.69 L1103.72,319.11 L1104.53,319.51 L1105.33,319.88 L1106.14,320.22 L1106.95,320.54 L1107.75,320.83 L1108.56,321.10 L1109.37,321.35 L1110.17,321.57 L1110.98,321.78 L1111.79,321.97 L1112.59,322.15 L1113.40,322.31 L1114.21,322.45 L1115.01,322.58 L1115.82,322.70 L1116.63,322.81 L1117.43,322.90 L1118.24,322.99 L1119.05,323.06 L1119.85,323.13 L1120.66,323.19 L1121.47,323.24 L1122.27,323.29 L1123.08,323.33 L1123.89,323.36 L1124.69,323.39 L1125.50,323.41 L1126.31,323.43 L1127.11,323.45 L1127.92,323.47 L1128.73,323.48 L1129.53,323.48 L1130.34,323.49 L1131.15,323.49 L1131.95,323.50 L1132.76,323.50 L1133.57,323.50 L1134.37,323.49 L1135.18,323.49 L1135.99,323.49 L1136.79,323.48 L1137.60,323.48 L1138.41,323.47 L1139.21,323.46 L1140.02,323.46 L1140.83,323.45 L1141.63,323.44 L1142.44,323.44 L1143.25,323.43 L1144.05,323.42 L1144.86,323.42 L1145.67,323.41 L1146.47,323.40 L1147.28,323.40 L1148.09,323.39 L1148.89,323.38 L1149.70,323.38 L1150.51,323.37 L1151.31,323.37 L1152.12,323.36 L1152.93,323.36 L1153.73,323.35 L1154.54,323.35 L1155.35,323.34 L1156.15,323.34 L1156.96,323.34 L1157.77,323.33 L1158.57,323.33 L1159.38,323.33 L1160.19,323.32 L1160.99,323.32 L1161.80,323.32 L1162.61,323.32 L1163.41,323.31 L1164.22,323.31 L1165.03,323.31 L1165.83,323.31 L1166.64,323.31 L1167.45,323.31 L1168.25,323.30 L1169.06,323.29 L1169.87,323.29 L1170.67,323.29 L1171.48,323.29 L1172.29,323.29 L1173.09,323.29 L1173.90,323.29 L1174.71,323.29 L1175.51,323.29 L1176.32,323.29 L1177.13,323.29 L1177.93,323.29 L1178.74,323.29 L1179.55,323.29 L1180.35,323.29 L1181.16,323.29 L1181.97,323.29 L1182.77,323.29 L1183.58,323.29 L1184.39,323.29 L1185.19,323.29 L1186.00,323.29 " fill="none" stroke="#e8833a" stroke-width="1.8" stroke-dasharray="4 3"/><text x="1182" y="262" font-size="9" fill="#e8833a" text-anchor="end">velocity</text></svg> \ No newline at end of file diff --git a/app/vendor/rune/demo/motion/presence-and-paths.png b/app/vendor/rune/demo/motion/presence-and-paths.png new file mode 100644 index 0000000..69dd716 Binary files /dev/null and b/app/vendor/rune/demo/motion/presence-and-paths.png differ diff --git a/app/vendor/rune/demo/motion/presence-and-paths.svg b/app/vendor/rune/demo/motion/presence-and-paths.svg new file mode 100644 index 0000000..c954787 --- /dev/null +++ b/app/vendor/rune/demo/motion/presence-and-paths.svg @@ -0,0 +1 @@ +<svg xmlns="http://www.w3.org/2000/svg" width="840" height="840" viewBox="0 0 840 840" font-family="-apple-system, Helvetica, sans-serif"><rect width="100%" height="100%" fill="white"/><text x="16" y="26" font-size="16" font-weight="600" fill="#222">Presence and travel</text><rect x="44" y="68" width="362" height="276" fill="#fafbfc" stroke="#e3e6ea"/><text x="44" y="59" font-size="12" font-weight="600" fill="#333">blurReplace: enter, exit, revive mid-exit, exit</text><line x1="44" x2="406" y1="321.92" y2="321.92" stroke="#d5d9de" stroke-dasharray="3 3"/><text x="40" y="324.92" font-size="9" fill="#888" text-anchor="end">0</text><line x1="44" x2="406" y1="101.119995" y2="101.119995" stroke="#d5d9de" stroke-dasharray="3 3"/><text x="40" y="104.119995" font-size="9" fill="#888" text-anchor="end">1</text><text x="406" y="358" font-size="9" fill="#888" text-anchor="end">2.00 s</text><line x1="170.7" x2="170.7" y1="68" y2="344" stroke="#d64545" stroke-width="1" stroke-dasharray="2 3"/><line x1="209.91667" x2="209.91667" y1="68" y2="344" stroke="#d64545" stroke-width="1" stroke-dasharray="2 3"/><line x1="345.66666" x2="345.66666" y1="68" y2="344" stroke="#d64545" stroke-width="1" stroke-dasharray="2 3"/><path d="M44.00,321.92 L44.75,321.13 L45.51,318.92 L46.26,315.55 L47.02,311.22 L47.77,306.12 L48.53,300.40 L49.28,294.21 L50.03,287.66 L50.79,280.86 L51.54,273.89 L52.30,266.83 L53.05,259.74 L53.80,252.68 L54.56,245.70 L55.31,238.82 L56.07,232.08 L56.82,225.51 L57.58,219.12 L58.33,212.93 L59.08,206.95 L59.84,201.19 L60.59,195.65 L61.35,190.34 L62.10,185.26 L62.85,180.40 L63.61,175.77 L64.36,171.36 L65.12,167.16 L65.87,163.18 L66.62,159.40 L67.38,155.81 L68.13,152.42 L68.89,149.22 L69.64,146.19 L70.40,143.33 L71.15,140.64 L71.90,138.10 L72.66,135.71 L73.41,133.46 L74.17,131.34 L74.92,129.36 L75.68,127.49 L76.43,125.74 L77.18,124.09 L77.94,122.55 L78.69,121.11 L79.45,119.76 L80.20,118.49 L80.95,117.31 L81.71,116.20 L82.46,115.17 L83.22,114.20 L83.97,113.29 L84.72,112.45 L85.48,111.66 L86.23,110.93 L86.99,110.24 L87.74,109.60 L88.50,109.00 L89.25,108.45 L90.00,107.93 L90.76,107.45 L91.51,107.00 L92.27,106.58 L93.02,106.19 L93.78,105.83 L94.53,105.49 L95.28,105.17 L96.04,104.88 L96.79,104.61 L97.55,104.36 L98.30,104.12 L99.05,103.91 L99.81,103.70 L100.56,103.51 L101.32,103.34 L102.07,103.18 L102.82,103.03 L103.58,102.89 L104.33,102.76 L105.09,102.64 L105.84,102.53 L106.60,102.42 L107.35,102.33 L108.10,102.24 L108.86,102.15 L109.61,102.08 L110.37,102.01 L111.12,101.94 L111.88,101.88 L112.63,101.82 L113.38,101.77 L114.14,101.72 L114.89,101.68 L115.65,101.63 L116.40,101.60 L117.15,101.56 L117.91,101.53 L118.66,101.50 L119.42,101.47 L120.17,101.44 L120.93,101.42 L121.68,101.40 L122.43,101.37 L123.19,101.36 L123.94,101.34 L124.70,101.32 L125.45,101.31 L126.20,101.29 L126.96,101.28 L127.71,101.27 L128.47,101.26 L129.22,101.25 L129.98,101.24 L130.73,101.23 L131.48,101.22 L132.24,101.21 L132.99,101.20 L133.75,101.20 L134.50,101.19 L135.25,101.19 L136.01,101.18 L136.76,101.18 L137.52,101.17 L138.27,101.17 L139.02,101.16 L139.78,101.16 L140.53,101.16 L141.29,101.15 L142.04,101.15 L142.80,101.15 L143.55,101.15 L144.30,101.15 L145.06,101.14 L145.81,101.14 L146.57,101.14 L147.32,101.14 L148.07,101.14 L148.83,101.14 L149.58,101.13 L150.34,101.13 L151.09,101.13 L151.85,101.13 L152.60,101.13 L153.35,101.13 L154.11,101.13 L154.86,101.13 L155.62,101.13 L156.37,101.13 L157.12,101.13 L157.88,101.13 L158.63,101.13 L159.39,101.13 L160.14,101.12 L160.90,101.12 L161.65,101.12 L162.40,101.12 L163.16,101.12 L163.91,101.12 L164.67,101.12 L165.42,101.12 L166.18,101.12 L166.93,101.12 L167.68,101.12 L168.44,101.12 L169.19,101.12 L169.95,101.12 L170.70,101.12 L171.45,102.34 L172.21,105.67 L172.96,110.66 L173.72,116.92 L174.47,124.15 L175.23,132.07 L175.98,140.46 L176.73,149.15 L177.49,157.98 L178.24,166.83 L179.00,175.61 L179.75,184.22 L180.50,192.62 L181.26,200.75 L182.01,208.58 L182.77,216.09 L183.52,223.26 L184.27,230.07 L185.03,236.53 L185.78,242.64 L186.54,248.40 L187.29,253.81 L188.05,258.89 L188.80,263.64 L189.55,268.09 L190.31,272.24 L191.06,276.11 L191.82,279.71 L192.57,283.05 L193.32,286.16 L194.08,289.03 L194.83,291.70 L195.59,294.16 L196.34,296.44 L197.10,298.54 L197.85,300.49 L198.60,302.28 L199.36,303.92 L200.11,305.44 L200.87,306.84 L201.62,308.12 L202.38,309.30 L203.13,310.38 L203.88,311.38 L204.64,312.29 L205.39,313.13 L206.15,313.89 L206.90,314.59 L207.65,315.24 L208.41,315.82 L209.16,316.36 L209.92,316.85 L210.67,316.51 L211.43,314.71 L212.18,311.72 L212.93,307.73 L213.69,302.94 L214.44,297.50 L215.20,291.57 L215.95,285.25 L216.70,278.66 L217.46,271.89 L218.21,265.01 L218.97,258.08 L219.72,251.17 L220.48,244.32 L221.23,237.56 L221.98,230.94 L222.74,224.47 L223.49,218.17 L224.25,212.06 L225.00,206.16 L225.75,200.47 L226.51,195.00 L227.26,189.75 L228.02,184.72 L228.77,179.91 L229.52,175.32 L230.28,170.95 L231.03,166.79 L231.79,162.84 L232.54,159.09 L233.30,155.53 L234.05,152.17 L234.80,148.99 L235.56,145.98 L236.31,143.14 L237.07,140.46 L237.82,137.94 L238.58,135.56 L239.33,133.33 L240.08,131.22 L240.84,129.25 L241.59,127.39 L242.35,125.65 L243.10,124.01 L243.85,122.48 L244.61,121.04 L245.36,119.70 L246.12,118.44 L246.87,117.26 L247.62,116.16 L248.38,115.12 L249.13,114.16 L249.89,113.26 L250.64,112.42 L251.40,111.63 L252.15,110.90 L252.90,110.22 L253.66,109.58 L254.41,108.98 L255.17,108.43 L255.92,107.91 L256.67,107.43 L257.43,106.98 L258.18,106.57 L258.94,106.18 L259.69,105.81 L260.45,105.48 L261.20,105.17 L261.95,104.87 L262.71,104.60 L263.46,104.35 L264.22,104.12 L264.97,103.90 L265.73,103.70 L266.48,103.51 L267.23,103.34 L267.99,103.17 L268.74,103.02 L269.50,102.88 L270.25,102.75 L271.00,102.63 L271.76,102.52 L272.51,102.42 L273.27,102.32 L274.02,102.23 L274.77,102.15 L275.53,102.08 L276.28,102.00 L277.04,101.94 L277.79,101.88 L278.55,101.82 L279.30,101.77 L280.05,101.72 L280.81,101.68 L281.56,101.63 L282.32,101.60 L283.07,101.56 L283.83,101.53 L284.58,101.50 L285.33,101.47 L286.09,101.44 L286.84,101.42 L287.60,101.40 L288.35,101.37 L289.10,101.36 L289.86,101.34 L290.61,101.32 L291.37,101.31 L292.12,101.29 L292.88,101.28 L293.63,101.27 L294.38,101.26 L295.14,101.24 L295.89,101.24 L296.65,101.23 L297.40,101.22 L298.15,101.21 L298.91,101.20 L299.66,101.20 L300.42,101.19 L301.17,101.19 L301.92,101.18 L302.68,101.18 L303.43,101.17 L304.19,101.17 L304.94,101.16 L305.70,101.16 L306.45,101.16 L307.20,101.15 L307.96,101.15 L308.71,101.15 L309.47,101.15 L310.22,101.15 L310.98,101.14 L311.73,101.14 L312.48,101.14 L313.24,101.14 L313.99,101.14 L314.75,101.14 L315.50,101.13 L316.25,101.13 L317.01,101.13 L317.76,101.13 L318.52,101.13 L319.27,101.13 L320.02,101.13 L320.78,101.13 L321.53,101.13 L322.29,101.13 L323.04,101.13 L323.80,101.13 L324.55,101.13 L325.30,101.13 L326.06,101.12 L326.81,101.12 L327.57,101.12 L328.32,101.12 L329.08,101.12 L329.83,101.12 L330.58,101.12 L331.34,101.12 L332.09,101.12 L332.85,101.12 L333.60,101.12 L334.35,101.12 L335.11,101.12 L335.86,101.12 L336.62,101.12 L337.37,101.12 L338.12,101.12 L338.88,101.12 L339.63,101.12 L340.39,101.12 L341.14,101.12 L341.90,101.12 L342.65,101.12 L343.40,101.12 L344.16,101.12 L344.91,101.12 L345.67,101.12 L346.42,102.34 L347.17,105.67 L347.93,110.65 L348.68,116.92 L349.44,124.14 L350.19,132.07 L350.95,140.46 L351.70,149.15 L352.45,157.98 L353.21,166.83 L353.96,175.61 L354.72,184.22 L355.47,192.62 L356.23,200.75 L356.98,208.58 L357.73,216.09 L358.49,223.26 L359.24,230.07 L360.00,236.53 L360.75,242.64 L361.50,248.39 L362.26,253.81 L363.01,258.89 L363.77,263.64 L364.52,268.09 L365.27,272.24 L366.03,276.11 L366.78,279.71 L367.54,283.05 L368.29,286.16 L369.05,289.03 L369.80,291.70 L370.55,294.16 L371.31,296.44 L372.06,298.54 L372.82,300.49 L373.57,302.28 L374.33,303.92 L375.08,305.44 L375.83,306.84 L376.59,308.12 L377.34,309.30 L378.10,310.38 L378.85,311.38 L379.60,312.29 L380.36,313.13 L381.11,313.89 L381.87,314.59 L382.62,315.24 L383.38,315.82 L384.13,316.36 L384.88,316.85 L385.64,317.30 L386.39,317.71 L387.15,318.09 L387.90,318.43 L388.65,318.74 L389.41,319.03 L390.16,319.29 L390.92,319.53 L391.67,319.74 L392.42,319.94 L393.18,320.12 L393.93,320.28 L394.69,320.43 L395.44,320.57 L396.20,320.69 L396.95,320.80 L397.70,320.91 L398.46,321.00 L399.21,321.08 L399.97,321.16 L400.72,321.23 L401.48,321.29 L402.23,321.35 L402.98,321.41 L403.74,321.45 L404.49,321.50 L405.25,321.54 L406.00,321.57 " fill="none" stroke="#2f6fec" stroke-width="1.8"/><text x="402" y="80" font-size="9" fill="#2f6fec" text-anchor="end">opacity</text><path d="M44.00,101.12 L44.75,101.91 L45.51,104.12 L46.26,107.49 L47.02,111.82 L47.77,116.92 L48.53,122.64 L49.28,128.83 L50.03,135.38 L50.79,142.18 L51.54,149.15 L52.30,156.21 L53.05,163.30 L53.80,170.36 L54.56,177.34 L55.31,184.22 L56.07,190.96 L56.82,197.53 L57.58,203.92 L58.33,210.11 L59.08,216.09 L59.84,221.85 L60.59,227.39 L61.35,232.70 L62.10,237.78 L62.85,242.64 L63.61,247.27 L64.36,251.68 L65.12,255.88 L65.87,259.86 L66.62,263.64 L67.38,267.23 L68.13,270.62 L68.89,273.82 L69.64,276.85 L70.40,279.71 L71.15,282.40 L71.90,284.94 L72.66,287.33 L73.41,289.58 L74.17,291.70 L74.92,293.68 L75.68,295.55 L76.43,297.30 L77.18,298.95 L77.94,300.49 L78.69,301.93 L79.45,303.28 L80.20,304.55 L80.95,305.73 L81.71,306.84 L82.46,307.87 L83.22,308.84 L83.97,309.75 L84.72,310.59 L85.48,311.38 L86.23,312.11 L86.99,312.80 L87.74,313.44 L88.50,314.04 L89.25,314.59 L90.00,315.11 L90.76,315.59 L91.51,316.04 L92.27,316.46 L93.02,316.85 L93.78,317.21 L94.53,317.55 L95.28,317.87 L96.04,318.16 L96.79,318.43 L97.55,318.68 L98.30,318.92 L99.05,319.13 L99.81,319.34 L100.56,319.53 L101.32,319.70 L102.07,319.86 L102.82,320.01 L103.58,320.15 L104.33,320.28 L105.09,320.40 L105.84,320.51 L106.60,320.62 L107.35,320.71 L108.10,320.80 L108.86,320.89 L109.61,320.96 L110.37,321.03 L111.12,321.92 L111.88,321.92 L112.63,321.92 L113.38,321.92 L114.14,321.92 L114.89,321.92 L115.65,321.92 L116.40,321.92 L117.15,321.92 L117.91,321.92 L118.66,321.92 L119.42,321.92 L120.17,321.92 L120.93,321.92 L121.68,321.92 L122.43,321.92 L123.19,321.92 L123.94,321.92 L124.70,321.92 L125.45,321.92 L126.20,321.92 L126.96,321.92 L127.71,321.92 L128.47,321.92 L129.22,321.92 L129.98,321.92 L130.73,321.92 L131.48,321.92 L132.24,321.92 L132.99,321.92 L133.75,321.92 L134.50,321.92 L135.25,321.92 L136.01,321.92 L136.76,321.92 L137.52,321.92 L138.27,321.92 L139.02,321.92 L139.78,321.92 L140.53,321.92 L141.29,321.92 L142.04,321.92 L142.80,321.92 L143.55,321.92 L144.30,321.92 L145.06,321.92 L145.81,321.92 L146.57,321.92 L147.32,321.92 L148.07,321.92 L148.83,321.92 L149.58,321.92 L150.34,321.92 L151.09,321.92 L151.85,321.92 L152.60,321.92 L153.35,321.92 L154.11,321.92 L154.86,321.92 L155.62,321.92 L156.37,321.92 L157.12,321.92 L157.88,321.92 L158.63,321.92 L159.39,321.92 L160.14,321.92 L160.90,321.92 L161.65,321.92 L162.40,321.92 L163.16,321.92 L163.91,321.92 L164.67,321.92 L165.42,321.92 L166.18,321.92 L166.93,321.92 L167.68,321.92 L168.44,321.92 L169.19,321.92 L169.95,321.92 L170.70,321.92 L171.45,320.70 L172.21,317.37 L172.96,312.38 L173.72,306.12 L174.47,298.89 L175.23,290.97 L175.98,282.58 L176.73,273.89 L177.49,265.06 L178.24,256.21 L179.00,247.43 L179.75,238.82 L180.50,230.42 L181.26,222.29 L182.01,214.46 L182.77,206.95 L183.52,199.78 L184.27,192.97 L185.03,186.51 L185.78,180.40 L186.54,174.64 L187.29,169.23 L188.05,164.15 L188.80,159.40 L189.55,154.95 L190.31,150.80 L191.06,146.93 L191.82,143.33 L192.57,139.99 L193.32,136.88 L194.08,134.01 L194.83,131.34 L195.59,128.88 L196.34,126.60 L197.10,124.50 L197.85,122.55 L198.60,120.76 L199.36,119.12 L200.11,117.60 L200.87,116.20 L201.62,114.92 L202.38,113.74 L203.13,112.66 L203.88,111.66 L204.64,110.75 L205.39,109.91 L206.15,109.15 L206.90,108.45 L207.65,107.80 L208.41,107.22 L209.16,106.68 L209.92,106.19 L210.67,106.53 L211.43,108.33 L212.18,111.32 L212.93,115.31 L213.69,120.10 L214.44,125.54 L215.20,131.47 L215.95,137.79 L216.70,144.38 L217.46,151.15 L218.21,158.03 L218.97,164.96 L219.72,171.87 L220.48,178.72 L221.23,185.48 L221.98,192.10 L222.74,198.57 L223.49,204.87 L224.25,210.98 L225.00,216.88 L225.75,222.57 L226.51,228.04 L227.26,233.29 L228.02,238.32 L228.77,243.13 L229.52,247.72 L230.28,252.09 L231.03,256.25 L231.79,260.20 L232.54,263.95 L233.30,267.51 L234.05,270.87 L234.80,274.05 L235.56,277.06 L236.31,279.90 L237.07,282.58 L237.82,285.10 L238.58,287.48 L239.33,289.71 L240.08,291.82 L240.84,293.79 L241.59,295.65 L242.35,297.39 L243.10,299.03 L243.85,300.56 L244.61,302.00 L245.36,303.34 L246.12,304.60 L246.87,305.78 L247.62,306.88 L248.38,307.92 L249.13,308.88 L249.89,309.78 L250.64,310.62 L251.40,311.41 L252.15,312.14 L252.90,312.82 L253.66,313.46 L254.41,314.06 L255.17,314.61 L255.92,315.13 L256.67,315.61 L257.43,316.06 L258.18,316.47 L258.94,316.86 L259.69,317.23 L260.45,317.56 L261.20,317.87 L261.95,318.17 L262.71,318.44 L263.46,318.69 L264.22,318.92 L264.97,319.14 L265.73,319.34 L266.48,319.53 L267.23,319.70 L267.99,319.87 L268.74,320.02 L269.50,320.16 L270.25,320.29 L271.00,320.41 L271.76,320.52 L272.51,320.62 L273.27,320.72 L274.02,320.81 L274.77,320.89 L275.53,320.96 L276.28,321.04 L277.04,321.92 L277.79,321.92 L278.55,321.92 L279.30,321.92 L280.05,321.92 L280.81,321.92 L281.56,321.92 L282.32,321.92 L283.07,321.92 L283.83,321.92 L284.58,321.92 L285.33,321.92 L286.09,321.92 L286.84,321.92 L287.60,321.92 L288.35,321.92 L289.10,321.92 L289.86,321.92 L290.61,321.92 L291.37,321.92 L292.12,321.92 L292.88,321.92 L293.63,321.92 L294.38,321.92 L295.14,321.92 L295.89,321.92 L296.65,321.92 L297.40,321.92 L298.15,321.92 L298.91,321.92 L299.66,321.92 L300.42,321.92 L301.17,321.92 L301.92,321.92 L302.68,321.92 L303.43,321.92 L304.19,321.92 L304.94,321.92 L305.70,321.92 L306.45,321.92 L307.20,321.92 L307.96,321.92 L308.71,321.92 L309.47,321.92 L310.22,321.92 L310.98,321.92 L311.73,321.92 L312.48,321.92 L313.24,321.92 L313.99,321.92 L314.75,321.92 L315.50,321.92 L316.25,321.92 L317.01,321.92 L317.76,321.92 L318.52,321.92 L319.27,321.92 L320.02,321.92 L320.78,321.92 L321.53,321.92 L322.29,321.92 L323.04,321.92 L323.80,321.92 L324.55,321.92 L325.30,321.92 L326.06,321.92 L326.81,321.92 L327.57,321.92 L328.32,321.92 L329.08,321.92 L329.83,321.92 L330.58,321.92 L331.34,321.92 L332.09,321.92 L332.85,321.92 L333.60,321.92 L334.35,321.92 L335.11,321.92 L335.86,321.92 L336.62,321.92 L337.37,321.92 L338.12,321.92 L338.88,321.92 L339.63,321.92 L340.39,321.92 L341.14,321.92 L341.90,321.92 L342.65,321.92 L343.40,321.92 L344.16,321.92 L344.91,321.92 L345.67,321.92 L346.42,320.70 L347.17,317.37 L347.93,312.39 L348.68,306.12 L349.44,298.90 L350.19,290.97 L350.95,282.58 L351.70,273.89 L352.45,265.06 L353.21,256.21 L353.96,247.43 L354.72,238.82 L355.47,230.42 L356.23,222.29 L356.98,214.46 L357.73,206.95 L358.49,199.78 L359.24,192.97 L360.00,186.51 L360.75,180.40 L361.50,174.65 L362.26,169.23 L363.01,164.15 L363.77,159.40 L364.52,154.95 L365.27,150.80 L366.03,146.93 L366.78,143.33 L367.54,139.99 L368.29,136.88 L369.05,134.01 L369.80,131.34 L370.55,128.88 L371.31,126.60 L372.06,124.50 L372.82,122.55 L373.57,120.76 L374.33,119.12 L375.08,117.60 L375.83,116.20 L376.59,114.92 L377.34,113.74 L378.10,112.66 L378.85,111.66 L379.60,110.75 L380.36,109.91 L381.11,109.15 L381.87,108.45 L382.62,107.80 L383.38,107.22 L384.13,106.68 L384.88,106.19 L385.64,105.74 L386.39,105.33 L387.15,104.95 L387.90,104.61 L388.65,104.30 L389.41,104.01 L390.16,103.75 L390.92,103.51 L391.67,103.30 L392.42,103.10 L393.18,102.92 L393.93,102.76 L394.69,102.61 L395.44,102.47 L396.20,102.35 L396.95,102.24 L397.70,102.13 L398.46,102.04 L399.21,101.96 L399.97,101.88 L400.72,101.81 L401.48,101.75 L402.23,101.69 L402.98,101.63 L403.74,101.59 L404.49,101.54 L405.25,101.50 L406.00,101.47 " fill="none" stroke="#8a5cd6" stroke-width="1.8"/><text x="402" y="92" font-size="9" fill="#8a5cd6" text-anchor="end">blur / 4 px</text><path d="M44.00,321.92 L44.75,321.13 L45.51,318.92 L46.26,315.55 L47.02,311.22 L47.77,306.12 L48.53,300.40 L49.28,294.21 L50.03,287.66 L50.79,280.86 L51.54,273.89 L52.30,266.83 L53.05,259.74 L53.80,252.68 L54.56,245.70 L55.31,238.82 L56.07,232.08 L56.82,225.51 L57.58,219.12 L58.33,212.93 L59.08,206.95 L59.84,201.19 L60.59,195.65 L61.35,190.34 L62.10,185.26 L62.85,180.40 L63.61,175.77 L64.36,171.36 L65.12,167.16 L65.87,163.18 L66.62,159.40 L67.38,155.81 L68.13,152.42 L68.89,149.22 L69.64,146.19 L70.40,143.33 L71.15,140.64 L71.90,138.10 L72.66,135.71 L73.41,133.46 L74.17,131.34 L74.92,129.36 L75.68,127.49 L76.43,125.74 L77.18,124.09 L77.94,122.55 L78.69,121.11 L79.45,119.76 L80.20,118.49 L80.95,117.31 L81.71,116.20 L82.46,115.17 L83.22,114.20 L83.97,113.29 L84.72,112.45 L85.48,111.66 L86.23,110.93 L86.99,110.24 L87.74,109.60 L88.50,109.00 L89.25,108.45 L90.00,107.93 L90.76,107.45 L91.51,107.00 L92.27,106.58 L93.02,106.19 L93.78,105.82 L94.53,105.49 L95.28,105.17 L96.04,104.88 L96.79,104.61 L97.55,104.36 L98.30,104.12 L99.05,103.90 L99.81,103.70 L100.56,103.51 L101.32,103.34 L102.07,103.18 L102.82,103.03 L103.58,102.89 L104.33,102.76 L105.09,102.64 L105.84,102.53 L106.60,102.42 L107.35,102.33 L108.10,102.24 L108.86,102.15 L109.61,102.08 L110.37,102.01 L111.12,101.94 L111.88,101.88 L112.63,101.82 L113.38,101.77 L114.14,101.72 L114.89,101.68 L115.65,101.63 L116.40,101.60 L117.15,101.56 L117.91,101.53 L118.66,101.50 L119.42,101.47 L120.17,101.44 L120.93,101.42 L121.68,101.40 L122.43,101.37 L123.19,101.36 L123.94,101.34 L124.70,101.32 L125.45,101.31 L126.20,101.29 L126.96,101.28 L127.71,101.27 L128.47,101.26 L129.22,101.24 L129.98,101.24 L130.73,101.23 L131.48,101.22 L132.24,101.21 L132.99,101.20 L133.75,101.20 L134.50,101.19 L135.25,101.19 L136.01,101.18 L136.76,101.18 L137.52,101.17 L138.27,101.17 L139.02,101.16 L139.78,101.16 L140.53,101.16 L141.29,101.15 L142.04,101.15 L142.80,101.15 L143.55,101.15 L144.30,101.15 L145.06,101.14 L145.81,101.14 L146.57,101.14 L147.32,101.14 L148.07,101.14 L148.83,101.14 L149.58,101.13 L150.34,101.13 L151.09,101.13 L151.85,101.13 L152.60,101.13 L153.35,101.13 L154.11,101.13 L154.86,101.13 L155.62,101.13 L156.37,101.13 L157.12,101.13 L157.88,101.13 L158.63,101.13 L159.39,101.12 L160.14,101.12 L160.90,101.12 L161.65,101.12 L162.40,101.12 L163.16,101.12 L163.91,101.12 L164.67,101.12 L165.42,101.12 L166.18,101.12 L166.93,101.12 L167.68,101.12 L168.44,101.12 L169.19,101.12 L169.95,101.12 L170.70,101.12 L171.45,102.34 L172.21,105.67 L172.96,110.66 L173.72,116.92 L174.47,124.14 L175.23,132.07 L175.98,140.46 L176.73,149.15 L177.49,157.98 L178.24,166.83 L179.00,175.61 L179.75,184.22 L180.50,192.62 L181.26,200.75 L182.01,208.58 L182.77,216.09 L183.52,223.26 L184.27,230.07 L185.03,236.53 L185.78,242.64 L186.54,248.40 L187.29,253.81 L188.05,258.89 L188.80,263.64 L189.55,268.09 L190.31,272.24 L191.06,276.11 L191.82,279.71 L192.57,283.05 L193.32,286.16 L194.08,289.03 L194.83,291.70 L195.59,294.16 L196.34,296.44 L197.10,298.54 L197.85,300.49 L198.60,302.28 L199.36,303.92 L200.11,305.44 L200.87,306.84 L201.62,308.12 L202.38,309.30 L203.13,310.38 L203.88,311.38 L204.64,312.29 L205.39,313.13 L206.15,313.89 L206.90,314.59 L207.65,315.24 L208.41,315.82 L209.16,316.36 L209.92,316.85 L210.67,316.51 L211.43,314.71 L212.18,311.72 L212.93,307.73 L213.69,302.94 L214.44,297.50 L215.20,291.57 L215.95,285.25 L216.70,278.66 L217.46,271.89 L218.21,265.01 L218.97,258.08 L219.72,251.17 L220.48,244.32 L221.23,237.56 L221.98,230.94 L222.74,224.47 L223.49,218.17 L224.25,212.06 L225.00,206.16 L225.75,200.47 L226.51,195.00 L227.26,189.75 L228.02,184.72 L228.77,179.91 L229.52,175.32 L230.28,170.95 L231.03,166.79 L231.79,162.84 L232.54,159.09 L233.30,155.53 L234.05,152.17 L234.80,148.99 L235.56,145.98 L236.31,143.14 L237.07,140.46 L237.82,137.94 L238.58,135.56 L239.33,133.33 L240.08,131.22 L240.84,129.25 L241.59,127.39 L242.35,125.65 L243.10,124.01 L243.85,122.48 L244.61,121.04 L245.36,119.70 L246.12,118.44 L246.87,117.26 L247.62,116.16 L248.38,115.12 L249.13,114.16 L249.89,113.26 L250.64,112.42 L251.40,111.63 L252.15,110.90 L252.90,110.22 L253.66,109.58 L254.41,108.98 L255.17,108.43 L255.92,107.91 L256.67,107.43 L257.43,106.98 L258.18,106.57 L258.94,106.18 L259.69,105.81 L260.45,105.48 L261.20,105.17 L261.95,104.87 L262.71,104.60 L263.46,104.35 L264.22,104.12 L264.97,103.90 L265.73,103.70 L266.48,103.51 L267.23,103.34 L267.99,103.17 L268.74,103.02 L269.50,102.88 L270.25,102.75 L271.00,102.63 L271.76,102.52 L272.51,102.42 L273.27,102.32 L274.02,102.23 L274.77,102.15 L275.53,102.08 L276.28,102.00 L277.04,101.94 L277.79,101.88 L278.55,101.82 L279.30,101.77 L280.05,101.72 L280.81,101.68 L281.56,101.63 L282.32,101.60 L283.07,101.56 L283.83,101.53 L284.58,101.50 L285.33,101.47 L286.09,101.44 L286.84,101.42 L287.60,101.39 L288.35,101.37 L289.10,101.35 L289.86,101.34 L290.61,101.32 L291.37,101.31 L292.12,101.29 L292.88,101.28 L293.63,101.27 L294.38,101.26 L295.14,101.24 L295.89,101.24 L296.65,101.23 L297.40,101.22 L298.15,101.21 L298.91,101.20 L299.66,101.20 L300.42,101.19 L301.17,101.19 L301.92,101.18 L302.68,101.18 L303.43,101.17 L304.19,101.17 L304.94,101.16 L305.70,101.16 L306.45,101.16 L307.20,101.15 L307.96,101.15 L308.71,101.15 L309.47,101.15 L310.22,101.15 L310.98,101.14 L311.73,101.14 L312.48,101.14 L313.24,101.14 L313.99,101.14 L314.75,101.14 L315.50,101.13 L316.25,101.13 L317.01,101.13 L317.76,101.13 L318.52,101.13 L319.27,101.13 L320.02,101.13 L320.78,101.13 L321.53,101.13 L322.29,101.13 L323.04,101.13 L323.80,101.13 L324.55,101.13 L325.30,101.12 L326.06,101.12 L326.81,101.12 L327.57,101.12 L328.32,101.12 L329.08,101.12 L329.83,101.12 L330.58,101.12 L331.34,101.12 L332.09,101.12 L332.85,101.12 L333.60,101.12 L334.35,101.12 L335.11,101.12 L335.86,101.12 L336.62,101.12 L337.37,101.12 L338.12,101.12 L338.88,101.12 L339.63,101.12 L340.39,101.12 L341.14,101.12 L341.90,101.12 L342.65,101.12 L343.40,101.12 L344.16,101.12 L344.91,101.12 L345.67,101.12 L346.42,102.34 L347.17,105.67 L347.93,110.65 L348.68,116.92 L349.44,124.14 L350.19,132.07 L350.95,140.46 L351.70,149.15 L352.45,157.98 L353.21,166.83 L353.96,175.60 L354.72,184.22 L355.47,192.62 L356.23,200.75 L356.98,208.58 L357.73,216.09 L358.49,223.26 L359.24,230.07 L360.00,236.53 L360.75,242.64 L361.50,248.39 L362.26,253.81 L363.01,258.89 L363.77,263.64 L364.52,268.09 L365.27,272.24 L366.03,276.11 L366.78,279.71 L367.54,283.05 L368.29,286.16 L369.05,289.03 L369.80,291.70 L370.55,294.16 L371.31,296.44 L372.06,298.54 L372.82,300.49 L373.57,302.28 L374.33,303.92 L375.08,305.44 L375.83,306.84 L376.59,308.12 L377.34,309.30 L378.10,310.38 L378.85,311.38 L379.60,312.29 L380.36,313.13 L381.11,313.89 L381.87,314.59 L382.62,315.24 L383.38,315.82 L384.13,316.36 L384.88,316.85 L385.64,317.30 L386.39,317.71 L387.15,318.09 L387.90,318.43 L388.65,318.74 L389.41,319.03 L390.16,319.29 L390.92,319.53 L391.67,319.74 L392.42,319.94 L393.18,320.12 L393.93,320.28 L394.69,320.43 L395.44,320.57 L396.20,320.69 L396.95,320.80 L397.70,320.91 L398.46,321.00 L399.21,321.08 L399.97,321.16 L400.72,321.23 L401.48,321.29 L402.23,321.35 L402.98,321.41 L403.74,321.45 L404.49,321.50 L405.25,321.54 L406.00,321.57 " fill="none" stroke="#2fa35a" stroke-width="1.8" stroke-dasharray="4 3"/><text x="402" y="104" font-size="9" fill="#2fa35a" text-anchor="end">(scale − .96) / .04</text><rect x="464" y="68" width="362" height="276" fill="#fafbfc" stroke="#e3e6ea"/><text x="464" y="59" font-size="12" font-weight="600" fill="#333">child path in root space (parent GLIDE, child DRIFT)</text><path d="M475.31,76.62 L478.21,77.96 L485.79,81.50 L496.64,86.64 L509.65,92.94 L523.99,100.03 L539.03,107.62 L554.30,115.50 L569.43,123.51 L584.18,131.52 L598.38,139.45 L611.91,147.22 L624.71,154.78 L636.74,162.11 L647.99,169.19 L658.47,176.00 L668.21,182.54 L677.24,188.82 L685.59,194.83 L693.31,200.58 L700.44,206.08 L707.02,211.34 L713.09,216.37 L718.70,221.17 L723.88,225.78 L728.67,230.17 L733.10,234.37 L737.20,238.40 L741.01,242.25 L744.54,245.93 L747.82,249.46 L750.88,252.83 L753.73,256.07 L756.39,259.17 L758.89,262.13 L761.21,264.97 L763.40,267.70 L765.45,270.31 L767.38,272.82 L769.20,275.21 L770.91,277.51 L772.53,279.71 L774.05,281.82 L775.50,283.84 L776.86,285.78 L778.16,287.63 L779.39,289.41 L780.55,291.12 L781.65,292.74 L782.70,294.31 L783.70,295.80 L784.65,297.23 L785.55,298.60 L786.42,299.90 L787.23,301.16 L788.01,302.36 L788.75,303.50 L789.46,304.59 L790.13,305.64 L790.76,306.64 L791.37,307.60 L791.96,308.51 L792.50,309.38 L793.03,310.21 L793.54,311.01 L794.02,311.76 L794.48,312.49 L794.91,313.18 L795.32,313.84 L795.72,314.47 L796.09,315.07 L796.45,315.64 L796.79,316.18 L797.12,316.70 L797.43,317.20 L797.73,317.67 L798.00,318.12 L798.28,318.55 L798.52,318.95 L798.77,319.34 L799.00,319.72 L799.22,320.07 L799.42,320.40 L799.63,320.72 L799.81,321.02 L799.99,321.31 L800.17,321.59 L800.33,321.84 L800.48,322.09 L800.63,322.33 L800.77,322.56 L800.90,322.77 L801.02,322.97 L801.15,323.17 L801.26,323.35 L801.37,323.52 L801.47,323.69 L801.57,323.85 L801.66,323.99 L801.75,324.14 L801.84,324.27 L801.92,324.40 L801.99,324.52 L802.06,324.63 L802.13,324.75 L802.19,324.85 L802.25,324.95 L802.31,325.05 L802.37,325.13 L802.42,325.21 L802.47,325.29 L802.52,325.38 L802.56,325.44 L802.61,325.51 L802.65,325.58 L802.69,325.64 L802.72,325.70 L802.76,325.75 L802.79,325.81 L802.82,325.85 L802.84,325.90 L802.88,325.95 L802.91,325.99 L802.92,326.03 L802.95,326.07 L802.98,326.10 L802.99,326.14 L803.01,326.17 L803.03,326.20 L803.06,326.23 L803.07,326.26 L803.08,326.29 L803.10,326.31 L803.12,326.33 L803.13,326.35 L803.15,326.38 L803.15,326.40 L803.16,326.41 L803.18,326.43 L803.19,326.45 L803.20,326.47 L803.21,326.48 L803.22,326.49 L803.22,326.51 L803.23,326.52 L803.24,326.53 L803.25,326.55 L803.25,326.55 L803.26,326.57 L803.27,326.57 L803.28,326.59 L803.28,326.60 L803.29,326.60 L803.29,326.62 L803.30,326.62 L803.30,326.63 L803.30,326.64 L803.30,326.64 L803.31,326.65 L803.31,326.65 L803.31,326.66 L803.32,326.66 L803.32,326.67 L803.32,326.67 L803.33,326.68 L803.33,326.68 L803.33,326.68 L803.34,326.69 L803.34,326.69 L803.34,326.70 L803.34,326.70 L803.34,326.70 L803.35,326.70 L803.35,326.70 L803.35,326.71 L803.35,326.71 L803.35,326.71 L803.35,326.72 L803.36,326.72 L803.36,326.72 L803.36,326.72 L803.36,326.72 L803.36,326.72 L803.36,326.72 L803.36,326.72 L803.36,326.73 L803.36,326.73 L803.37,326.73 L803.37,326.73 L803.37,326.73 L803.37,326.73 L803.37,326.74 L803.37,326.74 L803.37,326.74 L803.37,326.74 L803.37,326.74 L803.37,326.74 L803.37,326.74 L803.37,326.74 L803.37,326.74 L803.37,326.74 L803.37,326.74 L803.37,326.74 L803.37,326.74 L803.37,326.74 L803.37,326.74 L803.38,326.74 L803.38,326.74 L803.38,326.74 L803.38,326.74 L803.38,326.74 L803.38,326.74 L803.38,326.74 L803.38,326.74 L803.38,326.74 L803.38,326.74 L803.38,326.74 L803.38,326.74 L803.38,326.74 L803.38,326.75 " fill="none" stroke="#9aa3ad" stroke-width="1.8"/><text x="822" y="80" font-size="9" fill="#9aa3ad" text-anchor="end">parent space: dog-leg</text><path d="M475.31,76.62 L475.91,77.08 L477.61,78.38 L480.27,80.41 L483.78,83.08 L488.02,86.31 L492.89,90.03 L498.31,94.16 L504.19,98.65 L510.46,103.42 L517.05,108.44 L523.89,113.66 L530.93,119.03 L538.13,124.52 L545.45,130.10 L552.84,135.73 L560.26,141.39 L567.69,147.06 L575.11,152.71 L582.47,158.33 L589.77,163.89 L596.99,169.40 L604.11,174.82 L611.12,180.17 L617.99,185.41 L624.73,190.55 L631.34,195.58 L637.78,200.49 L644.07,205.29 L650.21,209.97 L656.17,214.52 L661.97,218.94 L667.61,223.24 L673.07,227.40 L678.36,231.44 L683.49,235.35 L688.46,239.13 L693.25,242.79 L697.89,246.32 L702.36,249.73 L706.67,253.02 L710.83,256.19 L714.85,259.25 L718.70,262.19 L722.42,265.03 L725.99,267.75 L729.42,270.36 L732.72,272.88 L735.90,275.30 L738.94,277.62 L741.85,279.84 L744.66,281.98 L747.34,284.03 L749.92,286.00 L752.39,287.88 L754.75,289.68 L757.01,291.40 L759.19,293.06 L761.25,294.64 L763.23,296.14 L765.13,297.59 L766.95,298.97 L768.68,300.30 L770.34,301.56 L771.92,302.77 L773.42,303.91 L774.87,305.02 L776.24,306.06 L777.56,307.07 L778.81,308.02 L780.01,308.93 L781.16,309.81 L782.24,310.64 L783.28,311.43 L784.27,312.18 L785.21,312.90 L786.11,313.58 L786.96,314.24 L787.78,314.86 L788.55,315.45 L789.30,316.02 L789.99,316.55 L790.67,317.06 L791.30,317.55 L791.91,318.01 L792.49,318.45 L793.03,318.87 L793.56,319.26 L794.06,319.65 L794.53,320.00 L794.98,320.35 L795.40,320.67 L795.81,320.98 L796.20,321.28 L796.57,321.56 L796.91,321.82 L797.24,322.07 L797.56,322.32 L797.86,322.55 L798.14,322.76 L798.42,322.97 L798.67,323.17 L798.91,323.35 L799.14,323.52 L799.36,323.69 L799.57,323.85 L799.77,324.00 L799.95,324.14 L800.13,324.28 L800.31,324.41 L800.47,324.53 L800.62,324.65 L800.76,324.76 L800.90,324.86 L801.02,324.96 L801.15,325.05 L801.27,325.15 L801.38,325.23 L801.48,325.31 L801.58,325.38 L801.68,325.46 L801.77,325.52 L801.85,325.59 L801.93,325.65 L802.01,325.71 L802.08,325.77 L803.38,326.75 L803.38,326.75 " fill="none" stroke="#2f6fec" stroke-width="1.8"/><text x="822" y="92" font-size="9" fill="#2f6fec" text-anchor="end">Travel::Screen: straight</text></svg> \ No newline at end of file diff --git a/app/vendor/rune/demo/motion/press.png b/app/vendor/rune/demo/motion/press.png new file mode 100644 index 0000000..7fd1800 Binary files /dev/null and b/app/vendor/rune/demo/motion/press.png differ diff --git a/app/vendor/rune/demo/motion/retarget.png b/app/vendor/rune/demo/motion/retarget.png new file mode 100644 index 0000000..34ee1ca Binary files /dev/null and b/app/vendor/rune/demo/motion/retarget.png differ diff --git a/app/vendor/rune/demo/motion/retarget.svg b/app/vendor/rune/demo/motion/retarget.svg new file mode 100644 index 0000000..e83445f --- /dev/null +++ b/app/vendor/rune/demo/motion/retarget.svg @@ -0,0 +1 @@ +<svg xmlns="http://www.w3.org/2000/svg" width="1140" height="1140" viewBox="0 0 1140 1140" font-family="-apple-system, Helvetica, sans-serif"><rect width="100%" height="100%" fill="white"/><text x="16" y="26" font-size="16" font-weight="600" fill="#222">Retargeting at the red lines: position and velocity stay continuous</text><rect x="44" y="68" width="322" height="166" fill="#fafbfc" stroke="#e3e6ea"/><text x="44" y="59" font-size="12" font-weight="600" fill="#333">spring merge (SwiftUI): keeps x and v</text><line x1="44" x2="366" y1="157.91667" y2="157.91667" stroke="#d5d9de" stroke-dasharray="3 3"/><text x="40" y="160.91667" font-size="9" fill="#888" text-anchor="end">0</text><line x1="44" x2="366" y1="88.750015" y2="88.750015" stroke="#d5d9de" stroke-dasharray="3 3"/><text x="40" y="91.750015" font-size="9" fill="#888" text-anchor="end">1</text><text x="366" y="248" font-size="9" fill="#888" text-anchor="end">1.20 s</text><line x1="84.25" x2="84.25" y1="68" y2="234" stroke="#d64545" stroke-width="1" stroke-dasharray="2 3"/><line x1="129.86667" x2="129.86667" y1="68" y2="234" stroke="#d64545" stroke-width="1" stroke-dasharray="2 3"/><line x1="191.58333" x2="191.58333" y1="68" y2="234" stroke="#d64545" stroke-width="1" stroke-dasharray="2 3"/><path d="M44.00,157.92 L44.67,157.86 L45.34,157.71 L46.01,157.47 L46.68,157.15 L47.35,156.75 L48.03,156.27 L48.70,155.74 L49.37,155.14 L50.04,154.49 L50.71,153.79 L51.38,153.05 L52.05,152.27 L52.72,151.46 L53.39,150.61 L54.06,149.73 L54.73,148.83 L55.40,147.91 L56.08,146.98 L56.75,146.02 L57.42,145.05 L58.09,144.08 L58.76,143.09 L59.43,142.10 L60.10,141.10 L60.77,140.10 L61.44,139.11 L62.11,138.11 L62.78,137.11 L63.45,136.12 L64.12,135.13 L64.80,134.15 L65.47,133.17 L66.14,132.21 L66.81,131.25 L67.48,130.30 L68.15,129.36 L68.82,128.43 L69.49,127.51 L70.16,126.61 L70.83,125.71 L71.50,124.83 L72.17,123.97 L72.85,123.11 L73.52,122.27 L74.19,121.44 L74.86,120.63 L75.53,119.83 L76.20,119.05 L76.87,118.28 L77.54,117.52 L78.21,116.78 L78.88,116.05 L79.55,115.34 L80.22,114.64 L80.90,113.96 L81.57,113.29 L82.24,112.63 L82.91,111.99 L83.58,111.37 L84.25,110.75 L84.92,110.78 L85.59,110.85 L86.26,110.97 L86.93,111.12 L87.60,111.32 L88.28,111.54 L88.95,111.80 L89.62,112.09 L90.29,112.40 L90.96,112.74 L91.63,113.10 L92.30,113.47 L92.97,113.87 L93.64,114.27 L94.31,114.70 L94.98,115.13 L95.65,115.57 L96.32,116.02 L97.00,116.48 L97.67,116.95 L98.34,117.42 L99.01,117.90 L99.68,118.37 L100.35,118.85 L101.02,119.34 L101.69,119.82 L102.36,120.30 L103.03,120.78 L103.70,121.26 L104.38,121.73 L105.05,122.21 L105.72,122.68 L106.39,123.14 L107.06,123.60 L107.73,124.06 L108.40,124.51 L109.07,124.96 L109.74,125.40 L110.41,125.84 L111.08,126.27 L111.75,126.69 L112.42,127.11 L113.10,127.52 L113.77,127.93 L114.44,128.33 L115.11,128.72 L115.78,129.10 L116.45,129.48 L117.12,129.85 L117.79,130.22 L118.46,130.58 L119.13,130.93 L119.80,131.27 L120.47,131.61 L121.15,131.94 L121.82,132.26 L122.49,132.57 L123.16,132.88 L123.83,133.18 L124.50,133.48 L125.17,133.77 L125.84,134.05 L126.51,134.33 L127.18,134.60 L127.85,134.86 L128.52,135.12 L129.20,135.37 L129.87,135.61 L130.54,135.57 L131.21,135.46 L131.88,135.27 L132.55,135.02 L133.22,134.70 L133.89,134.34 L134.56,133.92 L135.23,133.46 L135.90,132.95 L136.57,132.41 L137.25,131.83 L137.92,131.23 L138.59,130.59 L139.26,129.93 L139.93,129.25 L140.60,128.55 L141.27,127.84 L141.94,127.11 L142.61,126.36 L143.28,125.61 L143.95,124.85 L144.62,124.09 L145.30,123.31 L145.97,122.54 L146.64,121.76 L147.31,120.99 L147.98,120.21 L148.65,119.44 L149.32,118.66 L149.99,117.90 L150.66,117.13 L151.33,116.37 L152.00,115.62 L152.67,114.88 L153.35,114.14 L154.02,113.41 L154.69,112.69 L155.36,111.97 L156.03,111.27 L156.70,110.57 L157.37,109.89 L158.04,109.22 L158.71,108.55 L159.38,107.90 L160.05,107.25 L160.72,106.62 L161.40,106.00 L162.07,105.39 L162.74,104.79 L163.41,104.20 L164.08,103.63 L164.75,103.06 L165.42,102.51 L166.09,101.97 L166.76,101.43 L167.43,100.91 L168.10,100.40 L168.77,99.91 L169.45,99.42 L170.12,98.94 L170.79,98.47 L171.46,98.02 L172.13,97.57 L172.80,97.14 L173.47,96.71 L174.14,96.30 L174.81,95.89 L175.48,95.50 L176.15,95.11 L176.82,94.74 L177.50,94.37 L178.17,94.01 L178.84,93.66 L179.51,93.32 L180.18,92.99 L180.85,92.67 L181.52,92.35 L182.19,92.05 L182.86,91.75 L183.53,91.46 L184.20,91.18 L184.87,90.90 L185.55,90.63 L186.22,90.37 L186.89,90.12 L187.56,89.87 L188.23,89.63 L188.90,89.40 L189.57,89.17 L190.24,88.95 L190.91,88.73 L191.58,88.53 L192.25,88.55 L192.92,88.61 L193.60,88.70 L194.27,88.84 L194.94,89.00 L195.61,89.19 L196.28,89.40 L196.95,89.64 L197.62,89.91 L198.29,90.19 L198.96,90.49 L199.63,90.80 L200.30,91.13 L200.97,91.47 L201.65,91.83 L202.32,92.19 L202.99,92.56 L203.66,92.94 L204.33,93.32 L205.00,93.71 L205.67,94.11 L206.34,94.50 L207.01,94.90 L207.68,95.31 L208.35,95.71 L209.02,96.11 L209.70,96.51 L210.37,96.92 L211.04,97.32 L211.71,97.71 L212.38,98.11 L213.05,98.50 L213.72,98.89 L214.39,99.28 L215.06,99.66 L215.73,100.04 L216.40,100.42 L217.07,100.79 L217.75,101.15 L218.42,101.51 L219.09,101.87 L219.76,102.22 L220.43,102.56 L221.10,102.90 L221.77,103.23 L222.44,103.56 L223.11,103.88 L223.78,104.20 L224.45,104.51 L225.12,104.81 L225.80,105.11 L226.47,105.41 L227.14,105.69 L227.81,105.98 L228.48,106.25 L229.15,106.52 L229.82,106.79 L230.49,107.04 L231.16,107.30 L231.83,107.54 L232.50,107.79 L233.17,108.02 L233.85,108.25 L234.52,108.48 L235.19,108.70 L235.86,108.91 L236.53,109.12 L237.20,109.33 L237.87,109.53 L238.54,109.72 L239.21,109.92 L239.88,110.10 L240.55,110.28 L241.23,110.46 L241.90,110.63 L242.57,110.80 L243.24,110.96 L243.91,111.12 L244.58,111.27 L245.25,111.42 L245.92,111.57 L246.59,111.71 L247.26,111.85 L247.93,111.99 L248.60,112.12 L249.27,112.25 L249.95,112.37 L250.62,112.49 L251.29,112.61 L251.96,112.73 L252.63,112.84 L253.30,112.95 L253.97,113.05 L254.64,113.15 L255.31,113.25 L255.98,113.35 L256.65,113.44 L257.32,113.53 L258.00,113.62 L258.67,113.71 L259.34,113.79 L260.01,113.87 L260.68,113.95 L261.35,114.03 L262.02,114.10 L262.69,114.18 L263.36,114.25 L264.03,114.31 L264.70,114.38 L265.38,114.44 L266.05,114.50 L266.72,114.56 L267.39,114.62 L268.06,114.68 L268.73,114.73 L269.40,114.79 L270.07,114.84 L270.74,114.89 L271.41,114.94 L272.08,114.99 L272.75,115.03 L273.42,115.08 L274.10,115.12 L274.77,115.16 L275.44,115.20 L276.11,115.24 L276.78,115.28 L277.45,115.31 L278.12,115.35 L278.79,115.38 L279.46,115.42 L280.13,115.45 L280.80,115.48 L281.47,115.51 L282.15,115.54 L282.82,115.57 L283.49,115.60 L284.16,115.62 L284.83,115.65 L285.50,115.67 L286.17,115.70 L286.84,115.72 L287.51,115.74 L288.18,115.77 L288.85,115.79 L289.52,115.81 L290.20,115.83 L290.87,115.85 L291.54,115.87 L292.21,115.89 L292.88,115.90 L293.55,115.92 L294.22,115.94 L294.89,115.95 L295.56,115.97 L296.23,115.98 L296.90,116.00 L297.57,116.01 L298.25,116.02 L298.92,116.04 L299.59,116.05 L300.26,116.06 L300.93,116.07 L301.60,116.09 L302.27,116.10 L302.94,116.11 L303.61,116.12 L304.28,116.13 L304.95,116.14 L305.62,116.15 L306.30,116.16 L306.97,116.16 L307.64,116.17 L308.31,116.18 L308.98,116.19 L309.65,116.20 L310.32,116.20 L310.99,116.21 L311.66,116.22 L312.33,116.23 L313.00,116.23 L313.67,116.24 L314.35,116.24 L315.02,116.25 L315.69,116.26 L316.36,116.26 L317.03,116.27 L317.70,116.27 L318.37,116.28 L319.04,116.28 L319.71,116.29 L320.38,116.29 L321.05,116.29 L321.72,116.30 L322.40,116.30 L323.07,116.31 L323.74,116.31 L324.41,116.31 L325.08,116.32 L325.75,116.32 L326.42,116.32 L327.09,116.33 L327.76,116.33 L328.43,116.33 L329.10,116.34 L329.77,116.34 L330.45,116.34 L331.12,116.34 L331.79,116.35 L332.46,116.35 L333.13,116.35 L333.80,116.35 L334.47,116.36 L335.14,116.36 L335.81,116.36 L336.48,116.36 L337.15,116.36 L337.82,116.37 L338.50,116.37 L339.17,116.37 L339.84,116.37 L340.51,116.37 L341.18,116.37 L341.85,116.38 L342.52,116.38 L343.19,116.38 L343.86,116.38 L344.53,116.38 L345.20,116.38 L345.87,116.38 L346.55,116.38 L347.22,116.39 L347.89,116.39 L348.56,116.39 L349.23,116.39 L349.90,116.39 L350.57,116.39 L351.24,116.39 L351.91,116.39 L352.58,116.39 L353.25,116.39 L353.92,116.39 L354.60,116.40 L355.27,116.40 L355.94,116.40 L356.61,116.40 L357.28,116.40 L357.95,116.40 L358.62,116.40 L359.29,116.40 L359.96,116.40 L360.63,116.40 L361.30,116.40 L361.97,116.40 L362.65,116.40 L363.32,116.40 L363.99,116.40 L364.66,116.40 L365.33,116.40 L366.00,116.41 " fill="none" stroke="#9aa3ad" stroke-width="1.8"/><text x="362" y="80" font-size="9" fill="#9aa3ad" text-anchor="end">naive restart (v = 0)</text><path d="M44.00,157.92 L44.67,150.82 L45.34,144.26 L46.01,138.23 L46.68,132.67 L47.35,127.58 L48.03,122.91 L48.70,118.65 L49.37,114.77 L50.04,111.24 L50.71,108.05 L51.38,105.18 L52.05,102.60 L52.72,100.30 L53.39,98.26 L54.06,96.46 L54.73,94.88 L55.40,93.52 L56.08,92.36 L56.75,91.38 L57.42,90.58 L58.09,89.93 L58.76,89.44 L59.43,89.08 L60.10,88.86 L60.77,88.75 L61.44,88.75 L62.11,88.86 L62.78,89.06 L63.45,89.35 L64.12,89.71 L64.80,90.15 L65.47,90.66 L66.14,91.23 L66.81,91.86 L67.48,92.53 L68.15,93.25 L68.82,94.02 L69.49,94.82 L70.16,95.65 L70.83,96.51 L71.50,97.40 L72.17,98.31 L72.85,99.24 L73.52,100.19 L74.19,101.15 L74.86,102.13 L75.53,103.11 L76.20,104.10 L76.87,105.09 L77.54,106.09 L78.21,107.09 L78.88,108.09 L79.55,109.09 L80.22,110.08 L80.90,111.07 L81.57,112.06 L82.24,113.03 L82.91,114.01 L83.58,114.97 L84.25,157.92 L84.92,161.34 L85.59,164.50 L86.26,167.41 L86.93,170.08 L87.60,172.54 L88.28,174.79 L88.95,176.84 L89.62,178.71 L90.29,180.41 L90.96,181.95 L91.63,183.33 L92.30,184.57 L92.97,185.68 L93.64,186.67 L94.31,187.53 L94.98,188.29 L95.65,188.95 L96.32,189.51 L97.00,189.98 L97.67,190.37 L98.34,190.68 L99.01,190.92 L99.68,191.09 L100.35,191.20 L101.02,191.25 L101.69,191.25 L102.36,191.20 L103.03,191.10 L103.70,190.96 L104.38,190.78 L105.05,190.57 L105.72,190.33 L106.39,190.05 L107.06,189.75 L107.73,189.43 L108.40,189.08 L109.07,188.71 L109.74,188.32 L110.41,187.92 L111.08,187.51 L111.75,187.08 L112.42,186.64 L113.10,186.19 L113.77,185.73 L114.44,185.27 L115.11,184.80 L115.78,184.33 L116.45,183.85 L117.12,183.37 L117.79,182.89 L118.46,182.41 L119.13,181.93 L119.80,181.45 L120.47,180.97 L121.15,180.49 L121.82,180.02 L122.49,179.55 L123.16,179.08 L123.83,178.61 L124.50,178.15 L125.17,177.70 L125.84,177.25 L126.51,176.80 L127.18,176.37 L127.85,175.93 L128.52,175.50 L129.20,175.08 L129.87,157.92 L130.54,152.40 L131.21,147.30 L131.88,142.61 L132.55,138.29 L133.22,134.33 L133.89,130.70 L134.56,127.38 L135.23,124.37 L135.90,121.63 L136.57,119.15 L137.25,116.91 L137.92,114.91 L138.59,113.12 L139.26,111.53 L139.93,110.13 L140.60,108.90 L141.27,107.85 L141.94,106.94 L142.61,106.18 L143.28,105.56 L143.95,105.06 L144.62,104.67 L145.30,104.40 L145.97,104.22 L146.64,104.14 L147.31,104.14 L147.98,104.22 L148.65,104.38 L149.32,104.60 L149.99,104.89 L150.66,105.23 L151.33,105.62 L152.00,106.06 L152.67,106.55 L153.35,107.08 L154.02,107.64 L154.69,108.23 L155.36,108.85 L156.03,109.50 L156.70,110.17 L157.37,110.86 L158.04,111.57 L158.71,112.29 L159.38,113.03 L160.05,113.78 L160.72,114.54 L161.40,115.30 L162.07,116.07 L162.74,116.84 L163.41,117.62 L164.08,118.39 L164.75,119.17 L165.42,119.95 L166.09,120.72 L166.76,121.49 L167.43,122.26 L168.10,123.02 L168.77,123.77 L169.45,124.52 L170.12,125.26 L170.79,126.00 L171.46,126.72 L172.13,127.44 L172.80,128.15 L173.47,128.85 L174.14,129.54 L174.81,130.22 L175.48,130.89 L176.15,131.55 L176.82,132.19 L177.50,132.83 L178.17,133.46 L178.84,134.07 L179.51,134.68 L180.18,135.27 L180.85,135.85 L181.52,136.42 L182.19,136.98 L182.86,137.53 L183.53,138.07 L184.20,138.59 L184.87,139.11 L185.55,139.61 L186.22,140.10 L186.89,140.59 L187.56,141.06 L188.23,141.52 L188.90,141.97 L189.57,142.41 L190.24,142.84 L190.91,143.26 L191.58,157.92 L192.25,160.78 L192.92,163.42 L193.60,165.86 L194.27,168.10 L194.94,170.15 L195.61,172.03 L196.28,173.75 L196.95,175.32 L197.62,176.74 L198.29,178.02 L198.96,179.18 L199.63,180.22 L200.30,181.15 L200.97,181.97 L201.65,182.70 L202.32,183.33 L202.99,183.88 L203.66,184.35 L204.33,184.75 L205.00,185.07 L205.67,185.33 L206.34,185.53 L207.01,185.67 L207.68,185.76 L208.35,185.81 L209.02,185.81 L209.70,185.76 L210.37,185.68 L211.04,185.57 L211.71,185.42 L212.38,185.24 L213.05,185.04 L213.72,184.81 L214.39,184.56 L215.06,184.28 L215.73,183.99 L216.40,183.68 L217.07,183.36 L217.75,183.03 L218.42,182.68 L219.09,182.32 L219.76,181.95 L220.43,181.58 L221.10,181.19 L221.77,180.81 L222.44,180.41 L223.11,180.02 L223.78,179.62 L224.45,179.22 L225.12,178.82 L225.80,178.41 L226.47,178.01 L227.14,177.61 L227.81,177.21 L228.48,176.81 L229.15,176.41 L229.82,176.02 L230.49,175.62 L231.16,175.24 L231.83,174.85 L232.50,174.47 L233.17,174.09 L233.85,173.72 L234.52,173.35 L235.19,172.99 L235.86,172.63 L236.53,172.28 L237.20,171.93 L237.87,171.59 L238.54,171.26 L239.21,170.93 L239.88,170.60 L240.55,170.28 L241.23,169.97 L241.90,169.66 L242.57,169.36 L243.24,169.06 L243.91,168.77 L244.58,168.49 L245.25,168.21 L245.92,167.94 L246.59,167.67 L247.26,167.41 L247.93,167.15 L248.60,166.90 L249.27,166.66 L249.95,166.42 L250.62,166.19 L251.29,165.96 L251.96,165.74 L252.63,165.52 L253.30,165.31 L253.97,165.10 L254.64,164.90 L255.31,164.70 L255.98,164.51 L256.65,164.32 L257.32,164.14 L258.00,163.96 L258.67,163.78 L259.34,163.61 L260.01,163.45 L260.68,163.29 L261.35,163.13 L262.02,162.98 L262.69,162.83 L263.36,162.69 L264.03,162.54 L264.70,162.41 L265.38,162.27 L266.05,162.14 L266.72,162.02 L267.39,161.90 L268.06,161.78 L268.73,161.66 L269.40,161.55 L270.07,161.44 L270.74,161.33 L271.41,161.23 L272.08,161.13 L272.75,161.03 L273.42,160.93 L274.10,160.84 L274.77,160.75 L275.44,160.66 L276.11,160.58 L276.78,160.50 L277.45,160.42 L278.12,160.34 L278.79,160.26 L279.46,160.19 L280.13,160.12 L280.80,160.05 L281.47,159.99 L282.15,159.92 L282.82,159.86 L283.49,159.80 L284.16,159.74 L284.83,159.68 L285.50,159.62 L286.17,159.57 L286.84,159.52 L287.51,159.47 L288.18,159.42 L288.85,159.37 L289.52,159.32 L290.20,159.28 L290.87,159.24 L291.54,159.19 L292.21,159.15 L292.88,159.11 L293.55,159.07 L294.22,159.04 L294.89,159.00 L295.56,158.97 L296.23,158.93 L296.90,158.90 L297.57,158.87 L298.25,158.84 L298.92,158.81 L299.59,158.78 L300.26,158.75 L300.93,158.72 L301.60,158.70 L302.27,158.67 L302.94,158.65 L303.61,158.62 L304.28,158.60 L304.95,158.58 L305.62,158.55 L306.30,158.53 L306.97,158.51 L307.64,158.49 L308.31,158.48 L308.98,158.46 L309.65,158.44 L310.32,158.42 L310.99,158.40 L311.66,158.39 L312.33,158.37 L313.00,158.36 L313.67,158.34 L314.35,158.33 L315.02,158.32 L315.69,158.30 L316.36,158.29 L317.03,158.28 L317.70,158.26 L318.37,158.25 L319.04,158.24 L319.71,158.23 L320.38,158.22 L321.05,158.21 L321.72,158.20 L322.40,158.19 L323.07,158.18 L323.74,158.17 L324.41,158.16 L325.08,158.16 L325.75,158.15 L326.42,158.14 L327.09,158.13 L327.76,158.13 L328.43,158.12 L329.10,158.11 L329.77,158.10 L330.45,158.10 L331.12,158.09 L331.79,158.09 L332.46,158.08 L333.13,158.08 L333.80,158.07 L334.47,158.06 L335.14,158.06 L335.81,158.05 L336.48,158.05 L337.15,158.05 L337.82,158.04 L338.50,158.04 L339.17,158.03 L339.84,158.03 L340.51,158.02 L341.18,158.02 L341.85,158.02 L342.52,158.01 L343.19,158.01 L343.86,158.01 L344.53,158.00 L345.20,158.00 L345.87,158.00 L346.55,158.00 L347.22,157.99 L347.89,157.99 L348.56,157.99 L349.23,157.99 L349.90,157.98 L350.57,157.98 L351.24,157.98 L351.91,157.98 L352.58,157.97 L353.25,157.97 L353.92,157.97 L354.60,157.97 L355.27,157.97 L355.94,157.97 L356.61,157.96 L357.28,157.96 L357.95,157.96 L358.62,157.96 L359.29,157.96 L359.96,157.96 L360.63,157.95 L361.30,157.95 L361.97,157.95 L362.65,157.95 L363.32,157.95 L363.99,157.95 L364.66,157.95 L365.33,157.95 L366.00,157.95 " fill="none" stroke="#9aa3ad" stroke-width="1.8" stroke-dasharray="4 3"/><path d="M44.00,157.92 L44.67,157.86 L45.34,157.71 L46.01,157.47 L46.68,157.15 L47.35,156.75 L48.03,156.27 L48.70,155.74 L49.37,155.14 L50.04,154.49 L50.71,153.79 L51.38,153.05 L52.05,152.27 L52.72,151.46 L53.39,150.61 L54.06,149.73 L54.73,148.83 L55.40,147.91 L56.08,146.98 L56.75,146.02 L57.42,145.05 L58.09,144.08 L58.76,143.09 L59.43,142.10 L60.10,141.10 L60.77,140.10 L61.44,139.11 L62.11,138.11 L62.78,137.11 L63.45,136.12 L64.12,135.13 L64.80,134.15 L65.47,133.17 L66.14,132.21 L66.81,131.25 L67.48,130.30 L68.15,129.36 L68.82,128.43 L69.49,127.51 L70.16,126.61 L70.83,125.71 L71.50,124.83 L72.17,123.97 L72.85,123.11 L73.52,122.27 L74.19,121.44 L74.86,120.63 L75.53,119.83 L76.20,119.05 L76.87,118.28 L77.54,117.52 L78.21,116.78 L78.88,116.05 L79.55,115.34 L80.22,114.64 L80.90,113.96 L81.57,113.29 L82.24,112.63 L82.91,111.99 L83.58,111.37 L84.25,110.75 L84.92,110.19 L85.59,109.73 L86.26,109.35 L86.93,109.05 L87.60,108.82 L88.28,108.67 L88.95,108.58 L89.62,108.55 L90.29,108.57 L90.96,108.64 L91.63,108.76 L92.30,108.93 L92.97,109.13 L93.64,109.37 L94.31,109.65 L94.98,109.95 L95.65,110.28 L96.32,110.64 L97.00,111.02 L97.67,111.42 L98.34,111.84 L99.01,112.27 L99.68,112.72 L100.35,113.18 L101.02,113.65 L101.69,114.14 L102.36,114.63 L103.03,115.12 L103.70,115.62 L104.38,116.13 L105.05,116.64 L105.72,117.15 L106.39,117.66 L107.06,118.18 L107.73,118.69 L108.40,119.20 L109.07,119.71 L109.74,120.22 L110.41,120.73 L111.08,121.23 L111.75,121.72 L112.42,122.22 L113.10,122.71 L113.77,123.19 L114.44,123.67 L115.11,124.14 L115.78,124.60 L116.45,125.06 L117.12,125.51 L117.79,125.96 L118.46,126.40 L119.13,126.83 L119.80,127.26 L120.47,127.68 L121.15,128.09 L121.82,128.49 L122.49,128.89 L123.16,129.28 L123.83,129.66 L124.50,130.03 L125.17,130.40 L125.84,130.76 L126.51,131.11 L127.18,131.45 L127.85,131.79 L128.52,132.12 L129.20,132.44 L129.87,132.76 L130.54,133.02 L131.21,133.19 L131.88,133.26 L132.55,133.26 L133.22,133.18 L133.89,133.03 L134.56,132.81 L135.23,132.54 L135.90,132.21 L136.57,131.83 L137.25,131.41 L137.92,130.94 L138.59,130.44 L139.26,129.90 L139.93,129.33 L140.60,128.74 L141.27,128.12 L141.94,127.47 L142.61,126.81 L143.28,126.13 L143.95,125.44 L144.62,124.74 L145.30,124.02 L145.97,123.30 L146.64,122.57 L147.31,121.83 L147.98,121.09 L148.65,120.35 L149.32,119.61 L149.99,118.86 L150.66,118.12 L151.33,117.38 L152.00,116.65 L152.67,115.91 L153.35,115.19 L154.02,114.46 L154.69,113.75 L155.36,113.04 L156.03,112.34 L156.70,111.64 L157.37,110.96 L158.04,110.28 L158.71,109.61 L159.38,108.95 L160.05,108.30 L160.72,107.66 L161.40,107.03 L162.07,106.42 L162.74,105.81 L163.41,105.21 L164.08,104.62 L164.75,104.04 L165.42,103.48 L166.09,102.92 L166.76,102.37 L167.43,101.84 L168.10,101.32 L168.77,100.80 L169.45,100.30 L170.12,99.81 L170.79,99.33 L171.46,98.86 L172.13,98.39 L172.80,97.94 L173.47,97.50 L174.14,97.07 L174.81,96.65 L175.48,96.24 L176.15,95.84 L176.82,95.45 L177.50,95.07 L178.17,94.69 L178.84,94.33 L179.51,93.98 L180.18,93.63 L180.85,93.29 L181.52,92.96 L182.19,92.64 L182.86,92.33 L183.53,92.03 L184.20,91.73 L184.87,91.44 L185.55,91.16 L186.22,90.89 L186.89,90.62 L187.56,90.36 L188.23,90.11 L188.90,89.86 L189.57,89.62 L190.24,89.39 L190.91,89.16 L191.58,88.94 L192.25,88.76 L192.92,88.62 L193.60,88.54 L194.27,88.51 L194.94,88.52 L195.61,88.57 L196.28,88.66 L196.95,88.78 L197.62,88.93 L198.29,89.12 L198.96,89.33 L199.63,89.56 L200.30,89.82 L200.97,90.09 L201.65,90.39 L202.32,90.70 L202.99,91.03 L203.66,91.37 L204.33,91.72 L205.00,92.08 L205.67,92.45 L206.34,92.82 L207.01,93.21 L207.68,93.59 L208.35,93.99 L209.02,94.38 L209.70,94.78 L210.37,95.19 L211.04,95.59 L211.71,95.99 L212.38,96.39 L213.05,96.80 L213.72,97.20 L214.39,97.60 L215.06,97.99 L215.73,98.39 L216.40,98.78 L217.07,99.17 L217.75,99.55 L218.42,99.93 L219.09,100.31 L219.76,100.68 L220.43,101.05 L221.10,101.41 L221.77,101.76 L222.44,102.12 L223.11,102.46 L223.78,102.80 L224.45,103.14 L225.12,103.47 L225.80,103.79 L226.47,104.11 L227.14,104.42 L227.81,104.73 L228.48,105.03 L229.15,105.32 L229.82,105.61 L230.49,105.90 L231.16,106.17 L231.83,106.44 L232.50,106.71 L233.17,106.97 L233.85,107.23 L234.52,107.47 L235.19,107.72 L235.86,107.96 L236.53,108.19 L237.20,108.42 L237.87,108.64 L238.54,108.85 L239.21,109.07 L239.88,109.27 L240.55,109.47 L241.23,109.67 L241.90,109.86 L242.57,110.05 L243.24,110.23 L243.91,110.41 L244.58,110.58 L245.25,110.75 L245.92,110.91 L246.59,111.07 L247.26,111.23 L247.93,111.38 L248.60,111.53 L249.27,111.67 L249.95,111.81 L250.62,111.95 L251.29,112.08 L251.96,112.21 L252.63,112.34 L253.30,112.46 L253.97,112.58 L254.64,112.69 L255.31,112.81 L255.98,112.92 L256.65,113.02 L257.32,113.12 L258.00,113.23 L258.67,113.32 L259.34,113.42 L260.01,113.51 L260.68,113.60 L261.35,113.68 L262.02,113.77 L262.69,113.85 L263.36,113.93 L264.03,114.01 L264.70,114.08 L265.38,114.15 L266.05,114.23 L266.72,114.29 L267.39,114.36 L268.06,114.42 L268.73,114.49 L269.40,114.55 L270.07,114.61 L270.74,114.66 L271.41,114.72 L272.08,114.77 L272.75,114.83 L273.42,114.88 L274.10,114.92 L274.77,114.97 L275.44,115.02 L276.11,115.06 L276.78,115.11 L277.45,115.15 L278.12,115.19 L278.79,115.23 L279.46,115.27 L280.13,115.30 L280.80,115.34 L281.47,115.37 L282.15,115.41 L282.82,115.44 L283.49,115.47 L284.16,115.50 L284.83,115.53 L285.50,115.56 L286.17,115.59 L286.84,115.62 L287.51,115.64 L288.18,115.67 L288.85,115.69 L289.52,115.72 L290.20,115.74 L290.87,115.76 L291.54,115.78 L292.21,115.80 L292.88,115.82 L293.55,115.84 L294.22,115.86 L294.89,115.88 L295.56,115.90 L296.23,115.91 L296.90,115.93 L297.57,115.95 L298.25,115.96 L298.92,115.98 L299.59,115.99 L300.26,116.01 L300.93,116.02 L301.60,116.03 L302.27,116.05 L302.94,116.06 L303.61,116.07 L304.28,116.08 L304.95,116.09 L305.62,116.10 L306.30,116.11 L306.97,116.12 L307.64,116.13 L308.31,116.14 L308.98,116.15 L309.65,116.16 L310.32,116.17 L310.99,116.18 L311.66,116.19 L312.33,116.19 L313.00,116.20 L313.67,116.21 L314.35,116.22 L315.02,116.22 L315.69,116.23 L316.36,116.24 L317.03,116.24 L317.70,116.25 L318.37,116.25 L319.04,116.26 L319.71,116.26 L320.38,116.27 L321.05,116.27 L321.72,116.28 L322.40,116.28 L323.07,116.29 L323.74,116.29 L324.41,116.30 L325.08,116.30 L325.75,116.31 L326.42,116.31 L327.09,116.31 L327.76,116.32 L328.43,116.32 L329.10,116.32 L329.77,116.33 L330.45,116.33 L331.12,116.33 L331.79,116.34 L332.46,116.34 L333.13,116.34 L333.80,116.34 L334.47,116.35 L335.14,116.35 L335.81,116.35 L336.48,116.35 L337.15,116.36 L337.82,116.36 L338.50,116.36 L339.17,116.36 L339.84,116.36 L340.51,116.37 L341.18,116.37 L341.85,116.37 L342.52,116.37 L343.19,116.37 L343.86,116.37 L344.53,116.37 L345.20,116.38 L345.87,116.38 L346.55,116.38 L347.22,116.38 L347.89,116.38 L348.56,116.38 L349.23,116.38 L349.90,116.39 L350.57,116.39 L351.24,116.39 L351.91,116.39 L352.58,116.39 L353.25,116.39 L353.92,116.39 L354.60,116.39 L355.27,116.39 L355.94,116.39 L356.61,116.39 L357.28,116.40 L357.95,116.40 L358.62,116.40 L359.29,116.40 L359.96,116.40 L360.63,116.40 L361.30,116.40 L361.97,116.40 L362.65,116.40 L363.32,116.40 L363.99,116.40 L364.66,116.40 L365.33,116.40 L366.00,116.40 " fill="none" stroke="#2f6fec" stroke-width="1.8"/><text x="362" y="104" font-size="9" fill="#2f6fec" text-anchor="end">position</text><path d="M44.00,157.92 L44.67,150.82 L45.34,144.26 L46.01,138.23 L46.68,132.67 L47.35,127.58 L48.03,122.91 L48.70,118.65 L49.37,114.77 L50.04,111.24 L50.71,108.05 L51.38,105.18 L52.05,102.60 L52.72,100.30 L53.39,98.26 L54.06,96.46 L54.73,94.88 L55.40,93.52 L56.08,92.36 L56.75,91.38 L57.42,90.58 L58.09,89.93 L58.76,89.44 L59.43,89.08 L60.10,88.86 L60.77,88.75 L61.44,88.75 L62.11,88.86 L62.78,89.06 L63.45,89.35 L64.12,89.71 L64.80,90.15 L65.47,90.66 L66.14,91.23 L66.81,91.86 L67.48,92.53 L68.15,93.25 L68.82,94.02 L69.49,94.82 L70.16,95.65 L70.83,96.51 L71.50,97.40 L72.17,98.31 L72.85,99.24 L73.52,100.19 L74.19,101.15 L74.86,102.13 L75.53,103.11 L76.20,104.10 L76.87,105.09 L77.54,106.09 L78.21,107.09 L78.88,108.09 L79.55,109.09 L80.22,110.08 L80.90,111.07 L81.57,112.06 L82.24,113.03 L82.91,114.01 L83.58,114.97 L84.25,115.92 L84.92,122.55 L85.59,128.72 L86.26,134.48 L86.93,139.83 L87.60,144.81 L88.28,149.42 L88.95,153.71 L89.62,157.67 L90.29,161.34 L90.96,164.72 L91.63,167.84 L92.30,170.71 L92.97,173.35 L93.64,175.76 L94.31,177.96 L94.98,179.97 L95.65,181.79 L96.32,183.44 L97.00,184.92 L97.67,186.26 L98.34,187.45 L99.01,188.51 L99.68,189.44 L100.35,190.26 L101.02,190.96 L101.69,191.56 L102.36,192.07 L103.03,192.49 L103.70,192.83 L104.38,193.09 L105.05,193.27 L105.72,193.39 L106.39,193.45 L107.06,193.45 L107.73,193.40 L108.40,193.30 L109.07,193.16 L109.74,192.97 L110.41,192.75 L111.08,192.49 L111.75,192.20 L112.42,191.88 L113.10,191.53 L113.77,191.17 L114.44,190.77 L115.11,190.36 L115.78,189.94 L116.45,189.49 L117.12,189.04 L117.79,188.57 L118.46,188.09 L119.13,187.61 L119.80,187.11 L120.47,186.61 L121.15,186.11 L121.82,185.60 L122.49,185.09 L123.16,184.58 L123.83,184.07 L124.50,183.55 L125.17,183.04 L125.84,182.53 L126.51,182.02 L127.18,181.51 L127.85,181.01 L128.52,180.51 L129.20,180.02 L129.87,179.52 L130.54,172.65 L131.21,166.27 L131.88,160.36 L132.55,154.90 L133.22,149.85 L133.89,145.19 L134.56,140.91 L135.23,136.97 L135.90,133.36 L136.57,130.06 L137.25,127.06 L137.92,124.32 L138.59,121.84 L139.26,119.60 L139.93,117.59 L140.60,115.79 L141.27,114.19 L141.94,112.77 L142.61,111.53 L143.28,110.45 L143.95,109.52 L144.62,108.74 L145.30,108.08 L145.97,107.55 L146.64,107.14 L147.31,106.83 L147.98,106.62 L148.65,106.50 L149.32,106.47 L149.99,106.52 L150.66,106.63 L151.33,106.82 L152.00,107.07 L152.67,107.37 L153.35,107.73 L154.02,108.13 L154.69,108.58 L155.36,109.07 L156.03,109.59 L156.70,110.14 L157.37,110.73 L158.04,111.34 L158.71,111.97 L159.38,112.62 L160.05,113.29 L160.72,113.98 L161.40,114.68 L162.07,115.39 L162.74,116.11 L163.41,116.84 L164.08,117.57 L164.75,118.31 L165.42,119.05 L166.09,119.79 L166.76,120.53 L167.43,121.28 L168.10,122.02 L168.77,122.76 L169.45,123.49 L170.12,124.22 L170.79,124.94 L171.46,125.66 L172.13,126.38 L172.80,127.08 L173.47,127.78 L174.14,128.47 L174.81,129.15 L175.48,129.82 L176.15,130.49 L176.82,131.14 L177.50,131.79 L178.17,132.42 L178.84,133.04 L179.51,133.66 L180.18,134.26 L180.85,134.85 L181.52,135.44 L182.19,136.01 L182.86,136.57 L183.53,137.12 L184.20,137.66 L184.87,138.19 L185.55,138.71 L186.22,139.21 L186.89,139.71 L187.56,140.20 L188.23,140.67 L188.90,141.14 L189.57,141.60 L190.24,142.04 L190.91,142.48 L191.58,142.90 L192.25,146.87 L192.92,150.55 L193.60,153.96 L194.27,157.13 L194.94,160.05 L195.61,162.75 L196.28,165.24 L196.95,167.53 L197.62,169.64 L198.29,171.56 L198.96,173.33 L199.63,174.93 L200.30,176.39 L200.97,177.71 L201.65,178.90 L202.32,179.97 L202.99,180.93 L203.66,181.78 L204.33,182.53 L205.00,183.19 L205.67,183.76 L206.34,184.25 L207.01,184.67 L207.68,185.01 L208.35,185.29 L209.02,185.50 L209.70,185.66 L210.37,185.76 L211.04,185.82 L211.71,185.83 L212.38,185.80 L213.05,185.73 L213.72,185.62 L214.39,185.48 L215.06,185.31 L215.73,185.11 L216.40,184.89 L217.07,184.64 L217.75,184.37 L218.42,184.09 L219.09,183.78 L219.76,183.46 L220.43,183.13 L221.10,182.79 L221.77,182.43 L222.44,182.06 L223.11,181.69 L223.78,181.31 L224.45,180.92 L225.12,180.53 L225.80,180.14 L226.47,179.74 L227.14,179.34 L227.81,178.94 L228.48,178.53 L229.15,178.13 L229.82,177.73 L230.49,177.32 L231.16,176.92 L231.83,176.53 L232.50,176.13 L233.17,175.74 L233.85,175.35 L234.52,174.96 L235.19,174.58 L235.86,174.20 L236.53,173.83 L237.20,173.46 L237.87,173.10 L238.54,172.74 L239.21,172.38 L239.88,172.03 L240.55,171.69 L241.23,171.35 L241.90,171.02 L242.57,170.69 L243.24,170.37 L243.91,170.06 L244.58,169.75 L245.25,169.45 L245.92,169.15 L246.59,168.86 L247.26,168.57 L247.93,168.29 L248.60,168.02 L249.27,167.75 L249.95,167.48 L250.62,167.23 L251.29,166.98 L251.96,166.73 L252.63,166.49 L253.30,166.25 L253.97,166.02 L254.64,165.80 L255.31,165.58 L255.98,165.37 L256.65,165.16 L257.32,164.95 L258.00,164.76 L258.67,164.56 L259.34,164.37 L260.01,164.19 L260.68,164.01 L261.35,163.83 L262.02,163.66 L262.69,163.50 L263.36,163.33 L264.03,163.18 L264.70,163.02 L265.38,162.87 L266.05,162.73 L266.72,162.58 L267.39,162.45 L268.06,162.31 L268.73,162.18 L269.40,162.05 L270.07,161.93 L270.74,161.81 L271.41,161.69 L272.08,161.58 L272.75,161.47 L273.42,161.36 L274.10,161.26 L274.77,161.16 L275.44,161.06 L276.11,160.96 L276.78,160.87 L277.45,160.78 L278.12,160.69 L278.79,160.60 L279.46,160.52 L280.13,160.44 L280.80,160.36 L281.47,160.29 L282.15,160.21 L282.82,160.14 L283.49,160.07 L284.16,160.00 L284.83,159.94 L285.50,159.88 L286.17,159.81 L286.84,159.75 L287.51,159.70 L288.18,159.64 L288.85,159.59 L289.52,159.53 L290.20,159.48 L290.87,159.43 L291.54,159.38 L292.21,159.34 L292.88,159.29 L293.55,159.25 L294.22,159.20 L294.89,159.16 L295.56,159.12 L296.23,159.08 L296.90,159.05 L297.57,159.01 L298.25,158.98 L298.92,158.94 L299.59,158.91 L300.26,158.88 L300.93,158.84 L301.60,158.81 L302.27,158.79 L302.94,158.76 L303.61,158.73 L304.28,158.70 L304.95,158.68 L305.62,158.65 L306.30,158.63 L306.97,158.61 L307.64,158.58 L308.31,158.56 L308.98,158.54 L309.65,158.52 L310.32,158.50 L310.99,158.48 L311.66,158.46 L312.33,158.44 L313.00,158.43 L313.67,158.41 L314.35,158.39 L315.02,158.38 L315.69,158.36 L316.36,158.35 L317.03,158.33 L317.70,158.32 L318.37,158.31 L319.04,158.29 L319.71,158.28 L320.38,158.27 L321.05,158.26 L321.72,158.25 L322.40,158.23 L323.07,158.22 L323.74,158.21 L324.41,158.20 L325.08,158.19 L325.75,158.18 L326.42,158.18 L327.09,158.17 L327.76,158.16 L328.43,158.15 L329.10,158.14 L329.77,158.13 L330.45,158.13 L331.12,158.12 L331.79,158.11 L332.46,158.11 L333.13,158.10 L333.80,158.09 L334.47,158.09 L335.14,158.08 L335.81,158.08 L336.48,158.07 L337.15,158.07 L337.82,158.06 L338.50,158.06 L339.17,158.05 L339.84,158.05 L340.51,158.04 L341.18,158.04 L341.85,158.03 L342.52,158.03 L343.19,158.03 L343.86,158.02 L344.53,158.02 L345.20,158.02 L345.87,158.01 L346.55,158.01 L347.22,158.01 L347.89,158.00 L348.56,158.00 L349.23,158.00 L349.90,157.99 L350.57,157.99 L351.24,157.99 L351.91,157.99 L352.58,157.98 L353.25,157.98 L353.92,157.98 L354.60,157.98 L355.27,157.97 L355.94,157.97 L356.61,157.97 L357.28,157.97 L357.95,157.97 L358.62,157.97 L359.29,157.96 L359.96,157.96 L360.63,157.96 L361.30,157.96 L361.97,157.96 L362.65,157.96 L363.32,157.95 L363.99,157.95 L364.66,157.95 L365.33,157.95 L366.00,157.95 " fill="none" stroke="#e8833a" stroke-width="1.8" stroke-dasharray="4 3"/><text x="362" y="116" font-size="9" fill="#e8833a" text-anchor="end">velocity</text><rect x="424" y="68" width="322" height="166" fill="#fafbfc" stroke="#e3e6ea"/><text x="424" y="59" font-size="12" font-weight="600" fill="#333">tween additive (Core Animation)</text><line x1="424" x2="746" y1="157.91667" y2="157.91667" stroke="#d5d9de" stroke-dasharray="3 3"/><text x="420" y="160.91667" font-size="9" fill="#888" text-anchor="end">0</text><line x1="424" x2="746" y1="88.750015" y2="88.750015" stroke="#d5d9de" stroke-dasharray="3 3"/><text x="420" y="91.750015" font-size="9" fill="#888" text-anchor="end">1</text><text x="746" y="248" font-size="9" fill="#888" text-anchor="end">1.20 s</text><line x1="464.25" x2="464.25" y1="68" y2="234" stroke="#d64545" stroke-width="1" stroke-dasharray="2 3"/><line x1="509.86667" x2="509.86667" y1="68" y2="234" stroke="#d64545" stroke-width="1" stroke-dasharray="2 3"/><line x1="571.5833" x2="571.5833" y1="68" y2="234" stroke="#d64545" stroke-width="1" stroke-dasharray="2 3"/><path d="M424.00,157.92 L424.67,157.91 L425.34,157.89 L426.01,157.86 L426.68,157.81 L427.35,157.75 L428.02,157.67 L428.70,157.58 L429.37,157.48 L430.04,157.36 L430.71,157.23 L431.38,157.08 L432.05,156.92 L432.72,156.74 L433.39,156.55 L434.06,156.35 L434.73,156.12 L435.40,155.89 L436.08,155.64 L436.75,155.37 L437.42,155.09 L438.09,154.79 L438.76,154.48 L439.43,154.15 L440.10,153.80 L440.77,153.44 L441.44,153.07 L442.11,152.68 L442.78,152.27 L443.45,151.85 L444.12,151.41 L444.80,150.95 L445.47,150.48 L446.14,150.00 L446.81,149.50 L447.48,148.98 L448.15,148.45 L448.82,147.91 L449.49,147.35 L450.16,146.77 L450.83,146.18 L451.50,145.57 L452.17,144.96 L452.85,144.32 L453.52,143.68 L454.19,143.02 L454.86,142.34 L455.53,141.66 L456.20,140.96 L456.87,140.25 L457.54,139.52 L458.21,138.79 L458.88,138.04 L459.55,137.29 L460.23,136.52 L460.90,135.75 L461.57,134.96 L462.24,134.17 L462.91,133.37 L463.58,132.56 L464.25,131.74 L464.92,131.74 L465.59,131.75 L466.26,131.75 L466.93,131.76 L467.60,131.77 L468.27,131.79 L468.95,131.80 L469.62,131.82 L470.29,131.84 L470.96,131.86 L471.63,131.89 L472.30,131.92 L472.97,131.95 L473.64,131.99 L474.31,132.02 L474.98,132.06 L475.65,132.10 L476.33,132.15 L477.00,132.20 L477.67,132.25 L478.34,132.30 L479.01,132.36 L479.68,132.41 L480.35,132.48 L481.02,132.54 L481.69,132.61 L482.36,132.68 L483.03,132.75 L483.70,132.83 L484.38,132.90 L485.05,132.98 L485.72,133.07 L486.39,133.15 L487.06,133.24 L487.73,133.34 L488.40,133.43 L489.07,133.53 L489.74,133.63 L490.41,133.73 L491.08,133.84 L491.75,133.94 L492.42,134.05 L493.10,134.17 L493.77,134.28 L494.44,134.40 L495.11,134.52 L495.78,134.64 L496.45,134.77 L497.12,134.89 L497.79,135.02 L498.46,135.15 L499.13,135.29 L499.80,135.42 L500.47,135.56 L501.15,135.70 L501.82,135.84 L502.49,135.98 L503.16,136.12 L503.83,136.27 L504.50,136.41 L505.17,136.56 L505.84,136.71 L506.51,136.86 L507.18,137.00 L507.85,137.16 L508.52,137.31 L509.20,137.46 L509.87,137.61 L510.54,137.60 L511.21,137.59 L511.88,137.56 L512.55,137.52 L513.22,137.47 L513.89,137.41 L514.56,137.34 L515.23,137.26 L515.90,137.16 L516.58,137.05 L517.25,136.94 L517.92,136.81 L518.59,136.66 L519.26,136.51 L519.93,136.34 L520.60,136.16 L521.27,135.97 L521.94,135.77 L522.61,135.56 L523.28,135.33 L523.95,135.09 L524.62,134.83 L525.30,134.57 L525.97,134.29 L526.64,134.00 L527.31,133.70 L527.98,133.38 L528.65,133.05 L529.32,132.71 L529.99,132.36 L530.66,131.99 L531.33,131.62 L532.00,131.22 L532.67,130.82 L533.35,130.40 L534.02,129.98 L534.69,129.54 L535.36,129.08 L536.03,128.62 L536.70,128.14 L537.37,127.66 L538.04,127.16 L538.71,126.65 L539.38,126.12 L540.05,125.59 L540.72,125.05 L541.40,124.50 L542.07,123.93 L542.74,123.36 L543.41,122.78 L544.08,122.18 L544.75,121.58 L545.42,120.97 L546.09,120.36 L546.76,119.73 L547.43,119.10 L548.10,118.46 L548.78,117.81 L549.45,117.16 L550.12,116.50 L550.79,115.84 L551.46,115.17 L552.13,114.50 L552.80,113.82 L553.47,113.14 L554.14,112.46 L554.81,111.78 L555.48,111.09 L556.15,110.41 L556.83,109.72 L557.50,109.03 L558.17,108.35 L558.84,107.66 L559.51,106.98 L560.18,106.30 L560.85,105.62 L561.52,104.94 L562.19,104.27 L562.86,103.60 L563.53,102.94 L564.20,102.28 L564.88,101.63 L565.55,100.98 L566.22,100.34 L566.89,99.71 L567.56,99.09 L568.23,98.47 L568.90,97.86 L569.57,97.26 L570.24,96.67 L570.91,96.08 L571.58,95.51 L572.25,95.51 L572.92,95.52 L573.60,95.53 L574.27,95.54 L574.94,95.56 L575.61,95.58 L576.28,95.61 L576.95,95.64 L577.62,95.68 L578.29,95.72 L578.96,95.76 L579.63,95.81 L580.30,95.86 L580.97,95.92 L581.65,95.98 L582.32,96.05 L582.99,96.12 L583.66,96.20 L584.33,96.28 L585.00,96.36 L585.67,96.46 L586.34,96.55 L587.01,96.65 L587.68,96.75 L588.35,96.86 L589.03,96.98 L589.70,97.09 L590.37,97.22 L591.04,97.34 L591.71,97.48 L592.38,97.61 L593.05,97.76 L593.72,97.90 L594.39,98.05 L595.06,98.21 L595.73,98.37 L596.40,98.54 L597.07,98.71 L597.75,98.88 L598.42,99.06 L599.09,99.24 L599.76,99.43 L600.43,99.62 L601.10,99.81 L601.77,100.01 L602.44,100.22 L603.11,100.43 L603.78,100.64 L604.45,100.85 L605.12,101.07 L605.80,101.29 L606.47,101.52 L607.14,101.75 L607.81,101.98 L608.48,102.21 L609.15,102.45 L609.82,102.69 L610.49,102.93 L611.16,103.18 L611.83,103.42 L612.50,103.67 L613.17,103.92 L613.85,104.17 L614.52,104.43 L615.19,104.68 L615.86,104.94 L616.53,105.19 L617.20,105.45 L617.87,105.71 L618.54,105.96 L619.21,106.22 L619.88,106.48 L620.55,106.73 L621.22,106.99 L621.90,107.25 L622.57,107.50 L623.24,107.75 L623.91,108.01 L624.58,108.26 L625.25,108.50 L625.92,108.75 L626.59,109.00 L627.26,109.24 L627.93,109.48 L628.60,109.72 L629.28,109.95 L629.95,110.18 L630.62,110.41 L631.29,110.63 L631.96,110.86 L632.63,111.08 L633.30,111.29 L633.97,111.50 L634.64,111.71 L635.31,111.91 L635.98,112.11 L636.65,112.31 L637.32,112.50 L638.00,112.69 L638.67,112.87 L639.34,113.05 L640.01,113.22 L640.68,113.39 L641.35,113.56 L642.02,113.72 L642.69,113.87 L643.36,114.02 L644.03,114.17 L644.70,114.31 L645.38,114.45 L646.05,114.58 L646.72,114.71 L647.39,114.83 L648.06,114.95 L648.73,115.06 L649.40,115.17 L650.07,115.28 L650.74,115.38 L651.41,115.47 L652.08,115.56 L652.75,115.65 L653.42,115.73 L654.10,115.80 L654.77,115.88 L655.44,115.94 L656.11,116.00 L656.78,116.06 L657.45,116.12 L658.12,116.16 L658.79,116.21 L659.46,116.25 L660.13,116.28 L660.80,116.32 L661.47,116.34 L662.15,116.37 L662.82,116.38 L663.49,116.40 L664.16,116.41 L664.83,116.41 L665.50,116.42 L666.17,116.42 L666.84,116.42 L667.51,116.42 L668.18,116.42 L668.85,116.42 L669.53,116.42 L670.20,116.42 L670.87,116.42 L671.54,116.42 L672.21,116.42 L672.88,116.42 L673.55,116.42 L674.22,116.42 L674.89,116.42 L675.56,116.42 L676.23,116.42 L676.90,116.42 L677.57,116.42 L678.25,116.42 L678.92,116.42 L679.59,116.42 L680.26,116.42 L680.93,116.42 L681.60,116.42 L682.27,116.42 L682.94,116.42 L683.61,116.42 L684.28,116.42 L684.95,116.42 L685.62,116.42 L686.30,116.42 L686.97,116.42 L687.64,116.42 L688.31,116.42 L688.98,116.42 L689.65,116.42 L690.32,116.42 L690.99,116.42 L691.66,116.42 L692.33,116.42 L693.00,116.42 L693.67,116.42 L694.35,116.42 L695.02,116.42 L695.69,116.42 L696.36,116.42 L697.03,116.42 L697.70,116.42 L698.37,116.42 L699.04,116.42 L699.71,116.42 L700.38,116.42 L701.05,116.42 L701.72,116.42 L702.40,116.42 L703.07,116.42 L703.74,116.42 L704.41,116.42 L705.08,116.42 L705.75,116.42 L706.42,116.42 L707.09,116.42 L707.76,116.42 L708.43,116.42 L709.10,116.42 L709.78,116.42 L710.45,116.42 L711.12,116.42 L711.79,116.42 L712.46,116.42 L713.13,116.42 L713.80,116.42 L714.47,116.42 L715.14,116.42 L715.81,116.42 L716.48,116.42 L717.15,116.42 L717.82,116.42 L718.50,116.42 L719.17,116.42 L719.84,116.42 L720.51,116.42 L721.18,116.42 L721.85,116.42 L722.52,116.42 L723.19,116.42 L723.86,116.42 L724.53,116.42 L725.20,116.42 L725.88,116.42 L726.55,116.42 L727.22,116.42 L727.89,116.42 L728.56,116.42 L729.23,116.42 L729.90,116.42 L730.57,116.42 L731.24,116.42 L731.91,116.42 L732.58,116.42 L733.25,116.42 L733.92,116.42 L734.60,116.42 L735.27,116.42 L735.94,116.42 L736.61,116.42 L737.28,116.42 L737.95,116.42 L738.62,116.42 L739.29,116.42 L739.96,116.42 L740.63,116.42 L741.30,116.42 L741.97,116.42 L742.65,116.42 L743.32,116.42 L743.99,116.42 L744.66,116.42 L745.33,116.42 L746.00,116.42 " fill="none" stroke="#9aa3ad" stroke-width="1.8"/><text x="742" y="80" font-size="9" fill="#9aa3ad" text-anchor="end">naive restart (v = 0)</text><path d="M424.00,157.92 L424.67,156.78 L425.34,155.62 L426.01,154.46 L426.68,153.29 L427.35,152.10 L428.02,150.91 L428.70,149.70 L429.37,148.49 L430.04,147.26 L430.71,146.03 L431.38,144.79 L432.05,143.53 L432.72,142.27 L433.39,141.00 L434.06,139.72 L434.73,138.43 L435.40,137.14 L436.08,135.84 L436.75,134.53 L437.42,133.22 L438.09,131.90 L438.76,130.58 L439.43,129.26 L440.10,127.93 L440.77,126.60 L441.44,125.26 L442.11,123.93 L442.78,122.60 L443.45,121.27 L444.12,119.94 L444.80,118.61 L445.47,117.29 L446.14,115.98 L446.81,114.67 L447.48,113.37 L448.15,112.08 L448.82,110.80 L449.49,109.53 L450.16,108.28 L450.83,107.04 L451.50,105.82 L452.17,104.62 L452.85,103.44 L453.52,102.28 L454.19,101.15 L454.86,100.04 L455.53,98.96 L456.20,97.90 L456.87,96.88 L457.54,95.89 L458.21,94.94 L458.88,94.02 L459.55,93.14 L460.23,92.30 L460.90,91.50 L461.57,90.75 L462.24,90.03 L462.91,89.37 L463.58,88.75 L464.25,157.92 L464.92,158.12 L465.59,158.33 L466.26,158.53 L466.93,158.74 L467.60,158.95 L468.27,159.17 L468.95,159.38 L469.62,159.60 L470.29,159.82 L470.96,160.04 L471.63,160.26 L472.30,160.48 L472.97,160.71 L473.64,160.94 L474.31,161.16 L474.98,161.39 L475.65,161.62 L476.33,161.86 L477.00,162.09 L477.67,162.32 L478.34,162.56 L479.01,162.79 L479.68,163.03 L480.35,163.27 L481.02,163.51 L481.69,163.74 L482.36,163.98 L483.03,164.22 L483.70,164.46 L484.38,164.69 L485.05,164.93 L485.72,165.17 L486.39,165.40 L487.06,165.63 L487.73,165.87 L488.40,166.10 L489.07,166.32 L489.74,166.55 L490.41,166.77 L491.08,166.99 L491.75,167.21 L492.42,167.43 L493.10,167.64 L493.77,167.84 L494.44,168.05 L495.11,168.24 L495.78,168.44 L496.45,168.62 L497.12,168.81 L497.79,168.98 L498.46,169.15 L499.13,169.32 L499.80,169.47 L500.47,169.62 L501.15,169.77 L501.82,169.90 L502.49,170.03 L503.16,170.15 L503.83,170.26 L504.50,170.36 L505.17,170.45 L505.84,170.54 L506.51,170.61 L507.18,170.67 L507.85,170.73 L508.52,170.77 L509.20,170.81 L509.87,157.92 L510.54,157.00 L511.21,156.07 L511.88,155.13 L512.55,154.18 L513.22,153.23 L513.89,152.27 L514.56,151.29 L515.23,150.31 L515.90,149.33 L516.58,148.33 L517.25,147.33 L517.92,146.32 L518.59,145.30 L519.26,144.27 L519.93,143.24 L520.60,142.21 L521.27,141.16 L521.94,140.11 L522.61,139.06 L523.28,138.00 L523.95,136.94 L524.62,135.87 L525.30,134.80 L525.97,133.73 L526.64,132.66 L527.31,131.59 L527.98,130.51 L528.65,129.44 L529.32,128.36 L529.99,127.29 L530.66,126.22 L531.33,125.16 L532.00,124.10 L532.67,123.04 L533.35,121.99 L534.02,120.95 L534.69,119.92 L535.36,118.90 L536.03,117.89 L536.70,116.89 L537.37,115.91 L538.04,114.94 L538.71,113.99 L539.38,113.05 L540.05,112.14 L540.72,111.24 L541.40,110.37 L542.07,109.52 L542.74,108.70 L543.41,107.90 L544.08,107.13 L544.75,106.39 L545.42,105.68 L546.09,105.00 L546.76,104.36 L547.43,103.75 L548.10,103.18 L548.78,102.64 L549.45,102.14 L550.12,101.68 L550.79,101.26 L551.46,100.89 L552.13,100.55 L552.80,100.26 L553.47,100.01 L554.14,99.81 L554.81,99.65 L555.48,99.54 L556.15,99.47 L556.83,99.44 L557.50,99.47 L558.17,99.54 L558.84,99.65 L559.51,99.81 L560.18,100.01 L560.85,100.26 L561.52,100.55 L562.19,100.89 L562.86,101.26 L563.53,101.68 L564.20,102.14 L564.88,102.64 L565.55,103.18 L566.22,103.75 L566.89,104.36 L567.56,105.00 L568.23,105.68 L568.90,106.39 L569.57,107.13 L570.24,107.90 L570.91,108.70 L571.58,157.92 L572.25,158.26 L572.92,158.61 L573.60,158.96 L574.27,159.32 L574.94,159.67 L575.61,160.03 L576.28,160.40 L576.95,160.77 L577.62,161.14 L578.29,161.51 L578.96,161.89 L579.63,162.26 L580.30,162.65 L580.97,163.03 L581.65,163.42 L582.32,163.81 L582.99,164.20 L583.66,164.59 L584.33,164.98 L585.00,165.38 L585.67,165.78 L586.34,166.18 L587.01,166.58 L587.68,166.98 L588.35,167.38 L589.03,167.79 L589.70,168.19 L590.37,168.59 L591.04,168.99 L591.71,169.40 L592.38,169.80 L593.05,170.20 L593.72,170.59 L594.39,170.99 L595.06,171.38 L595.73,171.77 L596.40,172.16 L597.07,172.54 L597.75,172.92 L598.42,173.29 L599.09,173.66 L599.76,174.03 L600.43,174.38 L601.10,174.73 L601.77,175.08 L602.44,175.41 L603.11,175.74 L603.78,176.06 L604.45,176.37 L605.12,176.66 L605.80,176.95 L606.47,177.23 L607.14,177.50 L607.81,177.75 L608.48,177.99 L609.15,178.22 L609.82,178.44 L610.49,178.64 L611.16,178.82 L611.83,179.00 L612.50,179.15 L613.17,179.29 L613.85,179.42 L614.52,179.53 L615.19,179.62 L615.86,179.70 L616.53,179.76 L617.20,179.80 L617.87,179.83 L618.54,179.83 L619.21,179.83 L619.88,179.80 L620.55,179.76 L621.22,179.70 L621.90,179.62 L622.57,179.53 L623.24,179.42 L623.91,179.29 L624.58,179.15 L625.25,179.00 L625.92,178.82 L626.59,178.64 L627.26,178.44 L627.93,178.22 L628.60,177.99 L629.28,177.75 L629.95,177.50 L630.62,177.23 L631.29,176.95 L631.96,176.66 L632.63,176.37 L633.30,176.06 L633.97,175.74 L634.64,175.41 L635.31,175.08 L635.98,174.73 L636.65,174.38 L637.32,174.03 L638.00,173.66 L638.67,173.29 L639.34,172.92 L640.01,172.54 L640.68,172.16 L641.35,171.77 L642.02,171.38 L642.69,170.99 L643.36,170.59 L644.03,170.20 L644.70,169.80 L645.38,169.40 L646.05,168.99 L646.72,168.59 L647.39,168.19 L648.06,167.79 L648.73,167.38 L649.40,166.98 L650.07,166.58 L650.74,166.18 L651.41,165.78 L652.08,165.38 L652.75,164.98 L653.42,164.59 L654.10,164.20 L654.77,163.81 L655.44,163.42 L656.11,163.03 L656.78,162.65 L657.45,162.26 L658.12,161.89 L658.79,161.51 L659.46,161.14 L660.13,160.77 L660.80,160.40 L661.47,160.03 L662.15,159.67 L662.82,159.32 L663.49,158.96 L664.16,158.61 L664.83,158.26 L665.50,157.92 L666.17,157.92 L666.84,157.92 L667.51,157.92 L668.18,157.92 L668.85,157.92 L669.53,157.92 L670.20,157.92 L670.87,157.92 L671.54,157.92 L672.21,157.92 L672.88,157.92 L673.55,157.92 L674.22,157.92 L674.89,157.92 L675.56,157.92 L676.23,157.92 L676.90,157.92 L677.57,157.92 L678.25,157.92 L678.92,157.92 L679.59,157.92 L680.26,157.92 L680.93,157.92 L681.60,157.92 L682.27,157.92 L682.94,157.92 L683.61,157.92 L684.28,157.92 L684.95,157.92 L685.62,157.92 L686.30,157.92 L686.97,157.92 L687.64,157.92 L688.31,157.92 L688.98,157.92 L689.65,157.92 L690.32,157.92 L690.99,157.92 L691.66,157.92 L692.33,157.92 L693.00,157.92 L693.67,157.92 L694.35,157.92 L695.02,157.92 L695.69,157.92 L696.36,157.92 L697.03,157.92 L697.70,157.92 L698.37,157.92 L699.04,157.92 L699.71,157.92 L700.38,157.92 L701.05,157.92 L701.72,157.92 L702.40,157.92 L703.07,157.92 L703.74,157.92 L704.41,157.92 L705.08,157.92 L705.75,157.92 L706.42,157.92 L707.09,157.92 L707.76,157.92 L708.43,157.92 L709.10,157.92 L709.78,157.92 L710.45,157.92 L711.12,157.92 L711.79,157.92 L712.46,157.92 L713.13,157.92 L713.80,157.92 L714.47,157.92 L715.14,157.92 L715.81,157.92 L716.48,157.92 L717.15,157.92 L717.82,157.92 L718.50,157.92 L719.17,157.92 L719.84,157.92 L720.51,157.92 L721.18,157.92 L721.85,157.92 L722.52,157.92 L723.19,157.92 L723.86,157.92 L724.53,157.92 L725.20,157.92 L725.88,157.92 L726.55,157.92 L727.22,157.92 L727.89,157.92 L728.56,157.92 L729.23,157.92 L729.90,157.92 L730.57,157.92 L731.24,157.92 L731.91,157.92 L732.58,157.92 L733.25,157.92 L733.92,157.92 L734.60,157.92 L735.27,157.92 L735.94,157.92 L736.61,157.92 L737.28,157.92 L737.95,157.92 L738.62,157.92 L739.29,157.92 L739.96,157.92 L740.63,157.92 L741.30,157.92 L741.97,157.92 L742.65,157.92 L743.32,157.92 L743.99,157.92 L744.66,157.92 L745.33,157.92 L746.00,157.92 " fill="none" stroke="#9aa3ad" stroke-width="1.8" stroke-dasharray="4 3"/><path d="M424.00,157.92 L424.67,157.91 L425.34,157.89 L426.01,157.86 L426.68,157.81 L427.35,157.75 L428.02,157.67 L428.70,157.58 L429.37,157.48 L430.04,157.36 L430.71,157.23 L431.38,157.08 L432.05,156.92 L432.72,156.74 L433.39,156.55 L434.06,156.35 L434.73,156.12 L435.40,155.89 L436.08,155.64 L436.75,155.37 L437.42,155.09 L438.09,154.79 L438.76,154.48 L439.43,154.15 L440.10,153.80 L440.77,153.44 L441.44,153.07 L442.11,152.68 L442.78,152.27 L443.45,151.85 L444.12,151.41 L444.80,150.95 L445.47,150.48 L446.14,150.00 L446.81,149.50 L447.48,148.98 L448.15,148.45 L448.82,147.91 L449.49,147.35 L450.16,146.77 L450.83,146.18 L451.50,145.57 L452.17,144.96 L452.85,144.32 L453.52,143.68 L454.19,143.02 L454.86,142.34 L455.53,141.66 L456.20,140.96 L456.87,140.25 L457.54,139.52 L458.21,138.79 L458.88,138.04 L459.55,137.29 L460.23,136.52 L460.90,135.75 L461.57,134.96 L462.24,134.17 L462.91,133.37 L463.58,132.56 L464.25,131.74 L464.92,130.92 L465.59,130.11 L466.26,129.31 L466.93,128.51 L467.60,127.71 L468.27,126.93 L468.95,126.15 L469.62,125.39 L470.29,124.63 L470.96,123.88 L471.63,123.15 L472.30,122.43 L472.97,121.72 L473.64,121.02 L474.31,120.34 L474.98,119.68 L475.65,119.03 L476.33,118.40 L477.00,117.78 L477.67,117.19 L478.34,116.61 L479.01,116.05 L479.68,115.51 L480.35,115.00 L481.02,114.50 L481.69,114.02 L482.36,113.57 L483.03,113.14 L483.70,112.73 L484.38,112.35 L485.05,111.99 L485.72,111.66 L486.39,111.35 L487.06,111.06 L487.73,110.80 L488.40,110.56 L489.07,110.35 L489.74,110.17 L490.41,110.01 L491.08,109.88 L491.75,109.77 L492.42,109.69 L493.10,109.64 L493.77,109.61 L494.44,109.60 L495.11,109.63 L495.78,109.68 L496.45,109.75 L497.12,109.85 L497.79,109.97 L498.46,110.12 L499.13,110.30 L499.80,110.49 L500.47,110.72 L501.15,110.96 L501.82,111.23 L502.49,111.52 L503.16,111.83 L503.83,112.16 L504.50,112.52 L505.17,112.89 L505.84,113.29 L506.51,113.70 L507.18,114.14 L507.85,114.59 L508.52,115.06 L509.20,115.55 L509.87,116.05 L510.54,116.56 L511.21,117.08 L511.88,117.60 L512.55,118.12 L513.22,118.64 L513.89,119.16 L514.56,119.68 L515.23,120.20 L515.90,120.72 L516.58,121.23 L517.25,121.74 L517.92,122.25 L518.59,122.74 L519.26,123.22 L519.93,123.67 L520.60,124.11 L521.27,124.52 L521.94,124.92 L522.61,125.29 L523.28,125.64 L523.95,125.97 L524.62,126.27 L525.30,126.55 L525.97,126.81 L526.64,127.05 L527.31,127.26 L527.98,127.45 L528.65,127.61 L529.32,127.74 L529.99,127.86 L530.66,127.94 L531.33,128.00 L532.00,128.04 L532.67,128.05 L533.35,128.03 L534.02,127.99 L534.69,127.93 L535.36,127.83 L536.03,127.72 L536.70,127.57 L537.37,127.40 L538.04,127.21 L538.71,126.99 L539.38,126.75 L540.05,126.48 L540.72,126.19 L541.40,125.87 L542.07,125.53 L542.74,125.16 L543.41,124.78 L544.08,124.37 L544.75,123.93 L545.42,123.48 L546.09,123.00 L546.76,122.51 L547.43,121.99 L548.10,121.45 L548.78,120.90 L549.45,120.32 L550.12,119.73 L550.79,119.12 L551.46,118.49 L552.13,117.85 L552.80,117.19 L553.47,116.51 L554.14,115.82 L554.81,115.12 L555.48,114.40 L556.15,113.68 L556.83,112.94 L557.50,112.19 L558.17,111.43 L558.84,110.66 L559.51,109.90 L560.18,109.14 L560.85,108.38 L561.52,107.63 L562.19,106.88 L562.86,106.13 L563.53,105.39 L564.20,104.66 L564.88,103.93 L565.55,103.21 L566.22,102.49 L566.89,101.79 L567.56,101.09 L568.23,100.40 L568.90,99.72 L569.57,99.05 L570.24,98.39 L570.91,97.74 L571.58,97.10 L572.25,96.47 L572.92,95.86 L573.60,95.28 L574.27,94.70 L574.94,94.15 L575.61,93.62 L576.28,93.11 L576.95,92.62 L577.62,92.14 L578.29,91.69 L578.96,91.26 L579.63,90.85 L580.30,90.46 L580.97,90.09 L581.65,89.74 L582.32,89.42 L582.99,89.11 L583.66,88.83 L584.33,88.57 L585.00,88.33 L585.67,88.11 L586.34,87.92 L587.01,87.74 L587.68,87.59 L588.35,87.46 L589.03,87.35 L589.70,87.27 L590.37,87.20 L591.04,87.16 L591.71,87.14 L592.38,87.14 L593.05,87.16 L593.72,87.21 L594.39,87.27 L595.06,87.36 L595.73,87.46 L596.40,87.59 L597.07,87.74 L597.75,87.91 L598.42,88.10 L599.09,88.31 L599.76,88.53 L600.43,88.78 L601.10,89.05 L601.77,89.34 L602.44,89.64 L603.11,89.97 L603.78,90.31 L604.45,90.67 L605.12,91.03 L605.80,91.40 L606.47,91.77 L607.14,92.15 L607.81,92.53 L608.48,92.92 L609.15,93.31 L609.82,93.71 L610.49,94.11 L611.16,94.51 L611.83,94.92 L612.50,95.33 L613.17,95.75 L613.85,96.16 L614.52,96.58 L615.19,97.00 L615.86,97.42 L616.53,97.85 L617.20,98.27 L617.87,98.70 L618.54,99.12 L619.21,99.55 L619.88,99.98 L620.55,100.40 L621.22,100.83 L621.90,101.25 L622.57,101.67 L623.24,102.09 L623.91,102.50 L624.58,102.92 L625.25,103.33 L625.92,103.74 L626.59,104.14 L627.26,104.54 L627.93,104.94 L628.60,105.33 L629.28,105.72 L629.95,106.10 L630.62,106.48 L631.29,106.85 L631.96,107.22 L632.63,107.58 L633.30,107.94 L633.97,108.29 L634.64,108.63 L635.31,108.97 L635.98,109.30 L636.65,109.62 L637.32,109.94 L638.00,110.25 L638.67,110.55 L639.34,110.84 L640.01,111.13 L640.68,111.41 L641.35,111.68 L642.02,111.95 L642.69,112.21 L643.36,112.46 L644.03,112.70 L644.70,112.94 L645.38,113.16 L646.05,113.38 L646.72,113.59 L647.39,113.80 L648.06,113.99 L648.73,114.18 L649.40,114.36 L650.07,114.53 L650.74,114.70 L651.41,114.85 L652.08,115.00 L652.75,115.14 L653.42,115.28 L654.10,115.40 L654.77,115.52 L655.44,115.63 L656.11,115.73 L656.78,115.83 L657.45,115.92 L658.12,116.00 L658.79,116.07 L659.46,116.14 L660.13,116.20 L660.80,116.25 L661.47,116.29 L662.15,116.33 L662.82,116.36 L663.49,116.39 L664.16,116.40 L664.83,116.41 L665.50,116.42 L666.17,116.42 L666.84,116.42 L667.51,116.42 L668.18,116.42 L668.85,116.42 L669.53,116.42 L670.20,116.42 L670.87,116.42 L671.54,116.42 L672.21,116.42 L672.88,116.42 L673.55,116.42 L674.22,116.42 L674.89,116.42 L675.56,116.42 L676.23,116.42 L676.90,116.42 L677.57,116.42 L678.25,116.42 L678.92,116.42 L679.59,116.42 L680.26,116.42 L680.93,116.42 L681.60,116.42 L682.27,116.42 L682.94,116.42 L683.61,116.42 L684.28,116.42 L684.95,116.42 L685.62,116.42 L686.30,116.42 L686.97,116.42 L687.64,116.42 L688.31,116.42 L688.98,116.42 L689.65,116.42 L690.32,116.42 L690.99,116.42 L691.66,116.42 L692.33,116.42 L693.00,116.42 L693.67,116.42 L694.35,116.42 L695.02,116.42 L695.69,116.42 L696.36,116.42 L697.03,116.42 L697.70,116.42 L698.37,116.42 L699.04,116.42 L699.71,116.42 L700.38,116.42 L701.05,116.42 L701.72,116.42 L702.40,116.42 L703.07,116.42 L703.74,116.42 L704.41,116.42 L705.08,116.42 L705.75,116.42 L706.42,116.42 L707.09,116.42 L707.76,116.42 L708.43,116.42 L709.10,116.42 L709.78,116.42 L710.45,116.42 L711.12,116.42 L711.79,116.42 L712.46,116.42 L713.13,116.42 L713.80,116.42 L714.47,116.42 L715.14,116.42 L715.81,116.42 L716.48,116.42 L717.15,116.42 L717.82,116.42 L718.50,116.42 L719.17,116.42 L719.84,116.42 L720.51,116.42 L721.18,116.42 L721.85,116.42 L722.52,116.42 L723.19,116.42 L723.86,116.42 L724.53,116.42 L725.20,116.42 L725.88,116.42 L726.55,116.42 L727.22,116.42 L727.89,116.42 L728.56,116.42 L729.23,116.42 L729.90,116.42 L730.57,116.42 L731.24,116.42 L731.91,116.42 L732.58,116.42 L733.25,116.42 L733.92,116.42 L734.60,116.42 L735.27,116.42 L735.94,116.42 L736.61,116.42 L737.28,116.42 L737.95,116.42 L738.62,116.42 L739.29,116.42 L739.96,116.42 L740.63,116.42 L741.30,116.42 L741.97,116.42 L742.65,116.42 L743.32,116.42 L743.99,116.42 L744.66,116.42 L745.33,116.42 L746.00,116.42 " fill="none" stroke="#2f6fec" stroke-width="1.8"/><text x="742" y="104" font-size="9" fill="#2f6fec" text-anchor="end">position</text><path d="M424.00,157.92 L424.67,156.79 L425.34,155.64 L426.01,154.49 L426.68,153.33 L427.35,152.15 L428.02,150.97 L428.70,149.77 L429.37,148.57 L430.04,147.35 L430.71,146.13 L431.38,144.89 L432.05,143.65 L432.72,142.40 L433.39,141.14 L434.06,139.87 L434.73,138.59 L435.40,137.31 L436.08,136.02 L436.75,134.72 L437.42,133.42 L438.09,132.12 L438.76,130.80 L439.43,129.49 L440.10,128.17 L440.77,126.85 L441.44,125.53 L442.11,124.21 L442.78,122.89 L443.45,121.57 L444.12,120.25 L444.80,118.93 L445.47,117.62 L446.14,116.32 L446.81,115.02 L447.48,113.73 L448.15,112.45 L448.82,111.18 L449.49,109.93 L450.16,108.68 L450.83,107.46 L451.50,106.25 L452.17,105.06 L452.85,103.89 L453.52,102.74 L454.19,101.61 L454.86,100.51 L455.53,99.44 L456.20,98.39 L456.87,97.38 L457.54,96.40 L458.21,95.45 L458.88,94.54 L459.55,93.67 L460.23,92.84 L460.90,92.04 L461.57,91.29 L462.24,90.59 L462.91,89.93 L463.58,89.31 L464.25,88.75 L464.92,89.14 L465.59,89.59 L466.26,90.10 L466.93,90.67 L467.60,91.31 L468.27,92.00 L468.95,92.77 L469.62,93.59 L470.29,94.48 L470.96,95.43 L471.63,96.44 L472.30,97.52 L472.97,98.66 L473.64,99.87 L474.31,101.13 L474.98,102.46 L475.65,103.84 L476.33,105.29 L477.00,106.79 L477.67,108.35 L478.34,109.96 L479.01,111.62 L479.68,113.33 L480.35,115.09 L481.02,116.90 L481.69,118.75 L482.36,120.64 L483.03,122.57 L483.70,124.53 L484.38,126.54 L485.05,128.57 L485.72,130.63 L486.39,132.72 L487.06,134.83 L487.73,136.96 L488.40,139.11 L489.07,141.27 L489.74,143.45 L490.41,145.63 L491.08,147.82 L491.75,150.02 L492.42,152.21 L493.10,154.41 L493.77,156.60 L494.44,158.78 L495.11,160.94 L495.78,163.10 L496.45,165.24 L497.12,167.36 L497.79,169.46 L498.46,171.54 L499.13,173.58 L499.80,175.61 L500.47,177.59 L501.15,179.55 L501.82,181.47 L502.49,183.35 L503.16,185.20 L503.83,187.00 L504.50,188.76 L505.17,190.47 L505.84,192.14 L506.51,193.76 L507.18,195.33 L507.85,196.85 L508.52,198.32 L509.20,199.73 L509.87,201.10 L510.54,201.39 L511.21,201.62 L511.88,201.78 L512.55,201.88 L513.22,201.92 L513.89,201.89 L514.56,201.80 L515.23,201.64 L515.90,201.43 L516.58,201.15 L517.25,200.81 L517.92,200.41 L518.59,198.83 L519.26,197.21 L519.93,195.54 L520.60,193.82 L521.27,192.07 L521.94,190.27 L522.61,188.44 L523.28,186.57 L523.95,184.67 L524.62,182.73 L525.30,180.76 L525.97,178.76 L526.64,176.74 L527.31,174.69 L527.98,172.62 L528.65,170.53 L529.32,168.43 L529.99,166.30 L530.66,164.17 L531.33,162.02 L532.00,159.86 L532.67,157.70 L533.35,155.54 L534.02,153.37 L534.69,151.20 L535.36,149.04 L536.03,146.89 L536.70,144.74 L537.37,142.60 L538.04,140.48 L538.71,138.37 L539.38,136.28 L540.05,134.21 L540.72,132.16 L541.40,130.14 L542.07,128.14 L542.74,126.18 L543.41,124.24 L544.08,122.34 L544.75,120.48 L545.42,118.65 L546.09,116.86 L546.76,115.12 L547.43,113.41 L548.10,111.76 L548.78,110.15 L549.45,108.59 L550.12,107.08 L550.79,105.62 L551.46,104.22 L552.13,102.87 L552.80,101.57 L553.47,100.33 L554.14,99.15 L554.81,98.03 L555.48,96.96 L556.15,95.96 L556.83,95.01 L557.50,94.12 L558.17,93.29 L558.84,93.42 L559.51,93.59 L560.18,93.82 L560.85,94.09 L561.52,94.42 L562.19,94.79 L562.86,95.20 L563.53,95.67 L564.20,96.17 L564.88,96.73 L565.55,97.32 L566.22,97.96 L566.89,98.63 L567.56,99.34 L568.23,100.09 L568.90,100.88 L569.57,101.70 L570.24,102.55 L570.91,103.43 L571.58,104.35 L572.25,105.85 L572.92,107.39 L573.60,108.96 L574.27,110.55 L574.94,112.17 L575.61,113.82 L576.28,115.49 L576.95,117.18 L577.62,118.89 L578.29,120.62 L578.96,122.37 L579.63,124.13 L580.30,125.91 L580.97,127.70 L581.65,129.50 L582.32,131.31 L582.99,133.13 L583.66,134.96 L584.33,136.80 L585.00,138.64 L585.67,140.48 L586.34,142.32 L587.01,144.17 L587.68,146.02 L588.35,147.86 L589.03,149.71 L589.70,151.55 L590.37,153.39 L591.04,155.22 L591.71,157.04 L592.38,158.86 L593.05,160.67 L593.72,162.47 L594.39,164.26 L595.06,166.04 L595.73,167.81 L596.40,169.56 L597.07,171.30 L597.75,173.02 L598.42,174.73 L599.09,176.42 L599.76,178.09 L600.43,179.74 L601.10,181.37 L601.77,182.99 L602.44,184.57 L603.11,186.14 L603.78,187.68 L604.45,188.18 L605.12,188.67 L605.80,189.15 L606.47,189.60 L607.14,190.04 L607.81,190.46 L608.48,190.85 L609.15,191.23 L609.82,191.58 L610.49,191.91 L611.16,192.22 L611.83,192.50 L612.50,192.76 L613.17,192.99 L613.85,193.20 L614.52,193.37 L615.19,193.53 L615.86,193.65 L616.53,193.75 L617.20,193.82 L617.87,193.86 L618.54,193.88 L619.21,193.86 L619.88,193.82 L620.55,193.75 L621.22,193.65 L621.90,193.53 L622.57,193.37 L623.24,193.20 L623.91,192.99 L624.58,192.76 L625.25,192.50 L625.92,192.22 L626.59,191.91 L627.26,191.58 L627.93,191.23 L628.60,190.85 L629.28,190.46 L629.95,190.04 L630.62,189.60 L631.29,189.15 L631.96,188.67 L632.63,188.18 L633.30,187.68 L633.97,187.16 L634.64,186.62 L635.31,186.07 L635.98,185.51 L636.65,184.93 L637.32,184.35 L638.00,183.75 L638.67,183.15 L639.34,182.53 L640.01,181.91 L640.68,181.28 L641.35,180.65 L642.02,180.01 L642.69,179.36 L643.36,178.72 L644.03,178.06 L644.70,177.41 L645.38,176.75 L646.05,176.09 L646.72,175.43 L647.39,174.77 L648.06,174.11 L648.73,173.45 L649.40,172.79 L650.07,172.13 L650.74,171.47 L651.41,170.82 L652.08,170.16 L652.75,169.51 L653.42,168.86 L654.10,168.22 L654.77,167.58 L655.44,166.94 L656.11,166.31 L656.78,165.68 L657.45,165.05 L658.12,164.43 L658.79,163.81 L659.46,163.20 L660.13,162.59 L660.80,161.99 L661.47,161.39 L662.15,160.80 L662.82,160.21 L663.49,159.63 L664.16,159.05 L664.83,158.48 L665.50,157.92 L666.17,157.92 L666.84,157.92 L667.51,157.92 L668.18,157.92 L668.85,157.92 L669.53,157.92 L670.20,157.92 L670.87,157.92 L671.54,157.92 L672.21,157.92 L672.88,157.92 L673.55,157.92 L674.22,157.92 L674.89,157.92 L675.56,157.92 L676.23,157.92 L676.90,157.92 L677.57,157.92 L678.25,157.92 L678.92,157.92 L679.59,157.92 L680.26,157.92 L680.93,157.92 L681.60,157.92 L682.27,157.92 L682.94,157.92 L683.61,157.92 L684.28,157.92 L684.95,157.92 L685.62,157.92 L686.30,157.92 L686.97,157.92 L687.64,157.92 L688.31,157.92 L688.98,157.92 L689.65,157.92 L690.32,157.92 L690.99,157.92 L691.66,157.92 L692.33,157.92 L693.00,157.92 L693.67,157.92 L694.35,157.92 L695.02,157.92 L695.69,157.92 L696.36,157.92 L697.03,157.92 L697.70,157.92 L698.37,157.92 L699.04,157.92 L699.71,157.92 L700.38,157.92 L701.05,157.92 L701.72,157.92 L702.40,157.92 L703.07,157.92 L703.74,157.92 L704.41,157.92 L705.08,157.92 L705.75,157.92 L706.42,157.92 L707.09,157.92 L707.76,157.92 L708.43,157.92 L709.10,157.92 L709.78,157.92 L710.45,157.92 L711.12,157.92 L711.79,157.92 L712.46,157.92 L713.13,157.92 L713.80,157.92 L714.47,157.92 L715.14,157.92 L715.81,157.92 L716.48,157.92 L717.15,157.92 L717.82,157.92 L718.50,157.92 L719.17,157.92 L719.84,157.92 L720.51,157.92 L721.18,157.92 L721.85,157.92 L722.52,157.92 L723.19,157.92 L723.86,157.92 L724.53,157.92 L725.20,157.92 L725.88,157.92 L726.55,157.92 L727.22,157.92 L727.89,157.92 L728.56,157.92 L729.23,157.92 L729.90,157.92 L730.57,157.92 L731.24,157.92 L731.91,157.92 L732.58,157.92 L733.25,157.92 L733.92,157.92 L734.60,157.92 L735.27,157.92 L735.94,157.92 L736.61,157.92 L737.28,157.92 L737.95,157.92 L738.62,157.92 L739.29,157.92 L739.96,157.92 L740.63,157.92 L741.30,157.92 L741.97,157.92 L742.65,157.92 L743.32,157.92 L743.99,157.92 L744.66,157.92 L745.33,157.92 L746.00,157.92 " fill="none" stroke="#e8833a" stroke-width="1.8" stroke-dasharray="4 3"/><text x="742" y="116" font-size="9" fill="#e8833a" text-anchor="end">velocity</text><rect x="804" y="68" width="322" height="166" fill="#fafbfc" stroke="#e3e6ea"/><text x="804" y="59" font-size="12" font-weight="600" fill="#333">spring, bounce .3</text><line x1="804" x2="1126" y1="157.91667" y2="157.91667" stroke="#d5d9de" stroke-dasharray="3 3"/><text x="800" y="160.91667" font-size="9" fill="#888" text-anchor="end">0</text><line x1="804" x2="1126" y1="88.750015" y2="88.750015" stroke="#d5d9de" stroke-dasharray="3 3"/><text x="800" y="91.750015" font-size="9" fill="#888" text-anchor="end">1</text><text x="1126" y="248" font-size="9" fill="#888" text-anchor="end">1.20 s</text><line x1="844.25" x2="844.25" y1="68" y2="234" stroke="#d64545" stroke-width="1" stroke-dasharray="2 3"/><line x1="889.86664" x2="889.86664" y1="68" y2="234" stroke="#d64545" stroke-width="1" stroke-dasharray="2 3"/><line x1="951.5833" x2="951.5833" y1="68" y2="234" stroke="#d64545" stroke-width="1" stroke-dasharray="2 3"/><path d="M804.00,157.92 L804.67,157.86 L805.34,157.71 L806.01,157.46 L806.68,157.12 L807.35,156.70 L808.03,156.20 L808.70,155.62 L809.37,154.98 L810.04,154.27 L810.71,153.50 L811.38,152.67 L812.05,151.79 L812.72,150.86 L813.39,149.89 L814.06,148.88 L814.73,147.84 L815.40,146.76 L816.08,145.65 L816.75,144.52 L817.42,143.36 L818.09,142.18 L818.76,140.99 L819.43,139.78 L820.10,138.56 L820.77,137.33 L821.44,136.09 L822.11,134.85 L822.78,133.61 L823.45,132.36 L824.12,131.12 L824.80,129.87 L825.47,128.64 L826.14,127.41 L826.81,126.19 L827.48,124.97 L828.15,123.77 L828.82,122.58 L829.49,121.40 L830.16,120.24 L830.83,119.09 L831.50,117.96 L832.17,116.84 L832.85,115.74 L833.52,114.66 L834.19,113.60 L834.86,112.56 L835.53,111.54 L836.20,110.53 L836.87,109.55 L837.54,108.59 L838.21,107.66 L838.88,106.74 L839.55,105.85 L840.22,104.97 L840.90,104.13 L841.57,103.30 L842.24,102.49 L842.91,101.71 L843.58,100.95 L844.25,100.21 L844.92,100.25 L845.59,100.34 L846.26,100.50 L846.93,100.72 L847.60,100.98 L848.28,101.30 L848.95,101.67 L849.62,102.08 L850.29,102.53 L850.96,103.02 L851.63,103.54 L852.30,104.10 L852.97,104.69 L853.64,105.30 L854.31,105.94 L854.98,106.61 L855.65,107.29 L856.33,107.99 L857.00,108.71 L857.67,109.45 L858.34,110.19 L859.01,110.95 L859.68,111.72 L860.35,112.49 L861.02,113.27 L861.69,114.06 L862.36,114.84 L863.03,115.63 L863.70,116.42 L864.38,117.21 L865.05,118.00 L865.72,118.78 L866.39,119.56 L867.06,120.34 L867.73,121.11 L868.40,121.87 L869.07,122.63 L869.74,123.37 L870.41,124.11 L871.08,124.84 L871.75,125.56 L872.42,126.27 L873.10,126.96 L873.77,127.65 L874.44,128.32 L875.11,128.98 L875.78,129.63 L876.45,130.27 L877.12,130.89 L877.79,131.50 L878.46,132.09 L879.13,132.67 L879.80,133.24 L880.47,133.79 L881.15,134.33 L881.82,134.86 L882.49,135.37 L883.16,135.86 L883.83,136.34 L884.50,136.81 L885.17,137.27 L885.84,137.71 L886.51,138.13 L887.18,138.54 L887.85,138.94 L888.53,139.33 L889.20,139.70 L889.87,140.05 L890.54,140.01 L891.21,139.88 L891.88,139.67 L892.55,139.39 L893.22,139.03 L893.89,138.61 L894.56,138.12 L895.23,137.58 L895.90,136.98 L896.58,136.33 L897.25,135.64 L897.92,134.90 L898.59,134.12 L899.26,133.30 L899.93,132.45 L900.60,131.57 L901.27,130.66 L901.94,129.73 L902.61,128.78 L903.28,127.80 L903.95,126.81 L904.62,125.81 L905.30,124.79 L905.97,123.76 L906.64,122.73 L907.31,121.68 L907.98,120.64 L908.65,119.59 L909.32,118.54 L909.99,117.50 L910.66,116.45 L911.33,115.41 L912.00,114.37 L912.67,113.34 L913.35,112.32 L914.02,111.31 L914.69,110.31 L915.36,109.32 L916.03,108.34 L916.70,107.37 L917.37,106.42 L918.04,105.48 L918.71,104.55 L919.38,103.64 L920.05,102.75 L920.72,101.87 L921.40,101.01 L922.07,100.17 L922.74,99.34 L923.41,98.54 L924.08,97.75 L924.75,96.98 L925.42,96.22 L926.09,95.49 L926.76,94.78 L927.43,94.08 L928.10,93.40 L928.78,92.74 L929.45,92.10 L930.12,91.48 L930.79,90.88 L931.46,90.30 L932.13,89.73 L932.80,89.19 L933.47,88.66 L934.14,88.15 L934.81,87.65 L935.48,87.18 L936.15,86.72 L936.83,86.28 L937.50,85.86 L938.17,85.45 L938.84,85.06 L939.51,84.69 L940.18,84.33 L940.85,83.98 L941.52,83.66 L942.19,83.34 L942.86,83.04 L943.53,82.76 L944.20,82.49 L944.88,82.23 L945.55,81.99 L946.22,81.76 L946.89,81.54 L947.56,81.33 L948.23,81.14 L948.90,80.95 L949.57,80.78 L950.24,80.62 L950.91,80.47 L951.58,80.33 L952.25,80.35 L952.92,80.43 L953.60,80.56 L954.27,80.74 L954.94,80.96 L955.61,81.22 L956.28,81.52 L956.95,81.86 L957.62,82.23 L958.29,82.63 L958.96,83.07 L959.63,83.52 L960.30,84.01 L960.97,84.51 L961.65,85.04 L962.32,85.59 L962.99,86.15 L963.66,86.73 L964.33,87.32 L965.00,87.92 L965.67,88.54 L966.34,89.16 L967.01,89.79 L967.68,90.43 L968.35,91.07 L969.03,91.71 L969.70,92.36 L970.37,93.01 L971.04,93.66 L971.71,94.31 L972.38,94.96 L973.05,95.60 L973.72,96.25 L974.39,96.88 L975.06,97.52 L975.73,98.14 L976.40,98.77 L977.07,99.38 L977.75,99.99 L978.42,100.59 L979.09,101.18 L979.76,101.76 L980.43,102.33 L981.10,102.90 L981.77,103.45 L982.44,103.99 L983.11,104.53 L983.78,105.05 L984.45,105.56 L985.12,106.06 L985.80,106.55 L986.47,107.03 L987.14,107.50 L987.81,107.95 L988.48,108.39 L989.15,108.83 L989.82,109.25 L990.49,109.65 L991.16,110.05 L991.83,110.44 L992.50,110.81 L993.17,111.17 L993.85,111.52 L994.52,111.86 L995.19,112.19 L995.86,112.50 L996.53,112.81 L997.20,113.10 L997.87,113.39 L998.54,113.66 L999.21,113.92 L999.88,114.17 L1000.55,114.42 L1001.22,114.65 L1001.90,114.87 L1002.57,115.08 L1003.24,115.29 L1003.91,115.48 L1004.58,115.67 L1005.25,115.84 L1005.92,116.01 L1006.59,116.17 L1007.26,116.32 L1007.93,116.46 L1008.60,116.60 L1009.28,116.73 L1009.95,116.85 L1010.62,116.96 L1011.29,117.07 L1011.96,117.17 L1012.63,117.26 L1013.30,117.35 L1013.97,117.43 L1014.64,117.51 L1015.31,117.58 L1015.98,117.64 L1016.65,117.70 L1017.32,117.75 L1018.00,117.80 L1018.67,117.85 L1019.34,117.89 L1020.01,117.92 L1020.68,117.95 L1021.35,117.98 L1022.02,118.00 L1022.69,118.02 L1023.36,118.04 L1024.03,118.05 L1024.70,118.06 L1025.38,118.07 L1026.05,118.08 L1026.72,118.08 L1027.39,118.08 L1028.06,118.07 L1028.73,118.07 L1029.40,118.06 L1030.07,118.05 L1030.74,118.04 L1031.41,118.02 L1032.08,118.01 L1032.75,117.99 L1033.43,117.97 L1034.10,117.95 L1034.77,117.93 L1035.44,117.91 L1036.11,117.88 L1036.78,117.86 L1037.45,117.84 L1038.12,117.81 L1038.79,117.78 L1039.46,117.76 L1040.13,117.73 L1040.80,117.70 L1041.47,117.67 L1042.15,117.64 L1042.82,117.61 L1043.49,117.58 L1044.16,117.55 L1044.83,117.52 L1045.50,117.49 L1046.17,117.46 L1046.84,117.43 L1047.51,117.40 L1048.18,117.37 L1048.85,117.34 L1049.53,117.32 L1050.20,117.29 L1050.87,117.26 L1051.54,117.23 L1052.21,117.20 L1052.88,117.17 L1053.55,117.15 L1054.22,117.12 L1054.89,117.09 L1055.56,117.06 L1056.23,117.04 L1056.90,117.01 L1057.57,116.99 L1058.25,116.96 L1058.92,116.94 L1059.59,116.92 L1060.26,116.89 L1060.93,116.87 L1061.60,116.85 L1062.27,116.83 L1062.94,116.81 L1063.61,116.79 L1064.28,116.77 L1064.95,116.75 L1065.62,116.73 L1066.30,116.71 L1066.97,116.69 L1067.64,116.67 L1068.31,116.66 L1068.98,116.64 L1069.65,116.63 L1070.32,116.61 L1070.99,116.60 L1071.66,116.58 L1072.33,116.57 L1073.00,116.56 L1073.68,116.54 L1074.35,116.53 L1075.02,116.52 L1075.69,116.51 L1076.36,116.50 L1077.03,116.49 L1077.70,116.48 L1078.37,116.47 L1079.04,116.46 L1079.71,116.45 L1080.38,116.44 L1081.05,116.44 L1081.72,116.43 L1082.40,116.42 L1083.07,116.41 L1083.74,116.41 L1084.41,116.40 L1085.08,116.40 L1085.75,116.39 L1086.42,116.39 L1087.09,116.38 L1087.76,116.38 L1088.43,116.37 L1089.10,116.37 L1089.78,116.37 L1090.45,116.36 L1091.12,116.36 L1091.79,116.36 L1092.46,116.36 L1093.13,116.35 L1093.80,116.35 L1094.47,116.35 L1095.14,116.35 L1095.81,116.35 L1096.48,116.34 L1097.15,116.34 L1097.82,116.34 L1098.50,116.34 L1099.17,116.34 L1099.84,116.34 L1100.51,116.34 L1101.18,116.34 L1101.85,116.34 L1102.52,116.34 L1103.19,116.34 L1103.86,116.34 L1104.53,116.34 L1105.20,116.34 L1105.88,116.34 L1106.55,116.34 L1107.22,116.34 L1107.89,116.34 L1108.56,116.35 L1109.23,116.35 L1109.90,116.35 L1110.57,116.35 L1111.24,116.35 L1111.91,116.35 L1112.58,116.35 L1113.25,116.35 L1113.93,116.35 L1114.60,116.36 L1115.27,116.36 L1115.94,116.36 L1116.61,116.36 L1117.28,116.36 L1117.95,116.36 L1118.62,116.36 L1119.29,116.36 L1119.96,116.37 L1120.63,116.37 L1121.30,116.37 L1121.97,116.37 L1122.65,116.37 L1123.32,116.37 L1123.99,116.37 L1124.66,116.38 L1125.33,116.38 L1126.00,116.38 " fill="none" stroke="#9aa3ad" stroke-width="1.8"/><text x="1122" y="80" font-size="9" fill="#9aa3ad" text-anchor="end">naive restart (v = 0)</text><path d="M804.00,157.92 L804.67,152.15 L805.34,146.71 L806.01,141.57 L806.68,136.73 L807.35,132.19 L808.03,127.92 L808.70,123.93 L809.37,120.20 L810.04,116.73 L810.71,113.50 L811.38,110.52 L812.05,107.76 L812.72,105.23 L813.39,102.92 L814.06,100.80 L814.73,98.89 L815.40,97.17 L816.08,95.63 L816.75,94.27 L817.42,93.08 L818.09,92.04 L818.76,91.16 L819.43,90.43 L820.10,89.84 L820.77,89.38 L821.44,89.05 L822.11,88.84 L822.78,88.75 L823.45,88.76 L824.12,88.88 L824.80,89.10 L825.47,89.40 L826.14,89.80 L826.81,90.27 L827.48,90.82 L828.15,91.44 L828.82,92.13 L829.49,92.88 L830.16,93.69 L830.83,94.55 L831.50,95.46 L832.17,96.41 L832.85,97.41 L833.52,98.44 L834.19,99.51 L834.86,100.60 L835.53,101.73 L836.20,102.88 L836.87,104.05 L837.54,105.24 L838.21,106.44 L838.88,107.66 L839.55,108.89 L840.22,110.12 L840.90,111.36 L841.57,112.61 L842.24,113.85 L842.91,115.10 L843.58,116.34 L844.25,157.92 L844.92,161.57 L845.59,165.03 L846.26,168.28 L846.93,171.35 L847.60,174.24 L848.28,176.94 L848.95,179.47 L849.62,181.84 L850.29,184.04 L850.96,186.09 L851.63,187.98 L852.30,189.73 L852.97,191.33 L853.64,192.80 L854.31,194.14 L854.98,195.35 L855.65,196.45 L856.33,197.42 L857.00,198.28 L857.67,199.04 L858.34,199.70 L859.01,200.25 L859.68,200.72 L860.35,201.09 L861.02,201.38 L861.69,201.59 L862.36,201.73 L863.03,201.79 L863.70,201.78 L864.38,201.70 L865.05,201.57 L865.72,201.37 L866.39,201.12 L867.06,200.82 L867.73,200.47 L868.40,200.08 L869.07,199.64 L869.74,199.17 L870.41,198.66 L871.08,198.11 L871.75,197.53 L872.42,196.93 L873.10,196.30 L873.77,195.64 L874.44,194.96 L875.11,194.27 L875.78,193.55 L876.45,192.82 L877.12,192.08 L877.79,191.33 L878.46,190.57 L879.13,189.79 L879.80,189.02 L880.47,188.23 L881.15,187.44 L881.82,186.66 L882.49,185.87 L883.16,185.08 L883.83,184.29 L884.50,183.50 L885.17,182.72 L885.84,181.94 L886.51,181.17 L887.18,180.41 L887.85,179.65 L888.53,178.90 L889.20,178.16 L889.87,157.92 L890.54,153.07 L891.21,148.48 L891.88,144.16 L892.55,140.09 L893.22,136.26 L893.89,132.67 L894.56,129.31 L895.23,126.17 L895.90,123.25 L896.58,120.53 L897.25,118.02 L897.92,115.70 L898.59,113.57 L899.26,111.62 L899.93,109.84 L900.60,108.23 L901.27,106.78 L901.94,105.49 L902.61,104.34 L903.28,103.34 L903.95,102.47 L904.62,101.73 L905.30,101.11 L905.97,100.61 L906.64,100.23 L907.31,99.95 L907.98,99.77 L908.65,99.70 L909.32,99.71 L909.99,99.81 L910.66,99.99 L911.33,100.24 L912.00,100.58 L912.67,100.97 L913.35,101.44 L914.02,101.96 L914.69,102.54 L915.36,103.17 L916.03,103.85 L916.70,104.57 L917.37,105.34 L918.04,106.14 L918.71,106.98 L919.38,107.85 L920.05,108.75 L920.72,109.67 L921.40,110.62 L922.07,111.59 L922.74,112.57 L923.41,113.57 L924.08,114.59 L924.75,115.61 L925.42,116.64 L926.09,117.68 L926.76,118.73 L927.43,119.78 L928.10,120.82 L928.78,121.87 L929.45,122.92 L930.12,123.96 L930.79,125.00 L931.46,126.03 L932.13,127.05 L932.80,128.07 L933.47,129.08 L934.14,130.07 L934.81,131.06 L935.48,132.03 L936.15,132.99 L936.83,133.93 L937.50,134.86 L938.17,135.78 L938.84,136.68 L939.51,137.56 L940.18,138.43 L940.85,139.27 L941.52,140.11 L942.19,140.92 L942.86,141.72 L943.53,142.49 L944.20,143.25 L944.88,143.99 L945.55,144.72 L946.22,145.42 L946.89,146.10 L947.56,146.77 L948.23,147.42 L948.90,148.04 L949.57,148.65 L950.24,149.24 L950.91,149.81 L951.58,157.92 L952.25,160.92 L952.92,163.76 L953.60,166.45 L954.27,168.97 L954.94,171.34 L955.61,173.57 L956.28,175.65 L956.95,177.60 L957.62,179.41 L958.29,181.09 L958.96,182.65 L959.63,184.09 L960.30,185.41 L960.97,186.62 L961.65,187.72 L962.32,188.71 L962.99,189.61 L963.66,190.42 L964.33,191.13 L965.00,191.75 L965.67,192.29 L966.34,192.75 L967.01,193.13 L967.68,193.44 L968.35,193.68 L969.03,193.85 L969.70,193.96 L970.37,194.01 L971.04,194.00 L971.71,193.94 L972.38,193.83 L973.05,193.67 L973.72,193.46 L974.39,193.21 L975.06,192.93 L975.73,192.60 L976.40,192.24 L977.07,191.85 L977.75,191.43 L978.42,190.98 L979.09,190.51 L979.76,190.01 L980.43,189.49 L981.10,188.95 L981.77,188.39 L982.44,187.82 L983.11,187.23 L983.78,186.63 L984.45,186.02 L985.12,185.40 L985.80,184.78 L986.47,184.14 L987.14,183.50 L987.81,182.86 L988.48,182.21 L989.15,181.56 L989.82,180.91 L990.49,180.26 L991.16,179.61 L991.83,178.97 L992.50,178.32 L993.17,177.68 L993.85,177.05 L994.52,176.42 L995.19,175.79 L995.86,175.18 L996.53,174.57 L997.20,173.96 L997.87,173.37 L998.54,172.78 L999.21,172.21 L999.88,171.64 L1000.55,171.08 L1001.22,170.54 L1001.90,170.00 L1002.57,169.47 L1003.24,168.96 L1003.91,168.45 L1004.58,167.96 L1005.25,167.48 L1005.92,167.01 L1006.59,166.55 L1007.26,166.10 L1007.93,165.66 L1008.60,165.24 L1009.28,164.83 L1009.95,164.43 L1010.62,164.04 L1011.29,163.66 L1011.96,163.29 L1012.63,162.94 L1013.30,162.60 L1013.97,162.26 L1014.64,161.94 L1015.31,161.63 L1015.98,161.34 L1016.65,161.05 L1017.32,160.77 L1018.00,160.51 L1018.67,160.25 L1019.34,160.00 L1020.01,159.77 L1020.68,159.54 L1021.35,159.33 L1022.02,159.12 L1022.69,158.92 L1023.36,158.73 L1024.03,158.55 L1024.70,158.38 L1025.38,158.22 L1026.05,158.07 L1026.72,157.92 L1027.39,157.78 L1028.06,157.65 L1028.73,157.53 L1029.40,157.41 L1030.07,157.30 L1030.74,157.20 L1031.41,157.10 L1032.08,157.01 L1032.75,156.93 L1033.43,156.85 L1034.10,156.78 L1034.77,156.71 L1035.44,156.65 L1036.11,156.60 L1036.78,156.55 L1037.45,156.50 L1038.12,156.46 L1038.79,156.42 L1039.46,156.39 L1040.13,156.36 L1040.80,156.34 L1041.47,156.32 L1042.15,156.30 L1042.82,156.28 L1043.49,156.27 L1044.16,156.26 L1044.83,156.26 L1045.50,156.26 L1046.17,156.26 L1046.84,156.26 L1047.51,156.27 L1048.18,156.27 L1048.85,156.28 L1049.53,156.29 L1050.20,156.31 L1050.87,156.32 L1051.54,156.34 L1052.21,156.36 L1052.88,156.37 L1053.55,156.40 L1054.22,156.42 L1054.89,156.44 L1055.56,156.46 L1056.23,156.49 L1056.90,156.51 L1057.57,156.54 L1058.25,156.57 L1058.92,156.60 L1059.59,156.62 L1060.26,156.65 L1060.93,156.68 L1061.60,156.71 L1062.27,156.74 L1062.94,156.77 L1063.61,156.80 L1064.28,156.83 L1064.95,156.86 L1065.62,156.89 L1066.30,156.92 L1066.97,156.95 L1067.64,156.98 L1068.31,157.01 L1068.98,157.04 L1069.65,157.07 L1070.32,157.09 L1070.99,157.12 L1071.66,157.15 L1072.33,157.18 L1073.00,157.21 L1073.68,157.23 L1074.35,157.26 L1075.02,157.28 L1075.69,157.31 L1076.36,157.34 L1077.03,157.36 L1077.70,157.38 L1078.37,157.41 L1079.04,157.43 L1079.71,157.45 L1080.38,157.48 L1081.05,157.50 L1081.72,157.52 L1082.40,157.54 L1083.07,157.56 L1083.74,157.58 L1084.41,157.60 L1085.08,157.62 L1085.75,157.63 L1086.42,157.65 L1087.09,157.67 L1087.76,157.69 L1088.43,157.70 L1089.10,157.72 L1089.78,157.73 L1090.45,157.75 L1091.12,157.76 L1091.79,157.77 L1092.46,157.79 L1093.13,157.80 L1093.80,157.81 L1094.47,157.82 L1095.14,157.83 L1095.81,157.84 L1096.48,157.85 L1097.15,157.86 L1097.82,157.87 L1098.50,157.88 L1099.17,157.89 L1099.84,157.90 L1100.51,157.90 L1101.18,157.91 L1101.85,157.92 L1102.52,157.92 L1103.19,157.93 L1103.86,157.93 L1104.53,157.94 L1105.20,157.94 L1105.88,157.95 L1106.55,157.95 L1107.22,157.96 L1107.89,157.96 L1108.56,157.97 L1109.23,157.97 L1109.90,157.97 L1110.57,157.97 L1111.24,157.98 L1111.91,157.98 L1112.58,157.98 L1113.25,157.98 L1113.93,157.99 L1114.60,157.99 L1115.27,157.99 L1115.94,157.99 L1116.61,157.99 L1117.28,157.99 L1117.95,157.99 L1118.62,157.99 L1119.29,157.99 L1119.96,157.99 L1120.63,157.99 L1121.30,157.99 L1121.97,157.99 L1122.65,157.99 L1123.32,157.99 L1123.99,157.99 L1124.66,157.99 L1125.33,157.99 L1126.00,157.99 " fill="none" stroke="#9aa3ad" stroke-width="1.8" stroke-dasharray="4 3"/><path d="M804.00,157.92 L804.67,157.86 L805.34,157.71 L806.01,157.46 L806.68,157.12 L807.35,156.70 L808.03,156.20 L808.70,155.62 L809.37,154.98 L810.04,154.27 L810.71,153.50 L811.38,152.67 L812.05,151.79 L812.72,150.86 L813.39,149.89 L814.06,148.88 L814.73,147.84 L815.40,146.76 L816.08,145.65 L816.75,144.52 L817.42,143.36 L818.09,142.18 L818.76,140.99 L819.43,139.78 L820.10,138.56 L820.77,137.33 L821.44,136.09 L822.11,134.85 L822.78,133.61 L823.45,132.36 L824.12,131.12 L824.80,129.87 L825.47,128.64 L826.14,127.41 L826.81,126.19 L827.48,124.97 L828.15,123.77 L828.82,122.58 L829.49,121.40 L830.16,120.24 L830.83,119.09 L831.50,117.96 L832.17,116.84 L832.85,115.74 L833.52,114.66 L834.19,113.60 L834.86,112.56 L835.53,111.54 L836.20,110.53 L836.87,109.55 L837.54,108.59 L838.21,107.66 L838.88,106.74 L839.55,105.85 L840.22,104.97 L840.90,104.13 L841.57,103.30 L842.24,102.49 L842.91,101.71 L843.58,100.95 L844.25,100.21 L844.92,99.54 L845.59,98.97 L846.26,98.50 L846.93,98.12 L847.60,97.83 L848.28,97.62 L848.95,97.50 L849.62,97.45 L850.29,97.48 L850.96,97.57 L851.63,97.73 L852.30,97.95 L852.97,98.23 L853.64,98.56 L854.31,98.94 L854.98,99.37 L855.65,99.84 L856.33,100.36 L857.00,100.91 L857.67,101.50 L858.34,102.12 L859.01,102.77 L859.68,103.44 L860.35,104.14 L861.02,104.87 L861.69,105.61 L862.36,106.37 L863.03,107.15 L863.70,107.94 L864.38,108.75 L865.05,109.56 L865.72,110.38 L866.39,111.21 L867.06,112.04 L867.73,112.88 L868.40,113.72 L869.07,114.56 L869.74,115.40 L870.41,116.24 L871.08,117.07 L871.75,117.90 L872.42,118.73 L873.10,119.54 L873.77,120.36 L874.44,121.16 L875.11,121.96 L875.78,122.74 L876.45,123.52 L877.12,124.28 L877.79,125.04 L878.46,125.78 L879.13,126.51 L879.80,127.23 L880.47,127.93 L881.15,128.62 L881.82,129.30 L882.49,129.96 L883.16,130.61 L883.83,131.25 L884.50,131.87 L885.17,132.47 L885.84,133.06 L886.51,133.64 L887.18,134.20 L887.85,134.74 L888.53,135.27 L889.20,135.78 L889.87,136.28 L890.54,136.72 L891.21,137.05 L891.88,137.28 L892.55,137.42 L893.22,137.46 L893.89,137.42 L894.56,137.30 L895.23,137.10 L895.90,136.83 L896.58,136.49 L897.25,136.09 L897.92,135.62 L898.59,135.11 L899.26,134.53 L899.93,133.91 L900.60,133.25 L901.27,132.54 L901.94,131.80 L902.61,131.02 L903.28,130.21 L903.95,129.37 L904.62,128.50 L905.30,127.61 L905.97,126.70 L906.64,125.77 L907.31,124.82 L907.98,123.86 L908.65,122.89 L909.32,121.91 L909.99,120.92 L910.66,119.92 L911.33,118.92 L912.00,117.92 L912.67,116.92 L913.35,115.92 L914.02,114.92 L914.69,113.93 L915.36,112.94 L916.03,111.95 L916.70,110.98 L917.37,110.01 L918.04,109.05 L918.71,108.11 L919.38,107.17 L920.05,106.25 L920.72,105.33 L921.40,104.44 L922.07,103.55 L922.74,102.68 L923.41,101.83 L924.08,100.99 L924.75,100.17 L925.42,99.36 L926.09,98.57 L926.76,97.80 L927.43,97.05 L928.10,96.31 L928.78,95.59 L929.45,94.89 L930.12,94.21 L930.79,93.54 L931.46,92.89 L932.13,92.27 L932.80,91.65 L933.47,91.06 L934.14,90.49 L934.81,89.93 L935.48,89.39 L936.15,88.87 L936.83,88.36 L937.50,87.87 L938.17,87.40 L938.84,86.95 L939.51,86.51 L940.18,86.09 L940.85,85.68 L941.52,85.30 L942.19,84.92 L942.86,84.56 L943.53,84.22 L944.20,83.89 L944.88,83.58 L945.55,83.28 L946.22,82.99 L946.89,82.72 L947.56,82.46 L948.23,82.22 L948.90,81.98 L949.57,81.76 L950.24,81.55 L950.91,81.36 L951.58,81.17 L952.25,81.02 L952.92,80.93 L953.60,80.90 L954.27,80.93 L954.94,81.00 L955.61,81.13 L956.28,81.30 L956.95,81.52 L957.62,81.77 L958.29,82.07 L958.96,82.40 L959.63,82.76 L960.30,83.16 L960.97,83.58 L961.65,84.03 L962.32,84.50 L962.99,85.00 L963.66,85.52 L964.33,86.05 L965.00,86.61 L965.67,87.18 L966.34,87.76 L967.01,88.35 L967.68,88.96 L968.35,89.57 L969.03,90.19 L969.70,90.82 L970.37,91.45 L971.04,92.08 L971.71,92.72 L972.38,93.36 L973.05,94.00 L973.72,94.64 L974.39,95.27 L975.06,95.91 L975.73,96.54 L976.40,97.17 L977.07,97.79 L977.75,98.41 L978.42,99.02 L979.09,99.63 L979.76,100.23 L980.43,100.82 L981.10,101.40 L981.77,101.97 L982.44,102.54 L983.11,103.09 L983.78,103.64 L984.45,104.17 L985.12,104.70 L985.80,105.21 L986.47,105.71 L987.14,106.21 L987.81,106.69 L988.48,107.16 L989.15,107.62 L989.82,108.07 L990.49,108.50 L991.16,108.93 L991.83,109.34 L992.50,109.75 L993.17,110.14 L993.85,110.52 L994.52,110.88 L995.19,111.24 L995.86,111.58 L996.53,111.92 L997.20,112.24 L997.87,112.55 L998.54,112.85 L999.21,113.14 L999.88,113.42 L1000.55,113.69 L1001.22,113.95 L1001.90,114.20 L1002.57,114.44 L1003.24,114.67 L1003.91,114.89 L1004.58,115.10 L1005.25,115.30 L1005.92,115.49 L1006.59,115.67 L1007.26,115.84 L1007.93,116.01 L1008.60,116.17 L1009.28,116.32 L1009.95,116.46 L1010.62,116.59 L1011.29,116.72 L1011.96,116.84 L1012.63,116.95 L1013.30,117.06 L1013.97,117.15 L1014.64,117.25 L1015.31,117.33 L1015.98,117.41 L1016.65,117.49 L1017.32,117.56 L1018.00,117.62 L1018.67,117.68 L1019.34,117.73 L1020.01,117.78 L1020.68,117.82 L1021.35,117.86 L1022.02,117.90 L1022.69,117.93 L1023.36,117.96 L1024.03,117.98 L1024.70,118.00 L1025.38,118.01 L1026.05,118.03 L1026.72,118.04 L1027.39,118.04 L1028.06,118.05 L1028.73,118.05 L1029.40,118.05 L1030.07,118.05 L1030.74,118.04 L1031.41,118.03 L1032.08,118.02 L1032.75,118.01 L1033.43,118.00 L1034.10,117.98 L1034.77,117.96 L1035.44,117.95 L1036.11,117.93 L1036.78,117.91 L1037.45,117.88 L1038.12,117.86 L1038.79,117.84 L1039.46,117.81 L1040.13,117.79 L1040.80,117.76 L1041.47,117.74 L1042.15,117.71 L1042.82,117.68 L1043.49,117.65 L1044.16,117.62 L1044.83,117.59 L1045.50,117.57 L1046.17,117.54 L1046.84,117.51 L1047.51,117.48 L1048.18,117.45 L1048.85,117.42 L1049.53,117.39 L1050.20,117.36 L1050.87,117.33 L1051.54,117.30 L1052.21,117.27 L1052.88,117.25 L1053.55,117.22 L1054.22,117.19 L1054.89,117.16 L1055.56,117.13 L1056.23,117.11 L1056.90,117.08 L1057.57,117.06 L1058.25,117.03 L1058.92,117.00 L1059.59,116.98 L1060.26,116.96 L1060.93,116.93 L1061.60,116.91 L1062.27,116.89 L1062.94,116.86 L1063.61,116.84 L1064.28,116.82 L1064.95,116.80 L1065.62,116.78 L1066.30,116.76 L1066.97,116.74 L1067.64,116.72 L1068.31,116.71 L1068.98,116.69 L1069.65,116.67 L1070.32,116.66 L1070.99,116.64 L1071.66,116.62 L1072.33,116.61 L1073.00,116.59 L1073.68,116.58 L1074.35,116.57 L1075.02,116.55 L1075.69,116.54 L1076.36,116.53 L1077.03,116.52 L1077.70,116.51 L1078.37,116.50 L1079.04,116.49 L1079.71,116.48 L1080.38,116.47 L1081.05,116.46 L1081.72,116.45 L1082.40,116.44 L1083.07,116.44 L1083.74,116.43 L1084.41,116.42 L1085.08,116.41 L1085.75,116.41 L1086.42,116.40 L1087.09,116.40 L1087.76,116.39 L1088.43,116.39 L1089.10,116.38 L1089.78,116.38 L1090.45,116.37 L1091.12,116.37 L1091.79,116.37 L1092.46,116.36 L1093.13,116.36 L1093.80,116.36 L1094.47,116.36 L1095.14,116.35 L1095.81,116.35 L1096.48,116.35 L1097.15,116.35 L1097.82,116.35 L1098.50,116.35 L1099.17,116.34 L1099.84,116.34 L1100.51,116.34 L1101.18,116.34 L1101.85,116.34 L1102.52,116.34 L1103.19,116.34 L1103.86,116.34 L1104.53,116.34 L1105.20,116.34 L1105.88,116.34 L1106.55,116.34 L1107.22,116.34 L1107.89,116.34 L1108.56,116.34 L1109.23,116.34 L1109.90,116.35 L1110.57,116.35 L1111.24,116.35 L1111.91,116.35 L1112.58,116.35 L1113.25,116.35 L1113.93,116.35 L1114.60,116.35 L1115.27,116.35 L1115.94,116.35 L1116.61,116.36 L1117.28,116.36 L1117.95,116.36 L1118.62,116.36 L1119.29,116.36 L1119.96,116.36 L1120.63,116.36 L1121.30,116.37 L1121.97,116.37 L1122.65,116.37 L1123.32,116.37 L1123.99,116.37 L1124.66,116.37 L1125.33,116.37 L1126.00,116.37 " fill="none" stroke="#2f6fec" stroke-width="1.8"/><text x="1122" y="104" font-size="9" fill="#2f6fec" text-anchor="end">position</text><path d="M804.00,157.92 L804.67,152.15 L805.34,146.71 L806.01,141.57 L806.68,136.73 L807.35,132.19 L808.03,127.92 L808.70,123.93 L809.37,120.20 L810.04,116.73 L810.71,113.50 L811.38,110.52 L812.05,107.76 L812.72,105.23 L813.39,102.92 L814.06,100.80 L814.73,98.89 L815.40,97.17 L816.08,95.63 L816.75,94.27 L817.42,93.08 L818.09,92.04 L818.76,91.16 L819.43,90.43 L820.10,89.84 L820.77,89.38 L821.44,89.05 L822.11,88.84 L822.78,88.75 L823.45,88.76 L824.12,88.88 L824.80,89.10 L825.47,89.40 L826.14,89.80 L826.81,90.27 L827.48,90.82 L828.15,91.44 L828.82,92.13 L829.49,92.88 L830.16,93.69 L830.83,94.55 L831.50,95.46 L832.17,96.41 L832.85,97.41 L833.52,98.44 L834.19,99.51 L834.86,100.60 L835.53,101.73 L836.20,102.88 L836.87,104.05 L837.54,105.24 L838.21,106.44 L838.88,107.66 L839.55,108.89 L840.22,110.12 L840.90,111.36 L841.57,112.61 L842.24,113.85 L842.91,115.10 L843.58,116.34 L844.25,117.58 L844.92,123.42 L845.59,129.00 L846.26,134.33 L846.93,139.41 L847.60,144.24 L848.28,148.83 L848.95,153.20 L849.62,157.33 L850.29,161.25 L850.96,164.95 L851.63,168.45 L852.30,171.74 L852.97,174.83 L853.64,177.73 L854.31,180.45 L854.98,182.99 L855.65,185.36 L856.33,187.55 L857.00,189.59 L857.67,191.47 L858.34,193.20 L859.01,194.78 L859.68,196.22 L860.35,197.53 L861.02,198.71 L861.69,199.76 L862.36,200.70 L863.03,201.52 L863.70,202.23 L864.38,202.84 L865.05,203.35 L865.72,203.76 L866.39,204.08 L867.06,204.32 L867.73,204.47 L868.40,204.54 L869.07,204.54 L869.74,204.47 L870.41,204.34 L871.08,204.14 L871.75,203.88 L872.42,203.57 L873.10,203.21 L873.77,202.80 L874.44,202.34 L875.11,201.84 L875.78,201.30 L876.45,200.73 L877.12,200.12 L877.79,199.48 L878.46,198.81 L879.13,198.12 L879.80,197.40 L880.47,196.66 L881.15,195.91 L881.82,195.14 L882.49,194.35 L883.16,193.55 L883.83,192.74 L884.50,191.92 L885.17,191.09 L885.84,190.26 L886.51,189.42 L887.18,188.59 L887.85,187.75 L888.53,186.91 L889.20,186.07 L889.87,185.23 L890.54,179.22 L891.21,173.49 L891.88,168.04 L892.55,162.87 L893.22,157.97 L893.89,153.34 L894.56,148.95 L895.23,144.82 L895.90,140.92 L896.58,137.26 L897.25,133.83 L897.92,130.62 L898.59,127.62 L899.26,124.82 L899.93,122.23 L900.60,119.82 L901.27,117.61 L901.94,115.57 L902.61,113.70 L903.28,112.00 L903.95,110.46 L904.62,109.08 L905.30,107.84 L905.97,106.74 L906.64,105.78 L907.31,104.94 L907.98,104.24 L908.65,103.65 L909.32,103.17 L909.99,102.80 L910.66,102.53 L911.33,102.36 L912.00,102.29 L912.67,102.30 L913.35,102.39 L914.02,102.56 L914.69,102.81 L915.36,103.12 L916.03,103.50 L916.70,103.95 L917.37,104.44 L918.04,105.00 L918.71,105.60 L919.38,106.25 L920.05,106.94 L920.72,107.67 L921.40,108.44 L922.07,109.24 L922.74,110.07 L923.41,110.93 L924.08,111.81 L924.75,112.72 L925.42,113.64 L926.09,114.58 L926.76,115.54 L927.43,116.50 L928.10,117.48 L928.78,118.47 L929.45,119.46 L930.12,120.46 L930.79,121.46 L931.46,122.46 L932.13,123.46 L932.80,124.46 L933.47,125.46 L934.14,126.45 L934.81,127.44 L935.48,128.42 L936.15,129.39 L936.83,130.35 L937.50,131.30 L938.17,132.24 L938.84,133.17 L939.51,134.09 L940.18,134.99 L940.85,135.88 L941.52,136.75 L942.19,137.61 L942.86,138.46 L943.53,139.28 L944.20,140.09 L944.88,140.89 L945.55,141.67 L946.22,142.43 L946.89,143.17 L947.56,143.90 L948.23,144.61 L948.90,145.30 L949.57,145.97 L950.24,146.62 L950.91,147.26 L951.58,147.88 L952.25,151.36 L952.92,154.66 L953.60,157.79 L954.27,160.76 L954.94,163.56 L955.61,166.21 L956.28,168.70 L956.95,171.04 L957.62,173.23 L958.29,175.29 L958.96,177.21 L959.63,179.00 L960.30,180.66 L960.97,182.19 L961.65,183.61 L962.32,184.92 L962.99,186.11 L963.66,187.20 L964.33,188.19 L965.00,189.07 L965.67,189.87 L966.34,190.57 L967.01,191.19 L967.68,191.72 L968.35,192.18 L969.03,192.55 L969.70,192.86 L970.37,193.10 L971.04,193.27 L971.71,193.38 L972.38,193.43 L973.05,193.43 L973.72,193.37 L974.39,193.26 L975.06,193.10 L975.73,192.90 L976.40,192.66 L977.07,192.38 L977.75,192.06 L978.42,191.71 L979.09,191.33 L979.76,190.91 L980.43,190.47 L981.10,190.01 L981.77,189.52 L982.44,189.01 L983.11,188.48 L983.78,187.93 L984.45,187.37 L985.12,186.79 L985.80,186.20 L986.47,185.60 L987.14,184.99 L987.81,184.37 L988.48,183.75 L989.15,183.12 L989.82,182.48 L990.49,181.85 L991.16,181.21 L991.83,180.57 L992.50,179.93 L993.17,179.29 L993.85,178.66 L994.52,178.02 L995.19,177.39 L995.86,176.77 L996.53,176.15 L997.20,175.53 L997.87,174.93 L998.54,174.33 L999.21,173.73 L999.88,173.15 L1000.55,172.57 L1001.22,172.00 L1001.90,171.44 L1002.57,170.90 L1003.24,170.36 L1003.91,169.83 L1004.58,169.31 L1005.25,168.80 L1005.92,168.30 L1006.59,167.82 L1007.26,167.34 L1007.93,166.88 L1008.60,166.43 L1009.28,165.99 L1009.95,165.56 L1010.62,165.14 L1011.29,164.73 L1011.96,164.34 L1012.63,163.95 L1013.30,163.58 L1013.97,163.22 L1014.64,162.87 L1015.31,162.54 L1015.98,162.21 L1016.65,161.89 L1017.32,161.59 L1018.00,161.29 L1018.67,161.01 L1019.34,160.74 L1020.01,160.48 L1020.68,160.22 L1021.35,159.98 L1022.02,159.75 L1022.69,159.53 L1023.36,159.31 L1024.03,159.11 L1024.70,158.91 L1025.38,158.73 L1026.05,158.55 L1026.72,158.38 L1027.39,158.22 L1028.06,158.07 L1028.73,157.93 L1029.40,157.79 L1030.07,157.66 L1030.74,157.54 L1031.41,157.42 L1032.08,157.32 L1032.75,157.21 L1033.43,157.12 L1034.10,157.03 L1034.77,156.95 L1035.44,156.87 L1036.11,156.80 L1036.78,156.74 L1037.45,156.68 L1038.12,156.62 L1038.79,156.57 L1039.46,156.53 L1040.13,156.48 L1040.80,156.45 L1041.47,156.42 L1042.15,156.39 L1042.82,156.36 L1043.49,156.34 L1044.16,156.32 L1044.83,156.31 L1045.50,156.30 L1046.17,156.29 L1046.84,156.29 L1047.51,156.28 L1048.18,156.28 L1048.85,156.29 L1049.53,156.29 L1050.20,156.30 L1050.87,156.31 L1051.54,156.32 L1052.21,156.33 L1052.88,156.35 L1053.55,156.36 L1054.22,156.38 L1054.89,156.40 L1055.56,156.42 L1056.23,156.44 L1056.90,156.46 L1057.57,156.49 L1058.25,156.51 L1058.92,156.54 L1059.59,156.56 L1060.26,156.59 L1060.93,156.62 L1061.60,156.64 L1062.27,156.67 L1062.94,156.70 L1063.61,156.73 L1064.28,156.76 L1064.95,156.79 L1065.62,156.82 L1066.30,156.84 L1066.97,156.87 L1067.64,156.90 L1068.31,156.93 L1068.98,156.96 L1069.65,156.99 L1070.32,157.02 L1070.99,157.05 L1071.66,157.08 L1072.33,157.11 L1073.00,157.13 L1073.68,157.16 L1074.35,157.19 L1075.02,157.22 L1075.69,157.24 L1076.36,157.27 L1077.03,157.29 L1077.70,157.32 L1078.37,157.34 L1079.04,157.37 L1079.71,157.39 L1080.38,157.42 L1081.05,157.44 L1081.72,157.46 L1082.40,157.48 L1083.07,157.50 L1083.74,157.52 L1084.41,157.55 L1085.08,157.56 L1085.75,157.58 L1086.42,157.60 L1087.09,157.62 L1087.76,157.64 L1088.43,157.66 L1089.10,157.67 L1089.78,157.69 L1090.45,157.70 L1091.12,157.72 L1091.79,157.73 L1092.46,157.75 L1093.13,157.76 L1093.80,157.77 L1094.47,157.79 L1095.14,157.80 L1095.81,157.81 L1096.48,157.82 L1097.15,157.83 L1097.82,157.84 L1098.50,157.85 L1099.17,157.86 L1099.84,157.87 L1100.51,157.88 L1101.18,157.89 L1101.85,157.90 L1102.52,157.90 L1103.19,157.91 L1103.86,157.92 L1104.53,157.92 L1105.20,157.93 L1105.88,157.93 L1106.55,157.94 L1107.22,157.94 L1107.89,157.95 L1108.56,157.95 L1109.23,157.96 L1109.90,157.96 L1110.57,157.96 L1111.24,157.97 L1111.91,157.97 L1112.58,157.97 L1113.25,157.98 L1113.93,157.98 L1114.60,157.98 L1115.27,157.98 L1115.94,157.98 L1116.61,157.99 L1117.28,157.99 L1117.95,157.99 L1118.62,157.99 L1119.29,157.99 L1119.96,157.99 L1120.63,157.99 L1121.30,157.99 L1121.97,157.99 L1122.65,157.99 L1123.32,157.99 L1123.99,157.99 L1124.66,157.99 L1125.33,157.99 L1126.00,157.99 " fill="none" stroke="#e8833a" stroke-width="1.8" stroke-dasharray="4 3"/><text x="1122" y="116" font-size="9" fill="#e8833a" text-anchor="end">velocity</text></svg> \ No newline at end of file diff --git a/app/vendor/rune/demo/motion/swiftui.png b/app/vendor/rune/demo/motion/swiftui.png new file mode 100644 index 0000000..0b7cead Binary files /dev/null and b/app/vendor/rune/demo/motion/swiftui.png differ diff --git a/app/vendor/rune/demo/motion/swiftui.svg b/app/vendor/rune/demo/motion/swiftui.svg new file mode 100644 index 0000000..4a58e86 --- /dev/null +++ b/app/vendor/rune/demo/motion/swiftui.svg @@ -0,0 +1 @@ +<svg xmlns="http://www.w3.org/2000/svg" width="900" height="900" viewBox="0 0 900 900" font-family="-apple-system, Helvetica, sans-serif"><rect width="100%" height="100%" fill="white"/><text x="16" y="26" font-size="16" font-weight="600" fill="#222">SwiftUI springs</text><rect x="44" y="68" width="242" height="116" fill="#fafbfc" stroke="#e3e6ea"/><text x="44" y="59" font-size="12" font-weight="600" fill="#333">.smooth 0.5/0</text><line x1="44" x2="286" y1="153.29411" y2="153.29411" stroke="#d5d9de" stroke-dasharray="3 3"/><text x="40" y="156.29411" font-size="9" fill="#888" text-anchor="end">0</text><line x1="44" x2="286" y1="85.05882" y2="85.05882" stroke="#d5d9de" stroke-dasharray="3 3"/><text x="40" y="88.05882" font-size="9" fill="#888" text-anchor="end">1</text><text x="286" y="198" font-size="9" fill="#888" text-anchor="end">1.50 s</text><line x1="124.66667" x2="124.66667" y1="68" y2="184" stroke="#d64545" stroke-width="1" stroke-dasharray="2 3"/><path d="M44.00,153.29 L44.81,153.16 L45.61,152.80 L46.42,152.22 L47.23,151.47 L48.03,150.56 L48.84,149.51 L49.65,148.34 L50.45,147.08 L51.26,145.74 L52.07,144.33 L52.87,142.87 L53.68,141.37 L54.49,139.83 L55.29,138.28 L56.10,136.71 L56.91,135.13 L57.71,133.55 L58.52,131.98 L59.33,130.43 L60.13,128.88 L60.94,127.36 L61.75,125.86 L62.55,124.39 L63.36,122.94 L64.17,121.52 L64.97,120.14 L65.78,118.79 L66.59,117.47 L67.39,116.19 L68.20,114.95 L69.01,113.74 L69.81,112.57 L70.62,111.43 L71.43,110.33 L72.23,109.27 L73.04,108.24 L73.85,107.25 L74.65,106.29 L75.46,105.37 L76.27,104.48 L77.07,103.62 L77.88,102.80 L78.69,102.00 L79.49,101.24 L80.30,100.51 L81.11,99.81 L81.91,99.13 L82.72,98.49 L83.53,97.87 L84.33,97.27 L85.14,96.70 L85.95,96.16 L86.75,95.63 L87.56,95.13 L88.37,94.66 L89.17,94.20 L89.98,93.76 L90.79,93.34 L91.59,92.94 L92.40,92.56 L93.21,92.20 L94.01,91.85 L94.82,91.52 L95.63,91.20 L96.43,90.90 L97.24,90.61 L98.05,90.34 L98.85,90.08 L99.66,89.83 L100.47,89.59 L101.27,89.36 L102.08,89.15 L102.89,88.94 L103.69,88.75 L104.50,88.56 L105.31,88.38 L106.11,88.21 L106.92,88.05 L107.73,87.90 L108.53,87.76 L109.34,87.62 L110.15,87.49 L110.95,87.36 L111.76,87.24 L112.57,87.13 L113.37,87.03 L114.18,86.92 L114.99,86.83 L115.79,86.74 L116.60,86.65 L117.41,86.57 L118.21,86.49 L119.02,86.41 L119.83,86.34 L120.63,86.27 L121.44,86.21 L122.25,86.15 L123.05,86.09 L123.86,86.04 L124.67,85.99 L125.47,85.94 L126.28,85.89 L127.09,85.85 L127.89,85.81 L128.70,85.77 L129.51,85.73 L130.31,85.69 L131.12,85.66 L131.93,85.63 L132.73,85.60 L133.54,85.57 L134.35,85.54 L135.15,85.51 L135.96,85.49 L136.77,85.47 L137.57,85.45 L138.38,85.42 L139.19,85.40 L139.99,85.39 L140.80,85.37 L141.61,85.35 L142.41,85.34 L143.22,85.32 L144.03,85.31 L144.83,85.29 L145.64,85.28 L146.45,85.27 L147.25,85.26 L148.06,85.25 L148.87,85.24 L149.67,85.23 L150.48,85.22 L151.29,85.21 L152.09,85.20 L152.90,85.19 L153.71,85.19 L154.51,85.18 L155.32,85.17 L156.13,85.17 L156.93,85.16 L157.74,85.15 L158.55,85.15 L159.35,85.14 L160.16,85.14 L160.97,85.14 L161.77,85.13 L162.58,85.13 L163.39,85.12 L164.19,85.12 L165.00,85.12 L165.81,85.11 L166.61,85.11 L167.42,85.11 L168.23,85.10 L169.03,85.10 L169.84,85.10 L170.65,85.10 L171.45,85.10 L172.26,85.09 L173.07,85.09 L173.87,85.09 L174.68,85.09 L175.49,85.09 L176.29,85.08 L177.10,85.08 L177.91,85.08 L178.71,85.08 L179.52,85.08 L180.33,85.08 L181.13,85.08 L181.94,85.08 L182.75,85.08 L183.55,85.07 L184.36,85.07 L185.17,85.07 L185.97,85.07 L186.78,85.07 L187.59,85.07 L188.39,85.07 L189.20,85.07 L190.01,85.07 L190.81,85.07 L191.62,85.07 L192.43,85.07 L193.23,85.07 L194.04,85.07 L194.85,85.07 L195.65,85.07 L196.46,85.06 L197.27,85.06 L198.07,85.06 L198.88,85.06 L199.69,85.06 L200.49,85.06 L201.30,85.06 L202.11,85.06 L202.91,85.06 L203.72,85.06 L204.53,85.06 L205.33,85.06 L206.14,85.06 L206.95,85.06 L207.75,85.06 L208.56,85.06 L209.37,85.06 L210.17,85.06 L210.98,85.06 L211.79,85.06 L212.59,85.06 L213.40,85.06 L214.21,85.06 L215.01,85.06 L215.82,85.06 L216.63,85.06 L217.43,85.06 L218.24,85.06 L219.05,85.06 L219.85,85.06 L220.66,85.06 L221.47,85.06 L222.27,85.06 L223.08,85.06 L223.89,85.06 L224.69,85.06 L225.50,85.06 L226.31,85.06 L227.11,85.06 L227.92,85.06 L228.73,85.06 L229.53,85.06 L230.34,85.06 L231.15,85.06 L231.95,85.06 L232.76,85.06 L233.57,85.06 L234.37,85.06 L235.18,85.06 L235.99,85.06 L236.79,85.06 L237.60,85.06 L238.41,85.06 L239.21,85.06 L240.02,85.06 L240.83,85.06 L241.63,85.06 L242.44,85.06 L243.25,85.06 L244.05,85.06 L244.86,85.06 L245.67,85.06 L246.47,85.06 L247.28,85.06 L248.09,85.06 L248.89,85.06 L249.70,85.06 L250.51,85.06 L251.31,85.06 L252.12,85.06 L252.93,85.06 L253.73,85.06 L254.54,85.06 L255.35,85.06 L256.15,85.06 L256.96,85.06 L257.77,85.06 L258.57,85.06 L259.38,85.06 L260.19,85.06 L260.99,85.06 L261.80,85.06 L262.61,85.06 L263.41,85.06 L264.22,85.06 L265.03,85.06 L265.83,85.06 L266.64,85.06 L267.45,85.06 L268.25,85.06 L269.06,85.06 L269.87,85.06 L270.67,85.06 L271.48,85.06 L272.29,85.06 L273.09,85.06 L273.90,85.06 L274.71,85.06 L275.51,85.06 L276.32,85.06 L277.13,85.06 L277.93,85.06 L278.74,85.06 L279.55,85.06 L280.35,85.06 L281.16,85.06 L281.97,85.06 L282.77,85.06 L283.58,85.06 L284.39,85.06 L285.19,85.06 L286.00,85.06 " fill="none" stroke="#2f6fec" stroke-width="1.8"/><text x="282" y="80" font-size="9" fill="#2f6fec" text-anchor="end">position</text><path d="M44.00,153.29 L44.81,142.35 L45.61,132.74 L46.42,124.34 L47.23,117.04 L48.03,110.73 L48.84,105.33 L49.65,100.74 L50.45,96.89 L51.26,93.71 L52.07,91.12 L52.87,89.07 L53.68,87.49 L54.49,86.35 L55.29,85.59 L56.10,85.18 L56.91,85.06 L57.71,85.21 L58.52,85.59 L59.33,86.19 L60.13,86.96 L60.94,87.88 L61.75,88.94 L62.55,90.11 L63.36,91.38 L64.17,92.73 L64.97,94.14 L65.78,95.61 L66.59,97.11 L67.39,98.65 L68.20,100.21 L69.01,101.78 L69.81,103.36 L70.62,104.93 L71.43,106.50 L72.23,108.06 L73.04,109.60 L73.85,111.12 L74.65,112.62 L75.46,114.09 L76.27,115.53 L77.07,116.95 L77.88,118.33 L78.69,119.67 L79.49,120.99 L80.30,122.27 L81.11,123.51 L81.91,124.71 L82.72,125.88 L83.53,127.02 L84.33,128.11 L85.14,129.17 L85.95,130.20 L86.75,131.19 L87.56,132.14 L88.37,133.06 L89.17,133.95 L89.98,134.80 L90.79,135.62 L91.59,136.41 L92.40,137.17 L93.21,137.90 L94.01,138.60 L94.82,139.28 L95.63,139.92 L96.43,140.54 L97.24,141.13 L98.05,141.70 L98.85,142.24 L99.66,142.76 L100.47,143.26 L101.27,143.74 L102.08,144.19 L102.89,144.63 L103.69,145.04 L104.50,145.44 L105.31,145.82 L106.11,146.18 L106.92,146.53 L107.73,146.86 L108.53,147.18 L109.34,147.48 L110.15,147.76 L110.95,148.04 L111.76,148.30 L112.57,148.55 L113.37,148.78 L114.18,149.01 L114.99,149.22 L115.79,149.43 L116.60,149.62 L117.41,149.81 L118.21,149.98 L119.02,150.15 L119.83,150.31 L120.63,150.46 L121.44,150.61 L122.25,150.75 L123.05,150.88 L123.86,151.00 L124.67,151.12 L125.47,151.23 L126.28,151.34 L127.09,151.44 L127.89,151.53 L128.70,151.62 L129.51,151.71 L130.31,151.79 L131.12,151.87 L131.93,151.95 L132.73,152.02 L133.54,152.08 L134.35,152.15 L135.15,152.21 L135.96,152.26 L136.77,152.32 L137.57,152.37 L138.38,152.42 L139.19,152.47 L139.99,152.51 L140.80,152.55 L141.61,152.59 L142.41,152.63 L143.22,152.66 L144.03,152.70 L144.83,152.73 L145.64,152.76 L146.45,152.79 L147.25,152.81 L148.06,152.84 L148.87,152.86 L149.67,152.89 L150.48,152.91 L151.29,152.93 L152.09,152.95 L152.90,152.97 L153.71,152.99 L154.51,153.00 L155.32,153.02 L156.13,153.03 L156.93,153.05 L157.74,153.06 L158.55,153.07 L159.35,153.09 L160.16,153.10 L160.97,153.11 L161.77,153.12 L162.58,153.13 L163.39,153.14 L164.19,153.14 L165.00,153.15 L165.81,153.16 L166.61,153.17 L167.42,153.17 L168.23,153.18 L169.03,153.19 L169.84,153.19 L170.65,153.20 L171.45,153.20 L172.26,153.21 L173.07,153.21 L173.87,153.22 L174.68,153.22 L175.49,153.23 L176.29,153.23 L177.10,153.23 L177.91,153.24 L178.71,153.24 L179.52,153.24 L180.33,153.25 L181.13,153.25 L181.94,153.25 L182.75,153.25 L183.55,153.26 L184.36,153.26 L185.17,153.26 L185.97,153.26 L186.78,153.26 L187.59,153.27 L188.39,153.27 L189.20,153.27 L190.01,153.27 L190.81,153.27 L191.62,153.27 L192.43,153.27 L193.23,153.27 L194.04,153.28 L194.85,153.28 L195.65,153.28 L196.46,153.28 L197.27,153.28 L198.07,153.28 L198.88,153.28 L199.69,153.28 L200.49,153.28 L201.30,153.28 L202.11,153.28 L202.91,153.28 L203.72,153.29 L204.53,153.29 L205.33,153.29 L206.14,153.29 L206.95,153.29 L207.75,153.29 L208.56,153.29 L209.37,153.29 L210.17,153.29 L210.98,153.29 L211.79,153.29 L212.59,153.29 L213.40,153.29 L214.21,153.29 L215.01,153.29 L215.82,153.29 L216.63,153.29 L217.43,153.29 L218.24,153.29 L219.05,153.29 L219.85,153.29 L220.66,153.29 L221.47,153.29 L222.27,153.29 L223.08,153.29 L223.89,153.29 L224.69,153.29 L225.50,153.29 L226.31,153.29 L227.11,153.29 L227.92,153.29 L228.73,153.29 L229.53,153.29 L230.34,153.29 L231.15,153.29 L231.95,153.29 L232.76,153.29 L233.57,153.29 L234.37,153.29 L235.18,153.29 L235.99,153.29 L236.79,153.29 L237.60,153.29 L238.41,153.29 L239.21,153.29 L240.02,153.29 L240.83,153.29 L241.63,153.29 L242.44,153.29 L243.25,153.29 L244.05,153.29 L244.86,153.29 L245.67,153.29 L246.47,153.29 L247.28,153.29 L248.09,153.29 L248.89,153.29 L249.70,153.29 L250.51,153.29 L251.31,153.29 L252.12,153.29 L252.93,153.29 L253.73,153.29 L254.54,153.29 L255.35,153.29 L256.15,153.29 L256.96,153.29 L257.77,153.29 L258.57,153.29 L259.38,153.29 L260.19,153.29 L260.99,153.29 L261.80,153.29 L262.61,153.29 L263.41,153.29 L264.22,153.29 L265.03,153.29 L265.83,153.29 L266.64,153.29 L267.45,153.29 L268.25,153.29 L269.06,153.29 L269.87,153.29 L270.67,153.29 L271.48,153.29 L272.29,153.29 L273.09,153.29 L273.90,153.29 L274.71,153.29 L275.51,153.29 L276.32,153.29 L277.13,153.29 L277.93,153.29 L278.74,153.29 L279.55,153.29 L280.35,153.29 L281.16,153.29 L281.97,153.29 L282.77,153.29 L283.58,153.29 L284.39,153.29 L285.19,153.29 L286.00,153.29 " fill="none" stroke="#e8833a" stroke-width="1.8" stroke-dasharray="4 3"/><text x="282" y="92" font-size="9" fill="#e8833a" text-anchor="end">velocity (norm.)</text><rect x="344" y="68" width="242" height="116" fill="#fafbfc" stroke="#e3e6ea"/><text x="344" y="59" font-size="12" font-weight="600" fill="#333">.snappy 0.5/0.15</text><line x1="344" x2="586" y1="153.29411" y2="153.29411" stroke="#d5d9de" stroke-dasharray="3 3"/><text x="340" y="156.29411" font-size="9" fill="#888" text-anchor="end">0</text><line x1="344" x2="586" y1="85.05882" y2="85.05882" stroke="#d5d9de" stroke-dasharray="3 3"/><text x="340" y="88.05882" font-size="9" fill="#888" text-anchor="end">1</text><text x="586" y="198" font-size="9" fill="#888" text-anchor="end">1.50 s</text><line x1="424.6667" x2="424.6667" y1="68" y2="184" stroke="#d64545" stroke-width="1" stroke-dasharray="2 3"/><path d="M344.00,153.29 L344.81,153.16 L345.61,152.79 L346.42,152.20 L347.23,151.43 L348.03,150.48 L348.84,149.38 L349.65,148.15 L350.45,146.81 L351.26,145.38 L352.07,143.86 L352.87,142.28 L353.68,140.65 L354.49,138.97 L355.29,137.26 L356.10,135.53 L356.91,133.78 L357.71,132.03 L358.52,130.28 L359.33,128.54 L360.13,126.81 L360.94,125.10 L361.75,123.42 L362.55,121.76 L363.36,120.13 L364.17,118.54 L364.97,116.98 L365.78,115.46 L366.59,113.98 L367.39,112.54 L368.20,111.15 L369.01,109.79 L369.81,108.49 L370.62,107.23 L371.43,106.01 L372.23,104.84 L373.04,103.71 L373.85,102.62 L374.65,101.58 L375.46,100.59 L376.27,99.64 L377.07,98.72 L377.88,97.85 L378.69,97.03 L379.49,96.23 L380.30,95.48 L381.11,94.77 L381.91,94.09 L382.72,93.44 L383.53,92.83 L384.33,92.26 L385.14,91.71 L385.95,91.20 L386.75,90.71 L387.56,90.25 L388.37,89.82 L389.17,89.42 L389.98,89.03 L390.79,88.68 L391.59,88.34 L392.40,88.03 L393.21,87.74 L394.01,87.47 L394.82,87.21 L395.63,86.98 L396.43,86.76 L397.24,86.55 L398.05,86.36 L398.85,86.19 L399.66,86.03 L400.47,85.88 L401.27,85.74 L402.08,85.62 L402.89,85.50 L403.69,85.40 L404.50,85.30 L405.31,85.22 L406.11,85.14 L406.92,85.07 L407.73,85.01 L408.53,84.95 L409.34,84.90 L410.15,84.85 L410.95,84.81 L411.76,84.78 L412.57,84.75 L413.37,84.72 L414.18,84.70 L414.99,84.68 L415.79,84.67 L416.60,84.65 L417.41,84.64 L418.21,84.64 L419.02,84.63 L419.83,84.63 L420.63,84.63 L421.44,84.63 L422.25,84.63 L423.05,84.64 L423.86,84.64 L424.67,84.65 L425.47,84.66 L426.28,84.66 L427.09,84.67 L427.89,84.68 L428.70,84.69 L429.51,84.70 L430.31,84.71 L431.12,84.72 L431.93,84.73 L432.73,84.74 L433.54,84.75 L434.35,84.76 L435.15,84.78 L435.96,84.79 L436.77,84.80 L437.57,84.81 L438.38,84.82 L439.19,84.83 L439.99,84.84 L440.80,84.85 L441.61,84.86 L442.41,84.87 L443.22,84.88 L444.03,84.89 L444.83,84.90 L445.64,84.90 L446.45,84.91 L447.25,84.92 L448.06,84.93 L448.87,84.94 L449.67,84.94 L450.48,84.95 L451.29,84.96 L452.09,84.96 L452.90,84.97 L453.71,84.97 L454.51,84.98 L455.32,84.98 L456.13,84.99 L456.93,84.99 L457.74,85.00 L458.55,85.00 L459.35,85.01 L460.16,85.01 L460.97,85.01 L461.77,85.02 L462.58,85.02 L463.39,85.02 L464.19,85.03 L465.00,85.03 L465.81,85.03 L466.61,85.03 L467.42,85.04 L468.23,85.04 L469.03,85.04 L469.84,85.04 L470.65,85.04 L471.45,85.05 L472.26,85.05 L473.07,85.05 L473.87,85.05 L474.68,85.05 L475.49,85.05 L476.29,85.05 L477.10,85.05 L477.91,85.05 L478.71,85.06 L479.52,85.06 L480.33,85.06 L481.13,85.06 L481.94,85.06 L482.75,85.06 L483.55,85.06 L484.36,85.06 L485.17,85.06 L485.97,85.06 L486.78,85.06 L487.59,85.06 L488.39,85.06 L489.20,85.06 L490.01,85.06 L490.81,85.06 L491.62,85.06 L492.43,85.06 L493.23,85.06 L494.04,85.06 L494.85,85.06 L495.65,85.06 L496.46,85.06 L497.27,85.06 L498.07,85.06 L498.88,85.06 L499.69,85.06 L500.49,85.06 L501.30,85.06 L502.11,85.06 L502.91,85.06 L503.72,85.06 L504.53,85.06 L505.33,85.06 L506.14,85.06 L506.95,85.06 L507.75,85.06 L508.56,85.06 L509.37,85.06 L510.17,85.06 L510.98,85.06 L511.79,85.06 L512.59,85.06 L513.40,85.06 L514.21,85.06 L515.01,85.06 L515.82,85.06 L516.63,85.06 L517.43,85.06 L518.24,85.06 L519.05,85.06 L519.85,85.06 L520.66,85.06 L521.47,85.06 L522.27,85.06 L523.08,85.06 L523.89,85.06 L524.69,85.06 L525.50,85.06 L526.31,85.06 L527.11,85.06 L527.92,85.06 L528.73,85.06 L529.53,85.06 L530.34,85.06 L531.15,85.06 L531.95,85.06 L532.76,85.06 L533.57,85.06 L534.37,85.06 L535.18,85.06 L535.99,85.06 L536.79,85.06 L537.60,85.06 L538.41,85.06 L539.21,85.06 L540.02,85.06 L540.83,85.06 L541.63,85.06 L542.44,85.06 L543.25,85.06 L544.05,85.06 L544.86,85.06 L545.67,85.06 L546.47,85.06 L547.28,85.06 L548.09,85.06 L548.89,85.06 L549.70,85.06 L550.51,85.06 L551.31,85.06 L552.12,85.06 L552.93,85.06 L553.73,85.06 L554.54,85.06 L555.35,85.06 L556.15,85.06 L556.96,85.06 L557.77,85.06 L558.57,85.06 L559.38,85.06 L560.19,85.06 L560.99,85.06 L561.80,85.06 L562.61,85.06 L563.41,85.06 L564.22,85.06 L565.03,85.06 L565.83,85.06 L566.64,85.06 L567.45,85.06 L568.25,85.06 L569.06,85.06 L569.87,85.06 L570.67,85.06 L571.48,85.06 L572.29,85.06 L573.09,85.06 L573.90,85.06 L574.71,85.06 L575.51,85.06 L576.32,85.06 L577.13,85.06 L577.93,85.06 L578.74,85.06 L579.55,85.06 L580.35,85.06 L581.16,85.06 L581.97,85.06 L582.77,85.06 L583.58,85.06 L584.39,85.06 L585.19,85.06 L586.00,85.06 " fill="none" stroke="#2f6fec" stroke-width="1.8"/><text x="582" y="80" font-size="9" fill="#2f6fec" text-anchor="end">position</text><path d="M344.00,153.29 L344.81,143.35 L345.61,134.44 L346.42,126.51 L347.23,119.48 L348.03,113.30 L348.84,107.88 L349.65,103.19 L350.45,99.16 L351.26,95.74 L352.07,92.88 L352.87,90.54 L353.68,88.67 L354.49,87.23 L355.29,86.19 L356.10,85.50 L356.91,85.13 L357.71,85.06 L358.52,85.25 L359.33,85.67 L360.13,86.31 L360.94,87.13 L361.75,88.12 L362.55,89.25 L363.36,90.50 L364.17,91.87 L364.97,93.32 L365.78,94.85 L366.59,96.45 L367.39,98.10 L368.20,99.78 L369.01,101.50 L369.81,103.23 L370.62,104.98 L371.43,106.73 L372.23,108.48 L373.04,110.22 L373.85,111.94 L374.65,113.65 L375.46,115.33 L376.27,116.98 L377.07,118.60 L377.88,120.19 L378.69,121.74 L379.49,123.25 L380.30,124.72 L381.11,126.14 L381.91,127.53 L382.72,128.87 L383.53,130.17 L384.33,131.42 L385.14,132.63 L385.95,133.79 L386.75,134.90 L387.56,135.98 L388.37,137.01 L389.17,137.99 L389.98,138.94 L390.79,139.84 L391.59,140.70 L392.40,141.52 L393.21,142.30 L394.01,143.04 L394.82,143.75 L395.63,144.42 L396.43,145.06 L397.24,145.66 L398.05,146.23 L398.85,146.77 L399.66,147.27 L400.47,147.75 L401.27,148.21 L402.08,148.63 L402.89,149.03 L403.69,149.40 L404.50,149.76 L405.31,150.09 L406.11,150.39 L406.92,150.68 L407.73,150.95 L408.53,151.20 L409.34,151.43 L410.15,151.65 L410.95,151.85 L411.76,152.03 L412.57,152.20 L413.37,152.36 L414.18,152.51 L414.99,152.64 L415.79,152.76 L416.60,152.87 L417.41,152.98 L418.21,153.07 L419.02,153.15 L419.83,153.23 L420.63,153.30 L421.44,153.36 L422.25,153.42 L423.05,153.47 L423.86,153.51 L424.67,153.55 L425.47,153.58 L426.28,153.61 L427.09,153.64 L427.89,153.66 L428.70,153.68 L429.51,153.69 L430.31,153.70 L431.12,153.71 L431.93,153.72 L432.73,153.72 L433.54,153.72 L434.35,153.72 L435.15,153.72 L435.96,153.72 L436.77,153.71 L437.57,153.71 L438.38,153.70 L439.19,153.70 L439.99,153.69 L440.80,153.68 L441.61,153.67 L442.41,153.66 L443.22,153.65 L444.03,153.64 L444.83,153.63 L445.64,153.62 L446.45,153.61 L447.25,153.60 L448.06,153.59 L448.87,153.57 L449.67,153.56 L450.48,153.55 L451.29,153.54 L452.09,153.53 L452.90,153.52 L453.71,153.51 L454.51,153.50 L455.32,153.49 L456.13,153.48 L456.93,153.47 L457.74,153.46 L458.55,153.46 L459.35,153.45 L460.16,153.44 L460.97,153.43 L461.77,153.42 L462.58,153.42 L463.39,153.41 L464.19,153.40 L465.00,153.40 L465.81,153.39 L466.61,153.38 L467.42,153.38 L468.23,153.37 L469.03,153.37 L469.84,153.36 L470.65,153.36 L471.45,153.35 L472.26,153.35 L473.07,153.35 L473.87,153.34 L474.68,153.34 L475.49,153.33 L476.29,153.33 L477.10,153.33 L477.91,153.33 L478.71,153.32 L479.52,153.32 L480.33,153.32 L481.13,153.32 L481.94,153.31 L482.75,153.31 L483.55,153.31 L484.36,153.31 L485.17,153.31 L485.97,153.31 L486.78,153.30 L487.59,153.30 L488.39,153.30 L489.20,153.30 L490.01,153.30 L490.81,153.30 L491.62,153.30 L492.43,153.30 L493.23,153.30 L494.04,153.30 L494.85,153.30 L495.65,153.29 L496.46,153.29 L497.27,153.29 L498.07,153.29 L498.88,153.29 L499.69,153.29 L500.49,153.29 L501.30,153.29 L502.11,153.29 L502.91,153.29 L503.72,153.29 L504.53,153.29 L505.33,153.29 L506.14,153.29 L506.95,153.29 L507.75,153.29 L508.56,153.29 L509.37,153.29 L510.17,153.29 L510.98,153.29 L511.79,153.29 L512.59,153.29 L513.40,153.29 L514.21,153.29 L515.01,153.29 L515.82,153.29 L516.63,153.29 L517.43,153.29 L518.24,153.29 L519.05,153.29 L519.85,153.29 L520.66,153.29 L521.47,153.29 L522.27,153.29 L523.08,153.29 L523.89,153.29 L524.69,153.29 L525.50,153.29 L526.31,153.29 L527.11,153.29 L527.92,153.29 L528.73,153.29 L529.53,153.29 L530.34,153.29 L531.15,153.29 L531.95,153.29 L532.76,153.29 L533.57,153.29 L534.37,153.29 L535.18,153.29 L535.99,153.29 L536.79,153.29 L537.60,153.29 L538.41,153.29 L539.21,153.29 L540.02,153.29 L540.83,153.29 L541.63,153.29 L542.44,153.29 L543.25,153.29 L544.05,153.29 L544.86,153.29 L545.67,153.29 L546.47,153.29 L547.28,153.29 L548.09,153.29 L548.89,153.29 L549.70,153.29 L550.51,153.29 L551.31,153.29 L552.12,153.29 L552.93,153.29 L553.73,153.29 L554.54,153.29 L555.35,153.29 L556.15,153.29 L556.96,153.29 L557.77,153.29 L558.57,153.29 L559.38,153.29 L560.19,153.29 L560.99,153.29 L561.80,153.29 L562.61,153.29 L563.41,153.29 L564.22,153.29 L565.03,153.29 L565.83,153.29 L566.64,153.29 L567.45,153.29 L568.25,153.29 L569.06,153.29 L569.87,153.29 L570.67,153.29 L571.48,153.29 L572.29,153.29 L573.09,153.29 L573.90,153.29 L574.71,153.29 L575.51,153.29 L576.32,153.29 L577.13,153.29 L577.93,153.29 L578.74,153.29 L579.55,153.29 L580.35,153.29 L581.16,153.29 L581.97,153.29 L582.77,153.29 L583.58,153.29 L584.39,153.29 L585.19,153.29 L586.00,153.29 " fill="none" stroke="#e8833a" stroke-width="1.8" stroke-dasharray="4 3"/><text x="582" y="92" font-size="9" fill="#e8833a" text-anchor="end">velocity (norm.)</text><rect x="644" y="68" width="242" height="116" fill="#fafbfc" stroke="#e3e6ea"/><text x="644" y="59" font-size="12" font-weight="600" fill="#333">.bouncy 0.5/0.3</text><line x1="644" x2="886" y1="153.29411" y2="153.29411" stroke="#d5d9de" stroke-dasharray="3 3"/><text x="640" y="156.29411" font-size="9" fill="#888" text-anchor="end">0</text><line x1="644" x2="886" y1="85.05882" y2="85.05882" stroke="#d5d9de" stroke-dasharray="3 3"/><text x="640" y="88.05882" font-size="9" fill="#888" text-anchor="end">1</text><text x="886" y="198" font-size="9" fill="#888" text-anchor="end">1.50 s</text><line x1="724.6667" x2="724.6667" y1="68" y2="184" stroke="#d64545" stroke-width="1" stroke-dasharray="2 3"/><path d="M644.00,153.29 L644.81,153.16 L645.61,152.79 L646.42,152.19 L647.23,151.38 L648.03,150.39 L648.84,149.24 L649.65,147.95 L650.45,146.52 L651.26,144.99 L652.07,143.35 L652.87,141.63 L653.68,139.85 L654.49,138.01 L655.29,136.12 L656.10,134.20 L656.91,132.25 L657.71,130.29 L658.52,128.33 L659.33,126.36 L660.13,124.41 L660.94,122.47 L661.75,120.56 L662.55,118.67 L663.36,116.81 L664.17,114.99 L664.97,113.21 L665.78,111.47 L666.59,109.78 L667.39,108.14 L668.20,106.55 L669.01,105.01 L669.81,103.53 L670.62,102.10 L671.43,100.73 L672.23,99.41 L673.04,98.15 L673.85,96.95 L674.65,95.80 L675.46,94.71 L676.27,93.68 L677.07,92.70 L677.88,91.77 L678.69,90.89 L679.49,90.07 L680.30,89.30 L681.11,88.58 L681.91,87.90 L682.72,87.27 L683.53,86.69 L684.33,86.14 L685.14,85.64 L685.95,85.18 L686.75,84.76 L687.56,84.38 L688.37,84.03 L689.17,83.71 L689.98,83.42 L690.79,83.17 L691.59,82.94 L692.40,82.74 L693.21,82.57 L694.01,82.42 L694.82,82.29 L695.63,82.19 L696.43,82.10 L697.24,82.03 L698.05,81.98 L698.85,81.95 L699.66,81.93 L700.47,81.92 L701.27,81.93 L702.08,81.94 L702.89,81.97 L703.69,82.01 L704.50,82.05 L705.31,82.11 L706.11,82.17 L706.92,82.23 L707.73,82.30 L708.53,82.38 L709.34,82.46 L710.15,82.54 L710.95,82.62 L711.76,82.71 L712.57,82.80 L713.37,82.89 L714.18,82.98 L714.99,83.07 L715.79,83.16 L716.60,83.25 L717.41,83.34 L718.21,83.43 L719.02,83.51 L719.83,83.60 L720.63,83.68 L721.44,83.76 L722.25,83.84 L723.05,83.92 L723.86,84.00 L724.67,84.07 L725.47,84.14 L726.28,84.21 L727.09,84.27 L727.89,84.34 L728.70,84.40 L729.51,84.46 L730.31,84.51 L731.12,84.56 L731.93,84.61 L732.73,84.66 L733.54,84.71 L734.35,84.75 L735.15,84.79 L735.96,84.83 L736.77,84.86 L737.57,84.90 L738.38,84.93 L739.19,84.96 L739.99,84.98 L740.80,85.01 L741.61,85.03 L742.41,85.05 L743.22,85.07 L744.03,85.09 L744.83,85.11 L745.64,85.12 L746.45,85.13 L747.25,85.15 L748.06,85.16 L748.87,85.17 L749.67,85.17 L750.48,85.18 L751.29,85.19 L752.09,85.19 L752.90,85.19 L753.71,85.20 L754.51,85.20 L755.32,85.20 L756.13,85.20 L756.93,85.20 L757.74,85.20 L758.55,85.20 L759.35,85.20 L760.16,85.20 L760.97,85.20 L761.77,85.19 L762.58,85.19 L763.39,85.19 L764.19,85.19 L765.00,85.18 L765.81,85.18 L766.61,85.17 L767.42,85.17 L768.23,85.17 L769.03,85.16 L769.84,85.16 L770.65,85.15 L771.45,85.15 L772.26,85.15 L773.07,85.14 L773.87,85.14 L774.68,85.13 L775.49,85.13 L776.29,85.13 L777.10,85.12 L777.91,85.12 L778.71,85.11 L779.52,85.11 L780.33,85.11 L781.13,85.10 L781.94,85.10 L782.75,85.10 L783.55,85.09 L784.36,85.09 L785.17,85.09 L785.97,85.09 L786.78,85.08 L787.59,85.08 L788.39,85.08 L789.20,85.08 L790.01,85.08 L790.81,85.07 L791.62,85.07 L792.43,85.07 L793.23,85.07 L794.04,85.07 L794.85,85.06 L795.65,85.06 L796.46,85.06 L797.27,85.06 L798.07,85.06 L798.88,85.06 L799.69,85.06 L800.49,85.06 L801.30,85.06 L802.11,85.06 L802.91,85.06 L803.72,85.05 L804.53,85.05 L805.33,85.05 L806.14,85.05 L806.95,85.05 L807.75,85.05 L808.56,85.05 L809.37,85.05 L810.17,85.05 L810.98,85.05 L811.79,85.05 L812.59,85.05 L813.40,85.05 L814.21,85.05 L815.01,85.05 L815.82,85.05 L816.63,85.05 L817.43,85.05 L818.24,85.05 L819.05,85.05 L819.85,85.05 L820.66,85.05 L821.47,85.05 L822.27,85.05 L823.08,85.05 L823.89,85.05 L824.69,85.05 L825.50,85.05 L826.31,85.05 L827.11,85.05 L827.92,85.05 L828.73,85.05 L829.53,85.06 L830.34,85.06 L831.15,85.06 L831.95,85.06 L832.76,85.06 L833.57,85.06 L834.37,85.06 L835.18,85.06 L835.99,85.06 L836.79,85.06 L837.60,85.06 L838.41,85.06 L839.21,85.06 L840.02,85.06 L840.83,85.06 L841.63,85.06 L842.44,85.06 L843.25,85.06 L844.05,85.06 L844.86,85.06 L845.67,85.06 L846.47,85.06 L847.28,85.06 L848.09,85.06 L848.89,85.06 L849.70,85.06 L850.51,85.06 L851.31,85.06 L852.12,85.06 L852.93,85.06 L853.73,85.06 L854.54,85.06 L855.35,85.06 L856.15,85.06 L856.96,85.06 L857.77,85.06 L858.57,85.06 L859.38,85.06 L860.19,85.06 L860.99,85.06 L861.80,85.06 L862.61,85.06 L863.41,85.06 L864.22,85.06 L865.03,85.06 L865.83,85.06 L866.64,85.06 L867.45,85.06 L868.25,85.06 L869.06,85.06 L869.87,85.06 L870.67,85.06 L871.48,85.06 L872.29,85.06 L873.09,85.06 L873.90,85.06 L874.71,85.06 L875.51,85.06 L876.32,85.06 L877.13,85.06 L877.93,85.06 L878.74,85.06 L879.55,85.06 L880.35,85.06 L881.16,85.06 L881.97,85.06 L882.77,85.06 L883.58,85.06 L884.39,85.06 L885.19,85.06 L886.00,85.06 " fill="none" stroke="#2f6fec" stroke-width="1.8"/><text x="882" y="80" font-size="9" fill="#2f6fec" text-anchor="end">position</text><path d="M644.00,153.29 L644.81,144.35 L645.61,136.19 L646.42,128.78 L647.23,122.09 L648.03,116.08 L648.84,110.72 L649.65,105.97 L650.45,101.80 L651.26,98.17 L652.07,95.06 L652.87,92.43 L653.68,90.25 L654.49,88.50 L655.29,87.13 L656.10,86.13 L656.91,85.47 L657.71,85.12 L658.52,85.06 L659.33,85.26 L660.13,85.70 L660.94,86.36 L661.75,87.22 L662.55,88.25 L663.36,89.44 L664.17,90.77 L664.97,92.23 L665.78,93.80 L666.59,95.46 L667.39,97.19 L668.20,99.00 L669.01,100.85 L669.81,102.75 L670.62,104.68 L671.43,106.63 L672.23,108.59 L673.04,110.56 L673.85,112.52 L674.65,114.47 L675.46,116.40 L676.27,118.31 L677.07,120.19 L677.88,122.04 L678.69,123.85 L679.49,125.62 L680.30,127.35 L681.11,129.02 L681.91,130.65 L682.72,132.23 L683.53,133.75 L684.33,135.22 L685.14,136.63 L685.95,137.99 L686.75,139.29 L687.56,140.53 L688.37,141.72 L689.17,142.85 L689.98,143.93 L690.79,144.95 L691.59,145.92 L692.40,146.83 L693.21,147.69 L694.01,148.50 L694.82,149.26 L695.63,149.97 L696.43,150.63 L697.24,151.25 L698.05,151.82 L698.85,152.35 L699.66,152.84 L700.47,153.29 L701.27,153.70 L702.08,154.08 L702.89,154.42 L703.69,154.72 L704.50,155.00 L705.31,155.25 L706.11,155.47 L706.92,155.66 L707.73,155.83 L708.53,155.97 L709.34,156.09 L710.15,156.19 L710.95,156.27 L711.76,156.34 L712.57,156.38 L713.37,156.41 L714.18,156.43 L714.99,156.43 L715.79,156.42 L716.60,156.40 L717.41,156.37 L718.21,156.33 L719.02,156.29 L719.83,156.23 L720.63,156.17 L721.44,156.10 L722.25,156.03 L723.05,155.96 L723.86,155.88 L724.67,155.79 L725.47,155.71 L726.28,155.62 L727.09,155.53 L727.89,155.44 L728.70,155.35 L729.51,155.26 L730.31,155.17 L731.12,155.08 L731.93,154.99 L732.73,154.90 L733.54,154.82 L734.35,154.73 L735.15,154.65 L735.96,154.57 L736.77,154.49 L737.57,154.41 L738.38,154.34 L739.19,154.26 L739.99,154.19 L740.80,154.13 L741.61,154.06 L742.41,154.00 L743.22,153.94 L744.03,153.88 L744.83,153.83 L745.64,153.77 L746.45,153.73 L747.25,153.68 L748.06,153.63 L748.87,153.59 L749.67,153.55 L750.48,153.52 L751.29,153.48 L752.09,153.45 L752.90,153.42 L753.71,153.39 L754.51,153.36 L755.32,153.34 L756.13,153.32 L756.93,153.29 L757.74,153.28 L758.55,153.26 L759.35,153.24 L760.16,153.23 L760.97,153.22 L761.77,153.20 L762.58,153.19 L763.39,153.19 L764.19,153.18 L765.00,153.17 L765.81,153.17 L766.61,153.16 L767.42,153.16 L768.23,153.15 L769.03,153.15 L769.84,153.15 L770.65,153.15 L771.45,153.15 L772.26,153.15 L773.07,153.15 L773.87,153.15 L774.68,153.15 L775.49,153.16 L776.29,153.16 L777.10,153.16 L777.91,153.16 L778.71,153.17 L779.52,153.17 L780.33,153.18 L781.13,153.18 L781.94,153.18 L782.75,153.19 L783.55,153.19 L784.36,153.20 L785.17,153.20 L785.97,153.20 L786.78,153.21 L787.59,153.21 L788.39,153.22 L789.20,153.22 L790.01,153.22 L790.81,153.23 L791.62,153.23 L792.43,153.24 L793.23,153.24 L794.04,153.24 L794.85,153.25 L795.65,153.25 L796.46,153.25 L797.27,153.26 L798.07,153.26 L798.88,153.26 L799.69,153.26 L800.49,153.27 L801.30,153.27 L802.11,153.27 L802.91,153.27 L803.72,153.28 L804.53,153.28 L805.33,153.28 L806.14,153.28 L806.95,153.28 L807.75,153.29 L808.56,153.29 L809.37,153.29 L810.17,153.29 L810.98,153.29 L811.79,153.29 L812.59,153.29 L813.40,153.29 L814.21,153.29 L815.01,153.30 L815.82,153.30 L816.63,153.30 L817.43,153.30 L818.24,153.30 L819.05,153.30 L819.85,153.30 L820.66,153.30 L821.47,153.30 L822.27,153.30 L823.08,153.30 L823.89,153.30 L824.69,153.30 L825.50,153.30 L826.31,153.30 L827.11,153.30 L827.92,153.30 L828.73,153.30 L829.53,153.30 L830.34,153.30 L831.15,153.30 L831.95,153.30 L832.76,153.30 L833.57,153.30 L834.37,153.30 L835.18,153.30 L835.99,153.30 L836.79,153.30 L837.60,153.30 L838.41,153.30 L839.21,153.30 L840.02,153.30 L840.83,153.30 L841.63,153.30 L842.44,153.30 L843.25,153.30 L844.05,153.30 L844.86,153.30 L845.67,153.30 L846.47,153.30 L847.28,153.30 L848.09,153.30 L848.89,153.30 L849.70,153.30 L850.51,153.30 L851.31,153.30 L852.12,153.30 L852.93,153.30 L853.73,153.30 L854.54,153.30 L855.35,153.30 L856.15,153.30 L856.96,153.30 L857.77,153.30 L858.57,153.30 L859.38,153.30 L860.19,153.29 L860.99,153.29 L861.80,153.29 L862.61,153.29 L863.41,153.29 L864.22,153.29 L865.03,153.29 L865.83,153.29 L866.64,153.29 L867.45,153.29 L868.25,153.29 L869.06,153.29 L869.87,153.29 L870.67,153.29 L871.48,153.29 L872.29,153.29 L873.09,153.29 L873.90,153.29 L874.71,153.29 L875.51,153.29 L876.32,153.29 L877.13,153.29 L877.93,153.29 L878.74,153.29 L879.55,153.29 L880.35,153.29 L881.16,153.29 L881.97,153.29 L882.77,153.29 L883.58,153.29 L884.39,153.29 L885.19,153.29 L886.00,153.29 " fill="none" stroke="#e8833a" stroke-width="1.8" stroke-dasharray="4 3"/><text x="882" y="92" font-size="9" fill="#e8833a" text-anchor="end">velocity (norm.)</text><rect x="44" y="238" width="242" height="116" fill="#fafbfc" stroke="#e3e6ea"/><text x="44" y="229" font-size="12" font-weight="600" fill="#333">overdamped 0.5/-0.5</text><line x1="44" x2="286" y1="323.29413" y2="323.29413" stroke="#d5d9de" stroke-dasharray="3 3"/><text x="40" y="326.29413" font-size="9" fill="#888" text-anchor="end">0</text><line x1="44" x2="286" y1="255.05882" y2="255.05882" stroke="#d5d9de" stroke-dasharray="3 3"/><text x="40" y="258.05884" font-size="9" fill="#888" text-anchor="end">1</text><text x="286" y="368" font-size="9" fill="#888" text-anchor="end">1.50 s</text><line x1="124.66667" x2="124.66667" y1="238" y2="354" stroke="#d64545" stroke-width="1" stroke-dasharray="2 3"/><path d="M44.00,323.29 L44.81,323.17 L45.61,322.84 L46.42,322.34 L47.23,321.72 L48.03,321.00 L48.84,320.22 L49.65,319.38 L50.45,318.50 L51.26,317.60 L52.07,316.68 L52.87,315.74 L53.68,314.81 L54.49,313.87 L55.29,312.94 L56.10,312.01 L56.91,311.09 L57.71,310.18 L58.52,309.28 L59.33,308.39 L60.13,307.51 L60.94,306.64 L61.75,305.79 L62.55,304.95 L63.36,304.12 L64.17,303.30 L64.97,302.50 L65.78,301.71 L66.59,300.93 L67.39,300.17 L68.20,299.42 L69.01,298.68 L69.81,297.95 L70.62,297.23 L71.43,296.53 L72.23,295.84 L73.04,295.16 L73.85,294.49 L74.65,293.83 L75.46,293.18 L76.27,292.55 L77.07,291.92 L77.88,291.31 L78.69,290.70 L79.49,290.11 L80.30,289.52 L81.11,288.95 L81.91,288.38 L82.72,287.82 L83.53,287.28 L84.33,286.74 L85.14,286.21 L85.95,285.69 L86.75,285.18 L87.56,284.68 L88.37,284.18 L89.17,283.69 L89.98,283.22 L90.79,282.75 L91.59,282.28 L92.40,281.83 L93.21,281.38 L94.01,280.94 L94.82,280.51 L95.63,280.09 L96.43,279.67 L97.24,279.26 L98.05,278.85 L98.85,278.46 L99.66,278.07 L100.47,277.68 L101.27,277.30 L102.08,276.93 L102.89,276.57 L103.69,276.21 L104.50,275.86 L105.31,275.51 L106.11,275.17 L106.92,274.83 L107.73,274.50 L108.53,274.18 L109.34,273.86 L110.15,273.54 L110.95,273.23 L111.76,272.93 L112.57,272.63 L113.37,272.34 L114.18,272.05 L114.99,271.77 L115.79,271.49 L116.60,271.21 L117.41,270.94 L118.21,270.68 L119.02,270.42 L119.83,270.16 L120.63,269.91 L121.44,269.66 L122.25,269.42 L123.05,269.18 L123.86,268.94 L124.67,268.71 L125.47,268.48 L126.28,268.26 L127.09,268.04 L127.89,267.82 L128.70,267.61 L129.51,267.40 L130.31,267.19 L131.12,266.99 L131.93,266.79 L132.73,266.60 L133.54,266.40 L134.35,266.21 L135.15,266.03 L135.96,265.84 L136.77,265.66 L137.57,265.49 L138.38,265.31 L139.19,265.14 L139.99,264.97 L140.80,264.81 L141.61,264.65 L142.41,264.49 L143.22,264.33 L144.03,264.17 L144.83,264.02 L145.64,263.87 L146.45,263.72 L147.25,263.58 L148.06,263.44 L148.87,263.30 L149.67,263.16 L150.48,263.02 L151.29,262.89 L152.09,262.76 L152.90,262.63 L153.71,262.51 L154.51,262.38 L155.32,262.26 L156.13,262.14 L156.93,262.02 L157.74,261.90 L158.55,261.79 L159.35,261.68 L160.16,261.57 L160.97,261.46 L161.77,261.35 L162.58,261.25 L163.39,261.14 L164.19,261.04 L165.00,260.94 L165.81,260.84 L166.61,260.75 L167.42,260.65 L168.23,260.56 L169.03,260.47 L169.84,260.38 L170.65,260.29 L171.45,260.20 L172.26,260.11 L173.07,260.03 L173.87,259.95 L174.68,259.87 L175.49,259.79 L176.29,259.71 L177.10,259.63 L177.91,259.55 L178.71,259.48 L179.52,259.40 L180.33,259.33 L181.13,259.26 L181.94,259.19 L182.75,259.12 L183.55,259.05 L184.36,258.99 L185.17,258.92 L185.97,258.86 L186.78,258.79 L187.59,258.73 L188.39,258.67 L189.20,258.61 L190.01,258.55 L190.81,258.49 L191.62,258.43 L192.43,258.38 L193.23,258.32 L194.04,258.27 L194.85,258.21 L195.65,258.16 L196.46,258.11 L197.27,258.06 L198.07,258.01 L198.88,257.96 L199.69,257.91 L200.49,257.86 L201.30,257.82 L202.11,257.77 L202.91,257.73 L203.72,257.68 L204.53,257.64 L205.33,257.59 L206.14,257.55 L206.95,257.51 L207.75,257.47 L208.56,257.43 L209.37,257.39 L210.17,257.35 L210.98,257.31 L211.79,257.27 L212.59,257.24 L213.40,257.20 L214.21,257.17 L215.01,257.13 L215.82,257.10 L216.63,257.06 L217.43,257.03 L218.24,257.00 L219.05,256.96 L219.85,256.93 L220.66,256.90 L221.47,256.87 L222.27,256.84 L223.08,256.81 L223.89,256.78 L224.69,256.75 L225.50,256.72 L226.31,256.70 L227.11,256.67 L227.92,256.64 L228.73,256.61 L229.53,256.59 L230.34,256.56 L231.15,256.54 L231.95,256.51 L232.76,256.49 L233.57,256.47 L234.37,256.44 L235.18,256.42 L235.99,256.40 L236.79,256.37 L237.60,256.35 L238.41,256.33 L239.21,256.31 L240.02,256.29 L240.83,256.27 L241.63,256.25 L242.44,256.23 L243.25,256.21 L244.05,256.19 L244.86,256.17 L245.67,256.15 L246.47,256.13 L247.28,256.12 L248.09,256.10 L248.89,256.08 L249.70,256.06 L250.51,256.05 L251.31,256.03 L252.12,256.01 L252.93,256.00 L253.73,255.98 L254.54,255.97 L255.35,255.95 L256.15,255.94 L256.96,255.92 L257.77,255.91 L258.57,255.89 L259.38,255.88 L260.19,255.87 L260.99,255.85 L261.80,255.84 L262.61,255.83 L263.41,255.81 L264.22,255.80 L265.03,255.79 L265.83,255.78 L266.64,255.76 L267.45,255.75 L268.25,255.74 L269.06,255.73 L269.87,255.72 L270.67,255.71 L271.48,255.70 L272.29,255.69 L273.09,255.68 L273.90,255.66 L274.71,255.65 L275.51,255.64 L276.32,255.64 L277.13,255.63 L277.93,255.62 L278.74,255.61 L279.55,255.60 L280.35,255.59 L281.16,255.58 L281.97,255.57 L282.77,255.56 L283.58,255.55 L284.39,255.55 L285.19,255.54 L286.00,255.53 " fill="none" stroke="#2f6fec" stroke-width="1.8"/><text x="282" y="250" font-size="9" fill="#2f6fec" text-anchor="end">position</text><path d="M44.00,323.29 L44.81,305.96 L45.61,292.54 L46.42,282.21 L47.23,274.31 L48.03,268.35 L48.84,263.90 L49.65,260.64 L50.45,258.33 L51.26,256.76 L52.07,255.77 L52.87,255.24 L53.68,255.06 L54.49,255.16 L55.29,255.47 L56.10,255.96 L56.91,256.57 L57.71,257.27 L58.52,258.05 L59.33,258.89 L60.13,259.76 L60.94,260.66 L61.75,261.58 L62.55,262.51 L63.36,263.45 L64.17,264.39 L64.97,265.32 L65.78,266.25 L66.59,267.17 L67.39,268.08 L68.20,268.99 L69.01,269.88 L69.81,270.76 L70.62,271.62 L71.43,272.48 L72.23,273.32 L73.04,274.15 L73.85,274.97 L74.65,275.77 L75.46,276.56 L76.27,277.34 L77.07,278.11 L77.88,278.86 L78.69,279.60 L79.49,280.33 L80.30,281.05 L81.11,281.75 L81.91,282.44 L82.72,283.13 L83.53,283.80 L84.33,284.46 L85.14,285.10 L85.95,285.74 L86.75,286.37 L87.56,286.98 L88.37,287.59 L89.17,288.19 L89.98,288.77 L90.79,289.35 L91.59,289.92 L92.40,290.47 L93.21,291.02 L94.01,291.56 L94.82,292.09 L95.63,292.61 L96.43,293.12 L97.24,293.63 L98.05,294.12 L98.85,294.61 L99.66,295.09 L100.47,295.56 L101.27,296.02 L102.08,296.48 L102.89,296.92 L103.69,297.36 L104.50,297.80 L105.31,298.22 L106.11,298.64 L106.92,299.05 L107.73,299.46 L108.53,299.86 L109.34,300.25 L110.15,300.63 L110.95,301.01 L111.76,301.38 L112.57,301.75 L113.37,302.11 L114.18,302.46 L114.99,302.81 L115.79,303.15 L116.60,303.49 L117.41,303.82 L118.21,304.14 L119.02,304.46 L119.83,304.78 L120.63,305.09 L121.44,305.39 L122.25,305.69 L123.05,305.98 L123.86,306.27 L124.67,306.56 L125.47,306.84 L126.28,307.11 L127.09,307.38 L127.89,307.65 L128.70,307.91 L129.51,308.16 L130.31,308.42 L131.12,308.67 L131.93,308.91 L132.73,309.15 L133.54,309.39 L134.35,309.62 L135.15,309.85 L135.96,310.07 L136.77,310.29 L137.57,310.51 L138.38,310.72 L139.19,310.93 L139.99,311.14 L140.80,311.34 L141.61,311.54 L142.41,311.74 L143.22,311.93 L144.03,312.12 L144.83,312.31 L145.64,312.49 L146.45,312.67 L147.25,312.85 L148.06,313.02 L148.87,313.19 L149.67,313.36 L150.48,313.53 L151.29,313.69 L152.09,313.85 L152.90,314.01 L153.71,314.16 L154.51,314.32 L155.32,314.47 L156.13,314.61 L156.93,314.76 L157.74,314.90 L158.55,315.04 L159.35,315.18 L160.16,315.31 L160.97,315.45 L161.77,315.58 L162.58,315.71 L163.39,315.83 L164.19,315.96 L165.00,316.08 L165.81,316.20 L166.61,316.32 L167.42,316.44 L168.23,316.55 L169.03,316.66 L169.84,316.77 L170.65,316.88 L171.45,316.99 L172.26,317.10 L173.07,317.20 L173.87,317.30 L174.68,317.40 L175.49,317.50 L176.29,317.60 L177.10,317.69 L177.91,317.78 L178.71,317.88 L179.52,317.97 L180.33,318.06 L181.13,318.14 L181.94,318.23 L182.75,318.31 L183.55,318.40 L184.36,318.48 L185.17,318.56 L185.97,318.64 L186.78,318.72 L187.59,318.79 L188.39,318.87 L189.20,318.94 L190.01,319.01 L190.81,319.09 L191.62,319.16 L192.43,319.22 L193.23,319.29 L194.04,319.36 L194.85,319.43 L195.65,319.49 L196.46,319.55 L197.27,319.62 L198.07,319.68 L198.88,319.74 L199.69,319.80 L200.49,319.86 L201.30,319.91 L202.11,319.97 L202.91,320.02 L203.72,320.08 L204.53,320.13 L205.33,320.19 L206.14,320.24 L206.95,320.29 L207.75,320.34 L208.56,320.39 L209.37,320.44 L210.17,320.48 L210.98,320.53 L211.79,320.58 L212.59,320.62 L213.40,320.67 L214.21,320.71 L215.01,320.75 L215.82,320.80 L216.63,320.84 L217.43,320.88 L218.24,320.92 L219.05,320.96 L219.85,321.00 L220.66,321.04 L221.47,321.07 L222.27,321.11 L223.08,321.15 L223.89,321.18 L224.69,321.22 L225.50,321.25 L226.31,321.29 L227.11,321.32 L227.92,321.35 L228.73,321.39 L229.53,321.42 L230.34,321.45 L231.15,321.48 L231.95,321.51 L232.76,321.54 L233.57,321.57 L234.37,321.60 L235.18,321.63 L235.99,321.65 L236.79,321.68 L237.60,321.71 L238.41,321.74 L239.21,321.76 L240.02,321.79 L240.83,321.81 L241.63,321.84 L242.44,321.86 L243.25,321.89 L244.05,321.91 L244.86,321.93 L245.67,321.95 L246.47,321.98 L247.28,322.00 L248.09,322.02 L248.89,322.04 L249.70,322.06 L250.51,322.08 L251.31,322.10 L252.12,322.12 L252.93,322.14 L253.73,322.16 L254.54,322.18 L255.35,322.20 L256.15,322.22 L256.96,322.24 L257.77,322.25 L258.57,322.27 L259.38,322.29 L260.19,322.30 L260.99,322.32 L261.80,322.34 L262.61,322.35 L263.41,322.37 L264.22,322.38 L265.03,322.40 L265.83,322.41 L266.64,322.43 L267.45,322.44 L268.25,322.46 L269.06,322.47 L269.87,322.49 L270.67,322.50 L271.48,322.51 L272.29,322.53 L273.09,322.54 L273.90,322.55 L274.71,322.56 L275.51,322.58 L276.32,322.59 L277.13,322.60 L277.93,322.61 L278.74,322.62 L279.55,322.63 L280.35,322.64 L281.16,322.66 L281.97,322.67 L282.77,322.68 L283.58,322.69 L284.39,322.70 L285.19,322.71 L286.00,322.72 " fill="none" stroke="#e8833a" stroke-width="1.8" stroke-dasharray="4 3"/><text x="282" y="262" font-size="9" fill="#e8833a" text-anchor="end">velocity (norm.)</text><rect x="344" y="238" width="242" height="116" fill="#fafbfc" stroke="#e3e6ea"/><text x="344" y="229" font-size="12" font-weight="600" fill="#333">interactive 0.15/0.13999999</text><line x1="344" x2="586" y1="323.29413" y2="323.29413" stroke="#d5d9de" stroke-dasharray="3 3"/><text x="340" y="326.29413" font-size="9" fill="#888" text-anchor="end">0</text><line x1="344" x2="586" y1="255.05882" y2="255.05882" stroke="#d5d9de" stroke-dasharray="3 3"/><text x="340" y="258.05884" font-size="9" fill="#888" text-anchor="end">1</text><text x="586" y="368" font-size="9" fill="#888" text-anchor="end">1.50 s</text><line x1="368.2" x2="368.2" y1="238" y2="354" stroke="#d64545" stroke-width="1" stroke-dasharray="2 3"/><path d="M344.00,323.29 L344.81,321.97 L345.61,318.59 L346.42,313.90 L347.23,308.47 L348.03,302.72 L348.84,296.96 L349.65,291.41 L350.45,286.20 L351.26,281.42 L352.07,277.12 L352.87,273.32 L353.68,269.99 L354.49,267.12 L355.29,264.68 L356.10,262.62 L356.91,260.91 L357.71,259.50 L358.52,258.35 L359.33,257.43 L360.13,256.70 L360.94,256.14 L361.75,255.70 L362.55,255.37 L363.36,255.13 L364.17,254.96 L364.97,254.85 L365.78,254.77 L366.59,254.73 L367.39,254.72 L368.20,254.72 L369.01,254.73 L369.81,254.75 L370.62,254.78 L371.43,254.81 L372.23,254.84 L373.04,254.87 L373.85,254.89 L374.65,254.92 L375.46,254.94 L376.27,254.96 L377.07,254.98 L377.88,254.99 L378.69,255.01 L379.49,255.02 L380.30,255.03 L381.11,255.03 L381.91,255.04 L382.72,255.05 L383.53,255.05 L384.33,255.05 L385.14,255.05 L385.95,255.06 L386.75,255.06 L387.56,255.06 L388.37,255.06 L389.17,255.06 L389.98,255.06 L390.79,255.06 L391.59,255.06 L392.40,255.06 L393.21,255.06 L394.01,255.06 L394.82,255.06 L395.63,255.06 L396.43,255.06 L397.24,255.06 L398.05,255.06 L398.85,255.06 L399.66,255.06 L400.47,255.06 L401.27,255.06 L402.08,255.06 L402.89,255.06 L403.69,255.06 L404.50,255.06 L405.31,255.06 L406.11,255.06 L406.92,255.06 L407.73,255.06 L408.53,255.06 L409.34,255.06 L410.15,255.06 L410.95,255.06 L411.76,255.06 L412.57,255.06 L413.37,255.06 L414.18,255.06 L414.99,255.06 L415.79,255.06 L416.60,255.06 L417.41,255.06 L418.21,255.06 L419.02,255.06 L419.83,255.06 L420.63,255.06 L421.44,255.06 L422.25,255.06 L423.05,255.06 L423.86,255.06 L424.67,255.06 L425.47,255.06 L426.28,255.06 L427.09,255.06 L427.89,255.06 L428.70,255.06 L429.51,255.06 L430.31,255.06 L431.12,255.06 L431.93,255.06 L432.73,255.06 L433.54,255.06 L434.35,255.06 L435.15,255.06 L435.96,255.06 L436.77,255.06 L437.57,255.06 L438.38,255.06 L439.19,255.06 L439.99,255.06 L440.80,255.06 L441.61,255.06 L442.41,255.06 L443.22,255.06 L444.03,255.06 L444.83,255.06 L445.64,255.06 L446.45,255.06 L447.25,255.06 L448.06,255.06 L448.87,255.06 L449.67,255.06 L450.48,255.06 L451.29,255.06 L452.09,255.06 L452.90,255.06 L453.71,255.06 L454.51,255.06 L455.32,255.06 L456.13,255.06 L456.93,255.06 L457.74,255.06 L458.55,255.06 L459.35,255.06 L460.16,255.06 L460.97,255.06 L461.77,255.06 L462.58,255.06 L463.39,255.06 L464.19,255.06 L465.00,255.06 L465.81,255.06 L466.61,255.06 L467.42,255.06 L468.23,255.06 L469.03,255.06 L469.84,255.06 L470.65,255.06 L471.45,255.06 L472.26,255.06 L473.07,255.06 L473.87,255.06 L474.68,255.06 L475.49,255.06 L476.29,255.06 L477.10,255.06 L477.91,255.06 L478.71,255.06 L479.52,255.06 L480.33,255.06 L481.13,255.06 L481.94,255.06 L482.75,255.06 L483.55,255.06 L484.36,255.06 L485.17,255.06 L485.97,255.06 L486.78,255.06 L487.59,255.06 L488.39,255.06 L489.20,255.06 L490.01,255.06 L490.81,255.06 L491.62,255.06 L492.43,255.06 L493.23,255.06 L494.04,255.06 L494.85,255.06 L495.65,255.06 L496.46,255.06 L497.27,255.06 L498.07,255.06 L498.88,255.06 L499.69,255.06 L500.49,255.06 L501.30,255.06 L502.11,255.06 L502.91,255.06 L503.72,255.06 L504.53,255.06 L505.33,255.06 L506.14,255.06 L506.95,255.06 L507.75,255.06 L508.56,255.06 L509.37,255.06 L510.17,255.06 L510.98,255.06 L511.79,255.06 L512.59,255.06 L513.40,255.06 L514.21,255.06 L515.01,255.06 L515.82,255.06 L516.63,255.06 L517.43,255.06 L518.24,255.06 L519.05,255.06 L519.85,255.06 L520.66,255.06 L521.47,255.06 L522.27,255.06 L523.08,255.06 L523.89,255.06 L524.69,255.06 L525.50,255.06 L526.31,255.06 L527.11,255.06 L527.92,255.06 L528.73,255.06 L529.53,255.06 L530.34,255.06 L531.15,255.06 L531.95,255.06 L532.76,255.06 L533.57,255.06 L534.37,255.06 L535.18,255.06 L535.99,255.06 L536.79,255.06 L537.60,255.06 L538.41,255.06 L539.21,255.06 L540.02,255.06 L540.83,255.06 L541.63,255.06 L542.44,255.06 L543.25,255.06 L544.05,255.06 L544.86,255.06 L545.67,255.06 L546.47,255.06 L547.28,255.06 L548.09,255.06 L548.89,255.06 L549.70,255.06 L550.51,255.06 L551.31,255.06 L552.12,255.06 L552.93,255.06 L553.73,255.06 L554.54,255.06 L555.35,255.06 L556.15,255.06 L556.96,255.06 L557.77,255.06 L558.57,255.06 L559.38,255.06 L560.19,255.06 L560.99,255.06 L561.80,255.06 L562.61,255.06 L563.41,255.06 L564.22,255.06 L565.03,255.06 L565.83,255.06 L566.64,255.06 L567.45,255.06 L568.25,255.06 L569.06,255.06 L569.87,255.06 L570.67,255.06 L571.48,255.06 L572.29,255.06 L573.09,255.06 L573.90,255.06 L574.71,255.06 L575.51,255.06 L576.32,255.06 L577.13,255.06 L577.93,255.06 L578.74,255.06 L579.55,255.06 L580.35,255.06 L581.16,255.06 L581.97,255.06 L582.77,255.06 L583.58,255.06 L584.39,255.06 L585.19,255.06 L586.00,255.06 " fill="none" stroke="#2f6fec" stroke-width="1.8"/><text x="582" y="250" font-size="9" fill="#2f6fec" text-anchor="end">position</text><path d="M344.00,323.29 L344.81,293.92 L345.61,274.51 L346.42,262.76 L347.23,256.78 L348.03,255.06 L348.84,256.36 L349.65,259.72 L350.45,264.40 L351.26,269.83 L352.07,275.57 L352.87,281.33 L353.68,286.89 L354.49,292.10 L355.29,296.88 L356.10,301.19 L356.91,305.00 L357.71,308.33 L358.52,311.20 L359.33,313.65 L360.13,315.71 L360.94,317.43 L361.75,318.84 L362.55,319.99 L363.36,320.91 L364.17,321.64 L364.97,322.21 L365.78,322.65 L366.59,322.98 L367.39,323.22 L368.20,323.39 L369.01,323.51 L369.81,323.58 L370.62,323.62 L371.43,323.64 L372.23,323.63 L373.04,323.62 L373.85,323.60 L374.65,323.57 L375.46,323.55 L376.27,323.52 L377.07,323.49 L377.88,323.46 L378.69,323.44 L379.49,323.41 L380.30,323.39 L381.11,323.38 L381.91,323.36 L382.72,323.35 L383.53,323.34 L384.33,323.33 L385.14,323.32 L385.95,323.31 L386.75,323.31 L387.56,323.30 L388.37,323.30 L389.17,323.30 L389.98,323.30 L390.79,323.29 L391.59,323.29 L392.40,323.29 L393.21,323.29 L394.01,323.29 L394.82,323.29 L395.63,323.29 L396.43,323.29 L397.24,323.29 L398.05,323.29 L398.85,323.29 L399.66,323.29 L400.47,323.29 L401.27,323.29 L402.08,323.29 L402.89,323.29 L403.69,323.29 L404.50,323.29 L405.31,323.29 L406.11,323.29 L406.92,323.29 L407.73,323.29 L408.53,323.29 L409.34,323.29 L410.15,323.29 L410.95,323.29 L411.76,323.29 L412.57,323.29 L413.37,323.29 L414.18,323.29 L414.99,323.29 L415.79,323.29 L416.60,323.29 L417.41,323.29 L418.21,323.29 L419.02,323.29 L419.83,323.29 L420.63,323.29 L421.44,323.29 L422.25,323.29 L423.05,323.29 L423.86,323.29 L424.67,323.29 L425.47,323.29 L426.28,323.29 L427.09,323.29 L427.89,323.29 L428.70,323.29 L429.51,323.29 L430.31,323.29 L431.12,323.29 L431.93,323.29 L432.73,323.29 L433.54,323.29 L434.35,323.29 L435.15,323.29 L435.96,323.29 L436.77,323.29 L437.57,323.29 L438.38,323.29 L439.19,323.29 L439.99,323.29 L440.80,323.29 L441.61,323.29 L442.41,323.29 L443.22,323.29 L444.03,323.29 L444.83,323.29 L445.64,323.29 L446.45,323.29 L447.25,323.29 L448.06,323.29 L448.87,323.29 L449.67,323.29 L450.48,323.29 L451.29,323.29 L452.09,323.29 L452.90,323.29 L453.71,323.29 L454.51,323.29 L455.32,323.29 L456.13,323.29 L456.93,323.29 L457.74,323.29 L458.55,323.29 L459.35,323.29 L460.16,323.29 L460.97,323.29 L461.77,323.29 L462.58,323.29 L463.39,323.29 L464.19,323.29 L465.00,323.29 L465.81,323.29 L466.61,323.29 L467.42,323.29 L468.23,323.29 L469.03,323.29 L469.84,323.29 L470.65,323.29 L471.45,323.29 L472.26,323.29 L473.07,323.29 L473.87,323.29 L474.68,323.29 L475.49,323.29 L476.29,323.29 L477.10,323.29 L477.91,323.29 L478.71,323.29 L479.52,323.29 L480.33,323.29 L481.13,323.29 L481.94,323.29 L482.75,323.29 L483.55,323.29 L484.36,323.29 L485.17,323.29 L485.97,323.29 L486.78,323.29 L487.59,323.29 L488.39,323.29 L489.20,323.29 L490.01,323.29 L490.81,323.29 L491.62,323.29 L492.43,323.29 L493.23,323.29 L494.04,323.29 L494.85,323.29 L495.65,323.29 L496.46,323.29 L497.27,323.29 L498.07,323.29 L498.88,323.29 L499.69,323.29 L500.49,323.29 L501.30,323.29 L502.11,323.29 L502.91,323.29 L503.72,323.29 L504.53,323.29 L505.33,323.29 L506.14,323.29 L506.95,323.29 L507.75,323.29 L508.56,323.29 L509.37,323.29 L510.17,323.29 L510.98,323.29 L511.79,323.29 L512.59,323.29 L513.40,323.29 L514.21,323.29 L515.01,323.29 L515.82,323.29 L516.63,323.29 L517.43,323.29 L518.24,323.29 L519.05,323.29 L519.85,323.29 L520.66,323.29 L521.47,323.29 L522.27,323.29 L523.08,323.29 L523.89,323.29 L524.69,323.29 L525.50,323.29 L526.31,323.29 L527.11,323.29 L527.92,323.29 L528.73,323.29 L529.53,323.29 L530.34,323.29 L531.15,323.29 L531.95,323.29 L532.76,323.29 L533.57,323.29 L534.37,323.29 L535.18,323.29 L535.99,323.29 L536.79,323.29 L537.60,323.29 L538.41,323.29 L539.21,323.29 L540.02,323.29 L540.83,323.29 L541.63,323.29 L542.44,323.29 L543.25,323.29 L544.05,323.29 L544.86,323.29 L545.67,323.29 L546.47,323.29 L547.28,323.29 L548.09,323.29 L548.89,323.29 L549.70,323.29 L550.51,323.29 L551.31,323.29 L552.12,323.29 L552.93,323.29 L553.73,323.29 L554.54,323.29 L555.35,323.29 L556.15,323.29 L556.96,323.29 L557.77,323.29 L558.57,323.29 L559.38,323.29 L560.19,323.29 L560.99,323.29 L561.80,323.29 L562.61,323.29 L563.41,323.29 L564.22,323.29 L565.03,323.29 L565.83,323.29 L566.64,323.29 L567.45,323.29 L568.25,323.29 L569.06,323.29 L569.87,323.29 L570.67,323.29 L571.48,323.29 L572.29,323.29 L573.09,323.29 L573.90,323.29 L574.71,323.29 L575.51,323.29 L576.32,323.29 L577.13,323.29 L577.93,323.29 L578.74,323.29 L579.55,323.29 L580.35,323.29 L581.16,323.29 L581.97,323.29 L582.77,323.29 L583.58,323.29 L584.39,323.29 L585.19,323.29 L586.00,323.29 " fill="none" stroke="#e8833a" stroke-width="1.8" stroke-dasharray="4 3"/><text x="582" y="262" font-size="9" fill="#e8833a" text-anchor="end">velocity (norm.)</text><rect x="644" y="238" width="242" height="116" fill="#fafbfc" stroke="#e3e6ea"/><text x="644" y="229" font-size="12" font-weight="600" fill="#333">very bouncy 0.5/0.7</text><line x1="644" x2="886" y1="323.29413" y2="323.29413" stroke="#d5d9de" stroke-dasharray="3 3"/><text x="640" y="326.29413" font-size="9" fill="#888" text-anchor="end">0</text><line x1="644" x2="886" y1="255.05882" y2="255.05882" stroke="#d5d9de" stroke-dasharray="3 3"/><text x="640" y="258.05884" font-size="9" fill="#888" text-anchor="end">1</text><text x="886" y="368" font-size="9" fill="#888" text-anchor="end">1.50 s</text><line x1="724.6667" x2="724.6667" y1="238" y2="354" stroke="#d64545" stroke-width="1" stroke-dasharray="2 3"/><path d="M644.00,323.29 L644.81,323.16 L645.61,322.77 L646.42,322.13 L647.23,321.25 L648.03,320.15 L648.84,318.84 L649.65,317.33 L650.45,315.64 L651.26,313.77 L652.07,311.75 L652.87,309.58 L653.68,307.28 L654.49,304.86 L655.29,302.34 L656.10,299.73 L656.91,297.04 L657.71,294.29 L658.52,291.49 L659.33,288.65 L660.13,285.79 L660.94,282.91 L661.75,280.03 L662.55,277.16 L663.36,274.32 L664.17,271.50 L664.97,268.72 L665.78,266.00 L666.59,263.33 L667.39,260.73 L668.20,258.20 L669.01,255.75 L669.81,253.40 L670.62,251.13 L671.43,248.97 L672.23,246.90 L673.04,244.95 L673.85,243.11 L674.65,241.38 L675.46,239.77 L676.27,238.28 L677.07,236.91 L677.88,235.66 L678.69,234.53 L679.49,233.52 L680.30,232.63 L681.11,231.86 L681.91,231.21 L682.72,230.68 L683.53,230.26 L684.33,229.95 L685.14,229.76 L685.95,229.66 L686.75,229.67 L687.56,229.78 L688.37,229.98 L689.17,230.27 L689.98,230.64 L690.79,231.10 L691.59,231.63 L692.40,232.23 L693.21,232.90 L694.01,233.63 L694.82,234.42 L695.63,235.26 L696.43,236.14 L697.24,237.06 L698.05,238.02 L698.85,239.01 L699.66,240.03 L700.47,241.06 L701.27,242.11 L702.08,243.18 L702.89,244.25 L703.69,245.32 L704.50,246.39 L705.31,247.45 L706.11,248.51 L706.92,249.55 L707.73,250.57 L708.53,251.57 L709.34,252.55 L710.15,253.50 L710.95,254.43 L711.76,255.32 L712.57,256.18 L713.37,257.00 L714.18,257.78 L714.99,258.53 L715.79,259.23 L716.60,259.89 L717.41,260.51 L718.21,261.08 L719.02,261.61 L719.83,262.10 L720.63,262.54 L721.44,262.93 L722.25,263.28 L723.05,263.58 L723.86,263.84 L724.67,264.06 L725.47,264.23 L726.28,264.36 L727.09,264.45 L727.89,264.51 L728.70,264.52 L729.51,264.49 L730.31,264.43 L731.12,264.34 L731.93,264.21 L732.73,264.05 L733.54,263.87 L734.35,263.65 L735.15,263.41 L735.96,263.15 L736.77,262.87 L737.57,262.56 L738.38,262.24 L739.19,261.90 L739.99,261.55 L740.80,261.19 L741.61,260.81 L742.41,260.43 L743.22,260.04 L744.03,259.65 L744.83,259.25 L745.64,258.85 L746.45,258.45 L747.25,258.06 L748.06,257.66 L748.87,257.27 L749.67,256.89 L750.48,256.51 L751.29,256.14 L752.09,255.78 L752.90,255.44 L753.71,255.10 L754.51,254.77 L755.32,254.46 L756.13,254.16 L756.93,253.88 L757.74,253.61 L758.55,253.36 L759.35,253.12 L760.16,252.90 L760.97,252.70 L761.77,252.51 L762.58,252.34 L763.39,252.19 L764.19,252.05 L765.00,251.93 L765.81,251.83 L766.61,251.74 L767.42,251.67 L768.23,251.61 L769.03,251.57 L769.84,251.55 L770.65,251.54 L771.45,251.54 L772.26,251.56 L773.07,251.59 L773.87,251.63 L774.68,251.68 L775.49,251.75 L776.29,251.82 L777.10,251.91 L777.91,252.00 L778.71,252.11 L779.52,252.22 L780.33,252.33 L781.13,252.46 L781.94,252.59 L782.75,252.72 L783.55,252.86 L784.36,253.00 L785.17,253.14 L785.97,253.29 L786.78,253.44 L787.59,253.59 L788.39,253.73 L789.20,253.88 L790.01,254.03 L790.81,254.18 L791.62,254.32 L792.43,254.46 L793.23,254.60 L794.04,254.73 L794.85,254.87 L795.65,254.99 L796.46,255.12 L797.27,255.23 L798.07,255.35 L798.88,255.45 L799.69,255.56 L800.49,255.65 L801.30,255.74 L802.11,255.83 L802.91,255.91 L803.72,255.98 L804.53,256.05 L805.33,256.11 L806.14,256.16 L806.95,256.21 L807.75,256.25 L808.56,256.28 L809.37,256.31 L810.17,256.33 L810.98,256.35 L811.79,256.36 L812.59,256.37 L813.40,256.37 L814.21,256.37 L815.01,256.36 L815.82,256.34 L816.63,256.32 L817.43,256.30 L818.24,256.28 L819.05,256.24 L819.85,256.21 L820.66,256.17 L821.47,256.13 L822.27,256.09 L823.08,256.05 L823.89,256.00 L824.69,255.95 L825.50,255.90 L826.31,255.85 L827.11,255.79 L827.92,255.74 L828.73,255.69 L829.53,255.63 L830.34,255.58 L831.15,255.52 L831.95,255.46 L832.76,255.41 L833.57,255.36 L834.37,255.30 L835.18,255.25 L835.99,255.20 L836.79,255.15 L837.60,255.10 L838.41,255.06 L839.21,255.01 L840.02,254.97 L840.83,254.93 L841.63,254.89 L842.44,254.85 L843.25,254.82 L844.05,254.79 L844.86,254.75 L845.67,254.73 L846.47,254.70 L847.28,254.68 L848.09,254.66 L848.89,254.64 L849.70,254.62 L850.51,254.61 L851.31,254.60 L852.12,254.59 L852.93,254.58 L853.73,254.57 L854.54,254.57 L855.35,254.57 L856.15,254.57 L856.96,254.57 L857.77,254.58 L858.57,254.58 L859.38,254.59 L860.19,254.60 L860.99,254.61 L861.80,254.62 L862.61,254.64 L863.41,254.65 L864.22,254.67 L865.03,254.68 L865.83,254.70 L866.64,254.72 L867.45,254.74 L868.25,254.76 L869.06,254.78 L869.87,254.80 L870.67,254.82 L871.48,254.84 L872.29,254.86 L873.09,254.88 L873.90,254.90 L874.71,254.92 L875.51,254.94 L876.32,254.96 L877.13,254.98 L877.93,255.00 L878.74,255.02 L879.55,255.04 L880.35,255.05 L881.16,255.07 L881.97,255.09 L882.77,255.10 L883.58,255.12 L884.39,255.13 L885.19,255.14 L886.00,255.16 " fill="none" stroke="#2f6fec" stroke-width="1.8"/><text x="882" y="250" font-size="9" fill="#2f6fec" text-anchor="end">position</text><path d="M644.00,323.29 L644.81,317.03 L645.61,311.03 L646.42,305.29 L647.23,299.84 L648.03,294.68 L648.84,289.82 L649.65,285.27 L650.45,281.03 L651.26,277.12 L652.07,273.53 L652.87,270.26 L653.68,267.32 L654.49,264.71 L655.29,262.42 L656.10,260.45 L656.91,258.80 L657.71,257.46 L658.52,256.42 L659.33,255.68 L660.13,255.23 L660.94,255.06 L661.75,255.16 L662.55,255.52 L663.36,256.13 L664.17,256.98 L664.97,258.05 L665.78,259.33 L666.59,260.82 L667.39,262.49 L668.20,264.34 L669.01,266.35 L669.81,268.50 L670.62,270.78 L671.43,273.19 L672.23,275.70 L673.04,278.30 L673.85,280.98 L674.65,283.72 L675.46,286.52 L676.27,289.35 L677.07,292.21 L677.88,295.09 L678.69,297.97 L679.49,300.84 L680.30,303.69 L681.11,306.51 L681.91,309.29 L682.72,312.02 L683.53,314.70 L684.33,317.31 L685.14,319.85 L685.95,322.30 L686.75,324.67 L687.56,326.95 L688.37,329.12 L689.17,331.20 L689.98,333.17 L690.79,335.02 L691.59,336.77 L692.40,338.39 L693.21,339.90 L694.01,341.28 L694.82,342.55 L695.63,343.69 L696.43,344.72 L697.24,345.62 L698.05,346.40 L698.85,347.07 L699.66,347.61 L700.47,348.05 L701.27,348.37 L702.08,348.58 L702.89,348.69 L703.69,348.69 L704.50,348.60 L705.31,348.41 L706.11,348.13 L706.92,347.76 L707.73,347.32 L708.53,346.79 L709.34,346.20 L710.15,345.54 L710.95,344.81 L711.76,344.03 L712.57,343.20 L713.37,342.33 L714.18,341.41 L714.99,340.45 L715.79,339.47 L716.60,338.45 L717.41,337.42 L718.21,336.37 L719.02,335.31 L719.83,334.24 L720.63,333.17 L721.44,332.10 L722.25,331.03 L723.05,329.98 L723.86,328.94 L724.67,327.91 L725.47,326.90 L726.28,325.92 L727.09,324.97 L727.89,324.04 L728.70,323.14 L729.51,322.28 L730.31,321.45 L731.12,320.67 L731.93,319.92 L732.73,319.21 L733.54,318.54 L734.35,317.92 L735.15,317.34 L735.96,316.80 L736.77,316.31 L737.57,315.87 L738.38,315.47 L739.19,315.12 L739.99,314.81 L740.80,314.54 L741.61,314.32 L742.41,314.14 L743.22,314.00 L744.03,313.91 L744.83,313.85 L745.64,313.83 L746.45,313.85 L747.25,313.91 L748.06,314.00 L748.87,314.12 L749.67,314.28 L750.48,314.46 L751.29,314.67 L752.09,314.91 L752.90,315.17 L753.71,315.45 L754.51,315.75 L755.32,316.07 L756.13,316.41 L756.93,316.76 L757.74,317.12 L758.55,317.49 L759.35,317.87 L760.16,318.26 L760.97,318.66 L761.77,319.05 L762.58,319.45 L763.39,319.85 L764.19,320.25 L765.00,320.64 L765.81,321.03 L766.61,321.42 L767.42,321.80 L768.23,322.17 L769.03,322.53 L769.84,322.88 L770.65,323.21 L771.45,323.54 L772.26,323.85 L773.07,324.15 L773.87,324.44 L774.68,324.71 L775.49,324.96 L776.29,325.20 L777.10,325.42 L777.91,325.63 L778.71,325.82 L779.52,325.99 L780.33,326.15 L781.13,326.29 L781.94,326.41 L782.75,326.51 L783.55,326.60 L784.36,326.68 L785.17,326.73 L785.97,326.78 L786.78,326.80 L787.59,326.82 L788.39,326.81 L789.20,326.80 L790.01,326.77 L790.81,326.73 L791.62,326.68 L792.43,326.61 L793.23,326.54 L794.04,326.45 L794.85,326.36 L795.65,326.26 L796.46,326.15 L797.27,326.03 L798.07,325.91 L798.88,325.78 L799.69,325.65 L800.49,325.51 L801.30,325.37 L802.11,325.23 L802.91,325.08 L803.72,324.93 L804.53,324.79 L805.33,324.64 L806.14,324.49 L806.95,324.34 L807.75,324.20 L808.56,324.05 L809.37,323.91 L810.17,323.77 L810.98,323.64 L811.79,323.50 L812.59,323.38 L813.40,323.25 L814.21,323.13 L815.01,323.02 L815.82,322.91 L816.63,322.81 L817.43,322.71 L818.24,322.62 L819.05,322.53 L819.85,322.46 L820.66,322.38 L821.47,322.32 L822.27,322.25 L823.08,322.20 L823.89,322.15 L824.69,322.11 L825.50,322.07 L826.31,322.05 L827.11,322.02 L827.92,322.00 L828.73,321.99 L829.53,321.98 L830.34,321.98 L831.15,321.99 L831.95,322.00 L832.76,322.01 L833.57,322.03 L834.37,322.05 L835.18,322.07 L835.99,322.10 L836.79,322.14 L837.60,322.17 L838.41,322.21 L839.21,322.26 L840.02,322.30 L840.83,322.35 L841.63,322.40 L842.44,322.45 L843.25,322.50 L844.05,322.55 L844.86,322.61 L845.67,322.66 L846.47,322.72 L847.28,322.77 L848.09,322.83 L848.89,322.88 L849.70,322.94 L850.51,322.99 L851.31,323.04 L852.12,323.10 L852.93,323.15 L853.73,323.20 L854.54,323.24 L855.35,323.29 L856.15,323.34 L856.96,323.38 L857.77,323.42 L858.57,323.46 L859.38,323.50 L860.19,323.53 L860.99,323.56 L861.80,323.59 L862.61,323.62 L863.41,323.65 L864.22,323.67 L865.03,323.69 L865.83,323.71 L866.64,323.73 L867.45,323.74 L868.25,323.75 L869.06,323.76 L869.87,323.77 L870.67,323.78 L871.48,323.78 L872.29,323.78 L873.09,323.78 L873.90,323.78 L874.71,323.78 L875.51,323.77 L876.32,323.76 L877.13,323.75 L877.93,323.74 L878.74,323.73 L879.55,323.72 L880.35,323.70 L881.16,323.69 L881.97,323.67 L882.77,323.65 L883.58,323.64 L884.39,323.62 L885.19,323.60 L886.00,323.58 " fill="none" stroke="#e8833a" stroke-width="1.8" stroke-dasharray="4 3"/><text x="882" y="262" font-size="9" fill="#e8833a" text-anchor="end">velocity (norm.)</text></svg> \ No newline at end of file diff --git a/app/vendor/rune/demo/motion/tokens.png b/app/vendor/rune/demo/motion/tokens.png new file mode 100644 index 0000000..9e2ae8e Binary files /dev/null and b/app/vendor/rune/demo/motion/tokens.png differ diff --git a/app/vendor/rune/demo/motion/tokens.svg b/app/vendor/rune/demo/motion/tokens.svg new file mode 100644 index 0000000..9959a06 --- /dev/null +++ b/app/vendor/rune/demo/motion/tokens.svg @@ -0,0 +1 @@ +<svg xmlns="http://www.w3.org/2000/svg" width="1200" height="1200" viewBox="0 0 1200 1200" font-family="-apple-system, Helvetica, sans-serif"><rect width="100%" height="100%" fill="white"/><text x="16" y="26" font-size="16" font-weight="600" fill="#222">Kit motion tokens: position (blue), velocity (orange), duration (red)</text><rect x="44" y="68" width="242" height="116" fill="#fafbfc" stroke="#e3e6ea"/><text x="44" y="59" font-size="12" font-weight="600" fill="#333">instant 0.1/0</text><line x1="44" x2="286" y1="153.29411" y2="153.29411" stroke="#d5d9de" stroke-dasharray="3 3"/><text x="40" y="156.29411" font-size="9" fill="#888" text-anchor="end">0</text><line x1="44" x2="286" y1="85.05882" y2="85.05882" stroke="#d5d9de" stroke-dasharray="3 3"/><text x="40" y="88.05882" font-size="9" fill="#888" text-anchor="end">1</text><text x="286" y="198" font-size="9" fill="#888" text-anchor="end">1.20 s</text><line x1="64.166664" x2="64.166664" y1="68" y2="184" stroke="#d64545" stroke-width="1" stroke-dasharray="2 3"/><path d="M44.00,153.29 L44.81,151.47 L45.61,147.08 L46.42,141.37 L47.23,135.13 L48.03,128.88 L48.84,122.94 L49.65,117.47 L50.45,112.57 L51.26,108.24 L52.07,104.48 L52.87,101.24 L53.68,98.49 L54.49,96.16 L55.29,94.20 L56.10,92.56 L56.91,91.20 L57.71,90.08 L58.52,89.15 L59.33,88.38 L60.13,87.76 L60.94,87.24 L61.75,86.83 L62.55,86.49 L63.36,86.21 L64.17,85.99 L64.97,85.81 L65.78,85.66 L66.59,85.54 L67.39,85.45 L68.20,85.37 L69.01,85.31 L69.81,85.26 L70.62,85.22 L71.43,85.19 L72.23,85.16 L73.04,85.14 L73.85,85.12 L74.65,85.11 L75.46,85.10 L76.27,85.09 L77.07,85.08 L77.88,85.08 L78.69,85.08 L79.49,85.07 L80.30,85.07 L81.11,85.07 L81.91,85.07 L82.72,85.06 L83.53,85.06 L84.33,85.06 L85.14,85.06 L85.95,85.06 L86.75,85.06 L87.56,85.06 L88.37,85.06 L89.17,85.06 L89.98,85.06 L90.79,85.06 L91.59,85.06 L92.40,85.06 L93.21,85.06 L94.01,85.06 L94.82,85.06 L95.63,85.06 L96.43,85.06 L97.24,85.06 L98.05,85.06 L98.85,85.06 L99.66,85.06 L100.47,85.06 L101.27,85.06 L102.08,85.06 L102.89,85.06 L103.69,85.06 L104.50,85.06 L105.31,85.06 L106.11,85.06 L106.92,85.06 L107.73,85.06 L108.53,85.06 L109.34,85.06 L110.15,85.06 L110.95,85.06 L111.76,85.06 L112.57,85.06 L113.37,85.06 L114.18,85.06 L114.99,85.06 L115.79,85.06 L116.60,85.06 L117.41,85.06 L118.21,85.06 L119.02,85.06 L119.83,85.06 L120.63,85.06 L121.44,85.06 L122.25,85.06 L123.05,85.06 L123.86,85.06 L124.67,85.06 L125.47,85.06 L126.28,85.06 L127.09,85.06 L127.89,85.06 L128.70,85.06 L129.51,85.06 L130.31,85.06 L131.12,85.06 L131.93,85.06 L132.73,85.06 L133.54,85.06 L134.35,85.06 L135.15,85.06 L135.96,85.06 L136.77,85.06 L137.57,85.06 L138.38,85.06 L139.19,85.06 L139.99,85.06 L140.80,85.06 L141.61,85.06 L142.41,85.06 L143.22,85.06 L144.03,85.06 L144.83,85.06 L145.64,85.06 L146.45,85.06 L147.25,85.06 L148.06,85.06 L148.87,85.06 L149.67,85.06 L150.48,85.06 L151.29,85.06 L152.09,85.06 L152.90,85.06 L153.71,85.06 L154.51,85.06 L155.32,85.06 L156.13,85.06 L156.93,85.06 L157.74,85.06 L158.55,85.06 L159.35,85.06 L160.16,85.06 L160.97,85.06 L161.77,85.06 L162.58,85.06 L163.39,85.06 L164.19,85.06 L165.00,85.06 L165.81,85.06 L166.61,85.06 L167.42,85.06 L168.23,85.06 L169.03,85.06 L169.84,85.06 L170.65,85.06 L171.45,85.06 L172.26,85.06 L173.07,85.06 L173.87,85.06 L174.68,85.06 L175.49,85.06 L176.29,85.06 L177.10,85.06 L177.91,85.06 L178.71,85.06 L179.52,85.06 L180.33,85.06 L181.13,85.06 L181.94,85.06 L182.75,85.06 L183.55,85.06 L184.36,85.06 L185.17,85.06 L185.97,85.06 L186.78,85.06 L187.59,85.06 L188.39,85.06 L189.20,85.06 L190.01,85.06 L190.81,85.06 L191.62,85.06 L192.43,85.06 L193.23,85.06 L194.04,85.06 L194.85,85.06 L195.65,85.06 L196.46,85.06 L197.27,85.06 L198.07,85.06 L198.88,85.06 L199.69,85.06 L200.49,85.06 L201.30,85.06 L202.11,85.06 L202.91,85.06 L203.72,85.06 L204.53,85.06 L205.33,85.06 L206.14,85.06 L206.95,85.06 L207.75,85.06 L208.56,85.06 L209.37,85.06 L210.17,85.06 L210.98,85.06 L211.79,85.06 L212.59,85.06 L213.40,85.06 L214.21,85.06 L215.01,85.06 L215.82,85.06 L216.63,85.06 L217.43,85.06 L218.24,85.06 L219.05,85.06 L219.85,85.06 L220.66,85.06 L221.47,85.06 L222.27,85.06 L223.08,85.06 L223.89,85.06 L224.69,85.06 L225.50,85.06 L226.31,85.06 L227.11,85.06 L227.92,85.06 L228.73,85.06 L229.53,85.06 L230.34,85.06 L231.15,85.06 L231.95,85.06 L232.76,85.06 L233.57,85.06 L234.37,85.06 L235.18,85.06 L235.99,85.06 L236.79,85.06 L237.60,85.06 L238.41,85.06 L239.21,85.06 L240.02,85.06 L240.83,85.06 L241.63,85.06 L242.44,85.06 L243.25,85.06 L244.05,85.06 L244.86,85.06 L245.67,85.06 L246.47,85.06 L247.28,85.06 L248.09,85.06 L248.89,85.06 L249.70,85.06 L250.51,85.06 L251.31,85.06 L252.12,85.06 L252.93,85.06 L253.73,85.06 L254.54,85.06 L255.35,85.06 L256.15,85.06 L256.96,85.06 L257.77,85.06 L258.57,85.06 L259.38,85.06 L260.19,85.06 L260.99,85.06 L261.80,85.06 L262.61,85.06 L263.41,85.06 L264.22,85.06 L265.03,85.06 L265.83,85.06 L266.64,85.06 L267.45,85.06 L268.25,85.06 L269.06,85.06 L269.87,85.06 L270.67,85.06 L271.48,85.06 L272.29,85.06 L273.09,85.06 L273.90,85.06 L274.71,85.06 L275.51,85.06 L276.32,85.06 L277.13,85.06 L277.93,85.06 L278.74,85.06 L279.55,85.06 L280.35,85.06 L281.16,85.06 L281.97,85.06 L282.77,85.06 L283.58,85.06 L284.39,85.06 L285.19,85.06 L286.00,85.06 " fill="none" stroke="#2f6fec" stroke-width="1.8"/><text x="282" y="80" font-size="9" fill="#2f6fec" text-anchor="end">position</text><path d="M44.00,153.29 L44.81,117.04 L45.61,96.89 L46.42,87.49 L47.23,85.06 L48.03,86.96 L48.84,91.38 L49.65,97.11 L50.45,103.36 L51.26,109.60 L52.07,115.53 L52.87,120.99 L53.68,125.88 L54.49,130.20 L55.29,133.95 L56.10,137.17 L56.91,139.92 L57.71,142.24 L58.52,144.19 L59.33,145.82 L60.13,147.18 L60.94,148.30 L61.75,149.22 L62.55,149.98 L63.36,150.61 L64.17,151.12 L64.97,151.53 L65.78,151.87 L66.59,152.15 L67.39,152.37 L68.20,152.55 L69.01,152.70 L69.81,152.81 L70.62,152.91 L71.43,152.99 L72.23,153.05 L73.04,153.10 L73.85,153.14 L74.65,153.17 L75.46,153.19 L76.27,153.21 L77.07,153.23 L77.88,153.24 L78.69,153.25 L79.49,153.26 L80.30,153.27 L81.11,153.27 L81.91,153.28 L82.72,153.28 L83.53,153.28 L84.33,153.29 L85.14,153.29 L85.95,153.29 L86.75,153.29 L87.56,153.29 L88.37,153.29 L89.17,153.29 L89.98,153.29 L90.79,153.29 L91.59,153.29 L92.40,153.29 L93.21,153.29 L94.01,153.29 L94.82,153.29 L95.63,153.29 L96.43,153.29 L97.24,153.29 L98.05,153.29 L98.85,153.29 L99.66,153.29 L100.47,153.29 L101.27,153.29 L102.08,153.29 L102.89,153.29 L103.69,153.29 L104.50,153.29 L105.31,153.29 L106.11,153.29 L106.92,153.29 L107.73,153.29 L108.53,153.29 L109.34,153.29 L110.15,153.29 L110.95,153.29 L111.76,153.29 L112.57,153.29 L113.37,153.29 L114.18,153.29 L114.99,153.29 L115.79,153.29 L116.60,153.29 L117.41,153.29 L118.21,153.29 L119.02,153.29 L119.83,153.29 L120.63,153.29 L121.44,153.29 L122.25,153.29 L123.05,153.29 L123.86,153.29 L124.67,153.29 L125.47,153.29 L126.28,153.29 L127.09,153.29 L127.89,153.29 L128.70,153.29 L129.51,153.29 L130.31,153.29 L131.12,153.29 L131.93,153.29 L132.73,153.29 L133.54,153.29 L134.35,153.29 L135.15,153.29 L135.96,153.29 L136.77,153.29 L137.57,153.29 L138.38,153.29 L139.19,153.29 L139.99,153.29 L140.80,153.29 L141.61,153.29 L142.41,153.29 L143.22,153.29 L144.03,153.29 L144.83,153.29 L145.64,153.29 L146.45,153.29 L147.25,153.29 L148.06,153.29 L148.87,153.29 L149.67,153.29 L150.48,153.29 L151.29,153.29 L152.09,153.29 L152.90,153.29 L153.71,153.29 L154.51,153.29 L155.32,153.29 L156.13,153.29 L156.93,153.29 L157.74,153.29 L158.55,153.29 L159.35,153.29 L160.16,153.29 L160.97,153.29 L161.77,153.29 L162.58,153.29 L163.39,153.29 L164.19,153.29 L165.00,153.29 L165.81,153.29 L166.61,153.29 L167.42,153.29 L168.23,153.29 L169.03,153.29 L169.84,153.29 L170.65,153.29 L171.45,153.29 L172.26,153.29 L173.07,153.29 L173.87,153.29 L174.68,153.29 L175.49,153.29 L176.29,153.29 L177.10,153.29 L177.91,153.29 L178.71,153.29 L179.52,153.29 L180.33,153.29 L181.13,153.29 L181.94,153.29 L182.75,153.29 L183.55,153.29 L184.36,153.29 L185.17,153.29 L185.97,153.29 L186.78,153.29 L187.59,153.29 L188.39,153.29 L189.20,153.29 L190.01,153.29 L190.81,153.29 L191.62,153.29 L192.43,153.29 L193.23,153.29 L194.04,153.29 L194.85,153.29 L195.65,153.29 L196.46,153.29 L197.27,153.29 L198.07,153.29 L198.88,153.29 L199.69,153.29 L200.49,153.29 L201.30,153.29 L202.11,153.29 L202.91,153.29 L203.72,153.29 L204.53,153.29 L205.33,153.29 L206.14,153.29 L206.95,153.29 L207.75,153.29 L208.56,153.29 L209.37,153.29 L210.17,153.29 L210.98,153.29 L211.79,153.29 L212.59,153.29 L213.40,153.29 L214.21,153.29 L215.01,153.29 L215.82,153.29 L216.63,153.29 L217.43,153.29 L218.24,153.29 L219.05,153.29 L219.85,153.29 L220.66,153.29 L221.47,153.29 L222.27,153.29 L223.08,153.29 L223.89,153.29 L224.69,153.29 L225.50,153.29 L226.31,153.29 L227.11,153.29 L227.92,153.29 L228.73,153.29 L229.53,153.29 L230.34,153.29 L231.15,153.29 L231.95,153.29 L232.76,153.29 L233.57,153.29 L234.37,153.29 L235.18,153.29 L235.99,153.29 L236.79,153.29 L237.60,153.29 L238.41,153.29 L239.21,153.29 L240.02,153.29 L240.83,153.29 L241.63,153.29 L242.44,153.29 L243.25,153.29 L244.05,153.29 L244.86,153.29 L245.67,153.29 L246.47,153.29 L247.28,153.29 L248.09,153.29 L248.89,153.29 L249.70,153.29 L250.51,153.29 L251.31,153.29 L252.12,153.29 L252.93,153.29 L253.73,153.29 L254.54,153.29 L255.35,153.29 L256.15,153.29 L256.96,153.29 L257.77,153.29 L258.57,153.29 L259.38,153.29 L260.19,153.29 L260.99,153.29 L261.80,153.29 L262.61,153.29 L263.41,153.29 L264.22,153.29 L265.03,153.29 L265.83,153.29 L266.64,153.29 L267.45,153.29 L268.25,153.29 L269.06,153.29 L269.87,153.29 L270.67,153.29 L271.48,153.29 L272.29,153.29 L273.09,153.29 L273.90,153.29 L274.71,153.29 L275.51,153.29 L276.32,153.29 L277.13,153.29 L277.93,153.29 L278.74,153.29 L279.55,153.29 L280.35,153.29 L281.16,153.29 L281.97,153.29 L282.77,153.29 L283.58,153.29 L284.39,153.29 L285.19,153.29 L286.00,153.29 " fill="none" stroke="#e8833a" stroke-width="1.8" stroke-dasharray="4 3"/><text x="282" y="92" font-size="9" fill="#e8833a" text-anchor="end">velocity (norm.)</text><rect x="344" y="68" width="242" height="116" fill="#fafbfc" stroke="#e3e6ea"/><text x="344" y="59" font-size="12" font-weight="600" fill="#333">instant exit 0.1/0</text><line x1="344" x2="586" y1="153.29411" y2="153.29411" stroke="#d5d9de" stroke-dasharray="3 3"/><text x="340" y="156.29411" font-size="9" fill="#888" text-anchor="end">0</text><line x1="344" x2="586" y1="85.05882" y2="85.05882" stroke="#d5d9de" stroke-dasharray="3 3"/><text x="340" y="88.05882" font-size="9" fill="#888" text-anchor="end">1</text><text x="586" y="198" font-size="9" fill="#888" text-anchor="end">1.20 s</text><line x1="364.16666" x2="364.16666" y1="68" y2="184" stroke="#d64545" stroke-width="1" stroke-dasharray="2 3"/><path d="M344.00,153.29 L344.81,151.47 L345.61,147.08 L346.42,141.37 L347.23,135.13 L348.03,128.88 L348.84,122.94 L349.65,117.47 L350.45,112.57 L351.26,108.24 L352.07,104.48 L352.87,101.24 L353.68,98.49 L354.49,96.16 L355.29,94.20 L356.10,92.56 L356.91,91.20 L357.71,90.08 L358.52,89.15 L359.33,88.38 L360.13,87.76 L360.94,87.24 L361.75,86.83 L362.55,86.49 L363.36,86.21 L364.17,85.99 L364.97,85.81 L365.78,85.66 L366.59,85.54 L367.39,85.45 L368.20,85.37 L369.01,85.31 L369.81,85.26 L370.62,85.22 L371.43,85.19 L372.23,85.16 L373.04,85.14 L373.85,85.12 L374.65,85.11 L375.46,85.10 L376.27,85.09 L377.07,85.08 L377.88,85.08 L378.69,85.08 L379.49,85.07 L380.30,85.07 L381.11,85.07 L381.91,85.07 L382.72,85.06 L383.53,85.06 L384.33,85.06 L385.14,85.06 L385.95,85.06 L386.75,85.06 L387.56,85.06 L388.37,85.06 L389.17,85.06 L389.98,85.06 L390.79,85.06 L391.59,85.06 L392.40,85.06 L393.21,85.06 L394.01,85.06 L394.82,85.06 L395.63,85.06 L396.43,85.06 L397.24,85.06 L398.05,85.06 L398.85,85.06 L399.66,85.06 L400.47,85.06 L401.27,85.06 L402.08,85.06 L402.89,85.06 L403.69,85.06 L404.50,85.06 L405.31,85.06 L406.11,85.06 L406.92,85.06 L407.73,85.06 L408.53,85.06 L409.34,85.06 L410.15,85.06 L410.95,85.06 L411.76,85.06 L412.57,85.06 L413.37,85.06 L414.18,85.06 L414.99,85.06 L415.79,85.06 L416.60,85.06 L417.41,85.06 L418.21,85.06 L419.02,85.06 L419.83,85.06 L420.63,85.06 L421.44,85.06 L422.25,85.06 L423.05,85.06 L423.86,85.06 L424.67,85.06 L425.47,85.06 L426.28,85.06 L427.09,85.06 L427.89,85.06 L428.70,85.06 L429.51,85.06 L430.31,85.06 L431.12,85.06 L431.93,85.06 L432.73,85.06 L433.54,85.06 L434.35,85.06 L435.15,85.06 L435.96,85.06 L436.77,85.06 L437.57,85.06 L438.38,85.06 L439.19,85.06 L439.99,85.06 L440.80,85.06 L441.61,85.06 L442.41,85.06 L443.22,85.06 L444.03,85.06 L444.83,85.06 L445.64,85.06 L446.45,85.06 L447.25,85.06 L448.06,85.06 L448.87,85.06 L449.67,85.06 L450.48,85.06 L451.29,85.06 L452.09,85.06 L452.90,85.06 L453.71,85.06 L454.51,85.06 L455.32,85.06 L456.13,85.06 L456.93,85.06 L457.74,85.06 L458.55,85.06 L459.35,85.06 L460.16,85.06 L460.97,85.06 L461.77,85.06 L462.58,85.06 L463.39,85.06 L464.19,85.06 L465.00,85.06 L465.81,85.06 L466.61,85.06 L467.42,85.06 L468.23,85.06 L469.03,85.06 L469.84,85.06 L470.65,85.06 L471.45,85.06 L472.26,85.06 L473.07,85.06 L473.87,85.06 L474.68,85.06 L475.49,85.06 L476.29,85.06 L477.10,85.06 L477.91,85.06 L478.71,85.06 L479.52,85.06 L480.33,85.06 L481.13,85.06 L481.94,85.06 L482.75,85.06 L483.55,85.06 L484.36,85.06 L485.17,85.06 L485.97,85.06 L486.78,85.06 L487.59,85.06 L488.39,85.06 L489.20,85.06 L490.01,85.06 L490.81,85.06 L491.62,85.06 L492.43,85.06 L493.23,85.06 L494.04,85.06 L494.85,85.06 L495.65,85.06 L496.46,85.06 L497.27,85.06 L498.07,85.06 L498.88,85.06 L499.69,85.06 L500.49,85.06 L501.30,85.06 L502.11,85.06 L502.91,85.06 L503.72,85.06 L504.53,85.06 L505.33,85.06 L506.14,85.06 L506.95,85.06 L507.75,85.06 L508.56,85.06 L509.37,85.06 L510.17,85.06 L510.98,85.06 L511.79,85.06 L512.59,85.06 L513.40,85.06 L514.21,85.06 L515.01,85.06 L515.82,85.06 L516.63,85.06 L517.43,85.06 L518.24,85.06 L519.05,85.06 L519.85,85.06 L520.66,85.06 L521.47,85.06 L522.27,85.06 L523.08,85.06 L523.89,85.06 L524.69,85.06 L525.50,85.06 L526.31,85.06 L527.11,85.06 L527.92,85.06 L528.73,85.06 L529.53,85.06 L530.34,85.06 L531.15,85.06 L531.95,85.06 L532.76,85.06 L533.57,85.06 L534.37,85.06 L535.18,85.06 L535.99,85.06 L536.79,85.06 L537.60,85.06 L538.41,85.06 L539.21,85.06 L540.02,85.06 L540.83,85.06 L541.63,85.06 L542.44,85.06 L543.25,85.06 L544.05,85.06 L544.86,85.06 L545.67,85.06 L546.47,85.06 L547.28,85.06 L548.09,85.06 L548.89,85.06 L549.70,85.06 L550.51,85.06 L551.31,85.06 L552.12,85.06 L552.93,85.06 L553.73,85.06 L554.54,85.06 L555.35,85.06 L556.15,85.06 L556.96,85.06 L557.77,85.06 L558.57,85.06 L559.38,85.06 L560.19,85.06 L560.99,85.06 L561.80,85.06 L562.61,85.06 L563.41,85.06 L564.22,85.06 L565.03,85.06 L565.83,85.06 L566.64,85.06 L567.45,85.06 L568.25,85.06 L569.06,85.06 L569.87,85.06 L570.67,85.06 L571.48,85.06 L572.29,85.06 L573.09,85.06 L573.90,85.06 L574.71,85.06 L575.51,85.06 L576.32,85.06 L577.13,85.06 L577.93,85.06 L578.74,85.06 L579.55,85.06 L580.35,85.06 L581.16,85.06 L581.97,85.06 L582.77,85.06 L583.58,85.06 L584.39,85.06 L585.19,85.06 L586.00,85.06 " fill="none" stroke="#2f6fec" stroke-width="1.8"/><text x="582" y="80" font-size="9" fill="#2f6fec" text-anchor="end">position</text><path d="M344.00,153.29 L344.81,117.04 L345.61,96.89 L346.42,87.49 L347.23,85.06 L348.03,86.96 L348.84,91.38 L349.65,97.11 L350.45,103.36 L351.26,109.60 L352.07,115.53 L352.87,120.99 L353.68,125.88 L354.49,130.20 L355.29,133.95 L356.10,137.17 L356.91,139.92 L357.71,142.24 L358.52,144.19 L359.33,145.82 L360.13,147.18 L360.94,148.30 L361.75,149.22 L362.55,149.98 L363.36,150.61 L364.17,151.12 L364.97,151.53 L365.78,151.87 L366.59,152.15 L367.39,152.37 L368.20,152.55 L369.01,152.70 L369.81,152.81 L370.62,152.91 L371.43,152.99 L372.23,153.05 L373.04,153.10 L373.85,153.14 L374.65,153.17 L375.46,153.19 L376.27,153.21 L377.07,153.23 L377.88,153.24 L378.69,153.25 L379.49,153.26 L380.30,153.27 L381.11,153.27 L381.91,153.28 L382.72,153.28 L383.53,153.28 L384.33,153.29 L385.14,153.29 L385.95,153.29 L386.75,153.29 L387.56,153.29 L388.37,153.29 L389.17,153.29 L389.98,153.29 L390.79,153.29 L391.59,153.29 L392.40,153.29 L393.21,153.29 L394.01,153.29 L394.82,153.29 L395.63,153.29 L396.43,153.29 L397.24,153.29 L398.05,153.29 L398.85,153.29 L399.66,153.29 L400.47,153.29 L401.27,153.29 L402.08,153.29 L402.89,153.29 L403.69,153.29 L404.50,153.29 L405.31,153.29 L406.11,153.29 L406.92,153.29 L407.73,153.29 L408.53,153.29 L409.34,153.29 L410.15,153.29 L410.95,153.29 L411.76,153.29 L412.57,153.29 L413.37,153.29 L414.18,153.29 L414.99,153.29 L415.79,153.29 L416.60,153.29 L417.41,153.29 L418.21,153.29 L419.02,153.29 L419.83,153.29 L420.63,153.29 L421.44,153.29 L422.25,153.29 L423.05,153.29 L423.86,153.29 L424.67,153.29 L425.47,153.29 L426.28,153.29 L427.09,153.29 L427.89,153.29 L428.70,153.29 L429.51,153.29 L430.31,153.29 L431.12,153.29 L431.93,153.29 L432.73,153.29 L433.54,153.29 L434.35,153.29 L435.15,153.29 L435.96,153.29 L436.77,153.29 L437.57,153.29 L438.38,153.29 L439.19,153.29 L439.99,153.29 L440.80,153.29 L441.61,153.29 L442.41,153.29 L443.22,153.29 L444.03,153.29 L444.83,153.29 L445.64,153.29 L446.45,153.29 L447.25,153.29 L448.06,153.29 L448.87,153.29 L449.67,153.29 L450.48,153.29 L451.29,153.29 L452.09,153.29 L452.90,153.29 L453.71,153.29 L454.51,153.29 L455.32,153.29 L456.13,153.29 L456.93,153.29 L457.74,153.29 L458.55,153.29 L459.35,153.29 L460.16,153.29 L460.97,153.29 L461.77,153.29 L462.58,153.29 L463.39,153.29 L464.19,153.29 L465.00,153.29 L465.81,153.29 L466.61,153.29 L467.42,153.29 L468.23,153.29 L469.03,153.29 L469.84,153.29 L470.65,153.29 L471.45,153.29 L472.26,153.29 L473.07,153.29 L473.87,153.29 L474.68,153.29 L475.49,153.29 L476.29,153.29 L477.10,153.29 L477.91,153.29 L478.71,153.29 L479.52,153.29 L480.33,153.29 L481.13,153.29 L481.94,153.29 L482.75,153.29 L483.55,153.29 L484.36,153.29 L485.17,153.29 L485.97,153.29 L486.78,153.29 L487.59,153.29 L488.39,153.29 L489.20,153.29 L490.01,153.29 L490.81,153.29 L491.62,153.29 L492.43,153.29 L493.23,153.29 L494.04,153.29 L494.85,153.29 L495.65,153.29 L496.46,153.29 L497.27,153.29 L498.07,153.29 L498.88,153.29 L499.69,153.29 L500.49,153.29 L501.30,153.29 L502.11,153.29 L502.91,153.29 L503.72,153.29 L504.53,153.29 L505.33,153.29 L506.14,153.29 L506.95,153.29 L507.75,153.29 L508.56,153.29 L509.37,153.29 L510.17,153.29 L510.98,153.29 L511.79,153.29 L512.59,153.29 L513.40,153.29 L514.21,153.29 L515.01,153.29 L515.82,153.29 L516.63,153.29 L517.43,153.29 L518.24,153.29 L519.05,153.29 L519.85,153.29 L520.66,153.29 L521.47,153.29 L522.27,153.29 L523.08,153.29 L523.89,153.29 L524.69,153.29 L525.50,153.29 L526.31,153.29 L527.11,153.29 L527.92,153.29 L528.73,153.29 L529.53,153.29 L530.34,153.29 L531.15,153.29 L531.95,153.29 L532.76,153.29 L533.57,153.29 L534.37,153.29 L535.18,153.29 L535.99,153.29 L536.79,153.29 L537.60,153.29 L538.41,153.29 L539.21,153.29 L540.02,153.29 L540.83,153.29 L541.63,153.29 L542.44,153.29 L543.25,153.29 L544.05,153.29 L544.86,153.29 L545.67,153.29 L546.47,153.29 L547.28,153.29 L548.09,153.29 L548.89,153.29 L549.70,153.29 L550.51,153.29 L551.31,153.29 L552.12,153.29 L552.93,153.29 L553.73,153.29 L554.54,153.29 L555.35,153.29 L556.15,153.29 L556.96,153.29 L557.77,153.29 L558.57,153.29 L559.38,153.29 L560.19,153.29 L560.99,153.29 L561.80,153.29 L562.61,153.29 L563.41,153.29 L564.22,153.29 L565.03,153.29 L565.83,153.29 L566.64,153.29 L567.45,153.29 L568.25,153.29 L569.06,153.29 L569.87,153.29 L570.67,153.29 L571.48,153.29 L572.29,153.29 L573.09,153.29 L573.90,153.29 L574.71,153.29 L575.51,153.29 L576.32,153.29 L577.13,153.29 L577.93,153.29 L578.74,153.29 L579.55,153.29 L580.35,153.29 L581.16,153.29 L581.97,153.29 L582.77,153.29 L583.58,153.29 L584.39,153.29 L585.19,153.29 L586.00,153.29 " fill="none" stroke="#e8833a" stroke-width="1.8" stroke-dasharray="4 3"/><text x="582" y="92" font-size="9" fill="#e8833a" text-anchor="end">velocity (norm.)</text><rect x="644" y="68" width="242" height="116" fill="#fafbfc" stroke="#e3e6ea"/><text x="644" y="59" font-size="12" font-weight="600" fill="#333">snap 0.25/0</text><line x1="644" x2="886" y1="153.29411" y2="153.29411" stroke="#d5d9de" stroke-dasharray="3 3"/><text x="640" y="156.29411" font-size="9" fill="#888" text-anchor="end">0</text><line x1="644" x2="886" y1="85.05882" y2="85.05882" stroke="#d5d9de" stroke-dasharray="3 3"/><text x="640" y="88.05882" font-size="9" fill="#888" text-anchor="end">1</text><text x="886" y="198" font-size="9" fill="#888" text-anchor="end">1.20 s</text><line x1="694.4167" x2="694.4167" y1="68" y2="184" stroke="#d64545" stroke-width="1" stroke-dasharray="2 3"/><path d="M644.00,153.29 L644.81,152.97 L645.61,152.09 L646.42,150.75 L647.23,149.06 L648.03,147.08 L648.84,144.90 L649.65,142.57 L650.45,140.14 L651.26,137.65 L652.07,135.13 L652.87,132.61 L653.68,130.12 L654.49,127.66 L655.29,125.27 L656.10,122.94 L656.91,120.69 L657.71,118.52 L658.52,116.45 L659.33,114.46 L660.13,112.57 L660.94,110.77 L661.75,109.06 L662.55,107.44 L663.36,105.92 L664.17,104.48 L664.97,103.12 L665.78,101.85 L666.59,100.65 L667.39,99.53 L668.20,98.49 L669.01,97.51 L669.81,96.59 L670.62,95.74 L671.43,94.94 L672.23,94.20 L673.04,93.51 L673.85,92.87 L674.65,92.27 L675.46,91.72 L676.27,91.20 L677.07,90.73 L677.88,90.28 L678.69,89.88 L679.49,89.50 L680.30,89.15 L681.11,88.82 L681.91,88.52 L682.72,88.25 L683.53,87.99 L684.33,87.76 L685.14,87.54 L685.95,87.34 L686.75,87.15 L687.56,86.98 L688.37,86.83 L689.17,86.68 L689.98,86.55 L690.79,86.43 L691.59,86.31 L692.40,86.21 L693.21,86.12 L694.01,86.03 L694.82,85.95 L695.63,85.87 L696.43,85.81 L697.24,85.74 L698.05,85.69 L698.85,85.63 L699.66,85.58 L700.47,85.54 L701.27,85.50 L702.08,85.46 L702.89,85.43 L703.69,85.40 L704.50,85.37 L705.31,85.34 L706.11,85.32 L706.92,85.30 L707.73,85.28 L708.53,85.26 L709.34,85.24 L710.15,85.22 L710.95,85.21 L711.76,85.20 L712.57,85.19 L713.37,85.17 L714.18,85.16 L714.99,85.16 L715.79,85.15 L716.60,85.14 L717.41,85.13 L718.21,85.13 L719.02,85.12 L719.83,85.11 L720.63,85.11 L721.44,85.11 L722.25,85.10 L723.05,85.10 L723.86,85.09 L724.67,85.09 L725.47,85.09 L726.28,85.09 L727.09,85.08 L727.89,85.08 L728.70,85.08 L729.51,85.08 L730.31,85.08 L731.12,85.07 L731.93,85.07 L732.73,85.07 L733.54,85.07 L734.35,85.07 L735.15,85.07 L735.96,85.07 L736.77,85.07 L737.57,85.07 L738.38,85.07 L739.19,85.07 L739.99,85.06 L740.80,85.06 L741.61,85.06 L742.41,85.06 L743.22,85.06 L744.03,85.06 L744.83,85.06 L745.64,85.06 L746.45,85.06 L747.25,85.06 L748.06,85.06 L748.87,85.06 L749.67,85.06 L750.48,85.06 L751.29,85.06 L752.09,85.06 L752.90,85.06 L753.71,85.06 L754.51,85.06 L755.32,85.06 L756.13,85.06 L756.93,85.06 L757.74,85.06 L758.55,85.06 L759.35,85.06 L760.16,85.06 L760.97,85.06 L761.77,85.06 L762.58,85.06 L763.39,85.06 L764.19,85.06 L765.00,85.06 L765.81,85.06 L766.61,85.06 L767.42,85.06 L768.23,85.06 L769.03,85.06 L769.84,85.06 L770.65,85.06 L771.45,85.06 L772.26,85.06 L773.07,85.06 L773.87,85.06 L774.68,85.06 L775.49,85.06 L776.29,85.06 L777.10,85.06 L777.91,85.06 L778.71,85.06 L779.52,85.06 L780.33,85.06 L781.13,85.06 L781.94,85.06 L782.75,85.06 L783.55,85.06 L784.36,85.06 L785.17,85.06 L785.97,85.06 L786.78,85.06 L787.59,85.06 L788.39,85.06 L789.20,85.06 L790.01,85.06 L790.81,85.06 L791.62,85.06 L792.43,85.06 L793.23,85.06 L794.04,85.06 L794.85,85.06 L795.65,85.06 L796.46,85.06 L797.27,85.06 L798.07,85.06 L798.88,85.06 L799.69,85.06 L800.49,85.06 L801.30,85.06 L802.11,85.06 L802.91,85.06 L803.72,85.06 L804.53,85.06 L805.33,85.06 L806.14,85.06 L806.95,85.06 L807.75,85.06 L808.56,85.06 L809.37,85.06 L810.17,85.06 L810.98,85.06 L811.79,85.06 L812.59,85.06 L813.40,85.06 L814.21,85.06 L815.01,85.06 L815.82,85.06 L816.63,85.06 L817.43,85.06 L818.24,85.06 L819.05,85.06 L819.85,85.06 L820.66,85.06 L821.47,85.06 L822.27,85.06 L823.08,85.06 L823.89,85.06 L824.69,85.06 L825.50,85.06 L826.31,85.06 L827.11,85.06 L827.92,85.06 L828.73,85.06 L829.53,85.06 L830.34,85.06 L831.15,85.06 L831.95,85.06 L832.76,85.06 L833.57,85.06 L834.37,85.06 L835.18,85.06 L835.99,85.06 L836.79,85.06 L837.60,85.06 L838.41,85.06 L839.21,85.06 L840.02,85.06 L840.83,85.06 L841.63,85.06 L842.44,85.06 L843.25,85.06 L844.05,85.06 L844.86,85.06 L845.67,85.06 L846.47,85.06 L847.28,85.06 L848.09,85.06 L848.89,85.06 L849.70,85.06 L850.51,85.06 L851.31,85.06 L852.12,85.06 L852.93,85.06 L853.73,85.06 L854.54,85.06 L855.35,85.06 L856.15,85.06 L856.96,85.06 L857.77,85.06 L858.57,85.06 L859.38,85.06 L860.19,85.06 L860.99,85.06 L861.80,85.06 L862.61,85.06 L863.41,85.06 L864.22,85.06 L865.03,85.06 L865.83,85.06 L866.64,85.06 L867.45,85.06 L868.25,85.06 L869.06,85.06 L869.87,85.06 L870.67,85.06 L871.48,85.06 L872.29,85.06 L873.09,85.06 L873.90,85.06 L874.71,85.06 L875.51,85.06 L876.32,85.06 L877.13,85.06 L877.93,85.06 L878.74,85.06 L879.55,85.06 L880.35,85.06 L881.16,85.06 L881.97,85.06 L882.77,85.06 L883.58,85.06 L884.39,85.06 L885.19,85.06 L886.00,85.06 " fill="none" stroke="#2f6fec" stroke-width="1.8"/><text x="882" y="80" font-size="9" fill="#2f6fec" text-anchor="end">position</text><path d="M644.00,153.29 L644.81,136.43 L645.61,122.79 L646.42,111.92 L647.23,103.40 L648.03,96.89 L648.84,92.09 L649.65,88.72 L650.45,86.55 L651.26,85.39 L652.07,85.06 L652.87,85.41 L653.68,86.33 L654.49,87.68 L655.29,89.39 L656.10,91.38 L656.91,93.57 L657.71,95.90 L658.52,98.34 L659.33,100.83 L660.13,103.36 L660.94,105.87 L661.75,108.37 L662.55,110.82 L663.36,113.21 L664.17,115.53 L664.97,117.78 L665.78,119.94 L666.59,122.01 L667.39,123.99 L668.20,125.88 L669.01,127.68 L669.81,129.38 L670.62,130.99 L671.43,132.51 L672.23,133.95 L673.04,135.30 L673.85,136.57 L674.65,137.76 L675.46,138.88 L676.27,139.92 L677.07,140.90 L677.88,141.81 L678.69,142.66 L679.49,143.45 L680.30,144.19 L681.11,144.88 L681.91,145.52 L682.72,146.11 L683.53,146.66 L684.33,147.18 L685.14,147.65 L685.95,148.09 L686.75,148.50 L687.56,148.87 L688.37,149.22 L689.17,149.55 L689.98,149.84 L690.79,150.12 L691.59,150.37 L692.40,150.61 L693.21,150.82 L694.01,151.02 L694.82,151.21 L695.63,151.38 L696.43,151.53 L697.24,151.68 L698.05,151.81 L698.85,151.93 L699.66,152.04 L700.47,152.15 L701.27,152.24 L702.08,152.33 L702.89,152.41 L703.69,152.48 L704.50,152.55 L705.31,152.61 L706.11,152.67 L706.92,152.72 L707.73,152.77 L708.53,152.81 L709.34,152.85 L710.15,152.89 L710.95,152.93 L711.76,152.96 L712.57,152.99 L713.37,153.01 L714.18,153.04 L714.99,153.06 L715.79,153.08 L716.60,153.10 L717.41,153.11 L718.21,153.13 L719.02,153.14 L719.83,153.16 L720.63,153.17 L721.44,153.18 L722.25,153.19 L723.05,153.20 L723.86,153.21 L724.67,153.21 L725.47,153.22 L726.28,153.23 L727.09,153.23 L727.89,153.24 L728.70,153.24 L729.51,153.25 L730.31,153.25 L731.12,153.26 L731.93,153.26 L732.73,153.26 L733.54,153.26 L734.35,153.27 L735.15,153.27 L735.96,153.27 L736.77,153.27 L737.57,153.28 L738.38,153.28 L739.19,153.28 L739.99,153.28 L740.80,153.28 L741.61,153.28 L742.41,153.28 L743.22,153.28 L744.03,153.29 L744.83,153.29 L745.64,153.29 L746.45,153.29 L747.25,153.29 L748.06,153.29 L748.87,153.29 L749.67,153.29 L750.48,153.29 L751.29,153.29 L752.09,153.29 L752.90,153.29 L753.71,153.29 L754.51,153.29 L755.32,153.29 L756.13,153.29 L756.93,153.29 L757.74,153.29 L758.55,153.29 L759.35,153.29 L760.16,153.29 L760.97,153.29 L761.77,153.29 L762.58,153.29 L763.39,153.29 L764.19,153.29 L765.00,153.29 L765.81,153.29 L766.61,153.29 L767.42,153.29 L768.23,153.29 L769.03,153.29 L769.84,153.29 L770.65,153.29 L771.45,153.29 L772.26,153.29 L773.07,153.29 L773.87,153.29 L774.68,153.29 L775.49,153.29 L776.29,153.29 L777.10,153.29 L777.91,153.29 L778.71,153.29 L779.52,153.29 L780.33,153.29 L781.13,153.29 L781.94,153.29 L782.75,153.29 L783.55,153.29 L784.36,153.29 L785.17,153.29 L785.97,153.29 L786.78,153.29 L787.59,153.29 L788.39,153.29 L789.20,153.29 L790.01,153.29 L790.81,153.29 L791.62,153.29 L792.43,153.29 L793.23,153.29 L794.04,153.29 L794.85,153.29 L795.65,153.29 L796.46,153.29 L797.27,153.29 L798.07,153.29 L798.88,153.29 L799.69,153.29 L800.49,153.29 L801.30,153.29 L802.11,153.29 L802.91,153.29 L803.72,153.29 L804.53,153.29 L805.33,153.29 L806.14,153.29 L806.95,153.29 L807.75,153.29 L808.56,153.29 L809.37,153.29 L810.17,153.29 L810.98,153.29 L811.79,153.29 L812.59,153.29 L813.40,153.29 L814.21,153.29 L815.01,153.29 L815.82,153.29 L816.63,153.29 L817.43,153.29 L818.24,153.29 L819.05,153.29 L819.85,153.29 L820.66,153.29 L821.47,153.29 L822.27,153.29 L823.08,153.29 L823.89,153.29 L824.69,153.29 L825.50,153.29 L826.31,153.29 L827.11,153.29 L827.92,153.29 L828.73,153.29 L829.53,153.29 L830.34,153.29 L831.15,153.29 L831.95,153.29 L832.76,153.29 L833.57,153.29 L834.37,153.29 L835.18,153.29 L835.99,153.29 L836.79,153.29 L837.60,153.29 L838.41,153.29 L839.21,153.29 L840.02,153.29 L840.83,153.29 L841.63,153.29 L842.44,153.29 L843.25,153.29 L844.05,153.29 L844.86,153.29 L845.67,153.29 L846.47,153.29 L847.28,153.29 L848.09,153.29 L848.89,153.29 L849.70,153.29 L850.51,153.29 L851.31,153.29 L852.12,153.29 L852.93,153.29 L853.73,153.29 L854.54,153.29 L855.35,153.29 L856.15,153.29 L856.96,153.29 L857.77,153.29 L858.57,153.29 L859.38,153.29 L860.19,153.29 L860.99,153.29 L861.80,153.29 L862.61,153.29 L863.41,153.29 L864.22,153.29 L865.03,153.29 L865.83,153.29 L866.64,153.29 L867.45,153.29 L868.25,153.29 L869.06,153.29 L869.87,153.29 L870.67,153.29 L871.48,153.29 L872.29,153.29 L873.09,153.29 L873.90,153.29 L874.71,153.29 L875.51,153.29 L876.32,153.29 L877.13,153.29 L877.93,153.29 L878.74,153.29 L879.55,153.29 L880.35,153.29 L881.16,153.29 L881.97,153.29 L882.77,153.29 L883.58,153.29 L884.39,153.29 L885.19,153.29 L886.00,153.29 " fill="none" stroke="#e8833a" stroke-width="1.8" stroke-dasharray="4 3"/><text x="882" y="92" font-size="9" fill="#e8833a" text-anchor="end">velocity (norm.)</text><rect x="944" y="68" width="242" height="116" fill="#fafbfc" stroke="#e3e6ea"/><text x="944" y="59" font-size="12" font-weight="600" fill="#333">snap exit 0.2/0</text><line x1="944" x2="1186" y1="153.29411" y2="153.29411" stroke="#d5d9de" stroke-dasharray="3 3"/><text x="940" y="156.29411" font-size="9" fill="#888" text-anchor="end">0</text><line x1="944" x2="1186" y1="85.05882" y2="85.05882" stroke="#d5d9de" stroke-dasharray="3 3"/><text x="940" y="88.05882" font-size="9" fill="#888" text-anchor="end">1</text><text x="1186" y="198" font-size="9" fill="#888" text-anchor="end">1.20 s</text><line x1="984.3333" x2="984.3333" y1="68" y2="184" stroke="#d64545" stroke-width="1" stroke-dasharray="2 3"/><path d="M944.00,153.29 L944.81,152.80 L945.61,151.47 L946.42,149.51 L947.23,147.08 L948.03,144.33 L948.84,141.37 L949.65,138.28 L950.45,135.13 L951.26,131.98 L952.07,128.88 L952.87,125.86 L953.68,122.94 L954.49,120.14 L955.29,117.47 L956.10,114.95 L956.91,112.57 L957.71,110.33 L958.52,108.24 L959.33,106.29 L960.13,104.48 L960.94,102.80 L961.75,101.24 L962.55,99.81 L963.36,98.49 L964.17,97.27 L964.97,96.16 L965.78,95.13 L966.59,94.20 L967.39,93.34 L968.20,92.56 L969.01,91.85 L969.81,91.20 L970.62,90.61 L971.43,90.08 L972.23,89.59 L973.04,89.15 L973.85,88.75 L974.65,88.38 L975.46,88.05 L976.27,87.76 L977.07,87.49 L977.88,87.24 L978.69,87.03 L979.49,86.83 L980.30,86.65 L981.11,86.49 L981.91,86.34 L982.72,86.21 L983.53,86.09 L984.33,85.99 L985.14,85.89 L985.95,85.81 L986.75,85.73 L987.56,85.66 L988.37,85.60 L989.17,85.54 L989.98,85.49 L990.79,85.45 L991.59,85.40 L992.40,85.37 L993.21,85.34 L994.01,85.31 L994.82,85.28 L995.63,85.26 L996.43,85.24 L997.24,85.22 L998.05,85.20 L998.85,85.19 L999.66,85.17 L1000.47,85.16 L1001.27,85.15 L1002.08,85.14 L1002.89,85.13 L1003.69,85.12 L1004.50,85.12 L1005.31,85.11 L1006.11,85.10 L1006.92,85.10 L1007.73,85.10 L1008.53,85.09 L1009.34,85.09 L1010.15,85.08 L1010.95,85.08 L1011.76,85.08 L1012.57,85.08 L1013.37,85.08 L1014.18,85.07 L1014.99,85.07 L1015.79,85.07 L1016.60,85.07 L1017.41,85.07 L1018.21,85.07 L1019.02,85.07 L1019.83,85.07 L1020.63,85.06 L1021.44,85.06 L1022.25,85.06 L1023.05,85.06 L1023.86,85.06 L1024.67,85.06 L1025.47,85.06 L1026.28,85.06 L1027.09,85.06 L1027.89,85.06 L1028.70,85.06 L1029.51,85.06 L1030.31,85.06 L1031.12,85.06 L1031.93,85.06 L1032.73,85.06 L1033.54,85.06 L1034.35,85.06 L1035.15,85.06 L1035.96,85.06 L1036.77,85.06 L1037.57,85.06 L1038.38,85.06 L1039.19,85.06 L1039.99,85.06 L1040.80,85.06 L1041.61,85.06 L1042.41,85.06 L1043.22,85.06 L1044.03,85.06 L1044.83,85.06 L1045.64,85.06 L1046.45,85.06 L1047.25,85.06 L1048.06,85.06 L1048.87,85.06 L1049.67,85.06 L1050.48,85.06 L1051.29,85.06 L1052.09,85.06 L1052.90,85.06 L1053.71,85.06 L1054.51,85.06 L1055.32,85.06 L1056.13,85.06 L1056.93,85.06 L1057.74,85.06 L1058.55,85.06 L1059.35,85.06 L1060.16,85.06 L1060.97,85.06 L1061.77,85.06 L1062.58,85.06 L1063.39,85.06 L1064.19,85.06 L1065.00,85.06 L1065.81,85.06 L1066.61,85.06 L1067.42,85.06 L1068.23,85.06 L1069.03,85.06 L1069.84,85.06 L1070.65,85.06 L1071.45,85.06 L1072.26,85.06 L1073.07,85.06 L1073.87,85.06 L1074.68,85.06 L1075.49,85.06 L1076.29,85.06 L1077.10,85.06 L1077.91,85.06 L1078.71,85.06 L1079.52,85.06 L1080.33,85.06 L1081.13,85.06 L1081.94,85.06 L1082.75,85.06 L1083.55,85.06 L1084.36,85.06 L1085.17,85.06 L1085.97,85.06 L1086.78,85.06 L1087.59,85.06 L1088.39,85.06 L1089.20,85.06 L1090.01,85.06 L1090.81,85.06 L1091.62,85.06 L1092.43,85.06 L1093.23,85.06 L1094.04,85.06 L1094.85,85.06 L1095.65,85.06 L1096.46,85.06 L1097.27,85.06 L1098.07,85.06 L1098.88,85.06 L1099.69,85.06 L1100.49,85.06 L1101.30,85.06 L1102.11,85.06 L1102.91,85.06 L1103.72,85.06 L1104.53,85.06 L1105.33,85.06 L1106.14,85.06 L1106.95,85.06 L1107.75,85.06 L1108.56,85.06 L1109.37,85.06 L1110.17,85.06 L1110.98,85.06 L1111.79,85.06 L1112.59,85.06 L1113.40,85.06 L1114.21,85.06 L1115.01,85.06 L1115.82,85.06 L1116.63,85.06 L1117.43,85.06 L1118.24,85.06 L1119.05,85.06 L1119.85,85.06 L1120.66,85.06 L1121.47,85.06 L1122.27,85.06 L1123.08,85.06 L1123.89,85.06 L1124.69,85.06 L1125.50,85.06 L1126.31,85.06 L1127.11,85.06 L1127.92,85.06 L1128.73,85.06 L1129.53,85.06 L1130.34,85.06 L1131.15,85.06 L1131.95,85.06 L1132.76,85.06 L1133.57,85.06 L1134.37,85.06 L1135.18,85.06 L1135.99,85.06 L1136.79,85.06 L1137.60,85.06 L1138.41,85.06 L1139.21,85.06 L1140.02,85.06 L1140.83,85.06 L1141.63,85.06 L1142.44,85.06 L1143.25,85.06 L1144.05,85.06 L1144.86,85.06 L1145.67,85.06 L1146.47,85.06 L1147.28,85.06 L1148.09,85.06 L1148.89,85.06 L1149.70,85.06 L1150.51,85.06 L1151.31,85.06 L1152.12,85.06 L1152.93,85.06 L1153.73,85.06 L1154.54,85.06 L1155.35,85.06 L1156.15,85.06 L1156.96,85.06 L1157.77,85.06 L1158.57,85.06 L1159.38,85.06 L1160.19,85.06 L1160.99,85.06 L1161.80,85.06 L1162.61,85.06 L1163.41,85.06 L1164.22,85.06 L1165.03,85.06 L1165.83,85.06 L1166.64,85.06 L1167.45,85.06 L1168.25,85.06 L1169.06,85.06 L1169.87,85.06 L1170.67,85.06 L1171.48,85.06 L1172.29,85.06 L1173.09,85.06 L1173.90,85.06 L1174.71,85.06 L1175.51,85.06 L1176.32,85.06 L1177.13,85.06 L1177.93,85.06 L1178.74,85.06 L1179.55,85.06 L1180.35,85.06 L1181.16,85.06 L1181.97,85.06 L1182.77,85.06 L1183.58,85.06 L1184.39,85.06 L1185.19,85.06 L1186.00,85.06 " fill="none" stroke="#2f6fec" stroke-width="1.8"/><text x="1182" y="80" font-size="9" fill="#2f6fec" text-anchor="end">position</text><path d="M944.00,153.29 L944.81,132.74 L945.61,117.04 L946.42,105.33 L947.23,96.89 L948.03,91.12 L948.84,87.49 L949.65,85.59 L950.45,85.06 L951.26,85.59 L952.07,86.96 L952.87,88.94 L953.68,91.38 L954.49,94.14 L955.29,97.11 L956.10,100.21 L956.91,103.36 L957.71,106.50 L958.52,109.60 L959.33,112.62 L960.13,115.53 L960.94,118.33 L961.75,120.99 L962.55,123.51 L963.36,125.88 L964.17,128.11 L964.97,130.20 L965.78,132.14 L966.59,133.95 L967.39,135.62 L968.20,137.17 L969.01,138.60 L969.81,139.92 L970.62,141.13 L971.43,142.24 L972.23,143.26 L973.04,144.19 L973.85,145.04 L974.65,145.82 L975.46,146.53 L976.27,147.18 L977.07,147.76 L977.88,148.30 L978.69,148.78 L979.49,149.22 L980.30,149.62 L981.11,149.98 L981.91,150.31 L982.72,150.61 L983.53,150.88 L984.33,151.12 L985.14,151.34 L985.95,151.53 L986.75,151.71 L987.56,151.87 L988.37,152.02 L989.17,152.15 L989.98,152.26 L990.79,152.37 L991.59,152.47 L992.40,152.55 L993.21,152.63 L994.01,152.70 L994.82,152.76 L995.63,152.81 L996.43,152.86 L997.24,152.91 L998.05,152.95 L998.85,152.99 L999.66,153.02 L1000.47,153.05 L1001.27,153.07 L1002.08,153.10 L1002.89,153.12 L1003.69,153.14 L1004.50,153.15 L1005.31,153.17 L1006.11,153.18 L1006.92,153.19 L1007.73,153.20 L1008.53,153.21 L1009.34,153.22 L1010.15,153.23 L1010.95,153.24 L1011.76,153.24 L1012.57,153.25 L1013.37,153.25 L1014.18,153.26 L1014.99,153.26 L1015.79,153.27 L1016.60,153.27 L1017.41,153.27 L1018.21,153.27 L1019.02,153.28 L1019.83,153.28 L1020.63,153.28 L1021.44,153.28 L1022.25,153.28 L1023.05,153.28 L1023.86,153.29 L1024.67,153.29 L1025.47,153.29 L1026.28,153.29 L1027.09,153.29 L1027.89,153.29 L1028.70,153.29 L1029.51,153.29 L1030.31,153.29 L1031.12,153.29 L1031.93,153.29 L1032.73,153.29 L1033.54,153.29 L1034.35,153.29 L1035.15,153.29 L1035.96,153.29 L1036.77,153.29 L1037.57,153.29 L1038.38,153.29 L1039.19,153.29 L1039.99,153.29 L1040.80,153.29 L1041.61,153.29 L1042.41,153.29 L1043.22,153.29 L1044.03,153.29 L1044.83,153.29 L1045.64,153.29 L1046.45,153.29 L1047.25,153.29 L1048.06,153.29 L1048.87,153.29 L1049.67,153.29 L1050.48,153.29 L1051.29,153.29 L1052.09,153.29 L1052.90,153.29 L1053.71,153.29 L1054.51,153.29 L1055.32,153.29 L1056.13,153.29 L1056.93,153.29 L1057.74,153.29 L1058.55,153.29 L1059.35,153.29 L1060.16,153.29 L1060.97,153.29 L1061.77,153.29 L1062.58,153.29 L1063.39,153.29 L1064.19,153.29 L1065.00,153.29 L1065.81,153.29 L1066.61,153.29 L1067.42,153.29 L1068.23,153.29 L1069.03,153.29 L1069.84,153.29 L1070.65,153.29 L1071.45,153.29 L1072.26,153.29 L1073.07,153.29 L1073.87,153.29 L1074.68,153.29 L1075.49,153.29 L1076.29,153.29 L1077.10,153.29 L1077.91,153.29 L1078.71,153.29 L1079.52,153.29 L1080.33,153.29 L1081.13,153.29 L1081.94,153.29 L1082.75,153.29 L1083.55,153.29 L1084.36,153.29 L1085.17,153.29 L1085.97,153.29 L1086.78,153.29 L1087.59,153.29 L1088.39,153.29 L1089.20,153.29 L1090.01,153.29 L1090.81,153.29 L1091.62,153.29 L1092.43,153.29 L1093.23,153.29 L1094.04,153.29 L1094.85,153.29 L1095.65,153.29 L1096.46,153.29 L1097.27,153.29 L1098.07,153.29 L1098.88,153.29 L1099.69,153.29 L1100.49,153.29 L1101.30,153.29 L1102.11,153.29 L1102.91,153.29 L1103.72,153.29 L1104.53,153.29 L1105.33,153.29 L1106.14,153.29 L1106.95,153.29 L1107.75,153.29 L1108.56,153.29 L1109.37,153.29 L1110.17,153.29 L1110.98,153.29 L1111.79,153.29 L1112.59,153.29 L1113.40,153.29 L1114.21,153.29 L1115.01,153.29 L1115.82,153.29 L1116.63,153.29 L1117.43,153.29 L1118.24,153.29 L1119.05,153.29 L1119.85,153.29 L1120.66,153.29 L1121.47,153.29 L1122.27,153.29 L1123.08,153.29 L1123.89,153.29 L1124.69,153.29 L1125.50,153.29 L1126.31,153.29 L1127.11,153.29 L1127.92,153.29 L1128.73,153.29 L1129.53,153.29 L1130.34,153.29 L1131.15,153.29 L1131.95,153.29 L1132.76,153.29 L1133.57,153.29 L1134.37,153.29 L1135.18,153.29 L1135.99,153.29 L1136.79,153.29 L1137.60,153.29 L1138.41,153.29 L1139.21,153.29 L1140.02,153.29 L1140.83,153.29 L1141.63,153.29 L1142.44,153.29 L1143.25,153.29 L1144.05,153.29 L1144.86,153.29 L1145.67,153.29 L1146.47,153.29 L1147.28,153.29 L1148.09,153.29 L1148.89,153.29 L1149.70,153.29 L1150.51,153.29 L1151.31,153.29 L1152.12,153.29 L1152.93,153.29 L1153.73,153.29 L1154.54,153.29 L1155.35,153.29 L1156.15,153.29 L1156.96,153.29 L1157.77,153.29 L1158.57,153.29 L1159.38,153.29 L1160.19,153.29 L1160.99,153.29 L1161.80,153.29 L1162.61,153.29 L1163.41,153.29 L1164.22,153.29 L1165.03,153.29 L1165.83,153.29 L1166.64,153.29 L1167.45,153.29 L1168.25,153.29 L1169.06,153.29 L1169.87,153.29 L1170.67,153.29 L1171.48,153.29 L1172.29,153.29 L1173.09,153.29 L1173.90,153.29 L1174.71,153.29 L1175.51,153.29 L1176.32,153.29 L1177.13,153.29 L1177.93,153.29 L1178.74,153.29 L1179.55,153.29 L1180.35,153.29 L1181.16,153.29 L1181.97,153.29 L1182.77,153.29 L1183.58,153.29 L1184.39,153.29 L1185.19,153.29 L1186.00,153.29 " fill="none" stroke="#e8833a" stroke-width="1.8" stroke-dasharray="4 3"/><text x="1182" y="92" font-size="9" fill="#e8833a" text-anchor="end">velocity (norm.)</text><rect x="44" y="238" width="242" height="116" fill="#fafbfc" stroke="#e3e6ea"/><text x="44" y="229" font-size="12" font-weight="600" fill="#333">settle 0.3/0</text><line x1="44" x2="286" y1="323.29413" y2="323.29413" stroke="#d5d9de" stroke-dasharray="3 3"/><text x="40" y="326.29413" font-size="9" fill="#888" text-anchor="end">0</text><line x1="44" x2="286" y1="255.05882" y2="255.05882" stroke="#d5d9de" stroke-dasharray="3 3"/><text x="40" y="258.05884" font-size="9" fill="#888" text-anchor="end">1</text><text x="286" y="368" font-size="9" fill="#888" text-anchor="end">1.20 s</text><line x1="104.5" x2="104.5" y1="238" y2="354" stroke="#d64545" stroke-width="1" stroke-dasharray="2 3"/><path d="M44.00,323.29 L44.81,323.07 L45.61,322.44 L46.42,321.47 L47.23,320.22 L48.03,318.74 L48.84,317.08 L49.65,315.28 L50.45,313.36 L51.26,311.37 L52.07,309.32 L52.87,307.23 L53.68,305.13 L54.49,303.03 L55.29,300.94 L56.10,298.88 L56.91,296.86 L57.71,294.87 L58.52,292.94 L59.33,291.06 L60.13,289.24 L60.94,287.47 L61.75,285.77 L62.55,284.14 L63.36,282.57 L64.17,281.06 L64.97,279.62 L65.78,278.24 L66.59,276.92 L67.39,275.67 L68.20,274.48 L69.01,273.34 L69.81,272.27 L70.62,271.24 L71.43,270.27 L72.23,269.36 L73.04,268.49 L73.85,267.66 L74.65,266.89 L75.46,266.16 L76.27,265.46 L77.07,264.81 L77.88,264.20 L78.69,263.62 L79.49,263.07 L80.30,262.56 L81.11,262.08 L81.91,261.63 L82.72,261.20 L83.53,260.80 L84.33,260.43 L85.14,260.08 L85.95,259.75 L86.75,259.44 L87.56,259.15 L88.37,258.88 L89.17,258.62 L89.98,258.38 L90.79,258.16 L91.59,257.95 L92.40,257.76 L93.21,257.57 L94.01,257.40 L94.82,257.24 L95.63,257.10 L96.43,256.96 L97.24,256.83 L98.05,256.71 L98.85,256.59 L99.66,256.49 L100.47,256.39 L101.27,256.30 L102.08,256.21 L102.89,256.13 L103.69,256.06 L104.50,255.99 L105.31,255.92 L106.11,255.86 L106.92,255.81 L107.73,255.75 L108.53,255.70 L109.34,255.66 L110.15,255.62 L110.95,255.58 L111.76,255.54 L112.57,255.51 L113.37,255.47 L114.18,255.45 L114.99,255.42 L115.79,255.39 L116.60,255.37 L117.41,255.35 L118.21,255.33 L119.02,255.31 L119.83,255.29 L120.63,255.27 L121.44,255.26 L122.25,255.24 L123.05,255.23 L123.86,255.22 L124.67,255.21 L125.47,255.20 L126.28,255.19 L127.09,255.18 L127.89,255.17 L128.70,255.16 L129.51,255.15 L130.31,255.15 L131.12,255.14 L131.93,255.13 L132.73,255.13 L133.54,255.12 L134.35,255.12 L135.15,255.11 L135.96,255.11 L136.77,255.11 L137.57,255.10 L138.38,255.10 L139.19,255.10 L139.99,255.09 L140.80,255.09 L141.61,255.09 L142.41,255.09 L143.22,255.08 L144.03,255.08 L144.83,255.08 L145.64,255.08 L146.45,255.08 L147.25,255.08 L148.06,255.08 L148.87,255.07 L149.67,255.07 L150.48,255.07 L151.29,255.07 L152.09,255.07 L152.90,255.07 L153.71,255.07 L154.51,255.07 L155.32,255.07 L156.13,255.07 L156.93,255.07 L157.74,255.07 L158.55,255.06 L159.35,255.06 L160.16,255.06 L160.97,255.06 L161.77,255.06 L162.58,255.06 L163.39,255.06 L164.19,255.06 L165.00,255.06 L165.81,255.06 L166.61,255.06 L167.42,255.06 L168.23,255.06 L169.03,255.06 L169.84,255.06 L170.65,255.06 L171.45,255.06 L172.26,255.06 L173.07,255.06 L173.87,255.06 L174.68,255.06 L175.49,255.06 L176.29,255.06 L177.10,255.06 L177.91,255.06 L178.71,255.06 L179.52,255.06 L180.33,255.06 L181.13,255.06 L181.94,255.06 L182.75,255.06 L183.55,255.06 L184.36,255.06 L185.17,255.06 L185.97,255.06 L186.78,255.06 L187.59,255.06 L188.39,255.06 L189.20,255.06 L190.01,255.06 L190.81,255.06 L191.62,255.06 L192.43,255.06 L193.23,255.06 L194.04,255.06 L194.85,255.06 L195.65,255.06 L196.46,255.06 L197.27,255.06 L198.07,255.06 L198.88,255.06 L199.69,255.06 L200.49,255.06 L201.30,255.06 L202.11,255.06 L202.91,255.06 L203.72,255.06 L204.53,255.06 L205.33,255.06 L206.14,255.06 L206.95,255.06 L207.75,255.06 L208.56,255.06 L209.37,255.06 L210.17,255.06 L210.98,255.06 L211.79,255.06 L212.59,255.06 L213.40,255.06 L214.21,255.06 L215.01,255.06 L215.82,255.06 L216.63,255.06 L217.43,255.06 L218.24,255.06 L219.05,255.06 L219.85,255.06 L220.66,255.06 L221.47,255.06 L222.27,255.06 L223.08,255.06 L223.89,255.06 L224.69,255.06 L225.50,255.06 L226.31,255.06 L227.11,255.06 L227.92,255.06 L228.73,255.06 L229.53,255.06 L230.34,255.06 L231.15,255.06 L231.95,255.06 L232.76,255.06 L233.57,255.06 L234.37,255.06 L235.18,255.06 L235.99,255.06 L236.79,255.06 L237.60,255.06 L238.41,255.06 L239.21,255.06 L240.02,255.06 L240.83,255.06 L241.63,255.06 L242.44,255.06 L243.25,255.06 L244.05,255.06 L244.86,255.06 L245.67,255.06 L246.47,255.06 L247.28,255.06 L248.09,255.06 L248.89,255.06 L249.70,255.06 L250.51,255.06 L251.31,255.06 L252.12,255.06 L252.93,255.06 L253.73,255.06 L254.54,255.06 L255.35,255.06 L256.15,255.06 L256.96,255.06 L257.77,255.06 L258.57,255.06 L259.38,255.06 L260.19,255.06 L260.99,255.06 L261.80,255.06 L262.61,255.06 L263.41,255.06 L264.22,255.06 L265.03,255.06 L265.83,255.06 L266.64,255.06 L267.45,255.06 L268.25,255.06 L269.06,255.06 L269.87,255.06 L270.67,255.06 L271.48,255.06 L272.29,255.06 L273.09,255.06 L273.90,255.06 L274.71,255.06 L275.51,255.06 L276.32,255.06 L277.13,255.06 L277.93,255.06 L278.74,255.06 L279.55,255.06 L280.35,255.06 L281.16,255.06 L281.97,255.06 L282.77,255.06 L283.58,255.06 L284.39,255.06 L285.19,255.06 L286.00,255.06 " fill="none" stroke="#2f6fec" stroke-width="1.8"/><text x="282" y="250" font-size="9" fill="#2f6fec" text-anchor="end">position</text><path d="M44.00,323.29 L44.81,309.00 L45.61,297.01 L46.42,287.04 L47.23,278.84 L48.03,272.19 L48.84,266.89 L49.65,262.78 L50.45,259.70 L51.26,257.49 L52.07,256.06 L52.87,255.28 L53.68,255.06 L54.49,255.31 L55.29,255.97 L56.10,256.96 L56.91,258.22 L57.71,259.71 L58.52,261.38 L59.33,263.19 L60.13,265.11 L60.94,267.11 L61.75,269.17 L62.55,271.25 L63.36,273.36 L64.17,275.45 L64.97,277.54 L65.78,279.60 L66.59,281.62 L67.39,283.60 L68.20,285.53 L69.01,287.41 L69.81,289.23 L70.62,290.99 L71.43,292.68 L72.23,294.32 L73.04,295.88 L73.85,297.39 L74.65,298.82 L75.46,300.20 L76.27,301.51 L77.07,302.76 L77.88,303.95 L78.69,305.08 L79.49,306.15 L80.30,307.17 L81.11,308.14 L81.91,309.05 L82.72,309.92 L83.53,310.74 L84.33,311.51 L85.14,312.24 L85.95,312.93 L86.75,313.58 L87.56,314.19 L88.37,314.77 L89.17,315.31 L89.98,315.82 L90.79,316.30 L91.59,316.75 L92.40,317.18 L93.21,317.57 L94.01,317.95 L94.82,318.30 L95.63,318.63 L96.43,318.93 L97.24,319.22 L98.05,319.49 L98.85,319.75 L99.66,319.98 L100.47,320.21 L101.27,320.41 L102.08,320.61 L102.89,320.79 L103.69,320.96 L104.50,321.12 L105.31,321.27 L106.11,321.40 L106.92,321.53 L107.73,321.65 L108.53,321.77 L109.34,321.87 L110.15,321.97 L110.95,322.06 L111.76,322.15 L112.57,322.23 L113.37,322.30 L114.18,322.37 L114.99,322.43 L115.79,322.49 L116.60,322.55 L117.41,322.60 L118.21,322.65 L119.02,322.70 L119.83,322.74 L120.63,322.78 L121.44,322.81 L122.25,322.85 L123.05,322.88 L123.86,322.91 L124.67,322.94 L125.47,322.96 L126.28,322.99 L127.09,323.01 L127.89,323.03 L128.70,323.05 L129.51,323.06 L130.31,323.08 L131.12,323.10 L131.93,323.11 L132.73,323.12 L133.54,323.14 L134.35,323.15 L135.15,323.16 L135.96,323.17 L136.77,323.18 L137.57,323.19 L138.38,323.19 L139.19,323.20 L139.99,323.21 L140.80,323.21 L141.61,323.22 L142.41,323.23 L143.22,323.23 L144.03,323.23 L144.83,323.24 L145.64,323.24 L146.45,323.25 L147.25,323.25 L148.06,323.25 L148.87,323.26 L149.67,323.26 L150.48,323.26 L151.29,323.26 L152.09,323.27 L152.90,323.27 L153.71,323.27 L154.51,323.27 L155.32,323.27 L156.13,323.28 L156.93,323.28 L157.74,323.28 L158.55,323.28 L159.35,323.28 L160.16,323.28 L160.97,323.28 L161.77,323.28 L162.58,323.28 L163.39,323.28 L164.19,323.29 L165.00,323.29 L165.81,323.29 L166.61,323.29 L167.42,323.29 L168.23,323.29 L169.03,323.29 L169.84,323.29 L170.65,323.29 L171.45,323.29 L172.26,323.29 L173.07,323.29 L173.87,323.29 L174.68,323.29 L175.49,323.29 L176.29,323.29 L177.10,323.29 L177.91,323.29 L178.71,323.29 L179.52,323.29 L180.33,323.29 L181.13,323.29 L181.94,323.29 L182.75,323.29 L183.55,323.29 L184.36,323.29 L185.17,323.29 L185.97,323.29 L186.78,323.29 L187.59,323.29 L188.39,323.29 L189.20,323.29 L190.01,323.29 L190.81,323.29 L191.62,323.29 L192.43,323.29 L193.23,323.29 L194.04,323.29 L194.85,323.29 L195.65,323.29 L196.46,323.29 L197.27,323.29 L198.07,323.29 L198.88,323.29 L199.69,323.29 L200.49,323.29 L201.30,323.29 L202.11,323.29 L202.91,323.29 L203.72,323.29 L204.53,323.29 L205.33,323.29 L206.14,323.29 L206.95,323.29 L207.75,323.29 L208.56,323.29 L209.37,323.29 L210.17,323.29 L210.98,323.29 L211.79,323.29 L212.59,323.29 L213.40,323.29 L214.21,323.29 L215.01,323.29 L215.82,323.29 L216.63,323.29 L217.43,323.29 L218.24,323.29 L219.05,323.29 L219.85,323.29 L220.66,323.29 L221.47,323.29 L222.27,323.29 L223.08,323.29 L223.89,323.29 L224.69,323.29 L225.50,323.29 L226.31,323.29 L227.11,323.29 L227.92,323.29 L228.73,323.29 L229.53,323.29 L230.34,323.29 L231.15,323.29 L231.95,323.29 L232.76,323.29 L233.57,323.29 L234.37,323.29 L235.18,323.29 L235.99,323.29 L236.79,323.29 L237.60,323.29 L238.41,323.29 L239.21,323.29 L240.02,323.29 L240.83,323.29 L241.63,323.29 L242.44,323.29 L243.25,323.29 L244.05,323.29 L244.86,323.29 L245.67,323.29 L246.47,323.29 L247.28,323.29 L248.09,323.29 L248.89,323.29 L249.70,323.29 L250.51,323.29 L251.31,323.29 L252.12,323.29 L252.93,323.29 L253.73,323.29 L254.54,323.29 L255.35,323.29 L256.15,323.29 L256.96,323.29 L257.77,323.29 L258.57,323.29 L259.38,323.29 L260.19,323.29 L260.99,323.29 L261.80,323.29 L262.61,323.29 L263.41,323.29 L264.22,323.29 L265.03,323.29 L265.83,323.29 L266.64,323.29 L267.45,323.29 L268.25,323.29 L269.06,323.29 L269.87,323.29 L270.67,323.29 L271.48,323.29 L272.29,323.29 L273.09,323.29 L273.90,323.29 L274.71,323.29 L275.51,323.29 L276.32,323.29 L277.13,323.29 L277.93,323.29 L278.74,323.29 L279.55,323.29 L280.35,323.29 L281.16,323.29 L281.97,323.29 L282.77,323.29 L283.58,323.29 L284.39,323.29 L285.19,323.29 L286.00,323.29 " fill="none" stroke="#e8833a" stroke-width="1.8" stroke-dasharray="4 3"/><text x="282" y="262" font-size="9" fill="#e8833a" text-anchor="end">velocity (norm.)</text><rect x="344" y="238" width="242" height="116" fill="#fafbfc" stroke="#e3e6ea"/><text x="344" y="229" font-size="12" font-weight="600" fill="#333">settle exit 0.24/0</text><line x1="344" x2="586" y1="323.29413" y2="323.29413" stroke="#d5d9de" stroke-dasharray="3 3"/><text x="340" y="326.29413" font-size="9" fill="#888" text-anchor="end">0</text><line x1="344" x2="586" y1="255.05882" y2="255.05882" stroke="#d5d9de" stroke-dasharray="3 3"/><text x="340" y="258.05884" font-size="9" fill="#888" text-anchor="end">1</text><text x="586" y="368" font-size="9" fill="#888" text-anchor="end">1.20 s</text><line x1="392.4" x2="392.4" y1="238" y2="354" stroke="#d64545" stroke-width="1" stroke-dasharray="2 3"/><path d="M344.00,323.29 L344.81,322.95 L345.61,321.99 L346.42,320.56 L347.23,318.74 L348.03,316.65 L348.84,314.33 L349.65,311.87 L350.45,309.32 L351.26,306.71 L352.07,304.08 L352.87,301.46 L353.68,298.88 L354.49,296.36 L355.29,293.90 L356.10,291.52 L356.91,289.24 L357.71,287.04 L358.52,284.95 L359.33,282.95 L360.13,281.06 L360.94,279.27 L361.75,277.57 L362.55,275.98 L363.36,274.48 L364.17,273.07 L364.97,271.75 L365.78,270.51 L366.59,269.36 L367.39,268.28 L368.20,267.27 L369.01,266.34 L369.81,265.46 L370.62,264.66 L371.43,263.90 L372.23,263.21 L373.04,262.56 L373.85,261.96 L374.65,261.41 L375.46,260.90 L376.27,260.43 L377.07,259.99 L377.88,259.59 L378.69,259.22 L379.49,258.88 L380.30,258.56 L381.11,258.27 L381.91,258.00 L382.72,257.76 L383.53,257.53 L384.33,257.32 L385.14,257.13 L385.95,256.96 L386.75,256.80 L387.56,256.65 L388.37,256.51 L389.17,256.39 L389.98,256.27 L390.79,256.17 L391.59,256.07 L392.40,255.99 L393.21,255.91 L394.01,255.83 L394.82,255.77 L395.63,255.70 L396.43,255.65 L397.24,255.60 L398.05,255.55 L398.85,255.51 L399.66,255.47 L400.47,255.43 L401.27,255.40 L402.08,255.37 L402.89,255.34 L403.69,255.32 L404.50,255.29 L405.31,255.27 L406.11,255.25 L406.92,255.24 L407.73,255.22 L408.53,255.21 L409.34,255.19 L410.15,255.18 L410.95,255.17 L411.76,255.16 L412.57,255.15 L413.37,255.14 L414.18,255.14 L414.99,255.13 L415.79,255.12 L416.60,255.12 L417.41,255.11 L418.21,255.11 L419.02,255.10 L419.83,255.10 L420.63,255.09 L421.44,255.09 L422.25,255.09 L423.05,255.09 L423.86,255.08 L424.67,255.08 L425.47,255.08 L426.28,255.08 L427.09,255.08 L427.89,255.07 L428.70,255.07 L429.51,255.07 L430.31,255.07 L431.12,255.07 L431.93,255.07 L432.73,255.07 L433.54,255.07 L434.35,255.07 L435.15,255.07 L435.96,255.06 L436.77,255.06 L437.57,255.06 L438.38,255.06 L439.19,255.06 L439.99,255.06 L440.80,255.06 L441.61,255.06 L442.41,255.06 L443.22,255.06 L444.03,255.06 L444.83,255.06 L445.64,255.06 L446.45,255.06 L447.25,255.06 L448.06,255.06 L448.87,255.06 L449.67,255.06 L450.48,255.06 L451.29,255.06 L452.09,255.06 L452.90,255.06 L453.71,255.06 L454.51,255.06 L455.32,255.06 L456.13,255.06 L456.93,255.06 L457.74,255.06 L458.55,255.06 L459.35,255.06 L460.16,255.06 L460.97,255.06 L461.77,255.06 L462.58,255.06 L463.39,255.06 L464.19,255.06 L465.00,255.06 L465.81,255.06 L466.61,255.06 L467.42,255.06 L468.23,255.06 L469.03,255.06 L469.84,255.06 L470.65,255.06 L471.45,255.06 L472.26,255.06 L473.07,255.06 L473.87,255.06 L474.68,255.06 L475.49,255.06 L476.29,255.06 L477.10,255.06 L477.91,255.06 L478.71,255.06 L479.52,255.06 L480.33,255.06 L481.13,255.06 L481.94,255.06 L482.75,255.06 L483.55,255.06 L484.36,255.06 L485.17,255.06 L485.97,255.06 L486.78,255.06 L487.59,255.06 L488.39,255.06 L489.20,255.06 L490.01,255.06 L490.81,255.06 L491.62,255.06 L492.43,255.06 L493.23,255.06 L494.04,255.06 L494.85,255.06 L495.65,255.06 L496.46,255.06 L497.27,255.06 L498.07,255.06 L498.88,255.06 L499.69,255.06 L500.49,255.06 L501.30,255.06 L502.11,255.06 L502.91,255.06 L503.72,255.06 L504.53,255.06 L505.33,255.06 L506.14,255.06 L506.95,255.06 L507.75,255.06 L508.56,255.06 L509.37,255.06 L510.17,255.06 L510.98,255.06 L511.79,255.06 L512.59,255.06 L513.40,255.06 L514.21,255.06 L515.01,255.06 L515.82,255.06 L516.63,255.06 L517.43,255.06 L518.24,255.06 L519.05,255.06 L519.85,255.06 L520.66,255.06 L521.47,255.06 L522.27,255.06 L523.08,255.06 L523.89,255.06 L524.69,255.06 L525.50,255.06 L526.31,255.06 L527.11,255.06 L527.92,255.06 L528.73,255.06 L529.53,255.06 L530.34,255.06 L531.15,255.06 L531.95,255.06 L532.76,255.06 L533.57,255.06 L534.37,255.06 L535.18,255.06 L535.99,255.06 L536.79,255.06 L537.60,255.06 L538.41,255.06 L539.21,255.06 L540.02,255.06 L540.83,255.06 L541.63,255.06 L542.44,255.06 L543.25,255.06 L544.05,255.06 L544.86,255.06 L545.67,255.06 L546.47,255.06 L547.28,255.06 L548.09,255.06 L548.89,255.06 L549.70,255.06 L550.51,255.06 L551.31,255.06 L552.12,255.06 L552.93,255.06 L553.73,255.06 L554.54,255.06 L555.35,255.06 L556.15,255.06 L556.96,255.06 L557.77,255.06 L558.57,255.06 L559.38,255.06 L560.19,255.06 L560.99,255.06 L561.80,255.06 L562.61,255.06 L563.41,255.06 L564.22,255.06 L565.03,255.06 L565.83,255.06 L566.64,255.06 L567.45,255.06 L568.25,255.06 L569.06,255.06 L569.87,255.06 L570.67,255.06 L571.48,255.06 L572.29,255.06 L573.09,255.06 L573.90,255.06 L574.71,255.06 L575.51,255.06 L576.32,255.06 L577.13,255.06 L577.93,255.06 L578.74,255.06 L579.55,255.06 L580.35,255.06 L581.16,255.06 L581.97,255.06 L582.77,255.06 L583.58,255.06 L584.39,255.06 L585.19,255.06 L586.00,255.06 " fill="none" stroke="#2f6fec" stroke-width="1.8"/><text x="582" y="250" font-size="9" fill="#2f6fec" text-anchor="end">position</text><path d="M344.00,323.29 L344.81,305.78 L345.61,291.75 L346.42,280.69 L347.23,272.13 L348.03,265.70 L348.84,261.05 L349.65,257.90 L350.45,255.99 L351.26,255.10 L352.07,255.06 L352.87,255.70 L353.68,256.88 L354.49,258.50 L355.29,260.46 L356.10,262.66 L356.91,265.05 L357.71,267.56 L358.52,270.15 L359.33,272.78 L360.13,275.40 L360.94,278.01 L361.75,280.57 L362.55,283.07 L363.36,285.49 L364.17,287.83 L364.97,290.08 L365.78,292.23 L366.59,294.28 L367.39,296.24 L368.20,298.09 L369.01,299.84 L369.81,301.49 L370.62,303.04 L371.43,304.50 L372.23,305.87 L373.04,307.16 L373.85,308.36 L374.65,309.48 L375.46,310.52 L376.27,311.50 L377.07,312.41 L377.88,313.25 L378.69,314.03 L379.49,314.76 L380.30,315.43 L381.11,316.06 L381.91,316.64 L382.72,317.17 L383.53,317.66 L384.33,318.12 L385.14,318.54 L385.95,318.93 L386.75,319.29 L387.56,319.62 L388.37,319.92 L389.17,320.20 L389.98,320.46 L390.79,320.70 L391.59,320.92 L392.40,321.12 L393.21,321.30 L394.01,321.47 L394.82,321.62 L395.63,321.77 L396.43,321.90 L397.24,322.02 L398.05,322.13 L398.85,322.23 L399.66,322.32 L400.47,322.40 L401.27,322.48 L402.08,322.55 L402.89,322.61 L403.69,322.67 L404.50,322.73 L405.31,322.78 L406.11,322.82 L406.92,322.86 L407.73,322.90 L408.53,322.94 L409.34,322.97 L410.15,323.00 L410.95,323.02 L411.76,323.05 L412.57,323.07 L413.37,323.09 L414.18,323.11 L414.99,323.12 L415.79,323.14 L416.60,323.15 L417.41,323.17 L418.21,323.18 L419.02,323.19 L419.83,323.20 L420.63,323.21 L421.44,323.21 L422.25,323.22 L423.05,323.23 L423.86,323.23 L424.67,323.24 L425.47,323.24 L426.28,323.25 L427.09,323.25 L427.89,323.26 L428.70,323.26 L429.51,323.26 L430.31,323.27 L431.12,323.27 L431.93,323.27 L432.73,323.27 L433.54,323.27 L434.35,323.28 L435.15,323.28 L435.96,323.28 L436.77,323.28 L437.57,323.28 L438.38,323.28 L439.19,323.28 L439.99,323.29 L440.80,323.29 L441.61,323.29 L442.41,323.29 L443.22,323.29 L444.03,323.29 L444.83,323.29 L445.64,323.29 L446.45,323.29 L447.25,323.29 L448.06,323.29 L448.87,323.29 L449.67,323.29 L450.48,323.29 L451.29,323.29 L452.09,323.29 L452.90,323.29 L453.71,323.29 L454.51,323.29 L455.32,323.29 L456.13,323.29 L456.93,323.29 L457.74,323.29 L458.55,323.29 L459.35,323.29 L460.16,323.29 L460.97,323.29 L461.77,323.29 L462.58,323.29 L463.39,323.29 L464.19,323.29 L465.00,323.29 L465.81,323.29 L466.61,323.29 L467.42,323.29 L468.23,323.29 L469.03,323.29 L469.84,323.29 L470.65,323.29 L471.45,323.29 L472.26,323.29 L473.07,323.29 L473.87,323.29 L474.68,323.29 L475.49,323.29 L476.29,323.29 L477.10,323.29 L477.91,323.29 L478.71,323.29 L479.52,323.29 L480.33,323.29 L481.13,323.29 L481.94,323.29 L482.75,323.29 L483.55,323.29 L484.36,323.29 L485.17,323.29 L485.97,323.29 L486.78,323.29 L487.59,323.29 L488.39,323.29 L489.20,323.29 L490.01,323.29 L490.81,323.29 L491.62,323.29 L492.43,323.29 L493.23,323.29 L494.04,323.29 L494.85,323.29 L495.65,323.29 L496.46,323.29 L497.27,323.29 L498.07,323.29 L498.88,323.29 L499.69,323.29 L500.49,323.29 L501.30,323.29 L502.11,323.29 L502.91,323.29 L503.72,323.29 L504.53,323.29 L505.33,323.29 L506.14,323.29 L506.95,323.29 L507.75,323.29 L508.56,323.29 L509.37,323.29 L510.17,323.29 L510.98,323.29 L511.79,323.29 L512.59,323.29 L513.40,323.29 L514.21,323.29 L515.01,323.29 L515.82,323.29 L516.63,323.29 L517.43,323.29 L518.24,323.29 L519.05,323.29 L519.85,323.29 L520.66,323.29 L521.47,323.29 L522.27,323.29 L523.08,323.29 L523.89,323.29 L524.69,323.29 L525.50,323.29 L526.31,323.29 L527.11,323.29 L527.92,323.29 L528.73,323.29 L529.53,323.29 L530.34,323.29 L531.15,323.29 L531.95,323.29 L532.76,323.29 L533.57,323.29 L534.37,323.29 L535.18,323.29 L535.99,323.29 L536.79,323.29 L537.60,323.29 L538.41,323.29 L539.21,323.29 L540.02,323.29 L540.83,323.29 L541.63,323.29 L542.44,323.29 L543.25,323.29 L544.05,323.29 L544.86,323.29 L545.67,323.29 L546.47,323.29 L547.28,323.29 L548.09,323.29 L548.89,323.29 L549.70,323.29 L550.51,323.29 L551.31,323.29 L552.12,323.29 L552.93,323.29 L553.73,323.29 L554.54,323.29 L555.35,323.29 L556.15,323.29 L556.96,323.29 L557.77,323.29 L558.57,323.29 L559.38,323.29 L560.19,323.29 L560.99,323.29 L561.80,323.29 L562.61,323.29 L563.41,323.29 L564.22,323.29 L565.03,323.29 L565.83,323.29 L566.64,323.29 L567.45,323.29 L568.25,323.29 L569.06,323.29 L569.87,323.29 L570.67,323.29 L571.48,323.29 L572.29,323.29 L573.09,323.29 L573.90,323.29 L574.71,323.29 L575.51,323.29 L576.32,323.29 L577.13,323.29 L577.93,323.29 L578.74,323.29 L579.55,323.29 L580.35,323.29 L581.16,323.29 L581.97,323.29 L582.77,323.29 L583.58,323.29 L584.39,323.29 L585.19,323.29 L586.00,323.29 " fill="none" stroke="#e8833a" stroke-width="1.8" stroke-dasharray="4 3"/><text x="582" y="262" font-size="9" fill="#e8833a" text-anchor="end">velocity (norm.)</text><rect x="644" y="238" width="242" height="116" fill="#fafbfc" stroke="#e3e6ea"/><text x="644" y="229" font-size="12" font-weight="600" fill="#333">reflow 0.4/0</text><line x1="644" x2="886" y1="323.29413" y2="323.29413" stroke="#d5d9de" stroke-dasharray="3 3"/><text x="640" y="326.29413" font-size="9" fill="#888" text-anchor="end">0</text><line x1="644" x2="886" y1="255.05882" y2="255.05882" stroke="#d5d9de" stroke-dasharray="3 3"/><text x="640" y="258.05884" font-size="9" fill="#888" text-anchor="end">1</text><text x="886" y="368" font-size="9" fill="#888" text-anchor="end">1.20 s</text><line x1="724.6667" x2="724.6667" y1="238" y2="354" stroke="#d64545" stroke-width="1" stroke-dasharray="2 3"/><path d="M644.00,323.29 L644.81,323.16 L645.61,322.80 L646.42,322.22 L647.23,321.47 L648.03,320.56 L648.84,319.51 L649.65,318.34 L650.45,317.08 L651.26,315.74 L652.07,314.33 L652.87,312.87 L653.68,311.37 L654.49,309.83 L655.29,308.28 L656.10,306.71 L656.91,305.13 L657.71,303.55 L658.52,301.98 L659.33,300.43 L660.13,298.88 L660.94,297.36 L661.75,295.86 L662.55,294.39 L663.36,292.94 L664.17,291.52 L664.97,290.14 L665.78,288.79 L666.59,287.47 L667.39,286.19 L668.20,284.95 L669.01,283.74 L669.81,282.57 L670.62,281.43 L671.43,280.33 L672.23,279.27 L673.04,278.24 L673.85,277.25 L674.65,276.29 L675.46,275.37 L676.27,274.48 L677.07,273.62 L677.88,272.80 L678.69,272.00 L679.49,271.24 L680.30,270.51 L681.11,269.81 L681.91,269.13 L682.72,268.49 L683.53,267.87 L684.33,267.27 L685.14,266.70 L685.95,266.16 L686.75,265.63 L687.56,265.13 L688.37,264.66 L689.17,264.20 L689.98,263.76 L690.79,263.34 L691.59,262.94 L692.40,262.56 L693.21,262.20 L694.01,261.85 L694.82,261.52 L695.63,261.20 L696.43,260.90 L697.24,260.61 L698.05,260.34 L698.85,260.08 L699.66,259.83 L700.47,259.59 L701.27,259.36 L702.08,259.15 L702.89,258.94 L703.69,258.75 L704.50,258.56 L705.31,258.38 L706.11,258.21 L706.92,258.05 L707.73,257.90 L708.53,257.76 L709.34,257.62 L710.15,257.49 L710.95,257.36 L711.76,257.24 L712.57,257.13 L713.37,257.03 L714.18,256.92 L714.99,256.83 L715.79,256.74 L716.60,256.65 L717.41,256.57 L718.21,256.49 L719.02,256.41 L719.83,256.34 L720.63,256.27 L721.44,256.21 L722.25,256.15 L723.05,256.09 L723.86,256.04 L724.67,255.99 L725.47,255.94 L726.28,255.89 L727.09,255.85 L727.89,255.81 L728.70,255.77 L729.51,255.73 L730.31,255.69 L731.12,255.66 L731.93,255.63 L732.73,255.60 L733.54,255.57 L734.35,255.54 L735.15,255.51 L735.96,255.49 L736.77,255.47 L737.57,255.45 L738.38,255.42 L739.19,255.40 L739.99,255.39 L740.80,255.37 L741.61,255.35 L742.41,255.34 L743.22,255.32 L744.03,255.31 L744.83,255.29 L745.64,255.28 L746.45,255.27 L747.25,255.26 L748.06,255.25 L748.87,255.24 L749.67,255.23 L750.48,255.22 L751.29,255.21 L752.09,255.20 L752.90,255.19 L753.71,255.19 L754.51,255.18 L755.32,255.17 L756.13,255.17 L756.93,255.16 L757.74,255.15 L758.55,255.15 L759.35,255.14 L760.16,255.14 L760.97,255.14 L761.77,255.13 L762.58,255.13 L763.39,255.12 L764.19,255.12 L765.00,255.12 L765.81,255.11 L766.61,255.11 L767.42,255.11 L768.23,255.10 L769.03,255.10 L769.84,255.10 L770.65,255.10 L771.45,255.10 L772.26,255.09 L773.07,255.09 L773.87,255.09 L774.68,255.09 L775.49,255.09 L776.29,255.08 L777.10,255.08 L777.91,255.08 L778.71,255.08 L779.52,255.08 L780.33,255.08 L781.13,255.08 L781.94,255.08 L782.75,255.08 L783.55,255.07 L784.36,255.07 L785.17,255.07 L785.97,255.07 L786.78,255.07 L787.59,255.07 L788.39,255.07 L789.20,255.07 L790.01,255.07 L790.81,255.07 L791.62,255.07 L792.43,255.07 L793.23,255.07 L794.04,255.07 L794.85,255.07 L795.65,255.07 L796.46,255.06 L797.27,255.06 L798.07,255.06 L798.88,255.06 L799.69,255.06 L800.49,255.06 L801.30,255.06 L802.11,255.06 L802.91,255.06 L803.72,255.06 L804.53,255.06 L805.33,255.06 L806.14,255.06 L806.95,255.06 L807.75,255.06 L808.56,255.06 L809.37,255.06 L810.17,255.06 L810.98,255.06 L811.79,255.06 L812.59,255.06 L813.40,255.06 L814.21,255.06 L815.01,255.06 L815.82,255.06 L816.63,255.06 L817.43,255.06 L818.24,255.06 L819.05,255.06 L819.85,255.06 L820.66,255.06 L821.47,255.06 L822.27,255.06 L823.08,255.06 L823.89,255.06 L824.69,255.06 L825.50,255.06 L826.31,255.06 L827.11,255.06 L827.92,255.06 L828.73,255.06 L829.53,255.06 L830.34,255.06 L831.15,255.06 L831.95,255.06 L832.76,255.06 L833.57,255.06 L834.37,255.06 L835.18,255.06 L835.99,255.06 L836.79,255.06 L837.60,255.06 L838.41,255.06 L839.21,255.06 L840.02,255.06 L840.83,255.06 L841.63,255.06 L842.44,255.06 L843.25,255.06 L844.05,255.06 L844.86,255.06 L845.67,255.06 L846.47,255.06 L847.28,255.06 L848.09,255.06 L848.89,255.06 L849.70,255.06 L850.51,255.06 L851.31,255.06 L852.12,255.06 L852.93,255.06 L853.73,255.06 L854.54,255.06 L855.35,255.06 L856.15,255.06 L856.96,255.06 L857.77,255.06 L858.57,255.06 L859.38,255.06 L860.19,255.06 L860.99,255.06 L861.80,255.06 L862.61,255.06 L863.41,255.06 L864.22,255.06 L865.03,255.06 L865.83,255.06 L866.64,255.06 L867.45,255.06 L868.25,255.06 L869.06,255.06 L869.87,255.06 L870.67,255.06 L871.48,255.06 L872.29,255.06 L873.09,255.06 L873.90,255.06 L874.71,255.06 L875.51,255.06 L876.32,255.06 L877.13,255.06 L877.93,255.06 L878.74,255.06 L879.55,255.06 L880.35,255.06 L881.16,255.06 L881.97,255.06 L882.77,255.06 L883.58,255.06 L884.39,255.06 L885.19,255.06 L886.00,255.06 " fill="none" stroke="#2f6fec" stroke-width="1.8"/><text x="882" y="250" font-size="9" fill="#2f6fec" text-anchor="end">position</text><path d="M644.00,323.29 L644.81,312.35 L645.61,302.74 L646.42,294.34 L647.23,287.04 L648.03,280.73 L648.84,275.33 L649.65,270.74 L650.45,266.89 L651.26,263.71 L652.07,261.12 L652.87,259.07 L653.68,257.49 L654.49,256.35 L655.29,255.59 L656.10,255.18 L656.91,255.06 L657.71,255.21 L658.52,255.59 L659.33,256.19 L660.13,256.96 L660.94,257.88 L661.75,258.94 L662.55,260.11 L663.36,261.38 L664.17,262.73 L664.97,264.14 L665.78,265.61 L666.59,267.11 L667.39,268.65 L668.20,270.21 L669.01,271.78 L669.81,273.36 L670.62,274.93 L671.43,276.50 L672.23,278.06 L673.04,279.60 L673.85,281.12 L674.65,282.62 L675.46,284.09 L676.27,285.53 L677.07,286.95 L677.88,288.33 L678.69,289.67 L679.49,290.99 L680.30,292.27 L681.11,293.51 L681.91,294.71 L682.72,295.88 L683.53,297.02 L684.33,298.11 L685.14,299.17 L685.95,300.20 L686.75,301.19 L687.56,302.14 L688.37,303.06 L689.17,303.95 L689.98,304.80 L690.79,305.62 L691.59,306.41 L692.40,307.17 L693.21,307.90 L694.01,308.60 L694.82,309.28 L695.63,309.92 L696.43,310.54 L697.24,311.13 L698.05,311.70 L698.85,312.24 L699.66,312.76 L700.47,313.26 L701.27,313.74 L702.08,314.19 L702.89,314.63 L703.69,315.04 L704.50,315.44 L705.31,315.82 L706.11,316.18 L706.92,316.53 L707.73,316.86 L708.53,317.18 L709.34,317.48 L710.15,317.76 L710.95,318.04 L711.76,318.30 L712.57,318.55 L713.37,318.78 L714.18,319.01 L714.99,319.22 L715.79,319.43 L716.60,319.62 L717.41,319.81 L718.21,319.98 L719.02,320.15 L719.83,320.31 L720.63,320.46 L721.44,320.61 L722.25,320.75 L723.05,320.88 L723.86,321.00 L724.67,321.12 L725.47,321.23 L726.28,321.34 L727.09,321.44 L727.89,321.53 L728.70,321.62 L729.51,321.71 L730.31,321.79 L731.12,321.87 L731.93,321.95 L732.73,322.02 L733.54,322.08 L734.35,322.15 L735.15,322.21 L735.96,322.26 L736.77,322.32 L737.57,322.37 L738.38,322.42 L739.19,322.47 L739.99,322.51 L740.80,322.55 L741.61,322.59 L742.41,322.63 L743.22,322.66 L744.03,322.70 L744.83,322.73 L745.64,322.76 L746.45,322.79 L747.25,322.81 L748.06,322.84 L748.87,322.86 L749.67,322.89 L750.48,322.91 L751.29,322.93 L752.09,322.95 L752.90,322.97 L753.71,322.99 L754.51,323.00 L755.32,323.02 L756.13,323.03 L756.93,323.05 L757.74,323.06 L758.55,323.07 L759.35,323.09 L760.16,323.10 L760.97,323.11 L761.77,323.12 L762.58,323.13 L763.39,323.14 L764.19,323.14 L765.00,323.15 L765.81,323.16 L766.61,323.17 L767.42,323.17 L768.23,323.18 L769.03,323.19 L769.84,323.19 L770.65,323.20 L771.45,323.20 L772.26,323.21 L773.07,323.21 L773.87,323.22 L774.68,323.22 L775.49,323.23 L776.29,323.23 L777.10,323.23 L777.91,323.24 L778.71,323.24 L779.52,323.24 L780.33,323.25 L781.13,323.25 L781.94,323.25 L782.75,323.25 L783.55,323.26 L784.36,323.26 L785.17,323.26 L785.97,323.26 L786.78,323.26 L787.59,323.27 L788.39,323.27 L789.20,323.27 L790.01,323.27 L790.81,323.27 L791.62,323.27 L792.43,323.27 L793.23,323.27 L794.04,323.28 L794.85,323.28 L795.65,323.28 L796.46,323.28 L797.27,323.28 L798.07,323.28 L798.88,323.28 L799.69,323.28 L800.49,323.28 L801.30,323.28 L802.11,323.28 L802.91,323.28 L803.72,323.29 L804.53,323.29 L805.33,323.29 L806.14,323.29 L806.95,323.29 L807.75,323.29 L808.56,323.29 L809.37,323.29 L810.17,323.29 L810.98,323.29 L811.79,323.29 L812.59,323.29 L813.40,323.29 L814.21,323.29 L815.01,323.29 L815.82,323.29 L816.63,323.29 L817.43,323.29 L818.24,323.29 L819.05,323.29 L819.85,323.29 L820.66,323.29 L821.47,323.29 L822.27,323.29 L823.08,323.29 L823.89,323.29 L824.69,323.29 L825.50,323.29 L826.31,323.29 L827.11,323.29 L827.92,323.29 L828.73,323.29 L829.53,323.29 L830.34,323.29 L831.15,323.29 L831.95,323.29 L832.76,323.29 L833.57,323.29 L834.37,323.29 L835.18,323.29 L835.99,323.29 L836.79,323.29 L837.60,323.29 L838.41,323.29 L839.21,323.29 L840.02,323.29 L840.83,323.29 L841.63,323.29 L842.44,323.29 L843.25,323.29 L844.05,323.29 L844.86,323.29 L845.67,323.29 L846.47,323.29 L847.28,323.29 L848.09,323.29 L848.89,323.29 L849.70,323.29 L850.51,323.29 L851.31,323.29 L852.12,323.29 L852.93,323.29 L853.73,323.29 L854.54,323.29 L855.35,323.29 L856.15,323.29 L856.96,323.29 L857.77,323.29 L858.57,323.29 L859.38,323.29 L860.19,323.29 L860.99,323.29 L861.80,323.29 L862.61,323.29 L863.41,323.29 L864.22,323.29 L865.03,323.29 L865.83,323.29 L866.64,323.29 L867.45,323.29 L868.25,323.29 L869.06,323.29 L869.87,323.29 L870.67,323.29 L871.48,323.29 L872.29,323.29 L873.09,323.29 L873.90,323.29 L874.71,323.29 L875.51,323.29 L876.32,323.29 L877.13,323.29 L877.93,323.29 L878.74,323.29 L879.55,323.29 L880.35,323.29 L881.16,323.29 L881.97,323.29 L882.77,323.29 L883.58,323.29 L884.39,323.29 L885.19,323.29 L886.00,323.29 " fill="none" stroke="#e8833a" stroke-width="1.8" stroke-dasharray="4 3"/><text x="882" y="262" font-size="9" fill="#e8833a" text-anchor="end">velocity (norm.)</text><rect x="944" y="238" width="242" height="116" fill="#fafbfc" stroke="#e3e6ea"/><text x="944" y="229" font-size="12" font-weight="600" fill="#333">reflow exit 0.32/0</text><line x1="944" x2="1186" y1="323.29413" y2="323.29413" stroke="#d5d9de" stroke-dasharray="3 3"/><text x="940" y="326.29413" font-size="9" fill="#888" text-anchor="end">0</text><line x1="944" x2="1186" y1="255.05882" y2="255.05882" stroke="#d5d9de" stroke-dasharray="3 3"/><text x="940" y="258.05884" font-size="9" fill="#888" text-anchor="end">1</text><text x="1186" y="368" font-size="9" fill="#888" text-anchor="end">1.20 s</text><line x1="1008.5333" x2="1008.5333" y1="238" y2="354" stroke="#d64545" stroke-width="1" stroke-dasharray="2 3"/><path d="M944.00,323.29 L944.81,323.09 L945.61,322.54 L946.42,321.67 L947.23,320.56 L948.03,319.23 L948.84,317.73 L949.65,316.08 L950.45,314.33 L951.26,312.50 L952.07,310.60 L952.87,308.67 L953.68,306.71 L954.49,304.74 L955.29,302.77 L956.10,300.81 L956.91,298.88 L957.71,296.98 L958.52,295.12 L959.33,293.30 L960.13,291.52 L960.94,289.80 L961.75,288.13 L962.55,286.51 L963.36,284.95 L964.17,283.44 L964.97,281.99 L965.78,280.60 L966.59,279.27 L967.39,277.99 L968.20,276.76 L969.01,275.59 L969.81,274.48 L970.62,273.41 L971.43,272.40 L972.23,271.43 L973.04,270.51 L973.85,269.64 L974.65,268.81 L975.46,268.02 L976.27,267.27 L977.07,266.56 L977.88,265.89 L978.69,265.26 L979.49,264.66 L980.30,264.09 L981.11,263.55 L981.91,263.04 L982.72,262.56 L983.53,262.11 L984.33,261.68 L985.14,261.28 L985.95,260.90 L986.75,260.54 L987.56,260.21 L988.37,259.89 L989.17,259.59 L989.98,259.31 L990.79,259.04 L991.59,258.79 L992.40,258.56 L993.21,258.34 L994.01,258.13 L994.82,257.94 L995.63,257.76 L996.43,257.59 L997.24,257.42 L998.05,257.27 L998.85,257.13 L999.66,257.00 L1000.47,256.87 L1001.27,256.76 L1002.08,256.65 L1002.89,256.55 L1003.69,256.45 L1004.50,256.36 L1005.31,256.27 L1006.11,256.20 L1006.92,256.12 L1007.73,256.05 L1008.53,255.99 L1009.34,255.93 L1010.15,255.87 L1010.95,255.82 L1011.76,255.77 L1012.57,255.72 L1013.37,255.68 L1014.18,255.63 L1014.99,255.60 L1015.79,255.56 L1016.60,255.53 L1017.41,255.50 L1018.21,255.47 L1019.02,255.44 L1019.83,255.41 L1020.63,255.39 L1021.44,255.37 L1022.25,255.35 L1023.05,255.33 L1023.86,255.31 L1024.67,255.29 L1025.47,255.28 L1026.28,255.26 L1027.09,255.25 L1027.89,255.24 L1028.70,255.22 L1029.51,255.21 L1030.31,255.20 L1031.12,255.19 L1031.93,255.18 L1032.73,255.18 L1033.54,255.17 L1034.35,255.16 L1035.15,255.15 L1035.96,255.15 L1036.77,255.14 L1037.57,255.14 L1038.38,255.13 L1039.19,255.12 L1039.99,255.12 L1040.80,255.12 L1041.61,255.11 L1042.41,255.11 L1043.22,255.11 L1044.03,255.10 L1044.83,255.10 L1045.64,255.10 L1046.45,255.09 L1047.25,255.09 L1048.06,255.09 L1048.87,255.09 L1049.67,255.09 L1050.48,255.08 L1051.29,255.08 L1052.09,255.08 L1052.90,255.08 L1053.71,255.08 L1054.51,255.08 L1055.32,255.07 L1056.13,255.07 L1056.93,255.07 L1057.74,255.07 L1058.55,255.07 L1059.35,255.07 L1060.16,255.07 L1060.97,255.07 L1061.77,255.07 L1062.58,255.07 L1063.39,255.07 L1064.19,255.07 L1065.00,255.07 L1065.81,255.07 L1066.61,255.06 L1067.42,255.06 L1068.23,255.06 L1069.03,255.06 L1069.84,255.06 L1070.65,255.06 L1071.45,255.06 L1072.26,255.06 L1073.07,255.06 L1073.87,255.06 L1074.68,255.06 L1075.49,255.06 L1076.29,255.06 L1077.10,255.06 L1077.91,255.06 L1078.71,255.06 L1079.52,255.06 L1080.33,255.06 L1081.13,255.06 L1081.94,255.06 L1082.75,255.06 L1083.55,255.06 L1084.36,255.06 L1085.17,255.06 L1085.97,255.06 L1086.78,255.06 L1087.59,255.06 L1088.39,255.06 L1089.20,255.06 L1090.01,255.06 L1090.81,255.06 L1091.62,255.06 L1092.43,255.06 L1093.23,255.06 L1094.04,255.06 L1094.85,255.06 L1095.65,255.06 L1096.46,255.06 L1097.27,255.06 L1098.07,255.06 L1098.88,255.06 L1099.69,255.06 L1100.49,255.06 L1101.30,255.06 L1102.11,255.06 L1102.91,255.06 L1103.72,255.06 L1104.53,255.06 L1105.33,255.06 L1106.14,255.06 L1106.95,255.06 L1107.75,255.06 L1108.56,255.06 L1109.37,255.06 L1110.17,255.06 L1110.98,255.06 L1111.79,255.06 L1112.59,255.06 L1113.40,255.06 L1114.21,255.06 L1115.01,255.06 L1115.82,255.06 L1116.63,255.06 L1117.43,255.06 L1118.24,255.06 L1119.05,255.06 L1119.85,255.06 L1120.66,255.06 L1121.47,255.06 L1122.27,255.06 L1123.08,255.06 L1123.89,255.06 L1124.69,255.06 L1125.50,255.06 L1126.31,255.06 L1127.11,255.06 L1127.92,255.06 L1128.73,255.06 L1129.53,255.06 L1130.34,255.06 L1131.15,255.06 L1131.95,255.06 L1132.76,255.06 L1133.57,255.06 L1134.37,255.06 L1135.18,255.06 L1135.99,255.06 L1136.79,255.06 L1137.60,255.06 L1138.41,255.06 L1139.21,255.06 L1140.02,255.06 L1140.83,255.06 L1141.63,255.06 L1142.44,255.06 L1143.25,255.06 L1144.05,255.06 L1144.86,255.06 L1145.67,255.06 L1146.47,255.06 L1147.28,255.06 L1148.09,255.06 L1148.89,255.06 L1149.70,255.06 L1150.51,255.06 L1151.31,255.06 L1152.12,255.06 L1152.93,255.06 L1153.73,255.06 L1154.54,255.06 L1155.35,255.06 L1156.15,255.06 L1156.96,255.06 L1157.77,255.06 L1158.57,255.06 L1159.38,255.06 L1160.19,255.06 L1160.99,255.06 L1161.80,255.06 L1162.61,255.06 L1163.41,255.06 L1164.22,255.06 L1165.03,255.06 L1165.83,255.06 L1166.64,255.06 L1167.45,255.06 L1168.25,255.06 L1169.06,255.06 L1169.87,255.06 L1170.67,255.06 L1171.48,255.06 L1172.29,255.06 L1173.09,255.06 L1173.90,255.06 L1174.71,255.06 L1175.51,255.06 L1176.32,255.06 L1177.13,255.06 L1177.93,255.06 L1178.74,255.06 L1179.55,255.06 L1180.35,255.06 L1181.16,255.06 L1181.97,255.06 L1182.77,255.06 L1183.58,255.06 L1184.39,255.06 L1185.19,255.06 L1186.00,255.06 " fill="none" stroke="#2f6fec" stroke-width="1.8"/><text x="1182" y="250" font-size="9" fill="#2f6fec" text-anchor="end">position</text><path d="M944.00,323.29 L944.81,309.82 L945.61,298.39 L946.42,288.76 L947.23,280.72 L948.03,274.10 L948.84,268.72 L949.65,264.43 L950.45,261.11 L951.26,258.62 L952.07,256.86 L952.87,255.74 L953.68,255.16 L954.49,255.06 L955.29,255.36 L956.10,256.01 L956.91,256.94 L957.71,258.12 L958.52,259.50 L959.33,261.04 L960.13,262.71 L960.94,264.49 L961.75,266.34 L962.55,268.25 L963.36,270.20 L964.17,272.16 L964.97,274.13 L965.78,276.10 L966.59,278.05 L967.39,279.97 L968.20,281.86 L969.01,283.72 L969.81,285.52 L970.62,287.29 L971.43,289.00 L972.23,290.66 L973.04,292.26 L973.85,293.81 L974.65,295.30 L975.46,296.73 L976.27,298.11 L977.07,299.43 L977.88,300.69 L978.69,301.90 L979.49,303.06 L980.30,304.16 L981.11,305.21 L981.91,306.22 L982.72,307.17 L983.53,308.08 L984.33,308.94 L985.14,309.76 L985.95,310.54 L986.75,311.27 L987.56,311.97 L988.37,312.63 L989.17,313.26 L989.98,313.85 L990.79,314.41 L991.59,314.94 L992.40,315.44 L993.21,315.91 L994.01,316.36 L994.82,316.78 L995.63,317.18 L996.43,317.55 L997.24,317.90 L998.05,318.23 L998.85,318.55 L999.66,318.84 L1000.47,319.12 L1001.27,319.38 L1002.08,319.62 L1002.89,319.85 L1003.69,320.07 L1004.50,320.27 L1005.31,320.46 L1006.11,320.64 L1006.92,320.81 L1007.73,320.97 L1008.53,321.12 L1009.34,321.26 L1010.15,321.39 L1010.95,321.51 L1011.76,321.62 L1012.57,321.73 L1013.37,321.83 L1014.18,321.93 L1014.99,322.02 L1015.79,322.10 L1016.60,322.18 L1017.41,322.25 L1018.21,322.32 L1019.02,322.38 L1019.83,322.44 L1020.63,322.50 L1021.44,322.55 L1022.25,322.60 L1023.05,322.65 L1023.86,322.69 L1024.67,322.73 L1025.47,322.77 L1026.28,322.80 L1027.09,322.83 L1027.89,322.86 L1028.70,322.89 L1029.51,322.92 L1030.31,322.94 L1031.12,322.97 L1031.93,322.99 L1032.73,323.01 L1033.54,323.03 L1034.35,323.05 L1035.15,323.06 L1035.96,323.08 L1036.77,323.09 L1037.57,323.11 L1038.38,323.12 L1039.19,323.13 L1039.99,323.14 L1040.80,323.15 L1041.61,323.16 L1042.41,323.17 L1043.22,323.18 L1044.03,323.19 L1044.83,323.19 L1045.64,323.20 L1046.45,323.21 L1047.25,323.21 L1048.06,323.22 L1048.87,323.22 L1049.67,323.23 L1050.48,323.23 L1051.29,323.24 L1052.09,323.24 L1052.90,323.25 L1053.71,323.25 L1054.51,323.25 L1055.32,323.25 L1056.13,323.26 L1056.93,323.26 L1057.74,323.26 L1058.55,323.26 L1059.35,323.27 L1060.16,323.27 L1060.97,323.27 L1061.77,323.27 L1062.58,323.27 L1063.39,323.27 L1064.19,323.28 L1065.00,323.28 L1065.81,323.28 L1066.61,323.28 L1067.42,323.28 L1068.23,323.28 L1069.03,323.28 L1069.84,323.28 L1070.65,323.28 L1071.45,323.28 L1072.26,323.29 L1073.07,323.29 L1073.87,323.29 L1074.68,323.29 L1075.49,323.29 L1076.29,323.29 L1077.10,323.29 L1077.91,323.29 L1078.71,323.29 L1079.52,323.29 L1080.33,323.29 L1081.13,323.29 L1081.94,323.29 L1082.75,323.29 L1083.55,323.29 L1084.36,323.29 L1085.17,323.29 L1085.97,323.29 L1086.78,323.29 L1087.59,323.29 L1088.39,323.29 L1089.20,323.29 L1090.01,323.29 L1090.81,323.29 L1091.62,323.29 L1092.43,323.29 L1093.23,323.29 L1094.04,323.29 L1094.85,323.29 L1095.65,323.29 L1096.46,323.29 L1097.27,323.29 L1098.07,323.29 L1098.88,323.29 L1099.69,323.29 L1100.49,323.29 L1101.30,323.29 L1102.11,323.29 L1102.91,323.29 L1103.72,323.29 L1104.53,323.29 L1105.33,323.29 L1106.14,323.29 L1106.95,323.29 L1107.75,323.29 L1108.56,323.29 L1109.37,323.29 L1110.17,323.29 L1110.98,323.29 L1111.79,323.29 L1112.59,323.29 L1113.40,323.29 L1114.21,323.29 L1115.01,323.29 L1115.82,323.29 L1116.63,323.29 L1117.43,323.29 L1118.24,323.29 L1119.05,323.29 L1119.85,323.29 L1120.66,323.29 L1121.47,323.29 L1122.27,323.29 L1123.08,323.29 L1123.89,323.29 L1124.69,323.29 L1125.50,323.29 L1126.31,323.29 L1127.11,323.29 L1127.92,323.29 L1128.73,323.29 L1129.53,323.29 L1130.34,323.29 L1131.15,323.29 L1131.95,323.29 L1132.76,323.29 L1133.57,323.29 L1134.37,323.29 L1135.18,323.29 L1135.99,323.29 L1136.79,323.29 L1137.60,323.29 L1138.41,323.29 L1139.21,323.29 L1140.02,323.29 L1140.83,323.29 L1141.63,323.29 L1142.44,323.29 L1143.25,323.29 L1144.05,323.29 L1144.86,323.29 L1145.67,323.29 L1146.47,323.29 L1147.28,323.29 L1148.09,323.29 L1148.89,323.29 L1149.70,323.29 L1150.51,323.29 L1151.31,323.29 L1152.12,323.29 L1152.93,323.29 L1153.73,323.29 L1154.54,323.29 L1155.35,323.29 L1156.15,323.29 L1156.96,323.29 L1157.77,323.29 L1158.57,323.29 L1159.38,323.29 L1160.19,323.29 L1160.99,323.29 L1161.80,323.29 L1162.61,323.29 L1163.41,323.29 L1164.22,323.29 L1165.03,323.29 L1165.83,323.29 L1166.64,323.29 L1167.45,323.29 L1168.25,323.29 L1169.06,323.29 L1169.87,323.29 L1170.67,323.29 L1171.48,323.29 L1172.29,323.29 L1173.09,323.29 L1173.90,323.29 L1174.71,323.29 L1175.51,323.29 L1176.32,323.29 L1177.13,323.29 L1177.93,323.29 L1178.74,323.29 L1179.55,323.29 L1180.35,323.29 L1181.16,323.29 L1181.97,323.29 L1182.77,323.29 L1183.58,323.29 L1184.39,323.29 L1185.19,323.29 L1186.00,323.29 " fill="none" stroke="#e8833a" stroke-width="1.8" stroke-dasharray="4 3"/><text x="1182" y="262" font-size="9" fill="#e8833a" text-anchor="end">velocity (norm.)</text><rect x="44" y="408" width="242" height="116" fill="#fafbfc" stroke="#e3e6ea"/><text x="44" y="399" font-size="12" font-weight="600" fill="#333">glide 0.32/0</text><line x1="44" x2="286" y1="493.29413" y2="493.29413" stroke="#d5d9de" stroke-dasharray="3 3"/><text x="40" y="496.29413" font-size="9" fill="#888" text-anchor="end">0</text><line x1="44" x2="286" y1="425.05884" y2="425.05884" stroke="#d5d9de" stroke-dasharray="3 3"/><text x="40" y="428.05884" font-size="9" fill="#888" text-anchor="end">1</text><text x="286" y="538" font-size="9" fill="#888" text-anchor="end">1.20 s</text><line x1="108.53333" x2="108.53333" y1="408" y2="524" stroke="#d64545" stroke-width="1" stroke-dasharray="2 3"/><path d="M44.00,493.29 L44.81,493.09 L45.61,492.54 L46.42,491.67 L47.23,490.56 L48.03,489.23 L48.84,487.73 L49.65,486.08 L50.45,484.33 L51.26,482.50 L52.07,480.60 L52.87,478.67 L53.68,476.71 L54.49,474.74 L55.29,472.77 L56.10,470.81 L56.91,468.88 L57.71,466.98 L58.52,465.12 L59.33,463.30 L60.13,461.52 L60.94,459.80 L61.75,458.13 L62.55,456.51 L63.36,454.95 L64.17,453.44 L64.97,451.99 L65.78,450.60 L66.59,449.27 L67.39,447.99 L68.20,446.76 L69.01,445.59 L69.81,444.48 L70.62,443.41 L71.43,442.40 L72.23,441.43 L73.04,440.51 L73.85,439.64 L74.65,438.81 L75.46,438.02 L76.27,437.27 L77.07,436.56 L77.88,435.89 L78.69,435.26 L79.49,434.66 L80.30,434.09 L81.11,433.55 L81.91,433.04 L82.72,432.56 L83.53,432.11 L84.33,431.68 L85.14,431.28 L85.95,430.90 L86.75,430.54 L87.56,430.21 L88.37,429.89 L89.17,429.59 L89.98,429.31 L90.79,429.04 L91.59,428.79 L92.40,428.56 L93.21,428.34 L94.01,428.13 L94.82,427.94 L95.63,427.76 L96.43,427.59 L97.24,427.42 L98.05,427.27 L98.85,427.13 L99.66,427.00 L100.47,426.87 L101.27,426.76 L102.08,426.65 L102.89,426.55 L103.69,426.45 L104.50,426.36 L105.31,426.27 L106.11,426.20 L106.92,426.12 L107.73,426.05 L108.53,425.99 L109.34,425.93 L110.15,425.87 L110.95,425.82 L111.76,425.77 L112.57,425.72 L113.37,425.68 L114.18,425.63 L114.99,425.60 L115.79,425.56 L116.60,425.53 L117.41,425.50 L118.21,425.47 L119.02,425.44 L119.83,425.41 L120.63,425.39 L121.44,425.37 L122.25,425.35 L123.05,425.33 L123.86,425.31 L124.67,425.29 L125.47,425.28 L126.28,425.26 L127.09,425.25 L127.89,425.24 L128.70,425.22 L129.51,425.21 L130.31,425.20 L131.12,425.19 L131.93,425.18 L132.73,425.18 L133.54,425.17 L134.35,425.16 L135.15,425.15 L135.96,425.15 L136.77,425.14 L137.57,425.14 L138.38,425.13 L139.19,425.12 L139.99,425.12 L140.80,425.12 L141.61,425.11 L142.41,425.11 L143.22,425.11 L144.03,425.10 L144.83,425.10 L145.64,425.10 L146.45,425.09 L147.25,425.09 L148.06,425.09 L148.87,425.09 L149.67,425.09 L150.48,425.08 L151.29,425.08 L152.09,425.08 L152.90,425.08 L153.71,425.08 L154.51,425.08 L155.32,425.07 L156.13,425.07 L156.93,425.07 L157.74,425.07 L158.55,425.07 L159.35,425.07 L160.16,425.07 L160.97,425.07 L161.77,425.07 L162.58,425.07 L163.39,425.07 L164.19,425.07 L165.00,425.07 L165.81,425.07 L166.61,425.06 L167.42,425.06 L168.23,425.06 L169.03,425.06 L169.84,425.06 L170.65,425.06 L171.45,425.06 L172.26,425.06 L173.07,425.06 L173.87,425.06 L174.68,425.06 L175.49,425.06 L176.29,425.06 L177.10,425.06 L177.91,425.06 L178.71,425.06 L179.52,425.06 L180.33,425.06 L181.13,425.06 L181.94,425.06 L182.75,425.06 L183.55,425.06 L184.36,425.06 L185.17,425.06 L185.97,425.06 L186.78,425.06 L187.59,425.06 L188.39,425.06 L189.20,425.06 L190.01,425.06 L190.81,425.06 L191.62,425.06 L192.43,425.06 L193.23,425.06 L194.04,425.06 L194.85,425.06 L195.65,425.06 L196.46,425.06 L197.27,425.06 L198.07,425.06 L198.88,425.06 L199.69,425.06 L200.49,425.06 L201.30,425.06 L202.11,425.06 L202.91,425.06 L203.72,425.06 L204.53,425.06 L205.33,425.06 L206.14,425.06 L206.95,425.06 L207.75,425.06 L208.56,425.06 L209.37,425.06 L210.17,425.06 L210.98,425.06 L211.79,425.06 L212.59,425.06 L213.40,425.06 L214.21,425.06 L215.01,425.06 L215.82,425.06 L216.63,425.06 L217.43,425.06 L218.24,425.06 L219.05,425.06 L219.85,425.06 L220.66,425.06 L221.47,425.06 L222.27,425.06 L223.08,425.06 L223.89,425.06 L224.69,425.06 L225.50,425.06 L226.31,425.06 L227.11,425.06 L227.92,425.06 L228.73,425.06 L229.53,425.06 L230.34,425.06 L231.15,425.06 L231.95,425.06 L232.76,425.06 L233.57,425.06 L234.37,425.06 L235.18,425.06 L235.99,425.06 L236.79,425.06 L237.60,425.06 L238.41,425.06 L239.21,425.06 L240.02,425.06 L240.83,425.06 L241.63,425.06 L242.44,425.06 L243.25,425.06 L244.05,425.06 L244.86,425.06 L245.67,425.06 L246.47,425.06 L247.28,425.06 L248.09,425.06 L248.89,425.06 L249.70,425.06 L250.51,425.06 L251.31,425.06 L252.12,425.06 L252.93,425.06 L253.73,425.06 L254.54,425.06 L255.35,425.06 L256.15,425.06 L256.96,425.06 L257.77,425.06 L258.57,425.06 L259.38,425.06 L260.19,425.06 L260.99,425.06 L261.80,425.06 L262.61,425.06 L263.41,425.06 L264.22,425.06 L265.03,425.06 L265.83,425.06 L266.64,425.06 L267.45,425.06 L268.25,425.06 L269.06,425.06 L269.87,425.06 L270.67,425.06 L271.48,425.06 L272.29,425.06 L273.09,425.06 L273.90,425.06 L274.71,425.06 L275.51,425.06 L276.32,425.06 L277.13,425.06 L277.93,425.06 L278.74,425.06 L279.55,425.06 L280.35,425.06 L281.16,425.06 L281.97,425.06 L282.77,425.06 L283.58,425.06 L284.39,425.06 L285.19,425.06 L286.00,425.06 " fill="none" stroke="#2f6fec" stroke-width="1.8"/><text x="282" y="420" font-size="9" fill="#2f6fec" text-anchor="end">position</text><path d="M44.00,493.29 L44.81,479.82 L45.61,468.39 L46.42,458.76 L47.23,450.72 L48.03,444.10 L48.84,438.72 L49.65,434.43 L50.45,431.11 L51.26,428.62 L52.07,426.86 L52.87,425.74 L53.68,425.16 L54.49,425.06 L55.29,425.36 L56.10,426.01 L56.91,426.94 L57.71,428.12 L58.52,429.50 L59.33,431.04 L60.13,432.71 L60.94,434.49 L61.75,436.34 L62.55,438.25 L63.36,440.20 L64.17,442.16 L64.97,444.13 L65.78,446.10 L66.59,448.05 L67.39,449.97 L68.20,451.86 L69.01,453.72 L69.81,455.52 L70.62,457.29 L71.43,459.00 L72.23,460.66 L73.04,462.26 L73.85,463.81 L74.65,465.30 L75.46,466.73 L76.27,468.11 L77.07,469.43 L77.88,470.69 L78.69,471.90 L79.49,473.06 L80.30,474.16 L81.11,475.21 L81.91,476.22 L82.72,477.17 L83.53,478.08 L84.33,478.94 L85.14,479.76 L85.95,480.54 L86.75,481.27 L87.56,481.97 L88.37,482.63 L89.17,483.26 L89.98,483.85 L90.79,484.41 L91.59,484.94 L92.40,485.44 L93.21,485.91 L94.01,486.36 L94.82,486.78 L95.63,487.18 L96.43,487.55 L97.24,487.90 L98.05,488.23 L98.85,488.55 L99.66,488.84 L100.47,489.12 L101.27,489.38 L102.08,489.62 L102.89,489.85 L103.69,490.07 L104.50,490.27 L105.31,490.46 L106.11,490.64 L106.92,490.81 L107.73,490.97 L108.53,491.12 L109.34,491.26 L110.15,491.39 L110.95,491.51 L111.76,491.62 L112.57,491.73 L113.37,491.83 L114.18,491.93 L114.99,492.02 L115.79,492.10 L116.60,492.18 L117.41,492.25 L118.21,492.32 L119.02,492.38 L119.83,492.44 L120.63,492.50 L121.44,492.55 L122.25,492.60 L123.05,492.65 L123.86,492.69 L124.67,492.73 L125.47,492.77 L126.28,492.80 L127.09,492.83 L127.89,492.86 L128.70,492.89 L129.51,492.92 L130.31,492.94 L131.12,492.97 L131.93,492.99 L132.73,493.01 L133.54,493.03 L134.35,493.05 L135.15,493.06 L135.96,493.08 L136.77,493.09 L137.57,493.11 L138.38,493.12 L139.19,493.13 L139.99,493.14 L140.80,493.15 L141.61,493.16 L142.41,493.17 L143.22,493.18 L144.03,493.19 L144.83,493.19 L145.64,493.20 L146.45,493.21 L147.25,493.21 L148.06,493.22 L148.87,493.22 L149.67,493.23 L150.48,493.23 L151.29,493.24 L152.09,493.24 L152.90,493.25 L153.71,493.25 L154.51,493.25 L155.32,493.25 L156.13,493.26 L156.93,493.26 L157.74,493.26 L158.55,493.26 L159.35,493.27 L160.16,493.27 L160.97,493.27 L161.77,493.27 L162.58,493.27 L163.39,493.27 L164.19,493.28 L165.00,493.28 L165.81,493.28 L166.61,493.28 L167.42,493.28 L168.23,493.28 L169.03,493.28 L169.84,493.28 L170.65,493.28 L171.45,493.28 L172.26,493.29 L173.07,493.29 L173.87,493.29 L174.68,493.29 L175.49,493.29 L176.29,493.29 L177.10,493.29 L177.91,493.29 L178.71,493.29 L179.52,493.29 L180.33,493.29 L181.13,493.29 L181.94,493.29 L182.75,493.29 L183.55,493.29 L184.36,493.29 L185.17,493.29 L185.97,493.29 L186.78,493.29 L187.59,493.29 L188.39,493.29 L189.20,493.29 L190.01,493.29 L190.81,493.29 L191.62,493.29 L192.43,493.29 L193.23,493.29 L194.04,493.29 L194.85,493.29 L195.65,493.29 L196.46,493.29 L197.27,493.29 L198.07,493.29 L198.88,493.29 L199.69,493.29 L200.49,493.29 L201.30,493.29 L202.11,493.29 L202.91,493.29 L203.72,493.29 L204.53,493.29 L205.33,493.29 L206.14,493.29 L206.95,493.29 L207.75,493.29 L208.56,493.29 L209.37,493.29 L210.17,493.29 L210.98,493.29 L211.79,493.29 L212.59,493.29 L213.40,493.29 L214.21,493.29 L215.01,493.29 L215.82,493.29 L216.63,493.29 L217.43,493.29 L218.24,493.29 L219.05,493.29 L219.85,493.29 L220.66,493.29 L221.47,493.29 L222.27,493.29 L223.08,493.29 L223.89,493.29 L224.69,493.29 L225.50,493.29 L226.31,493.29 L227.11,493.29 L227.92,493.29 L228.73,493.29 L229.53,493.29 L230.34,493.29 L231.15,493.29 L231.95,493.29 L232.76,493.29 L233.57,493.29 L234.37,493.29 L235.18,493.29 L235.99,493.29 L236.79,493.29 L237.60,493.29 L238.41,493.29 L239.21,493.29 L240.02,493.29 L240.83,493.29 L241.63,493.29 L242.44,493.29 L243.25,493.29 L244.05,493.29 L244.86,493.29 L245.67,493.29 L246.47,493.29 L247.28,493.29 L248.09,493.29 L248.89,493.29 L249.70,493.29 L250.51,493.29 L251.31,493.29 L252.12,493.29 L252.93,493.29 L253.73,493.29 L254.54,493.29 L255.35,493.29 L256.15,493.29 L256.96,493.29 L257.77,493.29 L258.57,493.29 L259.38,493.29 L260.19,493.29 L260.99,493.29 L261.80,493.29 L262.61,493.29 L263.41,493.29 L264.22,493.29 L265.03,493.29 L265.83,493.29 L266.64,493.29 L267.45,493.29 L268.25,493.29 L269.06,493.29 L269.87,493.29 L270.67,493.29 L271.48,493.29 L272.29,493.29 L273.09,493.29 L273.90,493.29 L274.71,493.29 L275.51,493.29 L276.32,493.29 L277.13,493.29 L277.93,493.29 L278.74,493.29 L279.55,493.29 L280.35,493.29 L281.16,493.29 L281.97,493.29 L282.77,493.29 L283.58,493.29 L284.39,493.29 L285.19,493.29 L286.00,493.29 " fill="none" stroke="#e8833a" stroke-width="1.8" stroke-dasharray="4 3"/><text x="282" y="432" font-size="9" fill="#e8833a" text-anchor="end">velocity (norm.)</text><rect x="344" y="408" width="242" height="116" fill="#fafbfc" stroke="#e3e6ea"/><text x="344" y="399" font-size="12" font-weight="600" fill="#333">glide exit 0.26/0</text><line x1="344" x2="586" y1="493.29413" y2="493.29413" stroke="#d5d9de" stroke-dasharray="3 3"/><text x="340" y="496.29413" font-size="9" fill="#888" text-anchor="end">0</text><line x1="344" x2="586" y1="425.05884" y2="425.05884" stroke="#d5d9de" stroke-dasharray="3 3"/><text x="340" y="428.05884" font-size="9" fill="#888" text-anchor="end">1</text><text x="586" y="538" font-size="9" fill="#888" text-anchor="end">1.20 s</text><line x1="396.43332" x2="396.43332" y1="408" y2="524" stroke="#d64545" stroke-width="1" stroke-dasharray="2 3"/><path d="M344.00,493.29 L344.81,493.00 L345.61,492.17 L346.42,490.92 L347.23,489.34 L348.03,487.48 L348.84,485.42 L349.65,483.21 L350.45,480.90 L351.26,478.52 L352.07,476.10 L352.87,473.68 L353.68,471.26 L354.49,468.88 L355.29,466.55 L356.10,464.27 L356.91,462.07 L357.71,459.93 L358.52,457.88 L359.33,455.90 L360.13,454.02 L360.94,452.21 L361.75,450.50 L362.55,448.87 L363.36,447.32 L364.17,445.86 L364.97,444.48 L365.78,443.17 L366.59,441.94 L367.39,440.79 L368.20,439.70 L369.01,438.68 L369.81,437.73 L370.62,436.83 L371.43,435.99 L372.23,435.21 L373.04,434.48 L373.85,433.79 L374.65,433.16 L375.46,432.56 L376.27,432.01 L377.07,431.49 L377.88,431.01 L378.69,430.57 L379.49,430.16 L380.30,429.77 L381.11,429.41 L381.91,429.08 L382.72,428.78 L383.53,428.49 L384.33,428.23 L385.14,427.98 L385.95,427.76 L386.75,427.55 L387.56,427.35 L388.37,427.17 L389.17,427.01 L389.98,426.86 L390.79,426.71 L391.59,426.58 L392.40,426.46 L393.21,426.35 L394.01,426.25 L394.82,426.15 L395.63,426.07 L396.43,425.99 L397.24,425.91 L398.05,425.84 L398.85,425.78 L399.66,425.72 L400.47,425.67 L401.27,425.62 L402.08,425.57 L402.89,425.53 L403.69,425.49 L404.50,425.46 L405.31,425.43 L406.11,425.40 L406.92,425.37 L407.73,425.34 L408.53,425.32 L409.34,425.30 L410.15,425.28 L410.95,425.26 L411.76,425.24 L412.57,425.23 L413.37,425.21 L414.18,425.20 L414.99,425.19 L415.79,425.18 L416.60,425.17 L417.41,425.16 L418.21,425.15 L419.02,425.14 L419.83,425.14 L420.63,425.13 L421.44,425.12 L422.25,425.12 L423.05,425.11 L423.86,425.11 L424.67,425.10 L425.47,425.10 L426.28,425.10 L427.09,425.09 L427.89,425.09 L428.70,425.09 L429.51,425.09 L430.31,425.08 L431.12,425.08 L431.93,425.08 L432.73,425.08 L433.54,425.08 L434.35,425.07 L435.15,425.07 L435.96,425.07 L436.77,425.07 L437.57,425.07 L438.38,425.07 L439.19,425.07 L439.99,425.07 L440.80,425.07 L441.61,425.07 L442.41,425.07 L443.22,425.06 L444.03,425.06 L444.83,425.06 L445.64,425.06 L446.45,425.06 L447.25,425.06 L448.06,425.06 L448.87,425.06 L449.67,425.06 L450.48,425.06 L451.29,425.06 L452.09,425.06 L452.90,425.06 L453.71,425.06 L454.51,425.06 L455.32,425.06 L456.13,425.06 L456.93,425.06 L457.74,425.06 L458.55,425.06 L459.35,425.06 L460.16,425.06 L460.97,425.06 L461.77,425.06 L462.58,425.06 L463.39,425.06 L464.19,425.06 L465.00,425.06 L465.81,425.06 L466.61,425.06 L467.42,425.06 L468.23,425.06 L469.03,425.06 L469.84,425.06 L470.65,425.06 L471.45,425.06 L472.26,425.06 L473.07,425.06 L473.87,425.06 L474.68,425.06 L475.49,425.06 L476.29,425.06 L477.10,425.06 L477.91,425.06 L478.71,425.06 L479.52,425.06 L480.33,425.06 L481.13,425.06 L481.94,425.06 L482.75,425.06 L483.55,425.06 L484.36,425.06 L485.17,425.06 L485.97,425.06 L486.78,425.06 L487.59,425.06 L488.39,425.06 L489.20,425.06 L490.01,425.06 L490.81,425.06 L491.62,425.06 L492.43,425.06 L493.23,425.06 L494.04,425.06 L494.85,425.06 L495.65,425.06 L496.46,425.06 L497.27,425.06 L498.07,425.06 L498.88,425.06 L499.69,425.06 L500.49,425.06 L501.30,425.06 L502.11,425.06 L502.91,425.06 L503.72,425.06 L504.53,425.06 L505.33,425.06 L506.14,425.06 L506.95,425.06 L507.75,425.06 L508.56,425.06 L509.37,425.06 L510.17,425.06 L510.98,425.06 L511.79,425.06 L512.59,425.06 L513.40,425.06 L514.21,425.06 L515.01,425.06 L515.82,425.06 L516.63,425.06 L517.43,425.06 L518.24,425.06 L519.05,425.06 L519.85,425.06 L520.66,425.06 L521.47,425.06 L522.27,425.06 L523.08,425.06 L523.89,425.06 L524.69,425.06 L525.50,425.06 L526.31,425.06 L527.11,425.06 L527.92,425.06 L528.73,425.06 L529.53,425.06 L530.34,425.06 L531.15,425.06 L531.95,425.06 L532.76,425.06 L533.57,425.06 L534.37,425.06 L535.18,425.06 L535.99,425.06 L536.79,425.06 L537.60,425.06 L538.41,425.06 L539.21,425.06 L540.02,425.06 L540.83,425.06 L541.63,425.06 L542.44,425.06 L543.25,425.06 L544.05,425.06 L544.86,425.06 L545.67,425.06 L546.47,425.06 L547.28,425.06 L548.09,425.06 L548.89,425.06 L549.70,425.06 L550.51,425.06 L551.31,425.06 L552.12,425.06 L552.93,425.06 L553.73,425.06 L554.54,425.06 L555.35,425.06 L556.15,425.06 L556.96,425.06 L557.77,425.06 L558.57,425.06 L559.38,425.06 L560.19,425.06 L560.99,425.06 L561.80,425.06 L562.61,425.06 L563.41,425.06 L564.22,425.06 L565.03,425.06 L565.83,425.06 L566.64,425.06 L567.45,425.06 L568.25,425.06 L569.06,425.06 L569.87,425.06 L570.67,425.06 L571.48,425.06 L572.29,425.06 L573.09,425.06 L573.90,425.06 L574.71,425.06 L575.51,425.06 L576.32,425.06 L577.13,425.06 L577.93,425.06 L578.74,425.06 L579.55,425.06 L580.35,425.06 L581.16,425.06 L581.97,425.06 L582.77,425.06 L583.58,425.06 L584.39,425.06 L585.19,425.06 L586.00,425.06 " fill="none" stroke="#2f6fec" stroke-width="1.8"/><text x="582" y="420" font-size="9" fill="#2f6fec" text-anchor="end">position</text><path d="M344.00,493.29 L344.81,477.01 L345.61,463.72 L346.42,453.02 L347.23,444.55 L348.03,437.97 L348.84,433.03 L349.65,429.46 L350.45,427.06 L351.26,425.65 L352.07,425.06 L352.87,425.15 L353.68,425.81 L354.49,426.92 L355.29,428.40 L356.10,430.17 L356.91,432.17 L357.71,434.33 L358.52,436.61 L359.33,438.98 L360.13,441.39 L360.94,443.81 L361.75,446.23 L362.55,448.63 L363.36,450.98 L364.17,453.28 L364.97,455.51 L365.78,457.67 L366.59,459.76 L367.39,461.76 L368.20,463.68 L369.01,465.51 L369.81,467.26 L370.62,468.92 L371.43,470.49 L372.23,471.99 L373.04,473.40 L373.85,474.73 L374.65,475.98 L375.46,477.16 L376.27,478.27 L377.07,479.32 L377.88,480.30 L378.69,481.21 L379.49,482.07 L380.30,482.87 L381.11,483.62 L381.91,484.32 L382.72,484.98 L383.53,485.59 L384.33,486.15 L385.14,486.68 L385.95,487.17 L386.75,487.63 L387.56,488.06 L388.37,488.45 L389.17,488.82 L389.98,489.16 L390.79,489.47 L391.59,489.76 L392.40,490.03 L393.21,490.29 L394.01,490.52 L394.82,490.73 L395.63,490.93 L396.43,491.12 L397.24,491.29 L398.05,491.44 L398.85,491.59 L399.66,491.72 L400.47,491.85 L401.27,491.96 L402.08,492.07 L402.89,492.17 L403.69,492.26 L404.50,492.34 L405.31,492.41 L406.11,492.49 L406.92,492.55 L407.73,492.61 L408.53,492.67 L409.34,492.72 L410.15,492.76 L410.95,492.81 L411.76,492.85 L412.57,492.88 L413.37,492.92 L414.18,492.95 L414.99,492.97 L415.79,493.00 L416.60,493.03 L417.41,493.05 L418.21,493.07 L419.02,493.09 L419.83,493.10 L420.63,493.12 L421.44,493.13 L422.25,493.15 L423.05,493.16 L423.86,493.17 L424.67,493.18 L425.47,493.19 L426.28,493.20 L427.09,493.21 L427.89,493.21 L428.70,493.22 L429.51,493.23 L430.31,493.23 L431.12,493.24 L431.93,493.24 L432.73,493.25 L433.54,493.25 L434.35,493.25 L435.15,493.26 L435.96,493.26 L436.77,493.26 L437.57,493.27 L438.38,493.27 L439.19,493.27 L439.99,493.27 L440.80,493.27 L441.61,493.28 L442.41,493.28 L443.22,493.28 L444.03,493.28 L444.83,493.28 L445.64,493.28 L446.45,493.28 L447.25,493.28 L448.06,493.29 L448.87,493.29 L449.67,493.29 L450.48,493.29 L451.29,493.29 L452.09,493.29 L452.90,493.29 L453.71,493.29 L454.51,493.29 L455.32,493.29 L456.13,493.29 L456.93,493.29 L457.74,493.29 L458.55,493.29 L459.35,493.29 L460.16,493.29 L460.97,493.29 L461.77,493.29 L462.58,493.29 L463.39,493.29 L464.19,493.29 L465.00,493.29 L465.81,493.29 L466.61,493.29 L467.42,493.29 L468.23,493.29 L469.03,493.29 L469.84,493.29 L470.65,493.29 L471.45,493.29 L472.26,493.29 L473.07,493.29 L473.87,493.29 L474.68,493.29 L475.49,493.29 L476.29,493.29 L477.10,493.29 L477.91,493.29 L478.71,493.29 L479.52,493.29 L480.33,493.29 L481.13,493.29 L481.94,493.29 L482.75,493.29 L483.55,493.29 L484.36,493.29 L485.17,493.29 L485.97,493.29 L486.78,493.29 L487.59,493.29 L488.39,493.29 L489.20,493.29 L490.01,493.29 L490.81,493.29 L491.62,493.29 L492.43,493.29 L493.23,493.29 L494.04,493.29 L494.85,493.29 L495.65,493.29 L496.46,493.29 L497.27,493.29 L498.07,493.29 L498.88,493.29 L499.69,493.29 L500.49,493.29 L501.30,493.29 L502.11,493.29 L502.91,493.29 L503.72,493.29 L504.53,493.29 L505.33,493.29 L506.14,493.29 L506.95,493.29 L507.75,493.29 L508.56,493.29 L509.37,493.29 L510.17,493.29 L510.98,493.29 L511.79,493.29 L512.59,493.29 L513.40,493.29 L514.21,493.29 L515.01,493.29 L515.82,493.29 L516.63,493.29 L517.43,493.29 L518.24,493.29 L519.05,493.29 L519.85,493.29 L520.66,493.29 L521.47,493.29 L522.27,493.29 L523.08,493.29 L523.89,493.29 L524.69,493.29 L525.50,493.29 L526.31,493.29 L527.11,493.29 L527.92,493.29 L528.73,493.29 L529.53,493.29 L530.34,493.29 L531.15,493.29 L531.95,493.29 L532.76,493.29 L533.57,493.29 L534.37,493.29 L535.18,493.29 L535.99,493.29 L536.79,493.29 L537.60,493.29 L538.41,493.29 L539.21,493.29 L540.02,493.29 L540.83,493.29 L541.63,493.29 L542.44,493.29 L543.25,493.29 L544.05,493.29 L544.86,493.29 L545.67,493.29 L546.47,493.29 L547.28,493.29 L548.09,493.29 L548.89,493.29 L549.70,493.29 L550.51,493.29 L551.31,493.29 L552.12,493.29 L552.93,493.29 L553.73,493.29 L554.54,493.29 L555.35,493.29 L556.15,493.29 L556.96,493.29 L557.77,493.29 L558.57,493.29 L559.38,493.29 L560.19,493.29 L560.99,493.29 L561.80,493.29 L562.61,493.29 L563.41,493.29 L564.22,493.29 L565.03,493.29 L565.83,493.29 L566.64,493.29 L567.45,493.29 L568.25,493.29 L569.06,493.29 L569.87,493.29 L570.67,493.29 L571.48,493.29 L572.29,493.29 L573.09,493.29 L573.90,493.29 L574.71,493.29 L575.51,493.29 L576.32,493.29 L577.13,493.29 L577.93,493.29 L578.74,493.29 L579.55,493.29 L580.35,493.29 L581.16,493.29 L581.97,493.29 L582.77,493.29 L583.58,493.29 L584.39,493.29 L585.19,493.29 L586.00,493.29 " fill="none" stroke="#e8833a" stroke-width="1.8" stroke-dasharray="4 3"/><text x="582" y="432" font-size="9" fill="#e8833a" text-anchor="end">velocity (norm.)</text><rect x="644" y="408" width="242" height="116" fill="#fafbfc" stroke="#e3e6ea"/><text x="644" y="399" font-size="12" font-weight="600" fill="#333">morph 0.3/0.16</text><line x1="644" x2="886" y1="493.29413" y2="493.29413" stroke="#d5d9de" stroke-dasharray="3 3"/><text x="640" y="496.29413" font-size="9" fill="#888" text-anchor="end">0</text><line x1="644" x2="886" y1="425.05884" y2="425.05884" stroke="#d5d9de" stroke-dasharray="3 3"/><text x="640" y="428.05884" font-size="9" fill="#888" text-anchor="end">1</text><text x="886" y="538" font-size="9" fill="#888" text-anchor="end">1.20 s</text><line x1="704.5" x2="704.5" y1="408" y2="524" stroke="#d64545" stroke-width="1" stroke-dasharray="2 3"/><path d="M644.00,493.29 L644.81,493.07 L645.61,492.42 L646.42,491.42 L647.23,490.12 L648.03,488.56 L648.84,486.79 L649.65,484.85 L650.45,482.78 L651.26,480.60 L652.07,478.34 L652.87,476.03 L653.68,473.69 L654.49,471.33 L655.29,468.99 L656.10,466.66 L656.91,464.37 L657.71,462.12 L658.52,459.93 L659.33,457.79 L660.13,455.72 L660.94,453.72 L661.75,451.80 L662.55,449.95 L663.36,448.19 L664.17,446.50 L664.97,444.90 L665.78,443.37 L666.59,441.93 L667.39,440.56 L668.20,439.28 L669.01,438.07 L669.81,436.93 L670.62,435.86 L671.43,434.87 L672.23,433.94 L673.04,433.07 L673.85,432.27 L674.65,431.52 L675.46,430.83 L676.27,430.19 L677.07,429.61 L677.88,429.07 L678.69,428.57 L679.49,428.12 L680.30,427.70 L681.11,427.33 L681.91,426.99 L682.72,426.68 L683.53,426.40 L684.33,426.14 L685.14,425.92 L685.95,425.72 L686.75,425.54 L687.56,425.38 L688.37,425.24 L689.17,425.11 L689.98,425.01 L690.79,424.91 L691.59,424.83 L692.40,424.77 L693.21,424.71 L694.01,424.66 L694.82,424.62 L695.63,424.59 L696.43,424.57 L697.24,424.55 L698.05,424.54 L698.85,424.53 L699.66,424.53 L700.47,424.53 L701.27,424.54 L702.08,424.55 L702.89,424.56 L703.69,424.57 L704.50,424.58 L705.31,424.60 L706.11,424.61 L706.92,424.63 L707.73,424.65 L708.53,424.66 L709.34,424.68 L710.15,424.70 L710.95,424.72 L711.76,424.74 L712.57,424.75 L713.37,424.77 L714.18,424.79 L714.99,424.80 L715.79,424.82 L716.60,424.84 L717.41,424.85 L718.21,424.86 L719.02,424.88 L719.83,424.89 L720.63,424.90 L721.44,424.92 L722.25,424.93 L723.05,424.94 L723.86,424.95 L724.67,424.96 L725.47,424.97 L726.28,424.97 L727.09,424.98 L727.89,424.99 L728.70,425.00 L729.51,425.00 L730.31,425.01 L731.12,425.01 L731.93,425.02 L732.73,425.02 L733.54,425.03 L734.35,425.03 L735.15,425.03 L735.96,425.04 L736.77,425.04 L737.57,425.04 L738.38,425.05 L739.19,425.05 L739.99,425.05 L740.80,425.05 L741.61,425.05 L742.41,425.05 L743.22,425.06 L744.03,425.06 L744.83,425.06 L745.64,425.06 L746.45,425.06 L747.25,425.06 L748.06,425.06 L748.87,425.06 L749.67,425.06 L750.48,425.06 L751.29,425.06 L752.09,425.06 L752.90,425.06 L753.71,425.06 L754.51,425.06 L755.32,425.06 L756.13,425.06 L756.93,425.06 L757.74,425.06 L758.55,425.06 L759.35,425.06 L760.16,425.06 L760.97,425.06 L761.77,425.06 L762.58,425.06 L763.39,425.06 L764.19,425.06 L765.00,425.06 L765.81,425.06 L766.61,425.06 L767.42,425.06 L768.23,425.06 L769.03,425.06 L769.84,425.06 L770.65,425.06 L771.45,425.06 L772.26,425.06 L773.07,425.06 L773.87,425.06 L774.68,425.06 L775.49,425.06 L776.29,425.06 L777.10,425.06 L777.91,425.06 L778.71,425.06 L779.52,425.06 L780.33,425.06 L781.13,425.06 L781.94,425.06 L782.75,425.06 L783.55,425.06 L784.36,425.06 L785.17,425.06 L785.97,425.06 L786.78,425.06 L787.59,425.06 L788.39,425.06 L789.20,425.06 L790.01,425.06 L790.81,425.06 L791.62,425.06 L792.43,425.06 L793.23,425.06 L794.04,425.06 L794.85,425.06 L795.65,425.06 L796.46,425.06 L797.27,425.06 L798.07,425.06 L798.88,425.06 L799.69,425.06 L800.49,425.06 L801.30,425.06 L802.11,425.06 L802.91,425.06 L803.72,425.06 L804.53,425.06 L805.33,425.06 L806.14,425.06 L806.95,425.06 L807.75,425.06 L808.56,425.06 L809.37,425.06 L810.17,425.06 L810.98,425.06 L811.79,425.06 L812.59,425.06 L813.40,425.06 L814.21,425.06 L815.01,425.06 L815.82,425.06 L816.63,425.06 L817.43,425.06 L818.24,425.06 L819.05,425.06 L819.85,425.06 L820.66,425.06 L821.47,425.06 L822.27,425.06 L823.08,425.06 L823.89,425.06 L824.69,425.06 L825.50,425.06 L826.31,425.06 L827.11,425.06 L827.92,425.06 L828.73,425.06 L829.53,425.06 L830.34,425.06 L831.15,425.06 L831.95,425.06 L832.76,425.06 L833.57,425.06 L834.37,425.06 L835.18,425.06 L835.99,425.06 L836.79,425.06 L837.60,425.06 L838.41,425.06 L839.21,425.06 L840.02,425.06 L840.83,425.06 L841.63,425.06 L842.44,425.06 L843.25,425.06 L844.05,425.06 L844.86,425.06 L845.67,425.06 L846.47,425.06 L847.28,425.06 L848.09,425.06 L848.89,425.06 L849.70,425.06 L850.51,425.06 L851.31,425.06 L852.12,425.06 L852.93,425.06 L853.73,425.06 L854.54,425.06 L855.35,425.06 L856.15,425.06 L856.96,425.06 L857.77,425.06 L858.57,425.06 L859.38,425.06 L860.19,425.06 L860.99,425.06 L861.80,425.06 L862.61,425.06 L863.41,425.06 L864.22,425.06 L865.03,425.06 L865.83,425.06 L866.64,425.06 L867.45,425.06 L868.25,425.06 L869.06,425.06 L869.87,425.06 L870.67,425.06 L871.48,425.06 L872.29,425.06 L873.09,425.06 L873.90,425.06 L874.71,425.06 L875.51,425.06 L876.32,425.06 L877.13,425.06 L877.93,425.06 L878.74,425.06 L879.55,425.06 L880.35,425.06 L881.16,425.06 L881.97,425.06 L882.77,425.06 L883.58,425.06 L884.39,425.06 L885.19,425.06 L886.00,425.06 " fill="none" stroke="#2f6fec" stroke-width="1.8"/><text x="882" y="420" font-size="9" fill="#2f6fec" text-anchor="end">position</text><path d="M644.00,493.29 L644.81,480.35 L645.61,469.18 L646.42,459.64 L647.23,451.57 L648.03,444.84 L648.84,439.30 L649.65,434.85 L650.45,431.36 L651.26,428.74 L652.07,426.88 L652.87,425.70 L653.68,425.12 L654.49,425.06 L655.29,425.45 L656.10,426.24 L656.91,427.36 L657.71,428.77 L658.52,430.41 L659.33,432.25 L660.13,434.25 L660.94,436.37 L661.75,438.59 L662.55,440.87 L663.36,443.20 L664.17,445.54 L664.97,447.90 L665.78,450.24 L666.59,452.55 L667.39,454.83 L668.20,457.06 L669.01,459.23 L669.81,461.35 L670.62,463.39 L671.43,465.36 L672.23,467.26 L673.04,469.07 L673.85,470.81 L674.65,472.47 L675.46,474.04 L676.27,475.53 L677.07,476.95 L677.88,478.28 L678.69,479.54 L679.49,480.72 L680.30,481.83 L681.11,482.87 L681.91,483.84 L682.72,484.75 L683.53,485.59 L684.33,486.37 L685.14,487.10 L685.95,487.77 L686.75,488.39 L687.56,488.96 L688.37,489.48 L689.17,489.96 L689.98,490.40 L690.79,490.80 L691.59,491.16 L692.40,491.49 L693.21,491.79 L694.01,492.06 L694.82,492.30 L695.63,492.51 L696.43,492.71 L697.24,492.88 L698.05,493.03 L698.85,493.16 L699.66,493.28 L700.47,493.38 L701.27,493.47 L702.08,493.55 L702.89,493.61 L703.69,493.66 L704.50,493.71 L705.31,493.74 L706.11,493.77 L706.92,493.79 L707.73,493.81 L708.53,493.82 L709.34,493.82 L710.15,493.82 L710.95,493.82 L711.76,493.81 L712.57,493.80 L713.37,493.79 L714.18,493.78 L714.99,493.77 L715.79,493.75 L716.60,493.74 L717.41,493.72 L718.21,493.70 L719.02,493.68 L719.83,493.66 L720.63,493.65 L721.44,493.63 L722.25,493.61 L723.05,493.59 L723.86,493.58 L724.67,493.56 L725.47,493.54 L726.28,493.53 L727.09,493.51 L727.89,493.50 L728.70,493.48 L729.51,493.47 L730.31,493.46 L731.12,493.44 L731.93,493.43 L732.73,493.42 L733.54,493.41 L734.35,493.40 L735.15,493.39 L735.96,493.38 L736.77,493.38 L737.57,493.37 L738.38,493.36 L739.19,493.35 L739.99,493.35 L740.80,493.34 L741.61,493.34 L742.41,493.33 L743.22,493.33 L744.03,493.32 L744.83,493.32 L745.64,493.32 L746.45,493.31 L747.25,493.31 L748.06,493.31 L748.87,493.31 L749.67,493.30 L750.48,493.30 L751.29,493.30 L752.09,493.30 L752.90,493.30 L753.71,493.30 L754.51,493.30 L755.32,493.29 L756.13,493.29 L756.93,493.29 L757.74,493.29 L758.55,493.29 L759.35,493.29 L760.16,493.29 L760.97,493.29 L761.77,493.29 L762.58,493.29 L763.39,493.29 L764.19,493.29 L765.00,493.29 L765.81,493.29 L766.61,493.29 L767.42,493.29 L768.23,493.29 L769.03,493.29 L769.84,493.29 L770.65,493.29 L771.45,493.29 L772.26,493.29 L773.07,493.29 L773.87,493.29 L774.68,493.29 L775.49,493.29 L776.29,493.29 L777.10,493.29 L777.91,493.29 L778.71,493.29 L779.52,493.29 L780.33,493.29 L781.13,493.29 L781.94,493.29 L782.75,493.29 L783.55,493.29 L784.36,493.29 L785.17,493.29 L785.97,493.29 L786.78,493.29 L787.59,493.29 L788.39,493.29 L789.20,493.29 L790.01,493.29 L790.81,493.29 L791.62,493.29 L792.43,493.29 L793.23,493.29 L794.04,493.29 L794.85,493.29 L795.65,493.29 L796.46,493.29 L797.27,493.29 L798.07,493.29 L798.88,493.29 L799.69,493.29 L800.49,493.29 L801.30,493.29 L802.11,493.29 L802.91,493.29 L803.72,493.29 L804.53,493.29 L805.33,493.29 L806.14,493.29 L806.95,493.29 L807.75,493.29 L808.56,493.29 L809.37,493.29 L810.17,493.29 L810.98,493.29 L811.79,493.29 L812.59,493.29 L813.40,493.29 L814.21,493.29 L815.01,493.29 L815.82,493.29 L816.63,493.29 L817.43,493.29 L818.24,493.29 L819.05,493.29 L819.85,493.29 L820.66,493.29 L821.47,493.29 L822.27,493.29 L823.08,493.29 L823.89,493.29 L824.69,493.29 L825.50,493.29 L826.31,493.29 L827.11,493.29 L827.92,493.29 L828.73,493.29 L829.53,493.29 L830.34,493.29 L831.15,493.29 L831.95,493.29 L832.76,493.29 L833.57,493.29 L834.37,493.29 L835.18,493.29 L835.99,493.29 L836.79,493.29 L837.60,493.29 L838.41,493.29 L839.21,493.29 L840.02,493.29 L840.83,493.29 L841.63,493.29 L842.44,493.29 L843.25,493.29 L844.05,493.29 L844.86,493.29 L845.67,493.29 L846.47,493.29 L847.28,493.29 L848.09,493.29 L848.89,493.29 L849.70,493.29 L850.51,493.29 L851.31,493.29 L852.12,493.29 L852.93,493.29 L853.73,493.29 L854.54,493.29 L855.35,493.29 L856.15,493.29 L856.96,493.29 L857.77,493.29 L858.57,493.29 L859.38,493.29 L860.19,493.29 L860.99,493.29 L861.80,493.29 L862.61,493.29 L863.41,493.29 L864.22,493.29 L865.03,493.29 L865.83,493.29 L866.64,493.29 L867.45,493.29 L868.25,493.29 L869.06,493.29 L869.87,493.29 L870.67,493.29 L871.48,493.29 L872.29,493.29 L873.09,493.29 L873.90,493.29 L874.71,493.29 L875.51,493.29 L876.32,493.29 L877.13,493.29 L877.93,493.29 L878.74,493.29 L879.55,493.29 L880.35,493.29 L881.16,493.29 L881.97,493.29 L882.77,493.29 L883.58,493.29 L884.39,493.29 L885.19,493.29 L886.00,493.29 " fill="none" stroke="#e8833a" stroke-width="1.8" stroke-dasharray="4 3"/><text x="882" y="432" font-size="9" fill="#e8833a" text-anchor="end">velocity (norm.)</text><rect x="944" y="408" width="242" height="116" fill="#fafbfc" stroke="#e3e6ea"/><text x="944" y="399" font-size="12" font-weight="600" fill="#333">morph exit 0.27/0.08</text><line x1="944" x2="1186" y1="493.29413" y2="493.29413" stroke="#d5d9de" stroke-dasharray="3 3"/><text x="940" y="496.29413" font-size="9" fill="#888" text-anchor="end">0</text><line x1="944" x2="1186" y1="425.05884" y2="425.05884" stroke="#d5d9de" stroke-dasharray="3 3"/><text x="940" y="428.05884" font-size="9" fill="#888" text-anchor="end">1</text><text x="1186" y="538" font-size="9" fill="#888" text-anchor="end">1.20 s</text><line x1="998.45" x2="998.45" y1="408" y2="524" stroke="#d64545" stroke-width="1" stroke-dasharray="2 3"/><path d="M944.00,493.29 L944.81,493.01 L945.61,492.24 L946.42,491.05 L947.23,489.52 L948.03,487.72 L948.84,485.71 L949.65,483.53 L950.45,481.23 L951.26,478.84 L952.07,476.40 L952.87,473.94 L953.68,471.47 L954.49,469.03 L955.29,466.62 L956.10,464.25 L956.91,461.95 L957.71,459.72 L958.52,457.56 L959.33,455.48 L960.13,453.49 L960.94,451.59 L961.75,449.77 L962.55,448.04 L963.36,446.41 L964.17,444.86 L964.97,443.39 L965.78,442.01 L966.59,440.72 L967.39,439.50 L968.20,438.36 L969.01,437.29 L969.81,436.30 L970.62,435.37 L971.43,434.50 L972.23,433.70 L973.04,432.95 L973.85,432.26 L974.65,431.62 L975.46,431.03 L976.27,430.48 L977.07,429.98 L977.88,429.52 L978.69,429.09 L979.49,428.70 L980.30,428.34 L981.11,428.02 L981.91,427.72 L982.72,427.44 L983.53,427.19 L984.33,426.97 L985.14,426.76 L985.95,426.57 L986.75,426.40 L987.56,426.25 L988.37,426.11 L989.17,425.98 L989.98,425.87 L990.79,425.77 L991.59,425.67 L992.40,425.59 L993.21,425.52 L994.01,425.45 L994.82,425.40 L995.63,425.34 L996.43,425.30 L997.24,425.26 L998.05,425.22 L998.85,425.19 L999.66,425.16 L1000.47,425.14 L1001.27,425.12 L1002.08,425.10 L1002.89,425.08 L1003.69,425.07 L1004.50,425.06 L1005.31,425.05 L1006.11,425.04 L1006.92,425.04 L1007.73,425.03 L1008.53,425.03 L1009.34,425.02 L1010.15,425.02 L1010.95,425.02 L1011.76,425.02 L1012.57,425.02 L1013.37,425.02 L1014.18,425.02 L1014.99,425.02 L1015.79,425.02 L1016.60,425.02 L1017.41,425.02 L1018.21,425.02 L1019.02,425.02 L1019.83,425.02 L1020.63,425.02 L1021.44,425.03 L1022.25,425.03 L1023.05,425.03 L1023.86,425.03 L1024.67,425.03 L1025.47,425.03 L1026.28,425.04 L1027.09,425.04 L1027.89,425.04 L1028.70,425.04 L1029.51,425.04 L1030.31,425.04 L1031.12,425.04 L1031.93,425.04 L1032.73,425.05 L1033.54,425.05 L1034.35,425.05 L1035.15,425.05 L1035.96,425.05 L1036.77,425.05 L1037.57,425.05 L1038.38,425.05 L1039.19,425.05 L1039.99,425.05 L1040.80,425.05 L1041.61,425.05 L1042.41,425.05 L1043.22,425.05 L1044.03,425.05 L1044.83,425.06 L1045.64,425.06 L1046.45,425.06 L1047.25,425.06 L1048.06,425.06 L1048.87,425.06 L1049.67,425.06 L1050.48,425.06 L1051.29,425.06 L1052.09,425.06 L1052.90,425.06 L1053.71,425.06 L1054.51,425.06 L1055.32,425.06 L1056.13,425.06 L1056.93,425.06 L1057.74,425.06 L1058.55,425.06 L1059.35,425.06 L1060.16,425.06 L1060.97,425.06 L1061.77,425.06 L1062.58,425.06 L1063.39,425.06 L1064.19,425.06 L1065.00,425.06 L1065.81,425.06 L1066.61,425.06 L1067.42,425.06 L1068.23,425.06 L1069.03,425.06 L1069.84,425.06 L1070.65,425.06 L1071.45,425.06 L1072.26,425.06 L1073.07,425.06 L1073.87,425.06 L1074.68,425.06 L1075.49,425.06 L1076.29,425.06 L1077.10,425.06 L1077.91,425.06 L1078.71,425.06 L1079.52,425.06 L1080.33,425.06 L1081.13,425.06 L1081.94,425.06 L1082.75,425.06 L1083.55,425.06 L1084.36,425.06 L1085.17,425.06 L1085.97,425.06 L1086.78,425.06 L1087.59,425.06 L1088.39,425.06 L1089.20,425.06 L1090.01,425.06 L1090.81,425.06 L1091.62,425.06 L1092.43,425.06 L1093.23,425.06 L1094.04,425.06 L1094.85,425.06 L1095.65,425.06 L1096.46,425.06 L1097.27,425.06 L1098.07,425.06 L1098.88,425.06 L1099.69,425.06 L1100.49,425.06 L1101.30,425.06 L1102.11,425.06 L1102.91,425.06 L1103.72,425.06 L1104.53,425.06 L1105.33,425.06 L1106.14,425.06 L1106.95,425.06 L1107.75,425.06 L1108.56,425.06 L1109.37,425.06 L1110.17,425.06 L1110.98,425.06 L1111.79,425.06 L1112.59,425.06 L1113.40,425.06 L1114.21,425.06 L1115.01,425.06 L1115.82,425.06 L1116.63,425.06 L1117.43,425.06 L1118.24,425.06 L1119.05,425.06 L1119.85,425.06 L1120.66,425.06 L1121.47,425.06 L1122.27,425.06 L1123.08,425.06 L1123.89,425.06 L1124.69,425.06 L1125.50,425.06 L1126.31,425.06 L1127.11,425.06 L1127.92,425.06 L1128.73,425.06 L1129.53,425.06 L1130.34,425.06 L1131.15,425.06 L1131.95,425.06 L1132.76,425.06 L1133.57,425.06 L1134.37,425.06 L1135.18,425.06 L1135.99,425.06 L1136.79,425.06 L1137.60,425.06 L1138.41,425.06 L1139.21,425.06 L1140.02,425.06 L1140.83,425.06 L1141.63,425.06 L1142.44,425.06 L1143.25,425.06 L1144.05,425.06 L1144.86,425.06 L1145.67,425.06 L1146.47,425.06 L1147.28,425.06 L1148.09,425.06 L1148.89,425.06 L1149.70,425.06 L1150.51,425.06 L1151.31,425.06 L1152.12,425.06 L1152.93,425.06 L1153.73,425.06 L1154.54,425.06 L1155.35,425.06 L1156.15,425.06 L1156.96,425.06 L1157.77,425.06 L1158.57,425.06 L1159.38,425.06 L1160.19,425.06 L1160.99,425.06 L1161.80,425.06 L1162.61,425.06 L1163.41,425.06 L1164.22,425.06 L1165.03,425.06 L1165.83,425.06 L1166.64,425.06 L1167.45,425.06 L1168.25,425.06 L1169.06,425.06 L1169.87,425.06 L1170.67,425.06 L1171.48,425.06 L1172.29,425.06 L1173.09,425.06 L1173.90,425.06 L1174.71,425.06 L1175.51,425.06 L1176.32,425.06 L1177.13,425.06 L1177.93,425.06 L1178.74,425.06 L1179.55,425.06 L1180.35,425.06 L1181.16,425.06 L1181.97,425.06 L1182.77,425.06 L1183.58,425.06 L1184.39,425.06 L1185.19,425.06 L1186.00,425.06 " fill="none" stroke="#2f6fec" stroke-width="1.8"/><text x="1182" y="420" font-size="9" fill="#2f6fec" text-anchor="end">position</text><path d="M944.00,493.29 L944.81,478.29 L945.61,465.77 L946.42,455.44 L947.23,447.04 L948.03,440.32 L948.84,435.09 L949.65,431.14 L950.45,428.31 L951.26,426.44 L952.07,425.40 L952.87,425.06 L953.68,425.32 L954.49,426.08 L955.29,427.25 L956.10,428.76 L956.91,430.55 L957.71,432.56 L958.52,434.74 L959.33,437.03 L960.13,439.42 L960.94,441.86 L961.75,444.32 L962.55,446.78 L963.36,449.23 L964.17,451.64 L964.97,454.01 L965.78,456.31 L966.59,458.55 L967.39,460.71 L968.20,462.79 L969.01,464.79 L969.81,466.69 L970.62,468.51 L971.43,470.24 L972.23,471.88 L973.04,473.44 L973.85,474.90 L974.65,476.29 L975.46,477.59 L976.27,478.81 L977.07,479.95 L977.88,481.02 L978.69,482.02 L979.49,482.95 L980.30,483.82 L981.11,484.62 L981.91,485.37 L982.72,486.07 L983.53,486.71 L984.33,487.30 L985.14,487.85 L985.95,488.35 L986.75,488.82 L987.56,489.24 L988.37,489.64 L989.17,490.00 L989.98,490.32 L990.79,490.63 L991.59,490.90 L992.40,491.15 L993.21,491.38 L994.01,491.59 L994.82,491.78 L995.63,491.95 L996.43,492.10 L997.24,492.24 L998.05,492.37 L998.85,492.48 L999.66,492.58 L1000.47,492.67 L1001.27,492.76 L1002.08,492.83 L1002.89,492.90 L1003.69,492.96 L1004.50,493.01 L1005.31,493.05 L1006.11,493.09 L1006.92,493.13 L1007.73,493.16 L1008.53,493.19 L1009.34,493.21 L1010.15,493.23 L1010.95,493.25 L1011.76,493.27 L1012.57,493.28 L1013.37,493.29 L1014.18,493.30 L1014.99,493.31 L1015.79,493.32 L1016.60,493.32 L1017.41,493.33 L1018.21,493.33 L1019.02,493.33 L1019.83,493.33 L1020.63,493.34 L1021.44,493.34 L1022.25,493.34 L1023.05,493.34 L1023.86,493.34 L1024.67,493.34 L1025.47,493.33 L1026.28,493.33 L1027.09,493.33 L1027.89,493.33 L1028.70,493.33 L1029.51,493.33 L1030.31,493.33 L1031.12,493.33 L1031.93,493.32 L1032.73,493.32 L1033.54,493.32 L1034.35,493.32 L1035.15,493.32 L1035.96,493.32 L1036.77,493.31 L1037.57,493.31 L1038.38,493.31 L1039.19,493.31 L1039.99,493.31 L1040.80,493.31 L1041.61,493.31 L1042.41,493.31 L1043.22,493.31 L1044.03,493.30 L1044.83,493.30 L1045.64,493.30 L1046.45,493.30 L1047.25,493.30 L1048.06,493.30 L1048.87,493.30 L1049.67,493.30 L1050.48,493.30 L1051.29,493.30 L1052.09,493.30 L1052.90,493.30 L1053.71,493.30 L1054.51,493.30 L1055.32,493.30 L1056.13,493.30 L1056.93,493.30 L1057.74,493.30 L1058.55,493.30 L1059.35,493.30 L1060.16,493.30 L1060.97,493.30 L1061.77,493.30 L1062.58,493.30 L1063.39,493.30 L1064.19,493.30 L1065.00,493.29 L1065.81,493.29 L1066.61,493.29 L1067.42,493.29 L1068.23,493.29 L1069.03,493.29 L1069.84,493.29 L1070.65,493.29 L1071.45,493.29 L1072.26,493.29 L1073.07,493.29 L1073.87,493.29 L1074.68,493.29 L1075.49,493.29 L1076.29,493.29 L1077.10,493.29 L1077.91,493.29 L1078.71,493.29 L1079.52,493.29 L1080.33,493.29 L1081.13,493.29 L1081.94,493.29 L1082.75,493.29 L1083.55,493.29 L1084.36,493.29 L1085.17,493.29 L1085.97,493.29 L1086.78,493.29 L1087.59,493.29 L1088.39,493.29 L1089.20,493.29 L1090.01,493.29 L1090.81,493.29 L1091.62,493.29 L1092.43,493.29 L1093.23,493.29 L1094.04,493.29 L1094.85,493.29 L1095.65,493.29 L1096.46,493.29 L1097.27,493.29 L1098.07,493.29 L1098.88,493.29 L1099.69,493.29 L1100.49,493.29 L1101.30,493.29 L1102.11,493.29 L1102.91,493.29 L1103.72,493.29 L1104.53,493.29 L1105.33,493.29 L1106.14,493.29 L1106.95,493.29 L1107.75,493.29 L1108.56,493.29 L1109.37,493.29 L1110.17,493.29 L1110.98,493.29 L1111.79,493.29 L1112.59,493.29 L1113.40,493.29 L1114.21,493.29 L1115.01,493.29 L1115.82,493.29 L1116.63,493.29 L1117.43,493.29 L1118.24,493.29 L1119.05,493.29 L1119.85,493.29 L1120.66,493.29 L1121.47,493.29 L1122.27,493.29 L1123.08,493.29 L1123.89,493.29 L1124.69,493.29 L1125.50,493.29 L1126.31,493.29 L1127.11,493.29 L1127.92,493.29 L1128.73,493.29 L1129.53,493.29 L1130.34,493.29 L1131.15,493.29 L1131.95,493.29 L1132.76,493.29 L1133.57,493.29 L1134.37,493.29 L1135.18,493.29 L1135.99,493.29 L1136.79,493.29 L1137.60,493.29 L1138.41,493.29 L1139.21,493.29 L1140.02,493.29 L1140.83,493.29 L1141.63,493.29 L1142.44,493.29 L1143.25,493.29 L1144.05,493.29 L1144.86,493.29 L1145.67,493.29 L1146.47,493.29 L1147.28,493.29 L1148.09,493.29 L1148.89,493.29 L1149.70,493.29 L1150.51,493.29 L1151.31,493.29 L1152.12,493.29 L1152.93,493.29 L1153.73,493.29 L1154.54,493.29 L1155.35,493.29 L1156.15,493.29 L1156.96,493.29 L1157.77,493.29 L1158.57,493.29 L1159.38,493.29 L1160.19,493.29 L1160.99,493.29 L1161.80,493.29 L1162.61,493.29 L1163.41,493.29 L1164.22,493.29 L1165.03,493.29 L1165.83,493.29 L1166.64,493.29 L1167.45,493.29 L1168.25,493.29 L1169.06,493.29 L1169.87,493.29 L1170.67,493.29 L1171.48,493.29 L1172.29,493.29 L1173.09,493.29 L1173.90,493.29 L1174.71,493.29 L1175.51,493.29 L1176.32,493.29 L1177.13,493.29 L1177.93,493.29 L1178.74,493.29 L1179.55,493.29 L1180.35,493.29 L1181.16,493.29 L1181.97,493.29 L1182.77,493.29 L1183.58,493.29 L1184.39,493.29 L1185.19,493.29 L1186.00,493.29 " fill="none" stroke="#e8833a" stroke-width="1.8" stroke-dasharray="4 3"/><text x="1182" y="432" font-size="9" fill="#e8833a" text-anchor="end">velocity (norm.)</text><rect x="44" y="578" width="242" height="116" fill="#fafbfc" stroke="#e3e6ea"/><text x="44" y="569" font-size="12" font-weight="600" fill="#333">pop 0.25/0.15</text><line x1="44" x2="286" y1="663.2941" y2="663.2941" stroke="#d5d9de" stroke-dasharray="3 3"/><text x="40" y="666.2941" font-size="9" fill="#888" text-anchor="end">0</text><line x1="44" x2="286" y1="595.05884" y2="595.05884" stroke="#d5d9de" stroke-dasharray="3 3"/><text x="40" y="598.05884" font-size="9" fill="#888" text-anchor="end">1</text><text x="286" y="708" font-size="9" fill="#888" text-anchor="end">1.20 s</text><line x1="94.416664" x2="94.416664" y1="578" y2="694" stroke="#d64545" stroke-width="1" stroke-dasharray="2 3"/><path d="M44.00,663.29 L44.81,662.97 L45.61,662.06 L46.42,660.68 L47.23,658.90 L48.03,656.81 L48.84,654.48 L49.65,651.96 L50.45,649.31 L51.26,646.57 L52.07,643.78 L52.87,640.98 L53.68,638.19 L54.49,635.44 L55.29,632.75 L56.10,630.13 L56.91,627.60 L57.71,625.16 L58.52,622.83 L59.33,620.60 L60.13,618.49 L60.94,616.49 L61.75,614.61 L62.55,612.84 L63.36,611.18 L64.17,609.64 L64.97,608.20 L65.78,606.86 L66.59,605.63 L67.39,604.49 L68.20,603.44 L69.01,602.48 L69.81,601.61 L70.62,600.80 L71.43,600.08 L72.23,599.42 L73.04,598.82 L73.85,598.28 L74.65,597.80 L75.46,597.36 L76.27,596.98 L77.07,596.63 L77.88,596.33 L78.69,596.06 L79.49,595.82 L80.30,595.62 L81.11,595.44 L81.91,595.29 L82.72,595.15 L83.53,595.04 L84.33,594.95 L85.14,594.87 L85.95,594.81 L86.75,594.75 L87.56,594.71 L88.37,594.68 L89.17,594.66 L89.98,594.64 L90.79,594.63 L91.59,594.63 L92.40,594.63 L93.21,594.64 L94.01,594.64 L94.82,594.65 L95.63,594.67 L96.43,594.68 L97.24,594.70 L98.05,594.71 L98.85,594.73 L99.66,594.75 L100.47,594.76 L101.27,594.78 L102.08,594.80 L102.89,594.82 L103.69,594.83 L104.50,594.85 L105.31,594.86 L106.11,594.88 L106.92,594.89 L107.73,594.91 L108.53,594.92 L109.34,594.93 L110.15,594.94 L110.95,594.95 L111.76,594.96 L112.57,594.97 L113.37,594.98 L114.18,594.99 L114.99,595.00 L115.79,595.00 L116.60,595.01 L117.41,595.02 L118.21,595.02 L119.02,595.03 L119.83,595.03 L120.63,595.03 L121.44,595.04 L122.25,595.04 L123.05,595.04 L123.86,595.05 L124.67,595.05 L125.47,595.05 L126.28,595.05 L127.09,595.05 L127.89,595.05 L128.70,595.06 L129.51,595.06 L130.31,595.06 L131.12,595.06 L131.93,595.06 L132.73,595.06 L133.54,595.06 L134.35,595.06 L135.15,595.06 L135.96,595.06 L136.77,595.06 L137.57,595.06 L138.38,595.06 L139.19,595.06 L139.99,595.06 L140.80,595.06 L141.61,595.06 L142.41,595.06 L143.22,595.06 L144.03,595.06 L144.83,595.06 L145.64,595.06 L146.45,595.06 L147.25,595.06 L148.06,595.06 L148.87,595.06 L149.67,595.06 L150.48,595.06 L151.29,595.06 L152.09,595.06 L152.90,595.06 L153.71,595.06 L154.51,595.06 L155.32,595.06 L156.13,595.06 L156.93,595.06 L157.74,595.06 L158.55,595.06 L159.35,595.06 L160.16,595.06 L160.97,595.06 L161.77,595.06 L162.58,595.06 L163.39,595.06 L164.19,595.06 L165.00,595.06 L165.81,595.06 L166.61,595.06 L167.42,595.06 L168.23,595.06 L169.03,595.06 L169.84,595.06 L170.65,595.06 L171.45,595.06 L172.26,595.06 L173.07,595.06 L173.87,595.06 L174.68,595.06 L175.49,595.06 L176.29,595.06 L177.10,595.06 L177.91,595.06 L178.71,595.06 L179.52,595.06 L180.33,595.06 L181.13,595.06 L181.94,595.06 L182.75,595.06 L183.55,595.06 L184.36,595.06 L185.17,595.06 L185.97,595.06 L186.78,595.06 L187.59,595.06 L188.39,595.06 L189.20,595.06 L190.01,595.06 L190.81,595.06 L191.62,595.06 L192.43,595.06 L193.23,595.06 L194.04,595.06 L194.85,595.06 L195.65,595.06 L196.46,595.06 L197.27,595.06 L198.07,595.06 L198.88,595.06 L199.69,595.06 L200.49,595.06 L201.30,595.06 L202.11,595.06 L202.91,595.06 L203.72,595.06 L204.53,595.06 L205.33,595.06 L206.14,595.06 L206.95,595.06 L207.75,595.06 L208.56,595.06 L209.37,595.06 L210.17,595.06 L210.98,595.06 L211.79,595.06 L212.59,595.06 L213.40,595.06 L214.21,595.06 L215.01,595.06 L215.82,595.06 L216.63,595.06 L217.43,595.06 L218.24,595.06 L219.05,595.06 L219.85,595.06 L220.66,595.06 L221.47,595.06 L222.27,595.06 L223.08,595.06 L223.89,595.06 L224.69,595.06 L225.50,595.06 L226.31,595.06 L227.11,595.06 L227.92,595.06 L228.73,595.06 L229.53,595.06 L230.34,595.06 L231.15,595.06 L231.95,595.06 L232.76,595.06 L233.57,595.06 L234.37,595.06 L235.18,595.06 L235.99,595.06 L236.79,595.06 L237.60,595.06 L238.41,595.06 L239.21,595.06 L240.02,595.06 L240.83,595.06 L241.63,595.06 L242.44,595.06 L243.25,595.06 L244.05,595.06 L244.86,595.06 L245.67,595.06 L246.47,595.06 L247.28,595.06 L248.09,595.06 L248.89,595.06 L249.70,595.06 L250.51,595.06 L251.31,595.06 L252.12,595.06 L252.93,595.06 L253.73,595.06 L254.54,595.06 L255.35,595.06 L256.15,595.06 L256.96,595.06 L257.77,595.06 L258.57,595.06 L259.38,595.06 L260.19,595.06 L260.99,595.06 L261.80,595.06 L262.61,595.06 L263.41,595.06 L264.22,595.06 L265.03,595.06 L265.83,595.06 L266.64,595.06 L267.45,595.06 L268.25,595.06 L269.06,595.06 L269.87,595.06 L270.67,595.06 L271.48,595.06 L272.29,595.06 L273.09,595.06 L273.90,595.06 L274.71,595.06 L275.51,595.06 L276.32,595.06 L277.13,595.06 L277.93,595.06 L278.74,595.06 L279.55,595.06 L280.35,595.06 L281.16,595.06 L281.97,595.06 L282.77,595.06 L283.58,595.06 L284.39,595.06 L285.19,595.06 L286.00,595.06 " fill="none" stroke="#2f6fec" stroke-width="1.8"/><text x="282" y="590" font-size="9" fill="#2f6fec" text-anchor="end">position</text><path d="M44.00,663.29 L44.81,647.87 L45.61,635.01 L46.42,624.43 L47.23,615.87 L48.03,609.10 L48.84,603.90 L49.65,600.06 L50.45,597.42 L51.26,595.80 L52.07,595.06 L52.87,595.07 L53.68,595.71 L54.49,596.88 L55.29,598.48 L56.10,600.44 L56.91,602.66 L57.71,605.11 L58.52,607.70 L59.33,610.41 L60.13,613.18 L60.94,615.98 L61.75,618.78 L62.55,621.56 L63.36,624.28 L64.17,626.94 L64.97,629.52 L65.78,632.01 L66.59,634.39 L67.39,636.67 L68.20,638.84 L69.01,640.90 L69.81,642.84 L70.62,644.66 L71.43,646.38 L72.23,647.98 L73.04,649.47 L73.85,650.85 L74.65,652.13 L75.46,653.32 L76.27,654.41 L77.07,655.41 L77.88,656.33 L78.69,657.17 L79.49,657.93 L80.30,658.63 L81.11,659.25 L81.91,659.82 L82.72,660.33 L83.53,660.79 L84.33,661.20 L85.14,661.56 L85.95,661.88 L86.75,662.17 L87.56,662.42 L88.37,662.64 L89.17,662.83 L89.98,663.00 L90.79,663.14 L91.59,663.26 L92.40,663.36 L93.21,663.45 L94.01,663.52 L94.82,663.58 L95.63,663.62 L96.43,663.66 L97.24,663.68 L98.05,663.70 L98.85,663.72 L99.66,663.72 L100.47,663.72 L101.27,663.72 L102.08,663.71 L102.89,663.71 L103.69,663.69 L104.50,663.68 L105.31,663.67 L106.11,663.65 L106.92,663.63 L107.73,663.61 L108.53,663.60 L109.34,663.58 L110.15,663.56 L110.95,663.54 L111.76,663.53 L112.57,663.51 L113.37,663.50 L114.18,663.48 L114.99,663.47 L115.79,663.45 L116.60,663.44 L117.41,663.43 L118.21,663.41 L119.02,663.40 L119.83,663.39 L120.63,663.38 L121.44,663.38 L122.25,663.37 L123.05,663.36 L123.86,663.35 L124.67,663.35 L125.47,663.34 L126.28,663.33 L127.09,663.33 L127.89,663.32 L128.70,663.32 L129.51,663.32 L130.31,663.31 L131.12,663.31 L131.93,663.31 L132.73,663.31 L133.54,663.30 L134.35,663.30 L135.15,663.30 L135.96,663.30 L136.77,663.30 L137.57,663.30 L138.38,663.30 L139.19,663.29 L139.99,663.29 L140.80,663.29 L141.61,663.29 L142.41,663.29 L143.22,663.29 L144.03,663.29 L144.83,663.29 L145.64,663.29 L146.45,663.29 L147.25,663.29 L148.06,663.29 L148.87,663.29 L149.67,663.29 L150.48,663.29 L151.29,663.29 L152.09,663.29 L152.90,663.29 L153.71,663.29 L154.51,663.29 L155.32,663.29 L156.13,663.29 L156.93,663.29 L157.74,663.29 L158.55,663.29 L159.35,663.29 L160.16,663.29 L160.97,663.29 L161.77,663.29 L162.58,663.29 L163.39,663.29 L164.19,663.29 L165.00,663.29 L165.81,663.29 L166.61,663.29 L167.42,663.29 L168.23,663.29 L169.03,663.29 L169.84,663.29 L170.65,663.29 L171.45,663.29 L172.26,663.29 L173.07,663.29 L173.87,663.29 L174.68,663.29 L175.49,663.29 L176.29,663.29 L177.10,663.29 L177.91,663.29 L178.71,663.29 L179.52,663.29 L180.33,663.29 L181.13,663.29 L181.94,663.29 L182.75,663.29 L183.55,663.29 L184.36,663.29 L185.17,663.29 L185.97,663.29 L186.78,663.29 L187.59,663.29 L188.39,663.29 L189.20,663.29 L190.01,663.29 L190.81,663.29 L191.62,663.29 L192.43,663.29 L193.23,663.29 L194.04,663.29 L194.85,663.29 L195.65,663.29 L196.46,663.29 L197.27,663.29 L198.07,663.29 L198.88,663.29 L199.69,663.29 L200.49,663.29 L201.30,663.29 L202.11,663.29 L202.91,663.29 L203.72,663.29 L204.53,663.29 L205.33,663.29 L206.14,663.29 L206.95,663.29 L207.75,663.29 L208.56,663.29 L209.37,663.29 L210.17,663.29 L210.98,663.29 L211.79,663.29 L212.59,663.29 L213.40,663.29 L214.21,663.29 L215.01,663.29 L215.82,663.29 L216.63,663.29 L217.43,663.29 L218.24,663.29 L219.05,663.29 L219.85,663.29 L220.66,663.29 L221.47,663.29 L222.27,663.29 L223.08,663.29 L223.89,663.29 L224.69,663.29 L225.50,663.29 L226.31,663.29 L227.11,663.29 L227.92,663.29 L228.73,663.29 L229.53,663.29 L230.34,663.29 L231.15,663.29 L231.95,663.29 L232.76,663.29 L233.57,663.29 L234.37,663.29 L235.18,663.29 L235.99,663.29 L236.79,663.29 L237.60,663.29 L238.41,663.29 L239.21,663.29 L240.02,663.29 L240.83,663.29 L241.63,663.29 L242.44,663.29 L243.25,663.29 L244.05,663.29 L244.86,663.29 L245.67,663.29 L246.47,663.29 L247.28,663.29 L248.09,663.29 L248.89,663.29 L249.70,663.29 L250.51,663.29 L251.31,663.29 L252.12,663.29 L252.93,663.29 L253.73,663.29 L254.54,663.29 L255.35,663.29 L256.15,663.29 L256.96,663.29 L257.77,663.29 L258.57,663.29 L259.38,663.29 L260.19,663.29 L260.99,663.29 L261.80,663.29 L262.61,663.29 L263.41,663.29 L264.22,663.29 L265.03,663.29 L265.83,663.29 L266.64,663.29 L267.45,663.29 L268.25,663.29 L269.06,663.29 L269.87,663.29 L270.67,663.29 L271.48,663.29 L272.29,663.29 L273.09,663.29 L273.90,663.29 L274.71,663.29 L275.51,663.29 L276.32,663.29 L277.13,663.29 L277.93,663.29 L278.74,663.29 L279.55,663.29 L280.35,663.29 L281.16,663.29 L281.97,663.29 L282.77,663.29 L283.58,663.29 L284.39,663.29 L285.19,663.29 L286.00,663.29 " fill="none" stroke="#e8833a" stroke-width="1.8" stroke-dasharray="4 3"/><text x="282" y="602" font-size="9" fill="#e8833a" text-anchor="end">velocity (norm.)</text><rect x="344" y="578" width="242" height="116" fill="#fafbfc" stroke="#e3e6ea"/><text x="344" y="569" font-size="12" font-weight="600" fill="#333">pop exit 0.2/0.05</text><line x1="344" x2="586" y1="663.2941" y2="663.2941" stroke="#d5d9de" stroke-dasharray="3 3"/><text x="340" y="666.2941" font-size="9" fill="#888" text-anchor="end">0</text><line x1="344" x2="586" y1="595.05884" y2="595.05884" stroke="#d5d9de" stroke-dasharray="3 3"/><text x="340" y="598.05884" font-size="9" fill="#888" text-anchor="end">1</text><text x="586" y="708" font-size="9" fill="#888" text-anchor="end">1.20 s</text><line x1="384.33334" x2="384.33334" y1="578" y2="694" stroke="#d64545" stroke-width="1" stroke-dasharray="2 3"/><path d="M344.00,663.29 L344.81,662.80 L345.61,661.45 L346.42,659.47 L347.23,657.00 L348.03,654.18 L348.84,651.14 L349.65,647.95 L350.45,644.70 L351.26,641.44 L352.07,638.23 L352.87,635.09 L353.68,632.05 L354.49,629.15 L355.29,626.38 L356.10,623.76 L356.91,621.29 L357.71,618.98 L358.52,616.83 L359.33,614.82 L360.13,612.97 L360.94,611.26 L361.75,609.68 L362.55,608.23 L363.36,606.91 L364.17,605.70 L364.97,604.60 L365.78,603.60 L366.59,602.69 L367.39,601.87 L368.20,601.12 L369.01,600.45 L369.81,599.85 L370.62,599.31 L371.43,598.82 L372.23,598.38 L373.04,597.99 L373.85,597.64 L374.65,597.33 L375.46,597.06 L376.27,596.81 L377.07,596.59 L377.88,596.40 L378.69,596.23 L379.49,596.08 L380.30,595.94 L381.11,595.83 L381.91,595.72 L382.72,595.63 L383.53,595.55 L384.33,595.48 L385.14,595.42 L385.95,595.37 L386.75,595.32 L387.56,595.28 L388.37,595.25 L389.17,595.22 L389.98,595.19 L390.79,595.17 L391.59,595.15 L392.40,595.14 L393.21,595.12 L394.01,595.11 L394.82,595.10 L395.63,595.09 L396.43,595.08 L397.24,595.08 L398.05,595.07 L398.85,595.07 L399.66,595.07 L400.47,595.06 L401.27,595.06 L402.08,595.06 L402.89,595.06 L403.69,595.06 L404.50,595.06 L405.31,595.05 L406.11,595.05 L406.92,595.05 L407.73,595.05 L408.53,595.05 L409.34,595.05 L410.15,595.05 L410.95,595.05 L411.76,595.05 L412.57,595.05 L413.37,595.05 L414.18,595.06 L414.99,595.06 L415.79,595.06 L416.60,595.06 L417.41,595.06 L418.21,595.06 L419.02,595.06 L419.83,595.06 L420.63,595.06 L421.44,595.06 L422.25,595.06 L423.05,595.06 L423.86,595.06 L424.67,595.06 L425.47,595.06 L426.28,595.06 L427.09,595.06 L427.89,595.06 L428.70,595.06 L429.51,595.06 L430.31,595.06 L431.12,595.06 L431.93,595.06 L432.73,595.06 L433.54,595.06 L434.35,595.06 L435.15,595.06 L435.96,595.06 L436.77,595.06 L437.57,595.06 L438.38,595.06 L439.19,595.06 L439.99,595.06 L440.80,595.06 L441.61,595.06 L442.41,595.06 L443.22,595.06 L444.03,595.06 L444.83,595.06 L445.64,595.06 L446.45,595.06 L447.25,595.06 L448.06,595.06 L448.87,595.06 L449.67,595.06 L450.48,595.06 L451.29,595.06 L452.09,595.06 L452.90,595.06 L453.71,595.06 L454.51,595.06 L455.32,595.06 L456.13,595.06 L456.93,595.06 L457.74,595.06 L458.55,595.06 L459.35,595.06 L460.16,595.06 L460.97,595.06 L461.77,595.06 L462.58,595.06 L463.39,595.06 L464.19,595.06 L465.00,595.06 L465.81,595.06 L466.61,595.06 L467.42,595.06 L468.23,595.06 L469.03,595.06 L469.84,595.06 L470.65,595.06 L471.45,595.06 L472.26,595.06 L473.07,595.06 L473.87,595.06 L474.68,595.06 L475.49,595.06 L476.29,595.06 L477.10,595.06 L477.91,595.06 L478.71,595.06 L479.52,595.06 L480.33,595.06 L481.13,595.06 L481.94,595.06 L482.75,595.06 L483.55,595.06 L484.36,595.06 L485.17,595.06 L485.97,595.06 L486.78,595.06 L487.59,595.06 L488.39,595.06 L489.20,595.06 L490.01,595.06 L490.81,595.06 L491.62,595.06 L492.43,595.06 L493.23,595.06 L494.04,595.06 L494.85,595.06 L495.65,595.06 L496.46,595.06 L497.27,595.06 L498.07,595.06 L498.88,595.06 L499.69,595.06 L500.49,595.06 L501.30,595.06 L502.11,595.06 L502.91,595.06 L503.72,595.06 L504.53,595.06 L505.33,595.06 L506.14,595.06 L506.95,595.06 L507.75,595.06 L508.56,595.06 L509.37,595.06 L510.17,595.06 L510.98,595.06 L511.79,595.06 L512.59,595.06 L513.40,595.06 L514.21,595.06 L515.01,595.06 L515.82,595.06 L516.63,595.06 L517.43,595.06 L518.24,595.06 L519.05,595.06 L519.85,595.06 L520.66,595.06 L521.47,595.06 L522.27,595.06 L523.08,595.06 L523.89,595.06 L524.69,595.06 L525.50,595.06 L526.31,595.06 L527.11,595.06 L527.92,595.06 L528.73,595.06 L529.53,595.06 L530.34,595.06 L531.15,595.06 L531.95,595.06 L532.76,595.06 L533.57,595.06 L534.37,595.06 L535.18,595.06 L535.99,595.06 L536.79,595.06 L537.60,595.06 L538.41,595.06 L539.21,595.06 L540.02,595.06 L540.83,595.06 L541.63,595.06 L542.44,595.06 L543.25,595.06 L544.05,595.06 L544.86,595.06 L545.67,595.06 L546.47,595.06 L547.28,595.06 L548.09,595.06 L548.89,595.06 L549.70,595.06 L550.51,595.06 L551.31,595.06 L552.12,595.06 L552.93,595.06 L553.73,595.06 L554.54,595.06 L555.35,595.06 L556.15,595.06 L556.96,595.06 L557.77,595.06 L558.57,595.06 L559.38,595.06 L560.19,595.06 L560.99,595.06 L561.80,595.06 L562.61,595.06 L563.41,595.06 L564.22,595.06 L565.03,595.06 L565.83,595.06 L566.64,595.06 L567.45,595.06 L568.25,595.06 L569.06,595.06 L569.87,595.06 L570.67,595.06 L571.48,595.06 L572.29,595.06 L573.09,595.06 L573.90,595.06 L574.71,595.06 L575.51,595.06 L576.32,595.06 L577.13,595.06 L577.93,595.06 L578.74,595.06 L579.55,595.06 L580.35,595.06 L581.16,595.06 L581.97,595.06 L582.77,595.06 L583.58,595.06 L584.39,595.06 L585.19,595.06 L586.00,595.06 " fill="none" stroke="#2f6fec" stroke-width="1.8"/><text x="582" y="590" font-size="9" fill="#2f6fec" text-anchor="end">position</text><path d="M344.00,663.29 L344.81,643.30 L345.61,627.83 L346.42,616.15 L347.23,607.61 L348.03,601.66 L348.84,597.85 L349.65,595.76 L350.45,595.06 L351.26,595.47 L352.07,596.74 L352.87,598.68 L353.68,601.11 L354.49,603.89 L355.29,606.92 L356.10,610.10 L356.91,613.35 L357.71,616.61 L358.52,619.83 L359.33,622.97 L360.13,626.02 L360.94,628.94 L361.75,631.72 L362.55,634.36 L363.36,636.84 L364.17,639.16 L364.97,641.33 L365.78,643.35 L366.59,645.22 L367.39,646.94 L368.20,648.53 L369.01,649.99 L369.81,651.32 L370.62,652.54 L371.43,653.65 L372.23,654.66 L373.04,655.58 L373.85,656.41 L374.65,657.16 L375.46,657.84 L376.27,658.45 L377.07,659.00 L377.88,659.49 L378.69,659.93 L379.49,660.33 L380.30,660.68 L381.11,660.99 L381.91,661.27 L382.72,661.52 L383.53,661.74 L384.33,661.94 L385.14,662.11 L385.95,662.26 L386.75,662.40 L387.56,662.52 L388.37,662.62 L389.17,662.71 L389.98,662.79 L390.79,662.86 L391.59,662.93 L392.40,662.98 L393.21,663.03 L394.01,663.07 L394.82,663.10 L395.63,663.13 L396.43,663.16 L397.24,663.18 L398.05,663.20 L398.85,663.22 L399.66,663.23 L400.47,663.24 L401.27,663.25 L402.08,663.26 L402.89,663.27 L403.69,663.27 L404.50,663.28 L405.31,663.28 L406.11,663.29 L406.92,663.29 L407.73,663.29 L408.53,663.29 L409.34,663.30 L410.15,663.30 L410.95,663.30 L411.76,663.30 L412.57,663.30 L413.37,663.30 L414.18,663.30 L414.99,663.30 L415.79,663.30 L416.60,663.30 L417.41,663.30 L418.21,663.30 L419.02,663.30 L419.83,663.30 L420.63,663.30 L421.44,663.30 L422.25,663.30 L423.05,663.30 L423.86,663.30 L424.67,663.30 L425.47,663.30 L426.28,663.30 L427.09,663.30 L427.89,663.30 L428.70,663.30 L429.51,663.30 L430.31,663.30 L431.12,663.30 L431.93,663.30 L432.73,663.30 L433.54,663.30 L434.35,663.29 L435.15,663.29 L435.96,663.29 L436.77,663.29 L437.57,663.29 L438.38,663.29 L439.19,663.29 L439.99,663.29 L440.80,663.29 L441.61,663.29 L442.41,663.29 L443.22,663.29 L444.03,663.29 L444.83,663.29 L445.64,663.29 L446.45,663.29 L447.25,663.29 L448.06,663.29 L448.87,663.29 L449.67,663.29 L450.48,663.29 L451.29,663.29 L452.09,663.29 L452.90,663.29 L453.71,663.29 L454.51,663.29 L455.32,663.29 L456.13,663.29 L456.93,663.29 L457.74,663.29 L458.55,663.29 L459.35,663.29 L460.16,663.29 L460.97,663.29 L461.77,663.29 L462.58,663.29 L463.39,663.29 L464.19,663.29 L465.00,663.29 L465.81,663.29 L466.61,663.29 L467.42,663.29 L468.23,663.29 L469.03,663.29 L469.84,663.29 L470.65,663.29 L471.45,663.29 L472.26,663.29 L473.07,663.29 L473.87,663.29 L474.68,663.29 L475.49,663.29 L476.29,663.29 L477.10,663.29 L477.91,663.29 L478.71,663.29 L479.52,663.29 L480.33,663.29 L481.13,663.29 L481.94,663.29 L482.75,663.29 L483.55,663.29 L484.36,663.29 L485.17,663.29 L485.97,663.29 L486.78,663.29 L487.59,663.29 L488.39,663.29 L489.20,663.29 L490.01,663.29 L490.81,663.29 L491.62,663.29 L492.43,663.29 L493.23,663.29 L494.04,663.29 L494.85,663.29 L495.65,663.29 L496.46,663.29 L497.27,663.29 L498.07,663.29 L498.88,663.29 L499.69,663.29 L500.49,663.29 L501.30,663.29 L502.11,663.29 L502.91,663.29 L503.72,663.29 L504.53,663.29 L505.33,663.29 L506.14,663.29 L506.95,663.29 L507.75,663.29 L508.56,663.29 L509.37,663.29 L510.17,663.29 L510.98,663.29 L511.79,663.29 L512.59,663.29 L513.40,663.29 L514.21,663.29 L515.01,663.29 L515.82,663.29 L516.63,663.29 L517.43,663.29 L518.24,663.29 L519.05,663.29 L519.85,663.29 L520.66,663.29 L521.47,663.29 L522.27,663.29 L523.08,663.29 L523.89,663.29 L524.69,663.29 L525.50,663.29 L526.31,663.29 L527.11,663.29 L527.92,663.29 L528.73,663.29 L529.53,663.29 L530.34,663.29 L531.15,663.29 L531.95,663.29 L532.76,663.29 L533.57,663.29 L534.37,663.29 L535.18,663.29 L535.99,663.29 L536.79,663.29 L537.60,663.29 L538.41,663.29 L539.21,663.29 L540.02,663.29 L540.83,663.29 L541.63,663.29 L542.44,663.29 L543.25,663.29 L544.05,663.29 L544.86,663.29 L545.67,663.29 L546.47,663.29 L547.28,663.29 L548.09,663.29 L548.89,663.29 L549.70,663.29 L550.51,663.29 L551.31,663.29 L552.12,663.29 L552.93,663.29 L553.73,663.29 L554.54,663.29 L555.35,663.29 L556.15,663.29 L556.96,663.29 L557.77,663.29 L558.57,663.29 L559.38,663.29 L560.19,663.29 L560.99,663.29 L561.80,663.29 L562.61,663.29 L563.41,663.29 L564.22,663.29 L565.03,663.29 L565.83,663.29 L566.64,663.29 L567.45,663.29 L568.25,663.29 L569.06,663.29 L569.87,663.29 L570.67,663.29 L571.48,663.29 L572.29,663.29 L573.09,663.29 L573.90,663.29 L574.71,663.29 L575.51,663.29 L576.32,663.29 L577.13,663.29 L577.93,663.29 L578.74,663.29 L579.55,663.29 L580.35,663.29 L581.16,663.29 L581.97,663.29 L582.77,663.29 L583.58,663.29 L584.39,663.29 L585.19,663.29 L586.00,663.29 " fill="none" stroke="#e8833a" stroke-width="1.8" stroke-dasharray="4 3"/><text x="582" y="602" font-size="9" fill="#e8833a" text-anchor="end">velocity (norm.)</text><rect x="644" y="578" width="242" height="116" fill="#fafbfc" stroke="#e3e6ea"/><text x="644" y="569" font-size="12" font-weight="600" fill="#333">drift 0.85/0</text><line x1="644" x2="886" y1="663.2941" y2="663.2941" stroke="#d5d9de" stroke-dasharray="3 3"/><text x="640" y="666.2941" font-size="9" fill="#888" text-anchor="end">0</text><line x1="644" x2="886" y1="595.05884" y2="595.05884" stroke="#d5d9de" stroke-dasharray="3 3"/><text x="640" y="598.05884" font-size="9" fill="#888" text-anchor="end">1</text><text x="886" y="708" font-size="9" fill="#888" text-anchor="end">1.20 s</text><line x1="815.4166" x2="815.4166" y1="578" y2="694" stroke="#d64545" stroke-width="1" stroke-dasharray="2 3"/><path d="M644.00,663.29 L644.81,663.26 L645.61,663.18 L646.42,663.04 L647.23,662.85 L648.03,662.62 L648.84,662.34 L649.65,662.02 L650.45,661.66 L651.26,661.27 L652.07,660.84 L652.87,660.38 L653.68,659.89 L654.49,659.38 L655.29,658.84 L656.10,658.27 L656.91,657.69 L657.71,657.08 L658.52,656.46 L659.33,655.82 L660.13,655.17 L660.94,654.50 L661.75,653.82 L662.55,653.13 L663.36,652.43 L664.17,651.73 L664.97,651.01 L665.78,650.29 L666.59,649.56 L667.39,648.83 L668.20,648.09 L669.01,647.35 L669.81,646.61 L670.62,645.87 L671.43,645.13 L672.23,644.39 L673.04,643.65 L673.85,642.91 L674.65,642.17 L675.46,641.43 L676.27,640.70 L677.07,639.97 L677.88,639.24 L678.69,638.52 L679.49,637.81 L680.30,637.09 L681.11,636.39 L681.91,635.69 L682.72,634.99 L683.53,634.30 L684.33,633.62 L685.14,632.94 L685.95,632.27 L686.75,631.61 L687.56,630.95 L688.37,630.30 L689.17,629.66 L689.98,629.03 L690.79,628.40 L691.59,627.78 L692.40,627.17 L693.21,626.57 L694.01,625.97 L694.82,625.38 L695.63,624.80 L696.43,624.23 L697.24,623.67 L698.05,623.11 L698.85,622.57 L699.66,622.03 L700.47,621.50 L701.27,620.97 L702.08,620.46 L702.89,619.95 L703.69,619.45 L704.50,618.96 L705.31,618.48 L706.11,618.00 L706.92,617.54 L707.73,617.08 L708.53,616.62 L709.34,616.18 L710.15,615.74 L710.95,615.31 L711.76,614.89 L712.57,614.48 L713.37,614.07 L714.18,613.67 L714.99,613.28 L715.79,612.89 L716.60,612.51 L717.41,612.14 L718.21,611.78 L719.02,611.42 L719.83,611.07 L720.63,610.72 L721.44,610.38 L722.25,610.05 L723.05,609.73 L723.86,609.41 L724.67,609.09 L725.47,608.79 L726.28,608.49 L727.09,608.19 L727.89,607.90 L728.70,607.62 L729.51,607.34 L730.31,607.07 L731.12,606.80 L731.93,606.54 L732.73,606.28 L733.54,606.03 L734.35,605.78 L735.15,605.54 L735.96,605.31 L736.77,605.08 L737.57,604.85 L738.38,604.63 L739.19,604.41 L739.99,604.20 L740.80,603.99 L741.61,603.79 L742.41,603.59 L743.22,603.39 L744.03,603.20 L744.83,603.01 L745.64,602.83 L746.45,602.65 L747.25,602.48 L748.06,602.30 L748.87,602.14 L749.67,601.97 L750.48,601.81 L751.29,601.65 L752.09,601.50 L752.90,601.35 L753.71,601.20 L754.51,601.06 L755.32,600.92 L756.13,600.78 L756.93,600.65 L757.74,600.51 L758.55,600.39 L759.35,600.26 L760.16,600.14 L760.97,600.02 L761.77,599.90 L762.58,599.78 L763.39,599.67 L764.19,599.56 L765.00,599.45 L765.81,599.35 L766.61,599.25 L767.42,599.15 L768.23,599.05 L769.03,598.95 L769.84,598.86 L770.65,598.77 L771.45,598.68 L772.26,598.59 L773.07,598.51 L773.87,598.42 L774.68,598.34 L775.49,598.26 L776.29,598.19 L777.10,598.11 L777.91,598.04 L778.71,597.96 L779.52,597.89 L780.33,597.82 L781.13,597.76 L781.94,597.69 L782.75,597.63 L783.55,597.56 L784.36,597.50 L785.17,597.44 L785.97,597.38 L786.78,597.33 L787.59,597.27 L788.39,597.22 L789.20,597.16 L790.01,597.11 L790.81,597.06 L791.62,597.01 L792.43,596.96 L793.23,596.92 L794.04,596.87 L794.85,596.83 L795.65,596.78 L796.46,596.74 L797.27,596.70 L798.07,596.66 L798.88,596.62 L799.69,596.58 L800.49,596.54 L801.30,596.51 L802.11,596.47 L802.91,596.43 L803.72,596.40 L804.53,596.37 L805.33,596.33 L806.14,596.30 L806.95,596.27 L807.75,596.24 L808.56,596.21 L809.37,596.18 L810.17,596.15 L810.98,596.13 L811.79,596.10 L812.59,596.07 L813.40,596.05 L814.21,596.02 L815.01,596.00 L815.82,595.98 L816.63,595.95 L817.43,595.93 L818.24,595.91 L819.05,595.89 L819.85,595.87 L820.66,595.84 L821.47,595.82 L822.27,595.81 L823.08,595.79 L823.89,595.77 L824.69,595.75 L825.50,595.73 L826.31,595.72 L827.11,595.70 L827.92,595.68 L828.73,595.67 L829.53,595.65 L830.34,595.64 L831.15,595.62 L831.95,595.61 L832.76,595.59 L833.57,595.58 L834.37,595.57 L835.18,595.55 L835.99,595.54 L836.79,595.53 L837.60,595.52 L838.41,595.50 L839.21,595.49 L840.02,595.48 L840.83,595.47 L841.63,595.46 L842.44,595.45 L843.25,595.44 L844.05,595.43 L844.86,595.42 L845.67,595.41 L846.47,595.40 L847.28,595.39 L848.09,595.39 L848.89,595.38 L849.70,595.37 L850.51,595.36 L851.31,595.35 L852.12,595.35 L852.93,595.34 L853.73,595.33 L854.54,595.32 L855.35,595.32 L856.15,595.31 L856.96,595.30 L857.77,595.30 L858.57,595.29 L859.38,595.29 L860.19,595.28 L860.99,595.27 L861.80,595.27 L862.61,595.26 L863.41,595.26 L864.22,595.25 L865.03,595.25 L865.83,595.24 L866.64,595.24 L867.45,595.23 L868.25,595.23 L869.06,595.22 L869.87,595.22 L870.67,595.22 L871.48,595.21 L872.29,595.21 L873.09,595.20 L873.90,595.20 L874.71,595.20 L875.51,595.19 L876.32,595.19 L877.13,595.19 L877.93,595.18 L878.74,595.18 L879.55,595.18 L880.35,595.17 L881.16,595.17 L881.97,595.17 L882.77,595.16 L883.58,595.16 L884.39,595.16 L885.19,595.16 L886.00,595.15 " fill="none" stroke="#2f6fec" stroke-width="1.8"/><text x="882" y="590" font-size="9" fill="#2f6fec" text-anchor="end">position</text><path d="M644.00,663.29 L644.81,657.97 L645.61,652.96 L646.42,648.24 L647.23,643.80 L648.03,639.64 L648.84,635.74 L649.65,632.08 L650.45,628.66 L651.26,625.47 L652.07,622.49 L652.87,619.72 L653.68,617.14 L654.49,614.75 L655.29,612.54 L656.10,610.50 L656.91,608.62 L657.71,606.89 L658.52,605.32 L659.33,603.88 L660.13,602.57 L660.94,601.39 L661.75,600.34 L662.55,599.39 L663.36,598.56 L664.17,597.82 L664.97,597.19 L665.78,596.65 L666.59,596.19 L667.39,595.82 L668.20,595.53 L669.01,595.31 L669.81,595.16 L670.62,595.08 L671.43,595.06 L672.23,595.10 L673.04,595.19 L673.85,595.34 L674.65,595.54 L675.46,595.78 L676.27,596.07 L677.07,596.39 L677.88,596.76 L678.69,597.16 L679.49,597.59 L680.30,598.06 L681.11,598.55 L681.91,599.07 L682.72,599.62 L683.53,600.18 L684.33,600.77 L685.14,601.38 L685.95,602.00 L686.75,602.65 L687.56,603.30 L688.37,603.97 L689.17,604.65 L689.98,605.34 L690.79,606.04 L691.59,606.75 L692.40,607.47 L693.21,608.19 L694.01,608.92 L694.82,609.66 L695.63,610.39 L696.43,611.13 L697.24,611.87 L698.05,612.61 L698.85,613.36 L699.66,614.10 L700.47,614.84 L701.27,615.58 L702.08,616.32 L702.89,617.05 L703.69,617.78 L704.50,618.51 L705.31,619.24 L706.11,619.96 L706.92,620.67 L707.73,621.39 L708.53,622.09 L709.34,622.79 L710.15,623.49 L710.95,624.17 L711.76,624.86 L712.57,625.53 L713.37,626.20 L714.18,626.86 L714.99,627.52 L715.79,628.17 L716.60,628.81 L717.41,629.44 L718.21,630.06 L719.02,630.68 L719.83,631.29 L720.63,631.89 L721.44,632.49 L722.25,633.07 L723.05,633.65 L723.86,634.22 L724.67,634.78 L725.47,635.34 L726.28,635.88 L727.09,636.42 L727.89,636.95 L728.70,637.47 L729.51,637.99 L730.31,638.49 L731.12,638.99 L731.93,639.48 L732.73,639.96 L733.54,640.43 L734.35,640.90 L735.15,641.36 L735.96,641.81 L736.77,642.25 L737.57,642.69 L738.38,643.12 L739.19,643.54 L739.99,643.95 L740.80,644.35 L741.61,644.75 L742.41,645.14 L743.22,645.53 L744.03,645.91 L744.83,646.28 L745.64,646.64 L746.45,647.00 L747.25,647.35 L748.06,647.69 L748.87,648.03 L749.67,648.36 L750.48,648.68 L751.29,649.00 L752.09,649.31 L752.90,649.62 L753.71,649.92 L754.51,650.21 L755.32,650.50 L756.13,650.79 L756.93,651.06 L757.74,651.33 L758.55,651.60 L759.35,651.86 L760.16,652.12 L760.97,652.37 L761.77,652.61 L762.58,652.85 L763.39,653.09 L764.19,653.32 L765.00,653.54 L765.81,653.76 L766.61,653.98 L767.42,654.19 L768.23,654.40 L769.03,654.60 L769.84,654.80 L770.65,655.00 L771.45,655.19 L772.26,655.37 L773.07,655.56 L773.87,655.73 L774.68,655.91 L775.49,656.08 L776.29,656.25 L777.10,656.41 L777.91,656.57 L778.71,656.73 L779.52,656.88 L780.33,657.03 L781.13,657.18 L781.94,657.32 L782.75,657.46 L783.55,657.60 L784.36,657.73 L785.17,657.86 L785.97,657.99 L786.78,658.12 L787.59,658.24 L788.39,658.36 L789.20,658.47 L790.01,658.59 L790.81,658.70 L791.62,658.81 L792.43,658.92 L793.23,659.02 L794.04,659.12 L794.85,659.22 L795.65,659.32 L796.46,659.42 L797.27,659.51 L798.07,659.60 L798.88,659.69 L799.69,659.78 L800.49,659.86 L801.30,659.94 L802.11,660.02 L802.91,660.10 L803.72,660.18 L804.53,660.26 L805.33,660.33 L806.14,660.40 L806.95,660.47 L807.75,660.54 L808.56,660.61 L809.37,660.67 L810.17,660.74 L810.98,660.80 L811.79,660.86 L812.59,660.92 L813.40,660.98 L814.21,661.04 L815.01,661.09 L815.82,661.14 L816.63,661.20 L817.43,661.25 L818.24,661.30 L819.05,661.35 L819.85,661.40 L820.66,661.44 L821.47,661.49 L822.27,661.53 L823.08,661.58 L823.89,661.62 L824.69,661.66 L825.50,661.70 L826.31,661.74 L827.11,661.78 L827.92,661.82 L828.73,661.85 L829.53,661.89 L830.34,661.93 L831.15,661.96 L831.95,661.99 L832.76,662.02 L833.57,662.06 L834.37,662.09 L835.18,662.12 L835.99,662.15 L836.79,662.18 L837.60,662.20 L838.41,662.23 L839.21,662.26 L840.02,662.28 L840.83,662.31 L841.63,662.33 L842.44,662.36 L843.25,662.38 L844.05,662.40 L844.86,662.43 L845.67,662.45 L846.47,662.47 L847.28,662.49 L848.09,662.51 L848.89,662.53 L849.70,662.55 L850.51,662.57 L851.31,662.59 L852.12,662.61 L852.93,662.62 L853.73,662.64 L854.54,662.66 L855.35,662.67 L856.15,662.69 L856.96,662.70 L857.77,662.72 L858.57,662.73 L859.38,662.75 L860.19,662.76 L860.99,662.78 L861.80,662.79 L862.61,662.80 L863.41,662.81 L864.22,662.83 L865.03,662.84 L865.83,662.85 L866.64,662.86 L867.45,662.87 L868.25,662.88 L869.06,662.89 L869.87,662.90 L870.67,662.91 L871.48,662.92 L872.29,662.93 L873.09,662.94 L873.90,662.95 L874.71,662.96 L875.51,662.97 L876.32,662.98 L877.13,662.99 L877.93,662.99 L878.74,663.00 L879.55,663.01 L880.35,663.02 L881.16,663.02 L881.97,663.03 L882.77,663.04 L883.58,663.04 L884.39,663.05 L885.19,663.06 L886.00,663.06 " fill="none" stroke="#e8833a" stroke-width="1.8" stroke-dasharray="4 3"/><text x="882" y="602" font-size="9" fill="#e8833a" text-anchor="end">velocity (norm.)</text><rect x="944" y="578" width="242" height="116" fill="#fafbfc" stroke="#e3e6ea"/><text x="944" y="569" font-size="12" font-weight="600" fill="#333">drift exit 0.6/0</text><line x1="944" x2="1186" y1="663.2941" y2="663.2941" stroke="#d5d9de" stroke-dasharray="3 3"/><text x="940" y="666.2941" font-size="9" fill="#888" text-anchor="end">0</text><line x1="944" x2="1186" y1="595.05884" y2="595.05884" stroke="#d5d9de" stroke-dasharray="3 3"/><text x="940" y="598.05884" font-size="9" fill="#888" text-anchor="end">1</text><text x="1186" y="708" font-size="9" fill="#888" text-anchor="end">1.20 s</text><line x1="1065" x2="1065" y1="578" y2="694" stroke="#d64545" stroke-width="1" stroke-dasharray="2 3"/><path d="M944.00,663.29 L944.81,663.24 L945.61,663.07 L946.42,662.80 L947.23,662.44 L948.03,661.99 L948.84,661.47 L949.65,660.88 L950.45,660.22 L951.26,659.51 L952.07,658.74 L952.87,657.93 L953.68,657.08 L954.49,656.20 L955.29,655.28 L956.10,654.33 L956.91,653.36 L957.71,652.38 L958.52,651.37 L959.33,650.35 L960.13,649.32 L960.94,648.28 L961.75,647.23 L962.55,646.18 L963.36,645.13 L964.17,644.08 L964.97,643.03 L965.78,641.98 L966.59,640.94 L967.39,639.91 L968.20,638.88 L969.01,637.87 L969.81,636.86 L970.62,635.86 L971.43,634.87 L972.23,633.90 L973.04,632.94 L973.85,631.99 L974.65,631.06 L975.46,630.14 L976.27,629.24 L977.07,628.35 L977.88,627.47 L978.69,626.62 L979.49,625.77 L980.30,624.95 L981.11,624.14 L981.91,623.34 L982.72,622.57 L983.53,621.81 L984.33,621.06 L985.14,620.33 L985.95,619.62 L986.75,618.92 L987.56,618.24 L988.37,617.57 L989.17,616.92 L989.98,616.29 L990.79,615.67 L991.59,615.07 L992.40,614.48 L993.21,613.90 L994.01,613.34 L994.82,612.80 L995.63,612.27 L996.43,611.75 L997.24,611.24 L998.05,610.75 L998.85,610.27 L999.66,609.81 L1000.47,609.36 L1001.27,608.91 L1002.08,608.49 L1002.89,608.07 L1003.69,607.66 L1004.50,607.27 L1005.31,606.89 L1006.11,606.52 L1006.92,606.16 L1007.73,605.81 L1008.53,605.46 L1009.34,605.13 L1010.15,604.81 L1010.95,604.50 L1011.76,604.20 L1012.57,603.90 L1013.37,603.62 L1014.18,603.34 L1014.99,603.07 L1015.79,602.81 L1016.60,602.56 L1017.41,602.32 L1018.21,602.08 L1019.02,601.85 L1019.83,601.63 L1020.63,601.41 L1021.44,601.20 L1022.25,601.00 L1023.05,600.80 L1023.86,600.61 L1024.67,600.43 L1025.47,600.25 L1026.28,600.08 L1027.09,599.91 L1027.89,599.75 L1028.70,599.59 L1029.51,599.44 L1030.31,599.29 L1031.12,599.15 L1031.93,599.01 L1032.73,598.88 L1033.54,598.75 L1034.35,598.62 L1035.15,598.50 L1035.96,598.38 L1036.77,598.27 L1037.57,598.16 L1038.38,598.05 L1039.19,597.95 L1039.99,597.85 L1040.80,597.76 L1041.61,597.66 L1042.41,597.57 L1043.22,597.49 L1044.03,597.40 L1044.83,597.32 L1045.64,597.24 L1046.45,597.17 L1047.25,597.10 L1048.06,597.03 L1048.87,596.96 L1049.67,596.89 L1050.48,596.83 L1051.29,596.77 L1052.09,596.71 L1052.90,596.65 L1053.71,596.59 L1054.51,596.54 L1055.32,596.49 L1056.13,596.44 L1056.93,596.39 L1057.74,596.34 L1058.55,596.30 L1059.35,596.25 L1060.16,596.21 L1060.97,596.17 L1061.77,596.13 L1062.58,596.09 L1063.39,596.06 L1064.19,596.02 L1065.00,595.99 L1065.81,595.95 L1066.61,595.92 L1067.42,595.89 L1068.23,595.86 L1069.03,595.83 L1069.84,595.81 L1070.65,595.78 L1071.45,595.75 L1072.26,595.73 L1073.07,595.70 L1073.87,595.68 L1074.68,595.66 L1075.49,595.64 L1076.29,595.62 L1077.10,595.60 L1077.91,595.58 L1078.71,595.56 L1079.52,595.54 L1080.33,595.52 L1081.13,595.51 L1081.94,595.49 L1082.75,595.47 L1083.55,595.46 L1084.36,595.45 L1085.17,595.43 L1085.97,595.42 L1086.78,595.40 L1087.59,595.39 L1088.39,595.38 L1089.20,595.37 L1090.01,595.36 L1090.81,595.35 L1091.62,595.34 L1092.43,595.33 L1093.23,595.32 L1094.04,595.31 L1094.85,595.30 L1095.65,595.29 L1096.46,595.28 L1097.27,595.27 L1098.07,595.26 L1098.88,595.26 L1099.69,595.25 L1100.49,595.24 L1101.30,595.24 L1102.11,595.23 L1102.91,595.22 L1103.72,595.22 L1104.53,595.21 L1105.33,595.21 L1106.14,595.20 L1106.95,595.20 L1107.75,595.19 L1108.56,595.19 L1109.37,595.18 L1110.17,595.18 L1110.98,595.17 L1111.79,595.17 L1112.59,595.16 L1113.40,595.16 L1114.21,595.16 L1115.01,595.15 L1115.82,595.15 L1116.63,595.15 L1117.43,595.14 L1118.24,595.14 L1119.05,595.14 L1119.85,595.13 L1120.66,595.13 L1121.47,595.13 L1122.27,595.13 L1123.08,595.12 L1123.89,595.12 L1124.69,595.12 L1125.50,595.12 L1126.31,595.11 L1127.11,595.11 L1127.92,595.11 L1128.73,595.11 L1129.53,595.11 L1130.34,595.10 L1131.15,595.10 L1131.95,595.10 L1132.76,595.10 L1133.57,595.10 L1134.37,595.10 L1135.18,595.10 L1135.99,595.09 L1136.79,595.09 L1137.60,595.09 L1138.41,595.09 L1139.21,595.09 L1140.02,595.09 L1140.83,595.09 L1141.63,595.09 L1142.44,595.08 L1143.25,595.08 L1144.05,595.08 L1144.86,595.08 L1145.67,595.08 L1146.47,595.08 L1147.28,595.08 L1148.09,595.08 L1148.89,595.08 L1149.70,595.08 L1150.51,595.08 L1151.31,595.08 L1152.12,595.08 L1152.93,595.07 L1153.73,595.07 L1154.54,595.07 L1155.35,595.07 L1156.15,595.07 L1156.96,595.07 L1157.77,595.07 L1158.57,595.07 L1159.38,595.07 L1160.19,595.07 L1160.99,595.07 L1161.80,595.07 L1162.61,595.07 L1163.41,595.07 L1164.22,595.07 L1165.03,595.07 L1165.83,595.07 L1166.64,595.07 L1167.45,595.07 L1168.25,595.07 L1169.06,595.07 L1169.87,595.07 L1170.67,595.07 L1171.48,595.07 L1172.29,595.07 L1173.09,595.06 L1173.90,595.06 L1174.71,595.06 L1175.51,595.06 L1176.32,595.06 L1177.13,595.06 L1177.93,595.06 L1178.74,595.06 L1179.55,595.06 L1180.35,595.06 L1181.16,595.06 L1181.97,595.06 L1182.77,595.06 L1183.58,595.06 L1184.39,595.06 L1185.19,595.06 L1186.00,595.06 " fill="none" stroke="#2f6fec" stroke-width="1.8"/><text x="1182" y="590" font-size="9" fill="#2f6fec" text-anchor="end">position</text><path d="M944.00,663.29 L944.81,655.84 L945.61,649.00 L946.42,642.74 L947.23,637.01 L948.03,631.79 L948.84,627.04 L949.65,622.73 L950.45,618.84 L951.26,615.33 L952.07,612.19 L952.87,609.38 L953.68,606.89 L954.49,604.70 L955.29,602.78 L956.10,601.12 L956.91,599.70 L957.71,598.49 L958.52,597.49 L959.33,596.69 L960.13,596.06 L960.94,595.59 L961.75,595.28 L962.55,595.10 L963.36,595.06 L964.17,595.13 L964.97,595.31 L965.78,595.59 L966.59,595.97 L967.39,596.42 L968.20,596.96 L969.01,597.56 L969.81,598.22 L970.62,598.94 L971.43,599.71 L972.23,600.52 L973.04,601.38 L973.85,602.27 L974.65,603.19 L975.46,604.14 L976.27,605.11 L977.07,606.10 L977.88,607.11 L978.69,608.13 L979.49,609.17 L980.30,610.21 L981.11,611.25 L981.91,612.30 L982.72,613.36 L983.53,614.41 L984.33,615.45 L985.14,616.50 L985.95,617.54 L986.75,618.57 L987.56,619.60 L988.37,620.61 L989.17,621.62 L989.98,622.62 L990.79,623.60 L991.59,624.57 L992.40,625.53 L993.21,626.48 L994.01,627.41 L994.82,628.33 L995.63,629.23 L996.43,630.12 L997.24,630.99 L998.05,631.84 L998.85,632.68 L999.66,633.51 L1000.47,634.32 L1001.27,635.11 L1002.08,635.88 L1002.89,636.64 L1003.69,637.39 L1004.50,638.11 L1005.31,638.82 L1006.11,639.52 L1006.92,640.20 L1007.73,640.86 L1008.53,641.51 L1009.34,642.14 L1010.15,642.76 L1010.95,643.36 L1011.76,643.95 L1012.57,644.52 L1013.37,645.08 L1014.18,645.62 L1014.99,646.15 L1015.79,646.67 L1016.60,647.17 L1017.41,647.66 L1018.21,648.14 L1019.02,648.60 L1019.83,649.05 L1020.63,649.49 L1021.44,649.92 L1022.25,650.33 L1023.05,650.74 L1023.86,651.13 L1024.67,651.51 L1025.47,651.88 L1026.28,652.24 L1027.09,652.59 L1027.89,652.93 L1028.70,653.26 L1029.51,653.58 L1030.31,653.89 L1031.12,654.19 L1031.93,654.49 L1032.73,654.77 L1033.54,655.04 L1034.35,655.31 L1035.15,655.57 L1035.96,655.82 L1036.77,656.07 L1037.57,656.30 L1038.38,656.53 L1039.19,656.75 L1039.99,656.97 L1040.80,657.18 L1041.61,657.38 L1042.41,657.57 L1043.22,657.76 L1044.03,657.95 L1044.83,658.13 L1045.64,658.30 L1046.45,658.47 L1047.25,658.63 L1048.06,658.78 L1048.87,658.93 L1049.67,659.08 L1050.48,659.22 L1051.29,659.36 L1052.09,659.49 L1052.90,659.62 L1053.71,659.75 L1054.51,659.87 L1055.32,659.98 L1056.13,660.10 L1056.93,660.21 L1057.74,660.31 L1058.55,660.41 L1059.35,660.51 L1060.16,660.61 L1060.97,660.70 L1061.77,660.79 L1062.58,660.88 L1063.39,660.96 L1064.19,661.04 L1065.00,661.12 L1065.81,661.19 L1066.61,661.27 L1067.42,661.34 L1068.23,661.40 L1069.03,661.47 L1069.84,661.53 L1070.65,661.60 L1071.45,661.65 L1072.26,661.71 L1073.07,661.77 L1073.87,661.82 L1074.68,661.87 L1075.49,661.92 L1076.29,661.97 L1077.10,662.02 L1077.91,662.06 L1078.71,662.11 L1079.52,662.15 L1080.33,662.19 L1081.13,662.23 L1081.94,662.26 L1082.75,662.30 L1083.55,662.34 L1084.36,662.37 L1085.17,662.40 L1085.97,662.43 L1086.78,662.47 L1087.59,662.49 L1088.39,662.52 L1089.20,662.55 L1090.01,662.58 L1090.81,662.60 L1091.62,662.63 L1092.43,662.65 L1093.23,662.67 L1094.04,662.70 L1094.85,662.72 L1095.65,662.74 L1096.46,662.76 L1097.27,662.78 L1098.07,662.80 L1098.88,662.81 L1099.69,662.83 L1100.49,662.85 L1101.30,662.86 L1102.11,662.88 L1102.91,662.90 L1103.72,662.91 L1104.53,662.92 L1105.33,662.94 L1106.14,662.95 L1106.95,662.96 L1107.75,662.97 L1108.56,662.99 L1109.37,663.00 L1110.17,663.01 L1110.98,663.02 L1111.79,663.03 L1112.59,663.04 L1113.40,663.05 L1114.21,663.06 L1115.01,663.07 L1115.82,663.07 L1116.63,663.08 L1117.43,663.09 L1118.24,663.10 L1119.05,663.10 L1119.85,663.11 L1120.66,663.12 L1121.47,663.12 L1122.27,663.13 L1123.08,663.14 L1123.89,663.14 L1124.69,663.15 L1125.50,663.15 L1126.31,663.16 L1127.11,663.16 L1127.92,663.17 L1128.73,663.17 L1129.53,663.18 L1130.34,663.18 L1131.15,663.19 L1131.95,663.19 L1132.76,663.19 L1133.57,663.20 L1134.37,663.20 L1135.18,663.20 L1135.99,663.21 L1136.79,663.21 L1137.60,663.21 L1138.41,663.22 L1139.21,663.22 L1140.02,663.22 L1140.83,663.23 L1141.63,663.23 L1142.44,663.23 L1143.25,663.23 L1144.05,663.23 L1144.86,663.24 L1145.67,663.24 L1146.47,663.24 L1147.28,663.24 L1148.09,663.24 L1148.89,663.25 L1149.70,663.25 L1150.51,663.25 L1151.31,663.25 L1152.12,663.25 L1152.93,663.26 L1153.73,663.26 L1154.54,663.26 L1155.35,663.26 L1156.15,663.26 L1156.96,663.26 L1157.77,663.26 L1158.57,663.26 L1159.38,663.27 L1160.19,663.27 L1160.99,663.27 L1161.80,663.27 L1162.61,663.27 L1163.41,663.27 L1164.22,663.27 L1165.03,663.27 L1165.83,663.27 L1166.64,663.27 L1167.45,663.27 L1168.25,663.28 L1169.06,663.28 L1169.87,663.28 L1170.67,663.28 L1171.48,663.28 L1172.29,663.28 L1173.09,663.28 L1173.90,663.28 L1174.71,663.28 L1175.51,663.28 L1176.32,663.28 L1177.13,663.28 L1177.93,663.28 L1178.74,663.28 L1179.55,663.28 L1180.35,663.28 L1181.16,663.28 L1181.97,663.28 L1182.77,663.28 L1183.58,663.28 L1184.39,663.29 L1185.19,663.29 L1186.00,663.29 " fill="none" stroke="#e8833a" stroke-width="1.8" stroke-dasharray="4 3"/><text x="1182" y="602" font-size="9" fill="#e8833a" text-anchor="end">velocity (norm.)</text></svg> \ No newline at end of file diff --git a/app/vendor/rune/demo/opencode/home.png b/app/vendor/rune/demo/opencode/home.png new file mode 100644 index 0000000..f24074c Binary files /dev/null and b/app/vendor/rune/demo/opencode/home.png differ diff --git a/app/vendor/rune/demo/opencode/session-bottom.png b/app/vendor/rune/demo/opencode/session-bottom.png new file mode 100644 index 0000000..6fec3f5 Binary files /dev/null and b/app/vendor/rune/demo/opencode/session-bottom.png differ diff --git a/app/vendor/rune/demo/opencode/session-light.png b/app/vendor/rune/demo/opencode/session-light.png new file mode 100644 index 0000000..34d9e64 Binary files /dev/null and b/app/vendor/rune/demo/opencode/session-light.png differ diff --git a/app/vendor/rune/demo/opencode/session-top.png b/app/vendor/rune/demo/opencode/session-top.png new file mode 100644 index 0000000..f4901d0 Binary files /dev/null and b/app/vendor/rune/demo/opencode/session-top.png differ diff --git a/app/vendor/rune/demo/opencode/sidebar-closed.png b/app/vendor/rune/demo/opencode/sidebar-closed.png new file mode 100644 index 0000000..c148952 Binary files /dev/null and b/app/vendor/rune/demo/opencode/sidebar-closed.png differ diff --git a/app/vendor/rune/demo/opencode/sidebar-status.png b/app/vendor/rune/demo/opencode/sidebar-status.png new file mode 100644 index 0000000..0d81f61 Binary files /dev/null and b/app/vendor/rune/demo/opencode/sidebar-status.png differ diff --git a/app/vendor/rune/demo/opencode/streaming.png b/app/vendor/rune/demo/opencode/streaming.png new file mode 100644 index 0000000..132972b Binary files /dev/null and b/app/vendor/rune/demo/opencode/streaming.png differ diff --git a/app/vendor/rune/demo/opencode/switch-strip.png b/app/vendor/rune/demo/opencode/switch-strip.png new file mode 100644 index 0000000..ca466e0 Binary files /dev/null and b/app/vendor/rune/demo/opencode/switch-strip.png differ diff --git a/app/vendor/rune/demo/rune-poster.png b/app/vendor/rune/demo/rune-poster.png new file mode 100644 index 0000000..1487fcc Binary files /dev/null and b/app/vendor/rune/demo/rune-poster.png differ diff --git a/app/vendor/rune/demo/settings-dark.png b/app/vendor/rune/demo/settings-dark.png new file mode 100644 index 0000000..2237084 Binary files /dev/null and b/app/vendor/rune/demo/settings-dark.png differ diff --git a/app/vendor/rune/demo/settings-light.png b/app/vendor/rune/demo/settings-light.png new file mode 100644 index 0000000..7264d69 Binary files /dev/null and b/app/vendor/rune/demo/settings-light.png differ diff --git a/app/vendor/rune/demo/sticky-headers.png b/app/vendor/rune/demo/sticky-headers.png new file mode 100644 index 0000000..3f97f34 Binary files /dev/null and b/app/vendor/rune/demo/sticky-headers.png differ diff --git a/app/vendor/rune/demo/text/README.md b/app/vendor/rune/demo/text/README.md new file mode 100644 index 0000000..1228773 --- /dev/null +++ b/app/vendor/rune/demo/text/README.md @@ -0,0 +1,19 @@ +# Text calibration + +Each font/mode/density sheet reads **before → after → CoreText**. Rows are +11, 12, 13, 15 and 24 pt. The `diff` sheets show absolute error ×4; `phases` +sheets show nine horizontal positions from the raw-coverage sweep. + +- [Method, tradeoffs and reproduction](../../research/23-text-quality.md) +- [Inter, light 1×](inter-light-1x.png) +- [SF, light 2×](sf-light-2x.png) +- [Settings, OpenCode and kit crops](ui-crops.png) +- `metrics.json`: per-font, per-stage raster and motion aggregates. Regenerate + per-row and glyph-cell measurements with `scripts/text-quality.py`. +- `performance.json`: isolated paired timings and later integration checks, + including the saved integration executable hashes. +- `kit-metrics.json`: refreshed samples against the existing Linux web references. + +These isolate rasterization and blending at matched glyph positions. They do not +measure native shaping or display presentation. SF dark 1× has a small SSIM +regression; residual motion brightness variation remains nonzero. diff --git a/app/vendor/rune/demo/text/inter-dark-1x.png b/app/vendor/rune/demo/text/inter-dark-1x.png new file mode 100644 index 0000000..96cf5c6 Binary files /dev/null and b/app/vendor/rune/demo/text/inter-dark-1x.png differ diff --git a/app/vendor/rune/demo/text/inter-dark-2x.png b/app/vendor/rune/demo/text/inter-dark-2x.png new file mode 100644 index 0000000..51fc662 Binary files /dev/null and b/app/vendor/rune/demo/text/inter-dark-2x.png differ diff --git a/app/vendor/rune/demo/text/inter-diff-dark-1x.png b/app/vendor/rune/demo/text/inter-diff-dark-1x.png new file mode 100644 index 0000000..c686ff1 Binary files /dev/null and b/app/vendor/rune/demo/text/inter-diff-dark-1x.png differ diff --git a/app/vendor/rune/demo/text/inter-diff-dark-2x.png b/app/vendor/rune/demo/text/inter-diff-dark-2x.png new file mode 100644 index 0000000..4069251 Binary files /dev/null and b/app/vendor/rune/demo/text/inter-diff-dark-2x.png differ diff --git a/app/vendor/rune/demo/text/inter-diff-light-1x.png b/app/vendor/rune/demo/text/inter-diff-light-1x.png new file mode 100644 index 0000000..16de7dd Binary files /dev/null and b/app/vendor/rune/demo/text/inter-diff-light-1x.png differ diff --git a/app/vendor/rune/demo/text/inter-diff-light-2x.png b/app/vendor/rune/demo/text/inter-diff-light-2x.png new file mode 100644 index 0000000..f11551f Binary files /dev/null and b/app/vendor/rune/demo/text/inter-diff-light-2x.png differ diff --git a/app/vendor/rune/demo/text/inter-light-1x.png b/app/vendor/rune/demo/text/inter-light-1x.png new file mode 100644 index 0000000..73327a7 Binary files /dev/null and b/app/vendor/rune/demo/text/inter-light-1x.png differ diff --git a/app/vendor/rune/demo/text/inter-light-2x.png b/app/vendor/rune/demo/text/inter-light-2x.png new file mode 100644 index 0000000..c2c1bc7 Binary files /dev/null and b/app/vendor/rune/demo/text/inter-light-2x.png differ diff --git a/app/vendor/rune/demo/text/inter-phases-1x.png b/app/vendor/rune/demo/text/inter-phases-1x.png new file mode 100644 index 0000000..3d69103 Binary files /dev/null and b/app/vendor/rune/demo/text/inter-phases-1x.png differ diff --git a/app/vendor/rune/demo/text/inter-phases-2x.png b/app/vendor/rune/demo/text/inter-phases-2x.png new file mode 100644 index 0000000..a265e9d Binary files /dev/null and b/app/vendor/rune/demo/text/inter-phases-2x.png differ diff --git a/app/vendor/rune/demo/text/kit-metrics.json b/app/vendor/rune/demo/text/kit-metrics.json new file mode 100644 index 0000000..f0e00bd --- /dev/null +++ b/app/vendor/rune/demo/text/kit-metrics.json @@ -0,0 +1,74 @@ +[ + { + "story": "components-card--warning", + "scheme": "dark", + "similarity": 99.446, + "off": 1.064 + }, + { + "story": "components-card--warning", + "scheme": "light", + "similarity": 99.54, + "off": 1.051 + }, + { + "story": "ui-button--all-states", + "scheme": "dark", + "similarity": 98.494, + "off": 3.82 + }, + { + "story": "ui-button--all-states", + "scheme": "light", + "similarity": 99.004, + "off": 2.54 + }, + { + "story": "ui-menu--rich", + "scheme": "dark", + "similarity": 99.452, + "off": 1.04 + }, + { + "story": "ui-menu--rich", + "scheme": "light", + "similarity": 99.578, + "off": 1.107 + }, + { + "story": "ui-select--grouped", + "scheme": "dark", + "similarity": 99.56, + "off": 0.97 + }, + { + "story": "ui-select--grouped", + "scheme": "light", + "similarity": 99.55, + "off": 1.007 + }, + { + "story": "ui-text-input--states", + "scheme": "dark", + "similarity": 99.615, + "off": 0.508 + }, + { + "story": "ui-text-input--states", + "scheme": "light", + "similarity": 99.738, + "off": 0.467 + }, + { + "story": "ui-toast--all-examples", + "scheme": "dark", + "similarity": 99.099, + "off": 1.32 + }, + { + "story": "ui-toast--all-examples", + "scheme": "light", + "similarity": 99.297, + "off": 1.294 + } +] diff --git a/app/vendor/rune/demo/text/metrics.json b/app/vendor/rune/demo/text/metrics.json new file mode 100644 index 0000000..e1c2689 --- /dev/null +++ b/app/vendor/rune/demo/text/metrics.json @@ -0,0 +1,334 @@ +{ + "inter": { + "before": [ + { + "name": "dark-1x", + "ssim": 0.9716146441330367, + "mean_abs_weight_error_pct": 7.459733677896943, + "signed_weight_error_pct": -7.029037410056933, + "ink_mae": 0.19699435543018723 + }, + { + "name": "dark-2x", + "ssim": 0.9824625497328944, + "mean_abs_weight_error_pct": 11.929607640950037, + "signed_weight_error_pct": -11.929607640950037, + "ink_mae": 0.14209103678266966 + }, + { + "name": "light-1x", + "ssim": 0.9585930839046739, + "mean_abs_weight_error_pct": 30.140869003568497, + "signed_weight_error_pct": -30.140869003568497, + "ink_mae": 0.3460501400849008 + }, + { + "name": "light-2x", + "ssim": 0.9683103799374527, + "mean_abs_weight_error_pct": 22.844341879027642, + "signed_weight_error_pct": -22.844341879027642, + "ink_mae": 0.22895880824051834 + }, + { + "motion": { + "scale": 1, + "coverage_cv_pct": 0.036881349267480774, + "coverage_peak_to_peak_pct": 0.13248970634254328, + "frame_delta_rms_pct": 0.014292654410546342 + } + }, + { + "brightness": { + "scale": 1, + "mode": "light", + "gamma": 0.8007058823529412, + "brightness_cv_pct": 1.542940627196456, + "frame_delta_rms_pct": 0.7936208799411508 + } + }, + { + "brightness": { + "scale": 1, + "mode": "dark", + "gamma": 0.9853333333333334, + "brightness_cv_pct": 0.713902775177586, + "frame_delta_rms_pct": 0.22893269953751044 + } + }, + { + "motion": { + "scale": 2, + "coverage_cv_pct": 0.01896086206957598, + "coverage_peak_to_peak_pct": 0.06166884422139391, + "frame_delta_rms_pct": 0.007171086861257315 + } + }, + { + "brightness": { + "scale": 2, + "mode": "light", + "gamma": 0.8007058823529412, + "brightness_cv_pct": 0.4339405170162412, + "frame_delta_rms_pct": 0.18705637887701157 + } + }, + { + "brightness": { + "scale": 2, + "mode": "dark", + "gamma": 0.9853333333333334, + "brightness_cv_pct": 0.46631529486705714, + "frame_delta_rms_pct": 0.17994754320042808 + } + } + ], + "after": [ + { + "name": "dark-1x", + "ssim": 0.9807071910278374, + "mean_abs_weight_error_pct": 6.455468663067887, + "signed_weight_error_pct": -4.408847231654011, + "ink_mae": 0.1697804580925686 + }, + { + "name": "dark-2x", + "ssim": 0.9855486479572976, + "mean_abs_weight_error_pct": 6.323475551232054, + "signed_weight_error_pct": -6.323475551232054, + "ink_mae": 0.11270549558994043 + }, + { + "name": "light-1x", + "ssim": 0.982740118262236, + "mean_abs_weight_error_pct": 4.042392705394947, + "signed_weight_error_pct": 0.8405155770191609, + "ink_mae": 0.18817670744183151 + }, + { + "name": "light-2x", + "ssim": 0.9907954079268976, + "mean_abs_weight_error_pct": 3.460727562854633, + "signed_weight_error_pct": 1.0004735815853891, + "ink_mae": 0.08708380041295152 + }, + { + "motion": { + "scale": 1, + "coverage_cv_pct": 0.021636029014035586, + "coverage_peak_to_peak_pct": 0.0869531130968066, + "frame_delta_rms_pct": 0.009683299586084809 + } + }, + { + "brightness": { + "scale": 1, + "mode": "light", + "gamma": 0.4582352638244629, + "brightness_cv_pct": 0.9900482910865214, + "frame_delta_rms_pct": 0.5256861166244147 + } + }, + { + "brightness": { + "scale": 1, + "mode": "dark", + "gamma": 1.4233332872390747, + "brightness_cv_pct": 0.2073322110536778, + "frame_delta_rms_pct": 0.0802918428365147 + } + }, + { + "motion": { + "scale": 2, + "coverage_cv_pct": 0.011647725204740424, + "coverage_peak_to_peak_pct": 0.048232635404883234, + "frame_delta_rms_pct": 0.005692732963293403 + } + }, + { + "brightness": { + "scale": 2, + "mode": "light", + "gamma": 0.4770587980747223, + "brightness_cv_pct": 0.27092886059674937, + "frame_delta_rms_pct": 0.11632392594292278 + } + }, + { + "brightness": { + "scale": 2, + "mode": "dark", + "gamma": 1.6100000143051147, + "brightness_cv_pct": 0.14171386371131395, + "frame_delta_rms_pct": 0.04881897394132222 + } + } + ] + }, + "sf": { + "before": [ + { + "name": "dark-1x", + "ssim": 0.9496091406169307, + "mean_abs_weight_error_pct": 8.09907159935723, + "signed_weight_error_pct": -8.09907159935723, + "ink_mae": 0.3482999324398511 + }, + { + "name": "dark-2x", + "ssim": 0.977341763833318, + "mean_abs_weight_error_pct": 12.419653314895367, + "signed_weight_error_pct": -12.419653314895367, + "ink_mae": 0.16656865891458925 + }, + { + "name": "light-1x", + "ssim": 0.9234343776787631, + "mean_abs_weight_error_pct": 30.69146347812472, + "signed_weight_error_pct": -30.69146347812472, + "ink_mae": 0.44139445492012647 + }, + { + "name": "light-2x", + "ssim": 0.9630387018591527, + "mean_abs_weight_error_pct": 23.87326352670329, + "signed_weight_error_pct": -23.87326352670329, + "ink_mae": 0.24608684448453094 + }, + { + "motion": { + "scale": 1, + "coverage_cv_pct": 0.028618016384076447, + "coverage_peak_to_peak_pct": 0.08581844978285223, + "frame_delta_rms_pct": 0.013860831534552049 + } + }, + { + "brightness": { + "scale": 1, + "mode": "light", + "gamma": 0.8007058823529412, + "brightness_cv_pct": 2.1545530304133744, + "frame_delta_rms_pct": 0.9337121648431985 + } + }, + { + "brightness": { + "scale": 1, + "mode": "dark", + "gamma": 0.9853333333333334, + "brightness_cv_pct": 0.5017886191634411, + "frame_delta_rms_pct": 0.25164163796411737 + } + }, + { + "motion": { + "scale": 2, + "coverage_cv_pct": 0.027570431418438523, + "coverage_peak_to_peak_pct": 0.10358135365599239, + "frame_delta_rms_pct": 0.008298119086196057 + } + }, + { + "brightness": { + "scale": 2, + "mode": "light", + "gamma": 0.8007058823529412, + "brightness_cv_pct": 1.208648883872369, + "frame_delta_rms_pct": 0.3674519149794775 + } + }, + { + "brightness": { + "scale": 2, + "mode": "dark", + "gamma": 0.9853333333333334, + "brightness_cv_pct": 0.22162465288548483, + "frame_delta_rms_pct": 0.11994232875112003 + } + } + ], + "after": [ + { + "name": "dark-1x", + "ssim": 0.9482086603220428, + "mean_abs_weight_error_pct": 6.198829186928209, + "signed_weight_error_pct": -6.011266029901663, + "ink_mae": 0.3355731252140466 + }, + { + "name": "dark-2x", + "ssim": 0.9794155845448091, + "mean_abs_weight_error_pct": 7.133983873231395, + "signed_weight_error_pct": -7.133983873231395, + "ink_mae": 0.1508271532326289 + }, + { + "name": "light-1x", + "ssim": 0.950077285833176, + "mean_abs_weight_error_pct": 2.6770652502274475, + "signed_weight_error_pct": -0.8633287766518296, + "ink_mae": 0.37717626248218017 + }, + { + "name": "light-2x", + "ssim": 0.9867471047105884, + "mean_abs_weight_error_pct": 2.795747343520524, + "signed_weight_error_pct": 0.19920391414374086, + "ink_mae": 0.1287055029378169 + }, + { + "motion": { + "scale": 1, + "coverage_cv_pct": 0.023892834900920323, + "coverage_peak_to_peak_pct": 0.10969670815920068, + "frame_delta_rms_pct": 0.014441859346107522 + } + }, + { + "brightness": { + "scale": 1, + "mode": "light", + "gamma": 0.4582352638244629, + "brightness_cv_pct": 1.6517202471526473, + "frame_delta_rms_pct": 0.5993040934379498 + } + }, + { + "brightness": { + "scale": 1, + "mode": "dark", + "gamma": 1.4233332872390747, + "brightness_cv_pct": 0.2331057861660113, + "frame_delta_rms_pct": 0.09610676397054692 + } + }, + { + "motion": { + "scale": 2, + "coverage_cv_pct": 0.023340295725994793, + "coverage_peak_to_peak_pct": 0.08534041381502722, + "frame_delta_rms_pct": 0.007342217744949102 + } + }, + { + "brightness": { + "scale": 2, + "mode": "light", + "gamma": 0.4770587980747223, + "brightness_cv_pct": 0.7519136946723961, + "frame_delta_rms_pct": 0.23318706090887426 + } + }, + { + "brightness": { + "scale": 2, + "mode": "dark", + "gamma": 1.6100000143051147, + "brightness_cv_pct": 0.1323659794578848, + "frame_delta_rms_pct": 0.05257400808474724 + } + } + ] + } +} diff --git a/app/vendor/rune/demo/text/performance.json b/app/vendor/rune/demo/text/performance.json new file mode 100644 index 0000000..7d69eb1 --- /dev/null +++ b/app/vendor/rune/demo/text/performance.json @@ -0,0 +1,876 @@ +{ + "isolated": { + "results": { + "stream": { + "before": { + "median": { + "gpu_ms": 13.2, + "first_ms": 4.98, + "mean_ms": 0.408, + "p50_ms": 0.313, + "p95_ms": 0.665, + "max_ms": 11.512, + "instances": 1126.0 + }, + "mad": { + "gpu_ms": 0.8999999999999986, + "first_ms": 0.5499999999999998, + "mean_ms": 0.12999999999999995, + "p50_ms": 0.01100000000000001, + "p95_ms": 0.17100000000000004, + "max_ms": 6.460000000000001, + "instances": 0.0 + }, + "runs": [ + { + "gpu_ms": 12.3, + "first_ms": 3.94, + "mean_ms": 0.339, + "p50_ms": 0.313, + "p95_ms": 0.66, + "max_ms": 3.937, + "instances": 1126.0 + }, + { + "gpu_ms": 13.2, + "first_ms": 4.98, + "mean_ms": 0.408, + "p50_ms": 0.317, + "p95_ms": 0.665, + "max_ms": 11.512, + "instances": 1126.0 + }, + { + "gpu_ms": 15.7, + "first_ms": 4.34, + "mean_ms": 0.271, + "p50_ms": 0.269, + "p95_ms": 0.481, + "max_ms": 4.345, + "instances": 1126.0 + }, + { + "gpu_ms": 13.1, + "first_ms": 5.05, + "mean_ms": 0.278, + "p50_ms": 0.271, + "p95_ms": 0.494, + "max_ms": 5.052, + "instances": 1126.0 + }, + { + "gpu_ms": 14.2, + "first_ms": 5.18, + "mean_ms": 0.551, + "p50_ms": 0.319, + "p95_ms": 1.229, + "max_ms": 14.396, + "instances": 1126.0 + }, + { + "gpu_ms": 13.0, + "first_ms": 4.41, + "mean_ms": 0.463, + "p50_ms": 0.302, + "p95_ms": 0.692, + "max_ms": 13.99, + "instances": 1126.0 + }, + { + "gpu_ms": 17.7, + "first_ms": 5.53, + "mean_ms": 0.698, + "p50_ms": 0.354, + "p95_ms": 1.29, + "max_ms": 25.165, + "instances": 1126.0 + } + ] + }, + "after": { + "median": { + "gpu_ms": 14.8, + "first_ms": 5.39, + "mean_ms": 0.32, + "p50_ms": 0.295, + "p95_ms": 0.604, + "max_ms": 6.606, + "instances": 1126.0 + }, + "mad": { + "gpu_ms": 1.3000000000000007, + "first_ms": 0.8799999999999999, + "mean_ms": 0.043999999999999984, + "p50_ms": 0.019999999999999962, + "p95_ms": 0.11499999999999999, + "max_ms": 2.093, + "instances": 0.0 + }, + "runs": [ + { + "gpu_ms": 13.8, + "first_ms": 4.19, + "mean_ms": 0.32, + "p50_ms": 0.304, + "p95_ms": 0.604, + "max_ms": 4.194, + "instances": 1126.0 + }, + { + "gpu_ms": 16.9, + "first_ms": 7.46, + "mean_ms": 0.302, + "p50_ms": 0.284, + "p95_ms": 0.56, + "max_ms": 7.463, + "instances": 1126.0 + }, + { + "gpu_ms": 14.3, + "first_ms": 4.73, + "mean_ms": 0.276, + "p50_ms": 0.275, + "p95_ms": 0.489, + "max_ms": 4.726, + "instances": 1126.0 + }, + { + "gpu_ms": 13.5, + "first_ms": 4.51, + "mean_ms": 0.272, + "p50_ms": 0.27, + "p95_ms": 0.476, + "max_ms": 4.513, + "instances": 1126.0 + }, + { + "gpu_ms": 14.8, + "first_ms": 5.39, + "mean_ms": 0.352, + "p50_ms": 0.295, + "p95_ms": 0.61, + "max_ms": 6.606, + "instances": 1126.0 + }, + { + "gpu_ms": 16.4, + "first_ms": 6.41, + "mean_ms": 0.578, + "p50_ms": 0.404, + "p95_ms": 1.014, + "max_ms": 12.501, + "instances": 1126.0 + }, + { + "gpu_ms": 16.8, + "first_ms": 5.72, + "mean_ms": 0.754, + "p50_ms": 0.376, + "p95_ms": 2.448, + "max_ms": 16.74, + "instances": 1126.0 + } + ] + } + }, + "long-stream": { + "before": { + "median": { + "gpu_ms": 14.2, + "first_ms": 9.7, + "mean_ms": 0.735, + "p50_ms": 0.327, + "p95_ms": 3.891, + "max_ms": 10.968, + "instances": 1126.0 + }, + "mad": { + "gpu_ms": 0.8999999999999986, + "first_ms": 0.14999999999999858, + "mean_ms": 0.050999999999999934, + "p50_ms": 0.029000000000000026, + "p95_ms": 0.2030000000000003, + "max_ms": 1.3930000000000007, + "instances": 0.0 + }, + "runs": [ + { + "gpu_ms": 14.2, + "first_ms": 9.58, + "mean_ms": 0.773, + "p50_ms": 0.362, + "p95_ms": 3.891, + "max_ms": 9.575, + "instances": 1126.0 + }, + { + "gpu_ms": 19.9, + "first_ms": 9.79, + "mean_ms": 0.684, + "p50_ms": 0.298, + "p95_ms": 4.313, + "max_ms": 12.835, + "instances": 1126.0 + }, + { + "gpu_ms": 13.3, + "first_ms": 9.7, + "mean_ms": 0.496, + "p50_ms": 0.144, + "p95_ms": 3.615, + "max_ms": 9.697, + "instances": 1126.0 + }, + { + "gpu_ms": 18.1, + "first_ms": 11.22, + "mean_ms": 0.497, + "p50_ms": 0.147, + "p95_ms": 3.576, + "max_ms": 11.224, + "instances": 1126.0 + }, + { + "gpu_ms": 14.4, + "first_ms": 9.41, + "mean_ms": 0.744, + "p50_ms": 0.334, + "p95_ms": 3.851, + "max_ms": 9.41, + "instances": 1126.0 + }, + { + "gpu_ms": 13.9, + "first_ms": 9.91, + "mean_ms": 0.735, + "p50_ms": 0.349, + "p95_ms": 4.044, + "max_ms": 10.968, + "instances": 1126.0 + }, + { + "gpu_ms": 13.2, + "first_ms": 9.55, + "mean_ms": 0.869, + "p50_ms": 0.327, + "p95_ms": 4.094, + "max_ms": 22.655, + "instances": 1126.0 + } + ] + }, + "after": { + "median": { + "gpu_ms": 14.2, + "first_ms": 10.4, + "mean_ms": 0.674, + "p50_ms": 0.311, + "p95_ms": 3.695, + "max_ms": 11.397, + "instances": 1126.0 + }, + "mad": { + "gpu_ms": 0.40000000000000036, + "first_ms": 1.0500000000000007, + "mean_ms": 0.051999999999999935, + "p50_ms": 0.033999999999999975, + "p95_ms": 0.2410000000000001, + "max_ms": 1.357000000000001, + "instances": 0.0 + }, + "runs": [ + { + "gpu_ms": 19.4, + "first_ms": 11.47, + "mean_ms": 0.726, + "p50_ms": 0.345, + "p95_ms": 3.936, + "max_ms": 11.469, + "instances": 1126.0 + }, + { + "gpu_ms": 20.7, + "first_ms": 12.85, + "mean_ms": 0.524, + "p50_ms": 0.173, + "p95_ms": 3.533, + "max_ms": 12.851, + "instances": 1126.0 + }, + { + "gpu_ms": 14.1, + "first_ms": 10.4, + "mean_ms": 0.495, + "p50_ms": 0.148, + "p95_ms": 3.614, + "max_ms": 10.397, + "instances": 1126.0 + }, + { + "gpu_ms": 12.9, + "first_ms": 8.8, + "mean_ms": 0.465, + "p50_ms": 0.137, + "p95_ms": 3.322, + "max_ms": 8.8, + "instances": 1126.0 + }, + { + "gpu_ms": 14.2, + "first_ms": 10.04, + "mean_ms": 0.722, + "p50_ms": 0.325, + "p95_ms": 4.05, + "max_ms": 10.04, + "instances": 1126.0 + }, + { + "gpu_ms": 14.1, + "first_ms": 11.4, + "mean_ms": 0.724, + "p50_ms": 0.344, + "p95_ms": 4.125, + "max_ms": 11.397, + "instances": 1126.0 + }, + { + "gpu_ms": 14.6, + "first_ms": 9.35, + "mean_ms": 0.674, + "p50_ms": 0.311, + "p95_ms": 3.695, + "max_ms": 28.508, + "instances": 1126.0 + } + ] + } + } + } + }, + "rebase_live": { + "results": { + "stream": { + "before": { + "median": { + "gpu_ms": 11.6, + "first_ms": 4.07, + "mean_ms": 0.243, + "p50_ms": 0.248, + "p95_ms": 0.423, + "max_ms": 4.071, + "instances": 1126.0 + }, + "mad": { + "gpu_ms": 0.40000000000000036, + "first_ms": 0.07000000000000028, + "mean_ms": 0.0040000000000000036, + "p50_ms": 0.0020000000000000018, + "p95_ms": 0.01799999999999996, + "max_ms": 0.07599999999999962, + "instances": 0.0 + }, + "runs": [ + { + "gpu_ms": 11.5, + "first_ms": 4.08, + "mean_ms": 0.236, + "p50_ms": 0.246, + "p95_ms": 0.379, + "max_ms": 4.076, + "instances": 1126.0 + }, + { + "gpu_ms": 11.4, + "first_ms": 3.9, + "mean_ms": 0.247, + "p50_ms": 0.253, + "p95_ms": 0.423, + "max_ms": 3.903, + "instances": 1126.0 + }, + { + "gpu_ms": 11.2, + "first_ms": 4.17, + "mean_ms": 0.236, + "p50_ms": 0.246, + "p95_ms": 0.398, + "max_ms": 4.171, + "instances": 1126.0 + }, + { + "gpu_ms": 12.2, + "first_ms": 4.05, + "mean_ms": 0.245, + "p50_ms": 0.252, + "p95_ms": 0.405, + "max_ms": 4.049, + "instances": 1126.0 + }, + { + "gpu_ms": 12.4, + "first_ms": 4.0, + "mean_ms": 0.241, + "p50_ms": 0.248, + "p95_ms": 0.434, + "max_ms": 3.995, + "instances": 1126.0 + }, + { + "gpu_ms": 12.2, + "first_ms": 4.07, + "mean_ms": 0.243, + "p50_ms": 0.246, + "p95_ms": 0.431, + "max_ms": 4.071, + "instances": 1126.0 + }, + { + "gpu_ms": 11.6, + "first_ms": 4.18, + "mean_ms": 0.256, + "p50_ms": 0.255, + "p95_ms": 0.45, + "max_ms": 4.176, + "instances": 1126.0 + } + ] + }, + "after": { + "median": { + "gpu_ms": 11.8, + "first_ms": 4.09, + "mean_ms": 0.239, + "p50_ms": 0.248, + "p95_ms": 0.407, + "max_ms": 4.087, + "instances": 1126.0 + }, + "mad": { + "gpu_ms": 0.3000000000000007, + "first_ms": 0.08999999999999986, + "mean_ms": 0.0010000000000000009, + "p50_ms": 0.0020000000000000018, + "p95_ms": 0.020999999999999963, + "max_ms": 0.08699999999999974, + "instances": 0.0 + }, + "runs": [ + { + "gpu_ms": 12.1, + "first_ms": 4.09, + "mean_ms": 0.239, + "p50_ms": 0.246, + "p95_ms": 0.41, + "max_ms": 4.087, + "instances": 1126.0 + }, + { + "gpu_ms": 11.4, + "first_ms": 3.97, + "mean_ms": 0.238, + "p50_ms": 0.248, + "p95_ms": 0.407, + "max_ms": 3.97, + "instances": 1126.0 + }, + { + "gpu_ms": 11.5, + "first_ms": 4.0, + "mean_ms": 0.238, + "p50_ms": 0.25, + "p95_ms": 0.386, + "max_ms": 4.0, + "instances": 1126.0 + }, + { + "gpu_ms": 11.8, + "first_ms": 4.04, + "mean_ms": 0.234, + "p50_ms": 0.245, + "p95_ms": 0.385, + "max_ms": 4.042, + "instances": 1126.0 + }, + { + "gpu_ms": 11.7, + "first_ms": 4.11, + "mean_ms": 0.239, + "p50_ms": 0.246, + "p95_ms": 0.399, + "max_ms": 4.109, + "instances": 1126.0 + }, + { + "gpu_ms": 12.6, + "first_ms": 4.51, + "mean_ms": 0.257, + "p50_ms": 0.252, + "p95_ms": 0.464, + "max_ms": 4.513, + "instances": 1126.0 + }, + { + "gpu_ms": 14.3, + "first_ms": 4.65, + "mean_ms": 0.256, + "p50_ms": 0.254, + "p95_ms": 0.458, + "max_ms": 4.651, + "instances": 1126.0 + } + ] + } + }, + "long-stream": { + "before": { + "median": { + "gpu_ms": 12.2, + "first_ms": 9.06, + "mean_ms": 0.423, + "p50_ms": 0.126, + "p95_ms": 2.88, + "max_ms": 9.058, + "instances": 1126.0 + }, + "mad": { + "gpu_ms": 0.40000000000000036, + "first_ms": 0.75, + "mean_ms": 0.013000000000000012, + "p50_ms": 0.0040000000000000036, + "p95_ms": 0.040999999999999925, + "max_ms": 0.7509999999999994, + "instances": 0.0 + }, + "runs": [ + { + "gpu_ms": 12.3, + "first_ms": 9.06, + "mean_ms": 0.406, + "p50_ms": 0.121, + "p95_ms": 2.839, + "max_ms": 9.058, + "instances": 1126.0 + }, + { + "gpu_ms": 12.2, + "first_ms": 7.92, + "mean_ms": 0.418, + "p50_ms": 0.126, + "p95_ms": 2.885, + "max_ms": 7.915, + "instances": 1126.0 + }, + { + "gpu_ms": 11.6, + "first_ms": 9.81, + "mean_ms": 0.428, + "p50_ms": 0.13, + "p95_ms": 2.917, + "max_ms": 9.809, + "instances": 1126.0 + }, + { + "gpu_ms": 11.8, + "first_ms": 8.5, + "mean_ms": 0.436, + "p50_ms": 0.13, + "p95_ms": 2.88, + "max_ms": 8.499, + "instances": 1126.0 + }, + { + "gpu_ms": 12.6, + "first_ms": 9.19, + "mean_ms": 0.472, + "p50_ms": 0.145, + "p95_ms": 3.238, + "max_ms": 9.189, + "instances": 1126.0 + }, + { + "gpu_ms": 14.0, + "first_ms": 9.89, + "mean_ms": 0.423, + "p50_ms": 0.124, + "p95_ms": 2.783, + "max_ms": 9.886, + "instances": 1126.0 + }, + { + "gpu_ms": 11.6, + "first_ms": 8.28, + "mean_ms": 0.398, + "p50_ms": 0.121, + "p95_ms": 2.782, + "max_ms": 8.282, + "instances": 1126.0 + } + ] + }, + "after": { + "median": { + "gpu_ms": 11.8, + "first_ms": 6.31, + "mean_ms": 0.371, + "p50_ms": 0.148, + "p95_ms": 2.272, + "max_ms": 6.313, + "instances": 1126.0 + }, + "mad": { + "gpu_ms": 0.5, + "first_ms": 0.1200000000000001, + "mean_ms": 0.014000000000000012, + "p50_ms": 0.006000000000000005, + "p95_ms": 0.16000000000000014, + "max_ms": 0.11699999999999999, + "instances": 0.0 + }, + "runs": [ + { + "gpu_ms": 11.5, + "first_ms": 6.43, + "mean_ms": 0.366, + "p50_ms": 0.15, + "p95_ms": 2.188, + "max_ms": 6.43, + "instances": 1126.0 + }, + { + "gpu_ms": 11.8, + "first_ms": 6.33, + "mean_ms": 0.376, + "p50_ms": 0.142, + "p95_ms": 2.32, + "max_ms": 6.328, + "instances": 1126.0 + }, + { + "gpu_ms": 11.3, + "first_ms": 6.3, + "mean_ms": 0.357, + "p50_ms": 0.148, + "p95_ms": 2.091, + "max_ms": 6.301, + "instances": 1126.0 + }, + { + "gpu_ms": 11.9, + "first_ms": 6.17, + "mean_ms": 0.404, + "p50_ms": 0.156, + "p95_ms": 2.432, + "max_ms": 6.171, + "instances": 1126.0 + }, + { + "gpu_ms": 42.5, + "first_ms": 8.49, + "mean_ms": 0.449, + "p50_ms": 0.173, + "p95_ms": 2.662, + "max_ms": 8.488, + "instances": 1126.0 + }, + { + "gpu_ms": 10.9, + "first_ms": 5.94, + "mean_ms": 0.371, + "p50_ms": 0.14, + "p95_ms": 2.272, + "max_ms": 5.944, + "instances": 1126.0 + }, + { + "gpu_ms": 12.4, + "first_ms": 6.31, + "mean_ms": 0.351, + "p50_ms": 0.147, + "p95_ms": 2.082, + "max_ms": 6.313, + "instances": 1126.0 + } + ] + } + } + }, + "binaries": { + "before": "c2bb31da0a331b0fc68e9edbd228ac7df1e42ff3058851d32655d49f4f0cdb44", + "after": "8faaceaeaa6137c5664e730a3d01107002d410fd11eb15e674b73d6da2b72fe9" + } + }, + "timeline_hold": { + "results": { + "stream": { + "median": { + "gpu_ms": 11.4, + "first_ms": 4.02, + "mean_ms": 0.237, + "p50_ms": 0.249, + "p95_ms": 0.402, + "max_ms": 4.021, + "instances": 1126.0 + }, + "mad": { + "gpu_ms": 0.20000000000000107, + "first_ms": 0.10999999999999943, + "mean_ms": 0.0, + "p50_ms": 0.0010000000000000009, + "p95_ms": 0.009000000000000008, + "max_ms": 0.11499999999999977, + "instances": 0.0 + }, + "runs": [ + { + "gpu_ms": 11.2, + "first_ms": 4.21, + "mean_ms": 0.294, + "p50_ms": 0.275, + "p95_ms": 0.541, + "max_ms": 4.215, + "instances": 1126.0 + }, + { + "gpu_ms": 11.5, + "first_ms": 4.49, + "mean_ms": 0.243, + "p50_ms": 0.25, + "p95_ms": 0.425, + "max_ms": 4.488, + "instances": 1126.0 + }, + { + "gpu_ms": 11.4, + "first_ms": 4.02, + "mean_ms": 0.237, + "p50_ms": 0.249, + "p95_ms": 0.393, + "max_ms": 4.021, + "instances": 1126.0 + }, + { + "gpu_ms": 11.0, + "first_ms": 3.94, + "mean_ms": 0.237, + "p50_ms": 0.249, + "p95_ms": 0.382, + "max_ms": 3.941, + "instances": 1126.0 + }, + { + "gpu_ms": 11.5, + "first_ms": 4.0, + "mean_ms": 0.237, + "p50_ms": 0.25, + "p95_ms": 0.399, + "max_ms": 3.998, + "instances": 1126.0 + }, + { + "gpu_ms": 11.8, + "first_ms": 4.18, + "mean_ms": 0.237, + "p50_ms": 0.247, + "p95_ms": 0.402, + "max_ms": 4.183, + "instances": 1126.0 + }, + { + "gpu_ms": 10.9, + "first_ms": 3.91, + "mean_ms": 0.235, + "p50_ms": 0.245, + "p95_ms": 0.405, + "max_ms": 3.906, + "instances": 1126.0 + } + ] + }, + "long-stream": { + "median": { + "gpu_ms": 11.0, + "first_ms": 5.92, + "mean_ms": 0.347, + "p50_ms": 0.147, + "p95_ms": 1.969, + "max_ms": 5.919, + "instances": 1126.0 + }, + "mad": { + "gpu_ms": 0.09999999999999964, + "first_ms": 0.25, + "mean_ms": 0.007999999999999952, + "p50_ms": 0.0030000000000000027, + "p95_ms": 0.020000000000000018, + "max_ms": 0.24499999999999922, + "instances": 0.0 + }, + "runs": [ + { + "gpu_ms": 10.9, + "first_ms": 5.67, + "mean_ms": 0.339, + "p50_ms": 0.147, + "p95_ms": 1.978, + "max_ms": 5.674, + "instances": 1126.0 + }, + { + "gpu_ms": 10.7, + "first_ms": 5.9, + "mean_ms": 0.347, + "p50_ms": 0.177, + "p95_ms": 1.903, + "max_ms": 5.896, + "instances": 1126.0 + }, + { + "gpu_ms": 11.0, + "first_ms": 5.92, + "mean_ms": 0.339, + "p50_ms": 0.145, + "p95_ms": 1.989, + "max_ms": 5.919, + "instances": 1126.0 + }, + { + "gpu_ms": 11.3, + "first_ms": 6.69, + "mean_ms": 0.336, + "p50_ms": 0.15, + "p95_ms": 1.892, + "max_ms": 6.691, + "instances": 1126.0 + }, + { + "gpu_ms": 13.3, + "first_ms": 8.05, + "mean_ms": 0.379, + "p50_ms": 0.139, + "p95_ms": 2.483, + "max_ms": 8.048, + "instances": 1126.0 + }, + { + "gpu_ms": 11.1, + "first_ms": 5.61, + "mean_ms": 0.349, + "p50_ms": 0.162, + "p95_ms": 1.965, + "max_ms": 5.61, + "instances": 1126.0 + }, + { + "gpu_ms": 10.9, + "first_ms": 6.11, + "mean_ms": 0.348, + "p50_ms": 0.146, + "p95_ms": 1.969, + "max_ms": 6.114, + "instances": 1126.0 + } + ] + } + } + } +} diff --git a/app/vendor/rune/demo/text/sf-dark-1x.png b/app/vendor/rune/demo/text/sf-dark-1x.png new file mode 100644 index 0000000..2513305 Binary files /dev/null and b/app/vendor/rune/demo/text/sf-dark-1x.png differ diff --git a/app/vendor/rune/demo/text/sf-dark-2x.png b/app/vendor/rune/demo/text/sf-dark-2x.png new file mode 100644 index 0000000..9517a31 Binary files /dev/null and b/app/vendor/rune/demo/text/sf-dark-2x.png differ diff --git a/app/vendor/rune/demo/text/sf-diff-dark-1x.png b/app/vendor/rune/demo/text/sf-diff-dark-1x.png new file mode 100644 index 0000000..954dbd9 Binary files /dev/null and b/app/vendor/rune/demo/text/sf-diff-dark-1x.png differ diff --git a/app/vendor/rune/demo/text/sf-diff-dark-2x.png b/app/vendor/rune/demo/text/sf-diff-dark-2x.png new file mode 100644 index 0000000..e37bb43 Binary files /dev/null and b/app/vendor/rune/demo/text/sf-diff-dark-2x.png differ diff --git a/app/vendor/rune/demo/text/sf-diff-light-1x.png b/app/vendor/rune/demo/text/sf-diff-light-1x.png new file mode 100644 index 0000000..5399c61 Binary files /dev/null and b/app/vendor/rune/demo/text/sf-diff-light-1x.png differ diff --git a/app/vendor/rune/demo/text/sf-diff-light-2x.png b/app/vendor/rune/demo/text/sf-diff-light-2x.png new file mode 100644 index 0000000..5eab834 Binary files /dev/null and b/app/vendor/rune/demo/text/sf-diff-light-2x.png differ diff --git a/app/vendor/rune/demo/text/sf-light-1x.png b/app/vendor/rune/demo/text/sf-light-1x.png new file mode 100644 index 0000000..4319156 Binary files /dev/null and b/app/vendor/rune/demo/text/sf-light-1x.png differ diff --git a/app/vendor/rune/demo/text/sf-light-2x.png b/app/vendor/rune/demo/text/sf-light-2x.png new file mode 100644 index 0000000..4b37efb Binary files /dev/null and b/app/vendor/rune/demo/text/sf-light-2x.png differ diff --git a/app/vendor/rune/demo/text/sf-phases-1x.png b/app/vendor/rune/demo/text/sf-phases-1x.png new file mode 100644 index 0000000..f223f5a Binary files /dev/null and b/app/vendor/rune/demo/text/sf-phases-1x.png differ diff --git a/app/vendor/rune/demo/text/sf-phases-2x.png b/app/vendor/rune/demo/text/sf-phases-2x.png new file mode 100644 index 0000000..8ce146e Binary files /dev/null and b/app/vendor/rune/demo/text/sf-phases-2x.png differ diff --git a/app/vendor/rune/demo/text/ui-crops.png b/app/vendor/rune/demo/text/ui-crops.png new file mode 100644 index 0000000..0ced422 Binary files /dev/null and b/app/vendor/rune/demo/text/ui-crops.png differ diff --git a/app/vendor/rune/examples/background/Cargo.toml b/app/vendor/rune/examples/background/Cargo.toml new file mode 100644 index 0000000..6280404 --- /dev/null +++ b/app/vendor/rune/examples/background/Cargo.toml @@ -0,0 +1,11 @@ +[package] +name = "background" +version = "0.0.1" +edition.workspace = true +license.workspace = true + +[dependencies] +rune = { workspace = true, default-features = true, features = ["keys-overlay"] } + +[lints] +workspace = true diff --git a/app/vendor/rune/examples/background/src/main.rs b/app/vendor/rune/examples/background/src/main.rs new file mode 100644 index 0000000..1baa53d --- /dev/null +++ b/app/vendor/rune/examples/background/src/main.rs @@ -0,0 +1,249 @@ +//! An app that outlives its window: it starts with none, a background thread feeds it, and +//! commands on stdin open, focus, close and quit it. Closing the window keeps the app running; +//! reopening shows the same state (the ticks kept counting, the note kept its text). +//! +//! ```sh +//! cargo run -p background # stdin: open | show | hide | focus | activate TOKEN | close | status | quit +//! cargo run -p background -- --open # start with the window +//! cargo run -p background -- --release-gpu # closing also drops the GPU device +//! cargo run -p background -- --accessory # macOS: no Dock icon until `dock on` +//! # `hud show|hide|top|bottom|recording|transcribing|status` drives a recording-HUD overlay; +//! # `capsule show|hide|left|wide|status` a clickable corner capsule +//! cargo run -p background -- --snap /tmp/background.png +//! ``` + +#![forbid(unsafe_code)] + +use std::io::BufRead; +use std::time::Duration; + +use rune::tok::{self, radius, space, type_}; +use rune::{App, Cx, El, Key, KeyEvent, TextEdit, Tx, col, el, row, text, text_input}; + +struct Background { + ticks: u64, + closes: u32, + note: TextEdit, +} + +fn init() -> Background { + Background { + ticks: 0, + closes: 0, + note: TextEdit::new("Type here, close, reopen"), + } +} + +fn button(key: &'static str, label: &'static str, t: tok::Theme, f: impl Fn(&mut Background, &mut Tx) + 'static) -> El { + row() + .key(key) + .role("button") + .label(label) + .h(28.0) + .px(space::S3) + .center() + .radius(radius::MD) + .fill(t.card) + .border(1.0, t.card_border) + .on_press_tx(f) + .child(text(label).font(type_::LABEL).color(t.text)) +} + +fn view(s: &Background, cx: &mut Cx<Background>) -> El { + let t = tok::theme(cx.system_dark()); + col() + .key("window") + .fill(t.bg) + .px(space::S6) + .py(space::S6) + .gap(space::S3) + .child(text("Background app").key("title").font(type_::TITLE).color(t.text)) + .child( + text(format!( + "{} ticks from a background thread, window closed {} times", + s.ticks, s.closes + )) + .key("ticks") + .font(type_::BODY) + .color(t.text_secondary), + ) + .child( + el().key("note-field") + .w_full() + .h(32.0) + .px(space::S2) + .radius(radius::MD) + .fill(t.card) + .border(1.0, t.card_border) + .center_y() + .child( + text_input(&s.note, type_::BODY) + .key("note") + .color(t.text) + .on_edit(|s: &mut Background| &mut s.note), + ), + ) + .child( + row() + .key("actions") + .gap(space::S2) + .child(button("close", "Close window", t, |_, tx| tx.close_window())) + .child(button("quit", "Quit", t, |_, tx| tx.quit())), + ) +} + +/// Cmd/Ctrl-W closes the window, Cmd/Ctrl-Q quits. +fn on_key(_: &mut Background, ev: &KeyEvent, tx: &mut Tx) -> bool { + match ev.key { + Key::Command('w') => tx.close_window(), + Key::Command('q') => tx.quit(), + _ => return false, + } + true +} + +fn on_close(s: &mut Background, _: &mut Tx) { + s.closes += 1; + eprintln!("background: window closed; still running"); +} + +/// The overlay's own state: what a recording HUD shows. +#[derive(Default)] +struct Hud { + seconds: u64, + transcribing: bool, +} + +fn hud(h: &Hud, _: &mut Cx<Hud>) -> El { + let label = if h.transcribing { "Transcribing".to_owned() } else { format!("Recording {}:{:02}", h.seconds / 60, h.seconds % 60) }; + row().key("hud").w_full().h_full().center().child( + row() + .key("pill") + .h(36.0) + .px(space::S3) + .gap(space::S2) + .center() + .radius(18.0) + .fill(rune::oklch(0.2, 0.0, 0.0)) + .border(1.0, rune::oklch(0.3, 0.0, 0.0)) + .child(el().key("dot").size(8.0, 8.0).radius(4.0).fill(if h.seconds.is_multiple_of(2) { rune::oklch(0.65, 0.2, 25.0) } else { rune::oklch(0.45, 0.12, 25.0) })) + .child(text(label).key("label").font(type_::LABEL).color(rune::oklch(0.93, 0.0, 0.0))), + ) +} + +fn capsule(presses: &u32, _: &mut Cx<u32>) -> El { + let t = tok::theme(true); + row().key("capsule").w_full().h_full().px(space::S2).gap(space::S2).center().radius(24.0).fill(t.card).border(1.0, t.card_border).child( + text(format!("Pressed {presses} times")).key("presses").font(type_::LABEL).color(t.text), + ) + .child( + row().key("press").role("button").h(28.0).px(space::S3).center().radius(radius::MD).fill(t.control_off).hover(t.hover) + .on_press(|n: &mut u32| { + *n += 1; + eprintln!("background: capsule pressed {n}"); + }) + .child(text("Press").font(type_::LABEL).color(t.text)), + ) +} + +fn main() { + let mut app = App::new(rune::AppSpec::<Background> { + scenes: &[("ticked", |s| s.ticks = 42)], + on_key: Some(on_key), + ..rune::AppSpec::new("Background", (480.0, 420.0), init, view) + }) + .keep_running() + .on_close(on_close) + .on_window(|window| { + let native = window.with_raw_handle(|handle| format!("{:?}", handle.as_raw())).unwrap_or_default(); + eprintln!("background: native window {}", native.split('(').next().unwrap_or_default()); + }); + if !std::env::args().any(|a| a == "--open") { + app = app.windowless(); + } + if std::env::args().any(|a| a == "--accessory") { + app = app.accessory(); + } + if std::env::args().any(|a| a == "--release-gpu") { + app = app.release_gpu_when_closed(); + } + // `--hud-large` covers most of the screen, to check that clicks pass through it. + let size = if std::env::args().any(|a| a == "--hud-large") { (1200.0, 700.0) } else { (240.0, 44.0) }; + let overlay = app.overlay( + rune::OverlaySpec { + name: "background-hud", + size, + edge: rune::ScreenEdge::Top, + margin: 16.0, + align: rune::Align::Center, + inset: 0.0, + interactive: false, + view: hud, + }, + Hud::default(), + ); + // A clickable capsule in the top-right corner, like a meeting offer: clicks reach it, focus + // stays where it was. + let capsule = app.overlay( + rune::OverlaySpec { + name: "background-capsule", + size: (220.0, 48.0), + edge: rune::ScreenEdge::Top, + margin: 40.0, + align: rune::Align::End, + inset: 12.0, + interactive: true, + view: capsule, + }, + 0, + ); + let ticker = app.handle(); + let hud_ticker = overlay.clone(); + std::thread::spawn(move || { + loop { + std::thread::sleep(Duration::from_secs(1)); + ticker.update(|s, _| s.ticks += 1); + hud_ticker.update(|h, _| h.seconds += 1); + } + }); + let commands = app.handle(); + std::thread::spawn(move || { + for line in std::io::stdin().lock().lines() { + let Ok(line) = line else { break }; + let mut words = line.split_whitespace(); + match (words.next(), words.next()) { + (Some("open"), _) => commands.open(), + (Some("show"), _) => commands.show(), + (Some("hide"), _) => commands.hide(), + (Some("focus"), _) => commands.focus(), + (Some("position"), Some(x)) => { + if let (Ok(x), Some(Ok(y))) = (x.parse::<i32>(), words.next().map(str::parse::<i32>)) { + commands.set_position((x, y)); + } + } + (Some("activate"), Some(token)) => commands.activate(token), + (Some("close"), _) => commands.close(), + (Some("quit"), _) => commands.quit(), + (Some("status"), _) => eprintln!("background: visible {}, window error {:?}", commands.is_visible(), commands.window_error()), + (Some("dock"), Some(on)) => commands.set_dock_icon(on == "on"), + (Some("hud"), Some("show")) => overlay.show(), + (Some("hud"), Some("hide")) => overlay.hide(), + (Some("hud"), Some("top")) => overlay.set_edge(rune::ScreenEdge::Top), + (Some("hud"), Some("bottom")) => overlay.set_edge(rune::ScreenEdge::Bottom), + (Some("hud"), Some("transcribing")) => overlay.update(|h, _| h.transcribing = true), + (Some("hud"), Some("recording")) => overlay.update(|h, _| h.transcribing = false), + (Some("hud"), Some("status")) => eprintln!("background: hud {:?}", overlay.availability()), + (Some("capsule"), Some("show")) => capsule.show(), + (Some("capsule"), Some("hide")) => capsule.hide(), + (Some("capsule"), Some("left")) => capsule.set_align(rune::Align::Start, 12.0), + (Some("capsule"), Some("wide")) => capsule.resize((320.0, 48.0)), + (Some("capsule"), Some("status")) => eprintln!("background: capsule {:?}", capsule.availability()), + (Some(other), _) => { + eprintln!("background: unknown command {other:?} (open | show | hide | focus | position X Y | activate TOKEN | close | dock on|off | hud show|hide|top|bottom|recording|transcribing|status | capsule show|hide|left|wide|status | quit)") + } + (None, _) => {} + } + } + }); + app.run(); +} diff --git a/app/vendor/rune/examples/cursed-settings/Cargo.toml b/app/vendor/rune/examples/cursed-settings/Cargo.toml new file mode 100644 index 0000000..a10ff8b --- /dev/null +++ b/app/vendor/rune/examples/cursed-settings/Cargo.toml @@ -0,0 +1,31 @@ +[package] +name = "cursed-settings" +version = "0.0.1" +edition.workspace = true +license.workspace = true +publish = false + +[dependencies] +rune = { workspace = true, default-features = true, features = ["keys-overlay"] } +rune-motion = { workspace = true } +rune-kit = { workspace = true, default-features = true } +rune-theme-opencode = { workspace = true } +rune-fx = { workspace = true } +rune-light = { workspace = true } +wgpu = { workspace = true, features = ["std", "parking_lot", "wgsl"] } +bytemuck = { workspace = true } + +[target.'cfg(target_vendor = "apple")'.dependencies] +wgpu = { workspace = true, features = ["metal"] } + +[target.'cfg(target_os = "windows")'.dependencies] +wgpu = { workspace = true, features = ["dx12"] } + +[target.'cfg(all(not(target_vendor = "apple"), not(target_arch = "wasm32"), not(target_os = "windows")))'.dependencies] +wgpu = { workspace = true, features = ["vulkan"] } + +[target.'cfg(target_arch = "wasm32")'.dependencies] +wgpu = { workspace = true, features = ["webgpu"] } + +[lints] +workspace = true diff --git a/app/vendor/rune/examples/cursed-settings/scripts/showcase.json b/app/vendor/rune/examples/cursed-settings/scripts/showcase.json new file mode 100644 index 0000000..eed0e04 --- /dev/null +++ b/app/vendor/rune/examples/cursed-settings/scripts/showcase.json @@ -0,0 +1 @@ +{"events": [{"t": 0.6083, "type": "move", "x": 600.01, "y": 420.0}, {"t": 0.6167, "type": "move", "x": 600.04, "y": 419.99}, {"t": 0.625, "type": "move", "x": 600.15, "y": 419.95}, {"t": 0.6333, "type": "move", "x": 600.34, "y": 419.88}, {"t": 0.6417, "type": "move", "x": 600.65, "y": 419.78}, {"t": 0.65, "type": "move", "x": 601.1, "y": 419.62}, {"t": 0.6583, "type": "move", "x": 601.72, "y": 419.42}, {"t": 0.6667, "type": "move", "x": 602.52, "y": 419.14}, {"t": 0.675, "type": "move", "x": 603.52, "y": 418.8}, {"t": 0.6833, "type": "move", "x": 604.74, "y": 418.39}, {"t": 0.6917, "type": "move", "x": 606.18, "y": 417.9}, {"t": 0.7, "type": "move", "x": 607.87, "y": 417.33}, {"t": 0.7083, "type": "move", "x": 609.81, "y": 416.67}, {"t": 0.7167, "type": "move", "x": 612.0, "y": 415.92}, {"t": 0.725, "type": "move", "x": 614.46, "y": 415.08}, {"t": 0.7333, "type": "move", "x": 617.2, "y": 414.14}, {"t": 0.7417, "type": "move", "x": 620.2, "y": 413.11}, {"t": 0.75, "type": "move", "x": 623.48, "y": 411.98}, {"t": 0.7583, "type": "move", "x": 627.02, "y": 410.75}, {"t": 0.7667, "type": "move", "x": 630.84, "y": 409.41}, {"t": 0.775, "type": "move", "x": 634.93, "y": 407.98}, {"t": 0.7833, "type": "move", "x": 639.27, "y": 406.43}, {"t": 0.7917, "type": "move", "x": 643.87, "y": 404.78}, {"t": 0.8, "type": "move", "x": 648.71, "y": 403.02}, {"t": 0.8083, "type": "move", "x": 653.79, "y": 401.14}, {"t": 0.8167, "type": "move", "x": 659.08, "y": 399.15}, {"t": 0.825, "type": "move", "x": 664.59, "y": 397.04}, {"t": 0.8333, "type": "move", "x": 670.29, "y": 394.8}, {"t": 0.8417, "type": "move", "x": 676.17, "y": 392.44}, {"t": 0.85, "type": "move", "x": 682.2, "y": 389.96}, {"t": 0.8583, "type": "move", "x": 688.39, "y": 387.33}, {"t": 0.8667, "type": "move", "x": 694.7, "y": 384.58}, {"t": 0.875, "type": "move", "x": 701.11, "y": 381.68}, {"t": 0.8833, "type": "move", "x": 707.62, "y": 378.64}, {"t": 0.8917, "type": "move", "x": 714.19, "y": 375.46}, {"t": 0.9, "type": "move", "x": 720.82, "y": 372.14}, {"t": 0.9083, "type": "move", "x": 727.47, "y": 368.67}, {"t": 0.9167, "type": "move", "x": 734.13, "y": 365.07}, {"t": 0.925, "type": "move", "x": 740.79, "y": 361.32}, {"t": 0.9333, "type": "move", "x": 747.42, "y": 357.43}, {"t": 0.9417, "type": "move", "x": 754.01, "y": 353.42}, {"t": 0.95, "type": "move", "x": 760.54, "y": 349.28}, {"t": 0.9583, "type": "move", "x": 767.0, "y": 345.03}, {"t": 0.9667, "type": "move", "x": 773.36, "y": 340.67}, {"t": 0.975, "type": "move", "x": 779.63, "y": 336.22}, {"t": 0.9833, "type": "move", "x": 785.78, "y": 331.7}, {"t": 0.9917, "type": "move", "x": 791.81, "y": 327.11}, {"t": 1.0, "type": "move", "x": 797.71, "y": 322.47}, {"t": 1.0083, "type": "move", "x": 803.46, "y": 317.79}, {"t": 1.0167, "type": "move", "x": 809.06, "y": 313.11}, {"t": 1.025, "type": "move", "x": 814.5, "y": 308.43}, {"t": 1.0333, "type": "move", "x": 819.78, "y": 303.77}, {"t": 1.0417, "type": "move", "x": 824.89, "y": 299.15}, {"t": 1.05, "type": "move", "x": 829.82, "y": 294.59}, {"t": 1.0583, "type": "move", "x": 834.57, "y": 290.11}, {"t": 1.0667, "type": "move", "x": 839.14, "y": 285.72}, {"t": 1.075, "type": "move", "x": 843.52, "y": 281.44}, {"t": 1.0833, "type": "move", "x": 847.71, "y": 277.29}, {"t": 1.0917, "type": "move", "x": 851.7, "y": 273.28}, {"t": 1.1, "type": "move", "x": 855.5, "y": 269.43}, {"t": 1.1083, "type": "move", "x": 859.09, "y": 265.74}, {"t": 1.1167, "type": "move", "x": 862.49, "y": 262.23}, {"t": 1.125, "type": "move", "x": 865.68, "y": 258.9}, {"t": 1.1333, "type": "move", "x": 868.67, "y": 255.77}, {"t": 1.1417, "type": "move", "x": 871.46, "y": 252.83}, {"t": 1.15, "type": "move", "x": 874.04, "y": 250.1}, {"t": 1.1583, "type": "move", "x": 876.42, "y": 247.58}, {"t": 1.1667, "type": "move", "x": 878.59, "y": 245.27}, {"t": 1.175, "type": "move", "x": 880.57, "y": 243.16}, {"t": 1.1833, "type": "move", "x": 882.34, "y": 241.26}, {"t": 1.1917, "type": "move", "x": 883.93, "y": 239.57}, {"t": 1.2, "type": "move", "x": 885.33, "y": 238.07}, {"t": 1.2083, "type": "move", "x": 886.54, "y": 236.77}, {"t": 1.2167, "type": "move", "x": 887.59, "y": 235.66}, {"t": 1.225, "type": "move", "x": 888.46, "y": 234.72}, {"t": 1.2333, "type": "move", "x": 889.18, "y": 233.95}, {"t": 1.2417, "type": "move", "x": 889.76, "y": 233.33}, {"t": 1.25, "type": "move", "x": 890.2, "y": 232.85}, {"t": 1.2583, "type": "move", "x": 890.53, "y": 232.5}, {"t": 1.2667, "type": "move", "x": 890.76, "y": 232.26}, {"t": 1.275, "type": "move", "x": 890.89, "y": 232.11}, {"t": 1.2833, "type": "move", "x": 890.97, "y": 232.03}, {"t": 1.2917, "type": "move", "x": 891.0, "y": 232.0}, {"t": 1.3, "type": "move", "x": 891.0, "y": 232.0}, {"t": 1.42, "type": "tap", "x": 891, "y": 232, "hold": 0.09}, {"t": 2.8283, "type": "move", "x": 891.0, "y": 232.0}, {"t": 2.8367, "type": "move", "x": 890.99, "y": 232.03}, {"t": 2.845, "type": "move", "x": 890.98, "y": 232.08}, {"t": 2.8533, "type": "move", "x": 890.95, "y": 232.19}, {"t": 2.8617, "type": "move", "x": 890.91, "y": 232.37}, {"t": 2.87, "type": "move", "x": 890.84, "y": 232.63}, {"t": 2.8783, "type": "move", "x": 890.76, "y": 232.97}, {"t": 2.8867, "type": "move", "x": 890.64, "y": 233.42}, {"t": 2.895, "type": "move", "x": 890.5, "y": 233.97}, {"t": 2.9033, "type": "move", "x": 890.34, "y": 234.65}, {"t": 2.9117, "type": "move", "x": 890.14, "y": 235.44}, {"t": 2.92, "type": "move", "x": 889.91, "y": 236.37}, {"t": 2.9283, "type": "move", "x": 889.64, "y": 237.42}, {"t": 2.9367, "type": "move", "x": 889.35, "y": 238.61}, {"t": 2.945, "type": "move", "x": 889.02, "y": 239.94}, {"t": 2.9533, "type": "move", "x": 888.66, "y": 241.4}, {"t": 2.9617, "type": "move", "x": 888.27, "y": 243.0}, {"t": 2.97, "type": "move", "x": 887.86, "y": 244.73}, {"t": 2.9783, "type": "move", "x": 887.41, "y": 246.6}, {"t": 2.9867, "type": "move", "x": 886.95, "y": 248.6}, {"t": 2.995, "type": "move", "x": 886.47, "y": 250.72}, {"t": 3.0033, "type": "move", "x": 885.98, "y": 252.97}, {"t": 3.0117, "type": "move", "x": 885.48, "y": 255.34}, {"t": 3.02, "type": "move", "x": 884.97, "y": 257.81}, {"t": 3.0283, "type": "move", "x": 884.47, "y": 260.4}, {"t": 3.0367, "type": "move", "x": 883.98, "y": 263.08}, {"t": 3.045, "type": "move", "x": 883.51, "y": 265.85}, {"t": 3.0533, "type": "move", "x": 883.07, "y": 268.71}, {"t": 3.0617, "type": "move", "x": 882.65, "y": 271.64}, {"t": 3.07, "type": "move", "x": 882.28, "y": 274.63}, {"t": 3.0783, "type": "move", "x": 881.95, "y": 277.69}, {"t": 3.0867, "type": "move", "x": 881.67, "y": 280.79}, {"t": 3.095, "type": "move", "x": 881.45, "y": 283.94}, {"t": 3.1033, "type": "move", "x": 881.29, "y": 287.11}, {"t": 3.1117, "type": "move", "x": 881.19, "y": 290.3}, {"t": 3.12, "type": "move", "x": 881.16, "y": 293.5}, {"t": 3.1283, "type": "move", "x": 881.19, "y": 296.7}, {"t": 3.1367, "type": "move", "x": 881.29, "y": 299.89}, {"t": 3.145, "type": "move", "x": 881.45, "y": 303.06}, {"t": 3.1533, "type": "move", "x": 881.67, "y": 306.21}, {"t": 3.1617, "type": "move", "x": 881.95, "y": 309.31}, {"t": 3.17, "type": "move", "x": 882.28, "y": 312.37}, {"t": 3.1783, "type": "move", "x": 882.65, "y": 315.36}, {"t": 3.1867, "type": "move", "x": 883.07, "y": 318.29}, {"t": 3.195, "type": "move", "x": 883.51, "y": 321.15}, {"t": 3.2033, "type": "move", "x": 883.98, "y": 323.92}, {"t": 3.2117, "type": "move", "x": 884.47, "y": 326.6}, {"t": 3.22, "type": "move", "x": 884.97, "y": 329.19}, {"t": 3.2283, "type": "move", "x": 885.48, "y": 331.66}, {"t": 3.2367, "type": "move", "x": 885.98, "y": 334.03}, {"t": 3.245, "type": "move", "x": 886.47, "y": 336.28}, {"t": 3.2533, "type": "move", "x": 886.95, "y": 338.4}, {"t": 3.2617, "type": "move", "x": 887.41, "y": 340.4}, {"t": 3.27, "type": "move", "x": 887.86, "y": 342.27}, {"t": 3.2783, "type": "move", "x": 888.27, "y": 344.0}, {"t": 3.2867, "type": "move", "x": 888.66, "y": 345.6}, {"t": 3.295, "type": "move", "x": 889.02, "y": 347.06}, {"t": 3.3033, "type": "move", "x": 889.35, "y": 348.39}, {"t": 3.3117, "type": "move", "x": 889.64, "y": 349.58}, {"t": 3.32, "type": "move", "x": 889.91, "y": 350.63}, {"t": 3.3283, "type": "move", "x": 890.14, "y": 351.56}, {"t": 3.3367, "type": "move", "x": 890.34, "y": 352.35}, {"t": 3.345, "type": "move", "x": 890.5, "y": 353.03}, {"t": 3.3533, "type": "move", "x": 890.64, "y": 353.58}, {"t": 3.3617, "type": "move", "x": 890.76, "y": 354.03}, {"t": 3.37, "type": "move", "x": 890.84, "y": 354.37}, {"t": 3.3783, "type": "move", "x": 890.91, "y": 354.63}, {"t": 3.3867, "type": "move", "x": 890.95, "y": 354.81}, {"t": 3.395, "type": "move", "x": 890.98, "y": 354.92}, {"t": 3.4033, "type": "move", "x": 890.99, "y": 354.97}, {"t": 3.4117, "type": "move", "x": 891.0, "y": 355.0}, {"t": 3.42, "type": "move", "x": 891.0, "y": 355.0}, {"t": 3.54, "type": "tap", "x": 891, "y": 355, "hold": 0.09}, {"t": 5.5483, "type": "move", "x": 891.0, "y": 355.0}, {"t": 5.5567, "type": "move", "x": 891.0, "y": 355.0}, {"t": 5.565, "type": "move", "x": 891.0, "y": 355.0}, {"t": 5.5733, "type": "move", "x": 891.0, "y": 355.0}, {"t": 5.5817, "type": "move", "x": 891.0, "y": 355.0}, {"t": 5.59, "type": "move", "x": 891.0, "y": 355.0}, {"t": 5.5983, "type": "move", "x": 891.0, "y": 355.0}, {"t": 5.6067, "type": "move", "x": 891.0, "y": 355.0}, {"t": 5.615, "type": "move", "x": 891.0, "y": 355.0}, {"t": 5.6233, "type": "move", "x": 891.0, "y": 355.0}, {"t": 5.6317, "type": "move", "x": 891.0, "y": 355.0}, {"t": 5.64, "type": "move", "x": 891.0, "y": 355.0}, {"t": 5.6483, "type": "move", "x": 891.0, "y": 355.0}, {"t": 5.6567, "type": "move", "x": 891.0, "y": 355.0}, {"t": 5.665, "type": "move", "x": 891.0, "y": 355.0}, {"t": 5.6733, "type": "move", "x": 891.0, "y": 355.0}, {"t": 5.6817, "type": "move", "x": 891.0, "y": 355.0}, {"t": 5.69, "type": "move", "x": 891.0, "y": 355.0}, {"t": 5.6983, "type": "move", "x": 891.0, "y": 355.0}, {"t": 5.7067, "type": "move", "x": 891.0, "y": 355.0}, {"t": 5.715, "type": "move", "x": 891.0, "y": 355.0}, {"t": 5.7233, "type": "move", "x": 891.0, "y": 355.0}, {"t": 5.7317, "type": "move", "x": 891.0, "y": 355.0}, {"t": 5.74, "type": "move", "x": 891.0, "y": 355.0}, {"t": 5.7483, "type": "move", "x": 891.0, "y": 355.0}, {"t": 5.7567, "type": "move", "x": 891.0, "y": 355.0}, {"t": 5.765, "type": "move", "x": 891.0, "y": 355.0}, {"t": 5.7733, "type": "move", "x": 891.0, "y": 355.0}, {"t": 5.7817, "type": "move", "x": 891.0, "y": 355.0}, {"t": 5.79, "type": "move", "x": 891.0, "y": 355.0}, {"t": 5.91, "type": "tap", "x": 891, "y": 355, "hold": 0.09}, {"t": 6.4183, "type": "move", "x": 890.97, "y": 354.99}, {"t": 6.4267, "type": "move", "x": 890.8, "y": 354.89}, {"t": 6.435, "type": "move", "x": 890.33, "y": 354.63}, {"t": 6.4433, "type": "move", "x": 889.45, "y": 354.14}, {"t": 6.4517, "type": "move", "x": 888.04, "y": 353.36}, {"t": 6.46, "type": "move", "x": 886.01, "y": 352.24}, {"t": 6.4683, "type": "move", "x": 883.27, "y": 350.72}, {"t": 6.4767, "type": "move", "x": 879.74, "y": 348.77}, {"t": 6.485, "type": "move", "x": 875.36, "y": 346.35}, {"t": 6.4933, "type": "move", "x": 870.08, "y": 343.44}, {"t": 6.5017, "type": "move", "x": 863.86, "y": 340.01}, {"t": 6.51, "type": "move", "x": 856.66, "y": 336.04}, {"t": 6.5183, "type": "move", "x": 848.47, "y": 331.54}, {"t": 6.5267, "type": "move", "x": 839.25, "y": 326.5}, {"t": 6.535, "type": "move", "x": 829.02, "y": 320.93}, {"t": 6.5433, "type": "move", "x": 817.77, "y": 314.84}, {"t": 6.5517, "type": "move", "x": 805.51, "y": 308.25}, {"t": 6.56, "type": "move", "x": 792.25, "y": 301.21}, {"t": 6.5683, "type": "move", "x": 778.02, "y": 293.74}, {"t": 6.5767, "type": "move", "x": 762.84, "y": 285.9}, {"t": 6.585, "type": "move", "x": 746.73, "y": 277.74}, {"t": 6.5933, "type": "move", "x": 729.75, "y": 269.32}, {"t": 6.6017, "type": "move", "x": 711.91, "y": 260.71}, {"t": 6.61, "type": "move", "x": 693.28, "y": 252.0}, {"t": 6.6183, "type": "move", "x": 673.9, "y": 243.24}, {"t": 6.6267, "type": "move", "x": 653.82, "y": 234.53}, {"t": 6.635, "type": "move", "x": 633.09, "y": 225.95}, {"t": 6.6433, "type": "move", "x": 611.78, "y": 217.56}, {"t": 6.6517, "type": "move", "x": 589.95, "y": 209.45}, {"t": 6.66, "type": "move", "x": 567.67, "y": 201.68}, {"t": 6.6683, "type": "move", "x": 545.01, "y": 194.32}, {"t": 6.6767, "type": "move", "x": 522.04, "y": 187.4}, {"t": 6.685, "type": "move", "x": 498.86, "y": 180.98}, {"t": 6.6933, "type": "move", "x": 475.54, "y": 175.08}, {"t": 6.7017, "type": "move", "x": 452.17, "y": 169.72}, {"t": 6.71, "type": "move", "x": 428.83, "y": 164.9}, {"t": 6.7183, "type": "move", "x": 405.63, "y": 160.61}, {"t": 6.7267, "type": "move", "x": 382.64, "y": 156.85}, {"t": 6.735, "type": "move", "x": 359.98, "y": 153.58}, {"t": 6.7433, "type": "move", "x": 337.72, "y": 150.78}, {"t": 6.7517, "type": "move", "x": 315.96, "y": 148.4}, {"t": 6.76, "type": "move", "x": 294.78, "y": 146.41}, {"t": 6.7683, "type": "move", "x": 274.28, "y": 144.76}, {"t": 6.7767, "type": "move", "x": 254.52, "y": 143.41}, {"t": 6.785, "type": "move", "x": 235.6, "y": 142.31}, {"t": 6.7933, "type": "move", "x": 217.57, "y": 141.42}, {"t": 6.8017, "type": "move", "x": 200.49, "y": 140.72}, {"t": 6.81, "type": "move", "x": 184.43, "y": 140.16}, {"t": 6.8183, "type": "move", "x": 169.42, "y": 139.72}, {"t": 6.8267, "type": "move", "x": 155.51, "y": 139.36}, {"t": 6.835, "type": "move", "x": 142.72, "y": 139.08}, {"t": 6.8433, "type": "move", "x": 131.07, "y": 138.86}, {"t": 6.8517, "type": "move", "x": 120.57, "y": 138.68}, {"t": 6.86, "type": "move", "x": 111.22, "y": 138.53}, {"t": 6.8683, "type": "move", "x": 103.0, "y": 138.41}, {"t": 6.8767, "type": "move", "x": 95.9, "y": 138.31}, {"t": 6.885, "type": "move", "x": 89.87, "y": 138.23}, {"t": 6.8933, "type": "move", "x": 84.87, "y": 138.17}, {"t": 6.9017, "type": "move", "x": 80.83, "y": 138.11}, {"t": 6.91, "type": "move", "x": 77.7, "y": 138.07}, {"t": 6.9183, "type": "move", "x": 75.38, "y": 138.04}, {"t": 6.9267, "type": "move", "x": 73.77, "y": 138.02}, {"t": 6.935, "type": "move", "x": 72.77, "y": 138.01}, {"t": 6.9433, "type": "move", "x": 72.23, "y": 138.0}, {"t": 6.9517, "type": "move", "x": 72.03, "y": 138.0}, {"t": 6.96, "type": "move", "x": 72.0, "y": 138.0}, {"t": 7.08, "type": "tap", "x": 72, "y": 138, "hold": 0.09}, {"t": 7.6883, "type": "move", "x": 72.02, "y": 138.01}, {"t": 7.6967, "type": "move", "x": 72.17, "y": 138.05}, {"t": 7.705, "type": "move", "x": 72.55, "y": 138.16}, {"t": 7.7133, "type": "move", "x": 73.28, "y": 138.37}, {"t": 7.7217, "type": "move", "x": 74.44, "y": 138.7}, {"t": 7.73, "type": "move", "x": 76.13, "y": 139.19}, {"t": 7.7383, "type": "move", "x": 78.42, "y": 139.85}, {"t": 7.7467, "type": "move", "x": 81.36, "y": 140.7}, {"t": 7.755, "type": "move", "x": 85.03, "y": 141.75}, {"t": 7.7633, "type": "move", "x": 89.47, "y": 143.03}, {"t": 7.7717, "type": "move", "x": 94.72, "y": 144.54}, {"t": 7.78, "type": "move", "x": 100.82, "y": 146.28}, {"t": 7.7883, "type": "move", "x": 107.79, "y": 148.28}, {"t": 7.7967, "type": "move", "x": 115.64, "y": 150.51}, {"t": 7.805, "type": "move", "x": 124.39, "y": 153.0}, {"t": 7.8133, "type": "move", "x": 134.05, "y": 155.72}, {"t": 7.8217, "type": "move", "x": 144.61, "y": 158.67}, {"t": 7.83, "type": "move", "x": 156.06, "y": 161.83}, {"t": 7.8383, "type": "move", "x": 168.4, "y": 165.19}, {"t": 7.8467, "type": "move", "x": 181.6, "y": 168.73}, {"t": 7.855, "type": "move", "x": 195.65, "y": 172.42}, {"t": 7.8633, "type": "move", "x": 210.5, "y": 176.22}, {"t": 7.8717, "type": "move", "x": 226.14, "y": 180.1}, {"t": 7.88, "type": "move", "x": 242.52, "y": 184.01}, {"t": 7.8883, "type": "move", "x": 259.6, "y": 187.93}, {"t": 7.8967, "type": "move", "x": 277.34, "y": 191.79}, {"t": 7.905, "type": "move", "x": 295.69, "y": 195.56}, {"t": 7.9133, "type": "move", "x": 314.6, "y": 199.17}, {"t": 7.9217, "type": "move", "x": 334.02, "y": 202.59}, {"t": 7.93, "type": "move", "x": 353.9, "y": 205.76}, {"t": 7.9383, "type": "move", "x": 374.16, "y": 208.65}, {"t": 7.9467, "type": "move", "x": 394.76, "y": 211.21}, {"t": 7.955, "type": "move", "x": 415.64, "y": 213.4}, {"t": 7.9633, "type": "move", "x": 436.72, "y": 215.19}, {"t": 7.9717, "type": "move", "x": 457.95, "y": 216.57}, {"t": 7.98, "type": "move", "x": 479.26, "y": 217.52}, {"t": 7.9883, "type": "move", "x": 500.58, "y": 218.03}, {"t": 7.9967, "type": "move", "x": 521.86, "y": 218.1}, {"t": 8.005, "type": "move", "x": 543.02, "y": 217.75}, {"t": 8.0133, "type": "move", "x": 563.99, "y": 216.99}, {"t": 8.0217, "type": "move", "x": 584.72, "y": 215.85}, {"t": 8.03, "type": "move", "x": 605.13, "y": 214.35}, {"t": 8.0383, "type": "move", "x": 625.18, "y": 212.54}, {"t": 8.0467, "type": "move", "x": 644.79, "y": 210.46}, {"t": 8.055, "type": "move", "x": 663.9, "y": 208.14}, {"t": 8.0633, "type": "move", "x": 682.47, "y": 205.64}, {"t": 8.0717, "type": "move", "x": 700.43, "y": 203.0}, {"t": 8.08, "type": "move", "x": 717.74, "y": 200.26}, {"t": 8.0883, "type": "move", "x": 734.35, "y": 197.47}, {"t": 8.0967, "type": "move", "x": 750.21, "y": 194.67}, {"t": 8.105, "type": "move", "x": 765.29, "y": 191.89}, {"t": 8.1133, "type": "move", "x": 779.55, "y": 189.17}, {"t": 8.1217, "type": "move", "x": 792.97, "y": 186.55}, {"t": 8.13, "type": "move", "x": 805.51, "y": 184.04}, {"t": 8.1383, "type": "move", "x": 817.15, "y": 181.66}, {"t": 8.1467, "type": "move", "x": 827.89, "y": 179.44}, {"t": 8.155, "type": "move", "x": 837.71, "y": 177.38}, {"t": 8.1633, "type": "move", "x": 846.61, "y": 175.5}, {"t": 8.1717, "type": "move", "x": 854.6, "y": 173.81}, {"t": 8.18, "type": "move", "x": 861.68, "y": 172.3}, {"t": 8.1883, "type": "move", "x": 867.88, "y": 170.97}, {"t": 8.1967, "type": "move", "x": 873.22, "y": 169.82}, {"t": 8.205, "type": "move", "x": 877.74, "y": 168.85}, {"t": 8.2133, "type": "move", "x": 881.47, "y": 168.05}, {"t": 8.2217, "type": "move", "x": 884.47, "y": 167.41}, {"t": 8.23, "type": "move", "x": 886.8, "y": 166.9}, {"t": 8.2383, "type": "move", "x": 888.51, "y": 166.54}, {"t": 8.2467, "type": "move", "x": 889.7, "y": 166.28}, {"t": 8.255, "type": "move", "x": 890.44, "y": 166.12}, {"t": 8.2633, "type": "move", "x": 890.83, "y": 166.04}, {"t": 8.2717, "type": "move", "x": 890.98, "y": 166.0}, {"t": 8.28, "type": "move", "x": 891.0, "y": 166.0}, {"t": 8.4, "type": "tap", "x": 891, "y": 166, "hold": 0.09}, {"t": 9.9083, "type": "move", "x": 891.0, "y": 166.01}, {"t": 9.9167, "type": "move", "x": 890.98, "y": 166.06}, {"t": 9.925, "type": "move", "x": 890.95, "y": 166.21}, {"t": 9.9333, "type": "move", "x": 890.88, "y": 166.5}, {"t": 9.9417, "type": "move", "x": 890.76, "y": 166.95}, {"t": 9.95, "type": "move", "x": 890.6, "y": 167.6}, {"t": 9.9583, "type": "move", "x": 890.37, "y": 168.49}, {"t": 9.9667, "type": "move", "x": 890.09, "y": 169.63}, {"t": 9.975, "type": "move", "x": 889.73, "y": 171.06}, {"t": 9.9833, "type": "move", "x": 889.3, "y": 172.78}, {"t": 9.9917, "type": "move", "x": 888.79, "y": 174.82}, {"t": 10.0, "type": "move", "x": 888.2, "y": 177.18}, {"t": 10.0083, "type": "move", "x": 887.52, "y": 179.88}, {"t": 10.0167, "type": "move", "x": 886.77, "y": 182.93}, {"t": 10.025, "type": "move", "x": 885.93, "y": 186.32}, {"t": 10.0333, "type": "move", "x": 885.01, "y": 190.07}, {"t": 10.0417, "type": "move", "x": 884.01, "y": 194.17}, {"t": 10.05, "type": "move", "x": 882.95, "y": 198.61}, {"t": 10.0583, "type": "move", "x": 881.82, "y": 203.39}, {"t": 10.0667, "type": "move", "x": 880.63, "y": 208.51}, {"t": 10.075, "type": "move", "x": 879.4, "y": 213.95}, {"t": 10.0833, "type": "move", "x": 878.14, "y": 219.71}, {"t": 10.0917, "type": "move", "x": 876.85, "y": 225.77}, {"t": 10.1, "type": "move", "x": 875.56, "y": 232.11}, {"t": 10.1083, "type": "move", "x": 874.28, "y": 238.72}, {"t": 10.1167, "type": "move", "x": 873.03, "y": 245.59}, {"t": 10.125, "type": "move", "x": 871.83, "y": 252.69}, {"t": 10.1333, "type": "move", "x": 870.69, "y": 260.0}, {"t": 10.1417, "type": "move", "x": 869.63, "y": 267.51}, {"t": 10.15, "type": "move", "x": 868.67, "y": 275.19}, {"t": 10.1583, "type": "move", "x": 867.83, "y": 283.01}, {"t": 10.1667, "type": "move", "x": 867.12, "y": 290.96}, {"t": 10.175, "type": "move", "x": 866.55, "y": 299.0}, {"t": 10.1833, "type": "move", "x": 866.14, "y": 307.13}, {"t": 10.1917, "type": "move", "x": 865.88, "y": 315.3}, {"t": 10.2, "type": "move", "x": 865.8, "y": 323.5}, {"t": 10.2083, "type": "move", "x": 865.88, "y": 331.7}, {"t": 10.2167, "type": "move", "x": 866.14, "y": 339.87}, {"t": 10.225, "type": "move", "x": 866.55, "y": 348.0}, {"t": 10.2333, "type": "move", "x": 867.12, "y": 356.04}, {"t": 10.2417, "type": "move", "x": 867.83, "y": 363.99}, {"t": 10.25, "type": "move", "x": 868.67, "y": 371.81}, {"t": 10.2583, "type": "move", "x": 869.63, "y": 379.49}, {"t": 10.2667, "type": "move", "x": 870.69, "y": 387.0}, {"t": 10.275, "type": "move", "x": 871.83, "y": 394.31}, {"t": 10.2833, "type": "move", "x": 873.03, "y": 401.41}, {"t": 10.2917, "type": "move", "x": 874.28, "y": 408.28}, {"t": 10.3, "type": "move", "x": 875.56, "y": 414.89}, {"t": 10.3083, "type": "move", "x": 876.85, "y": 421.23}, {"t": 10.3167, "type": "move", "x": 878.14, "y": 427.29}, {"t": 10.325, "type": "move", "x": 879.4, "y": 433.05}, {"t": 10.3333, "type": "move", "x": 880.63, "y": 438.49}, {"t": 10.3417, "type": "move", "x": 881.82, "y": 443.61}, {"t": 10.35, "type": "move", "x": 882.95, "y": 448.39}, {"t": 10.3583, "type": "move", "x": 884.01, "y": 452.83}, {"t": 10.3667, "type": "move", "x": 885.01, "y": 456.93}, {"t": 10.375, "type": "move", "x": 885.93, "y": 460.68}, {"t": 10.3833, "type": "move", "x": 886.77, "y": 464.07}, {"t": 10.3917, "type": "move", "x": 887.52, "y": 467.12}, {"t": 10.4, "type": "move", "x": 888.2, "y": 469.82}, {"t": 10.4083, "type": "move", "x": 888.79, "y": 472.18}, {"t": 10.4167, "type": "move", "x": 889.3, "y": 474.22}, {"t": 10.425, "type": "move", "x": 889.73, "y": 475.94}, {"t": 10.4333, "type": "move", "x": 890.09, "y": 477.37}, {"t": 10.4417, "type": "move", "x": 890.37, "y": 478.51}, {"t": 10.45, "type": "move", "x": 890.6, "y": 479.4}, {"t": 10.4583, "type": "move", "x": 890.76, "y": 480.05}, {"t": 10.4667, "type": "move", "x": 890.88, "y": 480.5}, {"t": 10.475, "type": "move", "x": 890.95, "y": 480.79}, {"t": 10.4833, "type": "move", "x": 890.98, "y": 480.94}, {"t": 10.4917, "type": "move", "x": 891.0, "y": 480.99}, {"t": 10.5, "type": "move", "x": 891.0, "y": 481.0}, {"t": 10.62, "type": "tap", "x": 891, "y": 481, "hold": 0.09}, {"t": 11.7283, "type": "move", "x": 890.97, "y": 480.98}, {"t": 11.7367, "type": "move", "x": 890.8, "y": 480.86}, {"t": 11.745, "type": "move", "x": 890.35, "y": 480.54}, {"t": 11.7533, "type": "move", "x": 889.49, "y": 479.95}, {"t": 11.7617, "type": "move", "x": 888.13, "y": 478.99}, {"t": 11.77, "type": "move", "x": 886.16, "y": 477.61}, {"t": 11.7783, "type": "move", "x": 883.49, "y": 475.75}, {"t": 11.7867, "type": "move", "x": 880.07, "y": 473.35}, {"t": 11.795, "type": "move", "x": 875.82, "y": 470.38}, {"t": 11.8033, "type": "move", "x": 870.69, "y": 466.8}, {"t": 11.8117, "type": "move", "x": 864.65, "y": 462.58}, {"t": 11.82, "type": "move", "x": 857.65, "y": 457.71}, {"t": 11.8283, "type": "move", "x": 849.69, "y": 452.17}, {"t": 11.8367, "type": "move", "x": 840.74, "y": 445.97}, {"t": 11.845, "type": "move", "x": 830.79, "y": 439.11}, {"t": 11.8533, "type": "move", "x": 819.86, "y": 431.6}, {"t": 11.8617, "type": "move", "x": 807.93, "y": 423.48}, {"t": 11.87, "type": "move", "x": 795.02, "y": 414.77}, {"t": 11.8783, "type": "move", "x": 781.16, "y": 405.52}, {"t": 11.8867, "type": "move", "x": 766.35, "y": 395.77}, {"t": 11.895, "type": "move", "x": 750.63, "y": 385.6}, {"t": 11.9033, "type": "move", "x": 734.03, "y": 375.07}, {"t": 11.9117, "type": "move", "x": 716.58, "y": 364.26}, {"t": 11.92, "type": "move", "x": 698.31, "y": 353.24}, {"t": 11.9283, "type": "move", "x": 679.28, "y": 342.1}, {"t": 11.9367, "type": "move", "x": 659.51, "y": 330.93}, {"t": 11.945, "type": "move", "x": 639.07, "y": 319.81}, {"t": 11.9533, "type": "move", "x": 618.01, "y": 308.85}, {"t": 11.9617, "type": "move", "x": 596.38, "y": 298.1}, {"t": 11.97, "type": "move", "x": 574.24, "y": 287.66}, {"t": 11.9783, "type": "move", "x": 551.68, "y": 277.6}, {"t": 11.9867, "type": "move", "x": 528.75, "y": 267.97}, {"t": 11.995, "type": "move", "x": 505.54, "y": 258.82}, {"t": 12.0033, "type": "move", "x": 482.13, "y": 250.19}, {"t": 12.0117, "type": "move", "x": 458.61, "y": 242.12}, {"t": 12.02, "type": "move", "x": 435.07, "y": 234.61}, {"t": 12.0283, "type": "move", "x": 411.61, "y": 227.66}, {"t": 12.0367, "type": "move", "x": 388.31, "y": 221.28}, {"t": 12.045, "type": "move", "x": 365.29, "y": 215.44}, {"t": 12.0533, "type": "move", "x": 342.64, "y": 210.12}, {"t": 12.0617, "type": "move", "x": 320.46, "y": 205.3}, {"t": 12.07, "type": "move", "x": 298.84, "y": 200.94}, {"t": 12.0783, "type": "move", "x": 277.87, "y": 197.0}, {"t": 12.0867, "type": "move", "x": 257.65, "y": 193.46}, {"t": 12.095, "type": "move", "x": 238.25, "y": 190.26}, {"t": 12.1033, "type": "move", "x": 219.75, "y": 187.39}, {"t": 12.1117, "type": "move", "x": 202.22, "y": 184.8}, {"t": 12.12, "type": "move", "x": 185.71, "y": 182.47}, {"t": 12.1283, "type": "move", "x": 170.28, "y": 180.38}, {"t": 12.1367, "type": "move", "x": 155.97, "y": 178.5}, {"t": 12.145, "type": "move", "x": 142.81, "y": 176.82}, {"t": 12.1533, "type": "move", "x": 130.82, "y": 175.32}, {"t": 12.1617, "type": "move", "x": 120.02, "y": 173.99}, {"t": 12.17, "type": "move", "x": 110.39, "y": 172.82}, {"t": 12.1783, "type": "move", "x": 101.93, "y": 171.8}, {"t": 12.1867, "type": "move", "x": 94.61, "y": 170.92}, {"t": 12.195, "type": "move", "x": 88.4, "y": 170.18}, {"t": 12.2033, "type": "move", "x": 83.25, "y": 169.57}, {"t": 12.2117, "type": "move", "x": 79.1, "y": 169.08}, {"t": 12.22, "type": "move", "x": 75.87, "y": 168.7}, {"t": 12.2283, "type": "move", "x": 73.48, "y": 168.41}, {"t": 12.2367, "type": "move", "x": 71.83, "y": 168.22}, {"t": 12.245, "type": "move", "x": 70.79, "y": 168.09}, {"t": 12.2533, "type": "move", "x": 70.24, "y": 168.03}, {"t": 12.2617, "type": "move", "x": 70.03, "y": 168.0}, {"t": 12.27, "type": "move", "x": 70.0, "y": 168.0}, {"t": 12.39, "type": "tap", "x": 70, "y": 168, "hold": 0.09}, {"t": 12.9983, "type": "move", "x": 70.02, "y": 168.01}, {"t": 13.0067, "type": "move", "x": 70.17, "y": 168.04}, {"t": 13.015, "type": "move", "x": 70.56, "y": 168.14}, {"t": 13.0233, "type": "move", "x": 71.29, "y": 168.32}, {"t": 13.0317, "type": "move", "x": 72.47, "y": 168.62}, {"t": 13.04, "type": "move", "x": 74.18, "y": 169.04}, {"t": 13.0483, "type": "move", "x": 76.49, "y": 169.61}, {"t": 13.0567, "type": "move", "x": 79.47, "y": 170.36}, {"t": 13.065, "type": "move", "x": 83.19, "y": 171.28}, {"t": 13.0733, "type": "move", "x": 87.68, "y": 172.39}, {"t": 13.0817, "type": "move", "x": 92.99, "y": 173.71}, {"t": 13.09, "type": "move", "x": 99.16, "y": 175.24}, {"t": 13.0983, "type": "move", "x": 106.2, "y": 176.98}, {"t": 13.1067, "type": "move", "x": 114.15, "y": 178.93}, {"t": 13.115, "type": "move", "x": 123.0, "y": 181.09}, {"t": 13.1233, "type": "move", "x": 132.77, "y": 183.46}, {"t": 13.1317, "type": "move", "x": 143.45, "y": 186.03}, {"t": 13.14, "type": "move", "x": 155.04, "y": 188.78}, {"t": 13.1483, "type": "move", "x": 167.51, "y": 191.69}, {"t": 13.1567, "type": "move", "x": 180.86, "y": 194.75}, {"t": 13.165, "type": "move", "x": 195.06, "y": 197.92}, {"t": 13.1733, "type": "move", "x": 210.07, "y": 201.18}, {"t": 13.1817, "type": "move", "x": 225.86, "y": 204.49}, {"t": 13.19, "type": "move", "x": 242.41, "y": 207.82}, {"t": 13.1983, "type": "move", "x": 259.65, "y": 211.11}, {"t": 13.2067, "type": "move", "x": 277.56, "y": 214.33}, {"t": 13.215, "type": "move", "x": 296.07, "y": 217.42}, {"t": 13.2233, "type": "move", "x": 315.13, "y": 220.35}, {"t": 13.2317, "type": "move", "x": 334.7, "y": 223.06}, {"t": 13.24, "type": "move", "x": 354.72, "y": 225.51}, {"t": 13.2483, "type": "move", "x": 375.11, "y": 227.65}, {"t": 13.2567, "type": "move", "x": 395.83, "y": 229.46}, {"t": 13.265, "type": "move", "x": 416.81, "y": 230.89}, {"t": 13.2733, "type": "move", "x": 437.99, "y": 231.91}, {"t": 13.2817, "type": "move", "x": 459.29, "y": 232.51}, {"t": 13.29, "type": "move", "x": 480.66, "y": 232.68}, {"t": 13.2983, "type": "move", "x": 502.03, "y": 232.41}, {"t": 13.3067, "type": "move", "x": 523.33, "y": 231.7}, {"t": 13.315, "type": "move", "x": 544.5, "y": 230.57}, {"t": 13.3233, "type": "move", "x": 565.47, "y": 229.04}, {"t": 13.3317, "type": "move", "x": 586.18, "y": 227.14}, {"t": 13.34, "type": "move", "x": 606.57, "y": 224.89}, {"t": 13.3483, "type": "move", "x": 626.57, "y": 222.35}, {"t": 13.3567, "type": "move", "x": 646.12, "y": 219.54}, {"t": 13.365, "type": "move", "x": 665.18, "y": 216.52}, {"t": 13.3733, "type": "move", "x": 683.67, "y": 213.34}, {"t": 13.3817, "type": "move", "x": 701.56, "y": 210.03}, {"t": 13.39, "type": "move", "x": 718.79, "y": 206.66}, {"t": 13.3983, "type": "move", "x": 735.32, "y": 203.25}, {"t": 13.4067, "type": "move", "x": 751.1, "y": 199.86}, {"t": 13.415, "type": "move", "x": 766.09, "y": 196.53}, {"t": 13.4233, "type": "move", "x": 780.27, "y": 193.29}, {"t": 13.4317, "type": "move", "x": 793.6, "y": 190.17}, {"t": 13.44, "type": "move", "x": 806.06, "y": 187.19}, {"t": 13.4483, "type": "move", "x": 817.64, "y": 184.39}, {"t": 13.4567, "type": "move", "x": 828.3, "y": 181.77}, {"t": 13.465, "type": "move", "x": 838.06, "y": 179.35}, {"t": 13.4733, "type": "move", "x": 846.9, "y": 177.14}, {"t": 13.4817, "type": "move", "x": 854.84, "y": 175.15}, {"t": 13.49, "type": "move", "x": 861.88, "y": 173.38}, {"t": 13.4983, "type": "move", "x": 868.04, "y": 171.82}, {"t": 13.5067, "type": "move", "x": 873.34, "y": 170.48}, {"t": 13.515, "type": "move", "x": 877.83, "y": 169.34}, {"t": 13.5233, "type": "move", "x": 881.54, "y": 168.4}, {"t": 13.5317, "type": "move", "x": 884.52, "y": 167.65}, {"t": 13.54, "type": "move", "x": 886.83, "y": 167.06}, {"t": 13.5483, "type": "move", "x": 888.53, "y": 166.63}, {"t": 13.5567, "type": "move", "x": 889.71, "y": 166.33}, {"t": 13.565, "type": "move", "x": 890.44, "y": 166.14}, {"t": 13.5733, "type": "move", "x": 890.83, "y": 166.04}, {"t": 13.5817, "type": "move", "x": 890.98, "y": 166.01}, {"t": 13.59, "type": "move", "x": 891.0, "y": 166.0}, {"t": 13.71, "type": "tap", "x": 891, "y": 166, "hold": 0.09}, {"t": 14.8183, "type": "move", "x": 890.99, "y": 166.01}, {"t": 14.8267, "type": "move", "x": 890.91, "y": 166.08}, {"t": 14.835, "type": "move", "x": 890.7, "y": 166.26}, {"t": 14.8433, "type": "move", "x": 890.31, "y": 166.61}, {"t": 14.8517, "type": "move", "x": 889.68, "y": 167.16}, {"t": 14.86, "type": "move", "x": 888.77, "y": 167.96}, {"t": 14.8683, "type": "move", "x": 887.54, "y": 169.04}, {"t": 14.8767, "type": "move", "x": 885.96, "y": 170.43}, {"t": 14.885, "type": "move", "x": 884.0, "y": 172.16}, {"t": 14.8933, "type": "move", "x": 881.63, "y": 174.23}, {"t": 14.9017, "type": "move", "x": 878.85, "y": 176.69}, {"t": 14.91, "type": "move", "x": 875.63, "y": 179.52}, {"t": 14.9183, "type": "move", "x": 871.98, "y": 182.75}, {"t": 14.9267, "type": "move", "x": 867.88, "y": 186.39}, {"t": 14.935, "type": "move", "x": 863.33, "y": 190.43}, {"t": 14.9433, "type": "move", "x": 858.36, "y": 194.88}, {"t": 14.9517, "type": "move", "x": 852.96, "y": 199.75}, {"t": 14.96, "type": "move", "x": 847.17, "y": 205.02}, {"t": 14.9683, "type": "move", "x": 840.99, "y": 210.69}, {"t": 14.9767, "type": "move", "x": 834.46, "y": 216.76}, {"t": 14.985, "type": "move", "x": 827.61, "y": 223.23}, {"t": 14.9933, "type": "move", "x": 820.48, "y": 230.09}, {"t": 15.0017, "type": "move", "x": 813.11, "y": 237.33}, {"t": 15.01, "type": "move", "x": 805.54, "y": 244.95}, {"t": 15.0183, "type": "move", "x": 797.83, "y": 252.93}, {"t": 15.0267, "type": "move", "x": 790.01, "y": 261.25}, {"t": 15.035, "type": "move", "x": 782.14, "y": 269.92}, {"t": 15.0433, "type": "move", "x": 774.26, "y": 278.91}, {"t": 15.0517, "type": "move", "x": 766.43, "y": 288.2}, {"t": 15.06, "type": "move", "x": 758.68, "y": 297.78}, {"t": 15.0683, "type": "move", "x": 751.07, "y": 307.61}, {"t": 15.0767, "type": "move", "x": 743.62, "y": 317.67}, {"t": 15.085, "type": "move", "x": 736.38, "y": 327.92}, {"t": 15.0933, "type": "move", "x": 729.37, "y": 338.33}, {"t": 15.1017, "type": "move", "x": 722.61, "y": 348.87}, {"t": 15.11, "type": "move", "x": 716.13, "y": 359.48}, {"t": 15.1183, "type": "move", "x": 709.94, "y": 370.12}, {"t": 15.1267, "type": "move", "x": 704.04, "y": 380.75}, {"t": 15.135, "type": "move", "x": 698.43, "y": 391.3}, {"t": 15.1433, "type": "move", "x": 693.13, "y": 401.74}, {"t": 15.1517, "type": "move", "x": 688.13, "y": 412.01}, {"t": 15.16, "type": "move", "x": 683.41, "y": 422.06}, {"t": 15.1683, "type": "move", "x": 678.99, "y": 431.84}, {"t": 15.1767, "type": "move", "x": 674.84, "y": 441.3}, {"t": 15.185, "type": "move", "x": 670.96, "y": 450.41}, {"t": 15.1933, "type": "move", "x": 667.35, "y": 459.11}, {"t": 15.2017, "type": "move", "x": 663.99, "y": 467.37}, {"t": 15.21, "type": "move", "x": 660.89, "y": 475.16}, {"t": 15.2183, "type": "move", "x": 658.02, "y": 482.45}, {"t": 15.2267, "type": "move", "x": 655.4, "y": 489.22}, {"t": 15.235, "type": "move", "x": 653.0, "y": 495.46}, {"t": 15.2433, "type": "move", "x": 650.84, "y": 501.14}, {"t": 15.2517, "type": "move", "x": 648.9, "y": 506.26}, {"t": 15.26, "type": "move", "x": 647.18, "y": 510.83}, {"t": 15.2683, "type": "move", "x": 645.67, "y": 514.85}, {"t": 15.2767, "type": "move", "x": 644.37, "y": 518.32}, {"t": 15.285, "type": "move", "x": 643.26, "y": 521.27}, {"t": 15.2933, "type": "move", "x": 642.35, "y": 523.71}, {"t": 15.3017, "type": "move", "x": 641.61, "y": 525.68}, {"t": 15.31, "type": "move", "x": 641.04, "y": 527.21}, {"t": 15.3183, "type": "move", "x": 640.62, "y": 528.35}, {"t": 15.3267, "type": "move", "x": 640.32, "y": 529.13}, {"t": 15.335, "type": "move", "x": 640.14, "y": 529.63}, {"t": 15.3433, "type": "move", "x": 640.04, "y": 529.89}, {"t": 15.3517, "type": "move", "x": 640.01, "y": 529.99}, {"t": 15.36, "type": "move", "x": 640.0, "y": 530.0}, {"t": 15.9683, "type": "move", "x": 640.01, "y": 530.01}, {"t": 15.9767, "type": "move", "x": 640.08, "y": 530.09}, {"t": 15.985, "type": "move", "x": 640.25, "y": 530.28}, {"t": 15.9933, "type": "move", "x": 640.58, "y": 530.64}, {"t": 16.0017, "type": "move", "x": 641.08, "y": 531.19}, {"t": 16.01, "type": "move", "x": 641.77, "y": 531.95}, {"t": 16.0183, "type": "move", "x": 642.69, "y": 532.96}, {"t": 16.0267, "type": "move", "x": 643.82, "y": 534.2}, {"t": 16.035, "type": "move", "x": 645.19, "y": 535.67}, {"t": 16.0433, "type": "move", "x": 646.78, "y": 537.37}, {"t": 16.0517, "type": "move", "x": 648.6, "y": 539.27}, {"t": 16.06, "type": "move", "x": 650.63, "y": 541.34}, {"t": 16.0683, "type": "move", "x": 652.88, "y": 543.53}, {"t": 16.0767, "type": "move", "x": 655.33, "y": 545.81}, {"t": 16.085, "type": "move", "x": 657.96, "y": 548.12}, {"t": 16.0933, "type": "move", "x": 660.77, "y": 550.42}, {"t": 16.1017, "type": "move", "x": 663.72, "y": 552.66}, {"t": 16.11, "type": "move", "x": 666.8, "y": 554.8}, {"t": 16.1183, "type": "move", "x": 669.96, "y": 556.82}, {"t": 16.1267, "type": "move", "x": 673.17, "y": 558.68}, {"t": 16.135, "type": "move", "x": 676.37, "y": 560.39}, {"t": 16.1433, "type": "move", "x": 679.52, "y": 561.93}, {"t": 16.1517, "type": "move", "x": 682.56, "y": 563.32}, {"t": 16.16, "type": "move", "x": 685.45, "y": 564.55}, {"t": 16.1683, "type": "move", "x": 688.14, "y": 565.63}, {"t": 16.1767, "type": "move", "x": 690.59, "y": 566.58}, {"t": 16.185, "type": "move", "x": 692.77, "y": 567.39}, {"t": 16.1933, "type": "move", "x": 694.65, "y": 568.08}, {"t": 16.2017, "type": "move", "x": 696.24, "y": 568.66}, {"t": 16.21, "type": "move", "x": 697.51, "y": 569.11}, {"t": 16.2183, "type": "move", "x": 698.49, "y": 569.46}, {"t": 16.2267, "type": "move", "x": 699.19, "y": 569.71}, {"t": 16.235, "type": "move", "x": 699.64, "y": 569.87}, {"t": 16.2433, "type": "move", "x": 699.89, "y": 569.96}, {"t": 16.2517, "type": "move", "x": 699.99, "y": 569.99}, {"t": 16.26, "type": "move", "x": 700.0, "y": 570.0}, {"t": 16.2683, "type": "move", "x": 699.98, "y": 569.98}, {"t": 16.2767, "type": "move", "x": 699.86, "y": 569.86}, {"t": 16.285, "type": "move", "x": 699.54, "y": 569.54}, {"t": 16.2933, "type": "move", "x": 698.94, "y": 568.93}, {"t": 16.3017, "type": "move", "x": 697.98, "y": 567.96}, {"t": 16.31, "type": "move", "x": 696.59, "y": 566.56}, {"t": 16.3183, "type": "move", "x": 694.72, "y": 564.67}, {"t": 16.3267, "type": "move", "x": 692.3, "y": 562.24}, {"t": 16.335, "type": "move", "x": 689.31, "y": 559.23}, {"t": 16.3433, "type": "move", "x": 685.7, "y": 555.59}, {"t": 16.3517, "type": "move", "x": 681.45, "y": 551.31}, {"t": 16.36, "type": "move", "x": 676.52, "y": 546.37}, {"t": 16.3683, "type": "move", "x": 670.91, "y": 540.74}, {"t": 16.3767, "type": "move", "x": 664.6, "y": 534.44}, {"t": 16.385, "type": "move", "x": 657.59, "y": 527.46}, {"t": 16.3933, "type": "move", "x": 649.87, "y": 519.81}, {"t": 16.4017, "type": "move", "x": 641.44, "y": 511.52}, {"t": 16.41, "type": "move", "x": 632.31, "y": 502.62}, {"t": 16.4183, "type": "move", "x": 622.49, "y": 493.14}, {"t": 16.4267, "type": "move", "x": 611.97, "y": 483.13}, {"t": 16.435, "type": "move", "x": 600.79, "y": 472.65}, {"t": 16.4433, "type": "move", "x": 588.95, "y": 461.74}, {"t": 16.4517, "type": "move", "x": 576.46, "y": 450.47}, {"t": 16.46, "type": "move", "x": 563.35, "y": 438.93}, {"t": 16.4683, "type": "move", "x": 549.63, "y": 427.18}, {"t": 16.4767, "type": "move", "x": 535.33, "y": 415.29}, {"t": 16.485, "type": "move", "x": 520.48, "y": 403.35}, {"t": 16.4933, "type": "move", "x": 505.1, "y": 391.44}, {"t": 16.5017, "type": "move", "x": 489.24, "y": 379.63}, {"t": 16.51, "type": "move", "x": 472.92, "y": 367.99}, {"t": 16.5183, "type": "move", "x": 456.2, "y": 356.58}, {"t": 16.5267, "type": "move", "x": 439.13, "y": 345.48}, {"t": 16.535, "type": "move", "x": 421.76, "y": 334.72}, {"t": 16.5433, "type": "move", "x": 404.15, "y": 324.35}, {"t": 16.5517, "type": "move", "x": 386.38, "y": 314.41}, {"t": 16.56, "type": "move", "x": 368.5, "y": 304.93}, {"t": 16.5683, "type": "move", "x": 350.6, "y": 295.91}, {"t": 16.5767, "type": "move", "x": 332.76, "y": 287.36}, {"t": 16.585, "type": "move", "x": 315.06, "y": 279.3}, {"t": 16.5933, "type": "move", "x": 297.58, "y": 271.71}, {"t": 16.6017, "type": "move", "x": 280.41, "y": 264.59}, {"t": 16.61, "type": "move", "x": 263.62, "y": 257.92}, {"t": 16.6183, "type": "move", "x": 247.3, "y": 251.69}, {"t": 16.6267, "type": "move", "x": 231.51, "y": 245.89}, {"t": 16.635, "type": "move", "x": 216.35, "y": 240.48}, {"t": 16.6433, "type": "move", "x": 201.86, "y": 235.47}, {"t": 16.6517, "type": "move", "x": 188.1, "y": 230.82}, {"t": 16.66, "type": "move", "x": 175.14, "y": 226.54}, {"t": 16.6683, "type": "move", "x": 163.01, "y": 222.6}, {"t": 16.6767, "type": "move", "x": 151.76, "y": 219.0}, {"t": 16.685, "type": "move", "x": 141.4, "y": 215.73}, {"t": 16.6933, "type": "move", "x": 131.95, "y": 212.77}, {"t": 16.7017, "type": "move", "x": 123.44, "y": 210.12}, {"t": 16.71, "type": "move", "x": 115.85, "y": 207.78}, {"t": 16.7183, "type": "move", "x": 109.18, "y": 205.72}, {"t": 16.7267, "type": "move", "x": 103.41, "y": 203.95}, {"t": 16.735, "type": "move", "x": 98.51, "y": 202.44}, {"t": 16.7433, "type": "move", "x": 94.45, "y": 201.2}, {"t": 16.7517, "type": "move", "x": 91.18, "y": 200.2}, {"t": 16.76, "type": "move", "x": 88.63, "y": 199.42}, {"t": 16.7683, "type": "move", "x": 86.74, "y": 198.84}, {"t": 16.7767, "type": "move", "x": 85.44, "y": 198.44}, {"t": 16.785, "type": "move", "x": 84.62, "y": 198.19}, {"t": 16.7933, "type": "move", "x": 84.19, "y": 198.06}, {"t": 16.8017, "type": "move", "x": 84.02, "y": 198.01}, {"t": 16.81, "type": "move", "x": 84.0, "y": 198.0}, {"t": 16.93, "type": "tap", "x": 84, "y": 198, "hold": 0.09}, {"t": 17.5383, "type": "move", "x": 84.02, "y": 198.01}, {"t": 17.5467, "type": "move", "x": 84.15, "y": 198.1}, {"t": 17.555, "type": "move", "x": 84.49, "y": 198.32}, {"t": 17.5633, "type": "move", "x": 85.13, "y": 198.75}, {"t": 17.5717, "type": "move", "x": 86.15, "y": 199.44}, {"t": 17.58, "type": "move", "x": 87.64, "y": 200.43}, {"t": 17.5883, "type": "move", "x": 89.65, "y": 201.77}, {"t": 17.5967, "type": "move", "x": 92.24, "y": 203.5}, {"t": 17.605, "type": "move", "x": 95.47, "y": 205.66}, {"t": 17.6133, "type": "move", "x": 99.38, "y": 208.27}, {"t": 17.6217, "type": "move", "x": 104.0, "y": 211.35}, {"t": 17.63, "type": "move", "x": 109.37, "y": 214.93}, {"t": 17.6383, "type": "move", "x": 115.5, "y": 219.01}, {"t": 17.6467, "type": "move", "x": 122.42, "y": 223.6}, {"t": 17.655, "type": "move", "x": 130.14, "y": 228.71}, {"t": 17.6633, "type": "move", "x": 138.66, "y": 234.33}, {"t": 17.6717, "type": "move", "x": 147.98, "y": 240.44}, {"t": 17.68, "type": "move", "x": 158.1, "y": 247.05}, {"t": 17.6883, "type": "move", "x": 169.02, "y": 254.12}, {"t": 17.6967, "type": "move", "x": 180.72, "y": 261.62}, {"t": 17.705, "type": "move", "x": 193.19, "y": 269.53}, {"t": 17.7133, "type": "move", "x": 206.42, "y": 277.8}, {"t": 17.7217, "type": "move", "x": 220.37, "y": 286.38}, {"t": 17.73, "type": "move", "x": 235.03, "y": 295.24}, {"t": 17.7383, "type": "move", "x": 250.38, "y": 304.3}, {"t": 17.7467, "type": "move", "x": 266.37, "y": 313.52}, {"t": 17.755, "type": "move", "x": 283.0, "y": 322.84}, {"t": 17.7633, "type": "move", "x": 300.21, "y": 332.18}, {"t": 17.7717, "type": "move", "x": 317.97, "y": 341.49}, {"t": 17.78, "type": "move", "x": 336.25, "y": 350.7}, {"t": 17.7883, "type": "move", "x": 355.0, "y": 359.76}, {"t": 17.7967, "type": "move", "x": 374.17, "y": 368.59}, {"t": 17.805, "type": "move", "x": 393.72, "y": 377.16}, {"t": 17.8133, "type": "move", "x": 413.6, "y": 385.41}, {"t": 17.8217, "type": "move", "x": 433.74, "y": 393.3}, {"t": 17.83, "type": "move", "x": 454.1, "y": 400.8}, {"t": 17.8383, "type": "move", "x": 474.61, "y": 407.88}, {"t": 17.8467, "type": "move", "x": 495.2, "y": 414.52}, {"t": 17.855, "type": "move", "x": 515.81, "y": 420.71}, {"t": 17.8633, "type": "move", "x": 536.37, "y": 426.45}, {"t": 17.8717, "type": "move", "x": 556.81, "y": 431.74}, {"t": 17.88, "type": "move", "x": 577.05, "y": 436.6}, {"t": 17.8883, "type": "move", "x": 597.04, "y": 441.03}, {"t": 17.8967, "type": "move", "x": 616.68, "y": 445.06}, {"t": 17.905, "type": "move", "x": 635.92, "y": 448.72}, {"t": 17.9133, "type": "move", "x": 654.68, "y": 452.03}, {"t": 17.9217, "type": "move", "x": 672.91, "y": 455.02}, {"t": 17.93, "type": "move", "x": 690.52, "y": 457.71}, {"t": 17.9383, "type": "move", "x": 707.48, "y": 460.13}, {"t": 17.9467, "type": "move", "x": 723.72, "y": 462.31}, {"t": 17.955, "type": "move", "x": 739.19, "y": 464.28}, {"t": 17.9633, "type": "move", "x": 753.85, "y": 466.05}, {"t": 17.9717, "type": "move", "x": 767.66, "y": 467.64}, {"t": 17.98, "type": "move", "x": 780.58, "y": 469.08}, {"t": 17.9883, "type": "move", "x": 792.6, "y": 470.37}, {"t": 17.9967, "type": "move", "x": 803.69, "y": 471.54}, {"t": 18.005, "type": "move", "x": 813.84, "y": 472.58}, {"t": 18.0133, "type": "move", "x": 823.05, "y": 473.5}, {"t": 18.0217, "type": "move", "x": 831.31, "y": 474.33}, {"t": 18.03, "type": "move", "x": 838.64, "y": 475.05}, {"t": 18.0383, "type": "move", "x": 845.06, "y": 475.68}, {"t": 18.0467, "type": "move", "x": 850.59, "y": 476.22}, {"t": 18.055, "type": "move", "x": 855.27, "y": 476.67}, {"t": 18.0633, "type": "move", "x": 859.14, "y": 477.05}, {"t": 18.0717, "type": "move", "x": 862.24, "y": 477.35}, {"t": 18.08, "type": "move", "x": 864.65, "y": 477.58}, {"t": 18.0883, "type": "move", "x": 866.43, "y": 477.75}, {"t": 18.0967, "type": "move", "x": 867.65, "y": 477.87}, {"t": 18.105, "type": "move", "x": 868.42, "y": 477.94}, {"t": 18.1133, "type": "move", "x": 868.82, "y": 477.98}, {"t": 18.1217, "type": "move", "x": 868.98, "y": 478.0}, {"t": 18.13, "type": "move", "x": 869.0, "y": 478.0}, {"t": 18.25, "type": "tap", "x": 869, "y": 478, "hold": 0.09}, {"t": 19.1583, "type": "move", "x": 868.98, "y": 477.98}, {"t": 19.1667, "type": "move", "x": 868.87, "y": 477.88}, {"t": 19.175, "type": "move", "x": 868.58, "y": 477.6}, {"t": 19.1833, "type": "move", "x": 868.04, "y": 477.07}, {"t": 19.1917, "type": "move", "x": 867.18, "y": 476.24}, {"t": 19.2, "type": "move", "x": 865.95, "y": 475.05}, {"t": 19.2083, "type": "move", "x": 864.3, "y": 473.46}, {"t": 19.2167, "type": "move", "x": 862.2, "y": 471.43}, {"t": 19.225, "type": "move", "x": 859.62, "y": 468.93}, {"t": 19.2333, "type": "move", "x": 856.53, "y": 465.95}, {"t": 19.2417, "type": "move", "x": 852.92, "y": 462.48}, {"t": 19.25, "type": "move", "x": 848.77, "y": 458.52}, {"t": 19.2583, "type": "move", "x": 844.1, "y": 454.08}, {"t": 19.2667, "type": "move", "x": 838.89, "y": 449.16}, {"t": 19.275, "type": "move", "x": 833.16, "y": 443.81}, {"t": 19.2833, "type": "move", "x": 826.9, "y": 438.05}, {"t": 19.2917, "type": "move", "x": 820.14, "y": 431.93}, {"t": 19.3, "type": "move", "x": 812.87, "y": 425.5}, {"t": 19.3083, "type": "move", "x": 805.13, "y": 418.82}, {"t": 19.3167, "type": "move", "x": 796.92, "y": 411.94}, {"t": 19.325, "type": "move", "x": 788.27, "y": 404.95}, {"t": 19.3333, "type": "move", "x": 779.2, "y": 397.91}, {"t": 19.3417, "type": "move", "x": 769.74, "y": 390.89}, {"t": 19.35, "type": "move", "x": 759.92, "y": 383.96}, {"t": 19.3583, "type": "move", "x": 749.78, "y": 377.18}, {"t": 19.3667, "type": "move", "x": 739.37, "y": 370.6}, {"t": 19.375, "type": "move", "x": 728.74, "y": 364.28}, {"t": 19.3833, "type": "move", "x": 717.94, "y": 358.25}, {"t": 19.3917, "type": "move", "x": 707.02, "y": 352.55}, {"t": 19.4, "type": "move", "x": 696.07, "y": 347.18}, {"t": 19.4083, "type": "move", "x": 685.15, "y": 342.17}, {"t": 19.4167, "type": "move", "x": 674.33, "y": 337.51}, {"t": 19.425, "type": "move", "x": 663.69, "y": 333.19}, {"t": 19.4333, "type": "move", "x": 653.3, "y": 329.22}, {"t": 19.4417, "type": "move", "x": 643.24, "y": 325.56}, {"t": 19.45, "type": "move", "x": 633.58, "y": 322.21}, {"t": 19.4583, "type": "move", "x": 624.37, "y": 319.16}, {"t": 19.4667, "type": "move", "x": 615.68, "y": 316.37}, {"t": 19.475, "type": "move", "x": 607.56, "y": 313.85}, {"t": 19.4833, "type": "move", "x": 600.05, "y": 311.58}, {"t": 19.4917, "type": "move", "x": 593.19, "y": 309.54}, {"t": 19.5, "type": "move", "x": 587.0, "y": 307.72}, {"t": 19.5083, "type": "move", "x": 581.49, "y": 306.13}, {"t": 19.5167, "type": "move", "x": 576.68, "y": 304.75}, {"t": 19.525, "type": "move", "x": 572.55, "y": 303.57}, {"t": 19.5333, "type": "move", "x": 569.1, "y": 302.58}, {"t": 19.5417, "type": "move", "x": 566.28, "y": 301.78}, {"t": 19.55, "type": "move", "x": 564.08, "y": 301.16}, {"t": 19.5583, "type": "move", "x": 562.43, "y": 300.69}, {"t": 19.5667, "type": "move", "x": 561.28, "y": 300.36}, {"t": 19.575, "type": "move", "x": 560.56, "y": 300.16}, {"t": 19.5833, "type": "move", "x": 560.17, "y": 300.05}, {"t": 19.5917, "type": "move", "x": 560.02, "y": 300.01}, {"t": 19.6, "type": "move", "x": 560.0, "y": 300.0}, {"t": 19.72, "type": "tap", "x": 560, "y": 300, "hold": 0.09}, {"t": 20.5283, "type": "move", "x": 560.01, "y": 300.0}, {"t": 20.5367, "type": "move", "x": 560.07, "y": 300.0}, {"t": 20.545, "type": "move", "x": 560.24, "y": 300.01}, {"t": 20.5533, "type": "move", "x": 560.55, "y": 300.02}, {"t": 20.5617, "type": "move", "x": 561.05, "y": 300.05}, {"t": 20.57, "type": "move", "x": 561.77, "y": 300.08}, {"t": 20.5783, "type": "move", "x": 562.75, "y": 300.12}, {"t": 20.5867, "type": "move", "x": 564.01, "y": 300.17}, {"t": 20.595, "type": "move", "x": 565.59, "y": 300.24}, {"t": 20.6033, "type": "move", "x": 567.49, "y": 300.33}, {"t": 20.6117, "type": "move", "x": 569.74, "y": 300.42}, {"t": 20.62, "type": "move", "x": 572.35, "y": 300.53}, {"t": 20.6283, "type": "move", "x": 575.34, "y": 300.66}, {"t": 20.6367, "type": "move", "x": 578.7, "y": 300.8}, {"t": 20.645, "type": "move", "x": 582.45, "y": 300.94}, {"t": 20.6533, "type": "move", "x": 586.59, "y": 301.1}, {"t": 20.6617, "type": "move", "x": 591.1, "y": 301.26}, {"t": 20.67, "type": "move", "x": 596.0, "y": 301.42}, {"t": 20.6783, "type": "move", "x": 601.27, "y": 301.58}, {"t": 20.6867, "type": "move", "x": 606.91, "y": 301.72}, {"t": 20.695, "type": "move", "x": 612.89, "y": 301.84}, {"t": 20.7033, "type": "move", "x": 619.21, "y": 301.92}, {"t": 20.7117, "type": "move", "x": 625.86, "y": 301.96}, {"t": 20.72, "type": "move", "x": 632.8, "y": 301.95}, {"t": 20.7283, "type": "move", "x": 640.03, "y": 301.87}, {"t": 20.7367, "type": "move", "x": 647.51, "y": 301.7}, {"t": 20.745, "type": "move", "x": 655.23, "y": 301.43}, {"t": 20.7533, "type": "move", "x": 663.16, "y": 301.05}, {"t": 20.7617, "type": "move", "x": 671.28, "y": 300.54}, {"t": 20.77, "type": "move", "x": 679.55, "y": 299.89}, {"t": 20.7783, "type": "move", "x": 687.95, "y": 299.09}, {"t": 20.7867, "type": "move", "x": 696.46, "y": 298.12}, {"t": 20.795, "type": "move", "x": 705.04, "y": 296.98}, {"t": 20.8033, "type": "move", "x": 713.66, "y": 295.66}, {"t": 20.8117, "type": "move", "x": 722.31, "y": 294.16}, {"t": 20.82, "type": "move", "x": 730.94, "y": 292.48}, {"t": 20.8283, "type": "move", "x": 739.54, "y": 290.62}, {"t": 20.8367, "type": "move", "x": 748.07, "y": 288.59}, {"t": 20.845, "type": "move", "x": 756.52, "y": 286.41}, {"t": 20.8533, "type": "move", "x": 764.85, "y": 284.07}, {"t": 20.8617, "type": "move", "x": 773.05, "y": 281.61}, {"t": 20.87, "type": "move", "x": 781.09, "y": 279.03}, {"t": 20.8783, "type": "move", "x": 788.95, "y": 276.37}, {"t": 20.8867, "type": "move", "x": 796.61, "y": 273.64}, {"t": 20.895, "type": "move", "x": 804.05, "y": 270.86}, {"t": 20.9033, "type": "move", "x": 811.25, "y": 268.06}, {"t": 20.9117, "type": "move", "x": 818.19, "y": 265.27}, {"t": 20.92, "type": "move", "x": 824.86, "y": 262.49}, {"t": 20.9283, "type": "move", "x": 831.25, "y": 259.77}, {"t": 20.9367, "type": "move", "x": 837.34, "y": 257.11}, {"t": 20.945, "type": "move", "x": 843.12, "y": 254.54}, {"t": 20.9533, "type": "move", "x": 848.57, "y": 252.07}, {"t": 20.9617, "type": "move", "x": 853.69, "y": 249.72}, {"t": 20.97, "type": "move", "x": 858.47, "y": 247.5}, {"t": 20.9783, "type": "move", "x": 862.91, "y": 245.42}, {"t": 20.9867, "type": "move", "x": 867.0, "y": 243.49}, {"t": 20.995, "type": "move", "x": 870.74, "y": 241.72}, {"t": 21.0033, "type": "move", "x": 874.13, "y": 240.1}, {"t": 21.0117, "type": "move", "x": 877.16, "y": 238.65}, {"t": 21.02, "type": "move", "x": 879.86, "y": 237.36}, {"t": 21.0283, "type": "move", "x": 882.21, "y": 236.23}, {"t": 21.0367, "type": "move", "x": 884.24, "y": 235.25}, {"t": 21.045, "type": "move", "x": 885.96, "y": 234.43}, {"t": 21.0533, "type": "move", "x": 887.38, "y": 233.74}, {"t": 21.0617, "type": "move", "x": 888.52, "y": 233.19}, {"t": 21.07, "type": "move", "x": 889.4, "y": 232.77}, {"t": 21.0783, "type": "move", "x": 890.06, "y": 232.46}, {"t": 21.0867, "type": "move", "x": 890.51, "y": 232.24}, {"t": 21.095, "type": "move", "x": 890.79, "y": 232.1}, {"t": 21.1033, "type": "move", "x": 890.94, "y": 232.03}, {"t": 21.1117, "type": "move", "x": 890.99, "y": 232.0}, {"t": 21.12, "type": "move", "x": 891.0, "y": 232.0}, {"t": 21.24, "type": "tap", "x": 891, "y": 232, "hold": 0.09}, {"t": 22.7483, "type": "move", "x": 891.0, "y": 232.0}, {"t": 22.7567, "type": "move", "x": 891.01, "y": 231.97}, {"t": 22.765, "type": "move", "x": 891.03, "y": 231.9}, {"t": 22.7733, "type": "move", "x": 891.06, "y": 231.76}, {"t": 22.7817, "type": "move", "x": 891.11, "y": 231.55}, {"t": 22.79, "type": "move", "x": 891.19, "y": 231.24}, {"t": 22.7983, "type": "move", "x": 891.29, "y": 230.83}, {"t": 22.8067, "type": "move", "x": 891.43, "y": 230.3}, {"t": 22.815, "type": "move", "x": 891.59, "y": 229.66}, {"t": 22.8233, "type": "move", "x": 891.78, "y": 228.89}, {"t": 22.8317, "type": "move", "x": 892.0, "y": 227.99}, {"t": 22.84, "type": "move", "x": 892.26, "y": 226.96}, {"t": 22.8483, "type": "move", "x": 892.54, "y": 225.8}, {"t": 22.8567, "type": "move", "x": 892.84, "y": 224.51}, {"t": 22.865, "type": "move", "x": 893.17, "y": 223.09}, {"t": 22.8733, "type": "move", "x": 893.52, "y": 221.56}, {"t": 22.8817, "type": "move", "x": 893.87, "y": 219.91}, {"t": 22.89, "type": "move", "x": 894.23, "y": 218.15}, {"t": 22.8983, "type": "move", "x": 894.59, "y": 216.29}, {"t": 22.9067, "type": "move", "x": 894.93, "y": 214.34}, {"t": 22.915, "type": "move", "x": 895.26, "y": 212.3}, {"t": 22.9233, "type": "move", "x": 895.55, "y": 210.2}, {"t": 22.9317, "type": "move", "x": 895.8, "y": 208.03}, {"t": 22.94, "type": "move", "x": 896.0, "y": 205.82}, {"t": 22.9483, "type": "move", "x": 896.16, "y": 203.57}, {"t": 22.9567, "type": "move", "x": 896.25, "y": 201.29}, {"t": 22.965, "type": "move", "x": 896.28, "y": 199.0}, {"t": 22.9733, "type": "move", "x": 896.25, "y": 196.71}, {"t": 22.9817, "type": "move", "x": 896.16, "y": 194.43}, {"t": 22.99, "type": "move", "x": 896.0, "y": 192.18}, {"t": 22.9983, "type": "move", "x": 895.8, "y": 189.97}, {"t": 23.0067, "type": "move", "x": 895.55, "y": 187.8}, {"t": 23.015, "type": "move", "x": 895.26, "y": 185.7}, {"t": 23.0233, "type": "move", "x": 894.93, "y": 183.66}, {"t": 23.0317, "type": "move", "x": 894.59, "y": 181.71}, {"t": 23.04, "type": "move", "x": 894.23, "y": 179.85}, {"t": 23.0483, "type": "move", "x": 893.87, "y": 178.09}, {"t": 23.0567, "type": "move", "x": 893.52, "y": 176.44}, {"t": 23.065, "type": "move", "x": 893.17, "y": 174.91}, {"t": 23.0733, "type": "move", "x": 892.84, "y": 173.49}, {"t": 23.0817, "type": "move", "x": 892.54, "y": 172.2}, {"t": 23.09, "type": "move", "x": 892.26, "y": 171.04}, {"t": 23.0983, "type": "move", "x": 892.0, "y": 170.01}, {"t": 23.1067, "type": "move", "x": 891.78, "y": 169.11}, {"t": 23.115, "type": "move", "x": 891.59, "y": 168.34}, {"t": 23.1233, "type": "move", "x": 891.43, "y": 167.7}, {"t": 23.1317, "type": "move", "x": 891.29, "y": 167.17}, {"t": 23.14, "type": "move", "x": 891.19, "y": 166.76}, {"t": 23.1483, "type": "move", "x": 891.11, "y": 166.45}, {"t": 23.1567, "type": "move", "x": 891.06, "y": 166.24}, {"t": 23.165, "type": "move", "x": 891.03, "y": 166.1}, {"t": 23.1733, "type": "move", "x": 891.01, "y": 166.03}, {"t": 23.1817, "type": "move", "x": 891.0, "y": 166.0}, {"t": 23.19, "type": "move", "x": 891.0, "y": 166.0}, {"t": 23.31, "type": "tap", "x": 891, "y": 166, "hold": 0.09}, {"t": 25.2183, "type": "move", "x": 891.0, "y": 166.0}, {"t": 25.2267, "type": "move", "x": 891.0, "y": 166.0}, {"t": 25.235, "type": "move", "x": 891.0, "y": 166.0}, {"t": 25.2433, "type": "move", "x": 891.0, "y": 166.0}, {"t": 25.2517, "type": "move", "x": 891.0, "y": 166.0}, {"t": 25.26, "type": "move", "x": 891.0, "y": 166.0}, {"t": 25.2683, "type": "move", "x": 891.0, "y": 166.0}, {"t": 25.2767, "type": "move", "x": 891.0, "y": 166.0}, {"t": 25.285, "type": "move", "x": 891.0, "y": 166.0}, {"t": 25.2933, "type": "move", "x": 891.0, "y": 166.0}, {"t": 25.3017, "type": "move", "x": 891.0, "y": 166.0}, {"t": 25.31, "type": "move", "x": 891.0, "y": 166.0}, {"t": 25.3183, "type": "move", "x": 891.0, "y": 166.0}, {"t": 25.3267, "type": "move", "x": 891.0, "y": 166.0}, {"t": 25.335, "type": "move", "x": 891.0, "y": 166.0}, {"t": 25.3433, "type": "move", "x": 891.0, "y": 166.0}, {"t": 25.3517, "type": "move", "x": 891.0, "y": 166.0}, {"t": 25.36, "type": "move", "x": 891.0, "y": 166.0}, {"t": 25.3683, "type": "move", "x": 891.0, "y": 166.0}, {"t": 25.3767, "type": "move", "x": 891.0, "y": 166.0}, {"t": 25.385, "type": "move", "x": 891.0, "y": 166.0}, {"t": 25.3933, "type": "move", "x": 891.0, "y": 166.0}, {"t": 25.4017, "type": "move", "x": 891.0, "y": 166.0}, {"t": 25.41, "type": "move", "x": 891.0, "y": 166.0}, {"t": 25.53, "type": "tap", "x": 891, "y": 166, "hold": 0.09}, {"t": 25.9383, "type": "move", "x": 890.97, "y": 166.0}, {"t": 25.9467, "type": "move", "x": 890.78, "y": 165.96}, {"t": 25.955, "type": "move", "x": 890.27, "y": 165.87}, {"t": 25.9633, "type": "move", "x": 889.32, "y": 165.71}, {"t": 25.9717, "type": "move", "x": 887.79, "y": 165.45}, {"t": 25.98, "type": "move", "x": 885.58, "y": 165.07}, {"t": 25.9883, "type": "move", "x": 882.6, "y": 164.56}, {"t": 25.9967, "type": "move", "x": 878.77, "y": 163.9}, {"t": 26.005, "type": "move", "x": 874.01, "y": 163.08}, {"t": 26.0133, "type": "move", "x": 868.28, "y": 162.1}, {"t": 26.0217, "type": "move", "x": 861.52, "y": 160.95}, {"t": 26.03, "type": "move", "x": 853.7, "y": 159.62}, {"t": 26.0383, "type": "move", "x": 844.81, "y": 158.11}, {"t": 26.0467, "type": "move", "x": 834.82, "y": 156.44}, {"t": 26.055, "type": "move", "x": 823.73, "y": 154.61}, {"t": 26.0633, "type": "move", "x": 811.55, "y": 152.63}, {"t": 26.0717, "type": "move", "x": 798.29, "y": 150.52}, {"t": 26.08, "type": "move", "x": 783.97, "y": 148.3}, {"t": 26.0883, "type": "move", "x": 768.64, "y": 146.01}, {"t": 26.0967, "type": "move", "x": 752.32, "y": 143.68}, {"t": 26.105, "type": "move", "x": 735.06, "y": 141.35}, {"t": 26.1133, "type": "move", "x": 716.91, "y": 139.07}, {"t": 26.1217, "type": "move", "x": 697.94, "y": 136.89}, {"t": 26.13, "type": "move", "x": 678.2, "y": 134.85}, {"t": 26.1383, "type": "move", "x": 657.76, "y": 133.02}, {"t": 26.1467, "type": "move", "x": 636.7, "y": 131.45}, {"t": 26.155, "type": "move", "x": 615.09, "y": 130.2}, {"t": 26.1633, "type": "move", "x": 593.02, "y": 129.32}, {"t": 26.1717, "type": "move", "x": 570.56, "y": 128.86}, {"t": 26.18, "type": "move", "x": 547.79, "y": 128.84}, {"t": 26.1883, "type": "move", "x": 524.81, "y": 129.32}, {"t": 26.1967, "type": "move", "x": 501.7, "y": 130.3}, {"t": 26.205, "type": "move", "x": 478.54, "y": 131.8}, {"t": 26.2133, "type": "move", "x": 455.42, "y": 133.82}, {"t": 26.2217, "type": "move", "x": 432.42, "y": 136.35}, {"t": 26.23, "type": "move", "x": 409.64, "y": 139.35}, {"t": 26.2383, "type": "move", "x": 387.14, "y": 142.81}, {"t": 26.2467, "type": "move", "x": 365.0, "y": 146.67}, {"t": 26.255, "type": "move", "x": 343.32, "y": 150.88}, {"t": 26.2633, "type": "move", "x": 322.15, "y": 155.38}, {"t": 26.2717, "type": "move", "x": 301.57, "y": 160.12}, {"t": 26.28, "type": "move", "x": 281.64, "y": 165.02}, {"t": 26.2883, "type": "move", "x": 262.44, "y": 170.02}, {"t": 26.2967, "type": "move", "x": 244.01, "y": 175.05}, {"t": 26.305, "type": "move", "x": 226.42, "y": 180.05}, {"t": 26.3133, "type": "move", "x": 209.71, "y": 184.96}, {"t": 26.3217, "type": "move", "x": 193.93, "y": 189.73}, {"t": 26.33, "type": "move", "x": 179.12, "y": 194.32}, {"t": 26.3383, "type": "move", "x": 165.3, "y": 198.67}, {"t": 26.3467, "type": "move", "x": 152.52, "y": 202.76}, {"t": 26.355, "type": "move", "x": 140.78, "y": 206.56}, {"t": 26.3633, "type": "move", "x": 130.09, "y": 210.05}, {"t": 26.3717, "type": "move", "x": 120.47, "y": 213.22}, {"t": 26.38, "type": "move", "x": 111.9, "y": 216.05}, {"t": 26.3883, "type": "move", "x": 104.38, "y": 218.54}, {"t": 26.3967, "type": "move", "x": 97.87, "y": 220.71}, {"t": 26.405, "type": "move", "x": 92.35, "y": 222.55}, {"t": 26.4133, "type": "move", "x": 87.77, "y": 224.07}, {"t": 26.4217, "type": "move", "x": 84.08, "y": 225.3}, {"t": 26.43, "type": "move", "x": 81.22, "y": 226.26}, {"t": 26.4383, "type": "move", "x": 79.09, "y": 226.97}, {"t": 26.4467, "type": "move", "x": 77.62, "y": 227.46}, {"t": 26.455, "type": "move", "x": 76.7, "y": 227.77}, {"t": 26.4633, "type": "move", "x": 76.21, "y": 227.93}, {"t": 26.4717, "type": "move", "x": 76.03, "y": 227.99}, {"t": 26.48, "type": "move", "x": 76.0, "y": 228.0}, {"t": 26.6, "type": "tap", "x": 76, "y": 228, "hold": 0.09}, {"t": 27.2083, "type": "move", "x": 76.02, "y": 228.0}, {"t": 27.2167, "type": "move", "x": 76.17, "y": 228.03}, {"t": 27.225, "type": "move", "x": 76.56, "y": 228.1}, {"t": 27.2333, "type": "move", "x": 77.31, "y": 228.22}, {"t": 27.2417, "type": "move", "x": 78.5, "y": 228.43}, {"t": 27.25, "type": "move", "x": 80.23, "y": 228.73}, {"t": 27.2583, "type": "move", "x": 82.56, "y": 229.13}, {"t": 27.2667, "type": "move", "x": 85.58, "y": 229.65}, {"t": 27.275, "type": "move", "x": 89.33, "y": 230.29}, {"t": 27.2833, "type": "move", "x": 93.87, "y": 231.07}, {"t": 27.2917, "type": "move", "x": 99.25, "y": 231.99}, {"t": 27.3, "type": "move", "x": 105.48, "y": 233.05}, {"t": 27.3083, "type": "move", "x": 112.6, "y": 234.27}, {"t": 27.3167, "type": "move", "x": 120.63, "y": 235.62}, {"t": 27.325, "type": "move", "x": 129.58, "y": 237.13}, {"t": 27.3333, "type": "move", "x": 139.45, "y": 238.76}, {"t": 27.3417, "type": "move", "x": 150.25, "y": 240.53}, {"t": 27.35, "type": "move", "x": 161.95, "y": 242.41}, {"t": 27.3583, "type": "move", "x": 174.55, "y": 244.39}, {"t": 27.3667, "type": "move", "x": 188.03, "y": 246.45}, {"t": 27.375, "type": "move", "x": 202.35, "y": 248.57}, {"t": 27.3833, "type": "move", "x": 217.5, "y": 250.71}, {"t": 27.3917, "type": "move", "x": 233.42, "y": 252.84}, {"t": 27.4, "type": "move", "x": 250.09, "y": 254.93}, {"t": 27.4083, "type": "move", "x": 267.45, "y": 256.94}, {"t": 27.4167, "type": "move", "x": 285.46, "y": 258.82}, {"t": 27.425, "type": "move", "x": 304.07, "y": 260.54}, {"t": 27.4333, "type": "move", "x": 323.21, "y": 262.06}, {"t": 27.4417, "type": "move", "x": 342.84, "y": 263.32}, {"t": 27.45, "type": "move", "x": 362.89, "y": 264.29}, {"t": 27.4583, "type": "move", "x": 383.3, "y": 264.93}, {"t": 27.4667, "type": "move", "x": 404.0, "y": 265.2}, {"t": 27.475, "type": "move", "x": 424.94, "y": 265.09}, {"t": 27.4833, "type": "move", "x": 446.03, "y": 264.56}, {"t": 27.4917, "type": "move", "x": 467.23, "y": 263.6}, {"t": 27.5, "type": "move", "x": 488.46, "y": 262.2}, {"t": 27.5083, "type": "move", "x": 509.66, "y": 260.37}, {"t": 27.5167, "type": "move", "x": 530.75, "y": 258.11}, {"t": 27.525, "type": "move", "x": 551.69, "y": 255.44}, {"t": 27.5333, "type": "move", "x": 572.4, "y": 252.39}, {"t": 27.5417, "type": "move", "x": 592.82, "y": 248.99}, {"t": 27.55, "type": "move", "x": 612.9, "y": 245.27}, {"t": 27.5583, "type": "move", "x": 632.57, "y": 241.28}, {"t": 27.5667, "type": "move", "x": 651.78, "y": 237.06}, {"t": 27.575, "type": "move", "x": 670.48, "y": 232.67}, {"t": 27.5833, "type": "move", "x": 688.61, "y": 228.15}, {"t": 27.5917, "type": "move", "x": 706.13, "y": 223.57}, {"t": 27.6, "type": "move", "x": 722.99, "y": 218.95}, {"t": 27.6083, "type": "move", "x": 739.15, "y": 214.37}, {"t": 27.6167, "type": "move", "x": 754.57, "y": 209.85}, {"t": 27.625, "type": "move", "x": 769.21, "y": 205.45}, {"t": 27.6333, "type": "move", "x": 783.05, "y": 201.19}, {"t": 27.6417, "type": "move", "x": 796.06, "y": 197.11}, {"t": 27.65, "type": "move", "x": 808.22, "y": 193.25}, {"t": 27.6583, "type": "move", "x": 819.5, "y": 189.62}, {"t": 27.6667, "type": "move", "x": 829.9, "y": 186.24}, {"t": 27.675, "type": "move", "x": 839.41, "y": 183.13}, {"t": 27.6833, "type": "move", "x": 848.03, "y": 180.29}, {"t": 27.6917, "type": "move", "x": 855.77, "y": 177.73}, {"t": 27.7, "type": "move", "x": 862.62, "y": 175.46}, {"t": 27.7083, "type": "move", "x": 868.63, "y": 173.46}, {"t": 27.7167, "type": "move", "x": 873.8, "y": 171.74}, {"t": 27.725, "type": "move", "x": 878.17, "y": 170.28}, {"t": 27.7333, "type": "move", "x": 881.78, "y": 169.08}, {"t": 27.7417, "type": "move", "x": 884.68, "y": 168.11}, {"t": 27.75, "type": "move", "x": 886.93, "y": 167.36}, {"t": 27.7583, "type": "move", "x": 888.59, "y": 166.8}, {"t": 27.7667, "type": "move", "x": 889.74, "y": 166.42}, {"t": 27.775, "type": "move", "x": 890.46, "y": 166.18}, {"t": 27.7833, "type": "move", "x": 890.84, "y": 166.05}, {"t": 27.7917, "type": "move", "x": 890.98, "y": 166.01}, {"t": 27.8, "type": "move", "x": 891.0, "y": 166.0}, {"t": 27.92, "type": "tap", "x": 891, "y": 166, "hold": 0.09}, {"t": 29.6283, "type": "move", "x": 891.0, "y": 166.01}, {"t": 29.6367, "type": "move", "x": 890.98, "y": 166.05}, {"t": 29.645, "type": "move", "x": 890.94, "y": 166.15}, {"t": 29.6533, "type": "move", "x": 890.86, "y": 166.35}, {"t": 29.6617, "type": "move", "x": 890.74, "y": 166.66}, {"t": 29.67, "type": "move", "x": 890.56, "y": 167.12}, {"t": 29.6783, "type": "move", "x": 890.31, "y": 167.73}, {"t": 29.6867, "type": "move", "x": 890.0, "y": 168.51}, {"t": 29.695, "type": "move", "x": 889.62, "y": 169.47}, {"t": 29.7033, "type": "move", "x": 889.16, "y": 170.63}, {"t": 29.7117, "type": "move", "x": 888.62, "y": 171.99}, {"t": 29.72, "type": "move", "x": 888.0, "y": 173.56}, {"t": 29.7283, "type": "move", "x": 887.31, "y": 175.33}, {"t": 29.7367, "type": "move", "x": 886.53, "y": 177.32}, {"t": 29.745, "type": "move", "x": 885.69, "y": 179.51}, {"t": 29.7533, "type": "move", "x": 884.77, "y": 181.91}, {"t": 29.7617, "type": "move", "x": 883.8, "y": 184.51}, {"t": 29.77, "type": "move", "x": 882.77, "y": 187.31}, {"t": 29.7783, "type": "move", "x": 881.7, "y": 190.29}, {"t": 29.7867, "type": "move", "x": 880.61, "y": 193.45}, {"t": 29.795, "type": "move", "x": 879.49, "y": 196.78}, {"t": 29.8033, "type": "move", "x": 878.38, "y": 200.26}, {"t": 29.8117, "type": "move", "x": 877.28, "y": 203.89}, {"t": 29.82, "type": "move", "x": 876.21, "y": 207.64}, {"t": 29.8283, "type": "move", "x": 875.19, "y": 211.52}, {"t": 29.8367, "type": "move", "x": 874.23, "y": 215.49}, {"t": 29.845, "type": "move", "x": 873.34, "y": 219.55}, {"t": 29.8533, "type": "move", "x": 872.53, "y": 223.67}, {"t": 29.8617, "type": "move", "x": 871.81, "y": 227.85}, {"t": 29.87, "type": "move", "x": 871.2, "y": 232.06}, {"t": 29.8783, "type": "move", "x": 870.69, "y": 236.28}, {"t": 29.8867, "type": "move", "x": 870.28, "y": 240.5}, {"t": 29.895, "type": "move", "x": 869.98, "y": 244.69}, {"t": 29.9033, "type": "move", "x": 869.78, "y": 248.84}, {"t": 29.9117, "type": "move", "x": 869.67, "y": 252.93}, {"t": 29.92, "type": "move", "x": 869.64, "y": 256.94}, {"t": 29.9283, "type": "move", "x": 869.69, "y": 260.84}, {"t": 29.9367, "type": "move", "x": 869.8, "y": 264.63}, {"t": 29.945, "type": "move", "x": 869.96, "y": 268.28}, {"t": 29.9533, "type": "move", "x": 870.16, "y": 271.78}, {"t": 29.9617, "type": "move", "x": 870.39, "y": 275.12}, {"t": 29.97, "type": "move", "x": 870.64, "y": 278.28}, {"t": 29.9783, "type": "move", "x": 870.9, "y": 281.24}, {"t": 29.9867, "type": "move", "x": 871.16, "y": 284.01}, {"t": 29.995, "type": "move", "x": 871.41, "y": 286.57}, {"t": 30.0033, "type": "move", "x": 871.65, "y": 288.9}, {"t": 30.0117, "type": "move", "x": 871.88, "y": 291.02}, {"t": 30.02, "type": "move", "x": 872.09, "y": 292.92}, {"t": 30.0283, "type": "move", "x": 872.27, "y": 294.59}, {"t": 30.0367, "type": "move", "x": 872.44, "y": 296.05}, {"t": 30.045, "type": "move", "x": 872.58, "y": 297.29}, {"t": 30.0533, "type": "move", "x": 872.69, "y": 298.32}, {"t": 30.0617, "type": "move", "x": 872.79, "y": 299.15}, {"t": 30.07, "type": "move", "x": 872.86, "y": 299.81}, {"t": 30.0783, "type": "move", "x": 872.92, "y": 300.29}, {"t": 30.0867, "type": "move", "x": 872.96, "y": 300.63}, {"t": 30.095, "type": "move", "x": 872.98, "y": 300.84}, {"t": 30.1033, "type": "move", "x": 872.99, "y": 300.95}, {"t": 30.1117, "type": "move", "x": 873.0, "y": 300.99}, {"t": 30.12, "type": "move", "x": 873.0, "y": 301.0}, {"t": 30.24, "type": "tap", "x": 873, "y": 301, "hold": 0.09}, {"t": 32.1483, "type": "move", "x": 872.97, "y": 300.99}, {"t": 32.1567, "type": "move", "x": 872.8, "y": 300.9}, {"t": 32.165, "type": "move", "x": 872.35, "y": 300.66}, {"t": 32.1733, "type": "move", "x": 871.49, "y": 300.21}, {"t": 32.1817, "type": "move", "x": 870.13, "y": 299.48}, {"t": 32.19, "type": "move", "x": 868.15, "y": 298.44}, {"t": 32.1983, "type": "move", "x": 865.49, "y": 297.04}, {"t": 32.2067, "type": "move", "x": 862.06, "y": 295.23}, {"t": 32.215, "type": "move", "x": 857.81, "y": 292.99}, {"t": 32.2233, "type": "move", "x": 852.69, "y": 290.29}, {"t": 32.2317, "type": "move", "x": 846.64, "y": 287.11}, {"t": 32.24, "type": "move", "x": 839.65, "y": 283.44}, {"t": 32.2483, "type": "move", "x": 831.69, "y": 279.26}, {"t": 32.2567, "type": "move", "x": 822.74, "y": 274.59}, {"t": 32.265, "type": "move", "x": 812.81, "y": 269.43}, {"t": 32.2733, "type": "move", "x": 801.88, "y": 263.79}, {"t": 32.2817, "type": "move", "x": 789.98, "y": 257.7}, {"t": 32.29, "type": "move", "x": 777.11, "y": 251.18}, {"t": 32.2983, "type": "move", "x": 763.29, "y": 244.28}, {"t": 32.3067, "type": "move", "x": 748.55, "y": 237.03}, {"t": 32.315, "type": "move", "x": 732.93, "y": 229.49}, {"t": 32.3233, "type": "move", "x": 716.45, "y": 221.73}, {"t": 32.3317, "type": "move", "x": 699.15, "y": 213.8}, {"t": 32.34, "type": "move", "x": 681.09, "y": 205.77}, {"t": 32.3483, "type": "move", "x": 662.3, "y": 197.73}, {"t": 32.3567, "type": "move", "x": 642.83, "y": 189.74}, {"t": 32.365, "type": "move", "x": 622.76, "y": 181.88}, {"t": 32.3733, "type": "move", "x": 602.12, "y": 174.23}, {"t": 32.3817, "type": "move", "x": 581.0, "y": 166.85}, {"t": 32.39, "type": "move", "x": 559.44, "y": 159.81}, {"t": 32.3983, "type": "move", "x": 537.53, "y": 153.16}, {"t": 32.4067, "type": "move", "x": 515.34, "y": 146.95}, {"t": 32.415, "type": "move", "x": 492.94, "y": 141.22}, {"t": 32.4233, "type": "move", "x": 470.42, "y": 135.99}, {"t": 32.4317, "type": "move", "x": 447.86, "y": 131.28}, {"t": 32.44, "type": "move", "x": 425.35, "y": 127.09}, {"t": 32.4483, "type": "move", "x": 402.98, "y": 123.42}, {"t": 32.4567, "type": "move", "x": 380.82, "y": 120.23}, {"t": 32.465, "type": "move", "x": 358.98, "y": 117.52}, {"t": 32.4733, "type": "move", "x": 337.54, "y": 115.25}, {"t": 32.4817, "type": "move", "x": 316.59, "y": 113.38}, {"t": 32.49, "type": "move", "x": 296.21, "y": 111.87}, {"t": 32.4983, "type": "move", "x": 276.47, "y": 110.67}, {"t": 32.5067, "type": "move", "x": 257.47, "y": 109.74}, {"t": 32.515, "type": "move", "x": 239.27, "y": 109.04}, {"t": 32.5233, "type": "move", "x": 221.92, "y": 108.54}, {"t": 32.5317, "type": "move", "x": 205.51, "y": 108.18}, {"t": 32.54, "type": "move", "x": 190.06, "y": 107.95}, {"t": 32.5483, "type": "move", "x": 175.63, "y": 107.8}, {"t": 32.5567, "type": "move", "x": 162.26, "y": 107.73}, {"t": 32.565, "type": "move", "x": 149.97, "y": 107.7}, {"t": 32.5733, "type": "move", "x": 138.77, "y": 107.71}, {"t": 32.5817, "type": "move", "x": 128.68, "y": 107.73}, {"t": 32.59, "type": "move", "x": 119.69, "y": 107.77}, {"t": 32.5983, "type": "move", "x": 111.79, "y": 107.81}, {"t": 32.6067, "type": "move", "x": 104.96, "y": 107.85}, {"t": 32.615, "type": "move", "x": 99.17, "y": 107.88}, {"t": 32.6233, "type": "move", "x": 94.36, "y": 107.92}, {"t": 32.6317, "type": "move", "x": 90.49, "y": 107.94}, {"t": 32.64, "type": "move", "x": 87.48, "y": 107.96}, {"t": 32.6483, "type": "move", "x": 85.25, "y": 107.98}, {"t": 32.6567, "type": "move", "x": 83.7, "y": 107.99}, {"t": 32.665, "type": "move", "x": 82.74, "y": 107.99}, {"t": 32.6733, "type": "move", "x": 82.22, "y": 108.0}, {"t": 32.6817, "type": "move", "x": 82.03, "y": 108.0}, {"t": 32.69, "type": "move", "x": 82.0, "y": 108.0}, {"t": 32.81, "type": "tap", "x": 82, "y": 108, "hold": 0.09}, {"t": 33.4183, "type": "move", "x": 82.02, "y": 108.01}, {"t": 33.4267, "type": "move", "x": 82.14, "y": 108.05}, {"t": 33.435, "type": "move", "x": 82.48, "y": 108.16}, {"t": 33.4433, "type": "move", "x": 83.11, "y": 108.38}, {"t": 33.4517, "type": "move", "x": 84.12, "y": 108.72}, {"t": 33.46, "type": "move", "x": 85.58, "y": 109.21}, {"t": 33.4683, "type": "move", "x": 87.57, "y": 109.89}, {"t": 33.4767, "type": "move", "x": 90.12, "y": 110.75}, {"t": 33.485, "type": "move", "x": 93.31, "y": 111.83}, {"t": 33.4933, "type": "move", "x": 97.16, "y": 113.13}, {"t": 33.5017, "type": "move", "x": 101.72, "y": 114.67}, {"t": 33.51, "type": "move", "x": 107.0, "y": 116.46}, {"t": 33.5183, "type": "move", "x": 113.05, "y": 118.49}, {"t": 33.5267, "type": "move", "x": 119.86, "y": 120.78}, {"t": 33.535, "type": "move", "x": 127.46, "y": 123.32}, {"t": 33.5433, "type": "move", "x": 135.84, "y": 126.11}, {"t": 33.5517, "type": "move", "x": 145.0, "y": 129.13}, {"t": 33.56, "type": "move", "x": 154.95, "y": 132.38}, {"t": 33.5683, "type": "move", "x": 165.66, "y": 135.84}, {"t": 33.5767, "type": "move", "x": 177.12, "y": 139.49}, {"t": 33.585, "type": "move", "x": 189.32, "y": 143.3}, {"t": 33.5933, "type": "move", "x": 202.23, "y": 147.25}, {"t": 33.6017, "type": "move", "x": 215.82, "y": 151.3}, {"t": 33.61, "type": "move", "x": 230.06, "y": 155.41}, {"t": 33.6183, "type": "move", "x": 244.92, "y": 159.55}, {"t": 33.6267, "type": "move", "x": 260.36, "y": 163.67}, {"t": 33.635, "type": "move", "x": 276.34, "y": 167.72}, {"t": 33.6433, "type": "move", "x": 292.83, "y": 171.68}, {"t": 33.6517, "type": "move", "x": 309.76, "y": 175.47}, {"t": 33.66, "type": "move", "x": 327.11, "y": 179.07}, {"t": 33.6683, "type": "move", "x": 344.81, "y": 182.44}, {"t": 33.6767, "type": "move", "x": 362.82, "y": 185.52}, {"t": 33.685, "type": "move", "x": 381.09, "y": 188.3}, {"t": 33.6933, "type": "move", "x": 399.55, "y": 190.74}, {"t": 33.7017, "type": "move", "x": 418.16, "y": 192.82}, {"t": 33.71, "type": "move", "x": 436.86, "y": 194.52}, {"t": 33.7183, "type": "move", "x": 455.59, "y": 195.84}, {"t": 33.7267, "type": "move", "x": 474.29, "y": 196.77}, {"t": 33.735, "type": "move", "x": 492.91, "y": 197.32}, {"t": 33.7433, "type": "move", "x": 511.38, "y": 197.51}, {"t": 33.7517, "type": "move", "x": 529.66, "y": 197.35}, {"t": 33.76, "type": "move", "x": 547.67, "y": 196.87}, {"t": 33.7683, "type": "move", "x": 565.37, "y": 196.09}, {"t": 33.7767, "type": "move", "x": 582.69, "y": 195.06}, {"t": 33.785, "type": "move", "x": 599.6, "y": 193.8}, {"t": 33.7933, "type": "move", "x": 616.02, "y": 192.36}, {"t": 33.8017, "type": "move", "x": 631.92, "y": 190.77}, {"t": 33.81, "type": "move", "x": 647.26, "y": 189.06}, {"t": 33.8183, "type": "move", "x": 661.97, "y": 187.29}, {"t": 33.8267, "type": "move", "x": 676.04, "y": 185.47}, {"t": 33.835, "type": "move", "x": 689.41, "y": 183.64}, {"t": 33.8433, "type": "move", "x": 702.06, "y": 181.84}, {"t": 33.8517, "type": "move", "x": 713.96, "y": 180.07}, {"t": 33.86, "type": "move", "x": 725.09, "y": 178.37}, {"t": 33.8683, "type": "move", "x": 735.43, "y": 176.76}, {"t": 33.8767, "type": "move", "x": 744.96, "y": 175.24}, {"t": 33.885, "type": "move", "x": 753.68, "y": 173.84}, {"t": 33.8933, "type": "move", "x": 761.58, "y": 172.55}, {"t": 33.9017, "type": "move", "x": 768.67, "y": 171.38}, {"t": 33.91, "type": "move", "x": 774.96, "y": 170.34}, {"t": 33.9183, "type": "move", "x": 780.47, "y": 169.43}, {"t": 33.9267, "type": "move", "x": 785.21, "y": 168.64}, {"t": 33.935, "type": "move", "x": 789.22, "y": 167.97}, {"t": 33.9433, "type": "move", "x": 792.54, "y": 167.41}, {"t": 33.9517, "type": "move", "x": 795.2, "y": 166.97}, {"t": 33.96, "type": "move", "x": 797.27, "y": 166.62}, {"t": 33.9683, "type": "move", "x": 798.79, "y": 166.37}, {"t": 33.9767, "type": "move", "x": 799.84, "y": 166.19}, {"t": 33.985, "type": "move", "x": 800.5, "y": 166.08}, {"t": 33.9933, "type": "move", "x": 800.85, "y": 166.03}, {"t": 34.0017, "type": "move", "x": 800.98, "y": 166.0}, {"t": 34.01, "type": "move", "x": 801.0, "y": 166.0}, {"t": 34.13, "type": "tap", "x": 801, "y": 166, "hold": 0.09}, {"t": 35.1383, "type": "move", "x": 800.99, "y": 166.0}, {"t": 35.1467, "type": "move", "x": 800.92, "y": 166.02}, {"t": 35.155, "type": "move", "x": 800.75, "y": 166.05}, {"t": 35.1633, "type": "move", "x": 800.41, "y": 166.13}, {"t": 35.1717, "type": "move", "x": 799.88, "y": 166.24}, {"t": 35.18, "type": "move", "x": 799.11, "y": 166.41}, {"t": 35.1883, "type": "move", "x": 798.06, "y": 166.64}, {"t": 35.1967, "type": "move", "x": 796.71, "y": 166.93}, {"t": 35.205, "type": "move", "x": 795.03, "y": 167.3}, {"t": 35.2133, "type": "move", "x": 792.99, "y": 167.74}, {"t": 35.2217, "type": "move", "x": 790.58, "y": 168.26}, {"t": 35.23, "type": "move", "x": 787.79, "y": 168.87}, {"t": 35.2383, "type": "move", "x": 784.6, "y": 169.57}, {"t": 35.2467, "type": "move", "x": 781.01, "y": 170.36}, {"t": 35.255, "type": "move", "x": 777.0, "y": 171.25}, {"t": 35.2633, "type": "move", "x": 772.59, "y": 172.24}, {"t": 35.2717, "type": "move", "x": 767.77, "y": 173.32}, {"t": 35.28, "type": "move", "x": 762.54, "y": 174.52}, {"t": 35.2883, "type": "move", "x": 756.93, "y": 175.82}, {"t": 35.2967, "type": "move", "x": 750.93, "y": 177.24}, {"t": 35.305, "type": "move", "x": 744.57, "y": 178.78}, {"t": 35.3133, "type": "move", "x": 737.87, "y": 180.45}, {"t": 35.3217, "type": "move", "x": 730.83, "y": 182.25}, {"t": 35.33, "type": "move", "x": 723.49, "y": 184.2}, {"t": 35.3383, "type": "move", "x": 715.88, "y": 186.3}, {"t": 35.3467, "type": "move", "x": 708.01, "y": 188.56}, {"t": 35.355, "type": "move", "x": 699.92, "y": 190.99}, {"t": 35.3633, "type": "move", "x": 691.65, "y": 193.6}, {"t": 35.3717, "type": "move", "x": 683.21, "y": 196.39}, {"t": 35.38, "type": "move", "x": 674.64, "y": 199.38}, {"t": 35.3883, "type": "move", "x": 665.98, "y": 202.57}, {"t": 35.3967, "type": "move", "x": 657.26, "y": 205.96}, {"t": 35.405, "type": "move", "x": 648.51, "y": 209.55}, {"t": 35.4133, "type": "move", "x": 639.76, "y": 213.35}, {"t": 35.4217, "type": "move", "x": 631.04, "y": 217.34}, {"t": 35.43, "type": "move", "x": 622.38, "y": 221.52}, {"t": 35.4383, "type": "move", "x": 613.81, "y": 225.88}, {"t": 35.4467, "type": "move", "x": 605.35, "y": 230.4}, {"t": 35.455, "type": "move", "x": 597.03, "y": 235.06}, {"t": 35.4633, "type": "move", "x": 588.87, "y": 239.85}, {"t": 35.4717, "type": "move", "x": 580.89, "y": 244.73}, {"t": 35.48, "type": "move", "x": 573.1, "y": 249.69}, {"t": 35.4883, "type": "move", "x": 565.54, "y": 254.69}, {"t": 35.4967, "type": "move", "x": 558.2, "y": 259.71}, {"t": 35.505, "type": "move", "x": 551.11, "y": 264.72}, {"t": 35.5133, "type": "move", "x": 544.28, "y": 269.68}, {"t": 35.5217, "type": "move", "x": 537.72, "y": 274.57}, {"t": 35.53, "type": "move", "x": 531.43, "y": 279.36}, {"t": 35.5383, "type": "move", "x": 525.44, "y": 284.02}, {"t": 35.5467, "type": "move", "x": 519.74, "y": 288.52}, {"t": 35.555, "type": "move", "x": 514.35, "y": 292.85}, {"t": 35.5633, "type": "move", "x": 509.27, "y": 296.97}, {"t": 35.5717, "type": "move", "x": 504.51, "y": 300.89}, {"t": 35.58, "type": "move", "x": 500.07, "y": 304.56}, {"t": 35.5883, "type": "move", "x": 495.96, "y": 308.0}, {"t": 35.5967, "type": "move", "x": 492.17, "y": 311.17}, {"t": 35.605, "type": "move", "x": 488.71, "y": 314.09}, {"t": 35.6133, "type": "move", "x": 485.58, "y": 316.74}, {"t": 35.6217, "type": "move", "x": 482.78, "y": 319.12}, {"t": 35.63, "type": "move", "x": 480.29, "y": 321.23}, {"t": 35.6383, "type": "move", "x": 478.11, "y": 323.08}, {"t": 35.6467, "type": "move", "x": 476.24, "y": 324.68}, {"t": 35.655, "type": "move", "x": 474.65, "y": 326.03}, {"t": 35.6633, "type": "move", "x": 473.34, "y": 327.15}, {"t": 35.6717, "type": "move", "x": 472.29, "y": 328.05}, {"t": 35.68, "type": "move", "x": 471.47, "y": 328.74}, {"t": 35.6883, "type": "move", "x": 470.87, "y": 329.26}, {"t": 35.6967, "type": "move", "x": 470.46, "y": 329.61}, {"t": 35.705, "type": "move", "x": 470.2, "y": 329.83}, {"t": 35.7133, "type": "move", "x": 470.06, "y": 329.95}, {"t": 35.7217, "type": "move", "x": 470.01, "y": 329.99}, {"t": 35.73, "type": "move", "x": 470.0, "y": 330.0}, {"t": 35.7383, "type": "move", "x": 469.99, "y": 330.0}, {"t": 35.7467, "type": "move", "x": 469.96, "y": 330.02}, {"t": 35.755, "type": "move", "x": 469.86, "y": 330.07}, {"t": 35.7633, "type": "move", "x": 469.68, "y": 330.15}, {"t": 35.7717, "type": "move", "x": 469.38, "y": 330.29}, {"t": 35.78, "type": "move", "x": 468.96, "y": 330.49}, {"t": 35.7883, "type": "move", "x": 468.38, "y": 330.77}, {"t": 35.7967, "type": "move", "x": 467.63, "y": 331.12}, {"t": 35.805, "type": "move", "x": 466.71, "y": 331.56}, {"t": 35.8133, "type": "move", "x": 465.58, "y": 332.09}, {"t": 35.8217, "type": "move", "x": 464.26, "y": 332.72}, {"t": 35.83, "type": "move", "x": 462.72, "y": 333.46}, {"t": 35.8383, "type": "move", "x": 460.96, "y": 334.29}, {"t": 35.8467, "type": "move", "x": 458.98, "y": 335.24}, {"t": 35.855, "type": "move", "x": 456.78, "y": 336.29}, {"t": 35.8633, "type": "move", "x": 454.35, "y": 337.46}, {"t": 35.8717, "type": "move", "x": 451.69, "y": 338.75}, {"t": 35.88, "type": "move", "x": 448.82, "y": 340.15}, {"t": 35.8883, "type": "move", "x": 445.74, "y": 341.66}, {"t": 35.8967, "type": "move", "x": 442.45, "y": 343.3}, {"t": 35.905, "type": "move", "x": 438.97, "y": 345.05}, {"t": 35.9133, "type": "move", "x": 435.3, "y": 346.93}, {"t": 35.9217, "type": "move", "x": 431.46, "y": 348.93}, {"t": 35.93, "type": "move", "x": 427.46, "y": 351.05}, {"t": 35.9383, "type": "move", "x": 423.32, "y": 353.3}, {"t": 35.9467, "type": "move", "x": 419.06, "y": 355.68}, {"t": 35.955, "type": "move", "x": 414.69, "y": 358.18}, {"t": 35.9633, "type": "move", "x": 410.24, "y": 360.82}, {"t": 35.9717, "type": "move", "x": 405.72, "y": 363.58}, {"t": 35.98, "type": "move", "x": 401.15, "y": 366.48}, {"t": 35.9883, "type": "move", "x": 396.55, "y": 369.5}, {"t": 35.9967, "type": "move", "x": 391.95, "y": 372.65}, {"t": 36.005, "type": "move", "x": 387.35, "y": 375.92}, {"t": 36.0133, "type": "move", "x": 382.78, "y": 379.3}, {"t": 36.0217, "type": "move", "x": 378.26, "y": 382.8}, {"t": 36.03, "type": "move", "x": 373.8, "y": 386.4}, {"t": 36.0383, "type": "move", "x": 369.41, "y": 390.09}, {"t": 36.0467, "type": "move", "x": 365.11, "y": 393.86}, {"t": 36.055, "type": "move", "x": 360.91, "y": 397.69}, {"t": 36.0633, "type": "move", "x": 356.82, "y": 401.57}, {"t": 36.0717, "type": "move", "x": 352.85, "y": 405.49}, {"t": 36.08, "type": "move", "x": 349.0, "y": 409.42}, {"t": 36.0883, "type": "move", "x": 345.28, "y": 413.35}, {"t": 36.0967, "type": "move", "x": 341.7, "y": 417.26}, {"t": 36.105, "type": "move", "x": 338.26, "y": 421.12}, {"t": 36.1133, "type": "move", "x": 334.97, "y": 424.93}, {"t": 36.1217, "type": "move", "x": 331.82, "y": 428.66}, {"t": 36.13, "type": "move", "x": 328.82, "y": 432.29}, {"t": 36.1383, "type": "move", "x": 325.97, "y": 435.8}, {"t": 36.1467, "type": "move", "x": 323.27, "y": 439.19}, {"t": 36.155, "type": "move", "x": 320.72, "y": 442.43}, {"t": 36.1633, "type": "move", "x": 318.33, "y": 445.51}, {"t": 36.1717, "type": "move", "x": 316.1, "y": 448.43}, {"t": 36.18, "type": "move", "x": 314.02, "y": 451.16}, {"t": 36.1883, "type": "move", "x": 312.1, "y": 453.71}, {"t": 36.1967, "type": "move", "x": 310.33, "y": 456.07}, {"t": 36.205, "type": "move", "x": 308.71, "y": 458.23}, {"t": 36.2133, "type": "move", "x": 307.25, "y": 460.19}, {"t": 36.2217, "type": "move", "x": 305.95, "y": 461.95}, {"t": 36.23, "type": "move", "x": 304.79, "y": 463.52}, {"t": 36.2383, "type": "move", "x": 303.77, "y": 464.89}, {"t": 36.2467, "type": "move", "x": 302.9, "y": 466.07}, {"t": 36.255, "type": "move", "x": 302.16, "y": 467.07}, {"t": 36.2633, "type": "move", "x": 301.55, "y": 467.89}, {"t": 36.2717, "type": "move", "x": 301.07, "y": 468.56}, {"t": 36.28, "type": "move", "x": 300.69, "y": 469.07}, {"t": 36.2883, "type": "move", "x": 300.41, "y": 469.45}, {"t": 36.2967, "type": "move", "x": 300.21, "y": 469.71}, {"t": 36.305, "type": "move", "x": 300.09, "y": 469.88}, {"t": 36.3133, "type": "move", "x": 300.03, "y": 469.96}, {"t": 36.3217, "type": "move", "x": 300.0, "y": 470.0}, {"t": 36.33, "type": "move", "x": 300.0, "y": 470.0}, {"t": 36.3383, "type": "move", "x": 299.99, "y": 470.01}, {"t": 36.3467, "type": "move", "x": 299.91, "y": 470.04}, {"t": 36.355, "type": "move", "x": 299.72, "y": 470.13}, {"t": 36.3633, "type": "move", "x": 299.35, "y": 470.3}, {"t": 36.3717, "type": "move", "x": 298.76, "y": 470.57}, {"t": 36.38, "type": "move", "x": 297.92, "y": 470.95}, {"t": 36.3883, "type": "move", "x": 296.8, "y": 471.46}, {"t": 36.3967, "type": "move", "x": 295.37, "y": 472.12}, {"t": 36.405, "type": "move", "x": 293.61, "y": 472.92}, {"t": 36.4133, "type": "move", "x": 291.51, "y": 473.89}, {"t": 36.4217, "type": "move", "x": 289.06, "y": 475.02}, {"t": 36.43, "type": "move", "x": 286.26, "y": 476.32}, {"t": 36.4383, "type": "move", "x": 283.11, "y": 477.79}, {"t": 36.4467, "type": "move", "x": 279.62, "y": 479.43}, {"t": 36.455, "type": "move", "x": 275.81, "y": 481.26}, {"t": 36.4633, "type": "move", "x": 271.69, "y": 483.26}, {"t": 36.4717, "type": "move", "x": 267.29, "y": 485.45}, {"t": 36.48, "type": "move", "x": 262.64, "y": 487.83}, {"t": 36.4883, "type": "move", "x": 257.76, "y": 490.41}, {"t": 36.4967, "type": "move", "x": 252.7, "y": 493.17}, {"t": 36.505, "type": "move", "x": 247.5, "y": 496.14}, {"t": 36.5133, "type": "move", "x": 242.18, "y": 499.3}, {"t": 36.5217, "type": "move", "x": 236.8, "y": 502.67}, {"t": 36.53, "type": "move", "x": 231.4, "y": 506.23}, {"t": 36.5383, "type": "move", "x": 226.0, "y": 509.98}, {"t": 36.5467, "type": "move", "x": 220.66, "y": 513.91}, {"t": 36.555, "type": "move", "x": 215.4, "y": 518.0}, {"t": 36.5633, "type": "move", "x": 210.25, "y": 522.23}, {"t": 36.5717, "type": "move", "x": 205.25, "y": 526.59}, {"t": 36.58, "type": "move", "x": 200.4, "y": 531.02}, {"t": 36.5883, "type": "move", "x": 195.74, "y": 535.52}, {"t": 36.5967, "type": "move", "x": 191.28, "y": 540.03}, {"t": 36.605, "type": "move", "x": 187.03, "y": 544.52}, {"t": 36.6133, "type": "move", "x": 182.99, "y": 548.94}, {"t": 36.6217, "type": "move", "x": 179.18, "y": 553.27}, {"t": 36.63, "type": "move", "x": 175.6, "y": 557.46}, {"t": 36.6383, "type": "move", "x": 172.26, "y": 561.48}, {"t": 36.6467, "type": "move", "x": 169.15, "y": 565.29}, {"t": 36.655, "type": "move", "x": 166.29, "y": 568.87}, {"t": 36.6633, "type": "move", "x": 163.68, "y": 572.19}, {"t": 36.6717, "type": "move", "x": 161.31, "y": 575.23}, {"t": 36.68, "type": "move", "x": 159.18, "y": 577.98}, {"t": 36.6883, "type": "move", "x": 157.3, "y": 580.43}, {"t": 36.6967, "type": "move", "x": 155.66, "y": 582.57}, {"t": 36.705, "type": "move", "x": 154.26, "y": 584.41}, {"t": 36.7133, "type": "move", "x": 153.08, "y": 585.95}, {"t": 36.7217, "type": "move", "x": 152.13, "y": 587.2}, {"t": 36.73, "type": "move", "x": 151.38, "y": 588.18}, {"t": 36.7383, "type": "move", "x": 150.82, "y": 588.92}, {"t": 36.7467, "type": "move", "x": 150.43, "y": 589.43}, {"t": 36.755, "type": "move", "x": 150.19, "y": 589.75}, {"t": 36.7633, "type": "move", "x": 150.06, "y": 589.92}, {"t": 36.7717, "type": "move", "x": 150.01, "y": 589.99}, {"t": 36.78, "type": "move", "x": 150.0, "y": 590.0}, {"t": 36.7883, "type": "move", "x": 150.0, "y": 590.0}, {"t": 36.7967, "type": "move", "x": 149.98, "y": 590.01}, {"t": 36.805, "type": "move", "x": 149.95, "y": 590.04}, {"t": 36.8133, "type": "move", "x": 149.88, "y": 590.08}, {"t": 36.8217, "type": "move", "x": 149.77, "y": 590.16}, {"t": 36.83, "type": "move", "x": 149.61, "y": 590.27}, {"t": 36.8383, "type": "move", "x": 149.4, "y": 590.41}, {"t": 36.8467, "type": "move", "x": 149.13, "y": 590.6}, {"t": 36.855, "type": "move", "x": 148.8, "y": 590.83}, {"t": 36.8633, "type": "move", "x": 148.4, "y": 591.11}, {"t": 36.8717, "type": "move", "x": 147.93, "y": 591.43}, {"t": 36.88, "type": "move", "x": 147.39, "y": 591.81}, {"t": 36.8883, "type": "move", "x": 146.78, "y": 592.24}, {"t": 36.8967, "type": "move", "x": 146.1, "y": 592.72}, {"t": 36.905, "type": "move", "x": 145.35, "y": 593.25}, {"t": 36.9133, "type": "move", "x": 144.54, "y": 593.83}, {"t": 36.9217, "type": "move", "x": 143.66, "y": 594.46}, {"t": 36.93, "type": "move", "x": 142.72, "y": 595.15}, {"t": 36.9383, "type": "move", "x": 141.73, "y": 595.89}, {"t": 36.9467, "type": "move", "x": 140.69, "y": 596.68}, {"t": 36.955, "type": "move", "x": 139.61, "y": 597.52}, {"t": 36.9633, "type": "move", "x": 138.5, "y": 598.41}, {"t": 36.9717, "type": "move", "x": 137.36, "y": 599.36}, {"t": 36.98, "type": "move", "x": 136.2, "y": 600.35}, {"t": 36.9883, "type": "move", "x": 135.03, "y": 601.38}, {"t": 36.9967, "type": "move", "x": 133.86, "y": 602.47}, {"t": 37.005, "type": "move", "x": 132.7, "y": 603.59}, {"t": 37.0133, "type": "move", "x": 131.54, "y": 604.76}, {"t": 37.0217, "type": "move", "x": 130.41, "y": 605.96}, {"t": 37.03, "type": "move", "x": 129.3, "y": 607.2}, {"t": 37.0383, "type": "move", "x": 128.22, "y": 608.46}, {"t": 37.0467, "type": "move", "x": 127.18, "y": 609.75}, {"t": 37.055, "type": "move", "x": 126.18, "y": 611.04}, {"t": 37.0633, "type": "move", "x": 125.21, "y": 612.35}, {"t": 37.0717, "type": "move", "x": 124.3, "y": 613.65}, {"t": 37.08, "type": "move", "x": 123.42, "y": 614.95}, {"t": 37.0883, "type": "move", "x": 122.59, "y": 616.23}, {"t": 37.0967, "type": "move", "x": 121.81, "y": 617.49}, {"t": 37.105, "type": "move", "x": 121.08, "y": 618.71}, {"t": 37.1133, "type": "move", "x": 120.39, "y": 619.89}, {"t": 37.1217, "type": "move", "x": 119.74, "y": 621.02}, {"t": 37.13, "type": "move", "x": 119.14, "y": 622.1}, {"t": 37.1383, "type": "move", "x": 118.58, "y": 623.12}, {"t": 37.1467, "type": "move", "x": 118.07, "y": 624.08}, {"t": 37.155, "type": "move", "x": 117.6, "y": 624.96}, {"t": 37.1633, "type": "move", "x": 117.17, "y": 625.78}, {"t": 37.1717, "type": "move", "x": 116.79, "y": 626.52}, {"t": 37.18, "type": "move", "x": 116.45, "y": 627.18}, {"t": 37.1883, "type": "move", "x": 116.15, "y": 627.76}, {"t": 37.1967, "type": "move", "x": 115.89, "y": 628.27}, {"t": 37.205, "type": "move", "x": 115.66, "y": 628.7}, {"t": 37.2133, "type": "move", "x": 115.48, "y": 629.06}, {"t": 37.2217, "type": "move", "x": 115.33, "y": 629.35}, {"t": 37.23, "type": "move", "x": 115.21, "y": 629.58}, {"t": 37.2383, "type": "move", "x": 115.13, "y": 629.75}, {"t": 37.2467, "type": "move", "x": 115.07, "y": 629.87}, {"t": 37.255, "type": "move", "x": 115.03, "y": 629.94}, {"t": 37.2633, "type": "move", "x": 115.01, "y": 629.98}, {"t": 37.2717, "type": "move", "x": 115.0, "y": 630.0}, {"t": 37.28, "type": "move", "x": 115.0, "y": 630.0}, {"t": 37.4, "type": "tap", "x": 115, "y": 630, "hold": 0.09}]} \ No newline at end of file diff --git a/app/vendor/rune/examples/cursed-settings/scripts/showcase.py b/app/vendor/rune/examples/cursed-settings/scripts/showcase.py new file mode 100644 index 0000000..3e8696f --- /dev/null +++ b/app/vendor/rune/examples/cursed-settings/scripts/showcase.py @@ -0,0 +1,119 @@ +#!/usr/bin/env python3 +"""Writes showcase.json: a pointer that glides between controls and flips them one after another. + +Coordinates are window points (960x660). Run: python3 showcase.py > showcase.json +""" +import json +import math + +events = [] +pos = [600.0, 420.0] +clock = 0.0 + + +def glide(to, dur=0.55, at=None): + """An eased, slightly arced move sampled at 120 Hz.""" + global pos, clock + if at is not None: + clock = at + x0, y0 = pos + x1, y1 = to + n = max(2, int(dur * 120)) + dx, dy = x1 - x0, y1 - y0 + bend = 0.08 * math.hypot(dx, dy) + nx, ny = (-dy, dx) if (dx or dy) else (0, 0) + ln = math.hypot(nx, ny) or 1.0 + for k in range(1, n + 1): + f = k / n + e = f * f * f * (f * (f * 6 - 15) + 10) + arc = math.sin(math.pi * e) * bend + events.append({ + "t": round(clock + dur * f, 4), + "type": "move", + "x": round(x0 + dx * e + nx / ln * arc, 2), + "y": round(y0 + dy * e + ny / ln * arc, 2), + }) + clock += dur + pos = [x1, y1] + + +def tap(to, dur=0.55, at=None, settle=0.12): + glide(to, dur, at) + global clock + clock += settle + events.append({"t": round(clock, 4), "type": "tap", "x": to[0], "y": to[1], "hold": 0.09}) + clock += 0.1 + + +def wait(s): + global clock + clock += s + + +NAV = {"general": (70, 78), "appearance": (82, 108), "network": (72, 138), "security": (70, 168), + "accessibility": (84, 198), "developer": (76, 228)} +SW1, SW2 = (891, 166), (891, 232) + +wait(0.6) +# General: lightning, then the spotlight. +tap((891, 232), 0.7) # Lightning-fast startup +wait(1.3) +tap((891, 355), 0.6) # Show in Spotlight +wait(1.9) +tap((891, 355), 0.25) # ...and back off +wait(0.4) + +# Network: firewall, static IP. +tap(NAV["network"], 0.55) +wait(0.5) +tap(SW1, 0.6) # Firewall +wait(1.4) +tap((891, 481), 0.6) # Static IP +wait(1.0) + +# Security: electric fence, then get too close. +tap(NAV["security"], 0.55) +wait(0.5) +tap(SW1, 0.6) # Electric fence +wait(1.0) +glide((640, 530), 0.55) +wait(0.6) +glide((700, 570), 0.3) + +# Accessibility: haptics Strong, frosting, contrast. +tap(NAV["accessibility"], 0.55) +wait(0.5) +tap((869, 478), 0.6) # Haptic feedback: Strong +wait(0.8) +tap((560, 300), 0.45) # Just clicking around. +wait(0.7) +tap(SW2, 0.6) # Reduce transparency +wait(1.4) +tap(SW1, 0.45) # Increase contrast +wait(1.8) +tap(SW1, 0.2) +wait(0.3) + +# Developer: hot reload, flush. +tap(NAV["developer"], 0.55) +wait(0.5) +tap(SW1, 0.6) # Hot reload +wait(1.6) +tap((873, 301), 0.5) # Flush cache +wait(1.8) + +# Appearance: Dark, then wander with the torch. +tap(NAV["appearance"], 0.55) +wait(0.5) +tap((801, 166), 0.6) # Dark +wait(0.9) +glide((470, 330), 0.6) +glide((300, 470), 0.6) +glide((150, 590), 0.45) + +# Restore Defaults. +tap((115, 630), 0.5) +wait(2.3) + +json.dump({"events": events}, open(__file__.replace(".py", ".json"), "w")) +print(f"{clock:.2f} s, {len(events)} events") diff --git a/app/vendor/rune/examples/cursed-settings/showcase.sh b/app/vendor/rune/examples/cursed-settings/showcase.sh new file mode 100644 index 0000000..bd05d6c --- /dev/null +++ b/app/vendor/rune/examples/cursed-settings/showcase.sh @@ -0,0 +1,26 @@ +#!/bin/sh +# Render the showcase clip headless and encode it (H.264, yuv420p, 60 fps) plus a poster and +# review stills into captures/cursed-show. Raw frames are deleted. +# Run from the repo root: sh examples/cursed-settings/showcase.sh +set -e +cargo build --release -p cursed-settings 2>&1 | grep -E '^error|-->' | head -40 || true +cargo build --release -p cursed-settings -q +bin="${CARGO_TARGET_DIR:-target}/release/cursed-settings" +out=captures/cursed-show +rm -rf "$out" && mkdir -p "$out" +script=examples/cursed-settings/scripts/showcase.json +secs=${SECS:-39.8} +frames=$(python3 -c "print(int($secs * 60))") +for theme in ${THEMES:-light dark}; do + dir=$(mktemp -d) + "$bin" --cursor --theme "$theme" --scale 2 --script "$script" --frames "$frames" --fps 60 --out "$dir" > "$out/$theme.log" 2>&1 + ffmpeg -loglevel error -y -framerate 60 -i "$dir/frame_%04d.png" -c:v libx264 -preset slow -crf 18 -pix_fmt yuv420p -r 60 -movflags +faststart "$out/showcase-$theme.mp4" + # Review stills: a moment after each punchline lands. + for t in ${REVIEW:-1.6 1.8 1.9 2.2 3.9 4.6 5.3 8.6 9.0 9.8 11.0 13.9 14.5 15.6 16.0 18.5 21.9 24.3 28.5 30.0 30.6 31.0 31.6 32.4 34.3 34.5 35.4 36.6 37.7 39.0}; do + n=$(python3 -c "print(f'{int(round($t * 60)):04d}')") + [ -f "$dir/frame_$n.png" ] && sips -s format jpeg -s formatOptions 80 -Z 1280 "$dir/frame_$n.png" --out "$out/$theme-$t.jpg" > /dev/null + done + cp "$dir/frame_$(python3 -c "print(f'{int(9.8 * 60):04d}')").png" "$out/poster-$theme.png" + rm -rf "$dir" +done +ls -la "$out" | head -80 diff --git a/app/vendor/rune/examples/cursed-settings/snap.sh b/app/vendor/rune/examples/cursed-settings/snap.sh new file mode 100644 index 0000000..f9317b9 --- /dev/null +++ b/app/vendor/rune/examples/cursed-settings/snap.sh @@ -0,0 +1,15 @@ +#!/bin/sh +# Build, then render headless stills of every scene into captures/cursed (both themes). +# Run from the repo root: sh examples/cursed-settings/snap.sh +set -e +cargo build --release -p cursed-settings 2>&1 | grep -E '^(error|warning: unused)|-->|^\s+\|' | head -80 || true +cargo build --release -p cursed-settings -q +bin="${CARGO_TARGET_DIR:-target}/release/cursed-settings" +out=captures/cursed +rm -rf "$out" && mkdir -p "$out" +for theme in light dark; do + for scene in ${SCENES:-general network security fire fence dark spotlight contrast frosted hot flushed}; do + "$bin" --scene "$scene" --theme "$theme" --scale 1 --at "${AT:-2.0}" --snap "$out/$scene-$theme.png" > "$out/$scene-$theme.log" 2>&1 || echo "FAIL $scene $theme" + done +done +ls "$out" diff --git a/app/vendor/rune/examples/cursed-settings/src/gags/lighting.rs b/app/vendor/rune/examples/cursed-settings/src/gags/lighting.rs new file mode 100644 index 0000000..53f3ef0 --- /dev/null +++ b/app/vendor/rune/examples/cursed-settings/src/gags/lighting.rs @@ -0,0 +1,148 @@ +//! Scene lighting for the gags: brightness, dark mode (lights out and torch), spotlight, +//! contrast, and the lightning strike's flash. + +use rune_light::{Light, Settings, TextPolicy}; +use rune_motion::{Animated, Spring, Vec2}; + +use super::{Gags, In, mix, smooth}; + +impl Gags { + pub(super) fn lighting( + &mut self, + i: &In, + storm: f32, + flash: f32, + flash_at: [f32; 2], + anim: &mut bool, + ) -> (Vec<Light>, Settings, f32) { + let p = &i.s.p; + let t = i.t; + let rm = p.reduce_motion; + let tg = &i.targets; + let px = |q: [f32; 2]| [q[0] * i.scale, q[1] * i.scale]; + let mut lights: Vec<Light> = Vec::new(); + + let mut amb = 0.1 + 0.9 * p.brightness.clamp(0.0, 1.0); + amb *= mix(1.0, 0.32, storm); + + let dark_on = p.appearance == 1; + self.dark.set(dark_on, t, rm); + let (darkness, torch) = if self.dark.is_on() { + let u = self.dark.since(t); + let flick = if rm { + smooth(0.0, 0.2, u) + } else if u < 0.05 { + 0.85 + } else if u < 0.11 { + 0.1 + } else if u < 0.17 { + 0.92 + } else if u < 0.23 { + 0.45 + } else { + 1.0 + }; + let from = self.dark.from; + let d = mix(from, 1.0, flick); + (d, smooth(0.0, 0.18, u - if rm { 0.2 } else { 0.6 })) + } else { + let d = self.dark.at(t); + (d, 0.0) + }; + *anim |= self.dark.moving(t) || self.dark.is_on() && self.dark.since(t) < 1.0; + amb *= mix(1.0, 0.006, darkness); + if torch > 0.0 { + if let Some(q) = i.pointer { + self.torch = q; + } + let q = self.torch; + let lp = [q[0] + 80.0, q[1] + 130.0]; + let (a, b) = (px(q), px(lp)); + let h = 260.0; + out_light(&mut lights, Light::point(b[0], b[1], h * i.scale) + .color([1.0, 0.95, 0.87]) + .intensity(7.0) + .radius(9.0 * i.scale) + .range(1800.0 * i.scale) + .spot([a[0] - b[0], a[1] - b[1], -h * i.scale], 0.56) + .specular(1.3) + .scaled(torch)); + } + + let spot_switched = self.spot.set(p.spotlight, t, rm); + let sv = self.spot.at(t); + *anim |= self.spot.moving(t); + if let Some((r, _)) = tg.search { + let target = Vec2 { x: r.x + r.w * 0.5, y: r.y + r.h * 0.5 }; + let sp = self.spot_pos.get_or_insert_with(|| Animated::new(target)); + if spot_switched && p.spotlight && !rm { + // Swing in from off-stage, upper right. + sp.set(Vec2 { x: i.vp.x + i.vp.w + 60.0, y: i.vp.y + 40.0 }); + } + if rm { + sp.set(target); + } else { + sp.animate_to(target, Spring::new(1.15, 0.16), i.now); + } + *anim |= sv > 0.0 && !sp.is_settled(i.now); + if sv > 0.003 { + let q = sp.sample(i.now); + let q = [q.x, q.y]; + let lp = [q[0] + 150.0, q[1] - 90.0]; + let h = 420.0; + let (a, b) = (px(q), px(lp)); + out_light(&mut lights, Light::point(b[0], b[1], h * i.scale) + .color([1.0, 0.93, 0.8]) + .intensity(4.5) + .radius(5.0 * i.scale) + .range(2400.0 * i.scale) + .spot([a[0] - b[0], a[1] - b[1], -h * i.scale], 0.27) + .specular(1.5) + .scaled(sv)); + } + } + amb *= mix(1.0, 0.025, sv); + + self.contrast.set(p.contrast, t, rm); + let cv = self.contrast.at(t); + *anim |= self.contrast.moving(t); + if cv > 0.003 { + let lp = px([i.vp.x - 90.0, i.vp.y + i.vp.h * 0.32]); + out_light(&mut lights, Light::point(lp[0], lp[1], 26.0 * i.scale) + .color([1.0, 0.88, 0.72]) + .intensity(6.0) + .radius(12.0 * i.scale) + .range(4000.0 * i.scale) + .specular(1.6) + .scaled(cv)); + } + amb *= mix(1.0, 0.28, cv); + + if flash > 0.003 { + let q = px([flash_at[0] + 30.0, flash_at[1] - 120.0]); + out_light(&mut lights, Light::point(q[0], q[1], 300.0 * i.scale) + .color([0.85, 0.9, 1.0]) + .intensity(6.0) + .radius(30.0 * i.scale) + .range(5000.0 * i.scale) + .scaled(flash)); + } + + let gloom = darkness.max(sv * 0.85).max(cv * 0.6); + let settings = Settings { + ambient: [amb, amb, amb * 1.05], + text: TextPolicy { floor: mix(0.82, 0.08, gloom), ceiling: 1.3, lit: 1.0, specular: 0.12 }, + rim: 0.8 + 0.8 * cv, + contact_ao: 0.35 + 0.2 * cv, + albedo_floor: 0.05, + background_gloss: 0.35, + ..Default::default() + }; + let lit = ((1.0 - amb) * 8.0 + (flash + torch + sv + cv) * 8.0).clamp(0.0, 1.0); + (lights, settings, lit) + } +} + +fn out_light(v: &mut Vec<Light>, l: Light) { + v.push(l); +} diff --git a/app/vendor/rune/examples/cursed-settings/src/gags/mod.rs b/app/vendor/rune/examples/cursed-settings/src/gags/mod.rs new file mode 100644 index 0000000..9d124f5 --- /dev/null +++ b/app/vendor/rune/examples/cursed-settings/src/gags/mod.rs @@ -0,0 +1,729 @@ +//! The punchlines. Each frame turns the settings (and where Rune drew their targets) into +//! rune-fx layers and rune-light lights. Every gag runs on an envelope that springs from where +//! it is toward on or off, so turning one off mid-flight cools it instead of cutting it. + +mod lighting; + +use std::f32::consts::{PI, TAU}; + +use rune_fx::{ + BlurMode, DistortParams, ElectricParams, ElectricStyle, FireParams, FireStyle, Fx, FxLayer, GlowParams, + LensParams, MotionBlurParams, MotionSamples, OneShots, Pose, PulseParams, PulseStyle, Rect, Rgb, Shape, rgb, +}; +use rune_light::{Light, Settings}; +use rune_motion::{Animated, Spring, Vec2}; + +use crate::ui::node; +use crate::{Cursed, Page}; + +/// How long the cache takes to go down the drain. +pub const FLUSH_SECONDS: f32 = 1.3; +/// The emptied card fading back in afterwards. +const FLUSH_REVEAL: f32 = 0.35; + +pub const SRC_NODE: u32 = 0; +const STRIKE_WINDUP: f32 = 0.32; + +// ---------------------------------------------------------------- envelopes + +/// Step response of a spring with Rune's (duration, bounce) parameters. +fn step(u: f32, dur: f32, bounce: f32) -> f32 { + if u <= 0.0 { + return 0.0; + } + let w = TAU / dur.max(1e-3); + if bounce <= 1e-3 { + 1.0 - (1.0 + w * u) * (-w * u).exp() + } else { + let z = 1.0 - bounce.min(0.95); + let wd = w * (1.0 - z * z).sqrt(); + 1.0 - (-z * w * u).exp() * ((wd * u).cos() + z * w / wd * (wd * u).sin()) + } +} + +fn smooth(e0: f32, e1: f32, x: f32) -> f32 { + let t = ((x - e0) / (e1 - e0)).clamp(0.0, 1.0); + t * t * (3.0 - 2.0 * t) +} + +fn mix(a: f32, b: f32, t: f32) -> f32 { + a + (b - a) * t +} + +/// A switched envelope: 0 off, 1 on, sprung from wherever it was when the switch flipped. +#[derive(Clone, Copy, Debug)] +pub struct Env { + on: Option<bool>, + t0: f32, + from: f32, + up: (f32, f32), + down: f32, + delay: f32, + reduced: bool, +} + +impl Env { + fn new(up: f32, bounce: f32, down: f32) -> Env { + Env { on: None, t0: -1e3, from: 0.0, up: (up, bounce), down, delay: 0.0, reduced: false } + } + fn delay(mut self, d: f32) -> Env { + self.delay = d; + self + } + /// The first sight is the resting state, not a transition. + fn set(&mut self, on: bool, t: f32, reduced: bool) -> bool { + match self.on { + None => { + self.on = Some(on); + self.from = on as u8 as f32; + false + } + Some(o) if o != on => { + self.from = self.at(t); + self.on = Some(on); + self.t0 = t; + self.reduced = reduced; + true + } + _ => false, + } + } + fn is_on(&self) -> bool { + self.on == Some(true) + } + fn since(&self, t: f32) -> f32 { + t - self.t0 + } + fn shape(&self) -> (f32, f32, f32) { + if self.reduced { + return (0.18, 0.0, 0.0); + } + if self.is_on() { (self.up.0, self.up.1, self.delay) } else { (self.down, 0.0, 0.0) } + } + fn at(&self, t: f32) -> f32 { + let target = if self.is_on() { 1.0 } else { 0.0 }; + let (dur, bounce, delay) = self.shape(); + self.from + (target - self.from) * step(t - self.t0 - delay, dur, bounce) + } + fn moving(&self, t: f32) -> bool { + let (dur, bounce, delay) = self.shape(); + self.since(t) < delay + dur * (1.3 + 2.5 * bounce) + } +} + +// ---------------------------------------------------------------- frame inputs and outputs + +#[derive(Clone, Copy, Debug)] +pub enum Anchor { + Under(u16), + Over(u16), + /// Above everything but the pointer. + Top, +} + +pub struct Lay { + pub layer: FxLayer, + pub anchor: Anchor, +} + +/// Where Rune drew each target this frame (points) and its opacity. +#[derive(Default)] +pub struct Targets { + pub fast: Option<(Rect, f32)>, + pub search: Option<(Rect, f32)>, + pub firewall: Option<(Rect, f32)>, + pub allowed: Option<(Rect, f32)>, + pub ip: Option<(Rect, f32)>, + pub fence: Option<(Rect, f32)>, + pub perimeter: Option<(Rect, f32)>, + pub reload: Option<(Rect, f32)>, + pub cache: Option<(Rect, f32)>, + pub sel: Option<(Rect, f32)>, +} + +pub struct In<'a> { + pub s: &'a Cursed, + pub t: f32, + pub now: f64, + /// Device px per pt. + pub scale: f32, + /// The window in points. + pub vp: Rect, + pub pointer: Option<[f32; 2]>, + pub dark_theme: bool, + /// The selection colour under the glass (linear). + pub glass_tint: [f32; 3], + pub targets: Targets, +} + +pub struct Out { + pub lays: Vec<Lay>, + pub lights: Vec<Light>, + pub settings: Settings, + /// How much of the lit frame shows over the plain one (0 skips lighting). + pub lit: f32, + /// The cache card's pose track while it drains, with its rest rect. + pub flush: Option<(MotionBlurParams, MotionSamples, Rect)>, + pub anim: bool, +} + +pub struct Gags { + fire: Env, + fire_x: f32, + charge: Env, + fence: Env, + dark: Env, + contrast: Env, + spot: Env, + spot_pos: Option<Animated<Vec2>>, + frost: Env, + hot: Env, + fast: Option<bool>, + strike: Option<f32>, + drop: Option<Animated<Vec2>>, + torch: [f32; 2], + taps: Option<u32>, + shocks: OneShots<[f32; 2]>, +} + +impl Default for Gags { + fn default() -> Self { + Gags { + fire: Env::new(0.9, 0.12, 0.55).delay(0.24), + fire_x: 0.0, + charge: Env::new(0.35, 0.0, 0.5), + fence: Env::new(0.45, 0.0, 0.4).delay(0.2), + dark: Env::new(0.22, 0.0, 0.5), + contrast: Env::new(0.6, 0.0, 0.5), + spot: Env::new(0.5, 0.0, 0.55), + spot_pos: None, + frost: Env::new(0.5, 0.0, 0.45), + hot: Env::new(1.6, 0.0, 2.4).delay(0.1), + fast: None, + strike: None, + drop: None, + torch: [480.0, 330.0], + taps: None, + shocks: OneShots::new(4), + } + } +} + +fn center(r: Rect) -> [f32; 2] { + [r.x + r.w * 0.5, r.y + r.h * 0.5] +} + +fn rounded(r: Rect, radius: f32) -> Shape { + Shape::rounded(r.x, r.y, r.w, r.h, radius) +} + +fn lin3(c: Rgb) -> [f32; 3] { + c.0 +} + +/// Black-body-ish ramp for heating metal: dull red, orange, yellow-white. +fn glow_of(h: f32) -> Rgb { + let a = lin3(rgb(0x7a1204)); + let b = lin3(rgb(0xff4a12)); + let c = lin3(rgb(0xffb347)); + let k = h.clamp(0.0, 1.0); + let (p, q, u) = if k < 0.6 { (a, b, k / 0.6) } else { (b, c, (k - 0.6) / 0.4) }; + Rgb([mix(p[0], q[0], u), mix(p[1], q[1], u), mix(p[2], q[2], u)]) +} + +/// Signed distance to a rounded rect and the nearest point on its border. +fn border_point(r: Rect, radius: f32, p: [f32; 2]) -> (f32, [f32; 2]) { + let c = center(r); + let half = [r.w * 0.5 - radius, r.h * 0.5 - radius]; + let q = [p[0] - c[0], p[1] - c[1]]; + let cl = [q[0].clamp(-half[0], half[0]), q[1].clamp(-half[1], half[1])]; + let d = [q[0] - cl[0], q[1] - cl[1]]; + let len = d[0].hypot(d[1]); + if len > 1e-3 { + let n = [d[0] / len, d[1] / len]; + (len - radius, [c[0] + cl[0] + n[0] * radius, c[1] + cl[1] + n[1] * radius]) + } else { + // Inside the core: push out to the nearest side. + let dx = half[0] + radius - q[0].abs(); + let dy = half[1] + radius - q[1].abs(); + if dx < dy { + (-dx, [c[0] + q[0].signum() * (half[0] + radius), p[1]]) + } else { + (-dy, [p[0], c[1] + q[1].signum() * (half[1] + radius)]) + } + } +} + +fn arc_shape(a: [f32; 2], b: [f32; 2]) -> Shape { + let x = a[0].min(b[0]); + let y = a[1].min(b[1]); + Shape::rounded(x, y, (a[0] - b[0]).abs().max(2.0), (a[1] - b[1]).abs().max(2.0), 0.0) +} + +impl Gags { + pub fn frame(&mut self, i: &In) -> Out { + let s = i.s; + let p = &s.p; + let t = i.t; + let rm = p.reduce_motion; + let tg = &i.targets; + let light_ui = !i.dark_theme; + // Emissive light vanishes on a white window: there it reads as ink, deep and opaque. + let (volt, volt_core, volt_occ, volt_k) = + if light_ui { (rgb(0x1f5cff), rgb(0x7fa6ff), 0.95, 1.5) } else { (rgb(0x5a9bff), rgb(0xeaf3ff), 0.12, 1.0) }; + let mut lays: Vec<Lay> = Vec::new(); + let mut anim = false; + let mut push = |layer: FxLayer, anchor: Anchor| lays.push(Lay { layer: layer.at(t).reduced(rm), anchor }); + let light_theme = !i.dark_theme; + + // ---- Firewall: a wall of fire along the top of "Allowed apps"; off leaves embers. + if self.fire.set(p.firewall, t, rm) && p.firewall { + self.fire_x = tg.firewall.map_or(0.0, |(r, _)| center(r)[0]); + } + anim |= self.fire.moving(t); + if let Some((a, alpha)) = tg.allowed { + let g = self.fire.at(t).max(0.0); + let since = self.fire.since(t); + if self.fire.is_on() && since < 0.8 && !rm + && let Some((sw, _)) = tg.firewall + { + // The spark: winds up, shoots from the switch to the card's edge, blooms there. + let from = center(sw); + let to = [self.fire_x.clamp(a.x + 12.0, a.x + a.w - 12.0), a.y]; + let d = [to[0] - from[0], to[1] - from[1]]; + let len = d[0].hypot(d[1]).max(1.0); + push( + Fx::pulse(PulseParams { + style: PulseStyle::Ping { from, dir: [d[0] / len, d[1] / len], travel: len }, + color: rgb(0xff7a1a), + core: rgb(0xfff1d6), + t0: self.fire.t0, + duration: 0.26, + head_radius: 2.4, + intensity: alpha, + ..Default::default() + }) + .on(Shape::circle(from[0], from[1], 6.0)), + Anchor::Top, + ); + anim = true; + } + if g > 0.003 { + let ix = self.fire_x.clamp(a.x, a.x + a.w); + let span = if self.fire.is_on() && !rm { step(since - 0.24, 0.85, 0.0) } else { 1.0 }; + let x0 = mix(ix, a.x, span); + let x1 = mix(ix, a.x + a.w, span); + let shape = Shape::rounded(x0, a.y, (x1 - x0).max(14.0), a.h, 8.0); + push( + Fx::fire(FireParams { + height: 46.0 * g, + scale: 17.0, + speed: 1.5, + intensity: g.min(1.0) * alpha * if light_theme { 1.5 } else { 1.0 }, + embers: 18, + ember_rise: 62.0, + occlusion: if light_theme { 0.9 } else { 0.3 }, + base_glow: 0.55, + ..Default::default() + }) + .on(shape) + .seed(5), + Anchor::Under(node::ALLOWED), + ); + push( + Fx::distort(DistortParams::HeatHaze { height: 70.0 * g, scale: 10.0, speed: 2.0, amount: 1.3 * g * alpha, whole_shape: false }) + .on(Shape::rounded(x0, a.y - 30.0 * g, (x1 - x0).max(14.0), a.h, 8.0)), + Anchor::Over(node::ALLOWED), + ); + } + if !self.fire.is_on() && self.fire.since(t) < 2.4 && !rm { + let k = 1.0 - smooth(0.2, 2.4, self.fire.since(t)); + push( + Fx::fire(FireParams { + style: FireStyle::Embers, + embers: 26, + ember_rise: 44.0, + ember_life: 1.9, + ember_size: 0.9, + intensity: k * alpha, + ..Default::default() + }) + .on(rounded(a, 8.0)) + .seed(6), + Anchor::Over(node::ALLOWED), + ); + anim = true; + } + } + + // ---- Static IP: the address field crackles with static. + self.charge.set(p.static_ip, t, rm); + anim |= self.charge.moving(t); + if let Some((f, alpha)) = tg.ip { + let c = self.charge.at(t); + if c > 0.003 { + let burst = if self.charge.is_on() { (-self.charge.since(t) / 0.4).exp() } else { 0.0 }; + let base = ElectricParams::charged(); + push( + Fx::electric(ElectricParams { + color: volt, + core: volt_core, + intensity: 0.85 * volt_k * c * alpha, + forks: 0.3 + 0.6 * burst, + amplitude: base.amplitude + 2.6 * burst, + glow: (base.glow * 0.6 + 2.0 * burst).max(1.0), + flicker: 0.25 * burst, + occlusion: volt_occ, + ..base + }) + .on(rounded(f, 6.0)) + .seed(9), + Anchor::Over(node::IP), + ); + } + } + + // ---- Electric fence: a charge runs from the switch to the perimeter, which goes live. + self.fence.set(p.fence, t, rm); + anim |= self.fence.moving(t); + if let Some((pr, alpha)) = tg.perimeter { + let v = self.fence.at(t); + let since = self.fence.since(t); + let blue = volt; + if self.fence.is_on() && since < 0.45 + && let Some((sw, _)) = tg.fence + { + let a = center(sw); + let b = [pr.x + pr.w - 24.0, pr.y + 2.0]; + let e = if since < 0.2 { 1.0 } else { (-(since - 0.2) / 0.08).exp() }; + push( + Fx::electric(ElectricParams { + style: ElectricStyle::Arc { a, b }, + color: blue, + amplitude: 7.0, + frequency: 2.0, + strands: 2, + forks: 0.6, + core: volt_core, + glow: 3.5, + intensity: e * volt_k * alpha, + occlusion: volt_occ, + ..Default::default() + }) + .on(arc_shape(a, b)) + .seed(2 + (since * 20.0) as u32), + Anchor::Top, + ); + anim = true; + } + if v > 0.003 { + push( + Fx::electric(ElectricParams { + style: ElectricStyle::Border, + color: blue, + amplitude: 3.6, + frequency: 2.6, + speed: 3.4, + core: volt_core, + glow: 2.8, + forks: 0.5, + strands: 2, + intensity: v * volt_k * alpha, + occlusion: volt_occ, + ..Default::default() + }) + .on(rounded(pr, 8.0)) + .seed(7), + Anchor::Over(node::PERIMETER), + ); + // Come close and it bites. + if let Some(q) = i.pointer { + let (d, n) = border_point(pr, 8.0, q); + let reach = 60.0; + if v > 0.5 && d.abs() < reach { + let k = (1.0 - d.abs() / reach).powf(0.8) * v * alpha; + push( + Fx::electric(ElectricParams { + style: ElectricStyle::Arc { a: n, b: q }, + color: blue, + amplitude: 3.0 + d.abs() * 0.08, + frequency: 2.4, + strands: 2, + forks: 0.7, + fork_len: 14.0, + core: volt_core, + glow: 3.0, + flicker: 0.6, + intensity: k * volt_k, + occlusion: volt_occ, + ..Default::default() + }) + .on(arc_shape(n, q)) + .seed(31 + (t * 11.0) as u32), + Anchor::Top, + ); + push( + Fx::glow(GlowParams { color: blue, core: volt_core, radius: 6.0, intensity: k, hot: 0.8, occlusion: if light_ui { 0.6 } else { 0.0 }, ..Default::default() }) + .on(Shape::circle(q[0], q[1], 2.5)) + .over(), + Anchor::Top, + ); + anim = true; + } + } + } + } + + // ---- Lightning-fast startup: lightning strikes the switch. + if let Some(prev) = self.fast + && !prev + && p.fast_startup + && s.page == Page::General + { + self.strike = Some(t); + } + self.fast = Some(p.fast_startup); + let mut flash = 0.0f32; + let mut flash_at = [0.0f32; 2]; + let mut storm = 0.0f32; + if let (Some(t0), Some((sw, alpha))) = (self.strike, tg.fast) { + // Anticipation: the sky darkens first, then the bolt lands and the room recovers. + let windup = if rm { 0.0 } else { STRIKE_WINDUP }; + let w = t - t0; + storm = if rm { 0.0 } else { smooth(0.0, windup, w) * (1.0 - smooth(windup + 0.15, windup + 0.9, w)) }; + let u = w - windup; + if u < 0.0 { + anim = true; + } else if u < 1.4 { + anim = true; + let e = if rm { + 1.0 - smooth(0.0, 0.3, u) + } else if u < 0.05 { + 1.0 + } else if u < 0.1 { + 0.12 + } else if u < 0.17 { + 1.0 + } else { + (-(u - 0.17) / 0.09).exp() + }; + let b = center(sw); + let a = [b[0] + 46.0, i.vp.y - 12.0]; + if e > 0.01 { + push( + Fx::electric(ElectricParams { + style: ElectricStyle::Arc { a, b }, + color: if light_ui { rgb(0x2a5cff) } else { rgb(0x9cc4ff) }, + core: if light_ui { rgb(0x9bb8ff) } else { rgb(0xffffff) }, + amplitude: 15.0, + frequency: 1.5, + speed: 6.0, + core_width: 1.3, + strands: 3, + forks: 0.95, + fork_len: 30.0, + glow: 4.5, + flicker: 0.0, + intensity: e * alpha * volt_k, + occlusion: if light_ui { 0.95 } else { 0.15 }, + ..Default::default() + }) + .on(arc_shape(a, b)) + .seed(if u < 0.1 { 3 } else { 4 }), + Anchor::Top, + ); + } + // The bolt lands: the window rings like a struck bell. + if !rm { + let full = Shape::rounded(i.vp.x, i.vp.y, i.vp.w, i.vp.h, 0.0); + let t1 = t0 + windup; + push( + Fx::distort(DistortParams::Shockwave { at: b, reach: 420.0, width: 26.0, amount: 12.0, chroma: 0.2, t0: t1, duration: 1.1 }).on(full), + Anchor::Top, + ); + } + // The switch stays hot for a moment. + let ember = (-u / 0.5).exp() * alpha; + push( + Fx::glow(GlowParams { color: rgb(0x8fb8ff), core: rgb(0xffffff), radius: 4.0, intensity: 0.6 * ember, hot: 0.7, occlusion: if light_ui { 0.6 } else { 0.15 }, ..Default::default() }) + .on(Shape::rounded(sw.x, sw.y, sw.w, sw.h, 4.0)), + Anchor::Top, + ); + flash = e; + flash_at = b; + } else { + self.strike = None; + } + } + + // ---- Reduce transparency: the sidebar's glass selection frosts over. + self.frost.set(p.reduce_transparency, t, rm); + anim |= self.frost.moving(t); + if let Some((r, alpha)) = tg.sel { + let c = Vec2 { x: r.x + r.w * 0.5, y: r.y + r.h * 0.5 }; + let d = self.drop.get_or_insert_with(|| Animated::new(c)); + if rm { + d.set(c); + } else { + d.animate_to(c, Spring::new(0.55, 0.0), i.now); + } + anim |= !d.is_settled(i.now); + let dc = d.sample(i.now); + let f = self.frost.at(t); + push( + Fx::lens(LensParams { + bevel: 7.0, + depth: 6.0, + dispersion: 0.12, + magnification: 1.03, + presence: alpha, + frost: f, + shadow: 0.18, + rim: 1.3, + tint: Rgb(i.glass_tint), + tint_amount: 0.92 * f, + second: Some(Shape::rounded(dc.x - r.w * 0.5, dc.y - r.h * 0.5, r.w, r.h, 6.0)), + union_k: 18.0, + ..Default::default() + }) + .on(rounded(r, 6.0)), + Anchor::Over(node::NAV), + ); + } + + // ---- Hot reload: the reload button glows red-hot and the air above it shimmers. + self.hot.set(p.hot_reload, t, rm); + anim |= self.hot.moving(t); + if let Some((b, alpha)) = tg.reload { + let h = self.hot.at(t).clamp(0.0, 1.2); + if h > 0.004 { + anim = true; + push( + Fx::glow(GlowParams { + color: glow_of(h), + core: rgb(0xffe6c0), + radius: 5.0 + 7.0 * h, + intensity: 0.9 * h * alpha, + hot: 0.35 * h, + breathe: 0.18, + breathe_period: 1.9, + occlusion: if light_theme { 0.7 } else { 0.1 }, + ..Default::default() + }) + .on(rounded(b, 6.0)), + Anchor::Under(node::RELOAD), + ); + let ht = FireParams::heat(); + push( + Fx::fire(FireParams { intensity: ht.intensity * 1.5 * h * alpha, height: 13.0 * h, occlusion: if light_theme { 1.0 } else { 0.1 }, ..ht }) + .on(rounded(b, 6.0)) + .seed(2), + Anchor::Under(node::RELOAD), + ); + push( + Fx::distort(DistortParams::HeatHaze { height: 52.0, scale: 9.0, speed: 2.2, amount: 1.1 * h * alpha, whole_shape: false }).on(rounded(b, 6.0)), + Anchor::Over(node::RELOAD), + ); + } + } + + // ---- Haptic feedback: Strong means every click shakes the window. + if let Some(prev) = self.taps + && s.taps != prev + && p.haptics == 2 + && let Some(q) = i.pointer + { + self.shocks.trigger(t, q); + } + self.taps = Some(s.taps); + self.shocks.prune(t, 1.4); + for (sh, k) in self.shocks.live(t, 1.4) { + anim = true; + let at = sh.data; + let full = Shape::rounded(i.vp.x, i.vp.y, i.vp.w, i.vp.h, 0.0); + push( + Fx::distort(DistortParams::Shockwave { at, reach: 320.0, width: 22.0, amount: 13.0, chroma: 0.5, t0: sh.t0, duration: 1.15 }) + .on(full) + .opacity(k), + Anchor::Top, + ); + push( + Fx::pulse(PulseParams { + style: PulseStyle::Ripple { at }, + color: if light_ui { rgb(0x4a6cff) } else { rgb(0x8fb0ff) }, + core: if light_ui { rgb(0x8ea4ff) } else { rgb(0xffffff) }, + reach: 300.0, + width: 2.0, + t0: sh.t0, + duration: 1.0, + intensity: if light_ui { 0.6 } else { 0.35 }, + occlusion: if light_ui { 0.7 } else { 0.0 }, + ..Default::default() + }) + .on(full) + .over() + .opacity(k), + Anchor::Top, + ); + } + + // ---- Flush cache: the list spirals down the drain, with real shutter blur. + let mut flush = None; + if let (Some(t0), Some((c, _))) = (s.flush_t0, tg.cache) { + let u = t - t0; + if u <= FLUSH_SECONDS + FLUSH_REVEAL { + anim = true; + let rest = c; + let cc = center(c); + let drain = [cc[0], c.y + c.h + 36.0]; + let pose_at = move |tt: f32| -> Pose { flush_pose(tt - t0, rest, cc, drain, rm) }; + let mp = MotionBlurParams { + mode: BlurMode::Shutter, + shutter_angle: if rm { 0.0 } else { 200.0 }, + max_samples: 48, + ..Default::default() + }; + let samples = MotionSamples::from_track(&mp, rest, t, i.scale, pose_at); + flush = Some((mp, samples, rest)); + } + } + + let (lights, settings, lit) = self.lighting(i, storm, flash, flash_at, &mut anim); + Out { lays, lights, settings, lit, flush, anim } + } +} + +/// The drain: a wind-up, then an accelerating spiral that shrinks into the plughole; then the +/// emptied card fades back in where it was. +fn flush_pose(u: f32, rest: Rect, cc: [f32; 2], drain: [f32; 2], rm: bool) -> Pose { + let _ = rest; + if u <= 0.0 { + return Pose::default(); + } + if u >= FLUSH_SECONDS { + let k = smooth(0.0, FLUSH_REVEAL, u - FLUSH_SECONDS); + return Pose { opacity: k, ..Default::default() }; + } + if rm { + return Pose { opacity: 1.0 - smooth(0.0, FLUSH_SECONDS * 0.6, u), ..Default::default() }; + } + let wind = 0.2; + if u < wind { + let w = (PI * u / wind).sin(); + return Pose { rotation: -0.035 * w, scale: 1.0 + 0.02 * w, y: -3.0 * w, ..Default::default() }; + } + let v = ((u - wind) / (FLUSH_SECONDS - wind)).clamp(0.0, 1.0); + let k = v.powf(2.2); + let r0 = (cc[1] - drain[1]).abs(); + let ang = -PI * 0.5 + k * TAU * 1.1; + let r = r0 * (1.0 - k); + let x = drain[0] + r * ang.cos(); + let y = drain[1] + r * ang.sin(); + Pose { + x: x - cc[0], + y: y - cc[1], + rotation: k * TAU * 1.35, + scale: mix(1.0, 0.03, k.powf(0.75)), + opacity: 1.0 - smooth(0.8, 1.0, v), + } +} diff --git a/app/vendor/rune/examples/cursed-settings/src/gfx.rs b/app/vendor/rune/examples/cursed-settings/src/gfx.rs new file mode 100644 index 0000000..4526ffa --- /dev/null +++ b/app/vendor/rune/examples/cursed-settings/src/gfx.rs @@ -0,0 +1,581 @@ +//! The compositor: Rune builds the settings window as usual; this draws it into one HDR frame +//! with the gags' effect layers slotted under or over the elements they belong to (by mark), +//! lights the whole window with rune-light when a gag needs the lights, and resolves once with +//! dither. With nothing burning it draws the plain UI and asks for no frames. + +use std::collections::HashMap; +use std::sync::Arc; +use std::sync::atomic::{AtomicU8, Ordering}; + +use rune::compose::{Compositor, Frame, is_glyph}; +use rune::render::{Instance, KIND_RECT}; +use rune_fx::{Fx, FxFrame, FxLayer, FxOptions, FxRenderer, Rect, Shape}; +use rune_light::{Light, LightRenderer, Prim, Scene as LightScene}; + +use crate::Cursed; +use crate::gags::{Anchor, FLUSH_SECONDS, Gags, In, SRC_NODE, Targets}; +use crate::ui::{mark_material, mark_node, mat, node}; + +const HDR: wgpu::TextureFormat = wgpu::TextureFormat::Rgba16Float; + +// ---------------------------------------------------------------- GPU resources + +struct Tex { + tex: wgpu::Texture, + view: wgpu::TextureView, +} + +fn tex(device: &wgpu::Device, label: &str, size: (u32, u32), usage: wgpu::TextureUsages) -> Tex { + let tex = device.create_texture(&wgpu::TextureDescriptor { + label: Some(label), + size: wgpu::Extent3d { width: size.0, height: size.1, depth_or_array_layers: 1 }, + mip_level_count: 1, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + format: HDR, + usage, + view_formats: &[], + }); + let view = tex.create_view(&Default::default()); + Tex { tex, view } +} + +const SHADERS: &str = r#" +@group(0) @binding(0) var src: texture_2d<f32>; +@group(0) @binding(1) var<uniform> alpha: vec4f; + +struct V { @builtin(position) pos: vec4f } + +@vertex +fn vs(@builtin(vertex_index) vi: u32) -> V { + let p = vec2f(f32((vi << 1u) & 2u), f32(vi & 2u)); + var o: V; + o.pos = vec4f(p * 2.0 - 1.0, 0.0, 1.0); + return o; +} + +fn pcg(v: u32) -> u32 { + let s = v * 747796405u + 2891336453u; + let w = ((s >> ((s >> 28u) + 4u)) ^ s) * 277803737u; + return (w >> 22u) ^ w; +} +fn u01(n: u32) -> f32 { return f32(pcg(n) >> 8u) * (1.0 / 16777216.0); } +fn to_srgb(c: vec3f) -> vec3f { + let lo = c * 12.92; + let hi = 1.055 * pow(max(c, vec3f(0.0)), vec3f(1.0 / 2.4)) - 0.055; + return select(hi, lo, c <= vec3f(0.0031308)); +} +fn from_srgb(c: vec3f) -> vec3f { + let lo = c / 12.92; + let hi = pow((max(c, vec3f(0.0)) + 0.055) / 1.055, vec3f(2.4)); + return select(hi, lo, c <= vec3f(0.04045)); +} +fn dithered(pos: vec2f) -> vec3f { + let ip = vec2u(pos); + let c = textureLoad(src, vec2i(ip), 0); + let n = u01(ip.x + pcg(ip.y)) + u01(ip.x * 7919u + pcg(ip.y + 104729u)) - 1.0; + return clamp(to_srgb(clamp(c.rgb, vec3f(0.0), vec3f(1.0))) + vec3f(n / 255.0), vec3f(0.0), vec3f(1.0)); +} + +// Linear HDR scene -> 8-bit target with TPDF dither, once. +@fragment +fn fs_resolve_srgb(in: V) -> @location(0) vec4f { return vec4f(from_srgb(dithered(in.pos.xy)), 1.0); } +@fragment +fn fs_resolve_unorm(in: V) -> @location(0) vec4f { return vec4f(dithered(in.pos.xy), 1.0); } + +// The lit window (sRGB-encoded by rune-light's composite) over the linear scene. +@fragment +fn fs_blit(in: V) -> @location(0) vec4f { + let c = textureLoad(src, vec2i(in.pos.xy), 0); + return vec4f(from_srgb(c.rgb) * alpha.x, alpha.x); +} +"#; + +struct Fullscreen { + pipeline: wgpu::RenderPipeline, + bgl: wgpu::BindGroupLayout, +} + +fn fullscreen(device: &wgpu::Device, module: &wgpu::ShaderModule, entry: &str, format: wgpu::TextureFormat, blend: Option<wgpu::BlendState>) -> Fullscreen { + let bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + label: Some(entry), + entries: &[ + wgpu::BindGroupLayoutEntry { + binding: 0, + visibility: wgpu::ShaderStages::FRAGMENT, + ty: wgpu::BindingType::Texture { + sample_type: wgpu::TextureSampleType::Float { filterable: false }, + view_dimension: wgpu::TextureViewDimension::D2, + multisampled: false, + }, + count: None, + }, + wgpu::BindGroupLayoutEntry { + binding: 1, + visibility: wgpu::ShaderStages::FRAGMENT, + ty: wgpu::BindingType::Buffer { ty: wgpu::BufferBindingType::Uniform, has_dynamic_offset: false, min_binding_size: None }, + count: None, + }, + ], + }); + let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { label: Some(entry), bind_group_layouts: &[Some(&bgl)], immediate_size: 0 }); + let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { + label: Some(entry), + layout: Some(&layout), + vertex: wgpu::VertexState { module, entry_point: Some("vs"), compilation_options: Default::default(), buffers: &[] }, + primitive: Default::default(), + depth_stencil: None, + multisample: Default::default(), + fragment: Some(wgpu::FragmentState { + module, + entry_point: Some(entry), + compilation_options: Default::default(), + targets: &[Some(wgpu::ColorTargetState { format, blend, write_mask: wgpu::ColorWrites::ALL })], + }), + multiview_mask: None, + cache: None, + }); + Fullscreen { pipeline, bgl } +} + +/// Whole-frame GPU time from timestamps on the compositor's own passes, read back a couple of +/// frames later without stalling. +struct Timer { + qs: wgpu::QuerySet, + resolve: wgpu::Buffer, + read: wgpu::Buffer, + /// 0 idle, 4 written, 1 copy recorded, 2 mapping, 3 mapped. + state: Arc<AtomicU8>, + period: f32, + recording: bool, +} + +impl Timer { + fn new(device: &wgpu::Device, queue: &wgpu::Queue) -> Option<Timer> { + if !device.features().contains(wgpu::Features::TIMESTAMP_QUERY) { + return None; + } + let qs = device.create_query_set(&wgpu::QuerySetDescriptor { label: Some("cursed ts"), ty: wgpu::QueryType::Timestamp, count: 2 }); + let buf = |label, usage| device.create_buffer(&wgpu::BufferDescriptor { label: Some(label), size: 16, usage, mapped_at_creation: false }); + let resolve = buf("cursed ts resolve", wgpu::BufferUsages::QUERY_RESOLVE | wgpu::BufferUsages::COPY_SRC); + let read = buf("cursed ts read", wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ); + Some(Timer { qs, resolve, read, state: Arc::new(AtomicU8::new(0)), period: queue.get_timestamp_period(), recording: false }) + } + + /// Collects a finished reading (ms) and decides whether this frame records one. Last frame's queries are + /// resolved here, a command buffer later: Metal orders work by resource, so a resolve in the same encoder + /// can run before the final pass's end-of-pass sample lands. + fn begin(&mut self, enc: &mut wgpu::CommandEncoder) -> Option<f32> { + let mut out = None; + match self.state.load(Ordering::Acquire) { + 4 => { + enc.resolve_query_set(&self.qs, 0..2, &self.resolve, 0); + enc.copy_buffer_to_buffer(&self.resolve, 0, &self.read, 0, 16); + self.state.store(1, Ordering::Release); + } + 1 => { + self.state.store(2, Ordering::Release); + let st = self.state.clone(); + self.read.slice(..).map_async(wgpu::MapMode::Read, move |r| st.store(if r.is_ok() { 3 } else { 0 }, Ordering::Release)); + } + 3 => { + if let Ok(data) = self.read.slice(..).get_mapped_range() { + let t: &[u64] = bytemuck::cast_slice(&data); + out = (t[1] > t[0]).then(|| (t[1] - t[0]) as f32 * self.period / 1e6); + } + self.read.unmap(); + self.state.store(0, Ordering::Release); + } + _ => {} + } + self.recording = self.state.load(Ordering::Acquire) == 0; + out + } + + /// The query set when this frame records. The writes go on the compositor's own render passes: Metal may + /// overlap a resource-free marker pass with the work around it, so empty marker passes read near zero. + fn query(&self) -> Option<wgpu::QuerySet> { + self.recording.then(|| self.qs.clone()) + } + + fn end(&mut self) { + if self.recording { + self.state.store(4, Ordering::Release); + } + } +} + +struct Res { + size: (u32, u32), + format: wgpu::TextureFormat, + scene: Tex, + backdrop: Tex, + node: Tex, + base: Tex, + text: Tex, + lit: Tex, + light: Option<LightRenderer>, + fx: FxRenderer, + resolve: Fullscreen, + blit: Fullscreen, + resolve_bg: wgpu::BindGroup, + blit_bg: wgpu::BindGroup, + blit_alpha: wgpu::Buffer, + timer: Option<Timer>, +} + +impl Res { + fn new(device: &wgpu::Device, queue: &wgpu::Queue, size: (u32, u32), format: wgpu::TextureFormat, ui: &mut rune::render::Renderer) -> Res { + use wgpu::TextureUsages as U; + ui.add_format(device, HDR); + let rt = U::RENDER_ATTACHMENT | U::TEXTURE_BINDING; + let scene = tex(device, "cursed scene", size, rt | U::COPY_SRC); + let backdrop = tex(device, "cursed backdrop", size, U::TEXTURE_BINDING | U::COPY_DST); + let node = tex(device, "cursed node layer", size, rt); + let base = tex(device, "cursed base", size, rt); + let text = tex(device, "cursed text", size, rt); + let lit = tex(device, "cursed lit", size, rt); + let module = device.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some("cursed"), source: wgpu::ShaderSource::Wgsl(SHADERS.into()) }); + let resolve = fullscreen(device, &module, if format.is_srgb() { "fs_resolve_srgb" } else { "fs_resolve_unorm" }, format, None); + let blit = fullscreen(device, &module, "fs_blit", HDR, Some(wgpu::BlendState::PREMULTIPLIED_ALPHA_BLENDING)); + let blit_alpha = device.create_buffer(&wgpu::BufferDescriptor { + label: Some("cursed blit alpha"), + size: 16, + usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + }); + let bind = |f: &Fullscreen, v: &wgpu::TextureView| { + device.create_bind_group(&wgpu::BindGroupDescriptor { + label: None, + layout: &f.bgl, + entries: &[ + wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::TextureView(v) }, + wgpu::BindGroupEntry { binding: 1, resource: blit_alpha.as_entire_binding() }, + ], + }) + }; + let resolve_bg = bind(&resolve, &scene.view); + let blit_bg = bind(&blit, &lit.view); + Res { + size, + format, + light: None, + fx: FxRenderer::new(device, HDR, FxOptions { dither: false }), + timer: Timer::new(device, queue), + scene, + backdrop, + node, + base, + text, + lit, + resolve, + blit, + resolve_bg, + blit_bg, + blit_alpha, + } + } +} + +fn pass<'e>( + enc: &'e mut wgpu::CommandEncoder, + view: &'e wgpu::TextureView, + clear: Option<[f32; 4]>, + timestamp_writes: Option<wgpu::RenderPassTimestampWrites<'e>>, +) -> wgpu::RenderPass<'e> { + let load = clear.map_or(wgpu::LoadOp::Load, |c| wgpu::LoadOp::Clear(wgpu::Color { r: c[0] as f64, g: c[1] as f64, b: c[2] as f64, a: c[3] as f64 })); + enc.begin_render_pass(&wgpu::RenderPassDescriptor { + label: Some("cursed"), + color_attachments: &[Some(wgpu::RenderPassColorAttachment { + view, + depth_slice: None, + resolve_target: None, + ops: wgpu::Operations { load, store: wgpu::StoreOp::Store }, + })], + depth_stencil_attachment: None, + timestamp_writes, + occlusion_query_set: None, + multiview_mask: None, + }) +} + +// ---------------------------------------------------------------- the compositor + +#[derive(Default)] +pub struct Gfx { + res: Option<Res>, + gags: Gags, + animating: bool, + view_pending: bool, + total_gpu: (f64, u32), + frames: u32, + lit_frames: u32, + max_layers: usize, +} + +/// How a marked rect stands on the UI plane (device px). +fn prim(ins: &Instance, material: u8, s: f32) -> Option<Prim> { + if ins.fill[3] < 0.02 { + return None; + } + let a = ins.fill[3].max(1e-4); + let p = Prim::from_rune(ins.rect, ins.radii).albedo([ins.fill[0] / a, ins.fill[1] / a, ins.fill[2] / a]); + Some(match material { + mat::CARD => p.raised(5.0 * s).bevel(5.0 * s, 1.5 * s).gloss(0.45, 0.45), + mat::CONTROL => p.on(5.0 * s).raised(2.5 * s).bevel(4.0 * s, 1.2 * s).gloss(0.6, 0.35), + mat::SEL => p.raised(1.5 * s).bevel(4.0 * s, 0.8 * s).gloss(0.5, 0.4), + _ => return None, + }) +} + +impl Compositor<Cursed> for Gfx { + fn features(&self) -> wgpu::Features { + wgpu::Features::TIMESTAMP_QUERY + } + + fn animating(&self) -> bool { + self.animating || self.view_pending + } + + fn summary(&mut self, _device: &wgpu::Device) -> Option<String> { + let (sum, n) = self.total_gpu; + let gpu = if n > 0 { format!("gpu frame mean {:.3} ms over {n} timed frames", sum / n as f64) } else { "no GPU timestamps".to_owned() }; + Some(format!("cursed-settings: {gpu}; {} frames, {} lit, at most {} effect layers", self.frames, self.lit_frames, self.max_layers)) + } + + fn render(&mut self, f: &mut Frame<'_, Cursed>) { + if self.res.as_ref().is_none_or(|r| r.size != f.size || r.format != f.format) { + self.res = Some(Res::new(f.device, f.queue, f.size, f.format, f.ui)); + } + self.view_pending = false; + f.device.poll(wgpu::PollType::Poll).ok(); + let res = self.res.as_mut().unwrap(); + let gpu_ms = res.timer.as_mut().and_then(|t| t.begin(f.encoder)); + let rt = &mut *f.rt; + let scale = rt.env.scale; + let now = rt.t; + let t = now as f32; + let (w, h) = f.size; + let vp = Rect::new(0.0, 0.0, w as f32 / scale, h as f32 / scale); + let pointer = rt.pointer().map(|p| [p.0, p.1]); + + // ---- state the compositor owns: the clock, flush timing, the demo pointer + let mut dirty = false; + { + let st = &mut rt.state; + st.now = now; + if st.flush_requested { + st.flush_requested = false; + st.flush_t0 = Some(t); + dirty = true; + } + if st.flush_t0.is_some_and(|t0| t > t0 + FLUSH_SECONDS + 0.4) { + st.flush_t0 = None; + dirty = true; + } + if st.show_cursor && st.cursor != pointer { + st.cursor = pointer; + dirty = true; + } + } + if dirty { + rt.invalidate(); + self.view_pending = true; + } + + // ---- the gags + let rect = |k: &str| rt.presented(k).filter(|(r, _)| r[2] > 0.0 && r[3] > 0.0).map(|(r, a)| (Rect::new(r[0], r[1], r[2], r[3]), a)); + let targets = Targets { + fast: rect("fast-switch"), + search: rect("search"), + firewall: rect("firewall-switch"), + allowed: rect("allowed-card"), + ip: rect("ip-field"), + fence: rect("fence-switch"), + perimeter: rect("perimeter-card"), + reload: rect("reload-btn"), + cache: rect("cache-card"), + sel: rect("nav-sel"), + }; + let dark_theme = crate::ui::dark_theme(&rt.state, rt.env.system_dark); + let tint = rune_theme_opencode::kit(dark_theme).c.layer_03; + let out = self.gags.frame(&In { + s: &rt.state, + t, + now, + scale, + vp, + pointer, + dark_theme, + glass_tint: [tint.r, tint.g, tint.b], + targets, + }); + let mut anim = out.anim; + let lit_on = out.lit > 0.002; + let flushing = out.flush.is_some(); + + // ---- partition Rune's instances + let inst = &rt.instances; + let marks = &rt.marks; + let mut main: Vec<Instance> = Vec::with_capacity(inst.len()); + let (mut base, mut text, mut nodel, mut top) = (Vec::new(), Vec::new(), Vec::new(), Vec::new()); + let mut prims: Vec<Prim> = Vec::new(); + let mut first: HashMap<u16, usize> = HashMap::new(); + let mut last: HashMap<u16, usize> = HashMap::new(); + for (i, ins) in inst.iter().enumerate() { + let m = marks.get(i).copied().unwrap_or(0); + let nd = mark_node(m); + if nd == node::CURSOR { + top.push(*ins); + continue; + } + first.entry(nd).or_insert(main.len()); + if flushing && nd == node::CACHE { + nodel.push(*ins); + } else { + main.push(*ins); + if lit_on { + if is_glyph(ins) { + text.push(*ins); + } else { + base.push(*ins); + if ins.params[1] == KIND_RECT + && let Some(p) = prim(ins, mark_material(m), scale) + { + prims.push(p); + } + } + } + } + last.insert(nd, main.len()); + } + + // ---- where each effect layer goes in the main list + enum Op { + Blit, + Fx(usize), + } + let end = main.len(); + let mut ops: Vec<(usize, Op)> = Vec::new(); + if lit_on { + ops.push((end, Op::Blit)); + } + let mut lays = out.lays; + if let Some((p, samples, rest)) = out.flush { + let layer = Fx::motion_blur(p, samples).on(Shape::rounded(rest.x, rest.y, rest.w, rest.h, 8.0)).source(SRC_NODE, vp).at(t); + lays.push(crate::gags::Lay { layer, anchor: Anchor::Over(node::CACHE) }); + } + let mut layers: Vec<FxLayer> = Vec::new(); + let mut needs_bd: Vec<bool> = Vec::new(); + for l in lays { + anim |= l.layer.is_animating(); + let pos = match l.anchor { + Anchor::Under(n) => first.get(&n).copied(), + Anchor::Over(n) => last.get(&n).copied(), + Anchor::Top => Some(end), + }; + let Some(pos) = pos else { continue }; + // Lit, the window is one image: effects go on top of it. + let pos = if lit_on { end } else { pos }; + needs_bd.push(l.layer.fx.needs_backdrop()); + ops.push((pos, Op::Fx(layers.len()))); + layers.push(l.layer); + } + ops.sort_by_key(|o| o.0); + self.max_layers = self.max_layers.max(layers.len()); + + // ---- upload and draw + let clear = rt.clear_color(); + let ranges = f.ui.prepare_lists(f.device, f.queue, &mut rt.text.atlas, &[&main, &base, &text, &nodel, &top], f.size); + let sources = [&res.node.view]; + res.fx.prepare(f.device, f.queue, &FxFrame { viewport: [w, h], scale, layers: &layers, backdrop: Some(&res.backdrop.view), sources: &sources }); + let enc = &mut *f.encoder; + let tq = res.timer.as_ref().and_then(Timer::query); + let mut began = false; + let mut stamp = |end: bool| { + let first = !std::mem::replace(&mut began, true); + tq.as_ref().filter(|_| first || end).map(|q| wgpu::RenderPassTimestampWrites { + query_set: q, + beginning_of_pass_write_index: first.then_some(0), + end_of_pass_write_index: end.then_some(1), + }) + }; + if !nodel.is_empty() { + let mut p = pass(enc, &res.node.view, Some([0.0; 4]), stamp(false)); + f.ui.draw_range(&mut p, HDR, ranges[3].clone()); + } + let mut lit_drawn = false; + if lit_on { + let a = clear[3].max(1e-4); + { + let mut p = pass(enc, &res.base.view, Some([clear[0] / a, clear[1] / a, clear[2] / a, 1.0]), stamp(false)); + f.ui.draw_range(&mut p, HDR, ranges[1].clone()); + } + { + let mut p = pass(enc, &res.text.view, Some([0.0; 4]), None); + f.ui.draw_range(&mut p, HDR, ranges[2].clone()); + } + let mut lights: Vec<Light> = out.lights; + if lights.is_empty() { + // Ambient only (the brightness slider): one dark light keeps the pass running. + lights.push(Light::point(0.0, 0.0, 1.0).intensity(0.0)); + } + let mut st = out.settings; + st.time = t; + let light = res.light.get_or_insert_with(|| LightRenderer::new(f.device, f.queue, w, h, HDR)); + lit_drawn = light.render(f.device, f.queue, enc, &LightScene { prims: &prims, lights: &lights, settings: st, emission: None }, &res.base.view, &res.text.view, &res.lit.view); + f.queue.write_buffer(&res.blit_alpha, 0, bytemuck::cast_slice(&[out.lit, 0.0, 0.0, 0.0])); + self.lit_frames += 1; + } + let mut cursor = 0usize; + let mut rp = pass(enc, &res.scene.view, Some(clear), stamp(false)).forget_lifetime(); + let main_range = ranges[0].clone(); + for (pos, op) in ops { + if pos > cursor { + f.ui.draw_range(&mut rp, HDR, main_range.start + cursor as u32..main_range.start + pos as u32); + cursor = pos; + } + match op { + Op::Blit => { + if lit_drawn { + rp.set_pipeline(&res.blit.pipeline); + rp.set_bind_group(0, &res.blit_bg, &[]); + rp.draw(0..3, 0..1); + } + } + Op::Fx(i) => { + if needs_bd[i] { + drop(rp); + enc.copy_texture_to_texture( + wgpu::TexelCopyTextureInfo { texture: &res.scene.tex, mip_level: 0, origin: wgpu::Origin3d::ZERO, aspect: wgpu::TextureAspect::All }, + wgpu::TexelCopyTextureInfo { texture: &res.backdrop.tex, mip_level: 0, origin: wgpu::Origin3d::ZERO, aspect: wgpu::TextureAspect::All }, + wgpu::Extent3d { width: w, height: h, depth_or_array_layers: 1 }, + ); + rp = pass(enc, &res.scene.view, None, None).forget_lifetime(); + } + res.fx.draw_layer(&mut rp, i); + } + } + } + if cursor < end { + f.ui.draw_range(&mut rp, HDR, main_range.start + cursor as u32..main_range.end); + } + f.ui.draw_range(&mut rp, HDR, ranges[4].clone()); + drop(rp); + { + let mut p = pass(enc, f.target, Some([0.0, 0.0, 0.0, 1.0]), stamp(true)); + p.set_pipeline(&res.resolve.pipeline); + p.set_bind_group(0, &res.resolve_bg, &[]); + p.draw(0..3, 0..1); + } + if let Some(tm) = res.timer.as_mut() { + tm.end(); + } + if let Some(g) = gpu_ms { + self.total_gpu.0 += g as f64; + self.total_gpu.1 += 1; + } + self.frames += 1; + self.animating = anim; + } +} diff --git a/app/vendor/rune/examples/cursed-settings/src/icons.rs b/app/vendor/rune/examples/cursed-settings/src/icons.rs new file mode 100644 index 0000000..cca92d4 --- /dev/null +++ b/app/vendor/rune/examples/cursed-settings/src/icons.rs @@ -0,0 +1,21 @@ +//! Sidebar icons the OpenCode catalog doesn't have, drawn in its 16 point stroke style. + +use rune::Icon; + +pub static SUN: Icon = Icon { + name: "sun", + view: 16.0, + body: r#"<circle cx="8" cy="8" r="2.75" stroke="currentColor"/><path d="M8 1.5V3M8 13V14.5M1.5 8H3M13 8H14.5M3.4 3.4L4.46 4.46M11.54 11.54L12.6 12.6M3.4 12.6L4.46 11.54M11.54 4.46L12.6 3.4" stroke="currentColor"/>"#, +}; + +pub static SHIELD: Icon = Icon { + name: "shield", + view: 16.0, + body: r#"<path d="M8 1.75L13 3.5V7.5C13 10.6 10.9 13.1 8 14.25C5.1 13.1 3 10.6 3 7.5V3.5L8 1.75Z" stroke="currentColor" stroke-linejoin="round"/>"#, +}; + +pub static PERSON: Icon = Icon { + name: "person-circle", + view: 16.0, + body: r#"<circle cx="8" cy="8" r="6.25" stroke="currentColor"/><circle cx="8" cy="5.25" r="1" fill="currentColor"/><path d="M4.75 7H11.25M8 7V9.25M8 9.25L6.5 12M8 9.25L9.5 12" stroke="currentColor" stroke-linejoin="round"/>"#, +}; diff --git a/app/vendor/rune/examples/cursed-settings/src/main.rs b/app/vendor/rune/examples/cursed-settings/src/main.rs new file mode 100644 index 0000000..c8ae07c --- /dev/null +++ b/app/vendor/rune/examples/cursed-settings/src/main.rs @@ -0,0 +1,218 @@ +//! Cursed Settings: a believable settings window where every control does exactly what its +//! label says. The Firewall switch builds a wall of fire, the electric fence electrifies the +//! perimeter, Dark mode turns the lights off. Effects come from rune-fx and rune-light, drawn +//! inside Rune's frame through the compositor hook (`gfx.rs`); `gags/` decides what burns. + +#![forbid(unsafe_code)] + +mod gags; +mod gfx; +mod icons; +mod ui; + +use rune::{AppSpec, TextEdit, Tx}; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Page { + General, + Appearance, + Network, + Security, + Accessibility, + Developer, +} + +pub const PAGES: [Page; 6] = [Page::General, Page::Appearance, Page::Network, Page::Security, Page::Accessibility, Page::Developer]; + +impl Page { + fn meta(self) -> (&'static str, &'static str) { + match self { + Page::General => ("General", "general"), + Page::Appearance => ("Appearance", "appearance"), + Page::Network => ("Network", "network"), + Page::Security => ("Security", "security"), + Page::Accessibility => ("Accessibility", "accessibility"), + Page::Developer => ("Developer", "developer"), + } + } + pub fn title(self) -> &'static str { self.meta().0 } + pub fn id(self) -> &'static str { self.meta().1 } +} + +pub const APPEARANCES: [&str; 3] = ["Light", "Dark", "Auto"]; +pub const HAPTICS: [&str; 3] = ["Off", "Light", "Strong"]; + +/// Every setting, at its default. +#[derive(Clone, Debug)] +pub struct Prefs { + pub launch_at_login: bool, + pub fast_startup: bool, + pub spotlight: bool, + pub auto_update: bool, + /// 0 Light, 1 Dark, 2 Auto. + pub appearance: usize, + pub brightness: f32, + pub firewall: bool, + pub stealth: bool, + pub static_ip: bool, + pub fence: bool, + pub lock_on_sleep: bool, + pub contrast: bool, + pub reduce_transparency: bool, + pub reduce_motion: bool, + /// 0 Off, 1 Light, 2 Strong. + pub haptics: usize, + pub hot_reload: bool, + pub flushed: bool, +} + +impl Default for Prefs { + fn default() -> Self { + Prefs { + launch_at_login: true, + fast_startup: false, + spotlight: false, + auto_update: true, + appearance: 2, + brightness: 1.0, + firewall: false, + stealth: false, + static_ip: false, + fence: false, + lock_on_sleep: true, + contrast: false, + reduce_transparency: false, + reduce_motion: false, + haptics: 1, + hot_reload: false, + flushed: false, + } + } +} + +pub struct Cursed { + pub page: Page, + pub p: Prefs, + pub search: TextEdit, + pub ip: TextEdit, + /// Presses so far; the compositor turns new ones into haptic feedback at the pointer. + pub taps: u32, + /// Flush requested by the button; the compositor stamps `flush_t0` on its clock. + pub flush_requested: bool, + pub flush_t0: Option<f32>, + /// When the restore-defaults toast goes away (compositor clock). + pub toast_until: Option<f64>, + /// The compositor's clock at the last frame. + pub now: f64, + /// Demo recordings draw a pointer (`--cursor`). + pub show_cursor: bool, + pub cursor: Option<[f32; 2]>, +} + +impl Cursed { + fn new() -> Cursed { + Cursed { + page: Page::General, + p: Prefs::default(), + search: TextEdit::default(), + ip: TextEdit::new("192.168.1.42"), + taps: 0, + flush_requested: false, + flush_t0: None, + toast_until: None, + now: 0.0, + show_cursor: rune::extra_args().iter().any(|a| a == "--cursor"), + cursor: None, + } + } + + /// Everything back to its default, calmly: each gag cools down on its own envelope. + pub fn restore(&mut self) { + self.p = Prefs::default(); + self.flush_t0 = None; + self.toast_until = Some(self.now + 4.5); + } +} + +/// While the toast shows or the cache drains, time moves state forward on its own. +fn poll(s: &mut Cursed, _clock: f64, _tx: &mut Tx) -> bool { + let mut changed = false; + if s.toast_until.is_some_and(|u| s.now >= u) { + s.toast_until = None; + changed = true; + } + if let Some(t0) = s.flush_t0 + && s.now as f32 >= t0 + gags::FLUSH_SECONDS + && !s.p.flushed + { + s.p.flushed = true; + changed = true; + } + changed +} + +fn page(p: Page) -> impl Fn(&mut Cursed) { + move |s| s.page = p +} + +fn main() { + rune::run_with( + AppSpec { + title: "Settings", + size: (960.0, 660.0), + min_size: Some((860.0, 600.0)), + init: Cursed::new, + view: ui::view, + scenes: &[ + ("default", |_| {}), + ("general", |s| page(Page::General)(s)), + ("appearance", |s| page(Page::Appearance)(s)), + ("network", |s| page(Page::Network)(s)), + ("security", |s| page(Page::Security)(s)), + ("accessibility", |s| page(Page::Accessibility)(s)), + ("developer", |s| page(Page::Developer)(s)), + ("fire", |s| { + s.page = Page::Network; + s.p.firewall = true; + s.p.static_ip = true; + }), + ("fence", |s| { + s.page = Page::Security; + s.p.fence = true; + }), + ("dark", |s| { + s.page = Page::Appearance; + s.p.appearance = 1; + }), + ("spotlight", |s| s.p.spotlight = true), + ("contrast", |s| { + s.page = Page::Accessibility; + s.p.contrast = true; + }), + ("frosted", |s| { + s.page = Page::Accessibility; + s.p.reduce_transparency = true; + }), + ("hot", |s| { + s.page = Page::Developer; + s.p.hot_reload = true; + }), + ("flushed", |s| { + s.page = Page::Developer; + s.p.flushed = true; + }), + ("reduced-fire", |s| { + s.page = Page::Network; + s.p.firewall = true; + s.p.reduce_motion = true; + }), + ], + fonts: rune_theme_opencode::FONTS, + families: rune_theme_opencode::FAMILIES, + setup: None, + poll: Some(poll), + on_key: None, + }, + gfx::Gfx::default(), + ); +} diff --git a/app/vendor/rune/examples/cursed-settings/src/ui.rs b/app/vendor/rune/examples/cursed-settings/src/ui.rs new file mode 100644 index 0000000..efed57e --- /dev/null +++ b/app/vendor/rune/examples/cursed-settings/src/ui.rs @@ -0,0 +1,663 @@ +//! The settings window, in OpenCode's settings design language: a sidebar of pages, then +//! titled sections of rows with a control on the right. Nothing here knows about effects +//! except the marks that tell the compositor which element is which. + +use rune::tok::motion; +use rune::{Align, Color, Cx, Drag, El, Phase, Shape, Spring, TextStyle, Transition, Tx, canvas, col, el, icon, row, spacer, text}; +use rune_kit::{Badge, BadgeVariant, Button, ButtonVariant, ControlSize, Kit, SegmentedControl, Select, Switch, TextInput, Toast, ToastRegion}; +use rune_theme_opencode::icons as oc; + +use crate::{APPEARANCES, Cursed, HAPTICS, PAGES, Page, icons}; + +pub const SIDEBAR_W: f32 = 232.0; +const NAV_PITCH: f32 = 30.0; +const NAV_H: f32 = 28.0; + +// ---------------------------------------------------------------- marks + +/// A mark: lighting material and effect node. Bit 31 keeps every explicit mark non-zero (0 inherits). +pub fn mk(material: u8, node: u16) -> u32 { + (1 << 31) | ((material as u32) << 16) | node as u32 +} + +pub fn mark_node(m: u32) -> u16 { + (m & 0xFFFF) as u16 +} + +pub fn mark_material(m: u32) -> u8 { + ((m >> 16) & 0xFF) as u8 +} + +/// How a rect stands on the UI plane when the lights are on. +pub mod mat { + /// Flat: no occluder. + pub const NONE: u8 = 0; + pub const CARD: u8 = 1; + pub const CONTROL: u8 = 2; + pub const SEL: u8 = 3; +} + +/// Effect anchors. +pub mod node { + pub const NAV: u16 = 1; + pub const SEARCH: u16 = 2; + pub const ALLOWED: u16 = 10; + pub const IP: u16 = 11; + pub const PERIMETER: u16 = 20; + pub const RELOAD: u16 = 30; + pub const CACHE: u16 = 31; + pub const TOAST: u16 = 0xFFFE; + pub const CURSOR: u16 = 0xFFFF; +} + +// ---------------------------------------------------------------- type + +const TITLE: TextStyle = TextStyle::new(15.0, 640.0).lh(22.0); +const SECTION: TextStyle = TextStyle::new(13.0, 530.0).lh(16.0); + +/// A press that counts as a tap (haptic feedback follows taps). +fn tap(f: impl Fn(&mut Cursed) + 'static) -> impl Fn(&mut Cursed) + 'static { + move |s: &mut Cursed| { + f(s); + s.taps += 1; + } +} + +pub fn dark_theme(s: &Cursed, system_dark: bool) -> bool { + match s.p.appearance { + 0 => false, + _ => system_dark, + } +} + +pub fn view(s: &Cursed, cx: &mut Cx<Cursed>) -> El { + cx.reduced_motion(s.p.reduce_motion); + let k = rune_theme_opencode::kit(dark_theme(s, cx.system_dark())); + let hair = 1.0 / cx.env().scale; + let c = &k.c; + let mut overlays = Vec::new(); + if s.toast_until.is_some() { + let toast = Toast::new("restored", "Defaults restored") + .description("The fire department has been notified.") + .icon(k, &oc::CIRCLE_CHECK) + .build(k); + overlays.push(ToastRegion::new().toast(toast).build(k).mark(mk(mat::NONE, node::TOAST))); + } + if s.show_cursor + && let Some(p) = s.cursor + { + overlays.push(pointer(p)); + } + let base = row() + .key("window") + .fill(c.bg_base) + .child(sidebar(s, k)) + .child(el().key("sidebar-edge").w(hair).h_full().fill(c.border_base)) + .child(content(s, k, hair)); + rune_kit::root(base, overlays) +} + +// ---------------------------------------------------------------- sidebar + +fn sidebar(s: &Cursed, k: &Kit) -> El { + let c = &k.c; + let w = SIDEBAR_W - 24.0; + let idx = PAGES.iter().position(|p| *p == s.page).unwrap_or(0); + let mut nav = el() + .key("nav") + .w(w) + .h(PAGES.len() as f32 * NAV_PITCH) + .mark(mk(mat::NONE, node::NAV)) + .child( + el().key("nav-sel") + .absolute(0.0, idx as f32 * NAV_PITCH) + .size(w, NAV_H) + .radius(6.0) + .fill(c.layer_03) + .lead(motion::LEAD, motion::DEFAULT) + .mark(mk(mat::SEL, node::NAV)), + ); + for (i, p) in PAGES.into_iter().enumerate() { + let selected = i == idx; + let glyph = match p { + Page::General => &oc::SETTINGS_GEAR, + Page::Appearance => &icons::SUN, + Page::Network => &oc::GLOBE, + Page::Security => &icons::SHIELD, + Page::Accessibility => &icons::PERSON, + Page::Developer => &oc::CONSOLE, + }; + nav = nav.child( + row() + .key(format!("nav-{}", p.id())) + .role("tab") + .label(p.title()) + .absolute(0.0, i as f32 * NAV_PITCH) + .size(w, NAV_H) + .px(8.0) + .gap(8.0) + .center_y() + .radius(6.0) + .hover(if selected { Color::TRANSPARENT } else { c.hover }) + .on_press(tap(move |s: &mut Cursed| s.page = p)) + .child(icon(glyph, 16.0).key("icon").color(if selected { c.icon_base } else { c.icon_muted })) + .child(text(p.title()).key("label").font(k.ty.ui).color(if selected { c.text_base } else { c.text_muted })), + ); + } + col() + .key("sidebar") + .w(SIDEBAR_W) + .h_full() + .fill(c.page) + .px(12.0) + .pt(20.0) + .pb(16.0) + .gap(16.0) + .child( + TextInput::new(&s.search) + .placeholder("Search") + .leading_icon(&oc::MAGNIFYING_GLASS) + .width(Some(w)) + .on_edit(|s: &mut Cursed| &mut s.search) + .build(k) + .key("search") + .mark(mk(mat::CONTROL, node::SEARCH)), + ) + .child(nav) + .child(spacer()) + .child( + Button::new("Restore Defaults") + .variant(ButtonVariant::Neutral) + .on_press(tap(|s: &mut Cursed| s.restore())) + .build(k) + .key("restore") + .mark(mk(mat::CONTROL, 0)), + ) +} + +// ---------------------------------------------------------------- content + +fn content(s: &Cursed, k: &Kit, hair: f32) -> El { + let page = match s.page { + Page::General => general(s, k, hair), + Page::Appearance => appearance(s, k, hair), + Page::Network => network(s, k, hair), + Page::Security => security(s, k, hair), + Page::Accessibility => accessibility(s, k, hair), + Page::Developer => developer(s, k, hair), + }; + col().key("content").grow(1.0).h_full().fill(k.c.bg_base).child( + page.key(format!("page-{}", s.page.id())) + .w_full() + .px(40.0) + .pt(32.0) + .gap(24.0) + .transition(Transition::asymmetric(Transition::opacity(), Transition::identity())) + .opacity_motion(Spring::new(0.18, 0.0)), + ) +} + +fn header(k: &Kit, title: &str, desc: &str) -> El { + col() + .key("header") + .gap(2.0) + .child(text(title).key("title").font(TITLE).color(k.c.text_base)) + .child(text(desc).key("desc").font(k.ty.ui).color(k.c.text_muted)) +} + +/// A titled list of rows with hairlines between them. `node` anchors effects to the card. +fn section(k: &Kit, hair: f32, key: &str, title: &str, trailing: Option<El>, node: u16, rows: Vec<El>) -> El { + let c = &k.c; + let mut inner = col().key("rows").w_full().mark(mk(mat::NONE, node)); + let n = rows.len(); + for (i, r) in rows.into_iter().enumerate() { + inner = inner.child(r); + if i + 1 < n { + inner = inner.child(el().key(format!("sep{i}")).h(hair).w_full().fill(c.border_base)); + } + } + let mut head = row().key("head").w_full().h(24.0).center_y().justify_between().child(text(title).key("title").font(SECTION).color(c.text_base)); + if let Some(t) = trailing { + head = head.child(t); + } + col().key(key).w_full().gap(10.0).child(head).child( + col() + .key(format!("{key}-card")) + .w_full() + .radius(8.0) + .fill(c.layer_01) + .border(0.5, c.border_muted) + .px(16.0) + .mark(mk(mat::CARD, node)) + .child(inner), + ) +} + +fn setting(k: &Kit, key: &str, title: &str, desc: &str, control: El) -> El { + row() + .key(key) + .w_full() + .py(12.0) + .gap(16.0) + .center_y() + .child( + col() + .key("copy") + .grow(1.0) + .shrink() + .gap(1.0) + .child(text(title).key("title").font(k.ty.ui_medium).color(k.c.text_base)) + .child(text(desc).key("desc").font(k.ty.ui).color(k.c.text_muted)), + ) + .child(control) +} + +fn switch(k: &Kit, key: &str, on: bool, label: &str, flip: impl Fn(&mut Cursed) + 'static) -> El { + Switch::new(on).label(label).hide_label().on_toggle(tap(flip)).build(k).key(key).mark(mk(mat::CONTROL, 0)) +} + +fn toggle_row(k: &Kit, key: &str, title: &str, desc: &str, on: bool, flip: impl Fn(&mut Cursed) + 'static) -> El { + setting(k, key, title, desc, switch(k, &format!("{key}-switch"), on, title, flip)) +} + +/// A plain row: a name with a trailing value. +fn item(k: &Kit, key: &str, lead: El, name: &str, trailing: El) -> El { + row() + .key(key) + .w_full() + .h(44.0) + .gap(10.0) + .center_y() + .child(lead) + .child(text(name).key("name").font(k.ty.ui_medium).color(k.c.text_base).grow(1.0)) + .child(trailing) +} + +fn app_tile(key: &str, letter: &str, color: Color) -> El { + row() + .key(key) + .size(22.0, 22.0) + .radius(5.5) + .fill(color) + .center() + .child(text(letter).key("letter").font(TextStyle::new(11.0, 640.0)).color(Color::WHITE)) +} + +fn muted(k: &Kit, key: &str, s: &str) -> El { + text(s).key(key).font(k.ty.ui).color(k.c.text_muted) +} + +fn hx(h: u32) -> Color { + rune::color::hex(&format!("#{h:06x}")).unwrap_or(Color::BLACK) +} + +// ---------------------------------------------------------------- pages + +fn general(s: &Cursed, k: &Kit, hair: f32) -> El { + let p = &s.p; + let mut layer = Vec::new(); + col() + .child(header(k, "General", "Startup, search and updates.")) + .child(section( + k, + hair, + "startup", + "Startup", + None, + 0, + vec![ + toggle_row(k, "login", "Launch at login", "Open OpenCode when you log in.", p.launch_at_login, |s| { + s.p.launch_at_login = !s.p.launch_at_login + }), + toggle_row(k, "fast", "Lightning-fast startup", "Skip the splash screen and open instantly.", p.fast_startup, |s| { + s.p.fast_startup = !s.p.fast_startup + }), + ], + )) + .child(section( + k, + hair, + "search", + "Search", + None, + 0, + vec![ + toggle_row(k, "spotlight", "Show in Spotlight", "Let Spotlight find your sessions and settings.", p.spotlight, |s| { + s.p.spotlight = !s.p.spotlight + }), + setting( + k, + "language", + "Language", + "Used for menus and messages.", + Select::new("lang", &["English"]).current(Some("English")).build(k, &mut layer), + ), + ], + )) + .child(section( + k, + hair, + "updates", + "Updates", + None, + 0, + vec![toggle_row(k, "updates", "Automatic updates", "Download and install updates in the background.", p.auto_update, |s| { + s.p.auto_update = !s.p.auto_update + })], + )) +} + +fn appearance(s: &Cursed, k: &Kit, hair: f32) -> El { + let p = &s.p; + col() + .child(header(k, "Appearance", "How OpenCode looks.")) + .child(section( + k, + hair, + "theme", + "Theme", + None, + 0, + vec![ + setting( + k, + "mode", + "Appearance", + "Match the system, or pick one.", + SegmentedControl::new(&APPEARANCES, Some(p.appearance)) + .width(Some(204.0)) + .on_pick(|s: &mut Cursed, i: usize, tx: &mut Tx| { + s.p.appearance = i; + s.taps += 1; + tx.color_motion(Spring::new(0.4, 0.0)); + }) + .build(k) + .key("mode-control") + .mark(mk(mat::CONTROL, 0)), + ), + setting(k, "brightness", "Brightness", "How bright the window is.", slider(k, p.brightness)), + ], + )) + .child(section( + k, + hair, + "text", + "Text", + None, + 0, + vec![ + setting(k, "size", "Text size", "Used across the app.", Select::new("size", &["13 pt"]).current(Some("13 pt")).build(k, &mut Vec::new())), + setting(k, "font", "Code font", "Used in diffs and the terminal.", Select::new("font", &["IBM Plex Mono"]).current(Some("IBM Plex Mono")).build(k, &mut Vec::new())), + ], + )) +} + +fn network(s: &Cursed, k: &Kit, hair: f32) -> El { + let p = &s.p; + let allow = |key: &str, letter: &str, col_: u32, name: &str| { + item(k, key, app_tile("tile", letter, hx(col_)), name, muted(k, "state", "Allow incoming connections")) + }; + col() + .child(header(k, "Network", "Firewall and addresses.")) + .child(section( + k, + hair, + "firewall", + "Firewall", + None, + 0, + vec![toggle_row(k, "firewall", "Firewall", "Block incoming connections from unknown apps.", p.firewall, |s| { + s.p.firewall = !s.p.firewall + })], + )) + .child(section( + k, + hair, + "allowed", + "Allowed apps", + None, + crate::ui::node::ALLOWED, + vec![ + allow("opencode", "O", 0x1d1d1f, "OpenCode"), + allow("rune", "R", 0x6d4aff, "Rune"), + allow("display", "S", 0x2f80ed, "Studio Display Updater"), + ], + )) + .child(section( + k, + hair, + "address", + "Address", + None, + 0, + vec![ + toggle_row(k, "static", "Static IP", "Use a fixed address instead of DHCP.", p.static_ip, |s| s.p.static_ip = !s.p.static_ip), + setting( + k, + "ip", + "IP address", + "This Mac's address on the local network.", + TextInput::new(&s.ip) + .width(Some(168.0)) + .disabled(!p.static_ip) + .on_edit(|s: &mut Cursed| &mut s.ip) + .build(k) + .key("ip-field") + .mark(mk(mat::CONTROL, node::IP)), + ), + ], + )) +} + +fn security(s: &Cursed, k: &Kit, hair: f32) -> El { + let p = &s.p; + let door = |key: &str, name: &str, state: &str| { + item( + k, + key, + el().key("dot").size(8.0, 8.0).radius(4.0).fill(k.c.success.icon).ml(7.0).mr(7.0), + name, + Badge::new(state).variant(BadgeVariant::Subtle).build(k), + ) + }; + col() + .child(header(k, "Security", "Locks, passwords and the perimeter.")) + .child(section( + k, + hair, + "protection", + "Protection", + None, + 0, + vec![ + toggle_row(k, "fence", "Electric fence", "Protect the perimeter of your network.", p.fence, |s| s.p.fence = !s.p.fence), + toggle_row(k, "sleep", "Require password after sleep", "Ask for your password when the display wakes.", p.lock_on_sleep, |s| { + s.p.lock_on_sleep = !s.p.lock_on_sleep + }), + ], + )) + .child(section( + k, + hair, + "perimeter", + "Perimeter", + None, + node::PERIMETER, + vec![ + door("front", "Front door", "Locked"), + door("back", "Back door", "Locked"), + door("ssh", "Port 22", "Closed"), + door("server", "Port 4096", "OpenCode only"), + ], + )) +} + +fn accessibility(s: &Cursed, k: &Kit, hair: f32) -> El { + let p = &s.p; + col() + .child(header(k, "Accessibility", "Display, motion and feedback.")) + .child(section( + k, + hair, + "display", + "Display", + None, + 0, + vec![ + toggle_row(k, "contrast", "Increase contrast", "Make edges and text stand out more.", p.contrast, |s| s.p.contrast = !s.p.contrast), + toggle_row(k, "transparency", "Reduce transparency", "Make glass surfaces solid.", p.reduce_transparency, |s| { + s.p.reduce_transparency = !s.p.reduce_transparency + }), + ], + )) + .child(section( + k, + hair, + "motion", + "Motion", + None, + 0, + vec![toggle_row(k, "reduce", "Reduce motion", "Calmer, shorter animations.", p.reduce_motion, |s| { + s.p.reduce_motion = !s.p.reduce_motion + })], + )) + .child(section( + k, + hair, + "feedback", + "Feedback", + None, + 0, + vec![setting( + k, + "haptics", + "Haptic feedback", + "How strongly clicks are felt.", + SegmentedControl::new(&HAPTICS, Some(p.haptics)) + .width(Some(204.0)) + .on_pick(|s: &mut Cursed, i: usize, _: &mut Tx| { + s.p.haptics = i; + s.taps += 1; + }) + .build(k) + .key("haptics-control") + .mark(mk(mat::CONTROL, 0)), + )], + )) +} + +fn developer(s: &Cursed, k: &Kit, hair: f32) -> El { + let p = &s.p; + let c = &k.c; + let mut reload = Button::new("Reload now").on_press(tap(|_: &mut Cursed| {})).build(k).key("reload-btn").mark(mk(mat::CONTROL, node::RELOAD)); + if p.hot_reload { + reload = reload.fill(hx(0xd8401a)).motion(Spring::new(1.6, 0.0)); + } else { + reload = reload.motion(Spring::new(2.0, 0.0)); + } + let size = |key: &str, name: &str, v: &str| item(k, key, icon(&oc::FOLDER, 16.0).key("icon").color(c.icon_muted).ml(3.0).mr(3.0), name, muted(k, "size", v)); + let rows = if p.flushed { + vec![row().key("empty").w_full().h(44.0).center_y().child(muted(k, "label", "Nothing cached."))] + } else { + vec![ + size("shaders", "Shader cache", "1.2 GB"), + size("thumbs", "Thumbnails", "640 MB"), + size("snapshots", "Session snapshots", "512 MB"), + ] + }; + let flush = Button::new("Flush cache") + .control_size(ControlSize::Regular) + .disabled(p.flushed || s.flush_t0.is_some()) + .on_press(tap(|s: &mut Cursed| s.flush_requested = true)) + .build(k) + .key("flush-btn") + .mark(mk(mat::CONTROL, 0)); + col() + .child(header(k, "Developer", "Builds, reloads and caches.")) + .child(section( + k, + hair, + "reloading", + "Reloading", + None, + 0, + vec![ + toggle_row(k, "hot", "Hot reload", "Reload the app when files change.", p.hot_reload, |s| s.p.hot_reload = !s.p.hot_reload), + setting(k, "reload", "Reload renderer", "Rebuild shaders and reload the window.", reload), + ], + )) + .child(section( + k, + hair, + "cache", + if p.flushed { "Cache · Zero KB" } else { "Cache · 2.4 GB" }, + Some(flush), + node::CACHE, + rows, + )) +} + +// ---------------------------------------------------------------- controls + +fn slider(k: &Kit, v: f32) -> El { + let c = &k.c; + let (w, h, kd, bar) = (168.0, 20.0, 16.0, 4.0); + let travel = w - kd; + let to_value = move |x: f32| ((x - kd / 2.0) / travel).clamp(0.0, 1.0); + row() + .key("brightness-control") + .gap(10.0) + .center_y() + .child(icon(&icons::SUN, 14.0).key("dim").color(c.icon_faint)) + .child( + el().key("brightness-slider") + .role("slider") + .label("Brightness") + .size(w, h) + .motion(motion::SNAPPY) + .on_drag(move |s: &mut Cursed, d: &mut Drag, tx: &mut Tx| { + let knob = kd / 2.0 + s.p.brightness * travel; + match d.phase { + Phase::Down => { + d.data = s.p.brightness; + if (d.x - knob).abs() > kd / 2.0 + 3.0 { + s.p.brightness = to_value(d.x); + } + } + Phase::Move => { + let knob = kd / 2.0 + d.data * travel; + let grab = if (d.start_x - knob).abs() <= kd / 2.0 + 3.0 { d.start_x - knob } else { 0.0 }; + s.p.brightness = to_value(d.x - grab); + tx.instant(); + } + Phase::Up => { if d.cancelled() { s.p.brightness = d.data; } } + } + }) + .child(el().key("track").size(w, bar).absolute(0.0, (h - bar) / 2.0).radius(bar / 2.0).fill(c.layer_04)) + .child(el().key("fill").size(kd / 2.0 + v * travel, bar).absolute(0.0, (h - bar) / 2.0).radius(bar / 2.0).fill(c.icon_base)) + .child( + el().key("knob") + .size(kd, kd) + .absolute(v * travel, (h - kd) / 2.0) + .radius(kd / 2.0) + .fill(c.knob_on) + .border(0.5, c.border_strong) + .shadow(1.0, 3.0, k.dark_a(0.18)) + .mark(mk(mat::CONTROL, 0)), + ), + ) + .child(icon(&icons::SUN, 18.0).key("bright").color(c.icon_muted)) + .child(text(format!("{:.0}%", v * 100.0)).key("value").w(36.0).font(k.ty.ui).color(c.text_muted).align(Align::End)) +} + +/// The demo pointer: a black arrow with a white keyline, tip at `p`. +fn pointer(p: [f32; 2]) -> El { + let arrow = [[0.0, 0.0], [0.0, 16.5], [4.1, 12.7], [6.9, 19.2], [9.4, 18.1], [6.7, 11.8], [12.2, 11.8]]; + let mut ring = arrow.to_vec(); + ring.push(arrow[0]); + canvas(Shape::new().fill(arrow.to_vec(), Color::BLACK).stroke(ring, 1.3, Color::WHITE)) + .key("demo-pointer") + .size(14.0, 21.0) + .absolute(p[0], p[1]) + .mark(mk(mat::NONE, node::CURSOR)) +} diff --git a/app/vendor/rune/examples/drag-out/Cargo.toml b/app/vendor/rune/examples/drag-out/Cargo.toml new file mode 100644 index 0000000..97554f3 --- /dev/null +++ b/app/vendor/rune/examples/drag-out/Cargo.toml @@ -0,0 +1,11 @@ +[package] +name = "drag-out" +version = "0.0.1" +edition.workspace = true +license.workspace = true + +[dependencies] +rune = { workspace = true, default-features = true, features = ["keys-overlay"] } + +[lints] +workspace = true diff --git a/app/vendor/rune/examples/drag-out/src/main.rs b/app/vendor/rune/examples/drag-out/src/main.rs new file mode 100644 index 0000000..ce84a53 --- /dev/null +++ b/app/vendor/rune/examples/drag-out/src/main.rs @@ -0,0 +1,84 @@ +//! Drag a file, an app bundle or a line of text out of a Rune window into Finder, System +//! Settings or a text field. `cargo run -p drag-out`; set `DRAG_OUT_APP` to drag a different +//! app bundle. A tile dims while it's dragged; each drag's end prints +//! `drag-end <tile> <outcome>`. + +#![forbid(unsafe_code)] + +use std::path::PathBuf; + +use rune::tok::{self, radius, space, type_}; +use rune::{AppSpec, Cursor, Cx, DragItem, DragOutcome, El, col, row, text}; + +struct State { + file: PathBuf, + app: PathBuf, + last: Option<(&'static str, DragOutcome)>, + dragging: Option<&'static str>, +} + +fn tile(s: &State, key: &'static str, title: &str, detail: String, item: fn(&State) -> DragItem) -> El { + let t = tok::theme(true); + col().key(key).role("button").size(150.0, 92.0).padding(space::S3).gap(space::S1).radius(radius::LG) + .fill(t.card).border(1.0, t.card_border).hover(t.hover).press(t.press).cursor(Cursor::Grab) + .opacity(if s.dragging == Some(key) { 0.28 } else { 1.0 }) + .child(text(title).font(type_::TITLE).color(t.text)) + .child(text(detail).font(type_::LABEL).color(t.text_secondary)) + .drag_out(move |s: &State| Some(item(s).opaque(tok::theme(true).bg))) + .on_drag_start(move |s: &mut State, _| s.dragging = Some(key)) + .on_drag_end(move |s: &mut State, outcome, _| { + println!("drag-end {key} {outcome:?}"); + s.dragging = None; + s.last = Some((key, outcome)); + }) +} + +fn name(path: &std::path::Path) -> String { + path.file_name().map_or_else(|| path.display().to_string(), |n| n.to_string_lossy().into_owned()) +} + +fn view(s: &State, _: &mut Cx<State>) -> El { + let t = tok::theme(true); + let status = match s.last { + Some((key, outcome)) => format!("Last drag: {key}, {outcome:?}"), + None => "Drag a tile out of the window".into(), + }; + col().w_full().h_full().center().gap(space::S6).fill(t.bg) + .child(row().gap(space::S3) + .child(tile(s, "file", "A file", name(&s.file), |s| DragItem::new().file(&s.file))) + .child(tile(s, "app", "An app", name(&s.app), |s| DragItem::new().file(&s.app))) + .child(tile(s, "text", "Some text", "Hello from Rune".into(), |_| DragItem::new().text("Hello from Rune")))) + .child(text(status).key("status").font(type_::BODY).color(t.text_secondary)) +} + +fn initial() -> State { + let file = std::env::temp_dir().join("Dragged out of Rune.txt"); + std::fs::write(&file, "This file was dragged out of a Rune window.\n").ok(); + let app = std::env::var_os("DRAG_OUT_APP").map_or_else(|| PathBuf::from("/System/Applications/Calculator.app"), PathBuf::from); + State { file, app, last: None, dragging: None } +} + +fn main() { + rune::run(AppSpec::new("Drag Out", (520.0, 200.0), initial, view)); +} + +#[cfg(test)] +mod tests { + use super::*; + use rune::{Env, Runtime}; + + #[test] + fn dragging_a_tile_hands_its_file_to_the_system() { + let state = State { file: "/tmp/a.txt".into(), app: "/Applications/Example.app".into(), last: None, dragging: None }; + let mut rt = Runtime::new(state, view, (520.0, 200.0), Env { system_dark: true, scale: 2.0 }); + rt.frame(0.0); + let (x, y) = rt.find("app").unwrap(); + rt.pointer_move(x, y); + rt.pointer_down(x, y); + rt.pointer_move(x + 20.0, y); + assert!(rt.events.iter().any(|e| e.starts_with("drag-out ") && e.ends_with("app")), "{:?}", rt.events); + rt.frame(0.0); + // No system took the drag here, so it ends Cancelled in the same frame it started. + assert_eq!((rt.state.dragging, rt.state.last), (None, Some(("app", DragOutcome::Cancelled)))); + } +} diff --git a/app/vendor/rune/examples/drop-files/Cargo.toml b/app/vendor/rune/examples/drop-files/Cargo.toml new file mode 100644 index 0000000..5b14bd3 --- /dev/null +++ b/app/vendor/rune/examples/drop-files/Cargo.toml @@ -0,0 +1,11 @@ +[package] +name = "drop-files" +version = "0.0.1" +edition.workspace = true +license.workspace = true + +[dependencies] +rune = { workspace = true, default-features = true, features = ["keys-overlay"] } + +[lints] +workspace = true diff --git a/app/vendor/rune/examples/drop-files/scripts/drop.json b/app/vendor/rune/examples/drop-files/scripts/drop.json new file mode 100644 index 0000000..b7a06e6 --- /dev/null +++ b/app/vendor/rune/examples/drop-files/scripts/drop.json @@ -0,0 +1,8 @@ +[ + {"t": 0.1, "drag_files": {"paths": ["photo.png", "notes.txt"], "key": "anything"}}, + {"t": 0.3, "drag_files": {"paths": ["photo.png", "notes.txt"], "key": "pictures"}}, + {"t": 0.5, "drop_files": {"paths": ["photo.png", "notes.txt"], "key": "pictures"}}, + {"t": 0.7, "drop_files": {"paths": ["notes.txt"], "key": "pictures", "hover": 0.2}}, + {"t": 1.1, "drag_files": {"paths": ["song.m4a"], "key": "anything"}}, + {"t": 1.3, "drag_files": "leave"} +] diff --git a/app/vendor/rune/examples/drop-files/src/main.rs b/app/vendor/rune/examples/drop-files/src/main.rs new file mode 100644 index 0000000..a23a6a3 --- /dev/null +++ b/app/vendor/rune/examples/drop-files/src/main.rs @@ -0,0 +1,93 @@ +//! Drop files into a Rune window from Finder, Explorer or a file manager. `cargo run -p +//! drop-files`. The pictures zone takes images only; the other zone takes anything; a drop +//! anywhere else lands on the window. Each drop prints `drop <target> <files>`. +//! +//! Headless, with the highlight held before each drop: +//! `cargo run -p drop-files -- --script examples/drop-files/scripts/drop.json --frames 90 --every 6 --cols 5 --strip strip.png` + +#![forbid(unsafe_code)] + +use std::path::PathBuf; + +use rune::tok::{self, radius, space, type_}; +use rune::{AppSpec, Color, Cx, El, col, row, text}; + +#[derive(Default)] +struct State { + /// The zone a file drag is over. + over: Option<&'static str>, + last: Option<(&'static str, Vec<PathBuf>)>, +} + +fn names(files: &[PathBuf]) -> String { + files.iter().map(|f| f.file_name().map_or_else(|| f.display().to_string(), |n| n.to_string_lossy().into_owned())) + .collect::<Vec<_>>().join(", ") +} + +fn dropped(s: &mut State, target: &'static str, files: &[PathBuf]) { + println!("drop {target} {}", names(files)); + s.last = Some((target, files.to_vec())); +} + +fn zone(s: &State, accent: Color, key: &'static str, title: &str, detail: &str) -> El { + let t = tok::theme(true); + let over = s.over == Some(key); + col().key(key).size(200.0, 120.0).padding(space::S3).gap(space::S1).radius(radius::LG).center() + .fill(if over { accent.alpha(0.18) } else { t.card }) + .border(if over { 2.0 } else { 1.0 }, if over { accent } else { t.card_border }) + .child(text(title).font(type_::TITLE).color(t.text)) + .child(text(detail).font(type_::LABEL).color(t.text_secondary)) + .on_drop_files(move |s: &mut State, files, _| dropped(s, key, files)) + .on_drop_hover(move |s: &mut State, over, _| { + if over { s.over = Some(key) } else if s.over == Some(key) { s.over = None } + }) +} + +fn view(s: &State, cx: &mut Cx<State>) -> El { + let t = tok::theme(true); + let accent = cx.accent(); + let status = match &s.last { + Some((target, files)) => format!("Dropped on {target}: {}", names(files)), + None => "Drag files from another app onto a zone".into(), + }; + col().w_full().h_full().center().gap(space::S6).fill(t.bg) + .child(row().gap(space::S3) + .child(zone(s, accent, "pictures", "Pictures", "PNG, JPEG, GIF or HEIC") + .accepts_extensions(&["png", "jpg", "jpeg", "gif", "heic"])) + .child(zone(s, accent, "anything", "Anything", "Any file"))) + .child(text(status).key("status").font(type_::BODY).color(t.text_secondary)) + .on_drop_files(|s: &mut State, files, _| dropped(s, "window", files)) +} + +fn main() { + rune::run(AppSpec::new("Drop Files", (520.0, 240.0), State::default, view)); +} + +#[cfg(test)] +mod tests { + use super::*; + use rune::{Env, Runtime}; + + fn run() -> Runtime<State> { + let mut rt = Runtime::new(State::default(), view, (520.0, 240.0), Env { system_dark: true, scale: 2.0 }); + rt.frame(0.0); + rt + } + + #[test] + fn pictures_go_to_the_pictures_zone_and_the_rest_to_the_zone_around_them() { + let mut rt = run(); + let at = rt.find("pictures"); + rt.drag_files(vec!["a.png".into(), "notes.txt".into()], at); + rt.frame(1.0 / 60.0); + assert_eq!(rt.state.over, Some("pictures"), "the zone lights up under the drag"); + rt.drop_files(vec!["a.png".into(), "notes.txt".into()], at); + rt.frame(2.0 / 60.0); + assert_eq!(rt.state.over, None); + assert_eq!(rt.state.last, Some(("pictures", vec!["a.png".into()]))); + + rt.drop_files(vec!["notes.txt".into()], at); + rt.frame(3.0 / 60.0); + assert_eq!(rt.state.last, Some(("window", vec!["notes.txt".into()])), "the window takes what the zone refuses"); + } +} diff --git a/app/vendor/rune/examples/frosted-bar/Cargo.toml b/app/vendor/rune/examples/frosted-bar/Cargo.toml new file mode 100644 index 0000000..1c2130d --- /dev/null +++ b/app/vendor/rune/examples/frosted-bar/Cargo.toml @@ -0,0 +1,11 @@ +[package] +name = "frosted-bar" +version = "0.0.1" +edition.workspace = true +license.workspace = true + +[dependencies] +rune = { workspace = true, default-features = true, features = ["keys-overlay"] } + +[lints] +workspace = true diff --git a/app/vendor/rune/examples/frosted-bar/scroll.json b/app/vendor/rune/examples/frosted-bar/scroll.json new file mode 100644 index 0000000..8efc831 --- /dev/null +++ b/app/vendor/rune/examples/frosted-bar/scroll.json @@ -0,0 +1,6 @@ +[ + {"t": 0.2, "type": "scroll", "key": "list", "dy": -600, "dur": 1.0}, + {"t": 1.4, "type": "scroll", "key": "list", "dy": 400, "dur": 0.8}, + {"t": 2.4, "type": "scroll", "key": "list", "dy": -900, "dur": 1.2}, + {"t": 3.8, "type": "mark", "name": "end"} +] diff --git a/app/vendor/rune/examples/frosted-bar/src/main.rs b/app/vendor/rune/examples/frosted-bar/src/main.rs new file mode 100644 index 0000000..b78d213 --- /dev/null +++ b/app/vendor/rune/examples/frosted-bar/src/main.rs @@ -0,0 +1,97 @@ +//! A long list scrolling under a frosted bottom bar: `El::backdrop_blur` blurs the rows behind +//! the bar each frame, and the bar's fill tints the blur. +//! +//! ```sh +//! cargo run -p frosted-bar --release +//! cargo run -p frosted-bar -- --snap bar.png --scale 2 --theme dark +//! cargo run -p frosted-bar --profile perf -- --script examples/frosted-bar/scroll.json --frames 480 --fps 120 --scale 2 +//! ``` +//! +//! The bar blurs at σ 8 pt under a light tint. `--scene strong` blurs at σ 20 pt under a +//! heavier tint; `--scene plain` draws the bar with its tint alone, for comparison. + +#![forbid(unsafe_code)] + +use rune::tok::{self, type_}; +use rune::{AppSpec, Cx, El, ScrollSpec, TextStyle, col, el, oklch, oklcha, row, text}; + +const BAR: f32 = 60.0; +const TABS: [&str; 4] = ["Inbox", "Today", "Later", "Done"]; + +#[derive(Default, Clone, Copy, PartialEq)] +enum Look { + #[default] + Soft, + Strong, + Plain, +} + +#[derive(Default)] +struct State { + tab: usize, + look: Look, +} + +fn list_row(i: usize, dark: bool) -> El { + let t = tok::theme(dark); + let hue = (i as f32 * 47.0) % 360.0; + let swatch = el().size(40.0, 40.0).radius(12.0).fill(oklch(if dark { 0.62 } else { 0.7 }, 0.16, hue)); + let lines = col().grow(1.0).gap(3.0) + .child(text(format!("Item {}", i + 1)).font(type_::TITLE).color(t.text)) + .child(text(format!("A row that scrolls under the bar, hue {hue:.0}")).font(type_::BODY).color(t.text_secondary)); + row().w_full().px(16.0).py(10.0).gap(12.0).center_y().child(swatch).child(lines) +} + +fn tab(i: usize, s: &State, dark: bool) -> El { + let t = tok::theme(dark); + let on = s.tab == i; + col().key(TABS[i]).role("button").label(TABS[i]).hit().grow(1.0).h_full().center().gap(4.0) + .on_press(move |s: &mut State| s.tab = i) + .child(el().size(22.0, 4.0).radius(2.0).fill(if on { tok::accent(0, dark) } else { t.control_off })) + .child(text(TABS[i]).font(TextStyle::new(11.0, if on { 650.0 } else { 500.0 })) + .color(if on { t.text } else { t.text_secondary })) +} + +fn view(s: &State, cx: &mut Cx<State>) -> El { + let dark = cx.system_dark(); + let t = tok::theme(dark); + let rows = col().w_full().pb(BAR).children((0..60).map(|i| list_row(i, dark))); + let list = col().key("list").w_full().h_full().scroll(ScrollSpec { stick_bottom: false }).child(rows); + let (sigma, alpha) = match s.look { + Look::Soft => (8.0, if dark { 0.4 } else { 0.45 }), + Look::Strong => (20.0, if dark { 0.55 } else { 0.6 }), + Look::Plain => (0.0, if dark { 0.4 } else { 0.45 }), + }; + let tint = if dark { oklcha(0.2, 0.005, 265.0, alpha) } else { oklcha(0.98, 0.003, 265.0, alpha) }; + let hairline = el().w_full().h(0.5).fill(t.separator); + let bar = col().key("bar").pin(Some(0.0), None, Some(0.0), Some(0.0)).h(BAR) + .backdrop_blur(sigma).fill(tint) + .child(hairline) + .child(row().w_full().grow(1.0).children((0..TABS.len()).map(|i| tab(i, s, dark)))); + el().w_full().h_full().fill(t.bg).child(list).child(bar) +} + +fn main() { + rune::run(AppSpec::<State> { + scenes: &[("strong", |s| s.look = Look::Strong), ("plain", |s| s.look = Look::Plain)], + ..AppSpec::new("Frosted bar", (390.0, 640.0), State::default, view) + }); +} + +#[cfg(test)] +mod tests { + use super::*; + use rune::{Env, Runtime, render::KIND_BACKDROP_BLUR}; + + #[test] + fn the_bar_blurs_and_a_tab_takes_a_tap() { + let mut rt = Runtime::new(State::default(), view, (390.0, 640.0), Env::new(true, 2.0)); + rt.frame(0.0); + assert_eq!(rt.instances.iter().filter(|i| i.params[1] == KIND_BACKDROP_BLUR).count(), 1); + let (x, y) = rt.find("Later").unwrap(); + rt.pointer_down(x, y); + rt.pointer_up(x, y); + rt.frame(1.0 / 60.0); + assert_eq!(rt.state.tab, 2); + } +} diff --git a/app/vendor/rune/examples/glass-card/Cargo.toml b/app/vendor/rune/examples/glass-card/Cargo.toml new file mode 100644 index 0000000..eba8b4e --- /dev/null +++ b/app/vendor/rune/examples/glass-card/Cargo.toml @@ -0,0 +1,11 @@ +[package] +name = "glass-card" +version = "0.0.1" +edition.workspace = true +license.workspace = true + +[dependencies] +rune = { workspace = true, default-features = true, features = ["keys-overlay"] } + +[lints] +workspace = true diff --git a/app/vendor/rune/examples/glass-card/src/main.rs b/app/vendor/rune/examples/glass-card/src/main.rs new file mode 100644 index 0000000..b5f7cd0 --- /dev/null +++ b/app/vendor/rune/examples/glass-card/src/main.rs @@ -0,0 +1,148 @@ +//! A system material card in a transparent, borderless window, flying over a busy test pattern +//! in a second window and docking, with a spring on its frame and corner radius. Rune draws the +//! card's shadow and contents; on macOS the glass (or the popover material before macOS 26) +//! is a native view that moves in the same Core Animation transaction as each frame. +//! +//! ```sh +//! cargo run -p glass-card --release +//! RUNE_SYSTEM_MATERIAL=legacy cargo run -p glass-card --release # NSVisualEffectView popover +//! RUNE_SYSTEM_MATERIAL=unsynced cargo run -p glass-card --release # views move outside the frame's transaction +//! GLASS_CARD_PATTERN=black cargo run -p glass-card --release # black backdrop and a magenta card edge, to measure sync +//! GLASS_CARD_BUSY_MS=6 cargo run -p glass-card --release # spend 6 ms of each frame busy on the main thread +//! ``` +//! +//! Space or the button flies and docks the card; `b` toggles a busy main thread. The card +//! flies on its own every 1.6 seconds unless `GLASS_CARD_MANUAL` is set, and the app quits after +//! `GLASS_CARD_SECONDS` when that is set. `GLASS_CARD_AT=x,y` places both windows, in points from +//! the primary display's top left (default `80,80`). `GLASS_CARD_TRACE=card.jsonl` writes the +//! card window's frame trace, with each drawable's on-screen present time. + +#![forbid(unsafe_code)] + +use std::time::Duration; + +use rune::{ + App, AppSpec, Color, Cx, El, Key, KeyEvent, LoopSpec, MacWindowOptions, Spring, SystemMaterial, TextStyle, Tx, + WindowOptions, WindowSpec, col, el, oklch, row, text, +}; + +const SIZE: (f32, f32) = (760.0, 480.0); +const MAGENTA: Color = Color { r: 1.0, g: 0.0, b: 1.0, a: 1.0 }; + +struct Card { + docked: bool, + busy_ms: u64, + measure: bool, + material: SystemMaterial, +} + +fn init() -> Card { + Card { + docked: false, + busy_ms: rune::env::var("GLASS_CARD_BUSY_MS").and_then(|v| v.parse().ok()).unwrap_or(0), + measure: measuring(), + material: if std::env::var_os("GLASS_CARD_POPOVER").is_some() { SystemMaterial::Popover } else { SystemMaterial::Glass }, + } +} + +fn measuring() -> bool { + rune::env::var("GLASS_CARD_PATTERN").is_some_and(|v| v == "black") +} + +/// The card's frame and corner radius: a wide card, or a capsule docked bottom right. +fn frame(docked: bool) -> ([f32; 4], f32) { + if docked { ([SIZE.0 - 290.0, SIZE.1 - 94.0, 250.0, 60.0], 30.0) } else { ([70.0, 60.0, 400.0, 260.0], 28.0) } +} + +fn card_view(s: &Card, _: &mut Cx<Card>) -> El { + let ([x, y, w, h], radius) = frame(s.docked); + let label = if s.docked { "Fly" } else { "Dock" }; + let button = row().key("toggle").role("button").label(label).hit().h(30.0).px(14.0).center().radius(15.0) + .fill(Color::WHITE.alpha(0.18)).border(1.0, Color::WHITE.alpha(0.3)) + .on_press(|s: &mut Card| s.docked = !s.docked) + .child(text(label).font(TextStyle::new(13.0, 600.0)).color(Color::WHITE)); + let title = text(if s.docked { "Docked" } else { "Liquid glass" }).key("title").font(TextStyle::new(if s.docked { 15.0 } else { 26.0 }, 650.0)).color(Color::WHITE); + let body = (!s.docked).then(|| text("Frame and corner radius on one spring. The material moves in the same transaction as this text, its shadow and the button.") + .key("body").w_full().wrap().font(TextStyle::new(14.0, 450.0)).color(Color::WHITE.alpha(0.85))); + let busy = (s.busy_ms > 0).then(|| text(format!("Main thread busy {} ms a frame", s.busy_ms)).key("busy") + .font(TextStyle::new(12.0, 500.0)).color(Color::WHITE.alpha(0.7))); + let mut card = col().key("card").absolute(x, y).size(w, h).radius(radius).padding(if s.docked { 16.0 } else { 26.0 }).gap(12.0) + .shadow(18.0, 44.0, Color { r: 0.0, g: 0.0, b: 0.0, a: 0.35 }) + .system_material(s.material) + .motion(Spring::new(0.7, 0.22)); + if s.measure { card = card.border(2.0, MAGENTA); } + let card = if s.docked { + card.child(row().w_full().h_full().center_y().gap(12.0).child(title).child(el().grow(1.0)).child(button)) + } else { + card.child(title).children(body).children(busy).child(el().grow(1.0)).child(row().w_full().child(el().grow(1.0)).child(button)) + }; + el().key("root").w_full().h_full().child(card) +} + +fn busy(s: &mut Card, _: f64, _: &mut Tx) -> bool { + if s.busy_ms > 0 { + let until = rune::time::now() + Duration::from_millis(s.busy_ms); + while rune::time::now() < until { std::hint::spin_loop(); } + } + false +} + +fn key(s: &mut Card, event: &KeyEvent, _: &mut Tx) -> bool { + match &event.key { + Key::Text(t) if t == " " => s.docked = !s.docked, + Key::Text(t) if t == "b" => s.busy_ms = if s.busy_ms > 0 { 0 } else { 8 }, + _ => return false, + } + true +} + +/// Moving bars over a grid of colour tiles, or plain black to measure edges against. +fn pattern_view(_: &(), _: &mut Cx<()>) -> El { + if measuring() { return el().key("pattern").w_full().h_full().fill(Color { r: 0.0, g: 0.0, b: 0.0, a: 1.0 }); } + let (cols, rows) = (16, 10); + let tile = (SIZE.0 / cols as f32, SIZE.1 / rows as f32); + let tiles = (0..cols * rows).map(move |i| { + let (c, r) = (i % cols, i / cols); + let light = if (c + r) % 2 == 0 { 0.78 } else { 0.42 }; + el().absolute(c as f32 * tile.0, r as f32 * tile.1).size(tile.0, tile.1).fill(oklch(light, 0.16, (i * 23 % 360) as f32)) + }); + let bars = (0..6).map(|k| { + el().absolute(0.0, 0.0).size(36.0, SIZE.1).fill(if k % 2 == 0 { Color::WHITE } else { Color { r: 0.0, g: 0.0, b: 0.0, a: 1.0 } }) + .looping(LoopSpec { delay: k as f64 * 0.6, ..LoopSpec::slide(3.6, [-1.0, 0.0], [SIZE.0 / 36.0, 0.0]) }) + }); + let words = (0..3).map(|k| { + text("RUNE 120 Hz").font(TextStyle::new(64.0, 800.0)).color(Color::WHITE).absolute(40.0, 60.0 + k as f32 * 170.0) + .looping(LoopSpec { delay: k as f64 * 1.3, ..LoopSpec::slide(4.0, [0.0, 0.0], [0.9, 0.0]) }) + }); + el().key("pattern").w_full().h_full().fill(Color { r: 0.1, g: 0.1, b: 0.12, a: 1.0 }).children(tiles).children(bars).children(words) +} + +fn main() { + rune::run_windows(|displays| { + let display = displays.iter().find(|d| d.primary).or_else(|| displays.first()); + let place = rune::env::var("GLASS_CARD_AT").and_then(|v| v.split_once(',').and_then(|(x, y)| Some((x.parse::<f64>().ok()?, y.parse::<f64>().ok()?)))); + let (x, y) = place.unwrap_or((80.0, 80.0)); + let origin = display.map_or((0, 0), |d| (d.position.0 + (x * d.scale) as i32, d.position.1 + (y * d.scale) as i32)); + let pattern = App::new(AppSpec { min_size: Some(SIZE), ..AppSpec::new("Glass card pattern", SIZE, || (), pattern_view) }).args(vec![]); + let trace = rune::env::var("GLASS_CARD_TRACE").map_or(vec![], |path| vec!["--native".into(), "--trace".into(), path]); + let card = App::new(AppSpec { min_size: Some(SIZE), poll: Some(busy), on_key: Some(key), ..AppSpec::new("Glass card", SIZE, init, card_view) }).args(trace); + let handle = card.handle(); + if std::env::var_os("GLASS_CARD_MANUAL").is_none() { + let handle = handle.clone(); + std::thread::spawn(move || loop { + std::thread::sleep(Duration::from_millis(1600)); + handle.update(|s, _| s.docked = !s.docked); + }); + } + if let Ok(seconds) = rune::env::var("GLASS_CARD_SECONDS").unwrap_or_default().parse::<f64>() { + std::thread::spawn(move || { std::thread::sleep(Duration::from_secs_f64(seconds)); handle.quit(); }); + } + let at = WindowOptions { borderless: true, position: Some(origin), resizable: false, always_on_top: true, ..Default::default() }; + // Rune draws the card's shadow, so the window has none of its own. + let over = WindowOptions { transparent: true, ..at.clone() }.macos(MacWindowOptions::default().shadow(false)); + vec![ + WindowSpec::from_app("pattern", pattern).options(at).into(), + WindowSpec::from_app("card", card).configured_options(over).into(), + ] as Vec<rune::AnyWindowSpec> + }); +} diff --git a/app/vendor/rune/examples/glass-panel/Cargo.toml b/app/vendor/rune/examples/glass-panel/Cargo.toml new file mode 100644 index 0000000..acdb7bb --- /dev/null +++ b/app/vendor/rune/examples/glass-panel/Cargo.toml @@ -0,0 +1,11 @@ +[package] +name = "glass-panel" +version = "0.0.1" +edition.workspace = true +license.workspace = true + +[dependencies] +rune = { workspace = true, default-features = true, features = ["keys-overlay"] } + +[lints] +workspace = true diff --git a/app/vendor/rune/examples/glass-panel/src/main.rs b/app/vendor/rune/examples/glass-panel/src/main.rs new file mode 100644 index 0000000..74e4717 --- /dev/null +++ b/app/vendor/rune/examples/glass-panel/src/main.rs @@ -0,0 +1,261 @@ +//! A floating card on a system material, built the way a native AppKit panel is. It fades in, +//! flies across one big window (an arc over the menu bar, width leading height, its corners +//! and shadows changing every frame), then hands off to a card-sized window that follows a +//! moving target sixty times a second, and fades out. +//! +//! - Liquid Glass (`NSGlassEffectView`) on macOS 26+, the popover material before. +//! - A frost of the window background colour at 62% over the glass, with label-colour rows, +//! a hairline and text, blended in sRGB as Core Animation blends (`srgb_blend`). +//! - Continuous corners on the glass and the content clip. +//! - Two Core Animation shadows, contact and ambient, that lift with the flight. +//! - Non-activating overlay panels that never take focus: the flight window at +//! `.floating + 1`, the docked one at `.floating`, fading their alpha in (0.18 s) and out +//! (0.144 s). +//! - Content swaps with opacity, a 0.96 scale and a 3 pt blur over the still glass. +//! +//! The hand-off shows the docked window and hides the flight window in one event-loop turn, +//! with the same pixels in the same place. The app never activates, so the material shows +//! as it does while another app is frontmost. +//! +//! ```sh +//! cargo run -p glass-panel --release +//! RUNE_SYSTEM_MATERIAL=legacy cargo run -p glass-panel --release # the popover material, as before macOS 26 +//! ``` +//! +//! `GLASS_PANEL_AT=x,y` places the flight window, in points from the primary display's top +//! left (default `360,0`). The app quits after `GLASS_PANEL_SECONDS` when that is set. +//! `GLASS_PANEL_POPOVER` asks for the popover material everywhere, and `GLASS_PANEL_MARK` +//! draws a marker that tells the two windows apart in a recording. + +#![forbid(unsafe_code)] + +use std::sync::OnceLock; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::time::Duration; + +use rune::{ + App, AppSpec, Color, Cx, DisplayTarget, El, KeyPolicy, LoopSpec, OverlayHandle, OverlayInput, OverlayOptions, + OverlayPlacement, OverlaySpec, RunOptions, Shadow, SystemMaterial, TextStyle, Transition, Tx, WindowSpec, col, el, + oklch, row, text, +}; + +/// The flight window's size. It reaches the top of the screen, so the arc passes over the menu bar. +const FLIGHT_WINDOW: (f32, f32) = (1000.0, 640.0); +/// The card where it appears and where it docks, in the flight window, with their radii. +const START: [f32; 4] = [120.0, 300.0, 420.0, 236.0]; +const DOCK: [f32; 4] = [600.0, 64.0, 320.0, 92.0]; +const START_RADIUS: f32 = 26.0; +const DOCK_RADIUS: f32 = 18.0; +/// Room for the shadows around the docked card, in its own window. +const MARGIN: f32 = 48.0; +const FLIGHT_SECONDS: f64 = 0.6; +/// The landed card holds still this long in the flight window before the hand-off. +const HOLD_SECONDS: f64 = 0.15; +const BLACK: Color = Color { r: 0.0, g: 0.0, b: 0.0, a: 1.0 }; + +#[derive(Clone, Copy, PartialEq)] +enum Role { + Backdrop, + Flight, + Dock, +} + +struct Panel { + role: Role, + material: SystemMaterial, + /// Start flying on the next frame. + fly: bool, + started: Option<f64>, + landed: Option<f64>, + handed: bool, + now: f64, + frames: u32, + /// `GLASS_PANEL_MARK`: a few marker pixels beside the docked card, magenta from the + /// docked window and cyan from the flight window, to find the hand-off in a recording. + mark: bool, +} + +fn panel(role: Role) -> Panel { + let material = if std::env::var_os("GLASS_PANEL_POPOVER").is_some() { SystemMaterial::Popover } else { SystemMaterial::Glass }; + let mark = std::env::var_os("GLASS_PANEL_MARK").is_some(); + Panel { role, material, fly: false, started: None, landed: None, handed: false, now: 0.0, frames: 0, mark } +} + +/// The flight and docked windows, for the hand-off. +static HANDLES: OnceLock<(OverlayHandle<Panel>, OverlayHandle<Panel>)> = OnceLock::new(); +/// Set at the hand-off, which unparks the driver thread. +static HANDED: AtomicBool = AtomicBool::new(false); +static DRIVER: OnceLock<std::thread::Thread> = OnceLock::new(); + +/// Steps the flight from the frame clock, and hands off once the card has held still. +fn poll(s: &mut Panel, now: f64, _: &mut Tx) -> bool { + if s.fly { + (s.fly, s.started, s.landed, s.handed, s.frames) = (false, Some(now), None, false, 0); + } + let Some(started) = s.started else { return false }; + if s.handed { return false; } + s.now = now; + s.frames += 1; + if s.landed.is_none() && now - started >= FLIGHT_SECONDS { + s.landed = Some(now); + eprintln!("glass-panel: flight drew {} frames in {:.3} s", s.frames, now - started); + } + if let Some(landed) = s.landed && now - landed >= HOLD_SECONDS { + s.handed = true; + if let Some((flight, dock)) = HANDLES.get() { + dock.show(); + flight.hide(); + } + HANDED.store(true, Ordering::Release); + if let Some(driver) = DRIVER.get() { driver.unpark(); } + } + true +} + +fn ease(t: f32) -> f32 { + let t = t.clamp(0.0, 1.0); + t * t * (3.0 - 2.0 * t) +} + +fn lerp(a: f32, b: f32, t: f32) -> f32 { a + (b - a) * t } + +/// The card at flight time `t` (0 to 1): its rect, corner radius and lift. Width leads height, +/// and the centre rides an arc that rises over the dock before it settles. +fn flight(t: f32) -> ([f32; 4], f32, f32) { + let p = ease(t); + let w = lerp(START[2], DOCK[2], ease(t * 1.25)); + let h = lerp(START[3], DOCK[3], ease(t * 1.25 - 0.25)); + let centre = |r: [f32; 4]| [r[0] + r[2] * 0.5, r[1] + r[3] * 0.5]; + let (from, to) = (centre(START), centre(DOCK)); + let control = [lerp(from[0], to[0], 0.6), 0.0]; + let arc = |a: usize| (1.0 - p) * (1.0 - p) * from[a] + 2.0 * p * (1.0 - p) * control[a] + p * p * to[a]; + ([arc(0) - w * 0.5, arc(1) - h * 0.5, w, h], lerp(START_RADIUS, DOCK_RADIUS, p), (std::f32::consts::PI * p).sin()) +} + +fn button(label: &'static str, ink: Color, fill: f32) -> El { + row().key(label).h(30.0).px(14.0).center().radius(9.0).continuous_corners().fill(ink.alpha(fill)) + .child(text(label).font(TextStyle::new(13.0, 560.0)).color(ink.alpha(0.847))) +} + +/// The card: glass, frost, hairline and contents, clipped with continuous corners, over two +/// shadows that deepen and spread with `lift`. +fn card(s: &Panel, dark: bool, [x, y, w, h]: [f32; 4], radius: f32, lift: f32, docked: bool) -> El { + let ink = if dark { Color::WHITE } else { BLACK }; + let frost = if dark { rune::color::hex("#1e1e1e").unwrap_or(BLACK) } else { Color::WHITE }.alpha(0.62); + let swap = Transition::opacity().combined(Transition::scale(0.96)).combined(Transition::blur(3.0)); + let content = if docked { + row().key("docked").absolute(0.0, 0.0).size(DOCK[2], DOCK[3]).px(20.0).gap(12.0).center_y().transition(swap) + .child(col().gap(3.0) + .child(text("Waiting for access").font(TextStyle::new(15.0, 620.0)).color(ink.alpha(0.847))) + .child(text("Turn it on in System Settings").font(TextStyle::new(12.0, 450.0)).color(ink.alpha(0.5)))) + .child(el().grow(1.0)) + .child(button("Open", ink, 0.12)) + } else { + col().key("asking").absolute(0.0, 0.0).size(START[2], START[3]).padding(22.0).gap(12.0).transition(swap) + .child(text("Allow screen recording?").font(TextStyle::new(19.0, 650.0)).color(ink.alpha(0.847))) + .child(text("The assistant needs to see the window you are working in to help with it.") + .w_full().wrap().font(TextStyle::new(13.5, 450.0)).color(ink.alpha(0.5))) + .child(row().key("setting").w_full().h(44.0).px(14.0).center_y().radius(11.0).continuous_corners().fill(ink.alpha(0.065)) + .child(text("Screen & System Audio Recording").font(TextStyle::new(13.0, 550.0)).color(ink.alpha(0.847)))) + .child(el().grow(1.0)) + .child(row().w_full().gap(10.0).child(el().grow(1.0)).child(button("Not Now", ink, 0.065)).child(button("Open Settings", ink, 0.12))) + }; + let frosted = el().key("frost").w_full().h_full().radius(radius).continuous_corners().clip_rounded(radius) + .fill(frost).border(1.0, ink.alpha(0.08)).child(content); + el().key("card").absolute(x, y).size(w, h).radius(radius).continuous_corners() + .box_shadow(Shadow::core_animation(0.0, 0.5, 1.5, BLACK.alpha(0.3 - 0.1 * lift))) + .box_shadow(Shadow::core_animation(0.0, 8.0 + 12.0 * lift, 18.0 + 14.0 * lift, BLACK.alpha(0.32 + 0.14 * lift))) + .system_material(s.material) + .child(frosted) +} + +fn view(s: &Panel, cx: &mut Cx<Panel>) -> El { + let dark = cx.system_dark(); + let root = el().key("root").w_full().h_full(); + match s.role { + Role::Backdrop => backdrop(), + Role::Dock => root.child(card(s, dark, [MARGIN, MARGIN, DOCK[2], DOCK[3]], DOCK_RADIUS, 0.0, true)) + .children(s.mark.then(|| marker(4.0, 4.0, Color { r: 1.0, g: 0.0, b: 1.0, a: 1.0 }))), + Role::Flight => { + let t = s.started.map_or(0.0, |started| ((s.now - started) / FLIGHT_SECONDS) as f32); + let (rect, radius, lift) = flight(t); + let root = root.child(card(s, dark, rect, radius, lift, t >= 0.4)) + .children(s.mark.then(|| marker(DOCK[0] - MARGIN + 12.0, DOCK[1] - MARGIN + 4.0, Color { r: 0.0, g: 1.0, b: 1.0, a: 1.0 }))); + // Keeps frames, and so `poll`, coming until the hand-off. + if s.started.is_some() && !s.handed { + root.child(el().key("frames").absolute(0.0, 0.0).size(1.0, 1.0).looping(LoopSpec::rotation(1.0))) + } else { root } + } + } +} + +fn marker(x: f32, y: f32, color: Color) -> El { el().key("mark").absolute(x, y).size(4.0, 4.0).fill(color) } + +/// Colour tiles and sweeping bars behind the flight, so the glass has something to bend. +fn backdrop() -> El { + let (w, h) = FLIGHT_WINDOW; + let (cols, rows) = (20, 13); + let tile = (w / cols as f32, h / rows as f32); + let tiles = (0..cols * rows).map(move |i| { + let (c, r) = (i % cols, i / cols); + let light = if (c + r) % 2 == 0 { 0.8 } else { 0.5 }; + el().absolute(c as f32 * tile.0, r as f32 * tile.1).size(tile.0, tile.1).fill(oklch(light, 0.14, (i * 23 % 360) as f32)) + }); + let bars = (0..4).map(move |k| { + el().absolute(0.0, 0.0).size(30.0, h).fill(if k % 2 == 0 { Color::WHITE } else { BLACK }) + .looping(LoopSpec { delay: k as f64 * 0.8, ..LoopSpec::slide(4.8, [-1.0, 0.0], [w / 30.0, 0.0]) }) + }); + el().key("backdrop").w_full().h_full().children(tiles).children(bars) +} + +fn main() { + let at = rune::env::var("GLASS_PANEL_AT") + .and_then(|v| v.split_once(',').and_then(|(x, y)| Some((x.parse::<f32>().ok()?, y.parse::<f32>().ok()?)))) + .unwrap_or((360.0, 0.0)); + rune::run_windows_with(RunOptions { accessory: true }, move |_| { + let mut app = App::new(AppSpec::new("Glass panel", (1.0, 1.0), || panel(Role::Backdrop), view)).windowless(); + let rect = |x: f32, y: f32, (width, height): (f32, f32)| Some(OverlayPlacement::Rect { x, y, width, height }); + let options = |placement| OverlayOptions { + display: DisplayTarget::Primary, placement, input: OverlayInput::None, keys: KeyPolicy::None, prewarm: true, ..Default::default() + }; + let dock_size = (DOCK[2] + 2.0 * MARGIN, DOCK[3] + 2.0 * MARGIN); + let home = (at.0 + DOCK[0] - MARGIN, at.1 + DOCK[1] - MARGIN); + let backdrop = app.overlay(OverlaySpec::new("Glass panel backdrop", FLIGHT_WINDOW, view) + .options(options(rect(at.0, at.1, FLIGHT_WINDOW))).macos_level(0), panel(Role::Backdrop)); + let flight = app.overlay(OverlaySpec::new("Glass panel flight", FLIGHT_WINDOW, view) + .options(options(rect(at.0, at.1, FLIGHT_WINDOW))).macos_level(4).srgb_blend(true).poll(poll), panel(Role::Flight)); + let dock = app.overlay(OverlaySpec::new("Glass panel dock", dock_size, view) + .options(options(rect(home.0, home.1, dock_size))).macos_level(3).srgb_blend(true), panel(Role::Dock)); + HANDLES.set((flight.clone(), dock.clone())).ok(); + backdrop.show(); + std::thread::spawn(move || { + DRIVER.set(std::thread::current()).ok(); + std::thread::sleep(Duration::from_millis(800)); + loop { + flight.update(|s, _| (s.started, s.landed, s.handed) = (None, None, false)); + flight.set_macos_level(4); + flight.fade_in(Duration::from_millis(180)); + std::thread::sleep(Duration::from_millis(700)); + HANDED.store(false, Ordering::Release); + flight.update(|s, _| s.fly = true); + while !HANDED.load(Ordering::Acquire) { std::thread::park(); } + std::thread::sleep(Duration::from_millis(250)); + // The docked window follows a target that moves side to side, 60 times a second. + let follow = rune::time::now(); + while follow.elapsed() < Duration::from_millis(2400) { + let dx = 60.0 * (std::f32::consts::TAU * follow.elapsed().as_secs_f32() / 2.4).sin(); + dock.set_placement(rect(home.0 + dx, home.1, dock_size)); + std::thread::sleep(Duration::from_micros(16_667)); + } + dock.set_placement(rect(home.0, home.1, dock_size)); + dock.fade_out(Duration::from_millis(144)); + std::thread::sleep(Duration::from_millis(600)); + } + }); + if let Ok(seconds) = rune::env::var("GLASS_PANEL_SECONDS").unwrap_or_default().parse::<f64>() { + let handle = app.handle(); + std::thread::spawn(move || { std::thread::sleep(Duration::from_secs_f64(seconds)); handle.quit(); }); + } + vec![WindowSpec::from_app("panel", app)] + }); +} diff --git a/app/vendor/rune/examples/hello/Cargo.toml b/app/vendor/rune/examples/hello/Cargo.toml new file mode 100644 index 0000000..f15df55 --- /dev/null +++ b/app/vendor/rune/examples/hello/Cargo.toml @@ -0,0 +1,11 @@ +[package] +name = "hello" +version = "0.0.1" +edition.workspace = true +license.workspace = true + +[dependencies] +rune = { workspace = true, default-features = true } + +[lints] +workspace = true diff --git a/app/vendor/rune/examples/hello/src/main.rs b/app/vendor/rune/examples/hello/src/main.rs new file mode 100644 index 0000000..c2e9eb1 --- /dev/null +++ b/app/vendor/rune/examples/hello/src/main.rs @@ -0,0 +1,60 @@ +//! The smallest Rune app: one piece of state, a view of it, and a switch that flips it on a spring. +//! `cargo run -p hello` opens the window; `-- --snap hello.png --scene on` renders it headless. + +#![forbid(unsafe_code)] + +use rune::tok::{self, motion, type_}; +use rune::{AppSpec, Cx, El, col, el, text}; + +#[derive(Default)] +struct State { + on: bool, +} + +fn view(s: &State, _: &mut Cx<State>) -> El { + let t = tok::theme(true); + let label = text(if s.on { "Lights on" } else { "Lights off" }) + .font(type_::TITLE).color(t.text); + let knob = el().key("knob").size(18.0, 18.0).radius(9.0).fill(t.knob) + .absolute(if s.on { 18.0 } else { 2.0 }, 2.0); + // Screen readers hear "Lights, switch, on": the label names it, `checked` says its state. + let switch = el().key("switch").role("switch").label("Lights").checked(s.on).focusable(true).size(38.0, 22.0).radius(11.0) + .fill(if s.on { tok::accent(0, true) } else { t.control_off }) + .motion(motion::SNAPPY) + .on_press(|s: &mut State| s.on = !s.on) + .child(knob); + col().w_full().h_full().center().gap(16.0).fill(t.bg).child(label).child(switch) +} + +fn main() { + rune::run(AppSpec::<State> { + scenes: &[("on", |s| s.on = true)], + ..AppSpec::new("Hello", (320.0, 200.0), State::default, view) + }); +} + +#[cfg(test)] +mod tests { + use super::*; + use rune::{Env, Runtime}; + + #[test] + fn a_tap_flips_the_switch_and_the_knob_springs_across() { + let env = Env { system_dark: true, scale: 2.0 }; + let mut rt = Runtime::new(State::default(), view, (320.0, 200.0), env); + rt.frame(0.0); + let knob_x = |rt: &Runtime<State>| rt.presented("knob").unwrap().0[0]; + let off = knob_x(&rt); + + let (x, y) = rt.find("switch").unwrap(); + rt.pointer_down(x, y); + rt.pointer_up(x, y); + for _ in 0..6 { rt.frame(1.0 / 60.0); } + assert!(rt.state.on); + let mid = knob_x(&rt); + for _ in 0..60 { rt.frame(1.0 / 60.0); } + let on = knob_x(&rt); + assert!(off < mid && mid < on, "the knob travels: {off} → {mid} → {on}"); + assert!((on - off - 16.0).abs() < 0.01, "and lands 16 points over"); + } +} diff --git a/app/vendor/rune/examples/kit-gallery/Cargo.toml b/app/vendor/rune/examples/kit-gallery/Cargo.toml new file mode 100644 index 0000000..3d353ef --- /dev/null +++ b/app/vendor/rune/examples/kit-gallery/Cargo.toml @@ -0,0 +1,17 @@ +[package] +name = "kit-gallery" +version = "0.0.1" +edition.workspace = true +license.workspace = true +publish = false + +[dependencies] +rune = { workspace = true, default-features = true, features = ["keys-overlay"] } +rune-kit = { workspace = true, default-features = true, features = ["markdown", "mermaid"] } +rune-theme-opencode = { workspace = true } + +[dev-dependencies] +wgpu = { workspace = true } + +[lints] +workspace = true diff --git a/app/vendor/rune/examples/kit-gallery/rustfmt.toml b/app/vendor/rune/examples/kit-gallery/rustfmt.toml new file mode 100644 index 0000000..c775577 --- /dev/null +++ b/app/vendor/rune/examples/kit-gallery/rustfmt.toml @@ -0,0 +1,2 @@ +max_width = 120 +use_small_heuristics = "Max" diff --git a/app/vendor/rune/examples/kit-gallery/scripts/combobox-animated-filter.json b/app/vendor/rune/examples/kit-gallery/scripts/combobox-animated-filter.json new file mode 100644 index 0000000..9e0a69f --- /dev/null +++ b/app/vendor/rune/examples/kit-gallery/scripts/combobox-animated-filter.json @@ -0,0 +1,7 @@ +[ + {"t": 0.25, "type": "key", "name": "Up"}, + {"t": 0.6, "type": "type", "text": "099"}, + {"t": 1.1, "type": "key", "name": "Enter"}, + {"t": 1.6, "type": "click", "key": "model-trigger"}, + {"t": 2.1, "type": "key", "name": "Escape"} +] diff --git a/app/vendor/rune/examples/kit-gallery/scripts/combobox.json b/app/vendor/rune/examples/kit-gallery/scripts/combobox.json new file mode 100644 index 0000000..481ad22 --- /dev/null +++ b/app/vendor/rune/examples/kit-gallery/scripts/combobox.json @@ -0,0 +1,7 @@ +[ + {"t": 0.25, "type": "key", "name": "Up"}, + {"t": 0.6, "type": "type", "text": "099", "expect": "instant", "scope": "model-content"}, + {"t": 1.1, "type": "key", "name": "Enter"}, + {"t": 1.6, "type": "click", "key": "model-trigger"}, + {"t": 2.1, "type": "key", "name": "Escape"} +] diff --git a/app/vendor/rune/examples/kit-gallery/scripts/help-tooltip.json b/app/vendor/rune/examples/kit-gallery/scripts/help-tooltip.json new file mode 100644 index 0000000..0fd86d3 --- /dev/null +++ b/app/vendor/rune/examples/kit-gallery/scripts/help-tooltip.json @@ -0,0 +1,4 @@ +[ + {"t": 0.2, "type": "move", "key": "copy"}, + {"t": 1.2, "type": "mark", "name": "end"} +] diff --git a/app/vendor/rune/examples/kit-gallery/scripts/motion-focus-modal.json b/app/vendor/rune/examples/kit-gallery/scripts/motion-focus-modal.json new file mode 100644 index 0000000..6136c4f --- /dev/null +++ b/app/vendor/rune/examples/kit-gallery/scripts/motion-focus-modal.json @@ -0,0 +1,15 @@ +[ + {"t":0.1,"type":"key","name":"Tab"}, + {"t":0.2,"type":"key","name":"Enter"}, + {"t":0.5,"type":"key","name":"Tab"}, + {"t":0.6,"type":"key","name":"Tab"}, + {"t":1.8,"type":"key","name":"Escape"}, + {"t":2.4,"type":"key","name":"Tab"}, + {"t":2.5,"type":"type","text":" "}, + {"t":2.8,"type":"key","name":"Tab"}, + {"t":2.9,"type":"type","text":" "}, + {"t":3.2,"type":"key","name":"Tab"}, + {"t":3.3,"type":"key","name":"Right"}, + {"t":3.8,"type":"tap","key":"opener"}, + {"t":4.8,"type":"tap","x":10,"y":10} +] diff --git a/app/vendor/rune/examples/kit-gallery/scripts/motion-stagger-list.json b/app/vendor/rune/examples/kit-gallery/scripts/motion-stagger-list.json new file mode 100644 index 0000000..99df69b --- /dev/null +++ b/app/vendor/rune/examples/kit-gallery/scripts/motion-stagger-list.json @@ -0,0 +1,6 @@ +[ + {"t":0.2,"type":"tap","key":"opener"}, + {"t":1.4,"type":"tap","key":"opener"}, + {"t":2.0,"type":"tap","key":"opener"}, + {"t":2.08,"type":"tap","key":"opener"} +] diff --git a/app/vendor/rune/examples/kit-gallery/scripts/selectable-text.json b/app/vendor/rune/examples/kit-gallery/scripts/selectable-text.json new file mode 100644 index 0000000..0c80a88 --- /dev/null +++ b/app/vendor/rune/examples/kit-gallery/scripts/selectable-text.json @@ -0,0 +1,4 @@ +[ + {"t": 0.2, "type": "drag", "x": 99, "y": 74, "dx": 126, "dy": 0, "dur": 0.4}, + {"t": 1.0, "type": "mark", "name": "end"} +] diff --git a/app/vendor/rune/examples/kit-gallery/src/layer_timing.rs b/app/vendor/rune/examples/kit-gallery/src/layer_timing.rs new file mode 100644 index 0000000..138688d --- /dev/null +++ b/app/vendor/rune/examples/kit-gallery/src/layer_timing.rs @@ -0,0 +1,149 @@ +//! Manual, headless disabled-control timing and legacy per-instance pixel comparison. +use super::*; +use rune::render::{Gpu, Instance, Renderer, Offscreen, OFFSCREEN_FORMAT, KIND_LAYER, KIND_LAYER_END, KIND_GRADIENT}; + +fn disabled_controls(_: &G, _: &mut Cx<G>) -> El { + let mut s = init(); + let k = kit(&s, true); + let mut overlays = Vec::new(); + let mut columns = rune::row().gap(24.0); + for story in ["ui-radio--states", "ui-text-input--states", "ui-select--disabled"] { + s.story = story; + columns = columns.child(col().w(300.0).child(stories::render(&s, k, &mut overlays))); + } + let segmented = rune_kit::SegmentedControl::new(&["List", "Grid", "Board"], Some(0)) + .segment_state(0, rune_kit::State::Disabled) + .segment_state(1, rune_kit::State::Disabled) + .segment_state(2, rune_kit::State::Disabled).build(k); + rune_kit::root(col().fill(k.c.page).padding(24.0).gap(24.0).child(columns).child(segmented), overlays) +} + +fn legacy(instances: &[Instance]) -> Vec<Instance> { + let mut alpha = 1.0; + let mut stack = Vec::new(); + let mut out = Vec::new(); + for i in instances { + if i.params[1] == KIND_LAYER { stack.push(alpha); alpha *= i.fill[3]; } + else if i.params[1] == KIND_LAYER_END { alpha = stack.pop().unwrap(); } + else { + let mut i = *i; + i.fill = i.fill.map(|v| v * alpha); + i.border = i.border.map(|v| v * alpha); + if i.params[1] == KIND_GRADIENT { i.uv = i.uv.map(|v| v * alpha); } + out.push(i); + } + } + assert!(stack.is_empty()); + out +} + +#[test] +#[ignore = "manual byte-for-byte disabled styling check; provide RUNE_KIT_PIXEL_BASELINE"] +fn disabled_controls_match_legacy_pixels() { + // Record against the pre-dimming kit source (reconstructing dev's per-instance opacity), + // then run without RECORD on the new source. Keep the directory outside the build checkout. + let directory = std::path::PathBuf::from(std::env::var_os("RUNE_KIT_PIXEL_BASELINE").unwrap()); + let record = std::env::var_os("RUNE_KIT_RECORD_BASELINE").is_some(); + std::fs::create_dir_all(&directory).unwrap(); + let gpu = Gpu::headless(); + let mut renderer = Renderer::new(&gpu.device, OFFSCREEN_FORMAT); + for dark in [false, true] { + for scale in [1.0, 2.0] { + let target = Offscreen::new(&gpu.device, (1024.0 * scale) as u32, (800.0 * scale) as u32); + for story in ["ui-button--all-states", "ui-icon-button--all-states", "ui-radio--states", + "ui-text-input--states", "ui-textarea--states", "ui-select--disabled", + "ui-switch--states", "ui-menu--basic", "ui-segmented-control--basic"] { + let Some((_, setup)) = stories::SCENES.iter().find(|(id, _)| *id == story) else { panic!("missing {story}") }; + let mut s = init(); setup(&mut s); + let text = rune::text::TextSystem::new(rune_theme_opencode::FONTS, rune_theme_opencode::FAMILIES); + let mut rt = rune::Runtime::with_text(s, view, (1024.0, 800.0), rune::Env { scale, system_dark: dark }, text); + rt.frame(0.0); rt.settle_all(); rt.frame(0.0); + if record && story == "ui-button--all-states" { + assert!(rt.instances.iter().any(|i| i.params[1] == KIND_LAYER), + "record the legacy baseline with the pre-dimming kit source"); + } + let instances = if record { legacy(&rt.instances) } else { rt.instances.clone() }; + renderer.prepare(&gpu.device, &gpu.queue, &mut rt.text.atlas, &instances, ((1024.0 * scale) as u32, (800.0 * scale) as u32)); + let mut encoder = gpu.device.create_command_encoder(&Default::default()); + renderer.draw(&mut encoder, &target.view, [0.0; 4]); target.copy(&mut encoder); + gpu.queue.submit([encoder.finish()]); + let pixels = target.read(&gpu.device); + let path = directory.join(format!("{story}-{dark}-{scale}.rgba")); + if record { std::fs::write(path, pixels).unwrap(); } + else { + let before = std::fs::read(path).unwrap(); + let differences = pixels.iter().zip(&before).filter(|(a, b)| a != b).count(); + assert_eq!(pixels.len(), before.len()); + assert_eq!(differences, 0, "{story} dark={dark} scale={scale}"); + } + } + } + } +} + +#[test] +#[ignore = "manual disabled-controls GPU comparison; run on a build worker"] +fn disabled_controls_gpu_cost() { + let gpu = Gpu::headless(); + assert!(gpu.device.features().contains(wgpu::Features::TIMESTAMP_QUERY)); + eprintln!("adapter: {:?}", gpu.adapter.get_info()); + let text = rune::text::TextSystem::new(rune_theme_opencode::FONTS, rune_theme_opencode::FAMILIES); + let mut rt = rune::Runtime::with_text(init(), disabled_controls, (1024.0, 640.0), + rune::Env { scale: 2.0, system_dark: true }, text); + rt.frame(0.0); rt.settle_all(); rt.frame(0.0); + assert!(rt.instances.iter().all(|i| i.params[1] != KIND_LAYER && i.params[1] != KIND_LAYER_END)); + let old = legacy(&rt.instances); + let mut renderers = [Renderer::new(&gpu.device, OFFSCREEN_FORMAT), Renderer::new(&gpu.device, OFFSCREEN_FORMAT)]; + for (renderer, instances) in renderers.iter_mut().zip([&old, &rt.instances]) { + rt.text.atlas.dirty = Some((0, rune::text::ATLAS_SIZE)); + renderer.prepare(&gpu.device, &gpu.queue, &mut rt.text.atlas, instances, (2048, 1280)); + } + assert_eq!(renderers[1].layer_stats().targets, 0, "disabled styling must stay on the direct path"); + let target = Offscreen::new(&gpu.device, 2048, 1280); + for _ in 0..8 { + for renderer in &renderers { + let mut enc = gpu.device.create_command_encoder(&Default::default()); + renderer.draw(&mut enc, &target.view, [0.0; 4]); + gpu.queue.submit([enc.finish()]); + gpu.device.poll(wgpu::PollType::wait_indefinitely()).unwrap(); + } + } + const N: u32 = 60; + let queries = gpu.device.create_query_set(&wgpu::QuerySetDescriptor { label: None, ty: wgpu::QueryType::Timestamp, count: N * 4 }); + let resolve = gpu.device.create_buffer(&wgpu::BufferDescriptor { label: None, size: u64::from(N) * 32, + usage: wgpu::BufferUsages::QUERY_RESOLVE | wgpu::BufferUsages::COPY_SRC, mapped_at_creation: false }); + let read = gpu.device.create_buffer(&wgpu::BufferDescriptor { label: None, size: u64::from(N) * 32, + usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ, mapped_at_creation: false }); + for sample in 0..N { + // Alternate paired order to reduce drift; each sample is one completed frame. + for offset in 0..2 { + let mode = (sample + offset) % 2; + let query = sample * 4 + mode * 2; + let mut enc = gpu.device.create_command_encoder(&Default::default()); + renderers[mode as usize].draw_timed(&mut enc, &target.view, [0.0; 4], Some(wgpu::RenderPassTimestampWrites { + query_set: &queries, beginning_of_pass_write_index: Some(query), end_of_pass_write_index: Some(query + 1), + })); + gpu.queue.submit([enc.finish()]); + gpu.device.poll(wgpu::PollType::wait_indefinitely()).unwrap(); + } + } + let mut enc = gpu.device.create_command_encoder(&Default::default()); + enc.resolve_query_set(&queries, 0..N * 4, &resolve, 0); + enc.copy_buffer_to_buffer(&resolve, 0, &read, 0, u64::from(N) * 32); + gpu.queue.submit([enc.finish()]); + read.slice(..).map_async(wgpu::MapMode::Read, |r| r.unwrap()); + gpu.device.poll(wgpu::PollType::wait_indefinitely()).unwrap(); + let bytes = read.slice(..).get_mapped_range().unwrap(); + for (mode, name) in ["flat-reference", "disabled-leaves"].into_iter().enumerate() { + let mut ms: Vec<f64> = bytes.chunks_exact(32).map(|b| { + let b = &b[mode * 16..mode * 16 + 16]; + let a = u64::from_le_bytes(b[..8].try_into().unwrap()); + let z = u64::from_le_bytes(b[8..].try_into().unwrap()); + assert!(z >= a && z != 0); + (z - a) as f64 * f64::from(gpu.queue.get_timestamp_period()) / 1e6 + }).collect(); + ms.sort_by(f64::total_cmp); + eprintln!("disabled-controls {name}: n={N} median={:.6}ms p95={:.6}ms {:?}", + ms[N as usize / 2], ms[N as usize * 95 / 100 - 1], renderers[mode].layer_stats()); + } +} diff --git a/app/vendor/rune/examples/kit-gallery/src/main.rs b/app/vendor/rune/examples/kit-gallery/src/main.rs new file mode 100644 index 0000000..c27f0e1 --- /dev/null +++ b/app/vendor/rune/examples/kit-gallery/src/main.rs @@ -0,0 +1,156 @@ +//! The rune-kit gallery: one scene per `@opencode/ui` Storybook story, in the story's id, so +//! `scripts/kit-diff.py` can render both and diff them. `--kit neutral` renders the same +//! components on Rune's core neutral theme instead of OpenCode's; `--kit palette` on +//! `Kit::from_palette` with a near-black, off-white and red seed (a dark palette with a red accent); +//! `--kit palette black` (dark) and `--kit palette warm` (light) use pure-black and +//! paper seeds with ink focus rings. `--reduced-motion` renders in the runtime's reduced-motion +//! mode. +//! +//! ```sh +//! kit-gallery --list-scenes +//! kit-gallery --scene ui-button--variants --snap out.png --theme dark --size 720x300 +//! ``` + +#![forbid(unsafe_code)] + +mod stories; + +#[cfg(test)] +mod layer_timing; + +use std::collections::{HashMap, HashSet}; + +use rune::{AppSpec, Cx, El, TextEdit, col}; +use rune_kit::Kit; + +pub struct G { + pub story: &'static str, + /// Toggled things by key (switches, checkboxes, expanded items). + pub on: HashSet<String>, + /// Picked values by group key (radio groups, selects, segmented controls, tabs). + pub pick: HashMap<String, String>, + /// The open overlay, by key. + pub open: Option<String>, + pub edits: [TextEdit; 8], + pub combo: rune_kit::ComboboxState, + /// The file tree story's files. + pub files: rune_kit::TreeModel<rune_kit::FileNode<()>>, + pub neutral: bool, + pub palette: bool, + /// `--reduced-motion`: the runtime's reduced-motion mode. + pub reduced: bool, +} + +impl G { + pub fn is(&self, key: &str) -> bool { + self.on.contains(key) + } + pub fn flip(&mut self, key: &str) { + if !self.on.remove(key) { + self.on.insert(key.to_owned()); + } + } + pub fn picked<'a>(&'a self, group: &str, default: &'a str) -> &'a str { + self.pick.get(group).map_or(default, String::as_str) + } + pub fn toggle_open(&mut self, key: &str) { + self.open = if self.open.as_deref() == Some(key) { None } else { Some(key.to_owned()) }; + } +} + +fn init() -> G { + G { + story: "index", + on: HashSet::new(), + pick: HashMap::new(), + open: None, + edits: Default::default(), + combo: Default::default(), + files: files(), + neutral: rune::extra_args().iter().any(|a| a == "neutral"), + palette: rune::extra_args().iter().any(|a| a == "palette"), + reduced: rune::extra_args().iter().any(|a| a == "--reduced-motion"), + } +} + +/// The acme-web checkout Desktop's Files panel shows, `src/util` open on `format.ts`. +fn files() -> rune_kit::TreeModel<rune_kit::FileNode<()>> { + let paths = [".git/HEAD", "src/util/format.ts", "src/money.ts", "src/index.ts", "package.json", "README.md"]; + let mut m = rune_kit::FileTree::new().compact_folders(false).build(paths.map(|p| (p, ()))); + m.expand_to("src/util/format.ts"); + m.select("src/util/format.ts"); + m +} + +pub fn kit(s: &G, dark: bool) -> &'static Kit { + if s.palette { + static D: std::sync::OnceLock<Kit> = std::sync::OnceLock::new(); + static L: std::sync::OnceLock<Kit> = std::sync::OnceLock::new(); + let hex = |c: &str| rune::color::hex(c).unwrap(); + let seed = |bg: &str, fg: &str, accent: &str| rune_kit::PaletteSeed { bg: hex(bg), fg: hex(fg), accent: hex(accent) }; + // `--kit palette black|warm`: pure-black and paper seeds with ink focus. + let variant = |name: &str| rune::extra_args().iter().any(|a| a == name); + let ink = |seed| Kit::from_palette_focus(seed, rune_kit::PaletteFocus::Ink); + return if dark { + D.get_or_init(|| match variant("black") { + true => ink(seed("#000000", "#ffffff", "#ff2a2a")), + false => Kit::from_palette(seed("#0a0a0a", "#ededed", "#e5484d")), + }) + } else { + L.get_or_init(|| match variant("warm") { + true => ink(seed("#e8e4dc", "#000000", "#d81414")), + false => Kit::from_palette(seed("#ffffff", "#171717", "#e5484d")), + }) + }; + } + if s.neutral { + static D: std::sync::OnceLock<Kit> = std::sync::OnceLock::new(); + static L: std::sync::OnceLock<Kit> = std::sync::OnceLock::new(); + return if dark { D.get_or_init(|| Kit::neutral(true)) } else { L.get_or_init(|| Kit::neutral(false)) }; + } + rune_theme_opencode::kit(dark) +} + +fn view(s: &G, cx: &mut Cx<G>) -> El { + if s.reduced { + cx.reduced_motion(true); + } + let k = kit(s, cx.system_dark()); + let mut overlays = Vec::new(); + let body = stories::render(s, k, &mut overlays); + // Storybook's decorator: the page colour and 24 px of padding around the story. + rune_kit::root(col().key("frame").fill(k.c.page).padding(24.0).child(body), overlays) +} + +fn main() { + rune::run(AppSpec { + scenes: stories::SCENES, + fonts: rune_theme_opencode::FONTS, + families: rune_theme_opencode::FAMILIES, + ..AppSpec::new("rune-kit gallery", (720.0, 480.0), init, view) + }); +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Every story builds on both appearances of both themes (no GPU needed). + #[test] + fn every_story_builds() { + for (neutral, palette) in [(false, false), (true, false), (false, true)] { + for dark in [false, true] { + let mut s = init(); + s.neutral = neutral; + s.palette = palette; + for (id, setup) in stories::SCENES { + setup(&mut s); + let k = kit(&s, dark); + let mut layer = Vec::new(); + let _ = stories::render(&s, k, &mut layer); + assert_eq!(s.story, *id); + } + } + } + } +} diff --git a/app/vendor/rune/examples/kit-gallery/src/stories.rs b/app/vendor/rune/examples/kit-gallery/src/stories.rs new file mode 100644 index 0000000..fe33719 --- /dev/null +++ b/app/vendor/rune/examples/kit-gallery/src/stories.rs @@ -0,0 +1,450 @@ +//! The stories, one function per `@opencode/ui` Storybook story id (title + export name). +//! Layout wrappers copy each story's own inline styles. + +use rune::{Edge, El, Stagger, TextEdit, TextStyle, Transition, Tx, col, el, row, text}; +use rune_kit::*; +use rune_theme_opencode::icons as ic; + +use crate::G; + +mod combobox; +mod controls; +mod display; +mod icons; +mod inputs; +mod markdown; +mod overlays; + +use controls::{button_all_states, button_icon, button_playground, button_sizes, button_variants, checkbox_basic, checkbox_custom_icon, checkbox_hidden_label, checkbox_states, icon_button_all_states, icon_button_playground, icon_button_sizes, icon_button_variants, radio_basic, radio_controlled, radio_states, switch_appearances, switch_basic, switch_hidden_label, switch_sizes, switch_states, switch_web}; +use display::{accordion_basic, accordion_multiple, accordion_single, badge_accent, badge_appearances, badge_basic, badge_high_contrast, badge_subtle, card_error, card_info, card_normal, card_success, card_warning, collapsible_basic, collapsible_ghost, keybind_all, keybind_multiple, keybind_playground, keybind_symbols, keybind_variants, list_active_icon, list_basic, list_divider, list_empty, list_grouped, list_no_search, list_with_add, loader_basic, loader_sizes, progress_basic, progress_indeterminate, progress_no_label, rolling_text_basic, scroll_view_thumb, segmented_basic, segmented_controlled, spinner_basic, spinner_sizes}; +use inputs::{field_direct_child, field_invalid, field_text_input, field_textarea, select_disabled, select_grouped, select_invalid, select_playground, select_states, select_with_field, text_input_appearances, text_input_controlled, text_input_copy, text_input_playground, text_input_states, text_input_with_field, textarea_controlled, textarea_playground, textarea_states, textarea_with_field}; +use markdown::{ + markdown_basic, markdown_code, markdown_diagrams, markdown_lenient, markdown_mermaid_charts, markdown_mermaid_data, markdown_mermaid_flows, markdown_mermaid_git, markdown_mermaid_hover, markdown_mermaid_maps, markdown_mermaid_plan, markdown_mermaid_plan_zoomed, markdown_mermaid_shapes, markdown_mermaid_streaming, markdown_mermaid_systems, markdown_stream_tail, markdown_streaming, markdown_table_styles, + markdown_walkthrough, +}; +use overlays::{hover_card_basic, menu_appearances, menu_basic, menu_checkbox, menu_radio, menu_rich, menu_submenu, popover_basic, popover_controlled, toast_all, tooltip_keybind, tooltip_path, tooltip_simple, tooltip_title_description}; + +type Story = fn(&G, &Kit, &mut Vec<El>) -> El; + +macro_rules! stories { + ($($id:literal => $f:path,)*) => { + pub const STORIES: &[(&str, Story)] = &[$(($id, $f),)*]; + pub const SCENES: &[(&str, fn(&mut G))] = &[$(($id, |s: &mut G| { + s.story = $id; + s.combo = ComboboxState::default(); + if $id.starts_with("rune-combobox--") { let _ = s.combo.step(ComboboxEvent::Toggle { current: None }); } + if $id == "rune-popup-list--composer" { + s.edits[7] = TextEdit::new("/"); + s.edits[7].focused = true; + } + s.open = OPENED.iter().find(|(id, _)| *id == $id).map(|(_, k)| (*k).to_owned()); + }),)*]; + }; +} + +/// Stories whose web version opens an overlay (by default or through the harness's click): +/// their scene starts with that overlay open. +const OPENED: &[(&str, &str)] = &[ + ("ui-dialog--basic", "dialog"), + ("rune-dialog--fit", "dialog-fit"), + ("rune-popup-list--composer", "popup-list"), + ("ui-menu--basic", "menu"), + ("ui-menu--rich", "menu"), + ("ui-menu--with-checkbox", "menu"), + ("ui-menu--with-radio", "menu"), + ("ui-menu--with-submenu", "menu"), + ("ui-menu--appearances", "both"), + ("ui-select--playground", "select"), + ("ui-select--grouped", "select"), + ("rune-select--states", "select"), + ("components-popover--basic", "popover"), + ("components-popover--controlled", "popover"), + ("components-hover-card--basic", "card"), + ("ui-tooltip--simple", "tip"), + ("ui-tooltip--with-keybind", "tip"), + ("ui-tooltip--path", "tip"), + ("ui-tooltip--title-description", "tip"), + ("ui-toast--all-examples", "toast"), +]; + +fn is_open(s: &G, key: &str) -> bool { + s.open.as_deref() == Some(key) || s.open.as_deref() == Some("both") +} + +fn toggle(key: &'static str) -> impl Fn(&mut G) + Clone { + move |s: &mut G| s.toggle_open(key) +} + +fn close(s: &mut G) { + s.open = None; +} + +fn flip(key: &'static str) -> impl Fn(&mut G) { + move |s: &mut G| s.flip(key) +} + +stories! { + "rune-combobox--searchable" => combobox::searchable, + "rune-combobox--animated-filter" => combobox::animated_filter, + "ui-dialog--basic" => dialog_basic, + "motion-focus-modal" => motion_focus_modal, + "motion-stagger-list" => motion_stagger_list, + "ui-button--playground" => button_playground, + "ui-button--variants" => button_variants, + "ui-button--sizes" => button_sizes, + "ui-button--icon" => button_icon, + "ui-button--all-states" => button_all_states, + "ui-icon-button--playground" => icon_button_playground, + "ui-icon-button--variants" => icon_button_variants, + "ui-icon-button--sizes" => icon_button_sizes, + "ui-icon-button--all-states" => icon_button_all_states, + "ui-switch--basic" => switch_basic, + "ui-switch--appearances" => switch_appearances, + "ui-switch--states" => switch_states, + "ui-switch--hidden-label" => switch_hidden_label, + "rune-switch--web" => switch_web, + "ui-checkbox--basic" => checkbox_basic, + "ui-checkbox--states" => checkbox_states, + "ui-checkbox--custom-icon" => checkbox_custom_icon, + "ui-checkbox--hidden-label" => checkbox_hidden_label, + "ui-radio--basic" => radio_basic, + "ui-radio--controlled" => radio_controlled, + "ui-radio--states" => radio_states, + "ui-text-input--playground" => text_input_playground, + "ui-text-input--with-copy-button" => text_input_copy, + "ui-text-input--controlled" => text_input_controlled, + "ui-text-input--appearances" => text_input_appearances, + "ui-text-input--with-field" => text_input_with_field, + "ui-text-input--states" => text_input_states, + "ui-textarea--playground" => textarea_playground, + "ui-textarea--controlled" => textarea_controlled, + "ui-textarea--with-field" => textarea_with_field, + "ui-textarea--states" => textarea_states, + "ui-field--text-input-example" => field_text_input, + "ui-field--text-input-direct-child" => field_direct_child, + "ui-field--textarea-example" => field_textarea, + "ui-field--invalid" => field_invalid, + "ui-select--playground" => select_playground, + "ui-select--grouped" => select_grouped, + "ui-select--invalid" => select_invalid, + "ui-select--disabled" => select_disabled, + "ui-select--with-field" => select_with_field, + "rune-select--states" => select_states, + "components-popover--basic" => popover_basic, + "components-popover--controlled" => popover_controlled, + "ui-menu--basic" => menu_basic, + "ui-menu--appearances" => menu_appearances, + "ui-menu--rich" => menu_rich, + "ui-menu--with-checkbox" => menu_checkbox, + "ui-menu--with-radio" => menu_radio, + "ui-menu--with-submenu" => menu_submenu, + "ui-tooltip--simple" => tooltip_simple, + "ui-tooltip--with-keybind" => tooltip_keybind, + "ui-tooltip--path" => tooltip_path, + "ui-tooltip--title-description" => tooltip_title_description, + "components-hover-card--basic" => hover_card_basic, + "ui-toast--all-examples" => toast_all, + "components-card--normal" => card_normal, + "components-card--error" => card_error, + "components-card--warning" => card_warning, + "components-card--success" => card_success, + "components-card--info" => card_info, + "components-list--basic" => list_basic, + "components-list--grouped" => list_grouped, + "components-list--empty" => list_empty, + "components-list--with-add" => list_with_add, + "components-list--divider" => list_divider, + "components-list--active-icon" => list_active_icon, + "components-list--no-search" => list_no_search, + "ui-accordion--basic" => accordion_basic, + "ui-accordion--multiple" => accordion_multiple, + "ui-accordion--non-collapsible" => accordion_single, + "components-collapsible--basic" => collapsible_basic, + "components-collapsible--ghost" => collapsible_ghost, + "ui-badge--basic" => badge_basic, + "ui-badge--appearances" => badge_appearances, + "ui-badge--subtle" => badge_subtle, + "ui-badge--high-contrast" => badge_high_contrast, + "ui-badge--accent" => badge_accent, + "ui-keybind--playground" => keybind_playground, + "ui-keybind--variants" => keybind_variants, + "ui-keybind--multiple-keys" => keybind_multiple, + "ui-keybind--all-examples" => keybind_all, + "components-spinner--basic" => spinner_basic, + "components-spinner--sizes" => spinner_sizes, + "ui-loader--basic" => loader_basic, + "ui-loader--sizes" => loader_sizes, + "components-progress--basic" => progress_basic, + "components-progress--no-label" => progress_no_label, + "components-progress--indeterminate" => progress_indeterminate, + "ui-segmented-control--basic" => segmented_basic, + "ui-segmented-control--controlled" => segmented_controlled, + "rune-keybind--symbols" => keybind_symbols, + "rune-switch--sizes" => switch_sizes, + "rune-scroll-view--thumb" => scroll_view_thumb, + "rune-rolling-text--basic" => rolling_text_basic, + "rune-markdown--basic" => markdown_basic, + "rune-markdown--streaming" => markdown_streaming, + "rune-markdown--stream-tail" => markdown_stream_tail, + "rune-markdown--walkthrough" => markdown_walkthrough, + "rune-markdown--diagrams" => markdown_diagrams, + "rune-markdown--lenient" => markdown_lenient, + "rune-markdown--mermaid-shapes" => markdown_mermaid_shapes, + "rune-markdown--mermaid-charts" => markdown_mermaid_charts, + "rune-markdown--mermaid-maps" => markdown_mermaid_maps, + "rune-markdown--mermaid-git" => markdown_mermaid_git, + "rune-markdown--mermaid-data" => markdown_mermaid_data, + "rune-markdown--mermaid-systems" => markdown_mermaid_systems, + "rune-markdown--mermaid-flows" => markdown_mermaid_flows, + "rune-markdown--mermaid-hover" => markdown_mermaid_hover, + "rune-markdown--mermaid-streaming" => markdown_mermaid_streaming, + "rune-markdown--mermaid-plan" => markdown_mermaid_plan, + "rune-markdown--mermaid-plan-zoomed" => markdown_mermaid_plan_zoomed, + "rune-markdown--table-styles" => markdown_table_styles, + "rune-markdown--code" => markdown_code, + "rune-text--selectable-help" => text_selectable_help, + "rune-text--truncate-middle" => text_truncate_middle, + "rune-dialog--fit" => dialog_fit, + "rune-popup-list--composer" => popup_list_composer, + "rune-scroll-bar--basic" => scroll_bar_basic, + "rune-scroll-bar--grow" => scroll_bar_grow, + "components-file-icon--samples" => icons::file_icon_samples, + "components-file-icon--folder" => icons::file_icon_folder, + "ui-icon--gallery" => icons::icon_gallery, + "rune-icon--catalog" => icons::icon_catalog, + "rune-file-icon--catalog" => icons::file_icon_catalog, + "rune-tree-icon--catalog" => icons::tree_icon_catalog, + "rune-tree--files" => icons::file_tree, +} + +fn popup_list_composer(s: &G, k: &Kit, layer: &mut Vec<El>) -> El { + let entries = [ + ("review", "/review", "Review branch changes", &glyphs::SPARKLE, "⏎", false), + ("compact", "/compact", "Summarize the conversation", &glyphs::FILE_TEXT, "⌘K", false), + ("search", "/search", "Search workspace files", k.glyph.search, "⌘P", false), + ("share", "/share", "Create a read-only link", k.glyph.lock, "", true), + ]; + let q = s.edits[7].text.trim_start_matches('/').to_lowercase(); + let filtered: Vec<_> = entries.into_iter().filter(|(_, label, desc, ..)| { + q.is_empty() || label.to_lowercase().contains(&q) || desc.to_lowercase().contains(&q) + }).collect(); + let count = filtered.len(); + let active = s.pick.get("popup-list").and_then(|v| v.parse::<usize>().ok()).unwrap_or(0).min(count.saturating_sub(1)); + let items = filtered.into_iter().map(|(id, label, desc, glyph, hint, disabled)| { + let mut item = PopupItem::new(id, label) + .description(desc) + .leading(rune::icon(glyph, 14.0).color(k.c.icon_muted)) + .disabled(disabled); + if !hint.is_empty() { + item = item.trailing(text(hint).font(k.ty.small_medium).color(k.c.text_faint)); + } + item + }); + PopupList::new("popup-list", "composer") + .open(is_open(s, "popup-list")) + .width(320.0) + .items(items) + .active((count > 0).then_some(active)) + .on_active(|s: &mut G, i| { s.pick.insert("popup-list".into(), i.to_string()); }) + .on_choose(|s: &mut G, id, _| { + s.edits[7] = TextEdit::new(format!("/{id} ")); + s.edits[7].focused = true; + s.open = None; + }) + .build(k, layer); + TextInput::new(&s.edits[7]) + .width(Some(320.0)) + .placeholder("Type / for commands or @ to mention…") + .animate_edit_layout() + .on_edit(|s: &mut G| &mut s.edits[7]) + .on_change(|s: &mut G, _| { s.open = Some("popup-list".into()); s.pick.insert("popup-list".into(), "0".into()); }) + .build(k) + .key("composer") +} + +fn dialog_basic(s: &G, k: &Kit, layer: &mut Vec<El>) -> El { + Dialog::new("dialog", "Dialog").description("Description").open(is_open(s, "dialog")) + .on_close(close).child(body_text(k, "Dialog body content.")).build(k, layer); + Button::new("Open dialog").on_press(toggle("dialog")).build(k).key("opener") +} + +fn dialog_fit(s: &G, k: &Kit, layer: &mut Vec<El>) -> El { + let actions = row().w_full().padding(16.0).gap(8.0).justify_end() + .child(Button::new("Cancel").variant(ButtonVariant::Ghost).on_press(close).build(k)) + .child(Button::new("Delete").on_press(close).build(k)); + Dialog::new("dialog-fit", "Delete item?").description("This cannot be undone.").width(400.0).fit() + .open(is_open(s, "dialog-fit")).on_close(close).child(actions).build(k, layer); + Button::new("Open confirmation").on_press(toggle("dialog-fit")).build(k).key("opener") +} + +fn motion_focus_modal(s: &G, k: &Kit, layer: &mut Vec<El>) -> El { + Dialog::new("dialog", "Loading").open(is_open(s, "dialog")).on_close(close) + .child(row().gap(16.0).child(Spinner::new().build(k).key("spinner")) + .child(Loader::new().build(k).key("loader"))) + .child(Button::new("Done").on_press(close).build(k).key("done")).build(k, layer); + col().gap(16.0) + .child(Button::new("Open dialog").on_press(toggle("dialog")).build(k).key("opener")) + .child(Switch::new(s.is("switch")).label("Sync").on_toggle(|s: &mut G| s.flip("switch")).build(k).key("switch")) + .child(Checkbox::new(s.is("check")).label("Remember").on_toggle(|s: &mut G| s.flip("check")).build(k).key("check")) + .child(SegmentedControl::new(&["First", "Second"], Some(if s.is("second") { 1 } else { 0 })) + .on_pick(|s: &mut G, i, _| { if s.is("second") != (i == 1) { s.flip("second"); } }).build(k)) +} + +/// Five rows that rise and fade in one after another (`El::enter_delay` with a `Stagger`) and +/// leave together. +fn motion_stagger_list(s: &G, k: &Kit, _: &mut Vec<El>) -> El { + const ROWS: [&str; 5] = ["Inbox", "Drafts", "Sent", "Archive", "Trash"]; + let stagger = Stagger::new(0.05); + let rows = ROWS.iter().enumerate().filter(|_| s.is("rows")).map(|(i, label)| { + row().key(*label).w(240.0).h(36.0).px(12.0).center_y().fill(k.c.surface_base).radius(k.radius.md) + .child(text(*label).font(k.ty.ui).color(k.c.text_base)) + .transition(Transition::offset(0.0, 12.0).combined(Transition::opacity())) + .enter_delay(stagger.delay(i, ROWS.len())) + }); + col().gap(8.0) + .child(Button::new("Show rows").on_press(|s: &mut G| s.flip("rows")).build(k).key("opener")) + .child(col().key("rows").gap(4.0).children(rows)) +} + +pub fn render(s: &G, k: &Kit, overlays: &mut Vec<El>) -> El { + match STORIES.iter().find(|(id, _)| *id == s.story) { + Some((_, f)) => f(s, k, overlays), + None => index(s, k, overlays), + } +} + +/// Every story stacked, for browsing in a window. +fn index(s: &G, k: &Kit, overlays: &mut Vec<El>) -> El { + let mut c = col().key("index").gap(24.0); + for (id, f) in STORIES { + c = c.child(col().key(*id).gap(8.0).child(caption(k, id)).child(f(s, k, overlays))); + } + c +} + +/// The stories' `font-size: 12px; color: var(--text-weak)` labels (line height inherited). +fn caption(k: &Kit, label: &str) -> El { + text(label).font(TextStyle::new(12.0, 440.0).lh(24.0)).color(k.c.text_weak) +} + +/// `display: flex; gap; align-items: center; flex-wrap: wrap`. +fn flex(gap: f32) -> El { + row().gap(gap).center_y().flex_wrap() +} + +/// CSS `text-transform: capitalize`: the first letter of every word (hyphens split words). +fn title_case(s: &str) -> String { + let mut out = String::new(); + let mut start = true; + for ch in s.chars() { + if start { + out.extend(ch.to_uppercase()) + } else { + out.push(ch) + } + start = !ch.is_alphanumeric(); + } + out +} + +/// The stories' own `toTitleCase`: only the first letter. +fn cap_first(s: &str) -> String { + let mut c = s.chars(); + c.next().map(|f| f.to_uppercase().collect::<String>() + c.as_str()).unwrap_or_default() +} + +const STATES: [(&str, State); 5] = [ + ("default", State::Rest), + ("hover", State::Hover), + ("pressed", State::Pressed), + ("focus", State::Focus), + ("disabled", State::Disabled), +]; + +// --------------------------------------------------------------------------------------------- +// Selectable text and help + +const SERVE: &str = "opencode serve --port 4096 --hostname 0.0.0.0"; + +/// A settings row: a command people can select and copy, highlighted as the kit's fields +/// highlight a selection, and an icon-only copy button that explains itself on hover. +fn text_selectable_help(s: &G, k: &Kit, _: &mut Vec<El>) -> El { + let c = &k.c; + col().w(480.0).gap(8.0) + .child(caption(k, "Run the server from a terminal")) + .child( + row().key("command-row").h(36.0).pl(12.0).pr(4.0).gap(8.0).center_y() + .fill(c.surface_base).radius(k.radius.md).border(1.0, c.border_weak) + .child(text(SERVE).key("command").font(k.ty.mono).color(c.text_base).grow(1.0).shrink() + .selectable(true).selection_color(k.selection())) + .child(IconButton::new(&ic::COPY).variant(IconButtonVariant::Ghost).control_size(ControlSize::Small) + .label("Copy command").on_press_tx(|_: &mut G, tx: &mut Tx| tx.copy(SERVE)).build(k) + .key("copy").help("Copy command")), + ) + .child(row().w(280.0).child(TextInput::new(&s.edits[7]).placeholder("Selected like a field") + .on_edit(|s: &mut G| &mut s.edits[7]).build(k).key("field"))) +} + +const LONG_PATH: &str = "~/Projects/rune/crates/rune-kit/src/components/settings/appearance_panel.rs"; + +/// A path keeps its folder and file name as its box narrows, beside the end and head cuts, each +/// with a `Type::caption` line under it. +fn text_truncate_middle(_: &G, k: &Kit, _: &mut Vec<El>) -> El { + let c = &k.c; + let path = |w: f32, cut: fn(El) -> El, how: &str| col().w(w) + .child(cut(text(LONG_PATH).font(k.ty.ui).color(c.text_base)).selectable(true).selection_color(k.selection())) + .child(text(format!("{how}, {w} pt")).font(k.ty.caption()).color(c.text_weak)); + col().gap(12.0) + .child(path(360.0, El::truncate_middle, "Middle")) + .child(path(240.0, El::truncate_middle, "Middle")) + .child(path(160.0, El::truncate_middle, "Middle")) + .child(path(240.0, El::truncate, "End")) + .child(path(240.0, El::truncate_head, "Head")) +} + +fn scroll_bar_basic(_: &G, k: &Kit, _: &mut Vec<El>) -> El { + scroll_feed(k, 24, None) +} + +/// A feed whose button lengthens or shortens what follows its rows, so its thumb glides to each +/// new length. +fn scroll_bar_grow(s: &G, k: &Kit, _: &mut Vec<El>) -> El { + col().gap(8.0) + .child(Button::new("Change rows").on_press(flip("more")).build(k).key("more")) + .child(scroll_feed(k, 12, Some(if s.is("more") { 600.0 } else { 0.0 }))) +} + +fn scroll_feed(k: &Kit, rows: usize, tail: Option<f32>) -> El { + col() + .key("panel") + .w(360.0) + .h(260.0) + .radius(k.radius.md) + .fill(k.c.layer_01) + .border(1.0, k.c.border_weak) + .clip_soft(k.radius.md) + .child( + col() + .key("feed") + .w_full() + .grow(1.0) + .min_h(0.0) + .padding(8.0) + .gap(4.0) + .scroll(rune::ScrollSpec { stick_bottom: false }) + .children((0..rows).map(|i| { + row() + .key(format!("item-{i}")) + .w_full() + .h(32.0) + .px(10.0) + .center_y() + .justify_between() + .radius(k.radius.sm) + .child(text(format!("Build step {:02}", i + 1)).font(k.ty.ui_compact).color(k.c.text_base)) + .child(text(format!("{} ms", 12 + i * 7)).font(k.ty.small).color(k.c.text_muted)) + })) + .children(tail.map(|h| el().key("tail").w_full().h(h))) + .scroll_bar(k), + ) +} diff --git a/app/vendor/rune/examples/kit-gallery/src/stories/combobox.rs b/app/vendor/rune/examples/kit-gallery/src/stories/combobox.rs new file mode 100644 index 0000000..d4c8e86 --- /dev/null +++ b/app/vendor/rune/examples/kit-gallery/src/stories/combobox.rs @@ -0,0 +1,23 @@ +//! Rune's own combobox scenes; there is no Storybook story to match. + +use rune::El; +use rune_kit::{Combobox, ComboboxOption, Kit}; + +use crate::G; + +pub(super) fn searchable(s: &G, k: &Kit, layer: &mut Vec<El>) -> El { + models(s, false).build(k, layer) +} + +/// The same list, crossfading each keystroke's rows and springing the popover's height. +pub(super) fn animated_filter(s: &G, k: &Kit, layer: &mut Vec<El>) -> El { + models(s, true).build(k, layer) +} + +fn models(s: &G, animate: bool) -> Combobox<G> { + let options: Vec<_> = (0..200).map(|i| ComboboxOption::new(format!("model-{i}"), format!("Model {i:03}"))).collect(); + Combobox::new("model", &s.combo, &options, |s: &mut G| &mut s.combo) + .label("Model").placeholder("Choose model").current(s.pick.get("model").map(String::as_str)) + .animate_filtering(animate) + .on_choose(|s, id, _| { s.pick.insert("model".into(), id.into()); }) +} diff --git a/app/vendor/rune/examples/kit-gallery/src/stories/controls.rs b/app/vendor/rune/examples/kit-gallery/src/stories/controls.rs new file mode 100644 index 0000000..3fbd5b9 --- /dev/null +++ b/app/vendor/rune/examples/kit-gallery/src/stories/controls.rs @@ -0,0 +1,280 @@ +//! Button, IconButton, Switch, Checkbox and Radio. + +use super::*; + +// Button + +pub(super) fn button_playground(_: &G, k: &Kit, _: &mut Vec<El>) -> El { + row().child(Button::new("Button").build(k)) +} + +pub(super) fn button_variants(_: &G, k: &Kit, _: &mut Vec<El>) -> El { + use ButtonVariant::*; + flex(12.0) + .child(Button::new("Neutral").variant(Neutral).build(k)) + .child(Button::new("Danger").variant(Danger).build(k)) + .child(Button::new("Warning").variant(Warning).build(k)) + .child(Button::new("Contrast").variant(Contrast).build(k)) + .child(Button::new("Submit").variant(Submit).build(k)) + .child(Button::new("Ghost").variant(Ghost).build(k)) + .child(Button::new("Ghost muted").variant(GhostMuted).icon(&ic::EDIT).build(k)) + .child(Button::new("Ghost faint").variant(GhostFaint).icon(&ic::EDIT).build(k)) + .child(Button::new("Loading").variant(Loading).build(k)) +} + +pub(super) fn button_sizes(_: &G, k: &Kit, _: &mut Vec<El>) -> El { + flex(12.0) + .child(Button::new("Mini").control_size(ControlSize::Mini).build(k)) + .child(Button::new("Small").control_size(ControlSize::Small).build(k)) + .child(Button::new("Regular").build(k)) + .child(Button::new("Large").control_size(ControlSize::Large).build(k)) + .child(Button::new("Extra large").control_size(ControlSize::ExtraLarge).build(k)) +} + +pub(super) fn button_icon(_: &G, k: &Kit, _: &mut Vec<El>) -> El { + flex(12.0) + .child(Button::new("Regular").icon(&ic::PLUS).build(k)) + .child(Button::new("Large").variant(ButtonVariant::Contrast).control_size(ControlSize::Large).icon(&ic::PLUS).build(k)) +} + +pub(super) fn button_all_states(_: &G, k: &Kit, _: &mut Vec<El>) -> El { + use ButtonVariant::*; + let variants = [ + ("neutral", Neutral), + ("danger", Danger), + ("warning", Warning), + ("contrast", Contrast), + ("submit", Submit), + ("ghost", Ghost), + ("ghost-muted", GhostMuted), + ("ghost-faint", GhostFaint), + ("loading", Loading), + ]; + let mut c = col().gap(12.0); + for (name, v) in variants { + let mut r = row().gap(8.0).flex_wrap(); + for (state, st) in STATES { + r = r.child(Button::new(cap_first(state)).variant(v).state(st).build(k).key(format!("{name}-{state}"))); + } + c = c.child(col().gap(8.0).child(caption(k, &title_case(name))).child(r)); + } + c +} + +// IconButton + +pub(super) fn icon_button_playground(_: &G, k: &Kit, _: &mut Vec<El>) -> El { + row().child(IconButton::new(&ic::PLUS).label("Add").build(k)) +} + +pub(super) fn icon_button_variants(_: &G, k: &Kit, _: &mut Vec<El>) -> El { + use IconButtonVariant::*; + flex(12.0) + .child(IconButton::new(&ic::PLUS).label("Add").variant(Neutral).build(k)) + .child(IconButton::new(&ic::PLUS).label("Add").variant(Contrast).build(k)) + .child(IconButton::new(&ic::ARROW_UP).label("Send").variant(Submit).build(k)) + .child(IconButton::new(&ic::PLUS).label("Add").variant(Ghost).build(k)) +} + +pub(super) fn icon_button_sizes(_: &G, k: &Kit, _: &mut Vec<El>) -> El { + flex(12.0) + .child(IconButton::new(&ic::PLUS).label("Add").control_size(ControlSize::Mini).build(k)) + .child(IconButton::new(&ic::PLUS).label("Add").control_size(ControlSize::Small).build(k)) + .child(IconButton::new(&ic::PLUS).label("Add").build(k)) + .child(IconButton::new(&ic::PLUS).label("Add").control_size(ControlSize::Large).build(k)) + .child(IconButton::new(&ic::PLUS).label("Add").control_size(ControlSize::ExtraLarge).build(k)) +} + +pub(super) fn icon_button_all_states(_: &G, k: &Kit, _: &mut Vec<El>) -> El { + use IconButtonVariant::*; + let variants = [("neutral", Neutral), ("contrast", Contrast), ("submit", Submit), ("ghost", Ghost)]; + let mut c = col().gap(12.0); + for (name, v) in variants { + let mut r = row().gap(8.0).flex_wrap(); + for (state, st) in STATES { + r = r.child(IconButton::new(&ic::PLUS).label("Add").variant(v).state(st).build(k).key(format!("{name}-{state}"))); + } + c = c.child(col().gap(8.0).child(caption(k, &title_case(name))).child(r)); + } + c +} + +// Switch + +/// `defaultChecked` items read as on until toggled. +fn on_by_default(s: &G, key: &str) -> bool { + !s.is(key) +} + +pub(super) fn switch_basic(s: &G, k: &Kit, _: &mut Vec<El>) -> El { + row().child(Switch::new(on_by_default(s, "sw")).label("Enable notifications").on_toggle(flip("sw")).build(k)) +} + +pub(super) fn switch_appearances(s: &G, k: &Kit, _: &mut Vec<El>) -> El { + col() + .gap(12.0) + .child(Switch::new(on_by_default(s, "std")).label("Standard").standard().on_toggle(flip("std")).build(k)) + .child(Switch::new(on_by_default(s, "cmp")).label("Compact").on_toggle(flip("cmp")).build(k)) +} + +pub(super) fn switch_states(s: &G, k: &Kit, _: &mut Vec<El>) -> El { + col() + .gap(12.0) + .child(Switch::new(on_by_default(s, "a")).label("Enabled").on_toggle(flip("a")).build(k)) + .child(Switch::new(s.is("b")).label("Disabled").on_toggle(flip("b")).build(k)) + .child(Switch::new(false).label("Disabled switch").disabled(true).build(k)) +} + +/// Every control size off, on, hovered and pressed. +pub(super) fn switch_sizes(s: &G, k: &Kit, _: &mut Vec<El>) -> El { + let sizes = [("Mini", ControlSize::Mini), ("Small", ControlSize::Small), ("Regular", ControlSize::Regular), + ("Large", ControlSize::Large), ("Extra large", ControlSize::ExtraLarge)]; + col().gap(12.0).children(sizes.into_iter().map(|(name, size)| { + let key = format!("size-{name}"); + let sw = |on: bool, st: State| Switch::new(on).control_size(size).state(st).build(k); + row().gap(12.0).center_y() + .child(caption(k, name).w(80.0)) + .child(Switch::new(s.is(&key)).control_size(size).label(name).hide_label().on_toggle(move |s: &mut G| s.flip(&key)).build(k)) + .child(sw(true, State::Rest)) + .child(sw(false, State::Hover)) + .child(sw(true, State::Pressed)) + })) +} + +/// The compact switch as the web draws it (`Switch::web`): off and on, at rest, hovered, +/// keyboard-focused and disabled. +pub(super) fn switch_web(s: &G, k: &Kit, _: &mut Vec<El>) -> El { + let states = [("Rest", State::Rest), ("Hover", State::Hover), ("Focus", State::Focus), ("Disabled", State::Disabled)]; + col().gap(12.0) + .child(row().gap(12.0).center_y().child(caption(k, "Live").w(80.0)) + .child(Switch::new(s.is("web")).web().label("Web").hide_label().on_toggle(flip("web")).build(k))) + .children(states.into_iter().map(|(name, st)| { + row().gap(16.0).center_y() + .child(caption(k, name).w(80.0)) + .child(Switch::new(false).web().state(st).build(k)) + .child(Switch::new(true).web().state(st).build(k)) + })) +} + +pub(super) fn switch_hidden_label(s: &G, k: &Kit, _: &mut Vec<El>) -> El { + row().child(Switch::new(on_by_default(s, "sw")).label("Hidden label").hide_label().on_toggle(flip("sw")).build(k)) +} + +// Checkbox + +pub(super) fn checkbox_basic(s: &G, k: &Kit, _: &mut Vec<El>) -> El { + row().child(Checkbox::new(on_by_default(s, "cb")).label("Checkbox").on_toggle(flip("cb")).build(k)) +} + +pub(super) fn checkbox_states(s: &G, k: &Kit, _: &mut Vec<El>) -> El { + col() + .gap(12.0) + .child(Checkbox::new(on_by_default(s, "a")).label("Checked").on_toggle(flip("a")).build(k)) + .child(Checkbox::new(s.is("b")).label("Unchecked").on_toggle(flip("b")).build(k)) + .child(Checkbox::new(false).label("Disabled").disabled(true).build(k)) + .child( + Checkbox::new(s.is("d")).label("With description").description("Helper text").on_toggle(flip("d")).build(k), + ) +} + +pub(super) fn checkbox_custom_icon(s: &G, k: &Kit, _: &mut Vec<El>) -> El { + row().child( + Checkbox::new(on_by_default(s, "cb")).label("Custom icon").icon(&ic::CHECK).on_toggle(flip("cb")).build(k), + ) +} + +pub(super) fn checkbox_hidden_label(s: &G, k: &Kit, _: &mut Vec<El>) -> El { + row().child(Checkbox::new(s.is("cb")).label("Hidden label").hide_label().on_toggle(flip("cb")).build(k)) +} + +// Radio + +fn radio_group( + s: &G, + group: &'static str, + default: &str, + label: &str, + items: &[(&'static str, &str, Option<&str>)], +) -> RadioGroup { + let current = s.picked(group, default).to_owned(); + let mut g = RadioGroup::new().label(label); + for (value, l, d) in items { + let v = *value; + let mut item = RadioItem::new(*l, current == v).on_select(move |s: &mut G| { + s.pick.insert(group.to_owned(), v.to_owned()); + }); + if let Some(d) = d { + item = item.description(*d); + } + g = g.item(item); + } + g +} + +pub(super) fn radio_basic(s: &G, k: &Kit, _: &mut Vec<El>) -> El { + radio_group( + s, + "freq", + "daily", + "Notification frequency", + &[ + ("daily", "Daily", Some("Once per day at 9am.")), + ("weekly", "Weekly", Some("Every Monday morning.")), + ("never", "Never", Some("No notifications.")), + ], + ) + .build(k) +} + +pub(super) fn radio_controlled(s: &G, k: &Kit, _: &mut Vec<El>) -> El { + let v = s.picked("ctl", "daily").to_owned(); + col() + .gap(12.0) + .child( + radio_group( + s, + "ctl", + "daily", + "Controlled", + &[("daily", "Daily", None), ("weekly", "Weekly", None), ("never", "Never", None)], + ) + .build(k), + ) + .child(text(format!("Value: {v}")).font(TextStyle::new(12.0, 440.0).lh(24.0)).color(k.c.text_faint)) +} + +pub(super) fn radio_states(s: &G, k: &Kit, _: &mut Vec<El>) -> El { + let disabled_item = RadioGroup::new() + .label("Disabled item") + .item(RadioItem::new("Enabled", s.picked("di", "a") == "a").on_select(|s: &mut G| { + s.pick.insert("di".into(), "a".into()); + })) + .item(RadioItem::new("Disabled", false).disabled(true)); + col() + .gap(20.0) + .child( + radio_group( + s, + "def", + "a", + "Default", + &[("a", "Option A", None), ("b", "Option B", Some("Has a description."))], + ) + .build(k), + ) + .child( + RadioGroup::new() + .label("Disabled group") + .disabled(true) + .item(RadioItem::new("Option A", true)) + .item(RadioItem::new("Option B", false)) + .build(k), + ) + .child(disabled_item.build(k)) + .child( + radio_group(s, "inv", "a", "Invalid", &[("a", "Option A", None), ("b", "Option B", None)]) + .description("Pick one option.") + .invalid(true) + .build(k), + ) +} diff --git a/app/vendor/rune/examples/kit-gallery/src/stories/display.rs b/app/vendor/rune/examples/kit-gallery/src/stories/display.rs new file mode 100644 index 0000000..4ad364e --- /dev/null +++ b/app/vendor/rune/examples/kit-gallery/src/stories/display.rs @@ -0,0 +1,355 @@ +//! Card, List, Accordion, Collapsible, Badge, Keybind, Spinner, Loader, Progress and SegmentedControl. + +use super::*; + +// Card, List, Accordion, Collapsible + +fn card(k: &Kit, accent: Option<rune::Color>, icon: Option<&'static rune::Icon>) -> El { + let mut c = Card::new() + .title("Card title", icon) + .description("Small supporting text.") + .action(Button::new("Action").build(k)); + if let Some(a) = accent { + c = c.accent(a); + } + c.build(k) +} + +pub(super) fn card_normal(_: &G, k: &Kit, _: &mut Vec<El>) -> El { + card(k, None, None) +} +pub(super) fn card_error(_: &G, k: &Kit, _: &mut Vec<El>) -> El { + card(k, Some(k.c.danger.icon), Some(&ic::CIRCLE_BAN_SIGN_BOLD)) +} +pub(super) fn card_warning(_: &G, k: &Kit, _: &mut Vec<El>) -> El { + card(k, Some(k.c.warning.icon), Some(&ic::WARNING_BOLD)) +} +pub(super) fn card_success(_: &G, k: &Kit, _: &mut Vec<El>) -> El { + card(k, Some(k.c.success.icon), Some(&ic::CIRCLE_CHECK_BOLD)) +} +pub(super) fn card_info(_: &G, k: &Kit, _: &mut Vec<El>) -> El { + card(k, Some(k.c.info.icon), Some(&ic::HELP_BOLD)) +} + +fn list(s: &G, items: &[&str], search: bool) -> List { + let mut l = List::new(); + if search { + l = l.search(&s.edits[3], "").on_search_edit(|s: &mut G| &mut s.edits[3]); + } + for i in items { + l = l.item(ListItem::new(*i)); + } + l +} + +pub(super) fn list_basic(s: &G, k: &Kit, _: &mut Vec<El>) -> El { + list(s, &["One", "Two", "Three", "Four"], true).build(k) +} +pub(super) fn list_grouped(s: &G, k: &Kit, _: &mut Vec<El>) -> El { + List::new() + .search(&s.edits[3], "") + .item(ListItem::new("Alpha").group("Group A")) + .item(ListItem::new("Bravo").group("Group A")) + .item(ListItem::new("Delta").group("Group B")) + .build(k) +} +pub(super) fn list_empty(s: &G, k: &Kit, _: &mut Vec<El>) -> El { + list(s, &[], true).build(k) +} +pub(super) fn list_with_add(s: &G, k: &Kit, _: &mut Vec<El>) -> El { + list(s, &["One", "Two"], true) + .add_row( + row() + .px(8.0) + .py(6.0) + .child(text("Add item").font(TextStyle::new(14.0, 500.0).lh(21.0)).color(k.c.text_strong)), + ) + .build(k) +} +pub(super) fn list_divider(s: &G, k: &Kit, _: &mut Vec<El>) -> El { + list(s, &["One", "Two", "Three"], false).divider().build(k) +} +pub(super) fn list_active_icon(s: &G, k: &Kit, _: &mut Vec<El>) -> El { + list(s, &["Alpha", "Beta", "Gamma"], false).active_icon(&ic::CHEVRON_RIGHT).build(k) +} +pub(super) fn list_no_search(s: &G, k: &Kit, _: &mut Vec<El>) -> El { + list(s, &["One", "Two", "Three"], false).build(k) +} + +fn accordion_content(k: &Kit, s: &str, padded: bool) -> El { + let t = text(s).font(TextStyle::new(13.0, 440.0).lh(24.0)); + if padded { row().py(8.0).child(t.color(k.c.text_weak)) } else { row().child(t.color(k.c.std_text)) } +} + +/// The web story's `value="first"` arrives as a control arg and renders closed; so does this. +pub(super) fn accordion_basic(s: &G, k: &Kit, _: &mut Vec<El>) -> El { + let open = s.picked("acc", "").to_owned(); + let pick = |v: &'static str| { + move |s: &mut G| { + let cur = s.picked("acc", "").to_owned(); + s.pick.insert("acc".into(), if cur == v { String::new() } else { v.into() }); + } + }; + col().w(420.0).gap(8.0).child( + Accordion::new() + .item( + AccordionItem::new("First") + .expanded(open == "first") + .child(accordion_content(k, "Accordion content.", true)) + .on_toggle(pick("first")), + ) + .item( + AccordionItem::new("Second") + .expanded(open == "second") + .child(accordion_content(k, "More content.", true)) + .on_toggle(pick("second")), + ) + .build(k), + ) +} + +pub(super) fn accordion_multiple(s: &G, k: &Kit, _: &mut Vec<El>) -> El { + Accordion::new() + .item( + AccordionItem::new("First") + .expanded(!s.is("a1")) + .child(accordion_content(k, "Accordion content.", false)) + .on_toggle(flip("a1")), + ) + .item( + AccordionItem::new("Second") + .expanded(!s.is("a2")) + .child(accordion_content(k, "More content.", false)) + .on_toggle(flip("a2")), + ) + .build(k) +} + +/// The web story passes `value="first"` without `multiple` or `collapsible` and renders closed. +pub(super) fn accordion_single(_: &G, k: &Kit, _: &mut Vec<El>) -> El { + Accordion::new() + .item(AccordionItem::new("First").expanded(false).child(accordion_content(k, "Accordion content.", false))) + .build(k) +} + +pub(super) fn collapsible_basic(s: &G, k: &Kit, _: &mut Vec<El>) -> El { + Collapsible::new("Details", !s.is("c")) + .child( + row().pt(8.0).child( + text("Optional details sit here.").font(TextStyle::new(13.0, 440.0).lh(24.0)).color(k.c.text_weak), + ), + ) + .on_toggle(flip("c")) + .build(k) +} + +pub(super) fn collapsible_ghost(s: &G, k: &Kit, _: &mut Vec<El>) -> El { + Collapsible::new("Ghost trigger", s.is("c")) + .ghost() + .child( + row().pt(8.0).child(text("Ghost content.").font(TextStyle::new(13.0, 440.0).lh(24.0)).color(k.c.text_weak)), + ) + .on_toggle(flip("c")) + .build(k) +} + +// Badge, Keybind, Spinner, Loader, Progress, SegmentedControl + +pub(super) fn badge_basic(_: &G, k: &Kit, _: &mut Vec<El>) -> El { + row().child(Badge::new("Label").build(k)) +} +pub(super) fn badge_appearances(_: &G, k: &Kit, _: &mut Vec<El>) -> El { + row().gap(8.0).center_y().child(Badge::new("Standard").standard().build(k)).child(Badge::new("Compact").build(k)) +} +pub(super) fn badge_subtle(_: &G, k: &Kit, _: &mut Vec<El>) -> El { + row() + .gap(8.0) + .center_y() + .child(Badge::new("1").variant(BadgeVariant::Subtle).build(k)) + .child(Badge::new("12").variant(BadgeVariant::Subtle).build(k)) +} +pub(super) fn badge_high_contrast(_: &G, k: &Kit, _: &mut Vec<El>) -> El { + row().gap(8.0).center_y().child(Badge::new("Label").build(k)).child(Badge::new("Label").high_contrast().build(k)) +} +pub(super) fn badge_accent(_: &G, k: &Kit, _: &mut Vec<El>) -> El { + row().child(Badge::new("New").variant(BadgeVariant::Accent).build(k)) +} + +pub(super) fn keybind_playground(_: &G, k: &Kit, _: &mut Vec<El>) -> El { + row().child(Keybind::new(&["⌘"]).build(k)) +} +pub(super) fn keybind_variants(_: &G, k: &Kit, _: &mut Vec<El>) -> El { + row() + .gap(24.0) + .center_y() + .child(Keybind::new(&["⌘"]).build(k)) + .child(Keybind::new(&["⌘"]).variant(KeybindVariant::Ghost).build(k)) +} +pub(super) fn keybind_multiple(_: &G, k: &Kit, _: &mut Vec<El>) -> El { + row() + .gap(24.0) + .center_y() + .child(Keybind::new(&["⌘", "K"]).build(k)) + .child(Keybind::new(&["⌘", "K"]).variant(KeybindVariant::Ghost).build(k)) + .child(Keybind::new(&["Ctrl", "B"]).build(k)) + .child(Keybind::new(&["Ctrl", "B"]).variant(KeybindVariant::Ghost).build(k)) +} +pub(super) fn keybind_all(_: &G, k: &Kit, _: &mut Vec<El>) -> El { + let line = |name: &str, v: KeybindVariant| { + row() + .gap(24.0) + .center_y() + .child( + text(name) + .w(50.0) + .font(TextStyle::new(11.0, 440.0).lh(24.0)) + .color(rune::theme::hex("#808080").unwrap_or_default()), + ) + .child(Keybind::new(&["⌘"]).variant(v).build(k)) + .child(Keybind::new(&["⌘", "K"]).variant(v).build(k)) + .child(Keybind::new(&["⌘", "⇧", "P"]).variant(v).build(k)) + .child(Keybind::new(&["Ctrl", "Shift", "B"]).variant(v).build(k)) + }; + col().gap(16.0).child(line("Neutral", KeybindVariant::Neutral)).child(line("Ghost", KeybindVariant::Ghost)) +} + +/// Keyboard symbols next to capitals, in both families at 13 and 15 pt, then keycaps. +pub(super) fn keybind_symbols(_: &G, k: &Kit, _: &mut Vec<El>) -> El { + const SAMPLE: &str = "⌘K ⇧P ⏎ ⌫ ⎋ ⌥⌃ ←↑ HP"; + let mut c = col().gap(10.0); + for mono in [false, true] { + for size in [13.0, 15.0] { + let font = TextStyle::new(size, 500.0).lh(size * 1.5); + let font = if mono { font.mono() } else { font }; + let label = format!("{} {size}", if mono { "Plex Mono" } else { "Inter" }); + c = c.child( + row() + .gap(16.0) + .center_y() + .child(text(label).w(96.0).font(TextStyle::new(11.0, 440.0).lh(16.0)).color(k.c.text_faint)) + .child(text(SAMPLE).font(font).color(k.c.text_base)), + ); + } + let mut kk = k.clone(); + if mono { + kk.ty.small_medium = kk.ty.small_medium.mono(); + } + let mut caps = row().gap(12.0).center_y().child( + text(if mono { "Plex Mono caps" } else { "Inter caps" }) + .w(96.0) + .font(TextStyle::new(11.0, 440.0).lh(16.0)) + .color(k.c.text_faint), + ); + let sets: [&[&str]; 6] = [&["⌘", "⇧", "P"], &["⇧", "⏎"], &["⌫"], &["⎋"], &["⌥", "⌃", "K"], &["←", "↑"]]; + for keys in sets { + caps = caps.child(Keybind::new(keys).build(&kk)); + } + c = c.child(caps); + } + c +} + +pub(super) fn spinner_basic(_: &G, k: &Kit, _: &mut Vec<El>) -> El { + row().child(Spinner::new().build(k)) +} +pub(super) fn spinner_sizes(_: &G, k: &Kit, _: &mut Vec<El>) -> El { + row() + .gap(16.0) + .center_y() + .child(Spinner::new().size(12.0).build(k)) + .child(Spinner::new().size(20.0).build(k)) + .child(Spinner::new().size(28.0).build(k)) +} +pub(super) fn loader_basic(_: &G, k: &Kit, _: &mut Vec<El>) -> El { + row().child(Loader::new().build(k)) +} +pub(super) fn loader_sizes(_: &G, k: &Kit, _: &mut Vec<El>) -> El { + row() + .gap(16.0) + .center_y() + .child(Loader::new().size(12.0).build(k)) + .child(Loader::new().build(k)) + .child(Loader::new().size(24.0).build(k)) +} +pub(super) fn progress_basic(_: &G, k: &Kit, _: &mut Vec<El>) -> El { + Progress::new(Some(0.6)).label("Progress").show_value().build(k) +} +pub(super) fn progress_no_label(_: &G, k: &Kit, _: &mut Vec<El>) -> El { + Progress::new(Some(0.3)).build(k) +} +pub(super) fn progress_indeterminate(_: &G, k: &Kit, _: &mut Vec<El>) -> El { + Progress::new(None).label("Loading").build(k) +} + +pub(super) fn segmented_basic(s: &G, k: &Kit, _: &mut Vec<El>) -> El { + let sel = s.picked("seg", "0").parse().unwrap_or(0); + row().child( + SegmentedControl::new(&["Label", "Label", "Label", "Label"], Some(sel)) + .on_pick(|s: &mut G, i: usize, _: &mut Tx| { + s.pick.insert("seg".into(), i.to_string()); + }) + .build(k), + ) +} +pub(super) fn segmented_controlled(s: &G, k: &Kit, _: &mut Vec<El>) -> El { + let sel: usize = s.picked("seg", "1").parse().unwrap_or(1); + col() + .gap(12.0) + .items_start() + .child( + SegmentedControl::new(&["List", "Grid", "Board"], Some(sel)) + .label("View") + .on_pick(|s: &mut G, i: usize, _: &mut Tx| { + s.pick.insert("seg".into(), i.to_string()); + }) + .build(k), + ) + .child( + text(format!("Value: {}", ["a", "b", "c"][sel.min(2)])) + .font(TextStyle::new(12.0, 440.0).lh(24.0)) + .color(rune::theme::hex("#808080").unwrap_or_default()), + ) +} + +/// A copy label and countdown, sans and mono. Each press of "Roll" advances one step: +/// "Copy password" → "Copied, clears in 0:30" → "… 0:29", and the countdown "0:30" → "0:29" → …. +pub(super) fn rolling_text_basic(s: &G, k: &Kit, _: &mut Vec<El>) -> El { + let step: u32 = s.picked("roll", "0").parse().unwrap_or(0); + let label = if step == 0 { "Copy password".to_owned() } else { format!("Copied, clears in 0:{:02}", 31 - step.min(31)) }; + let count = format!("0:{:02}", 30 - step.min(30)); + let big = TextStyle::new(28.0, 600.0); + let line = |name: &str, e: El| row().gap(12.0).center_y().child(text(name).font(k.ty.small).color(k.c.text_faint).w(56.0)).child(e); + col() + .gap(14.0) + .child( + row() + .gap(8.0) + .child( + Button::new("Roll") + .on_press(|s: &mut G| { + let n: u32 = s.picked("roll", "0").parse().unwrap_or(0); + s.pick.insert("roll".into(), (n + 1).to_string()); + }) + .build(k) + .key("roll"), + ) + .child(Button::new(label.clone()).rolling("roll-button").build(k).key("rolling-button")) + .child(Button::new("Cancel").build(k).key("cancel")), + ) + .child(line("Sans", RollingText::new("roll-sans", label.clone()).font(k.ty.body).build(k))) + .child(line("Mono", RollingText::new("roll-mono", label.clone()).font(k.ty.mono).build(k))) + .child(line("Centred", row().w(260.0).center().child(RollingText::new("roll-centre", label).font(k.ty.body).build(k)))) + .child(line("Count", RollingText::new("count-sans", count.clone()).font(big).from(Edge::Top).build(k))) + .child(line("", RollingText::new("count-mono", count).font(big.mono()).from(Edge::Top).build(k))) +} + +/// `ScrollBarStyle::scroll_view`: the `@opencode/ui` ScrollView thumb, hidden at rest and shown while +/// the pointer is over the list or it scrolls. +pub(super) fn scroll_view_thumb(_: &G, k: &Kit, _: &mut Vec<El>) -> El { + let rows = (1..=24).map(|i| row().key(format!("row{i}")).h(28.0).px(12.0).center_y() + .child(text(format!("Row {i}")).font(k.ty.ui_compact).color(k.c.text_base))); + col().key("list").w(240.0).h(180.0).radius(k.radius.md).fill(k.c.bg_base).border(1.0, k.c.border_weak) + .scroll(rune::ScrollSpec { stick_bottom: false }) + .child(col().children(rows)) + .scroll_bar_styled(ScrollBarStyle::scroll_view(k)) +} diff --git a/app/vendor/rune/examples/kit-gallery/src/stories/icons.rs b/app/vendor/rune/examples/kit-gallery/src/stories/icons.rs new file mode 100644 index 0000000..033dde1 --- /dev/null +++ b/app/vendor/rune/examples/kit-gallery/src/stories/icons.rs @@ -0,0 +1,118 @@ +//! FileIcon and Icon, as `file-icon.stories.tsx` and `icon.stories.tsx` lay them out, and Rune's own +//! catalogs of every OpenCode icon, file-type badge and file tree icon, and its file tree. + +use rune::icon; +use rune_theme_opencode::{file_icons, tree_icons}; + +use super::*; + +/// `display: grid; grid-template-columns: repeat(auto-fill, minmax(min, 1fr)); gap` at the +/// story's 672-point width. +fn grid(min: f32, gap: f32, cells: Vec<El>) -> El { + let columns = ((672.0 + gap) / (min + gap)).floor().max(1.0) as usize; + let width = (672.0 - gap * (columns - 1) as f32) / columns as f32; + let mut rows = col().gap(gap); + let mut cells = cells.into_iter().peekable(); + while cells.peek().is_some() { + rows = rows.child(row().gap(gap).children(cells.by_ref().take(columns).map(|c| c.w(width)))); + } + rows +} + +/// The stories' `font-size: 12px; color: var(--text-weak)` names. +fn name(k: &Kit, label: &str) -> El { + text(label).font(TextStyle::new(12.0, 440.0).lh(18.0)).color(k.c.text_weak).truncate() +} + +pub(super) fn file_icon_samples(_: &G, k: &Kit, _: &mut Vec<El>) -> El { + let items = [ + ("README.md", false), + ("package.json", false), + ("tsconfig.json", false), + ("index.ts", false), + ("styles.css", false), + ("logo.svg", false), + ("photo.png", false), + ("Dockerfile", false), + (".env", false), + ("src", true), + ("public", true), + ]; + let cells = items + .iter() + .map(|&(path, dir)| { + let glyph = if dir { file_icons::folder(path, false) } else { file_icons::file(path) }; + row().gap(8.0).center_y().child(icon(glyph, 16.0).color(k.c.text_base)).child(name(k, path)) + }) + .collect(); + grid(120.0, 12.0, cells) +} + +pub(super) fn file_icon_folder(_: &G, k: &Kit, _: &mut Vec<El>) -> El { + row().child(icon(file_icons::folder("src", true), 16.0).color(k.c.text_base)) +} + +pub(super) fn icon_gallery(_: &G, k: &Kit, _: &mut Vec<El>) -> El { + let names = [ + "archive", "arrow-left", "arrow-right", "arrow-up-right", "branch", "check", "chevron-down", "close", "code-slash", "edit", + "folder", "graduation-cap", "help", "magnifying-glass", "menu", "monitor", "outline-arrow-to-corner-top-right", + "outline-copy", "outline-dots", "outline-eye", "outline-eye-slash", "outline-hexagonal-warning", "plus", "review", + "settings-gear", "trash", "workspace", + ]; + // A name the catalog lacks draws `plus`, as `Icon` does. + let find = |n: &str| ic::ALL.iter().copied().find(|i| i.name == n).unwrap_or(&ic::PLUS); + let cells = names + .iter() + .map(|n| { + col().gap(6.0).items_center().child(icon(find(n), 16.0).color(k.c.icon_base)).child( + text(*n).font(TextStyle::new(10.0, 440.0).lh(15.0)).color(k.c.text_weak).truncate(), + ) + }) + .collect(); + grid((672.0 - 48.0) / 5.0, 12.0, cells) +} + +/// Every icon in OpenCode's catalog, by name. +pub(super) fn icon_catalog(_: &G, k: &Kit, _: &mut Vec<El>) -> El { + let cells = ic::ALL + .iter() + .map(|i| row().gap(8.0).center_y().child(icon(i, 16.0).color(k.c.icon_base)).child(name(k, i.name))) + .collect(); + grid(128.0, 8.0, cells) +} + +/// Every FileIcon badge and folder icon. +pub(super) fn file_icon_catalog(_: &G, k: &Kit, _: &mut Vec<El>) -> El { + let cells = file_icons::all().iter().map(|i| row().gap(8.0).center_y().child(icon(i, 16.0).color(k.c.text_base)).child(name(k, i.name))).collect(); + grid(128.0, 8.0, cells) +} + +/// Every file tree icon, at rest in `icon-muted` and in its type's colour as a selected row draws it. +pub(super) fn tree_icon_catalog(_: &G, k: &Kit, _: &mut Vec<El>) -> El { + let muted = rune_theme_opencode::theme(k.dark).color("v2-icon-icon-muted"); + let cells = tree_icons::all() + .map(|t| { + row() + .gap(6.0) + .center_y() + .child(icon(t.icon(), 16.0).color(muted)) + .child(icon(t.icon(), 16.0).color(t.color(k.dark))) + .child(name(k, t.token())) + }) + .collect(); + grid(128.0, 8.0, cells) +} + +/// Desktop's file tree: folders show only a chevron, files their type's icon, coloured on the +/// selected row. +pub(super) fn file_tree(s: &G, k: &Kit, _: &mut Vec<El>) -> El { + let dark = k.dark; + let tree = Tree::new(|s: &G| &s.files, |s: &mut G| &mut s.files, FileNode::label) + .row(move |n, r| tree_icons::item(&n.name, &n.path, n.dir, r.selected, dark)) + .style(tree_icons::style(k)) + .name("Files") + .build(s, k) + .h(8.0 * 28.0 + 8.0); + // The tree's scroller: 4 points above the rows and 8 either side (`TREE_UNSAFE_CSS`). + col().w(240.0).fill(k.c.bg_base).pt(4.0).px(8.0).child(tree) +} diff --git a/app/vendor/rune/examples/kit-gallery/src/stories/inputs.rs b/app/vendor/rune/examples/kit-gallery/src/stories/inputs.rs new file mode 100644 index 0000000..32822b1 --- /dev/null +++ b/app/vendor/rune/examples/kit-gallery/src/stories/inputs.rs @@ -0,0 +1,242 @@ +//! TextInput, Textarea, Field and Select. + +use super::*; + +// TextInput, Textarea, Field +// +// Solid passes `defaultValue` to these inputs as an attribute the DOM ignores, so the web +// stories show their placeholders; the gallery does the same. + +fn edit(v: &str) -> TextEdit { + TextEdit::new(v) +} + +fn grid(gap: f32, width: f32) -> El { + col().gap(gap).w(width).items_stretch() +} + +pub(super) fn text_input_playground(s: &G, k: &Kit, _: &mut Vec<El>) -> El { + row().child(TextInput::new(&s.edits[0]).placeholder("Placeholder").on_edit(|s: &mut G| &mut s.edits[0]).build(k)) +} + +pub(super) fn text_input_copy(_: &G, k: &Kit, _: &mut Vec<El>) -> El { + row().child(TextInput::new(&edit("")).placeholder("api.example.com/v1").copy_button().build(k)) +} + +pub(super) fn text_input_controlled(s: &G, k: &Kit, _: &mut Vec<El>) -> El { + let value = if s.edits[1].text.is_empty() && !s.is("typed") { + "Controlled value".to_owned() + } else { + s.edits[1].text.clone() + }; + col() + .gap(12.0) + .child(TextInput::new(&edit(&value)).placeholder("Type here…").build(k)) + .child(text(format!("Value: {value}")).font(TextStyle::new(12.0, 440.0).lh(24.0)).color(k.c.std_text)) +} + +pub(super) fn text_input_appearances(_: &G, k: &Kit, _: &mut Vec<El>) -> El { + grid(20.0, 280.0) + .child(TextInput::new(&edit("")).placeholder("Base (28px)").build(k)) + .child(TextInput::new(&edit("")).placeholder("Large (32px)").large().build(k)) + .child(TextInput::new(&edit("")).placeholder("Large with copy").large().copy_button().build(k)) +} + +pub(super) fn text_input_with_field(_: &G, k: &Kit, _: &mut Vec<El>) -> El { + grid(24.0, 280.0) + .child( + Field::new() + .label("Label") + .info() + .prefix("Prefix") + .control(TextInput::new(&edit("")).placeholder("Text").copy_button().build(k)) + .suffix("Suffix") + .build(k), + ) + .child( + Field::new() + .label("Label") + .prefix("Prefix") + .control(TextInput::new(&edit("")).placeholder("Text").copy_button().invalid(true).build(k)) + .suffix("Suffix") + .build(k), + ) +} + +pub(super) fn text_input_states(_: &G, k: &Kit, _: &mut Vec<El>) -> El { + grid(20.0, 280.0) + .child(TextInput::new(&edit("")).placeholder("Default").build(k)) + .child(TextInput::new(&edit("")).placeholder("With value").build(k)) + .child(TextInput::new(&edit("")).placeholder("With copy").copy_button().build(k)) + .child(TextInput::new(&edit("")).placeholder("Invalid").invalid(true).copy_button().build(k)) + .child(TextInput::new(&edit("")).placeholder("Disabled").disabled(true).build(k)) + .child(TextInput::new(&edit("")).placeholder("Disabled with value").disabled(true).copy_button().build(k)) +} + +pub(super) fn textarea_playground(s: &G, k: &Kit, _: &mut Vec<El>) -> El { + row().child(TextArea::new(&s.edits[2]).placeholder("Placeholder").on_edit(|s: &mut G| &mut s.edits[2]).build(k)) +} + +pub(super) fn textarea_controlled(_: &G, k: &Kit, _: &mut Vec<El>) -> El { + grid(12.0, 280.0) + .child(TextArea::new(&edit("")).placeholder("Type here…").build(k)) + .child(text("Value: Controlled value").font(TextStyle::new(12.0, 440.0).lh(24.0)).color(k.c.std_text)) +} + +pub(super) fn textarea_with_field(_: &G, k: &Kit, _: &mut Vec<El>) -> El { + grid(24.0, 280.0) + .child( + Field::new() + .label("Label") + .info() + .prefix("Prefix") + .control(TextArea::new(&edit("")).placeholder("Text").build(k)) + .suffix("Suffix") + .build(k), + ) + .child( + Field::new() + .label("Label") + .prefix("Prefix") + .control(TextArea::new(&edit("")).placeholder("Text").invalid(true).build(k)) + .suffix("Suffix") + .build(k), + ) +} + +pub(super) fn textarea_states(_: &G, k: &Kit, _: &mut Vec<El>) -> El { + grid(20.0, 280.0) + .child(TextArea::new(&edit("")).placeholder("Default").build(k)) + .child(TextArea::new(&edit("")).placeholder("With value").build(k)) + .child(TextArea::new(&edit("")).placeholder("Invalid").invalid(true).build(k)) + .child(TextArea::new(&edit("")).placeholder("Disabled").disabled(true).build(k)) + .child(TextArea::new(&edit("")).placeholder("Disabled with value").disabled(true).build(k)) +} + +pub(super) fn field_text_input(_: &G, k: &Kit, _: &mut Vec<El>) -> El { + grid(0.0, 280.0).child( + Field::new() + .label("Label") + .info() + .prefix("Prefix") + .control(TextInput::new(&edit("")).placeholder("Text").copy_button().build(k)) + .suffix("Suffix") + .build(k), + ) +} + +pub(super) fn field_direct_child(_: &G, k: &Kit, _: &mut Vec<El>) -> El { + grid(0.0, 280.0).child( + Field::new() + .label("Label") + .prefix("Prefix") + .control(TextInput::new(&edit("")).placeholder("Text").build(k)) + .suffix("Suffix") + .build(k), + ) +} + +pub(super) fn field_textarea(_: &G, k: &Kit, _: &mut Vec<El>) -> El { + grid(0.0, 280.0).child( + Field::new() + .label("Label") + .prefix("Prefix") + .control(TextArea::new(&edit("")).placeholder("Text").build(k)) + .suffix("Suffix") + .build(k), + ) +} + +pub(super) fn field_invalid(_: &G, k: &Kit, _: &mut Vec<El>) -> El { + grid(0.0, 280.0).child( + Field::new() + .label("Label") + .prefix("Prefix") + .control(TextInput::new(&edit("")).placeholder("Text").copy_button().invalid(true).build(k)) + .suffix("Suffix") + .build(k), + ) +} + +// Select + +const FRUITS: [&str; 5] = ["Apple", "Banana", "Cherry", "Date", "Elderberry"]; + +fn fruit_select(s: &G, key: &'static str) -> Select { + let current = s.pick.get(key).cloned(); + Select::new(key, &FRUITS) + .label("Fruit") + .placeholder("Pick a fruit") + .current(current.as_deref()) + .open(is_open(s, key)) + .on_toggle(toggle(key)) + .on_close(close) + .on_choose(move |s: &mut G, v: &str, _: &mut Tx| { + s.pick.insert(key.to_owned(), v.to_owned()); + s.open = None; + }) +} + +pub(super) fn select_playground(s: &G, k: &Kit, layer: &mut Vec<El>) -> El { + row().child(fruit_select(s, "select").build(k, layer)) +} + +pub(super) fn select_grouped(s: &G, k: &Kit, layer: &mut Vec<El>) -> El { + let cities = + [("North", "Boston"), ("South", "Miami"), ("South", "Atlanta"), ("West", "Seattle"), ("West", "Denver")]; + let current = s.pick.get("select").cloned(); + row().child( + Select::grouped("select", &cities) + .label("City") + .placeholder("Pick a fruit") + .current(current.as_deref()) + .open(is_open(s, "select")) + .on_toggle(toggle("select")) + .on_close(close) + .on_choose(|s: &mut G, v: &str, _: &mut Tx| { + s.pick.insert("select".into(), v.to_owned()); + s.open = None; + }) + .build(k, layer), + ) +} + +pub(super) fn select_invalid(s: &G, k: &Kit, layer: &mut Vec<El>) -> El { + row().child(fruit_select(s, "select").invalid(true).build(k, layer)) +} + +pub(super) fn select_disabled(_: &G, k: &Kit, layer: &mut Vec<El>) -> El { + row().child(Select::new("select", &FRUITS).current(Some("Cherry")).disabled(true).build(k, layer)) +} + +/// Both triggers in every state, forced, and an open field with its listbox: the inline trigger's +/// rest, hover, open and disabled; the 280 x 28 field's rest, hover, keyboard focus, open, +/// invalid and disabled. +pub(super) fn select_states(s: &G, k: &Kit, layer: &mut Vec<El>) -> El { + let pick = |key: &'static str, st: State| Select::new(key, &FRUITS).label("Fruit").placeholder("Pick a fruit").current(Some("Banana")).state(st); + let line = |name: &str, e: El| row().gap(16.0).center_y().child(text(name.to_owned()).font(k.ty.small).color(k.c.text_faint).w(72.0)).child(e); + let field = |key: &'static str, st: State| pick(key, st).appearance(SelectAppearance::Field); + col().gap(10.0) + .child(line("Inline", pick("i1", State::Rest).trigger(k))) + .child(line("Hover", pick("i2", State::Hover).trigger(k))) + .child(line("Open", pick("i3", State::Rest).open(true).trigger(k))) + .child(line("Disabled", pick("i4", State::Rest).disabled(true).trigger(k))) + .child(line("Field", field("f1", State::Rest).trigger(k))) + .child(line("Hover", field("f2", State::Hover).trigger(k))) + .child(line("Focus", field("f3", State::Focus).trigger(k))) + .child(line("Invalid", field("f4", State::Rest).invalid(true).trigger(k))) + .child(line("Disabled", field("f5", State::Rest).disabled(true).trigger(k))) + .child(line("Open", fruit_select(s, "select").appearance(SelectAppearance::Field).build(k, layer))) +} + +pub(super) fn select_with_field(s: &G, k: &Kit, layer: &mut Vec<El>) -> El { + grid(0.0, 280.0).child( + Field::new() + .label("Fruit") + .info() + .prefix("Optional helper") + .control(fruit_select(s, "select").build(k, layer)) + .suffix("After selection") + .build(k), + ) +} diff --git a/app/vendor/rune/examples/kit-gallery/src/stories/markdown.rs b/app/vendor/rune/examples/kit-gallery/src/stories/markdown.rs new file mode 100644 index 0000000..1ba0933 --- /dev/null +++ b/app/vendor/rune/examples/kit-gallery/src/stories/markdown.rs @@ -0,0 +1,697 @@ +//! Markdown. + +use super::*; + +const MARKDOWN: &str = "# Rune markdown\n\nParagraphs take **strong**, *emphasis*, `inline code` and [links](https://rune.dev). \ +Links are styled now and become clickable with rich-text spans.\n\n## Lists\n\n- First item\n- Second item with `code`\n\n\ +1. One\n2. Two\n\n### Quote and rule\n\n> Quoted text sits behind a rule.\n\n---\n\n#### A muted heading\n\n```rust\nfn main() {\n println!(\"hello\");\n}\n```\n"; + +pub(super) fn markdown_basic(_: &G, k: &Kit, _: &mut Vec<El>) -> El { + col().w(560.0).child(Markdown::new(MARKDOWN).on_link(|_: &mut G, _| {}).build(k)) +} + +/// Tables, diffs and diagrams: what an agent's answer about a code change looks like. +const WALKTHROUGH: &str = r#"## Retry with backoff + +The client now retries failed requests with **exponential backoff**, capped at `max_delay`. + +| Attempt | Delay | Jitter | Notes | +|:--------|------:|:------:|-------| +| 1 | 0 ms | none | first try | +| 2 | 200 ms | ±20% | after a `503` | +| 3 | 400 ms | ±20% | | +| 4 | 800 ms | ±20% | gives up after this one and reports the **last** error | + +```diff +@@ -12,7 +12,9 @@ impl Client { + pub async fn send(&self, req: Request) -> Result<Response> { +- self.inner.send(req).await ++ retry(self.policy, || self.inner.send(req.clone())) ++ .await ++ .map_err(Error::from) + } +``` + +```mermaid +flowchart LR + A[Request] --> B{Status?} + B -->|2xx| C([Done]) + B -->|503| D[Wait backoff] + D --> E[(Retry budget)] + E -.->|left| A + E -->|spent| F[Report error] +``` + +```mermaid +sequenceDiagram + autonumber + actor U as User + participant C as Client + participant S as Server + U->>+C: send(req) + loop until success or budget spent + C->>S: POST /items + S--xC: 503 Unavailable + Note right of S: overloaded + end + C-->>-U: Err(last error) +``` +"#; + +/// Subgraphs, every node shape, a left-to-right chart that fits, a pie chart, and an unsupported +/// diagram. +const DIAGRAMS: &str = r#"```mermaid +graph TD + subgraph client [Client] + UI[Web app] --> Cache[(Local cache)] + end + subgraph edge [Edge] + LB{{Load balancer}} --> W1[Worker 1] & W2[Worker 2] + end + UI ==> LB + W1 --> DB[(Postgres)] + W2 --> DB + W2 -.-> Q>Queue] +``` + +```mermaid +flowchart LR + a([Stadium]) --> b[[Subroutine]] --> c((Circle)) --o d{Diamond} + d --x e[/Lean/] <--> f[/Trapezoid\] +``` + +| Narrow | Table | +|---|---| +| wraps | when its column runs out of room, like this long cell does | + +```mermaid +pie title Pets + "Dogs" : 386 + "Cats" : 85 +``` + +```mermaid +kanban + Todo + Write docs +``` +"#; + +pub(super) fn markdown_diagrams(_: &G, k: &Kit, _: &mut Vec<El>) -> El { + col().w(520.0).child(Markdown::new(DIAGRAMS).build(k)) +} + +/// What the lenient parser reads: an unclosed `[/…` label is a plain rectangle, a line that doesn't +/// read is skipped; plus a class diagram and sequence `box` groups with a `rect` band. +const LENIENT: &str = r#"```mermaid +flowchart LR + A[List + count] --> B[/items split view] + B --> C[Details] + C --> D[Pause / Resume / Delete] + C -- --> D +``` + +```mermaid +flowchart LR + a[setting.some_name] --> b[run_* + /go] + c[(store -> row)] --> d[Item.Worker] + d --> e[/api/v2/item] +``` + +```mermaid +classDiagram + direction LR + class Shape { + <<trait>> + +area() f32 + } + class Circle { + +radius f32 + } + class Canvas { + +shapes Vec~Shape~ + +draw() + } + Shape <|.. Circle + Canvas o-- "many" Shape : holds +``` + +```mermaid +sequenceDiagram + box Front + actor U as User + participant A as App + end + box Back + participant S as Server + end + U->>A: open list + rect rgb(80, 140, 220) + A->>+S: fetch items + S-->>-A: 20 items + end + A-->>U: show list +``` +"#; + +pub(super) fn markdown_lenient(_: &G, k: &Kit, _: &mut Vec<El>) -> El { + let style = MarkdownStyle::from_kit(k).diagram_max_width(560.0); + col().w(560.0).child(Markdown::new(LENIENT).style(style).build(k)) +} + +/// Every Mermaid v11 flowchart shape, four to a row. +const SHAPES: &str = r#"```mermaid +flowchart LR + a1[rect] ~~~ a2(rounded) ~~~ a3([stadium]) ~~~ a4[[subproc]] + b1[(cyl)] ~~~ b2((circle)) ~~~ b3(((dbl-circ))) ~~~ b4>odd] + c1{diam} ~~~ c2{{hex}} ~~~ c3[/lean-r/] ~~~ c4[\lean-l\] + d1[/trap-b\] ~~~ d2[\trap-t/] ~~~ d3@{ shape: bang, label: "bang" } ~~~ d4@{ shape: cloud, label: "cloud" } + e1@{ shape: notch-rect, label: "card" } ~~~ e2@{ shape: hourglass, label: "collate" } ~~~ e3@{ shape: bolt, label: "com-link" } ~~~ e4@{ shape: delay, label: "delay" } + f1@{ shape: brace, label: "comment" } ~~~ f2@{ shape: brace-r, label: "brace-r" } ~~~ f3@{ shape: braces, label: "braces" } ~~~ f4@{ shape: text, label: "text" } + g1@{ shape: h-cyl, label: "h-cyl" } ~~~ g2@{ shape: lin-cyl, label: "lin-cyl" } ~~~ g3@{ shape: curv-trap, label: "display" } ~~~ g4@{ shape: div-rect, label: "div-rect" } + h1@{ shape: doc, label: "doc" } ~~~ h2@{ shape: lin-doc, label: "lin-doc" } ~~~ h3@{ shape: docs, label: "docs" } ~~~ h4@{ shape: tag-doc, label: "tag-doc" } + i1@{ shape: tri, label: "extract" } ~~~ i2@{ shape: flip-tri, label: "manual file" } ~~~ i3@{ shape: win-pane, label: "win-pane" } ~~~ i4@{ shape: lin-rect, label: "lin-rect" } + j1@{ shape: notch-pent, label: "loop limit" } ~~~ j2@{ shape: sl-rect, label: "manual input" } ~~~ j3@{ shape: st-rect, label: "processes" } ~~~ j4@{ shape: flag, label: "paper tape" } + k1@{ shape: bow-rect, label: "stored data" } ~~~ k2@{ shape: tag-rect, label: "tag-rect" } ~~~ k3@{ shape: sm-circ } ~~~ k4@{ shape: f-circ } + l1@{ shape: fr-circ } ~~~ l2@{ shape: cross-circ } ~~~ l3@{ shape: fork } ~~~ l4@{ shape: icon, form: circle, label: "icon" } +``` +"#; + +pub(super) fn markdown_mermaid_shapes(_: &G, k: &Kit, _: &mut Vec<El>) -> El { + let style = MarkdownStyle::from_kit(k).diagram_max_width(560.0); + col().w(560.0).child(Markdown::new(SHAPES).style(style).build(k)) +} + +/// Sequence participant types, `create` and `destroy`, numbering from 10; and a state diagram with +/// notes, concurrent regions, a fork and join and a choice. +const FLOWS: &str = r#"```mermaid +sequenceDiagram + autonumber 10 + participant UI@{ "type": "boundary" } + participant Ctl@{ "type": "control" } + participant Db@{ "type": "database" } + participant Q@{ "type": "queue" } + UI->>Ctl: submit + Ctl->>Db: save + create participant Job + Ctl->>Job: start + Job->>Q: enqueue + destroy Job + Job-->>Ctl: done + Note over UI,Ctl: saved +``` + +```mermaid +stateDiagram-v2 + [*] --> Ready + state Ready { + [*] --> Idle + Idle --> Typing : key + -- + [*] --> Offline + Offline --> Online : connect + } + Ready --> split + state split <<fork>> + split --> Save + split --> Sync + state merge <<join>> + Save --> merge + Sync --> merge + merge --> ok + state ok <<choice>> + ok --> [*] : fine + ok --> Ready : retry + note right of Save : writes to disk +``` +"#; + +/// An entity-relationship diagram, a gantt chart and a pie chart. +const CHARTS: &str = r#"```mermaid +erDiagram + CUSTOMER ||--o{ ORDER : places + ORDER ||--|{ LINE-ITEM : contains + PRODUCT |o..o{ LINE-ITEM : "listed in" + CUSTOMER { + string id PK + string name + string email UK "login" + } + ORDER { + int id PK + string customer FK + date placed + } + LINE-ITEM { + int qty + decimal price + } +``` + +```mermaid +gantt + title Release 2.0 + dateFormat YYYY-MM-DD + axisFormat %b %d + excludes weekends + section Build + Design :done, des, 2024-03-04, 4d + Core engine :active, core, after des, 8d + Plugins :plug, after des, 6d + section Ship + Beta :crit, beta, after core plug, 4d + Docs :docs, after plug, 5d + Release :milestone, after beta docs, 0d + Code freeze :vert, 2024-03-18, 0d +``` + +```mermaid +pie showData title Where the time went + "Building" : 42 + "Reviewing" : 23 + "Waiting on CI" : 18 + "Meetings" : 9 + "Other" : 4 +``` +"#; + +pub(super) fn markdown_mermaid_charts(_: &G, k: &Kit, _: &mut Vec<El>) -> El { + let style = MarkdownStyle::from_kit(k).diagram_max_width(560.0); + col().w(560.0).child(Markdown::new(CHARTS).style(style).build(k)) +} + +/// A mindmap, a timeline and a user journey. +const MAPS: &str = r#"```mermaid +mindmap + root((Rune)) + Layout + Flex rows + Virtual lists + Text measure + Motion + Springs + Transitions + Platforms + Mac + iOS + Web + Diagrams + Flowcharts + Charts))new(( +``` + +```mermaid +timeline + title Shipping a release + section Plan + Week 1 : Scope : Design review + Week 2 : Prototype + section Build + Week 3 : Core engine : Tests + Week 4 : Plugins + section Ship + Week 5 : Beta : Docs + Week 6 : Launch +``` + +```mermaid +journey + title A first-time user + section Discover + Find the site: 4: User + Read the docs: 3: User + section Try + Install: 2: User, CLI + First build: 5: User, CLI + section Share + Tell a friend: 5: User +``` +"#; + +pub(super) fn markdown_mermaid_maps(_: &G, k: &Kit, _: &mut Vec<El>) -> El { + let style = MarkdownStyle::from_kit(k).diagram_max_width(560.0); + col().w(560.0).child(Markdown::new(MAPS).style(style).build(k)) +} + +/// A git graph, a short timeline and a quadrant chart. +const GIT: &str = r#"```mermaid +timeline + title Rune + 2024 : First window + 2025 : Kit components : Motion + 2026 : Mermaid diagrams +``` + +```mermaid +gitGraph + commit id: "init" + commit id: "layout" tag: "v0.1" + branch feature + checkout feature + commit id: "springs" + commit id: "fix" type: REVERSE + checkout main + commit id: "docs" type: HIGHLIGHT + merge feature id: "merge" tag: "v0.2" + branch hotfix + commit id: "patch" + checkout main + cherry-pick id: "patch" +``` + +```mermaid +quadrantChart + title Reach and engagement + x-axis Low Reach --> High Reach + y-axis Low Engagement --> High Engagement + quadrant-1 Expand + quadrant-2 Promote + quadrant-3 Re-evaluate + quadrant-4 Improve + Campaign A: [0.3, 0.6] + Campaign B: [0.45, 0.23] + Campaign C: [0.57, 0.69] + Campaign D: [0.78, 0.34] + Campaign E: [0.40, 0.34] + Campaign F: [0.35, 0.78] radius: 8, color: #e8590c +``` +"#; + +pub(super) fn markdown_mermaid_git(_: &G, k: &Kit, _: &mut Vec<El>) -> El { + let style = MarkdownStyle::from_kit(k).diagram_max_width(560.0); + col().w(560.0).child(Markdown::new(GIT).style(style).build(k)) +} + +/// An XY chart, a sankey diagram and a block diagram. +const DATA: &str = r#"```mermaid +xychart-beta + title "Frame time by build" + x-axis [debug, release, perf, wasm] + y-axis "Milliseconds" 0 --> 20 + bar "p50" [16.2, 6.1, 5.8, 9.4] + line "p99" [19.1, 8.3, 7.9, 13.2] +``` + +```mermaid +sankey-beta +Input,Layout,40 +Input,Text,25 +Layout,Paint,32 +Layout,Idle,8 +Text,Paint,25 +Paint,GPU,50 +Paint,Cache,7 +``` + +```mermaid +block-beta + columns 3 + app["App"]:3 + view["Views"] state[("State")] motion(["Motion"]) + block:core:2 + columns 2 + layout["Layout"] text["Text"] + end + gpu{{"wgpu"}} + arrow<["frames"]>(down):3 + screen["Screen"]:3 + view --> layout + state -- "reads" --> text +``` +"#; + +pub(super) fn markdown_mermaid_data(_: &G, k: &Kit, _: &mut Vec<El>) -> El { + let style = MarkdownStyle::from_kit(k).diagram_max_width(560.0); + col().w(560.0).child(Markdown::new(DATA).style(style).build(k)) +} + +/// A requirement diagram and a C4 container diagram. +const SYSTEMS: &str = r#"```mermaid +requirementDiagram + requirement fast_start { + id: 1 + text: First frame in 100 ms. + risk: high + verifymethod: test + } + performanceRequirement idle { + id: 1.1 + text: An idle window draws nothing. + risk: medium + verifymethod: analysis + } + element runtime { + type: crate + docref: crates/rune + } + fast_start - contains -> idle + runtime - satisfies -> fast_start + runtime - verifies -> idle +``` + +```mermaid +C4Container + title Notes app + Person(user, "Writer", "Takes notes on a laptop") + System_Boundary(app, "Notes") { + Container(ui, "Window", "Rust, Rune", "Draws the editor") + Container(sync, "Sync", "Rust", "Merges edits") + ContainerDb(db, "Store", "SQLite", "Notes and history") + } + System_Ext(cloud, "Cloud backup", "Keeps a copy") + Rel(user, ui, "Types in") + Rel(ui, sync, "Sends edits") + Rel(sync, db, "Reads and writes", "SQL") + Rel(sync, cloud, "Uploads", "HTTPS") +``` +"#; + +pub(super) fn markdown_mermaid_systems(_: &G, k: &Kit, _: &mut Vec<El>) -> El { + let style = MarkdownStyle::from_kit(k).diagram_max_width(560.0); + col().w(560.0).child(Markdown::new(SYSTEMS).style(style).build(k)) +} + +pub(super) fn markdown_mermaid_flows(_: &G, k: &Kit, _: &mut Vec<El>) -> El { + let style = MarkdownStyle::from_kit(k).diagram_max_width(560.0); + col().w(560.0).child(Markdown::new(FLOWS).style(style).build(k)) +} + +/// A state diagram for hover: pointing at an edge or its label lights both. +const HOVER: &str = r#"```mermaid +stateDiagram-v2 + [*] --> Idle + Idle --> Loading : fetch + Loading --> Ready : 200 OK + Loading --> Failed : error + Failed --> Loading : retry + Ready --> [*] +``` +"#; + +pub(super) fn markdown_mermaid_hover(_: &G, k: &Kit, _: &mut Vec<El>) -> El { + let style = MarkdownStyle::from_kit(k).diagram_max_width(560.0); + col().w(560.0).child(Markdown::new(HOVER).style(style).build(k)) +} + +/// A wide build plan: four subgraphs whose ranks interleave, fourteen classDef-tinted nodes, and +/// edges that fan out of one node into another subgraph. +fn plan_markdown() -> String { + format!("```mermaid\n{}```\n", include_str!("../../../../crates/rune-mermaid/fixtures/plan.mmd")) +} + +/// The plan in a reply-wide column that fits any diagram whole, as a chat app shows it. +pub(super) fn markdown_mermaid_plan(_: &G, k: &Kit, _: &mut Vec<El>) -> El { + let style = MarkdownStyle::from_kit(k).diagram_max_width(680.0).diagram_min_scale(0.0); + col().w(680.0).child(Markdown::new(plan_markdown()).style(style).build(k)) +} + +/// [`markdown_mermaid_plan`] magnified 3×, as a lightbox shows it to read. +pub(super) fn markdown_mermaid_plan_zoomed(g: &G, k: &Kit, o: &mut Vec<El>) -> El { + col().w(680.0).origin(0.0, 0.0).scale(3.0).child(markdown_mermaid_plan(g, k, o)) +} + +/// A table without an outline, with a dimmed header and figures that line up, and a diff whose +/// line text is tinted too. +const TABLE_STYLES: &str = "| Field | Compared |\n|---|---|\n| title | yes |\n| updatedAt | yes |\n| draft cursor | no |\n\n| Build | Files | Time | Size |\n|:--|--:|--:|--:|\n| debug | 1,204 | 41.8 s | 118.4 MB |\n| release | 1,204 | 71.0 s | 31.1 MB |\n| perf | 1,211 | 69.6 s | 33.7 MB |\n\n```diff\n@@ -3,3 +3,3 @@ fields:\n title: compared\n- draft: compared\n+ draft: ignored\n```\n"; + +pub(super) fn markdown_table_styles(_: &G, k: &Kit, _: &mut Vec<El>) -> El { + let style = MarkdownStyle::from_kit(k) + .table(k.c.border_muted, rune::Color::TRANSPARENT) + .table_outline(None) + .table_header_text(k.c.text_muted) + .diff_text_tint(0.5); + col().w(560.0).child(Markdown::new(TABLE_STYLES).style(style).build(k)) +} + +/// Fenced code in each language family the highlighter knows. +const CODE: &str = r#"```tsx +// Loads a user, then renders their card. +export async function load(id: string): Promise<User | null> { + const res = await fetch(`/api/users/${id}`, { method: "GET" }); + return res.ok ? res.json() : null; +} +const Card = ({ user }: Props) => <div className="card">{user.name}</div>; +``` + +```rust +#[derive(Debug, Clone)] +pub struct Retry<'a> { name: &'a str, attempts: u32 } + +fn backoff(n: u32) -> Duration { + Duration::from_millis(200 * 2u64.pow(n)) // capped by the caller +} +``` + +```python +@dataclass +class Job: + name: str + tries: int = 3 # per run + + def label(self) -> str: + return f"{self.name} ×{self.tries}" if self.tries > 1 else self.name +``` + +```go +func (s *Server) Serve(ctx context.Context) error { + for job := range s.queue { + if err := job.Run(ctx); err != nil { + return fmt.Errorf("job %q: %w", job.Name, err) + } + } + return nil +} +``` + +```sh +# Build, then ship the release. +FEATURES=markdown cargo build --release && echo "done in $SECONDS s" +if [ -n "$TAG" ]; then gh release create "$TAG" ./target/*.tar.gz; fi +``` + +```sql +SELECT u.id, count(*) AS posts +FROM users u JOIN posts p ON p.user_id = u.id +WHERE u.created_at > '2026-01-01' AND p.draft = false +GROUP BY u.id ORDER BY posts DESC LIMIT 10; +``` + +```yaml +name: ci +on: [push, pull_request] +jobs: + test: + runs-on: macos-15 # Apple silicon + timeout-minutes: 30 + steps: + - run: cargo test --workspace +``` +"#; + +pub(super) fn markdown_code(_: &G, k: &Kit, _: &mut Vec<El>) -> El { + col().w(620.0).child(Markdown::new(CODE).build(k)) +} + +pub(super) fn markdown_walkthrough(_: &G, k: &Kit, _: &mut Vec<El>) -> El { + col().w(680.0).child(Markdown::new(WALKTHROUGH).on_link(|_: &mut G, _| {}).build(k)) +} + +pub(super) fn markdown_streaming(s: &G, k: &Kit, _: &mut Vec<El>) -> El { + let n: usize = s.picked("md-stream", "60").parse().unwrap_or(60); + let end = MARKDOWN.char_indices().map(|(i, _)| i).nth(n).unwrap_or(MARKDOWN.len()); + col().w(560.0).gap(12.0) + .child( + Button::new("Stream more") + .on_press(move |s: &mut G| { + s.pick.insert("md-stream".into(), (n + 40).to_string()); + }) + .build(k) + .key("stream-more"), + ) + .child(Markdown::new(&MARKDOWN[..end]).reveal(0.18).streaming(end < MARKDOWN.len()).build(k)) +} + +/// A reply streaming in a chunk a press, each ending inside markup: an open emphasis, code or +/// strike span draws styled, never its markers, and the table's header line waits to be a table +/// rather than laying out as a paragraph first. Each press also starts a block, so it draws. +const TAIL_STREAM: [&str; 5] = [ + "Open **Settings ›", + " Appearance** and pick *Dark*.\n\n- run `theme", + " dark`\n- then ~~restart", + "~~ nothing\n\nChanged:\n\n| File", + " | Change |\n|---|---|\n| theme.rs | dark |\n", +]; + +pub(super) fn markdown_stream_tail(s: &G, k: &Kit, _: &mut Vec<El>) -> El { + let n: usize = s.picked("md-tail-stream", "0").parse().unwrap_or(0); + let src = TAIL_STREAM[..n.min(TAIL_STREAM.len())].concat(); + col().w(560.0).gap(12.0) + .child( + Button::new("Stream more") + .on_press(move |s: &mut G| { + s.pick.insert("md-tail-stream".into(), (n + 1).to_string()); + }) + .build(k) + .key("stream-more"), + ) + .child(Markdown::new(src).streaming(n < TAIL_STREAM.len()).build(k)) +} + +/// A reply streaming in with a flowchart and a sequence diagram: each "Stream more" adds lines up +/// to the next one that draws something (a fence, its header or a blank line draws nothing). +const DIAGRAM_STREAM: &str = r#"Here's the flow: + +```mermaid +flowchart LR + A[Request] --> B{Cached?} + B -->|yes| C[Serve] + B -->|no| D[Fetch] + D --> E[(Store)] + E --> C +``` + +And who talks to whom: + +```mermaid +sequenceDiagram + participant U as User + participant A as App + participant S as Server + U->>A: Open + A->>S: GET /items + S-->>A: 200 OK + A-->>U: Show list +``` +"#; + +pub(super) fn markdown_mermaid_streaming(s: &G, k: &Kit, _: &mut Vec<El>) -> El { + let end: usize = s.picked("md-diagram-stream", "0").parse().unwrap_or(0).min(DIAGRAM_STREAM.len()); + let style = MarkdownStyle::from_kit(k).diagram_max_width(560.0); + col().w(560.0).gap(12.0) + .child( + Button::new("Stream more") + .on_press(move |s: &mut G| { + s.pick.insert("md-diagram-stream".into(), next_drawn_line(DIAGRAM_STREAM, end).to_string()); + }) + .build(k) + .key("stream-more"), + ) + .child(Markdown::new(&DIAGRAM_STREAM[..end]).style(style).streaming(end < DIAGRAM_STREAM.len()).build(k)) +} + +/// The end of the first line after `from` that draws something, taking any quiet lines before it +/// (and the quiet lines that end the reply, so the last press also closes its fence). +fn next_drawn_line(src: &str, from: usize) -> usize { + let quiet = |line: &str| { + let t = line.trim(); + t.is_empty() || t.starts_with("```") || t == "flowchart LR" || t == "sequenceDiagram" + }; + let mut at = from; + for line in src[from..].split_inclusive('\n') { + at += line.len(); + if !quiet(line) { + break; + } + } + if src[at..].split_inclusive('\n').all(quiet) { src.len() } else { at } +} diff --git a/app/vendor/rune/examples/kit-gallery/src/stories/overlays.rs b/app/vendor/rune/examples/kit-gallery/src/stories/overlays.rs new file mode 100644 index 0000000..a46826e --- /dev/null +++ b/app/vendor/rune/examples/kit-gallery/src/stories/overlays.rs @@ -0,0 +1,244 @@ +//! Popover, Menu, Tooltip, HoverCard and Toast. + +use super::*; + +fn trigger_text(k: &Kit, s: &str) -> El { + body_text(k, s) +} + +pub(super) fn popover_basic(s: &G, k: &Kit, layer: &mut Vec<El>) -> El { + row().child( + Popover::new("popover") + .trigger(trigger_text(k, "Open popover")) + .title("Popover") + .description("Optional description") + .child(overlay_text(k, "Popover content")) + .open(is_open(s, "popover")) + .on_close(close) + .build(k, layer) + .on_press(toggle("popover")), + ) +} + +pub(super) fn popover_controlled(s: &G, k: &Kit, layer: &mut Vec<El>) -> El { + row().child( + Popover::new("popover") + .trigger(trigger_text(k, "Toggle popover")) + .title("Controlled") + .description("Open state is controlled") + .child(overlay_text(k, "Controlled content")) + .open(is_open(s, "popover")) + .on_close(close) + .build(k, layer) + .on_press(toggle("popover")), + ) +} + +fn menu_button(k: &Kit, label: &str, key: &'static str, open: bool) -> El { + Button::new(label).expanded(open).on_press(toggle(key)).build(k) +} + +pub(super) fn menu_basic(s: &G, k: &Kit, layer: &mut Vec<El>) -> El { + let open = is_open(s, "menu"); + row().child( + Menu::new("menu") + .trigger(menu_button(k, "Open menu", "menu", open)) + .item(MenuItem::new("New file").on_select(close)) + .item(MenuItem::new("Open file").on_select(close)) + .item(MenuItem::new("Save").on_select(close)) + .separator() + .item(MenuItem::new("Print").disabled(true)) + .open(open) + .on_close(close) + .build(k, layer), + ) +} + +pub(super) fn menu_appearances(s: &G, k: &Kit, layer: &mut Vec<El>) -> El { + let open = is_open(s, "both"); + row() + .gap(16.0) + .child( + Menu::new("standard") + .standard() + .trigger(menu_button(k, "Standard", "both", open)) + .item(MenuItem::new("New file")) + .item(MenuItem::new("Open file")) + .open(open) + .build(k, layer), + ) + .child( + Menu::new("compact") + .trigger(menu_button(k, "Compact", "both", open)) + .item(MenuItem::new("New file")) + .item(MenuItem::new("Open file")) + .open(open) + .build(k, layer), + ) +} + +pub(super) fn menu_rich(s: &G, k: &Kit, layer: &mut Vec<El>) -> El { + let open = is_open(s, "menu"); + let avatar = row() + .size(16.0, 16.0) + .center() + .radius(4.0) + .fill(k.c.layer_03) + .child(text("A").font(k.ty.small_medium).color(k.c.text_base)); + row().child( + Menu::new("menu") + .trigger(menu_button(k, "Open rich menu", "menu", open)) + .min_width(240.0) + .item(MenuItem::new("Text").lead(avatar).icon(&ic::PLUS).shortcut("⇧ D").badge("Label")) + .item(MenuItem::new("New window").icon(&ic::PLUS).shortcut("⌘ N")) + .item(MenuItem::new("Save as…").icon(&ic::PLUS).shortcut("⌘ S").badge("Beta")) + .separator() + .item(MenuItem::new("Print").icon(&ic::PLUS).shortcut("⌘ P").disabled(true)) + .open(open) + .on_close(close) + .build(k, layer), + ) +} + +pub(super) fn menu_checkbox(s: &G, k: &Kit, layer: &mut Vec<El>) -> El { + let open = is_open(s, "menu"); + row().child( + Menu::new("menu") + .trigger(menu_button(k, "View", "menu", open)) + .min_width(200.0) + .item(MenuItem::new("Word wrap").shortcut("⌥ Z").checked(!s.is("wrap")).on_select(flip("wrap"))) + .item(MenuItem::new("Minimap").checked(s.is("minimap")).on_select(flip("minimap"))) + .item(MenuItem::new("Ruler").checked(false).disabled(true)) + .open(open) + .on_close(close) + .build(k, layer), + ) +} + +pub(super) fn menu_radio(s: &G, k: &Kit, layer: &mut Vec<El>) -> El { + let open = is_open(s, "menu"); + let theme = s.picked("theme", "system").to_owned(); + let pick = |v: &'static str| { + move |s: &mut G| { + s.pick.insert("theme".into(), v.into()); + } + }; + row().child( + Menu::new("menu") + .trigger(menu_button(k, "Theme", "menu", open)) + .min_width(200.0) + .group_label("Appearance") + .item(MenuItem::new("Light").checked(theme == "light").on_select(pick("light"))) + .item(MenuItem::new("Dark").checked(theme == "dark").on_select(pick("dark"))) + .item(MenuItem::new("System").badge("Auto").checked(theme == "system").on_select(pick("system"))) + .open(open) + .on_close(close) + .build(k, layer), + ) +} + +pub(super) fn menu_submenu(s: &G, k: &Kit, layer: &mut Vec<El>) -> El { + let open = is_open(s, "menu"); + let recent = vec![ + MenuEntry::item(MenuItem::new("project-alpha.tsx")), + MenuEntry::item(MenuItem::new("project-beta.tsx")), + MenuEntry::item(MenuItem::new("project-gamma.tsx")), + MenuEntry::Separator, + MenuEntry::item(MenuItem::new("Clear recent")), + ]; + row().child( + Menu::new("menu") + .trigger(menu_button(k, "File", "menu", open)) + .min_width(200.0) + .item(MenuItem::new("New file").shortcut("⌘ N")) + .item(MenuItem::new("Open file").shortcut("⌘ O")) + .item(MenuItem::new("Open recent").submenu(recent, s.is("recent")).on_select(flip("recent"))) + .separator() + .item(MenuItem::new("Save").shortcut("⌘ S")) + .item(MenuItem::new("Save as…").shortcut("⇧⌘ S")) + .open(open) + .on_close(close) + .build(k, layer), + ) +} + +/// The tooltip stories' frame: 80 points of padding, centred. +fn tip_frame(e: El) -> El { + row().w_full().padding(80.0).center().child(e) +} + +pub(super) fn tooltip_simple(s: &G, k: &Kit, layer: &mut Vec<El>) -> El { + let t = Tooltip::new("tip").trigger(body_text(k, "Hover me")).open(is_open(s, "tip")); + tip_frame(t.text(k, "Tooltip Text").build(k, layer)) +} + +pub(super) fn tooltip_keybind(s: &G, k: &Kit, layer: &mut Vec<El>) -> El { + let t = Tooltip::new("tip").trigger(body_text(k, "Hover me")).open(is_open(s, "tip")); + tip_frame(t.text(k, "Tooltip Text").child(Keybind::new(&["⌘", "⌘"]).build(k)).build(k, layer)) +} + +pub(super) fn tooltip_path(s: &G, k: &Kit, layer: &mut Vec<El>) -> El { + let t = Tooltip::new("tip").trigger(body_text(k, "Hover me")).open(is_open(s, "tip")); + let font = t.font(k); + let parts = row() + .gap(3.0) + .child(text("Components").font(font).color(k.c.text_base)) + .child(text("/").font(font).color(k.c.text_faint)) + .child(text("Tooltip").font(font).color(k.c.text_base)); + tip_frame(t.child(parts).build(k, layer)) +} + +pub(super) fn tooltip_title_description(s: &G, k: &Kit, layer: &mut Vec<El>) -> El { + let t = Tooltip::new("tip").trigger(body_text(k, "Hover me")).open(is_open(s, "tip")); + let font = t.font(k); + tip_frame( + t.child(text("Title").font(font).color(k.c.text_base)) + .child(text("·").font(font).color(k.c.text_faint)) + .child(text("Description").font(font).color(k.c.text_faint)) + .build(k, layer), + ) +} + +pub(super) fn hover_card_basic(s: &G, k: &Kit, layer: &mut Vec<El>) -> El { + row().child( + HoverCard::new("card") + .trigger(body_text(k, "Hover me")) + .child( + col() + .gap(6.0) + .child(text("Preview").font(TextStyle::new(13.0, 600.0).lh(24.0)).color(k.c.std_text)) + .child( + text("Short supporting text.").font(TextStyle::new(12.0, 440.0).lh(24.0)).color(k.c.text_weak), + ), + ) + .open(is_open(s, "card")) + .build(k, layer), + ) +} + +static DOWNLOAD: rune::Icon = rune::Icon { + name: "story-download", + view: 16.0, + body: r#"<path d="M13.5554 10.4453V13.5564H11.7777H4.22211C3.23989 13.5564 2.44434 13.5564 2.44434 13.5564V10.4453" stroke="currentColor"/><path d="M4.88867 6L7.99978 9.11111L11.1109 6" stroke="currentColor"/><path d="M8 9.11198V2.44531" stroke="currentColor"/>"#, +}; + +pub(super) fn toast_all(s: &G, k: &Kit, layer: &mut Vec<El>) -> El { + let buttons = col() + .gap(12.0) + .items_start() + .child(Button::new("Show download toast").on_press(|s: &mut G| s.open = Some("toast".into())).build(k)) + .child(Button::new("Show saved toast").build(k)) + .child(Button::new("Show saving toast").build(k)) + .child(Button::new("Show unsaved changes toast").build(k)); + if is_open(s, "toast") { + let t = Toast::new("download", "Download started...") + .description("23% · 2 min left") + .icon(k, &DOWNLOAD) + .closable() + .action(k, "Run in background", true, |s: &mut G, _: &mut Tx| s.open = None) + .action(k, "Cancel", false, |s: &mut G, _: &mut Tx| s.open = None) + .build(k); + layer.push(ToastRegion::new().toast(t).build(k)); + } + buttons +} diff --git a/app/vendor/rune/examples/knobs/Cargo.toml b/app/vendor/rune/examples/knobs/Cargo.toml new file mode 100644 index 0000000..946cb9f --- /dev/null +++ b/app/vendor/rune/examples/knobs/Cargo.toml @@ -0,0 +1,17 @@ +[package] +name = "knobs" +version = "0.0.1" +edition.workspace = true +license.workspace = true + +[dependencies] +rune = { workspace = true, default-features = true, features = ["keys-overlay"] } +rune-knobs = { workspace = true } + +[features] +default = ["panel"] +# A real app turns this on only in its dev builds; shipped builds read each knob's default. +panel = ["rune-knobs/panel"] + +[lints] +workspace = true diff --git a/app/vendor/rune/examples/knobs/src/main.rs b/app/vendor/rune/examples/knobs/src/main.rs new file mode 100644 index 0000000..df04226 --- /dev/null +++ b/app/vendor/rune/examples/knobs/src/main.rs @@ -0,0 +1,132 @@ +//! A card tuned live with `rune-knobs`: ⌘⇧K slides the panel in beside the page, and its sliders +//! and choices change the card as you drag. `cargo run -p knobs`; `-- --snap knobs.png --scene +//! open` renders it headless with the panel open, and `-- --playground "Knobs"` opens the +//! playground, whose side column hosts the same knobs as rows. + +#![forbid(unsafe_code)] + +use rune::tok::{self, type_}; +use rune::{App, AppSpec, Cx, El, KeyEvent, Playground, Story, Tx, col, text}; +use rune_knobs::{Group, Knob, Knobs, Preset, Style}; + +const RADIUS: Knob = Knob::new("Card radius", 0.0, 32.0, 14.0).about("How round the card's corners are"); +const PAD: Knob = Knob::new("Card padding", 8.0, 48.0, 24.0).step(1.0); +const TINT: Knob = Knob::choice("Card tint", &["Plain", "Accent", "Raised"], 0); +const SHADOW: Knob = Knob::choice("Card shadow", &["Off", "On"], 0); +const GROUPS: &[Group] = &[Group::new("Card", "card", &[RADIUS, PAD, TINT, SHADOW]).presets(&[Preset { name: "Round", values: &[("Card radius", 28.0)] }])]; + +#[derive(Default)] +struct State { + knobs: Knobs, +} + +fn page(s: &State, cx: &mut Cx<State>) -> El { + let t = tok::theme(cx.system_dark()); + let ink = if cx.system_dark() { t.bg } else { t.text }; + let k = &s.knobs; + let fill = match k.get(&TINT) as usize { + 1 => tok::accent(0, true), + 2 => t.control_off, + _ => t.knob, + }; + let card = col() + .key("card") + .shadow(if k.get(&SHADOW) > 0.5 { 10.0 } else { 0.0 }, 24.0, t.bg.alpha(0.35)) + .w(240.0) + .padding(k.get(&PAD)) + .gap(6.0) + .radius(k.get(&RADIUS)) + .fill(fill) + .child(text("Tune me").font(type_::TITLE).color(ink)) + .child(text("⌘⇧K opens the knobs").color(ink)); + col().key("page").grow(1.0).h_full().center().fill(t.bg).child(card) +} + +fn view(s: &State, cx: &mut Cx<State>) -> El { + let page = page(s, cx); + rune_knobs::side(page, &s.knobs, GROUPS, style(cx), |s: &mut State| &mut s.knobs) +} + +fn style(cx: &Cx<State>) -> Style { + if cx.system_dark() { Style::dark() } else { Style::light() } +} + +/// The playground's side column: the same knobs as rows, filling its width. With the keyboard +/// on them (→ from the list), ↑↓ pick a knob and ←→ step it. +fn story_side(s: &State, active: bool, cx: &mut Cx<State>) -> El { + rune_knobs::inline(&s.knobs, GROUPS, style(cx), |s: &mut State| &mut s.knobs, active) +} + +fn playground() -> Playground<State> { + Playground::new().story(Story::new("Card/Knobs", State::default, page).side_keys(story_side, rune_knobs::side_key(GROUPS, |s: &mut State| &mut s.knobs))) +} + +fn on_key(s: &mut State, ev: &KeyEvent, tx: &mut Tx) -> bool { + let taken = rune_knobs::key(&mut s.knobs, ev); + if taken { + tx.motion(s.knobs.slide()); + } + taken +} + +fn main() { + let spec = AppSpec::<State> { + scenes: &[("open", |s| s.knobs.show()), ("filter", |s| { s.knobs.show(); s.knobs.filter("pad"); })], + on_key: Some(on_key), + ..AppSpec::new("Knobs", (820.0, 520.0), State::default, view) + }; + App::new(spec).playground(playground()).run(); +} + +#[cfg(test)] +mod tests { + use super::*; + use rune::{Env, Key, Mods, Runtime}; + use rune_knobs::Knob; + + fn press(rt: &mut Runtime<State>, key: Key, shift: bool) { + rt.key(KeyEvent { key, mods: Mods { shift, ..Mods::default() } }); + rt.frame(1.0 / 60.0); + } + + fn knob(rt: &Runtime<State>, d: &Knob) -> f32 { + rt.playground_state::<State>().map(|s| s.knobs.get(d)).unwrap() + } + + #[test] + fn in_the_playground_arrows_pick_and_step_the_side_columns_knobs() { + let spec = AppSpec::new("Knobs", (820.0, 520.0), State::default, view); + let mut rt = App::new(spec).playground(playground()).headless_runtime((820.0, 520.0), Env::new(true, 1.0)); + rt.open_playground("card-knobs", None); + press(&mut rt, Key::Right, false); + press(&mut rt, Key::Right, false); + assert!((knob(&rt, &RADIUS) - 14.32).abs() < 1e-4, "→ steps the first knob, the radius"); + press(&mut rt, Key::Down, false); + press(&mut rt, Key::Right, true); + assert_eq!(knob(&rt, &PAD), 34.0, "↓ picks the padding, and ⇧→ steps it ten"); + press(&mut rt, Key::Left, false); + assert_eq!(knob(&rt, &PAD), 33.0, "← steps back rather than leaving"); + assert!(rt.elements().iter().any(|e| e.key.as_deref() == Some("playground-slot-0") && e.focused), "the keyboard is on the knobs"); + press(&mut rt, Key::Escape, false); + press(&mut rt, Key::Down, false); + assert_eq!(knob(&rt, &PAD), 33.0, "after Esc, ↓ moves in the list again"); + assert_eq!(rt.state.knobs.get(&RADIUS), RADIUS.default, "the real state is untouched"); + } + + #[test] + fn cmd_shift_k_opens_the_panel_and_a_knob_changes_the_card() { + let mut rt = Runtime::new(State::default(), view, (820.0, 520.0), Env::new(true, 1.0)); + rt.on_key = Some(on_key); + rt.frame(0.0); + let ev = KeyEvent { key: Key::Command('k'), mods: Mods { cmd: true, shift: true, ..Mods::default() } }; + rt.key(ev); + for _ in 0..40 { + rt.frame(1.0 / 60.0); + } + assert!(rt.state.knobs.open && rt.find("knobs-top").is_some()); + rt.state.knobs.set(&RADIUS, 30.0); + rt.invalidate(); + rt.frame(1.0 / 60.0); + assert_eq!(rt.state.knobs.get(&RADIUS), 30.0); + } +} diff --git a/app/vendor/rune/examples/lab/Cargo.toml b/app/vendor/rune/examples/lab/Cargo.toml new file mode 100644 index 0000000..091ba5a --- /dev/null +++ b/app/vendor/rune/examples/lab/Cargo.toml @@ -0,0 +1,28 @@ +[package] +name = "lab" +version = "0.0.1" +edition.workspace = true +license.workspace = true + +[dependencies] +rune = { workspace = true, default-features = true, features = ["keys-overlay"] } +rune-motion = { workspace = true } +rune-fx = { workspace = true } +rune-light = { workspace = true } +wgpu = { workspace = true, features = ["std", "parking_lot", "wgsl"] } +bytemuck = { workspace = true } + +[target.'cfg(target_vendor = "apple")'.dependencies] +wgpu = { workspace = true, features = ["metal"] } + +[target.'cfg(target_os = "windows")'.dependencies] +wgpu = { workspace = true, features = ["dx12"] } + +[target.'cfg(all(not(target_vendor = "apple"), not(target_arch = "wasm32"), not(target_os = "windows")))'.dependencies] +wgpu = { workspace = true, features = ["vulkan"] } + +[target.'cfg(target_arch = "wasm32")'.dependencies] +wgpu = { workspace = true, features = ["webgpu"] } + +[lints] +workspace = true diff --git a/app/vendor/rune/examples/lab/assets/theme.json b/app/vendor/rune/examples/lab/assets/theme.json new file mode 100644 index 0000000..72c2ced --- /dev/null +++ b/app/vendor/rune/examples/lab/assets/theme.json @@ -0,0 +1,330 @@ +{ + "name": "OpenCode", + "blend": { + "mode": "srgb", + "over": "background-bg-base" + }, + "palette": { + "grey-50": "#ffffffff", + "grey-100": "#fafafaff", + "grey-200": "#f2f2f2ff", + "grey-300": "#eeeeeeff", + "grey-400": "#dbdbdbff", + "grey-500": "#aeaeaeff", + "grey-600": "#808080ff", + "grey-700": "#5c5c5cff", + "grey-800": "#3a3a3aff", + "grey-900": "#2e2e2eff", + "grey-1000": "#242424ff", + "grey-1100": "#161616ff", + "grey-1200": "#080808ff", + "alpha-dark-100": "#000000ff", + "alpha-dark-90": "#000000e5", + "alpha-dark-80": "#000000cc", + "alpha-dark-70": "#000000b2", + "alpha-dark-60": "#00000099", + "alpha-dark-50": "#00000080", + "alpha-dark-40": "#00000066", + "alpha-dark-30": "#0000004d", + "alpha-dark-24": "#0000003d", + "alpha-dark-20": "#00000033", + "alpha-dark-16": "#00000029", + "alpha-dark-14": "#00000024", + "alpha-dark-12": "#0000001f", + "alpha-dark-10": "#0000001a", + "alpha-dark-8": "#00000014", + "alpha-dark-6": "#0000000f", + "alpha-dark-4": "#0000000a", + "alpha-dark-2": "#00000005", + "alpha-dark-0": "#00000000", + "alpha-light-100": "#ffffffff", + "alpha-light-90": "#ffffffe5", + "alpha-light-80": "#ffffffcc", + "alpha-light-70": "#ffffffb2", + "alpha-light-60": "#ffffff99", + "alpha-light-50": "#ffffff80", + "alpha-light-40": "#ffffff66", + "alpha-light-30": "#ffffff4d", + "alpha-light-24": "#ffffff3d", + "alpha-light-20": "#ffffff33", + "alpha-light-16": "#ffffff29", + "alpha-light-14": "#ffffff24", + "alpha-light-12": "#ffffff1f", + "alpha-light-10": "#ffffff1a", + "alpha-light-8": "#ffffff14", + "alpha-light-6": "#ffffff0f", + "alpha-light-4": "#ffffff0a", + "alpha-light-2": "#ffffff05", + "alpha-light-0": "#ffffff00", + "red-100": "#fcecebff", + "red-200": "#f6d5d3ff", + "red-300": "#f2bbb7ff", + "red-400": "#f29b96ff", + "red-500": "#f17471ff", + "red-600": "#f1484fff", + "red-700": "#d92e3cff", + "red-800": "#b82d35ff", + "red-900": "#97252bff", + "red-1000": "#7a1f23ff", + "red-1100": "#5f1a1cff", + "red-1200": "#461516ff", + "orange-100": "#fdf2edff", + "orange-200": "#ffe7dcff", + "orange-300": "#ffd8c6ff", + "orange-400": "#ffc1a4ff", + "orange-500": "#ffa478ff", + "orange-600": "#ff8648ff", + "orange-700": "#ee7330ff", + "orange-800": "#d16427ff", + "orange-900": "#b35624ff", + "orange-1000": "#954c27ff", + "orange-1100": "#723d22ff", + "orange-1200": "#5a2c14ff", + "yellow-100": "#fefaecff", + "yellow-200": "#fcefd0ff", + "yellow-300": "#f7e5b5ff", + "yellow-400": "#f3da9bff", + "yellow-500": "#f2cf76ff", + "yellow-600": "#f6c251ff", + "yellow-700": "#e7af36ff", + "yellow-800": "#cb9f34ff", + "yellow-900": "#ac8833ff", + "yellow-1000": "#8e7231ff", + "yellow-1100": "#68552bff", + "yellow-1200": "#4b4025ff", + "green-100": "#e7f9eaff", + "green-200": "#d0f0d5ff", + "green-300": "#b8e9c1ff", + "green-400": "#96e3a6ff", + "green-500": "#6bd586ff", + "green-600": "#49c970ff", + "green-700": "#2eaf5aff", + "green-800": "#198b43ff", + "green-900": "#1d783cff", + "green-1000": "#196130ff", + "green-1100": "#164c26ff", + "green-1200": "#14361dff", + "cyan-100": "#e2f7fbff", + "cyan-200": "#c4edf4ff", + "cyan-300": "#a3e4efff", + "cyan-400": "#65d9ebff", + "cyan-500": "#00c5dfff", + "cyan-600": "#00abcfff", + "cyan-700": "#0096b8ff", + "cyan-800": "#007d9bff", + "cyan-900": "#006c85ff", + "cyan-1000": "#005a6eff", + "cyan-1100": "#004756ff", + "cyan-1200": "#00353fff", + "blue-100": "#f5f8ffff", + "blue-200": "#ecf1feff", + "blue-300": "#c3d4fdff", + "blue-400": "#a2bcffff", + "blue-500": "#7698fdff", + "blue-600": "#3b5cf6ff", + "blue-700": "#0b34f4ff", + "blue-800": "#3250dfff", + "blue-900": "#2c47c8ff", + "blue-1000": "#263fa9ff", + "blue-1100": "#22388fff", + "blue-1200": "#021945ff", + "purple-100": "#ebecfeff", + "purple-200": "#d5d5fcff", + "purple-300": "#b9b8f5ff", + "purple-400": "#9e99f7ff", + "purple-500": "#8271f8ff", + "purple-600": "#7152f4ff", + "purple-700": "#623be2ff", + "purple-800": "#5230c2ff", + "purple-900": "#442aa1ff", + "purple-1000": "#361f83ff", + "purple-1100": "#2b1b6aff", + "purple-1200": "#221358ff", + "pink-100": "#fdecf3ff", + "pink-200": "#f7d5e4ff", + "pink-300": "#fabcd8ff", + "pink-400": "#f799c6ff", + "pink-500": "#f26cb2ff", + "pink-600": "#f64aabff", + "pink-700": "#e4429eff", + "pink-800": "#c83d8bff", + "pink-900": "#aa3576ff", + "pink-1000": "#8c2d61ff", + "pink-1100": "#6f284fff", + "pink-1200": "#5c1d3fff" + }, + "light": { + "agent-build-solid": "blue-800", + "agent-explore-solid": "yellow-900", + "agent-plan-solid": "pink-800", + "agent-review-solid": "green-800", + "agent-writer-solid": "purple-700", + "avatar-bg-blue": "#3250dfff", + "avatar-bg-cyan": "#0096b8ff", + "avatar-bg-gray": "#5c5c5cff", + "avatar-bg-green": "#2eaf5aff", + "avatar-bg-orange": "#ee7330ff", + "avatar-bg-pink": "#e4429eff", + "avatar-bg-purple": "#623be2ff", + "avatar-bg-red": "#d92e3cff", + "avatar-bg-yellow": "#e7af36ff", + "avatar-border-blue": "#2c47c8ff", + "avatar-border-cyan": "#007d9bff", + "avatar-border-gray": "#3a3a3aff", + "avatar-border-green": "#198b43ff", + "avatar-border-orange": "#d16427ff", + "avatar-border-pink": "#c83d8bff", + "avatar-border-purple": "#5230c2ff", + "avatar-border-red": "#b82d35ff", + "avatar-border-yellow": "#cb9f34ff", + "avatar-fg": "#ffffffff", + "background-bg-accent": "blue-600", + "background-bg-base": "grey-50", + "background-bg-button-neutral": "grey-50", + "background-bg-code-path": "cyan-100", + "background-bg-contrast": "grey-1000", + "background-bg-deep": "grey-100", + "background-bg-icon-button-contrast": "grey-1000", + "background-bg-inverse": "grey-1100", + "background-bg-layer-01": "grey-100", + "background-bg-layer-02": "grey-200", + "background-bg-layer-03": "grey-300", + "background-bg-layer-04": "grey-400", + "border-border-base": "alpha-dark-10", + "border-border-focus": "blue-500", + "border-border-inverse": "grey-1000", + "border-border-muted": "alpha-dark-8", + "border-border-strong": "alpha-dark-20", + "icon-icon-accent": "blue-600", + "icon-icon-accent-hover": "blue-700", + "icon-icon-base": "grey-800", + "icon-icon-contrast": "grey-100", + "icon-icon-faint": "grey-500", + "icon-icon-inverse": "grey-50", + "icon-icon-muted": "grey-600", + "illustration-illustration-layer-01": "grey-300", + "illustration-illustration-layer-02": "grey-400", + "illustration-illustration-layer-03": "grey-500", + "overlay-gradient-depth-overlay-depth-bot": "alpha-light-0", + "overlay-gradient-depth-overlay-depth-top": "alpha-light-100", + "overlay-simple-overlay-contrast-hover": "alpha-light-12", + "overlay-simple-overlay-contrast-pressed": "alpha-light-24", + "overlay-simple-overlay-hover": "alpha-dark-4", + "overlay-simple-overlay-pressed": "alpha-dark-8", + "overlay-simple-overlay-scrim": "alpha-dark-40", + "overlay-simple-tab-active-scrim": "#fafafa00", + "overlay-simple-tab-hover-scrim": "#eeeeee00", + "overlay-simple-tab-scrim": "#fafafa00", + "state-bg-danger": "red-100", + "state-bg-info": "blue-200", + "state-bg-success": "green-100", + "state-bg-warning": "yellow-100", + "state-border-danger": "red-300", + "state-border-info": "blue-300", + "state-border-success": "green-300", + "state-border-warning": "yellow-300", + "state-fg-danger": "red-800", + "state-fg-info": "blue-800", + "state-fg-success": "green-800", + "state-fg-warning": "yellow-800", + "text-text-accent": "blue-600", + "text-text-accent-hover": "blue-700", + "text-text-base": "grey-1100", + "text-text-code-accent": "blue-900", + "text-text-code-path": "blue-900", + "text-text-contrast": "grey-50", + "text-text-faint": "grey-600", + "text-text-inverse": "grey-50", + "text-text-muted": "grey-700" + }, + "dark": { + "agent-build-solid": "blue-300", + "agent-explore-solid": "yellow-300", + "agent-plan-solid": "pink-400", + "agent-review-solid": "green-300", + "agent-writer-solid": "purple-400", + "avatar-bg-blue": "#263fa9ff", + "avatar-bg-cyan": "#005a6eff", + "avatar-bg-gray": "#5c5c5cff", + "avatar-bg-green": "#196130ff", + "avatar-bg-orange": "#723d22ff", + "avatar-bg-pink": "#8c2d61ff", + "avatar-bg-purple": "#361f83ff", + "avatar-bg-red": "#7a1f23ff", + "avatar-bg-yellow": "#68552bff", + "avatar-border-blue": "#7698fdff", + "avatar-border-cyan": "#0096b8ff", + "avatar-border-gray": "#aeaeaeff", + "avatar-border-green": "#49c970ff", + "avatar-border-orange": "#ff8648ff", + "avatar-border-pink": "#e4429eff", + "avatar-border-purple": "#7152f4ff", + "avatar-border-red": "#d92e3cff", + "avatar-border-yellow": "#e7af36ff", + "avatar-fg": "#ffffffff", + "background-bg-accent": "blue-600", + "background-bg-base": "grey-1100", + "background-bg-button-neutral": "alpha-light-6", + "background-bg-code-path": "cyan-1200", + "background-bg-contrast": "grey-700", + "background-bg-deep": "grey-1200", + "background-bg-icon-button-contrast": "grey-400", + "background-bg-inverse": "grey-50", + "background-bg-layer-01": "grey-1000", + "background-bg-layer-02": "grey-900", + "background-bg-layer-03": "grey-800", + "background-bg-layer-04": "grey-700", + "border-border-base": "alpha-light-10", + "border-border-focus": "blue-500", + "border-border-inverse": "grey-100", + "border-border-muted": "alpha-light-8", + "border-border-strong": "alpha-light-20", + "icon-icon-accent": "blue-400", + "icon-icon-accent-hover": "blue-300", + "icon-icon-base": "grey-400", + "icon-icon-contrast": "grey-100", + "icon-icon-faint": "grey-700", + "icon-icon-inverse": "grey-1100", + "icon-icon-muted": "grey-600", + "illustration-illustration-layer-01": "grey-900", + "illustration-illustration-layer-02": "grey-800", + "illustration-illustration-layer-03": "grey-700", + "overlay-gradient-depth-overlay-depth-bot": "alpha-light-0", + "overlay-gradient-depth-overlay-depth-top": "alpha-light-100", + "overlay-simple-overlay-contrast-hover": "alpha-dark-24", + "overlay-simple-overlay-contrast-pressed": "alpha-dark-40", + "overlay-simple-overlay-hover": "alpha-light-6", + "overlay-simple-overlay-pressed": "alpha-light-10", + "overlay-simple-overlay-scrim": "alpha-dark-60", + "overlay-simple-tab-active-scrim": "#24242400", + "overlay-simple-tab-hover-scrim": "#3a3a3a00", + "overlay-simple-tab-scrim": "#08080800", + "state-bg-danger": "red-1200", + "state-bg-info": "blue-1200", + "state-bg-success": "green-1200", + "state-bg-warning": "yellow-1200", + "state-border-danger": "red-900", + "state-border-info": "blue-900", + "state-border-success": "green-900", + "state-border-warning": "yellow-900", + "state-fg-danger": "red-500", + "state-fg-info": "blue-500", + "state-fg-success": "green-500", + "state-fg-warning": "yellow-500", + "text-text-accent": "blue-400", + "text-text-accent-hover": "blue-300", + "text-text-base": "grey-100", + "text-text-code-accent": "blue-400", + "text-text-code-path": "blue-300", + "text-text-contrast": "grey-50", + "text-text-faint": "grey-600", + "text-text-inverse": "grey-1100", + "text-text-muted": "grey-500" + }, + "numbers": { + "radius-panel": 10, + "radius-row": 6, + "inset-shell": 8, + "container-session": 744 + } +} diff --git a/app/vendor/rune/examples/lab/scripts/electric.json b/app/vendor/rune/examples/lab/scripts/electric.json new file mode 100644 index 0000000..e11aa7d --- /dev/null +++ b/app/vendor/rune/examples/lab/scripts/electric.json @@ -0,0 +1,4 @@ +[ + {"t": 0.1, "type": "move", "x": 810, "y": 410}, + {"t": 0.9, "type": "move", "x": 1200, "y": 650} +] diff --git a/app/vendor/rune/examples/lab/scripts/flashlight.json b/app/vendor/rune/examples/lab/scripts/flashlight.json new file mode 100644 index 0000000..8e3fe49 --- /dev/null +++ b/app/vendor/rune/examples/lab/scripts/flashlight.json @@ -0,0 +1,6 @@ +[ + {"t": 0.1, "type": "move", "x": 640, "y": 330}, + {"t": 0.3, "type": "move", "x": 740, "y": 380}, + {"t": 0.5, "type": "move", "x": 810, "y": 410}, + {"t": 0.9, "type": "move", "x": 1200, "y": 650} +] diff --git a/app/vendor/rune/examples/lab/scripts/keys.json b/app/vendor/rune/examples/lab/scripts/keys.json new file mode 100644 index 0000000..032813d --- /dev/null +++ b/app/vendor/rune/examples/lab/scripts/keys.json @@ -0,0 +1,6 @@ +[ + {"t": 0.05, "type": "move", "x": 300, "y": 300}, + {"t": 0.3, "type": "move", "x": 700, "y": 330}, + {"t": 0.5, "type": "tap", "x": 455, "y": 444, "hold": 0.3}, + {"t": 0.6, "type": "move", "x": 1000, "y": 360} +] diff --git a/app/vendor/rune/examples/lab/scripts/lamp.json b/app/vendor/rune/examples/lab/scripts/lamp.json new file mode 100644 index 0000000..aafb682 --- /dev/null +++ b/app/vendor/rune/examples/lab/scripts/lamp.json @@ -0,0 +1,3 @@ +[ + {"t": 0.1, "type": "drag", "x": 930, "y": 296, "dx": -420, "dy": 230, "dur": 0.8} +] diff --git a/app/vendor/rune/examples/lab/scripts/lens.json b/app/vendor/rune/examples/lab/scripts/lens.json new file mode 100644 index 0000000..995610e --- /dev/null +++ b/app/vendor/rune/examples/lab/scripts/lens.json @@ -0,0 +1,4 @@ +[ + {"t": 0.1, "type": "drag", "x": 470, "y": 304, "dx": 230, "dy": -150, "dur": 0.6}, + {"t": 1.0, "type": "tap", "x": 900, "y": 420} +] diff --git a/app/vendor/rune/examples/lab/scripts/motion.json b/app/vendor/rune/examples/lab/scripts/motion.json new file mode 100644 index 0000000..336c107 --- /dev/null +++ b/app/vendor/rune/examples/lab/scripts/motion.json @@ -0,0 +1,3 @@ +[ + {"t": 0.1, "type": "drag", "x": 630, "y": 400, "dx": 120, "dy": -60, "dur": 0.12} +] diff --git a/app/vendor/rune/examples/lab/scripts/pulses.json b/app/vendor/rune/examples/lab/scripts/pulses.json new file mode 100644 index 0000000..248a6a1 --- /dev/null +++ b/app/vendor/rune/examples/lab/scripts/pulses.json @@ -0,0 +1,5 @@ +[ + {"t": 0.1, "type": "tap", "x": 500, "y": 560}, + {"t": 0.3, "type": "tap", "key": "send"}, + {"t": 0.5, "type": "tap", "x": 900, "y": 450} +] diff --git a/app/vendor/rune/examples/lab/src/gfx.rs b/app/vendor/rune/examples/lab/src/gfx.rs new file mode 100644 index 0000000..3fef38f --- /dev/null +++ b/app/vendor/rune/examples/lab/src/gfx.rs @@ -0,0 +1,483 @@ +//! The compositor: Rune's instances (tagged by `El::mark`) become rune-light occluders and anchor +//! rune-fx layers. One HDR frame, one resolve into the window or the offscreen target. +//! +//! Per frame: partition the instances (lit canvases → base/text/prims, a moving card → its node +//! layer, masks → the mask pyramid, everything else → the main list), light the lit canvases, +//! then draw the main list into the HDR scene with each effect layer inserted under or over the +//! node it belongs to (copying the backdrop before distortion), and resolve with dither. + +mod gpu; +mod scenes; + +use std::collections::HashMap; + +use rune::compose::{Compositor, Frame, is_glyph}; +use rune::render::{Instance, KIND_GRADIENT, KIND_LAYER, KIND_LAYER_END, KIND_RECT}; +use rune_fx::{BlurMode, Fx, FxFrame, FxLayer, MotionBlurParams, MotionSamples, Pose, Rect, Shape}; +use rune_light::{Light, LightRenderer, Prim, Scene as LightScene, Settings}; +use rune_motion::Vec2; + +use crate::knobs::{ALL, FX_COLORS, Scene}; +use crate::stage::{self, mark_material, mark_node, mark_scene, node}; +use crate::{Grab, Lab}; + +use gpu::{HDR, Res, Timer, pass, pass_ts}; +use scenes::{Live, PrimCx, prim}; + +pub(self) const SRC_MASK: u32 = 0; +const SRC_NODE: u32 = 1; + +#[derive(Clone, Copy)] +enum Anchor { + Under(u8), + Over(u8), + /// Over everything in the canvas. + Top, +} + +struct Lay { + layer: FxLayer, + scene: Scene, + anchor: Anchor, +} + +/// One canvas on screen this frame. +struct Cv<'a> { + s: &'a Lab, + sc: Scene, + t: f32, + now: f64, + scale: f32, + origin: [f32; 2], + /// Canvas opacity (presence): lights and effects scale with it. + a: f32, + pointer: Option<[f32; 2]>, + reduced: bool, + viewport: Rect, +} + +impl Cv<'_> { + fn k(&self, id: &str) -> f32 { + self.s.k(self.sc, id) + } + fn on(&self, id: &str) -> bool { + self.s.on(self.sc, id) + } + /// Canvas points → window points. + fn w(&self, p: [f32; 2]) -> [f32; 2] { + [self.origin[0] + p[0], self.origin[1] + p[1]] + } + /// Canvas points → device pixels. + fn px(&self, p: [f32; 2]) -> [f32; 2] { + let q = self.w(p); + [q[0] * self.scale, q[1] * self.scale] + } + fn rounded(&self, r: Rect, radius: f32) -> Shape { + Shape::rounded(self.origin[0] + r.x, self.origin[1] + r.y, r.w, r.h, radius) + } + /// The whole viewport; the stage scissor clips it, so full-stage effects don't stop at the canvas edge. + fn everywhere(&self) -> Shape { + let v = self.viewport; + Shape::rounded(v.x, v.y, v.w, v.h, 0.0) + } + fn capsule(&self, r: Rect) -> Shape { + Shape::capsule(self.origin[0] + r.x, self.origin[1] + r.y, r.w, r.h) + } + fn circle(&self, c: [f32; 3]) -> Shape { + let q = self.w([c[0], c[1]]); + Shape::circle(q[0], q[1], c[2]) + } + fn swatch(&self) -> u32 { + FX_COLORS[(self.k("color") as usize).min(FX_COLORS.len() - 1)] + } +} + +#[derive(Default)] +pub struct LabGfx { + res: Option<Res>, + live: Live, + animating: bool, + view_pending: bool, + cpu: (f64, u32), + gpu: (f64, u32), + last_push: Option<f64>, + shown: Option<(i32, Option<i32>, bool)>, + last_pointer: Option<(f32, f32)>, + total_gpu: (f64, u32), +} + +impl Compositor<Lab> for LabGfx { + fn features(&self) -> wgpu::Features { + wgpu::Features::TIMESTAMP_QUERY + } + + fn animating(&self) -> bool { + self.animating || self.view_pending + } + + fn summary(&mut self, _device: &wgpu::Device) -> Option<String> { + let (sum, n) = self.total_gpu; + Some(if n > 0 { + format!("lab: gpu frame mean {:.3} ms over {n} timed frames (timestamp markers around the whole compositor)", sum / n as f64) + } else { + "lab: no GPU timestamps (adapter lacks TIMESTAMP_QUERY or too few frames)".to_owned() + }) + } + + fn render(&mut self, f: &mut Frame<'_, Lab>) { + let started = rune::time::now(); + let rebuilt = self.res.as_ref().is_none_or(|r| r.size != f.size || r.format != f.format); + if rebuilt { + self.res = Some(Res::new(f.device, f.queue, f.size, f.format, f.ui)); + } + self.view_pending = false; + f.device.poll(wgpu::PollType::Poll).ok(); + let res = self.res.as_mut().unwrap(); + let gpu_ms = res.timer.as_mut().and_then(|t| t.begin(f.encoder)); + let rt = &mut *f.rt; + let scale = rt.env.scale; + let now = rt.t; + let t = now as f32; + let (w, h) = f.size; + let vp = Rect::new(0.0, 0.0, w as f32 / scale, h as f32 / scale); + let stage_r = rt.presented("stage").map_or([vp.x, vp.y, vp.w, vp.h], |(r, _)| r); + let in_stage = |p: (f32, f32)| p.0 >= stage_r[0] && p.0 <= stage_r[0] + stage_r[2] && p.1 >= stage_r[1] && p.1 <= stage_r[1] + stage_r[3]; + let pointer = rt.pointer().filter(|p| in_stage(*p)); + let canvases: Vec<(Scene, [f32; 2], f32)> = ALL + .iter() + .filter_map(|sc| rt.presented(&format!("canvas-{}", sc.id())).map(|(r, a)| (*sc, [r[0], r[1]], a))) + .filter(|c| c.2 > 0.001) + .collect(); + let s = &rt.state; + let mut anim = false; + + // ---- lights and effect layers per visible canvas + let mut lights: Vec<Light> = Vec::new(); + let mut settings: Option<(f32, Settings)> = None; + let mut lit_alpha = 0.0f32; + let mut pc = PrimCx::default(); + let mut lays: Vec<Lay> = Vec::new(); + for &(sc, origin, a) in &canvases { + let cv = Cv { + s, + sc, + t, + now, + scale, + origin, + a, + pointer: pointer.map(|p| [p.0 - origin[0], p.1 - origin[1]]), + reduced: s.reduced, + viewport: vp, + }; + if sc.lit() { + lit_alpha = lit_alpha.max(a); + let st = self.live.lights(&cv, &mut lights, &mut pc, &mut anim); + if settings.as_ref().is_none_or(|(sa, _)| a > *sa) { + settings = Some((a, st)); + } + } else { + self.live.layers(&cv, &mut lays, &mut anim); + } + } + for l in &lays { + anim |= l.layer.is_animating(); + } + + // ---- the motion card: rest rect (where Rune drew it) and its pose along the track + let card_drawn = rt.presented("card").map(|(r, _)| r); + let mut card_blur: Option<(MotionBlurParams, MotionSamples, Rect)> = None; + let mut card_off = [0.0f32; 2]; + if let (Some(r), Some(&(_, origin, _))) = (card_drawn, canvases.iter().find(|c| c.0 == Scene::Motion)) { + let rest = Rect::new(r[0], r[1], r[2], r[3]); + let dragging = matches!(s.grab, Some(Grab::Card(_))); + let pose_at = |tt: f32| -> Pose { + let c = if dragging { + let c = s.card.target(); + let v = s.card_vt.velocity(); + let dt = (tt as f64 - now) as f32; + Vec2 { x: c.x + v.x * dt, y: c.y + v.y * dt } + } else { + s.card.sample(tt as f64) + }; + Pose { x: origin[0] + c.x - rest.x, y: origin[1] + c.y - rest.y, ..Default::default() } + }; + let p = MotionBlurParams { + mode: if s.on(Scene::Motion, "directional") { BlurMode::Directional } else { BlurMode::Shutter }, + shutter_angle: if s.reduced { 0.0 } else { s.k(Scene::Motion, "shutter_angle") }, + smooth_shutter: s.on(Scene::Motion, "smooth"), + ..Default::default() + }; + let samples = MotionSamples::from_track(&p, rest, t, scale, pose_at); + let pm = pose_at(t); + card_off = [pm.x * scale, pm.y * scale]; + anim |= dragging || !s.card.is_settled(now); + if samples.is_moving() { + card_blur = Some((p, samples, rest)); + } + } + if let Some((p, samples, rest)) = card_blur { + let layer = Fx::motion_blur(p, samples).on(Shape::rounded(rest.x, rest.y, rest.w, rest.h, 14.0)).source(SRC_NODE, vp).at(t); + lays.push(Lay { layer, scene: Scene::Motion, anchor: Anchor::Over(node::CARD) }); + } + + // ---- partition Rune's instances + let inst = &rt.instances; + let marks = &rt.marks; + let mut main: Vec<Instance> = Vec::with_capacity(inst.len()); + let (mut base, mut text, mut nodel, mut mask) = (Vec::new(), Vec::new(), Vec::new(), Vec::new()); + let mut prims: Vec<Prim> = Vec::new(); + let mut first_lit: Option<usize> = None; + let mut first: HashMap<(usize, u8), usize> = HashMap::new(); + let mut last: HashMap<(usize, u8), usize> = HashMap::new(); + let mut top: HashMap<usize, usize> = HashMap::new(); + let mut stage_fill = [0.0, 0.0, 0.0, 1.0]; + let needs_mask = lays.iter().any(|l| l.layer.source.is_some_and(|s| s.slot == SRC_MASK)); + // This demo owns a different effect graph: it splits glyphs from their backgrounds + // and inserts effects between individual nodes. Preserve its existing flattened + // opacity semantics until that graph can composite an entire scope after lighting. + // Ordinary Rune compositors instead preserve scopes and call encode_layers. + let mut opacity = 1.0; + let mut opacity_stack = Vec::new(); + for (i, ins) in inst.iter().enumerate() { + if ins.params[1] == KIND_LAYER { + opacity_stack.push(opacity); + opacity *= ins.fill[3]; + continue; + } + if ins.params[1] == KIND_LAYER_END { + opacity = opacity_stack.pop().expect("balanced Rune layer scopes"); + continue; + } + let mut flattened = *ins; + flattened.fill = flattened.fill.map(|v| v * opacity); + flattened.border = flattened.border.map(|v| v * opacity); + if flattened.params[1] == KIND_GRADIENT { flattened.uv = flattened.uv.map(|v| v * opacity); } + let ins = &flattened; + let m = marks.get(i).copied().unwrap_or(0); + if m == stage::STAGE_MARK && ins.params[1] == KIND_RECT { + stage_fill = ins.fill; + } + let sc = mark_scene(m); + let nd = mark_node(m); + if let Some(sc) = sc { + first.entry((sc.idx(), nd)).or_insert(main.len()); + } + match sc { + Some(sc) if sc.lit() => { + first_lit.get_or_insert(main.len()); + if is_glyph(ins) { + text.push(*ins); + } else { + base.push(*ins); + if ins.params[1] == KIND_RECT + && let Some(p) = prim(ins, mark_material(m), nd, &pc, scale) + { + prims.push(p); + } + } + } + Some(Scene::Motion) if nd == node::CARD => { + if card_blur.is_some() { + nodel.push(*ins); + } else { + let mut c = *ins; + c.rect[0] += card_off[0]; + c.rect[1] += card_off[1]; + main.push(c); + } + } + _ => main.push(*ins), + } + if needs_mask && matches!(nd, node::GLOW_TEXT | node::SKELETON | node::THINKING) && sc.is_some_and(|s| !s.lit()) { + mask.push(*ins); + } + if let Some(sc) = sc { + last.insert((sc.idx(), nd), main.len()); + top.insert(sc.idx(), main.len()); + } + } + let light_on = !base.is_empty() && settings.is_some(); + if light_on && lights.is_empty() { + // GI off with no lights: an ambient-only pass keeps the canvas lit by its settings. + lights.push(Light::point(0.0, 0.0, 1.0).intensity(0.0)); + } + + // ---- ops: where each effect layer goes in the main list + enum Op { + Ui, + Blit, + Fx(usize), + } + let mut ops: Vec<(usize, Op)> = Vec::new(); + if light_on && let Some(p) = first_lit { + ops.push((p, Op::Blit)); + } + let mut layers: Vec<FxLayer> = Vec::new(); + let mut needs_bd: Vec<bool> = Vec::new(); + for l in lays { + let key = |n: u8| (l.scene.idx(), n); + let pos = match l.anchor { + Anchor::Under(n) => first.get(&key(n)).copied(), + Anchor::Over(n) => last.get(&key(n)).copied(), + Anchor::Top => top.get(&l.scene.idx()).copied(), + }; + let Some(pos) = pos else { continue }; + needs_bd.push(l.layer.fx.needs_backdrop()); + ops.push((pos, Op::Fx(layers.len()))); + layers.push(l.layer.reduced(s.reduced)); + } + ops.sort_by_key(|o| o.0); + ops.push((main.len(), Op::Ui)); + + // ---- upload and draw + let clear = rt.clear_color(); + let ranges = f.ui.prepare_lists(f.device, f.queue, &mut rt.text.atlas, &[&main, &base, &text, &nodel, &mask], f.size); + let sources = [&res.pyramid.view, &res.node.view]; + let stats = res.fx.prepare( + f.device, + f.queue, + &FxFrame { viewport: [w, h], scale, layers: &layers, backdrop: Some(&res.backdrop.view), sources: &sources }, + ); + let enc = &mut *f.encoder; + // GPU time spans the first pass the compositor records through the end of the resolve pass. + let tq = res.timer.as_ref().and_then(Timer::query); + let mut began = false; + let mut stamp = |end: bool| { + let first = !std::mem::replace(&mut began, true); + tq.as_ref().filter(|_| first || end).map(|q| wgpu::RenderPassTimestampWrites { + query_set: q, + beginning_of_pass_write_index: first.then_some(0), + end_of_pass_write_index: end.then_some(1), + }) + }; + if needs_mask && !mask.is_empty() { + { + let mut p = pass_ts(enc, &res.pyramid.levels[0], Some([0.0; 4]), stamp(false)); + f.ui.draw_range(&mut p, HDR, ranges[4].clone()); + } + res.fx.build_mips(f.device, enc, &res.pyramid); + } + if !nodel.is_empty() { + let mut p = pass_ts(enc, &res.node.view, Some([0.0; 4]), stamp(false)); + f.ui.draw_range(&mut p, HDR, ranges[3].clone()); + } + let mut lit_drawn = false; + if light_on { + let (_, mut st) = settings.unwrap(); + st.time = t; + let a = stage_fill[3].max(1e-4); + { + let mut p = pass_ts(enc, &res.base.view, Some([stage_fill[0] / a, stage_fill[1] / a, stage_fill[2] / a, 1.0]), stamp(false)); + f.ui.draw_range(&mut p, HDR, ranges[1].clone()); + } + { + let mut p = pass(enc, &res.text.view, Some([0.0; 4])); + f.ui.draw_range(&mut p, HDR, ranges[2].clone()); + } + let light = res.light.get_or_insert_with(|| LightRenderer::new(f.device, f.queue, w, h, HDR)); + lit_drawn = light.render( + f.device, + f.queue, + enc, + &LightScene { prims: &prims, lights: &lights, settings: st, emission: None }, + &res.base.view, + &res.text.view, + &res.lit.view, + ); + f.queue.write_buffer(&res.blit_alpha, 0, bytemuck::cast_slice(&[lit_alpha, 0.0, 0.0, 0.0])); + } + let px = |v: f32| (v * scale).round().max(0.0) as u32; + let (sx, sy) = (px(stage_r[0]).min(w), px(stage_r[1]).min(h)); + let (sw, sh) = (px(stage_r[0] + stage_r[2]).min(w) - sx, px(stage_r[1] + stage_r[3]).min(h) - sy); + if res.fx.simulate_pending() { + let ts = stamp(false).map(|w| wgpu::ComputePassTimestampWrites { + query_set: w.query_set, + beginning_of_pass_write_index: w.beginning_of_pass_write_index, + end_of_pass_write_index: w.end_of_pass_write_index, + }); + res.fx.simulate(f.queue, enc, ts); + } + let mut cursor = 0usize; + let mut rp = pass_ts(enc, &res.scene.view, Some(clear), stamp(false)).forget_lifetime(); + for (pos, op) in ops { + if pos > cursor { + rp.set_scissor_rect(0, 0, w, h); + f.ui.draw_range(&mut rp, HDR, ranges[0].start + cursor as u32..ranges[0].start + pos as u32); + cursor = pos; + } + match op { + Op::Ui => {} + Op::Blit if lit_drawn && sw > 0 && sh > 0 => { + rp.set_scissor_rect(sx, sy, sw, sh); + rp.set_pipeline(&res.blit.pipeline); + rp.set_bind_group(0, &res.blit_bg, &[]); + rp.draw(0..3, 0..1); + } + Op::Blit => {} + Op::Fx(i) => { + if sw == 0 || sh == 0 { + continue; + } + if needs_bd[i] { + drop(rp); + let o = wgpu::Origin3d { x: sx, y: sy, z: 0 }; + enc.copy_texture_to_texture( + wgpu::TexelCopyTextureInfo { texture: &res.scene.tex, mip_level: 0, origin: o, aspect: wgpu::TextureAspect::All }, + wgpu::TexelCopyTextureInfo { texture: &res.backdrop.tex, mip_level: 0, origin: o, aspect: wgpu::TextureAspect::All }, + wgpu::Extent3d { width: sw, height: sh, depth_or_array_layers: 1 }, + ); + res.fx.blur_backdrop(f.device, f.queue, enc, &res.backdrop.view, i); + rp = pass(enc, &res.scene.view, None).forget_lifetime(); + } + rp.set_scissor_rect(sx, sy, sw, sh); + res.fx.draw_layer(&mut rp, i); + } + } + } + drop(rp); + { + let mut p = pass_ts(enc, f.target, Some([0.0, 0.0, 0.0, 1.0]), stamp(true)); + p.set_pipeline(&res.resolve.pipeline); + p.set_bind_group(0, &res.resolve_bg, &[]); + p.draw(0..3, 0..1); + } + if let Some(tm) = res.timer.as_mut() { + tm.end(); + } + self.animating = anim; + + // ---- readout: averaged over a quarter second of Rune's clock. It asks for a redraw only on frames that + // were drawing anyway (animating, the display link flipping, the pointer moving), so a scene at rest never + // draws frames for its own readout. + let moved = std::mem::replace(&mut self.last_pointer, rt.pointer()) != self.last_pointer; + // A frame that (re)built resources pays pipeline compiles; it would stick in an at-rest readout. + if !rebuilt { + self.cpu.0 += f.update_ms + started.elapsed().as_secs_f64() * 1000.0; + self.cpu.1 += 1; + } + if let Some(g) = gpu_ms { + self.gpu.0 += g as f64; + self.gpu.1 += 1; + self.total_gpu.0 += g as f64; + self.total_gpu.1 += 1; + } + let due = self.last_push.is_none_or(|p| now - p >= 0.25); + let live_flip = self.shown.is_some_and(|(_, _, l)| l != anim); + if due && (anim || moved) || live_flip { + let c = if self.cpu.1 > 0 { (self.cpu.0 / self.cpu.1 as f64) as f32 } else { rt.state.perf.cpu_ms }; + let g = (self.gpu.1 > 0).then(|| (self.gpu.0 / self.gpu.1 as f64) as f32).or(rt.state.perf.gpu_ms); + let key = ((c * 100.0).round() as i32, g.map(|g| (g * 100.0).round() as i32), anim); + if self.shown != Some(key) { + rt.state.perf = crate::Perf { cpu_ms: c, gpu_ms: g, draws: stats.drawn, live: anim }; + rt.invalidate(); + self.view_pending = true; + self.shown = Some(key); + } + self.cpu = (0.0, 0); + self.gpu = (0.0, 0); + self.last_push = Some(now); + } + rt.state.now = now; + } +} diff --git a/app/vendor/rune/examples/lab/src/gfx/gpu.rs b/app/vendor/rune/examples/lab/src/gfx/gpu.rs new file mode 100644 index 0000000..cb042c4 --- /dev/null +++ b/app/vendor/rune/examples/lab/src/gfx/gpu.rs @@ -0,0 +1,298 @@ +//! Offscreen HDR render targets, resolve/blit shaders and async GPU frame timer. + +use std::sync::Arc; +use std::sync::atomic::{AtomicU8, Ordering}; + +use rune_fx::{FxOptions, FxRenderer, MaskPyramid}; +use rune_light::LightRenderer; + +pub(super) const HDR: wgpu::TextureFormat = wgpu::TextureFormat::Rgba16Float; + +pub(super) struct Tex { + pub(super) tex: wgpu::Texture, + pub(super) view: wgpu::TextureView, +} + +fn tex(device: &wgpu::Device, label: &str, size: (u32, u32), usage: wgpu::TextureUsages) -> Tex { + let tex = device.create_texture(&wgpu::TextureDescriptor { + label: Some(label), + size: wgpu::Extent3d { width: size.0, height: size.1, depth_or_array_layers: 1 }, + mip_level_count: 1, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + format: HDR, + usage, + view_formats: &[], + }); + let view = tex.create_view(&Default::default()); + Tex { tex, view } +} + +const SHADERS: &str = r#" +@group(0) @binding(0) var src: texture_2d<f32>; +@group(0) @binding(1) var<uniform> alpha: vec4f; + +struct V { @builtin(position) pos: vec4f } + +@vertex +fn vs(@builtin(vertex_index) vi: u32) -> V { + let p = vec2f(f32((vi << 1u) & 2u), f32(vi & 2u)); + var o: V; + o.pos = vec4f(p * 2.0 - 1.0, 0.0, 1.0); + return o; +} + +fn pcg(v: u32) -> u32 { + let s = v * 747796405u + 2891336453u; + let w = ((s >> ((s >> 28u) + 4u)) ^ s) * 277803737u; + return (w >> 22u) ^ w; +} +fn u01(n: u32) -> f32 { return f32(pcg(n) >> 8u) * (1.0 / 16777216.0); } +fn to_srgb(c: vec3f) -> vec3f { + let lo = c * 12.92; + let hi = 1.055 * pow(max(c, vec3f(0.0)), vec3f(1.0 / 2.4)) - 0.055; + return select(hi, lo, c <= vec3f(0.0031308)); +} +fn from_srgb(c: vec3f) -> vec3f { + let lo = c / 12.92; + let hi = pow((max(c, vec3f(0.0)) + 0.055) / 1.055, vec3f(2.4)); + return select(hi, lo, c <= vec3f(0.04045)); +} +fn dithered(pos: vec2f) -> vec3f { + let ip = vec2u(pos); + let c = textureLoad(src, vec2i(ip), 0); + let n = u01(ip.x + pcg(ip.y)) + u01(ip.x * 7919u + pcg(ip.y + 104729u)) - 1.0; + return clamp(to_srgb(clamp(c.rgb, vec3f(0.0), vec3f(1.0))) + vec3f(n / 255.0), vec3f(0.0), vec3f(1.0)); +} + +// Linear HDR scene -> 8-bit target with TPDF dither, once. +@fragment +fn fs_resolve_srgb(in: V) -> @location(0) vec4f { return vec4f(from_srgb(dithered(in.pos.xy)), 1.0); } +@fragment +fn fs_resolve_unorm(in: V) -> @location(0) vec4f { return vec4f(dithered(in.pos.xy), 1.0); } + +// The lit stage (sRGB-encoded by rune-light's composite) into the linear scene. +@fragment +fn fs_blit(in: V) -> @location(0) vec4f { + let c = textureLoad(src, vec2i(in.pos.xy), 0); + return vec4f(from_srgb(c.rgb) * alpha.x, alpha.x); +} +"#; + +pub(super) struct Fullscreen { + pub(super) pipeline: wgpu::RenderPipeline, + bgl: wgpu::BindGroupLayout, +} + +fn fullscreen(device: &wgpu::Device, module: &wgpu::ShaderModule, entry: &str, format: wgpu::TextureFormat, blend: Option<wgpu::BlendState>) -> Fullscreen { + let bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + label: Some(entry), + entries: &[ + wgpu::BindGroupLayoutEntry { + binding: 0, + visibility: wgpu::ShaderStages::FRAGMENT, + ty: wgpu::BindingType::Texture { + sample_type: wgpu::TextureSampleType::Float { filterable: false }, + view_dimension: wgpu::TextureViewDimension::D2, + multisampled: false, + }, + count: None, + }, + wgpu::BindGroupLayoutEntry { + binding: 1, + visibility: wgpu::ShaderStages::FRAGMENT, + ty: wgpu::BindingType::Buffer { ty: wgpu::BufferBindingType::Uniform, has_dynamic_offset: false, min_binding_size: None }, + count: None, + }, + ], + }); + let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { label: Some(entry), bind_group_layouts: &[Some(&bgl)], immediate_size: 0 }); + let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { + label: Some(entry), + layout: Some(&layout), + vertex: wgpu::VertexState { module, entry_point: Some("vs"), compilation_options: Default::default(), buffers: &[] }, + primitive: Default::default(), + depth_stencil: None, + multisample: Default::default(), + fragment: Some(wgpu::FragmentState { + module, + entry_point: Some(entry), + compilation_options: Default::default(), + targets: &[Some(wgpu::ColorTargetState { format, blend, write_mask: wgpu::ColorWrites::ALL })], + }), + multiview_mask: None, + cache: None, + }); + Fullscreen { pipeline, bgl } +} + +/// Whole-frame GPU time from timestamps on the compositor's own passes, read back a couple of +/// frames later without stalling. +pub(super) struct Timer { + qs: wgpu::QuerySet, + resolve: wgpu::Buffer, + read: wgpu::Buffer, + /// 0 idle, 4 written, 1 copy recorded, 2 mapping, 3 mapped. + state: Arc<AtomicU8>, + period: f32, + recording: bool, +} + +impl Timer { + fn new(device: &wgpu::Device, queue: &wgpu::Queue) -> Option<Timer> { + if !device.features().contains(wgpu::Features::TIMESTAMP_QUERY) { + return None; + } + let qs = device.create_query_set(&wgpu::QuerySetDescriptor { label: Some("lab ts"), ty: wgpu::QueryType::Timestamp, count: 2 }); + let buf = |label, usage| device.create_buffer(&wgpu::BufferDescriptor { label: Some(label), size: 16, usage, mapped_at_creation: false }); + let resolve = buf("lab ts resolve", wgpu::BufferUsages::QUERY_RESOLVE | wgpu::BufferUsages::COPY_SRC); + let read = buf("lab ts read", wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ); + Some(Timer { qs, resolve, read, state: Arc::new(AtomicU8::new(0)), period: queue.get_timestamp_period(), recording: false }) + } + + /// Collects a finished reading (ms) and decides whether this frame records one. Last frame's queries are + /// resolved here, a command buffer later: Metal orders work by resource, so a resolve in the same encoder + /// can run before the final pass's end-of-pass sample lands. + pub(super) fn begin(&mut self, enc: &mut wgpu::CommandEncoder) -> Option<f32> { + let mut out = None; + match self.state.load(Ordering::Acquire) { + 4 => { + enc.resolve_query_set(&self.qs, 0..2, &self.resolve, 0); + enc.copy_buffer_to_buffer(&self.resolve, 0, &self.read, 0, 16); + self.state.store(1, Ordering::Release); + } + 1 => { + self.state.store(2, Ordering::Release); + let st = self.state.clone(); + self.read.slice(..).map_async(wgpu::MapMode::Read, move |r| st.store(if r.is_ok() { 3 } else { 0 }, Ordering::Release)); + } + 3 => { + if let Ok(data) = self.read.slice(..).get_mapped_range() { + let t: &[u64] = bytemuck::cast_slice(&data); + out = (t[1] > t[0]).then(|| (t[1] - t[0]) as f32 * self.period / 1e6); + } + self.read.unmap(); + self.state.store(0, Ordering::Release); + } + _ => {} + } + self.recording = self.state.load(Ordering::Acquire) == 0; + out + } + + /// The query set when this frame records. The writes go on the compositor's own render passes: Metal may + /// overlap a resource-free marker pass with the work around it, so empty marker passes read near zero. + pub(super) fn query(&self) -> Option<wgpu::QuerySet> { + self.recording.then(|| self.qs.clone()) + } + + pub(super) fn end(&mut self) { + if self.recording { + self.state.store(4, Ordering::Release); + } + } +} + +pub(super) struct Res { + pub(super) size: (u32, u32), + pub(super) format: wgpu::TextureFormat, + pub(super) scene: Tex, + pub(super) backdrop: Tex, + pub(super) node: Tex, + pub(super) base: Tex, + pub(super) text: Tex, + pub(super) lit: Tex, + pub(super) pyramid: MaskPyramid, + pub(super) light: Option<LightRenderer>, + pub(super) fx: FxRenderer, + pub(super) resolve: Fullscreen, + pub(super) blit: Fullscreen, + pub(super) resolve_bg: wgpu::BindGroup, + pub(super) blit_bg: wgpu::BindGroup, + pub(super) blit_alpha: wgpu::Buffer, + pub(super) timer: Option<Timer>, +} + +impl Res { + pub(super) fn new(device: &wgpu::Device, queue: &wgpu::Queue, size: (u32, u32), format: wgpu::TextureFormat, ui: &mut rune::render::Renderer) -> Res { + use wgpu::TextureUsages as U; + ui.add_format(device, HDR); + let rt = U::RENDER_ATTACHMENT | U::TEXTURE_BINDING; + let scene = tex(device, "lab scene", size, rt | U::COPY_SRC); + let backdrop = tex(device, "lab backdrop", size, U::TEXTURE_BINDING | U::COPY_DST); + let node = tex(device, "lab node layer", size, rt); + let base = tex(device, "lab base", size, rt); + let text = tex(device, "lab text", size, rt); + let lit = tex(device, "lab lit", size, rt); + let module = device.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some("lab"), source: wgpu::ShaderSource::Wgsl(SHADERS.into()) }); + let resolve = fullscreen(device, &module, if format.is_srgb() { "fs_resolve_srgb" } else { "fs_resolve_unorm" }, format, None); + let blit = fullscreen(device, &module, "fs_blit", HDR, Some(wgpu::BlendState::PREMULTIPLIED_ALPHA_BLENDING)); + let blit_alpha = device.create_buffer(&wgpu::BufferDescriptor { + label: Some("lab blit alpha"), + size: 16, + usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + }); + let bind = |f: &Fullscreen, v: &wgpu::TextureView| { + device.create_bind_group(&wgpu::BindGroupDescriptor { + label: None, + layout: &f.bgl, + entries: &[ + wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::TextureView(v) }, + wgpu::BindGroupEntry { binding: 1, resource: blit_alpha.as_entire_binding() }, + ], + }) + }; + let resolve_bg = bind(&resolve, &scene.view); + let blit_bg = bind(&blit, &lit.view); + Res { + size, + format, + pyramid: MaskPyramid::new(device, size.0, size.1), + light: None, + fx: { + let mut fx = FxRenderer::new(device, HDR, FxOptions { dither: false }); + fx.set_fire_sim(device, true); + fx + }, + timer: Timer::new(device, queue), + scene, + backdrop, + node, + base, + text, + lit, + resolve, + blit, + resolve_bg, + blit_bg, + blit_alpha, + } + } +} + +pub(super) fn pass<'e>(enc: &'e mut wgpu::CommandEncoder, view: &'e wgpu::TextureView, clear: Option<[f32; 4]>) -> wgpu::RenderPass<'e> { + pass_ts(enc, view, clear, None) +} + +pub(super) fn pass_ts<'e>( + enc: &'e mut wgpu::CommandEncoder, + view: &'e wgpu::TextureView, + clear: Option<[f32; 4]>, + timestamp_writes: Option<wgpu::RenderPassTimestampWrites<'e>>, +) -> wgpu::RenderPass<'e> { + let load = clear.map_or(wgpu::LoadOp::Load, |c| wgpu::LoadOp::Clear(wgpu::Color { r: c[0] as f64, g: c[1] as f64, b: c[2] as f64, a: c[3] as f64 })); + enc.begin_render_pass(&wgpu::RenderPassDescriptor { + label: Some("lab"), + color_attachments: &[Some(wgpu::RenderPassColorAttachment { + view, + depth_slice: None, + resolve_target: None, + ops: wgpu::Operations { load, store: wgpu::StoreOp::Store }, + })], + depth_stencil_attachment: None, + timestamp_writes, + occlusion_query_set: None, + multiview_mask: None, + }) +} diff --git a/app/vendor/rune/examples/lab/src/gfx/scenes.rs b/app/vendor/rune/examples/lab/src/gfx/scenes.rs new file mode 100644 index 0000000..ceb9a69 --- /dev/null +++ b/app/vendor/rune/examples/lab/src/gfx/scenes.rs @@ -0,0 +1,607 @@ +//! Per-scene lights, rune-light material primitives and rune-fx layers. + +use rune::render::Instance; +use rune_fx::{ + AuroraParams, DistortParams, ElectricParams, ElectricStyle, FireParams, Fx, FxLayer, GlowParams, GlowStyle, + GrainParams, Heat, LensParams, PulseParams, PulseStyle, Shape, ShimmerParams, SparkleParams, rgb, +}; +use rune_light::{Gi, Light, Prim, Settings, TextPolicy}; +use rune_motion::{Animated, Spring, Vec2}; + +use crate::ShotKind; +use crate::knobs::{LAMP_COLORS, Scene, lin}; +use crate::stage::{self, mat, node}; + +use super::{Anchor, Cv, Lay, SRC_MASK}; + +/// A light that follows the pointer 1:1 while it's over the stage and cools when it leaves. +struct Follow { + pos: [f32; 2], + k: Animated<f32>, + inside: Option<bool>, +} + +impl Follow { + fn new(rest: [f32; 2]) -> Follow { + Follow { pos: rest, k: Animated::new(1.0), inside: None } + } + + fn update(&mut self, p: Option<[f32; 2]>, now: f64) -> ([f32; 2], f32) { + match p { + Some(p) => { + self.pos = p; + if self.inside != Some(true) { + self.k.animate_to(1.0, Spring::new(0.3, 0.0), now); + self.inside = Some(true); + } + } + None if self.inside == Some(true) => { + self.k.animate_to(0.0, Spring::new(0.45, 0.0), now); + self.inside = Some(false); + } + None => {} + } + (self.pos, self.k.sample(now).clamp(0.0, 1.0)) + } + + fn moving(&self, now: f64) -> bool { + !self.k.is_settled(now) + } +} + +/// A light switched by state: it warms up fast and cools slowly. +struct Switch { + on: Option<bool>, + heat: Heat, +} + +impl Switch { + fn new(attack: f32, cool: f32) -> Switch { + Switch { on: None, heat: Heat::new(attack, cool) } + } + + fn at(&mut self, on: bool, t: f32) -> f32 { + if self.on != Some(on) { + // The first sight is the resting state, not a warm-up. + self.heat.set(if self.on.is_none() { -10.0 } else { t }, on); + self.on = Some(on); + } + self.heat.at(t) + } + + fn moving(&self, t: f32) -> bool { + self.heat.is_active(t) + } +} + +pub(super) struct Live { + torch: Follow, + keylight: Follow, + sun: Follow, + neon: Switch, + charged: Switch, + rec: Switch, + upload: Switch, + droplet: Option<Animated<Vec2>>, +} + +impl Default for Live { + fn default() -> Self { + Live { + torch: Follow::new([470.0, 250.0]), + keylight: Follow::new([150.0, 230.0]), + sun: Follow::new(stage::GODRAY_REST), + neon: Switch::new(0.12, 0.32), + charged: Switch::new(0.15, 0.5), + rec: Switch::new(0.12, 0.6), + upload: Switch::new(0.12, 0.6), + droplet: None, + } + } +} + +/// Per-scene material inputs for prims. +#[derive(Default)] +pub(super) struct PrimCx { + keys: Vec<f32>, + bevel: f32, + gloss: f32, + rec: f32, + status: f32, + progress: f32, +} + +fn srgbf(r: f32, g: f32, b: f32) -> [f32; 3] { + let f = rune::color::srgb_decode; + [f(r), f(g), f(b)] +} + +pub(super) fn prim(ins: &Instance, material: u8, nd: u8, pc: &PrimCx, s: f32) -> Option<Prim> { + let a = ins.fill[3].max(1e-4); + let alb = [ins.fill[0] / a, ins.fill[1] / a, ins.fill[2] / a]; + let p = Prim::from_rune(ins.rect, ins.radii).albedo(alb); + let (bv, g) = (pc.bevel, pc.gloss); + Some(match material { + mat::CARD => p.raised(6.0 * s).bevel(6.0 * s, 2.0 * s).gloss(0.55, 0.42), + mat::CHIP => p.on(6.0 * s).raised(2.5 * s).bevel(4.0 * s, 1.0 * s).gloss(0.4, 0.4), + mat::BUTTON => p.on(10.0 * s).raised(4.0 * s).bevel(10.0 * s, 3.0 * s).gloss(0.8, 0.3), + mat::COMPOSER => p.raised(10.0 * s).bevel(7.0 * s, 2.5 * s).gloss(0.6, 0.38), + mat::ON_CARD => p.on(6.0 * s).gloss(0.4, 0.4), + mat::SWITCH => p.on(6.0 * s).raised(5.0 * s).bevel(9.0 * s, 4.0 * s).gloss(0.7, 0.3), + mat::PILL => p.on(6.0 * s).raised(3.0 * s).bevel(4.0 * s, 1.2 * s).gloss(0.5, 0.4), + mat::BAR => p.on(6.0 * s).raised(2.0 * s), + mat::DIAL => p.on(6.0 * s).bevel(16.0 * s, 4.0 * s).gloss(0.6, 0.35), + mat::EMIT => { + let k = match nd { + node::REC => pc.rec, + node::STATUS => pc.status, + node::PROGRESS => pc.progress, + _ => 0.0, + }; + p.on(6.0 * s).emissive([alb[0] * k, alb[1] * k, alb[2] * k]) + } + mat::FLAT => p, + mat::KNOB => p.floating(10.0 * s, 22.0 * s).bevel(30.0 * bv * s, 10.0 * bv * s).gloss(0.9, 0.26), + mat::KEY => { + let d = nd.checked_sub(node::KEY0).and_then(|i| pc.keys.get(i as usize)).copied().unwrap_or(0.0).clamp(0.0, 1.2); + p.floating((10.0 - 6.0 * d) * s, (18.0 - 11.0 * d) * s).bevel(12.0 * bv * s, 4.5 * bv * s).gloss(g, 0.28) + } + mat::BODY => p.raised(10.0 * s).bevel(22.0 * bv * s, 7.0 * bv * s).gloss(0.7, 0.32), + mat::SCREEN => p.on(10.0 * s).gloss(1.0, 0.18), + mat::TILE => p.raised(14.0 * s).bevel(8.0 * s, 2.5 * s).gloss(0.5, 0.4), + _ => return None, + }) +} + +impl Live { + /// Lights for a lit canvas (appended, scaled by its presence) and its settings. + pub(super) fn lights(&mut self, cv: &Cv, out: &mut Vec<Light>, pc: &mut PrimCx, anim: &mut bool) -> Settings { + let s = cv.scale; + let (t, now) = (cv.t, cv.now); + match cv.sc { + Scene::Lamp => { + let p = cv.px(cv.s.lamp); + let col = lin(LAMP_COLORS[(cv.k("color") as usize).min(LAMP_COLORS.len() - 1)]); + out.push( + Light::point(p[0], p[1], cv.k("height") * s) + .color(col) + .intensity(cv.k("intensity")) + .radius(cv.k("radius") * s) + .range(1100.0 * s) + .bulb(0.75) + .specular(1.2) + .scaled(cv.a), + ); + if cv.on("fill") { + let q = cv.px([-300.0, -200.0]); + out.push(Light::point(q[0], q[1], 900.0 * s).color(srgbf(0.55, 0.65, 1.0)).intensity(0.35).radius(220.0 * s).range(6000.0 * s).specular(0.4).scaled(cv.a)); + } + Settings { + ambient: [0.62, 0.63, 0.7], + albedo_floor: 0.07, + gi: cv.on("bounce").then_some(Gi { strength: 1.0, air: 0.0, bounce: 0.6, absorption: 0.24, ..Default::default() }), + rim: 0.9, + contact_ao: 0.45, + ..Default::default() + } + } + Scene::Flashlight => { + let (p, k) = self.torch.update(cv.pointer, now); + *anim |= self.torch.moving(now); + let h = cv.k("height"); + let lp = [p[0] + 80.0, p[1] + 130.0]; + let (a, b) = (cv.px(p), cv.px(lp)); + let axis = [a[0] - b[0], a[1] - b[1], -h * s]; + out.push( + Light::point(b[0], b[1], h * s) + .color(srgbf(1.0, 0.95, 0.88)) + .intensity(cv.k("intensity")) + .radius(cv.k("radius") * s) + .range(1800.0 * s) + .spot(axis, cv.k("beam")) + .specular(1.4) + .scaled(cv.a * k), + ); + let am = cv.k("ambient"); + Settings { + ambient: [am, am * 1.07, am * 1.28], + albedo_floor: 0.04, + text: TextPolicy { floor: 0.32, ceiling: 1.3, lit: 1.0, specular: 0.1 }, + rim: 1.0, + contact_ao: 0.3, + background_gloss: 0.5, + ..Default::default() + } + } + Scene::Gi => { + let b = if cv.reduced { 1.0 } else { 0.775 + 0.225 * (std::f32::consts::TAU * t / 2.2).sin() }; + *anim |= !cv.reduced; + let e = cv.k("emission"); + let rec = self.rec.at(cv.s.recording, t); + let up = self.upload.at(cv.s.uploading, t); + *anim |= self.rec.moving(t) || self.upload.moving(t); + pc.rec = 7.0 * b * rec * e; + pc.status = 2.2 * (0.6 + 0.4 * b) * e; + pc.progress = 1.9 * (0.85 + 0.15 * b) * up * e; + let am = cv.k("ambient"); + Settings { + ambient: [am, am * 1.03, am * 1.17], + gi: cv.on("gi").then_some(Gi { strength: cv.k("strength"), air: cv.k("air"), bounce: cv.k("bounce"), absorption: 0.24, ..Default::default() }), + contact_ao: 0.4, + rim: 0.6, + ..Default::default() + } + } + Scene::Keys => { + let (p, k) = self.keylight.update(cv.pointer, now); + *anim |= self.keylight.moving(now); + pc.keys = cv.s.keys.iter().map(|a| a.sample(now)).collect(); + *anim |= cv.s.keys.iter().any(|a| !a.is_settled(now)); + pc.bevel = cv.k("bevel"); + pc.gloss = cv.k("gloss"); + let q = cv.px(p); + out.push( + Light::point(q[0], q[1], cv.k("height") * s) + .color(srgbf(1.0, 0.93, 0.85)) + .intensity(3.4) + .radius(cv.k("radius") * s) + .range(2200.0 * s) + .specular(2.4) + .scaled(cv.a * k), + ); + if cv.on("fill") { + let q = cv.px([1100.0, 760.0]); + out.push(Light::point(q[0], q[1], 700.0 * s).color(srgbf(0.5, 0.62, 1.0)).intensity(0.4).radius(200.0 * s).range(5000.0 * s).specular(0.6).scaled(cv.a)); + } + Settings { ambient: [0.3, 0.31, 0.34], rim: 1.1, contact_ao: 0.5, ..Default::default() } + } + Scene::GodRays => { + let (p, k) = self.sun.update(cv.pointer, now); + *anim |= self.sun.moving(now); + let q = cv.px(p); + out.push( + Light::point(q[0], q[1], cv.k("height") * s) + .color(srgbf(1.0, 0.8, 0.55)) + .intensity(cv.k("intensity")) + .radius(12.0 * s) + .range(3000.0 * s) + .shafts(cv.k("shafts")) + .softness(cv.k("softness")) + .scaled(cv.a * k), + ); + Settings { ambient: [0.5, 0.5, 0.58], shafts_over: 0.12, rim: 0.8, contact_ao: 0.35, ..Default::default() } + } + _ => Settings::default(), + } + } + + /// Effect layers for an effects canvas, anchored to the nodes they decorate. + pub(super) fn layers(&mut self, cv: &Cv, out: &mut Vec<Lay>, anim: &mut bool) { + let t = cv.t; + let sc = cv.sc; + let mut push = |layer: FxLayer, anchor: Anchor| out.push(Lay { layer: layer.at(t), scene: sc, anchor }); + match sc { + Scene::Glow => { + let (r, i, br, rim, hot) = (cv.k("radius") / 14.0, cv.k("intensity") * cv.a, cv.k("breathe"), cv.k("rim_width"), cv.k("hot")); + let color = cv.swatch(); + push( + Fx::glow(GlowParams { radius: 16.0 * r, intensity: 0.85 * i, breathe: br.max(0.4), breathe_period: 2.6, hot: 0.4 * hot / 0.6, ..Default::default() }) + .on(cv.capsule(stage::GLOW_BTN)), + Anchor::Under(node::GLOW_BUTTON), + ); + let heat = self.neon.at(cv.s.neon_on, t); + *anim |= self.neon.moving(t); + push( + Fx::glow(GlowParams { + style: GlowStyle::Neon, + color: rgb(color), + core: rgb(0xeafcff), + radius: 10.0 * r, + intensity: i, + inner: 0.35, + heat, + hot: (0.9 * hot / 0.6).min(1.0), + rim_width: rim * 0.55 / 0.6, + breathe: br, + ..Default::default() + }) + .on(cv.rounded(stage::NEON, 16.0)) + .over(), + Anchor::Over(node::NEON), + ); + push( + Fx::glow(GlowParams { + style: GlowStyle::Aura, + color: rgb(0xff5fa2), + core: rgb(0x8b5cf6), + third: rgb(0x38bdf8), + radius: 12.0 * r, + intensity: 0.9 * i, + inner: 0.55, + hot: 0.55, + aura_speed: 0.15, + rim_width: rim, + occlusion: 0.1, + ..Default::default() + }) + .on(cv.capsule(stage::AURA)) + .over(), + Anchor::Over(node::AURA), + ); + push( + Fx::glow(GlowParams { + style: GlowStyle::Mask, + color: rgb(0xff8a2a), + core: rgb(0xfff1d6), + radius: 10.0 * r, + intensity: 1.1 * i, + hot: 0.0, + breathe: br.max(0.25), + breathe_period: 3.2, + ..Default::default() + }) + .on(cv.rounded(stage::GLOW_TEXT, 0.0)) + .source(SRC_MASK, cv.viewport), + Anchor::Under(node::GLOW_TEXT), + ); + push( + Fx::glow(GlowParams { color: rgb(0xffa630), core: rgb(0xfff6e0), radius: 9.0 * r, intensity: 1.3 * i, hot: (hot / 0.6).min(1.0), breathe: br, ..Default::default() }) + .on(cv.circle(stage::HOT_DOT)), + Anchor::Under(node::HOT_DOT), + ); + } + Scene::Pulses => { + let (reach, width, period, count, i) = (cv.k("reach"), cv.k("width"), cv.k("period"), cv.k("count").round() as u32, cv.k("intensity") * cv.a); + let color = rgb(cv.swatch()); + push( + Fx::pulse(PulseParams { color, core: rgb(0xffffff), reach: reach * 46.0 / 36.0, width: width * 1.3 / 1.6, period: period * 2.2 / 2.4, count, intensity: i, ..Default::default() }) + .on(cv.circle(stage::RADAR)), + Anchor::Under(node::RADAR), + ); + push( + Fx::pulse(PulseParams { style: PulseStyle::Breathe, color: rgb(0x34d399), core: rgb(0xd1fae5), reach: 12.0, period: 2.8, intensity: 0.8 * i, ..Default::default() }) + .on(cv.circle(stage::AVATAR)), + Anchor::Under(node::AVATAR), + ); + push( + Fx::pulse(PulseParams { style: PulseStyle::Heartbeat, color: rgb(0xff3b6b), core: rgb(0xffe4ec), reach: 26.0, width: 1.1, period: 1.1, intensity: i, ..Default::default() }) + .on(cv.capsule(stage::LIVE)), + Anchor::Under(node::LIVE), + ); + for (shot, k) in cv.s.shots.live(t, 3.0) { + let sh = &shot.data; + let mut push = |layer: FxLayer, anchor: Anchor| push(layer.opacity(k), anchor); + match sh.kind { + ShotKind::Ripple => push( + Fx::pulse(PulseParams { + style: PulseStyle::Ripple { at: cv.w(sh.at) }, + color, + core: rgb(0xffffff), + reach: reach * 6.0, + width: 2.2 * width / 1.6, + t0: sh.t0, + duration: 0.9, + intensity: 0.7 * i, + ..Default::default() + }) + .on(cv.everywhere()) + .over(), + Anchor::Top, + ), + ShotKind::RippleCard => push( + Fx::pulse(PulseParams { style: PulseStyle::Ripple { at: cv.w(sh.at) }, color, core: rgb(0xffffff), reach: 0.0, width: 2.2, t0: sh.t0, duration: 0.9, intensity: 0.7 * i, ..Default::default() }) + .on(cv.rounded(stage::INBOX, 16.0)) + .over(), + Anchor::Over(node::INBOX), + ), + ShotKind::Ping => { + let from = [stage::SEND[0] + stage::SEND[2], stage::SEND[1]]; + let to = [stage::INBOX.x + 6.0, stage::INBOX.y + stage::INBOX.h * 0.5]; + let d = [to[0] - from[0], to[1] - from[1]]; + let len = d[0].hypot(d[1]); + push( + Fx::pulse(PulseParams { + style: PulseStyle::Ping { from: cv.w(from), dir: [d[0] / len, d[1] / len], travel: len }, + color, + core: rgb(0xf0f7ff), + t0: sh.t0, + duration: stage::PING_DURATION, + lag: 0.16, + head_radius: 2.6, + intensity: i, + ..Default::default() + }) + .on(cv.circle(stage::SEND)), + Anchor::Top, + ); + push( + Fx::pulse(PulseParams { + style: PulseStyle::Ripple { at: cv.w(to) }, + color, + core: rgb(0xffffff), + reach: 0.0, + width: 2.2, + t0: sh.t0 + stage::PING_DURATION, + duration: 0.9, + intensity: 0.7 * i, + ..Default::default() + }) + .on(cv.rounded(stage::INBOX, 16.0)) + .over(), + Anchor::Over(node::INBOX), + ); + } + _ => {} + } + } + } + Scene::Electric => { + let (amp, fq, sp, gl, fk) = (cv.k("amplitude"), cv.k("frequency"), cv.k("speed"), cv.k("glow"), cv.k("forks")); + let color = rgb(cv.swatch()); + let (a, b) = (cv.w([stage::ARC_A[0] + 6.0, stage::ARC_A[1]]), cv.w([stage::ARC_B[0] - 6.0, stage::ARC_B[1]])); + push( + Fx::electric(ElectricParams { + style: ElectricStyle::Arc { a, b }, + color, + amplitude: amp * 9.0 / 5.0, + frequency: fq, + speed: sp, + glow: gl * 6.0 / 5.0, + forks: (fk * 0.6 / 0.55).min(1.0), + strands: 3, + intensity: cv.a, + ..Default::default() + }) + .on(Shape::rounded(a[0], a[1] - 1.0, b[0] - a[0], 2.0, 0.0)), + Anchor::Under(node::TERMINALS), + ); + for (shot, k) in cv.s.shots.live(t, ElectricParams::ZAP_LIFE).filter(|(sh, _)| sh.data.kind == ShotKind::Zap) { + let to = cv.w(shot.data.at); + let from = if (to[0] - a[0]).hypot(to[1] - a[1]) < (to[0] - b[0]).hypot(to[1] - b[1]) { a } else { b }; + push( + Fx::electric(ElectricParams { + style: ElectricStyle::Arc { a: from, b: to }, + color, + amplitude: amp * 9.0 / 5.0, + frequency: fq, + glow: gl * 6.0 / 5.0, + forks: (fk * 0.6 / 0.55).min(1.0), + intensity: cv.a, + zap: Some(shot.t0), + ..Default::default() + }) + .on(Shape::rounded(from[0].min(to[0]), from[1].min(to[1]), (to[0] - from[0]).abs().max(1.0), (to[1] - from[1]).abs().max(1.0), 0.0)) + .seed(shot.seed) + .opacity(k), + Anchor::Top, + ); + } + push( + Fx::electric(ElectricParams { color, amplitude: amp * 0.8, frequency: fq, speed: sp, glow: gl, forks: fk, gap: 3.0, fork_len: 22.0, intensity: cv.a, ..Default::default() }) + .on(cv.rounded(stage::OVERLOAD, 18.0)) + .seed(7), + Anchor::Over(node::OVERLOAD), + ); + let hovered = cv.pointer.is_some_and(|p| { + let r = stage::CHARGED; + p[0] >= r.x && p[0] <= r.x + r.w && p[1] >= r.y && p[1] <= r.y + r.h + }); + let heat = self.charged.at(hovered, t); + *anim |= self.charged.moving(t); + if heat > 0.002 { + let base = ElectricParams::charged(); + push( + Fx::electric(ElectricParams { color, intensity: base.intensity * heat * cv.a, glow: base.glow * (0.6 + 0.4 * heat), ..base }) + .on(cv.capsule(stage::CHARGED)) + .seed(3), + Anchor::Over(node::CHARGED), + ); + } + } + Scene::Fire => { + let i = cv.k("intensity") * cv.a; + push( + Fx::fire(FireParams { + height: cv.k("height"), + scale: cv.k("scale"), + speed: cv.k("speed"), + embers: cv.k("embers").round() as u32, + intensity: i, + swirl: cv.k("swirl"), + ..Default::default() + }) + .on(cv.rounded(stage::FLAMES, 18.0)) + .seed(5), + Anchor::Under(node::FLAMES), + ); + let pl = FireParams::plasma(); + push(Fx::fire(FireParams { intensity: pl.intensity * i, speed: pl.speed * cv.k("speed") / 1.5, ..pl }).on(cv.capsule(stage::PLASMA)).seed(11), Anchor::Under(node::PLASMA)); + let ht = FireParams::heat(); + push(Fx::fire(FireParams { intensity: ht.intensity * i, ..ht }).on(cv.capsule(stage::DEPLOY)).seed(2), Anchor::Under(node::DEPLOY)); + push( + Fx::distort(DistortParams::HeatHaze { height: 26.0, scale: 9.0, speed: 2.0, amount: 1.1 * cv.a, whole_shape: false }).on(cv.capsule(stage::DEPLOY)), + Anchor::Over(node::DEPLOY), + ); + } + Scene::Lens => { + let now = cv.now; + let target = Vec2 { x: cv.s.lens[0] + 128.0, y: cv.s.lens[1] + 8.0 }; + let d = self.droplet.get_or_insert_with(|| Animated::new(target)); + d.animate_to(target, Spring::new(0.5, 0.0), now); + *anim |= !d.is_settled(now); + let dp = d.sample(now); + for (shot, k) in cv.s.shots.live(t, 3.0).filter(|(sh, _)| sh.data.kind == ShotKind::Shockwave) { + let sh = &shot.data; + push( + Fx::distort(DistortParams::shockwave(cv.w(sh.at), sh.t0)).on(cv.everywhere()).opacity(k), + Anchor::Top, + ); + } + if cv.on("crt") { + push(Fx::distort(DistortParams::crt()).on(cv.rounded(stage::CRT, 14.0)), Anchor::Over(node::CRT)); + } + push( + Fx::distort(DistortParams::ChromaSplit { offset: [1.6, 0.0], glitch: 0.3, feather: 2.0 }).on(cv.rounded(stage::CHROMA, 6.0)), + Anchor::Over(node::CHROMA), + ); + let q = cv.w([dp.x, dp.y]); + push( + Fx::lens(LensParams { + depth: cv.k("depth"), + bevel: cv.k("bevel"), + dispersion: cv.k("dispersion"), + magnification: cv.k("magnification"), + frost: cv.k("frost"), + presence: cv.a, + second: Some(Shape::circle(q[0], q[1], 26.0)), + union_k: 26.0, + ..Default::default() + }) + .on(cv.capsule(stage::lens_rect(cv.s.lens))), + Anchor::Top, + ); + } + Scene::Extras => { + if cv.on("shimmer") { + push( + Fx::shimmer(ShimmerParams { intensity: 0.11 * cv.a, band: 42.0, use_mask: true, ..Default::default() }) + .on(cv.rounded(stage::SKELETON, 16.0)) + .source(SRC_MASK, cv.viewport), + Anchor::Over(node::SKELETON), + ); + push( + Fx::shimmer(ShimmerParams { intensity: 0.85 * cv.a, band: 18.0, period: 1.6, angle: 0.25, use_mask: true, ..Default::default() }) + .on(cv.rounded(stage::THINKING, 0.0)) + .source(SRC_MASK, cv.viewport), + Anchor::Over(node::THINKING), + ); + } + if cv.on("aurora") { + push( + Fx::aurora(AuroraParams { intensity: 0.75 * cv.a, scale: 110.0, feather: 18.0, speed: cv.k("speed"), ..Default::default() }) + .on(cv.rounded(stage::AURORA, 18.0)) + .over(), + Anchor::Over(node::AURORA), + ); + } + if cv.on("grain") { + push(Fx::grain(GrainParams { amount: 0.016 * cv.a, ..Default::default() }).on(cv.rounded(stage::AURORA, 18.0)), Anchor::Over(node::AURORA)); + } + if cv.on("sparkles") { + push( + Fx::sparkles(SparkleParams { margin: 20.0, size: 8.0, count: 6, intensity: cv.a, ..Default::default() }).on(cv.capsule(stage::PRO)).seed(4), + Anchor::Over(node::PRO), + ); + } + let burst = SparkleParams { margin: 34.0, size: 9.0, count: 8, intensity: cv.a, ..Default::default() }; + for (shot, k) in cv.s.shots.live(t, burst.burst_life()).filter(|(sh, _)| sh.data.kind == ShotKind::Sparkles) { + push( + Fx::sparkles(SparkleParams { burst: Some(shot.t0), ..burst }).on(cv.capsule(stage::PRO)).seed(shot.seed).opacity(k), + Anchor::Over(node::PRO), + ); + } + } + _ => {} + } + } +} diff --git a/app/vendor/rune/examples/lab/src/knobs.rs b/app/vendor/rune/examples/lab/src/knobs.rs new file mode 100644 index 0000000..e7f5039 --- /dev/null +++ b/app/vendor/rune/examples/lab/src/knobs.rs @@ -0,0 +1,223 @@ +//! Scenes and their knobs. Effect knobs take their range and default from the effect's typed +//! params (`GlowParams::KNOBS`, …); lighting knobs are declared here. + +use std::sync::OnceLock; + +use rune_fx::{ElectricParams, FireParams, GlowParams, Knob, MotionBlurParams, PulseParams}; + +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub enum Scene { + Lamp, + Flashlight, + Gi, + Keys, + GodRays, + Glow, + Pulses, + Electric, + Fire, + Motion, + Lens, + Extras, +} + +pub const ALL: [Scene; 12] = [ + Scene::Lamp, + Scene::Flashlight, + Scene::Gi, + Scene::Keys, + Scene::GodRays, + Scene::Glow, + Scene::Pulses, + Scene::Electric, + Scene::Fire, + Scene::Motion, + Scene::Lens, + Scene::Extras, +]; + +impl Scene { + pub const fn idx(self) -> usize { + self as usize + } + + /// Lit by rune-light (the others composite rune-fx layers). + pub fn lit(self) -> bool { + self.idx() < 5 + } + + fn meta(self) -> (&'static str, &'static str, &'static str) { + match self { + Scene::Lamp => ("lamp", "Lamp", "Drag the lamp. Every bubble casts a soft shadow from the analytic field."), + Scene::Flashlight => ("flashlight", "Flashlight", "Move the pointer. The torch is held low and to the right, so shadows swing."), + Scene::Gi => ("gi", "Emissive light", "Glowing elements light their neighbours. Click the record button or the progress bar."), + Scene::Keys => ("keys", "Raised keys", "Move the pointer to sweep the light. Press a key."), + Scene::GodRays => ("godrays", "God rays", "Move the pointer. The light sits behind the grid and shines through the gaps."), + Scene::Glow => ("glow", "Glow", "Click the neon card to switch it off: lights cool, never cut."), + Scene::Pulses => ("pulses", "Pulses", "Click anywhere for a ripple. Press send to ping the inbox."), + Scene::Electric => ("electric", "Electricity", "Hover the charged button."), + Scene::Fire => ("fire", "Fire", "Flames, a plasma border and heat haze over a button."), + Scene::Motion => ("motion", "Motion blur", "Drag the card and fling it. It glides on a spring with shutter blur."), + Scene::Lens => ("lens", "Liquid glass", "Drag the glass over the page. Click anywhere for a shockwave."), + Scene::Extras => ("extras", "Extras", "Shimmer, sparkles, aurora and grain."), + } + } + + pub fn id(self) -> &'static str { self.meta().0 } + pub fn title(self) -> &'static str { self.meta().1 } + pub fn hint(self) -> &'static str { self.meta().2 } +} + +#[derive(Clone, Copy, Debug)] +pub enum Kind { + /// Decimal places shown. + Slider(u8), + Toggle, + /// sRGB hex colours; the value is the index. + Swatch(&'static [u32]), +} + +#[derive(Clone, Copy, Debug)] +pub struct KnobSpec { + pub id: &'static str, + pub label: &'static str, + pub min: f32, + pub max: f32, + pub default: f32, + pub kind: Kind, +} + +pub const FX_COLORS: &[u32] = &[0x22d3ee, 0x8b5cf6, 0xff5fa2, 0xff8a2a, 0x34d399, 0x60a5fa]; +pub const LAMP_COLORS: &[u32] = &[0xffc78c, 0xff9a4d, 0xfff3e6, 0xb3ccff, 0xff8fb0, 0x9dffd0]; + +fn sl(id: &'static str, label: &'static str, min: f32, max: f32, default: f32, dec: u8) -> KnobSpec { + KnobSpec { id, label, min, max, default, kind: Kind::Slider(dec) } +} + +fn tg(id: &'static str, label: &'static str, on: bool) -> KnobSpec { + KnobSpec { id, label, min: 0.0, max: 1.0, default: if on { 1.0 } else { 0.0 }, kind: Kind::Toggle } +} + +fn sw(id: &'static str, label: &'static str, palette: &'static [u32]) -> KnobSpec { + KnobSpec { id, label, min: 0.0, max: (palette.len() - 1) as f32, default: 0.0, kind: Kind::Swatch(palette) } +} + +/// A slider over an effect's own knob: its range and default come from the typed params. +fn fx(knobs: &'static [Knob], name: &'static str, label: &'static str, dec: u8) -> KnobSpec { + let k = knobs.iter().find(|k| k.name == name).unwrap_or_else(|| panic!("no knob {name}")); + KnobSpec { id: k.name, label, min: k.min, max: k.max, default: k.default, kind: Kind::Slider(dec) } +} + +pub fn specs(scene: Scene) -> &'static [KnobSpec] { + static ALL_SPECS: OnceLock<Vec<Vec<KnobSpec>>> = OnceLock::new(); + &ALL_SPECS.get_or_init(|| ALL.iter().map(|s| build(*s)).collect())[scene.idx()] +} + +fn build(scene: Scene) -> Vec<KnobSpec> { + let g = GlowParams::KNOBS; + let p = PulseParams::KNOBS; + let e = ElectricParams::KNOBS; + let f = FireParams::KNOBS; + let m = MotionBlurParams::KNOBS; + match scene { + Scene::Lamp => vec![ + sl("height", "Lamp height", 10.0, 240.0, 40.0, 0), + sl("radius", "Source size", 2.0, 40.0, 11.0, 0), + sl("intensity", "Intensity", 0.0, 6.0, 2.6, 1), + sw("color", "Colour", LAMP_COLORS), + tg("fill", "Fill light", true), + tg("bounce", "Bounce light (GI)", false), + ], + Scene::Flashlight => vec![ + sl("beam", "Beam angle", 0.2, 1.2, 0.58, 2), + sl("height", "Torch height", 60.0, 420.0, 260.0, 0), + sl("radius", "Source size", 2.0, 30.0, 9.0, 0), + sl("intensity", "Intensity", 0.0, 14.0, 7.0, 1), + sl("ambient", "Ambient", 0.0, 0.4, 0.07, 2), + ], + Scene::Gi => vec![ + tg("gi", "Global illumination", true), + sl("strength", "GI strength", 0.0, 3.0, 1.0, 2), + sl("air", "Air scatter", 0.0, 0.3, 0.09, 2), + sl("bounce", "Bounce", 0.0, 1.0, 0.0, 2), + sl("emission", "Emission", 0.0, 3.0, 1.0, 2), + sl("ambient", "Ambient", 0.0, 1.0, 0.3, 2), + ], + Scene::Keys => vec![ + sl("height", "Light height", 30.0, 400.0, 150.0, 0), + sl("radius", "Source size", 4.0, 60.0, 26.0, 0), + sl("bevel", "Bevel", 0.3, 2.0, 1.0, 2), + sl("gloss", "Gloss", 0.0, 1.0, 0.85, 2), + tg("fill", "Fill light", true), + ], + Scene::GodRays => vec![ + sl("shafts", "Shafts", 0.0, 3.0, 1.5, 2), + sl("intensity", "Intensity", 0.0, 4.0, 1.6, 2), + sl("softness", "Softness", 0.5, 4.0, 2.2, 2), + sl("height", "Light height", 1.0, 40.0, 4.0, 0), + ], + Scene::Glow => vec![ + fx(g, "radius", "Radius", 0), + fx(g, "intensity", "Intensity", 2), + fx(g, "breathe", "Breathe", 2), + fx(g, "rim_width", "Rim width", 2), + fx(g, "hot", "Hot core", 2), + sw("color", "Neon colour", FX_COLORS), + ], + Scene::Pulses => vec![ + fx(p, "reach", "Reach", 0), + fx(p, "width", "Ring width", 1), + fx(p, "period", "Period", 1), + fx(p, "count", "Rings", 0), + fx(p, "intensity", "Intensity", 2), + sw("color", "Colour", FX_COLORS), + ], + Scene::Electric => vec![ + fx(e, "amplitude", "Amplitude", 1), + fx(e, "frequency", "Frequency", 1), + fx(e, "speed", "Speed", 1), + fx(e, "glow", "Glow", 1), + fx(e, "forks", "Forks", 2), + sw("color", "Colour", FX_COLORS), + ], + Scene::Fire => vec![ + fx(f, "height", "Flame height", 0), + fx(f, "scale", "Scale", 0), + fx(f, "speed", "Speed", 2), + fx(f, "embers", "Embers", 0), + fx(f, "intensity", "Intensity", 2), + fx(f, "swirl", "Swirl", 2), + ], + Scene::Motion => vec![ + fx(m, "shutter_angle", "Shutter angle", 0), + sl("glide", "Glide duration", 0.3, 1.4, 0.6, 2), + tg("smooth", "Soft shutter ends", true), + tg("directional", "Directional fallback", false), + ], + Scene::Lens => vec![ + sl("depth", "Depth", 0.0, 40.0, 16.0, 0), + sl("bevel", "Bevel", 2.0, 40.0, 14.0, 0), + sl("dispersion", "Dispersion", 0.0, 0.5, 0.14, 2), + sl("magnification", "Magnification", 0.9, 1.3, 1.04, 2), + sl("frost", "Frost", 0.0, 1.0, 0.0, 2), + tg("crt", "CRT terminal", true), + ], + Scene::Extras => vec![ + tg("shimmer", "Shimmer", true), + tg("aurora", "Aurora", true), + tg("grain", "Grain", true), + tg("sparkles", "Sparkles", true), + sl("speed", "Aurora speed", 0.0, 1.0, 0.25, 2), + ], + } +} + +pub fn defaults() -> Vec<Vec<f32>> { + ALL.iter().map(|s| specs(*s).iter().map(|k| k.default).collect()).collect() +} + +/// Linear RGB of an sRGB hex colour. +pub fn lin(hex: u32) -> [f32; 3] { + let f = |c: u32| rune::color::srgb_decode(c as f32 / 255.0); + [f((hex >> 16) & 255), f((hex >> 8) & 255), f(hex & 255)] +} diff --git a/app/vendor/rune/examples/lab/src/main.rs b/app/vendor/rune/examples/lab/src/main.rs new file mode 100644 index 0000000..0e8477a --- /dev/null +++ b/app/vendor/rune/examples/lab/src/main.rs @@ -0,0 +1,193 @@ +//! Rune Lab: rune-light and rune-fx composited live inside Rune's renderer, with knobs. + +#![forbid(unsafe_code)] + +mod gfx; +mod knobs; +mod stage; +mod ui; + +use knobs::{ALL, Scene, specs}; +use rune::{AppSpec, Key, KeyEvent, Modifier, Tx}; +use rune_motion::{Animated, Spring, Vec2, VelocityTracker}; + +/// What the pointer is holding on the stage. +#[derive(Clone, Copy, Debug)] +pub enum Grab { + Lamp([f32; 2]), + Card([f32; 2]), + Lens([f32; 2]), + Key(usize), +} + +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum ShotKind { + /// A ripple across the whole canvas. + Ripple, + /// A ripple confined to the inbox card. + RippleCard, + /// The send button's ping to the inbox (which ripples on arrival). + Ping, + Shockwave, + /// A lightning strike from the nearer electrode to the click. + Zap, + /// A burst of sparkles off the PRO badge. + Sparkles, +} + +#[derive(Clone, Copy, Debug)] +pub struct Shot { + pub kind: ShotKind, + /// Canvas points. + pub at: [f32; 2], + pub t0: f32, +} + +#[derive(Clone, Copy, Debug, Default)] +pub struct Perf { + pub cpu_ms: f32, + pub gpu_ms: Option<f32>, + pub draws: u32, + pub live: bool, +} + +pub struct Lab { + pub scene: Scene, + pub reduced: bool, + pub vals: Vec<Vec<f32>>, + /// Rune's animation clock at the last drawn frame (handlers stamp one-shots with it). + pub now: f64, + pub perf: Perf, + pub lamp: [f32; 2], + pub keys: Vec<Animated<f32>>, + pub recording: bool, + pub uploading: bool, + pub neon_on: bool, + /// Taps, pings and shockwaves: each overlaps the ones still running (a bounded pool). + pub shots: rune_fx::OneShots<Shot>, + /// The motion card's top-left in canvas points. + pub card: Animated<Vec2>, + pub card_vt: VelocityTracker<Vec2>, + pub lens: [f32; 2], + pub grab: Option<Grab>, +} + +impl Lab { + fn new() -> Lab { + Lab { + scene: Scene::Lamp, + reduced: false, + vals: knobs::defaults(), + now: 0.0, + perf: Perf::default(), + lamp: stage::LAMP_REST, + keys: (0..stage::KEY_COUNT).map(|_| Animated::new(0.0f32)).collect(), + recording: true, + uploading: true, + neon_on: true, + shots: rune_fx::OneShots::new(8), + card: Animated::new(Vec2 { x: stage::CARD_REST[0], y: stage::CARD_REST[1] }), + card_vt: VelocityTracker::new(), + lens: stage::LENS_REST, + grab: None, + } + } + + /// The current value of `scene`'s knob `id`. + pub fn k(&self, scene: Scene, id: &str) -> f32 { + let i = specs(scene).iter().position(|k| k.id == id).unwrap_or_else(|| panic!("no knob {id} in {scene:?}")); + self.vals[scene.idx()][i] + } + + pub fn on(&self, scene: Scene, id: &str) -> bool { + self.k(scene, id) > 0.5 + } + + fn select(&mut self, scene: Scene) { + if self.scene != scene { + self.scene = scene; + self.grab = None; + } + } +} + +fn on_key(s: &mut Lab, e: &KeyEvent, _tx: &mut Tx) -> bool { + let i = s.scene.idx(); + match e.key { + Key::Up => s.select(ALL[(i + ALL.len() - 1) % ALL.len()]), + Key::Down => s.select(ALL[(i + 1) % ALL.len()]), + // Modifier keys alone play the bottom row of the Keys scene, each side its own key. + Key::Modifier { modifier, pressed } if s.scene == Scene::Keys => { + let Some(key) = modifier_pad(modifier) else { return false }; + let (to, spring) = if pressed { (1.0, Spring::new(0.1, 0.0)) } else { (0.0, Spring::new(0.25, 0.0)) }; + s.keys[key].animate_to(to, spring, s.now); + } + _ => return false, + } + true +} + +fn modifier_pad(modifier: Modifier) -> Option<usize> { + let row = stage::KEY_COLS; + Some(row + match modifier { + Modifier::ShiftLeft => 0, + Modifier::Fn => 1, + Modifier::ControlLeft => 2, + Modifier::AltLeft => 3, + Modifier::SuperLeft => 4, + Modifier::SuperRight => 5, + Modifier::AltRight => 6, + Modifier::ControlRight => 7, + Modifier::ShiftRight => 9, + _ => return None, + }) +} + +/// A throw already in flight at t = 0, for snapshots without a script. +fn thrown(s: &mut Lab) { + s.scene = Scene::Motion; + s.card.set(Vec2 { x: -60.0, y: 300.0 }); + s.card.release(Vec2 { x: 2400.0, y: -900.0 }, Vec2 { x: 470.0, y: 160.0 }, Spring::new(0.6, 0.0), 0.0); +} + +fn main() { + let app = rune::App::new( + AppSpec::<Lab> { + min_size: Some((1080.0, 640.0)), + scenes: &[ + ("lamp", |s| s.scene = Scene::Lamp), + ("flashlight", |s| s.scene = Scene::Flashlight), + ("gi", |s| s.scene = Scene::Gi), + ("keys", |s| s.scene = Scene::Keys), + ("godrays", |s| s.scene = Scene::GodRays), + ("glow", |s| s.scene = Scene::Glow), + ("pulses", |s| s.scene = Scene::Pulses), + ("electric", |s| s.scene = Scene::Electric), + ("fire", |s| s.scene = Scene::Fire), + ("motion", |s| s.scene = Scene::Motion), + ("lens", |s| s.scene = Scene::Lens), + ("lens-frost", |s| { + s.scene = Scene::Lens; + let i = specs(Scene::Lens).iter().position(|k| k.id == "frost").unwrap(); + s.vals[Scene::Lens.idx()][i] = 1.0; + }), + ("extras", |s| s.scene = Scene::Extras), + ("motion-thrown", thrown), + ("fire-reduced", |s| { + s.scene = Scene::Fire; + s.reduced = true; + }), + ], + fonts: &[ + include_bytes!("../../../crates/rune/assets/Inter-Regular.ttf"), + include_bytes!("../../../crates/rune/assets/Inter-Medium.ttf"), + include_bytes!("../../../crates/rune/assets/Inter-SemiBold.ttf"), + include_bytes!("../../../themes/opencode/assets/fonts/IBMPlexMono-Medium.ttf"), + ], + families: ("Inter", "IBM Plex Mono"), + on_key: Some(on_key), + ..AppSpec::new("Rune Lab", (1320.0, 800.0), Lab::new, ui::view) + }, + ).compositor(gfx::LabGfx::default()).modifier_keys(); + app.run(); +} diff --git a/app/vendor/rune/examples/lab/src/stage.rs b/app/vendor/rune/examples/lab/src/stage.rs new file mode 100644 index 0000000..ada53c9 --- /dev/null +++ b/app/vendor/rune/examples/lab/src/stage.rs @@ -0,0 +1,750 @@ +//! The stage: one canvas of Rune elements per scene, laid out in canvas points, plus the +//! stage's pointer handling. Marks tell the compositor what each element is: which canvas it +//! belongs to, its lighting material, and the effect node it anchors. + +use rune::color::{Color, oklch, oklcha}; +use rune::{Drag, El, Phase, Tx, TextStyle, el, text}; +use rune_fx::Rect; +use rune_motion::{Spring, Vec2}; + +use crate::knobs::Scene; +use crate::{Grab, Lab, Shot, ShotKind}; + +pub const CW: f32 = 780.0; +pub const CH: f32 = 600.0; + +// ---------------------------------------------------------------- marks + +/// The stage's own background (not in any canvas). +pub const STAGE_MARK: u32 = 0xFE << 24; + +pub fn mk(scene: Scene, material: u8, node: u8) -> u32 { + ((scene.idx() as u32 + 1) << 24) | ((node as u32) << 8) | material as u32 +} + +pub fn mark_scene(m: u32) -> Option<Scene> { + let i = (m >> 24) as usize; + (1..=crate::knobs::ALL.len()).contains(&i).then(|| crate::knobs::ALL[i - 1]) +} + +pub fn mark_material(m: u32) -> u8 { + (m & 0xFF) as u8 +} + +pub fn mark_node(m: u32) -> u8 { + ((m >> 8) & 0xFF) as u8 +} + +/// Lighting materials (how a marked rect stands on the UI plane). +pub mod mat { + pub const CARD: u8 = 1; + pub const CHIP: u8 = 2; + pub const BUTTON: u8 = 3; + pub const KNOB: u8 = 4; + pub const KEY: u8 = 5; + pub const BODY: u8 = 6; + pub const SCREEN: u8 = 7; + pub const EMIT: u8 = 8; + pub const TILE: u8 = 9; + pub const SWITCH: u8 = 10; + pub const ON_CARD: u8 = 11; + pub const BAR: u8 = 12; + pub const PILL: u8 = 13; + pub const DIAL: u8 = 14; + pub const COMPOSER: u8 = 15; + pub const FLAT: u8 = 16; +} + +/// Effect anchors. +pub mod node { + pub const LAMP: u8 = 1; + pub const GLOW_BUTTON: u8 = 2; + pub const NEON: u8 = 3; + pub const AURA: u8 = 4; + pub const GLOW_TEXT: u8 = 5; + pub const HOT_DOT: u8 = 6; + pub const RADAR: u8 = 7; + pub const AVATAR: u8 = 8; + pub const LIVE: u8 = 9; + pub const SEND: u8 = 10; + pub const INBOX: u8 = 11; + pub const TERMINALS: u8 = 12; + pub const OVERLOAD: u8 = 14; + pub const CHARGED: u8 = 15; + pub const FLAMES: u8 = 16; + pub const PLASMA: u8 = 17; + pub const DEPLOY: u8 = 18; + pub const CARD: u8 = 19; + pub const CRT: u8 = 20; + pub const CHROMA: u8 = 21; + pub const SKELETON: u8 = 22; + pub const THINKING: u8 = 23; + pub const AURORA: u8 = 24; + pub const PRO: u8 = 25; + pub const REC: u8 = 26; + pub const PROGRESS: u8 = 27; + pub const STATUS: u8 = 28; + pub const PAGE: u8 = 29; + /// Keys are `KEY0 + index`. + pub const KEY0: u8 = 100; +} + +// ---------------------------------------------------------------- layout (canvas points) + +pub const LAMP_REST: [f32; 2] = [690.0, 196.0]; + +pub const GLOW_BTN: Rect = Rect::new(70.0, 110.0, 180.0, 52.0); +pub const NEON: Rect = Rect::new(320.0, 84.0, 190.0, 116.0); +pub const HOT_DOT: [f32; 3] = [592.0, 132.0, 8.0]; +pub const AURA: Rect = Rect::new(70.0, 300.0, 360.0, 56.0); +pub const GLOW_TEXT: Rect = Rect::new(496.0, 270.0, 220.0, 100.0); + +pub const RADAR: [f32; 3] = [110.0, 140.0, 20.0]; +pub const AVATAR: [f32; 3] = [290.0, 140.0, 26.0]; +pub const LIVE: Rect = Rect::new(430.0, 124.0, 88.0, 32.0); +pub const SEND: [f32; 3] = [100.0, 390.0, 20.0]; +pub const INBOX: Rect = Rect::new(530.0, 332.0, 190.0, 116.0); +pub const PING_DURATION: f32 = 0.62; + +pub const ARC_A: [f32; 2] = [70.0, 120.0]; +pub const ARC_B: [f32; 2] = [710.0, 120.0]; +pub const OVERLOAD: Rect = Rect::new(70.0, 230.0, 290.0, 160.0); +pub const CHARGED: Rect = Rect::new(450.0, 280.0, 240.0, 60.0); + +pub const FLAMES: Rect = Rect::new(80.0, 320.0, 270.0, 150.0); +pub const PLASMA: Rect = Rect::new(430.0, 150.0, 270.0, 66.0); +pub const DEPLOY: Rect = Rect::new(475.0, 360.0, 180.0, 52.0); + +pub const CARD_SIZE: [f32; 2] = [156.0, 92.0]; +pub const CARD_REST: [f32; 2] = [312.0, 254.0]; + +pub const LENS_SIZE: [f32; 2] = [220.0, 72.0]; +pub const LENS_REST: [f32; 2] = [230.0, 204.0]; +pub const CRT: Rect = Rect::new(40.0, 330.0, 300.0, 140.0); +pub const CHROMA: Rect = Rect::new(372.0, 356.0, 360.0, 76.0); + +pub const SKELETON: Rect = Rect::new(40.0, 70.0, 330.0, 216.0); +pub const THINKING: Rect = Rect::new(34.0, 330.0, 150.0, 44.0); +pub const AURORA: Rect = Rect::new(420.0, 70.0, 310.0, 186.0); +pub const PRO: Rect = Rect::new(524.0, 336.0, 104.0, 40.0); + +pub const REC: [f32; 3] = [390.0, 318.0, 30.0]; +pub const PROGRESS: Rect = Rect::new(20.0, 430.0, 740.0, 10.0); + +pub const KEY_COLS: usize = 10; +pub const KEY_COUNT: usize = 20; + +pub fn key_rect(i: usize) -> Rect { + let (r, c) = (i / KEY_COLS, i % KEY_COLS); + Rect::new(40.0 + c as f32 * 71.0, 300.0 + r as f32 * 106.0, 62.0, 88.0) +} + +fn accent_key(i: usize) -> bool { + matches!(i, 2 | 7 | 18) +} + +pub fn lens_rect(c: [f32; 2]) -> Rect { + Rect::new(c[0] - LENS_SIZE[0] * 0.5, c[1] - LENS_SIZE[1] * 0.5, LENS_SIZE[0], LENS_SIZE[1]) +} + +fn inside(r: Rect, p: [f32; 2], pad: f32) -> bool { + p[0] >= r.x - pad && p[0] <= r.x + r.w + pad && p[1] >= r.y - pad && p[1] <= r.y + r.h + pad +} + +fn near(c: [f32; 2], p: [f32; 2], r: f32) -> bool { + (c[0] - p[0]).hypot(c[1] - p[1]) <= r +} + +/// Background colour behind each scene's canvas. +pub fn backdrop(scene: Scene) -> Color { + match scene { + Scene::Lamp => oklch(0.17, 0.006, 265.0), + Scene::Flashlight => oklch(0.16, 0.005, 265.0), + Scene::Gi => oklch(0.15, 0.006, 265.0), + Scene::Keys => oklch(0.18, 0.004, 265.0), + Scene::GodRays => oklch(0.11, 0.014, 265.0), + _ => oklch(0.145, 0.006, 265.0), + } +} + +// ---------------------------------------------------------------- input + +/// Every stage gesture: lamp, keys, emitters, ripples, the card, the lens. +pub fn on_stage(s: &mut Lab, d: &mut Drag, tx: &mut Tx) { + let p = [d.x - (d.w - CW) * 0.5, d.y - (d.h - CH) * 0.5]; + let now = s.now; + let t = now as f32; + match d.phase { + Phase::Down => { + s.grab = None; + match s.scene { + Scene::Lamp if near(s.lamp, p, 30.0) => s.grab = Some(Grab::Lamp([p[0] - s.lamp[0], p[1] - s.lamp[1]])), + Scene::Keys => { + if let Some(i) = (0..KEY_COUNT).find(|&i| inside(key_rect(i), p, 0.0)) { + s.keys[i].animate_to(1.0, Spring::new(0.1, 0.0), now); + s.grab = Some(Grab::Key(i)); + } + } + Scene::Gi => { + if near([REC[0], REC[1]], p, REC[2] + 20.0) { + s.recording = !s.recording; + } else if inside(PROGRESS, p, 10.0) { + s.uploading = !s.uploading; + } + } + Scene::Glow if inside(NEON, p, 0.0) => s.neon_on = !s.neon_on, + Scene::Pulses => { + let shot = if near([SEND[0], SEND[1]], p, SEND[2] + 4.0) { + Shot { kind: ShotKind::Ping, at: [SEND[0], SEND[1]], t0: t } + } else if inside(INBOX, p, 0.0) { + Shot { kind: ShotKind::RippleCard, at: p, t0: t } + } else { + Shot { kind: ShotKind::Ripple, at: p, t0: t } + }; + s.shots.prune(t, 3.0); + s.shots.trigger(t, shot); + } + Scene::Motion => { + let c = s.card.sample(now); + if inside(Rect::new(c.x, c.y, CARD_SIZE[0], CARD_SIZE[1]), p, 6.0) { + s.grab = Some(Grab::Card([p[0] - c.x, p[1] - c.y])); + // Catching it mid-glide holds it where it is. + s.card.set(c); + s.card_vt.reset(); + s.card_vt.add(now, c); + tx.instant(); + } + } + Scene::Electric if !inside(CHARGED, p, 0.0) => { + s.shots.prune(t, 3.0); + s.shots.trigger(t, Shot { kind: ShotKind::Zap, at: p, t0: t }); + } + Scene::Extras if inside(PRO, p, 8.0) => { + s.shots.prune(t, 3.0); + s.shots.trigger(t, Shot { kind: ShotKind::Sparkles, at: p, t0: t }); + } + Scene::Lens => { + if inside(lens_rect(s.lens), p, 4.0) { + s.grab = Some(Grab::Lens([p[0] - s.lens[0], p[1] - s.lens[1]])); + } else { + s.shots.prune(t, 3.0); + s.shots.trigger(t, Shot { kind: ShotKind::Shockwave, at: p, t0: t }); + } + } + _ => {} + } + } + Phase::Move => match s.grab { + Some(Grab::Lamp(o)) => { + s.lamp = [(p[0] - o[0]).clamp(0.0, CW), (p[1] - o[1]).clamp(0.0, CH)]; + tx.instant(); + } + Some(Grab::Card(o)) => { + let c = Vec2 { x: p[0] - o[0], y: p[1] - o[1] }; + s.card.set(c); + s.card_vt.add(now, c); + tx.instant(); + } + Some(Grab::Lens(o)) => { + s.lens = [(p[0] - o[0]).clamp(0.0, CW), (p[1] - o[1]).clamp(0.0, CH)]; + tx.instant(); + } + _ => {} + }, + Phase::Up => { + if d.cancelled() { + let start = [d.start_x - (d.w - CW) * 0.5, d.start_y - (d.h - CH) * 0.5]; + match s.grab { + Some(Grab::Lamp(o)) => s.lamp = [start[0] - o[0], start[1] - o[1]], + Some(Grab::Lens(o)) => s.lens = [start[0] - o[0], start[1] - o[1]], + Some(Grab::Card(o)) => { s.card.set(Vec2::new(start[0] - o[0], start[1] - o[1])); s.card_vt.reset(); } + Some(Grab::Key(i)) => s.keys[i].animate_to(0.0, Spring::new(0.25, 0.0), now), + _ => {} + } + s.grab = None; + return; + } + match s.grab { + Some(Grab::Key(i)) => s.keys[i].animate_to(0.0, Spring::new(0.25, 0.0), now), + Some(Grab::Card(_)) => { + // Fling: project where the throw would coast to, keep it on the canvas, and + // glide there on a zero-bounce spring that starts at the release velocity. + let v = s.card_vt.velocity(); + let c = s.card.sample(now); + let rate = rune_motion::deceleration::NORMAL; + let tx_ = rune_motion::project(c.x, v.x, rate).clamp(0.0, CW - CARD_SIZE[0]); + let ty_ = rune_motion::project(c.y, v.y, rate).clamp(0.0, CH - CARD_SIZE[1]); + let glide = s.k(Scene::Motion, "glide"); + s.card.release(v, Vec2 { x: tx_, y: ty_ }, Spring::new(glide, 0.0), now); + tx.instant(); + } + _ => {} + } + s.grab = None; + } + } +} + +// ---------------------------------------------------------------- view helpers + +struct P { + sc: Scene, + txt: Color, + txt2: Color, + txt3: Color, + hair: Color, + card: Color, +} + +fn bx(x: f32, y: f32, w: f32, h: f32) -> El { + el().absolute(x, y).size(w, h) +} + +fn label(x: f32, y: f32, s: &str, size: f32, weight: f32, c: Color) -> El { + text(s).absolute(x, y).font(TextStyle::new(size, weight)).color(c) +} + +fn mono(x: f32, y: f32, s: &str, size: f32, c: Color) -> El { + text(s).absolute(x, y).font(TextStyle::new(size, 500.0).mono()).color(c) +} + +fn r(rc: Rect) -> El { + bx(rc.x, rc.y, rc.w, rc.h) +} + +fn circle(c: [f32; 3]) -> El { + bx(c[0] - c[2], c[1] - c[2], c[2] * 2.0, c[2] * 2.0).radius(c[2]) +} + +fn hx(h: u32) -> Color { + rune::color::hex(&format!("#{h:06x}")).unwrap_or(Color::BLACK) +} + +/// Placeholder text lines (skeleton bars). +fn lines(p: &P, x: f32, y: f32, w: f32, n: usize) -> Vec<El> { + (0..n) + .map(|i| { + let ww = w * [1.0, 0.82, 0.6, 0.9][i % 4]; + bx(x, y + i as f32 * 14.0, ww, 6.0).radius(3.0).fill(oklch(0.3, 0.008, 265.0)).mark(mk(p.sc, 0, 0)) + }) + .collect() +} + +fn fx_card(p: &P, rc: Rect, radius: f32, node: u8) -> El { + r(rc).radius(radius) + .fill(p.card) + .border(0.5, p.hair) + .shadow(8.0, 28.0, oklcha(0.0, 0.0, 0.0, 0.5)) + .mark(mk(p.sc, 0, node)) +} + +fn caption(p: &P, x: f32, y: f32, s: &str) -> El { + label(x, y, s, 11.0, 500.0, p.txt3) +} + +// ---------------------------------------------------------------- canvases + +pub fn canvas(s: &Lab, scene: Scene) -> El { + let p = P { + sc: scene, + txt: oklch(0.94, 0.003, 265.0), + txt2: oklch(0.68, 0.01, 265.0), + txt3: oklch(0.52, 0.01, 265.0), + hair: oklcha(1.0, 0.0, 0.0, 0.07), + card: oklch(0.225, 0.007, 265.0), + }; + let kids = match scene { + Scene::Lamp => lamp(s, &p), + Scene::Flashlight => flashlight(&p), + Scene::Gi => gi(s, &p), + Scene::Keys => keys(&p), + Scene::GodRays => godrays(&p), + Scene::Glow => glow(s, &p), + Scene::Pulses => pulses(&p), + Scene::Electric => electric(&p), + Scene::Fire => fire(&p), + Scene::Motion => motion(s, &p), + Scene::Lens => lens(&p), + Scene::Extras => extras(&p), + }; + el().key(format!("canvas-{}", scene.id())).size(CW, CH).mark(mk(scene, 0, 0)).children(kids) +} + +fn lamp(s: &Lab, p: &P) -> Vec<El> { + let user = oklch(0.3, 0.045, 258.0); + let user_hair = oklcha(1.0, 0.0, 0.0, 0.08); + let card = |rc: Rect, c: Color, h: Color| r(rc).radius(16.0).fill(c).border(1.0, h).mark(mk(p.sc, mat::CARD, 0)); + let body = |x: f32, y: f32, ls: &[&str]| -> Vec<El> { + ls.iter().enumerate().map(|(i, l)| label(x, y + i as f32 * 21.0, l, 14.0, 400.0, p.txt)).collect() + }; + let mut v = vec![ + card(Rect::new(400.0, 20.0, 360.0, 64.0), user, user_hair), + card(Rect::new(20.0, 106.0, 500.0, 150.0), p.card, p.hair), + card(Rect::new(500.0, 280.0, 260.0, 44.0), user, user_hair), + card(Rect::new(20.0, 348.0, 540.0, 160.0), p.card, p.hair), + ]; + v.extend(body(418.0, 32.0, &["what if lighting effects. like you could", "put a light and it would raytrace…"])); + v.extend(body( + 40.0, + 122.0, + &[ + "Every Rune element is an analytic rounded rect, so the", + "frame is already an exact distance field. A light can", + "sphere-trace soft shadows straight through it.", + ], + )); + for (i, chip) in ["Read shader.wgsl", "Edit lib.rs", "Run bench"].iter().enumerate() { + let x = 40.0 + [0.0, 136.0, 236.0][i]; + let w = [124.0, 88.0, 84.0][i]; + v.push(bx(x, 212.0, w, 26.0).radius(13.0).fill(oklch(0.27, 0.008, 265.0)).border(1.0, p.hair).mark(mk(p.sc, mat::CHIP, 0))); + v.push(label(x + 11.0, 217.0, chip, 12.0, 500.0, p.txt2)); + } + v.extend(body(520.0, 292.0, &["MAKE THIS SOOO GOOOD"])); + v.extend(body(40.0, 364.0, &["Lights are springs like everything else."])); + v.push(bx(36.0, 396.0, 508.0, 96.0).radius(10.0).fill(oklch(0.195, 0.008, 265.0)).border(1.0, p.hair).mark(mk(p.sc, mat::ON_CARD, 0))); + let code = oklch(0.8, 0.06, 200.0); + for (i, l) in ["let lamp = Light::point(x, y, 40.0)", " .color(WARM).intensity(2.6).radius(11.0);", "lights.render(&scene, &[lamp], target);"].iter().enumerate() { + v.push(mono(54.0, 412.0 + i as f32 * 22.0, l, 12.5, code)); + } + v.push(r(Rect::new(20.0, 532.0, 740.0, 56.0)).radius(18.0).fill(p.card).border(1.0, oklcha(1.0, 0.0, 0.0, 0.09)).mark(mk(p.sc, mat::COMPOSER, 0))); + v.push(label(42.0, 550.0, "Ask anything…", 14.0, 400.0, p.txt3)); + v.push(circle([728.0, 560.0, 16.0]).fill(oklch(0.72, 0.15, 255.0)).mark(mk(p.sc, mat::BUTTON, 0))); + v.push(bx(723.0, 559.0, 10.0, 2.0).radius(1.0).fill(oklch(0.2, 0.02, 255.0)).mark(mk(p.sc, 0, 0))); + // The lamp's handle: a ring around the bulb, which the light draws itself. + let held = matches!(s.grab, Some(Grab::Lamp(_))); + v.push( + circle([s.lamp[0], s.lamp[1], 15.0]) + .key("lamp") + .border(1.0, oklcha(1.0, 0.0, 0.0, if held { 0.5 } else { 0.22 })) + .mark(mk(p.sc, 0, node::LAMP)) + .motion(Spring::new(0.2, 0.0)), + ); + v +} + +fn flashlight(p: &P) -> Vec<El> { + let accent = oklch(0.7, 0.15, 255.0); + let mut v = vec![ + label(20.0, 6.0, "Settings", 24.0, 600.0, p.txt), + label(20.0, 42.0, "Appearance, sound and shortcuts", 13.0, 400.0, p.txt2), + ]; + let rows: [(&str, &str, u8); 9] = [ + ("Appearance", "Dark", 2), + ("Accent", "", 3), + ("Reduce motion", "", 1), + ("Sound effects", "", 0), + ("Volume", "", 4), + ("Push to talk", "⌥ Space", 2), + ("Auto-update", "", 1), + ("Crash reports", "", 0), + ("Launch at login", "", 1), + ]; + for g in 0..3 { + let x = 20.0 + g as f32 * 253.0; + let y = 84.0; + v.push(bx(x, y, 233.0, 156.0).radius(14.0).fill(p.card).border(1.0, p.hair).mark(mk(p.sc, mat::CARD, 0))); + for ri in 0..3 { + let (name, value, kind) = rows[g * 3 + ri]; + let ry = y + ri as f32 * 52.0; + if ri > 0 { + v.push(bx(x + 14.0, ry, 205.0, 1.0).fill(p.hair).mark(mk(p.sc, 0, 0))); + } + v.push(label(x + 16.0, ry + 18.0, name, 13.0, 500.0, p.txt)); + let rx = x + 233.0 - 16.0; + match kind { + 0 | 1 => { + let on = kind == 1; + v.push(bx(rx - 40.0, ry + 15.0, 40.0, 22.0).radius(11.0).fill(if on { accent } else { oklch(0.33, 0.006, 265.0) }).mark(mk(p.sc, mat::ON_CARD, 0))); + let kx = if on { rx - 20.0 } else { rx - 38.0 }; + v.push(bx(kx, ry + 17.0, 18.0, 18.0).radius(9.0).fill(oklch(0.96, 0.0, 0.0)).mark(mk(p.sc, mat::SWITCH, 0))); + } + 2 => { + let w = 14.0 + value.chars().count() as f32 * 7.4; + v.push(bx(rx - w, ry + 13.0, w, 26.0).radius(8.0).fill(oklch(0.3, 0.006, 265.0)).border(1.0, p.hair).mark(mk(p.sc, mat::PILL, 0))); + v.push(label(rx - w + 8.0, ry + 18.0, value, 12.0, 500.0, p.txt)); + } + 3 => { + for (k, h) in [255.0, 300.0, 350.0, 40.0, 150.0].iter().enumerate() { + let cx = rx - 16.0 - k as f32 * 24.0; + v.push(bx(cx, ry + 18.0, 16.0, 16.0).radius(8.0).fill(oklch(0.68, 0.15, *h)).mark(mk(p.sc, mat::SWITCH, 0))); + } + } + _ => { + v.push(bx(rx - 110.0, ry + 25.0, 110.0, 4.0).radius(2.0).fill(oklch(0.33, 0.006, 265.0)).mark(mk(p.sc, mat::ON_CARD, 0))); + v.push(bx(rx - 110.0, ry + 25.0, 70.0, 4.0).radius(2.0).fill(accent).mark(mk(p.sc, mat::ON_CARD, 0))); + v.push(bx(rx - 49.0, ry + 18.0, 18.0, 18.0).radius(9.0).fill(oklch(0.96, 0.0, 0.0)).mark(mk(p.sc, mat::SWITCH, 0))); + } + } + } + } + let by = 266.0; + v.push(bx(20.0, by, 739.0, 132.0).radius(14.0).fill(p.card).border(1.0, p.hair).mark(mk(p.sc, mat::CARD, 0))); + v.push(label(40.0, by + 18.0, "Keyboard shortcuts", 15.0, 600.0, p.txt)); + v.push(label(40.0, by + 42.0, "Press a key combination to record a new shortcut.", 13.0, 400.0, p.txt2)); + for (i, k) in ["⌘", "⇧", "K"].iter().enumerate() { + let x = 40.0 + i as f32 * 52.0; + v.push(bx(x, by + 72.0, 44.0, 44.0).radius(10.0).fill(oklch(0.3, 0.006, 265.0)).border(1.0, p.hair).mark(mk(p.sc, mat::PILL, 0))); + v.push(label(x + 15.0, by + 84.0, k, 15.0, 600.0, p.txt)); + } + v.push(bx(589.0, by + 78.0, 150.0, 36.0).radius(10.0).fill(accent).mark(mk(p.sc, mat::PILL, 0))); + v.push(label(611.0, by + 87.0, "Record shortcut", 13.0, 600.0, oklch(0.18, 0.03, 255.0))); + v.push(bx(459.0, by + 78.0, 116.0, 36.0).radius(10.0).fill(oklch(0.3, 0.006, 265.0)).border(1.0, p.hair).mark(mk(p.sc, mat::PILL, 0))); + v.push(label(498.0, by + 87.0, "Reset", 13.0, 600.0, p.txt)); + let names = ["Microphone", "Speakers", "Camera", "Battery"]; + let subs = ["MacBook Pro", "Studio Display", "FaceTime HD", "92 %"]; + for i in 0..4 { + let x = 20.0 + i as f32 * 189.5; + v.push(bx(x, 424.0, 172.0, 116.0).radius(14.0).fill(p.card).border(1.0, p.hair).mark(mk(p.sc, mat::CARD, 0))); + v.push(label(x + 16.0, 440.0, names[i], 13.0, 600.0, p.txt)); + v.push(label(x + 16.0, 462.0, subs[i], 12.0, 400.0, p.txt2)); + v.push(bx(x + 16.0, 502.0, 140.0, 16.0).radius(8.0).fill(oklch(0.27, 0.006, 265.0)).mark(mk(p.sc, mat::ON_CARD, 0))); + let f = [0.7, 0.45, 0.0, 0.92][i]; + if f > 0.0 { + v.push(bx(x + 16.0, 502.0, 140.0 * f, 16.0).radius(8.0).fill(accent).mark(mk(p.sc, mat::PILL, 0))); + } + } + v +} + +fn gi(s: &Lab, p: &P) -> Vec<El> { + let mut v = vec![ + label(20.0, 4.0, "Voice memo", 24.0, 600.0, p.txt), + label(20.0, 40.0, "Recording · Studio Display microphone", 13.0, 400.0, p.txt2), + ]; + let card = |rc: Rect, radius: f32| r(rc).radius(radius).fill(p.card).border(1.0, p.hair).mark(mk(p.sc, mat::CARD, 0)); + for (i, (t, sub)) in [("Transcript", "Live, 2 speakers"), ("Markers", "3 added"), ("Noise", "Voice isolation on")].iter().enumerate() { + let y = 80.0 + i as f32 * 110.0; + v.push(card(Rect::new(20.0, y, 200.0, 96.0), 16.0)); + v.push(label(40.0, y + 18.0, t, 14.0, 600.0, p.txt)); + v.push(label(40.0, y + 42.0, sub, 13.0, 400.0, p.txt2)); + } + v.push(card(Rect::new(240.0, 80.0, 300.0, 316.0), 20.0)); + v.push(label(262.0, 98.0, "00:42.18", 30.0, 600.0, p.txt)); + v.push(label(262.0, 140.0, if s.recording { "Recording" } else { "Paused" }, 13.0, 500.0, oklch(0.75, 0.12, 25.0))); + for k in 0..30 { + let h = 8.0 + 40.0 * (0.5 + 0.5 * ((k as f32 * 0.7).sin() * (k as f32 * 0.23 + 1.0).cos())).abs(); + v.push(bx(262.0 + k as f32 * 8.6, 206.0 - h * 0.5, 4.4, h).radius(2.2).fill(oklch(0.5, 0.01, 265.0)).mark(mk(p.sc, mat::BAR, 0))); + } + v.push(circle([REC[0], REC[1], 50.0]).fill(oklch(0.27, 0.008, 265.0)).border(1.0, p.hair).mark(mk(p.sc, mat::DIAL, 0))); + v.push(circle(REC).fill(oklch(0.66, 0.2, 25.0)).mark(mk(p.sc, mat::EMIT, node::REC))); + for (i, (t, sub)) in [("Agent finished", "Demos rendered"), ("Build passed", "ci · 1m 12s"), ("Review", "No blockers")].iter().enumerate() { + let y = 80.0 + i as f32 * 110.0; + v.push(card(Rect::new(560.0, y, 200.0, 96.0), 16.0)); + v.push(label(598.0, y + 18.0, t, 14.0, 600.0, p.txt)); + v.push(label(598.0, y + 42.0, sub, 13.0, 400.0, p.txt2)); + let c = if i == 0 { oklch(0.78, 0.17, 150.0) } else { oklch(0.45, 0.01, 265.0) }; + v.push(bx(578.0, y + 22.0, 10.0, 10.0).radius(5.0).fill(c).mark(mk(p.sc, mat::EMIT, if i == 0 { node::STATUS } else { 0 }))); + } + v.push(r(PROGRESS).radius(5.0).fill(oklch(0.24, 0.006, 265.0)).mark(mk(p.sc, mat::FLAT, 0))); + v.push(r(Rect::new(PROGRESS.x, PROGRESS.y, PROGRESS.w * 0.62, PROGRESS.h)).radius(5.0).fill(oklch(0.78, 0.13, 210.0)).mark(mk(p.sc, mat::EMIT, node::PROGRESS))); + v.push(label(20.0, 452.0, "Uploading to OpenCode · 3 of 5 files", 12.0, 500.0, p.txt2)); + for i in 0..5 { + let x = 20.0 + i as f32 * 151.0; + v.push(card(Rect::new(x, 492.0, 136.0, 90.0), 16.0)); + v.push(label(x + 18.0, 510.0, ["Pause", "Marker", "Trim", "Share", "Export"][i], 13.0, 600.0, p.txt)); + } + v +} + +fn keys(p: &P) -> Vec<El> { + let key = oklch(0.29, 0.004, 265.0); + let mut v = vec![ + r(Rect::new(0.0, 0.0, CW, CH)).radius(32.0).fill(oklch(0.255, 0.004, 265.0)).border(1.0, oklcha(1.0, 0.0, 0.0, 0.05)).mark(mk(p.sc, mat::BODY, 0)), + label(40.0, 30.0, "OP-1 Field · Control surface", 15.0, 600.0, p.txt), + label(40.0, 54.0, "Bevels from the SDF catch the light", 12.0, 400.0, p.txt2), + ]; + let hues = [255.0, 150.0, 60.0, 25.0]; + for (i, h) in hues.iter().enumerate() { + let cx = 90.0 + i as f32 * 116.0; + v.push(circle([cx, 170.0, 42.0]).fill(key).mark(mk(p.sc, mat::KNOB, 0))); + v.push(circle([cx, 140.0, 5.0]).fill(oklch(0.7, 0.14, *h)).mark(mk(p.sc, mat::FLAT, 0))); + } + v.push(bx(530.0, 100.0, 210.0, 140.0).radius(18.0).fill(oklch(0.14, 0.01, 265.0)).mark(mk(p.sc, mat::SCREEN, 0))); + v.push(label(554.0, 124.0, "128 BPM", 26.0, 600.0, oklch(0.85, 0.12, 150.0))); + v.push(label(554.0, 166.0, "Pattern A · bar 12", 13.0, 400.0, oklch(0.6, 0.06, 150.0))); + let names = ["C", "D", "E", "F", "G", "A", "B", "C", "D", "E"]; + for i in 0..KEY_COUNT { + let rc = key_rect(i); + let accent = accent_key(i); + v.push(r(rc).radius(14.0).fill(if accent { oklch(0.62, 0.17, 35.0) } else { key }).mark(mk(p.sc, mat::KEY, node::KEY0 + i as u8))); + v.push(label(rc.x + 12.0, rc.y + 12.0, names[i % KEY_COLS], 12.0, 600.0, if accent { oklch(0.2, 0.03, 35.0) } else { p.txt2 })); + } + v +} + +fn godrays(p: &P) -> Vec<El> { + let names = [ + "Inbox", "Calendar", "Notes", "Music", "Photos", "Maps", "Files", "Terminal", "Mail", "Weather", "Clock", "Books", "Home", "Wallet", + "Health", "Code", "Notes", "Rune", + ]; + let mut v = vec![ + label(28.0, 70.0, "Good evening", 30.0, 600.0, p.txt), + label(28.0, 114.0, "18 apps · light from behind the grid", 14.0, 400.0, p.txt2), + ]; + for i in 0..18 { + let (rw, c) = (i / 6, i % 6); + let (x, y) = (28.0 + c as f32 * 124.0, 190.0 + rw as f32 * 124.0); + v.push(bx(x, y, 104.0, 104.0).radius(22.0).fill(oklch(0.21, 0.008, 265.0)).border(1.0, p.hair).mark(mk(p.sc, mat::TILE, 0))); + v.push(bx(x + 16.0, y + 16.0, 36.0, 36.0).radius(11.0).fill(oklch(0.62, 0.12, (i as f32 * 47.0) % 360.0)).mark(mk(p.sc, mat::FLAT, 0))); + v.push(label(x + 16.0, y + 70.0, names[i], 13.0, 600.0, p.txt)); + } + v +} + +pub const GODRAY_REST: [f32; 2] = [374.0, 304.0]; + +fn glow(s: &Lab, p: &P) -> Vec<El> { + let btn = GLOW_BTN; + let mut v = vec![ + r(btn).radius(btn.h * 0.5).fill(hx(0x7a5cf6)).border(0.5, oklcha(1.0, 0.0, 0.0, 0.16)).shadow(4.0, 10.0, oklcha(0.0, 0.0, 0.0, 0.4)).mark(mk(p.sc, 0, node::GLOW_BUTTON)), + label(btn.x + 52.0, btn.y + 16.0, "Generate", 15.0, 600.0, Color::WHITE), + caption(p, btn.x, btn.y + 80.0, "Soft · breathing"), + fx_card(p, NEON, 16.0, node::NEON), + label(NEON.x + 18.0, NEON.y + 20.0, "Neon", 15.0, 600.0, hx(0xe6f9ff)), + ]; + v.extend(lines(p, NEON.x + 18.0, NEON.y + 50.0, 120.0, 3)); + v.push(caption(p, NEON.x, NEON.y + NEON.h + 24.0, if s.neon_on { "Neon · click to switch off" } else { "Neon · click to switch on" })); + v.push(circle(HOT_DOT).fill(hx(0xfff3dc)).mark(mk(p.sc, 0, node::HOT_DOT))); + v.push(label(HOT_DOT[0] + 18.0, HOT_DOT[1] - 9.0, "Recording", 13.0, 500.0, oklch(0.88, 0.005, 265.0))); + v.push(caption(p, HOT_DOT[0] - 10.0, NEON.y + NEON.h + 24.0, "Hot core")); + v.push(r(AURA).radius(AURA.h * 0.5).fill(oklch(0.2, 0.008, 265.0)).border(0.5, oklcha(1.0, 0.0, 0.0, 0.08)).shadow(6.0, 14.0, oklcha(0.0, 0.0, 0.0, 0.5)).mark(mk(p.sc, 0, node::AURA))); + v.push(label(AURA.x + 26.0, AURA.y + 18.0, "Ask anything…", 15.0, 400.0, oklch(0.62, 0.01, 265.0))); + v.push(caption(p, AURA.x, AURA.y + AURA.h + 24.0, "Aura · flowing spectrum")); + v.push(text("Rune").absolute(GLOW_TEXT.x, GLOW_TEXT.y).font(TextStyle::new(76.0, 600.0)).color(hx(0xfff4e6)).mark(mk(p.sc, 0, node::GLOW_TEXT))); + v.push(caption(p, GLOW_TEXT.x, AURA.y + AURA.h + 24.0, "Mask · text bloom")); + v +} + +fn pulses(p: &P) -> Vec<El> { + let mut v = vec![ + circle(RADAR).fill(hx(0xf04e5e)).border(0.5, oklcha(1.0, 0.0, 0.0, 0.2)).mark(mk(p.sc, 0, node::RADAR)), + bx(RADAR[0] - 6.0, RADAR[1] - 6.0, 12.0, 12.0).radius(3.0).fill(oklcha(1.0, 0.0, 0.0, 0.95)).mark(mk(p.sc, 0, 0)), + caption(p, RADAR[0] - 18.0, RADAR[1] + 70.0, "Radar"), + circle(AVATAR).fill(oklch(0.33, 0.012, 265.0)).border(1.0, hx(0x34d399)).mark(mk(p.sc, 0, node::AVATAR)), + label(AVATAR[0] - 10.0, AVATAR[1] - 9.0, "KL", 14.0, 600.0, oklch(0.95, 0.003, 265.0)), + caption(p, AVATAR[0] - 40.0, AVATAR[1] + 70.0, "Breathing halo"), + r(LIVE).radius(LIVE.h * 0.5).fill(hx(0xe8315a)).border(0.5, oklcha(1.0, 0.0, 0.0, 0.2)).mark(mk(p.sc, 0, node::LIVE)), + label(LIVE.x + 28.0, LIVE.y + 8.0, "LIVE", 12.0, 600.0, Color::WHITE), + caption(p, LIVE.x + 10.0, AVATAR[1] + 70.0, "Heartbeat"), + fx_card(p, INBOX, 16.0, node::INBOX), + label(INBOX.x + 18.0, INBOX.y + 20.0, "Inbox", 15.0, 600.0, p.txt), + ]; + v.extend(lines(p, INBOX.x + 18.0, INBOX.y + 50.0, 120.0, 3)); + v.push(circle(SEND).key("send").fill(hx(0x3d7ff5)).border(0.5, oklcha(1.0, 0.0, 0.0, 0.16)).shadow(4.0, 10.0, oklcha(0.0, 0.0, 0.0, 0.4)).mark(mk(p.sc, 0, node::SEND))); + v.push(label(SEND[0] - 6.0, SEND[1] - 10.0, "→", 16.0, 600.0, Color::WHITE)); + v.push(caption(p, SEND[0] - 30.0, SEND[1] + 46.0, "Send · ping → ripple")); + v.push(caption(p, 250.0, 560.0, "Click anywhere for a ripple")); + v +} + +fn electric(p: &P) -> Vec<El> { + let mut v = Vec::new(); + for t in [ARC_A, ARC_B] { + v.push(circle([t[0], t[1], 9.0]).fill(oklch(0.72, 0.01, 265.0)).border(0.5, oklcha(1.0, 0.0, 0.0, 0.3)).mark(mk(p.sc, 0, node::TERMINALS))); + } + v.push(caption(p, ARC_A[0], ARC_A[1] + 40.0, "Arc · click to zap")); + v.push(fx_card(p, OVERLOAD, 18.0, node::OVERLOAD)); + v.push(label(OVERLOAD.x + 22.0, OVERLOAD.y + 22.0, "Overload", 16.0, 600.0, p.txt)); + v.extend(lines(p, OVERLOAD.x + 22.0, OVERLOAD.y + 56.0, 200.0, 4)); + v.push(caption(p, OVERLOAD.x, OVERLOAD.y + OVERLOAD.h + 26.0, "Border current")); + v.push(r(CHARGED).key("charged").radius(CHARGED.h * 0.5).fill(hx(0x1b2740)).border(0.5, oklcha(1.0, 0.0, 0.0, 0.14)).shadow(4.0, 10.0, oklcha(0.0, 0.0, 0.0, 0.4)).mark(mk(p.sc, 0, node::CHARGED))); + v.push(label(CHARGED.x + 86.0, CHARGED.y + 19.0, "Charged", 16.0, 600.0, hx(0xdbe8ff))); + v.push(caption(p, CHARGED.x, CHARGED.y + CHARGED.h + 26.0, "Hover to charge")); + v +} + +fn fire(p: &P) -> Vec<El> { + let mut v = vec![ + fx_card(p, FLAMES, 18.0, node::FLAMES), + label(FLAMES.x + 22.0, FLAMES.y + 24.0, "Hot take", 16.0, 600.0, hx(0xfff1e6)), + ]; + v.extend(lines(p, FLAMES.x + 22.0, FLAMES.y + 58.0, 190.0, 4)); + v.push(caption(p, FLAMES.x, FLAMES.y + FLAMES.h + 26.0, "Flames + embers")); + v.push(r(PLASMA).radius(PLASMA.h * 0.5).fill(hx(0x15122a)).border(0.5, hx(0xb9a8ff).alpha(0.25)).mark(mk(p.sc, 0, node::PLASMA))); + v.push(label(PLASMA.x + 106.0, PLASMA.y + 22.0, "Plasma", 16.0, 600.0, hx(0xe9e4ff))); + v.push(caption(p, PLASMA.x, PLASMA.y + PLASMA.h + 28.0, "Plasma border")); + v.push(r(DEPLOY).radius(DEPLOY.h * 0.5).fill(hx(0xf2702a)).border(0.5, oklcha(1.0, 0.0, 0.0, 0.16)).shadow(4.0, 10.0, oklcha(0.0, 0.0, 0.0, 0.4)).mark(mk(p.sc, 0, node::DEPLOY))); + v.push(label(DEPLOY.x + 62.0, DEPLOY.y + 16.0, "Deploy", 15.0, 600.0, Color::WHITE)); + v.push(caption(p, DEPLOY.x, DEPLOY.y + DEPLOY.h + 28.0, "Heat + haze")); + v +} + +fn motion(s: &Lab, p: &P) -> Vec<El> { + let mut v = Vec::new(); + // A faint dot grid so travel reads. + for gy in 0..11 { + for gx in 0..14 { + v.push(bx(30.0 + gx as f32 * 55.0, 26.0 + gy as f32 * 55.0, 2.0, 2.0).radius(1.0).fill(oklcha(1.0, 0.0, 0.0, 0.07)).mark(mk(p.sc, 0, 0))); + } + } + // The card sits at its target; the compositor draws it along its track (with blur in flight). + let c = s.card.target(); + let m = mk(p.sc, 0, node::CARD); + let (w, h) = (CARD_SIZE[0], CARD_SIZE[1]); + v.push( + bx(c.x, c.y, w, h) + .key("card") + .radius(14.0) + .fill(oklch(0.25, 0.008, 265.0)) + .border(0.5, oklcha(1.0, 0.0, 0.0, 0.1)) + .shadow(4.0, 8.0, oklcha(0.0, 0.0, 0.0, 0.35)) + .mark(m) + .child(bx(12.0, 12.0, 28.0, 28.0).radius(14.0).fill(hx(0x8462fa))) + .child(label(50.0, 13.0, "Flight 204", 13.0, 600.0, oklch(0.96, 0.003, 265.0))) + .child(label(50.0, 31.0, "Departing 9:41", 11.0, 400.0, oklch(0.7, 0.01, 265.0))) + .child(bx(12.0, 66.0, w - 24.0, 6.0).radius(3.0).fill(oklch(0.33, 0.008, 265.0))) + .child(bx(12.0, 66.0, (w - 24.0) * 0.62, 6.0).radius(3.0).fill(hx(0x22c48a))), + ); + v.push(caption(p, 300.0, 560.0, "Drag and fling the card")); + v +} + +fn lens(p: &P) -> Vec<El> { + let tiles = [(0x7c4ff0, "Violet"), (0xf07a2c, "Ember"), (0x22b5a4, "Lagoon"), (0xe0559c, "Orchid")]; + let mut v = Vec::new(); + for (i, (c, n)) in tiles.iter().enumerate() { + let x = 40.0 + i as f32 * 180.0; + v.push(bx(x, 60.0, 160.0, 80.0).radius(14.0).fill(hx(*c)).border(0.5, oklcha(1.0, 0.0, 0.0, 0.15)).mark(mk(p.sc, 0, node::PAGE))); + v.push(label(x + 14.0, 110.0, n, 14.0, 600.0, oklcha(1.0, 0.0, 0.0, 0.95))); + } + for (i, l) in [ + "Glass bends what is behind it: the rim squeezes the page,", + "the middle stays sharp, and colour splits only at the edge.", + "Rune copies the backdrop once per lens and lights the rim.", + ] + .iter() + .enumerate() + { + v.push(label(40.0, 176.0 + i as f32 * 24.0, l, 15.0, 400.0, oklch(0.78, 0.01, 265.0))); + } + v.push(r(CRT).radius(14.0).fill(hx(0x0c1910)).mark(mk(p.sc, 0, node::CRT))); + v.push(mono(CRT.x + 18.0, CRT.y + 22.0, "> rune build --release", 13.0, hx(0x4ade80))); + v.push(mono(CRT.x + 18.0, CRT.y + 44.0, " compiling rune-fx", 13.0, hx(0x86efac).alpha(0.8))); + v.push(mono(CRT.x + 18.0, CRT.y + 66.0, " finished in 1.84 s", 13.0, hx(0x86efac).alpha(0.8))); + v.push(bx(CRT.x + 18.0, CRT.y + 96.0, 132.0, 14.0).radius(3.0).fill(hx(0x22c55e)).mark(mk(p.sc, 0, node::CRT))); + v.push(text("Chromatic").absolute(CHROMA.x + 8.0, CHROMA.y + 6.0).font(TextStyle::new(52.0, 600.0)).color(oklch(0.96, 0.003, 265.0)).mark(mk(p.sc, 0, node::CHROMA))); + v.push(caption(p, 270.0, 560.0, "Drag the glass · click for a shockwave")); + v +} + +fn extras(p: &P) -> Vec<El> { + let mut v = vec![fx_card(p, SKELETON, 16.0, 0)]; + let bar = oklch(0.27, 0.006, 265.0); + let sk = mk(p.sc, 0, node::SKELETON); + for i in 0..3 { + let y = SKELETON.y + 24.0 + i as f32 * 62.0; + v.push(bx(SKELETON.x + 22.0, y, 36.0, 36.0).radius(18.0).fill(bar).mark(sk)); + v.push(bx(SKELETON.x + 72.0, y + 5.0, 190.0 - i as f32 * 28.0, 11.0).radius(5.5).fill(bar).mark(sk)); + v.push(bx(SKELETON.x + 72.0, y + 23.0, 120.0, 9.0).radius(4.5).fill(bar).mark(sk)); + } + v.push(caption(p, SKELETON.x, SKELETON.y + SKELETON.h + 24.0, "Skeleton shimmer")); + v.push(text("Thinking…").absolute(THINKING.x + 6.0, THINKING.y + 8.0).font(TextStyle::new(22.0, 500.0)).color(oklch(0.62, 0.01, 265.0)).mark(mk(p.sc, 0, node::THINKING))); + v.push(caption(p, THINKING.x + 6.0, THINKING.y + THINKING.h + 16.0, "Text sheen")); + v.push(fx_card(p, AURORA, 18.0, node::AURORA)); + v.push(label(AURORA.x + 22.0, AURORA.y + AURORA.h - 40.0, "Aurora", 19.0, 600.0, oklch(0.97, 0.003, 265.0))); + v.push(caption(p, AURORA.x, AURORA.y + AURORA.h + 24.0, "Aurora + static grain")); + v.push(r(PRO).radius(PRO.h * 0.5).fill(hx(0xe9c46a)).border(0.5, oklcha(1.0, 0.0, 0.0, 0.4)).mark(mk(p.sc, 0, node::PRO))); + v.push(label(PRO.x + 36.0, PRO.y + 11.0, "PRO", 14.0, 600.0, hx(0x3b2a06))); + v.push(caption(p, PRO.x, PRO.y + PRO.h + 26.0, "Sparkles · click for a burst")); + v +} diff --git a/app/vendor/rune/examples/lab/src/ui.rs b/app/vendor/rune/examples/lab/src/ui.rs new file mode 100644 index 0000000..218ca66 --- /dev/null +++ b/app/vendor/rune/examples/lab/src/ui.rs @@ -0,0 +1,360 @@ +//! Chrome in OpenCode's dark design language: a scene list, the stage, and a knobs panel with a +//! frame-time readout. + +use std::sync::OnceLock; + +use rune::tok::motion; +use rune::{Align, Color, Cx, Drag, El, Phase, Spring, TextStyle, Theme, col, el, row, spacer, text}; + +use crate::knobs::{ALL, Kind, KnobSpec, Scene, specs}; +use crate::stage; +use crate::Lab; + +const SIDEBAR_W: f32 = 212.0; +const PANEL_W: f32 = 272.0; +// Sidebar geometry. Every text line (eyebrows, rows, the footer hint) starts on one edge, +// TEXT_X, which is also the knobs panel's inset. Row pills (hover and the travelling selection) +// sit PILL_INSET in from both sidebar edges and bleed out PILL_PAD around their text. +const PILL_INSET: f32 = 10.0; +const PILL_PAD: f32 = 10.0; +const TEXT_X: f32 = PILL_INSET + PILL_PAD; +const PILL_W: f32 = SIDEBAR_W - 2.0 * PILL_INSET; +const ROW_H: f32 = 28.0; +const ROW_PITCH: f32 = 30.0; +const PILL_R: f32 = 8.0; +const GROUP_H: f32 = 28.0; +const GROUP_GAP: f32 = 16.0; +const SLIDER_W: f32 = PANEL_W - 40.0; + +pub struct Pal { + pub base: Color, + pub deep: Color, + pub text: Color, + pub muted: Color, + pub faint: Color, + pub accent: Color, + pub border: Color, + pub hover: Color, + pub pressed: Color, + pub selected: Color, + pub track: Color, + pub knob: Color, + pub shadow: Color, +} + +pub fn pal() -> &'static Pal { + static P: OnceLock<Pal> = OnceLock::new(); + P.get_or_init(|| { + let t = Theme::from_json(include_str!("../assets/theme.json"), true).unwrap_or_else(|e| panic!("{e}")); + let c = |n: &str| t.color(n); + Pal { + base: c("background-bg-base"), + deep: c("background-bg-deep"), + text: c("text-text-base"), + muted: c("text-text-muted"), + faint: c("text-text-faint"), + accent: c("text-text-accent"), + border: c("border-border-base"), + hover: c("overlay-simple-overlay-hover"), + pressed: c("overlay-simple-overlay-pressed"), + selected: c("background-bg-layer-02"), + track: c("background-bg-layer-03"), + knob: c("text-text-base"), + shadow: c("alpha-dark-30"), + } + }) +} + +const BODY: TextStyle = TextStyle::new(13.0, 400.0); +const LABEL: TextStyle = TextStyle::new(12.5, 500.0); +const EYEBROW: TextStyle = TextStyle::new(11.0, 600.0).tracking(0.4); +const TITLE: TextStyle = TextStyle::new(17.0, 600.0); +const VALUE: TextStyle = TextStyle::new(11.5, 500.0).mono(); + +pub fn view(s: &Lab, cx: &mut Cx<Lab>) -> El { + cx.reduced_motion(s.reduced); + let p = pal(); + let hair = 1.0 / cx.env().scale; + row() + .key("window") + .fill(p.deep) + .w_full() + .h_full() + .child(sidebar(s, hair)) + .child(stage_view(s)) + .child(panel(s, hair)) +} + +// ---------------------------------------------------------------- sidebar + +fn sidebar(s: &Lab, hair: f32) -> El { + let p = pal(); + let mut list = el().key("scenes").w_full(); + let mut y = 0.0; + let mut sel_y = 0.0; + let mut items: Vec<El> = Vec::new(); + for (g, group) in [("Light", &ALL[..5]), ("Effects", &ALL[5..])].iter().enumerate() { + if g > 0 { + y += GROUP_GAP; + } + items.push( + row() + .key(format!("group{g}")) + .absolute(0.0, y) + .size(SIDEBAR_W, GROUP_H) + .pl(TEXT_X) + .center_y() + .child(text(group.0.to_uppercase()).key("label").font(EYEBROW).color(p.faint)), + ); + y += GROUP_H; + for sc in group.1.iter().copied() { + let selected = sc == s.scene; + if selected { + sel_y = y; + } + items.push( + row() + .key(sc.id()) + .role("tab") + .label(sc.title()) + .absolute(PILL_INSET, y) + .size(PILL_W, ROW_H) + .px(PILL_PAD) + .center_y() + .radius(PILL_R) + .hover(if selected { Color::TRANSPARENT } else { p.hover }) + .press(p.pressed) + .on_press(move |s: &mut Lab| s.select(sc)) + .child(text(sc.title()).key("label").font(BODY).color(if selected { p.text } else { p.muted })), + ); + y += ROW_PITCH; + } + } + list = list + .h(y) + .child( + el().key("selection") + .absolute(PILL_INSET, sel_y) + .size(PILL_W, ROW_H) + .radius(PILL_R) + .fill(p.selected) + .lead(motion::LEAD, motion::DEFAULT), + ) + .children(items); + row() + .key("sidebar-wrap") + .h_full() + .child( + col() + .key("sidebar") + .w(SIDEBAR_W) + .h_full() + .fill(p.base) + .child(row().key("brand").h(52.0).w_full().pl(86.0).center_y().child(text("Rune Lab").key("title").font(TextStyle::new(13.0, 600.0)).color(p.text))) + .child(list) + .child(spacer()) + .child( + text("↑ ↓ to switch scenes") + .key("keys-hint") + .font(TextStyle::new(11.5, 400.0)) + .color(p.faint) + .ml(TEXT_X) + .mb(16.0), + ), + ) + .child(el().key("sidebar-edge").w(hair).h_full().fill(p.border)) +} + +// ---------------------------------------------------------------- stage + +fn stage_view(s: &Lab) -> El { + el().key("stage") + .role("canvas") + .grow(1.0) + .h_full() + .center() + .fill(stage::backdrop(s.scene)) + .motion(motion::DEFAULT) + .clip_soft(0.0) + .mark(stage::STAGE_MARK) + .on_drag(stage::on_stage) + .child(stage::canvas(s, s.scene)) +} + +// ---------------------------------------------------------------- panel + +fn panel(s: &Lab, hair: f32) -> El { + let p = pal(); + let sc = s.scene; + let mut knobs = col().key(format!("knobs-{}", sc.id())).gap(18.0).w_full(); + for (i, k) in specs(sc).iter().enumerate() { + knobs = knobs.child(knob(s, sc, i, k)); + } + row() + .key("panel-wrap") + .h_full() + .child(el().key("panel-edge").w(hair).h_full().fill(p.border)) + .child( + col() + .key("panel") + .w(PANEL_W) + .h_full() + .fill(p.base) + .px(20.0) + .pt(48.0) + .pb(20.0) + .child(text(sc.title()).key("scene-title").font(TITLE).color(p.text)) + .child(text(sc.hint()).key("scene-hint").w(PANEL_W - 40.0).wrap().font(TextStyle::new(12.5, 400.0).lh(18.0)).color(p.muted).mt(8.0)) + .child(el().key("sep").h(hair).w_full().fill(p.border).mt(20.0).mb(20.0)) + .child(knobs) + .child(spacer()) + .child(el().key("sep2").h(hair).w_full().fill(p.border).mb(14.0)) + .child(toggle_row("reduced", "Reduce motion", s.reduced, |s: &mut Lab| s.reduced = !s.reduced)) + .child(readout(s)), + ) +} + +fn readout(s: &Lab) -> El { + let p = pal(); + let f = |v: Option<f32>| v.map_or("—".to_owned(), |v| format!("{v:.2} ms")); + let line = |key: &str, name: &str, value: String| { + row() + .key(key.to_owned()) + .h(20.0) + .w_full() + .center_y() + .justify_between() + .child(text(name).key("name").font(TextStyle::new(12.0, 400.0)).color(p.faint)) + .child(text(value).key("value").font(VALUE).color(p.muted).align(Align::End)) + }; + let state = if s.perf.live { "Animating" } else { "At rest · no frames" }; + col() + .key("readout") + .mt(12.0) + .gap(2.0) + .child(line("gpu", "GPU frame", f(s.perf.gpu_ms))) + .child(line("cpu", "CPU frame", f(Some(s.perf.cpu_ms).filter(|v| *v > 0.0)))) + .child(line("state", "Display link", state.to_owned())) +} + +fn knob(s: &Lab, sc: Scene, i: usize, k: &KnobSpec) -> El { + let v = s.vals[sc.idx()][i]; + match k.kind { + Kind::Slider(dec) => slider(sc, i, k, v, dec), + Kind::Toggle => { + let on = v > 0.5; + toggle_row(k.id, k.label, on, move |s: &mut Lab| { + let cur = &mut s.vals[sc.idx()][i]; + *cur = if *cur > 0.5 { 0.0 } else { 1.0 }; + }) + } + Kind::Swatch(palette) => swatches(sc, i, k, v as usize, palette), + } +} + +fn slider(sc: Scene, i: usize, k: &KnobSpec, v: f32, dec: u8) -> El { + let p = pal(); + let (w, h, kd, bar) = (SLIDER_W, 18.0, 14.0, 4.0); + let travel = w - kd; + let (min, max) = (k.min, k.max); + let u = ((v - min) / (max - min)).clamp(0.0, 1.0); + let to_value = move |x: f32| min + ((x - kd / 2.0) / travel).clamp(0.0, 1.0) * (max - min); + let value = format!("{:.*}", dec as usize, v); + col() + .key(k.id) + .gap(6.0) + .child( + row() + .key("head") + .w_full() + .justify_between() + .child(text(k.label).key("label").font(LABEL).color(p.text)) + .child(text(value).key("value").font(VALUE).color(p.muted).align(Align::End)), + ) + .child( + el().key("slider") + .role("slider") + .label(k.label) + .size(w, h) + .motion(motion::SNAPPY) + .on_drag(move |s: &mut Lab, d: &mut Drag, tx| { + let cur = s.vals[sc.idx()][i]; + let knob_x = kd / 2.0 + ((cur - min) / (max - min)).clamp(0.0, 1.0) * travel; + match d.phase { + Phase::Down => { + d.data = cur; + if (d.x - knob_x).abs() > kd / 2.0 + 3.0 { + s.vals[sc.idx()][i] = to_value(d.x); + } + } + Phase::Move => { + let knob = kd / 2.0 + ((d.data - min) / (max - min)).clamp(0.0, 1.0) * travel; + let grab = if (d.start_x - knob).abs() <= kd / 2.0 + 3.0 { d.start_x - knob } else { 0.0 }; + s.vals[sc.idx()][i] = to_value(d.x - grab); + tx.instant(); + } + Phase::Up => { if d.cancelled() { s.vals[sc.idx()][i] = d.data; } } + } + }) + .child(el().key("track").size(w, bar).absolute(0.0, (h - bar) / 2.0).radius(bar / 2.0).fill(p.track)) + .child(el().key("fill").size(kd / 2.0 + u * travel, bar).absolute(0.0, (h - bar) / 2.0).radius(bar / 2.0).fill(p.accent)) + .child( + el().key("knob") + .size(kd, kd) + .absolute(u * travel, (h - kd) / 2.0) + .radius(kd / 2.0) + .fill(p.knob) + .shadow(1.0, 3.0, p.shadow), + ), + ) +} + +fn toggle_row(key: &'static str, label: &str, on: bool, flip: impl Fn(&mut Lab) + 'static) -> El { + let p = pal(); + let (w, h, k) = (32.0, 18.0, 14.0); + let inset = (h - k) / 2.0; + row() + .key(key) + .role("toggle") + .label(label) + .h(26.0) + .w_full() + .center_y() + .justify_between() + .on_press(flip) + .child(text(label.to_owned()).key("label").font(LABEL).color(p.text)) + .child( + el().key("switch") + .size(w, h) + .radius(h / 2.0) + .fill(if on { p.accent } else { p.track }) + .motion(motion::SNAPPY) + .child(el().key("knob").size(k, k).absolute(if on { w - k - inset } else { inset }, inset).radius(k / 2.0).fill(p.knob).shadow(1.0, 2.0, p.shadow)), + ) +} + +fn swatches(sc: Scene, i: usize, k: &KnobSpec, cur: usize, palette: &'static [u32]) -> El { + let p = pal(); + let (d, gap, ring_w) = (16.0, 10.0, 1.5); + let ring = d + 2.0 * (ring_w + 2.0); + let mut r = row().key("swatches").gap(gap).motion(motion::SNAPPY).child( + el().key("ring") + .size(ring, ring) + .absolute(cur as f32 * (d + gap) - (ring - d) / 2.0, -(ring - d) / 2.0) + .radius(ring / 2.0) + .border(ring_w, p.text) + .lead(Spring::new(0.22, 0.0), Spring::new(0.28, 0.0)), + ); + for (j, hex) in palette.iter().enumerate() { + let c = rune::color::hex(&format!("#{hex:06x}")).unwrap_or(Color::WHITE); + r = r.child( + el().key(format!("c{j}")) + .role("swatch") + .size(d, d) + .radius(d / 2.0) + .fill(c) + .on_press(move |s: &mut Lab| s.vals[sc.idx()][i] = j as f32), + ); + } + col().key(k.id).gap(10.0).child(text(k.label).key("label").font(LABEL).color(p.text)).child(r) +} diff --git a/app/vendor/rune/examples/launcher/Cargo.toml b/app/vendor/rune/examples/launcher/Cargo.toml new file mode 100644 index 0000000..72e2c31 --- /dev/null +++ b/app/vendor/rune/examples/launcher/Cargo.toml @@ -0,0 +1,11 @@ +[package] +name = "launcher" +version = "0.0.1" +edition.workspace = true +license.workspace = true + +[dependencies] +rune = { workspace = true, default-features = true, features = ["keys-overlay"] } + +[lints] +workspace = true diff --git a/app/vendor/rune/examples/launcher/backdrop.png b/app/vendor/rune/examples/launcher/backdrop.png new file mode 100644 index 0000000..88287f3 Binary files /dev/null and b/app/vendor/rune/examples/launcher/backdrop.png differ diff --git a/app/vendor/rune/examples/launcher/scripts/demo.json b/app/vendor/rune/examples/launcher/scripts/demo.json new file mode 100644 index 0000000..a2a2255 --- /dev/null +++ b/app/vendor/rune/examples/launcher/scripts/demo.json @@ -0,0 +1,10 @@ +{"displays": [{"id": 1, "frame": [0, 0, 1280, 800], "scale": 2, "primary": true}], + "events": [ + {"t": 0.50, "type": "tap", "key": "note-2"}, + {"t": 1.30, "type": "shortcut", "chord": "cmd+space"}, + {"t": 1.90, "type": "type", "text": "lis", "every": 0.12}, + {"t": 2.60, "type": "key", "name": "Down"}, + {"t": 3.00, "type": "key", "name": "Up"}, + {"t": 3.50, "type": "key", "name": "Enter"}, + {"t": 4.70, "type": "mark", "name": "end"} +]} diff --git a/app/vendor/rune/examples/launcher/src/main.rs b/app/vendor/rune/examples/launcher/src/main.rs new file mode 100644 index 0000000..320778d --- /dev/null +++ b/app/vendor/rune/examples/launcher/src/main.rs @@ -0,0 +1,168 @@ +//! A notes app with a ⌘Space launcher panel: three windows that `--desktop` records together. +//! `cargo run -p launcher` opens the notes window; ⌘Space shows the launcher. +//! +//! ```sh +//! target/release/launcher --desktop examples/launcher/backdrop.png \ +//! --script examples/launcher/scripts/demo.json --video demo.mp4 --keys --pointer +//! ``` +//! +//! With `--desktop` the app adds a fake menu bar, so the recording reads as a desktop. + +#![forbid(unsafe_code)] + +use std::sync::atomic::{AtomicBool, Ordering}; + +use rune::tok::{self, type_}; +use rune::{ + Align, AppHandle, AppSpec, App, Color, Cx, DisplayTarget, El, Key, KeyEvent, MacWindowOptions, OverlayPlacement, + ScreenEdge, TextEdit, Tx, WindowOptions, WindowSpec, col, el, row, spacer, text, text_input, +}; + +/// Recording with `--desktop`: there is no native chrome, so the app draws its own. +static DESKTOP: AtomicBool = AtomicBool::new(false); + +const NOTES: [(&str, &str); 4] = [ + ("Groceries", "Oat milk, lemons, basil, sourdough, two avocados."), + ("Trip to Lisbon", "Book the tram tour. Pastéis de nata first."), + ("Reading list", "The Design of Everyday Things. Thinking in Systems."), + ("Ideas", "A launcher that opens notes by typing their first letters."), +]; + +struct Notes { + selected: usize, + focused: bool, +} + +struct Launcher { + query: TextEdit, + picked: usize, + me: AppHandle<Launcher>, + notes: AppHandle<Notes>, +} + +fn matches(query: &str) -> Vec<usize> { + let q = query.to_lowercase(); + (0..NOTES.len()).filter(|&i| NOTES[i].0.to_lowercase().contains(&q)).collect() +} + +fn notes_view(s: &Notes, _: &mut Cx<Notes>) -> El { + let t = tok::theme(true); + let accent = tok::accent(0, true); + let light = |c: (f32, f32, f32)| el().size(12.0, 12.0).radius(6.0) + .fill(if s.focused { Color { r: c.0, g: c.1, b: c.2, a: 1.0 } } else { t.control_off }); + let title_bar = row().h(38.0).px(14.0).gap(8.0).center_y() + .child(light((1.0, 0.37, 0.34))).child(light((1.0, 0.74, 0.18))).child(light((0.16, 0.79, 0.25))) + .child(spacer()).child(text("Notes").font(type_::TITLE).color(t.text_secondary)).child(spacer()) + .child(el().w(52.0)); + let mut list = col().key("list").w(170.0).h_full().px(8.0).gap(2.0); + for (i, (title, _)) in NOTES.iter().enumerate() { + let on = i == s.selected; + list = list.child(row().key(format!("note-{i}")).h(30.0).px(10.0).radius(6.0).center_y() + .fill(if on { accent.alpha(0.85) } else { Color::TRANSPARENT }) + .child(text(*title).font(type_::BODY).color(if on { Color::WHITE } else { t.text })) + .on_press(move |s: &mut Notes| s.selected = i)); + } + let (title, body) = NOTES[s.selected]; + let page = col().key("page").grow(1.0).h_full().padding(20.0).gap(10.0).fill(t.bg) + .child(text(title).font(type_::TITLE.lh(22.0)).color(t.text)) + .child(text(body).font(type_::BODY.lh(20.0)).color(t.text_secondary)) + .child(spacer()) + .child(text("⌘Space to search").font(type_::LABEL).color(t.text_secondary.alpha(0.7))); + col().w_full().h_full().fill(t.card) + .child(if DESKTOP.load(Ordering::Relaxed) { title_bar } else { el().h(12.0) }) + .child(row().w_full().grow(1.0).child(list).child(page)) +} + +fn launcher_view(s: &Launcher, _: &mut Cx<Launcher>) -> El { + let t = tok::theme(true); + let accent = tok::accent(0, true); + let found = matches(&s.query.text); + let field = text_input(&s.query, type_::BODY.lh(26.0)).key("query").single_line().grow(1.0) + .color(t.text).placeholder("Search notes", t.text_secondary) + .on_edit(|s: &mut Launcher| &mut s.query) + .on_input_key(|s: &mut Launcher, ev: &KeyEvent, tx: &mut Tx| { + let n = matches(&s.query.text).len(); + match ev.key { + Key::Down if n > 0 => s.picked = (s.picked + 1) % n, + Key::Up if n > 0 => s.picked = (s.picked + n - 1) % n, + Key::Escape => tx.close_window(), + _ => return false, + } + true + }) + .on_input_change(|s: &mut Launcher, _| s.picked = 0) + .on_submit(open_picked); + let mut panel = col().key("panel").w_full().radius(14.0).clip_rounded(14.0) + .fill(t.card).border(1.0, Color::WHITE.alpha(0.1)) + .child(row().h(56.0).px(18.0).gap(12.0).center_y() + .child(text("⌕").font(type_::TITLE.lh(26.0)).color(t.text_secondary)) + .child(field)); + if !found.is_empty() { + let mut results = col().key("results").padding(6.0).gap(2.0); + for (row_i, &i) in found.iter().enumerate() { + let on = row_i == s.picked; + results = results.child(row().key(format!("result-{i}")).h(36.0).px(12.0).radius(8.0).center_y() + .fill(if on { accent.alpha(0.85) } else { Color::TRANSPARENT }) + .child(text(NOTES[i].0).font(type_::BODY).color(if on { Color::WHITE } else { t.text }))); + } + panel = panel.child(el().h(1.0).w_full().fill(t.separator)).child(results); + } + col().w_full().h_full().child(panel) +} + +fn open_picked(s: &mut Launcher, tx: &mut Tx) { + let Some(&i) = matches(&s.query.text).get(s.picked) else { return }; + s.notes.update(move |n, _| n.selected = i); + s.notes.focus(); + s.query.clear(); + tx.close_window(); +} + +fn menu_bar_view(_: &(), _: &mut Cx<()>) -> El { + let ink = Color::WHITE.alpha(0.92); + let item = |s: &'static str| text(s).font(type_::BODY).color(ink); + row().w_full().h_full().px(14.0).gap(18.0).center_y().fill(Color::BLACK.alpha(0.22)) + .child(text("◆").font(type_::TITLE).color(ink)) + .child(text("Notes").font(type_::TITLE).color(ink)) + .child(item("File")).child(item("Edit")).child(item("View")).child(item("Window")) + .child(spacer()) + .child(item("Sat 9:41")) +} + +fn main() { + DESKTOP.store(std::env::args().any(|a| a == "--desktop"), Ordering::Relaxed); + rune::run_windows(|displays| { + let notes = App::new(AppSpec::new("Notes", (520.0, 320.0), || Notes { selected: 0, focused: true }, notes_view)) + .keep_running() + .on_focus(|s, focused, _| s.focused = focused); + let launcher = App::new(AppSpec::new("Launcher", (560.0, 220.0), || unreachable!(), launcher_view)).windowless(); + let (notes_handle, me) = (notes.handle(), launcher.handle()); + let launcher = launcher + .init(move || { + let mut query = TextEdit::new(""); + query.focused = true; + Launcher { query, picked: 0, me, notes: notes_handle } + }) + .global_shortcut("cmd+space", |s, _| { + s.me.place(DisplayTarget::Primary, OverlayPlacement::Edge { + edge: ScreenEdge::Top, margin: 150.0, align: Align::Center, inset: 0.0, + }); + s.me.show(); + }) + .on_focus(|_, focused, tx| if !focused { tx.close_window() }); + let mut windows: Vec<rune::AnyWindowSpec> = vec![ + WindowSpec::from_app("notes", notes).into(), + WindowSpec::from_app("launcher", launcher).configured_options(WindowOptions::launcher_panel()).into(), + ]; + if DESKTOP.load(Ordering::Relaxed) && let Some(d) = displays.iter().find(|d| d.primary).or(displays.first()) { + let bar = WindowOptions { + transparent: true, borderless: true, click_through: true, always_on_top: true, + position: Some(d.position), physical_size: Some((d.size.0, (24.0 * d.scale).round() as u32)), + min_size: Some((0.0, 0.0)), ..Default::default() + }; + windows.push(WindowSpec::new("menu-bar", AppSpec::new("Menu bar", (0.0, 24.0), || (), menu_bar_view)) + .configured_options(bar.macos(MacWindowOptions::default().shadow(false))).into()); + } + windows + }); +} diff --git a/app/vendor/rune/examples/live-values/Cargo.toml b/app/vendor/rune/examples/live-values/Cargo.toml new file mode 100644 index 0000000..09d6540 --- /dev/null +++ b/app/vendor/rune/examples/live-values/Cargo.toml @@ -0,0 +1,11 @@ +[package] +name = "live-values" +version = "0.0.1" +edition.workspace = true +license.workspace = true + +[dependencies] +rune = { workspace = true, default-features = true, features = ["keys-overlay"] } + +[lints] +workspace = true diff --git a/app/vendor/rune/examples/live-values/README.md b/app/vendor/rune/examples/live-values/README.md new file mode 100644 index 0000000..f885cdb --- /dev/null +++ b/app/vendor/rune/examples/live-values/README.md @@ -0,0 +1,48 @@ +# Live values + +Sixteen speaking rings at 60 Hz and four remote cursors at 120 Hz. The window uses +a background producer; headless runs use the same scripted values at virtual time. +Updates stop after four seconds, then the window sleeps. `--scene smooth` adds an +interruptible 160 ms, zero-bounce cursor spring. + +```rust +let level = rune::Live::new(0.0_f32); +let cursor = rune::Live::new([0.0_f32, 0.0]); +// Clone into a producer thread; no view invalidation or explicit Waker needed. +level.set(0.8); +cursor.set([120.0, 64.0]); +let ring = rune::el().live_opacity(&level); +let pointer = rune::el().live_offset(cursor.smooth(rune::Spring::new(0.16, 0.0))); +``` + +```sh +cargo build --release -p live-values +target/release/live-values --snap live.png --at 2 +target/release/live-values --scene smooth --trace live.jsonl --frames 840 --fps 120 + +cargo build --profile perf -p live-values +target/perf/live-values --bench +``` + +`--rebuild` selects the reference poll/view/layout path. `--bench` compares both +paths with one warmup and seven measured runs, reporting median CPU frame time. +It includes synthetic producer work but excludes wgpu/driver work. Wake/idle +counters model 120 Hz consumption; they are not OS power or native presentation +measurements. Ordinary headless `--frames` deliberately forces frames even at rest. + +Bindings override the corresponding authored property, preserving layout. Offset +is additive in parent points; scale is uniform about the centre. Fill is linear +RGBA. Bindings on removed nodes disconnect while the last pose exits. Shared +sources independently wake each subscribed, visible window. First mount lands +immediately; smoothing obeys Rune's reduced-motion policy. + +`.live_rect(&Live<[f32; 4]>)` controls `[x, y, width, height]` in parent points +without reflowing siblings or rewrapping text. This also supports a meter's fill +width. `.live_fill(&Live<Color>)` and `.live_scale(&Live<f32>)` use the same path. + +Values use coherent 128-bit atomic snapshots, including concurrent producers. +Desktop CPUs must support lock-free 128-bit atomics (`Live::new` checks). `set` +ignores NaN and clamps ±inf, so audio callbacks never panic. Publication and CPU presentation allocate nothing after mounting; +platform wake callbacks are not hard-real-time guarantees. Subscription metadata +is one cell per source/runtime pair, reused across view rebuilds and freed when +the last source handle dies. Keep sources scoped to their app/window lifetime. diff --git a/app/vendor/rune/examples/live-values/src/main.rs b/app/vendor/rune/examples/live-values/src/main.rs new file mode 100644 index 0000000..a25f7a6 --- /dev/null +++ b/app/vendor/rune/examples/live-values/src/main.rs @@ -0,0 +1,144 @@ +#![forbid(unsafe_code)] + +use rune::{AppSpec, Color, Cx, El, Env, Live, Runtime, Spring, Tx, col, el, row}; +use std::sync::{Arc, atomic::{AtomicBool, AtomicUsize, Ordering}}; + +static WINDOWED: AtomicBool = AtomicBool::new(false); + +struct State { + levels: [f32; 16], + cursors: [[f32; 2]; 4], + tick: u64, + live_levels: [Live<f32>; 16], + live_cursors: [Live<[f32; 2]>; 4], + rebuild: bool, + smooth: bool, +} + +fn init() -> State { + let mut s = State { levels: [0.5; 16], cursors: [[0.0; 2]; 4], tick: 0, + live_levels: std::array::from_fn(|_| Live::new(0.5)), + live_cursors: std::array::from_fn(|_| Live::new([0.0; 2])), + rebuild: rune::extra_args().iter().any(|a| a == "--rebuild"), smooth: false }; + sample(&mut s, 0); + s +} + +fn sample(s: &mut State, tick: u64) { + if tick % 2 == 0 { + for (i, level) in s.levels.iter_mut().enumerate() { + *level = 0.5 + 0.45 * (tick as f32 / 120.0 * 3.0 + i as f32).sin(); + } + } + for (i, cursor) in s.cursors.iter_mut().enumerate() { + let t = tick as f32 / 120.0 + i as f32; + *cursor = [250.0 + 180.0 * t.sin(), 190.0 + 120.0 * (t * 0.7).cos()]; + } + if !s.rebuild { + for (live, value) in s.live_levels.iter().zip(s.levels) { live.set(value); } + for (live, value) in s.live_cursors.iter().zip(s.cursors) { live.set(value); } + } +} + +fn poll(s: &mut State, t: f64, tx: &mut Tx) -> bool { + if WINDOWED.load(Ordering::Relaxed) && !s.rebuild { return false; } + let tick = (t.min(4.0) * 120.0).round() as u64; + if tick == s.tick { return false; } + s.tick = tick; + sample(s, tick); + tx.instant(); + s.rebuild +} + +fn view(s: &State, _: &mut Cx<State>) -> El { + let green = Color { r: 0.1, g: 0.8, b: 0.4, a: 1.0 }; + let mut grid = col().gap(20.0).padding(40.0); + for y in 0..4 { + let mut line = row().gap(24.0); + for x in 0..4 { + let i = y * 4 + x; + let ring = el().key(format!("speaker-{i}")).size(64.0, 64.0) + .radius(32.0).border(3.0, green); + line = line.child(if s.rebuild { ring.opacity(s.levels[i]) } else { ring.live_opacity(&s.live_levels[i]) }); + } + grid = grid.child(line); + } + let mut root = el().fill(Color { r: 0.018, g: 0.024, b: 0.03, a: 1.0 }) + .size(560.0, 440.0).child(grid); + for (i, p) in s.cursors.iter().enumerate() { + let cursor = el().key(format!("cursor-{i}")).size(12.0, 18.0).radius(3.0).fill(green); + root = root.child(if s.rebuild { cursor.pin(Some(p[0]), Some(p[1]), None, None) } + else { + let cursor = cursor.pin(Some(0.0), Some(0.0), None, None); + if s.smooth { cursor.live_offset(s.live_cursors[i].smooth(Spring::new(0.16, 0.0))) } + else { cursor.live_offset(&s.live_cursors[i]) } + }); + } + root +} + +fn bench_mode(rebuild: bool) { + let mut medians = Vec::new(); + for run in 0..8 { + let mut state = init(); state.rebuild = rebuild; + let mut rt = Runtime::new(state, view, (560.0, 440.0), Env::new(true, 2.0)); + let wakes = Arc::new(AtomicUsize::new(0)); let count = wakes.clone(); + rt.set_live_waker(Arc::new(move || { count.fetch_add(1, Ordering::Relaxed); })); + rt.poll = Some(poll); + rt.frame(0.0); + let mut times = Vec::new(); + for _ in 0..480 { + let start = rune::time::now(); + rt.frame(1.0 / 120.0); + times.push(start.elapsed().as_secs_f64() * 1e6); + } + times.sort_by(f64::total_cmp); + if run > 0 { medians.push(times[times.len() / 2]); } + if run == 7 && !rebuild { + let wake_count = wakes.load(Ordering::Relaxed); + let mut frames = 0; + for _ in 0..1200 { + sample(&mut rt.state, 480); + if rt.live_pending() || rt.animating { rt.frame(1.0 / 120.0); frames += 1; } + } + println!("METRIC simulated_wakes_per_second={} idle_frames={} idle_wakes={}", wake_count as f64 / 4.0, + frames, wakes.load(Ordering::Relaxed) - wake_count); + } + } + medians.sort_by(f64::total_cmp); + println!("METRIC {}_cpu_us_median={:.3} runs={medians:?}", if rebuild { "rebuild" } else { "live" }, medians[3]); +} + +fn setup(s: &mut State, wake: rune::Waker) { + if !WINDOWED.load(Ordering::Relaxed) { return; } + if s.rebuild { + std::thread::spawn(move || { + for _ in 0..480 { std::thread::sleep(std::time::Duration::from_secs_f64(1.0 / 120.0)); wake(); } + }); + return; + } + let levels = s.live_levels.clone(); + let cursors = s.live_cursors.clone(); + std::thread::spawn(move || { + let start = rune::time::now(); + for tick in 1..=480 { + std::thread::sleep((start + std::time::Duration::from_secs_f64(tick as f64 / 120.0)).saturating_duration_since(rune::time::now())); + if tick % 2 == 0 { + for (i, level) in levels.iter().enumerate() { level.set(0.5 + 0.45 * (tick as f32 / 120.0 * 3.0 + i as f32).sin()); } + } + for (i, cursor) in cursors.iter().enumerate() { + let t = tick as f32 / 120.0 + i as f32; + cursor.set([250.0 + 180.0 * t.sin(), 190.0 + 120.0 * (t * 0.7).cos()]); + } + } + }); +} + +fn main() { + if std::env::args().any(|a| a == "--bench") { bench_mode(true); return bench_mode(false); } + WINDOWED.store(!std::env::args().any(|a| matches!(a.as_str(), "--snap" | "--trace" | "--tree" | "--frames" | "--strip" | "--first-pixels" | "--list-scenes")), Ordering::Relaxed); + rune::run(AppSpec::<State> { + scenes: &[("smooth", |s| s.smooth = true)], setup: Some(setup), poll: Some(poll), + ..AppSpec::new("Live values", (560.0, 440.0), init, view) + }); +} diff --git a/app/vendor/rune/examples/luau-panel/Cargo.toml b/app/vendor/rune/examples/luau-panel/Cargo.toml new file mode 100644 index 0000000..82080da --- /dev/null +++ b/app/vendor/rune/examples/luau-panel/Cargo.toml @@ -0,0 +1,36 @@ +[package] +name = "luau-panel" +version = "0.0.1" +edition.workspace = true +license.workspace = true +publish = false + +[lib] +crate-type = ["cdylib", "rlib"] + +[[bin]] +name = "luau-panel" +path = "src/main.rs" + +[[bin]] +name = "luau-bench" +path = "src/bin/bench.rs" + +[dependencies] +rune = { workspace = true, default-features = true, features = ["keys-overlay"] } +serde = { workspace = true, features = ["derive"] } +rune-luau = { workspace = true, features = ["serde"] } + +[target.'cfg(not(target_arch = "wasm32"))'.dependencies] +rune-luau = { workspace = true, features = ["serde", "watch"] } + +# The bench compares Luau's interpreter with its native code, which this example turns on where +# Luau has it. +[target.'cfg(all(any(target_os = "windows", target_os = "linux"), any(target_arch = "x86_64", target_arch = "aarch64")))'.dependencies] +rune-luau = { workspace = true, features = ["serde", "watch", "native-code"] } + +[target.'cfg(target_arch = "wasm32")'.dependencies] +wasm-bindgen = { workspace = true } + +[lints] +workspace = true diff --git a/app/vendor/rune/examples/luau-panel/demo.json b/app/vendor/rune/examples/luau-panel/demo.json new file mode 100644 index 0000000..0b77a37 --- /dev/null +++ b/app/vendor/rune/examples/luau-panel/demo.json @@ -0,0 +1,11 @@ +{"events": [ + {"t": 0.60, "type": "tap", "key": "pulse"}, + {"t": 1.60, "type": "tap", "key": "ping"}, + {"t": 2.20, "type": "tap", "x": 300, "y": 230}, + {"t": 2.80, "type": "scroll", "x": 360, "y": 400, "dy": -1800, "dur": 1.2}, + {"t": 4.40, "type": "tap", "x": 300, "y": 330}, + {"t": 5.00, "type": "tap", "key": "shuffle"}, + {"t": 5.60, "type": "scroll", "x": 360, "y": 400, "dy": -9000, "dur": 1.0}, + {"t": 7.20, "type": "scroll", "x": 360, "y": 400, "dy": 12000, "dur": 1.2}, + {"t": 9.00, "type": "mark", "name": "end"} +]} diff --git a/app/vendor/rune/examples/luau-panel/scripts/panel/init.luau b/app/vendor/rune/examples/luau-panel/scripts/panel/init.luau new file mode 100644 index 0000000..fec2a58 --- /dev/null +++ b/app/vendor/rune/examples/luau-panel/scripts/panel/init.luau @@ -0,0 +1,134 @@ +--!strict +-- A panel a Rune app hosts: a header that counts presses, a pulse driven by task.wait, a +-- signal, and a 1,000-row virtual list. Edit this file while the app runs: it reloads in place +-- and keeps the selection and counters (saveHotState / loadHotState). +local ui = require("@rune/ui") +local rows = require("@self/rows") + +local state = { + selected = 0, + presses = 0, + pulse = 0, + pings = 0, + shuffles = 0, +} + +local items = rows.items(1000) +local listVersion = 0 +local headerVersion = 0 +local pulsing: thread? = nil +local pinged = require("@rune/signal").new() + +local function changed(list: boolean) + headerVersion += 1 + if list then + listVersion += 1 + end +end + +pinged:Connect(function(n: number) + state.pings = n + changed(false) +end) + +local function select(i: number) + state.selected = i + state.presses += 1 + changed(true) +end + +local function pulse() + if pulsing then + task.cancel(pulsing) + end + pulsing = task.spawn(function() + for step = 10, 0, -1 do + state.pulse = step + changed(false) + task.wait(0.08) + end + pulsing = nil + end) +end + +local function button(key: string, label: string, onPress: () -> ()) + return ui.row({ + key = key, + px = 10, + py = 4, + radius = 6, + fill = "control-off", + hover = "hover", + press = "press", + onPress = onPress, + }, { ui.text(label, { size = 12, weight = "medium" }) }) +end + +local function header() + local selected = if state.selected > 0 then `#{state.selected}` else "none" + return ui.col({ key = "header", w = "full", px = 16, pt = 14, pb = 10, gap = 8 }, { + ui.row({ w = "full", gap = 8, align = "center" }, { + ui.text("Luau panel", { size = 15, weight = "semibold" }), + ui.spacer(), + ui.text(`{#items} rows · selected {selected} · {state.presses} presses`, { size = 12, color = "text-secondary" }), + }), + ui.row({ w = "full", gap = 6, align = "center" }, { + button("shuffle", "Shuffle", function() + state.shuffles += 1 + rows.shuffle(items, state.shuffles) + changed(true) + end), + button("pulse", "Pulse", pulse), + button("ping", "Ping", function() + pinged:Fire(state.pings + 1) + end), + ui.spacer(), + ui.box({ w = 120, h = 6, radius = 3, fill = "separator" }, { + ui.box({ w = state.pulse * 12, h = 6, radius = 3, fill = ui.hex("#009fff") }), + }), + ui.text(`{state.pings} pings`, { size = 12, color = "text-secondary", w = 60 }), + }), + }) +end + +local function render(view) + return ui.col({ key = "panel", w = "full", h = "full", fill = "bg" }, { + view:Memo("header", headerVersion, header), + ui.box({ w = "full", h = 1, fill = "separator" }), + ui.virtualList({ + key = "items", + w = "full", + grow = 1, + count = #items, + estimatedRowHeight = 28, + version = listVersion, + renderRow = function(i: number) + return rows.row(items[i], i == state.selected, function() + select(i) + end) + end, + }), + }) +end + +return { + render = render, + -- For the host: select a row, and read the selection. + select = select, + selected = function() + return state.selected + end, + -- A 20-row stateful panel: the rebuild the performance gate measures. + panel20 = function(view) + return rows.panel20(state.presses) + end, + saveHotState = function() + return state + end, + loadHotState = function(saved) + for k, v in saved do + state[k] = v + end + rows.shuffle(items, state.shuffles) + end, +} diff --git a/app/vendor/rune/examples/luau-panel/scripts/panel/rows.luau b/app/vendor/rune/examples/luau-panel/scripts/panel/rows.luau new file mode 100644 index 0000000..eece985 --- /dev/null +++ b/app/vendor/rune/examples/luau-panel/scripts/panel/rows.luau @@ -0,0 +1,75 @@ +--!strict +local ui = require("@rune/ui") + +export type Item = { id: number, name: string, size: number, done: boolean } + +local NAMES = { "alpha", "bravo", "charlie", "delta", "echo", "foxtrot", "golf", "hotel", "india", "juliet" } + +local function items(n: number): { Item } + local out = table.create(n) + for i = 1, n do + out[i] = { id = i, name = `{NAMES[(i - 1) % #NAMES + 1]} {i}`, size = (i * 7919) % 1000, done = i % 3 == 0 } + end + return out +end + +-- Reorders sizes deterministically for round `seed`. +local function shuffle(list: { Item }, seed: number) + for i, item in list do + item.size = (i * 7919 + seed * 104729) % 1000 + end +end + +local function row(item: Item, selected: boolean, onPress: () -> ()) + return ui.row({ + key = item.id, + w = "full", + h = 28, + px = 16, + gap = 10, + align = "center", + fill = if selected then "control-off" else nil, + hover = "hover", + onPress = onPress, + }, { + ui.text(`#{item.id}`, { size = 11, mono = true, color = "text-secondary", w = 44 }), + ui.text(item.name, { size = 13, grow = 1, truncate = true }), + ui.box({ w = 100, h = 4, radius = 2, fill = "separator" }, { + ui.box({ w = item.size / 10, h = 4, radius = 2, fill = ui.hex("#009fff") }), + }), + ui.text(if item.done then "done" else "open", { + size = 11, + color = if item.done then ui.hex("#30a46c") else "text-secondary", + w = 36, + }), + }) +end + +local LABELS = { + "Session", "Messages", "Provider", "Model", "Context limit", "Total tokens", "Usage", "Input tokens", + "Output tokens", "Reasoning tokens", "Cache read", "Cache write", "User messages", "Assistant messages", + "Total cost", "Created", "Last activity", "System prompt", "Tools", "Files", +} + +-- Twenty label/value/bar rows, values computed per build as a stats tab's would be. +local function panel20(seed: number) + local out = table.create(20) + for i = 1, 20 do + local value = (i * 7919 + seed * 31) % 100000 + out[i] = ui.row({ key = i, w = "full", h = 24, px = 16, gap = 8, align = "center" }, { + ui.text(LABELS[i], { size = 12, color = "text-secondary", w = 140 }), + ui.text(`{value // 1000},{string.format("%03d", value % 1000)}`, { size = 12, grow = 1, mono = true }), + ui.box({ w = 80, h = 4, radius = 2, fill = "separator" }, { + ui.box({ w = (value % 100) * 0.8, h = 4, radius = 2, fill = ui.hex("#009fff") }), + }), + }) + end + return ui.col({ key = "panel20", w = "full", py = 8 }, out) +end + +return { + items = items, + shuffle = shuffle, + row = row, + panel20 = panel20, +} diff --git a/app/vendor/rune/examples/luau-panel/src/bench.rs b/app/vendor/rune/examples/luau-panel/src/bench.rs new file mode 100644 index 0000000..6e5f71a --- /dev/null +++ b/app/vendor/rune/examples/luau-panel/src/bench.rs @@ -0,0 +1,272 @@ +//! The Luau performance gates, measured on this panel in a headless `Runtime`: the same code +//! natively (`luau-bench`) and in the browser (`luau_bench()`). + +use std::fmt; +use std::time::Duration; + +use rune::time::now; +use rune::{Env, Runtime}; +use rune_luau::{Data, Script, Sources}; + +use crate::{State, sources, view}; + +/// Iteration counts: the web gets fewer, and reports means over them (browsers coarsen timers). +#[derive(Clone, Copy, PartialEq)] +pub enum Scale { + Native, + Web, +} + +/// Microseconds. +#[derive(Clone, Copy, Default)] +pub struct Stat { + pub n: usize, + pub mean: f64, + pub p50: f64, + pub p99: f64, + pub max: f64, +} + +impl Stat { + fn of(mut samples: Vec<f64>) -> Stat { + if samples.is_empty() { + return Stat::default(); + } + samples.sort_by(f64::total_cmp); + let n = samples.len(); + let at = |q: f64| samples[((n - 1) as f64 * q).round() as usize]; + Stat { n, mean: samples.iter().sum::<f64>() / n as f64, p50: at(0.5), p99: at(0.99), max: samples[n - 1] } + } + + fn json(&self) -> String { + format!(r#"{{"n":{},"mean_us":{:.3},"p50_us":{:.3},"p99_us":{:.3},"max_us":{:.3}}}"#, self.n, self.mean, self.p50, self.p99, self.max) + } +} + +pub struct Report { + pub native_code: bool, + /// Idle frames polled, frames any of them asked for, and VM entries they made. + pub idle: (usize, usize, u64), + /// `Script::view` on a view rebuilt by host state only, and the VM entries those calls made. + pub memo_hit: (Stat, u64), + /// Wall time, and the time the thread ran (Windows). + pub rebuild20: (Stat, Option<Stat>), + /// Script time per 120 fps scroll frame, whole frame time, rows `renderRow` built. + pub scroll: (Stat, Stat, u64), + /// Compile + swap, compile, swap; whether hot state survived every reload. + pub reload: (Stat, Stat, Stat, bool), + pub checks: Vec<crate::checks::Check>, +} + +const SIZE: (f32, f32) = (720.0, 640.0); +const DT: f64 = 1.0 / 120.0; + +fn us(d: Duration) -> f64 { + d.as_secs_f64() * 1e6 +} + +pub fn run(scale: Scale) -> Report { + let n = if scale == Scale::Web { 300 } else { 1000 }; + Report { + native_code: rune_luau::NATIVE_CODE, + idle: idle(), + memo_hit: memo_hit(n), + rebuild20: rebuild20(n), + scroll: scroll(), + reload: reload(if scale == Scale::Web { 10 } else { 20 }), + checks: crate::checks::run(), + } +} + +/// A runtime showing the panel, polled and framed until nothing is left to do. +fn runtime() -> (Runtime<State>, f64) { + let mut rt = Runtime::new(State::new(Script::new("panel", sources())), view, SIZE, Env::new(true, 1.0)); + let mut now = 0.0; + rt.frame(0.0); + for _ in 0..600 { + now += DT; + let stale = rt.update_if(|s, tx| s.script.poll(now, tx)); + if !rt.frame(DT) && !stale { + break; + } + } + (rt, now) +} + +fn idle() -> (usize, usize, u64) { + let (mut rt, mut now) = runtime(); + let before = rt.state.script.metrics().vm_calls; + let frames = 1200; + let mut asked = 0; + for _ in 0..frames { + now += DT; + let stale = rt.update_if(|s, tx| s.script.poll(now, tx)); + if rt.frame(DT) || stale { + asked += 1; + } + } + (frames, asked, rt.state.script.metrics().vm_calls - before) +} + +fn memo_hit(n: usize) -> (Stat, u64) { + let (mut rt, _) = runtime(); + let mut calls = 0; + let mut samples = Vec::with_capacity(n); + for _ in 0..n { + rt.update(|s, _| s.host_ticks += 1); + rt.frame(DT); + samples.push(us(rt.state.view_time.get())); + calls += rt.state.view_calls.get(); + } + (Stat::of(samples), calls) +} + +/// Wall time, and (on Windows) the time the thread actually ran, which leaves out the time +/// other processes on a busy machine held its core. +fn rebuild20(n: usize) -> (Stat, Option<Stat>) { + let script = Script::new("panel20", sources()); + for _ in 0..50 { + drop(script.render_uncached::<State>("panel20", true)); + } + let per_us = cpu::cycles_per_us(); + let (mut wall, mut ran) = (Vec::with_capacity(n), Vec::with_capacity(n)); + for _ in 0..n { + let (start, cycles) = (now(), cpu::cycles()); + let el = script.render_uncached::<State>("panel20", true); + wall.push(us(start.elapsed())); + if let (Some(per_us), Some(a), Some(b)) = (per_us, cycles, cpu::cycles()) { + ran.push((b - a) as f64 / per_us); + } + drop(el); + } + (Stat::of(wall), (!ran.is_empty()).then(|| Stat::of(ran))) +} + +/// The thread's cycle count (`QueryThreadCycleTime`), and its rate, measured against the clock. +mod cpu { + #[cfg(windows)] + #[allow(unsafe_code)] + pub fn cycles() -> Option<u64> { + unsafe extern "system" { + fn GetCurrentThread() -> isize; + fn QueryThreadCycleTime(thread: isize, cycles: *mut u64) -> i32; + } + let mut c = 0; + // SAFETY: the pseudo-handle for this thread, and a valid out pointer. + (unsafe { QueryThreadCycleTime(GetCurrentThread(), &mut c) } != 0).then_some(c) + } + + #[cfg(not(windows))] + pub fn cycles() -> Option<u64> { + None + } + + /// The fastest of a few 20 ms spins: a spin the scheduler interrupted reads slow. + pub fn cycles_per_us() -> Option<f64> { + (0..5) + .filter_map(|_| { + let (start, c0) = (rune::time::now(), cycles()?); + while start.elapsed().as_millis() < 20 { + std::hint::spin_loop(); + } + Some((cycles()? - c0) as f64 / (start.elapsed().as_secs_f64() * 1e6)) + }) + .reduce(f64::max) + } +} + +fn scroll() -> (Stat, Stat, u64) { + let (mut rt, _) = runtime(); + let rows_before = rt.state.script.metrics().rows; + let (mut script, mut frame) = (Vec::new(), Vec::new()); + // 40 points a frame at 120 fps (4,800 pt/s): one or two new rows enter most frames. + for _ in 0..360 { + let m = rt.state.script.metrics(); + let start = now(); + rt.wheel(360.0, 400.0, -40.0); + rt.frame(DT); + frame.push(us(start.elapsed())); + script.push(us(rt.state.script.metrics().vm_time - m.vm_time)); + } + (Stat::of(script), Stat::of(frame), rt.state.script.metrics().rows - rows_before) +} + +fn reload(n: usize) -> (Stat, Stat, Stat, bool) { + let script = Script::new("panel", sources()); + script.call("select", [Data::Number(7.0)]).ok(); + let base = sources(); + let init = base.get("init.luau").unwrap_or_default().to_owned(); + let (mut total, mut compile, mut swap) = (Vec::new(), Vec::new(), Vec::new()); + let mut kept = true; + for i in 0..n { + let edited: Sources = base.clone().with("init.luau", format!("{init}\n-- edit {i}\n")); + match script.reload(edited) { + Ok(r) => { + total.push(us(r.compile + r.swap)); + compile.push(us(r.compile)); + swap.push(us(r.swap)); + } + Err(e) => { + kept = false; + eprintln!("reload failed: {e}"); + } + } + kept &= script.query("selected", []).ok().and_then(|d| d.as_f64()) == Some(7.0); + } + (Stat::of(total), Stat::of(compile), Stat::of(swap), kept) +} + +impl Report { + pub fn json(&self) -> String { + format!( + concat!( + r#"{{"native_code":{},"idle":{{"frames":{},"frames_asked":{},"vm_calls":{}}},"#, + r#""memo_hit":{{"view":{},"vm_calls":{}}},"rebuild20":{},"rebuild20_thread_time":{},"#, + r#""scroll":{{"script_per_frame":{},"frame":{},"rows_built":{}}},"#, + r#""reload":{{"total":{},"compile":{},"swap":{},"state_kept":{}}},"checks":[{}]}}"# + ), + self.native_code, + self.idle.0, + self.idle.1, + self.idle.2, + self.memo_hit.0.json(), + self.memo_hit.1, + self.rebuild20.0.json(), + self.rebuild20.1.map_or("null".to_owned(), |s| s.json()), + self.scroll.0.json(), + self.scroll.1.json(), + self.scroll.2, + self.reload.0.json(), + self.reload.1.json(), + self.reload.2.json(), + self.reload.3, + self.checks + .iter() + .map(|c| format!(r#"{{"name":{:?},"ok":{},"detail":{:?}}}"#, c.name, c.ok, c.detail)) + .collect::<Vec<_>>() + .join(","), + ) + } +} + +impl fmt::Display for Report { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let row = |name: &str, s: &Stat, gate: &str| format!("{name:<34} n={:<5} mean {:>9.2} µs p50 {:>9.2} p99 {:>9.2} max {:>9.2} gate {gate}", s.n, s.mean, s.p50, s.p99, s.max); + writeln!(f, "Luau {}", if self.native_code { "native code (luau-jit)" } else { "interpreter" })?; + writeln!(f, "idle: {} frames polled, {} asked for a frame, {} VM calls (gate: 0)", self.idle.0, self.idle.1, self.idle.2)?; + writeln!(f, "{} VM calls {}", row("memo hit (Script::view)", &self.memo_hit.0, "≤ 5 µs"), self.memo_hit.1)?; + writeln!(f, "{}", row("20-row panel rebuild", &self.rebuild20.0, "≤ 120 µs"))?; + if let Some(s) = &self.rebuild20.1 { + writeln!(f, "{}", row("20-row panel rebuild, thread time", s, "≤ 120 µs"))?; + } + writeln!(f, "{}", row("scroll frame, script time", &self.scroll.0, "≤ 300 µs"))?; + writeln!(f, "{} rows built {}", row("scroll frame, whole frame", &self.scroll.1, "—"), self.scroll.2)?; + writeln!(f, "{}", row("hot reload, compile + swap", &self.reload.0, "≤ 5,000 µs"))?; + writeln!(f, "{}", row("hot reload, compile", &self.reload.1, "—"))?; + writeln!(f, "{} state kept {}", row("hot reload, swap", &self.reload.2, "—"), self.reload.3)?; + for c in &self.checks { + writeln!(f, "check {:<24} {} {}", c.name, if c.ok { "ok " } else { "FAIL" }, c.detail)?; + } + Ok(()) + } +} diff --git a/app/vendor/rune/examples/luau-panel/src/bin/bench.rs b/app/vendor/rune/examples/luau-panel/src/bin/bench.rs new file mode 100644 index 0000000..94e6726 --- /dev/null +++ b/app/vendor/rune/examples/luau-panel/src/bin/bench.rs @@ -0,0 +1,10 @@ +//! `cargo run -p luau-panel --bin luau-bench --profile perf`: the Luau performance gates, +//! measured headless on the example panel. Prints a table, then the numbers as JSON. + +#![forbid(unsafe_code)] + +fn main() { + let report = luau_panel::bench::run(luau_panel::bench::Scale::Native); + println!("{report}"); + println!("{}", report.json()); +} diff --git a/app/vendor/rune/examples/luau-panel/src/checks.rs b/app/vendor/rune/examples/luau-panel/src/checks.rs new file mode 100644 index 0000000..20c64b4 --- /dev/null +++ b/app/vendor/rune/examples/luau-panel/src/checks.rs @@ -0,0 +1,129 @@ +//! Behaviour the panel doesn't exercise, shown on small scripts: the watchdog, a failing render, +//! `require` by Luau's rules, a cycle, numbers crossing to Rust, and a host signal and async +//! call. Printed by `luau-bench` and `luau_bench()` next to the performance numbers. + +use std::time::Duration; + +use rune::time::now; +use rune_luau::mlua::Value; +use rune_luau::{Data, ErrorKind, Script, ScriptOptions, Sources}; + +use crate::State; + +pub struct Check { + pub name: &'static str, + pub ok: bool, + pub detail: String, +} + +pub fn run() -> Vec<Check> { + vec![watchdog(), render_error(), require_rules(), require_cycle(), numbers(), host_signal_and_async()] +} + +fn check(name: &'static str, ok: bool, detail: impl Into<String>) -> Check { + Check { name, ok, detail: detail.into() } +} + +/// `while true do end` stops at the 250 ms limit with a timeout, and the script keeps working. +fn watchdog() -> Check { + let script = Script::new("spin", Sources::single("return { spin = function() while true do end end, ok = function() return 1 end }")); + let start = now(); + let err = script.query("spin", []).err(); + let took = start.elapsed(); + let still = script.query("ok", []).ok().and_then(|d| d.as_i64()); + let ok = err.as_ref().is_some_and(|e| e.kind == ErrorKind::Timeout) && took < Duration::from_millis(260) && still == Some(1); + check("watchdog", ok, format!("stopped after {:.1} ms ({:?}); the next call returned {still:?}", took.as_secs_f64() * 1e3, err.map(|e| e.kind))) +} + +/// A render that raises shows the error card instead of panicking, and the log has the error. +fn render_error() -> Check { + let script = Script::new("broken", Sources::single("local ui = require('@rune/ui')\nreturn function() local t = nil; return ui.text(t.field) end")); + let el = script.render_uncached::<State>("render", true); + drop(el); + let logged = script.log().iter().any(|l| l.message.contains("attempt to index nil")); + check("render error", logged, script.log().last().map(|l| l.message.lines().next().unwrap_or_default().to_owned()).unwrap_or_default()) +} + +/// Luau's rules: from `init.luau` (which stands for its folder), `@self/x` is `x.luau` in the +/// folder and `./x` would be beside the folder, so it fails; from `views/row.luau`, `./util` +/// is `views/util.luau`, and the folder's `.luaurc` alias `@lib` resolves. +fn require_rules() -> Check { + let sources = Sources::new() + .with("init.luau", "local row = require('@self/views/row')\nlocal escaped = pcall(require, './views/row')\nreturn { probe = function() return row .. '|' .. tostring(escaped) end }") + .with("views/row.luau", "return 'row+' .. require('./util') .. '+' .. require('@lib/util')") + .with("views/util.luau", "return 'util'") + .with(".luaurc", r#"{ "aliases": { "lib": "./views" } }"#); + let script = Script::new("req", sources); + let got = script.query("probe", []).map(|d| d.as_str().unwrap_or_default().to_owned()).unwrap_or_else(|e| e.message); + check("require", got == "row+util+util|false", got) +} + +fn require_cycle() -> Check { + let sources = Sources::new().with("init.luau", "return require('@self/a')").with("a.luau", "return require('./b')").with("b.luau", "return require('./a')"); + let script = Script::new("cycle", sources); + let err = script.error().map(|e| e.message).unwrap_or_default(); + check("require cycle", err.contains("require cycle: init.luau -> a.luau -> b.luau -> a.luau"), err.lines().next().unwrap_or_default().to_owned()) +} + +/// Whole numbers come across as integers, through `Data` and through mlua's serde. +fn numbers() -> Check { + let script = Script::new("nums", Sources::single("return { values = function() return { small = 3, big = 2^40, half = 2.5 } end }")); + let data = script.query("values", []).unwrap_or_default(); + let via_data = (data.get("small").as_i64(), data.get("big").as_i64(), data.get("half").as_f64()); + let serde = script.with_lua(|lua| { + use rune_luau::mlua::LuaSerdeExt; + let t: Value = lua.load("return { small = 3, big = 2^40 }").eval().unwrap_or(Value::Nil); + let small = lua.from_value::<std::collections::HashMap<String, i64>>(t.clone()).map_err(|e| e.to_string()); + small.map(|m| (m.get("small").copied(), m.get("big").copied())) + }); + #[derive(serde::Deserialize, Debug, PartialEq)] + struct Values { + small: i64, + big: i64, + half: f64, + } + let decoded = data.decode::<Values>().map_err(|e| e.to_string()); + let ok = via_data == (Some(3), Some(1 << 40), Some(2.5)) && decoded == Ok(Values { small: 3, big: 1 << 40, half: 2.5 }); + check("numbers", ok, format!("Data: {via_data:?}; Data::decode: {decoded:?}; mlua serde into i64: {serde:?}")) +} + +/// A host signal fires into a connection, and a host async call resumes its task. +fn host_signal_and_async() -> Check { + let options = ScriptOptions::new().setup(|host| { + let signal = host.signal("changed")?; + let double = host.async_function("double", |_, args, done| { + let n = match args.front() { + Some(Value::Integer(i)) => *i as f64, + Some(Value::Number(n)) => *n, + _ => 0.0, + }; + rune_luau::spawn_blocking(move || done.complete(n * 2.0)); + Ok(()) + })?; + let module = host.lua().create_table()?; + module.raw_set("changed", signal)?; + module.raw_set("double", double)?; + host.register_module("@app/host", module) + }); + let src = "local host = require('@app/host')\nlocal seen = {}\nhost.changed:Connect(function(v) seen.signal = v end)\nreturn { start = function() seen.async = host.double(21) end, seen = function() return seen end }"; + let script = Script::with_options("host", Sources::single(src), options); + script.fire("changed", [Data::from("hello")]); + script.call("start", []).ok(); + // The async result arrives on a worker thread; poll until the task resumes. + let mut rt = rune::Runtime::new((), |_: &(), _: &mut rune::Cx<()>| rune::el(), (10.0, 10.0), rune::Env::new(true, 1.0)); + let mut now = 0.0; + for _ in 0..200 { + now += 1.0 / 120.0; + rt.update_if(|_, tx| script.poll(now, tx)); + if script.query("seen", []).ok().is_some_and(|d| d.get("async") != &Data::Nil) { + break; + } + // On the web the result arrives in a microtask, after this synchronous loop. + #[cfg(not(target_arch = "wasm32"))] + std::thread::sleep(Duration::from_millis(1)); + } + let seen = script.query("seen", []).unwrap_or_default(); + let async_done = seen.get("async").as_i64() == Some(42) || cfg!(target_arch = "wasm32"); + let ok = seen.get("signal").as_str() == Some("hello") && async_done; + check("host signal and async", ok, format!("{seen:?} {:?}", script.log().iter().map(|l| l.message.clone()).collect::<Vec<_>>())) +} diff --git a/app/vendor/rune/examples/luau-panel/src/lib.rs b/app/vendor/rune/examples/luau-panel/src/lib.rs new file mode 100644 index 0000000..b25ce45 --- /dev/null +++ b/app/vendor/rune/examples/luau-panel/src/lib.rs @@ -0,0 +1,88 @@ +//! A Rune app hosting a Luau script (`scripts/panel`): a header with buttons, a pulse driven +//! by `task.wait`, a signal, and a 1,000-row `ui.virtualList`. Native builds watch the script +//! folder, so saving a `.luau` file reloads the panel in place. The same script runs on the web: +//! `scripts/web-build.sh luau-panel` (with `WASI_SDK_PATH` set). +//! +//! `cargo run -p luau-panel`; `cargo run -p luau-panel --bin luau-bench --profile perf` measures +//! the performance gates (idle, memo hit, 20-row rebuild, list scroll, hot reload). + +use std::cell::Cell; +use std::time::Duration; + +use rune::time::now; +use rune::{AppSpec, Cx, El, Tx, Waker, col}; +use rune_luau::{Script, Sources}; + +pub mod bench; +pub mod checks; + +pub struct State { + pub script: Script, + /// Host state the script doesn't read: bumping it re-runs the view, not the script. + pub host_ticks: u64, + /// How long the last `Script::view` call took, and the VM entries it made. + pub view_time: Cell<Duration>, + pub view_calls: Cell<u64>, +} + +impl State { + pub fn new(script: Script) -> Self { + State { script, host_ticks: 0, view_time: Cell::new(Duration::ZERO), view_calls: Cell::new(0) } + } +} + +/// The panel's files, built into the binary. +pub fn sources() -> Sources { + Sources::new() + .with("init.luau", include_str!("../scripts/panel/init.luau")) + .with("rows.luau", include_str!("../scripts/panel/rows.luau")) +} + +fn init() -> State { + #[cfg(not(target_arch = "wasm32"))] + { + let dir = concat!(env!("CARGO_MANIFEST_DIR"), "/scripts/panel"); + if let Ok(sources) = Sources::from_dir(dir) { + let options = rune_luau::ScriptOptions::new().on_log(|level, line| eprintln!("luau-panel {level:?}: {line}")); + let script = Script::with_options("panel", sources, options); + if let Err(e) = script.watch(dir) { + eprintln!("luau-panel: not watching {dir}: {e}"); + } + return State::new(script); + } + } + State::new(Script::new("panel", sources())) +} + +pub fn view(s: &State, cx: &mut Cx<State>) -> El { + let calls = s.script.metrics().vm_calls; + let start = now(); + let panel = s.script.view(cx); + s.view_time.set(start.elapsed()); + s.view_calls.set(s.script.metrics().vm_calls - calls); + col().w_full().h_full().child(panel) +} + +fn setup(s: &mut State, waker: Waker) { + s.script.set_waker(waker); +} + +fn poll(s: &mut State, now: f64, tx: &mut Tx) -> bool { + s.script.poll(now, tx) +} + +pub fn spec() -> AppSpec<State> { + AppSpec { setup: Some(setup), poll: Some(poll), ..AppSpec::new("Luau panel", (720.0, 640.0), init, view) } +} + +#[cfg_attr(target_arch = "wasm32", wasm_bindgen::prelude::wasm_bindgen(start))] +pub fn start() { + rune::run(spec()); +} + +/// Runs the performance measurements in the page and returns them as JSON. +#[cfg(target_arch = "wasm32")] +#[wasm_bindgen::prelude::wasm_bindgen] +pub fn luau_bench() -> String { + bench::run(bench::Scale::Web).json() +} diff --git a/app/vendor/rune/examples/luau-panel/src/main.rs b/app/vendor/rune/examples/luau-panel/src/main.rs new file mode 100644 index 0000000..d079c96 --- /dev/null +++ b/app/vendor/rune/examples/luau-panel/src/main.rs @@ -0,0 +1,5 @@ +#![forbid(unsafe_code)] + +fn main() { + luau_panel::start(); +} diff --git a/app/vendor/rune/examples/luau-panel/web-proof.mjs b/app/vendor/rune/examples/luau-panel/web-proof.mjs new file mode 100644 index 0000000..750172a --- /dev/null +++ b/app/vendor/rune/examples/luau-panel/web-proof.mjs @@ -0,0 +1,89 @@ +// Browser proof for luau-panel: the Luau panel renders in Rune's web build, rests at zero frames, +// scrolls its 1,000-row list, answers presses, and reports the interpreter's performance numbers. +// Requires Playwright. Usage: node web-proof.mjs [web dir] [output dir] +// (build first: scripts/web-build.sh luau-panel --out target/web-luau, with WASI_SDK_PATH set). +import assert from 'node:assert/strict'; +import { createServer } from 'node:http'; +import { readFile, mkdir, writeFile } from 'node:fs/promises'; +import { resolve, extname, sep } from 'node:path'; +const { chromium } = await import(process.env.PLAYWRIGHT_MODULE || 'playwright'); +const root = resolve(process.argv[2] || 'target/web-luau'); +const output = resolve(process.argv[3] || 'target/web-luau-proof'); +await mkdir(output, { recursive: true }); +const server = createServer(async (request, response) => { + if (request.url === '/favicon.ico') { response.writeHead(204).end(); return; } + const path = resolve(root, '.' + new URL(request.url, 'http://localhost').pathname.replace(/\/$/, '/index.html')); + if (!path.startsWith(root + sep)) { response.writeHead(403).end(); return; } + try { + const bytes = await readFile(path); + response.setHeader('Content-Type', ({ '.wasm': 'application/wasm', '.js': 'text/javascript', '.html': 'text/html' })[extname(path)] || 'application/octet-stream'); + response.end(bytes); + } catch { response.writeHead(404).end(); } +}); +await new Promise(done => server.listen(0, '127.0.0.1', done)); +const browser = await chromium.launch({ headless: true, executablePath: process.env.CHROMIUM_PATH, args: ['--enable-unsafe-webgpu'] }); +const errors = []; +const log = []; +try { + const context = await browser.newContext({ viewport: { width: 720, height: 640 }, deviceScaleFactor: 1, colorScheme: 'dark', + recordVideo: { dir: output, size: { width: 720, height: 640 } } }); + const page = await context.newPage(); + page.on('pageerror', error => errors.push(error.message)); + page.on('console', message => { log.push(`${message.type()}: ${message.text()}`); if (message.type() === 'error') errors.push(message.text()); }); + await page.addInitScript(() => { + Error.stackTraceLimit = 100; + window.__proof = { submits: 0, rafs: 0 }; + const raf = window.requestAnimationFrame; + window.requestAnimationFrame = callback => { window.__proof.rafs++; return raf.call(window, callback); }; + if (!globalThis.GPUQueue) return; + const submit = GPUQueue.prototype.submit; + GPUQueue.prototype.submit = function (...args) { window.__proof.submits++; return submit.apply(this, args); }; + }); + await page.goto(`http://127.0.0.1:${server.address().port}`); + await page.waitForFunction(() => window.__proof?.submits > 0, null, { timeout: 60000 }).catch(async error => { + console.log(log.join('\n'), errors.join('\n'), await page.locator('body').innerText()); + throw error; + }); + await page.waitForTimeout(1500); + const counts = () => page.evaluate(() => ({ ...window.__proof })); + const idle = async ms => { const a = await counts(); await page.waitForTimeout(ms); const b = await counts(); return { submits: b.submits - a.submits, rafs: b.rafs - a.rafs, ms }; }; + const result = { idle: await idle(3000) }; + await page.screenshot({ path: `${output}/01-loaded.png` }); + + // Scroll the 1,000-row list: 120 wheel steps of 40 px, one per frame. + const before = await counts(); + await page.mouse.move(360, 400); + for (let i = 0; i < 120; i++) { await page.mouse.wheel(0, 40); await page.waitForTimeout(8); } + await page.waitForTimeout(500); + result.scroll = { submits: (await counts()).submits - before.submits }; + await page.screenshot({ path: `${output}/02-scrolled.png` }); + result.idleAfterScroll = await idle(2000); + + // Press a row, then Pulse (a task.wait countdown), then Ping (a signal). + await page.mouse.click(300, 300); + await page.waitForTimeout(300); + await page.screenshot({ path: `${output}/03-selected.png` }); + await page.mouse.click(110, 52); + await page.waitForTimeout(300); + await page.screenshot({ path: `${output}/04-pulsing.png` }); + await page.waitForTimeout(1500); + await page.mouse.click(160, 52); + await page.waitForTimeout(300); + await page.screenshot({ path: `${output}/05-pinged.png` }); + result.idleAfterTasks = await idle(2000); + + // The interpreter's numbers, measured in this page by the same code as the native bench. + result.bench = JSON.parse(await page.evaluate(async () => (await import('./app.js')).luau_bench())); + result.errors = errors; + await writeFile(`${output}/web-proof.json`, JSON.stringify(result, null, 2)); + await writeFile(`${output}/console.txt`, log.join('\n')); + console.log(JSON.stringify(result, null, 2)); + assert.equal(result.idle.submits, 0, 'an idle page draws nothing'); + assert.ok(result.scroll.submits > 30, 'scrolling draws'); + assert.equal(result.idleAfterTasks.submits, 0, 'the page rests after its tasks finish'); + assert.deepEqual(errors, []); + await context.close(); +} finally { + await browser.close(); + server.close(); +} diff --git a/app/vendor/rune/examples/matched/Cargo.toml b/app/vendor/rune/examples/matched/Cargo.toml new file mode 100644 index 0000000..d66edb1 --- /dev/null +++ b/app/vendor/rune/examples/matched/Cargo.toml @@ -0,0 +1,12 @@ +[package] +name = "matched" +version = "0.0.1" +edition.workspace = true +license.workspace = true +publish = false + +[dependencies] +rune = { workspace = true, default-features = true, features = ["keys-overlay"] } + +[lints] +workspace = true diff --git a/app/vendor/rune/examples/matched/scripts/zoom.json b/app/vendor/rune/examples/matched/scripts/zoom.json new file mode 100644 index 0000000..ce1dffa --- /dev/null +++ b/app/vendor/rune/examples/matched/scripts/zoom.json @@ -0,0 +1,8 @@ +[ + {"t":0.3,"type":"key","name":"2"}, + {"t":0.6,"type":"key","name":"Enter"}, + {"t":1.7,"type":"key","name":"Escape"}, + {"t":2.8,"type":"key","name":"Enter"}, + {"t":2.98,"type":"key","name":"Escape"}, + {"t":3.12,"type":"key","name":"Enter"} +] diff --git a/app/vendor/rune/examples/matched/src/main.rs b/app/vendor/rune/examples/matched/src/main.rs new file mode 100644 index 0000000..5e551a6 --- /dev/null +++ b/app/vendor/rune/examples/matched/src/main.rs @@ -0,0 +1,130 @@ +//! Shared-element motion with `El::matched`: a 2×2 grid of picture tiles. 1–4 picks a tile, ↩ +//! (or a click) zooms it to the whole stage and Esc zooms it back. Both places are plain flex +//! layout; the tile flies between them because both carry the same `matched` id. +//! +//! ```sh +//! cargo run -p matched +//! cargo run -p matched -- --script examples/matched/scripts/zoom.json --frames 240 --out frames +//! ``` + +#![forbid(unsafe_code)] + +use rune::tok::{self, type_}; +use rune::{AppSpec, Color, Cx, El, Key, KeyEvent, Pixels, SurfaceFit, TextStyle, Transition, Tx, col, el, row, text}; + +struct State { + picked: usize, + zoomed: bool, + pictures: [Pixels; 4], +} + +/// Sky, ground and sun colours of each tile's picture, as sRGB bytes. +const SCENES: [([u8; 3], [u8; 3], [u8; 3]); 4] = [ + ([255, 166, 120], [58, 40, 92], [255, 236, 170]), + ([120, 200, 255], [30, 90, 70], [255, 255, 235]), + ([196, 150, 255], [40, 30, 70], [255, 200, 240]), + ([255, 214, 120], [120, 60, 30], [255, 250, 220]), +]; + +const NAMES: [&str; 4] = ["Dusk", "Lake", "Haze", "Dune"]; + +fn picture(i: usize) -> Pixels { + let (w, h) = (320u32, 240u32); + let (sky, ground, sun) = SCENES[i]; + let mix = |a: [u8; 3], b: [u8; 3], t: f32| a.map(|v| v as f32).iter().zip(b).map(|(a, b)| a + (b as f32 - a) * t).collect::<Vec<_>>(); + let mut rgba = Vec::with_capacity((w * h * 4) as usize); + for y in 0..h { + for x in 0..w { + let (u, v) = (x as f32 / w as f32, y as f32 / h as f32); + let horizon = 0.62 + 0.04 * (u * 6.0 + i as f32).sin(); + // Ground coverage of this pixel, anti-aliased over one pixel row. + let land = ((v - horizon) * h as f32 + 0.5).clamp(0.0, 1.0); + let air = mix(sky, ground, (v / horizon).min(1.0).powf(2.2) * 0.5); + let d = ((u - 0.3 - 0.12 * i as f32).powi(2) + ((v - 0.42) * 0.75).powi(2)).sqrt(); + let glow = (1.0 - (d / 0.16)).clamp(0.0, 1.0).powf(0.6); + let air: Vec<f32> = air.iter().zip(sun).map(|(a, b)| a + (b as f32 - a) * glow).collect(); + let soil = mix(ground, [10, 10, 16], (v - horizon).max(0.0) * 1.6); + rgba.extend(air.iter().zip(soil).map(|(a, s)| (a + (s - a) * land).clamp(0.0, 255.0) as u8)); + rgba.push(255); + } + } + let p = Pixels::new(); + p.set(w, h, rgba); + p +} + +fn init() -> State { + State { picked: 0, zoomed: false, pictures: std::array::from_fn(picture) } +} + +fn tile(s: &State, i: usize) -> El { + let id = format!("tile-{}", i + 1); + let mut t = el().key(id.as_str()).matched(id.as_str()).grow(1.0).radius(20.0).clip_rounded(20.0) + .fill(Color::BLACK) + .on_press(move |s: &mut State| { + if s.zoomed { s.zoomed = false } else { (s.picked, s.zoomed) = (i, true) } + }) + .child(el().w_full().h_full().pixels_fit(&s.pictures[i], SurfaceFit::Fill)) + .child(text(format!("{} {}", i + 1, NAMES[i])).font(TextStyle::new(22.0, 600.0)).color(Color::WHITE).absolute(18.0, 14.0)); + if s.picked == i { + t = t.child(el().absolute(0.0, 0.0).w_full().h_full().radius(20.0).border(3.0, Color::WHITE)); + } + t +} + +fn view(s: &State, _: &mut Cx<State>) -> El { + let theme = tok::theme(true); + let hint = text("1–4 pick ↩ zoom esc back").font(type_::LABEL).color(theme.text_secondary); + let stage = col().key("stage").w_full().grow(1.0); + let stage = if s.zoomed { + stage.child(tile(s, s.picked)) + } else { + // The grid's own entrance and exit; the matched tile rides above it. + let pair = |a: usize| row().key(format!("row-{a}")).grow(1.0).gap(12.0).child(tile(s, a)).child(tile(s, a + 1)); + stage.child(col().key("grid").grow(1.0).gap(12.0).transition(Transition::scale(0.96)) + .child(pair(0)).child(pair(2))) + }; + col().w_full().h_full().padding(24.0).gap(14.0).fill(theme.bg).child(hint).child(stage) +} + +fn on_key(s: &mut State, e: &KeyEvent, _: &mut Tx) -> bool { + match &e.key { + Key::Text(t) if !s.zoomed && let Some(n @ 1..=4) = t.parse::<usize>().ok() => s.picked = n - 1, + Key::Enter => s.zoomed = true, + Key::Escape => s.zoomed = false, + _ => return false, + } + true +} + +fn main() { + rune::run(AppSpec::<State> { + scenes: &[("grid", |_| {}), ("one", |s| s.zoomed = true)], + on_key: Some(on_key), + ..AppSpec::new("Matched", (720.0, 480.0), init, view) + }); +} + +#[cfg(test)] +mod tests { + use super::*; + use rune::{Env, Runtime}; + + #[test] + fn enter_zooms_the_picked_tile_from_its_grid_cell() { + let mut rt = Runtime::new(init(), view, (720.0, 480.0), Env::new(true, 2.0)); + rt.frame(0.0); + rt.update(|s, _| s.picked = 3); + rt.frame(1.0 / 60.0); + let cell = rt.presented("tile-4").unwrap().0; + rt.update(|s, _| s.zoomed = true); + rt.frame(1.0 / 120.0); + let first = rt.presented("tile-4").unwrap().0; + assert!((first[0] - cell[0]).abs() < 8.0 && (first[2] - cell[2]).abs() < 8.0, "{cell:?} -> {first:?}"); + for _ in 0..120 { + rt.frame(1.0 / 60.0); + } + let one = rt.presented("tile-4").unwrap().0; + assert!(one[2] > 600.0 && one[3] > 350.0, "fills the stage: {one:?}"); + } +} diff --git a/app/vendor/rune/examples/motion-bento/Cargo.toml b/app/vendor/rune/examples/motion-bento/Cargo.toml new file mode 100644 index 0000000..7b5d1d0 --- /dev/null +++ b/app/vendor/rune/examples/motion-bento/Cargo.toml @@ -0,0 +1,14 @@ +[package] +name = "motion-bento" +version = "0.0.1" +edition.workspace = true +license.workspace = true +publish = false + +[dependencies] +rune = { workspace = true, default-features = true, features = ["keys-overlay"] } +rune-kit = { workspace = true, default-features = true } +motion-bento-chaos = { path = "chaos" } + +[lints] +workspace = true diff --git a/app/vendor/rune/examples/motion-bento/README.md b/app/vendor/rune/examples/motion-bento/README.md new file mode 100644 index 0000000..ce8cd1a --- /dev/null +++ b/app/vendor/rune/examples/motion-bento/README.md @@ -0,0 +1,82 @@ +# Motion bento + +A 1440×900 control center whose twelve tiles all move at once: a segmented scene picker, a +thermostat ring, light switches, mixer faders, an XY pad, a card deck, an activity feed, and a +bottom row of five tiles that reflow around whichever one has focus. A seeded chaos schedule taps +them (a few times a second, with bursts of six to twelve taps 30–60 ms apart), so nearly every +frame has springs in flight. + +`chaos/` (`motion-bento-chaos`) holds everything that isn't Rune: the model, the schedule, the +look (colours, grid, spring tunings) and the frame meter. It has no Rune dependency, so another +toolkit can build the same window and play the same schedule. + +```sh +cargo run -p motion-bento --profile perf -- --seed 7 --duration 30 --intensity 1.5 --hud +``` + +| Flag | Default | | +| --- | --- | --- | +| `--seed N` | 1 | Names one schedule, and every random choice its taps make. | +| `--duration S` | 20 | Seconds of chaos. The window quits a second later. Rune's headless runs read it too. | +| `--intensity X` | 1 | Scales the rate of taps: 2 is twice as many. | +| `--variant NAME` | `default` | Spring tuning: `default`, `bouncy` or `stiff`. | +| `--metrics PATH` | | Write the frame meter's JSON when the run ends (a headless run: at `--duration` + 1 s). | +| `--hud` | off | Show the frame meter from the start. `H` toggles it. | +| `--stay` | off | Keep the window open after the schedule ends. | +| `--emit-script PATH` | | Write the schedule as a Rune headless script and exit. | +| `--load N` | | Stress mode: a wall of N live controls instead of the bento. | +| `--ramp A:B` | | Stress mode, growing from A to B controls by ×√2 a step. Sets `--duration` unless given. | +| `--hold S` | 2.5 | Seconds a ramp spends at each step. | +| `--naive` | off | Stress mode: build the whole wall again every frame instead of binding live values. | +| `--frames PATH` | | Write every frame as CSV when the run ends: show time, load, build, work, start, and CPU time since the frame before (thread and process). | +| `--hud-from PATH` | | Stress mode: the HUD replays a `--frames` CSV from an earlier run, so a capture run shows what a clean run measured at the same moment. | + +## Stress mode + +`--load` and `--ramp` swap the bento for a wall of controls (`chaos/src/stress.rs`): each a card +with a glowing status dot, a name, a status word, a reading that changes every frame, a +percentage, eight gradient bars that retarget every few hundred milliseconds, a progress track +and a switch. The wall reshuffles every 2 s, one in twelve controls goes double width (reselected +every 1.7 s), hues and statuses change on their own clocks, and a new control scales and fades in. +What the wall shows is a pure function of the seed, the show time and the load, so the GPUI build +draws the same wall frame for frame. + +```sh +motion-bento --seed 7 --ramp 32:1024 --frames ramp.csv --snap end.png --at 29.6 --size 1440x900 --scale 2 --fps 120 +``` + +With `--hud`, the header shows a frame-time readout and graph against the 120 Hz and 60 Hz budgets. + +The wall is built the way a Rune app should build it (`src/stress/live.rs`): each card's inside is +a `memo` built once per size, and its reading, bars, switch, progress and colours are `Live` +values that `poll` sets, so the view runs and commits only when the wall reshuffles or grows. +`--naive` (`src/stress/naive.rs`) rebuilds every card every frame, as a first port would. + +## Headless + +Every action is a tap on a keyed element (`Action::key`), so the schedule is also a script: + +```sh +motion-bento --seed 7 --duration 8 --emit-script chaos.json +motion-bento --seed 7 --duration 8 --script chaos.json --video bento.mp4 --size 1440x900 +motion-bento --seed 7 --duration 8 --script chaos.json --tree end.json --at mark:end +``` + +With a script, the window plays its taps instead of the schedule, and both reach the same state +(`script_taps_reach_the_same_state_as_the_schedule`). + +## The meter + +Measured from `App::on_frame_encoded`, for drawn frames only: + +- **work**: `update_ms + encode_ms`, from the frame's start (after its drawable came) until its + commands were submitted: events, `poll`, the view, layout, paint, uploads and encode. CPU wall + time, not GPU time. +- **build**: `update_ms` alone: events, `poll`, the view, layout and paint, without the encode. + The GPUI build can only time this part, so compare GPUI with this number. +- **interval**: time between frame starts. A display-paced window starts each frame on a refresh, + so this is the gap between frames on screen. +- **late**: intervals over 1.5 refreshes (`FrameEncoded::refresh_hz`), and the refreshes they + skipped. Gaps over 100 ms are the window resting, not late frames. +- **CPU** and **footprint**: process CPU time over the run's wall time, and the physical footprint, + from `procwatch`. diff --git a/app/vendor/rune/examples/motion-bento/chaos/Cargo.toml b/app/vendor/rune/examples/motion-bento/chaos/Cargo.toml new file mode 100644 index 0000000..e73b78d --- /dev/null +++ b/app/vendor/rune/examples/motion-bento/chaos/Cargo.toml @@ -0,0 +1,19 @@ +[package] +name = "motion-bento-chaos" +version = "0.0.1" +edition.workspace = true +license.workspace = true +publish = false +description = "The motion bento's shared parts: the seeded chaos schedule, the tiles' logical state, the springs and colours, and the frame meter. No UI framework." + +[dependencies] +procwatch = { workspace = true } + +[target.'cfg(not(windows))'.dependencies] +libc = { workspace = true } + +[target.'cfg(windows)'.dependencies] +windows-sys = { workspace = true, features = ["Win32_Foundation", "Win32_System_Threading"] } + +[lints] +workspace = true diff --git a/app/vendor/rune/examples/motion-bento/chaos/src/config.rs b/app/vendor/rune/examples/motion-bento/chaos/src/config.rs new file mode 100644 index 0000000..3b2c3ff --- /dev/null +++ b/app/vendor/rune/examples/motion-bento/chaos/src/config.rs @@ -0,0 +1,169 @@ +//! The flags both builds share. Each build strips these and keeps the rest for its framework. + +use std::path::PathBuf; + +use crate::stress::Load; + +#[derive(Clone, Debug)] +pub struct Config { + /// Names one chaos schedule (and the random choices each action makes). + pub seed: u64, + /// Seconds of chaos. The window quits a second after it ends, writing metrics if asked. + pub duration: f64, + /// Scales how often things happen: 2 is twice the events. + pub intensity: f64, + /// Where to write the frame meter's JSON when the run ends. + pub metrics: Option<PathBuf>, + /// Show the frame meter over the window from the start (H toggles it). + pub hud: bool, + /// Write the schedule as a Rune script and exit. + pub emit_script: Option<PathBuf>, + /// A named look or spring tuning (`look::Variant`). + pub variant: String, + /// Keep the window open after the schedule ends instead of quitting. + pub stay: bool, + /// Stress mode (`--load N` or `--ramp A:B`): the wall of controls instead of the bento. + pub load: Option<Load>, + /// Where to write every frame's show time, load and times as CSV when the run ends. + pub frames: Option<PathBuf>, + /// Draw the stress HUD from this measured run's frames CSV instead of this run's own. + pub hud_from: Option<PathBuf>, + /// Build the whole view every frame, as a first port does, instead of each framework's + /// idiomatic way (memoised cards and live values in Rune, per-card entities in GPUI). + pub naive: bool, +} + +impl Default for Config { + fn default() -> Config { + Config { + seed: 1, + duration: 20.0, + intensity: 1.0, + metrics: None, + hud: false, + emit_script: None, + variant: "default".into(), + stay: false, + load: None, + frames: None, + hud_from: None, + naive: false, + } + } +} + +impl Config { + /// Takes the bento's own flags out of `args` (the program name first) and returns them with the + /// rest. `--duration` is read and also kept, since Rune's headless runs use it for video length. + pub fn parse(args: impl IntoIterator<Item = String>) -> Result<(Config, Vec<String>), String> { + let mut config = Config::default(); + let mut rest = Vec::new(); + let mut args = args.into_iter(); + let (mut fixed, mut ramp, mut hold, mut timed) = (None, None, 2.5, false); + fn value(flag: &str, next: Option<String>) -> Result<String, String> { + next.ok_or_else(|| format!("{flag} needs a value")) + } + fn number<T: std::str::FromStr>(flag: &str, v: &str) -> Result<T, String> { + v.parse().map_err(|_| format!("{flag}: not a number: {v}")) + } + while let Some(arg) = args.next() { + let (flag, inline) = match arg.split_once('=') { + Some((f, v)) if f.starts_with("--") => (f.to_string(), Some(v.to_string())), + _ => (arg.clone(), None), + }; + let take = |args: &mut dyn Iterator<Item = String>| match &inline { + Some(v) => Ok(v.clone()), + None => value(&flag, args.next()), + }; + match flag.as_str() { + "--seed" => config.seed = number(&flag, &take(&mut args)?)?, + "--intensity" => { + config.intensity = number(&flag, &take(&mut args)?)?; + if !(config.intensity > 0.0) { + return Err("--intensity must be above 0".into()); + } + } + "--duration" => { + let v = take(&mut args)?; + if v != "auto" { + config.duration = number(&flag, &v)?; + } + timed = true; + rest.push("--duration".into()); + rest.push(v); + } + "--metrics" => config.metrics = Some(take(&mut args)?.into()), + "--emit-script" => config.emit_script = Some(take(&mut args)?.into()), + "--variant" => config.variant = take(&mut args)?, + "--load" => fixed = Some(number::<usize>(&flag, &take(&mut args)?)?.max(1)), + "--ramp" => ramp = Some(take(&mut args)?), + "--hold" => hold = number(&flag, &take(&mut args)?)?, + "--frames" => config.frames = Some(take(&mut args)?.into()), + "--hud-from" => { + config.hud_from = Some(take(&mut args)?.into()); + config.hud = true; + } + "--hud" => config.hud = true, + "--stay" => config.stay = true, + "--naive" => config.naive = true, + _ => rest.push(arg), + } + } + config.load = match (fixed, ramp) { + (Some(_), Some(_)) => return Err("--load and --ramp: pick one".into()), + (Some(n), None) => Some(Load::Fixed(n)), + (None, Some(r)) => Some(Load::parse_ramp(&r, hold)?), + (None, None) => None, + }; + // A ramp runs as long as its levels, unless told otherwise; Rune's headless runs read it too. + if let (false, Some(d)) = (timed, config.load.as_ref().and_then(Load::duration)) { + config.duration = d; + rest.push("--duration".into()); + rest.push(format!("{d}")); + } + Ok((config, rest)) + } + + /// The seconds between events on a quiet stretch, before intensity. + pub fn gap(&self) -> (f64, f64) { + (0.1 / self.intensity, 0.3 / self.intensity) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn args(s: &str) -> Vec<String> { + s.split_whitespace().map(String::from).collect() + } + + #[test] + fn takes_its_own_flags_and_keeps_the_rest() { + let (c, rest) = + Config::parse(args("bento --seed 9 --snap a.png --intensity=2 --duration 4 --hud --naive --at 1")).unwrap(); + assert_eq!(c.seed, 9); + assert!(c.naive); + assert_eq!(c.intensity, 2.0); + assert_eq!(c.duration, 4.0); + assert!(c.hud); + assert_eq!(rest, args("bento --snap a.png --duration 4 --at 1")); + } + + #[test] + fn a_ramp_sets_the_duration_unless_given() { + let (c, rest) = Config::parse(args("bento --ramp 16:64 --hold 2")).unwrap(); + assert_eq!(c.load.as_ref().map(|l| l.levels().to_vec()), Some(vec![16, 23, 32, 45, 64])); + assert_eq!(c.duration, 10.6); + assert_eq!(rest, args("bento --duration 10.6")); + let (c, _) = Config::parse(args("bento --load 40 --duration 3")).unwrap(); + assert_eq!((c.load, c.duration), (Some(Load::Fixed(40)), 3.0)); + assert!(Config::parse(args("bento --load 4 --ramp 1:2")).is_err()); + } + + #[test] + fn rejects_a_bad_number() { + assert!(Config::parse(args("bento --seed x")).is_err()); + assert!(Config::parse(args("bento --intensity 0")).is_err()); + } +} diff --git a/app/vendor/rune/examples/motion-bento/chaos/src/hud.rs b/app/vendor/rune/examples/motion-bento/chaos/src/hud.rs new file mode 100644 index 0000000..66fd2ee --- /dev/null +++ b/app/vendor/rune/examples/motion-bento/chaos/src/hud.rs @@ -0,0 +1,149 @@ +//! The stress HUD's numbers, shared so both builds show the same thing: the last [`GRAPH`] +//! frames' build times against the 120 Hz and 60 Hz budgets, a big readout, and frame rate. +//! +//! Live, the HUD reads the frames the meter has seen, and its frame rate and misses are the +//! window's. Replaying (`--hud-from`), it reads a measured run's per-frame CSV by show time, so a +//! capture run, whose own frames the capture slows, shows what the clean run measured at the same +//! moment; its frame rate is then what that CPU cost allows at 120 Hz, nothing presented. + +use crate::meter::Meter; + +pub const BUDGET_120: f32 = 1000.0 / 120.0; +pub const BUDGET_60: f32 = 1000.0 / 60.0; +/// Frames in the graph. +pub const GRAPH: usize = 120; +/// The graph's top, in ms. +pub const GRAPH_MAX: f32 = 40.0; +/// Frames the big readout takes the median of. +const READOUT: usize = 15; + +/// A measured run's frames: show time and build ms, by show time. +pub struct Replay { + samples: Vec<(f32, f32)>, +} + +impl Replay { + /// Reads [`Meter::frames_csv`] output. + pub fn load(path: &std::path::Path) -> Result<Replay, String> { + let text = std::fs::read_to_string(path).map_err(|e| format!("{}: {e}", path.display()))?; + let mut samples = Vec::new(); + for line in text.lines().skip(1) { + let mut f = line.split(','); + let (Some(t), Some(_), Some(ms)) = (f.next(), f.next(), f.next()) else { continue }; + if let (Ok(t), Ok(ms)) = (t.parse::<f32>(), ms.parse::<f32>()) + && t.is_finite() + { + samples.push((t, ms)); + } + } + samples.sort_by(|a, b| a.0.total_cmp(&b.0)); + Ok(Replay { samples }) + } + + /// The frames at or before show time `t`. + pub fn until(&self, t: f64) -> &[(f32, f32)] { + let t = t as f32 + 1e-4; + &self.samples[..self.samples.partition_point(|s| s.0 <= t)] + } +} + +#[derive(Clone, Debug, Default, PartialEq)] +pub struct Readout { + /// Oldest first, at most [`GRAPH`]. + pub graph: Vec<f32>, + /// The median of the last few frames. + pub ms: f32, + pub p95: f32, + pub fps: f32, + /// Refreshes missed: live, all run; replayed, in the last second. + pub missed: u32, + pub source: &'static str, +} + +/// 0 within the 120 Hz budget, 1 within 60 Hz, 2 over. +pub fn grade(ms: f32) -> usize { + if ms <= BUDGET_120 { + 0 + } else if ms <= BUDGET_60 { + 1 + } else { + 2 + } +} + +fn pct(v: &mut [f32], p: f32) -> f32 { + if v.is_empty() { + return 0.0; + } + v.sort_by(f32::total_cmp); + v[((v.len() - 1) as f32 * p).round() as usize] +} + +impl Readout { + fn of(samples: impl Iterator<Item = (f32, f32)>) -> Readout { + let graph: Vec<f32> = samples.map(|s| s.1).collect(); + let graph = graph[graph.len().saturating_sub(GRAPH)..].to_vec(); + let ms = pct(&mut graph[graph.len().saturating_sub(READOUT)..].to_vec(), 0.5); + let p95 = pct(&mut graph.clone(), 0.95); + Readout { graph, ms, p95, ..Default::default() } + } + + /// From a measured run: the frame rate this CPU cost allows at 120 Hz. + pub fn replay(r: &Replay, t: f64) -> Readout { + let mut out = Readout::of(r.until(t).iter().copied()); + let refreshes: u32 = out.graph.iter().map(|&ms| (ms / BUDGET_120).ceil().max(1.0) as u32).sum(); + out.missed = refreshes.saturating_sub(out.graph.len() as u32); + out.fps = if refreshes > 0 { 120.0 * out.graph.len() as f32 / refreshes as f32 } else { 0.0 }; + out.source = "measured headless · live pending"; + out + } + + pub fn live(m: &Meter) -> Readout { + let mut out = Readout::of(m.tail(GRAPH)); + let recent = m.recent(); + out.fps = recent.fps as f32; + out.missed = recent.dropped as u32; + out.source = "live window"; + out + } + + pub fn big(&self) -> String { + format!("{:.1} ms", self.ms) + } + + pub fn detail(&self) -> String { + format!("build + layout + paint · p95 {:.1}", self.p95) + } + + pub fn rate(&self) -> String { + if self.source == "live window" { + format!("{:.0} fps · missed {}", self.fps, self.missed) + } else { + format!("≈ {:.0} fps at 120 Hz · {} missed / s", self.fps, self.missed) + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_replay_counts_the_refreshes_slow_frames_miss() { + let dir = std::env::temp_dir().join(format!("bento-hud-{}.csv", std::process::id())); + let mut csv = String::from("show_s,load,build_ms,work_ms,start_s\n"); + for i in 0..240 { + // Half the frames take two refreshes. + csv.push_str(&format!("{},16,{},0,0\n", i as f32 / 120.0, if i % 2 == 0 { 4.0 } else { 12.0 })); + } + std::fs::write(&dir, csv).unwrap(); + let r = Replay::load(&dir).unwrap(); + std::fs::remove_file(dir).unwrap(); + assert_eq!(r.until(0.5).len(), 61); + let out = Readout::replay(&r, 10.0); + assert_eq!(out.graph.len(), GRAPH); + assert_eq!(out.missed, 60); + assert!((out.fps - 80.0).abs() < 0.01); + assert_eq!((grade(4.0), grade(12.0), grade(20.0)), (0, 1, 2)); + } +} diff --git a/app/vendor/rune/examples/motion-bento/chaos/src/lib.rs b/app/vendor/rune/examples/motion-bento/chaos/src/lib.rs new file mode 100644 index 0000000..ba3b5a2 --- /dev/null +++ b/app/vendor/rune/examples/motion-bento/chaos/src/lib.rs @@ -0,0 +1,25 @@ +//! The motion bento's shared parts, used by its Rune build and its GPUI build alike: the command +//! line, a seeded RNG, the chaos schedule, the tiles' logical state ([`Model`]), the springs and +//! colours both builds animate with, and the frame meter that writes `metrics.json`. +//! +//! Nothing here draws. Each framework turns a [`Model`] into its own view and animates the change +//! from the last one with its own springs, using the durations and bounces in [`look`]. + +pub mod config; +pub mod hud; +pub mod look; +pub mod meter; +pub mod model; +pub mod rng; +pub mod schedule; +pub mod stress; + +pub use config::Config; +pub use meter::Meter; +pub use model::Action; +pub use model::Model; +pub use rng::Rng; +pub use schedule::Event; +pub use schedule::Player; +pub use schedule::schedule; +pub use schedule::script_json; diff --git a/app/vendor/rune/examples/motion-bento/chaos/src/look.rs b/app/vendor/rune/examples/motion-bento/chaos/src/look.rs new file mode 100644 index 0000000..b681534 --- /dev/null +++ b/app/vendor/rune/examples/motion-bento/chaos/src/look.rs @@ -0,0 +1,191 @@ +//! The look both builds share: colours as OKLCH, the grid's measurements, and the springs, as +//! perceptual duration and bounce (SwiftUI's `Spring(duration:bounce:)`). + +/// An OKLCH colour with alpha. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Lch { + pub l: f32, + pub c: f32, + pub h: f32, + pub a: f32, +} + +pub const fn lch(l: f32, c: f32, h: f32) -> Lch { + Lch { l, c, h, a: 1.0 } +} + +impl Lch { + pub const fn alpha(self, a: f32) -> Lch { + Lch { a, ..self } + } + + /// OKLab (L, a, b): the space both builds interpolate colour in. + pub fn lab(self) -> [f32; 3] { + let h = self.h.to_radians(); + [self.l, self.c * h.cos(), self.c * h.sin()] + } + + /// Gamma-encoded sRGB, clamped to the gamut, with alpha. + pub fn srgb(self) -> [f32; 4] { + let [r, g, b] = lab_to_linear(self.lab()); + [encode(r), encode(g), encode(b), self.a] + } +} + +pub fn lab_to_linear([l, a, b]: [f32; 3]) -> [f32; 3] { + let l_ = l + 0.396_337_78 * a + 0.215_803_76 * b; + let m_ = l - 0.105_561_346 * a - 0.063_854_17 * b; + let s_ = l - 0.089_484_18 * a - 1.291_485_5 * b; + let (l3, m3, s3) = (l_ * l_ * l_, m_ * m_ * m_, s_ * s_ * s_); + [ + 4.076_741_7 * l3 - 3.307_711_6 * m3 + 0.230_969_94 * s3, + -1.268_438 * l3 + 2.609_757_4 * m3 - 0.341_319_38 * s3, + -0.004_196_086_3 * l3 - 0.703_418_6 * m3 + 1.707_614_7 * s3, + ] +} + +/// Linear to gamma-encoded sRGB, clamped to 0..1. +pub fn encode(x: f32) -> f32 { + let x = x.clamp(0.0, 1.0); + if x <= 0.003_130_8 { 12.92 * x } else { 1.055 * x.powf(1.0 / 2.4) - 0.055 } +} + +pub mod color { + use super::{Lch, lch}; + + pub const ACCENT_HUE: f32 = 245.0; + pub const BG: Lch = lch(0.155, 0.012, 260.0); + pub const TILE: Lch = lch(0.205, 0.014, 258.0); + pub const TILE_FOCUS: Lch = lch(0.235, 0.022, 252.0); + pub const EDGE: Lch = lch(1.0, 0.0, 0.0).alpha(0.07); + pub const WELL: Lch = lch(0.255, 0.014, 258.0); + pub const WELL_HI: Lch = lch(0.31, 0.016, 258.0); + pub const TEXT: Lch = lch(0.96, 0.005, 258.0); + pub const TEXT_2: Lch = lch(0.72, 0.012, 258.0); + pub const TEXT_3: Lch = lch(0.54, 0.014, 258.0); + pub const ACCENT: Lch = lch(0.66, 0.17, ACCENT_HUE); + pub const ACCENT_DIM: Lch = lch(0.66, 0.17, ACCENT_HUE).alpha(0.18); + pub const ON_ACCENT: Lch = lch(0.99, 0.0, 0.0); + pub const GOOD: Lch = lch(0.74, 0.15, 155.0); + pub const WARM: Lch = lch(0.78, 0.14, 70.0); + + /// Each scene's mood: its swatch, and the glow it casts on the header. + pub const SCENE: [Lch; 4] = [ + lch(0.66, 0.17, ACCENT_HUE), + lch(0.74, 0.13, 175.0), + lch(0.78, 0.14, 70.0), + lch(0.6, 0.17, 295.0), + ]; +} + +/// The window and the grid, in points. +pub mod grid { + pub const WIDTH: f32 = 1440.0; + pub const HEIGHT: f32 = 900.0; + pub const PAD: f32 = 28.0; + pub const GAP: f32 = 14.0; + pub const HEADER: f32 = 64.0; + pub const RADIUS: f32 = 18.0; + pub const TILE_PAD: f32 = 18.0; + /// Row heights below the header; the dock row takes what's left. + pub const ROW1: f32 = 236.0; + pub const ROW2: f32 = 262.0; + /// The focused dock tile's share of the row against 1 for each other tile. + pub const DOCK_FOCUS: f32 = 2.4; +} + +/// A spring as perceptual duration (seconds) and bounce, mass 1. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Spring { + pub duration: f32, + pub bounce: f32, +} + +impl Spring { + pub const fn new(duration: f32, bounce: f32) -> Spring { + Spring { duration, bounce } + } + + /// ω = 2π / duration. + pub fn omega(self) -> f32 { + std::f32::consts::TAU / self.duration + } + + /// ζ = 1 − bounce (≥ 0), 1 / (1 + bounce) below. + pub fn zeta(self) -> f32 { + if self.bounce >= 0.0 { 1.0 - self.bounce } else { 1.0 / (1.0 + self.bounce) } + } + + /// k = ω². + pub fn stiffness(self) -> f32 { + self.omega() * self.omega() + } + + /// c = 2ζω. + pub fn damping(self) -> f32 { + 2.0 * self.zeta() * self.omega() + } +} + +/// The springs each kind of motion uses. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Springs { + /// Tiles reflowing, cards and feed rows moving. + pub layout: Spring, + /// Controls: switches, segments, chips filling. + pub snap: Spring, + /// Shape and colour changes. + pub morph: Spring, + /// Things arriving with a little life. + pub pop: Spring, + /// The XY pad's puck and the mixer's faders. + pub travel: Spring, +} + +impl Springs { + /// `default` is the shipped tuning. `bouncy` and `stiff` exist for A/B runs. + pub fn variant(name: &str) -> Springs { + let base = Springs { + layout: Spring::new(0.4, 0.0), + snap: Spring::new(0.25, 0.0), + morph: Spring::new(0.3, 0.16), + pop: Spring::new(0.25, 0.15), + travel: Spring::new(0.35, 0.12), + }; + match name { + "bouncy" => Springs { + layout: Spring::new(0.5, 0.28), + snap: Spring::new(0.3, 0.22), + morph: Spring::new(0.45, 0.35), + pop: Spring::new(0.35, 0.35), + travel: Spring::new(0.5, 0.35), + }, + "stiff" => Springs { + layout: Spring::new(0.22, 0.0), + snap: Spring::new(0.15, 0.0), + morph: Spring::new(0.18, 0.0), + pop: Spring::new(0.15, 0.0), + travel: Spring::new(0.2, 0.0), + }, + _ => base, + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn accent_is_rune_blue() { + let [r, g, b, _] = color::ACCENT.srgb(); + assert!(b > r && b > g && r < 0.4, "{r} {g} {b}"); + } + + #[test] + fn spring_constants_match_swiftui() { + let s = Spring::new(0.5, 0.0); + assert!((s.stiffness() - (4.0 * std::f32::consts::PI).powi(2)).abs() < 1e-3); + assert!((s.damping() - 2.0 * 4.0 * std::f32::consts::PI).abs() < 1e-3); + } +} diff --git a/app/vendor/rune/examples/motion-bento/chaos/src/meter.rs b/app/vendor/rune/examples/motion-bento/chaos/src/meter.rs new file mode 100644 index 0000000..0b6ab31 --- /dev/null +++ b/app/vendor/rune/examples/motion-bento/chaos/src/meter.rs @@ -0,0 +1,369 @@ +//! The frame meter both builds feed, one call per drawn frame, so their numbers mean the same. +//! +//! It keeps each frame's start time, its CPU work (whatever span the build can time: see each +//! build's README) and, where a build can split it out, the part that builds the frame: view, +//! layout and paint, without the GPU encode. From those it derives frame-start intervals, missed frames (an interval over +//! 1.5 refresh periods) and percentiles, and it samples the process's CPU time and memory from +//! procwatch. + +#![allow(unsafe_code)] + +use std::time::Instant; + +#[derive(Clone, Copy, Debug)] +struct Frame { + /// Seconds since the meter started. + start: f64, + work_ms: f32, + /// NaN when the build can't split it out. + build_ms: f32, + /// The show time and load the app tagged the frame with ([`Meter::tag`]). + show: f32, + load: u32, + /// CPU time since the frame before: this thread's, and the whole process's. Unlike the + /// spans above, a busy machine that preempts the app doesn't add to them. + cpu_ms: f32, + proc_ms: f32, +} + +/// An interval longer than this is the window resting, not a slow frame. +const IDLE_GAP: f64 = 0.1; + +pub struct Meter { + framework: String, + refresh_hz: f64, + t0: Instant, + cpu0: f64, + frames: Vec<Frame>, + footprint_peak: u64, + footprint_last: u64, + footprint_at: f64, + resident_last: u64, + /// Seconds since the meter started that bound what [`Meter::summary`] counts. + window: Option<(f64, f64)>, + extra: Vec<(String, String)>, + tag: (f32, u32), + /// Thread and process CPU seconds at the last frame. + cpu_last: (f64, f64), +} + +#[derive(Clone, Debug, Default, PartialEq)] +pub struct Summary { + pub frames: usize, + pub seconds: f64, + pub fps: f64, + pub interval_ms: [f64; 4], + pub work_ms: [f64; 4], + /// View, layout and paint only; `None` when no frame reported it. + pub build_ms: Option<[f64; 4]>, + /// Intervals over 1.5 refresh periods. + pub late: usize, + /// Refreshes those late intervals skipped. + pub dropped: usize, + pub idle_gaps: usize, + pub cpu_percent: f64, + pub footprint_mb: f64, + pub footprint_peak_mb: f64, + pub resident_mb: f64, +} + +fn pct(sorted: &[f64], p: f64) -> f64 { + if sorted.is_empty() { + return 0.0; + } + let i = ((sorted.len() - 1) as f64 * p).round() as usize; + sorted[i] +} + +/// p50, p95, p99 and max of `v`. +fn spread(mut v: Vec<f64>) -> [f64; 4] { + v.sort_by(f64::total_cmp); + [pct(&v, 0.5), pct(&v, 0.95), pct(&v, 0.99), v.last().copied().unwrap_or(0.0)] +} + +fn cpu_seconds() -> f64 { + procwatch::snapshot().map_or(0.0, |s| s.cpu_s) +} + +/// This thread's CPU seconds, and the process's (user and system), cheaply enough for every frame. +#[cfg(windows)] +fn cpu_now() -> (f64, f64) { + use windows_sys::Win32::Foundation::FILETIME; + use windows_sys::Win32::System::Threading::{GetCurrentProcess, GetCurrentThread, GetProcessTimes, GetThreadTimes}; + let zero = || FILETIME { dwLowDateTime: 0, dwHighDateTime: 0 }; + let secs = |f: FILETIME| ((f.dwHighDateTime as u64) << 32 | f.dwLowDateTime as u64) as f64 * 1e-7; + let (mut created, mut exited, mut kernel, mut user) = (zero(), zero(), zero(), zero()); + // SAFETY: the pseudo-handles need no closing; each call only writes the structs it's given. + let thread = if unsafe { GetThreadTimes(GetCurrentThread(), &mut created, &mut exited, &mut kernel, &mut user) } != 0 { secs(kernel) + secs(user) } else { f64::NAN }; + // SAFETY: as above. + let process = if unsafe { GetProcessTimes(GetCurrentProcess(), &mut created, &mut exited, &mut kernel, &mut user) } != 0 { secs(kernel) + secs(user) } else { f64::NAN }; + (thread, process) +} + +/// This thread's CPU seconds, and the process's (user and system), cheaply enough for every frame. +#[cfg(not(windows))] +fn cpu_now() -> (f64, f64) { + let mut ts = libc::timespec { tv_sec: 0, tv_nsec: 0 }; + // SAFETY: both calls only write the struct they're given. + let thread = if unsafe { libc::clock_gettime(libc::CLOCK_THREAD_CPUTIME_ID, &mut ts) } == 0 { ts.tv_sec as f64 + ts.tv_nsec as f64 * 1e-9 } else { f64::NAN }; + let mut ru = std::mem::MaybeUninit::<libc::rusage>::zeroed(); + // SAFETY: as above. + let process = if unsafe { libc::getrusage(libc::RUSAGE_SELF, ru.as_mut_ptr()) } == 0 { + // SAFETY: getrusage filled it. + let ru = unsafe { ru.assume_init() }; + let tv = |t: libc::timeval| t.tv_sec as f64 + t.tv_usec as f64 * 1e-6; + tv(ru.ru_utime) + tv(ru.ru_stime) + } else { + f64::NAN + }; + (thread, process) +} + +impl Meter { + pub fn new(framework: &str, refresh_hz: f64) -> Meter { + let mut m = Meter { + framework: framework.into(), + refresh_hz, + // motion-bento-chaos is a framework-independent native benchmark crate. + #[allow(clippy::disallowed_methods)] + t0: Instant::now(), + cpu0: cpu_seconds(), + frames: Vec::with_capacity(8192), + footprint_peak: 0, + footprint_last: 0, + footprint_at: -1.0, + resident_last: 0, + window: None, + extra: Vec::new(), + tag: (f32::NAN, 0), + cpu_last: cpu_now(), + }; + m.sample_memory(0.0); + m + } + + pub fn set_refresh(&mut self, hz: f64) { + if hz > 1.0 { + self.refresh_hz = hz; + } + } + + pub fn refresh_hz(&self) -> f64 { + self.refresh_hz + } + + /// Seconds since the meter started. + pub fn now(&self) -> f64 { + self.t0.elapsed().as_secs_f64() + } + + pub fn seconds_at(&self, at: Instant) -> f64 { + at.saturating_duration_since(self.t0).as_secs_f64() + } + + /// Restarts the CPU count from here, and counts only frames from now on. + pub fn begin(&mut self) { + let now = self.now(); + self.cpu0 = cpu_seconds(); + self.window = Some((now, f64::INFINITY)); + } + + /// Stops counting frames from here. + pub fn end(&mut self) { + let now = self.now(); + if let Some((from, _)) = self.window { + self.window = Some((from, now)); + } + } + + /// Adds a line to the JSON (a build's version, how it timed work). + pub fn note(&mut self, key: &str, value: &str) { + self.extra.push((key.into(), value.into())); + } + + /// One drawn frame that started at `start` and took `work_ms` of CPU. + pub fn frame(&mut self, start: Instant, work_ms: f64) { + self.push(start, work_ms, f32::NAN); + } + + /// One drawn frame whose `work_ms` includes `build_ms` of view, layout and paint. + pub fn frame_with_build(&mut self, start: Instant, work_ms: f64, build_ms: f64) { + self.push(start, work_ms, build_ms as f32); + } + + /// Tags the frames reported from here with the show time and load they drew. + pub fn tag(&mut self, show: f64, load: usize) { + self.tag = (show as f32, load as u32); + } + + fn push(&mut self, start: Instant, work_ms: f64, build_ms: f32) { + let s = self.seconds_at(start); + let (show, load) = self.tag; + let cpu = cpu_now(); + let (cpu_ms, proc_ms) = (((cpu.0 - self.cpu_last.0) * 1000.0) as f32, ((cpu.1 - self.cpu_last.1) * 1000.0) as f32); + self.cpu_last = cpu; + self.frames.push(Frame { start: s, work_ms: work_ms as f32, build_ms, show, load, cpu_ms, proc_ms }); + if s - self.footprint_at >= 0.5 { + self.sample_memory(s); + } + } + + fn sample_memory(&mut self, at: f64) { + let u = procwatch::usage(); + self.footprint_last = u.footprint.unwrap_or(0); + self.resident_last = u.resident.unwrap_or(0); + self.footprint_peak = self.footprint_peak.max(self.footprint_last); + self.footprint_at = at; + } + + fn counted(&self) -> &[Frame] { + let Some((from, to)) = self.window else { return &self.frames }; + let a = self.frames.partition_point(|f| f.start < from); + let b = self.frames.partition_point(|f| f.start <= to); + &self.frames[a..b] + } + + fn summarise(&self, frames: &[Frame], seconds: f64, cpu_s: f64) -> Summary { + let period = 1.0 / self.refresh_hz; + let mut intervals = Vec::with_capacity(frames.len()); + let (mut late, mut dropped, mut idle_gaps) = (0, 0, 0); + for w in frames.windows(2) { + let iv = w[1].start - w[0].start; + if iv > IDLE_GAP { + idle_gaps += 1; + continue; + } + intervals.push(iv * 1000.0); + if iv > 1.5 * period { + late += 1; + dropped += ((iv / period).round() as usize).saturating_sub(1); + } + } + let mb = |b: u64| b as f64 / 1_048_576.0; + let builds: Vec<f64> = frames.iter().filter(|f| !f.build_ms.is_nan()).map(|f| f.build_ms as f64).collect(); + Summary { + frames: frames.len(), + seconds, + fps: if seconds > 0.0 { frames.len() as f64 / seconds } else { 0.0 }, + interval_ms: spread(intervals), + work_ms: spread(frames.iter().map(|f| f.work_ms as f64).collect()), + build_ms: (!builds.is_empty()).then(|| spread(builds)), + late, + dropped, + idle_gaps, + cpu_percent: if seconds > 0.0 { 100.0 * cpu_s / seconds } else { 0.0 }, + footprint_mb: mb(self.footprint_last), + footprint_peak_mb: mb(self.footprint_peak), + resident_mb: mb(self.resident_last), + } + } + + /// The whole counted window. Reads the process's CPU time, so call it once at the end. + pub fn summary(&mut self) -> Summary { + let now = self.now(); + self.sample_memory(now); + let (from, to) = self.window.unwrap_or((0.0, now)); + let seconds = to.min(now) - from; + let cpu = cpu_seconds() - self.cpu0; + self.summarise(self.counted(), seconds, cpu) + } + + /// The last second, for the HUD. CPU% there is left at 0: reading it costs a thread walk. + pub fn recent(&self) -> Summary { + let now = self.now(); + let a = self.frames.partition_point(|f| f.start < now - 1.0); + let mut s = self.summarise(&self.frames[a..], 1.0, 0.0); + let total = self.summarise(self.counted(), 1.0, 0.0); + s.late = total.late; + s.dropped = total.dropped; + s + } + + /// Short HUD lines. + pub fn hud(&self) -> [String; 4] { + let s = self.recent(); + [ + format!("{} · {:.0} Hz display", self.framework, self.refresh_hz), + format!("{:.0} fps · interval p95 {:.1} ms", s.fps, s.interval_ms[1]), + format!("work p50 {:.2} · p95 {:.2} ms", s.work_ms[0], s.work_ms[1]), + format!("missed {} · {:.0} MB", s.dropped, s.footprint_mb), + ] + } + + /// The summary as JSON, with the build's notes. + pub fn json(&mut self) -> String { + let s = self.summary(); + let arr = |v: [f64; 4]| format!("{{\"p50\": {:.3}, \"p95\": {:.3}, \"p99\": {:.3}, \"max\": {:.3}}}", v[0], v[1], v[2], v[3]); + let mut out = String::from("{\n"); + out.push_str(&format!(" \"framework\": \"{}\",\n", self.framework)); + out.push_str(&format!(" \"refresh_hz\": {:.2},\n", self.refresh_hz)); + out.push_str(&format!(" \"seconds\": {:.3},\n", s.seconds)); + out.push_str(&format!(" \"frames\": {},\n", s.frames)); + out.push_str(&format!(" \"fps\": {:.2},\n", s.fps)); + out.push_str(&format!(" \"interval_ms\": {},\n", arr(s.interval_ms))); + out.push_str(&format!(" \"work_ms\": {},\n", arr(s.work_ms))); + if let Some(b) = s.build_ms { + out.push_str(&format!(" \"build_ms\": {},\n", arr(b))); + } + out.push_str(&format!(" \"late_intervals\": {},\n", s.late)); + out.push_str(&format!(" \"dropped_frames\": {},\n", s.dropped)); + out.push_str(&format!(" \"idle_gaps\": {},\n", s.idle_gaps)); + out.push_str(&format!(" \"cpu_percent\": {:.2},\n", s.cpu_percent)); + out.push_str(&format!(" \"footprint_mb\": {:.2},\n", s.footprint_mb)); + out.push_str(&format!(" \"footprint_peak_mb\": {:.2},\n", s.footprint_peak_mb)); + out.push_str(&format!(" \"resident_mb\": {:.2}", s.resident_mb)); + for (k, v) in &self.extra { + out.push_str(&format!(",\n \"{k}\": \"{}\"", v.replace('\\', "\\\\").replace('"', "\\\""))); + } + out.push_str("\n}\n"); + out + } + + /// The last `n` frames' show time and build time (work where the build can't split it). + pub fn tail(&self, n: usize) -> impl Iterator<Item = (f32, f32)> + '_ { + self.frames[self.frames.len().saturating_sub(n)..].iter().map(|f| (f.show, if f.build_ms.is_nan() { f.work_ms } else { f.build_ms })) + } + + /// Every frame as CSV, one line each: `show_s,load,build_ms,work_ms,start_s,cpu_ms,proc_ms` + /// (`cpu_ms` and `proc_ms` are the CPU time since the frame before, thread and process). + pub fn frames_csv(&self) -> String { + let mut out = String::from("show_s,load,build_ms,work_ms,start_s,cpu_ms,proc_ms\n"); + for f in &self.frames { + out.push_str(&format!("{:.4},{},{:.4},{:.4},{:.4},{:.4},{:.4}\n", f.show, f.load, f.build_ms, f.work_ms, f.start, f.cpu_ms, f.proc_ms)); + } + out + } + + pub fn write(&mut self, path: &std::path::Path) -> std::io::Result<()> { + let json = self.json(); + std::fs::write(path, json) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::time::Duration; + + #[test] + fn counts_late_frames_against_the_refresh() { + let mut m = Meter::new("test", 120.0); + let t0 = m.t0; + let period = Duration::from_secs_f64(1.0 / 120.0); + let mut at = t0; + for i in 0..240 { + // Every 60th frame takes three refreshes. + at += if i % 60 == 59 { period * 3 } else { period }; + m.frame_with_build(at, 2.0, 1.5); + } + // A rest is not a miss. + m.frame(at + Duration::from_millis(400), 2.0); + let s = m.summarise(&m.frames, 2.0, 0.0); + assert_eq!(s.late, 4); + assert_eq!(s.dropped, 8); + assert_eq!(s.idle_gaps, 1); + assert!((s.interval_ms[0] - 1000.0 / 120.0).abs() < 0.01); + assert_eq!(s.build_ms.map(|b| b[0]), Some(1.5)); + assert!(m.json().contains("\"dropped_frames\"")); + } +} diff --git a/app/vendor/rune/examples/motion-bento/chaos/src/model.rs b/app/vendor/rune/examples/motion-bento/chaos/src/model.rs new file mode 100644 index 0000000..2d2bf21 --- /dev/null +++ b/app/vendor/rune/examples/motion-bento/chaos/src/model.rs @@ -0,0 +1,344 @@ +//! The bento's logical state and the actions that change it. +//! +//! An [`Action`] carries only indices. Whatever randomness an action needs (a fader's new level, +//! the puck's next spot) comes from that tile's own [`Rng`] inside the model, so two builds that +//! apply the same actions in the same order hold the same state, whatever they draw. + +use crate::rng::Rng; + +pub const SCENES: [&str; 4] = ["Focus", "Relax", "Away", "Night"]; +pub const LIGHTS: [&str; 4] = ["Studio", "Desk lamp", "Hallway", "Porch"]; +pub const FADERS: [&str; 5] = ["Kick", "Bass", "Keys", "Vox", "FX"]; +pub const SCENE_NOTES: [&str; 4] = [ + "Cool, bright light. Notifications held.", + "Warm light and something slow playing.", + "Lights off, cameras armed, heat eased.", + "Dim amber light. Quiet hours.", +]; +pub const DOCK: [&str; 5] = ["Energy", "Genres", "Orb", "Transfers", "Visitors"]; +/// Each dock tile's key. +pub const DOCK_KEYS: [&str; 5] = ["energy", "chips", "orb", "transfers", "visitors"]; +pub const CHIPS: [&str; 8] = ["Ambient", "Lo-fi", "Jazz", "Rain", "Synth", "Piano", "Cafe", "Forest"]; +/// Chips shown while the chip tile is collapsed. +pub const CHIPS_FOLDED: usize = 4; +pub const TRACKS: [(&str, &str); 8] = [ + ("Night Drive", "Lumen"), + ("Paper Moons", "Hollow Coast"), + ("Glasshouse", "Ines Varga"), + ("Slow Orbit", "Kites"), + ("Low Tide", "Marlowe"), + ("Afterglow", "Sable Youth"), + ("Neon Rain", "Oda"), + ("Soft Static", "Fen"), +]; +pub const QUEUE_LEN: usize = 4; +pub const FEED_KINDS: [&str; 8] = [ + "Front door unlocked", + "Motion in the hallway", + "Washer finished", + "Package delivered", + "Living room at 21°", + "Garage closed", + "Doorbell rang", + "Air purifier on", +]; +pub const FEED_LEN: usize = 4; +pub const FILES: [&str; 3] = ["mix-final.wav", "photos-oct.zip", "backup.tar"]; +pub const ENERGY_BARS: usize = 7; +/// Recent visitor arrivals the visitors tile charts. +pub const VISITS: usize = 12; +/// The most visitors one arrival brings. +pub const VISIT_MAX: u32 = 48; +pub const TEMP_MIN: f32 = 16.0; +pub const TEMP_MAX: f32 = 28.0; + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum Action { + Scene(u8), + TempUp, + TempDown, + Light(u8), + Fader(u8), + Puck, + Queue, + Feed, + Focus(u8), + Energy, + ChipsMore, + Chip(u8), + Orb, + Transfer(u8), + Visitors, +} + +impl Action { + /// The key of the element a person would tap for this action. Both builds key their elements + /// this way, and the Rune script taps them. + pub fn key(self) -> String { + match self { + Action::Scene(i) => format!("scene/seg{i}"), + Action::TempUp => "thermo/up".into(), + Action::TempDown => "thermo/down".into(), + Action::Light(i) => format!("lights/light{i}"), + Action::Fader(i) => format!("mixer/fader{i}"), + Action::Puck => "xy/pad".into(), + Action::Queue => "queue/head/skip".into(), + Action::Feed => "feed/head/test".into(), + Action::Focus(i) => format!("{}/head", DOCK_KEYS[i as usize % DOCK_KEYS.len()]), + Action::Energy => "energy/bars".into(), + Action::ChipsMore => "chips/head/more".into(), + Action::Chip(i) => format!("chips/chip{i}"), + Action::Orb => "orb/orb".into(), + Action::Transfer(i) => format!("transfers/row{i}"), + Action::Visitors => "visitors/count".into(), + } + } +} + +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct FeedItem { + /// Unique for the run: the element's identity. + pub id: u32, + pub kind: usize, + /// Minutes past the hour, for the time label. + pub minute: u32, +} + +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Card { + pub id: u32, + pub track: usize, +} + +/// One arrival of visitors: a bar in the visitors chart. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Visit { + pub id: u32, + pub count: u32, +} + +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Orb { + /// 0..1 of the largest size. + pub size: f32, + /// OKLCH hue in degrees. + pub hue: f32, + /// Corner radius as a fraction of the side: 0.5 is a circle. + pub round: f32, + /// Degrees, always growing so the spring turns one way. + pub turn: f32, +} + +#[derive(Clone, Debug)] +pub struct Model { + /// Actions applied so far: the header's counter. + pub events: u32, + pub scene: usize, + pub temp: f32, + pub lights: [bool; 4], + pub faders: [f32; 5], + /// The XY pad's puck, 0..1 on each axis. + pub puck: [f32; 2], + /// Front card first. + pub queue: Vec<Card>, + /// Newest first. + pub feed: Vec<FeedItem>, + /// Which dock tile is wide. + pub focus: usize, + pub energy: [f32; ENERGY_BARS], + /// Tenths of a kWh, so both builds print the same digits. + pub kwh_tenths: u32, + pub chips_open: bool, + pub chips: [bool; 8], + pub orb: Orb, + pub transfers: [f32; 3], + pub visitors: u32, + /// Oldest first. + pub visits: Vec<Visit>, + next_id: u32, + minute: u32, + rng: [Rng; 8], +} + +const R_FADER: usize = 0; +const R_PUCK: usize = 1; +const R_QUEUE: usize = 2; +const R_FEED: usize = 3; +const R_ENERGY: usize = 4; +const R_ORB: usize = 5; +const R_TRANSFER: usize = 6; +const R_VISITORS: usize = 7; + +impl Model { + pub fn new(seed: u64) -> Model { + let rng = std::array::from_fn(|i| Rng::new(seed.wrapping_mul(0x2545_f491_4f6c_dd1d) ^ (i as u64 + 1))); + let mut m = Model { + events: 0, + scene: 0, + temp: 21.5, + lights: [true, false, true, false], + faders: [0.72, 0.58, 0.44, 0.66, 0.3], + puck: [0.62, 0.38], + queue: Vec::new(), + feed: Vec::new(), + focus: 0, + energy: [0.42, 0.55, 0.38, 0.7, 0.62, 0.48, 0.8], + kwh_tenths: 128, + chips_open: false, + chips: [true, false, true, false, false, false, false, false], + orb: Orb { size: 0.8, hue: 245.0, round: 0.5, turn: 0.0 }, + transfers: [0.35, 0.7, 0.12], + visitors: 1284, + visits: Vec::new(), + next_id: 0, + minute: 2, + rng, + }; + for track in 0..QUEUE_LEN { + let id = m.id(); + m.queue.push(Card { id, track }); + } + for count in [12, 18, 9, 22, 30, 26, 14, 19, 33, 28, 21, 17] { + let id = m.id(); + m.visits.push(Visit { id, count }); + } + for kind in [2, 0, 5] { + let id = m.id(); + m.minute += 3; + m.feed.insert(0, FeedItem { id, kind, minute: m.minute }); + } + m + } + + fn id(&mut self) -> u32 { + self.next_id += 1; + self.next_id + } + + pub fn chips_shown(&self) -> usize { + if self.chips_open { CHIPS.len() } else { CHIPS_FOLDED } + } + + pub fn energy_kwh(&self) -> String { + format!("{}.{}", self.kwh_tenths / 10, self.kwh_tenths % 10) + } + + pub fn temp_label(&self) -> String { + format!("{:.1}°", self.temp) + } + + /// 0..1 around the thermostat's ring. + pub fn temp_fraction(&self) -> f32 { + (self.temp - TEMP_MIN) / (TEMP_MAX - TEMP_MIN) + } + + pub fn apply(&mut self, action: Action) { + self.events += 1; + match action { + Action::Scene(i) => self.scene = i as usize % SCENES.len(), + Action::TempUp => self.temp = (self.temp + 0.5).min(TEMP_MAX), + Action::TempDown => self.temp = (self.temp - 0.5).max(TEMP_MIN), + Action::Light(i) => { + let l = &mut self.lights[i as usize % 4]; + *l = !*l; + } + Action::Fader(i) => { + let r = &mut self.rng[R_FADER]; + let f = &mut self.faders[i as usize % FADERS.len()]; + // Move far enough to see. + let mut next = r.rangef(0.12, 0.96); + if (next - *f).abs() < 0.2 { + next = if *f > 0.5 { *f - 0.35 } else { *f + 0.35 }; + } + *f = next; + } + Action::Puck => { + let r = &mut self.rng[R_PUCK]; + self.puck = [r.rangef(0.08, 0.92), r.rangef(0.1, 0.9)]; + } + Action::Queue => { + self.queue.remove(0); + let last = self.queue.last().map_or(0, |c| c.track); + let track = (last + 1 + self.rng[R_QUEUE].below(TRACKS.len() - 1)) % TRACKS.len(); + let id = self.id(); + self.queue.push(Card { id, track }); + } + Action::Feed => { + let r = &mut self.rng[R_FEED]; + let kind = r.below(FEED_KINDS.len()); + self.minute = (self.minute + 1 + r.below(4) as u32) % 60; + let id = self.id(); + self.feed.insert(0, FeedItem { id, kind, minute: self.minute }); + self.feed.truncate(FEED_LEN); + } + Action::Focus(i) => self.focus = i as usize % DOCK.len(), + Action::Energy => { + let r = &mut self.rng[R_ENERGY]; + for b in &mut self.energy { + *b = r.rangef(0.15, 1.0); + } + self.kwh_tenths += 3 + r.below(23) as u32; + } + Action::ChipsMore => self.chips_open = !self.chips_open, + Action::Chip(i) => { + let c = &mut self.chips[i as usize % CHIPS.len()]; + *c = !*c; + } + Action::Orb => { + let r = &mut self.rng[R_ORB]; + self.orb = Orb { + size: r.rangef(0.55, 1.0), + hue: (self.orb.hue + r.rangef(40.0, 140.0)) % 360.0, + round: [0.5, 0.32, 0.22][r.below(3)], + turn: self.orb.turn + [45.0, 90.0, 135.0][r.below(3)], + }; + } + Action::Transfer(i) => { + let step = self.rng[R_TRANSFER].rangef(0.15, 0.4); + let t = &mut self.transfers[i as usize % 3]; + *t = if *t >= 1.0 { 0.0 } else { (*t + step).min(1.0) }; + } + Action::Visitors => { + let count = 1 + self.rng[R_VISITORS].below(VISIT_MAX as usize) as u32; + self.visitors += count; + let id = self.id(); + self.visits.remove(0); + self.visits.push(Visit { id, count }); + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_same_actions_give_the_same_state() { + let actions = [Action::Fader(2), Action::Puck, Action::Queue, Action::Feed, Action::Orb, Action::Energy]; + let run = |seed| { + let mut m = Model::new(seed); + for a in actions.iter().chain(&actions) { + m.apply(*a); + } + format!("{:?}", (m.faders, m.puck, m.queue, m.feed, m.orb, m.energy, m.kwh_tenths)) + }; + assert_eq!(run(3), run(3)); + assert_ne!(run(3), run(4)); + } + + #[test] + fn lists_keep_their_length() { + let mut m = Model::new(1); + for _ in 0..20 { + m.apply(Action::Queue); + m.apply(Action::Feed); + m.apply(Action::Visitors); + } + assert_eq!(m.visits.len(), VISITS); + assert_eq!(m.queue.len(), QUEUE_LEN); + assert_eq!(m.feed.len(), FEED_LEN); + let ids: std::collections::HashSet<u32> = m.queue.iter().map(|c| c.id).chain(m.feed.iter().map(|f| f.id)).collect(); + assert_eq!(ids.len(), QUEUE_LEN + FEED_LEN); + } +} diff --git a/app/vendor/rune/examples/motion-bento/chaos/src/rng.rs b/app/vendor/rune/examples/motion-bento/chaos/src/rng.rs new file mode 100644 index 0000000..9ec2bac --- /dev/null +++ b/app/vendor/rune/examples/motion-bento/chaos/src/rng.rs @@ -0,0 +1,69 @@ +//! SplitMix64: tiny, fast and identical on every platform, so a seed names one show everywhere. + +#[derive(Clone, Debug)] +pub struct Rng(u64); + +impl Rng { + pub fn new(seed: u64) -> Rng { + Rng(seed ^ 0x9e37_79b9_7f4a_7c15) + } + + pub fn next_u64(&mut self) -> u64 { + self.0 = self.0.wrapping_add(0x9e37_79b9_7f4a_7c15); + let mut z = self.0; + z = (z ^ (z >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9); + z = (z ^ (z >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb); + z ^ (z >> 31) + } + + /// Uniform in [0, 1). + pub fn f64(&mut self) -> f64 { + (self.next_u64() >> 11) as f64 / (1u64 << 53) as f64 + } + + /// Uniform in [lo, hi). + pub fn range(&mut self, lo: f64, hi: f64) -> f64 { + lo + (hi - lo) * self.f64() + } + + pub fn rangef(&mut self, lo: f32, hi: f32) -> f32 { + self.range(lo as f64, hi as f64) as f32 + } + + /// Uniform in 0..n. + pub fn below(&mut self, n: usize) -> usize { + ((self.f64() * n as f64) as usize).min(n.saturating_sub(1)) + } + + /// An index into `weights`, chosen in proportion to them. + pub fn weighted(&mut self, weights: &[u32]) -> usize { + let total: u32 = weights.iter().sum(); + let mut pick = (self.f64() * total as f64) as u32; + for (i, w) in weights.iter().enumerate() { + if pick < *w { + return i; + } + pick -= w; + } + weights.len() - 1 + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_seed_names_one_sequence() { + let a: Vec<u64> = (0..4).map({ + let mut r = Rng::new(7); + move |_| r.next_u64() + }).collect(); + let b: Vec<u64> = (0..4).map({ + let mut r = Rng::new(7); + move |_| r.next_u64() + }).collect(); + assert_eq!(a, b); + assert_ne!(Rng::new(8).next_u64(), a[0]); + } +} diff --git a/app/vendor/rune/examples/motion-bento/chaos/src/schedule.rs b/app/vendor/rune/examples/motion-bento/chaos/src/schedule.rs new file mode 100644 index 0000000..d4ef109 --- /dev/null +++ b/app/vendor/rune/examples/motion-bento/chaos/src/schedule.rs @@ -0,0 +1,185 @@ +//! The chaos schedule: a seeded list of timed actions, quiet stretches broken by bursts. +//! +//! The schedule plays the actions against its own [`Model`] as it picks them, so every action is +//! one a person could take at that moment (a chip that's showing, a scene that isn't already on). + +use crate::config::Config; +use crate::model::{Action, CHIPS, DOCK, FADERS, Model, SCENES}; +use crate::rng::Rng; + +/// Chaos starts once the first frames have settled. +pub const START: f64 = 0.6; +/// A Rune script taps this long before the event's time and lifts at it, so the action lands at +/// `t` in a recording. +pub const TAP_LEAD: f64 = 0.01; + +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Event { + pub t: f64, + pub action: Action, +} + +// Relative odds per kind of action. +const KINDS: [u32; 15] = [5, 4, 4, 9, 12, 8, 6, 8, 6, 6, 3, 8, 6, 8, 6]; + +fn pick(rng: &mut Rng, m: &Model) -> Action { + let other = |rng: &mut Rng, n: usize, current: usize| ((current + 1 + rng.below(n - 1)) % n) as u8; + match rng.weighted(&KINDS) { + 0 => Action::Scene(other(rng, SCENES.len(), m.scene)), + 1 => Action::TempUp, + 2 => Action::TempDown, + 3 => Action::Light(rng.below(4) as u8), + 4 => Action::Fader(rng.below(FADERS.len()) as u8), + 5 => Action::Puck, + 6 => Action::Queue, + 7 => Action::Feed, + 8 => Action::Focus(other(rng, DOCK.len(), m.focus)), + 9 => Action::Energy, + 10 => Action::ChipsMore, + 11 => Action::Chip(rng.below(m.chips_shown().min(CHIPS.len())) as u8), + 12 => Action::Orb, + 13 => Action::Transfer(rng.below(3) as u8), + _ => Action::Visitors, + } +} + +/// The run's actions in time order, from [`START`] to `config.duration`. +pub fn schedule(config: &Config) -> Vec<Event> { + let mut rng = Rng::new(config.seed); + let mut model = Model::new(config.seed); + let mut events = Vec::new(); + let (lo, hi) = config.gap(); + let mut t = START; + let mut next_burst = START + rng.range(1.2, 2.2); + while t < config.duration { + let action = pick(&mut rng, &model); + model.apply(action); + events.push(Event { t, action }); + if t >= next_burst { + // A burst: 6–12 actions 30–60 ms apart, then a breath. + let n = 6 + rng.below(7); + for _ in 0..n { + t += rng.range(0.03, 0.06); + if t >= config.duration { + break; + } + let action = pick(&mut rng, &model); + model.apply(action); + events.push(Event { t, action }); + } + t += rng.range(0.35, 0.6); + next_burst = t + rng.range(2.0, 3.0); + } else { + t += rng.range(lo, hi); + } + } + events +} + +/// The schedule as a Rune headless script: one tap per action at its key, and an `end` mark a +/// second after the last so the springs settle on camera. +pub fn script_json(config: &Config) -> String { + let mut out = String::from("{\"events\": [\n"); + for e in schedule(config) { + out.push_str(&format!( + " {{\"t\": {:.4}, \"type\": \"tap\", \"key\": \"{}\", \"hold\": {TAP_LEAD}}},\n", + e.t - TAP_LEAD, + e.action.key() + )); + } + out.push_str(&format!(" {{\"t\": {:.4}, \"type\": \"mark\", \"name\": \"end\"}}\n]}}\n", config.duration + 1.0)); + out +} + +/// Plays a schedule against a clock: hands back each action once its time has come. +#[derive(Clone, Debug)] +pub struct Player { + events: Vec<Event>, + next: usize, +} + +impl Player { + pub fn new(config: &Config) -> Player { + Player { events: schedule(config), next: 0 } + } + + /// The actions due by `t` seconds that haven't been handed out yet. + pub fn due(&mut self, t: f64) -> impl Iterator<Item = Action> + '_ { + let start = self.next; + while self.next < self.events.len() && self.events[self.next].t <= t { + self.next += 1; + } + self.events[start..self.next].iter().map(|e| e.action) + } + + pub fn done(&self) -> bool { + self.next == self.events.len() + } + + /// The time of the next action, if any. + pub fn next_at(&self) -> Option<f64> { + self.events.get(self.next).map(|e| e.t) + } + + pub fn len(&self) -> usize { + self.events.len() + } + + pub fn is_empty(&self) -> bool { + self.events.is_empty() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn config(seed: u64, duration: f64, intensity: f64) -> Config { + Config { seed, duration, intensity, ..Config::default() } + } + + #[test] + fn a_seed_names_one_schedule() { + assert_eq!(schedule(&config(5, 10.0, 1.0)), schedule(&config(5, 10.0, 1.0))); + assert_ne!(schedule(&config(5, 10.0, 1.0)), schedule(&config(6, 10.0, 1.0))); + } + + #[test] + fn intensity_scales_the_rate_and_bursts_happen() { + let calm = schedule(&config(1, 20.0, 1.0)); + let busy = schedule(&config(1, 20.0, 2.0)); + assert!(busy.len() as f64 > calm.len() as f64 * 1.4, "{} vs {}", busy.len(), calm.len()); + let tight = calm.windows(2).filter(|w| w[1].t - w[0].t < 0.07).count(); + assert!(tight >= 30, "bursts: {tight} tight gaps"); + assert!(calm.windows(2).all(|w| w[1].t > w[0].t && w[1].t - w[0].t >= 0.03 - 1e-9)); + assert!(calm.iter().all(|e| e.t >= START && e.t < 20.0)); + } + + #[test] + fn every_action_is_takeable() { + let mut m = Model::new(2); + for e in schedule(&config(2, 30.0, 3.0)) { + match e.action { + Action::Scene(i) => assert_ne!(i as usize, m.scene), + Action::Focus(i) => assert_ne!(i as usize, m.focus), + Action::Chip(i) => assert!((i as usize) < m.chips_shown()), + _ => {} + } + m.apply(e.action); + } + } + + #[test] + fn the_player_hands_out_each_action_once() { + let c = config(3, 6.0, 1.0); + let mut p = Player::new(&c); + let mut seen = 0; + let mut t = 0.0; + while !p.done() { + t += 1.0 / 120.0; + seen += p.due(t).count(); + } + assert_eq!(seen, schedule(&c).len()); + assert!(script_json(&c).contains("\"key\": \"")); + } +} diff --git a/app/vendor/rune/examples/motion-bento/chaos/src/stress.rs b/app/vendor/rune/examples/motion-bento/chaos/src/stress.rs new file mode 100644 index 0000000..da86975 --- /dev/null +++ b/app/vendor/rune/examples/motion-bento/chaos/src/stress.rs @@ -0,0 +1,368 @@ +//! Stress mode: a wall of live controls, each a small bento of its own, that all move at once, +//! so both builds can be loaded until one of them misses its frames. +//! +//! `--load N` holds N controls. `--ramp A:B` steps from A controls to B, ×√2 a step, holding each +//! for `--hold` seconds. Everything a control shows is a pure function of the seed, its id and the +//! show time, so the two builds draw the same wall at the same moment without sharing anything +//! but this module: each control's bars retarget every 0.16–0.46 s, its reading changes every +//! frame, its switch flips, its tint drifts; every 1.7 s a twelfth of the wall goes wide and every +//! 2 s the whole wall reshuffles, so every control flies to a new place. + +use crate::look::{Lch, grid, lch}; +use crate::schedule::START; + +/// Bars in each control's meter. +pub const BARS: usize = 8; +/// The header above the wall: the title, the load and the HUD. +pub const HEADER: f32 = 120.0; +/// Seconds between reshuffles of the whole wall. +pub const SHUFFLE: f64 = 2.0; +/// Seconds between changes of which controls are wide. +pub const WIDE_EVERY: f64 = 1.7; +/// One control in this many is wide. +pub const WIDE_SHARE: usize = 12; +pub const STATUS: [&str; 6] = ["Idle", "Heat", "Cool", "Boost", "Eco", "Auto"]; +pub const HUES: [f32; 5] = [245.0, 200.0, 290.0, 165.0, 70.0]; +/// A control's width over its height. +const ASPECT: f32 = 1.5; + +/// How many controls the wall holds over time. +#[derive(Clone, Debug, PartialEq)] +pub enum Load { + Fixed(usize), + /// Each level for `hold` seconds, the first from [`START`]. + Ramp { levels: Vec<usize>, hold: f64 }, +} + +impl Load { + /// From `from` to `to` controls, ×√2 a step (rounded), `to` last. + pub fn ramp(from: usize, to: usize, hold: f64) -> Load { + let mut levels = Vec::new(); + let mut n = from.max(1) as f64; + while (n.round() as usize) < to { + levels.push(n.round() as usize); + n *= std::f64::consts::SQRT_2; + } + levels.push(to.max(from.max(1))); + Load::Ramp { levels, hold } + } + + /// `A:B`, as `--ramp` takes it. + pub fn parse_ramp(spec: &str, hold: f64) -> Result<Load, String> { + let (a, b) = spec.split_once(':').ok_or_else(|| format!("--ramp wants FROM:TO, got {spec}"))?; + let n = |s: &str| s.trim().parse::<usize>().map_err(|_| format!("--ramp: not a count: {s}")); + let (a, b) = (n(a)?, n(b)?); + if a == 0 || b < a { + return Err(format!("--ramp wants 0 < FROM ≤ TO, got {spec}")); + } + Ok(Load::ramp(a, b, hold)) + } + + pub fn levels(&self) -> &[usize] { + match self { + Load::Fixed(n) => std::slice::from_ref(n), + Load::Ramp { levels, .. } => levels, + } + } + + /// The level index at show time `t`. + pub fn step_at(&self, t: f64) -> usize { + match self { + Load::Fixed(_) => 0, + Load::Ramp { levels, hold } => (((t - START).max(0.0) / hold) as usize).min(levels.len() - 1), + } + } + + pub fn at(&self, t: f64) -> usize { + self.levels()[self.step_at(t)] + } + + /// The show a ramp needs: every level held once. `None` for a fixed load. + pub fn duration(&self) -> Option<f64> { + match self { + Load::Fixed(_) => None, + Load::Ramp { levels, hold } => Some(START + levels.len() as f64 * hold), + } + } +} + +/// The wall's rectangle in window points, below the header. +pub fn area() -> [f32; 4] { + let y = grid::PAD - 8.0 + HEADER + grid::GAP; + [grid::PAD, y, grid::WIDTH - 2.0 * grid::PAD, grid::HEIGHT - grid::PAD - y] +} + +/// A control's accent, its bars' top and bottom. +pub fn tint(hue: f32) -> Lch { + lch(0.72, 0.15, hue) +} +pub fn tint_hi(hue: f32) -> Lch { + lch(0.82, 0.12, hue) +} +pub fn tint_lo(hue: f32) -> Lch { + lch(0.52, 0.16, hue) +} +/// A hot control's card and edge. +pub fn hot_fill(hue: f32) -> Lch { + lch(0.235, 0.035, hue) +} +pub fn hot_edge(hue: f32) -> Lch { + lch(0.72, 0.15, hue).alpha(0.55) +} + +/// One control at one moment. +#[derive(Clone, Debug, PartialEq)] +pub struct Cell { + pub id: u32, + /// x, y, w, h in window points. + pub rect: [f32; 4], + pub wide: bool, + pub hue: f32, + pub on: bool, + /// Its bars average over 0.6: the card takes its tint. + pub hot: bool, + /// 0..1 of the meter's height. + pub bars: [f32; BARS], + pub progress: f32, + pub status: &'static str, + reading: f64, +} + +impl Cell { + pub fn name(&self) -> String { + format!("Zone {}", self.id + 1) + } + + /// Changes every frame. + pub fn reading(&self) -> String { + format!("{:.2}", self.reading) + } + + pub fn percent(&self) -> String { + format!("{:.0}%", self.progress * 100.0) + } +} + +/// Every size inside a control, from the height of the wall's rows, so a control looks the same +/// from 16 on the wall to a thousand, only smaller. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Metrics { + /// The scale: 1 is a 100-point-tall control. + pub u: f32, + pub pad: f32, + pub gap: f32, + pub radius: f32, + pub name: f32, + pub reading: f32, + pub small: f32, + pub dot: f32, + pub bar_gap: f32, + pub bars_h: f32, + pub foot_h: f32, + pub track_h: f32, + pub switch_w: f32, + pub switch_h: f32, + pub knob: f32, + pub shadow_y: f32, + pub shadow_blur: f32, +} + +/// Line height for a type size, as both builds set it. +pub fn lh(size: f32) -> f32 { + (size * 1.3).round() +} + +impl Metrics { + pub fn for_height(h: f32) -> Metrics { + let u = ((h / 100.0).clamp(0.25, 1.5) * 16.0).round() / 16.0; + let (pad, gap, name, reading, small) = (7.0 * u, 4.0 * u, 11.0 * u, 16.0 * u, 10.0 * u); + let foot_h = 12.0 * u; + let bars_h = (h - 2.0 * pad - 3.0 * gap - lh(name) - lh(reading) - foot_h).max(2.0); + Metrics { + u, + pad, + gap, + radius: 12.0 * u, + name, + reading, + small, + dot: 6.0 * u, + bar_gap: 3.0 * u, + bars_h, + foot_h, + track_h: 4.0 * u, + switch_w: 22.0 * u, + switch_h: 12.0 * u, + knob: 10.0 * u, + shadow_y: 4.0 * u, + shadow_blur: 12.0 * u, + } + } +} + +fn mix(seed: u64, id: u32, salt: u32, epoch: u64) -> u64 { + let mut z = seed ^ (id as u64).wrapping_mul(0x9e37_79b9_7f4a_7c15) ^ ((salt as u64) << 40) ^ epoch.wrapping_mul(0xd6e8_feb8_6659_fd93); + z = (z ^ (z >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9); + z = (z ^ (z >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb); + z ^ (z >> 31) +} + +fn unit(x: u64) -> f32 { + (x >> 40) as f32 / (1u64 << 24) as f32 +} + +fn epoch(t: f64, every: f64, phase: f32) -> u64 { + (t / every + phase as f64).max(0.0).floor() as u64 +} + +/// The wall: its controls at the last [`Wall::update`]. +pub struct Wall { + seed: u64, + cells: Vec<Cell>, + /// Ids in the order they flow into the grid, for `order_epoch`. + order: Vec<u32>, + order_epoch: Option<(u64, usize)>, + wide: Vec<bool>, + wide_epoch: Option<(u64, usize)>, + pub metrics: Metrics, + pub cols: usize, + pub rows: usize, +} + +impl Wall { + pub fn new(seed: u64) -> Wall { + Wall { + seed, + cells: Vec::new(), + order: Vec::new(), + order_epoch: None, + wide: Vec::new(), + wide_epoch: None, + metrics: Metrics::for_height(100.0), + cols: 1, + rows: 1, + } + } + + /// The controls by id: a control keeps its index for as long as it's on the wall. + pub fn cells(&self) -> &[Cell] { + &self.cells + } + + /// Moves the wall to show time `t` with `n` controls. + pub fn update(&mut self, t: f64, n: usize) { + let seed = self.seed; + self.cells.truncate(n); + while self.cells.len() < n { + let id = self.cells.len() as u32; + self.cells.push(Cell { id, rect: [0.0; 4], wide: false, hue: 0.0, on: false, hot: false, bars: [0.0; BARS], progress: 0.0, status: "", reading: 0.0 }); + } + let e = epoch(t, SHUFFLE, 0.5); + if self.order_epoch != Some((e, n)) { + self.order_epoch = Some((e, n)); + self.order = (0..n as u32).collect(); + self.order.sort_unstable_by_key(|&id| mix(seed, id, 1, e)); + } + let e = epoch(t, WIDE_EVERY, 0.0); + if self.wide_epoch != Some((e, n)) { + self.wide_epoch = Some((e, n)); + let k = n / WIDE_SHARE; + let mut ids: Vec<u32> = (0..n as u32).collect(); + if k > 0 { + ids.select_nth_unstable_by_key(k - 1, |&id| mix(seed, id, 2, e)); + } + self.wide = vec![false; n]; + for &id in &ids[..k] { + self.wide[id as usize] = true; + } + } + for c in &mut self.cells { + let id = c.id; + let h = |salt: u32| unit(mix(seed, id, salt, 0)); + let eb = epoch(t, 0.16 + 0.3 * h(3) as f64, h(4)); + for (j, b) in c.bars.iter_mut().enumerate() { + *b = 0.1 + 0.9 * unit(mix(seed, id, 100 + j as u32, eb)); + } + let level = c.bars.iter().sum::<f32>() / BARS as f32; + c.hot = level > 0.6; + c.on = unit(mix(seed, id, 5, epoch(t, 0.7 + 1.2 * h(6) as f64, h(7)))) < 0.5; + c.hue = HUES[(mix(seed, id, 8, epoch(t, 3.0, h(9))) % HUES.len() as u64) as usize]; + c.progress = ((t * (0.05 + 0.25 * h(10) as f64) + h(11) as f64).fract()) as f32; + c.status = STATUS[(mix(seed, id, 12, epoch(t, 1.1, h(13))) % STATUS.len() as u64) as usize]; + c.reading = 20.0 + 980.0 * h(14) as f64 + t * (1.5 + 30.0 * h(15) as f64); + c.wide = self.wide[id as usize]; + } + self.flow(); + } + + /// Places the controls in reading order: a wide control takes two columns, or one at a + /// row's end. The rows are sized for `n + n / WIDE_SHARE` slots, so they never overflow. + fn flow(&mut self) { + let n = self.cells.len(); + let [ax, ay, aw, ah] = area(); + let slots = (n + n / WIDE_SHARE).max(1); + let cols = (((slots as f32) * (aw / ah) / ASPECT).sqrt().round() as usize).clamp(1, slots); + let rows = slots.div_ceil(cols); + let gap = (10.0 * (40.0 / slots as f32).sqrt()).clamp(3.0, 12.0); + let cw = (aw - gap * (cols - 1) as f32) / cols as f32; + let ch = (ah - gap * (rows - 1) as f32) / rows as f32; + self.metrics = Metrics::for_height(ch); + self.cols = cols; + self.rows = rows; + let (mut col, mut row) = (0usize, 0usize); + for &id in &self.order { + let c = &mut self.cells[id as usize]; + let span = if c.wide && col + 2 <= cols { 2 } else { 1 }; + c.rect = [ax + col as f32 * (cw + gap), ay + row as f32 * (ch + gap), span as f32 * cw + (span - 1) as f32 * gap, ch]; + col += span; + if col >= cols { + col = 0; + row += 1; + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_ramp_steps_by_root_two_and_ends_on_its_target() { + let l = Load::parse_ramp("16:256", 2.5).unwrap(); + assert_eq!(l.levels(), [16, 23, 32, 45, 64, 91, 128, 181, 256]); + assert_eq!(l.at(0.0), 16); + assert_eq!(l.at(START + 2.5), 23); + assert_eq!(l.at(1e6), 256); + assert_eq!(l.duration(), Some(START + 9.0 * 2.5)); + assert!(Load::parse_ramp("8", 1.0).is_err()); + } + + #[test] + fn the_wall_is_a_function_of_time_and_fits_its_area() { + let [ax, ay, aw, ah] = area(); + for n in [1, 16, 91, 512] { + let mut a = Wall::new(7); + let mut b = Wall::new(7); + for t in [0.0, 1.3, 2.71, 6.05] { + a.update(t, n); + } + b.update(6.05, n); + assert_eq!(a.cells(), b.cells(), "{n} controls"); + for c in a.cells() { + let [x, y, w, h] = c.rect; + assert!(x >= ax - 0.01 && y >= ay - 0.01 && x + w <= ax + aw + 0.01 && y + h <= ay + ah + 0.01, "{n}: {:?}", c.rect); + } + assert_eq!(a.cells().iter().filter(|c| c.wide).count(), n / WIDE_SHARE); + } + } + + #[test] + fn readings_change_every_frame() { + let mut w = Wall::new(3); + w.update(1.0, 32); + let before: Vec<String> = w.cells().iter().map(Cell::reading).collect(); + w.update(1.0 + 1.0 / 120.0, 32); + assert!(w.cells().iter().zip(&before).all(|(c, b)| c.reading() != *b)); + } +} diff --git a/app/vendor/rune/examples/motion-bento/src/dock.rs b/app/vendor/rune/examples/motion-bento/src/dock.rs new file mode 100644 index 0000000..956057c --- /dev/null +++ b/app/vendor/rune/examples/motion-bento/src/dock.rs @@ -0,0 +1,205 @@ +//! The bottom row: five tiles that reflow so the focused one is wide. + +use motion_bento_chaos::Action; +use motion_bento_chaos::look::{color, grid, lch}; +use motion_bento_chaos::model::{CHIPS, DOCK, DOCK_KEYS, ENERGY_BARS, FILES, VISIT_MAX}; +use rune::{El, Transition, col, el, memo, row, spacer, text}; +use rune_kit::{Kit, RollingText}; + +use crate::State; +use crate::style::{c, caption, font, nums, spring, tile}; + +const DAYS: [&str; ENERGY_BARS] = ["M", "T", "W", "T", "F", "S", "S"]; + +pub fn dock(s: &State, k: &Kit) -> El { + let body_h = dock_h() - 2.0 * grid::TILE_PAD - 34.0; + let mut dock = row().key("dock").w_full().h(dock_h()).gap(grid::GAP); + for i in 0..DOCK.len() { + let focused = s.m.focus == i; + dock = dock.child(memo(DOCK_KEYS[i], (focused, version(s, i)), || { + let (aside, body) = match i { + 0 => energy(s, k, body_h), + 1 => chips(s, k), + 2 => orb(s, k, body_h), + 3 => transfers(s, k), + _ => visitors(s, k, body_h), + }; + tile(DOCK_KEYS[i], DOCK[i], aside, body) + .grow(if focused { grid::DOCK_FOCUS } else { 1.0 }) + .w(0.0) + .h_full() + .fill(c(if focused { color::TILE_FOCUS } else { color::TILE })) + .border(1.0, c(if focused { color::ACCENT.alpha(0.45) } else { color::EDGE })) + .clip_rounded(grid::RADIUS) + .on_press(move |s: &mut State| s.act(Action::Focus(i as u8))) + })); + } + dock +} + +/// What dock tile `i` shows of the model, as a memo version: f32s by their bits. +fn version(s: &State, i: usize) -> Vec<u32> { + let m = &s.m; + match i { + 0 => m.energy.iter().map(|v| v.to_bits()).chain([m.kwh_tenths]).collect(), + 1 => m.chips.iter().map(|&c| c as u32).chain([m.chips_open as u32]).collect(), + 2 => [m.orb.size, m.orb.hue, m.orb.round, m.orb.turn].map(f32::to_bits).to_vec(), + 3 => m.transfers.map(f32::to_bits).to_vec(), + _ => m.visits.iter().flat_map(|v| [v.id, v.count]).chain([m.visitors]).collect(), + } +} + +pub fn dock_h() -> f32 { + grid::HEIGHT - 2.0 * grid::PAD - grid::HEADER - grid::ROW1 - grid::ROW2 - 3.0 * grid::GAP +} + +fn energy(s: &State, k: &Kit, h: f32) -> (El, El) { + let bars_h = h - 22.0; + let mut bars = row().key("bars").w_full().h(bars_h).items_end().gap(6.0).on_press(|s: &mut State| s.act(Action::Energy)); + let mut days = row().w_full().gap(6.0); + for (i, v) in s.m.energy.iter().enumerate() { + let peak = s.m.energy.iter().cloned().fold(0.0, f32::max) == *v; + bars = bars.child( + el().grow(1.0) + .w(0.0) + .h(10.0 + v * (bars_h - 10.0)) + .radius(6.0) + .gradient(c(if peak { lch(0.8, 0.13, 240.0) } else { lch(0.5, 0.1, 250.0) }), c(if peak { color::ACCENT } else { lch(0.36, 0.07, 255.0) })) + .motion(spring(s.springs.travel)), + ); + days = days.child(row().grow(1.0).w(0.0).center().child(caption(DAYS[i]))); + } + let aside = RollingText::new("kwh", format!("{} kWh", s.m.energy_kwh())).value(s.m.kwh_tenths as f64).font(nums(12.0, 560.0)).color(c(color::TEXT_2)).build(k); + (aside, col().w_full().gap(6.0).child(bars).child(days)) +} + +fn chips(s: &State, _k: &Kit) -> (El, El) { + let snap = spring(s.springs.snap); + let mut wrap = row().w_full().flex_wrap().gap(6.0).motion(spring(s.springs.layout)); + for i in 0..s.m.chips_shown() { + let on = s.m.chips[i]; + wrap = wrap.child( + row() + .key(format!("chip{i}")) + .h(28.0) + .px(12.0) + .radius(14.0) + .center() + .fill(c(if on { color::ACCENT } else { color::WELL })) + .border(1.0, c(if on { color::ACCENT.alpha(0.0) } else { color::EDGE })) + .press_scale(0.94) + .transition(Transition::scale(0.8)) + .on_press(move |s: &mut State| s.act(Action::Chip(i as u8))) + .child(text(CHIPS[i]).font(font(13.0, 540.0)).color(c(if on { color::ON_ACCENT } else { color::TEXT_2 })).motion(snap)) + .motion(snap), + ); + } + let more = row() + .key("more") + .h(22.0) + .px(8.0) + .radius(11.0) + .center() + .hover(c(color::WELL)) + .on_press(|s: &mut State| s.act(Action::ChipsMore)) + .child(RollingText::new("more-label", if s.m.chips_open { "Less" } else { "More" }).font(font(12.0, 560.0)).color(c(color::ACCENT)).build(_k)); + (more, wrap) +} + +fn orb(s: &State, k: &Kit, h: f32) -> (El, El) { + let o = s.m.orb; + let side = 40.0 + o.size * (h - 50.0); + let tint = lch(0.7, 0.16, o.hue); + let shape = el() + .key("orb") + .size(side, side) + .radius(o.round * side) + .gradient(c(lch(0.84, 0.12, o.hue - 20.0)), c(lch(0.52, 0.19, o.hue + 25.0))) + .shadow(10.0, 44.0, c(tint.alpha(0.55))) + .rotate(o.turn.to_radians()) + .motion(spring(s.springs.morph)) + .on_press(|s: &mut State| s.act(Action::Orb)) + .child(el().size(side * 0.34, side * 0.34).absolute(side * 0.14, side * 0.14).radius(side * 0.17).fill(c(lch(1.0, 0.0, 0.0).alpha(0.28)))); + let aside = RollingText::new("hue", format!("{:.0}°", o.hue)).value(o.hue as f64).font(nums(12.0, 560.0)).color(c(color::TEXT_2)).build(k); + (aside, row().w_full().h(h).center().child(shape)) +} + +fn transfers(s: &State, k: &Kit) -> (El, El) { + let travel = spring(s.springs.travel); + let mut rows = col().w_full().gap(12.0); + for (i, name) in FILES.iter().enumerate() { + let p = s.m.transfers[i]; + let done = p >= 1.0; + let label = if done { "Done".to_string() } else { format!("{:.0}%", p * 100.0) }; + rows = rows.child( + col() + .key(format!("row{i}")) + .w_full() + .gap(6.0) + .on_press(move |s: &mut State| s.act(Action::Transfer(i as u8))) + .child( + row() + .w_full() + .center_y() + .child(text(*name).font(font(13.0, 500.0)).color(c(color::TEXT)).truncate()) + .child(spacer()) + .child(RollingText::new(format!("pct{i}"), label).value(p as f64).font(nums(12.0, 560.0)).color(c(if done { color::GOOD } else { color::TEXT_2 })).trailing().build(k)), + ) + .child( + el().w_full().h(6.0).radius(3.0).fill(c(color::WELL)).child( + el().w_frac(p.max(0.02)).h(6.0).radius(3.0).fill(c(if done { color::GOOD } else { color::ACCENT })).motion(travel), + ), + ), + ); + } + let active = s.m.transfers.iter().filter(|p| **p < 1.0).count(); + let aside = RollingText::new("active", format!("{active} active")).value(active as f64).font(font(12.0, 460.0)).color(c(color::TEXT_3)).build(k); + (aside, rows) +} + +fn thousands(n: u32) -> String { + let s = n.to_string(); + let mut out = String::new(); + for (i, ch) in s.chars().enumerate() { + if i > 0 && (s.len() - i) % 3 == 0 { + out.push(','); + } + out.push(ch); + } + out +} + +fn visitors(s: &State, k: &Kit, h: f32) -> (El, El) { + let count = row() + .key("count") + .on_press(|s: &mut State| s.act(Action::Visitors)) + .child(RollingText::new("visitors", thousands(s.m.visitors)).value(s.m.visitors as f64).font(nums(40.0, 660.0)).color(c(color::TEXT)).build(k)); + let chart_h = h - 52.0 - 18.0 - 14.0; + let newest = s.m.visits.last().map(|v| v.id); + let mut chart = row().w_full().h(chart_h).items_end().gap(4.0).motion(spring(s.springs.layout)); + for v in &s.m.visits { + let fresh = Some(v.id) == newest; + chart = chart.child( + el().key(format!("visit{}", v.id)) + .grow(1.0) + .w(0.0) + .h(4.0 + (chart_h - 4.0) * v.count as f32 / VISIT_MAX as f32) + .radius(3.0) + .fill(c(if fresh { color::GOOD } else { lch(0.4, 0.06, 160.0) })) + .transition(Transition::scale_anchor(0.05, rune::Vec2::new(0.5, 1.0))), + ); + } + let body = col().gap(4.0).child(count).child(caption("Unique visitors today")).child(el().h(10.0)).child(chart); + let live = row().gap(6.0).center_y().child(el().size(6.0, 6.0).radius(3.0).fill(c(color::GOOD))).child(caption("Live")); + (live, body) +} + +#[cfg(test)] +mod tests { + #[test] + fn thousands_groups_digits() { + assert_eq!(super::thousands(1284), "1,284"); + assert_eq!(super::thousands(999), "999"); + assert_eq!(super::thousands(1_000_000), "1,000,000"); + } +} diff --git a/app/vendor/rune/examples/motion-bento/src/main.rs b/app/vendor/rune/examples/motion-bento/src/main.rs new file mode 100644 index 0000000..82773c4 --- /dev/null +++ b/app/vendor/rune/examples/motion-bento/src/main.rs @@ -0,0 +1,330 @@ +//! Motion bento: a 1440×900 control center whose twelve tiles all move at once, driven by a +//! seeded chaos schedule. The same schedule drives the GPUI build of the same window, so the two +//! can be watched and measured side by side. See README.md. + +#![forbid(unsafe_code)] + +mod dock; +mod stress; +mod style; +#[cfg(test)] +mod tests; +mod tiles_mid; +mod tiles_top; + +use std::cell::RefCell; +use std::sync::OnceLock; +use std::time::Duration; + +use motion_bento_chaos::hud::{Readout, Replay}; +use motion_bento_chaos::look::{Springs, color, grid}; +use motion_bento_chaos::stress::Wall; +use motion_bento_chaos::model::SCENES; +use motion_bento_chaos::schedule::START; +use motion_bento_chaos::{Action, Config, Meter, Model, Player, script_json}; +use rune::{AppSpec, Cx, El, FrameOutcome, Key, KeyEvent, Live, Tx, col, el, memo, row, spacer, text}; +use rune_kit::{Kit, RollingText}; + +use style::{c, caption, font, nums, spring}; + +static CONFIG: OnceLock<Config> = OnceLock::new(); + +thread_local! { + static METER: RefCell<Option<Meter>> = const { RefCell::new(None) }; +} + +pub fn config() -> &'static Config { + CONFIG.get_or_init(Config::default) +} + +pub struct State { + pub m: Model, + pub springs: Springs, + /// The thermostat ring's drawn span, smoothed by its spring. + pub ring: Live<[f32; 2]>, + k: Kit, + /// Plays the schedule from `poll`; `None` when a script's taps drive the window instead. + player: Option<Player>, + hud: bool, + hud_lines: [String; 4], + hud_at: f64, + begun: bool, + ended: bool, + written: bool, + /// Stress mode's wall, its show time, and the HUD's source and numbers. + wall: Option<Wall>, + t: f64, + replay: Option<Replay>, + readout: Option<Readout>, + /// The live values the idiomatic wall binds; `None` with `--naive` or outside stress mode. + live: Option<stress::Bindings>, +} + +impl State { + fn new() -> State { + let cfg = config(); + let scripted = rune::tooling::headless_run().is_some_and(|r| r.script().is_some()); + let m = Model::new(cfg.seed); + let mut k = Kit::neutral(true); + k.c.bg_accent = c(color::ACCENT); + State { + ring: Live::new([0.0, m.temp_fraction()]), + m, + springs: Springs::variant(&cfg.variant), + k, + player: (!scripted && cfg.load.is_none()).then(|| Player::new(cfg)), + hud: cfg.hud, + hud_lines: Default::default(), + hud_at: f64::NEG_INFINITY, + begun: false, + ended: false, + written: false, + wall: cfg.load.as_ref().map(|_| Wall::new(cfg.seed)), + t: 0.0, + replay: cfg.hud_from.as_ref().map(|p| Replay::load(p).unwrap_or_else(|e| panic!("--hud-from: {e}"))), + readout: None, + live: (cfg.load.is_some() && !cfg.naive).then(stress::Bindings::new), + } + } + + pub fn act(&mut self, action: Action) { + self.m.apply(action); + self.ring.set([0.0, self.m.temp_fraction()]); + } + + fn write_metrics(&mut self) { + if self.written { + return; + } + self.written = true; + METER.with(|m| { + let mut m = m.borrow_mut(); + let Some(m) = m.as_mut() else { return }; + m.end(); + if let Some(path) = &config().frames + && let Err(e) = std::fs::write(path, m.frames_csv()) + { + eprintln!("motion-bento: writing {}: {e}", path.display()); + } + if let Some(path) = &config().metrics + && let Err(e) = m.write(path) + { + eprintln!("motion-bento: writing {}: {e}", path.display()); + } + }); + } +} + +fn poll(s: &mut State, t: f64, tx: &mut Tx) -> bool { + let cfg = config(); + let mut changed = false; + if let Some(p) = &mut s.player { + let due: Vec<Action> = p.due(t).collect(); + if let Some(next) = p.next_at() { + tx.wake_after(Duration::from_secs_f64((next - t).max(0.0))); + } + for a in due { + s.act(a); + changed = true; + } + } + if let (Some(wall), Some(load)) = (&mut s.wall, &cfg.load) { + let n = load.at(t); + wall.update(t, n); + s.t = t; + METER.with(|m| m.borrow_mut().as_mut().map(|m| m.tag(t, n))); + if s.hud { + s.readout = match &s.replay { + Some(r) => Some(Readout::replay(r, t)), + None => METER.with(|m| m.borrow().as_ref().map(Readout::live)), + }; + } + tx.wake_after(Duration::ZERO); + // Idiomatic: the bars, numbers and colours are live values; only a reshuffle or a new + // level runs the view. Naive: every frame does. + changed |= s.live.as_mut().is_none_or(|b| b.sync(wall, t, s.readout.as_ref())); + } + if !s.begun && t >= START { + s.begun = true; + METER.with(|m| m.borrow_mut().as_mut().map(Meter::begin)); + } + if !s.ended && t >= cfg.duration { + s.ended = true; + METER.with(|m| m.borrow_mut().as_mut().map(Meter::end)); + } + // Not `rune::is_headless()`: it reads the process's arguments, where `--variant` is ours. + let headless = rune::tooling::headless_run().is_some(); + if !headless && !cfg.stay { + if t >= cfg.duration + 1.0 { + s.write_metrics(); + tx.quit(); + } else if s.ended || t >= cfg.duration { + tx.wake_after(Duration::from_secs_f64((cfg.duration + 1.0 - t).max(0.0))); + } + } + if headless && t >= cfg.duration + 1.0 { + s.write_metrics(); + } + if s.hud && s.wall.is_none() && !headless && t - s.hud_at >= 0.25 { + s.hud_at = t; + if let Some(lines) = METER.with(|m| m.borrow().as_ref().map(Meter::hud)) { + changed |= lines != s.hud_lines; + s.hud_lines = lines; + } + tx.wake_after(Duration::from_millis(250)); + } + changed +} + +fn on_key(s: &mut State, e: &KeyEvent, _tx: &mut Tx) -> bool { + match &e.key { + Key::Text(t) if t.eq_ignore_ascii_case("h") => { + s.hud = !s.hud; + s.readout = None; + s.hud_at = f64::NEG_INFINITY; + true + } + _ => false, + } +} + +fn on_close(s: &mut State, _tx: &mut Tx) { + s.write_metrics(); +} + +fn header(s: &State) -> El { + let k = &s.k; + let mood = color::SCENE[s.m.scene]; + let scene = row() + .h(34.0) + .px(14.0) + .gap(8.0) + .radius(17.0) + .center_y() + .fill(c(color::TILE)) + .border(1.0, c(color::EDGE)) + .motion(spring(s.springs.layout)) + .child(el().size(10.0, 10.0).radius(5.0).fill(c(mood)).motion(spring(s.springs.morph))) + .child(RollingText::new("head-scene", SCENES[s.m.scene]).value(s.m.scene as f64).font(font(13.0, 560.0)).color(c(color::TEXT)).build(k)); + let events = row() + .gap(6.0) + .center_y() + .child(RollingText::new("events", s.m.events.to_string()).value(s.m.events as f64).font(nums(13.0, 600.0)).color(c(color::TEXT)).build(k)) + .child(caption("events")); + row() + .w_full() + .h(grid::HEADER) + .center_y() + .gap(16.0) + .child( + col() + .gap(2.0) + .child(text("Studio").font(font(24.0, 680.0)).color(c(color::TEXT))) + .child(caption("Control center · Friday evening")), + ) + .child(spacer()) + .child(events) + .child(scene) +} + +fn hud(s: &State) -> El { + let mut lines = col() + .key("hud") + .absolute(grid::WIDTH - grid::PAD - 300.0, 12.0) + .w(300.0) + .padding(12.0) + .gap(3.0) + .radius(12.0) + .fill(c(color::BG.alpha(0.92))) + .border(1.0, c(color::ACCENT.alpha(0.4))) + .raise(); + for l in &s.hud_lines { + lines = lines.child(text(l.clone()).font(nums(11.0, 500.0).mono()).color(c(color::TEXT_2))); + } + lines +} + +fn view(s: &State, _: &mut Cx<State>) -> El { + if let Some(wall) = &s.wall { + return stress::view(s, wall); + } + // Each tile builds again only when the part of the model it shows changes; the springs and + // the kit never change. + let (k, m) = (&s.k, &s.m); + let mut root = col() + .w(grid::WIDTH) + .h(grid::HEIGHT) + .px(grid::PAD) + .pb(grid::PAD) + .pt(grid::PAD - 8.0) + .gap(grid::GAP) + .fill(c(color::BG)) + .motion(spring(s.springs.layout)) + .child(memo("header", (m.scene, m.events), || header(s))) + .child( + row() + .h(grid::ROW1) + .gap(grid::GAP) + .child(memo("scene", (m.scene, m.lights, m.chips, m.temp.to_bits()), || tiles_top::scenes(s, k))) + .child(memo("thermo", m.temp.to_bits(), || tiles_top::thermostat(s, k))) + .child(memo("lights", m.lights, || tiles_top::lights(s, k))), + ) + .child( + row() + .h(grid::ROW2) + .gap(grid::GAP) + .child(memo("mixer", m.faders.map(f32::to_bits), || tiles_mid::mixer(s, k))) + .child(memo("xy", m.puck.map(f32::to_bits), || tiles_mid::xy(s, k))) + .child(memo("queue", m.queue.iter().map(|c| (c.id, c.track)).collect::<Vec<_>>(), || tiles_mid::queue(s, k))) + .child(memo("feed", m.feed.iter().map(|f| (f.id, f.kind, f.minute)).collect::<Vec<_>>(), || tiles_mid::feed(s, k))), + ) + .child(dock::dock(s, k)); + if s.hud { + root = root.child(hud(s)); + } + root +} + +fn main() { + let (cfg, rest) = Config::parse(std::env::args()).unwrap_or_else(|e| { + eprintln!("motion-bento: {e}"); + std::process::exit(2); + }); + if let Some(path) = &cfg.emit_script { + std::fs::write(path, script_json(&cfg)).unwrap_or_else(|e| panic!("writing {}: {e}", path.display())); + return; + } + CONFIG.set(cfg).ok(); + METER.with(|m| { + let mut meter = Meter::new("rune", 120.0); + meter.note("work", "update_ms + encode_ms: events, poll, view, layout, paint, upload and encode, to submit"); + meter.note("build", "update_ms: events, poll, view, layout and paint"); + meter.note("variant", &config().variant); + meter.note("seed", &config().seed.to_string()); + meter.note("mode", if config().naive { "naive" } else { "idiomatic" }); + *m.borrow_mut() = Some(meter); + }); + let spec = AppSpec { + poll: Some(poll), + on_key: Some(on_key), + min_size: Some((grid::WIDTH, grid::HEIGHT)), + ..AppSpec::new("Motion bento", (grid::WIDTH, grid::HEIGHT), State::new, view) + }; + rune::App::new(spec) + .args(rest.into_iter().skip(1)) + .on_close(on_close) + .on_frame_encoded(|f| { + let (FrameOutcome::Drawn, Some(start)) = (f.outcome(), f.started()) else { return }; + let build = f.update_ms().unwrap_or(0.0); + let work = build + f.encode_ms().unwrap_or(0.0); + METER.with(|m| { + if let Some(m) = m.borrow_mut().as_mut() { + if let Some(hz) = f.refresh_hz() { + m.set_refresh(hz); + } + m.frame_with_build(start, work, build); + } + }); + }) + .run(); +} diff --git a/app/vendor/rune/examples/motion-bento/src/stress/hud.rs b/app/vendor/rune/examples/motion-bento/src/stress/hud.rs new file mode 100644 index 0000000..c13170f --- /dev/null +++ b/app/vendor/rune/examples/motion-bento/src/stress/hud.rs @@ -0,0 +1,84 @@ +//! The stress HUD built once, its numbers and graph bars live values. + +use motion_bento_chaos::hud::{BUDGET_60, BUDGET_120, GRAPH, GRAPH_MAX, Readout}; +use motion_bento_chaos::look::{Lch, color, grid}; +use motion_bento_chaos::stress::HEADER; +use rune::{Color, El, Live, LiveText, col, el, row, text}; + +use super::{GRAPH_H, GRAPH_W, HUD_W, OVER, grade_color}; +use crate::style::{c, caption, nums}; + +pub struct Hud { + source: &'static str, + big: LiveText, + big_color: Live<Color>, + detail: LiveText, + rate: LiveText, + bars: [(Live<[f32; 4]>, Live<Color>); GRAPH], +} + +impl Hud { + pub fn new() -> Hud { + Hud { + source: "", + big: LiveText::new(""), + big_color: Live::new(c(color::GOOD)), + detail: LiveText::new(""), + rate: LiveText::new(""), + bars: std::array::from_fn(|_| (Live::new([0.0; 4]), Live::new(c(color::GOOD)))), + } + } + + pub fn set(&mut self, r: &Readout) { + self.source = r.source; + self.big.set(r.big()); + self.big_color.set(c(grade_color(r.ms))); + self.detail.set(r.detail()); + self.rate.set(r.rate()); + let bw = GRAPH_W / GRAPH as f32; + for (i, (rect, fill)) in self.bars.iter().enumerate() { + let ms = r.graph.get(i).copied().unwrap_or(0.0); + let h = (ms / GRAPH_MAX).min(1.0) * GRAPH_H; + rect.set([i as f32 * bw, GRAPH_H - h, bw, h]); + fill.set(c(grade_color(ms))); + } + } + + pub fn view(&self) -> El { + let mut graph = el().size(GRAPH_W, GRAPH_H).absolute(0.0, 0.0); + for (rect, fill) in &self.bars { + graph = graph.child(el().absolute(0.0, 0.0).size(0.0, 0.0).fill(c(color::GOOD)).live_fill(fill).live_rect(rect)); + } + let line = |ms: f32, col: Lch| el().size(GRAPH_W, 1.0).absolute(0.0, GRAPH_H - ms / GRAPH_MAX * GRAPH_H).fill(c(col)); + let label = |ms: f32, s: &str| text(s.to_owned()).font(nums(10.0, 560.0)).color(c(color::TEXT_2)).absolute(GRAPH_W + 6.0, GRAPH_H - ms / GRAPH_MAX * GRAPH_H - 7.0); + let graph = el() + .size(GRAPH_W + 40.0, GRAPH_H) + .child(el().size(GRAPH_W, GRAPH_H).absolute(0.0, 0.0).radius(4.0).fill(c(color::WELL))) + .child(graph) + .child(line(BUDGET_120, color::ACCENT)) + .child(line(BUDGET_60, OVER)) + .child(label(BUDGET_120, "120 Hz")) + .child(label(BUDGET_60, "60 Hz")); + let small = |placeholder: &str, live: &LiveText| text(placeholder.to_owned()).font(nums(11.0, 500.0)).color(c(color::TEXT_2)).live_text(live); + row() + .key("hud") + .absolute(grid::WIDTH - grid::PAD - HUD_W, grid::PAD - 8.0) + .size(HUD_W, HEADER) + .padding(12.0) + .gap(14.0) + .radius(14.0) + .fill(c(color::TILE)) + .border(1.0, c(color::ACCENT.alpha(0.4))) + .raise() + .child( + col() + .w(HUD_W - GRAPH_W - 40.0 - 14.0 - 24.0) + .gap(1.0) + .child(caption(format!("Rune · {}", self.source))) + .child(text("00.0 ms").font(nums(36.0, 700.0)).color(c(color::GOOD)).live_text_color(&self.big_color).live_text(&self.big)) + .child(small("build + layout + paint · p95 00.0", &self.detail)) + .child(small("≈ 000 fps at 120 Hz · 000 missed / s", &self.rate)), + ) + .child(graph) + } +} diff --git a/app/vendor/rune/examples/motion-bento/src/stress/live.rs b/app/vendor/rune/examples/motion-bento/src/stress/live.rs new file mode 100644 index 0000000..4e6a3b1 --- /dev/null +++ b/app/vendor/rune/examples/motion-bento/src/stress/live.rs @@ -0,0 +1,277 @@ +//! The wall as Rune means it to be built. A control's card is built once for each size it takes +//! (`memo`), and placed again only when the wall reshuffles. Everything that moves inside it, its +//! reading, bars, switch, progress and colours, is a live value `poll` sets, so on most frames +//! the view doesn't run and nothing commits. + +use motion_bento_chaos::hud::Readout; +use motion_bento_chaos::look::{Springs, color, grid}; +use motion_bento_chaos::stress::{self, BARS, Cell, HEADER, HUES, Metrics, Wall, lh}; +use rune::{Align, Color, El, Live, LiveText, Transition, col, el, memo, row, spacer, text}; + +use super::hud::Hud; +use super::{HUD_W, KNOB, SWITCH_OFF}; +use crate::State; +use crate::style::{c, caption, font, nums, spring}; + +/// One hue's colours, worked out once. +struct Palette { + tint: Color, + glow: Color, + hi: Color, + lo: Color, + hot_fill: Color, + hot_edge: Color, +} + +/// What moves inside one control. +struct Control { + reading: LiveText, + percent: LiveText, + status: LiveText, + tint: Live<Color>, + glow: Live<Color>, + hi: Live<Color>, + lo: Live<Color>, + card: Live<Color>, + edge: Live<Color>, + switch: Live<Color>, + knob: Live<[f32; 2]>, + bars: [Live<[f32; 4]>; BARS], + progress: Live<[f32; 4]>, + shown: (u32, &'static str), +} + +impl Control { + fn new() -> Control { + let unset = || Live::new(Color::TRANSPARENT); + Control { + reading: LiveText::new(""), + percent: LiveText::new(""), + status: LiveText::new(""), + tint: unset(), + glow: unset(), + hi: unset(), + lo: unset(), + card: Live::new(c(color::TILE)), + edge: Live::new(c(color::EDGE)), + switch: Live::new(c(SWITCH_OFF)), + knob: Live::new([0.0; 2]), + bars: std::array::from_fn(|_| Live::new([0.0; 4])), + progress: Live::new([0.0; 4]), + shown: (u32::MAX, ""), + } + } + + fn set(&mut self, cell: &Cell, m: &Metrics, p: &Palette) { + let [_, _, w, _] = cell.rect; + self.reading.set(cell.reading()); + let pct = (cell.progress * 100.0).round() as u32; + if self.shown.0 != pct { + self.percent.set(cell.percent()); + } + if self.shown.1 != cell.status { + self.status.set(cell.status); + } + self.shown = (pct, cell.status); + self.tint.set(p.tint); + self.glow.set(p.glow); + self.hi.set(p.hi); + self.lo.set(p.lo); + let (card, edge) = if cell.hot { (p.hot_fill, p.hot_edge) } else { (c(color::TILE), c(color::EDGE)) }; + self.card.set(card); + self.edge.set(edge); + self.switch.set(if cell.on { p.tint } else { c(SWITCH_OFF) }); + let inset = (m.switch_h - m.knob) / 2.0; + self.knob.set([if cell.on { m.switch_w - 2.0 * inset - m.knob } else { 0.0 }, 0.0]); + let inner = w - 2.0 * m.pad; + let bar_w = (inner - (BARS - 1) as f32 * m.bar_gap) / BARS as f32; + for (j, (live, &b)) in self.bars.iter().zip(&cell.bars).enumerate() { + let h = b * m.bars_h; + live.set([j as f32 * (bar_w + m.bar_gap), m.bars_h - h, bar_w, h]); + } + let track = inner - 2.0 * m.gap - m.switch_w; + self.progress.set([0.0, 0.0, cell.progress * track, m.track_h]); + } +} + +/// The live values the wall's view binds, and what it last built from. +pub struct Bindings { + palette: Vec<Palette>, + controls: Vec<Control>, + t: LiveText, + pub(super) hud: Hud, + /// The controls' rects the view last placed: a change needs a commit. + built: Vec<[f32; 4]>, +} + +impl Bindings { + pub fn new() -> Bindings { + let palette = HUES + .iter() + .map(|&h| Palette { + tint: c(stress::tint(h)), + glow: c(stress::tint(h).alpha(0.8)), + hi: c(stress::tint_hi(h)), + lo: c(stress::tint_lo(h)), + hot_fill: c(stress::hot_fill(h)), + hot_edge: c(stress::hot_edge(h)), + }) + .collect(); + Bindings { palette, controls: Vec::new(), t: LiveText::new(""), hud: Hud::new(), built: Vec::new() } + } + + /// Sets every live value to the wall at show time `t`. True when the wall's shape changed + /// (a control came or went, or moved or resized), which only a commit can show. + pub fn sync(&mut self, wall: &Wall, t: f64, readout: Option<&Readout>) -> bool { + let cells = wall.cells(); + // Controls are never dropped, so a card a memo kept still binds its own values. + while self.controls.len() < cells.len() { + self.controls.push(Control::new()); + } + for (cell, control) in cells.iter().zip(&mut self.controls) { + let hue = HUES.iter().position(|&h| h == cell.hue).unwrap_or(0); + control.set(cell, &wall.metrics, &self.palette[hue]); + } + self.t.set(format!("{t:.2} s")); + if let Some(r) = readout { + self.hud.set(r); + } + let moved = self.built.len() != cells.len() || cells.iter().zip(&self.built).any(|(c, r)| c.rect != *r); + if moved { + self.built.clear(); + self.built.extend(cells.iter().map(|c| c.rect)); + } + moved + } +} + +pub fn view(s: &State, wall: &Wall, b: &Bindings) -> El { + let mut root = el().w(grid::WIDTH).h(grid::HEIGHT).fill(c(color::BG)).child(header(s, wall, b)); + for (cell, control) in wall.cells().iter().zip(&b.controls) { + root = root.child(card(&s.springs, cell, &wall.metrics, control)); + } + if s.readout.is_some() { + root = root.child(b.hud.view()); + } + root +} + +fn header(s: &State, wall: &Wall, b: &Bindings) -> El { + let cfg = crate::config(); + let load = cfg.load.as_ref(); + let steps = load.map_or(1, |l| l.levels().len()); + let n = wall.cells().len(); + // The view runs whenever the count changes, so the step it reads is current. + let step = load.map_or(0, |l| l.step_at(s.t)); + col() + .absolute(grid::PAD, grid::PAD - 8.0) + .size(grid::WIDTH - 2.0 * grid::PAD - HUD_W - grid::GAP, HEADER) + .gap(4.0) + .child( + row() + .gap(10.0) + .center_y() + .child(text("Rune").font(font(24.0, 680.0)).color(c(color::ACCENT))) + .child(text("stress wall").font(font(24.0, 680.0)).color(c(color::TEXT))), + ) + .child( + row() + .gap(4.0) + .child(caption(format!("Seed {} · every control retargets, ticks and reflows at once · t", cfg.seed))) + .child(text("00.00 s").font(nums(12.0, 460.0)).color(c(color::TEXT_3)).live_text(&b.t)), + ) + .child( + row() + .gap(10.0) + .items_end() + .child(text(format!("{n}")).font(nums(40.0, 700.0)).color(c(color::TEXT))) + .child(text("live controls").font(font(16.0, 560.0)).color(c(color::TEXT_2))) + .child(caption(format!("step {} of {steps} · {}×{} grid", step + 1, wall.cols, wall.rows))), + ) +} + +/// The card is placed on each commit; what's inside builds once per size. +fn card(springs: &Springs, cell: &Cell, m: &Metrics, b: &Control) -> El { + let [x, y, w, h] = cell.rect; + let layout = spring(springs.layout); + let id = cell.id; + col() + .key(format!("z{id}")) + .absolute(x, y) + .size(w, h) + .padding(m.pad) + .radius(m.radius) + .fill(c(color::TILE)) + .live_fill(b.card.smooth(layout)) + .border(1.0, c(color::EDGE)) + .live_border(b.edge.smooth(layout)) + .shadow(m.shadow_y, m.shadow_blur, Color::BLACK.alpha(0.35)) + .clip_rounded(m.radius) + .motion(layout) + .transition(Transition::scale(0.85).combined(Transition::opacity())) + .child(memo(format!("c{id}"), (w.to_bits(), h.to_bits()), || inside(springs, cell, m, b))) +} + +fn inside(springs: &Springs, cell: &Cell, m: &Metrics, b: &Control) -> El { + let [_, _, w, _] = cell.rect; + let (travel, snap) = (spring(springs.travel), spring(springs.snap)); + // Authored colours only until the first latch: the live values own them. + let ink = c(color::ACCENT); + let inner = w - 2.0 * m.pad; + let bar_w = (inner - (BARS - 1) as f32 * m.bar_gap) / BARS as f32; + let mut bars = el().w_full().h(m.bars_h); + for live in &b.bars { + bars = bars.child( + el().absolute(0.0, 0.0) + .size(bar_w, m.bars_h) + .radius(2.0 * m.u) + .gradient(ink, ink) + .live_gradient(b.hi.smooth(travel), b.lo.smooth(travel)) + .live_rect(live.smooth(travel)), + ); + } + let inset = (m.switch_h - m.knob) / 2.0; + let switch = el() + .size(m.switch_w, m.switch_h) + .radius(m.switch_h / 2.0) + .fill(c(SWITCH_OFF)) + .live_fill(b.switch.smooth(snap)) + .child(el().size(m.knob, m.knob).absolute(inset, inset).radius(m.knob / 2.0).fill(c(KNOB)).live_offset(b.knob.smooth(snap))); + let track = el() + .grow(1.0) + .h(m.track_h) + .radius(m.track_h / 2.0) + .fill(c(color::WELL)) + .child(el().absolute(0.0, 0.0).size(0.0, m.track_h).radius(m.track_h / 2.0).fill(ink).live_fill(&b.tint).live_rect(&b.progress)); + col() + .w_full() + .h_full() + .gap(m.gap) + .child( + row() + .h(lh(m.name)) + .gap(m.gap) + .center_y() + .child( + el().size(m.dot, m.dot) + .radius(m.dot / 2.0) + .fill(ink) + .live_fill(&b.tint) + .shadow(0.0, 2.0 * m.dot, ink) + .live_shadow(&b.glow), + ) + .child(text(cell.name()).font(font(m.name, 520.0)).color(c(color::TEXT_2))) + .child(spacer()) + .child(text("Boost").font(font(m.small, 600.0)).color(ink).align(Align::End).live_text_color(&b.tint).live_text(&b.status)), + ) + .child( + row() + .h(lh(m.reading)) + .center_y() + .child(text("0000.00").font(nums(m.reading, 640.0)).color(c(color::TEXT)).live_text(&b.reading)) + .child(spacer()) + .child(text("100%").font(nums(m.small, 500.0)).color(c(color::TEXT_3)).align(Align::End).live_text(&b.percent)), + ) + .child(bars) + .child(row().w_full().h(m.foot_h).gap(2.0 * m.gap).center_y().child(track).child(switch)) +} diff --git a/app/vendor/rune/examples/motion-bento/src/stress/mod.rs b/app/vendor/rune/examples/motion-bento/src/stress/mod.rs new file mode 100644 index 0000000..6fbffb0 --- /dev/null +++ b/app/vendor/rune/examples/motion-bento/src/stress/mod.rs @@ -0,0 +1,37 @@ +//! Stress mode's view: the wall of controls under a header with the load and, with `--hud`, the +//! frame-time HUD. What the wall shows comes from `motion_bento_chaos::stress`; this only draws it. +//! +//! By default the wall is built the way Rune is meant to be used ([`live`]): memoised cards and +//! live values, so a frame where only numbers, bars and colours move runs no view and commits +//! nothing. `--naive` ([`naive`]) builds everything every frame. + +mod hud; +mod live; +mod naive; + +use motion_bento_chaos::hud::grade; +use motion_bento_chaos::look::{Lch, color, lch}; +use motion_bento_chaos::stress::Wall; +use rune::El; + +pub use live::Bindings; + +use crate::State; + +const SWITCH_OFF: Lch = lch(0.44, 0.012, 258.0); +const KNOB: Lch = lch(0.98, 0.0, 0.0); +const OVER: Lch = lch(0.66, 0.2, 25.0); +const HUD_W: f32 = 660.0; +const GRAPH_W: f32 = 300.0; +const GRAPH_H: f32 = 92.0; + +pub fn grade_color(ms: f32) -> Lch { + [color::GOOD, color::WARM, OVER][grade(ms)] +} + +pub fn view(s: &State, wall: &Wall) -> El { + match &s.live { + Some(b) => live::view(s, wall, b), + None => naive::view(s, wall), + } +} diff --git a/app/vendor/rune/examples/motion-bento/src/stress/naive.rs b/app/vendor/rune/examples/motion-bento/src/stress/naive.rs new file mode 100644 index 0000000..f7ad1ed --- /dev/null +++ b/app/vendor/rune/examples/motion-bento/src/stress/naive.rs @@ -0,0 +1,145 @@ +//! `--naive`: the whole wall built again every frame, as a first port draws it. Every number, +//! bar and colour that moves reruns the view and commits the whole tree. + +use motion_bento_chaos::hud::{BUDGET_60, BUDGET_120, GRAPH, GRAPH_MAX, Readout}; +use motion_bento_chaos::look::{Lch, color, grid, lch}; +use motion_bento_chaos::stress::{self, Cell, HEADER, Metrics, Wall, lh}; +use rune::{El, Transition, col, el, row, spacer, text}; + +use super::{GRAPH_H, GRAPH_W, HUD_W, KNOB, OVER, SWITCH_OFF, grade_color}; +use crate::State; +use crate::style::{c, caption, font, nums, spring}; + +pub fn view(s: &State, wall: &Wall) -> El { + let mut root = el().w(grid::WIDTH).h(grid::HEIGHT).fill(c(color::BG)).child(header(s, wall)); + for cell in wall.cells() { + root = root.child(control(s, cell, &wall.metrics)); + } + if let Some(r) = &s.readout { + root = root.child(hud(r)); + } + root +} + +fn header(s: &State, wall: &Wall) -> El { + let load = crate::config().load.as_ref(); + let steps = load.map_or(1, |l| l.levels().len()); + let step = load.map_or(0, |l| l.step_at(s.t)); + let n = wall.cells().len(); + col() + .absolute(grid::PAD, grid::PAD - 8.0) + .size(grid::WIDTH - 2.0 * grid::PAD - HUD_W - grid::GAP, HEADER) + .gap(4.0) + .child( + row() + .gap(10.0) + .center_y() + .child(text("Rune").font(font(24.0, 680.0)).color(c(color::ACCENT))) + .child(text("stress wall").font(font(24.0, 680.0)).color(c(color::TEXT))), + ) + .child(caption(format!("Seed {} · every control retargets, ticks and reflows at once · t {:.2} s", crate::config().seed, s.t))) + .child( + row() + .gap(10.0) + .items_end() + .child(text(format!("{n}")).font(nums(40.0, 700.0)).color(c(color::TEXT))) + .child(text("live controls").font(font(16.0, 560.0)).color(c(color::TEXT_2))) + .child(caption(format!("step {} of {steps} · {}×{} grid", step + 1, wall.cols, wall.rows))), + ) +} + +fn control(s: &State, cell: &Cell, m: &Metrics) -> El { + let [x, y, w, h] = cell.rect; + let tint = stress::tint(cell.hue); + let (fill, edge) = if cell.hot { (stress::hot_fill(cell.hue), stress::hot_edge(cell.hue)) } else { (color::TILE, color::EDGE) }; + let travel = spring(s.springs.travel); + let snap = spring(s.springs.snap); + let mut bars = row().w_full().h(m.bars_h).gap(m.bar_gap).items_end(); + for &b in &cell.bars { + bars = bars.child(el().grow(1.0).h(b * m.bars_h).radius(2.0 * m.u).gradient(c(stress::tint_hi(cell.hue)), c(stress::tint_lo(cell.hue))).motion(travel)); + } + let inset = (m.switch_h - m.knob) / 2.0; + let switch = el() + .size(m.switch_w, m.switch_h) + .radius(m.switch_h / 2.0) + .fill(c(if cell.on { tint } else { SWITCH_OFF })) + .motion(snap) + .child(el().size(m.knob, m.knob).absolute(if cell.on { m.switch_w - inset - m.knob } else { inset }, inset).radius(m.knob / 2.0).fill(c(KNOB)).motion(snap)); + let track = el() + .grow(1.0) + .h(m.track_h) + .radius(m.track_h / 2.0) + .fill(c(color::WELL)) + .child(el().w_frac(cell.progress).h(m.track_h).radius(m.track_h / 2.0).fill(c(tint))); + col() + .key(format!("z{}", cell.id)) + .absolute(x, y) + .size(w, h) + .padding(m.pad) + .gap(m.gap) + .radius(m.radius) + .fill(c(fill)) + .border(1.0, c(edge)) + .shadow(m.shadow_y, m.shadow_blur, c(lch(0.0, 0.0, 0.0).alpha(0.35))) + .clip_rounded(m.radius) + .motion(spring(s.springs.layout)) + .transition(Transition::scale(0.85).combined(Transition::opacity())) + .child( + row() + .h(lh(m.name)) + .gap(m.gap) + .center_y() + .child(el().size(m.dot, m.dot).radius(m.dot / 2.0).fill(c(tint)).shadow(0.0, 2.0 * m.dot, c(tint.alpha(0.8)))) + .child(text(cell.name()).font(font(m.name, 520.0)).color(c(color::TEXT_2))) + .child(spacer()) + .child(text(cell.status).font(font(m.small, 600.0)).color(c(tint))), + ) + .child( + row() + .h(lh(m.reading)) + .center_y() + .child(text(cell.reading()).font(nums(m.reading, 640.0)).color(c(color::TEXT))) + .child(spacer()) + .child(text(cell.percent()).font(nums(m.small, 500.0)).color(c(color::TEXT_3))), + ) + .child(bars) + .child(row().w_full().h(m.foot_h).gap(2.0 * m.gap).center_y().child(track).child(switch)) +} + +fn hud(r: &Readout) -> El { + let bw = GRAPH_W / GRAPH as f32; + let mut graph = row().size(GRAPH_W, GRAPH_H).items_end(); + for &ms in &r.graph { + graph = graph.child(el().w(bw).h((ms / GRAPH_MAX).min(1.0) * GRAPH_H).fill(c(grade_color(ms)))); + } + let line = |ms: f32, col: Lch| el().size(GRAPH_W, 1.0).absolute(0.0, GRAPH_H - ms / GRAPH_MAX * GRAPH_H).fill(c(col)); + let label = |ms: f32, s: &str| text(s.to_owned()).font(nums(10.0, 560.0)).color(c(color::TEXT_2)).absolute(GRAPH_W + 6.0, GRAPH_H - ms / GRAPH_MAX * GRAPH_H - 7.0); + let graph = el() + .size(GRAPH_W + 40.0, GRAPH_H) + .child(el().size(GRAPH_W, GRAPH_H).absolute(0.0, 0.0).radius(4.0).fill(c(color::WELL))) + .child(graph.absolute(0.0, 0.0)) + .child(line(BUDGET_120, color::ACCENT)) + .child(line(BUDGET_60, OVER)) + .child(label(BUDGET_120, "120 Hz")) + .child(label(BUDGET_60, "60 Hz")); + row() + .key("hud") + .absolute(grid::WIDTH - grid::PAD - HUD_W, grid::PAD - 8.0) + .size(HUD_W, HEADER) + .padding(12.0) + .gap(14.0) + .radius(14.0) + .fill(c(color::TILE)) + .border(1.0, c(color::ACCENT.alpha(0.4))) + .raise() + .child( + col() + .w(HUD_W - GRAPH_W - 40.0 - 14.0 - 24.0) + .gap(1.0) + .child(caption(format!("Rune · {}", r.source))) + .child(text(r.big()).font(nums(36.0, 700.0)).color(c(grade_color(r.ms)))) + .child(text(r.detail()).font(nums(11.0, 500.0)).color(c(color::TEXT_2))) + .child(text(r.rate()).font(nums(11.0, 500.0)).color(c(color::TEXT_2))), + ) + .child(graph) +} diff --git a/app/vendor/rune/examples/motion-bento/src/style.rs b/app/vendor/rune/examples/motion-bento/src/style.rs new file mode 100644 index 0000000..699673f --- /dev/null +++ b/app/vendor/rune/examples/motion-bento/src/style.rs @@ -0,0 +1,72 @@ +//! The shared look in Rune terms: colours, type and the tile frame every tile sits in. + +use motion_bento_chaos::look::{self, Lch, color, grid}; +use rune::{Color, El, TextStyle, col, oklcha, row, spacer, text}; + +pub fn c(l: Lch) -> Color { + oklcha(l.l, l.c, l.h, l.a) +} + +pub fn spring(s: look::Spring) -> rune::Spring { + rune::Spring::new(s.duration, s.bounce) +} + +pub fn font(size: f32, weight: f32) -> TextStyle { + TextStyle::new(size, weight).lh((size * 1.3).round()) +} + +/// Tabular figures, so changing numbers don't jitter sideways. +pub fn nums(size: f32, weight: f32) -> TextStyle { + font(size, weight).features("'tnum' 1") +} + +pub fn title(s: &str) -> El { + text(s).font(font(13.0, 560.0)).color(c(color::TEXT_2)) +} + +pub fn caption(s: impl Into<String>) -> El { + text(s.into()).font(font(12.0, 460.0)).color(c(color::TEXT_3)) +} + +/// A tile: a rounded card with a title row (title on the left, `aside` on the right) over `body`. +pub fn tile(key: &str, name: &str, aside: El, body: El) -> El { + col() + .key(key.to_owned()) + .radius(grid::RADIUS) + .fill(c(color::TILE)) + .border(1.0, c(color::EDGE)) + .padding(grid::TILE_PAD) + .gap(14.0) + .child(row().key("head").h(20.0).center_y().gap(8.0).child(title(name)).child(spacer()).child(aside)) + .child(body) +} + +/// Column width in the 4-column grid. +pub fn col_w() -> f32 { + (grid::WIDTH - 2.0 * grid::PAD - 3.0 * grid::GAP) / 4.0 +} + +/// A tile's inside width for a span of `cols` columns. +pub fn inner_w(cols: f32) -> f32 { + col_w() * cols + grid::GAP * (cols - 1.0) - 2.0 * grid::TILE_PAD +} + +/// A tile's body height for a row of height `h`. +pub fn inner_h(h: f32) -> f32 { + h - 2.0 * grid::TILE_PAD - 20.0 - 14.0 +} + +/// A rounded button in the well colour. +pub fn well_button(key: &str, label: &str, w: f32, h: f32) -> El { + row() + .key(key.to_owned()) + .size(w, h) + .radius(h * 0.32) + .center() + .fill(c(color::WELL)) + .border(1.0, c(color::EDGE)) + .hover(c(color::WELL_HI)) + .press(c(color::WELL_HI)) + .press_scale(0.94) + .child(text(label.to_owned()).font(font(15.0, 560.0)).color(c(color::TEXT))) +} diff --git a/app/vendor/rune/examples/motion-bento/src/tests.rs b/app/vendor/rune/examples/motion-bento/src/tests.rs new file mode 100644 index 0000000..9c2f647 --- /dev/null +++ b/app/vendor/rune/examples/motion-bento/src/tests.rs @@ -0,0 +1,45 @@ +use motion_bento_chaos::schedule::{TAP_LEAD, schedule}; +use motion_bento_chaos::{Config, Model}; +use rune::{Env, Runtime}; + +use super::{State, view}; +use motion_bento_chaos::look::grid; + +/// Taps every scheduled action's key the way the headless script does, and checks the window's +/// model after each tap against the model the schedule simulated. A tap that lands on the wrong +/// element, or on none, shows up as the first action where the two part. +#[test] +fn script_taps_reach_the_same_state_as_the_schedule() { + for seed in [1, 2, 3] { + let cfg = Config { seed, duration: 12.0, ..Config::default() }; + let mut rt = Runtime::new(State::new(), view, (grid::WIDTH, grid::HEIGHT), Env { system_dark: true, scale: 1.0 }); + rt.state.player = None; + rt.state.m = Model::new(seed); + let mut want = Model::new(seed); + let dt = 1.0 / 60.0; + let mut t = 0.0; + rt.frame(0.0); + for (n, e) in schedule(&cfg).into_iter().enumerate() { + while t + dt <= e.t - TAP_LEAD { + t += dt; + rt.frame(dt); + } + let key = e.action.key(); + let (x, y) = rt.find(&key).unwrap_or_else(|| panic!("seed {seed}: event {n} at {:.3}: no element {key}", e.t)); + rt.pointer_move(x, y); + rt.pointer_down(x, y); + t += dt; + rt.frame(dt); + rt.pointer_up(x, y); + rt.frame(0.0); + want.apply(e.action); + assert_eq!( + format!("{:?}", rt.state.m), + format!("{want:?}"), + "seed {seed}: event {n} at {:.3}: tapping {key} ({x:.0}, {y:.0}) for {:?}", + e.t, + e.action + ); + } + } +} diff --git a/app/vendor/rune/examples/motion-bento/src/tiles_mid.rs b/app/vendor/rune/examples/motion-bento/src/tiles_mid.rs new file mode 100644 index 0000000..8dc383f --- /dev/null +++ b/app/vendor/rune/examples/motion-bento/src/tiles_mid.rs @@ -0,0 +1,228 @@ +//! The middle row: the mixer, the XY pad, the play queue and the activity feed. + +use motion_bento_chaos::Action; +use motion_bento_chaos::look::{color, grid, lch}; +use motion_bento_chaos::model::{FADERS, FEED_KINDS, TRACKS}; +use rune::{Edge, El, Shape, Transition, canvas, col, el, row, spacer, text}; +use rune_kit::{Kit, RollingText}; + +use crate::State; +use crate::style::{c, caption, font, inner_h, inner_w, nums, spring, tile}; + +const TRACK_H: f32 = 132.0; + +fn tile_w() -> f32 { + inner_w(1.0) + 2.0 * grid::TILE_PAD +} + +pub fn mixer(s: &State, k: &Kit) -> El { + let travel = spring(s.springs.travel); + let mut faders = row().w_full().h(inner_h(grid::ROW2)).justify_between(); + for (i, name) in FADERS.iter().enumerate() { + let v = s.m.faders[i]; + let h = 12.0 + v * (TRACK_H - 12.0); + let track = el() + .size(30.0, TRACK_H) + .child(el().size(8.0, TRACK_H).absolute(11.0, 0.0).radius(4.0).fill(c(color::WELL))) + .child( + el().size(8.0, h) + .absolute(11.0, TRACK_H - h) + .radius(4.0) + .gradient(c(lch(0.74, 0.14, 240.0)), c(color::ACCENT)) + .motion(travel), + ) + .child( + el().size(30.0, 12.0) + .absolute(0.0, TRACK_H - h - 6.0) + .radius(6.0) + .fill(c(color::TEXT)) + .shadow(2.0, 6.0, c(lch(0.0, 0.0, 0.0).alpha(0.5))) + .motion(travel), + ); + faders = faders.child( + col() + .key(format!("fader{i}")) + .items_center() + .gap(8.0) + .on_press(move |s: &mut State| s.act(Action::Fader(i as u8))) + .child(RollingText::new(format!("level{i}"), format!("{:.0}", v * 100.0)).value(v as f64).font(nums(12.0, 560.0)).color(c(color::TEXT_2)).build(k)) + .child(track) + .child(caption(*name)), + ); + } + let live = row() + .gap(6.0) + .center_y() + .child(el().size(6.0, 6.0).radius(3.0).fill(c(color::GOOD))) + .child(caption("Live")); + tile("mixer", "Mixer", live, faders).w(tile_w()) +} + +fn grid_lines(w: f32, h: f32) -> Shape { + let line = c(lch(1.0, 0.0, 0.0).alpha(0.06)); + let mut s = Shape::new(); + for i in 1..4 { + let x = w * i as f32 / 4.0; + let y = h * i as f32 / 4.0; + s = s.line([x, 0.0], [x, h], 1.0, rune::LineCap::Butt, line).line([0.0, y], [w, y], 1.0, rune::LineCap::Butt, line); + } + s +} + +pub fn xy(s: &State, k: &Kit) -> El { + let travel = spring(s.springs.travel); + let (w, h) = (inner_w(1.0), inner_h(grid::ROW2)); + let [px, py] = s.m.puck; + let (x, y) = (px * w, py * h); + let pad = el() + .key("pad") + .size(w, h) + .radius(14.0) + .fill(c(color::WELL)) + .border(1.0, c(color::EDGE)) + .clip_rounded(14.0) + .on_press(|s: &mut State| s.act(Action::Puck)) + .child(canvas(grid_lines(w, h)).size(w, h).absolute(0.0, 0.0)) + .child(el().size(1.0, h).absolute(x, 0.0).fill(c(color::ACCENT.alpha(0.35))).motion(travel)) + .child(el().size(w, 1.0).absolute(0.0, y).fill(c(color::ACCENT.alpha(0.35))).motion(travel)) + .child(el().size(96.0, 96.0).absolute(x - 48.0, y - 48.0).radius(48.0).fill(c(color::ACCENT.alpha(0.28))).blur(18.0).motion(travel)) + .child( + el().size(24.0, 24.0) + .absolute(x - 12.0, y - 12.0) + .radius(12.0) + .fill(c(color::ACCENT)) + .border(3.0, c(color::TEXT)) + .shadow(3.0, 10.0, c(lch(0.0, 0.0, 0.0).alpha(0.45))) + .motion(travel), + ); + let readout = row() + .gap(10.0) + .child(RollingText::new("cutoff", format!("{:.0} Hz", 200.0 + px * 7800.0)).value(px as f64).font(nums(12.0, 500.0)).color(c(color::TEXT_3)).build(k)) + .child(RollingText::new("res", format!("Q {:.1}", 0.5 + (1.0 - py) * 9.5)).value((1.0 - py) as f64).font(nums(12.0, 500.0)).color(c(color::TEXT_3)).build(k)); + tile("xy", "Filter", readout, pad).w(tile_w()) +} + +/// The queue's card art: a two-tone gradient per track. +fn art(track: usize) -> El { + let hue = (track as f32 * 47.0 + 200.0) % 360.0; + el().size(64.0, 64.0) + .radius(12.0) + .linear_gradient(135f32.to_radians(), [(0.0, c(lch(0.72, 0.15, hue))), (1.0, c(lch(0.42, 0.14, (hue + 50.0) % 360.0)))]) +} + +pub const CARD_H: f32 = 140.0; +/// How far each card behind the front one sits lower, and how much smaller it is. +pub const PEEK: f32 = 14.0; +pub const SHRINK: f32 = 0.05; + +pub fn queue(s: &State, _k: &Kit) -> El { + let layout = spring(s.springs.layout); + let w = inner_w(1.0); + let h = inner_h(grid::ROW2); + let mut deck = el().w(w).h(h); + // Back to front, so the front card paints last. + for (depth, card) in s.m.queue.iter().enumerate().rev() { + let d = depth as f32; + let front = depth == 0; + let (title, artist) = TRACKS[card.track]; + let shade = lch(0.29 - 0.025 * d, 0.018, 258.0); + let progress = 0.18 + 0.09 * (card.id % 7) as f32; + let info = col() + .gap(14.0) + .w_full() + .opacity(if front { 1.0 } else { 0.0 }) + .child( + row() + .gap(14.0) + .center_y() + .child(art(card.track)) + .child( + col() + .gap(3.0) + .child(text(title).font(font(16.0, 620.0)).color(c(color::TEXT))) + .child(text(artist).font(font(13.0, 460.0)).color(c(color::TEXT_2))), + ), + ) + .child( + col() + .gap(6.0) + .child(el().w_full().h(4.0).radius(2.0).fill(c(color::WELL_HI)).child(el().w_frac(progress).h(4.0).radius(2.0).fill(c(color::TEXT_2)))) + .child( + row() + .child(text(format!("{}:{:02}", (progress * 220.0) as u32 / 60, (progress * 220.0) as u32 % 60)).font(nums(11.0, 500.0)).color(c(color::TEXT_3))) + .child(spacer()) + .child(text("3:40").font(nums(11.0, 500.0)).color(c(color::TEXT_3))), + ), + ); + deck = deck.child( + col() + .key(format!("card{}", card.id)) + .size(w, CARD_H) + .absolute(0.0, d * PEEK) + .scale(1.0 - d * SHRINK) + .radius(16.0) + .fill(c(shade)) + .border(1.0, c(color::EDGE)) + .shadow(6.0, 18.0, c(lch(0.0, 0.0, 0.0).alpha(0.35))) + .padding(16.0) + .motion(layout) + .transition(Transition::asymmetric( + Transition::scale(0.9), + Transition::move_edge(Edge::Trailing).combined(Transition::opacity()), + )) + .child(info), + ); + } + let skip = row() + .key("skip") + .h(24.0) + .px(10.0) + .radius(12.0) + .center() + .fill(c(color::ACCENT_DIM)) + .hover(c(color::ACCENT.alpha(0.28))) + .press_scale(0.94) + .on_press(|s: &mut State| s.act(Action::Queue)) + .child(text("Skip").font(font(12.0, 600.0)).color(c(color::ACCENT))); + tile("queue", "Up next", skip, deck).w(tile_w()) +} + +const KIND_HUES: [f32; 8] = [245.0, 30.0, 155.0, 70.0, 200.0, 265.0, 330.0, 175.0]; + +pub fn feed(s: &State, _k: &Kit) -> El { + let mut rows = col().w_full().gap(6.0); + for item in &s.m.feed { + let hue = KIND_HUES[item.kind % KIND_HUES.len()]; + rows = rows.child( + row() + .key(format!("item{}", item.id)) + .h(40.0) + .w_full() + .px(12.0) + .gap(10.0) + .radius(12.0) + .center_y() + .fill(c(color::WELL)) + .transition(Transition::asymmetric( + Transition::offset(0.0, -12.0).combined(Transition::opacity()), + Transition::scale(0.96), + )) + .child(el().size(8.0, 8.0).radius(4.0).fill(c(lch(0.72, 0.15, hue)))) + .child(text(FEED_KINDS[item.kind]).font(font(13.0, 500.0)).color(c(color::TEXT)).truncate()) + .child(spacer()) + .child(text(format!("9:{:02}", item.minute)).font(nums(12.0, 460.0)).color(c(color::TEXT_3))), + ); + } + let test = row() + .key("test") + .h(24.0) + .px(10.0) + .radius(12.0) + .center() + .fill(c(color::WELL)) + .hover(c(color::WELL_HI)) + .press_scale(0.94) + .on_press(|s: &mut State| s.act(Action::Feed)) + .child(text("Test alert").font(font(12.0, 560.0)).color(c(color::TEXT_2))); + tile("feed", "Activity", test, rows.motion(spring(s.springs.layout))).w(tile_w()) +} diff --git a/app/vendor/rune/examples/motion-bento/src/tiles_top.rs b/app/vendor/rune/examples/motion-bento/src/tiles_top.rs new file mode 100644 index 0000000..31e5eb1 --- /dev/null +++ b/app/vendor/rune/examples/motion-bento/src/tiles_top.rs @@ -0,0 +1,174 @@ +//! The top row: scenes, the thermostat and the lights. + +use motion_bento_chaos::Action; +use motion_bento_chaos::look::{color, grid}; +use motion_bento_chaos::model::{LIGHTS, SCENE_NOTES, SCENES}; +use rune::{El, LineCap, Shape, canvas, col, el, row, spacer, text}; +use rune_kit::{Kit, RollingText, Switch}; + +use crate::State; +use crate::style::{c, caption, font, inner_h, inner_w, nums, spring, tile, well_button}; + +const SEG_H: f32 = 44.0; +const SEG_PAD: f32 = 4.0; + +pub fn scenes(s: &State, k: &Kit) -> El { + let m = &s.m; + let mood = color::SCENE[m.scene]; + let w = inner_w(2.0); + let seg_w = (w - 2.0 * SEG_PAD) / SCENES.len() as f32; + let snap = spring(s.springs.snap); + let morph = spring(s.springs.morph); + + let mut segments = row() + .w(w) + .h(SEG_H) + .radius(12.0) + .fill(c(color::WELL)) + .border(1.0, c(color::EDGE)) + .padding(SEG_PAD) + .child( + el().size(seg_w, SEG_H - 2.0 * SEG_PAD) + .absolute(SEG_PAD + seg_w * m.scene as f32, SEG_PAD) + .radius(9.0) + .fill(c(mood)) + .shadow(4.0, 14.0, c(mood.alpha(0.45))) + .motion(snap), + ); + for (i, name) in SCENES.iter().enumerate() { + let on = i == m.scene; + segments = segments.child( + row() + .key(format!("seg{i}")) + .grow(1.0) + .h_full() + .center() + .on_press(move |s: &mut State| s.act(Action::Scene(i as u8))) + .child(text(*name).font(font(14.0, 560.0)).color(c(if on { color::ON_ACCENT } else { color::TEXT_2 })).motion(snap)), + ); + } + + let lights_on = m.lights.iter().filter(|l| **l).count(); + let picked = m.chips.iter().filter(|c| **c).count(); + let stat = |label: &str, value: String| { + col() + .gap(2.0) + .padding(10.0) + .w(118.0) + .radius(12.0) + .fill(c(color::WELL)) + .child(caption(label)) + .child(RollingText::new(format!("stat-{label}"), value).font(nums(16.0, 600.0)).color(c(color::TEXT)).build(k)) + }; + let summary = row() + .h(inner_h(grid::ROW1) - SEG_H - 16.0) + .w(w) + .center_y() + .gap(10.0) + .child( + // The mood's glow, sliding under the summary toward the picked segment. + el().size(260.0, 90.0) + .absolute(-30.0 + seg_w * m.scene as f32 * 0.55, 6.0) + .radius(45.0) + .fill(c(mood.alpha(0.22))) + .blur(36.0) + .motion(morph), + ) + .child( + col() + .gap(4.0) + .grow(1.0) + .child(RollingText::new("scene-name", SCENES[m.scene]).value(m.scene as f64).font(font(30.0, 650.0)).color(c(color::TEXT)).build(k)) + .child(text(SCENE_NOTES[m.scene]).font(font(13.0, 460.0)).color(c(color::TEXT_2))), + ) + .child(stat("Lights", format!("{lights_on} of 4"))) + .child(stat("Target", m.temp_label())) + .child(stat("Genres", picked.to_string())); + + let swatch = row() + .gap(8.0) + .center_y() + .child(caption("Mood")) + .child(el().size(14.0, 14.0).radius(7.0).fill(c(mood)).shadow(0.0, 8.0, c(mood.alpha(0.6))).motion(morph)); + tile("scene", "Scenes", swatch, col().gap(16.0).child(segments).child(summary)).w(inner_w(2.0) + 2.0 * grid::TILE_PAD) +} + +/// The thermostat ring's arc: 270° from the lower left, clockwise, as points. +fn arc(size: f32, inset: f32) -> Vec<[f32; 2]> { + let r = size / 2.0 - inset; + let (a0, sweep) = (135f32.to_radians(), 270f32.to_radians()); + (0..=96) + .map(|i| { + let a = a0 + sweep * i as f32 / 96.0; + [size / 2.0 + r * a.cos(), size / 2.0 + r * a.sin()] + }) + .collect() +} + +pub const RING: f32 = 150.0; + +pub fn thermostat(s: &State, k: &Kit) -> El { + let m = &s.m; + let points = arc(RING, 9.0); + let track = Shape::new().stroke_with(points.clone(), false, 10.0, LineCap::Round, c(color::WELL_HI)); + let fill = Shape::new().stroke_with(points, false, 10.0, LineCap::Round, c(color::ACCENT)); + let ring = el() + .size(RING, RING) + .child(canvas(track).size(RING, RING).absolute(0.0, 0.0)) + .child(canvas(fill).size(RING, RING).absolute(0.0, 0.0).live_trim(s.ring.smooth(spring(s.springs.travel)))) + .child( + col() + .size(RING, RING) + .absolute(0.0, 0.0) + .center() + .gap(0.0) + .child(RollingText::new("temp", m.temp_label()).value(m.temp as f64).font(nums(34.0, 640.0)).color(c(color::TEXT)).build(k)) + .child(caption("Target")), + ); + let heating = m.temp > 21.0; + let aside = row() + .gap(6.0) + .center_y() + .child(el().size(8.0, 8.0).radius(4.0).fill(c(if heating { color::WARM } else { color::ACCENT })).motion(spring(s.springs.morph))) + .child(RollingText::new("mode", if heating { "Heating" } else { "Cooling" }).font(font(12.0, 460.0)).color(c(color::TEXT_3)).build(k)); + let buttons = col() + .gap(10.0) + .child(well_button("up", "+", 52.0, 44.0).on_press(|s: &mut State| s.act(Action::TempUp))) + .child(well_button("down", "−", 52.0, 44.0).on_press(|s: &mut State| s.act(Action::TempDown))); + let body = row().h(inner_h(grid::ROW1)).center_y().gap(14.0).child(ring).child(spacer()).child(buttons); + tile("thermo", "Thermostat", aside, body).w(inner_w(1.0) + 2.0 * grid::TILE_PAD) +} + +pub fn lights(s: &State, k: &Kit) -> El { + let m = &s.m; + let on = m.lights.iter().filter(|l| **l).count(); + let mut rows = col().gap(4.0); + for (i, name) in LIGHTS.iter().enumerate() { + let lit = m.lights[i]; + rows = rows.child( + row() + .h(34.0) + .center_y() + .gap(12.0) + .child( + el().size(10.0, 10.0) + .radius(5.0) + .fill(c(if lit { color::WARM } else { color::WELL_HI })) + .shadow(0.0, 10.0, c(if lit { color::WARM.alpha(0.7) } else { color::WARM.alpha(0.0) })) + .motion(spring(s.springs.snap)), + ) + .child(text(*name).font(font(14.0, 500.0)).color(c(if lit { color::TEXT } else { color::TEXT_2 }))) + .child(spacer()) + .child( + Switch::new(lit) + .label(*name) + .hide_label() + .on_toggle(move |s: &mut State| s.act(Action::Light(i as u8))) + .build(k) + .key(format!("light{i}")), + ), + ); + } + let aside = RollingText::new("lights-on", format!("{on} on")).value(on as f64).font(font(12.0, 460.0)).color(c(color::TEXT_3)).build(k); + tile("lights", "Lights", aside, rows).w(inner_w(1.0) + 2.0 * grid::TILE_PAD) +} diff --git a/app/vendor/rune/examples/odometer/Cargo.toml b/app/vendor/rune/examples/odometer/Cargo.toml new file mode 100644 index 0000000..4b4b498 --- /dev/null +++ b/app/vendor/rune/examples/odometer/Cargo.toml @@ -0,0 +1,13 @@ +[package] +name = "odometer" +version = "0.0.1" +edition.workspace = true +license.workspace = true +publish = false + +[dependencies] +rune = { workspace = true, default-features = true, features = ["keys-overlay"] } +rune-kit = { workspace = true, default-features = true } + +[lints] +workspace = true diff --git a/app/vendor/rune/examples/odometer/src/main.rs b/app/vendor/rune/examples/odometer/src/main.rs new file mode 100644 index 0000000..17854df --- /dev/null +++ b/app/vendor/rune/examples/odometer/src/main.rs @@ -0,0 +1,91 @@ +//! A count and a right-aligned run time as `RollingText` odometers. "Up" and "Down" step the +//! number: changed digits roll up as it rises and down as it falls, and "9s" → "10s" grows the +//! time to the left with every digit in its column. Below, header rows with a long title that +//! truncates and a usage group (context and cost) on the right: "Step" and "Big step" add spend, +//! so the cost gains a digit and the token count changes length. The usage group slides on a +//! width-leading spring in the first two headers and on the labels' own spring in the third. +//! `cargo run -p odometer`; the motion audit records it with +//! `scripts/motion-audit/scenarios/odometer.json`. + +#![forbid(unsafe_code)] + +use rune::{AppSpec, Cx, El, Spring, TextStyle, col, el, row, spacer, text}; +use rune_kit::{Button, Kit, RollingText}; + +struct State { + n: i64, + cents: i64, + tokens: u64, +} + +/// The header numbers' roll and slide: quick, with no overshoot. +const USAGE: Spring = Spring::new(0.3, 0.0); + +fn tokens_short(n: u64) -> String { + if n >= 1_000 { format!("{:.1}K", n as f64 / 1e3) } else { n.to_string() } +} + +/// A long title that truncates, and a usage group: a ring, the context and the cost. +fn header(k: &Kit, s: &State, name: &str, trailing_cost: bool, leads: bool) -> El { + let font = TextStyle::new(12.0, 440.0).lh(16.0).features("'tnum' 1"); + let label = |key: String, t: String, v: f64, trailing: bool| { + let l = RollingText::new(key, t).value(v).font(font).color(k.c.text_weak).spring(USAGE); + if trailing { l.trailing() } else { l }.build(k) + }; + let mut usage = row().key(format!("{name}-usage")).gap(6.0).center_y().motion(USAGE); + if leads { + usage = usage.width_leads(); + } + let usage = usage + .child(el().size(14.0, 14.0).radius(7.0).border(2.0, k.c.border_base)) + .child(label(format!("{name}-ctx"), tokens_short(s.tokens), s.tokens as f64, true)) + .child(label(format!("{name}-cost"), format!("${}.{:02}", s.cents / 100, s.cents % 100), s.cents as f64, trailing_cost)); + row() + .key(name.to_owned()) + .w(300.0) + .h(32.0) + .px(10.0) + .gap(8.0) + .center_y() + .fill(k.c.bg_deep) + .child(row().key(format!("{name}-crumbs")).center_y().shrink().child(text("Refactor the session list so pinned rows keep their place").font(TextStyle::new(13.0, 530.0)).truncate())) + .child(spacer()) + .child(usage) +} + +fn view(s: &State, _: &mut Cx<State>) -> El { + let k = Kit::neutral(true); + let big = TextStyle::new(28.0, 600.0).mono(); + let count = RollingText::new("count", s.n.to_string()).value(s.n as f64).font(big).build(&k); + let time = RollingText::new("secs", format!("{}s", s.n)).value(s.n as f64).font(k.ty.mono).trailing().build(&k); + let button = |label: &str, key: &str, f: fn(&mut State)| Button::new(label).on_press(f).build(&k).key(key); + col() + .w_full() + .h_full() + .padding(24.0) + .gap(16.0) + .fill(k.c.bg_base) + .child( + row() + .gap(8.0) + .child(button("Up", "up", |s| s.n += 1)) + .child(button("Down", "down", |s| s.n -= 1)) + .child(button("Step", "step", |s| { + s.cents += 7; + s.tokens += 1_400; + })) + .child(button("Big step", "big", |s| { + s.cents += 996; + s.tokens += 98_000; + })), + ) + .child(count) + .child(row().w(160.0).justify_end().motion(RollingText::SPRING).child(time)) + .child(header(&k, s, "head", true, true)) + .child(header(&k, s, "head-lead", false, true)) + .child(header(&k, s, "head-plain", true, false)) +} + +fn main() { + rune::run(AppSpec::new("Odometer", (420.0, 360.0), || State { n: 9, cents: 42, tokens: 12_345 }, view)); +} diff --git a/app/vendor/rune/examples/overlay-lab/Cargo.toml b/app/vendor/rune/examples/overlay-lab/Cargo.toml new file mode 100644 index 0000000..ece53da --- /dev/null +++ b/app/vendor/rune/examples/overlay-lab/Cargo.toml @@ -0,0 +1,12 @@ +[package] +name = "overlay-lab" +default-run = "overlay-lab" +version = "0.0.1" +edition.workspace = true +license.workspace = true + +[dependencies] +rune = { workspace = true, default-features = true, features = ["keys-overlay"] } + +[lints] +workspace = true diff --git a/app/vendor/rune/examples/overlay-lab/README.md b/app/vendor/rune/examples/overlay-lab/README.md new file mode 100644 index 0000000..37fe2d9 --- /dev/null +++ b/app/vendor/rune/examples/overlay-lab/README.md @@ -0,0 +1,223 @@ +# Overlay lab + +## Native layer-filter proof + +`layer-filter-overlay` draws two static exiting-chip samples in a prewarmed native panel. +Both use a 400×40 pt capsule, nested dissolve/blur, sigma 1.5 pt and opacity .65. The upper +row is unmasked; the lower row uses `clip_rounded(20)`. Run from the repo root: + +```sh +cargo build -p overlay-lab --bin layer-filter-overlay -j 2 +python3 examples/overlay-lab/native/run-filter-probe.py examples/overlay-lab/artifacts/layer-filters/native-overlay +``` + +Run it on a GUI test Mac, never on a developer's desk display. The runner holds the host's GUI lock, waits for visible alpha and positive Metal presentation, +then captures that exact window with Cua. It closes the app's stdin to quit, ends the Cua +session and removes its diagnostic dylib. Evidence includes `native-overlay.png`, the +presentation log and Cua's valid-frame/window metadata. This proves Rune's native rendering +of a blurred, rounded capsule; the separate headless regression covers fully off-wall sources. + +## Interactive lab + +`cargo run -p overlay-lab` opens a transparent pill on the display under the pointer. +Only its chips intercept clicks; the background and hover label pass through. iPhone/Paste +change its contents inside a fixed maximum canvas. Area/Window/Screen open one picker per +display. Drag selects an area; Escape closes all pickers on platforms with overlay keys. + +Headless stills use the same views, selected as the ordinary `lab` host: + +``` +cargo run -p overlay-lab -- --scene pill --snap pill.png +cargo run -p overlay-lab -- --scene expanded --snap expanded.png +cargo run -p overlay-lab -- --scene picker --size 960x600 --snap picker.png +``` + +Set `OVERLAY_LAB_SECONDS=15` for a bounded desktop probe with panel-ID/capture-request +logging. `OVERLAY_LAB_PICKER=1` opens the picker immediately. Run desktop probes in a GUI test +Mac's logged-in session, at normal priority, not on a developer's desk display. +`OVERLAY_LAB_UNDERLAY=1` runs a separate normal-window process that logs clicks, for +cross-process pass-through/focus checks. `OVERLAY_LAB_INCLUDE_IN_CAPTURE=1` disables the +capture request while grounding input coordinates; omit it for the exclusion check. + +Linux capture exclusion is unavailable. Wayland only observes pointer movement inside its +input region, and the compositor chooses an output for UnderPointer. It cannot follow the +global pointer. OnDemand permits click-to-focus on layer-shell v4, X11 and Windows (where +`request_keys` takes the foreground only when Windows lets the process); XWayland has no key +focus. Capture requests on macOS must be supplemented with an explicit ScreenCaptureKit +window-ID filter when the OS capture path ignores NSWindow sharingType. +Wayland keeps all three levels on the compositor's overlay layer; it has no higher layer and +does not guarantee ordering among peers. Native status/status+1 levels are macOS-specific. + +## Integrating an app's overlays + +- The lab prewarms hidden hosts and logs `on_created` with the actual macOS CGWindowID. + `window_number()` is available after that callback and stays stable through hide/show. + Host creation happens on the event loop, not synchronously in `App::overlay`. +- Use `set_input(OverlayInput::All)` for selection and `set_input(OverlayInput::None)` for + pass-through ink/glow on the same host. Mode changes wait for an owned drag's release. + `Regions` uses `.hit()` geometry; `Legacy` restores the spec's `interactive` behavior. +- `set_follow_pointer(bool)` enables/disables following independently of placement/input. + An app can keep it disabled and supply its own `Rect` and `set_display` requests. +- `ConfiguredOverlay::poll(fn(&mut T, f64, &mut Tx) -> bool)` overrides the app's poll. + Overlays with the same state type inherit `AppSpec::poll`; different state types use the + builder. Return true when state changed, and use `Tx::wake_after` for the next deadline. + Hidden deadlines poll without drawing, matching the window host. +- `ConfiguredOverlay::compositor(...)` takes the same `Compositor<T>` as `App::compositor`. + Call `frame.draw_ui()` and then `frame.rt.elements()` to trace each rendered overlay frame, + including alpha-zero/offscreen prewarm. Runtime-only hidden updates do not call it. + `animating()` keeps visible frames running; false allows them to go idle. +- Standalone modifier transitions (for example, pressing/releasing Shift without another + key) are not delivered; the desktop and Wayland overlay callbacks have TODOs for a + shared modifier-only key event. Pressed keys + still carry modifier state, and Escape works. +- `Display::native_id()` maps to `DisplayTarget::Native`: macOS CGDirectDisplayID, Windows + full-width HMONITOR, X11 RandR CRTC, Wayland wl_output registry name. X11 output IDs can + also be targeted with `NativeDisplayId::X11Output`. `native_bounds()` is global top-left + (macOS/Wayland points, Windows/X11 pixels); `scale` converts local lengths. +- The pill uses `AboveOverlays` (macOS 27), above the picker's `AboveStatus` (26). Both use + CanJoinAllSpaces, FullScreenAuxiliary and Stationary. Wayland ordering remains compositor-owned. +- Desktop hide retains the native window, GPU surface and renderer. With `prewarm`, macOS + renders a frame into the panel's actual surface at alpha zero, then orders it out. + An unchanged show orders it back in and restores input and alpha; stale hidden changes render + before reveal, preserving elapsed motion from hidden commits (see below). + Hidden hosts have no pointer observers or draw loop. Wayland recreates its + layer after hide. +- macOS Regions mode samples native pointer position/buttons at up to 120 Hz while visible. + Monitors wake the loop; native local downs establish ownership through delivery of Up. + Input changes also wait for native ownership when `.hit()` has no Runtime press handler. + A known queued Up stays protected until dispatch. If no native Up was queued, 100 ms of + observed button-up clears ownership and forwards one recovered release to Runtime at the + first observed release position. Every Left Up acknowledges native ownership, even in None. + None/All and hidden modes stop the polling deadline. Unchanged hover does not draw. +- Release measurements on a shared M2 Max: 30 retained re-shows reached the alpha setter in + **0.369 ms median / 0.776 ms p95**. This is **not a presentation timestamp**. Alpha-only + reveal reuses a drawable; Metal does not timestamp its compositor reveal. Opt-in diagnostic + redraws reached positive `presentedTime` at **49.728 ms median / 75.907 ms p95**. + **Sub-16 ms visible presentation remains unproven.** +- Ten-second idle intervals measured **0.044% CPU / 104 interrupt wakes/s** for a visible + Regions pill with the pointer elsewhere and about **0.002% CPU** hidden. Neither interval + produced drawable callbacks. All/None stopped polling and also produced no drawable callbacks. + +The idle path filters outside-canvas motion and skips unchanged hover redraws. Windows hooks +run on a separate message-loop thread; X11 observes XI2 raw motion instead of polling. The +shared Wayland socket wakes its private queue; legacy noninteractive HUDs bind no seat and +reuse their empty input region. + +## Commit an entrance, then show + +For a prewarmed macOS overlay, initialize the view in its entry pose A (for example, a +collapsed capsule), then commit target B. Request `show()` in that poll or a later turn: + +```rust,ignore +fn poll(s: &mut Capsule, _now: f64, tx: &mut Tx) -> bool { + // Keep the app's existing wake scheduling here (Tx::wake_after, for example). + let Ok(Command::Enter) = s.events.try_recv() else { return false; }; + s.expanded = true; // B: normal motion, not tx.instant(). + s.overlay.as_ref().unwrap().show(); // Reveal the current pose on the way to B. + true +} + +let configured = OverlaySpec::new("capsule", canvas_size, view) + .options(OverlayOptions { prewarm: true, ..Default::default() }) + .poll(poll); +// Initialize expanded=false, install the returned OverlayHandle in the state, +// and let startup prewarm finish before accepting Enter commands. +``` + +No early show or delay is needed. Hidden transitions keep their own render-clock time: +show 16 ms after the commit and the entrance is near its start; show 2 s later and it is +already at rest. Rune catches motion up when polling or preparing the reveal, without a +hidden draw loop. Time before a commit is never charged to that new transition. + +The revealed frame contains current content, geometry and live values, including instant +and text-only changes. Only motion keeps its original timing. Initial prewarm and +ordinary/unretained overlays still settle their first frame. Updates after `show()` can +also animate normally. + +You can kick the first hidden poll with a queued `update()` or schedule it with +`tx.wake_after(..)`. A queued update makes the prepared frame stale, but refreshing it now +preserves the entry's elapsed motion instead of settling it. + +## Native measurement harness (macOS) + +Ordinary windows can opt into the same native switches without changing exhaustive +`WindowOptions` literals: + +```rust +WindowSpec::from_app("capsule", app).configured_options( + WindowOptions { transparent: true, borderless: true, ..Default::default() } + .macos(MacWindowOptions::default() + .shadow(false).level(27) + .collection_behavior(1 | 16 | 64 | 256) + .exclude_from_capture(true)) +) +``` + +The mask above is CanJoinAllSpaces | Stationary | IgnoresCycle | FullScreenAuxiliary. +These settings apply at each native creation; other platforms ignore them. They do not +change an ordinary window into a nonactivating panel. Runtime `set_always_on_top` overrides +the configured native level, including after recreation. `OVERLAY_LAB_UNDERLAY=1` plus +`OVERLAY_LAB_NATIVE_WINDOW=1` exercises native options; `OVERLAY_PROBE_NATIVE_OPTIONS=1` +logs native readbacks when the diagnostic library is loaded. + +Use `configured_options` for native builders; `options(WindowOptions)` remains concrete so +existing `.options(Default::default())` calls keep compiling. + +`native/` contains diagnostic tools, loaded only into the lab process. Build them, then +copy the products into a fresh temporary directory on the GUI test host: + +```sh +cargo build --release -p overlay-lab -j 2 +xcrun clang -dynamiclib -fobjc-arc -framework AppKit -framework QuartzCore -framework Metal \ + examples/overlay-lab/native/presentation-probe.m -o presentation-probe.dylib +xcrun swiftc -parse-as-library examples/overlay-lab/native/capture-probe.swift -o capture-probe +``` + +Put `overlay-lab`, `presentation-probe.dylib` and `capture-probe` in that directory. Hold +the host's GUI lock file (`fcntl.LOCK_EX`), then run +`python3 examples/overlay-lab/native/run-native-probe.py <directory>` at normal priority. + +`OVERLAY_LAB_CONTROL` names a unique Unix socket and starts the pill prewarmed but hidden. +Newline-terminated `show`, `hide`, `status`, `none`, `all`, `regions`, and `quit` commands are accepted. The driver +records the request's `CACurrentMediaTime` immediately before `handle.show()` and the +drawable's actual `presentedTime`, not queue submission or callback arrival time. Zero +timestamps are reported separately, with a two-second deadline for a positive timestamp. +It checks WindowServer identity before 31 shows (initial plus 30 re-shows). Set +`OVERLAY_PROBE_RETAINED=1` for alpha-zero hosts; the old order-out baseline omits it. +The retained run fails before showing if the pill has no alpha-zero `nextDrawable` +acquisition before `on_created`. This catches regressions in the wgpu occlusion override. +`python3 native/prewarm_trace.py <presentation.log>` checks every created overlay in a saved +trace; keep `prewarm_trace.py` beside the runner when copying the harness to another host. +`OVERLAY_PROBE_REDRAW=1` adds diagnostic redraws until a positive timestamp. Report this +endpoint separately from the alpha-only reveal; it includes work absent in normal showing. +`results.json` and `presentation.log` are the evidence; the lab has a bounded shutdown timer. + +`run-idle-probe.py` samples process CPU and interrupt wake counters over ten-second intervals, +without redraw assistance, and counts drawable callbacks. `--modes` measures All/None/Regions. +`run-pill-probe.py <installed-binary> <directory>` runs 30 `lab pill tap-then-screen` +cycles of an installed reference app using the same diagnostic library without redraw +assistance. It measures native already-visible `orderFrontRegardless` entry to positive +presentation, not the beginning of the app's request. +`run-input-probe.py` drives an independent underlay and twenty raw-motion enter/click/leave/click +cycles. Build `mouse-path.swift`, copy it to a stable path and ad-hoc sign once before the +user grants Accessibility. Do not replace the granted binary. Point +`OVERLAY_MOUSE_HELPER` at it; the runner's default path is machine-specific. Set +`RUNE_OVERLAY_TRACE_INPUT=1` to log regions, monitor callbacks, polls, and native input flips. + +`run-cua-input-probe.py <directory> prepare` drives the same checks through CuaDriver. +It holds the GUI lock file, starts two disposable lab processes, captures `grounding.png`, +then waits up to two minutes on `cua-control.sock`. After inspecting that screenshot and +its backing scale, send JSON `{"run":true,"scale":2}` over the socket. It verifies twenty +enter/click/leave/click cycles, hide-mid-press recovery, and `hit-only` → None during an +owned press; `hit-only` and `chips` control commands switch the fixture. The final None +assertion checks underlay delivery because None stops polling. `cycles:0,hide_case:false` +runs only the handlerless case. Preserve `actions.jsonl`, `steps.jsonl`, and both process +logs. + +The capture helper uses ScreenCaptureKit with and without the exact CGWindowID in +`excludingWindows`. It checks permission first and exits 77 if unavailable. The probe does not change TCC; +an app verifies its own CGWindowID exclusion filter with its Screen Recording permission. + +For click-through checks, use an independent underlay process. A coordinate-only synthetic +click does not establish that native mouse-move observation ran first. Check actual pointer +movement and both directions across the region boundary, and verify underlay/overlay logs. diff --git a/app/vendor/rune/examples/overlay-lab/artifacts/layer-filters/native-overlay/.gitignore b/app/vendor/rune/examples/overlay-lab/artifacts/layer-filters/native-overlay/.gitignore new file mode 100644 index 0000000..fedeb7e --- /dev/null +++ b/app/vendor/rune/examples/overlay-lab/artifacts/layer-filters/native-overlay/.gitignore @@ -0,0 +1,3 @@ +*.json +*.log +*.dylib diff --git a/app/vendor/rune/examples/overlay-lab/artifacts/layer-filters/native-overlay/native-overlay.png b/app/vendor/rune/examples/overlay-lab/artifacts/layer-filters/native-overlay/native-overlay.png new file mode 100644 index 0000000..76f381f Binary files /dev/null and b/app/vendor/rune/examples/overlay-lab/artifacts/layer-filters/native-overlay/native-overlay.png differ diff --git a/app/vendor/rune/examples/overlay-lab/native/capture-probe.swift b/app/vendor/rune/examples/overlay-lab/native/capture-probe.swift new file mode 100644 index 0000000..3efbf2d --- /dev/null +++ b/app/vendor/rune/examples/overlay-lab/native/capture-probe.swift @@ -0,0 +1,54 @@ +import AppKit +import ScreenCaptureKit + +@main struct CaptureProbe { + static func main() async throws { + let args = CommandLine.arguments + let id = CGWindowID(args[1])! + if args.count > 2 && args[2] == "--geometry" { + let windows = CGWindowListCopyWindowInfo(.optionAll, kCGNullWindowID) as? [[String: Any]] ?? [] + guard let match = windows.first(where: { ($0[kCGWindowNumber as String] as? UInt32) == id }), + let bounds = match[kCGWindowBounds as String] else { exit(1) } + let data = try JSONSerialization.data(withJSONObject: bounds, options: [.sortedKeys]) + print(String(decoding: data, as: UTF8.self)) + return + } + if args.count == 2 || args[2] == "--hidden" { + let started = ProcessInfo.processInfo.systemUptime + var match: [String: Any]? + // AppKit orderOut returns before WindowServer publishes its window list. + // Bound this readiness check; it is outside the show/presentation interval. + repeat { + let windows = CGWindowListCopyWindowInfo(.optionAll, kCGNullWindowID) as? [[String: Any]] ?? [] + match = windows.first { ($0[kCGWindowNumber as String] as? UInt32) == id } + if args.count == 2 || (match?[kCGWindowIsOnscreen as String] as? Bool) != true { break } + try await Task.sleep(for: .milliseconds(10)) + } while ProcessInfo.processInfo.systemUptime - started < 1 + print("window=\(id) exists=\(match != nil) onScreen=\(match?[kCGWindowIsOnscreen as String] ?? false)") + return + } + guard CGPreflightScreenCaptureAccess() else { + print("BLOCKED: ScreenCaptureKit probe lacks screen-recording permission; no permission requested") + Foundation.exit(77) + } + let content = try await SCShareableContent.excludingDesktopWindows(false, onScreenWindowsOnly: false) + guard let window = content.windows.first(where: { $0.windowID == id }), + let display = content.displays.first(where: { $0.frame.intersects(window.frame) }) else { + fatalError("window not found: \(id)") + } + print("window=\(id) frame=\(window.frame) onScreen=\(window.isOnScreen) pid=\(window.owningApplication?.processID ?? 0)") + let config = SCStreamConfiguration() + config.sourceRect = window.frame.offsetBy(dx: -display.frame.minX, dy: -display.frame.minY) + config.width = Int(window.frame.width * 2) + config.height = Int(window.frame.height * 2) + config.showsCursor = false + for exclude in [false, true] { + let filter = SCContentFilter(display: display, excludingWindows: exclude ? [window] : []) + let image = try await SCScreenshotManager.captureImage(contentFilter: filter, configuration: config) + let bitmap = NSBitmapImageRep(cgImage: image) + let suffix = exclude ? "excluded" : "included" + try bitmap.representation(using: .png, properties: [:])!.write(to: URL(fileURLWithPath: "\(args[2])-\(suffix).png")) + print("capture=\(suffix) width=\(image.width) height=\(image.height)") + } + } +} diff --git a/app/vendor/rune/examples/overlay-lab/native/mouse-path.swift b/app/vendor/rune/examples/overlay-lab/native/mouse-path.swift new file mode 100644 index 0000000..13a37c2 --- /dev/null +++ b/app/vendor/rune/examples/overlay-lab/native/mouse-path.swift @@ -0,0 +1,29 @@ +// Native input probe. Explicitly posts motion events; never substitutes cursor warps. +import ApplicationServices +import Foundation + +let args = CommandLine.arguments +guard CGPreflightPostEventAccess() else { + print("BLOCKED: input helper lacks event-posting permission; no permission requested") + exit(77) +} +let source = CGEventSource(stateID: .hidSystemState)! +source.localEventsSuppressionInterval = 0 +let from = CGPoint(x: Double(args[1])!, y: Double(args[2])!) +let to = CGPoint(x: Double(args[3])!, y: Double(args[4])!) +let steps = Int(args[5])! +for step in 0...steps { + let t = Double(step) / Double(max(1, steps)) + let p = CGPoint(x: from.x + (to.x-from.x)*t, y: from.y + (to.y-from.y)*t) + let event = CGEvent(mouseEventSource: source, mouseType: .mouseMoved, mouseCursorPosition: p, mouseButton: .left)! + event.post(tap: .cghidEventTap) + // Fixed input cadence, not a readiness poll. Exercise multiple native callbacks. + Thread.sleep(forTimeInterval: 0.008) +} +if args.count > 6 && args[6] == "click" { + for kind in [CGEventType.leftMouseDown, .leftMouseUp] { + CGEvent(mouseEventSource: source, mouseType: kind, mouseCursorPosition: to, mouseButton: .left)!.post(tap: .cghidEventTap) + Thread.sleep(forTimeInterval: 0.008) + } +} +print("posted moves=\(steps+1) from=\(from) to=\(to) click=\(args.count > 6)") diff --git a/app/vendor/rune/examples/overlay-lab/native/presentation-probe.m b/app/vendor/rune/examples/overlay-lab/native/presentation-probe.m new file mode 100644 index 0000000..eb4b2b6 --- /dev/null +++ b/app/vendor/rune/examples/overlay-lab/native/presentation-probe.m @@ -0,0 +1,79 @@ +// Diagnostic injection into overlay-lab only. No cross-process hooks are installed. +// Correlate Metal's actual presentedTime with the lab's CACurrentMediaTime show requests. +#import <AppKit/AppKit.h> +#import <QuartzCore/CAMetalLayer.h> +#import <Metal/Metal.h> +#import <objc/runtime.h> + +static id<CAMetalDrawable> (*originalNext)(id, SEL); +static void (*originalOut)(id, SEL, id); +static void (*originalAlpha)(id, SEL, CGFloat); +static void (*originalFront)(id, SEL); +static void orderFront(NSWindow *window, SEL selector) { + double requested = CACurrentMediaTime(); + BOOL wasVisible = window.visible; + originalFront(window, selector); + fprintf(stderr, "probe front window=%ld requested=%.9f was_visible=%d panel=%d level=%ld view=%s\n", + (long)window.windowNumber, requested, wasVisible, [window isKindOfClass:NSPanel.class], + (long)window.level, class_getName(window.contentView.class)); +} +static void setAlpha(NSWindow *window, SEL selector, CGFloat alpha) { + originalAlpha(window, selector, alpha); + if (![window isKindOfClass:NSPanel.class]) return; + fprintf(stderr, "probe alpha window=%ld alpha=%.1f time=%.9f\n", (long)window.windowNumber, alpha, CACurrentMediaTime()); + // Opt-in measurement assistance, not Rune behavior. Alpha-only reveal reuses a + // previously submitted drawable; Metal cannot timestamp its compositor reveal. + if (alpha == 1 && getenv("OVERLAY_PROBE_REDRAW")) { + double deadline = CACurrentMediaTime() + 2; + objc_setAssociatedObject(window, @selector(setAlphaValue:), @(deadline), OBJC_ASSOCIATION_RETAIN_NONATOMIC); + window.contentView.needsDisplay = YES; + } +} +static void orderOut(NSWindow *window, SEL selector, id sender) { + originalOut(window, selector, sender); + if ([window isKindOfClass:NSPanel.class]) + fprintf(stderr, "probe hidden window=%ld visible=%d time=%.9f\n", (long)window.windowNumber, window.visible, CACurrentMediaTime()); +} +static id<CAMetalDrawable> nextDrawable(id layer, SEL selector) { + id<CAMetalDrawable> drawable = originalNext(layer, selector); + if (!drawable) return drawable; + NSInteger windowID = 0; + for (NSWindow *window in NSApp.windows) { + CALayer *root = window.contentView.layer; + for (CALayer *p = layer; p; p = p.superlayer) { + // Rune forwards source-window readbacks to the adopted content view. Its + // real NSView.window identifies the panel rather than the hidden source. + if (p == root) { windowID = window.contentView.window.windowNumber; break; } + } + if (windowID) break; + } + double acquired = CACurrentMediaTime(); + __weak NSWindow *owner; + for (NSWindow *window in NSApp.windows) + if (window.windowNumber == windowID) { owner = window; break; } + fprintf(stderr, "probe acquired window=%ld alpha=%.1f time=%.9f\n", (long)windowID, owner.alphaValue, acquired); + if (getenv("OVERLAY_PROBE_NATIVE_OPTIONS")) + fprintf(stderr, "probe native window=%ld shadow=%d level=%ld collection=%lu sharing=%lu\n", + (long)owner.windowNumber, owner.hasShadow, (long)owner.level, + (unsigned long)owner.collectionBehavior, (unsigned long)owner.sharingType); + [drawable addPresentedHandler:^(id<MTLDrawable> d) { + fprintf(stderr, "probe presented window=%ld acquired=%.9f presented=%.9f callback=%.9f\n", + (long)windowID, acquired, d.presentedTime, CACurrentMediaTime()); + if (d.presentedTime == 0 && getenv("OVERLAY_PROBE_REDRAW")) dispatch_async(dispatch_get_main_queue(), ^{ + NSWindow *window = owner; + NSNumber *deadline = objc_getAssociatedObject(window, @selector(setAlphaValue:)); + if (window.alphaValue == 1 && deadline.doubleValue > CACurrentMediaTime()) window.contentView.needsDisplay = YES; + }); + }]; + return drawable; +} +__attribute__((constructor)) static void install(void) { + Method method = class_getInstanceMethod(CAMetalLayer.class, @selector(nextDrawable)); + originalNext = (void *)method_setImplementation(method, (IMP)nextDrawable); + Method out = class_getInstanceMethod(NSWindow.class, @selector(orderOut:)); + originalOut = (void *)method_setImplementation(out, (IMP)orderOut); + Method alpha = class_getInstanceMethod(NSWindow.class, @selector(setAlphaValue:)); + originalAlpha = (void *)method_setImplementation(alpha, (IMP)setAlpha); + Method front = class_getInstanceMethod(NSWindow.class, @selector(orderFrontRegardless)); + originalFront = (void *)method_setImplementation(front, (IMP)orderFront); +} diff --git a/app/vendor/rune/examples/overlay-lab/native/prewarm_trace.py b/app/vendor/rune/examples/overlay-lab/native/prewarm_trace.py new file mode 100644 index 0000000..961c20f --- /dev/null +++ b/app/vendor/rune/examples/overlay-lab/native/prewarm_trace.py @@ -0,0 +1,28 @@ +"""Assert native alpha-zero drawable acquisition before an overlay's creation callback.""" +import re + + +def assert_prewarmed(lines, window): + acquired = False + for line in lines: + match = re.match(r'probe acquired window=(\d+) alpha=([\d.]+) time=', line) + if match and int(match[1]) == window: + acquired |= float(match[2]) == 0.0 + if ' created OverlayCreated ' in line and f'window_number: Some({window})' in line: + if not acquired: + raise AssertionError(f'window {window}: no alpha-zero drawable acquired before on_created; check prewarm/occlusion') + return + raise AssertionError(f'window {window}: missing on_created marker') + + +if __name__ == '__main__': + import pathlib + import sys + lines = pathlib.Path(sys.argv[1]).read_text().splitlines() + windows = [int(match[1]) for line in lines if ' created OverlayCreated ' in line + and (match := re.search(r'window_number: Some\((\d+)\)', line))] + if not windows: + raise AssertionError('no created overlays in trace') + for window in windows: + assert_prewarmed(lines, window) + print(f'Alpha-zero prewarm verified before on_created for {len(windows)} overlays: {windows}') diff --git a/app/vendor/rune/examples/overlay-lab/native/run-cua-input-probe.py b/app/vendor/rune/examples/overlay-lab/native/run-cua-input-probe.py new file mode 100644 index 0000000..8e091d6 --- /dev/null +++ b/app/vendor/rune/examples/overlay-lab/native/run-cua-input-probe.py @@ -0,0 +1,233 @@ +"""Authorized Pro desktop proof via CuaDriver; holds the GUI lock for the whole run. + +prepare starts a bounded worker and returns after its grounding screenshot. Read that +image, then send {"run":true,"scale":2} to cua-control.sock to run the proof. The +worker streams its result on that socket and exits, closing its own apps/session. +""" +import ast, fcntl, json, os, pathlib, re, selectors, socket, subprocess, sys, threading, time + +root = pathlib.Path(sys.argv[1]).resolve() +driver = str(pathlib.Path.home()/'.local/bin/cua-driver') +session = 'rune-overlay-boundary' +target = {'kind': 'desktop', 'display_id': 'primary'} + +if len(sys.argv) > 2 and sys.argv[2] == 'prepare': + with (root/'worker.log').open('w') as log: + worker = subprocess.Popen([sys.executable, '-u', __file__, str(root)], + stdout=subprocess.PIPE, stderr=log, start_new_session=True) + ready = selectors.DefaultSelector() + ready.register(worker.stdout, selectors.EVENT_READ) + if not ready.select(90): raise TimeoutError('worker did not prepare in 90 seconds') + line = worker.stdout.readline().decode() + if not line: raise RuntimeError('worker exited; inspect worker.log') + print(line, end='') + sys.exit(0) + +lock = open('/tmp/pro-gui.lock', 'a') +fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) +if subprocess.run(['pgrep', '-f', '[r]une-smoke/ci/Hex.app'], capture_output=True).returncode == 0: + raise RuntimeError('competing Hex smoke app') +condition = threading.Condition() +state = {'clicks': 0, 'chips': 0, 'window': None, 'trace': None, 'seq': 0, 'regions': []} +actions = (root/'actions.jsonl').open('w') +steps = (root/'steps.jsonl').open('w') +apps = [] + +def record(file, value): + file.write(json.dumps(value)+'\n'); file.flush() + +def cua(tool, **args): + payload = dict(args, session=session) + run = subprocess.run([driver, tool, json.dumps(payload)], capture_output=True, text=True, timeout=35) + record(actions, {'tool': tool, 'args': payload, 'stdout': run.stdout, 'stderr': run.stderr, 'exit': run.returncode}) + if run.returncode: raise RuntimeError(f'Cua {tool}: {run.stdout} {run.stderr}') + result = json.loads(run.stdout) + if result.get('isError') or result.get('error'): raise RuntimeError(f'Cua {tool}: {result}') + return result + +def read_logs(name, app): + with (root/f'input-{name}.log').open('w') as log: + for line in app.stdout: + log.write(line); log.flush() + with condition: + if name == 'underlay' and 'underlay click ' in line: + state['clicks'] = int(line.rsplit(' ', 1)[1]) + if name == 'overlay' and 'overlay-lab chip iPhone' in line: state['chips'] += 1 + if name == 'overlay' and 'pill created' in line: + state['window'] = int(re.search(r'window_number: Some\((\d+)\)', line)[1]) + if name == 'overlay' and line.startswith('overlay-input '): + window = int(re.search(r'window=(\d+)', line)[1]) + if window == state['window']: + state['seq'] += 1 + state['regions'] = ast.literal_eval(line.split('regions=', 1)[1]) + state['trace'] = line.strip() + condition.notify_all() + +def wait(test, seconds=8): + with condition: + if not condition.wait_for(lambda: test(state), timeout=seconds): + raise TimeoutError(f'predicate timed out: {state}') + return dict(state) + +def snapshot(label, fresh=True, ignore=None): + with condition: seq = state['seq'] + # Region publication logs precede observe() in the same frame. Wait for a + # subsequent poll readback, not that intentionally pre-update diagnostic row. + value = wait(lambda s: s['seq'] > seq and 'source=poll ' in (s['trace'] or '') + and (ignore is None or f'ignore={str(ignore).lower()}' in s['trace'])) if fresh else dict(state) + record(steps, {'step': label, **value}) + return value + +def command(value): + with socket.socket(socket.AF_UNIX) as client: + client.settimeout(8); client.connect(str(root/'input.sock')) + client.sendall((value+'\n').encode()) + result = client.recv(4096).decode() + record(actions, {'command': value, 'result': result}) + +def launch(name, **extra): + env = dict(os.environ, OVERLAY_LAB_SECONDS='600', RUNE_OVERLAY_TRACE_INPUT='1', + OVERLAY_LAB_INCLUDE_IN_CAPTURE='1', **extra) + app = subprocess.Popen([str(root/'overlay-lab')], env=env, stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, text=True, bufsize=1) + apps.append(app) + threading.Thread(target=read_logs, args=(name, app), daemon=True).start() + return app + +def move(point): + cua('move_cursor', target=target, x=point[0]*scale, y=point[1]*scale) + +def click(point): + cua('click', target=target, x=point[0]*scale, y=point[1]*scale) + +def center(region): + return (origin[0]+(region[0]+region[2])/2, origin[1]+(region[1]+region[3])/2) + +def drag_while(start, end, action): + result = [] + def run(): + try: + result.append(cua('drag', target=target, from_x=start[0]*scale, from_y=start[1]*scale, + to_x=end[0]*scale, to_y=end[1]*scale, duration_ms=2500, steps=100)) + except Exception as error: result.append(error) + thread = threading.Thread(target=run) + thread.start() + try: + wait(lambda s: s['trace'] and 'captured=true' in s['trace'] and 'buttons=1 ' in s['trace']) + snapshot('held-before-'+action) + command(action) + if action == 'none': + current = snapshot('held-after-none') + assert 'input=Regions ' in current['trace'] and 'captured=true' in current['trace'] + finally: + thread.join(timeout=35) + if thread.is_alive(): raise TimeoutError('Cua drag did not return') + if not result or isinstance(result[0], Exception): raise RuntimeError(str(result)) + +connection = None +try: + cua('start_session') + launch('underlay', OVERLAY_LAB_UNDERLAY='1') + overlay = launch('overlay', OVERLAY_LAB_CONTROL=str(root/'input.sock')) + wait(lambda s: s['window'] is not None) + command('show') + wait(lambda s: len(s['regions']) >= 4) + geometry = json.loads(subprocess.check_output([str(root/'capture-probe'), str(state['window']), '--geometry'], text=True)) + origin = (geometry['X'], geometry['Y']) + desktop = cua('get_desktop_state', screenshot_out_file=str(root/'grounding.png')) + (root/'grounding.json').write_text(json.dumps(desktop, indent=2)) + server = socket.socket(socket.AF_UNIX) + server.bind(str(root/'cua-control.sock')); server.listen(1); server.settimeout(120) + print(json.dumps({'ready': True, 'worker': os.getpid(), 'window': state['window'], 'geometry': geometry, + 'screenshot': str(root/'grounding.png')}), flush=True) + connection, _ = server.accept(); connection.settimeout(400) + request = json.loads(connection.recv(4096)) + if not request.get('run'): raise RuntimeError('run not authorized') + scale = request['scale'] + cycles = request.get('cycles', 20) + hide_case = request.get('hide_case', True) + outside = (origin[0]+20, origin[1]+80) + move(outside) + initial = snapshot('initial-outside', ignore=True) + assert 'ignore=true' in initial['trace'] + for trial in range(cycles): + inside = center(state['regions'][3]) + move(inside) + entered = snapshot(f'{trial+1}:enter', ignore=False) + assert 'ignore=false' in entered['trace'], entered + click(inside) + wait(lambda s: s['chips'] == trial+1 or s['clicks'] > trial) + pressed = snapshot(f'{trial+1}:inside-click') + assert pressed['chips'] == trial+1 and pressed['clicks'] == trial, pressed + move(outside) + left = snapshot(f'{trial+1}:leave', ignore=True) + assert 'ignore=true' in left['trace'], left + click(outside) + wait(lambda s: s['clicks'] == trial+1) + passed = snapshot(f'{trial+1}:outside-click') + assert passed['chips'] == trial+1 and passed['clicks'] == trial+1, passed + (root/'boundary-results.json').write_text(json.dumps({'cycles': cycles, 'overlay_clicks': state['chips'], + 'underlay_clicks': state['clicks'], 'window': state['window']}, indent=2)) + # Cancel an owned press by hiding mid-drag, then prove both routes recover. + if hide_case: + inside = center(state['regions'][3]) + move(inside) + drag_while(inside, outside, 'hide') + command('show') + move(outside); click(outside) + wait(lambda s: s['clicks'] == cycles+1) + snapshot('hide-mid-press-outside-recovered') + inside = center(state['regions'][3]) + move(inside); click(inside) + wait(lambda s: s['chips'] == cycles+1) + snapshot('hide-mid-press-inside-recovered') + count = cycles + int(hide_case) + # No Runtime press/drag handler: native capture alone must defer None. + command('hit-only') + wait(lambda s: len(s['regions']) == 1) + hit = center(state['regions'][0]) + move(hit) + click(hit) + bare = snapshot('hit-only-click') + assert bare['clicks'] == count and bare['chips'] == count, bare + drag_while(hit, outside, 'none') + # None stops polling. The final release row can precede applying the deferred + # mode, so prove None by actual cross-process delivery instead of another tick. + wait(lambda s: 'captured=false' in (s['trace'] or '')) + snapshot('hit-only-none-after-up', fresh=False) + move(hit); click(hit) + wait(lambda s: s['clicks'] == count+1) + record(steps, {'step': 'hit-only-through-after-none', **state}) + command('regions') + move(outside) + snapshot('regions-restored') + cua('get_desktop_state', screenshot_out_file=str(root/'final.png')) + result = {'cycles': cycles, 'overlay_clicks': cycles, 'underlay_clicks': cycles, + 'hide_mid_press': 'passed' if hide_case else 'not run', 'handlerless_hit_none_mid_press': 'passed', + 'final_overlay_clicks': state['chips'], 'final_underlay_clicks': state['clicks'], + 'window': state['window'], 'input_driver': 'CuaDriver desktop global input', + 'lost_up_limit': 'hide-mid-press cancellation; 100ms recovery remains unit-covered'} + (root/'results.json').write_text(json.dumps(result, indent=2)) + connection.sendall((json.dumps(result)+'\n').encode()) +except Exception as error: + (root/'failure.txt').write_text(repr(error)) + try: cua('get_desktop_state', screenshot_out_file=str(root/'failure.png')) + except Exception: pass + if connection: + connection.sendall((json.dumps({'error': repr(error)})+'\n').encode()) + raise +finally: + try: command('quit') + except OSError: pass + for app in apps: + if app.poll() is None: + # These are the two disposable probe processes created above, not user apps. + app.terminate() + app.wait(timeout=15) + try: cua('end_session') + except Exception as error: record(actions, {'cleanup_error': repr(error)}) + for name in ['input.sock', 'cua-control.sock']: (root/name).unlink(missing_ok=True) + actions.close(); steps.close() + lock.close() + (root/'finished').write_text('apps exited; Cua session ended; GUI lock released\n') + if connection: connection.close() diff --git a/app/vendor/rune/examples/overlay-lab/native/run-filter-probe.py b/app/vendor/rune/examples/overlay-lab/native/run-filter-probe.py new file mode 100644 index 0000000..5919731 --- /dev/null +++ b/app/vendor/rune/examples/overlay-lab/native/run-filter-probe.py @@ -0,0 +1,89 @@ +"""One native capsule still on the build Mac, while holding its shared GUI lock. Run on a build worker.""" +import fcntl +import json +import os +import pathlib +import re +import selectors +import subprocess +import sys +import time + +root = pathlib.Path(sys.argv[1]).resolve() +root.mkdir(parents=True, exist_ok=True) +lock = open('/tmp/pro-gui.lock', 'a') +fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) +driver = pathlib.Path.home() / '.local/bin/cua-driver' +session = 'rune-layer-filter-overlay' +binary = pathlib.Path(os.environ['CARGO_TARGET_DIR']) / 'debug/layer-filter-overlay' +probe = root / 'presentation-probe.dylib' +subprocess.run(['xcrun', 'clang', '-dynamiclib', '-fobjc-arc', '-framework', 'AppKit', + '-framework', 'QuartzCore', '-framework', 'Metal', + 'examples/overlay-lab/native/presentation-probe.m', '-o', str(probe)], check=True) + +def cua(tool, **args): + run = subprocess.run([str(driver), tool, json.dumps(dict(args, session=session))], + capture_output=True, text=True, timeout=45) + (root / (tool + '.json')).write_text(run.stdout) + if run.returncode: + raise RuntimeError(run.stdout + run.stderr) + value = json.loads(run.stdout) + if value.get('isError') or value.get('error'): + raise RuntimeError(run.stdout) + return value + +app = None +try: + cua('start_session') + app = subprocess.Popen([str(binary)], stdin=subprocess.PIPE, stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, env=dict(os.environ, DYLD_INSERT_LIBRARIES=str(probe))) + ready = selectors.DefaultSelector() + ready.register(app.stdout, selectors.EVENT_READ) + deadline = time.monotonic() + 60 + pending = b'' + lines = [] + window = None + shown = set() + presented = set() + while time.monotonic() < deadline: + if not ready.select(max(0, deadline - time.monotonic())): + break + chunk = os.read(app.stdout.fileno(), 65536) + if not chunk: + raise RuntimeError('overlay exited before presentation') + pending += chunk + while b'\n' in pending: + raw, pending = pending.split(b'\n', 1) + line = raw.decode(errors='replace') + lines.append(line) + if 'filter-overlay created' in line: + window = int(re.search(r'window_number: Some\((\d+)\)', line)[1]) + match = re.search(r'probe alpha window=(\d+) alpha=1\.0 ', line) + if match: + shown.add(int(match[1])) + match = re.search(r'probe presented window=(\d+) .*presented=([\d.]+)', line) + if match and float(match[2]) > 0: + presented.add(int(match[1])) + if window in shown and window in presented: + break + (root / 'presentation.log').write_text('\n'.join(lines) + '\n') + if window not in shown or window not in presented: + raise TimeoutError('no visible, positively presented overlay drawable') + cua('get_window_state', pid=app.pid, window_id=window, include_accessibility_tree=False, + max_image_dimension=0, screenshot_out_file=str(root / 'native-overlay.png')) + if not (root / 'native-overlay.png').is_file(): + raise RuntimeError('Cua did not capture the requested window') + result = dict(pid=app.pid, window=window, positive_presentation=True, + screenshot='native-overlay.png', fixture='400x40pt; sigma 1.5pt; opacity .65') + (root / 'result.json').write_text(json.dumps(result, indent=2)) + print(json.dumps(result), flush=True) +finally: + if app is not None: + app.stdin.close() + try: + app.wait(timeout=15) + except subprocess.TimeoutExpired: + app.terminate() + app.wait(timeout=10) + cua('end_session') + probe.unlink(missing_ok=True) diff --git a/app/vendor/rune/examples/overlay-lab/native/run-idle-probe.py b/app/vendor/rune/examples/overlay-lab/native/run-idle-probe.py new file mode 100644 index 0000000..ecb6c6d --- /dev/null +++ b/app/vendor/rune/examples/overlay-lab/native/run-idle-probe.py @@ -0,0 +1,74 @@ +"""Measure normal-priority idle costs on an authorized Mac; caller holds its GUI lock.""" +import ctypes, json, os, pathlib, selectors, socket, subprocess, sys, time + +root = pathlib.Path(sys.argv[1]) +control = root/'idle.sock' +env = dict(os.environ, OVERLAY_LAB_SECONDS='70', OVERLAY_LAB_CONTROL=str(control), + DYLD_INSERT_LIBRARIES=str(root/'presentation-probe.dylib')) +env.pop('OVERLAY_PROBE_REDRAW', None) +env.pop('RUNE_OVERLAY_TRACE_INPUT', None) +log = (root/'idle.log').open('w') +process = subprocess.Popen([str(root/'overlay-lab')], env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) +selector = selectors.DefaultSelector() +selector.register(process.stdout, selectors.EVENT_READ) +buffer, frames = b'', 0 + +def drain(seconds): + global buffer, frames + deadline = time.monotonic()+seconds + while True: + while b'\n' in buffer: + raw, buffer = buffer.split(b'\n',1) + line = raw.decode(errors='replace'); log.write(line+'\n'); log.flush() + if line.startswith('probe presented '): frames += 1 + if seconds == 0 and 'pill created' in line: return + remaining = 10 if seconds == 0 else deadline-time.monotonic() + if remaining <= 0: return + if not selector.select(remaining): + if seconds == 0: raise TimeoutError('no created callback') + return + chunk = os.read(process.stdout.fileno(),65536) + if not chunk: raise RuntimeError('app exited') + buffer += chunk + +class Usage(ctypes.Structure): + _fields_ = [('uuid',ctypes.c_uint8*16)] + [(name,ctypes.c_uint64) for name in + ['user','system','package_wakes','interrupt_wakes','pageins','wired','resident','footprint','start','exit']] + +lib = ctypes.CDLL('/usr/lib/libproc.dylib') +def usage(): + value = Usage() + if lib.proc_pid_rusage(process.pid,0,ctypes.byref(value)) != 0: raise OSError('proc_pid_rusage failed') + return value + +def command(value): + with socket.socket(socket.AF_UNIX) as client: + client.settimeout(5); client.connect(str(control)); client.sendall((value+'\n').encode()) + return client.recv(4096).decode() + +results = [] +try: + drain(0) + phases = [('hidden','status'),('visible','show'),('hidden-again','hide')] + if '--modes' in sys.argv: + command('show') + phases = [('all','all'),('none','none'),('regions','regions')] + for phase, action in phases: + command(action) + # Exclude transition work; drain logs continuously during the measurement. + drain(1) + before, count, started = usage(), frames, time.monotonic() + drain(10) + elapsed, after = time.monotonic()-started, usage() + result = dict(phase=phase, seconds=elapsed, + cpu_percent=(after.user+after.system-before.user-before.system)/1e9/elapsed*100, + interrupt_wakes_per_second=(after.interrupt_wakes-before.interrupt_wakes)/elapsed, + package_wakes_per_second=(after.package_wakes-before.package_wakes)/elapsed, + drawable_callbacks=frames-count) + results.append(result); print(json.dumps(result),flush=True) + (root/'idle-results.json').write_text(json.dumps(results,indent=2)) +finally: + try: command('quit') + except OSError: pass + process.wait(timeout=75) + log.close(); control.unlink(missing_ok=True) diff --git a/app/vendor/rune/examples/overlay-lab/native/run-input-probe.py b/app/vendor/rune/examples/overlay-lab/native/run-input-probe.py new file mode 100644 index 0000000..d7db5e9 --- /dev/null +++ b/app/vendor/rune/examples/overlay-lab/native/run-input-probe.py @@ -0,0 +1,82 @@ +"""Explicitly authorized native input test; caller holds the host GUI lock.""" +import ast, json, os, pathlib, re, selectors, socket, subprocess, sys, time + +root = pathlib.Path(sys.argv[1]) +control = root / 'input.sock' +env = dict(os.environ, OVERLAY_LAB_SECONDS='90', RUNE_OVERLAY_TRACE_INPUT='1', + OVERLAY_LAB_INCLUDE_IN_CAPTURE='1') +underlay = subprocess.Popen([str(root/'overlay-lab')], env=dict(env, OVERLAY_LAB_UNDERLAY='1'), + stdout=subprocess.PIPE, stderr=subprocess.STDOUT) +overlay = subprocess.Popen([str(root/'overlay-lab')], env=dict(env, OVERLAY_LAB_CONTROL=str(control)), + stdout=subprocess.PIPE, stderr=subprocess.STDOUT) +selector = selectors.DefaultSelector() +for name, process in [('underlay', underlay), ('overlay', overlay)]: + selector.register(process.stdout, selectors.EVENT_READ, name) +buffers = {'underlay': b'', 'overlay': b''} +logs = {name: (root/f'input-{name}.log').open('w') for name in buffers} +regions, clicks, chips, window = [], 0, 0, None +snapshots = {} + +def pump(until, seconds=5): + global regions, clicks, chips, window + deadline = time.monotonic() + seconds + while not until(): + if time.monotonic() >= deadline: raise TimeoutError('input assertion timed out') + for key, _ in selector.select(max(0, deadline-time.monotonic())): + name = key.data + chunk = os.read(key.fileobj.fileno(), 65536) + if not chunk: raise RuntimeError(f'{name} exited') + buffers[name] += chunk + while b'\n' in buffers[name]: + line, buffers[name] = buffers[name].split(b'\n', 1) + line = line.decode(errors='replace') + logs[name].write(line+'\n'); logs[name].flush() + if name == 'underlay' and 'underlay click ' in line: + clicks = int(line.rsplit(' ', 1)[1]) + if name == 'overlay' and 'overlay-lab chip iPhone' in line: chips += 1 + if name == 'overlay' and 'pill created' in line: + window = int(re.search(r'window_number: Some\((\d+)\)', line)[1]) + if line.startswith('overlay-input ') and 'regions=' in line: + observed = int(re.search(r'window=(\d+)', line)[1]) + snapshots[observed] = ast.literal_eval(line.split('regions=', 1)[1]) + regions = snapshots.get(window, []) + +def command(value): + with socket.socket(socket.AF_UNIX) as client: + client.settimeout(5); client.connect(str(control)); client.sendall((value+'\n').encode()) + return client.recv(4096).decode() + +def move(start, finish, click=False): + helper = os.environ.get('OVERLAY_MOUSE_HELPER', str(pathlib.Path.home()/'tmp/rune-overlay-probe/mouse-path')) + result = subprocess.run([helper, *map(str, start+finish), '32'] + (['click'] if click else []), + capture_output=True, text=True, timeout=5) + print(result.stdout.strip(), flush=True) + if result.returncode: raise RuntimeError(f'input helper failed: {result.returncode} {result.stderr}') + +try: + pump(lambda: window is not None and len(regions) >= 4) + command('show') + geometry = json.loads(subprocess.check_output([str(root/'capture-probe'), str(window), '--geometry'], text=True)) + x, y = geometry['X'], geometry['Y'] + outside = (x+20, y+80) + move((x+20, y+200), outside) + for trial in range(20): + # iPhone is the fourth hit chip; its geometry shifts when Route appears. + r = regions[3] + inside = (x+(r[0]+r[2])/2, y+(r[1]+r[3])/2) + move(outside, inside, True) + pump(lambda: chips == trial+1 or clicks > trial) + assert chips == trial+1 and clicks == trial, f'inside: chips={chips} underlay={clicks} trial={trial+1}' + move(inside, outside, True) + pump(lambda: clicks == trial+1) + assert chips == trial+1 and clicks == trial+1 + print(f'PASS cycle={trial+1} overlay={chips} underlay={clicks}', flush=True) + (root/'input-results.json').write_text(json.dumps({'cycles':20, 'overlay_clicks':chips, 'underlay_clicks':clicks, 'window':window}, indent=2)) +finally: + try: command('quit') + except OSError: pass + # Underlay has its own bounded app timer; do not terminate unrelated processes. + overlay.wait(timeout=100) + underlay.wait(timeout=100) + for file in logs.values(): file.close() + control.unlink(missing_ok=True) diff --git a/app/vendor/rune/examples/overlay-lab/native/run-native-probe.py b/app/vendor/rune/examples/overlay-lab/native/run-native-probe.py new file mode 100644 index 0000000..627ee8e --- /dev/null +++ b/app/vendor/rune/examples/overlay-lab/native/run-native-probe.py @@ -0,0 +1,101 @@ +"""Run on an authorized Mac, while the caller holds its GUI lock.""" +import json, math, os, pathlib, re, selectors, socket, statistics, subprocess, sys, time +from prewarm_trace import assert_prewarmed + +root = pathlib.Path(sys.argv[1]) +retained = os.environ.get('OVERLAY_PROBE_RETAINED') == '1' +if subprocess.run(['pgrep', '-f', '[r]une-smoke/ci/Hex.app'], capture_output=True).returncode == 0: + raise SystemExit('BLOCKED: competing Hex GUI probe is still alive') +control = root / 'control.sock' +env = dict(os.environ, OVERLAY_LAB_SECONDS='100', OVERLAY_LAB_CONTROL=str(control), + DYLD_INSERT_LIBRARIES=str(root / 'presentation-probe.dylib')) +process = subprocess.Popen([str(root / 'overlay-lab')], env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) +selector = selectors.DefaultSelector() +selector.register(process.stdout, selectors.EVENT_READ) +buffer = b'' +lines = [] +log = (root / 'presentation.log').open('w') + +def wait_for(predicate, seconds=20): + global buffer + deadline = time.monotonic() + seconds + while time.monotonic() < deadline: + while b'\n' in buffer: + raw, buffer = buffer.split(b'\n', 1) + line = raw.decode(errors='replace') + log.write(line + '\n'); log.flush(); lines.append(line) + if predicate(line): return line + if not selector.select(max(0, deadline - time.monotonic())): break + chunk = os.read(process.stdout.fileno(), 65536) + if not chunk: raise RuntimeError('overlay exited before expected event') + buffer += chunk + raise TimeoutError('native event did not arrive') + +def command(value): + with socket.socket(socket.AF_UNIX) as connection: + connection.settimeout(5) + connection.connect(str(control)) + connection.sendall((value+'\n').encode()) + reply = connection.recv(4096).decode().strip() + print(reply, flush=True) + return reply + +try: + created = wait_for(lambda line: 'pill created' in line) + window = int(re.search(r'window_number: Some\((\d+)\)', created)[1]) + if retained: + assert_prewarmed(lines, window) + samples, identities, timed_out, alpha_ms, dropped = [], [], [], [], 0 + for trial in range(31): + if trial: + hidden = command('hide') + assert f'window=Some({window})' in hidden, hidden + prefix = f'probe alpha window={window} alpha=0.0 ' if retained else f'probe hidden window={window} visible=0 ' + wait_for(lambda line: line.startswith(prefix)) + state = subprocess.check_output([str(root / 'capture-probe'), str(window)] + ([] if retained else ['--hidden']), text=True, timeout=10).strip() + assert 'exists=true' in state, state + if not retained: assert 'onScreen=0' in state or 'onScreen=false' in state, state + shown = command('show') + assert f'window=Some({window})' in shown, shown + requested = float(re.search(r'time=([\d.]+)', shown)[1]) + if retained: + flipped = wait_for(lambda line: line.startswith(f'probe alpha window={window} alpha=1.0 ')) + alpha_ms.append((float(re.search(r'time=([\d.]+)', flipped)[1])-requested)*1000) + def first_presentation(line): + global dropped + if not line.startswith(f'probe presented window={window} '): return False + if float(re.search(r'acquired=([\d.]+)', line)[1]) < requested: return False + presented = float(re.search(r'presented=([\d.]+)', line)[1]) + if presented == 0: dropped += 1 + return presented >= requested + try: + # Never hide after a discarded drawable. Wait for a positive timestamp; + # a two-second absence is a failed trial, not a zero-latency success. + frame = wait_for(first_presentation, seconds=2) + except TimeoutError: + timed_out.append(trial+1) + delta = None + else: + presented = float(re.search(r'presented=([\d.]+)', frame)[1]) + assert presented >= requested, frame + delta = (presented - requested) * 1000 + samples.append(delta) + identities.append(window) + print(f'trial={trial+1} show_to_present_ms={delta} window={window}', flush=True) + capture = subprocess.run([str(root / 'capture-probe'), str(window), str(root / 'capture')], capture_output=True, text=True, timeout=20) + print(capture.stdout, capture.stderr, flush=True) + result = dict(samples_ms=samples, window_ids=identities, capture_exit=capture.returncode, + unpresented_callbacks=dropped, timed_out_trials=timed_out, alpha_ms=alpha_ms, + diagnostic_redraw=bool(os.environ.get('OVERLAY_PROBE_REDRAW')), + min_ms=min(samples) if samples else None, median_ms=statistics.median(samples) if samples else None, + p95_ms=sorted(samples)[math.ceil(len(samples)*.95)-1] if samples else None, + max_ms=max(samples) if samples else None, under_16=sum(v < 16 for v in samples)) + (root / 'results.json').write_text(json.dumps(result, indent=2)) + print(json.dumps(result), flush=True) +finally: + # Ask the lab to quit; its bounded timer is a fallback if the socket is unavailable. + try: command('quit') + except (OSError, TimeoutError): pass + process.wait(timeout=110) + log.close() + control.unlink(missing_ok=True) diff --git a/app/vendor/rune/examples/overlay-lab/native/run-pill-probe.py b/app/vendor/rune/examples/overlay-lab/native/run-pill-probe.py new file mode 100644 index 0000000..c64cb0a --- /dev/null +++ b/app/vendor/rune/examples/overlay-lab/native/run-pill-probe.py @@ -0,0 +1,45 @@ +"""Compare the installed Metal pill; caller holds /tmp/pro-gui.lock on the authorized Mac. + +Endpoint is native orderFrontRegardless entry during an app's already-visible panel sync, +not the beginning of the app's coordinator request. No redraw assistance is injected. +""" +import hashlib, json, math, os, pathlib, re, statistics, subprocess, sys + +binary, root = map(pathlib.Path, sys.argv[1:3]) +env = dict(os.environ, DYLD_INSERT_LIBRARIES=str(root/'presentation-probe.dylib')) +for key in ['OVERLAY_PROBE_REDRAW', 'OVERLAY_PROBE_NATIVE_OPTIONS']: + env.pop(key, None) +args = [str(binary), 'lab', 'pill', 'tap-then-screen', '--repeat', '30', + '--time-scale', '1', '--no-backdrop', '--trace', str(root/'motion.jsonl')] +(root/'load-before.txt').write_bytes(subprocess.check_output(['top','-l','1','-n','0'])) +run = subprocess.run(args, env=env, capture_output=True, text=True, timeout=160) +(root/'presentation.log').write_text(run.stdout+run.stderr) +(root/'load-after.txt').write_bytes(subprocess.check_output(['top','-l','1','-n','0'])) +if run.returncode: raise RuntimeError(f'Reference app lab exited {run.returncode}; see presentation.log') +fronts, frames = [], [] +for line in run.stderr.splitlines(): + front = re.match(r'probe front window=(\d+) requested=([\d.]+) was_visible=1 panel=1 level=30 view=(.*)',line) + if front and 'PillView' in front[3]: fronts.append((int(front[1]),float(front[2]))) + frame = re.match(r'probe presented window=(\d+) acquired=([\d.]+) presented=([\d.]+)',line) + if frame: frames.append((int(frame[1]),float(frame[2]),float(frame[3]))) +trials = [] +for i, (window, requested) in enumerate(fronts): + limit = min(requested+2, fronts[i+1][1]) if i+1 < len(fronts) else requested+2 + candidates = [presented for owner, acquired, presented in frames + if owner == window and requested <= acquired < limit and requested <= presented < limit] + trials.append(dict(window=window, requested=requested, + latency_ms=(min(candidates)-requested)*1000 if candidates else None)) +samples = [t['latency_ms'] for t in trials if t['latency_ms'] is not None] +result = dict(binary=str(binary), sha256=hashlib.sha256(binary.read_bytes()).hexdigest(), + profile='installed app; optimization profile not established', + start='native orderFrontRegardless entry during already-visible pill sync', + end='first positive Metal presentedTime acquired after that entry', + diagnostic_redraw=False, trials=trials, + min_ms=min(samples) if samples else None, median_ms=statistics.median(samples) if samples else None, + p95_ms=sorted(samples)[math.ceil(len(samples)*.95)-1] if samples else None, + max_ms=max(samples) if samples else None, under_16=sum(v<16 for v in samples), + zero_callbacks=sum(presented==0 for _,_,presented in frames)) +(root/'results.json').write_text(json.dumps(result,indent=2)) +print(json.dumps({k:v for k,v in result.items() if k!='trials'},indent=2),flush=True) +print(f'trials={len(trials)} valid={len(samples)}',flush=True) +if len(trials)!=30 or len(samples)!=30: raise RuntimeError('Expected 30 native show markers and valid presentations') diff --git a/app/vendor/rune/examples/overlay-lab/native/run-window-panel-probe.py b/app/vendor/rune/examples/overlay-lab/native/run-window-panel-probe.py new file mode 100644 index 0000000..7fe5875 --- /dev/null +++ b/app/vendor/rune/examples/overlay-lab/native/run-window-panel-probe.py @@ -0,0 +1,51 @@ +"""One bounded Pro GUI lease; serve explicit Cua/fixture actions under the GUI lock.""" +import fcntl, json, os, pathlib, socket, subprocess, sys, time + +assert socket.gethostname().startswith('Kits-Shiny-Computer') +root = pathlib.Path(sys.argv[1]).resolve() +root.mkdir(parents=True, exist_ok=True) +driver = str(pathlib.Path.home()/'.local/bin/cua-driver') +session = 'rune-window-panel' + +def command(text): + with socket.socket(socket.AF_UNIX) as client: + client.settimeout(8) + client.connect(str(root/'app.sock')) + client.sendall((text+'\n').encode()) + return client.makefile().readline().strip() + +with open('/tmp/pro-gui.lock', 'a') as lock, (root/'app.log').open('w') as log, (root/'actions.jsonl').open('w') as actions: + fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + subprocess.run([driver, 'start_session', json.dumps({'session':session})], capture_output=True, check=True, timeout=15) + with socket.socket(socket.AF_UNIX) as server: + server.bind(str(root/'proof.sock')) + server.listen() + server.settimeout(600) + app = subprocess.Popen([sys.argv[2]], env=dict(os.environ, WINDOW_PANEL_SOCKET=str(root/'app.sock')), stdout=log, stderr=subprocess.STDOUT) + try: + print(json.dumps({'ready':str(root/'proof.sock'),'pid':app.pid}), flush=True) + while True: + client, _ = server.accept() + with client: + request = json.loads(client.makefile().readline()) + try: + if 'command' in request: + result = command(request['command']) + elif 'tool' in request: + args = dict(request.get('args', {}), session=session) + run = subprocess.run([driver, request['tool'], json.dumps(args)], capture_output=True, text=True, timeout=45) + result = {'exit':run.returncode,'stdout':run.stdout,'stderr':run.stderr} + else: + result = 'finished' + actions.write(json.dumps({'time':time.time(),'request':request,'result':result})+'\n'); actions.flush() + client.sendall((json.dumps(result)+'\n').encode()) + if request.get('finish'): break + except Exception as error: + client.sendall((json.dumps({'error':str(error)})+'\n').encode()) + finally: + if app.poll() is None: + try: command('quit'); app.wait(timeout=5) + except Exception: app.terminate(); app.wait(timeout=5) + subprocess.run([driver,'end_session',json.dumps({'session':session})], capture_output=True, timeout=15) + for name in ['app.sock','proof.sock']: (root/name).unlink(missing_ok=True) + print('Fixture exited; GUI lock released on exit.', flush=True) diff --git a/app/vendor/rune/examples/overlay-lab/native/test_prewarm_trace.py b/app/vendor/rune/examples/overlay-lab/native/test_prewarm_trace.py new file mode 100644 index 0000000..6da8d14 --- /dev/null +++ b/app/vendor/rune/examples/overlay-lab/native/test_prewarm_trace.py @@ -0,0 +1,23 @@ +import unittest + +from prewarm_trace import assert_prewarmed + + +class PrewarmTraceTests(unittest.TestCase): + created = 'overlay-lab pill created OverlayCreated { window_number: Some(12), capabilities: ... }' + acquired = 'probe acquired window=12 alpha=0.0 time=1.0' + + def test_accepts_alpha_zero_acquisition_before_creation(self): + assert_prewarmed([self.acquired, self.created], 12) + + def test_rejects_occlusion_skip_late_or_visible_acquisition(self): + for lines in ([self.created], [self.created, self.acquired], + [self.acquired.replace('alpha=0.0', 'alpha=1.0'), self.created], + [self.acquired.replace('window=12', 'window=11'), self.created], + [self.acquired]): + with self.subTest(lines=lines), self.assertRaises(AssertionError): + assert_prewarmed(lines, 12) + + +if __name__ == '__main__': + unittest.main() diff --git a/app/vendor/rune/examples/overlay-lab/native/window-panel-focus.json b/app/vendor/rune/examples/overlay-lab/native/window-panel-focus.json new file mode 100644 index 0000000..5526e08 --- /dev/null +++ b/app/vendor/rune/examples/overlay-lab/native/window-panel-focus.json @@ -0,0 +1,5 @@ +[ + {"t": 0, "focus": true}, + {"t": 0.1, "focus": false}, + {"t": 0.2, "focus": false} +] diff --git a/app/vendor/rune/examples/overlay-lab/src/bin/layer-filter-overlay.rs b/app/vendor/rune/examples/overlay-lab/src/bin/layer-filter-overlay.rs new file mode 100644 index 0000000..b0c9593 --- /dev/null +++ b/app/vendor/rune/examples/overlay-lab/src/bin/layer-filter-overlay.rs @@ -0,0 +1,44 @@ +//! Static exit samples on a real native overlay, for capsule/filter integration review. + +#![forbid(unsafe_code)] + +use rune::{App, AppSpec, Color, Cx, DisplayTarget, El, OverlayInput, OverlayLevel, + OverlayOptions, OverlaySpec, RunOptions, WindowSpec, el, text}; + +const INK: Color = Color { r: 0.06, g: 0.32, b: 1.0, a: 1.0 }; +const SURFACE: Color = Color { r: 0.035, g: 0.035, b: 0.035, a: 1.0 }; + +fn view(_: &(), _: &mut Cx<()>) -> El { + let mut root = el().size(620.0, 176.0); + for (label, y, clipped) in [("Unmasked", 32.0, false), ("Clipped", 112.0, true)] { + let mut capsule = el().size(400.0, 40.0).absolute(112.0, y).radius(20.0).fill(SURFACE); + if clipped { capsule = capsule.clip_rounded(20.0); } + // Shared background stays outside the dissolve; blur is on the leaving state. + let state = el().size(72.0, 28.0).absolute(370.0, 6.0).opacity(0.65).blur(1.5) + .radius(8.0).fill(INK).child(text("Leaving").absolute(8.0, 6.0)); + root = root.child(text(label).absolute(12.0, y + 11.0)) + .child(capsule.child(el().size(400.0, 40.0).dissolve().child(state))); + } + root +} + +fn main() { + let spec = AppSpec { title: "Layer filter overlay", size: (620.0, 176.0), min_size: None, + init: || (), view, scenes: &[], fonts: &[], families: ("sans-serif", "monospace"), + setup: None, poll: None, on_key: None }; + rune::run_windows_with(RunOptions { accessory: true }, |_| { + let mut app = App::new(spec).windowless(); + let pill = app.overlay(OverlaySpec::new("Layer filter capsule proof", (620.0, 176.0), view) + .options(OverlayOptions { display: DisplayTarget::Primary, input: OverlayInput::None, + level: OverlayLevel::AboveOverlays, exclude_from_capture: false, prewarm: true, ..Default::default() }) + .on_created(|created| eprintln!("filter-overlay created {created:?}")), ()); + pill.show(); + let handle = app.handle(); + // The probe owns stdin and closes it even on capture failure. No persistent GUI job. + std::thread::spawn(move || { + std::io::stdin().read_line(&mut String::new()).ok(); + handle.quit(); + }); + vec![WindowSpec::from_app("filter-proof", app)] + }); +} diff --git a/app/vendor/rune/examples/overlay-lab/src/bin/occluded-timer.rs b/app/vendor/rune/examples/overlay-lab/src/bin/occluded-timer.rs new file mode 100644 index 0000000..82bd798 --- /dev/null +++ b/app/vendor/rune/examples/overlay-lab/src/bin/occluded-timer.rs @@ -0,0 +1,93 @@ +//! An overlay with a repeating 100 ms timer, for measuring idle cost while the panel is +//! covered or the displays sleep. Prints its timer count once a second. +//! +//! `OCCLUDED_TIMER_SECONDS=n` quits after n seconds; `OCCLUDED_TIMER_PREWARM=1` prewarms the +//! panel; `OCCLUDED_TIMER_REGIONS=1` takes pointer input over its pill only; +//! `OCCLUDED_TIMER_BOTTOM=1` puts it at the bottom edge; `OCCLUDED_TIMER_WINDOW=1` runs the +//! timer in a regular window instead. `OCCLUDED_TIMER_UPDATE=1` replaces the repeating timer +//! with one 100 ms `wake_after` that an update from another thread sets each second, and also +//! prints the latest that timer fired. + +#![forbid(unsafe_code)] + +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::time::{Duration, Instant}; +use rune::{App, AppSpec, Color, Cx, El, OverlayInput, OverlayOptions, OverlaySpec, RunOptions, ScreenEdge, Tx, WindowOptions, WindowSpec, el, text}; + +const PERIOD: f64 = 0.1; +const ARMED: Duration = Duration::from_millis(100); +static FIRED: AtomicUsize = AtomicUsize::new(0); +static WORST_MS: AtomicUsize = AtomicUsize::new(0); + +#[derive(Default)] +struct State { next: f64, armed: Option<Instant> } + +fn view(_: &State, _: &mut Cx<State>) -> El { + el().key("pill").hit().padding(12.0).radius(16.0).fill(Color { r: 0.1, g: 0.12, b: 0.16, a: 0.95 }) + .child(text(format!("fired {}", FIRED.load(Ordering::Relaxed))).color(Color::WHITE)) +} + +fn poll(s: &mut State, t: f64, tx: &mut Tx) -> bool { + if updates() { return poll_armed(s); } + let fired = t >= s.next; + if fired { + FIRED.fetch_add(1, Ordering::Relaxed); + s.next = t + PERIOD; + } + tx.wake_after(Duration::from_secs_f64((s.next - t).max(0.0))); + fired +} + +/// Counts the update's timer once it is due, and how late it ran. +fn poll_armed(s: &mut State) -> bool { + let Some(at) = s.armed.filter(|at| at.elapsed() >= ARMED) else { return false }; + s.armed = None; + FIRED.fetch_add(1, Ordering::Relaxed); + WORST_MS.fetch_max(at.elapsed().as_millis() as usize, Ordering::Relaxed); + true +} + +fn arm(s: &mut State, tx: &mut Tx) { + s.armed = Some(rune::time::now()); + tx.wake_after(ARMED); +} + +fn updates() -> bool { std::env::var_os("OCCLUDED_TIMER_UPDATE").is_some() } + +fn main() { + rune::run_windows_with(RunOptions { accessory: true }, |_| { + let window = std::env::var_os("OCCLUDED_TIMER_WINDOW").is_some(); + let spec = AppSpec { poll: window.then_some(poll as fn(&mut State, f64, &mut Tx) -> bool), ..AppSpec::new("Occluded timer", (420.0, 400.0), State::default, view) }; + let mut app = App::new(spec); + if window { + let handle = app.handle(); + report(app.handle(), move || handle.update(arm)); + // Side by side, so neither covers the other. + let x = if std::env::var_os("OCCLUDED_TIMER_BOTTOM").is_some() { 900 } else { 100 }; + return vec![WindowSpec::from_app("occluded-timer", app).options(WindowOptions { position: Some((x, 200)), ..Default::default() })]; + } + app = app.windowless(); + let input = if std::env::var_os("OCCLUDED_TIMER_REGIONS").is_some() { OverlayInput::Regions } else { OverlayInput::All }; + let edge = if std::env::var_os("OCCLUDED_TIMER_BOTTOM").is_some() { ScreenEdge::Bottom } else { ScreenEdge::Top }; + let overlay = app.overlay(OverlaySpec { edge, ..OverlaySpec::new("Occluded timer", (220.0, 60.0), view) }.options(OverlayOptions { + input, prewarm: std::env::var_os("OCCLUDED_TIMER_PREWARM").is_some(), ..Default::default() + }).poll(poll), State::default()); + overlay.show(); + report(app.handle(), move || overlay.update(arm)); + vec![WindowSpec::from_app("occluded-timer", app)] + }); +} + +fn report(handle: rune::AppHandle<State>, arm: impl Fn() + Send + 'static) { + let quit = rune::env::var("OCCLUDED_TIMER_SECONDS").and_then(|s| s.parse::<u64>().ok()); + std::thread::spawn(move || { + let start = rune::time::now(); + loop { + std::thread::sleep(Duration::from_secs(1)); + let elapsed = start.elapsed().as_secs(); + eprintln!("occluded-timer t={elapsed} fired={} worst_ms={}", FIRED.load(Ordering::Relaxed), WORST_MS.load(Ordering::Relaxed)); + if quit.is_some_and(|q| elapsed >= q) { handle.quit(); return; } + if updates() { arm(); } + } + }); +} diff --git a/app/vendor/rune/examples/overlay-lab/src/main.rs b/app/vendor/rune/examples/overlay-lab/src/main.rs new file mode 100644 index 0000000..4339acb --- /dev/null +++ b/app/vendor/rune/examples/overlay-lab/src/main.rs @@ -0,0 +1,186 @@ +use std::sync::{Arc, Mutex}; +use rune::{App, AppSpec, Color, Cx, DisplayTarget, El, Key, KeyEvent, KeyPolicy, OverlayHandle, OverlayInput, OverlayLevel, OverlayOptions, OverlayPlacement, OverlaySpec, Phase, RunOptions, Tx, WindowSpec, col, el, row, text}; + +const BLUE: Color = Color { r: 0.25, g: 0.55, b: 1.0, a: 1.0 }; +const DARK: Color = Color { r: 0.055, g: 0.065, b: 0.085, a: 0.97 }; + +#[derive(Default)] +struct Handles { pill: Option<OverlayHandle<State>>, pickers: Vec<OverlayHandle<State>> } +struct State { + underlay: bool, + hit_only: bool, + clicks: u32, + picker: bool, + expanded: bool, + hovered: String, + selection: Option<[f32; 4]>, + selection_at_press: Option<[f32; 4]>, + pointer: rune::Live<[f32; 2]>, + handles: Arc<Mutex<Handles>>, +} +fn init() -> State { + State { underlay: false, hit_only: false, clicks: 0, picker: false, expanded: false, hovered: String::new(), selection: None, selection_at_press: None, pointer: rune::Live::new([160.0, 100.0]), handles: Arc::default() } +} +fn show_picker(s: &mut State) { + let handles = s.handles.lock().unwrap(); + for picker in &handles.pickers { picker.show(); } + // One key owner, even with several full-display surfaces. + if let Some(picker) = handles.pickers.first() { picker.request_keys(); } + eprintln!("overlay-lab picker shown"); +} +fn hide_picker(s: &mut State) { + for picker in &s.handles.lock().unwrap().pickers { picker.hide(); } + eprintln!("overlay-lab picker hidden"); +} +fn key(s: &mut State, event: &KeyEvent, _: &mut Tx) -> bool { + eprintln!("overlay-lab key {event:?}"); + if event.key == Key::Escape { hide_picker(s); return true; } + false +} +fn chip(label: &'static str, action: fn(&mut State)) -> El { + el().key(label).hit().padding(10.0).radius(16.0).fill(BLUE.alpha(0.16)) + .child(text(label).color(Color::WHITE)) + .on_hover(move |s: &mut State| { s.hovered = label.into(); }) + .on_press(move |s: &mut State| { eprintln!("overlay-lab chip {label}"); action(s); }) +} +fn view(s: &State, _: &mut Cx<State>) -> El { + if s.underlay { + return el().w_full().h_full().fill(DARK).padding(40.0) + .child(text(format!("Underlay clicks: {}", s.clicks)).color(Color::WHITE)) + .on_press(|s: &mut State| { s.clicks += 1; eprintln!("overlay-lab underlay click {}", s.clicks); }); + } + if s.picker { + let mut root = el().w_full().h_full().hit().fill(BLUE.alpha(0.06)) + .on_pointer_move_local(|s: &mut State, p, tx| { + s.pointer.set([p.window_x, p.window_y]); + tx.live_only(); + }) + .on_drag(|s: &mut State, drag, tx| { + tx.instant(); + if drag.phase == Phase::Down { s.selection_at_press = s.selection; } + if drag.cancelled() { s.selection = s.selection_at_press.take(); return; } + let (x, y) = (drag.x.min(drag.start_x), drag.y.min(drag.start_y)); + s.selection = Some([x, y, (drag.x - drag.start_x).abs(), (drag.y - drag.start_y).abs()]); + if drag.phase == Phase::Up { eprintln!("overlay-lab selection {:?}", s.selection); } + }) + .child(text("Drag an area · Escape to close").color(Color::WHITE).pin(Some(24.0), Some(24.0), None, None)) + .child(el().size(8.0, 8.0).radius(4.0).fill(BLUE).pin(Some(0.0), Some(0.0), None, None).live_offset(&s.pointer)); + if let Some([x, y, w, h]) = s.selection { + root = root.child(el().key("selection").size(w, h).border(2.0, BLUE).fill(BLUE.alpha(0.12)).pin(Some(x), Some(y), None, None)); + } + return root; + } + if s.hit_only { + return col().w_full().h_full().center().child(el().key("hit-only").size(300.0, 48.0).hit() + .fill(DARK).child(text("Native hit region").color(Color::WHITE))); + } + let mut chips = row().key("pill").padding(8.0).gap(4.0).radius(28.0).fill(DARK) + .child(chip("Area", show_picker)).child(chip("Window", show_picker)) + .child(chip("Screen", show_picker)).child(chip("iPhone", |s| s.expanded = !s.expanded)); + if s.expanded { chips = chips.child(chip("Route", |s| s.expanded = false)); } + chips = chips.child(chip("Paste", |s| s.expanded = !s.expanded)) + .child(chip("×", |s| { if let Some(pill) = &s.handles.lock().unwrap().pill { pill.hide(); } })); + col().w_full().h_full().center().gap(8.0).child(chips) + .child(text(&s.hovered).color(BLUE)) +} +fn spec() -> AppSpec<State> { + AppSpec { title: "Overlay lab", size: (680.0, 160.0), min_size: None, init, view, + scenes: &[("pill", |_| {}), ("expanded", |s| s.expanded = true), ("picker", |s| { s.picker = true; s.selection = Some([140.0, 100.0, 560.0, 320.0]); })], + fonts: &[], families: ("sans-serif", "monospace"), setup: None, poll: None, on_key: Some(key) } +} + +/// Optional local control socket for bounded native lifecycle/presentation probes. +#[cfg(target_os = "macos")] +#[allow(unsafe_code)] +fn native_probe(pill: OverlayHandle<State>, app: rune::AppHandle<State>) { + use std::io::{BufRead, BufReader, Write}; + use std::os::unix::net::UnixListener; + #[link(name = "QuartzCore", kind = "framework")] + unsafe extern "C" { fn CACurrentMediaTime() -> f64; } + let Some(path) = std::env::var_os("OVERLAY_LAB_CONTROL") else { return }; + let listener = UnixListener::bind(&path).expect("unique overlay probe socket"); + std::thread::spawn(move || { + for stream in listener.incoming() { + let Ok(mut stream) = stream else { break }; + let mut command = String::new(); + if BufReader::new(&stream).read_line(&mut command).is_err() { continue; } + // SAFETY: `CACurrentMediaTime` takes no arguments and is safe to call from any thread. + let at = unsafe { CACurrentMediaTime() }; + match command.trim() { + "show" => pill.show(), + "hide" => pill.hide(), + "none" => pill.set_input(OverlayInput::None), + "all" => pill.set_input(OverlayInput::All), + "regions" => pill.set_input(OverlayInput::Regions), + "hit-only" => pill.update(|s, _| s.hit_only = true), + "chips" => pill.update(|s, _| s.hit_only = false), + "status" => {}, + "quit" => app.quit(), + _ => { writeln!(stream, "unknown command").ok(); continue; } + } + let line = format!("probe command={} time={at:.9} window={:?}", command.trim(), pill.window_number()); + eprintln!("{line}"); + writeln!(stream, "{line}").ok(); + } + }); +} +fn main() { + if std::env::var_os("OVERLAY_LAB_UNDERLAY").is_some() { + rune::run_windows(|displays| { + let mut state = init(); state.underlay = true; + let app = App::new(spec()).init(move || state); + if let Ok(seconds) = rune::env::var("OVERLAY_LAB_SECONDS").unwrap_or_default().parse::<u64>() { + let handle = app.handle(); + std::thread::spawn(move || { std::thread::sleep(std::time::Duration::from_secs(seconds)); handle.quit(); }); + } + let options = displays.iter().find(|d| d.primary).or_else(|| displays.first()).map(|display| rune::WindowOptions { + borderless: true, position: Some(display.position), physical_size: Some(display.size), ..Default::default() + }).unwrap_or_default(); + let options = if std::env::var_os("OVERLAY_LAB_NATIVE_WINDOW").is_some() { + options.macos(rune::MacWindowOptions::default().shadow(false).level(24) + .collection_behavior(1 | 16 | 64 | 256).exclude_from_capture(true)) + } else { options.into() }; + vec![WindowSpec::from_app("underlay", app).configured_options(options)] + }); + return; + } + rune::run_windows_with(RunOptions { accessory: true }, |displays| { + let exclude = std::env::var_os("OVERLAY_LAB_INCLUDE_IN_CAPTURE").is_none(); + let handles = Arc::new(Mutex::new(Handles::default())); + let mut app = App::new(spec()).windowless(); + for display in displays { + let mut state = init(); + state.picker = true; + state.handles = handles.clone(); + let target = display.id.clone().map_or(DisplayTarget::Primary, DisplayTarget::Id); + let picker = app.overlay(OverlaySpec::new("Rune picker", (680.0, 160.0), view).options(OverlayOptions { + display: target, placement: Some(OverlayPlacement::FullScreen), level: OverlayLevel::AboveStatus, + input: OverlayInput::All, exclude_from_capture: exclude, keys: KeyPolicy::OnDemand, prewarm: true, ..Default::default() + }).on_key(key).on_created(|created| eprintln!("overlay-lab picker created {created:?}")), state); + handles.lock().unwrap().pickers.push(picker); + } + let mut state = init(); + state.handles = handles.clone(); + let pill = app.overlay(OverlaySpec { margin: 40.0, ..OverlaySpec::new("Rune pill", (680.0, 160.0), view) }.options(OverlayOptions { + display: DisplayTarget::UnderPointer, follow_pointer: true, + input: OverlayInput::Regions, exclude_from_capture: exclude, level: OverlayLevel::AboveOverlays, prewarm: true, ..Default::default() + }).on_created(|created| eprintln!("overlay-lab pill created {created:?}")), state); + handles.lock().unwrap().pill = Some(pill.clone()); + #[cfg(target_os = "macos")] + native_probe(pill.clone(), app.handle()); + if !cfg!(target_os = "macos") || std::env::var_os("OVERLAY_LAB_CONTROL").is_none() { pill.show(); } + if std::env::var_os("OVERLAY_LAB_PICKER").is_some() { + let mut state = init(); state.handles = handles; show_picker(&mut state); + } + if let Ok(seconds) = rune::env::var("OVERLAY_LAB_SECONDS").unwrap_or_default().parse::<u64>() { + let app_handle = app.handle(); + std::thread::spawn(move || { + std::thread::sleep(std::time::Duration::from_millis(750)); + eprintln!("overlay-lab window={:?} capture={:?}", pill.window_number(), pill.capture_exclusion()); + std::thread::sleep(std::time::Duration::from_secs(seconds)); + app_handle.quit(); + }); + } + vec![WindowSpec::from_app("lab", app).options(rune::WindowOptions { transparent: true, ..Default::default() })] + }); +} diff --git a/app/vendor/rune/examples/overlay-lab/window-panel.md b/app/vendor/rune/examples/overlay-lab/window-panel.md new file mode 100644 index 0000000..9fee6ca --- /dev/null +++ b/app/vendor/rune/examples/overlay-lab/window-panel.md @@ -0,0 +1,103 @@ +# Ordinary quick panels + +## Cached launcher panels + +Launcher-style apps can use a retained quick panel: + +```rust,ignore +WindowSpec::from_app("quick", App::new(spec).keep_running()) + .configured_options(WindowOptions::launcher_panel()) + .on_focus(|_, focused, tx| { if !focused { tx.close_window(); } }) + .on_ready(|window| { + // Hidden, with a completed cached frame. Register your shortcut here. + assert!(window.is_ready()); + }) +``` + +For a single-window app, use `App::configured_options(WindowOptions::launcher_panel())`. +Keep using accessory launch policy as described below. The preset is initially hidden, +borderless, transparent and non-resizable, with no inherited minimum size. AppSpec sets its +size. On macOS it prepares even with `App::windowless()`. `on_created` still means native +creation; `on_ready` means the first surface frame completed on the GPU, not merely submission. +Both callbacks run on the event thread. Readiness is per native lifetime, not a freshness +guarantee for later state updates. Headless rendering does not invoke native callbacks. + +`WindowHandle::set_visible(true)`/`show()` and `AppHandle::show()`/`open()` reveal cached +pixels and take keys without app activation. A show before readiness waits behind the +first-frame fence; hide cancels that pending show. Hide leaves the panel ordered in at +alpha zero, ignores mouse input, and returns keys through AppKit. It retains the surface +even when `release_gpu_when_closed()` is set. Use `keep_running()` if closing should hide +rather than end this host. Ordinary non-launcher windows keep their existing show semantics. + +The reveal itself does no settling, layout, surface configuration or drawable acquisition. +Queued state updates, focus handlers and later input can draw fresh frames normally. +Hidden updates, and `poll` changes after `AppHandle::wake()`, render at alpha zero: the first +after a quiet spell at once, later ones at most every 250 ms; hidden animations do not drive a +continuous loop. A shown launcher redraws on every wake. A show whose state changed since the +cached frame (an `update()` in the same turn, or one still waiting for that pace) first renders +one fenced hidden frame, so it never reveals stale pixels. That frame commits the new state +without settling it: content is fresh on reveal and the update's motion runs on from there. +First preparation retries unavailable drawables for at most two seconds, then reports through +`AppHandle::window_error()` and remains hidden; a later show retries preparation. A late +successful frame still completes readiness. Other platforms use an ordinary hidden +window; their `on_ready` fires after the first shown frame completes on the GPU. + +The implementation ports the spike's retained reveal and uses a GPU fence for hidden preparation +(a never-shown alpha-zero layer need not emit a positive `presentedTime`). Existing spike +measurements (cached alpha 7.9/12.7 ms; native 6.2/15.8 ms) describe that experiment, not a new +benchmark of this API. `WINDOW_PANEL_LAUNCHER=1` selects the launcher in the native fixture; +its `visible`/`invisible` commands exercise WindowHandle directly. + +## Ordinary panels and focus + +`AppSpec`, `WindowSpec`, `WindowOptions` and `OverlaySpec` literals retain their fields. +Configure focus callbacks on `App::on_focus`, `WindowSpec::on_focus`, or +`ConfiguredOverlay::on_focus`. Each callback takes `fn(&mut S, bool, &mut Tx)`. +Repeated focus notifications are deduplicated per runtime. Callbacks run on the event +thread even when the window is hidden/occluded, before requiring a drawable. +`Tx::close_window()` dismisses a keep-running ordinary window or hides an overlay. + +```rust,ignore +let quick = App::new(spec).windowless().on_focus(|_, focused, tx| { + if !focused { tx.close_window(); } +}); +let handle = quick.handle(); +let window = WindowSpec::from_app("quick", quick).configured_options( + WindowOptions { borderless: true, ..Default::default() } + .macos(MacWindowOptions::default().nonactivating_panel(true)) +); +// From a shortcut callback on any thread: +handle.place(DisplayTarget::UnderPointer, OverlayPlacement::Edge { + edge: ScreenEdge::Top, margin: 160.0, align: Align::Center, inset: 0.0, +}); +handle.open(); +``` + +The macOS panel takes keys without activating its application. `show()` does not take +keys; `open()`/`focus()` do. Hiding lets AppKit return keys to the prior application. +For a single-window app use `App::macos_window(...)`. Use `App::accessory()` or +`run_windows_with(RunOptions { accessory: true }, ...)` to prevent launch activation too. +Panel policy is ignored on other platforms; poll, scenes, on_key and headless tooling +remain ordinary-window features. + +Both AppHandle and WindowHandle have `place(display, placement)`. UnderPointer samples +at the calling thread, not after a delayed event-loop wake. Placement is retained across +recreation and re-resolved on open and scale changes; disconnected display IDs fall back +to primary. Rect and FullScreen resize as well as place; Edge uses the current window size. +Coordinates are display-local points, as for overlays. Wayland ignores placement requests. +`set_position` replaces a pending/retained display placement, and vice versa. + +Headless runs resolve `AppHandle::place` against displays a `--script` object declares, +`{"displays":[{"id":1,"frame":[0,0,1512,982],"scale":2,"primary":true}],"pointer":[800,400],"events":[]}` +(frames and pointer in global points; ids match `DisplayTarget::Native`). Without them there is +one 1920x1080-pixel primary display, which `run_windows` factories also receive. Each +placement prints `rune-placed {"t":…,"display":1,"frame":[x,y,w,h]}` and the latest one +appears as `"placed"` in `--tree`. The headless viewport keeps its size. + +Headless scripts accept `{"t": 0.1, "focus": false}` (time defaults to zero), delivering +the same app callback as native input. Existing root `El::on_window_focus` callbacks also +receive the queued focus event when Runtime next advances. + +`cargo run -p rune --example window-panel --release` supplies two independent windows with +the same state type. `WINDOW_PANEL_SOCKET` enables the fixture's open/focus/hide/status/quit +commands. `native/run-window-panel-probe.py` holds the GUI test host's lock for a bounded Cua proof. diff --git a/app/vendor/rune/examples/overlay/Cargo.toml b/app/vendor/rune/examples/overlay/Cargo.toml new file mode 100644 index 0000000..1b2eae8 --- /dev/null +++ b/app/vendor/rune/examples/overlay/Cargo.toml @@ -0,0 +1,11 @@ +[package] +name = "overlay" +version = "0.0.1" +edition.workspace = true +license.workspace = true + +[dependencies] +rune = { workspace = true, default-features = true, features = ["keys-overlay"] } + +[lints] +workspace = true diff --git a/app/vendor/rune/examples/overlay/README.md b/app/vendor/rune/examples/overlay/README.md new file mode 100644 index 0000000..5a62daa --- /dev/null +++ b/app/vendor/rune/examples/overlay/README.md @@ -0,0 +1,71 @@ +# Display overlays + +One normal control window and one transparent, borderless, always-on-top overlay +per display. The overlays pass clicks through by default. “Test overlay input” +enables hit-testing; clicking any overlay restores click-through on all of them. +This keeps the normal control window reachable. Each overlay draws a stroke and shares one +background-driven `Live<[f32; 2]>` remote cursor. Updates stop after four seconds. + +```rust +rune::run_windows(|displays| { + displays.iter().enumerate().map(|(i, display)| { + rune::WindowSpec::new(format!("overlay-{i}"), app_spec()) + .options(rune::WindowOptions::overlay(display)) + .on_created(|window| { + // CGWindowID on macOS; retain these for ScreenCaptureKit exclusions. + let number = window.window_number(); + // window.set_click_through(false)?; + }) + }).collect() +}); +``` + +`WindowSpec::state(state)` supplies distinct initial state while sharing services +or Live handles. The factory runs once after monitor enumeration. Display origins +and `WindowOptions::position/physical_size` are physical pixels, including negative +origins; `AppSpec::size` and view layout use logical points. + +Use `WindowSpec::from_app(key, App::new(spec).keep_running())` when a window must +retain its state after closing. The App's handle opens/activates/updates that window; +`WindowHandle::open` can also reopen a retained host. Default hosts are removed on +close, and the last host ends the loop. Any `AppHandle::quit` or `Tx::quit` quits the +whole loop. The outer tooling arguments apply to all specs; `App::args` is ignored +inside `run_windows`. `App::accessory` is a process launch option for `App::run`, +not a per-window option; `run_windows` starts with regular activation policy. +Use `run_windows_with_args(RunOptions { accessory: true }, [], factory)` +for a menu-bar app whose command-line flags belong to its host, not Rune. +An AppHandle's `set_dock_icon` still changes the whole process at runtime. + +```sh +cargo build --release -p overlay +target/release/overlay --list-windows +target/release/overlay --window controls --snap controls.png +target/release/overlay --window overlay-0 --snap overlay.png --at 2 +target/release/overlay --window overlay-0 --trace overlay.jsonl --frames 720 --fps 120 +``` + +Headless tools select one window by its stable key and use one virtual display +(1920×1080 physical pixels, 2× scale by default). They create no native windows; +`on_created` does not run. `--size` and `--scale` override the selected capture. +Overlay PNGs retain transparency. A stroke is an SVG icon rasterized by Rune; +an interactive drawing editor is outside this example. + +## Native boundaries + +Windowed paths are compile-checked, not exercised on a desktop. Window-manager support +for transparency, topmost placement and click-through varies. Monitor placement +is a startup snapshot; hot-plug reconciliation is the app's next integration step. +The native window-number accessor supplies the macOS CGWindowID that a host app can +match to `SCWindow` for `SCContentFilter`; ScreenCaptureKit itself stays in the host app. +It can initially be `None` until AppKit registers the window; retain the handle +and query again. The native reference refreshes if a retained host is recreated. +Borrow raw-window-handles only through the handle's callback while the native +window is alive, on a platform-appropriate thread. + +These are winit windows, not non-activating `NSPanel`s. Non-activating panels, +all-Spaces/fullscreen-space behavior and a status item still require Rune's own +Mac shell. This example does not implement them. + +All windows share a GPU device. Unsupported transparency uses opaque rendering +with a diagnostic, and unsupported click-through reports the platform error. +Metal surfaces stay premultiplied for Core Animation; PNG exports are straight alpha. diff --git a/app/vendor/rune/examples/overlay/src/main.rs b/app/vendor/rune/examples/overlay/src/main.rs new file mode 100644 index 0000000..0e3087b --- /dev/null +++ b/app/vendor/rune/examples/overlay/src/main.rs @@ -0,0 +1,90 @@ +#![forbid(unsafe_code)] + +use std::sync::{Arc, Mutex, atomic::{AtomicBool, Ordering}}; +use rune::{AppSpec, Color, Cx, El, Icon, Live, Tx, WindowHandle, WindowOptions, WindowSpec, col, el, icon, text}; + +static WINDOWED: AtomicBool = AtomicBool::new(false); +static STROKE: Icon = Icon { + name: "shared-stroke", view: 240.0, + body: r#"<path d="M 12 190 C 55 30 90 210 130 70 S 190 170 228 35" fill="none" stroke="currentColor" stroke-width="4" stroke-linecap="round"/>"#, +}; +struct State { + overlay: bool, + cursor: Live<[f32; 2]>, + overlays: Arc<Mutex<Vec<WindowHandle>>>, +} +impl Drop for State { + fn drop(&mut self) { + if !self.overlay { + for window in self.overlays.lock().unwrap().iter() { window.close(); } + } + } +} +fn init() -> State { + State { overlay: false, cursor: Live::new([120.0, 90.0]), overlays: Arc::new(Mutex::new(Vec::new())) } +} +fn view(s: &State, _: &mut Cx<State>) -> El { + let green = Color { r: 0.1, g: 0.85, b: 0.45, a: 1.0 }; + if s.overlay { + return el().w_full().h_full().child(icon(&STROKE, 240.0).key("stroke").color(green) + .pin(Some(80.0), Some(80.0), None, None)) + .child(el().key("remote-cursor").size(12.0, 18.0).radius(3.0).fill(green) + .pin(Some(0.0), Some(0.0), None, None).live_offset(&s.cursor)) + .on_press(|s: &mut State| { + for window in s.overlays.lock().unwrap().iter() { window.set_click_through(true).ok(); } + }); + } + col().w_full().h_full().padding(40.0).gap(20.0) + .fill(Color { r: 0.018, g: 0.024, b: 0.03, a: 1.0 }) + .child(text("Display overlays").font(rune::tok::type_::BODY)) + .child(el().padding(16.0).radius(8.0).fill(green.alpha(0.15)) + .child(text("Test overlay input")) + .on_press(|s: &mut State| { + for window in s.overlays.lock().unwrap().iter() { + if let Err(e) = window.set_click_through(false) { eprintln!("click-through: {e}"); } + } + })) +} +fn point(t: f64) -> [f32; 2] { + let t = t.min(4.0) as f32; + [120.0 + 120.0 * (t * 0.7).sin(), 90.0 + 50.0 * t.sin()] +} +fn poll(s: &mut State, t: f64, _: &mut Tx) -> bool { + if !WINDOWED.load(Ordering::Relaxed) { s.cursor.set(point(t)); } + false +} +fn setup(s: &mut State, _: rune::Waker) { + if !WINDOWED.load(Ordering::Relaxed) || s.overlay { return; } + let cursor = s.cursor.clone(); + std::thread::spawn(move || { + let start = rune::time::now(); + for tick in 1..=480 { + let t = tick as f64 / 120.0; + std::thread::sleep((start + std::time::Duration::from_secs_f64(t)).saturating_duration_since(rune::time::now())); + cursor.set(point(t)); + } + }); +} +fn spec() -> AppSpec<State> { + AppSpec { setup: Some(setup), poll: Some(poll), ..AppSpec::new("Rooms overlay example", (560.0, 440.0), init, view) } +} +fn main() { + WINDOWED.store(!std::env::args().any(|a| matches!(a.as_str(), "--snap" | "--trace" | "--tree" | "--frames" | "--strip" | "--first-pixels" | "--list-scenes" | "--list-windows")), Ordering::Relaxed); + rune::run_windows(|displays| { + let controls = init(); + let cursor = controls.cursor.clone(); + let overlays = controls.overlays.clone(); + let mut windows = vec![WindowSpec::new("controls", spec()).state(controls)]; + for (i, display) in displays.iter().enumerate() { + let state = State { overlay: true, cursor: cursor.clone(), overlays: overlays.clone() }; + let handles = overlays.clone(); + windows.push(WindowSpec::new(format!("overlay-{i}"), spec()).state(state) + .options(WindowOptions::overlay(display)).on_created(move |window| { + // ScreenCaptureKit: exclude this CGWindowID using SCContentFilter. + eprintln!("overlay native window number: {:?}", window.window_number()); + handles.lock().unwrap().push(window); + })); + } + windows + }); +} diff --git a/app/vendor/rune/examples/playground/Cargo.toml b/app/vendor/rune/examples/playground/Cargo.toml new file mode 100644 index 0000000..385d823 --- /dev/null +++ b/app/vendor/rune/examples/playground/Cargo.toml @@ -0,0 +1,11 @@ +[package] +name = "playground" +version = "0.0.1" +edition.workspace = true +license.workspace = true + +[dependencies] +rune = { workspace = true, default-features = true, features = ["keys-overlay"] } + +[lints] +workspace = true diff --git a/app/vendor/rune/examples/playground/src/main.rs b/app/vendor/rune/examples/playground/src/main.rs new file mode 100644 index 0000000..c3e884d --- /dev/null +++ b/app/vendor/rune/examples/playground/src/main.rs @@ -0,0 +1,293 @@ +//! A small preferences window with a playground (⌘⇧D): its scenes, a live page, a story with its +//! own state and timer, and an overlay, grouped by type, with triggers, variants (1–9) and a +//! side-column control. "Controls" nests groups inside it by path ("Controls/Switches/Toggle") +//! and comes first in the list. Every group starts folded but the open story's, and a click on +//! a group's header folds or unfolds it; / filters the list. "Every device" scrolls its stage, +//! and "Windows/Preferences" fills it edge to edge. +//! +//! `cargo run -p playground` shows the bar along the bottom; `-- --playground "Upload"` opens +//! the playground at that story, and `-- --snap out.png --playground` renders it headless; +//! `--variant "Long names"` beside `--playground "Many devices"` picks a variant. + +#![forbid(unsafe_code)] + +use std::time::Duration; + +use rune::tok::{self, Theme, motion, radius, type_}; +use rune::{Align, App, AppSpec, Color, Cx, El, OverlaySpec, Play, Playground, ScreenEdge, Stage, Story, Tx, col, el, row, text}; + +#[derive(Clone, Copy, PartialEq, Eq)] +enum Section { + General, + Sync, + Devices, +} + +const SECTIONS: [(Section, &str); 3] = [(Section::General, "General"), (Section::Sync, "Sync"), (Section::Devices, "Devices")]; + +struct Prefs { + section: Section, + launch_at_login: bool, + sounds: bool, + sync: bool, + wifi_only: bool, + devices: Vec<&'static str>, +} + +fn init() -> Prefs { + Prefs { section: Section::General, launch_at_login: true, sounds: false, sync: true, wifi_only: true, devices: vec!["Studio desk", "Travel laptop"] } +} + +static SCENES: &[(&str, fn(&mut Prefs))] = &[ + ("Sections/General", |s| s.section = Section::General), + ("Sections/Sync paused", |s| { s.section = Section::Sync; s.sync = false; }), + ("Lists/Many devices", |s| { + s.section = Section::Devices; + s.devices.extend(["Kitchen tablet", "Spare phone", "Lab machine", "Old desktop"]); + }), +]; + +fn view(s: &Prefs, cx: &mut Cx<Prefs>) -> El { + let t = tok::theme(cx.system_dark()); + let accent = tok::accent(0, cx.system_dark()); + let nav = col().key("nav").w(176.0).h_full().pt(if cx.titlebar_inset() > 0.0 { 44.0 } else { 12.0 }).px(8.0).gap(2.0) + .children(SECTIONS.iter().map(|&(section, name)| { + let on = s.section == section; + row().key(name).w_full().h(28.0).px(10.0).center_y().radius(radius::SM) + .fill(if on { t.control_track } else { Color::TRANSPARENT }) + .hover(if on { t.control_track } else { t.hover }) + .child(text(name).font(type_::BODY).color(t.text)) + .role("tab").label(name) + .on_press(move |s: &mut Prefs| s.section = section) + })); + let body = match s.section { + Section::General => col().gap(8.0) + .child(switch_row(t, accent, "launch", "Open at login", s.launch_at_login, |s| s.launch_at_login = !s.launch_at_login)) + .child(switch_row(t, accent, "sounds", "Play sounds", s.sounds, |s| s.sounds = !s.sounds)), + Section::Sync => col().gap(8.0) + .child(switch_row(t, accent, "sync", "Sync across devices", s.sync, |s| s.sync = !s.sync)) + .child(switch_row(t, accent, "wifi", "Only on Wi-Fi", s.wifi_only && s.sync, |s| s.wifi_only = !s.wifi_only).opacity(if s.sync { 1.0 } else { 0.5 })) + .children((!s.sync).then(|| text("Changes stay on this device until sync is back on.").font(type_::BODY).color(t.text_secondary).px(4.0))), + Section::Devices => devices(s, cx), + }; + let title = SECTIONS.iter().find(|(section, _)| *section == s.section).map_or("", |(_, name)| name); + row().w_full().h_full().fill(t.bg) + .child(nav) + .child(el().w(1.0).h_full().fill(t.separator)) + .child(col().key("content").grow(1.0).h_full().padding(24.0).gap(16.0) + .child(text(title).font(type_::TITLE).color(t.text)) + .child(body)) +} + +/// The playground's live devices page: the list, drawn from the real state. +fn devices_page(s: &Prefs, cx: &mut Cx<Prefs>) -> El { + col().w_full().h_full().padding(24.0).child(devices(s, cx)) +} + +/// The "Every device" story: more devices than the stage is tall, on a scrolling stage. +fn every_device() -> Prefs { + Prefs { devices: EVERY_DEVICE.to_vec(), ..init() } +} + +const EVERY_DEVICE: [&str; 24] = [ + "Studio desk", "Travel laptop", "Kitchen tablet", "Spare phone", "Lab machine", "Old desktop", + "Living room TV", "Garage Pi", "Work phone", "Reading tablet", "Build server", "Test phone", + "Backup drive", "Guest laptop", "Car display", "Watch", "Office printer", "Media box", + "Shared iPad", "Loaner laptop", "Render node", "Home server", "Second monitor hub", "Field kit", +]; + +fn devices(s: &Prefs, cx: &mut Cx<Prefs>) -> El { + let t = tok::theme(cx.system_dark()); + col().key("devices").w_full().radius(radius::MD).fill(t.card).outline(1.0, 0.0, t.card_border) + .children(s.devices.iter().enumerate().map(|(i, name)| { + let line = (i > 0).then(|| el().w_full().h(1.0).fill(t.separator)); + col().key(format!("device-{i}")).w_full() + .children(line) + .child(row().w_full().h(36.0).px(12.0).center_y().justify_between() + .child(text(*name).font(type_::BODY).color(t.text)) + .child(text(if i == 0 { "This device" } else { "Synced" }).font(type_::LABEL).color(t.text_secondary))) + })) +} + +fn switch_row(t: Theme, accent: Color, key: &str, label: &'static str, on: bool, flip: fn(&mut Prefs)) -> El { + switch(t, accent, key, label, on, flip) +} + +/// A labelled switch on any state, `flip` turning it. +fn switch<S: 'static>(t: Theme, accent: Color, key: &str, label: &'static str, on: bool, flip: fn(&mut S)) -> El { + let (w, h, k) = (34.0, 20.0, 16.0); + let knob = el().size(k, k).absolute(if on { w - k - 2.0 } else { 2.0 }, 2.0).radius(k / 2.0).fill(t.knob).shadow(1.0, 3.0, t.knob_shadow); + row().key(key.to_owned()).w_full().h(44.0).px(12.0).center_y().justify_between() + .radius(radius::MD).fill(t.card).outline(1.0, 0.0, t.card_border) + .child(text(label).font(type_::BODY).color(t.text)) + .child(el().size(w, h).radius(h / 2.0).fill(if on { accent } else { t.control_off }).motion(motion::SNAPPY).child(knob)) + .role("switch").label(label) + .on_press(move |s: &mut S| flip(s)) +} + +/// The "Controls/Switches" stories' own state: one switch. +struct Switch { + on: bool, + dimmed: bool, + label: &'static str, +} + +fn switch_story(s: &Switch, cx: &mut Cx<Switch>) -> El { + let t = tok::theme(cx.system_dark()); + let accent = tok::accent(0, cx.system_dark()); + col().w_full().h_full().center().child( + col().w(300.0).child(switch(t, accent, "switch", s.label, s.on, |s: &mut Switch| s.on = !s.on).opacity(if s.dimmed { 0.5 } else { 1.0 })), + ) +} + +/// The "Controls/Rows" stories: the devices list on its own. +fn device_rows(devices: &'static [&'static str]) -> impl Fn() -> Prefs { + move || Prefs { devices: devices.to_vec(), ..init() } +} + +/// The "Upload" story's own state: a pretend upload ticking along on a timer. +struct Upload { + progress: u32, + running: bool, + last: f64, +} + +fn upload_init() -> Upload { + Upload { progress: 0, running: false, last: 0.0 } +} + +/// One step every 0.1 s while running: `wake_after` asks for the next frame, whose poll steps. +fn upload_poll(u: &mut Upload, t: f64, tx: &mut Tx) -> bool { + if !u.running { return false; } + tx.wake_after(Duration::from_millis(100)); + if t - u.last < 0.1 { return false; } + u.last = t; + u.progress = (u.progress + 4).min(100); + u.running = u.progress < 100; + true +} + +fn upload_view(u: &Upload, cx: &mut Cx<Upload>) -> El { + let t = tok::theme(cx.system_dark()); + let accent = tok::accent(0, cx.system_dark()); + let label = match (u.running, u.progress) { + (true, _) => "Pause", + (false, 100) => "Again", + (false, 0) => "Start", + (false, _) => "Resume", + }; + let track = 240.0; + col().w_full().h_full().center().gap(12.0) + .child(text(format!("Uploading backup · {}%", u.progress)).font(type_::BODY).color(t.text)) + .child(el().w(track).h(6.0).radius(3.0).fill(t.control_track) + .child(el().w(track * u.progress as f32 / 100.0).h(6.0).radius(3.0).fill(accent).motion(motion::SNAPPY))) + .child(row().key("upload-toggle").h(28.0).px(14.0).center().radius(radius::SM).fill(t.control_track).hover(t.hover) + .child(text(label).font(type_::LABEL).color(t.text)) + .role("button").label(label) + .on_press_tx(|u: &mut Upload, tx: &mut Tx| { + if u.progress == 100 { u.progress = 0; } + u.running = !u.running; + tx.wake_after(Duration::ZERO); + })) +} + +/// The toast an app shows over the desktop when a sync finishes, previewed as a story. +struct Toast { + message: &'static str, + failed: bool, +} + +fn toast_view(s: &Toast, cx: &mut Cx<Toast>) -> El { + let t = tok::theme(cx.system_dark()); + el().w_full().h_full().center() + .child(row().h(36.0).px(16.0).gap(8.0).center_y().radius(18.0).fill(t.card).outline(1.0, 0.0, t.card_border).shadow(4.0, 16.0, t.shadow_soft) + .child(el().size(8.0, 8.0).radius(4.0).fill(tok::accent(if s.failed { 3 } else { 4 }, cx.system_dark()))) + .child(text(s.message).font(type_::BODY).color(t.text))) +} + +static TOAST: OverlaySpec<Toast> = OverlaySpec { + name: "Sync toast", + size: (320.0, 64.0), + edge: ScreenEdge::Top, + margin: 12.0, + align: Align::Center, + inset: 0.0, + interactive: false, + view: toast_view, +}; + +/// The "Many devices" scene's own control in the side column: how many devices it lists. +fn device_count(s: &Prefs, cx: &mut Cx<Prefs>) -> El { + let t = tok::theme(cx.system_dark()); + let step = |key: &str, label: &'static str, f: fn(&mut Prefs)| { + row().key(key.to_owned()).size(24.0, 24.0).center().radius(radius::SM).hover(t.hover).press(t.press) + .child(text(label).font(type_::BODY).color(t.text)) + .role("button").label(label) + .on_press(move |s: &mut Prefs| f(s)) + }; + row().key("device-count").w_full().h(36.0).pl(12.0).pr(6.0).gap(2.0).center_y().radius(radius::LG).fill(t.card).outline(1.0, 0.0, t.card_border) + .child(text("Devices").font(type_::BODY).color(t.text)) + .child(el().grow(1.0)) + .child(text(s.devices.len().to_string()).font(type_::BODY).color(t.text_secondary).pr(6.0)) + .child(step("fewer", "−", |s| { if s.devices.len() > 1 { s.devices.pop(); } })) + .child(step("more", "+", |s| s.devices.push("New device"))) +} + +/// R on the upload: start over, then pause part way and pick up again, on the logical clock. +fn upload_replay(u: &mut Upload, play: &mut Play<'_, Upload>) { + u.running = true; + play.wake_after(Duration::ZERO); + play.after(0.6, |u, _| u.running = false); + play.after(1.2, |u, play| { + u.running = true; + play.wake_after(Duration::ZERO); + }); +} + +fn main() { + let spec = AppSpec { scenes: SCENES, ..AppSpec::new("Preferences", (640.0, 420.0), init, view) }; + App::new(spec) + .playground( + Playground::<Prefs>::new() + .page("Lists/Live devices", devices_page) + .trigger("Lists/Many devices", 'a', "Add device", |s, _| s.devices.push("New device")) + .trigger("Lists/Many devices", 'x', "Remove the last", |s, _| { s.devices.pop(); }) + .side("Lists/Many devices", device_count) + .variant("Lists/Many devices", "Six", |_| {}) + .variant("Lists/Many devices", "Just this one", |s| s.devices.truncate(1)) + .variant("Lists/Many devices", "Long names", |s| { + s.devices = vec!["Studio desk in the back office", "Travel laptop (borrowed for the conference)", "Kitchen tablet"]; + }) + .story(Story::new("Lists/Every device", every_device, devices).stage(Stage::Scroll)) + .story(Story::new("Windows/Preferences", init, view).stage(Stage::Fill)) + .story( + Story::new("Progress/Upload", upload_init, upload_view) + .poll(upload_poll) + .trigger('r', "Run, pause, resume", upload_replay) + .trigger('f', "Finish", |u, _| { u.progress = 100; u.running = false; }) + .variant("From the start", |_| {}) + .variant("Half done", |u| u.progress = 48), + ) + .story( + Story::overlay("Toasts/Sync toast", &TOAST, || Toast { message: "Synced 3 devices", failed: false }) + .trigger('e', "Fail", |s, _| { s.message = "Sync failed, retrying"; s.failed = true; }) + .variant("Synced", |_| {}) + .variant("Failed", |s| { s.message = "Sync failed, retrying"; s.failed = true; }), + ) + .story( + Story::new("Controls/Switches/Toggle", || Switch { on: true, dimmed: false, label: "Sync across devices" }, switch_story) + .trigger('t', "Flip", |s, _| s.on = !s.on) + .variant("On", |_| {}) + .variant("Off", |s| s.on = false) + .variant("Dimmed", |s| s.dimmed = true), + ) + .story(Story::new("Controls/Switches/Long label", || Switch { on: false, dimmed: false, label: "Only sync over Wi-Fi when on battery" }, switch_story)) + .story(Story::new("Controls/Rows/Two devices", device_rows(&["Studio desk", "Travel laptop"]), devices)) + .story(Story::new("Controls/Rows/One device", device_rows(&["Studio desk"]), devices)) + .story(Story::new("Controls/Rows/Long names", device_rows(&["Studio desk in the back office", "Travel laptop (borrowed for the conference)"]), devices)) + .group_order(&["Controls"]) + .start_folded(true) + .sizes(&[("Compact", (420.0, 300.0)), ("Wide", (900.0, 560.0))]), + ) + .run(); +} diff --git a/app/vendor/rune/examples/rich-clipboard/Cargo.toml b/app/vendor/rune/examples/rich-clipboard/Cargo.toml new file mode 100644 index 0000000..c790f0e --- /dev/null +++ b/app/vendor/rune/examples/rich-clipboard/Cargo.toml @@ -0,0 +1,11 @@ +[package] +name = "rich-clipboard" +version = "0.0.1" +edition.workspace = true +license.workspace = true + +[dependencies] +rune = { workspace = true, default-features = true, features = ["keys-overlay"] } + +[lints] +workspace = true diff --git a/app/vendor/rune/examples/rich-clipboard/src/main.rs b/app/vendor/rune/examples/rich-clipboard/src/main.rs new file mode 100644 index 0000000..bb05315 --- /dev/null +++ b/app/vendor/rune/examples/rich-clipboard/src/main.rs @@ -0,0 +1,95 @@ +//! Copy and paste formatted text. `cargo run -p rich-clipboard`. +//! +//! Paste into the field from a browser, Notes, TextEdit or Pages: the field still pastes the +//! plain text, and the panel below shows which forms arrived and the start of the sanitised +//! HTML (on macOS, RTF-only sources arrive converted to HTML). Each paste also prints its +//! HTML. "Copy formatted" puts plain text, HTML and RTF on the clipboard: paste it into +//! TextEdit or Mail and it keeps its bold and italic. "Read clipboard" looks without pasting. + +#![forbid(unsafe_code)] + +use rune::tok::{self, radius, space, type_}; +use rune::{AppSpec, ClipboardContent, Cx, El, TextEdit, Tx, col, row, text, text_input}; + +#[derive(Default)] +struct State { + field: TextEdit, + /// How the last paste or read arrived, and what it held. + last: Option<(&'static str, ClipboardContent)>, +} + +fn sample() -> ClipboardContent { + ClipboardContent::new("Rune copies bold and italic text.") + .with_html("Rune copies <b>bold</b> and <i>italic</i> text.") + .with_rtf(r"{\rtf1\ansi{\fonttbl\f0\fswiss Helvetica;}\f0 Rune copies {\b bold} and {\i italic} text.}") +} + +fn seen(s: &mut State, how: &'static str, content: &ClipboardContent) { + println!("{how}: text {} bytes, html {:?} bytes, rtf {:?} bytes", content.text().len(), content.html().map(str::len), content.rtf().map(str::len)); + if let Some(html) = content.html() { println!("{html}"); } + s.last = Some((how, content.clone())); +} + +fn summary(last: &Option<(&'static str, ClipboardContent)>) -> (String, String) { + let Some((how, content)) = last else { return ("Paste formatted text into the field".into(), String::new()) }; + let form = |name: &str, len: Option<usize>| match len { Some(n) => format!("{name} {n} B"), None => format!("no {name}") }; + let head = format!("{how}: text {} B, {}, {}", content.text().len(), form("HTML", content.html().map(str::len)), form("RTF", content.rtf().map(str::len))); + let preview: String = content.html().unwrap_or("").chars().take(400).collect(); + (head, preview) +} + +fn button(key: &'static str, label: &str, f: impl Fn(&mut State, &mut Tx) + 'static) -> El { + let t = tok::theme(true); + row().key(key).role("button").padding(space::S2).radius(radius::MD).fill(t.card).border(1.0, t.card_border) + .child(text(label).font(type_::LABEL).color(t.text)) + .on_press_tx(f) +} + +fn view(s: &State, _: &mut Cx<State>) -> El { + let t = tok::theme(true); + let (head, preview) = summary(&s.last); + let field = text_input(&s.field, type_::BODY).key("field").w_full().min_h(80.0).padding(space::S2) + .radius(radius::MD).fill(t.card).border(1.0, t.card_border).color(t.text) + .on_edit(|s: &mut State| &mut s.field) + // Look at every form, then let the editor paste the text as usual. + .on_input_paste(|s: &mut State, content, _| { seen(s, "Pasted", content); false }); + col().w_full().h_full().padding(space::S6).gap(space::S3).fill(t.bg) + .child(field) + .child(row().gap(space::S2) + .child(button("copy", "Copy formatted", |_, tx| tx.copy_rich(sample()))) + .child(button("read", "Read clipboard", |_, tx| tx.read_clipboard(|s: &mut State, content, _| seen(s, "Read", content))))) + .child(text(head).key("summary").font(type_::BODY).color(t.text_secondary)) + .child(text(preview).key("preview").font(type_::LABEL).color(t.text_secondary).w_full()) +} + +fn main() { + rune::run(AppSpec::new("Rich Clipboard", (560.0, 420.0), State::default, view)); +} + +#[cfg(test)] +mod tests { + use super::*; + use rune::{Env, Runtime, clipboard}; + + #[test] + fn a_rich_paste_shows_its_forms_and_the_field_keeps_the_text() { + let board = clipboard::memory(); + let mut rt = Runtime::new(State::default(), view, (560.0, 420.0), Env::new(true, 2.0)); + rt.use_clipboard(&board); + rt.frame(0.0); + rt.update(|s, _| s.field.focused = true); + rt.frame(0.0); + board.set_content(ClipboardContent::new("Hi").with_html("<b>Hi</b><img src=x onerror=alert(1)>")); + rt.update(|_, tx| tx.request_paste()); + rt.frame(0.0); + assert_eq!(rt.state.field.text, "Hi"); + let (how, content) = rt.state.last.clone().unwrap(); + assert_eq!((how, content.html()), ("Pasted", Some(r#"<b>Hi</b><img src="x">"#))); + + let (x, y) = rt.find("copy").unwrap(); + rt.pointer_down(x, y); + rt.pointer_up(x, y); + rt.frame(0.0); + assert_eq!(board.content(), Some(sample())); + } +} diff --git a/app/vendor/rune/examples/settings/Cargo.toml b/app/vendor/rune/examples/settings/Cargo.toml new file mode 100644 index 0000000..c1a1e64 --- /dev/null +++ b/app/vendor/rune/examples/settings/Cargo.toml @@ -0,0 +1,16 @@ +[package] +name = "settings" +version = "0.0.1" +edition.workspace = true +license.workspace = true + +[features] +frame-profile = ["rune/frame-profile", "dep:procwatch"] +hot = ["rune/hot"] + +[dependencies] +procwatch = { workspace = true, optional = true } +rune = { workspace = true, default-features = true, features = ["keys-overlay"] } + +[lints] +workspace = true diff --git a/app/vendor/rune/examples/settings/scripts/accent.json b/app/vendor/rune/examples/settings/scripts/accent.json new file mode 100644 index 0000000..4126c8d --- /dev/null +++ b/app/vendor/rune/examples/settings/scripts/accent.json @@ -0,0 +1 @@ +{"events": [{"t": 0.1, "type": "tap", "key": "green"}]} diff --git a/app/vendor/rune/examples/settings/scripts/bench.json b/app/vendor/rune/examples/settings/scripts/bench.json new file mode 100644 index 0000000..24b5362 --- /dev/null +++ b/app/vendor/rune/examples/settings/scripts/bench.json @@ -0,0 +1,10 @@ +{"events": [ + {"t": 0.10, "type": "tap", "key": "Light", "hold": 0.03}, + {"t": 0.20, "type": "tap", "key": "login", "hold": 0.03}, + {"t": 0.30, "type": "tap", "key": "pink", "hold": 0.03}, + {"t": 0.40, "type": "drag", "key": "slider/knob", "dx": 50, "dur": 0.4}, + {"t": 1.00, "type": "tap", "key": "Dark", "hold": 0.03}, + {"t": 1.10, "type": "tap", "key": "sounds", "hold": 0.03}, + {"t": 1.20, "type": "tap", "key": "blue", "hold": 0.03}, + {"t": 1.30, "type": "tap", "key": "slider/track", "hold": 0.03} +]} diff --git a/app/vendor/rune/examples/settings/scripts/demo.json b/app/vendor/rune/examples/settings/scripts/demo.json new file mode 100644 index 0000000..9a6f33a --- /dev/null +++ b/app/vendor/rune/examples/settings/scripts/demo.json @@ -0,0 +1,4 @@ +{"events": [ + {"t": 0.10, "type": "tap", "key": "Dark", "hold": 0.03}, + {"t": 0.14, "type": "tap", "key": "sounds", "hold": 0.03} +]} diff --git a/app/vendor/rune/examples/settings/scripts/hover.json b/app/vendor/rune/examples/settings/scripts/hover.json new file mode 100644 index 0000000..0e86ca7 --- /dev/null +++ b/app/vendor/rune/examples/settings/scripts/hover.json @@ -0,0 +1 @@ +{"events": [{"t": 0.1, "type": "move", "key": "menubar"}, {"t": 0.5, "type": "down", "key": "menubar"}]} diff --git a/app/vendor/rune/examples/settings/scripts/keycaps.json b/app/vendor/rune/examples/settings/scripts/keycaps.json new file mode 100644 index 0000000..ae387c3 --- /dev/null +++ b/app/vendor/rune/examples/settings/scripts/keycaps.json @@ -0,0 +1,13 @@ +{"events": [ + {"t": 0.40, "type": "tap", "key": "Light"}, + {"t": 1.10, "type": "tap", "key": "pink"}, + {"t": 1.80, "type": "type", "text": "hello rune", "every": 0.07}, + {"t": 3.00, "type": "key", "name": "Tab"}, + {"t": 3.20, "type": "key", "name": "Tab"}, + {"t": 3.40, "type": "key", "name": "Tab"}, + {"t": 3.90, "type": "key", "cmd": true, "name": "k"}, + {"t": 4.30, "type": "tap", "key": "sounds"}, + {"t": 4.90, "type": "drag", "key": "slider/knob", "dx": 60, "dur": 0.5}, + {"t": 5.80, "type": "tap", "key": "Dark"}, + {"t": 7.20, "type": "mark", "name": "end"} +]} diff --git a/app/vendor/rune/examples/settings/scripts/segmented-light.json b/app/vendor/rune/examples/settings/scripts/segmented-light.json new file mode 100644 index 0000000..5af1148 --- /dev/null +++ b/app/vendor/rune/examples/settings/scripts/segmented-light.json @@ -0,0 +1 @@ +{"events": [{"t": 0.1, "type": "tap", "key": "Light"}]} diff --git a/app/vendor/rune/examples/settings/scripts/segmented-retarget.json b/app/vendor/rune/examples/settings/scripts/segmented-retarget.json new file mode 100644 index 0000000..fda7ee3 --- /dev/null +++ b/app/vendor/rune/examples/settings/scripts/segmented-retarget.json @@ -0,0 +1,4 @@ +{"events": [ + {"t": 0.1, "type": "tap", "key": "Light", "hold": 0.03}, + {"t": 0.22, "type": "tap", "key": "Dark", "hold": 0.03} +]} diff --git a/app/vendor/rune/examples/settings/scripts/slider.json b/app/vendor/rune/examples/settings/scripts/slider.json new file mode 100644 index 0000000..fb06b94 --- /dev/null +++ b/app/vendor/rune/examples/settings/scripts/slider.json @@ -0,0 +1,4 @@ +{"events": [ + {"t": 0.1, "type": "drag", "key": "slider/knob", "dx": -60, "dur": 0.3}, + {"t": 0.8, "type": "tap", "key": "slider/track"} +]} diff --git a/app/vendor/rune/examples/settings/scripts/toggle-retarget.json b/app/vendor/rune/examples/settings/scripts/toggle-retarget.json new file mode 100644 index 0000000..8f11c00 --- /dev/null +++ b/app/vendor/rune/examples/settings/scripts/toggle-retarget.json @@ -0,0 +1,4 @@ +{"events": [ + {"t": 0.1, "type": "tap", "key": "login", "hold": 0.03}, + {"t": 0.2, "type": "tap", "key": "login", "hold": 0.03} +]} diff --git a/app/vendor/rune/examples/settings/scripts/toggle.json b/app/vendor/rune/examples/settings/scripts/toggle.json new file mode 100644 index 0000000..29dae62 --- /dev/null +++ b/app/vendor/rune/examples/settings/scripts/toggle.json @@ -0,0 +1 @@ +{"events": [{"t": 0.1, "type": "tap", "key": "sounds"}]} diff --git a/app/vendor/rune/examples/settings/src/main.rs b/app/vendor/rune/examples/settings/src/main.rs new file mode 100644 index 0000000..025d1ee --- /dev/null +++ b/app/vendor/rune/examples/settings/src/main.rs @@ -0,0 +1,377 @@ +//! A small Settings window rendered entirely by Rune. + +#![forbid(unsafe_code)] + +use rune::tok::{self, Theme, motion, radius, space, type_}; +#[cfg(feature = "frame-profile")] +#[global_allocator] +static ALLOC: procwatch::alloc::Counting = procwatch::alloc::Counting::system(); +use rune::{Align, AppSpec, Color, Cx, Drag, El, Phase, Spring, col, el, row, text}; + +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +enum Appearance { + Auto, + Light, + Dark, +} + +struct Settings { + appearance: Appearance, + accent: usize, + launch_at_login: bool, + menu_bar: bool, + sounds: bool, + /// Slider position 0..1; animation speed is 2^(2v − 1), so the middle is 1×. + speed: f32, + reduce_motion: bool, +} + +impl Default for Settings { + fn default() -> Self { + Settings { + appearance: Appearance::Auto, + accent: 0, + launch_at_login: true, + menu_bar: true, + sounds: false, + speed: 0.5, + reduce_motion: false, + } + } +} + +fn speed_of(v: f32) -> f32 { + 2f32.powf(v * 2.0 - 1.0) +} + +#[test] +fn cancelling_the_speed_slider_restores_its_value_before_a_track_press() { + let mut rt = rune::Runtime::new(Settings::default(), view, (620.0, 520.0), rune::Env::new(true, 1.0)); + rt.frame(0.0); + let (x, y) = rt.find("slider").unwrap(); + rt.pointer_down(x + 60.0, y); + rt.pointer_move(x + 70.0, y); + rt.frame(1.0 / 60.0); + assert!(rt.state.speed > 0.5); + rt.key(rune::KeyEvent { key: rune::Key::Escape, mods: rune::Mods::default() }); + rt.frame(1.0 / 60.0); + assert_eq!(rt.state.speed, 0.5); + rt.pointer_up(x + 70.0, y); + rt.frame(0.0); + assert_eq!(rt.state.speed, 0.5); +} + +/// Everything a component needs to paint itself. +#[derive(Clone, Copy)] +struct Paint { + t: Theme, + accent: Color, + hair: f32, +} + +fn view(s: &Settings, cx: &mut Cx<Settings>) -> El { + let dark = match s.appearance { + Appearance::Auto => cx.system_dark(), + Appearance::Light => false, + Appearance::Dark => true, + }; + cx.reduced_motion(s.reduce_motion); + cx.time_scale(speed_of(s.speed)); + let p = Paint { t: tok::theme(dark), accent: tok::accent(s.accent, dark), hair: 1.0 / cx.env().scale }; + let t = p.t; + + col() + .key("window") + .role("window") + .fill(t.bg) + .child( + row() + .key("titlebar") + .h(40.0) + .w_full() + .center() + .child(text("Settings").key("title").font(type_::TITLE).color(t.text)), + ) + .child( + col() + .key("content") + .grow(1.0) + .px(space::S6) + .pt(space::S1) + .pb(space::S6) + .gap(space::S6) + .clip_fade(0.0, space::S1, 0.0, space::S6) + .child(section( + p, + "appearance", + "Appearance", + [ + setting_row(p, "theme", "Theme", None, segmented(p, s.appearance)), + setting_row(p, "accent", "Accent colour", None, swatches(p, s.accent, dark)), + ], + )) + .child(section( + p, + "general", + "General", + [ + toggle_row(p, "login", "Launch at login", s.launch_at_login, |s| { + s.launch_at_login = !s.launch_at_login + }), + toggle_row(p, "menubar", "Show in menu bar", s.menu_bar, |s| s.menu_bar = !s.menu_bar), + toggle_row(p, "sounds", "Play sounds", s.sounds, |s| s.sounds = !s.sounds), + ], + )) + .child(section( + p, + "motion", + "Motion", + [ + setting_row(p, "speed", "Animation speed", None, speed_control(p, s.speed)), + toggle_row(p, "reduce", "Reduce motion", s.reduce_motion, |s| { + s.reduce_motion = !s.reduce_motion + }), + ], + )), + ) +} + +fn section<const N: usize>(p: Paint, key: &str, title: &str, rows: [El; N]) -> El { + let mut card = col() + .key("card") + .padding(space::S1) + .fill(p.t.card) + .radius(radius::LG) + .border(p.hair, p.t.card_border) + .shadow(1.0, 2.0, p.t.shadow) + .shadow(8.0, 24.0, p.t.shadow_soft); + for (i, r) in rows.into_iter().enumerate() { + card = card.child(r); + if i + 1 < N { + card = card.child(el().key(format!("sep{i}")).h(p.hair).ml(space::S3).mr(space::S3).fill(p.t.separator).a11y_hidden()); + } + } + col() + .key(key) + .gap(space::S2) + .child(text(title).key("header").font(type_::SECTION).color(p.t.text_secondary).ml(space::S3)) + .child(card) +} + +fn setting_row(p: Paint, key: &str, label: &str, on_press: Option<fn(&mut Settings)>, control: El) -> El { + let mut r = row() + .key(key) + .h(44.0) + .px(space::S3) + .center_y() + .justify_between() + .radius(radius::MD) + .label(label) + .child(text(label).key("label").font(type_::BODY).color(p.t.text).a11y_hidden()) + .child(control); + if let Some(f) = on_press { + r = r.hover(p.t.hover).press(p.t.press).focusable(true).on_press(f); + } + r +} + +fn toggle_row(p: Paint, key: &str, label: &str, on: bool, flip: fn(&mut Settings)) -> El { + setting_row(p, key, label, Some(flip), toggle(p, on).a11y_hidden()).role("switch").checked(on) +} + +fn toggle(p: Paint, on: bool) -> El { + let (w, h, k) = (38.0, 22.0, 18.0); + let inset = (h - k) / 2.0; + el().key("switch") + .role("switch") + .size(w, h) + .radius(h / 2.0) + .fill(if on { p.accent } else { p.t.control_off }) + .motion(motion::SNAPPY) + .child( + el().key("knob") + .size(k, k) + .absolute(if on { w - k - inset } else { inset }, inset) + .radius(k / 2.0) + .fill(p.t.knob) + .shadow(1.0, 3.0, p.t.knob_shadow) + .shadow(0.0, 0.5, p.t.edge), + ) +} + +const APPEARANCES: [(Appearance, &str); 3] = + [(Appearance::Auto, "Auto"), (Appearance::Light, "Light"), (Appearance::Dark, "Dark")]; + +fn segmented(p: Paint, current: Appearance) -> El { + let (w, h, pad) = (205.0, 28.0, 2.0); + let seg = (w - 2.0 * pad) / 3.0; + let idx = APPEARANCES.iter().position(|(a, _)| *a == current).unwrap_or(0); + let mut segs = row().key("segments"); + for (i, (a, name)) in APPEARANCES.into_iter().enumerate() { + let selected = i == idx; + segs = segs.child( + el().key(name) + .role("segment") + .label(name) + .checked(selected) + .focusable(true) + .size(seg, h - 2.0 * pad) + .center() + .radius(radius::SM) + .hover(if selected { Color::TRANSPARENT } else { p.t.hover }) + .on_press_tx(move |s: &mut Settings, tx| { + s.appearance = a; + tx.color_motion(motion::CALM); + }) + .child( + text(name) + .key("label") + .font(type_::LABEL) + .color(if selected { p.t.text } else { p.t.text_secondary }) + .a11y_hidden(), + ), + ); + } + el().key("segmented") + .role("segmented") + .size(w, h) + .padding(pad) + .radius(radius::MD) + .fill(p.t.control_track) + .motion(motion::SNAPPY) + .child( + el().key("indicator") + .size(seg, h - 2.0 * pad) + .absolute(pad + idx as f32 * seg, pad) + .radius(radius::SM) + .fill(p.t.indicator) + .shadow(1.0, 3.0, p.t.shadow) + .shadow(0.0, 0.5, p.t.edge) + .lead(motion::LEAD, motion::DEFAULT) + .a11y_hidden(), + ) + .child(segs) +} + +fn swatches(p: Paint, current: usize, dark: bool) -> El { + let (d, gap, ring_w) = (18.0, 12.0, 2.0); + let ring = d + 2.0 * (ring_w + 2.0); + let mut r = row().key("swatches").role("radiogroup").label("Accent colour").gap(gap).motion(motion::SNAPPY); + r = r.child( + el().key("ring") + .size(ring, ring) + .absolute(current as f32 * (d + gap) - (ring - d) / 2.0, -(ring - d) / 2.0) + .radius(ring / 2.0) + .border(ring_w, p.accent) + .lead(Spring::new(0.22, 0.0), Spring::new(0.28, 0.0)) + .a11y_hidden(), + ); + for i in 0..6 { + r = r.child( + el().key(tok::ACCENT_NAMES[i]) + .role("radio") + .label(tok::ACCENT_NAMES[i]) + .checked(i == current) + .focusable(true) + .size(d, d) + .radius(d / 2.0) + .fill(tok::accent(i, dark)) + .border(p.hair, Color::BLACK.alpha(if dark { 0.0 } else { 0.08 })) + .on_press(move |s: &mut Settings| s.accent = i), + ); + } + r +} + +fn speed_control(p: Paint, v: f32) -> El { + let (w, h, k, bar) = (180.0, 22.0, 18.0, 4.0); + let travel = w - k; + let to_value = move |x: f32| ((x - k / 2.0) / travel).clamp(0.0, 1.0); + row() + .key("speed-control") + .gap(space::S3) + .center_y() + .child( + el().key("slider") + .role("slider") + .label("Animation speed") + // The slider's position, in twentieths; it reads as the speed it gives. + .range_value(f64::from(v), 0.0, 1.0) + .range_step(0.05) + .a11y_value(format!("{:.2}×", speed_of(v))) + .on_step(|s: &mut Settings, steps, _| s.speed = (s.speed + steps as f32 * 0.05).clamp(0.0, 1.0)) + .size(w, h) + .motion(motion::SNAPPY) + .on_drag(move |s: &mut Settings, d: &mut Drag, tx| match d.phase { + Phase::Down => { + d.data = s.speed; + let knob = k / 2.0 + v * travel; + if (d.x - knob).abs() > k / 2.0 + 2.0 { + // Clicked the track: the knob animates there. + s.speed = to_value(d.x); + } + } + Phase::Move => { + let knob = k / 2.0 + d.data * travel; + let grab = if (d.start_x - knob).abs() <= k / 2.0 + 2.0 { d.start_x - knob } else { 0.0 }; + s.speed = to_value(d.x - grab); + tx.instant(); + } + Phase::Up => { if d.cancelled() { s.speed = d.data; } } + }) + .child( + el().key("track") + .size(w, bar) + .absolute(0.0, (h - bar) / 2.0) + .radius(bar / 2.0) + .fill(p.t.control_off) + .a11y_hidden(), + ) + .child( + el().key("fill") + .size(k / 2.0 + v * travel, bar) + .absolute(0.0, (h - bar) / 2.0) + .radius(bar / 2.0) + .fill(p.accent) + .a11y_hidden(), + ) + .child( + el().key("knob") + .size(k, k) + .absolute(v * travel, (h - k) / 2.0) + .radius(k / 2.0) + .fill(p.t.knob) + .shadow(1.0, 3.0, p.t.knob_shadow) + .shadow(0.0, 0.5, p.t.edge) + .a11y_hidden(), + ), + ) + .child( + text(format!("{:.2}×", speed_of(v))) + .key("value") + .w(40.0) + .font(type_::MONO_CAPTION) + .color(p.t.text_secondary) + .align(Align::End) + .a11y_hidden(), + ) +} + +fn main() { + rune::run(AppSpec::<Settings> { + scenes: &[ + ("default", |_| {}), + ("light", |s| s.appearance = Appearance::Light), + ("dark", |s| s.appearance = Appearance::Dark), + ("reduced-motion", |s| s.reduce_motion = true), + ("toggles-off", |s| { + s.launch_at_login = false; + s.menu_bar = false; + s.sounds = false; + }), + ("accent-pink", |s| s.accent = 2), + ("slow", |s| s.speed = 0.0), + ], + ..AppSpec::new("Settings", (620.0, 520.0), Settings::default, view) + }); +} diff --git a/app/vendor/rune/examples/shapes/Cargo.toml b/app/vendor/rune/examples/shapes/Cargo.toml new file mode 100644 index 0000000..be04e35 --- /dev/null +++ b/app/vendor/rune/examples/shapes/Cargo.toml @@ -0,0 +1,11 @@ +[package] +name = "shapes" +version = "0.0.1" +edition.workspace = true +license.workspace = true + +[dependencies] +rune = { workspace = true, default-features = true, features = ["keys-overlay"] } + +[lints] +workspace = true diff --git a/app/vendor/rune/examples/shapes/src/main.rs b/app/vendor/rune/examples/shapes/src/main.rs new file mode 100644 index 0000000..5f02143 --- /dev/null +++ b/app/vendor/rune/examples/shapes/src/main.rs @@ -0,0 +1,169 @@ +//! Vector shapes: a filled waveform envelope, polylines, meters, a Bézier path and a concave +//! polygon. `cargo run -p shapes -- --snap shapes.png` renders it headless; time animates the +//! waveform, so `--at 1.5` shows another moment. + +#![forbid(unsafe_code)] + +use rune::{AppSpec, Color, Cx, El, LineCap, Path, Shape, Tx, canvas, col, memo, row, text}; + +struct State { + t: f32, +} + +const INK: Color = Color { + r: 0.92, + g: 0.93, + b: 0.95, + a: 1.0, +}; +const ACCENT: Color = Color { + r: 0.35, + g: 0.55, + b: 1.0, + a: 1.0, +}; +const SOFT: Color = Color { + r: 0.35, + g: 0.55, + b: 1.0, + a: 0.35, +}; +const WARM: Color = Color { + r: 1.0, + g: 0.55, + b: 0.3, + a: 1.0, +}; + +fn level(t: f32, i: usize) -> f32 { + let x = i as f32 * 0.09 + t * 2.0; + ((x.sin() * 0.6 + (x * 2.7).sin() * 0.3 + (x * 7.1).cos() * 0.1).abs()).min(1.0) +} + +fn waveform(t: f32, w: f32, h: f32) -> Shape { + let n = 160; + let mid = h / 2.0; + let top: Vec<[f32; 2]> = (0..n) + .map(|i| { + [ + i as f32 * w / (n - 1) as f32, + mid - level(t, i) * (mid - 2.0) - 0.5, + ] + }) + .collect(); + let mut envelope = top.clone(); + envelope.extend(top.iter().rev().map(|p| [p[0], 2.0 * mid - p[1]])); + let line: Vec<[f32; 2]> = (0..n) + .map(|i| { + [ + i as f32 * w / (n - 1) as f32, + mid + (i as f32 * 0.21 + t * 3.0).sin() * mid * 0.8, + ] + }) + .collect(); + // Drawn in a w × h box and stretched to the element's size. + Shape::new() + .fill(envelope, SOFT) + .stroke(line, 1.5, ACCENT) + .line([0.0, mid], [w, mid], 0.5, LineCap::Butt, INK) + .view_box(w, h) +} + +fn meters(t: f32) -> Shape { + let mut s = Shape::new(); + for i in 0..24 { + let x = 4.0 + i as f32 * 10.0; + let v = level(t, i * 7) * 56.0 + 4.0; + s = s.line( + [x, 64.0], + [x, 64.0 - v], + 6.0, + LineCap::Round, + if v > 48.0 { WARM } else { ACCENT }, + ); + } + s +} + +fn curves() -> Shape { + let wave = Path::new() + .move_to([4.0, 50.0]) + .cubic_to([40.0, -20.0], [80.0, 120.0], [116.0, 50.0]) + .quad_to([150.0, 0.0], [186.0, 50.0]); + let blob = Path::new() + .move_to([210.0, 30.0]) + .cubic_to([230.0, 0.0], [270.0, 0.0], [280.0, 30.0]) + .line_to([260.0, 80.0]) + .line_to([220.0, 80.0]) + .close(); + let star: Vec<[f32; 2]> = (0..10) + .map(|i| { + let a = i as f32 * std::f32::consts::PI / 5.0 - std::f32::consts::FRAC_PI_2; + let r = if i % 2 == 0 { 40.0 } else { 16.0 }; + [340.0 + a.cos() * r, 46.0 + a.sin() * r] + }) + .collect(); + Shape::new() + .stroke_path(&wave, 3.0, LineCap::Round, WARM) + .fill_path(&blob, ACCENT) + .stroke_path(&blob, 1.0, LineCap::Round, INK) + .fill(star, INK) + .line([400.0, 10.0], [460.0, 86.0], 0.5, LineCap::Butt, INK) + .line([410.0, 10.0], [470.0, 86.0], 1.0, LineCap::Butt, INK) + .line([420.0, 10.0], [480.0, 86.0], 2.0, LineCap::Butt, INK) +} + +fn label(s: &str) -> El { + text(s).color(INK) +} + +fn view(s: &State, _: &mut Cx<State>) -> El { + col() + .key("root") + .padding(24.0) + .gap(16.0) + .fill(Color { + r: 0.06, + g: 0.065, + b: 0.08, + a: 1.0, + }) + .child(label("Waveform: filled envelope, polyline, hairline")) + .child( + canvas(waveform(s.t, 260.0, 96.0)) + .key("wave") + .size(520.0, 96.0) + .fill(Color { + r: 0.1, + g: 0.11, + b: 0.13, + a: 1.0, + }) + .radius(8.0), + ) + .child( + row() + .gap(24.0) + .child( + col() + .gap(8.0) + .child(label("Meters")) + .child(canvas(meters(s.t)).key("meters").size(244.0, 68.0)), + ) + .child( + col() + .gap(8.0) + .child(label("Paths, a concave fill, line widths")) + .child(memo("curves", (), || canvas(curves()).size(490.0, 96.0))), + ), + ) +} + +fn poll(s: &mut State, t: f64, _: &mut Tx) -> bool { + s.t = t as f32; + true +} + +fn main() { + rune::run(AppSpec { poll: Some(poll), ..AppSpec::new("Shapes", (820.0, 360.0), || State { t: 0.0 }, view) }); +} diff --git a/app/vendor/rune/examples/showreel/Cargo.toml b/app/vendor/rune/examples/showreel/Cargo.toml new file mode 100644 index 0000000..d04c7a0 --- /dev/null +++ b/app/vendor/rune/examples/showreel/Cargo.toml @@ -0,0 +1,27 @@ +[package] +name = "showreel" +version = "0.0.1" +edition.workspace = true +license.workspace = true +publish = false + +[dependencies] +rune = { workspace = true, default-features = true, features = ["keys-overlay"] } +rune-motion = { workspace = true } +rune-fx = { workspace = true } +wgpu = { workspace = true, features = ["std", "parking_lot", "wgsl"] } + +[target.'cfg(target_vendor = "apple")'.dependencies] +wgpu = { workspace = true, features = ["metal"] } + +[target.'cfg(target_os = "windows")'.dependencies] +wgpu = { workspace = true, features = ["dx12"] } + +[target.'cfg(all(not(target_vendor = "apple"), not(target_arch = "wasm32"), not(target_os = "windows")))'.dependencies] +wgpu = { workspace = true, features = ["vulkan"] } + +[target.'cfg(target_arch = "wasm32")'.dependencies] +wgpu = { workspace = true, features = ["webgpu"] } + +[lints] +workspace = true diff --git a/app/vendor/rune/examples/showreel/README.md b/app/vendor/rune/examples/showreel/README.md new file mode 100644 index 0000000..2449fe3 --- /dev/null +++ b/app/vendor/rune/examples/showreel/README.md @@ -0,0 +1,7 @@ +# showreel + +The scene set behind Rune's README video. + +Run one scene with `cargo run --release -p showreel -- --scene <name>`; record it with `--video out.mp4 --size 960x540 --scale 2 --fps 60 --duration D`. + +Scenes: `word`, `card`, `deploy`, `glass`, `fire`, `pricing`, `ask`, `shock`, `keys`, `tabs`. diff --git a/app/vendor/rune/examples/showreel/src/gfx.rs b/app/vendor/rune/examples/showreel/src/gfx.rs new file mode 100644 index 0000000..d1f0eed --- /dev/null +++ b/app/vendor/rune/examples/showreel/src/gfx.rs @@ -0,0 +1,188 @@ +//! The compositor: every `El::effect` slot becomes one rune-fx layer. The slot's mark says which +//! effect, its `effect_data` carries the effect's few live numbers, and its presented rect and +//! radius are the shape. Glass, lenses and shockwaves read a backdrop copy taken at their slot. + +use rune::compose::{Compositor, Frame}; +use rune::render::{EffectPhase, EffectSite, KIND_EFFECT}; +use rune_fx::*; + +use crate::State; + +pub const CHROME: u32 = 1; +pub const MESH: u32 = 2; +pub const FLUTED: u32 = 3; +pub const FIRE: u32 = 4; +pub const ELECTRIC: u32 = 5; +pub const ARC: u32 = 6; +pub const GLOW: u32 = 7; +pub const SPARKLES: u32 = 8; +pub const SHOCK: u32 = 9; +pub const LENS: u32 = 10; +pub const PLASTIC: u32 = 11; +pub const PULSE: u32 = 12; +pub const SHIMMER: u32 = 13; +pub const GRAIN: u32 = 14; +pub const AURORA: u32 = 15; +pub const HAZE: u32 = 16; +pub const GRAIN_GRADIENT: u32 = 17; + +/// Effect colours, by index (effect data carries the index). +pub const COLORS: [u32; 14] = [ + 0xffffff, 0x4f8dff, 0x22d3ee, 0x7c5cff, 0x34d399, 0xffb547, 0xff5ca8, 0xff4d4d, 0xff7a1a, 0xf1ece1, 0x2e3036, 0xe8552b, + 0x3d6bff, 0x54b3fd, +]; + +fn col(i: f32) -> Rgb { + rgb(COLORS[(i.max(0.0) as usize).min(COLORS.len() - 1)]) +} + +fn layer(kind: u32, d: [f32; 4], shape: Shape, t: f32) -> Option<FxLayer> { + let fx = match kind { + CHROME => { + let mut p = match d[0] as u32 { + 1 => LiquidMetalParams::gold(), + 2 => LiquidMetalParams::rose(), + 3 => LiquidMetalParams::gunmetal(), + 4 => LiquidMetalParams { light: rgb(0xd6e8ff), iridescence: 0.3, scale: 240.0, bevel: 3.5, dome: 0.2, contrast: 1.15, ..LiquidMetalParams::chrome() }, + 5 => LiquidMetalParams { scale: 360.0, flow: 0.5, speed: 0.6, dome: 0.8, contrast: 0.85, bevel: 12.0, angle: 0.45, ..LiquidMetalParams::chrome() }, + _ => LiquidMetalParams::chrome(), + }; + if d[2] > 0.0 { + p.flow *= d[2]; + } + if d[3] > 0.5 { + p = p.anchor(FillAnchor::Element); + } + if d[1] > 0.0 { Fx::fill(p.border(d[1])) } else { Fx::fill(p) } + } + MESH => { + let mut p = match d[0] as u32 { + 1 => MeshGradientParams::lagoon(), + 2 => MeshGradientParams::orchid(), + 3 => MeshGradientParams::graphite(), + 4 => MeshGradientParams { colors: Stops::hex(&[0x0d1b4c, 0x3d6bff, 0x9b5cff, 0x22d3ee, 0x101030]), ..MeshGradientParams::dusk() }, + 5 => MeshGradientParams { colors: Stops::hex(&[0x2a0a12, 0xff4d4d, 0xffb547, 0x7a1640, 0xff7a1a]), ..MeshGradientParams::dusk() }, + 6 => MeshGradientParams { colors: Stops::hex(&[0x062a24, 0x34d399, 0xd9f99d, 0x0f766e]), ..MeshGradientParams::dusk() }, + 7 => MeshGradientParams { colors: Stops::hex(&[0x1a1033, 0xff5ca8, 0x7c5cff, 0xffd1e8, 0x2b1b5a]), ..MeshGradientParams::dusk() }, + _ => MeshGradientParams::dusk(), + }; + if d[1] > 0.0 { + p.speed = d[1]; + } + if d[3] > 0.0 { + p.drift = d[3]; + } + return Some(Fx::fill(p).on(shape).at(t).seed(d[2] as u32 + 1)); + } + FLUTED => Fx::fill(FlutedGlassParams { rib: d[0], refraction: d[1], frost: d[2], dispersion: d[3], highlight: 0.55, ..FlutedGlassParams::reeded() }), + FIRE => { + let style = match d[2] as u32 { + 1 => FireStyle::Border, + 2 => FireStyle::Heat, + 3 => FireStyle::Embers, + _ => FireStyle::Top, + }; + Fx::fire(FireParams { style, height: d[0], intensity: d[1], smoke: d[3], embers: 24, scale: 26.0, ..FireParams::default() }) + } + ELECTRIC => { + let base = if d[2] > 0.5 { ElectricParams::charged() } else { ElectricParams::default() }; + Fx::electric(ElectricParams { intensity: d[0], amplitude: if d[1] > 0.0 { d[1] } else { base.amplitude }, color: col(d[3]), ..base }) + } + ARC => Fx::electric(ElectricParams { style: ElectricStyle::Arc { a: [d[0], d[1]], b: [d[2], d[3]] }, amplitude: 9.0, glow: 7.0, intensity: 1.2, ..Default::default() }), + GLOW => { + let style = match d[0] as u32 { + 1 => GlowStyle::Neon, + 2 => GlowStyle::Aura, + _ => GlowStyle::Soft, + }; + Fx::glow(GlowParams { style, color: col(d[1]), intensity: d[2], radius: if d[3] > 0.0 { d[3] } else { 14.0 }, aura_speed: 0.35, ..Default::default() }) + } + SPARKLES => Fx::sparkles(SparkleParams { burst: (d[0] >= 0.0).then_some(d[0]), count: d[1] as u32, size: d[2], color: col(d[3]), margin: 26.0, ..Default::default() }), + SHOCK => Fx::distort(DistortParams::Shockwave { at: [d[0], d[1]], reach: 1100.0, width: 90.0, amount: d[3], chroma: 0.6, t0: d[2], duration: 1.1 }), + LENS => Fx::lens(LensParams { + second: (d[2] > 0.0).then(|| Shape::circle(d[0], d[1], d[2])), + frost: d[3], + bevel: 16.0, + depth: 20.0, + dispersion: 0.18, + magnification: 1.06, + union_k: 26.0, + ..Default::default() + }), + PLASTIC => Fx::fill(PlasticParams { color: col(d[0]), roughness: d[1], dome: d[2], bevel: if d[3] > 0.0 { d[3] } else { 6.0 }, angle: -0.6 }), + PULSE => { + let style = match d[0] as u32 { + 1 => PulseStyle::Breathe, + 2 => PulseStyle::Heartbeat, + _ => PulseStyle::Radar, + }; + Fx::pulse(PulseParams { style, color: col(d[1]), reach: d[3], period: if d[2] > 0.0 { d[2] } else { 2.4 }, ..Default::default() }) + } + SHIMMER => Fx::shimmer(ShimmerParams { intensity: d[0], period: d[1], band: d[2], ..Default::default() }), + GRAIN => Fx::grain(GrainParams { amount: d[0], fps: d[1], ..Default::default() }), + AURORA => Fx::aurora(AuroraParams { intensity: d[0], speed: d[1], ..Default::default() }), + HAZE => Fx::distort(DistortParams::HeatHaze { height: d[0], scale: 14.0, speed: 1.4, amount: d[1], whole_shape: d[2] > 0.5 }), + GRAIN_GRADIENT => Fx::fill(GrainGradientParams { kind: GradientKind::Radial, colors: Stops::hex(&[0x1b1530, 0x0a0a0c]), amount: 0.12, ..GrainGradientParams::default() }), + _ => return None, + }; + Some(fx.on(shape).at(t)) +} + +#[derive(Default)] +pub struct Gfx { + fx: Option<FxRenderer>, +} + +impl Compositor<State> for Gfx { + fn animating(&self) -> bool { + true + } + + fn render(&mut self, f: &mut Frame<'_, State>) { + let (device, queue, size) = (f.device, f.queue, f.size); + let t = f.rt.t as f32; + let marks = &f.rt.marks; + let mut at: Vec<u32> = Vec::new(); + let mut layers: Vec<FxLayer> = Vec::new(); + let mut placements: Vec<FxSlot> = Vec::new(); + let mut fire = false; + for (n, i) in f.rt.instances.iter().enumerate() { + if i.params[1] != KIND_EFFECT { + continue; + } + let kind = marks.get(n).copied().unwrap_or(0) & 0xff; + let k = i.params[3]; + let [x, y, w, h] = i.rect.map(|v| v / k); + let r = i.radii.iter().fold(0.0f32, |a, v| a.max(v.abs())) / k; + let Some(l) = layer(kind, i.uv, Shape::rounded(x, y, w, h, r), t) else { continue }; + fire |= kind == FIRE; + at.push(n as u32); + layers.push(l); + placements.push(FxSlot::default().scale(k).clip(i.clip, i.fade)); + } + let fx = self.fx.get_or_insert_with(|| { + let mut fx = FxRenderer::new(device, f.format, FxOptions { dither: true }); + fx.set_fire_sim(device, true); + fx + }); + fx.set_srgb_blend(f.srgb_blend()); + fx.add_format(device, wgpu::TextureFormat::Rgba16Float); + fx.prepare_with_slots(device, queue, &FxFrame { viewport: [size.0, size.1], scale: 1.0, layers: &layers, backdrop: None, sources: &[] }, &placements); + if fire { + fx.simulate(queue, f.encoder, None); + } + let clear = f.rt.clear_color(); + f.ui.prepare(device, queue, &mut f.rt.text.atlas, &f.rt.instances, size); + f.ui.draw_with_backdrop(f.encoder, f.target, clear, &mut |phase, s: &EffectSite<'_>| { + let Some(k) = at.iter().position(|n| *n == s.index) else { return }; + match phase { + EffectPhase::Backdrop(enc) => { + if let Some(bd) = s.backdrop { + fx.blur_backdrop(device, queue, enc, bd, k); + } + } + EffectPhase::Draw(pass) => fx.draw_layer_in(pass, s.format, s.origin, k), + } + }); + } +} diff --git a/app/vendor/rune/examples/showreel/src/kit.rs b/app/vendor/rune/examples/showreel/src/kit.rs new file mode 100644 index 0000000..b94f52f --- /dev/null +++ b/app/vendor/rune/examples/showreel/src/kit.rs @@ -0,0 +1,118 @@ +//! Shared look and motion helpers for the scenes. + +use rune::color::Color; +use rune::{El, TextStyle, el, text}; +use rune_motion::Spring; + +pub const W: f32 = 960.0; +pub const H: f32 = 540.0; + +/// An sRGB hex colour. +pub fn c(hex: u32) -> Color { + let ch = |shift: u32| rune::color::srgb_decode(((hex >> shift) & 0xff) as f32 / 255.0); + Color { r: ch(16), g: ch(8), b: ch(0), a: 1.0 } +} + +pub fn ca(hex: u32, a: f32) -> Color { + c(hex).alpha(a) +} + +pub const BG: u32 = 0x0b0b0d; +pub const PANEL: u32 = 0x141417; +pub const RAISED: u32 = 0x1b1b1f; +pub const TEXT: u32 = 0xededef; +pub const MUTED: u32 = 0x9a9aa3; +pub const FAINT: u32 = 0x5f5f68; + +pub fn hair() -> Color { + ca(0xffffff, 0.08) +} + +pub fn t(s: impl Into<String>, size: f32, weight: f32, color: u32) -> El { + text(s).font(TextStyle::new(size, weight)).color(c(color)) +} + +pub fn ta(s: impl Into<String>, size: f32, weight: f32, color: u32, alpha: f32) -> El { + text(s).font(TextStyle::new(size, weight)).color(ca(color, alpha.clamp(0.0, 1.0))) +} + +pub fn mono_a(s: impl Into<String>, size: f32, color: u32, alpha: f32) -> El { + text(s).font(TextStyle::new(size, 500.0).mono()).color(ca(color, alpha.clamp(0.0, 1.0))) +} + +pub fn mono(s: impl Into<String>, size: f32, color: u32) -> El { + text(s).font(TextStyle::new(size, 500.0).mono()).color(c(color)) +} + +/// An effect slot: `kind` is a `gfx` constant, `data` its numbers. +pub fn fx(kind: u32, data: [f32; 4]) -> El { + rune::effect(kind).effect_data(data) +} + +/// 0 → 1 between `t0` and `t0 + dur`, smoothstep. +pub fn ease(t: f64, t0: f64, dur: f64) -> f32 { + let x = ((t - t0) / dur).clamp(0.0, 1.0) as f32; + x * x * (3.0 - 2.0 * x) +} + +/// A value that starts at `from` and springs to each key's target at its time, carrying velocity +/// across retargets (as an interrupted Rune spring does). +pub fn track(t: f64, from: f32, keys: &[(f64, f32, Spring)]) -> f32 { + let (mut x, mut v, mut target, mut t0, mut spring) = (from, 0.0f32, from, 0.0f64, Spring::new(0.3, 0.0)); + for &(tk, to, sp) in keys { + if t < tk { + break; + } + let (nx, nv) = spring.sample(x, v, target, (tk - t0) as f32); + x = nx; + v = nv; + target = to; + t0 = tk; + spring = sp; + } + spring.sample(x, v, target, (t - t0) as f32).0 +} + +pub const fn sp(duration: f32, bounce: f32) -> Spring { + Spring::new(duration, bounce) +} + +/// An iPad-style round pointer at (x, y), centred, squeezed while pressed. +pub fn pointer(x: f32, y: f32, press: f32) -> El { + let r = 9.0 * (1.0 - 0.22 * press); + el().key("pointer") + .absolute(x - r, y - r) + .size(2.0 * r, 2.0 * r) + .radius(r) + .fill(ca(0xf4f4f6, 0.92)) + .border(1.0, ca(0x000000, 0.35)) + .shadow(2.0, 8.0, ca(0x000000, 0.45)) +} + +/// A pointer that follows `path` (time, x, y) on springs and presses at each time in `taps`. +pub fn pointer_at(t: f64, start: [f32; 2], path: &[(f64, f32, f32)], taps: &[f64]) -> El { + let s = sp(0.55, 0.0); + let kx: Vec<(f64, f32, Spring)> = path.iter().map(|&(tk, x, _)| (tk, x, s)).collect(); + let ky: Vec<(f64, f32, Spring)> = path.iter().map(|&(tk, _, y)| (tk, y, s)).collect(); + let x = track(t, start[0], &kx); + let y = track(t, start[1], &ky); + let k: Vec<(f64, f32, Spring)> = taps.iter().flat_map(|&tp| [(tp, 1.0, sp(0.12, 0.0)), (tp + 0.14, 0.0, sp(0.3, 0.4))]).collect(); + pointer(x, y, track(t, 0.0, &k)) +} + +/// Press depth (0 → 1 → 0) for a tap at `tp`: down fast, back on a bouncy spring. +pub fn pressed(t: f64, tp: f64) -> f32 { + track(t, 0.0, &[(tp, 1.0, sp(0.12, 0.0)), (tp + 0.14, 0.0, sp(0.35, 0.45))]) +} + +pub fn avatar(letter: &str, color: u32, size: f32) -> El { + el().size(size, size) + .radius(size / 2.0) + .fill(c(color)) + .center() + .child(t(letter, size * 0.42, 600.0, 0x0b0b0d)) +} + +pub fn dot(color: u32, size: f32) -> El { + el().size(size, size).radius(size / 2.0).fill(c(color)) +} diff --git a/app/vendor/rune/examples/showreel/src/main.rs b/app/vendor/rune/examples/showreel/src/main.rs new file mode 100644 index 0000000..36b049f --- /dev/null +++ b/app/vendor/rune/examples/showreel/src/main.rs @@ -0,0 +1,83 @@ +//! Showreel: purpose-made 960×540 scenes for Rune's showcase video. Each scene animates itself from +//! the (virtual) clock, so a headless `--video` run records it frame-exact: +//! +//! showreel --scene deploy --video deploy.mp4 --size 960x540 --scale 2 --duration 4 + +#![forbid(unsafe_code)] + +mod gfx; +mod kit; +mod scenes; + +use rune::{AppSpec, Cx, El}; + +#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)] +pub enum Scene { + #[default] + Word, + Card, + Deploy, + Glass, + Fire, + Pricing, + Ask, + Shock, + Keys, + Tabs, + Type, +} + +#[derive(Default)] +pub struct State { + pub scene: Scene, + /// Seconds since the scene started (Rune's virtual clock when headless). + pub t: f64, +} + +fn view(s: &State, cx: &mut Cx<State>) -> El { + match s.scene { + Scene::Word => scenes::word::view(s, cx, false), + Scene::Card => scenes::word::view(s, cx, true), + Scene::Deploy => scenes::deploy::view(s, cx), + Scene::Glass => scenes::glass::view(s, cx), + Scene::Fire => scenes::fire::view(s, cx), + Scene::Pricing => scenes::pricing::view(s, cx), + Scene::Ask => scenes::ask::view(s, cx), + Scene::Shock => scenes::shock::view(s, cx), + Scene::Keys => scenes::keys::view(s, cx), + Scene::Tabs => scenes::tabs::view(s, cx), + Scene::Type => scenes::type_::view(s, cx), + } +} + +fn main() { + let app = rune::App::new(AppSpec::<State> { + scenes: &[ + ("word", |s| s.scene = Scene::Word), + ("card", |s| s.scene = Scene::Card), + ("deploy", |s| s.scene = Scene::Deploy), + ("glass", |s| s.scene = Scene::Glass), + ("fire", |s| s.scene = Scene::Fire), + ("pricing", |s| s.scene = Scene::Pricing), + ("ask", |s| s.scene = Scene::Ask), + ("shock", |s| s.scene = Scene::Shock), + ("keys", |s| s.scene = Scene::Keys), + ("tabs", |s| s.scene = Scene::Tabs), + ("type", |s| s.scene = Scene::Type), + ], + fonts: &[ + include_bytes!("../../../crates/rune/assets/Inter-Regular.ttf"), + include_bytes!("../../../crates/rune/assets/Inter-Medium.ttf"), + include_bytes!("../../../crates/rune/assets/Inter-SemiBold.ttf"), + include_bytes!("../../../themes/opencode/assets/fonts/IBMPlexMono-Medium.ttf"), + ], + families: ("Inter", "IBM Plex Mono"), + poll: Some(|s, t, _| { + s.t = t; + true + }), + ..AppSpec::new("Showreel", (960.0, 540.0), State::default, view) + }) + .compositor(gfx::Gfx::default()); + app.run(); +} diff --git a/app/vendor/rune/examples/showreel/src/scenes/ask.rs b/app/vendor/rune/examples/showreel/src/scenes/ask.rs new file mode 100644 index 0000000..47edec9 --- /dev/null +++ b/app/vendor/rune/examples/showreel/src/scenes/ask.rs @@ -0,0 +1,80 @@ +//! An assistant's composer wrapped in a flowing aura. A prompt types itself, send flares the glow, +//! the composer drops to the bottom and the reply streams in under a shimmer. + +use rune::{Cx, El, col, el, row, spacer}; + +use crate::gfx::{GLOW, PULSE, SHIMMER}; +use crate::kit::*; +use crate::State; + +const PROMPT: &str = "make the settings page feel alive"; +const TYPE_FROM: f64 = 0.3; +const TYPE_RATE: f64 = 30.0; +const SEND: f64 = 1.55; + +fn chip(s: &str, a: f32) -> El { + row().h(32.0).px(14.0).radius(16.0).center().fill(ca(0xffffff, 0.05 * a)).border(1.0, ca(0xffffff, 0.08 * a)).child(ta(s, 13.0, 500.0, MUTED, a)) +} + +pub fn view(s: &State, _: &mut Cx<State>) -> El { + let t_ = s.t; + let n = (((t_ - TYPE_FROM) * TYPE_RATE).max(0.0) as usize).min(PROMPT.len()); + let sent = t_ >= SEND; + let press = pressed(t_, SEND); + let flare = if sent { 1.6 * (-(t_ - SEND) as f32 * 2.2).exp() } else { 0.0 }; + let drop = track(t_, 0.0, &[(SEND + 0.08, 1.0, sp(0.6, 0.12))]); + let (cw, ch) = (640.0, 128.0); + let cx0 = (W - cw) / 2.0; + let cy0 = 214.0 + (382.0 - 214.0) * drop; + + let caret_on = ((t_ * 2.0) as i64) % 2 == 0 || n < PROMPT.len(); + let typed = if sent { String::new() } else { PROMPT[..n].to_string() }; + let field = row().gap(1.0).center_y() + .child(if typed.is_empty() && !sent && n == 0 { t("Ask anything…", 17.0, 400.0, FAINT) } else { t(typed, 17.0, 400.0, TEXT) }) + .child(el().w(2.0).h(22.0).radius(1.0).fill(ca(0x9fd4ff, if caret_on { 1.0 } else { 0.0 }))); + + let send = el().size(36.0, 36.0).radius(18.0).scale(1.0 - 0.12 * press).fill(if n > 0 { c(0xf4f6fb) } else { ca(0xffffff, 0.15) }).center().child(t("↑", 18.0, 600.0, 0x0b0b0d)); + let composer = col().key("composer").absolute(cx0, cy0).size(cw, ch).padding(20.0).radius(24.0).fill(c(0x131317)).border(1.0, ca(0xffffff, 0.1)) + .child(field) + .child(spacer()) + .child( + row().w_full().center_y().gap(8.0) + .child(row().h(30.0).px(12.0).radius(15.0).center().gap(6.0).fill(ca(0xffffff, 0.06)).child(dot(0x54b3fd, 6.0)).child(t("Build", 12.5, 500.0, 0xc9c9d0))) + .child(row().h(30.0).px(12.0).radius(15.0).center().fill(ca(0xffffff, 0.06)).child(t("opus", 12.5, 500.0, 0xc9c9d0))) + .child(spacer()) + .child(send), + ); + + let greet = 1.0 - ease(t_, SEND, 0.25); + let mut root = el().w(W).h(H).fill(c(0x09090b)) + .child(col().key("greet").absolute(0.0, 150.0 - 20.0 * (1.0 - greet)).w(W).items_center().child(ta("What should we build?", 30.0, 600.0, TEXT, greet))) + .child( + row().key("chips").absolute(0.0, 214.0 + ch + 22.0).w(W).justify_center().gap(10.0) + .child(chip("A springy toggle", greet)) + .child(chip("Liquid metal button", greet)) + .child(chip("Glass sidebar", greet)), + ) + .child(fx(GLOW, [2.0, 3.0, 1.0 + flare, 22.0]).key("aura").absolute(cx0, cy0).size(cw, ch).radius(24.0).effect_bleed(70.0)) + .child(composer); + + if sent { + let k = track(t_, 0.0, &[(SEND + 0.12, 1.0, sp(0.45, 0.25))]); + let a = k.clamp(0.0, 1.0); + let bubble = row().h(42.0).px(16.0).radius(16.0).center().fill(ca(0x1f2633, a)).child(ta(PROMPT, 15.0, 400.0, 0xe6ecf7, a)); + root = root.child(row().key("bubble").absolute(0.0, 58.0 + 14.0 * (1.0 - k)).w(W - 160.0).justify_end().child(bubble)); + let r = ease(t_, SEND + 0.4, 0.3); + let mut reply = col().key("reply").absolute(160.0, 132.0).w(640.0).gap(12.0) + .child(row().gap(10.0).center_y() + .child(el().size(10.0 * r, 10.0 * r).child(fx(PULSE, [1.0, 13.0, 1.2, 10.0]).absolute(0.0, 0.0).size(10.0, 10.0).radius(5.0).effect_bleed(16.0)).child(dot(0x54b3fd, 10.0).absolute(0.0, 0.0))) + .child(ta("Thinking", 14.0, 500.0, MUTED, r))); + for (i, w) in [600.0, 540.0, 580.0, 360.0].iter().enumerate() { + let k2 = ease(t_, SEND + 0.55 + i as f64 * 0.12, 0.25); + reply = reply.child( + el().w(*w * (0.6 + 0.4 * k2)).h(12.0).radius(6.0).fill(ca(0xffffff, 0.07 * k2)) + .child(fx(SHIMMER, [0.35 * k2, 1.3, 60.0, 0.0]).absolute(0.0, 0.0).w(*w * (0.6 + 0.4 * k2)).h(12.0).radius(6.0)), + ); + } + root = root.child(reply); + } + root.child(pointer_at(t_, [760.0, 470.0], &[(0.9, cx0 + cw - 38.0, 214.0 + ch - 38.0), (SEND + 0.25, 860.0, 520.0)], &[SEND])) +} diff --git a/app/vendor/rune/examples/showreel/src/scenes/deploy.rs b/app/vendor/rune/examples/showreel/src/scenes/deploy.rs new file mode 100644 index 0000000..8994d7a --- /dev/null +++ b/app/vendor/rune/examples/showreel/src/scenes/deploy.rs @@ -0,0 +1,168 @@ +//! A deploy dashboard whose Deploy button is liquid metal. The pointer comes in, presses it, a new +//! deployment springs into the list, builds and goes live. + +use rune::{Cx, El, Transition, col, el, row, spacer}; + +use crate::gfx::{CHROME, GLOW, PULSE, SHIMMER, SPARKLES}; +use crate::kit::*; +use crate::State; + +/// The toolbar's Deploy, then the confirm sheet's. +const TAP: f64 = 0.7; +const CONFIRM: f64 = 1.6; +const DISMISS: f64 = 2.3; +const INSERT: f64 = 2.4; +const READY: f64 = 3.4; + +const ROWS: [(&str, &str, &str, &str, u32); 5] = [ + ("overlay: motion started while hidden plays on show", "f6d096b", "38s", "12m", 0x7c5cff), + ("text: a span keeps the paragraph's leading ratio", "4112cac", "41s", "1h", 0xff7a1a), + ("text: snap the pen to 1/256 px before flooring", "bac9e90", "40s", "2h", 0x34d399), + ("rune-mermaid: hover settings keep their style", "c83aa06", "44s", "3h", 0x54b3fd), + ("fx: frosted glass reads a blurred backdrop", "9e1d4b2", "39s", "5h", 0xff5ca8), +]; + +fn status(label: &str, color: u32, pulse: Option<u32>) -> El { + let mut d = el().size(8.0, 8.0); + if let Some(p) = pulse { + d = d.child(fx(PULSE, [1.0, p as f32, 1.2, 9.0]).absolute(0.0, 0.0).size(8.0, 8.0).radius(4.0).effect_bleed(14.0)); + } + d = d.child(dot(color, 8.0).absolute(0.0, 0.0)); + row().w(118.0).gap(9.0).center_y().child(d).child(t(label, 13.0, 500.0, TEXT)) +} + +fn list_row(msg: &str, sha: &str, dur: &str, ago: &str, who: u32, st: El, extra: Option<El>) -> El { + let mut info = col().gap(5.0).child(t(msg, 13.5, 500.0, TEXT)).child( + row().gap(8.0).center_y().child( + el().px(6.0).py(1.0).radius(5.0).fill(ca(0xffffff, 0.06)).child(mono("dev", 11.0, MUTED)), + ) + .child(mono(sha, 11.0, FAINT)), + ); + if let Some(e) = extra { + info = info.child(e); + } + row().key(format!("row-{sha}")) + .w_full() + .h(62.0) + .px(20.0) + .center_y() + .child(st) + .child(info.grow(1.0)) + .child(t(dur, 13.0, 400.0, MUTED).w(60.0)) + .child(t(ago, 13.0, 400.0, MUTED).w(54.0)) + .child(avatar("", who, 22.0)) +} + +pub fn view(s: &State, _: &mut Cx<State>) -> El { + let t_ = s.t; + let hover = track(t_, 0.0, &[(0.5, 1.0, sp(0.35, 0.3))]); + let press = pressed(t_, TAP); + let scale = 1.0 + 0.05 * hover - 0.08 * press; + let flow = 1.0 + 1.2 * (if t_ > TAP { (-(t_ - TAP) as f32 * 1.5).exp() } else { 0.0 }); + + // The Deploy button: liquid metal under the label, a soft glow while hovered. + let button = el().key("deploy") + .size(132.0, 40.0) + .radius(20.0) + .scale(scale) + .child(fx(GLOW, [0.0, 0.0, 0.22 * hover, 12.0]).absolute(0.0, 0.0).size(132.0, 40.0).radius(20.0).effect_bleed(40.0)) + .child(fx(CHROME, [5.0, 0.0, flow, 0.0]).absolute(0.0, 0.0).size(132.0, 40.0).radius(20.0)) + .child(row().absolute(0.0, 0.0).size(132.0, 40.0).center().child(t("Deploy", 15.0, 600.0, 0x0e0f12))) + ; + + let logo = el().size(26.0, 26.0).radius(7.0).linear_gradient(2.3, [(0.0, c(0x54b3fd)), (1.0, c(0x3d6bff))]); + let top = row().w_full() + .h(64.0) + .px(24.0) + .center_y() + .gap(12.0) + .child(logo) + .child(t("anomaly", 14.0, 500.0, MUTED)) + .child(t("/", 14.0, 400.0, FAINT)) + .child(t("rune", 14.0, 600.0, TEXT)) + .child( + row().ml(6.0).px(10.0).py(4.0).gap(6.0).radius(10.0).center_y().fill(ca(0x34d399, 0.12)) + .child(dot(0x34d399, 6.0)) + .child(t("Production", 12.0, 500.0, 0x6ee7b7)), + ) + .child(spacer()) + .child(row().child(avatar("", 0xff7a1a, 26.0).border(2.0, c(BG))).child(avatar("", 0x7c5cff, 26.0).border(2.0, c(BG)).ml(-7.0)).child(avatar("", 0x34d399, 26.0).border(2.0, c(BG)).ml(-7.0))) + .child(el().w(10.0)) + .child(button); + + let tabs = ["Overview", "Deployments", "Analytics", "Logs", "Storage", "Settings"]; + let mut tab_row = row().w_full().h(42.0).px(24.0).gap(26.0).center_y(); + for (i, name) in tabs.iter().enumerate() { + let on = i == 1; + tab_row = tab_row.child( + col().h(42.0).justify_center().child(t(*name, 13.5, if on { 600.0 } else { 450.0 }, if on { TEXT } else { MUTED })).child( + el().absolute(0.0, 40.0).h(2.0).w_full().fill(if on { c(TEXT) } else { ca(0, 0.0) }), + ), + ); + } + + // The new deployment springs in at the top of the list once Deploy is pressed. + let grow = track(t_, 0.0, &[(INSERT, 1.0, sp(0.5, 0.18))]); + let ready = t_ >= READY; + let mut list = col().w_full().radius(14.0).fill(c(PANEL)).border(1.0, hair()).clip_rounded(14.0); + if grow > 0.001 { + let progress = ease(t_, INSERT + 0.1, READY - INSERT - 0.15); + let fade = 1.0 - ease(t_, READY, 0.3); + let bar = el().mt(4.0).w(260.0).h(3.0).radius(2.0).fill(ca(0xffffff, 0.08 * fade)).child( + el().absolute(0.0, 0.0).h(3.0).w(260.0 * progress).radius(2.0).fill(ca(0xffb547, fade)) + .child(fx(SHIMMER, [0.5 * fade, 0.9, 40.0, 0.0]).absolute(0.0, 0.0).h(3.0).w(260.0 * progress).radius(2.0)), + ); + let st = if ready { status("Ready", 0x34d399, Some(4)) } else { status("Building", 0xffb547, Some(5)) }; + let fresh = list_row("README: a 30 second showcase, cut from real renders", "ba5b054", if ready { "1m 39s" } else { "…" }, "now", 0x54b3fd, st, Some(bar)); + list = list.child( + el().key("fresh").w_full().h(62.0 * grow + 9.0 * grow).clip_rounded(0.0).child( + el().absolute(0.0, -62.0 * (1.0 - grow)).w_full().fill(ca(0xffffff, 0.025 + 0.03 * (1.0 - ease(t_, READY, 0.8)))).child(fresh), + ), + ); + } + for (i, (msg, sha, dur, ago, who)) in ROWS.iter().enumerate() { + if i > 0 || grow > 0.001 { + list = list.child(el().key(format!("sep-{i}")).w_full().h(1.0).fill(hair())); + } + list = list.child(list_row(msg, sha, dur, ago, *who, status("Ready", 0x34d399, None), None)); + } + + let header = row().w_full().items_end().child( + col().gap(6.0).child(t("Deployments", 26.0, 600.0, TEXT)).child(t("Every push to dev ships to production.", 13.5, 400.0, MUTED)), + ) + .child(spacer()) + .child(row().w(230.0).h(36.0).px(12.0).radius(10.0).center_y().fill(c(PANEL)).border(1.0, hair()).child(t("Search deployments…", 13.0, 400.0, FAINT))) + .child(el().w(10.0)) + .child(row().h(36.0).px(14.0).radius(10.0).center_y().fill(c(PANEL)).border(1.0, hair()).child(t("All environments", 13.0, 500.0, MUTED))); + + let page = col().w(960.0).h(540.0).fill(c(BG)) + .child(top) + .child(tab_row) + .child(el().w_full().h(1.0).fill(hair())) + .child(col().w_full().px(32.0).pt(26.0).gap(20.0).child(header).child(list)); + + // The confirm sheet: a big liquid-metal button, centred, over the dimmed page. + let dim = ease(t_, TAP + 0.05, 0.3) * (1.0 - ease(t_, DISMISS, 0.3)); + let mut root = el().w(960.0).h(540.0) + .child(page.absolute(0.0, 0.0)) + .child(el().key("dim").absolute(0.0, 0.0).size(960.0, 540.0).backdrop_blur(10.0 * dim).fill(ca(0x000000, 0.68 * dim))); + if t_ >= TAP + 0.05 && t_ < DISMISS { + let press2 = pressed(t_, CONFIRM); + let flow2 = 1.0 + 1.8 * (if t_ > CONFIRM { (-(t_ - CONFIRM) as f32 * 1.6).exp() } else { 0.0 }); + let (bw, bh) = (372.0, 58.0); + let big = el().size(bw, bh).radius(bh / 2.0).scale(1.0 - 0.06 * press2) + .child(fx(CHROME, [5.0, 0.0, flow2, 0.0]).absolute(0.0, 0.0).size(bw, bh).radius(bh / 2.0)) + .child(row().absolute(0.0, 0.0).size(bw, bh).center().child(t("Deploy", 18.0, 600.0, 0x0e0f12))) + .child(fx(SPARKLES, [CONFIRM as f32 + 0.06, 14.0, 11.0, 0.0]).absolute(0.0, 0.0).size(bw, bh).radius(bh / 2.0).effect_bleed(60.0)); + let sheet = col().key("sheet").absolute(264.0, 150.0).w(432.0).padding(30.0).gap(8.0).radius(24.0) + .fill(c(0x151518)).border(1.0, ca(0xffffff, 0.1)).shadow(24.0, 60.0, ca(0x000000, 0.6)) + .transition(Transition::scale(0.9).combined(Transition::opacity())) + .child(row().gap(10.0).center_y().child(dot(0x34d399, 8.0)).child(t("Production", 12.5, 600.0, 0x6ee7b7))) + .child(t("Deploy rune to production?", 21.0, 600.0, TEXT)) + .child(row().gap(8.0).center_y().child(mono("dev", 12.0, MUTED)).child(t("·", 12.0, 400.0, FAINT)).child(mono("ba5b054", 12.0, MUTED)).child(t("·", 12.0, 400.0, FAINT)).child(t("README: a 30 second showcase", 13.0, 400.0, MUTED))) + .child(el().h(18.0)) + .child(big); + root = root.child(sheet); + } + root.child(pointer_at(t_, [560.0, 420.0], &[(0.12, 861.0, 33.0), (1.0, 500.0, 333.0)], &[TAP, CONFIRM])) +} diff --git a/app/vendor/rune/examples/showreel/src/scenes/fire.rs b/app/vendor/rune/examples/showreel/src/scenes/fire.rs new file mode 100644 index 0000000..04f1757 --- /dev/null +++ b/app/vendor/rune/examples/showreel/src/scenes/fire.rs @@ -0,0 +1,68 @@ +//! Friday, 4:58 PM. A release card with a Ship it button; pressing it sets the card on fire +//! (simulated flames and embers off its top edge, heat haze above). + +use rune::{Cx, El, col, el, row, spacer}; + +use crate::gfx::{FIRE, GLOW, HAZE}; +use crate::kit::*; +use crate::State; + +const TAP: f64 = 0.95; + +fn channel(name: &str, on: bool) -> El { + row().w_full().h(30.0).px(12.0).radius(8.0).center_y().gap(8.0) + .fill(if on { ca(0xffffff, 0.07) } else { ca(0, 0.0) }) + .child(t("#", 14.0, 500.0, FAINT)) + .child(t(name, 13.5, if on { 600.0 } else { 450.0 }, if on { TEXT } else { MUTED })) +} + +fn msg(who: u32, name: &str, time: &str, body: &str) -> El { + row().w_full().gap(12.0) + .child(avatar("", who, 30.0)) + .child(col().gap(4.0).child(row().gap(8.0).center_y().child(t(name, 13.5, 600.0, TEXT)).child(t(time, 12.0, 400.0, FAINT))).child(t(body, 13.5, 400.0, 0xc9c9d0))) +} + +pub fn view(s: &State, _: &mut Cx<State>) -> El { + let t_ = s.t; + let press = pressed(t_, TAP); + let blaze = ease(t_, TAP, 0.5); + let flame = 0.18 + 1.25 * blaze; + + let mut side = col().w(220.0).h(H).px(12.0).pt(22.0).gap(2.0).fill(c(0x101013)).border(1.0, hair()); + side = side.child(row().px(12.0).pb(16.0).gap(10.0).center_y().child(el().size(22.0, 22.0).radius(6.0).fill(c(0xff7a1a))).child(t("Anomaly", 14.0, 600.0, TEXT))); + for (i, ch) in ["general", "releases", "incidents", "design", "random"].iter().enumerate() { + side = side.child(channel(ch, i == 1)); + } + + let cx0 = 220.0 + (W - 220.0 - 460.0) / 2.0; + let cy0 = 250.0; + let card = col().absolute(cx0, cy0).w(460.0).h(220.0).padding(24.0).gap(10.0).radius(18.0).fill(c(0x1c1b1f)).border(1.0, ca(0xffffff, 0.09)) + .shadow(18.0, 40.0, ca(0x000000, 0.5)) + .child(row().gap(10.0).center_y().child(t("Release", 12.0, 600.0, 0xff9a5a)).child(spacer()).child(mono("v2.0.0", 12.0, MUTED))) + .child(t("Ship v2.0 to production", 22.0, 600.0, TEXT)) + .child(t("Friday · 4:58 PM · 214 files changed", 13.5, 400.0, MUTED)) + .child(spacer()) + .child( + row().w_full().gap(10.0) + .child(spacer()) + .child(row().h(38.0).px(18.0).radius(10.0).center().fill(ca(0xffffff, 0.06)).child(t("Not today", 13.5, 500.0, MUTED))) + .child( + row().h(38.0).px(20.0).radius(10.0).center().scale(1.0 - 0.07 * press).fill(c(0xff5a1f)) + .child(t(if t_ >= TAP { "Shipping…" } else { "Ship it" }, 13.5, 600.0, 0xffffff)), + ), + ); + + let thread = col().absolute(220.0 + 40.0, 40.0).w(W - 300.0).gap(18.0) + .child(msg(0x7c5cff, "mira", "4:51 PM", "all green on dev, release notes are in")) + .child(msg(0x34d399, "kai", "4:55 PM", "it's friday. it's 4:55. are we sure")) + .child(msg(0xff7a1a, "ode", "4:57 PM", "rune renders it at 120 Hz, what could go wrong")); + + el().w(W).h(H).fill(c(BG)) + .child(side.absolute(0.0, 0.0)) + .child(thread) + .child(fx(GLOW, [0.0, 8.0, 0.25 + 0.9 * blaze, 30.0]).absolute(cx0, cy0).size(460.0, 220.0).radius(18.0).effect_bleed(80.0)) + .child(fx(FIRE, [64.0 + 70.0 * blaze, flame, 0.0, 0.6]).absolute(cx0, cy0).size(460.0, 220.0).radius(18.0).effect_bleed(200.0)) + .child(card) + .child(fx(HAZE, [150.0, 1.6 * blaze, 0.0, 0.0]).effect_backdrop(true).absolute(cx0 - 10.0, cy0 - 170.0).size(480.0, 180.0)) + .child(pointer_at(t_, [700.0, 520.0], &[(0.25, cx0 + 400.0, cy0 + 182.0)], &[TAP])) +} diff --git a/app/vendor/rune/examples/showreel/src/scenes/glass.rs b/app/vendor/rune/examples/showreel/src/scenes/glass.rs new file mode 100644 index 0000000..695bf63 --- /dev/null +++ b/app/vendor/rune/examples/showreel/src/scenes/glass.rs @@ -0,0 +1,70 @@ +//! Now playing: the cover is a live mesh gradient under a huge title and a moving waveform. A +//! slab of fluted glass slides in over all of it and the queue settles onto the glass. + +use rune::{Cx, El, col, el, row, spacer}; + +use crate::gfx::{FLUTED, MESH}; +use crate::kit::*; +use crate::State; + +const QUEUE: [(&str, &str, &str, u32); 5] = [ + ("Low Light", "Kaito Hayes", "3:41", 7), + ("Glass Hours", "Mira Sol", "4:02", 1), + ("Afterimage", "Sunday Static", "2:57", 5), + ("Paper Moons", "Kaito Hayes", "3:18", 4), + ("Slow Signal", "Ode Park", "5:06", 6), +]; + +pub fn view(s: &State, _: &mut Cx<State>) -> El { + let t_ = s.t; + let mut root = el().w(W).h(H).fill(c(0x120a1e)); + root = root.child(fx(MESH, [7.0, 0.55, 3.0, 0.22]).absolute(0.0, 0.0).size(W, H)); + + // A waveform across the whole width, so the glass has something moving behind it. + let mut wave = row().absolute(40.0, 400.0).w(W - 40.0).h(80.0).gap(4.0).items_end(); + for i in 0..112 { + let x = i as f32; + let h = 10.0 + 34.0 * (0.5 + 0.5 * (x * 0.37 + t_ as f32 * 5.1).sin()) * (0.55 + 0.45 * (x * 0.11 - t_ as f32 * 2.3).sin().abs()); + wave = wave.child(el().w(4.0).h(h).radius(2.0).fill(ca(0xffffff, if x < 44.0 { 0.85 } else { 0.5 }))); + } + root = root.child(wave); + + let title = col().absolute(48.0, 120.0) + .gap(6.0) + .child(ta("NOW PLAYING", 12.0, 600.0, 0xffffff, 0.75)) + .child(t("Night Drive", 128.0, 600.0, 0xffffff)) + .child(ta("Kaito Hayes · Low Light Sessions", 20.0, 500.0, 0xffffff, 0.8)); + root = root.child(title); + + let progress = 0.38 + 0.02 * t_ as f32; + root = root.child( + row().absolute(48.0, 496.0).w(470.0).gap(12.0).center_y() + .child(mono("1:42", 12.0, 0xffffff)) + .child(el().w(380.0).h(4.0).radius(2.0).fill(ca(0xffffff, 0.25)).child(el().absolute(0.0, 0.0).h(4.0).w(380.0 * progress).radius(2.0).fill(c(0xffffff)))) + .child(mono("3:58", 12.0, 0xffffff)), + ); + + // The slab slides in from the right edge on a spring. + let x = track(t_, W + 10.0, &[(0.35, 548.0, sp(0.95, 0.12))]); + let gw = W - 548.0; + let mut queue = col().absolute(x, 0.0).w(gw).h(H).pt(54.0).px(34.0).gap(4.0); + let head = ease(t_, 0.95, 0.4); + queue = queue.child( + row().w_full().mb(14.0).offset(0.0, 10.0 * (1.0 - head)) + .child(ta("Up next", 22.0, 600.0, 0xffffff, head)) + .child(spacer()) + .child(ta("Shuffle", 13.0, 500.0, 0xffffff, 0.7 * head)), + ); + for (i, (name, artist, dur, pal)) in QUEUE.iter().enumerate() { + let k = track(t_, 0.0, &[(1.05 + i as f64 * 0.07, 1.0, sp(0.5, 0.2))]); + queue = queue.child( + row().w_full().h(68.0).gap(14.0).center_y().offset(24.0 * (1.0 - k), 0.0) + .child(fx(MESH, [*pal as f32, 0.4, i as f32 + 5.0, 0.0]).size(48.0 * k.clamp(0.0, 1.0), 48.0 * k.clamp(0.0, 1.0)).radius(10.0)) + .child(col().gap(4.0).grow(1.0).child(ta(*name, 15.0, 600.0, 0xffffff, k)).child(ta(*artist, 13.0, 400.0, 0xffffff, 0.7 * k))) + .child(mono_a(*dur, 12.0, 0xffffff, 0.8 * k)), + ); + } + root.child(fx(FLUTED, [18.0, 16.0, 0.12, 0.3]).effect_backdrop(true).absolute(x, 0.0).size(gw + 10.0, H)) + .child(el().absolute(x, 0.0).w(1.0).h(H).fill(ca(0xffffff, 0.35))) + .child(queue) +} diff --git a/app/vendor/rune/examples/showreel/src/scenes/keys.rs b/app/vendor/rune/examples/showreel/src/scenes/keys.rs new file mode 100644 index 0000000..9827e19 --- /dev/null +++ b/app/vendor/rune/examples/showreel/src/scenes/keys.rs @@ -0,0 +1,106 @@ +//! A pad controller playing a boom-bap pattern at 90 BPM: glossy plastic keys, two liquid-metal +//! keys, each press springing down and lighting up. + +use rune::{Cx, El, col, el, row}; + +use crate::gfx::{CHROME, GLOW, PLASTIC}; +use crate::kit::*; +use crate::State; + +const EIGHTH: f64 = 60.0 / 90.0 / 2.0; +/// (colour index, label) per key; colour 99 is liquid metal. +const KEYS: [(u32, &str); 16] = [ + (10, "A"), (9, "B"), (9, "C"), (9, "D"), (10, "E"), (12, "F"), (99, "G"), (10, "H"), + (11, "KICK"), (10, "I"), (9, "J"), (10, "K"), (12, "SNR"), (9, "L"), (99, "M"), (11, "FX"), +]; +const LIGHT: [u32; 16] = [0, 9, 9, 9, 0, 12, 0, 0, 11, 0, 9, 0, 12, 9, 0, 11]; + +fn hits(n: i64) -> Vec<usize> { + let mut v = Vec::new(); + let m = n.rem_euclid(16); + if [0, 3, 5, 8, 11, 13].contains(&m) { + v.push(8); + } + if m % 4 == 2 { + v.push(12); + } + v.push(if m % 2 == 0 { 2 } else { 1 }); + if m == 7 || m == 15 { + v.push(6); + } + if m == 14 { + v.push(14); + } + if m == 10 { + v.push(5); + } + if m == 6 { + v.push(13); + } + v +} + +fn press_of(t: f64, key: usize) -> f32 { + let now = (t / EIGHTH).floor() as i64; + let mut p = 0.0f32; + for n in (now - 3)..=now { + if n < 0 { + continue; + } + if hits(n).contains(&key) { + p = p.max(pressed(t, n as f64 * EIGHTH)); + } + } + p +} + +pub fn view(s: &State, _: &mut Cx<State>) -> El { + let t_ = s.t; + let (bw, bh) = (864.0, 384.0); + let (bx, by) = ((W - bw) / 2.0, (H - bh) / 2.0 + 4.0); + let key = 86.0; + let gap = 12.0; + let kx0 = bx + (bw - 8.0 * key - 7.0 * gap) / 2.0; + let ky0 = by + 152.0; + + let bar = 12 + (t_ / (EIGHTH * 8.0)) as i64; + let display = col().absolute(kx0, by + 38.0).w(230.0).h(70.0).px(16.0).justify_center().gap(4.0).radius(12.0).fill(c(0x050506)).border(1.0, ca(0xffffff, 0.05)) + .child(row().gap(8.0).items_end().child(mono("90", 30.0, 0x5df2a8)).child(mono("BPM", 13.0, 0x5df2a8).mb(5.0))) + .child(mono(format!("pattern A · bar {bar}"), 11.0, 0x3c9b6c)); + + let mut root = el().w(W).h(H).linear_gradient(1.57, [(0.0, c(0x17161a)), (1.0, c(0x0a0a0b))]) + .child(el().absolute(bx, by).size(bw, bh).radius(30.0).linear_gradient(1.57, [(0.0, c(0x232227)), (1.0, c(0x161619))]).border(1.0, ca(0xffffff, 0.08)).shadow(30.0, 60.0, ca(0x000000, 0.6))) + .child(display) + .child(col().absolute(bx + bw - (kx0 - bx) - 120.0, by + 44.0).w(120.0).items_end().gap(8.0).child(t("PAD-16", 13.0, 600.0, 0x8a8a93)).child(row().gap(6.0).center_y().child(dot(0xff5a4d, 7.0)).child(t("REC", 12.0, 600.0, 0xff5a4d)))); + + // Knobs that turn slowly. + for i in 0..4 { + let kx = kx0 + 280.0 + i as f32 * 70.0; + let ky = by + 46.0; + let ang = (t_ as f32 * 0.9 + i as f32 * 1.3).sin() * 2.2 - std::f32::consts::FRAC_PI_2; + let (dx, dy) = (ang.cos() * 16.0, ang.sin() * 16.0); + root = root.child(fx(PLASTIC, [10.0, 0.35, 0.7, 10.0]).absolute(kx, ky).size(54.0, 54.0).radius(27.0)) + .child(dot(0xf1ece1, 6.0).absolute(kx + 27.0 + dx - 3.0, ky + 27.0 + dy - 3.0)); + } + + for (i, (col_, label)) in KEYS.iter().enumerate() { + let (cx, cy) = ((i % 8) as f32, (i / 8) as f32); + let p = press_of(t_, i); + let x = kx0 + cx * (key + gap); + let y = ky0 + cy * (key + gap) + 3.0 * p; + let size = key * (1.0 - 0.04 * p); + let off = (key - size) / 2.0; + let dark = matches!(*col_, 10 | 99); + let face = if *col_ == 99 { + fx(CHROME, [0.0, 0.0, 1.4, 1.0]) + } else { + fx(PLASTIC, [*col_ as f32, 0.22, 0.35, 7.0]) + }; + root = root + .child(el().absolute(x, ky0 + cy * (key + gap) + 5.0).size(key, key).radius(14.0).fill(ca(0x000000, 0.45))) + .child(fx(GLOW, [0.0, LIGHT[i] as f32, 1.4 * p, 16.0]).absolute(x + off, y + off).size(size, size).radius(14.0).effect_bleed(50.0)) + .child(face.absolute(x + off, y + off).size(size, size).radius(14.0)) + .child(el().absolute(x + off + 10.0, y + off + 8.0).child(ta(*label, 11.5, 600.0, if dark && *col_ != 99 { 0xb9b9c2 } else { 0x2a2a2e }, 0.85))); + } + root +} diff --git a/app/vendor/rune/examples/showreel/src/scenes/mod.rs b/app/vendor/rune/examples/showreel/src/scenes/mod.rs new file mode 100644 index 0000000..5d836c0 --- /dev/null +++ b/app/vendor/rune/examples/showreel/src/scenes/mod.rs @@ -0,0 +1,10 @@ +pub mod ask; +pub mod deploy; +pub mod fire; +pub mod glass; +pub mod keys; +pub mod pricing; +pub mod shock; +pub mod tabs; +pub mod type_; +pub mod word; diff --git a/app/vendor/rune/examples/showreel/src/scenes/pricing.rs b/app/vendor/rune/examples/showreel/src/scenes/pricing.rs new file mode 100644 index 0000000..24a4257 --- /dev/null +++ b/app/vendor/rune/examples/showreel/src/scenes/pricing.rs @@ -0,0 +1,65 @@ +//! A pricing page. The Pro card hums with a charged border; hovering charges it up, and Upgrade +//! throws an electric border round it with a burst of sparks. + +use rune::{Cx, El, col, el, row, spacer}; + +use crate::gfx::{ELECTRIC, GLOW, SPARKLES}; +use crate::kit::*; +use crate::State; + +const HOVER: f64 = 0.55; +const TAP: f64 = 1.25; + +fn feature(s: &str, on: bool) -> El { + row().gap(10.0).center_y() + .child(el().size(16.0, 16.0).radius(8.0).center().fill(if on { ca(0x54b3fd, 0.18) } else { ca(0xffffff, 0.06) }).child(dot(if on { 0x54b3fd } else { 0x8a8a93 }, 5.0))) + .child(t(s, 13.5, 400.0, 0xc9c9d0)) +} + +fn plan(name: &str, price: &str, blurb: &str, feats: [&str; 4], cta: &str, pro: bool, press: f32) -> El { + let mut c_ = col().w(268.0).h(318.0).padding(24.0).gap(8.0).radius(20.0) + .fill(if pro { c(0x16181f) } else { c(0x121215) }) + .border(1.0, if pro { ca(0x54b3fd, 0.35) } else { hair() }) + .child(row().w_full().center_y().child(t(name, 15.0, 600.0, TEXT)).child(spacer()).child(if pro { + el().px(8.0).py(3.0).radius(8.0).fill(ca(0x54b3fd, 0.16)).child(t("Popular", 11.5, 600.0, 0x8fd0ff)) + } else { + el() + })) + .child(row().mt(6.0).items_end().gap(4.0).child(t(price, 40.0, 600.0, TEXT)).child(t("/mo", 14.0, 500.0, MUTED).mb(8.0))) + .child(t(blurb, 13.0, 400.0, MUTED).mb(10.0)); + for (i, f) in feats.iter().enumerate() { + c_ = c_.child(feature(f, pro || i < 2)); + } + c_.child(spacer()).child( + row().w_full().h(40.0).radius(11.0).center().scale(1.0 - 0.06 * press) + .fill(if pro { c(0xeef4ff) } else { ca(0xffffff, 0.07) }) + .child(t(cta, 14.0, 600.0, if pro { 0x0e1320 } else { TEXT })), + ) +} + +pub fn view(s: &State, _: &mut Cx<State>) -> El { + let t_ = s.t; + let hover = ease(t_, HOVER, 0.35); + let hit = ease(t_, TAP, 0.08); + let press = pressed(t_, TAP); + let x0 = (W - 3.0 * 268.0 - 2.0 * 22.0) / 2.0; + let y0 = 176.0; + let px_ = x0 + 268.0 + 22.0; + let lift = track(t_, 0.0, &[(HOVER, 1.0, sp(0.45, 0.3))]); + + let header = col().absolute(0.0, 54.0).w(W).items_center().gap(10.0) + .child(t("PRICING", 12.0, 600.0, 0x54b3fd)) + .child(t("Plans that scale with you", 32.0, 600.0, TEXT)) + .child(t("Start free. Upgrade when your team needs more.", 15.0, 400.0, MUTED)); + + let pro_y = y0 - 8.0 * lift; + el().w(W).h(H).fill(c(0x0a0a0c)) + .child(header) + .child(plan("Hobby", "$0", "For side projects and prototypes.", ["One project", "Preview deploys", "Community support", "Analytics"], "Get started", false, 0.0).absolute(x0, y0)) + .child(plan("Team", "$60", "For studios shipping together.", ["Unlimited projects", "SSO and audit log", "Analytics", "Priority support"], "Contact us", false, 0.0).absolute(x0 + 2.0 * (268.0 + 22.0), y0)) + .child(fx(GLOW, [1.0, 13.0, 0.35 + 0.5 * hover + 0.8 * hit, 22.0]).absolute(px_, pro_y).size(268.0, 318.0).radius(20.0).effect_bleed(60.0)) + .child(plan("Pro", "$20", "For apps people use every day.", ["Unlimited projects", "Custom domains", "Team analytics", "Priority builds"], "Upgrade", true, press).absolute(px_, pro_y)) + .child(fx(ELECTRIC, [0.5 + 0.7 * hover + 0.4 * hit, if t_ >= TAP { 6.0 } else { 0.0 }, if t_ >= TAP { 0.0 } else { 1.0 }, 13.0]).absolute(px_, pro_y).size(268.0, 318.0).radius(20.0).effect_bleed(40.0)) + .child(fx(SPARKLES, [TAP as f32 + 0.05, 14.0, 10.0, 13.0]).absolute(px_ + 24.0, pro_y + 254.0).size(220.0, 40.0).radius(11.0).effect_bleed(60.0)) + .child(pointer_at(t_, [960.0, 560.0], &[(0.12, px_ + 180.0, pro_y + 140.0), (0.75, px_ + 140.0, y0 + 272.0)], &[TAP])) +} diff --git a/app/vendor/rune/examples/showreel/src/scenes/shock.rs b/app/vendor/rune/examples/showreel/src/scenes/shock.rs new file mode 100644 index 0000000..c107657 --- /dev/null +++ b/app/vendor/rune/examples/showreel/src/scenes/shock.rs @@ -0,0 +1,51 @@ +//! A photo library of live gradients. Taps send shockwaves through the whole window, on the beat. + +use rune::{Cx, El, col, el, row, spacer}; + +use crate::gfx::{MESH, SHOCK}; +use crate::kit::*; +use crate::State; + +/// Taps: time and grid cell (column, row). 0.6667 s apart, a beat at 90 BPM. +const TAPS: [(f64, usize, usize); 3] = [(0.5, 2, 1), (1.1667, 0, 2), (1.8333, 4, 0)]; + +pub fn view(s: &State, _: &mut Cx<State>) -> El { + let t_ = s.t; + let (cols, rows) = (5usize, 3usize); + let (gx, gy, gap) = (28.0, 92.0, 10.0); + let tw = (W - 2.0 * gx - gap * (cols as f32 - 1.0)) / cols as f32; + let th = (H - gy - 24.0 - gap * (rows as f32 - 1.0)) / rows as f32; + + let seg = ["Years", "Months", "Days", "All Photos"]; + let sel = track(t_, 3.0, &[(0.25, 2.0, sp(0.45, 0.25))]); + let mut seg_row = el().h(34.0).w(4.0 * 92.0 + 8.0).radius(10.0).fill(ca(0xffffff, 0.06)) + .child(el().absolute(4.0 + sel * 92.0, 4.0).size(92.0, 26.0).radius(7.0).fill(ca(0xffffff, 0.14))); + for (i, name) in seg.iter().enumerate() { + seg_row = seg_row.child(row().absolute(4.0 + i as f32 * 92.0, 4.0).size(92.0, 26.0).center().child(t(*name, 13.0, 500.0, if (sel - i as f32).abs() < 0.5 { TEXT } else { MUTED }))); + } + let header = row().absolute(gx, 28.0).w(W - 2.0 * gx).center_y() + .child(col().gap(3.0).child(t("Library", 24.0, 600.0, TEXT)).child(t("1,284 photos · 3 albums", 13.0, 400.0, MUTED))) + .child(spacer()) + .child(seg_row); + + let mut root = el().w(W).h(H).fill(c(0x08080a)).child(header); + for r in 0..rows { + for cc in 0..cols { + let i = r * cols + cc; + let press = TAPS.iter().filter(|(_, x, y)| *x == cc && *y == r).map(|(tp, _, _)| pressed(t_, *tp)).fold(0.0f32, f32::max); + let x = gx + cc as f32 * (tw + gap); + let y = gy + r as f32 * (th + gap); + root = root.child(fx(MESH, [(i % 8) as f32, 0.5, i as f32, 0.25]).key(format!("tile-{i}")).absolute(x, y).size(tw, th).radius(12.0).scale(1.0 - 0.06 * press)); + } + } + // Always in the tree (an idle shockwave draws nothing), so no slot enters inside a fade layer, + // where its backdrop would be the empty layer. + for (tp, cc, r) in TAPS { + let x = gx + cc as f32 * (tw + gap) + tw / 2.0; + let y = gy + r as f32 * (th + gap) + th / 2.0; + root = root.child(fx(SHOCK, [x, y, tp as f32 + 0.03, 22.0]).key(format!("shock-{cc}-{r}")).effect_backdrop(true).absolute(0.0, 0.0).size(W, H)); + } + let path: Vec<(f64, f32, f32)> = TAPS.iter().map(|(tp, cc, r)| (tp - 0.42, gx + *cc as f32 * (tw + gap) + tw / 2.0, gy + *r as f32 * (th + gap) + th / 2.0)).collect(); + let taps: Vec<f64> = TAPS.iter().map(|x| x.0).collect(); + root.child(pointer_at(t_, [700.0, 500.0], &path, &taps)) +} diff --git a/app/vendor/rune/examples/showreel/src/scenes/tabs.rs b/app/vendor/rune/examples/showreel/src/scenes/tabs.rs new file mode 100644 index 0000000..2002289 --- /dev/null +++ b/app/vendor/rune/examples/showreel/src/scenes/tabs.rs @@ -0,0 +1,56 @@ +//! A feed scrolling under a floating liquid-glass tab bar. The selection is a drop of the same +//! glass that slides between tabs and bulges out of the bar as it goes. + +use rune::{Cx, El, col, el, row}; + +use crate::gfx::{LENS, MESH}; +use crate::kit::*; +use crate::State; + +const STORIES: [(&str, &str, u32); 6] = [ + ("Kyoto after rain", "Photo essay · 12 min", 1), + ("The quiet studio", "Design · 6 min", 7), + ("Night markets", "Travel · 9 min", 5), + ("Ferry to Naoshima", "Photo essay · 8 min", 4), + ("Paper and light", "Craft · 5 min", 2), + ("Cold coast", "Travel · 11 min", 6), +]; + +fn story(title: &str, meta: &str, pal: u32, w: f32, h: f32, seed: f32) -> El { + col().w(w).gap(10.0) + .child(fx(MESH, [pal as f32, 0.5, seed, 0.25]).w(w).h(h).radius(18.0)) + .child(t(title, 17.0, 600.0, TEXT)) + .child(t(meta, 13.0, 400.0, MUTED)) +} + +pub fn view(s: &State, _: &mut Cx<State>) -> El { + let t_ = s.t; + // The feed scrolls on its own, with a flick a second in. + let scroll = 50.0 * t_ as f32 + track(t_, 0.0, &[(0.9, 260.0, sp(1.1, 0.0))]); + let mut feed = col().absolute(40.0, 30.0 - scroll).w(W - 80.0).gap(28.0) + .child(col().gap(4.0).child(t("Today", 30.0, 600.0, TEXT)).child(t("Friday, November 6", 14.0, 500.0, MUTED))) + .child(story("Glass, light and the long weekend", "Featured · 14 min", 0, W - 80.0, 300.0, 1.0)); + for pair in STORIES.chunks(3) { + let mut r = row().gap(20.0); + for (i, (title, meta, pal)) in pair.iter().enumerate() { + r = r.child(story(title, meta, *pal, (W - 80.0 - 40.0) / 3.0, 180.0, 10.0 + i as f32 + *pal as f32)); + } + feed = feed.child(r); + } + + // The bar and its selection drop. + let (bw, bh) = (400.0, 64.0); + let (bx, by) = ((W - bw) / 2.0, H - bh - 26.0); + let tabs = ["Today", "Search", "Saved", "Profile"]; + let slot = bw / 4.0; + let sel = track(t_, 0.0, &[(0.55, 2.0, sp(0.7, 0.28)), (1.75, 1.0, sp(0.6, 0.3))]); + let sx = bx + slot * (sel + 0.5); + let mut root = el().w(W).h(H).fill(c(0x0b0b0d)).child(feed) + .child(fx(LENS, [sx, by + bh / 2.0, 42.0, 0.2]).effect_backdrop(true).absolute(bx, by).size(bw, bh).radius(bh / 2.0)) + .child(fx(LENS, [0.0, 0.0, 0.0, 0.25]).effect_backdrop(true).absolute(bx + bw + 16.0, by).size(bh, bh).radius(bh / 2.0)); + for (i, name) in tabs.iter().enumerate() { + let on = (sel - i as f32).abs() < 0.5; + root = root.child(row().absolute(bx + slot * i as f32, by).size(slot, bh).center().child(t(*name, 13.5, 600.0, if on { 0xffffff } else { 0xd8d8de }))); + } + root.child(row().absolute(bx + bw + 16.0, by).size(bh, bh).center().child(t("+", 26.0, 400.0, 0xffffff))) +} diff --git a/app/vendor/rune/examples/showreel/src/scenes/type_.rs b/app/vendor/rune/examples/showreel/src/scenes/type_.rs new file mode 100644 index 0000000..23399c4 --- /dev/null +++ b/app/vendor/rune/examples/showreel/src/scenes/type_.rs @@ -0,0 +1,93 @@ +//! A writing app: a note on type. The last line types itself under a blinking caret, then a +//! double click selects two words and a format bar springs up over them. Made for macro shots +//! (`--scale 6`), where the glyph edges are the subject. + +use rune::{Cx, El, TextStyle, col, el, row, text}; + +use crate::kit::*; +use crate::State; + +const TITLE: &str = "Small type, sharp edges"; +const LINES: [&str; 2] = ["Good interfaces are mostly text. Labels, numbers,", "code and long reading all live or die by the edge"]; +const TYPED: (&str, &str, &str) = ("of ", "every glyph", ", and where it lands on the pixel."); +const TYPE_FROM: f64 = 0.5; +const TYPE_RATE: f64 = 16.0; +const SELECT: f64 = 3.9; + +const BODY: f32 = 17.0; +const INK: u32 = 0xc9cad1; + +fn body(s: impl Into<String>, color: u32) -> El { + text(s).font(TextStyle::new(BODY, 400.0)).color(c(color)) +} + +fn caret(t_: f64, typing: bool) -> El { + let on = typing || ((t_ * 1.8) as i64) % 2 == 0; + el().w(2.0).h(22.0).radius(1.0).fill(ca(0x8ab4ff, if on { 1.0 } else { 0.0 })) +} + +fn format_bar(k: f32) -> El { + let item = |s: &str, w: f32, on: bool| { + row().size(30.0, 28.0).radius(7.0).center().fill(ca(0xffffff, if on { 0.1 } else { 0.0 })) + .child(text(s).font(TextStyle::new(14.0, w)).color(c(if on { 0xffffff } else { 0xb4b6bf }))) + }; + row().key("format").h(38.0).px(5.0).gap(2.0).radius(11.0).center_y() + .fill(c(0x1d1e23)).border(1.0, ca(0xffffff, 0.1)).shadow(10.0, 28.0, ca(0x000000, 0.55)) + .scale(0.86 + 0.14 * k).opacity(k.clamp(0.0, 1.0)) + .child(item("B", 700.0, true)) + .child(item("I", 400.0, false)) + .child(item("U", 400.0, false)) + .child(el().w(1.0).h(18.0).mx(4.0).fill(ca(0xffffff, 0.12))) + .child(item("Aa", 500.0, false)) + .child(item("“", 500.0, false)) +} + +pub fn view(s: &State, _: &mut Cx<State>) -> El { + let t_ = s.t; + let full = format!("{}{}{}", TYPED.0, TYPED.1, TYPED.2); + let n = (((t_ - TYPE_FROM) * TYPE_RATE).max(0.0) as usize).min(full.chars().count()); + let typing = n < full.chars().count(); + let sel = track(t_, 0.0, &[(SELECT, 1.0, sp(0.3, 0.0))]); + let bar = track(t_, 0.0, &[(SELECT + 0.12, 1.0, sp(0.45, 0.32))]); + + let last = if t_ < SELECT { + let typed: String = full.chars().take(n).collect(); + row().h(28.0).center_y().child(body(typed, INK)).child(caret(t_, typing)) + } else { + row().h(28.0).center_y() + .child(body(TYPED.0, INK)) + .child(el().radius(3.0).fill(ca(0x3b82f6, 0.42 * sel)).child(body(TYPED.1, 0xffffff))) + .child(body(TYPED.2, INK)) + }; + + let mut doc = col().key("doc").absolute(200.0, 130.0).w(600.0).gap(0.0) + .child(row().gap(8.0).center_y() + .child(text("Notes").font(TextStyle::new(12.5, 500.0)).color(c(FAINT))) + .child(text("/").font(TextStyle::new(12.5, 400.0)).color(c(0x45454c))) + .child(text("Typography").font(TextStyle::new(12.5, 500.0)).color(c(MUTED)))) + .child(el().h(22.0)) + .child(text(TITLE).font(TextStyle { tracking: -0.9, ..TextStyle::new(40.0, 600.0) }).color(c(0xf3f3f5))) + .child(el().h(10.0)) + .child(row().gap(10.0).center_y() + .child(avatar("", 0x7c5cff, 18.0)) + .child(text("Mira Chen").font(TextStyle::new(13.0, 500.0)).color(c(MUTED))) + .child(text("·").font(TextStyle::new(13.0, 400.0)).color(c(FAINT))) + .child(text("4 min read").font(TextStyle::new(13.0, 400.0)).color(c(FAINT)))) + .child(el().h(26.0)); + for l in LINES { + doc = doc.child(row().h(28.0).center_y().child(body(l, INK))); + } + doc = doc.child(last); + doc = doc.child(el().h(24.0)).child( + row().gap(10.0).center_y() + .child(el().px(8.0).py(3.0).radius(6.0).fill(ca(0xffffff, 0.06)).child(mono("font-feature-settings: \"tnum\"", 12.5, 0x9ecbff))) + .child(text("0123456789").font(TextStyle::new(13.0, 500.0)).color(c(MUTED))), + ); + + let mut root = el().w(W).h(H).fill(c(0x0b0b0d)).child(doc); + if t_ >= SELECT + 0.1 { + // Centred over the selected words on the third body line. + root = root.child(row().key("format-at").absolute(181.0, 284.0 - 6.0 * (1.0 - bar)).child(format_bar(bar))); + } + root +} diff --git a/app/vendor/rune/examples/showreel/src/scenes/word.rs b/app/vendor/rune/examples/showreel/src/scenes/word.rs new file mode 100644 index 0000000..076562a --- /dev/null +++ b/app/vendor/rune/examples/showreel/src/scenes/word.rs @@ -0,0 +1,93 @@ +//! ᚱUNE, the wordmark from the site's pixel grid, built from liquid-metal tiles that spring in +//! along the letters and then flow as one surface. `card` adds the repository line under it. + +use rune::{Cx, El, el}; + +use crate::gfx::CHROME; +use crate::kit::*; +use crate::State; + +const GLYPHS: [&str; 4] = [ + "###....|####...|##.##..|##..##.|##..##.|##.##..|####...|##.##..|##..##.|##...##|##...##", + "##...##|##...##|##...##|##...##|##...##|##...##|##...##|##...##|##...##|#######|.#####.", + "###...##|####..##|####..##|####..##|##.##.##|##.##.##|##.##.##|##..####|##..####|##..####|##...###", + "######|######|##....|##....|#####.|#####.|##....|##....|##....|######|######", +]; + +fn ink(rows: &[&str], dx: i32) -> Vec<(i32, i32)> { + let mut v = Vec::new(); + for (y, r) in rows.iter().enumerate() { + for (x, ch) in r.chars().enumerate() { + if ch == '#' { + v.push((x as i32 + dx, y as i32)); + } + } + } + v +} + +/// Every inked cell of the wordmark, letters fitted one clear pixel apart (diagonals included). +pub fn cells() -> (Vec<(i32, i32, usize)>, i32) { + let mut out: Vec<(i32, i32, usize)> = Vec::new(); + let mut at = 0; + let mut width = 0; + let mut prev: Option<Vec<(i32, i32)>> = None; + for (g, glyph) in GLYPHS.iter().enumerate() { + let rows: Vec<&str> = glyph.split('|').collect(); + let b = ink(&rows, 0); + if let Some(a) = &prev { + let mut x = at + 1; + while a.iter().any(|(ax, ay)| b.iter().any(|(bx, by)| (bx + x - ax).abs() <= 1 && (by - ay).abs() <= 1)) { + x += 1; + } + at = x; + } + let placed = ink(&rows, at); + out.extend(placed.iter().map(|&(x, y)| (x, y, g))); + width = at + rows[0].len() as i32; + prev = Some(placed); + } + (out, width) +} + +pub fn view(s: &State, _: &mut Cx<State>, card: bool) -> El { + let t = s.t; + let (cells, width) = cells(); + let cell = if card { 19.0 } else { 25.0 }; + let tile = cell - 1.0; + let total_w = width as f32 * cell; + let total_h = 11.0 * cell; + // A slow push in, about the frame's centre. + let zoom = if card { 1.0 } else { 1.0 + 0.05 * ease(t, 0.0, 4.0) }; + let ox = (W - total_w * zoom) / 2.0; + let oy = if card { 168.0 } else { (H - total_h * zoom) / 2.0 }; + let mut root = el().w(W).h(H).fill(c(0x000000)); + for &(x, y, g) in &cells { + // A wave left to right, each letter a beat behind the last, rows rippling down. + let delay = 0.08 + g as f64 * 0.11 + x as f64 * 0.012 + y as f64 * 0.018; + let k = track(t, 0.0, &[(delay, 1.0, sp(0.55, 0.38))]); + let size = tile * zoom * k.max(0.0); + let cx = ox + (x as f32 + 0.5) * cell * zoom; + let cy = oy + (y as f32 + 0.5) * cell * zoom; + if size < 0.5 { + continue; + } + root = root.child( + fx(CHROME, [4.0, 0.0, 1.25, 0.0]) + .key(format!("c{x}_{y}")) + .absolute(cx - size / 2.0, cy - size / 2.0) + .size(size, size) + .radius(2.5 * zoom * k), + ); + } + if card { + let a = ease(t, 0.9, 0.6); + root = root.child( + el().absolute(0.0, oy + total_h + 46.0 - 8.0 * a) + .w(W) + .center() + .child(mono_a("github.com/anomalyco/rune", 22.0, 0xb8bcc6, a)), + ); + } + root +} diff --git a/app/vendor/rune/examples/site-scenes/Cargo.toml b/app/vendor/rune/examples/site-scenes/Cargo.toml new file mode 100644 index 0000000..f0cb7d9 --- /dev/null +++ b/app/vendor/rune/examples/site-scenes/Cargo.toml @@ -0,0 +1,28 @@ +[package] +name = "site-scenes" +version = "0.0.1" +edition.workspace = true +license.workspace = true +publish = false +description = "Renders the material stills on Rune's home page headless: liquid metal, glass and light." + +[dependencies] +rune = { workspace = true, default-features = true } +rune-fx = { workspace = true } +rune-light = { workspace = true } +wgpu = { workspace = true, features = ["std", "parking_lot", "wgsl"] } + +[target.'cfg(target_vendor = "apple")'.dependencies] +wgpu = { workspace = true, features = ["metal"] } + +[target.'cfg(target_os = "windows")'.dependencies] +wgpu = { workspace = true, features = ["dx12"] } + +[target.'cfg(all(not(target_vendor = "apple"), not(target_arch = "wasm32"), not(target_os = "windows")))'.dependencies] +wgpu = { workspace = true, features = ["vulkan"] } + +[target.'cfg(target_arch = "wasm32")'.dependencies] +wgpu = { workspace = true, features = ["webgpu"] } + +[lints] +workspace = true diff --git a/app/vendor/rune/examples/site-scenes/src/main.rs b/app/vendor/rune/examples/site-scenes/src/main.rs new file mode 100644 index 0000000..402f1fc --- /dev/null +++ b/app/vendor/rune/examples/site-scenes/src/main.rs @@ -0,0 +1,351 @@ +//! The material stills on Rune's home page (`www/`), rendered headless at 2x: liquid metal from +//! rune-fx, and glass and light from rune-light, over frames drawn by Rune's own renderer. +//! +//! cargo run --release -p site-scenes -- [--out target/site-scenes] [--only NAME] [--t SECONDS] +//! +//! Each scene writes `<name>.png`, 1920 × 1080: one subject, centred and small, on the page's +//! black, in Rune blue and neutrals. + +#![forbid(unsafe_code)] + +use std::path::PathBuf; + +use rune::color::{Color, oklch, oklcha}; +use rune::render::{Gpu, Instance, KIND_RADIAL, KIND_RECT, KIND_SHADOW, NO_CLIP, Offscreen, Renderer, write_png}; +use rune::text::TextSystem; +use rune_fx::{FillAnchor, Fx, FxFrame, FxOptions, FxRenderer, LiquidMetalParams, Shape, rgb}; +use rune_light::{Gi, Glass, GlassLight, GlassRenderer, GlassSettings, Light, LightRenderer, Prim, Scene, Settings}; + +/// The canvas in points, and device px per point. +const W: f32 = 960.0; +const H: f32 = 540.0; +const S: f32 = 2.0; +const PW: u32 = (W * S) as u32; +const PH: u32 = (H * S) as u32; +const F16: wgpu::TextureFormat = wgpu::TextureFormat::Rgba16Float; +/// Rune blue's OKLCH hue. +const HUE: f32 = 245.0; + +const SCENES: [&str; 3] = ["metal", "glass", "light"]; + +// ------------------------------------------------------------------ painting + +fn px(r: [f32; 4]) -> [f32; 4] { + r.map(|v| v * S) +} + +fn lin(c: Color) -> [f32; 3] { + [c.r, c.g, c.b] +} + +fn inst(rect: [f32; 4], radius: f32, fill: [f32; 4], border: [f32; 4], params: [f32; 4], uv: [f32; 4]) -> Instance { + Instance { rect, radii: [radius; 4], fill, border, params, uv, clip: NO_CLIP, fade: [0; 4] } +} + +/// Rune instances in points, and the lighting primitives that go with them. +#[derive(Default)] +struct Paint { + out: Vec<Instance>, + prims: Vec<Prim>, +} + +impl Paint { + fn rect(&mut self, r: [f32; 4], radius: f32, c: Color) { + self.out.push(inst(px(r), radius * S, c.premul(1.0), [0.0; 4], [0.0, KIND_RECT, 0.0, 1.0], [0.0; 4])); + } + + /// A rect that is also a lighting primitive, configured by `light`. + fn solid(&mut self, r: [f32; 4], radius: f32, c: Color, light: impl FnOnce(Prim) -> Prim) { + self.rect(r, radius, c); + self.prims.push(light(Prim::from_rune(px(r), [radius * S; 4]).albedo(lin(c)))); + } + + /// A Gaussian shadow of a rounded rect, `sigma` in points. + fn shadow(&mut self, r: [f32; 4], radius: f32, sigma: f32, c: Color) { + self.out.push(inst(px(r), radius * S, c.premul(1.0), [0.0; 4], [0.0, KIND_SHADOW, sigma * S, 1.0], [0.0; 4])); + } + + /// An elliptical pool of colour that falls smoothly to nothing at (rx, ry). + fn pool(&mut self, cx: f32, cy: f32, rx: f32, ry: f32, c: Color) { + const N: usize = 16; + let f = |t: f32| (1.0 - t * t).max(0.0).powi(3); + let rect = px([cx - rx, cy - ry, 2.0 * rx, 2.0 * ry]); + for k in 0..N { + let (t0, t1) = (k as f32 / N as f32, (k + 1) as f32 / N as f32); + let open0 = if k > 0 { 2.0 } else { 0.0 }; + let open1 = if k + 1 < N { 2.0 } else { 0.0 }; + let uv = [rx * S, ry * S, rx * S, ry * S]; + self.out.push(inst(rect, 0.0, c.premul(f(t0)), c.premul(f(t1)), [t0 + open0, KIND_RADIAL, 0.0, t1 + open1], uv)); + } + } + + /// The page's black, with the faintest lift behind the subject. + fn backdrop(&mut self) { + self.pool(W * 0.5, H * 0.5, W * 0.62, H * 0.9, oklcha(0.2, 0.012, HUE, 0.5)); + } +} + +// ------------------------------------------------------------------ GPU + +fn target(device: &wgpu::Device, w: u32, h: u32, usage: wgpu::TextureUsages) -> wgpu::TextureView { + device + .create_texture(&wgpu::TextureDescriptor { + label: None, + size: wgpu::Extent3d { width: w, height: h, depth_or_array_layers: 1 }, + mip_level_count: 1, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + format: F16, + usage, + view_formats: &[], + }) + .create_view(&Default::default()) +} + +struct Ctx { + device: wgpu::Device, + queue: wgpu::Queue, + rune: Renderer, + ts: TextSystem, + /// The frame Rune draws (linear); effects draw onto it, glass and light read it. + base: wgpu::TextureView, + /// Glyphs only, for rune-light. These scenes have none. + text: wgpu::TextureView, + /// Glass output. + glassed: wgpu::TextureView, + black: wgpu::TextureView, + out: Offscreen, + resolve: wgpu::RenderPipeline, +} + +impl Ctx { + fn new() -> Ctx { + let Gpu { adapter, device, queue, .. } = Gpu::headless(); + eprintln!("adapter: {}", adapter.get_info().name); + let rt = wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING; + let base = target(&device, PW, PH, rt); + let text = target(&device, PW, PH, rt); + let glassed = target(&device, PW, PH, rt); + let black = target(&device, 1, 1, wgpu::TextureUsages::TEXTURE_BINDING); + let out = Offscreen::with_format(&device, PW, PH, wgpu::TextureFormat::Rgba8Unorm); + let rune = Renderer::new(&device, F16); + let module = device.create_shader_module(wgpu::ShaderModuleDescriptor { + label: Some("resolve"), + source: wgpu::ShaderSource::Wgsl(include_str!("resolve.wgsl").into()), + }); + let resolve = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { + label: Some("resolve"), + layout: None, + vertex: wgpu::VertexState { module: &module, entry_point: Some("vs"), compilation_options: Default::default(), buffers: &[] }, + primitive: Default::default(), + depth_stencil: None, + multisample: Default::default(), + fragment: Some(wgpu::FragmentState { + module: &module, + entry_point: Some("fs"), + compilation_options: Default::default(), + targets: &[Some(wgpu::ColorTargetState { format: wgpu::TextureFormat::Rgba8Unorm, blend: None, write_mask: wgpu::ColorWrites::ALL })], + }), + multiview_mask: None, + cache: None, + }); + Ctx { device, queue, rune, ts: TextSystem::default(), base, text, glassed, black, out, resolve } + } + + /// Draws `p` into `base` over `clear`, and clears the text layer. + fn draw(&mut self, p: &Paint, clear: Color) { + self.rune.prepare(&self.device, &self.queue, &mut self.ts.atlas, &p.out, (PW, PH)); + let mut enc = self.device.create_command_encoder(&Default::default()); + self.rune.draw(&mut enc, &self.base, [clear.r, clear.g, clear.b, 1.0]); + self.queue.submit([enc.finish()]); + self.rune.prepare(&self.device, &self.queue, &mut self.ts.atlas, &[], (PW, PH)); + let mut enc = self.device.create_command_encoder(&Default::default()); + self.rune.draw(&mut enc, &self.text, [0.0; 4]); + self.queue.submit([enc.finish()]); + } + + fn pass<'e>(enc: &'e mut wgpu::CommandEncoder, view: &'e wgpu::TextureView, load: wgpu::LoadOp<wgpu::Color>) -> wgpu::RenderPass<'e> { + enc.begin_render_pass(&wgpu::RenderPassDescriptor { + label: None, + color_attachments: &[Some(wgpu::RenderPassColorAttachment { + view, + depth_slice: None, + resolve_target: None, + ops: wgpu::Operations { load, store: wgpu::StoreOp::Store }, + })], + depth_stencil_attachment: None, + timestamp_writes: None, + occlusion_query_set: None, + multiview_mask: None, + }) + } + + /// Encodes a linear frame to sRGB and reads it back. + fn resolve(&self, src: &wgpu::TextureView) -> Vec<u8> { + let bg = self.device.create_bind_group(&wgpu::BindGroupDescriptor { + label: None, + layout: &self.resolve.get_bind_group_layout(0), + entries: &[wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::TextureView(src) }], + }); + let mut enc = self.device.create_command_encoder(&Default::default()); + { + let mut p = Self::pass(&mut enc, &self.out.view, wgpu::LoadOp::Clear(wgpu::Color::BLACK)); + p.set_pipeline(&self.resolve); + p.set_bind_group(0, &bg, &[]); + p.draw(0..3, 0..1); + } + self.out.copy(&mut enc); + self.queue.submit([enc.finish()]); + self.out.read(&self.device) + } +} + +// ------------------------------------------------------------------ scenes + +/// Liquid metal, nearly still, lit by a cool studio. +fn metal(ctx: &mut Ctx, t: f32, shape: Shape, r: [f32; 4], radius: f32) -> Vec<u8> { + let mut p = Paint::default(); + p.backdrop(); + // A contact shadow under the object, then a soft blue spill on the floor. + p.pool(r[0] + r[2] * 0.5, r[1] + r[3] + 6.0, r[2] * 0.62, 26.0, oklcha(0.42, 0.09, HUE, 0.22)); + p.shadow([r[0] + 8.0, r[1] + 18.0, r[2] - 16.0, r[3]], radius, 22.0, oklcha(0.0, 0.0, 0.0, 0.85)); + ctx.draw(&p, oklch(0.0, 0.0, 0.0)); + let params = LiquidMetalParams { + tint: rgb(0xe4e9f0), + light: rgb(0xd8e6ff), + flow: 0.12, + scale: 180.0, + speed: 0.2, + bevel: 18.0, + dome: 0.85, + angle: -0.5, + iridescence: 0.0, + contrast: 1.2, + ..LiquidMetalParams::chrome() + } + .anchor(FillAnchor::Element); + let layers = [Fx::fill(params).on(shape).at(t)]; + let mut fx = FxRenderer::new(&ctx.device, F16, FxOptions { dither: false }); + fx.prepare(&ctx.device, &ctx.queue, &FxFrame { viewport: [PW, PH], scale: S, layers: &layers, backdrop: None, sources: &[] }); + let mut enc = ctx.device.create_command_encoder(&Default::default()); + { + let mut pass = Ctx::pass(&mut enc, &ctx.base, wgpu::LoadOp::Load); + fx.draw_layer(&mut pass, 0); + } + ctx.queue.submit([enc.finish()]); + ctx.resolve(&ctx.base) +} + +/// A frosted pane of thick glass over crisp blue discs: sharp beside the pane, soft through it. +fn glass(ctx: &mut Ctx, t: f32, pane: [f32; 4], radius: f32, frost: f32, orbs: &[(f32, f32, f32, Color)]) -> Vec<u8> { + let mut p = Paint::default(); + p.backdrop(); + for &(x, y, r, c) in orbs { + // Each disc drifts a little on its own slow circle. + let (x, y) = (x + (t * 0.35 + x).sin() * 6.0, y + (t * 0.3 + y).cos() * 4.0); + p.pool(x, y, r * 2.4, r * 2.4, Color { a: 0.3, ..c }); + p.rect([x - r, y - r, 2.0 * r, 2.0 * r], r, c); + } + ctx.draw(&p, oklch(0.0, 0.0, 0.0)); + let k = S; + let slab = Glass::rounded(pane[0] * k, pane[1] * k, pane[2] * k, pane[3] * k, radius * k) + .thickness(40.0 * k) + .bevel(34.0 * k) + .dome(6.0 * k) + .gap(16.0 * k) + .ior(1.5) + .dispersion(0.025) + .frost(frost) + .tint([0.0005, 0.00035, 0.0002]); + let lamp = GlassLight { pos: [(pane[0] + pane[2] * 0.3) * k, (pane[1] - 220.0) * k, 420.0 * k, 260.0 * k], color: [0.9, 1.0, 1.15, 0.0] }; + let mut gl = GlassRenderer::new(&ctx.device, PW, PH, F16); + let settings = GlassSettings { env: 0.45, shadow: 0.6, shadow_offset: [0.0, 24.0 * k], shadow_blur: 36.0 * k, caustic: 0.5 }; + let mut enc = ctx.device.create_command_encoder(&Default::default()); + gl.render(&ctx.device, &ctx.queue, &mut enc, &[slab], &[lamp], settings, &ctx.base, &ctx.black, &ctx.glassed); + ctx.queue.submit([enc.finish()]); + ctx.resolve(&ctx.glassed) +} + +/// Raised controls on a dark floor, under a single cool light. +fn light(ctx: &mut Ctx, t: f32, build: impl FnOnce(&mut Paint, f32, f32)) -> Vec<u8> { + let mut p = Paint::default(); + let (cx, cy) = (W * 0.5, H * 0.5); + // A dark floor that fades to the page's black before the frame's edge. + p.pool(cx, cy, W * 0.46, H * 0.8, oklch(0.15, 0.004, HUE)); + build(&mut p, cx, cy); + ctx.draw(&p, oklch(0.0, 0.0, 0.0)); + let k = S; + // The key light sways slowly above and to the left; a faint blue fill from behind. + let a = -2.25 + 0.12 * (t * 0.5).sin(); + let key = Light::point((cx + 150.0 * a.cos()) * k, (cy + 130.0 * a.sin()) * k, 200.0 * k) + .color(lin(oklch(0.97, 0.012, HUE))) + .intensity(2.6) + .radius(40.0 * k) + .range(1000.0 * k) + .specular(2.6); + let fill = Light::point((cx + 420.0) * k, (cy - 300.0) * k, 420.0 * k) + .color(lin(oklch(0.72, 0.12, HUE))) + .intensity(0.35) + .radius(160.0 * k) + .range(2400.0 * k) + .specular(0.8); + let settings = Settings { + ambient: [0.06, 0.06, 0.07], + rim: 1.1, + contact_ao: 0.55, + background_gloss: 0.35, + background_roughness: 0.6, + gi: Some(Gi::default()), + time: t, + ..Default::default() + }; + let mut lights = LightRenderer::new(&ctx.device, &ctx.queue, PW, PH, wgpu::TextureFormat::Rgba8Unorm); + let mut enc = ctx.device.create_command_encoder(&Default::default()); + let scene = Scene { prims: &p.prims, lights: &[key, fill], settings, emission: None }; + lights.render(&ctx.device, &ctx.queue, &mut enc, &scene, &ctx.base, &ctx.text, &ctx.out.view); + ctx.out.copy(&mut enc); + ctx.queue.submit([enc.finish()]); + ctx.out.read(&ctx.device) +} + +fn render(ctx: &mut Ctx, name: &str, t: f32) -> Vec<u8> { + let (cx, cy) = (W * 0.5, H * 0.5); + match name { + "metal" => { + let r = 92.0; + metal(ctx, t, Shape::circle(cx, cy, r), [cx - r, cy - r, 2.0 * r, 2.0 * r], r) + } + "glass" => glass(ctx, t, [cx - 70.0, cy - 110.0, 220.0, 220.0], 50.0, 0.6, &[(cx - 48.0, cy - 50.0, 100.0, oklch(0.62, 0.16, HUE))]), + "light" => light(ctx, t, |p, cx, cy| { + // A keypad: eight dark keys and one lit in blue. + let (s, gap) = (60.0, 16.0); + for i in 0..3 { + for j in 0..3 { + let (x, y) = (cx - 1.5 * s - gap + j as f32 * (s + gap), cy - 1.5 * s - gap + i as f32 * (s + gap)); + let lit = i == 1 && j == 1; + let c = if lit { oklch(0.55, 0.15, HUE) } else { oklch(0.4, 0.005, HUE) }; + p.solid([x, y, s, s], 16.0, c, |q| { + let q = q.raised(12.0 * S).bevel(12.0 * S, 4.0 * S).gloss(0.8, 0.3); + if lit { q.emissive([0.006, 0.024, 0.08]) } else { q } + }); + } + } + }), + _ => panic!("unknown scene {name}; scenes: {}", SCENES.join(", ")), + } +} + +fn main() { + let args: Vec<String> = std::env::args().collect(); + let get = |k: &str| args.iter().position(|a| a == k).and_then(|i| args.get(i + 1)).cloned(); + let out = get("--out").map_or_else(|| PathBuf::from("target/site-scenes"), PathBuf::from); + let t: f32 = get("--t").map_or(1.2, |s| s.parse().expect("--t SECONDS")); + let only = get("--only"); + std::fs::create_dir_all(&out).unwrap(); + let mut ctx = Ctx::new(); + for name in SCENES.iter().copied().filter(|n| only.as_deref().is_none_or(|o| o == *n)) { + let px = render(&mut ctx, name, t); + write_png(&out.join(format!("{name}.png")), PW, PH, &px).unwrap(); + eprintln!("wrote {name}.png"); + } +} diff --git a/app/vendor/rune/examples/site-scenes/src/resolve.wgsl b/app/vendor/rune/examples/site-scenes/src/resolve.wgsl new file mode 100644 index 0000000..f0ba50f --- /dev/null +++ b/app/vendor/rune/examples/site-scenes/src/resolve.wgsl @@ -0,0 +1,29 @@ +// Linear 16f to sRGB 8-bit with TPDF dither, once, at the final write. +@group(0) @binding(0) var scene: texture_2d<f32>; + +@vertex +fn vs(@builtin(vertex_index) vi: u32) -> @builtin(position) vec4f { + let p = vec2f(f32((vi << 1u) & 2u), f32(vi & 2u)); + return vec4f(p * 2.0 - 1.0, 0.0, 1.0); +} + +fn pcg(v: u32) -> u32 { + let s = v * 747796405u + 2891336453u; + let w = ((s >> ((s >> 28u) + 4u)) ^ s) * 277803737u; + return (w >> 22u) ^ w; +} +fn u01(n: u32) -> f32 { return f32(pcg(n) >> 8u) * (1.0 / 16777216.0); } +fn to_srgb(c: vec3f) -> vec3f { + let lo = c * 12.92; + let hi = 1.055 * pow(max(c, vec3f(0.0)), vec3f(1.0 / 2.4)) - 0.055; + return select(hi, lo, c <= vec3f(0.0031308)); +} + +@fragment +fn fs(@builtin(position) pos: vec4f) -> @location(0) vec4f { + let ip = vec2u(pos.xy); + let c = textureLoad(scene, vec2i(ip), 0); + let n = u01(ip.x + pcg(ip.y)) + u01(ip.x * 7919u + pcg(ip.y + 104729u)) - 1.0; + let s = to_srgb(clamp(c.rgb, vec3f(0.0), vec3f(1.0))) + vec3f(n / 255.0); + return vec4f(clamp(s, vec3f(0.0), vec3f(1.0)), 1.0); +} diff --git a/app/vendor/rune/examples/sketch/Cargo.toml b/app/vendor/rune/examples/sketch/Cargo.toml new file mode 100644 index 0000000..f4af904 --- /dev/null +++ b/app/vendor/rune/examples/sketch/Cargo.toml @@ -0,0 +1,11 @@ +[package] +name = "sketch" +version = "0.0.1" +edition.workspace = true +license.workspace = true + +[dependencies] +rune = { workspace = true, default-features = true, features = ["keys-overlay"] } + +[lints] +workspace = true diff --git a/app/vendor/rune/examples/sketch/assets/pencil.png b/app/vendor/rune/examples/sketch/assets/pencil.png new file mode 100644 index 0000000..c84f9ce Binary files /dev/null and b/app/vendor/rune/examples/sketch/assets/pencil.png differ diff --git a/app/vendor/rune/examples/sketch/scripts/pencil.py b/app/vendor/rune/examples/sketch/scripts/pencil.py new file mode 100644 index 0000000..91f4a1b --- /dev/null +++ b/app/vendor/rune/examples/sketch/scripts/pencil.py @@ -0,0 +1,63 @@ +#!/usr/bin/env python3 +"""Draws assets/pencil.png: a 64x64 px (32x32 pt at 2x) pencil cursor, tip at (4, 60) px.""" +import math, os, struct, zlib + +SIZE, SS = 64, 4 +TIP, W = (4.0, 60.0), 6.5 +D = (1 / math.sqrt(2), -1 / math.sqrt(2)) +N = (-D[1], D[0]) +# The silhouette in pencil space (u along the pencil from the tip, v across it): convex. +HULL = [(0.0, 0.0), (16.0, -W), (74.0, -W), (74.0, W), (16.0, W)] + +def hexc(h): return tuple(int(h[i:i + 2], 16) / 255 for i in (0, 2, 4)) +INK, HALO = hexc("1d1d1f"), (1.0, 1.0, 1.0) + +def inside(u, v): return 0 <= u <= 74 and abs(v) <= min(W, W * u / 16) + +def edge_dist(u, v): + best = 1e9 + for (au, av), (bu, bv) in zip(HULL, HULL[1:] + HULL[:1]): + eu, ev = bu - au, bv - av + t = max(0.0, min(1.0, ((u - au) * eu + (v - av) * ev) / (eu * eu + ev * ev))) + best = min(best, math.hypot(u - au - t * eu, v - av - t * ev)) + return best + +def fill(u, v): + if u < 5: return INK + if u < 16: return hexc("e8c39e") + if u < 62: return hexc("d9a800") if v < -W / 3 else hexc("ffd84d") if v > W / 3 else hexc("f5c518") + if u < 66: return hexc("a9a9b2") + return hexc("f08a9a") + +def sample(x, y): + px, py = x - TIP[0], y - TIP[1] + u, v = px * D[0] + py * D[1], px * N[0] + py * N[1] + d = edge_dist(u, v) + if inside(u, v): + return (INK if d < 0.8 or 61.6 < u < 62.4 or 65.6 < u < 66.4 else fill(u, v)) + (1.0,) + if d < 0.8: return INK + (1.0,) + if d < 2.0: return HALO + (1.0,) + return (0.0, 0.0, 0.0, 0.0) + +rows = [] +for y in range(SIZE): + row = bytearray([0]) + for x in range(SIZE): + acc = [0.0] * 4 + for j in range(SS): + for i in range(SS): + r, g, b, a = sample(x + (i + 0.5) / SS, y + (j + 0.5) / SS) + acc[0] += r * a; acc[1] += g * a; acc[2] += b * a; acc[3] += a + a = acc[3] / (SS * SS) + rgb = [c / acc[3] if acc[3] else 0.0 for c in acc[:3]] + row += bytes(round(c * 255) for c in rgb + [a]) + rows.append(bytes(row)) + +def chunk(kind, data): + return struct.pack(">I", len(data)) + kind + data + struct.pack(">I", zlib.crc32(kind + data)) + +png = b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", struct.pack(">IIBBBBB", SIZE, SIZE, 8, 6, 0, 0, 0)) \ + + chunk(b"IDAT", zlib.compress(b"".join(rows), 9)) + chunk(b"IEND", b"") +out = os.path.join(os.path.dirname(__file__), "..", "assets", "pencil.png") +open(out, "wb").write(png) +print(f"{out}: {len(png)} bytes") diff --git a/app/vendor/rune/examples/sketch/src/main.rs b/app/vendor/rune/examples/sketch/src/main.rs new file mode 100644 index 0000000..8badd63 --- /dev/null +++ b/app/vendor/rune/examples/sketch/src/main.rs @@ -0,0 +1,61 @@ +//! A pencil over a canvas: `Cursor::Image` with a 2x PNG, its hot spot on the tip. Drag to +//! draw. `cargo run -p sketch`. `scripts/pencil.py` draws `assets/pencil.png`. + +#![forbid(unsafe_code)] + +use rune::tok::{self, radius, space, type_}; +use rune::{AppSpec, Color, Cursor, CursorImage, Cx, El, LineCap, Phase, Shape, canvas, col, text}; + +/// 64×64 px, so 32×32 pt, with the graphite tip at (2, 30) pt. +const PENCIL: CursorImage = CursorImage::png(include_bytes!("../assets/pencil.png"), [2.0, 30.0]); +const INK: Color = Color { r: 0.11, g: 0.11, b: 0.12, a: 1.0 }; + +#[derive(Default)] +struct State { + strokes: Vec<Vec<[f32; 2]>>, +} + +fn drawing(s: &State) -> Shape { + s.strokes.iter().fold(Shape::new(), |shape, stroke| match stroke.as_slice() { + [p] => shape.line(*p, *p, 2.5, LineCap::Round, INK), + points => shape.stroke(points.to_vec(), 2.5, INK), + }) +} + +fn view(s: &State, _: &mut Cx<State>) -> El { + let t = tok::theme(false); + col().w_full().h_full().padding(space::S6).gap(space::S3).fill(t.bg) + .child(text("Drag to draw").font(type_::BODY).color(t.text_secondary)) + .child(canvas(drawing(s)).key("paper").w_full().grow(1.0).radius(radius::LG) + .fill(Color::WHITE).border(1.0, t.card_border) + .cursor(Cursor::Image(PENCIL)) + .on_drag(|s: &mut State, d, _| match d.phase { + Phase::Down => s.strokes.push(vec![[d.x, d.y]]), + _ => if let Some(stroke) = s.strokes.last_mut() { stroke.push([d.x, d.y]) }, + })) +} + +fn main() { + rune::run(AppSpec::new("Sketch", (560.0, 420.0), State::default, view)); +} + +#[cfg(test)] +mod tests { + use super::*; + use rune::{Env, Runtime}; + + #[test] + fn the_paper_shows_the_pencil_and_takes_strokes() { + let mut rt = Runtime::new(State::default(), view, (560.0, 420.0), Env { system_dark: false, scale: 2.0 }); + rt.frame(0.0); + let (x, y) = rt.find("paper").unwrap(); + rt.pointer_move(x, y); + assert_eq!(rt.cursor(), Cursor::Image(PENCIL)); + rt.pointer_down(x, y); + rt.pointer_move(x + 30.0, y + 10.0); + rt.pointer_up(x + 30.0, y + 10.0); + rt.frame(0.0); + assert_eq!(rt.state.strokes.len(), 1); + assert!(rt.state.strokes[0].len() >= 2, "{:?}", rt.state.strokes); + } +} diff --git a/app/vendor/rune/examples/todo/Cargo.toml b/app/vendor/rune/examples/todo/Cargo.toml new file mode 100644 index 0000000..1a22049 --- /dev/null +++ b/app/vendor/rune/examples/todo/Cargo.toml @@ -0,0 +1,11 @@ +[package] +name = "todo" +version = "0.0.1" +edition.workspace = true +license.workspace = true + +[dependencies] +rune = { workspace = true, default-features = true, features = ["keys-overlay"] } + +[lints] +workspace = true diff --git a/app/vendor/rune/examples/todo/src/main.rs b/app/vendor/rune/examples/todo/src/main.rs new file mode 100644 index 0000000..36cde2a --- /dev/null +++ b/app/vendor/rune/examples/todo/src/main.rs @@ -0,0 +1,66 @@ +//! A list with state: keyed rows you can add, tick off and remove. Rows animate in and out on +//! their own and the progress bar springs to its new width; the view only says where things are. +//! `cargo run -p todo -- --snap todo.png`. + +#![forbid(unsafe_code)] + +use rune::tok::{self, Theme, radius, type_}; +use rune::{AppSpec, Cx, El, ScrollSpec, Spring, col, el, row, text}; + +struct Todo { id: u32, title: String, done: bool } + +struct State { todos: Vec<Todo>, next: u32 } + +impl Default for State { + fn default() -> Self { + let titles = ["Write the view", "Run it headless", "Ship it"]; + let todos = titles.iter().zip(0..) + .map(|(title, id)| Todo { id, title: title.to_string(), done: id == 0 }); + State { todos: todos.collect(), next: 3 } + } +} + +fn view(s: &State, _: &mut Cx<State>) -> El { + let t = tok::theme(true); + let mut list = col().key("list").gap(4.0); + for todo in &s.todos { + let id = todo.id; + let check = el().key("check").size(16.0, 16.0).radius(8.0) + .fill(if todo.done { tok::accent(0, true) } else { t.control_off }) + .on_press(move |s: &mut State| { + if let Some(t) = s.todos.iter_mut().find(|t| t.id == id) { t.done = !t.done } + }); + let title = text(todo.title.clone()).font(type_::BODY).grow(1.0) + .color(if todo.done { t.text_secondary } else { t.text }); + let remove = text("Remove").font(type_::LABEL).color(t.text_secondary) + .on_press(move |s: &mut State| s.todos.retain(|t| t.id != id)); + list = list.child( + row().key(format!("todo-{id}")).h(36.0).px(12.0).gap(12.0).center_y() + .radius(radius::SM).fill(t.card) + .child(check).child(title).child(remove), + ); + } + let add = text("Add a todo").key("add").font(type_::LABEL).color(tok::accent(0, true)) + .on_press(|s: &mut State| { + s.todos.push(Todo { id: s.next, title: format!("Todo {}", s.next + 1), done: false }); + s.next += 1; + }); + let done = s.todos.iter().filter(|t| t.done).count(); + col().w_full().h_full().padding(24.0).gap(12.0).fill(t.bg) + .child(progress(done, s.todos.len(), t)) + // Past what the window holds, the list scrolls, following new rows, and "Add" stays. + .child(list.scroll(ScrollSpec { stick_bottom: true }).shrink().min_h(0.0)) + .child(add) +} + +fn progress(done: usize, total: usize, t: Theme) -> El { + let width = 312.0 * done as f32 / total.max(1) as f32; + el().key("track").w_full().h(4.0).radius(2.0).fill(t.control_off).child( + el().key("bar").w(width).h(4.0).radius(2.0).fill(tok::accent(0, true)) + .motion(Spring::new(0.4, 0.2)), + ) +} + +fn main() { + rune::run(AppSpec::new("Todo", (360.0, 240.0), State::default, view)); +} diff --git a/app/vendor/rune/examples/video-player/Cargo.toml b/app/vendor/rune/examples/video-player/Cargo.toml new file mode 100644 index 0000000..effbcf2 --- /dev/null +++ b/app/vendor/rune/examples/video-player/Cargo.toml @@ -0,0 +1,11 @@ +[package] +name = "video-player" +version = "0.0.1" +edition.workspace = true +license.workspace = true + +[dependencies] +rune = { workspace = true, default-features = true, features = ["keys-overlay"] } + +[lints] +workspace = true diff --git a/app/vendor/rune/examples/video-player/src/main.rs b/app/vendor/rune/examples/video-player/src/main.rs new file mode 100644 index 0000000..b6a314e --- /dev/null +++ b/app/vendor/rune/examples/video-player/src/main.rs @@ -0,0 +1,100 @@ +//! Play a movie or audio file, or a URL. `cargo run -p video-player -- clip.mov` opens a video +//! looping and muted; tap to pause or resume. An audio file (mp3, m4a, wav) shows a progress +//! bar and waits for a tap, since audio is audible. With no argument it plays the four-frame +//! test clip. `-- --snap out.png --at 0.6` renders the frame at 0.6 s headless. +//! +//! Keys: space plays or pauses, m mutes, v turns the volume to 0 and back, l loops, left and right seek 5 s, 0 goes to the start, +//! h hides the clip (it stops drawing, as when scrolled away) and shows it again. + +#![forbid(unsafe_code)] + +use rune::tok::{self, type_}; +use rune::{AppSpec, Cx, El, Key, KeyEvent, Player, PlayerState, SurfaceFit, Tx, Waker, col, el, row, text}; +use std::time::Duration; + +const WIDTH: f32 = 480.0; +const AUDIO: &[&str] = &["mp3", "m4a", "aac", "wav", "aif", "aiff", "flac", "ogg"]; + +struct Viewer { + clip: Player, + hidden: bool, +} + +fn state() -> Viewer { + let source = rune::extra_args() + .first() + .cloned() + .unwrap_or_else(|| concat!(env!("CARGO_MANIFEST_DIR"), "/../../crates/rune/tests/fixtures/rgbw.mp4").into()); + let ext = source.rsplit_once('.').map(|(_, ext)| ext.to_ascii_lowercase()).unwrap_or_default(); + if AUDIO.contains(&ext.as_str()) { + return Viewer { clip: Player::audio(source), hidden: false }; + } + let clip = Player::new(source.into()); + clip.set_looping(true); + clip.play(); + Viewer { clip, hidden: false } +} + +/// The clip calls the waker when it loads, ends or fails, so the label follows. +fn setup(s: &mut Viewer, waker: Waker) { + s.clip.set_waker(waker); +} + +/// Audio progress: re-run the view about 30 times a second while it plays, and never otherwise. +fn poll(s: &mut Viewer, _: f64, tx: &mut Tx) -> bool { + if s.clip.is_audio() && s.clip.is_playing() { + tx.wake_after(Duration::from_millis(33)); + } + s.clip.is_audio() +} + +fn toggle(s: &mut Viewer) { + if s.clip.is_playing() { s.clip.pause() } else { s.clip.play() } +} + +fn on_key(s: &mut Viewer, event: &KeyEvent, _: &mut Tx) -> bool { + let clip = &s.clip; + match &event.key { + Key::Text(t) if t == " " => toggle(s), + Key::Text(t) if t == "m" => clip.set_muted(!clip.muted()), + Key::Text(t) if t == "v" => clip.set_volume(if clip.volume() > 0.0 { 0.0 } else { 1.0 }), + Key::Text(t) if t == "l" => clip.set_looping(!clip.looping()), + Key::Text(t) if t == "0" => clip.seek(0.0), + Key::Text(t) if t == "h" => s.hidden = !s.hidden, + Key::Left => clip.seek(clip.time() - 5.0), + Key::Right => clip.seek(clip.time() + 5.0), + _ => return false, + } + true +} + +fn view(s: &Viewer, _: &mut Cx<Viewer>) -> El { + let t = tok::theme(true); + let label = match s.clip.state() { + PlayerState::Loading => "Loading".to_string(), + PlayerState::Playing => "Playing, tap to pause".to_string(), + PlayerState::Ready => "Paused, tap to play".to_string(), + PlayerState::Ended => "Ended, tap to replay".to_string(), + PlayerState::Failed(e) => e, + _ => String::new(), + }; + let media = if s.clip.is_audio() { + let progress = s.clip.duration().filter(|d| *d > 0.0).map_or(0.0, |d| (s.clip.time() / d) as f32); + row() + .key("progress") + .w(WIDTH) + .h(4.0) + .radius(2.0) + .fill(t.control_track) + .child(el().w(WIDTH * progress.clamp(0.0, 1.0)).h(4.0).radius(2.0).fill(t.indicator)) + } else { + let (w, h) = s.clip.natural_size().unwrap_or((16, 9)); + let frame = el().key("video").w(WIDTH).h(WIDTH * h as f32 / w as f32).radius(10.0); + if s.hidden { frame } else { frame.video(&s.clip, SurfaceFit::Fit) } + }; + col().w_full().h_full().center().gap(12.0).fill(t.bg).on_press(toggle).child(media).child(text(label).font(type_::BODY).color(t.text_secondary)) +} + +fn main() { + rune::run(AppSpec { setup: Some(setup), poll: Some(poll), on_key: Some(on_key), ..AppSpec::new("Video player", (520.0, 340.0), state, view) }); +} diff --git a/app/vendor/rune/examples/video-tiles/Cargo.toml b/app/vendor/rune/examples/video-tiles/Cargo.toml new file mode 100644 index 0000000..10402cd --- /dev/null +++ b/app/vendor/rune/examples/video-tiles/Cargo.toml @@ -0,0 +1,13 @@ +[package] +name = "video-tiles" +version = "0.0.1" +edition.workspace = true +license.workspace = true + +[dependencies] +rune = { workspace = true, default-features = true, features = ["keys-overlay"] } +wgpu = { workspace = true, features = ["std", "wgsl"] } +serde_json = { workspace = true } + +[lints] +workspace = true diff --git a/app/vendor/rune/examples/video-tiles/README.md b/app/vendor/rune/examples/video-tiles/README.md new file mode 100644 index 0000000..d7b5ded --- /dev/null +++ b/app/vendor/rune/examples/video-tiles/README.md @@ -0,0 +1,121 @@ +# Video tiles + +Four Rune nodes fed by a background producer. macOS creates synthetic NV12 IOSurfaces; +other platforms use the same shader with uploaded byte planes. `--snap` freezes frame 0. + +```sh +cargo build --release -p video-tiles +target/release/video-tiles --snap tiles.png --scale 2 + +cargo build --profile perf -p video-tiles +target/perf/video-tiles --bench-native +``` + +`--bench-native` is headless: 1/4/9 independent 1080p tiles, then one 4K and one 5K +surface, all at 1:1 device-pixel scale. It uses three prefilled IOSurfaces per tile, +pushes fresh frame IDs at 60 Hz, excludes generation/readback from timing, and emits +seven measured runs after one warmup. CPU includes push/import/encode/submit; GPU is +GPU render-pass timestamp duration. A 16-byte timing readback follows each pass; no pixel +readback is timed. No window, physical display, decoder, or network is measured. + +## App integration + +```rust,ignore +let surface = rune::NativeSurface::new(); // keep in app state; clones share a bounded slot +surface.set_waker(waker); // from AppSpec::setup +surface.set_observer(Arc::new(|timing| { + // First notification: frame_id + submitted_at (std::time::Instant). + // Second: completed_at plus optional GPU render-pass timestamp seconds. + // Callbacks can arrive on Rune's completion worker. Keep them short. +})); + +// VideoToolbox callback, after decoding has completed: +let pixel_buffer = unsafe { + rune::native_surface::macos::PixelBuffer::from_raw(cv_pixel_buffer.cast())? +}; // retains the borrowed CVPixelBufferRef +surface.push(pixel_buffer, frame_id)?; + +// In the ordinary Rune view; dimensions are points (960x540 at 2x is 1920x1080): +el().w(960.0).h(540.0).radius(12.0) + .native_surface(&surface, rune::SurfaceFit::Fit) +``` + +The buffer's pixels and attachments must remain immutable until all Rune/GPU ownership +ends. Request IOSurface-backed, Metal-compatible output from VideoToolbox. There is no +CPU pixel lock, copy, or upload in the import path. `push` is thread-safe and replaces +the pending frame; only the newest is imported at render preparation. Repeated rendering +of the same source is cached. `clear()` removes the frame and wakes the app. + +Import failures (e.g. a non-IOSurface pixel buffer) appear in `surface.last_error()`; +unsupported formats/colour metadata are rejected by `push`. On non-macOS, `push_bytes` +accepts packed BGRA or two packed NV12 planes. The native `PixelBuffer` API is macOS-only. + +## Camera preview + +Ask `AVCaptureVideoDataOutput` for IOSurface-backed, Metal-compatible BGRA or `420v` +buffers (`kCVPixelBufferMetalCompatibilityKey`), and `push` each one from its sample-buffer +delegate. Then: + +```rust,ignore +surface.set_mirrored(front_camera); // draw-time flip; captured stills stay unmirrored +el().w(480.0).h(480.0).radius(24.0) + .native_surface(&surface, rune::SurfaceFit::Fill) // aspect-fill, centred crop +``` + +Mirroring flips about the image centre, so a Fill crop stays centred, and 1:1 pixels stay +exact. Changing it wakes the app and redraws the current frame. When the preview window +hides, stop the capture session and call `clear()`: a hidden window draws nothing, but +each `push` still wakes the app. + +## Colour, sampling, ownership and timing + +- BGRA, NV12 `420v` (16..235 luma / 16..240 chroma) and `420f` (full range). +- YCbCr BT.601/BT.709 matrix and sRGB/BT.709 transfer come from CoreVideo attachments. + Missing matrix defaults to BT.601 for <=576-line sources, BT.709 otherwise; missing + transfer defaults to BT.709 for NV12, sRGB for BGRA. Output is linear RGB into Rune's + sRGB target. Unsupported matrix/transfer metadata is an error. SDR only; wide-gamut + primary conversion, HDR, interlacing, clean-aperture cropping, rotation and explicit + chroma-siting metadata are not implemented. BGRA alpha is treated as straight alpha. +- Fit letterboxes; Fill crops. Matching pixel size snaps the image origin to device + pixels and uses `textureLoad`: no luma/BGRA interpolation at 1:1, including Retina. + NV12's native 2x2 chroma samples are preserved at 1:1. Other scales use bilinear + sampling with an area grid up to 8x8 taps for shrinking. Beyond 8x shrink this is + an approximation, not a full-resolution area integral. Rounded corners, inherited + rectangular soft clips, node opacity and painter order apply to the video. +- Each imported plane owns its `CVMetalTexture` **and** pixel buffer through a wgpu-hal + drop callback. wgpu retains these resources through in-flight submissions, even if + a new frame arrives, the node disappears, or an encoder is abandoned. Decoder pool + buffers cannot be recycled merely because the pending slot changed. +- `counts()` returns draw submissions/completions, not unique decoded frames; dropped + pending frames generate no submit notification. A source frame can be submitted more + than once. `timing()` holds the newest submission only; the observer receives both + events for every draw. `submitted_at` is sampled immediately before submit setup; + `completed_at` is when completion was observed, while `gpu_start_seconds/gpu_end_seconds` + come from hardware render-pass queries (the containing UI pass, when embedded in Rune). + Their difference is GPU duration; the GPU epoch is backend-specific. Do not subtract + them from `Instant`. Backends without timestamp queries still report completion. + An explicit query set passed to `Renderer::draw_timed` takes precedence; that draw's + NativeSurface notifications carry CPU submit/completion times only. + `Frame::draw_ui`, `Renderer::draw`, and `draw_range` interleave prepared video at its + `before_instance` position, including inside isolated groups. A custom compositor must + preserve those absolute insertion indices when concatenating or rearranging lists and + call `encode_layers` before opening its render pass. Prepared but undrawn video generates + no submission notification. + A coalesced completion worker uses nonblocking polls, sleeping between them, including + for the final frame at idle. It never holds wgpu's device lock while waiting on a GPU + fence. Counter resolution runs in a separate submission after render completion to + avoid stale Metal counter samples; the second notification follows its 16-byte readback. + Completion time is captured before that readback, but includes callback latency; it is not an exact Metal + command-buffer completion timestamp. wgpu 30 rejects `as_hal_mut` after normal render + encoding, so its raw completed-handler hook cannot be used here. A tested prototype + hit that validation error and was removed. No backend fork or untracked raw submission. +- True **presented-frame** timestamps require Rune's own Mac shell owning CAMetalLayer / + CAMetalDisplayLink (planned, not built). wgpu-hal 30 exposes the render layer and raw + command buffer but keeps the acquired drawable private. There is no cheap, supported + presented-handler hook to prototype without owning that shell. GPU-done is not present. + +Verification: `cargo test -p rune-media native_surface -- --test-threads=1` (and `cargo test -p rune --lib -- native_surface:: --test-threads=1` for renderer interleaving). +The GPU test compares native IOSurface and byte-upload results with a scalar colour oracle, +checks exact one-pixel patterns, fitting/clipping, notifications, and released backing ownership. +The overlap test acquires the same exclusive device lock as presentation while GPU work +is still in flight, without creating a window. diff --git a/app/vendor/rune/examples/video-tiles/src/bench.rs b/app/vendor/rune/examples/video-tiles/src/bench.rs new file mode 100644 index 0000000..09d36e9 --- /dev/null +++ b/app/vendor/rune/examples/video-tiles/src/bench.rs @@ -0,0 +1,134 @@ +//! No window/pixel readback. Import/encode/submit CPU and GPU render-pass timestamp duration. +use rune::native_surface::{NativeSurface, SurfaceDraw, SurfaceFit, SurfaceRenderer, synthetic}; +use rune::render::{Gpu, OFFSCREEN_FORMAT}; +use std::sync::{Arc, Mutex}; +use std::time::Duration; + +pub fn run() { + let gpu = Gpu::new(Gpu::instance(), None); + eprintln!("adapter={:?}", gpu.adapter.get_info()); + for (tiles, w, h) in [(1, 1920, 1080), (4, 1920, 1080), (9, 1920, 1080), (1, 3840, 2160), (1, 5120, 2880)] { + let columns = (tiles as f32).sqrt() as u32; + let size = (w * columns, h * columns); + let target = gpu.device.create_texture(&wgpu::TextureDescriptor { + label: Some("video benchmark"), + size: wgpu::Extent3d { width: size.0, height: size.1, depth_or_array_layers: 1 }, + mip_level_count: 1, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + format: OFFSCREEN_FORMAT, + usage: wgpu::TextureUsages::RENDER_ATTACHMENT, + view_formats: &[], + }); + let view = target.create_view(&Default::default()); + let mut renderer = SurfaceRenderer::new(&gpu.device, OFFSCREEN_FORMAT); + let timings = Arc::new(Mutex::new(Vec::new())); + let (completed, completion) = std::sync::mpsc::channel(); + let surfaces: Vec<_> = (0..tiles).map(|_| NativeSurface::new()).collect(); + let times = timings.clone(); + surfaces[0].set_observer(Arc::new(move |t| { + if let (Some(a), Some(b)) = (t.gpu_start_seconds, t.gpu_end_seconds) { + times.lock().unwrap().push((b - a) * 1000.0); + } + if t.completed_at.is_some() { + completed.send(()).ok(); + } + })); + let draws: Vec<_> = surfaces + .iter() + .enumerate() + .map(|(i, s)| SurfaceDraw { + surface: s.clone(), + fit: SurfaceFit::Fit, + before_instance: 0, + rect: [(i as u32 % columns * w) as f32, (i as u32 / columns * h) as f32, w as f32, h as f32], + radii: [0.0; 4], + clip: rune::render::NO_CLIP, + fade: [0; 4], + opacity: 1.0, + }) + .collect(); + // Three independent IOSurface buffers per tile model a decoder's recyclable output pool. + // Fill only before timing: production import never accesses pixels on CPU. + #[cfg(target_os = "macos")] + let buffers: Vec<Vec<_>> = (0..tiles) + .map(|_| { + (0..3) + .map(|i| rune::native_surface::macos::PixelBuffer::from_bytes(&synthetic(w, h, i)).unwrap()) + .collect() + }) + .collect(); + let mut runs = Vec::new(); + for run in 0..8 { + timings.lock().unwrap().clear(); + let mut cpu = Vec::new(); + for frame in 0..30 { + let begin = rune::time::now(); + for (i, s) in surfaces.iter().enumerate() { + #[cfg(target_os = "macos")] + s.push(buffers[i][frame % 3].clone(), (run * 30 + frame) as u64).unwrap(); + #[cfg(not(target_os = "macos"))] + { + let _ = i; + s.push_bytes(synthetic(w, h, frame as u64), (run * 30 + frame) as u64).unwrap(); + } + } + renderer.prepare(&gpu.device, &gpu.queue, &draws, size); + let mut encoder = gpu.device.create_command_encoder(&Default::default()); + { + let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { + label: Some("video benchmark"), + color_attachments: &[Some(wgpu::RenderPassColorAttachment { + view: &view, + depth_slice: None, + resolve_target: None, + ops: wgpu::Operations { + load: wgpu::LoadOp::Clear(wgpu::Color::BLACK), + store: wgpu::StoreOp::Store, + }, + })], + depth_stencil_attachment: None, + timestamp_writes: renderer.timestamp_writes(), + occlusion_query_set: None, + multiview_mask: None, + }); + for i in 0..renderer.len() { + renderer.draw(&mut pass, i); + } + } + renderer.submit(&gpu.queue, encoder); + cpu.push(begin.elapsed().as_secs_f64() * 1000.0); + completion.recv_timeout(Duration::from_secs(10)).expect("final frame completion without another draw"); + // Pace actual submissions at 60 Hz; waiting is excluded from CPU cost. + if let Some(wait) = Duration::from_secs_f64(1.0 / 60.0).checked_sub(begin.elapsed()) { + std::thread::sleep(wait); + } + } + let gpu_ms = timings.lock().unwrap().clone(); + if gpu.device.features().contains(wgpu::Features::TIMESTAMP_QUERY) { + assert_eq!(gpu_ms.len(), 30, "every submitted frame must have a valid GPU timestamp pair"); + } + for s in &surfaces { + assert_eq!(s.last_error(), None); + } + if run > 0 { + runs.push(serde_json::json!({"cpu_p50_ms":median(&cpu),"cpu_p95_ms":percentile(&cpu,0.95),"gpu_samples":gpu_ms.len(),"gpu_p50_ms":median(&gpu_ms),"gpu_p95_ms":percentile(&gpu_ms,0.95)})); + } + } + let cpu: Vec<_> = runs.iter().map(|r| r["cpu_p50_ms"].as_f64().unwrap()).collect(); + let gpu_ms: Vec<_> = runs.iter().filter_map(|r| r["gpu_p50_ms"].as_f64()).collect(); + println!( + "{}", + serde_json::json!({"tiles":tiles,"source":[w,h],"target":[size.0,size.1],"hz":60,"warmup_runs":1,"runs":runs, + "cpu_median_ms":median(&cpu),"gpu_median_ms":median(&gpu_ms),"cpu_per_tile_ms":median(&cpu).map(|v|v/tiles as f64),"gpu_per_tile_ms":median(&gpu_ms).map(|v|v/tiles as f64)}) + ); + } +} +fn median(xs: &[f64]) -> Option<f64> { + percentile(xs, 0.5) +} +fn percentile(xs: &[f64], p: f64) -> Option<f64> { + let mut xs = xs.to_vec(); + xs.sort_by(f64::total_cmp); + xs.get((xs.len() as f64 * p) as usize).copied() +} diff --git a/app/vendor/rune/examples/video-tiles/src/main.rs b/app/vendor/rune/examples/video-tiles/src/main.rs new file mode 100644 index 0000000..c9f42ec --- /dev/null +++ b/app/vendor/rune/examples/video-tiles/src/main.rs @@ -0,0 +1,76 @@ +//! Copy this producer/view boundary into a VideoToolbox application. + +#![forbid(unsafe_code)] + +use rune::native_surface::{ByteFrame, synthetic}; +use rune::{AppSpec, Cx, El, NativeSurface, SurfaceFit, Waker, col, el, row}; +use std::time::Duration; +mod bench; + +fn push(surface: &NativeSurface, bytes: &ByteFrame, id: u64) { + #[cfg(target_os = "macos")] + surface.push(rune::native_surface::macos::PixelBuffer::from_bytes(bytes).unwrap(), id).unwrap(); + #[cfg(not(target_os = "macos"))] + surface + .push_bytes( + ByteFrame { + width: bytes.width, + height: bytes.height, + format: bytes.format, + color: bytes.color, + planes: bytes.planes.clone(), + }, + id, + ) + .unwrap(); +} +struct Tiles { + surfaces: Vec<NativeSurface>, +} +fn state() -> Tiles { + let surfaces: Vec<_> = (0..4).map(|_| NativeSurface::new()).collect(); + let bytes = synthetic(640, 360, 0); + for s in &surfaces { + push(s, &bytes, 0); + } + Tiles { surfaces } +} +fn setup(s: &mut Tiles, wake: Waker) { + for surface in &s.surfaces { + surface.set_waker(wake.clone()); + } + // Headless scenes use the deterministic initial frame, not a wall-clock producer. + if std::env::args() + .any(|v| matches!(v.as_str(), "--snap" | "--frames" | "--first-pixels" | "--tree" | "--trace" | "--strip")) + { + return; + } + let surfaces = s.surfaces.clone(); + std::thread::spawn(move || { + for id in 1..=u64::MAX { + let bytes = synthetic(640, 360, id); + for s in &surfaces { + push(s, &bytes, id); + } + std::thread::sleep(Duration::from_millis(16)); + } + }); +} +fn view(s: &Tiles, _: &mut Cx<Tiles>) -> El { + col().key("tiles").gap(8.0).padding(8.0).children((0..2).map(|y| { + row().gap(8.0).children((0..2).map(|x| { + el().key(format!("tile-{x}-{y}")) + .w(320.0) + .h(180.0) + .radius(8.0) + .native_surface(&s.surfaces[y * 2 + x], SurfaceFit::Fit) + })) + })) +} +fn main() { + if std::env::args().any(|a| a == "--bench-native") { + bench::run(); + return; + } + rune::run(AppSpec { setup: Some(setup), ..AppSpec::new("Video tiles", (664.0, 384.0), state, view) }); +} diff --git a/app/vendor/rune/examples/web-hello/Cargo.toml b/app/vendor/rune/examples/web-hello/Cargo.toml new file mode 100644 index 0000000..2253dc6 --- /dev/null +++ b/app/vendor/rune/examples/web-hello/Cargo.toml @@ -0,0 +1,17 @@ +[package] +name = "web-hello" +version = "0.0.1" +edition.workspace = true +license.workspace = true + +[lib] +crate-type = ["cdylib", "rlib"] + +[dependencies] +rune = { workspace = true, default-features = true, features = ["keys-overlay"] } + +[target.'cfg(target_arch = "wasm32")'.dependencies] +wasm-bindgen = { workspace = true } + +[lints] +workspace = true diff --git a/app/vendor/rune/examples/web-hello/assets/proof.jpg b/app/vendor/rune/examples/web-hello/assets/proof.jpg new file mode 100644 index 0000000..95ce760 Binary files /dev/null and b/app/vendor/rune/examples/web-hello/assets/proof.jpg differ diff --git a/app/vendor/rune/examples/web-hello/assets/proof.png b/app/vendor/rune/examples/web-hello/assets/proof.png new file mode 100644 index 0000000..d1893db Binary files /dev/null and b/app/vendor/rune/examples/web-hello/assets/proof.png differ diff --git a/app/vendor/rune/examples/web-hello/src/image_proof.rs b/app/vendor/rune/examples/web-hello/src/image_proof.rs new file mode 100644 index 0000000..f0b4cb8 --- /dev/null +++ b/app/vendor/rune/examples/web-hello/src/image_proof.rs @@ -0,0 +1,57 @@ +//! Browser image-decode fixture, selected only by ?image-proof: a JPEG the browser decodes and a +//! PNG Rune decodes, both from bytes, and the PNG again as the cursor over it. +use rune::{AppSpec, Cursor, CursorImage, Cx, El, Image, ImageCache, col, el}; +use wasm_bindgen::prelude::*; + +#[wasm_bindgen(inline_js = " +export function imageProof() { return new URLSearchParams(location.search).has('image-proof'); } +export function imageReport(name, width, height, error) { + (window.__imageProof ||= {})[name] = error ? { error } : { width, height }; +} +")] +extern "C" { + #[wasm_bindgen(js_name = imageProof)] + pub fn enabled() -> bool; + #[wasm_bindgen(js_name = imageReport)] + fn report(name: &str, width: u32, height: u32, error: &str); +} + +const PNG: &[u8] = include_bytes!("../assets/proof.png"); +const CURSOR: CursorImage = CursorImage::png(PNG, [1.0, 2.0]); + +#[derive(Default)] +struct State { + cache: Option<ImageCache>, + images: Vec<(&'static str, Image)>, +} + +fn view(s: &State, _: &mut Cx<State>) -> El { + let mut out = col().w_full().h_full().padding(16.0).gap(8.0); + for (name, image) in &s.images { + out = out.child(el().key(*name).w(120.0).h(60.0).pixels(image.pixels()) + .cursor(Cursor::Image(CURSOR)).on_press(|_: &mut State| {})); + } + out +} + +pub fn run() { + let mut spec = AppSpec::new("Image proof", (390.0, 760.0), State::default, view); + spec.setup = Some(|s, waker| { + let cache = s.cache.insert(ImageCache::new(waker)); + s.images = vec![ + ("jpeg", cache.load(&include_bytes!("../assets/proof.jpg")[..])), + ("png", cache.load(PNG)), + ]; + }); + spec.poll = Some(|s, _, _| { + for (name, image) in &s.images { + match (image.size(), image.error()) { + (Some([w, h]), _) => report(name, w, h, ""), + (_, Some(e)) => report(name, 0, 0, &e.0), + _ => {} + } + } + false + }); + rune::run(spec); +} diff --git a/app/vendor/rune/examples/web-hello/src/input_proof.rs b/app/vendor/rune/examples/web-hello/src/input_proof.rs new file mode 100644 index 0000000..56ae7c0 --- /dev/null +++ b/app/vendor/rune/examples/web-hello/src/input_proof.rs @@ -0,0 +1,268 @@ +//! Browser input regression fixture, selected only by ?input-proof (and ?input-proof&audit). +use std::{cell::Cell, rc::Rc}; + +use rune::{ + App, AppHandle, AppSpec, Cx, Drag, El, Key, Phase, PhysicalInput, ScrollPos, TextEdit, col, el, + row, text, text_input, tok, +}; +use wasm_bindgen::prelude::*; + +#[wasm_bindgen(inline_js = " +export function enabled() { return new URLSearchParams(location.search).has('input-proof'); } +export function auditEnabled() { return new URLSearchParams(location.search).has('audit'); } +export function queryZoom() { + const z = parseFloat(new URLSearchParams(location.search).get('zoom') ?? '1'); + return Number.isFinite(z) && z > 0 ? z : 1; +} +export function report(plain, display, single, secretLength, submits, shortcuts, visible) { + window.__inputProof = { plain, display, single, secretLength, submits, shortcuts, visible, + polls: (window.__inputProof?.polls ?? 0) + 1 }; +} +export function reportAudit(json) { + const prev = window.__auditProof?.polls ?? 0; + const data = JSON.parse(json); + data.polls = prev + 1; + window.__auditProof = data; +} +export function reportScroll(x, y) { + window.__auditScroll = { x, y }; +} +")] +extern "C" { + pub fn enabled() -> bool; + #[wasm_bindgen(js_name = auditEnabled)] + fn audit_enabled() -> bool; + #[wasm_bindgen(js_name = queryZoom)] + fn query_zoom() -> f32; + fn report(plain: &str, display: &str, single: &str, secret_length: usize, submits: u32, shortcuts: u32, visible: bool); + #[wasm_bindgen(js_name = reportAudit)] + fn report_audit(json: &str); + #[wasm_bindgen(js_name = reportScroll)] + fn report_scroll(x: f32, y: f32); +} + +struct State { + plain: TextEdit, + single: TextEdit, + secret: TextEdit, + submits: u32, + shortcuts: u32, + handle: Option<AppHandle<State>>, +} + +impl Default for State { + fn default() -> Self { + Self { plain: TextEdit::default(), single: TextEdit::default(), secret: TextEdit::default().secure(), + submits: 0, shortcuts: 0, handle: None } + } +} + +fn view(s: &State, _: &mut Cx<State>) -> El { + let field = |edit: &TextEdit| text_input(edit, tok::type_::BODY).w_full().h(48.0); + col().w_full().h_full().padding(16.0).gap(8.0) + .child(field(&s.plain).key("plain").on_edit(|s: &mut State| &mut s.plain) + .on_submit(|s: &mut State, _| s.submits += 1)) + .child(field(&s.single).key("single").single_line().on_edit(|s: &mut State| &mut s.single) + .on_submit(|s: &mut State, _| s.submits += 1)) + .child(field(&s.secret).key("secret").single_line().on_edit(|s: &mut State| &mut s.secret) + .on_submit(|s: &mut State, _| s.submits += 1)) + .child(el().key("button").focusable(true).w_full().h(48.0).child(text("Button")) + .on_press(|s: &mut State| s.submits += 1)) +} + +struct Audit { + zoom: f32, + clicks: Vec<String>, + secondary: u32, + middle: u32, + wheels: Vec<String>, + pinches: Vec<f32>, + scroll: Rc<Cell<(f32, f32)>>, + keys: Vec<String>, + key_ups: Vec<String>, + physical_mods: Vec<String>, + focus_lost: u32, + drags: Vec<String>, + hovered: bool, + edit: TextEdit, + handle: Option<AppHandle<Audit>>, +} + +impl Default for Audit { + fn default() -> Self { + Self { + zoom: query_zoom(), + clicks: Vec::new(), + secondary: 0, + middle: 0, + wheels: Vec::new(), + pinches: Vec::new(), + scroll: Rc::new(Cell::new((0.0, 0.0))), + keys: Vec::new(), + key_ups: Vec::new(), + physical_mods: Vec::new(), + focus_lost: 0, + drags: Vec::new(), + hovered: false, + edit: TextEdit::default(), + handle: None, + } + } +} + +fn mods_json(m: rune::Mods) -> String { + format!(r#"{{"shift":{},"ctrl":{},"alt":{},"meta":{}}}"#, m.shift, m.ctrl, m.alt, m.logo) +} + +fn json_str(s: &str) -> String { + let mut out = String::with_capacity(s.len() + 2); + out.push('"'); + for ch in s.chars() { + match ch { + '"' => out.push_str("\\\""), + '\\' => out.push_str("\\\\"), + '\n' => out.push_str("\\n"), + '\r' => out.push_str("\\r"), + '\t' => out.push_str("\\t"), + c if c.is_control() => out.push_str(&format!("\\u{:04x}", c as u32)), + c => out.push(c), + } + } + out.push('"'); + out +} + +fn publish_audit(s: &Audit) { + let (sx, sy) = s.scroll.get(); + let pinches: Vec<String> = s.pinches.iter().map(|d| format!("{d:.4}")).collect(); + let key_ups: Vec<String> = s.key_ups.iter().map(|k| json_str(k)).collect(); + let preedit = s.edit.preedit().map(|(p, _)| p).unwrap_or(""); + let json = format!( + r#"{{"zoom":{:.2},"clicks":[{}],"secondary":{},"middle":{},"wheels":[{}],"pinches":[{}],"scrollX":{:.2},"scrollY":{:.2},"keys":[{}],"keyUps":[{}],"physicalMods":[{}],"focusLost":{},"drags":[{}],"hovered":{},"plain":{},"preedit":{},"visible":{}}}"#, + s.zoom, + s.clicks.join(","), + s.secondary, + s.middle, + s.wheels.join(","), + pinches.join(","), + sx, + sy, + s.keys.join(","), + key_ups.join(","), + s.physical_mods.join(","), + s.focus_lost, + s.drags.join(","), + s.hovered, + json_str(&s.edit.text), + json_str(preedit), + s.handle.as_ref().is_some_and(AppHandle::is_visible), + ); + report_audit(&json); +} + +fn audit_view(s: &Audit, cx: &mut Cx<Audit>) -> El { + cx.zoom(s.zoom); + publish_audit(s); + let scroll = s.scroll.clone(); + col().w_full().h_full() + .on_key_up(|s: &mut Audit, ev, _| { s.key_ups.push(format!("{:?}", ev.key)); true }) + .child( + row().h(60.0) + .child(el().key("left").size(120.0, 60.0).on_press_tx(|s: &mut Audit, tx| { + s.clicks.push(format!(r#"{{"target":"left","mods":{}}}"#, mods_json(tx.mods()))); + })) + .child(el().key("right").size(120.0, 60.0).on_press_tx(|s: &mut Audit, tx| { + s.clicks.push(format!(r#"{{"target":"right","mods":{}}}"#, mods_json(tx.mods()))); + })), + ) + .child( + row().h(60.0) + .child( + el().key("drag").size(120.0, 60.0).focusable(true) + .on_hover_change(|s: &mut Audit, h, _| s.hovered = h) + .on_drag(|s: &mut Audit, d: &mut Drag, _| { + let phase = match d.phase { Phase::Down => "down", Phase::Move => "move", Phase::Up => "up" }; + s.drags.push(format!(r#"{{"phase":"{phase}","cancelled":{}}}"#, d.cancelled())); + }) + .on_secondary_press(|s: &mut Audit, _, _| s.secondary += 1) + .on_middle_press(|s: &mut Audit, _| s.middle += 1) + .on_physical_input(|s: &mut Audit, ev, _| match ev { + PhysicalInput::Modifiers(m) => { s.physical_mods.push(mods_json(*m)); true } + PhysicalInput::FocusLost => { s.focus_lost += 1; true } + PhysicalInput::Key { .. } => false, + }), + ) + .child( + el().key("wheel").size(120.0, 60.0).hit() + .on_wheel(|s: &mut Audit, ev, _| { + s.wheels.push(format!( + r#"{{"dx":{:.2},"dy":{:.2},"precise":{},"mods":{}}}"#, + ev.dx, ev.dy, ev.precise, mods_json(ev.mods) + )); + true + }) + .on_magnify(|s: &mut Audit, ev, _| { s.pinches.push(ev.delta); true }), + ), + ) + .child( + el().key("scroller").size(240.0, 100.0).scroll_xy() + .on_scroll_offset(move |pos: ScrollPos| { + scroll.set((pos.offset[0], pos.offset[1])); + report_scroll(pos.offset[0], pos.offset[1]); + }) + .child(el().size(1200.0, 1200.0)), + ) + .child( + text_input(&s.edit, tok::type_::BODY).key("field").size(240.0, 48.0) + .on_edit(|s: &mut Audit| &mut s.edit), + ) +} + +fn run_audit() { + let mut spec = AppSpec::new("Input audit", (450.0, 600.0), Audit::default, audit_view); + spec.poll = Some(|s, _, _| { + publish_audit(s); + false + }); + spec.on_key = Some(|s, ev, tx| { + let phys = tx.physical_key().map(|p| json_str(&format!("{p:?}"))).unwrap_or_else(|| "null".into()); + let base = tx.key_base().map(|c| json_str(&c.to_string())).unwrap_or_else(|| "null".into()); + s.keys.push(format!( + r#"{{"key":{},"physical":{},"base":{},"repeat":{},"mods":{}}}"#, + json_str(&format!("{:?}", ev.key)), + phys, + base, + tx.key_repeat(), + mods_json(ev.mods), + )); + true + }); + let app = App::new(spec); + let handle = app.handle(); + let state_handle = handle.clone(); + handle.update(move |s, _| s.handle = Some(state_handle)); + app.run(); +} + +pub fn run() { + if audit_enabled() { + run_audit(); + return; + } + let mut spec = AppSpec::new("Input proof", (390.0, 760.0), State::default, view); + spec.poll = Some(|s, _, _| { + report(&s.plain.text, &s.plain.display().0, &s.single.text, s.secret.text.chars().count(), + s.submits, s.shortcuts, s.handle.as_ref().is_some_and(AppHandle::is_visible)); + false + }); + spec.on_key = Some(|s, event, _| { + if event.key == Key::Command('k') { s.shortcuts += 1; true } else { false } + }); + let app = App::new(spec); + let handle = app.handle(); + let state_handle = handle.clone(); + handle.update(move |s, _| s.handle = Some(state_handle)); + handle.show(); + handle.set_position((0, 0)); // Must warn, never cover the canvas with an error page. + app.run(); +} diff --git a/app/vendor/rune/examples/web-hello/src/lib.rs b/app/vendor/rune/examples/web-hello/src/lib.rs new file mode 100644 index 0000000..231a212 --- /dev/null +++ b/app/vendor/rune/examples/web-hello/src/lib.rs @@ -0,0 +1,67 @@ +#![forbid(unsafe_code)] + +use rune::{AppSpec, Cx, El, ScrollSpec, TextEdit, Tx, col, el, row, text, text_input}; +use rune::tok::{self, type_}; +#[cfg(target_arch = "wasm32")] +mod image_proof; +#[cfg(target_arch = "wasm32")] +mod input_proof; + +struct State { + messages: Vec<String>, + draft: TextEdit, +} + +impl Default for State { + fn default() -> Self { + Self { + messages: (1..=24).map(|n| format!("Message {n}: Hello from Rune." )).collect(), + draft: TextEdit::new(""), + } + } +} + +fn send(state: &mut State, tx: &mut Tx) { + if state.draft.text.trim().is_empty() { return; } + state.messages.push(state.draft.text.clone()); + state.draft.clear(); + tx.scroll_to_bottom("messages"); +} + +fn view(state: &State, cx: &mut Cx<State>) -> El { + let dark = cx.system_dark(); + let t = tok::theme(dark); + let [top, right, bottom, left] = cx.safe_area(); + let mut messages = col().w_full().gap(12.0).py(16.0); + for (i, message) in state.messages.iter().enumerate() { + messages = messages.child(text(message.clone()).key(format!("message-{i}")) + .font(type_::BODY).color(t.text).w_full().padding(16.0).radius(12.0).fill(t.card)); + } + let composer = text_input(&state.draft, type_::BODY).key("composer") + .placeholder("Message", t.text_secondary).color(t.text) + .grow(1.0).h(48.0).padding(12.0).radius(12.0).fill(t.card) + .on_edit(|s: &mut State| &mut s.draft).on_submit(send); + let send_button = el().key("send").h(48.0).px(16.0).center().radius(12.0).fill(t.control_off) + .child(text("Send").font(type_::LABEL).color(t.text)).on_press_tx(send); + let copy = el().key("copy").h(44.0).px(8.0).center() + .child(text("Copy last").font(type_::LABEL).color(t.text_secondary)).on_press_tx(|s: &mut State, tx| { + if let Some(message) = s.messages.last() { tx.copy(message.clone()); } + }); + let title = text("Messages").font(type_::TITLE).color(t.text).grow(1.0); + #[cfg(target_arch = "wasm32")] + let title = title.on_press(|_: &mut State| { rune::web::open_url("https://www.rust-lang.org/").ok(); }); + col().w_full().h_full().pt(16.0 + top).pr(16.0 + right).pb(16.0 + bottom).pl(16.0 + left).gap(8.0).fill(t.bg) + .child(row().w_full().center_y().child(title).child(copy)) + .child(col().key("messages").w_full().grow(1.0).shrink() + .scroll(ScrollSpec { stick_bottom: true }).scroll_edge_fade(16.0).child(messages)) + .child(row().w_full().gap(8.0).child(composer).child(send_button)) +} + +#[cfg_attr(target_arch = "wasm32", wasm_bindgen::prelude::wasm_bindgen(start))] +pub fn start() { + #[cfg(target_arch = "wasm32")] + if input_proof::enabled() { input_proof::run(); return; } + #[cfg(target_arch = "wasm32")] + if image_proof::enabled() { image_proof::run(); return; } + rune::run(AppSpec::new("Messages", (390.0, 760.0), State::default, view)); +} diff --git a/app/vendor/rune/examples/web-hello/src/main.rs b/app/vendor/rune/examples/web-hello/src/main.rs new file mode 100644 index 0000000..877e030 --- /dev/null +++ b/app/vendor/rune/examples/web-hello/src/main.rs @@ -0,0 +1,3 @@ +#![forbid(unsafe_code)] + +fn main() { web_hello::start(); } diff --git a/app/vendor/rune/examples/web-showcase/Cargo.toml b/app/vendor/rune/examples/web-showcase/Cargo.toml new file mode 100644 index 0000000..653c98d --- /dev/null +++ b/app/vendor/rune/examples/web-showcase/Cargo.toml @@ -0,0 +1,17 @@ +[package] +name = "web-showcase" +version = "0.0.1" +edition.workspace = true +license.workspace = true + +[lib] +crate-type = ["cdylib", "rlib"] + +[dependencies] +rune = { workspace = true, default-features = true, features = ["keys-overlay"] } + +[target.'cfg(target_arch = "wasm32")'.dependencies] +wasm-bindgen = { workspace = true } + +[lints] +workspace = true diff --git a/app/vendor/rune/examples/web-showcase/src/lib.rs b/app/vendor/rune/examples/web-showcase/src/lib.rs new file mode 100644 index 0000000..a3f7d41 --- /dev/null +++ b/app/vendor/rune/examples/web-showcase/src/lib.rs @@ -0,0 +1,165 @@ +//! The live panel on Rune's website: a switch, a spring picker and a puck you can throw along a +//! track, drawn by Rune on a canvas the page already has. Nothing moves until you touch it. +//! `cargo run -p web-showcase -- --snap poster.png --size 560x320 --scale 2` draws the page's poster. + +#![forbid(unsafe_code)] + +use rune::tok; +use rune::{AppSpec, Color, Cx, Drag, El, Phase, Spring, TextStyle, Tx, col, el, oklch, oklcha, row, text}; + +const SPRINGS: [(&str, Spring); 3] = + [("Snappy", Spring::new(0.25, 0.0)), ("Smooth", Spring::new(0.4, 0.0)), ("Bouncy", Spring::new(0.5, 0.3))]; +const CARD_W: f32 = 376.0; +/// The canvas is this tall; the page reserves the same box, so nothing shifts when it mounts. +const STAGE_H: f32 = 320.0; +const PUCK: f32 = 28.0; +const STOPS: usize = 4; + +pub struct State { + on: bool, + spring: usize, + /// The puck's position along the track, 0 to 1. + at: f32, +} + +impl Default for State { + fn default() -> Self { + Self { on: true, spring: 2, at: 0.0 } + } +} + +fn ink() -> Color { + oklch(0.74, 0.14, 245.0) +} + +fn snap(at: f32) -> f32 { + let n = (STOPS - 1) as f32; + (at * n).round() / n +} + +fn switch(s: &State) -> El { + let t = tok::theme(true); + let (w, h, k) = (44.0, 26.0, 22.0); + let inset = (h - k) / 2.0; + el().key("switch").role("switch").label("Lights").checked(s.on).focusable(true) + .size(w, h).radius(h / 2.0) + .fill(if s.on { ink() } else { t.control_off }) + .motion(SPRINGS[s.spring].1) + .on_press(|s: &mut State| s.on = !s.on) + .child(el().key("knob").size(k, k).radius(k / 2.0).fill(t.knob) + .absolute(if s.on { w - k - inset } else { inset }, inset) + .shadow(1.0, 3.0, t.knob_shadow)) +} + +fn picker(s: &State, seg: f32) -> El { + let t = tok::theme(true); + let (h, pad) = (32.0, 3.0); + let mut segs = row().key("springs"); + for (i, (name, _)) in SPRINGS.into_iter().enumerate() { + let selected = i == s.spring; + segs = segs.child( + el().key(name).role("segment").label(name).checked(selected).focusable(true) + .size(seg, h - 2.0 * pad).center() + .on_press(move |s: &mut State| s.spring = i) + .child(text(name).font(TextStyle::new(13.0, 500.0)) + .color(if selected { t.text } else { t.text_secondary })), + ); + } + el().key("picker").size(seg * 3.0 + 2.0 * pad, h).radius(h / 2.0).fill(t.control_track) + .child(el().key("thumb").size(seg, h - 2.0 * pad).radius((h - 2.0 * pad) / 2.0) + .absolute(pad + seg * s.spring as f32, pad) + .fill(oklcha(1.0, 0.0, 0.0, 0.12)) + .motion(SPRINGS[s.spring].1)) + .child(segs.absolute(pad, pad)) +} + +fn track(s: &State, track_w: f32) -> El { + let t = tok::theme(true); + let travel = track_w - PUCK; + let to_at = move |x: f32| ((x - PUCK / 2.0) / travel).clamp(0.0, 1.0); + let mut stops = row().key("stops").w(travel).h(PUCK).absolute(PUCK / 2.0, 0.0); + for i in 0..STOPS { + let x = travel * i as f32 / (STOPS - 1) as f32; + stops = stops.child(el().key(format!("stop-{i}")).size(4.0, 4.0).radius(2.0) + .fill(oklcha(1.0, 0.0, 0.0, 0.22)).absolute(x - 2.0, PUCK / 2.0 - 2.0)); + } + el().key("track").role("slider").label("Puck").range_value(f64::from(s.at), 0.0, 1.0) + .range_step(1.0 / (STOPS - 1) as f64) + .on_step(|s: &mut State, steps, _| s.at = snap(s.at + steps as f32 / (STOPS - 1) as f32).clamp(0.0, 1.0)) + .size(track_w, PUCK) + .motion(SPRINGS[s.spring].1) + .on_drag(move |s: &mut State, d: &mut Drag, tx: &mut Tx| match d.phase { + Phase::Down => { + d.data = s.at; + let puck = PUCK / 2.0 + s.at * travel; + if (d.x - puck).abs() > PUCK / 2.0 + 4.0 { + // Tapped the track: the puck springs to the nearest stop, keeping its speed. + s.at = snap(to_at(d.x)); + } + } + Phase::Move => { + let puck = PUCK / 2.0 + d.data * travel; + let grab = if (d.start_x - puck).abs() <= PUCK / 2.0 + 4.0 { d.start_x - puck } else { 0.0 }; + s.at = to_at(d.x - grab); + tx.instant(); + } + Phase::Up => { + s.at = if d.cancelled() { d.data } else { snap(s.at) }; + } + }) + .child(el().key("rail").size(travel, 2.0).radius(1.0).fill(t.control_off) + .absolute(PUCK / 2.0, PUCK / 2.0 - 1.0).a11y_hidden()) + .child(el().key("lit").size(travel * s.at, 2.0).radius(1.0).fill(ink()) + .absolute(PUCK / 2.0, PUCK / 2.0 - 1.0).a11y_hidden()) + .child(stops.a11y_hidden()) + .child(el().key("puck").size(PUCK, PUCK).radius(PUCK / 2.0).fill(t.knob) + .absolute(travel * s.at, 0.0) + .shadow(2.0, 8.0, oklcha(0.0, 0.0, 0.0, 0.5)).a11y_hidden()) +} + +fn line(label: &str, control: El) -> El { + let t = tok::theme(true); + row().w_full().h(36.0).center_y() + .child(text(label.to_string()).font(TextStyle::new(14.0, 400.0)).color(t.text_secondary).grow(1.0)) + .child(control) +} + +fn view(s: &State, cx: &mut Cx<State>) -> El { + // As wide as the page lets it be, up to CARD_W; the canvas is as wide as its parent. + let stage = cx.layout_size("stage").map_or(560.0, |[w, _]| w); + let card_w = (stage - 16.0).clamp(280.0, CARD_W); + let pad = if card_w < CARD_W { 20.0 } else { 32.0 }; + let inner = card_w - 2.0 * pad; + let seg = ((inner - 76.0) / 3.0).min(88.0); + let card = col().key("card").w(card_w).padding(pad).gap(16.0).radius(20.0) + .fill(oklch(0.17, 0.006, 265.0)) + .border(1.0, oklcha(1.0, 0.0, 0.0, 0.08)) + .child(line("Lights", switch(s))) + .child(line("Spring", picker(s, seg))) + .child(el().h(8.0)) + .child(track(s, inner)); + col().key("stage").w_full().h(STAGE_H).center().fill(Color::BLACK).child(card) +} + +fn spec() -> AppSpec<State> { + AppSpec::new("Rune", (560.0, STAGE_H), State::default, view) +} + +#[cfg_attr(target_arch = "wasm32", wasm_bindgen::prelude::wasm_bindgen(start))] +pub fn start() { + #[cfg(target_arch = "wasm32")] + { + if let Err(error) = rune::App::new(spec()).canvas_id("rune-live").fit_content_height().try_run() { + web_sys_log(&format!("{error}")); + } + } + #[cfg(not(target_arch = "wasm32"))] + rune::run(spec()); +} + +#[cfg(target_arch = "wasm32")] +#[wasm_bindgen::prelude::wasm_bindgen] +extern "C" { + #[wasm_bindgen(js_namespace = console, js_name = error)] + fn web_sys_log(message: &str); +} diff --git a/app/vendor/rune/examples/web-showcase/src/main.rs b/app/vendor/rune/examples/web-showcase/src/main.rs new file mode 100644 index 0000000..dfb01e6 --- /dev/null +++ b/app/vendor/rune/examples/web-showcase/src/main.rs @@ -0,0 +1,3 @@ +#![forbid(unsafe_code)] + +fn main() { web_showcase::start(); } diff --git a/app/vendor/rune/research/01-gpui-zed-warp.md b/app/vendor/rune/research/01-gpui-zed-warp.md new file mode 100644 index 0000000..1659665 --- /dev/null +++ b/app/vendor/rune/research/01-gpui-zed-warp.md @@ -0,0 +1,344 @@ +# 01 — GPUI, Zed Text & Rendering Architecture, and Warp's UI Framework (`warpui`) + +**Sources inspected directly:** +- `kitlangton/gpui` (`gpui 0.2.2` + Kit's commit `2582af8`, "Fix Metal display link fallback and rendering quality") +- `zed-industries/zed` (`5447804`, Oct 2026) — `crates/gpui`, `crates/gpui_apple`, `crates/gpui_macos`, `crates/gpui_ios`, `crates/gpui_linux`, `crates/gpui_windows`, `crates/gpui_wgpu`, `crates/gpui_web`, `crates/sum_tree`, `crates/rope`, `crates/text`, `crates/multi_buffer`, `crates/editor` +- `warpdotdev/warp` (`f8a9c71`, Oct 2026) — `crates/warpui_core` (MIT), `crates/warpui` (MIT), and ["How Warp Works"](https://www.warp.dev/blog/how-warp-works) +- a private Mac launcher app, cited as `launcher/` (`docs/motion.md`, `docs/glass.md`, `docs/perf-log.md`, `docs/raycast-research.md`, `src/native_ui.rs`) +- `scrawl` (`src/native/pill/{mod.rs,model.rs,atlas.rs,pill.metal}`, `scrawl/perf/start-latency.md`) + +--- + +## Executive Summary + +1. **GPUI has grown into a 174k-LoC multi-crate platform engine (`gpui*` across 13 crates at Zed `5447804`), up from ~97k LoC in `gpui 0.2.2`.** Between `0.2.2` and Oct 2026, Zed split GPUI into `gpui` (101,878 LoC), `gpui_apple` (5,351 LoC, shared Metal + CoreText), `gpui_macos` (9,711 LoC), `gpui_ios` (3,684 LoC), `gpui_linux` (16,934 LoC), `gpui_windows` (14,798 LoC), `gpui_wgpu` (7,969 LoC, replacing `blade-graphics` and powering Linux + Web), and `gpui_web` (7,866 LoC, WASM + WebGPU/WebGL2 + Canvas2D fallback). +2. **GPUI's renderer is a flat 7-primitive batcher (`Shadow`, `Quad`, `Underline`, `MonochromeSprite`, `SubpixelSprite`, `PolychromeSprite`, `Path`, `Surface`) sorted by a 4-ary spatial R-tree (`BoundsTree`).** It achieves ~0.2–0.8 ms GPU encode/render times for typical editor frames by packing primitives into a single 64 KB-aligned `InstanceBuffer` (`crates/gpui_apple/src/metal_renderer.rs:58-77`) and merging non-overlapping draw batches across `DrawOrder` via `BoundsTree<Bounds<ScaledPixels>>` (`crates/gpui/src/bounds_tree.rs:14-18`, `MAX_CHILDREN = 4`). +3. **GPUI's biggest rendering weaknesses are full-window redraws, lack of offscreen layer/filter compositing, and synchronous window-resize barriers.** GPUI clears and redraws the entire window drawable every dirty frame (`MTLLoadAction::Clear`, no dirty-rect scissor damage). Its `AnyView::cached` mechanism (`crates/gpui/src/view.rs:258-312`, `crates/gpui/src/window.rs:4014-4123`) only skips *CPU* layout/prepaint/paint by replaying `Scene` slices (`Scene::replay`, `crates/gpui/src/scene.rs:208-274`). Worse, `Path` batches clear and resolve a full-viewport 4x MSAA intermediate texture on *every* path batch (`crates/gpui_apple/src/metal_renderer.rs:1100-1215`), and live window resizing sets `presentsWithTransaction = true` with `command_buffer.waitUntilScheduled()` on the main thread (`crates/gpui_apple/src/metal_renderer.rs:845-853`). +4. **Two of Kit's four `kitlangton/gpui` (`2582af8`) fixes are still missing in upstream Zed (`5447804`).** Upstream Zed now includes perceptual luminance-based glyph dilation (`glyph_dilation_for_color`, `crates/gpui_apple/src/text_system.rs:265-274, 510-516`) and triangular blue-noise gradient dithering (`gradient_color`, `crates/gpui_apple/src/shaders.metal:326-331`). However, upstream Zed **still** lacks Gaussian shadow dithering in `shadow_fragment` (`crates/gpui_apple/src/shaders.metal:472-502`), still leaves `CAMetalLayer` colorspace unconfigured when `use_display_p3` is false (`crates/gpui_apple/src/metal_renderer.rs:321-334`), and still lacks the `CVDisplayLinkCreateWithCGDisplay` fallback in `crates/gpui_macos/src/display_link.rs:28-56` (causing `kCVReturnInvalidDisplay = -6661` panics/failures on headless or asleep Mac Studio displays). +5. **GPUI's 3-phase `Element` pipeline (`request_layout` → `prepaint` → `paint`) + `EntityMap` lease model is ergonomic for static/editor UIs but brittle for choreographed motion and nested state.** Entities are leased out of a `SecondaryMap<EntityId, Box<dyn Any>>` onto the stack during `update` (`crates/gpui/src/app/entity_map.rs:138-233`), causing runtime `double_lease_panic` crashes whenever an observer, event callback, or AppKit delegate re-enters an entity currently being updated. +6. **Zed's text engine (`sum_tree` → `rope` → `text` → `multi_buffer` → `editor::display_map`) is best-in-class and cleanly decoupled from GPUI.** `SumTree<T>` (`crates/sum_tree/src/sum_tree.rs:18`, `TREE_BASE = 6`, 12 items/node) + `Chunk` (`crates/rope/src/chunk.rs:9-33`, 128-byte `ArrayString` with four `u128` bitmaps for `chars`, `chars_utf16`, `newlines`, `tabs`) provides $O(\log N)$ seek between UTF-8 bytes, UTF-16 code units, and `Point(row, col)` using hardware `popcnt`/`tzcnt`, and `LineLayoutCache` (`crates/gpui/src/text_system/line_layout.rs:458-560`) adds zero-allocation `shape_line_by_hash` (`crates/gpui/src/text_system.rs:689-720`). +7. **Upstream GPUI added `spring.rs`, `hot_reload.rs` (`subsecond`), `AccessKit` (`window/a11y.rs`), `gpui_ios`, and `gpui_web`, but animation remains a closure wrapper.** Even with `SpringAnimation` (`crates/gpui/src/spring.rs:1-214`), GPUI animations work by cloning and rebuilding the wrapped element subtree inside `request_layout` on every tick (`crates/gpui/src/elements/animation.rs:208-246`), with no persistent velocity across interrupted retargets, no off-main-thread compositor, and no GPU-property-only fast path. +8. **The launcher and Scrawl both hit hard architectural walls in GPUI and replaced GPUI windows with native AppKit/Core Animation/Metal surfaces.** The launcher's GPUI morph suffered 6 structural visual defects (`launcher/docs/motion.md:20-75`), 11–18 ms cold glyph/emoji stalls (`launcher/docs/perf-log.md:72-97`), and 641 µs `SyncList` re-measurements, leading it to move its panel to a `WindowServer`-composited `CASpringAnimation` + SwiftUI panel (`launcher/src/native_ui.rs`). Scrawl replaced GPUI's `HudPillWindow` with a 440-line 3-pass native `CAMetalLayer` + `NSGlassEffectView` renderer (`scrawl/src/native/pill/mod.rs:1-31`) to get offscreen blur/glow passes, sub-millisecond cold start (`0.08 ms` hidden init vs `6.93 ms` eager), and zero idle CPU. +9. **Warp's `warpui` (`crates/warpui_core` + `crates/warpui`, MIT-licensed in `warpdotdev/warp`) is GPUI v1's direct sibling—originally co-designed with Nathan Sobo in 2021.** Warp kept the retained `Presenter` + Flutter-style `SizeConstraint` `Element` tree while adding two notable innovations GPUI lacks: thread-local automatic dependency tracking via `Tracked<T>` (`crates/warpui_core/src/core/autotracking/mod.rs:1-200`, eliminating manual `cx.notify()`) and a dual GUI + Ratatui TUI presenter (`crates/warpui_core/src/presenter/tui.rs:1-150`). However, its rendering pipeline (3 shaders, shelf-next-fit atlas without eviction, no subpixel AA, no offscreen filter passes) is less capable than GPUI's. +10. **Recommendation for Rune: Do NOT fork GPUI (or `warpui`); build a fresh, modular architecture while stealing `sum_tree`/`rope`, `BoundsTree` batching, `etagere` + `LineLayoutCache`, and `kitlangton/gpui` (`2582af8`) shader/text refinements.** Forking GPUI locks Rune into a 174k-LoC monolithic `App`/`Window` god-object where fixing borrow-reentrancy, retained compositor layers, interruptible spring retargeting, offscreen filter graphs, and damage-tracked rendering requires rewriting the core anyway. + +--- + +## 1. GPUI Renderer (`gpui`, `gpui_apple`, `gpui_wgpu`, `gpui_windows`) + +### 1.1 Scene Representation & Batching (`crates/gpui/src/scene.rs`, `bounds_tree.rs`) +Every frame, GPUI's paint phase populates a flat `Scene` struct (`crates/gpui/src/scene.rs:34-46`): + +```rust +pub struct Scene { + pub(crate) shadows: Vec<Shadow>, + pub(crate) quads: Vec<Quad>, + pub(crate) paths: Vec<Path<ScaledPixels>>, + pub(crate) underlines: Vec<Underline>, + pub(crate) monochrome_sprites: Vec<MonochromeSprite>, + pub(crate) subpixel_sprites: Vec<SubpixelSprite>, + pub(crate) polychrome_sprites: Vec<PolychromeSprite>, + pub(crate) surfaces: Vec<PaintSurface>, + layer_stack: Vec<DrawOrder>, + bounds_tree: BoundsTree<Bounds<ScaledPixels>>, +} +``` + +- **Spatial `DrawOrder` assignment via `BoundsTree`:** Instead of assigning monotonically increasing z-indices (which would break batching whenever a parent draws a quad, then text, then another sibling quad), `Scene::insert_primitive` queries `bounds_tree.insert(bounds)` (`crates/gpui/src/scene.rs:171-206`). `BoundsTree` (`crates/gpui/src/bounds_tree.rs:14-18`) is a custom 4-ary R-tree (`MAX_CHILDREN: usize = 4`) where each node stores the maximum `u32` ordering among its descendants. Querying the tree finds the highest `DrawOrder` of any *spatially intersecting* primitive already in the scene and assigns `max_overlapping_order + 1`. Non-overlapping primitives of the same kind therefore receive identical `DrawOrder`s (or sort adjacent to each other). +- **Finish & `PrimitiveBatch` iterator:** At the end of `Window::draw`, `Scene::finish()` (`crates/gpui/src/scene.rs:283-292`) sorts all 7 primitive vectors by `(draw_order, id)` using `.sort_unstable()`. During `present()`, `Scene::batches()` (`crates/gpui/src/scene.rs:299-415`) runs a 7-way merge iterator that coalesces contiguous primitives of the same kind (and same `AtlasTextureId` for sprites) into a single `PrimitiveBatch` instanced draw call. +- **Coordinate spaces:** Layout runs in logical `Pixels(f32)`, scene primitives are stored in `ScaledPixels(f32)` (`Pixels * scale_factor`), and atlas/rasterization coordinates use integer `DevicePixels(i32)` (`crates/gpui/src/scene.rs:10-25`). + +### 1.2 Metal Backend (`crates/gpui_apple/src/metal_renderer.rs`, `shaders.metal`) +On macOS and iOS, `MetalRenderer` (`crates/gpui_apple/src/metal_renderer.rs:226-265`) renders into a `CAMetalLayer`: +- **Single-buffer instancing:** All per-frame instance data (`Quad`, `Shadow`, `Underline`, `MonochromeSprite`, `SubpixelSprite`, `PolychromeSprite`, `PathRasterizationVertex`, `PathSprite`) is bumped into one shared `InstanceBuffer` (`crates/gpui_apple/src/metal_renderer.rs:58-77`, default capacity `2 * 1024 * 1024` bytes = 2 MB, grown dynamically) with 64 KB-aligned sub-allocations (`align = 64 * 1024`). If the buffer overflows mid-frame, `draw()` returns `false`, doubles `instance_buffer_size`, and retries the command buffer encode (`crates/gpui_apple/src/metal_renderer.rs:483-509`). +- **Triple-buffered pool:** `InstanceBufferPool` (`crates/gpui_apple/src/metal_renderer.rs:79-121`) holds `max_buffers_in_flight = 3` (`CAMetalLayer.maximumDrawableCount = 3`), returning buffers to the pool in the `MTLCommandBuffer` completion handler block (`crates/gpui_apple/src/metal_renderer.rs:835-843`). +- **8 Render Pipeline States:** + 1. `quads` (`quad_vertex` / `quad_fragment`, `crates/gpui_apple/src/shaders.metal:333-444`): SDF rounded rectangle with per-corner radii (`Corners<ScaledPixels>`), per-edge border widths (`Edges<ScaledPixels>`), dashed/solid border antialiasing, and solid/linear-gradient background fill (`BackgroundTag::Solid | LinearGradient | PatternSlash`). + 2. `shadows` (`shadow_vertex` / `shadow_fragment`, `crates/gpui_apple/src/shaders.metal:446-502`): Analytic 4-step Gaussian integral of an SDF rounded box (`erf` approximation along X, 4-sample quadrature along Y). + 3. `underlines` (`underline_vertex` / `underline_fragment`, `crates/gpui_apple/src/shaders.metal:551-621`): Straight or sine-wave (`wavy`) underlines. + 4. `monochrome_sprites` (`monochrome_sprite_vertex` / `monochrome_sprite_fragment`, `crates/gpui_apple/src/shaders.metal:623-702`): Samples `R8Unorm` glyph/SVG masks from `MetalAtlas`, supports 2x2 `TransformationMatrix` (for rotated SVGs), and outputs premultiplied `HSLA -> linear/sRGB RGBA`. + 5. `subpixel_sprites` (`subpixel_sprite_vertex` / `subpixel_sprite_fragment`, `crates/gpui_apple/src/shaders.metal:704-777`): Dual-source blending (`color(0), index(0)` and `color(0), index(1)`) with `Source1Color` blend factor for LCD subpixel text AA. (Note: disabled by default on macOS in `gpui_apple` where grayscale + luminance dilation is preferred, used on Windows/Linux). + 6. `polychrome_sprites` (`polychrome_sprite_vertex` / `polychrome_sprite_fragment`, `crates/gpui_apple/src/shaders.metal:779-858`): `BGRA8Unorm` atlas tiles (color emojis, raster images) with SDF corner clipping, grayscale filter, and opacity. + 7. `paths_rasterization` + `paths` (`path_rasterization_vertex`/`fragment` and `path_vertex`/`fragment`, `crates/gpui_apple/src/shaders.metal:504-549`): Arbitrary vector paths (`PathBuilder`, `crates/gpui/src/path_builder.rs:1-250`). Filled paths use Lyon (`lyon::tessellation::FillTessellator`) or Loop-Blinn quadratic curve UV coordinates (`st_position` in `PathVertex`); stroked paths use `lyon::tessellation::StrokeTessellator`. + 8. `surfaces` (`surface_vertex` / `surface_fragment`, `crates/gpui_apple/src/shaders.metal:860-910`): Hardware-decoded `CVPixelBuffer` (`kCVPixelFormatType_420YpCbCr8BiPlanarFullRange`) YCbCr-to-RGB video surfaces via `CVMetalTextureCache`. + +### 1.3 Severe Bottlenecks in GPUI's Renderer +1. **Path rendering allocates & clears a full-viewport 4x MSAA texture per path batch:** Look at `MetalRenderer::draw_paths_to_intermediate` (`crates/gpui_apple/src/metal_renderer.rs:1100-1215`). Every time `Scene::batches()` yields a `PrimitiveBatch::Paths` (which cannot be merged across an intervening `Quad` or `MonochromeSprite` if bounding boxes overlap), GPUI ends the main `MTLRenderCommandEncoder`, starts a new render pass on a **full-window** `path_sample_count = 4` MSAA texture + resolve texture (`MTLLoadAction::Clear` across the entire viewport, not just the path's bounding box!), renders the path triangles, ends the encoder, and starts a *new* main `MTLRenderCommandEncoder` with `MTLLoadAction::Load` to blit the resolved texture via `path_sprite`. Having N interleaved path layers in a frame triggers $2N + 1$ full render-pass switches and $N$ full-window 4x MSAA clears. +2. **No offscreen layer stack, backdrop filter, or group opacity:** `window.with_element_opacity(opacity, ...)` (`crates/gpui/src/window.rs:1249`) simply multiplies `element_opacity` into each individual quad/sprite color at CPU paint time. Overlapping children within a translucent container bleed through each other (Classic alpha-compositing bug) instead of compositing as a group. There is zero support for offscreen Gaussian blur, vibrancy, or shader post-processing passes—which is why Scrawl had to bypass GPUI for its glowing/blurred HUD pill (`scrawl/src/native/pill/mod.rs:1-31`). +3. **Full-window redraw every frame & `Scene::replay` limits:** GPUI has no dirty-rect scissor/damage tracking at the GPU level; `draw()` always runs `MTLLoadAction::Clear` on the full `CAMetalDrawable`. `Entity::cached` (`crates/gpui/src/view.rs:258`) + `Scene::replay` (`crates/gpui/src/scene.rs:208-274`) copies the previous frame's `Quad`/`MonochromeSprite` structs from `rendered_frame.scene` into `next_frame.scene` and re-inserts every primitive into `BoundsTree` on the CPU. If *any* animation ticks in a window, the entire window's `Scene` is re-sorted, re-uploaded to `InstanceBuffer`, and re-rendered by the GPU. +4. **Synchronous `presentsWithTransaction` stall during resize:** During window resize (`crates/gpui_macos/src/window.rs:3320-3341`), GPUI sets `renderer.set_presents_with_transaction(true)`, which forces `command_buffer.commit(); command_buffer.wait_until_scheduled(); drawable.present();` on the main thread (`crates/gpui_apple/src/metal_renderer.rs:845-853`). + +### 1.4 Cross-Platform Renderers (`gpui_wgpu`, `gpui_windows`) +- **`gpui_wgpu` (`crates/gpui_wgpu/src/wgpu_renderer.rs:1-250`):** In `gpui 0.2.2`, Linux used `blade-graphics`. By Oct 2026 (`5447804`), Zed replaced `blade-graphics` with `gpui_wgpu` (7,969 LoC), which now powers **both** `gpui_linux` (Wayland + X11 via Vulkan/GL) and `gpui_web` (WebGPU + WebGL2 fallback). It implements the exact same 7-primitive pipeline in WGSL (`crates/gpui_wgpu/src/shaders.wgsl`) including dual-source blending (`wgpu::Features::DUAL_SOURCE_BLENDING`) when supported by the adapter (`crates/gpui_wgpu/src/wgpu_renderer.rs:150-166`), falling back to single-source alpha blending on WebGL2/uncooperative drivers. +- **`gpui_windows` (`crates/gpui_windows/src/directx_renderer.rs:1-200`):** Uses raw Direct3D 11 (`ID3D11Device`, `IDXGISwapChain1`) bound to `IDCompositionDevice` / `IDCompositionVisual` (`DirectComposition`) for transparent/acrylic window support and low-latency flip-model presentation, with 4x MSAA intermediate textures for paths (`PATH_MULTISAMPLE_COUNT = 4`, line 29) and HLSL shaders compiled at build time. + +### 1.5 Texture Atlas (`etagere` in `crates/gpui_apple/src/metal_atlas.rs`) +`MetalAtlas` (`crates/gpui_apple/src/metal_atlas.rs:1-250`) wraps `etagere::BucketedAtlasAllocator`: +- Separate texture lists by `AtlasTextureKind`: + - `Monochrome` → `MTLPixelFormatR8Unorm` (glyphs, rasterized `resvg` SVGs) + - `Subpixel` → `MTLPixelFormatBGRA8Unorm` + - `Polychrome` → `MTLPixelFormatBGRA8Unorm` (color emojis, images) +- Starting page size: **1024×1024** for Monochrome/Subpixel, **2048×2048** for Polychrome (`crates/gpui_apple/src/metal_atlas.rs:138-145`), dynamically allocating additional `MTLTexture` pages when `etagere` fills up. +- Uploads happen synchronously on the CPU into `MTLStorageModeManaged` (Intel) or `MTLStorageModeShared` (Apple Silicon unified memory) via `replaceRegion_mipmapLevel_withBytes_bytesPerRow` (`crates/gpui_apple/src/metal_atlas.rs:265-285`). + +### 1.6 Exact Diff Analysis: `kitlangton/gpui` (`2582af8`) vs Upstream Zed (`5447804`) +In `kitlangton/gpui`, commit `2582af8` ("Fix Metal display link fallback and rendering quality", 4 files changed, +127/-16 lines) fixed four concrete production bugs in `gpui 0.2.2`: + +| Fix in `kitlangton/gpui` (`2582af8`) | How it works in `kitlangton/gpui` | Status in Upstream Zed (`5447804`, Oct 2026) | +|---|---|---| +| **1. `CVDisplayLink` fallback (`src/platform/mac/display_link.rs:25-60`)** | When `CVDisplayLinkCreateWithCGDisplay(display_id, ...)` fails with `kCVReturnInvalidDisplay` (`-6661`, common on headless/asleep displays or virtual displays), falls back to `CVDisplayLinkCreateWithActiveCGDisplays` and calls `CVDisplayLinkSetCurrentCGDisplay` best-effort. | **MISSING in upstream Zed.** `crates/gpui_macos/src/display_link.rs:28-56` still calls `CVDisplayLinkCreateWithCGDisplay` and immediately returns `Err` on non-zero `CVReturn`! Worse, `crates/gpui_macos/src/window.rs:839-845` skips starting the display link if `!occlusionState.contains(NSWindowOcclusionStateVisible)`, but `WindowFrameSource` still uses a 60 Hz `dispatch_source_create(DISPATCH_source_type_timer)` fallback only when occluded (`display_link.rs:240-310`). | +| **2. Explicit `sRGB` `CAMetalLayer` colorspace (`src/platform/mac/metal_renderer.rs:257-263`)** | Sets `layer.set_colorspace(CGColorSpaceCreateWithName(kCGColorSpaceSRGB))` on the `CAMetalLayer` so macOS WindowServer composites `BGRA8Unorm` in a deterministic sRGB color space instead of untagged device RGB. | **PARTIALLY MISSING in upstream Zed.** `crates/gpui_apple/src/metal_renderer.rs:321-334` only sets `kCGColorSpaceDisplayP3` when `use_display_p3()` is true (`colorspace` setting =P3) and sets `null()` when false, leaving default sRGB windows untagged! | +| **3. Gradient + Shadow dithering (`src/platform/mac/shaders.metal:326-331, 495-503`)** | Adds interleaved gradient noise `dither_noise(position)` (`fract(52.9829189 * fract(dot(position, float2(0.06711056, 0.00583715))))`) with triangular PDF `(n1 + n2 - 1.0) / 255.0` to **both** linear gradients (`gradient_color`) **and** `shadow_fragment` (scaled by `min(alpha * 2.0, 1.0)`), eliminating 8-bit Mach banding on dark glass/shadows. | **HALF-MERGED in upstream Zed.** `crates/gpui_apple/src/shaders.metal:326-331` has the exact same `gradient_color` triangular dither, **but `shadow_fragment` (`crates/gpui_apple/src/shaders.metal:472-502`) has NO dithering**, so subtle dark drop shadows still band in 8-bit `BGRA8Unorm`. | +| **4. Perceptual luminance glyph dilation (`src/platform/mac/text_system.rs:274-305, 514-525`)** | Replaces constant black-on-white CoreGraphics glyph rasterization (`set_gray_fill_color(0.0, 1.0)`) with 5 discrete dilation levels (`0..=4`) keyed in `RenderGlyphParams::dilation` based on perceptual luminance `(0.2126*R + 0.7152*G + 0.0722*B).sqrt()`, calling `cx.set_should_smooth_fonts(true)` + `cx.set_gray_fill_color(luminance, 1.0)` so light text on dark backgrounds gets native macOS stem thickening. | **MERGED in upstream Zed.** Present verbatim in `crates/gpui_apple/src/text_system.rs:265-274, 510-516` (`glyph_dilation_for_color`, `params.dilation as f64 * 0.25`). | + +--- + +## 2. Element / View / Entity Model (`crates/gpui/src/{app.rs,view.rs,element.rs,window.rs}`) + +### 2.1 Ownership & the `EntityMap` Lease Model (`crates/gpui/src/app/entity_map.rs`) +GPUI solves Rust's single-owner graph problem by making `App` the sole owner of all stateful models and views (`crates/gpui/src/_ownership_and_data_flow.rs:1-40`): +- `EntityMap` (`crates/gpui/src/app/entity_map.rs:56-60`) stores `entities: SecondaryMap<EntityId, Box<dyn Any>>` alongside `ref_counts: Arc<RwLock<EntityRefCounts>>` (a `SlotMap<EntityId, AtomicUsize>`). +- `Entity<T>` is a lightweight handle (`EntityId` + `Weak<RwLock<EntityRefCounts>>` + `PhantomData<T>`) that increments/decrements the atomic refcount on `Clone`/`Drop` and pushes zero-refcount IDs onto `dropped_entity_ids` (`crates/gpui/src/app/entity_map.rs:190-209`). +- **How `entity.update(cx, |this, cx| ...)` works:** `EntityMap::lease` (`crates/gpui/src/app/entity_map.rs:138-167, 219-227`) **physically removes** `Box<dyn Any>` from `self.entities` (`self.entities.remove(entity_id)`), moves it onto the call stack inside a `Lease<T>`, runs the closure with `(&mut T, &mut Context<T>)`, and re-inserts it in `end_lease` (`self.entities.insert(entity_id, entity)`). +- **The Re-Entrancy Footgun (`double_lease_panic`):** Because `lease` removes the `Box<dyn Any>` from `SecondaryMap`, *any* attempt to `.read(cx)` or `.update(cx)` that same `Entity<T>` while its `update` closure is still on the call stack hits `None` and panics at runtime (`crates/gpui/src/app/entity_map.rs:230-233`): + ```rust + panic!("cannot {operation} {entity_type} while it is already being updated") + ``` + While `Context::notify()` and `Context::emit()` queue effects onto `App::pending_effects` (`VecDeque<Effect>`) and flush them in a loop only when the outermost `App::update` finishes, synchronous callbacks (such as window activation/appearance callbacks, focus listeners, or helper methods passed an `&mut App` that also hold an `Entity<Self>`) routinely trigger this panic. Note `crates/gpui/src/window.rs:1992-2000` where Zed itself had to spawn an async task on `foreground_executor` inside `on_appearance_changed` specifically to avoid a synchronous App borrow panic! + +### 2.2 Views (`Render`), Components (`RenderOnce`), and the 3-Phase `Element` Pipeline +In GPUI (`crates/gpui/src/view.rs:197-247`, `crates/gpui/src/element.rs:1-520`): +- **Stateful Views (`impl Render for MyView`):** Hold persistent state in `Entity<MyView>`. Calling `cx.notify()` marks the `EntityId` dirty in `window.dirty_views` (`crates/gpui/src/window.rs:2265-2275`). +- **Stateless Components (`#[derive(IntoElement)] impl RenderOnce for MyButton`):** Consumed by value (`fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement`) each frame. +- **3-Phase `Element` Trait (`crates/gpui/src/element.rs:50-145`):** + 1. **`request_layout(&mut self, global_id, inspector_id, window, cx) -> (LayoutId, Self::RequestLayoutState)`:** Builds the Taffy layout tree (`TaffyLayoutEngine`, `crates/gpui/src/taffy.rs:31-107`, which wraps `taffy::TaffyTree` with `taffy.disable_rounding()` and custom pixel-snapping in `compute_layout`). Views call `Render::render` during this phase (or during `prepaint` if cached). + 2. **`prepaint(&mut self, global_id, inspector_id, bounds, request_layout, window, cx) -> Self::PrepaintState`:** Runs **after** Taffy solves `compute_layout` at the root (`crates/gpui/src/window.rs:3721-3728`). Every element now knows its resolved `Bounds<Pixels>`. Elements register `Hitbox`es (`window.insert_hitbox`), push `DispatchNode`s into `DispatchTree` for keyboard/action routing, build `AccessKit` nodes if a screen reader is active (`crates/gpui/src/element.rs:428-463`), and shape text lines. + 3. **`paint(&mut self, global_id, inspector_id, bounds, request_layout, prepaint, window, cx)`:** Runs after `self.mouse_hit_test = self.next_frame.hit_test(self.mouse_position)` (`crates/gpui/src/window.rs:3758`). Because hit-testing happens *between* `prepaint` and `paint`, elements can query `hitbox.is_hovered(window)` during `paint` and emit hover colors/cursors on the same frame without a 1-frame lag! Elements push primitives into `window.next_frame.scene` and register mouse listeners (`window.on_mouse_event`). +- **`ElementArena` (`crates/gpui/src/arena.rs`, `window.rs:395-476`):** `AnyElement` boxes are bump-allocated into a per-`App` `Arena` (cleared at the end of `window.draw(cx)` via `arena_clear_needed.clear(cx)`, `crates/gpui/src/window.rs:1910-1912`) so constructing thousands of `Div`/`Svg`/`Canvas` elements per frame does not hit the system allocator. +- **Cross-frame Element State (`GlobalElementId`):** Elements with an explicit `.id(...)` push onto `window.element_id_stack` (`ElementIdStack`, `crates/gpui/src/window.rs:1023`), forming a path-hashed `GlobalElementId` (`crates/gpui/src/element.rs:250-285`). `window.with_element_state::<S, _>(global_id, ...)` moves state from `rendered_frame.element_states` (`FxHashMap<(GlobalElementId, TypeId), ElementStateBox>`) into `next_frame.element_states` (`crates/gpui/src/window.rs:1203-1210`). Unvisited state is automatically dropped at frame end (immediate-mode GC). +- **View Caching (`Entity::cached`, `crates/gpui/src/view.rs:258, 484-643`):** Opt-in only (`entity.cached(style)`), requiring a caller-supplied definite `StyleRefinement` because GPUI skips calling `Render::render` during `request_layout`! During `prepaint_view` (`view.rs:546-561`), if `bounds`, `content_mask`, and `text_style` match the previous frame and `!window.dirty_views.contains(&entity_id)`, GPUI calls `window.reuse_prepaint` and `window.reuse_paint` (`crates/gpui/src/window.rs:4014-4123`), which slice-clones hitboxes, mouse listeners, dispatch tree nodes, line layouts, and `Scene` primitives from `rendered_frame` into `next_frame`. **Pain point:** Notice comments at `window.rs:3463-3500` and `3893-3900`—because `reuse_prepaint`/`reuse_paint` rely on fragile index ranges (`Range<PrepaintStateIndex>`, `Range<PaintIndex>`) into flat `Frame` vectors, any mutation that shifts vector indices (such as nested `deferred_draws` or `.pop()` on `input_handlers`) corrupts cached subtrees and panics! + +### 2.3 Focus, Actions, and Keybinding Dispatch (`crates/gpui/src/key_dispatch.rs`) +- **`FocusHandle` & `FocusId` (`crates/gpui/src/window.rs:543-726`):** Ref-counted slotmap key owned by `App::focus_handles`. During `prepaint`, `.track_focus(&focus_handle)` attaches a `FocusId` to the current `DispatchNode` in `DispatchTree` (`crates/gpui/src/key_dispatch.rs:220-224`). +- **`DispatchTree` & `KeyContext` (`crates/gpui/src/key_dispatch.rs:71-250`):** Every frame builds a tree of `DispatchNode`s mirroring the element hierarchy. Each node can hold a `KeyContext` (e.g., `"Editor && mode == full"`), `focus_id`, `key_listeners`, and `action_listeners` (`TypeId` → closure). +- **Capture & Bubble Phases:** When a keystroke arrives, `DispatchTree::dispatch_key` computes the `focus_path` from the root `DispatchNode` down to the focused `FocusId`, matches single-key or multi-key chord sequences (`"cmd-k left"`) against the `Keymap` from deepest context to root, and dispatches the resulting `Action` (`Capture` phase top-down, then `Bubble` phase bottom-up). + +--- + +## 3. Text & Layout System (`crates/gpui/src/text_system.rs`, `sum_tree`, `rope`, `text`, `multi_buffer`) + +### 3.1 Platform Shaping & Rasterization Backends +GPUI abstracts platform text shaping behind `PlatformTextSystem` (`crates/gpui/src/platform.rs`): +1. **macOS & iOS (`AppleTextSystem`, `crates/gpui_apple/src/text_system.rs:1-749`):** + - Uses `font-kit` for font loading/metrics and Apple **CoreText** (`CTLine::new_with_attributed_string`, `crates/gpui_apple/src/text_system.rs:540-636`) for shaping. + - **Ligature-breaking trick across syntax runs (`crates/gpui_apple/src/text_system.rs:567-579`):** Because CoreText shapes an entire `CFAttributedString` at once and will form ligatures across adjacent syntax tokens if their attributes are identical, GPUI alternates `px(f32::from(font_size).next_up())` (1 ULP float increment!) on adjacent `FontRun`s (`break_ligature = !break_ligature`) so CoreText breaks ligatures at token boundaries (e.g. when a cursor or selection splits `!=`). + - **Subpixel positioning & Dilation (`crates/gpui_apple/src/text_system.rs:480-537`):** Rasterizes glyphs into an 8-bit grayscale `CGContext` (or 32-bit RGBA premultiplied for color emojis, swapped to straight-alpha BGRA) with `SUBPIXEL_VARIANTS_X = 4, SUBPIXEL_VARIANTS_Y = 1` (`crates/gpui/src/text_system.rs:49-52`), shifting the glyph origin by `subpixel_variant / 4.0` device pixels and applying 5-step luminance dilation (`0.0..=1.0` gray fill color with `set_should_smooth_fonts(true)`). +2. **Linux & Web (`CosmicTextSystem`, `crates/gpui_wgpu/src/cosmic_text_system.rs:1-200`):** + - Uses `cosmic-text` (`FontSystem`, `ShapeLine`, `ShapeBuffer` — which uses `rustybuzz` / HarfBuzz under the hood) for shaping and `swash` (`ScaleContext`) for subpixel-positioned glyph/emoji rasterization. + - On `gpui_web` (`crates/gpui_web/src/text_system.rs:1-200`), `WebTextSystem` wraps `CosmicTextSystem` (loaded with embedded fonts) and adds a **Canvas2D fallback** (`CanvasFontFallback`) that measures and rasterizes missing CJK/emoji glyphs via the browser's native `<canvas>` 2D context using system fonts! +3. **Windows (`DirectWriteTextSystem`, `crates/gpui_windows/src/direct_write.rs:1-200`):** + - Uses `IDWriteFactory5`, `IDWriteTextAnalyzer1`, and `IDWriteFontFallback` for shaping, ClearType subpixel rendering with gamma/contrast tables (`DirectXRenderer::get_font_info`, `directx_renderer.rs:32-37`), and a dedicated Direct3D 11 shader pass (`ShaderModule::EmojiRasterization`, `direct_write.rs:63-165`) to rasterize layered COLRv0/COLRv1/DirectWrite color glyphs into the atlas. + +### 3.2 `LineLayoutCache` & Zero-Allocation Hash Lookups (`crates/gpui/src/text_system/line_layout.rs:458-560`) +- `LineLayoutCache` maintains two `FrameCache` maps (`previous_frame` and `current_frame`). Every shaped line is looked up in `current_frame`; on miss, it checks `previous_frame`, moves the `Arc<LineLayout>` into `current_frame` if found, or calls `platform_text_system.layout_line(...)` on miss. At `finish_frame()`, `previous_frame` is replaced by `current_frame`, automatically evicting any line layout that wasn't used in the frame just drawn. +- **`shape_line_by_hash` (`crates/gpui/src/text_system.rs:689-720`):** Added in recent Zed so the editor can hash rope chunks + `FontRun`s and hit `lines_by_hash` *without* allocating a contiguous `SharedString` per visible line on every frame. + +### 3.3 Zed's Rope, `SumTree`, CRDT `Buffer`, `MultiBuffer`, and `DisplayMap` +Zed's text architecture is a layered tower of immutable, persistent, `Arc`-shared B+ trees (`crates/sum_tree/src/sum_tree.rs:1-200`): + +``` +[ DisplayMap ] ← Highlighting + BlockMap (diagnostics/creases) + ↑ +[ WrapMap ] ← Soft-wrapping transforms (SumTree<WrapTransform>) + ↑ +[ TabMap ] ← Hard-tab expansion transforms + ↑ +[ FoldMap ] ← Code folding transforms (SumTree<FoldTransform>) + ↑ +[ InlayMap ] ← LSP inlay hints injected without mutating buffer + ↑ +[ MultiBuffer ] ← Excerpts from 1..N buffers (SumTree<Excerpt>) — powers project search & split diffs + ↑ +[ text::Buffer ] ← CRDT operation log, Lamport anchors, UndoMap, SumTree<Fragment> + ↑ +[ rope::Rope ] ← SumTree<Chunk> (128-byte ArrayString + 4x u128 bitmaps) +``` + +1. **`SumTree<T: Item>` (`crates/sum_tree/src/sum_tree.rs:18`):** A copy-on-write B+ tree (`Arc<Node<T>>`) with `TREE_BASE = 6` (up to $2 \times 6 = 12$ child pointers or leaf items per node). Every internal node caches a `Summary` (monoid with `zero()` and `add_summary()`) for each child. A single `SumTree` can be indexed and binary-searched (`cursor.seek(&target, Bias::Left)`) along **any `Dimension<'a, S>`** derived from `S` in $O(\log_{12} N)$ time, and cloned in $O(1)$ (`Arc::clone`) for background threads! +2. **`rope::Rope` & `Chunk` (`crates/rope/src/{rope.rs,chunk.rs}`):** + - `Rope` is simply `SumTree<Chunk>` (`crates/rope/src/rope.rs:26-28`). + - Each leaf `Chunk` (`crates/rope/src/chunk.rs:9-33`) holds an inline `ArrayString<128, u8>` (`MAX_BASE = 128`, `MIN_BASE = 64`) plus **four `u128` bitmaps** (1 bit per byte of the 128-byte chunk!): + - `chars: u128` — bit $i$ is 1 iff `text[i]` is a UTF-8 code point start byte. + - `chars_utf16: u128` — bit $i$ is 1 for every UTF-8 start byte, *plus* bit $i+1$ is 1 for 4-byte UTF-8 sequences ($\ge 240$, which take 2 UTF-16 code units). Thus `(chars_utf16 & mask).count_ones()` gives the exact UTF-16 offset in 1 CPU instruction! + - `newlines: u128` — bit $i$ is 1 iff `text[i] == b'\n'`. + - `tabs: u128` — bit $i$ is 1 iff `text[i] == b'\t'`. + - Each node summarizes `TextSummary { len: usize, chars: usize, len_utf16: OffsetUtf16, lines: Point, first_line_chars: u32, last_line_chars: u32, last_line_len_utf16: u32, longest_row: u32, longest_row_chars: u32 }`. Converting between byte offset, `Point(row, column)`, and LSP `PointUtf16(row, utf16_col)` descends the `SumTree` to the 128-byte `Chunk` and uses bitwise mask + `count_ones()` (`popcnt`) / `leading_zeros()` (`lzcnt`)—no linear byte scanning. +3. **`text::Buffer` & `Anchor` (`crates/text/src/{text.rs,anchor.rs}`):** + - Implements an operation-based CRDT (`BufferSnapshot`, `crates/text/src/text.rs:113-124`) backed by `visible_text: Rope`, `deleted_text: Rope`, `fragments: SumTree<Fragment>`, and `insertions: SumTree<InsertionFragment>`. + - `Anchor` (`Lamport` timestamp + offset within insertion fragment + `Bias`) survives arbitrary concurrent local and remote edits and resolves back to a byte/`Point` offset in $O(\log N)$ via `fragments`. +4. **`multi_buffer::MultiBuffer` (`crates/multi_buffer/src/multi_buffer.rs:74-93`):** + - Presents either a single `Buffer` (`singleton: true`) or a `SumTree<Excerpt>` stitching slices from multiple `Buffer`s into one unified coordinate space (`MultiBufferRow`, `MultiBufferPoint`, `Anchor`). Every Zed editor view—single file, multibuffer project search results, inline git diff hunks, and split diffs—renders a `MultiBuffer`. +5. **`editor::DisplayMap` (`crates/editor/src/display_map.rs:1-145`):** + - A 5-layer pipeline (`InlayMap` → `FoldMap` → `TabMap` → `WrapMap` → `BlockMap`) where each layer is a `SumTree<Transform>` with `TransformSummary { input: TextSummary, output: TextSummary }`. Incrementally synced via `Patch<T>` (`Edit<InputDim>` → `Edit<OutputDim>`), allowing soft-wrapping (`WrapMap` runs asynchronously on a background thread when lines exceed a threshold), code folding, inlay hints, and inline diagnostic/AI blocks without mutating the underlying `MultiBuffer`. + +### 3.4 IME & Accessibility Integration +- **macOS `NSTextInputClient` (`crates/gpui_macos/src/window.rs:236-270, 3368-3587`):** Implemented via Objective-C runtime class registration on `GPUIView`, forwarding `insertText:replacementRange:`, `setMarkedText:selectedRange:replacementRange:`, `unmarkText`, `firstRectForCharacterRange:actualRange:`, and `characterIndexForPoint:` to the active element's `PlatformInputHandler` (registered during `paint` via `window.handle_input(&focus_handle, handler, cx)`). +- **iOS `UITextInput` (`crates/gpui_ios/src/ios/text_input.rs:129-200`):** Implemented via a hidden responder `GPUITextInputView` subclassing `UIView` with custom `GPUITextPosition`, `GPUITextRange`, and `GPUITextSelectionRect` classes. +- **Web `ImeMirror` (`crates/gpui_web/src/window.rs:57, 70-86`):** Synchronizes a hidden DOM `<textarea>` (`ImeMirror`) with the canvas caret. +- **Accessibility (`crates/gpui/src/window/a11y.rs`, `crates/gpui/src/_accessibility.rs`):** Recently added `AccessKit` integration (`accesskit::TreeUpdate` built lazily during `prepaint` only when `window.a11y.is_active()` is true, `crates/gpui/src/window.rs:3691-3694, 3790-3815`, using `GlobalElementId::accesskit_node_id()`, `crates/gpui/src/element.rs:253-255, 428-463`). + +--- + +## 4. Animation, Platform Layer, Hot Reload, and Real-World Failure Modes + +### 4.1 Animation Architecture (`crates/gpui/src/elements/animation.rs`, `spring.rs`) +- **In `gpui 0.2.2` (`kitlangton/gpui`):** Only time-based `Animation { duration, oneshot, easing: Rc<dyn Fn(f32) -> f32> }` (`ease_in_out`, `cubic_bezier`, `pulsating_between`, `bounce`). +- **In Zed `5447804` (`crates/gpui/src/spring.rs:1-214`):** Upstream Zed added an analytic underdamped/critically-damped/overdamped harmonic oscillator solver (`SpringConfig { stiffness, damping, mass }`, presets `SpringConfig::snappy()` = stiffness 400 / damping 30, `bouncy()` = 300 / 15, `smooth()` = 200 / 25) and `SpringAnimation<T: Interpolatable>` (`f32`, `Pixels`, `Point<Pixels>`, `Size<Pixels>`, `Hsla`). +- **Why GPUI's animation model is still fundamentally limited:** + 1. **Immediate-mode subtree cloning on every tick:** Look at `AnimationElement::request_layout` (`crates/gpui/src/elements/animation.rs:208-246`) and `SpringElement::request_layout` (`crates/gpui/src/spring.rs:410-465`). On every frame while an animation is active, GPUI clones the underlying element (`self.element.clone()`), calls the user's animator closure `animator(element, delta)`, schedules `window.request_animation_frame()`, and runs full **Taffy `request_layout` → `prepaint` → `paint` → full-window `Scene` sort → GPU clear & redraw**. + 2. **No velocity preservation on retargeting:** `SpringAnimation` (`crates/gpui/src/spring.rs:165-195`) computes position analytically from `(from, to, start: Instant)` with zero initial velocity ($\dot{x}(0) = 0$). If `to` changes mid-flight (interruptible UI interaction), resetting the spring discards current velocity $\dot{x}(t)$ instead of integrating or solving the initial-value problem with non-zero $v_0$. + 3. **Main-thread bound:** Because animations run inside `Window::draw` via `next_frame_callbacks` (`crates/gpui/src/window.rs:1878-1887`), any main-thread hitch (even 8.4 ms on a 120 Hz ProMotion display) drops frames across every animation in the window. + +### 4.2 Why the Launcher and Scrawl Had to Bypass GPUI +Kit's own production apps (the launcher and `scrawl`) provide the most concrete empirical evidence of where GPUI breaks down: + +#### Case Study A: The launcher (`launcher/docs/{motion.md,perf-log.md}`) +The launcher originally built its panel and compact pill morph in GPUI (`kitlangton/gpui`) and hit two walls: +1. **Six structural motion/compositing defects (`launcher/docs/motion.md:20-75`):** + - *Two competing coordinate spaces:* Moving/resizing the `NSWindow` via AppKit (`window.resize()`) while rendering the inner pill inside GPUI's `Scene` caused 1-frame desynchronization ("two systems fighting over the same pixels"). + - *Top-left anchor jump on collapse:* Switching from the expanded 680×424 window to the compact 100×36 pill caused the pill to render at `(0,0)` (top-left of the large window) for 1–2 frames before `NSWindow::setFrame:` took effect. + - *Hard content pop & background snap:* Because GPUI cannot cross-fade two retained view snapshots as offscreen textures with independent scale/blur transforms, the search bar and results list popped out in 1 frame (`Frame 12 → Frame 13`), and background alpha snapped (`0.95 → 0.30`). + - *Fix in the launcher:* The launcher replaced the GPUI morph and launcher panel with native AppKit/SwiftUI (`launcher/src/native_ui.rs:1-99`) using a single `NSGlassEffectView` / `CAMetalLayer` driven by `CASpringAnimation` in `WindowServer` at a locked 120 Hz with zero per-frame Rust/CPU participation. +2. **Measured GPUI CPU frame times & cold-glyph spikes (`launcher/docs/perf-log.md:1-145`):** + - Steady-state GPUI `Window::draw` CPU frame time (cached): **2.65 ms** before optimization, **1.46 ms** after removing per-row `SyncList` re-measurement (**641 µs/frame** wasted re-measuring row 0) and `TextInput` re-layout (**266 µs/frame**). + - **Cold glyph/emoji rasterization spikes:** Opening the Emoji grid in GPUI caused **11.1–18.4 ms** frame spikes (2.2× the 8.33 ms 120 Hz budget) because `AppleTextSystem::rasterize_glyph` (`crates/gpui_apple/src/text_system.rs:435-537`) synchronously allocates a `CGContext`, renders the `CTFont` glyph on the CPU main thread, and uploads to `MetalAtlas` during `paint`. + - **Memory footprint:** Even an idle GPUI window with `MetalRenderer` (3× 2 MB `InstanceBuffer`s + `MetalAtlas` pages + font caches) consumed **78.8 MB RSS** at launch (`launcher/docs/perf-log.md:135`). + +#### Case Study B: Scrawl (`scrawl/src/native/pill/mod.rs`, `scrawl/perf/start-latency.md`) +Scrawl's HUD pill needs a liquid-glass capsule (`NSGlassEffectView`), an offscreen Gaussian-blurred waveform glow (`glow_a`, `glow_b` intermediate `RGBA8Unorm` textures), and 120 Hz spring animations: +- GPUI's `Scene` cannot express multi-pass offscreen blur (`Pass 1: Clear glow_a` → `Pass 2: H-blur glow_a -> glow_b` → `Pass 3: Composite V-blurred glow_b + SDF shapes + R8 atlas text onto drawable`, `scrawl/src/native/pill/mod.rs:11-23`). +- Scrawl replaced GPUI's `HudPillWindow` with a 440-line native `NSPanel` + `CAMetalLayer` + `CVDisplayLink` module (`scrawl/src/native/pill/{mod.rs,model.rs,atlas.rs,pill.metal}`). +- **Measured startup win (`scrawl/perf/start-latency.md:26-35`):** Deferring `NSPanel`/`CAMetalLayer`/pipeline creation until the pill is shown cut `HudPillHandle::spawn()` cold-start latency from **6.93 ms** to **0.08 ms** (an **86×** reduction), and the display link fully stops (`CVDisplayLinkStop`) when idle for **0% CPU/GPU usage**. + +### 4.3 Mobile (`gpui_ios`), Web (`gpui_web`), Hot Reload (`subsecond`), and Compile Times +- **`gpui_ios` (`crates/gpui_ios/src/ios/{window.rs,text_input.rs}`, 3,684 LoC):** Uses `objc2-ui-kit` (`UIWindow`, `UIViewController`, `GPUIMetalView` with `CAMetalLayer`, `CADisplayLink`, `UIPanGestureRecognizer`, `UIScreenEdgePanGestureRecognizer` for back-swipe, and `GPUITextInputView` implementing `UITextInput`). Still early: `TouchEvent` in `crates/gpui/src/interactive.rs:114-117` explicitly notes *"Dispatch contract (core implementation pending)"*. +- **`gpui_web` (`crates/gpui_web/src/{window.rs,text_system.rs}`, 7,866 LoC):** Runs GPUI in WASM on a full-bleed `<canvas>` using `gpui_wgpu` (`WebGPU` or `WebGL2`), `ResizeObserver`, `requestAnimationFrame`, `ImeMirror`, and `WebTextSystem` (`CosmicTextSystem` + `<canvas>` 2D fallback for system CJK/emoji fonts). +- **Hot Reload (`crates/gpui/src/hot_reload.rs:1-82`, `crates/gpui/src/view.rs:344-352`):** Compiled when `--cfg gpui_hot_reload` is active. Integrates Dioxus's **`subsecond`** binary hot-patching crate (`dx serve --hot-patch`). Every `ViewElement` render passes through `subsecond::HotFn::current(render_view_impl::<V>).call((view, window, cx))` (`crates/gpui/src/view.rs:351`), and when `subsecond` applies a jump-table patch, `hot_reload::register` marks all views in all windows dirty and calls `window.refresh()`. +- **Compile-time & Dependency Weight:** `gpui` + platform crates total **174,157 LoC** and pull in heavy transitive dependencies (`taffy`, `lyon`, `resvg`/`usvg`, `etagere`, `cosmic-text`/`swash`/`fontdb`, `font-kit`, `accesskit`, `wgpu`/`naga`, `objc2-*`/`windows`, `blade-macros`). Clean builds of `gpui` take ~25–45s on Apple Silicon M-series Max/Ultra, and incremental links without `subsecond` or `lld`/`wild` take 2–6s. + +--- + +## 5. Warp's UI Framework (`warpui_core` + `warpui`) + +### 5.1 Shared Genealogy with GPUI & Open-Source Status +In Warp's July 2021 engineering post (["How Warp Works"](https://www.warp.dev/blog/how-warp-works)), Warp explained that they partnered with **Nathan Sobo** (before he left to co-found Zed) to build a Flutter-inspired Rust UI framework on top of Metal and `SumTree`. As of 2026, `warpdotdev/warp` (`f8a9c71`) is open-source on GitHub: the terminal application is AGPL-3.0, while **`crates/warpui_core` (91,602 LoC) and `crates/warpui` (38,862 LoC) are MIT-licensed** (`crates/warpui_core/Cargo.toml:7`, `crates/warpui/Cargo.toml:7`). + +Studying `warpui_core` side-by-side with `gpui` reveals that **`warpui` is the evolutionary sibling of GPUI v1**: +- Both share `App` / `AppContext`, `EntityId`, `ViewHandle<V>` / `ModelHandle<M>`, `Action`, hierarchical `Keymap` context matching, `Scene`, and `sum_tree`. +- Where Zed rewrote GPUI v1 into GPUI v2 (replacing Flutter constraints with Taffy flexbox and replacing retained `Box<dyn Element>` trees with 3-phase arena-allocated immediate/retained elements), Warp kept and evolved the original `Presenter` architecture. + +### 5.2 How `warpui` Differs from GPUI v2 +1. **Retained `Box<dyn Element>` per View (`Presenter`, `crates/warpui_core/src/presenter.rs:28-37, 318-381`):** + - `Presenter` holds `rendered_views: EntityIdMap<Box<dyn Element>>`. + - When a view is invalidated, `Presenter::invalidate` calls `app.render_view(window_id, view_id)` **only** on the invalidated `view_id`s and replaces their `Box<dyn Element>` in `rendered_views` (`presenter.rs:318-331`). Unchanged child views are embedded via `ChildView<T>` (`presenter.rs:282-287`) and never re-run `View::render`! + - Layout is single-pass Flutter-style box constraints (`Element::layout(&mut self, constraint: SizeConstraint, ctx: &mut LayoutContext, app: &AppContext) -> Vector2F`, `crates/warpui_core/src/elements/gui/mod.rs:109-115`), followed by `after_layout` and `paint`. +2. **Thread-Local Automatic Dependency Tracking (`Tracked<T>`, `crates/warpui_core/src/core/autotracking/mod.rs:1-200`):** + - Unlike GPUI (where forgetting `cx.observe(&model, ...)` or `cx.notify()` is a constant source of stale-UI bugs), `warpui_core` provides `Tracked<T>`. + - During `View::render`, `autotracking::render_view` sets a thread-local `CACHE.rendering_view = Some(View { window_id, view_id })` (`autotracking/mod.rs:174-192`). + - Reading a `Tracked<T>` via `Deref` automatically records `(View, TrackedId)` in a bidirectional `HashMap`. Mutating a `Tracked<T>` via `DerefMut` automatically pushes all dependent `View`s into `CACHE.invalidations`, which `App` drains alongside manual `ctx.notify()` calls! +3. **3-Primitive Renderer (`Rect`, `Image`/`Icon`, `Glyph`) + `rstar::RTree` Hit Map (`crates/warpui_core/src/scene.rs:29-123`):** + - `warpui` has **no** vector path tessellator (`lyon`) and **no** separate shadow or underline pipeline. Instead, `Rect` (`crates/warpui/src/platform/mac/rendering/metal/shaders/shaders.metal:9-43, 117-200`) evaluates drop shadow (4-step Gaussian `erf`), per-corner radius, per-edge solid/dashed border, and linear gradient inside a **single uber-fragment shader** (`rect_fragment_shader`)! + - Icons and SVGs are rasterized once via `resvg` into `TextureCache` and drawn via `image_fragment_shader`. + - Glyphs (`glyph_fragment_shader`) support horizontal alpha fades (`GlyphFade::Horizontal { start, end }`, `scene.rs:78-83`) so overflowing terminal/tab text fades out smoothly in the shader without extra mask layers. + - Each `Layer` in `Scene` builds an `rstar::RTree<Rectangle>` (`scene.rs:31`) of opaque hit rects so `EventContext::is_covered(point)` and `visible_rect(origin, size)` can test z-layer occlusion during event dispatch (`presenter.rs:246-258`). + - **Weakness:** `warpui`'s glyph atlas (`crates/warpui/src/rendering/atlas/allocator.rs:13-55`) is a naive shelf-next-fit allocator (`ATLAS_SIZE = 1024`) with **zero eviction**—when `GlyphConfig` changes it blows away all textures (`glyph_cache.rs:80-86`), otherwise it allocates new 1024×1024 `MTLTexture`s forever. +4. **Dual GUI + Ratatui TUI Runtime (`crates/warpui_core/src/presenter/tui.rs:1-150`):** + - Enabled via `--features tui` (`ratatui = "0.30"`). Allows the exact same `App`, `Model`, `EntityId`, `Action`, and `Keymap` core to render either to a GPU window (`Presenter` → `Scene`) or to a terminal screen (`TuiPresenter` → `TuiFrame` cell buffer). +5. **Platform Split:** + - macOS uses custom AppKit + raw Metal (`crates/warpui/src/platform/mac/rendering/metal/renderer.rs:1-200`), reporting **1.9 ms average redraw time (>144 FPS on 4K)** in Warp's telemetry. + - Linux, Windows, and WASM use `winit` + `wgpu` + `cosmic-text`/`swash` (`crates/warpui/src/windowing/winit/` and `crates/warpui/src/rendering/wgpu/renderer.rs:1-145`). + +--- + +## 6. What to Steal vs. What to Avoid + +### Steal (With Exact File Citations) +1. **Zed's `sum_tree` + `rope` (`Chunk` with 4× `u128` bitmaps):** + - *Source:* `zed:crates/sum_tree/src/sum_tree.rs:18-200` and `zed:crates/rope/src/{rope.rs,chunk.rs:9-102}`. + - *Why:* Self-contained (7,765 LoC combined for `sum_tree` + `rope`), zero GPUI dependency, $O(1)$ clone (`Arc`), $O(\log_{12} N)$ multi-dimensional seek across byte/char/UTF-16/`Point(row, col)`, and hardware-accelerated `popcnt`/`tzcnt` within 128-byte leaf chunks. Use it directly or vendor it verbatim for Rune's text buffers and virtualized list height prefix sums. +2. **`BoundsTree` Spatial Z-Order Assignment for Instanced Batching:** + - *Source:* `zed:crates/gpui/src/bounds_tree.rs:14-180` and `zed:crates/gpui/src/scene.rs:171-206`. + - *Why:* A ~200-line 4-ary R-tree that assigns each primitive `max_overlapping_order + 1` instead of a global counter. This turns painter's-algorithm trees (e.g. 100 list rows each drawing a background quad + icon + text) into 3 instanced GPU draw calls instead of 300. +3. **Kit's GPUI fork (`kitlangton/gpui`) (`2582af8`) Rendering & DisplayLink Fixes:** + - *Source:* `kitlangton/gpui` commit `2582af8`: + - Triangular blue-noise dithering in **both** gradients and Gaussian drop shadows (`src/platform/mac/shaders.metal:326-331, 495-503`). + - Perceptual luminance-driven 5-step CoreText glyph dilation (`src/platform/mac/text_system.rs:274-305, 514-525`). + - Explicit `kCGColorSpaceSRGB` (or `kCGColorSpaceExtendedSRGB` / `DisplayP3`) tagging on `CAMetalLayer` (`src/platform/mac/metal_renderer.rs:257-263`). + - `CVDisplayLinkCreateWithCGDisplay` → `CVDisplayLinkCreateWithActiveCGDisplays` fallback (`src/platform/mac/display_link.rs:25-60`) + complete stop when idle (`scrawl/src/native/pill/mod.rs:310-340`). +4. **Two-Generation `LineLayoutCache` + `shape_line_by_hash` + Ligature-Breaking ULP Trick:** + - *Source:* `zed:crates/gpui/src/text_system/line_layout.rs:458-560`, `zed:crates/gpui/src/text_system.rs:689-720`, `zed:crates/gpui_apple/src/text_system.rs:567-579`. + - *Why:* Swapping `current_frame` and `previous_frame` `FxHashMap`s gives zero-overhead frame-to-frame layout retention and automatic eviction of offscreen lines without LRU bookkeeping, while `px(font_size.next_up())` cleanly breaks CoreText ligatures across syntax/selection boundaries. +5. **Hit-Testing Between `prepaint` (Layout Resolved) and `paint`:** + - *Source:* `zed:crates/gpui/src/window.rs:3728-3765`. + - *Why:* Running `hit_test(mouse_position)` immediately after layout/hitbox registration—before `paint`—means hover states and cursors are always 0-frame-lag accurate even when layout shifts under the cursor. +6. **Warp's `Tracked<T>` Automatic Dependency Tracking & `GlyphFade`:** + - *Source:* `warp:crates/warpui_core/src/core/autotracking/mod.rs:1-200` and `warp:crates/warpui_core/src/scene.rs:78-89`. + - *Why:* Automatic read-tracking during `render` eliminates forgotten `cx.notify()` / `cx.observe()` bugs; shader-level horizontal `GlyphFade` clips overflowing text with a smooth gradient at zero extra draw-call or mask-texture cost. +7. **Dioxus `subsecond` Jump-Table Hot Patching Hook at View Boundaries:** + - *Source:* `zed:crates/gpui/src/hot_reload.rs:1-82` and `zed:crates/gpui/src/view.rs:344-352`. + - *Why:* Wrapping view render functions in `subsecond::HotFn::current(...)` gives sub-second Rust UI hot-reloading while preserving live `App`/entity state. + +### Avoid (With Concrete Reasons) +1. **Avoid GPUI's Full-Viewport 4x MSAA Intermediate Pass per `Path` Batch:** + - *Where:* `zed:crates/gpui_apple/src/metal_renderer.rs:1100-1215`. + - *Why:* Clearing and resolving a full-window 4x MSAA texture on every interleaved path batch destroys tile memory bandwidth. Either render vector shapes via analytical SDFs / Vello / slug-style compute shaders, or scissor-clip the MSAA resolve to the tight union of the batch's `Bounds`. +2. **Avoid GPUI's `EntityMap` Remove-on-Lease Pattern Without Granular State Splits:** + - *Where:* `zed:crates/gpui/src/app/entity_map.rs:138-233`. + - *Why:* Leasing an entire view/model out of `SecondaryMap` guarantees runtime `double_lease_panic` crashes whenever nested callbacks, observers, or OS delegates fire synchronously. Fine-grained reactive signals/atoms or split state cells avoid whole-view lease panics. +3. **Avoid Animation-by-Element-Subtree-Rebuild (`AnimationElement` / `SpringElement`):** + - *Where:* `zed:crates/gpui/src/elements/animation.rs:208-246` and `zed:crates/gpui/src/spring.rs:410-465`. + - *Why:* Cloning the element subtree and re-running Taffy layout + full-window CPU/GPU draw on every 120 Hz tick wastes CPU and prevents compositor-level transform/opacity/filter animations. Springs must also preserve velocity $(\dot{x}_0 \ne 0)$ on retargeting. +4. **Avoid Lack of Offscreen Compositor Layers / Filter Passes:** + - *Where:* `zed:crates/gpui/src/scene.rs:34-46`. + - *Why:* Without offscreen layer targets (`RenderLayer` with group opacity, transform matrix, clip mask, Gaussian blur, and blend mode), you cannot build Scrawl-grade glass morphs, cross-dissolving view transitions, or glow passes without dropping down to raw `CAMetalLayer` / `CALayer`. +5. **Avoid Fragile Vector-Slice Index Caching (`reuse_prepaint` / `reuse_paint`):** + - *Where:* `zed:crates/gpui/src/window.rs:4003-4123` and `zed:crates/gpui/src/view.rs:540-642`. + - *Why:* Caching views by recording `(start_idx..end_idx)` slices into global per-frame vectors breaks whenever deferred draws or input handlers shift indices, and still forces the CPU to copy primitives and rebuild `BoundsTree` every frame. Retain per-view display lists (`RenderNode` / `Layer`) directly! +6. **Avoid Synchronous Main-Thread Glyph/Emoji Rasterization Without Prewarming/Async Staging:** + - *Where:* `zed:crates/gpui_apple/src/text_system.rs:435-537` (`launcher/docs/perf-log.md:72-97`). + - *Why:* Cold CoreText/CGContext rasterization of 50+ emojis stalls the main thread for **11–18 ms**, blowing past the 8.33 ms 120 Hz budget. + +--- + +## 7. Recommendation for Rune + +### Decisive Verdict: Build Fresh (Modular Crate Architecture) — Do NOT Fork GPUI or `warpui` + +**Rune should NOT fork GPUI (neither `gpui 0.2.2` nor Zed HEAD `5447804`) and should NOT fork `warpui`.** Instead, Rune should **build a fresh, layered UI & rendering engine** while directly vendoring/adapting Zed's standalone text crates (`sum_tree`, `rope`) and porting ~1,500 lines of proven low-level algorithms (`BoundsTree`, `etagere` atlas + `LineLayoutCache`, and `kitlangton/gpui` `2582af8` shader/text refinements). + +#### Why Starting Fresh Beats Forking GPUI +1. **The 4 architectural walls that forced the launcher and Scrawl off GPUI are load-bearing in GPUI's core:** + - In GPUI, `Window` (`crates/gpui/src/window.rs`, 9,979 LoC) + `App` (`crates/gpui/src/app.rs`) + `Scene` (`crates/gpui/src/scene.rs`) are tightly coupled around a **single-pass, flat-vector, full-window-clear** frame loop. + - Adding **retained compositor layers** (group opacity, 2D/3D layer transforms, offscreen blur/glow render passes like Scrawl's 3-pass HUD pill, and cross-fade view transitions like the launcher's morph), **damage-tracked partial redraws**, **velocity-preserving retargetable springs**, and **fine-grained reactive state that doesn't panic on re-entrant borrows** requires replacing `Scene`, `MetalRenderer::draw`, `ViewElementState`, `AnimationElement`, and `EntityMap`—i.e., rewriting the heart of GPUI while fighting 174,157 lines of Zed-specific coupling. +2. **Massive complexity and compile-time tax for features Rune doesn't want:** + - Upstream GPUI is 174k LoC (and growing rapidly for Zed's specific IDE needs). Maintaining a fork of GPUI (as `kitlangton/gpui` already demonstrated) means either freezing on an old snapshot (`0.2.2`, losing `gpui_wgpu`, `gpui_ios`, `gpui_web`, `AccessKit`, `subsecond`) or rebasing against thousands of Zed-internal commits per month. +3. **The highest-leverage parts of Zed are already small and separable:** + - `sum_tree` (3,327 LoC) + `rope` (4,438 LoC) have **zero** dependency on `gpui`. + - `BoundsTree` is 240 LoC; `MetalAtlas` (`etagere`) is 405 LoC; `shaders.metal` (with `2582af8` fixes) is 910 LoC; `LineLayoutCache` is ~300 LoC. You can bring all of GPUI's best engineering into Rune in **<10,000 LoC** without inheriting the 165,000 LoC of baggage. + +### Rejected Alternatives & Why +1. **Rejected Alternative 1: Forking `kitlangton/gpui` (`gpui 0.2.2` + `2582af8`)** + - *Why rejected:* `gpui 0.2.2` is a 97k-LoC monolithic crate frozen before Zed's `gpui_apple`/`gpui_wgpu`/`gpui_ios`/`gpui_web`/`AccessKit`/`subsecond` work. It still suffers from the 11–18 ms cold emoji stalls, 78.8 MB idle RSS, `double_lease_panic` re-entrancy, lack of offscreen passes, and full-window redraws that forced the launcher and Scrawl to write native SwiftUI/Metal escape hatches. +2. **Rejected Alternative 2: Tracking Upstream Zed's `gpui` (`5447804`) as a Git Dependency or Rebased Fork** + - *Why rejected:* Upstream `gpui` is not published as a stable independent product—its APIs churn weekly to serve Zed, it still lacks two of Kit's `2582af8` fixes (shadow dithering and `CVDisplayLink` fallback), and its flat `Scene` + `InstanceBuffer` architecture still cannot do offscreen blur/glow passes, compositor-driven morphs, or partial-damage rendering. +3. **Rejected Alternative 3: Forking Warp's `warpui_core` + `warpui` (`f8a9c71`, MIT)** + - *Why rejected:* Although MIT-licensed and possessing nice ideas (`Tracked<T>`, 3-shader simplicity, Ratatui TUI backend), `warpui` is 130,464 LoC of 2021-era GPUI-v1 architecture with custom Flutter-style layout (no CSS Grid/Taffy), a naive shelf-next-fit glyph atlas with no eviction, no subpixel AA or luminance glyph dilation, and heavy Warp-specific telemetry/asset coupling. + +--- + +## 8. Open Questions for Rune's Design + +1. **Compositor Layer Hybrid vs. Pure GPU Scene:** Should Rune's window compositor use native `CALayer` / `CAMetalLayer` sublayers for window-level glass/morph surfaces (like the launcher and Scrawl proved on macOS via `NSGlassEffectView` + `WindowServer` `CASpringAnimation`) while running a multi-pass GPU scene graph inside each surface, or should Rune implement its own multi-pass offscreen layer compositor across all platforms? +2. **Vector Path Rendering Strategy:** Since GPUI's Lyon + 4x MSAA full-window intermediate pass is a major bottleneck and `warpui` skips arbitrary paths entirely, should Rune restrict UI primitives to analytical SDFs + `resvg` sprite caching, or adopt a tile-based GPU path rasterizer? +3. **Reactive State Model:** Should Rune adopt `warpui`-style automatic read tracking (`Tracked<T>` / fine-grained signals) so views never need manual `cx.notify()` and never hit `double_lease_panic` on re-entrant reads, or keep explicit entity handles with split read/write arenas? +4. **Text Buffer Scope:** Does Rune only need `sum_tree` + `rope` + single-buffer undo/anchors (~10k LoC), or does it also need Zed's full `multi_buffer` + 5-layer `DisplayMap` (`InlayMap` → `FoldMap` → `TabMap` → `WrapMap` → `BlockMap`) for code-editor-class views? diff --git a/app/vendor/rune/research/02-rust-ui-ecosystem.md b/app/vendor/rune/research/02-rust-ui-ecosystem.md new file mode 100644 index 0000000..d62a734 --- /dev/null +++ b/app/vendor/rune/research/02-rust-ui-ecosystem.md @@ -0,0 +1,274 @@ +# 02 — Rust UI Ecosystem & Shared Foundation Survey (2025–2026) + +## Executive Summary + +- **The Rust UI ecosystem has split cleanly into a shared low-level foundation and diverging high-level paradigms.** Across otherwise competing frameworks, text, layout, geometry, and accessibility have converged onto the same crates: `taffy` (layout), `parley` + `fontique` + `harfrust` + `skrifa` (text discovery, shaping, metrics/outlines), `kurbo` + `peniko` + `color` (2D geometry and styling), and `accesskit` (platform accessibility). Even `egui` 0.37 migrated `epaint` onto `fontique` + `harfrust` + `skrifa` + `vello_cpu` (`egui/crates/epaint/Cargo.toml:88-100`). +- **Linebender pivoted Vello from compute-only to Sparse Strips (`vello_cpu` + `vello_gpu`).** In 2026, the original compute-shader renderer (`vello` 0.8.0, 26k+ LOC of WGSL/Rust) was moved into `research/vello_research/` (`vello/ARCHITECTURE.md:5-31`). The active production path is **Sparse Strips** (`vello_common` 0.3, `vello_cpu` 0.3, and `vello_gpu` 0.3—renamed from `vello_hybrid` on 2026-10-02 in `vello/vello_gpu/CHANGELOG.md:9-19`), which tiles paths into 4×N strip spans on the CPU using `fearless_simd` and rasterizes/composites via either multithreaded SIMD CPU pipelines or universal vertex/fragment GPU shaders (including WebGL2 and tile-based mobile GPUs where compute shaders hit driver bugs and memory limits). +- **Makepad 2.0 (`dev` branch, 2026) is the most relevant prior art for Rune's live-tuning and agent-driven thesis.** Makepad replaced its legacy `live_design!` macro with **Splash (`script_mod!`)**, a reactive bytecode VM (`makepad-script`, `makepad/platform/script/Cargo.toml:1-12`) whose blocks are hot-extracted directly from `.rs` source files on disk without recompiling (`makepad/platform/src/live_reload.rs:144-179`). It also shipped a built-in HTTP `--remote` agent control protocol (`/snap`, `/g`, `/gseq`, `/click`, `if_user_seq` in `makepad/platform/src/remote.rs:1-42`, `makepad/docs/agents/app-remote.md:1-120`), a live visual `/tweak` inspector that writes layout edits back to Rust source lines (`makepad/widgets/families/tweaker/src/tweaker.rs:1-50`), a GPU **Slug** quadratic-Bezier text renderer for crisp large glyphs (`makepad/draw/src/text/slug_atlas.rs:1-45`), and inertia/spring scroll physics (`makepad/widgets/src/scroll_motion.rs:1-40`). +- **GPUI v0.2 and `gpui-component` (`gpui-kit` 0.8) prove that a custom 2D UI Uber-shader beats generic vector renderers for desktop apps, but raw GPUI lacks ergonomic primitives.** GPUI renders a small fixed set of UI primitives (`Quad`, `Shadow`, `Path`, `Underline`, `MonochromeSprite`, `PolychromeSprite`) in a single batchable GPU pass (`zed/crates/gpui/src/scene.rs:1-120`) and added `subsecond` hot-reloading (`zed/crates/gpui/Cargo.toml:50-56`). Longbridge's `gpui-kit` (`gpui-base` + `gpui-component` + `gpui-shell`) supplies the missing 75+ accessible controls, headless UI integration tests, and tested AI coding recipes (`gpui-component/README.md:13-51`, `gpui-component/docs/ARCHITECTURE.md:18-48`). +- **Dioxus 0.7 / Blitz 0.3 and Subsecond changed the Rust iteration speed curve.** `subsecond` binary hot-patching is now embedded across Dioxus (`dioxus/packages/devtools/Cargo.toml:19`), GPUI (`zed/crates/gpui/Cargo.toml:55`), and Freya (`freya/crates/freya-core/Cargo.toml:62`), enabling sub-second Rust view function patching without losing state. Meanwhile, `dioxus-native` renders HTML/CSS natively via Servo's `stylo` + `taffy` + `parley` + `anyrender` (`vello_hybrid`/`vello_cpu`/`skia`) without a WebView (`dioxus/packages/native/Cargo.toml:13-88`). +- **Iced 0.14 / 0.15-dev matured its runtime and developer tooling (`comet`, `iced_test`, `lilt` animations, `cargo-hot`), while Slint 1.19 added an embedded MCP server (`SLINT_MCP_PORT`).** However, Iced still lacks merged upstream `accesskit` support in `iced` master (`iced/Cargo.toml:25-94`), and Slint's `.slint` DSL splits application logic across two languages under a dual GPLv3/commercial license (`slint/Cargo.toml:83`). +- **Animation, audio, and multi-sensory polish remain third-class citizens across almost every Rust UI crate.** Only Makepad (`Animator` + shader-driven state tracks + `scroll_motion.rs`), Iced (`iced_core::animation::Animation` backed by `lilt` 0.8), GPUI (frame-interpolated `AnimationElement`), and Floem (reactive keyframe/spring transitions) provide built-in animation primitives—and none treat interruptible 2D/3D spring velocities, layout-transition FLIP morphing, or procedural UI audio synthesis as core primitives. +- **Decisive Recommendation for Rune:** Do **not** build a font parser, shaper, bidi/line-breaker, CSS Flexbox/Grid solver, or OS accessibility bridge. Depend on **`taffy`**, **`parley`** (which brings **`fontique`**, **`harfrust`**, **`skrifa`**, **`read-fonts`**, and **`icu4x`**), **`kurbo`**, **`peniko`**, **`color`**, and **`accesskit`**. Use **`vello_cpu` / `vello_gpu`** only for complex arbitrary SVG/vector path layers (`AnyRender`-style escape hatch), while building Rune's **primary UI compositor and custom SDF/box-shadow/material/spring-animated quad pipeline directly on `wgpu`** (the GPUI / Makepad model) alongside a **Splash/Knobs-style hot-tunable parameter + agent inspection layer**. + +--- + +## 1. The Linebender Stack (`Xilem`, `Masonry`, `Vello`, `Parley`, `Fontations`, `HarfRust`, `AccessKit`, `Kurbo`, `Peniko`) + +In Q1 2026, Linebender core authors Raph Levien and Daniel McNab joined Canva while continuing open-source stewardship of the Linebender stack. By October 2026, Linebender's modular crates have become the de facto lower-half standard of the Rust UI ecosystem. + +### 1.1 `Xilem` (0.4.0) & `Masonry` (0.4.0) +- **Architecture & State Model:** Linebender separates its reactive view tree (`xilem_core` / `xilem_masonry`) from its retained widget tree (`masonry_core` / `masonry`) (`xilem/ARCHITECTURE.md:1-60`). + - **`xilem_core::View`** (`xilem/xilem_core/src/view.rs:53-103`) is a lightweight, statically typed, short-lived description parameterized by `(State, Action, Context)` with two associated types—`type Element: ViewElement` and `type ViewState`—and four core methods: `build`, `rebuild(prev, view_state, ctx, element, app_state)`, `teardown`, and `message`. Because widget sequences are typed as nested tuples implementing `ViewSequence`, tree diffing is statically monomorphized with zero heap allocation or dynamic dispatch on unchanged subtrees (`memoize`). + - **`masonry_core::core::Widget`** (`xilem/masonry_core/src/core/widget.rs:140-260`) is the retained, mutable object layer stored inside `WidgetPod`s with generational `WidgetId(NonZeroU64)` handles (`widget.rs:42`). Widgets receive explicit lifecycle passes: `on_pointer_event`, `on_text_event`, `on_access_event`, `on_anim_frame`, `update`, `measure`, `layout`, `compose`, `paint`, and `accessibility` (`widget.rs:115-123`). +- **Renderer Approach:** In 2026 (`v0.4.0`), Masonry decoupled itself from hardcoding `vello` by introducing the `imaging` painter abstraction (`xilem/Cargo.toml:98-103`, `masonry_core/src/core/widget.rs:20`), allowing Masonry windows to render via `imaging_vello`, `imaging_vello_hybrid`, `imaging_vello_cpu`, or `imaging_skia`. +- **Layout:** Masonry 0.4 replaced its legacy Druid box constraints with an explicit `measure` + `layout` + `compose` pass (`widget.rs:121`). Separate `compose` passes allow scroll/transform updates to reposition children without re-running layout. +- **Accessibility & Testing:** First-class `accesskit` 0.24 integration (`xilem/Cargo.toml:90`). Every widget implements `accessibility(&mut self, ctx: &mut AccessCtx, props: &PropertiesRef, node: &mut accesskit::Node)` (`widget.rs:122`). `masonry_testing` provides a headless test harness that drives pointer/text/accessibility events and snapshots rendered output. +- **Weaknesses:** Deeply nested tuple types in `Xilem` can produce multi-screen compiler errors if `ViewMarker` / `Action` types mismatch, and `Xilem` does not yet expose declarative spring/layout-transition animations (`on_anim_frame` in `widget.rs:206-211` is manual per-frame nanosecond delta stepping). + +### 1.2 `Vello` (0.8.0 Research vs. Sparse Strips `vello_cpu` 0.3.0 & `vello_gpu` 0.3.0) +The most consequential architectural shift in Rust 2D graphics during 2025–2026 occurred inside `linebender/vello`: +- **Why Linebender pivoted from Compute Vello to Sparse Strips:** + - The original **`vello`** crate (`v0.8.0`, now relocated to `research/vello_research/` per `vello/ARCHITECTURE.md:5-31`) is a full GPU compute-shader pipeline (`pathtag_reduce`, `bbox_clear`, `flatten`, `tile_alloc`, `coarse`, `fine` in `wgpu` compute shaders). + - While compute Vello excels on high-end desktop GPUs for massive vector scenes (e.g., Paris map SVG with 100k+ paths), it suffered severe production blockers for general UI and mobile/web deployment (`vello/vello_gpu/README.md:84-90`, `vello/vello_gpu/CHANGELOG.md:105-145`): + 1. **Mobile GPU driver bugs & tile-memory limits:** Android Adreno and ARM Mali GPUs (e.g., Mali-G52) exhibited driver compilation failures, workgroup shared-memory exhaustion, and pipeline stalls on complex compute prefix-scans. + 2. **No WebGL2 / Downlevel support:** Compute shaders require full WebGPU/Vulkan/Metal/DX12 compute queues, ruling out WebGL2 browsers and older GLES devices. + 3. **Unbounded GPU buffer pre-allocation:** Complex paths could overflow fixed transient bump buffers mid-frame. + 4. **Excessive shader compilation startup latency & binary footprint.** +- **The Sparse Strips Architecture (`vello_common` 0.3, `vello_cpu` 0.3, `vello_gpu` 0.3):** + - Developed from Laurenz Stampfl's 2025 ETH Zürich thesis (*High-performance 2D graphics rendering on the CPU using sparse strips*, cited in `vello/vello_cpu/README.md:169`), Sparse Strips splits rendering into: + 1. **CPU Path Flattening & 4×N Strip Tiling (`vello_common`):** Flattens `kurbo::BezPath` curves and packs anti-aliased alpha coverage into compact 4-pixel-tall horizontal strip spans (`vello/vello_common/Cargo.toml:1-31`). + 2. **`vello_cpu` (0.3.0):** Rasterizes and composites those strips entirely on the CPU using portable explicit SIMD via `fearless_simd` 1.0 (`NEON` on aarch64, `AVX2`/`SSE4.2` on x86_64, `wasm32` SIMD128) with two selectable pipelines: `u8_pipeline` (`RenderMode::OptimizeSpeed`) and `f32_pipeline` (`RenderMode::OptimizeQuality`), plus optional multithreaded tiling (`vello/vello_cpu/README.md:113-136`). + 3. **`vello_gpu` (0.3.0, formerly `vello_hybrid` until 2026-10-02):** Performs path flattening and strip generation on the CPU, uploads the tiny strip buffer to the GPU, and performs strip rasterization, image sampling, gradients, clip masks, andblurred rounded rects in standard **vertex + fragment shaders** over `wgpu` 29 or `webgl2` (`vello/vello_gpu/README.md:29-66`, `vello/vello_gpu/CHANGELOG.md:9-48`). + 4. **`glifo` (0.4.0):** Shared glyph run preparation and atlas caching crate sitting atop `vello_common` and `skrifa` (`vello/glifo/Cargo.toml:1-35`). +- **Performance & Status (Oct 2026):** + - `vello_cpu` (`u8_pipeline` + `fearless_simd`) achieves sub-millisecond to low-single-digit-millisecond frame times for typical UI scenes on Apple Silicon and x86_64 (`https://laurenzv.github.io/vello_chart/`, cited in `vello/vello_cpu/README.md:159-164`), making it fast enough that `egui` 0.37 adopted `vello_cpu` as its built-in glyph/color-emoji rasterizer (`egui/crates/epaint/Cargo.toml:41,100`). + - `vello_gpu` 0.3.0 explicitly validates against Adreno, Mali-G52 (`max_textures_per_shader_stage = 16`), Apple Silicon Metal, Vulkan, DX12, and WebGL2 (`vello/vello_gpu/CHANGELOG.md:36-46, 118-137`), though complex filter graphs and non-isolated blend modes are still unimplemented (`vello/vello_gpu/README.md:94-96`). + +### 1.3 `Parley` (0.12.0), `Fontations` (`skrifa` 0.49 / `read-fonts` 0.46), and `HarfRust` (0.14.0) +- **The Pure-Rust Text Stack:** + - **`fontations` (`read-fonts` 0.46 + `skrifa` 0.49):** Google Fonts' memory-safe replacement for FreeType, shipped in production Chrome and Android (`fontations/Cargo.toml:25-73`). Provides zero-copy OpenType table parsing, variable font variation axis interpolation, TrueType/CFF hinting (`autohint`), glyph metrics, outline extraction (`kurbo`), and `COLR`v0/v1 color glyph painting. + - **`harfrust` (0.14.0):** Official HarfBuzz team port of the complete HarfBuzz OpenType shaping engine to safe Rust built directly on `read-fonts` (`harfrust/Cargo.toml:5-27`). Replaces `rustybuzz` with upstream parity and active Google Fonts backing. + - **`fontique` (0.12.0):** System font enumeration, font fallback per script/locale, and generic family resolution (`parley/Cargo.toml:45`). + - **`parley` (0.12.0):** Rich text layout engine combining `fontique`, `harfrust`, `skrifa`, and `icu4x` (`icu_properties`, `icu_segmenter`, `unicode-bidi`) for bidirectional text reordering, script segmentation, dictionary/UAX#14 line breaking (`complex-scripts` feature), inline boxes, and cursor/selection hit-testing (`parley/parley/Cargo.toml:16-51`). + - **Important 2026 Split (`parley` vs `parley_engine`):** In 0.12, Parley split out `parley_engine` and `parlance` (`parley/parley/Cargo.toml:38-39`) so frameworks that want to manage their own style caching can drive the layout engine without Parley's high-level `LayoutContext` wrapper. + +### 1.4 `Kurbo` (0.13.1), `Peniko` (0.6.1), `Color` (0.3.3), and `AccessKit` (0.25.1) +- **`kurbo` (0.13.1):** `#![forbid(unsafe_code)]`, `no_std`-capable 2D curve and geometry library (`Point`, `Vec2`, `Size`, `Rect`, `RoundedRect`, `Affine`, `BezPath`, cubic/quadratic flattening, stroke expansion, dash patterns, tight bounding boxes) (`kurbo/Cargo.toml:10-36`). +- **`peniko` (0.6.1) & `color` (0.3.3):** Shared vocabulary types (`Brush`, `Gradient`, `ImageBrush`, `BlendMode`, `Fill`, `FontData`, `Blob` via `linebender_resource_handle`) plus CSS Color 4 color spaces (`Oklab`, `Oklch`, `DisplayP3`, `Srgb`, `PremulRgba8` interpolation) (`peniko/peniko/Cargo.toml:34-38`). +- **`accesskit` (0.25.1):** Cross-platform accessibility tree diffing (`TreeUpdate`, `Node`, `Role`, `ActionRequest`) with native adapters for **macOS (`NSAccessibility`)**, **iOS (`UIAccessibility`)**, **Windows (`UIAutomation`)**, **Linux (`AT-SPI` via D-Bus)**, and **Android (`AccessibilityNodeProvider`)** (`accesskit/Cargo.toml:3-14`, `accesskit/accesskit/Cargo.toml:1-30`). + +--- + +## 2. Makepad (v1.0 crates.io / v2.0 `dev` branch, 2026) + +Makepad (`makepad/makepad`, created by Rik Arends) is a full-stack GPU-rendered UI and application environment with zero dependencies on `wgpu`, `winit`, or `taffy`. Its 2025–2026 evolution on the `dev` branch (`v2.0.0`) contains the most advanced live-coding, shader-styling, and AI-agent inspection infrastructure in the Rust ecosystem. + +- **From `live_design!` to Splash (`script_mod!`) & `makepad-script`:** + - In Makepad 1.0 (May 2025), UI layout and shaders were declared inside `live_design! { ... }` macros. In Makepad 2.0 (2026 `dev`), `live_design!` was completely replaced by **Splash** via `script_mod! { ... }` backed by `makepad-script` (`makepad/AGENTS.md:27-88`, `makepad/platform/script/Cargo.toml:1-12`). + - `makepad-script` is a custom, minimal-dependency dynamically typed scripting language and bytecode VM with prototype inheritance (`+WidgetBase { ... }`), reactive property propagation, closures, and embedded shader code (`makepad/platform/script/src/vm.rs`). +- **True Hot Reload Without Recompiling (`live_reload.rs`):** + - Why does Makepad embed `script_mod!` inside `.rs` files? Because at runtime (`MAKEPAD=lines cargo run` or Makepad Studio), `makepad_platform::live_reload::extract_script_mod_from_file` (`makepad/platform/src/live_reload.rs:144-179`) watches `.rs` files on disk, tokenizes the file to extract the token stream inside `script_mod! { ... }` without invoking `rustc`, re-evaluates the script module in the `makepad-script` VM, and patches widget properties, layouts, and GPU shaders in single-digit milliseconds while preserving Rust struct state. +- **Shader DSL & Rendering Pipeline (`makepad-draw`):** + - Every widget's visual primitives (`DrawQuad`, `DrawColor`, `DrawText`, custom SDF shapes) are written in Makepad's Rust-embedded shader language (`draw_bg: { pixel: fn() -> vec4 { ... } }`), which cross-compiles at runtime to **Metal MSL**, **DirectX 11 HLSL**, **OpenGL/GLES GLSL**, and **WebGL2** (`makepad/platform/src/os/`). + - Instead of CPU-tessellating vector paths for standard UI controls, Makepad draws controls as instanced quads with analytical SDF math in the fragment shader—making per-pixel animations, procedural materials, glow, and morphing effectively free on the GPU. +- **Text Stack (GPU Slug + MSDF + Raster Atlas):** + - In 2026, Makepad uses a hybrid text engine (`makepad/draw/src/text/`): + - **`slug_atlas.rs` (`makepad/draw/src/text/slug_atlas.rs:1-45`):** Implements Eric Lengyel's **Slug** algorithm, packing quadratic Bézier curves and horizontal/vertical spatial bands into GPU textures and evaluating exact winding numbers per pixel in the fragment shader. Used for large/scaled text where bitmap atlases blur or blow out VRAM. + - **Raster/SDF Glyph Atlas + `rustybuzz` (`makepad/draw/Cargo.toml:14`):** Used for small hinted body text. +- **Layout & Animation:** + - Custom single-pass turtle/flow layout engine (`Walk`, `Layout`, `Flow::Right`, `Flow::Down`, `Flow::Overlay`, `Size::fill()`, `Size::fit()`) in `makepad-draw`—very fast ($O(N)$ single pass), though less expressive than CSS Grid/Flexbox alignment edge cases. + - Built-in `Animator` state machine (`animator: { hover = { default: off, on = { from: { all: Forward { duration: 0.15 } }, apply: { draw_bg: { hover: 1.0 } } } } }`) that interpolates shader uniforms and layout properties directly, plus `ScrollMotion` (`makepad/widgets/src/scroll_motion.rs:1-40`) for flick inertia and spring bounce-back. +- **First-Class Agent Inspection, Frame Tracing & Live Tweaker (2026):** + - **`--remote` HTTP Control Protocol (`makepad/platform/src/remote.rs:1-42`, `makepad/docs/agents/app-remote.md:1-120`):** Running any Makepad app with `--remote 127.0.0.1:8123` (and optionally `MAKEPAD_HIDE_WINDOWS=1` for headless verification) exposes: + - `GET /snap` → compact semantic widget hierarchy + bounding boxes + `user_seq` counter. + - `GET /g` and `GET /gseq?frames=10&interval_ms=33` → single or multi-frame PNG screenshots of active windows without waking the OS screen. + - `POST /click`, `/scroll`, `/type`, `/key`, `/Eval` with `if_user_seq` optimistic concurrency guards so agents never click stale coordinates. + - **`/tweak` Live Tweaker (`makepad/widgets/families/tweaker/src/tweaker.rs:1-50`, `makepad/docs/agents/tweaker.md:1-90`):** Holding `Alt/Option` (or calling `GET/POST /tweak`) inspects every live `Walk`/`Layout`/`DrawQuad` value alongside its exact `file:line:col` origin and writes interactive slider drags directly back to the `.rs` file on disk. + - **Frame & Present Tracing (`makepad/platform/src/frame_trace.rs`, `present_trace.rs`):** Per-frame timing instrumentation for debugging hitches. +- **Platforms:** Custom zero-`winit` OS backends in `makepad/platform/src/os/`: **macOS / iOS / tvOS / visionOS** (`apple/`), **Windows** (`windows/`), **Linux X11/Wayland/Direct DRM** (`linux/`), **Android** (`android/`), **WebAssembly/WebGL2** (`web/`), and **Meta Quest OpenXR** (`linux/openxr*.rs`). +- **Compile Times & Binary Size:** Because Makepad avoids heavy proc-macros (`syn`/`quote`), `wgpu`, and `winit`, a clean debug build of `makepad-example-simple` compiles ~120 crates (vs 400+ for `wgpu`+`winit` stacks) in ~15–25s on Apple Silicon, with stripped release binaries around **4–7 MB** (measured/documented across Makepad builds). +- **Weaknesses:** Poor external documentation (`makepad/AGENTS.md` is actually better written for AI agents than human docs on crates.io), no `accesskit` integration (screen readers cannot read Makepad windows; verified in `blog.wybxc.cc` Aug 2026 survey), and IME preedit composition overlay positioning is incomplete. + +--- + +## 3. Major Rust UI Frameworks (2025–2026) + +### 3.1 Slint (`v1.19.0`) +- **Approach & DSL:** Uses a dedicated QML-like `.slint` declarative language (`slint/Cargo.toml:1-87`). `.slint` files can either be ahead-of-time compiled to Rust/C++ code (`slint-build` / `slint!` macro) with static vtables (`helper_crates/vtable`) and fine-grained two-way property bindings (`Property<T>`), or dynamically loaded via `slint-interpreter` (`internal/interpreter`) for live preview (`SLINT_LIVE_PREVIEW=1`). +- **Renderers:** Pluggable across four backends (`slint/api/rs/slint/Cargo.toml:210-239`): + 1. **`renderer-femtovg`** (default on desktop, OpenGL or `wgpu` via `renderer-femtovg-wgpu`). + 2. **`renderer-skia`** (Metal, Vulkan, D3D, OpenGL, or CPU). + 3. **`renderer-software`** (`#![no_std]` capable dirty-rect scanline renderer supporting `RGB565` and `Gray8` for MCUs with <300 KB RAM). + 4. **`renderer-vello` / `i-slint-renderer-anyrender`** (`slint/Cargo.toml:101`, `slint/api/rs/slint/Cargo.toml:231-238`, experimental Vello/AnyRender backend). +- **Text, Layout, Animation & Accessibility:** + - **Text:** Migrated in 1.18–1.19 to `parley` + `fontique` 0.12 + `skrifa` 0.44 + `read-fonts` 0.41 + `rustybuzz` 0.20 + `icu_*` (`slint/Cargo.toml:133, 148-172`). + - **Layout:** Built-in `HorizontalLayout`, `VerticalLayout`, `GridLayout`, and Flexbox-like stretch constraints compiled directly into property dependency graphs. + - **Animation:** Declarative `animate prop { duration: 250ms; easing: ease-in-out-back; }` and `states [ ... ]` transitions in `.slint`. + - **Accessibility & Agent Tooling:** Full `accesskit` integration (`accessibility` feature enabled by default in `slint/api/rs/slint/Cargo.toml:28, 85`), working out-of-the-box with macOS VoiceOver and IME. Notably, **Slint 1.19 added an embedded MCP server (`mcp` feature, `SLINT_MCP_PORT`)** and system-testing server (`slint/api/rs/slint/Cargo.toml:136-152`) so AI agents can inspect and drive a running Slint UI over Streamable HTTP. +- **Platforms:** Desktop (macOS, Windows, Linux X11/Wayland/KMS-DRM), Android (`backend-android-activity-06`), iOS, WebAssembly, and bare-metal MCUs (ESP32, STM32, RP2040). +- **Licensing:** Triple-licensed (`GPL-3.0-only OR LicenseRef-Slint-Royalty-free-2.0 OR LicenseRef-Slint-Software-3.0`, `slint/Cargo.toml:83`)—restrictive for an MIT/Apache-2.0 open-source framework like Rune. + +### 3.2 Dioxus (`v0.7.x`) & Blitz (`v0.3.0-beta.4`) + `Subsecond` +- **Architecture:** Dioxus 0.7 offers two native desktop paths: + 1. **`dioxus-desktop`:** Renders `rsx!` VirtualDOM inside the OS WebView (`wry`/`tao`). + 2. **`dioxus-native` (`dioxus/packages/native/Cargo.toml:1-99`):** Renders Dioxus `rsx!` HTML/CSS components natively on the GPU without a WebView via **Blitz** (`blitz-dom`, `blitz-paint`, `blitz-shell`). +- **How Blitz Works (`blitz/packages/blitz-dom/Cargo.toml:46-84`):** + - Combines **Servo's `stylo`** (`style`, `selectors`, `cssparser`) for parallel CSS cascade/selector matching with **`stylo_taffy` + `taffy` 0.15** (Flexbox, CSS Grid, Block, Float, `calc()`) for layout, **`parley` + `skrifa` + `icu4x`** for inline/rich text layout, **`accesskit`** for accessibility, and **`anyrender`** (`anyrender_vello_hybrid` by default in `dioxus/packages/native/Cargo.toml:13, 37-45`, with `vello`, `vello_cpu`, and `skia` options) for painting. +- **State Model:** Copyable arena-allocated reactive signals (`Signal<T>`, `Memo<T>`, `Resource<T>`) backed by `generational-box` (`dioxus/packages/signals/`), paired with structural `rsx!` template diffing (`dioxus-core`). +- **`Subsecond` Hot-Patching (`dioxus/packages/devtools/Cargo.toml:19`):** + - Dioxus 0.7 introduced `subsecond`, a Rust binary hot-patching runtime and linker workflow (`dx serve --hot-patch`). When a Rust function changes, `dx` compiles a tiny dynamic object containing only the modified symbols and patches a jump table in the running process—allowing arbitrary Rust view code, closures, and new widgets to hot-reload in <500ms without restarting the app or losing signal state. +- **Weaknesses:** Carrying `stylo` + full HTML DOM semantics adds substantial compile-time weight (~500+ crates) and forces desktop UI into web CSS quirks rather than purpose-built native motion/interaction primitives. + +### 3.3 Iced (`v0.14.0` / `v0.15.0-dev`) +- **State Model & Runtime:** Strictly follows the Elm Architecture (`State`, `Message`, `update(&mut State, Message) -> Task<Message>`, `view(&State) -> Element<Message>`) (`iced/Cargo.toml:1-198`). In `0.14.0` (`iced/CHANGELOG.md:9-48`), Iced introduced **reactive rendering** (redrawing and re-laying out only when visual outputs change) and **`Task`** (replacing `Command` with composable async streams via `sipper`). +- **Renderer & Text:** + - Dual renderer architecture (`iced/Cargo.toml:25-31`): **`iced_wgpu`** (on `wgpu` 30, using instanced quads, `cryoglyph` glyph atlas, and `lyon` tessellation for vector canvas) with automatic fallback to **`iced_tiny_skia`** (`tiny-skia` 0.12 software rasterizer + `softbuffer`). + - Text shaping and layout use **`cosmic-text`** (`iced/Cargo.toml:206`), which wraps `swash`, `rustybuzz`, and `fontdb`. +- **Layout & Animation:** + - Custom Flexbox-inspired `Layout` and `Node` solver in `iced_core::layout` (does not use `taffy`). + - Added first-class `iced_core::animation::Animation` in 0.14 (`iced/Cargo.toml:215`), backed by the `lilt` 0.8 spring/easing transition crate, paired with `window::frames()` for smooth vsync-driven transitions. +- **2025–2026 Tooling (`comet`, `iced_test`, `cargo-hot`):** + - **`comet` & Time-Travel Debugging (`iced/Cargo.toml:46-47`):** Because all state mutations flow through `Message`, Iced 0.14 shipped `comet`, an external visual debugger with live time-travel scrubbing across message history and performance metrics (`F12`). + - **`iced_test` & `iced_tester` (`iced/Cargo.toml:50, 193-194`):** Headless `Simulator` that queries widgets by text/ID (`iced_selector`), synthesizes clicks/keys, and compares visual snapshots across `wgpu` and `tiny-skia`. + - **`cargo-hot` (`iced/Cargo.toml:48-49, 205`):** Experimental hot-reloading of `view` functions. +- **Ecosystem Adoption (System76 COSMIC):** System76's `libcosmic` fork of Iced powers the production COSMIC Linux desktop environment (and added `accesskit` + `taffy` in its fork), but upstream `iced` 0.15-dev still lacks built-in `accesskit` integration (`blog.wybxc.cc` survey, Aug 2026). + +### 3.4 GPUI (`v0.2.2` in Zed) & `gpui-component` / `gpui-kit` (`v0.8.0`) +- **GPUI Architecture (`zed/crates/gpui/`):** + - Hybrid **Entity + Immediate-Element + Retained-Fiber** architecture. Application state lives in reference-counted `Entity<T>` handles owned by the `App` context (`cx.new(...)`, `cx.notify()`). Views implement `Render::render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement`. + - **Renderer (`zed/crates/gpui/src/scene.rs`):** Instead of general 2D path tessellation, GPUI sorts primitives by draw order/stacking context into a flat GPU `Scene` of `Quad` (with analytic border/corner-radius/background), `Shadow` (analytic box shadow), `Underline`, `MonochromeSprite` (text glyphs/icons), `PolychromeSprite` (images/emoji), and `Path` (rare custom shapes via `lyon` / screen-space MSAA). On macOS it renders via direct Metal (`objc2-metal` / `blade-graphics` on Linux/Windows/WebGPU), effortlessly hitting 120 FPS in Zed. + - **Layout & Text:** Uses **`taffy`** (`zed/crates/gpui/Cargo.toml:107-115`) for Flexbox/Grid layout and native platform text APIs (**CoreText** on macOS, **DirectWrite** on Windows, ** cosmic-text / font-kit** on Linux) for OS-authentic glyph rasterization and subpixel AA. + - **2026 Additions:** Added WebAssembly target support (`wasm32-unknown-unknown`), `accesskit` workspace dependency (`zed/crates/gpui/Cargo.toml:62`), `leak-detection` (`Cargo.toml:38`), and `subsecond` `hot-reload` (`Cargo.toml:50-56`). +- **Why `gpui-kit` / `gpui-component` (`v0.8.0`) Matters (`gpui-component/README.md:1-146`, `docs/ARCHITECTURE.md:1-150`):** + - Raw GPUI ships zero high-level widgets (not even a `TextInput`). Longbridge built **`gpui-kit`** (powering Longbridge Pro desktop) with a clean three-layer split: + 1. **`gpui-base`:** Unstyled behavioral primitives (focus traps, popup collision `Positioner`, `InputState`, `EditorState`, `VirtualList`, `TreeState`, `DockArea`, and `AccessKit` role/action wiring). + 2. **`gpui-component`:** 75+ styled Shadcn-inspired desktop controls (`DataTable`, 200k-line Tree-sitter `CodeEditor`, `Select`, `Dialog`, `Sheet`, `Calendar`, `Toast`). + 3. **`gpui-shell`:** Capability-gated QuickJS (`quickjs-jit`) extension runtime for JS plugins. + - Notably, `gpui-kit` also ships **`examples/ai_recipes/`** (`gpui-component/examples/ai_recipes/README.md:1-40`)—a verified suite of executable consumer recipes and `script/check-ai` drift gates specifically designed so AI coding agents produce compiling, non-leaking GPUI code on the first attempt. + +### 3.5 `egui` (`v0.37.0`) +- **Architecture:** Pure immediate-mode GUI (`ui.button("Click").clicked()`). Every frame rebuilds a flat mesh of textured triangles (`epaint::Mesh` with a single 1D feathering/gradient texture + font atlas) so the entire UI renders in a handful of draw calls on `egui_wgpu` (default in `eframe` since 0.34) or `egui_glow`. +- **2026 Text Overhaul (`egui/crates/epaint/Cargo.toml:38-42, 88-100`):** In `0.37.0`, `epaint` replaced its legacy `ab_glyph` rasterizer with **`fontique` + `harfrust` + `skrifa` + `vello_cpu`**, gaining proper OpenType shaping, system font fallback (`egui_system_font_provider`), and `COLR`/`sbix`/`CBDT` color emoji rendering! +- **Accessibility & Testing:** Strong `accesskit` 0.24 support and **`egui_kittest`** (`egui/Cargo.toml:25, 111`), which lets tests query and drive widgets semantically through their AccessKit nodes (`harness.get_by_label("Submit").click()`). +- **Why `egui` is Great for Tools and Bad for High-Craft Consumer Feel:** + - *Great for tools:* Zero state synchronization boilerplate, trivial embedding in game/3D viewports (`rerun.io`), fast compile times. + - *Bad for feel:* Immediate-mode single-pass layout requires knowing child sizes *after* placing parents (causing one-frame layout lag/flicker on dynamic content resized first frame), lacks retained per-element velocity state for interruptible spring physics or FLIP layout morphing, and forces custom look-and-feel into procedural `Painter` math rather than composable style/animation trees. + +### 3.6 `Floem` (`v0.2.0`), `Freya` (`v0.5.0-beta.12`), `Vizia` (`v0.4.0`), and `Cushy` (`v0.4.0`) / `Kludgine` (`v0.11.0`) +- **Floem (`v0.2.0`, `floem/Cargo.toml:1-150`):** + - Fine-grained reactive signals (`RwSignal<T>` is `Copy`, backed by arena IDs in `floem_reactive`) where views are constructed once and closures surgical-patch styles/text without virtual DOM diffing. + - Uses **`taffy` 0.9.2** for Flexbox/Grid layout, **`parley` 0.7 + `fontique` 0.7** for text, **`ui-events` 0.3**, and J.R. Moulton's new **`understory`** crates (`understory_box_tree`, `understory_event_state`, `understory_focus`, `understory_virtual_list` in `floem/Cargo.toml:117-121`) for spatial indexing and focus management. + - Pluggable renderer trait (`floem_renderer`) with backends for `vger` (GPU SDF shaders), `vello`, `skia`, and `tiny_skia` fallback. Includes built-in reactive keyframe and spring animations (`.animation(...)`) and a rich style transition system, but in 2026 its IME and AccessKit wiring on macOS remain broken (`blog.wybxc.cc` survey). +- **Freya (`v0.5.0-beta.12`, `freya/Cargo.toml`, `freya/crates/freya-core/Cargo.toml:1-96`):** + - **Major 2025–2026 Pivot:** Freya 0.4/0.5 dropped Dioxus's VirtualDOM/RSX runtime entirely and built its own **`freya-core`** reactivity (`generational-box` signals + `pathgraph` tree + `ragnarok` event dispatch) with a clean builder API instead of HTML tags. + - Uses **`torin`** (`freya/crates/torin/`, custom Flexbox-like layout engine with caching), **`freya-skia-safe`** (`skia-safe` 0.93 for rendering and `skia::textlayout::Paragraph` for text), **`accesskit` 0.21**, **`freya-testing`** headless harness, and **`subsecond` 0.7.4** for hot-reloading. +- **Vizia (`v0.4.0`, `vizia/ARCHITECTURE.md:1-90`, `vizia/Cargo.toml:50-111`):** + - ECS-inspired retained tree (`Entity` IDs indexing sparse-set component stores for styles/layout caches) with fine-grained signals (`vizia_reactive`), CSS stylesheet parsing (`cssparser` 0.37 + `selectors` 0.39) with CSS property animations, **`morphorm` 0.9** (custom single-pass stretch layout), **`skia-safe` 0.99** (with Skia `textlayout`), **`accesskit` 0.24**, and `vizia_baseview` for VST/CLAP audio plugin windows alongside `vizia_winit`. +- **Cushy (`v0.4.0`) & Kludgine (`v0.11.0`) (`cushy/Cargo.toml:1-66`, `kludgine/Cargo.toml:1-49`):** + - Built by Khonsu Labs around a single ergonomic reactive primitive (`Dynamic<T>`), rendered on `wgpu` 24 via `kludgine` (`lyon_tessellation` + `cosmic-text` 0.12 + `etagere` atlas packer). Clean widget composition and built-in `Dynamic` easing animations, but development has been largely dormant since late 2024 and lacks `accesskit` screen-reader support. + +### 3.7 `Taffy` (`v0.15.0`) +- **Status & Capabilities (`taffy/Cargo.toml:1-91`):** Maintained under `DioxusLabs/taffy` by Nico Burns, Alice Cecile, and Jonathan Kelley. `taffy` 0.15 implements **CSS Flexbox** (including CSS Flexbox Level 2 `flex-wrap: balance`), **CSS Grid**, **CSS Block**, **CSS Float (`float_layout`)**, and **`calc()`** expressions. +- **Architecture:** Exposes both a ready-to-use arena (`TaffyTree` backed by `slotmap`) and low-level traits (`TraversePartialTree`, `LayoutFlexboxContainer`, `LayoutGridContainer`) so frameworks can store layout styles directly inside their own widget tree or ECS without duplicating nodes, using a custom measure callback (`measure_function`) to invoke `parley` for inline text measurement. +- **Who Uses It:** **Zed (`gpui`)**, **Bevy (`bevy_ui`)**, **Dioxus Native / Blitz (`stylo_taffy`)**, **Floem**, **Lapce**, **System76 `libcosmic`**, **Rosin**, and **Tessera**. + +### 3.8 Notable 2025–2026 Entrants (`Blinc`, `Rosin`, `Tessera`, `Ply`) +- **Blinc (`project-blinc/Blinc`, early 2026):** Reactive `wgpu`-based cross-platform UI framework targeting desktop, iOS, and Android with stateful components; early alpha with incomplete CJK font fallback, manual reactive event wiring on inputs, and no `accesskit` integration (`blog.wybxc.cc` survey, Aug 2026). +- **Rosin (`docs.rs/rosin`, 2026):** Combines top-level centralized state with fine-grained reactive lenses, CSS stylesheet styling, `vello` rendering (exposing raw `vello` canvas callbacks per node via `.on_canvas(...)`), working IME, and `accesskit` integration. +- **Tessera (`tessera-ui` 2.5.0, 2025–2026):** Declarative immediate-mode UI framework using proc-macro positional memoization (`#[tessera]`) and a pluggable `wgpu` shader pipeline (e.g., frosted glass/fluid shaders) targeting Material Design 3; still suffers from platform `wgpu` surface bugs on macOS (`blog.wybxc.cc` survey). +- **Ply (`plyx.iz.rs`, v1.0 in March 2026):** Clay-inspired immediate-mode builder UI library focused on minimal boilerplate and autocompletion-friendly layout builders, with optional `accesskit` setup. + +--- + +## 4. Ecosystem Comparison Matrix (Oct 2026) + +| Framework (Version) | Renderer Approach | Text Stack | Layout Engine | State Model | Animation Support | Accessibility (`accesskit`) | Platforms (Desktop / Mobile / Web) | Hot Reload / Live Tooling | Clean Debug Compile / Stripped Release Size | +| :--- | :--- | :--- | :--- | :--- | :--- | :--- | :--- | :--- | :--- | +| **Xilem / Masonry** (`0.4.0`) | `imaging` trait (`vello`, `vello_gpu`, `vello_cpu`, `skia`) | `parley` 0.12 (`fontique` + `harfrust` + `skrifa` + `icu4x`) | Masonry custom `measure` / `layout` / `compose` | Static typed `View` tree diffing (`ViewSequence`) | Manual `on_anim_frame(ns)` per widget | **Yes** (`accesskit` 0.24, built-in + `masonry_testing`) | Win, Mac, Linux, Android (`xilem_web` separate DOM crate) | None built-in (`subsecond` compatible) | ~45–60s (est.) / ~8–12 MB (est.) | +| **Makepad** (`1.0` / `2.0-dev`) | Custom GPU instanced SDF shaders (Metal, DX11, GL, WebGL2) | GPU **Slug** curve atlas (`slug_atlas.rs`) + SDF/raster + `rustybuzz` | Custom 1-pass Turtle `Walk` / `Flow` | `script_mod!` (Splash VM) + Rust `Widget` structs | Shader-driven `Animator` tracks + `ScrollMotion` springs | **No** | Win, Mac, Linux, **iOS, Android, WebGL2, visionOS, Quest** | **Best-in-class:** zero-recompile `script_mod!` reload + `/tweak` + `--remote` HTTP API | **~15–25s** / **~4–7 MB** (measured/repo) | +| **Slint** (`1.19.0`) | `femtovg` (GL/wgpu), `skia`, `software` (`no_std`), `anyrender`/`vello` | `parley` + `fontique` 0.12 + `skrifa` 0.44 + `rustybuzz` | Built-in compiled constraint/grid/flex solver | `.slint` two-way reactive `Property<T>` bindings | Declarative `animate` & `states` in `.slint` | **Yes** (default on desktop, works with VoiceOver) | Win, Mac, Linux (KMS), **Android, iOS, WASM, MCUs** | `SLINT_LIVE_PREVIEW` interpreter + VS Code preview + **`SLINT_MCP_PORT`** | ~35–50s / **~2–5 MB** (`software`/`femtovg`) | +| **Dioxus Native / Blitz** (`0.7` / `0.3-b4`) | `anyrender` (`vello_hybrid` default, `vello`, `vello_cpu`, `skia`) | `parley` + `fontique` + `skrifa` + `icu4x` | Servo `stylo` + `stylo_taffy` + **`taffy` 0.15** | Copyable arena `Signal<T>` + `rsx!` template diffing | CSS transitions (partial in Blitz) or frame signals | **Yes** (`accesskit` in `blitz-dom`) | Win, Mac, Linux, iOS/Android (experimental), WASM | **`subsecond`** binary hot-patching + RSX template hot reload (`dx serve`) | ~60–90s (`stylo` heavy) / ~15–25 MB (est.) | +| **Iced** (`0.14` / `0.15-dev`) | `iced_wgpu` (`wgpu` 30 quads + `lyon`) + `tiny-skia` CPU fallback | `cosmic-text` (`swash` + `rustybuzz` + `fontdb`) + `cryoglyph` | Custom `iced_core::layout` Flexbox solver | Elm Architecture (`State`, `Message`, `Task`) | `Animation<T>` (`lilt` 0.8 springs/easings) | **No** upstream (present in System76 `libcosmic` fork) | Win, Mac, Linux, WASM (limited mobile) | **`comet`** time-travel debugger + `cargo-hot` + `iced_test` | ~35–50s / ~8–14 MB (est.) | +| **GPUI + `gpui-kit`** (`0.2.2` / `0.8.0`) | Custom Uber-shader (`Quad`, `Shadow`, `Sprite`, `Path`) on Metal/Blade/WebGPU | Native OS (**CoreText**, **DirectWrite**) + `font-kit` | **`taffy`** (Flexbox + CSS Grid) | Retained `Entity<T>` models + immediate `Element` fiber | `AnimationElement` + `gpui-base` motion helpers | **Yes** (`accesskit` wired in `gpui-base`) | Mac, Win, Linux, **WASM** (minimal mobile) | **`subsecond`** (`hot-reload` feature) + `gpui-shell` QuickJS + Inspector | ~45–70s / ~15–30 MB (`gpui-shell` 78 MB stripped) | +| **egui** (`0.37.0`) | Immediate-mode 2D triangle mesh (`egui_wgpu` / `egui_glow`) | `fontique` + `harfrust` + `skrifa` + **`vello_cpu`** | Custom 1-pass immediate-mode cursor layout | Immediate mode + `Context` ID memory store | `ctx.animate_bool` / `animate_value_with_time` | **Yes** (`accesskit` 0.24 + **`egui_kittest`**) | Win, Mac, Linux, **WASM**, Android/iOS (via `winit`) | External only (`subsecond` / `hot-lib-reloader`) | **~20–30s** / **~5–9 MB** | +| **Floem** (`0.2.0`) | `vger` (GPU SDF), `vello`, `skia`, `tiny_skia` | `parley` 0.7 + `fontique` 0.7 + `swash` | **`taffy` 0.9.2** + `understory_box_tree` | Fine-grained `Copy` `RwSignal<T>` (no VDOM) | Built-in reactive keyframe & spring `.animation()` | Partial / broken on macOS in 0.2 | Win, Mac, Linux, WASM | Inspector overlay only | ~40–55s / ~10–15 MB (est.) | +| **Freya** (`0.5.0-beta.12`) | `freya-skia-safe` (`skia-safe` 0.93 Metal/GL/Vulkan/D3D) | Skia `textlayout::Paragraph` | Custom **`torin`** Flexbox layout engine | `freya-core` `generational-box` signals + builder views | `freya-animation` hook-based easings/springs | Wired (`accesskit` 0.21), macOS screen reader issues | Win, Mac, Linux | **`subsecond` 0.7.4** + `freya-devtools` + `freya-testing` | ~30–45s (with prebuilt Skia bin) / ~18–28 MB | +| **Vizia** (`0.4.0`) | `skia-safe` 0.99 (Metal, Vulkan, D3D, GL) | Skia `textlayout` + `unicode-bidi` | **`morphorm` 0.9** (1-pass stretch layout) | ECS sparse-sets + `vizia_reactive` signals | CSS stylesheet animations (`vizia_style`) | Wired (`accesskit` 0.24), crashes on edit signal | Win, Mac, Linux (`winit` + **`baseview`** audio plugins) | CSS stylesheet reload at runtime | ~35–50s (prebuilt Skia) / ~18–28 MB | +| **Cushy / Kludgine** (`0.4` / `0.11`) | `kludgine` on `wgpu` 24 (`lyon_tessellation`) | `cosmic-text` 0.12 | Custom `Widget` constraint layout (`figures` units) | Reactive `Dynamic<T>` values & bindings | `Dynamic` value transitions (`easing-function`) | **No** | Win, Mac, Linux, WASM | None | ~35–45s / ~9–13 MB (est.) | + +--- + +## 5. What Rune Should Steal vs. What Rune Should Avoid + +### What to Steal +1. **Steal GPUI & Makepad's "UI Uber-Shader + SDF Instanced Quad" primary renderer, NOT general path tessellation for Chrome.** + - 98% of UI frames consist of rounded rectangles with borders, gradients, inner/outer analytic shadows, clip masks, textured sprites, and glyph runs (`zed/crates/gpui/src/scene.rs`). Rendering these as instanced SDF quads in a single uber-shader pass gives 120–240 Hz performance, zero CPU tessellation cost during spring animations, and effortless shader effects (backdrop blur, noise, specular borders, liquid morphing). +2. **Steal Makepad's `--remote` Agent Protocol and `/tweak` Source Write-Back (`makepad/platform/src/remote.rs`, `makepad/docs/agents/tweaker.md`).** + - Every Rune application should compile with an optional embedded local agent/inspector server (like Makepad's `--remote` and Slint's `SLINT_MCP_PORT`) that supports: + - Headless off-screen window rendering (`RUNE_HEADLESS=1`, never waking the user's display). + - Semantic + geometric snapshot (`GET /snap`) with monotonic interaction sequence guards (`if_user_seq`). + - Multi-frame motion capture (`GET /gseq?frames=N&interval_ms=16`) and per-frame motion trace export (`frame_trace.rs`) so agents can verify spring curves and catch 1-frame layout pops deterministically. + - Live knob/style tweaking (`#[knob]` / `script_mod!`) that writes tuned constants back to the exact `file!():line!():column!()` in `.rs` source. +3. **Steal `egui_kittest` + `gpui-base`'s AccessKit-driven headless testing and AI Recipes (`egui/crates/kittest`, `gpui-component/examples/ai_recipes/README.md`).** + - Wiring `accesskit` into unstyled behavioral primitives from day one gives both real OS screen-reader accessibility and a zero-flake semantic query tree (`get_by_role`, `get_by_label`) for automated tests. Pair this with `gpui-kit`-style `check-ai` canonical consumer recipes. +4. **Steal Makepad's GPU Slug text (`makepad/draw/src/text/slug_atlas.rs`) for scale/transform-animated typography, paired with a hinted raster atlas (`skrifa` + `vello_cpu`/`glifo`) for body text.** + - Traditional bitmap glyph atlases shimmer or blur when text scales continuously during a spring transition, zoomable canvas pan, or 3D card tilt. Using hinted raster atlases for static 1x body text and Slug GPU curve evaluation (or high-res SDF) for transformed/large display text solves both crispness and kinetic typography. +5. **Steal Floem's `Copy` Arena Signals (`RwSignal<T>`) + Xilem/Masonry's `measure` / `layout` / `compose` separation (`masonry_core/src/core/widget.rs:121`).** + - Separating `layout` (expensive Taffy box calculation) from `compose` (cheap transform/scroll/spring-offset matrix update) means spring animations and scroll physics never trigger layout recalculation unless box dimensions actually depend on them. +6. **Steal `Subsecond` integration (`zed/crates/gpui/Cargo.toml:55`) + zero-recompile style/knob hot reload (`makepad/platform/src/live_reload.rs`).** + - Combine zero-recompile file watching for literal style/spring/shader blocks with `subsecond` binary jump-table patching for structural Rust code changes. + +### What to Avoid +1. **Avoid C++ FFI rendering dependencies (`skia-safe`, Qt, GTK, WebView).** + - `skia-safe` (used by Freya and Vizia) bloats binary size by 15–25 MB, complicates cross-compilation to iOS/Android/WASM, and hides the GPU command encoder so you cannot seamlessly interleave custom `wgpu` shaders or 3D layers with UI widgets. +2. **Avoid building a custom DSL that replaces Rust for control flow and business logic (`.slint`, legacy Makepad `live_design!`, Ribir's `@ { pipe!(...) }` macros).** + - Custom DSLs break standard `rust-analyzer` refactoring, split state across two languages, and confuse coding agents when syntax drifts from training data (as seen in the Aug 2026 survey on Ribir and Makepad). Keep view trees in normal Rust syntax; use lightweight macros or `#[knob]` attributes only for live-reloadable literals/shaders whose values can be parsed out of `.rs` files without recompiling. +3. **Avoid Compute-only Vello (`vello` 0.8) as the primary UI renderer.** + - Even Linebender moved compute `vello` to `research/vello_research/` (`vello/ARCHITECTURE.md:27-31`) because compute pipelines struggle on mobile tile GPUs, WebGL2, and memory-constrained devices. +4. **Avoid full HTML/CSS engines (`stylo` in Blitz) for native app UI.** + - Pulling in Servo's `stylo` adds hundreds of crates and browser layout baggage without giving you interruptible springs, FLIP layout morphing, or custom GPU materials. `taffy` alone gives 100% of the Flexbox/Grid ergonomics needed at a tiny fraction of the compile cost. +5. **Avoid immediate-mode one-pass layout (`egui`, `ply`).** + - Immediate-mode layout cannot size a parent container to dynamic children without either a two-pass measure or a one-frame visual pop—fatal for Kit's motion standards. + +--- + +## 6. Concrete Crate Dependency vs. Custom-Build Recommendation for Rune + +### Crates Rune Should Depend On Directly +| Layer | Recommended Crate(s) | Version (Oct 2026) | Why Depend Instead of Build | +| :--- | :--- | :--- | :--- | +| **2D Geometry & Curves** | `kurbo` | `0.13.1` | `#![forbid(unsafe_code)]`, `no_std`, shared by `skrifa`, `parley`, `vello_common`, and `accesskit`. Zero reason to reinvent `Point`, `Rect`, `RoundedRect`, `Affine`, or `BezPath`. | +| **Color & Brush Types** | `color`, `peniko` | `0.3.3`, `0.6.1` | First-class CSS Color 4 (`Oklch`, `Oklab`, `DisplayP3`, `Srgb`) perceptual color interpolation and shared `Brush`/`Gradient`/`FontData` handles. | +| **Box Layout (Flexbox & Grid)** | `taffy` | `0.15.0` | Battle-tested in Zed, Bevy, Dioxus, and Floem; minimal dependencies (`slotmap`, `smallvec`, `grid`, `flexbox`, `block_layout`); trait-based API lets Rune run layout directly over its own retained node arena. | +| **Font Parsing, Hinting & Shaping** | `parley` (or `parley_engine` + `fontique` + `harfrust` + `skrifa` + `read-fonts`) | `parley` `0.12.0`, `skrifa` `0.49`, `harfrust` `0.14` | Google Fonts (`skrifa`/`harfrust`) + Linebender (`fontique`/`parley`) is the undisputed pure-Rust standard in 2026. Handles variable fonts, autohinting, OpenType shaping, bidi, UAX#14/CJK line breaking, and cursor hit-testing. | +| **Vector / Emoji Raster Escape Hatch** | `vello_cpu` (+ optional `vello_gpu` / `glifo`) | `0.3.0` (`glifo` `0.4.0`) | Use `vello_cpu` (just like `egui` 0.37 does in `epaint`) for color emoji (`COLR`), complex SVG icons, and CPU snapshot testing, and optionally `vello_gpu` for complex canvas vector layers. | +| **Accessibility** | `accesskit` (+ platform adapters) | `0.25.1` | Non-negotiable for macOS VoiceOver, Windows UIA, Linux AT-SPI, iOS, and Android, and doubles as the semantic backbone for headless UI testing and agent introspection. | +| **Input Event Vocabulary** | `ui-events` | `0.3.0` | W3C-aligned `PointerEvent`, `KeyboardEvent`, and modifier state types (`kurbo`-integrated), already shared by Masonry and Floem. | +| **Spatial Indexing (Optional)** | `understory_box_tree` / `etagere` | `0.1` / `0.2.8` | Proven R-tree / bounding-box hit-testing (`understory`) and shelf texture atlas packing (`etagere`, used by GPUI, Iced, and Kludgine). | +| **Hot-Patching Hook (Optional)** | `subsecond` | `0.7.10` | Proven in Dioxus, GPUI, and Freya for sub-second symbol hot-patching of Rust view functions. | + +### Subsystems Rune Should Build Itself (and Why) +1. **Retained Reactivity + Explicit 4-Phase Frame Pipeline (`Update → Measure/Layout → Animate/Compose → Paint`):** + - *Why build:* None of Xilem, Iced, Floem, or GPUI treat **FLIP layout transitions** (automatically animating a node's bounds with a spring when Taffy moves it) and **interruptible velocity-preserving springs** as first-class steps between `Layout` and `Compose`. Rune needs a custom retained node graph where Taffy computes target layout boxes and the `Compose` phase applies active spring/gesture deltas before generating GPU instances. +2. **Custom `wgpu` UI Uber-Shader + Analytic Material/Shadow/SDF Pass (+ GPU Slug/SDF Text):** + - *Why build:* General 2D vector renderers (`vello_gpu`, `femtovg`, `tiny-skia`) do not natively expose per-quad analytic squircle corners, multi-layered elevation shadows, backdrop blur/refraction, or custom WGSL material shaders per widget. Building a compact ~2,500-LOC `wgpu` instanced primitive compositor (drawing on GPUI's `Scene` and Makepad's `DrawQuad` + `SlugAtlas`) gives Rune complete control over visual craft and 120Hz frame pacing. +3. **First-Class Multi-Sensory & Motion Engine (Springs, Gestures, Procedural Audio/Haptics):** + - *Why build:* No existing Rust UI framework links pointer velocity, spring physics, and sub-millisecond procedural UI audio/tactile feedback into a unified interaction primitive. +4. **Built-in Live Tuning (`knobs`) + Headless Agent Remote Protocol (`/snap`, `/gseq`, `/tweak`, Motion Trace):** + - *Why build:* Makepad proved the architecture (`remote.rs`, `tweaker.rs`, `frame_trace.rs`, `live_reload.rs`), and Rune should build a clean, pure-Rust version natively integrated with Kit's `knobs` and Scrawl's motion-trace format from day one—allowing both humans and coding agents to tune springs/styles live without recompiling and verify motion traces headlessly. + +### Rejected Alternatives (and Why) +- **Forking or building directly on `Xilem` / `Masonry`:** Masonry's `Widget` trait and `imaging` abstraction are well-engineered, but Xilem's deeply nested static tuple view types create hostile compiler diagnostics for humans and agents, and Masonry's rendering model assumes a traditional 2D vector painter (`vello`) rather than a shader-first instanced compositor with FLIP layout springs and backdrop materials. +- **Building on `GPUI` or `gpui-kit`:** GPUI's macOS backend is tightly coupled to Zed's internal workspace crates (`gpui-pre` snapshots require exact `=0.3.9` pins per `gpui-component/Cargo.toml:62-71`), lacks iOS/Android support, and relies on platform-specific graphics abstractions (`blade-graphics` / raw `objc2-metal`) rather than a clean cross-platform `wgpu` pipeline. +- **Building on `Makepad`:** Makepad's custom `script_mod!` VM, custom turtle layout (no Flexbox/CSS Grid), and lack of `accesskit` or standard Rust ecosystem types (`kurbo`/`taffy`/`parley`) make it an island ecosystem rather than a composable Rust library. +- **Building on `Iced` or `Slint`:** Iced's Elm Architecture forces all component animation/gesture state through top-level messages (or opaque internal widget state) and lacks `accesskit`; Slint's `.slint` DSL and GPLv3/commercial licensing are incompatible with a permissively licensed Rust-native library. + +--- + +## 7. Open Questions for Rune Architecture + +1. **`parley` High-Level API vs. `parley_engine` Direct Integration:** Should Rune use `parley::LayoutContext` directly, or depend on the newer lower-level `parley_engine` + `fontique` + `skrifa` crates (introduced in Parley 0.12, `parley/parley/Cargo.toml:37-39`) to avoid intermediate style buffer allocations during high-frequency text layout? +2. **Text Rendering Dual-Path Threshold:** At what pixel size or transform state should Rune switch between a hinted `skrifa` + `vello_cpu` raster glyph atlas (crispest at 10–18px static UI text) and a Makepad-style GPU Slug / MSDF curve evaluator (artifact-free during spring scale/rotation/3D transforms)? +3. **Windowing Layer (`winit` 0.30/0.31 vs. Custom Platform Shells on macOS/iOS):** Is `winit` sufficient for Rune's frame-pacing (`CADisplayLink` / `CAMetalDisplayLink` 120Hz ProMotion sync, trackpad gesture phases, and transparent/vibrancy window chrome), or should Rune follow GPUI and Makepad in owning a thin native `objc2` macOS/iOS window shell while keeping `winit` as a fallback for Linux/Windows/Web? +4. **Zero-Recompile Tuning Syntax vs. `Subsecond`:** Should Rune parse `#[knob]` / style macro literals directly from `.rs` source files on disk (like `makepad_platform::live_reload::extract_script_mod_from_file` in `makepad/platform/src/live_reload.rs:144`) for sub-5ms zero-recompile parameter reloads, and pair that with optional `subsecond` binary patching when structural Rust code changes? diff --git a/app/vendor/rune/research/03-flutter-apple-rive-figma.md b/app/vendor/rune/research/03-flutter-apple-rive-figma.md new file mode 100644 index 0000000..4977cdd --- /dev/null +++ b/app/vendor/rune/research/03-flutter-apple-rive-figma.md @@ -0,0 +1,763 @@ +# 03 — Flutter (reach), SwiftUI/Core Animation (feel), Rive, Figma, Lottie, Compose + +Research date: 2026-10-21. Sources are linked inline. Source code read from shallow clones of +`flutter/flutter` (HEAD `77f043bc`, committed 2026-10-21) and `rive-runtime` (HEAD as of 2026-10-21) +in a scratch directory. Apple claims come from WWDC transcripts and DocC JSON. Anything marked +**(inference)** is my reading and not a documented fact. Anything marked **(estimate)** is not measured. + +--- + +## Summary + +- **Flutter's reach comes from owning every pixel behind one thin C ABI** + ([`embedder.h`](https://github.com/flutter/flutter/blob/main/engine/src/flutter/shell/platform/embedder/embedder.h)). + Each platform shell only supplies a surface, a vsync, input, text input and accessibility. + Web is the exception: it is a separate engine (CanvasKit/Skwasm) that skips the C++ engine and display + lists ([Impeller FAQ](https://github.com/flutter/flutter/blob/main/docs/engine/impeller/docs/faq.md)). + That fork is a cost Rune should avoid by building the same Rust renderer for wasm + WebGPU, which is + what Figma does with C++/Dawn. +- **Impeller's main lesson is to make every GPU pipeline known at build time.** Shaders are authored once + (GLSL 4.60), compiled offline to MSL, SPIR-V or GLSL ES, and reflected into C++ structs. No shader is + compiled at runtime, so there is no first-run jank. Impeller is now the only renderer on iOS, and the + default on Android, macOS, Windows and Linux as of 3.47 (Impeller + [README availability matrix](https://github.com/flutter/flutter/blob/main/engine/src/flutter/impeller/README.md)). +- **Flutter's threading converged on what GPUI already does: UI code runs on the platform main thread.** + The "great thread merge" shipped on iOS/Android in 3.29 and on macOS/Windows in 3.35. Rasterization + stays on its own thread. +- **The feel benchmark is not "the render server does everything".** Core Animation's out-of-process + render server keeps `CAAnimation`s running when the main thread blocks. But Apple's modern SwiftUI + animations do **not** create `CAAnimation`s: they evaluate springs in-process and write presentation + values directly, off the main thread for built-in effects + ([WWDC24 10145](https://developer.apple.com/videos/play/wwdc2024/10145/), + [WWDC23 10156](https://developer.apple.com/videos/play/wwdc2023/10156/)). So Rune can match the feel + with an in-process animation clock that is off the main thread and has excellent frame pacing. + It does not need to lower everything to CA. +- **The spring model to copy is exactly Apple's `spring(duration:bounce:)`**: mass 1, k = (2π/d)², + ζ = 1 − bounce for bounce ≥ 0 and 1/(1 + bounce) for bounce < 0. When an animation is retargeted it + merges and keeps its velocity. Flutter now ships the identical conversion + (`SpringDescription.withDurationAndBounce`). Gesture handoff should come from **merging interactive + springs**, not from a hand-computed initial velocity (WWDC24). +- **iOS scroll feel is known, published arithmetic.** Deceleration is 0.998/ms (normal) or 0.99/ms (fast). + The rubber band is `(1 − 1/(x·0.55/d + 1))·d`. Fling projection is `v/1000 · r/(1 − r)`. Flutter + tunes its versions by overlaying a native scroll view and fitting curves. That is a good proof loop + to steal. +- **Liquid Glass (iOS/macOS 26) cannot be honestly reproduced by a custom renderer**, because the system + material adapts continuously to what is behind it. It *can* be hosted: `UIGlassEffect` and + `NSGlassEffectView` sample whatever the render server composites beneath them, including a + `CAMetalLayer` **(inference; matches the launcher's experience, verify in a spike)**. Flutter has no + first-party Liquid Glass after 16 months + ([flutter#170310](https://github.com/flutter/flutter/issues/170310)). Its apps fall back to platform + views for it. +- **Rive's renderer is the best non-Rust reference for vector quality.** It uses analytic coverage via + tessellated, signed-winding triangle patches; a "clockwise" fill rule; and pixel-local-storage or + atomic interlock modes. Its **vector feathering** computes soft edges as the integral of a Gaussian + along the real path edges, using a lookup texture, with no blur pass + ([Rive blog](https://rive.app/blog/how-rive-reinvented-feathering-for-the-vectorian-era), + `renderer/src/shaders/draw_path_common.glsl:186`). This is the right primitive for Kit's "soft + gradient masks, never a hard clip". +- **Figma's lessons**: one C++ renderer compiled to both wasm and native, with Dawn underneath both. A + draw API with explicit arguments (no global binding state). Batched uniform uploads. Hot device-loss + fallback (WebGPU→WebGL mid-session). Per-PR perf tests on real hardware + ([Figma WebGPU](https://www.figma.com/blog/figma-rendering-powered-by-webgpu/), + [Keeping Figma fast](https://www.figma.com/blog/keeping-figma-fast/)). +- **Animation-as-data (Lottie/Skottie, Rive state machines) gives a pure function `seek(t) → scene`.** + That is exactly what agent verification needs: deterministic frame N on demand. Flutter's test binding + does the same with a fake clock (`FakeAsync`, clock fixed at 2015-01-01) and a box-glyph test font + ("Ahem"), so golden images are deterministic. + +--- + +## 1. Flutter + Impeller (the reach benchmark) + +### 1.1 Engine architecture and threads + +- **Pipeline.** The framework (Dart) runs build → layout → paint and produces a `Scene` (engine-side + `LayerTree` of container, transform, clip, opacity, backdrop-filter and picture layers). Picture + layers hold **DisplayLists**, Flutter's recorded command buffers. The Animator posts the layer tree into + a pipeline. The Rasterizer on the raster thread runs `Preroll` + `Paint` over the layers, and those + dispatch DisplayList ops to Impeller (or Skia) + ([Life of a Flutter Frame](https://github.com/flutter/flutter/blob/main/docs/engine/Life-of-a-Flutter-Frame.md)). + Display lists are the seam where renderers can be swapped: "the engine has Skia and Impeller + dispatchers for display lists" + ([Impeller FAQ](https://github.com/flutter/flutter/blob/main/docs/engine/impeller/docs/faq.md)). +- **Layout** is a single depth-first pass: constraints go down, sizes go up, O(n) for the initial layout + and sublinear for updates thanks to relayout boundaries + ([architectural overview](https://docs.flutter.dev/resources/architectural-overview), + [Inside Flutter § Sublinear layout](https://docs.flutter.dev/resources/inside-flutter)). +- **Threads.** Historically there were four task runners: platform (OS main), UI (Dart), raster and IO. + **Thread merge:** from 3.29, Dart runs on the platform thread on iOS and Android ("the UI thread is + removed"). macOS and Windows followed in 3.35 + ([breaking-change doc](https://docs.flutter.dev/release/breaking-changes/macos-windows-merged-threads), + [flutter#150525](https://github.com/flutter/flutter/issues/150525)). A secondary source says Linux + is still opted out by default + ([Medium](https://medium.com/easy-flutter/flutters-great-thread-merge-what-it-means-for-your-apps-1f712d6b253d)). + The stated reason was that split threads "prevented Flutter apps and plugins from using Dart FFI to + interoperate with native APIs that must be called on the platform thread". The raster thread is still + separate. *Relevance:* Rune (Rust UI on the main thread + a render thread) matches where Flutter + ended up. Synchronous native calls on the UI thread are a feature, not a bug. +- **Warm-up frame.** Before the first vsync, the framework builds, lays out and paints once so that the + first real frame is cheap (Life of a Flutter Frame § Warm-up frame). + +### 1.2 Why Impeller replaced Skia + +- **The problem was shader compilation jank.** Skia generated and compiled shaders lazily, when a draw + type was first seen, so the first animation stuttered. The old fix (SkSL warm-up capture) was brittle. +- **Impeller's objectives** + ([README](https://github.com/flutter/flutter/blob/main/engine/src/flutter/impeller/README.md)): + - "All shader compilation and reflection is performed offline at build time. All pipeline state + objects are built upfront. Caching is explicit." + - Every GPU resource is labelled ("Instrumentable"). + - Portable across backends. + - Spreads a frame across threads when needed. +- **Shader pipeline:** GLSL 4.60 → SPIR-V via `impellerc` → MSL, Vulkan SPIR-V or GLSL ES 1.00 → a single + blob embedded in the binary. A reflector emits C++ structs for the uniform and vertex layouts, so + "changes to the shader interface lead to compile time errors". This idea maps directly onto Rust: + WGSL/naga reflection into `#[repr(C)]` structs at build time. +- **Layering:** `renderer` (backend-agnostic HAL) → `entity` (2D renderer, pass-rewriting/eliding + optimizations) → `display_list` (DisplayList dispatcher) → `typographer` (glyph atlases only; "Impeller + does **not** do any text layout or shaping"). It also has a `playground` test harness that opens any + test case in a window or attaches a frame debugger. Impeller-level golden tests live in + `impeller/golden_tests`. +- **Anti-aliasing:** 4× MSAA everywhere. SDF rendering for primitives is on by default on desktop and + off by default on mobile ([Impeller AA](https://docs.flutter.dev/perf/antialiasing)). This is weaker + than Rive's or Vello's analytic coverage. For example, MSAA gives four coverage levels per pixel + unless SDFs are used. +- **Status in 2026** (README matrix, 3.47 stable): + - iOS: ⭐ exclusive. Skia removed in 3.29. + - Android: ✅ default, Vulkan first with a fallback to Impeller-GLES. The 2026 roadmap aims to remove + Skia on Android 10+ entirely + ([Roadmap 2026](https://github.com/flutter/flutter/blob/master/docs/roadmap/Roadmap.md)). + - macOS, Windows, Linux: ✅ default as of 3.47. They were preview or experimental through 3.44. + - Web: 🚫. CanvasKit/Skwasm remain. The FAQ says porting the web engine to Impeller is a non-goal, + although WGSL compilation was sanity-checked. + - Skia pieces still in use: SkParagraph for text layout, and the Skia-wrapped image codecs (attempts + to replace them with system decoders stalled, flutter#144438 and #177863). +- **Flutter GPU** is a Dart API over Impeller's HAL (`engine/src/flutter/lib/gpu`) for custom renderers, + with Flutter Scene for 3D. In 2026 it is still "early preview… switching to the master channel is + strongly recommended" + ([Flutter-GPU.md](https://github.com/flutter/flutter/blob/main/docs/engine/impeller/Flutter-GPU.md)). + +### 1.3 Platform views (the cost of hosting native views) + +- **Android** + ([docs](https://docs.flutter.dev/platform-integration/android/platform-views)) has three modes: + - **Texture Layer:** the native view renders to a texture that Impeller composites. It is "janky during + quick scrolling" and breaks SurfaceView, accessibility and the magnifier. + - **Hybrid Composition:** the native view stays in the Android hierarchy and Flutter renders into + `ImageReader`-backed overlays. It "causes thread merging of raster & platform, which degrades + Flutter FPS". Before Android 10 it also copied every frame. + - **HCPP (experimental):** both Flutter and the native view render to native Surfaces, and + SurfaceFlinger composites them using native transaction sync. It requires API 34+, Vulkan and + Impeller. +- **iOS** uses hybrid composition only. Flutter slices its output into extra overlay Metal layers above + and below each `UIView` (`FlutterPlatformViewsController.mm`, `overlay_layer_pool.mm`). Mutators + (clips, transforms, opacity) are replayed onto the UIView. `ShaderMask` and `ColorFiltered` are not + supported over platform views, and `BackdropFilter` is limited + ([iOS platform views](https://docs.flutter.dev/platform-integration/ios/platform-views)). The docs + even suggest screenshotting the native view into a texture while animating. +- **macOS:** the raster thread must synchronize with the platform thread, so "any slow or blocking + operations on the platform thread can negatively impact Flutter graphics performance" + ([macOS platform views](https://docs.flutter.dev/platform-integration/macos/platform-views)). +- **Lesson:** hosting native views inside a self-drawn surface is a compositing-synchronization problem + (the GPU frame and the OS layer transaction must land in the same vsync). It is not a drawing problem. + The correct primitive is atomic present-with-transaction: + - iOS/macOS: `CAMetalLayer.presentsWithTransaction` or IOSurface contents in a `CATransaction`. + - Android: SurfaceControl transactions, which is what HCPP does. + - Windows: DirectComposition commit. + +### 1.4 Semantics (accessibility) + +The framework builds a parallel **SemanticsNode** tree (labels, actions, flags, rects) and sends deltas +to the engine. Each embedder maps the tree onto native accessibility: + +- iOS: `SemanticsObject.mm` creates `UIAccessibilityElement`s, plus `TextInputSemanticsObject` for + fields and `FlutterSemanticsScrollView` for scroll containers. +- Android: `AccessibilityNodeInfo`. +- Web: a DOM shadow tree. + +Test pumps default to `EnginePhase.sendSemanticsUpdate`, so semantics are exercised in every widget test +(`flutter_test/lib/src/binding.dart:1454`). *Steal:* make the semantics tree a first-class output of +every frame. It doubles as the agent-queryable inspector tree. + +### 1.5 Text + +- **Layout/shaping:** `txt/` wraps **SkParagraph** (Skia's paragraph module over HarfBuzz + ICU). It + replaced the original libtxt, a fork of Android's Minikin (`engine/src/flutter/txt/src/skia/paragraph_skia.cc`). +- **Rasterization:** Impeller's typographer has a single backend, `typographer/backends/skia`, which + rasterizes glyphs into atlases. +- **Text editing is the weak spot.** On iOS, Flutter implements `UITextInput` on a hidden proxy view and + draws caret, selection and handles itself. `FlutterTextInputPlugin.mm` is 3,403 lines and handles: + - marked text (`kInvalidFirstRect` hacks to hide or show IME candidates); + - the floating cursor; + - `UITextInteraction` for some modes; + - `UIEditMenuInteraction` for the native edit menu; + - dictation placeholders; + - Scribble (`UIIndirectScribbleInteraction`). + + Every new iOS text feature has to be re-implemented, and parity always lags. + +### 1.6 Hot reload (why it works and what it can't do) + +- **Mechanism** ([docs](https://docs.flutter.dev/tools/hot-reload)): + 1. The tool recompiles only the changed libraries, plus the path from `main` to them, into Dart + **kernel** files. + 2. It ships them over the VM service. + 3. The VM reloads the libraries in place. The heap and all objects stay alive, and "so far no code is + re-executed". + 4. The framework then calls `reassemble`, which rebuilds, relayouts and repaints every widget. + + The docs show "Reloaded 1 of 448 libraries in 978ms". In practice it is often 200–800 ms + **(estimate)**. It works over USB/Wi-Fi to physical iPhones in debug (JIT) builds. +- **Why it works so well:** + - The JIT VM can swap function bodies and class shapes under a live heap. + - UI is a pure function of state (`build`), so re-running `build` everywhere shows the new code with + the old state. + - State lives in `State` objects and Elements keyed by tree position, which survive the reload. +- **What it can't do:** + - `main()` and `initState()` are not re-run. + - Global and static field initializers are treated as state, so they are not re-evaluated (const is + the exception). + - Changing an enum to a class or vice versa needs a restart, as do generic arity changes and native + code changes. + - `CupertinoTabView` builders don't reload. + - Release builds are AOT and can't reload at all. The 2026 roadmap explores "interpreted bytecode in + the Dart runtime" for ephemeral code. +- **Rust implication:** there is no VM, so the equivalent has to come from: + 1. view and state code in a dylib that is reloaded, or a wasm module, or an interpreted UI DSL; + 2. state held outside the reloaded code (an arena keyed by stable ids or tree position); + 3. a framework `reassemble()` that rebuilds everything. + + Flutter's failure cases show the design rule: **anything evaluated once at startup won't reload**, so + keep configuration in getters or rebuild paths. + +### 1.7 Tooling and tests + +- **DevTools** talks to the VM service (JSON-RPC over WebSocket) and offers a widget inspector (tree, + layout explorer), a performance view (UI/raster frame bars, timeline), a CPU profiler and memory views + ([DevTools](https://docs.flutter.dev/tools/devtools)). In 2025–26 the same service is exposed to + agents through the Dart/Flutter **MCP server** (roadmap 2026, [docs](https://docs.flutter.dev/ai/mcp-server)). +- **Goldens:** `matchesGoldenFile` does an exact pixel comparison (`LocalFileComparator`) and writes + master/test/diff/masked-diff images on failure (`flutter_test/lib/src/_goldens_io.dart`). + `--update-goldens` regenerates them. Determinism comes from: + - the **Ahem** test font (every glyph is a square), via `--use-test-fonts`; + - `FakeAsync` with a fixed clock (`DateTime.utc(2015)`, `binding.dart:2687-2689`); + - `pump(duration)`, which advances virtual time. +- **Device tests:** `integration_test` runs widget-test APIs on a real device. It replaced most + `flutter_driver` use, which was a remote-control protocol. +- **Impeller playground:** any test fixture can open interactively or attach Xcode/RenderDoc captures. + +### 1.8 What made Flutter reach six platforms + +1. **It owns the pixels.** One renderer and one text stack give identical output everywhere, so a new + platform means implementing an embedder, not a widget set. +2. **A stable C embedder API** (`embedder.h`). Third parties ship their own embedders (automotive, + embedded Linux, flutter-pi), and the 2026 roadmap wants new platforms to be authored "out-of-tree". +3. **The same Dart in two compilation modes:** JIT for development (hot reload) and AOT for release. +4. **Platform channels and FFI** for native APIs. After the thread merge, FFI calls into main-thread-only + APIs are synchronous. +5. **Adaptive but self-drawn design systems** (Material, Cupertino), which are now being decoupled into + separate packages (roadmap 2026). + +### 1.9 What still feels non-native + +- **Scroll physics are approximations.** `BouncingScrollPhysics` is fitted by overlaying a native + scroll view (`scroll_physics.dart:908`, "Use … platform_tests/scroll_overlay to test with Flutter and + platform scroll views superimposed"): + - friction 0.135 = 0.998¹⁰⁰⁰ (`scroll_simulation.dart:50-53`); + - overscroll resistance `0.52·(1 − overscroll/viewport)²` (`scroll_physics.dart:826`), which is not + Apple's 0.55 formula; + - momentum carry `0.000816·|v|^1.967` (`:921`). +- **Gesture thresholds:** `kTouchSlop` = 18 logical px and `kMinFlingVelocity` = 50 lp/s + (`gestures/constants.dart:65,90`). iOS's swipe hysteresis is "usually 10 points" + ([WWDC18 803](https://developer.apple.com/videos/play/wwdc2018/803/)). +- **Text selection, IME, magnifier, context menus.** Re-implemented, as above. `SystemContextMenu` now + uses the native menu on iOS. +- **Keyboard sync.** iOS has no per-frame keyboard callback, so Flutter animates a *hidden UIView* with + the keyboard's curve and samples its `presentationLayer` every vsync + (`KeyboardInsetManager.swift:22-36`). This is a clever, reusable trick for following any system + animation. +- **New system design arrives late or never.** There is still no first-party Liquid Glass (flutter#170310). + Packages such as `adaptive_platform_ui` and `cupertino_native` embed real UIKit controls as platform + views. +- **ProMotion needs `CADisableMinimumFrameDurationOnPhone`** on iPhone. Flutter sets the + `CADisplayLink.preferredFrameRateRange` to `[max/2, max]` (`VSyncClient.swift:89-104`, + `DisplayLinkManager.swift:45-49`). It also replaced `CAMetalLayer` with **`FlutterMetalLayer`**, a + custom IOSurface-backed `CALayer` that presents by setting `contents` inside a `CATransaction` on the + main thread (`FlutterMetalLayer.h:10-15`, `.mm:325-363`). The comment reads "This is needed otherwise + frame gets skipped on touch begin / end. Go figure." Even Google couldn't get stock `CAMetalLayer` + pacing right. + +### 1.10 Startup and binary size + +- Old official numbers: + - A 2021 FAQ measured a minimal release APK at about 4.3 MB (arm32) and 4.8 MB (arm64) + **(older, from memory of the 2021 FAQ; the current FAQ only says "a few megabytes compressed")** + ([FAQ](https://docs.flutter.dev/resources/faq#how-big-is-the-flutter-engine)). + - The iOS demo app in Flutter 1.17 was 5.4 MB download and 13.7 MB installed + ([app size](https://docs.flutter.dev/perf/app-size)). +- The engine tracks `hello_world_{android,ios}__compile/release_size_bytes` in CI + ([Engine disk footprint](https://github.com/flutter/flutter/blob/main/docs/engine/Engine-disk-footprint.md)). + I found no current public numbers for size or for cold-start time. Engine init plus isolate start is + expensive enough that add-to-app docs recommend pre-warming a `FlutterEngine` + ([docs](https://docs.flutter.dev/add-to-app/performance)). + +--- + +## 2. SwiftUI + Core Animation (the feel benchmark) + +### 2.1 The render loop and render server + +- The five phases ([Explore UI animation hitches](https://developer.apple.com/videos/play/tech-talks/10855/)): + 1. **event** + 2. **commit**: the app updates the layer tree and "submits that to the render server" + 3. **render prepare**: in "a separate process called the render server" (backboardd on iOS, + WindowServer on macOS) + 4. **render execute**: on the GPU + 5. **display** + + Frames are double-buffered, with a triple-buffer fallback that gives the render server an extra frame. +- **Why CA animations survive a blocked main thread:** a `CAAnimation` is committed once as a + description (from/to/timing). The render server interpolates it every frame in its own process. The + model layer holds the final value, and the presentation layer reflects the in-flight value. +- **Kit's launcher experience** (a 120 Hz glass morph moved to CA) is explained by this. Anything expressed + as CA layer animations is immune to app-side hitches. + +### 2.2 Implicit, additive and interruptible animation (UIKit/CA) + +- **Implicit actions:** setting a layer property inside a `CATransaction` creates a default animation. + UIView suppresses these outside animation blocks. +- **Additive by default since iOS 8** + ([WWDC14 236 notes](https://wwdcnotes.com/documentation/wwdc14-236-building-interruptible-and-responsive-interactions/)). + A new UIView animation on a property that is already animating no longer snaps or replaces. It adds a + relative animation (from old target to new target) on top of the running one, so the presentation + value stays continuous. That is how UIKit got interruptibility without reading presentation state. +- **`UIViewPropertyAnimator`** (iOS 10, + [WWDC16 216](https://developer.apple.com/videos/play/wwdc2016/216/)) is interruptible, scrubbable + (`fractionComplete`) and reversible, and continues with new timing parameters. + `UISpringTimingParameters(initialVelocity:)` takes a *unit-relative* velocity (points/s ÷ distance). +- **`CASpringAnimation`:** iOS 17 added `init(perceptualDuration:bounce:)`, and + `UIView.animate(duration:bounce:)` gives UIKit the same parameterisation + ([WWDC23 10158](https://developer.apple.com/videos/play/wwdc2023/10158/)). + +### 2.3 SwiftUI's Animation/Transaction model + +- **Transactions.** State changes happen inside a `Transaction`, which carries the `Animation` and + flags such as `disablesAnimations`. `withAnimation` sets it explicitly, and `.animation(_:value:)` + sets it implicitly for a subtree. iOS 17 added custom `TransactionKey`s and completion criteria + (`.logicallyComplete` uses the perceptual duration, not the settling time). +- **Animatable attributes vs. animations** + ([WWDC23 10156](https://developer.apple.com/videos/play/wwdc2023/10156/)). The animatable data is a + `VectorArithmetic` value. The animation is a function `(target, elapsed, context) → value?`. The + `CustomAnimation` protocol (iOS 17) has `animate`, `velocity` and `shouldMerge`. +- **Merging.** When `shouldMerge` returns true, the new animation inherits the previous one's state and + elapsed time and replaces it. Springs merge and **preserve velocity**. The default (false) runs both + animations and combines their results, which is additive like UIKit + ([shouldMerge docs](https://developer.apple.com/documentation/swiftui/customanimation/shouldmerge(previous:value:time:context:))). + Docs for `spring(duration:bounce:blendDuration:)`: "each spring animation will be replaced by their + successor, preserving velocity from one animation to the next." +- **Where the evaluation happens:** + - "For built-in animatable attributes like scaleEffect, SwiftUI … is able to do this work off the + main thread and without calling into any of your view code." + - A custom `Animatable` view "will run body for every frame of the animation" (WWDC23 10156). + - "The SwiftUI animation does not create a CAAnimation, but instead animates the view's layer's + presentation values directly" (WWDC24 10145, on using SwiftUI `Animation` with UIKit in iOS 18). + + **So the state of the art is in-process, per-frame spring evaluation on a non-main animation thread.** + It is not render-server keyframes. +- **Velocity handoff from gestures** (WWDC24 10145). During a drag, each change event starts an + `.interactiveSpring` that retargets the previous one. On release, a normal spring is merged in, and + "uses the velocity from the interactiveSprings, to carry the animation forward with continuous + velocity". There is no manual velocity computation. iOS 18 brought the same behaviour to UIKit and + AppKit (`UIView.animate(_ animation: Animation)`). +- **`matchedGeometryEffect`** (iOS 14) synchronizes geometry for views that share an id in a + `@Namespace`. When one view is inserted and another removed in the same transaction, SwiftUI + "interpolate[s] their frame rectangles in window space" ([docs](https://developer.apple.com/documentation/swiftui/view/matchedgeometryeffect(id:in:properties:anchor:issource:))). + It links geometry only; the enter and exit rendering are normal transitions. Liquid Glass's + `glassEffectID` is the same idea applied to glass morphing. + +### 2.4 Springs: duration + bounce + +Apple's conversion is on the "Spring Parameter Conversion" slide of WWDC23 10158. The transcript's text +version is garbled, so the formula below is derived and matches Flutter's implementation: + +``` +mass = 1 +stiffness k = (2π / duration)² +damping c = 4π(1 − bounce) / duration bounce ≥ 0 (ζ = 1 − bounce) + c = 4π / (duration · (1 + bounce)) bounce < 0 (ζ = 1/(1+bounce)) +``` + +- "duration" is a **perceptual duration**. It is roughly the settle time, and for very bouncy springs it + is the oscillation period. It is deliberately not the settling duration, which is unpredictable. +- Bounce ranges from −1 to 1. The default is 0 (critically damped), which is "what you get if you don't + specify the bounce". +- Springs have been the default `withAnimation` animation since iOS 17. +- Presets: `.smooth` (no bounce), `.snappy` (small bounce), `.bouncy` (more bounce). Each takes + `duration:` and `extraBounce:`. +- Flutter's identical implementation is in `physics/spring_simulation.dart:70-82`. Its doc comment says + "This constructor produces the same result as SwiftUI's `spring(duration:bounce:blendDuration:)`". + +Reference values (computed): + +| spec | k | c / ζ | +|---|---|---| +| d=0.5, b=0 | 157.9 | 25.13 / 1.0 | +| d=0.5, b=0.15 | 157.9 | 21.36 / 0.85 | +| d=0.5, b=0.3 | 157.9 | 17.59 / 0.7 | +| Compose default `spring()` (k=1500, ζ=1) | 1500 | ≡ d≈0.162 s, b=0 | +| M3 Expressive default spatial (k=380, ζ=0.8) | 380 | ≡ d≈0.322 s, b=0.2 | + +### 2.5 Scroll physics + +- **Deceleration:** `UIScrollView.DecelerationRate.normal` = 0.998 and `.fast` = 0.99. Each is the + velocity multiplier per millisecond (Flutter's comment confirms 0.998, `scroll_simulation.dart:50`). + Velocity follows v(t) = v₀·rᵗᵐˢ. +- **Projection** (WWDC18 803 sample code): `project(v) = (v/1000)·r/(1 − r)`. With r = 0.998, a + 1000 pt/s fling travels about 499 pt. With 0.99 it travels about 99 pt. Use it to pick snap targets + from the *projected* position, not the release position. +- **Rubber band:** `b = (1 − 1/(x·c/d + 1))·d` with c = 0.55 and d = the viewport dimension. This was + reverse-engineered ([gist](https://gist.github.com/originell/6961057)) and is widely reused. On an + 844 pt iPhone, 100 pt of drag gives about 51.6 pt of movement and 400 pt gives about 174.5 pt. The + release springs back with an overdamped-ish spring. +- **Scroll edge effects.** In iOS 26 the system applies a "subtle blur and fade" under bars + (`scrollEdgeEffectStyle`, [WWDC25 323](https://developer.apple.com/videos/play/wwdc2025/323/)). That + is Apple formalising Kit's "no hard clipped edges". + +### 2.6 ProMotion frame pacing + +- **`CADisplayLink.preferredFrameRateRange`** (iOS 15+) takes a min/max/preferred range. On iPhone, + rates above 60 Hz need `CADisableMinimumFrameDurationOnPhone = true` in Info.plist (Flutter + `DisplayLinkManager.swift:45-49`). CA animations get their rates from the system automatically. +- **`CAMetalDisplayLink`** (iOS 17, macOS 14, + [docs](https://developer.apple.com/documentation/quartzcore/cametaldisplaylink)) is made for Metal + renderers that "need more control over the timing window": + - its delegate receives an update containing a drawable and a `targetPresentationTimestamp` + ("update your animations based on the time difference between this timestamp and the previous + timestamp"); + - `preferredFrameLatency` accepts only 1 or 2 frames, and "may be bigger … for windowed modes on + macOS". + - Caveat: Rive reported that `CAMetalDisplayLink` "is currently causing crashes on _some_ iOS + devices" and fell back to `CADisplayLink` + ([rive-ios#349](https://github.com/rive-app/rive-ios/issues/349)). +- **Adaptive-Sync on Mac** ([WWDC21 10147](https://developer.apple.com/videos/play/wwdc2021/10147/)): + use `presentAfterMinimumDuration` / `presentAtTime` for even pacing on VRR displays. Relying on + drawable back-pressure gives uneven frames. +- **Rule for Rune:** always animate against the *target presentation time*, not the callback time. + The animation clock must advance by actual presented intervals, so that a dropped frame produces a + bigger step rather than a stall. That is what keeps motion on its curve. + +### 2.7 Liquid Glass (iOS/macOS 26) + +- **What it is** ([WWDC25 219](https://developer.apple.com/videos/play/wwdc2025/219/)): + - a material defined by **lensing** (refraction of the content behind it); + - layers that "continuously adapt based on what's behind it" (shadow, tint, dynamic range, + independent light/dark flipping); + - morphing between control states. + - Its rules: no glass on glass, and Regular and Clear variants are never mixed. +- **APIs:** + - SwiftUI: `glassEffect(_:in:)`, `GlassEffectContainer`, `glassEffectID`. + - UIKit: `UIVisualEffectView` + `UIGlassEffect` / `UIGlassContainerEffect`. + - AppKit: `NSGlassEffectView` (`contentView`) / `NSGlassEffectContainerView` (`spacing`). + - These are OS 26+ only ([glassEffect docs](https://developer.apple.com/documentation/swiftui/view/glasseffect(_:in:))). +- **Mechanics that matter for hosting:** + - "This effect is achieved by sampling content from an area larger than itself. However, glass can + not sample other glass" (WWDC25 323). + - AppKit: put content in `contentView` so that the system applies vibrancy and legibility treatment. + "Avoid placing the NSGlassEffectView behind your content as a sibling view" + ([WWDC25 310](https://developer.apple.com/videos/play/wwdc2025/310/)). +- **Can a custom renderer reproduce it?** It could approximate it: an SDF capsule, backdrop + blur/refraction with a displacement map, a rim highlight, adaptive tint from backdrop luminance. Rive + feathering or a WGSL backdrop shader could get close. It will not track Apple's per-release tuning, + accessibility settings (Reduce Transparency, Increase Contrast) or system-wide light response. Flutter + contributors argue it would "not 100% match" and would lag behind + ([flutter#170310 comment](https://github.com/flutter/flutter/issues/170310#issuecomment-2958004370)). +- **Can it host it? Yes, with constraints (inference; spike needed).** + - The glass is a CA layer subtree. The render server samples whatever is composited below it, and a + `CAMetalLayer`/IOSurface layer is ordinary composited content, so a Rune surface *under* a native + glass view should refract correctly. + - Content *on* the glass (labels, icons) must be inside the glass's `contentView` to get vibrancy. That + means either native views, or a second Rune surface (a Metal layer) placed inside `contentView`, + with legibility treatment applied by Rune rather than the system. + - Glass geometry (position, size, morph) must be animated with CA or SwiftUI in the *same transaction* + as Rune's frame. Otherwise glass and content drift by a frame. This is the same sync problem as + Flutter's platform views. + - In practice: drive glass shapes from Rune's layout, and commit them through `CATransaction` with + the Metal present (`presentsWithTransaction`, or IOSurface `contents` like `FlutterMetalLayer`). + Use the system's `GlassEffectContainer` morphing where possible. + +### 2.8 What a non-Apple framework must replicate to feel native on iOS + +The full checklist is in "What Rune must match" below. The core is: + +- continuity of position and velocity on every interruption; +- spring-default motion with duration/bounce; +- gesture → animation handoff by merging; +- the exact scroll constants; +- 120 Hz pacing against the presentation timestamp; +- native text input and accessibility; +- system materials and transitions hosted rather than faked. + +--- + +## 3. Rive, Figma, Lottie/Skottie + +### 3.1 Rive renderer (`rive-runtime/renderer`, MIT) + +- **Design.** It is a vector and raster renderer "custom-built for Rive content, for animation, and for + runtime". Backends: Metal, Vulkan, D3D11/12, GL/WebGL2, WebGPU (`renderer/src/{metal,vulkan,d3d11,d3d12,gl,webgpu}`). + `RenderContext` "manages all the GPU buffers… required for Rive's pixel local storage path rendering + algorithm" (`include/rive/renderer/render_context.hpp:86-88`). +- **Paths.** Béziers are tessellated *on the GPU* (`shaders/tessellate.glsl`) into triangle patches + around the edges. The antialiasing is described in the + [feathering blog](https://rive.app/blog/how-rive-reinvented-feathering-for-the-vectorian-era): + "triangle-based coverage interpolation… Depending on whether a triangle naturally falls clockwise or + counterclockwise, it contributes positive or negative coverage to a pixel." +- **Interlock modes** (`include/rive/renderer/gpu.hpp:1073-1088`): + - `rasterOrdering`: pixel local storage / raster order groups on Apple and Android tile GPUs; + - `atomics`; + - `clockwise` and `clockwiseAtomic`: these override fill rules with "clockwise" (only positive + winding fills), which makes atomics usable without barriers; + - `depthStencil` (MSAA fallback). + + Gradients go into a 512-wide ramp texture (`constants.glsl:61`). Advanced blend modes are implemented + in-shader. +- **Vector feathering** (shipped February 2025): + - "Instead of an anti-aliasing ramp that's one pixel wide, we could extend it to any width… shape that + transition based on a normal distribution curve." The feather opacity "is the integral of the normal + distribution function", centred on the true edge. + - Corners and curves need a 2D integral. The shader uses a separability trick plus a precomputed + **Gaussian-integral 1D texture** (`constants.glsl:64-73`, `GAUSSIAN_INTEGRAL_TEXTURE_STDDEVS = 3`) + and evaluates per-corner coverage in `eval_feathered_fill` (`draw_path_common.glsl:186-204`). + - Large feathers go through a feather atlas (`FEATHER_ATLAS_BLIT`). + - It needs the Clockwise fill rule. NoesisGUI notes it is "tightly coupled to their own custom + renderer" ([forum](https://www.noesisengine.com/forums/viewtopic.php?t=3718)). +- **Text:** HarfBuzz + SheenBidi shaping (`premake5_v2.lua:97-98`, `src/text/`). Glyphs render as paths + through the same analytic AA, which is "Perfect text… crisp at any size". +- **The runtime is quietly becoming a UI framework.** It has: + - Yoga layout (`dependencies/premake5_yoga_v2.lua`, `src/layout/`); + - state machines with layers, blend states and transitions; + - listeners for pointer, keyboard, focus, gamepad, plus `semantic_listener_group.cpp`; + - data binding / view models (`src/viewmodel`); + - Luau scripting (`src/lua`, `scripting/`); + - a threaded command queue/server (`command_queue.cpp`, `command_server.cpp`). + + Rive's state machine is declarative animation-as-data: inputs (bool/number/trigger) or view-model + properties drive transitions with conditions and blend durations. It is evaluated by + `advance(dt)`, which is deterministic. + +### 3.2 Figma renderer + +- **Architecture** (2015, [Evan Wallace](https://www.figma.com/blog/building-a-professional-design-tool-on-the-web/)): + - a C++ editor compiled with Emscripten (asm.js, then wasm); + - all memory in one typed array, so there are no GC pauses; + - a "highly-optimized **tile-based** engine with support for masking, blurring, dithered gradients, + blend modes, nested layer opacity"; + - "our own DOM, our own compositor, our own **text layout engine**", because browser text layout + "is inconsistent between browsers… and even… platforms". Their biggest web pain was "lack of access + to glyph outlines and kerning tables". +- **WebGPU migration** (shipped September 2025, + [Figma rendering: Powered by WebGPU](https://www.figma.com/blog/figma-rendering-powered-by-webgpu/)): + 1. They redesigned the graphics interface **before** touching WebGPU. Draw calls take explicit + arguments, `context->draw(vertexBuffer, framebuffer, {texture}, material, …)`, instead of global + binds. This "fixed a handful of bugs in our WebGL renderer before we even touched WebGPU". + 2. Uniforms are batched: `encodeDraw(uniforms, material)…submit()` uploads all uniform data to one + buffer with offsets. + 3. Shaders stay in WebGL1 GLSL. A custom preprocessor upgrades them, then **naga** (wgpu's + translator) emits WGSL, and layouts are reflected for the app. + 4. The same C++ renderer goes to wasm (browser WebGPU through Emscripten bindings, moving to Dawn's + `emdawnwebgpu`) and to native x64/arm64 (server-side rendering, tests, debugging) via **Dawn**. + 5. Readback is async-only in WebGPU, so load-blocking GPU self-tests became impossible. Instead there + is a **dynamic mid-session fallback** from WebGPU to WebGL, modelled on context-loss handling, plus + device blocklists keyed by fallback rate. + 6. Results: "a performance improvement… on some classes of devices… neutral on others, but no + regressions". Next up are compute-shader blur, MSAA and RenderBundles. +- **Perf process** ([Keeping Figma fast](https://www.figma.com/blog/keeping-figma-fast/)): every PR runs + perf scenarios in under 10 min, in parallel, on GPU VMs plus a targeted real-hardware farm. They + rejected counting CPU instructions because the bottleneck is sometimes the GPU or I/O. + +### 3.3 Lottie and Skottie: animation as data + +- **Lottie** is JSON exported from After Effects (Bodymovin, 2015). It is now an open spec stewarded by + the Lottie Animation Community, with a published spec, a validator and compliance tests + ([lottie.github.io](https://lottie.github.io/)). +- **Skottie** (Skia's player, `modules/skottie/include/Skottie.h`) does the following: + - `Animation::Builder` parses the JSON once into an **sksg scene graph** (`sk_sp<sksg::RenderNode>`) + plus a list of animators; + - `seek(t)` / `seekFrame` / `seekFrameTime(t, InvalidationController*)` run the animators to mutate + node properties and collect damage rects; + - `render(canvas)` draws. + - Hooks: `PropertyObserver` for runtime overrides, `MarkerObserver`, `PrecompInterceptor`, + `ExpressionManager` (AE expressions), and a pluggable text shaper. +- **Why it matters for Rune:** + 1. The output is a pure function of t, so any frame can be rendered headlessly, which makes goldens + of motion trivial. + 2. Designers author and engineers bind. + 3. Damage tracking falls out of property invalidation. + + Rive goes further with interactive state machines. Lottie is timeline-only. + +--- + +## 4. Jetpack Compose (the Android feel reference, briefly) + +- **Runtime.** A compiler plugin turns `@Composable` functions into calls against a **slot table**: a + gap buffer holding groups, remembered values and keys, with positional memoization + ([Under the hood of Compose, 2020](https://medium.com/androiddevelopers/under-the-hood-of-jetpack-compose-part-2-of-2-37b2c20c6cdd), older). + Snapshot state tracks reads per scope, and recomposition reruns only the scopes that read changed + state, skipping when inputs are stable. **New in 2026:** an opt-in linked-list slot table + (`ComposeRuntimeFlags.isLinkBufferComposerEnabled`, default false) "designed to improve performance + primarily when deleting, moving, and reordering" ([source](https://github.com/androidx/androidx/blob/androidx-main/compose/runtime/runtime/src/commonMain/kotlin/androidx/compose/runtime/ComposeRuntimeFlags.kt)). +- **Phases:** composition → layout (measure, then place, with separate restart scopes) → draw + ([docs](https://developer.android.com/develop/ui/compose/phases)). **Deferred state reads** inside + `Modifier.offset { }` or `graphicsLayer { }` lambdas skip composition and remeasure. That is how + per-frame animations stay cheap, and it is a key pattern for Rune: animated values should + invalidate *paint/transform only*, never rebuild. +- **Animation:** + - `Animatable` (a coroutine-based single value): `animateTo` "continu[es] the current value and + velocity", and `animateDecay` handles flings. + - `animate*AsState` and `updateTransition` default to `spring()`, which "guarantees the continuity of + velocity when target value changes" ([docs](https://developer.android.com/develop/ui/compose/animation/customize)). + - `Spring` constants (`animation-core/api/current.txt:681-690`): `DampingRatioNoBouncy` 1.0, + `LowBouncy` 0.75, `MediumBouncy` 0.5, `HighBouncy` 0.2. `StiffnessHigh` 10000, `Medium` 1500 + (the default), `MediumLow` 400, `Low` 200, `VeryLow` 50. + - Material 3 Expressive `MotionScheme` tokens: default spatial k=380, ζ=0.8; fast spatial k=800, + ζ=0.6; effects ζ=1 (`ExpressiveMotionTokens.kt`). + - Compose parameterises springs by stiffness and damping ratio. Apple's duration/bounce is the more + designer-legible API, and the two convert losslessly (table in §2.4). +- **The RenderThread analogue.** Android's HWUI RenderThread can run `RenderNodeAnimator`s, as ripples + do, while the UI thread is blocked. That is a partial equivalent of CA's render server. + +--- + +## What Rune must match to feel native on iOS/macOS + +1. **120 Hz, paced to presentation time.** + - iPhone needs `CADisableMinimumFrameDurationOnPhone` and a `preferredFrameRateRange` up to the + maximum. + - Animate against `targetPresentationTimestamp` (`CAMetalDisplayLink` on iOS 17+/macOS 14+, with a + `CADisplayLink` fallback given Rive's crash report). + - Use frame latency 1 when possible. + - Drop to lower rates when idle. +2. **Present atomically with CA transactions.** If any native layer, glass or system view moves with + Rune content, the Metal present and the CA geometry change must commit together. Learn from + `FlutterMetalLayer`: IOSurface pool, `contents` swap inside `CATransaction`, skip stale-size frames. +3. **Springs exactly like Apple's:** + - `spring(duration, bounce)` with default bounce 0, the formula in §2.4, perceptual-duration + completion, and the presets smooth/snappy/bouncy. + - Per-property independent springs that start and stop at different times. +4. **Retargeting that preserves position and velocity on every interruption:** merge semantics (springs + replace and inherit velocity) and additive semantics for non-mergeable curves. +5. **Gesture handoff by merging:** interactive springs during a drag (short duration, tracking), then a + final spring that inherits velocity. Choose snap targets by projected position + (`v/1000·r/(1−r)`). Swipe hysteresis is about 10 pt. +6. **The scroll view, bit for bit:** deceleration 0.998/0.99 per ms, the 0.55 rubber band, momentum + carry on repeated flings, the overscroll spring, paging, scroll-edge soft fade. Verify by overlaying a + real `UIScrollView` and comparing traces (Flutter's `scroll_overlay` method). +7. **An animation clock off the main thread** for transform, opacity, clip, colour and filter, like + SwiftUI's built-in animatable attributes. A main-thread stall should cost layout updates, not motion. + Optionally, lower trivially describable animations to `CAAnimation` for full immunity. +8. **Layout animation with identity:** matched-geometry-style interpolation in window space across + insert and remove, with transitions for enter and exit. Nothing pops. +9. **Soft edges as a primitive:** analytic feathered fills and masks (Rive-style Gaussian-integral + coverage). Make scroll-edge fades and clip feathering cheap enough to be the default. +10. **Native text input and accessibility.** Implement `UITextInput`/`NSTextInputClient` properly, + including marked text, dictation, Scribble, the floating cursor and edit menus. Expose a semantics + tree to `UIAccessibility`/`NSAccessibility`. Follow system keyboard animations; Flutter's hidden-view + `presentationLayer` sampling is a usable trick. +11. **Hosting, not faking, system materials and controls:** Liquid Glass via + `UIGlassEffect`/`NSGlassEffectView` positioned by Rune's layout; system menus, sheets and share UI. + +## What to steal from Flutter's reach strategy + +- **Own the pixels behind a tiny embedder contract**: surface, vsync with timestamps, input, IME, + accessibility tree, clipboard, windows. Write it down as a Rust trait plus a C ABI so third parties + (and agents) can add platforms out of tree. +- **Precompile every pipeline** (Impeller). Use WGSL or Slang compiled at build time, reflected into + Rust structs, with no runtime shader compilation. +- **A display-list seam** between UI and renderer, so recorded frames can be replayed headlessly, + diffed, serialised for bug reports, and dispatched to multiple backends. +- **Semantics as a first-class frame output.** It is also the queryable inspector tree for agents. +- **Deterministic test mode:** a fake clock, a box-glyph test font option alongside real-font goldens, + `pump(duration)`, exact-pixel goldens with diff and masked-diff artifacts, `--update-goldens`. +- **Hot reload with state kept outside the reloaded code** and a full `reassemble()` rebuild. Flutter's + documented failure list (startup initializers, statics, type-shape changes) is the spec for what to + design around. +- **One renderer on the web too.** Figma's architecture (same code on native and wasm, Dawn/wgpu under + both) rather than Flutter's separate web engine. +- **Labelled GPU resources and a "playground" harness** that opens any test in a window or attaches a + frame capture. + +## What to avoid + +- **Re-implementing text editing and selection.** This is Flutter's longest-running parity gap (3,400 + lines of `UITextInput` shim on iOS alone). Use the platform's text input protocols and system menus. + Render glyphs yourself but delegate behaviour. +- **Platform views as an afterthought.** Thread merging, extra overlay layers per native view, and + unsupported filters over native views all come from not designing for atomic CA/SurfaceControl + composition up front. +- **Approximate scroll physics hand-tuned per platform** without a measurement loop. Constants should be + either exact (Apple's are known) or fitted against an overlay test. +- **MSAA-only antialiasing** for UI vectors (Impeller defaults to 4× MSAA). Use analytic coverage. +- **A separate web engine.** +- **Imitating system design languages** (Cupertino imitating UIKit). They drift every year, as Liquid + Glass shows. Host system components where "native" matters, and make Rune's own design language + first-class everywhere else. +- **Stock `CAMetalLayer` assumptions.** Flutter needed a custom layer to avoid skipped frames, and Rive + saw `CAMetalDisplayLink` crashes. Budget a pacing spike with frame traces on real devices. + +--- + +## Recommendation for Rune + +1. **Animation model.** Adopt Apple's semantics exactly: + - `Spring { duration, bounce }` as the only user-facing spring type, with a stiffness/damping escape + hatch; + - merge-with-velocity for springs, additive composition for curves; + - interactive-spring gesture tracking with merge-on-release; + - perceptual-duration completion. + + Evaluate on a dedicated animation and render thread that reads a snapshot of the animatable + properties. The main thread only commits targets. This reproduces SwiftUI's built-in behaviour and + keeps motion alive through UI-thread hitches. +2. **Frame pacing.** + - Darwin: `CAMetalDisplayLink` (latency 1) with a `CADisplayLink` fallback. + - Present through a Flutter-style IOSurface `CALayer` *or* `CAMetalLayer` with + `presentsWithTransaction` when native layers must stay in sync. Decide by spike with Instruments + hitch traces on an iPhone Pro and a Mac with ProMotion. +3. **Renderer quality bar.** Analytic AA plus a feathered-edge primitive (Rive's approach) as table + stakes. Feathered masks are the default clip style. +4. **Native integration.** Build first-class "host layer" nodes, whose CA layers are placed and + animated in the same transaction as Rune frames, from day one. Spike Liquid Glass hosting (Metal + content under `UIGlassEffect`, Rune-driven glass geometry) before committing to any custom glass. +5. **Testing.** Deterministic headless mode (fake clock, seekable animations, display-list dumps, + golden PNGs with diff artifacts) plus a scroll/spring overlay harness that compares Rune traces + against `UIScrollView` and `CASpringAnimation` traces numerically. + +**Rejected alternatives** + +- *Lower all motion to Core Animation (CA-as-renderer).* It gives perfect hitch immunity, but it ties + the renderer to Apple, prevents custom shaders and feathering inside animated content, and doesn't + port. Apple's own SwiftUI no longer works this way. +- *Wrap Flutter or Impeller.* Brief says own the stack. Impeller's MSAA/SDF quality is below the bar, + and Dart is the wrong language. +- *Use Rive's renderer directly.* It is MIT and high quality, but it is C++ and specialised for `.riv` + content. Port the algorithms (clockwise fill, analytic feathering) into Rune's Rust renderer, or + compare against Vello (see other reports). +- *A Cupertino-style imitation widget set.* Ruled out by the Liquid Glass lesson. + +## Open questions + +1. Does a `CAMetalLayer` (or IOSurface layer) under `UIGlassEffect`/`NSGlassEffectView` refract with + full fidelity, and can glass geometry be animated in lockstep with Metal presents at 120 Hz? + (Spike on iOS 26 and macOS 26.) +2. How stable is `CAMetalDisplayLink` on current iOS (26.x)? Is the Rive crash still reproducible? +3. Does SwiftUI's off-main-thread evaluation survive a fully blocked main thread, or does it only avoid + calling view code? Measure with a deliberate 200 ms main-thread stall during `.spring` scaleEffect, + versus a `CASpringAnimation`. +4. Are Apple's exact rubber-band and paging constants unchanged in iOS 26? Measure by tracing + `UIScrollView.contentOffset` per frame and fitting. +5. What is the cost of analytic feathering vs. a separable blur at UI scale (hundreds of soft-edged + rects at 120 Hz on an A-series GPU)? Benchmark Rive's renderer `path_fiddle` vs. Vello on a reserved Mac. +6. Hot reload on a physical iPhone without a JIT: is a wasm UI module, an interpreted DSL, or dylib + reload viable under iOS code-signing rules in debug builds? (Flutter relies on the Dart VM's JIT in + debug.) diff --git a/app/vendor/rune/research/04-language-gpu-renderer.md b/app/vendor/rune/research/04-language-gpu-renderer.md new file mode 100644 index 0000000..3713007 --- /dev/null +++ b/app/vendor/rune/research/04-language-gpu-renderer.md @@ -0,0 +1,332 @@ +# 04 — Language, GPU API, 2D Renderer Design & Input-to-Photon Latency + +## 1. Executive Summary + +Rune’s foundational bet is **Rust + a thin custom GPU HAL (~1,800 LOC per native backend) over raw Metal (macOS/iOS) and `wgpu` (Linux/Windows/WebGPU), paired with a hybrid Core Animation compositor host (`NSGlassEffectView`/`UIVisualEffectView` + `CAMetalLayer`) and an uber-primitive instanced SDF + Sparse-Strips/Slug renderer**. + +1. **Language — Rust (with thin Swift/ObjC2 platform shims and Dioxus `subsecond` hot-patching):** Rust remains the only systems language in 2026 that simultaneously gives zero-GC deterministic frame times, production-grade text/layout/accessibility crates (`taffy`, `parley`, `harfrust`, `fontations`, `swash`, `accesskit`), fearless multi-threaded background work, and top-tier LLM/agent synthesis reliability (compiler diagnostics + strict type/borrow checking catch hallucinations before runtime). Its historical weakness—1–3 s incremental UI iteration—is solved in 2025–2026 by **ThinLink + jump-table binary hot-patching (`subsecond`)** (<200–500 ms stateful UI patches) plus `-Zthreads=8`, `-Zshare-generics=y`, and `mold`/`wild`/Apple `ld_prime`. +2. **GPU API — Custom Thin HAL (`RuneGpu`) with First-Class Raw Metal on Apple + `wgpu` 28+ Elsewhere:** Neither pure `wgpu` everywhere nor four hand-written native backends is optimal. On macOS/iOS, raw Metal (`objc2-metal`) combined with a shallow `CALayer` host tree is mandatory for zero-copy `IOSurface` video/camera surfaces, `NSGlassEffectView` liquid glass backdrops, `CATransaction`-synchronized window resizing (`presentsWithTransaction`), programmable tile/framebuffer fetch, and EDR headroom. On Linux, Windows, and Web, Zed’s February 2026 migration from `blade-graphics` to `wgpu` ([zed#46758](https://github.com/zed-industries/zed/pull/46758), cutting median CPU draw time from 301 µs to 236 µs) proves `wgpu` is now fast enough and eliminates thousands of lines of Vulkan/D3D12 driver-quirk maintenance while giving WebGPU for free. +3. **2D Renderer — Single-Pass Uber-SDF Primitives + Public-Domain `Slug` (Large/Transformed Text & Icons) + `vello_gpu` Sparse Strips (Complex Vector Art):** + - **95% of UI** (rounded boxes, per-corner radii, elliptical inner borders, analytic 4-sample `erf` Gaussian drop/inner shadows, bevel/specular surface materials, Oklab gradients with Jimenez IGN triangular dithering, and **analytic 4-edge soft-clip masks**) renders in a **single instanced uber-shader pass** with zero geometry tessellation and zero intermediate passes. + - **Text** uses a dual-path pipeline: crisp hinted grayscale/subpixel raster atlas (`R8Unorm`/`RGBA8Unorm`) for body/code text (`≤ 32 px` axis-aligned), switching seamlessly to **Eric Lengyel’s Slug algorithm** (dedicated to the public domain in March 2026, [EricLengyel/Slug](https://github.com/EricLengyel/Slug), and already proven in Makepad’s `draw_text.rs`) for zoomable canvas text, large headings, rotated/sheared labels, and monochrome vector icons. + - **Arbitrary vector paths** (charts, complex SVGs, strokes) use Linebender’s 2026 **`vello_gpu` Sparse Strips** pipeline (4×4 pixel blocks after SIMD CPU flattening) rather than heavyweight full-GPU compute `vello` or CPU triangle tessellation (`lyon`). +4. **Latency — Event-Driven Unthrottled Input Fast-Path + `CADisplayLink` Animation Pacing (< 6 ms p50 on 120 Hz ProMotion):** Waiting for a display link callback before processing input or acquiring a drawable adds 16–49 ms of pipeline lead (measured at 41.5 ms / 5 refreshes in windowed `CAMetalDisplayLink` on 120 Hz macOS). Rune decouples discrete input from `CADisplayLink`: keystrokes, clicks, and trackpad scrolls immediately wake the UI thread, update state, encode a <0.4 ms Metal pass into a `maximumDrawableCount = 2` ring, and present on the very next scanout (~4–8 ms input-to-photon on 120 Hz ProMotion), engaging `CADisplayLink` (`preferredFrameRateRange`) only while springs or timeline animations are in flight. + +--- + +## 2. Detailed Findings by Topic + +### Topic 1: Programming Language Evaluation (2026 Landscape) + +#### Comparative Matrix + +| Dimension | Rust (2024 Ed. / 1.86+) | Swift 6.3 / 6.4 | Zig 0.15 / 0.16-dev | C++23 / C++26 | Odin / Jai / Mojo | +| :--- | :--- | :--- | :--- | :--- | :--- | +| **Runtime Perf & Tail Latency** | **A+** (No GC, no pervasive ARC atomic traffic, SIMD via `wide`/`std::simd`) | **B+** (ARC retain/release traffic & existential boxing unless carefully annotated) | **A+** (Manual allocators, `@Vector` SIMD, zero hidden control flow) | **A+** (Zero-cost abstractions, mature intrinsics) | **A** (Odin/Jai manual memory; Mojo focused on AI kernels) | +| **Platform Reach (macOS, iOS, Win, Linux, Android, Web)** | **A+** (Tier-1 native everywhere + `wasm32-unknown-unknown` <1 MB) | **B** (macOS/iOS A+; Android SDK added in 6.3; Wasm 6.2+ still bulky; Linux/Win GUI immature) | **A** (Cross-compiles everywhere; mobile/Web bindings require manual C glue) | **A** (Everywhere via CMake/Emscripten, painful packaging) | **C** (Odin/Jai weak on iOS/Android/Web; Mojo has no GUI targets) | +| **UI Ecosystem (Text, Layout, A11y)** | **A+** (`taffy`, `parley`, `harfrust`, `fontations`, `swash`, `accesskit`, `kurbo`) | **C** (Apple-only `CoreText`/`NSAccessibility`; zero cross-platform equivalents) | **C** (Wraps C libraries: `harfbuzz`, `freetype`, `stb_truetype`; no `accesskit`) | **A-** (`HarfBuzz`, `Skia`, `DirectWrite`, `Yoga`, `ICU` — heavy C++ deps) | **D** (Must bind C libraries from scratch) | +| **Incremental Compile Speed** | **B** (0.8–2.5 s cold-ish crate rebuild; **<0.4 s** with `subsecond` ThinLink) | **B-** (Swift Build 6.4 fast for small modules, slow on heavy generics/macros) | **A+** on Linux x86_64 (<150 ms via `Elf2`); **C+** on macOS arm64 (Mach-O incremental WIP) | **C** (Header/module bloat; 2–10 s incremental link) | **A+** (Odin ~0.3 s; Jai <0.2 s full builds) | +| **Hot-Reload Friendliness** | **A-** (`subsecond` jump-table binary patching + dylib state preservation) | **A-** (`@_dynamicReplacement` + Mach-O `-bundle_loader`, ~100–300 ms on macOS) | **B+** (Clean C ABI `dlopen` state reload) | **B** (Live++ on Windows; fragile `dlopen` on macOS) | **A** (Odin/Jai trivial DLL reload) | +| **Agent-Writability (LLM Synthesis)** | **A+** (Exhaustive `rustc`/Clippy errors guide autonomous self-repair; huge corpus) | **B+** (Swift 6 strict concurrency region errors frequently trip LLMs) | **C+** (0.14→0.15→0.16 stdlib/build.zig churn causes stale LLM syntax) | **B** (Template SFINAE errors and UB escape compiler checks) | **D** (Small training corpus; Jai closed beta) | +| **Memory & Thread Safety** | **A+** (`Send`/`Sync` compile-time race freedom; `unsafe` quarantined to FFI) | **A** (Swift 6 data-race safety + ARC, but Reference Cycles leak) | **C** (Spatial checks in Debug, manual lifetime/thread discipline) | **D** (Use-after-free, iterator invalidation, data races) | **C** (Manual memory management) | + +#### Deep Dive on the Contenders + +1. **Rust’s Compile-Time & Hot-Reload Reality in 2026:** + - **Compiler & Linker Gains:** The [2025 Rust Compiler Performance Survey](https://blog.rust-lang.org/2025/09/10/rust-compiler-performance-survey-2025-results) identified single-crate incremental rebuilds and `cargo check`/`cargo build` cache splitting as top pain points. In 2026, enabling the parallel frontend (`-Zthreads=8`), `-Zshare-generics=y`, `-Cdebuginfo=line-tables-only`, and fast linkers (`ld_prime` on macOS, `mold` or incremental [`wild`](https://github.com/davidlattimore/wild) on Linux) cuts workspace incremental rebuilds by 30–45%. + - **Cranelift (`rustc_codegen_cranelift`):** Per the [February 2026 Rust Project Goal](https://goals.rust-lang.org/2026/improve-cg_clif-performance.html), on a 16-core machine building Zed incrementally, Cranelift is currently **12% faster than LLVM** with `-Cdebug-info=line-tables-only` (and 10–15% faster across the `rustc` benchmark suite), with an active 2026 roadmap for an in-memory machine-code caching daemon targeting a 2× backend speedup. + - **Subsecond (`subsecond` 0.7) Binary Hot-Patching:** Built by Dioxus ([`docs.rs/subsecond/0.7.10`](https://docs.rs/subsecond/0.7.10/subsecond/)), `subsecond` introduces **ThinLinking** (automatic dynamic linking of workspace dependencies + object-file diffing + runtime jump tables). When a developer or agent edits a UI view function, only the modified functions are recompiled into a tiny patch object and redirected via jump tables without restarting the process or losing app state, shrinking Rust incremental UI iteration to **< 500 ms** (typically 150–350 ms for leaf view edits). + - **Architecture Discipline for Compile Times:** GPUI’s slow compile times in Zed come primarily from monomorphizing massive view trees (`Div::child(impl IntoElement)`) and putting 100k+ LOC inside single monolithic crates. Keeping Rune’s element tree type-erased at container boundaries (`SmallVec<[AnyElement; 4]>`) and splitting widget crates cleanly keeps standard incremental `cargo build` under 1.2 s even without hot-patching. + +2. **Zig (0.15 / 0.16-dev in 2026):** + - Ghostty proved Zig + Metal + AppKit/SwiftUI (`libghostty`) can ship a wonderful macOS/Linux terminal. + - **Why Zig loses for Rune:** First, Zig’s flagship incremental compilation (`-fincremental` + in-place binary patching) works on `x86_64-linux` (`Elf2`), but on `aarch64-macos` (our primary target) the self-hosted `aarch64` backend and Mach-O incremental in-place linker remain incomplete in 2026 ([ziglang/zig#21165](https://github.com/ziglang/zig/issues/21165)). Second, Zig would force Rune to abandon the entire pure-Rust Linebender/AccessKit stack (`taffy`, `parley`, `harfrust`, `fontations`, `accesskit`) and revert to C FFI over `HarfBuzz`/`FreeType` plus writing a cross-platform accessibility tree from scratch. Third, LLMs routinely hallucinate Zig `build.zig` and `std.Io` APIs due to breaking changes between 0.13, 0.14, 0.15, and 0.16. + +3. **Swift (Swift 6.3 / 6.4 in 2026):** + - Swift has made real cross-platform strides: [Swift 6.3](https://www.swift.org/blog/swift-6.3-released/) shipped an official Android SDK, [Swift 6.4](https://www.swift.org/blog/) defaulted to the unified `Swift Build` engine, and `JavaScriptKit` optimized Wasm bridges. Kit’s own `hot-reload-kit` demonstrates 100–300 ms hot-reloading on macOS via `@_dynamicReplacement` and `-bundle_loader`. + - **Why Swift loses as core language (but wins as Apple host glue):** Outside Apple platforms, Swift has no cross-platform GUI/text/accessibility ecosystem; Wasm binaries carry heavy runtime weight unless restricted to Embedded Swift; and pervasive ARC reference counting across dense retained/immediate UI trees introduces atomic retain/release traffic and accidental closure reference cycles. However, using ~500 lines of Swift/Objective-C via `objc2` for macOS/iOS system integration (e.g., `NSGlassEffectView`, menu bars, `RPSystemBroadcastPickerView`, share sheets, as done in `launcher/native/LauncherView.swift`) is effortless and strongly recommended. + +4. **C++23/26, Odin, Jai, Mojo:** + - **C++** lacks memory safety, suffers from header/build fragmentation, and makes fearless multi-threaded UI state scheduling hazardous. + - **Odin** and **Jai** compile fast and excel at standalone games, but have near-zero accessibility, international text shaping, or mobile/web platform infrastructure, and tiny LLM training corpora. + - **Mojo** is specialized for heterogeneous AI/tensor compute and has no desktop/mobile windowing or UI ecosystem. + +--- + +### Topic 2: GPU API & Compositor Integration + +#### The Contenders Analyzed + +1. **Raw Metal (`objc2-metal`) on macOS & iOS:** + - **Evidence from GPUI, Scrawl, and Makepad:** + - GPUI’s original macOS renderer (`kitlangton/gpui/src/platform/mac/metal_renderer.rs:1-850`) is **850 lines of Rust**. + - Kit’s production recording pill renderer in Scrawl (`scrawl/src/native/pill/mod.rs:1-420` + `pill.metal:1-369`) is **~790 lines total**, directly driving a 3-pass separable Gaussian blur + SDF capsule pipeline on a `CAMetalLayer` over an `NSGlassEffectView`. + - Makepad’s direct Metal backend (`makepad/platform/src/os/apple/metal.rs:1-1100`) gives direct `IOSurface` cross-process texture sharing and exact `MTLCommandBuffer` GPU start/end timestamps (`GPUStartTime`/`GPUEndTime`, lines 318–326). + - **Capabilities `wgpu` hides or complicates on Apple:** + - **Programmable Framebuffer Fetch / Tile Memory (`[[color(0)]]`, `[[imageblock_data]]`, `[[raster_order_group(0)]]`)**: Apple Silicon is a Tile-Based Deferred Renderer (TBDR). Rive’s Metal shaders (`rive-runtime/renderer/src/shaders/metal.glsl:301-450`) read and write 4 pixel-local planes (`colorBuffer`, `clipBuffer`, `scratchColorBuffer`, `coverageCountBuffer`) directly in on-chip tile SRAM (`[[color(IDX)]]`) at zero system memory bandwidth cost. `wgpu` does not expose multi-plane tile memory / programmable blending on Metal. + - **Zero-Copy Video & Camera (`CVMetalTextureCache` / `IOSurface`)**: GPUI’s `surface_fragment` (`shaders.metal:874-890`) samples bi-planar `Y` (`R8Unorm`) and `CbCr` (`RG8Unorm`) `IOSurface` planes directly from `CVPixelBuffer` hardware decoders without CPU/GPU copies. + - **Live Resize Synchronization (`presentsWithTransaction`)**: Both GPUI (`zed/crates/gpui_macos/src/window.rs:3202,3328`) and Scrawl (`scrawl/src/native/pill/mod.rs:403-417`) toggle `layer.setPresentsWithTransaction(true)` inside `CATransaction` during window resize/frame changes so Metal content never lags behind the window border. + - **Precompiled `.metallib` Instant Startup**: `xcrun metal` compiles `.metal` at `build.rs` time into a binary `.metallib`. `newLibraryWithData` loads in **< 0.5 ms** at startup, versus 15–60 ms for runtime WGSL→Naga→MSL string translation + `newLibraryWithSource`. + +2. **`wgpu` (v28+ in 2026) vs `blade-graphics`:** + - Historically, `wgpu` had heavy state-tracking and validation overhead, prompting Zed to adopt Kvark’s lighter `blade-graphics` for Linux/Windows. + - **Crucial 2026 Update:** In February 2026, Zed merged [PR #46758 ("Migrate from blade-graphics to wgpu")](https://github.com/zed-industries/zed/pull/46758) (`zed/crates/gpui_wgpu/src/wgpu_renderer.rs`). Benchmarks in that PR showed **`wgpu` reduced median CPU draw time from 301.29 µs to 235.67 µs (-21.8%)** compared to `blade-graphics`, while adding `wgpu::Features::DUAL_SOURCE_BLENDING` for subpixel text AA (`wgpu_renderer.rs:781-795`), pipeline disk caching (`PipelineCache`), Vulkan/Wayland stability fixes, and a WebGPU/WebGL2 target. + - **Tradeoffs:** `wgpu` + `naga` adds ~2.5–3.8 MB to stripped binary size and translates WGSL to backend shaders. That is an unacceptable tax on Apple-specific capabilities if used as the *only* backend on macOS/iOS, but an **overwhelming win** for Linux (Vulkan), Windows (D3D12/Vulkan), Android, and Web (WebGPU). + +3. **SDL3 `SDL_gpu`, Google `Dawn`, and Flutter `Impeller`:** + - **`SDL_gpu` (shipped in SDL 3.2+):** Clean C API, ~400 KB binary footprint, good for games, but lacks `wgpu`’s Rust safety, storage buffer ergonomics, dual-source blending portable setup, and WebGPU browser integration. + - **Dawn:** Powers Chromium’s WebGPU; C++ build (CMake/GN + `tint` + `spirv-tools`) adds 8–15 MB to binaries and heavy C++ build times. + - **Flutter Impeller:** Proves the value of **100% AOT-compiled shaders** (`impellerc`) to eliminate runtime PSO compilation hitching—a lesson Rune must steal via build-time `.metallib` / SPIR-V / DXIL / WGSL validation. + +4. **Hybrid Core Animation (`CALayer` Tree + Custom Metal) vs Pure Single-Drawable:** + - **How macOS/iOS actually works:** The WindowServer compositor is already a hardware-accelerated `CALayer` tree evaluator with direct display-controller scanout planes. + - **What `CALayer` does better than custom shaders:** + - **System Materials & Liquid Glass (`NSGlassEffectView` / `NSVisualEffectView`):** Private WindowServer backdrop filters blur and refract windows *behind* the app at zero app-GPU cost. Both Zed (`gpui_macos/src/window.rs:301,3810`) and Scrawl (`scrawl/src/native/pill/mod.rs:348-380`) place an `NSVisualEffectView` / `NSGlassEffectView` behind a transparent `CAMetalLayer`. + - **Out-of-process HDR Video & WebViews (`AVSampleBufferDisplayLayer`, `WKWebView`):** Composited directly by WindowServer hardware planes without waking the UI render pass. + - **What `CALayer` does poorly (Avoid 1-Layer-Per-Widget):** Allocating hundreds of `CALayer`s for normal buttons/rows causes Core Animation IPC serialization overhead, layout-to-GPU desynchronization, and breaks cross-platform behavior. + - **The Sweet Spot ("Shallow Compositor Host"):** 1 root `NSGlassEffectView`/`NSVisualEffectView` + 1 primary `CAMetalLayer` for all 2D UI + optional sibling native `CALayer`s only for hardware video/camera/WebView cutouts. + +--- + +### Topic 3: 2D UI Renderer Design + +#### 3.1 Instanced SDF Primitives & Analytic Surface Shading +- **GPUI’s Baseline (`kitlangton/gpui/src/platform/mac/shaders.metal:102-545`):** + - Draws `Shadow`, `Quad`, and `Underline` as instanced 4-vertex unit quads reading per-instance structs from storage/constant buffers (`[[buffer(QuadInputIndex_Quads)]]`). + - `quad_fragment` evaluates an exact outer rounded-box SDF (`quad_sdf_impl`, line 1065) and an inner border SDF (`quarter_ellipse_sdf`, line 440) that handles non-uniform border widths (`top != left`), plus perimeter-parameterized dashed borders (`dash_alpha`, line 421). + - **Limitation in GPUI:** Because `Shadow`, `Quad`, and `Border` are separate primitive batches in `scene.rs` (`zed/crates/gpui/src/scene.rs:88-115`), a button with a drop shadow, background fill, inner highlight, and border emits multiple draw instances or requires batch-breaking z-order sorts. +- **Makepad’s Analytic `Material` Breakthrough (`makepad/draw/src/shader/surface.rs:27-165`):** + - Evaluates **bevel profile & normal (`m_normal`)**, **wrapped Lambert diffuse + Blinn-Phong specular (`m_lit`)**, **edge ambient occlusion (`m_ao`)**, **rim lighting (`m_rim`)**, **sky-box gloss (`m_gloss`)**, and **4-sample `erf` Gaussian inner/outer shadow (`box_cov`)** purely as a function of the signed distance `d` inside a *single* fragment pass! +- **Analytic Drop & Inner Shadows:** + - Both GPUI (`shaders.metal:525-542,1087-1104`) and Makepad (`sdf.rs:10-76`) use Evan Wallace’s separable formulation: exact closed-form 1D Gaussian integral along X via a polynomial `erf()` approximation (`blur_along_x`), integrated across Y with a 4-step midpoint quadrature clamped to `[-3σ, +3σ]`. + - **Crucial detail to steal from GPUI (`shaders.metal:541,1170-1177`):** 8-bit `BGRA8Unorm` framebuffers visibly band in the `[0.0, 0.02]` alpha tail of soft shadows and Oklab gradients. GPUI adds **Jimenez Interleaved Gradient Noise (IGN) with a 2-tap triangular PDF (`±1/255` amplitude)** modulated by `smoothstep(0.0, 0.02, alpha) * smoothstep(1.0, 0.98, alpha)`, completely eliminating shadow and gradient mach banding at 3 ALU instructions per pixel. +- **Rune’s Uber-Primitive Upgrade:** + - Combine Rounded/Squircle (G2 continuous $L^p$ superellipse option) Box + Border + Inner Shadow/Bevel/Rim + Outer Shadow into a single 128-byte `UberQuad` instance struct so an entire styled card renders in **1 instance** with **1 SDF evaluation**. + +#### 3.2 Vector Paths & Curves: The 2026 Showdown + +| Technique | Representative Engine | How It Works | CPU Cost | GPU Cost & Memory | Verdict for Rune | +| :--- | :--- | :--- | :--- | :--- | :--- | +| **CPU Triangle Tessellation** | `lyon`, Iced fallback, GPUI legacy | Ear-clipping / sweep-line on CPU → indexed triangles | **High** (0.5–4 ms for complex paths; poor for animated morphs) | Low fragment, high vertex count, requires 4× MSAA | **Avoid** (CPU bottleneck on dynamic vector UI) | +| **Loop-Blinn + 4× MSAA Intermediate** | GPUI (`shaders.metal:737-838`) | CPU triangulates hull; fragment shader solves $u^2 - v$ into full-viewport 4× MSAA texture, then blits | Medium (CPU earcut hull) | **High** (allocates full-window 4× MSAA texture + resolve + blit pass) | **Avoid** (Massive memory & bandwidth waste for small icons) | +| **Full Compute Pipeline** | `vello` (classic compute) | 9+ compute stages (pathtag, bbox, flatten, bin, tile, backdrop, coarse, fine) | Very Low | **High baseline** (~0.4–0.8 ms dispatch overhead even for 1 path; complex shaders) | **Avoid** (Linebender moved it to `research/` in 2026) | +| **Sparse Strips (Hybrid CPU+GPU)** | `vello_gpu` / `vello_hybrid` (`vello/ARCHITECTURE.md`) | SIMD CPU flattening + tiling into 4×4 pixel alpha strips; simple instanced GPU raster pass | Low (~50–200 µs via NEON/AVX) | **Very Low** (Simple vertex/fragment shader, zero compute dispatch overhead) | **Steal for general vector art / charts / complex SVGs** | +| **Direct GPU Quadratic Bézier Winding** | **Slug** ([EricLengyel/Slug](https://github.com/EricLengyel/Slug), `makepad/.../draw_text.rs:42-350`) | Curves stored once in `curve_texture` + horizontal/vertical `band_texture`; fragment shader raycasts exact roots | **Zero per frame** (static em-space upload once per glyph/icon) | **Low** (Exact analytical AA at any scale/rotation/perspective; zero atlas invalidation) | **Steal for large/transformed text & vector icons!** | +| **PLS / Atomic Analytical Coverage** | Rive (`draw_raster_order_path.frag`) | Cubic tessellation in vertex shader + exact winding accumulation in tile memory (`[[color(n)]]`) | Low | Ultra-fast for 10,000-path animations; requires tile-memory/ROV shader variants | Optional plugin for embedded `.riv` files | + +- **Why the March 2026 Slug Public-Domain Dedication Changes Everything:** + - On March 17, 2026, Eric Lengyel dedicated US Patent `#10,373,352` (Slug GPU Bézier rendering) to the public domain ([`github.com/EricLengyel/Slug`](https://github.com/EricLengyel/Slug)). + - Makepad immediately integrated Slug in `makepad/draw/src/text/slug_atlas.rs:1-200` and `draw_text.rs:41-350`. + - In Slug, a glyph or SVG icon’s quadratic Bézier curves (cubics split once via `CUBIC_TO_QUAD_TOLERANCE = 0.05`) are uploaded **once** in em-space into an append-only `RGBA32F`/`RGBA16F` `curve_texture` and indexed into horizontal and vertical spatial bands (`band_texture`). The vertex shader dilates the bounding quad by 0.5 px in screen space (`slug_dilate`), and the fragment shader scans only the curves intersecting the pixel’s horizontal/vertical band (`scan_horizontal_list`, `scan_vertical_list`), using Lengyel’s bit-shift root eligibility code `(u32(11892) >> shift) & u32(257)` (`draw_text.rs:237`) to avoid numerical edge dropouts. + - **Result:** Infinite zoom, rotation, 3D perspective, and scale animations on text and UI icons with **zero CPU re-rasterization and zero glyph-atlas thrashing**. + +#### 3.3 Text Rendering: Hybrid Raster Atlas + Slug +- **Why not Slug for *all* text?** At body sizes (`11–18 px` on 2× Retina = `22–36` device px), an `R8Unorm` texture sample costs 1 texture fetch (~2 GPU cycles) and preserves platform-specific stem darkening / optical hinting (`CoreText` on macOS, `DirectWrite` on Windows, `fontations`+`swash` autohinting on Linux). Slug requires 4–10 texel fetches + quadratic root math per pixel. +- **Subpixel vs Grayscale AA on Retina (2026):** + - On macOS, Apple removed subpixel LCD layout from CoreGraphics in Mojave, and all modern Macs/iPhones ship ≥2× Retina panels (many OLED or mini-LED with non-RGB-stripe subpixel layouts on iPad Pro M4 / iPhone). However, CoreText still applies **font smoothing / stem darkening** (`CGContextSetAllowsFontSmoothing`). + - As proven in `scrawl/src/native/pill/atlas.rs:133-201`, rasterizing glyphs with CoreText into an `R8Unorm` shelf-packed atlas (with 2×2 subpixel bin positioning for fractional X offsets) uses 4× less VRAM than `RGBA8` and blends in a single pass. + - For Windows/Linux 1× external monitors, `wgpu::Features::DUAL_SOURCE_BLENDING` (as implemented in `zed/crates/gpui_wgpu/src/wgpu_renderer.rs:781-795`) enables proper per-channel RGB subpixel alpha blending in a single draw call. +- **Rune’s Hybrid Text Rule:** + - **Axis-aligned text `≤ 32 pt` with static scale:** Shelf-packed `R8Unorm` (macOS/iOS Retina) or `RGBA8` dual-source subpixel (1× Windows/Linux) glyph atlas, keyed by `(FontId, GlyphId, FontSizeFixed, SubpixelBinX)`. + - **Text `> 32 pt`, any rotated/skewed/3D-transformed text, or text undergoing continuous zoom/scale animation:** Rendered directly via **Slug** (`SlugAtlas`), eliminating the infamous "blurry scaled atlas" or "100 MB atlas eviction storm during pinch-to-zoom". + +#### 3.4 Blur, Backdrop Filters & Peak-Alpha Legibility +- **Window-Level Backdrop Blur (Zero App GPU Cost):** Delegated to `NSGlassEffectView` (macOS 26+) / `NSVisualEffectView` (macOS 14–15) / `UIVisualEffectView` (iOS) / `DwmEnableBlurBehindWindow` / `Mica` (Windows). +- **In-App Element Backdrop Blur (`backdrop-filter: blur()`):** + - **Dual Kawase Pyramid** for large radii (`σ > 6 px`): Downsample 2× per pass (4-tap bilinear offset `(±1, ±1)`) for $N$ levels (typically 2–3 levels down to 1/4 or 1/8 resolution), then upsample 2× per pass (8-tap tent filter) restricted strictly to the dirty/clipped bounding rect of the blurring element. At 1/4 resolution, blurring a 400×300 popover takes **< 60 µs** on Apple M-series GPUs. + - **Separable 1D Gaussian + Peak-Alpha Boost** for animated morphs & small blurs (`σ ≤ 6 px`): Steal directly from Kit’s `scrawl/src/native/pill/pill.metal:208-360`. When blurring UI elements (like morphing pill labels or crossfading icons), standard Gaussian blur reduces peak alpha and makes text look washed out. Scrawl’s `composite_fragment` (`pill.metal:326-349`) computes `boost = 1.0 + smoothstep(0.0, 0.35, b) * 2.5` and `pow(a, 1.0 / boost)`, keeping blurred text crisp and luminous throughout the transition. + +#### 3.5 Cheap Soft-Edge Gradient Masks at Every Clip Edge +- **The Problem:** Traditional UI engines clip scroll views and containers using either hardware `glScissor`/`setScissorRect` (hard pixel edge, axis-aligned only), hardware `[[clip_distance]]` planes (GPUI `shaders.metal:56,80`, hard edge), or an offscreen mask texture (expensive render pass switch). When content scrolls under a header or a pill morphs width, hard clips look abrupt; developers want a 6–16 px soft alpha fade at the top/bottom/left/right clip edge without allocating an offscreen layer. +- **The Zero-Pass Solution (Analytic Soft-Clip Mask + Room Gating):** + 1. **Per-Fragment Analytic Rounded-Clip & 4-Edge Feather:** Every draw instance carries a `clip_index: u32` indexing into a compact `ClipStackBuffer` on the GPU. Each `ClipNode` (32 bytes) stores: + - `bounds: float4` (`origin.xy, size.zw`) + - `corner_radii: float4` (`tl, tr, br, bl`) + - `edge_feather: half4` (`top, right, bottom, left` feather distances in scaled pixels; `0.0` = crisp 1px antialiased SDF clip; `> 0.0` = smooth gradient mask fade over `edge_feather` px!). + In the fragment shader, evaluating the clip costs ~8 ALU instructions: + ```metal + // Signed distance to the rounded clip rect (negative inside, positive outside) + float clip_sdf = quad_sdf(frag_pos, clip.bounds, clip.corner_radii); + float hard_aa = saturate(0.5 - clip_sdf); + // Directional 4-edge soft gradient fade inside the clip rect + float4 dist_to_edges = float4( + frag_pos.y - clip.bounds.origin.y, // top + (clip.bounds.origin.x + clip.bounds.size.x) - frag_pos.x, // right + (clip.bounds.origin.y + clip.bounds.size.y) - frag_pos.y, // bottom + frag_pos.x - clip.bounds.origin.x // left + ); + float4 edge_alpha = saturate(dist_to_edges / max(float4(clip.edge_feather), float4(1e-4))); + // Hermite smoothstep across each feathered edge + edge_alpha = edge_alpha * edge_alpha * (3.0 - 2.0 * edge_alpha); + float clip_mask = hard_aa * edge_alpha.x * edge_alpha.y * edge_alpha.z * edge_alpha.w; + color *= clip_mask; // Premultiplied alpha modulation + ``` + 2. **Per-Element SDF Room Gating (Steal from `scrawl/src/native/pill/model.rs:146-184`):** When an item sits inside a morphing container (e.g., a pill or collapsing sidebar), evaluating `box_clearance` (the container’s analytic SDF clearance around the child’s bounding box) on the CPU or vertex shader produces a continuous `presence = smoothstep((room + feather) / feather)` multiplier that drives both opacity and subtle scale/blur before the child ever touches the border. + 3. **Result:** Every scroll view, overflow container, rounded card, and morphing pill gets arbitrary rounded-corner clipping **and** independent top/right/bottom/left soft gradient fade masks with **zero offscreen textures, zero stencil buffers, and zero render-pass breaks**. + +#### 3.6 Layers, Offscreen Caching & Group Opacity +- **When Offscreen Passes Are Needed:** Only for (a) true group opacity (`0.0 < opacity < 1.0` on a container with *overlapping* children, where per-element alpha would show internal seams), (b) container-wide `backdrop-filter` / `filter: blur()`, or (c) explicitly cached complex subtrees (`will_change` / `cache_layer`). +- **Tile-Local Group Opacity Shortcut on Apple Silicon:** When a group with `opacity < 1.0` fits within a single pass and does not require blur, Metal programmable blending (`[[color(0)]]` scratch plane in tile memory, like Rive’s `scratchColorBuffer` in `draw_raster_order_path.frag:10`) can composite the group in on-chip tile memory and blend it onto the main color plane without ever allocating or bandwidth-flushing an offscreen texture! +- **Transient Texture Pool:** For effects that do cross pixel neighborhoods (blur), maintain a power-of-two / bucketed `MTLTexture` / `wgpu::Texture` pool with frame-age eviction (evict after 120 idle frames). + +#### 3.7 Damage Tracking, Partial Present & 120 Hz Power Cost +- **The 120 Hz Power Reality:** + - Running a full-window 4K/5K Metal render pass at 120 Hz consumes 4–9 W of package power even if only a 2×18 px text cursor is blinking. + - At complete rest (zero dirty views, zero active springs), Rune **must draw 0 frames/sec** (0% CPU, 0% GPU). +- **Partial Present & Damage Tracking on Metal vs D3D12/Vulkan:** + - Metal’s `CAMetalLayer` does **not** expose an equivalent to `EGL_KHR_swap_buffers_with_damage` or `IDXGISwapChain1::Present1(DirtyRects)`—when you present a `CAMetalDrawable`, WindowServer treats the drawable as a full surface, and because `nextDrawable` cycles through a ring of 2–3 buffers (`maximumDrawableCount`), rendering only a dirty scissor rect directly into `nextDrawable()` leaves stale content from 2–3 frames ago outside the scissor rect! + - **How to Make Damage Tracking Actually Work on Metal:** + 1. **Persistent Backing Texture + Scissored Dirty Render:** Render the UI scene into a single persistent `MTLTexture` (`StorageModePrivate`, `BGRA8Unorm` / `RGBA16Float`) using `MTLLoadActionLoad` and `setScissorRect(dirty_bbox)` so Apple Silicon’s TBDR GPU only shades tiles overlapping `dirty_bbox`. Then encode a single hardware blit (`MTLBlitCommandEncoder::copyFromTexture`) or scissored copy into the `CAMetalDrawable`. On Apple Silicon unified memory, a tile-aligned blit of a 5K buffer takes ~80 µs while saving 95%+ of fragment shader execution on partial updates (like typing or cursor blink). + 2. **ProMotion Dynamic Frame Rate Scaling (`preferredFrameRateRange`):** Use `CADisplayLink`’s `CAFrameRateRangeMake(min, max, preferred)` ([Apple ProMotion Docs](https://developer.apple.com/documentation/quartzcore/optimizing-iphone-and-ipad-apps-to-support-promotion-displays)): + - Interactive scroll, drag, or fast spring velocity: `CAFrameRateRangeMake(80, 120, 120)` (8.33 ms). + - Settling spring tail (`velocity < threshold`) or subtle spinner/pulse: `CAFrameRateRangeMake(30, 60, 60)` or `24–48 Hz`. + - Cursor blink / static timer: **Display link paused**, scheduled via timer only on blink transitions. + +#### 3.8 Wide Color (Display P3), EDR/HDR, Linear Blending & Dithering +- **Color Pipeline:** + - Authoring colors in sRGB, Display P3, or **Oklab / Oklch** (perceptually uniform lightness/chroma). + - Gradients interpolate in **Oklab** (like GPUI `shaders.metal:950-988,1225`) or linear Display P3, with Jimenez IGN triangular dithering (`±1/255`). + - **Surface Format:** Default `MTLPixelFormatBGRA8Unorm` with `CGColorSpaceCreateWithName(kCGColorSpaceDisplayP3)` on wide-gamut displays (50% less memory bandwidth than `RGBA16Float`), upgrading dynamically to `MTLPixelFormatRGBA16Float` with `wantsExtendedDynamicRangeContent = YES` only when an HDR/EDR surface or specular HDR highlight (> 1.0 headroom) is mounted in the scene. + +--- + +### Topic 4: Input-to-Photon Latency Architecture + +#### 4.1 Real-World Latency Measurements (macOS & iOS, 2025–2026) + +| System / Benchmark | Display Rate | Measured Input-to-Photon (p50 / p99) | Architectural Cause | +| :--- | :--- | :--- | :--- | +| **Hardware + OS Compositor Floor** (Windowed macOS ProMotion) | 120 Hz (8.33 ms) | **~4.2–8.5 ms** | USB/SPI keyboard scan (~1 ms) + AppKit event delivery (~0.5 ms) + GPU render (<0.5 ms) + WindowServer next scanout (0–8.33 ms) | +| **Blackbird Terminal** ([`vtebench-2026-04-20.md`](https://github.com/conjfrnk/blackbird/blob/main/docs/benchmarks/vtebench-2026-04-20.md)) | 120 Hz ProMotion | **p50 ≤ 6 ms, p99 ≤ 20 ms** (CI-gated) | Direct event-triggered render without waiting for display-link lead | +| **Alacritty 0.17** ([`komsit37/ghostty-input-latency`](https://github.com/komsit37/ghostty-input-latency), Jul 2026) | 60 Hz (16.67 ms) | **p50 17.9 ms** (~4 ms above 14 ms capture floor) | Immediate redraw on PTY/key event; `maximumDrawableCount = 2` | +| **Ghostty 1.3.2** ([`komsit37/ghostty-input-latency`](https://github.com/komsit37/ghostty-input-latency), Jul 2026) | 60 Hz (16.67 ms) | **p50 58.6 ms** (~40 ms slower than Alacritty) | Queued frame scheduling / multi-refresh display-link pipeline lead | +| **`CAMetalDisplayLink` Windowed** ([`rrva/metal-display-link-pacing`](https://github.com/rrva/metal-display-link-pacing), 2026) | 60 Hz / 120 Hz | **66.5 ms (60 Hz) / 41.5 ms (120 Hz)** callback → screen | Windowed `CAMetalDisplayLink` targets **3 refreshes (49.8 ms at 60 Hz)** or **5 refreshes (41.5 ms at 120 Hz)** ahead of its callback! | +| **Zed (`gpui_macos`)** | 120 Hz ProMotion | **~12–20 ms** | `CVDisplayLink` io-thread → GCD `DispatchSource` → main thread `step()` (`display_link.rs:122-160`), adds 1 refresh vs direct input draw | + +#### 4.2 Why `CAMetalDisplayLink` and `CVDisplayLink` Add Latency if Misused +1. **The `CAMetalDisplayLink` Trap:** Apple introduced `CAMetalDisplayLink` in macOS 14 / iOS 17 with `preferredFrameLatency` (accepting only `1.0` or `2.0`). However, Apple’s documentation notes: *"The final latency may be bigger if the system needs more time, such as for windowed modes on macOS."* Independent 2026 empirical measurements ([`rrva/metal-display-link-pacing`](https://github.com/rrva/metal-display-link-pacing)) prove that in **windowed mode on macOS**, `CAMetalDisplayLink` schedules its callback **5 refreshes (41.5 ms) ahead of scanout on 120 Hz panels** and **3 refreshes (49.8 ms) ahead on 60 Hz panels**. That guarantees smooth 120 fps throughput for heavy 3D games, but adds **33–50 ms of input lag** to a UI framework if input waits for `CAMetalDisplayLinkUpdate`! +2. **The `CVDisplayLink` Trap:** As documented in Zed’s `zed/crates/gpui_macos/src/display_link.rs:1-52`, `CVDisplayLink` runs on a separate high-priority CoreVideo I/O thread, has broken teardown semantics (`CVDisplayLinkStop` races with in-flight callbacks, causing segfaults in `CVHWTime::reset`), lacks `preferredFrameRateRange` for ProMotion power saving, and requires cross-thread signaling (`dispatch_source_merge_data`) to wake the main runloop. + +#### 4.3 Rune’s Zero-Wait Input-to-Photon Pipeline (< 6 ms p50 on 120 Hz) +To achieve sub-frame (~4–6 ms p50) input-to-photon latency while maintaining butter-smooth 120 Hz animations: +1. **Two Distinct Frame Triggers (Input-Immediate vs DisplayLink-Paced):** + - **Path A — Discrete Input Fast-Path (KeyDown, MouseDown, Trackpad Scroll phase, Direct Manipulation):** When `NSEvent` / `UIEvent` arrives on the main runloop and no frame has been presented in the current VSync interval (`now - last_present_time > 0.75 * refresh_period`), **do not wait for the next `CADisplayLink` tick**. Coalesce any pending events currently in the runloop queue, run incremental layout/paint (< 0.4 ms), acquire `layer.nextDrawable()`, encode and `commit()` immediately. Because a UI render pass takes ~0.2–0.4 ms on Apple Silicon, the drawable finishes rendering well before the compositor’s next VSync deadline and scans out on the **immediately upcoming refresh** (0–8.33 ms away, **p50 ~4.8 ms**). + - **Path B — Continuous Animation Pacing (`CADisplayLink` on Main `NSRunLoop`):** When springs, physics scroll momentum, or shaders are actively animating, `CADisplayLink` (macOS 14+ / iOS) drives frame ticks on `NSRunLoopCommonModes` using `targetTimestamp` to step analytical springs (`model.rs` exact closed-form `spring(duration, bounce)`) to the exact display presentation time, eliminating dt-jitter. +2. **Double Buffering (`maximumDrawableCount = 2`) with Completion Pacing:** + - Triple buffering (`maximumDrawableCount = 3`) allows the CPU to run 2 full frames ahead of the display, adding 8.3–16.6 ms of latency during continuous trackpad dragging. + - Set `CAMetalLayer.maximumDrawableCount = 2` (or bound in-flight frames to 1 via an `MTLSharedEvent` / `dispatch_semaphore_t` signaled in `commandBuffer.addCompletedHandler`), ensuring `nextDrawable()` never queues stale frames. +3. **Live Window Resize Without Jitter (`presentsWithTransaction`):** + - Keep `presentsWithTransaction = false` during normal operation (so asynchronous commits never block the main thread). + - Inside `setFrameSize:` / `displayLayer:` (`zed/crates/gpui_macos/src/window.rs:3327-3340`, `scrawl/src/native/pill/mod.rs:403-417`), temporarily set `presentsWithTransaction = true`, call `commandBuffer.commit()`, `commandBuffer.waitUntilScheduled()`, and `drawable.present()`, then restore `presentsWithTransaction = false`. + +--- + +## 3. What to Steal vs. What to Avoid + +### What to Steal +1. **Zed (`gpui_macos` & `gpui_wgpu`):** + - **Oklab gradient interpolation + Jimenez IGN 2-tap triangular dithering** (`±1/255`) in `kitlangton/gpui/src/platform/mac/shaders.metal:950-988,1170-1177` to eliminate 8-bit banding in shadows and gradients. + - **Quarter-ellipse inner border SDF** and **perimeter-parameterized dashed borders** (`shaders.metal:194-449`). + - **`wgpu` backend architecture for Linux/Windows/Web** with storage buffers + dual-source subpixel blending (`zed/crates/gpui_wgpu/src/wgpu_renderer.rs:781-795`). + - **Zero-copy bi-planar `Y`/`CbCr` `IOSurface` video rendering** (`surface_fragment` in `shaders.metal:874-890`). +2. **Kit’s Scrawl (`scrawl/src/native/pill/`):** + - **Peak-alpha boost during Gaussian blur** (`boost = 1.0 + smoothstep(0.0, 0.35, b) * 2.5`, `scrawl/src/native/pill/pill.metal:326-349`) so morphing/blurring text stays crisp and legible. + - **Analytic SDF `box_clearance` room gating** (`scrawl/src/native/pill/model.rs:146-184`) to smoothly fade/scale child elements as container bounds morph. + - **Hybrid `NSGlassEffectView` + `CAMetalLayer` host** (`scrawl/src/native/pill/mod.rs:348-380`). +3. **Makepad (`makepad/draw/src/shader/`):** + - **Public-domain Slug GPU Bézier text & icon renderer** (`makepad/draw/src/shader/draw_text.rs:41-350` and `slug_atlas.rs:1-200`). + - **Single-pass analytic SDF `Material` shading** (bevel, wrapped Lambert diffuse, Blinn-Phong specular, rim light, inner shadow coverage, `makepad/draw/src/shader/surface.rs:27-165`). +4. **Linebender (`vello_gpu` / `parley` / `harfrust` / `fontations`):** + - **Sparse Strips (`vello_gpu`)** 4×4 pixel alpha tile strips (`vello/vello_gpu/src/render/wgpu/mod.rs`) for complex multi-contour vector paths and strokes. +5. **Rive (`rive-runtime/renderer/src/shaders/`):** + - **Apple Silicon programmable framebuffer fetch (`[[color(IDX)]]`)** (`rive-runtime/renderer/src/shaders/metal.glsl:396-450`) for zero-bandwidth tile-local group opacity and blending. +6. **Dioxus (`subsecond`):** + - **ThinLink + jump-table hot-patching** ([`docs.rs/subsecond`](https://docs.rs/subsecond/0.7.10/subsecond/)) for <400 ms stateful Rust UI hot-reloading. + +### What to Avoid +1. **Avoid GPUI’s 4× MSAA Full-Window Intermediate Texture for Paths** (`kitlangton/gpui/src/platform/mac/metal_renderer.rs:195-235`): Allocating a full-window 4× MSAA texture and running a separate resolve + sprite-blit pass just to draw a few SVG icons wastes tens of megabytes of VRAM and breaks batching. Use **Slug** for icons/curves and **`vello_gpu` Sparse Strips** for complex vector art. +2. **Avoid `CVDisplayLink` on macOS 14+** (`zed/crates/gpui_macos/src/display_link.rs:1-52`): Deprecated, lacks ProMotion `preferredFrameRateRange`, and has unsafe thread teardown races. Use `CADisplayLink` on the main `NSRunLoop` combined with an immediate input-triggered draw fast-path. +3. **Avoid Windowed `CAMetalDisplayLink` for Latency-Critical Input**: Its 3–5 refresh lead (41–50 ms on macOS windowed mode) makes typing and dragging feel sluggish. +4. **Avoid Full Compute `vello`**: Moved to `research/` by Linebender in 2026 because its 9-stage compute pipeline has too high a baseline dispatch cost for low-latency 120 Hz UI frames. +5. **Avoid Maintaining Custom Vulkan & D3D12 Backends (`blade-graphics` / `gpui_windows`)**: Zed’s 2026 migration to `wgpu` proved that `wgpu` is faster on Linux/Windows while saving thousands of lines of driver-workaround code. + +--- + +## 4. Decisive Recommendation & Renderer Architecture Sketch + +### Decisive Stack Choice +- **Core Language:** **Rust (2024 Edition)** with thin `objc2` / Swift 6 host shims on Apple platforms and `subsecond` jump-table hot-patching in dev builds. +- **GPU Layer (`rune-gpu`):** A ~400-line internal trait (`GpuDevice`, `RenderPass`, `BufferSlice`, `TextureHandle`) with **two backends**: + 1. **`rune-metal` (macOS & iOS):** Direct `objc2-metal` (~1,600 LOC) with build-time `.metallib`, `IOSurface` zero-copy textures, programmable framebuffer fetch (`[[color(0..1)]]`), and `CAMetalLayer` + `NSGlassEffectView` host integration. + 2. **`rune-wgpu` (Linux, Windows, Android, WebGPU):** `wgpu` 28+ (~1,200 LOC) sharing the exact same scene buffer layout. + +### Threading & Latency Architecture + +``` +┌─────────────────────────────────────────────────────────────────────────┐ +│ MAIN / UI THREAD (NSRunLoop / UIEventLoop) │ +│ 1. Input Fast-Path (NSEvent/UIEvent) OR CADisplayLink(targetTimestamp) │ +│ 2. Step analytical springs (exact closed-form at targetTimestamp) │ +│ 3. Reactive view diff -> Taffy incremental layout -> SceneBuilder │ +│ 4. Pack flat GPU instance buffers (UberQuad, GlyphRun, Slug, Strip) │ +└───────────────────────────────┬─────────────────────────────────────────┘ + │ Lock-free triple-buffered SceneArena + ▼ +┌─────────────────────────────────────────────────────────────────────────┐ +│ GPU SUBMISSION (Inline on Main Thread <250 µs, or Dedicated Render Q) │ +│ • Acquire persistent backing texture + dirty scissor bbox │ +│ • Upload dirty glyph/Slug/strip pages via UMA mapped ring buffer │ +│ • Encode RenderPass -> Blit to CAMetalDrawable -> commit() │ +└─────────────────────────────────────────────────────────────────────────┘ + ▲ +┌───────────────────────────────┴─────────────────────────────────────────┐ +│ BACKGROUND WORKER POOL (Rayon / Async Executor) │ +│ • Async image decoding -> staging ring buffer │ +│ • Large text paragraph shaping (Parley + HarfRust) │ +│ • Heavy SVG / chart flattening into vello_gpu Sparse Strips │ +└─────────────────────────────────────────────────────────────────────────┘ +``` + +### Frame Graph (Typical Frame = 1 Render Pass + 1 Scissored Blit) + +``` +[Pass 0: Atlas Upload (Blit Encoder, only when new glyphs/icons/strips added)] + └── Append dirty R8/RGBA8 glyph tiles, Slug curve/band texels, or Sparse Strip alphas + +[Pass 1: Backdrop Blur Pyramid (Only if scene contains active in-app BackdropBlur)] + └── Scissored Dual-Kawase 2x downsample (2 levels) -> 2x tent upsample + +[Pass 2: Main UI Uber-Pass (Single RenderCommandEncoder, Scissored to Dirty Union)] + ├── DrawBatch::UberQuad (Rounded/Squircle box, border, outer/inner erf shadow, + │ analytic surface material, Oklab gradient + IGN dither) + ├── DrawBatch::AtlasSprite (Hinted body text R8/dual-source RGB + raster images) + ├── DrawBatch::SlugVector (Large/rotated/zooming text + crisp SVG icons via Slug) + ├── DrawBatch::SparseStrips (Complex multi-color vector paths via vello_gpu 4x4 strips) + └── DrawBatch::NativeSurface(Zero-copy YCbCr / RGBA IOSurface video & camera frames) + * Every primitive evaluates `ClipStackBuffer[instance.clip_id]` in-shader for + rounded-rect clipping + 4-edge analytic soft-gradient masks (zero mask passes!). + * On Apple Silicon, non-blurred group opacity uses tile-local `[[color(1)]]` scratch + plane without breaking Pass 2! + +[Pass 3: Present] + └── Copy/present persistent backing texture to `CAMetalDrawable` (`maximumDrawableCount = 2`) +``` + +### Core GPU Primitive Set (6 Primitives Total) + +| Primitive | Instance Size | Responsibilities | +| :--- | :--- | :--- | +| `ClipNode` (GPU Buffer Table) | 32 B | `bounds`, `corner_radii`, `edge_feather (top, right, bottom, left)`, `parent_clip_id`, `transform_id`. Indexed by all primitives. | +| `UberQuad` | 128 B | Fill (Solid / Linear/Radial/Angular Oklab Gradient / Noise), per-corner radii + squircle exponent, border widths/style/color, analytic 4-sample `erf` outer/inner shadow, optional Makepad-style `Material` (bevel/rim/gloss). | +| `AtlasSprite` | 64 B | Monochrome (`R8Unorm`), Subpixel (`RGBA8` dual-source), or Polychrome (`RGBA8`) atlas tile + tint + rounded corner radii + transformation ref. | +| `SlugInstance` | 64 B | Em-space quad bounds, `curve_offset`, `curve_count`, `band_offset`, `band_count`, fill rule, color/gradient ref. | +| `SparseStripInstance` | 32 B | `vello_gpu` 4×4 pixel strip header (`x, y, width, alpha_offset, paint_id`) for arbitrary stroked/filled vector art. | +| `BackdropEffect` | 64 B | Kawase blur radius, saturation/contrast matrix, peak-alpha legibility boost (`pill.metal`), tint, and rounded-rect mask. | + +--- + +## 5. Open Questions for Prototyping + +1. **Uber-Shader Branching vs. Specialized PSOs on Low-End Integrated GPUs:** On Apple M1–M4, evaluating the unified `UberQuad` shader with uniform early-out branches (`if (quad.shadow_sigma == 0 && quad.bevel == 0)`) has near-zero divergence cost within 32-thread SIMD-groups. On older Intel/Qualcomm integrated GPUs via `wgpu`, should `UberQuad` split into `SimpleQuad` (64 B, flat/rounded + border) and `RichQuad` (128 B, shadow + gradient + material) pipelines? +2. **Slug Crossover Threshold on 2× vs 3× Retina:** At what exact pixel size (`24 px` vs `32 px` vs `48 px`) does Slug’s fragment raycasting match CoreText’s stem-darkened optical weight on macOS Retina displays without needing synthetic stem dilation in the Slug vertex shader? +3. **Persistent Texture Blit vs. Direct Drawable Rendering Threshold:** When >60% of the window area is dirty (e.g., full-window scrolling), rendering directly into `CAMetalDrawable` saves the 80 µs blit copy. What dirty-area ratio (e.g., `dirty_area / window_area > 0.35`) is the optimal hysteresis threshold to switch between persistent-texture partial redraw and direct-drawable full redraw? diff --git a/app/vendor/rune/research/05-text-ime-a11y-layout.md b/app/vendor/rune/research/05-text-ime-a11y-layout.md new file mode 100644 index 0000000..9e62fec --- /dev/null +++ b/app/vendor/rune/research/05-text-ime-a11y-layout.md @@ -0,0 +1,440 @@ +# 05 — Text, IME, Accessibility, and Layout + +*Research date: 2026-10-21* + +## Executive Summary + +- **Pure-Rust text shaping and font parsing are production-ready in 2026 (`harfrust` + `skrifa` + `fontique`).** Google Fonts' `harfrust` (`v0.14.0`, Oct 2026) has reached HarfBuzz 14.5.1 parity, uses zero-copy `fontations`/`read-fonts` tables directly (`ShaperData` + `ShaperInstance`), and runs 10–15% faster than `rustybuzz` while supporting variable-font variation coordinates, AAT (`morx`/`kerx`/`trak`), and shape plans. Pair it with `skrifa` (`v0.42.0`) for TrueType/CFF hinting + COLRv1 and `fontique` (`v0.8.0`) for font enumeration and script/locale fallback. +- **Keep OS font metrics on Apple (`CTFont`) while using `harfrust` + `parley` for cross-platform shaping and line breaking.** On macOS and iOS, system UI fonts (`SF Pro`, `SF Compact`, `.AppleSystemUIFont`) rely on optical-size (`opsz`) tracking tables (`trak`) and OS-specific ascent/descent rules. Use `parley` (`v0.12.0`, built on `parley_engine` + `fontique` + `harfrust` + `skrifa` + `icu4x`) for bidirectional paragraph layout, mixed inline runs, and cursor/selection geometry, augmented with GPUI's two-tier unwrapped-vs-wrapped `LineLayoutCache` (`zed/crates/gpui/src/text_system/line_layout.rs:523-698`) so container resizes only recompute wrap boundaries without re-shaping. +- **Luminance-quantized glyph dilation solves light-on-dark thin text on Apple displays without subpixel LCD fringes.** Subpixel LCD rendering is incompatible with transparent layers and GPU transforms. Instead, steal Kit's GPUI fork (`kitlangton/gpui`) luminance glyph dilation (`kitlangton/gpui/src/platform/mac/text_system.rs:42-81, 470-564`, commit `2582af8ad0`): quantize text color relative luminance ($0.2126R + 0.7152G + 0.0722B$) into 5 cache buckets (`0..=4`), pad `raster_bounds` by `1px`, and rasterize with `set_should_smooth_fonts(true)` at that gray fill level when `AppleFontSmoothing != 0`, paired with linear-space (`sRGB` framebuffer) alpha blending. +- **Never re-rasterize hinted glyphs on every frame of a spring transform.** Vello's `glifo` (`vello/glifo/src/glyph.rs:1702-1731`) folds uniform transform scale into `draw_font_size` and hashes `size.to_bits()`, thrashing the glyph atlas and causing stem-hinting pop on every frame of a 120 Hz spring animation. During active transforms, lock glyphs to unhinted/linear-metrics outlines rasterized at the target (or octave-stepped) scale and sample bilinearly, or promote large/hero animated text (`> 28px` or explicitly tagged) to Rive-style per-glyph vector paths (`rive-runtime/src/text/text.cpp:544-592`). +- **Use a unified `SumTree`-backed rope + display map for all text editing, from single-line inputs to multi-megabyte buffers.** Zed's concurrent B+ tree `SumTree` (`zed/crates/sum_tree/src/sum_tree.rs`, `TREE_BASE = 6`) maintains UTF-8 bytes, UTF-16 code units (required by Apple/Windows/Web IME), UTF-32 chars, line breaks, and soft-wrap display rows in $O(\log N)$ time with zero-copy `Arc` snapshots. +- **Implement native platform IME protocols directly on desktop and iOS, with a sliding-window `<textarea>` + `EditContext` hybrid on Web.** Direct `NSTextInputClient` (macOS), `UITextInput` + `UIEditMenuInteraction` subclass (iOS, stealing GPUI's deferred `reconcileTextInput` in `gpui_ios/src/ios/text_input.rs:197-318`), `ITfThreadMgr`/`ImmGetCompositionStringW` (Windows), and `zwp_text_input_v3` (Wayland) avoid hidden-native-widget desynchronization while preserving marked text, candidate window anchoring, Dictation, and Apple Writing Tools. +- **AccessKit (`v0.24` / 2026) is the clear winner for cross-platform accessibility and doubles as Rune's agent-inspector tree.** AccessKit now covers macOS (`accesskit_macos`), Windows (`accesskit_windows`), Linux AT-SPI (`accesskit_unix`), Android (`accesskit_android`), and iOS (`accesskit_ios`, `accesskit/adapters/ios/src/node.rs`). Building a single retained `accesskit::TreeUpdate` per frame gives VoiceOver/TalkBack/NVDA and AI testing/automation agents (`cua-driver`) one canonical semantic tree with roles, bounds, values, and deterministic `ActionRequest` dispatch. +- **Adopt a two-path layout architecture: `Taffy` (`v0.9.x`) for general Flexbox/CSS Grid UI + a `SumTree`-indexed height cache for virtualized lists + first-class layout interpolation hooks.** `Taffy` is heavily optimized (1.6 ms for 1,000 nodes vs Yoga's 1.5 ms on M1 Pro; 59 ms vs 84 ms on 100k Twitter feed nodes) and matches CSS mental models that LLMs write fluently, whereas `Pretext` + `SumTree` prefix-sum heights eliminate the 106.4 ms SwiftUI `sizeThatFits` bottleneck (a private iOS layout benchmark), dropping 500-paragraph resize passes to 2.6 ms. + +--- + +## 1. Text Shaping & Fonts + +### 1.1 `harfrust` vs `rustybuzz` vs OS Shapers (CoreText / DirectWrite) + +| Dimension | `harfrust` (`v0.14.0`, Oct 2026) | `rustybuzz` (`v0.20.x`) | CoreText (`CTLine`/`CTTypesetter`) | DirectWrite (`IDWriteTextAnalyzer`) | +|---|---|---|---|---| +| **HarfBuzz parity** | HarfBuzz 14.5.1 (`harfrust/CHANGELOG.md:9`) | Trails HarfBuzz ~6–12 months | Apple AAT + OpenType engine | Microsoft OpenType engine | +| **Font table backend** | Native `read-fonts` (`fontations`), zero-copy via `ShaperData` | Bundled `ttf-parser` | `CGFont` / `CTFont` | `IDWriteFontFace` | +| **Performance** | ~10–15% faster than `rustybuzz`; caches reusable `ShaperData` & `ShaperInstance` | Fast CPU, re-parses tables per face | Fast, but Objective-C/CF allocation overhead per run | Fast, COM call overhead | +| **Apple `trak` / AAT (`morx`, `kerx`)** | Supported (`harfrust` ports HarfBuzz AAT tables) | Partial AAT support | Reference implementation (including optical size `opsz` tracking) | No AAT `morx` | +| **Cross-platform determinism** | 100% identical glyph IDs & advances across all OSes | 100% identical across all OSes | Apple-only | Windows-only | + +**Source findings:** +- **`harfrust` has superseded `rustybuzz` across the Linebender and Servo ecosystems.** Originally started by Simon Cozens and Behdad Esfahbod (`harfrust/CHANGELOG.md:201-215`), `harfrust` is maintained directly under the HarfBuzz organization with Behdad Esfahbod and Chad Brokaw actively porting HarfBuzz algorithmic improvements (`harfrust/CHANGELOG.md:7-55`). +- **Pre-parsed table caching (`ShaperData`) and variation instance caching (`ShaperInstance`):** In `harfrust/src/hb/ot_shaper.rs` and `parley/parley/src/shape.rs:146-172`, `ShaperData::new(&font_ref)` pre-validates font tables once, while `ShaperInstance::from_variations(&font_ref, coords)` caches variation-axis coordinate lookups and feature stores. Shaping a run reuses a thread-local `harfrust::UnicodeBuffer` (`parley/parley/src/shape.rs:424-449`) with zero per-run heap allocations. +- **CoreText vs `harfrust` tradeoff on Apple:** GPUI currently calls `CTTypesetterCreateWithAttributedString` and `CTLineGetGlyphRuns` directly on macOS and iOS (`zed/crates/gpui_apple/src/text_system.rs:477-568`). While CoreText automatically applies Apple's undocumented optical tracking for `.AppleSystemUIFont` (`SF Pro`), allocating `CFAttributedString` and `CFDictionary` per text run costs measurable CPU time: in a private iOS layout benchmark, cold `CTFramesetter` measurement across 500 chat paragraphs takes **17.8 ms** (35.5 µs/msg), and SwiftUI `Text.sizeThatFits` takes **106.4 ms** (212.9 µs/msg). + +### 1.2 Font Loading, Parsing, Hinting, and Fallback (`fontations`/`skrifa`, `swash`, `fontique`) + +- **`fontations` (`read-fonts` + `skrifa` v0.42.0) vs `swash`:** + - Google's `fontations` workspace (`skrifa` + `read-fonts`) is now the standard Rust font stack used by Chrome (replacing FreeType in Chromium), Parley, Vello (`glifo`), and Bevy. + - `skrifa` (`fontations/skrifa/src/outline/mod.rs:1-148`) provides a complete TrueType bytecode interpreter, CFF/CFF2 hint engine, and a FreeType-derived Latin/CJK **autohinter** (`HintingOptions { engine: Engine::AutoFallback, target: Target::Smooth { mode: SmoothMode::Lcd | Normal, symmetric_rendering: true, preserve_linear_metrics: false } }`). + - `swash` is effectively unmaintained upstream; Parley removed `swash` entirely in `v0.4.0` (`parley/CHANGELOG.md:191-215`) in favor of `harfrust` + `skrifa`. +- **`fontique` (`v0.8.0`) for system font discovery and fallback:** + - `fontique` (maintained inside `parley/fontique`) handles cross-platform system font collection (`CoreText` on macOS/iOS, `DirectWrite` on Windows, `fontconfig` on Linux, `Android` XML/NDK font configuration) plus app-registered memory fonts (`register_fonts`). + - During shaping (`parley/parley/src/shape.rs:212-345`), `fontique` partitions text by `icu_properties::CodePointMapData::<Script>`, queries the family list first, and only falls back to `font_ctx.collection.fallback_families(FallbackKey::new(script, locale))` for `.notdef` (`glyph_id == 0`) sub-clusters, preserving variable font variation coordinates across fallback faces. + +### 1.3 Variable Fonts, OpenType Features, and Emoji + +- **Variable fonts (`wght`, `opsz`, `wdth`, `slnt`, custom axes):** `skrifa::MetadataProvider::axes()` resolves user axis tags into normalized `F2Dot14` design-space coordinates shared identically between `harfrust::ShaperInstance` (for `GPOS`/`GSUB` feature variations and `HVAR`/`MVAR` advances) and `skrifa::outline::OutlineGlyphCollection` (for `gvar`/`CFF2` interpolated glyph outlines). +- **OpenType features:** `harfrust::Feature` supports arbitrary 4-byte OpenType tags (`liga`, `calt`, `dlig`, `tnum`, `onum`, `zero`, `ss01`–`ss20`, `cv01`–`cv99`, `kern`) scoped by byte range (`parley/parley/src/shape.rs:178-206`). +- **Emoji (`COLRv0`/`COLRv1`, `sbix`, `CBDT`/`CBLC`):** + - Apple Color Emoji uses **`sbix`** (embedded PNG strips per strike ppem). + - Google Noto Color Emoji (Android/Linux/Web) uses **`COLRv1`** (vector paint graphs with linear/radial/sweep gradients, blend modes, and `VARC` variable composites) or **`CBDT`/`CBLC`** (embedded PNG bitmaps). + - Windows Segoe UI Emoji uses **`COLRv0`/`COLRv1`**. + - Vello's `glifo` (`vello/glifo/src/glyph.rs:289-424` and `vello/glifo/src/colr.rs`) inspects glyph tables in priority order: `skrifa::color::ColorGlyphCollection` (`COLRv0`/`COLRv1`) -> `sbix`/`CBDT` bitmap strikes (`image::load_from_memory_with_format(..., ImageFormat::Png)`) -> standard monochrome outline. + +--- + +## 2. Text Layout + +### 2.1 `parley` vs `cosmic-text` vs GPUI's Text System + +| Engine | Shaping / Bidi / Line-Break Stack | Strengths | Weaknesses | +|---|---|---|---| +| **`parley` (`v0.12.0`, Oct 2026)** | `harfrust` + `skrifa` + `fontique` + `icu4x` (`icu_segmenter`, `parley_bidi`) | Clean split between `parley_engine` (core layout) and `fontique`; supports inline boxes (`InlineBox`), text-indent (`IndentOptions`), cluster/cursor geometry, `Alignment::Justify`, zero allocations on warm `LayoutContext`. | Does not include a built-in cross-frame unwrapped-vs-wrapped line cache out of the box (expects host UI to cache `Layout`). | +| **`cosmic-text`** | `rustybuzz` + `swash` + `fontdb` + `unicode-bidi` | Battle-tested in System76 COSMIC; includes a basic shape cache (`ShapeLine` vs `LayoutLine`). | Stuck on legacy `swash`/`rustybuzz`; weaker inline-box and CSS-aligned typography model than `parley`. | +| **GPUI (`gpui` + `gpui_apple` / `gpui_wgpu`)** | Platform `LineWrapper` + `layout_line` (`CoreText` on Apple, `DirectWrite` on Windows, `cosmic-text` on Linux/Web) | Best-in-class two-tier `LineLayoutCache` (`line_layout.rs:523-698`) with frame-epoch eviction and bulk `reuse_layouts`. | Fragmented per-OS shaping leads to subtle cross-platform line-break and fallback differences; manual boundary wrapper (`LineWrapper::wrap_line`) rather than full UAX #14. | + +### 2.2 Bidirectional Text, Mixed Inline Runs, and Line Breaking + +- **Bidirectional layout (UAX #9):** `parley` uses `parley_bidi` (`parley/CHANGELOG.md:27`) to resolve embedding levels per paragraph and reorders visual runs per wrapped line *after* line breaking (as required by UAX #9 Section 3.4), ensuring hit-testing (`Cursor::from_point`) and selection rectangles (`Selection::geometry_with`) remain accurate across mixed RTL/LTR/numeric runs. +- **Line breaking (UAX #14) & hyphenation:** `parley` uses `icu_segmenter::LineSegmenter` for locale-aware UAX #14 line break opportunities (handling CJK kinsoku shori, Thai dictionary breaking, and emergency `WordBreakStrength::BreakAll` / `KeepAll`). +- **Inline boxes (pills, badges, icons, inline code):** `parley::LayoutBuilder::push_inline_box(InlineBox { id, index, width, height })` (`parley/parley/src/layout.rs`) participates directly in line breaking, baseline alignment, and cursor navigation as an atomic cluster—essential for chat UIs with `@mention` pills, file chips, and inline status badges. + +### 2.3 Truncation, Ellipsis, and SwiftUI/TextKit 2 Soft Fade Masks + +- **Why ellipsis (`…`) layout is expensive when naively implemented:** Shaping an ellipsis string and re-shaping the truncated line tail on every resize requires mutating the glyph stream. GPUI (`zed/crates/gpui/src/text_system/line_wrapper.rs`) measures the ellipsis width once per font/size and truncates at cluster boundaries, while SwiftUI/TextKit 2 (`NSTextLayoutManager`) supports both glyph-replacement ellipsis and visual fade masks. +- **Soft fade masks instead of `…`:** In modern streaming chat and card UIs (and animated label containers), hard `…` glyph substitution causes jarring character popping as width animates or tokens stream in. Rendering the full shaped line clipped to the container rect with a **horizontal alpha gradient mask** over the trailing `16–24px` (in linear alpha space, direction-aware for LTR/RTL) requires **zero re-shaping during width animations**, never pops glyphs, and signals overflow cleanly. Rune should support both `Overflow::Ellipsis` (cached ellipsis cluster substitution on `max_lines`) and `Overflow::FadeMask { tail_px: f32 }` (shader-evaluated edge ramp in the text quad primitive). + +### 2.4 Caching Shaped Lines Across Frames (Zed's `LineLayoutCache` & `Pretext`) + +- **Zed's two-tier `LineLayoutCache` (`zed/crates/gpui/src/text_system/line_layout.rs:523-698`):** + 1. **Unwrapped tier (`lines`):** Keyed by `(SharedString, font_size: Pixels, SmallVec<[FontRun; 1]>, force_width: Option<Pixels>)`. Stores `Arc<LineLayout>` containing shaped glyph positions and UTF-8 indices. + 2. **Wrapped tier (`wrapped_lines`):** Keyed by `(SharedString, font_size, runs, wrap_width: Option<Pixels>)`. When `wrap_width` changes (e.g., dragging a split pane or rotating a phone), `layout_wrapped_line` (`line_layout.rs:639-644`) hits the cached `unwrapped_layout` and only runs `compute_wrap_boundaries` over pre-shaped advances. + 3. **Two-frame epoch eviction + bulk reuse:** `LineLayoutCache` holds `current_frame` and `previous_frame` hash maps (`FxHashMap`). Views that do not re-layout call `reuse_layouts(range: Range<LineLayoutIndex>)` (`line_layout.rs:523-566`), which moves used entries from `previous_frame` to `current_frame` by index slice without even hashing keys. At `finish_frame()` (`line_layout.rs:586-600`), the maps swap and stale entries from `previous_frame` are dropped. +- **`Pretext` validation (a private iOS layout benchmark):** + - Across 500 mixed markdown/code chat messages on iOS, re-measuring height on viewport width change took **106.44 ms** with SwiftUI `sizeThatFits`, **17.75 ms** with cold `CTFramesetter`, **2.60 ms** with cached `CTFramesetter` frames, and **0.23 ms** with Pretext's pre-segmented width table (a **462x** speedup over SwiftUI `sizeThatFits`, though Pretext's naive whitespace Collapse had a 29% height mismatch against TextKit 2's hyphenation/kerning). Using **exact glyph-run advances** from the unwrapped `LineLayout` cache gives Pretext-class resize speed (**< 1 ms for 500 paragraphs**) with **0% height drift**. + +--- + +## 3. Glyph Rendering + +### 3.1 Glyph Atlas (Grayscale vs Subpixel AA) vs GPU Vector Outlines + +| Technique | Crispness at 10–16pt (2x Retina / 1x LoDPI) | Memory & Bandwidth | Arbitrary 2D/3D / Spring Scale Cost | Verdict for Rune | +|---|---|---|---|---| +| **Grayscale Mask Atlas + Luminance Dilation (`kitlangton/gpui`)** | Excellent on 2x Retina and 1x with `skrifa` hinting + 5-level luminance dilation | Low (`R8Unorm` 1 byte/px; `RGBA8` 4 bytes/px for emoji) | Fast at fixed scale; thrashes atlas if re-rasterized per scale frame | **Primary UI text path** | +| **Subpixel LCD Atlas (`RGB` ClearType/FreeType LCD)** | Sharpest on 1x non-Retina horizontal RGB panels | 3–4x atlas memory; requires dual-source blending (`blend_src1`) | Breaks under rotation, scale, non-RGB subpixel layouts (OLED), or unpremultiplied compositing | **Avoid** (dead on macOS since Mojave, broken on OLED/mobile/rotated layers) | +| **SDF / MSDF Atlas** | Poor at 11–14pt UI sizes (rounded corners, stem weight distortion on CJK/kanji) | Medium (offline or slow generator per glyph) | Smooth infinite zoom | **Avoid for UI text** | +| **Slug (Lengyel GPU Bezier evaluation)** | Exact unhinted outlines at any zoom | Compact curve/band textures | Zero atlas thrashing under zoom/3D; higher fragment shader ALU per covered pixel; no stem hinting at 11–13pt | Optional hero/3D/canvas text path (patent entered public domain / open-sourced in 2026, or via `glifo`/Vello compute) | +| **Vello / `glifo` CPU-cached Atlas (`vello/glifo/src/glyph.rs`)** | Good (`skrifa` hinted outlines rasterized via `vello_common::kurbo` strip generator into shelf-packed `AtlasPage`) | Low (`PlainMask` + `Color` atlases) | Currently absorbs transform `t_d` into `draw_font_size` (`glyph.rs:1702-1731`), thrashing cache on scale animations | Steal `glifo`'s `skrifa` + `COLRv1` + `sbix` pipeline, **fix** its transform-scale key behavior | +| **Rive Direct Vector Path (`rive-runtime/src/text/text.cpp:544-592`)** | Exact unhinted vector curves tessellated/rasterized by GPU path renderer | Zero glyph atlas | Native per-glyph `TextModifierGroup` affine transforms + variable-font axis keyframing at 120 Hz | **Use for hero / animated / path-warped text (`TextRenderMode::Vector`)** | + +### 3.2 macOS Font Smoothing, Stem Darkening, and Kit's GPUI fork (`kitlangton/gpui`) Luminance Glyph Dilation + +**Why text in naive GPU renderers looks "too thin" or "washed out" on macOS:** +1. **Gamma blending error:** Blending a linear coverage mask $\alpha$ directly in non-linear sRGB space computes $C_{\text{out}} = \alpha C_{\text{fg}} + (1 - \alpha) C_{\text{bg}}$ in sRGB, which darkens mid-tones and makes light text on a dark background lose ~20–30% of its perceived stroke weight compared to dark text on a light background. +2. **CoreGraphics `AppleFontSmoothing` behavior in alpha-only contexts:** When rasterizing glyphs into a single-channel `kCGImageAlphaOnly` bitmap (`gpui_apple/src/text_system.rs:429-434`), calling `CGContextSetShouldSmoothFonts(cx, true)` tells CoreGraphics to apply **stem darkening (synthetic bolding/dilation)**—but CoreGraphics modulates the dilation strength by the *luminance of the active fill color* in the `CGContext`! If a GPU renderer rasterizes glyphs once into an alpha-only atlas with a fixed white (`1.0`) or black (`0.0`) fill color, either dark-on-light text looks overly heavy or light-on-dark text looks spindly. + +**How Kit's GPUI fork (`kitlangton/gpui`) Luminance Glyph Dilation works (`kitlangton/gpui/src/platform/mac/text_system.rs`, commit `2582af8ad0`):** +- **5-bucket relative luminance quantization (`text_system.rs:42-69`):** + ```rust + pub(crate) const GLYPH_DILATION_LEVELS: u8 = 5; + + pub(crate) fn glyph_dilation_for_color(color: Hsla) -> u8 { + if !font_smoothing_enabled() { + return 0; + } + let rgba = color.to_rgb(); + let luminance = 0.2126 * rgba.r + 0.7152 * rgba.g + 0.0722 * rgba.b; + (luminance * (GLYPH_DILATION_LEVELS - 1) as f32) + .round() + .clamp(0.0, (GLYPH_DILATION_LEVELS - 1) as f32) as u8 + } + ``` +- **System default detection (`text_system.rs:71-81`):** Reads macOS `NSUserDefaults::standardUserDefaults().integerForKey("AppleFontSmoothing")` once via `OnceLock`; enabled when `!= 0` (matching macOS default `2`). +- **Cache key & bounds padding (`text_system.rs:470-499`):** `RenderGlyphParams` includes `dilation: u8` (`0..=4`). When `font_smoothing_enabled()` is true, `raster_bounds` adds `1px` padding on all four sides (`origin - (1, 1)`, `size + (2, 2)`) so dilated glyph stems never clip at the atlas tile boundary. +- **Rasterization (`text_system.rs:537-564`):** Inside `rasterize_glyph`, when `params.dilation > 0`: + ```rust + let luminance = params.dilation as f64 / (GLYPH_DILATION_LEVELS - 1) as f64; + cx.set_should_smooth_fonts(true); + cx.set_gray_fill_color(luminance, 1.0); + ``` + This feeds CoreGraphics the exact 25%-stepped gray luminance (`0.0, 0.25, 0.50, 0.75, 1.0`), producing authentic macOS stem weight across both light and dark themes while capping atlas growth to at most the active foreground luminance buckets (typically 2 buckets per theme: primary text + muted text). +- **Cross-platform equivalent on `skrifa`/FreeType (`Windows`/`Linux`/`Android`):** When using `skrifa` + CPU/GPU outline rasterization off Apple, apply FreeType/Adobe CFF **stem darkening** in outline space (`darken_x = 0.025 * ppem`, modulated by foreground-vs-background luminance contrast) or a linear-space coverage gamma adjustment ($\alpha' = \alpha^{1.0 / \gamma_{\text{contrast}}}$) in the glyph fragment shader. + +### 3.3 Why SDF / MSDF Fails for Small UI Text + +- **Single-channel SDF** cannot preserve sharp corners (a single distance value rounds every corner when reconstructed at scales different from the raster grid), making `11–14pt` sans-serif stems (`I`, `l`, `m`, `n`) look mushy or blob-like. +- **Multi-channel SDF (MSDF)** preserves sharp 2-edge corners by encoding signed distances to two edge segments in R/G/B channels and taking `median(r, g, b)`. However: + 1. Complex glyphs with >2 converging edges per texel (common in `11–14pt` CJK ideographs, `@`, `%`, `&`, and serif joins) suffer from **false edge artifacts (spikes and dropouts)** unless the MSDF texel resolution is high (`32x32` to `64x64` per glyph). + 2.Generating an MSDF on the CPU on demand for newly encountered CJK/Unicode glyphs is **10–30x slower** than scanline coverage rasterization. + 3. MSDF operates on unhinted outlines, losing pixel-grid stem alignment at `10–15pt` on 1x/2x displays. + +### 3.4 Subpixel Positioning (`4` Horizontal × `1` Vertical Phases) + +- Without subpixel positioning, snapping glyph origins to integer device pixels causes uneven inter-glyph kerning ("dancing letters" when slowly scrolling or adjusting tracking). +- Both GPUI (`zed/crates/gpui/src/text_system.rs`, `SUBPIXEL_VARIANTS_X = 4, SUBPIXEL_VARIANTS_Y = 1` on Retina) and Vello's `glifo` (`vello/glifo/src/glyph.rs:437-465`, `SubpixelAxis::Four` = `0.0, 0.25, 0.5, 0.75`) quantize the fractional device-pixel X coordinate into **4 horizontal subpixel phases** (`u8` `0..=3`) and **1 vertical phase** (since horizontal text baselines align vertically to rows). +- **Important optimization from `glifo/src/glyph.rs:444-465`:** Above a font size threshold (`OPTICAL_SIZE_THRESHOLD` ~ `24–32px` device pixels), subpixel phase quantization is reduced to `SubpixelAxis::Two` or `One` (integer pixel snapping), preventing atlas bloat on large headings where a `0.25px` shift is imperceptible. + +### 3.5 Animated Text Under Spring Transforms (Why Text Jitters & How Apple / Figma / Rive Solve It) + +**The bug in naive atlas renderers (including Vello `glifo`):** +- In `vello/glifo/src/glyph.rs:1702-1731` (`GlyphScaleProperties::new`), when a draw transform has uniform or axis-aligned scale (`t_a`, `t_d`), `glifo` folds `t_d` directly into `draw_font_size = font_size * t_d` and keys the glyph cache by `size: draw_font_size.to_bits()` (`u32`, `glyph.rs:480-523`). +- During a 120 Hz spring scale animation (e.g., `scale: 0.92 -> 1.02 -> 1.00`), `draw_font_size` takes 60+ distinct `f32` bit patterns in 500 ms. Worse, if hinting or integer advance rounding is enabled, stems jump between pixel columns ("swimming / jittering letters") and the glyph atlas thrashes on every frame. + +**How production engines solve animated text:** +1. **Apple CoreAnimation / SwiftUI (`CATextLayer`, `.drawingGroup()`, `NSStringDrawingOptions`):** + - For standard layer transforms (`scaleEffect`, modal spring entrance), CoreAnimation caches the text layer at its **target (`1.0x`) contentsScale** (or highest octave scale) and applies the spring transform in the GPU compositor with bilinear texture filtering + linear metric advances (`CTFontCreateWithFontDescriptor` with `kCTFontLinearMetricsAttribute` / subpixel positioning). + - For SwiftUI `matchedGeometryEffect` / variable font transitions, Apple interpolates between two pre-rasterized scale snapshots or switches to unhinted subpixel-positioned outlines (`preserve_linear_metrics: true`). +2. **Figma (WebGL / WebGPU canvas renderer):** + - Figma renders text via cached glyph textures while stationary at a discrete zoom level, and during continuous zoom/spring animations either samples the nearest higher power-of-two mip octave from the glyph atlas with linear metrics or renders vector glyph meshes on the GPU. +3. **Rive (`rive-runtime/src/text/text.cpp:544-592`, `text_modifier_group.cpp`):** + - Rive never uses a bitmap glyph atlas for scene text. Every shaped glyph outline is extracted as an unhinted `RawPath` in normalized em-space (`rive-runtime/src/text/text.cpp:544-592`) and rendered directly by Rive's GPU vector renderer (PLS / atomic feathering) under per-glyph `Mat2D` transforms (`TextModifierGroup::transformGlyph` supporting per-character opacity, rotation, scale, position, and variable font axis keyframing at 120 Hz with zero atlas re-rasterization). + +**Rune's hybrid rule for animated text:** +- **Static & scrolling UI text (`<= 28pt`, no active scale/rotation animation):** Hinted (`skrifa` `preserve_linear_metrics: false` on 1x, unhinted/light-hinted `preserve_linear_metrics: true` on $\ge 2\text{x}$ Retina) + 4x horizontal subpixel phase + 5-level luminance dilation in the glyph atlas. +- **Text inside an active scale/rotation spring transform:** Automatically switch the text primitive to **transform-invariant atlas sampling**: rasterize once at `ceil_octave(max_expected_scale) * font_size` with `preserve_linear_metrics: true` and fractional GPU quad positions (do **not** snap glyph quads to integer device pixels while transforming!), sampling with bilinear filtering + mild sharpening. +- **Hero / kinetic typography (`> 28pt`, or explicit `.textRenderMode(.vector)` / per-glyph `TextModifier`):** Bypass the bitmap atlas and emit unhinted `skrifa` outlines directly into Rune's GPU vector path pipeline (Vello/Slug-style curve evaluation), enabling Rive-class per-character spring choreography and variable-font weight/width animations with zero atlas traffic. + +--- + +## 4. Text Editing (Single-Line Input through Rich Code/Prose Editor) + +### 4.1 Selection, Caret, Bidirectional Cursor Movement, and Affinity + +- **Selection representation:** Every selection is an ordered or directional pair `Selection { start: usize, end: usize, reversed: bool, goal_column: Option<f32> }` in UTF-8 byte offsets, accompanied by `Affinity::{Upstream, Downstream}` (`parley/parley/src/cursor.rs`). +- **Why `Affinity` is mandatory:** At a soft line wrap boundary, byte offset $k$ corresponds to **two distinct screen positions**: the end of line $i$ (`Affinity::Upstream`) and the start of line $i+1$ (`Affinity::Downstream`). Likewise, at an LTR/RTL bidi boundary, a single byte offset maps to two split-caret visual X positions. `parley::Cursor` encodes `(index: usize, affinity: Affinity)` directly and computes visual geometry via `Cursor::geometry(&layout, size)`. +- **Grapheme and word navigation (UAX #29):** + - Left/Right arrow movement steps by **extended grapheme clusters** (`icu_segmenter::GraphemeClusterSegmenter` or `unicode-segmentation`), so multi-codepoint emoji (family ZWJ sequences `👨‍👩‍👧‍👦`, skin-tone modifiers, flag pairs) and combining marks move and delete (`Backspace` vs `Delete`) correctly. + - Option+Left/Right (macOS) / Ctrl+Left/Right (Windows/Linux) and double-click word selection use UAX #29 word boundaries customized with character-class tables (`Alphanumeric`, `Punctuation`, `Whitespace`, plus configurable `word_characters` like `_` or `$` for code inputs). + - Triple-click selects the logical paragraph (or visual line with modifier), dragging extends selection by word (double-click-drag) or line (triple-click-drag) by anchoring the initial word/line range (`gpui_ios/src/ios/text_input.rs` / `zed/crates/editor`). + +### 4.2 Buffer Data Structures: Ropes vs Zed's `SumTree` + +| Data Structure | Memory / Node | Concurrent Snapshot | Multi-Coordinate Indexing (UTF-8, UTF-16, Lines, Display Wrap) | Used By | +|---|---|---|---|---| +| **`String` / Gap Buffer** | Contiguous `Vec<u8>` | Requires full clone | $O(N)$ scan for UTF-16 or line numbers | Naive single-line inputs | +| **`ropey`** | B-tree of UTF-8 chunks | Clone-on-write (`Arc`) | UTF-8, chars, lines; UTF-16 conversion added but no custom summary dimensions | Helix, cosmic-text | +| **Zed `SumTree` + `Rope` (`zed/crates/sum_tree/src/sum_tree.rs`, `zed/crates/rope`)** | `Arc`-backed B+ tree (`TREE_BASE = 6`, up to 12 children/node) | $O(1)$ lock-free `Clone` | Arbitrary `Summary` trait + multiple simultaneous `Dimension` types (`usize` bytes, `Point`, `PointUtf16`, `OffsetUtf16`, `Chars`) | Zed (`Buffer`, `DisplayMap`, `WrapMap`, `FoldMap`, `BlockMap`) | + +**Why Rune should steal Zed's `SumTree` + `Rope` pattern (`zed/crates/sum_tree/src/sum_tree.rs:1-140`):** +- Every node in `SumTree<T>` stores an aggregated `T::Summary`. For `Rope::Chunk`, `TextSummary` tracks `len: usize` (UTF-8), `len_utf16: OffsetUtf16`, `lines: Point` (row/col), `first_line_chars`, `last_line_chars`, and `longest_row`. +- Converting between **UTF-8 byte offsets** (used by Rust/`harfrust`/`parley`) and **UTF-16 code-unit offsets** (mandated by macOS `NSRange`, iOS `UITextPosition`, Windows `ImmGetCompositionStringW`, and Web `EditContext`/`HTMLTextAreaElement`) is a single $O(\log N)$ B+ tree traversal (`rope.offset_to_offset_utf16(byte_offset)`), eliminating the #1 source of UTF-16 surrogate-pair crashes in emoji-heavy inputs! +- Even better, the **exact same `SumTree` crate** powers both text buffers and **virtualized list prefix-sum heights** (Section 7). + +### 4.3 Undo/Redo Grouping, `DefaultKeyBinding.dict`, and System Text Services + +- **Undo/Redo transaction grouping:** Group consecutive character insertions within a `300 ms` typing window (broken by whitespace/newline, paste, cursor jump, or backspace transitions) into a single undo transaction storing `(transaction_id, timestamp, selection_before, selection_after, Vec<Edit>)`. +- **macOS `DefaultKeyBinding.dict` bug in GPUI and how to fix it:** + - In `zed/crates/gpui_macos/src/window.rs:3513-3531`, GPUI implements `doCommandBySelector:` as: + ```rust + // We ignore which selector it asks us to do because the user may have + // bound the shortcut to something else. + extern "C" fn do_command_by_selector(this: &Object, _: Sel, _: Sel) { ... } + ``` + Because GPUI drops the `selector: Sel` argument and simply replays `keystroke_for_do_command` into its own keymap, any custom user binding in `~/Library/KeyBindings/DefaultKeyBinding.dict` (such as mapping a key chord to `deleteWordBackward:`, `moveToBeginningOfParagraph:`, `yank:`, `setMark:`, `swapWithMark:`, or a multi-selector array) is ignored! + - **Fix for Rune:** First check if the application keymap explicitly binds the raw keystroke. If not (or if `NSTextInputContext` synthesized one or more `NSStandardKeyBindingResponding` selectors from `DefaultKeyBinding.dict`), dispatch the actual `Sel` (`insertNewline:`, `deleteBackward:`, `deleteWordBackward:`, `moveWordForward:`, `moveToBeginningOfLine:`, `transpose:`, `yank:`, etc.) to the focused text input handler. +- **Spellcheck, Autocorrect, Dictation, and Apple Writing Tools (macOS 15+ / iOS 18+):** + - **Spellcheck & Autocorrect:** On macOS, query `NSSpellChecker.sharedSpellChecker` asynchronously on background worker threads per edited paragraph (`checkSpellingOfString:startingAt:language:wrap:inSpellDocumentWithTag:wordCount:`) and render wavy/dotted underlines as a text decoration layer; on iOS, `UITextInputTraits.spellCheckingType` and `autocorrectionType` are driven natively by `UITextInteraction`. + - **Dictation:** On both macOS (`NSTextInputClient`) and iOS (`UITextInput`), system Dictation streams tentative transcriptions via `setMarkedText:selectedRange:replacementRange:` and commits via `insertText:replacementRange:` (plus `insertDictationResult:` on iOS). + - **Apple Writing Tools (macOS 15+ / iOS 18+):** Conforming to `NSWritingToolsCoordinatorDelegate` (macOS) or `UIWritingToolsCoordinatorDelegate` / `UITextInput` (iOS) allows Apple Intelligence Writing Tools to read context ranges, animate proofreading/rewrite highlights, and apply replacements with built-in undo support. + +--- + +## 5. IME (Input Method Editors) Per Platform + +### 5.1 Architecture Matrix Across All 6 Platforms + +| Platform | Native Protocol / API | Coordinate Unit | Composition / Marked Text | Candidate Window Positioning | Context / Recon Strategy | +|---|---|---|---|---|---| +| **macOS** | `NSTextInputClient` on `NSView` + `NSTextInputContext` (`gpui_macos/src/window.rs:236-298, 2700-2780, 3368-3532`) | UTF-16 `NSRange` | `setMarkedText:selectedRange:replacementRange:`; `unmarkText` | `firstRectForCharacterRange:actualRange:` (screen coordinates, bottom-left origin!) | Synchronous query into `InputHandler` during `handleEvent:` | +| **iOS** | Custom `UIView <UITextInput, UIKeyInput>` + `UITextInteraction` + `UIEditMenuInteraction` (`gpui_ios/src/ios/text_input.rs:197-1150`; `FlutterTextInputPlugin.mm:180-1100`) | Abstract `UITextPosition` wrapping UTF-16 index | `setMarkedText:selectedRange:`; `unmarkText` | `firstRectForRange:` + `caretRectForPosition:` + `selectionRectsForRange:` | **Deferred coalesced `reconcileTextInput`** (`dispatch_async` to main queue) to prevent UIKit feedback loops | +| **Android** | `View.onCreateInputConnection` -> `BaseInputConnection` + `InputMethodManager` | UTF-16 `Editable` / offsets | `setComposingText`, `setComposingRegion`, `finishComposingText` | `CursorAnchorInfo.Builder` (`setInsertionMarkerLocation`, `addCharacterBounds`) | State push via `imm.updateSelection` + `imm.updateCursorAnchorInfo` | +| **Web (2026)** | Primary: **Sliding-Window Hidden `<textarea>`** (`gpui_web/src/ime_mirror.rs:1-450`, `CONTEXT_CHARS = 512`) + progressive enhancement to **`EditContext` API** on Chromium/Edge | UTF-16 DOM offsets | `compositionstart`, `compositionupdate`, `compositionend`, `beforeinput` (`insertFromComposition`) | CSS positioning of `<textarea>` at `bounds_for_range` (`ime_mirror.rs:412-448`) or `EditContext.updateCharacterBounds` | Sliding 1,024-char window synced after every frame | +| **Windows** | `WM_IME_STARTCOMPOSITION`, `WM_IME_COMPOSITION` (`ImmGetCompositionStringW` with `GCS_COMPSTR`, `GCS_COMPATTR`, `GCS_CURSORPOS`, `GCS_RESULTSTR`) + TSF (`ITfThreadMgr` / `ITfContext`) (`gpui_windows/src/events.rs:654-790, 1710-1760`) | UTF-16 (`WCHAR` slice) | Clause-attributed composition (`ATTR_TARGET_CONVERTED`, `ATTR_CONVERTED`, `ATTR_INPUT`) | `ImmSetCompositionWindow` + `ImmSetCandidateWindow` (`CFS_CANDIDATEPOS`) | Per-window `ImmAssociateContextEx` enabled only when text input focused | +| **Linux (Wayland / X11)** | Wayland: `zwp_text_input_v3` (`gpui_linux/src/linux/wayland/client.rs:2278-2354`); X11: XIM (`XIC`) | UTF-8 byte offsets | `Event::PreeditString { text, cursor_begin, cursor_end }` buffered until `Event::Done { serial }` | `set_cursor_rectangle(x, y, width, height)` + `commit()` with serial tracking | Transactional `PreeditString` + `CommitString` applied atomically on `Done` | + +### 5.2 Deep-Dive Findings & Subtle Platform Traps + +1. **macOS Key Routing Order (`gpui_macos/src/window.rs:2700-2748`):** + - If you run app keybindings *before* `[inputContext handleEvent: native_event]`, multi-keystroke bindings (like Vim `jj` or chord shortcuts) intercept keys meant for Japanese/Chinese/Korean IME (turning `ji` into `jい` instead of `じ`) or swallow dead keys (`Option+e` -> `é`). + - Conversely, if you send *all* keys to `inputContext` first when no text input is focused, macOS beeps or eats shortcuts. + - **Rule:** Send key events to `inputContext` first if and only if: (a) `hasMarkedText()` is true (`is_composing`), OR (b) a printable key without `Ctrl`/`Cmd`/`Fn` is pressed while an IME input source is active and the focused view accepts text input (`is_ime_printable_key`), OR (c) it is a dead key (`key_char.is_none()`). +2. **iOS Direct `UITextInput` vs Hidden `UITextField` (`gpui_ios/src/ios/text_input.rs` & `FlutterTextInputPlugin.mm`):** + - **Why a hidden `UITextField` / `UITextView` fails:** A hidden native text field has its own internal TextKit layout and gesture recognizers; its selection handles, loupe magnifier, Scribble (Apple Pencil), and floating trackpad cursor (holding Spacebar on iOS keyboard) cannot match custom-rendered GPU text lines. + - **How GPUI and Flutter solve iOS `UITextInput` directly:** + - Create a dedicated `UIView` subclass (`GPUITextInputView` in `gpui_ios/src/ios/text_input.rs:197-318`, `FlutterTextInputView` in `FlutterTextInputPlugin.mm:400-1100`) that conforms to `UITextInput` and `UIKeyInput`. + - Attach a `UITextInteraction::editableInteraction()` (`text_input.rs:285-295`) and `UIEditMenuInteraction` so UIKit renders the **native iOS selection handles, double-tap/long-press loupe, floating keyboard trackpad cursor (`beginFloatingCursorAtPoint:` / `updateFloatingCursorAtPoint:` / `endFloatingCursor`), Scribble, and Cut/Copy/Paste/Autofill callout bar** directly over the GPU canvas using geometry returned by `firstRectForRange:`, `caretRectForPosition:`, and `selectionRectsForRange:`! + - **Critical anti-reentrancy trick (`gpui_ios/src/ios/text_input.rs:212-238, 1080-1145`):** Calling `[inputDelegate textWillChange:]` / `[inputDelegate selectionDidChange:]` synchronously inside a UIKit callback causes UIKit's `UITextInteraction` and autocorrect engine to re-enter `UITextInput` methods with stale state. GPUI sets an `in_input_callback: BOOL` ivar and schedules a single coalesced `reconcileTextInput` via `dispatch_async_f(dispatch_get_main_queue(), ...)` to notify `inputDelegate` (`selectionWillChange`/`selectionDidChange`/`textWillChange`/`textDidChange`) only when the model state actually diverged from what UIKit already knows. + - **Flutter's iOS 17+ `UITextInteraction` workaround (`FlutterTextInputPlugin.mm:260-285`):** On iOS 17+, `UITextInteraction` requires an view in the responder chain when keyboard dictation / trackpad mode activates; keeping `GPUITextInputView` in the view hierarchy (with zero visual sublayers) satisfies UIKit's responder checks. +3. **Web IME in 2026: Hidden Sliding-Window `<textarea>` + `EditContext` (`gpui_web/src/ime_mirror.rs:1-450`):** + - **State of `EditContext` in 2026:** W3C `EditContext` is shipping in Chromium/Edge (`Chrome 121+`), giving direct `textupdate`, `characterboundsupdate`, and `textformatupdate` (Japanese clause underline thickness/style) without DOM mutation side-effects. However, **Safari (WebKit) and Firefox still lack complete `EditContext` support on mobile/desktop in 2026**. + - **Why GPUI's `ImeMirror` (`gpui_web/src/ime_mirror.rs:1-130`) works everywhere:** Instead of mirroring an entire 100 KB document into a hidden `<textarea>` (which freezes mobile Safari), `ImeMirror` mirrors only a **sliding window of `CONTEXT_CHARS = 512` characters before and after the selection** (`ime_mirror.rs:23`), tracks `window_start_utf16` and `composition_start_utf16`, and positions the `1px` transparent `<textarea>` directly at the caret's `bounds_for_range` (`ime_mirror.rs:412-448`) so the OS candidate popup and macOS emoji picker (`Ctrl+Cmd+Space`) anchor to the exact caret pixel. +4. **Windows Clause Underline Attributes (`gpui_windows/src/events.rs:713-785, 1738-1760`):** + - Japanese and Chinese IMEs on Windows split an active composition into multiple clauses, where one clause is the **active conversion target** (`ATTR_TARGET_CONVERTED` / `ATTR_TARGET_NOTCONVERTED`, rendered with a thick or highlighted underline) and sibling clauses are `ATTR_CONVERTED` (thin/dotted underline). Querying `ImmGetCompositionStringW(ctx, GCS_COMPATTR, ...)` alongside `GCS_CURSORPOS` is required so users can see which clause Left/Right arrow keys are reconverting. +5. **Linux Wayland `zwp_text_input_v3` Serial & Vim-Mode Quirks (`gpui_linux/src/linux/wayland/client.rs:2278-2354`):** + - Wayland `zwp_text_input_v3` sends `PreeditString` and `CommitString` as pending state followed by `Event::Done { serial }`. If `Done` arrives with `ime_pre_edit == None` while previously composing, the client must clear marked text (`client.rs:2346-2350`). + - Also note `client.rs:2306-2320`: IBus intercepts single ASCII keys like `a` or `b` and sends them as `CommitString("a")` instead of `wl_keyboard::Key`, which breaks modal keybindings unless single-byte ASCII commits when not composing are routed through `KeyDown`. + +--- + +## 6. Accessibility (a11y) & Agent Inspection + +### 6.1 AccessKit in 2026 (`accesskit` v0.24+) + +Inspection of `accesskit/` confirms AccessKit now ships first-party platform adapters across **all five native targets**: +- **macOS (`accesskit_macos`):** Maps `accesskit::Node` to `NSAccessibilityElement` subclasses (`accesskit/adapters/macos/src/node.rs:36-210`), posting `NSAccessibilityFocusedUIElementChangedNotification`, `NSAccessibilityValueChangedNotification`, and `NSAccessibilityLayoutChangedNotification`. +- **iOS (`accesskit_ios`):** Implemented in `accesskit/adapters/ios/src/node.rs:1-515` (`v0.4.0`), mapping `accesskit::Node` to `UIAccessibilityElement` with `UIAccessibilityTraits` (`Button`, `Header`, `Adjustable`, `UpdatesFrequently`, `Selected`, `NotEnabled`), `accessibilityFrame` (converted via `UIAccessibilityConvertFrameToScreenCoordinates`), `accessibilityActivate`, `accessibilityIncrement`/`Decrement`, and `accessibilityScroll:`. +- **Android (`accesskit_android`):** Implemented in `accesskit/adapters/android/` (`v0.6.0`), bridging to Android's `AccessibilityNodeProvider` (`AccessibilityNodeInfo` virtual view hierarchy) for TalkBack. +- **Windows (`accesskit_windows`):** Implements UI Automation (`IRawElementProviderSimple`, `ITextProvider`, `IValueProvider`, `IScrollItemProvider`) for Narrator, NVDA, and JAWS. +- **Linux (`accesskit_unix`):** Implements AT-SPI2 over D-Bus (`zbus`) for Orca. + +### 6.2 Roles, Actions, Live Regions, Focus, and Text Navigation + +- **Core primitives (`accesskit/accesskit/src/lib.rs`):** + - `NodeId(NonZeroU64)`: Stable 64-bit identifier per semantic node. + - `Role` (`lib.rs:62-284`): 180+ WAI-ARIA / native roles (`Button`, `TextInput`, `MultilineTextInput`, `Switch`, `Slider`, `List`, `ListItem`, `Dialog`, `Tab`, `TabPanel`, `ScrollView`, `TextRun`, etc.). + - `Action` (`lib.rs:289-350`): `Click`, `Focus`, `Blur`, `Increment`, `Decrement`, `ReplaceSelectedText`, `SetValue`, `SetTextSelection`, `ScrollIntoView`, `ScrollToPoint`, `SetScrollOffset`, `Expand`, `Collapse`, `ShowContextMenu`, `CustomAction`. + - `Live` (`lib.rs:584`): `Off`, `Polite`, `Assertive` (maps to `UIAccessibilityPostNotification(UIAccessibilityAnnouncementNotification, ...)` on iOS and `NSAccessibilityAnnouncementRequestedNotification` on macOS). + - **Character-level text navigation (`Role::TextRun`):** For multi-line text inputs and selectable text, AccessKit represents each wrapped visual line as a child `Role::TextRun` node carrying `character_lengths: Box<[u8]>`, `character_positions: Box<[f32]>`, `character_widths: Box<[f32]>`, and `word_starts: Box<[u8]>`. AccessKit transforms this directly into macOS `accessibilityFrameForRange:`, Windows `ITextRangeProvider`, and iOS text selection navigation without platform-specific text glue! + +### 6.3 How Flutter Maps `SemanticsNode` and What iOS VoiceOver Needs + +- In Flutter (`flutter/engine/src/flutter/shell/platform/darwin/ios/framework/Source/SemanticsObject.h` & `SemanticsObject.mm`), every `SemanticsNode` becomes a `SemanticsObject : UIAccessibilityElement` (or `SemanticsObjectContainer` for children). +- **Critical iOS VoiceOver requirements that custom GPU frameworks miss:** + 1. **Two-finger Z-scrub ("Escape" gesture):** iOS VoiceOver users scrub a "Z" with two fingers to dismiss modals, pop navigation stacks, or close sheets. `accesskit_ios` (`accesskit/adapters/ios/src/node.rs`) and Rune's root container must implement `accessibilityPerformEscape` and map it to a dismiss/back action on the active modal or navigation route. + 2. **Modal sibling masking (`accessibilityViewIsModal`):** When a dialog, sheet, or popover is open, setting `Node::set_modal(true)` (which maps to `accessibilityViewIsModal = YES` on iOS) prevents VoiceOver swipe navigation from cycling through background views behind the scrim. + 3. **Scroll-on-swipe (`accessibilityScroll:` & `Action::ScrollIntoView`):** When VoiceOver swipes past the last visible row of a virtualized list, the list must keep a **1-screen buffer of offscreen semantic nodes** above and below the viewport and handle `Action::ScrollIntoView` + `accessibilityScroll:` by advancing the virtual scroll offset and posting `UIAccessibilityLayoutChangedNotification`. + 4. **Rotor Custom Actions (`UIAccessibilityCustomAction`):** Swipe actions on list rows (e.g., Archive, Delete, Pin) must register as `CustomAction` on the row's `accesskit::Node` so VoiceOver users can trigger them via the vertical swipe rotor. + +### 6.4 Should the Accessibility Tree Double as the Agent-Inspector Tree? + +**Yes — unequivocally.** +- Kit's existing automation tools (`cua-driver`, macOS Accessibility inspector, agent proof scripts) already operate by snapshotting the accessibility tree, binding stable element tokens, reading bounds/labels/values, and invoking semantic actions (`Click`, `SetValue`, `ScrollIntoView`). +- By making `accesskit::TreeUpdate` a **first-class frame output** (built incrementally for dirty subtrees or serialized on demand over a local Unix socket / WebSocket / MCP debug endpoint even when OS screen readers are inactive), Rune gets: + 1. **Zero-cost agent drivability on every platform** (including headless Linux CI, iOS simulators, Android emulators, and Web) via one JSON/binary `TreeUpdate` schema. + 2. **Built-in a11y enforcement:** If an AI agent cannot see or click a button in an agent proof script, a blind VoiceOver user cannot use it either. + 3. **Lightweight extension:** Add an optional side-table `InspectorMetadata` keyed by `accesskit::NodeId` for agent-only diagnostics (component source `file:line`, test ID, computed style/spring state, layout constraints) without polluting the OS accessibility bridge. + +--- + +## 7. Layout + +### 7.1 Comparative Evaluation of Layout Models + +| Dimension | **Taffy (`v0.9.x`, Flexbox + CSS Grid)** | **SwiftUI Proposal / Size Negotiation** | **Flutter Constraints-Down, Sizes-Up (`BoxConstraints`)** | **Clay (Nic Barker's C micro-layout)** | **Morphorm (Subform / Vizir units)** | +|---|---|---|---|---|---| +| **Mental Model** | CSS Flexbox & CSS Grid (`Style` struct) | Parent proposes `(w?, h?)` -> Child picks size -> Parent places child | Parent passes `(min_w..max_w, min_h..max_h)` -> Child returns `Size` | Single-header immediate-mode `Sizing::Fixed`, `Grow`, `Percent`, `Fit` | Constraint units (`Pixels`, `Percentage`, `Stretch`, `Auto`) | +| **Passes per Tree** | 1–3 passes (Flex intrinsic measure + flex resolve; cached by `(known_dimensions, available_space)`) | 1–3 proposals (`nil` ideal, `0` min, `.infinity` max, concrete width) | Strictly $O(N)$ single pass (except `IntrinsicWidth`/`Height`) | Strictly 3 linear array passes (BFS/DFS over flat arena) | 2 passes (upward intrinsic, downward stretch) | +| **Agent-Writability (LLM accuracy)** | **Highest:** Every LLM has millions of Tailwind/CSS Flexbox/Grid examples in pretraining | High (SwiftUI modifiers), but `.frame(maxWidth: .infinity)` + `layoutPriority` traps are common | Medium-High (`Expanded`/`Flexible` inside unconstrained `ScrollView` panics at runtime!) | Good for simple rows/columns; no CSS Grid or baseline wrap | Low training corpus; unfamiliar `Units::Stretch` rules | +| **1M-Row Virtualized List Perf** | Must NOT instantiate 1M Taffy nodes; pair with virtual viewport + `SumTree` height index | `LazyVStack` struggles with variable heights (`sizeThatFits` = 106.4 ms / 500 rows) | `SliverList` is fast, requires custom sliver protocol | Arena-based (~15 µs for visible ~100 nodes), no built-in virtualization | Requires external virtualization | +| **Layout Animation (FLIP / Shared Element)** | Outputs static `Layout { location, size }`; requires framework-level previous-rect diffing | First-class (`matchedGeometryEffect`, `Layout` protocol animatable properties) | Manual (`AnimatedSize`, `Hero` overlay widgets) | Immediate-mode rect output; easy to interpolate `(x, y, w, h)` per ID | Static rect output | + +### 7.2 Measured & Cited Benchmark Numbers + +1. **Taffy (`v0.9.2`) vs Yoga (`v3.2.1`) on Apple M1 Pro (`taffy/README.md:94-114`, Criterion benchmarks):** + - **1,000 nodes (deep hierarchy):** Taffy **1.60 ms** vs Yoga **1.50 ms** (~1.6 µs/node). + - **10,000 nodes (deep hierarchy):** Taffy **17.5 ms** vs Yoga **16.2 ms**. + - **10,000 nodes (super-deep 12-level hierarchy):** Taffy **24.6 ms** vs Yoga **36.2 ms** (**Taffy is 32% faster** due to 9-slot `Cache` in `taffy/src/tree/cache.rs` avoiding exponential re-measurement). + - **100,000 nodes (wide 2-level hierarchy):** Taffy **98.9 ms** vs Yoga **191.5 ms** (**Taffy is 48% faster**). + - **Twitter feed benchmark (`yoga/taffy` real-world cards):** + - 1,500 nodes: Taffy **626 µs** vs Yoga **950 µs** (**1.52x faster**). + - 15,000 nodes: Taffy **6.40 ms** vs Yoga **11.17 ms** (**1.75x faster**). + - 100,000 nodes: Taffy **59.17 ms** vs Yoga **84.42 ms** (**1.43x faster**). +2. **GPUI's Taffy Integration (`zed/crates/gpui/src/taffy.rs:1-315`):** + - GPUI wraps `TaffyTree<NodeContext>` in `TaffyLayoutEngine`, using `FxHashMap<GlobalElementId, NodeId>` and a 2-frame mark-and-sweep (`computed_layouts: FxHashSet<NodeId>`) so unchanged subtrees keep their Taffy nodes and measurement cache across frames instead of rebuilding the Taffy arena from scratch each frame. +3. **Text Measurement Inside Layout (a private iOS layout benchmark):** + - In any real UI, **80–90% of layout wall-clock time is spent inside the leaf `measure_function` (text shaping & line wrapping), not in the Flexbox solver itself.** + - Measuring 500 chat paragraphs on iOS: + - SwiftUI `sizeThatFits`: **106.44 ms** (212.88 µs/item) — blows nine 120 Hz frames (8.33 ms budget). + - Cold CoreText `CTFramesetter`: **17.75 ms** (35.51 µs/item). + - Reused `CTFramesetter` height: **2.60 ms** (5.19 µs/item). + - Pre-computed width-break table (`Pretext`): **0.23 ms** (0.45 µs/item). + +### 7.3 Solving the 3 Hard Layout Cases in Rune + +1. **Agent-Writability:** + - Expose **Tailwind/Flexbox/Grid-aligned builder methods** backed by `taffy` (`flex()`, `flex_col()`, `items_center()`, `justify_between()`, `gap(px(8.))`, `grid_cols(3)`) **plus** ergonomic SwiftUI-style shorthand (`hstack()`, `vstack()`, `zstack()`, `spacer()`) that compile down to the exact same `taffy::Style`. Agents never hit Flutter's dreaded *"RenderFlex children have non-zero flex but incoming height constraints are unbounded"* crash because Taffy gracefully resolves `flex-grow` inside auto-sized containers to content size. +2. **1M-Row Variable-Height Virtualized Lists:** + - Never insert offscreen rows into `TaffyTree`. + - Store the 1M-row list state in a **`SumTree<ListItemSummary>`** (`zed/crates/sum_tree/src/sum_tree.rs`) where each item summary stores `(count: usize, height: f32, is_measured: bool)`: + - Unmeasured items initialize with a fast estimated height (or `LineLayoutCache` unwrapped width / container wrap width estimate). + - Mapping a scroll pixel offset $y \in [0, 50,000,000]$ to the first visible row index is a **$O(\log N)$ `SumTree` seek (~200 nanoseconds for 1M items)**. + - Only the visible viewport rows + overscan buffer (~20–40 rows) are laid out via `Taffy` each frame (< 0.15 ms). When a row's measured height differs from its estimate while scrolling upward, anchor scroll position relative to the first visible item's top edge so the viewport never jumps. +3. **Layout Animation (Spring-Driven Bounds & Shared-Element `layout_id`):** + - Why layout animation is painful in raw Flexbox: Taffy outputs discrete `(location, size)` rectangles per frame. + - **Rune's solution:** Attach an optional `.layout_id(id)` / `.animate_layout(Spring)` to any element. After `Taffy` computes the target layout rect $R_{\text{target}} = (x, y, w, h)$ in window space, Rune's layout-animation pass compares $R_{\text{target}}$ against the previous frame's rendered rect $R_{\text{prev}}$ for that `ElementId`: + - **Position delta ($\Delta x, \Delta y$):** Drive a 2D spring offset on the element's GPU transform matrix (zero re-layout cost!). + - **Size delta ($\Delta w, \Delta h$):** Drive a 2D spring on the element's rendered clip/background bounds while keeping text children anchored (or using `Overflow::FadeMask`) so text never re-wraps on every intermediate frame of a container resize spring! + +--- + +## 8. What to Steal / What to Avoid + +### What to Steal + +1. **Kit's GPUI fork (`kitlangton/gpui`) 5-level Luminance Glyph Dilation (`kitlangton/gpui/src/platform/mac/text_system.rs:42-81, 470-564`, commit `2582af8ad0`):** Quantize text foreground luminance into 5 buckets (`0..=4`), pad glyph bounds by `1px`, and rasterize with `AppleFontSmoothing` / stem darkening scaled to that luminance so light-on-dark and dark-on-light text have optically matched weight. +2. **GPUI's Two-Tier `LineLayoutCache` (`zed/crates/gpui/src/text_system/line_layout.rs:523-698`):** Separate cached unwrapped `LineLayout` (shaping) from `WrappedLineLayout` (wrap boundaries) with two-frame epoch swapping and index-range `reuse_layouts`. Resizing a window or split pane only recomputes line breaks over cached glyph advances, never re-running HarfRust/CoreText shaping. +3. **Zed's `SumTree` (`zed/crates/sum_tree/src/sum_tree.rs`):** Use one battle-tested concurrent B+ tree for both text ropes (simultaneous UTF-8, UTF-16, line/col, and soft-wrap coordinates in $O(\log N)$) and 1M-row virtualized list height indexing. +4. **Parley `v0.12.0` (`parley` + `fontique` + `harfrust` + `skrifa` + `icu4x`):** Use Parley's shaping/bidi/segmentation pipeline (`parley/parley/src/shape.rs`, `layout.rs`, `cursor.rs`) for UAX #9 bidi reordering, UAX #14 line breaking, `InlineBox` layout, and `Affinity`-aware cursor/selection geometry. +5. **Vello `glifo`'s `COLRv1` + `sbix` + `skrifa` Glyph Extractor (`vello/glifo/src/glyph.rs:289-465`, `colr.rs`):** Steal `glifo`'s priority waterfall (`COLRv0/v1` vector paint trees -> `sbix`/`CBDT` PNG bitmaps -> `skrifa` hinted outlines) and size-adaptive subpixel quantization (`SubpixelAxis::Four` at body sizes, `One` at large sizes). +6. **GPUI iOS's `GPUITextInputView` + Deferred `reconcileTextInput` (`zed/crates/gpui_ios/src/ios/text_input.rs:197-318, 1080-1145`) & Flutter's `UIEditMenuInteraction` / Floating Cursor (`FlutterTextInputPlugin.mm:400-950`):** Direct `UITextInput` conformance with `UITextInteraction` and coalesced main-queue delegate reconciliation gives native iOS selection handles, loupe, Scribble, Dictation, and Spacebar trackpad cursor with zero reentrancy bugs. +7. **GPUI Web's 512-Char Sliding-Window `ImeMirror` (`zed/crates/gpui_web/src/ime_mirror.rs:1-130, 412-448`):** Bound hidden `<textarea>` synchronization to $\pm 512$ characters around the selection and position it at the exact caret rect, adding Chromium `EditContext` as a fast path when detected. +8. **AccessKit (`v0.24+`) Across All 5 Platforms (`accesskit/adapters/{macos,ios,android,windows,unix}`):** Emit one `accesskit::TreeUpdate` that simultaneously powers VoiceOver (macOS/iOS), TalkBack (Android), UIA (Windows), AT-SPI (Linux), and Rune's AI agent inspector. + +### What to Avoid + +1. **Avoid absorbing continuous spring scale transforms into the glyph atlas cache key (`vello/glifo/src/glyph.rs:1702-1731`):** Hashing `draw_font_size.to_bits()` during a 120 Hz scale animation rasterizes 60+ transient font sizes per glyph, thrashing the atlas and causing stem-hinting jitter. +2. **Avoid ignoring the `Sel` argument in macOS `doCommandBySelector:` (`zed/crates/gpui_macos/src/window.rs:3515`):** Dropping the Cocoa selector breaks custom `~/Library/KeyBindings/DefaultKeyBinding.dict` bindings and standard Cocoa text movement/kill-ring commands. +3. **Avoid SDF / MSDF for body UI text (`10–16pt`):** MSDF rounds or spikes complex CJK/symbol corners, lacks stem hinting, and has slow CPU generation for dynamic Unicode fallback. +4. **Avoid subpixel LCD (`RGB`) glyph atlases:** Incompatible with layer opacity, rotation, scale springs, OLED subpixel layouts, and modern macOS/mobile compositors. +5. **Avoid hidden native `UITextField` / `NSTextView` overlays for mobile/desktop IME:** They desynchronize selection handles, break custom line heights/inline pills, and fight custom scroll physics. +6. **Avoid per-OS text shapers as the sole layout engine:** Relying exclusively on CoreText on Apple and DirectWrite on Windows causes cross-platform line-wrap differences and `CFAttributedString` allocation overhead (17.8 ms / 500 paragraphs cold vs < 1 ms cached `harfrust` + `LineLayoutCache`). +7. **Avoid putting offscreen virtualized list items into `TaffyTree` or re-running text shaping during width animations:** Use `SumTree` height prefix-sums for offscreen rows and `Overflow::FadeMask` or cached unwrapped glyph advances during animated width transitions. + +--- + +## 9. Decisive Recommendations for Rune + +### 9.1 Architectural Decisions & Rejected Alternatives + +| Sub-Area | Rune Decision | Rejected Alternatives & Why | +|---|---|---| +| **1. Text Shaping & Fonts** | **`harfrust` (`0.14`) + `skrifa` (`0.42`) + `fontique` (`0.8`)**, with a thin platform bridge on Apple to read `.AppleSystemUIFont` (`SF Pro`) `trak` optical tracking tables. | **Rejected `rustybuzz` + `swash`:** `swash` is unmaintained; `rustybuzz` is 10–15% slower and duplicates `ttf-parser` tables.<br>**Rejected CoreText/DirectWrite-only shaping:** Allocates OS objects per run and produces divergent line wraps across platforms. | +| **2. Text Layout** | **`parley` (`0.12`)** wrapped in **GPUI's two-tier `LineLayoutCache`** (unwrapped shaped runs separated from wrapped line boundaries) + first-class **`Overflow::FadeMask`** shader clip alongside `Overflow::Ellipsis`. | **Rejected `cosmic-text`:** Tied to `rustybuzz`/`swash`, lacks `InlineBox` layout.<br>**Rejected naive `Pretext` whitespace width tables:** 29% height mismatch on hyphenated/kerned prose (`opencode-ios-pretext-layout`); caching exact `LineLayout` glyph advances achieves the same sub-millisecond resize speed with 0% drift. | +| **3. Glyph Rendering** | **Two-tier hybrid:**<br>• **Tier 1 (UI Text `<= 28pt`):** Grayscale `R8Unorm` (`RGBA8` for `COLRv1`/`sbix` emoji) shelf-packed atlas with `skrifa` hinting, 4x X-subpixel phases, and **5-level luminance glyph dilation (`kitlangton/gpui`)**.<br>• **Tier 2 (Animated / Hero Text):** Transform-invariant linear-metrics octave sampling for scaled UI containers, and **direct GPU vector paths (`skrifa` outlines -> Vello/Slug)** for hero/per-character animated text (`> 28pt` or `.textRenderMode(.vector)`). | **Rejected SDF/MSDF:** Artifacts on CJK and `11–14pt` UI text.<br>**Rejected LCD subpixel AA:** Breaks transparency and transforms.<br>**Rejected per-frame `draw_font_size` atlas rasterization (`glifo` default):** Thrashes atlas on spring scales. | +| **4. Text Editing** | **Single unified `TextBuffer` built on Zed's `SumTree` + `Rope`**, supporting both `<Input>` and multi-MB `<Editor>`, UAX #29 grapheme/word movement (`icu_segmenter`), `Affinity`-aware bidi carets, 300 ms undo coalescing, and macOS `DefaultKeyBinding.dict` selector dispatch. | **Rejected separate `String` for `<Input>` and `ropey` for `<Editor>`:** Maintaining two cursor/IME/UTF-16/undo stacks doubles surface area for surrogate-pair and IME bugs. | +| **5. Platform IME** | **Direct native protocols per OS:** `NSTextInputClient` (macOS), `UITextInput` + `UITextInteraction` + deferred `reconcileTextInput` (iOS), `InputConnection` + `CursorAnchorInfo` (Android), `ImmGetCompositionStringW`/TSF (Windows), `zwp_text_input_v3` (Wayland), and **512-char sliding-window `<textarea>` + `EditContext`** (Web). | **Rejected hidden `UITextField`/`NSTextField`:** Breaks native iOS loupe/handles/Scribble alignment on custom GPU text.<br>**Rejected `EditContext`-only on Web:** Not supported on Safari/iOS WebKit or Firefox in 2026. | +| **6. Accessibility & Agent Tree** | **`accesskit` (`v0.24+`) across all 5 native platforms**, with the frame's `accesskit::TreeUpdate` + `InspectorMetadata` exposed directly as Rune's **AI Agent Inspector & Automation Tree**. | **Rejected custom per-OS accessibility bridges:** Thousands of lines of duplicated ObjC/JNI/COM glue.<br>**Rejected separate DOM/inspector tree for agents:** Diverges from real screen-reader semantics. | +| **7. Layout** | **`taffy` (`0.9.x`, incremental retained tree) + `SumTree` prefix-sum height virtualizer for lists + built-in FLIP/Spring layout-rect interpolation.** | **Rejected Flutter `BoxConstraints`-only:** Poor LLM ergonomics (`Expanded` in `ScrollView` runtime crashes) and lacks CSS Grid.<br>**Rejected `Clay` / `Morphorm`:** Lack CSS Grid and deep LLM pretraining familiarity. | + +### 9.2 Recommended Rust Crate Dependencies + +```toml +[dependencies] +# Text Shaping, Fonts, Bidi & Segmentation +harfrust = "0.14" +skrifa = { version = "0.42", features = ["std", "autohint_shaping"] } +read-fonts = "0.37" +fontique = "0.8" +parley = "0.12" +icu_segmenter = "2.0" +icu_properties = "2.0" + +# Buffer & Virtualized List Indexing +sum_tree = { path = "crates/sum_tree" } # Forked/extracted from zed/crates/sum_tree +rope = { path = "crates/rope" } # Forked/extracted from zed/crates/rope + +# Layout +taffy = { version = "0.9", features = ["flexbox", "grid", "taffy_tree"] } +etagere = "0.2" # Shelf-packing allocator for glyph & emoji atlases + +# Accessibility (Core + Platform Adapters) +accesskit = "0.24" +[target.'cfg(target_os = "macos")'.dependencies] +accesskit_macos = "0.24" +[target.'cfg(target_os = "ios")'.dependencies] +accesskit_ios = "0.4" +[target.'cfg(target_os = "windows")'.dependencies] +accesskit_windows = "0.31" +[target.'cfg(target_os = "linux")'.dependencies] +accesskit_unix = "0.20" +[target.'cfg(target_os = "android")'.dependencies] +accesskit_android = "0.6" +``` + +### 9.3 Top Risks Ranked + +1. **Risk #1 (High): iOS `UITextInput` + `UITextInteraction` edge cases across iOS 17/18/19 (Scribble, Floating Trackpad Cursor, Autofill, Dictation, Hardware Keyboard).** + - *Why:* UIKit's `UITextInteraction` makes undocumented synchronous re-entrant calls into `UITextInput` during autocorrect and trackpad gestures. + - *Mitigation:* Port `GPUITextInputView` (`zed/crates/gpui_ios/src/ios/text_input.rs`) and its deferred `reconcileTextInput` state machine verbatim, augmented with Flutter's `beginFloatingCursorAtPoint:` (`FlutterTextInputPlugin.mm:780-845`), and test on real iOS Simulator via `fieldwork-prove`. +2. **Risk #2 (High): Cross-platform stem weight & Apple `.AppleSystemUIFont` (`SF Pro`) optical fidelity when moving from CoreText to `harfrust` + `skrifa`.** + - *Why:* Users immediately notice if macOS/iOS text looks 5% thinner, wider, or differently tracked than native SwiftUI/AppKit. + - *Mitigation:* Apply `SF Pro` `trak` table optical tracking in `harfrust` on Apple platforms, and support both CoreGraphics `rasterize_glyph` (with 5-level luminance dilation from `kitlangton/gpui`) on Apple and `skrifa` + stem-darkening dilation on Windows/Linux/Android/Web. +3. **Risk #3 (Medium-High): Animated text jitter and re-wrap stutters during 120 Hz spring layout transitions.** + - *Why:* Naive layout springs re-wrap text at every intermediate width and re-snap glyphs to device pixel grids, causing visible 1px crawling and line-reflow pops. + - *Mitigation:* Enforce two invariants in the renderer: (a) during an active transform spring, disable integer pixel-grid snapping and lock the glyph atlas lookup to unhinted linear-metric outlines at the target octave scale; (b) during animated width transitions, freeze wrap width to the target width (or use `Overflow::FadeMask`) unless explicitly opted into live reflow. +4. **Risk #4 (Medium): Virtualized list scroll-anchor jumping with dynamic streaming markdown/chat rows.** + - *Why:* When unmeasured items above the viewport resolve to a different height than estimated, naive scroll-top offsets jump visibly. + - *Mitigation:* Anchor the scroll state to `(anchor_item_id, pixel_offset_within_item)` in the `SumTree<ListItemSummary>` rather than a raw global `scroll_top` pixel float. +5. **Risk #5 (Low-Medium): AccessKit iOS (`accesskit_ios`) maturity for complex custom gestures and virtualized lists.** + - *Why:* `accesskit_ios` (`v0.4.0`) is the newest AccessKit adapter and requires host cooperation for `accessibilityScroll:` and offscreen buffer nodes. + - *Mitigation:* Keep a 1-viewport semantic overscan buffer in virtualized lists and wire `Action::ScrollIntoView` + `accessibilityPerformEscape` directly into Rune's scroll and navigation primitives. + +--- + +## 10. Open Questions (Requiring Prototype or Benchmark) + +1. **`skrifa` + CPU/GPU stem darkening vs CoreGraphics `CGContext` glyph rasterization on macOS/iOS:** Can `skrifa` (`Target::Smooth` with custom 5-level luminance dilation in our shader/outline dilator) match CoreGraphics `CTFontDrawGlyphs` + `AppleFontSmoothing` pixel-for-pixel on `SF Pro` at `11–15pt` on 2x Retina, allowing us to drop `CGContext` glyph rasterization on Apple entirely, or should we keep `CGContext` rasterization on Apple as an `AppleGlyphRasterizer` backend? *(Needs a side-by-side pixel-diff prototype at 5 luminance levels.)* +2. **Hero vector text threshold (`28pt` vs `36pt`) and GPU cost on mobile:** At what exact point size does rendering unhinted `skrifa` outlines directly through the Vello/Slug GPU path pipeline match or beat the glyph atlas in frame time and memory bandwidth on an iPhone 16 Pro at 120 Hz? *(Needs a GPU frame-time benchmark on iOS device.)* +3. **Android `InputConnection` batch edit behavior on Samsung Keyboard vs Gboard:** Samsung Keyboard issues aggressive `beginBatchEdit` / `setComposingRegion` sequences across word boundaries that differ from Gboard. *(Needs a small Android IME harness test against our `SumTree` UTF-16 offset mapping.)* diff --git a/app/vendor/rune/research/06-reactivity-animation.md b/app/vendor/rune/research/06-reactivity-animation.md new file mode 100644 index 0000000..25f6a13 --- /dev/null +++ b/app/vendor/rune/research/06-reactivity-animation.md @@ -0,0 +1,981 @@ +# 06 — State/reactivity model and animation as a first-class primitive + +Research agent notes, 2026-10-21. Sources are cited inline. Kit's own code is cited by `repo/path:line`. Numbers marked *est.* are estimates, not measurements. + +## Summary + +- **State pick: a keyed retained tree rebuilt from pure view functions, with GPUI-style models and + Xilem-style handlers.** App state lives in typed `Model<T>`s held in a store. Views are plain + `fn(&mut Cx, ..) -> El`. Reading a model through `cx.read` subscribes that view scope. Handlers get + `&mut T` when they run, queued between frames, so there is no `RefCell` re-entry and no + `cx.notify()` to forget. The output is a type-erased `El` tree that is diffed by key. Fine-grained + signals, GPUI's re-render-per-frame and immediate mode are rejected as the *primary* model (see the + recommendation below). +- **Animation is never state.** Animated values never pass through view functions. A view states + *targets*. The diff sees that a target changed and sends `Animate{prop, target, spring}` to a + **render thread**. That thread owns the presented tree, the property tracks, scroll physics and + drag bindings. When one value animates, the main thread does **zero** work: no view re-run, no + layout, no diff. SwiftUI (attribute graph), Core Animation (render server), Compose (deferred + draw-phase reads) and Motion (`MotionValue`s that skip React) all reach for this same split. +- **Every property is a piecewise analytic track.** A segment is `{t0, x0, v0, target, curve}`, and + you sample position *and* velocity at any absolute time. Retargeting = sample `(x, v)` at the + commit's presentation time, then start a new segment from there. This is psychopomp's model + (`psychopomp/crates/psychopomp/src/timeline.rs:143-337`) generalised. It fixes the launcher's problem that Core + Animation can't report velocity (`launcher/src/macos.rs:2735-2777` has to guess "mid-flight" from + heights and fall back to an analytical model). +- **Springs are `Spring::new(duration, bounce)` with ω = 2π/duration and ζ = 1 − bounce** + (1/(1+bounce) when bounce < 0). This matches SwiftUI, Flutter's `withDurationAndBounce`, knobs, + the private iOS client and Kit's generated presets exactly. Each spring is a named token pair (enter/exit) loaded from + Kit's motion presets, and the render thread re-resolves tokens live, so tuning + retargets springs already in flight. +- **Layout animation sits between layout and commit.** Layout runs once, at the target. For each + node whose frame changed, the runtime animates the **edges** (left, right, top, bottom) in + parent space, with one spring per axis. A stationary edge gets no track, so it can't jiggle. Width + leads by giving the X axis a faster spring. Rigid travel stays rigid. Backgrounds, borders, + shadows and glass are parametric shapes drawn at the presented size, so there's no FLIP scale + distortion. +- **Presence and identity are built into the runtime.** Removing a keyed node moves it to + `Exiting{gen}`. By default it leaves layout flow (`popLayout`), plays its exit and unmounts only + after its opacity track has *settled at 0*. If the same key comes back first, the node revives + from where it is now. This is PresenceGate's generation guard + (`PresenceGate.swift:12-69`) applied to every node. +- **Kit's rules become defaults, not discipline.** Direct manipulation applies instantly. Nothing + animates on first mount. Reduced motion is applied per property class by the runtime. Both edges + snap to 1/64 device px on the render thread. Every clip has soft edges by default; a hard clip is + an explicit opt-out that the inspector reports. Persistent items never blur. +- **One clock, with time scaling and manual stepping.** Virtual time is `base + (host − anchor) × + scale` and re-anchors when the scale changes (`scrawl/src/ui/motion.rs:17-53`). Tracks are sampled + at the frame's **target presentation timestamp**. Tests use `Clock::Manual{hz}`, and the frames + come out bit-identical when the math uses deterministic `libm`. +- **The render thread writes motion traces natively** in Scrawl's JSONL format + (`scrawl/src/ui/motion.rs:563-788`): the element tuple `[id,x,y,w,h,a,r,flags,(vis)]`, plus exact + flag and intent bits (the motion linter's `src/analyze.ts:41-43`). The runtime *knows* which changes were + intended, so the internal motion linter no longer has to infer it. Tracing costs nothing when it's off. + +--- + +## Part 1 — State and reactivity + +### 1.1 Criteria (from the brief and the task) + +| Criterion | Why it matters for Rune | +| --- | --- | +| Per-frame CPU when one value animates | 120 Hz means an 8.33 ms budget. Animation must not depend on how complex the view tree is. | +| A 1M-row list | Infinite-software apps: logs, transcripts, mail. | +| Agent-writability | Explicit data flow, few silent failure modes, clear errors, fast compiles. | +| Hot-reload state preservation | Edit to pixels in under 300 ms with state kept, through code patches. | +| Borrow-checker ergonomics | Agents give up, or reach for `Rc<RefCell>`, when lifetimes fight them. | +| Test determinism | Headless rendering, golden frames, golden motion traces. | + +### 1.2 The models compared + +**Fine-grained signals: SolidJS, Leptos `reactive_graph`, Sycamore, Floem.** +Components run once and build a graph of signals, memos and effects. Writing a signal re-runs only +the effects that read it. Rust implementations keep signals in an arena and hand out `Copy` handles, +which removes lifetimes. Floem's `RwSignal` is just an `Id` plus phantom types +(`floem/reactive/src/signal.rs:223-228`), and Leptos 0.7 moved to arena-allocated `Copy` signals +([reactive_graph docs](https://docs.rs/reactive_graph)). +- *One value animating:* the cost is minimal: one effect runs and sets one property. In a native + Rust renderer, though, the property write still triggers a style, layout and paint pass on the + main thread (Floem animates through its style pass; `floem/src/animate/mod.rs`, `easing.rs:208`). +- *1M rows:* a keyed `<For>` diffs the whole source on each change (O(n)), and a signal per row + costs memory (around 100 B or more each, *est.*, so ~100 MB). You still need virtualization; the + signal graph doesn't help there. +- *Agents:* silent failure modes. Reading a signal outside a tracking scope gives a stale UI with no + error. Effects can form cycles, ordering inside a batch is subtle, a disposed signal panics later, + and `move ||` closures are everywhere. +- *Hot reload:* **the worst of the four.** State is captured in closures created by a component body + that runs once. Patching that body means re-running it, which recreates the signals. Leptos + hot-reloads `view!` templates, but a Rust logic change resets state + ([cargo-leptos](https://github.com/leptos-rs/cargo-leptos)). Dioxus 0.7 keeps state across + [Subsecond](https://github.com/DioxusLabs/dioxus/tree/main/packages/subsecond) patches precisely + *because* it re-runs components and stores state in hooks, which is the retained model. +- *Determinism:* fine when single-threaded. + +**Retained tree plus diff: React, Xilem, SwiftUI's AttributeGraph, Compose's slot table.** +View functions are re-run when their inputs change. The result is diffed against the retained tree +by structural identity plus explicit keys, and state lives in slots keyed by that identity. +- *One value animating:* naive React re-renders the component subtree every frame. That's why + framer-motion skips React with `MotionValue`s. The serious systems take animation out of the view + layer. SwiftUI interpolates `Animatable` attributes in the attribute graph without re-evaluating + `body` ([WWDC23 Explore SwiftUI animation](https://developer.apple.com/videos/play/wwdc2023/10156/); + for graph internals see [Rens Breur's reverse engineering](https://rensbr.eu/blog/swiftui-attribute-graph/)). + Compose's `Modifier.graphicsLayer { }` lambda reads state only in the draw phase, so animating it + skips composition and layout ([Compose phases](https://developer.android.com/develop/ui/compose/phases)). + Compose's footgun is that reading the same value during composition silently recomposes every frame. +- *1M rows:* fine when the list is lazy (LazyColumn, `List`). Only visible rows exist as views. +- *Agents:* the best of the four. `view = f(state)` is explicit and testable. The footguns are + React's rules of hooks (order-based identity) and deep generic view types (Xilem's + `View<State, Action, Context>` with `build/rebuild/teardown`, `xilem/xilem_core/src/view.rs:53-90`), + which mean long compiles and unreadable errors. +- *Hot reload:* **the best of the four.** After a patch, re-run every view; state survives because + identity is stable (React Fast Refresh, Compose Live Edit, SwiftUI previews). +- *Borrow checker:* Xilem's handlers receive `&mut State` when they run, which is borrow-free at + compile time. That's the nicest Rust ergonomics I found. + +**GPUI: entities plus whole-view render.** +`Entity<T>` lives in `App`. `render(&mut self, window, cx)` rebuilds the element tree whenever the +view is notified. Layout (Taffy) and paint run for dirty views, and `AnyView::cached` reuses clean +subtrees (`zed/crates/gpui/src/view.rs:46,258`). As of today GPUI has analytic springs +(`crates/gpui/src/spring.rs:13-37`, stiffness/damping/mass) and `with_spring` that keeps position and +velocity per element ID (`elements/animation.rs:119-160`). But every animation frame calls +`window.request_animation_frame()`, which **notifies the current view** +(`window.rs:2742-2745`; `animation.rs:349`). So the view is re-rendered, laid out and painted on the +main thread every frame. +- *Agents:* forgetting `cx.notify()` gives a stale UI. Updating an entity while it's already being + updated panics at runtime. Every call takes `window, cx`. +- *Hot reload:* reasonable. Entity state lives outside the code, but a changed struct layout breaks + Subsecond-style patching. + +**Immediate mode: egui, Clay.** +The whole UI is rebuilt and laid out every frame. Persistent bits sit in ID-keyed memory, such as +egui's `animate_bool`. +- *One value animating:* the full UI is rebuilt on the main thread every frame, around 1–3 ms for a + rich app (*est.*), and nothing can be offloaded to a compositor. It costs battery on a 120 Hz + display. +- *1M rows:* fine with manual virtualization. +- *Agents:* the simplest of the four, and state is just the app struct, which survives hot patching. +- *Gaps:* layout animation, presence and matched geometry all need retained identity and the + previous frame's rects. Once you add those you've rebuilt a retained tree. + +**Summary table** (✓ good, ~ mixed, ✗ poor): + +| | One value animating | 1M rows | Agent footguns | Hot-reload state | Borrow ergonomics | Determinism | +| --- | --- | --- | --- | --- | --- | --- | +| Signals (Leptos/Floem) | ✓ (main-thread effect) | ~ | ✗ silent stale reads | ✗ | ✓ Copy handles | ✓ | +| Retained diff (SwiftUI/Compose/Xilem) | ✓ *if* animation lives below views | ✓ lazy | ✓ (hooks/generics aside) | ✓ | ✓ Xilem-style | ✓ | +| GPUI entity + render | ✗ re-render per frame | ✓ (`list` sum tree) | ~ notify/double borrow | ~ | ~ | ✓ | +| Immediate (egui/Clay) | ✗ full rebuild | ✓ manual | ✓ | ✓ | ✓ | ✓ | + +### 1.3 The pick + +**Retained, keyed, type-erased view tree. Model-granularity auto-tracking. Queued `&mut` handlers. +All animation below the view layer, on a render thread.** + +1. **App state lives in `Model<T>`** (a `Copy` generational handle into the store, owned by the + app). The store is the hot-reload unit: one place to snapshot, serialize and inspect. +2. **Views are plain functions returning `El`.** `El` is a type-erased builder (boxed nodes, no deep + generics), which keeps compiles fast and errors short for agents. `cx.read(model)` returns `&T` + and records a dependency for the current *view scope* (a component function or a list row). + Writing a model marks its readers dirty. There's no manual notify. +3. **Handlers are `move |state: &mut T, event, tx| ..`**, queued and applied in order before the next + build. They can't run while views are being built, so a double borrow can't happen. `tx` holds + the transaction: animation choice, origin, extra model updates. +4. **Local state uses explicit string keys** within a scope: `cx.state("open", || false)`. Rejected: + hook order (React's rules, a classic agent footgun) and `#[track_caller]` positions (Compose-style + positional memoization; a hot patch shifts line numbers and loses the state). A duplicate key in + one scope panics with the scope path in the message. +5. **Identity is the parent path plus an explicit `.key(..)`.** Keys are required on dynamic + children (`list`, `for_each`); without one, the build fails loudly with a message saying how to + fix it. +6. **Values that change every frame never re-run views.** Animations, scroll offsets and drag + offsets are render-thread tracks or `Live<f32>` values (§2.4). Views state targets and + bindings; they never see the per-frame value. If a view needs the presented geometry (hit + testing, "fling from where it is"), `cx.presented(node)` gives a snapshot that is *not tracked*. + This removes Compose's "read in the wrong phase" footgun by design. +7. **Finer invalidation comes later.** A `#[derive(Model)]` can record field-level reads, the way + Swift's `@Observable` does. Model-level tracking is the v1 default because it's simpler and + honest. Agents split models when invalidation is too coarse. + +### 1.4 API sketch (as an agent would write it) + +```rust +use rune::prelude::*; +use rune::motion; // generated from Kit's motion presets: SNAP, SETTLE, REFLOW, GLIDE, MORPH, ... + +#[derive(Model, Default)] // Model = reflect (inspector) + serde (hot-reload migration) +pub struct Mail { + pub threads: Vec<Thread>, // 1M is fine: only visible rows become views + pub selected: Option<ThreadId>, + pub query: String, +} + +pub fn app(cx: &mut Cx) -> El { + let mail = cx.model::<Mail>(); // created once, keyed by type (or cx.model_keyed("inbox")) + let m = cx.read(mail); // this scope re-runs when `mail` changes + col() + .child( + search_field(&m.query) + // direct manipulation: Origin::Direct, so applied instantly (Kit rule 5) + .on_input(mail, |m, text, _tx| m.query = text), + ) + .child(thread_list(mail, m.filtered())) +} + +fn thread_list(mail: Model<Mail>, rows: impl ListSource<Item = Thread>) -> El { + list(rows) // ListSource: len(), key(i), get(i); no Vec<El> + .key(|t| t.id) + .estimated_row_height(56.0) + .row(move |cx, t| { // each row is its own tracked scope, built lazily + let selected = cx.read(mail).selected == Some(t.id); + thread_row(mail, t, selected) + }) + .layout_animation(motion::REFLOW) // siblings slide into gaps, container resizes on a spring + .presence(Presence::pop()) // removed rows exit in place, out of flow +} + +fn thread_row(mail: Model<Mail>, t: &Thread, selected: bool) -> El { + let id = t.id; + row() + .padding(12) + .fill(if selected { theme::ACCENT_SOFT } else { theme::CLEAR }) // a target, not a frame value + .animate(Prop::Fill, motion::SNAP) // node default for this prop + .child(text(&t.subject).weight(if t.unread { 600 } else { 400 })) // overflow: soft right fade + .on_tap(mail, move |m, _ev, tx| { + tx.animate(motion::SNAP); // opt in: a tap that selects isn't dragging the thing itself + m.selected = Some(id); + }) + .on_key(Key::Backspace, mail, move |m, _ev, tx| { + tx.animate(motion::REFLOW); + m.threads.retain(|x| x.id != id); // row exits, siblings slide + }) +} + +fn disclosure(cx: &mut Cx, title: &str, body: impl FnOnce(&mut Cx) -> El) -> El { + let open = cx.state("open", || false); // State<bool>, keyed by scope path + "open" + col() + .child(button(title).on_tap(open, |o, _, tx| { tx.animate(motion::SETTLE); *o = !*o; })) + .child_if(*cx.get(open), body) // enters and exits through presence, height reflows + .resize(Resize::Mask { feather: 28.0 }) +} +``` + +Remote and sync changes go through `app.apply(Origin::Remote, |m: &mut Mail| ...)`. Their default is +*animate with the node's declared spring*, because Kit animates undo, redo and remote changes, not +the user's own hand. + +### 1.5 The 1M-row list + +- `ListSource` is a trait (`len`, `key(i)`, `get(i)`, optional `height_hint(i)`). App data stays in the + app's `Vec`, a database cursor or a rope. **No views and no signals per row.** +- Heights live in a **sum tree** keyed by row (GPUI's `list` does the same). That gives O(log n) + offset↔index lookups, and unmeasured rows use estimates. Measured heights replace estimates with + **scroll anchoring**: the first visible row keeps its screen position, which matters for streaming + transcripts in the private iOS client. +- The main thread materializes the visible rows plus overscan (around 1.5 screens) as row scopes and + diffs them by key: O(visible) per change, not O(n). The render thread scrolls through what is + already there (§2.11) and publishes the offset so the main thread can top up overscan. Running out + of rows (checkerboarding) is a hard problem, below. +- Inserting or deleting in the middle shifts indices but not keys. Presence and layout animation work + on keys, so a deleted row exits and its visible neighbours slide. +- Rough budget (*est.*): 60 visible rows × (view build + diff + incremental layout) ≈ 0.3–0.8 ms on + M-series when a model change touches every visible row; 0 ms per scroll frame between overscan + top-ups. + +### 1.6 Hot-reload state preservation + +- **Code patch, same types** (Subsecond-style jump-table patching; see the hot-reload research doc): + the store and every `cx.state` slot are untouched. The runtime marks every view scope dirty and + rebuilds. The diff reconciles by key, and the render thread's tracks keep running. If a patched + view emits new targets, they **retarget from the current position and velocity**, so you can tune + a value while it's moving. +- **Changed model or state struct layout:** `#[derive(Model)]` includes serde. The runtime + serializes the store and keyed slots, swaps in the new code (or restarts the process) and + deserializes with defaults for new fields. Local `cx.state` slots with an incompatible type reset + one at a time and log the key path. +- **Spring or token edits:** the token table is data (§2.18), so changing it needs no code patch. +- Why the alternatives lose: signals tie state to closures created by run-once component bodies; + hook order and `#[track_caller]` identity break when a patch moves code. + +### 1.7 Determinism and tests + +- A single-threaded build/diff/layout pipeline. Handlers apply in queue order. A deterministic + `HashMap` seed in test builds. +- `TestApp` runs the render thread's frame function **synchronously** on the test thread, with + `Clock::Manual{hz: 120}`. Every frame lands at `n × 1/120 s`. +- Track math uses a deterministic `libm` (no platform `exp`/`sin` differences), so traces and PNGs + are bit-identical on macOS and Linux CI. The extra cost is a few ns per call (*est.*). + +```rust +#[test] +fn deleting_a_row_slides_siblings_and_exits_in_place() { + let mut app = TestApp::new(app).size(390, 844).scale(3.0).hz(120); + app.apply(Origin::Remote, |m: &mut Mail| m.threads = fixtures::threads(5)); + app.settle(); // runs until no track is active + app.focus(key!("thread", 2)).press(Key::Backspace); + let trace = app.record(|app| app.advance(ms(600))); // motion-trace JSONL, in memory + trace.assert_clean(); // pop-in, jump, reversal, fade-cutoff, ... + assert!(app.node(key!("thread", 2)).is_none()); // unmounted only after its exit settled + assert_eq!(app.node(key!("thread", 3)).unwrap().frame().y, 2.0 * 56.0); + insta::assert_binary_snapshot!("after.png", app.png()); +} +``` + +--- + +## Part 2 — Animation as a first-class primitive + +### 2.1 Kit's prior art and what each one teaches + +| Source | What it does | Lesson for Rune | +| --- | --- | --- | +| knobs `src/core/spring.ts:61-73` | `springMotion({duration,bounce})`: ω = 2π/d, ζ = 1−b (1/(1+b) below 0) | The canonical mapping. | +| knobs `spring.ts:1-2, 33-53` | Semi-implicit Euler in fixed 480 Hz substeps, dt clamped to 0.1 s; retarget keeps `v` | Works, but it can't be sampled at an arbitrary *t*. Rune uses closed form. | +| knobs `spring.ts:16-26` | `set(target, delay)`: delayed retargets (cascades); repeating the same target is a no-op | Delays and the no-op rule belong in the track model. | +| knobs `spring.ts:84-96` | Samples a spring into CSS `linear()` | The web backend can bake tracks into `linear()` only where WAAPI offload helps. | +| The private iOS client `SpringSolver.swift:86-90, 96-113, 168-200` (on `origin/main`; the brief's `Core/Utilities/Motion.swift` path doesn't exist, and local `main` is behind) | Closed form for under-, critically and over-damped springs; `retarget(to:preservingVelocity:)` | The exact math Rune's segment uses. Velocity override = gesture handoff. | +| The private iOS client `PresenceGate.swift:12-69` | Mounts immediately on open; unmounts only when *the latest generation's* completion fires while closed | Generation-guarded presence, in the runtime for every keyed node. | +| The private iOS client `PresenceGate.swift:71-97` | Blur forced to 0 at progress ≥ .98 (no offscreen cost at rest), but **kept until unmount on close** so the last frame doesn't flash sharp | Blur filters attach and detach on settle and unmount, never mid-transition. | +| The private iOS client `MotionDisplayLink.swift:4-11, 62-73` | One 80–120 Hz link; `dt` and `now` from `targetTimestamp` through `AnimationTimeScale` | Sample at the predicted presentation time, through the scaled clock. | +| The private iOS client `MotionConstants.swift:10-37` | Every spring and fade is a named, live-tunable token; `reducedFade` .20 s | A token table, not literals. | +| Scrawl `src/ui/motion.rs:17-53` | One clock: `base + elapsed × scale`; changing the scale re-anchors so running ages continue | Clock design, verbatim. | +| Scrawl `motion.rs:58-163, 316-360` | `Tune::DEFAULT` plus `tune.json` polled at 4 Hz in debug builds; presets; `scrawl tune rust` prints a paste-back | Live tuning loop; the source of truth stays in code. | +| Scrawl `motion.rs:551-788` | motion-trace JSONL: header, per-frame `e/m/g/c/cm/ev`, writes only what changed, `SCRAWL_MOTION_TRACE` | Rune emits the same format from the render thread. | +| Scrawl `src/native/pill/model.rs:130-200` | Closed-form critically damped step that **snaps to the target if it would cross it** | Prevents velocity overshoot, but it's a velocity cliff (the motion linter's `stop-dead`). Rune keeps C¹ by default (open question). | +| Scrawl `src/ui.rs:82-95` | `Spring::visual(d, b)` stored in a field called `response` | Naming drift: `response` means different things in psychopomp. Use `duration` everywhere. | +| The launcher `docs/motion.md:41-44` | Pill↔panel morph runs in WindowServer (CA); GPUI renders the panel **once at its final layout**; CA drives clip/scale/blur | Final-layout-once plus animated geometry is FLIP. It works at 120 Hz with zero CPU relayout. | +| The launcher `src/ui/core.rs:2425-2481` | `CaSpringSpec`; velocity **normalized by distance** for `CASpringAnimation.initialVelocity` | Keep velocities in property units; normalize only at a CA boundary. | +| The launcher `core.rs:2483-2522` | `eval_ca_spring_spec_at`: evaluates the CA spring analytically so `CAShapeLayer` paths stay within < 0.02 pt | If Rune mirrors tracks into CA (system glass), it must evaluate the same function. | +| The launcher `core.rs:2604-2705` + `macos.rs:2735-2777` | `compute_ca_interruption_handoff` (called from `src/ui.rs:1461,1695`): the analytical presented state, overridden by `presentationLayer` values only when "mid-flight" is detected by a height heuristic (`h > 34.5 && |h − analytic| < 80`) | **CA doesn't expose velocity, and presentation values are racy.** Rune's render thread owns the analytic tracks, so `(x, v)` is always exact. | +| Kit's motion presets (generated Rust) | `KitSpring{duration,bounce}`, `omega()/zeta()`; enter/exit pairs (`SETTLE` .3/.24, `REFLOW` .4/.32, `MORPH` .3/.16 → .27/.08, …) | Tokens are pairs. Exit springs run 10–25% shorter. | +| psychopomp `crates/psychopomp/src/motion.rs:43-73` | `Spring::sample(initial: MotionState{position,velocity}, target, elapsed)` | Pure sampling from `(x0, v0)`. | +| psychopomp `motion.rs:75-132` | `settling_time`: a deterministic time after which *both* error and speed stay under thresholds (envelope for ζ < 1, bisection for ζ = 1) | Precompute `settle_at` per segment, so finding idle tracks needs no sampling and no hysteresis. | +| psychopomp `timeline.rs:143-248` | Track = list of segments (`Set`/`Spring`/`Ease`); `sample_at` picks the last segment with start ≤ t | The track data structure. | +| psychopomp `timeline.rs:250-337`, `timeline/retarget.rs:62-67, 120-215` | A retarget samples the prior state at its start time; `Animate`/`Replay{from}`/`Immediate`; batches are transactional; "an unchanged Animate request retains its pending due time and existing trajectory" | Retarget semantics: transactional commits; setting the same target again is a no-op. | + +### 2.2 Other frameworks + +- **SwiftUI.** `withAnimation`/`Transaction` attach an animation to a *state change*, and the change + propagates to every animatable attribute it touches. `Spring(duration:bounce:)` is the mapping + above ([docs](https://developer.apple.com/documentation/swiftui/spring)). Springs **merge**: a + retarget keeps velocity ([WWDC23 Animate with springs](https://developer.apple.com/videos/play/wwdc2023/10158/)). + `CustomAnimation` (iOS 17) exposes `animate(value:time:context:)`, `velocity` and `shouldMerge` + ([docs](https://developer.apple.com/documentation/swiftui/customanimation)). Non-merging animations + run alongside the earlier ones and are combined. `matchedGeometryEffect` handles shared elements; + `.transition` with `.blurReplace` covers presence. *Steal:* transactions, merge-by-default springs, + velocity as part of the API. *Avoid:* animations evaluated on the main thread. +- **Core Animation.** A model tree and a presentation tree. Implicit animations come through actions + and are batched by `CATransaction`. Interpolation runs out of process in the render server + (`backboardd` on iOS, WindowServer on macOS), so a main-thread hitch doesn't stall motion. UIKit + made animations interruptible with **additive** animations + ([WWDC14 #236](https://developer.apple.com/videos/play/wwdc2014/236/)) and + `UIViewPropertyAnimator` ([WWDC16 #216](https://developer.apple.com/videos/play/wwdc2016/216/)). + `CASpringAnimation(perceptualDuration:bounce:)` arrived in iOS 17 + ([docs](https://developer.apple.com/documentation/quartzcore/caspringanimation/init(perceptualduration:bounce:))). + *Steal:* the off-main render thread, model/presentation split, atomic transactions. *Avoid:* no + velocity readback (the launcher's workaround above), no determinism, Apple-only. +- **Compose `Animatable`.** `animateTo(target, spec, initialVelocity = velocity)` cancels the running + animation and continues from its current value and velocity. `animateDecay` handles flings + ([docs](https://developer.android.com/develop/ui/compose/animation/value-based#animatable)). Deferred + reads in `graphicsLayer {}` skip composition and layout. *Steal:* the retarget signature and phase + separation. *Avoid:* leaving phase choice to the author. +- **Motion (framer-motion).** `layout` does FLIP with transforms plus *scale correction* for + border-radius, shadows and children. `layoutId` handles shared elements, `AnimatePresence + mode="popLayout"` lets exits leave layout flow, and `LayoutGroup` coordinates siblings + ([layout docs](https://motion.dev/docs/react-layout-animations)). It computes deltas in a + projection tree so nested elements don't drift. Note that Motion's `visualDuration` = SwiftUI + duration / 1.2 (Kit's motion rules). *Steal:* popLayout, layoutId, projection to keep paths + straight. *Avoid:* scale-based FLIP, which distorts text and needs corrections. Rune draws + shapes parametrically instead. +- **Flutter.** `AnimationController` ticks on the UI (now main) thread with `Simulation`s + (`SpringSimulation`, `FrictionSimulation`), and the raster thread only draws. Since 3.29 (iOS and + Android) and 3.35 (macOS and Windows), Dart runs on the platform main thread, giving up a separate + UI thread for synchronous platform interop + ([breaking change](https://docs.flutter.dev/release/breaking-changes/macos-windows-merged-threads)). + So Flutter animations hitch whenever the main thread does. `SpringDescription.withDurationAndBounce` + matches SwiftUI (`flutter/packages/flutter/lib/src/physics/spring_simulation.dart:70-82`). Its scroll + physics are the best open reference (§2.11). *Steal:* the simulation trait, scroll physics, velocity + trackers. *Avoid:* animation evaluated on the main thread. +- **Rive.** State machines with typed inputs (bool, number, trigger), transitions with their own + duration, interpolation and interruptibility, blend states, and `advance(dt)`, which is + deterministic (`rive-runtime/src/animation/`, e.g. `state_machine_instance.cpp`, + `blend_state_1d.cpp`). *Steal:* a transition table keyed by (from-phase, to-phase), the right shape + for Scrawl-style pills with phases. Rive files could become a node type later. +- **GPUI.** Springs now exist (above), but they're evaluated on the main thread inside + `request_layout`, which forces a view re-render every frame. *Avoid* that structure. +- **Xilem/Masonry.** `on_anim_frame(elapsed_ns)` runs as a pass over the widget tree on the main + thread (`xilem/masonry_core/src/passes/anim.rs:11-51`). It's fine for simple widgets, but nothing + happens off-thread. + +### 2.3 Spring math (normative) + +``` +Spring::new(duration d, bounce b): ω = 2π / d + ζ = 1 − b (b ≥ 0) + ζ = 1 / (1 + b) (b < 0) +mass 1, stiffness k = ω², damping c = 2ζω +Δ = x0 − T +ζ < 1: ωd = ω√(1−ζ²); x(t) = T + e^{−ζωt} (Δ cos ωd t + (v0 + ζωΔ)/ωd · sin ωd t) +ζ = 1: x(t) = T + (Δ + (v0 + ωΔ) t) e^{−ωt} +ζ > 1: r1,2 = −ω(ζ ∓ √(ζ²−1)); c1 = (v0 − r2Δ)/(r1 − r2), c2 = Δ − c1; x = T + c1 e^{r1 t} + c2 e^{r2 t} +v(t) is the analytic derivative (SpringSolver.swift:168-200). +``` + +- **Units:** velocity is property units per second (pt/s, opacity/s). It's normalized only when a + CA mirror needs it (the launcher `core.rs:2441-2454`). +- **Settling:** each segment stores `settle_at = t0 + settling_time(x0, v0, T, ε_pos, ε_vel)` using + psychopomp's bound (`motion.rs:75-132`). `ε_pos` comes from the property class and is set *below the + snap quantum*: 1/128 device px for geometry, 1/512 for opacity, 1/64 px for blur. So the final snap + to `T` is invisible. After `settle_at` the track returns exactly `(T, 0)` and is retired. +- **Conversions** at the boundaries: psychopomp's `SpringPlan::visual` multiplies duration by 1.2, + and Motion divides by 1.2 (Kit's motion rules and presets). Rune stores + `(duration, bounce)` and exports ω and ζ. +- **Other curves**, as segment kinds that sample analytically: + - `Decay{k}` (fling, scroll inertia): `x = x0 + v0/k · (1 − e^{−kt})`, `v = v0 e^{−kt}`. + - `Tween{dur, cubic}` (fades, reduced motion): velocity from the curve's slope, as psychopomp's + `Ease` does. + - `Rubber{..}` (overscroll). + - `Bound(live, expr)` (render-thread binding). + - `Fixed`. + +### 2.4 Runtime architecture + +``` + platform main thread render thread (one per display) + ┌──────────────────────────────────────────────┐ commits ┌────────────────────────────────────────┐ + │ input pump ─┬─ live-binding input ───────────┼────────────▶│ vsync (CAMetalDisplayLink / CVDL / rAF)│ + │ └─ app events → handler queue │ (SPSC, │ 1 drain commits with apply_at ≤ T │ + │ apply handlers (&mut models, tx) │ lock-free)│ 2 drain forwarded input → Live values │ + │ rebuild dirty view scopes → El │ │ 3 step scroll sims & bindings │ + │ diff by key → node ops │ │ 4 sample tracks at target time T │ + │ incremental layout (target frames) │ │ 5 world xforms → 2-edge snap → masks │ + │ layout-animation planner → Animate ops │ │ 6 encode + submit GPU, present at T │ + │ text shaping / display lists for changed │◀────────────┤ 7 publish presented snapshot (triple │ + │ content only │ events │ buffer); Settled/Exited/Release evts │ + │ build Commit{apply_at, ops} │ │ 8 trace frame (if on); sleep if idle │ + └──────────────────────────────────────────────┘ └────────────────────────────────────────┘ +``` + +**On the render thread:** +- sampling every track; +- scroll position integration (decay, rubber band, spring-back, paging snap); +- 1:1 drag bindings; +- matched-geometry flights; +- world transforms; +- two-edge snapping; +- soft-mask and blur parameters; +- compositing and encoding of already-recorded display lists and glyph runs; +- presentation timing; +- trace output. + +**Not on the render thread:** +- app logic, handlers and view functions; +- diff; +- layout; +- text shaping and line breaking; +- deciding a fling's target (the main thread decides; the render thread bridges, §2.10); +- accessibility tree; +- platform calls. + +This matches Core Animation's split: the app builds the model tree, and the server interpolates and +composites. + +**Why app logic stays on the platform main thread:** platform interop (text input, accessibility, +menus) is synchronous. Flutter merged its threads for exactly this reason. Animations stay smooth +while the main thread hitches, because the render thread keeps sampling and content updates simply +land a frame late. The input latency of render-thread-owned gestures still depends on the main +thread pumping events quickly. That pump is a tiny forwarder, kept apart from app work by +budgeting: rebuild and layout are time-sliced, and text shaping is async (open question 1). + +**Data structures** (render thread): + +```rust +#[derive(Copy, Clone)] struct NodeId(u32 /*index*/, u32 /*generation*/); +#[repr(u8)] enum Prop { L, T, R, B, Opacity, Blur, Scale, Rotation, Radius, + FillL, FillA, FillB, FillAlpha, MaskFeather, Custom(u8) } + +#[derive(Copy, Clone)] +enum Curve { + Spring { omega: f32, zeta: f32, token: TokenId }, + Decay { k: f32 }, + Tween { dur: f32, cubic: [f32; 4] }, + Rubber { min: f32, max: f32, dim: f32, c: f32 }, + Bound { live: LiveId, expr: ExprId }, // tiny pure expression, not a closure + Fixed, +} +#[derive(Copy, Clone)] +struct Segment { t0: f64, x0: f32, v0: f32, target: f32, curve: Curve, settle_at: f64 } +struct Track { seg: Segment, pending: Option<(f64 /*due*/, Segment)>, gen: u32 } // knobs-style delay +struct Animator { + tracks: SlotMap<TrackId, Track>, // ~48 B each (est.) + by_prop: HashMap<(NodeId, Prop), TrackId>, + active: Vec<TrackId>, // compacted on settle; a timer wheel on settle_at if large +} +``` + +Colour channels animate in OKLab, so a hue change doesn't pass through grey. Rects animate as edges +(§2.7). + +**Commit protocol** (main → render, applied atomically at one frame, like `CATransaction`): + +```rust +struct Commit { id: u64, apply_at: f64 /* target presentation time */, origin: Origin, ops: Vec<Op> } +enum Op { + Insert { node: NodeId, parent: NodeId, index: u32, props: PropSet, content: ContentId }, + Remove { node: NodeId, exit: Option<ExitSpec>, gen: u32 }, + Revive { node: NodeId, gen: u32 }, + Set { node: NodeId, prop: Prop, value: f32 }, + Animate { node: NodeId, prop: Prop, target: f32, curve: Curve, + velocity: Velocity /* Inherit | Override(f32) */, delay: f32 }, + Content { node: NodeId, display_list: Arc<DisplayList> }, + Bind { node: NodeId, prop: Prop, live: LiveId, expr: ExprId }, + Matched { ns: u32, id: u64, incoming: NodeId, mode: MatchMode }, + Clip { node: NodeId, shape: RRect, feather: [f32; 4] }, +} +``` + +`apply_at` is the next target presentation time at least one render lead (≈ 2 ms) after the commit +is ready. Every op in a commit starts on the same frame. Kit's rule that the pill width and the word +roll start together holds by construction. + +**Per-frame cost when one value animates** (*est.*, M-series): +- main thread: 0; +- render thread: drain plus one closed-form sample (~30 ns), world-transform update for that subtree, + snap, and re-encoding of the scene; +- the scene encode dominates (renderer doc), and 10,000 concurrently animating tracks still sample in + about 0.3 ms. + +When nothing is active, no commits are pending and no scroll or binding is live, the display link is +paused: zero idle CPU (Kit's idle rule). + +### 2.5 How a property gets an animation (resolution order) + +When the diff finds that a node's target for `prop` changed, the runtime decides between `Set` and +`Animate` in this order: + +1. **Transaction override.** `tx.instant()` → `Set`. `tx.animate(spring)` or + `tx.prop(Prop::Opacity, curve)` / `tx.axis(Axis::X, spring)` → that curve. +2. **Origin policy.** `Origin::Direct` (typing, dragging, arrow-key selection and other changes made + with the user's own hand) → `Set` unless the transaction opted in. `Origin::Undo | Redo | Remote | + System` → continue to step 3. (Kit rule 5.) +3. **The node's declared default**, `.animate(Prop::Fill, motion::SNAP)`, or the inherited + `.layout_animation(..)` / `.presence(..)`. +4. **Otherwise `Set`.** Nothing animates unless something asked for it. +5. **First mount.** Nodes inserted in a scope's first build (`Mount::Initial`) always `Set` (`initial + = false`, Kit rule 6). Descendants inserted together with an animating parent don't animate on + their own; they ride the parent, which avoids cascades. +6. **Reduced-motion filter** (§2.12) is applied last. + +Spring *pairs* (enter/exit tokens) are resolved by direction. Presence exits and `open → closed` +toggles (`child_if`, `.open(bool)`) use `.exit`; everything else uses `.enter`. + +### 2.6 Retargeting + +```rust +fn retarget(track: &mut Track, at: f64, target: f32, curve: Curve, vel: Velocity) { + let (x, v) = track.seg.sample(at); // exact, analytic + if target == track.seg.target && curve.same_params(&track.seg.curve) && vel.is_inherit() { + return; // psychopomp: unchanged Animate keeps trajectory + } + let v0 = match vel { Velocity::Inherit => v, Velocity::Override(g) => g }; + track.seg = Segment::new(at, x, v0, target, curve); // recomputes settle_at + track.gen += 1; +} +``` + +- **Sample-and-restart, not additive stacking.** Springs are linear ODEs. Restarting from the sampled + `(x, v)` with the same spring gives *exactly* the motion UIKit's additive animations add up to, + while using one segment per property, O(1) evaluation and no growing stack. A different spring on + retarget is also C¹ (position and velocity continue). Only acceleration jumps, which nobody can see. +- `at` is the commit's `apply_at`. Main and render threads agree on it, so a test can predict the + exact frame. +- Changing a token while tracks are live retargets every live track using that token, at the + current frame, to the same target with the new ω and ζ. Live tuning is therefore smooth. +- Reversing mid-flight keeps velocity. There's no snap back to the start (Kit's motion checklist). + +### 2.7 Layout animation with the layout engine (FLIP done natively) + +Layout (Taffy-like, incremental, with two-edge rounding) runs **once, at the target state**. Then +the planner runs on the main thread: + +``` +for node in layout.changed_nodes(): // frames in parent space, device-rounded + old = node.prev_target; new = node.target + policy = resolve(tx, node) // §2.5, gives per-axis springs or Set + for axis in [X, Y]: + (e0, e1) = edges(old, axis); (n0, n1) = edges(new, axis) + spring = policy.axis_spring(axis) // "width leads": X faster than Y + if e0 != n0: Animate(node, axis.start_edge, n0, spring, Inherit) + if e1 != n1: Animate(node, axis.end_edge, n1, spring, Inherit) + // an unchanged edge gets no op at all, so it can't jiggle +``` + +- **Edges, not origin plus size.** Animating `(x, w)` with different springs moves an "anchored" + edge: `x + w` drifts when x and w ride different curves. With edge tracks: + - a stationary edge has no track; + - rigid travel (both edges moving by the same Δ on the same spring with equal velocities) stays + rigid, even across retargets; + - two-edge snapping (§2.13) falls out of this directly. +- **Parent-relative by default.** If a child's parent-relative frame doesn't change, it rides its + parent with no tracks of its own. +- **Straight paths (Kit rule 12).** One transaction gives every layout track the same spring and the + same `t0`. With zero initial velocity, the composed screen path is `start + (end − start)·s(t)` for a + single shape `s`, so it's a straight line. When that can't hold (different springs, or retargets + with mixed velocities) use `.travel(Travel::Screen)`. Then the node's edges are tracked in the + **space of the transaction's common ancestor** and converted to parent space at sample time using + the parent's *presented* transform, which is Motion's projection idea. Matched-geometry flights + always use screen space. +- **Content while a container resizes** is chosen per node with `.resize(..)`: + - `Resize::Shape` (default for surfaces): background, border, shadow, radius and glass are + parametric primitives drawn at the presented rect every frame. That's free, and nothing is + scaled. + - `Resize::Mask{feather}` (default for clipping containers): children are laid out at the target + and revealed by a soft-edged mask that follows the presented rect (OpenCode's `TopAnchoredRow`, + Kit's motion patterns #6; the launcher's "static final-layout render"). + - `Resize::Scale`: FLIP scale for media and thumbnails only. + - `Resize::Relayout`: re-runs layout per frame with interpolated constraints on the main thread. + Opt-in only, for text that must reflow. The inspector flags it as main-thread-per-frame. +- **Siblings sliding into gaps** need nothing extra. When the removed row leaves flow (popLayout), + the siblings' targets change, so their edges animate on the transaction's spring (`REFLOW`). +- **Row growth** (streamed text, images loading): a `.growth(Growth::capped(max_speed, max_accel))` + policy implements OpenCode's `RowGrowth`/`GrowthRide` (Kit's motion patterns #5). It caps speed per + frame and cuts immediately on catch-up bursts. + +### 2.8 Presence (exits that stay mounted, identity by key) + +The main-thread node phase is `Present | Exiting{gen}`. + +- **Removal.** When a keyed child disappears from the view output, the node's phase becomes + `Exiting{gen+1}`. + - `Presence::pop()` (the list default) takes it out of layout flow at its last presented rect in + parent space. Siblings reflow. + - `Presence::hold()` keeps it in flow and collapses its slot along the main axis with a mask. + - `Op::Remove{exit: ExitSpec, gen}` sends the exit targets on the exit spring. The defaults are + opacity → 0, blur → 4 px and scale → .96 on `SETTLE.exit` (.24/0, 20% shorter than enter). +- **Unmount.** The render thread sends `Exited{node, gen}` when the node's exit tracks pass + `settle_at`. The main thread drops the node **only if** its phase is still `Exiting{gen}`. So + nothing ever unmounts at opacity > 0. The blur filter stays attached until unmount, so the last + frame doesn't flash sharp (`PresenceGate.swift:76-79`). +- **Revive.** If the same key comes back while it's exiting, the node returns to `Present` with + `gen+1` (the late `Exited` is ignored). Its props retarget back to rest from their current values + and velocities, and it isn't remounted. Identity is preserved. +- **Enter.** An insert after first mount starts at the enter-from props (opacity 0, blur 4, scale .96) + and animates to rest in the same commit. `.enter_from(anchor)` makes an item that was hidden + *behind* another start under the anchor's presented rect and travel a straight path, drawn beneath + it (Kit rule 12). +- **Persistent items never blur.** Blur is only part of enter and exit specs. Nodes that move because + of layout have no blur track. Validation clamps presence scale to ≥ .9 and rejects scale 0. +- **Nesting.** Children of an exiting parent ride the parent's exit and aren't exited on their own. + Opt out with `.exit_independently()`. + +### 2.9 Shared-element and matched geometry + +- `.matched(ns, id)` — **move.** In one commit, when node A with `(ns, id)` leaves and node B with the + same id arrives, B's edges start at A's *presented screen rect* and velocities, converted to B's + space, and animate to B's layout target. A hides instantly. While in flight, B is drawn in a + **flight layer** at the transaction's common ancestor, so it isn't clipped by a scroll container it + is leaving. Its own soft masks still apply (z-order is an open question). +- `.morph(ns, id)` — **one shape** (Kit rule 9, Liquid Glass `matchedGeometry`, Kit's motion patterns + #9). The *surface* (rect, radius, fill or glass) is a single primitive that interpolates from A's + presented shape to B's. A's content fades out with blur, riding the surface, and B's content fades + in on a short lead. Width leads through the X-axis spring (launcher morph: `width_vd = 0.78·vd`, + `docs/motion.md:47-50`). +- Under reduced motion both become a .15–.2 s crossfade in place (Apple's `.materialize` analogue). + +### 2.10 Gestures and velocity handoff + +```rust +let offset = cx.live("drawer.y", 0.0); // Live<f32>: render-thread owned, keyed +drawer() + .translate_y(offset) // Bind op: no view re-run while dragging + .draggable(Axis::Y, offset, Bounds::new(0.0, 640.0).rubber_band()) + .on_release(ui, move |u, fling, tx| { // main thread decides the target + let land = fling.projected_y(Decel::IOS_NORMAL); // x + v/1000 · r/(1−r) + u.drawer_open = land < 320.0; + tx.animate_live(offset, if u.drawer_open { 0.0 } else { 640.0 }, motion::GLIDE) + .velocity(Velocity::Inherit); // keep the live velocity + }) +``` + +- **During the drag** (render thread): pointer deltas apply 1:1 to the `Live` value. That's the + user's hand, so there's no spring (Kit rule 5). The only exception is an opt-in `follow` spring + (palette: ω 34, ζ .86 lead). +- **Velocity estimation** uses platform event timestamps (not arrival time) and coalesced touches. + - The default is least squares over the last 100 ms and 20 samples, treating 40 ms of silence as + stopped (Flutter `velocity_tracker.dart:142-144`). + - On iOS, scroll flings use UIScrollView-like weights over the last three deltas, 0.6/0.35/0.05 + (`velocity_tracker.dart:295-369`). + - On macOS: 0.15/0.65/0.2 (`velocity_tracker.dart:416-439`, fetched from flutter `master`). +- **The release bridge.** The main thread's decision arrives one or two frames late. So on release + the render thread immediately continues the `Live` value as a `Decay{k}` with the release velocity. + When the main thread's `Animate{velocity: Inherit}` lands, it retargets from the decay's exact + `(x, v)`. The result is C¹ with no stall at release, which is the problem UIKit solves by running + everything on the main thread. +- **Projection.** Use `fling.projected(rate)` with the iOS formula from + [WWDC18 Designing Fluid Interfaces](https://developer.apple.com/videos/play/wwdc2018/803/), so the + target snap point respects the user's momentum. + +### 2.11 Scroll physics per platform + +A `ScrollPhysics` trait produces segment kinds for the render thread. Scroll offset is a `Live` value +the render thread owns, and the main thread gets offset snapshots for virtualization and +non-blocking `on_scroll` events. + +| Platform | Inertia | Overscroll | Notes | +| --- | --- | --- | --- | +| iOS | `v(t) = v0 · r^(t_ms)`, r = 0.998 normal / 0.99 fast ([UIScrollView.DecelerationRate](https://developer.apple.com/documentation/uikit/uiscrollview/decelerationrate-swift.struct)); as `Decay{k}` with k = −1000·ln r ≈ 2.002 s⁻¹; Flutter uses the same constant, `0.998^1000 ≈ 0.135` (`scroll_simulation.dart:50-56`) | Rubber band `f(x) = (1 − 1/(x·c/d + 1))·d`, c = 0.55, d = viewport dimension ([Grant Paul, 2012](https://twitter.com/chpwn/status/285540192096497664), older but still the reference); release out of range → spring back, ζ ≈ 1 (Flutter default ≈ mass .5, k 100, ζ 1.1, `scroll_physics.dart:434-438`) | Hand off to the spring at the edge with friction velocity capped at 5000 pt/s (Flutter `maxSpringTransferVelocity`, `scroll_simulation.dart:79-81`). Paging = projected target snapped to a page, spring with inherited velocity. | +| macOS | **The OS generates momentum.** Trackpad `NSEvent`s carry `phase` and `momentumPhase` with system-computed deltas, which must be applied 1:1, not re-simulated | While the gesture or momentum pushes past the edge, apply the elastic formula to the deltas; spring back when the momentum phase ends | Mouse wheel (non-precise) deltas: animate line steps on `instant` (.1/0). Never double-apply inertia. | +| Android | Spline fling (`SplineOverScroller`): decel rate ln(.78)/ln(.9), inflexion .35, physical coefficient ≈ 9.8·39.37·ppi·0.84 (Flutter port `scroll_simulation.dart:201-259`) | Android 12+ **stretch** `EdgeEffect` (scale toward the edge), not glow | Velocity in px/s against ppi. | +| Windows | DirectManipulation supplies inertia for precision touchpads | Clamp or optional bounce | Wheel = discrete steps on `instant`. | +| Web | Wheel deltas on macOS *already include* OS momentum; touch is browser-native | Emulate per the host OS (UA-detected) | When possible, back the scroll container with a native scroller and read its offset. | + +Every scroll viewport gets soft edge masks: 24 pt by default on edges where content overflows. The +mask strength is `min(1, overflow/feather)`, so it ramps in instead of popping (Kit rule 11). The +mask is attached to the viewport, not the content (Kit's "edge travel" rule). Scrolling runs on the +render thread, so checkerboarding is possible. The mitigations are an overscan sized to the current +scroll velocity and a placeholder skeleton (hard problem 3). + +### 2.12 Reduced motion + +The runtime applies it per property class, so authors can't forget it: + +| Class | Under Reduce Motion | +| --- | --- | +| Spatial (edges, translate, scale, rotation, layout animation, matched flights, programmatic scroll) | `Set` (no travel) | +| Opacity, presence enter/exit | Opacity-only `Tween` of .15–.2 s (token `motion::REDUCED_FADE`; OpenCode `reducedFade` .20, `MotionConstants.swift:33-37`; the launcher 75 ms, `docs/motion.md:78`) | +| Blur | 0 (and the filter is never attached) | +| Morph | Crossfade in place | +| User's hand (drag, fling inertia, trackpad momentum) | Unchanged: it's the user's own motion | +| Continuous loops (shimmers, orbs) | Hold a calm static pose that still shows state | + +The source is the OS setting (`accessibilityReduceMotion`, `prefers-reduced-motion`, Android +animator scale). Tests can override it: `TestApp::reduce_motion(true)`. + +### 2.13 Two-edge 1/64 px snapping + +This runs as the last step on the render thread, in device pixels. For axis-aligned world transforms, +`x0 = grid(left)` and `x1 = grid(right)`, and width is *derived* as `x1 − x0`, where +`grid(v) = round(v·64)/64` (Kit's motion patterns #3; Signal desk v3 `autocomplete.js`). With +rotation or non-uniform scale, only the translation is snapped. + +At rest, layout has already rounded both edges to device pixels using the same cumulative two-edge +pattern Taffy uses (`taffy/src/compute/mod.rs:381-393`: `size = round(cum + w) − round(cum)`). So the +moving 1/64 grid and the resting pixel grid agree, and a node lands with no final shift. Settle +thresholds sit below the quantum (§2.3). + +### 2.14 Soft-edge masks everywhere + +- **The clip primitive** is `Clip{shape: RRect, feather: [l, t, r, b]}`, evaluated as an SDF ramp in + the composite shader. It costs a few ALU ops per pixel. Nested clips multiply. +- **Defaults:** + - scroll viewports: 24 pt on overflowing edges, ramped (§2.11); + - text overflow: a 1.5 em right-edge fade, never an ellipsis; + - panels and cards clipping children: a 16 pt inner fade on the clipping side; + - rounded corners: an anti-aliased SDF, so no stair-steps. +- **Hard clips** need an explicit `.clip_hard(reason)`. The inspector and the trace (`flags.clipped` + plus the `vis` rect) let the internal motion linter flag unmasked cuts. Every clipping ancestor and axis is + checked, matching the skill's audit rule. +- **Group isolation.** When a masked subtree has overlapping translucent children, it's rendered to + an offscreen layer, which the renderer can do automatically (renderer doc). + +### 2.15 Blur and scale for enter and exit + +- **Defaults:** + - whole-element replacement in place: 3–4 px blur, scale ≈ .96, plus opacity; + - exits run 10–25% shorter; + - persistent and sliding content stays sharp. +- **Blur cost.** Blur is a filter on an offscreen layer (dual-Kawase at reduced resolution, radius + ≤ 8 px). It's attached when a blur track becomes non-zero and detached when it *settles* at 0. + On exit it stays until unmount. Resting UI pays no blur cost (the launcher removes `CAFilter`s at rest, + `docs/motion.md:43`; `PresenceGate.swift:92-97`). + +### 2.16 One clock, time scaling and deterministic stepping + +```rust +enum ClockSource { Display, Manual { hz: f64 } } +struct Clock { anchor_host: f64, base: f64, scale: f64 } // τ = base + (host − anchor)·scale +impl Clock { + fn set_scale(&mut self, s: f64, host_now: f64) { // re-anchor (scrawl motion.rs:42-53) + self.base += (host_now - self.anchor_host) * self.scale; + self.anchor_host = host_now; + self.scale = s.clamp(0.02, 4.0); + } +} +``` + +- **Every** consumer reads τ: tracks, scroll simulations, presence timing, trace `t` and `sc`. Slow + motion is truthful only when every clock scales together (Kit's motion patterns #12). If a CA mirror + is used, its `layer.speed` and `timeOffset` get re-anchored in the same step. +- Frames are sampled at the display link's **target presentation timestamp** + (`CAMetalDisplayLink`/`CADisplayLink.targetTimestamp`; `MotionDisplayLink.swift:62-68`). Tracks + sample absolute time, so a hitch lands motion where it should be, which is CA's behaviour. + Eye-tracked flights can opt into a dt clamp (Kit's motion patterns #1). +- `Manual{hz}`: `app.advance(ms(500))` steps exact frames, `app.settle()` runs until there are no + active tracks, and `app.frame()` steps one frame. + +### 2.17 motion traces + +Turn it on with `RUNE_MOTION_TRACE=<file>`, mirroring `SCRAWL_MOTION_TRACE` +(`scrawl/src/ui/motion.rs:551-561`). When it's off it costs one `OnceLock` read. In tests, +`app.record(..)` returns the trace in memory. The render thread writes after step 5, so the trace +records **exactly what was presented**: post-snap and post-mask. + +```jsonc +{"type":"header","launch":"mail","width":1512,"height":982,"hz":120,"scale":2, + "platform":"rune-macos","units":"pt","clock":"virtual"} +{"t":1234.567,"n":1,"sc":1, + "ev":["tx#41 Direct tap thread:7 SNAP","retarget thread:3.T REFLOW v=-212.4"], + "ai":[[12,16,112,358,56,2,400]], // intent: [id,x,y,w,h,bits,ms] from Animate ops + "m":[{"id":12,"cls":"row","nm":"thread:3","host":"list:inbox","pv":4}], + "e":[[12,16,140.25,358,56,1,8,258]], // [id,x,y,w,h,alpha,radius,flags,(vis x,y,w,h)] + "g":[9], // unmounted (only after its exit settled) + "cm":[{"id":1,"name":"scroll:inbox","kind":"position"}],"c":[[1,840.5]]} +``` + +- **Flags** use the motion linter's bits (`analyze.ts:41-43`): animated 1, ancestorAnimated 2, scrolling 4, + clipped 8, filtered 16, occluded 32. Intent classes are packed at `<<8` (own) and `<<16` + (ancestor): position 1, size 2, opacity 4, shape 8, transition 16, reveal 32, contents 64. + Rune sets them from the actual track kinds, so the motion linter's "was this intended?" logic gets the + truth instead of a guess. +- **Events** carry the commit id, origin, token name and retarget velocities. Channels carry scroll + offsets and, optionally, per-track progress. +- **Scrubbing.** The runtime can also emit a *sweep*: sample a recorded commit sequence at any τ + without running the app. Tracks are pure, which gives the motion linter's `sweepClock` the same power + natively. +- **In-process invariants in debug builds.** "Unmount at opacity > 0" is impossible by construction. + Warnings fire for a visible `Set` of a spatial prop whose origin isn't Direct (a likely pop), a + `.clip_hard` without a reason, and blur on a persistent node. + +### 2.18 Live tuning and tokens + +- `motion::*` constants are *token ids* whose defaults are generated from Kit's motion presets + (generated Rust today). The render thread resolves tokens through a `TokenTable`. +- Debug builds watch `~/.config/<app>/tune.json` (Scrawl's loop, `motion.rs:316-360`) and accept a + knobs remote over WebSocket. A change retargets live tracks (§2.6). +- `rune tune rust` prints the paste-back for the token defaults (`scrawl tune rust`, + `motion.rs:442-455`). +- The trace logs token names, so a clip can be matched to the knob that produced it. + +### 2.19 Public animation API (a summary) + +```rust +// springs +Spring::new(0.30, 0.0) // duration, bounce +SpringPair { enter: Spring::new(0.30, 0.16), exit: Spring::new(0.27, 0.08) } // motion::MORPH + +// transactions (inside handlers) +tx.animate(motion::MORPH).axis(Axis::X, motion::SNAP) // width leads + .prop(Prop::Opacity, Curve::fade(0.16)).delay(Prop::Opacity, 0.012); +tx.instant(); +tx.animate_live(live, target, spring).velocity(Velocity::Override(v)); + +// node modifiers +.animate(Prop::Fill, motion::SNAP) +.layout_animation(motion::REFLOW) +.presence(Presence::pop().enter(Fx::fade().blur(4.0).scale(0.96)).exit(Fx::fade().blur(4.0).scale(0.96))) +.enter_from(key!("pile-top")) +.matched(ns, id) / .morph(ns, id) +.travel(Travel::Screen) +.resize(Resize::Mask { feather: 28.0 }) +.transitions(phase, |t| t.on(Phase::Recording, Phase::Picker, motion::MORPH)) // Rive-style table +.clip_soft([0.0, 24.0, 0.0, 24.0]) / .clip_hard("video surface owns its edges") + +// live values +let v: Live<f32> = cx.live("drawer.y", 0.0); +node.translate_y(v).opacity(v.map(Expr::remap(0.0, 640.0, 1.0, 0.4))); +cx.presented(key!("thread", 3)) -> Option<PresentedRect> // untracked snapshot +``` + +--- + +## Steal + +- SwiftUI: transaction-scoped animation, merging springs, `Spring(duration:bounce:)`. +- Core Animation: an off-main render thread, model/presentation split, atomic commits. +- Compose: `animateTo(.., initialVelocity = velocity)` and phase separation. +- Motion: `popLayout`, `layoutId`, projection to keep paths straight. +- Flutter: the `Simulation` trait, scroll physics constants and velocity trackers. +- Rive: a transition table keyed by (from, to) phases. +- psychopomp: pure piecewise tracks, `settling_time`, transactional retargets. +- The private iOS client: `PresenceGate` generations, blur gating, one display link through `AnimationTimeScale`. +- Scrawl: the clock, live tuning and the trace writer. +- The launcher: final-layout-once plus animated geometry, and per-axis "width leads" springs. +- Xilem: handlers that receive `&mut State`. +- GPUI: `Model` entities as the hot-reload unit, and the `list` sum tree. +- Taffy: two-edge cumulative rounding. + +## Avoid + +- Animations evaluated on the main thread (GPUI's `request_animation_frame → notify`, Flutter, egui). +- Velocity you can't read back (CA `presentationLayer` heuristics). +- Numeric integrators that can't be sampled at an arbitrary *t* (knobs' 480 Hz Euler). +- Run-once components whose state lives in closures (signals) when hot reload matters. +- Hook-order or call-site identity. +- Deep generic view types (compile times, error messages). +- Scale-based FLIP for anything with text. +- Snapping a critically damped spring to its target when it crosses, which creates a velocity cliff. +- Manual `notify()`. +- `Task.sleep`-style unmount timers. +- Hard clips and ellipses. + +## Recommendation + +**Rune uses:** +- a **keyed retained tree built from pure view functions over `Model<T>` stores**, with model-level + auto-tracking and queued `&mut` handlers; +- a **type-erased `El`** for compile speed; +- explicit string keys for local state; +- an **animation runtime on a dedicated render thread per display**: piecewise analytic tracks per + property, transactional commits with presentation-time `apply_at`, sample-and-restart retargeting, + edge-based layout animation, generation-guarded presence, render-thread scroll and drag bindings + with a decay bridge on release, runtime-enforced reduced motion, two-edge snapping, soft masks by + default, one scalable or manual clock, and native motion traces. + +**Rejected alternatives:** + +| Alternative | Why not | +| --- | --- | +| Fine-grained signals as the primary model | Their main advantage (a cheap per-frame update) is already delivered by render-thread tracks. They lose on hot reload and have silent stale-read footguns. Kept as a narrow tool: `Live<f32>` is effectively a render-thread signal. | +| GPUI's entity plus re-render per frame | Per-frame cost scales with view complexity; manual notify; runtime double-borrow panics. | +| Immediate mode | CPU every frame, nothing offloaded, and presence or layout animation would rebuild a retained tree anyway. | +| Core Animation as the engine | No velocity readback, Apple-only, no determinism, no custom shaders for soft masks or glass inside CA's content model. Keep it only as an optional mirror for system materials (`NSGlassEffectView`, `CABackdropLayer`). | +| Additive animation stacks | Equivalent for linear springs, but more state and harder to trace. | +| Running app logic off the main thread by default | Conflicts with synchronous platform APIs (Flutter's thread merge). Revisit if input latency measurements demand it. | + +## Hard problems + +1. **Straight paths with nested, independently timed animations.** Parent and child on different + springs, or retargeted with mixed velocities, compose into curves. `Travel::Screen` fixes + individual nodes, but choosing the coordinate root automatically, and reparenting mid-flight, is + subtle (Motion's projection tree is roughly 2k lines for a reason). +2. **Content during resize.** Mask vs shape vs scale vs per-frame relayout. Text that must reflow + during a size animation forces main-thread work every frame, so it needs a budget and a lint. +3. **Main/render consistency.** + - Hit-testing must use *presented* geometry: a tap on a moving row should hit what you see. + - Virtualization runs behind render-thread scrolling (checkerboarding on fast flings, sizing + overscan to velocity). + - Commit latency is one frame plus input-to-photon. +4. **Presence edge cases.** + - Exits inside an exiting parent. + - The z-order of exiting nodes versus new arrivals. + - Exits inside a scroll container that is itself scrolling. + - A key that moves to a different parent (a reparent: it should travel, not exit and enter). +5. **Matched geometry across clip and scroll ancestors.** Should the flight layer escape clipping + (Flutter Hero) or stay under the chrome it's passing beneath (Kit's "emerge from behind")? This is + probably per transition, which needs a z-policy API. +6. **macOS scrolling.** Mixing OS-provided momentum with Rune's rubber band, spring-back and + render-thread offset, plus the rule that web wheel deltas must never get inertia twice. +7. **Determinism.** Cross-platform float math (deterministic `libm`), the order of commit + application against forwarded input in tests, and time-scaling CA mirrors in lockstep. +8. **System materials (Liquid Glass) in lockstep with Rune's Metal layer.** Either mirror tracks + into `CASpringAnimation`s evaluated with identical math (the launcher `eval_ca_spring_spec_at`), or drive + CA every frame from the render thread with actions disabled (Scrawl's fixed `NSPanel` plus single + `CATransaction`). Both have a one-frame-skew risk. +9. **Blur and mask cost at scale.** Offscreen passes per blurred or isolated group, and many + simultaneous exits in a big list (cap concurrent blurred layers; degrade to opacity-only past N). +10. **Overshoot from velocity at bounce 0.** A fast fling into a critically damped spring physically + overshoots. Is that "bounce"? Scrawl clamps, which causes a velocity cliff. My default is to allow + the physics; an opt-in `no_overshoot` would clamp *velocity*, not position. +11. **Hot reload while animations are in flight**, when node identity changes shape (a key type + changes, a list becomes a grid): decide between exit/enter and a best-effort matched transfer. +12. **Streaming text** (line-hold, growth caps) belongs half in layout and half here. The interface + between text layout and the growth policy needs design together with the text doc. + +## Open questions + +1. App logic on the platform main thread (the default) vs a separate app thread with a thin + main-thread forwarder. Measure input-to-photon for render-thread drags under a deliberately busy + main thread before deciding. +2. Field-level read tracking (`@Observable`-style derive) in v1, or model-level only? +3. Does the renderer re-encode the whole scene every frame (Vello-style) or cache layer textures? + This sets the render-thread budget. Coordinate with the renderer doc. +4. Port the motion linter's core rules to Rust for in-process `trace.assert_clean()`, or shell out to the + TS CLI? +5. The default list presence: `pop` (siblings close the gap immediately, while the exit plays) or + `hold` (the gap closes as the exit plays)? Kit's "siblings slide into the gap" works with both. + Needs a blind A/B. +6. Confirm the semantic token names (`snap`, `settle`, `reflow`, `glide`, `morph`, `pop`, `drift`) + proposed in Kit's motion presets. Kit's motion rules still treats the old palette as the reference. +7. Should `Origin::Direct` include keyboard selection moves? The skill says keys apply 1:1, but a + selection *highlight* gliding on `SNAP` is often wanted. Probably the highlight animates and the + content doesn't. diff --git a/app/vendor/rune/research/07-hot-reload.md b/app/vendor/rune/research/07-hot-reload.md new file mode 100644 index 0000000..9279f60 --- /dev/null +++ b/app/vendor/rune/research/07-hot-reload.md @@ -0,0 +1,358 @@ +# Hot reload: keep the native host, reload the view and small handlers + +Research date: 2026-10-21. This report supports the choice of Rune's reload architecture. It is source research, not a completed benchmark; the practical spike is separate. + +## Summary + +- Aim for under 300 ms from saved edit to presented frame for tokens, view structure, and small interpreted handlers on both Mac and a connected iPhone. Keep rendering, text, layout, animation evaluation, and durable app state native. +- Use one reloadable view representation on both platforms. A small declarative language or restricted expression interpreter avoids native compilation and executable-memory changes for the edits designers make most often. +- Add Subsecond for Mac and simulator Rust implementation edits. Its current source explicitly excludes physical iOS devices. Its documentation also understates current workspace support, so use the inspected implementation rather than the introductory limitations alone. +- Native function replacement does not migrate Rust state. Struct layout, closures, futures, trait-object vtables, thread-local storage, and destructor ownership all need an explicit compatibility boundary. +- Flutter demonstrates that device hot reload and JIT remain possible with debugger cooperation. Current Dart/Flutter code contains special executable-page handling and version-specific LLDB workarounds. Attaching a debugger once is not a general solution for a Rust dylib loader. +- InjectionNext advertises device support, but a detailed July 2026 iPhone failure and an October maintainer response leave modern device loading unresolved. HotReloadKit deliberately supports only Mac and simulator. Neither establishes a dependable physical-iPhone Rust patch path. +- wasm3, WAMR's interpreter, and wasmi can execute replacement logic without native JIT. They still incur module loading, interpretation, and, for Rust guests, Rust compilation. A current iPhone benchmark supports keeping expensive UI work outside the interpreter. +- Build state preservation around explicit node/state IDs and schemas. Preserve compatible state; migrate declared changes; reset only incompatible subtrees; restart with a snapshot for native-core changes. Apply each generation atomically and acknowledge its first presented frame. +- No source reviewed establishes a general sub-300 ms native-Rust or physical-device edit-to-pixels guarantee. The budgets below are proposed engineering targets, not measurements. + +## 1. Measure the whole edit-to-frame path + +For a save-triggered reload, measure: + +```text +file save → detection/batching → parse or compile → link/package + → device transfer → validate/load → commit generation + → reconcile/layout → GPU work → presented frame +``` + +An application receipt after `dlopen`, or a CLI message after compilation, stops too early. Record generation IDs at every stage. For interactive controls, use the input event rather than a file save as the start. At 120 Hz a frame interval is 8.33 ms; at 60 Hz it is 16.67 ms. Compilation can happen in the background, but final application must also fit the active frame workload. + +### What the available numbers actually establish + +| System | Number | Evidence class and limitation | +|---|---|---| +| Subsecond/ThinLink | Incremental build below 500 ms | Author claim in [runtime docs, lines 168–183](https://github.com/DioxusLabs/dioxus/blob/7a817390a69294f614b3055aae2dacdf25c050a2/packages/subsecond/subsecond/src/lib.rs#L168-L183). No device-to-presented-frame distribution. | +| Subsecond symbol cache | Docsite patch time reduced from 3 s to 1.1 s | Author-reported measurement in [source comment, lines 63–68](https://github.com/DioxusLabs/dioxus/blob/7a817390a69294f614b3055aae2dacdf25c050a2/packages/cli/src/build/patch.rs#L63-L68). Hardware and sampling unspecified. Shows real workloads can exceed 300 ms. | +| HotReloadKit | Roughly 100–300 ms for safe edits | [README](https://github.com/kitlangton/hot-reload-kit/blob/410708f0a204618d7ef3afc923f3e5790bcc80d6/README.md) claim, not a published latency dataset. Runtime receipt follows invalidation, not confirmed display. | +| Flutter | Example log says 978 ms | [Official hot-reload guide](https://docs.flutter.dev/tools/hot-reload). Illustrative output, not a benchmark or SLA. | +| React Native Fast Refresh | “Within a second or two” | [Official guide](https://reactnative.dev/docs/fast-refresh), qualitative product expectation rather than a sub-300 ms result. | +| `hot-lib-reloader` | 500 ms default debounce; suggests 20–50 ms | [README](https://github.com/rksm/hot-lib-reloader-rs/blob/master/README.md). Configured waiting time, before compilation/loading/rendering costs. | +| Slint live preview | 50 ms rebuild debounce | [Implementation](https://github.com/slint-ui/slint/blob/6a6fe8c874809d8c35a656809ccb33582276989d/internal/live-preview/lib.rs). Its separate macOS 200 ms [watcher rescan delay](https://github.com/slint-ui/slint/blob/6a6fe8c874809d8c35a656809ccb33582276989d/internal/live-preview/file_watcher.rs#L98-L108) repairs missed events after watch changes; it is not a universal 200 ms edit delay. | +| Makepad current scripting reload | No trustworthy end-to-end number found | Source establishes a no-Rust-compile path for script edits, not a measured latency. | + +The Subsecond CLI's completion log also precedes a rendered-frame acknowledgement ([builder source](https://github.com/DioxusLabs/dioxus/blob/7a817390a69294f614b3055aae2dacdf25c050a2/packages/cli/src/build/builder.rs#L883-L895)). Do not compare these figures as if they all measured the same endpoint. + +## 2. Subsecond removes much linking work, but leaves Rust compatibility to Rune + +Inspected Dioxus revision: `7a817390a69294f614b3055aae2dacdf25c050a2` (2026-10-17). Published Subsecond documentation currently exposes version 0.7.10; the implementation findings here refer to the pinned repository revision. + +### ThinLink reuses the running program's symbols + +The baseline build records compiler/linker arguments and symbol information. For a patch, the CLI recompiles changed workspace crates and the tip crate, then links fresh code against symbols already resident in the running process. It generates assembly stubs for otherwise undefined symbols, using an address supplied by the running application to account for address-space randomization. The patch therefore avoids relinking unchanged dependency archives into a whole new application. + +The runtime loads the patch image, adjusts the address map, retains the image, and publishes a new jump table. Calls through `subsecond::call`/`HotFn` reach updated implementations. Framework integration still decides when to invalidate/rebuild views and how to handle retained state. See [workspace/link flow](https://github.com/DioxusLabs/dioxus/blob/7a817390a69294f614b3055aae2dacdf25c050a2/packages/cli/src/build/link.rs#L135-L265), [symbol mapping](https://github.com/DioxusLabs/dioxus/blob/7a817390a69294f614b3055aae2dacdf25c050a2/packages/cli/src/build/patch.rs#L424-L463), and [runtime loading](https://github.com/DioxusLabs/dioxus/blob/7a817390a69294f614b3055aae2dacdf25c050a2/packages/subsecond/subsecond/src/lib.rs#L498-L546). + +Two documentation discrepancies matter: + +1. **Workspace support exists in the inspected implementation.** The runtime's introductory docs still say only the tip crate patches. `compile_workspace_hotpatch` now replays changed workspace crates in dependency order and links their updated rlibs. The old [workspace issue #4160](https://github.com/DioxusLabs/dioxus/issues/4160) was closed through #5291 in February 2026. This does not prove every workspace configuration works, but “main.rs only” is stale guidance. +2. **Do not assume exact function-body diffing.** ThinLink's docs advertise object-file diffing. The inspected path collects fresh `.rcgu.o` files plus updated workspace rlibs, and the patch map matches same-name symbols. That is not evidence that only bytewise-changed function bodies enter each patch. Measure patch size and invalidation scope rather than assuming ideal granularity. + +### Unchanged state is only safe when its representation remains compatible + +The [runtime's own limitations](https://github.com/DioxusLabs/dioxus/blob/7a817390a69294f614b3055aae2dacdf25c050a2/packages/subsecond/subsecond/src/lib.rs#L77-L122) include: + +- Struct size/alignment/layout changes need framework-managed re-instancing. Calling new code on an old layout can crash. +- Tracked globals persist, renamed globals are new, and changed initializers are ignored. Newly introduced globals do not have their destructors run. +- Patched-crate thread-locals reset. Current [TLS patch handling](https://github.com/DioxusLabs/dioxus/blob/7a817390a69294f614b3055aae2dacdf25c050a2/packages/cli/src/build/patch.rs#L1192-L1234) still makes per-patch copies; initializer fixes do not make them persistent host state. +- Function pointer identity is not a reliable fine-grained change detector across generations. + +`subsecond::call` provides a reload/unwind boundary, not a proof that arbitrary existing Rust values match new code. The inspected `try_call` path casts callable pointers; it does not provide comprehensive schema/layout validation. A changed async function also changes its compiler-generated future type. Existing futures, captured closures, and trait objects can retain old implementation pointers even if a top-level function was replaced. + +**Rune use:** keep the scheduler, runtime/Tokio ownership, state store, GPU objects, and thread-locals in the stable host. Patch small view-builder/reducer entry points. Reject incompatible schemas before invoking replacement code. Use generation-scoped tasks and callbacks, with quiescence or cancellation at reload. Keep old images resident until safe reclamation is demonstrable; bound memory with a snapshot/restart policy. + +### Platform labels need qualification + +The source lists macOS, Linux, Windows, Android, wasm32, and iOS arm64, then explicitly says **physical iOS devices are unsupported due to code signing; use the simulator** ([lines 193–208](https://github.com/DioxusLabs/dioxus/blob/7a817390a69294f614b3055aae2dacdf25c050a2/packages/subsecond/subsecond/src/lib.rs#L193-L208)). This is project-declared support, not a matrix independently tested here. For Rune, count Mac/simulator native patching as available to investigate and physical iPhone native patching as unavailable through stock Subsecond. + +## 3. A stable-ABI dylib is simpler to reason about, but has the same device barrier + +[`hot-lib-reloader`](https://github.com/rksm/hot-lib-reloader-rs) watches a dynamic library, uses unique shadow copies to avoid loader caching/locking problems, loads exported symbols through `libloading`, and coordinates replacement. It does not eliminate Cargo/rustc compilation. Its examples using `#[unsafe(no_mangle)]` do not automatically establish a stable C ABI; unmangled names and ABI stability are different properties. + +Its [documented limitations](https://github.com/rksm/hot-lib-reloader-rs/blob/master/README.md#know-the-limitations) cover signature/layout mismatches, generic exports, globals, and changing `TypeId`s. The README also describes a tracing-callsite crash, illustrating how third-party global registries can retain references into unloaded images. + +For a Rune-owned boundary, use an explicit `extern "C"` entry point returning a versioned `#[repr(C)]` function table. Pass opaque host handles, fixed-width scalars, or explicitly owned byte buffers. Keep allocation/freeing paired with the owning side. Do not pass `Vec`, `String`, Rust trait objects, references with hidden lifetimes, or panics across the boundary. Validate ABI version and schema fingerprints before installation. + +Host-owned state can survive every library generation. Library-owned state needs a serialization/migration call into the old generation before retiring it. Every registered callback/task must either retain its owning generation or be unregistered and drained before unload. A C ABI does not solve those lifetime problems by itself. + +**Tradeoff:** this is a useful Mac fallback if Subsecond integration proves too coupled to Dioxus tooling. It requires more explicit API design and still cannot load arbitrary downloaded native code on ordinary physical iOS. Reject it as the shared Mac/iPhone reload foundation. + +## 4. Makepad and Slint demonstrate a more portable view boundary + +### Makepad reparses scripts and reapplies them to a live native app + +Inspected Makepad revision: `44ecb822b48106fa76bde4dfd309e5a8a7ff1932`. Current Splash documentation uses `script_mod!`; older `live_design!` descriptions refer to the archived system ([current scripting guide](https://github.com/makepad/makepad/blob/44ecb822b48106fa76bde4dfd309e5a8a7ff1932/docs/agents/splash.md)). + +The reload path receives changed file contents, extracts script blocks from Rust source, matches them to compiled sites, checks block counts and embedded Rust `#(...)` placeholder counts, then tokenizes/parses the replacement scripts. It stages a new override map and publishes it only after validation of the batch. See [live_reload.rs, lines 186–366](https://github.com/makepad/makepad/blob/44ecb822b48106fa76bde4dfd309e5a8a7ff1932/platform/src/live_reload.rs#L186-L366). + +The app then reapplies scripts to the existing application through `ScriptApply` ([app_main.rs](https://github.com/makepad/makepad/blob/44ecb822b48106fa76bde4dfd309e5a8a7ff1932/platform/src/app_main.rs#L326-L350)). `StudioToApp::LiveChange { file_name, content }` supplies a transport-shaped entry point ([cx_shared.rs](https://github.com/makepad/makepad/blob/44ecb822b48106fa76bde4dfd309e5a8a7ff1932/platform/src/os/cx_shared.rs)). This is a concrete design for sending source as data rather than loading a new native library. + +Preservation follows the existing object's apply behavior; it is not universal migration of arbitrary Rust fields. Native Rust code and changed embedded Rust values still require compilation. Shader cache invalidation is a separate concern from applying style properties. Source inspection establishes these mechanisms, but does not establish current end-to-end iPhone transport reliability or a latency distribution. + +**Steal:** a live language embedded near native code, stable binding sites, preflight validation, batched application, and native hot paths. Prefer explicit IDs over line/column-derived identity where source movement should preserve state. + +### Slint reconstructs a component and restores explicitly retained values + +Inspected Slint revision: `6a6fe8c874809d8c35a656809ccb33582276989d`. The live-preview implementation watches `.slint` dependencies and resources, compiles on a worker using the interpreter, and retains the last working component on compilation failure. On success it creates a new component using the existing window ([live_component.rs, lines 118–145](https://github.com/slint-ui/slint/blob/6a6fe8c874809d8c35a656809ccb33582276989d/internal/live-preview/live_component.rs#L118-L145)). + +It restores the properties and callbacks held in its explicit registration maps ([lines 174–199](https://github.com/slint-ui/slint/blob/6a6fe8c874809d8c35a656809ccb33582276989d/internal/live-preview/live_component.rs#L174-L199)). That is narrower than preserving every current internal widget value, focus target, scroll offset, or running animation. Values changed only inside the old instance are not automatically all represented by those maps. + +**Steal:** worker compilation, diagnostics, an existing-window handoff, and last-good retention. **Improve for Rune:** define persistent state separately from the generated view tree, so state survival does not depend on incidental property registration. The inspected preview facility is not proof of a turnkey physical-iPhone live-preview product; Rune would supply the device host and transport. + +## 5. Flutter and React preserve state because their runtimes know its identity + +### Flutter controls both executable code and object metadata + +Flutter's debug hot reload sends changed Dart program material to the VM, updates code, and rebuilds the widget tree while preserving compatible state. `main()` and `initState()` do not rerun; static/global initialization is generally retained. Native Swift/Objective-C/Kotlin/Java changes require a restart/rebuild. Enum/class changes and changes to generic type parameter counts are among documented reload restrictions ([official guide](https://docs.flutter.dev/tools/hot-reload)). + +The [Dart VM reload design](https://dart.googlesource.com/sdk/+/42ec219908a0ce38b0f16593302f96cad6f38e9b/docs/Hot-reload.md) explains replacement of method dictionaries, retention of existing field values, and invalidation of inline caches and optimized assumptions. This works because the VM owns object metadata and code dispatch. Rust's unmanaged existing allocations do not come with that capability. + +Flutter supports physical and virtual targets in debug mode. Its device JIT/debugger machinery is substantial, as detailed below. The reusable idea is the division between persistent state and replaceable behavior, not the assumption that a native Rust function patch inherits Dart's migration semantics. + +### React Fast Refresh uses component families and hook signatures + +The [refresh runtime](https://github.com/facebook/react/blob/main/packages/react-refresh/src/ReactFreshRuntime.js) associates old/new component implementations with stable families. It compares component kinds and hook signatures, including custom-hook dependencies, then separates families that can update from families that must remount. + +Function-component hook state can survive compatible edits; class component state is not preserved. Changed hook structure can force a reset. Effects, memoized values, and callbacks refresh even with otherwise unchanged dependency arrays, and module export shape affects how far refresh propagates ([React Native guide](https://reactnative.dev/docs/fast-refresh)). + +**Rune lesson:** give every reloadable component a stable family ID and a state-schema signature. Distinguish “recompute this view” from “recreate this state.” Rerun subscriptions with cleanup rules instead of preserving stale closure pointers. React's “second or two” wording is not evidence for the target latency. + +## 6. Swift tooling is useful precedent, with a sharp simulator/device split + +### HotReloadKit has a narrow compatibility planner worth copying + +Inspected revision: `410708f0a204618d7ef3afc923f3e5790bcc80d6`, plus local `README.md` and `docs/architecture.md`. + +HotReloadKit parses baseline and edited Swift with SwiftSyntax, replaces allowed function/computed-property bodies with empty bodies, and compares the remaining structure. Compatible edits produce `@_dynamicReplacement` thunks with source-scoped private imports. It compiles those thunks with `swiftc -emit-object`, links a Mach-O bundle against the baseline executable using `clang -bundle -bundle_loader`, publishes an atomic manifest, loads the bundle with `dlopen`, invalidates affected observers, and writes a receipt ([architecture](https://github.com/kitlangton/hot-reload-kit/blob/410708f0a204618d7ef3afc923f3e5790bcc80d6/docs/architecture.md)). + +Stored-property, signature, and new-type changes fall back to rebuilding. Opaque return types need additional restrictions; TCA reducer edits are constrained to suitable closure bodies. SwiftUI state survives when the existing identity remains. Recreating a subtree through `.rebuildsOnHotReload()` resets its local state, focus, and scroll, while externally owned models survive ([README](https://github.com/kitlangton/hot-reload-kit/blob/410708f0a204618d7ef3afc923f3e5790bcc80d6/README.md)). + +The runtime is intentionally inert on physical devices and in release builds. Its filesystem manifest depends on the shared host/simulator filesystem; adding a socket would solve transport, but not native device loading. Loaded Swift images remain resident; the documented 50-generation restart policy bounds accumulation. Its claimed 100–300 ms is promising for a narrow edit class, not a measured device guarantee. + +### Modern SwiftUI previews are not simply third-party dynamic replacement + +Apple's current [build-product layout documentation](https://developer.apple.com/documentation/xcode/understanding-build-product-layout-changes) describes the debug executable stub, application `.debug.dylib`, and `__preview.dylib`. Older descriptions focused on generated dynamic-replacement thunks. HotReloadKit deliberately uses its own compatible build layout and replacement mechanism; its README's relationship to previews should not be read as a complete description of current Xcode internals. + +Apple's supported preview workflow, including on-device previews, does not establish that an ordinary development app may receive a newly built dylib into its data container and `dlopen` it. Use previews as precedent for edit classification and tooling, not evidence for a portable Rust device loader. No comparable current edit-to-presented-frame dataset was found. + +### InjectionNext's actual loader is more informative than its support label + +InjectionIII and its successor InjectionNext rebuild changed Swift/Objective-C source and replace behavior using injection/runtime mechanisms. InjectionNext advertises device support. At inspected revision `b39c9f15cf8d8b99978297cb76514a7e0280ec8c`, the host signs generated dylibs using a selected Apple Development identity ([NextCompiler.swift, lines 392–411](https://github.com/johnno1962/InjectionNext/blob/b39c9f15cf8d8b99978297cb76514a7e0280ec8c/App/InjectionNext/NextCompiler.swift#L392-L411)); the app receives bytes, writes a temporary file, and loads/patches it ([runtime, lines 349–354](https://github.com/johnno1962/InjectionNext/blob/b39c9f15cf8d8b99978297cb76514a7e0280ec8c/Sources/InjectionNext/InjectionNext.swift#L349-L354)). + +Counterevidence is specific and recent. [Issue #81, July 2026](https://github.com/johnno1962/InjectionNext/issues/81#issuecomment-5106386779) reports an iPhone 15 on iOS 26.4.2 with Xcode 26.3 rejecting the dylib with `code signature invalid … (errno=1)`, despite a matching signing identity and corrected load commands. An entitlement hypothesis did not resolve the report. On [2026-10-06 the maintainer wrote](https://github.com/johnno1962/InjectionNext/issues/81#issuecomment-6006741081), “Been unable to test this on an iOS 26 phone thus far.” + +The thread also [quotes Apple DTS](https://github.com/johnno1962/InjectionNext/issues/81#issuecomment-5106411624) distinguishing OS/embedded libraries from downloaded libraries in the data container. The original [Apple forum thread](https://developer.apple.com/forums/thread/773210) was blocked by security verification during this research, so that quotation is secondary evidence. The thread does not prove every native injection technique is impossible on every iOS version. It does rule out treating “sign the dylib with the same identity” as an established solution. + +## 7. Physical iPhone reload must separate data loading from native executable loading + +Apple's [runtime process security documentation](https://support.apple.com/guide/security/runtime-process-security-sec15bfe098e/web) explains signed entitlements and execute-never protections. A development signing identity, Developer Mode, and `get-task-allow` are not interchangeable with permission to execute arbitrary downloaded native pages. `get-task-allow` enables debugger attachment; macOS's hardened-runtime JIT entitlement is not a general iOS entitlement an ordinary app can add. + +Historically, debugger attachment and `CS_DEBUGGED` relaxed relevant checks. See the [XNU code-signing flags](https://github.com/apple-oss-distributions/xnu/blob/main/osfmk/kern/cs_blobs.h) and [technical investigation of iOS 18.4 changes](https://gist.github.com/osy/8940e5ae5f24646b808f58d197883ca5). With newer Trusted Execution Monitor restrictions, executable pages may require debugger-assisted handling rather than merely a one-time attachment. + +Current working source shows the distinction: + +- Dart's [virtual_memory_posix.cc](https://github.com/dart-lang/sdk/blob/main/runtime/vm/virtual_memory_posix.cc) creates executable mappings/aliases and calls `NOTIFY_DEBUGGER_ABOUT_RX_PAGES` for debugger-assisted preparation. +- Flutter's [ios/lldb.dart](https://github.com/flutter/flutter/blob/master/packages/flutter_tools/lib/src/ios/lldb.dart) installs a Python callback that touches those pages via LLDB `WriteMemory`, including the `IHELPED!` marker. The inspected implementation also contains an iOS 27 manual-continue workaround. +- [UTM's corresponding change](https://github.com/utmapp/UTM/commit/07c79d17c5c9cc3136d50b00867bdeb56ca070d2) provides another concrete debugger-assisted JIT precedent. + +Therefore, both “iOS JIT is impossible” and “attach LLDB and normal dylib loading works” are too broad. A native Rust experiment could investigate debugger-assisted executable pages, but would additionally need Mach-O/object relocation, symbol resolution, unwind metadata, TLS handling, architecture-specific details, and patch lifetime management. That is a new loader/runtime project, not an entitlement flag for Subsecond. + +| Route | Mac | iOS simulator | Physical iPhone | +|---|---|---|---| +| Tokens, assets, parsed view descriptions | Ordinary data reload | Ordinary data reload | Ordinary data reload; implement device transport | +| Native Subsecond patch | Project-supported | Project-supported | Explicitly unsupported in current source | +| HotReloadKit | Supported Debug path | Supported Debug path | Runtime deliberately inert | +| InjectionNext dylib transfer | Native injection path | Native injection path | Advertised, but recent signing/load failure unresolved | +| Dart/Flutter debug hot reload | Supported framework workflow | Supported framework workflow | Supported framework workflow with debugger machinery | +| Interpreter embedded in signed host | Feasible | Feasible | Avoids native executable mapping for replacement bytecode | +| Custom debugger-assisted Rust loader | Unnecessary for baseline | Unnecessary for baseline | Experimental, no Rune implementation or latency proof | + +For development, transfer ordinary data to an already installed native host. A release build can compile out the reload transport and ship bundled descriptions or a native lowering of the same representation. App Store distribution policy is a separate question from whether a developer-installed interpreter can run; do not describe an interpreter choice as automatic approval for arbitrary downloaded production features. + +## 8. Interpreted Wasm can carry Rust logic, but should not carry the renderer + +An interpreter treats incoming Wasm bytes as data and executes them through code already in the signed host. Configure interpreter-only builds explicitly: WAMR also offers AOT/JIT modes, and a native-code AOT artifact does not gain the portability of interpreted bytecode merely by coming from a Wasm toolchain. + +| Runtime | Mechanism and fit | Main question for Rune | +|---|---|---| +| [wasm3](https://github.com/wasm3/wasm3) | C interpreter, internal execution representation without native JIT. Strong current scalar/call-heavy benchmark results. | Does the chosen Rust Wasm target emit only supported features? Measure load time and the host-call boundary. | +| [WAMR](https://github.com/bytecodealliance/wasm-micro-runtime) fast interpreter | Configurable C runtime with interpreter, AOT, and JIT options. Use interpreter only. | Select features carefully; published benchmark patches must not be mistaken for upstream functionality. | +| [wasmi](https://github.com/wasmi-labs/wasmi) | Rust interpreter with validation, embedding APIs, and fuel metering. Version 2.0 arrived 2026-09-01 with accumulator IR and revised dispatch. | Benchmark current v2, rather than using historical rankings. Its [changelog](https://github.com/wasmi-labs/wasmi/blob/main/CHANGELOG.md) claims 2.2× geomean improvement over v1; that is not an iPhone comparison. | + +The strongest current physical-device evidence found is a [2026-09-22 interpreter comparison](https://github.com/rebeckerspecialties/wasm-benchmark/blob/main/docs/runtime-comparison-2026-09-22.md), with raw data and N=10 runs on an iPhone XS Max/A12, iOS 18.7.10, primarily E-core execution. Across 17 mutually supported cases, geometric means of CPU time relative to the fastest runtime per case were wasm3 **1.04**, WAMR **1.38**, and Pulley **1.68**. Those are relative interpreter scores, not slowdowns versus native, and wasmi was absent. The WAMR build carried patches. + +That benchmark's full femtovg Wasm guest achieved only **7.0 fps** for scene 0 on wasm3/A12. Pulley's load-time translation of the roughly 1 MB guest took about **2.7 s**. These workloads do not predict tiny-handler reload times, but they directly contradict assuming that a full interpreted Rust UI stack will comfortably maintain 120 Hz or load below 300 ms. + +Recommended boundary: + +- Native host owns layout, text shaping, rasterization, springs/gesture integration, resource caches, and authoritative state. +- Guest computes small event reductions and view descriptions when dependencies change. It does not run a whole per-frame renderer. +- Host calls are batched through a compact command/result buffer. Avoid crossing the interpreter boundary for every property of every node. +- Stable numeric handles identify native state and resources. Guest memory is generation-local unless an explicitly versioned serialization contract migrates it. +- Fuel/time limits contain runaway handlers. A failed candidate generation leaves the previous one active. + +Rust-to-Wasm still invokes rustc. A small isolated crate may compile quickly, but no sub-300 ms result was established here. For the primary design loop, a parsed view/expression language is the stronger latency bet. Wasm is an optional logic tier when Rust reuse is worth the compilation and embedding cost. Reusing an old guest's linear-memory bytes with a changed Rust allocator/data layout is not state migration. + +## 9. Tokens, assets, and shaders should each have a direct reload path + +### Reuse knobs' typed remote-control model + +Local sources inspected: the knobs library's `README.md`, especially `createRemoteControls`, and `docs/migration.md`. Remote descriptors carry typed values such as spring, color, point, easing, gradient, and curve. `onSet` handles individual updates; `onSetBatch`/`setMany` batches related edits; `null` resets a value. Incoming `.sync` updates avoid echoing back and creating undo entries. + +The requested tuning files from a private iOS client were absent from the current checkout. They were inspected through Git revision `67fbf2b6`: `scripts/tune-server.ts` and `scripts/tune-page/index.ts` in the private iOS client. That historical implementation uses `/phone` and `/ui` WebSockets, capability negotiation, atomic batch validation, and the older `setValues` name. State broadcasts are coalesced for 16 ms. The page's `echo: 5000` setting suppresses stale echoes; it is not a five-second outbound delay. Do not assume those historical paths or protocol names describe the present checkout. + +For Rune, connect each typed descriptor to a stable host property ID. Validate a whole edit transaction before applying it on the UI thread. Preserve spring position and velocity when changing targets or parameters. Stream compact deltas while dragging; persist the final chosen values to source/configuration with an explicit policy so a live value is not mistaken for a saved default. + +### Assets can swap by stable resource handle + +Proposed asset pipeline: content hash → transfer missing bytes → decode/shape/upload off the render thread where possible → replace the resource generation at a frame boundary. Keep the old resource on decode failure and while GPU work references it. A font change must invalidate affected text/layout caches; it is more expensive than changing a color. Large texture uploads and font work get separate latency reporting rather than being hidden in the token budget. + +### Shader compilation is available without arbitrary CPU JIT + +Metal exposes runtime shader-library compilation through [`MTLDevice.makeLibrary(source:options:)`](https://developer.apple.com/documentation/metal/mtldevice/makelibrary(source:options:)). For a portable WGSL front end, [naga](https://github.com/gfx-rs/wgpu/tree/trunk/naga) can validate and translate to backend shader code. Neither API implies a universal shader-to-pixels latency. + +Proposed pipeline: parse/validate → compile shader and pipeline asynchronously → validate resource/binding compatibility → stage the new pipeline → swap at a frame boundary. Retain old pipeline/resources until prior GPU submissions complete. Binding-layout changes need a compatible resource rebuild or a rejected patch. On any error, retain the last working pipeline and report source diagnostics. Cached small shaders may fit 300 ms; cold or complex pipeline compilation needs measurement and must not block ordinary view/token edits. + +## 10. State preservation needs an explicit contract + +The state host should retain application entities/signals, navigation, keyed list identity, text selection/composition, focus, scroll anchors, gesture ownership, and animation position/velocity independently of replaceable view code. Stable identity must be explicit enough to survive inserting a sibling or moving a source block. A source line number or Rust `TypeId` alone is insufficient. + +### Classify edits before publishing them + +| Edit | Proposed behavior | +|---|---| +| Color, spacing, text, spring target/parameters | Update values, invalidate affected dependencies, retain state and motion continuity. | +| View structure with the same explicit node/state IDs | Reconcile nodes; preserve compatible state, focus, and scroll anchors. | +| Handler/body change with the same state and call schema | Install new behavior at a safe boundary; retained state remains authoritative. | +| Added optional state field with a declared default | Run a transactional schema migration. Existing fields keep their values. | +| Renamed field with an explicit migration | Migrate by stable field ID or declared mapping, not coincidental position. | +| Incompatible component state or changed hook-like signature | Reset only that component/subtree and report the reason. | +| Native renderer/layout ABI, allocator, or platform-shell change | Snapshot supported state, rebuild/relaunch, restore; replay if required. | + +Schemas must capture semantic compatibility, not just `size_of`/alignment. Two equally sized fields can change meaning or order. State outside the stable host needs an explicit export/import contract; absence of a migration means reset or restart, not a best-effort pointer cast. + +### Commit one generation, with no mixed old/new behavior + +Proposed transaction: + +1. Receive generation N with base-generation ID, source hashes, required host capabilities, ABI/schema fingerprints, and all changed resources. +2. Parse/compile and validate in staging. Reject missing dependencies, stale bases, incompatible bindings, or invalid migration plans without mutating the live generation. +3. At a safe event/frame boundary, finish the current reducer. Drain or cancel generation-owned work. Take the migration snapshot from the current state, not an earlier background copy that would lose intervening user input. +4. Apply migrations and install view/handler/resource references as one commit. Route future events through stable handler IDs. Drop late async results from retired generations unless their host-owned operation explicitly survives reload. +5. Reconcile affected nodes, render, and acknowledge N on its first presented frame. Release retired resources only when CPU callbacks and GPU submissions no longer reference them. + +Old native images may need to stay loaded because destructors/vtables/code pointers remain reachable. Interpreted generations are easier to reclaim if host handles and generation ownership are enforced. Validation can be atomic even when parsing allocates staging objects; execution-time traps still need an explicit rollback/reset policy rather than a claim that every script has been proven safe. + +### Snapshot/replay is a fallback, not a substitute for live identity + +Record semantic inputs, external I/O responses, timer delivery, a controlled clock, and random seeds. Rebuild from a snapshot and replay events to restore a useful development state after native changes. Network mutations and other external side effects must be suppressed or substituted during replay, with stable operation IDs to avoid duplicate sends. + +Replay needs the same deterministic scheduler/input model used for headless agent verification. It will not automatically recreate arbitrary OS handles, an in-progress IME session, or undocumented platform state. Expose which state was preserved, migrated, reset, or reconstructed in the inspector. + +## 11. Steal and avoid + +### Steal + +- Subsecond's baseline-symbol reuse and jump-table entry points for desktop native edits. +- HotReloadKit's conservative compatibility planner, atomic publication, and runtime receipt, extended through actual presentation. +- Makepad's source-as-data update path and preflight of a complete script batch. +- Slint's worker compilation, diagnostics, and last-good retention. +- React's stable component families and compatibility signatures. +- Flutter's persistent-state/replaced-behavior model, with explicit restart-only edit classes. +- Knobs' typed descriptors, batch validation, remote synchronization, and echo suppression. + +### Avoid + +- Calling simulator support “iOS device hot reload.” +- Claiming <300 ms from a compiler timer, animation GIF, or unqualified README number. +- Depending on arbitrary data-container dylib loading for the main iPhone workflow. +- Patching arbitrary Rust allocations or async futures across type-layout changes. +- Using reloadable-crate TLS/globals as the durable state host. +- Unloading libraries while callbacks, tracing registries, vtables, or destructors still reference them. +- Putting text/layout/rendering or spring integration into an interpreter merely to make everything reloadable. +- Rebuilding the entire view state on every edit, or replaying external side effects to reconstruct it. +- Applying half of a multi-file save or reporting success before the changed generation is visible. + +## 12. Recommended Rune layers and latency budgets + +Use a native runtime with one persistent state store and one keyed view representation. Expose four reload classes through the same development connection: + +1. **Live values:** typed tokens, animation parameters, and resource references. This should be the quickest path on every platform. +2. **Live views:** a declarative tree plus bounded expressions/handlers that can be parsed without invoking Rust. Keep IDs, schemas, diagnostics, and dependency tracking shared with the native runtime. The same representation can be bundled or lowered for production. +3. **Replaceable logic:** small interpreted Wasm modules when Rust reuse is needed; Subsecond as the Mac/simulator native acceleration path. Both use the same host-state and handler-ID contract where practical. +4. **Native rebuild:** renderer/platform/core changes rebuild with snapshot restoration and deterministic replay support. + +Do not make an elaborate language a prerequisite for the first spike. Start with a minimal typed tree and a tiny handler/expression vocabulary that can change real behavior. Let the device result determine whether to expand that language or add Wasm. + +### Proposed warm-path budgets, not measurements + +All figures below are milliseconds. Assumptions: app already running in the foreground; established connection; small payload (tokens or view/handler delta up to roughly 32 KiB); no large asset upload; warm caches; no new native build. These are allocations to validate, not percentiles inferred from other frameworks. + +| Stage | Tokens, Mac / iPhone | View data + small interpreted expressions, Mac / iPhone | +|---|---:|---:| +| Detect/settle save or collect input | 10 / 10 | 20 / 20 | +| Parse, validate, package | 2 / 2 | 25 / 25 | +| Established transport | 2 / 15 | 2 / 20 | +| Receiver decode/validation/staging | 2 / 5 | 15 / 30 | +| Wait for safe boundary and commit | 10 / 10 | 10 / 10 | +| Reconcile/layout/render/present | 17 / 25 | 25 / 35 | +| Scheduling/variance reserve | 15 / 25 | 40 / 60 | +| **Allocated total** | **58 / 92** | **137 / 200** | + +The render stage can span multiple display intervals; these numbers do not authorize a single 25–35 ms UI-thread stall. Background staging and incremental work must preserve the normal 8.33 ms frame budget. View updates have 100 ms of headroom under the 300 ms target, which may be consumed by realistic trees, transport variance, or cache misses. + +For small Rust-to-Wasm edits, a separate **aspirational iPhone allocation** is 20 ms detect + 100 ms compile/package + 20 ms transfer + 40 ms load/validate + 10 ms commit + 35 ms render/present + 50 ms reserve = **275 ms**. The 100 ms Rust compilation and 40 ms module-load allocations are unproven and may fail. If they do, retain the fast interpreted view path rather than moving its target to match Rust compile time. + +For Mac Subsecond, write the total as **rustc + patch link + approximately 50–100 ms delivery/application/presentation overhead**, with that overhead also a proposed allowance. A 300 ms total would leave only about 200–250 ms for compilation/linking. The reviewed evidence does not establish that allowance for realistic Rune crates. Treat native patching as a convenience tier with measured per-edit results, not the foundation of the latency promise. + +### Device transport must be measured independently + +Use a long-lived bidirectional connection with generation IDs, hashes, capability negotiation, and last-applied/last-presented acknowledgements. Test local-network and a deliberately configured USB-forwarded route separately. A plugged-in phone may still be sending traffic over Wi-Fi; log the actual route. USB pairing/forwarding setup and cold connection time are separate from warm edit latency. Remote build-worker-to-Mac artifact transfer, when used, must be counted as an extra stage. + +Use a host monotonic clock for save-to-returned-present-ack time. That includes acknowledgement return transit and is a conservative observable bound. Device timestamps partition receive-to-present without cross-machine clock assumptions. For more precise one-way attribution, estimate clock offset and uncertainty explicitly. A submitted command buffer is not a presented drawable; use presentation timing where available and label any proxy. + +### Rejected foundations + +| Alternative | Why reject it as the primary architecture | +|---|---| +| Subsecond everywhere | Current physical iPhone exclusion, Rust compile variability, and no automatic arbitrary-state migration. | +| One stable-ABI native dylib everywhere | Cleaner boundary, same device executable-loading problem. | +| Build/sign/download a dylib into the iPhone container | Recent concrete failure; no dependable supported recipe established. | +| Custom debugger-assisted native Rust JIT first | High loader/runtime cost and OS-version coupling before proving the basic design loop. Keep as a later experiment. | +| Entire UI stack in interpreted Wasm | Conflicts with the 120 Hz priority; current full-renderer benchmark and load-time evidence are poor. | +| Rust-to-Wasm for every spacing/text edit | Retains compiler latency for edits that can be parsed directly. | +| Restart and replay for every edit | Loses immediate interaction continuity and makes external side-effect reconstruction part of the common path. | +| Adopt Flutter or a WebView solely for hot reload | Gives up the requested ownership of Rune's native rendering/layout/state stack. Reuse the state model instead. | + +## 13. Validate the physical-iPhone path first + +The first spike should run a development-signed native host on a physical iPhone, launched **without an attached debugger**, with the same minimal view representation on Mac. Keep native state, rendering, and animation alive while a remote edit changes a token, a keyed subtree, and a small event handler. A counter whose increment changes from one to two proves changed behavior rather than only remote styling. + +The spike should answer these questions in order: + +1. Can token, tree, and handler changes travel to the phone as data and appear within 300 ms, measured through presentation? Record hardware, OS/toolchain, payload sizes, transport route, warm/cold status, and each pipeline stage. Collect at least 30 warm edits per class, reporting median, p95, maximum, and failures; this is proposed spike work, not work performed in this report. +2. Does the same state survive? Include a nonzero counter, text input/selection, a scrolled keyed list, navigation, and an active spring. Check that position/velocity continue across a parameter or subtree edit. +3. Does malformed input leave the last good generation visible? Does an incompatible state-schema change reset only its intended subtree? Can two rapid edits supersede an older staged generation without mixing resources? +4. Does the interpreter remain outside the frame-critical path? Measure handler execution and reload-commit work against the existing native frame budget. Add Wasm only after the simpler path establishes transport and state behavior. +5. Separately, how fast are small Mac Subsecond edits in a realistically partitioned workspace? Include body-only, changed workspace dependency, closure capture, added state field, and patched-crate TLS cases. Record rejection/reset behavior, not just successful reloads. + +Only then consider a separate modern-iPhone native-loader experiment with debugger assistance. Its acceptance criterion is repeatable success across the actual device/OS/toolchain combination, including reconnect and multiple generations, not one successful `dlopen`. + +## Open questions + +- How much application behavior must be live for the first consumers? That determines whether a small expression language is sufficient before introducing Wasm. +- Can a shared typed view representation lower to native production code without dev/release semantic drift? Which constructs must be rejected or interpreted in both modes? +- Which state schemas can be generated mechanically, and which require explicit migrations? How should agents receive precise reset/restart diagnostics? +- What are actual p95 transport and presentation latencies on Kit's connected iPhone over USB forwarding versus local Wi-Fi? +- Which current interpreter wins on Rune-sized modules when compilation, instantiation, host calls, and memory reclamation are included? Include wasmi v2, absent from the cited device comparison. +- Does the chosen renderer expose reliable presented-frame timestamps on every target, or must some targets report a clearly labeled submission/completion proxy? +- How much resident memory accumulates across Subsecond/Swift-style native generations, and when should snapshot/restart occur? +- Can shader/layout changes preserve a moving interface without a visible discontinuity, and which binding or geometry changes require an explicit transition/reset? diff --git a/app/vendor/rune/research/08-spike-hot-patch.md b/app/vendor/rune/research/08-spike-hot-patch.md new file mode 100644 index 0000000..4491824 --- /dev/null +++ b/app/vendor/rune/research/08-spike-hot-patch.md @@ -0,0 +1,159 @@ +# Standalone Rust hot-patching with Subsecond + +Hands-on spike, 2026-10-21. [Source and reproduction instructions](../spikes/hot-patch/README.md). All Rust execution took place on a remote M2 Max build Mac. No windows were opened. + +## Summary + +- **Yes, a standalone Rust program can hot-patch without a Dioxus UI.** A terminal loop used `dioxus_devtools::connect_subsecond()` and `subsecond::call(...)`; the patched function returned a string. +- Ten successive body edits preserved the running process, counter, Vec allocation and contents, and main-owned struct instance. Save→first new-function output was **989 ms median / 1,150 ms p95**, with a 712–1,150 ms range. +- This did **not** meet Rune's approximately 300 ms target. Even save→patch-applied, before waiting for the next tick, was **826 ms median / 1,100 ms p95**. +- A conventional build of the final spike took **71.33 s artifact-cold** and **1.846 s for one incremental body edit**. The registry was warm for that cold-artifact build. +- The exact simple expression `subsecond::call(|| render(&state))` silently kept running old code in 0.7.10. A two-reference capture worked; `HotFn::current(render).call((&state,))` also worked and is the better integration candidate. +- Generic function bodies, a closure body, and a statically dispatched trait implementation patched successfully. A cached `Box<dyn Trait>` retained its old method. A signature change inside a stable closure patched; changing the explicit `HotFn` boundary signature left old behavior running. +- **State preservation is conditional.** Adding a struct field was accepted without migration or rejection. Tip-crate atomic statics and thread locals reset on patches in this experiment, including a separately tested exported static. The static result contradicts the broad documentation claim. +- Subsecond 0.7.10 explicitly documents **physical iOS devices as unsupported for Rust hot-patching**. Simulator support is documented but was not measured. Recommendation: an optional desktop development backend, not Rune's sole hot-reload foundation. + +## 1. Environment and integration + +| Item | Actual setup | +|---|---| +| Worker | M2 Max build worker, Apple M2 Max, 12 cores / 96 GiB | +| OS | macOS 27.0.1, build 26A434 | +| Compiler | `rustc 1.99.0 (b940084d7 2026-09-28)`, stable aarch64 Apple Darwin | +| CLI | `dioxus 0.7.10 (57d6794)` | +| Crates | `subsecond = =0.7.10`, `dioxus-devtools = =0.7.10`, lockfile retained | +| Build settings | `opt-level=0`, `debug=0`, incremental enabled, two Cargo jobs | +| Execution | Remote shell on a background-priority job runner | + +The pre-existing `dx` on `PATH` was Deno's launcher. I installed the latest available Dioxus release with `cargo-binstall dioxus-cli --no-confirm` on the worker. It installed `~/.cargo/bin/dx`, which the driver addresses explicitly. The inherited sccache wrapper rejected incremental compilation, so the driver clears `RUSTC_WRAPPER` for its subprocesses. [Recorded environment](../spikes/hot-patch/evidence/environment.json). + +The binary has a counter, `Vec<u64>`, and nested `Panel` struct owned by `main`. Each nominal 120 Hz tick increments the counter and first Vec entry, calls `render`, and prints a timestamp, PID, state/Vec addresses, and output. It creates no `VirtualDom` or Dioxus renderer. `dioxus-devtools` does bring Dioxus core/signals dependencies transitively; this proves independence from the UI runtime, not a dependency graph free of Dioxus crates. + +The devtools adapter supplies a WebSocket connection with the PID, build ID, and ASLR reference, then passes matching jump tables to `subsecond::apply_patch`. The runtime loads the patch dylib and updates its jump table. It retains loaded libraries and jump tables rather than unloading previous code. Sources: [devtools 0.7.10, `connect_subsecond` and `connect_at`](https://github.com/DioxusLabs/dioxus/blob/v0.7.10/packages/devtools/src/lib.rs#L69-L120), [Subsecond `apply_patch`](https://github.com/DioxusLabs/dioxus/blob/v0.7.10/packages/subsecond/subsecond/src/lib.rs#L498-L555), and [jump-table storage](https://github.com/DioxusLabs/dioxus/blob/v0.7.10/packages/subsecond/subsecond/src/lib.rs#L270-L321). + +The measured closure needs a second captured reference because of the bug discussed below. A separate successful probe used this simpler API: + +```rust +dioxus_devtools::connect_subsecond(); +// main owns state; each iteration calls the latest render implementation. +let output = subsecond::HotFn::current(render).call((&state,)); +``` + +## 2. Measured edit latency and builds + +The driver writes `src/main.rs`, closes it, records Python `time.time_ns()`, and waits for the first frame whose revision matches the edit. Rust records its epoch timestamp immediately after the patched call returns. Both clocks are on the worker. These numbers include filesystem watching, compilation/linking, patch delivery/loading, and the next actual call. They exclude syncing the source to the worker. The script makes ten revision edits in one process, with at least 30 observed frames between them. [Raw samples](../spikes/hot-patch/evidence/benchmark.json). + +| Edit | Save→new output, ms | Save→patch callback, ms | +|---:|---:|---:| +| 1 | 1,150.117 | 1,099.745 | +| 2 | 712.420 | 663.000 | +| 3 | 998.195 | 807.863 | +| 4 | 867.826 | 712.570 | +| 5 | 753.253 | 751.811 | +| 6 | 1,005.250 | 834.011 | +| 7 | 851.558 | 817.549 | +| 8 | 979.820 | 860.620 | +| 9 | 1,036.368 | 915.992 | +| 10 | 1,030.275 | 938.728 | +| **Median** | **989.008** | **825.780** | +| **p95, nearest rank** | **1,150.117** | **1,099.745** | + +With ten observations, nearest-rank p95 is the maximum. This is one short run on a shared worker, not a population estimate. The CLI's own ten reported hot-patch durations were 962, 523, 665, 575, 617, 695, 678, 723, 773, and 732 ms; their median is 686.5 ms. CLI duration alone omits part of the experienced delay. + +### Scheduling qualification + +The job runner launches jobs with background/utility scheduling and `nice 10`. The sleep-based 120 Hz loop was visibly batched: among 1,453 adjacent frame intervals, median was 0.004 ms, p95 16.917 ms, and maximum 207.965 ms. It catches up missed deadlines rather than presenting evenly spaced frames. Patch callback→first new output was 105.374 ms median and 190.332 ms maximum. + +These are actual background-worker measurements. They do not establish 120 Hz rendering quality or foreground-app latency. The callback timings still show that removing frame-wakeup delay alone would not get this run under 300 ms. A foreground-priority measurement would need a separate controlled run. + +### Comparison with normal builds + +| Operation | Wall time | Conditions | +|---|---:|---| +| Conventional artifact-cold build, final source | 71.333 s | Empty `target/normal-final`; dependencies already downloaded | +| Conventional incremental rebuild, final source | 1.846 s | One render constant changed; same target directory | +| Initial conventional cold build | 79.600 s | Earlier minimal source; included dependency resolution/download work | +| Initial conventional incremental rebuild | 1.672 s | Earlier minimal source | +| Initial `dx` hotpatch-enabled build | CLI reported 133.88 s | Separate DX artifact/profile cache; initial single-capture version | + +The final normal-build pair is the closer comparison. Both conventional builds exited successfully. The median live patch was about 1.87× faster than that single conventional incremental build, while also retaining the tested state. Conventional build timing stops at build completion and does not include app relaunch/state reconstruction. [Final build results](../spikes/hot-patch/evidence/builds.json), [initial build results](../spikes/hot-patch/evidence/initial-builds.json). + +## 3. What preserved state, what broke + +The ten body edits all retained PID `12294`, Vec address `4313468912`, and state address `6169897736`. At every first patched tick, the counter advanced, `vec0 == counter + 73`, and panel width remained 800. This establishes preservation of these existing main-owned values, not arbitrary Rust state. + +Each following probe began with a fresh process. The driver saved the source edit and observed the running output. [Probe results](../spikes/hot-patch/evidence/probes.json), [extra probes](../spikes/hot-patch/evidence/extras.json), [explicit boundary-signature probe](../spikes/hot-patch/evidence/extra-explicit_hotfn_signature.json). + +| Edit | Observed behavior | +|---|---| +| Generic `generic<T: Display>` body, `g0`→`g1` | New monomorphized behavior appeared in 811 ms; main-owned state preserved. This tests an existing `u64` instantiation, not all generic changes. | +| Closure body inside `render`, `value+10`→`value+20` | New result appeared in 974 ms; state preserved. | +| Trait implementation, direct `state.panel.label()` | `t1` appeared in 1,051 ms; state preserved. | +| Trait implementation with a `Box<dyn Label>` cached in main-owned state | Revision changed in 838 ms, but the trait call still returned `t0:42x24`. The existing object's vtable continued to call old code. | +| `render(&state)`→`render(&state, tone)`, with callsite changed inside the two-capture closure | `rev=99` appeared in 1,351 ms. The outer `FnMut() -> String` boundary stayed compatible, allowing its body and inner call to change together. | +| Same signature change when `HotFn::current(render)` was called directly from the original main loop | Patch callback fired, but old `rev=0` continued through the five-second observation. No automatic restart or panic was observed. The host's old call boundary was not replaced. | +| Append `extra: u64` to `AppState`; change its initializer in main | Patch accepted in 1,449 ms. Patched code reported size 56 instead of 48, while PID, state address, and existing contents remained. Main's new initializer did not run. No migration or incompatible-layout rejection occurred. | +| Atomic static initializer, 1000→9000 | First patched output was `static=9000`, rather than the next old counter value. Appeared in 1,123 ms. | +| Same static test after adding `#[unsafe(no_mangle)] pub` | Still reset to 9000; appeared in 1,104 ms. Exporting its symbol did not preserve it in this configuration. | +| Thread-local initializer, 2000→9000 | First patched output was `tls=9000`; appeared in 872 ms. | + +Even the ten ordinary revision edits reset the unchanged tip-crate static and TLS to 1000 and 2000 on each first patched frame. The [0.7.10 docs](https://docs.rs/subsecond/0.7.10/subsecond/#globals-statics-and-thread-locals) warn about tip-crate TLS, but claim globals are tracked and initializer edits are not observed. **The static probes did not match that claim.** This result is specific to the tested macOS tip-crate static; dependency statics were not tested. + +The struct probe deliberately did not explicitly read `extra`, to avoid turning an out-of-bounds read into a supposed success. Crossing that changed Rust type is already outside the supported safety contract. It demonstrates acceptance of an incompatible patch, not that adding fields is safe. The upstream [layout limitation](https://docs.rs/subsecond/0.7.10/subsecond/#struct-layout-and-alignment) explicitly leaves re-instancing to framework authors. + +### Pointer-sized capture bug + +The requested minimal `subsecond::call(|| render(&state))` compiled and ran normally, but a revision edit never appeared during the initial 30-second observation. A second isolated reproduction with a patch callback confirmed that a jump table was applied, yet old output continued for five seconds. [Initial failure](../spikes/hot-patch/evidence/pointer-capture-failure.json), [instrumented reproduction](../spikes/hot-patch/evidence/extras.json). + +The source explains this behavior. [`HotFn::try_call`](https://github.com/DioxusLabs/dioxus/blob/v0.7.10/packages/subsecond/subsecond/src/lib.rs#L411-L440) chooses function-pointer dispatch whenever the closure's size equals a function pointer's size. One captured reference satisfies that test. [`call_as_ptr`](https://github.com/DioxusLabs/dioxus/blob/v0.7.10/packages/subsecond/subsecond/src/lib.rs#L900-L949) then searches the jump table with those captured bytes, and falls back to the original callable when there is no match. The observed lack of a diagnostic is consistent with that fallback. + +Adding a second captured reference makes the measured closure follow the other dispatch path. The separate explicit-argument `HotFn` probe changed behavior in 918 ms with state preserved. Use that API with a stable signature rather than relying on the artificial second capture. Its signature-change probe also shows why the stable-signature restriction matters. + +## 4. iOS and GPU scope + +### Simulator + +Not executed. The worker had Xcode 27.1, no booted simulators, and only the `aarch64-apple-darwin` Rust target installed. More importantly, the release's [`start_ios_sim`](https://github.com/DioxusLabs/dioxus/blob/v0.7.10/packages/cli/src/build/apple.rs#L85-L145) boots a simulator and calls `open::that_detached` on `Simulator.app`. A straightforward `dx serve --ios` would violate this spike's no-visible-windows constraint. A headless simulator launcher would be a separate integration task. No simulator latency or state-preservation claim is made here. + +### Physical iPhone, researched only + +The [Subsecond 0.7.10 platform documentation](https://docs.rs/subsecond/0.7.10/subsecond/#platform-support) explicitly excludes devices because of code-signing requirements. The [release architecture note](https://github.com/DioxusLabs/dioxus/blob/v0.7.10/notes/architecture/07-HOTRELOAD.md) also lists iOS Simulator support and device hot-patching as unsupported. + +Ordinary device deployment needs the `aarch64-apple-ios` target, a signed development app with matching bundle ID/provisioning profile, a development identity, Developer Mode/device trust, and transport to the device. The CLI's [Apple signing path](https://github.com/DioxusLabs/dioxus/blob/v0.7.10/packages/cli/src/build/apple.rs#L282-L363) embeds a provisioning profile and signs the bundle; its generated development entitlements include `get-task-allow`. The [device-serving discussion](https://github.com/DioxusLabs/dioxus/discussions/3545) reports ordinary `dx serve --ios --device` working in 2026. That does not establish Rust dylib hot-patching. + +Subsecond additionally needs each newly generated patch to reach the running app, load as executable code under iOS's signing restrictions, and be mapped to that process's ASLR addresses. I found no supported turnkey device path in this release. A proposed debugger-assisted or signed-patch loader remains unverified engineering work; a simulator result would not remove this blocker. + +### GPU + +The optional wgpu/Metal extension was not attempted. This spike preserves CPU heap allocations and state, not a verified live GPU device/queue/texture. Owning GPU resources outside the patched code is a plausible design, but cached callbacks/vtables and changing Rust wrapper layouts would still need attention. + +## Steal + +- Use explicit patch boundaries around a small UI-logic function, with state owned by a stable host. +- Keep the compiler/linker cache warm and compile the smallest changing crate. Subsecond documents that only the executable's tip crate patches; `mod` files in that crate fit better than a changing library dependency. [Workspace limitation](https://docs.rs/subsecond/0.7.10/subsecond/#workspace-support). +- Record save time, patch-applied time, and first new frame separately. Verify state with identities and content invariants rather than a CLI success message. +- Reuse the ASLR/PID/build-ID protocol if implementing a smaller Rune-specific transport. The existing adapter is sufficient for an initial experiment. + +## Avoid + +- Promising approximately 300 ms from the name “Subsecond” or its compiler timer alone. +- Treating arbitrary captured closures, changed type layouts, tip-crate statics, or persistent trait-object vtables as transparently reloadable. +- Assuming a successful Rust build or patch callback means the application is executing new code. +- Designing the connected-iPhone workflow around an unverified device patch loader. + +## Recommendation for Rune + +Keep Subsecond as an optional **desktop development backend** worth evaluating with a realistic Rune renderer. Put long-lived state and GPU ownership in a stable host, expose explicit patch functions with stable argument/return shapes, and rebuild or migrate state on incompatible schema changes. Replace cached callbacks or trait objects when their implementation changes. Any such migration and invalidation machinery belongs to Rune; this spike did not implement it. + +Reject Subsecond 0.7.10 as the **sole Mac-and-iPhone hot-reload layer** for now. The measured latency misses the target, physical devices remain unsupported, and several ordinary Rust patterns silently keep old behavior or lose state. Also reject “wrap everything in `subsecond::call`” as an integration strategy, and do not change the entire renderer to Dioxus just to obtain its compiler tooling: the standalone integration already works. + +Normal rebuild/relaunch is the known fallback for incompatible Rust changes, but it does not satisfy the requested state-preserving iteration loop. A runtime-editable UI/layout description could cover frequent visual edits without recompilation; that is a candidate for a separate measurement, not a result of this spike. + +## Open questions + +1. How much faster is the same end-to-end test under a real foreground app's scheduling policy, and with Rune-sized dependencies? +2. Can the pointer-sized capture and tip-static behavior be fixed upstream or constrained reliably in an adapter? +3. How should Rune detect incompatible schema changes before applying a patch and migrate state across them? +4. What is the practical memory growth over hundreds of patches, given retained libraries and jump tables? +5. Can a supported, repeatable physical-iPhone patch loader meet the target without restarting the app? +6. Do real wgpu/Metal resources survive patches once cached callbacks, vtables, and renderer-thread coordination are included? diff --git a/app/vendor/rune/research/09-agent-native-and-perf-targets.md b/app/vendor/rune/research/09-agent-native-and-perf-targets.md new file mode 100644 index 0000000..1f3d052 --- /dev/null +++ b/app/vendor/rune/research/09-agent-native-and-perf-targets.md @@ -0,0 +1,467 @@ +# Agent-native tooling and performance targets for Rune + +Research date: 2026-10-21. Reader: Kit and the Rune architecture team. This report supports a decision about the first tooling interfaces and the workloads that should define “fast.” All Rune interfaces and budgets below are proposals, not implemented features or measured results. + +## Summary + +- Make the scene runner, inspector protocol, clock, and trace schema part of the framework's first architecture. Adding them after applications exist makes deterministic verification much harder. +- Give agents stable semantic IDs, small tree queries, computed geometry, presentation values, source locations, and structured errors. A screenshot alone cannot explain which constraint, state update, or animation caused a failure. +- Use deterministic offscreen rendering for correctness and dedicated devices for performance. Virtual time can prove a spring's continuity; it cannot prove that the GPU presented its frames on time. +- Reuse Scrawl's motion-trace JSONL format, Scrawl's named scene labs, the layout linter's invariant checks, and knobs' remote parameter descriptors. Keep a richer internal trace so the compatibility format does not constrain the renderer. +- Published startup, memory, and size comparisons are useful only with their measurement boundaries attached. One widely cited toolkit benchmark measures container memory rather than process RSS, and its dependency sizes are Docker image deltas. +- Current small Rust app measurements put stripped executables roughly in the 4–14 MiB range for GPUI, egui, Iced, Slint, and Tauri. These are small todo apps on one Mac, not a universal hello-world baseline. +- Set initial Mac goals of fresh-process first presentation p95 ≤200 ms, idle hello-app process RSS ≤50 MiB, and a stripped arm64 hello executable ≤5 MiB. These are proposed engineering budgets, not claims that every platform can already meet them. +- At 120 Hz, gate a defined workload against 8.333 ms presentation opportunities. Start with 1,000 inexpensive animated quads, a separately specified effects scene, and one million virtualized rows. An unspecified “number of animated layers” is not a useful benchmark. +- Measure physical input-to-photon on a dedicated fixture and event-to-presentation in ordinary device CI. Keep the two metrics separate. Published latency rankings change with compositor configuration, refresh rate, and measurement method. +- The <300 ms reload goal should initially cover state-preserving UI, style, asset, and tuning edits. Ordinary Rust code changes need their own rebuild budget and explicit state migration behavior. + +## A. Build an interface that agents can inspect and replay + +### A1. Determinism requires a complete execution contract + +Playwright explicitly warns that screenshots vary with OS, browser version, hardware, power settings, and headless mode. Its screenshot assertion waits for two matching screenshots before comparing, but this is a stabilization heuristic, not a determinism guarantee. Its default perceptual threshold is 0.2. [Playwright visual comparisons](https://playwright.dev/docs/test-snapshots) + +Flutter's golden matcher documents its default Ahem test font and warns that fonts can render differently across platforms and Flutter versions. Point-Free's Swift snapshot library similarly requires the same simulator for image reference comparisons. These are good reasons to pin rendering environments and retain semantic snapshots alongside pixels. [Flutter goldens](https://api.flutter.dev/flutter/flutter_test/matchesGoldenFile.html), [Swift SnapshotTesting](https://github.com/pointfreeco/swift-snapshot-testing) + +**Proposed contract:** every replay artifact records the framework revision, scene revision, renderer/backend, OS image, GPU/driver, logical viewport, pixel scale, output color space, font and asset hashes, locale, text direction, seed, clock policy, and fixture versions. Fix font fallback explicitly. An unavailable font should fail the fixture instead of silently changing line wrapping. + +Control these inputs through injected services: + +| Input | Deterministic scene behavior | Real-device behavior | +|---|---|---| +| Monotonic clock, timers, animation tick | One manually advanced clock | Host monotonic time, with recorded display deadlines | +| Wall clock, random values, IDs | Fixed wall epoch and seeded generators | Actual services; record seeds where applicable | +| Network, files, permissions, clipboard | Named fixture responses and ordered completions | Platform integration suite | +| Async completions | Replay scheduler releases recorded completions | Normal executor; record event order | +| Fonts and images | Pinned bytes; explicit decode/upload readiness | Same assets, real upload timings | +| Window and environment | Fixed size, scale, appearance, insets, locale | Physical display and current device configuration | +| Input | Timestamped events through normal hit-testing/dispatch | OS-delivered events and real touch/HID fixture | + +“Idle” must mean no pending work relevant to the requested frame. It must not mean “wait forever for all tasks,” because an app can contain polling, cursors, and perpetual animations. Expose `settle` with a bounded deadline and a diagnostic list of remaining work. Expose a separate exact-time render that deliberately permits active animations. + +Use two pixel lanes: + +1. **Canonical correctness:** pinned offscreen backend and environment; exact hashes where repeatable. Save expected, actual, diff, semantic tree, and layout tree on failure. +2. **Platform fidelity:** actual Metal/WebGPU/other backend with separately keyed baselines. Allow only explicitly justified regional tolerance, with changed-pixel and edge limits. Font/platform changes require their own baseline review. + +Skia Gold's accepted image hashes and configuration dimensions are a useful model. It supports multiple accepted exact images as well as fuzzy/Sobel matching. Broad fuzzy thresholds can hide real damage, so they should not be the default response to nondeterministic tests. [Chromium GPU pixel tests with Gold](https://chromium.googlesource.com/chromium/src/+/main/docs/gpu/gpu_pixel_testing_with_gold.md) + +A software renderer, if Rune has one, would be a useful canonical lane but cannot stand in for testing the shipping GPU renderer. Avoid committing to a second renderer solely to get screenshots before assessing the maintenance cost. + +### A2. The inspector should answer causes as well as shapes + +Several existing tools provide complementary pieces: + +| System | Useful mechanism | Limitation or lesson | +|---|---|---| +| Flutter Inspector | Creation locations, widget/render-object inspection, constraints and layout exploration | Rune needs both logical ownership and render/layout objects, rather than pretending one tree explains everything | +| Dart VM service | Versioned JSON-RPC 2.0 over WebSocket, subscriptions, object IDs, service extensions | Make ID lifetime, version negotiation, and stream loss explicit | +| Chrome DevTools Protocol | DOM snapshot, computed CSS, full accessibility tree, input dispatch, animation controls, virtual time | Copy a coherent subset; implementing the entire web protocol would impose irrelevant semantics | +| React DevTools | Compact tree-operation messages and lazy inspection of properties | Avoid serializing every property of every node on every frame | +| SwiftUI/Xcode | Mixed SwiftUI/UIKit hierarchy inspection; invalidation diagnostics | `_printChanges` is a debugging-only, best-effort explanation, not a stable machine protocol | +| Dioxus devtools | Source keys using file/line/column/index; build/PID checks before patching | Useful patch provenance; its transport should not be mistaken for a complete geometry inspector | + +Sources: [Flutter Inspector](https://docs.flutter.dev/tools/devtools/inspector), [Dart VM service specification](https://raw.githubusercontent.com/dart-lang/sdk/main/runtime/vm/service/service.md), [CDP schema](https://raw.githubusercontent.com/ChromeDevTools/devtools-protocol/master/json/browser_protocol.json), [React DevTools architecture](https://github.com/facebook/react/blob/main/packages/react-devtools/OVERVIEW.md), [SwiftUI performance](https://developer.apple.com/videos/play/wwdc2023/10160/), [Xcode hierarchy debugging](https://developer.apple.com/videos/play/wwdc2019/412/), [Dioxus devtools source](https://raw.githubusercontent.com/DioxusLabs/dioxus/main/packages/devtools/src/lib.rs). + +**Proposed node record:** stable app-defined key, generation-scoped runtime ID, role/name/state, logical parent, layout parent, render parent, source location, model/layout/presentation bounds, effective clip, transform, opacity, z-order, hit-test eligibility, focus, owning state dependencies, last invalidation cause, and active animations. Properties that are expensive to compute should be requested lazily. + +Keep the coordinate systems explicit: logical points versus device pixels; local, window, and screen bounds; pre-transform versus post-transform; geometry versus visible clipped geometry. A model rectangle can be correct while its presentation rectangle jumps or its effective opacity becomes zero. + +Add queries for the questions an agent actually asks: + +- Why is this node invisible, unclickable, clipped, or outside its parent? +- Which constraint set its width, and which ancestor supplied that constraint? +- What invalidated this subtree, and how many layout/paint passes followed? +- Which node received this input, and why did the expected node lose hit-testing? +- Which state read keeps this component subscribed, and what was the last write? +- Which animation owns this presentation property, and what happened when it retargeted? + +Use accessible role/name/state queries for normal automation. Playwright's ARIA snapshots show how compact a useful semantic contract can be. Retain explicit test IDs for repeated or unnamed objects, plus stable item keys for virtualized collections. Do not use array index as list identity. [Playwright ARIA snapshots](https://playwright.dev/docs/aria-snapshots) + +### A3. A small versioned protocol can serve the CLI and visual inspector + +The following API is a proposed design sketch. It is not a description of an existing Rune tool. Use JSON-RPC 2.0 with generated Rust types and JSON Schema; expose stdio for a spawned scene runner and an explicitly enabled local socket/WebSocket for a running development app. Ship no listening inspector in normal release builds. + +| Domain | Initial methods | Important semantics | +|---|---|---| +| Session | `hello`, `capabilities`, `subscribe` | Protocol/schema versions, build ID, scene epoch, supported operations | +| Scene | `list`, `load`, `reset`, `settle` | Named fixtures, seeded reset, bounded completion, new epoch on reset | +| Tree | `query`, `snapshot`, `inspect`, `explain` | Role/key selectors, depth limits, lazy properties, invalidation reasons | +| Input | `pointer`, `key`, `text`, `scroll`, `touch` | Timestamp, pointer identity, coordinate space, dispatched/processed frame IDs | +| Clock | `pause`, `advance`, `seek`, `setRate` | Monotonic advance; backward seek resets and replays rather than reversing physics | +| Capture | `image`, `semantics`, `layout` | Capture all three at one frame ID; explicit GPU completion/readback | +| Animation | `list`, `inspect`, `retarget` | Position, velocity, target, duration/bounce, lifecycle, property ownership | +| Trace | `start`, `stop`, `status` | Chosen channels, bounded buffers, dropped-event count, capture overhead | +| Tune | `list`, `set`, `setBatch`, `reset` | Typed descriptors, atomic batch revision, applied frame ID | + +Example request and abbreviated response: + +```json +{"jsonrpc":"2.0","id":17,"method":"Tree.inspect","params":{"selector":{"key":"composer.send"},"epoch":4,"fields":["source","layout","presentation","hitTest"]}} +``` + +```json +{"jsonrpc":"2.0","id":17,"result":{"epoch":4,"frame":73,"node":"4:208","key":"composer.send","source":{"file":"src/composer.rs","line":82},"layout":{"space":"window-points","rect":[280,640,44,44]},"presentation":{"rect":[280,648,44,44],"opacity":1},"hitTest":{"eligible":false,"reason":"covered","by":"4:219"}}} +``` + +Node IDs expire on removal or epoch change. A stale selection returns a structured `StaleNode` error with the observed/current epoch; it must never resolve to a newly reused allocation. Mutation requests carry the expected scene/build revision. Stream records carry sequence numbers so a client can request a fresh snapshot after a gap. Large captures return artifact handles rather than embedding megabytes of PNG data in tree messages. + +The CLI is a thin client of the same protocol: + +```sh +# Proposed commands, not runnable today. +rune scene list --json +rune scene run composer/send --seed 7 --clock manual --headless --out run/ +rune inspect --key composer.send --fields layout,presentation,source --json +rune input pointer --phase down --x 300 --y 660 --at-ms 200 +rune clock advance --ms 8.333333 +rune capture --frame current --image --layout --semantics --out frame/ +rune trace stop --formats native,motion-trace,perfetto --out run/ +``` + +Use stable machine-readable stdout, diagnostics on stderr, meaningful exit status, and bounded requests. `text` injection should be separate from physical key events and IME composition so an agent does not accidentally claim keyboard/IME coverage from a direct model mutation. Semantic activation is useful for functional tests, but it does not exercise pointer routing or establish latency. + +### A4. Named scenes should replay real UI with fake external services + +Scrawl already has a good local example: `scrawl lab pill <scene>` replays named capsule states with a pretend recording and no mic/capture/ingest side effects. The lab supports time scaling and per-frame motion traces; tuning values reload within 250 ms. This is stronger than a gallery of inert components because it drives the transition sequence used by the app. [Scrawl's AGENTS.md](https://github.com/kitlangton/scrawl/blob/main/AGENTS.md), implementation in `scrawl/src/ui/lab.rs` and `scrawl/src/ui/motion.rs`. + +Rune should let every feature register scenes next to its implementation. A scene supplies initial state, fixture services, stable keys, and an input script. Include empty/loading/error states, long text, large text settings, right-to-left layout, keyboard appearance, interruptions, rapid repeated input, resize, and background/resume when relevant. + +Proposed scene manifest: + +```json +{ + "schema": 1, + "scene": "composer/send-interrupted", + "seed": 7, + "viewport": {"width": 390, "height": 844, "scale": 3}, + "environment": {"locale": "en-US", "appearance": "dark"}, + "fixtures": {"messages": "two-short", "send": "complete-at-800ms"}, + "steps": [ + {"atMs": 0, "input": {"activateKey": "composer.send"}}, + {"atMs": 90, "input": {"activateKey": "composer.cancel"}}, + {"atMs": 120, "capture": ["image", "layout", "semantics"]}, + {"atMs": 500, "assert": {"key": "composer.send", "visible": true}} + ] +} +``` + +This functional example uses semantic activation; a sibling pointer/touch scene should verify hit-testing and gesture cancellation. All operations happen through the same dispatch and animation machinery as the app. A fake transport completes a send; it does not swap in a different presentation implementation. + +Record enough input and service completion data to replay a failure. Seeded random values alone do not make concurrent task scheduling reproducible. For deterministic tests, replay ordered external completions; for real-world race detection, run separate scheduling/fuzz tests. + +### A5. Time control must preserve animation semantics + +All springs, delays, transitions, gesture velocity calculations, and animation lifecycle decisions should read one injected monotonic clock. Keep wall time and networking deadlines separate. Pause should freeze animation without accidentally preventing the inspector from responding. + +Test a transition at exact time, at a regular 60/120 Hz sample interval, and with irregular intervals. Retarget at several points while preserving current position and velocity. Test cancellation, removal/reinsertion with the same key, and reduced motion. Verify that lifecycle events occur once and that an outgoing surface remains until its visual contribution ends. + +Do not implement time scaling by simply multiplying every spring parameter or by slowing some timers but not others. Advance the shared simulation clock; report both simulation and wall time. Define whether an animation uses analytic evaluation or integration and retain that definition across replay. Large time jumps must have explicit event-processing behavior. + +CDP's `Emulation.setVirtualTimePolicy` and `Animation.seekAnimations`/`setPaused`/`setPlaybackRate` demonstrate the value of separate scheduling and animation controls. Rune can provide a more coherent clock because it owns both. [CDP schema](https://raw.githubusercontent.com/ChromeDevTools/devtools-protocol/master/json/browser_protocol.json) + +### A6. Reuse Kit's trace tools without corrupting timing measurements + +#### Scrawl's motion-trace JSONL is the initial exchange format + +The current writer has a header with `type`, `launch`, `width`, `height`, `hz`, `scale`, `wall`, and optional `platform`, `clock`, `units`, `sampleHz`. Frame records use fields including `t`, `n`, `sc`, `ct`, `m`, `e`, `g`, `cm`, `c`, `cg`, `tx`, `tf`, `k`, `bg`, `s`, and `ev`. `t` is milliseconds; `ct` is seconds. Metadata entries use `{id,cls,nm,view,host,ax,pv}` and geometry entries start `[id,x,y,w,h,opacity,radius,flags]`, optionally followed by visible-rectangle values. The writer rounds geometry to 0.01 and opacity to 0.001. Sources: the internal motion linter's writer, run discovery and README. + +Important compatibility detail: virtual sweeps deliberately use `hz:60` and `sc:60*dt`. A 120 Hz virtual sample therefore uses `sc:0.5`, with sampling frequency represented separately. Do not set `hz:120` in an adapter and silently change the motion linter's normalization assumptions. Validate an adapter against actual writer output and parser fixtures. + +Export stable node IDs, presentation rectangles, effective opacity, visible clips, scalar channels, and transition events. Include channels for blur, mask progress, spring position/velocity, and ownership/gating where supported. Keep full-precision values in Rune's native trace because rounded motion-trace geometry is unsuitable for some numerical continuity checks. + +#### The internal layout linter supplies a useful failure model + +The internal layout linter reports shared-line near misses, clipping, overflow, and off-center icons. Its candidate-fix mode applies one change at a time, remeasures, and rejects changes that break previously satisfied invariants. Its scope isolation prevents comparing a transformed device stage's internal coordinates to unrelated page chrome. (the layout linter's README.) + +For Rune, expose geometry so equivalent rules can run directly on layout snapshots. Return signed deltas, node keys, relevant ancestors, source locations, and the violated invariant. Do not automatically “fix” deliberate asymmetry. Let scenes declare alignment groups, allowed overlap, intentional overflow, and hit-target constraints. + +#### A motion inspector supplies presentation-level evidence + +A private iOS client's tooling document was recovered from Git history (revision `632aea45`) because it is absent from the current checkout. Its motion inspector's documentation describes capture of presentation geometry, opacity, transforms, blur, masks, Core Animation springs, source locations, and tunable keys. It reports approximately 0.8–2 ms/frame capture overhead, with serialization deferred until capture stops. These are historical tooling observations, not a Rune overhead target. + +Reported failures caught by this tooling include duplicate morph surfaces, gaps during opacity handoffs, premature layer retirement, geometry jumps, and stacked blur overdraw. Those cases should become named Rune regression scenes. Continuity checks need property ownership and lifecycle data as well as rectangles; otherwise an intentional exit can look like a teleport or a missing surface can simply vanish from the sample set. + +#### Knobs supplies the tuning interface + +Knobs' remote descriptor protocol supports typed values, spring descriptors with `{duration,bounce}`, single and batched setters, and incoming synchronization without echo. Expose the same descriptor vocabulary through `Tune.*`; acknowledge the applied revision/frame so an agent knows which capture contains its change. Keep tune keys linked to source declarations and active animation IDs. ([knobs README](https://github.com/kitlangton/knobs#readme), remote controls section.) + +#### Separate correctness capture from performance capture + +The internal motion linter warns that walking all layers can add milliseconds per frame, that display-link probes miss render-server/GPU lateness, and that simulator hitch results are relative. A 2 ms observer would consume 24% of a 120 Hz budget. (the motion linter's README.) + +Provide three modes: + +| Mode | Data | Use | +|---|---|---| +| Full deterministic | Every node/property, exact state, input, screenshots on request | Correctness and explanation; no speed claims | +| Low-overhead real time | CPU spans, GPU timestamps, frame IDs, presentation feedback, counters, selected animations | Performance gates; record overhead and dropped data | +| Focused diagnosis | Selected subtree/layers and optional screenshots | Explain a known hitch; compare with the low-overhead run | + +Record input arrival → dispatch → state change → layout → paint encoding → submission → GPU execution → actual presentation where the platform exposes it. Preserve clock domains and calibration uncertainty. GPU completion is not presentation, and a display callback is not proof the submitted frame was visible. + +Prefer Perfetto TrackEvent protobuf for the detailed timeline; optionally export Chrome trace JSON for easy inspection. Chrome JSON has nesting constraints and is not an unrestricted event format. Tracy is a useful optional live profiler for CPU/GPU/allocations/locks, but integrate its client instead of promising an invented universal `.tracy` exporter. [Perfetto formats](https://perfetto.dev/docs/getting-started/other-formats), [conversion guidance](https://perfetto.dev/docs/getting-started/converting), [Tracy](https://github.com/wolfpld/tracy) + +### A7. Rust APIs should make common agent mistakes hard to express + +Zed's own contributor guidance documents incorrect context borrowing in nested closures, nested updates that panic, dropped tasks/subscriptions, missing notification after mutation, and misuse of test clocks. These are concrete failure modes in a mature Rust UI codebase. Dioxus documents runtime borrow panics when signal borrows cross `await`, and handles whose owner has already been disposed. [Zed contributor rules](https://raw.githubusercontent.com/zed-industries/zed/main/.rules), [Dioxus signals](https://dioxuslabs.com/learn/0.7/essentials/basics/signals/) + +| Failure mode | Proposed Rune response | +|---|---| +| State changes without redraw | Updates invalidate automatically within a typed transaction; expose the dependency graph | +| Runtime borrow held across `await` | Async task API takes owned input snapshots and returns a message; keep UI mutation on the UI executor | +| Reentrant entity mutation | Queue an update or return a structured diagnostic with both call sites; avoid hidden nested borrowing | +| Dropped task/subscription | Explicit owner-scoped tasks and subscriptions, with visible cancellation reason and optional deliberate detach | +| Stale callback after component removal | Generation-checked weak target; cancellation tied to owner lifetime | +| List reorder resets state or motion | Required stable item keys for stateful virtualization; duplicate-key diagnostics | +| Layout depends on hidden context | Named constraints and computed provenance available through inspector | +| Model bounds mistaken for visible bounds | Separate model/layout/presentation/visible geometry in types and protocol | +| Incorrect hot-reload assumptions | Capability report says which edits patch, migrate, or restart; preserve old runnable app on failed patch | +| Examples use a different framework version | Versioned docs, small compiling examples, generated API schema, diagnostic links to installed version | + +Favor small explicit operations and typed IDs over deeply generic builder types exposed in every error. Keep engine complexity behind modules. A useful compiler/runtime error names the operation, expected owner/thread/epoch, actual value, source location, and likely repair. Avoid making agents reverse-engineer a 200-line generic mismatch to discover an expired node. + +The 2026 ecosystem experiment supplies additional agent-specific observations: agents had to consult vendored source because examples/docs did not match installed versions; a feature-gated Iced timer produced an unhelpful missing-function error; webview drag defaults swallowed intended events; and the GPUI example had to hand-roll a limited text input without IME/selection/clipboard. These are documented implementation experiences, not a controlled study of LLM success rates. Rune should ship a complete standard text-input path and version-matched executable examples before treating agent code generation as solved. [Interactive experiment and caveats](https://github.com/GoldStrikeArch/rust-gui-desktop-ecosystem-state/blob/main/report/11-interactive-results.md) + +Dioxus distinguishes RSX/literal/asset hot reload from Rust hotpatching and changes that require rebuilding. Rune should be equally specific. “Hot reload” must not imply arbitrary Rust type-layout changes in <300 ms. [Dioxus hot reload](https://dioxuslabs.com/learn/0.7/essentials/ui/hotreload/) + +## B. Published measurements support budgets, not a universal ranking + +### B1. Evidence labels and measurement boundaries + +The tables distinguish **reproducible-source measurements** (published harness or raw results), **reported observations** (a concrete configuration but incomplete reproduction), **speaker claims**, and **proposed targets**. Published source does not mean this research independently reran the benchmark. No framework builds or device benchmarks were run for this report. + +Keep these boundaries separate: + +- Fresh process versus cache-cold start versus first launch after installation. +- App entry, window creation, first GPU submission, first presentation, and interactive readiness. +- Single-process RSS, total app/process-tree RSS, physical footprint, GPU allocations, and container memory. +- Stripped executable, resources, app bundle, compressed download, installed runtime, and system-provided dependencies. +- Software event-to-screen-sample versus software event-to-presentation versus physical input-to-photon. +- Average fps, CPU frame duration, GPU duration, and missed presentation opportunities. + +### B2. Startup results span different workloads and clocks + +| Source and status | Workload/configuration | Published result | What it establishes | +|---|---|---|---| +| Zed March 2026 user measurement | Zed 0.226.5, M2 Pro, macOS 15.5; launch-to-first-frame log | New window/no warmup mean 258 ±78 ms; restored 273 ±51; warm 225 ±18; clean config/warm 221 ±14 | A full editor can report first frame in a few hundred ms. Occasional 1–2 s cold launches were reported but not quantified | +| September 2026 GPUI discussion, weaker report | M4 Max, 5K/144 Hz, 100k rows, 15 fresh processes | Median/p95: GPUI 152.5/159.6 ms; egui 158.1/165.2; Slint 190.2/252.4; AppKit 155.1/165.8 | Suggests an approximately 200 ms small-app budget is plausible; no linked raw harness, not cache-cold or hello-world | +| Kalbertodt 2023, reproducible comparison | Ubuntu 20.04, X11/Nvidia, OBS at 60 Hz | Tauri ≈380 ms; Iced ≈230 ms; egui ≈280 ms | Older small-app screen-based observation, platform-specific and frame-quantized | +| IronOxidizer raw results and harness | Containerized Linux toolkit samples; five launches | Iced 99 ms; egui 175 ms; Tauri 470 ms; Electron 717 ms | Startup measures image stabilization after container start, not a universal launch-to-first-present metric | +| Jacob Ras 2023 app comparison | Cat-image app, iPhone 12 mini, AppLaunch measurement | SwiftUI 1.441 s; Flutter 1.608 s | A concrete mobile app comparison; not hello-world and not directly comparable to desktop logging | + +Sources: [Zed launch measurements](https://github.com/zed-industries/zed/discussions/51187), [September GPUI report](https://github.com/zed-industries/zed/discussions/63832), [2023 Rust GUI comparison](https://lukaskalbertodt.github.io/2023/02/03/tauri-iced-egui-performance-comparison.html), [IronOxidizer results](https://raw.githubusercontent.com/IronOxidizer/gui-toolkit-benchmarks/main/utils/result.json), [IronOxidizer harness](https://raw.githubusercontent.com/IronOxidizer/gui-toolkit-benchmarks/main/utils/benchmark.py), [Flutter/native/KMP app and measurements](https://github.com/jacobras/flutter-vs-native-vs-kmp). + +The last source also reports a Pixel 4a Android median of 634.2 ms for Flutter versus 413.1 ms native. Keep mobile OS launch policy in view; a Mac process-start goal should not become an unexplained iPhone cold-launch promise. + +### B3. Binary sizes are available; comparable hello-world idle RSS is missing + +A July 2026 AI-assisted ecosystem study publishes raw measurements for identical small todo apps on M4 Pro/24 GiB, macOS 26.5.2, rustc 1.96.1. These are useful disclosed experiments, with less independent validation than a maintained benchmark suite. The following conversions use 1 MiB = 1,048,576 bytes. [Method/results](https://github.com/GoldStrikeArch/rust-gui-desktop-ecosystem-state/blob/main/report/10-empirical-results.md), [raw CSV](https://raw.githubusercontent.com/GoldStrikeArch/rust-gui-desktop-ecosystem-state/main/measurements/results-iter1.csv) + +| Framework | Stripped executable, exact bytes | MiB | Clean / incremental build, seconds | Separate active-dashboard max RSS | +|---|---:|---:|---:|---:| +| GPUI | 4,467,704 | 4.26 | 56 / 1 | 79 MiB | +| egui | 11,054,344 | 10.54 | 27 / 1 | 109 MiB | +| Iced | 8,885,624 | 8.47 | 22 / 2 | 95 MiB | +| Slint | 13,873,752 | 13.23 | 42 / 4 | 95 MiB | +| Tauri | 6,682,264 | 6.37 | 36 / 10 | 211 MiB, including helpers | + +Versions were GPUI 0.2.2, egui/eframe 0.35.0, Iced 0.14.0, Slint 1.17.1, and Tauri 2.11.5. In particular, the published GPUI crate does not represent every change on Zed's current main branch. Profiles used framework defaults with `strip -Sx`, rather than identical custom LTO settings. + +The RSS column is the maximum over a 30-second sample of a different workload, a 10 Hz dashboard. The report explicitly did not retain a controlled idle dataset; webview helper attribution was best-effort. Do not call these idle hello-world numbers. Build caches had a warm registry but clean targets; incremental measurements after touching a source file do not prove the cost of a meaningful semantic edit. [Interactive results](https://github.com/GoldStrikeArch/rust-gui-desktop-ecosystem-state/blob/main/report/11-interactive-results.md) + +Other requested frameworks and older comparison data: + +| Framework/source | Available measurement | Why it does not fill the hello-world idle-RSS gap | +|---|---|---| +| Electron, IronOxidizer | Container memory 192,814 KiB; source/executable field 1 KiB; dependency-image delta 1,327,205 KiB | The 1 KiB entry is not a shipped Electron app. Docker image delta is not runtime distribution size | +| Iced, same harness | Container memory 47,397 KiB; executable 4,496 KiB | Container memory includes more than process RSS | +| egui, same harness | Container memory 52,100 KiB; executable 10,597 KiB | Same restriction; versions/platform differ from the Mac table | +| Tauri, same harness | Container memory 109,117 KiB; executable 4,918 KiB | Same restriction, including WebKit/runtime accounting | +| SwiftUI, Jacob Ras 2023 | Thinned iOS app 1.7 MB | Real cat-image app; system SwiftUI dependencies are not bundled | +| Flutter, same app | Thinned iOS app 17.9 MB | Same app/platform comparison is meaningful, but not a framework-only size | +| Makepad, 2022 talk | Desktop ZIP ≈1 MB; web Brotli ≈500 KB; UI construction ≈1 ms | Speaker claims about a particular demo; ZIP is not executable size and construction time is not launch-to-present | +| Makepad, 2025 Linux/Nvidia issue | User reported ≈300 MB for an empty release window and idle CPU activity | Bug report, not a current baseline; September 2026 closure reports idle fixes and lazy font loading | + +Sources: [IronOxidizer raw data](https://raw.githubusercontent.com/IronOxidizer/gui-toolkit-benchmarks/main/utils/result.json), [measurement code](https://raw.githubusercontent.com/IronOxidizer/gui-toolkit-benchmarks/main/utils/benchmark.py), [SwiftUI/Flutter comparison](https://github.com/jacobras/flutter-vs-native-vs-kmp), [Makepad talk](https://gitnation.com/contents/makepad-leveraging-rust-wasm-webgl-to-build-amazing-cross-platform-applications), [Makepad issue #787](https://github.com/makepad/makepad/issues/787). + +The critical IronOxidizer source expression is `container.stats()["memory_stats"]["usage"]`. Relabeling this field as RSS would create a false comparison. There is insufficient evidence here for a complete, current, same-device hello-world idle-RSS ranking of GPUI, egui, Iced, Slint, Tauri, Electron, SwiftUI, Flutter, and Makepad. + +### B4. Input latency depends strongly on how it is measured + +Typometer injects OS keyboard events and samples pixels. It measures a useful software path but excludes the physical input device and display scanout. A camera or photodiode covers a different interval. [Typometer implementation and method](https://github.com/pavelfatin/typometer) + +Recomputed from matklad's published CSV, 200 samples per condition, nearest-rank p95: + +| App / condition | Mean | p95 | +|---|---:|---:| +| VS Code, compositor off | 17.80 ms | 31.22 ms | +| Sublime Text 3, compositor off | 7.04 ms | 8.01 ms | +| VS Code, compositor on | 36.97 ms | 49.56 ms | +| Sublime Text 3, compositor on | 22.57 ms | 25.77 ms | + +[Raw historical CSV](https://gist.githubusercontent.com/matklad/cf9080a2e6c600d05f12263b24e4b12e/raw/data.csv). These are older software measurements, not a current macOS or physical-input benchmark. The compositor difference is large enough to overwhelm many framework-level improvements. + +Additional evidence: + +- A 2022 VS Code latency experiment reports Typometer means at Windows/60 Hz of the proposed VS Code build 17.6 ms, Sublime 34.2 ms, and an Electron textarea with vsync disabled 16.7 ms. The author discusses the refresh-related floor and ultimately abandons the change because earlier DOM updates did not cause earlier browser rendering. This demonstrates why “Electron always has X ms latency” is not defensible. [VS Code PR #164192](https://github.com/microsoft/vscode/pull/164192) +- A weak 2026 user report gives M2 Pro means of Zed 26.3 ms, Sublime 25.9 ms, and VS Code 20.6 ms, with p95 36.8/33.5/31.7 ms. There is no raw harness, so use it only as contrary evidence against an assumed ranking. [User report](https://news.ycombinator.com/item?id=47959402) +- Historical 240 fps camera tests report VS Code at 116.7 ms on a Windows Dell XPS 13 and 95.8 ms on Ubuntu. A 240 fps camera quantizes observation at approximately 4.17 ms. These cannot be compared directly to Typometer numbers. [Is It Snappy](https://isitsnappy.com/) +- A June 2025 Flutter issue uses an FSR, photodiode, and Bela sampling at 44.1 kHz on an iPad M3 Pro. It reports basic Swift mean 67.8 ms, n=151, and basic Flutter 77.2 ms, n=209. Action semantics and application/network behavior matter; this is not a universal iPhone framework constant. [Physical touch benchmark](https://github.com/flutter/flutter/issues/170735) +- A recent Flutter touch-delivery issue reports smoothing delayed approximately 99% of packets by one vsync, alongside 120 Hz delivery-spread values around 0.18–0.21 ms. Delivery jitter is not end-to-end touch latency. [Flutter touch scheduling](https://github.com/flutter/flutter/issues/191199) + +**Conclusion:** a reasonable Rune goal is minimal extra scheduling delay after input arrives, with physical qualification against an equivalent native control on the same device. Do not promise <8.33 ms physical touch-to-photon merely because rendering fits one 120 Hz frame. + +### B5. “120 fps” needs an exact scene and actual presentation data + +There is no defensible universal animated-layer count. One thousand opaque translated rectangles, one thousand reshaped text runs, and one thousand large blur surfaces are radically different GPU and CPU workloads. Report surface area, overlap, clips, effects, text shaping, resolution, scale, and how much changes per frame. + +Robius's May 2024 benchmark provides source and xctrace scripts for a shadow-heavy iOS demo. On iPhone 12/13 running iOS 17.3, it reports Makepad at 60 fps versus Flutter/SwiftUI around 45 fps. These are 60 Hz devices, and the demo's bundled fonts were approximately 40 MB. It is useful evidence about an effects workload, not proof of 120 Hz capacity or minimal app size. [Robius benchmark](https://robius.rs/blog/performance-benchmarking-ios/) + +The article titled “SwiftUI Scroll Performance: The 120FPS Challenge” actually performs its main testing at 60 Hz in Low Power Mode on iPhone 15 Pro. Its observations are useful, but the title alone is not a 120 Hz measurement. [Article and methodology](https://blog.jacobstechtavern.com/p/swiftui-scroll-performance-the-120fps) + +At 120 Hz, the nominal interval is 8.333 ms. Frame work must leave room for the compositor and OS. Measure the observed presentation schedule and requested display rate, since ProMotion can vary refresh rate. CPU callback cadence alone cannot tell whether the screen displayed repeated frames. + +### B6. One million rows is feasible only with explicit virtualization + +LazyLayoutKit reports a one-million-item masonry workload on iPhone 14 Pro/A16/iOS 26.5.2 Release: 54 materialized items, 120 fps, p99 frame interval 8.34 ms, and approximately 2 μs query time during a 20-second recorded run. It also reports zero frames over 16.7 ms. The latter threshold alone would miss many 120 Hz deadline failures; use the p99 and raw presentation evidence rather than treating >16.7 ms as the 120 Hz criterion. [LazyLayoutKit](https://github.com/Dave861/LazyLayoutKit) + +The same library reports a dense timeline at p99 33–38 ms with 17–31% of frames over 16.7 ms, and approximately 3.115 seconds for a 100k-text-item first measurement pass on A16. This is useful honesty: known-size arithmetic and first-pass arbitrary text measurement are different problems. + +The 2026 Rust ecosystem study's 100k-row grids filter in roughly 1.5–6.1 ms across implementations, but one implementation materializes only 20 Slint rows. Neither row count nor filter time proves one-million-row 120 Hz scrolling. [Data-grid results](https://github.com/GoldStrikeArch/rust-gui-desktop-ecosystem-state/blob/main/report/16-data-grid-results.md) + +Rune should benchmark fixed-height arithmetic indexing, variable heights with cached measurements, and previously unseen wrapped text separately. Require bounded realized nodes, stable focus/selection by item key, correct scroll anchoring when estimates change, and bounded work on jump-to-end. Test insertion and removal above the viewport, not just steady scrolling through immutable rows. + +### B7. Large-file handling is mostly a data-model and scheduling problem + +Zed reports include 100–300 MB log files taking seconds to open and a 43 MB JSON file stalling for 30–40 seconds on Windows. These are workload-specific user observations, not a controlled framework comparison. [Large log discussion](https://github.com/zed-industries/zed/discussions/52549), [JSON stall report](https://github.com/zed-industries/zed/discussions/45861) + +A stronger primary source is Zed's August 2026 change to stream 1 MB blocks directly into its rope. For a 729 MB SQL file on Ryzen 5950X/Windows 11, the PR reports approximately 25% less peak memory and 28% less CPU. The release notes confirm the change shipped. [Zed PR #62748](https://github.com/zed-industries/zed/pull/62748), [Zed 1.17.2](https://zed.dev/releases/stable/1.17.2) + +A separate gpui-component report describes 500 MB text consuming 3.2–5 GB. That editor component's storage/tokenization behavior should not be attributed to GPUI's renderer or to Zed. [gpui-component issue #2566](https://github.com/longbridge/gpui-component/issues/2566) + +For Rune, the renderer contract is viewport-proportional work, incremental invalidation, cancellation, and bounded caches. A 100 MB editor demo also needs a streaming text store, deferred syntax work, and a long-line policy. Keep the demo's file-open budget separate from the renderer's frame budget. + +## C. Proposed targets and automated measurement + +### C1. Pin reference devices before calling a number a gate + +Proposed qualification classes are an M2 Pro Mac with 16 GiB and a verified 120 Hz display mode, and an iPhone 14 Pro/A16. These choices are reference classes, not a claim that those exact devices are available. Pin the actual device, OS, toolchain, renderer, power mode, thermal state, viewport, and scale in the benchmark manifest. If the test hardware differs, establish a new baseline rather than relabeling its results. + +Mac reference viewport: 1280×800 logical points at 2× for rendering workloads. iPhone: native full-screen viewport/scale, recorded explicitly. Use Release builds without inspector tree walks or video capture. Fonts and image assets remain fixed. The canonical offscreen lane runs on a pinned build worker; physical qualification runs on a dedicated device, never a developer's desk display. + +All values in the following tables are **proposed initial budgets**. They need a first implementation and baseline before becoming release promises. Cross-framework evidence supports their order of magnitude, not a guarantee that Rune will achieve them. + +### C2. Startup, footprint, and development budgets + +| Metric / exact workload | Proposed target | Automated measurement | +|---|---|---| +| Mac hello app, fresh process, caches warm | First presentation p50 ≤150 ms, p95 ≤200 ms; interactive p95 ≤250 ms | External launcher timestamps spawn; correlate first actual presentation and successful input acknowledgment; 30 launches | +| Mac first launch after reboot, already installed | First presentation ≤500 ms in each of 5 scheduled qualification runs | Dedicated reboot sequence; retain every sample. Treat installer/quarantine first-run separately; 5 samples do not establish p95 | +| iPhone hello app, terminated app launch | OS-reported launch p95 ≤800 ms; app-entry-to-first-present p95 ≤250 ms | XCTest/Instruments plus app signposts, 30 launches; report both boundaries | +| Mac hello app idle | Process-tree RSS ≤50 MiB after 10 s settled; GPU allocations reported separately | Sample RSS over 30 s, include helpers; also retain physical footprint where available | +| iPhone hello app idle | Physical footprint ≤40 MiB after settling | Device memory metrics; keep GPU/resource accounting explicit; do not label footprint as RSS | +| Mac hello executable | Stripped arm64 ≤5 MiB; installed app/resources ≤10 MiB | Record executable bytes, bundle bytes, assets, debug symbols separately; system library dependencies listed | +| iPhone hello app size | Thinned installed app ≤10 MiB excluding optional content packs | Archive/export size report on release worker; separate download size | +| Settled UI without periodic app work | Zero framework animation ticks and GPU submissions during a 10 s sample | Internal counters after startup/cursor/animations disabled; report process CPU as a secondary noisy metric | +| Style/layout/assets/tuning reload, Mac and USB-connected iPhone | File-save-to-present p95 ≤300 ms; state preserved | At least 30 meaningful edits; timestamp save, patch, device receipt, apply, present; assert state/focus/scroll continuity | +| Ordinary Rust body edit in a small sample app | Warm incremental compile/link/restart p95 ≤2 s | Edit a consumed function body, not just `touch`; retain compiler/cache/linker versions; explicitly outside the <300 ms patch promise | +| Clean sample-app build, dependencies cached | ≤60 s on nominated build worker | Fixed job concurrency and cache state; this is a developer-cost budget, not a runtime benchmark | + +The 5 MiB executable and 200 ms first-present goals are close to the published GPUI small-app range. The idle-memory budgets are deliberate goals in an evidence gap. The mobile launch and footprint budgets are provisional until measured on the reference iPhone. A framework may trade size against shaders, fonts, accessibility, or platform support; optional content packs must not hide dependencies required by the hello workload. + +### C3. Frame, list, text, and latency budgets + +For each 120 Hz scene below, run at least 60 seconds after a declared warmup and repeat five times. Target CPU UI work p95 ≤4 ms and GPU work p95 ≤4 ms, while separately requiring missed presentation opportunities <0.1% and no app-caused stall >25 ms. CPU and GPU times may overlap; neither their sum nor their individual percentiles establishes the presentation result. Report the full interval histogram and worst frame. + +| Workload | Defined contents | Proposed additional target | +|---|---|---| +| Cheap animation | 1,000 24×24 pt rounded quads, independent spring-driven translation/opacity, no blur/shadow/text reshaping; fixed overlap seed | Meet the 120 Hz budget on both reference devices; report retarget cost separately | +| Effects animation | 12 overlapping 160×100 pt cards, 16 pt blur radius, gradient edge masks and shadows, fixed 3-layer maximum overlap | Meet the same budget; publish exact effects implementation and resolution. Do not extrapolate to 1,000 blur layers | +| Text/controls scene | 100 visible text rows with pinned font and mixed Unicode, selection/caret, fixed toolbar; scroll without reshaping unchanged runs | Meet the frame budget after glyph warmup; publish separate cold-glyph/upload measurements | +| One-million fixed-height rows | Generated data, 32 pt row height, stable keys, bounded overscan; fling, reverse, jump-to-end, mutate above viewport | Realized nodes O(viewport + overscan), ≤200 rows in reference viewport; list CPU p95 ≤1 ms; usable first viewport ≤100 ms after data source attach | +| One-million variable-height rows | Cached heights plus estimated unseen wrapped-text rows; fixed text corpus | List CPU p95 ≤2 ms in steady state; no eager million-row shaping; bounded scroll-anchor correction; report cold-measurement costs separately | +| 100 MB plain-text editor demo, Mac | Local UTF-8 file, normal lines, syntax/search deferred | First usable viewport p95 ≤250 ms with warm filesystem cache; complete indexing ≤2 s; incremental peak memory ≤2.5× file bytes plus measured empty-editor baseline | +| Pathological text | 100 MB single line; malformed input; very long grapheme sequence | Remain responsive and cancelable; report explicit truncation/chunking policy; never claim normal-line timings apply | +| Software input-to-presentation | OS event arrival to presentation of an identified changed pixel region | At 120 Hz, p95 ≤16.7 ms; dispatch-to-submit p95 ≤4 ms; phase-randomized input, at least 1,000 samples | +| Physical keyboard-to-photon, Mac | Dedicated HID trigger and photodiode, equivalent minimal text control | Provisional p95 ≤35 ms; compare native AppKit on same fixture; retain both distributions | +| Physical touch-to-photon, iPhone | Instrumented touch actuator/force trigger and photodiode; pointer-down visual response | Provisional p95 ≤80 ms and no more than one 120 Hz interval above equivalent native pointer-down control; do not mix touch-up action timings | + +The physical budgets are intentionally looser than a frame interval because they include hardware and OS delivery. They are ambitious qualification targets, not derived claims about all iPhones. Measure drag tracking, touch-down feedback, and button activation separately. A button that activates on release can appear “slower” simply because the test includes finger dwell time. + +For missed-frame accounting, infer expected opportunities from the display's actual rate and platform presentation feedback, with a documented timestamp tolerance. Do not call every interval above exactly 8.333000 ms a miss: clock quantization and refresh variation matter. Conversely, a >16.7 ms threshold misses single-slot failures at 120 Hz. Record rate changes and distinguish a system-downshifted display from an app that failed to deliver a requested frame. + +### C4. Use a layered CI schedule + +| When | Gate | Artifacts | +|---|---|---| +| Every relevant change | Deterministic scene replay, semantic/layout assertions, selected pixel goldens, spring continuity/lifecycle checks | Scene manifest, hashes, input log, tree diff, motion trace, image diff | +| Every renderer/state/scheduler change on reserved hardware | Defined animation/list scenes; startup warm-process samples; software latency; low-overhead trace | Raw samples, distributions, presentation timeline, CPU/GPU counters, machine manifest | +| Nightly or scheduled qualification | Mobile launch, cache-cold/reboot startup, physical input latency, long-run memory/cache growth | Fixture calibration, raw sensor data, all launch samples, memory timeline | +| Release | Binary/bundle size, cross-platform rendering checks, accessibility and IME/device integration | Size breakdown, platform baseline metadata, device reports | + +Use both absolute budgets and paired baseline regressions. Initial regression policy: flag >10% deterioration when it also exceeds a metric-specific noise floor, such as 0.5 ms for frame work, 10 ms for startup, or 2 MiB for memory. These thresholds are policy proposals and must be calibrated from repeated baseline runs. Compare the same worker/device and interleave baseline/candidate runs where practical. Avoid universal percentage gates on tiny values. + +No noisy retry-until-green policy: preserve the first failure, inspect thermal/background conditions, and rerun only with a stated reason. Store sample count, p50/p95/p99, worst value, and confidence/variability rather than one averaged score. Separate instrumentation-on versus instrumentation-off calibration; report dropped events. A proposed low-overhead trace budget is <0.2 ms/frame p95 observer cost, measured with paired runs. Full-tree captures have no such performance promise. + +Physical latency requires hardware. Ordinary CI can automatically check event-to-presentation, but it cannot honestly claim input-to-photon without a sensor fixture. A high-speed camera can provide occasional external checks with stated frame quantization; a calibrated photodiode/HID or touch rig is better for automated repeated samples. + +## Steal + +- Flutter's source-linked layout inspection and separate logical/render concepts. +- Dart VM service's versioned RPC and subscriptions, CDP's explicit input/time controls, and React DevTools' compact updates with lazy property reads. +- Playwright's role-based selection and readable semantic snapshots, paired with pixels rather than substituted for them. +- Skia Gold's environment-keyed accepted images and explicit baseline review. +- Scrawl's named side-effect-free scene labs and one scaled animation clock. +- The motion inspector's presentation properties, property ownership, source/tunable links, and deferred serialization. +- The motion linter's format/rules, the layout linter's scope-aware invariants, and knobs' duration/bounce tuning descriptors. +- LazyLayoutKit's bounded materialization and its publication of workloads where performance degrades. +- Zed's streaming large-file approach and clear separation between loading, storage, and rendering work. + +## Avoid + +- Pixel tests that depend on arbitrary sleeps, system font fallback, network timing, or unspecified GPU/OS configurations. +- A screenshot-only “agent API,” pointer coordinates as the only selector, or a giant full-tree dump every frame. +- Animation tests that read target/model values while the visible presentation is elsewhere. +- Treating slowed/virtual motion as a hitch benchmark, or counting display callbacks as displayed frames. +- Unqualified “120 fps,” “cold start,” “idle memory,” or “binary size” claims. +- Treating a process exit, compilation success, or a zero-finding motion trace as proof that a visible surface exists. +- APIs that require remembering to notify after every mutation, hold runtime borrows across async work, or silently discard tasks. +- Promising arbitrary Rust hot reload in <300 ms without a proven compiler/runtime strategy. + +## Recommendation for Rune + +Build a small end-to-end vertical slice before expanding the widget catalog: a text field and send/cancel morph, a virtualized list, and the two animation workloads above. Give the slice stable identity, an injected clock, fixture services, semantic/layout/presentation snapshots, source-linked queries, and a motion-trace adapter. Use the same registered scenes in offscreen tests and the real Mac/iPhone app. + +Keep scene state, interaction dispatch, layout, presentation, and backend submission observable at explicit boundaries. This supports agents and also exposes where runtime cost occurs. Add full Perfetto/performance instrumentation after frame IDs and clocks are coherent; otherwise traces will imply precision they do not possess. + +Prioritize the <300 ms state-preserving UI patch path over general Rust hotpatching. Validate actual edit-to-present on a connected iPhone early, because serialization, transport, shader/asset upload, and preserved state are part of that budget. Retain a clear rebuild path for unsupported edits. + +Rejected alternatives: + +| Alternative | Reason to reject initially | +|---|---| +| Screenshot automation around a normal app as the only test interface | Cannot reliably control time, seed state, explain failures, or inspect invisible/retiring surfaces | +| Implement all of CDP | Large irrelevant web compatibility surface; a small generated protocol can expose Rune's actual model | +| Only a human visual inspector | Agents need queryable, bounded, structured operations; the GUI can be a client of the same protocol | +| Full layer tracing always enabled | Observer cost can consume a substantial fraction of the 8.333 ms frame budget | +| One “framework score” combining startup, memory, and fps | Hides workload boundaries and makes regressions difficult to diagnose | +| Mandatory new framework builds for this report | Published raw size data already answers the rough scale; new builds without a matched benchmark design would add cost without comparable evidence | +| One cross-platform pixel hash | Platform text and GPU differences make it brittle or force tolerances broad enough to miss defects | + +## Open questions + +1. Which exact Mac and iPhone can remain dedicated to performance qualification, and what display/power/thermal controls can the lab enforce? +2. Can the first renderer produce repeatable offscreen GPU pixels on a pinned worker, or does it need a small reference raster path for a subset of primitives? +3. What is the UI patch boundary: a compiled scene description, a data-driven view layer, dynamic code, or another representation? This determines what the <300 ms promise includes. +4. Which platforms expose reliable presentation feedback, and what proxy plus uncertainty must be reported elsewhere? +5. How much source/dependency provenance can remain available in development without adding per-frame allocation or invalidation cost? +6. Should the one-million-row and 100 MB editor workloads ship as framework examples or a separate benchmark application? The renderer should not inherit every editor data-model responsibility. +7. What exact effects scene best represents Scrawl's and the launcher's glass morph, including blur sampling and soft masks? The provisional 12-card benchmark must be replaced or supplemented by that real workload. +8. Does the internal motion linter's consumer need any schema extension for Rune's transform/mask/velocity data, or can its current scalar channels carry the first adapter without changes? + +## Research scope and reproducibility notes + +This report inspected local source/docs for internal motion and layout linters, Scrawl, knobs, and a private iOS client's historical motion tooling; read primary protocol/tooling documentation; examined published benchmark results and measurement code; and recomputed the cited Typometer CSV statistics. It did not independently reproduce the external performance measurements, run release-size builds, open GUI windows, or benchmark a desk display. No optional build time was consumed. + +Repository links to `main` are mutable. Before using an external number as a release gate, pin its source revision and retain the harness, assets, raw data, and machine manifest in the benchmark artifact. Local relative links in this report point to sibling checkouts; the historical iOS document requires the Git revision given above. diff --git a/app/vendor/rune/research/11-platform-shells.md b/app/vendor/rune/research/11-platform-shells.md new file mode 100644 index 0000000..e637d83 --- /dev/null +++ b/app/vendor/rune/research/11-platform-shells.md @@ -0,0 +1,388 @@ +# 11 — Platform Shells & Platform Order + +Research for **Rune** (working title), an experimental Rust UI & animation framework for macOS, iOS, web, Windows, Linux, and Android. +Checked October 2026 against local checkouts of `winit` (`0.31.0-beta.3`), Zed's `gpui` (`gpui_macos`, `gpui_ios`, `gpui_web`, `gpui_windows`, `gpui_linux`), `makepad`, `flutter/engine`, and Kit's production apps (`scrawl`, `hex`, a private Mac launcher and a private iOS client). + +--- + +## Summary + +- **Write thin per-platform shells (`rune-macos`, `rune-ios`, `rune-web`, etc.) behind a narrow `Platform` / `PlatformWindow` trait; do not build on `winit`.** In `winit` `0.31.0-beta.3`, macOS live resize does not synchronize `CAMetalLayer` presentation with AppKit's `CATransaction`, macOS `NSTextInputClient` cannot read document context (`selectedRange` returns `NSNotFound` and `attributedSubstringForProposedRange` returns `None`), and iOS (`winit-uikit`) only implements `UIKeyInput` instead of `UITextInput`—breaking autocorrect, Japanese/Chinese IME, Dictation, Scribble, and selection handles. +- **Per-platform shells are smaller than `winit` while doing far more.** Zed's `gpui_macos` (9,711 LOC), `gpui_ios` (3,561 LOC), and `gpui_web` (6,994 LOC) are comparable in size to `winit-appkit` (8,667 LOC), `winit-uikit` (3,471 LOC), and `winit-web` (7,794 LOC), yet include full `NSTextInputClient` / `UITextInput` / hidden-`<textarea>` IME bridges, native menus, pasteboard, drag-and-drop, and `presentsWithTransaction` resize synchronization. +- **macOS 26 / iOS 26 Liquid Glass requires native backdrop views (`NSGlassEffectView` / `UIVisualEffectView` / `GlassEffectContainer`) behind or around a transparent `CAMetalLayer`.** Apple's private `CASDFElementLayer` + `CABackdropLayer` pipeline samples live desktop/wallpaper buffers behind the window that a client Metal shader cannot read. Scrawl's pill (`scrawl/src/native/pill/mod.rs:447-453, 1111-1147`) proves the exact pattern: an `NSGlassEffectView` under a transparent `CAMetalLayer` (`presentsWithTransaction = true`), updated together inside `CATransaction::begin() ... commit()`. +- **120 Hz ProMotion requires explicit frame-rate pinning on both macOS and iOS.** On macOS 14+, `NSView.displayLinkWithTarget:selector:` returns a `CADisplayLink` that adaptively throttles to 30 Hz (33.9 ms) unless `setPreferredFrameRateRange:` is pinned to `CAFrameRateRange { minimum: 120.0, maximum: 120.0, preferred: 120.0 }` (`makepad/.../macos_app.rs:1458-1482`). If using `CVDisplayLink`, keep instances immortal per `CGDirectDisplayID` (`gpui_macos/src/display_link.rs:1-86`) to avoid CoreVideo teardown segfaults. On iOS, pair `CADisplayLink.preferredFrameRateRange = CAFrameRateRangeMake(80, 120, 120)` with `CADisableMinimumFrameDurationOnPhone = YES` in `Info.plist`. +- **Incremental adoption in existing SwiftUI/UIKit apps (the iOS client, `hex`) is a first-class requirement.** Rune must work in two modes on Apple platforms: **Full-Window Shell** (Rune owns `NSApplication`/`UIApplication`) and **Embedded View** (`RuneMetalView: UIView` / `NSView` wrapped in `UIViewRepresentable` / `NSViewRepresentable`, sharing a single process-wide `MTLDevice` and `MTLCommandQueue`). +- **Native view embedding inside a Rune window should use Z-ordered underlay/overlay slots (`NSGlassEffectView` / `WKWebView` / `AVPlayerLayer` / `MKMapView`), not general-purpose interleaved slicing.** Flutter's `FlutterPlatformViewsController.mm` requires `EmbedderViewSlice` picture-recording, `OverlayLayerPool` allocations, and `FlutterTouchInterceptingView` gesture delay buffers for every interleaved platform view. Restricting embedded native views to background underlays (glass materials, video, maps) or top overlays (sheets, popovers, inspectors) eliminates intermediate GPU render targets. +- **Web in 2026 has universal WebGPU (including Safari 26 on macOS/iOS), but `EditContext` is still Chromium-only.** For web text input, steal `gpui_web`'s sliding-window hidden `<textarea>` (`gpui_web/src/ime_mirror.rs:1-198`, 512 UTF-16 code units each side of the selection, coalesced once per frame) plus an offscreen DOM accessibility mirror (`accesskit_web` pattern). +- **Ship in strict platform order: (1) macOS → (2) iOS + SwiftUI/UIKit host view → (3) Web (WASM + WebGPU) → (4) Windows → (5) Linux (Wayland-first) → (6) Android.** macOS and iOS share ~40% of their platform code (`gpui_apple`: Metal, CoreText, CoreAnimation, `dispatch2`, `objc2`) and serve all of Kit's immediate apps (`scrawl`, `hex`, the launcher and the iOS client), while Web is mandatory for interactive docs, playgrounds, and shareable demos. + +--- + +## 1. `winit` vs Own Per-Platform Shells vs SDL3 + +### Codebase Size Reality Check (Measured October 2026) + +| Codebase | macOS | iOS | Shared Apple | Web | Windows | Linux | Android | Total | +|---|---:|---:|---:|---:|---:|---:|---:|---:| +| **`winit` `0.31.0-beta.3`** (`winit-core`: 7,799) | 8,667 | 3,471 | — | 7,794 | 12,864 | 21,669 (WL 9,897 + X11 11,772) | 1,885 | **64,149 LOC** | +| **Zed `gpui`** (`platform.rs`: 1,731) | 9,711 | 3,561 | 3,865 | 6,994 | 13,187 | 16,422 (WL + X11 + Portals) | — | **55,471 LOC** | + +`winit` is not smaller than a purpose-built GUI shell—it is larger, because it carries generality for game engines, legacy OS versions, and raw window handle permutations while omitting the exact primitives a UI toolkit needs (menus, clipboard, drag-and-drop, system dialogs, native backdrop views, and document-aware IME). + +### Where `winit` (`0.31.0-beta.3`) Fails a High-Craft UI Framework + +1. **macOS IME (`NSTextInputClient`) is stateless and broken for context-aware input:** + In `winit/winit-appkit/src/view.rs:344-414`: + - `selectedRange` (`lines 384-387`) unconditionally returns `NSRange { location: NSNotFound, length: 0 }` with a `// TODO` comment. + - `attributedSubstringForProposedRange` (`lines 344-351`) unconditionally returns `None` (`// TODO`). + - `insertText:replacementRange:` (`lines 285-310`) ignores `_replacement_range` (`// TODO: Implement replacement_range`). + - Without `selectedRange` and `attributedSubstringForProposedRange`, macOS inline predictive text, press-and-hold accents, Japanese/Chinese reconversion, and Emoji replacement (`Ctrl+Cmd+Space` replacing a word) fail or insert at the wrong offset. + - Compare `gpui_macos/src/window.rs:2125-2258`, which routes `selectedRange`, `markedRange`, `attributedSubstringForProposedRange`, `insertText:replacementRange:`, `setMarkedText:selectedRange:replacementRange:`, and `firstRectForCharacterRange:` directly to the focused widget's `PlatformInputHandler`. + +2. **iOS (`winit-uikit`) has no `UITextInput` implementation at all:** + In `winit/winit-uikit/src/view.rs:94-156`, `WinitView` only implements the minimal `UIKeyInput` protocol (`hasText`, `insertText:`, `deleteBackward`), and `insertText:` (`lines 102-135`) loops `.chars()` to synthesize fake `WindowEvent::KeyboardInput` key-down/key-up events. + - Because it does not implement `UITextInput` (`textInRange:`, `replaceRange:withText:`, `selectedTextRange`, `markedTextRange`, `setMarkedText:selectedRange:`, `tokenizer`), iOS disables multistage CJK IME composition, autocorrect replacement spans, inline predictive text, Dictation, Scribble (Apple Pencil), and native Loupe/selection drag handles. + - Compare `gpui_ios/src/ios/text_input.rs:1-1180`, which implements all 30+ `UITextInput` selectors in Rust on `GPUITextInputView` with generation-stamped `GPUITextPosition` / `GPUITextRange` objects so UIKit's async text-system queries never apply stale ranges after app state changes. + +3. **macOS Live Resize Jank and `RunLoop` Re-entrancy:** + During interactive window edge dragging on macOS, AppKit spins a modal nested run loop inside `-[NSWindow _resizeWithEvent:]` in `NSEventTrackingRunLoopMode`. + - `winit-appkit` (`observer.rs`) uses `CFRunLoop` before-waiting/after-waiting observers to synthesize `RedrawRequested`, which fights AppKit's synchronized `CATransaction` resize pass unless the view implements `displayLayer:` with `CAMetalLayer.presentsWithTransaction = true`. + - In `gpui_macos/src/window.rs:2260-2285`, the content view implements `wantsUpdateLayer -> YES` and `displayLayer:`. During `displayLayer:`, GPUI stops its display link, flips `metal_layer.set_presents_with_transaction(true)` (`gpui_macos/src/metal_renderer.rs:297-300`), renders synchronously at the new `bounds` and `backingScaleFactor`, calls `command_buffer.waitUntilScheduled()`, calls `drawable.present()`, and restores `presentsWithTransaction = false` when the display link resumes (`window.rs:2058-2075`). The window frame and Metal content resize in the exact same WindowServer commit with zero rubber-banding or black gutter. + +4. **Embedded View Mode (`UIViewRepresentable` / `NSViewRepresentable`):** + `winit` assumes ownership of `UIApplicationMain` (`winit-uikit/src/event_loop.rs`) or `NSApplication` activation policy and delegate (`winit-appkit`). Embedding a single Rune canvas inside an existing SwiftUI screen in the iOS client or `hex` is awkward and unsupported in `winit`, whereas a thin `RuneHostView` (`UIView` / `NSView`) shares 90% of `rune-ios` / `rune-macos`'s windowing/input/rendering code without owning `UIApplication`. + +5. **SDL3 (`sdl3-sys`):** + SDL3 improved GPU and high-DPI APIs over SDL2 and added `SDL_AddEventWatch` for live resize callbacks, but it remains a C game runtime: it lacks native macOS `NSGlassEffectView` / `NSPanel` vibrancy integration, full document-context `UITextInput` on iOS, native macOS `NSMenu` responder-chain validation, and web accessibility trees, while adding a C build dependency across every target. + +--- + +## 2. macOS Deep Dive (`rune-macos`) + +### Windowing (`NSWindow`, `NSPanel`, Traffic Lights, Fullscreen, Key Status) +- **Standard vs Floating Utility Windows:** + Support two window classes in `rune-macos` (`gpui_macos/src/window.rs:197-205`): + - `GPUIWindow: NSWindow` for standard document/app windows. + - `GPUIPanel: NSPanel` for floating overlays, HUDs, pills, and launchers (`NSWindowStyleMaskNonactivatingPanel`, `collectionBehavior = CanJoinAllSpaces | FullScreenAuxiliary`, `level = NSFloatingWindowLevel` or `NSPopUpMenuWindowLevel` (`101`)). +- **Non-Activating Key Input & Cold-Start Warm-Up:** + - In both Scrawl (`scrawl/src/native/pill/mod.rs:342-358`) and the launcher (`launcher/native/Launcher.swift:26-44`), subclass `NSPanel` to override `canBecomeKeyWindow -> YES` and `canBecomeMainWindow -> NO`. This allows typing and Escape/shortcut handling in a floating launcher or recording pill without stealing active-app status from the user's frontmost app. + - **Cold-start warm-up:** On first launch, `NSPanel` + Metal/SwiftUI shader compilation can cause a 1-frame flash. The launcher (`launcher/native/Launcher.swift:566-578`) solves this by setting `panel.alphaValue = 0`, calling `orderFrontRegardless()` + `layoutIfNeeded()`, then `orderOut(nil)` and restoring `alphaValue = 1` at startup. +- **Traffic Lights & Titlebar Integration:** + - Use `NSWindowStyleMaskTitled | NSWindowStyleMaskFullSizeContentView` with `titlebarAppearsTransparent = YES` and `titleVisibility = NSWindowTitleHidden`. + - Override `layout` in the `NSWindow`/`NSPanel` subclass or inspect `standardWindowButton:` (`NSWindowCloseButton`, `NSWindowMiniaturizeButton`, `NSWindowZoomButton`) to position the traffic lights at a custom inset (`gpui_macos/src/window.rs:780-865`) and report `WindowControls` geometry to Rune's layout engine so app toolbars automatically pad around traffic lights (and shrink that padding to `0` when entering native fullscreen via `windowWillEnterFullScreen:` / `windowDidExitFullScreen:`). + - Support native double-click-on-titlebar (`AppleMiniaturizeOnDoubleClick` / `performMiniaturize:` / `zoom:`) and `window.performWindowDragWithEvent:` when dragging an empty toolbar region. + +### Liquid Glass (`NSGlassEffectView` on macOS 26) + `CAMetalLayer` Composition + Apple's macOS 26 (`Tahoe`) introduced `NSGlassEffectView` (and `NSGlassEffectContainerView` for metaball-style merging of adjacent glass elements). +- **Why a pure Metal shader cannot replicate native Liquid Glass:** + Inside WindowServer, `NSGlassEffectView` builds a layer tree containing `SDFLayer` + `CABackdropLayer` + `CASDFElementLayer`. WindowServer composites the live desktop wallpaper and windows *behind* your `NSWindow` into that `CABackdropLayer` with chromatic refraction and specular rim lighting before compositing your window's layers on top. A client process's `CAMetalLayer` has no read access to behind-window pixels without ScreenCaptureKit permissions and 1-frame latency. +- **How Scrawl composites `NSGlassEffectView` + `CAMetalLayer` in lockstep (`scrawl/src/native/pill/mod.rs`):** + 1. **View Hierarchy (`lines 422-455, 644-675`):** + `panel.contentView` (`FlippedRootView`, `wantsLayer = YES`) contains: + - **Underlay:** `NSGlassEffectView` (`setStyle: 0` for Regular or `1` for Clear, `setCornerRadius: h * 0.5`, `setTintColor: NSColor(srgb: 0.04, 0.04, 0.06, 0.25)`). + - **Overlay:** `PillInteractiveView` (`wantsLayer = YES`), hosting a `CAMetalLayer` (`opaque = NO`, `pixelFormat = MTLPixelFormatBGRA8Unorm`, `framebufferOnly = YES`, `presentsWithTransaction = YES`). + 2. **Critical AppKit Initialization Quirk (`lines 447-453`):** + `window.displayIfNeeded()` **must** be called once on the main thread while `glass_view` is non-hidden (`alphaValue = 0.0`) so AppKit executes its first `updateLayer` pass and constructs the internal `SDFLayer` + `CABackdropLayer` + `CASDFElementLayer` tree. If `glass_view` starts with `isHidden = YES`, AppKit skips building the backdrop layers until the first visible frame, causing a un-refracted pop. + 3. **Zero-Lag Synchronized Morphing (`lines 1111-1147`):** + When the pill morphs size, position, or corner radius at 120 Hz, updating `NSGlassEffectView` outside the Metal frame causes a 1-frame tear between the glass capsule and the GPU-rendered waveform/controls inside it. Scrawl eliminates this by wrapping both in a single explicit `CATransaction`: + ```rust + CATransaction::begin(); + CATransaction::setDisableActions(true); + // 1. Update NSGlassEffectView frame, cornerRadius, alphaValue + layoutSubtreeIfNeeded() + self.sync_glass_view(glass_rect, corner_radius, glass_alpha, ...); + // 2. Encode Metal render pass into CAMetalDrawable (with clearColor = 0,0,0,0) + // ... + cmd.commit(); + cmd.wait_until_scheduled(); + drawable.present(); // Because presentsWithTransaction = true, waits for CATransaction::commit() + CATransaction::commit(); + ``` + 4. **Fallback on macOS 14–15:** Fall back cleanly to `NSVisualEffectView` (`material = HUDWindow` or `UnderWindowBackground`, `blendingMode = BehindWindow`, `state = Active`) with a `CAShapeLayer` mask. + +### Frame Pacing & ProMotion (120 Hz) on macOS +There are two display-link APIs on macOS, each with a sharp edge discovered in our reference codebases: +1. **`NSView.displayLinkWithTarget:selector:` (`CADisplayLink`, macOS 14+):** + Used by Makepad (`makepad/platform/src/os/apple/macos/macos_app.rs:1458-1482`). + - **Gotcha:** By default on ProMotion MacBook Pros, macOS's `CADisplayLink` uses adaptive frame pacing and drops to **30 Hz (33.9 ms)** when it does not detect native CoreAnimation layer animations! + - **Fix (`macos_app.rs:1464-1474`):** Query `window.screen.maximumFramesPerSecond` (120 on ProMotion) and immediately call: + ```rust + let rate = max_fps as f32; + let range = CAFrameRateRange { minimum: rate, maximum: rate, preferred: rate }; + let _: () = msg_send![display_link, setPreferredFrameRateRange: range]; + ``` +2. **`CVDisplayLink` (CoreVideo):** + Used by GPUI (`gpui_macos/src/display_link.rs:1-86`). + - **Gotcha:** Stopping and deallocating a `CVDisplayLink` when a window closes or switches monitors races with CoreVideo's high-priority background thread and causes intermittent segfaults inside `CVDisplayLink::runIOThread` (`ZED-7XR`, Zed PR `#32116`). + - **Fix (`display_link.rs:16-75`):** Maintain a process-global `Mutex<BTreeMap<CGDirectDisplayID, ImmortalDisplayLink>>` that creates at most one `CVDisplayLink` per display ID, never drops it, and uses `CVDisplayLinkStart` / `CVDisplayLinkStop` with reference counting across active windows on that display. +- **Recommendation for Rune:** Require macOS 14+ and use `NSWindow`/`NSView.displayLinkWithTarget:selector:` (`CADisplayLink`), which runs directly on the main run loop without cross-thread dispatch latency, and pin `preferredFrameRateRange` to `(80.0, max_fps, max_fps)` while animations or gestures are active. + +### Pointer, Trackpad Momentum, Gesture Phases & Force Touch +- **`NSTrackingArea`:** Install an `NSTrackingArea` with `NSTrackingMouseMoved | NSTrackingActiveAlways | NSTrackingInVisibleRect | NSTrackingMouseEnteredAndExited` (`gpui_macos/src/window.rs:640-655`) so cursor changes and hover states work even when a floating panel or unfocused window is hovered. +- **Scroll Phases (`phase` vs `momentumPhase`):** + macOS `NSEventTypeScrollWheel` carries two distinct `NSEventPhase` bitmasks: + - `event.phase`: physical finger contact on the trackpad (`Began`, `Changed`, `Stationary`, `Ended`, `Cancelled`, or `MayBegin` when two fingers rest on the trackpad before moving). + - `event.momentumPhase`: synthetic inertial scroll events generated by macOS after fingers lift (`Began`, `Changed`, `Ended`). + - **Crucial detail:** When a user flicks a scroll view on a Mac trackpad and then puts two fingers back down on the trackpad, AppKit sends `event.phase == NSEventPhaseMayBegin` (and an `Ended` on the previous `momentumPhase`). Rune must expose both `phase` and `momentum_phase` plus `hasPreciseScrollingDeltas` (`scrollingDeltaX`/`Y` in points vs line ticks for notched mouse wheels) so custom spring/scroll physics can immediately interrupt momentum on finger touch-down. +- **Magnify, Rotate, SmartMagnify & Force Touch:** + - Forward `magnifyWithEvent:` (`event.magnification`, `event.phase`), `rotateWithEvent:` (`event.rotation`), `smartMagnifyWithEvent:` (two-finger double-tap to zoom), and `pressureChangeWithEvent:` (`event.pressure` in `0.0..=1.0`, `event.stage` `1` = click, `2` = deep press / Force Touch) plus `NSHapticFeedbackManager::defaultPerformer().performFeedbackPattern:performanceTime:` for tactile detents when scrubbing sliders or snapping alignment guides. + +### Menus, Menu-Bar Extras, Clipboard, Drag-and-Drop & Services +- **Menus & Responder Chain:** Build real `NSMenu` / `NSMenuItem` trees (`gpui_macos/src/menu.rs`) wired to an action selector that queries `validateMenuItem:` against Rune's focused responder chain. This gives macOS native Help-menu search, native keyboard shortcut learning, and native context menus (`NSMenu::popUpContextMenu:withEvent:forView:`) for free. +- **Menu-Bar Extras (`NSStatusItem`):** Provide a first-class `StatusItem` API on `rune-macos` (`NSStatusBar::systemStatusBar().statusItemWithLength(NSVariableStatusItemLength)`) that can either show a native `NSMenu` or anchor a borderless `NSPanel` popover below the status bar button's `window.frame`. +- **Clipboard (`NSPasteboard`) & Drag-and-Drop (`NSDraggingDestination` / `NSDraggingSource`):** + Register `NSPasteboardTypeString`, `NSPasteboardTypeFileURL`, `NSPasteboardTypePNG`, `NSPasteboardTypeTIFF`, and custom UTI types (`window.registerForDraggedTypes:`). Implement `draggingEntered:`, `draggingUpdated:`, `draggingExited:`, and `performDragOperation:` (`gpui_macos/src/window.rs:2338-2435`) to convert external file/image/text drops into `PlatformInput::FileDrop` events with cursor coordinates. +- **Services & Quick Look:** Forward `validRequestorForSendType:returnType:` for macOS Services and `acceptsPreviewPanelControl:` / `beginPreviewPanelControl:` (`QLPreviewPanel`, as in `launcher/native/Launcher.swift:46-75`) so pressing Space on a file item opens native Quick Look. + +--- + +## 3. iOS Deep Dive (`rune-ios`) + +### Lifecycle (`UIApplication`, `UIScene`), `CAMetalLayer` & 120 Hz ProMotion +- **`UIScene` Lifecycle:** Modern iOS (and iOS 26+) requires scene-based lifecycle (`UIWindowSceneDelegate`) rather than legacy `UIApplicationDelegate.window` (`gpui_ios/src/ios/application.rs:145-315`). +- **`CAMetalLayer` Backing:** Subclass `UIView` (`RuneMetalView`) and override `+ (Class)layerClass` to return `[CAMetalLayer class]` (`gpui_ios/src/ios/window.rs:84-98`). Set `view.contentScaleFactor = UIScreen.mainScreen.nativeScale` (or `windowScene.screen.nativeScale`) and update `metalLayer.drawableSize` inside `layoutSubviews` so rotation and iPad Stage Manager / Split View resizes are synchronous. +- **120 Hz ProMotion on iPhone & iPad:** + Two pieces are required—missing either locks the app to 60 Hz: + 1. `Info.plist` **must** include `<key>CADisableMinimumFrameDurationOnPhone</key><true/>`. Without this key, iPhone Pro displays ignore `CADisplayLink` requests above 60 Hz for third-party Metal views. + 2. On the `CADisplayLink` instance, call `setPreferredFrameRateRange:` with `CAFrameRateRangeMake(80.0, 120.0, 120.0)` during active animations/scrolls, and pause (`setPaused:YES`) when the scene is idle (`gpui_ios/src/ios/application.rs:331-340` currently omits `setPreferredFrameRateRange:`, leaving a ProMotion gap we should fix in Rune). +- **Concentric Corner Radius (iOS 26):** Use `UICornerConfiguration::containerConcentricRadius()` (`gpui_ios/src/ios/window.rs:391-425`) to read the hardware screen bezel corner radius so edge-aligned sheets and cards match the physical display curvature. + +### Safe Areas, Keyboard Avoidance & Interactive Keyboard Dismissal +- **Safe Areas:** Observe `safeAreaInsetsDidChange` on the root `UIView` and feed `WindowInsets { top, left, bottom, right }` in logical points to Rune's layout root (`gpui_ios/src/ios/window.rs:342-389`). +- **Keyboard Avoidance & Interactive Frame Tracking:** + Subscribe to `UIKeyboardWillChangeFrameNotification` / `UIKeyboardDidChangeFrameNotification` (`gpui_ios/src/ios/window.rs:285-338`), converting `UIKeyboardFrameEndUserInfoKey` into the view's coordinate space (`convertRect:fromCoordinateSpace:`) and reading `UIKeyboardAnimationDurationUserInfoKey` and `UIKeyboardAnimationCurveUserInfoKey` (curve `7` is Apple's private CASpringAnimation curve). + - **Better on iOS 16+ / iOS 26:** Attach a constraint or observation to `view.keyboardLayoutGuide.followsUndockedKeyboard = YES` (`UIKeyboardLayoutGuide` / `UITrackingLayoutGuide`), which tracks the keyboard frame *frame-by-frame* during interactive scroll-to-dismiss gestures (`UIScrollViewKeyboardDismissModeInteractive`). + +### Text Input (`UITextInput`), Selection Handles, Dictation & Scribble +- Do **not** use `UIKeyInput`. Use `gpui_ios/src/ios/text_input.rs` as the blueprint: + - Implement `UITextInput` + `UITextInputTraits` directly on the Metal host view (or a dedicated responder subview). + - Stamp custom `UITextPosition` and `UITextRange` Objective-C subclasses with a monotonically increasing `session_token: u64` (`text_input.rs:42-198`) that increments whenever the underlying Rust text buffer mutates outside UIKit's knowledge. Any stale range UIKit queries returns `nil` instead of panicking on out-of-bounds UTF-16/UTF-8 slicing. + - Before changing selection or text from Rust, bracket the mutation with `[inputDelegate selectionWillChange:self]` / `[inputDelegate selectionDidChange:self]` or `textWillChange:` / `textDidChange:`. + - Implement `firstRectForRange:` and `selectionRectsForRange:` returning `UITextSelectionRect` objects so iOS draws native floating autocorrect bubbles, the magnifying Loupe, Dictation glow, and Apple Pencil Scribble previews at the exact glyph bounds rendered by Rune's GPU text engine. + +### Scroll Physics & Gesture Recognizers: Native vs Custom +- **Scroll Physics (`UIScrollView` vs Custom):** + iOS users immediately notice non-native scroll deceleration or rubber-banding. Rather than embedding hidden `UIScrollView` instances for every scrollable list, replicate Apple's exact analytical scroll equations in Rust: + - **Deceleration:** Exponential decay with `UIScrollViewDecelerationRateNormal = 0.998` per millisecond (`v(t) = v_0 * 0.998^t`, stopping threshold `|v| < 0.05 pt/ms`). + - **Overscroll Rubber-Banding:** `offset = (1.0 - (1.0 / ((distance * 0.55 / dimension) + 1.0))) * dimension` (constant `c = 0.55`), transitioning into a critically damped spring (`ζ = 1.0`, response `~0.45s`) on release or boundary impact. +- **Gesture Disambiguation (`UIGestureRecognizer` Interop):** + - Install a `UIScreenEdgePanGestureRecognizer` (`edges = UIRectEdgeLeft`) on the root view (`gpui_ios/src/ios/window.rs:248-275`) so system/navigation back-swipe gestures work naturally. + - When Rune is hosted inside a UIKit/SwiftUI `NavigationStack` or `UIScrollView`, implement `UIGestureRecognizerDelegate` (`gestureRecognizerShouldBegin:` and `gestureRecognizer:shouldRecognizeSimultaneouslyWithGestureRecognizer:`) on a touch-forwarding recognizer on `RuneMetalView` so Rune can claim horizontal drags (e.g., scrubbing a timeline or carousel) while letting vertical drags or left-edge back-swipes pass through to the parent SwiftUI/UIKit container. + +### Haptics & Dynamic Type +- **Haptics:** Wrap `UIImpactFeedbackGenerator` (`Light`, `Medium`, `Heavy`, `Soft`, `Rigid`), `UISelectionFeedbackGenerator`, and `UINotificationFeedbackGenerator` behind a zero-allocation `PlatformWindow::trigger_haptic(HapticPattern)` method, plus `CHHapticEngine` (CoreHaptics) for continuous texture/transient curves synced to spring velocity. +- **Dynamic Type:** Read `UITraitCollection.currentTraitCollection.preferredContentSizeCategory` and observe `UIContentSizeCategoryDidChangeNotification` (`registerForTraitChanges:@[UITraitPreferredContentSizeCategory.self]`). Expose the user's Dynamic Type scale factor (`UIFontMetrics.defaultMetrics.scaledValueForValue:`) to Rune's style system. + +### Platform View Embedding & Bidirectional Hosting (Incremental Adoption in the iOS Client / Hex) + +#### How Existing Frameworks Embed Native Views (and the Cost) +- **Flutter (`FlutterPlatformViewsController.mm:46-210`, `FlutterPlatformViews_Internal.h:23-160`):** + Uses Hybrid Composition. When a Dart widget tree places a native `UIView` (`WKWebView`, `MKMapView`) between two Flutter widgets: + 1. The raster thread slices the display list around the platform view (`EmbedderViewSlice`), rendering background widgets to the base `CAMetalLayer` and foreground widgets into a pooled `FlutterOverlayView` (`OverlayLayerPool`) allocated as an extra full-size `CAMetalLayer` above the `UIView`. + 2. Every clip path on the platform view requires a `FlutterClippingMaskView` (`UIView.maskView`), which forces an offscreen CoreAnimation alpha mask pass. + 3. Every touch goes through `FlutterTouchInterceptingView`, which buffers `UITouch` sequences on the main thread until the Dart UI thread replies over an async hop whether its gesture arena won or lost. +- **Compose Multiplatform (`UIKitView` / `UIKitViewController`):** + Places native `UIView`s in an overlay/underlay `UIView` container synchronized in `layoutSubviews`, punching a transparent hole (`BlendMode.Clear`) into the Skia/Metal canvas when using an underlay. +- **React Native (Fabric):** + Every component *is* a `UIView`, so embedding is free, at the cost of no unified custom GPU canvas and main-thread `UIView` layout overhead. + +#### Rune's Bidirectional Strategy +1. **Hosting Rune inside SwiftUI / UIKit (`RuneHostView` — Priority #1 for the iOS client and `hex`):** + - Provide a C-ABI / Swift package wrapper (`RuneKit`) exposing `RuneUIView: UIView` and `RuneView: UIViewRepresentable` (and `RuneNSView` on macOS). + - **Shared GPU Context:** Multiple `RuneUIView` instances in an existing SwiftUI app (e.g., an animated voice orb in `hex`, a streaming code/diff canvas or canvas diagram in the iOS client) share a single singleton `WgpuContext` / `MTLDevice` / `MTLCommandQueue` and glyph atlas in Rust, while each `RuneUIView` owns a lightweight `CAMetalLayer` surface and participates in a single shared `CADisplayLink`. + - **Intrinsic Size & Transparent Background:** `RuneUIView` sets `isOpaque = NO`, `layer.opaque = NO`, and supports `sizeThatFits:` / `intrinsicContentSize` driven by Rune's layout pass so SwiftUI's `ScrollView` or `VStack` can size a Rune component naturally. +2. **Embedding Native Views inside Rune (Underlay / Overlay Slots):** + - Instead of Flutter's arbitrary N-layer `EmbedderViewSlice` interleaving, support two explicit native-view slots per Rune window: + - **Underlay slot** (behind the transparent `CAMetalLayer`, with Rune punching an alpha-0 cutout rect + corner radius in its Metal pass): used for `NSGlassEffectView` / `UIVisualEffectView` (Liquid Glass), `AVPlayerLayer` (zero-copy hardware video), and `MKMapView`. + - **Overlay slot** (child `UIView`/`NSView` positioned above the `CAMetalLayer` synced inside `CATransaction`): used for `WKWebView`, `PHPickerViewController`, `PKCanvasView`, or native sheets/popovers. + - Because Rust runs on the main UI thread (unlike Flutter's separate Dart UI / Raster threads), touch routing and `CATransaction` frame syncing happen **synchronously on the same thread** with zero `FlutterTouchInterceptingView` buffering latency. + +### Liquid Glass on iOS 26 +As documented in `ios-client/OpenCode/Glass.swift:1-59` and `ios-client/docs/native-ui-guidance.md:11-34`: +- iOS 26 introduces `GlassEffectContainer`, `.glassEffect(glass.interactive(), in: shape)` in SwiftUI, and `UIGlassEffect` / `UIGlassContainerEffect` in `UIVisualEffectView` for UIKit. +- When Rune runs in **Embedded View** mode inside the iOS client, SwiftUI toolbars and floating composer pills use native `OpenCodeGlassContainer` / `.openCodeGlass(in:)` while Rune renders content surfaces or interactive visualizations. +- When Rune owns the full window on iOS 26, `rune-ios` can instantiate `UIVisualEffectView(effect: UIGlassEffect.regular)` in the **Underlay slot** behind the transparent `CAMetalLayer` using the exact same `CATransaction`-synced architecture as Scrawl's macOS pill. + +### Rust-to-iOS Build & Deploy Ergonomics +Inspected across `hex/ios/project.yml` and `ios-client/project.yml`: +- **Avoid `cargo-mobile2` and `dx bundle` for serious iOS work:** They generate brittle template Xcode projects that break as soon as an app adds Share Extensions (`OpenCodeShare`), Custom Keyboard Extensions (`HEXKeyboard`), App Groups, or Xcode Cloud (`ci_scripts/ci_post_clone.sh`). +- **Recommended Pipeline (`XcodeGen` + `cargo` staticlib/XCFramework + `xcrun devicectl`):** + 1. Define the Xcode project declaratively in `project.yml` (`XcodeGen`, used in both `hex` and the iOS client). + 2. Compile Rust as a `staticlib` (`librune_app.a`) for `aarch64-apple-ios` (device) and `aarch64-apple-ios-sim` (simulator) with a header/Swift bridge (`objc2` when Rust owns `main`, or `uniffi` / `@_cdecl` C-ABI when Swift owns `@main`). + 3. For simulator iteration: `cargo build --target aarch64-apple-ios-sim` → `xcodebuild` → `xcrun simctl install booted ... && xcrun simctl launch booted ...`. + 4. For physical iPhone ProMotion testing: `xcrun devicectl device install app --device <id> <App.app>` + `xcrun devicectl device process launch --device <id> --console <bundle-id>` gives sub-5-second incremental deploy and live stdout/stderr streaming over USB-C or Wi-Fi. + +--- + +## 4. Web Deep Dive (`rune-web`) + +### WebGPU in 2026 +- **Browser Support:** As of 2026 (including **Safari 26** on macOS 26 and iOS 26, Chrome 113+, Edge 113+, and Firefox 141+), WebGPU (`navigator.gpu`) is enabled by default across all major desktop and mobile browsers. +- **Fallback:** Keep `wgpu`'s WebGL2 backend as a compile-time/runtime fallback (`Backends::BROWSER_WEBGPU | Backends::GL`) only for legacy corporate/Linux browsers or headless test environments without WebGPU adapters. +- **High-DPI Canvas Sizing (`ResizeObserver` `devicePixelContentBoxSize`):** + As implemented in `gpui_web/src/window.rs:161-163, 455-510`, attach a `ResizeObserver` with `{ box: "device-pixel-content-box" }` (falling back to `contentRect * window.devicePixelRatio` on browsers lacking `devicePixelContentBoxSize`). This prevents 1-pixel rounding blur at fractional browser zoom levels (e.g., 110%, 125%). + +### Canvas vs DOM Hybrid & Native Scroll Feel +- Render UI into a full-viewport `<canvas tabindex="-1" style="touch-action: none; user-select: none;">` (`gpui_web/src/window.rs:114-135`). +- **Trackpad vs Mouse Wheel on Web:** Browser `WheelEvent`s do not expose macOS's `phase` / `momentumPhase` directly. Distinguish trackpads from discrete mouse wheels using `event.deltaMode == WheelEvent.DOM_DELTA_PIXEL` + fractional/high-frequency deltas vs `DOM_DELTA_LINE`, and detect pinch-to-zoom via `wheel` events with `event.ctrlKey == true` (the standard convention browsers use for trackpad two-finger pinch). + +### Text Input on Web: Hidden `<textarea>` Sliding Mirror vs `EditContext` +- **`EditContext` status in 2026:** The W3C `EditContext` API is shipped in Chromium (Chrome/Edge 121+), where it cleanly decouples IME composition from the DOM. However, **Safari 26 (WebKit) and Firefox still do not support `EditContext`**, meaning any production web shell must maintain a hidden DOM input element. +- **The Right Architecture — Steal `gpui_web/src/ime_mirror.rs` (`lines 1-198`):** + - Naively using an empty hidden `<input>` breaks mobile soft keyboards (iOS Safari, Android Gboard) because backspace, swipe-typing, and autocorrect inspect the text surrounding the caret before emitting edits. + - `gpui_web`'s `ImeMirror` creates a fixed `1px × 1px`, `opacity: 0`, `font-size: 16px` `<textarea>` (using `16px` prevents mobile Safari/Chrome from auto-zooming the viewport on focus; using `<textarea>` instead of `<input>` prevents the browser from silently stripping `\n`). + - On touch devices (`matchMedia("(pointer: coarse)")`), it sets `inputmode="none"` until the user completes a tap (not a scroll pan!) on an editable widget (`window.rs:81-86`, `ime_mirror.rs:119-123`). + - It mirrors a sliding window of `CONTEXT_CHARS = 512` UTF-16 code units before and after the current selection (`ime_mirror.rs:40-48`), and coalesces writes to the `<textarea>` at most once per event-loop turn (`schedule_sync`) because every write to `textarea.value` restarts the browser's IME connection. + +### Accessibility on Web (DOM Mirror / AccessKit) +- A raw `<canvas>` is invisible to VoiceOver, NVDA, and browser Find-in-Page. +- Synchronize Rune's `accesskit::TreeUpdate` into a visually hidden (`opacity: 0; pointer-events: none; position: absolute`) ARIA DOM subtree positioned over the canvas (using `accesskit_web` or a lightweight semantic DOM projector) so screen readers, Tab navigation, and mobile accessibility gestures highlight exact widget bounding boxes. + +### WASM Binary Size, Startup & Threading (`SharedArrayBuffer` / COOP-COEP) +- **Single-Threaded Default on Web:** Requiring `SharedArrayBuffer` (for WASM pthreads / `rayon`) forces every host page to serve `Cross-Origin-Opener-Policy: same-origin` and `Cross-Origin-Embedder-Policy: require-corp` headers. Those headers break embedding Rune demos inside documentation sites, GitHub Pages, iframes, or third-party blogs. + - **Rule:** Rune's core layout, animation, and rendering pipeline on `wasm32-unknown-unknown` **must run cleanly on the main browser thread without `SharedArrayBuffer`** (`ForegroundExecutor` + `BackgroundExecutor` backed by browser microtasks / `postMessage` / optional Web Workers via message passing, as in `gpui_web/src/dispatcher.rs`). +- **Binary Size Budget:** Strip debug symbols, compile with `opt-level = "z"` or `"s"` + `lto = "fat"` + `wasm-opt -Oz`, and dynamically stream-load fonts rather than embedding multi-megabyte `.ttf` files in `.wasm`. Target **< 1.5 MB Brotli-compressed `.wasm`** for initial load. + +--- + +## 5. Windows, Linux & Android + +### Windows (`rune-windows`) +Grounded in `gpui_windows` (13,187 LOC): +- **Windowing & Composition (`DirectComposition`):** + Create a Win32 `HWND` (`WS_EX_NOREDIRECTIONBITMAP`) paired with `IDCompositionDevice` / `IDCompositionTarget` / `IDCompositionVisual` (`gpui_windows/src/directx_renderer.rs:118-135`). Using DirectComposition with a flip-model swap chain (`DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL`, `DXGI_ALPHA_MODE_PREMULTIPLIED`) enables per-pixel transparency, Windows 11 Mica/Acrylic backdrops (`DwmSetWindowAttribute` with `DWMWA_SYSTEMBACKDROP_TYPE`), and smooth resize. +- **VSync & Frame Pacing (`vsync.rs:1-85`):** + Query the monitor refresh period via `DwmGetCompositionTimingInfo` (`qpcRefreshPeriod`) and wait on `DwmFlush()` on a dedicated VSync thread. As `gpui_windows/src/vsync.rs:45-58` notes, when a monitor sleeps or is occluded, `DwmFlush()` returns immediately (< 1 ms); detect `elapsed < 1ms` and fall back to `sleep(interval)` so the app never busy-loops at 10,000 FPS. +- **Precision Touchpad Gestures (`DirectManipulation`):** + Do **not** rely solely on legacy `WM_MOUSEWHEEL` / `WM_MOUSEHWHEEL` on Windows—they lack gesture phase (`Began`/`Ended`) and trackpad pinch zoom. Steal `gpui_windows/src/direct_manipulation.rs:1-160`: create an `IDirectManipulationManager` + `IDirectManipulationViewport` on the `HWND` and call `viewport.SetContact(pointer_id)` on `WM_POINTERHITTEST` when `pointer_type == PT_TOUCHPAD`. This delivers smooth pixel-accurate translation, inertia, and pinch-scale callbacks with explicit gesture phases. +- **Text & IME:** Use DirectWrite (`IDWriteFactory5`) for system font fallback and ClearType/grayscale contrast parameters (`directx_renderer.rs:32-37`), and `ImmAssociateContextEx` / `ImmSetCandidateWindow` (`IMM32` + TSF compatibility) for candidate window positioning. +- **GPU Backend:** Use `wgpu` on DX12 (or a direct DX11/DX12 backend behind Rune's renderer trait), ensuring `DXGI_ERROR_DEVICE_REMOVED` / `DEVICE_RESET` triggers an atlas wipe and forced full redraw (`gpui_windows/src/window.rs:68-75`). + +### Linux (`rune-linux`) +Grounded in `gpui_linux` (16,422 LOC): +- **Wayland-First, X11 Fallback:** + Build the event loop on `calloop` (`gpui_linux/src/linux/wayland/window.rs:10`). Target Wayland natively via `wayland-client` + `wayland-protocols`: + - `xdg_wm_base` / `xdg_toplevel` / `xdg_popup` for windows and popups. + - `wp_fractional_scale_v1` + `wp_viewporter` (`window.rs:21, 28`) for crisp native fractional scaling (125%, 150%, 175%) without XWayland blur. + - `wl_surface::frame` callbacks (`pending_frame_callback`, `window.rs:136`) for compositor-driven VSync per monitor. + - `zwp_text_input_v3` for IME composition and candidate rectangle placement (`set_cursor_rectangle`). + - `zxdg_toplevel_decoration_v1` to negotiate server-side vs client-side window decorations (`CSD`/`SSD`), plus `zwlr_layer_surface_v1` (`wlr-layer-shell`) so Rune can build Linux status bars, launchers, and notifications. +- **XDG Desktop Portals (`ashpd`):** + Steal `gpui_linux/src/linux/xdg_desktop_portal.rs:1-150`: connect an `ashpd` D-Bus listener into `calloop` to reactively track dark/light `ColorScheme`, cursor theme/size, titlebar button layout, and native sandboxed file pickers (`org.freedesktop.portal.FileChooser`) and screen sharing. + +### Android (`rune-android`) +- **`GameActivity` / Custom `Activity` + `SurfaceView` vs `TextureView`:** + - Full-screen Rune apps should use a lightweight Kotlin `Activity` hosting a `SurfaceView` (which gets its own hardware compositor layer and avoids extra GPU texture copies) synced to `Choreographer.getInstance().postFrameCallback` for 120 Hz VSync. + - When Rune is embedded inside a scrolling Jetpack Compose / Android `View` hierarchy, use `TextureView` (or `SurfaceView` with `setZOrderMediaOverlay`) so it participates in view clipping and alpha transitions. +- **IME (`InputConnection`) & Accessibility (`AccessibilityNodeProvider`):** + - Android software keyboards (Gboard, Samsung Keyboard) communicate via `View.onCreateInputConnection(EditorInfo)` returning a stateful `BaseInputConnection` (`setComposingText`, `commitText`, `deleteSurroundingText`, `getExtractedText`). Pure native `NativeActivity` cannot implement `InputConnection` without JNI calls to a Java/Kotlin `View`. + - Pair a ~300-line Kotlin host view (`RuneSurfaceView.kt`) that implements `onCreateInputConnection` and `AccessibilityNodeProvider` (bridged to `accesskit`) with JNI calls into `rune-android`. + +--- + +## 6. Platform-Specific Feel: Native vs Rune's Own + +| Concern | Use OS Native | Build in Rune (Platform-Tuned) | Why | +|---|---|---|---| +| **Scroll physics** | — | **Rune's own**, parameterized by platform (`MacTrackpad`, `iOSMomentum`, `DesktopWheel`) | Gives deterministic 120 Hz spring interruption, programmatic scroll-to-element, and cross-view coordinated animations while matching iOS `0.998` deceleration + `0.55` rubber-band math and macOS `NSEventPhase` momentum handoff. | +| **Text selection UX** | **OS IME & Mobile Callout Bar** (`UITextInput` / `UIMenuController` / `UIEditMenuInteraction`) | **Rune renders selection highlights, carets & desktop handles** | On iOS, returning `selectionRectsForRange:` from `UITextInput` lets UIKit render the native Loupe and Copy/Paste/Translate pill while Rune renders the glyphs and selection quads at 120 Hz. | +| **Context menus** | **OS Native on macOS** (`NSMenu`) **& iOS** (`UIEditMenuInteraction` / `UIContextMenuInteraction`); **Rune custom** on Web/Win/Linux (or when custom rich previews are needed) | Configurable per menu | macOS users expect native `NSMenu` translucency, screen-edge flipping, and Services integration; rich app-specific command palettes use Rune's own overlay layer. | +| **Focus rings & Keyboard nav** | Respect OS settings (`NSApplication.fullKeyboardAccessEnabled`, `UIAccessibilityIsReduceMotionEnabled`, Windows high-contrast) | **Rune's own focus graph & animated focus ring** | Only Rune knows widget geometry and spring transitions; focus ring thickness, color (`accentColor`), and Tab traversal rules adapt to the active platform's conventions. | +| **File dialogs, Share sheets, Permissions** | **Always OS Native** (`NSOpenPanel`/`NSSavePanel`, `UIActivityViewController`/`PHPickerViewController`, XDG FileChooser Portal, Web `<input type="file">`) | Never custom | Security sandboxes (TCC, App Sandbox, Wayland Portals, browser security) require native OS pickers. | + +--- + +## 7. Steal / Avoid Lists + +### Steal +1. **Scrawl's `CATransaction`-synchronized `NSGlassEffectView` + `CAMetalLayer` pipeline** (`scrawl/src/native/pill/mod.rs:447-453, 644-675, 1111-1147`): `presentsWithTransaction = true`, initial `window.displayIfNeeded()` while `alphaValue = 0.0` so AppKit materializes `SDFLayer` + `CABackdropLayer`, and `CATransaction::begin() ... cmd.wait_until_scheduled(); drawable.present(); CATransaction::commit()` for zero-lag glass morphing. +2. **The launcher's non-activating `NSPanel` + cold-start warm-up + Quick Look responder chain** (`launcher/native/Launcher.swift:26-75, 566-578`): `canBecomeKey = true`, `canBecomeMain = false`, invisible warm-up pass on startup, and `QLPreviewPanel` control forwarding. +3. **Makepad's `CADisplayLink` 120 Hz ProMotion pinning on macOS 14+** (`makepad/platform/src/os/apple/macos/macos_app.rs:1458-1482`): pinning `setPreferredFrameRateRange:` to `window.screen.maximumFramesPerSecond` so macOS never throttles custom GPU views to 30 Hz. +4. **GPUI's `displayLayer:` synchronous live-resize dance on macOS** (`gpui_macos/src/window.rs:2058-2075, 2260-2285`): pausing the display link during `displayLayer:`, enabling `presentsWithTransaction = true`, rendering at the new size, and committing inside AppKit's resize transaction. +5. **GPUI's `GPUITextInputView` on iOS** (`gpui_ios/src/ios/text_input.rs:42-350`): full `UITextInput` implementation in Rust with `session_token`-stamped `UITextPosition`/`UITextRange` and deferred `reconcileTextInput`. +6. **GPUI Web's `ImeMirror` sliding-window hidden `<textarea>`** (`gpui_web/src/ime_mirror.rs:1-198`): 512-UTF-16-unit context window around the selection, `font-size: 16px`, `inputmode="none"` until tap completion on touch screens, and single-write-per-frame coalescing. +7. **GPUI Windows' `DirectManipulationHandler` & VSync sleep fallback** (`gpui_windows/src/direct_manipulation.rs:1-160`, `vsync.rs:41-60`): native precision-touchpad scroll/pinch phases on Windows and occlusion-safe `DwmFlush()` frame pacing. +8. **GPUI Linux's `calloop` + Wayland fractional scale + `ashpd` portal stream** (`gpui_linux/src/linux/wayland/window.rs`, `xdg_desktop_portal.rs`): clean event-loop integration of Wayland protocols and D-Bus desktop settings. + +### Avoid +1. **Avoid `winit` as a dependency.** Working around its missing `UITextInput` on iOS, incomplete `NSTextInputClient` on macOS, lack of `presentsWithTransaction` resize sync, and inability to mount as a lightweight `UIViewRepresentable` costs more effort than writing thin shells directly with `objc2` / `web-sys` / `windows` / `wayland-client`. +2. **Avoid tearing down `CVDisplayLink` on window close** (`gpui_macos/src/display_link.rs:16-30`); prefer macOS 14+ `NSView.displayLinkWithTarget:selector:` (`CADisplayLink`) or immortal per-display `CVDisplayLink`s. +3. **Avoid Flutter-style general N-layer `EmbedderViewSlice` platform view slicing.** Allocating intermediate full-screen `CAMetalLayer`s and buffering touch events across threads (`FlutterPlatformViewsController.mm`) adds memory, GPU bandwidth, and input lag. Use explicit Underlay and Overlay view slots on the main thread instead. +4. **Avoid requiring `SharedArrayBuffer` (COOP/COEP headers) on Web.** It makes embedding Rune canvases in docs, blogs, and standard web pages impossible without custom server headers. +5. **Avoid `cargo-mobile2` or `dx bundle` for iOS project management.** Use `XcodeGen` (`project.yml`) + a `cargo` staticlib/XCFramework script so app extensions (`OpenCodeShare`, `HEXKeyboard`), entitlements, and Xcode Cloud continue to work like normal Xcode projects. + +--- + +## 8. Recommendations for Rune + +### 8.1 Own Thin Shells vs `winit` +**Decision: Write Rune's own thin per-platform shells (`rune-platform-*`).** +- **Rejected alternative (`winit` `0.31`):** Rejected because text input (`UITextInput` / `NSTextInputClient`), live-resize transaction sync (`presentsWithTransaction`), native materials (`NSGlassEffectView` / `UIGlassEffect`), and `UIViewRepresentable` / `NSViewRepresentable` embedding are architectural load-bearing walls, not bolt-on plugins. +- **Rejected alternative (`SDL3`):** Rejected because it adds a large C dependency without solving native Apple/Web text input, accessibility, or SwiftUI/UIKit view hosting. + +### 8.2 The Shell API Surface (The Rust Traits) +Keep the boundary between `rune-core` and platform shells narrow—roughly 5 traits in `rune_core::platform` (modeled on a cleaner, slimmer version of `gpui/src/platform.rs`): + +```rust +pub trait Platform: 'static { + fn run(&self, on_Ready: Box<dyn FnOnce(&mut AppContext)>); + fn dispatcher(&self) -> Arc<dyn PlatformDispatcher>; + fn open_window(&self, options: WindowOptions) -> anyhow::Result<Box<dyn PlatformWindow>>; + fn displays(&self) -> Vec<Rc<dyn PlatformDisplay>>; + fn clipboard(&self) -> &dyn PlatformClipboard; + fn set_menus(&self, menus: Vec<Menu>, keymap: &Keymap); +} + +pub trait PlatformWindow: 'static { + fn bounds(&self) -> Bounds<LogicalPixels>; + fn scale_factor(&self) -> f32; + fn safe_area_insets(&self) -> Edges<LogicalPixels>; + fn appearance(&self) -> WindowAppearance; + fn request_frame(&self, FrameRequest); // ActiveAnimation (120Hz) vs SingleFrame + fn draw(&mut self, scene: &Scene, glass_underlays: &[GlassRegion], native_overlays: &[NativeOverlay]); + fn set_input_handler(&mut self, handler: Option<PlatformInputHandler>); + fn set_cursor(&mut self, cursor: CursorStyle); + fn trigger_haptic(&self, pattern: HapticPattern); + fn update_accessibility_tree(&mut self, update: accesskit::TreeUpdate); + // Callbacks registered by rune-core: + fn on_frame(&mut self, cb: Box<dyn FnMut(FrameInfo)>); + fn on_input(&mut self, cb: Box<dyn FnMut(PlatformInput) -> EventResult>); + fn on_resize(&mut self, cb: Box<dyn FnMut(Size<LogicalPixels>, f32, Edges<LogicalPixels>)>); +} + +pub trait PlatformTextInput { + fn text_for_range(&mut self, range_utf16: Range<usize>, adjusted: &mut Option<Range<usize>>) -> Option<String>; + fn selected_range(&mut self, ignore_marked: bool) -> Option<SelectionUtf16>; + fn marked_range(&self) -> Option<Range<usize>>; + fn replace_text_in_range(&mut self, range_utf16: Option<Range<usize>>, text: &str); + fn replace_and_mark_text_in_range(&mut self, range_utf16: Option<Range<usize>>, new_text: &str, selected_utf16: Option<Range<usize>>); + fn unmark_text(&mut self); + fn bounds_for_range(&mut self, range_utf16: Range<usize>) -> Option<Bounds<LogicalPixels>>; + fn character_index_for_point(&mut self, point: Point<LogicalPixels>) -> Option<usize>; +} +``` +Notice `draw(&mut self, scene: &Scene, glass_underlays: &[GlassRegion], native_overlays: &[NativeOverlay])`: passing native glass/underlay regions alongside the GPU `Scene` lets `rune-macos` and `rune-ios` synchronize `NSGlassEffectView` / `UIVisualEffectView` frames and corner radii inside the **same `CATransaction`** as the Metal drawable presentation (`scrawl/src/native/pill/mod.rs:1111-1147`). + +### 8.3 Native View Embedding Strategy +Support two complementary mechanisms: +1. **Rune-in-Native (`RuneHostView`):** Every platform shell exposes a constructor that wraps an existing native view (`UIView`, `NSView`, `<canvas>`, `HWND`, `SurfaceView`) instead of creating a top-level OS window. On iOS and macOS, ship a thin Swift wrapper (`RuneView: UIViewRepresentable` / `NSViewRepresentable`) so the iOS client, `hex`, `scrawl`, and the launcher can drop a 120 Hz Rune view into any SwiftUI screen today, sharing one process-wide `MTLDevice` and `CADisplayLink`. +2. **Native-in-Rune (Underlay & Overlay Slots):** Within a Rune window, support declarative `NativeUnderlay` (for `NSGlassEffectView` / `UIGlassEffect`, `AVPlayerLayer`, `MKMapView` behind a transparent hole in the Metal pass) and `NativeOverlay` (for `WKWebView`, system pickers, and popovers above the Metal layer), synced synchronously on the main thread inside `CATransaction`. + +### 8.4 Platform Order & Effort Estimates + +| Priority | Platform Shell | Est. Size | Est. Effort | Why This Order | +|---:|---|---:|---:|---| +| **1** | **macOS (`rune-macos` + `rune-apple`)** | ~4,500 LOC (`macos`) + ~2,000 LOC (`apple` shared) | **2–3 weeks** | Fastest local compile/debug cycle; directly powers `scrawl` and the launcher; establishes the `objc2` + `CAMetalLayer` + `CATransaction` + `NSGlassEffectView` + CoreText foundation shared with iOS. | +| **2** | **iOS (`rune-ios` + `RuneKit` Swift host)** | ~3,000 LOC Rust + ~400 LOC Swift | **2 weeks** | Reuses `rune-apple` (CoreText, Metal/wgpu, `dispatch2`, `objc2`); unlocks 120 Hz ProMotion touch/spring validation on iPhone and immediate incremental adoption inside the iOS client and `hex` via `RuneView: UIViewRepresentable`. | +| **3** | **Web (`rune-web`, WASM + WebGPU)** | ~3,500 LOC | **2 weeks** | Safari 26 + Chrome/Firefox/Edge now all support WebGPU; essential for interactive documentation, motion playgrounds, and zero-install demos shared over Tailscale or the web. | +| **4** | **Windows (`rune-windows`)** | ~6,500 LOC | **3–4 weeks** | Largest desktop user base outside macOS; `gpui_windows` provides a complete blueprint for DirectComposition, `DwmFlush` VSync, and `DirectManipulation` trackpad gestures. | +| **5** | **Linux (`rune-linux`, Wayland-first)** | ~6,000 LOC (Wayland + `ashpd` portals) | **3 weeks** | Focus on Wayland (`xdg-shell`, `wp-fractional-scale-v1`, `text-input-v3`, `wlr-layer-shell`, `ashpd`); defer native X11 unless XWayland proves insufficient for specific users. | +| **6** | **Android (`rune-android`)** | ~2,500 LOC Rust + ~400 LOC Kotlin | **2–3 weeks** | Lowest immediate priority for Kit's apps; architectural requirements (JNI `InputConnection` + `Choreographer` + `SurfaceView`/`TextureView`) are already accommodated by the `PlatformWindow` and `PlatformTextInput` traits designed in steps 1–3. | + +--- + +## 9. Open Questions + +1. **Multiple `NSGlassEffectView` instances vs `NSGlassEffectContainerView` on macOS 26 / iOS 26:** When a Rune window contains multiple floating glass pills that morph and merge (metaball effect), should `GlassRegion` group them under a single `NSGlassEffectContainerView` / `UIGlassContainerEffect` underlay, and how many concurrent glass regions can WindowServer composite at 120 Hz before backdrop bandwidth drops frames? +2. **Swift 6.2 `@MainActor` interop with `RuneKit`:** In the iOS client (`SWIFT_DEFAULT_ACTOR_ISOLATION: MainActor`), what is the cleanest zero-boilerplate Swift macro or `@MainActor` wrapper so TCA reducers/views can drive `RuneView` state props without copying large buffers across FFI? +3. **Web `EditContext` progressive enhancement:** Should `rune-web` use Chromium's `EditContext` API when `window.EditContext !== undefined` and fall back to `ImeMirror` (`<textarea>`) on Safari/Firefox, or use `ImeMirror` everywhere on Web to avoid maintaining two browser IME codepaths? +4. **Linux X11 support:** Is Wayland + XWayland sufficient for Rune's Linux target in 2026–2027, saving ~6,000 LOC of legacy X11/XCB/XIM code (`gpui_linux/src/linux/x11`), or do target Linux users still require a native X11 backend? diff --git a/app/vendor/rune/research/12-research-rendering.md b/app/vendor/rune/research/12-research-rendering.md new file mode 100644 index 0000000..120e4bb --- /dev/null +++ b/app/vendor/rune/research/12-research-rendering.md @@ -0,0 +1,288 @@ +# 12. Rendering research and tricks for Rune (2D/UI GPU rendering, 2023-2026) + +Scope: analytic AA and coverage, sparse strips, Slug, Rive feathering, blur and backdrop, glass lensing, SDF shapes, +GPU-driven UI, Apple TBDR, damage tracking, HDR, dithering, colour. Written 2026-10-21. Sources were fetched via search +snippets and (where quoted) real source; items marked *(from memory)* or *(estimate)* were not re-verified. Nothing was +built or measured here. + +## Summary + +- **Most of the PLAN §4.3 primitive list is already right.** Research mostly confirms it and sharpens details. Nothing + found says "change the architecture". +- **Biggest new finds:** (1) `vello_cpu` is a fast, SIMD, multithreaded CPU renderer, so it can be the *reference + renderer* tenet 7 asks for, for free. (2) Rive's *vector feathering* is an analytic Gaussian blur of arbitrary + paths, and its "never blur above 16 px, scale up instead" rule applies to Rune's backdrop too. (3) Evaluating the + closed-form springs *in the vertex shader* is a trick only a render-thread-owns-animation design can use. +- **Backdrop blur:** the Jimenez 13-tap down / 9-tap tent up pyramid is still the right tool (2014, still current). + The new problem is temporal: an animated blur radius must be continuous, so blend between pyramid levels. +- **Glass in-app:** open-source "liquid glass" shaders (WebGL, Metal gist, a GPUI fork) all use the same recipe: SDF + height field, normal, refraction offset, chroma split, Fresnel/specular, blurred copy. It is cheap *given* a + backdrop copy. The copy is the expensive part, so scissor it to the glass bounds. +- **Slug:** patent dedicated to public domain 2026-03-17; MIT reference shaders now include dynamic dilation and drop + the band-split and supersampling complications. Good for scale-animated text and icons. +- **Skip or defer:** GPU-driven indirect rendering (UI scenes are too small), partial present (power, not feel; Metal + gives no buffer age), HDR UI, Apple tile shaders for blur (tiles cannot see neighbours). +- Exact-count perf gates (tenet 7) fit every technique below: all are countable (taps, passes, instances, bytes). + +## Ranked ideas + +### 1. `vello_cpu` as the CPU reference renderer (and `vello_gpu` as the complex-vector lane) — **adopt now / spike** + +- Sources: [Stampfl thesis, ETH, Oct 2025](https://ethz.ch/content/dam/ethz/special-interest/infk/inst-pls/plf-dam/documents/StudentProjects/MasterTheses/2025-Laurenz-Thesis.pdf); + [Vello ARCHITECTURE.md](https://cdn.jsdelivr.net/gh/linebender/vello@main/ARCHITECTURE.md); + [Linebender Jul 2025](https://linebender.org/blog/tmil-19/), [Oct 2025](https://linebender.org/blog/tmil-22/); + [sparse-strips v0.0.8](https://github.com/linebender/vello/releases/tag/sparse-strips-v0.0.8); + [benchmarks](https://laurenzv.github.io/vello_chart/). +- What it is: paths flatten, bin into tiles, and become run-length "sparse strips" (coverage kept only at edges, + solid runs stored compactly). One CPU pipeline (`vello_common`) feeds `vello_cpu` (SIMD via `fearless_simd` + NEON/SSE4.2/WASM, optional multithreading) and `vello_gpu` (plain vertex/fragment, wgpu and WebGL2, no compute). + Compute Vello moved to `research/`, matching PLAN. Measured (M1 Pro, Blend2D harness, preliminary): vello_cpu is + second to Blend2D in many tests and often beats Skia and Cairo, more so on large geometry. It already has blurred + rounded-rect paints, opacity layers, non-isolated blending, and early image filters including blur. +- Rune use: (a) the **reference path** from tenet 7 / §6b "same pixels on every platform": render the same scene + description through vello_cpu and diff against the GPU lane (tolerance per primitive). (b) The deterministic + headless lane for agents on machines with no GPU (CI, Linux boxes). (c) `vello_gpu` as the `SparseStrips` + primitive for icons/illustrations. API is explicitly unstable; pin a version and wrap it. +- Cost/risk: alpha-quality, API churn, MSRV bumps. CPU AA differs slightly from GPU analytic AA, so diff tolerance + must be calibrated per primitive, not zero. Verdict: adopt vello_cpu as oracle now; spike vello_gpu. + +### 2. Evaluate analytic springs in the vertex shader — **spike** *(my idea; no source)* + +- Rune already uses closed-form springs (position, velocity, target, t0, omega, zeta). Upload those few floats as + instance data and evaluate `x(t)` in the vertex shader with a per-frame `time` uniform. While anything animates, + the app thread does nothing, and the render thread rewrites only the uniform. Instance buffers become retained, + rewritten only on retarget or tree change, instead of rebuilt per frame. +- Gains: zero CPU per animated node per frame (a list of 500 sliding rows costs the same as one); sample time is the + display-link target timestamp, so late frames still land on the right pose; the GPU and CPU copies of the same + function make a perfect differential test (render the same `t` on both). +- Caveats: hit-testing, clip tables, text positions and layout children need the CPU value too (same function, run + lazily only when queried, e.g. on input). Float32 vs f64 drift: define springs relative to t0 so `t - t0` is small. + Properties that feed other computations (shadow offset depends on position) need the shader to evaluate several + springs per instance; budget a fixed number of tracks per instance (e.g. 4) in the layout of the instance struct. +- Verdict: spike, measuring encode CPU time with 1k animating nodes vs the baseline of per-frame instance rebuild. + +### 3. Pyramid backdrop blur (Jimenez dual filter) with continuous radius — **adopt now** + +- Sources: [Jimenez, SIGGRAPH 2014](https://www.iryoku.com/next-generation-post-processing-in-call-of-duty-advanced-warfare/); + [three.js port with numbers](https://tobis.vision/notes/three-js-bloom-jimenez-dual-filter) (claims 9x faster than + the stock bloom; a radius-22 Gaussian is 86 taps at one level vs 9 on the pyramid); + [WGSL downsample with Karis average](https://docs.rs/crate/myth_render/latest/source/src/pipeline/shaders/entry/post_process/bloom/downsample.wgsl). + Dual Kawase (ARM, SIGGRAPH 2015) is the cheaper 5-tap cousin, *(from memory)*. +- Mechanics: 13-tap downsample (weights 0.125/0.0625/0.03125, sum 1), 3x3 tent upsample added into the finer level, + Karis luminance weighting on the first level only for stability against sparkle. Wide blur comes from depth of the + pyramid, not kernel width. +- Rune use for the `Backdrop` primitive: (a) scissor everything to the union of glass bounds plus the blur margin; + (b) pick pyramid depth from the requested sigma; (c) **fractional radius**: crossfade the two nearest pyramid + levels by the fractional part so an animated radius never steps (the actual risk for Kit's motion rules: a radius + spring must not snap between integer levels); (d) store the pyramid in rgba16f or rg11b10 to avoid banding and + dither at the final composite (see idea 9); (e) cache the blurred pyramid when the underlying scene is unchanged + (glass over static content costs one composite). +- Rive's rule is a useful twin: [`draw.cpp`](https://github.com/rive-app/rive-runtime/blob/f4e896a4/renderer/src/draw.cpp) + never renders a blur wider than 16 px at the render scale; it renders smaller and scales up. The pyramid is the same + idea. +- Cost/risk: low. Downsampled upsample can leak the glass edge into the blur; premultiply and use the glass mask at + composite (the three.js liquid-glass repos premultiply on the first pass for this reason). +- Peak-alpha boost (Scrawl) is orthogonal and composes after the blur. + +### 4. Liquid-glass-style lens as an in-app material — **spike** + +- Sources (all MIT-ish, small): [liquid-glass-js `webgl.ts`](https://github.com/Amir-Abushanab/liquid-glass-js/blob/main/packages/core/src/webgl.ts) + (SDF mask, baked displacement map RG, specular B, chroma split, adaptive specular: additive on dark, multiplicative + on bright, plus a vibrancy pull toward mid grey for legibility); + [liquid-glass-studio](https://github.com/iyinchao/liquid-glass-studio/) (refraction, dispersion, Fresnel, + superellipse shapes, **smooth-union blob merging**, spring-driven shape animation, WebGL2 and WebGPU); + [Metal gist](https://gist.github.com/destefanis/b69545e63b38eb91a13c7c5d330d1345); + [GPUI fork PR adding BlurRect and LensRect primitives](https://github.com/df49b9cd/zed/pull/1) (Apr 2026, shows the + same shape of primitive in GPUI). +- What Rune would do: one `Lens` material on `UberQuad`: compute the SDF, derive a height profile from the distance + (smoothstep or erf edge falloff), normal = gradient of height, refracted sample offset = normal * strength, sample + the backdrop at three offsets for dispersion, mix with the blurred pyramid for frost, add Fresnel and a + specular rim. For rounded rects and superellipses the height and gradient are closed-form per pixel, so the + baked displacement map in those repos is unnecessary and the shape can animate every frame (no map regeneration). +- The real cost is the backdrop copy (render pass break, see idea 7). Scissor-copy only the glass bounds plus + displacement margin; for several glass shapes copy their union rect once. +- The "adaptive specular + vibrancy" trick matters for §6b "real contrast": it is a legibility control, and the + contrast checker can verify it. +- This is the in-app answer to PLAN §4.4's limit ("Rune can't draw Liquid Glass"): the system's own shader is out of + reach, but a plausible lens is not, and it works on web/Windows/Linux too, which native underlays never will. +- Risk: it will not match Apple's exactly; design decision for Kit. Verdict: spike with one hero element, compare + against `NSGlassEffectView` side by side. + +### 5. Slug for scale-animated text and icons — **spike** (already in the plan; new facts) + +- Sources: [A Decade of Slug](https://terathon.com/blog/decade-slug.html) (patent #10,373,352 dedicated to the public + domain 2026-03-17), [reference shaders, MIT/Apache](https://github.com/EricLengyel/Slug), the JCGT 2017 paper, + [dilation write-up](https://terathon.com/blog/glyph-dilation.html). +- New facts: the 2026 pixel shader is "a significant upgrade"; the vertex shader has **dynamic dilation** (expand the + bounding polygon by half a pixel in viewport space per vertex, using the MVP and viewport, so no wasted padding and + no missing edge pixels under perspective or scale); adaptive supersampling and the band-split optimisation were + removed (simpler). Curve and band data live in textures (fixed 4096-wide); per pixel it solves quadratic roots in + two directions. +- Rune use: text or icons under scale springs (a title growing 0.9 to 1.0) re-rasterise glyph-atlas entries at + every size, which pops; Slug has no atlas. Pair with a coverage-based weight boost (their `SLUG_WEIGHT` sqrt) to + keep light-on-dark text from thinning. Keep the atlas for body text at 1x (cheaper per pixel). +- Cost/risk: fragment cost is higher than atlas sampling; quadratic outlines only (TrueType native, CFF cubics need + conversion); no hinting. Gate with a per-scene counter of Slug pixels. Verdict: spike after the glyph atlas works. + +### 6. Rive-style analytic feathering for soft shapes — **later / steal one trick now** + +- Sources: [Rive blog (Apr 2025)](https://rive.app/blog/how-rive-reinvented-feathering-for-the-vectorian-era), + [intro (Feb 2025)](https://rive.app/blog/introducing-vector-feathering), + [renderer source: `draw.cpp`, `tessellate.glsl`](https://github.com/rive-app/rive-runtime/blob/5360c834/renderer/src/shaders/tessellate.glsl), + [Khronos slides](https://www.khronos.org/assets/uploads/developers/presentations/Rive.pdf). +- What it does: widens the one-pixel AA ramp into a Gaussian CDF ramp (`erf`) of the chosen width, computed + procedurally from the same coverage triangles. A 1D lookup texture holds the CDF and its inverse. At corners the + integral is done with about four samples per fragment; in the tessellator, curvature dims the feather by + flattening the curve's control points (`dimming = 1 - curvature/pi`). No offscreen blur pass, resolution + independent, cheap on weak GPUs. Large radii fall back to an atlas path rendered small then scaled up. +- Rune use: free-form soft glows and inner/outer shadows of arbitrary paths (icons, blobs) without an offscreen + pass. For rounded rects the Levien closed form (idea 8) is simpler and exact; feathering matters only for + non-rect paths. It needs an own tessellator with signed-winding triangles (Rive's coverage scheme), which Rune does + not have; `vello_cpu`'s blur filter or an offscreen blur is the pragmatic route until then. +- Steal now: (1) CDF 1D texture trick for any ramp (it replaces `erf` approximations in the shader); (2) "design-tool + blur = 2 sigma wide" convention (feather radius = amount * stddevs / 2) so Figma-like numbers match. +- Verdict: later, behind Rune having its own path tessellator. + +### 7. Apple TBDR discipline (framebuffer fetch, memoryless, load/store) — **later, Metal backend only** + +- Sources: [WWDC20 Harness Apple GPUs](https://developer.apple.com/videos/play/wwdc2020/10602/), + [WWDC21 image processing on Apple silicon](https://developer.apple.com/videos/play/wwdc2021/10153/), + [Metal 2 on A11: imageblocks](https://developer.apple.com/videos/play/tech-talks/603/) and + [tile shading](https://developer.apple.com/videos/play/tech-talks/604/), + [Tailor your apps for TBDR](https://developer.apple.com/documentation/metal/tailor-your-apps-for-apple-gpus-and-tile-based-deferred-rendering). +- Key facts: alpha blending runs in tile memory and the target is written once per pass; programmable blending lets a + fragment read the tile's current colour (merges multi-pass effects with no intermediate store); memoryless + textures live only in tile memory (must be `DontCare`/`Clear` load and `DontCare` store, no sampling, no blit or + compute); `LoadActionDontCare`/`Clear` avoids reading what is overwritten. +- Rune use: (a) **group opacity** and non-trivial blend modes (multiply, screen, plus-lighter) via framebuffer fetch + in the one pass, avoiding offscreen layers (matches PLAN §4.2). (b) Always `DontCare` loads where the frame is + fully redrawn. (c) MSAA is unnecessary for UI (analytic AA), so memoryless MSAA is not a lever. +- Limits: a backdrop *sample* (blur, lens) reads neighbouring pixels, which tile memory cannot provide; tile shaders + see only their own tile. So glass still needs a pass break (store, then load) and the copy in idea 4. Raster order + groups (also used by Rive on D3D11/Metal) serialise overlapping fragments; Rive uses them for exact path + blending, which Rune does not need for the uber-quad lane. +- wgpu: **I could not confirm** any framebuffer-fetch or pixel-local-storage support in wgpu *(treat as unsupported)*; + this is a concrete reason to keep the raw-Metal HAL on the plan as a later optimisation. Verdict: later, justified + only by measured offscreen-layer cost. + +### 8. Closed-form blurred rounded rects, inset shadows, and squircles — **adopt now** + +- Sources: [Levien, blurred rounded rects](https://raphlinus.github.io/graphics/2020/04/21/blurred-rounded-rects.html) + (rounded-rect distance field, effective radius `sqrt(rc^2 + 1.25 rb^2)`, 1D erf cross-section, `erf7` using a + reciprocal sqrt); [Evan Wallace, fast rounded-rect shadows](https://madebyevan.com/shaders/fast-rounded-rectangle-shadows/) + (product of two erf boxes; CC0 code); [Vello's implementation, #665](https://github.com/linebender/vello/pull/665) + plus the active inset-shadow work ([#1374](https://github.com/linebender/vello/issues/1374), + [#1718](https://github.com/linebender/vello/pull/1718)) and [#1724](https://github.com/linebender/vello/pull/1724) + (cutting `powf` calls). +- Rune use: the `UberQuad` already plans analytic Gaussian shadows (PLAN §4.3). Take Levien's formula as the base, + differential-test it against numerically integrated results (the CPU reference) per radius and sigma, and add + inset shadows as `1 - blurred` per Vello's design. The same field gives soft per-side gradient edges for the "no + hard clip edges" rule, since a blurred rounded rect is exactly a soft mask. +- **Squircles (continuous corners):** iOS-style corners are not circles; Figma's "corner smoothing" parameter is the + common reference and a superellipse is the cheap stand-in *(from memory)*. Implicit shapes have no exact distance, + so use `f / |grad f|` as an AA distance (valid near the edge, wrong far away; fine because only the edge band is + shaded). Test against a high-resolution CPU rasteriser for AA ramp error. +- **Smooth union for morphing shapes:** polynomial `smin` (Quilez) over a handful of SDFs gives the metaball merge + seen in liquid-glass-studio; lerping two SDFs is a cheap shape morph. Fix a maximum number of operands per `Blob` + primitive (4) so the shader stays branch-free. This is how Rune can do the launcher's glass morph without SwiftUI on + non-Apple platforms. +- Cost/risk: low; the main risk is the AA width under non-uniform scale and rotation: derive the pixel footprint + from the Jacobian (`fwidth` or explicit inverse transform), not a scalar scale. Add a rotation/skew scene. + +### 9. Dithering and perceptual colour — **adopt now** + +- Sources: Jimenez interleaved gradient noise (same CoD talk as idea 3; cheap per-pixel hash, good temporal + behaviour); Christoph Peters, free blue-noise textures *(from memory, no link fetched)*; Ottosson's Oklab and + gamut-clipping posts *(from memory)*; PLAN §4.3 already cites Kit's GPUI fork (`kitlangton/gpui`) dithering fixes. +- Rune use: interpolate gradients in Oklab (or OKLCH for hue ramps) and blend in linear light on Display P3, as the + plan says; then dither once at the final write, with triangular-PDF noise of about +/-1 LSB, using a tiled blue + noise texture or IGN. One shared function for gradients, shadows, backdrop output, and video. +- Two traps worth encoding as tests: (1) **noise swim**: a screen-space-fixed pattern over scrolling content shimmers + relative to the content; use content-local coordinates for scrolling layers (or accept it for static UI). Never + animate the noise per frame (breaks "zero cost at rest" and snapshot determinism); the seed must be a pure function + of pixel coordinates. (2) **Banding in blurred backdrops**: a blur of 8-bit content upsampled by a pyramid bands; + dither after the final upsample and keep intermediates in 16-bit. +- Deterministic golden images then stay stable because the dither is deterministic and the same on CPU and GPU lane. + +### 10. Damage tracking / partial redraw — **skip for now; design the hook** + +- Sources: [Flutter Impeller partial repaint, issue #124526](https://github.com/flutter/flutter/issues/124526) and + [PR #40959](https://github.com/flutter/engine/pull/40959); [Flutter damage-rect discussion](https://github.com/flutter/flutter/issues/33939) + (Metal has no buffer-age API; track which of the 2-3 drawables you got by texture identity); + [Slint's Metal surface keeping per-drawable ages](https://github.com/slint-ui/slint/blob/507b650e/internal/renderers/skia/metal_surface.rs); + [EGL_KHR_partial_update](https://registry.khronos.org/EGL/extensions/KHR/EGL_KHR_partial_update.txt). +- Findings: Metal drawables are not preserved, so partial repaint means keeping your own full-frame texture and blitting + the damaged area into the drawable (Impeller measured the blit at about 0.5 us on iPhone 13, only bypassing partial + repaint above 70 % damage; I would treat that figure as encode time rather than GPU time) *(estimate)*; drawable + ages can drift, so track per drawable. +- For Rune: the benefit is battery and thermals, not feel; frames that animate usually damage most of the window or a + big glass region anyway, and at rest Rune submits nothing. Verdict: skip. Keep a per-frame damage rect in the scene + (cheap: union of changed instance bounds) so a counter shows how much a frame *could* skip; revisit if Scrawl or the launcher + idle-animation power shows up in profiling. + +### 11. GPU-driven UI (indirect draws, bindless, compute culling) — **skip** + +- A UI frame is one pass with one or a few instanced draws and a few thousand instances (PLAN §4.3). CPU encode cost is + already tiny; indirect command buffers or compute culling pay when there are tens of thousands of distinct draws + *(general knowledge)*. The pieces worth taking are the cheap ones: bindless-style texture arrays or one atlas to avoid + rebinding, and instance buffers written once per change (idea 2). Compute culling is useful only for huge scrolling + lists, where CPU range queries over a sorted arena are simpler and exactly testable. + +### 12. HDR / EDR UI — **later** + +- *(From memory, not re-fetched.)* On Apple, `CAMetalLayer.wantsExtendedDynamicRangeContent` with an + `rgba16Float` extended-linear Display P3 layer gives headroom above 1.0, and the headroom is queried per screen + and changes with brightness. For Rune it means HDR video/photos and specular highlights could exceed SDF white. + The cost is double the bandwidth for the frame. Keep the pipeline format-generic and linear (already planned) so EDR is + a switch, not a rewrite; keep chrome in SDR. Verdict: later. + +## Steal list + +- `vello_cpu` as reference and headless renderer; Vello's blurred-rounded-rect code as a CPU oracle for the analytic + shadow. +- Levien `erf7` + effective-radius formula; Evan Wallace's product-of-erf boxes (CC0). +- Jimenez 13-tap/tent pyramid with Karis first level; fractional-level crossfade (new for Rune). +- Rive: 16 px blur cap then upscale; CDF lookup texture; "2 sigma = design blur amount" convention. +- Liquid-glass recipe: SDF height, normal-based refraction, per-channel dispersion, adaptive specular, vibrancy toward + mid grey, polynomial smooth union for merging shapes. +- Slug dynamic dilation and the MIT reference shaders; sqrt coverage for optical weight. +- Slint/Impeller per-drawable age tracking if partial repaint is ever added. +- TBDR load/store discipline and framebuffer fetch group opacity (Metal backend). + +## Avoid list + +- Pre-baked displacement maps for glass: closed-form SDF is exact and animatable. +- Gaussian convolution with large kernels or a separable pass at full resolution for backdrop. +- MSAA for UI primitives (analytic AA is cheaper and deterministic). +- Per-frame animated dither noise (breaks determinism and zero cost at rest). +- Compute-shader Vello as a dependency (moved to `research/`; needs compute, memory-hungry). +- Indirect/bindless engines for a UI-sized draw count. +- Assuming wgpu exposes framebuffer fetch. +- Treating Apple tile shaders as a blur tool (tiles cannot read neighbours). + +## Recommendation for Rune + +1. Adopt now: closed-form blurred rounded rect and inset shadow (idea 8), pyramid backdrop with fractional radius + (3), Oklab + deterministic dither (9), `vello_cpu` as the reference renderer (1). +2. Spike next, each with an exact counter and a differential test: vertex-shader springs (2), glass lens (4), Slug for + animated text (5), `vello_gpu` lane (1). +3. Later: feathering (needs a tessellator), framebuffer-fetch group opacity (needs raw Metal), HDR. +4. Skip: GPU-driven draws, partial present, MSAA. + +Rejected alternatives: compute Vello (compatibility, memory); SDF/MSDF text (corner rounding, atlas pops, Slug +supersedes it now the patent is gone); full-resolution separable Gaussian (cost, banding); wrapping SwiftUI/CA for +all glass (does not reach web, Windows, Linux). + +## Open questions + +- How does fractional pyramid crossfade look at the transition between a thin and a thick blur while the glass also + moves? Needs a scene in the deterministic harness plus the motion linter. +- Does the vertex-shader spring path survive retarget bursts (a drag) without per-frame instance rewrites? Measure + encode time at 1k animating nodes. +- Can wgpu on Metal skip the drawable's initial clear and use an `IOSurface`-backed texture presented via CALayer + contents (retained, damage-friendly)? Unverified. +- Apple's real glass is likely a different material model (not a plain lens); is "close enough" acceptable to Kit + for non-Apple platforms, with native underlays kept on Apple? +- Slug quadratic-only limit: do Rune's fonts (SF, CFF fonts) need an offline cubic-to-quadratic step, and what is the + fragment cost at 120 Hz on iPhone-class GPUs? +- Dither noise swim on scrolling content: local-coordinate dither vs screen-space; needs a visual test. diff --git a/app/vendor/rune/research/13-research-latency-startup.md b/app/vendor/rune/research/13-research-latency-startup.md new file mode 100644 index 0000000..f02a658 --- /dev/null +++ b/app/vendor/rune/research/13-research-latency-startup.md @@ -0,0 +1,123 @@ +# 13 – Startup and input-to-photon latency tricks for Rune + +Written from existing knowledge of the sources below; no web crawl this pass and nothing was built or benchmarked. Numbers are from the cited sources unless marked *(estimate)*. Verify each link before relying on it. + +## Summary + +- Instant first frame is mostly a **compositor-handoff problem**, not a rendering problem. The cheapest route is a `CALayer`/`IOSurface` (or Android splash) holding pre-rendered pixels that the OS shows before our code runs. The live tree then replaces it without a visible change. +- A pre-rendered frame is only invisible if the live first frame is **bit-identical**. Rune's deterministic headless renderer makes that testable, which GPUI/Flutter lack. This is the strongest unique advantage. +- Cold-start cost on macOS is dominated by dyld, page faults, and wgpu device/pipeline creation. Static linking, page-ordering and a pipeline cache attack all three. +- Input latency wins come from three places: **late latching** (sample input as late as possible), **predicted touches**, and **present-time control** (`CAMetalDisplayLink`, `presentAfterMinimumDuration`, DirectFlip, Wayland commit-timing). +- Perceptual thresholds justify the targets: touch-to-photon around 1 ms is perceptibly better for direct manipulation, and 100 ms is the floor for "instant" launch. +- Most of these ideas are impractical for humans to maintain (order files, generated pixel blobs per appearance and size, per-platform present loops). They are cheap if the build pipeline regenerates them. + +## Findings + +### 1. Static first-frame layer shown by the OS (iOS/macOS) — **adopt now** +- iOS: launch screen storyboard, plus the app-switcher snapshot taken by the system (`applicationDidEnterBackground` snapshot, state restoration). Apple's guidance is that the launch image must match the first screen ([HIG: Launching](https://developer.apple.com/design/human-interface-guidelines/launching)). +- Rune use: the build generates a launch storyboard-equivalent or, more flexibly, a `CAMetalLayer`/`CALayer` whose `contents` is an `IOSurface` or `CGImage` embedded in the binary (decoded lazily from a compressed blob). It is installed in `applicationDidFinishLaunching` before any wgpu work. The Metal layer later takes `contents` over, with the static layer removed in the same CA transaction as the first live present. +- On macOS, show a borderless window with that layer before the runtime initialises. Set window background to match, which avoids a white flash. +- Variants: per appearance (light/dark), per scale factor, per common window size. Generate by running the headless renderer in CI and storing as AVIF/zstd'd BC7 or raw 8888 for tiny sizes. A 1280×800 8888 frame is about 4 MB *(estimate)*, so prefer zstd/lz4. Decode cost is roughly 2–5 ms at that size *(estimate)*. +- Risk: dynamic content (user data, restored window sizes). Mitigate by snapshotting the **last session's** frame at quit (see 2) and falling back to the build-time frame. + +### 2. Last-session snapshot, as in iOS app-switcher snapshots — **adopt now** +- Same mechanism as 1 but the pixels come from the final frame of the previous run (written at quit/background, keyed by appearance + size + scale). This is what iOS does for backgrounded apps and what browsers do with bfcache/tab thumbnails. +- Rune use: store `IOSurface` bytes in the app cache dir. Shown first on relaunch. Falls back to the build-time frame on mismatch (version hash changed). +- Risk: showing stale data. Require a "snapshot-safe" flag per view, with sensitive views excluded. + +### 3. Chrome paint holding / View Transitions-style handoff — **adopt (principle)** +- [Chrome paint holding](https://developer.chrome.com/blog/paint-holding) keeps the previous page painted during same-origin navigation until the new page's first contentful paint, avoiding white flashes. The same principle applies: **never present until the live frame is ready; keep the old pixels up until then.** +- Rune use: handoff rule is "live swap occurs on the first live frame that passed the visual-equality gate or is ready". A transition (e.g. 80 ms cross-fade, springs-based) is used only when the golden diff is non-zero. +- Cost: low. It is a presentation policy in the shell. + +### 4. Bit-identical handoff gate via deterministic rendering — **adopt now (Rune-specific)** +- The plan's guarantee ("golden diff = 0") needs the live GPU frame to equal the pre-render. Different GPUs and drivers produce different antialiasing/gamma/subpixel text; a CPU-rendered snapshot will differ from a GPU render by a few LSBs. +- Options: (a) render the snapshot with the same wgpu path on a reference GPU, accepting a small tolerance (e.g. ≤ 1/255 per channel) and fading over ~1 frame; (b) have the **first live frame** be the snapshot itself (a textured quad) and then re-render live, fading differences below the perceptual threshold; (c) snapshot per GPU family at first run (see 8). +- Ship (a)+(c). Measure max delta per device class in CI. + +### 5. Android SplashScreen API + Baseline Profiles — **later (Android is last), but the idea transfers** +- [SplashScreen API](https://developer.android.com/develop/ui/views/launch/splash-screen) and [Baseline Profiles](https://developer.android.com/topic/performance/baselineprofiles/overview): Google reports around 30% faster cold start from AOT-compiling hot code paths (varies per app). +- Transfer: the profile-guided idea is generic. Collect page-fault and call-order traces from a headless launch, and feed them to binary ordering (item 7). The splash handoff is the same as items 1–3. + +### 6. Process snapshotting: V8/Node startup snapshots, Emacs portable dumper, CRIU/CRaC — **spike (partial) / skip (full)** +- [Node startup snapshot](https://nodejs.org/api/cli.html#--build-snapshot) and V8 snapshots deserialize the heap in milliseconds instead of re-running init. [Emacs pdumper](https://www.gnu.org/software/emacs/manual/html_node/elisp/Dumping.html) does the same for Lisp state: startup drops from seconds to tens of ms. [CRaC](https://openjdk.org/projects/crac/) and CRIU restore a process after warmup (JVM startup from seconds to roughly 40–100 ms in the published demos). +- Rune use, practical subset: do not snapshot the process (GPU contexts and window system handles cannot be restored). Instead **snapshot the pure-CPU state**: initial tree, resolved layout, shaped text runs (Parley glyph clusters + positions), glyph atlas contents, and font tables, serialized in a zero-copy format (`rkyv`-style, mmap'd). Loading is `mmap` plus pointer fix-up (or none with relative pointers), so no parse or shape work at startup. +- Cost: format versioning. Agents can regenerate on every build. Risk is stale caches; key by content hash of the binary + fonts. +- Full-process CRIU on macOS is not available; skip. + +### 7. Binary layout: order files, PGO, BOLT, static linking, dyld costs — **adopt now (cheap), measure first** +- macOS dyld: each dylib adds mapping, rebinding and initializer cost. dyld 4 plus [chained fixups](https://developer.apple.com/videos/play/wwdc2022/110362/) reduce it. A single statically linked Rust binary with system frameworks only is near the floor (about 10–15 ms for a hello-world process on Apple silicon *(estimate)*). +- Page-in dominates cold launch: first execution of code pulls pages from disk (each 16 KB page fault is about tens of µs warm and much more cold). Linker `-order_file` (ld64/lld) places startup-touched functions contiguously. Apple documents order files and [Xcode's "Generate Link Map"/order file profiling](https://developer.apple.com/documentation/xcode/improving-your-app-s-performance). Meta/Google report double-digit % launch improvement from function ordering ([LLVM Propeller](https://research.google/pubs/propeller-a-profile-guided-relinking-optimizer-for-warehouse-scale-applications/), [BOLT](https://github.com/llvm/llvm-project/tree/main/bolt); BOLT is ELF-focused, so use Propeller/order-files on Linux and `-order_file` on Mach-O). +- Rune use: CI runs the headless startup under a tracer (e.g. `-finstrument`-style or sampling plus page-fault logging), emits an order file, and release links with it. Also: `opt-level=3` + `lto="fat"` + `codegen-units=1`, `panic=abort`, no `std::fmt` heavy init in startup, avoid `lazy_static` fan-out; `mach_absolute_time` stamps at `main`, post-window, post-device, first-present. Hot/cold splitting for the startup path. +- Cost: low-medium; an agent can maintain the pipeline. Gain *(estimate)*: 10–30% of cold launch before first frame. + +### 8. Pipeline/shader prewarming and caches — **adopt now** +- Metal pipeline creation (MSL compile + PSO) costs 5–50 ms each cold; [Metal binary archives](https://developer.apple.com/documentation/metal/mtlbinaryarchive) store compiled GPU binaries to avoid it. WebGPU/wgpu: pipeline caches exist in recent wgpu (`PipelineCache` on Vulkan; use naga → MSL ahead of time for Metal). +- Rune use: precompile all shaders (naga → MSL → `metallib`) at build time and load the library from the bundle; build a binary archive per GPU family on first run (and ship one for common Apple GPU families in the bundle). Bound the number of pipelines (small fixed set of uber-shaders plus specialization constants) so prewarm is a handful of calls, which can be issued on a background thread while the static frame is already on screen. +- Also prewarm the glyph atlas for the first frame (from item 6's cached shaped runs). + +### 9. Lazy / parallel init: critical path = pixels — **adopt now** +- Order: (1) main thread: window + static layer (≤ 20 ms); (2) thread A: wgpu instance/adapter/device; (3) thread B: font load via mmap, Parley shaping from cache; (4) thread C: tree build from snapshot; then render. Everything else (a11y tree, IME, network, hot reload server) is after first present. +- Known costs to measure: `wgpu` adapter enumeration (~5–30 ms on macOS *(estimate)*), `CAMetalLayer.nextDrawable` first call, font fallback enumeration with CoreText (can be 50+ ms; avoid system font enumeration at startup). +- Flutter comparison: [Flutter AOT](https://docs.flutter.dev/resources/faq#what-technology-is-flutter-built-with) removes JIT cost, and [Impeller](https://docs.flutter.dev/perf/impeller) precompiles shaders because Skia's runtime shader compilation caused first-run jank. Rune's analogue is already planned (item 8). + +### 10. Late-latching input before present (VR technique) — **adopt now** +- VR runtimes sample head pose as late as possible, after CPU frame construction and just before GPU submit ([Oculus late latching](https://developer.oculus.com/blog/optimizing-vr-graphics-with-late-latching/), reported roughly one frame of latency saved on mobile). +- Rune use: the render thread (analytic springs, GPU-driven) reads the **latest pointer position/drag velocity** from a lock-free atomic slot immediately before encoding the final uniform buffer. Because springs are analytic and evaluated at a presentation timestamp, drag-following transforms can be written into a small "late" uniform region that is patched after the main command buffer is built (a ring-buffer slot written right before `commit`). Layout and text are not re-done; only transforms of the dragged node are late-latched. +- Cost: moderate; requires a "late uniform" concept for dragged transforms. Gain: up to 1 frame (8.3 ms at 120 Hz). + +### 11. Predicted touches and pointer events — **adopt (iOS first), spike model choice** +- iOS: [`UIEvent.predictedTouches(for:)`](https://developer.apple.com/documentation/uikit/uievent/1613844-predictedtouches), and coalesced touches for the full-rate samples. Apple's own documentation recommends drawing predicted points then discarding them next frame. Chrome: [`getPredictedEvents()`](https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/getPredictedEvents) and the Chromium input predictor (kalman, least squares, linear/quadratic variants, [Chromium input prediction design](https://chromium.googlesource.com/chromium/src/+/refs/heads/main/ui/base/prediction/)), which found Kalman filter preferable for scrolling and least-squares for drawing. +- Rune use: for direct-manipulation gestures, use `coalescedTouches` at 240 Hz for the real sample path (smooth velocity for spring handoff), and predict ~1 frame ahead using a constant-velocity or damped-acceleration Kalman model, rendering the predicted position but never committing it to state. On release, hand over the **measured** (not predicted) velocity to the spring. On macOS trackpad/mouse, use prediction only for drag. +- Risk: overshoot artifacts at direction changes; clamp prediction horizon by confidence (cap at 1 vs. 2 frames) and check with recorded real traces replayed deterministically (a good agent-verification fit: record input traces, replay headless, measure prediction error). + +### 12. Present timing: CAMetalDisplayLink, minimum-duration, DirectFlip, Wayland — **adopt on Apple, spike elsewhere** +- Apple: [`CAMetalDisplayLink`](https://developer.apple.com/documentation/quartzcore/cametaldisplaylink) (iOS 17 / macOS 14) fires with a target present timestamp and a deadline for drawable submission, so a render thread can wake just-in-time rather than at vsync after a fixed offset. Use `drawable.present(afterMinimumDuration:)`/`present(at:)` to hold frame cadence, and `maximumDrawableCount = 2` for lowest latency on macOS (CAMetalLayer property). Set `displaySyncEnabled`, and `wantsExtendedDynamicRangeContent` off unless needed. Use `presentedTime` / `MTLDrawable.addPresentedHandler` for measured latency. +- Windows: DXGI flip model with [independent flip / DirectFlip](https://devblogs.microsoft.com/directx/dxgi-flip-model/) skips DWM composition when the swap chain covers the window (requires `DXGI_SWAP_EFFECT_FLIP_DISCARD`, a waitable object via `SetMaximumFrameLatency(1)` and `GetFrameLatencyWaitableObject`), cutting about a frame of latency in published tests. +- Linux/Wayland: [`wp_presentation`](https://wayland.app/protocols/presentation-time) feedback gives real present timestamps; [`wp_commit_timing_v1`](https://wayland.app/protocols/commit-timing-v1) (staging, 2024–25) lets clients target a presentation time; [`wp_fifo_v1`](https://wayland.app/protocols/fifo-v1) gives proper vsync-paced commits. Use for pacing when supported. +- Rune use: a `PresentClock` trait per shell that exposes `next_present_deadline()` and `actual_present_time(frame)`. The render thread schedules: input latch → spring eval at *target present time* → encode → submit with slack about 1–2 ms before deadline. This unifies with the analytic springs (evaluated at the exact predicted display time, which removes judder). +- Risk: per-platform code and wgpu limits (wgpu hides presentation timing; may need to bypass wgpu surface presentation on Apple via `CAMetalLayer` directly, which the plan seems to allow). Verify `wgpu` exposes a frame-time hint, else raw `CAMetalLayer`. + +### 13. Frame pacing research — **adopt (principles)** +- [Android Frame Pacing / Swappy](https://developer.android.com/games/sdk/frame-pacing) and Apple's own docs agree: pace on the display timeline, not on a timer; drop to a stable lower rate instead of oscillating; and measure present-to-present deltas, not frame times. Related research on input-to-photon (e.g., [Nvidia Reflex](https://www.nvidia.com/en-us/geforce/technologies/reflex/) cuts system latency by pacing CPU submission so the queue stays empty) is the same just-in-time idea as item 12. +- Rune use: keep render queue depth at 1; the render thread **sleeps until deadline minus a measured encode+GPU time budget (EWMA with a p99 margin)**, then latches. Trace it per frame in the frame traces the plan already wants. + +### 14. Perceptual latency thresholds — **use as targets** +- Ng, Lepinski, Wigdor, Sanders, Dietz, [*Designing for Low-Latency Direct-Touch Input* (UIST 2012)](https://dl.acm.org/doi/10.1145/2380116.2380174): people notice improvement down to about 1 ms in direct touch dragging; 10 ms is the commonly noticed "feels connected" edge; and the follow-up [*How Fast is Fast Enough?* (CHI 2013, Jota et al.)](https://dl.acm.org/doi/10.1145/2470654.2481317) found dragging at 1 ms vs 10 ms vs 50 ms are differentiable. Microsoft Research's demo of 1 ms touch is the source of the "1 ms touch" claim. +- Rune use: budget for drag-follow: iOS hardware floor is about 2 frames at 120 Hz (≈16 ms) with prediction offsetting about 1 frame; set CI gates on measured touch-to-present (via high-speed camera in the lab later; via `presentedTime` minus event timestamp in software now). Launch: ≤ 100 ms is "instant"; the plan's 50 ms is well inside it. + +### 15. Immediate draw on input for small updates — **spike** +- Draw feedback (press state, caret, drag handle) directly in the render thread without waiting for the main/UI thread to run layout/tree diff: input thread → render thread message → patch a retained "overlay" layer. This is what Core Animation's render server gives SwiftUI for free (`CAAnimation` runs out of process). +- Rune use: the render thread owns an "interaction layer" of transform/opacity/color overrides keyed by node id, updated by input events directly with analytic springs, so a press response never waits on the app thread. The app tree later confirms. Risk: two sources of truth; mitigate by making overrides explicit, ephemeral and traced. + +## Steal +- iOS snapshot + paint-holding handoff policy (1–3). +- Impeller's "no runtime shader compilation" rule (8). +- Late latching and Reflex-style just-in-time submission (10, 13). +- Chromium's predictor families and its habit of testing predictors on recorded traces (11). +- Emacs/Node idea of loading precomputed state instead of computing it, restricted to pure data (6). +- Order files / Propeller for page-in (7). + +## Avoid +- Full process checkpointing (CRIU/CRaC) — not portable to macOS/iOS and GPU state does not survive. +- Showing a stale snapshot for user-private or fast-changing views without a flag. +- Predicting beyond ~1 frame or committing predicted state to model data. +- Relying on BOLT for Mach-O (ELF-centric); use `-order_file`. +- Per-frame heap allocation or lock contention in the late-latch path. + +## Recommendation for Rune (ranked) +1. **Static pixel layer + bit-identical handoff gate** (items 1–4). Make it the first milestone shell feature; CI asserts max-delta and launch timeline. +2. **Precompiled shaders + Metal binary archive + parallel init critical path** (8, 9). Biggest controllable chunk of the 50 ms budget. +3. **Frame clock built on `CAMetalDisplayLink` with just-in-time latch and analytic springs evaluated at the target present time** (12, 13, 10). +4. **Coalesced+predicted touch pipeline with recorded-trace replay tests** (11). +5. **Order-file/PGO startup layout pipeline and cached shaped-text/atlas snapshot** (6, 7). + +Rejected: process snapshot (6, full); runtime shader JIT; fixed-offset vsync timers. + +## Open questions +- Does wgpu expose enough presentation control on Metal (target timestamps, drawable count, `presentedTime`), or must the Apple shell own `CAMetalLayer` directly? +- Achievable max pixel delta between the CPU/headless snapshot and live GPU frame on each Apple GPU family; is tolerance + 1-frame fade enough to be invisible? +- Real wgpu device init and first-`nextDrawable` costs on M-series cold boot (measure on a reserved Mac, not a developer's desk display). +- Size and decode cost of embedded snapshots across appearance × scale × window-size variants; do we store raw, lz4, or BC7? +- iOS: can a launch-screen replacement be a CALayer image set before `didFinishLaunching`, or must it be a storyboard/`UILaunchScreen` image? (The latter requires a static asset, so the build must emit a PNG into the asset catalog.) +- Which predictor (Kalman vs least-squares) performs best on Rune's own recorded drag traces? diff --git a/app/vendor/rune/research/14-research-determinism-verification.md b/app/vendor/rune/research/14-research-determinism-verification.md new file mode 100644 index 0000000..cdfc31b --- /dev/null +++ b/app/vendor/rune/research/14-research-determinism-verification.md @@ -0,0 +1,255 @@ +# 14. Determinism, verification and testing: cutting-edge ideas for Rune + +Scope: tenet 7 (fast path + reference path, exact counters, instant checks) and §6b (same pixels everywhere, +bug reports are replays, every pixel traces to code). Written 2026-10-21. + +**Provenance note.** Web search was down while writing. Items marked **[read]** I verified in source or docs this +session (vello checkout, WGSL spec, gungraun/FLIP/Kani/shuttle READMEs). Items marked **[recalled]** are from +memory of papers and tools and need a link check before anyone relies on a number. + +## Summary + +- The right architecture is already proven upstream: **Vello ships a `cpu_gpu_differential` cargo-fuzz target** that + generates bounded structured scenes (shapes, strokes, gradients, clips, layers), renders with `vello_cpu` and + `vello_gpu`, and compares RGBA8 with a per-channel tolerance (default 2, ≤4 outlier pixels) + [read: `vello/fuzz/README.md`]. Rune's "reference renderer vs fast renderer" is this, with Rune's own scene model. +- **Bit-exact across GPUs is not available from WGSL/wgpu**: the spec lets an implementation reassociate, fuse + (FMA), and use lower accuracy [read: WGSL §15.7.4–5]. So "same pixels everywhere" must be a *CPU-reference* lane + (integer/fixed-point, exact), and GPU lanes are tolerance lanes. Don't chase GPU bit-exactness; chase a *bounded + error with a proven budget*. +- A **u8/fixed-point CPU pipeline is the determinism anchor.** `vello_cpu` has a `u8_pipeline` (integer math) and an + optional `f32_pipeline`, plus a `libm` feature so float functions don't depend on the platform libc [read: + `vello_cpu/src/lib.rs`]. Integer math + `libm` + no FMA contraction gives identical bytes on x86 and arm64. +- **Perf gates by instruction count** (gungraun / iai-callgrind, CodSpeed) are exact and noise-free in virtualised CI + [read: gungraun README], but Valgrind does not run on macOS arm64; run those on Linux (a Linux + runner) and use Apple counters (`kpc`/Instruments) only for reserved-hardware confirmation. +- **Record/replay at the app level beats `rr`.** Rune owns the clock, input and randomness, so a deterministic + event-log replay (KBs) gives most of rr/Pernosco's value on macOS/iOS, where rr does not run [read: rr README lists + Linux only; Apple Silicon unsupported]. +- **Concurrency**: the render thread/main thread handoff is small enough for **shuttle** (randomized, replayable + schedules) and **loom** (exhaustive, tiny models) [read: shuttle README]. Cheap, high value. +- **Verification**: Kani (bit-precise model checking, strong for `unsafe` and overflow in fast-path kernels) is the + practical formal tool; Verus only for 1–2 core invariants. Agents are good at writing Kani harnesses and + specifications, which was the bottleneck for humans. + +## Findings + +### 1. Differential fuzzing of fast path vs reference (adopt now) +- Source: Vello's [`fuzz/` target](https://github.com/linebender/vello/tree/main/fuzz) [read]; cargo-fuzz + + `arbitrary` for structured inputs; Vello also keeps `fuzz_regression.rs` so every crash becomes a snapshot test + (tolerances recorded with the case) [read]. +- Achieves: finds backend divergences automatically; the README notes known-different features (image quality + Medium/High) are excluded so they don't drown new findings. That is the workflow lesson: **grow the generator + feature by feature with a ratchet**. +- Rune: one `Scene` generator (`arbitrary`) feeding *all* subsystems: layout (fast SoA Taffy-like vs a naive + recursive reference), springs (analytic closed form vs fine-step RK4 integration at 1e-6 dt), text (cached shaping + vs fresh), renderer (GPU vs CPU reference). Tolerance modelled as (max channel diff, max outlier count), exactly + Vello's. Every fuzz crash is auto-minimised (`tmin`) and committed as a named regression scene. +- Cost: low; generator maintenance. Risk: tolerance creep. Mitigation: tolerance is per-primitive and recorded; + CPU fast path vs CPU reference is **zero tolerance**. +- Verdict: **adopt now.** Spike S: copy Vello's harness shape in the first renderer milestone. + +### 2. A zero-tolerance exact lane built on integer/fixed-point CPU rendering (adopt now, scoped) +- Source: `vello_cpu` u8 pipeline + `libm` feature [read]; `tiny-skia` (Skia subset, SIMD with scalar fallbacks) + [read README]; Skia's own GM tests live on a CPU "raster" backend as the baseline for GPU backends (Skia Gold + compares across OS/arch/backend dimensions, >500k images per commit) [read: + [docs](https://docs.skia.org/docs/dev/testing/skiagold/)]. +- Achieves: bytes identical on any machine, so goldens are hashes, not images with fuzz. +- Rune: canonical goldens come from the CPU reference renderer. Rules for exactness: no FMA contraction (`-C + llvm-args=-fp-contract=off` or explicit `mul_add` ban via clippy `disallowed_methods`), no float `sum()` with + platform-dependent order, `libm` for transcendental functions, fixed iteration order, no HashMap iteration in + render paths, pinned font bytes. Add a CI job that runs the *same* binary tests on x86-64 Linux and arm64 macOS and + compares hashes; a mismatch is a hard failure that names the first differing scene. +- Cost: the CPU path must implement every primitive (UberQuad, glyph sprites, gradients, blur). That is already in + the plan (§4.3 differential renderer). Risk: reference renderer drifts from "what the GPU should do"; the + differential fuzz in item 1 is the leash. +- Verdict: **adopt now**; this is the plan's "canonical lane". + +### 3. GPU float divergence: bound it, don't forbid it (adopt now as policy) +- Source: WGSL spec §15.7.4/5: implementations may reassociate, fuse, and be more or less accurate than the + reference formula [read]; NVIDIA FLIP's precision note lists FMA, sqrt precision, and loop order as the reasons + five implementations of one metric never match bit-for-bit [read: + [precision.md](https://github.com/NVlabs/flip/blob/main/misc/precision.md)]. +- Rune: write shaders in a **conservative numeric style**: premultiplied u8 / unorm in, fixed-point coverage + (analytic AA from integer edge functions where possible, e.g. 8.8 subpixel positions snapped on CPU), quantize + positions to 1/64 px on CPU before upload (already in §6b), keep the GPU doing only blend/sample of values the CPU + decided. The more decisions are made in integers before the GPU, the smaller the cross-vendor surface. Then measure + the residual: render the scene corpus on M-series, an NVIDIA box, and software Vulkan (lavapipe) via wgpu, record + max per-channel error per primitive, and make that table the tolerance budget. +- Metal on Apple is one vendor family, so for macOS/iOS exact GPU hashes on a pinned device are plausible; treat + as a bonus lane, not the contract. +- Verdict: **adopt now** (policy + a one-off measurement spike, 1 day). + +### 4. Perceptual diff: FLIP plus a "does it matter" gate (spike) +- Source: [NVIDIA FLIP](https://github.com/NVlabs/flip) (LDR/HDR-FLIP, v1.7, in Ray Tracing Gems II; Rust port exists + in the wild [recalled]); Skia Gold's triage model (positive/negative digests, baselines outside git) [read]. +- Achieves: error maps that weight differences by human sensitivity; pooled score per image. +- Rune: for the *tolerance lanes* only (GPU vs CPU reference, cross-vendor), fail on `max(FLIP) > t` **or** a + count of outlier pixels, whichever is stricter; exact lane stays hash-equal. Output FLIP heatmaps next to + expected/actual/diff so an agent (or Kit) sees where. Don't use SSIM as the gate (blind to smooth gradient banding, + which Rune cares about: dithering). +- Gold-style: store baselines as content hashes outside git (or in a `goldens/` manifest of hashes + a blob store), + triage by "blame" commit. Overkill for a solo repo now; useful once multi-platform baselines multiply. +- Verdict: **spike** FLIP on the tolerance lane; **later** a Gold-like service. + +### 5. Metamorphic testing for layout and rendering (adopt now; cheap, finds real bugs) +- Source: metamorphic testing literature applied to GUIs/renderers (e.g. graphics-shader compiler testing with + semantics-preserving transforms in GraphicsFuzz/glsl-reduce, Donaldson et al. [recalled]; browser-layout + differential/metamorphic work such as "Hidden costs of browser layout" style studies [recalled]). Treat as + technique, not a specific citation. +- Relations Rune can assert without any oracle: + 1. **Translation invariance**: shift a subtree by integer px → output identical, shifted (exact on CPU lane). + 2. **Wrap invariance**: wrapping a node in a zero-style container or a no-op opacity(1) layer does not change + pixels (catches layer/clip bugs; should be bit-equal). + 3. **Order independence** of non-overlapping siblings. + 4. **Resize monotonicity**: widening a container never increases text line count; height never shrinks when text + scale grows (catches layout/shaping cache bugs). + 5. **Scale equivariance**: 2x scale-factor render, downsampled, is within tolerance of 1x render for vector content. + 6. **Retained vs immediate**: building the tree fresh vs mutating from a prior state gives identical output + (catches stale-cache bugs: the classic retained-UI bug class). This is the highest-value relation. + 7. **Time-split invariance for springs**: stepping 1×16.6 ms == 2×8.3 ms == 1×(seek 16.6 ms) within 1e-9 (analytic + springs make this *exact up to rounding*; a rare property few frameworks can claim). + 8. **Interrupt composition**: retarget at t, then evaluate: position and velocity continuous at t. +- Cost: tiny; each is ~30 lines over the scene generator. Verdict: **adopt now.** + +### 6. Property-based and model-based UI testing with stateful shrinking (adopt now) +- Source: proptest state-machine testing / `proptest-state-machine` and quickcheck-style model tests; Hypothesis + stateful testing [recalled]; Elm/Redux reducers as the model [recalled]. +- Rune: model = a trivial `Vec<Item>` / form state; SUT = the real tree + reconciler + keyed diff + enter/exit. + Generated operations = insert/remove/move/reorder, input events with timestamps, resize, time advance. Properties: + identity preserved across moves (same node id → same spring state), no node unmounted at opacity > 0, a11y tree + equals view tree, scroll offset clamped, no panics. Shrinking yields a *minimal event script* that is directly a + replay file (item 8). Agents love this: the failing case is a 6-line JSON. +- Verdict: **adopt now.** Pair with the same generator as item 1. + +### 7. GUI fuzzing and agentic exploration (later / spike) +- Source: Android GUI testing research (Monkey, Sapienz, Stoat, APE) [recalled]; LLM-driven GUI exploration papers + 2023–2025 (e.g. GPTDroid-style, VisionDroid-style) [recalled; unverified numbers]; Skia's fuzzing doc [link in + Skia docs sidebar, not read]. +- Rune advantage: no need for pixel/OCR-based exploration. The inspector exposes the semantic tree (roles, rects, + actions), so **coverage-guided event fuzzing over the a11y tree** is straightforward: choose among actionable + nodes, inject scripted input, coverage = distinct (node-role, state-hash) pairs plus code coverage (`-C + instrument-coverage`). Run the fuzzer with a fake clock so it's thousands of interactions per second headless. +- Oracles: no panic, no layout or motion linter finding, no hitch beyond budget in the counter model, tree + invariants. The internal motion linter as a *fuzz oracle* is a genuine differentiator (finds pops under random interrupt + sequences). +- Verdict: **spike** after the scene/inspector exist; the LLM-guided variant is **later**. + +### 8. Record/replay: app-level event log, with rr only as a Linux escape hatch (adopt now) +- Source: [rr](https://github.com/rr-debugger/rr) (Linux; README lists kernel ≥4.7, and some AArch64 parts) [read], + [Pernosco](https://pernos.co) (omniscient debugging on rr traces) [recalled], Replay.io (browser/Node + record-replay with app-level instrumentation) [recalled], Elm/Redux time-travel [recalled]. +- Why not rr: it records syscalls and hardware events on Linux; Metal/CoreAnimation/AppKit are out of reach on macOS. +- Rune: inputs + clock + RNG + window metrics + font/asset manifest + environment hash are the *only* nondeterminism + inputs (tenet: fixed clock, seeded randomness). Log them as a compact binary/JSONL stream; replay through the + headless CPU renderer to identical pixels (the §6b "bug reports are replays" guarantee). Add: + - **Periodic keyframes**: snapshot of state (arena dump) every N frames so replay can *seek* in O(N frames) and + support reverse-step by replaying from the previous keyframe (cheap time-travel debugging, the Elm trick). + - **State-hash per frame** in the log; on replay, first mismatching frame hash localises nondeterminism instantly + (this is how deterministic game engines and lockstep netcode find desyncs [recalled]). + - A `--chaos` mode that perturbs scheduling (shuttle, item 10) and asserts frame hashes unchanged. +- On Linux CI only, run failing replays under `rr record` and attach the trace for Pernosco if a crash is native. +- Verdict: **adopt now** (log + state-hash + keyframes); rr/Pernosco **skip** for macOS, **later** for Linux crashes. + +### 9. Exact performance counters in CI (adopt now, with a platform split) +- Source: [gungraun](https://github.com/gungraun/gungraun) (successor of iai-callgrind; instruction counts, + estimated cycles, DHAT, one-shot runs, usable in noisy virtualised CI; v0.20 on crates.io) [read]; + [iai](https://github.com/bheisler/iai) the cachegrind original [read]; CodSpeed (CPU-simulation instrument + based on Valgrind, plus walltime on dedicated macro runners) and Bencher (tracks metrics incl. iai instruction + counts with statistical thresholds) [recalled; docs pages 404'd on fetch, verify]. +- Rune: bench the *pure* functions (layout of a fixed scene, spring step for N springs, glyph run encode, CPU + rasterise a tile) under gungraun on Linux: instruction count, L1/LL misses, and **DHAT heap allocations** (this is + the "zero allocation per frame" gate, stronger than a counting allocator because it also reports bytes and sites). + Gate: >0.5% instruction regression fails the PR; the failing report includes callgrind diff by function so an + agent can fix it. Wall-clock on reserved hardware only as confirmation, because instruction count ≠ time on Apple + silicon. +- Caveat: Valgrind is not supported on macOS arm64, and instruction counts on x86-64 Linux don't predict Apple + cache/NEON behaviour. Use for regression detection and algorithmic cost, not absolute 8.33 ms claims. For the + latter: model budgets in counted units (instances, glyphs, nodes) which are platform independent (already planned). +- Verdict: **adopt now** (gungraun; pick CodSpeed/Bencher later only if a hosted trend UI is wanted). + +### 10. Deterministic concurrency testing of the render-thread handoff (adopt now) +- Source: [shuttle](https://github.com/awslabs/shuttle) (randomized scheduler incl. PCT with probabilistic + guarantees; replayable failing schedules; wrappers for tokio/rand) [read]; [loom](https://github.com/tokio-rs/loom) + (exhaustive C11 memory-model exploration; small models only) [recalled]; Antithesis-style whole-system + deterministic simulation [recalled, commercial, skip]. +- Rune: the main↔render thread protocol (triple-buffered target/command queue, spring track updates, input timestamp + handoff, frame-in-flight counting) should be a small isolated module whose sync primitives go through a `rune_sync` + facade (`std::sync` in prod, `shuttle::sync`/`loom::sync` under `cfg`). Test: random schedules x thousands; the + invariant is "presented frame sequence is a function of (input log, clock) only", which is the §6b replay + guarantee under concurrency. Failing schedule is a seed that reproduces exactly. +- Cost: facade discipline (agents handle that well). Risk: loom state explosion; keep models to 2–3 threads. +- Verdict: **adopt now** for the handoff; the rest of the app is single-threaded by design. + +### 11. Practical formal methods: Kani first, Miri always, Verus selectively (spike) +- Source: [Kani](https://github.com/model-checking/kani) (bit-precise model checker, UB detection for `unsafe`, + function contracts, Linux/macOS) [read]; AWS/Rust Foundation [std-library verification + effort](https://github.com/model-checking/verify-rust-std) with Kani, Verus-adjacent tools, VeriFast, Flux, etc. + [read]; [Verus](https://github.com/verus-lang/verus) (SMT-checked Rust subset; Atmosphere/other large proofs) + [read README; case studies recalled]; Miri for aliasing/UB in `unsafe` SIMD-adjacent code [recalled]. +- Rune fits: small `unsafe` kernels (SoA arena index math, SIMD tile blend, arena free-list, fixed-point rounding) + are exactly where Kani proves "no overflow/OOB for all inputs" in seconds and where an agent can write both the + harness and the `#[kani::proof]`. Examples worth proving: `blend_u8(a,b)` equals the reference + `(a*b+127)/255`-style formula for all 2^16 inputs (exhaustive, can also just be a brute-force test: **prefer + brute-force for 8/16-bit domains**); arena generation counters never alias; 26.6 fixed-point snap is idempotent. +- Verus: only if a core invariant resists testing (e.g. keyed-diff reconciliation preserves identity). Heavy; mark + **later**. +- Miri: run the whole unit suite under Miri nightly on the non-GPU crates; any `unsafe` merged without Miri green is + rejected. Verdict: Miri **adopt now**, Kani **spike** (1 kernel), Verus **later**. + +### 12. Pixel provenance / trace-to-source (adopt now, half of it is already in the plan) +- Source: general ideas: Chrome DevTools paint-flashing/"layer reasons", Flutter DevTools "creation location" of + widgets (`debugCreator`/inspector `creationLocation`) [recalled], React `__source`. +- Rune: stamp each node with `file:line` at construction (`#[track_caller]` is free); renderer emits a compact + **ID buffer** (u32 node id per pixel/tile) *only in debug/CI snapshot mode*, a second attachment on the CPU + reference renderer (zero cost on the fast path). With it, `mk inspect --at x,y` returns the topmost node, the whole + stack of contributors at that pixel (blend order), their `file:line`, and spring tokens. Diff reports then + *blame by node*: "37 px differ, all belong to node #412 `pill.rs:88`, whose shadow radius changed from 12.0 → 12.5". + That turns a screenshot diff into a semantic diff that an agent can act on without looking. +- Extension: **semantic diff first**: diff the (tree, layout rects, style hashes, spring states) before pixels; + report "layout unchanged, only shadow colour changed" so pure-visual changes are separated from layout changes. +- Cost: modest on the CPU renderer; risk none to production. Verdict: **adopt now** (CPU ID buffer + semantic diff). + +### 13. Frame-hash goldens with auto-explanation (adopt now) +- Rune: golden = BLAKE3 of the CPU frame plus the stored PNG only on failure (artifacts as expected/actual/diff/ + FLIP/ID-blame). `mk snap --bless` rewrites hashes; blessing prints which scenes changed and their semantic diff so + an agent reviewing a PR sees intent. Per-scene sequence goldens (hash at t = 0, 0.1, … s) cover motion + deterministically, because the clock is fixed; this *is* motion regression testing with no video. +- Verdict: **adopt now.** + +## Steal +- Vello's `cpu_gpu_differential` fuzz target, tolerance model and regression-snapshot loop. +- `vello_cpu`'s dual u8/f32 pipeline idea (fast integer vs accurate float) and `libm` feature for portable floats. +- gungraun's one-shot instruction/DHAT gating; callgrind per-function diffs in the failure report. +- shuttle seeds as replayable schedules; Elm-style keyframed time travel; lockstep-game state-hash desync detection. +- Skia Gold's baselines-by-hash with blame-based triage (later). +- FLIP for tolerance lanes, with its explicit precision caveats. + +## Avoid +- Promising GPU bit-exactness across vendors (WGSL forbids relying on it). +- SSIM/PSNR as the sole gate. Wall-clock benchmarks on shared CI. Full-system rr/Pernosco on macOS. +- Verus across the codebase; proof effort exceeds benefit outside tiny kernels. +- Fuzzing with tolerances so loose that they hide regressions; keep exact lanes exact, record every tolerance. + +## Recommendation for Rune +1. Build CPU reference renderer as integer/`libm`, zero-FMA, hash-golden canonical lane; GPU lanes use measured, + per-primitive tolerance budgets (items 2, 3). +2. One structured `Scene` generator drives differential fuzz, metamorphic relations, and stateful model tests (1, 5, + 6). Failures auto-minimise to replay scripts. +3. App-level replay with state hashes and keyframes (8); gungraun gates on Linux (9); shuttle for the handoff (10); + Miri on every PR (11). +4. CPU ID-buffer and semantic diff for blame (12). FLIP and Kani as spikes. + +Rejected: rr/Pernosco as the main replay story (platform), CodSpeed/Bencher as required infra (nice-to-have), +Verus broadly, GPU-exact hashing as the contract, Gold as a service (premature). + +## Open questions +- Can arm64 macOS and x86 Linux give identical CPU-lane bytes with auto-vectorised code? Needs an actual two-machine + hash test (the CPU lane may need explicitly-scalar or fixed-width `fearless_simd`-style kernels for exactness). +- Is the Apple GPU deterministic enough run-to-run (same device, same driver) for exact hashes as a bonus lane? + Likely yes; unmeasured. +- Does text shaping (Parley/HarfRust) output remain bit-stable across versions and platforms with pinned fonts? + Pin versions and add a shaping-hash lane. +- Instruction counts on Linux x86-64 vs Apple arm64: how well do they correlate for Rune's kernels? Calibrate once on + a Mac with `kpc` counters. +- Exact figures for CodSpeed/Bencher/Replay.io/GUI-fuzzing papers need verification when search is back. diff --git a/app/vendor/rune/research/15-research-motion-perception.md b/app/vendor/rune/research/15-research-motion-perception.md new file mode 100644 index 0000000..63d7906 --- /dev/null +++ b/app/vendor/rune/research/15-research-motion-perception.md @@ -0,0 +1,231 @@ +# 15 · Motion, perception and feel: research and tricks Rune can exploit + +Scope: smoothness/judder perception, frame-time variance, motion blur at high refresh, direct-manipulation latency, +spring vs easing, interruptibility, Apple/Google fluid-interface research, crisp moving text, layout animation, velocity +estimation, scroll physics, and automatic smoothness metrics. Written 2026-10-21 for Rune ([PLAN §4.9, tenet 7, §6b](../PLAN.md)). + +**Source quality legend.** *[read]* = I opened the source/paper page in this session. *[recall]* = from memory of the +talk/paper/source; cite-check before it goes into a spec. Numbers I could not verify are marked *(est.)*. +Rune's differentiators used throughout: analytic springs (exact x and v at any time), a render thread that owns every +presented value, a deterministic clock, and agents who can maintain fast-path + reference-path pairs. + +## Summary + +1. **Sample at the presentation time, not at "now".** Frame-time *variance* matters more than average fps, and with + analytic tracks the cure is free: evaluate every track at the display's *target presentation timestamp*. A late + frame then shows the right place instead of a velocity hiccup. (NVIDIA/UCSB: 12 ms of frame-time variation + measurably degrades perceived smoothness, 4 ms barely does. [read]) +2. **Smoothness metric = pixel error, not frame count.** Judder visibility is `velocity × timing error` in px/arcmin. + Rune can compute, per frame and per node, `|rendered_pos − ideal_pos(t_present)|` exactly, plus Apple's hitch-time + ratio. No other toolkit can score smoothness this precisely, because none owns both the ideal and the presented value. +3. **Late-latch input on the render thread.** Direct-manipulation latency down to ~1–10 ms is perceptible in dragging + (Ng/Jota, Microsoft Research [recall]). Sample the pointer at the last moment before encode, resample to the + presentation time like Android does, and extrapolate ≤ ~8 ms. +4. **Velocity: ship Android's impulse estimator** plus an LSQ2 reference, with a 100 ms horizon and a 40 ms "stopped" + rule. Differential-test both against a recorded gesture corpus, and tune the choice by post-release prediction error. +5. **Text under motion is a policy, not a flag**: vertical snap + ¼-px horizontal phases in grayscale while moving, + exact analytic settle time, then a sub-¼-px rest snap. Verify with a phase-sweep harness an agent can run. +6. **Layout animation by rect-space FLIP on presented rects**, never scale correction (Rune's edge tracks already avoid + it), with *glyph/word-level FLIP* for text reflow as a distinctive spike. +7. **Effects springs ≠ spatial springs** (Material 3 Expressive): opacity/colour/blur channels never overshoot. +8. **Scroll/fling are analytic**: `x(t)` closed form (iOS 0.998/ms, Android spline) so they are frame-rate independent + and retargetable; project the landing point and hand velocity to a spring for snapping. +9. **Synthetic motion blur: skip at 120 Hz**; keep a velocity-gated spike for flings, because Rune knows `v` exactly. +10. **Perception ground truth is thin for springs vs easing**; use Kit's blind A/B chooser (Bradley–Terry) as the oracle + and build it into `mk tune`. + +--- + +## Findings + +### 1. Present-time sampling and frame pacing — **adopt now** +- **Source:** NVIDIA Research, Klein/Spjut/Boudaoud/Kim, "Variable Frame Timing Affects Perception of Smoothness in + First-Person Gaming," IEEE CoG 2024 ([page](https://research.nvidia.com/publication/2024-08_variable-frame-timing-affects-perception-smoothness-first-person-gaming), + [arXiv](https://arxiv.org/abs/2306.01691)) [read]. Android FrameTimeline classifies jank by *predicted vs actual + present time*, and flags BufferStuffing as a latency state even when cadence is smooth ([Perfetto](https://perfetto.dev/docs/data-sources/frametimeline)) [read]. +- **What it shows:** frame-time variation of ±4–12 ms around 30–240 Hz; 12 ms degrades perceived smoothness, 4 ms has a + diminished effect. Average fps alone doesn't predict it. A 120 Hz period is 8.33 ms, so *one* skipped vsync is already + in the "visibly bad" regime. Practical corollary: at 120 Hz a frame that misses by half a period matters, at 60 Hz + the same absolute miss is a smaller fraction. +- **Rune use:** on Apple use `CAMetalDisplayLink`/`CADisplayLink` `targetTimestamp` / `targetPresentationTimestamp` + as the sample time `t_present` for all tracks; on other platforms use the compositor's predicted present time + (Android Choreographer vsync id/`AChoreographer` frame time, Wayland presentation-time, DXGI `GetFrameStatistics`, + WebGPU: `rAF` timestamp + one period). Never `Instant::now()`. A hitch becomes a one-frame *temporal* gap with + correct geometry instead of a speed discontinuity. Use `wgpu` `desired_maximum_frame_latency = 1` (2 = stuffing). +- **Cost/risk:** low; one-time plumbing per platform. Risk: platforms that don't expose a prediction (web). Fallback: previous frame timestamp + period. +- **Verdict:** adopt now. It is the single highest-leverage item: all other metrics presuppose it. + +### 2. Metrics a frame trace can compute that track perceived smoothness — **adopt now** +Rune records, per frame: `t_target`, `t_actual_present` (where the OS reports it), `t_sample`, and per animated node +`x_rendered`, `x_ideal(t_actual)` (exact from the track), `v`. From that (all computable headlessly with the fake clock +injecting synthetic delays): + +| Metric | Definition | Why it correlates | +|---|---|---| +| **Hitch time ratio** | Σ(excess present-interval over expected) ÷ animation duration, ms/s | Apple's own: WWDC20 "Eliminate animation hitches with XCTest" and WWDC21 "Detect and diagnose hitches" use thresholds ≈ < 5 ms/s good, 5–10 warn, > 10 critical [recall]. Use as the CI gate shape. | +| **Cadence deviation** | σ and max of `present_interval − period`, in periods | NVIDIA result above: variance, not mean. | +| **Position error px** | `|x_rendered − x_ideal(t_actual)|` per node per frame; report p99 and max | Judder visibility ≈ `v · Δt` in px; threshold in arcmin using the device's ppi and viewing distance (iPhone ≈ 460 ppi @ 35 cm ⇒ 1 px ≈ 0.55 arcmin, below acuity, but motion hyperacuity is finer). | +| **Visual jerk** | 3rd difference of presented position over *presented* frames, normalised by peak speed | Catches velocity snaps that hit-time metrics miss (e.g., retarget bugs). The motion linter's "velocity snap" rule, made exact. | +| **Velocity continuity at retarget** | `|v_after − v_before|` at every segment boundary (should be 0 up to float eps) | Exact in analytic tracks; interruption bugs show instantly. | +| **Input-to-photon (virtual)** | `t_present − t_input_hw` per touch-driven frame | Latency budget; reported per frame; trend on reserved hardware. | +| **Scroll Jank v4-style** | Chrome's per-frame scroll jank counting across input/frames ([blog, 2023](https://blog.google/chromium/smoother-scrolling-how-we-halved-scroll-jank-in-chrome-on-android/); [Chromium post](https://blog.chromium.org/2023/08/smoothing-out-scrolling-experience-in.html)) | Halved scroll jank by ensuring consistent input-to-frame delivery [read headline]. Copy the *definition*, not the code. | + +- Android **JankStats / FrameMetrics / FrameTimeline** give the vocabulary ("deadline missed", "buffer stuffing", + "prediction error") that Rune's hitch attribution should reuse: charge each hitch to a phase (view, layout, shape, + encode, GPU) as PLAN §6b already says. +- **Agent trick:** since the clock is fake, run every scene through a *jitter fuzzer* (inject present-interval noise of + 0/4/12 ms σ, drop 1 in N frames) and assert that position-error stays ≤ ε. This proves "time-correct sampling" holds + for every animated property, which nobody can claim for hand-written animation systems. +- **Verdict:** adopt now; it is mostly arithmetic over the trace Rune already plans to emit. + +### 3. Direct-manipulation latency, late latching, resampling, prediction — **adopt now (late latch + resample), spike (prediction)** +- **Sources:** Ng, Lepinski, Wigdor, Sanders, Dietz, "Designing for Low-Latency Direct-Touch Input," UIST 2012; + Jota, Ng, Dietz, Wigdor, "How Fast is Fast Enough?" CHI 2013 ([PDF](https://www.tactuallabs.com/papers/howFastIsFastEnoughCHI13.pdf)) [recall; the PDF did not extract here]. + Headline as I remember it: drag-tracking differences are perceptible at single-digit ms (≈ 1 ms vs 10 ms users could + tell), tapping tolerates more (tens of ms), and performance degrades measurably by ≈ 10–25 ms. *Verify exact numbers before quoting.* +- **Android input resampling** (read in AOSP `InputConsumer.cpp` [read]): sample time is `frame_time − RESAMPLE_LATENCY (5 ms)`; + interpolate between two events if available; otherwise extrapolate, only if events are ≥ `RESAMPLE_MIN_DELTA (2 ms)` + apart, treating gaps > `RESAMPLE_MAX_DELTA (20 ms)` as too stale, and cap extrapolation at + `min(delta/2, RESAMPLE_MAX_PREDICTION = 8 ms)`. These are tuned constants Rune can start from. +- **Android MotionPredictor / AndroidX `motionprediction`:** Kalman-based pointer predictors whose prediction amount + depends on "speed and jank" ([AndroidX source](https://android.googlesource.com/platform/frameworks/support/+/57cb7c62c62fe4c95643d4777db) , Kalman `SinglePointerPredictor`) [read search result]. iOS: `UIEvent.predictedTouches` + and `coalescedTouches` (UIKit) [recall]. Chrome: input resampling + scroll prediction filters [recall]. +- **Rune use:** (a) the render thread reads raw pointer events (hardware timestamps) and *samples the latest position + immediately before encode*, instead of reading app-thread state; (b) resample to `t_present − ~5 ms` with the AOSP + rules; (c) coalesced events go into the velocity estimator at full rate (see §4); (d) optional: Kalman/linear + extrapolation capped at 8 ms *only for dragged objects*, with a no-snap blend when the real sample arrives; never for scroll content under the + user's finger unless measured as better. +- **Cost/risk:** (a–c) low and fits PLAN §4.9 "drags apply 1:1 on the render thread". (d) prediction overshoot at + reversals; gate by position-error metric on a recorded gesture corpus; ship off by default. +- **Verdict:** a–c adopt now; d spike. + +### 4. Gesture velocity estimation — **adopt now** +- **Source:** Android `VelocityTracker` impulse strategy ([AOSP `VelocityTracker.cpp`](https://android.googlesource.com/platform/frameworks/native/+/refs/heads/main/libs/input/VelocityTracker.cpp)) [read]. + The file documents a physical model: treat the touch as an object whose kinetic energy at release equals the total work + done by the finger; `v_final = sqrt(2·Σ(Δv·|v|))` per segment, with the sign handled by `|v|` so braking subtracts + energy; an initial-condition choice (v₀ = 0 vs already moving → ½v₁² start) is spelled out. Uses a ~100 ms history horizon; + `ASSUME_POINTER_STOPPED_TIME = 40 ms` means a pause before release gives ~0 velocity [read]. The old default was LSQ2 + (2nd-order least squares over the horizon), now an alternative strategy; Flutter's tracker is a polynomial LSQ with a similar horizon and stop rule [recall]. +- **Why it matters:** velocity handoff is the "release feel" (Apple's central rule: continue with the finger's velocity). + LSQ is noisy at the endpoint (it fits the middle of the window), impulse is robust to jitter and un-ringing. +- **Rune use:** implement both (reference = LSQ2 in f64, fast = impulse over a ring buffer), use hardware timestamps, + include coalesced samples, apply the 40 ms stopped rule, clamp to a platform max fling speed. **Agent trick:** record a corpus of real + gestures (Kit's iPhone + Mac trackpad) with the trace recorder; score each estimator by how well `x(t_release) + ∫v` + predicts the *finger's next 30–50 ms if it hadn't lifted* (use gestures cut at random points); pick/tune constants by minimising that error. + Fixed hand-tuned constants are the norm elsewhere; an offline fit is cheap for agents. +- **Cost/risk:** tiny. Risk: trackpad momentum on macOS is OS-generated (§8), so this is for touch and pointer drags. +- **Verdict:** adopt now. + +### 5. Springs, retargeting, projection, effects vs spatial (Apple and Material) — **adopt now** +- **WWDC18 "Designing Fluid Interfaces"** (session 803, Karunamuni/Alonso) [recall]: response/damping ratio over + duration; interrupt and redirect without waiting; fluid gestures never wait for the previous animation; momentum + projection `dest = x + v·rate/(1−rate)` using the scroll deceleration rate; rubber banding `f(x) = (1 − 1/(x·c/d + 1))·d` + (c ≈ 0.55); velocity handed from the gesture into the spring. WWDC23 "Animate with springs" introduces duration+bounce + and `.smooth/.snappy/.bouncy`: Rune's parameterisation already matches it. +- **Material 3 Expressive (2025)** [recall; check [m3.material.io motion](https://m3.material.io/styles/motion/overview/specs)]: + spring tokens come in two families, **spatial** (position, size, rotation; may overshoot) and **effects** (colour, + opacity; never overshoot), each fast/default/slow. Direct support for Kit's "bounce 0 default" and avoids opacity > 1 or negative-alpha glitches. +- **Perception evidence is thin:** I found no controlled study that springs beat easing curves; the case is + physical continuity (velocity preservation, interruptibility) and animation-principles heritage. Chevalier et al., + "Animations 25 Years Later" (AVI 2016) [recall] is the review. So treat "springs feel better" as design rationale, and let Kit's + blind A/B chooser (Bradley–Terry) settle specific values. +- **Rune use:** add a per-track `class: Spatial | Effect`; Effect tracks clamp to [min,max] of start/target and use the + critically damped solution even when asked for bounce; settle rule = analytic time at which `|x−target|<ε_px and |v|<ε_v` + (ε_px = 1/64 px for geometry per Kit's snapping rule, 1/256 for opacity), then snap exactly and stop the clock (zero-cost-at-rest). + Accept additive-animation behaviour (UIKit/CA retarget semantics) only if it matches exact segment retargeting; differential-test + the two on random retarget sequences. +- **Verdict:** adopt now. + +### 6. Interruptibility as a testable property — **adopt now** +- Retargeting `(x, v)` is exact for analytic segments. Test generator: random event scripts (retarget at random times, + random spring class), asserting (i) `x` continuous, (ii) `v` continuous, (iii) no extra pop at settle, (iv) `x` bounded by + physical envelope. This is the motion linter's "reversal / velocity snap / stop-dead" family, but checked on *every frame + of every fuzzed script* rather than on recorded clips. +- **Layered interruption (Apple "pause then redirect"):** a gesture that grabs a running animation must read the *presented* + value and velocity (not model state), pause the track, drive 1:1, then restart from the finger's velocity. Rune's presented-tree design does this by construction. +- **Verdict:** adopt now (cheap, rides on §5). + +### 7. Keeping text crisp while it moves — **adopt policy now, spike the harness** +**Facts:** macOS dropped LCD subpixel text AA in Mojave (10.14, 2018), so Apple text is grayscale and safe to resample [recall]. +Core Animation text inside a layer is rasterised to a texture, so fractional translation is *bilinear resampling* +(stable but soft); Chrome snaps composited-layer raster translation to integers where it can, otherwise text blurs [recall]. +GPUI/Zed rasterise glyphs into an atlas at a few quantised horizontal subpixel phases (4 in x; verify the y count in +`crates/gpui/src/platform.rs`) [recall]; Rune lifts that code ([01](01-gpui-zed-warp.md)). + +**Policy proposal** (the trick is making it *state-driven by the analytic track*): +1. **Y snaps, X doesn't:** snap baselines to whole device pixels whenever the text is not translating vertically; keep x at ¼-px phases (8 on non-retina). Stem thickness is then constant, only horizontal phase varies. +2. **Moving fast (> ~0.5–1 device px/frame):** allow exact fractional positions (grayscale AA, no hinting). Eye tracking blurs the stems anyway, and the atlas phase quantisation is invisible. +3. **Settling (spring tail):** the tail crawls through sub-pixel phases for a long time, which is the visible "shimmer/crawl". Because Rune knows the analytic time `t_end` when `|x−target|<ε`, **end the track there** (ε = ¼ px for text; Kit's 1/64 px rule applies to shape edges) and snap. A ¼-px final pop is invisible, a 300 ms crawl is not. Also try quantising the *phase* of text only after speed < threshold. +4. **Never mix:** text and its container share one track so there's no relative sub-pixel drift between a label and its pill (Kit's rule on snapping both edges). +5. **Hypothesis to test:** with linear coverage, no gamma/contrast fiddling and no hinting, total ink coverage per glyph is phase-invariant + (box filter conserves area), so brightness shimmer comes from nonlinear text contrast/gamma and atlas quantisation, not from AA itself. A harness renders + "lHEx" at 64 phases per size/weight and reports variance of per-glyph ink and per-stem width; CI-gate it. Agents can do this in seconds on the CPU reference renderer. +- **Vernier caution:** even at 460 ppi, motion *hyperacuity* (≈ 5–10 arcsec) makes 1-px stepping visible at slow speeds, so "round to device pixel while moving" is not safe; hence fractional-x while moving, snap at rest. +- **Verdict:** adopt the policy now (it's configuration of existing pieces); spike the phase-sweep harness. + +### 8. Scroll physics — **adopt now, analytic** +- **iOS:** `UIScrollView.DecelerationRate.normal = 0.998` per ms; closed form `x(t) = x0 + v0·(r^t − 1)/ln r`, stop time where `|v|<ε`; rubber band `c = 0.55` ([WWDC18 803](https://developer.apple.com/videos/play/wwdc2018/803/)) [recall]. Android: `OverScroller` spline fling (friction ≈ 0.015, inflexion 0.35) and Compose `splineBasedDecay` [recall]. Both are analytic in *time*, so fling is frame-rate independent and exactly retargetable: perfect for tracks. +- **Snap/targeting trick (Apple):** project the landing point with the decay, choose the snap target from the *projection*, then run a spring from the current `(x, v)` to that target; the user perceives "it knew where I was going". +- **macOS trackpad:** momentum phases arrive from the OS as events ([PLAN §4.9](../PLAN.md)); don't re-simulate. Resample them with the §3 rules, and + keep your own decay only for programmatic scroll and for non-Apple platforms. +- **Verdict:** adopt now; implement as another track kind `Decay{v0, rate}` with the same retarget/present API. + +### 9. Motion blur for UI at high refresh — **skip by default; spike for flings** +- **Physics:** on sample-and-hold displays, perceived blur ≈ tracking speed × persistence; 1 ms ⇒ 1 px per 1000 px/s ([Blur Busters](https://blurbusters.com/blur-busters-law-amazing-journey-to-future-1000hz-displays-with-blurfree-sample-and-hold/) [recall]). 120 Hz halves hold blur vs 60 Hz, and per-frame displacement halves too, so stroboscopic/"phantom array" stepping disappears at moderate speeds. +- **Do UIs need synthetic blur?** Apple's UI doesn't use it for ordinary motion [recall]. It helps when per-frame displacement exceeds roughly 4–8 px *(est.)*, e.g. a hard fling of a text list; and Kit's rules already ban blur on persistent items (3–4 px defocus blur is only for in-place entry/exit). A directional shutter blur is a different thing from defocus blur, but Kit should decide whether it conflicts. +- **Rune advantage:** velocity is exact, so blur length `= v · shutter` (180° ≈ half a frame) costs nothing to compute. Implement as N instanced taps of a layer/sprite along `x(t_present ± shutter/2)` (analytic, no velocity buffer, no reprojection), applied only when `|v|·period > threshold`; it is the same shape as FLIP interpolation but in time. +- **Cost/risk:** N× fill for the layer; text readability; fights Kit's crispness rule. **Verdict:** skip at rest and normal speed, spike as a fling-only effect (opt-in token), test with a blind A/B. + +### 10. Layout animation: FLIP, Motion projection, shared elements — **adopt rect-space FLIP; spike text-reflow FLIP** +- **Prior art:** FLIP (Paul Lewis, 2015: First-Last-Invert-Play) [recall]; Motion/Framer Motion layout projection (Matt Perry): a projection tree measures old/new boxes, animates a transform delta, and **scale-corrects** children, border-radius and box-shadow so scaling doesn't distort them ([Motion layout docs](https://motion.dev/docs/react-layout-animations); internals in Perry's "Inside Framer Motion's layout animations") [recall]; SwiftUI `matchedGeometryEffect`; Compose `SharedTransitionLayout` (1.7, 2024); CSS View Transitions (browser snapshots old/new and morphs the pair) [recall]. +- **Why Rune differs:** FLIP and projection exist because DOM layout is expensive and transforms are the only cheap animatable. Rune lays out once to the final geometry and animates each node's *edges* (PLAN §4.9), and draws at the presented size, so there is nothing to scale-correct. Keep that. Two extras worth taking from Motion: + 1. **Read the presented rect as "first"**, not the last target, so interrupting a layout animation resumes from where it is (Motion calls this latest-snapshot; matches Kit's retarget rule). + 2. **Single progress for shared-element travel** (Kit rule 12): interpolate source→dest rects from one value per element; never separately-sprung camera plus element. +- **Spike: word/glyph-level FLIP for text reflow.** When a container resizes and a paragraph rewraps, SwiftUI/CSS snap lines. Because text content is stable, each cluster has a perfect identity (its character index). Parley gives us old and new cluster rects, so each word's track runs old→new in rect space, and glyphs outside the visible clip fade via the soft mask. Impractical by hand (identity bookkeeping everywhere); trivial with a generated per-run track table. No mainstream precedent I know of, so it is a feel differentiator. Risks: words crossing each other mid-flight (monotonic-path rule: lines reflow in reading order so usually fine), cost on long text (cap by visible lines/word count), ligatures/shaping across the move (move *runs*, not glyphs). +- **Verdict:** rect-space FLIP adopt (already planned); text-reflow FLIP spike. + +### 11. Dirty/idle correctness and display pacing details — **adopt now** +- ProMotion/VRR: request the display's max rate during motion and drop to idle with zero wakeups once all tracks settle (PLAN §6b). `CAMetalDisplayLink` (iOS 17 / macOS 14) provides the target present timestamp and a latency preference [recall]. Pace with the OS, never sleep-based loops: Kit's own HUD lessons (no per-frame window resizes, `TimelineView` idle pause) apply. +- **Verdict:** adopt now (cheap, already in the plan). + +### 12. Auto-tuning feel from comparisons — **later** +Kit's chooser (blind A/B with Bradley–Terry stopping rule) generalises: let agents sweep 3–5 values of duration/bounce for one interaction and ask Kit for ← / → picks, update the preset JSON. That puts *Kit's perception* in the loop at 10 comparisons per parameter, replacing guessing about spring-vs-easing. Cost: UI in `mk tune`. Verdict: later, after presets exist. + +--- + +## Steal +- Android `InputConsumer` resampling constants (5 / 2 / 20 / 8 ms) and the `VelocityTracker` impulse model with 100 ms horizon and 40 ms stop rule. +- Apple's hitch-time-ratio thresholds (5 / 10 ms/s) and the commit-vs-render hitch split. +- Perfetto FrameTimeline's jank taxonomy (deadline missed, buffer stuffing, prediction error). +- Chrome's "consistent input-to-frame delivery" framing for scroll jank. +- M3 Expressive's spatial vs effects spring classes. +- Motion's "measure presented rect as First" for interrupted layout animation. +- WWDC18's project-then-spring pattern for snapping and flings. + +## Avoid +- Sampling animation by wall-clock "now" or by frame count/accumulated dt (error accumulates and hides hitches). +- Rescaling children to fake size animation (distorts text, radii, shadows). +- Rounding text to whole device pixels while moving slowly (crawl) or leaving it fractional forever after (shimmer, blur). +- Prediction on scroll content by default (overshoot at direction reversals, feels "swimmy"). +- Quoting the 1 ms / 10 ms latency numbers without checking the primary PDF (unread here). +- Synthetic motion blur on persistent items (violates Kit rule 11/persistent-items). +- Treating average fps or "no dropped frames" as the smoothness gate. + +## Recommendation for Rune +1. Build the present-time sampling and trace fields first (§1, §2); everything else is measured against them. +2. Put input on the render thread with late latching and Android-style resampling (§3); add the impulse + LSQ2 estimators and the gesture-corpus harness (§4). +3. Add track classes (Spatial/Effect/Decay), analytic settle times, and fuzzed interruption tests (§5, §6, §8). +4. Encode the text policy as defaults plus the phase-sweep harness (§7). +5. Spikes, in order: text-reflow FLIP (§10), fling-only blur (§9), capped prediction for drags (§3d), A/B chooser in `mk tune` (§12). + +**Rejected:** a CA-style additive-animation model (equivalent to exact retarget but harder to reason about and lint); +average-fps gates; Motion-style transform/scale-correction projection (solves a DOM problem Rune lacks); always-on +motion blur (conflicts with Kit's rules, little benefit at 120 Hz); relying on OS compositor snapping for text. + +## Open questions +- Exact ms numbers in Ng/Jota (PDF unreadable via the fetch tool; run `pdftotext` locally or read it). +- How much display latency does Metal/wgpu add on macOS ProMotion with `maximumDrawableCount = 2` vs 3, and does `presentAfterMinimumDuration`/`CAMetalDisplayLink` remove it? Needs a reserved-hardware spike (not a developer's desk display). +- GPUI glyph atlas subpixel phase counts in x and y (read `platform.rs` before reusing). +- Whether iOS exposes enough touch-sample timestamps to a Rust render thread outside UIKit's main-thread delivery (coalesced touches arrive via the main run loop); see [11](11-platform-shells.md). +- Apple hitch thresholds and the Material 3 Expressive spring tokens were recalled, not re-read; confirm before they become policy. +- Does Kit want a directional (shutter) blur at all, given rule 11 and the "persistent items never blur" rule? diff --git a/app/vendor/rune/research/16-research-agent-generative-ui.md b/app/vendor/rune/research/16-research-agent-generative-ui.md new file mode 100644 index 0000000..0458c5f --- /dev/null +++ b/app/vendor/rune/research/16-research-agent-generative-ui.md @@ -0,0 +1,308 @@ +# 16. Agent-native and generative UI: what Rune should steal + +Scope: LLMs generating UI at runtime, how agents perceive and operate UIs, token-efficient UI representations, LLM +codegen failure modes for UI frameworks, self-verifying loops, design-system-constrained generation. Today is 2026-10-21. +Evidence quality is marked per item: **[read]** = I read the primary source this session; **[recall]** = from memory of the +paper/post, not re-verified now, treat numbers as approximate. + +## Summary + +- Every serious generative-UI system converged on the same shape: **a closed catalog of components, a flat + id-referenced element list (adjacency list), a separate data model, and a streamed patch/message protocol.** Google's A2UI, + Vercel's json-render, and Airbnb-style server-driven UI all look like this. Rune's command channel (tree diff + targets + + text runs) is already the same shape, one level lower. Expose it, don't build a second system. +- Two safety models exist: **declarative data against a trusted catalog** (A2UI, json-render: no code runs) and **sandboxed + code** (MCP Apps / OpenAI Apps SDK: HTML in a locked iframe). For a native-feel renderer, declarative is the only option that + gets real springs, native text and a11y. Code runs only in a separate, capability-limited process (WASM), later. +- Models are good at this now but not at first-try correctness of *novel framework APIs*. Failure evidence points at + spatial/structural errors (missing elements, wrong size/position) and at strict type/trait semantics in Rust. Both are + answered by the same fix: a small closed vocabulary, a schema the decoder is constrained to, and a validator that returns + fixes. +- Agents operate UIs best from a **semantic tree plus screenshots**, with element ids in both (set-of-marks style). Rune owns the + tree, so it can emit a compact, stable-id, diffable text form that no web or native framework can match. +- The biggest wedge is not "LLM makes the UI at runtime" but **"the agent's design-time loop is a first-class product":** + scene → render → critique → patch, with exact lint results, so first-try correctness comes from the loop, not the prompt. + +## Findings (ranked roughly by value to Rune) + +### 1. Catalog + flat element list + data model + streaming messages (A2UI) → **adopt now (as Rune's own "Surface" protocol, A2UI-compatible)** +- Source: [A2UI v0.9.1 spec](https://a2ui.org/specification/v0.9.1-a2ui/), [v1.0 candidate](https://github.com/a2ui-project/a2ui/blob/main/specification/v1_0/docs/a2ui_protocol.md) (Jun 2026), [Google launch post](https://developers.googleblog.com/introducing-a2ui-an-open-project-for-agent-driven-interfaces/) (Dec 2025). **[read]** +- What it does: four messages (`createSurface`, `updateComponents`, `updateDataModel`, `deleteSurface`). Components are a flat + list with `id`s and child id references, so the model can emit them in any order and the client renders progressively + (placeholders for missing children). Properties bind to a JSON-Pointer data model or to catalog-declared functions + (`formatCurrency`, `pluralize`, `required`…). Catalogs are JSON Schema documents with an optional `instructions` markdown + field that is fed to the model. User actions go back as `action` messages; `sendDataModel` returns the surface state with each. +- Rune use: define Rune's runtime-UI surface as A2UI-shaped (flat elements, ids, data model, patch messages) with the **Rune + design system as the catalog** (Stack, Text, Button, List, Sheet, Glass…). Map `updateComponents` onto the existing keyed + `El` tree diff, so identity-preserving enter/exit and springs come free: a model that re-sends a component with the same id and + changed props gets a retargeted spring, not a pop. A2UI has no motion vocabulary; Rune's catalog adds `transition` and + `layout` tokens (named, from the theme), never raw durations. +- Cost/risk: low. It is JSON, Rune already needs a serializable channel. Risk is spec churn (v0.8→0.9→1.0 renamed + everything in 6 months) so keep an adapter layer, don't make A2UI the internal format. +- Verdict: **adopt now.** Design the internal wire format first (see §Recommendations), ship an A2UI adapter second. + +### 2. Constrain decoding to the catalog schema (XGrammar and structured outputs) → **adopt now** +- Source: [XGrammar, MLSys'25](https://arxiv.org/abs/2411.15100): up to 100x faster CFG-constrained decoding, near-zero + overhead end-to-end in serving. **[read]** Provider-side structured outputs (OpenAI/Anthropic/Gemini JSON-schema modes) **[recall]**. +- What it does: the model cannot emit an unknown component, a misspelled prop, or an enum value outside the set. Syntax errors + go to zero by construction. +- Rune use: generate the JSON Schema for the catalog **from the Rust component definitions** (one source of truth, `rune + schema` command), publish it for provider structured-output modes, and run the same schema as the runtime validator. Use + `oneOf` discriminated by `component`, props `additionalProperties: false`, enums for every theme token (spacing, color + role, spring name). Keep the schema small: structured-output modes cap schema size/depth and large `oneOf` unions slow + compile (estimate: keep under ~50 component variants, depth under ~5). +- Cost/risk: low. Constrained decoding fixes syntax and vocabulary, not layout quality or semantics; still needs the lint loop (§6). +- Verdict: **adopt now.** + +### 3. Semantic tree as the agent's eyes, with ids shared with screenshots (set-of-marks) → **adopt now** +- Sources: Set-of-Mark prompting (Yang et al., 2023) **[recall]**; UGround ([arXiv 2410.05243](https://arxiv.org/html/2410.05243v3)): vision-only grounding beats prior models by up to 20% absolute, i.e. pure-pixel agents are viable **[read snippet]**; [ScreenSpot-Pro](https://www.alphaxiv.org/abs/2504.07981) shows high-res professional UIs are where pixel grounding is still weak **[read snippet]**; a 2026 process-centric benchmark evaluates Screenshot vs Screenshot+a11y-tree vs SoM inputs ([ACL Findings 2026](https://aclanthology.org/2026.findings-acl.750.pdf)). OSWorld-Verified has passed the 72.36% human baseline; aggregator sites list leaders at ~85% ([benchlm](https://benchlm.ai/benchmarks/osworld-verified), unverified numbers, treat as indicative only). +- What it does: the two channels are redundant. Trees give exact, cheap, scriptable targets but miss custom-drawn UI (GPU UIs + such as GPUI/Flutter canvases have empty trees, which is the failure that makes agents fall back to pixels). Screenshots + see everything but ground imprecisely and cost many tokens per frame. Marks (numbered boxes drawn on the screenshot, same + numbers in the text tree) combine them. +- Rune use: because the a11y tree *is* the render tree (tenet 3), Rune can guarantee **100% of visible interactive nodes are in + the tree with rect, role, label, state, source `file:line`**, and render a **marked screenshot** (`mk snap --marks`) where each + mark id = node id. Agents say `tap n17`, not coordinates. Inject input through the inspector, not synthetic OS events, so a + tap on a node is exact and timestamped. +- Cost/risk: low; mark overlay is a debug-lane draw pass. The real risk is label quality: models can only use what authors + write, so make `label` required for every interactive control (compile or lint error with fix). +- Verdict: **adopt now.** + +### 4. Token-efficient tree text format (compact, stable ids, diffs) → **adopt now, measure** +- Sources: browser-agent practice (Playwright MCP snapshots, browser-use, Stagehand) all converged on "pruned a11y tree as + indented text with ref ids", and [the GUI-agents paper list](https://github.com/OSU-NLP-Group/GUI-Agents-Paper-List) + tracks work on linearizing a11y trees into compact forms because raw trees are costly and noisy **[read snippet]**. +- What it does: raw DOM/AX dumps run to tens of thousands of tokens per page; pruned role+name+ref outlines are roughly 5-20x + smaller (estimate from experience, I did not benchmark here). +- Rune use, a concrete format: + ``` + window "Inbox" 390x844 + list key=threads (scroll y=0/2310) + row n17 key=thread:42 "Ana: lunch?" [selected] 358x64 @16,120 <ThreadRow src=inbox.rs:88> + text n18 "Ana" ; text n19 "lunch?" ; button n20 "Archive" + ``` + Rules: only semantic and visible nodes; collapse pure layout wrappers; ids derived from keys (stable across frames, so + `tap n17` survives re-render); layout rects optional (`--rects`); **diff mode** returns only changed nodes since frame id + N (the channel already carries tree diffs; surface the same diff as text). Add a token counter to every inspector reply so + size is a tracked metric. +- Cost/risk: trivial to build; the work is deciding what is "semantic" and keeping it stable. Add a golden test per scene on + the text tree: it doubles as a cheap, deterministic UI regression test that is far less flaky than pixels. +- Verdict: **adopt now.** + +### 5. Self-verifying loop: render, lint, critique, patch → **adopt now (this is the product)** +- Sources: Google's Generative UI paper uses **post-processors for error reporting and page analysis** and notes JS/CSS/HTML + errors still occur occasionally ([arXiv 2604.09577](https://arxiv.org/abs/2604.09577)), plus prompt ablation: full + prompt ELO 1553 vs minimal 1496 vs no-"philosophy" 1451, so instructions matter more than examples-free brevity **[read]**. + DesignBench ([arXiv 2506.06251](https://arxiv.org/abs/2506.06251)) separates generation, edit and repair tasks and finds + framework-specific limitations and that generation tasks fail mostly on spatial/structural errors ("wrong element size", + "element missing") **[read abstract+snippet]**. Design2Code (484 real pages, [Si et al. 2024](https://salt-nlp.github.io/Design2Code/)): omission of elements and + layout distortion are the dominant visual failures; text and color are easy **[recall]**. +- What it does: failures are *spatial and structural*, which is exactly what exact layout lint can catch without a vision + model. A visual critique by a model is the second pass, not the first. +- Rune use: the PLAN §6 tools already are this. Make it one command an agent runs after every edit: `rune check <scene>` = + compile + render scene + the internal layout linter (overflow, overlap, tap target < 44, off-grid, contrast) + the internal motion linter on a scripted + interaction + tree diff vs golden, and print **findings as fixes keyed to source locations** ("`Row` at inbox.rs:88 is 312 + pt wide in a 290 pt parent; set `.fill()` or wrap in `Scroll`"). Return a marked screenshot only when lint passes or the + agent asks. One structured result, small text, hot-reload speed (<1 s). This is what turns first-try into + second-try-within-seconds. +- Cost/risk: moderate engineering, but all pieces are already in the plan. Risk: findings must be precise; a noisy linter + trains agents to ignore it. +- Verdict: **adopt now.** + +### 6. Design-system-constrained generation (tokens, not values) → **adopt now** +- Sources: A2UI catalog `instructions` + `theme` ([spec](https://a2ui.org/specification/v0.9.1-a2ui/)); json-render's + `defineCatalog` with Zod props and `catalog.prompt()` that auto-generates the system prompt + ([repo](https://github.com/vercel-labs/json-render), 18.8k stars, Apache-2.0; has an `@json-render/mcp` package and Ink/RN/Remotion/PDF renderers) **[read]**. + Google's paper adds "consistent styling" as an option ([arXiv 2604.09577 §2.1](https://arxiv.org/html/2604.09577)) **[read]**. +- What it does: the model picks `spacing: "md"`, `color: "text.secondary"`, `motion: "snappy"` instead of `13px`, `#8E8E93`, + `0.35s ease`. No off-palette color, off-grid spacing or unspecified curve is expressible. This also makes output + automatically consistent with the app's theme (tenet 5). +- Rune use: the catalog's prop types are **enums of theme tokens only** plus a few numeric ranges with units. No raw hex, no + raw durations, no free-form style objects in the generative lane (they stay available in the trusted app lane). Generate the + prompt from the catalog (`rune prompt` emits catalog + rules + 3 scenes as few-shot) so docs and validator can't drift. +- Cost/risk: the catalog needs to be expressive enough that models don't hit walls; plan an escape hatch component (`Canvas` + with a restricted vector DSL) rather than loosening the main catalog. +- Verdict: **adopt now.** + +### 7. Generative UI quality and latency envelope (Google) → **calibrate expectations; later** +- Source: [Google Research blog](https://research.google/blog/generative-ui-a-rich-custom-visual-interactive-user-experience-for-any-prompt/) (Nov 2025), [paper](https://arxiv.org/abs/2604.09577). **[read]** +- Numbers: LMArena prompts, human pairwise preference: Generative UI beats markdown 82.8%, beats top search result 90%, loses to + human-expert sites (35-43% win depending on revision; paper versions disagree: v1 says 35.3%, the PDF says 43%). ELO ~1736 vs + expert 1800 vs markdown 1438. Capability is *emergent*: newest models show far fewer generation errors. **Generation takes + "a minute or two"; streaming halves the time-to-interaction.** Output is a single full HTML page rendered as-is, i.e. maximal + freedom, no catalog. +- Rune use: two lessons. (a) Latency is the problem, so a protocol that renders progressively on partial output (A2UI's + flat list + placeholder rule) is mandatory, and the 1-2 minute whole-page approach is not something to copy. (b) Quality + is model-driven and improving, so a catalog design that is slightly too restrictive today is a bet that models will not need + raw HTML. Plan the catalog to grow. +- Verdict: **later** for Rune-as-chat-surface; the research mostly validates #1, #2, #6. + +### 8. Sandboxed-code lane: MCP Apps and the OpenAI Apps SDK → **skip for rendering; adopt as the delivery pipe** +- Sources: [SEP-1865 MCP Apps, Stable 2026-01-26](https://github.com/modelcontextprotocol/ext-apps/blob/main/specification/2026-01-26/apps.mdx); [MCP Apps overview](https://modelcontextprotocol.io/extensions/apps/overview); [Microsoft Cowork adoption](https://learn.microsoft.com/en-us/microsoft-365/copilot/cowork/mcp-apps-support). **[read]** OpenAI Apps SDK (Oct 2025) is the same pattern (tool declares a UI template, sandboxed iframe, host bridge) **[recall]**. +- What it is: servers declare `ui://` HTML resources (`text/html;profile=mcp-app`) on tools via `_meta.ui.resourceUri`; hosts + render them in a sandboxed cross-origin iframe, CSP built from declared domains (default: no network), JSON-RPC over + `postMessage`, template/data separation, host-mediated tool calls with user consent. Adopted by Claude, ChatGPT, VS Code, Cowork. +- Why it matters for Rune: it is the **de facto distribution channel** for agent UI: any Rune-hosting product (OpenCode + Desktop) that wants to show third-party agent UI will be asked for it. But HTML-in-iframe is the opposite of native feel: + no shared springs, text, a11y tree or glass. +- Rune use: (a) **steal the security model verbatim for any untrusted code lane:** predeclared templates, no ambient network, + declared capabilities, all host calls as auditable messages with consent. (b) Offer a **Rune-native MCP Apps profile**: a new + `mimeType` for a Rune surface (A2UI-shaped JSON) behind the same `ui://` + `_meta.ui` linkage. The SEP reserves other content + types for future extensions. Tools stay unchanged; hosts that support the Rune profile render natively, others fall back to text. +- Cost/risk: spec is Stable so safe to target; a native profile needs host adoption, so spike with OpenCode Desktop first. +- Verdict: **spike** (native profile), **skip** (iframe rendering inside Rune). + +### 9. Server-driven UI in production (Airbnb Ghost Platform, Lyft, Shopify) → **steal the lessons** +- Sources: Airbnb "Ghost Platform" series (2021), Lyft Bikes and Scooters SDUI (2022-23), Shopify Mobile SDUI/"Remote UI" **[all recall, older than 2023, not re-fetched]**. +- Lessons that recur: (1) a **section/component registry versioned with the client**, because old clients must ignore or degrade + unknown components (negotiate capabilities up front, like A2UI's catalogId + capabilities exchange); (2) **layout and + data separated** so data refreshes don't resend structure; (3) **actions are a closed set** (navigate, setState, call + tool), never scripts; (4) the failure mode is the **escape-hatch creep** where "just one more prop" turns the schema + into a bad programming language (json-render's `$cond/$state/$computed` already shows the slope); (5) debuggability needs + a spec-inspector (json-render ships devtools: spec tree, state editor, action log, stream log). +- Rune use: version the catalog with semver per component, advertise `catalogId`+version on connect, define degrade rules + (`unknown → Placeholder with label`). Keep expressions to a deliberately tiny set: bind, cond, template, a registered + function list; no arithmetic beyond the catalog's `format*` functions. Ship a `rune surface` inspector that shows incoming + messages next to the resulting tree. +- Verdict: **adopt now** (as design constraints). + +### 10. Rust codegen failure modes → design the API against them → **adopt now** +- Sources: [Rust-SWE-bench, ICSE 2026](https://arxiv.org/abs/2602.22764): 500 tasks, 34 repos; best ReAct agents resolve up to 21.2%; the two named + bottlenecks are **repo-wide structure comprehension and compliance with Rust's strict type and trait semantics**; their RustForger + (issue reproduction + metaprogramming tracing) reaches 28.6% **[read]**. [Microsoft Research on LLMs fixing Rust compile errors](https://www.microsoft.com/en-us/research/wp-content/uploads/2024/08/paper.pdf) (2024) and + [Fortytwo's Strand-Rust-Coder report](https://huggingface.co/blog/Fortytwo-Network/strand-rust-coder-tech-report) both report borrow-checker violations as + the dominant base-model failure **[read snippets]**. Caveat: these are issue-resolution benchmarks on 2025-vintage models; no + published study I found measures *Rust UI framework* first-try compile rates. Treat any number about Rune specifically as + unmeasured until Rune runs its own eval (see §Recommendations: "Rune-Bench"). +- What it implies: errors come from (a) lifetimes and borrows, (b) deep generics/trait bounds, (c) misremembered APIs + (training data predates Rune; GPUI/Iced/Xilem APIs shift and models hallucinate them). +- Rune use: view code should require **no lifetimes, no generic bounds, no borrows crossing closures** in the common path: + `Copy` ids and handles, owned values, closures take `&mut Model` passed in, no `impl Trait` returns that need naming, one + concrete `El` type (the PLAN's type-erased debug mode helps). Fewer distinct concepts than SwiftUI. Ship `llms.txt` plus + **an examples directory that compiles in CI** and prefer many small canonical examples over prose (models copy examples). + Make compiler errors actionable via custom `#[diagnostic::on_unimplemented]` and `compile_error!` messages with the fix. +- Verdict: **adopt now.** + +### 11. Two lanes: trusted Rust app code vs generated surfaces → **adopt now (architecture)** +- Argument: a model can write Rust app code *at design time* (agent in the loop with a compiler) or emit a **surface** at + runtime (no compiler). The same Rune renderer must serve both. They differ in trust, latency and expressiveness: + + | Lane | Who writes | Trust | Latency to pixels | Expressiveness | + |---|---|---|---|---| + | App code (Rust, hot reload) | coding agent + human | full | ~300 ms hot patch | everything | + | Surface (A2UI-shaped JSON over the channel) | model at runtime, or server | **untrusted**: catalog only, validated, capability-limited | first partial in one token chunk | catalog + data bindings + closed actions | + | Plugin (future, WASM) | third party | sandboxed, capabilities declared | compile-time | restricted | + +- Rune use: the surface lane is just another *producer* feeding the same render-thread channel the app side feeds. Each + surface gets its own **sub-tree root with a resource budget** (node count, text bytes, image count, spring count, depth, layout + cost) enforced before commit; exceeding it truncates with a visible placeholder, never a frame drop (§6b "no dropped frames by budget" applied at runtime). +- Verdict: **adopt now** (shapes the channel protocol: tree producers are pluggable, ids are namespaced per producer). + +### 12. Runtime safety for model-generated surfaces → **adopt now (checklist), spike (fuzzing)** +- Threats: prompt-injected content rendering deceptive UI (fake system dialog, fake "Allow" button), resource exhaustion + (10^6 nodes), exfiltration via image URLs or `openUrl`, action spoofing, layout-time bombs (deep nesting, huge text). +- Rune use (all enforceable because Rune owns the pixels): + - **Provenance chrome:** every surface lives inside a visually distinct container the model cannot style away (inset glass + border, optional "generated" badge); surfaces cannot draw outside their bounds (soft mask, the same mechanism as no-hard-clip) or over app chrome. + - **Closed action set** with host-side policy: `setState` on the surface's own model, `emit(action)` back to the producer, + `openUrl` only via allowlist and user gesture. Anything that touches the app or network goes through a **capability grant** + (same shape as MCP Apps `permissions`/consent). + - **Resource budget + deadline** per surface, enforced at validate time and each frame; image loads through a host proxy + with domain allowlist (MCP Apps' `connectDomains/resourceDomains` model). + - **Validate then commit atomically:** patches that fail schema or budget are rejected whole and reported back to the model as + a structured error (the model fixes it next turn). No half-applied surfaces. + - **Input from surfaces is data, never code:** no expression language beyond the tiny set in §9. + - Fuzz the validator + layout with generated surfaces (property tests; the PLAN's scene fuzzing applies). +- Verdict: adopt the checklist; **spike** a validator fuzzer early. + +### 13. Native feel for model output: motion and layout come from the catalog, not the model → **adopt now** +- Insight: models can't be trusted to tune springs, and shouldn't. The catalog gives each component built-in + enter/exit/layout behavior from theme tokens (bounce 0 default, duration-based), identity from `id`, so streaming in a new + card, reordering a list, or the model rewriting the whole surface all animate correctly with no motion authored by the model. + Progressive rendering becomes a feature: A2UI-style streamed `updateComponents` inserts nodes that **fade/scale in with presence + tracks while text streams**, and layout animates as siblings arrive. The internal motion linter's rules (pop, jump, reflow) run on + surfaces too, so you can **prove** a streaming surface never jumps. +- Specific risk: streaming makes *layout churn* (content height grows token by token). Policy: reserve space (skeleton + placeholders by component default size), apply layout edge tracks with the standard spring, never animate every token; text + grows with a soft trailing mask rather than reflowing the box each token (precedent: the private iOS client's streaming text). +- Verdict: **adopt now**, as a test scene: "stream a 40-component surface at 30 tokens/s, the internal motion linter must be clean." + +### 14. Rune-Bench: our own eval of first-try correctness → **adopt now (small)** +- Why: no public benchmark measures LLM first-try correctness for a new Rust UI framework or catalog. Closest: DesignBench + (React/Vue/Angular generation/edit/repair), Design2Code, WebGen-Bench (end-to-end web apps, pass rate by UI tests; [recall]), Sketch2Code. + Their taxonomy (generation / edit / repair; structural vs visual errors) is what to copy. +- Rune use: 30-50 tasks as scenes (spec + fixture + reference tree/golden): *generate from prompt*, *edit* ("make the row + tappable"), *repair* (given lint failure). Metrics: compiles first try, lint-clean first try, tree-match vs reference, turns to green, tokens spent. Run per model on + every API change. **This turns "API agents can't misuse" into a number**, bisectable like the perf counts. +- Verdict: **adopt now** (week 1 of M1-ish); cheap and pays back on every API decision. + +## Steal / avoid + +**Steal** +- A2UI's flat element list + ids, separate data model, four-message envelope, catalogId negotiation, catalog `instructions`. +- json-render's: catalog → auto-generated prompt; SpecStream (streamed JSON patches compiled into a partial spec); devtools panel (spec tree, state, action log, stream log). +- MCP Apps's security model: predeclared templates, restrictive default, declared capabilities, auditable messages, user consent for UI-initiated calls; `ui://` linkage as a delivery vehicle. +- Browser-agent snapshot practice: indented role/name/ref text, ref ids stable within a snapshot. +- Set-of-marks overlay for pixel+tree grounding. +- Google's "post-processors for common issues": auto-repair passes (e.g. clamp, wrap in Scroll, add missing key) before showing an error to the model. +- DesignBench's generate/edit/repair task split for evals. + +**Avoid** +- Whole-page generation as raw HTML/code at runtime (1-2 minute latency, no safety, no catalog, JS errors) as the default. +- A general expression language in the schema (the slope from `$cond` to a bad scripting language). +- Raw style values in the generative lane (hex, px, durations). +- Coordinate-based agent actions as the primary interface; always prefer node ids. +- Making A2UI (still 0.9 → 1.0 candidate, renamed once already) the internal format. +- Screenshot-only verification as the first gate: slow, token-heavy, imprecise; use exact lint first. +- Relying on prompt text to teach the API; models' training data will not contain Rune (unlike SwiftUI/React). Compile-checked examples beat docs. + +## Recommendation for Rune + +**View API (for the Rust app lane), so models are right the first time** +1. One concrete tree type (`El`), builders only, no macro DSL, no lifetimes or generic bounds visible in signatures. Props via a + small fixed set of chainable modifiers whose names mirror SwiftUI where semantics match (models know SwiftUI deeply; reuse the + vocabulary: `Stack`/`HStack`/`VStack`, `.padding`, `.frame`, `.animation`), because **vocabulary alignment with training data is the cheapest first-try-correctness lever**. +2. Tokens, never numbers, in the public API for color, spacing, type, radius, motion (raw numbers only through an explicit `raw_*` escape that lint flags). +3. Explicit `.key()` required in dynamic lists; `label` required for interactive nodes; the compile error text says exactly what to write. +4. Every component registers a **catalog entry** (name, props schema from the Rust type, doc string, 2 scenes). The catalog JSON + Schema, the `llms.txt` section, the inspector's queryable names, and the generative lane's validator are generated from that single registry. +5. Examples dir compiled and run in CI; `rune check` as the single feedback command (§5 above). + +**Wire protocol (command channel, used by app side, hot reload, tests, agents, generated surfaces)** +- Messages (a superset of A2UI's four): `surface.create{id, catalog, version, budget}`, `surface.patch{id, ops}` (ops: upsert + element by id, remove, reorder children, set data path), `surface.delete`, plus lower-level render commands (targets, springs, text runs) that only trusted producers may send. +- Elements are a flat table `{id, kind, props, children[]}`; ids namespaced `producer/surface/local`; props reference data + paths or theme tokens; a validate step produces a typed `Rejection{path, rule, fix}` that goes back to the producer (and into the model's context). +- Events back: `action{surface, element, name, payload}`, `settled{frame}`, `data{surface, model}` (A2UI `sendDataModel`). +- Same stream recorded for replay (already planned), same stream carried over the inspector socket, same stream a `--agent` text view renders as the compact tree. One protocol, four consumers. +- Negotiate on connect: catalog id + semver, budget limits, supported motion tokens, max protocol version. + +**Rendering model-generated UI at runtime with native feel** +- Surface lane = declarative catalog only, validated + budgeted + provenance-marked (§12); trusted components provide springs, + text, a11y, glass. A2UI/MCP Apps adapters sit at the edge: A2UI JSON → surface patches; a Rune MCP Apps profile for hosts that opt in. +- Untrusted code (later): WASM component with host-granted capabilities, emits surface patches, never touches the render + thread; MCP Apps' consent/CSP model as the template. Not before M-late. + +**Rejected alternatives** +- *Embed a WebView for generated UI (MCP Apps iframe):* gives universal compatibility, loses everything Rune is for. Allow only as a clearly separate "web card" component if a host demands it. +- *Let the model write Rust at runtime and compile:* seconds-to-minutes compile, borrow-checker failure rates (Rust-SWE-bench: up to 21% issue resolution), no safe sandbox. Keep for design time only. +- *Adopt A2UI wholesale as the one format:* its component model has no motion, no layout animation, no a11y labels as required fields, and is mid-churn. Adapter, not foundation. +- *Screenshot-only agent operation:* strong models now handle it (OSWorld-Verified past the human baseline per aggregators), but it's costlier, noisier and misses state that the tree gives for free. + +## Order of work (suggested) +1. Define component registry → JSON Schema + `llms.txt` + prompt generator (items 2, 6, 10). +2. Compact tree text + marks screenshot + stable ids in inspector (3, 4). +3. `rune check` single-command verify loop with fix-oriented findings (5). +4. Rune-Bench v0 with 30 scenes (14). +5. Surface lane: patch protocol, validator, budgets, provenance chrome, fuzzer; A2UI adapter (1, 11, 12). +6. Streaming-surface motion scene under the internal motion linter (13). +7. Spike: Rune MCP Apps profile in OpenCode Desktop (8). Later: WASM plugin lane. + +## Open questions +- What is first-try compile + lint-clean rate for Rune's API per model today? Unknown until Rune-Bench exists; set the target + (suggest ≥80% generate, ≥90% edit within 2 turns) and track. +- How small can the catalog stay (estimate 30-50 components) before models hit walls, versus how big before constrained-decoding schema compile hurts per provider? +- Can the surface lane share the exact `El` diff path (zero extra work on the render thread), or does namespacing/budgeting need its own tree? Probably shared; prove with the counting allocator. +- Do hosts (OpenCode Desktop, Claude, ChatGPT) have any appetite for a native-surface MCP Apps profile? Needs a conversation with OpenCode before building. +- Text-tree vs marks: which gives better agent success per token on Rune scenes? Needs an A/B over Rune-Bench with two agent configs. +- Evidence gaps in this note: Set-of-Mark, Design2Code specifics, WebGen-Bench, Sketch2Code, Airbnb/Lyft/Shopify SDUI details, and the OpenAI Apps SDK are **[recall]**, not re-read; OSWorld-Verified leaderboard figures come from aggregator sites and could be wrong. Re-verify before quoting externally. diff --git a/app/vendor/rune/research/17-research-perf-architecture.md b/app/vendor/rune/research/17-research-perf-architecture.md new file mode 100644 index 0000000..addaffc --- /dev/null +++ b/app/vendor/rune/research/17-research-perf-architecture.md @@ -0,0 +1,298 @@ +# 17. Performance architecture: cutting-edge tricks for Rune + +Scope: UI-engine performance architecture, incremental computation, dirty tracking, render-thread handoff, GPU upload, +Rust compile speed, hot patching, PGO/BOLT. Written 2026-10-21 for tenet 7 (agents maintain the code, so fast-path + +reference-path and differential testing make "ugly but fast" safe). + +**Provenance.** Marked **[fetched]** = I read the page this session. Marked **[memory]** = from my own knowledge, link +given but not re-read; verify before relying on numbers. Estimates are labelled. + +## Summary + +- Rune's biggest structural win is already in the plan: animation on the render thread with analytic springs. The + cleverest extension is to **evaluate springs on the GPU** from a track table, with draw instances referencing + property-tree node ids, so an animating frame costs ~one uniform write on the CPU (idea 1). +- Slate's invalidation measurement shows the cost model: a 10k-widget UI paying full price "to do nothing" took + 34.29 ms/frame; with caching it took 0.35 ms [fetched]. Rune's "zero work at rest" needs per-node dirty classes, not + just a global "something changed" flag (idea 2). +- Cheapest big compile win on macOS, measured: `[profile.dev.package."*"] debug = false` cut a clean nushell debug + build 22-30%; `split-debuginfo = "packed"` adds ~16 s per edit [fetched]. Linking is not the bottleneck on macOS (idea 10). +- Cranelift is **not ready on macOS** (no unwinding on macOS, arm64-macOS ABI mismatches with LLVM as of the June 2025 + report [fetched]); skip for Rune dev builds on Apple. +- Deterministic channel replay (PLAN §6) doubles as a perfect PGO training corpus (idea 12). +- Don't adopt Salsa/SwiftUI-AttributeGraph-style general dependency graphs; take only **early cutoff** (equal recompute + → no propagation) and **constraint-based memoization** (comemo) at layout/text boundaries. + +--- + +## Ideas + +### 1. GPU-evaluated spring tracks + property trees (Chromium `cc` shape) — verdict: **spike (S-new, high value)** + +- **Source.** Chromium compositor property trees, the transform/clip/effect/scroll trees separate from layers, so + compositor-thread animation only mutates a tree node + ([docs](https://chromium.googlesource.com/chromium/src/+/main/docs/how_cc_works.md), [memory]; older but the design + still stands). Flutter/Impeller and Core Animation's render server do the same split. Analytic spring segments are + Psychopomp's model (PLAN §4.9). +- **What it achieves.** In Chromium, a transform animation never re-runs paint or layerization. Number: none I can cite. +- **How Rune uses it.** Scene build emits instances that carry `(transform_node, clip_node, effect_node)` u16/u32 + indices instead of baked positions. Tracks live in a GPU buffer as SoA `{t0, x0, v0, target, omega, zeta}`; a vertex + shader (or a tiny compute pre-pass per node level) evaluates `x(t)` closed-form for the frame's target timestamp. The + CPU per-frame cost while springs run becomes: write one `time` uniform, encode the same command buffer (or reuse an + Indirect Command Buffer). Retargeting writes one 24-byte segment. Hit-testing/culling still needs CPU-side values: + keep the CPU evaluator as the **reference path** and differential-test it against GPU readback in scenes + (floating-point: use `f32` with identical formula; allow 1/64 px tolerance, which matches the plan's edge snapping). +- **Cost/risk.** Layout-edge animation changes node rects, so text/glyph positions that depend on them need the + property-tree indirection to cover size as well as translation (an affine can't express an edge-only resize of a + rounded rect with unscaled corners; those need per-instance `rect = lerp(edges)` evaluated in-shader). Hit-testing at + presented positions needs the CPU evaluator anyway (it's cheap: a few flops per animating node). +- **Verdict.** Spike on the first scene with 1,000 animating cards: compare CPU instance-buffer rewrite vs GPU evaluate. + Expected (estimate) win is CPU time per animating frame dropping from O(animating instances) to O(1). + +### 2. Per-node dirty classes with a "volatile" escape hatch (Slate invalidation) — verdict: **adopt now** + +- **Source.** Unreal Slate [Invalidation docs](https://dev.epicgames.com/documentation/unreal-engine/invalidation-in-slate-and-umg-for-unreal-engine?lang=en-US) + [fetched]: four classes (Volatile/Visibility → Paint → Layout → Child) in increasing cost, each implying the later + steps, dirty list processed once per frame; Volatile widgets bypass paint caching but keep layout caching. Independent + measurement ([ta-dah.tech, Aug 2026](https://www.ta-dah.tech/blog/retainer-box-vs-invalidation-box-what-10000-updating-widgets-taught-me-about-umg-performance/) + [fetched]): 10,000 widgets, one updating: **34.29 ms → 0.35 ms** (Retainer) / **0.39 ms** (Invalidation Box); + `SWidget::Paint` count 4,487 → 29. Gotcha they hit: a Retainer set to render on a fixed phase *re-rendered every + frame* and ran at 50.9 ms, worse than no cache. Retainer gives about no extra CPU win over invalidation, costs a + render target per retainer (Epic: "try Invalidation Boxes first"). +- **How Rune uses it.** Dirty bits per node, SoA bitset: `PAINT`, `LAYOUT`, `CHILDREN`, plus `PRESENCE`/`VOLATILE`. + Tree diff sets the minimal class (colour change = PAINT only, no Taffy call; key add/remove = CHILDREN). Bits + propagate up as "subtree has dirty descendants" so traversals prune. Property tracks never set bits (they're + render-thread data). Cached subtree textures (retainers) only for provably static, expensive-to-draw subtrees + (blur, big vector art) with an exact invalidation rule; never on a phase timer. +- **Perf gate.** Count `nodes_visited_per_frame` and `nodes_painted` in the exact-counters harness; at rest both must + be 0 and the display link stopped. +- **Cost/risk.** Missed invalidation = stale pixels. Mitigation (tenet 7): reference path re-runs everything every + frame in test mode and diffs pixels against the incremental path ("paranoid mode", Slate itself ships a + `Slate.InvalidationDebugging` equivalent). +- **Verdict.** Adopt. It's the cheap 100× for scrolling lists and big static chrome. + +### 3. Early cutoff and "durability" from Salsa/Adapton/Incremental; skip the general graph — verdict: **adopt the cutoff, skip the engine** + +- **Sources.** [Salsa](https://salsa-rs.github.io/salsa/) (backdating: if a query recomputes to an equal value, its + dependents are not invalidated; durability levels skip re-validating stable inputs), [Adapton](https://docs.rs/adapton) + (demand-driven incremental, paper "Adapton: Composable, Demand-Driven Incremental Computation", PLDI 2014), + [Jane Street Incremental](https://github.com/janestreet/incremental) (cutoff functions on nodes; heap by height), + SwiftUI's AttributeGraph (not public; known via reverse engineering write-ups, [memory]). All [memory]. +- **What it achieves.** Salsa's rust-analyzer reuses work across edits; no UI-frame numbers. +- **How Rune uses it.** Three specific uses, none a general graph: + 1. After Taffy runs, compare each node's new rect to the old; only changed rects emit layout-edge commands to the + render thread (cutoff). Likewise text: new shaped-run hash equal → no re-upload. + 2. View-function inputs: `cx.read(model)` records a version number; if every read version is unchanged and props + hash equal, skip re-running the view and reuse its `El` subtree (React Compiler does exactly this by + auto-memoizing per-component values, [docs](https://react.dev/learn/react-compiler), [memory]). + 3. Durability: tag models as `static-ish` (theme, fonts, locale) vs `hot` (cursor, hover); a theme change is the only + thing that revalidates the world. +- **Why not the full engine.** PLAN §4.8 already rejected signals because state must survive hot patches; a graph keyed + by code identity breaks across patches. Version numbers on typed models don't. +- **Verdict.** Adopt cutoff + version-stamp memoization; skip Salsa/Adapton as dependencies. + +### 4. Constraint-based memoization (comemo) for layout and text — verdict: **spike** + +- **Source.** [comemo](https://github.com/typst/comemo) (Typst): memoize pure functions whose arguments are *tracked* + types; the cache entry records only which methods of the tracked argument were called and their results, so a changed + argument that doesn't change *those answers* still hits. [memory] +- **How Rune uses it.** Layout of a subtree depends on `(available space, style, children)`. Taffy already caches per + node with a small fixed set of slots keyed by available-space (known behaviour, [memory]); comemo-style tracking would + go further for text: shaping depends on `(text, font, size, features)` but wrapping depends only on *width bucket*; + record "line breaks stayed identical for any width in [w1, w2]" so container resizes during a spring don't re-wrap + (the plan's two-tier cache does a cruder version of this). Valuable for **layout animation** where width changes + continuously but the target layout is computed only at target (so it matters less); useful for resizable windows. +- **Cost/risk.** Tracked-call bookkeeping costs more than recomputing small nodes. Only worth it above a node-size or + text-length threshold. +- **Verdict.** Spike, only for paragraph wrap intervals. Cheap to try because Parley exposes break opportunities. + +### 5. Lock-free handoff: SPSC byte ring for commands, triple buffer for "latest state", left-right for read-mostly trees — verdict: **adopt now** + +- **Sources.** [triple_buffer](https://docs.rs/triple_buffer) (non-blocking, wait-free latest-value handoff where the + producer may overwrite; reader always sees a complete snapshot) [fetched via search page]; [left-right](https://github.com/jonhoo/left-right) + (Jon Gjengset: two copies of a structure, writers apply an op log to the idle copy, readers never block) [memory]; + [rtrb](https://github.com/mgeier/rtrb)/ringbuf for SPSC rings [memory]; seqlocks for tiny POD [memory]. +- **How Rune uses it.** The command channel is semantically two things; use two primitives: + - *Ordered, lossless*: tree diffs, spring targets, text runs → one SPSC ring of **length-prefixed POD records** + (bump-encoded, no per-command allocation, trivially serializable for the USB/replay path: the ring's bytes *are* + the replay log). + - *Latest-wins*: gesture/scroll offsets, viewport, presented-frame id back to the app → triple buffer / atomics. + - *Read-mostly shared structure*: hit-test data (presented rects) that the **main thread** queries for input while + the render thread updates → left-right with a per-frame "swap" at the end of scene build. Alternative: render thread + answers hit tests via a message (adds a hop); left-right avoids the hop. +- **Numbers.** None I can cite for UI; triple buffering's whole point is that reader/writer collisions cost no waiting + vs mutexes (crate docs). +- **Risk.** Exact memory-ordering bugs. Mitigation: loom tests for each primitive (agents write these well), or use + the published crates and skip custom code. +- **Verdict.** Adopt, using published crates first; hand-roll the byte ring only when the allocator counter says so. + +### 6. Struct-of-arrays subtree-contiguous tree + SIMD hit-test/cull — verdict: **adopt layout; spike SIMD** + +- **Sources.** [Clay](https://github.com/nicbarker/clay) (flat arrays, arena, two-pass flex layout, "microsecond layout" + claim from its README; author's walk-through video is the best explainer) [memory/search snippets]; Dear ImGui (ID + stack + immediate draw lists with a single vertex/index buffer per window) [memory]; Xilem/Masonry's per-pass dirty + flags (`needs_layout`, `needs_paint`) [memory]. +- **How Rune uses it.** Store nodes in DFS pre-order with `subtree_end[i]`. A subtree is a contiguous index range, so: + dirty propagation = range ops; clipping/culling = skip `i..subtree_end[i]`; "is this subtree animating" = one flag; + scene build is a linear scan. Rects as four `f32` columns (`x0,y0,x1,y1`) so a hit test or visibility test over 4 or 8 + nodes is one NEON/AVX compare + movemask (`std::simd` is still unstable; `wide` or hand-`core::arch::aarch64` works). + Keep a `Vec<Node>` (AoS) reference implementation behind the same trait for differential tests (tenet 7). +- **Numbers.** None measured. **Estimate**: hit-testing 10k nodes goes from ~10-20 µs scalar to ~3-5 µs with NEON; at + 120 Hz neither matters unless pointer-move storms run every frame, so SIMD is low priority. +- **Cost/risk.** DFS ordering is awkward on keyed insertion mid-tree (renumbering). Mitigate with generational ids plus a + per-frame compaction; the tree is rebuilt from views anyway. +- **Verdict.** Adopt DFS-contiguous SoA now; SIMD hit-test later, behind a counter that proves it matters. + +### 7. Per-frame bump arena + counting allocator as a test gate — verdict: **adopt now** + +- **Sources.** [bumpalo](https://github.com/fitzgen/bumpalo) [memory]; a counting `GlobalAlloc` (e.g. + [stats_alloc](https://docs.rs/stats_alloc), or ~30 lines hand-written) [memory]; PLAN tenet 7 already mandates it. +- **How Rune uses it.** Scene build, diff scratch and El construction go in an arena that resets per frame; long-lived + data (tracks, atlas, node SoA) are pre-sized `Vec`s with capacity reuse. A test asserts `allocations == 0` between + `begin_frame` and `present` for a fixed catalog of scenes, **at rest and while animating**. Note `El` trees built by + views each rebuild will allocate unless `El` children are arena slices; plan for `&'frame [El]` not `Vec<El>`, a + signature decision that is expensive to retrofit. +- **Verdict.** Adopt now and make the arena lifetime part of the `El` type from day one. + +### 8. Apple Silicon unified-memory upload: write instance data in place — verdict: **spike (after wgpu baseline)** + +- **Sources.** Apple [Metal Best Practices: Resource Options](https://developer.apple.com/library/archive/documentation/3DDrawing/Conceptual/MTLBestPracticesGuide/ResourceOptions.html) + (unified memory: CPU and GPU share system memory; `Shared` is the natural mode; triple-buffer dynamic data with a + semaphore) [search page]; `newBufferWithBytesNoCopy` needs page-aligned, page-multiple-length memory (and gotchas + on StackOverflow when contents read as zero) [search page]. +- **How Rune uses it.** Per-frame instance buffer = a ring of 3 persistently mapped `Shared` buffers; scene build writes + `UberQuad` instances **straight into the mapped slice** (no intermediate `Vec`, no memcpy). Atlas uploads: write into a + `Shared` staging region and `blit`/replaceRegion only dirty rects; glyph atlas on Apple can be `Shared` texture + directly. The shaped-text path can emit instances directly from cached glyph runs. +- **wgpu caveat.** wgpu's `queue.write_buffer` copies through an internal staging belt; to avoid that use + `mapped_at_creation` or `Buffer::map_async` rings, which on Metal map to the same unified allocation, but verify that + claim by reading wgpu-hal's Metal buffer code before relying on it [unverified]. +- **Cost/risk.** Honest answer: the memcpy of a few hundred KB of instances is ~tens of µs on M-series (**estimate**), so + this is a polish item not a bottleneck. Prioritize it only if frame traces show `encode` dominated by copies. +- **Verdict.** Spike with raw Metal in the §4.2 later backend; don't contort the wgpu path. + +### 9. Damage tracking on a TBDR GPU — verdict: **later** + +- **Source.** Apple GPUs are tile-based; load/store actions control bandwidth [memory]. `CAMetalLayer` presents the whole + drawable and rotates 2-3 of them, so partial redraw requires "buffer age" bookkeeping (EGL `EXT_buffer_age`-style) to + re-copy or re-draw regions that were stale in this drawable [memory]. +- **Opportunity.** Idle-ish frames (caret blink, a tiny spinner) draw a scissored rect. PLAN §4.3 already lists dirty-rect + scissoring. Win is **power**, not frame time. A caret blink at 2 Hz is "zero ticks" anyway if you present only on change. +- **Verdict.** Later. First measure whether a full pass at rest-with-small-change costs notable energy (Instruments + energy log) before building damage-history machinery. + +### 10. Rust compile-speed levers, measured — verdict: **adopt the cheap ones now** + +| Lever | Result | Source | Verdict | +|---|---|---|---| +| `[profile.dev.package."*"] debug = false` | clean build −22% / −30% (nushell, 799 units, M-series, Rust 1.99); `target/` 4.3→2.3 GB | [ImportStatic, Oct 2026](https://importstatic.com/rust/rust-debug-build-cargo-profile) [fetched] | **adopt** | +| leave `split-debuginfo` at macOS default (`unpacked`) | `packed` took edit→build from ~2 s to ~18 s | same [fetched] | **adopt** (never set `packed` in dev) | +| `debug = false` everywhere | clean −16/−20% but rebuild-after-edit *slower* (3.1-3.7 s vs 1.6-2.8 s, extra `strip=debuginfo` pass, likely cause unproven) | same | avoid | +| Linker choice on macOS | final link only ~2-4 s of a 112-216 s clean build; ~2 s incremental | same [fetched] | linker is not the bottleneck on Mac | +| mold | 4.9× lld, 1.9× wild at median; M1 Ultra (Linux) debug links 1.5-10× lld; README lists `macho/` in repo and says it's now written in Rust with an ASPLOS 2027 paper | [mold README](https://github.com/rui314/mold), [paper](https://arxiv.org/abs/2608.23228) [fetched] | watch: its Mach-O status unverified; check before assuming | +| wild | Linux-focused ("a very fast linker for Linux") | [wild](https://github.com/wild-linker/wild) [search snippet] | no use on macOS | +| Cranelift backend (`rustc_codegen_cranelift`) | reported 20-30% less clean-build time on some projects [reddit anecdote]; **no unwinding on macOS, several arm64-macOS ABI incompatibilities with LLVM** (June 2025 report) | [bjorn3 report](https://bjorn3.github.io/2025/06/30/progress-report-june-2025.html) [fetched] | **skip on Apple**; maybe on Linux CI | +| Parallel front end (`-Zthreads=N`) | claimed 20-30% on nightly; stabilization is a 2026 goal; known deadlock/ICE/incremental issues being fixed, no robust test suite yet | [Rust goals 2026](https://goals.rust-lang.org/2026/parallel-front-end.html) [fetched] | spike on nightly in a throwaway profile, not for the main loop | +| rustc itself | ~4.6% mean wall-time gain over two months of compiler work | cited in ImportStatic from Nethercote's Sept 2026 roundup [fetched, secondhand] | free over time | + +**Rune-specific levers (mostly my recommendations, not measured):** +- **Crate split along the hot-patch boundary:** `rune-core` (arena, tree, tracks, protocol; changes rarely) / + `rune-render` / app view crates. Subsecond patches the app crate only; keeping the patched crate tiny is the main + determinant of patch time (estimate: patch time ≈ incremental compile + thin link of that crate). +- **Dev profile:** `opt-level = 1` for the rune crates (springs/layout at `opt-level = 0` are too slow to feel right at + 120 Hz) and `opt-level = 3` for Taffy/Parley/skrifa/wgpu via `[profile.dev.package.taffy]` etc. This is the well-known + Bevy recipe [memory]; heavy deps compile once and stay cached. +- **Type-erased views and no generics tower** (already tenet 7); generics → `-Zshare-generics` helps incremental + [memory]. +- **`cargo check`-speed inner loop for agents** is likelier to be dominated by rust-analyzer-like analysis than linking; + run `cargo check` with `-Zthreads` only on a spike machine. +- The numbers above come from a 12-core Apple-silicon Mac, so + larger machines should do better. **Do a one-hour measurement of the real Rune workspace on a build Mac** before + committing to any of this beyond the two profile lines. + +### 11. Hot patching: shrink what's patched — verdict: **spike already in plan; tighten the design** + +- **Source.** [subsecond](https://docs.rs/subsecond): detours calls through a jump table; patches are separate objects + built by intercepting the link step and driving `rustc` manually; "works across macOS, Windows, Linux, iOS, Android" + per the author ([HN](https://news.ycombinator.com/item?id=44369642), [search snippet]); requires an ASLR reference + address from the running process. +- **How Rune uses it.** The plan's state design (typed models outside views, keyed by stable ids) is what makes patching + safe, since struct layout changes break old state. Add: (1) models are the only state that crosses a patch, and a + **layout hash of each model type** is stored with it; a mismatch triggers a reset of that model only, with an + inspector message, rather than UB; (2) keep the render thread's code out of the patch set (it's in `rune-render` + and not hot), so animation continues during a patch; (3) patch granularity = view functions, handlers. +- **Cost/risk.** Layout-hash gating is the difference between "usually works" and "agents trust it". Known from subsecond + docs: changing struct layouts requires a rebuild. +- **Verdict.** Already planned; add the layout-hash guard and render-thread isolation as requirements. + +### 12. PGO from replayed command streams; BOLT later — verdict: **later (post-M3)** + +- **Sources.** [cargo-pgo](https://github.com/Kobzol/cargo-pgo) and [Kobzol's write-up](https://kobzol.github.io/rust/cargo/2023/07/28/rust-cargo-pgo.html) + (PGO + BOLT; the tool's README claims up to ~15% speedups [search snippet]; Rust's own compiler ships PGO/BOLT-optimised + builds). Mach-O BOLT support was not mature when I last looked [memory, unverified]; PGO works with LLVM on macOS. +- **The agent-specific trick.** Rune records the command channel for deterministic replay (PLAN §6). A set of replayed + sessions (scroll a long list, spring storms, typing, window resize) is a **reproducible, repo-checked PGO training + corpus**, which most apps lack. CI can produce a profile and rebuild with `-Cprofile-use` automatically, and perf + counters (instructions) gate regressions precisely. +- **Cost/risk.** Profile staleness and build time (two-stage builds); PGO varies in effect on already-branch-light + SoA code. Estimate 3-10% on scene-build/layout paths; I would not expect it to change a 120 Hz verdict. +- **Verdict.** Later. Do it for shipped release builds once the scene catalog stabilises. + +### 13. Text: cache before you SIMD — verdict: **skip SIMD; adopt cache design** + +- **Sources.** [simdutf](https://github.com/simdutf/simdutf) (GB/s UTF-8↔UTF-16 validation/transcoding; used by Node, + Bun, ghostty) [search page]; Ash Vardanian's [UTF-8 SIMD search](https://ashvardanian.com/posts/search-utf8/) [search + page]. Both target bulk text. +- **Assessment.** UI strings are short; the cost is shaping and rasterizing, not validation or transcoding. The one place + bulk text matters is the editor (rope + sum tree, PLAN §4.6), where Zed's tree already gives O(log n) offsets. An ASCII + fast-path (all bytes < 0x80 → skip bidi/script itemization, use cached advance table) is worth more than SIMD and is + ~20 lines. +- **Do instead.** Glyph-run cache keyed by `(font id, size, features, text hash)`; wrap-interval caching (idea 4); + shape off the main thread for paragraphs above N glyphs (already in plan). +- **Verdict.** Skip SIMD text; adopt ASCII fast path + caches. + +--- + +## Steal + +- Slate's four dirty classes and the **Volatile** escape hatch; avoid time-phased retainers. +- Chromium property trees: instances reference tree nodes, so animation touches nodes not geometry. +- Salsa/Incremental **early cutoff**; React Compiler's memoize-by-input-versions idea; comemo's recorded-constraint hits. +- Clay's flat arena + contiguous subtrees; ImGui's single shared vertex/index buffer per frame. +- Triple buffer for latest-wins, byte-encoded SPSC ring for ordered commands (the ring is also the replay log). +- Counting allocator as a unit test; "frame arena in the `El` lifetime". +- `debug = false` for dependencies; `unpacked` split-debuginfo on macOS. + +## Avoid + +- A general reactive dependency graph (Salsa/Adapton/AttributeGraph): conflicts with hot-patch state survival; use + version stamps. +- Retainer/offscreen caching by timer ("render on phase"): the one measured foot-gun (50.9 ms, worse than uncached). +- Cranelift on Apple until macOS unwinding and arm64 ABI land. +- `split-debuginfo = "packed"` in dev profiles (+16 s per edit). +- SIMD for text validation/transcoding; SIMD hit-testing before a counter justifies it. +- Hand-written lock-free structures when published crates work; BOLT on Mach-O. + +## Recommendation for Rune (ranked) + +1. **Property-tree scene + GPU-evaluated spring tracks** (idea 1): the one idea that can make "animation costs the CPU + nothing" literally true; spike early, with a CPU reference evaluator. +2. **Dirty classes + early cutoff + exact counters** (ideas 2, 3): gates "zero work at rest" with numbers. +3. **Frame arena in `El`'s type + counting allocator** (idea 7): a signature decision that is expensive to change later; + decide before the view API ships. +4. **Command channel = byte SPSC ring + triple buffer, loom-tested** (idea 5), doubling as the replay log. +5. **Two-line Cargo profile + measured compile baseline** (idea 10), then hot-patch hardening (idea 11). + +**Rejected alternatives:** Salsa/SwiftUI-style graph (state vs patches); Slate retainers by phase (measured regression); +Cranelift on Apple (unwinding, ABI); SIMD text (wrong bottleneck); damage-history tracking now (power only, unmeasured). + +## Open questions + +- Does wgpu's Metal backend expose a path to write instance data in place without a staging copy? (read wgpu-hal.) +- Can edge-animated rounded rects and their text be expressed as property-tree nodes, or does idea 1 need per-instance + edge tracks only? (Prototype in the spring scene catalog.) +- Is mold's Mach-O linker production-ready on macOS 27 (the README lists `macho/`)? Only matters if link time shows up + in the real Rune workspace, where the nushell data says it won't. +- Real Rune compile numbers: baseline `cargo check`, dev build, and patch time with the crate split. +- Is a layout-hash guard on models enough for agent-trusted hot patching, or do we need a full state-migration hook? +- Measure energy (not frame time) of full-pass-at-rest-with-small-change to decide whether idea 9 is worth building. diff --git a/app/vendor/rune/research/18-desktop-timeline-motion.md b/app/vendor/rune/research/18-desktop-timeline-motion.md new file mode 100644 index 0000000..3f28fe7 --- /dev/null +++ b/app/vendor/rune/research/18-desktop-timeline-motion.md @@ -0,0 +1,134 @@ +# 18. Desktop timeline motion: what the DOM branch learned + +Scope: the OpenCode Desktop session timeline on branch `timeline-motion` (PR #57224, head `39eb86d`), for the Rune +rebuild of the session page. Written 2026-10-22. Constants come from source unless marked *measured* (the +branch's `.jank` harness) or *not in code*. Bare file names are under `packages/app/src/session/timeline/`. + +## Summary + +- One spring, `timeline.growth` at 0.32 s and bounce 0 (`row-growth.ts:6-14 @ 39eb86d`), drives row growth, gap + closing, Working's glide and the send flight. Springs are analytic and keep velocity when retuned + (`packages/ui/src/motion/spring.ts:59-91 @ 39eb86d`), but per-frame pixel caps make growth frame-rate dependent. +- The streaming edge is still an open decision, and "coming back lands at the bottom" is *not in code*. + +## 1. Streaming edge and word reveal + +The four edges are one table (`row-growth.ts:31-40 @ 39eb86d`): + +| Edge | mask max | floor | shrink/frame | catch-up | duration × | clip | +|---|---|---|---|---|---|---| +| Feather | 28 px | 18 px | 1.8 px | 1 | 1 | yes | +| Fast Feather | 12 px | 6 px | 4 px | 2.4 | 0.55 | yes | +| No Mask, Word Fade | 0 | 0 | 28 px | 1 | 1 | no | + +The mask aims for `min(max, max(floor, 1.5 × leftToGrow))`, growing at most 5 px per frame (`row-growth.ts:311-317 +@ 39eb86d`). Its gradient has 72% opacity at 0.62 of its height and 28% at 0.28, rounded to whole pixels so +unchanged masks aren't rewritten (`row-growth.ts:586-597 @ 39eb86d`). + +The "15 px mask, 40 px trail" figures are *measured* means: Feather showed 15.3 px of mask with content 39.5 px +ahead of the shown height, Fast Feather 5.7 and 19.8, No Mask 0 and 37.2, Word Fade 0 and 34.7. + +Words fade in over 180 ms ease-out (`packages/session-ui/src/components/markdown.css:54-56 @ 39eb86d`); No Mask +disables the fade and Word Fade makes it 360 ms (`markdown.css:470-480 @ 39eb86d`). The stagger between words is +20 ms, shrinking to 5.5 ms as the backlog grows (`packages/session-ui/src/components/markdown-solid.tsx:22-33 @ +39eb86d`). + +Paced text shows backlogs under 512 characters at once and reveals larger ones in chunks every 24 ms, snapped to +word or punctuation boundaries (`packages/session-ui/src/message/message-content.tsx:118-222 @ 39eb86d`). A live +row also holds back a trailing partial word of up to 24 characters +(`packages/session-ui/src/timeline/session-timeline-row.tsx:80-95 @ 39eb86d`). + +## 2. Row growth + +Growing rows share one spring whose step is a budget split between them (`row-growth.ts:163-339 @ 39eb86d`). Each +frame's take is capped (`row-growth.ts:222-239 @ 39eb86d`): it starts at 1.875 px, ramps up by at most 2.2× per +frame, and is capped at 11.5 px, rising to 16 px for long distances, or 7.5 px while carrying Working. Streaming +rows slow further near their target (`(0.085 × rem + 0.65) × catchUp` within 36 px). + +Only the ramps scale with `dt`, and `dt` is clamped to 1/30 s (`row-growth.ts:356 @ 39eb86d`), so the 16 px cap is +per frame. A 457 px bubble took about 1.5 s at 30 fps headless and about 0.5 s at 60 fps (*measured*). A growth +bent toward a nearer target lands there instead of overshooting (`row-growth.ts:177-178 @ 39eb86d`). + +Growth joins follow in `settle`: rows resize without TanStack's per-row scroll correction, then one `pinEnd` write +holds the end (`virtualizer.tsx:483-540 @ 39eb86d`). Space freed by the composer or a removed row is held under the +last row and closes on the same spring after 120 ms without growth (`row-growth.ts:359-366 @ 39eb86d`). A +streaming row never shrinks below what it shows (`virtualizer.tsx:709-719 @ 39eb86d`). + +## 3. Send flight + +In `send-flight.ts @ 39eb86d`, only the composer's visible lines are cloned, clipped with `clip-path` (lines +38-58). When the bubble mounts, a clone flies on `growthSpring` with `dt` capped at 1/60 (line 189). The measure +phase re-reads the live bubble rect every frame, so flights retarget as earlier bubbles land (lines 175-180). The +clone scales uniformly by width and reveals its height through a `clip-path` inset from where the composer had +scrolled (lines 200-209). If the wraps differ by over 2 px (line 166), composer text is gone by p = 0.25 and the +clone fades in over p = 0.1-0.4; otherwise they finish at 0.4 and 0.5 (lines 210-213). + +## 4. Working tail row + +Working is its own 36 px `Activity` row at the end of the active turn (`message-timeline.tsx:229-250 @ 39eb86d`), +inside an 82 px reserved tail (`virtualizer.tsx:50-52 @ 39eb86d`). At turn end it hands off over 0.34 s, blurring +to 6 px and scaling to 0.5 while the copy button sharpens from scale 0.6 (`row-growth.ts:53-102 @ 39eb86d`, +`virtualizer.tsx:937-995 @ 39eb86d`). + +## 5. Steer promotion + +Admission used to add a 24 px "Steering" label and move Working. Now the client predicts the status a steer sent +now will get (`packages/client/src/solid/data.ts:294-305,1491-1494 @ 39eb86d`), and the just-sent bubble sits where +admission will put it (`controller.tsx:89-114 @ 39eb86d`). On promotion, Working glides on the growth spring while +the gaps it leaves shrink in proportion (`virtualizer.tsx:775-847 @ 39eb86d`). A row shrinking mid-glide joins the +glide unless it is past 75% (`virtualizer.tsx:736-752 @ 39eb86d`). + +## 6. Width-change easing + +`holdLandingWidth` gives rows their landing width when a side panel starts moving, so text wraps once +(`packages/app/src/shell/panel-motion.ts:151-200 @ 39eb86d`). Heights wait for 120 ms of stable width, then growing +rows ease to their new heights; for 400 ms a streaming row may shrink (`virtualizer.tsx:672-693 @ 39eb86d`). + +## 7. Pretext sub-line measurement + +Rows are measured with `@chenglou/pretext` where possible. While streaming, the last line's fill is measured +(`packages/session-ui/src/timeline/text-layout.ts:156-170 @ 39eb86d`) and the target height lags by up to 0.52 +(one line) or 0.82 line heights, less as the line fills, rounded to 1/64 +(`packages/session-ui/src/timeline/markdown-layout.ts:168-180 @ 39eb86d`). A new line's height arrives as it +fills. The followed row uses this `streamHeight` (`virtualizer.tsx:466 @ 39eb86d`). + +## 8. The 1/64 px grid + +Heights and offsets are rounded to 1/64 px (`row-growth.ts:16 @ 39eb86d`, `virtualizer.tsx:46-48 @ 39eb86d`). +Chromium rounds `scrollTop` to whole pixels, so `writeScroll` writes the floor, draws the remainder as a +`translate`, and defers the commit until growth settles (`virtualizer.tsx:569-636 @ 39eb86d`). Sub-pixel reversals +went from 3163 to 0 (PR body). + +## 9. Follow and coming back + +Following needs pinned, a finished cold mount, no touch and no reduced motion (`virtualizer.tsx:769-771 @ +39eb86d`). Losing it lands every growth (`virtualizer.tsx:1137-1145 @ 39eb86d`). Cold opens stay hidden until +fonts load and the bottom is pinned (`virtualizer.tsx:1421-1445 @ 39eb86d`). + +A newer requirement is *not in code*: returning to a session, tab or window paints the bottom in the first +frame, with no animated scroll, nothing that arrived while away streaming or growing, and no remembered position. +While visible and following, a target more than about a viewport away should cut instead of gliding. Today a hidden tab pauses rAF, the first frame back clamps `dt` to 0.1 s (`packages/ui/src/motion/loop.ts:61 @ +39eb86d`), growth clamps it to 1/30, and the backlog animates at the per-frame cap. Paced text doesn't flush. + +## What was hardest in the DOM + +- **Reads vs writes.** Per-frame work goes through `frameLoop.addMeasured`, which runs all reads before any writes + (`loop.ts:68-99,136 @ 39eb86d`). One stray rect read after a write forces layout. +- **Caps per frame.** Headless 30 fps looks about 2× slower than 60 fps. +- **Reflow mid-animation**, handled by landing widths and the width hold. +- **Unknown heights.** TanStack doesn't cache a measurement equal to its estimate, which looped + (`virtualizer.tsx:1069-1070 @ 39eb86d`); pretext avoids DOM measurement. +- **Main-thread stalls.** SSE now flushes on rAF (commit `31c63cef78`); a ~170 ms render task on session open + remains. +- **Masks and clip-path.** Writes are rounded and deduplicated; paint cost was never measured. + +## What Rune should guarantee + +1. Springs evaluated in time, with speed limits per second, so 30 fps and 120 Hz give the same curves. +2. Retargeting that keeps position and velocity (`spring.ts:85-86 @ 39eb86d`). +3. Synchronous text measurement, including last-line fill. +4. A measure phase before a mutate phase, enforced by the API. +5. Fractional scroll offsets and wrap-once width animation. +6. No one-frame disappearance; leaving nodes fade where they stand. +7. A global reduced-motion mode that keeps 0.11-0.2 s opacity fades. +8. A settle-all for resume that lands every track and flushes paced text before the first frame. diff --git a/app/vendor/rune/research/23-text-quality.md b/app/vendor/rune/research/23-text-quality.md new file mode 100644 index 0000000..8619a7e --- /dev/null +++ b/app/vendor/rune/research/23-text-quality.md @@ -0,0 +1,254 @@ +# 23. Text raster quality and motion + +S5 from PLAN.md. Headless bitmaps only; no window or display capture. Results +below are filled from outputs, not from the hypothesis. + +## Oracle and metrics + +`crates/rune/examples/text_quality.rs` renders Inter Regular and system SF at 11, 12, 13, 15 +and 24 pt, 1×/2×, #181818 on #eeeeee and its inverse. Five strings per size +cover prose, UI labels, digits, ambiguous letters, ligatures and a stem probe. +It exports the exact Parley glyph IDs, quarter-pixel x positions and snapped +baselines. `scripts/coretext-quality.swift` draws those same glyphs with the +same font bytes into an sRGB CoreGraphics bitmap, with grayscale antialiasing, +font smoothing and fractional positioning enabled. This isolates **raster and +blend quality**. It does not claim parity with CoreText's shaping, optical-size +selection, SF tracking or line breaking. SF is supplied from the local system +font, never redistributed. + +Measured on an Apple M5 Max, macOS 27.0.1 (26A434). Font SHA-256: + +- Inter: `40d692fce188e4471e2b3cba937be967878f631ad3ebbbdcd587687c7ebe0c82`. +- `/System/Library/Fonts/SFNS.ttf`: `44890958f3e0b997028121ed7c7a789f3f5cce227c7a93ce8f86ec0db26da571`. + +SF's registered family is `System Font`. The CoreText oracle explicitly sets +`opsz` to point size × scale, matching Parley's current variation selection. +Without this, the 2× reference uses a different SF outline. This calibration +covers regular Latin UI text, not CJK, emoji, bold/italic, arbitrary backgrounds, +or native SF tracking. The CoreText bitmap is a reference, not an AppKit capture. + +`scripts/text-quality.py` reports Gaussian SSIM (sigma 1.5, population covariance, +data range 1) on each row's ink-bounded horizontal crop. Each row gets equal +weight; full-page blank backgrounds do not inflate the score. It also reports +signed and absolute relative ink-weight error, normalized ink MAE, and per-glyph +advance-cell coverage/weight. Overlapping side bearings belong to the adjacent +cell; these are attributed cells, not independently rasterized isolated glyphs. +No image alignment search, rescaling or blur is used to improve scores. + +The phase sweep moves `lHEximno` through two device pixels, 64 timestamps per +pixel. Each frame is a separate 40 px strip rendered through the real GPU path. +Inverse-sRGB decoding recovers linear coverage; coefficient of variation, +peak-to-peak range and adjacent-frame RMS quantify brightness shimmer. This +coverage metric is separate from perceived brightness after nonlinear blending. + +## Baseline policy and constraints + +- `text.rs` already uses four x phases and whole-pixel baselines, including + negative coordinates and carry into the next pixel. Hinting is on at 1× and + off at 2×. Atlas is **2048² R8** (the older README said 1024²). +- `shader.wgsl` uses exact texel loads for ordinary text. Bilinear filtering is + reserved for scaled flight snapshots. Changing filtering for ordinary text + would add blur to already phase-rasterized glyphs. +- The baseline `runtime.rs::glyph_gamma` uses `0.78 + 0.22 * sRGB(luminance)`. +- `rune-motion/src/layer.rs::settle_after` already computes a conservative + analytic settle time; the store lands at `(target, 0)` and removes the track. + Do not replace this with frame-by-frame epsilon tests or a second text spring. +- Preserve the shaped-layout cache, retained Taffy cache, virtual rows, + reusable cluster scratch and zero-allocation presentation gate. + +## Sources inspected + +1. [Wang et al., Image quality assessment: From error visibility to structural + similarity, IEEE TIP 2004](https://ece.uwaterloo.ca/~z70wang/research/ssim/). + SSIM is a spatial image metric, not proof of native subjective equivalence. +2. [Skia, The Raster Tragedy](https://skia.org/docs/dev/design/raster_tragedy/). + Distinguishes linear blending, the guessed-background gamma hack, optical + sizing and contrast enhancement. Full-pixel grayscale gamma adjustment is + not the same as LCD subpixel correction. CoreText's optical emboldening can + depend on nominal size, unlike hinting at final pixel size. +3. Kit's Apache-2.0 GPUI fork (`kitlangton/gpui`), commit + `2e52b98886063ddfa828312c83415a14208dfe87`, + `src/platform/mac/text_system.rs:194–201, 444–458`. Five luminance buckets + (0, .25, .5, .75, 1) select CoreText smoothing through the **fill color of an + alpha-only CGContext**. This is not a five-radius morphological max filter; + blindly copying bucket numbers into swash dilation would not reproduce it. +4. [Research 15 §7](15-research-motion-perception.md): pixel-y, quarter-phase x, + analytic settling, shared container tracks, a phase-sweep brightness oracle. +5. [WebRender macOS rasterizer](https://searchfox.org/mozilla-central/source/gfx/wr/wr_glyph_rasterizer/src/platform/macos/font.rs) + probes actual OS smoothing behavior, distinguishes dilation from LCD AA, + quantizes color for its smoothing masks and preblends grayscale. Its native + CoreGraphics masks cannot be copied into a deterministic swash path. Historical + [issue 1767](https://github.com/servo/webrender/issues/1767) documents separate + light/dark weightings, not a universal gamma constant. + +## Experiments + +| Experiment | Decision | Evidence | +|---|---|---| +| Independent swash oracle, default hinting, zero emboldening | Control | All four Inter GPU images and phase metrics equal production baseline. | +| No hinting at 1× | Keep with calibrated weight | Inter 1× dark SSIM .971615 → .981808; light .958593 → .964075. Alone it makes light-mode weight slightly worse. | +| 3×3 max-filter coverage dilation plus gamma sweep | Reject | A diagnostic approximation, not CoreText's outline smoothing. Broadens outside pixels and needs extra work; centered outline emboldening wins. | +| Centered swash outline emboldening, .1 device px | Partial | Improves 2× weight but overweights 1× light-on-dark with the old exponent. | +| Centered emboldening, .1 point (.1/.2 device px), scale-aware exponent | Keep | Weight error improves in all eight font/polarity/density groups; SSIM improves in seven. SF dark 1× is the exception below. | +| Fixed exponent `.375 + .875 * sRGB(luminance)` | Reject | Good static Inter fit, but SF dark 2× brightness variation regresses. The final density-aware expression improves all eight brightness probes. | +| Five luminance-keyed atlas copies | Reject for this pass | kitlangton/gpui's buckets invoke CoreText, not five interchangeable swash radii. A single shape plus continuous blend correction avoids up to 5× cache cardinality and bucket jumps during theme animation. | +| Bilinear filtering of ordinary glyphs | Reject | Quads already land on device pixels with rasterized x phases. Resampling them again softens text; flight filtering remains separate. | + +Calibration used the first two strings at each size; the remaining three were +held out. With .1/.2 device-pixel centered emboldening, the best gamma-only +training fits were .45/.45 for dark-on-light and 1.15/1.20 for light-on-dark. +The retained candidate uses one continuous expression, +`0.35 + (1.15 + 0.2 * clamp(scale - 1, 0, 1)) * sRGB(foreground_luminance)`. +This balances static weight with phase-dependent brightness, rather than +minimizing the training error alone. Outline expansion is recentered in both axes: +swash's `embolden(d)` adds +`d` translation as well as expansion. The cache key includes `d`: 12 pt at 2× +and 24 pt at 1× have the same pixel size but different nominal-size smoothing. +An early build emitted empty quads for spaces because emboldening gives empty +outlines nonzero bounds. Rejecting all-zero masks restores the original instance +count; the phase/cache test includes whitespace to prevent recurrence. + +The offline `coverage-*.png` diagnostic overwrites overlapping glyph masks; it +is only a parameter-search approximation. All static results below come from +actual GPU source-over output, not that approximation. + +### GPU results, Inter + +All SSIM values are row-crop means. Weight is mean absolute row ink-weight error. + +| Mode | SSIM before → after | Weight error before → after | +|---|---:|---:| +| Dark, 1× | .971615 → .980707 | 7.46% → 6.46% | +| Dark, 2× | .982463 → .985549 | 11.93% → 6.32% | +| Light, 1× | .958593 → .982740 | 30.14% → 4.04% | +| Light, 2× | .968310 → .990795 | 22.84% → 3.46% | + +### GPU results, SF + +| Mode | SSIM before → after | Weight error before → after | +|---|---:|---:| +| Dark, 1× | .949609 → .948209 | 8.10% → 6.20% | +| Dark, 2× | .977342 → .979416 | 12.42% → 7.13% | +| Light, 1× | .923434 → .950077 | 30.69% → 2.68% | +| Light, 2× | .963039 → .986747 | 23.87% → 2.80% | + +The SF dark 1× SSIM loss is .001400 (held-out strings: .950056 → .949516), +despite better average weight. This is a deliberate tradeoff for better light +text weight and lower phase brightness variation, not universal CoreText parity. +The other seven held-out groups improve. Per-font/stage aggregates are in +`demo/text/metrics.json`. `scripts/text-quality.py` regenerates full row and +attributed-glyph results, including 11/12/13/15/24 pt separately, in the ignored +run directory. The public report deliberately omits that large diagnostic data. +Group means hide size-specific losses: dark 1× SF at 24 pt loses .017929 SSIM, +and dark 1× Inter at 13 pt loses .010482. The retained policy favors the combined +weight/motion result; it is not a per-size static optimum. + +### Motion + +The production quarter-phase/pixel-baseline policy and conservative analytic +settle were already implemented. Keep them rather than introducing a second +text spring or switching hinting during motion. Two focused tests exercise +negative origins, phase carry, four cached phases per glyph, different nominal +sizes at equal pixel size, exact analytic landing, 120 identical resting samples +and no atlas writes after phase warmup. The warmed streaming allocation gate +still passes (zero allocations). + +| Probe | Before | After | +|---|---:|---:| +| Raw coverage CV, 1× | .03688% | .02164% | +| Raw coverage CV, 2× | .01896% | .01165% | +| Inter display ink CV, light 1× | 1.54294% | .99005% | +| Inter display ink CV, dark 1× | .71390% | .20733% | +| Inter display ink CV, light 2× | .43394% | .27093% | +| Inter display ink CV, dark 2× | .46632% | .14171% | +| SF display ink CV, light 1× | 2.15455% | 1.65172% | +| SF display ink CV, dark 1× | .50179% | .23311% | +| SF display ink CV, light 2× | 1.20865% | .75191% | +| SF display ink CV, dark 2× | .22162% | .13237% | + +Display ink is the polarity-normalized sRGB pixel difference from the background, +computed with the shader's exponent and linear source-over equation from the GPU +coverage sweep. It is not a psychophysical flicker threshold. Residual variation +is nonzero; the result supports **less shimmer**, not an unqualified “no shimmer”. +SF raw-coverage CV improves too, but its 1× peak-to-peak coverage rises from +.08582% to .10970%, and adjacent-frame coverage RMS from .01386% to .01444%. +Thus not every raw metric improves. This is a 13 pt horizontal stem probe at +virtual timestamps, not physical display cadence or a whole-font motion audit. + +## Performance + +Headless release on the same M5 Max, 120 Hz virtual time, one warmup and seven measured runs +per workload. Each pair alternates the saved original binary and the final one; +pair order reverses on successive runs. Synthetic fixtures only. +CPU includes update/build/encode/submit, excludes readback and is not GPU latency. +Both binaries end with **1,126 instances**. The atlas remains 2048² R8, four x +phases, no color-keyed copies, and warmed presentation still allocates nothing. + +| Workload | CPU p50 before → after | CPU p95 before → after | First CPU frame before → after | +|---|---:|---:|---:| +| Stream | .313 → .295 ms | .665 → .604 ms | 4.98 → 5.39 ms | +| 2,000-message stream | .327 → .311 ms | 3.891 → 3.695 ms | 9.70 → 10.40 ms | + +The machine was contended. p95 MADs were .171/.115 ms for stream and .203/.241 ms +for long-stream; first-frame MADs .55/.88 and .15/1.05 ms. Do not claim a speedup. +No warmed-frame regression is evident; a small first-raster cost remains possible. +Earlier unpaired baseline/final medians (.259/.334 ms stream p50) drifted with +load, so the paired comparison is authoritative. All paired runs and MADs are +retained in `demo/text/performance.json`. Research/19's structural caches, +virtualization and cluster scratch were not changed. + +Saved executable SHA-256: +before `c2bb31da0a331b0fc68e9edbd228ac7df1e42ff3058851d32655d49f4f0cdb44`, +after `e4c7d51a1ef2b8b05fdc6ec1d9e66944d7cc39c5fc5ce1a312a28c5f86d8b368`. + +## Images and goldens + +`demo/text/{inter,sf}-{light,dark}-{1,2}x.png` shows before / after / CoreText, +one representative line at each of the five sizes. `*-diff-*.png` shows absolute +pixel error amplified 4×. `*-phases-*.png` shows nine raw-coverage positions. +`ui-crops.png` contains actual settings/OpenCode/kit before/after crops. + +Inspected light/dark crops: dark-on-light stems gain the missing weight, rounded +edges remain antialiased, and 2× light-on-dark edges lose some bloom. Advance +positions and baselines stay fixed. SF 1× still has visible raster differences +from CoreText. The kit's Linux Chromium reference is a different oracle; its +scores need not improve when moving toward macOS weight. + +`scripts/text-goldens.py` refreshes seven settings/OpenCode stills, two kit index +images and twelve kit side-by-sides. It keeps the committed web columns and +recomputes Rune plus the diff, without another browser capture. Updated scores +live in `demo/text/kit-metrics.json`. +The streaming still is standardized to `--at 4`; its former capture time was +not recorded, so its change includes that state adjustment. Historical motion +strips/videos retain their recorded states and are not current text goldens. + +## Reproduction + +```sh +mkdir -p .lab-output/text/target/perf +cargo test -p rune quality_tests +cargo test -p rune --test alloc +cargo build --profile perf -p settings -p kit-gallery # (the OpenCode fixture example has since moved out of this repository) +cargo build --release -p rune --example text_quality +swiftc -O scripts/coretext-quality.swift -o .lab-output/text/coretext-quality +cp target/perf/{opencode,settings,kit-gallery} .lab-output/text/target/perf/ +cp target/release/examples/text_quality .lab-output/text/ + +# Headless bitmaps on the measurement host. Repeat for SFNS.ttf / "System Font". +FONT=crates/rune/assets/Inter-Regular.ttf +.lab-output/text/text_quality perf/autoresearch/text/before/inter "$FONT" Inter auto 0 legacy +.lab-output/text/text_quality perf/autoresearch/text/after/inter "$FONT" Inter +.lab-output/text/coretext-quality perf/autoresearch/text/before/inter +.lab-output/text/coretext-quality perf/autoresearch/text/after/inter +uv run --with numpy --with pillow --with scikit-image scripts/text-quality.py perf/autoresearch/text/before/inter +uv run --with numpy --with pillow --with scikit-image scripts/text-quality.py perf/autoresearch/text/after/inter +# After both fonts: +uv run --with numpy --with pillow scripts/text-report.py perf/autoresearch/text demo/text +mkdir -p target/perf target/release +cp .lab-output/text/target/perf/{opencode,settings,kit-gallery} target/perf/ +cp .lab-output/text/target/perf/{opencode,settings,kit-gallery} target/release/ # for text-goldens.py +python3 scripts/bench-ui.py --only stream,long-stream --out perf/autoresearch/text/perf-after +python3 scripts/text-bench.py --before .lab-output/text-before/target/perf/opencode \ + --after target/perf/opencode --out perf/autoresearch/text/perf-paired-new +uv run --with numpy --with pillow scripts/text-goldens.py +``` diff --git a/app/vendor/rune/research/24-reference-renderer.md b/app/vendor/rune/research/24-reference-renderer.md new file mode 100644 index 0000000..973d832 --- /dev/null +++ b/app/vendor/rune/research/24-reference-renderer.md @@ -0,0 +1,192 @@ +# 24. Reference renderer and differential testing + +Reader: the next agent changing Rune's renderer. Run the commands +below before changing a tolerance or a shader formula. + +`crates/rune-ref` evaluates Rune's current instance stream on the CPU and checks +the production wgpu renderer against it. The first corpus found a glyph sampling +bug: interpolated screen coordinates selected an adjacent atlas column. Its +single-primitive regression differed by up to 83 channel levels before the fix. +After the fix, measured single-primitive errors are at most 1 level; composited +scenes reach 2. The gate allows 2 per channel and **zero outlier pixels**. + +## The oracle evaluates the formulas Rune actually ships + +The scalar evaluator implements the five instance kinds present when this work began: + +| Kind | Reference behavior | +|---|---| +| 0 | Per-corner rounded-rect SDF, clamped capsule radii, softness, and an inset border (uniform or per-side) over the fill, hiding it by its alpha before opacity (`params[3]`) | +| 1 | Evan Wallace shadow formula, the shader's erf approximation and four y samples | +| 2 | R8 glyph texel loads, scaled bilinear footprints, coverage exponent; `params[0]` turns the quad about its centre and samples bilinearly in the glyph's own frame | +| 3 | Inset shadows with spread, offset and the sharp/blurred branch at sigma .3; square corners take exact pixel areas | +| 4 | Vertical premultiplied-linear gradient with rounded-rect coverage | + +Every kind uses the shader's four independent soft clip ramps. Expanded quad +bounds are included, since the GPU cannot shade outside its triangles. Outlines +and capsules already lower to rounded-rect instances. Positions are device pixels. +Translation, positive glyph scale and glyph rotation are the transforms the current +instance ABI supports for these five kinds. The generator keeps glyph rotation at zero: +at arbitrary angles a turned edge can pass within the rasterizer's sub-pixel precision of +a pixel centre. `rotated_glyphs` covers quarter turns, whose edges stay half a pixel away. Arbitrary affine transforms, path rendering, group +opacity and backdrop blur are not covered by this oracle. + +During the publication rebase, main added vector segment/triangle kinds 5 and 6 +(`d666064`). Those new kinds are rejected by this oracle's validator and are not +generated yet; extending the independent formulas and corpus is follow-up work. + +`vello_cpu` was considered, as PLAN §6c requests. Its path-area coverage would +introduce a second antialiasing definition, and its rounded-box blur need not +match Rune's four-sample approximation. A direct evaluator is a closer oracle +for our WGSL. Vello remains a good candidate for the future path renderer. +The CPU implementation is independent code, not generated from the shader. +That catches implementation drift; it cannot prove a shared mathematical model +is visually correct or that the four-sample shadow approximates a true Gaussian. + +The CPU lane uses strict scalar Rust f32 operations, fixed loop order, no +`mul_add`, and pinned `libm = 0.2.16` with `force-soft-floats` for +sqrt/exp/pow/round/floor. That feature disables libm's architecture shortcuts even +when another workspace dependency enables its default `arch` feature. Gate scripts +also pass `-C llvm-args=-fp-contract=off`; do not enable fast-math. Each blend +decodes the previous sRGB RGBA8 pixel, applies premultiplied source-over, and +quantizes back to sRGB RGBA8. Alpha stays linear. Clear is quantized too. +Sixteen BLAKE3 hashes in `goldens.json` pin the canonical corpus. Cross-architecture +byte equality still needs the Linux run; it is a design goal, not measured evidence. +The sixteen hashes agree in debug and optimized release builds on arm64; the +release check explicitly disabled FMA contraction. CPU-target Clippy passed with +warnings denied. The CLI regression replay reports node 4, `generated/3`, at +13,34 and a maximum GPU delta of 1 with no outliers. + +The CPU-only build has no Rune/wgpu/window/font dependency. `--features gpu` +adds a field-by-field adapter to **Rune's real Renderer**, including its shader, +blend state, atlas upload and sRGB Offscreen readback. `Primitive::from_instance` +accepts real emitted instances with a node/source sidecar. Frozen atlas bytes in +a JSON scene make replay independent of subsequent font/shaper changes. + +## One generator drives the checks + +`generate::scene` decodes a vector of bounded 32-byte records. Each record controls +kind, geometry, per-corner radii, colours/alpha, border, softness/sigma, clip/fades, +inset offsets and glyph scale. Text cases add real Parley/embedded-Inter runs and +freeze their atlas; those cases check sampling, not shaping correctness. Synthetic +atlas texels have guard space so the tests do not rely on undefined out-of-bounds +GPU texture loads. `generate::seeded` provides a stable SplitMix64 corpus. + +The shape follows Vello's `cpu_gpu_differential` target [1]: structured bounded +inputs, two persistent renderer implementations, a per-channel comparison, +and saved replay cases. Rune uses proptest rather than cargo-fuzz. Proptest +shrinks both the vector and its fields, persists failure seeds, and writes the +final minimized GPU failure as `crates/rune-ref/failures/minimized.json`. +`RUNE_REF_FAILURES` overrides that output directory for worker artifact collection. +Move understood cases into `regressions/`; the test replays every JSON there. + +CPU metamorphic tests require exact bytes for integer translation, opacity-zero +identity, full-viewport clip identity, and reorder of disjoint clipped groups. +The GPU runs the same four relations. Translation/full clip allow 2 levels; +transparent additions and disjoint order require exact equality. Comparison never +uses an image average that could hide an incorrect edge. + +### Measured budget on Apple M4 Pro / Metal + +Rust 1.99.0 on an Apple M4 Pro build worker; no windows or screen captures. One successful corpus run contains 128 generated scenes × 8 isolated +primitives, 128 composites, and 16 pinned-font text scenes. + +| Primitive | Measured maximum channel delta | Gate | +|---|---:|---:| +| Rounded rect / border / capsule | 1 | 2 | +| Outer shadow | 1 | 2 | +| Glyph, including scaled synthetic atlas | 1 | 2 | +| Inset shadow | 1 | 2 | +| Vertical gradient | 1 | 2 | +| Eight-primitive composite | 2 | 2 | + +There are no permitted outliers. One LSB covers rounding around an RGBA8 encoding +boundary; the second covers accumulated blend/encode rounding. This is an +empirical bounded-corpus budget, not a theorem or a cross-vendor certification. +WGSL allows FMA fusion and reassociation [2], and sRGB conversion accuracy adds +another backend-dependent rounding step. Measure Vulkan/D3D12 before claiming +their budget. Never increase the cap to hide a large geometric/texel mismatch. + +Also passed: 128 GPU proptest scenes, 128 CPU metamorphic cases, 32 GPU +metamorphic scenes, and the saved glyph regression. The allocation gates passed +for 30 warmed CPU-reference frames and Rune's existing 30-frame streaming runtime +test. These exclude scene construction, shaping/commit and GPU/driver allocations. + +## The glyph regression fixes a discontinuity + +`regressions/glyph-texel-boundary.json` came from seed 15, primitive 4. Its glyph +starts at x=10.5. At a pixel center x=13.5 the intended local coordinate is 3, +but triangle interpolation can produce a value just below 3. `floor` then loads +column 2. Before the fix, 231 pixels exceeded the 2-level cap, maximum delta 83. + +The glyph branch now uses fragment `@builtin(position).xy` for its texel lookup, +which is the rasterizer's pixel center. Both nearest and bilinear glyph sampling +use it. Other primitive formulas and clip interpolation are unchanged. The saved +case and full corpus pass. No existing PNG golden was rewritten. Fractionally +positioned glyphs can intentionally change where the old lookup selected the wrong +texel; existing app-wide snapshot equivalence has not been measured in this pass. + +Harness corrections during bring-up: avoid translating the sentinel NO_CLIP +bounds beyond the replay validator's coordinate limit; permit Rune's actual +2048² atlas rather than the README's historical 1024² size. Neither was a +production shader failure. The first compile also caught a mutable-array borrow +in generator setup. All were corrected before the successful runs above. + +## A differing pixel names its last contributor + +`Frame::new(width, height, true)` enables a primitive-index buffer. A positive +source alpha records the last contributing primitive, so transparent draws do +not erase provenance. `Frame::blame` resolves it to the node ID and source key +(which can be a file:line string supplied by an app). Diff JSON includes the first +outlier's x/y, expected/actual RGBA, node and source. This is top-contributor blame, +not a claim that the top node caused every error under translucent overlays. + +```sh +cargo run -p rune-ref --features gpu -- \ + --scene crates/rune-ref/regressions/glyph-texel-boundary.json --diff --blame 13,34 +``` + +`--seed N --save scene.json` creates a replay file. Without `--diff`, the CLI +needs no GPU and prints the exact BLAKE3 hash. Invalid scene geometry/atlas data +is rejected before upload. The optional provenance buffer is allocated once; +repeated rendering allocates nothing. + +## Exact gates are scripts, with Linux instruction measurement pending + +```sh +sh scripts/check-reference.sh --gpu +``` + +That runs exact CPU hashes/metamorphic properties, both allocation gates, GPU +differential fuzzing and saved regressions. The normal command without `--gpu` +still runs the production runtime allocator test, but does not initialize wgpu. + +`benches/instructions.rs` uses gungraun 0.20.0 [3,4] to count one fixed warmed +reference frame. Scene/frame allocation and destruction sit outside the measured +function. `scripts/check-reference-instructions.sh save` records a named base; +`check` compares the candidate, failing above **+0.5% instructions**. It checks +the Rust/Valgrind/runner version manifest and refuses a missing baseline marker. +Run both revisions on the same Linux worker with the same Cargo target directory. +Install the matching `gungraun-runner --version 0.20.0` and Valgrind first. + +No Linux worker was available when this was written, so instruction counts and +the Linux-only benchmark have not been executed. No instruction +number or performance improvement is claimed. These scripts are ready for any Linux runner. The first Linux run must validate the benchmark and save its baseline. + +## Sources and remaining verification + +1. [Vello fuzz README](https://github.com/linebender/vello/blob/main/fuzz/README.md). Its default permits 2 per channel and 4 outlier pixels; + Rune intentionally permits zero outliers. +2. [WGSL floating-point evaluation](https://www.w3.org/TR/WGSL/#floating-point-evaluation) + and research/14 §3 for FMA/reassociation and tolerance policy. +3. [Gungraun regression guide](https://github.com/gungraun/gungraun/blob/main/docs/src/regressions.md). Version 0.20 uses `Callgrind::soft_limits`. +4. [Gungraun baselines](https://github.com/gungraun/gungraun/blob/main/docs/src/cli_and_env/baselines.md). +5. Rune `shader.wgsl` and `render.rs`; research/12 and /14; PLAN tenet 7 and §6c. + +Every Renderer caller supplies target dimensions as the viewport, so fragment +position has the required coordinates. Static glyphs are pixel-snapped, which +keeps their texel choices unchanged. Non-Linux workspace benches skip cleanly; the +instruction-gate script still rejects non-Linux execution. + +Remaining: Linux instruction execution, x86/arm CPU hash comparison, Vulkan/D3D12 +budget measurement, broader app snapshot comparison, and the new vector kinds. diff --git a/app/vendor/rune/research/25-code-highlighting.md b/app/vendor/rune/research/25-code-highlighting.md new file mode 100644 index 0000000..1cc106d --- /dev/null +++ b/app/vendor/rune/research/25-code-highlighting.md @@ -0,0 +1,86 @@ +# Syntax highlighting in Markdown code fences + +How rune-kit colours fenced code, and why it uses hand-written scanners instead of a grammar +engine. + +## What it has to do + +- Colour the languages chat answers use most: TypeScript/TSX/JavaScript, JSON, Rust, Swift, + CSS, HTML, shell, SQL and YAML. Anything else stays plain. +- Treat the input as untrusted: model output can be huge or adversarial, so time must be linear + in the source with no backtracking, and work per block must be capped. +- Stream without layout shift: a fence grows a line at a time, and colouring must not move a + glyph. +- Build everywhere Rune builds, including wasm and iOS, without adding much to binaries. + +## Options + +**syntect** (Sublime Text grammars). The most accurate of the three for many languages, but +it ships a serialized grammar set (hundreds of KB to a few MB, depending on the languages kept), +loads it lazily at a noticeable startup cost, and its grammars rely on regexes with lookaround, +run by `onig` (C) or `fancy-regex`. Both backtrack, so a crafted line can take super-linear +time. Highlighting is per line with carried state, which fits streaming, but the cost and the +backtracking risk don't fit untrusted chat text. + +**tree-sitter**. Real incremental parsing and the best structure, but each language is a +generated C parser (the TypeScript and TSX grammars alone are large), the runtime is C, and +highlighting needs a query file per language. Every target, wasm and iOS included, then needs a +C toolchain, and the size cost is several hundred KB per language. It is the right tool for an +editor, more than a chat transcript needs. + +**Hand-written scanners** (chosen). One small byte scanner per language family (C-like, shell, +markup, CSS, SQL, YAML), in the same spirit as the native mermaid renderer. Each only moves +forward; lookaheads are bounded (a regex literal at most 512 bytes) or skip bytes the scanner +would otherwise visit; embedded code (template `${}`, JSX `{}`, `<script>`, `$()`) nests at most +three deep. Pure Rust, no dependencies, no data files, wasm-friendly. The cost is semantic +precision: it recognises tokens, not grammar, so an unusual construct can colour slightly +wrong. For reading an answer that is an acceptable trade, and the scanners err toward leaving +text plain. + +## Decisions + +- **Colour only.** Spans set a brush and nothing else: no weight, italic or size, so shaping + sees the same runs and glyph positions are identical with and without colour. A unit test + lays out the same code plain, coloured and part-coloured and compares every glyph quad. +- **Streaming.** An unclosed fence colours its complete lines only; the line still arriving + draws plain and takes its colour when its newline arrives. +- **Caps.** The first 32 KiB of a block (cut at a line end) and at most 8192 coloured runs; + the rest draws plain. Results are cached per (language, source) for the last 32 blocks on + the thread, the same bound as the parse cache. +- **Colours.** Eight token kinds from `MarkdownStyle`. Defaults use fixed familiar hues (violet + keywords, green strings, orange numbers, teal types, blue functions, rose properties) at one + lightness and chroma derived from the theme's text colour, and the theme's muted and faint + text for punctuation and comments. Theme status colours were tried as the hue source, but + they vary too much between themes (one theme's "info" is magenta) to keep kinds apart. +- **No new feature flag.** The scanners are about a thousand lines of plain Rust with no + dependencies, so they live under `markdown`. +- **`Block` keeps its shape.** Each code block's language travels beside the parsed blocks + rather than in a new `Block` variant, so apps that match on `Block::Code` keep working. + +## 2026-11: Desktop's own lexers, translated + +OpenCode Desktop doesn't highlight with a TextMate engine. Its diffs, file views and Markdown use +Pierre's Highlights (`@pierre/highlights`, Apache-2.0): 80 hand-written lexers, written in +WebAssembly Text and shipped as one 183 KB module, whose tokens are Zed capture names that +Desktop's theme maps to its `syntax-*` colours. The scanners above covered 20 of those +languages and coloured 82.9% of their samples' bytes as Desktop does. + +Options, measured on a Windows x64 desktop shared with other builds, with one sample per language, repeated to 1,000+ lines, +optimised builds; sizes are the growth of a minimal binary: + +| Option | Languages | Native size | Web (wasm32, gzip) | ms per 1,000 lines | Same colours as Desktop | +|---|---:|---:|---:|---:|---:| +| Hand-written scanners (before) | 20 | +81 KB | +25 KB | 0.1-0.4 | 82.9% | +| Highlights, translated to Rust (chosen) | 80 | +429 KB | +175 KB | 0.16-0.37 quiet, 0.56-0.70 loaded (V8 runs the module at 0.24 and 0.58-0.72) | 100% (tokens identical) | +| Highlights in an interpreter (wasmi) | 80 | about +2.9 MB | the browser's own WebAssembly | 8.4 | 100% | +| syntect, 75 Sublime grammars | 75 | +2.46 MB | - | 147 (warm) | TextMate scopes; see Shiki | +| Shiki's grammars (TextMate, JS or Oniguruma) | 80 | 3.9 MB of grammar JSON (487 KB gzip) + engine | - | 41-49 | 81.0% | +| tree-sitter, 8 grammars (parse only) | 8 | +16.2 MB | needs a C toolchain | 2.4-15.4 | different grammar and queries | + +The choice: `crates/rune-highlights` translates `highlights.wasm` to Rust in `build.rs` +(`codegen/translate.rs`, about 550 lines over `wasmparser`), so the same lexers run natively on +every target with no runtime and no compiling on users' machines. Its tokens are identical to +the module's in V8 on all 80 samples and 3,360 fuzzed sources (mutations, deep nesting, random +text); 200,000-deep nesting runs on a 1 MiB main-thread stack. A block streaming in uses +Highlights' stream mode: 0.044 ms per new line at 5,000 lines, against 1.5 ms to lex the whole +block again. A trap (a bug in the lexers) draws the code plain instead of panicking. diff --git a/app/vendor/rune/research/26-system-material-sync.md b/app/vendor/rune/research/26-system-material-sync.md new file mode 100644 index 0000000..11884f5 --- /dev/null +++ b/app/vendor/rune/research/26-system-material-sync.md @@ -0,0 +1,81 @@ +# 26. Native materials in step with Metal frames + +Reader: the next agent changing `system_material/macos.rs`, frame pacing on macOS, or the +present path. Re-run the lab below before changing either. + +`El::system_material` puts an `NSGlassEffectView` (macOS 26+) or an `NSVisualEffectView` +popover behind a transparent window's CAMetalLayer and sets its frame, corner radius and +alpha in the same `CATransaction` as the frame's drawable (`presentsWithTransaction`). This +note records what that buys, what it costs, and the one thing still limiting it. + +## How it was measured + +`examples/glass-card` with `GLASS_CARD_PATTERN=black` flies a card over a black window and +draws a 2 px magenta border on the card's edge. Over black the glass shows as a flat dark +grey, so each frame gives two edges: Rune's (magenta) and the native view's (grey). The +screen was captured at 120 fps (ScreenCaptureKit, 1x) on a MacBook Pro with a 120 Hz display +running macOS 27. For each frame with the card moving at least 2 px, a script measured how far +grey extends past the magenta edge, or black shows inside it, on rows and columns through the +card. The left and top edges are clear of the fading text and button, so they are the ones +counted. Cadence comes from `GLASS_CARD_TRACE` traces of the card window, as gaps between +submissions in display periods. + +## Results + +| Path | Moving frames with the glass edge off by more than 4 px | Frames one period after the last | +|---|---|---| +| Glass, synced (default) | 26 of 1421 (1.8%) | 70% | +| Glass, synced, main thread busy 8 ms a frame | 0 of 325 | about 60 Hz (the busy loop alone takes 8 ms) | +| Popover (`legacy`), synced | 2 of 538 (0.4%) | 98% | +| Glass, `unsynced` (views committed before the present) | 178 of 605 (29%) | 78% | +| Fallback fill (`off`) | n/a | 99% | + +Seven synced Glass runs ranged from 0 to 4% of moving frames, clustered in a few flights. + +- **The synced glass never lags.** Every miss is the glass one frame ahead: Rune's content + shows frame N while the glass is already at N+1. At the card's speed that is 10 to 14 px. + Unsynced shows the same one-frame gap on about a third of moving frames. +- **A busy main thread doesn't break the sync.** It delays the views and the drawable + equally, because both wait for the same transaction. +- **Glass is expensive to move.** `NSGlassEffectView` runs a SwiftUI graph on every frame or + radius change: `layoutSubtreeIfNeeded` takes 0.8 to 2 ms a frame (the radius makes no + difference). Skipping that call only moves the cost into the transaction commit. The popover + view costs about 0.2 ms. +- **That cost, not the transaction, drops Glass below 120 Hz.** With the fallback fill a + frame takes about 0.5 ms of CPU, and with Glass about 3.2 ms (median). The display link + refuses a tick that comes less than half a period after the last present (`permits` in + `display_link.rs`), so any frame over 4.2 ms skips the next one. In one trace, 192 of the + 219 frames over that line were followed by a skip. Skipped frames let the CPU clock down, + which makes the next glass layout slower. + +## Getting Glass to 120 Hz (not landed) + +Two experiments, env-gated and since removed, show what it would take: + +| Pacing change | Frames one period after the last | Glass edge off by more than 4 px | +|---|---|---| +| Drop the half-period check | 97% | 11 of 313 (3.5%) | +| Measure the half period from the last frame's start, not its present | 98.5% | 97 of 555 (17%) | +| Frame start, and wait for the GPU before presenting | 99% | 11 of 703 (1.6%) | + +Running at full rate without the GPU wait makes the misses much more common. wgpu's +`presentsWithTransaction` path only waits until the command buffer is scheduled +(`waitUntilScheduled`), so a drawable can join the transaction before it has rendered. The +WindowServer then applies the views and keeps showing the previous drawable for a frame. +Waiting for the GPU before the present (`device.poll(Wait)`) closes most of that gap. With the +stock pacer, Glass runs near 80 fps; there the wait made no clear difference to the misses +(0 and 21 frames in two runs) and lowered cadence to 62%. + +The pacing change affects every app's frame timing, so it belongs in its own change. The +existing pacer test (`late_frames_and_idle_restarts_cannot_catch_up_in_a_burst`) expects a +present-based check in one case, where a callback arrives 2 ms after an early present. + +## Notes for the implementation + +- `presentsWithTransaction` is read when wgpu acquires a drawable, so the first frame that + finds a material is dropped and redrawn once the flag is set. +- AppKit builds a glass view's backdrop layers on its first visible frame, so views are made + and parked at zero alpha, never hidden. A hidden one shows unrefracted for a frame when shown. +- The host view is flipped and returns nil from `hitTest:`, so winit's view gets every event. + AppKit can reorder sublayers, so each frame checks that the Metal layer is still above the + host's layer. diff --git a/app/vendor/rune/research/27-long-note-editing.md b/app/vendor/rune/research/27-long-note-editing.md new file mode 100644 index 0000000..44c77dc --- /dev/null +++ b/app/vendor/rune/research/27-long-note-editing.md @@ -0,0 +1,138 @@ +# 27. Editing a long Markdown note + +Reader: someone deciding how a notes app should hold a note in Rune, or changing text layout, +text paint or `TextEdit` history. Re-run the bench below before and after changing any of them. + +The question: can one multi-line `text_input` hold a whole ~50 KB Markdown note and stay +smooth at 120 Hz (8.3 ms a frame)? It can scroll, move the caret and follow it at any size +measured. It can't type at 50 KB: every keystroke reshapes the whole note, at 12 ms. + +## How it was measured + +`crates/rune/examples/long_note.rs`, headless, no window: + +``` +cargo run --profile perf -p rune --example long_note --features frame-profile -- \ + --sizes 5,50,200 --samples 60 --gpu [--blocks] +``` + +The note is generated from fictional words: headings, wrapping paragraphs, lists, task lists, +quotes and fenced code, at 8.9 KB (142 lines), 54 KB (861 lines) and 207 KB (3,289 lines). It +sits in a 760 × 900 pt scroll viewport at 2x, in 15 pt type. Each case times an input and the +frame it commits, in thread CPU. `--gpu` adds the renderer's encode and submit time on a +headless GPU, which stayed under 0.5 ms (p95) in every case. `--blocks` splits the note at blank +lines into one keyed field per block (about 1,600 fields at 200 KB). Numbers below are medians +(p95 in brackets) in ms, from an M4 Pro Mac mini. + +## Results: one field for the whole note + +| Case | 5 KB | 50 KB | 200 KB | +|---|---|---|---| +| Type a character (start, middle or end) | 2.2 (2.5) | 12.0 (12.2) | 45.7 (46.6) | +| Return | 2.0 (2.1) | 12.0 (12.3) | 46.2 (49.2) | +| Backspace | 2.0 (2.1) | 12.0 (12.4) | 46.4 (48.9) | +| Paste 2 KB | 2.4 (2.5) | 12.5 (12.8) | 47.7 (50.0) | +| Cmd+Z right after the paste | 0.12 (0.14) | 0.32 (0.35) | 0.74 (0.81) | +| Scroll frame | 0.10 (0.13) | 0.10 (0.12) | 0.09 (0.12) | +| Down arrow | 0.12 (0.15) | 0.19 (0.23) | 0.41 (0.46) | +| Cmd+Down to the end | 0.17 (0.22) | 0.23 (0.26) | 0.51 (0.56) | +| Click to place the caret | 0.11 (0.18) | 0.16 (0.18) | 0.39 (0.42) | + +Caret-follow held at every size: across 120 Down presses the caret never left the viewport, +which moved at most one line (22 pt) per press; Cmd+Down landed at the end with the caret in +view; 30 of 30 clicks placed the caret where clicked without moving the viewport. + +Memory (heap growth over the process before the note opened, MB): + +| | 5 KB | 50 KB | 200 KB | +|---|---|---|---| +| Opened | 5.5 | 9.8 | 24.8 | +| After 50 typed characters | 10.3 | 18.8 | 45.6 | +| After 200 | 10.5 | 18.8 | 45.6 | +| Undo steps kept of 100 small pastes | 53 | 9 | 2 | + +## Why typing costs what it does + +`TextSystem::layout_blocks` caches a layout under a hash of the field's whole text, so an edit +anywhere misses and Parley lays out the whole string again: font selection, text analysis, +HarfRust shaping and line breaking, about 0.22 ms per KB. A profile of 200 KB typing puts all +of the frame there. Cmd+Z right after an edit is cheap because the previous text's layout is +still in the cache (stale layouts stay for two commits, and longer within a 64 KB budget). + +Memory follows from the same thing: a whole-note layout is roughly 90 bytes of heap per byte +of text, and while typing two are alive, the current one and the previous one. + +Undo depth comes from `TextEdit`'s history: up to 128 steps within 1 MB, where each step holds +a full copy of the text before and after it. A long note fits only a few steps: about +1 MB ÷ (2 × note size). Typing coalesces a run of keystrokes into one step, so a step is a burst +of typing or one paste, but a 200 KB note still forgets everything before the last two. + +## What was fixed: paint walked every line + +Before this change, painting a text walked every glyph of its layout, looking each up in the +atlas, and only then dropped the glyphs outside the clip. A 200 KB note in a scroll view spent +5.4 ms of every frame on that, scrolling included. Paint now binary-searches the layout's lines +for the clip's band (with two ems of slack for ink past a line box) and walks only those. The +per-glyph clip test still decides what draws, so the output is unchanged: the glyph counts +match before and after in every case. + +| Case, median ms | 5 KB | 50 KB | 200 KB | +|---|---|---|---| +| Scroll frame | 0.27 → 0.10 | 1.46 → 0.10 | 5.45 → 0.09 | +| Down arrow | 0.30 → 0.12 | 1.58 → 0.19 | 5.81 → 0.41 | +| Click | 0.31 → 0.11 | 1.57 → 0.16 | 5.78 → 0.39 | +| Type a character | 2.44 → 2.19 | 13.68 → 11.96 | 51.46 → 45.72 | + +The test `a_long_scrolled_text_paints_only_its_visible_lines` checks that a glyph on a text's +last line isn't rasterized until it's scrolled into view. + +## Results: one field per block (`--blocks`) + +| Case | 5 KB | 50 KB | 200 KB | +|---|---|---|---| +| Type a character (middle) | 0.31 (0.36) | 0.82 (0.96) | 2.6 (3.2) | +| Type at the start | 0.22 (0.28) | 0.69 (0.87) | 3.0 (4.4) | +| Return | 0.27 (0.34) | 0.77 (0.96) | 2.5 (2.8) | +| Backspace | 0.28 (0.29) | 0.66 (0.82) | 2.4 (3.0) | +| Paste 2 KB | 0.70 (0.75) | 1.38 (1.58) | 3.4 (4.5) | +| Scroll frame | 0.10 (0.12) | 0.12 (0.17) | 0.18 (0.22) | +| Heap after 200 typed characters, MB | 7.2 | 11.7 | 27.1 | +| Undo steps kept of 100 | 100 | 100 | 100 | + +An edit reshapes one block (0.03 to 0.6 ms). What's left grows with the number of blocks: +building, diffing and laying out every field each commit, about 2.2 ms at 1,600 fields. + +## What's left, and a plan + +- **Typing in one field: whole-note reshape (12 ms at 50 KB).** Lay out each hard paragraph + (text between `\n`s) as its own Parley layout, cached under that paragraph's text, spans and + style, and stack them under a composite layout with a line index. An edit then reshapes one + paragraph. It's a large change: caret geometry, hit-testing, selection boxes, decorations, + pills, block indents, elision and the glyph walk all take one `parley::Layout` today, and all + would go through the composite. +- **Undo depth.** Store each step as its changed byte range (the removed and inserted text) + plus the small mark, block and soft-break lists, so a step costs its edit, not the note; + check an undo still applies by length and a hash rather than comparing full copies. +- **Per-commit work proportional to the note** (about 0.3 ms at 200 KB, outside text shaping): + the whole text is hashed for the layout cache and copied into the view on each rebuild. + Small; it goes away with paragraph layouts. +- **Many blocks.** `El::virtualize` would make a block-per-field note's commits independent of + its length, but in a first try a focused field inside a virtualized stack reported its caret + (`ElementInfo::caret`, which caret-follow also uses) away from its row, and a field revealed + with `Tx::scroll_into_view` didn't take typing headlessly. That needs its own look before a + notes app relies on it. + +## Advice for a notes app + +- Up to about 10 KB, one field per note is fine: 2 ms a keystroke. +- Beyond that, use one keyed field per Markdown block (paragraph, list, quote, code fence). That + stays under 1 ms a keystroke at 50 KB and under 4 ms at 200 KB, keeps a full undo history per + block, and holds a few MB instead of two whole-note layouts. +- Moving between blocks becomes the app's job: Up and Down at a block's first or last line move + focus to the neighbouring block; Backspace at a block's start merges it into the one above; + Return splits it; a selection across blocks and an undo spanning blocks need an app-level + model. +- Handle Return. In a multi-line `text_input`, plain Return in a paragraph submits (to + `on_submit`, or the default button when there is none), while Shift+Return and Option+Return + type a newline (as does plain Return inside a rich list, quote or code block). An editor + gives each field an `on_submit` that splits the block or inserts `"\n"`. diff --git a/app/vendor/rune/research/28-resize-rewrap.md b/app/vendor/rune/research/28-resize-rewrap.md new file mode 100644 index 0000000..e9fb72e --- /dev/null +++ b/app/vendor/rune/research/28-resize-rewrap.md @@ -0,0 +1,113 @@ +# 28. Resizing a window with a long Markdown note + +Reader: someone changing text layout or its cache, or deciding how a notes app shows a long +note. Re-run the bench below before and after changing either. + +The question: can a window showing a long Markdown note (`rune_kit::Markdown` in a scroll +view) be resized at 120 Hz (8.3 ms a frame)? Before this change it couldn't at 50 KB: every +frame of a live resize shaped every wrapped text of the note again, 16 ms a frame. Now a width +change only re-breaks lines, and a frame costs 4.6 ms. + +## How it was measured + +`crates/rune-kit/examples/markdown_resize.rs`, headless, no window: + +``` +cargo run --profile perf -p rune-kit --example markdown_resize --features markdown,frame-profile -- \ + --sizes 5,50,200 [--memo] +``` + +The note is generated from fictional words: headings, wrapping paragraphs with bold, italic, +inline code and links, bullet, numbered and task lists, quotes and fenced code, at 5.4 KB +(71 texts), 52 KB (645 texts, 1,364 layout nodes) and 202 KB (2,501 texts, 5,381 nodes). Only +32 texts are on screen at a time. The window is 900 pt tall at 2x; `resize` steps its width +from 900 to 600 pt and back in 1 pt steps, one frame per step (600 frames), as a live resize +does. Each frame is timed in thread CPU, split into the runtime's phases. Numbers are medians +(p95 in brackets) in ms from an M4 Pro Mac mini, the before and after builds run back to back. + +## Results + +| Resize frame | 5 KB | 50 KB | 200 KB | +|---|---|---|---| +| CPU, before | 1.57 (1.67) | 16.1 (17.1) | 70.6 (75.4) | +| CPU, after | 0.55 (0.59) | 4.6 (5.1) | 23.2 (24.0) | +| Text (shaping and line breaking), before | 1.08 | 11.9 | 49.2 | +| Text, after | 0.06 | 0.70 | 3.2 | +| Texts shaped per frame, before → after | 42 → 0 | 401 → 0 | 1,565 → 0 | +| Texts re-broken per frame, after | 42 | 401 | 1,565 | + +Scrolling (0.24 ms a frame at 50 KB) and opening the note (17 ms at 50 KB, 70 ms at 200 KB, +one shaping per distinct text) are unchanged. + +## What was slow + +`TextSystem` caches each layout under a hash of its text, spans, style, scale *and wrap width*. +A width it hasn't seen misses, and Parley lays the text out from scratch: font selection, +text analysis, HarfRust shaping, then line breaking. During a live resize every width is new, +so every frame shaped every wrapped text in the note, on screen or not (the column has to know +each block's height for its scroll extent). + +Only line breaking depends on the width. Parley's `LayoutBuilder::build` shapes; a built +`Layout` can be broken again with `break_all_lines` (or Rune's block-indent and pill breaker) +and aligned again, which clears its old lines and leaves the shaped runs alone. Alignment and +justification are stored per line, so nothing from an earlier width carries over. + +## What changed + +The cache key splits in two. A *shape key* hashes what shaping reads: text, spans, style, +scale, `wrap_anywhere` and pills. The *layout key* adds the width, alignment and block indents. Beside the +layout cache, an index maps each shape key to the layout key of the latest layout of that +shaping. A miss on the layout key whose shape key has a cached layout clones that layout +(a flat copy of its glyph and run arrays) and breaks and aligns the copy at the new width, +about 2 µs for a paragraph against about 30 µs to shape it. + +- Memory: the index holds no layouts, only keys, and drops an entry when its layout is + evicted. Layouts are kept and evicted exactly as before (one per text and width, two commits + and then the stale-text budget), so a resize holds what it held before. +- Secure text still bypasses the shared cache entirely: it neither reads nor feeds the index. +- Everything that reads a layout (carets, hit testing, selection boxes, decorations and span + rings, visible-line culling, `max_lines` and elision, alignment and justification) gets a + layout with the same lines and glyph positions as one built from scratch at that width. The + test `a_new_width_rebreaks_without_shaping_and_matches_a_fresh_layout` checks this bit for + bit across eight widths (zero and unbounded included) for spans of every kind, all four + alignments, `wrap_anywhere`, right-to-left and justified right-to-left text, CJK, emoji and math fallbacks, + monospace tabs, indented blocks and pills, and that none of it shapes. +- Measuring: Taffy measures a wrapped text at its definite width only (`w_full` texts in a + column are stretched, so min- and max-content aren't asked for), and the final pass asks for + the same width, so each wrapped text costs one re-break per resize frame and nothing else. + A `max_lines` text's trial cuts go through the same cache, so a cut tried at the last width + is re-broken rather than shaped. + +## What's left + +At 50 KB a resize frame is now 4.6 ms, comfortably inside 120 Hz. What it spends, all of it in +proportion to the note's 1,364 layout nodes, since none of the note is virtualized: + +| 50 KB resize frame, after | ms | +|---|---| +| View (building the Markdown tree again) | 0.78 | +| Flattening the tree into layout nodes, and the pass after layout | about 0.85 | +| Taffy layout | about 1.15 | +| Text line breaking | 0.70 | +| Apply (mounting, layout animation targets) | 0.81 | +| Paint | 0.22 | + +At 200 KB the same split is 23 ms: view 3.4, Taffy 5.8, line breaking 3.2, apply 4.8, the +rest flattening. A sample of it puts 11% in moving node structs (flatten and apply) and 5% in +hashing whole texts again in Taffy's measure callback, which asks about three times per text +per layout. + +A plan, most to least effect: + +1. **Virtualize long Markdown.** Build and lay out only the blocks near the viewport, keeping + measured heights per width for the rest (`El::virtualize`). That makes a resize frame + independent of note length. It needs an estimate for blocks never measured at the current + width, which a cheap re-break of their cached shapes can now supply. +2. **Skip the view on a viewport-only commit.** A resize rebuilds the view and flattens it even + when nothing the view read changed. Reusing the last flattened tree when no view read the + viewport or a layout would save view and flatten: about 1.6 ms at 50 KB, 8 ms at 200 KB. +3. **Hash each text once per commit.** Flattening already hashes every text for Taffy's cache; + passing that hash to the measure callback and the final pass saves the repeats, about 5%. + +An app can take some of the view cost today by memoizing the note's subtree on its revision +(`rune::memo`, `--memo` in the bench): view drops from 0.78 to 0.54 ms at 50 KB. diff --git a/app/vendor/rune/research/29-scroll-frame-cpu.md b/app/vendor/rune/research/29-scroll-frame-cpu.md new file mode 100644 index 0000000..cc4cccb --- /dev/null +++ b/app/vendor/rune/research/29-scroll-frame-cpu.md @@ -0,0 +1,25 @@ +# Scroll-frame CPU + +Fixtures: 1,000 plain rows, a long Markdown document, 40 sticky sidebar sections, +and a 1,000-row growth timeline receiving a row every 12 frames. Each drives +480 wheel deltas at virtual 120 Hz, reversing halfway, with the pointer inside. + +Metric: median thread CPU from wheel dispatch through draw-list construction; +GPU submission is excluded. One warmup and nine alternating before/after pairs. +Build instructions are in `scripts/bench-ui.py`; run with +`python3 scripts/bench-ui.py --frame-cpu --scroll --out target/scroll --runs 9`. + +Kept: skip unchanged default hover targets and gate interaction lookups on styles. +Improvement is the median paired ratio; CPU columns are medians in milliseconds. + +| Fixture | Before | After | Improvement | +| --- | ---: | ---: | ---: | +| Plain list | 0.401 | 0.306 | 22.1% | +| Markdown | 0.187 | 0.177 | 4.30% | +| Sticky sidebar | 0.333 | 0.276 | 18.9% | +| Growth timeline | 0.473 | 0.416 | 13.2% | + +Next proposals: +- Retain scroll-subtree geometry and conservatively cull branches. +- Commit and measure only changed growth rows, retaining keyed row structure. +- Index hover/press candidates instead of scanning every node twice per frame. diff --git a/app/vendor/rune/research/30-overlay-gpu-cost.md b/app/vendor/rune/research/30-overlay-gpu-cost.md new file mode 100644 index 0000000..e91c26b --- /dev/null +++ b/app/vendor/rune/research/30-overlay-gpu-cost.md @@ -0,0 +1,140 @@ +# Overlay GPU cost: Rune vs hand-written Metal + +Fixture: `crates/rune/examples/overlay_hud_cost.rs`, a 360×80 overlay whose compositor clears +the drawable in one render pass at 120 Hz with an empty Rune view. The comparison is +`research/overlay-cpu/metal_hud.swift`, the same panel cleared by hand from a CVDisplayLink +callback with one command buffer per frame. + +Metric: retired instructions per frame for the whole process (`proc_pid_rusage`), because the +test Mac moves between a fast and a slow CPU mode that changes CPU time by 2× but not +instruction counts. CPU percentages are from paired slow-mode runs. Runs alternate (3 or 4 +rounds), 8 to 10 s each after a 2 s warmup, on a real window. + +## Per frame + +| | Rune | Rune with the wgpu patches | Metal | +| --- | ---: | ---: | ---: | +| Command buffers committed | 6 | 2 | 1 | +| Completion handlers | 2 | 1 | 0 | +| Render encoders, presents | 1, 1 | 1, 1 | 1, 1 | +| Heap allocations | 65.1 | 55.1 | – | +| Kinstructions | ~1,555 | ~1,118 | ~850 | +| Process CPU | ~19.5% | ~16.0% | ~11.2% | + +Rune submits once per frame and, with no writes, its staging submits and recycles nothing. +The six command buffers are wgpu's: + +1. `(wgpu internal) Transit`: wgpu-core's barrier buffer for the submitted command buffer. Empty on Metal. +2. `(wgpu internal) Pre Pass`: the pass's barriers. Empty on Metal. +3. The render pass. +4. The surface texture's transition to PRESENT at `Queue::submit`, which gets the fence signal and a completion handler. Empty on Metal. +5. `Queue::present` → `prepare_surface_texture_for_present` submits again with a second signal and handler. That's a PRESENT→PRESENT barrier: no backend lists PRESENT among the usages that skip barriers. +6. wgpu-hal's present, which presents the drawable from a command buffer of its own. + +wgpu 30.0.1 is the latest release, and wgpu's main branch has the same code, so an upgrade +doesn't help. Two small patches do (`research/overlay-cpu/*.patch`, against 30.0.1): + +- `wgpu-core-present-skip.patch`: when the texture needs no clear and every pending transition + is from PRESENT, return without a submission. This affects every backend: Vulkan also leaves + PRESENT out of its ordered usages. +- `wgpu-hal-metal-lazy-command-buffer.patch`: a Metal command encoder makes its MTLCommandBuffer + on first use, so an encoding that records nothing commits nothing. The submit signals on the + last non-empty buffer. This is a prototype. Before sending it upstream, `raw_command_buffer()` + should make the buffer for `as_hal` callers, and the strict-event-sync wait value should be + read at `begin_encoding`. + +With the Metal HUD made to do what wgpu does, the gap is driver work per command buffer: + +| Metal HUD shape | Kinstructions | +| --- | ---: | +| 1 command buffer, present on it | ~848 | +| Present from its own command buffer, 1 handler (the patched shape) | ~929 | +| 2 extra empty buffers, split present, 1 handler | ~1,105 | +| 4 extra empty buffers, split present, 2 handlers (wgpu's shape) | ~1,213 | + +## By thread (8 s, both processes at once, ms) + +| | Driver and dispatch threads | Present thread | Main | Display link | Total | +| --- | ---: | ---: | ---: | ---: | ---: | +| Rune, patched | 650 | 205 | 183 | 21 | 1,059 | +| Metal | 468 | – | 3 | 296 | 767 | + +- Driver threads: `_submitAvailableCommandBuffers` (271 ms), completion notifications + (~100 ms), drawable presents (~50 ms). This cost scales with command buffers and handlers. +- Present thread: wgpu-hal into Metal 134 ms (commits, present), wgpu-core 43 ms, Rune ~1 ms. +- Main thread, standalone 10 s profile, patched: + - `acquire` 154 ms, of which `nextDrawable` 125 ms. Metal's display link spends the same on + `nextDrawable`. + - Rune's own work is about 105 ms: `frame::step` 46 (`step_motion` 34, the empty view's + `build` 23), `about_to_wait` 22 (pointer observe 7), `render_frame` 18, `submit_and_present` + 11 (the hand-off send 9), `PresentWorker::wait` 5, occlusion check 3. + - wgpu's `create_view` on the surface texture is 10 ms. +- The app's own work, which Metal does on its display link, is not in these runs. + +## Writes + +A frame that writes a buffer costs about 310 kinstructions more, whether it uses `Queue::write_buffer` +or `Frame::write_buffer`. Either way wgpu-core records the copy in a command buffer of its own +(`PendingWrites`, or the encoder's own buffer ahead of the pass), with a blit encoder. + +| Writes per frame | Queue | `Frame::write_buffer` | +| --- | ---: | ---: | +| 0 | ~1,558 | – | +| 1 | ~1,863 | ~1,881 | +| 4 | ~1,966 | ~1,918 | + +Staging maps its chunk once per frame however many writes share it, so each extra write costs +~12 kinstructions against ~35 for a queue write. + +## Rune's own frame + +Each change stacks on the one before. The fixture also prints the main thread's instructions +(`thread_selfcounts`), which isolate Rune's share from the driver threads. Medians of 6 +alternating rounds, 10 s each, no writes, unpatched wgpu: + +| Build | Main kinstructions | Main µs | Process kinstructions | Present thread ms/s | +| --- | ---: | ---: | ---: | ---: | +| Before | 161.9 | 149 | 1,395 | 17.0 | +| Claim the display link's frame before waiting on the present thread | 153.3 | 134 | 1,398 | 16.4 | +| Skip the pointer sample when nothing reads it | 148.3 | 127 | 1,388 | 15.5 | +| Read occlusion once a turn | 144.2 | 118 | 1,384 | 15.3 | +| Leave a still runtime alone while only the compositor animates | 139.2 | 102 | 1,371 | 14.9 | +| Skip the staging when nothing is staged | 140.8 | 109 | 1,375 | 13.7 | + +- The main thread does 13% fewer instructions. The process total moves by about as much as the + run-to-run spread (±50 kinstructions), because driver threads dominate it. +- A Time Profiler run on the main thread finds `frame_step` and `step_motion` (14 of 117 samples + before) gone once the runtime rests. What's left is `acquire`, mostly `nextDrawable`. +- Allocations stay at 65.1 a frame: they are wgpu's and Metal's, not Rune's. + +## Writes with immediates + +A compositor that asks for `Features::IMMEDIATES` gets the adapter's immediate size (4 KB on +Metal), so it can hand a frame's uniforms to `RenderPass::set_immediates` instead of writing a +buffer. Three writes a frame, same rounds: + +| Path | Process kinstructions | Main kinstructions | Allocations | Command buffers, blit encoders | +| --- | ---: | ---: | ---: | ---: | +| `Queue::write_buffer`, before | 1,708 | 277 | 82.1 | 7, 1 | +| `Queue::write_buffer`, after | 1,696 | 258 | 82.1 | 7, 1 | +| `Frame::write_buffer`, before | 1,679 | 166 | 85.1 | 7, 1 | +| `Frame::write_buffer`, after | 1,650 | 144 | 85.2 | 7, 1 | +| Immediates | 1,405 | 148 | 71.1 | 6, 0 | + +Immediates cost what a frame with no writes costs: no copy, so no command buffer and blit +encoder for it. A uniform ring in `MAPPABLE_PRIMARY_BUFFERS` memory was not tried. It would also +skip the copy, but it needs its own fencing per frame in flight, and it isn't available on every +backend. + +## What's left + +- Ship the wgpu fix. A `[patch]` in Rune's workspace doesn't reach apps that pin Rune. A git + dependency on a wgpu fork would, but every app that names `wgpu` itself would have to follow + it. Upstreaming both patches is the clean route. +- Without wgpu changes, Rune could acquire drawables from the CAMetalLayer itself, wrap each + texture with `create_texture_from_hal`, and present on its own command buffer after the frame's. + That would remove buffers 4 to 6 and one handler, about 110 kinstructions of driver work by the + Metal HUD's measure plus wgpu-core's present path. In exchange, Rune would bypass wgpu's + surface on macOS. +- Rune's main thread is now about 10% of the process's instructions, most of it `acquire`. The + rest of the cost is wgpu's command buffers and Metal's driver threads. diff --git a/app/vendor/rune/research/31-layout-text-cost.md b/app/vendor/rune/research/31-layout-text-cost.md new file mode 100644 index 0000000..e2808a1 --- /dev/null +++ b/app/vendor/rune/research/31-layout-text-cost.md @@ -0,0 +1,264 @@ +# 31. Where a frame goes: Taffy, Parley and Rune + +Reader: someone deciding whether to replace Taffy or Parley with engines built for Rune, or +looking for the next big CPU or memory win in a frame. Re-run the bench below before and after +a change to layout, text or the commit path. + +The question: how much of a real frame's CPU time, allocations and heap belong to Taffy, to +Parley and its font stack (Fontique, HarfRust, Swash, ICU), and to Rune's own code? + +The short answer: outside of shaping, Rune's own code is most of every frame. Taffy is 5% to +16% of a frame and Parley 0.4% to 20%, so the most either replacement could save there is +under 0.9 ms a frame. Shaping is the one place Parley dominates: 73% of opening a long note and 98% of +typing in one. Both cases come from shaping text whose shape is already known, and a cache +above Parley could avoid that without replacing it. + +## How it was measured + +`crates/rune-kit/examples/layout_text_cost`, headless, no window: + +``` +CARGO_PROFILE_PERF_DEBUG=limited cargo build --profile perf -p rune-kit \ + --example layout_text_cost --features markdown,frame-profile +target/perf/examples/layout_text_cost # timing +target/perf/examples/layout_text_cost --mode sample --repeat 3 --out s.txt # CPU profile +target/perf/examples/layout_text_cost --mode heap --out h.txt # allocation stacks +python3 scripts/cost-attribution.py symbolize s.txt --exe target/perf/examples/layout_text_cost > s.syms +python3 scripts/cost-attribution.py report s.txt s.syms --top 12 +``` + +Each case starts on a fresh runtime, lets it settle, then times its frames: + +| Case | What each frame does | +|---|---| +| `stack` | A settings-like column of 60 cards of switches, badges and buttons, not virtualized (5,283 layout nodes, 2,040 texts). Each frame flips one switch. | +| `stack-same` | The same column. Each frame re-runs the view with nothing changed. | +| `list` | 10,000 rows of three texts under `virtual_rows` (278 nodes mounted). Each frame scrolls two rows. | +| `edit` | One multi-line `text_input` holding a 50 KB note. Each frame types a character. | +| `md-resize` | A 50 KB Markdown note in a scroll view (1,268 nodes, 614 texts). Each frame steps the width 1 pt, 900 → 600 → 900, as a live resize does. | +| `md-same` | The same note. Each frame re-runs the view with nothing changed. | +| `md-open` | The first frame of a fresh runtime showing the note, so every text is shaped. | + +The note is generated from fictional words, like the one in [28](28-resize-rewrap.md). + +Three probes ran inside the example, since no system profiler was available on the build +machine: + +- **Timing.** Each frame's thread CPU time comes from `rune/frame-profile`, split into its + phases. Five runs alternated case order (forward, reverse, forward, …). The tables give the + median of the five runs' medians and p95s. Most runs landed within 5% of that median. One + run each of `stack-same` and `md-resize` was 19% and 24% slower, likely because of the other + jobs on the machine. +- **CPU sampling.** A thread suspends the main thread every 200 µs, walks its frame pointers + and resumes it. 208,000 samples over three repeats of every case. A sample belongs to the + innermost frame that isn't std, `alloc`, `core`, hashbrown and the like. Time in `malloc` + or `free` goes to *Allocator*, which also records who called it. In the tables, allocator + time counts toward its caller's bucket. Symbols come from `atos -i`, so inlined frames + count too. +- **Heap.** A counting global allocator records the stack of every allocation during the + measured frames, plus what is still live once the case settles. + +Machine: an M4 Pro Mac mini, `--profile perf`. It was running other build jobs at the time, +with a load average around 15. + +Buckets: + +- **Taffy:** `taffy::*`, including `Style` comparisons and drops in flatten. It doesn't + include the text measure callbacks Taffy calls. +- **Parley:** `parley`, `parley_engine`, HarfRust, read-fonts and skrifa (shaping), ICU and + bidi (text analysis), Fontique (font queries and fallback) and Swash (glyph raster). It also + includes Rune's clone of a shaped `Layout` before re-breaking it (see below), which exists + only because Parley breaks a layout in place. +- **Rune:** the `rune` crate and `rune_motion`. +- **View:** `rune_kit`, Markdown and the bench's own view code. +- **Instr.:** the frame-profile clock. Only builds with that feature pay for it. + +## Results + +### CPU time per frame + +The ms columns are thread CPU, median (p95). The bucket shares come from the samples. The +last three columns are the frame with that bucket's share removed: the most a free Taffy, a +free Parley, or both could save. + +| Case | ms | Rune | View | Taffy | Parley | Instr. | Taffy = 0 | Parley = 0 | Both = 0 | +|---|---|---|---|---|---|---|---|---|---| +| stack | 10.2 (13.6) | 86.8% | 7.2% | 5.6% | 0.4% | 0.0% | 9.6 | 10.2 | 9.6 | +| stack-same | 9.9 (11.7) | 86.6% | 7.8% | 5.1% | 0.5% | 0.1% | 9.4 | 9.9 | 9.4 | +| list (mean) | 0.44 | 72.7% | 2.9% | 5.3% | 18.2% | 0.5% | 0.41 | 0.36 | 0.33 | +| edit | 15.5 (17.1) | 1.6% | – | 0.1% | 97.8% | 0.1% | 15.5 | 0.34 | 0.33 | +| md-resize | 4.56 (5.87) | 53.7% | 6.4% | 15.6% | 19.6% | 4.5% | 3.85 | 3.67 | 2.96 | +| md-same | 1.98 (2.49) | 80.1% | 12.9% | 4.8% | 2.2% | 0.1% | 1.88 | 1.94 | 1.84 | +| md-open (one frame) | 18.3 (21.3) | 19.1% | 1.5% | 5.0% | 72.8% | 1.2% | 17.4 | 5.0 | 4.1 | + +`list` frames come in two kinds. Most mount nothing new (median 0.15 ms). Every few frames, +new rows mount and get shaped (p95 1.16 ms). The samples cover all frames, so the shares are +for the mean. + +The allocator takes 11% of `stack`, 12% of `md-resize`, 10% of `md-same` and under 6% +elsewhere. Most of that is Rune's: 9.4 of the 11 points in `stack`. In `md-resize` it splits +4.9 points Rune, 5.2 Parley and the layout clone, 1.6 Taffy. + +The Parley column broken down: + +| Case | Shaping (HarfRust) | Analysis (ICU, bidi) | Fontique | Line breaking | Layout building and glyph iteration | Clone before re-break | Swash raster | +|---|---|---|---|---|---|---|---| +| edit | 82.8% | 8.6% | 2.5% | 2.5% | 1.3% | – | – | +| md-open | 50.2% | 6.3% | 4.5% | 2.5% | 3.0% | – | 4.4% | +| md-resize | 0.5% | – | – | 7.6% | 2.4% | 3.8% + 2.8% allocator | – | +| list | 7.8% | 0.7% | 1.0% | 0.2% | 8.0% | – | – | + +In `list`, "layout building" is mostly paint walking Parley's lines and glyph runs to place +glyphs. + +What the time-mode phases say: + +| Case, ms | View | Commit | Layout | of which Text | Apply | Paint | +|---|---|---|---|---|---|---| +| stack | 2.41 | 8.54 | 0.058 | 0 | 2.92 | 1.09 | +| stack-same | 2.42 | 8.37 | 0.012 | 0 | 2.84 | 1.06 | +| edit | 0.01 | 15.36 | 15.25 | 15.21 | 0.06 | 0.12 | +| md-resize | 0.64 | 4.20 | 1.99 | 0.79 | 0.82 | 0.26 | +| md-same | 0.57 | 1.67 | 0.002 | 0 | 0.40 | 0.24 | +| md-open | 0.64 | 16.93 | 14.92 | 13.25 | 0.43 | 1.26 | + +Commit includes view, layout and apply. Layout includes text. + +### Allocations per frame + +Calls to the allocator per frame, by the owner of the allocating code, and bytes allocated +per frame: + +| Case | Total | Rune | View | Taffy | Parley | Bytes | +|---|---|---|---|---|---|---| +| stack | 45,657 | 39,293 (86%) | 6,290 | 74 | 0 | 30 MB | +| stack-same | 45,586 | 39,293 (86%) | 6,290 | 3 | 0 | 30 MB | +| list (mean) | 1,350 | 1,153 | 91 | 41 | 65 | 1.4 MB | +| edit | 1,176 | 87 | 1 | 14 | 1,074 (91%) | 3.8 MB | +| md-resize | 21,198 | 8,503 (40%) | 2,641 | 4,956 (23%) | 5,099 (24%) | 12 MB | +| md-same | 10,744 | 8,100 | 2,641 | 3 | 0 | 7 MB | +| md-open | 31,264 | 14,270 | 2,641 | 5,669 | 8,684 | 35 MB | + +The biggest single sources: + +- `flatten::node_path`: 4 allocations per node per frame. That's 21,130 of the 45,657 in + `stack`, and 5,070 in each Markdown case. +- `El::child` growing children `Vec`s: 4,742 allocations but 16 MB a frame in `stack`. An `El` + is large, so a few children take kilobytes, and each doubling copies them. +- `flatten` itself (one per node), `El::key`, and the label `String`s. +- Taffy's flexbox: `generate_anonymous_flex_items` and the `FlexLine` vectors allocate on every + layout of a flex container. That's 4,170 allocations per frame in `md-resize`. +- Parley's line breaker clones `BreakerState`, which owns a vector, once per line: 1,030 of + `edit`'s 1,176 allocations. +- The layout clone before re-breaking copies seven vectors per text: 3,540 allocations and + 2.2 MB per frame in `md-resize`. + +### Heap + +What is live once a case settles, by owner (MB = 10⁶ bytes): + +| Case | Live | Rune | Taffy | Parley | Other | +|---|---|---|---|---|---| +| stack (5,283 nodes, 2,040 texts) | 57.9 MB | 41.3 | 11.0 | 5.4 | 0.2 | +| list (278 nodes, 165 texts, 10,000 rows) | 11.4 MB | 8.0 | 0.7 | 0.8 | 1.9 (row data) | +| edit (1 field, 50 KB) | 19.2 MB | 5.3 | 0.02 | 13.8 | 0.1 | +| md-resize (1,268 nodes, 614 texts) | 20.8 MB | 13.3 | 2.8 | 3.9 | 0.9 (Markdown) | + +Per node and per text: + +| Owner | stack | md-resize | +|---|---|---| +| Taffy's node (`Style`, layout cache) | 2.1 KB / node | 2.2 KB / node | +| Rune's flattened node | 2.4 KB / node | 2.5 KB / node | +| `rune_motion` store and scene | 3.5 KB / node | 3.3 KB / node | +| Parley layout | 2.6 KB / text (short labels) | 6.3 KB / text, 76 bytes per byte of text | + +One 50 KB field holds 13.8 MB of Parley, about 270 bytes per byte of text. 7.8 MB of that is +`ShapedText`'s reserved runs, clusters and glyphs, and 4.3 MB is HarfRust's buffer. That buffer +grew to fit the whole text and stays that size. The glyph atlas's CPU copy is a fixed 4.2 MB +per runtime and counts toward Rune in every row. + +## Text: how much is re-shaping text that was shaped before + +- **Resize (`md-resize`): none.** Since [28](28-resize-rewrap.md), a width change re-breaks + 395 texts a frame and shapes none. The rewrap costs 0.8 ms of text time, which is Parley's + line breaking, cloning the shaped layout before breaking it (7.1% with its allocations), and + hashing (below). A word-shape cache would save nothing here. +- **Typing (`edit`): almost all of it.** Each keystroke shapes the whole 50 KB note as one + text: 15.2 ms, 83% of it in HarfRust. The note has 7,201 words and 772 distinct ones, and + one word changed. Splitting the field into paragraphs ([27](27-long-note-editing.md)) + removes nearly all of it, with no word cache needed. +- **Opening (`md-open`): most of it, if the cache is per word.** The 404 texts shaped hold the + same 7,201 words, of which 772 are distinct. A cache keyed by (word, style, font) would + shape 11% of them and could cut the 9.2 ms of HarfRust in this frame by up to about 8 ms. + That is an upper bound. The note's generator draws from a small vocabulary, so real prose + repeats words less. Shaping a word alone also loses context across word boundaries, which + some scripts and fonts need, so a cache like this needs a fallback for them. The list's + 10,000 rows have 149,438 words and 10,050 distinct ones (6.7%). + +## Layout: how much is re-solving unchanged subtrees + +- **When one switch flips (`stack`), almost none.** Taffy spends 0.058 ms laying out 5,283 + nodes, and 0.012 ms when nothing changed. Its cache already skips the clean subtrees. In + `stack`, Taffy's 5.6% is spent in flatten, not in layout: comparing and dropping `Style` + values to decide whether a node's style changed. Most of that goes to the grid fields Rune + never sets (`Style::eq` 1.0%, the grid track and placement comparisons 1.6%). +- **During a resize (`md-resize`), there are no unchanged subtrees to skip in Taffy's + terms.** Every node's available width changes, so every cache entry misses. Taffy's own + work is 15.6% of the frame (0.71 ms, about 0.56 µs per node), including about 4,170 + allocations for flex items and lines. Some subtrees end up the same size anyway (code blocks + and short lines that fit at both widths). Counting those would need instrumentation inside + the runtime, which this pass didn't add. Skipping all of Taffy's work is still at most 0.71 + ms. +- **Measure calls.** `text_hash` runs once per text in flatten, once in `measure_view`, and on + each Taffy measure call. Its time in each place puts Taffy's measure calls at about four per + text per frame during a resize. Each call hashes the whole text with SipHash before it + checks the cache. + +## The biggest costs + +Rune's own code: + +1. **Re-running and re-committing a view that didn't change.** `stack-same` costs 9.9 ms a + frame for 5,283 nodes: 1.9 µs, 8.6 allocations and 5.7 KB allocated per node. The time + splits into apply (27%), flatten (15%), paint (11%) and view building (10%, plus 6% in kit + components and 7% in the allocator). The allocations are `node_path` (4 per node) and + children `Vec`s of large `El`s. In `stack`, `rune_motion`'s `AnimationStore::set_raw` and + its OKLab conversion take 8%. +2. **Hashing whole texts on every measure.** `text_hash` (SipHash over the full text, its + spans and style) is 11.2% of `md-resize`, about 0.5 ms, and 4.4% of `stack`. Flatten + already computes the same hash. Passing it into measure would remove most of the cost. +3. **Cloning a shaped layout to re-break it:** 7.1% of `md-resize`, with 3,540 allocations a + frame. +4. **Heap per node:** about 2.5 KB in the flattened node and 3.3 to 3.5 KB in the motion store + and scene, against Taffy's 2.1 KB. +5. Instrumentation: frame-profile's clock costs 4.5% of `md-resize`, because a timing scope + opens on every re-break. Builds without the feature don't pay it, so a production + `md-resize` frame is closer to 4.35 ms than 4.56 ms. + +Dependencies: + +1. **HarfRust shaping** when a text is shaped: 50% of `md-open` and 83% of `edit`. A new + engine would still have to shape. What would make this cheaper is shaping less (paragraphs + for editing, maybe words for opening), and that works on top of Parley. +2. **Taffy during a resize:** 15.6%, 0.71 ms, and a quarter of the frame's allocations. + Elsewhere it's 5% or less, mostly `Style` comparison in flatten. +3. **Parley memory:** about 270 bytes of heap per byte of text in one large field, and 76 in + a Markdown note. +4. **Parley's per-line `BreakerState` clone:** 1,030 allocations per keystroke at 50 KB. + +## What headless leaves out + +- The GPU side: encoding, glyph and image uploads, submit, and waiting for presentation. Glyph + rasterizing on the CPU (Swash) is included. [30](30-overlay-gpu-cost.md) and + [29](29-scroll-frame-cpu.md) cover the GPU side. +- Delivery of real window events: winit, IME and the OS text input services, and the resize + handshake with the window server. +- Other threads. Rune does all of this work on the main thread, so a single-thread profile is + complete for these phases, but it says nothing about contention with other threads. +- Cache warmth in a real app. Each case runs on a fresh runtime in a process that has already + run the earlier cases. A real app's caches may be colder (after other windows) or warmer. +- Startup. The system font list is built once per process, before any timed frame. + `md-open` does include font matching and fallback queries (Fontique, 4.5%). +- The probes' own cost. The sampler stops the main thread for a few microseconds per sample, + and heap mode makes every allocation slower. Timing runs used neither probe. diff --git a/app/vendor/rune/research/32-engine-plan.md b/app/vendor/rune/research/32-engine-plan.md new file mode 100644 index 0000000..a049e42 --- /dev/null +++ b/app/vendor/rune/research/32-engine-plan.md @@ -0,0 +1,459 @@ +# 32. Layout and text engines: verdicts and frame-cost plan + +Reader: someone deciding whether Rune should build its own layout engine (replacing Taffy) or +text engine (replacing Parley), or choosing the next frame-time and memory wins in `rune`, +`rune-motion` and `rune-kit`. Re-run `layout_text_cost` ([31](31-layout-text-cost.md)) and +`scripts/motion-audit` before and after each phase below. + +The question: from first principles, should Rune replace Taffy and Parley with purpose-built +engines, and how should it cut frame CPU, per-frame allocations and retained heap from here? + +The short answer: **keep both Taffy and Parley.** Outside text shaping, Taffy is 5% to 16% of +a frame and Parley is 0.4% to 20% ([31](31-layout-text-cost.md)); replacing both with free, +zero-byte engines would leave a 5,283-node settings commit at 9.6 ms (still over the 8.3 ms +120 Hz budget) and a 50 KB Markdown resize at 2.96 ms. Where Parley dominates (98% of typing +in a 50 KB `text_input` at 15.5 ms, and 73% of cold-opening a 50 KB note at 18.3 ms), it is +spending 83% and 50% of the frame inside HarfRust OpenType shaping, which an own engine would +still run unless it shapes less text. Fixes inside Rune's own commit, motion, style and +caching layers can bring typing to ~1 ms, live resize to ~1.4 ms, and steady 5,283-node +commits to ~3.5 ms (< 0.8 ms with `memo`), while cutting per-node heap roughly in half. Two +focused layers *are* worth building from scratch now: a compact `BoxStyle` on `El` (replacing +inline `taffy::Style`) and a multi-paragraph composite `TextLayout` above `parley::Layout`. + +--- + +## 1. Verdict on an own layout engine: keep Taffy, delete the mirror's waste + +### Evidence + +- **Solver CPU is tiny.** In `layout_text_cost` ([31](31-layout-text-cost.md)), Taffy's layout + pass (`Phase::Layout`) takes **0.058 ms** for 5,283 nodes when one switch flips (`stack`) + and **0.012 ms** when nothing changed (`stack-same`). Taffy's 5.6% sample share in `stack` + (0.57 ms) is spent in `flatten`, comparing and dropping `taffy::Style` values whose CSS Grid + `Vec` fields Rune never populates (2.6% alone in `Style::eq` and grid track comparisons). +- **Even a full cache-miss resize has a 0.71 ms ceiling.** Stepping a 50 KB Markdown window's + width by 1 pt (`md-resize`, 1,268 nodes) invalidates every width constraint in Taffy. Taffy + takes 15.6% of the frame (**0.71 ms**, 0.56 µs/node, 4,170 flex-line allocations). A magic + zero-cost solver would take `md-resize` from 4.56 ms to 3.85 ms; skipping Rune's redundant + view/flatten rebuild on resize saves twice as much (~1.5 ms) in ~120 lines. +- **Taffy is the smallest of the three per-node heap owners.** Live heap per node in `stack` + is **2.1 KB** in Taffy, **2.4 KB** in Rune's flattened `Node`, and **3.5 KB** in + `rune_motion`. An earlier branch (`t710-taffy-adapter`) replaced `TaffyTree` with a dense + 364 B/node store (−71% layout-tree heap on 500 rows) and left commit time flat, confirming + that commit CPU sits in Rune's tree walk, string paths, style comparisons and `Scene` + retargeting rather than Taffy's slot maps. +- **Clean seam, real CSS parity risk.** `El.style` is `pub(crate)` (`crates/rune/src/el.rs:782`) + and `taffy` is never re-exported, touching 12 files in `crates/rune`. Rune uses flex + (`row`/`col`, grow/shrink/basis, wrap, gap, min/max, padding/border/margin, `aspect_ratio`), + `Position::Absolute` (under `Position::Relative` by default), and one grid helper, + `equal_columns(n)` (`repeat(n, 1fr)` on row 1). Even on that subset, views and `rune-kit`'s + components depend on CSS flexbox specifics: automatic minimum size (`min_h(0.0)` on flexing + scroll views), `flex_shrink: 0.0` defaults, `max-content` horizontal scroll rewrites + (`runtime/flatten.rs:312-334`), shrink negotiation under min/max bounds, and `flex_wrap` + with gaps. Re-owning those (~2.5 to 3.5 kLOC plus differential fuzzing) carries real + layout-regression risk for ≤ 0.71 ms of upside. + +### Measurable trigger to revisit an own layout solver + +Build a Rune-native single-pass layout solver over `Vec<Node>` only if, **after Phases 1 and 3 +land**, one of these holds on `layout_text_cost` (`--profile perf`, paired medians): + +1. `taffy::*` exceeds **30% of frame CPU and ≥ 1.0 ms** on a target 120 Hz workload (such as + resizing or mutating a 5,000-node unvirtualized table or canvas). +2. Taffy's rootward dirty propagation (`mark_dirty` walking to the root on any leaf edit) + spends **≥ 0.5 ms** on localized edits inside fixed-size or scrolling containers where + Flutter-style relayout boundaries would stop at the container. +3. Multi-pass layout commits (`aspect_fit`, `fit_anchored`, or `virtual_list` height-bound + retries) still run ≥ 2 full-tree solves on **> 5% of commits** in real traces after PR 4c. + +--- + +## 2. Verdict on an own text engine: keep Parley + HarfRust, cache at paragraph granularity + +### Evidence + +- **Outside shaping, Parley is ≤ 0.6 ms.** On steady commits (`stack`, `md-same`), the entire + text stack (Parley, `parley_engine`, HarfRust, Fontique, ICU4X, Swash) is 0.4% to 2.2% of + the frame (≤ 0.05 ms). On `md-resize` (4.56 ms), Parley's bucket is 19.6% (0.89 ms), but a + third of that (6.6%, 0.30 ms, 3,540 allocations) is Rune's own `Layout::clone` before + re-breaking; Parley's actual line breaking of 395 wrapped texts takes **0.35 ms** (0.88 µs + per paragraph). +- **Typing is slow because Rune hashes and reshapes the whole 50 KB field per keystroke.** + Typing one character in a 50 KB `text_input` (`edit`) takes **15.5 ms** (97.8% Parley, of + which 82.8% is HarfRust shaping and 8.6% is ICU/bidi analysis) and holds **13.8 MB** of + Parley heap (7.8 MB across two whole-note `ShapedText` buffers plus a 4.3 MB HarfRust + `UnicodeBuffer` high-water mark). Splitting the same 50 KB note into keyed blocks + ([27](27-long-note-editing.md) `--blocks`) already drops typing to **0.82 ms** (reshaping + one block takes 0.03 to 0.6 ms). Any custom text engine that shapes a 50 KB buffer as one + unit would still spend ~12 ms in HarfRust and fail 120 Hz. +- **Cold open is bounded by unique-word shaping and unvirtualized offscreen blocks.** `md-open` + shapes 404 texts in **18.3 ms** (9.2 ms HarfRust, 1.15 ms ICU/bidi, 0.82 ms Fontique, 0.81 ms + Swash). Note that `layout_text_cost`'s generator draws from a 50-word list (`main.rs:43-47`: + 772 distinct tokens across 7,201 words, an 89% repeat rate), whereas real prose and code + repeat ~40% to 55% of words. Meanwhile, only 32 of the 614 texts in `md-open` are on screen + ([28](28-resize-rewrap.md)); virtualizing Markdown blocks avoids shaping ~90% of offscreen + blocks on open without touching the shaper. +- **High parity cost for replacing Parley.** Owning text below `parley` means re-implementing + UAX #9 bidi reordering and visual-order cursor movement (`Cursor`/`Selection`), UAX #14/29 + line and grapheme segmentation, fallback itemization across ZWJ emoji and combining marks, + IME preedit caret/underline geometry, and CoreText vertical-metric parity + (`core_text_tests.rs`). Switching to per-OS native shapers (CoreText/DirectWrite) would give + up Rune's cross-platform layout determinism and still leave web/Linux needing a Rust stack. + +### Measurable trigger to revisit a lower text seam (`parley_engine` breaker) + +Never build an own OpenType shaper, bidi engine or OS-divergent shaper. Revisit replacing +`parley::Layout` with Rune's own line breaker and word/run shape cache directly over +`parley_engine 0.12` (`Analyzer` + `Shaper` + `FontSelector`) only if, **after Phases 1, 2 +and 4 land**: + +1. Cold open of **unvirtualized** UI or document views (≥ 300 uncached texts on screen at once) + still spends **≥ 6.0 ms in HarfRust**, **and** the Phase 0 spike on real English/code files + shows **≥ 50% word-cache hits and ≥ 2.0× net wall-clock speedup** after per-word overhead + and `unsafe-to-break` fallbacks; **or** +2. Workarounds around `parley::Layout` (inline-box `cursor_from_point`, `cursor_geometry` + `inline_min_coord`, `2n+1` pill re-breaks, space-widened tabs) need > 300 new lines of + wrapper code and upstream fixes in Parley are blocked. + +--- + +## 3. Five root causes verified in the code + +Checking the attribution numbers in [31](31-layout-text-cost.md) against `crates/rune` and +`crates/rune-motion` turned up five specific mechanisms that explain the big buckets: + +1. **`window_tree` walks every node and expands every `memo` even when no `virtualize` exists + (`crates/rune/src/runtime.rs:3543-3645`, `el.rs:1613-1618`).** + `window_tree` only mutates elements with `virtual_estimate.is_some()`, yet `build_tree` + runs it unconditionally over all 5,283 nodes of `stack` and 1,268 nodes of `md-*`. Worse, + line 3544 calls `el.expand_memo()` while `MemoCache` still holds a second `Rc<Shared>` + reference, forcing `Rc::unwrap_or_clone` to **deep-clone every cached memo subtree's + `Vec<El>`** before `flatten` consumes it. `window_tree` and `flatten` each call + `node_path` (`format!`), and `flatten.rs:229` calls `path.clone()`, accounting for all **4 + `node_path` allocations per node** (21,130 of 45,657 allocations in `stack`). +2. **`Scene::record_track` marks every node `dirty = true` on no-op `animate` calls, and + `apply` eagerly allocates 4 to 8 `AnimationStore` tracks on static nodes + (`crates/rune-motion/src/scene.rs:870-940, 1065-1085`, `store.rs:466, 940`, + `crates/rune/src/runtime.rs:3400, 4200-4298`).** + - Each lane in `AnimationStore` takes ~108 B (~160 B with `Vec` capacity; `Layer` is 64 B). + On commit 1, `apply` calls `set_or_anim(P_FILL, Color::TRANSPARENT)` on all 5,283 nodes + and `P_TEXT` on all 2,040 text/icon nodes, even though `Runtime::color` (`runtime.rs:3401`) + ignores `AnimationStore` whenever `!is_animating`. On commit 2, `Scene::animate` calls + `ensure_prop` *before* checking `target == base`, creating 4-lane `RADIUS` and 1-lane + `OPACITY` tracks on every static box (`Scene::insert` also creates `PRESENCE` on + `Mount::Initial`). Together, static nodes carry ~14 unused lanes and ~5 tracks, explaining + `rune_motion`'s **3.4 to 3.5 KB/node** (18.5 MB in `stack`). + - `AnimationStore::animate` runs `Color::write_lanes` (`3 × powf(2.4)` + `3 × cbrt()` for + OKLab) *before* checking whether the target changed (~10,000+ conversions/frame in `stack`). + - For the ~4,750 offscreen nodes in `stack`, `quiet = out_of_sight` calls `Scene::set` → + `set_raw`, which never checks if lanes already sit at `values` and pushes 9,500 + `TrackId`s into `set_touched`. For onscreen nodes, `record_track` sets `dirty = true` + even when `animate_raw` was a no-op, forcing `Scene::present_dirty` to recompute all + 5,283 `Presented` structs on every commit, including `stack-same` and `md-same`. +3. **`Cx<S>` has no `viewport` getter, and `Runtime` already computes `state_unchanged` + (`crates/rune/src/runtime.rs:270-386, 2299`).** + A view function can only depend on layout geometry through `Cx::caret` (`caret_watch`), + `Cx::layout*` (`layout_seen`), or `virtuals`. During `md-resize`, `state_unchanged` is + already `true`, `scale` is unchanged, and `virtuals` is empty, so re-running `view` + (0.64 ms) and `flatten` (~0.85 ms, 8,503 allocations) rebuilds the exact same `Node` and + Taffy trees every 1 pt step. +4. **`Layout::clone` during resize (7.1% of `md-resize`, 3,540 allocs, 2.2 MB/frame) comes + from `Rc` aliasing with `self.nodes` and stale widths in `self.layouts` + (`crates/rune/src/text.rs:1629-1639`, `runtime.rs:3711-3722`).** + `parley::Layout` stores shaped runs and broken lines in one struct (`LayoutData`). Cloning + happens because `self.nodes` (from the prior commit) and `self.layouts[prev_width]` both + hold `Rc<Layout<Ink>>` (`strong_count == 2`) while `compute_layout` runs. Clearing + `old.text_layout` on surviving (non-exiting) nodes before `compute_layout` and moving an + entry with `used < g` from `prev_key` to `key` drops `Rc::strong_count` to 1, letting + `Rc::make_mut` re-break `&mut Layout<Ink>` in place with zero allocations. +5. **Hidden Parley setup work in `layout_blocks_inner` (`crates/rune/src/text.rs:1602, 1763, + 1855-1875`).** + `lcx.ranged_builder` resolves `TextStyle::default()` (triggering an unused Fontique query + for `"sans-serif"`) and splits overlapping style ranges, even though `el.rs:1013` + (`flatten_spans`) already flattens spans into contiguous non-overlapping runs suited to + `lcx.style_run_builder`. And when a fallback font's `trak` table differs from the primary + font's, line 1874 rebuilds and reshapes the entire layout a second time. + +--- + +## 4. Ranked improvements + +Baselines from [31](31-layout-text-cost.md) (50 KB, `--profile perf`, M4 Pro): `edit` 15.5 ms +(19.2 MB heap), `md-open` 18.3 ms, `stack` 10.2 ms (45,657 allocs, 57.9 MB heap), `stack-same` +9.9 ms, `md-resize` 4.56 ms / 4.35 ms without `frame-profile` (21,198 allocs, 20.8 MB heap), +`md-same` 1.98 ms, `list` 0.44 ms mean (0.15 ms median). Savings note where items overlap on +the same workload. + +| Rank | Change | Expected CPU & alloc/heap impact | Size | Risk | +|---:|---|---|---|---| +| **1** | **Per-paragraph composite `TextLayout` + range-delta undo** (`text/composite.rs`, `edit/history.rs`, ~12 `Layout<Ink>` readers): split multi-paragraph text at `\n` into independently cached `Rc<parley::Layout<Ink>>` slices under a `(byte_start, y_top, line_start)` prefix index; store `TextEdit` undo steps as byte-range diffs. | **`edit`: −14.3 to −14.7 ms** (`15.5 → ~0.8–1.2 ms`); **−9 to −10 MB heap** in `edit` (caps HarfRust buffer to 1 paragraph, drops dual 50 KB `ShapedText` copies); `edit` allocs `1,176 → < 80`; keeps 100/100 undo steps at 200 KB. | ~900 LOC | Medium (UAX #9 bidi is paragraph-scoped so `\n` split is exact; work is routing readers cleanly). | +| **2** | **Lazy `Scene`/`AnimationStore` tracks, no-op `dirty` fix, and sRGB pre-check** (`rune-motion/src/scene.rs`, `store.rs`, `runtime/apply.rs`): leave `dirty = false` on unchanged `animate`; no-op `set_raw` when settled at target; create `PRESENCE`/`RADIUS`/`OPACITY`/`P_FILL`/`P_TEXT` tracks only when values differ from rest; compare `Color` floats before OKLab `powf`/`cbrt`. | **`stack` / `stack-same`: −2.3 to −2.8 ms** (`apply` `2.92 → ~0.4 ms`, removes 8% `set_raw`+OKLab and 5,283-node `present_dirty`). **`md-resize`: −0.55 ms**. **`md-same`: −0.32 ms**. Heap: **−14 to −16 MB in `stack`** (`3.5 → ~0.5 KB/node`), **−3.5 MB in `md-resize`**. | ~260 LOC | Low (`scripts/motion-audit` + retarget velocity tests gate exact behavior). | +| **3** | **`has_virtual` subtree bit + retained `(NodeId, Segment)` `PathTable` (`Rc<str>`)** (`runtime/path_table.rs`, `flatten.rs`, `el.rs`, `memo.rs`): propagate `has_virtual: bool` on `El`/`Shared` to skip `window_tree` (and stop pre-flatten `memo` deep-clones) when no virtual list is under a node; intern `(parent_id, key_or_index) → (NodeId, Rc<str>, LayoutEntry)` across commits. | **`stack` / `stack-same`: −1.8 to −2.4 ms**. **`md-resize` / `md-same`: −0.35 to −0.50 ms**. **`md-open`: −0.5 ms**. Allocs: **−21,130/frame in `stack`**, **−5,070/frame in `md-*`**, while keeping `&str` deref for all ~100 `.path` readers. | ~300 LOC | Low (`--tree` and `key_diagnostics` verify identical paths). | +| **4** | **Viewport-relayout fast path (skip `view` + `flatten` when `state_unchanged`)** (`runtime.rs`): on `relayout` with `state_unchanged && scale_unchanged && virtuals.is_empty()`, update `root_id`'s `style.size` on `self.layout` and run `compute_layout` + `place` + text re-break on `self.nodes`; fall back to `measure_view` only if `layout_reads_moved()` or `caret_moved()` fires. | **`md-resize`: −1.35 to −1.55 ms** (skips 0.64 ms `view` and ~0.85 ms `flatten`; overlaps with #3 on `md-resize`). Allocs: **−11,140/frame** (−5 MB/frame) in `md-resize`. | ~120 LOC | Low (`Cx` exposes no viewport; read/caret fallback preserves reactive views). | +| **5** | **Single `shape_key` hash per `TextSpec` with fast non-SipHash mixer** (`text/hash.rs`, `el.rs`, `flatten.rs`, `text_layout.rs`): compute `shape_key: u64` once on `TextSpec` (invalidated only by `apply_case`/`conceal`) and pass it through Taffy `measure` (~4×/text) and final text layout instead of SipHashing ~6×/frame. | **`md-resize`: −0.38 to −0.50 ms** (11.2% → < 0.5%). **`stack` / `stack-same`: −0.40 to −0.45 ms** (4.4%). **`md-open`: −0.25 ms**. | ~100 LOC | Very low. | +| **6** | **In-place `Layout` re-break via `Rc::make_mut` (remove `Layout::clone`)** (`text.rs`, `runtime.rs`): drop `old.text_layout` on non-exiting nodes before `compute_layout` and move `used < g` cache entries from `prev_key` to `key` so `Rc::make_mut` re-breaks in place with zero copies. | **`md-resize`: −0.28 to −0.33 ms** (7.1% of frame). Allocs: **−3,540/frame and −2.2 MB/frame** in `md-resize`; halves Parley resize cache memory. | ~80 LOC | Low (`rewrap_tests` and `secure_text` `strong_count` tests cover edge cases). | +| **7** | **Compact `BoxStyle` (~88 B `Copy`) + `Cold<T>` split on `El`/`Node` + `subtree_end` paint culling** (`el/style.rs`, `runtime/node.rs`, `runtime/paint.rs`): replace inline `taffy::Style` on `El` with `BoxStyle` (converting to `taffy::Style` only on style change, dropping unused `content_size`/`block_layout` features); box cold handler/scroll/motion/visual groups via `Cold<T>`; store `subtree_end: u32` on `Node` to skip offscreen scroll subtrees in O(1) during `paint`. | **`stack` / `stack-same`: −2.0 to −2.8 ms** (kills Taffy's 0.57 ms `Style` compare/drop in `flatten`, cuts 16 MB/frame `El::child` realloc copies ~5×, drops `paint` `1.09 → ~0.3 ms` on 88% offscreen cards). **`md-same`: −0.4 to −0.6 ms**. Heap: **−9 to −11 MB in `stack`** (`Node` `2.4 → ~0.6 KB/node`). | ~600 LOC | Low–Medium (mechanical layout/cold refactor; `BoxStyle` covers 100% of `El` builders). | +| **8** | **Flattened subtree reuse for `memo`** (`memo.rs`, `flatten.rs`, `runtime.rs`): once #3 stops `window_tree` from expanding memos, reuse the prior commit's flattened `Node` slice (rebasing parent/context indices) and Taffy `NodeId` subtree on a `memo` hit, skipping `flatten` and clean interior `apply`. | **Memoized `stack` / real app views: `9.9 ms → < 0.8 ms`** on 1-card flip; **`md-same --memo`: `1.98 → < 0.25 ms`**. Scales commit cost with changed subtrees instead of mounted nodes. | ~350 LOC | Medium (must replay `Cx` reads and rebase Taffy leaf context indices accurately). | +| **9** | **`ResolvedStyle` cache + `style_run_builder` + single-build `trak`** (`text/resolved.rs`, `text.rs`): cache family stacks, features, variations and `trak` by `(TextStyle, collection_gen)`; switch `ranged_builder` to `style_run_builder`; reuse `LayoutContext` on secure text; pre-resolve fallback `trak` / update run spacing instead of double-shaping on mismatch. | **`md-open`: −1.5 to −2.5 ms** (and −40% to −50% on mixed-script/emoji text that currently double-shapes). **`list` mounting p95: −15%**. Allocs: **−3,500+ in `md-open`**. | ~280 LOC | Low (`core_text_tests.rs` verifies metrics and tracking). | +| **10** | **Fix `El::virtualize` caret/reveal + virtualize `rune_kit::Markdown` blocks** (`virtual_list.rs`, `runtime/caret.rs`, `rune-kit/src/markdown.rs`): fix virtualized `ElementInfo::caret` and `scroll_into_view` headless typing ([27](27-long-note-editing.md)); virtualize top-level Markdown blocks with re-break height estimates while keeping `markdown/find.rs` and `virtual_selection` working. | **`md-open` (50 KB): −11 to −13 ms** (`18.3 → ~4.5–6.0 ms`, and bounds 200 KB open at ~6 ms instead of 70 ms). **200 KB `md-resize`: `23.2 → < 2.0 ms`**. Heap: **−12 MB** on 50 KB Markdown. | ~450 LOC | Medium (offscreen height estimates until lazily broken; selection/find integration). | +| **11** | **Single-pass `aspect_fit` leaf measure & subtree-scoped `fit_anchored`** (`runtime/flatten.rs`, `runtime/anchor.rs`): compute `aspect_fit` inside Taffy's leaf measure closure where childless; run overflowing `anchored_fit` re-layout on `overlay_id` instead of `root_id` (an `above` overlay never moves siblings). | **−30% to −66% of layout CPU** on media grids and overflowing popovers/menus (1 root solve instead of 2 or 3). | ~130 LOC | Low. | +| **12** | **(Conditional, gated on Spike & Trigger) Word/run shape cache over `parley_engine`** (`text/`): cache shaped runs for space-delimited words without cross-space GSUB/GPOS, falling back to full runs for complex scripts. | **`md-open` (only if unvirtualized): −3 to −4.5 ms on real prose** (up to −8 ms on 50-word bench). Unneeded for notes once #10 virtualizes `md-open`. | 3–4.5 kLOC | High (see §5). | + +### Projected scorecard after Phases 1 to 4 (keeping Taffy and Parley) + +| Case (50 KB) | Today (ms) | Free Taffy + Parley today (ms) | Projected Phases 1–4 (ms) | Live heap today → projected | +|---|---:|---:|---:|---| +| `edit` | 15.5 | 0.33 *(if shaping = 0)* | **~0.9–1.2** | 19.2 MB → **~9.5 MB** | +| `md-open` | 18.3 | 4.1 | **~15.0** *(unvirt.)* / **~4.5–6.0** *(virt.)* | 20.8 MB → **~14 MB** *(~7 MB virt.)* | +| `md-resize` | 4.56 *(4.35 prod)* | 2.96 | **~1.3–1.6** | 20.8 MB → **~14 MB** | +| `md-same` | 1.98 | 1.84 | **~0.6–0.8** *(< 0.25 with `memo`)* | 20.8 MB → **~14 MB** | +| `stack` | 10.2 | 9.6 | **~3.5–4.5** *(< 0.8 with card `memo`)* | 57.9 MB → **~23–26 MB** | +| `stack-same` | 9.9 | 9.4 | **~3.2–4.0** *(< 0.5 with card `memo`)* | 57.9 MB → **~23–26 MB** | +| `list` (mean) | 0.44 *(0.15 med)* | 0.33 | **~0.28–0.33** *(0.10 med)* | 11.4 MB → **~9.5 MB** | + +--- + +## 5. Where a from-scratch layer is the right choice + +### Build from scratch now + +1. **`BoxStyle` (~88 B, `Copy`) in `crates/rune/src/el/style.rs` (~350 LOC, zero parity risk).** + `El` currently embeds `taffy::Style` (~400+ B with nine CSS Grid `Vec`s Rune leaves empty), + paying to construct, move in `Vec<El>`, compare (`Style::eq`) and drop it on every node of + every commit. A purpose-built `BoxStyle` stores only Rune's actual box/flex/anchor/columns + fields in ~88 B, compares as plain words in `flatten`, and converts to `taffy::Style` only + when a node's style changed. It eliminates Taffy's 5.6% `stack` overhead today and cleanly + decouples `El` from Taffy if a native solver is ever warranted later. +2. **`ParagraphComposite` multi-paragraph layout in `crates/rune/src/text/composite.rs` (~800 LOC, + low-to-medium parity risk).** + `parley::Layout` is a single-block layout buffer by design. Building a thin composite over + `Vec<ParagraphSlice>` (each holding an `Rc<parley::Layout<Ink>>`, cached by paragraph + `shape_key` and width, indexed by binary search on byte, y and line offsets) solves long-note + editing (`15.5 → ~1 ms`) and halves Parley's editor memory while keeping Parley's exact + shaping, bidi and line-breaking behavior within every paragraph. + +### Keep gated behind §1 and §2 triggers (do not build before Phase 4) + +3. **Native single-pass flex + anchor solver over `Vec<Node>` and `BoxStyle` (~2.5 to 3.5 kLOC + solver + ~1.2 kLOC differential fuzzer against Taffy; medium-to-high parity risk).** + If a real workload ever trips the §1 trigger, a native solver wins by operating directly on + `Vec<Node>` rather than by running faster flex arithmetic: it writes straight into + `Node.local/target/inset` with one reusable scratch arena (zero per-container `FlexLine` + allocations), enforces relayout boundaries at scroll viewports and fixed-size boxes so leaf + edits stay O(subtree), and folds `aspect_fit`, `equal_columns(n)` and `anchored_fit` into + single-pass sizing rules. Parity risk sits in CSS automatic minimum sizes (`min_h(0.0)`), + `max-content` horizontal scroll sizing, shrink negotiation under min/max clamps, and + `flex_wrap` + `gap`; promotion must require `±0.01 pt` agreement with Taffy on generated + `El` trees and every `rune-kit` story. +4. **Custom line breaker + shaped-word/run cache over `parley_engine 0.12` (~3 to 4.5 kLOC + + ~1.5 kLOC RTL/CJK/emoji/CoreText suite; high parity risk).** + If unvirtualized cold-open shaping trips the §2 trigger, dropping `parley::Layout` for + `parley_engine::{Analyzer, Shaper, FontSelector}` separates immutable shaped runs from + lightweight `Vec<LineSlice>` line breaking, turns pills, real tab stops, block indents and + optical `trak` into first-class breaker inputs (deleting five wrapper layers), and enables a + Blink-style space-delimited word cache. Parity risk is high: `parley_engine` 0.12 notes that + line-edge reshaping (`unsafe-to-break`) is still in progress, Blink disables word caching + whenever a font has GSUB/GPOS rules touching space, complex scripts still shape per run, and + Rune would take over bidi visual-order `Cursor`/`Selection` movement and CoreText vertical + metrics parity. + +--- + +## 6. Phases, measurable gates, and the first spike + +Several target files (`runtime.rs`, `el.rs`, `text.rs`, `edit.rs`, `markdown.rs`) sit in +`scripts/file-size-exceptions.txt`. Per `AGENTS.md`, any phase touching one extracts that area +into a sibling module first and lowers its exception ceiling in `scripts/file-size.sh`. + +### First spike (do this first; ~180 LOC, throwaway, half a day) + +The two riskiest assumptions in this plan are (a) that stacking per-`\n` `parley::Layout<Ink>` +slices matches a single multi-paragraph `parley::Layout<Ink>` to the pixel across indents, +pills, RTL and Retina quantization (before refactoring ~12 reader call sites), and (b) whether +a word-shape cache still wins on *real* prose and code once `layout_text_cost`'s 50-word +synthetic vocabulary is replaced. + +1. **Paragraph-stacking equivalence + `edit` timing (~100 LOC test/bench):** Split `edit`'s + 50 KB string at `\n` into cached `(shape_key, width) → Rc<Layout<Ink>>` slices and stack + their line metrics. Check bit-exact `(glyph.id, x, y)` and line `[block_min_coord, + block_max_coord]` parity against `layout_blocks_inner` across `rewrap_tests.rs` (spans, all + 4 alignments, RTL, CJK, emoji, math, indented `Block`s, pills, trailing `\n`, scale 1x/2x), + and time `layout_text_cost --case edit`. + - **Gate:** 0 px discrepancy (or exact quantization rule pinned down) **and** `edit` median + `cpu_ms ≤ 1.2 ms`, live Parley heap `≤ 5.0 MB`. +2. **Real-corpus word-cache ceiling (~80 LOC bench):** Run three real ~50 KB inputs (`PLAN.md`, + `CHANGELOG.md`, `crates/rune/src/runtime.rs`) through `WORDS` token counting and a throwaway + per-word `parley_engine::Shaper` cache vs Parley paragraph shaping. + - **Gate:** If net wall-clock speedup on real Markdown/code is `< 2.0×`, **kill Option 5.4** + (`parley_engine` word-cache breaker) outright and rely on Phase 4b Markdown virtualization + for cold open. + +### Phase 1: Commit, resize and motion fast paths (4 PRs, ~550 LOC) + +- **PR 1a (`text/hash.rs`, `flatten.rs`, `text_layout.rs`):** Precompute `shape_key: u64` once + on `TextSpec` with a fast mixer (`Fx`) and pass it through `measure` and final layout. + - *Gate:* `md-resize` `cpu_ms` drops `≥ 0.35 ms` (`text_hash` sample `< 1%`, down from 11.2%); + `stack` drops `≥ 0.35 ms`. +- **PR 1b (`text.rs`, `runtime.rs`):** Clear `old.text_layout` on surviving nodes before + `compute_layout` and move `used < g` cache entries across widths so `Rc::make_mut` re-breaks + in place without `Layout::clone`. + - *Gate:* `md-resize` `allocs` drops `≥ 3,400/frame` (`21,198 → ≤ 17,700`) and `cpu_ms` drops + `≥ 0.25 ms`; `rewrap_tests` and `secure_text` `Rc::strong_count` tests pass. +- **PR 1c (`rune-motion/src/scene.rs`, `store.rs`, `runtime/apply.rs` extracted from + `runtime.rs`):** Leave `Scene` node `dirty = false` on unchanged `animate`; no-op `set_raw` + when settled at target; allocate `PRESENCE`/`RADIUS`/`OPACITY`/`P_FILL`/`P_TEXT` tracks + lazily on first change/animation; compare `Color` sRGB floats before OKLab conversion. + - *Gate:* `stack` and `stack-same` `apply_ms` `2.92 → ≤ 0.60 ms` (`cpu_ms ≤ 7.6 ms`), `stack` + live heap `57.9 → ≤ 43 MB` (`rune_motion ≤ 0.7 KB/node`), `scripts/motion-audit` clean. +- **PR 1d (`runtime.rs`):** Relayout-only fast path on `set_viewport` when `state_unchanged && + scale_unchanged && virtuals.is_empty()`, with fallback to `measure_view` if `layout_reads` or + `caret_watch` moved. + - *Gate:* `md-resize` `cpu_ms ≤ 1.7 ms`, `view_ms = 0`, `allocs ≤ 9,500/frame`. + +### Phase 2: Multi-paragraph `TextLayout` and delta undo (3 PRs, ~950 LOC) + +- **PR 2a (`text/composite.rs` extracted from `text.rs`, `edit.rs`, `links.rs`, + `selectable.rs`):** Route all `Layout<Ink>` readers through a single-layout `TextLayout` + wrapper first and lower `text.rs`/`edit.rs` ceilings. + - *Gate:* Zero `layout_text_cost` regression; full text/IME/selection test suite green; + `scripts/file-size.sh` passes with lowered ceilings. +- **PR 2b (`text/composite.rs`):** Enable per-`\n` paragraph slicing, per-paragraph shape/width + caching, and binary-searched line/byte/y lookup inside `TextLayout`. + - *Gate:* `edit` (50 KB) `cpu_ms` `15.5 → ≤ 1.2 ms` (p95 `≤ 1.6 ms`), `shaped = 1` per + keystroke, `edit` live heap `19.2 → ≤ 10.5 MB`; `long_note` 200 KB typing `45.7 → ≤ 1.8 ms`. +- **PR 2c (`edit/history.rs` extracted from `edit.rs`):** Replace full-string undo snapshots + with `(range, removed, inserted_len)` + mark/block deltas. + - *Gate:* `long_note` retains 100/100 undo steps at 50 KB and 200 KB within the 1 MB cap. + +### Phase 3: Path table, compact `BoxStyle`/`Node`, and flattened `memo` (4 PRs, ~1,250 LOC) + +- **PR 3a (`runtime/path_table.rs`, `flatten.rs`, `el.rs`, `memo.rs`):** Add `has_virtual: bool` + on `El`/`Shared` to skip `window_tree` when false; replace per-frame `node_path` formatting + with a retained `(NodeId, Segment) → (NodeId, Rc<str>, LayoutEntry)` `PathTable`. + - *Gate:* `stack` `allocs` drops `≥ 20,000/frame` (`≤ 25,000`), `md-same` `allocs ≤ 5,700`, + `stack` `cpu_ms` drops `≥ 1.5 ms`. +- **PR 3b (`el/style.rs` extracted from `el.rs`, `flatten.rs`, `Cargo.toml`):** Replace inline + `taffy::Style` on `El` with 88 B `Copy` `BoxStyle`; materialize `taffy::Style` only on style + change; drop unused `content_size` (and `block_layout` if unused). + - *Gate:* `taffy::*` sample share in `stack` `< 0.5%` (down from 5.6%); `El::child` allocated + bytes/frame drop `≥ 50%`. +- **PR 3c (`el.rs`, `runtime/node.rs`, `runtime/paint.rs`):** Group cold handler/scroll/motion/ + visual fields into `Cold<T>` on `El` and `Node`; add `subtree_end: u32` on `Node` and skip + offscreen subtrees inside scroll clips during `paint`. + - *Gate:* `stack` live heap `≤ 30 MB` (`Node ≤ 0.7 KB/node`), `paint_ms` `1.09 → ≤ 0.35 ms`, + un-memoized `stack` `cpu_ms ≤ 4.5 ms`. +- **PR 3d (`memo.rs`, `flatten.rs`, `runtime.rs`):** Reuse flattened `Node` slices and retained + Taffy `NodeId` subtrees on `memo` hits, skipping `flatten` and clean interior `apply`. + - *Gate:* Per-card `memo` on `stack` reaches `cpu_ms ≤ 0.8 ms` on a switch flip; `md-same` + with `memo` reaches `≤ 0.30 ms`. + +### Phase 4: Cold-open scaling and single-pass layout cleanups (3 PRs, ~850 LOC) + +- **PR 4a (`text/resolved.rs`, `text.rs`):** Add `ResolvedStyle` cache, switch `ranged_builder` + to `style_run_builder`, reuse `LayoutContext` (cleared) on secure text, and eliminate the + `trak` mismatch double build. + - *Gate:* `md-open` `cpu_ms` drops `≥ 1.5 ms` and `allocs` drops `≥ 3,500`; mixed-font `trak` + strings shape once (`shaped = 1`). +- **PR 4b (`virtual_list.rs`, `runtime/caret.rs`, `rune-kit/src/markdown/`):** Fix virtualized + field caret reporting and `scroll_into_view` typing; virtualize `Markdown` top-level blocks + above a block threshold while preserving `markdown/find.rs` and `virtual_selection`. + - *Gate:* `md-open` `cpu_ms` `18.3 → ≤ 6.0 ms` at 50 KB and `≤ 6.5 ms` at 200 KB (down from + 70 ms); 200 KB `md-resize` `23.2 → ≤ 2.0 ms`. +- **PR 4c (`runtime/flatten.rs`, `runtime/anchor.rs`):** Move childless `aspect_fit` into + Taffy's measure callback and scope `fit_anchored` re-layout to `overlay_id`. + - *Gate:* `aspect_fit` media-grid and overflowing `anchored_fit` menu scenes run 1 root + `compute_layout` pass instead of 2 or 3 (`Phase::Layout` `−40%+` on those scenes). + +### Phase 5: Re-measure and check §1 / §2 triggers + +Re-run `layout_text_cost` across `--mode time`, `--mode sample` and `--mode heap`. Start the +native flex solver (§5.3) or `parley_engine` line breaker (§5.4) only if a workload still trips +the §1 or §2 trigger. + +## Spike results + +Throwaway code on branch `spike/engine`: `research/engine-spike/paragraph_stack.rs`, compiled as +a test module of `rune` (it needs `layout_blocks_inner` and `test_alloc`). Timings use +`--profile perf` with `debug-assertions` on for the `rune` crate only, because its lib tests need +them. Parley and HarfRust build at plain perf settings. Modes alternate order on every keystroke +or round, and the numbers are medians. + +### Q1: one cached layout per `\n` paragraph, stacked + +**Equivalence.** The matrix is every `rewrap_tests` case plus Arabic followed by digits. Each case +is joined as `[case, plain, empty, case]`, `[plain, case]`, and both of those again with a +trailing `\n`. Every join runs at 1x and 2x, at widths 1200, 433.5, 210 and unbounded: 384 runs +per mode. A run is exact when every line box, run, glyph and pill box matches within 1e-3 px. + +| Stacking rule | Exact runs | +| --- | --- | +| Each paragraph laid out alone, tops summed | 264 / 384 | +| + every paragraph forced to the text's base direction | 318 / 384 | +| + line tops rounded from the running total, unbounded width aligned to the widest paragraph | **384 / 384** | + +The base rule is that each paragraph keeps its `\n`, and every paragraph but the last drops the +empty line after it. With that rule, trailing newlines, empty lines and their heights never +caused a mismatch. Three things did: + +1. **Base direction.** Parley sets one base level per layout, from the first strong character. + A paragraph laid out alone takes its own: a Latin line after Arabic goes LTR instead of RTL, + which moves its alignment and run order. This affected RTL, RTL justified, Arabic then + digits, end and centred. Fix: pass the whole text's direction to each paragraph's builder. + Bidi reordering never crosses a `\n`, so nothing else leaked between paragraphs. +2. **Line-top rounding.** Parley rounds each line's top from the unrounded sum of the line + heights above it. A fractional line height (monospace tabs at 32.5 px, pill lines at 1x) + shifts the lines after it by 0.5 px when a paragraph restarts from a rounded top. Fix: round + each line top from the running unrounded total, not the paragraph's own top. +3. **Unbounded width with centre, end or RTL alignment.** One layout aligns every line in its + widest line; a paragraph alone aligns in its own widest line. Fix: shift each paragraph by + (widest paragraph − its width) × the alignment share. When the widest paragraph changes, the + other paragraphs move but nothing is reshaped. + +**Typing.** The `edit` workload is a 50 KB note in 695 paragraphs, with one character typed mid-note +per keystroke at 1392 px width and 2x scale. Each mode ran 480 keystrokes: + +| Mode | cpu ms median | p95 | Parley heap after open | after 480 keys | +| --- | --- | --- | --- | --- | +| whole (one layout) | 15.2 | 16.7 | 5.39 MB | 5.46 MB | +| naive (every paragraph through the cache) | 0.23 | 0.31 | 4.03 MB | 7.21 MB | +| incremental (only the edited paragraph) | **0.10** | **0.14** | **4.03 MB** | 7.22 MB | + +Across three runs, incremental stayed between 0.10 and 0.18 ms median and between 0.14 and +0.26 ms p95. That is about 150× faster than one layout, and the gate is 1.2 ms. The live paragraph +layouts take 4.03 MB. Heap here means live growth from opening, which is not how research 31 +counted its 13.8 MB. + +The growth to 7.2 MB comes from the cache's stale copies of the edited paragraph. Clearing the +cache frees 3.18 MB while the live paragraphs stay. The stale budget (`STALE_TEXT`, 64 KB) is +charged in text bytes plus 64 per entry, but a 605-byte paragraph's layout holds about 31 KB. +So about 100 superseded copies fit, and the total settles near 64 KB × ~50. + +**Verdict: go.** Stacking matches exactly with the three rules above, and typing is 0.1 ms. The +heap gate holds only if the layout cache charges stale entries by layout heap, or an edited +paragraph's old layout is dropped instead of kept as stale. + +### Q2: per-word `parley_engine` shaper cache versus Parley paragraph shaping + +The first ~50 KB of each file, cut at a newline. Inter 15 pt for the Markdown files and IBM Plex +Mono 13 pt for `runtime.rs`, at 2x and 1392 px. The cache is a word-keyed map of shaped glyphs; +a miss shapes the word alone. A greedy breaker splits lines at spaces. Each row is the median of +20 rounds, with a cold cache every round. + +| File | tokens | distinct | hit rate | Parley ms | cache ms | + analysis | speedup | with analysis | warm cache | +| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | +| PLAN.md | 7,480 | 3,136 | 58.1% | 14.36 | 7.68 | 9.21 | 1.87× | **1.56×** | 8.9× | +| CHANGELOG.md | 7,231 | 2,980 | 58.8% | 14.20 | 8.26 | 9.73 | 1.72× | **1.46×** | 9.0× | +| runtime.rs | 6,252 | 2,661 | 57.4% | 6.30 | 2.69 | 4.02 | 2.34× | **1.57×** | 4.1× | + +On real text only 57–59% of words repeat within 50 KB, against 89% for the synthetic note's 772 +distinct words. "+ analysis" adds the per-paragraph `Analyzer` pass that any real breaker needs +for break opportunities, bidi and script, and with it the cache wins only 1.5×. "Warm cache" +means every word was already shaped, as on a re-wrap. That case is not the cache's to win: Parley +re-breaks an existing layout without reshaping, and per-paragraph caching already makes typing +0.1 ms. + +The cache side is also an upper bound. It uses one font with no fallback, a fixed advance for +spaces, no kerning or ligatures across spaces, and breaks only at `' '`, not UAX #14. + +**Verdict: kill** the custom breaker. A cold cache wins 1.5×, below the 2× bar, and the case +where it wins big (a warm cache) is already cheap with Parley plus per-paragraph layouts. diff --git a/app/vendor/rune/research/33-real-bottlenecks.md b/app/vendor/rune/research/33-real-bottlenecks.md new file mode 100644 index 0000000..02dbbcc --- /dev/null +++ b/app/vendor/rune/research/33-real-bottlenecks.md @@ -0,0 +1,244 @@ +# 33. Real-app bottlenecks, checked against the engine plan + +Reader: someone choosing the next frame-time work in `rune`, `rune-kit` or `rune-motion`, or +checking whether [32](32-engine-plan.md)'s ranked plan matches what real apps spend. Re-run the +harness below before and after a change that should move one of these numbers. + +The question: in four real Rune apps, during the interactions people actually do, which costs +push frames over the 8.3 ms budget at 120 Hz, and does [32](32-engine-plan.md) cover them? + +The short answer: the frames that miss the budget come from rebuilding too much, not from +Taffy or Parley. In every interaction measured here, shaping is 0% to 3.5% of the main +thread's busy time and Taffy 0% to 7.4%. The worst frames re-run a whole view and flatten its +tree after a small change: a keystroke, a step of a live resize, a scroll that mounts new rows, +or opening a card. In two apps the view runs every row's builder, Markdown included, because +the list is built in full and then virtualized. [32](32-engine-plan.md)'s flatten, `memo` and +motion items (#2, #3, #7, #8) hold up on real data, but its two largest projected savings don't +fire here: the resize fast path (#4) excludes any tree with a virtual list, which every measured +app has, and none of the measured interactions types into a long field, where the per-paragraph +layout (#1) would pay off. Three costs the plan doesn't mention: paint re-emits every visible +glyph each frame (21% to 37% of a scroll frame), a virtual window shift re-runs the whole view, +and a blocking read on the main thread looks like a fast frame unless wall time is logged +next to CPU time. + +## How it was measured + +- Rune `c83aa06b` (`dev`), with each app's `rune` dependencies patched to that tree and built + at `--profile perf` with `rune/frame-profile`. Apps were left unchanged apart from bench-only + seeding switches (a longer seeded conversation, a fixed reply to stream, a card to open). +- Headless and offscreen at scale 2, on a 12-core M2 Max worker that other jobs were also + using (load average 6 to 20 during the runs). Each scenario ran once as warmup and then five + more times, with scenario order alternating between runs. Numbers are medians across runs + with outliers kept. +- `RUNE_FRAME_LOG=FILE` (new here) writes one JSON line per frame: wall and thread-CPU time, + phase CPU (view, commit, layout, text, paint, apply), allocations, commits and texts + shaped. A closing line records memory. `RUNE_HEADLESS_WAIT=SECS` (also new) holds a headless + run before its first frame so a sampling profiler can attach in time to see launch. +- `scripts/real-frames.py` runs the scenarios, summarizes them per interaction window, and + buckets a 1 kHz macOS `sample` of the main thread by self time. +- **What headless leaves out:** GPU execution, presentation, display timing and the window + server. Headless also draws every frame. The tables count only frames a real window would + draw: ones where input arrived, a commit ran or something animated. + +Workloads, described generically: + +| Workload | Data | Interactions | +|---|---|---| +| Agent client | A real 1,200-message transcript (22 MB), plus a 7.2k-character Markdown reply streamed in | launch, scroll (5 swipes), stream, type in the composer, live resize | +| Task board | A real board snapshot: 895 tasks, some cards with long notes, one with a Mermaid diagram | board scroll, open 12 cards in turn, scroll a long card, open and scroll the diagram card | +| Team chat | A seeded conversation repeated 40 times, one day apart | launch with arrivals, scroll, type, live resize | +| Notes reader | 601 synthetic notes, one of them 200 KB | launch, open a note, step the block cursor, search palette, scroll, live resize | + +## Frame CPU per interaction + +Thread-CPU ms per drawn frame, from the median run. "Over" is the number of frames above +8.3 ms out of `n`. + +| Workload / interaction | n | p50 | p95 | p99 | max | over | +|---|---:|---:|---:|---:|---:|---:| +| Agent client / scroll | 544 | 1.16 | 3.93 | 5.66 | 11.7 | 2 | +| Agent client / stream | 1980 | 1.14 | 5.52 | 7.01 | 9.45 | 2 | +| Agent client / type | 96 | 3.44 | 5.51 | 6.50 | 6.50 | 0 | +| Agent client / resize | 266 | 4.87 | 8.59 | 9.62 | 10.6 | 18 | +| Task board / scroll | 178 | 1.93 | 2.47 | 3.33 | 9.90 | 1 | +| Task board / open cards | 324 | 3.21 | 25.5 | 43.1 | 47.4 | 106 | +| Task board / long card scroll | 361 | 5.47 | 31.1 | 32.9 | 33.9 | 82 | +| Task board / diagram card scroll | 435 | 3.59 | 17.2 | 18.9 | 22.0 | 60 | +| Team chat / scroll | 736 | 0.56 | 1.18 | 1.48 | 15.0 | 3 | +| Team chat / type | 659 | 0.51 | 12.1 | 22.7 | 24.9 | 92 | +| Team chat / resize | 336 | 18.4 | 39.7 | 42.8 | 44.6 | 241 | +| Notes reader / step cursor | 96 | 6.42 | 13.8 | 15.0 | 15.0 | 30 | +| Notes reader / palette search | 22 | 2.88 | 7.64 | 9.62 | 9.62 | 1 | +| Notes reader / scroll | 267 | 1.22 | 1.81 | 2.16 | 2.64 | 0 | +| Notes reader / resize | 242 | 7.71 | 13.7 | 15.3 | 15.5 | 102 | + +An earlier chat resize run on the same machine measured p50 13.4 ms with 228 frames over. +Palette search's CPU looks fine, but its wall time doesn't: see #2 below. + +Launch, headless (process start to first frame read back) and the first frame's CPU: + +| Workload | Process to pixels | First frame CPU | What the first frame spends | +|---|---:|---:|---| +| Agent client | 298 to 347 ms | 28 to 33 ms | before it, 63 to 193 ms loading the transcript; layout 13 to 16, text 12 to 15 (102 texts shaped) | +| Task board | 201 to 293 ms | 86 to 172 ms | shaping 27 to 38, layout 13 to 47, view 20 to 44 | +| Team chat | 68 to 112 ms | 34 to 45 ms | view 26 (every row built), paint 9 | +| Notes reader | 59 to 98 ms | 13 to 26 ms | view 5, layout 3, text 2 | + +## Where the main thread goes + +Share of busy main-thread samples (waits left out), by the self-time owner. "paint" is the +per-frame draw-list walk (`Runtime::build`, `Phase::Paint`). "glyphs" is Parley's laid-out-glyph +iterators, almost all of it called from that walk. "rtext" is Rune's text code: `push_glyph`, +`text_hash`, Markdown building. "app" and "os" include app code: when an app function's own +frames sit in system calls, they land in "os". + +| Interaction | paint | glyphs | rtext | view | flatten | taffy | shape | motion | alloc | app | os | +|---|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:| +| Agent client / scroll | 13.1 | 25.3 | 10.0 | 8.5 | 1.5 | 1.1 | 2.1 | 1.8 | 4.6 | 2.5 | 18.3 | +| Agent client / stream | 10.4 | 8.9 | 8.7 | 21.6 | 11.0 | 2.9 | 2.1 | 5.0 | 8.6 | 3.3 | 11.3 | +| Agent client / type | 17.2 | 18.7 | 8.7 | 12.6 | 5.2 | 0.9 | 2.8 | 3.3 | 6.1 | 2.8 | 14.3 | +| Agent client / resize | 7.8 | 8.2 | 7.6 | 21.0 | 12.8 | 6.2 | 0.6 | 6.6 | 8.1 | 2.8 | 11.7 | +| Task board / scroll | 13.6 | 2.3 | 1.5 | 10.4 | 1.9 | 0.0 | 0.0 | 12.5 | 6.3 | 22.7 | 22.7 | +| Task board / open cards | 8.2 | 1.9 | 2.8 | 9.5 | 3.6 | 0.4 | 1.0 | 3.6 | 11.6 | 26.8 | 23.3 | +| Task board / long card | 13.3 | 0.9 | 3.2 | 19.2 | 5.5 | 0.6 | 0.7 | 8.8 | 9.6 | 16.3 | 17.4 | +| Team chat / scroll | 19.6 | 16.0 | 8.2 | 14.9 | 0.5 | 0.3 | 0.5 | 3.5 | 6.5 | 2.2 | 17.7 | +| Team chat / type | 8.9 | 5.9 | 11.3 | 19.2 | 2.6 | 0.2 | 0.2 | 2.5 | 11.5 | 12.6 | 21.4 | +| Team chat / resize | 1.6 | 1.0 | 13.3 | 21.3 | 4.0 | 1.6 | 0.0 | 1.2 | 14.6 | 17.8 | 22.6 | +| Notes reader / step cursor | 13.1 | 15.1 | 13.0 | 16.4 | 7.4 | 0.4 | 0.4 | 8.4 | 7.3 | 2.4 | 9.7 | +| Notes reader / scroll | 21.8 | 26.1 | 12.1 | 6.7 | 0.4 | 0.0 | 1.9 | 5.8 | 2.2 | 1.3 | 10.8 | +| Notes reader / resize | 7.5 | 4.6 | 16.8 | 18.5 | 7.5 | 7.4 | 0.4 | 8.5 | 10.2 | 3.8 | 10.7 | + +Glyph rasterization and atlas work is at most 0.9% everywhere. Parley line breaking is at +most 3.4%. + +## The ten biggest costs + +Ranked by how often and how far each one takes frames past 8.3 ms. "Covered" refers to the +numbered items in [32](32-engine-plan.md) §4. + +1. **Team chat: a keystroke or a resize step rebuilds every message row.** A keystroke + commit takes 14.8 ms of CPU, 83% of it in view (12.3 ms). A resize step takes 18 to 20 ms + (view 16.8 ms), and 228 to 241 of 336 resize frames miss the budget. The view builds every + message, Markdown included, and then calls `El::virtualize`, which drops the offscreen rows + in `populate_virtual_children`'s non-`RowSource` branch + (`crates/rune/src/runtime/measure.rs:164-189`). The hot code is the app's row builder, + `rune_kit::markdown` (`markdown.rs:1556-1580`) and `el::text` (`el.rs:970-1006`). + *Not covered.* #4 excludes virtual lists, #8 helps only if the app memoizes rows, and + nothing makes `virtualize` build lazily. The `virtual_rows` API already avoids this. +2. **Notes reader: each keystroke in the search palette blocks for 260 to 540 ms.** Mean wall + time per update is 263 ms (p95 538 ms, worst 658 ms) while CPU stays at 3 ms. 90% of + main-thread samples sit in `recvfrom`: the key handler sends a search request to a local + daemon over a Unix socket and waits for the answer. This one cause accounts for the whole + hitch. *Not covered*, since the cost is in the app. Rune has nothing that reports a frame + whose wall time far exceeds its CPU time. +3. **Task board: opening a card or scrolling a long one re-runs the whole view.** Spike frames + cost 18 ms (open) and 28 ms (long card). That is view 9 to 10 ms (36% to 50%), + flatten and bookkeeping 3.6 to 6.5 ms, apply 1.3 to 4.2 ms and the app's poll 2 ms. 106 of + 324 and 82 of 361 frames miss. During a scroll, a virtual window or layout-read change sets + off a full commit (`runtime.rs:2285-2303` → `commit` → `measure`). That commit rebuilds the + card's note Markdown along with everything else. *Partly covered:* #2 (apply) and #3, #7 + and #8 (flatten). Nothing in the plan limits a window shift to building the newly mounted + rows. +4. **Task board launch: the first frame takes 86 to 172 ms of CPU, and opening the diagram + card 136 ms.** 27 to 38 ms of that is shaping text seen for the first time. Layout takes 13 + to 47 ms and view 20 to 44 ms over 1,350 to 4,800 layout nodes. This is a one-time spike, + almost all of it first-use shaping and layout of everything mounted. *Partly covered:* #9 + (resolved-style cache, −1.5 to −2.5 ms) and #10 (virtualized Markdown). The real cost is + 5 to 9× the plan's 18 ms `md-open` baseline because the whole board mounts. +5. **Live resize of virtualized views re-runs view and flatten on every step.** Notes reader: + 7.6 ms per step (view 1.4, layout 2.1, text 0.5, apply 1.3, flatten about 1.2, paint 0.7), + 102 of 242 frames over. Agent client: p50 4.9 ms, 18 of 266 over. `text_hash` alone is 8% of + the notes reader's resize (about 0.6 ms) and 4.4% of the agent client's; Taffy is 6% to 7%. + *Covered in idea only.* #4's fast path would skip about 1.4 to 2 ms here, but its gate + (`virtuals.is_empty()`) rejects all four apps. #5's projected saving holds: 0.2 to 0.6 ms. +6. **A small state change commits the whole tree.** Stepping the notes reader's block cursor + costs 6.4 ms with 25k allocations, and 30 of 96 frames miss. An agent client keystroke + costs 3.4 ms, and a streamed chunk 4.2 ms. The costs are in `flatten` (5% to 13%; + `flatten.rs:222` moves each `Node` in, `:340` compares Taffy styles), `El::clone` of `memo` + hits (2% to 7%, `expand_memo`), `apply` (3% to 6%, `runtime.rs:4449`), `Keyed::new` (2% to + 3%, `layout_read.rs:585`, a fresh map of every keyed node on each commit) and + `capture_keeps` (2.8%, `sticky.rs:439`). *Mostly covered* by #3, #7 and #8 (flatten, + clones) and #2 (apply). `Keyed::new` and `capture_keeps` are not. +7. **Paint re-emits every visible glyph every frame.** On scroll, paint takes 0.4 to 1.2 ms a + frame. Parley glyph iteration plus `push_glyph` (`runtime.rs:6959-6994`, `text.rs:2153`, + Parley `run.rs:335-359`) is 21% to 37% of a scroll frame, and the per-node walk + (`runtime.rs:5734`) another 13% to 22%. That makes it the floor under every scroll and + animation frame, and it grows with window size. *Not covered*, except #7's culling of + offscreen subtrees. Onscreen text has no cached quads. +8. **Task board: the app's poll costs 1.0 to 1.8 ms every frame, 98% of the time with no + change.** It makes 8k to 13k allocations a frame, half of a board-scroll frame. The cost is + in the app's per-frame status checks. *Not covered* (app code). +9. **Motion upkeep: `Scene::present_dirty` and `Scene::phase`.** These take 2% to 12.5% of + busy time, most on board scroll (about 0.24 ms a frame). Apply takes 4.2 ms on the long + card's spike frames. *Covered* by #2. Its −2.3 ms holds only for the largest tree (the + board's 4,800 nodes). The other apps' trees are smaller and would save 0.1 to 0.5 ms. +10. **First frames in the chat and agent client: 28 to 45 ms of CPU.** In the chat, the view + takes 26 ms because every row is built (as in #1), and paint takes 9 ms rasterizing glyphs + for the first time. In the agent client, layout takes 13 ms and text 12 ms for 102 texts. + *Partly covered* by #9 and #10. + +## Checking [32](32-engine-plan.md) against real data + +| # | Plan item | Real data | +|---|---|---| +| 1 | Per-paragraph `TextLayout` | None of the measured interactions types into a long field: the agent client's composer is short and the notes reader has no editor. Shaping is ≤ 3.5% everywhere, so −14 ms doesn't show up here. Still worth doing for long-field editing, but it isn't what these apps hit today. | +| 2 | Lazy motion tracks, no-op dirty | Holds. Motion is 2% to 12.5%, and apply is 0.6 to 4.2 ms on commit frames. Saves 0.1 to 0.5 ms on small trees and more on the board. | +| 3 | `has_virtual` bit and path table | Holds. `node_path` 2.2% and memo deep clones 2% to 7% match root cause 1. | +| 4 | Resize fast path | Doesn't fire on any measured app: all four have a virtual list. Its saving (~1.4 to 2 ms a step) is real only if the gate admits virtual lists whose window doesn't change. | +| 5 | One `shape_key` hash | Holds: `text_hash` is 2% to 8%, so 0.2 to 0.6 ms. | +| 6 | In-place re-break | Not visible. `Layout::clone` isn't among the top functions of any profile. | +| 7 | Compact `BoxStyle`, `Cold<T>`, culling | Holds for flatten (`:222` Node moves and `:340` style compares are its top lines). Culling is the plan's only paint change. | +| 8 | Flattened `memo` reuse | The best fit for #3 and #6, but only where apps memoize. The chat app doesn't. | +| 9 | Resolved-style cache | Small next to the board's 27 to 38 ms first-frame shaping. | +| 10 | Virtualize Markdown | Applies to card notes and transcript messages at first mount, not in steady state. | +| 11 | Single-pass `aspect_fit` | Not seen. | +| 12 | Word shape cache | No trigger: shaping is ≤ 3.5% after launch. | + +What the plan misses: + +- **Lazy virtual lists.** `El::virtualize` accepts a fully built list. Rune could warn when a + virtualized list builds far more rows than it mounts, or make lazy building the default + path. +- **Window shifts that build only the new rows.** When a virtual window or a layout read + moves, Rune re-runs the whole view (#3, and the agent client's roughly 59 commits per scroll run, at 3.9 ms each). +- **A glyph quad cache in paint.** Keep each text node's quads keyed by layout, scale and + colour, and translate them when the node moves (#7). +- **Per-commit bookkeeping:** `layout_read::Keyed::new` and `sticky::capture_keeps` (#6). +- **Stall detection.** The frame log's wall-versus-CPU split is what exposed #2. A debug + warning when an update's wall time is many times its CPU time would catch blocking I/O on + the main thread. + +## Memory + +App heap, where the app counts it: task board 50 to 100 MB live heap, notes reader 9 to +21 MB. Malloc regions from `footprint`: agent client while streaming 177 MB, chat 86 MB. + +Headless footprint numbers can't be compared across runs. The headless loop submits a frame +each time without polling the device, so GPU work and its buffers pile up while the run +renders frames faster than real time. `IOAccelerator (graphics)` reached 155 to 784 MB over +1,800 to 8,300 regions and grew with the number of frames rendered, not with the +interaction. An idle notes launch reached 967 MB after 3 s, with heap at 9 MB. That explains +why the same chat scenario measured 0.25 GB in one run and 1.6 GB in another. A real window +paces itself on the surface, so these numbers say nothing about real windows. Compare heap, +not footprint, until the headless loop polls the device every frame. + +## Caveats + +- The worker was shared. Wall times include preemption: the agent client's wall p95 is 15 to + 43 ms against a CPU p95 of 4 to 9 ms. The CPU numbers are the ones to compare. +- Headless profiling misses GPU and presentation costs. A HUD overlay app was left out + because its costs are in overlay presentation, which headless doesn't model and which is + being changed separately. +- The workloads' data is real, apart from the notes reader's synthetic fixture and the chat's + repeated seed. + +## Reproduce + +Build an app at `--profile perf` with `rune/frame-profile`, write a scenario config (format in +`scripts/real-frames.py`'s docstring), then: + +``` +scripts/real-frames.py run app.json --out out/app --runs 5 --sample --sample-secs 90 +scripts/real-frames.py summary app.json --out out/app --table +scripts/real-frames.py profile out/app/scroll.sample.txt --top 30 +``` diff --git a/app/vendor/rune/research/34-own-gpu-plan.md b/app/vendor/rune/research/34-own-gpu-plan.md new file mode 100644 index 0000000..620bdd6 --- /dev/null +++ b/app/vendor/rune/research/34-own-gpu-plan.md @@ -0,0 +1,681 @@ +# 34. Should Rune own its GPU layer? Verdict, numbers and plan + +Reader: someone deciding whether Rune should replace `wgpu` with its own GPU layer, or choosing +which layer to own on each platform. Re-run `overlay_hud_cost` ([30](30-overlay-gpu-cost.md)), +`upload_bench`, `frame_bench`, `layout_text_cost` ([31](31-layout-text-cost.md)) and +`scripts/motion-audit` at every gate below. + +The question: from first principles, should Rune build and own its own GPU backend instead of +paying `wgpu`'s per-frame overhead or waiting on upstream? + +**Verdict: yes on Apple (`macOS` and `iOS`), no everywhere else.** Build a ~2,800-line native +Metal backend inside `crates/rune/src/gpu/metal/` on `objc2-metal`, `objc2-quartz-core` and +build-time `naga` (all already in `Cargo.lock`), bridged into `wgpu` 30's `custom` backend +trait (`features = ["custom"]`) plus a direct internal fast path for Rune's own uploads and +present. Keep `wgpu` on Windows (DX12), Linux (Vulkan) and Web (WebGPU), and send three small +bug-fixed patches upstream to `gfx-rs/wgpu` (~120 lines, hand-written descriptions) so Windows +and Linux drop the redundant present submission when upstream ships them. + +Why this split wins: + +1. **Continuous 120 Hz frames spend 30% to 75% of process CPU in `wgpu` and driver dispatch.** + That covers HUD overlays, `virtual_rows` scrolling, `gpu_springs` ticks and multi-pass blur + or lighting frames. Even with both prototype `wgpu` patches from [30](30-overlay-gpu-cost.md), + any frame that writes a uniform or instance buffer still commits 3 `MTLCommandBuffer`s plus + a `MTLBlitCommandEncoder` and `unmap`/`map_async` round-trip, costing ~1,428 + kinstructions/frame against ~850 kinstructions/frame in hand-written Metal. +2. **Heavy window commits spend only 1% to 3.5% (~0.15 ms) in `wgpu`.** On `stack` (10.2 ms), + `edit` (15.5 ms) and `md-resize` (4.35 ms), the commit, motion and paragraph-caching work in + [32](32-engine-plan.md) must carry the win. Once [32](32-engine-plan.md) brings memoized + commits and scrolling under 0.3 to 0.8 ms, `wgpu` becomes a major share of normal windows too. +3. **`wgpu::custom` keeps 100% of the public API compiling.** `Compositor`, `Frame`, + `EffectHook`, `rune-fx`, `rune-light`, `rune-staging`, headless pixel tests and downstream + apps keep their exact `wgpu::*` types on crates.io `wgpu ~30.0.1` without `[patch.crates-io]` + (which Cargo ignores in git dependencies anyway). +4. **Owning Metal is small (~2.8 kLOC); owning Vulkan and DX12 is 5 to 7 times larger (~15 to + 20 kLOC) where driver and Wayland/X11 swapchain bugs hurt small teams.** Zed (`zed#46758`) + dropped `blade` on Linux and returned to `wgpu` in January 2026 while keeping raw Metal on + macOS; Warp ships the same native-Metal-plus-`wgpu` split; Flutter Impeller's Vulkan backend + (~21 kLOC) is 3.5 times its Metal backend (~5.9 kLOC). + +## Default on macOS + +Since 2026-10-31 the native backend is the default on macOS: `metal-backend` is one of Rune's +default features, and an app that doesn't call `App::gpu_backend` draws with it, prewarm +included. `App::gpu_backend(GpuBackend::Wgpu)` or `RUNE_GPU_BACKEND=wgpu` opts out, and an app +built with `default-features = false` keeps wgpu unless it adds the feature. `GpuBackend`'s +`Default` is still `Wgpu`; the backend keeps the app's choice as unset, `Wgpu` or `Metal` +internally, so an explicit `Wgpu` always wins. wgpu's `custom` feature is turned on for macOS +targets only, so Linux, Windows, web and iOS builds compile what they did before. iOS keeps wgpu. + +Where the native backend falls short of wgpu, a defaulted app either falls back or fails loudly: + +- A compositor whose `Compositor::features` asks for something the backend doesn't offer (it + offers `TIMESTAMP_QUERY` and `IMMEDIATES`) gets a wgpu device for that window or headless run, said once. +- Pipelines made with `layout: None` derive their layout from the shaders, as wgpu-core does. +- Depth and stencil, multisampling, more than four colour targets, indirect draws and + dispatches, render bundles, occlusion and pipeline-statistics queries, timestamps written + inside or between passes, non-WGSL shaders, `clear_texture`, binding arrays and uncommon + texture or vertex formats panic with a message that names the opt-out. + +## 1. Where GPU CPU goes: HUD overlays vs normal windows + +### Code checks and corrections to earlier notes + +Checking `crates/rune`, `crates/rune-fx`, `crates/rune-light` and `wgpu` 30.0.1 source turned up +five facts that change the options: + +1. **Normal macOS windows do not use `PresentWorker`.** Only overlays spawn the `rune present` + worker (`crates/rune/src/overlay/frame.rs:57`). `crates/rune/src/window/draw.rs:269-275` runs + `encoder.finish()`, `queue.submit` and `queue.present` synchronously on the AppKit main + thread. Once Metal submit-and-present folds onto one `MTLCommandBuffer` (~35 µs instead of + ~214 µs), overlays can drop `PresentWorker` too, saving its thread and two `mpsc` wakeups per + frame (~14 to 25 ms per 10 s). +2. **Both prototype `wgpu` patches still leave +310 kinstructions/frame on any buffer write, and + $P + 1$ command buffers on $P$-pass frames.** In `wgpu-core` 30.0.1 + (`command/render.rs:2308-2315`), `encode_render_pass` calls `raw_encoder.close_if_open()` + ahead of every pass so it can splice a barrier buffer before the pass (`close_and_swap` at + `:2765`). Any `copy_buffer_to_buffer` recorded by `Staging::flush` (`Frame::write_buffer` or + `Renderer::prepare`) opens a non-empty blit `MTLCommandBuffer` that `encode_render_pass` + immediately closes. `wgpu-hal-metal-lazy-command-buffer.patch` only skips *empty* command + buffers, so every frame with an upload still commits 3 `MTLCommandBuffer`s (blit, render, + present) plus `unmap`, `map_buffer_on_submit` and channel recycling (+323 kinstructions in + [30](30-overlay-gpu-cost.md)). Multi-pass frames (`backdrop_blur`, `layer_blur`, `rune-fx`, + `rune-light`) commit $2P + 4$ command buffers unpatched and $P + 1$ patched (~2.3 MiB of + transient `IOAccelerator` memory per command buffer, `wgpu#10494`). +3. **`wgpu-hal-metal-lazy-command-buffer.patch` has three bugs.** First, `begin_encoding` + (`metal/command.rs:487`) increments `command_buffer_created_not_submitted`, and `end_encoding` + clears `self.begun = false` while returning `CommandBuffer { raw: None }`; if that buffer is + dropped unsubmitted, `CommandBuffer::drop` (`:1978`) returns early on `None` and leaks a slot + toward the 2,048 `DeviceError::Lost` limit. Second, `Queue::submit` (`metal/mod.rs:755`) + unconditionally sets `"(wgpu internal) Signal"` on the last non-empty command buffer, which + with lazy buffers is the caller's render pass buffer, clobbering its label. Third, moving + `relay.next_release_value.load(Acquire)` out of `begin_encoding` into lazy `cmd_buf()` races + concurrent submissions under strict event sync. +4. **`wgpu` 30.0.1 already exposes `wgpu::custom` (`features = ["custom"]`).** Every `wgpu` + handle dispatches over `Core | WebGPU | Custom` (`wgpu/src/dispatch.rs:728`), with public + `Instance::from_custom`, `Texture::from_custom` and `as_custom::<T>()`. Both `Core` and + `Custom` coexist in one binary (`RUNE_GPU_BACKEND=metal|wgpu`). Meanwhile, Rune's full + surface uses two features a minimal quad renderer would miss: 2-target MRT (`gb0`/`gb1` in + `crates/rune-light/src/render.rs:108`) and dynamic uniform offsets (`has_dynamic_offset: true` + in `crates/rune-fx/src/renderer.rs:342`). +5. **`wgpu-hal` alone neither reaches 1 command buffer on Metal nor stays thin on Vulkan/DX12.** + `hal::metal::Queue::present` (`metal/mod.rs:810`) always commits a separate `Present` command + buffer, and `hal::metal::Queue::submit` (`:739`) always heap-allocates a `block2::RcBlock` + completion handler (+81 kinstructions/frame combined in `metal_hud.swift`). On Vulkan and + DX12, `wgpu-hal` (`lib.rs:48-52`) requires explicit caller-computed `transition_textures` and + `transition_buffers` barriers, which would force Rune to rebuild `wgpu-core`'s state tracker + to keep multi-pass effects and user `Compositor`s sound. + +### Attribution: HUD overlay (120 Hz, `overlay_hud_cost`) + +From [30](30-overlay-gpu-cost.md) (paired runs at 120 Hz, `proc_pid_rusage` retired instructions +and slow-mode process CPU): + +- **0-write HUD:** Rune today runs 1,555 kinstr/frame (19.5% CPU, 6 command buffers, 2 + handlers) vs 850 kinstr/frame (11.2% CPU, 1 command buffer, 0 handlers) for + `metal_hud.swift`. The two `wgpu` patches cut 4 empty command buffers and the second present + submit (-437 kinstr, to 1,118 kinstr / 16.0% CPU), leaving 268 kinstr (58% of the 8.3-point + CPU gap). From the 8 s and 10 s thread profiles, that remaining 268 kinstr splits into three + parts: + - **~81 kinstr in `wgpu-hal` Metal:** separate `Present` command buffer plus 1 `RcBlock` + completion handler and driver notification (`929k - 848k` measured on `metal_hud.swift`). + - **~90 kinstr in `wgpu-core` and `wgpu-hal`:** per-frame `Surface` `Texture`/`TextureView` + allocations and registry locks (`10 ms/10 s` in `create_view` alone), `ArcCommand` record + and replay, `Tracker` `set_size`/drop (`43 ms/8 s` on the present thread), 55 heap + allocations/frame, and duplicate `Fence::get_latest` `status()` polls. + - **~97 kinstr in Rune's own overlay loop (being fixed separately):** `frame::step` on an + unchanged empty view (`46 ms/10 s`), `about_to_wait` and pointer polling (`22 ms/10 s`), + `PresentWorker` handoff/wait (`14 ms/10 s`), and duplicate `surface_occluded` layer walks. +- **1-write animating HUD (`OVERLAY_WRITES=1`, live meters/waveforms):** Rune today runs 1,881 + kinstr/frame (`Frame::write_buffer`) or 1,863 kinstr (`Queue::write_buffer`). Patched `wgpu` + still lands around ~1,428 kinstr/frame because the blit copy splits out a 3rd command buffer + and unmaps/remaps the staging chunk every frame. A unified-memory `MTLStorageModeShared` ring + in a single `MTLCommandBuffer` writes 256 B with one `memcpy` and + `setVertexBufferOffset`/`setFragmentBufferOffset` (< 2 kinstr). + +### Attribution: normal window frames (`upload_bench`, `frame_bench`, [29], [31]) + +Running `upload_bench` and `frame_bench` (`--profile perf`, headless Metal) gives 54.3 µs CPU +to prepare, encode and submit a 2,000-instance steady frame, 83.0 µs when all 2,000 instances +scroll (256 KiB staged upload), 15.1 µs to record 10 `rune-light` GI passes (before `finish()` +replays them into 20+ command buffers), and 97.9 µs for 16 `rune-fx` layers with 4 backdrop +blurs. Adding main-thread surface acquire (excluding `nextDrawable`'s own wait, which native +Metal shares), `create_view`, `present`'s extra submit and background driver threads puts +avoidable `wgpu` overhead in a 1-pass window at ~0.14 to 0.20 ms/frame (~0.35 to 0.55 ms/frame +with 6 to 10 blur/effect passes): + +| Window workload (120 Hz = 8.33 ms) | Rune CPU today ([29], [31]) | Avoidable `wgpu` + driver CPU | `wgpu` share today | Rune CPU after [32] | `wgpu` share after [32] | +|---|---:|---:|---:|---:|---:| +| `edit` (typing in 50 KB note) | 15.50 ms | ~0.16 ms | ~1.0% | ~1.00 ms | ~14% | +| `stack` (5,283 nodes, 1 flip) | 10.20 ms | ~0.16 ms | ~1.5% | ~3.8 ms (< 0.8 `memo`) | ~4% (~17% `memo`) | +| `md-resize` (50 KB width drag) | 4.35 ms | ~0.16 ms | ~3.5% | ~1.40 ms | ~10% | +| `md-same` (unchanged commit) | 1.98 ms | ~0.13 ms | ~6.2% | ~0.7 ms (< 0.25 `memo`) | ~16% (~34% `memo`) | +| `list` scroll (`virtual_rows`) | 0.15–0.31 ms | ~0.17 ms | **35–53%** | ~0.10–0.22 ms | **44–63%** | +| `gpu_springs` (`present_at` tick) | ~0.01 ms | ~0.17 ms | **> 90%** | ~0.01 ms | **> 90%** | +| Window + backdrop blur / `rune-fx` | 0.30–1.50 ms | ~0.35–0.50 ms | **20–60%** | 0.20–0.80 ms | **30–70%** | + +## 2. Comparison of options + +HUD numbers show the projection after Rune's ~97 kinstr overlay-loop fixes (with pre-fix +numbers in parentheses for 0-write) so GPU layers are compared on equal footing against +`metal_hud.swift` (850 kinstr / 11.2% CPU). + +| Option | HUD 0-write / 1-write (kinstr, slow CPU %) | Normal window CPU saved | LOC to write & own | Public API & feature impact | Startup & shaders | Key risks | +|---|---|---|---|---|---|---| +| **Today (`wgpu` 30.0.1)** | `1,458k` (`1,555k` raw) / `1,784k`; ~18.3% / ~22.3% | Baseline (0 ms) | 0 | None; 10 macOS `as_hal` sites depend on `wgpu-core` + `wgpu-hal`. | `uber.metallib` only (85 ms); `fx`/`light`/blur/iOS compile WGSL at runtime; `PipelineCache` no-op. | 6–24 CBs/frame; +310k/write; `get_current_texture` leaks `TextureId` on miss. | +| **(A) Patched `wgpu` fork + upstream PRs** | `~1,021k` (`1,118k` raw) / **`~1,331k`**; ~13.5% / ~17.5% | ~0.06 ms (1-pass); ~0.15 ms (blur, empty CBs only) | ~150 LOC patch + fork rebases | **Cargo ignores `[patch]` in git deps**: every app must copy `[patch.crates-io]` or face split `wgpu` versions. | Unchanged (`Passthrough` still lacks `sized_bindings` & `override`; no `MTLBinaryArchive`). | Upstream Metal review is slow (`#5738` open since 2024); never fixes 1-write (+310k) or $P$-pass CB split. | +| **(B) macOS `CAMetalLayer` bypass + `from_hal`** | `~1,195k` (`~1,292k` raw) / `~1,505k`; ~15.4% / ~19.3% | ~0.04 ms | ~250 LOC in `crates/rune` | Zero breakage, but still links `wgpu-hal` + `wgpu-core`. | Unchanged. | Strictly worse than (A): `Transit` + `Pre Pass` + split `Present` CBs (4–5 CBs/frame) and per-frame `TextureId` churn stay. | +| **(C) `wgpu-hal` directly on Metal, DX12, Vulkan (Web on `wgpu`)** | `~935k` / `~960k` (2 CBs, 1 `RcBlock` handler); ~12.3% / ~12.6% | ~0.11 ms (1-pass); ~0.25 ms (multi-pass) | **~5,500–7,500 LOC** (incl. Vulkan/DX12 barrier tracker & fence ring) | Must wrap in `wgpu::custom` or break `Compositor`/`Frame`/`fx`/`light`. | Still no `MTLBinaryArchive`; `hal` passthrough still lacks `sized_bindings` unless forked. | **High:** `wgpu-hal` is semver-unstable with undocumented `unsafe` contracts; missing Vulkan/DX12 barriers corrupt user `Compositor`s. | +| **(D) Own Metal (`macOS`/`iOS`) via `wgpu::custom` + internal fast path; `wgpu` elsewhere + 3 upstream PRs** *(Recommended)* | **`~855–880k`** (`~955k` pre-overlay-fix) / **`~860–890k`**; **~11.3–11.6%** (1 CB, 0 handlers) | **~0.14–0.19 ms** (1-pass, −35–50% scroll CPU); **~0.35–0.48 ms** (multi-pass) | **~2,800 LOC** (−350 LOC `as_hal` deleted); 0 new Cargo deps | **Zero breakage:** `Compositor`, `Frame`, `fx`, `light`, video `IOSurface`, headless & web compile unchanged; runtime `RUNE_GPU_BACKEND=wgpu` toggle. | Build-time Naga WGSL→MSL→`.metallib` for **all** shaders (`macOS` + `iOS`) + on-disk `MTLBinaryArchive` (< 15 ms warm). | **Low:** scoped to Apple's stable Metal 2.3 API; `wgpu` stays as A/B oracle and Linux/Windows/Web workhorse. | +| **(E) Own backends everywhere (Metal, DX12, Vulkan; Web on `wgpu`)** | Same as (D) on Apple (`~855–880k`) | Same as (D) on Apple; ~0.12–0.20 ms on Win/Linux | **~17,000–23,000 LOC** + DXC/SPIR-V build & allocator stack | Same `wgpu::custom` bridge, but must emulate full WebGPU surface for `Compositor` on 3 APIs. | Offline `.metallib` + DXIL + SPIR-V + `VkPipelineCache`. | **Very high:** Wayland/X11/NVIDIA swapchain hangs (`zed#46758`), D3D12 descriptor heaps/DirectComposition, Lavapipe CI quirks. | + +## 3. Internal seam and public API preservation + +Rune keeps `wgpu` types at the public boundary (`Gpu`, `Renderer`, `Compositor`, `Frame`, +`EffectHook`) by enabling `wgpu = { version = "~30.0.1", features = ["custom", ...] }` on +`macOS` and `iOS` only (Windows, Linux and Web compile without `custom`, preserving `wgpu`'s +single-variant devirtualization there). Across 60 draws and 10 bind groups, `custom`'s vtable +dispatch adds ~75 calls (~0.1 µs, ~0.4 kinstr). Internally, Rune's window loop, overlay loop, +`Uploads` and `native_surface` downcast once to `MetalQueue` / `MetalDevice` / `MetalSurface` +to bypass staging blits, `PresentWorker`, and `as_hal`: + +```rust +// crates/rune/src/gpu/mod.rs: internal fast-path seam alongside wgpu::custom +pub(crate) trait BackendHooks { + fn write_shared_ring(&self, bytes: &[u8], align: u64) -> Option<(wgpu::Buffer, u64)>; + fn submit_and_present(&self, encoder: wgpu::CommandEncoder, frame: wgpu::SurfaceTexture); + fn uses_present_worker(&self) -> bool; // false on Metal (1-CB commit is ~35 us) +} + +// crates/rune/src/gpu/metal/command.rs: 1 MTLCommandBuffer across all blit/compute/render passes +enum ActiveEncoder { + None, + Render(Retained<ProtocolObject<dyn MTLRenderCommandEncoder>>, RenderStateCache), + Compute(Retained<ProtocolObject<dyn MTLComputeCommandEncoder>>, ComputeStateCache), + Blit(Retained<ProtocolObject<dyn MTLBlitCommandEncoder>>), +} + +pub(crate) struct MetalEncoder { + cmd_buf: Mutex<Option<Retained<ProtocolObject<dyn MTLCommandBuffer>>>>, + active: Mutex<ActiveEncoder>, +} + +impl wgpu::custom::CommandEncoderInterface for MetalEncoder { + fn begin_render_pass(&self, desc: &wgpu::RenderPassDescriptor<'_>) -> DispatchRenderPass { + let cb = self.ensure_cmd_buf(); + self.end_active_encoder(); // closes Blit/Compute without closing MTLCommandBuffer + DispatchRenderPass::custom(MetalRenderPass::open(&cb, desc)) + } + // begin_compute_pass and copy_* switch ActiveEncoder on the same MTLCommandBuffer. +} + +impl MetalQueue { + /// Window and overlay path: 1 command buffer, presentDrawable on it, MTLSharedEvent fence, + /// and 0 RcBlock completion handlers unless map_async / on_submitted_work_done registered one. + pub(crate) fn submit_presenting(&self, encoder: wgpu::CommandEncoder, frame: MetalDrawable) -> u64 { + let (cmd_buf, callbacks) = self.finish_custom(encoder); + let ticket = self.next_ticket.fetch_add(1, Ordering::Relaxed) + 1; + cmd_buf.encodeSignalEvent_value(&self.shared_event, ticket); // GPU counter, no ObjC block + if !callbacks.is_empty() { self.arm_event_listener(ticket, callbacks); } + if !frame.presents_with_transaction { + cmd_buf.presentDrawable(&frame.drawable); + cmd_buf.commit(); + } else { + cmd_buf.commit(); + cmd_buf.waitUntilScheduled(); + frame.drawable.present(); + } + self.retire_completed(self.shared_event.signaledValue()); + ticket + } +} +``` + +How every existing subsystem keeps working without signature changes: + +- **`Compositor` and `Frame` (`crates/rune/src/compose.rs`):** `Frame` still hands callers + `&wgpu::Device`, `&wgpu::Queue`, `&mut wgpu::CommandEncoder` and `&wgpu::TextureView`. App + compositors (`overlay_hud_cost`, `lab`, `cursed-settings`, `rune-fx`, `rune-light`) record + straight into `MetalEncoder`'s single `MTLCommandBuffer` through `wgpu::custom`. +- **Uploads (`Uploads` and `rune-staging`):** On Apple unified memory, `Renderer` and + `Frame::write_buffer` allocate from a triple-buffered `MTLStorageModeShared` ring retired by + `shared_event.signaledValue()`, copying bytes directly into `MTLBuffer.contents()` and binding + offsets with zero `MTLBlitCommandEncoder`s and zero `map_async` callbacks. Glyph and image + atlas row updates record `copyFromBuffer:toTexture:` on the frame's `MTLCommandBuffer` ahead + of the first render pass without closing the command buffer. +- **Video (`native_surface/macos.rs`) and AppKit (`macos.rs`, `present_time.rs`, + `system_material`):** `MetalDevice::import_cv_pixel_buffer` wraps `CVMetalTextureGetTexture` + directly via `wgpu::Texture::from_custom` (retaining `CVMetalTexture` + `PixelBuffer` in the + custom texture's `Drop`), and `MetalSurface::layer()` exposes `&CAMetalLayer` without + `wgpu-hal` or `wgpu-core`. +- **Headless tests & CI:** `Gpu::headless()` uses `MetalInstance` on macOS (1 `MTLCommandBuffer` + + `MTLBlitCommandEncoder` readback to a shared `MTLBuffer`) and `wgpu` Vulkan/Lavapipe on + Linux CI. Setting `RUNE_GPU_BACKEND=wgpu` switches macOS back to `wgpu-core` for differential + pixel and timing checks in the same binary. + +## 4. Phased plan and measurable gates + +### Parallel track: upstream three small fixes to `gfx-rs/wgpu` (~120 LOC, non-blocking) + +Fix the three bugs in `wgpu-hal-metal-lazy-command-buffer.patch` (decrement the counter when +dropping an unsubmitted `raw: None` `CommandBuffer`, preserve user command buffer labels on +signal, latch `relay.next_release_value` in `begin_encoding`), pair it with +`wgpu-core-present-skip.patch` and a `fid` cleanup on failed `surface_get_current_texture` +(`wgpu-core/src/present.rs:449`), and submit PRs with hand-written descriptions per `wgpu`'s +contribution policy. Do not block Rune on upstream review or carry a `[patch.crates-io]` fork; +once merged into a `wgpu` point release, Windows DX12 and Linux Vulkan gain single-submit +presentation automatically. + +### Phase 0: First spike (≤ 450 LOC, ≤ 1 day), single-CB `wgpu::custom` Metal + Naga MSL + +The two riskiest assumptions are (1) that `wgpu::custom` over `objc2-metal` + `MTLSharedEvent` +runs `overlay_hud_cost` unchanged with 1 command buffer, 0 completion handlers and 0 blit +encoders (eliminating both the empty-CB tax and the +310 kinstr upload tax), and (2) that +standalone `wgpu::naga` (`wgsl` → `process_overrides` → `msl`) compiles every WGSL shader in +`rune`, `rune-fx` and `rune-light` (`_mslBufferSizes`, `override`s, atomics, MRT) cleanly. + +1. **Build `crates/rune/src/gpu/metal_spike.rs` (~380 LOC, gated on `RUNE_GPU_BACKEND=metal`):** + implement minimal `InstanceInterface`, `SurfaceInterface` (`CAMetalLayer::nextDrawable`), + `DeviceInterface`, `BufferInterface` (`MTLStorageModeShared` direct write), + `CommandEncoderInterface`, `RenderPassInterface`, and `MetalQueue::submit_presenting` + (`presentDrawable` + `MTLSharedEvent`, 0 `RcBlock`s). +2. **Add a standalone Naga→MSL compile test (~60 LOC):** translate all 29 WGSL shaders (with + `layer_blur` override specializations and `rune-light`/`gpu_springs` storage-buffer size + slots) and compile each via `MTLDevice::newLibraryWithSource`. +3. **Exact measurement (`--profile perf`, real HUD window on a dedicated test Mac, 4 alternating + 10 s rounds after 2 s warmup, `OVERLAY_WRITES=0` and `OVERLAY_WRITES=1`):** + - **Go gate:** `OVERLAY_COUNT_METAL=1` reports `command_buffers=1.00`, `presents=1.00`, + `completed_handlers=0.00`, `blit_encoders=0.00` on both `WRITES=0` and `WRITES=1`; + `WRITES=0` lands within ≤ +40 kinstr/frame (≤ +0.5 CPU percentage points) of + `metal_hud.swift` once paired with the overlay-loop fixes (or ≤ 960 kinstr before them, + ≥ 595 kinstr below today's 1,555k); `WRITES=1` adds ≤ 15 kinstr/frame over `WRITES=0` + (down from +310–323 kinstr today); all 29 WGSL shaders compile to `MTLLibrary`. + - **Kill / pivot gate:** if `wgpu::custom` blocks a required `wgpu` handle operation or adds + `> 25 kinstr/frame` of dispatch overhead, keep the Metal backend and swap the `wgpu::custom` + shim for an internal `gpu::Encoder` enum (`Metal | Wgpu`). If single-CB Metal itself fails + to beat patched `wgpu` by `≥ 180 kinstr` on `WRITES=0` and `≥ 400 kinstr` on `WRITES=1`, + abandon owning Metal and ship only the upstream `wgpu` patches. + +### Phase 1: Core Metal backend, unified-memory upload ring and window/overlay integration (~1,500 LOC) + +- Implement full 2D textures, sRGB/linear views, mip views, samplers, MRT render passes (up to 4 + color attachments), dynamic uniform offsets, state deduplication, blit copies (`buf↔tex`, + `tex↔tex`, headless `tex→buf` readback), and `MTLSharedEvent` deferred-free resource + retirement (`Vec<(u64, Vec<Retained<AnyObject>>)>`). +- Wire `Uploads` and `Frame::write_buffer` on Metal to a bounded `MTLStorageModeShared` ring (no + staging copy or `map_async`), encode dirty glyph/image atlas blits onto the frame's single + `MTLCommandBuffer` without closing it, fold `submit + present` in `window/draw.rs` and + `overlay/frame.rs`, and skip spawning `PresentWorker` when running on `MetalQueue`. +- **Gate:** `cargo test -p rune -p rune-kit --features rune-kit/markdown` green on + `RUNE_GPU_BACKEND=metal`; `scripts/check-reference.sh` (`rune-ref`) and CoreText golden tests + match `wgpu` pixel-for-pixel; `scripts/motion-audit` passes with a HUD/scroll scenario added; + `upload_bench --profile perf` drops `steady` `54 µs → ≤ 15 µs` and `scroll` `83 µs → ≤ 22 µs` + with `0` buffer allocations/frame; `bench-ui.py --frame-cpu --scroll` + window present trace + commits `1.00` command buffer/frame and cuts total main+driver scroll CPU by `≥ 120 µs/frame`. + +### Phase 2: Compute, timestamps, `rune-fx`/`rune-light`, `IOSurface` video and `as_hal` removal (~900 LOC, −350 LOC deleted) + +- Add `MTLComputePipelineState`, `MTLComputeCommandEncoder` (switching cleanly inside the same + `MTLCommandBuffer`), `_mslBufferSizes` sideband `setVertexBytes`/`setFragmentBytes`/`setBytes`, + and `MTLCounterSampleBuffer` timestamp queries (`resolve_query_set`). +- Move `macos.rs`, `present_time.rs`, `system_material/macos.rs` and `native_surface/macos.rs` + (`CVMetalTextureCache` zero-copy BGRA/NV12 import) onto `MetalSurface` / `MetalDevice` + directly; make `RUNE_GPU_BACKEND=metal` the default on `macOS` and `iOS` and gate `wgpu`'s + `metal` feature + `wgpu-hal`/`wgpu-core` behind an optional `wgpu-metal-fallback` dev/debug + feature. +- **Gate:** `rune-fx` and `rune-light` test suites and `video_gui` pass (`live_planes == 0` on + drop); `frame_bench --profile perf` (including `finish + submit`) commits 1.00 + `MTLCommandBuffer`/frame across all 10+ GI and glass passes (down from 16–24), cutting + multi-pass submit+driver CPU by `≥ 60%`; `layout_text_cost` shows 0% regression; + `scripts/file-size.sh` passes with every new file under 800 non-test lines. + +### Phase 3: Build-time `.metallib` bundle for all shaders + `MTLBinaryArchive` cache (~450 LOC) + +- Extend `scripts/precompile-metal-shaders.sh` to run Naga (`wgsl` → `process_overrides` → + `msl`) and `xcrun metal` for `macos`, `ios` and `ios-simulator` across all library shaders + (`uber` + `gpu_springs`, `backdrop_blur`, `layer_blur`'s 5 specializations, `video`, + `rune-fx`'s 13 modules, `rune-light`'s 7 modules), embedding `.metallib` bytecode plus compact + `sized_bindings` tables (falling back to runtime Naga WGSL only for custom app shaders). +- Add a bounded on-disk `MTLBinaryArchive` keyed by `(OS build, GPU name, ABI hash)` so pipeline + creation hits cached GPU ISA after first launch. +- **Gate:** cold pipeline init for `Renderer` + `FxRenderer` + `LightRenderer` drops `≥ 3×` + (`≤ 80 ms` cold AIR, `≤ 15 ms` warm archive); `scripts/bench-startup.py` `first-pixels` median + beats or matches baseline; `.metallib` freshness and pixel-equivalence tests pass across + `rune`, `rune-fx` and `rune-light`. + +#### Done: every built-in pipeline precompiled (native backend, macOS and iOS) + +`gpu/metal/builtin.rs` looks up each pipeline's function in `builtin_native.metallib` before it +calls naga. The key hashes everything that decides naga's MSL: the WGSL, stage, entry point, +override constants, runtime checks, point size, and the slots *this pipeline's layout* hands out. +So a precompiled function binds exactly what the runtime path would give it, and a table row +carries the sized bindings and the workgroup size. A module whose WGSL is built in isn't parsed +unless a pipeline misses the table. `scripts/precompile-metal-shaders.sh` captures the MSL +(`RUNE_METAL_CAPTURE`) from rune-light's `builtin_shaders` test, which builds every pipeline, +and compiles it for macOS, iOS and the iOS simulator: 60 pipelines, 53 distinct functions, each +in its own namespace. The capture builds the uber shader from WGSL too, since iOS has no +`uber_native.metallib`. +The same test fails on a miss, so a shader edit without a regenerate shows up there. App shaders +miss the table and compile at runtime as before. + +Measured with `shader_first_use` (`--profile perf`, fresh processes, 10 alternating rounds, +medians, M-class MacBook Pro). Cold means `com.apple.metal` was cleared before the run: + +| First use | Cold, runtime MSL | Cold, precompiled | Warm, runtime | Warm, precompiled | +|---|---|---|---|---| +| `Renderer::new` (uber, already precompiled) | 110 ms | 114 ms | 1.2 ms | 1.3 ms | +| backdrop blur + composite | 394 ms | 29 ms | 2.2 ms | 0.7 ms | +| layer blur (5 specializations) | 727 ms | 45 ms | 1.6 ms | 0.2 ms | +| video | 201 ms | 22 ms | 1.1 ms | 0.2 ms | +| transparent window (straight alpha) | 87 ms | 5 ms | 0.2 ms | 0.1 ms | +| `Renderer::with_springs` | 305 ms | 81 ms | 3.3 ms | 0.2 ms | +| `FxRenderer::new` (before lazy pipelines, below) | 3,627 ms | 1,260 ms | 32.5 ms | 1.2 ms | +| `FxRenderer::add_format` (likewise) | 1,283 ms | 1,263 ms | 15.1 ms | 0.8 ms | +| fire simulation | 1,207 ms | 101 ms | 2.0 ms | 0.2 ms | +| `LightRenderer::new` | 1,389 ms | 127 ms | 5.7 ms | 0.6 ms | +| `GlassRenderer::new` | 392 ms | 126 ms | 6.0 ms | 4.0 ms | + +Most of a cold pipeline is Metal's front end (MSL to AIR). Clearing only Metal's library cache +cost a first layer blur 555 ms, and clearing only its function cache cost 45 ms. What remains is +GPU code generation, which the precompiled library can't skip. That's why `add_format`, the same +fx functions for another format, stayed at 1.26 s cold (until rune-fx stopped building pipelines it +hadn't drawn, below). 1,669 readbacks across the rune, rune-fx +and rune-light tests were byte-identical with the library on and off. `settings` first pixels +didn't change (it builds only the uber pipeline). + +Cost: 539 KB in the binary (`settings` stripped: 17.37 → 17.90 MB). The library compresses to +235 KB with deflate, which macOS's Compression framework could decode in about a millisecond. +That's left for later. naga stays in every binary: its WGSL front end, validator and MSL back end +are about 1.3 MB of `settings`' 11.2 MB of code, and both wgpu's backend in the same binary and +app shaders need them. The wgpu backend doesn't use the library. + +On the iOS 27 simulator (same Mac, 6 alternating rounds for `shader_first_use`, 8 for +`embed_cost`, medians; cold clears the simulator's and the host's `com.apple.metal`), the +precompiled library also covers the uber shader, which compiled at runtime there before: + +| First use, iOS simulator | Cold, runtime MSL | Cold, precompiled | Warm, runtime | Warm, precompiled | +|---|---|---|---|---| +| `embed_cost` first frame | 430 ms | 243 ms | 35.0 ms | 31.6 ms | +| `Renderer::new` (uber) | 390 ms | 194 ms | 5.9 ms | 2.6 ms | +| layer blur | 723 ms | 10 ms | 3.4 ms | 1.3 ms | +| `FxRenderer::new` | 2,098 ms | 85 ms | 40.7 ms | 5.2 ms | +| `LightRenderer::new` | 1,254 ms | 27 ms | 9.5 ms | 1.9 ms | +| every built-in pipeline | 6,631 ms | 440 ms | 102 ms | 18 ms | + +The device library (`builtin_native_ios.metallib`) compiles from the same MSL but hasn't run on +a phone yet. + +#### Done: rune-fx builds a pipeline the first time a frame draws it + +`FxRenderer::new` built every effect family (8) in both blends (16 pipelines), plus the mask +pyramid's and the backdrop blur's three, serially on the calling thread, and `add_format` built the +16 again for each extra format, whether or not the app ever drew those effects. After the library, +what's left of a cold pipeline is GPU code generation, and none of it is shared: per pipeline, on a +cold cache, glow 35 ms, pulse 31, electric 38, fire 74, distort 61, motion 21, extras 39 and fill +152, and the screen blend and the `Rgba16Float` format each cost as much again as the first, since +Apple GPUs blend in the fragment shader and each format is its own variant. Serially that's +937 ms per format. + +Now each `(format, family, blend)` pipeline sits in a `OnceLock` and is built when a frame first +needs it. `prepare` builds the ones its layers use for the frame's format, in parallel (scoped +threads; Metal compiles concurrently, and wgpu's `Device` is `Send + Sync`), and a draw into +another format builds its own on demand. The mask pyramid and backdrop blur passes wait for +`build_mips` and the first frosted layer. The keys the precompiled library looks up don't change, +so `builtin_shaders` (which now calls `FxRenderer::build_every_pipeline`) still finds all of them. + +Measured with `crates/rune-fx/examples/first_glow.rs` (`--profile perf`, fresh processes, +10 alternating rounds, medians, an M4 Pro Mac mini, native Metal backend with the library): new +renderer, `add_format(Rgba16Float)`, then prepare, draw, submit and read back one glow. + +| First glow | Cold, before | Cold, after | Warm, before | Warm, after | +|---|---|---|---|---| +| `FxRenderer::new` | 919 ms | 0.14 ms | 1.47 ms | 0.10 ms | +| `FxRenderer::add_format` | 865 ms | 0.00 ms | 0.67 ms | 0.00 ms | +| first frame (prepare, draw, read back) | 5.8 ms | 70.7 ms | 5.6 ms | 6.1 ms | +| **total, `new` to pixels** | **1,799 ms** | **70.9 ms** | **7.9 ms** | **6.2 ms** | + +About half of the 70 ms is a fresh process's first pipeline warming Metal's compiler up; after a +`Renderer::new` (as in an app) the same glow pipeline takes 40 to 50 ms cold. All 35 pipelines at +once (`shader_first_use`'s `fx_every_pipeline`, both formats, in parallel) take 410 ms cold against +1,796 ms for `new` plus `add_format` before; 16 pipelines on 16 threads take 217 ms, on 4 threads +332 ms, serially 937 ms. + +- **Considered: compile everything in the background at `new` and wait only at first draw.** The + glow is ready just as fast (70 ms, it goes first), but it spends about 930 ms of compiler time + per format on effects an app may never show, competing with its launch. +- **Considered: skip an effect until its pipeline is ready.** No frame would wait, but the first + frame would draw without the effect and then pop it in, and readbacks of a first frame would + change. +- **Not split: the two blend states.** Screen blending (`One, OneMinusSrc`) needs the destination, + which only fixed-function blending gives without a backdrop copy, so it stays its own pipeline, + built only when a `FxBlend::Screen` slot draws. + +#### Considered, not done: `MTLBinaryArchive` + +Measured on the native backend after step 4, on an M2-class Mac, with fresh processes and medians +of 10 alternating runs. `Renderer::new` builds one uber pipeline per format, and that one pipeline +is the whole cold cost: 89 ms with macOS's per-app shader cache cleared, 0.94 ms warm. + +- **Runtime archive, written by the app:** cold drops to 13.7 ms (9.2 ms of that is loading the + archive), but warm rises to 6.1 ms (5.2 ms load), and a first run that writes the archive costs + +38 ms. It only helps when macOS's cache is cold but ours is valid. macOS's cache survives + reboots, and the cases that empty it (first launch, OS or GPU driver update, shader change) also + leave our archive empty or stale. Archive hits don't refill macOS's cache, and + `FailOnBinaryArchiveMiss` doesn't count macOS's cache, so we can't tell when to skip it. + `MTLBinaryArchive.h` also advises against writing archives at runtime in shipping apps. +- **Shipped archive, built offline with `metal-tt`** for its 18 default Apple GPU variants: 1.12 MB + for the windowed format alone, 2.63 MB for Rune's four formats. One-pipeline builds were + byte-identical, but four-pipeline builds came out different on each of five runs. `xz -9` + shrinks the variants to about 56 KB per format (60 KB for all four together), so per-format + compressed archives would add about 225 KB, at the cost of first-launch decompression, a marker + file and a background recompile to fill macOS's cache. That's too much for about 75 ms once per + install or OS update. +- **Revisit if:** cold first launch becomes a measured complaint, `metal-tt` output becomes + deterministic, Apple shrinks offline archives, or many more pipelines move onto the startup path + and make the cold cost much larger. + +## 5. Triggers to expand or abandon + +- **Abandon / roll back to `wgpu` + upstream patches** if: (a) Phase 0 misses its kill gate, + (b) `crates/rune/src/gpu/metal/` exceeds 3,500 non-test LOC, or (c) Metal backend parity + causes `> 2` pixel or pacing regressions in a quarter once Phase 2 ships (`RUNE_GPU_BACKEND=wgpu` + provides an immediate fallback before `wgpu-metal-fallback` is ever removed). +- **Expand to an owned Windows DX12 backend (~3.5–4.5 kLOC)** only if, after upstream + `present-skip` ships and [32](32-engine-plan.md) Phases 1–3 land: (a) a real Windows 120 Hz + HUD or scrolling app spends ≥ 25% of frame CPU and ≥ 0.35 ms/frame inside + `wgpu_core`/`wgpu_hal::dx12`, and (b) every library shader precompiles offline to signed DXIL + so Rune never ships `dxcompiler.dll` (~20 MB) at runtime. +- **Never own WebGPU** (`wgpu` on `wasm32` already compiles straight to browser WebGPU bindings + without `wgpu-core`), and **do not own Linux Vulkan** unless `wgpu-core` exceeds 0.50 ms/frame + (> 30%) on a 120 Hz Wayland layer-shell workload after `present-skip` and a targeted upstream + `wgpu-hal/vulkan` patch cannot fix it. + +## Spike results (Phase 0) + +Code: `crates/rune/src/gpu_metal/` behind the `metal-spike` cargo feature and +`RUNE_GPU_BACKEND=metal` at run time; wgpu stays the default, and a build without the feature +compiles none of it. About 600 lines of backend (half of it `wgpu::custom` trait stubs), a +285-line shader test and a 90-line dispatch benchmark (`examples/metal_spike_dispatch.rs`). + +A frame through it: `nextDrawable` after waiting on an `MTLSharedEvent` counter if two frames +are in flight; the encoder makes one `MTLCommandBuffer` (`commandBufferWithUnretainedReferences`) +on its first render pass; `Queue::submit` holds a buffer that drew into the drawable; +`Queue::present` calls `presentDrawable` on that buffer, signals the event and commits. +`Queue::write_buffer` copies straight into `MTLStorageModeShared` memory. The overlay's +`submit_and_present` skips `PresentWorker` on this backend. No completion handlers. + +### Verdict + +| Gate | Result | | +| --- | --- | --- | +| 1 CB, 1 present, 0 handlers, 0 blits at `WRITES=0` and `1` | 1.00, 1.00, 0.00, 0.00 at both | go | +| `WRITES=0` ≤ 960 kinstr/frame | 894 | go | +| `WRITES=1` adds ≤ 15 kinstr/frame | +3 | go | +| 29/29 WGSL shaders compile to `MTLLibrary` | 29/29 (79 libraries) | go | +| `wgpu::custom` adds ≤ 25 kinstr/frame | +3.3 to +3.9 | no pivot | +| Beats patched wgpu by ≥ 180 at `WRITES=0` | by 143 | **miss** | +| Beats patched wgpu by ≥ 400 at `WRITES=1` | by 487 | go | +| `WRITES=0` within +40 of `metal_hud.swift` (after the loop fixes) | +86, without them | not tested | + +The kill gate is split. With no buffer writes, owning Metal saves 143 kinstr/frame (14%) over +wgpu with both upstream patches, short of 180. With one write a frame it saves 487 (35%), +because wgpu's write path still costs about +347 kinstr (a staging buffer, a blit encoder and a +command buffer) and the direct write costs 3. Both baselines are lower on this Mac than in +[30](30-overlay-gpu-cost.md) (patched 1,037 here vs 1,118; plain wgpu 1,395 vs 1,555; Swift +808 vs 850), so the absolute margins moved with them. + +What decides it: an app that writes any buffer per frame (every real HUD writes at least its +uniforms) sees the 487 saving, and an idle-clear HUD sees 143. Shipping the two wgpu patches +upstream gets the first ~358 kinstr either way. + +### Overlay HUD, per frame + +`overlay_hud_cost --profile perf`, real 360×80 overlay on an M2 Max MacBook Pro's built-in +120 Hz display (macOS 27.0.1, screen unlocked and awake), 4 alternating rounds of 10 s after a +2 s warmup, medians of the middle two. `queue.write_buffer` for writes (`OVERLAY_STAGED` unset). +Without `perf/overlay-rune-cost`. Patched wgpu is 30.0.1 with both `research/overlay-cpu/` +patches through `--config patch.crates-io`. The Swift HUD has no write option, so it shows once. + +| | Metal spike | wgpu | wgpu, patched | `metal_hud.swift` | +| --- | ---: | ---: | ---: | ---: | +| Kinstructions, `WRITES=0` | **894** | 1,395 | 1,037 | 808 | +| Kinstructions, `WRITES=1` | **897** | 1,668 | 1,384 | – | +| Process CPU, `WRITES=0` | 6.7% | 9.4% | 7.5% | 6.3% | +| Process CPU, `WRITES=1` | 6.6% | 10.9% | 10.1% | – | +| Heap allocations, `WRITES=0` / `1` | 7.1 / 7.1 | 65.1 / 73.1 | 55.1 / 64.1 | – | +| Command buffers, `WRITES=0` / `1` | 1 / 1 | 6 / 7 | 2 / 3 | 1 | +| Completion handlers | 0 / 0 | 2 / 2 | 1 / 1 | 0 | +| Blit encoders | 0 / 0 | 0 / 1 | 0 / 1 | 0 | + +Rounds, kinstr/frame: Metal 883, 903, 895, 894 and 900, 906, 895, 892; wgpu 1,396, 1,393, +1,397, 1,379 and 1,652, 1,710, 1,665, 1,670; patched 1,038, 1,042, 1,037, 1,037 and 1,383, +1,382, 1,385, 1,388; Swift 814, 806, 802, 811. Counts come from separate 8 s runs with +`OVERLAY_COUNT_METAL=1`, whose swizzles add instructions. + +CPU by thread, ms per second, `WRITES=0` (`WRITES=1`): + +| | Main | Present thread | Display link | Driver and the rest | Total | +| --- | ---: | ---: | ---: | ---: | ---: | +| Metal spike | 18.3 (17.8) | – | 2.0 (2.0) | 46.6 (46.4) | 66.9 (66.2) | +| wgpu | 14.4 (21.0) | 15.6 (17.2) | 1.9 (2.0) | 61.0 (68.7) | 94.3 (109.1) | +| wgpu, patched | 13.9 (22.2) | 11.9 (15.1) | 1.9 (2.0) | 47.4 (61.3) | 74.7 (101.2) | +| `metal_hud.swift` | 1.8 | – | 11.3 (draws here) | 50.7 | 63.4 | + +The main thread does more on Metal (about +4 ms/s) because it now encodes, commits and +presents itself instead of handing the frame to the present thread; the compositor callback +grows from ~4 µs to ~35 µs because the render pass is encoded there rather than replayed at +submit. The remaining 86 kinstr over Swift is Rune's own loop (step, `about_to_wait`, acquire), +which `perf/overlay-rune-cost` targets. + +### `wgpu::custom` + +`examples/metal_spike_dispatch.rs`, offscreen, the HUD frame through wgpu's API into the +custom backend against the same Metal calls made directly, 3,000 frames × 4 alternating rounds: + +| | Through `wgpu::custom` | Direct | Added | +| --- | ---: | ---: | ---: | +| `WRITES=0` | 213.9 | 210.6 | 3.3 | +| `WRITES=1` | 214.9 | 211.1 | 3.8 | + +Under the 25-kinstr pivot line, so the spike stays on `wgpu::custom`. What it could express: +the whole overlay frame unchanged, including holding a command buffer from `submit` to +`present` so the drawable presents on it, direct buffer writes, `map_async` that completes at +once, and adapter, surface and capability queries Rune's attach path makes. What it can't, or +what costs: + +- `Surface::as_hal` and `Device::as_hal` return `None` for a custom backend, so every macOS + helper that reaches the CAMetalLayer through them silently does nothing: the occlusion check, + `PresumeShown`, `present_with_transaction`, present timing, system materials, and + `NativeSurface` errors. Phase 2's move of these onto the backend is required, not optional. +- The traits are about 150 methods across 30 interfaces; a backend implements them all, and + most of the spike's are stubs (`unimplemented!` for compute, ray tracing, bundles and + external textures; inert shader modules, pipelines, bind groups and samplers). +- `Frame::write_buffer` (`rune-staging`) writes a mapped staging buffer and records a + `copy_buffer_to_buffer`; the spike drops copies, so that path is wrong here. A real backend + should let staging write straight into a shared destination. +- The `custom` feature adds a variant to every wgpu dispatch enum in any build that enables it; + its cost on the wgpu path wasn't measured (the wgpu baselines were built without it). + +### Shaders + +`gpu_metal/shader_tests.rs` composes each of the 29 WGSL files as its crate does (clip and +common prefixes, gi, glass and reel sections, `layer_blur`'s 5 override pairs), then for each +entry point runs naga `process_overrides` → `msl::write_string` with wgpu-hal's Metal options +(MSL 4.0 on macOS 26+, Restrict bounds checks, loop bounding, zero-initialized workgroup +memory, vertex pulling with a buffer at slot 30, per-entry resource slots with a sizes buffer) +and `newLibraryWithSource` with preserve-invariance. All 29 files compile in every module they +are part of: 31 modules, 79 libraries, 2.3 s in a debug build. No failures. + +What the test doesn't prove: resource slots come from the module's own bindings rather than each +pipeline's layout, and vertex inputs are packed into one buffer, so the MSL matches wgpu-hal's +shape but not each pipeline's exact strides. + +### Limits of the spike + +- It clears and presents; draws, pipelines and bind groups are inert. The HUD and its empty + Rune view need nothing more, so the measured frame is complete, but drawing cost is untested. +- A direct write can race a frame still on the GPU that reads the same buffer. Phase 1's ring + is needed for correctness, and will add a little to `WRITES=1`. +- The layer's scale is set once at creation and doesn't follow a display change. + +## Memory: Metal vs wgpu + +One app reported, from single unpaired runs, a headless footprint of about 330 MB on the Metal +backend against 1.5 to 1.6 GB on wgpu. Paired and alternating runs of one `--profile perf` binary +(`--features rune/metal-backend`, `RUNE_GPU_BACKEND=metal` or `wgpu`), five pairs each, medians. +Footprint is `phys_footprint` (`footprint`, `time -l` for the peak); RSS from `ps` or `time -l`. +Headless is `long_note --gpu --only scroll --sizes 200 --samples 300` (a 200 KB note scrolled +top to bottom, 785 frames, drawn on a headless GPU). Windows are real, on an M2 Max MacBook Pro +(macOS 27.0.1, unlocked, awake): `hello` idle after 5 s, and `window_scroll_cost` (60 sections of +text rows, scrolling at 600 pt/s) sampled at 7 s, about 400 frames in. + +| Case | Backend | Footprint | RSS | Peak footprint | +| --- | --- | ---: | ---: | ---: | +| Headless, Mac mini (M4 Pro) | wgpu | – | 49.1 MB | 278.1 MB | +| | Metal | – | 46.3 MB | 276.7 MB | +| Headless, MacBook Pro (M2 Max) | wgpu | – | 47.6 MB | 58.0 MB | +| | Metal | – | 44.7 MB | 57.8 MB | +| Window idle, 5 s | wgpu | 34 MB | 95.1 MB | 41.5 MB | +| | Metal | 33 MB | 92.5 MB | 39.7 MB | +| Window scrolling, 7 s | wgpu | 68 MB | 104.1 MB | 67.5 MB | +| | Metal | 74 MB | 101.1 MB | 74.2 MB | + +**The claim does not hold in these workloads.** The two backends are within a few MB of each +other everywhere, and neither gets near 330 MB, let alone 1.5 GB. Metal has about 3 MB less RSS; +in the scrolling window it has about 6 MB more footprint. I sampled only at 7 s, so growth over a longer run is +not ruled out. + +**Where the reported gap most likely came from: an unpaced headless run.** A later headless +scroll benchmark that submits frames as fast as it can (about 1,650 a second, 900 frames) +reproduced it: 325 MB footprint on Metal against 1,956 MB on wgpu. The GPU can't keep up at that +rate, so both runs take the same 0.55 s. Rune's Metal queue keeps Apple's default limit of 64 +command buffers in flight and blocks the next one at the start of encode. wgpu allows 2,048, so +it never blocks and gets hundreds of frames ahead, each holding its own buffers. A window paces +frames to the display, so neither queue fills there, which matches the tables above. The same +wait is why such a run reports a higher `encode_ms` on Metal (0.35 ms against 0.19) while its +frame CPU is lower (0.27 to 0.30 ms against 0.38). `encode_ms` is elapsed time, so in an unpaced +run it mostly measures how far behind the GPU is; compare backends there with `thread_cpu_ms` or +`cpu_ms`. + +Where the footprint goes (`footprint` by category, one run each): + +| Category | wgpu idle | Metal idle | wgpu scrolling | Metal scrolling | +| --- | ---: | ---: | ---: | ---: | +| IOSurface (the layer's drawables) | 5.6 MB | 5.6 MB | 22 MB | 22 MB | +| IOAccelerator (graphics), dirty | 1.1 MB | 1.2 MB | 4.4 MB | 6.6 MB | +| Owned physical footprint (graphics) | 6.2 MB | 5.6 MB | 7.6 MB | 9.6 MB | +| Malloc small | 12 MB | 11 MB | 20 MB | 19 MB | + +The wgpu#10494 growth (about 2.3 MiB of IOAccelerator memory per command buffer, held until the +buffers are collected) does not show: wgpu's IOAccelerator is no larger than Metal's after +hundreds of frames. The 6 MB scrolling difference is IOAccelerator and graphics-owned memory, +likely the Metal backend's own pooled buffers and the drawable it keeps in flight, and I did not +chase it further. + +So a gap of 1 GB or more is not something the backend alone produces. It must come from what that +app draws or keeps: large images or atlases, offscreen targets, or buffers that wgpu keeps alive +and the Metal backend frees or never makes. To attribute it, run that app's own headless frames +under both backends with `footprint --by-category` and `vmmap --summary`, and compare +IOAccelerator, IOSurface and Malloc. Not measured here: an app with image-heavy views, effects +or many windows, and a long idle run. diff --git a/app/vendor/rune/research/35-wgpu-vulkan-dx12-cost.md b/app/vendor/rune/research/35-wgpu-vulkan-dx12-cost.md new file mode 100644 index 0000000..b19c5e7 --- /dev/null +++ b/app/vendor/rune/research/35-wgpu-vulkan-dx12-cost.md @@ -0,0 +1,222 @@ +# 35. What wgpu costs a Rune frame on Vulkan and DX12 + +Reader: someone deciding whether Rune should own its Vulkan and DX12 backends, as +[34](34-own-gpu-plan.md) decided for Metal. Question: per frame, what does `wgpu` 30.0.1 cost on +Linux (Vulkan) and Windows (DX12) compared with the same frame written against the raw API, and how +much of that does the upstream present-skip patch already remove? + +**Answer: a native backend would save about 70k instructions and 0.06 to 0.09 ms of CPU per window +frame, under 1.1% of a 120 Hz frame.** The present-skip patch takes about a quarter of the +instructions and, on Vulkan, more than half of the time, because it removes a whole +`vkQueueSubmit`. On a normal window frame, where Rune's own work dominates, `wgpu` and the driver +are about 10% of the renderer's instructions. That backs [34](34-own-gpu-plan.md): keep `wgpu` on +Vulkan and DX12 and land the patch upstream. A 15 to 20 kLOC backend buys less than 0.1 ms a frame. + +All numbers come from software drivers (Mesa lavapipe, and vkd3d on top of it under Wine), so +driver instructions and every time below hold only for software drivers. API call counts, and the +instructions spent in `wgpu`, `wgpu-core` and `wgpu-hal`, don't depend on the GPU. + +## Setup + +- 8-vCPU AMD EPYC 9554P (Zen 4) VM, Ubuntu 24.04, no GPU. Mesa 25.2.8 lavapipe (Vulkan 1.4), Xvfb + with no vsync, so frames run uncapped. +- DX12: the same probe binaries cross-compiled to `x86_64-pc-windows-gnu` and run under Wine 9.0, + whose `d3d12.dll` is vkd3d over lavapipe. Every D3D12 call is translated to Vulkan, so DX12 + instructions include the translation. +- `wgpu` 30.0.1 with `vulkan` and `dx12`, as Rune builds it off Apple. "Patched" adds + `research/overlay-cpu/wgpu-core-present-skip.patch`. +- Workloads: + - `overlay_hud_cost` ([30](30-overlay-gpu-cost.md)): Rune's real overlay. Its compositor clears + a 360×80 drawable in one pass, with `OVERLAY_WRITES=0` or `1` queue writes per frame. + - `research/gpu-floor` (built from that directory, outside the workspace): + - `wgpu_frame`: the same frame through bare `wgpu` (acquire, `create_view`, N 256-byte + `Queue::write_buffer`s, one cleared pass, submit, present). + - `vk_floor` (ash) and `dx12_floor` (`windows`): that frame with the fewest calls each API + allows. `UPLOAD=mapped` writes the uniform into a persistently mapped ring with no API call. + `UPLOAD=copy` stages it and records a copy plus one barrier, as a discrete GPU needs. + - `upload_bench` (steady and scroll): a headless window-sized renderer frame + (`Renderer::prepare`, `draw`, `submit`, with no surface), standing in for a normal window. +- Instructions per frame are for the drawing thread only. Lavapipe rasterizes on its own threads, + and on real hardware that work is the GPU's, so those threads are left out. + - Callgrind collects only inside the frame function, Rune's `Compositor::render` or Rune's + renderer calls. `research/gpu-floor/cgsplit.py` then splits the counts by crate and + library, charging `std` and allocator code to its caller. + - `perf_event` instruction counters and `CLOCK_THREAD_CPUTIME_ID` give the user, kernel and CPU + time numbers: medians of 5 alternating rounds of 4,000 frames. +- Barriers were classified with a logging build of `wgpu-hal` + (`research/gpu-floor/wgpu-hal-log-barriers.patch`) on Vulkan and with vkd3d's trace log on + DX12. + +## Vulkan, per frame + +| HUD frame, 0 writes (1 write) | wgpu today | wgpu patched | Native floor | +| --- | ---: | ---: | ---: | +| `vkQueueSubmit` | 2 (2) | 1 (1) | 1 (1) | +| Command buffers begun and ended | 5 (6) | 4 (5) | 1 (1) | +| `vkResetCommandPool` | 2 (3) | 1 (2) | 1 (1) | +| `vkCmdPipelineBarrier` calls | 4 (5) | 2 (3) | 0 (copy: 1) | +| Barriers, of which no-ops | 4, 2 (6, 3) | 2, 0 (4, 1) | 0 (copy: 1, 0) | +| Image views created and destroyed | 2 (2) | 2 (2) | 0 | +| Framebuffers created and destroyed | 1 (1) | 1 (1) | 0 | +| Buffers created, bound, destroyed | 0 (1) | 0 (1) | 0 | +| Host semaphore or fence calls | 2 (2) | 2 (2) | 2 (2) | +| Heap allocations, `wgpu` crates | 81 (91) | 60 (70) | 0 | +| Heap allocations, driver | 57 (67) | 44 (54) | 29 (29; copy 37) | +| Kinstructions, `wgpu` + `wgpu-core` + `wgpu-hal` | 53.7 (62.3) | 43.0 (50.0) | 0 (probe 0.2) | +| Kinstructions, driver (software) | 34.1 (38.3) | 26.4 (30.6) | 16.9 (17.0; copy 19.2) | +| Kinstructions, thread total (callgrind) | 88.5 (101.3) | 70.0 (81.3) | 17.1 (17.2; copy 19.5) | +| Kinstructions user + kernel (`perf`) | 106.6 (119.0) | 81.3 (92.1) | 30.5 (30.8; copy 33.7) | +| Thread CPU, µs (VM, software driver) | 126 (133) | 89 (92) | 67 (70; copy 74) | + +Split of the 53.7 kinstructions on the `wgpu` side: `wgpu-core` 36.8, `wgpu-hal` 14.5, `wgpu` +2.4. Inclusive cost by entry point in Rune's overlay, including driver time: `Queue::submit` 32.4, +`Queue::present` 27.2 (8.2 patched), `CommandEncoder::finish` 16.5, `get_current_texture` 7.3, +`create_view` 3.3, `begin_render_pass` 2.3. + +What the floor drops, and why each call is avoidable: + +- **The second submit.** `Queue::present` submits a `PendingWrites` command buffer that holds only + PRESENT→PRESENT barriers, because Vulkan's ordered texture usages are `INCLUSIVE` only + (`wgpu-hal/src/vulkan/adapter.rs:3247`). `skip_barrier` therefore keeps the barrier + (`wgpu-core/src/track/mod.rs:341-345`), and `vulkan/command.rs:220,268` skip + `vkCmdPipelineBarrier` only when the list is empty. The patch removes this submit. +- **Two PRESENT→PRESENT image barriers.** Neither changes the layout (`PRESENT_SRC_KHR` both sides) + nor orders anything, so both are no-ops. +- **Three empty command buffers.** `Transit`, `Pre Pass` and `Present` each pay a + `vkBeginCommandBuffer`/`vkEndCommandBuffer` pair. The two barriers that matter, + UNDEFINED→COLOR_ATTACHMENT and COLOR_ATTACHMENT→PRESENT_SRC, ride in two of them. The floor gets + both transitions free from the render pass's `initialLayout` and `finalLayout`, with one external + subpass dependency on the acquire semaphore (`vk_floor.rs`). +- **Two image views and a framebuffer every frame.** `get_current_texture` builds a clear view for + the surface texture (`wgpu-core/src/present.rs:210-223`), and the app's `create_view` builds the + second. The framebuffer cache lives in the command encoder and is drained on every `reset_all` + (`vulkan/command.rs:184-187`), so the framebuffer for that frame's view is rebuilt every frame. + The floor makes views and framebuffers once per swapchain image. +- **With a write:** each `Queue::write_buffer` creates, binds and destroys a staging `VkBuffer` + through `gpu-allocator`, and records a copy into `PendingWrites`, the third command buffer + reset. Its MAP_WRITE→COPY_SRC barrier is a no-op, because `vkQueueSubmit` already makes host + writes visible (Vulkan spec, "Host Write Ordering Guarantees"). COPY_DST→COPY_DST orders the + write after last frame's copy into the same buffer and is needed. The floor writes into a mapped + ring. On a discrete GPU it records one `vkCmdCopyBuffer` and one buffer barrier, which costs + 2.3 kinstructions. + +Rune's real overlay agrees with the probe: 105.3 kinstructions per frame, of which Rune is 9.9, +the `wgpu` side 51.5, the driver 39.8 and windowing 4.1. With one write it's 116.7 (58.9 `wgpu`, +43.7 driver). Patched, those drop to 84.5 and 97.9. + +## DX12, per frame + +Traced through vkd3d, counted between two presents. Thread numbers are for the whole Wine stack. + +| HUD frame, 0 writes (1 write) | wgpu today | wgpu patched | Native floor | +| --- | ---: | ---: | ---: | +| `ExecuteCommandLists` | 2 (2) | 1 (1) | 1 (1) | +| Command lists reset and closed | 5 (6) | 4 (5) | 1 (1) | +| Command allocator resets | 2 (3) | 1 (2) | 1 (1) | +| `ResourceBarrier` calls, transitions | 2, 2 (3, 3) | 2, 2 (3, 3) | 2, 2 (copy: 2, 3) | +| No-op transitions | 0 (1) | 0 (1) | 0 | +| `Signal` on the frame fence | 2 | 1 | 1 | +| `CreateRenderTargetView` | 2 | 2 | 0 | +| Placed resource, `Map`/`Unmap` per write | 0 (1) | 0 (1) | 0 | +| Kinstructions user + kernel (`perf`) | 160.4 (200.7) | 137.9 (176.1) | 41.4 (41.7; copy 44.4) | +| Thread CPU, µs (Wine + vkd3d + lavapipe) | 130 (146) | 128 (133) | 61 (61; copy 64) | + +- DX12 already sits at the barrier floor. `transition_textures` drops a transition whose states + match (`wgpu-hal/src/dx12/command.rs:514-516`), so PRESENT→PRESENT never reaches the API, and + DX12 orders COLOR_TARGET and DEPTH_STENCIL_WRITE (`dx12/adapter.rs:1397-1400`). The two + PRESENT↔RENDER_TARGET transitions are required for a swapchain buffer, so the floor has them too. +- The one no-op is COMMON→COPY_SOURCE on the write's staging buffer: buffers are promoted + implicitly from COMMON, and upload-heap resources stay in GENERIC_READ anyway. +- What's left is the same shape as on Vulkan: a second `ExecuteCommandLists` with its `Signal` + (`dx12/mod.rs:1799-1802`), four extra command list Reset/Close pairs, two RTVs written per frame, + and a placed staging resource per write. +- The per-crate split wasn't measured on DX12, because callgrind can't follow the Windows binary + under Wine. `wgpu-core` is the same code on both backends, so its ~37 kinstructions carry over. + The rest of the 119-kinstruction gap is `wgpu-hal`'s dx12 code plus vkd3d translating its extra + calls, which real Windows doesn't pay. Treat the DX12 gap as an upper bound. +- The probe uses `wgpu`'s default HWND swapchain. Rune uses `DxgiFromVisual`, which differs only + in how the swapchain is created, not in the per-frame calls above. + +## Normal window frame + +`upload_bench` measures a renderer frame with no surface: `prepare`, one pass with one draw, and +submit. + +| Kinstructions per frame (Vulkan, callgrind) | steady | scroll | +| --- | ---: | ---: | +| Rune (`prepare`, `draw`) | 426.1 | 554.1 | +| `wgpu` + `wgpu-core` + `wgpu-hal` | 36.8 | 37.1 | +| Driver (software) | 11.8 | 12.3 | +| Total | 474.7 | 603.5 | +| `cpu_us` without valgrind | 56.9 | 72.1 | + +Per frame: 1 `vkQueueSubmit`, 4 command buffers, 3 barriers, 1 copy, 1 draw, and 83 heap +allocations in the `wgpu` crates. A native backend would keep roughly the driver part and add a +few kinstructions of its own, so it saves about 35 kinstructions, 6 to 7% of the frame. A window +also pays the surface costs measured on the HUD (acquire, view, present, and the second submit +today), so a normal window saves about the HUD's figure plus a few µs. + +## Projected savings + +The 120 Hz frame is 8.33 ms. "Measured" means CPU time on the VM with software drivers. +"Projected" assumes the `wgpu` side and the extra API calls run at 2 to 4 instructions per ns on a +desktop core. + +| Backend, HUD frame | Today → native | Patched → native | Today → patched | +| --- | ---: | ---: | ---: | +| Vulkan, kinstructions (callgrind) | −71 (−84 with a write) | −53 (−64) | −18.5 (−20) | +| Vulkan, measured | −0.059 ms, 0.71% (−0.063, 0.76%) | −0.022 ms, 0.27% | −0.037 ms, 0.45% | +| Vulkan, projected on hardware | −0.02 to −0.04 ms, 0.2 to 0.5% | −0.015 to −0.03 ms | −0.005 to −0.01 ms, plus one submit's kernel time | +| DX12, kinstructions (`perf`, includes vkd3d) | −119 (−159) | −96 (−134) | −23 (−25) | +| DX12, measured under Wine | −0.070 ms, 0.83% (−0.085, 1.0%) | −0.067 ms, 0.81% (−0.072) | ~0 (−0.013 with a write) | +| Normal window, kinstructions | ≈ HUD figure + 35 | ≈ HUD figure + 35 | as HUD | + +For scale, [30](30-overlay-gpu-cost.md) measured a 705-kinstruction gap per frame between Rune +and hand-written Metal, process-wide. The Vulkan gap here is about 10 times smaller in +instructions. A large part of the Metal gap is driver work per command buffer, which lavapipe +mostly hands to its own threads, so real Vulkan and DX12 drivers may cost more per extra submit +than these numbers show. + +## What paid hardware would settle + +- The real cost of each extra `vkQueueSubmit`/`ExecuteCommandLists`, empty command buffer, + per-frame view and framebuffer, and staging buffer on NVIDIA, AMD and Intel drivers. A real + submit goes to the kernel, and lavapipe's doesn't. That's the biggest unknown in the projection. +- DX12 with Microsoft's runtime instead of vkd3d, and Rune's `DxgiFromVisual` swapchain under DWM + with real vsync and frame latency waits. +- Cheapest option: one AWS `g4dn.xlarge` (NVIDIA T4) in us-east-1 at $0.526/h on Linux, about + $0.71/h on Windows (license included), or about $0.30/h spot. One hour each, about $1.25 on + demand, runs every probe here. +- A free middle step is a `windows-latest` GitHub Actions job on WARP, which is Microsoft's runtime + over a software rasterizer. Pushing a workflow file needs a token with the `workflow` scope, so it + wasn't tried here. + +## Cheaper than a backend + +1. Upstream `wgpu-core-present-skip.patch` (one fewer submit, two no-op barriers, a command buffer + and 20 allocations per frame on every backend). +2. In `wgpu-hal` Vulkan, keep the framebuffer cache across `reset_all`, or use imageless + framebuffers, and skip same-layout image barriers as DX12 does. +3. In `wgpu-core`, reuse the surface texture's clear view across frames for the same swapchain + image. +4. In Rune, keep writing through its own staging ring rather than `Queue::write_buffer`, which + creates a staging buffer per call on Vulkan and a placed resource per call on DX12. + +## Reproduce + +From `research/gpu-floor` on Linux with Mesa lavapipe and an X server (`DISPLAY`): + +```sh +cargo build --release +WRITES=0 ./target/release/wgpu_frame # BACKEND=vulkan|dx12 +WRITES=0 ./target/release/vk_floor # UPLOAD=mapped|copy +cargo build --release --target x86_64-pc-windows-gnu +BACKEND=dx12 WINE_PERF=1 wine64 target/x86_64-pc-windows-gnu/release/wgpu_frame.exe +WINE_PERF=1 wine64 target/x86_64-pc-windows-gnu/release/dx12_floor.exe +``` + +For the patched rows, add +`--config 'patch.crates-io.wgpu-core.path="<wgpu-core 30.0.1 with the present-skip patch>"'`. +Callgrind per frame: +`valgrind --tool=callgrind --collect-atstart=no '--toggle-collect=*Draw>::frame' --separate-threads=yes ...`, +then `cgsplit.py <main-thread profile> --frames N`. diff --git a/app/vendor/rune/research/37-what-to-own-next.md b/app/vendor/rune/research/37-what-to-own-next.md new file mode 100644 index 0000000..998f4d2 --- /dev/null +++ b/app/vendor/rune/research/37-what-to-own-next.md @@ -0,0 +1,234 @@ +# 37. What to own next + +Reader: someone deciding whether Rune should replace another dependency (Taffy, Parley, winit, +an image decoder) or put the next week into its own runtime. This note re-runs +[33](33-real-bottlenecks.md)'s four real-app workloads on current `dev` and ranks the parts +Rune could own by what they cost now. + +The short answer: there's nothing left worth owning. The dependencies Rune could replace now +cost little: Taffy is 1–4% of busy time outside a live resize, and 0.06–0.09 ms per committing +frame in an agent client's chat. Shaping is at most 4.7%, and image decode and Markdown parsing +are near zero. What costs now is Rune's own runtime: + +1. **Copying `Node`s in commit.** Memo reuse clones every reused node, each about 1.7 KB with + its `Visual`, on every commit, and apply then drops the old copies. That is 15–20% of commit + time in the agent client and most of the commit time that isn't view, layout, text or apply. +2. **Per-frame scans and ancestor walks** in the paint walk and frame step: `subtree_exiting` + walks up to the root for each hit-testable node, and `highlight_target_in`, `Keyed::new` and + `layout_of` scan every node. On the board's long card these cost 15–20% of busy time. A + small spike removed most of it: long-card scroll p50 −17%. +3. **The paint walk itself** (`Runtime::build`). It is 25–62% of a scroll frame. Scroll frames + are already 0.5–0.9 ms at p50, so making it cheaper saves power but doesn't fix missed frames. + +The one interaction still missing the frame budget is scrolling the board's long card: 82 +frames over 8.3 ms, with p95 15 ms. Item 2 is its first fix. + +## How it was measured + +- **Builds:** "Then" is the exact tree [33](33-real-bottlenecks.md) measured: Rune `c83aa06b` + with each app's code from that day. "Now" is Rune `dev` at `506f5421`, which matches + `29df6816` apart from three commits that only move files, with each app's current code. + So "now" includes app-side changes as well. The biggest is the team chat's timeline, which + now builds only its mounted rows; that explains much of its type and resize gains. +- **Rune changes in between:** + - glyph quad replay (`f560da33`); + - memo reuse of flattened slices and Taffy subtrees (`049a0b13`, `417da565`); + - the resize fast path that now admits virtual lists (`d7cdefde`). +- **Machine and builds:** `--profile perf` with `rune/frame-profile`, headless at scale 2, on a + 12-core M2 Max shared with other jobs (load 5–13). Each side has its own target dir. +- **Runs:** each app ran 6 paired rounds after a warmup. Each round ran every scenario on both + sides, alternating which side went first and the scenario order. Numbers are medians with + outliers kept. A 1 kHz main-thread `sample` ran 3 times per scenario per side, 90 s each. +- **Then figures:** the "then" column is this run's own paired figures. They differ from + [33](33-real-bottlenecks.md)'s because that run's machine was busier (load 6–20). +- **What headless leaves out:** GPU work, presentation, winit and window-server event delivery. + A Metal backend is landing separately, so GPU submission is out of scope here. + +## Frame CPU per interaction, then → now + +Thread-CPU ms per drawn frame: p50 / p95 / p99 / max, then frames over 8.3 ms. + +| Workload / interaction | Then | Now | +|---|---|---| +| Team chat / scroll | 0.55 / 0.96 / 1.15 / 16.5, 3 over | 0.46 / 0.75 / 0.98 / 3.21, 0 over | +| Team chat / type | 0.65 / 13.0 / 16.4 / 22.5, 84.5 over | 0.39 / 2.36 / 3.07 / 3.43, 0 over | +| Team chat / resize | 17.6 / 30.9 / 39.2 / 43.1, 239 over | 2.79 / 5.40 / 5.78 / 6.59, 0 over | +| Notes / open | 4.14 p50, 16.6 max, 2 over | 3.08 p50, 14.5 max, 2 over | +| Notes / cursor | 5.73 / 11.4 / 12.5, 23.5 over | 2.68 / 4.70 / 6.02, 0 over | +| Notes / scroll | 0.83 / 1.18 / 1.29 / 1.62 | 0.63 / 0.84 / 0.91 / 0.99 | +| Notes / resize | 6.67 / 9.81 / 11.5 / 12.8, 21 over | 1.80 / 3.33 / 4.69 / 6.10, 0 over | +| Agent client / scroll | 0.66 / 1.77 / 2.75 / 4.55 | 0.56 / 1.36 / 2.11 / 4.20 | +| Agent client / stream | 0.72 / 2.06 / 2.47 / 3.03 | 0.82 / 1.59 / 1.97 / 2.38 | +| Agent client / type | 1.53 / 1.77 / 2.15 / 2.15 | 0.88 / 1.15 / 1.27 / 1.40 | +| Agent client / resize | 2.01 / 2.68 / 3.08 / 3.73 | 1.23 / 1.72 / 1.91 / 2.10 | +| Board / scroll | 1.29 / 1.70 / 7.91 / 13.0, 2 over | 0.25 / 0.48 / 3.29 / 3.49, 0 over | +| Board / open cards | 1.83 / 11.1 / 17.7 / 30.1, 108 over | 0.39 / 0.71 / 3.66 / 14.7, 1 over | +| Board / long-card scroll | 3.33 / 21.5 / 23.3 / 24.3, 81.5 over | 2.34 / 15.2 / 19.6 / 20.4, 82 over | +| Board / diagram card, scroll | 2.41 / 12.4 / 13.7 / 14.7, 59 over | 0.91 / 4.38 / 5.45 / 6.67, 0 over | +| Board / diagram card, open | 98.3 max | 55.8 max | + +The notes palette still blocks on its daemon socket: its mean update wall time went from +231 ms to 188 ms, while its CPU time is small. That one is app-side. + +**An agent client's chat** was measured in a separate run on a bigger real transcript: `dev` +`29df6816`, headless release, medians of 3. The figures are CPU ms per active frame, before the +memo work → after. + +| Interaction | p50 | p95 | Allocated per frame, p50 | +|---|---|---|---| +| Typing | 3.92 → 2.15 | 4.63 → 2.71 | 5,072 → 2,446 KB | +| New message | 3.91 → 2.79 | 4.57 → 3.53 | 5,811 → 3,744 KB | + +## Launch, then → now + +Headless, from process start to the first frame read back, and the first frame's CPU. + +| Workload | Process to pixels | First frame CPU | +|---|---|---| +| Team chat | 65 → 50 ms | 31.1 → 17.5 ms | +| Notes | 59 → 75 ms | 16.1 → 16.2 ms | +| Agent client | 69 → 75 ms | 17.4 → 19.8 ms | +| Board | 168 → 111 ms | 67.8 → 25.1 ms | + +The notes and agent client launches stay within run-to-run spread; the agent client's extra +time is in app state loading (24 → 27 ms). + +## Where the main thread goes, then → now + +These are inclusive shares of main-thread busy time: self samples whose stack contains the +owner. Owners nest (glyph emission is inside the paint walk), so a row doesn't sum. A share can +rise only because the frame around it got cheaper. + +| Workload / interaction | Paint walk | Glyph emit | Flatten | Apply | Taffy | Shaping | Markdown | Alloc | +|---|---:|---:|---:|---:|---:|---:|---:|---:| +| Team chat / scroll | 52 → 48 | 8 → 11 | 1 → 0 | 1 → 1 | 1 → 1 | 1 → 1 | 3 → 0 | 6 → 6 | +| Team chat / type | 20 → 36 | 3 → 7 | 5 → 7 | 3 → 7 | 1 → 2 | 0 → 1 | 16 → 3 | 13 → 6 | +| Team chat / resize | 4 → 14 | 1 → 4 | 6 → 14 | 3 → 9 | 3 → 12 | 0 → 0 | 22 → 7 | 16 → 11 | +| Notes / scroll | 72 → 62 | 16 → 16 | 0 → 0 | 0 → 0 | 2 → 4 | 2 → 2 | 0 → 1 | 1 → 2 | +| Notes / cursor | 44 → 46 | 10 → 10 | 12 → 8 | 6 → 6 | 2 → 2 | 1 → 1 | 0 → 0 | 7 → 3 | +| Notes / resize | 20 → 29 | 4 → 7 | 13 → 0 | 13 → 15 | 26 → 25 | 1 → 1 | 0 → 0 | 8 → 3 | +| Agent client / scroll | 46 → 26 | 12 → 10 | 2 → 2 | 2 → 2 | 4 → 4 | 2 → 2 | 1 → 0 | 4 → 7 | +| Agent client / stream | 27 → 24 | 5 → 6 | 15 → 12 | 12 → 10 | 6 → 9 | 2 → 3 | 3 → 5 | 9 → 7 | +| Agent client / type | 46 → 30 | 10 → 8 | 7 → 4 | 4 → 5 | 4 → 4 | 2 → 3 | 0 → 0 | 5 → 8 | +| Agent client / resize | 20 → 19 | 3 → 7 | 19 → 14 | 9 → 9 | 11 → 14 | 1 → 1 | 0 → 0 | 11 → 7 | +| Board / open cards | 13 → 25 | 1 → 4 | 5 → 3 | 3 → 0 | 1 → 1 | 1 → 2 | 0 → 0 | 9 → 6 | +| Board / long-card scroll | 20 → 29 | 1 → 1 | 9 → 10 | 7 → 7 | 2 → 2 | 1 → 1 | 1 → 0 | 7 → 5 | +| Board / diagram card | 15 → 33 | 1 → 4 | 5 → 4 | 3 → 1 | 1 → 1 | 1 → 2 | 0 → 0 | 7 → 4 | + +Parley's glyph iterators, which [33](33-real-bottlenecks.md) found at 15–26% of a scroll frame, +are now 0–1.4%. What glyph emission still costs is Rune's own replay +(`glyphs_in_band_cached`, `glyph_or_image`). Image decode and winit don't appear in any sample: +the workloads load no images, and headless runs bypass winit's event loop. + +## The biggest costs now + +| Cost | Where | Share | +|---|---|---| +| `Runtime::build`, the paint walk's own lines | every scroll | 13–21% self | +| `highlight_target_in`, a full node scan with a `format!` for each highlight | board long card, diagram card | 6–11% | +| `Scene::phase`, from `subtree_exiting` walking to the root for each hit-testable node | board long card | 5% (+ about 7% inlined into the paint walk) | +| Node copies in flatten: `memmove`, `Node::clone`, `Visual::clone` | agent client stream, type | 6% of busy time, about 60% of flatten | +| `window_tree`: virtual-row builders, `El` moves, a SipHash `HashSet`, linear path finds | agent client stream | 7% | +| `Keyed::new`, a per-frame map of every node's key | board | 3–4.5% | +| `glyphs_in_band_cached` | scroll | 4–9% | +| `Renderer::prepare`, `pack_fade` | scroll | 3–12% (GPU work, out of scope) | +| Taffy `compute_flexbox_layout` | resize | 4.6–5.5% self | +| `__recvfrom` on the daemon socket | notes | 3–7% (app-side) | + +In the board runs, 1.7–5.5% goes to the frame log being echoed to stderr as JSON. That is the +harness's own overhead, not the app's. + +## What commit spends, besides view, layout, text and apply + +In the agent client's chat, about 1.2–1.7 ms of each commit is none of view, layout, text or +apply. Sampling the same workload here (agent client, type and stream) shows which functions +own it. The figures are shares of the samples under `Runtime::commit`: + +| Owner | Type | Stream | +|---|---:|---:| +| Flatten: copying reused nodes (`try_reuse_memo` → `Node::clone`, `Vec<Node>::push`) | 14.6 | 14.0 | +| Flatten: the rest (`Style` comparison, path strings) | 7.9 | 9.9 | +| `window_tree`: building virtual rows (app code that the view timer misses), moving `El`s, a SipHash set of mounted keys, a linear search for the scroll node | 7.3 | 17.2 | +| Apply: dropping the previous commit's nodes | 2.4 | 4.2 | +| Layout reads, `measure_virtuals`, `release_kept_layouts`, place | 9.7 | 10.7 | +| *For scale:* view 15.9 / 14.0, Taffy 17.7 / 15.2, the rest of apply 24.4 / 14.9 | | | + +Across commit, `memmove` is 17–20% of samples and allocation 7–9%. Most of that `memmove` is +`Node`s being moved or cloned: each is about 1.7 KB, around 100 fields plus a 71-field +`Visual`. + +Taffy's share of samples is larger than the frame profile's layout p50 (0.07 ms here, +0.06–0.09 ms in the agent client's chat) because samples weight by time. The commits that +rewrap streamed text pay for layout; the median commit doesn't. Layout's mean is 0.13–0.16 ms. + +## Verdicts + +Upper bounds are the measured share a change could remove at most, as a percentage of +main-thread busy time unless marked otherwise. + +| # | Candidate | Upper bound | Size | Risk | Verdict | +|---|---|---|---|---|---| +| 1 | (b) Smaller `Node`, starting with memo reuse moving nodes instead of cloning them | 15–20% of commit (0.35–0.6 ms per commit in the agent client's chat), plus paint-walk stride | Medium for the clone fix; large for a hot/cold split | Medium: apply's diffing and measure retries read the old nodes | **Own it**, in Rune. Stop cloning reused spans first, then split `Node` and `Visual` into hot and cold parts | +| 2 | (i) Per-frame scans and ancestor walks: `subtree_exiting`, `highlight_target_in`, `layout_of`, `Keyed::new`, `in_scope` | 15–20% on the board's long card, under 2% elsewhere | Small | Low | **Fix in Rune.** Spiked below | +| 3 | (i) `window_tree`: per-commit sets, string paths, linear finds; time row builders as view | 7–17% of commit | Small | Low | **Fix in Rune** | +| 4 | (i) Retained paint per subtree, translating cached spans on scroll | 25–62% of a scroll frame | Large | High: fades, clips, sticky headers, hover | **Later.** Scroll already fits the budget, so the gain is power | +| 5 | (c) Per-frame arena | Allocation is 2–11% of busy time, 7–9% of commit; an arena reaches only frame-lifetime allocations | Medium–large | Medium | **Don't bother.** Items 1 and 3 remove most of the churn | +| 6 | (d) Own flex and stack layout instead of Taffy | 1–4% outside resize; 8–10% self (≤ 25% with measure callbacks) on notes resize | Large | High | **Don't bother.** If resize needs it, skip clean subtrees within Taffy | +| 7 | (e) Own shaper and a shaped-word cache | ≤ 4.7% everywhere | Large | High | **Don't bother** | +| 8 | (f) Markdown parse and build in rune-kit | 0–7% now (was up to 22%) | Medium | Low | **Don't bother.** Memo already covers it | +| 9 | (a) Flat glyph runs for text paint | Landed (`f560da33`); Parley iteration 15–26% → 0–1.4% | Done | — | **Done** | +| 10 | (g) Own the macOS run loop and use CADisplayLink | Not visible headless; a windowed profile is needed | Large | High | **Don't own it for CPU.** Pacing or latency could justify it, but only with a windowed measurement | +| 11 | (h) Image decode | 0% in these workloads | — | — | **Don't bother** | + +## Spike: per-frame scans (#2) + +The spike made three changes on a scratch tree that won't land: + +- One forward pass per frame marks the subtrees that are exiting, and `subtree_exiting` reads + that mark during the frame step. +- A node reads its clock only when it has a loop track. +- `highlight_target_in` checks whether a node has highlights before testing scope, and matches + keys without building a path string. + +Both sides were built from the same tree, `dev` with each app's current code, with only the +patch differing. The board ran 6 paired rounds. Other jobs pushed the machine's load to 80–115 +during the run, so absolute times are inflated. The spike was faster in every paired round of +every scenario. + +| Board interaction | Base p50 | Spike p50 | Frames over 8.3 ms | Median paired ratio | +|---|---:|---:|---:|---:| +| Long-card scroll | 9.81 | 8.17 | 221 → 178 | 0.83 | +| Diagram card scroll | 3.13 | 2.93 | 19 → 20.5 | 0.93 | +| Board scroll | 1.07 | 1.03 | 1 → 2 | 0.96 | +| Open cards | 1.59 | 1.52 | 13 → 12.5 | 0.96 | + +In the long-card samples, `highlight_target_in` fell from 11.7% to 4.7%, and from 6.1% to +1.5% on the diagram card. Its remaining cost comes from `layout_of`, which calls it once for +each layout read, so the next step is an index from highlight key to node built once per +commit. `Keyed::new` can be cached per commit the same way. Re-run on a quiet machine before +quoting the size of the gain. + +No spike was run for #1, because a safe version has to keep the old nodes readable through +measure retries and apply's diffing, which makes it more than a scratch patch. Its upper bound +comes from the commit samples above. + +## Tried, not landed: pooling node path strings + +After `154e4d33` (inherited `hover_motion_within` curves kept beside a node's visuals), a +line-level profile of the 2,300-element card workload (`scroll_bench --workload card`) put +commit at 58% of the frame step: flatten 34% of that (moving the 552-byte `Style` into +`sync_taffy_node`, moving 1,152-byte `El` children out of their iterator, a `String`-keyed +`layout_entries` lookup per node), apply 21% with `clear_old_nodes` about 29% of apply, +`place` refilling `node_index` 2.4% of busy time and `release_kept_layouts`' path lookups +3.2%. The patch tried was the cheapest of these: flatten reused the path strings of the +nodes and layout entries the last build dropped (bounded to one per node, 256 bytes each). +On the card, paired over 10 alternating rounds, allocations per commit fell from 9,989 to +7,706 and instructions from 16.68 to 16.25 G (−2.6%). Commit p50 went from 2.10 to 1.83 ms in +one run and 1.86 to 1.81 ms in another. On the board's long card it saved 3.5% of commit +allocations, but instructions moved −0.02% and −0.85% in two runs, and the commit-frame +median was mixed (9.38 → 8.97 ms, then 7.94 → 8.11 ms). That's because memo reuse there moves +nodes instead of dropping them, so `clear_old_nodes` is about 1% of busy time. There, commit +is 32% of busy time: the app's view 42% of it, solve 15%, flatten 13.5%, and every Rune-side +candidate above is under 1% of busy time. Not worth the churn. Numbers come from an M4 Pro +under load 30–40, compared by median with outliers kept, headless, so GPU upload and +presentation are left out. diff --git a/app/vendor/rune/research/38-view-rerun-and-commit-cost.md b/app/vendor/rune/research/38-view-rerun-and-commit-cost.md new file mode 100644 index 0000000..f29fca8 --- /dev/null +++ b/app/vendor/rune/research/38-view-rerun-and-commit-cost.md @@ -0,0 +1,107 @@ +# 38. View re-run and commit cost + +Follows [37](37-what-to-own-next.md) on `dev` after `43a1a469`, `154e4d33`, `9beba394`, `bdf0507d`, +`8d3d3f72`, `fc9a3d07`, `8a14dda8` and `622890c4` had already landed (`e6371c48`). Those commits +moved `memo`-reused slices on normal rebuilds, split cold fields out of `Node` and `Visual`, and +replaced Taffy's map storage with dense slot tables. Two costs remained for apps that don't wrap +every subtree in `memo`: + +1. **Re-running the whole view and rebuilding static subtrees.** Scrolling an `El::virtual_rows` + list (or filling its overscan) re-ran the app's `view` closure and rebuilt every mounted row's + `El` tree even when app state hadn't changed. And `Markdown::render` parsed and built its entire + block/inline `El` tree on every commit unless the caller wrapped it in `memo`, while leaving + `reveal = 0.0` on static paragraphs so `apply` populated `reveals` and rejected `clean_apply_spans`. +2. **Copying and diffing unchanged commit state.** Resize commits (`relayout`) still cloned every + `Node` (`Node::relaid_from`), adjacent clean `memo` spans stayed uncoalesced, truncated and + line-clamped labels ran Parley binary-search shaping probes on every commit, non-memo `Node` + paths allocated fresh `String`s every commit, and `apply` ran ~20 `Scene` / `AnimationStore` + hash lookups on every non-memo node even when its layout, visuals and tracks were at rest. + +## What landed + +1. **Partial `virtual_rows` remount (`CommitWhy::VIRTUAL`).** When `!relayout && state_unchanged` + and no pending reveal or layout/caret read invalidates the view, `remount_virtuals` moves + non-list subtrees and staying rows straight out of `self.nodes`, calls the row closure only for + newly entering indices, and falls back cleanly to a full `view` pass if a layout read of a + culled or newly mounted row moves. `MemoCache` tags entries with `virtual_row` so view-level and + staying-row memos survive partial commits while culled row memos evict immediately. +2. **Automatic `Markdown::render` subtree caching.** Pure-data `Markdown` renders (not streaming, + no link/task/highlighter closures, no source-copy selection or Mermaid blocks) cache their built + and flattened subtree in `MemoCache` by a 128-bit `(FxHasher, DefaultHasher)` digest and pass + ordinal, preserving `el.key` (`None` when unkeyed, or `.key(..)` attached after `.render(..)`). + Static `Markdown::new` defaults `reveal` to `-1.0` so non-streaming Markdown skips `reveals` and + qualifies for `clean_apply_spans`. +3. **Move nodes on resize commits and coalesce clean apply spans.** `relayout` moves non-input, + non-secure `Node`s out of `self.nodes` via `Node::moved_stub` (restoring them if a virtual + window moves and forces a full `view` pass), and `clean_apply_spans` merges contiguous spans. +4. **Elision cache, in-place node path moves, and resting non-memo `apply` skip.** `TextSystem` + caches `El::truncate` and `El::max_lines` cuts (`CachedElision`) with the same two-commit + + `STALE_BYTES` eviction and `supersede` invalidation as shaped layouts (bypassed for `secure` + text) and reuses probe buffers and the winning binary-search probe. Committing flatten passes + move `old.path` `String`s directly from matching `self.nodes` slots (restored on retry or + `discard_measured`, as opposed to [37](37-what-to-own-next.md)'s dropped string-pool spike, this + also skips the `path_ids` hash lookup when `old_cursor` stays in step). Finally, + `Scene::is_resting_at` checks presence, frame and active tracks in one slot lookup so `apply` + skips unchanged resting non-memo nodes, and `commit_paint` short-circuits `!instant && from == Some(to)` + before querying `AnimationStore`. + +## Why arbitrary view helpers still need `memo` + +Rust evaluates arguments eagerly: in `parent.child(helper(state, cx))`, `helper` has already run +and built its `El` tree before `parent.child` sees anything, and `&S` is a plain shared reference +with no field-read tracking. Skipping arbitrary `fn(&S, &mut Cx<S>) -> El` helpers without `memo` +would require either reactive state handles or a view macro/compiler rewrite. Automatic skipping in +plain Rust therefore covers the two boundaries Rune already owns: `virtual_rows` closures when `&S` +didn't change, and pure-data component builders (`Markdown::render`). + +## Headless numbers, before → after + +Built with `--profile perf` and `rune-kit/markdown,frame-profile`, headless at scale 2 on an idle +Apple Silicon worker. Paired over 7 alternating rounds (`A B`, `B A`, …) with outliers kept, +compared by median. Headless figures leave out GPU upload, Metal/wgpu submission, window-server +events and presentation. + +### `layout_text_cost` (`e6371c48` → after) + +| Case | Commit p50 → after (ms) | Commit p95 → after (ms) | View p50 → after (ms) | Apply p50 → after (ms) | Allocs p50 → after | +|---|---:|---:|---:|---:|---:| +| `md-same` | 0.851 → 0.167 (−80.4%) | 0.952 → 0.186 (−80.5%) | 0.359 → 0.021 (−94.1%) | 0.201 → 0.038 (−81.0%) | 5,687 → 10 (−99.8%) | +| `memo-chat` | 0.549 → 0.340 (−38.0%) | 0.621 → 0.385 (−38.0%) | 0.072 → 0.071 (−1.7%) | 0.241 → 0.086 (−64.3%) | 1,047 → 713 (−31.9%) | +| `md-beside:commit` | 1.218 → 0.818 (−32.9%) | 1.418 → 0.984 (−30.6%) | 0.227 → 0.030 (−86.7%) | 0.223 → 0.111 (−50.3%) | 4,637 → 1,788 (−61.4%) | +| `list:commit` | 0.540 → 0.375 (−30.6%) | 0.599 → 0.419 (−30.1%) | 0.073 → 0.006 (−91.8%) | 0.140 → 0.089 (−36.0%) | 2,048 → 853 (−58.3%) | +| `md-virtual:commit` | 0.855 → 0.620 (−27.5%) | 1.046 → 0.793 (−24.2%) | 0.151 → 0.045 (−70.2%) | 0.136 → 0.069 (−49.4%) | 2,916 → 1,228 (−57.9%) | +| `stack` | 3.962 → 3.254 (−17.9%) | 4.735 → 4.011 (−15.3%) | 1.355 → 1.352 (−0.2%) | 1.278 → 0.788 (−38.4%) | 25,877 → 20,594 (−20.4%) | +| `tree` | 3.216 → 2.700 (−16.0%) | 3.728 → 3.244 (−13.0%) | 0.920 → 0.913 (−0.7%) | 1.163 → 0.733 (−37.0%) | 16,704 → 11,740 (−29.7%) | +| `stack-same` | 3.651 → 3.186 (−12.7%) | 4.365 → 3.861 (−11.5%) | 1.340 → 1.344 (+0.3%) | 1.035 → 0.773 (−25.4%) | 25,806 → 20,523 (−20.5%) | +| `vlist-resize` | 0.452 → 0.432 (−4.5%) | 0.498 → 0.480 (−3.6%) | 0.000 → 0.000 | 0.072 → 0.060 (−16.8%) | 2,236 → 1,747 (−21.9%) | +| `md-resize` | 1.822 → 1.742 (−4.4%) | 1.979 → 1.903 (−3.8%) | 0.000 → 0.000 | 0.265 → 0.230 (−13.2%) | 8,335 → 6,308 (−24.3%) | +| `md-open` | 17.674 → 17.543 (−0.7%) | 18.371 → 18.571 (+1.1%) | 0.456 → 0.481 (+5.5%) | 0.131 → 0.117 (−10.6%) | 47,253 → 48,266 (+2.1%) | +| `edit` | 18.980 → 19.009 (+0.2%) | 19.421 → 19.410 (−0.1%) | 0.007 → 0.007 (0.0%) | 0.053 → 0.052 (−1.7%) | 1,153 → 1,150 (−0.3%) | + +### `scroll_bench` (`e6371c48` → after) + +| Workload | Frame CPU p50 / p95 (ms) | Commit CPU p50 / p95 (ms) | View p50 / p95 (ms) | Apply p50 / p95 (ms) | Allocs p50 / p95 | +|---|---:|---:|---:|---:|---:| +| `card` | 2.010 → 1.268 (−36.9%) / 2.289 → 1.417 | 1.491 → 0.760 (−49.0%) / 1.700 → 0.853 | 0.513 → 0.301 (−41.3%) / 0.607 → 0.339 | 0.486 → 0.167 (−65.6%) / 0.551 → 0.196 | 9,327 → 3,504 (−62.4%) / 9,380 → 3,557 | +| `growth` (commits every 12th frame) | 0.478 → 0.481 / 2.315 → 2.047 (−11.6%) | 0.000 / 1.846 → 1.585 (−14.1%) | 0.000 / 0.356 → 0.355 | 0.000 / 0.595 → 0.395 (−33.6%) | 6 / 10,272 → 8,239 (−19.8%) | +| `list`, `markdown`, `prose`, `sticky` (non-committing scroll) | within ±1.2% | 0.000 → 0.000 | 0.000 → 0.000 | 0.000 → 0.000 | unchanged | + +## Tried and dropped + +- **Moving `Node`s on `!same_path` `memo` reuse.** When a reused `memo` subtree shifts to a new + parent path (`!same_path`), `old.id != new_id`. Replacing `old_nodes[flat.start + k]` with + `Node::moved_stub()` causes `apply`'s retirement loop (`if old.is_moved_stub() { forget(old); continue; }`) + to skip `Scene::remove(old.id)` whenever no sibling took `old`'s former path, dropping exit + transitions on the old slot. Kept `Node` moves strictly to `same_path` `memo` reuse, partial + `virtual_rows` remount, and `relayout`, where `old.id == new_id` is in `self.node_index`. +- **Keeping `n.text_layout` attached across `relayout`'s `solve`.** Clearing `n.text_layout = None` + before `solve` drops the node's `Rc<Layout<Ink>>` so `TextSystem`'s cache holds the sole + strong reference (`Rc::strong_count == 1`), letting width changes re-break shaped runs in place. + Fixed-size wrapped text (`w_full().h(..)`) skips Taffy's `measure_leaf`, so keeping `n.text_layout` + across `solve` leaves `strong_count == 2` at `lay_out_text` and forces a clone of the shaped runs + on resize (`resizing_rebreaks_kept_texts_in_place`). Dropped. +- **Two-step `get_key_value` lookup in `MemoCache` to avoid `Rc<str>` construction on nested hits.** + Doing `get_key_value(name)` followed by `get_mut(&existing_id)` added a second hash lookup on + every top-level `memo` hit and regressed `memo-chat` `view_ms` by ~11%. Storing `id: Rc<str>` on + `Entry` itself kept a single `get_mut(name)` lookup while still avoiding `Rc<str>` allocation + when nested. diff --git a/app/vendor/rune/research/engine-spike/paragraph_stack.rs b/app/vendor/rune/research/engine-spike/paragraph_stack.rs new file mode 100644 index 0000000..c99302f --- /dev/null +++ b/app/vendor/rune/research/engine-spike/paragraph_stack.rs @@ -0,0 +1,464 @@ +//! Throwaway spike for research/32-engine-plan.md ("Spike results"), included from +//! `crates/rune/src/text.rs` under `cfg(test)` on the `spike/engine` branch only. +//! +//! - `paragraphs_stack_like_one_layout`: one Parley layout per `\n` paragraph, stacked, against +//! one layout of the whole text, over the rewrap matrix joined into multi-paragraph texts. +//! - `bench_edit_keystroke` (ignored): typing in the 50 KB `edit` note, whole text vs stacked. +//! - `bench_word_cache` (ignored): a per-word `parley_engine` shaper cache vs Parley paragraph +//! shaping on real files. +//! +//! cargo test --profile perf -p rune --lib engine_spike -- --ignored --nocapture --test-threads=1 +use super::*; +use crate::edit::Block; +use std::cell::Cell; + +thread_local! { + /// Overrides the base direction Parley otherwise takes from a layout's first strong character. + pub(crate) static FORCE_DIR: Cell<Option<parley::BaseDirection>> = const { Cell::new(None) }; +} + +#[derive(Clone)] +struct Case { name: String, text: String, spans: Vec<Span>, blocks: Vec<Block>, pills: Vec<PillChip>, style: TextStyle, align: Alignment, wrap_anywhere: bool } + +fn case(name: &str, text: &str, style: TextStyle) -> Case { + Case { name: name.into(), text: text.into(), spans: vec![], blocks: vec![], pills: vec![], style, align: Alignment::Start, wrap_anywhere: false } +} + +/// `rewrap_tests::cases`, plus an Arabic paragraph ending in digits (bidi weak types across `\n`). +fn cases() -> Vec<Case> { + let body = TextStyle::new(15.0, 400.0).lh(22.0); + let rich = "The quick brown fox jumps over the_lazy_dog and keeps running past \ + https://example.com/a/very/long/unbreakable/path/that/overflows/any/line while larger words sit beside it."; + let at = |s: &str| rich.find(s).unwrap() as u32; + let spans = vec![ + Span { start: at("jumps"), end: at("jumps") + 5, ..Span::default() }.bold(), + Span { start: at("the_lazy_dog"), end: at("the_lazy_dog") + 12, ..Span::default() }.mono(), + Span { start: at("keeps"), end: at("keeps") + 5, ..Span::default() }.italic(), + Span { start: at("larger"), end: at("larger") + 12, ..Span::default() }.size(22.0), + ]; + let paragraphs = "First a plain paragraph that wraps over a few lines of text.\nA bullet item long enough to wrap onto a second line at most widths.\nA quoted line that also wraps when the width narrows enough.\nlet code = run(\"a long line of code\");"; + let pill_text = "ask @code-reviewer about @src/main.rs and @notes today please, then wrap"; + let pills = ["@code-reviewer", "@src/main.rs", "@notes"].iter().map(|label| { + let start = pill_text.find(label).unwrap() as u32; + PillChip { start, end: start + label.len() as u32, icon: None, bg: None, fg: None } + }).collect(); + vec![ + Case { spans: spans.clone(), ..case("spans", rich, body) }, + Case { spans: spans.clone(), wrap_anywhere: true, ..case("wrap anywhere", rich, body) }, + Case { spans: spans.clone(), align: Alignment::Center, ..case("centred", rich, body) }, + Case { spans: spans.clone(), align: Alignment::End, ..case("end", rich, body) }, + Case { spans, align: Alignment::Justify, ..case("justified", rich, body) }, + case("right to left", "مرحبا بالعالم هذا نص طويل يلتف عبر عدة أسطر في التخطيط، ثم שלום עולם וטקסט נוסף", body), + Case { align: Alignment::Justify, ..case("right to left justified", "مرحبا بالعالم هذا نص طويل يلتف عبر عدة أسطر في التخطيط والمزيد من الكلمات هنا", body) }, + case("arabic then digits", "مرحبا بالعالم 2024", body), + case("mixed fonts", "Mixed 中文字符和日本語のテキスト with emoji 🎉🚀 and math 𝑥² ∑ beside Latin words that wrap", body), + case("mono tabs", "fn main() {\n\tlet x = 1;\t// a comment that runs long enough to wrap\n}", TextStyle::new(13.0, 400.0).family(Family::Mono)), + Case { blocks: vec![Block::Paragraph, Block::Bullet(0), Block::Quote, Block::Code], ..case("blocks", paragraphs, body) }, + Case { pills, ..case("pills", pill_text, TextStyle::new(14.0, 400.0)) }, + ] +} + +const PLAIN: &str = "123 then a plain paragraph between the others, long enough to wrap at the narrower widths."; + +/// `c` joined with plain and empty paragraphs: `parts` of "case", "plain" and "empty". +fn join(c: &Case, parts: &[&str], trailing: bool) -> Case { + let name = format!("{} [{}{}]", c.name, parts.join(","), if trailing { ",\\n" } else { "" }); + let mut out = Case { name, text: String::new(), spans: vec![], blocks: vec![], pills: vec![], ..c.clone() }; + for (i, part) in parts.iter().enumerate() { + if i > 0 { out.text.push('\n'); } + let at = out.text.len() as u32; + if *part == "case" { + out.spans.extend(c.spans.iter().map(|s| Span { start: s.start + at, end: s.end + at, ..s.clone() })); + out.pills.extend(c.pills.iter().map(|p| PillChip { start: p.start + at, end: p.end + at, ..p.clone() })); + out.blocks.extend((0..c.text.split('\n').count()).map(|k| c.blocks.get(k).copied().unwrap_or(Block::Paragraph))); + out.text += &c.text; + } else { + out.text += if *part == "plain" { PLAIN } else { "" }; + out.blocks.push(Block::Paragraph); + } + } + if trailing { out.text.push('\n'); } + out +} + +type Row = (&'static str, Vec<f64>); + +/// The first `keep` lines of `l` as rows, moved down `y0` and along `byte0`, pill ids by `pill0`. +/// With `frac`, each line top rounds from `y0` plus the unrounded height above it, as breaking +/// the paragraph with Parley's `line_y` starting at `y0` would. Returns the kept lines' height. +fn rows(l: &Layout<Ink>, byte0: usize, (dx, y0): (f64, f64), pill0: u64, keep: usize, frac: bool, out: &mut Vec<Row>) -> f64 { + let mut h = 0.0; + for line in l.lines().take(keep) { + let (m, r) = (line.metrics(), line.text_range()); + let shift = if frac { (y0 + h).round() - m.block_min_coord as f64 } else { y0 }; + let y = |v: f32| v as f64 + shift; + h += m.line_height as f64; + out.push(("line", vec![(r.start + byte0) as f64, (r.end + byte0) as f64, m.offset as f64 + dx, y(m.baseline), m.advance as f64, + m.inline_min_coord as f64, y(m.block_min_coord), y(m.block_max_coord), m.line_height as f64])); + for item in line.items() { + match item { + PositionedLayoutItem::GlyphRun(run) => { + let font = run.run().font(); + let mut g = vec![font.data.id() as f64, font.index as f64, run.run().font_size() as f64, y(run.baseline()), run.offset() as f64 + dx]; + g.extend(run.positioned_glyphs().flat_map(|p| [p.id as f64, p.x as f64 + dx, y(p.y)])); + out.push(("glyphs", g)); + } + PositionedLayoutItem::InlineBox(b) => { + let id = if b.id & PILL_BOX != 0 { b.id + (pill0 << 1) } else { b.id }; + out.push(("box", vec![id as f64, b.x as f64 + dx, y(b.y)])); + } + } + } + } + h +} + +fn whole(ts: &mut TextSystem, c: &Case, scale: f32, width: Option<f32>) -> (Vec<Row>, bool) { + let l = ts.layout_blocks_inner(&c.text, &c.spans, &c.blocks, &c.pills, c.style, scale, width, c.align, c.wrap_anywhere, true); + let mut out = vec![("size", vec![l.full_width() as f64, l.width() as f64, l.height() as f64, l.len() as f64])]; + rows(&l, 0, (0.0, 0.0), 0, l.len(), false, &mut out); + (out, l.is_rtl()) +} + +/// `text` split after each `\n`; a paragraph keeps its `\n`, so its layout ends in an empty line. +fn split(text: &str) -> Vec<(usize, &str)> { + let mut at = 0; + let mut out: Vec<(usize, &str)> = text.split_inclusive('\n').map(|p| { at += p.len(); (at - p.len(), p) }).collect(); + if out.is_empty() { out.push((0, "")); } + out +} + +/// One layout per paragraph, stacked: each drops the empty line after its `\n` unless it is last. +/// With `fix`, line tops round as one layout's do (see `rows`), and at an unbounded width each +/// paragraph moves over to align in the widest paragraph rather than in its own widest line. +fn stacked(ts: &mut TextSystem, c: &Case, scale: f32, width: Option<f32>, fix: bool) -> Vec<Row> { + let (mut out, mut y, mut size, mut pill0) = (Vec::new(), 0.0f64, [0.0f64; 4], 0u64); + let paras = split(&c.text); + let mut laid = Vec::new(); + for (k, &(start, text)) in paras.iter().enumerate() { + let (s, e) = (start as u32, (start + text.len()) as u32); + let spans: Vec<Span> = c.spans.iter().filter(|x| x.start < e && x.end > s) + .map(|x| Span { start: x.start.max(s) - s, end: x.end.min(e) - s, ..x.clone() }).collect(); + let pills: Vec<PillChip> = c.pills.iter().filter(|p| p.start >= s && p.end <= e) + .map(|p| PillChip { start: p.start - s, end: p.end - s, ..p.clone() }).collect(); + let blocks = [c.blocks.get(k).copied().unwrap_or(Block::Paragraph)]; + let l = ts.layout_blocks_inner(text, &spans, &blocks, &pills, c.style, scale, width, c.align, c.wrap_anywhere, true); + laid.push((start, l, pills.len() as u64)); + } + let widest = laid.iter().map(|p| p.1.width()).fold(0.0f32, f32::max) as f64; + for (k, (start, l, pills)) in laid.into_iter().enumerate() { + let keep = if k + 1 < paras.len() { l.len() - 1 } else { l.len() }; + let share = match (c.align, l.is_rtl()) { + (Alignment::Center, _) => 0.5, + (Alignment::End, false) | (Alignment::Start | Alignment::Justify, true) => 1.0, + _ => 0.0, + }; + let dx = if fix && width.is_none() { (widest - l.width() as f64) * share } else { 0.0 }; + size[0] = size[0].max(l.full_width() as f64); + size[1] = size[1].max(l.width() as f64); + size[3] += keep as f64; + y += rows(&l, start, (dx, y), pill0, keep, fix, &mut out); + pill0 += pills; + } + size[2] = y; + out.insert(0, ("size", size.to_vec())); + out +} + +/// Rows that differ, the largest difference in px, and the first differing pair. +fn diff(a: &[Row], b: &[Row]) -> (usize, f64, String) { + let (mut n, mut max, mut first) = (a.len().abs_diff(b.len()), 0.0f64, String::new()); + if n > 0 { max = f64::INFINITY; first = format!("{} rows vs {}", a.len(), b.len()); } + for (x, y) in a.iter().zip(b) { + let d = if x.0 != y.0 || x.1.len() != y.1.len() { f64::INFINITY } else { + x.1.iter().zip(&y.1).map(|(p, q)| (p - q).abs()).fold(0.0, f64::max) + }; + if d > 0.0 { + n += 1; + if first.is_empty() { + let short = |r: &Row| format!("{} {:?}", r.0, &r.1[..r.1.len().min(9)]); + first = format!("{} | {}", short(x), short(y)); + } + max = max.max(d); + } + } + (n, max, first) +} + +#[test] +fn paragraphs_stack_like_one_layout() { + let mut ts = TextSystem::default(); + let shapes: [(&[&str], bool); 4] = [(&["case", "plain", "empty", "case"], false), (&["plain", "case"], false), + (&["case", "plain", "empty", "case"], true), (&["case"], true)]; + let (mut runs, mut exact, mut ulp) = (0, [0; 3], [0; 3]); + for c in cases() { + for (parts, trailing) in shapes { + let j = join(&c, parts, trailing); + for scale in [1.0, 2.0] { + for width in [Some(1200.0), Some(433.5), Some(210.0), None] { + for (m, mode) in ["auto", "forced", "forced+fix"].iter().enumerate() { + (ts.layouts.clear(), ts.shapes.clear()); + let (one, rtl) = whole(&mut ts, &j, scale, width); + let dir = if rtl { parley::BaseDirection::Rtl } else { parley::BaseDirection::Ltr }; + FORCE_DIR.set((m >= 1).then_some(dir)); + (ts.layouts.clear(), ts.shapes.clear()); + let many = stacked(&mut ts, &j, scale, width, m == 2); + FORCE_DIR.set(None); + let (n, max, first) = diff(&one, &many); + runs += usize::from(m == 0); + if n == 0 { exact[m] += 1 } else if max < 1e-3 { ulp[m] += 1 } + if max >= 1e-3 { + println!("MISMATCH {mode} {} @{scale}x w={width:?}: {n}/{} rows, max {max:.3} px\n {first}", j.name, one.len()); + } + } + } + } + } + } + println!("SUMMARY runs={runs} auto: exact={} ulp={} | forced: exact={} ulp={} | forced+fix: exact={} ulp={}", + exact[0], ulp[0], exact[1], ulp[1], exact[2], ulp[2]); +} + +// The `edit` workload: the 50 KB note of `layout_text_cost` (copied from its generator). + +const WORDS: &[&str] = &["amber", "lantern", "orchard", "quiet", "harbor", "copper", "meadow", "signal", "drift", + "pebble", "willow", "ember", "tide", "cinder", "fable", "glacier", "hollow", "juniper", "kestrel", "lumen", + "marrow", "nimbus", "opal", "prism", "quill", "ripple", "sable", "thistle", "umber", "vellum", "wander", + "yarrow", "zephyr", "bramble", "cobalt", "dune", "fern", "grove", "heron", "isle", "the", "a", "of", "and", + "to", "in", "with", "under", "over", "before"]; + +fn note(bytes: usize) -> String { + let mut s = 0x9e37_79b9_7f4a_7c15u64; + let mut r = |n: usize| { s ^= s << 13; s ^= s >> 7; s ^= s << 17; (s % n as u64) as usize }; + let w = |r: &mut dyn FnMut(usize) -> usize, n: usize| (0..n).map(|_| WORDS[r(WORDS.len())]).collect::<Vec<_>>().join(" "); + let rich = |r: &mut dyn FnMut(usize) -> usize, n: usize| (0..n).map(|_| { + let x = WORDS[r(WORDS.len())]; + match r(24) { + 0 => format!("**{x} {}**", WORDS[r(WORDS.len())]), + 1 => format!("*{x}*"), + 2 => format!("`{x}_{}`", r(100)), + 3 => format!("[{x}](https://example.com/{x})"), + _ => x.to_string(), + } + }).collect::<Vec<_>>().join(" "); + let (mut out, mut section) = (String::new(), 0); + while out.len() < bytes { + section += 1; + out += &format!("# Section {section}: {}\n\n", w(&mut r, 3)); + for sub in 0..3 { + out += &format!("## {} {sub}\n\n", w(&mut r, 2)); + for _ in 0..2 { let n = 25 + r(60); out += &rich(&mut r, n); out += ".\n\n"; } + for i in 0..4 + r(5) { + let n = 4 + r(10); + let item = rich(&mut r, n); + out += &if sub % 2 == 0 { format!("- {item}\n") } else { format!("{}. {item}\n", i + 1) }; + } + out += "\n"; + match r(3) { + 0 => { + out += "```rust\n"; + for i in 0..5 + r(6) { + let (name, call) = (WORDS[r(WORDS.len())], WORDS[r(WORDS.len())]); + out += &format!(" let {name}_{i} = {call}(\"{}\");\n", w(&mut r, 2)); + } + out += "```\n\n"; + } + 1 => { let n = 12 + r(20); out += &format!("> {}\n\n", rich(&mut r, n)); } + _ => { for _ in 0..3 { let n = 3 + r(6); out += &format!("- [ ] {}\n", rich(&mut r, n)); } out += "\n"; } + } + } + } + out +} + +/// This thread's CPU clock, ms. +fn cpu_ms() -> f64 { + let mut t = libc::timespec { tv_sec: 0, tv_nsec: 0 }; + // SAFETY: `t` is a valid timespec for the call to fill. + unsafe { libc::clock_gettime(libc::CLOCK_THREAD_CPUTIME_ID, &mut t) }; + t.tv_sec as f64 * 1e3 + t.tv_nsec as f64 / 1e6 +} + +fn median(v: &mut [f64]) -> (f64, f64) { + v.sort_by(f64::total_cmp); + (v[v.len() / 2], v[((v.len() - 1) as f64 * 0.95).round() as usize]) +} + +/// Each keystroke types `w` mid-note, as `layout_text_cost --case edit` does, then lays out: +/// whole (one layout), naive (every paragraph through the layout cache) or incremental (only +/// the edited paragraph; the others keep their `Rc`). Modes alternate order every keystroke. +#[test] +#[ignore] +fn bench_edit_keystroke() { + let src = note(50 * 1024); + let style = TextStyle::new(15.0, 400.0).lh(22.0); + let lay = |ts: &mut TextSystem, t: &str| ts.layout_blocks_inner(t, &[], &[], &[], style, 2.0, Some(696.0 * 2.0), Alignment::Start, false, true); + struct Mode { ts: TextSystem, text: String, caret: usize, paras: Vec<(usize, Rc<Layout<Ink>>)>, cpu: Vec<f64>, peak: Vec<f64>, heap: isize, open: isize } + let mut modes: Vec<Mode> = (0..3).map(|_| { + let mut ts = TextSystem::default(); + lay(&mut ts, "Warm fonts and a few words"); + for _ in 0..3 { ts.end_commit(); } + Mode { ts, text: src.clone(), caret: src[..src.len() / 2].rfind(' ').unwrap() + 1, paras: vec![], cpu: vec![], peak: vec![], heap: 0, open: 0 } + }).collect(); + let step = |k: usize, m: &mut Mode, typed: bool| { + if typed { m.text.insert(m.caret, 'w'); m.caret += 1; } + match k { + 0 => { lay(&mut m.ts, &m.text); } + 1 => { let ls: Vec<_> = split(&m.text).into_iter().map(|(s, p)| (s, lay(&mut m.ts, p))).collect(); m.paras = ls; } + _ if m.paras.is_empty() => { m.paras = split(&m.text).into_iter().map(|(s, p)| (s, lay(&mut m.ts, p))).collect(); } + _ => { + let i = m.paras.partition_point(|p| p.0 < m.caret) - 1; + for p in &mut m.paras[i + 1..] { p.0 += 1; } + let end = m.paras.get(i + 1).map_or(m.text.len(), |p| p.0); + m.paras[i].1 = lay(&mut m.ts, &m.text[m.paras[i].0..end]); + } + } + // The prefix index a composite keeps: each paragraph's top, from the heights above it. + let mut y = 0.0f64; + let tops: Vec<f64> = m.paras.iter().map(|p| { let t = y; y += p.1.height() as f64; t }).collect(); + std::hint::black_box(tops); + m.ts.end_commit(); + }; + for (k, m) in modes.iter_mut().enumerate() { + let live = crate::test_alloc::live(); + step(k, m, false); + m.open = crate::test_alloc::live() - live; + for _ in 0..3 { step(k, m, true); } + } + let mut mid = [0isize; 3]; + for i in 0..480 { + if i == 120 { for k in 0..3 { mid[k] = modes[k].open + modes[k].heap; } } + for j in 0..3 { + let k = if i % 2 == 0 { j } else { 2 - j }; + let m = &mut modes[k]; + let (live, cpu) = (crate::test_alloc::live(), cpu_ms()); + let ((), peak) = crate::test_alloc::peak(|| step(k, m, true)); + m.cpu.push(cpu_ms() - cpu); + m.heap += crate::test_alloc::live() - live; + m.peak.push(peak as f64 / 1e6); + } + } + let n = split(&modes[0].text).len(); + let edited = split(&modes[2].text).into_iter().filter(|p| p.0 < modes[2].caret).last().unwrap().1.len(); + println!("EDIT edited_paragraph_bytes={edited}"); + for (k, m) in modes.iter_mut().enumerate() { + // Stale entries only: live paragraphs stay alive through `m.paras`. + let live = crate::test_alloc::live(); + (m.ts.layouts.clear(), m.ts.shapes.clear()); + println!("EDIT mode={} stale_cache_mb={:.2}", ["whole", "naive", "incremental"][k], (live - crate::test_alloc::live()) as f64 / 1e6); + let (cpu, cpu95) = median(&mut m.cpu); + let (peak, _) = median(&mut m.peak); + println!("EDIT mode={} paragraphs={n} cpu_ms median={cpu:.3} p95={cpu95:.3} open_heap_mb={:.2} heap_at_120_mb={:.2} heap_at_480_mb={:.2} keystroke_peak_mb={peak:.2} shaped={} cached_layouts={}", + ["whole", "naive", "incremental"][k], m.open as f64 / 1e6, mid[k] as f64 / 1e6, (m.open + m.heap) as f64 / 1e6, m.ts.shaped, m.ts.layouts.len()); + } +} + +// Word cache: Parley shaping and breaking each `\n` paragraph, against a cache of shaped words +// over `parley_engine` (shaped alone on a miss) with a greedy breaker at spaces. + +struct OneFont<'a>(&'a parley_engine::FontInstance); +impl parley_engine::FontSelector for OneFont<'_> { + fn select_font(&mut self, _: &parley_engine::itemize::Segment, _: &parley_engine::ShapeOptions<'_>, + _: &mut parley_engine::shape::CharCluster) -> Option<parley_engine::FontInstanceRef<'_>> { + Some(self.0.as_ref()) + } +} + +#[derive(Default)] +struct Fx(u64); +impl Hasher for Fx { + fn finish(&self) -> u64 { self.0 } + fn write(&mut self, bytes: &[u8]) { for &b in bytes { self.0 = (self.0.rotate_left(5) ^ b as u64).wrapping_mul(0x51_7c_c1_b7_27_22_0a_95); } } +} + +#[derive(Default)] +struct Engine { analyzer: parley_engine::Analyzer, analysis: parley_engine::Analysis, shaper: parley_engine::Shaper, shaped: parley_engine::ShapedText, styles: Vec<u16> } +impl Engine { + fn shape(&mut self, word: &str, font: &parley_engine::FontInstance, px: f32) -> (f32, Vec<parley_engine::Glyph>) { + self.analyzer.analyze(word, &parley_engine::AnalysisOptions::default(), &mut self.analysis); + let n = self.analysis.char_info().len(); + (self.styles.clear(), self.styles.resize(n, 0)); + let options = parley_engine::ShapeOptions { font_size: px, language: None, features: &[], variations: &[] }; + let item = parley_engine::itemize::Item { char_end: n as u32, options }; + self.shaper.shape_text(word, &self.analysis, &self.styles, [item], OneFont(font), &mut self.shaped); + let glyphs = self.shaped.glyphs().to_vec(); + (glyphs.iter().map(|g| g.advance).sum(), glyphs) + } +} + +#[test] +#[ignore] +fn bench_word_cache() { + let mut collection = Collection::new(CollectionOptions { shared: false, system_fonts: false }); + for data in [&include_bytes!("../../crates/rune/assets/Inter-Regular.ttf")[..], include_bytes!("../../crates/rune/assets/IBMPlexMono-Regular.ttf")] { + collection.register_fonts(Blob::new(Arc::new(data)), None); + } + let mut fcx = FontContext { collection, source_cache: SourceCache::default() }; + let mut lcx = LayoutContext::<Ink>::new(); + let (scale, width) = (2.0f32, 696.0f32 * 2.0); + let root = concat!(env!("CARGO_MANIFEST_DIR"), "/../../"); + for (file, family, size) in [("PLAN.md", "Inter", 15.0f32), ("CHANGELOG.md", "Inter", 15.0), ("crates/rune/src/runtime.rs", "IBM Plex Mono", 13.0)] { + let all = std::fs::read_to_string(format!("{root}{file}")).unwrap(); + let text = &all[..all[..all.len().min(50 * 1024)].rfind('\n').unwrap()]; + let paras: Vec<&str> = text.split('\n').collect(); + let families = [FontFamilyName::named(family)]; + let mut parley = |lcx: &mut LayoutContext<Ink>, p: &str| { + let mut b = lcx.ranged_builder(&mut fcx, p, scale, true); + b.push_default(FontFamily::from(families.as_slice())); + b.push_default(StyleProperty::FontSize(size)); + b.push_default(LineHeight::Absolute(size * 1.5)); + let mut l: Layout<Ink> = b.build(p); + l.break_all_lines(Some(width)); + l + }; + let probe = parley(&mut lcx, "x"); + let font = probe.lines().next().unwrap().runs().next().unwrap().font().clone(); + let font = parley_engine::FontInstance { font, synthesis: Default::default() }; + let px = size * scale; + // Tokens and how many a per-word cache shapes: one per distinct word. + let words: Vec<&str> = paras.iter().flat_map(|p| p.split(' ')).filter(|w| !w.is_empty()).collect(); + let distinct = words.iter().collect::<std::collections::HashSet<_>>().len(); + let mut engine = Engine::default(); + type Words = HashMap<Box<str>, (f32, Vec<parley_engine::Glyph>), std::hash::BuildHasherDefault<Fx>>; + let mut warm: Words = HashMap::default(); + let cached = |engine: &mut Engine, analyze: bool, cache: &mut Words| { + let space = engine.shape(" ", &font, px).0; + let mut lines: Vec<(u32, f32)> = Vec::new(); + for p in &paras { + if analyze { engine.analyzer.analyze(p, &parley_engine::AnalysisOptions::default(), &mut engine.analysis); } + let mut x = 0.0f32; + for (i, w) in p.split(' ').enumerate() { + let adv = if w.is_empty() { 0.0 } else if let Some(e) = cache.get(w) { e.0 } else { + let e = engine.shape(w, &font, px); + let adv = e.0; + cache.insert(w.into(), e); + adv + }; + let next = if i == 0 { adv } else { x + space + adv }; + if next > width && x > 0.0 { lines.push((i as u32, x)); x = adv } else { x = next } + } + lines.push((u32::MAX, x)); + } + std::hint::black_box(&lines); + cache.len() + }; + let (mut t, mut parley_lines) = ([vec![], vec![], vec![], vec![]], 0); + for round in 0..21 { + for j in 0..4 { + let k = if round % 2 == 0 { j } else { 3 - j }; + let cpu = cpu_ms(); + match k { + 0 => parley_lines = paras.iter().map(|p| parley(&mut lcx, p).len()).sum(), + 1 => { cached(&mut engine, false, &mut HashMap::default()); } + 2 => { cached(&mut engine, true, &mut HashMap::default()); } + _ => { cached(&mut engine, true, &mut warm); } + } + if round > 0 { t[k].push(cpu_ms() - cpu); } + } + } + let [a, b, c, d] = t.map(|mut v: Vec<f64>| median(&mut v).0); + println!("WORDCACHE file={file} bytes={} paragraphs={} lines={parley_lines} tokens={} distinct={distinct} hit_rate={:.1}% \ + parley_ms={a:.2} cache_ms={b:.2} cache_plus_analysis_ms={c:.2} speedup={:.2}x speedup_with_analysis={:.2}x warm_ms={d:.2} warm_speedup={:.2}x", + text.len(), paras.len(), words.len(), 100.0 * (1.0 - distinct as f64 / words.len() as f64), a / b, a / c, a / d); + } +} diff --git a/app/vendor/rune/research/gpu-floor/Cargo.toml b/app/vendor/rune/research/gpu-floor/Cargo.toml new file mode 100644 index 0000000..8f2c4d2 --- /dev/null +++ b/app/vendor/rune/research/gpu-floor/Cargo.toml @@ -0,0 +1,27 @@ +# Probes behind research/35-wgpu-vulkan-dx12-cost.md. Not a workspace member: build it from this +# directory. `wgpu_frame` draws research/30's HUD frame through wgpu; `vk_floor` and `dx12_floor` +# draw the same frame on the raw API with the fewest calls it allows. +[package] +name = "gpu-floor" +version = "0.0.0" +edition = "2024" +publish = false + +[workspace] + +[dependencies] +wgpu = { version = "~30.0.1", default-features = false, features = ["std", "parking_lot", "vulkan", "dx12", "wgsl"] } +winit = { version = "0.30.13", default-features = false, features = ["rwh_06", "x11"] } +pollster = "1" +ash = "0.38" +ash-window = "0.13" + +[target.'cfg(unix)'.dependencies] +libc = "0.2" + +[target.'cfg(windows)'.dependencies] +windows = { version = "0.58", features = ["Win32_Foundation", "Win32_Graphics_Direct3D", "Win32_Graphics_Direct3D12", "Win32_Graphics_Dxgi", "Win32_Graphics_Dxgi_Common", "Win32_System_Threading", "Win32_Security"] } + +[profile.release] +codegen-units = 16 +debug = false diff --git a/app/vendor/rune/research/gpu-floor/cgsplit.py b/app/vendor/rune/research/gpu-floor/cgsplit.py new file mode 100644 index 0000000..8842e05 --- /dev/null +++ b/app/vendor/rune/research/gpu-floor/cgsplit.py @@ -0,0 +1,206 @@ +#!/usr/bin/env python3 +"""Split a callgrind profile's instructions into Rune, wgpu, wgpu-core, wgpu-hal, driver and +other, and count the driver entry points that non-driver code calls. + + cgsplit.py PROFILE [--frames N | --frame-fn SUBSTRING] [--top N] + +A function belongs to a component by its crate (the first path segment of its demangled name) +or, for C code, by its object file. Code that belongs to no component (std, alloc, hashbrown, +libc, ...) is charged to its callers in proportion to the inclusive cost of each call edge, so +a `Vec` growth inside wgpu-core counts as wgpu-core. Per-frame numbers divide by `--frames` +or by the call count of the first function whose name contains `--frame-fn`. +""" + +import argparse +import collections +import re +import sys + +DRIVER_OBJECTS = ("libvulkan_lvp", "libgallium", "libLLVM", "libvulkan.so", "libvkd3d", "d3d12", "dxgi") +CRATES = { + "wgpu_core": "wgpu-core", + "wgpu_hal": "wgpu-hal", + "ash": "wgpu-hal", + "gpu_alloc": "wgpu-hal", + "gpu_descriptor": "wgpu-hal", + "wgpu": "wgpu", + "wgpu_types": "wgpu", + "naga": "wgpu-core", + "floor": "probe", + "wgpu_frame": "probe", + "vk_floor": "probe", + "dx12_floor": "probe", +} +COMPONENTS = ("rune", "probe", "wgpu", "wgpu-core", "wgpu-hal", "driver", "platform", "other") + + +def crate_of(name): + s = name.lstrip("<&*") + if s.startswith("mut "): + s = s[4:] + if s.startswith("dyn "): + s = s[4:] + m = re.match(r"([A-Za-z_][A-Za-z0-9_]*)::", s) + return m.group(1) if m else None + + +def classify(name, obj): + if any(d in obj for d in DRIVER_OBJECTS): + return "driver" + crate = crate_of(name) + if crate is None: + return None + if crate in CRATES: + return CRATES[crate] + if crate.startswith("rune") or crate in ("overlay_hud_cost", "upload_bench", "layout_text_cost"): + return "rune" + if crate in ("winit", "x11rb", "x11_dl", "wayland_client", "wayland_backend", "calloop", "sctk", "smithay_client_toolkit"): + return "platform" + return None + + +def parse(path): + names = {"fn": {}, "ob": {}} + self_cost = collections.Counter() + edges = collections.defaultdict(lambda: [0, 0]) # (caller, callee) -> [calls, inclusive] + obj_of = {} + ob = fn = cob = cfn = None + pending_call = None + + def resolve(kind, rest): + rest = rest.strip() + m = re.match(r"\((\d+)\)(?:\s+(.*))?$", rest) + if not m: + return rest + key, text = m.group(1), m.group(2) + if text is not None: + names[kind][key] = text + return names[kind].get(key, key) + + with open(path, errors="replace") as f: + for line in f: + line = line.rstrip("\n") + if not line: + continue + c = line[0] + if c.isdigit() or c in "+-*": + parts = line.split() + cost = int(parts[1]) if len(parts) > 1 else 0 + if pending_call is not None: + e = edges[(fn, pending_call[0])] + e[0] += pending_call[1] + e[1] += cost + pending_call = None + cob = None + else: + self_cost[fn] += cost + continue + if line.startswith("ob="): + ob = resolve("ob", line[3:]) + elif line.startswith("fn="): + fn = resolve("fn", line[3:]) + obj_of[fn] = ob + cob = None + elif line.startswith("cob="): + cob = resolve("ob", line[4:]) + elif line.startswith("cfn="): + cfn = resolve("fn", line[4:]) + obj_of.setdefault(cfn, cob or ob) + elif line.startswith("calls="): + pending_call = (cfn, int(line[6:].split()[0])) + return self_cost, edges, obj_of + + +def attribute(self_cost, edges, obj_of): + fns = set(self_cost) | {a for a, _ in edges} | {b for _, b in edges} + cls = {f: classify(f or "", obj_of.get(f) or "") for f in fns} + incoming = collections.defaultdict(list) + for (a, b), (_, inc) in edges.items(): + if a != b: + incoming[b].append((a, inc)) + dist = {f: ({cls[f]: 1.0} if cls[f] else {"other": 1.0}) for f in fns} + for _ in range(40): + changed = False + for f in fns: + if cls[f]: + continue + acc = collections.Counter() + total = 0 + for a, inc in incoming.get(f, ()): + if inc <= 0: + continue + for k, v in dist[a].items(): + acc[k] += inc * v + total += inc + if total: + new = {k: v / total for k, v in acc.items()} + if new != dist[f]: + dist[f] = new + changed = True + if not changed: + break + out = collections.Counter() + for f, c in self_cost.items(): + for k, v in dist[f].items(): + out[k] += c * v + return out, cls, dist + + +def main(): + p = argparse.ArgumentParser() + p.add_argument("profile") + p.add_argument("--frames", type=float) + p.add_argument("--frame-fn") + p.add_argument("--top", type=int, default=40) + p.add_argument("--calls", action="store_true", help="list per-frame calls of every wgpu-core and wgpu-hal entry") + a = p.parse_args() + self_cost, edges, obj_of = parse(a.profile) + frames = a.frames + if a.frame_fn: + calls = collections.Counter() + for (x, y), (n, _) in edges.items(): + if y and a.frame_fn in y: + calls[y] += n + if not calls: + sys.exit(f"no function matches {a.frame_fn!r}") + name, frames = calls.most_common(1)[0] + print(f"frames: {frames} calls of {name}") + frames = frames or 1 + split, cls, dist = attribute(self_cost, edges, obj_of) + total = sum(split.values()) + print(f"total Ir: {total:,.0f} per frame: {total / frames / 1e3:,.1f} k") + for k in COMPONENTS: + if split.get(k): + print(f" {k:10s} {split[k] / frames / 1e3:10.1f} k/frame {100 * split[k] / total:5.1f}%") + api = collections.Counter() + api_cost = collections.Counter() + for (x, y), (n, inc) in edges.items(): + if cls.get(y) == "driver" and dist.get(x, {}).get("driver", 0) < 0.5: + api[y] += n + api_cost[y] += inc + print("driver entry points called from outside the driver (per frame, inclusive k):") + for name, n in sorted(api.items(), key=lambda kv: -api_cost[kv[0]])[: a.top]: + print(f" {n / frames:8.2f} {api_cost[name] / frames / 1e3:9.1f}k {name}") + allocs = collections.Counter() + for (x, y), (n, _) in edges.items(): + if y in ("malloc", "calloc", "realloc", "aligned_alloc", "posix_memalign", "memalign"): + for k, v in dist.get(x, {"other": 1.0}).items(): + allocs[k] += n * v + print("heap allocations per frame by component: " + ", ".join( + f"{k} {allocs[k] / frames:.1f}" for k in COMPONENTS if allocs.get(k, 0) / frames >= 0.05)) + wgpu = ("wgpu", "wgpu-core", "wgpu-hal") + entry = collections.Counter() + entry_calls = collections.Counter() + for (x, y), (n, inc) in edges.items(): + cy = cls.get(y) + if cy in wgpu and max(dist.get(x, {}), key=dist.get(x, {}).get, default=None) not in wgpu: + entry[y] += inc + entry_calls[y] += n + print("wgpu entry points called from outside wgpu (per frame, inclusive k):") + for name, inc in entry.most_common(a.top): + if inc / frames >= 100: + print(f" {entry_calls[name] / frames:8.2f} {inc / frames / 1e3:9.1f}k {name[:150]}") + + +if __name__ == "__main__": + main() diff --git a/app/vendor/rune/research/gpu-floor/src/bin/dx12_floor.rs b/app/vendor/rune/research/gpu-floor/src/bin/dx12_floor.rs new file mode 100644 index 0000000..d09a28c --- /dev/null +++ b/app/vendor/rune/research/gpu-floor/src/bin/dx12_floor.rs @@ -0,0 +1,220 @@ +//! research/30's HUD frame on raw D3D12 with the fewest calls the API allows: one command list, +//! two transition barriers (PRESENT -> RENDER_TARGET -> PRESENT, which D3D12 requires for a +//! swapchain buffer), one `ExecuteCommandLists`, one `Present`, one `Signal`. Views are made once. +//! +//! `WRITES=n` writes a 256-byte uniform `n` times a frame. `UPLOAD=mapped` (default) copies into a +//! persistently mapped upload-heap ring with no API call. `UPLOAD=copy` also records a +//! `CopyBufferRegion` per write into a default-heap buffer and one COPY_DEST -> constant-buffer +//! barrier; the buffer decays back to COMMON when the list finishes, so it needs no second one. + +#[path = "../count.rs"] +mod count; +#[path = "../harness.rs"] +mod harness; + +#[cfg(not(windows))] +fn main() { + eprintln!("dx12_floor runs on Windows (or under Wine with vkd3d)"); +} + +#[cfg(windows)] +fn main() { + harness::run("dx12_floor", |window| Box::new(unsafe { imp::Floor::new(window) })); +} + +#[cfg(windows)] +mod imp { + use std::mem::ManuallyDrop; + use std::sync::Arc; + + use windows::Win32::Foundation::{HANDLE, HWND}; + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; + use windows::Win32::Graphics::Direct3D12::*; + use windows::Win32::Graphics::Dxgi::Common::*; + use windows::Win32::Graphics::Dxgi::*; + use windows::Win32::System::Threading::{CreateEventW, INFINITE, WaitForSingleObject}; + use windows::core::Interface; + use winit::raw_window_handle::{HasWindowHandle, RawWindowHandle}; + use winit::window::Window; + + use crate::harness::{Draw, env}; + + const IN_FLIGHT: usize = 2; + const BUFFERS: usize = 3; + const SLOT: u64 = 256; + + pub struct Floor { + _window: Arc<Window>, + queue: ID3D12CommandQueue, + swapchain: IDXGISwapChain3, + targets: Vec<(ID3D12Resource, D3D12_CPU_DESCRIPTOR_HANDLE)>, + _heap: ID3D12DescriptorHeap, + allocators: [ID3D12CommandAllocator; IN_FLIGHT], + list: ID3D12GraphicsCommandList, + fence: ID3D12Fence, + event: HANDLE, + values: [u64; IN_FLIGHT], + next: u64, + mapped: *mut u8, + staging: ID3D12Resource, + uniforms: ID3D12Resource, + writes: usize, + copy: bool, + frame: usize, + } + + unsafe fn buffer(device: &ID3D12Device, size: u64, heap: D3D12_HEAP_TYPE, state: D3D12_RESOURCE_STATES) -> ID3D12Resource { + let props = D3D12_HEAP_PROPERTIES { Type: heap, ..Default::default() }; + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: size, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + ..Default::default() + }; + let mut resource = None; + unsafe { device.CreateCommittedResource(&props, D3D12_HEAP_FLAG_NONE, &desc, state, None, &mut resource).unwrap() }; + resource.unwrap() + } + + fn transition(resource: &ID3D12Resource, before: D3D12_RESOURCE_STATES, after: D3D12_RESOURCE_STATES) -> D3D12_RESOURCE_BARRIER { + D3D12_RESOURCE_BARRIER { + Type: D3D12_RESOURCE_BARRIER_TYPE_TRANSITION, + Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, + Anonymous: D3D12_RESOURCE_BARRIER_0 { + Transition: ManuallyDrop::new(D3D12_RESOURCE_TRANSITION_BARRIER { + // Borrowed for the call, not AddRef'd. + pResource: unsafe { std::mem::transmute_copy(resource) }, + Subresource: D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, + StateBefore: before, + StateAfter: after, + }), + }, + } + } + + impl Floor { + pub unsafe fn new(window: Arc<Window>) -> Floor { + unsafe { + let RawWindowHandle::Win32(handle) = window.window_handle().unwrap().as_raw() else { panic!("not Win32") }; + let hwnd = HWND(handle.hwnd.get() as *mut _); + let factory: IDXGIFactory4 = CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0)).unwrap(); + let adapter: IDXGIAdapter1 = factory.EnumAdapters1(0).unwrap(); + let mut device: Option<ID3D12Device> = None; + D3D12CreateDevice(&adapter, D3D_FEATURE_LEVEL_11_0, &mut device).unwrap(); + let device = device.unwrap(); + let queue: ID3D12CommandQueue = device + .CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: D3D12_COMMAND_LIST_TYPE_DIRECT, ..Default::default() }) + .unwrap(); + let desc = DXGI_SWAP_CHAIN_DESC1 { + Width: 360, + Height: 80, + Format: DXGI_FORMAT_B8G8R8A8_UNORM, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + BufferUsage: DXGI_USAGE_RENDER_TARGET_OUTPUT, + BufferCount: BUFFERS as u32, + SwapEffect: DXGI_SWAP_EFFECT_FLIP_DISCARD, + ..Default::default() + }; + let swapchain: IDXGISwapChain3 = factory.CreateSwapChainForHwnd(&queue, hwnd, &desc, None, None).unwrap().cast().unwrap(); + let heap: ID3D12DescriptorHeap = device + .CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { + Type: D3D12_DESCRIPTOR_HEAP_TYPE_RTV, + NumDescriptors: BUFFERS as u32, + ..Default::default() + }) + .unwrap(); + let start = heap.GetCPUDescriptorHandleForHeapStart(); + let step = device.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_RTV) as usize; + let view = D3D12_RENDER_TARGET_VIEW_DESC { + Format: DXGI_FORMAT_B8G8R8A8_UNORM_SRGB, + ViewDimension: D3D12_RTV_DIMENSION_TEXTURE2D, + ..Default::default() + }; + let targets = (0..BUFFERS) + .map(|i| { + let resource: ID3D12Resource = swapchain.GetBuffer(i as u32).unwrap(); + let handle = D3D12_CPU_DESCRIPTOR_HANDLE { ptr: start.ptr + i * step }; + device.CreateRenderTargetView(&resource, Some(&view), handle); + (resource, handle) + }) + .collect(); + let allocators = [(); IN_FLIGHT].map(|_| device.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).unwrap()); + let list: ID3D12GraphicsCommandList = + device.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &allocators[0], None).unwrap(); + list.Close().unwrap(); + let fence: ID3D12Fence = device.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + let event = CreateEventW(None, false, false, None).unwrap(); + + let writes = env("WRITES", 0usize); + let ring = SLOT * writes.max(1) as u64 * IN_FLIGHT as u64; + let staging = buffer(&device, ring, D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_STATE_GENERIC_READ); + let mut mapped = std::ptr::null_mut(); + staging.Map(0, None, Some(&mut mapped)).unwrap(); + let uniforms = buffer(&device, SLOT, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_COMMON); + let copy = std::env::var("UPLOAD").as_deref() == Ok("copy"); + Floor { + _window: window, + queue, + swapchain, + targets, + _heap: heap, + allocators, + list, + fence, + event, + values: [0; IN_FLIGHT], + next: 0, + mapped: mapped.cast(), + staging, + uniforms, + writes, + copy, + frame: 0, + } + } + } + } + + impl Draw for Floor { + fn frame(&mut self) { + let f = self.frame % IN_FLIGHT; + self.frame += 1; + unsafe { + if self.fence.GetCompletedValue() < self.values[f] { + self.fence.SetEventOnCompletion(self.values[f], self.event).unwrap(); + WaitForSingleObject(self.event, INFINITE); + } + self.allocators[f].Reset().unwrap(); + self.list.Reset(&self.allocators[f], None).unwrap(); + let (target, rtv) = &self.targets[self.swapchain.GetCurrentBackBufferIndex() as usize]; + let phase = (self.frame % 120) as f32 / 120.0; + let data = [phase.to_bits(); 64]; + for w in 0..self.writes { + let offset = (f * self.writes + w) as u64 * SLOT; + std::ptr::copy_nonoverlapping(data.as_ptr().cast::<u8>(), self.mapped.add(offset as usize), SLOT as usize); + if self.copy { + self.list.CopyBufferRegion(&self.uniforms, 0, &self.staging, offset, SLOT); + } + } + let mut barriers = Vec::with_capacity(2); + if self.copy && self.writes > 0 { + barriers.push(transition(&self.uniforms, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_VERTEX_AND_CONSTANT_BUFFER)); + } + barriers.push(transition(target, D3D12_RESOURCE_STATE_PRESENT, D3D12_RESOURCE_STATE_RENDER_TARGET)); + self.list.ResourceBarrier(&barriers); + self.list.ClearRenderTargetView(*rtv, &[0.0, 0.0, phase * 0.4, 0.4], None); + self.list.ResourceBarrier(&[transition(target, D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_PRESENT)]); + self.list.Close().unwrap(); + self.queue.ExecuteCommandLists(&[Some(self.list.cast().unwrap())]); + self.swapchain.Present(1, DXGI_PRESENT(0)).ok().unwrap(); + self.next += 1; + self.queue.Signal(&self.fence, self.next).unwrap(); + self.values[f] = self.next; + } + } + } +} diff --git a/app/vendor/rune/research/gpu-floor/src/bin/vk_floor.rs b/app/vendor/rune/research/gpu-floor/src/bin/vk_floor.rs new file mode 100644 index 0000000..75c5091 --- /dev/null +++ b/app/vendor/rune/research/gpu-floor/src/bin/vk_floor.rs @@ -0,0 +1,194 @@ +//! research/30's HUD frame on raw Vulkan with the fewest calls the API allows: one command +//! buffer, a render pass whose layouts do the swapchain transitions (no `vkCmdPipelineBarrier`), +//! one `vkQueueSubmit`, one present. Views, framebuffers and the render pass are made once. +//! +//! `WRITES=n` writes a 256-byte uniform `n` times a frame. `UPLOAD=mapped` (default) copies into +//! a persistently mapped host-visible ring, as on a unified-memory or resizable-BAR GPU, with no +//! API call. `UPLOAD=copy` stages the bytes and records a `vkCmdCopyBuffer` per write into a +//! device-local buffer, then one buffer barrier, in the frame's command buffer. + +#[path = "../count.rs"] +mod count; +#[path = "../harness.rs"] +mod harness; + +use std::sync::Arc; + +use ash::vk; +use harness::{Draw, env}; +use winit::raw_window_handle::{HasDisplayHandle, HasWindowHandle}; +use winit::window::Window; + +const IN_FLIGHT: usize = 2; +const SLOT: u64 = 256; + +struct Floor { + _window: Arc<Window>, + device: ash::Device, + swapchain_fn: ash::khr::swapchain::Device, + swapchain: vk::SwapchainKHR, + queue: vk::Queue, + render_pass: vk::RenderPass, + framebuffers: Vec<vk::Framebuffer>, + extent: vk::Extent2D, + pools: [vk::CommandPool; IN_FLIGHT], + cmds: [vk::CommandBuffer; IN_FLIGHT], + fences: [vk::Fence; IN_FLIGHT], + acquired: [vk::Semaphore; IN_FLIGHT], + rendered: Vec<vk::Semaphore>, + mapped: *mut u8, + staging: vk::Buffer, + uniforms: vk::Buffer, + writes: usize, + copy: bool, + frame: usize, +} + +fn memory_type(instance: &ash::Instance, pd: vk::PhysicalDevice, bits: u32, flags: vk::MemoryPropertyFlags) -> u32 { + let props = unsafe { instance.get_physical_device_memory_properties(pd) }; + (0..props.memory_type_count) + .find(|&i| bits & (1 << i) != 0 && props.memory_types[i as usize].property_flags.contains(flags)) + .expect("memory type") +} + +unsafe fn buffer(instance: &ash::Instance, pd: vk::PhysicalDevice, device: &ash::Device, size: u64, usage: vk::BufferUsageFlags, + flags: vk::MemoryPropertyFlags) -> (vk::Buffer, vk::DeviceMemory) { + unsafe { + let buffer = device.create_buffer(&vk::BufferCreateInfo::default().size(size).usage(usage), None).unwrap(); + let req = device.get_buffer_memory_requirements(buffer); + let info = vk::MemoryAllocateInfo::default().allocation_size(req.size).memory_type_index(memory_type(instance, pd, req.memory_type_bits, flags)); + let memory = device.allocate_memory(&info, None).unwrap(); + device.bind_buffer_memory(buffer, memory, 0).unwrap(); + (buffer, memory) + } +} + +impl Floor { + unsafe fn new(window: Arc<Window>) -> Floor { + unsafe { + let entry = ash::Entry::load().expect("libvulkan"); + let display = window.display_handle().unwrap().as_raw(); + let exts = ash_window::enumerate_required_extensions(display).unwrap(); + let app = vk::ApplicationInfo::default().api_version(vk::API_VERSION_1_2); + let instance = entry.create_instance(&vk::InstanceCreateInfo::default().application_info(&app).enabled_extension_names(exts), None).unwrap(); + let surface = ash_window::create_surface(&entry, &instance, display, window.window_handle().unwrap().as_raw(), None).unwrap(); + let surface_fn = ash::khr::surface::Instance::new(&entry, &instance); + let (pd, family) = instance.enumerate_physical_devices().unwrap().into_iter().find_map(|pd| { + instance.get_physical_device_queue_family_properties(pd).iter().enumerate().find_map(|(i, q)| { + let present = surface_fn.get_physical_device_surface_support(pd, i as u32, surface).unwrap_or(false); + (q.queue_flags.contains(vk::QueueFlags::GRAPHICS) && present).then_some((pd, i as u32)) + }) + }).expect("a device that presents"); + let name = instance.get_physical_device_properties(pd).device_name_as_c_str().unwrap().to_owned(); + eprintln!("device: {name:?}"); + let priorities = [1.0]; + let queues = [vk::DeviceQueueCreateInfo::default().queue_family_index(family).queue_priorities(&priorities)]; + let dev_exts = [ash::khr::swapchain::NAME.as_ptr()]; + let device = instance.create_device(pd, &vk::DeviceCreateInfo::default().queue_create_infos(&queues).enabled_extension_names(&dev_exts), None).unwrap(); + let queue = device.get_device_queue(family, 0); + + let caps = surface_fn.get_physical_device_surface_capabilities(pd, surface).unwrap(); + let format = surface_fn.get_physical_device_surface_formats(pd, surface).unwrap().into_iter() + .find(|f| f.format == vk::Format::B8G8R8A8_SRGB).expect("BGRA8 sRGB"); + let extent = vk::Extent2D { width: 360, height: 80 }; + let swapchain_fn = ash::khr::swapchain::Device::new(&instance, &device); + let swapchain = swapchain_fn.create_swapchain(&vk::SwapchainCreateInfoKHR::default() + .surface(surface).min_image_count(caps.min_image_count.max(2) + 1).image_format(format.format) + .image_color_space(format.color_space).image_extent(extent).image_array_layers(1) + .image_usage(vk::ImageUsageFlags::COLOR_ATTACHMENT).pre_transform(caps.current_transform) + .composite_alpha(vk::CompositeAlphaFlagsKHR::OPAQUE).present_mode(vk::PresentModeKHR::FIFO).clipped(true), None).unwrap(); + + let attachment = [vk::AttachmentDescription::default().format(format.format).samples(vk::SampleCountFlags::TYPE_1) + .load_op(vk::AttachmentLoadOp::CLEAR).store_op(vk::AttachmentStoreOp::STORE) + .initial_layout(vk::ImageLayout::UNDEFINED).final_layout(vk::ImageLayout::PRESENT_SRC_KHR)]; + let color = [vk::AttachmentReference { attachment: 0, layout: vk::ImageLayout::COLOR_ATTACHMENT_OPTIMAL }]; + let subpass = [vk::SubpassDescription::default().pipeline_bind_point(vk::PipelineBindPoint::GRAPHICS).color_attachments(&color)]; + // Orders the layout transition after the acquire semaphore's wait stage. + let dependency = [vk::SubpassDependency::default().src_subpass(vk::SUBPASS_EXTERNAL).dst_subpass(0) + .src_stage_mask(vk::PipelineStageFlags::COLOR_ATTACHMENT_OUTPUT).dst_stage_mask(vk::PipelineStageFlags::COLOR_ATTACHMENT_OUTPUT) + .dst_access_mask(vk::AccessFlags::COLOR_ATTACHMENT_WRITE)]; + let render_pass = device.create_render_pass(&vk::RenderPassCreateInfo::default() + .attachments(&attachment).subpasses(&subpass).dependencies(&dependency), None).unwrap(); + + let images = swapchain_fn.get_swapchain_images(swapchain).unwrap(); + let framebuffers = images.iter().map(|&image| { + let view = device.create_image_view(&vk::ImageViewCreateInfo::default().image(image).view_type(vk::ImageViewType::TYPE_2D) + .format(format.format).subresource_range(vk::ImageSubresourceRange::default() + .aspect_mask(vk::ImageAspectFlags::COLOR).level_count(1).layer_count(1)), None).unwrap(); + let views = [view]; + device.create_framebuffer(&vk::FramebufferCreateInfo::default().render_pass(render_pass).attachments(&views) + .width(extent.width).height(extent.height).layers(1), None).unwrap() + }).collect(); + let rendered = images.iter().map(|_| device.create_semaphore(&Default::default(), None).unwrap()).collect(); + + let pools = [(); IN_FLIGHT].map(|_| device.create_command_pool(&vk::CommandPoolCreateInfo::default() + .flags(vk::CommandPoolCreateFlags::TRANSIENT).queue_family_index(family), None).unwrap()); + let cmds = pools.map(|pool| device.allocate_command_buffers(&vk::CommandBufferAllocateInfo::default() + .command_pool(pool).command_buffer_count(1)).unwrap()[0]); + let fences = [(); IN_FLIGHT].map(|_| device.create_fence(&vk::FenceCreateInfo::default().flags(vk::FenceCreateFlags::SIGNALED), None).unwrap()); + let acquired = [(); IN_FLIGHT].map(|_| device.create_semaphore(&Default::default(), None).unwrap()); + + let writes = env("WRITES", 0usize); + let ring = SLOT * writes.max(1) as u64 * IN_FLIGHT as u64; + let host = vk::MemoryPropertyFlags::HOST_VISIBLE | vk::MemoryPropertyFlags::HOST_COHERENT; + let (staging, staging_memory) = buffer(&instance, pd, &device, ring, + vk::BufferUsageFlags::UNIFORM_BUFFER | vk::BufferUsageFlags::TRANSFER_SRC, host); + let mapped = device.map_memory(staging_memory, 0, vk::WHOLE_SIZE, vk::MemoryMapFlags::empty()).unwrap().cast(); + let (uniforms, _) = buffer(&instance, pd, &device, SLOT, + vk::BufferUsageFlags::UNIFORM_BUFFER | vk::BufferUsageFlags::TRANSFER_DST, vk::MemoryPropertyFlags::DEVICE_LOCAL); + let copy = std::env::var("UPLOAD").as_deref() == Ok("copy"); + Floor { _window: window, device, swapchain_fn, swapchain, queue, render_pass, framebuffers, extent, pools, cmds, fences, + acquired, rendered, mapped, staging, uniforms, writes, copy, frame: 0 } + } + } +} + +impl Draw for Floor { + fn frame(&mut self) { + let f = self.frame % IN_FLIGHT; + self.frame += 1; + let d = &self.device; + unsafe { + d.wait_for_fences(&[self.fences[f]], true, u64::MAX).unwrap(); + d.reset_fences(&[self.fences[f]]).unwrap(); + d.reset_command_pool(self.pools[f], vk::CommandPoolResetFlags::empty()).unwrap(); + let (image, _) = self.swapchain_fn.acquire_next_image(self.swapchain, u64::MAX, self.acquired[f], vk::Fence::null()).unwrap(); + let phase = (self.frame % 120) as f32 / 120.0; + let data = [phase.to_bits(); 64]; + let cmd = self.cmds[f]; + d.begin_command_buffer(cmd, &vk::CommandBufferBeginInfo::default().flags(vk::CommandBufferUsageFlags::ONE_TIME_SUBMIT)).unwrap(); + for w in 0..self.writes { + let offset = (f * self.writes + w) as u64 * SLOT; + std::ptr::copy_nonoverlapping(data.as_ptr().cast::<u8>(), self.mapped.add(offset as usize), SLOT as usize); + if self.copy { + d.cmd_copy_buffer(cmd, self.staging, self.uniforms, &[vk::BufferCopy { src_offset: offset, dst_offset: 0, size: SLOT }]); + } + } + if self.copy && self.writes > 0 { + let barrier = [vk::BufferMemoryBarrier::default().buffer(self.uniforms).size(vk::WHOLE_SIZE) + .src_access_mask(vk::AccessFlags::TRANSFER_WRITE).dst_access_mask(vk::AccessFlags::UNIFORM_READ)]; + d.cmd_pipeline_barrier(cmd, vk::PipelineStageFlags::TRANSFER, vk::PipelineStageFlags::VERTEX_SHADER | vk::PipelineStageFlags::FRAGMENT_SHADER, + vk::DependencyFlags::empty(), &[], &barrier, &[]); + } + let clear = [vk::ClearValue { color: vk::ClearColorValue { float32: [0.0, 0.0, phase * 0.4, 0.4] } }]; + d.cmd_begin_render_pass(cmd, &vk::RenderPassBeginInfo::default().render_pass(self.render_pass) + .framebuffer(self.framebuffers[image as usize]).render_area(self.extent.into()).clear_values(&clear), vk::SubpassContents::INLINE); + d.cmd_end_render_pass(cmd); + d.end_command_buffer(cmd).unwrap(); + let waits = [self.acquired[f]]; + let stages = [vk::PipelineStageFlags::COLOR_ATTACHMENT_OUTPUT]; + let cmds = [cmd]; + let signals = [self.rendered[image as usize]]; + let submit = [vk::SubmitInfo::default().wait_semaphores(&waits).wait_dst_stage_mask(&stages).command_buffers(&cmds).signal_semaphores(&signals)]; + d.queue_submit(self.queue, &submit, self.fences[f]).unwrap(); + let swapchains = [self.swapchain]; + let images = [image]; + self.swapchain_fn.queue_present(self.queue, &vk::PresentInfoKHR::default() + .wait_semaphores(&signals).swapchains(&swapchains).image_indices(&images)).unwrap(); + } + } +} + +fn main() { + harness::run("vk_floor", |window| Box::new(unsafe { Floor::new(window) })); +} diff --git a/app/vendor/rune/research/gpu-floor/src/bin/wgpu_frame.rs b/app/vendor/rune/research/gpu-floor/src/bin/wgpu_frame.rs new file mode 100644 index 0000000..7400e1a --- /dev/null +++ b/app/vendor/rune/research/gpu-floor/src/bin/wgpu_frame.rs @@ -0,0 +1,96 @@ +//! research/30's HUD frame through wgpu: acquire, `WRITES` 256-byte `Queue::write_buffer`s, one +//! pass that clears the drawable, submit, present. `BACKEND=vulkan|dx12` (default: the +//! platform's). + +#[path = "../count.rs"] +mod count; +#[path = "../harness.rs"] +mod harness; + +use std::sync::Arc; + +use harness::{Draw, env}; +use winit::window::Window; + +struct Gpu { + _window: Arc<Window>, + surface: wgpu::Surface<'static>, + device: wgpu::Device, + queue: wgpu::Queue, + buffer: wgpu::Buffer, + writes: usize, + frame: u64, +} + +impl Gpu { + fn new(window: Arc<Window>) -> Gpu { + let mut desc = wgpu::InstanceDescriptor::new_without_display_handle(); + desc.backends = match std::env::var("BACKEND").as_deref() { + Ok("dx12") => wgpu::Backends::DX12, + Ok("vulkan") => wgpu::Backends::VULKAN, + _ => wgpu::Backends::PRIMARY, + }; + desc.flags.remove(wgpu::InstanceFlags::VALIDATION_INDIRECT_CALL); + let instance = wgpu::Instance::new(desc); + let surface = instance.create_surface(window.clone()).expect("surface"); + let adapter = pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions { + compatible_surface: Some(&surface), + ..Default::default() + })) + .expect("adapter"); + eprintln!("adapter: {:?}", adapter.get_info()); + let (device, queue) = pollster::block_on(adapter.request_device(&wgpu::DeviceDescriptor::default())).expect("device"); + let size = window.inner_size(); + let mut config = surface.get_default_config(&adapter, size.width.max(1), size.height.max(1)).expect("config"); + config.present_mode = wgpu::PresentMode::AutoVsync; + config.desired_maximum_frame_latency = 2; + surface.configure(&device, &config); + let buffer = device.create_buffer(&wgpu::BufferDescriptor { + label: Some("hud uniforms"), + size: 256, + usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + }); + Gpu { _window: window, surface, device, queue, buffer, writes: env("WRITES", 0), frame: 0 } + } +} + +impl Draw for Gpu { + fn frame(&mut self) { + self.frame += 1; + let frame = match self.surface.get_current_texture() { + wgpu::CurrentSurfaceTexture::Success(t) | wgpu::CurrentSurfaceTexture::Suboptimal(t) => t, + other => panic!("no drawable: {other:?}"), + }; + let view = frame.texture.create_view(&Default::default()); + let phase = (self.frame % 120) as f32 / 120.0; + let data = [phase.to_bits(); 64]; + for _ in 0..self.writes { + // SAFETY: u32 has no padding. + let bytes = unsafe { std::slice::from_raw_parts(data.as_ptr().cast::<u8>(), 256) }; + self.queue.write_buffer(&self.buffer, 0, bytes); + } + let mut encoder = self.device.create_command_encoder(&Default::default()); + { + let _pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { + label: Some("hud"), + color_attachments: &[Some(wgpu::RenderPassColorAttachment { + view: &view, + resolve_target: None, + depth_slice: None, + ops: wgpu::Operations { + load: wgpu::LoadOp::Clear(wgpu::Color { r: 0.0, g: 0.0, b: phase as f64 * 0.4, a: 0.4 }), + store: wgpu::StoreOp::Store, + }, + })], + ..Default::default() + }); + } + self.queue.submit([encoder.finish()]); + self.queue.present(frame); + } +} + +fn main() { + harness::run("wgpu_frame", |window| Box::new(Gpu::new(window))); +} diff --git a/app/vendor/rune/research/gpu-floor/src/count.rs b/app/vendor/rune/research/gpu-floor/src/count.rs new file mode 100644 index 0000000..297678b --- /dev/null +++ b/app/vendor/rune/research/gpu-floor/src/count.rs @@ -0,0 +1,59 @@ +//! Retired user and kernel instructions on the calling thread, from Linux `perf_event_open`, and +//! the thread's CPU time. +//! A Windows build makes the same syscalls directly, which works when it runs under Wine on +//! x86-64 Linux and reads zero elsewhere. + +pub struct Counter { + fds: [i64; 2], +} + +const PERF_EVENT_OPEN: i64 = 298; +const READ: i64 = 0; +const CLOCK_GETTIME: i64 = 228; +const CLOCK_THREAD_CPUTIME_ID: i64 = 3; + +#[cfg(target_os = "linux")] +unsafe fn sys(n: i64, a: i64, b: i64, c: i64, d: i64, e: i64) -> i64 { + unsafe { libc::syscall(n, a, b, c, d, e) } +} + +#[cfg(all(windows, target_arch = "x86_64"))] +unsafe fn sys(n: i64, a: i64, b: i64, c: i64, d: i64, e: i64) -> i64 { + let ret: i64; + unsafe { + std::arch::asm!("syscall", inlateout("rax") n => ret, in("rdi") a, in("rsi") b, in("rdx") c, + in("r10") d, in("r8") e, lateout("rcx") _, lateout("r11") _, options(nostack)); + } + ret +} + +impl Counter { + /// `None` when the kernel refuses (no PMU, `perf_event_paranoid` too high, not Linux). + pub fn new() -> Option<Counter> { + if cfg!(windows) && std::env::var_os("WINE_PERF").is_none() { + return None; + } + let open = |exclude_user: bool| { + // perf_event_attr, version 8 (136 bytes): type HARDWARE, config INSTRUCTIONS. + let mut attr = [0u64; 17]; + attr[0] = (136u64 << 32) | 0; + attr[1] = 1; + attr[5] = if exclude_user { 1 << 4 } else { 1 << 5 } | 1 << 6; + unsafe { sys(PERF_EVENT_OPEN, attr.as_ptr() as i64, 0, -1, -1, 0) } + }; + let fds = [open(false), open(true)]; + (fds[0] >= 0 && fds[1] >= 0).then_some(Counter { fds }) + } + + /// (user instructions, kernel instructions, CPU nanoseconds) so far. + pub fn read(&self) -> (u64, u64, u64) { + let one = |fd: i64| { + let mut v = 0u64; + unsafe { sys(READ, fd, &mut v as *mut u64 as i64, 8, 0, 0) }; + v + }; + let mut ts = [0i64; 2]; + unsafe { sys(CLOCK_GETTIME, CLOCK_THREAD_CPUTIME_ID, ts.as_mut_ptr() as i64, 0, 0, 0) }; + (one(self.fds[0]), one(self.fds[1]), (ts[0] * 1_000_000_000 + ts[1]) as u64) + } +} diff --git a/app/vendor/rune/research/gpu-floor/src/harness.rs b/app/vendor/rune/research/gpu-floor/src/harness.rs new file mode 100644 index 0000000..eab711f --- /dev/null +++ b/app/vendor/rune/research/gpu-floor/src/harness.rs @@ -0,0 +1,93 @@ +//! A 360×80 window that draws a frame as fast as the loop turns, then prints instructions per +//! frame and CPU time per frame on the drawing thread. `FRAMES` (2,000) are measured after `WARMUP` (300). + +use std::sync::Arc; +use std::time::Instant; + +use winit::application::ApplicationHandler; +use winit::event::WindowEvent; +use winit::event_loop::{ActiveEventLoop, ControlFlow, EventLoop}; +use winit::window::{Window, WindowId}; + +use crate::count::Counter; + +pub trait Draw { + fn frame(&mut self); +} + +pub fn env<T: std::str::FromStr>(name: &str, default: T) -> T { + std::env::var(name).ok().and_then(|s| s.parse().ok()).unwrap_or(default) +} + +struct Run<F> { + make: F, + draw: Option<(Arc<Window>, Box<dyn Draw>)>, + counter: Option<Counter>, + frames: u64, + warmup: u64, + measured: u64, + instructions: (u64, u64, u64), + started: Option<Instant>, +} + +pub fn run(label: &str, make: impl FnMut(Arc<Window>) -> Box<dyn Draw> + 'static) { + let event_loop = EventLoop::new().expect("event loop"); + event_loop.set_control_flow(ControlFlow::Poll); + let mut run = Run { + make, + draw: None, + counter: Counter::new(), + frames: 0, + warmup: env("WARMUP", 300), + measured: env("FRAMES", 2000), + instructions: (0, 0, 0), + started: None, + }; + event_loop.run_app(&mut run).expect("run"); + let n = run.measured as f64; + let wall = run.started.map(|s| s.elapsed().as_secs_f64()).unwrap_or(0.0); + println!( + "{label}: frames={} kinstr_user={:.2} kinstr_kernel={:.2} cpu_us={:.2} fps={:.0}", + run.measured, + run.instructions.0 as f64 / n / 1e3, + run.instructions.1 as f64 / n / 1e3, + run.instructions.2 as f64 / n / 1e3, + n / wall + ); +} + +impl<F: FnMut(Arc<Window>) -> Box<dyn Draw>> ApplicationHandler for Run<F> { + fn resumed(&mut self, event_loop: &ActiveEventLoop) { + if self.draw.is_none() { + let attrs = Window::default_attributes().with_inner_size(winit::dpi::PhysicalSize::new(360, 80)).with_title("floor"); + let window = Arc::new(event_loop.create_window(attrs).expect("window")); + self.draw = Some((window.clone(), (self.make)(window))); + } + } + + fn window_event(&mut self, event_loop: &ActiveEventLoop, _: WindowId, event: WindowEvent) { + if let WindowEvent::CloseRequested = event { + event_loop.exit(); + } + } + + fn about_to_wait(&mut self, event_loop: &ActiveEventLoop) { + let Some((_, draw)) = self.draw.as_mut() else { return }; + let timed = self.frames >= self.warmup; + if timed && self.started.is_none() { + self.started = Some(Instant::now()); + } + let before = self.counter.as_ref().map(Counter::read).unwrap_or_default(); + draw.frame(); + if timed && let Some(c) = &self.counter { + let after = c.read(); + self.instructions.0 += after.0 - before.0; + self.instructions.1 += after.1 - before.1; + self.instructions.2 += after.2 - before.2; + } + self.frames += 1; + if self.frames >= self.warmup + self.measured { + event_loop.exit(); + } + } +} diff --git a/app/vendor/rune/research/gpu-floor/wgpu-hal-log-barriers.patch b/app/vendor/rune/research/gpu-floor/wgpu-hal-log-barriers.patch new file mode 100644 index 0000000..a9591c3 --- /dev/null +++ b/app/vendor/rune/research/gpu-floor/wgpu-hal-log-barriers.patch @@ -0,0 +1,36 @@ +--- a/src/vulkan/command.rs ++++ b/src/vulkan/command.rs +@@ -120,6 +120,7 @@ + type A = super::Api; + + unsafe fn begin_encoding(&mut self, label: crate::Label) -> Result<(), crate::DeviceError> { ++ if std::env::var_os("LOG_BARRIERS").is_some() { eprintln!("BEGIN {:?}", label); } + if self.free.is_empty() { + let vk_info = vk::CommandBufferAllocateInfo::default() + .command_pool(self.raw) +@@ -208,6 +209,7 @@ + let (dst_stage, dst_access) = conv::map_buffer_usage_to_barrier(bar.usage.to); + dst_stages |= dst_stage; + ++ if std::env::var_os("LOG_BARRIERS").is_some() { eprintln!("BARRIER buf {:?} -> {:?}", bar.usage.from, bar.usage.to); } + vk_barriers.push( + vk::BufferMemoryBarrier::default() + .buffer(bar.buffer.raw) +@@ -254,6 +256,7 @@ + let dst_layout = conv::derive_image_layout(bar.usage.to, bar.texture.format); + dst_stages |= dst_stage; + ++ if std::env::var_os("LOG_BARRIERS").is_some() { eprintln!("BARRIER tex {:?} -> {:?} layout {:?} -> {:?}", bar.usage.from, bar.usage.to, src_layout, dst_layout); } + vk_barriers.push( + vk::ImageMemoryBarrier::default() + .image(bar.texture.raw) +--- a/src/vulkan/mod.rs ++++ b/src/vulkan/mod.rs +@@ -1376,6 +1376,7 @@ + surface_textures: &[&SurfaceTexture], + (signal_fence, signal_value): (&Fence, crate::FenceValue), + ) -> Result<(), crate::DeviceError> { ++ if std::env::var_os("LOG_BARRIERS").is_some() { eprintln!("SUBMIT cbs={} surfaces={}", command_buffers.len(), surface_textures.len()); } + let mut fence_raw = vk::Fence::null(); + + let mut wait_semaphores = SemaphoreList::new(SemaphoreListMode::Wait); diff --git a/app/vendor/rune/research/overlay-cpu/metal_hud.swift b/app/vendor/rune/research/overlay-cpu/metal_hud.swift new file mode 100644 index 0000000..6f892b7 --- /dev/null +++ b/app/vendor/rune/research/overlay-cpu/metal_hud.swift @@ -0,0 +1,155 @@ +// A minimal hand-written Metal HUD for comparing per-frame CPU with Rune's overlay +// (crates/rune/examples/overlay_hud_cost.rs): a 360x80 borderless panel at the bottom of the +// screen whose CAMetalLayer is cleared to an animating colour from a CVDisplayLink callback, +// one command buffer per frame with the drawable presented on it. +// +// swiftc -O metal_hud.swift -o metal_hud && ./metal_hud +// +// Env: HUD_SECONDS (default 12); HUD_EXTRA_CBS=n commits n empty command buffers a frame; +// HUD_SPLIT_PRESENT=1 presents from a command buffer of its own; HUD_DIRECT_PRESENT=1 commits, +// waits until the command buffer is scheduled and presents the drawable with no command buffer; +// HUD_HANDLERS=n adds a completion handler to n command buffers a frame (extras first); +// HUD_LABELS=1 labels each one; HUD_MAIN=1 draws on the main thread (the display link only +// wakes it). These mimic what wgpu does per frame (research/30-overlay-gpu-cost.md). +// Prints frames, fps and CPU ms per second for the main thread, the drawing thread and the rest. + +import AppKit +import CoreVideo +import Metal +import QuartzCore + +func env(_ name: String, _ fallback: Int) -> Int { Int(ProcessInfo.processInfo.environment[name] ?? "") ?? fallback } +let seconds = Double(env("HUD_SECONDS", 12)) +let extraCBs = env("HUD_EXTRA_CBS", 0) +let splitPresent = env("HUD_SPLIT_PRESENT", 0) != 0 +let directPresent = env("HUD_DIRECT_PRESENT", 0) != 0 +let handlers = env("HUD_HANDLERS", 0) +let labels = env("HUD_LABELS", 0) != 0 +let onMain = env("HUD_MAIN", 0) != 0 + +func threadCPU() -> Double { + var t = timespec() + clock_gettime(CLOCK_THREAD_CPUTIME_ID, &t) + return Double(t.tv_sec) * 1e3 + Double(t.tv_nsec) / 1e6 +} +func processCPU() -> Double { + var u = rusage() + getrusage(RUSAGE_SELF, &u) + func ms(_ t: timeval) -> Double { Double(t.tv_sec) * 1e3 + Double(t.tv_usec) / 1e3 } + return ms(u.ru_utime) + ms(u.ru_stime) +} + +func processCounts() -> [UInt64] { + var info = rusage_info_v4() + let ok = withUnsafeMutablePointer(to: &info) { p in + p.withMemoryRebound(to: rusage_info_t?.self, capacity: 1) { proc_pid_rusage(getpid(), RUSAGE_INFO_V4, $0) } + } + return ok == 0 ? [info.ri_instructions, info.ri_cycles, info.ri_interrupt_wkups] : [0, 0, 0] +} + +final class Hud { + let device = MTLCreateSystemDefaultDevice()! + lazy var queue = device.makeCommandQueue()! + let layer = CAMetalLayer() + let start = Date() + var frames = 0 + var drawCPU = 0.0 + var mainCPU0 = 0.0, process0 = 0.0, draw0 = 0.0, frames0 = 0, wall0 = Date() + var warm = false + var counts0: [UInt64] = [0, 0, 0] + + var handled = 0 + + func frame() { + handled = 0 + let entered = threadCPU() + frames += 1 + let elapsed = Date().timeIntervalSince(start) + if !warm && elapsed >= 2 { + warm = true + process0 = processCPU(); counts0 = processCounts(); draw0 = drawCPU; frames0 = frames; wall0 = Date() + DispatchQueue.main.async { self.mainCPU0 = threadCPU() } + } + if warm && elapsed >= seconds { + let wall = Date().timeIntervalSince(wall0) + let n = Double(frames - frames0) + let draw = drawCPU - draw0 + let process = processCPU() - process0 + let counts = processCounts() + let per = { (i: Int) in Double(counts[i] - self.counts0[i]) / n } + DispatchQueue.main.async { + let main = threadCPU() - self.mainCPU0 + let drawing = onMain ? 0 : draw + print(String(format: "frames=%.0f fps=%.1f main_ms_per_s=%.1f draw_thread_ms_per_s=%.1f other_ms_per_s=%.1f process_cpu_pct=%.1f draw_us_per_frame=%.1f", + n, n / wall, main / wall, drawing / wall, (process - main - drawing) / wall, process / wall / 10, draw * 1e3 / n)) + print(String(format: "process_per_frame: kinstructions=%.1f kcycles=%.1f wakeups=%.2f", per(0) / 1e3, per(1) / 1e3, per(2))) + exit(0) + } + } + autoreleasepool { + guard let drawable = layer.nextDrawable() else { return } + let phase = sin(elapsed * 2) * 0.5 + 0.5 + for _ in 0..<extraCBs { commit(queue.makeCommandBufferWithUnretainedReferences()!, "extra") } + let cb = queue.makeCommandBufferWithUnretainedReferences()! + let pass = MTLRenderPassDescriptor() + pass.colorAttachments[0].texture = drawable.texture + pass.colorAttachments[0].loadAction = .clear + pass.colorAttachments[0].storeAction = .store + pass.colorAttachments[0].clearColor = MTLClearColor(red: 0, green: 0, blue: phase * 0.4, alpha: 0.4) + cb.makeRenderCommandEncoder(descriptor: pass)!.endEncoding() + if directPresent { + commit(cb, "frame") + cb.waitUntilScheduled() + drawable.present() + } else if splitPresent { + commit(cb, "frame") + let present = queue.makeCommandBuffer()! + present.present(drawable) + commit(present, "present") + } else { + cb.present(drawable) + commit(cb, "frame") + } + } + drawCPU += threadCPU() - entered + } + + func commit(_ cb: MTLCommandBuffer, _ label: String) { + if labels { cb.label = label } + if handled < handlers { handled += 1; cb.addCompletedHandler { _ in } } + cb.commit() + } +} + +let app = NSApplication.shared +app.setActivationPolicy(.accessory) +let hud = Hud() +let screen = NSScreen.main!.frame +let size = NSSize(width: 360, height: 80) +let panel = NSPanel(contentRect: NSRect(x: screen.midX - size.width / 2, y: screen.minY + 60, width: size.width, height: size.height), + styleMask: [.borderless, .nonactivatingPanel], backing: .buffered, defer: false) +panel.isOpaque = false +panel.backgroundColor = .clear +panel.level = .statusBar +panel.ignoresMouseEvents = true +let view = NSView(frame: NSRect(origin: .zero, size: size)) +view.wantsLayer = true +hud.layer.device = hud.device +hud.layer.pixelFormat = .bgra8Unorm +hud.layer.isOpaque = false +hud.layer.framebufferOnly = true +hud.layer.contentsScale = panel.backingScaleFactor +hud.layer.drawableSize = CGSize(width: size.width * panel.backingScaleFactor, height: size.height * panel.backingScaleFactor) +view.layer = hud.layer +panel.contentView = view +panel.orderFrontRegardless() + +var link: CVDisplayLink? +CVDisplayLinkCreateWithActiveCGDisplays(&link) +CVDisplayLinkSetOutputHandler(link!) { _, _, _, _, _ in + if onMain { DispatchQueue.main.async { hud.frame() } } else { hud.frame() } + return kCVReturnSuccess +} +CVDisplayLinkStart(link!) +DispatchQueue.main.asyncAfter(deadline: .now() + seconds + 20) { print("metal_hud: no frames"); exit(1) } +app.run() diff --git a/app/vendor/rune/research/overlay-cpu/wgpu-core-present-skip.patch b/app/vendor/rune/research/overlay-cpu/wgpu-core-present-skip.patch new file mode 100644 index 0000000..ffc1d2f --- /dev/null +++ b/app/vendor/rune/research/overlay-cpu/wgpu-core-present-skip.patch @@ -0,0 +1,16 @@ +diff --git a/src/device/queue.rs b/src/device/queue.rs +index 1c0ac26..7c9c458 100644 +--- a/src/device/queue.rs ++++ b/src/device/queue.rs +@@ -186,7 +186,10 @@ impl Queue { + pending + }; + +- if pending.is_empty() { ++ if pending.is_empty() ++ || (!needs_clear ++ && pending.iter().all(|p| p.usage.from == wgt::TextureUses::PRESENT)) ++ { + // This assert checks that we don't return here if we encoded a + // clear operation for the texture, which would be a problem since + // we haven't done anything yet to ensure it stays alive. If we diff --git a/app/vendor/rune/research/overlay-cpu/wgpu-hal-metal-lazy-command-buffer.patch b/app/vendor/rune/research/overlay-cpu/wgpu-hal-metal-lazy-command-buffer.patch new file mode 100644 index 0000000..dbc4f44 --- /dev/null +++ b/app/vendor/rune/research/overlay-cpu/wgpu-hal-metal-lazy-command-buffer.patch @@ -0,0 +1,254 @@ +diff --git a/src/metal/command.rs b/src/metal/command.rs +index ba41a63..5993441 100644 +--- a/src/metal/command.rs ++++ b/src/metal/command.rs +@@ -153,6 +153,35 @@ impl Encoder<'_> { + } + + impl super::CommandEncoder { ++ /// The Metal command buffer, made now if this encoding hasn't needed one yet. ++ fn cmd_buf(&mut self) -> Retained<ProtocolObject<dyn MTLCommandBuffer>> { ++ if self.raw_cmd_buf.is_none() { ++ assert!(self.begun); ++ let queue = &self.queue_shared.raw; ++ let retain_references = self.shared.settings.retain_command_buffer_references; ++ let relay = self.queue_shared.relay.get(); ++ let label = self.label.as_deref(); ++ let raw = autoreleasepool(move |_| { ++ let cmd_buf_ref = if retain_references { ++ queue.commandBuffer() ++ } else { ++ queue.commandBufferWithUnretainedReferences() ++ } ++ .unwrap(); ++ if let Some(label) = label { ++ cmd_buf_ref.setLabel(Some(&NSString::from_str(label))); ++ } ++ if let Some(relay) = relay { ++ let expected = relay.next_release_value.load(atomic::Ordering::Acquire); ++ cmd_buf_ref.encodeWaitForEvent_value(relay.event.as_ref(), expected); ++ } ++ cmd_buf_ref.to_owned() ++ }); ++ self.raw_cmd_buf = Some(raw); ++ } ++ self.raw_cmd_buf.clone().unwrap() ++ } ++ + pub fn raw_command_buffer(&self) -> Option<&ProtocolObject<dyn MTLCommandBuffer>> { + self.raw_cmd_buf.as_deref() + } +@@ -161,7 +190,7 @@ impl super::CommandEncoder { + if self.state.blit.is_none() { + self.leave_acceleration_structure_builder(); + debug_assert!(self.state.render.is_none() && self.state.compute.is_none()); +- let cmd_buf = self.raw_cmd_buf.as_ref().unwrap(); ++ let cmd_buf = &self.cmd_buf(); + + // This code path is currently unused since the written timestamp is always 0. + // We should see if we can get it working again, if not remove the code. +@@ -271,7 +300,7 @@ impl super::CommandEncoder { + && self.state.compute.is_none() + && self.state.blit.is_none() + ); +- let cmd_buf = self.raw_cmd_buf.as_ref().unwrap(); ++ let cmd_buf = &self.cmd_buf(); + autoreleasepool(|_| { + self.state.acceleration_structure_builder = + cmd_buf.accelerationStructureCommandEncoder().to_owned(); +@@ -500,32 +529,9 @@ impl crate::CommandEncoder for super::CommandEncoder { + return Err(crate::DeviceError::Lost); + } + +- let raw = autoreleasepool(move |_| { +- let cmd_buf_ref = if retain_references { +- queue.commandBuffer() +- } else { +- queue.commandBufferWithUnretainedReferences() +- } +- .unwrap(); +- if let Some(label) = label { +- cmd_buf_ref.setLabel(Some(&NSString::from_str(label))); +- } +- // If strict event sync is enabled on this queue, gate the +- // CB on the relay event at the value the next submit will +- // signal. The CB pauses at the start until the relay fires. +- if let Some(relay) = relay { +- let expected = relay.next_release_value.load(atomic::Ordering::Acquire); +- cmd_buf_ref.encodeWaitForEvent_value(relay.event.as_ref(), expected); +- } +- cmd_buf_ref.to_owned() +- }); +- +- // Queries should either be closed out, or cleared in `discard_encoding`. +- // This assertion is here mainly to facilitate comparison with the other +- // backends, which clear in `begin_encoding` rather than `discard_encoding`. +- debug_assert!(self.state.pending_timer_queries.is_empty()); +- +- self.raw_cmd_buf = Some(raw); ++ let _ = (queue, retain_references, relay); ++ self.label = label.map(str::to_owned); ++ self.begun = true; + + Ok(()) + } +@@ -542,7 +548,7 @@ impl crate::CommandEncoder for super::CommandEncoder { + encoder.endEncoding(); + } + self.state.pending_timer_queries.clear(); +- let had_command_buffer = self.raw_cmd_buf.is_some(); ++ let had_command_buffer = std::mem::take(&mut self.begun); + // Clear the Option first so the underlying `metal::CommandBuffer` is + // dropped before we update the counter. + self.raw_cmd_buf = None; +@@ -566,8 +572,9 @@ impl crate::CommandEncoder for super::CommandEncoder { + debug_assert!(self.state.compute.is_none()); + debug_assert!(self.state.pending_timer_queries.is_empty()); + ++ self.begun = false; + Ok(super::CommandBuffer { +- raw: self.raw_cmd_buf.take().unwrap(), ++ raw: self.raw_cmd_buf.take(), + queue_shared: Arc::clone(&self.queue_shared), + }) + } +@@ -1049,7 +1056,7 @@ impl crate::CommandEncoder for super::CommandEncoder { + if let Some(mv) = desc.multiview_mask { + descriptor.setRenderTargetArrayLength(32 - mv.leading_zeros() as usize); + } +- let raw = self.raw_cmd_buf.as_ref().unwrap(); ++ let raw = &self.cmd_buf(); + let encoder = raw.renderCommandEncoderWithDescriptor(&descriptor).unwrap(); + if let Some(mv) = desc.multiview_mask { + // Most likely the API just wasn't thought about enough. It's not like they ever allow you +@@ -1260,14 +1267,16 @@ impl crate::CommandEncoder for super::CommandEncoder { + unsafe fn begin_debug_marker(&mut self, group_label: &str) { + if let Some(encoder) = self.active_encoder() { + encoder.pushDebugGroup(&NSString::from_str(group_label)); +- } else if let Some(ref buf) = self.raw_cmd_buf { ++ } else if self.begun { ++ let buf = self.cmd_buf(); + buf.pushDebugGroup(&NSString::from_str(group_label)); + } + } + unsafe fn end_debug_marker(&mut self) { + if let Some(encoder) = self.active_encoder() { + encoder.popDebugGroup(); +- } else if let Some(ref buf) = self.raw_cmd_buf { ++ } else if self.begun { ++ let buf = self.cmd_buf(); + buf.popDebugGroup(); + } + } +@@ -1689,7 +1698,7 @@ impl crate::CommandEncoder for super::CommandEncoder { + debug_assert!(self.state.compute.is_none()); + debug_assert!(self.state.render.is_none()); + +- let raw = self.raw_cmd_buf.as_ref().unwrap(); ++ let raw = &self.cmd_buf(); + + autoreleasepool(|_| { + // TimeStamp Queries and ComputePassDescriptor were both introduced in Metal 2.3 (macOS 11, iOS 14) +@@ -1897,18 +1906,19 @@ impl crate::CommandEncoder for super::CommandEncoder { + command_buffers: &[&super::CommandBuffer], + dependencies: &[&super::AccelerationStructure], + ) { +- let Some(first_command_buffer) = command_buffers.first() else { ++ let Some(first_raw) = command_buffers.iter().find_map(|b| b.raw.as_ref()) else { + return; + }; + let desc = MTLResidencySetDescriptor::new(); +- desc.setLabel(first_command_buffer.raw.label().as_deref()); +- let residency_set = first_command_buffer +- .raw ++ desc.setLabel(first_raw.label().as_deref()); ++ let residency_set = first_raw + .device() + .newResidencySetWithDescriptor_error(&desc) + .unwrap(); + for command_buffer in command_buffers { +- command_buffer.raw.useResidencySet(&residency_set); ++ if let Some(raw) = &command_buffer.raw { ++ raw.useResidencySet(&residency_set); ++ } + } + for dependency in dependencies { + residency_set.addAllocation(ProtocolObject::from_ref(&*dependency.raw)); +@@ -1965,7 +1975,8 @@ impl Drop for super::CommandBuffer { + // `command_buffer_created_not_submitted` is usually decremented when the command + // buffer is submitted. But if we're dropping a command buffer that was never + // submitted, we need to decrement the count here. +- let status = self.raw.status(); ++ let Some(raw) = &self.raw else { return }; ++ let status = raw.status(); + if status == MTLCommandBufferStatus::NotEnqueued + || status == MTLCommandBufferStatus::Enqueued + { +diff --git a/src/metal/device.rs b/src/metal/device.rs +index d7287b9..9ba3335 100644 +--- a/src/metal/device.rs ++++ b/src/metal/device.rs +@@ -773,6 +773,8 @@ impl crate::Device for super::Device { + shared: Arc::clone(&self.shared), + queue_shared: Arc::clone(&desc.queue.shared), + raw_cmd_buf: None, ++ begun: false, ++ label: None, + state: super::CommandState::default(), + temp: super::Temp::default(), + counters: Arc::clone(&self.counters), +diff --git a/src/metal/mod.rs b/src/metal/mod.rs +index e227590..831e0f0 100644 +--- a/src/metal/mod.rs ++++ b/src/metal/mod.rs +@@ -741,8 +741,9 @@ impl crate::Queue for Queue { + fence_sync.1.notify_all(); + }); + +- let raw = match command_buffers.last() { +- Some(&cmd_buf) => cmd_buf.raw.clone(), ++ let last = command_buffers.iter().rev().find_map(|b| b.raw.clone()); ++ let raw = match last.clone() { ++ Some(raw) => raw, + None => { + // We do not bother adjusting `command_buffer_created_not_submitted` + // because we immediately commit this buffer. +@@ -775,14 +776,16 @@ impl crate::Queue for Queue { + } + + // only return an extra one if it's extra +- match command_buffers.last() { ++ match last { + Some(_) => None, + None => Some(raw), + } + }; + + for cmd_buffer in command_buffers { +- cmd_buffer.raw.commit(); ++ if let Some(raw) = &cmd_buffer.raw { ++ raw.commit(); ++ } + // One command buffer per `end_encoding` call moves from the + // "created but not yet submitted" bucket into the submitted + // set, so update the counter. +@@ -1354,6 +1357,10 @@ pub struct CommandEncoder { + shared: Arc<AdapterShared>, + queue_shared: Arc<QueueShared>, + raw_cmd_buf: Option<Retained<ProtocolObject<dyn MTLCommandBuffer>>>, ++ /// Between `begin_encoding` and `end_encoding`/`discard_encoding`; the Metal command ++ /// buffer is made on first use, so an encoding that records nothing commits nothing. ++ begun: bool, ++ label: Option<String>, + state: CommandState, + temp: Temp, + counters: Arc<wgt::HalCounters>, +@@ -1372,7 +1379,7 @@ unsafe impl Sync for CommandEncoder {} + + #[derive(Debug)] + pub struct CommandBuffer { +- raw: Retained<ProtocolObject<dyn MTLCommandBuffer>>, ++ raw: Option<Retained<ProtocolObject<dyn MTLCommandBuffer>>>, + queue_shared: Arc<QueueShared>, + } + diff --git a/app/vendor/rune/rust-toolchain.toml b/app/vendor/rune/rust-toolchain.toml new file mode 100644 index 0000000..cf59912 --- /dev/null +++ b/app/vendor/rune/rust-toolchain.toml @@ -0,0 +1,4 @@ +[toolchain] +channel = "1.99.1" +components = ["clippy", "rustfmt"] +targets = ["wasm32-unknown-unknown"] diff --git a/app/vendor/rune/scripts/app-audit b/app/vendor/rune/scripts/app-audit new file mode 100644 index 0000000..79d587b --- /dev/null +++ b/app/vendor/rune/scripts/app-audit @@ -0,0 +1,88 @@ +#!/usr/bin/env bash +# Crude checklist for the slow patterns Rune's "Fast apps" page (and its "Smooth scrolling" section) +# describes, over a repo's Rust files. +# Usage: scripts/app-audit [--strict] <repo> +# Prints one line per finding (check, file:line, source) and a count. Exits 0, or 1 with --strict +# when there are findings. Heuristics only: a finding is a place to look, not a verdict. +set -euo pipefail + +strict=0 +if [ "${1:-}" = "--strict" ]; then strict=1; shift; fi +root="${1:-}" +if [ -z "$root" ] || [ ! -d "$root" ]; then + echo "usage: scripts/app-audit [--strict] <repo>" >&2 + exit 2 +fi +command -v rg >/dev/null || { echo "app-audit: needs ripgrep (rg)" >&2; exit 2; } + +cd "$root" +out=$(rg --files -g '*.rs' -g '!target' -g '!**/tests/**' -g '!tests.rs' -g '!*_tests.rs' -g '!**/benches/**' 2>/dev/null \ + | LC_ALL=C sort \ + | xargs awk ' +function trim(s) { sub(/^[ \t]+/, "", s); if (length(s) > 70) s = substr(s, 1, 70) "..."; return s } +function near(i, before, after, re, j) { + for (j = i - before; j <= i + after; j++) if (j >= 1 && j <= N && L[j] ~ re) return 1 + return 0 +} +function hit(check, i) { printf "%s\t%s:%d\t%s\n", check, file, i, trim(L[i]) } +function flush( i, j, n, v, only, uses, win, cond, ms, evicts, entry) { + if (file == "") return + entry = 0; evicts = 0 + for (i = 1; i <= N; i++) { + if (L[i] ~ /fn (view|poll|init)[ (<]|\.on_[a-z_]+\(/) entry = 1 + if (L[i] ~ /retain|\.remove\(|\.pop|evict|\.clear\(\)|LruCache|truncate/) evicts = 1 + } + for (i = 1; i <= N; i++) { + if (L[i] ~ /^[ \t]*\/\//) continue + if (L[i] ~ /\.virtualize\(/ && L[i] !~ /virtual_rows/) { + win = 0 + for (j = i - 15; j <= i + 40; j++) if (j >= 1 && j <= N && L[j] ~ /\.child\(|\.children\(|\.extend\(|\.push\(/) win = 1 + if (win) hit("virtualize over built rows", i) + } + if (entry && L[i] ~ /Command::new|UnixStream|TcpStream|reqwest::blocking|rusqlite|std::fs::read_to_string|fs::read_to_string/ \ + && L[i] !~ /^[ \t]*use /) hit("blocking call near view/poll/init", i) + if (L[i] ~ /wake_after\(/ && match(L[i], /from_millis\([0-9]+\)/)) { + ms = substr(L[i], RSTART + 12, RLENGTH - 13) + 0 + if (ms <= 33) { + cond = 0 + for (j = i - 4; j <= i; j++) if (j >= 1 && L[j] ~ /(^|[^a-z_])(if|match|return)([^a-z_]|$)/) cond = 1 + if (!cond) hit("wake_after <= 33 ms, unconditional", i) + } + } + if (L[i] ~ /\.layout\((&|"|format)/) { + if (L[i] ~ /\.layout\([^;]*\[[23]\]/ && L[i] !~ /\[[01]\]/) hit("layout rect read for one size", i) + else if (match(L[i], /let (mut )?[a-z_][a-z_0-9]* = .*\.layout\(/)) { + v = L[i]; sub(/^[ \t]*let (mut )?/, "", v); sub(/[^a-z_0-9].*/, "", v) + only = 1; uses = 0 + for (j = i + 1; j <= i + 12 && j <= N; j++) { + n = L[j] + while (match(n, v "\\[[0-9]\\]")) { + uses++ + if (substr(n, RSTART + length(v) + 1, 1) !~ /[23]/) only = 0 + n = substr(n, RSTART + RLENGTH) + } + } + if (uses > 0 && only) hit("layout rect read for one size", i) + } + } + if (!evicts && L[i] ~ /static .*(HashMap|BTreeMap)/) hit("static map cache with no eviction in file", i) + if (L[i] ~ /\.window_layout\(/) hit("window_layout read (re-runs each scroll frame)", i) + if (L[i] ~ /\.on_(layout|drawn_layout)(_tx)?(::<[^>]*>)?\(/ && !near(i, 0, 8, "live_only")) hit("layout handler without live_only", i) + if (L[i] ~ /\.on_hover(_change)?(::<[^>]*>)?\(/ && !near(i, 0, 6, "live_only")) hit("hover kept in state", i) + if (L[i] ~ /scroll_to_instant\(/ && near(i, 10, 10, "wake_after\\(")) hit("instant scroll stepped by wake_after", i) + } +} +FNR == 1 { flush(); file = FILENAME; N = 0; stop = 0 } +{ if (!stop) { if ($0 ~ /#\[cfg\(test\)\]/) stop = 1; else L[++N] = $0 } } +END { flush() } +' 2>/dev/null || true) + +if [ -z "$out" ]; then + echo "app-audit: no findings" + exit 0 +fi +printf '%s\n' "$out" | awk -F'\t' '{ printf "%-42s %-48s %s\n", $1, $2, $3 }' +n=$(printf '%s\n' "$out" | wc -l | tr -d ' ') +echo "app-audit: $n finding(s)" +[ "$strict" = 1 ] && exit 1 +exit 0 diff --git a/app/vendor/rune/scripts/bench-live.py b/app/vendor/rune/scripts/bench-live.py new file mode 100644 index 0000000..c0b72ff --- /dev/null +++ b/app/vendor/rune/scripts/bench-live.py @@ -0,0 +1,34 @@ +#!/usr/bin/env python3 +"""CPU submission benchmark for 16 × 60 Hz meters + 4 × 120 Hz cursors; no window.""" +import argparse +import json +import re +import statistics +import subprocess + +from perf_binary import perf_binary + +p = argparse.ArgumentParser() +p.add_argument('--binary', default='target/perf/live-values') +p.add_argument('--baseline', action='store_true') +a = p.parse_args() +a.binary = str(perf_binary(a.binary)) +modes = ['rebuild'] if a.baseline else ['rebuild', 'live'] +samples = {mode: [] for mode in modes} +for run in range(8): + # Alternate order so driver load and temperature cannot systematically favour a mode. + for mode in modes[::(-1 if run % 2 else 1)]: + cmd = [a.binary, '--frames', '480', '--fps', '120'] + if mode == 'rebuild': + cmd.append('--rebuild') + output = subprocess.run(cmd, check=True, capture_output=True, text=True).stderr + match = re.search(r'frame cpu mean ([\d.]+) ms p50 ([\d.]+) p95 ([\d.]+)', output) + if not match: + raise RuntimeError(output) + if run: + samples[mode].append(dict(zip(['mean_ms', 'p50_ms', 'p95_ms'], map(float, match.groups())))) +results = {} +for mode, runs in samples.items(): + results[mode] = {k: statistics.median(r[k] for r in runs) for k in runs[0]} + results[mode]['runs'] = runs +print(json.dumps(results, indent=2)) diff --git a/app/vendor/rune/scripts/bench-startup.py b/app/vendor/rune/scripts/bench-startup.py new file mode 100644 index 0000000..d0c17d2 --- /dev/null +++ b/app/vendor/rune/scripts/bench-startup.py @@ -0,0 +1,51 @@ +#!/usr/bin/env python3 +"""Fresh-process launch to GPU-complete readable pixels; OS/driver caches stay warm.""" +import argparse +import json +import pathlib +import selectors +import statistics +import subprocess +import time + +from perf_binary import perf_binary + +p = argparse.ArgumentParser() +p.add_argument('--out', required=True, type=pathlib.Path) +p.add_argument('--runs', type=int, default=7) +a = p.parse_args() +a.out.mkdir(parents=True, exist_ok=True) +cases = { + 'settings': ['target/perf/settings'], +} +result = {} +for name, cmd in cases.items(): + cmd = [str(perf_binary(cmd[0])), *cmd[1:]] + runs = [] + for i in range(a.runs + 1): + start = time.perf_counter() + proc = subprocess.Popen(cmd + ['--first-pixels', '--frames', '1'], stdout=subprocess.PIPE, stderr=subprocess.PIPE) + try: + with selectors.DefaultSelector() as selector: + selector.register(proc.stdout, selectors.EVENT_READ) + if not selector.select(timeout=30): + raise TimeoutError(f'{name}: first pixels not ready after 30s') + line = proc.stdout.readline().decode() + elapsed = (time.perf_counter() - start) * 1000 + _, stderr = proc.communicate(timeout=30) + (a.out / f'{name}-{i}.log').write_bytes(line.encode() + stderr) + if proc.returncode or not line.startswith('rune-first-pixels '): + raise RuntimeError(f'{name}: {line}\n{stderr.decode()}') + row = json.loads(line.removeprefix('rune-first-pixels ')) + row['process_ms'] = elapsed + if i: + runs.append(row) + finally: + if proc.poll() is None: + proc.kill() + proc.wait() + median = {k: statistics.median(r[k] for r in runs) for k in runs[0]} + mad = {k: statistics.median(abs(r[k] - median[k]) for r in runs) for k in median} + result[name] = {'median': median, 'mad': mad, 'runs': runs} + print(name, json.dumps(median), flush=True) + (a.out / 'results.json').write_text(json.dumps(result, indent=2) + '\n') diff --git a/app/vendor/rune/scripts/bench-ui.py b/app/vendor/rune/scripts/bench-ui.py new file mode 100644 index 0000000..1934752 --- /dev/null +++ b/app/vendor/rune/scripts/bench-ui.py @@ -0,0 +1,148 @@ +#!/usr/bin/env python3 +"""Repeatable offscreen workloads; build and run on a headless GPU worker. + +Frame-CPU mode: + cargo build --profile perf -p settings --bins --features frame-profile + python3 scripts/bench-ui.py --frame-cpu --out target/frame-cpu --runs 9 + +Scroll frame-CPU mode (windowless; input through draw lists, no GPU submission): + cargo build --profile perf -p rune-kit --example scroll_bench --features markdown,frame-profile + python3 scripts/bench-ui.py --frame-cpu --scroll --out target/scroll --runs 9 +Save scroll_bench under saved/target/perf/examples/ to compare scroll workloads. + +Save the baseline binaries in saved/target/perf, +then build the candidate and add --compare saved/target/perf. Use separate Cargo +target directories for separate source roots. Comparison verifies binary hashes +differ, discards one warmup per side, and alternates paired runs; report medians +and MAD, and keep timing changes only above the observed noise. + +Commit includes view/layout/shaping, and Layout includes shaping: phases overlap; +do not sum them. CPU clocks measure the calling thread; elapsed encode/submit may +include queue backpressure. The runner forces idle frames, so idle is not native +wake CPU; startup measures first completed pixels, not display presentation. +""" +import argparse +import hashlib +import json +import pathlib +import re +import statistics +import subprocess +import os +import selectors +import time + +from perf_binary import perf_binary + +ROOT = pathlib.Path(__file__).resolve().parents[1] +p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) +p.add_argument('--out', required=True, type=pathlib.Path) +p.add_argument('--runs', type=int, default=7) +p.add_argument('--only', default='') +p.add_argument('--frame-cpu', action='store_true', help='include dense fixtures and phase/allocation metrics (build --features frame-profile)') +p.add_argument('--scroll', action='store_true', help='windowless scroll workloads; build rune-kit example scroll_bench with markdown,frame-profile') +p.add_argument('--compare', type=pathlib.Path, help='alternate with saved baseline binaries in a target/perf directory') +a = p.parse_args() +if a.runs < 1: + p.error('--runs must be positive') +a.out.mkdir(parents=True, exist_ok=True) +workloads = { + 'settings': ('settings', ['--script', 'examples/settings/scripts/bench.json', '--frames', '360']), +} +if a.frame_cpu: + workloads['startup'] = ('settings', ['--first-pixels', '--frames', '1']) +if a.scroll: + workloads = {f'scroll-{name}': ('examples/scroll_bench', ['--workload', name, '--frames', '480']) + for name in ('list', 'markdown', 'sticky', 'growth', 'prose')} +rx = re.compile(r'gpu init ([\d.]+) ms, first frame ([\d.]+) ms, frame cpu mean ([\d.]+) ms p50 ([\d.]+) p95 ([\d.]+) max ([\d.]+), (\d+) instances') +names = ['gpu_ms', 'first_ms', 'mean_ms', 'p50_ms', 'p95_ms', 'max_ms', 'instances'] +result = {} +targets = {'current': pathlib.Path(os.environ.get('CARGO_TARGET_DIR', ROOT / 'target')) / 'perf'} +if a.compare: + targets['before'] = a.compare.resolve() +for name, (binary, args) in workloads.items(): + if a.only and name not in a.only.split(','): + continue + binaries = {stage: perf_binary(target / binary) for stage, target in targets.items()} + if a.compare: + hashes = [] + for path in binaries.values(): + digest = hashlib.sha256() + with path.open('rb') as source: + for chunk in iter(lambda: source.read(1024 * 1024), b''): + digest.update(chunk) + hashes.append(digest.digest()) + if hashes[0] == hashes[1]: + p.error(f'{name}: current and before binaries have identical SHA-256 hashes; rebuild separate candidates') + samples = {stage: [] for stage in targets} + for i in range(a.runs + 1): + for stage in list(targets)[::(-1 if i % 2 else 1)]: + cmd = [str(binaries[stage]), *args, '--fps', '120'] + process_ms = None + log_path = a.out / f'{name}-{stage}-{i}.log' + if name == 'startup': + with log_path.open('w+') as log: + start = time.perf_counter() + with subprocess.Popen(cmd, cwd=ROOT, stdout=subprocess.PIPE, stderr=log, text=True) as proc: + try: + with selectors.DefaultSelector() as selector: + selector.register(proc.stdout, selectors.EVENT_READ) + if not selector.select(timeout=30): + raise TimeoutError('first pixels not ready after 30s') + first = proc.stdout.readline() + process_ms = (time.perf_counter() - start) * 1000 + if not first.startswith('rune-first-pixels '): + raise RuntimeError(f'unexpected first-pixels marker: {first}') + stdout, _ = proc.communicate(timeout=30) + log.seek(0) + r = subprocess.CompletedProcess(cmd, proc.returncode, first + stdout, log.read()) + r.check_returncode() + finally: + if proc.poll() is None: + proc.kill() + proc.wait() + else: + r = subprocess.run(cmd, cwd=ROOT, capture_output=True, text=True, check=True, timeout=180) + log_path.write_text(r.stdout + r.stderr) + if a.scroll: + profile = re.search(r'rune-scroll-profile (.+)', r.stdout) + if not profile: + raise RuntimeError(r.stdout + r.stderr) + if i: + samples[stage].append(json.loads(profile[1])) + continue + m = rx.search(r.stderr) + if not m: + raise RuntimeError(r.stderr) + row = dict(zip(names, map(float, m.groups()))) + phase = re.search(r'rune-frame-profile (.+)', r.stderr) + if a.frame_cpu and not phase: + raise RuntimeError('rebuild with --features frame-profile') + if phase: + row.update({k: v for k, v in json.loads(phase[1]).items() if v is not None}) + pixels = re.search(r'rune-first-pixels (.+)', r.stdout) + if pixels: + row.update(json.loads(pixels[1])) + if process_ms is not None: + row['process_ms'] = process_ms + if i: + samples[stage].append(row) + for stage, runs in samples.items(): + med = {k: statistics.median(r[k] for r in runs) for k in runs[0]} + mad = {k: statistics.median(abs(r[k] - med[k]) for r in runs) for k in med} + label = f'{name}.{stage}' if a.compare else name + result[label] = {'median': med, 'mad': mad, 'runs': runs} + print(label, json.dumps(med), flush=True) + for key, value in med.items(): + print(f'METRIC {label}.{key}={value:.6f}', flush=True) + print(f'METRIC {label}.{key}.mad={mad[key]:.6f}', flush=True) + if a.compare: + metric = 'cpu_ms_p50' if a.scroll else ('thread_cpu_ms' if 'thread_cpu_ms' in samples['current'][0] and 'thread_cpu_ms' in samples['before'][0] else 'mean_ms') + ratios = [cur[metric] / old[metric] for cur, old in zip(samples['current'], samples['before'])] + ratio = statistics.median(ratios) + spread = statistics.median(abs(r - ratio) for r in ratios) + result[f'{name}.paired'] = {'metric': metric, 'ratio': ratio, 'mad': spread} + print(f'{name}: paired ratio uses {metric}', flush=True) + print(f'METRIC {name}.paired_ratio={ratio:.6f}', flush=True) + print(f'METRIC {name}.paired_ratio.mad={spread:.6f}', flush=True) + (a.out / 'results.json').write_text(json.dumps(result, indent=2) + '\n') diff --git a/app/vendor/rune/scripts/build-math-wasm.sh b/app/vendor/rune/scripts/build-math-wasm.sh new file mode 100644 index 0000000..abc8c13 --- /dev/null +++ b/app/vendor/rune/scripts/build-math-wasm.sh @@ -0,0 +1,9 @@ +#!/bin/sh +# Reproducibly builds `crates/rune-kit/assets/math/ratex-math.wasm.deflate`, +# `crates/rune-kit/assets/math/katex-fonts.pack.deflate`, and +# `crates/rune-kit/src/math/wasm_hash.rs` from pinned `tools/ratex-math-wasm/`. +# Pass `--check` to rebuild from source and assert byte-for-byte equality. +set -eu + +cd "$(dirname "$0")/.." +exec cargo run --release --manifest-path tools/ratex-math-wasm/pack/Cargo.toml -- "$@" diff --git a/app/vendor/rune/scripts/changelog-fold b/app/vendor/rune/scripts/changelog-fold new file mode 100644 index 0000000..17a1e26 --- /dev/null +++ b/app/vendor/rune/scripts/changelog-fold @@ -0,0 +1,52 @@ +#!/usr/bin/env python3 +"""Fold changelog/unreleased/*.md into CHANGELOG.md under `## dev`, newest first, then delete them. + +Usage: scripts/changelog-fold [--check] +Order is each fragment's first-commit time (git log --diff-filter=A), else the date in its filename. +""" +import calendar, glob, os, re, subprocess, sys, time + +root = subprocess.check_output(["git", "rev-parse", "--show-toplevel"], text=True).strip() +os.chdir(root) +check = "--check" in sys.argv[1:] + + +def stamp(path): + out = subprocess.run( + ["git", "log", "--diff-filter=A", "--format=%ct", "-1", "--", path], + capture_output=True, text=True, + ).stdout.strip() + if out: + return int(out) + m = re.match(r"(\d{4})-(\d{2})-(\d{2})", os.path.basename(path)) + return calendar.timegm((int(m[1]), int(m[2]), int(m[3]), 0, 0, 0)) if m else int(time.time()) + + +frags = [f for f in glob.glob("changelog/unreleased/*.md") if os.path.basename(f) != "README.md"] +if not frags: + print("no fragments") + sys.exit(0) +frags.sort(key=lambda f: (-stamp(f), os.path.basename(f))) +entries = [open(f).read().strip("\n") for f in frags] + +text = open("CHANGELOG.md").read() +lines = text.split("\n") +i = lines.index("## dev") +j = i + 1 +while j < len(lines) and lines[j].strip() == "": + j += 1 +# keep the note line (and any other leading prose) above the entries +while j < len(lines) and lines[j] and not lines[j].startswith(("- ", "## ")): + j += 1 +while j < len(lines) and lines[j].strip() == "": + j += 1 +block = "\n\n".join(entries).split("\n") + [""] +new = lines[:j] + block + lines[j:] +if check: + for f in frags: + print("would fold", f) + sys.exit(0) +open("CHANGELOG.md", "w").write("\n".join(new)) +for f in frags: + os.remove(f) + print("folded", f) diff --git a/app/vendor/rune/scripts/check-dock-menu-macos.py b/app/vendor/rune/scripts/check-dock-menu-macos.py new file mode 100644 index 0000000..b161331 --- /dev/null +++ b/app/vendor/rune/scripts/check-dock-menu-macos.py @@ -0,0 +1,76 @@ +#!/usr/bin/env python3 +"""Pro-only accessory -> Regular proof; uses existing TCC and /tmp/pro-gui.lock.""" +import fcntl +import importlib +import json +import os +import platform +import subprocess +import sys + +native = importlib.import_module("check-native-menu-macos") +native.SESSION = "rune-dock-menu" + + +def check(binary, order): + process = subprocess.Popen([binary], stdin=subprocess.PIPE, stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, env=dict(os.environ, RUNE_MENU_ORDER=order)) + reader = native.Reader(process) + def command(text): + process.stdin.write((text + "\n").encode()) + process.stdin.flush() + def status(custom, regular=True): + command("status") + lines = reader.until("STATUS") + assert f"CUSTOM_PRESENT {str(custom).lower()}" in lines + assert f"POLICY NSApplicationActivationPolicy({0 if regular else 1})" in lines + return next(line.removeprefix("QUIT_KEY ") for line in lines if line.startswith("QUIT_KEY ")) + try: + reader.until("ACCESSORY_CUSTOM" if order == "before" else "ACCESSORY_MISSING") + command("show") + reader.until("WINDOW_READY") + native.call("start_session") + windows = native.call("list_windows", pid=process.pid) + window = next(w for w in windows["windows"] if w["pid"] == process.pid + and w.get("title") == "Rune Dock menu probe" and w.get("is_on_screen")) + target = dict(pid=process.pid, window_id=window["window_id"]) + status(order == "before") + if order == "after": + command("custom") + status(True) + # A real AX menu action verifies the application menu is available after promotion. + native.call("invoke_menu", **target, path=[os.path.basename(binary), "Custom Action"]) + reader.until("CUSTOM") + command("clear") + status(False) + command("dock-off") + status(False, regular=False) # The same root/defaults survive hiding the Dock icon. + command("dock-on") + quit_key = status(False) + native.call("press_key", **target, key=quit_key, modifiers=["cmd"], delivery_mode="foreground") + process.wait(timeout=15) + assert process.returncode == 0, process.returncode + print(f"PASS {order}: accessory promotion, visible app menu, custom composition/removal, Dock toggles and Cmd-Q", flush=True) + finally: + if process.poll() is None: + command("quit") + try: + process.wait(timeout=10) + except subprocess.TimeoutExpired: + process.terminate() + process.wait(timeout=10) + subprocess.run([native.CUA, "end_session", json.dumps({"session": native.SESSION})], + capture_output=True, timeout=15) + + +def main(): + if len(sys.argv) != 2 or not platform.node().lower().startswith("kits-shiny-computer"): + raise SystemExit("run on Pro: check-dock-menu-macos.py /path/to/dock_menu_probe") + with open("/tmp/pro-gui.lock", "a") as lock: + fcntl.flock(lock, fcntl.LOCK_EX) + for order in ("after", "before"): + check(sys.argv[1], order) + + +if __name__ == "__main__": + main() diff --git a/app/vendor/rune/scripts/check-global-shortcut-macos.py b/app/vendor/rune/scripts/check-global-shortcut-macos.py new file mode 100644 index 0000000..6a67cf9 --- /dev/null +++ b/app/vendor/rune/scripts/check-global-shortcut-macos.py @@ -0,0 +1,83 @@ +#!/usr/bin/env python3 +"""Run on pro with the built shortcut_probe binary. Does not change TCC permissions.""" +import fcntl +import json +import os +import platform +import selectors +import subprocess +import sys +import time + +CUA = "/Applications/CuaDriver.app/Contents/MacOS/cua-driver" +SESSION = "rune-global-shortcut" + + +def call(tool, arguments): + result = subprocess.run([CUA, tool, json.dumps(arguments)], capture_output=True, text=True, timeout=30) + if result.returncode: + raise RuntimeError(result.stderr or result.stdout) + value = json.loads(result.stdout) + if value.get("isError"): + raise RuntimeError(result.stdout) + return value + + +def line(process, expected): + deadline = time.monotonic() + 30 + pending = b"" + with selectors.DefaultSelector() as selector: + selector.register(process.stdout, selectors.EVENT_READ) + while time.monotonic() < deadline: + if not selector.select(max(0, deadline - time.monotonic())): + break + output = os.read(process.stdout.fileno(), 4096) + if not output: + raise RuntimeError(f"probe exited {process.poll()} before {expected}") + pending += output + while b"\n" in pending: + output, pending = pending.split(b"\n", 1) + output = output.decode() + print(output.rstrip(), flush=True) + if output.rstrip() == expected: + return + raise RuntimeError(f"timed out waiting for {expected}") + + +def main(): + if len(sys.argv) != 2: + raise SystemExit("usage: check-global-shortcut-macos.py /path/to/shortcut_probe") + if not platform.node().lower().startswith("kits-shiny-computer"): + raise SystemExit("this native check must run on pro, not a fallback worker") + with open("/tmp/pro-gui.lock", "a") as lock: + fcntl.flock(lock, fcntl.LOCK_EX) + owner = subprocess.Popen([sys.argv[1]], stdin=subprocess.PIPE, stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, text=True, bufsize=1) + try: + line(owner, "READY") + # A second process must get Carbon's real conflict, not an in-process duplicate. + conflict = subprocess.run([sys.argv[1], "--probe-conflict"], input="", capture_output=True, text=True, timeout=30) + if conflict.returncode or "CONFLICT" not in conflict.stdout: + raise RuntimeError(conflict.stdout + conflict.stderr) + print("SECOND PROCESS: CONFLICT", flush=True) + # Inspect the native session before input. The registered app stays windowless. + call("start_session", {"session": SESSION}) + call("list_apps", {"session": SESSION}) + result = call("press_key", {"session": SESSION, "target": {"kind": "desktop", "display_id": "primary"}, + "key": "k", "modifiers": ["cmd", "ctrl", "alt", "shift"]}) + print(json.dumps(result), flush=True) + # Driver success alone is not proof: the application must report the handler. + line(owner, "FIRED 1") + print("PASS: Carbon activation reached the app state on its creating thread", flush=True) + finally: + owner.stdin.close() + try: + owner.wait(timeout=10) + except subprocess.TimeoutExpired: + owner.terminate() + owner.wait(timeout=10) + subprocess.run([CUA, "end_session", json.dumps({"session": SESSION})], capture_output=True, timeout=15) + + +if __name__ == "__main__": + main() diff --git a/app/vendor/rune/scripts/check-local.sh b/app/vendor/rune/scripts/check-local.sh new file mode 100644 index 0000000..f02eb30 --- /dev/null +++ b/app/vendor/rune/scripts/check-local.sh @@ -0,0 +1,155 @@ +#!/usr/bin/env bash +# Fast, opt-in local developer checks for Rune (pure POSIX bash/awk/grep; no Python required). +# Usage: scripts/check-local.sh [--wasm] [--all] [--tests] [--help] +set -euo pipefail +cd "$(git rev-parse --show-toplevel)" + +usage() { + cat <<'EOF' +Usage: scripts/check-local.sh [options] + +Fast, opt-in local checks for Rune (no Python required). + +Default steps: + 1. scripts/file-size.sh (includes scripts/folder-shape.sh) + 2. Public-repo hygiene scan on staged + unstaged diff (git diff HEAD) + 3. cargo check (default workspace members) + 4. cargo clippy --lib --bins (default workspace members) + +Options: + --wasm Also run cargo check-wasm and cargo check-webgl + --all Check and lint --workspace --all-targets instead of default members + --tests Also run cargo test-fast + -h, --help Show this help message and exit +EOF +} + +run_wasm=0 +run_all=0 +run_tests=0 + +for arg in "$@"; do + case "$arg" in + --wasm) run_wasm=1 ;; + --all) run_all=1 ;; + --tests) run_tests=1 ;; + -h|--help) usage; exit 0 ;; + *) + printf 'unknown option: %s\n\n' "$arg" >&2 + usage >&2 + exit 2 + ;; + esac +done + +hygiene_tmp="" +trap 'rm -f "${hygiene_tmp:-}"' EXIT + +check_hygiene() { + # Bracketed slashes keep the pattern identical to the repo hygiene regex + # without matching this script itself. + local re='[/]Users[/]|[/]private[/]var[/]|\.ts\.net|ses_[A-Za-z0-9]{20}' + local rc=0 + hygiene_tmp=$(mktemp) || return 1 + git -c core.quotepath=false diff --no-color --no-ext-diff --src-prefix=a/ --dst-prefix=b/ -U0 HEAD -- \ + | awk ' + /^\+\+\+ b\// { + file = substr($0, 7) + sub(/\r$/, "", file) + sub(/\t$/, "", file) + next + } + /^@@ / { + if (match($0, /\+[0-9]+/)) { + line = substr($0, RSTART + 1, RLENGTH - 1) + 0 + } + next + } + /^\+/ && !/^\+\+\+/ { + body = substr($0, 2) + sub(/\r$/, "", body) + check = body + gsub(/host\.example\.ts\.net/, "", check) + printf "%s:%d: %s\n", file, line, check + line++ + } + ' \ + | grep -E -- "$re" > "$hygiene_tmp" || rc=$? + + if [ -s "$hygiene_tmp" ]; then + echo "Public-repo hygiene check found disallowed patterns in diff against HEAD:" >&2 + cat "$hygiene_tmp" >&2 + rm -f "$hygiene_tmp" + hygiene_tmp="" + return 1 + fi + rm -f "$hygiene_tmp" + hygiene_tmp="" + # grep exits 1 on zero matches; any other non-zero status means git/awk/grep errored. + [ "$rc" -eq 0 ] || [ "$rc" -eq 1 ] +} + +step_names=() +step_status=() +step_secs=() +failures=0 + +run_step() { + local name="$1" + shift + printf '\n==> %s\n' "$name" + local start="$SECONDS" + local rc=0 + "$@" || rc=$? + local elapsed=$((SECONDS - start)) + step_names+=("$name") + step_secs+=("$elapsed") + if [ "$rc" -eq 0 ]; then + step_status+=("PASS") + else + step_status+=("FAIL") + failures=$((failures + 1)) + fi +} + +total_start="$SECONDS" + +run_step "file-size" bash scripts/file-size.sh +run_step "public-repo hygiene" check_hygiene + +if [ "$run_all" -eq 1 ]; then + run_step "cargo check --workspace --all-targets" cargo check --workspace --all-targets + run_step "cargo lint-all" cargo lint-all +else + run_step "cargo check" cargo check + run_step "cargo clippy --lib --bins" cargo clippy --lib --bins +fi + +if [ "$run_wasm" -eq 1 ]; then + run_step "cargo check-wasm" cargo check-wasm + run_step "cargo check-webgl" cargo check-webgl +fi + +if [ "$run_tests" -eq 1 ]; then + run_step "cargo test-fast" cargo test-fast +fi + +total_elapsed=$((SECONDS - total_start)) +if [ "$failures" -eq 0 ]; then + overall="PASS" +else + overall="FAIL" +fi + +printf '\nSummary:\n' +printf ' %-38s %-6s %8s\n' "step" "status" "elapsed" +printf ' %-38s %-6s %8s\n' "--------------------------------------" "------" "--------" +i=0 +while [ "$i" -lt "${#step_names[@]}" ]; do + printf ' %-38s %-6s %7ds\n' "${step_names[$i]}" "${step_status[$i]}" "${step_secs[$i]}" + i=$((i + 1)) +done +printf ' %-38s %-6s %8s\n' "--------------------------------------" "------" "--------" +printf ' %-38s %-6s %7ds\n' "total" "$overall" "$total_elapsed" + +[ "$failures" -eq 0 ] diff --git a/app/vendor/rune/scripts/check-native-menu-macos.py b/app/vendor/rune/scripts/check-native-menu-macos.py new file mode 100644 index 0000000..526ad48 --- /dev/null +++ b/app/vendor/rune/scripts/check-native-menu-macos.py @@ -0,0 +1,111 @@ +#!/usr/bin/env python3 +"""Pro-only native menu proof. Uses existing CuaDriver permissions; no TCC changes.""" +import fcntl +import json +import os +import platform +import selectors +import subprocess +import sys +import time + +CUA = "/Applications/CuaDriver.app/Contents/MacOS/cua-driver" +SESSION = "rune-native-menu" + + +def call(tool, **arguments): + result = subprocess.run([CUA, tool, json.dumps(dict(session=SESSION, **arguments))], + capture_output=True, text=True, timeout=30) + if result.returncode: + raise RuntimeError(result.stderr or result.stdout) + value = json.loads(result.stdout) + if value.get("isError"): + raise RuntimeError(result.stdout) + print(tool, json.dumps(value), flush=True) + if "structuredContent" in value: + return value["structuredContent"] + for part in value.get("content", []): + if part.get("type") == "text": + try: + return json.loads(part["text"]) + except json.JSONDecodeError: + pass + return value + + +class Reader: + def __init__(self, process): + self.process = process + self.pending = b"" + + def until(self, expected): + deadline = time.monotonic() + 30 + lines = [] + with selectors.DefaultSelector() as selector: + selector.register(self.process.stdout, selectors.EVENT_READ) + while time.monotonic() < deadline: + while b"\n" in self.pending: + line, self.pending = self.pending.split(b"\n", 1) + line = line.decode().rstrip() + print(line, flush=True) + lines.append(line) + if line == expected: + return lines + if not selector.select(max(0, deadline - time.monotonic())): + break + chunk = os.read(self.process.stdout.fileno(), 4096) + if not chunk: + raise RuntimeError(f"probe exited {self.process.poll()} before {expected}") + self.pending += chunk + raise RuntimeError(f"timed out waiting for {expected}") + + +def main(): + if len(sys.argv) != 2 or not platform.node().lower().startswith("kits-shiny-computer"): + raise SystemExit("run on Pro: check-native-menu-macos.py /path/to/menu_probe") + with open("/tmp/pro-gui.lock", "a") as lock: + fcntl.flock(lock, fcntl.LOCK_EX) + process = subprocess.Popen([sys.argv[1]], stdin=subprocess.PIPE, stdout=subprocess.PIPE, + stderr=subprocess.STDOUT) + reader = Reader(process) + def command(text): + process.stdin.write((text + "\n").encode()) + process.stdin.flush() + try: + reader.until("READY") + call("start_session") + windows = call("list_windows", pid=process.pid) + records = windows.get("windows", windows) if isinstance(windows, dict) else windows + window = next(w for w in records if w["pid"] == process.pid and w.get("title") == "Rune menu probe" and w.get("is_on_screen")) + target = dict(pid=process.pid, window_id=window["window_id"]) + command("status") + status = reader.until("STATUS") + assert "NATIVE enabled=true checked=false" in status and "DOCK items=1" in status + assert "NAMED items=3 separators=[1]" in status + # winit labels the default app menu with NSProcessInfo.processName. + call("invoke_menu", **target, path=[os.path.basename(sys.argv[1]), "Open Quick Panel"]) + reader.until("FIRED 1") + call("press_key", **target, key="k", modifiers=["cmd", "alt", "shift"], delivery_mode="foreground") + reader.until("FIRED 2") + call("invoke_menu", **target, path=["Rune Tools", "Named Quick Panel"]) + reader.until("FIRED 3") + command("disable"); command("status") + status = reader.until("STATUS") + assert "NATIVE enabled=false checked=true" in status and "COUNT 3" in status + command("clear"); command("status") + status = reader.until("STATUS") + assert "NATIVE cleared" in status and "DOCK items=0" in status and "DEFAULTS preserved" in status + print("PASS: app-menu click, key equivalent and named-menu click ran on app thread; runtime state, Dock hook and defaults verified", flush=True) + finally: + if process.poll() is None: + command("quit") + try: + process.wait(timeout=10) + except subprocess.TimeoutExpired: + process.terminate(); process.wait(timeout=10) + subprocess.run([CUA, "end_session", json.dumps({"session": SESSION})], capture_output=True, timeout=15) + assert process.returncode == 0, process.returncode + + +if __name__ == "__main__": + main() diff --git a/app/vendor/rune/scripts/check-native-pacing.py b/app/vendor/rune/scripts/check-native-pacing.py new file mode 100644 index 0000000..3752a52 --- /dev/null +++ b/app/vendor/rune/scripts/check-native-pacing.py @@ -0,0 +1,18 @@ +#!/usr/bin/env python3 +"""Check a timestamp-only `pacing --native --trace FILE --frames 240` run.""" +import json +import statistics +import sys + +with open(sys.argv[1]) as source: + header, *frames = [json.loads(line) for line in source] +assert header['clock'] != 'virtual', 'headless timestamps cannot prove native pacing' +assert len(frames) >= 60, f'only {len(frames)} native frames' +assert sum(frame.get('quality', {}).get('animating', False) for frame in frames) >= 10, 'no spring animation' +# Exclude the first frame/initial gap, not later commit or idle-resume gaps. +gaps = [b['t'] - a['t'] for a, b in zip(frames[1:], frames[2:])] +half_refresh = 500 / header['hz'] +bad = [gap for gap in gaps if gap < half_refresh - 0.01] +print(json.dumps({'frames': len(frames), 'hz': header['hz'], 'half_refresh_ms': half_refresh, + 'minimum_gap_ms': min(gaps), 'median_gap_ms': statistics.median(gaps), 'short_gaps': len(bad)}, indent=2)) +assert not bad, f'{len(bad)} sub-half-refresh gaps' diff --git a/app/vendor/rune/scripts/check-reference-instructions.sh b/app/vendor/rune/scripts/check-reference-instructions.sh new file mode 100644 index 0000000..20dfaf2 --- /dev/null +++ b/app/vendor/rune/scripts/check-reference-instructions.sh @@ -0,0 +1,26 @@ +#!/bin/sh +# Run BOTH revisions on the same Linux worker/toolchain with a shared target dir. +# First: ... save; on the candidate: ... check. Never silently bless a missing baseline. +set -eu +[ "$(uname -s)" = Linux ] || { echo 'Linux + Valgrind required' >&2; exit 1; } +command -v valgrind >/dev/null +command -v gungraun-runner >/dev/null +export RUSTC_WRAPPER= +export RUSTFLAGS="${RUSTFLAGS:-} -C llvm-args=-fp-contract=off" +baseline="${CARGO_TARGET_DIR:-target}/rune-ref-instruction-baseline" +case "${1:-check}" in + save) + cargo bench --locked -p rune-ref --bench instructions -- --save-baseline=main + mkdir -p "$(dirname "$baseline")" + { rustc -Vv; valgrind --version; gungraun-runner --version; } > "$baseline" + ;; + check) + [ -f "$baseline" ] || { echo 'Missing baseline: measure base revision with save first' >&2; exit 1; } + current=$(mktemp) + trap 'rm -f "$current"' EXIT + { rustc -Vv; valgrind --version; gungraun-runner --version; } > "$current" + cmp "$baseline" "$current" + cargo bench --locked -p rune-ref --bench instructions -- --baseline=main + ;; + *) echo 'usage: check-reference-instructions.sh save|check' >&2; exit 1 ;; +esac diff --git a/app/vendor/rune/scripts/check-reference.sh b/app/vendor/rune/scripts/check-reference.sh new file mode 100644 index 0000000..acbe974 --- /dev/null +++ b/app/vendor/rune/scripts/check-reference.sh @@ -0,0 +1,11 @@ +#!/bin/sh +# Invoke on a build worker through the build queue. GPU is headless but still needs an adapter. +set -eu +export RUSTC_WRAPPER= +export RUSTFLAGS="${RUSTFLAGS:-} -C llvm-args=-fp-contract=off" +cargo test --locked -p rune-ref --test reference --test alloc +cargo test --locked -p rune --test alloc +if [ "${1:-}" = "--gpu" ]; then + cargo test --locked -p rune-ref --features gpu --test differential -- --test-threads=1 --nocapture + cargo test --locked -p rune-ref --features gpu --test fx_blend -- --test-threads=1 +fi diff --git a/app/vendor/rune/scripts/coretext-quality.swift b/app/vendor/rune/scripts/coretext-quality.swift new file mode 100644 index 0000000..c03e9c2 --- /dev/null +++ b/app/vendor/rune/scripts/coretext-quality.swift @@ -0,0 +1,58 @@ +// No AppKit, window, or screen access. Matched positions isolate rasterization from shaping. +import Foundation +import CoreText +import CoreGraphics +import ImageIO +import UniformTypeIdentifiers + +let dir = URL(fileURLWithPath: CommandLine.arguments[1]) +let nativeOpticalSize = CommandLine.arguments.contains("--native-opsz") +var shaping: [[String: Any]] = [] +for url in try FileManager.default.contentsOfDirectory(at: dir, includingPropertiesForKeys: nil) + where url.pathExtension == "json" && (url.lastPathComponent.hasPrefix("light-") || url.lastPathComponent.hasPrefix("dark-")) { + let data = try JSONSerialization.jsonObject(with: Data(contentsOf: url)) as! [String: Any] + let width = data["width"] as! Int, height = data["height"] as! Int + let scale = data["scale"] as! Double + let fontURL = URL(fileURLWithPath: data["font"] as! String) + let provider = CGDataProvider(url: fontURL as CFURL)! + let cgfont = CGFont(provider)! + let cs = CGColorSpace(name: CGColorSpace.sRGB)! + let ctx = CGContext(data:nil,width:width,height:height,bitsPerComponent:8,bytesPerRow:width*4, + space:cs,bitmapInfo:CGImageAlphaInfo.premultipliedLast.rawValue)! + let fg = CGFloat(data["fg"] as! Int)/255, bg = CGFloat(data["bg"] as! Int)/255 + ctx.setFillColor(red:bg,green:bg,blue:bg,alpha:1) + ctx.fill(CGRect(x:0,y:0,width:width,height:height)) + ctx.setFillColor(red:fg,green:fg,blue:fg,alpha:1) + ctx.setAllowsAntialiasing(true); ctx.setShouldAntialias(true) + ctx.setAllowsFontSmoothing(true); ctx.setShouldSmoothFonts(true) + ctx.setAllowsFontSubpixelPositioning(true); ctx.setShouldSubpixelPositionFonts(true) + ctx.setAllowsFontSubpixelQuantization(false); ctx.setShouldSubpixelQuantizeFonts(false) + // Preserve nominal point size: CoreText optical smoothing can depend on it. + ctx.scaleBy(x:scale,y:scale) + for row in data["rows"] as! [[String:Any]] { + let base = CTFontCreateWithGraphicsFont(cgfont,CGFloat(row["size"] as! Double),nil,nil) + // Parley's current optical-size selection uses the run's device-pixel size. + // Pin the reference to that same variation; otherwise SF compares different outlines. + let opsz = row["opsz"] as? Double ?? (row["size"] as! Double)*scale + let attrs = [kCTFontVariationAttribute: [NSNumber(value:0x6f70737a): opsz]] as CFDictionary + let font = nativeOpticalSize ? base : CTFontCreateCopyWithAttributes(base,0,nil,CTFontDescriptorCreateWithAttributes(attrs)) + let attributed = NSAttributedString(string: row["text"] as! String, + attributes: [NSAttributedString.Key(kCTFontAttributeName as String): font]) + let line = CTLineCreateWithAttributedString(attributed) + let advance = CTLineGetTypographicBounds(line, nil, nil, nil) * scale + shaping.append(["sample": url.lastPathComponent, "size": row["size"]!, "text": row["text"]!, + "rune_advance": row["advance"] ?? 0, "coretext_advance": advance, + "coretext_variations": String(describing: CTFontCopyVariation(font))]) + let items = row["glyphs"] as! [[String:Any]] + var glyphs = items.map { CGGlyph($0["id"] as! Int) } + var positions = items.map { CGPoint(x:($0["x"] as! Double)/scale,y:(Double(height)-($0["y"] as! Double))/scale) } + CTFontDrawGlyphs(font,&glyphs,&positions,glyphs.count,ctx) + } + let dest = dir.appendingPathComponent("coretext-"+url.deletingPathExtension().lastPathComponent+".png") + let sink = CGImageDestinationCreateWithURL(dest as CFURL,UTType.png.identifier as CFString,1,nil)! + CGImageDestinationAddImage(sink,ctx.makeImage()!,nil) + precondition(CGImageDestinationFinalize(sink)) + print(dest.lastPathComponent) +} +try JSONSerialization.data(withJSONObject: shaping, options: [.prettyPrinted, .sortedKeys]) + .write(to: dir.appendingPathComponent("coretext-shaping.json")) diff --git a/app/vendor/rune/scripts/coretext-reference.sh b/app/vendor/rune/scripts/coretext-reference.sh new file mode 100644 index 0000000..3196252 --- /dev/null +++ b/app/vendor/rune/scripts/coretext-reference.sh @@ -0,0 +1,22 @@ +#!/usr/bin/env bash +# Regenerates the CoreText reference sheets that `rune::text::pixel_compare` (its test and +# `--example coretext_compare`) compares Rune's text with. macOS only. Rune's layout of each +# case goes to scripts/coretext-reference.swift, which draws it with CoreText, font smoothing on +# and off; layout.txt records that layout so a change to it marks the sheets stale. +# crates/rune/tests/coretext/ Inter, committed. +# crates/rune/tests/coretext/sf/ San Francisco from this Mac's system font; never committed +# (Apple's font can't be redistributed). Skipped without SFNS. +# crates/rune/tests/coretext/mono/ SF Mono (SFNSMono) the same way. Skipped without it. +set -euo pipefail +cd "$(git rev-parse --show-toplevel)" +tmp=$(mktemp -d) +trap 'rm -rf "$tmp"' EXIT +cargo run -q -p rune --example coretext_compare -- export "$tmp" +for set in inter sf mono; do + [[ -d "$tmp/$set" ]] || continue + for scale in 1 2; do + swift scripts/coretext-reference.swift "$tmp/$set/cases-${scale}x.json" "$tmp/$set" >/dev/null + done +done +cargo run -q -p rune --example coretext_compare -- pack "$tmp" +du -ch crates/rune/tests/coretext/*.png | tail -1 diff --git a/app/vendor/rune/scripts/coretext-reference.swift b/app/vendor/rune/scripts/coretext-reference.swift new file mode 100644 index 0000000..877f153 --- /dev/null +++ b/app/vendor/rune/scripts/coretext-reference.swift @@ -0,0 +1,106 @@ +// CoreText references for `rune::text::pixel_compare`. +// usage: swift scripts/coretext-reference.swift cases-2x.json OUT_DIR +// +// Draws each case's glyphs (Rune's glyph ids at its unquantised pen positions and whole-pixel +// baselines) with CTFontDrawGlyphs into an opaque sRGB bitmap, one sheet per entry of "sheets": +// antialiasing, subpixel positioning and subpixel quantisation on, as macOS draws window text, +// with font smoothing on or off. Inter comes from its files; "system" cases use CoreText's own +// system font (CTFontCreateUIFontForLanguage) at the case's wght and opsz; "mono" cases AppKit's +// monospaced system font (NSFont.monospacedSystemFont, SF Mono) at the case's weight, the +// instance native apps draw code in. Sheets keep the green +// channel. No window or screen access. +import AppKit +import CoreGraphics +import CoreText +import Foundation +import ImageIO +import UniformTypeIdentifiers + +let args = CommandLine.arguments +let spec = try JSONSerialization.jsonObject(with: Data(contentsOf: URL(fileURLWithPath: args[1]))) as! [String: Any] +let out = URL(fileURLWithPath: args[2]) +let scale = CGFloat(spec["scale"] as! Double) +let width = spec["width"] as! Int, height = spec["height"] as! Int +let paths = spec["fonts"] as! [String: Any] + +func fileFont(_ path: String, _ size: CGFloat) -> CTFont { + let url = URL(fileURLWithPath: path) as CFURL + let desc = (CTFontManagerCreateFontDescriptorsFromURL(url) as! [CTFontDescriptor])[0] + return CTFontCreateWithFontDescriptor(desc, size, nil) +} + +func systemFont(_ size: CGFloat, weight: Double, opsz: Double) -> CTFont { + let base = CTFontCreateUIFontForLanguage(.system, size, nil)! + // Rune shapes the same file at the same instance; anything else would draw other glyphs. + let url = CTFontCopyAttribute(base, kCTFontURLAttribute) as! URL + let rune = paths["system"] as? String ?? "" + precondition(url.resolvingSymlinksInPath().path == URL(fileURLWithPath: rune).resolvingSymlinksInPath().path, + "CoreText's system font is \(url.path), Rune loaded \(rune)") + let axes = [NSNumber(value: 0x7767_6874): weight, NSNumber(value: 0x6f70_737a): opsz] as [NSNumber: Double] + let desc = CTFontDescriptorCreateWithAttributes([kCTFontVariationAttribute: axes] as CFDictionary) + return CTFontCreateCopyWithAttributes(base, size, nil, desc) +} + +func monoFont(_ size: CGFloat, weight: Double) -> CTFont { + let named: [(Double, NSFont.Weight)] = [(100, .ultraLight), (200, .thin), (300, .light), (400, .regular), (500, .medium), (600, .semibold), (700, .bold), (800, .heavy), (900, .black)] + let w = named.min { abs($0.0 - weight) < abs($1.0 - weight) }!.1 + let font = NSFont.monospacedSystemFont(ofSize: size, weight: w) as CTFont + // Rune shapes SFNSMono's glyph ids; the system's monospaced font must be that file. + let file = (CTFontManagerCreateFontDescriptorsFromURL(URL(fileURLWithPath: paths["mono"] as! String) as CFURL) as! [CTFontDescriptor])[0] + precondition(CTFontGetGlyphCount(font) == CTFontGetGlyphCount(CTFontCreateWithFontDescriptor(file, size, nil)), + "AppKit's monospaced system font isn't \(paths["mono"] as! String)") + return font +} + +func color(_ hex: String) -> CGColor { + let v = Int(hex.dropFirst(), radix: 16)! + return CGColor(srgbRed: CGFloat((v >> 16) & 255) / 255, green: CGFloat((v >> 8) & 255) / 255, blue: CGFloat(v & 255) / 255, alpha: 1) +} + +let cases = spec["cases"] as! [[String: Any]] +let fonts: [CTFont] = cases.map { c in + let size = CGFloat(c["size"] as! Double) + switch c["font"] as! String { + case "system": return systemFont(size, weight: c["weight"] as! Double, opsz: c["opsz"] as! Double) + case "mono": return monoFont(size, weight: c["weight"] as! Double) + case let name: return fileFont(paths[name] as! String, size) + } +} + +for sheet in spec["sheets"] as! [[String: Any]] { + let smooth = sheet["smooth"] as! Bool + let ctx = CGContext(data: nil, width: width, height: height, bitsPerComponent: 8, bytesPerRow: width * 4, + space: CGColorSpace(name: CGColorSpace.sRGB)!, bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue)! + ctx.setFillColor(color(sheet["bg"] as! String)) + ctx.fill(CGRect(x: 0, y: 0, width: width, height: height)) + // Top-left origin in points. + ctx.translateBy(x: 0, y: CGFloat(height)) + ctx.scaleBy(x: scale, y: -scale) + ctx.setAllowsAntialiasing(true); ctx.setShouldAntialias(true) + ctx.setAllowsFontSmoothing(smooth); ctx.setShouldSmoothFonts(smooth) + ctx.setAllowsFontSubpixelPositioning(true); ctx.setShouldSubpixelPositionFonts(true) + ctx.setAllowsFontSubpixelQuantization(true); ctx.setShouldSubpixelQuantizeFonts(true) + ctx.setFillColor(color(sheet["fg"] as! String)) + // The flipped text matrix draws glyphs upright under the y-down CTM; positions are in text + // space, so y is negated. + ctx.textMatrix = CGAffineTransform(scaleX: 1, y: -1) + for (c, f) in zip(cases, fonts) { + let rows = c["glyphs"] as! [[Double]] + var glyphs = rows.map { CGGlyph($0[0]) } + var positions = rows.map { CGPoint(x: CGFloat($0[1]) / scale, y: -CGFloat($0[2]) / scale) } + CTFontDrawGlyphs(f, &glyphs, &positions, glyphs.count, ctx) + } + // Keep the green channel only, as raw bytes: the comparison measures green, and one + // channel keeps the sheets small. + let rgba = ctx.data!.bindMemory(to: UInt8.self, capacity: width * height * 4) + var green = [UInt8](repeating: 0, count: width * height) + for i in 0..<(width * height) { green[i] = rgba[i * 4 + 1] } + let grey = CGImage(width: width, height: height, bitsPerComponent: 8, bitsPerPixel: 8, bytesPerRow: width, + space: CGColorSpaceCreateDeviceGray(), bitmapInfo: CGBitmapInfo(rawValue: CGImageAlphaInfo.none.rawValue), + provider: CGDataProvider(data: Data(green) as CFData)!, decode: nil, shouldInterpolate: false, intent: .defaultIntent)! + let name = sheet["file"] as! String + let sink = CGImageDestinationCreateWithURL(out.appendingPathComponent(name) as CFURL, UTType.png.identifier as CFString, 1, nil)! + CGImageDestinationAddImage(sink, grey, nil) + precondition(CGImageDestinationFinalize(sink)) + print(name) +} diff --git a/app/vendor/rune/scripts/cost-attribution.py b/app/vendor/rune/scripts/cost-attribution.py new file mode 100644 index 0000000..1fe1bfb --- /dev/null +++ b/app/vendor/rune/scripts/cost-attribution.py @@ -0,0 +1,253 @@ +#!/usr/bin/env python3 +"""Buckets the stacks `layout_text_cost --mode sample|heap` records by owner: Taffy, Parley +and its font stack, Rune (split by runtime phase), the app's view code, and the allocator. + + scripts/cost-attribution.py symbolize DUMP --exe BINARY > SYMS # where BINARY was built + scripts/cost-attribution.py report DUMP SYMS [--top 12] + +`symbolize` runs `atos -i` (run `dsymutil BINARY` first) so inlined frames count. `report` needs +`rustfilt` on PATH to demangle. Exclusive attribution: a sample or allocation belongs to the +innermost frame that isn't the standard library, collections or memmove; a sample in malloc or +free is the allocator's, with its caller's owner noted. See research/31-layout-text-cost.md. +""" +import collections +import re +import subprocess +import sys + +TRANSPARENT = {"core", "alloc", "std", "hashbrown", "smallvec", "arrayvec", "memchr", "compiler_builtins", + "unicode_segmentation", "rustc_hash", "foldhash", "ahash", "bytemuck", "indexmap", "tinyvec", "slotmap", + "usize", "isize", "u8", "u16", "u32", "u64", "u128", "i8", "i16", "i32", "i64", "i128", "f32", "f64", + "bool", "char", "str", "deduplicated_symbol", "DYLD", "?"} +OWNED = re.compile(r"\b(taffy|parley|parley_engine|fontique|swash|harfrust|skrifa|rune_kit|rune)::") +ALLOCATOR = re.compile(r"^(_?malloc|_?free|_?realloc|_?calloc|_?posix_memalign|_malloc_zone|_?szone|_?nanov2|_?mfm|_xzm|xzm|_?tiny_|_?small_|_?medium_|_?large_|_?default_zone|_?malloc_)") +MEMFN = re.compile(r"^_?(_platform_)?(memmove|memcpy|memset|bzero|memcmp|strlen|bcmp)") +PARLEY_PARTS = [ # first match on the stack, in this order + ("Parley shaping (HarfRust, font tables)", re.compile(r"^<?(harfrust|read_fonts|skrifa|font_types)::|shape::shaper|shape_text")), + ("Parley text analysis (ICU segmenter, bidi)", re.compile(r"^<?icu_|analysis::|itemize::|bidi::|analyze_text")), + ("Parley layout clone (re-break)", re.compile(r"parley::layout::layout::Layout<.*> as core::clone::Clone>::clone")), + ("Parley line breaking and alignment", re.compile(r"line_break|break_all_lines|alignment::align|BreakLines")), +] +PHASES = [ # innermost match wins + ("layout", re.compile(r"text_layout::compute_layout")), + ("flatten", re.compile(r"runtime::flatten::flatten")), + ("view", re.compile(r">::(build_tree|root_view)$|rune::memo::")), + ("place", re.compile(r">::place$")), + ("final text pass", re.compile(r">::measure_view$")), + ("apply", re.compile(r"runtime::Runtime<.*>>::apply$")), + ("paint", re.compile(r"runtime::Runtime<.*>>::build$")), +] + + +def owner_of_crate(crate, name): + if crate == "taffy": + return "Taffy" + if crate == "taffy" or "taffy::" in name and re.search(r"PartialEq|::eq\b", name): + return "Taffy" + if crate in ("parley", "parley_engine", "parley_data", "parley_emoji", "parlance", "harfrust", "skrifa", + "read_fonts", "font_types"): + return "Parley" # split by what the stack is doing, in `parley_part` + if crate == "fontique": + return "Fontique" + if crate in ("swash", "zeno"): + return "Swash raster" + if crate.startswith("icu_") or crate in ("zerovec", "zerotrie", "yoke", "unicode_bidi", "unicode_script"): + return "Parley" + if crate == "rune": + return "Instrumentation (frame-profile clock)" if "frame_profile" in name or "frame::profile" in name else "Rune" + if crate in ("rune_kit", "pulldown_cmark"): + return "Kit and Markdown" + if crate == "layout_text_cost": + return "App (bench views and data)" + if crate in ("rune_motion",): + return "Rune" + return "Other: " + crate + + +def crate_of(name): + """The crate a demangled frame belongs to; for `<T as Trait>::f` and drop glue, T's crate.""" + n = name + m = re.match(r"^core::ptr::drop_in_place::<(.*)>$", n) or re.match(r"^core::ptr::drop_in_place<(.*)>$", n) + if m: + n = m.group(1) + while n.startswith(("<", "&", "mut ", "dyn ", "[", "(", "*const ", "*mut ")): + for p in ("<", "&", "mut ", "dyn ", "[", "(", "*const ", "*mut "): + if n.startswith(p): + n = n[len(p):] + m = re.match(r"^([A-Za-z_][A-Za-z0-9_]*)", n) + return m.group(1) if m else "?" + + +def demangle(names): + names = list(names) + out = subprocess.run(["rustfilt"], input="\n".join(names), capture_output=True, text=True, check=True).stdout.split("\n") + return {a: re.sub(r"::h[0-9a-f]{16}$", "", b) for a, b in zip(names, out)} + + +def symbolize(dump, exe): + addrs = collections.defaultdict(list) + for line in open(dump): + if line.startswith("ADDR "): + _, a, base, sym, image = line.rstrip("\n").split(" ", 4) + if image == exe or image.endswith("/" + exe.split("/")[-1]): + addrs[base].append(a) + for base, group in addrs.items(): + lst = "\n".join(f"0x{int(a, 16) - 1:x}" for a in group) + res = subprocess.run(["atos", "-i", "-o", exe, "-l", "0x" + base], input=lst, capture_output=True, text=True, check=True).stdout + blocks = res.split("\n\n") + if len(blocks) < len(group): + sys.exit(f"atos returned {len(blocks)} blocks for {len(group)} addresses") + for a, block in zip(group, blocks): + frames = [re.sub(r" \(in [^)]*\).*$", "", f).strip() for f in block.strip("\n").split("\n") if f.strip()] + print("SYM " + a + " " + "\t".join(frames)) + + +def load(dump, syms): + cases, meta, addr, stacks = {}, [], {}, {} + samples, allocs, live = [], [], [] + for line in open(dump): + p = line.rstrip("\n").split(" ") + if p[0] == "CASE": + cases[int(p[1])] = p[2] + elif p[0] == "META": + meta.append(dict(kv.split("=", 1) for kv in p[1:])) + elif p[0] == "ADDR": + addr[p[1]] = [p[3]] # system image: its exported symbol; replaced by SYMS below + elif p[0] == "STACK": + stacks[int(p[1])] = p[2:] + elif p[0] == "SAMPLE": + samples.append((int(p[1]), int(p[2]), int(p[3]), 0)) + elif p[0] == "ALLOC": + allocs.append((int(p[1]), int(p[2]), int(p[3]), int(p[4]))) + elif p[0] == "LIVE": + live.append((int(p[1]), int(p[2]), int(p[3]), int(p[4]))) + mangled = set() + exe_frames = {} + for line in open(syms): + if line.startswith("SYM "): + _, a, rest = line.rstrip("\n").split(" ", 2) + exe_frames[a] = rest.split("\t") + mangled.update(exe_frames[a]) + names = demangle(mangled) + for a, frames in exe_frames.items(): + addr[a] = [names.get(f, f) for f in frames] + return cases, meta, addr, stacks, samples, allocs, live + + +def classify(stack, addr, exe_addrs): + """(owner, phase, allocator caller owner or None, inclusive owner set).""" + frames = [] # (name, in_exe) + for i, a in enumerate(stack): + names = addr.get(a, ["?"]) + if i == 1 and len(frames) and a in exe_addrs and addr.get(stack[0]) == names: + continue # the link register pointing into pc's own function + frames.extend((n, a in exe_addrs) for n in names) + owner, alloc_owner, in_alloc, leaf = None, None, False, None + inclusive = set() + for name, in_exe in frames: + if not in_exe: + if owner is None and ALLOCATOR.match(name): + in_alloc = True + continue + if re.search(r"layout_text_cost::probe|__rust_alloc|__rust_dealloc|__rust_realloc|__rdl_|__rg_", name): + continue + crate = crate_of(name) + if crate in TRANSPARENT: + # Dropping or cloning a container of another crate's values is that crate's. + m = re.search(r"drop|clone", name) and OWNED.search(name) + if not m: + continue + crate = m.group(1) + o = owner_of_crate(crate, name) + family = o.split(" ")[0] + if family in ("Taffy", "Parley", "Fontique", "Swash"): + inclusive.add("Parley+fonts" if family in ("Parley", "Fontique", "Swash") else family) + if owner is None: + owner, leaf = o, name + phase = "other" + for name, _ in frames: + hit = next((p for p, rx in PHASES if rx.search(name)), None) + if hit: + phase = hit + break + if owner is None: + owner = "System" if frames and not frames[0][1] else "Unknown" + if owner == "Parley": + owner = next((part for part, rx in PARLEY_PARTS if any(rx.search(n) for n, e in frames if e)), "Parley layout building") + if in_alloc: + alloc_owner, owner = owner, "Allocator" + return owner, phase, alloc_owner, inclusive, leaf or (frames[0][0] if frames else "?") + + +def report(dump, syms, top): + cases, meta, addr, stacks, samples, allocs, live = load(dump, syms) + exe_addrs = set() + for line in open(syms): + if line.startswith("SYM "): + exe_addrs.add(line.split(" ", 2)[1]) + cache = {} + + def cls(sid): + if sid not in cache: + cache[sid] = classify(stacks[sid], addr, exe_addrs) + return cache[sid] + + for kind, rows in (("SAMPLES", samples), ("ALLOCS", allocs), ("LIVE", live)): + if not rows: + continue + for tag, name in sorted(cases.items()): + mine = [r for r in rows if r[0] == tag] + if not mine: + continue + total = sum(r[2] for r in mine) + total_b = sum(r[3] for r in mine) + by_owner = collections.Counter() + by_owner_b = collections.Counter() + by_phase = collections.Counter() + by_alloc = collections.Counter() + incl = collections.Counter() + funcs = collections.defaultdict(collections.Counter) + funcs_b = collections.defaultdict(collections.Counter) + for _, sid, n, b in mine: + owner, phase, alloc_owner, inclusive, leaf = cls(sid) + by_owner[owner] += n + by_owner_b[owner] += b + by_phase[(owner if not owner.startswith("Rune") else "Rune", phase)] += n + if alloc_owner: + by_alloc[alloc_owner] += n + for o in inclusive: + incl[o] += n + funcs[owner][leaf[:140]] += n + funcs_b[owner][leaf[:140]] += b + print(f"\n== {kind} case={name} total={total}" + (f" bytes={total_b}" if kind != "SAMPLES" else "")) + for o, n in by_owner.most_common(): + extra = f" bytes {by_owner_b[o]:>12} {100 * by_owner_b[o] / max(total_b, 1):5.1f}%" if kind != "SAMPLES" else "" + print(f" {o:<34} {n:>9} {100 * n / total:5.1f}%{extra}") + if kind == "SAMPLES": + print(" -- inclusive (any frame on the stack)") + for o, n in incl.most_common(): + print(f" {o:<31} {100 * n / total:5.1f}%") + print(" -- by runtime phase (Rune = Rune's own code)") + for (o, ph), n in sorted(by_phase.items(), key=lambda kv: -kv[1])[:24]: + print(f" {o:<31} {ph:<16} {100 * n / total:5.1f}%") + if by_alloc: + print(" -- allocator time by caller") + for o, n in by_alloc.most_common(): + print(f" {o:<31} {100 * n / total:5.1f}%") + for o, _ in by_owner.most_common(6): + print(f" -- top in {o}") + for f, n in funcs[o].most_common(top): + extra = f" bytes {100 * funcs_b[o][f] / max(total_b, 1):5.1f}%" if kind != "SAMPLES" else "" + print(f" {100 * n / total:5.1f}%{extra} {f}") + for m in meta: + print("META", " ".join(f"{k}={v}" for k, v in m.items())) + + +if __name__ == "__main__": + a = sys.argv[1:] + if a and a[0] == "symbolize": + symbolize(a[1], a[a.index("--exe") + 1]) + elif a and a[0] == "report": + report(a[1], a[2], int(a[a.index("--top") + 1]) if "--top" in a else 12) + else: + sys.exit(__doc__) diff --git a/app/vendor/rune/scripts/file-size-exceptions.txt b/app/vendor/rune/scripts/file-size-exceptions.txt new file mode 100644 index 0000000..639b233 --- /dev/null +++ b/app/vendor/rune/scripts/file-size-exceptions.txt @@ -0,0 +1,2 @@ +# <path> <ceiling>: non-test line ceilings for files above 1500. Ceilings only go down. +# Refresh with scripts/file-size.sh --update-exceptions. diff --git a/app/vendor/rune/scripts/file-size.sh b/app/vendor/rune/scripts/file-size.sh new file mode 100644 index 0000000..68a4fd5 --- /dev/null +++ b/app/vendor/rune/scripts/file-size.sh @@ -0,0 +1,141 @@ +#!/usr/bin/env bash +# Checks Rust file sizes. Counts non-test lines per tracked .rs file under crates/ and examples/ +# (inline #[cfg(test)] items are excluded; test-only files are measured separately). +# warn > 800 non-test lines error > 1500 non-test lines unless listed in +# warn > 1000 lines in a test file or inline test module scripts/file-size-exceptions.txt ("<path> <ceiling>") +# Also runs scripts/folder-shape.sh (prefix families and folder breadth); its errors and warnings are +# added to the summary line, and --update-exceptions refreshes both exception lists. +# Usage: scripts/file-size.sh [--warn-only] [--update-exceptions [--allow-raise]] +set -euo pipefail +cd "$(git rev-parse --show-toplevel)" + +SOFT=800 HARD=1500 TESTCAP=1000 +EXC=scripts/file-size-exceptions.txt +warn_only=0 update=0 raise=0 +for a in "$@"; do + case "$a" in + --warn-only) warn_only=1 ;; + --update-exceptions) update=1 ;; + --allow-raise) raise=1 ;; + *) echo "unknown option: $a" >&2; exit 2 ;; + esac +done + +measure() { + git ls-files -z 'crates/*.rs' 'examples/*.rs' | xargs -0 awk ' + function reset() { prod = 0; test = 0; st = 0; depth = 0; maxtest = 0; cur = 0 } + function braces(s, t, o, c) { + gsub(/\\./, "", s); gsub(/"[^"]*"/, "", s); gsub(/\047.\047/, "", s) + sub(/\/\/.*/, "", s) + t = s; o = gsub(/\{/, "", t); t = s; c = gsub(/\}/, "", t) + return o - c + } + function flush() { + if (name != "") { + if (cur > maxtest) maxtest = cur + printf "%s %d %d %d\n", name, prod, test, maxtest + } + } + FNR == 1 { flush(); reset(); name = FILENAME + testfile = (FILENAME ~ /(^|\/)tests?\.rs$/ || FILENAME ~ /_tests\.rs$/ || FILENAME ~ /(^|\/)tests\//) } + { + if (testfile) { test++; cur++; next } + if (st == 0) { + if ($0 ~ /^[ \t]*#\[cfg\(test\)\]/) { st = 1; cur = 1; test++; next } + prod++; next + } + test++; cur++ + if (st == 1) { # attribute seen, find the item head + if ($0 ~ /^[ \t]*#\[/) next + d = braces($0) + if (d > 0 || $0 ~ /\{/) { depth = d; st = (depth > 0) ? 2 : 0 } + else if ($0 ~ /;[ \t]*$/) st = 0 + if (st == 0) { if (cur > maxtest) maxtest = cur; cur = 0 } + next + } + depth += braces($0) + if (depth <= 0) { st = 0; if (cur > maxtest) maxtest = cur; cur = 0 } + } + END { flush() }' +} + +rows=$(measure) +ceil_of() { [ -f "$EXC" ] && awk -v p="$1" '$1 == p { print $2; exit }' "$EXC" || true; } + +errors=0 warns=0 oversoft=0 overhard=0 +out=$(mktemp); trap 'rm -f "$out"' EXIT +ann() { [ "${GITHUB_ACTIONS:-}" = true ] && echo "::$1 file=$2::$3" || true; } + +while read -r p prod test maxtest; do + if [ "$prod" -eq 0 ] && [ "$test" -gt 0 ] && [ "$maxtest" -eq "$test" ] && [ "$test" -gt "$TESTCAP" ]; then + # test-only file + warns=$((warns + 1)) + printf '%6d %-6s %s\n' "$test" "tests" "$p" >> "$out" + ann warning "$p" "test file has $test lines (limit $TESTCAP)" + continue + fi + if [ "$maxtest" -gt "$TESTCAP" ]; then + warns=$((warns + 1)) + printf '%6d %-6s %s\n' "$maxtest" "tests" "$p" >> "$out" + ann warning "$p" "inline test module has $maxtest lines (limit $TESTCAP)" + fi + [ "$prod" -gt "$SOFT" ] || continue + oversoft=$((oversoft + 1)) + if [ "$prod" -gt "$HARD" ]; then + overhard=$((overhard + 1)) + limit=$(ceil_of "$p"); limit=${limit:-$HARD} + if [ "$prod" -gt "$limit" ]; then + errors=$((errors + 1)) + printf '%6d %-6s %s (limit %d)\n' "$prod" "ERROR" "$p" "$limit" >> "$out" + ann error "$p" "$prod non-test lines, limit $limit; split a module out before adding more" + else + warns=$((warns + 1)) + printf '%6d %-6s %s (exception, ceiling %d)\n' "$prod" "warn" "$p" "$limit" >> "$out" + ann warning "$p" "$prod non-test lines (exception ceiling $limit, soft limit $SOFT)" + fi + else + warns=$((warns + 1)) + printf '%6d %-6s %s\n' "$prod" "warn" "$p" >> "$out" + ann warning "$p" "$prod non-test lines (soft limit $SOFT)" + fi +done <<< "$rows" + +sort -rn "$out" +shape_args=() +[ "$update" -eq 1 ] && shape_args+=(--update-exceptions) +[ "$raise" -eq 1 ] && shape_args+=(--allow-raise) +shape_out=$(bash scripts/folder-shape.sh ${shape_args[@]+"${shape_args[@]}"} --warn-only) +if [ "$update" -eq 0 ]; then + printf '%s\n' "$shape_out" + shape_sum=$(printf '%s\n' "$shape_out" | tail -1) + errors=$((errors + $(sed -n 's/.*errors: \([0-9]*\),.*/\1/p' <<< "$shape_sum"))) + warns=$((warns + $(sed -n 's/.*warnings: \([0-9]*\)$/\1/p' <<< "$shape_sum"))) +else + printf '%s\n' "$shape_out" +fi +echo "over $SOFT: $oversoft, over $HARD: $overhard, errors: $errors, warnings: $warns" + +if [ "$update" -eq 1 ]; then + tmp=$(mktemp) + { + echo "# <path> <ceiling>: non-test line ceilings for files above $HARD. Ceilings only go down." + echo "# Refresh with scripts/file-size.sh --update-exceptions." + while read -r p prod _ _; do + [ "$prod" -gt "$HARD" ] || continue + old=$(ceil_of "$p") + if [ -z "$old" ]; then + if [ "$raise" -eq 1 ]; then echo "$p $prod"; else echo "not listing new oversized file $p ($prod); use --allow-raise" >&2; fi + elif [ "$prod" -gt "$old" ] && [ "$raise" -eq 0 ]; then + echo "$p $old" + else + echo "$p $prod" + fi + done <<< "$rows" | sort + } > "$tmp" + mv "$tmp" "$EXC" + echo "wrote $EXC ($(grep -vc '^#' "$EXC") entries)" + exit 0 +fi + +[ "$warn_only" -eq 1 ] && exit 0 +[ "$errors" -eq 0 ] diff --git a/app/vendor/rune/scripts/folder-shape-exceptions.txt b/app/vendor/rune/scripts/folder-shape-exceptions.txt new file mode 100644 index 0000000..8bede2d --- /dev/null +++ b/app/vendor/rune/scripts/folder-shape-exceptions.txt @@ -0,0 +1,2 @@ +# <key> <ceiling>: existing folder-shape violations (see scripts/folder-shape.sh). Ceilings only go down. +# Refresh with scripts/folder-shape.sh --update-exceptions. diff --git a/app/vendor/rune/scripts/folder-shape.sh b/app/vendor/rune/scripts/folder-shape.sh new file mode 100644 index 0000000..95c9c08 --- /dev/null +++ b/app/vendor/rune/scripts/folder-shape.sh @@ -0,0 +1,182 @@ +#!/usr/bin/env bash +# Checks folder shape for tracked source files under crates/ and examples/. +# prefix family x.rs or x/ plus 2+ x_*.rs siblings, or 3+ x_*.rs alone: error, "move into x/" +# folder breadth > 40 non-test source files in one folder: warn; > 60: error +# Files directly in examples/, benches/ and bin/ are skipped (each is its own program). +# Test files (*_tests.rs, *_test.rs, tests.rs, *.test.ts, ...) are not counted. The prefix is the stem +# up to the first "_" or "-". Existing violations are listed in scripts/folder-shape-exceptions.txt +# ("<key> [ceiling]", key is "<dir>/<prefix>_*" or "<dir>/"; the ceiling is optional); ceilings only go down. +# Usage: scripts/folder-shape.sh [--warn-only] [--update-exceptions [--allow-raise]] +set -euo pipefail +cd "$(git rev-parse --show-toplevel)" + +WARN=40 HARD=60 FAM=3 +EXC=scripts/folder-shape-exceptions.txt +warn_only=0 update=0 raise=0 +for a in "$@"; do + case "$a" in + --warn-only) warn_only=1 ;; + --update-exceptions) update=1 ;; + --allow-raise) raise=1 ;; + *) echo "unknown option: $a" >&2; exit 1 ;; + esac +done + +found=$( + git ls-files crates examples | awk -v warn="$WARN" -v fam="$FAM" ' + BEGIN { + src[".rs"] = 1; src[".ts"] = 1; src[".tsx"] = 1; src[".swift"] = 1 + prog["examples"] = 1; prog["benches"] = 1; prog["bin"] = 1 + } + { + sub(/\r$/, "") + if ($0 == "") next + slash = 0 + for (i = length($0); i >= 1; i--) { + if (substr($0, i, 1) == "/") { slash = i; break } + } + if (slash > 0) { + d = substr($0, 1, slash - 1) + name = substr($0, slash + 1) + } else { + d = "" + name = $0 + } + nparts = split(d, parts, "/") + if (nparts >= 3) { + parent = parts[1] "/" parts[2] + for (i = 3; i <= nparts; i++) { + has_sub[parent SUBSEP parts[i]] = 1 + dirs[parent] = 1 + parent = parent "/" parts[i] + } + } + if (nparts > 0 && (parts[nparts] in prog)) next + dot = 0 + for (i = length(name); i >= 1; i--) { + if (substr(name, i, 1) == ".") { dot = i; break } + } + if (dot > 1 && substr(name, 1, dot - 1) !~ /^\.+$/) { + stem = substr(name, 1, dot - 1) + ext = substr(name, dot) + } else { + stem = name + ext = "" + } + if (!(ext in src)) next + if (stem ~ /(^|[_.-])tests?$/) next + if (index("/" d "/", "/tests/") > 0) next + + dirs[d] = 1 + dir_count[d]++ + has_stem[d SUBSEP stem] = 1 + if (match(stem, /^[^_-]+[_-]/)) { + p = substr(stem, 1, RLENGTH - 1) + if (!((d SUBSEP p) in fam_count)) { + fam_n[d]++ + fam_list[d SUBSEP fam_n[d]] = p + } + fam_count[d SUBSEP p]++ + } + } + END { + for (d in dirs) { + m = fam_n[d] + 0 + for (i = 1; i <= m; i++) { + p = fam_list[d SUBSEP i] + base = ((d SUBSEP p) in has_stem) || ((d SUBSEP p) in has_sub) + limit = base ? 2 : fam + cnt = fam_count[d SUBSEP p] + if (cnt >= limit) { + printf "%s/%s_*\t%d\tmove into %s/\n", d, p, cnt, p + } + } + if (dir_count[d] + 0 > warn) { + printf "%s/\t%d\tgroup into capability subfolders\n", d, dir_count[d] + } + } + } + ' | LC_ALL=C sort -t $'\t' -k1,1 +) + +ceil_of() { + [ -f "$EXC" ] || return 0 + awk -v k="$1" ' + { sub(/\r$/, "") } + /^#/ || NF == 0 { next } + $1 == k { val = (NF > 1 ? $2 : 1000000000); seen = 1 } + END { if (seen) print val } + ' "$EXC" +} + +if [ "$update" -eq 1 ]; then + tmp=$(mktemp) + trap 'rm -f "$tmp"' EXIT + { + echo "# <key> <ceiling>: existing folder-shape violations (see scripts/folder-shape.sh). Ceilings only go down." + echo "# Refresh with scripts/folder-shape.sh --update-exceptions." + if [ -n "$found" ]; then + while IFS=$'\t' read -r k n _; do + case "$k" in + *_\*) ;; + *) [ "$n" -gt "$HARD" ] || continue ;; + esac + old=$(ceil_of "$k") + if [ -z "$old" ]; then + if [ "$raise" -eq 1 ]; then + echo "$k $n" + else + echo "not listing new violation $k ($n); use --allow-raise" >&2 + fi + elif [ "$n" -le "$old" ] || [ "$raise" -eq 1 ]; then + echo "$k $n" + else + echo "$k $old" + fi + done <<< "$found" + fi + } > "$tmp" + mv "$tmp" "$EXC" + trap - EXIT + entries=$(awk '/^#/ || NF == 0 { next } { c++ } END { print c + 0 }' "$EXC") + echo "wrote $EXC ($entries entries)" + exit 0 +fi + +errors=0 warns=0 families=0 over_warn=0 +rows=$(mktemp) +trap 'rm -f "$rows"' EXIT +if [ -n "$found" ]; then + while IFS=$'\t' read -r k n hint; do + case "$k" in + *_\*) fam=1; families=$((families + 1)) ;; + *) fam=0; over_warn=$((over_warn + 1)) ;; + esac + if [ "$fam" -eq 1 ] || [ "$n" -gt "$HARD" ]; then + limit=$(ceil_of "$k") + if [ -n "$limit" ] && [ "$n" -le "$limit" ]; then + warns=$((warns + 1)) + printf '%6d warn %s (%s; exception, ceiling %d)\n' "$n" "$k" "$hint" "$limit" >> "$rows" + else + errors=$((errors + 1)) + if [ -n "$limit" ]; then + printf '%6d ERROR %s (%s; limit %d)\n' "$n" "$k" "$hint" "$limit" >> "$rows" + else + printf '%6d ERROR %s (%s)\n' "$n" "$k" "$hint" >> "$rows" + fi + if [ "${GITHUB_ACTIONS:-}" = true ]; then + printf '::error file=%s::%d files: %s\n' "$k" "$n" "$hint" + fi + fi + else + warns=$((warns + 1)) + printf '%6d warn %s (%s, soft limit %d)\n' "$n" "$k" "$hint" "$WARN" >> "$rows" + fi + done <<< "$found" +fi + +if [ -s "$rows" ]; then + cat "$rows" +fi +echo "folder shape: families: $families, folders over $WARN: $over_warn, errors: $errors, warnings: $warns" +[ "$warn_only" -eq 1 ] || [ "$errors" -eq 0 ] diff --git a/app/vendor/rune/scripts/global-shortcut.json b/app/vendor/rune/scripts/global-shortcut.json new file mode 100644 index 0000000..508f838 --- /dev/null +++ b/app/vendor/rune/scripts/global-shortcut.json @@ -0,0 +1 @@ +[{"shortcut":"cmd+ctrl+alt+shift+k"}] diff --git a/app/vendor/rune/scripts/kit-diff.py b/app/vendor/rune/scripts/kit-diff.py new file mode 100644 index 0000000..6ef6f1e --- /dev/null +++ b/app/vendor/rune/scripts/kit-diff.py @@ -0,0 +1,147 @@ +#!/usr/bin/env -S uv run --script +# /// script +# requires-python = ">=3.11" +# dependencies = ["pillow>=10", "numpy>=1.26"] +# /// +"""Diffs rune-kit's gallery against @opencode/ui's Storybook, story by story. + +usage: + OPENCODE=<opencode checkout> scripts/kit-diff.py [--out perf/kit-diff] [--only button,switch] + [--schemes light,dark] [--no-build] + +Needs: `bun install` and `bun run --cwd packages/storybook build` in the OpenCode checkout +(Playwright's Chromium comes from that checkout), and a GPU or lavapipe for Rune +(VK_ICD_FILENAMES=/usr/share/vulkan/icd.d/lvp_icd.json on a headless Linux box). + +For every story in STORIES and each scheme it renders the web story in headless Chromium at +2x (viewport fitted to the story), renders the gallery scene of the same id at the same size, +and writes web.png, rune.png, diff.png (amplified |web - rune|) and side.png (web | rune | +diff) per story, plus report.json and report.md with two numbers per story: + + similarity 100 * (1 - mean |web - rune| / 255) over RGB; 100 is identical + off % of pixels whose largest channel differs by more than 24/255 (visible) +""" + +import argparse +import json +import os +import subprocess +import sys +from pathlib import Path + +import numpy as np +from PIL import Image + +ROOT = Path(__file__).resolve().parent.parent + +# Every gallery scene is diffed against the Storybook story of the same id. Per-story options: +# width (viewport points, default 720) and actions run before the web shot (click/hover/focus a +# selector) to reach the state the Rune scene starts in. +MENU = {"actions": [{"click": "#storybook-root button"}]} +OPTIONS: dict[str, dict] = { + "ui-dialog--basic": {"height": 480}, + "ui-menu--basic": MENU, + "ui-menu--rich": MENU, + "ui-menu--with-checkbox": MENU, + "ui-menu--with-radio": MENU, + "ui-menu--with-submenu": MENU, + "ui-select--playground": {"actions": [{"click": "[data-component=select-v2]"}]}, + "ui-select--grouped": {"actions": [{"click": "[data-component=select-v2]"}]}, + "components-hover-card--basic": {"actions": [{"hover": "[data-slot=hover-card-trigger]", "wait": 1200}]}, + "ui-tooltip--simple": {"actions": [{"hover": "[data-component=tooltip-v2-trigger]", "wait": 900}]}, + "ui-tooltip--with-keybind": {"actions": [{"hover": "[data-component=tooltip-v2-trigger]", "wait": 900}]}, + "ui-tooltip--path": {"actions": [{"hover": "[data-component=tooltip-v2-trigger]", "wait": 900}]}, + "ui-tooltip--title-description": {"actions": [{"hover": "[data-component=tooltip-v2-trigger]", "wait": 900}]}, + "ui-toast--all-examples": {"actions": [{"click": "#storybook-root button", "wait": 900}], "height": 480}, +} + + +def sh(cmd, **kw): + return subprocess.run(cmd, check=True, **kw) + + +def load(p: Path) -> np.ndarray: + return np.asarray(Image.open(p).convert("RGB")).astype(np.int16) + + +def compare(web: Path, rune: Path, out: Path) -> dict: + a, b = load(web), load(rune) + h, w = min(a.shape[0], b.shape[0]), min(a.shape[1], b.shape[1]) + a, b = a[:h, :w], b[:h, :w] + d = np.abs(a - b) + similarity = 100.0 * (1.0 - d.mean() / 255.0) + off = 100.0 * float((d.max(axis=2) > 24).mean()) + heat = np.clip(d.max(axis=2) * 4, 0, 255).astype(np.uint8) + diff = np.stack([heat, np.zeros_like(heat), np.zeros_like(heat)], axis=2) + base = (0.25 * a.mean(axis=2, keepdims=True)).astype(np.uint8) + diff = np.maximum(diff, np.repeat(base, 3, axis=2)) + Image.fromarray(diff).save(out / "diff.png") + gap = 8 + side = np.full((h, w * 3 + gap * 2, 3), 128, np.uint8) + side[:, :w] = a.astype(np.uint8) + side[:, w + gap : 2 * w + gap] = b.astype(np.uint8) + side[:, 2 * (w + gap) :] = diff + Image.fromarray(side).save(out / "side.png") + return {"similarity": round(similarity, 3), "off": round(off, 3)} + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--out", default=str(ROOT / "perf/kit-diff")) + ap.add_argument("--only", default="") + ap.add_argument("--schemes", default="light,dark") + ap.add_argument("--no-build", action="store_true") + ap.add_argument("--scale", type=float, default=2.0) + args = ap.parse_args() + out = Path(args.out) + out.mkdir(parents=True, exist_ok=True) + os.environ.setdefault("OPENCODE", str(ROOT.parent / "opencode")) + + if not args.no_build: + sh(["cargo", "build", "--release", "-q", "-p", "kit-gallery"], cwd=ROOT) + gallery = ROOT / "target/release/kit-gallery" + scenes = set(subprocess.run([gallery, "--list-scenes"], capture_output=True, text=True, check=True).stdout.split()) + + only = [s for s in args.only.split(",") if s] + ids = [i for i in sorted(scenes) if "--" in i and (not only or any(o in i for o in only))] + schemes = args.schemes.split(",") + + jobs = [] + for i in ids: + for sc in schemes: + d = out / i / sc + d.mkdir(parents=True, exist_ok=True) + o = OPTIONS.get(i, {}) + jobs.append({"id": i, "scheme": sc, "width": o.get("width", 720), "out": str(d / "web.png"), + "actions": o.get("actions", []), "scale": args.scale, **({"height": o["height"]} if "height" in o else {})}) + shots = subprocess.run(["node", str(ROOT / "scripts/kit/shots.mjs")], input=json.dumps(jobs), capture_output=True, + text=True, cwd=ROOT) + if shots.returncode != 0: + sys.exit(shots.stderr) + sizes = {(r["id"], r["scheme"]): (r["width"], r["height"]) for r in json.loads(shots.stdout)} + + env = dict(os.environ) + if sys.platform.startswith("linux") and Path("/usr/share/vulkan/icd.d/lvp_icd.json").exists(): + env.setdefault("VK_ICD_FILENAMES", "/usr/share/vulkan/icd.d/lvp_icd.json") + report = [] + for i in ids: + for sc in schemes: + d = out / i / sc + w, h = sizes[(i, sc)] + subprocess.run([gallery, "--scene", i, "--snap", d / "rune.png", "--theme", sc, "--size", f"{w}x{h}", + "--scale", str(args.scale)], check=True, env=env, capture_output=True) + r = {"id": i, "scheme": sc, "size": [w, h], **compare(d / "web.png", d / "rune.png", d)} + report.append(r) + print(f"{i:52} {sc:5} similarity {r['similarity']:7.3f} off {r['off']:6.2f}%") + + (out / "report.json").write_text(json.dumps(report, indent=1)) + lines = ["| story | scheme | similarity | off (% px) |", "|---|---|---:|---:|"] + lines += [f"| {r['id']} | {r['scheme']} | {r['similarity']:.2f} | {r['off']:.2f} |" for r in report] + mean = sum(r["similarity"] for r in report) / max(len(report), 1) + lines.append(f"\nmean similarity {mean:.2f} over {len(report)} renders") + (out / "report.md").write_text("\n".join(lines) + "\n") + print(f"mean similarity {mean:.3f} over {len(report)} renders -> {out}/report.md") + + +if __name__ == "__main__": + main() diff --git a/app/vendor/rune/scripts/kit/rects.mjs b/app/vendor/rune/scripts/kit/rects.mjs new file mode 100644 index 0000000..8800081 --- /dev/null +++ b/app/vendor/rune/scripts/kit/rects.mjs @@ -0,0 +1,28 @@ +// Prints the layout rects (points) of a story's slotted elements, for matching Rune layouts. +// usage: node scripts/kit/rects.mjs <story-id> [light|dark] [click-selector] +import { openStory, playwright, serve } from "./storybook.mjs" + +const [id, scheme = "light", click] = process.argv.slice(2) +const server = await serve() +const browser = await playwright().chromium.launch() +const page = await browser.newPage({ viewport: { width: 720, height: 900 } }) +await openStory(page, server.url, id, scheme) +if (click) { + await page.locator(click).first().click() + await page.waitForTimeout(500) +} +const rows = await page.evaluate(() => { + const out = [] + for (const el of document.querySelectorAll("[data-component], [data-slot], [role], button, input, label, span, svg")) { + const r = el.getBoundingClientRect() + if (!r.width || !r.height) continue + const cs = getComputedStyle(el) + const name = el.getAttribute("data-component") ?? el.getAttribute("data-slot") ?? el.getAttribute("role") ?? el.tagName.toLowerCase() + const t = el.children.length === 0 ? (el.textContent ?? "").trim().slice(0, 24) : "" + out.push(`${name.padEnd(32)} ${[r.x, r.y, r.width, r.height].map((v) => v.toFixed(2).padStart(8)).join(" ")} ${cs.fontSize}/${cs.lineHeight} ${cs.fontWeight} ${t}`) + } + return out +}) +console.log(rows.join("\n")) +await browser.close() +server.close() diff --git a/app/vendor/rune/scripts/kit/shots.mjs b/app/vendor/rune/scripts/kit/shots.mjs new file mode 100644 index 0000000..05ce192 --- /dev/null +++ b/app/vendor/rune/scripts/kit/shots.mjs @@ -0,0 +1,61 @@ +// Renders Storybook stories to PNG in headless Chromium, for scripts/kit-diff.py. +// +// stdin: JSON [{ id, scheme, width, height?, out, actions? }] +// actions: [{ click | hover | focus: selector, nth?: n }] run before the shot. +// Without `height`, the viewport is fitted to the story (frame padding included). +// stdout: JSON [{ id, scheme, width, height }] + +import fs from "node:fs" +import { openStory, playwright, serve } from "./storybook.mjs" + +const jobs = JSON.parse(fs.readFileSync(0, "utf8")) +const server = await serve() +const browser = await playwright().chromium.launch() +const results = [] +for (const job of jobs) { + const page = await browser.newPage({ viewport: { width: job.width, height: 1600 }, deviceScaleFactor: job.scale ?? 2 }) + await page.emulateMedia({ reducedMotion: "reduce" }) + await openStory(page, server.url, job.id, job.scheme) + for (const a of job.actions ?? []) { + const [kind, selector] = Object.entries(a).find(([k]) => ["click", "hover", "focus", "press"].includes(k)) + const loc = page.locator(selector).nth(a.nth ?? 0) + try { + if (kind === "click") await loc.click({ timeout: 5000 }) + if (kind === "hover") await loc.hover({ timeout: 5000 }) + if (kind === "focus") await loc.focus({ timeout: 5000 }) + if (kind === "press") await page.keyboard.press(selector) + } catch (e) { + process.stderr.write(`${job.id}: ${kind} ${selector} failed: ${e.message.split("\n")[0]}\n`) + } + await page.waitForTimeout(a.wait ?? 400) + } + // Pause every animation at its end so overlays are fully in. + await page.evaluate(() => { + for (const a of document.getAnimations()) { + try { + const t = a.effect?.getComputedTiming() + if (t && Number.isFinite(t.endTime)) a.currentTime = t.endTime + else a.currentTime = 0 + a.pause() + } catch {} + } + }) + const height = + job.height ?? + (await page.evaluate(() => { + const frame = document.querySelector("#storybook-root > div") + let bottom = 0 + for (const el of frame?.children ?? []) bottom = Math.max(bottom, el.getBoundingClientRect().bottom) + for (const el of document.querySelectorAll("[data-popper-positioner], [role=dialog], [role=tooltip], .toast-v2-region")) + bottom = Math.max(bottom, el.getBoundingClientRect().bottom) + return Math.ceil(bottom + 24) + })) + await page.setViewportSize({ width: job.width, height }) + await page.waitForTimeout(100) + await page.screenshot({ path: job.out }) + results.push({ id: job.id, scheme: job.scheme, width: job.width, height }) + await page.close() +} +await browser.close() +server.close() +process.stdout.write(JSON.stringify(results)) diff --git a/app/vendor/rune/scripts/kit/storybook.mjs b/app/vendor/rune/scripts/kit/storybook.mjs new file mode 100644 index 0000000..f3bc66b --- /dev/null +++ b/app/vendor/rune/scripts/kit/storybook.mjs @@ -0,0 +1,62 @@ +// Shared helpers for the kit scripts: serve a static Storybook build and open stories in +// headless Chromium through the OpenCode checkout's own Playwright. +// +// OPENCODE (env) points at an opencode checkout with `bun install` done and +// `packages/storybook/storybook-static` built (`bun run --cwd packages/storybook build`). + +import fs from "node:fs" +import http from "node:http" +import path from "node:path" +import { createRequire } from "node:module" + +export const opencode = process.env.OPENCODE ?? path.resolve(import.meta.dirname, "../../../opencode") +const storybookPkg = path.join(opencode, "packages/storybook/package.json") +export const staticDir = process.env.STORYBOOK_STATIC ?? path.join(opencode, "packages/storybook/storybook-static") + +const types = { + ".html": "text/html", + ".js": "text/javascript", + ".mjs": "text/javascript", + ".css": "text/css", + ".json": "application/json", + ".svg": "image/svg+xml", + ".woff2": "font/woff2", + ".woff": "font/woff", + ".ttf": "font/ttf", + ".png": "image/png", +} + +export async function serve() { + if (!fs.existsSync(path.join(staticDir, "iframe.html"))) { + throw new Error(`no Storybook build at ${staticDir}; run \`bun run --cwd packages/storybook build\` in ${opencode}`) + } + const server = http.createServer((req, res) => { + const url = decodeURIComponent(req.url.split("?")[0]) + const file = path.join(staticDir, url === "/" ? "index.html" : url) + if (!file.startsWith(staticDir) || !fs.existsSync(file) || fs.statSync(file).isDirectory()) { + res.statusCode = 404 + return res.end() + } + res.setHeader("content-type", types[path.extname(file)] ?? "application/octet-stream") + fs.createReadStream(file).pipe(res) + }) + await new Promise((ok) => server.listen(0, "127.0.0.1", ok)) + return { url: `http://127.0.0.1:${server.address().port}`, close: () => server.close() } +} + +export function playwright() { + return createRequire(storybookPkg)("@playwright/test") +} + +/** Open a story with the given scheme; the decorator's padding stays, Storybook's own body padding goes. */ +export async function openStory(page, base, id, scheme) { + await page.goto(`${base}/iframe.html?id=${id}&viewMode=story&globals=theme:${scheme}`) + await page.waitForSelector("#storybook-root > *", { timeout: 15000 }) + await page.addStyleTag({ + content: `body.sb-main-padded, body { padding: 0 !important; margin: 0 !important; } + html, body { background: var(--background-base) !important; } + *, *::before, *::after { transition: none !important; animation-play-state: paused !important; caret-color: transparent !important; }`, + }) + await page.evaluate(() => document.fonts.ready) + await page.waitForTimeout(250) +} diff --git a/app/vendor/rune/scripts/mac-app b/app/vendor/rune/scripts/mac-app new file mode 100644 index 0000000..89e4fa1 --- /dev/null +++ b/app/vendor/rune/scripts/mac-app @@ -0,0 +1,6 @@ +#!/usr/bin/env bash +# Stage, sign, atomically exchange and check the replacement's Rune ready receipt. +# --help lists the existing bundle flags; --no-rune-ready supports older binaries. +# All installers use flock on Applications/.NAME.app.install.lock (see mac-app.md). +set -euo pipefail +exec python3 "$(dirname "$0")/mac_app_install.py" "$@" diff --git a/app/vendor/rune/scripts/mac-app.md b/app/vendor/rune/scripts/mac-app.md new file mode 100644 index 0000000..bee9ba3 --- /dev/null +++ b/app/vendor/rune/scripts/mac-app.md @@ -0,0 +1,52 @@ +# Installing a Rune app + +`scripts/mac-app --name Demo --id com.example.demo --exe demo --bin target/release/demo` +stages and signs a bundle beside its destination, asks the running app to quit, +atomically exchanges the bundles, then launches the replacement. `--icon`, +`--scheme`, `--mic`, `--wait-idle SECONDS`, `MAC_APP_SIGN`, and arguments after `--` +work as before. Launches are normal, not occluded: an occluded first frame can +prevent Rune from reaching readiness. + +Use `--bundle path/to/Demo.app` instead of `--bin` to install an already signed +bundle. `--only-relaunch` updates a closed app without opening it. When no explicit +app arguments are supplied, running instances' exact arguments are preserved. +`--stamp PATH --revision REV` publishes a revision stamp under the install lock +only after success. These options also serve remote updaters; transfer each bundle +to its own directory and invoke this installer on the destination machine. + +The replacement must write its Rune ready receipt within 15 seconds. Each launch +gets a unique `RUNE_READY_DIR`; the receipt must identify its PID and bundle ID. +`--no-rune-ready` is only for binaries built before Rune's readiness protocol. +Failed launch or readiness restores the previous bundle with another atomic +exchange and reopens it. If the failed app refuses Cocoa quit, the installed +bundle is still restored, but no overlapping copy is opened. Desktop apps are +never force-quit. + +## Shared install protocol + +Rune and HiveMind land use the same protocol: + +1. Resolve the target path, then take an exclusive POSIX `flock` on the persistent + sibling `.<bundle filename>.install.lock`. Never unlink the lock file. +2. Hold the lock through staging, idle/busy waits, process capture, swap, readiness, + rollback and cleanup. A caller delegating to this installer must not hold the + same lock in its parent process. +3. Stage in a unique sibling `.<bundle filename>.install-*` directory. Existing + bundles are exchanged using `renamex_np(RENAME_SWAP)` on macOS. There is no + remove-then-rename fallback. First installs use a single rename. +4. The staging path now contains the previous bundle. Delete it only after the + replacement is ready or rollback has restored the previous bundle. + +An uncatchable interruption leaves a complete bundle at the live path and the +other complete bundle at the unique staging path. Recovery failures retain that +path and report it. Never sweep these retained backups as part of another install. +The lock is released by the kernel when its owner exits. + +During rollout, let installers using the old protocol finish before admitting +new installs. An already-running old installer cannot be made to honor a new lock. + +Regression tests use fake bundles only: + +```sh +python3 scripts/mac_app_install_tests.py +``` diff --git a/app/vendor/rune/scripts/mac_app_bundle.py b/app/vendor/rune/scripts/mac_app_bundle.py new file mode 100644 index 0000000..f43a509 --- /dev/null +++ b/app/vendor/rune/scripts/mac_app_bundle.py @@ -0,0 +1,91 @@ +"""Atomic bundle transaction. Lock protocol is also used by HiveMind land.""" +import ctypes +import fcntl +import os +from pathlib import Path +import shutil +import signal +import sys +import tempfile + + +def exchange(a, b): + libc = ctypes.CDLL(None, use_errno=True) + if sys.platform == "darwin": + rename = libc.renamex_np + rename.argtypes = [ctypes.c_char_p, ctypes.c_char_p, ctypes.c_uint] + result = rename(os.fsencode(a), os.fsencode(b), 2) # RENAME_SWAP + else: + rename = libc.renameat2 + rename.argtypes = [ctypes.c_int, ctypes.c_char_p, ctypes.c_int, ctypes.c_char_p, ctypes.c_uint] + result = rename(-100, os.fsencode(a), -100, os.fsencode(b), 2) + if result: + error = ctypes.get_errno() + raise OSError(error, os.strerror(error), str(a)) + + +class Bundle: + def __init__(self, live): + self.live = Path(live).resolve() + self.stage = None + self.published = False + self.committed = False + + def __enter__(self): + self.live.parent.mkdir(parents=True, exist_ok=True) + # Persistent inode, POSIX flock, same filename as HiveMind. Never unlink it. + self.lock = (self.live.parent / f".{self.live.name}.install.lock").open("a+b") + try: + fcntl.flock(self.lock, fcntl.LOCK_EX) + self.had_live = self.live.exists() + self.stage = Path(tempfile.mkdtemp(prefix=f".{self.live.name}.install-", dir=self.live.parent)) + except BaseException: + self.lock.close() + raise + return self + + def publish(self): + # Deliver catchable termination only after the in-memory state matches the + # syscall. SIGKILL still leaves both complete bundles on disk. + previous = signal.pthread_sigmask(signal.SIG_BLOCK, {signal.SIGINT, signal.SIGTERM}) + try: + if self.had_live: + exchange(self.stage, self.live) + else: + os.rename(self.stage, self.live) + self.published = True + finally: + signal.pthread_sigmask(signal.SIG_SETMASK, previous) + + def restore(self): + if not self.published: + return + if not self.had_live: + raise RuntimeError("no previous bundle to restore") + exchange(self.stage, self.live) + self.published = False + + def replace(self, stop, launch, stop_replacement): + """Keep the old bundle until launch and readiness succeed.""" + stop() + try: + self.publish() + launch(False) + except BaseException: + try: + stop_replacement() + finally: + # Restore the installed path even if the failed app refuses to quit. + self.restore() + launch(True) + raise + self.committed = True + + def __exit__(self, *_): + try: + if self.published and not self.committed: + print(f"mac-app: previous bundle retained at {self.stage}", file=sys.stderr) + elif self.stage and self.stage.exists(): + shutil.rmtree(self.stage) + finally: + self.lock.close() diff --git a/app/vendor/rune/scripts/mac_app_install.py b/app/vendor/rune/scripts/mac_app_install.py new file mode 100644 index 0000000..583db0c --- /dev/null +++ b/app/vendor/rune/scripts/mac_app_install.py @@ -0,0 +1,231 @@ +"""Build, atomically install and check a Rune app before discarding its old bundle.""" +import argparse +import ctypes +import json +import os +from pathlib import Path +import plistlib +import re +import shutil +import signal +import subprocess +import sys +import tempfile +import time + +from mac_app_bundle import Bundle + + +def command(*args, check=True): + return subprocess.run(args, check=check, capture_output=True, text=True, timeout=10) + + +def running(exe): + result = {} + for line in command("ps", "-axo", "pid=,lstart=,command=").stdout.splitlines(): + parts = line.split(None, 6) + if len(parts) == 7 and (parts[6] == str(exe) or parts[6].startswith(str(exe) + " ")): + result[int(parts[0])] = tuple(parts[1:6]) + return result + + +def parse_argv(data): + argc = int.from_bytes(data[:4], sys.byteorder, signed=True) + if argc <= 0: + raise ValueError("invalid process argument count") + rest = data[4:].split(b"\0", 1)[1].lstrip(b"\0") + args = rest.split(b"\0")[:argc] + if len(args) != argc: + raise ValueError("truncated process arguments") + return [os.fsdecode(arg) for arg in args[1:]] + + +def process_args(pid): + libc = ctypes.CDLL(None, use_errno=True) + mib = (ctypes.c_int * 3)(1, 49, pid) # CTL_KERN, KERN_PROCARGS2 + data = ctypes.create_string_buffer(1024 * 1024) + size = ctypes.c_size_t(len(data)) + if libc.sysctl(mib, 3, data, ctypes.byref(size), None, 0): + raise OSError(ctypes.get_errno(), f"cannot preserve app pid {pid}'s arguments") + return parse_argv(data.raw[:size.value]) + + +def cocoa(pid, action): + script = """ObjC.import('AppKit'); +function run(a) { + const app = $.NSRunningApplication.runningApplicationWithProcessIdentifier(Number(a[0])); + if (!app || app.isNil()) return 'gone'; + return (a[1] === 'quit' ? app.terminate : (!app.terminated && app.finishedLaunching)) ? 'yes' : 'no'; +}""" + return command("osascript", "-l", "JavaScript", "-e", script, str(pid), action).stdout.strip() == "yes" + + +def quit_apps(exe, apps): + for pid, birth in apps.items(): + if running(exe).get(pid) == birth and not cocoa(pid, "quit"): + if running(exe).get(pid) == birth: + raise RuntimeError(f"app pid {pid} declined quit") + deadline = time.monotonic() + 10 + while any(running(exe).get(pid) == birth for pid, birth in apps.items()): + if time.monotonic() >= deadline: + raise RuntimeError("app did not quit within 10s; no forced termination") + time.sleep(0.1) + + +def receipt_ready(directory, bundle_id, pid): + try: + receipt = json.loads((directory / f"{bundle_id}.{pid}").read_text()) + return receipt["pid"] == pid and receipt["bundle_id"] == bundle_id + except (OSError, ValueError, KeyError, TypeError): + return False + + +def launch(live, exe, bundle_id, args, ready_root, require_ready=True): + # A unique directory per launch excludes stale receipts, even after PID reuse. + with tempfile.TemporaryDirectory(prefix="install-", dir=ready_root) as tmp: + directory = Path(tmp) + command("open", "-n", "--env", f"RUNE_READY_DIR={directory}", str(live), "--args", *args) + deadline = time.monotonic() + 15 + while True: + for pid in running(exe): + if (not require_ready or receipt_ready(directory, bundle_id, pid)) and cocoa(pid, "ready"): + return + if time.monotonic() >= deadline: + raise RuntimeError("replacement did not become ready within 15s") + time.sleep(0.1) + + +def wait_idle(bundle_id, seconds): + if seconds is None: + return + while True: + front = command("lsappinfo", "front").stdout.strip() + info = command("lsappinfo", "info", "-only", "bundleid", front, check=False).stdout + if f'"{bundle_id}"' not in info: + return + idle = command("ioreg", "-c", "IOHIDSystem").stdout + match = re.search(r'"HIDIdleTime"\s*=\s*(\d+)', idle) + if match and int(match[1]) / 1_000_000_000 >= seconds: + return + time.sleep(2) + + +def build(stage, args): + if args.bundle: + source = Path(args.bundle) + if not (source / "Contents/MacOS" / args.exe).is_file(): + raise RuntimeError("source bundle has no executable") + shutil.copytree(source, stage, dirs_exist_ok=True, symlinks=True) + return + macos = stage / "Contents/MacOS" + resources = stage / "Contents/Resources" + macos.mkdir(parents=True) + resources.mkdir() + shutil.copy2(args.bin, macos / args.exe) + if args.icon: + shutil.copy2(args.icon, resources / "icon.icns") + plist = dict(CFBundleName=args.name, CFBundleDisplayName=args.name, + CFBundleIdentifier=args.id, CFBundleExecutable=args.exe, + CFBundleIconFile="icon", CFBundlePackageType="APPL", + CFBundleShortVersionString="0.0.1", LSMinimumSystemVersion="13.0", + NSHighResolutionCapable=True) + if args.scheme: + plist["CFBundleURLTypes"] = [dict(CFBundleURLName=args.id, CFBundleURLSchemes=[args.scheme])] + if args.mic: + plist["NSMicrophoneUsageDescription"] = args.mic + with (stage / "Contents/Info.plist").open("wb") as file: + plistlib.dump(plist, file) + identity = os.environ.get("MAC_APP_SIGN") or "-" + if command("codesign", "--force", "--sign", identity, str(stage), check=False).returncode: + if identity == "-": + raise RuntimeError("ad hoc signing failed") + print("mac-app: signing identity failed; signing ad hoc", file=sys.stderr) + command("codesign", "--force", "--sign", "-", str(stage)) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + for name in ("name", "id", "exe"): + parser.add_argument(f"--{name}", required=True) + source = parser.add_mutually_exclusive_group(required=True) + source.add_argument("--bin") + source.add_argument("--bundle", help="install an already signed bundle") + for name in ("icon", "scheme", "mic"): + parser.add_argument(f"--{name}") + parser.add_argument("--wait-idle", type=float) + parser.add_argument("--no-rune-ready", action="store_true", help="for binaries predating Rune readiness") + parser.add_argument("--only-relaunch", action="store_true", help="do not open an app that was not running") + parser.add_argument("--stamp", type=Path) + parser.add_argument("--revision") + parser.add_argument("args", nargs=argparse.REMAINDER) + args = parser.parse_args() + if args.args[:1] == ["--"]: + args.args = args.args[1:] + if args.bin and not os.access(args.bin, os.X_OK): + parser.error(f"no executable binary at {args.bin}") + if bool(args.stamp) != bool(args.revision): + parser.error("--stamp and --revision must be used together") + for name in (args.name, args.exe): + if name in (".", "..") or "/" in name: + parser.error("name and exe must be single path components") + home = Path.home() + live = home / "Applications" / f"{args.name}.app" + exe = live / "Contents/MacOS" / args.exe + ready_root = home / ".local/state/rune/ready" + ready_root.mkdir(parents=True, exist_ok=True) + with Bundle(live) as bundle: + build(bundle.stage, args) + wait_idle(args.id, args.wait_idle) + busy = home / "Library/Caches/mac-app/busy" + deadline = time.monotonic() + 900 + while any((busy / str(pid)).exists() for pid in running(exe)): + if time.monotonic() >= deadline: + raise RuntimeError("app still busy after 15 minutes") + time.sleep(2) + old = running(exe) + launch_args = args.args + if old and not launch_args: + captured = [process_args(pid) for pid in old] + if any(value != captured[0] for value in captured) or running(exe) != old: + raise RuntimeError("running app instances changed or have different arguments") + launch_args = captured[0] + + def start(rollback): + if args.scheme: + command("/System/Library/Frameworks/CoreServices.framework/Frameworks/LaunchServices.framework/Support/lsregister", + "-f", str(live), check=False) + launch(live, exe, args.id, launch_args, ready_root, + require_ready=not (rollback or args.no_rune_ready)) + + if args.only_relaunch and not old: + bundle.publish() + bundle.committed = True + else: + bundle.replace(lambda: quit_apps(exe, old), start, + lambda: quit_apps(exe, running(exe))) + if args.stamp: + stamp = args.stamp.expanduser() + stamp.parent.mkdir(parents=True, exist_ok=True) + with tempfile.NamedTemporaryFile(mode="w", dir=stamp.parent, delete=False) as file: + file.write(args.revision + "\n") + temporary = Path(file.name) + try: + os.replace(temporary, stamp) + finally: + temporary.unlink(missing_ok=True) + print(live) + + +if __name__ == "__main__": + def interrupted(signum, _frame): + # A second termination signal must not interrupt the rollback itself. + signal.signal(signal.SIGTERM, signal.SIG_IGN) + signal.signal(signal.SIGINT, signal.SIG_IGN) + raise InterruptedError(f"installer interrupted by signal {signum}") + signal.signal(signal.SIGTERM, interrupted) + signal.signal(signal.SIGINT, interrupted) + try: + main() + except Exception as error: + print(f"mac-app: {error}", file=sys.stderr) + sys.exit(1) diff --git a/app/vendor/rune/scripts/mac_app_install_tests.py b/app/vendor/rune/scripts/mac_app_install_tests.py new file mode 100644 index 0000000..a7c3881 --- /dev/null +++ b/app/vendor/rune/scripts/mac_app_install_tests.py @@ -0,0 +1,220 @@ +"""Fake-bundle regressions: never launches a desktop application.""" +import os +from pathlib import Path +import subprocess +import sys +import tempfile +import unittest +from unittest.mock import patch + +from mac_app_bundle import Bundle +from mac_app_install import launch, receipt_ready, parse_argv + + +class InstallerRegression(unittest.TestCase): + def test_preserves_exact_arguments_without_reading_environment(self): + data = (6).to_bytes(4, sys.byteorder) + b"/Applications/Demo.app/Contents/MacOS/demo\0\0demo\0--server\0https://example.com\0--directory\0/a path\0\0SECRET=not-an-argument\0" + self.assertEqual(parse_argv(data), ["--server", "https://example.com", "--directory", "/a path", ""]) + + def test_prebuilt_inactive_app_installs_without_launch_and_stamps_success(self): + with tempfile.TemporaryDirectory() as tmp: + home = Path(tmp) + source = home / "source.app" + binary = source / "Contents/MacOS/demo" + binary.parent.mkdir(parents=True) + binary.write_text("new") + commands = home / "commands" + commands.mkdir() + for name, body in {"ps": "exit 0", "open": "exit 99", "codesign": "exit 99"}.items(): + path = commands / name + path.write_text("#!/bin/sh\n" + body + "\n") + path.chmod(0o755) + stamp = home / "installed-rev" + result = subprocess.run( + [str(Path(__file__).with_name("mac-app")), "--name", "Demo", + "--id", "com.example.demo", "--exe", "demo", "--bundle", str(source), + "--only-relaunch", "--stamp", str(stamp), "--revision", "abc123"], + env={**os.environ, "HOME": tmp, "PATH": f"{commands}:/usr/bin:/bin"}, + capture_output=True, text=True, timeout=10, + ) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual((home / "Applications/Demo.app/Contents/MacOS/demo").read_text(), "new") + self.assertEqual(stamp.read_text(), "abc123\n") + + def bundle(self, home): + live = Path(home) / "Demo.app" + live.mkdir() + (live / "version").write_text("old") + return live + + def test_failed_launch_and_missing_receipt_roll_back(self): + for reason in ("open failed", "ready receipt timed out"): + with self.subTest(reason=reason), tempfile.TemporaryDirectory() as home: + live = self.bundle(home) + with Bundle(live) as bundle: + (bundle.stage / "version").write_text("new") + + def start(rollback): + self.assertEqual((live / "version").read_text(), "old" if rollback else "new") + if not rollback: + raise RuntimeError(reason) + + with self.assertRaisesRegex(RuntimeError, reason): + bundle.replace(lambda: None, start, lambda: None) + self.assertEqual((live / "version").read_text(), "old") + + def test_unresponsive_replacement_still_restores_installed_path(self): + with tempfile.TemporaryDirectory() as home: + live = self.bundle(home) + with Bundle(live) as bundle: + (bundle.stage / "version").write_text("new") + def fail(_rollback=False): + raise RuntimeError("unresponsive") + with self.assertRaisesRegex(RuntimeError, "unresponsive"): + bundle.replace(lambda: None, fail, fail) + self.assertEqual((live / "version").read_text(), "old") + + def test_receipt_timeout_uses_real_launch_path_and_rolls_back(self): + with tempfile.TemporaryDirectory() as home: + live = self.bundle(home) + with Bundle(live) as bundle: + (bundle.stage / "version").write_text("new") + with patch("mac_app_install.command"), patch("mac_app_install.running", return_value={123: ()}), \ + patch("mac_app_install.time.monotonic", side_effect=[0, 16]): + def start(rollback): + if not rollback: + launch(live, live / "demo", "com.example.demo", [], home) + with self.assertRaisesRegex(RuntimeError, "did not become ready"): + bundle.replace(lambda: None, start, lambda: None) + self.assertEqual((live / "version").read_text(), "old") + + def test_interrupt_after_exchange_keeps_both_bundles(self): + with tempfile.TemporaryDirectory() as home: + live = self.bundle(home) + script = """ +from mac_app_bundle import Bundle +from pathlib import Path +import os, sys +with Bundle(sys.argv[1]) as bundle: + (bundle.stage / 'version').write_text('new') + (bundle.live.parent / 'backup-path').write_text(str(bundle.stage)) + bundle.publish() + os._exit(0) +""" + subprocess.run([sys.executable, "-c", script, str(live)], check=True, + cwd=Path(__file__).parent, timeout=10) + self.assertEqual((live / "version").read_text(), "new") + backup = Path((live.parent / "backup-path").read_text()) + self.assertEqual((backup / "version").read_text(), "old") + with Bundle(live): # no stale lock remains after death + pass + + def test_termination_between_exchange_and_state_update_rolls_back(self): + with tempfile.TemporaryDirectory() as home: + live = self.bundle(home) + script = """ +import mac_app_bundle as m +import os, signal, sys +real_exchange = m.exchange +def interrupt(a, b): + real_exchange(a, b) + if (b / 'version').read_text() == 'new': + os.kill(os.getpid(), signal.SIGTERM) +def terminated(*_): + raise InterruptedError('terminated') +m.exchange = interrupt +signal.signal(signal.SIGTERM, terminated) +with m.Bundle(sys.argv[1]) as bundle: + (bundle.stage / 'version').write_text('new') + try: + bundle.replace(lambda: None, lambda _: None, lambda: None) + except InterruptedError: + pass + else: + raise AssertionError('termination was lost') + assert (bundle.live / 'version').read_text() == 'old' +""" + subprocess.run([sys.executable, "-c", script, str(live)], check=True, + cwd=Path(__file__).parent, timeout=10) + self.assertEqual((live / "version").read_text(), "old") + + def test_concurrent_installer_waits_until_rollback(self): + with tempfile.TemporaryDirectory() as home: + live = self.bundle(home) + script = """ +from mac_app_bundle import Bundle +import fcntl, pathlib, sys +live = pathlib.Path(sys.argv[1]) +with (live.parent / f'.{live.name}.install.lock').open('a+b') as f: + try: + fcntl.flock(f, fcntl.LOCK_EX | fcntl.LOCK_NB) + raise AssertionError('first installer has no lock') + except BlockingIOError: + print('blocked', flush=True) +with Bundle(live) as bundle: + assert (live / 'version').read_text() == 'old' + (bundle.stage / 'version').write_text('second') + bundle.replace(lambda: None, lambda _: None, lambda: None) +""" + with Bundle(live) as first: + (first.stage / "version").write_text("first") + first.publish() + child = subprocess.Popen([sys.executable, "-c", script, str(live)], + cwd=Path(__file__).parent, stdout=subprocess.PIPE, text=True) + self.assertEqual(child.stdout.readline().strip(), "blocked") + first.restore() + try: + self.assertEqual(child.wait(timeout=10), 0) + finally: + if child.poll() is None: + child.kill() + child.wait() + child.stdout.close() + self.assertEqual((live / "version").read_text(), "second") + + def test_receipt_must_identify_replacement(self): + with tempfile.TemporaryDirectory() as home: + directory = Path(home) + receipt = directory / "com.example.demo.123" + receipt.write_text('{"pid": 124, "bundle_id": "com.example.demo"}') + self.assertFalse(receipt_ready(directory, "com.example.demo", 123)) + receipt.write_text('{"pid": 123, "bundle_id": "com.example.demo"}') + self.assertTrue(receipt_ready(directory, "com.example.demo", 123)) + + def test_missing_stage_does_not_remove_live_app(self): + with tempfile.TemporaryDirectory() as tmp: + home = Path(tmp) + live = home / "Applications/Demo.app" + live.mkdir(parents=True) + (live / "version").write_text("old") + commands = home / "commands" + commands.mkdir() + # Simulate the other installer consuming this stage during codesign. + for name, body in { + "ps": "exit 0", + "codesign": 'for arg; do last="$arg"; done; rm -rf "$last"', + "open": "exit 1", + }.items(): + path = commands / name + path.write_text("#!/bin/sh\n" + body + "\n") + path.chmod(0o755) + binary = home / "demo" + binary.write_text("#!/bin/sh\nexit 0\n") + binary.chmod(0o755) + stamp = home / "installed-rev" + stamp.write_text("old-revision\n") + result = subprocess.run( + [str(Path(__file__).with_name("mac-app")), "--name", "Demo", + "--id", "com.example.demo", "--exe", "demo", "--bin", str(binary), + "--stamp", str(stamp), "--revision", "new-revision"], + env={**os.environ, "HOME": tmp, "PATH": f"{commands}:/usr/bin:/bin", "MAC_APP_SIGN": ""}, + capture_output=True, text=True, timeout=10, + ) + self.assertNotEqual(result.returncode, 0) + self.assertTrue(live.is_dir(), result.stderr) + self.assertEqual((live / "version").read_text(), "old") + self.assertEqual(stamp.read_text(), "old-revision\n") + + +if __name__ == "__main__": + unittest.main() diff --git a/app/vendor/rune/scripts/menu.json b/app/vendor/rune/scripts/menu.json new file mode 100644 index 0000000..8c830c0 --- /dev/null +++ b/app/vendor/rune/scripts/menu.json @@ -0,0 +1,5 @@ +[ + {"t": 0.1, "menu": "Open Quick Panel"}, + {"t": 0.3, "menu": "named"}, + {"t": 0.5, "menu": "dock"} +] diff --git a/app/vendor/rune/scripts/motion-audit/README.md b/app/vendor/rune/scripts/motion-audit/README.md new file mode 100644 index 0000000..6cfb7ca --- /dev/null +++ b/app/vendor/rune/scripts/motion-audit/README.md @@ -0,0 +1,133 @@ +# Motion audit + +Per-frame traces of every element in the example apps, and a checker that flags motion a user +would notice: snaps, pops, neighbours that jump, exits that vanish before they play, overshoot, +motion that never settles, and work spent on things nobody can see. + +```sh +scripts/motion-audit/run.sh # record all scenarios into target/motion-audit +python3 scripts/motion-audit/analyze.py target/motion-audit/*.jsonl [--quiet] [--json out.json] +python3 scripts/motion-audit/track.py target/motion-audit/oc-send.jsonl composer/editor 80 120 +python3 scripts/motion-audit/test_analyze.py # analyze.py on synthetic traces +``` + +`run.sh` records each scenario headless at 120 fps on the virtual clock with +`--trace-all --trace`. `--trace-all` adds unkeyed elements (named by path) to the usual +motion-lint JSONL, and every trace now says why each frame animated (`quality.why`) and which +tracks it sampled (`tk`: `[element id or path, property, active]`; inactive means settling). +It also says how far scrolling carries each element when that changes (`sc`: `[id, x, y]` in +window points, scaled and turned as its rect is). The motion checks (overshoot, jiggle, reversal, stall, dog-leg) add it back, so a node +gliding inside a list that follows its end is judged against the list, not the screen. + +`analyze.py` reports, per trace: + +| Finding | Meaning | +| --- | --- | +| `invisible-work` | tracks sampled on an element that is transparent, off-window, clipped or occluded | +| `idle-frames`, `never-settles` | frames that animate with no visible change; motion still running at the end | +| `pop-in`, `pop-out` | an element appears or disappears at full opacity and size with no transition | +| `appear-then-jump` | mounts in one place, then moves there in a frame | +| `jump`, `step`, `sibling-jump` | a one-frame change in position or size, on its own or next to something animating, seen on both frames and in what shows: the visible part in the window moves, or what the element holds that shows moves with it, or it brings what it holds into view with no input (a scroll offset that lands in one frame with nothing asking for it; a loop wrapping while transparent or clipped, or a fold dropping rows above the window with the scroll offset, is not one) | +| `overshoot`, `jiggle` | passes its target, or reverses direction more than once | +| `latency`, `hitch` | input with no motion for several frames; a frame over budget | +| `cut-exit` | unmounts partway through its fade: nothing leaves above opacity 0 | +| `reversal`, `dog-leg` | one motion heads the wrong way first or goes out and back; a route much longer than its chord, on screen and against its parent | +| `stall` | one motion's speed drops for a frame and picks up again, as a retarget that lost part of its velocity does | + +An app's scenario can say what each input should do with `"expect"` on its script event: + +| Expect | Checks | Finding | +| --- | --- | --- | +| `instant` | everything in `scope` (an element name part) lands within a frame or two of the input; pops and jumps there are intended | `not-instant` | +| `follow` | a drag's `element` moves 1:1 with the pointer while it moves (it may stop at a limit) | `lags-hand` | +| `smooth` | after the input, `element` travels over several frames, not in one | `snap` | +| `leaves` | `element` is what leaves, not a sibling (index keys remove the last row) | `wrong-exit` | + +```sh +python3 scripts/motion-audit/analyze.py --script s.json trace.jsonl --allow allow.json --fail +``` + +`--allow` takes a JSON list of `{"trace", "kind" (or a list), "element" (a substring), +"reason"}` rules for intended behaviour; every rule needs a reason, and a rule for a trace +the run recorded that matched nothing is listed as unused. `--fail` exits non-zero when a finding isn't allowed. + +A motion that hides what it moves (a fade to 0, a collapse, a slide out) runs on for a few +frames below what anyone can see, down to its settle threshold. Up to 250 ms of that tail, +ending as its track settles, isn't `invisible-work`. A loop (a spinner) runs for as long as +it's shown, so frames animating only loops aren't `idle-frames` or `never-settles`. + +Elements that draw nothing and hold nothing (hit and hover zones, spacers) carry the trace's +blank flag (64). Nobody can see them come, go or move, so they don't pop, jump or count as +drawn. + +`track.py` prints one element's frames (rect, opacity, flags, sampled tracks) to confirm a +finding. Add scenarios as script JSON under `scenarios/` and a `run` line in `run.sh`. + +## An app's own motion gate (`rune::motion_gate`) + +The scenarios above are Rune's examples, recorded as traces and read by `analyze.py`. An app +gates its own motion inside `cargo test`, on its real view and state, with `rune::motion_gate`: + +- `Run` wraps the app's `Runtime`: `idle` settles it unrecorded, `step`, `play` and `act` record + frames on the virtual clock (an `act` marks an input, so motion it retargets isn't held to one + path), and `quiet` marks where the cell's motion should end. +- `check` lists what a person would see go wrong in a `Recording`: `pop-in`, `pop-out`, + `cut-exit`, `jump`, `offset-jump`, `appear-then-jump`, `jerk`, `reversal`, `overshoot`, + `jiggle`, `text-swap`, `fade-snap`, `flicker`, `load-motion`, `never-settles`, `loop-jump`, + `wakes-after-end`, `lands-unseen`, `remount`, `unpinned`, `twice` and `scroll-commit` (the + app ran its view through a scroll). Thresholds and meanings are the `RULES` table. Elements are tracked by tree + path, so a keyed row keeps its identity however the rows around it change. +- Beside geometry and opacity, `check` follows everything an element paints (fill, border, + text, shadow, gradient and outline colours in OKLab, corners, border width, blurs, effect + payload, image and paint order) and the composited window as a grid of cells: `snap` (a + one-frame step between still frames), `flash` (it steps away and comes back, or drifts and + snaps back) and `changes-twice` (it changes, rests, then carries on). A colour counts by how + far it moves in OKLab and how much of it shows. The grid is a CPU raster of the painter + stream, or real frames through `Run::pixels`; a region finding is named after the surface + that changed, with ` (pixels)`. An input, a hover or press highlight landing, a + `Tx::instant` commit, `El::instant_changes` and `El::motion_intent` (`BOUNCE`, `KICK`, + `STEP`, `CUT`, `PULSE`, `TYPING`, …) mark a change as the design. Mark authored motion where + it's written rather than allowing it. +- `gate_rows(cells, ALLOW)` runs the app's cells (a name and a closure that records one) in + parallel, checks them, and fails the test on any finding its allowlist doesn't cover. Each + row is `AllowRow::new(kind, element contains, cells, why)`, needs its reason, scopes to the + cells it names (`"island-auto|island-click"`) and caps what it covers with `.max(n)`. A + whole run lists rows that matched nothing, so stale ones come out. `gate(cells, ALLOW)` takes + the older `(kind, element, cell, why)` tuples. +- Headless `rune` records the same checks with `RUNE_MOTION_GATE=<path>` (`run.sh` writes + `<name>.gate.txt` per scenario), and an app stepping its own runtime can use `Sampler`. + +The app keeps its scenarios, its circumstance matrix (cell names like `send/pinned/long/wide`) +and its allowlist; Rune keeps the checker and the runner. The module docs show a whole test. +`gate` runs one: + +```sh +scripts/motion-audit/gate -- -p my-app motion_gate # every cell +scripts/motion-audit/gate send/pinned -- -p my-app motion_gate # cells whose name contains it +scripts/motion-audit/gate --allowed -- -p my-app motion_gate # allowed findings too +scripts/motion-audit/gate --dump 'send/pinned/long/wide|composer|120|160' -- -p my-app motion_gate +scripts/motion-audit/gate --sheet 'send/pinned/long/wide|134|composer' -- -p my-app motion_gate +``` + +`--dump` writes one cell's tracks frame by frame (rect, visible rect, opacity, scale, flags, +and each painted property); +`--sheet` writes a PNG strip of the frames around one, every element outlined as strongly as +its opacity and the named one in red. An empty cell part (`'|composer|120|160'`) matches any +cell, and headless `rune` writes both beside its `RUNE_MOTION_GATE` report. Both are evidence +for reading a finding; the findings +are the gate. `MOTION_GATE_OUT` names the report (default `$TMPDIR/motion-gate`), and +`MOTION_GATE_WRAP` runs the test under a command prefix. + +## Tracing the real app (`motion-trace.py`) + +The gate runs headless on the virtual clock, so it says nothing about how long a real frame +takes. For that, an app can write its own trace in the installed build, one JSON line per key, +span and frame (the format is at the top of `motion-trace.py`), and read it: + +```sh +python3 scripts/motion-audit/motion-trace.py trace.jsonl --key Enter --frames 40 --budget 16.7 +``` + +For each matching key it prints how many frames passed before a watched element moved, then +each frame's update and render cost, marking the ones over budget, with the spans over 1 ms in +them. diff --git a/app/vendor/rune/scripts/motion-audit/analyze.py b/app/vendor/rune/scripts/motion-audit/analyze.py new file mode 100644 index 0000000..6a98bbd --- /dev/null +++ b/app/vendor/rune/scripts/motion-audit/analyze.py @@ -0,0 +1,1050 @@ +#!/usr/bin/env python3 +"""Motion audit of Rune traces (`--trace out.jsonl --trace-all`). + +Reads each element's presented rect, opacity and clipped rect per frame, the tracks the +motion store sampled (`tk`) and why the frame was animating (`quality.why`), and lists what +looks wrong: + + invisible-work tracks sampled while their element can't be seen (opacity 0, clipped + away or off the window) for several frames in a row + idle-frames frames that asked for another frame but changed nothing traced + never-settles still animating at the end of the run, long after the last input + pop-in/pop-out mounted or unmounted at full opacity with no transition + cut-exit unmounted partway through its fade (nothing leaves above opacity 0) + jump a rect edge moves far in one frame between still frames (no interpolation) + step one frame of a smooth motion moves much more than its neighbours + sibling-jump a jump in a sibling of something that just mounted or unmounted + overshoot an edge passes its rest value and comes back + jiggle an edge reverses direction twice or more within one motion + reversal one motion heads the wrong way first, or goes out and comes back + stall one motion's speed drops for a frame and picks up again (a retarget that + lost part of its velocity) + dog-leg a move's route is much longer than the straight line between its ends, on + screen and against its parent + latency input whose first visible response comes frames later + hitch frame CPU over budget during motion + +With `--script S.json` before a trace, the script's events can say what they expect +(`"expect": "instant" | "follow" | "smooth" | "leaves"`, see `expectations`), which adds +not-instant, lags-hand, snap and wrong-exit findings and makes cuts inside an instant +window intended. + +Usage: scripts/motion-audit/analyze.py [--script S.json] TRACE.jsonl... [--json out.json] + [--allow allow.json] [--fail] [--quiet] +`--allow` takes rules `{"trace", "kind" (or a list), "element" (a substring), "reason"}`; +every rule needs a reason. Exit code is 0 unless `--fail` and a finding isn't allowed. +""" + +import bisect +import json +import math +import statistics +import sys +from collections import defaultdict + +VISIBLE_OPACITY = 0.01 +POP_OPACITY = 0.5 +JUMP_PT = 12.0 +# Frames at rest a motion segment bridges (see the segments in `analyze`). +SEG_GAP = 2 +# A one-frame speed dip worth reporting: at least this many points a frame, and this share of +# the slower neighbour's speed (a spring's speed never has a corner). +STALL_PT = 0.5 +STALL_SHARE = 0.25 +MIN_AREA = 1.0 +ANIMATED = 1 # flags: a motion of its own (a spring, a stack, a loop) moves it this frame +SCROLLING = 4 # flags: under a scroll viewport whose offset moved this frame +LOOPING = 32 # flags: runs a loop of its own (a spinner, a sheen, a busy ring's dots) +BLANK = 64 # flags: draws nothing and holds nothing (a hit or hover zone, a spacer) +SETTLE_TAIL_MS = 250.0 # a motion's own sub-visible tail after it hides what it moves + + +def short(name, parts=3): + segs = name.split("/") + return "/".join(segs[-parts:]) if len(segs) > parts else name + + +class El: + __slots__ = ("id", "name", "parent", "rect", "op", "flags", "vis", "born", "hist", "ever_drawn", "scrolled") + + def __init__(self, id, name, parent): + self.id, self.name, self.parent = id, name, parent + self.rect = None + self.op = 1.0 + self.flags = 0 + self.vis = None + self.born = None + self.ever_drawn = False # had area at some point (spacers never do) + self.scrolled = (0.0, 0.0) # how far scrolling carries it, x and y (the trace's `sc`) + # (frame, x, y, w, h, op, flags, visible-area-fraction, on-screen, scrolled x, scrolled y, + # shown x, y, w, h: the visible part in the window, as `shown`) + self.hist = [] + + +def area(r): + return max(r[2], 0) * max(r[3], 0) + + +def on_screen(r, W, H): + return r[0] < W and r[1] < H and r[0] + r[2] > 0 and r[1] + r[3] > 0 and area(r) > 0 + + +def visible_part(e, W, H): + r = e.vis if e.vis is not None else e.rect + x0, y0 = max(r[0], 0), max(r[1], 0) + x1, y1 = min(r[0] + r[2], W), min(r[1] + r[3], H) + return [x0, y0, max(x1 - x0, 0), max(y1 - y0, 0)] + + +def shown(vp, W, H): + """What shows, where one wholly past the window's edge would come in. Jumps and steps are + judged on it: an edge its clips hide on both frames moves nobody can see.""" + return (min(vp[0], W), min(vp[1], H), vp[2], vp[3]) + + +def seen(e, W, H): + return e.op > VISIBLE_OPACITY and area(visible_part(e, W, H)) >= MIN_AREA + + +def load(path): + frames = [] + with open(path) as f: + header = json.loads(f.readline()) + for line in f: + line = line.strip() + if line: + frames.append(json.loads(line)) + return header, frames + + +def runs(frames_list): + """Consecutive frame indices → [(start, end)].""" + out = [] + for k in sorted(frames_list): + if out and k == out[-1][1] + 1: + out[-1][1] = k + else: + out.append([k, k]) + return [tuple(r) for r in out] + + +def fmt_runs(rs, limit=4): + s = ", ".join(f"{a}" if a == b else f"{a}–{b}" for a, b in rs[:limit]) + return s + (f" (+{len(rs) - limit} more)" if len(rs) > limit else "") + + +def loop_ids(els, moved): + """A loop (a spinner, a sheen, a busy ring's dots) keeps changing on most frames it's alive, + as one element or as a group of siblings taking turns. Its wraps and turns are its design.""" + busy = defaultdict(set) + group_busy = defaultdict(set) + for j, moves in enumerate(moved): + for id in moves: + busy[id].add(j) + if id in els: + group_busy[els[id].parent].add(j) + life = {e.id: len(e.hist) for e in els.values()} + out = {id for id in busy if life.get(id, 0) >= 60 and len(busy[id]) >= 0.5 * life[id]} + # One the trace marks as running a loop of its own is one however briefly it shows. + out |= {e.id for e in els.values() if any(st[6] & LOOPING for st in e.hist)} + groups = {p for p, ks in group_busy.items() if p in life and life[p] >= 60 and len(ks) >= 0.5 * life[p]} + out |= {e.id for e in els.values() if e.parent in groups} + # What a loop carries moves with it. + grew = True + while grew: + more = {e.id for e in els.values() if e.parent in out and e.id not in out} + grew = bool(more) + out |= more + return out + + +def unscrolled(h): + """History rows against the content they scroll with: a node gliding inside a list that + follows its end makes one motion there, however the scroll adds to it on screen.""" + return [(st[0], st[1] + st[9], st[2] + st[10], *st[3:]) for st in h] + + +def stalled(parent, edge, pts, travel): + """The first frame of one motion (`pts`, consecutive history rows) whose speed along + `travel` dips below both neighbours' and recovers, with the three speeds; one that rides + its parent (`parent`, its rows) is the parent's to report.""" + ph = {x[0]: x for x in parent} + sign = math.copysign(1, travel) + for m in range(2, len(pts) - 1): + if pts[m + 1][0] - pts[m - 2][0] != 3: + continue + u = [(pts[m + j][edge] - pts[m + j - 1][edge]) * sign for j in (-1, 0, 1)] + floor = min(u[0], u[2]) + if floor <= STALL_PT or u[1] >= floor - max(STALL_PT, STALL_SHARE * floor): + continue + k = pts[m][0] + if k in ph and k - 1 in ph and abs((ph[k][edge] - ph[k - 1][edge]) - (pts[m][edge] - pts[m - 1][edge])) < 0.05: + continue + return k, u + return None + + +def analyze(path, script=None): + header, frames = load(path) + W, H, hz = header["width"], header["height"], header["hz"] + dt_ms = 1000.0 / hz + els = {} + alive = set() + findings = [] + touched_invisible = defaultdict(list) # (name, prop) -> frames + sampled = defaultdict(set) # (id, prop) -> frames its track ran + touched_untraced = defaultdict(int) + idle = [] + animating = [] + inputs = [] # (frame, event) + births = defaultdict(list) # frame -> ids + deaths = defaultdict(list) # frame -> (id, last state) + scrolled = defaultdict(set) # frame -> containers (by path) of elements a scroll moved + cpu = [] + changed_by_frame = [] + t_ms = [] + changes = [] # frame -> {id: props whose value changed or whose track ran} + prev = {} # id -> (x, y, w, h, opacity) + + for k, fr in enumerate(frames): + t_ms.append(fr.get("t", k * dt_ms)) + moves = defaultdict(set) + changes.append(moves) + for m in fr.get("m", []): + e = els.get(m["id"]) + if e is None: + e = els[m["id"]] = El(m["id"], m["nm"], m.get("pv")) + else: + e.name, e.parent = m["nm"], m.get("pv", e.parent) + changed = set() + for row in fr.get("e", []): + id = row[0] + e = els[id] + e.rect = row[1:5] + e.op = row[5] + e.flags = row[7] + e.vis = row[8:12] if len(row) >= 12 else None + e.ever_drawn |= area(e.rect) >= MIN_AREA and not e.flags & BLANK + old = prev.get(id) + if old is not None and id in alive: + if abs(row[1] - old[0]) > 0.01 or abs(row[2] - old[1]) > 0.01: + moves[id].add("position") + if abs(row[3] - old[2]) > 0.01 or abs(row[4] - old[3]) > 0.01: + moves[id].add("size") + if abs(row[5] - old[4]) > 0.001: + moves[id].add("opacity") + prev[id] = tuple(row[1:6]) + if id not in alive: + alive.add(id) + e.born = k + if k > 0: + births[k].append(id) + changed.add(id) + for id, sx, sy in fr.get("sc", []): + els[id].scrolled = (sx, sy) + for id in fr.get("g", []): + if id in alive: + alive.discard(id) + e = els[id] + e.scrolled = (0.0, 0.0) + deaths[k].append((id, e.rect, e.op, seen(e, W, H) and not e.flags & BLANK)) + for id in alive: + e = els[id] + vp = visible_part(e, W, H) + frac = area(vp) / area(e.rect) if area(e.rect) > 0 else 0.0 + e.hist.append((k, *e.rect, e.op, e.flags, frac, on_screen(e.rect, W, H), *e.scrolled, *shown(vp, W, H))) + if e.flags & SCROLLING: + scrolled[k].add(e.name.rpartition("/")[0]) + q = fr.get("quality", {}) + cpu.append(q.get("cpu_ms", 0.0)) + anim = bool(q.get("animating")) + animating.append(anim) + visible_change = any(seen(els[i], W, H) or i in births.get(k, []) for i in changed) + changed_by_frame.append(visible_change) + for ev in fr.get("ev", []): + if not ev.startswith(("settled", "completed")): + inputs.append((k, ev)) + tracks = fr.get("tk", []) + why = tuple(q.get("why", [])) + # A loop's curve flattens at its turns, where a frame moves it less than the trace shows. + if anim and not changed and k > 0 and not any(a for _, _, a in tracks) and why != ("loop",): + idle.append((k, why)) + for who, prop, active in tracks: + if not active: + continue # set without animating: no motion this frame + if isinstance(who, str): + # An untraced container (a layout-only stack) is seen if what it holds is. + if not any(els[i].name.startswith(who + "/") and seen(els[i], W, H) for i in alive): + touched_untraced[(short(who), prop)] += 1 + continue + sampled[(who, prop)].add(k) + moves[who].add(prop) + e = els.get(who) + if e is None or who not in alive: + touched_untraced[(f"#{who}", prop)] += 1 + continue + if not seen(e, W, H) and e.ever_drawn: + touched_invisible[(e.name, prop, who)].append(k) + + n = len(frames) + acts = script_inputs(script) if script else [] + loops = loop_ids(els, changes) + + def frame_of(t): + return min(bisect.bisect_left(t_ms, t * 1000.0 - 0.01), n - 1) + + input_frames = sorted({frame_of(t) for a in acts for t in a["times"]} | {k for k, _ in inputs}) + # A wheel step or fling sets the scroll's speed itself, so what moves with the scroll without + # riding it (a scroll bar's thumb) slows and picks up with the hand, not at a lost retarget. + wheeled = {k for k, ev in inputs if ev.startswith(("wheel", "fling"))} + + def interrupted(k0, k1): + """An input landed mid-motion (a retarget may turn it around).""" + i = bisect.bisect_right(input_frames, k0) + return i < len(input_frames) and input_frames[i] <= k1 + + # invisible work: report the outermost element of a subtree that went unseen together + def covered(id, prop, ks): + p = els[id].parent + while p is not None: + for prop2 in {prop, "frame", "presence", "opacity"}: + if (p, prop2) in keys and set(ks) <= set(keys[(p, prop2)]): + return True + p = els[p].parent if p in els else None + return False + def tail(id, prop, a, b): + # The motion that just hid the element (a fade to 0, a collapse, a slide out), running + # out its last sub-visible stretch to its settle threshold, then stopping. + before = [st for st in els[id].hist if st[0] == a - 1] + was_seen = bool(before) and before[0][5] > VISIBLE_OPACITY and before[0][7] * before[0][3] * before[0][4] >= MIN_AREA + return was_seen and b + 1 not in sampled[(id, prop)] and (b - a + 1) * dt_ms <= SETTLE_TAIL_MS + for key, ks in list(touched_invisible.items()): + (name, prop, id) = key + rest = [k for a, b in runs(ks) if not tail(id, prop, a, b) for k in range(a, b + 1)] + if rest: + touched_invisible[key] = rest + else: + del touched_invisible[key] + keys = {(id, prop): ks for (name, prop, id), ks in touched_invisible.items()} + for (name, prop, id), ks in touched_invisible.items(): + if covered(id, prop, ks): + continue + rs = runs(ks) + longest = max(b - a + 1 for a, b in rs) + if longest < 6: + continue + e = els[id] + kset = set(ks) + unseen = [st for st in e.hist if st[0] in kset] + why = [] + if any(st[5] <= VISIBLE_OPACITY for st in unseen): + op = min(st[5] for st in unseen) + why.append(f"opacity {op}") + if any(st[7] == 0 and st[8] for st in unseen): + why.append("clipped away") + if any(not st[8] for st in unseen): + why.append("off-window") + findings.append(dict(kind="invisible-work", element=name, prop=prop, frames=len(ks), longest=longest, + at=fmt_runs(rs), detail=f"{prop} sampled on {len(ks)} frames while unseen ({', '.join(why) or 'unseen'})")) + for (who, prop), count in touched_untraced.items(): + if count >= 6: + findings.append(dict(kind="invisible-work", element=who, prop=prop, frames=count, longest=count, at="", + detail=f"{prop} sampled on {count} frames for a node not in the element tree")) + + # idle frames and settling + if idle: + by_why = defaultdict(list) + for k, why in idle: + by_why[why].append(k) + settle_cap = math.ceil(120.0 / dt_ms) + for why, ks in by_why.items(): + rs = runs(ks) + # A scaled layer's 100 ms sub-pixel settle eases `r` onto the device grid after motion + # while `self.drawn` (`r_exact`) is already still; flag only cold or overrun runs. + if why == ("scale-settle",): + bad_rs = [] + for a, b in rs: + p = a - 1 + while p >= 0 and tuple(frames[p].get("quality", {}).get("why", [])) == ("scale-settle",): + p -= 1 + warm = (p >= 0 and animating[p]) or (p + 1 < a and changed_by_frame[p + 1]) + if not warm or b - p > settle_cap: + bad_rs.append((a, b)) + rs = bad_rs + ks = [k for a, b in rs for k in range(a, b + 1)] + if not ks: + continue + findings.append(dict(kind="idle-frames", element="(frame)", frames=len(ks), longest=max(b - a + 1 for a, b in rs), + at=fmt_runs(rs), detail=f"{len(ks)} frames animating ({'+'.join(why) or '?'}) with no traced change")) + last_input = max((k for k, _ in inputs), default=0) + tail = [k for k in range(n) if animating[k]] + # A loop (a spinner) runs for as long as it's shown: only other motion fails to settle. + quiet = int(500 / dt_ms) + only_loops = frames[-1].get("quality", {}).get("why", []) == ["loop"] and not any( + a and who not in loops for fr in frames[-quiet:] for who, _, a in fr.get("tk", [])) + if animating and animating[-1] and (n - 1 - last_input) * dt_ms > 1000 and not only_loops: + q = frames[-1].get("quality", {}) + start = n - 1 + while start > 0 and animating[start - 1]: + start -= 1 + busy = defaultdict(int) + for fr in frames[start:]: + for who, prop, _ in fr.get("tk", []): + busy[(els[who].name if isinstance(who, int) and who in els else str(who), prop)] += 1 + top = sorted(busy.items(), key=lambda kv: -kv[1])[:4] + findings.append(dict(kind="never-settles", element="(frame)", frames=n - start, longest=n - start, at=f"{start}–{n - 1}", + detail=f"still animating ({'+'.join(q.get('why', []))}) {((n - 1 - last_input) * dt_ms / 1000):.1f}s after the last input; " + + ("busiest tracks: " + "; ".join(f"{short(nm)} {p} ×{c}" for (nm, p), c in top) if top else "no store tracks"))) + + # pops + def top_level(ids, k=None, table=None): + # By path too: a layout-only parent (an untraced stack) breaks the id chain. + s = set(ids) + names = {els[i].name for i in ids} + def under(i): + nm = els[i].name + return any(nm[:j] in names for j in range(len(nm)) if nm[j] == "/") + return [i for i in ids if els[i].parent not in s and not under(i)] + + for k, ids in births.items(): + for id in top_level(ids, k, births): + e = els[id] + if id in loops: + continue + h = [x for x in e.hist if x[0] >= k][:3] + if not h: + continue + k0, x, y, w, hh, op, flags, frac, ons = h[0][:9] + # A viewport's content entering as it scrolls (a virtual list mounting the rows an + # instant scroll lands on) is the scroll, which jumps already exempt, not a pop. + if op < POP_OPACITY or frac == 0 or not ons or w * hh < 4 or flags & (SCROLLING | BLANK): + continue + grows = len(h) > 1 and (abs(h[1][3] - w) > 0.5 or abs(h[1][4] - hh) > 0.5 or abs(h[1][5] - op) > 0.01) + intent = flags >> 8 + if grows or (intent & (16 | 4 | 32)): + continue + moved = len(h) > 1 and (abs(h[1][1] - x) > JUMP_PT or abs(h[1][2] - y) > JUMP_PT) + findings.append(dict(kind="pop-in" if not moved else "appear-then-jump", element=e.name, frames=1, longest=1, at=str(k), + detail=f"mounted at opacity {op} size {w:.0f}×{hh:.0f} at ({x:.0f},{y:.0f})" + + (f", then jumped to ({h[1][1]:.0f},{h[1][2]:.0f})" if moved else " with no transition"))) + for k, items in deaths.items(): + tops = set(top_level([i for i, *_ in items])) + for id, rect, op, was_seen in items: + # Leaving as its viewport scrolls (rows a jump left behind) is the scroll too. + if id not in tops or not was_seen or els[id].name.rpartition("/")[0] in scrolled[k]: + continue + # Nothing unmounts above opacity 0: a fade cut short is a smaller pop. + findings.append(dict(kind="pop-out" if op >= POP_OPACITY else "cut-exit", element=els[id].name, frames=1, longest=1, at=str(k), + detail=f"unmounted at opacity {op} size {rect[2]:.0f}×{rect[3]:.0f} at ({rect[0]:.0f},{rect[1]:.0f})" + + ("" if op >= POP_OPACITY else ", before its fade reached 0"))) + + # geometry: jumps, steps, overshoot, jiggle + changed_parents = defaultdict(set) # frame -> parents with births/deaths + for k, ids in births.items(): + for i in ids: + changed_parents[k].add(els[i].parent) + for k, items in deaths.items(): + for i, *_ in items: + changed_parents[k].add(els[i].parent) + pressing = [bool(fr.get("k")) for fr in frames] + kids = defaultdict(list) + for e in els.values(): + kids[e.parent].append(e) + at_frame = {} + + def at(e, k): + if e.id not in at_frame: + at_frame[e.id] = {st[0]: st for st in e.hist} + return at_frame[e.id].get(k) + + def carries(e, k, edge, step, entering): + """Whether something `e` holds shows on frames k - 1 and k and moves there by `step` with + it, as a scroll's rows do when its content jumps though its visible part stays put. With + `entering`, also one it brings into view from just off it: content that teleports pops in + a row that didn't show the frame before.""" + if edge > 2: + return False + for c in kids.get(e.id, ()): + a, b = at(c, k - 1), at(c, k) + if not (a and b): + continue + if b[7] > 0 and abs(b[edge] - a[edge] - step) < 0.25: + if a[7] > 0 and abs(b[10 + edge] - a[10 + edge] - step) < 0.25: + return True + if entering and a[7] == 0 and b[5] >= POP_OPACITY and not b[6] & BLANK: + return True + if carries(c, k, edge, step, entering): + return True + return False + + # Source/layout goals, not sampled spring positions. A streamed update can choose another + # destination without a key. Judge each destination separately; jumps still span updates. + goals = [{row[0]: row[1:] for row in fr.get("retarget", [])} for fr in frames] + + # What sits in a scroll area without scrolling (a scroll bar's thumb) reads the content's + # length, so a destination the content changes is a destination it changes too. + scrolls = {e.name for e in els.values() if any(st[9] or st[10] for st in e.hist)} + traced = {e.name for e in els.values()} + viewports = set() + for name in scrolls: + parts = name.split("/") + for i in range(len(parts) - 1, 0, -1): + p = "/".join(parts[:i]) + if p in traced and p not in scrolls: + viewports.add(p) + break + # A scroll bar sits beside its viewport, in the same area. + areas = viewports | {v.rpartition("/")[0] for v in viewports} + over = {} + + def scroll_area(e): + if e.id not in over: + a = None if e.name in scrolls else els.get(e.parent) + while a and a.name not in areas: + a = els.get(a.parent) + over[e.id] = a.name + "/" if a else None + return over[e.id] + + def retargeted(e, k, mask): + own, start = True, e + while e: + change = goals[k].get(e.id) + if change and change[0 if own else 1] & mask: + return True + own = False + e = els.get(e.parent) + area_ = scroll_area(start) + return bool(area_) and any(id in els and els[id].name.startswith(area_) and els[id].name in scrolls + for id, change in goals[k].items() if change[0] | change[1]) + + def braking(e, h, seg, edge, vals): + """A retarget preserves incoming velocity. Its first turn is braking, not a wind-up, + only while each step slows in the direction it was already travelling. A second turn, + a fresh acceleration away, or motion starting from rest still fails the usual checks.""" + first = seg[0] + if first < 2 or not retargeted(e, h[first][0], 1 << (edge - 1)): + return vals + incoming = h[first - 1][edge] - h[first - 2][edge] + if abs(incoming) <= 0.05 or incoming * (vals[-1] - vals[0]) >= 0: + return vals + speed = abs(incoming) + for i, (a, b) in enumerate(zip(vals, vals[1:])): + step = b - a + if step * incoming < 0: + return vals[i:] + if abs(step) > speed + 0.05: + return vals + speed = abs(step) + return vals + + for e in els.values(): + h = e.hist + if len(h) < 3 or e.id in loops: + continue + mine = unscrolled(h) + theirs = unscrolled(parent.hist) if (parent := els.get(e.parent)) else [] + # Only report the outermost element of a group moving together. + for edge, label in ((1, "x"), (2, "y"), (3, "w"), (4, "h")): + d = [h[i][edge] - h[i - 1][edge] if h[i][0] == h[i - 1][0] + 1 else 0.0 for i in range(1, len(h))] + for i in range(1, len(h)): + k = h[i][0] + step = d[i - 1] + if abs(step) < JUMP_PT: + continue + st, prev = h[i], h[i - 1] + if pressing[k] or st[6] & BLANK: + continue + # A scroll under a hand, or one gliding over frames, moves as it should. One that + # lands in a single frame with nothing asking for it is a teleport. + scrolling = (st[6] | prev[6]) & SCROLLING + hand = interrupted(k - 2, k) + if scrolling and hand: + continue + # A move nobody sees on either side isn't a jump: a loop wrapping while it's + # transparent or clipped away (a shimmer's sheen going back to its start). + if any(s[5] <= 0.05 or s[7] == 0 or not s[8] for s in (prev, st)): + continue + intent = st[6] >> 8 + if intent & (1 if label in "xy" else 2): + continue + # Judged on what shows: its visible part moves, or what it holds that shows does. + # A fold dropping its rows above the window steps its top and height with the + # scroll offset, and nothing that shows moves, or it starts to glide from where + # it showed. + clipped = any(s[7] < 0.999 for s in (prev, st)) + at_edge = edge if clipped and carries(e, k, edge, step, not hand) else 10 + edge + sd = lambda j: h[j][at_edge] - h[j - 1][at_edge] if 0 < j < len(h) and h[j][0] == h[j - 1][0] + 1 else 0.0 + if abs(sd(i)) < JUMP_PT: + continue + before, after = sd(i - 1), sd(i + 1) + if abs(before) < 1.0 and abs(after) < 1.0: + kind = "sibling-jump" if any(els.get(e.parent) and p == e.parent for p in changed_parents.get(k, ())) else "jump" + elif not scrolling and abs(sd(i)) > 3 * max(abs(before), abs(after), 1.0): + kind = "step" + else: + continue + parent = els.get(e.parent) + if parent and any(x[0] == k for x in parent.hist): + ph = {x[0]: x for x in parent.hist} + if k in ph and k - 1 in ph and abs((ph[k][edge] - ph[k - 1][edge]) - step) < 0.5 and label in "xy": + continue # rides its parent; the parent reports it + findings.append(dict(kind=kind, element=e.name, frames=1, longest=1, at=str(k), + detail=f"{label} {prev[at_edge]:.1f} → {st[at_edge]:.1f} ({sd(i):+.1f}pt) in one frame; neighbours {before:+.1f}/{after:+.1f}")) + # motion segments, against the scroll. A motion may rest a frame or two where it + # turns (an out-and-back through its start), so up to SEG_GAP frames at rest don't + # end one. + h = mine + seg = [] + for i in range(1, len(h)): + boundary = retargeted(e, h[i][0], 1 << (edge - 1)) + if boundary and i >= 2 and i + 1 < len(h): + pts = h[i - 2:i + 2] + travel = pts[-1][edge] - pts[0][edge] + visible = all(p[5] > 0.05 and p[7] > 0 and p[8] and not p[6] & BLANK for p in pts) + instant = any(pressing[p[0]] or (p[6] >> 8) & (1 if edge <= 2 else 2) for p in pts) + stall = stalled(theirs, edge, pts, travel) if visible and not instant and abs(travel) > 0.5 else None + if stall: + k, speeds = stall + findings.append(dict(kind="stall", element=e.name, frames=1, longest=1, at=str(k), + detail=f"{label} speed {speeds[0]:.1f} → {speeds[1]:.1f} → {speeds[2]:.1f} pt/frame at a retarget")) + changed = h[i][0] - h[i - 1][0] <= SEG_GAP + 1 and abs(h[i][edge] - h[i - 1][edge]) > 0.01 + moving = changed and not boundary + if moving: + seg.append(i) + elif not boundary and seg and h[i][0] - h[seg[-1]][0] <= SEG_GAP and i < len(h) - 1: + continue + # A move starts where it first shows: what it did before (laid out in a panel + # that hasn't opened yet) nobody saw. + while seg and (h[seg[0]][5] <= 0.05 or h[seg[0]][7] == 0 or not h[seg[0]][8]): + seg.pop(0) + if (not moving or i == len(h) - 1) and len(seg) >= 4: + vals = [h[seg[0] - 1][edge]] + [h[j][edge] for j in seg] + vals = braking(e, h, seg, edge, vals) + if all(h[j][5] <= 0.05 or not h[j][8] for j in seg): + seg = [] + continue + if any(pressing[h[j][0]] or h[j][6] & BLANK for j in seg): + seg = [] + continue + # Placed where it belongs every frame, declared instant and never springing: + # a readout of something else (a scroll bar's thumb showing the offset over + # the length as the list re-anchors), whose path is that thing's, judged there. + if all((h[j][6] >> 8) & (1 if edge <= 2 else 2) and not h[j][6] & ANIMATED for j in seg): + seg = [] + continue + rest = vals[-1] + start = vals[0] + travel = rest - start + signs = [math.copysign(1, b - a) for a, b in zip(vals, vals[1:]) if abs(b - a) > 0.05] + reversals = sum(1 for a, b in zip(signs, signs[1:]) if a != b) + past = max(((v - rest) * math.copysign(1, travel) for v in vals), default=0) if abs(travel) > 0.5 else 0 + k0, k1 = h[seg[0]][0], h[seg[-1]][0] + found = len(findings) + if past > 1.0: + findings.append(dict(kind="overshoot", element=e.name, frames=k1 - k0 + 1, longest=k1 - k0 + 1, at=f"{k0}–{k1}", + detail=f"{label} {start:.1f} → {rest:.1f}, overshoots by {past:.1f}pt ({100 * past / abs(travel):.0f}%)")) + elif reversals >= 2: + amp = max(vals) - min(vals) + if amp > 0.5: + findings.append(dict(kind="jiggle", element=e.name, frames=k1 - k0 + 1, longest=k1 - k0 + 1, at=f"{k0}–{k1}", + detail=f"{label} reverses {reversals}× over {amp:.1f}pt ({start:.1f} → {rest:.1f})")) + elif reversals == 1 and not interrupted(k0, k1): + # One monotonic path: no wind-up the wrong way, no out-and-back. + if abs(travel) > 0.5: + back = max((start - v) * math.copysign(1, travel) for v in vals) + what = f"{label} {start:.1f} → {rest:.1f} heads {back:.1f}pt the wrong way first" + else: + back = max(abs(v - start) for v in vals) + what = f"{label} goes {back:.1f}pt out from {start:.1f} and back" + if back > 1.0: + findings.append(dict(kind="reversal", element=e.name, frames=k1 - k0 + 1, longest=k1 - k0 + 1, at=f"{k0}–{k1}", + detail=what)) + if len(findings) == found and abs(travel) > 0.5: + stall = stalled(theirs, edge, [h[seg[0] - 1]] + [h[j] for j in seg], travel) + if stall and not wheeled & {stall[0] - 1, stall[0], stall[0] + 1}: + k, u = stall + findings.append(dict(kind="stall", element=e.name, frames=1, longest=1, at=str(k), + detail=f"{label} speed {u[0]:.1f} → {u[1]:.1f} → {u[2]:.1f} pt/frame ({start:.1f} → {rest:.1f})")) + if not moving: + seg = [i] if boundary and changed else [] + h = e.hist + # One straight path: the top-left corner's route against its chord, per continuous move, + # against the scroll. + h = mine + seg = [] + ph = {x[0]: x for x in theirs} + for i in range(1, len(h) + 1): + boundary = i < len(h) and retargeted(e, h[i][0], 3) + changed = i < len(h) and h[i][0] == h[i - 1][0] + 1 and (abs(h[i][1] - h[i - 1][1]) > 0.01 or abs(h[i][2] - h[i - 1][2]) > 0.01) + if changed and not boundary: + seg.append(i) + continue + if len(seg) >= 4: + pts = [h[seg[0] - 1]] + [h[j] for j in seg] + # The route starts where a retarget's braking ends, as the edges' checks do. + pts = pts[max(len(pts) - len(braking(e, h, seg, edge, [p[edge] for p in pts])) for edge in (1, 2)):] + # So does a step the trace marks as designed (a column landing at its new width). + pts = pts[max((j for j in range(1, len(pts)) if (pts[j][6] >> 8) & 1), default=0):] + if len(pts) < 3: + seg = [i] if boundary and changed else [] + continue + k0, k1 = pts[1][0], pts[-1][0] + hidden = all(p[5] <= 0.05 or not p[8] for p in pts) + held = any(pressing[p[0]] or p[6] & (4 | BLANK) for p in pts) + rides = all(p[0] in ph and p[0] - 1 in ph and abs((ph[p[0]][1] - ph[p[0] - 1][1]) - (p[1] - q[1])) < 0.05 + and abs((ph[p[0]][2] - ph[p[0] - 1][2]) - (p[2] - q[2])) < 0.05 for q, p in zip(pts, pts[1:])) + if not (hidden or held or rides or interrupted(k0, k1)): + route = sum(math.hypot(p[1] - q[1], p[2] - q[2]) for q, p in zip(pts, pts[1:])) + chord = math.hypot(pts[-1][1] - pts[0][1], pts[-1][2] - pts[0][2]) + # Its own move on a moving parent (a chevron sliding along a row as the list + # scrolls) bends only by the parent's: straight against the parent is one path. + if all(p[0] in ph for p in pts): + rel = [(p[1] - ph[p[0]][1], p[2] - ph[p[0]][2]) for p in pts] + own = sum(math.hypot(b[0] - a[0], b[1] - a[1]) for a, b in zip(rel, rel[1:])) + bent = own > 1.2 * math.hypot(rel[-1][0] - rel[0][0], rel[-1][1] - rel[0][1]) + if own < route - 0.01 and (own <= JUMP_PT or not bent): + route = chord + if chord > JUMP_PT and route > 1.2 * chord: + findings.append(dict(kind="dog-leg", element=e.name, frames=k1 - k0 + 1, longest=k1 - k0 + 1, at=f"{k0}–{k1}", + detail=f"({pts[0][1]:.0f},{pts[0][2]:.0f}) → ({pts[-1][1]:.0f},{pts[-1][2]:.0f}) travels {route:.0f}pt for a {chord:.0f}pt move")) + seg = [i] if boundary and changed else [] + + # latency: input to first visible change + for k, ev in inputs: + if not ev.startswith(("press", "key", "submit", "double press", "secondary press")): + continue + j = next((j for j in range(k, min(n, k + 30)) if changed_by_frame[j]), None) + if j is None: + findings.append(dict(kind="latency", element="(input)", frames=30, longest=30, at=str(k), detail=f"{ev}: no visible change within 30 frames")) + elif j - k >= 2: + findings.append(dict(kind="latency", element="(input)", frames=j - k, longest=j - k, at=f"{k}→{j}", + detail=f"{ev}: first visible change {j - k} frames ({(j - k) * dt_ms:.0f} ms) later")) + + # hitches during motion + moving_frames = [k for k in range(1, n) if animating[k - 1]] + if moving_frames: + vals = [cpu[k] for k in moving_frames] + med = statistics.median(vals) + budget = dt_ms + bad = [k for k in moving_frames if cpu[k] > max(budget, 3 * med)] + if bad: + worst = max(bad, key=lambda k: cpu[k]) + findings.append(dict(kind="hitch", element="(frame)", frames=len(bad), longest=len(bad), at=fmt_runs(runs(bad)), + detail=f"{len(bad)} animating frames over {budget:.1f} ms CPU (median {med:.2f}, worst {cpu[worst]:.1f} at frame {worst})")) + + if acts: + findings = expectations(acts, findings, els, changes, loops, deaths, n, hz, frame_of) + + return dict(trace=path, frames=n, hz=hz, inputs=[(k, ev) for k, ev in inputs], findings=findings, + animating_frames=sum(animating), idle_frames=len(idle)) + + +def script_inputs(script): + """The script's events with the times their inputs land (a typed string is one per key, + a tap a press and a release, a drag its press and its release).""" + events = script.get("events", []) if isinstance(script, dict) else script + out = [] + for i, e in enumerate(events): + t = float(e.get("t", 0.0)) + ty = e.get("type", "tap") + end = t + if ty == "type" and "paste" not in e: + every = e.get("every", 0.035) + times = [t + every * j for j in range(max(len(e.get("text", "")), 1))] + elif ty in ("tap", "click", "secondary-click"): + times = [t, t + e.get("hold", 0.08)] + elif ty in ("double-click", "double-tap", "triple-click"): + gap = max(e.get("gap", 0.15), e.get("hold", 0.06) + 0.01) + times = [t + gap * j for j in range(3 if ty == "triple-click" else 2)] + elif ty == "drag": + end = t + max(e.get("dur", 0.3), 0.01) + 0.02 + times = [t, end] + elif ty == "scroll": + end = t + max(e.get("dur", 0.2), 0.01) + times = [t, end] + else: + times = [t] + expect = e.get("expect", []) + out.append(dict(index=i, event=e, type=ty, times=times, end=max(times[-1], end), + expect=[expect] if isinstance(expect, str) else list(expect))) + return out + + +def describe(e): + ty = e.get("type", "tap") + mods = "".join(s for m, s in (("ctrl", "⌃"), ("alt", "⌥"), ("shift", "⇧"), ("cmd", "⌘")) if e.get(m)) + if ty in ("key", "key-up"): + return f"key {mods}{e.get('name', '')}" + if ty == "type": + return f"type {e.get('text', '')!r}" + where = e.get("key") or (f"({e['x']:.0f},{e['y']:.0f})" if "x" in e else "") + return f"{ty} {where}".strip() + + +def named(name, key): + return name == key or name.endswith("/" + key) + + +def expectations(acts, findings, els, moved, background, deaths, n, hz, frame_of): + """Checks the script's `expect`ations and drops generic findings they make intended. + + instant everything the input changes lands in the frame (a cut): nothing in `scope` + (an element name part, default all) still changes two frames after it + follow a drag's `element` moves with the pointer, 1:1, on the drag's axes (or `prop`) + smooth after the input (a drag's release), `element` travels over several frames; + no single frame covers most of the move, and it doesn't land at once + leaves `element` is the one that leaves; no sibling leaves in its place + """ + times = sorted({t for a in acts for t in a["times"]}) + out = [] + instant_windows = [] # (k0, k1, scope) + dying = defaultdict(list) + for k, items in deaths.items(): + for id, rect, op, was_seen in items: + dying[id].append((k, op)) + + def next_time(t): + i = bisect.bisect_right(times, t + 1e-6) + return times[i] if i < len(times) else None + + def window(t, cap): + k0 = frame_of(t) + nt = next_time(t) + k1 = min(frame_of(nt) if nt is not None else n, k0 + int(cap * hz), n) + return k0, max(k1, k0 + 1) + + def find(key, k0, k1): + cands = [e for e in els.values() if named(e.name, key) and any(k0 - 1 <= st[0] < k1 for st in e.hist)] + return min(cands, key=lambda e: (e.flags & BLANK != 0, len(e.name))) if cands else None + + def ancestors(id): + seen_ = set() + p = els[id].parent if id in els else None + while p is not None and p not in seen_: + seen_.add(p) + yield p + p = els[p].parent if p in els else None + + def missing(a, key): + out.append(dict(kind="expect-missing", element=key, frames=0, longest=0, at=str(frame_of(a["times"][0])), + detail=f"{describe(a['event'])}: no element {key!r} to check '{'/'.join(a['expect'])}' on")) + + for a in acts: + e, label = a["event"], describe(a["event"]) + if "instant" in a["expect"]: + scope = e.get("scope", "") + bad = {} # id -> (frames, props) + for t in a["times"]: + k0, k1 = window(t, 0.6) + instant_windows.append((k0, k1, scope)) + runs_ = defaultdict(list) + # A motion already running when the input lands (an entrance settling) isn't its answer. + already = defaultdict(set) + for j in range(max(k0 - 2, 0), k0): + for id, props in moved[j].items(): + already[id] |= props + for j in range(k0, k1): + for id, props in moved[j].items(): + el = els.get(id) + # A pressed control's feedback answers the finger, not the input's effect. + props = props - {"press"} - already[id] + if el is None or not props or id in background or el.flags & BLANK or scope not in el.name: + continue + runs_[id].append((j, props)) + for id, hits in runs_.items(): + ks = [j for j, _ in hits] + # Two changes in a row, the later two frames or more after the input: motion. + late = [j for j in ks if j - 1 in ks and j >= k0 + 2] + if late: + frames_, props = bad.get(id, ([], set())) + props = props | {p for j, ps in hits if j in late or j + 1 in late for p in ps} + bad[id] = (frames_ + [j for j in ks if j >= k0 + 1], props) + tops = [id for id in bad if not any(p in bad for p in ancestors(id))] + for id in sorted(tops, key=lambda i: -len(bad[i][0]))[:4]: + ks, props = bad[id] + rs = runs(ks) + out.append(dict(kind="not-instant", element=els[id].name, frames=len(ks), longest=max(b - a_ + 1 for a_, b in rs), at=fmt_runs(rs, 2), + detail=f"{label}: {', '.join(sorted(props))} still changing {max(b - a_ + 1 for a_, b in rs)} frames in a row (expected a cut)")) + if len(tops) > 4: + out.append(dict(kind="not-instant", element=f"(+{len(tops) - 4} more)", frames=0, longest=0, at="", detail=f"{label}: more elements animate")) + if "follow" in a["expect"]: + key = e.get("element") or e.get("key", "") + t0, dur = float(e.get("t", 0.0)), max(e.get("dur", 0.3), 0.01) + k0, k1 = frame_of(t0), frame_of(t0 + dur + 0.02) + el = find(key, k0, k1) + if el is None: + missing(a, key) + else: + steps = math.ceil(dur * 120) + + def hand(t): + s = max(0, min(steps, math.floor((t - t0) / dur * steps + 1e-6))) + f = s / steps + f = f * f * (3 - 2 * f) + return e.get("dx", 0.0) * f, e.get("dy", 0.0) * f + axes = [e["prop"]] if "prop" in e else [c for c, d in (("x", "dx"), ("y", "dy")) if e.get(d)] + idx = {"x": 1, "y": 2, "w": 3, "h": 4} + pos = {st[0]: st for st in el.hist} + off, started = [], False + drift = defaultdict(float) + for j in range(k0 + 1, k1): + if j not in pos or j - 1 not in pos: + continue + tj, tp = j / hz, (j - 1) / hz + for c in axes: + de = pos[j][idx[c]] - pos[j - 1][idx[c]] + dh = hand(tj)[0 if c in "xw" else 1] - hand(tp)[0 if c in "xw" else 1] + # The first move picks up what the hand moved inside the drag's slop. + pickup = not started and abs(de) > 0.05 + started |= pickup + # Held at a limit (the list's end, a minimum width), it may stop; while + # it moves, it moves with the hand, so a spring trailing it drifts off. + if started and not pickup and abs(de) > 0.05: + drift[c] += de - dh + if abs(drift[c]) > 2.0 or abs(de - dh) > 1.0: + off.append((j, drift[c] if abs(drift[c]) > 2.0 else de - dh)) + if not started and any(abs(v) > 1.0 for v in hand(t0 + dur)): + out.append(dict(kind="lags-hand", element=el.name, frames=0, longest=0, at=str(k0), + detail=f"{label}: doesn't move while the pointer drags it")) + elif len(off) >= 2: + worst = max(off, key=lambda o: abs(o[1])) + out.append(dict(kind="lags-hand", element=el.name, frames=len(off), longest=len(off), at=fmt_runs(runs([j for j, _ in off]), 2), + detail=f"{label}: moves off the pointer on {len(off)} frames (worst {worst[1]:+.1f}pt at frame {worst[0]}); a drag follows the hand 1:1")) + if "smooth" in a["expect"]: + key = e.get("element") or e.get("key", "") + k0, k1 = window(a["end"], 1.2) + el = find(key, k0, k1) + if el is None: + missing(a, key) + else: + h = [st for st in el.hist if k0 - 1 <= st[0] < k1] + born = el.born is not None and k0 - 1 <= el.born < k1 + worst = None + travel = 0.0 + for c, label_c in ((1, "x"), (2, "y"), (3, "w"), (4, "h")): + vals = [st[c] for st in h] + total = vals[-1] - vals[0] if vals else 0.0 + travel = max(travel, abs(total)) + steps_ = [b - a_ for a_, b in zip(vals, vals[1:])] + if abs(total) > JUMP_PT and steps_: + big = max(steps_, key=abs) + moving = sum(1 for s in steps_ if abs(s) > 0.05) + if abs(big) > 0.5 * abs(total) or moving < 3: + if worst is None or abs(big) > abs(worst[1]): + worst = (label_c, big, total, moving) + if worst: + c, big, total, moving = worst + out.append(dict(kind="snap", element=el.name, frames=moving, longest=moving, at=str(k0), + detail=f"{label}: {c} covers {big:+.1f}pt of its {total:+.1f}pt move in one frame ({moving} moving frames)")) + elif born and travel < 4 and h and h[0][5] >= POP_OPACITY: + out.append(dict(kind="snap", element=el.name, frames=1, longest=1, at=str(el.born), + detail=f"{label}: appears at its place with no travel ({h[0][3]:.0f}×{h[0][4]:.0f} at {h[0][1]:.0f},{h[0][2]:.0f})")) + if "leaves" in a["expect"]: + key = e.get("element") or e.get("key", "") + k0, k1 = window(a["end"], 1.2) + el = find(key, k0, k1) + if el is None: + missing(a, key) + else: + def leaves(x): + if any(k0 <= k < k1 for k, _ in dying[x.id]): + return True + ops = [st[5] for st in x.hist if k0 - 1 <= st[0] < k1] + return bool(ops) and ops[0] > POP_OPACITY and ops[-1] <= VISIBLE_OPACITY + gone = [x for x in els.values() if x.parent == el.parent and x.id != el.id and not x.flags & BLANK and leaves(x)] + if not leaves(el) or gone: + who = ", ".join(short(x.name, 1) for x in gone[:3]) or "nothing" + out.append(dict(kind="wrong-exit", element=el.name, frames=1, longest=1, at=str(k0), + detail=f"{label}: expected {short(el.name, 1)} to leave; {'it stays and ' if not leaves(el) else ''}{who} leave{'s' if len(gone) == 1 else ''}" + + " (index keys?)")) + + # What an instant input changes is meant to cut: pops and jumps inside its window aren't findings. + cuts = {"pop-in", "pop-out", "appear-then-jump", "jump", "step", "sibling-jump", "cut-exit"} + + def intended(f): + if f["kind"] not in cuts: + return False + k = int(f["at"].split("–")[0]) if f["at"][:1].isdigit() else -1 + return any(k0 <= k < k1 + 1 and scope in f["element"] for k0, k1, scope in instant_windows) + return [f for f in findings if not intended(f)] + out + + +def trace_name(path): + name = path.rsplit("/", 1)[-1] + return name[:-6] if name.endswith(".jsonl") else name + + +def allowed(rules, trace, f): + """The allowlist rule that covers finding `f` in `trace`, if any.""" + for r in rules: + kind = r.get("kind", f["kind"]) + if r.get("trace", trace) == trace and f["kind"] in ([kind] if isinstance(kind, str) else kind) \ + and r.get("element", "") in f["element"]: + return r + return None + + +def main(): + args = sys.argv[1:] + out = allow_path = None + quiet = "--quiet" in args + fail = "--fail" in args + args = [a for a in args if a not in ("--quiet", "--fail")] + for flag in ("--json", "--allow"): + if flag in args: + i = args.index(flag) + if flag == "--json": + out = args[i + 1] + else: + allow_path = args[i + 1] + del args[i:i + 2] + jobs, script = [], None + i = 0 + while i < len(args): + if args[i] == "--script": + with open(args[i + 1]) as f: + script = json.load(f) + i += 2 + continue + jobs.append((args[i], script)) + script = None + i += 1 + rules = [] + if allow_path: + with open(allow_path) as f: + rules = json.load(f) + for r in rules: + if not r.get("reason"): + sys.exit(f"{allow_path}: every rule needs a reason: {r}") + reports = [analyze(p, s) for p, s in jobs] + used, open_ = set(), 0 + for r in reports: + name = trace_name(r["trace"]) + for f in r["findings"]: + rule = allowed(rules, name, f) + f["allowed"] = rule["reason"] if rule else None + if rule: + used.add(id(rule)) + live = [f for f in r["findings"] if not f["allowed"]] + open_ += len(live) + print(f"== {name}: {r['frames']} frames, {r['animating_frames']} animating, {r['idle_frames']} idle, {len(live)} findings" + + (f" (+{len(r['findings']) - len(live)} allowed)" if len(live) < len(r["findings"]) else "")) + if quiet: + continue + for f in sorted(live, key=lambda f: (f["kind"], -f["frames"])): + print(f" {f['kind']:<16} {short(f['element']):<60} @{f['at']:<14} {f['detail']}") + ran = {trace_name(r["trace"]) for r in reports} + for r in rules: + # Only a rule for one trace this run recorded can go stale; a general rule may wait. + if id(r) not in used and r.get("trace") in ran: + print(f" unused allow rule: {json.dumps(r, ensure_ascii=False)}") + if out: + with open(out, "w") as f: + json.dump(reports, f, indent=1) + if fail: + print(f"{open_} finding{'' if open_ == 1 else 's'} not in the allowlist" if open_ else "no findings outside the allowlist") + sys.exit(1 if open_ else 0) + + +if __name__ == "__main__": + main() diff --git a/app/vendor/rune/scripts/motion-audit/gate b/app/vendor/rune/scripts/motion-audit/gate new file mode 100644 index 0000000..2bd4c41 --- /dev/null +++ b/app/vendor/rune/scripts/motion-audit/gate @@ -0,0 +1,37 @@ +#!/usr/bin/env bash +# Runs an app's motion gate (`rune::motion_gate::gate` in one of its tests) and prints one line per +# finding: kind, element, frame, detail and cell. Everything after `--` goes to `cargo test`, so it +# names the app's package and test: +# scripts/motion-audit/gate [CELL-FILTER] -- -p my-app motion_gate +# scripts/motion-audit/gate --sheet 'add-row/wide|134[|path part]' -- -p my-app motion_gate +# scripts/motion-audit/gate --dump 'add-row/wide|path part[|from|to]' -- -p my-app motion_gate +# scripts/motion-audit/gate --allowed [CELL-FILTER] -- … also list allowlisted findings +# `--sheet` writes a contact strip of the frames around one, the path part's outlines in red; +# `--dump` writes those tracks' frames. Both name a cell, which is also the filter. +# MOTION_GATE_OUT names the report file (default $TMPDIR/motion-gate). MOTION_GATE_WRAP runs the +# test under a command prefix (a build-queue lease, say); without it, it's plain cargo. +set -euo pipefail +OUT=${MOTION_GATE_OUT:-${TMPDIR:-/tmp}/motion-gate} +export MOTION_GATE_OUT=$OUT +filter="" +while [[ $# -gt 0 ]]; do + case "$1" in + --sheet) export MOTION_GATE_SHEET=$2; filter=${2%%|*}; shift 2 ;; + --dump) export MOTION_GATE_DUMP=$2; filter=${2%%|*}; shift 2 ;; + --allowed) export MOTION_GATE_ALLOWED=1; shift ;; + -h|--help) sed -n '2,13p' "$0"; exit 0 ;; + --) shift; break ;; + *) filter=$1; shift ;; + esac +done +[[ $# -gt 0 ]] || { echo "motion gate: name the app's test after --, e.g. -- -p my-app motion_gate" >&2; exit 2; } +export MOTION_GATE=$filter +rm -f "$OUT" "$OUT.sheet.png" "$OUT.dump" +wrap=() +[[ -n ${MOTION_GATE_WRAP:-} ]] && read -r -a wrap <<<"$MOTION_GATE_WRAP" +status=0 +${wrap[@]+"${wrap[@]}"} cargo test -q "$@" >/dev/null 2>&1 || status=$? +if [[ -s "$OUT" ]]; then cat "$OUT"; else echo "motion gate: the test didn't run (exit $status); run cargo test $* to see why" >&2; exit 1; fi +[[ -f "$OUT.sheet.png" ]] && echo "sheet: $OUT.sheet.png" +[[ -f "$OUT.dump" ]] && echo "dump: $OUT.dump" +exit $status diff --git a/app/vendor/rune/scripts/motion-audit/motion-trace.py b/app/vendor/rune/scripts/motion-audit/motion-trace.py new file mode 100644 index 0000000..9162615 --- /dev/null +++ b/app/vendor/rune/scripts/motion-audit/motion-trace.py @@ -0,0 +1,73 @@ +#!/usr/bin/env python3 +"""Reads an app's own motion trace, recorded in the installed app on real data, and prints, for +each key press, how many frames until a watched element first moved, and every frame of the move +that went over budget. + + scripts/motion-audit/motion-trace.py TRACE.jsonl [--key Enter] [--frames 40] [--budget 16.7] + +The trace is JSON lines the app writes (README.md, "Tracing the real app"): + {"k":"key","ms":…,"key":"Enter"} a key, as the app's handler got it + {"k":"span","ms":…,"name":"load","dur":…} time spent in one step on the main thread + {"k":"frame","ms":…,"update":…,"render":…,"rows":{"row-1":[y,h,opacity],…}} +`ms` is wall time since launch at the start of the step. A frame's cost is Rune's update +(handlers, poll, view, layout) plus the compositor's render; over the budget, the display shows +the previous frame again. `rows` holds whatever the app watches, by id, as numbers that change +when it moves. Spans over 1 ms in the frame are listed beside it. +""" +import argparse +import json + +ap = argparse.ArgumentParser() +ap.add_argument("trace") +ap.add_argument("--key", default="Enter") +ap.add_argument("--frames", type=int, default=40) +ap.add_argument("--budget", type=float, default=1000 / 60) +a = ap.parse_args() +lines = [json.loads(l) for l in open(a.trace) if l.strip()] +frames = [l for l in lines if l["k"] == "frame"] +spans = [l for l in lines if l["k"] == "span"] +keys = [l for l in lines if l["k"] == "key" and a.key in l["key"]] + + +def start(f): + return f["ms"] - f["update"] + + +def moved(a_, b): + rows_a, rows_b = a_.get("rows", {}), b.get("rows", {}) + for id_, r in rows_a.items(): + o = rows_b.get(id_) + if o is None or any(abs(x - y) > 0.01 for x, y in zip(o, r)): + return True + return any(id_ not in rows_a for id_ in rows_b) + + +print(a.trace) +for k in keys: + i = next((i for i, f in enumerate(frames) if f["ms"] >= k["ms"]), None) + if i is None: + continue + key_frame = frames[i] + first = next((j for j in range(i + 1, len(frames)) if moved(frames[j - 1], frames[j])), None) + # The key frame itself already moved rows: the move started on it. + if moved(frames[i - 1], key_frame) if i else False: + first = i + sel = f" (sel {key_frame['sel']})" if "sel" in key_frame else "" + print(f"\n{k['key']} at {k['ms']:.0f} ms, handled in the frame starting {start(key_frame):.0f} ms{sel}") + if first is None: + print(" nothing watched moved") + continue + print(f" first moved frame: +{first - i} frames, {frames[first]['ms'] + frames[first]['render'] - k['ms']:.0f} ms from the key to its render's end") + over = 0 + for j in range(i, min(len(frames), i + a.frames)): + f = frames[j] + cost = f["update"] + f["render"] + gap = start(f) - (frames[j - 1]["ms"] + frames[j - 1]["render"]) if j else 0 + if cost > a.budget: + over += 1 + mark = "OVER" if cost > a.budget else " " + big = [s for s in spans if start(f) <= s["ms"] < f["ms"] + f["render"] and s["dur"] > 1.0] + moving = "move" if j and moved(frames[j - 1], f) else " " + names = ", ".join(f"{s['name']} {s['dur']:.1f}" for s in big) + print(f" {mark} +{j - i:2d} {moving} update {f['update']:6.1f} render {f['render']:5.1f} idle-before {gap:6.1f} {names}") + print(f" frames over {a.budget:.1f} ms in the first {a.frames}: {over}") diff --git a/app/vendor/rune/scripts/motion-audit/run.sh b/app/vendor/rune/scripts/motion-audit/run.sh new file mode 100644 index 0000000..9d93bb0 --- /dev/null +++ b/app/vendor/rune/scripts/motion-audit/run.sh @@ -0,0 +1,65 @@ +#!/bin/sh +# Records a motion trace of every element (--trace-all) for each scenario below, at 120 fps on +# the virtual clock, plus the final element tree and what rune::motion_gate finds (<name>.gate.txt). +# Then scripts/motion-audit/analyze.py reads them. +# Run from the repo root: scripts/motion-audit/run.sh [out-dir] (default target/motion-audit). +set -e +O=${1:-target/motion-audit} +mkdir -p "$O" +MOTION_GATE_OUT="$O/live-tail.gate.txt" sh scripts/motion-audit/scenarios/live-tail.sh +cargo build --release -p todo -p settings -p kit-gallery -p odometer +cargo build --release -p rune-kit --features rune/tooling --example shell --example tab_strip +cargo build --release -p rune --features tooling --example growth_reorder --example keep_stuck --example sticky --example scroll_keys --example scroll_anchor --example text_glide --example one_snap +B=${CARGO_TARGET_DIR:-target}/release +SH=$B/examples/shell +GR=$B/examples/growth_reorder +KS=$B/examples/keep_stuck +S=scripts/motion-audit/scenarios +FPS=120 + +# name | seconds | command (trace args appended) +run() { + name=$1; secs=$2; shift 2 + frames=$(python3 -c "print(int($secs * $FPS))") + echo "== $name ($frames frames)" + RUNE_MOTION_GATE="$O/$name.gate.txt" "$@" --fps $FPS --frames "$frames" --trace-all --trace "$O/$name.jsonl" --tree "$O/$name-end.json" +} + +run todo-add-remove 4.4 $B/todo --script $S/todo-add-remove.json +run settings-toggle-retarget 1.5 $B/settings --script examples/settings/scripts/toggle-retarget.json +run settings-segmented-retarget 1.5 $B/settings --script examples/settings/scripts/segmented-retarget.json +run settings-slider 3.0 $B/settings --script examples/settings/scripts/slider.json +run settings-hover 3.0 $B/settings --script examples/settings/scripts/hover.json +run gallery-combobox 3.0 $B/kit-gallery --scene rune-combobox--searchable --script examples/kit-gallery/scripts/combobox.json +run gallery-combobox-animated 3.0 $B/kit-gallery --scene rune-combobox--animated-filter --script examples/kit-gallery/scripts/combobox-animated-filter.json +run gallery-scroll-bar 4.0 $B/kit-gallery --scene rune-scroll-bar--basic --script $S/gallery-scroll-bar.json +run gallery-scroll-bar-hover 3.2 $B/kit-gallery --scene rune-scroll-bar--basic --script $S/gallery-scroll-bar-hover.json +run gallery-scroll-bar-grow 2.4 $B/kit-gallery --scene rune-scroll-bar--grow --scroll-bars always --script $S/gallery-scroll-bar-grow.json +run gallery-modal 5.5 $B/kit-gallery --scene motion-focus-modal --script examples/kit-gallery/scripts/motion-focus-modal.json +run gallery-stagger-list 3.0 $B/kit-gallery --scene motion-stagger-list --script examples/kit-gallery/scripts/motion-stagger-list.json +run gallery-mermaid-stream 4.5 $B/kit-gallery --scene rune-markdown--mermaid-streaming --size 1100x1400 --script $S/gallery-mermaid-stream.json +run gallery-markdown-stream-tail 3.0 $B/kit-gallery --scene rune-markdown--stream-tail --script $S/gallery-markdown-stream-tail.json +run odometer 5.4 $B/odometer --script $S/odometer.json +run shell-idle 2.0 $SH +run shell-toggle 3.0 $SH --script $S/shell-toggle.json +run shell-peek 5.0 $SH --script $S/shell-peek.json +run shell-resize 3.6 $SH --script $S/shell-resize.json +run shell-reorder 3.6 $SH --script $S/shell-reorder.json +run shell-virtual-peek 5.0 $SH virtual --script $S/shell-peek.json +run shell-virtual-reorder 3.6 $SH virtual --script $S/shell-reorder-virtual.json +run shell-window-resize 3.0 $SH --script $S/shell-window-resize.json +run shell-virtual-window-resize 3.0 $SH virtual --script $S/shell-window-resize.json +run tab-strip 9.0 $B/examples/tab_strip --script $S/tab-strip.json +run growth-reorder 4.2 $GR --script $S/growth-reorder.json +run growth-reorder-virtual 4.0 $GR virtual --script $S/growth-reorder-virtual.json +run keep-stuck 3.2 $KS --script $S/keep-stuck.json +run growth-reorder-grow 3.5 $GR steer --script $S/growth-reorder-grow.json +run growth-reorder-gap 4.7 $GR steer --script $S/growth-reorder-gap.json +run growth-reorder-flight 2.6 $GR steer --script $S/growth-reorder-flight.json +run sticky-scroll 1.6 $B/examples/sticky --script crates/rune/examples/sticky.json +run scroll-keys 3.2 $B/examples/scroll_keys --script $S/scroll-keys.json +run wheel-distance 1.2 $B/examples/scroll_keys --script $S/wheel-distance.json +run scroll-anchor 3.4 $B/examples/scroll_anchor --script $S/scroll-anchor.json +run text-glide 3.8 $B/examples/text_glide --script $S/text-glide.json +run one-snap 4.4 $B/examples/one_snap --script $S/one-snap.json +ls "$O" diff --git a/app/vendor/rune/scripts/motion-audit/scenarios/gallery-markdown-stream-tail.json b/app/vendor/rune/scripts/motion-audit/scenarios/gallery-markdown-stream-tail.json new file mode 100644 index 0000000..474a453 --- /dev/null +++ b/app/vendor/rune/scripts/motion-audit/scenarios/gallery-markdown-stream-tail.json @@ -0,0 +1,7 @@ +[ + {"t":0.2,"type":"tap","key":"stream-more"}, + {"t":0.6,"type":"tap","key":"stream-more"}, + {"t":1.0,"type":"tap","key":"stream-more"}, + {"t":1.4,"type":"tap","key":"stream-more"}, + {"t":1.8,"type":"tap","key":"stream-more"} +] diff --git a/app/vendor/rune/scripts/motion-audit/scenarios/gallery-mermaid-stream.json b/app/vendor/rune/scripts/motion-audit/scenarios/gallery-mermaid-stream.json new file mode 100644 index 0000000..be599c6 --- /dev/null +++ b/app/vendor/rune/scripts/motion-audit/scenarios/gallery-mermaid-stream.json @@ -0,0 +1,16 @@ +[ + {"t":0.2,"type":"tap","key":"stream-more"}, + {"t":0.45,"type":"tap","key":"stream-more"}, + {"t":0.7,"type":"tap","key":"stream-more"}, + {"t":0.95,"type":"tap","key":"stream-more"}, + {"t":1.2,"type":"tap","key":"stream-more"}, + {"t":1.45,"type":"tap","key":"stream-more"}, + {"t":1.7,"type":"tap","key":"stream-more"}, + {"t":1.95,"type":"tap","key":"stream-more"}, + {"t":2.2,"type":"tap","key":"stream-more"}, + {"t":2.45,"type":"tap","key":"stream-more"}, + {"t":2.7,"type":"tap","key":"stream-more"}, + {"t":2.95,"type":"tap","key":"stream-more"}, + {"t":3.2,"type":"tap","key":"stream-more"}, + {"t":3.45,"type":"tap","key":"stream-more"} +] diff --git a/app/vendor/rune/scripts/motion-audit/scenarios/gallery-scroll-bar-grow.json b/app/vendor/rune/scripts/motion-audit/scenarios/gallery-scroll-bar-grow.json new file mode 100644 index 0000000..4beb4ac --- /dev/null +++ b/app/vendor/rune/scripts/motion-audit/scenarios/gallery-scroll-bar-grow.json @@ -0,0 +1,5 @@ +[ + { "t": 0.3, "type": "tap", "key": "more" }, + { "t": 1.3, "type": "tap", "key": "more" }, + { "t": 2.4, "type": "mark", "name": "end" } +] diff --git a/app/vendor/rune/scripts/motion-audit/scenarios/gallery-scroll-bar-hover.json b/app/vendor/rune/scripts/motion-audit/scenarios/gallery-scroll-bar-hover.json new file mode 100644 index 0000000..6e46553 --- /dev/null +++ b/app/vendor/rune/scripts/motion-audit/scenarios/gallery-scroll-bar-hover.json @@ -0,0 +1,6 @@ +[ + { "t": 0.25, "type": "move", "key": "item-3" }, + { "t": 0.6, "type": "move", "key": "thumb" }, + { "t": 1.4, "type": "move", "key": "item-3" }, + { "t": 3.2, "type": "mark", "name": "end" } +] diff --git a/app/vendor/rune/scripts/motion-audit/scenarios/gallery-scroll-bar.json b/app/vendor/rune/scripts/motion-audit/scenarios/gallery-scroll-bar.json new file mode 100644 index 0000000..90ae822 --- /dev/null +++ b/app/vendor/rune/scripts/motion-audit/scenarios/gallery-scroll-bar.json @@ -0,0 +1,5 @@ +[ + { "t": 0.25, "type": "scroll", "key": "feed", "dy": -260, "dur": 0.45 }, + { "t": 1.9, "type": "scroll", "key": "feed", "dy": 140, "dur": 0.35 }, + { "t": 4.0, "type": "mark", "name": "end" } +] diff --git a/app/vendor/rune/scripts/motion-audit/scenarios/growth-reorder-flight.json b/app/vendor/rune/scripts/motion-audit/scenarios/growth-reorder-flight.json new file mode 100644 index 0000000..359e539 --- /dev/null +++ b/app/vendor/rune/scripts/motion-audit/scenarios/growth-reorder-flight.json @@ -0,0 +1,7 @@ +{ + "events": [ + { "t": 0.38, "type": "tap", "key": "composer", "hold": 0 }, + { "t": 0.47, "type": "tap", "key": "working", "hold": 0, "expect": "smooth" }, + { "t": 1.5, "type": "move", "x": 10, "y": 10 } + ] +} diff --git a/app/vendor/rune/scripts/motion-audit/scenarios/growth-reorder-gap.json b/app/vendor/rune/scripts/motion-audit/scenarios/growth-reorder-gap.json new file mode 100644 index 0000000..ef21b20 --- /dev/null +++ b/app/vendor/rune/scripts/motion-audit/scenarios/growth-reorder-gap.json @@ -0,0 +1,8 @@ +{ + "events": [ + { "t": 0.3, "type": "tap", "key": "composer" }, + { "t": 0.9, "type": "tap", "key": "composer" }, + { "t": 2.6, "type": "tap", "key": "working", "expect": "smooth" }, + { "t": 4.6, "type": "move", "x": 10, "y": 10 } + ] +} diff --git a/app/vendor/rune/scripts/motion-audit/scenarios/growth-reorder-grow.json b/app/vendor/rune/scripts/motion-audit/scenarios/growth-reorder-grow.json new file mode 100644 index 0000000..bf21f11 --- /dev/null +++ b/app/vendor/rune/scripts/motion-audit/scenarios/growth-reorder-grow.json @@ -0,0 +1,7 @@ +{ + "events": [ + { "t": 0.3, "type": "tap", "key": "composer" }, + { "t": 1.8, "type": "tap", "key": "working", "expect": "smooth" }, + { "t": 3.4, "type": "move", "x": 10, "y": 10 } + ] +} diff --git a/app/vendor/rune/scripts/motion-audit/scenarios/growth-reorder-virtual.json b/app/vendor/rune/scripts/motion-audit/scenarios/growth-reorder-virtual.json new file mode 100644 index 0000000..053cfff --- /dev/null +++ b/app/vendor/rune/scripts/motion-audit/scenarios/growth-reorder-virtual.json @@ -0,0 +1,8 @@ +{ + "events": [ + { "t": 0.3, "type": "tap", "key": "v1", "expect": "smooth" }, + { "t": 1.4, "type": "tap", "key": "v0", "expect": "smooth" }, + { "t": 2.5, "type": "scroll", "x": 200, "y": 200, "dy": -300 }, + { "t": 3.6, "type": "move", "x": 10, "y": 10 } + ] +} diff --git a/app/vendor/rune/scripts/motion-audit/scenarios/growth-reorder.json b/app/vendor/rune/scripts/motion-audit/scenarios/growth-reorder.json new file mode 100644 index 0000000..01429d6 --- /dev/null +++ b/app/vendor/rune/scripts/motion-audit/scenarios/growth-reorder.json @@ -0,0 +1,9 @@ +{ + "events": [ + { "t": 0.3, "type": "tap", "key": "working", "expect": "smooth" }, + { "t": 1.4, "type": "tap", "key": "working", "expect": "smooth" }, + { "t": 1.5, "type": "tap", "key": "working", "expect": "smooth" }, + { "t": 2.6, "type": "tap", "key": "m1", "expect": "smooth" }, + { "t": 3.8, "type": "move", "x": 10, "y": 10 } + ] +} diff --git a/app/vendor/rune/scripts/motion-audit/scenarios/keep-stuck.json b/app/vendor/rune/scripts/motion-audit/scenarios/keep-stuck.json new file mode 100644 index 0000000..39cf706 --- /dev/null +++ b/app/vendor/rune/scripts/motion-audit/scenarios/keep-stuck.json @@ -0,0 +1,7 @@ +{ + "events": [ + { "t": 0.3, "type": "scroll", "x": 210, "y": 180, "dy": 450, "dur": 0.4 }, + { "t": 1.2, "type": "tap", "key": "hdr", "expect": "smooth", "element": "answer" }, + { "t": 3.0, "type": "move", "x": 10, "y": 10 } + ] +} diff --git a/app/vendor/rune/scripts/motion-audit/scenarios/live-tail.sh b/app/vendor/rune/scripts/motion-audit/scenarios/live-tail.sh new file mode 100644 index 0000000..4a48ef5 --- /dev/null +++ b/app/vendor/rune/scripts/motion-audit/scenarios/live-tail.sh @@ -0,0 +1,3 @@ +#!/bin/sh +# A poll delivers a pending row; unchanged window, resizing, and reading above the end. +exec scripts/motion-audit/gate live-tail -- -p rune --lib live_tail_motion_gate diff --git a/app/vendor/rune/scripts/motion-audit/scenarios/odometer.json b/app/vendor/rune/scripts/motion-audit/scenarios/odometer.json new file mode 100644 index 0000000..c8ef9cf --- /dev/null +++ b/app/vendor/rune/scripts/motion-audit/scenarios/odometer.json @@ -0,0 +1,11 @@ +{ + "events": [ + {"t": 0.3, "type": "tap", "key": "up", "expect": "smooth", "element": "secs.3"}, + {"t": 1.1, "type": "tap", "key": "down", "expect": "smooth", "element": "secs.5"}, + {"t": 1.9, "type": "tap", "key": "up"}, + {"t": 1.98, "type": "tap", "key": "down", "expect": "smooth", "element": "secs.8"}, + {"t": 2.8, "type": "tap", "key": "down", "expect": "smooth", "element": "count.8"}, + {"t": 3.4, "type": "tap", "key": "step"}, + {"t": 4.2, "type": "tap", "key": "big"} + ] +} diff --git a/app/vendor/rune/scripts/motion-audit/scenarios/one-snap.json b/app/vendor/rune/scripts/motion-audit/scenarios/one-snap.json new file mode 100644 index 0000000..343433d --- /dev/null +++ b/app/vendor/rune/scripts/motion-audit/scenarios/one-snap.json @@ -0,0 +1,7 @@ +{ + "events": [ + { "t": 0.25, "type": "tap", "key": "stage", "expect": "smooth", "element": "hud" }, + { "t": 1.6, "type": "tap", "key": "badge", "expect": "instant", "scope": "hud" }, + { "t": 2.4, "type": "tap", "key": "stage", "expect": "smooth", "element": "hud" } + ] +} diff --git a/app/vendor/rune/scripts/motion-audit/scenarios/scroll-anchor.json b/app/vendor/rune/scripts/motion-audit/scenarios/scroll-anchor.json new file mode 100644 index 0000000..408a4cd --- /dev/null +++ b/app/vendor/rune/scripts/motion-audit/scenarios/scroll-anchor.json @@ -0,0 +1,8 @@ +{ + "events": [ + { "t": 0.3, "type": "scroll", "key": "feed", "dy": -600, "dur": 0.4 }, + { "t": 1.4, "type": "key", "name": "Enter" }, + { "t": 2.4, "type": "key", "name": "Enter" }, + { "t": 3.4, "type": "mark", "name": "end" } + ] +} diff --git a/app/vendor/rune/scripts/motion-audit/scenarios/scroll-keys.json b/app/vendor/rune/scripts/motion-audit/scenarios/scroll-keys.json new file mode 100644 index 0000000..fff8341 --- /dev/null +++ b/app/vendor/rune/scripts/motion-audit/scenarios/scroll-keys.json @@ -0,0 +1,40 @@ +{ + "events": [ + {"t": 0.1, "type": "move", "x": 200, "y": 220}, + {"t": 0.3, "type": "key", "name": "Down", "expect": "smooth", "element": "card-5"}, + {"t": 0.55, "type": "key", "name": "Down", "repeat": true}, + {"t": 0.5833, "type": "key", "name": "Down", "repeat": true}, + {"t": 0.6167, "type": "key", "name": "Down", "repeat": true}, + {"t": 0.65, "type": "key", "name": "Down", "repeat": true}, + {"t": 0.6833, "type": "key", "name": "Down", "repeat": true}, + {"t": 0.7167, "type": "key", "name": "Down", "repeat": true}, + {"t": 0.75, "type": "key", "name": "Down", "repeat": true}, + {"t": 0.7833, "type": "key", "name": "Down", "repeat": true}, + {"t": 0.8167, "type": "key", "name": "Down", "repeat": true}, + {"t": 0.85, "type": "key", "name": "Down", "repeat": true}, + {"t": 0.8833, "type": "key", "name": "Down", "repeat": true}, + {"t": 0.9167, "type": "key", "name": "Down", "repeat": true}, + {"t": 0.95, "type": "key", "name": "Down", "repeat": true}, + {"t": 0.9833, "type": "key", "name": "Down", "repeat": true}, + {"t": 1.0167, "type": "key", "name": "Down", "repeat": true}, + {"t": 1.05, "type": "key", "name": "Down", "repeat": true}, + {"t": 1.0833, "type": "key", "name": "Down", "repeat": true}, + {"t": 1.1167, "type": "key", "name": "Down", "repeat": true}, + {"t": 1.15, "type": "key", "name": "Down", "repeat": true}, + {"t": 1.1833, "type": "key", "name": "Down", "repeat": true}, + {"t": 1.2167, "type": "key", "name": "Down", "repeat": true}, + {"t": 1.25, "type": "key", "name": "Down", "repeat": true}, + {"t": 1.2833, "type": "key", "name": "Down", "repeat": true}, + {"t": 1.3167, "type": "key", "name": "Down", "repeat": true}, + {"t": 1.35, "type": "key", "name": "Down", "repeat": true}, + {"t": 1.3833, "type": "key", "name": "Down", "repeat": true}, + {"t": 1.4167, "type": "key", "name": "Down", "repeat": true}, + {"t": 1.45, "type": "key", "name": "Down", "repeat": true}, + {"t": 1.4833, "type": "key", "name": "Down", "repeat": true}, + {"t": 1.5167, "type": "key", "name": "Down", "repeat": true}, + {"t": 2.2, "type": "key", "name": "Up"}, + {"t": 2.32, "type": "key", "name": "Up"}, + {"t": 2.44, "type": "key", "name": "Up"}, + {"t": 3.2, "type": "mark", "name": "end"} + ] +} diff --git a/app/vendor/rune/scripts/motion-audit/scenarios/shell-peek.json b/app/vendor/rune/scripts/motion-audit/scenarios/shell-peek.json new file mode 100644 index 0000000..26f4912 --- /dev/null +++ b/app/vendor/rune/scripts/motion-audit/scenarios/shell-peek.json @@ -0,0 +1,12 @@ +{ + "events": [ + { "t": 0.3, "type": "tap", "key": "sidebar-toggle" }, + { "t": 0.9, "type": "move", "x": 700, "y": 400 }, + { "t": 1.3, "type": "move", "x": 10, "y": 300 }, + { "t": 1.9, "type": "move", "x": 150, "y": 300 }, + { "t": 2.5, "type": "move", "x": 700, "y": 300 }, + { "t": 3.2, "type": "move", "key": "sidebar-toggle" }, + { "t": 3.7, "type": "tap", "key": "sidebar-toggle" }, + { "t": 4.4, "type": "move", "x": 700, "y": 400 } + ] +} diff --git a/app/vendor/rune/scripts/motion-audit/scenarios/shell-reorder-virtual.json b/app/vendor/rune/scripts/motion-audit/scenarios/shell-reorder-virtual.json new file mode 100644 index 0000000..158d206 --- /dev/null +++ b/app/vendor/rune/scripts/motion-audit/scenarios/shell-reorder-virtual.json @@ -0,0 +1,8 @@ +{ + "events": [ + { "t": 0.3, "type": "drag", "key": "v1", "dy": 120, "dur": 0.6 }, + { "t": 1.6, "type": "drag", "key": "v0", "dy": 160, "dur": 0.8 }, + { "t": 2.1, "type": "key", "name": "Escape" }, + { "t": 3.2, "type": "move", "x": 700, "y": 400 } + ] +} diff --git a/app/vendor/rune/scripts/motion-audit/scenarios/shell-reorder.json b/app/vendor/rune/scripts/motion-audit/scenarios/shell-reorder.json new file mode 100644 index 0000000..2de31e7 --- /dev/null +++ b/app/vendor/rune/scripts/motion-audit/scenarios/shell-reorder.json @@ -0,0 +1,8 @@ +{ + "events": [ + { "t": 0.3, "type": "drag", "key": "s2", "dy": 120, "dur": 0.6 }, + { "t": 1.6, "type": "drag", "key": "s1", "dy": 160, "dur": 0.8 }, + { "t": 2.1, "type": "key", "name": "Escape" }, + { "t": 3.2, "type": "move", "x": 700, "y": 400 } + ] +} diff --git a/app/vendor/rune/scripts/motion-audit/scenarios/shell-resize.json b/app/vendor/rune/scripts/motion-audit/scenarios/shell-resize.json new file mode 100644 index 0000000..9d80285 --- /dev/null +++ b/app/vendor/rune/scripts/motion-audit/scenarios/shell-resize.json @@ -0,0 +1,9 @@ +{ + "events": [ + { "t": 0.3, "type": "move", "key": "sidebar-grip" }, + { "t": 0.6, "type": "drag", "key": "sidebar-grip", "dx": 140, "dur": 0.5 }, + { "t": 1.5, "type": "drag", "key": "sidebar-grip", "dx": -320, "dur": 0.6 }, + { "t": 2.5, "type": "double-click", "key": "sidebar-grip" }, + { "t": 3.3, "type": "move", "x": 700, "y": 400 } + ] +} diff --git a/app/vendor/rune/scripts/motion-audit/scenarios/shell-toggle.json b/app/vendor/rune/scripts/motion-audit/scenarios/shell-toggle.json new file mode 100644 index 0000000..2e094e6 --- /dev/null +++ b/app/vendor/rune/scripts/motion-audit/scenarios/shell-toggle.json @@ -0,0 +1,8 @@ +{ + "events": [ + { "t": 0.3, "type": "tap", "key": "sidebar-toggle" }, + { "t": 1.0, "type": "move", "x": 700, "y": 400 }, + { "t": 1.3, "type": "tap", "key": "sidebar-toggle" }, + { "t": 2.2, "type": "move", "x": 700, "y": 400 } + ] +} diff --git a/app/vendor/rune/scripts/motion-audit/scenarios/shell-window-resize.json b/app/vendor/rune/scripts/motion-audit/scenarios/shell-window-resize.json new file mode 100644 index 0000000..4d6db1d --- /dev/null +++ b/app/vendor/rune/scripts/motion-audit/scenarios/shell-window-resize.json @@ -0,0 +1,7 @@ +{ + "events": [ + { "t": 0.3, "type": "resize", "dw": -320, "dur": 0.8 }, + { "t": 1.5, "type": "resize", "dw": 320, "dh": 160, "dur": 0.8 }, + { "t": 2.6, "type": "move", "x": 400, "y": 300 } + ] +} diff --git a/app/vendor/rune/scripts/motion-audit/scenarios/tab-strip.json b/app/vendor/rune/scripts/motion-audit/scenarios/tab-strip.json new file mode 100644 index 0000000..2f94a36 --- /dev/null +++ b/app/vendor/rune/scripts/motion-audit/scenarios/tab-strip.json @@ -0,0 +1,14 @@ +{ + "events": [ + { "t": 0.3, "type": "drag", "key": "top-list/t-s1", "dx": 300, "dur": 0.8 }, + { "t": 1.6, "type": "drag", "key": "side-list/t-s6", "dy": -125, "dur": 0.7 }, + { "t": 2.8, "type": "drag", "key": "side-list/t-s2", "dy": 90, "dur": 0.8 }, + { "t": 3.3, "type": "key", "name": "Escape" }, + { "t": 4.2, "type": "click", "key": "top-list/t-s7", "button": "middle" }, + { "t": 4.6, "type": "click", "button": "middle" }, + { "t": 5.2, "type": "move", "x": 700, "y": 500 }, + { "t": 6.0, "type": "drag", "key": "top-list/t-s2", "dx": 70, "dy": 160, "dur": 0.8 }, + { "t": 7.2, "type": "click", "key": "new-tab" }, + { "t": 7.9, "type": "move", "x": 700, "y": 500 } + ] +} diff --git a/app/vendor/rune/scripts/motion-audit/scenarios/text-glide.json b/app/vendor/rune/scripts/motion-audit/scenarios/text-glide.json new file mode 100644 index 0000000..4ef1161 --- /dev/null +++ b/app/vendor/rune/scripts/motion-audit/scenarios/text-glide.json @@ -0,0 +1,6 @@ +{ + "events": [ + { "t": 0.3, "type": "tap", "key": "card", "expect": "smooth", "element": "card" }, + { "t": 2.0, "type": "tap", "key": "card", "expect": "smooth", "element": "card" } + ] +} diff --git a/app/vendor/rune/scripts/motion-audit/scenarios/todo-add-remove.json b/app/vendor/rune/scripts/motion-audit/scenarios/todo-add-remove.json new file mode 100644 index 0000000..695ac6e --- /dev/null +++ b/app/vendor/rune/scripts/motion-audit/scenarios/todo-add-remove.json @@ -0,0 +1,40 @@ +{ + "events": [ + { + "t": 0.3, + "type": "tap", + "key": "add" + }, + { + "t": 0.9, + "type": "tap", + "key": "add" + }, + { + "t": 1.5, + "type": "tap", + "key": "todo-1/#2" + }, + { + "t": 2.1, + "type": "tap", + "key": "todo-2/check" + }, + { + "t": 2.7, + "type": "tap", + "key": "todo-0/#2" + }, + { + "t": 2.75, + "type": "tap", + "key": "add" + }, + { + "t": 3.6, + "type": "move", + "x": 10, + "y": 10 + } + ] +} \ No newline at end of file diff --git a/app/vendor/rune/scripts/motion-audit/scenarios/wheel-distance.json b/app/vendor/rune/scripts/motion-audit/scenarios/wheel-distance.json new file mode 100644 index 0000000..c2ca37d --- /dev/null +++ b/app/vendor/rune/scripts/motion-audit/scenarios/wheel-distance.json @@ -0,0 +1,6 @@ +{ + "events": [ + { "t": 0.25, "type": "wheel", "x": 200, "y": 220, "dy": -120, "precise": false, "expect": "instant", "scope": "cards" }, + { "t": 0.65, "type": "wheel", "x": 200, "y": 220, "dy": 12, "precise": true, "expect": "instant", "scope": "cards" } + ] +} diff --git a/app/vendor/rune/scripts/motion-audit/test_analyze.py b/app/vendor/rune/scripts/motion-audit/test_analyze.py new file mode 100644 index 0000000..4826464 --- /dev/null +++ b/app/vendor/rune/scripts/motion-audit/test_analyze.py @@ -0,0 +1,274 @@ +#!/usr/bin/env python3 +"""Checks analyze.py on small synthetic traces. Run: python3 scripts/motion-audit/test_analyze.py""" + +import json +import math +import os +import sys +import tempfile + +sys.dont_write_bytecode = True +sys.path.insert(0, os.path.dirname(__file__)) +import analyze # noqa: E402 + + +def trace(states): + """A 120 Hz trace of one 10×10 element; `states` holds (x, opacity, visible width) per frame.""" + lines = [json.dumps({"width": 200, "height": 100, "hz": 120})] + for k, (x, op, vis_w) in enumerate(states): + fr = {"e": [[1, x, 40, 10, 10, op, 0, 0, max(x, 20), 40, vis_w, 10]], "quality": {"animating": True}} + if k == 0: + fr["m"] = [{"id": 1, "nm": "label/sheen"}] + lines.append(json.dumps(fr)) + f = tempfile.NamedTemporaryFile("w", suffix=".jsonl", delete=False) + f.write("\n".join(lines) + "\n") + f.close() + return f.name + + +def jumps(states): + path = trace(states) + try: + return [f for f in analyze.analyze(path)["findings"] if f["kind"] in ("jump", "step")] + finally: + os.unlink(path) + + +def sheen(wrap_from, wrap_to): + """A loop sliding right 0.5 pt a frame, then wrapping back to its start.""" + before = [(86 - 0.5 * (9 - i), *wrap_from) for i in range(10)] + after = [(15 + 0.5 * i, *wrap_to) for i in range(10)] + return before + after + + +def scene(frames, flags=None, clips=None): + """A 120 Hz trace of named elements; each frame maps name -> (x, y, w, h, opacity), plus + how far scrolling carries it as (x, y) when it scrolls, and a name missing from a frame is + gone. A name's parent is its longest named prefix. `clips` maps a name to a window-space + clip (x0, y0, x1, y1) cutting the visible part of it and what it holds. A frame's "@ev" + lists the inputs the app recorded in it ("wheel 3.0").""" + names = sorted({nm for fr in frames for nm in fr if nm != "@ev"}) + ids = {nm: i + 1 for i, nm in enumerate(names)} + def parent(nm): + cut = [nm[:j] for j in range(len(nm)) if nm[j] == "/" and nm[:j] in ids] + return ids[cut[-1]] if cut else None + lines = [json.dumps({"width": 400, "height": 400, "hz": 120})] + alive, meta = set(), set() + for fr in frames: + out = {"e": [], "quality": {"animating": True}, "m": [], "g": [], "sc": [], "ev": fr.get("@ev", [])} + fr = {nm: v for nm, v in fr.items() if nm != "@ev"} + for nm, (x, y, w, h, op, *sc) in fr.items(): + out["sc"] += [[ids[nm], *sc[0]]] if sc else [] + if nm not in meta: + meta.add(nm) + out["m"].append({"id": ids[nm], "nm": nm, "pv": parent(nm)}) + vis = [x, y, w, h] + for c in [c for p, c in (clips or {}).items() if nm == p or nm.startswith(p + "/")]: + x0, y0 = max(vis[0], c[0]), max(vis[1], c[1]) + x1, y1 = min(vis[0] + vis[2], c[2]), min(vis[1] + vis[3], c[3]) + vis = [x0, y0, max(x1 - x0, 0), max(y1 - y0, 0)] + out["e"].append([ids[nm], x, y, w, h, op, 0, (flags or {}).get(nm, 0), *vis]) + alive.add(nm) + for nm in sorted(alive - set(fr)): + out["g"].append(ids[nm]) + alive.discard(nm) + lines.append(json.dumps(out)) + f = tempfile.NamedTemporaryFile("w", suffix=".jsonl", delete=False) + f.write("\n".join(lines) + "\n") + f.close() + return f.name + + +def kinds(frames, events=None, flags=None, clips=None): + path = scene(frames, flags, clips) + try: + return [f["kind"] for f in analyze.analyze(path, {"events": events} if events else None)["findings"]] + finally: + os.unlink(path) + + +def ease(a, b, n): + """n frames easing from a to b (no overshoot).""" + return [a + (b - a) * (1 - (1 - (i + 1) / n) ** 3) for i in range(n)] + + +def hold(fr, n): + return [dict(fr) for _ in range(n)] + + +def main(): + # instant: a key whose answer fades in over 20 frames isn't a cut. + still = {"root": (0, 0, 400, 400, 1.0)} + key = [{"t": 0.1, "type": "key", "name": "Escape", "expect": "instant"}] + fade = hold(still, 12) + [{**still, "root/panel": (10, 10, 100, 100, op)} for op in ease(0, 1, 20)] + hold({**still, "root/panel": (10, 10, 100, 100, 1)}, 20) + assert "not-instant" in kinds(fade, key), "a fade answering an instant input" + cut = hold(still, 12) + hold({**still, "root/panel": (10, 10, 100, 100, 1)}, 40) + assert "not-instant" not in kinds(cut, key) and "pop-in" not in kinds(cut, key), "a cut is the answer, not a pop" + + # follow: a drag that tracks the smoothstepped hand passes; one that trails it lags. + drag = [{"t": 0.1, "type": "drag", "key": "handle", "dx": 120, "dur": 0.5, "expect": "follow", "element": "root/handle"}] + def hand(k): + f = max(0, min(60, math.floor((k / 120 - 0.1) / 0.5 * 60 + 1e-6))) / 60 + return 120 * f * f * (3 - 2 * f) + track = [{**still, "root/handle": (10 + hand(k), 10, 20, 20, 1)} for k in range(100)] + assert "lags-hand" not in kinds(track, drag), "a handle on the hand" + lag, x = [], 10.0 + for k in range(100): + x += (10 + hand(k) - x) * 0.3 + lag.append({**still, "root/handle": (x, 10, 20, 20, 1)}) + assert "lags-hand" in kinds(lag, drag), "a handle on a spring behind the hand" + + # one monotonic path: a wind-up the wrong way, and an L-shaped route. + at = lambda x, y: {**still, "root/card": (x, y, 40, 40, 1)} + windup = hold(at(100, 100), 5) + [at(x, 100) for x in ease(100, 94, 4) + ease(94, 200, 16)] + hold(at(200, 100), 10) + assert "reversal" in kinds(windup), "a wind-up before the move" + straight = hold(at(100, 100), 5) + [at(x, 100) for x in ease(100, 200, 20)] + hold(at(200, 100), 10) + assert not {"reversal", "dog-leg", "overshoot"} & set(kinds(straight)), "a straight eased move" + ell = hold(at(100, 100), 5) + [at(x, 100) for x in ease(100, 200, 10)] + [at(200, y) for y in ease(100, 200, 10)] + hold(at(200, 200), 10) + assert "dog-leg" in kinds(ell), "across, then down" + # a chevron sliding along its row as the list scrolls: across on the list, up with it. + list_y = ease(300, 200, 20) + [200] * 20 + slide = [0] * 18 + ease(0, 100, 20) + [100] * 2 + scroll = hold({**still, "root/list": (0, 300, 400, 100, 1), "root/list/chevron": (100, 310, 10, 10, 1)}, 5) + scroll += [{**still, "root/list": (0, y, 400, 100, 1), "root/list/chevron": (100 + x, y + 10, 10, 10, 1)} for y, x in zip(list_y, slide)] + assert "dog-leg" not in kinds(scroll + hold(scroll[-1], 10)), "a slide on a scrolling list" + # an L of its own on a moving list is still one. + ell_x, ell_y = ease(0, 100, 15) + [100] * 15, [0] * 15 + ease(0, 100, 15) + ell_on = [{**still, "root/list": (0, y, 400, 100, 1), "root/list/chevron": (100 + x, y + 10 + dy, 10, 10, 1)} + for y, x, dy in zip(ease(300, 200, 30), ell_x, ell_y)] + assert "dog-leg" in kinds(scroll[:5] + ell_on + hold(ell_on[-1], 10)), "across, then down, on a moving list" + # a drift out and back that rests a frame where it turns is still one motion. + drift = hold(at(100, 100), 5) + [at(x, 100) for x in ease(100, 97.5, 6)] + hold(at(97.5, 100), 2) + [at(x, 100) for x in ease(97.5, 100, 12)] + hold(at(100, 100), 10) + assert "reversal" in kinds(drift), "out and back with a rest at the turn" + # in a list following its growing end, 2 pt a frame up: judged against the scroll. + def scrolling(own, flags=0, told=True): + frames = [] + for k in range(140): + t = min(max(k - 40, 0), 60) + frames.append({**still, "root/list/node": (100, 300 + own(t) - 2 * t, 40, 40, 1, *([(0, 2 * t)] if told else []))}) + return kinds(frames, flags={"root/list/node": flags}) + glide = lambda k: 60 * (1 - math.exp(-k / 8)) + assert "reversal" in scrolling(glide, told=False), "on screen the glide and the scroll turn back" + assert not {"reversal", "jiggle", "overshoot", "stall"} & set(scrolling(glide)), "against the scroll it is one glide" + assert not {"reversal", "jiggle", "overshoot", "stall"} & set(scrolling(glide, analyze.SCROLLING)) + wobble = lambda k: 2.5 * math.sin(k * 0.6) + assert "jiggle" not in scrolling(wobble, told=False), "on screen it only ever rises" + assert "jiggle" in scrolling(wobble), "against the scroll it wobbles" + assert "jiggle" in scrolling(wobble, analyze.SCROLLING), "a scroll that moves doesn't excuse it" + + # jumps are judged on what shows. A fold drops 900 pt above a 200 pt viewport in one frame + # with the scroll offset: the content's and the fold's tops and heights step, while what + # shows stays put. + view = {"root/list": (0, 0, 400, 200)} + def frame(content, fold, extra=None): + return {**still, "root/list": (0, *content, 1), "root/list/fold": (0, *fold, 1), + "root/list/fold/a": (0, 60, 400, 40, 1), "root/list/after": (0, 150, 400, 100, 1), **(extra or {})} + drop = hold(frame((-1100, 400, 1500), (-900, 400, 1200)), 40) + hold(frame((-200, 400, 600), (0, 400, 300)), 40) + found = set(kinds(drop, clips=view)) + assert not {"jump", "step", "sibling-jump"} & found, f"nothing that shows moves: {found}" + # Shut from its stuck header, the fold drops its rows above the window and its top comes + # in from the window's edge, gliding down from where it showed. + def shut(top): + return {**still, "root/list": (0, top - 1100, 400, 1500, 1), "root/list/fold": (0, top, 400, 200 - top, 1), + "root/list/after": (0, 200, 400, 100, 1)} + glide = hold(shut(-900), 40) + [shut(t) for t in (13, 43, 73, 100, 120, 135, 145, 150)] + hold(shut(150), 40) + found = set(kinds(glide, clips=view)) + assert not {"jump", "step", "sibling-jump"} & found, f"it glides from where it showed: {found}" + # A row that shows, teleported 100 pt in the scrolled list, jumps. + row = lambda y: {"root/list/fold/row": (0, y, 400, 30, 1)} + tele = hold(frame((-200, 400, 600), (0, 400, 300), row(20)), 40) + hold(frame((-200, 400, 600), (0, 400, 300), row(120)), 40) + assert "jump" in kinds(tele, clips=view), "a row that shows jumps" + # The content jumps 100 pt and the rows that show with it. + shift = lambda dy: {**still, "root/list": (0, -600 + dy, 400, 2000, 1), "root/list/a": (0, 20 + dy, 400, 30, 1), "root/list/b": (0, 60 + dy, 400, 30, 1)} + assert "jump" in kinds(hold(shift(0), 40) + hold(shift(100), 40), clips=view), "the content jumps with what shows of it" + # The offset jumps 40 pt with no input: the first row, just under the viewport, pops 40 pt + # into view, though nothing showed on both frames. Under a key, it's the key's scroll. + pad = lambda dy: {**still, "root/list": (0, -dy, 400, 1100, 1), "root/list/row": (0, 300 - dy, 400, 40, 1)} + padded = hold(pad(0), 40) + hold(pad(40), 40) + port, scroll = {"root/list": (0, 0, 400, 300)}, {"root/list": analyze.SCROLLING, "root/list/row": analyze.SCROLLING} + assert "jump" in kinds(padded, flags=scroll, clips=port), "content that teleports a row into view" + end = [{"t": 40 / 120, "type": "key", "name": "End"}] + assert not {"jump", "step"} & set(kinds(padded, end, flags=scroll, clips=port)), "a key's scroll" + glide = hold(pad(0), 40) + [pad(y) for y in ease(0, 40, 20)] + hold(pad(40), 20) + assert not {"jump", "step"} & set(kinds(glide, flags=scroll, clips=port)), "a scroll that glides" + + # one steady speed: a retarget that drops part of its speed for a frame stalls; one that + # keeps its speed and only pulls harder toward a farther target doesn't. + xs = ease(100, 200, 20) + slow = xs[7] + 0.3 * (xs[8] - xs[7]) + dip = xs[:8] + [slow] + [slow + v for v in ease(0, 230 - slow, 24)] + assert "stall" in kinds(hold(at(100, 100), 5) + [at(x, 100) for x in dip] + hold(at(dip[-1], 100), 10)), "a re-aim that lost its speed for a frame" + def spring(x, v, target, n, k=320.0, c=36.0, dt=1 / 120): + out = [] + for _ in range(n): + v += (k * (target - x) - c * v) * dt + x += v * dt + out.append(x) + return out, v + first, v = spring(100.0, 0.0, 200.0, 10) + retarget, _ = spring(first[-1], v, 240.0, 60) + assert "stall" not in kinds(hold(at(100, 100), 5) + [at(x, 100) for x in first + retarget] + hold(at(retarget[-1], 100), 10)), "a retarget at its own speed" + assert "stall" not in kinds(straight), "a straight eased move" + # A scroll bar's thumb follows the wheel: a wheel that slows to a stop and a fling that + # picks it up again is the hand's speed, not a lost retarget. + wheeled = [{**at(x, 100), "@ev": [f"wheel {v:.1f}"]} for x, v in zip(dip[:9], range(9, 0, -1))] + wheeled[8]["@ev"] = ["fling 1800"] + flung = hold(at(100, 100), 5) + wheeled + [at(x, 100) for x in dip[9:]] + hold(at(dip[-1], 100), 10) + assert "stall" not in kinds(flung), "the thumb slows and picks up with the wheel" + + # nothing unmounts above opacity 0. + half = hold({**still, "root/chip": (10, 10, 50, 20, 1)}, 5) + [{**still, "root/chip": (10, 10, 50, 20, op)} for op in ease(1, 0.4, 6)] + hold(still, 10) + assert "cut-exit" in kinds(half), "a fade cut short at 0.4" + full = hold({**still, "root/chip": (10, 10, 50, 20, 1)}, 5) + [{**still, "root/chip": (10, 10, 50, 20, op)} for op in ease(1, 0, 12)] + hold(still, 10) + assert not {"cut-exit", "pop-out"} & set(kinds(full)), "a fade to 0, then gone" + + # an instant scroll (wrapping to a long list's end) mounts the rows it lands on and drops the + # rows it left: the scroll, not pops. The same swap with no scroll pops. + top = {**still, "root/list/a": (0, 0, 200, 30, 1), "root/list/b": (0, 30, 200, 30, 1)} + end = {**still, "root/list/y": (0, 0, 200, 30, 1), "root/list/z": (0, 30, 200, 30, 1)} + swap = hold(top, 10) + hold(end, 20) + assert {"pop-in", "pop-out"} <= set(kinds(swap)), "rows swapped in place" + assert not {"pop-in", "pop-out"} & set(kinds(swap, flags={"root/list/y": 4 | 8, "root/list/z": 4 | 8})), "rows scrolled in" + + # stable identity: closing row a must remove a, not b (index keys remove the last row). + rows = lambda *ks: {**still, **{f"root/list/{k}": (0, 30 * i, 200, 30, 1) for i, k in enumerate(ks)}, "root/list": (0, 0, 200, 90, 1)} + close = [{"t": 0.1, "type": "tap", "key": "a/close", "expect": "leaves", "element": "root/list/a"}] + assert "wrong-exit" in kinds(hold(rows("a", "b", "c"), 12) + hold(rows("a", "b"), 40), close), "the last row left instead" + assert "wrong-exit" not in kinds(hold(rows("a", "b", "c"), 12) + hold(rows("b", "c"), 40), close), "row a left" + + # smooth: a release that lands in one frame snaps. + release = [{"t": 0.1, "type": "drag", "key": "card", "dx": 50, "dur": 0.1, "expect": "smooth", "element": "root/card"}] + assert "snap" in kinds(hold(at(100, 100), 30) + hold(at(200, 100), 40), release), "a landing in one frame" + assert "snap" not in kinds(hold(at(100, 100), 30) + [at(x, 100) for x in ease(100, 200, 24)] + hold(at(200, 100), 20), release), "a glide" + + assert not jumps(sheen((1.0, 0.0), (1.0, 5.0))), "a wrap from clipped away isn't a jump" + assert not jumps(sheen((0.0, 10.0), (1.0, 5.0))), "a wrap from transparent isn't a jump" + assert not jumps(sheen((1.0, 10.0), (0.0, 10.0))), "a wrap into transparent isn't a jump" + found = jumps(sheen((1.0, 10.0), (1.0, 10.0))) + assert len(found) == 1 and found[0]["at"] == "10", f"a wrap in sight is: {found}" + + # scale-settle: a <= 100 ms pixel-snap settle right after motion isn't idle; a cold or long one is. + def scale_settle_trace(settle_frames, preceded_by_motion=True): + lines = [json.dumps({"width": 200, "height": 100, "hz": 120})] + lines.append(json.dumps({"m": [{"id": 1, "nm": "stage"}], "e": [[1, 10, 10, 40, 20, 1, 0, 0]], "quality": {"animating": False, "why": []}})) + if preceded_by_motion: + lines.append(json.dumps({"e": [[1, 14, 10, 64, 32, 1, 0, 1]], "tk": [[1, "scale", 1]], "quality": {"animating": True, "why": ["tracks"]}})) + for _ in range(settle_frames): + lines.append(json.dumps({"quality": {"animating": True, "why": ["scale-settle"]}})) + lines.append(json.dumps({"quality": {"animating": False, "why": []}})) + f = tempfile.NamedTemporaryFile("w", suffix=".jsonl", delete=False) + f.write("\n".join(lines) + "\n") + f.close() + try: + return [x["kind"] for x in analyze.analyze(f.name)["findings"]] + finally: + os.unlink(f.name) + + assert "idle-frames" not in scale_settle_trace(12, True), "100 ms scale-settle after motion" + assert "idle-frames" in scale_settle_trace(20, True), "overrun scale-settle" + assert "idle-frames" in scale_settle_trace(6, False), "cold scale-settle" + print("ok") + + +if __name__ == "__main__": + main() diff --git a/app/vendor/rune/scripts/motion-audit/test_retargets.py b/app/vendor/rune/scripts/motion-audit/test_retargets.py new file mode 100644 index 0000000..a956666 --- /dev/null +++ b/app/vendor/rune/scripts/motion-audit/test_retargets.py @@ -0,0 +1,93 @@ +"""Retargets split trajectories, never excuse bad motion between destinations.""" +import json +import os +import unittest + +import analyze +from test_analyze import scene + + +class Retargets(unittest.TestCase): + def findings(self, xs, goals=None, parent=None, opacity=1, flags=None): + frames = [{"root": (0, 0, 400, 400, 1), "root/piece": (x, 40, 10, 10, opacity)} for x in xs] + frames = [frames[0]] * 80 + frames + [frames[-1]] * 80 + path = scene(frames, flags=flags) + try: + with open(path) as f: + rows = [json.loads(line) for line in f] + for k, mask in (goals or {}).items(): + rows[81 + k]["retarget"] = [[1 if parent else 2, mask, mask if parent == "scale" else mask & 3]] + with open(path, "w") as f: + f.write("\n".join(json.dumps(row) for row in rows)) + return {f["kind"] for f in analyze.analyze(path)["findings"]} + finally: + os.unlink(path) + + def test_a_new_destination_is_not_one_out_and_back(self): + xs = [40, 42, 44, 46, 48, 50, 48, 46, 44, 42, 40] + self.assertIn("reversal", self.findings(xs)) + self.assertNotIn("reversal", self.findings(xs, {6: 1})) + # A different property's goal cannot excuse this axis. + self.assertIn("reversal", self.findings(xs, {6: 2})) + + def test_parent_motion_carries_children_but_size_does_not(self): + xs = [40, 42, 44, 46, 48, 50, 48, 46, 44, 42, 40] + self.assertNotIn("reversal", self.findings(xs, {6: 15}, parent="scale")) + self.assertIn("reversal", self.findings(xs, {6: 4}, parent="size")) + + def test_retarget_preserves_decelerating_incoming_velocity(self): + xs = [40, 44, 48, 51, 53, 54, 53, 51, 48, 44, 40, 36, 33, 31, 30] + self.assertNotIn("reversal", self.findings(xs, {3: 1})) + xs[4:6] = [55, 60] # Accelerates away instead of braking. + self.assertIn("reversal", self.findings(xs, {3: 1})) + + def test_bad_motion_before_another_retarget_is_still_checked(self): + xs = [40, 44, 48, 52, 50, 48, 46, 44, 42, 40, 38, 36, 34, 32] + self.assertIn("reversal", self.findings(xs, {10: 1})) + + def test_a_jump_on_the_retarget_frame_still_fails(self): + self.assertIn("jump", self.findings([40, 40, 40, 100, 100, 100], {3: 1})) + + def test_a_retarget_that_loses_velocity_still_fails(self): + self.assertIn("stall", self.findings([40, 43, 46, 46.2, 49.2, 52.2, 55.2], {3: 1})) + + def thumb(self, ys, goal=None, flags=0): + """A scroll bar's thumb beside a scrolled list, with `goal` = (frame, name) retargeted.""" + def at(y): + return {"area": (0, 0, 400, 400, 1), "area/view": (0, 0, 390, 400, 1), "area/view/list": (0, -50, 390, 900, 1, (0, 50)), + "area/bar": (390, 0, 10, 400, 1), "area/bar/thumb": (392, y, 6, 120, 1), "other": (0, 0, 10, 10, 1)} + frames = [at(ys[0])] * 80 + [at(y) for y in ys] + [at(ys[-1])] * 80 + path = scene(frames, flags={"area/bar/thumb": flags}) + try: + with open(path) as f: + rows = [json.loads(line) for line in f] + ids = {m["nm"]: m["id"] for m in rows[1]["m"]} + if goal: + rows[81 + goal[0]]["retarget"] = [[ids[goal[1]], 8, 0]] + with open(path, "w") as f: + f.write("\n".join(json.dumps(row) for row in rows)) + return {f["kind"] for f in analyze.analyze(path)["findings"]} + finally: + os.unlink(path) + + def test_a_thumb_brakes_when_the_list_it_reads_retargets(self): + ys = [40, 44, 48, 51, 53, 54, 53, 51, 48, 44, 40, 36, 33, 31, 30] + self.assertIn("reversal", self.thumb(ys, flags=1)) + self.assertTrue({"reversal", "dog-leg"}.isdisjoint(self.thumb(ys, (3, "area/view/list"), flags=1))) + # Only the content it reads moves its destination. + self.assertIn("reversal", self.thumb(ys, (3, "other"), flags=1)) + + def test_a_placed_readout_has_no_shape_of_its_own(self): + ys = [40, 44, 48, 51, 53, 54, 53, 51, 48, 44, 40, 36, 33, 31, 30] + self.assertNotIn("reversal", self.thumb(ys, flags=3 << 8)) + # Springing, it answers for its own path. + self.assertIn("reversal", self.thumb(ys, flags=3 << 8 | 1)) + + def test_invisible_or_intentionally_instant_retargets_are_not_stalls(self): + xs = [40, 43, 46, 46.2, 49.2, 52.2, 55.2] + self.assertNotIn("stall", self.findings(xs, {3: 1}, opacity=0)) + self.assertNotIn("stall", self.findings(xs, {3: 1}, flags={"root/piece": 1 << 8})) + + +if __name__ == "__main__": + unittest.main() diff --git a/app/vendor/rune/scripts/motion-audit/track.py b/app/vendor/rune/scripts/motion-audit/track.py new file mode 100644 index 0000000..6a32e95 --- /dev/null +++ b/app/vendor/rune/scripts/motion-audit/track.py @@ -0,0 +1,57 @@ +#!/usr/bin/env python3 +"""Prints one element's per-frame state from a Rune trace: frame, t, rect, opacity, flags, +visible rect, and the tracks sampled for it. + +Usage: scripts/motion-audit/track.py TRACE.jsonl NAME-SUBSTRING [FROM [TO]] [--all-names] +""" + +import json +import sys + + +def main(): + path, needle = sys.argv[1], sys.argv[2] + rest = [a for a in sys.argv[3:] if not a.startswith("--")] + lo = int(rest[0]) if rest else 0 + hi = int(rest[1]) if len(rest) > 1 else 10**9 + names, state, alive = {}, {}, set() + with open(path) as f: + f.readline() + frames = [json.loads(l) for l in f if l.strip()] + if "--all-names" in sys.argv: + for fr in frames: + for m in fr.get("m", []): + if needle in m["nm"]: + names[m["id"]] = m["nm"] + for id, n in names.items(): + print(id, n) + return + for k, fr in enumerate(frames): + for m in fr.get("m", []): + names[m["id"]] = m["nm"] + rows = {r[0]: r for r in fr.get("e", [])} + for id, r in rows.items(): + state[id] = r + alive.add(id) + gone = set(fr.get("g", [])) + tk = {} + for who, prop, active in fr.get("tk", []): + tk.setdefault(who, []).append(prop + ("" if active else "·")) + if not (lo <= k <= hi): + alive -= gone + continue + for id in sorted(set(rows) | (gone & alive)): + if needle not in names.get(id, ""): + continue + if id in gone: + print(f"{k:4} {fr['t']:8.1f} {names[id][-50:]:<50} GONE") + continue + r = state[id] + vis = f" vis={r[8:12]}" if len(r) >= 12 else "" + q = fr.get("quality", {}) + print(f"{k:4} {fr['t']:8.1f} {names[id][-50:]:<50} x={r[1]:<8} y={r[2]:<8} w={r[3]:<8} h={r[4]:<8} op={r[5]:<6} fl={r[7]}{vis} tk={tk.get(id, '')} {'+'.join(q.get('why', []))}") + alive -= gone + + +if __name__ == "__main__": + main() diff --git a/app/vendor/rune/scripts/native-pacing/README.md b/app/vendor/rune/scripts/native-pacing/README.md new file mode 100644 index 0000000..71e37c7 --- /dev/null +++ b/app/vendor/rune/scripts/native-pacing/README.md @@ -0,0 +1,84 @@ +# Native presentation pacing + +Timestamp-only probe on a GUI Mac. No screen capture. It measures `nextDrawable` entry to +positive Metal `presentedTime`, using the overlay team's steady-state endpoint. +Three batches per mode, two-second warmup, then three three-second intervals; +the summary is the median of nine interval medians. + +Build with `cargo build --profile perf -j 2 -p rune --example pacing_overlay --example pacing` +on the Mac that runs the probe, and run jobs one at a time. Pass the +`target/perf/examples/` executable path; the runners refuse binaries from any +other profile. + +```sh +python3 scripts/native-pacing/run.py <out> <pacing_overlay> \ + --reference <path to a reference app executable> +``` + +The runner checks it is on the expected GUI host, holds a GUI lock file, bounds +app lifetimes, and removes its instrumentation dylib. `--modes native` selects only +the continuous Rune workload; the default tests injected redraws and native +animation. The reference app is optional and its order alternates between batches. + +Rune uses a 680×160-point overlay. Native mode animates opacity continuously; +injected mode uses a static view with an AppKit 60-Hz redraw timer. The reference +app runs on a different-sized surface. +Results include executable hashes, raw callback logs, drawable waits, interval +medians, acquisition gaps, and counts of excluded zero presentation timestamps. +These excluded callbacks are not a dropped-frame count. A timeout is a failed +run and cannot serve as a complete performance baseline. + +The `pacing` example separately exercises state commits, idle, hide/show and +shutdown. Run it under the same GUI lock with `--native --trace <file>`, then +check the file with `python3 scripts/check-native-pacing.py <file>`. + +## Isolated refresh-rate experiments + +Use a fresh output directory for each experiment: + +```sh +# Same production executable; one change at a time, in this order. +python3 scripts/native-pacing/run.py <out-ca> <pacing_overlay> --modes native --display-link ca +python3 scripts/native-pacing/run.py <out-two> <pacing_overlay> --modes native --drawables 2 +python3 scripts/native-pacing/run.py <out-unsynced> <pacing_overlay> --modes native --display-sync 0 +``` + +`clock-probe.m` interposes CV callback registration/start/stop. Its default mode +counts real CV callbacks. CA mode supplies the same Rune callback from an NSView +`CADisplayLink` with `CAFrameRateRangeMake(80, 120, 120)` on macOS 14+. This adapter +selects the fixture's visible panel and supports this single-surface workload; +it is not a general replacement for Rune's native display-link implementation. +Layer overrides affect Rune only. An optional reference app keeps its settings. + +For the admission-guard comparison, apply `admission-probe.patch` in a disposable +checkout, generate a new source manifest, and rebuild the example. Run `--guard production` then `--guard no-half` on that same executable. +The latter removes only elapsed-half-refresh admission, retaining stale-target +and duplicate-target rejection. The runner requires matching diagnostic output. +Counters are printed after stopping the link, not in the callback. Revert the +patch and rebuild when finished. Never ship this patch; it exists to reproduce +the experiment and intentionally leaves the original unit-test helper unused. + +`acquisition_hz` uses `nextDrawable` entry times. `presentation_hz` uses distinct, +positive `presentedTime` timestamps for frames acquired in the nine-second sample. +Callback Hz and guard counts cover the full app run, including warmup. Guard +reason counters can overlap; they are not an exhaustive partition of callbacks +because pending callbacks coalesce. The summary includes the selected overrides +and binary hash. Raw logs retain the actual layer settings. + +With display sync disabled, positive presentation timestamps do not establish +tear-free 120-Hz scanout. Apple's API explicitly allows tearing in this mode. + +## Findings + +With the default synced layer, the tested overlay presents at about 60 Hz on a +120-Hz display, although CVDisplayLink and NSView CADisplayLink both deliver +about 120 callbacks/s. Two drawables lower latency but keep 60-Hz presentation. +Disabling display sync raises positive presentations above 100/s, which does not +prove tear-free output. Removing the half-refresh admission guard moves waiting +into `nextDrawable` without raising presentation frequency, and breaks the +half-refresh bound: keep the guard. The evidence points to synced drawable +backpressure, not callback rate. + +`refresh-probe.m` then found the cause of the 60-Hz cap: Low Power Mode holds a +ProMotion panel at 60 Hz while both display links and `NSScreen` still report +120 Hz. `crates/rune/src/platform/display_link.rs` paces submissions at that cap. diff --git a/app/vendor/rune/scripts/native-pacing/admission-probe.patch b/app/vendor/rune/scripts/native-pacing/admission-probe.patch new file mode 100644 index 0000000..6e98c31 --- /dev/null +++ b/app/vendor/rune/scripts/native-pacing/admission-probe.patch @@ -0,0 +1,59 @@ +diff --git a/crates/rune/src/display_link.rs b/crates/rune/src/display_link.rs +index fc25f6e..25823f9 100644 +--- a/crates/rune/src/display_link.rs ++++ b/crates/rune/src/display_link.rs +@@ -25,6 +25,8 @@ pub(crate) struct DisplayLink { + last_target: Option<Instant>, + display: Option<u32>, + running: bool, ++ probe_no_half: bool, ++ probe_counts: [u64; 5], + } + + unsafe extern "C-unwind" fn tick( +@@ -70,7 +72,8 @@ impl DisplayLink { + }); + let status = unsafe { link.set_output_callback(Some(tick), (&mut *callback as *mut Callback).cast()) }; + if status != 0 { eprintln!("display link callback failed: {status}"); return None; } +- let mut pacing = Self { link, callback, last_present: None, last_target: None, display: None, running: false }; ++ let mut pacing = Self { link, callback, last_present: None, last_target: None, display: None, running: false, ++ probe_no_half: std::env::var("STEADY_GUARD").as_deref() == Ok("no-half"), probe_counts: [0; 5] }; + pacing.update_display(window); + Some(pacing) + } +@@ -93,13 +96,20 @@ impl DisplayLink { + self.running = true; + } + let host_target = self.callback.target.swap(0, Ordering::Acquire); +- if host_target == 0 { return None; } ++ if host_target == 0 { self.probe_counts[0] += 1; return None; } + let now = Instant::now(); + let target = target_time(now, CVGetCurrentHostTime(), host_target, self.callback.host_frequency); + let period = Duration::from_nanos(self.callback.period_ns.load(Ordering::Relaxed)); + // A late render followed by an on-time tick must skip, not submit two frames + // together. Also discard stale callbacks after main-thread stalls. +- if !permits(self.last_present, self.last_target, target, now, period) { return None; } ++ let stale = now >= target; ++ let duplicate = self.last_target.is_some_and(|last| target <= last); ++ let short = self.last_present.is_some_and(|last| now.saturating_duration_since(last) < period / 2); ++ self.probe_counts[1] += u64::from(stale); ++ self.probe_counts[2] += u64::from(duplicate); ++ self.probe_counts[3] += u64::from(short); ++ if stale || duplicate || (!self.probe_no_half && short) { return None; } ++ self.probe_counts[4] += 1; + self.last_target = Some(target); + Some(target) + } +@@ -110,6 +120,12 @@ impl DisplayLink { + + pub(crate) fn stop(&mut self) { + if self.running { self.link.stop(); self.running = false; } ++ if self.probe_counts[4] > 0 { ++ eprintln!("steady guard mode={} empty={} stale={} duplicate={} short={} admitted={}", ++ if self.probe_no_half { "no-half" } else { "production" }, self.probe_counts[0], self.probe_counts[1], ++ self.probe_counts[2], self.probe_counts[3], self.probe_counts[4]); ++ self.probe_counts = [0; 5]; ++ } + self.callback.target.store(0, Ordering::Relaxed); + } + } diff --git a/app/vendor/rune/scripts/native-pacing/clock-probe.m b/app/vendor/rune/scripts/native-pacing/clock-probe.m new file mode 100644 index 0000000..f963621 --- /dev/null +++ b/app/vendor/rune/scripts/native-pacing/clock-probe.m @@ -0,0 +1,78 @@ +// Diagnostic adapter only: keep Rune's admission/render path unchanged while swapping +// its CV callback source for an NSView CADisplayLink. Not linked into shipping Rune. +#import <AppKit/AppKit.h> +#import <QuartzCore/QuartzCore.h> +#import <CoreVideo/CoreVideo.h> + +@interface RuneClockProbe : NSObject +@property(nonatomic) CVDisplayLinkRef cv; +@property(nonatomic) CVDisplayLinkOutputCallback callback; +@property(nonatomic) void *context; +@property(nonatomic, strong) CADisplayLink *ca; +@property(nonatomic) unsigned count; +@property(nonatomic) double first; +@property(nonatomic) double last; +@end +@implementation RuneClockProbe +- (void)tick:(CADisplayLink *)link { + double now = CACurrentMediaTime(); + CVTimeStamp at = {0}, target = {0}; + at.hostTime = CVGetCurrentHostTime(); + target.hostTime = at.hostTime + (int64_t)((link.targetTimestamp - now) * CVGetHostClockFrequency()); + target.videoTimeScale = 1000000000; + target.videoRefreshPeriod = (int64_t)((link.targetTimestamp - link.timestamp) * 1e9); + target.flags = kCVTimeStampHostTimeValid | kCVTimeStampVideoRefreshPeriodValid; + CVOptionFlags flags = 0; + if (!self.count++) self.first = now; + self.last = now; + self.callback(self.cv, &at, &target, 0, &flags, self.context); +} +@end + +static NSMutableDictionary<NSValue *, RuneClockProbe *> *clocks; +static CVReturn counted(CVDisplayLinkRef link, const CVTimeStamp *now, const CVTimeStamp *target, + CVOptionFlags in, CVOptionFlags *out, void *context) { + RuneClockProbe *probe = (__bridge RuneClockProbe *)context; + double at = CACurrentMediaTime(); + if (!probe.count++) probe.first = at; + probe.last = at; + return probe.callback(link, now, target, in, out, probe.context); +} +static CVReturn probeSet(CVDisplayLinkRef link, CVDisplayLinkOutputCallback callback, void *context) { + if (!getenv("STEADY_CLOCK")) return CVDisplayLinkSetOutputCallback(link, callback, context); + if (!clocks) clocks = [NSMutableDictionary new]; + RuneClockProbe *probe = [RuneClockProbe new]; + probe.cv = link; probe.callback = callback; probe.context = context; + clocks[[NSValue valueWithPointer:link]] = probe; + return CVDisplayLinkSetOutputCallback(link, counted, (__bridge void *)probe); +} +static CVReturn probeStart(CVDisplayLinkRef link) { + RuneClockProbe *probe = clocks[[NSValue valueWithPointer:link]]; + if (!getenv("STEADY_CA") || !probe) return CVDisplayLinkStart(link); + if (@available(macOS 14.0, *)) { + NSView *view = nil; + for (NSWindow *window in NSApp.windows) + if ([window isKindOfClass:NSPanel.class] && window.visible) { view = window.contentView; break; } + if (!view) return kCVReturnError; + probe.ca = [view displayLinkWithTarget:probe selector:@selector(tick:)]; + probe.ca.preferredFrameRateRange = CAFrameRateRangeMake(80, 120, 120); + [probe.ca addToRunLoop:NSRunLoop.mainRunLoop forMode:NSRunLoopCommonModes]; + return kCVReturnSuccess; + } + return kCVReturnError; +} +static CVReturn probeStop(CVDisplayLinkRef link) { + RuneClockProbe *probe = clocks[[NSValue valueWithPointer:link]]; + CVReturn status = kCVReturnSuccess; + if (probe.ca) { [probe.ca invalidate]; probe.ca = nil; } + else status = CVDisplayLinkStop(link); + if (probe.count > 1) fprintf(stderr, "steady clock source=%s callbacks=%u hz=%.3f\n", + getenv("STEADY_CA") ? "ca" : "cv", probe.count, (probe.count - 1) / (probe.last - probe.first)); + probe.count = 0; + return status; +} +#define INTERPOSE(new, old) __attribute__((used)) static struct { const void *replacement; const void *original; } \ + interpose_##old __attribute__((section("__DATA,__interpose"))) = { (const void *)&new, (const void *)&old } +INTERPOSE(probeSet, CVDisplayLinkSetOutputCallback); +INTERPOSE(probeStart, CVDisplayLinkStart); +INTERPOSE(probeStop, CVDisplayLinkStop); diff --git a/app/vendor/rune/scripts/native-pacing/commit-probe.py b/app/vendor/rune/scripts/native-pacing/commit-probe.py new file mode 100644 index 0000000..0505f63 --- /dev/null +++ b/app/vendor/rune/scripts/native-pacing/commit-probe.py @@ -0,0 +1,77 @@ +"""Pro-only, no capture. Post-commit cadence of the `pacing` example under /tmp/pro-gui.lock. + +python3 scripts/native-pacing/commit-probe.py <out> <pacing executable> [runs] + +Each burst starts after an idle gap. Prints the first acquisition (`nextDrawable` entry) and +positive Metal presentedTime intervals of each burst, plus totals over all bursts. +""" +import fcntl +import json +import os +import re +import socket +import statistics +import subprocess +import sys +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) +from perf_binary import perf_binary + +assert socket.gethostname().startswith("Kits-Shiny-Computer"), "Pro only" +out, pacing = Path(sys.argv[1]).resolve(), perf_binary(sys.argv[2]) +runs = int(sys.argv[3]) if len(sys.argv) > 3 else 3 +out.mkdir(parents=True, exist_ok=True) +library = out / "steady-probe.dylib" +subprocess.run(["clang", "-dynamiclib", "-fobjc-arc", "-fblocks", "-O2", str(Path(__file__).with_name("steady-probe.m")), + "-framework", "AppKit", "-framework", "QuartzCore", "-framework", "Metal", "-o", str(library)], check=True) +env = {k: v for k, v in os.environ.items() if not k.startswith("STEADY_")} +env["DYLD_INSERT_LIBRARIES"] = str(library) + + +def gaps(times): + return [round((b - a) * 1000, 1) for a, b in zip(times, times[1:])] + + +summary = [] +with open("/tmp/pro-gui.lock", "a") as lock: + fcntl.flock(lock, fcntl.LOCK_EX) + try: + for run in range(runs): + log = out / f"{run}-pacing.log" + trace = out / f"{run}-pacing.jsonl" + with log.open("w") as output: + subprocess.run([str(pacing), "--native", "--trace", str(trace)], env=env, stdout=output, + stderr=subprocess.STDOUT, timeout=60, check=True) + rows = [{k: float(v) for k, v in re.findall(r"(\w+)=([\d.]+)", line)} + for line in log.read_text().splitlines() if line.startswith("steady frame ")] + rows.sort(key=lambda r: r["entered"]) + bursts, current = [], [] + for row in rows: + if current and row["entered"] - current[-1]["entered"] > 0.05: + bursts.append(current) + current = [] + current.append(row) + bursts.append(current) + for index, burst in enumerate(bursts[1:], 1): + presented = sorted(r["presented"] for r in burst if r["presented"] > 0) + result = dict(run=run, burst=index, frames=len(burst), zero=sum(r["presented"] == 0 for r in burst), + acquisition_gaps_ms=gaps([r["entered"] for r in burst]), + presentation_gaps_ms=gaps(presented), + latency_ms=round(statistics.median((r["presented"] - r["entered"]) * 1000 + for r in burst if r["presented"] > 0), 1), + wait_ms=round(statistics.median((r["acquired"] - r["entered"]) * 1000 for r in burst), 2)) + summary.append(result) + print(json.dumps(result), flush=True) + finally: + library.unlink(missing_ok=True) +acquisition = [g for r in summary for g in r["acquisition_gaps_ms"]] +presentation = [g for r in summary for g in r["presentation_gaps_ms"]] +first = [g for r in summary for g in r["acquisition_gaps_ms"][:4]] +total = dict(bursts=len(summary), frames=sum(r["frames"] for r in summary), + median_acquisition_ms=statistics.median(acquisition), median_presentation_ms=statistics.median(presentation), + first_four_acquisition_gaps_under_12ms=sum(g < 12 for g in first), first_four_acquisition_gaps=len(first), + presentation_gaps_under_12ms=sum(g < 12 for g in presentation), + median_latency_ms=statistics.median(r["latency_ms"] for r in summary)) +(out / "summary.json").write_text(json.dumps(dict(total=total, bursts=summary), indent=2) + "\n") +print(json.dumps(total), flush=True) diff --git a/app/vendor/rune/scripts/native-pacing/refresh-probe.m b/app/vendor/rune/scripts/native-pacing/refresh-probe.m new file mode 100644 index 0000000..bf0d195 --- /dev/null +++ b/app/vendor/rune/scripts/native-pacing/refresh-probe.m @@ -0,0 +1,150 @@ +// Minimal native CAMetalLayer presenter, independent of Rune and wgpu. Prints the display's +// power and refresh state, then measures positive presentedTime cadence and the screen's +// framebuffer-update cadence for one presentation variant. +// refresh-probe <present|transaction|minduration|unsynced> <sub|backing> <drawables> <seconds> +#import <AppKit/AppKit.h> +#import <QuartzCore/QuartzCore.h> +#import <Metal/Metal.h> +#import <CoreVideo/CoreVideo.h> + +static NSString *mode, *host; +static int drawables; +static double seconds; +static CAMetalLayer *layer; +static id<MTLCommandQueue> queue; +static NSMutableArray<NSNumber *> *presented, *updates, *callbacks; +static double started; +static NSScreen *screen; + +static void summary(NSString *name, NSArray<NSNumber *> *times) { + NSArray<NSNumber *> *sorted = [times sortedArrayUsingSelector:@selector(compare:)]; + NSMutableDictionary<NSNumber *, NSNumber *> *ticks = [NSMutableDictionary dictionary]; + double first = 0, last = 0; + for (NSUInteger i = 1; i < sorted.count; i++) { + double gap = (sorted[i].doubleValue - sorted[i - 1].doubleValue) * 1000; + NSNumber *key = @(lround(gap / (1000.0 / 120))); + ticks[key] = @(ticks[key].intValue + 1); + } + if (sorted.count > 1) { first = sorted.firstObject.doubleValue; last = sorted.lastObject.doubleValue; } + NSMutableString *histogram = [NSMutableString string]; + for (NSNumber *key in [ticks.allKeys sortedArrayUsingSelector:@selector(compare:)]) + [histogram appendFormat:@" %@t:%@", key, ticks[key]]; + printf("probe %s n=%lu hz=%.2f gaps_in_120hz_ticks=%s\n", name.UTF8String, (unsigned long)sorted.count, + sorted.count > 1 ? (sorted.count - 1) / (last - first) : 0, histogram.UTF8String); +} + +@interface Target : NSObject +@end +@implementation Target +- (void)tick:(CADisplayLink *)link { + double now = CACurrentMediaTime(); + if (now - started > seconds) { + [link invalidate]; + dispatch_after(dispatch_time(DISPATCH_TIME_NOW, NSEC_PER_SEC / 2), dispatch_get_main_queue(), ^{ + printf("probe variant mode=%s host=%s drawables=%d presents_with_transaction=%d display_sync=%d opaque=%d format=%lu\n", + mode.UTF8String, host.UTF8String, drawables, layer.presentsWithTransaction, + layer.displaySyncEnabled, layer.opaque, (unsigned long)layer.pixelFormat); + summary(@"callbacks", callbacks); + summary(@"positive_presentations", presented); + summary(@"screen_updates", updates); + exit(0); + }); + return; + } + [callbacks addObject:@(now)]; + if (@available(macOS 12.0, *)) { + NSNumber *update = @(screen.lastDisplayUpdateTimestamp); + if (update.doubleValue > 0 && ![updates.lastObject isEqual:update]) [updates addObject:update]; + } + id<CAMetalDrawable> drawable = [layer nextDrawable]; + if (!drawable) return; + BOOL measured = now - started > 1; + [drawable addPresentedHandler:^(id<MTLDrawable> d) { + if (measured && d.presentedTime > 0) dispatch_async(dispatch_get_main_queue(), ^{ [presented addObject:@(d.presentedTime)]; }); + }]; + MTLRenderPassDescriptor *pass = [MTLRenderPassDescriptor renderPassDescriptor]; + pass.colorAttachments[0].texture = drawable.texture; + pass.colorAttachments[0].loadAction = MTLLoadActionClear; + pass.colorAttachments[0].storeAction = MTLStoreActionStore; + double phase = fmod(now, 1.0); + pass.colorAttachments[0].clearColor = MTLClearColorMake(0.1 * phase, 0.3 * phase, 0.6 * phase, 0.6 + 0.3 * phase); + id<MTLCommandBuffer> buffer = [queue commandBuffer]; + [[buffer renderCommandEncoderWithDescriptor:pass] endEncoding]; + if ([mode isEqual:@"transaction"]) { + [buffer commit]; + [buffer waitUntilScheduled]; + [drawable present]; + } else { + if ([mode isEqual:@"minduration"]) [buffer presentDrawable:drawable afterMinimumDuration:1.0 / 120]; + else [buffer presentDrawable:drawable]; + [buffer commit]; + } +} +@end + +int main(int argc, char **argv) { + @autoreleasepool { + mode = argc > 1 ? @(argv[1]) : @"present"; + host = argc > 2 ? @(argv[2]) : @"sub"; + drawables = argc > 3 ? atoi(argv[3]) : 3; + seconds = argc > 4 ? atof(argv[4]) : 5; + [NSApplication sharedApplication]; + NSApp.activationPolicy = NSApplicationActivationPolicyAccessory; + screen = NSScreen.mainScreen; + CGDirectDisplayID display = [screen.deviceDescription[@"NSScreenNumber"] unsignedIntValue]; + CGDisplayModeRef displayMode = CGDisplayCopyDisplayMode(display); + CVDisplayLinkRef cv; + CVDisplayLinkCreateWithCGDisplay(display, &cv); + CVTime nominal = CVDisplayLinkGetNominalOutputVideoRefreshPeriod(cv); + printf("probe system low_power=%d thermal=%ld max_fps=%ld min_interval_ms=%.3f max_interval_ms=%.3f granularity_ms=%.3f mode_hz=%.2f cv_nominal_ms=%.3f builtin=%d asleep=%d\n", + NSProcessInfo.processInfo.isLowPowerModeEnabled, (long)NSProcessInfo.processInfo.thermalState, + (long)screen.maximumFramesPerSecond, screen.minimumRefreshInterval * 1000, screen.maximumRefreshInterval * 1000, + screen.displayUpdateGranularity * 1000, CGDisplayModeGetRefreshRate(displayMode), + nominal.timeScale ? 1000.0 * nominal.timeValue / nominal.timeScale : 0, CGDisplayIsBuiltin(display), + CGDisplayIsAsleep(display)); + CGDisplayModeRelease(displayMode); + CVDisplayLinkRelease(cv); + + NSRect frame = NSMakeRect(NSMidX(screen.frame) - 340, NSMaxY(screen.visibleFrame) - 200, 680, 160); + NSPanel *panel = [[NSPanel alloc] initWithContentRect:frame + styleMask:NSWindowStyleMaskBorderless | NSWindowStyleMaskNonactivatingPanel backing:NSBackingStoreBuffered defer:NO]; + panel.opaque = NO; + panel.backgroundColor = NSColor.clearColor; + panel.level = NSStatusWindowLevel; + panel.hasShadow = NO; + panel.ignoresMouseEvents = YES; + NSView *view = [[NSView alloc] initWithFrame:NSMakeRect(0, 0, 680, 160)]; + layer = [CAMetalLayer layer]; + layer.device = MTLCreateSystemDefaultDevice(); + layer.pixelFormat = MTLPixelFormatBGRA8Unorm_sRGB; + layer.opaque = NO; + layer.maximumDrawableCount = drawables; + layer.displaySyncEnabled = ![mode isEqual:@"unsynced"]; + layer.presentsWithTransaction = [mode isEqual:@"transaction"]; + layer.contentsScale = screen.backingScaleFactor; + layer.drawableSize = CGSizeMake(680 * screen.backingScaleFactor, 160 * screen.backingScaleFactor); + if ([host isEqual:@"backing"]) { + view.layer = layer; + view.wantsLayer = YES; + } else { + view.wantsLayer = YES; + layer.frame = view.layer.bounds; + [view.layer addSublayer:layer]; + } + panel.contentView = view; + [panel orderFrontRegardless]; + queue = [layer.device newCommandQueue]; + presented = [NSMutableArray array]; + updates = [NSMutableArray array]; + callbacks = [NSMutableArray array]; + started = CACurrentMediaTime(); + CADisplayLink *link = [view displayLinkWithTarget:[Target new] selector:@selector(tick:)]; + link.preferredFrameRateRange = CAFrameRateRangeMake(80, 120, 120); + [link addToRunLoop:NSRunLoop.mainRunLoop forMode:NSRunLoopCommonModes]; + dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)((seconds + 5) * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ + fprintf(stderr, "probe timeout\n"); + exit(2); + }); + [NSApp run]; + } +} diff --git a/app/vendor/rune/scripts/native-pacing/refresh-probe.py b/app/vendor/rune/scripts/native-pacing/refresh-probe.py new file mode 100644 index 0000000..9465a95 --- /dev/null +++ b/app/vendor/rune/scripts/native-pacing/refresh-probe.py @@ -0,0 +1,27 @@ +"""Pro-only, no capture. Runs refresh-probe.m variants under /tmp/pro-gui.lock. + +python3 scripts/native-pacing/refresh-probe.py <out> [mode:host:drawables ...] +""" +import fcntl +import socket +import subprocess +import sys +from pathlib import Path + +assert socket.gethostname().startswith("Kits-Shiny-Computer"), "Pro only" +out = Path(sys.argv[1]).resolve() +out.mkdir(parents=True, exist_ok=True) +variants = sys.argv[2:] or ["present:sub:3", "transaction:backing:3", "minduration:sub:3", "present:sub:2", "unsynced:sub:3"] +binary = out / "refresh-probe" +subprocess.run(["clang", "-fobjc-arc", "-O2", str(Path(__file__).with_name("refresh-probe.m")), + "-framework", "AppKit", "-framework", "QuartzCore", "-framework", "Metal", + "-framework", "CoreVideo", "-Wno-deprecated-declarations", "-o", str(binary)], check=True) +with open("/tmp/pro-gui.lock", "a") as lock: + fcntl.flock(lock, fcntl.LOCK_EX) + for variant in variants: + mode, host, drawables = variant.split(":") + result = subprocess.run([str(binary), mode, host, drawables, "5"], capture_output=True, text=True, timeout=30) + text = result.stdout + result.stderr + (out / f"{mode}-{host}-{drawables}.log").write_text(text) + print(text, flush=True) +binary.unlink(missing_ok=True) diff --git a/app/vendor/rune/scripts/native-pacing/run.py b/app/vendor/rune/scripts/native-pacing/run.py new file mode 100644 index 0000000..cb8932c --- /dev/null +++ b/app/vendor/rune/scripts/native-pacing/run.py @@ -0,0 +1,161 @@ +"""Pro-only, no capture. Same 3 batches x 3 intervals and endpoint as the overlay team's probe. + +Run through hash-checked GUI admission on the build queue. A matched 1360x320 Rune surface is +tested with both injected 60 Hz redraws and its real continuous animation scheduler. +""" +import argparse +import fcntl +import hashlib +import json +import math +import os +from pathlib import Path +import re +import socket +import signal +import statistics +import subprocess +import sys + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) +from perf_binary import perf_binary + +parser = argparse.ArgumentParser() +parser.add_argument("out", type=Path) +parser.add_argument("rune", type=Path) +parser.add_argument("--reference", type=Path) +parser.add_argument("--modes", default="injected,native") +parser.add_argument("--display-link", choices=["cv", "ca"], default="cv") +parser.add_argument("--drawables", choices=["2", "3"]) +parser.add_argument("--display-sync", choices=["0", "1"]) +parser.add_argument("--guard", choices=["production", "no-half"], help="requires the diagnostic admission patch") +args = parser.parse_args() +assert socket.gethostname().startswith("Kits-Shiny-Computer"), "Pro only" +root, rune = args.out.resolve(), perf_binary(args.rune) +root.mkdir(parents=True, exist_ok=True) + + +def stats(values): + if not values: + return None + return dict(n=len(values), median=statistics.median(values), + p95=sorted(values)[math.ceil(len(values) * .95) - 1], min=min(values), max=max(values)) + + +def parse(path, mode): + rows, configs, clocks, guards = [], [], [], [] + for line in path.read_text().splitlines(): + if line.startswith("steady config "): + configs.append(line) + if line.startswith("steady clock "): + clocks.append(line) + if line.startswith("steady guard "): + guards.append(line) + if line.startswith("steady frame "): + rows.append({k: float(v) for k, v in re.findall(r"(\w+)=([\d.]+)", line)}) + visible = [r for r in rows if r["visible"] and r["window"] > 0] + assert visible, f"no visible frames: {path}" + start = min(r["entered"] for r in visible) + 2 + selected = [r for r in visible if start <= r["entered"] < start + 9] + valid = [r for r in selected if r["presented"] >= r["acquired"]] + assert len(valid) >= 30, f"too few valid presentations: {path}" + intervals = [stats([(r["presented"] - r["entered"]) * 1000 for r in valid + if start + i * 3 <= r["entered"] < start + (i + 1) * 3]) for i in range(3)] + requests = [r for r in valid if 0 < r["requested"] <= r["entered"]] + entries = sorted(r["entered"] for r in selected) + gaps = [(b - a) * 1000 for a, b in zip(entries, entries[1:])] + presented = sorted(set(r["presented"] for r in valid)) + presentation_gaps = [(b - a) * 1000 for a, b in zip(presented, presented[1:])] + if args.guard and mode != "reference": + assert guards and all(f"mode={args.guard} " in line for line in guards), "wrong admission-probe binary" + return dict(configs=configs, clocks=clocks, guards=guards, positive=len(valid), visible_callbacks=len(selected), + acquisition_hz=(len(entries)-1)/(entries[-1]-entries[0]), + presentation_hz=(len(presented)-1)/(presented[-1]-presented[0]), + presentation_gaps_ms=stats(presentation_gaps), + zero_callbacks=sum(r["presented"] == 0 for r in selected), + acquire_to_present_ms=stats([(r["presented"] - r["entered"]) * 1000 for r in valid]), + next_drawable_wait_ms=stats([(r["acquired"] - r["entered"]) * 1000 for r in valid]), + request_to_present_ms=stats([(r["presented"] - r["requested"]) * 1000 for r in requests]), + acquisition_gaps_ms=stats(gaps), sub_half_refresh_gaps=sum(g < 4.166666 - .01 for g in gaps), + interval_medians=intervals) + + +with open("/tmp/pro-gui.lock", "a") as lock: + def lock_timeout(_signal, _frame): + raise TimeoutError("Pro GUI lock remained busy for ten minutes") + signal.signal(signal.SIGALRM, lock_timeout) + signal.alarm(600) + fcntl.flock(lock, fcntl.LOCK_EX) + signal.alarm(0) + for pattern in ["[r]une-smoke/ci/Hex.app", "[s]crawl lab"]: + assert subprocess.run(["pgrep", "-f", pattern], capture_output=True).returncode != 0, pattern + for name in ["overlay-lab", "pacing_overlay"]: + assert subprocess.run(["pgrep", "-x", name], capture_output=True).returncode != 0, name + library = root / "steady-probe.dylib" + subprocess.run(["clang", "-dynamiclib", "-fobjc-arc", "-fblocks", "-O2", + str(Path(__file__).with_name("steady-probe.m")), str(Path(__file__).with_name("clock-probe.m")), + "-Wno-deprecated-declarations", "-framework", "AppKit", "-framework", "CoreVideo", + "-framework", "QuartzCore", "-framework", "Metal", "-o", str(library)], check=True) + env = dict(os.environ, DYLD_INSERT_LIBRARIES=str(library)) + for key in ["OVERLAY_LAB_CONTROL", "OVERLAY_PROBE_REDRAW", "RUNE_OVERLAY_TRACE_INPUT", + "STEADY_RUNE_REDRAW", "STEADY_MAX_DRAWABLES", "STEADY_TRANSACTION", "PACING_NATIVE", + "STEADY_CA", "STEADY_CLOCK", "STEADY_DISPLAY_SYNC", "STEADY_GUARD"]: + env.pop(key, None) + modes = args.modes.split(",") + (["reference"] if args.reference else []) + assert all(mode in ["injected", "native", "reference"] for mode in modes) + results = [] + (root / "load-before.txt").write_bytes(subprocess.check_output(["top", "-l", "1", "-n", "0"])) + try: + for batch in range(3): + for mode in (modes if batch % 2 == 0 else list(reversed(modes))): + command = [str(rune)] if mode != "reference" else [str(args.reference.resolve()), "lab", "pill", + "tap-then-screen", "--repeat", "0", "--time-scale", "1", "--no-backdrop"] + runenv = dict(env) + if mode != "reference": + runenv["STEADY_CLOCK"] = "1" + if args.display_link == "ca": runenv["STEADY_CA"] = "1" + if args.drawables: runenv["STEADY_MAX_DRAWABLES"] = args.drawables + if args.display_sync: runenv["STEADY_DISPLAY_SYNC"] = args.display_sync + if args.guard: runenv["STEADY_GUARD"] = args.guard + if mode == "injected": + runenv["STEADY_RUNE_REDRAW"] = "1" + elif mode == "native": + runenv["PACING_NATIVE"] = "1" + log = root / f"{batch}-{mode}.log" + with log.open("w") as output: + process = subprocess.Popen(command, env=runenv, stdout=output, stderr=subprocess.STDOUT) + try: + process.wait(timeout=14 if mode == "reference" else 22) + assert mode != "reference" and process.returncode == 0, (mode, process.returncode) + except subprocess.TimeoutExpired: + if mode != "reference": + subprocess.run(["sample", str(process.pid), "1", "-file", str(root / f"{batch}-{mode}-timeout.txt")], timeout=10) + raise + finally: + if process.poll() is None: + process.terminate() + try: + process.wait(timeout=5) + except subprocess.TimeoutExpired: + process.kill() + process.wait(timeout=5) + result = dict(batch=batch, mode=mode, **parse(log, mode)) + results.append(result) + print(json.dumps(result), flush=True) + summary = dict(endpoint="nextDrawable entry to positive Metal presentedTime", + rune_sha256=hashlib.sha256(rune.read_bytes()).hexdigest(), runs=results, + experiment=dict(display_link=args.display_link, drawables=args.drawables, + display_sync=args.display_sync, guard=args.guard)) + if args.reference: + summary["reference_sha256"] = hashlib.sha256(args.reference.read_bytes()).hexdigest() + for mode in modes: + medians = [interval["median"] for r in results if r["mode"] == mode + for interval in r["interval_medians"] if interval] + assert len(medians) == 9, (mode, medians) + summary[mode] = stats(medians) + (root / "results.json").write_text(json.dumps(summary, indent=2) + "\n") + print(json.dumps({k: v for k, v in summary.items() if k != "runs"}), flush=True) + finally: + library.unlink(missing_ok=True) + (root / "load-after.txt").write_bytes(subprocess.check_output(["top", "-l", "1", "-n", "0"])) +print("All disposable apps exited; GUI lock released.", flush=True) diff --git a/app/vendor/rune/scripts/native-pacing/steady-probe.m b/app/vendor/rune/scripts/native-pacing/steady-probe.m new file mode 100644 index 0000000..20dc8a1 --- /dev/null +++ b/app/vendor/rune/scripts/native-pacing/steady-probe.m @@ -0,0 +1,64 @@ +// Same nextDrawable -> positive presentedTime endpoint as overlays/steady-state/steady-probe.m. +#import <AppKit/AppKit.h> +#import <QuartzCore/CAMetalLayer.h> +#import <Metal/Metal.h> +#import <objc/runtime.h> + +static id<CAMetalDrawable> (*originalNext)(id, SEL); +static char requestKey, configKey; +static dispatch_source_t timer; + +static NSWindow *ownerOf(CALayer *layer) { + for (NSWindow *window in NSApp.windows) { + CALayer *root = window.contentView.layer; + for (CALayer *p = layer; p; p = p.superlayer) + if (p == root) return window.contentView.window; + } + return nil; +} + +static id<CAMetalDrawable> nextDrawable(CAMetalLayer *layer, SEL selector) { + if (getenv("STEADY_MAX_DRAWABLES")) layer.maximumDrawableCount = atoi(getenv("STEADY_MAX_DRAWABLES")); + if (getenv("STEADY_DISPLAY_SYNC")) layer.displaySyncEnabled = atoi(getenv("STEADY_DISPLAY_SYNC")); + double entered = CACurrentMediaTime(); + id<CAMetalDrawable> drawable = originalNext(layer, selector); + double acquired = CACurrentMediaTime(); + if (!drawable) return drawable; + NSWindow *owner = ownerOf(layer); + NSInteger windowID = owner.windowNumber; + BOOL visible = owner.visible && owner.alphaValue > 0; + NSNumber *request = objc_getAssociatedObject(owner, &requestKey); + double requested = request.doubleValue; + if (owner) objc_setAssociatedObject(owner, &requestKey, nil, OBJC_ASSOCIATION_RETAIN_NONATOMIC); + if (!objc_getAssociatedObject(layer, &configKey)) { + objc_setAssociatedObject(layer, &configKey, @YES, OBJC_ASSOCIATION_RETAIN_NONATOMIC); + fprintf(stderr, "steady config window=%ld max_drawables=%lu transaction=%d display_sync=%d width=%.0f height=%.0f screen_hz=%ld\n", + (long)windowID, (unsigned long)layer.maximumDrawableCount, layer.presentsWithTransaction, + layer.displaySyncEnabled, layer.drawableSize.width, layer.drawableSize.height, + (long)owner.screen.maximumFramesPerSecond); + } + [drawable addPresentedHandler:^(id<MTLDrawable> d) { + fprintf(stderr, "steady frame window=%ld visible=%d requested=%.9f entered=%.9f acquired=%.9f presented=%.9f callback=%.9f\n", + (long)windowID, visible, requested, entered, acquired, d.presentedTime, CACurrentMediaTime()); + }]; + return drawable; +} + +__attribute__((constructor)) static void install(void) { + Method method = class_getInstanceMethod(CAMetalLayer.class, @selector(nextDrawable)); + originalNext = (void *)method_setImplementation(method, (IMP)nextDrawable); + if (!getenv("STEADY_RUNE_REDRAW")) return; + dispatch_async(dispatch_get_main_queue(), ^{ + timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatch_get_main_queue()); + dispatch_source_set_timer(timer, dispatch_time(DISPATCH_TIME_NOW, NSEC_PER_SEC), NSEC_PER_SEC / 60, 0); + dispatch_source_set_event_handler(timer, ^{ + for (NSWindow *window in NSApp.windows) { + if (![window isKindOfClass:NSPanel.class] || !window.visible || window.alphaValue <= 0) continue; + if (!objc_getAssociatedObject(window, &requestKey)) + objc_setAssociatedObject(window, &requestKey, @(CACurrentMediaTime()), OBJC_ASSOCIATION_RETAIN_NONATOMIC); + window.contentView.needsDisplay = YES; + } + }); + dispatch_resume(timer); + }); +} diff --git a/app/vendor/rune/scripts/perf_binary.py b/app/vendor/rune/scripts/perf_binary.py new file mode 100644 index 0000000..43344e0 --- /dev/null +++ b/app/vendor/rune/scripts/perf_binary.py @@ -0,0 +1,23 @@ +"""Benchmarks time `--profile perf` binaries only. Release builds are incremental, which can move timings.""" +import os +from pathlib import Path +import sys + + +def _is_target(path): + target = os.environ.get('CARGO_TARGET_DIR') + return path.name == 'target' or (target is not None and path == Path(target).resolve()) + + +def perf_binary(path): + path = Path(path).resolve() + profile = path.parent.parent if path.parent.name == 'examples' else path.parent + # <target>/perf/<bin>, <target>/perf/examples/<bin> or <target>/<triple>/perf/... + if profile.name != 'perf' or not (_is_target(profile.parent) or _is_target(profile.parent.parent)): + sys.exit(f'refusing to benchmark {path}: not a --profile perf build.\n' + 'Build with `cargo build --profile perf -p <package>` and pass target/perf/<binary> ' + '(target/perf/examples/<example> for examples; a saved copy must keep the ' + 'target/perf/ layout). Release builds are incremental, so their timings are not comparable.') + if not path.is_file(): + sys.exit(f'missing perf binary {path}: build it with `cargo build --profile perf`.') + return path diff --git a/app/vendor/rune/scripts/precompile-metal-shaders.sh b/app/vendor/rune/scripts/precompile-metal-shaders.sh new file mode 100644 index 0000000..5a5f97e --- /dev/null +++ b/app/vendor/rune/scripts/precompile-metal-shaders.sh @@ -0,0 +1,167 @@ +#!/bin/sh +# Regenerates crates/rune/src/shaders/uber.metallib (wgpu's Metal backend), crates/rune/src/shaders/uber_native.metallib +# (Rune's own, `metal-backend`) and crates/rune/src/render/uber/metallib_hash.rs from +# crates/rune/src/shaders/{clip,shader}.wgsl using wgpu::naga and Xcode's Metal toolchain, the Windfoil +# variant's crates/rune/src/shaders/uber_windfoil{,_native}.metallib and render/uber/windfoil_hash.rs, then +# crates/rune-gpu/src/shaders/builtin_native{,_ios,_ios_sim}.metallib and crates/rune-gpu/src/metal/builtin_table.rs: +# every other pipeline Rune, rune-fx and rune-light ship, captured from Rune's Metal backend. +# App builds embed the committed libraries and do not run xcrun. Needs a Mac with a GPU. +set -eu + +cd "$(dirname "$0")/.." + +if ! xcrun -sdk macosx --find metal >/dev/null 2>&1; then + echo "error: xcrun -sdk macosx metal not found (install Xcode or Metal Toolchain)" >&2 + exit 1 +fi + +tmp="$(mktemp -d "${TMPDIR:-/tmp}/rune-metallib.XXXXXX")" +trap 'rm -rf "$tmp"' EXIT + +if ! cargo test --locked -p rune --features metal-backend --lib render::metallib::tests::dump_uber_msl -- --ignored --exact --nocapture >"$tmp/dump.txt" 2>&1; then + cat "$tmp/dump.txt" >&2 + exit 1 +fi + +python3 - "$tmp/dump.txt" "$tmp" <<'PY' +import pathlib, re, sys + +text = pathlib.Path(sys.argv[1]).read_text() +out = pathlib.Path(sys.argv[2]) + +def extract(tag: str) -> str: + m = re.search(rf"---BEGIN_{tag}---\n(.*?)\n?---END_{tag}---", text, re.S) + if not m: + raise SystemExit(f"missing {tag} in dump output") + return m.group(1) + +(out / "wgsl.blake3").write_text(extract("WGSL_BLAKE3").strip()) +(out / "msl.blake3").write_text(extract("MSL_BLAKE3").strip()) +(out / "flags.txt").write_text(extract("METAL_FLAGS").strip()) +(out / "abi.fnv64").write_text(extract("ABI_FNV64").strip()) +(out / "options.fnv64").write_text(extract("OPTIONS_FNV64").strip()) +(out / "vs.metal").write_text(extract("VS_MSL") + "\n") +(out / "fs.metal").write_text(extract("FS_MSL") + "\n") +(out / "native.blake3").write_text(extract("NATIVE_MSL_BLAKE3").strip()) +(out / "native_flags.txt").write_text(extract("NATIVE_METAL_FLAGS").strip()) +(out / "native_vs.metal").write_text(extract("NATIVE_VS_MSL") + "\n") +(out / "native_fs.metal").write_text(extract("NATIVE_FS_MSL") + "\n") +(out / "windfoil.blake3").write_text(extract("WINDFOIL_WGSL_BLAKE3").strip()) +(out / "windfoil_abi.fnv64").write_text(extract("WINDFOIL_ABI_FNV64").strip()) +(out / "windfoil_vs.metal").write_text(extract("WINDFOIL_VS_MSL") + "\n") +(out / "windfoil_fs.metal").write_text(extract("WINDFOIL_FS_MSL") + "\n") +(out / "windfoil_native_vs.metal").write_text(extract("WINDFOIL_NATIVE_VS_MSL") + "\n") +(out / "windfoil_native_fs.metal").write_text(extract("WINDFOIL_NATIVE_FS_MSL") + "\n") +PY + +flags="$(cat "$tmp/flags.txt")" +# shellcheck disable=SC2086 +xcrun -sdk macosx metal $flags -c "$tmp/vs.metal" -o "$tmp/vs.air" +# shellcheck disable=SC2086 +xcrun -sdk macosx metal $flags -c "$tmp/fs.metal" -o "$tmp/fs.air" +xcrun -sdk macosx metallib "$tmp/vs.air" "$tmp/fs.air" -o crates/rune/src/shaders/uber.metallib + +native_flags="$(cat "$tmp/native_flags.txt")" +# shellcheck disable=SC2086 +xcrun -sdk macosx metal $native_flags -c "$tmp/native_vs.metal" -o "$tmp/native_vs.air" +# shellcheck disable=SC2086 +xcrun -sdk macosx metal $native_flags -c "$tmp/native_fs.metal" -o "$tmp/native_fs.air" +xcrun -sdk macosx metallib "$tmp/native_vs.air" "$tmp/native_fs.air" -o crates/rune/src/shaders/uber_native.metallib + +python3 - "$tmp" crates/rune/src/shaders/uber.metallib crates/rune/src/render/uber/metallib_hash.rs crates/rune/src/shaders/uber_native.metallib <<'PY' +import pathlib, sys + +tmp = pathlib.Path(sys.argv[1]) +metallib_path = pathlib.Path(sys.argv[2]) +hash_rs_path = pathlib.Path(sys.argv[3]) + +wgsl_hash = (tmp / "wgsl.blake3").read_text().strip() +msl_hash = (tmp / "msl.blake3").read_text().strip() +native_hash = (tmp / "native.blake3").read_text().strip() +data = metallib_path.read_bytes() + +def fnv64(data): + h = 0xcbf29ce484222325 + for b in data: + h = ((h ^ b) * 0x100000001b3) & 0xFFFFFFFFFFFFFFFF + return h + +h = fnv64(data) +native_h = fnv64(pathlib.Path(sys.argv[4]).read_bytes()) +native_cfg = '#[cfg(all(test, target_os = "macos", feature = "metal-backend"))]\n' + +hash_rs_path.write_text( + "// Generated by scripts/precompile-metal-shaders.sh, or refreshed from the freshness test when MSL is unchanged.\n" + '#[cfg(any(test, target_os = "macos"))]\n' + f'pub(super) const UBER_WGSL_BLAKE3: &str = "{wgsl_hash}";\n' + '#[cfg(any(test, target_os = "macos"))]\n' + f'pub(super) const UBER_ABI_FNV64: u64 = 0x{(tmp / "abi.fnv64").read_text().strip()};\n' + "#[cfg(all(test, target_os = \"macos\"))]\n" + f'pub(super) const UBER_MSL_OPTIONS_FNV64: u64 = 0x{(tmp / "options.fnv64").read_text().strip()};\n' + "#[cfg(test)]\n" + f'pub(super) const UBER_MSL_BLAKE3: &str = "{msl_hash}";\n' + "#[cfg(test)]\n" + f"pub(super) const UBER_METALLIB_FNV64: u64 = 0x{h:016x};\n" + + native_cfg + + f'pub(super) const UBER_NATIVE_MSL_BLAKE3: &str = "{native_hash}";\n' + + native_cfg + + f"pub(super) const UBER_NATIVE_METALLIB_FNV64: u64 = 0x{native_h:016x};\n" +) +print(f"wrote {metallib_path} ({len(data)} bytes, fnv64=0x{h:016x})") +PY + +# The Windfoil uber variant (crates/rune/src/render/variant.rs), which only a renderer drawing +# glyphs from outlines loads: uber_windfoil.metallib (wgpu) and uber_windfoil_native.metallib (Rune's). +# shellcheck disable=SC2086 +xcrun -sdk macosx metal $flags -c "$tmp/windfoil_vs.metal" -o "$tmp/windfoil_vs.air" +# shellcheck disable=SC2086 +xcrun -sdk macosx metal $flags -c "$tmp/windfoil_fs.metal" -o "$tmp/windfoil_fs.air" +xcrun -sdk macosx metallib "$tmp/windfoil_vs.air" "$tmp/windfoil_fs.air" -o crates/rune/src/shaders/uber_windfoil.metallib +# shellcheck disable=SC2086 +xcrun -sdk macosx metal $native_flags -c "$tmp/windfoil_native_vs.metal" -o "$tmp/windfoil_native_vs.air" +# shellcheck disable=SC2086 +xcrun -sdk macosx metal $native_flags -c "$tmp/windfoil_native_fs.metal" -o "$tmp/windfoil_native_fs.air" +xcrun -sdk macosx metallib "$tmp/windfoil_native_vs.air" "$tmp/windfoil_native_fs.air" -o crates/rune/src/shaders/uber_windfoil_native.metallib +printf '%s\n' \ + "// Generated by scripts/precompile-metal-shaders.sh. Empty until a Mac has built uber_windfoil.metallib." \ + "pub(super) const WINDFOIL_WGSL_BLAKE3: &str = \"$(cat "$tmp/windfoil.blake3")\";" \ + "pub(super) const WINDFOIL_ABI_FNV64: u64 = 0x$(cat "$tmp/windfoil_abi.fnv64");" \ + > crates/rune/src/render/uber/windfoil_hash.rs +echo "wrote crates/rune/src/shaders/uber_windfoil.metallib and uber_windfoil_native.metallib" + +# Every other built-in pipeline (crates/rune-gpu/src/metal/builtin.rs), captured once and compiled +# for macOS, iOS and the iOS simulator. MSL 3.0 needs macOS 13 and iOS 16. RUNE_DISABLE_METALLIB +# makes the uber shader compile from WGSL so it's captured too: iOS has no uber_native.metallib. +cap="$tmp/capture" +mkdir -p "$cap" +if ! RUNE_GPU_BACKEND=metal RUNE_DISABLE_METALLIB=1 RUNE_METAL_CAPTURE="$cap" cargo test --locked -p rune-light --features rune/metal-backend --test builtin_shaders >"$tmp/capture.txt" 2>&1; then + cat "$tmp/capture.txt" >&2 + exit 1 +fi +ios_flags="$(echo "$native_flags" | sed 's/-mmacosx-version-min=13.0/-mios-version-min=16.0/')" +sim_flags="$(echo "$native_flags" | sed 's/-mmacosx-version-min=13.0/-mios-simulator-version-min=16.0/')" +for target in "macosx:$native_flags:builtin_native" "iphoneos:$ios_flags:builtin_native_ios" "iphonesimulator:$sim_flags:builtin_native_ios_sim"; do + sdk="${target%%:*}" rest="${target#*:}" + flags="${rest%:*}" name="${rest##*:}" + mkdir -p "$cap/$sdk" + export sdk flags + # shellcheck disable=SC2016 + find "$cap" -maxdepth 1 -name '*.metal' -print0 | xargs -0 -P 8 -n 1 sh -c 'xcrun -sdk "$sdk" metal $flags -Wno-unused-variable -c "$1" -o "$(dirname "$1")/$sdk/$(basename "${1%.metal}").air"' sh + xcrun -sdk "$sdk" metallib "$cap/$sdk"/*.air -o "crates/rune-gpu/src/shaders/$name.metallib" +done + +python3 - "$cap" crates/rune-gpu/src/metal/builtin_table.rs <<'PY' +import pathlib, sys + +cap = pathlib.Path(sys.argv[1]) +rows = "".join(p.read_text() for p in sorted(cap.glob("*.row"))) +sources = "".join(f' "{p.stem}",\n' for p in sorted(cap.glob("*.source"))) +pathlib.Path(sys.argv[2]).write_text( + "// Generated by scripts/precompile-metal-shaders.sh: the built-in shaders' WGSL hashes, and each\n" + "// precompiled pipeline's key, function, sized bindings, workgroup size and workgroup memory sizes,\n" + "// sorted by key.\n" + f"const SOURCES: &[&str] = &[\n{sources}];\n" + f"const FUNCTIONS: &[(&str, &str, &[(u32, u32)], [u32; 3], &[u32])] = &[\n{rows}];\n" +) +print(f"wrote {sys.argv[2]} ({len(list(cap.glob('*.row')))} pipelines)") +PY diff --git a/app/vendor/rune/scripts/real-frames.py b/app/vendor/rune/scripts/real-frames.py new file mode 100644 index 0000000..8c217e0 --- /dev/null +++ b/app/vendor/rune/scripts/real-frames.py @@ -0,0 +1,479 @@ +#!/usr/bin/env python3 +"""Real-app frame costs from headless runs: per-frame distributions, launch and memory, and +where the main thread's time goes. + + run Runs an app's scenarios from a JSON config, alternating their order across runs, + with RUNE_FRAME_LOG set (build the app with rune/frame-profile). `--sample` adds one + extra run per scenario under macOS `sample`, kept apart from the timed runs. + summary Reads a run directory: per scenario and window, frame CPU p50/p95/p99/max and frames + over the 120 Hz budget (median across runs, warmup left out), phase means, memory, + and committing frames by reason (the frame log's `why`: poll, input, layout, read, + dirty, relayout, settle, virtual, route; "other" for a commit outside the frame's checks). + profile Buckets a `sample` dump's main thread by self time (`--binary` adds file:line for + the hottest functions through atos). + +Config: {"binary": "...", "args": [...], "env": {...}, "fps": 120, "size": "1240x780", + "scenarios": {"name": {"args": [...], "env": {...}, "frames": 600, + "script": [events] | "path", "windows": {"scroll": [1.0, 4.5]}}}} +Relative paths in the config resolve against the config's directory; "$OUT" in args and env +becomes the run directory. + +Headless numbers are main-thread CPU for update, build, layout, paint and encode/submit. They +leave out GPU execution, presentation, display timing and the window server, and headless draws +every frame, so a frame "drawn" here may be one a real window skips: summary also reports the +frames a window would draw (input arrived, a commit, or something animating). +""" +import argparse +import json +import math +import os +import re +import shutil +import statistics +import subprocess +import sys +import time +from pathlib import Path + +BUDGET_MS = 1000 / 120 + + +def load_config(path): + cfg = json.loads(Path(path).read_text()) + cfg["_dir"] = Path(path).resolve().parent + return cfg + + +def resolve(cfg, value, out): + value = os.path.expandvars(str(value).replace("$OUT", str(out))) + if value.startswith(("./", "../")): + return str((cfg["_dir"] / value).resolve()) + return value + + +def command(cfg, name, sc, out, log): + script = sc.get("script") + if isinstance(script, list): + path = out / f"{name}.script.json" + path.write_text(json.dumps(script)) + script = str(path) + elif script: + script = resolve(cfg, script, out) + args = [resolve(cfg, cfg["binary"], out)] + args += [resolve(cfg, a, out) for a in cfg.get("args", []) + sc.get("args", [])] + if script: + args += ["--script", script] + args += ["--fps", str(cfg.get("fps", 120)), "--frames", str(sc.get("frames", 600))] + if cfg.get("size") and "--size" not in args: + args += ["--size", cfg["size"]] + env = dict(os.environ) + env.update({k: resolve(cfg, v, out) for k, v in {**cfg.get("env", {}), **sc.get("env", {})}.items()}) + if log: + env["RUNE_FRAME_LOG"] = str(log) + cwd = resolve(cfg, sc.get("cwd", cfg.get("cwd", ".")), out) + return args, env, cwd + + +def setup(cfg, sc, out): + for step in cfg.get("setup", []) + sc.get("setup", []): + subprocess.run(resolve(cfg, step, out), shell=True, check=True, cwd=cfg["_dir"]) + + +def run(args): + cfg = load_config(args.config) + out = Path(args.out).resolve() + out.mkdir(parents=True, exist_ok=True) + names = [n for n in cfg["scenarios"] if not args.only or n in args.only.split(",")] + failed = set() + for n in range(args.runs + 1): + order = names if n % 2 == 0 else names[::-1] + for name in order: + if name in failed: + continue + sc = cfg["scenarios"][name] + setup(cfg, sc, out) + log = out / f"{name}-{n}.jsonl" + cmd, env, cwd = command(cfg, name, sc, out, log) + start = time.monotonic() + p = subprocess.run(cmd, env=env, cwd=cwd, capture_output=True, text=True, timeout=args.timeout) + wall = time.monotonic() - start + text = p.stdout + p.stderr + (out / f"{name}-{n}.log").write_text(text) + if p.returncode: + # Keep going with the other scenarios; the log keeps the failure. + print(f"{name} run {n} failed ({p.returncode}): {text[-1500:]}", file=sys.stderr, flush=True) + failed.add(name) + if log.exists(): + log.rename(log.with_suffix(".failed")) + continue + launch = next((json.loads(l.split(" ", 1)[1]) for l in text.splitlines() if l.startswith("rune-first-pixels ")), None) + with log.open("a") as f: + f.write(json.dumps({"run": n, "warmup": n == 0, "process_wall_s": wall, "launch": launch}) + "\n") + print(f"{name} run {n}: {wall:.2f} s", flush=True) + if args.sample: + for name in (n for n in names if n not in failed): + sc = cfg["scenarios"][name] + setup(cfg, sc, out) + cmd, env, cwd = command(cfg, name, sc, out, None) + # A still of the last frame, to check the scenario did what it says. + if "--snap" not in cmd: + cmd += ["--snap", str(out / f"{name}.check.png"), "--at", f"{(sc.get('frames', 600) - 1) / cfg.get('fps', 120):.3f}"] + # The run holds before it starts (RUNE_HEADLESS_WAIT) so `sample` is attached for launch. + env["RUNE_HEADLESS_WAIT"] = str(args.sample_hold) + p = subprocess.Popen(cmd, env=env, cwd=cwd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + dump = out / f"{name}.sample.txt" + subprocess.run(["/usr/bin/sample", str(p.pid), str(args.sample_secs), "1", "-mayDie", "-file", str(dump)], + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + p.wait() + print(f"{name}: sampled to {dump.name}", flush=True) + + +def q(values, p): + v = sorted(values) + return v[min(len(v) - 1, max(0, math.ceil(p * len(v)) - 1))] if v else None + + +def dist(values): + return {"n": len(values), "p50": q(values, .5), "p95": q(values, .95), "p99": q(values, .99), + "max": max(values, default=None), "over_budget": sum(v > BUDGET_MS for v in values), + "missed_refreshes": sum(max(0, math.ceil(v / BUDGET_MS) - 1) for v in values)} + + +def read_log(path): + frames, end, meta = [], None, None + for line in path.read_text().splitlines(): + v = json.loads(line) + if "k" in v: + frames.append(v) + elif v.get("end"): + end = v + elif "run" in v: + meta = v + return frames, end, meta + + +PHASES = ("view_cpu", "commit_cpu", "layout_cpu", "text_cpu", "paint_cpu", "apply_cpu", "update_ms", "encode_ms") + + +def window_stats(frames, fps, t0, t1): + inside = [f for f in frames if t0 * fps <= f["k"] < t1 * fps] + drawn = [f for f in inside if f["animating"] or f["commits"] or f["events"]] + cost = lambda f: f["cpu_ms"] if f.get("cpu_ms") is not None else f["ms"] + return { + "all": dist([cost(f) for f in inside]), + "drawn": dist([cost(f) for f in drawn]), + "wall_drawn": dist([f["ms"] for f in drawn]), + "phases_mean_ms": {p: statistics.fmean(f[p] for f in drawn) if drawn else None for p in PHASES}, + "allocations_mean": statistics.fmean(f["allocations"] for f in drawn) if drawn else None, + "commits_per_frame": statistics.fmean(f["commits"] for f in inside) if inside else None, + "commit_why": commit_why(inside), + "shaped_mean": statistics.fmean(f["shaped"] for f in drawn) if drawn else None, + "worst": sorted(({"k": f["k"], "t": round(f["k"] / fps, 3), "cpu_ms": cost(f), "shaped": f["shaped"], + "text_cpu": f["text_cpu"], "layout_cpu": f["layout_cpu"], "view_cpu": f["view_cpu"], + "encode_ms": f["encode_ms"], "allocations": f["allocations"]} for f in drawn), + key=lambda f: -f["cpu_ms"])[:5], + } + + +def commit_why(frames): + """Committing frames per reason (the frame log's `why`; "other" when it names none).""" + counts = {} + for f in frames: + if f["commits"]: + for why in f.get("why") or ["other"]: + counts[why] = counts.get(why, 0) + 1 + return counts + + +def median_of(rows, path): + vals = [] + for r in rows: + v = r + for key in path: + v = v.get(key) if isinstance(v, dict) else None + if v is not None: + vals.append(v) + return statistics.median(vals) if vals else None + + +def summary(args): + cfg = load_config(args.config) + out = Path(args.out) + fps = cfg.get("fps", 120) + report = {} + for name, sc in cfg["scenarios"].items(): + logs = sorted(out.glob(f"{name}-*.jsonl"), key=lambda p: int(p.stem.rsplit("-", 1)[1])) + if not logs: + continue + runs = [] + for path in logs: + frames, end, meta = read_log(path) + if not meta or meta.get("warmup"): + continue + windows = sc.get("windows") or {"all": [1 / fps, len(frames) / fps]} + runs.append({"windows": {w: window_stats(frames, fps, *span) for w, span in windows.items()}, + "memory": end, "launch": meta.get("launch"), "first_frame": frames[0] if frames else None, + "process_wall_s": meta.get("process_wall_s")}) + if not runs: + continue + entry = {"runs": len(runs), "windows": {}} + for w in runs[0]["windows"]: + ws = [r["windows"][w] for r in runs] + entry["windows"][w] = { + "drawn_cpu_ms": {k: median_of(ws, ["drawn", k]) for k in ("n", "p50", "p95", "p99", "max", "over_budget", "missed_refreshes")}, + "drawn_p50_range": [min(x["drawn"]["p50"] or 0 for x in ws), max(x["drawn"]["p50"] or 0 for x in ws)], + "drawn_max_range": [min(x["drawn"]["max"] or 0 for x in ws), max(x["drawn"]["max"] or 0 for x in ws)], + "all_cpu_ms": {k: median_of(ws, ["all", k]) for k in ("n", "p50", "p95", "p99", "max", "over_budget")}, + "phases_mean_ms": {p: median_of(ws, ["phases_mean_ms", p]) for p in PHASES}, + "allocations_mean": median_of(ws, ["allocations_mean"]), + "commits_per_frame": median_of(ws, ["commits_per_frame"]), + "commit_why": {k: statistics.median(x["commit_why"].get(k, 0) for x in ws) + for k in sorted({k for x in ws for k in x["commit_why"]})}, + "shaped_mean": median_of(ws, ["shaped_mean"]), + "worst_frames_by_run": [x["worst"][:3] for x in ws], + } + entry["memory_mb"] = {k: median_of(runs, ["memory", k]) / 1e6 for k in ("footprint", "footprint_peak", "resident", "heap_live") + if median_of(runs, ["memory", k]) is not None} + if any(r["launch"] for r in runs): + entry["launch_ms"] = {k: median_of(runs, ["launch", k]) for k in ("headless_ms", "state_ms", "runtime_ms", "gpu_init_ms", "frame_cpu_ms")} + entry["first_frame_cpu_ms"] = median_of(runs, ["first_frame", "cpu_ms"]) + entry["first_frame_phases"] = {p: median_of(runs, ["first_frame", p]) for p in PHASES} + report[name] = entry + text = json.dumps(report, indent=1) + if args.write: + Path(args.write).write_text(text + "\n") + print(table(report) if args.table else text) + + +def table(report): + """One line per scenario window: drawn-frame CPU quantiles, budget misses and the phase split.""" + f = lambda v: "-" if v is None else f"{v:.2f}" if isinstance(v, float) else str(v) + rows = ["scenario/window n p50 p95 p99 max >8.3ms view commit layout text paint update encode"] + for name, e in report.items(): + for w, x in e["windows"].items(): + d, ph = x["drawn_cpu_ms"], x["phases_mean_ms"] + rows.append(f"{name + '/' + w:<20} " + " ".join(f(d[k]) for k in ("n", "p50", "p95", "p99", "max", "over_budget")) + + " " + " ".join(f(ph[k]) for k in ("view_cpu", "commit_cpu", "layout_cpu", "text_cpu", "paint_cpu", "update_ms", "encode_ms"))) + if x.get("commit_why"): + rows.append(f"{'':<20} committing frames by reason: " + ", ".join(f"{k} {f(v)}" for k, v in x["commit_why"].items())) + if e.get("launch_ms"): + rows.append(f"{name}: launch " + json.dumps({k: round(v, 1) for k, v in e["launch_ms"].items() if v is not None}) + + " first frame " + f(e["first_frame_cpu_ms"]) + " memory MB " + json.dumps({k: round(v) for k, v in e["memory_mb"].items()})) + return "\n".join(rows) + + +# Buckets for self time, by the frame that owns it (generic std/alloc frames defer to their caller). +BUCKETS = [ + ("waiting (GPU, locks, sleep)", r"^(__semwait_signal|__psynch_cvwait|__psynch_mutexwait|mach_msg2_trap|mach_msg_trap|__workq_kernreturn|__ulock_wait|semaphore_wait_trap|nanosleep|kevent)"), + ("allocation", r"^(_?malloc|_?free|_?realloc|_?calloc|szone_|tiny_|small_|nanov2_|_nanov2|mvm_|_malloc|_free|__rust_(alloc|dealloc|realloc)|alloc::alloc::|procwatch::alloc|<procwatch::alloc|xzm_|_xzm|malloc_|free_)"), + ("motion", r"^(rune_motion::|<rune_motion::|rune::runtime::(motion|flights|transition|anim)|rune::motion|rune::anim)"), + ("taffy", r"^(taffy::|<taffy::)"), + # Walking laid-out glyphs, mostly from the paint walk's glyph emission rather than line breaking. + ("glyph iteration (parley)", r"^<parley::layout::(run::Glyphs|line::GlyphRunIter|line::GlyphRun)\b"), + ("text shaping (parley/harfrust/fontique)", r"^(parley::shape|<parley::shape|harfrust::|<harfrust::|harfruzz::|rustybuzz::|fontique::|<fontique::|skrifa::|<skrifa::|read_fonts::|<read_fonts::|swash::shape|parley::resolve|parley::builder|parley::context|parley::analysis|<parley::analysis|icu_|<icu_)"), + ("text breaking/layout (parley)", r"^(parley::|<parley::)"), + ("glyph raster/atlas", r"^(swash::|<swash::|zeno::|<zeno::|rune::text::(atlas|raster|glyph)|rune::glyph|etagere::|<etagere::|guillotiere::)"), + ("rune text", r"^(rune::text|<rune::text|rune_kit::markdown|<rune_kit::markdown|pulldown_cmark|<pulldown_cmark|rune_kit::(code|syntax|highlight)|syntect|tree_sitter)"), + ("flatten/diff/commit", r"^(rune::runtime::(flatten|commit|diff|reconcile|mount|keys|bands)|<rune::runtime::(flatten|commit)|rune::tree|rune::diff|rune::reconcile)"), + ("rune layout (non-taffy)", r"^(rune::(runtime::)?(layout|measure)|<rune::(runtime::)?layout)"), + ("rune render/encode", r"^(rune::(render|paint|renderer|batch|instances|gpu|scene|draw|shape|offscreen|record|surface)|<rune::(render|paint))"), + ("wgpu/naga", r"^(wgpu|<wgpu|naga|<naga|metal::|<metal::|objc2_metal)"), + ("driver/OS", r"^(objc_|_objc|-\[|\+\[|AGX|IOGPU|IOKit|IOConnect|mach_|__|_dispatch|dispatch_|CF|CA|MTL|_MTL|os_unfair|pthread_|_pthread|semaphore_|kevent|_platform_|swift_|AGXMetal|libsystem|dyld)"), + # `Runtime::build` is the per-frame draw-list walk (Phase::Paint), not the view. + ("rune paint walk", r"^(<rune::runtime::Runtime<.*>>::(build|glyphs_into|draw_text)\b|rune::runtime::paint)"), + ("rune view/build", r"^(rune::|<rune::|rune_kit::|<rune_kit::|rune_theme|rune_fx|<rune_fx)"), + ("hashing/containers (std)", r"^(hashbrown|<hashbrown|core::hash|<core::hash|std::collections|<std::collections|alloc::collections|<alloc::collections|rustc_hash|<rustc_hash|ahash|<ahash)"), +] +GENERIC = re.compile(r"^(<?(core|alloc|std|hashbrown|smallvec|<smallvec|rustc_hash|ahash)::|_platform_mem|DYLD-STUB|<&|<\[|<\(|<\*)") + + +def demangle(sym): + s = sym + for a, b in (("$LT$", "<"), ("$GT$", ">"), ("$u20$", " "), ("$RF$", "&"), ("$BP$", "*"), ("$C$", ","), + ("$u7b$", "{"), ("$u7d$", "}"), ("$u5b$", "["), ("$u5d$", "]"), ("$u27$", "'"), ("$u3b$", ";"), + ("$u22$", '"'), ("$LP$", "("), ("$RP$", ")"), ("$u2b$", "+"), ("$SP$", "@")): + s = s.replace(a, b) + s = s.replace("..", "::") + s = re.sub(r"::h[0-9a-f]{16}$", "", s) + return re.sub(r"^_(?=<)", "", s) + + +LINE = re.compile(r"^(?P<lead>[ +!:|]*)(?P<count>\d+) (?P<sym>.+?) \(in (?P<lib>[^)]+)\)(?: \+ [\d,.]+)?" + r"(?: \[(?P<addr>0x[0-9a-f]+)\](?:\s+(?P<src>\S+:\d+))?)?") + + +def demangle_all(syms): + """Rust v0 and legacy symbols through rustfilt when it's installed, else the legacy rules.""" + syms = sorted(set(syms)) + if shutil.which("rustfilt"): + p = subprocess.run(["rustfilt"], input="\n".join(syms), capture_output=True, text=True) + out = p.stdout.splitlines() + if p.returncode == 0 and len(out) == len(syms): + return {a: re.sub(r"^_(?=<)", "", b) for a, b in zip(syms, out)} + return {a: demangle(a) for a in syms} + + +def parse_threads(path): + """{thread title: [(depth, count, sym, lib, addr)]} from a `sample` call graph.""" + threads, cur, in_graph = {}, None, False + for line in Path(path).read_text().splitlines(): + if line.startswith("Call graph:"): + in_graph = True + continue + if in_graph and (line.startswith("Total number in stack") or line.startswith("Sort by top of stack")): + break + if not in_graph or not line.strip(): + continue + m = re.match(r"^ {4}(\d+) (Thread_\d+.*)$", line) + if m: + cur = m.group(2).strip() + threads[cur] = [] + continue + m = LINE.match(line[4:]) if cur else None + if m: + depth = len(m.group("lead")) // 2 + threads[cur].append((depth, int(m.group("count")), m.group("sym").strip(), m.group("lib"), m.group("addr"), m.group("src"))) + names = demangle_all(r[2] for rows in threads.values() for r in rows) + return {t: [(d, c, names[sym], lib, addr, src) for d, c, sym, lib, addr, src in rows] for t, rows in threads.items()} + + +def bucket_of(sym, lib, app_libs): + for name, rx in BUCKETS: + if re.search(rx, sym): + return name + if lib in app_libs or re.match(r"^<?[a-z_0-9]+::", sym): + return "app code" + return "driver/OS" if lib not in app_libs else "other" + + +def self_times(rows): + """(self count, symbol, owner symbol, lib, addr, source line) for each node of one thread's tree, + leaving out the sampled run's RUNE_HEADLESS_WAIT hold.""" + children = [0] * len(rows) + parents, stack = [None] * len(rows), [] + for i, (depth, count, *_rest) in enumerate(rows): + while stack and rows[stack[-1]][0] >= depth: + stack.pop() + if stack: + parents[i] = stack[-1] + children[stack[-1]] += count + stack.append(i) + out = [] + for i, (depth, count, sym, lib, addr, src) in enumerate(rows): + own = count - children[i] + if own <= 0: + continue + path, j = [], i + while j is not None: + path.append(j) + j = parents[j] + if any(rows[j][2].startswith("std::thread::") and "sleep" in rows[j][2] for j in path): + continue + # The hold's sleep is inlined into headless_configured in optimized builds. + if any(rows[j][2] == "nanosleep" and parents[j] is not None and "headless_configured" in rows[parents[j]][2] for j in path): + continue + owner = next((rows[j] for j in path if not GENERIC.match(rows[j][2]) or re.match(BUCKETS[0][1], rows[j][2])), rows[i]) + out.append((own, sym, owner[2], owner[3], addr, owner[5] or src)) + return out + + +def atos(binary, load, addrs): + if not addrs: + return {} + p = subprocess.run(["atos", "-i", "-o", binary, "-l", load, *addrs], capture_output=True, text=True) + lines, out, k = p.stdout.splitlines(), {}, 0 + # One block per address, inlined frames first, separated by blank lines. + blocks, cur = [], [] + for line in lines: + if not line.strip(): + if cur: + blocks.append(cur) + cur = [] + else: + cur.append(line) + if cur: + blocks.append(cur) + for addr, block in zip(addrs, blocks): + out[addr] = block + return out + + +def profile(args): + text = Path(args.dump).read_text() + threads = parse_threads(args.dump) + if not any(threads.values()): + sys.exit(f"{args.dump}: no samples (the process exited before sample attached)") + main = next((t for t in threads if "main-thread" in t), None) or max(threads, key=lambda t: sum(c for d, c, *_ in threads[t] if d == 0)) + rows = threads[main] + exe = re.search(r"^Path:\s+(.+)$", text, re.M) + app_libs = {Path(exe.group(1)).name} if exe else set() + nodes = self_times(rows) + total = sum(n[0] for n in nodes) + buckets, funcs = {}, {} + for count, sym, owner, lib, addr, src in nodes: + b = bucket_of(sym, lib, app_libs) + if b in ("other", "driver/OS") or GENERIC.match(sym): + ob = bucket_of(owner, lib, app_libs) + b = b if b == "allocation" or (b == "driver/OS" and ob == "app code") else ob + buckets[b] = buckets.get(b, 0) + count + f = funcs.setdefault(owner, {"samples": 0, "bucket": b, "addrs": {}, "leaf": {}, "src": {}}) + f["samples"] += count + if src: + f["src"][src] = f["src"].get(src, 0) + count + if addr: + f["addrs"][addr] = f["addrs"].get(addr, 0) + count + f["leaf"][sym] = f["leaf"].get(sym, 0) + count + if args.exclude: + rx = re.compile(args.exclude) + idle = sum(c for c, s, *_ in nodes if rx.search(s)) + else: + idle = 0 + top = sorted(funcs.items(), key=lambda kv: -kv[1]["samples"])[:args.top] + lines = {} + if args.binary: + load = re.search(r"^Load Address:\s+(0x[0-9a-f]+)", text, re.M) + addrs = [max(f["addrs"], key=f["addrs"].get) for _, f in top if f["addrs"]] + lines = atos(args.binary, load.group(1), addrs) if load else {} + report = { + "thread": main, "samples": total, "ms_per_sample": 1, + "buckets": {b: {"samples": c, "pct": round(100 * c / total, 1)} for b, c in sorted(buckets.items(), key=lambda kv: -kv[1])}, + "top": [{"fn": fn, "samples": f["samples"], "pct": round(100 * f["samples"] / total, 1), "bucket": f["bucket"], + "leaves": sorted(f["leaf"].items(), key=lambda kv: -kv[1])[:3], + "lines": sorted(f["src"].items(), key=lambda kv: -kv[1])[:3], + "at": lines.get(max(f["addrs"], key=f["addrs"].get)) if f["addrs"] else None} for fn, f in top], + } + text = json.dumps(report, indent=1) + if args.write: + Path(args.write).write_text(text + "\n") + print(text) + + +def main(): + p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + sub = p.add_subparsers(dest="cmd", required=True) + r = sub.add_parser("run") + r.add_argument("config") + r.add_argument("--out", required=True) + r.add_argument("--runs", type=int, default=5, help="measured runs, after one warmup") + r.add_argument("--only", help="comma-separated scenarios") + r.add_argument("--sample", action="store_true") + r.add_argument("--sample-secs", type=int, default=120) + r.add_argument("--sample-hold", type=float, default=1.5, help="seconds the sampled run waits before starting") + r.add_argument("--timeout", type=int, default=600) + s = sub.add_parser("summary") + s.add_argument("config") + s.add_argument("--out", required=True) + s.add_argument("--write") + s.add_argument("--table", action="store_true", help="print a one-line-per-window table instead of JSON") + f = sub.add_parser("profile") + f.add_argument("dump") + f.add_argument("--binary") + f.add_argument("--top", type=int, default=25) + f.add_argument("--exclude") + f.add_argument("--write") + a = p.parse_args() + {"run": run, "summary": summary, "profile": profile}[a.cmd](a) + + +if __name__ == "__main__": + main() diff --git a/app/vendor/rune/scripts/rune-dev b/app/vendor/rune/scripts/rune-dev new file mode 100644 index 0000000..dee2b28 --- /dev/null +++ b/app/vendor/rune/scripts/rune-dev @@ -0,0 +1,998 @@ +#!/usr/bin/env python3 +"""Guarded Rune hot editing. The compiler and app always run in the same build lease. + +On the desk Mac this relays source edits to the build Mac; on a worker it watches a validated mirror. +Only view function bodies can patch. All other build inputs require a restart. + + rune-dev settings [-- APP ARGS] + rune-dev --manifest-path APP/Cargo.toml --patch 'src/ui/*.rs' [--bin B] [--features F] [-- APP ARGS] + +--desk compiles on the build Mac but runs the app on this Mac, patching it over an SSH tunnel. +--local (or RUNE_DEV_LOCAL=1) compiles and runs the app on this machine, with no build Mac, and +rebuilds and relaunches it after an edit that needs a restart. RUNE_DEV_WRAP runs that under a +command prefix (a build-queue lease, say); by default it's plain cargo. +""" +import argparse +from dataclasses import dataclass +import hashlib +import json +import os +from pathlib import Path, PurePosixPath +import platform +import posixpath +import re +import select +import shlex +import shutil +import signal +import socket +import subprocess +import sys +import tempfile +import threading +import time +import tomllib +from urllib.parse import parse_qs, urlsplit + +ROOT = Path(__file__).resolve().parents[1] +EXAMPLES = {"settings": {"examples/settings/src/main.rs"}} +# Matches the workspace's [profile.rune-hot], for apps that don't define their own. +PROFILE = ['profile.rune-hot.inherits="dev"', "profile.rune-hot.debug=0", "profile.rune-hot.incremental=true", + "profile.rune-hot.package.png.opt-level=3", "profile.rune-hot.package.fdeflate.opt-level=3"] +SKIP_DIRS = ("target", ".git", "__pycache__", "node_modules") + + +@dataclass +class External: + """An app crate outside Rune. Its files are `external/<path from base>` keys.""" + base: Path + crate: str + dirs: list + tops: list + + +# Set when this process reads an external crate's original files; a build Mac's staging +# area already holds them at their keys. +EXTERNAL = None + + +def git_or_walk(directory, roots=("",)): + try: + out = subprocess.run(["git", "ls-files", "--cached", "--others", "--exclude-standard", "-z", "--", *[r or "." for r in roots]], + cwd=directory, capture_output=True, check=True).stdout.decode() + return [p for p in out.split("\0") if p] + except (subprocess.CalledProcessError, FileNotFoundError, NotADirectoryError): + result = [] + for root in roots: + for parent, dirs, names in os.walk(directory / root): + dirs[:] = [d for d in dirs if d not in SKIP_DIRS] + result.extend(str((Path(parent) / n).relative_to(directory)) for n in names) + return result + + +def files(): + manifest = ROOT / ".rune-dev-files.json" + if manifest.exists(): + return json.loads(manifest.read_text()) + if EXTERNAL: + tooling = [p for p in git_or_walk(ROOT, ("tools/rune-dev-guard",)) if not p.startswith("tools/rune-dev-guard/target/")] + keys = set(tooling) | {"scripts/rune-dev"} | {"external/" + p for p in EXTERNAL.tops} + for d in EXTERNAL.dirs: + keys.update(str(PurePosixPath("external", d, p)) for p in git_or_walk(EXTERNAL.base / d)) + return sorted(keys) + if not (ROOT / ".git").exists(): + # The build queue syncs source without Git metadata. + result = [] + for directory in ("crates", "examples", "themes", "tools", "scripts", ".cargo"): + for parent, dirs, names in os.walk(ROOT / directory): + dirs[:] = [d for d in dirs if d not in SKIP_DIRS] + result.extend(str((Path(parent) / n).relative_to(ROOT)) for n in names) + result.extend(p for p in ("Cargo.toml", "Cargo.lock", "rust-toolchain.toml") if (ROOT / p).exists()) + return result + return subprocess.check_output(["git", "ls-files", "--cached", "--others", "--exclude-standard", "-z"], cwd=ROOT).decode().strip("\0").split("\0") + + +def source(p): + """The file behind a key on this machine.""" + if EXTERNAL and (p == "external" or p.startswith("external/")): + return EXTERNAL.base / p.removeprefix("external").lstrip("/") + return ROOT / p + + +def tracked(p): + if not p or Path(p).name.startswith(".env") or Path(p).suffix in (".pem", ".key"): + return False + return p.startswith(("crates/", "examples/", "themes/", "external/")) or p in ("Cargo.toml", "Cargo.lock", "rust-toolchain.toml", ".cargo/config.toml") + + +def inputs(cache): + def stamp(path): + s = path.stat() + # ctime/inode also catch same-size saves with restored mtimes and atomic replacements. + return s.st_size, s.st_mtime_ns, s.st_ctime_ns, s.st_dev, s.st_ino + + current = {} + for p in files(): + if not tracked(p): + continue + path = source(p) + try: + before = stamp(path) + except (FileNotFoundError, NotADirectoryError): + continue + old = cache.get(p) + if old is not None and old[0] == before: + current[p] = old + else: + data = path.read_bytes() + if stamp(path) != before: + raise OSError(f"input changed while reading: {p}") + current[p] = before, data + # Publish the cache only after a complete scan, including deletions. + cache.clear() + cache.update(current) + return {p: data for p, (_, data) in current.items()} + + +def transfer_files(source): + return sorted(set(source) | {p for p in files() if p.startswith("tools/rune-dev-guard/")} | {"scripts/rune-dev"}) + + +def watch(on_change, process, previous, cache, on_tick=None): + while process.poll() is None: + select.select([], [], [], .1) + if on_tick: + on_tick() + try: + current = inputs(cache) + except (OSError, json.JSONDecodeError): + continue # An editor or source relay is replacing a file. + if current != previous: + on_change(current) + previous = current + + +def stop(process): + if process.poll() is None: + os.killpg(process.pid, signal.SIGTERM) + try: + process.wait(timeout=15) + except subprocess.TimeoutExpired: + os.killpg(process.pid, signal.SIGKILL) + process.wait() + + +# --- Arguments -------------------------------------------------------------------------------- + +def parse(argv): + parser = argparse.ArgumentParser(prog="rune-dev", description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + parser.add_argument("example", nargs="?", choices=sorted(EXAMPLES)) + parser.add_argument("--manifest-path", type=Path, help="an external app crate's Cargo.toml") + parser.add_argument("--package", help="default: the manifest's package") + parser.add_argument("--bin") + parser.add_argument("--features", default="", help="besides hot") + parser.add_argument("--patch", action="append", default=[], metavar="GLOB", + help="files, relative to the app crate, whose fn bodies patch live (repeatable; ** spans directories)") + parser.add_argument("--port", type=int, default=18744) + parser.add_argument("--desk", action="store_true", help="run the app on this Mac and compile on --build-host") + parser.add_argument("--local", action="store_true", default=bool(os.environ.get("RUNE_DEV_LOCAL")), + help="compile and run here; a restart-needed edit rebuilds and relaunches (env RUNE_DEV_LOCAL)") + parser.add_argument("--build-host", default=os.environ.get("RUNE_DEV_BUILD_HOST", "pro"), help="SSH host (env RUNE_DEV_BUILD_HOST)") + split = argv.index("--") if "--" in argv else len(argv) + opts, unknown = parser.parse_known_args(argv[:split]) + # Before `--`, unrecognised arguments go to the app too, as they always have. + opts.app_args = unknown + argv[split + 1:] + if (opts.example is None) == (opts.manifest_path is None): + parser.error("name an example or pass --manifest-path") + if opts.manifest_path and not opts.patch: + parser.error("--manifest-path needs at least one --patch GLOB; every other file restarts") + if opts.example and (opts.patch or opts.package or opts.bin or opts.features): + parser.error("--patch, --package, --bin and --features are for --manifest-path") + if opts.local and opts.desk: + parser.error("--local runs everything here; --desk compiles on --build-host") + opts.parser = parser + return opts + + +def worker(host): + return os.environ.get("RUNE_DEV_WORKER", host) + + +# --- External crates -------------------------------------------------------------------------- + +def read_toml(path): + return tomllib.loads(Path(path).read_text()) + + +def path_dependencies(doc, directory): + """Directories of `path` dependencies in any dependency table, `[patch]` or `[replace]`.""" + found = [] + def walk(node, inside): + if isinstance(node, dict): + if inside and isinstance(node.get("path"), str): + found.append((directory / node["path"]).resolve()) + for key, value in node.items(): + walk(value, inside or key.endswith("dependencies") or key in ("patch", "replace")) + walk(doc, False) + return found + + +def workspace_root(package, stop=None): + doc = read_toml(package / "Cargo.toml") + explicit = doc.get("package", {}).get("workspace") + if isinstance(explicit, str): + return (package / explicit).resolve() + directory = package + while True: + manifest = directory / "Cargo.toml" + if manifest.exists() and "workspace" in read_toml(manifest): + return directory + if directory.parent == directory or directory == stop: + return None + directory = directory.parent + + +def external_layout(manifest): + """The app crate, every path dependency and their workspaces' manifests and lockfiles.""" + crate = manifest.resolve().parent + packages, roots = [], [] + pending = [crate] + while pending: + package = pending.pop() + if package in packages: + continue + if not (package / "Cargo.toml").exists(): + raise SystemExit(f"rune-dev: path dependency {package} has no Cargo.toml") + packages.append(package) + pending.extend(path_dependencies(read_toml(package / "Cargo.toml"), package)) + root = workspace_root(package) + if root and root not in roots: + roots.append(root) + pending.extend(path_dependencies(read_toml(root / "Cargo.toml"), root)) + base = Path(os.path.commonpath([*packages, *roots])) + rel = lambda p: str(PurePosixPath(p.relative_to(base).as_posix())) + tops = [rel(r / name) for r in roots for name in ("Cargo.toml", "Cargo.lock", "rust-toolchain", "rust-toolchain.toml", ".cargo/config.toml", ".cargo/config") + if (r / name).is_file()] + return External(base=base, crate=str(PurePosixPath("external", rel(crate))), dirs=sorted({rel(p) for p in packages}), tops=tops) + + +def workspace_key(crate, data): + """The key of the app crate's workspace manifest among staged inputs, or None.""" + doc = tomllib.loads(data[crate + "/Cargo.toml"].decode()) + explicit = doc.get("package", {}).get("workspace") + if isinstance(explicit, str): + key = posixpath.normpath(posixpath.join(crate, explicit, "Cargo.toml")) + return key if key in data else None + directory = PurePosixPath(crate) + while True: + key = str(directory / "Cargo.toml") + if key in data and "workspace" in tomllib.loads(data[key].decode()): + return key + if str(directory) == "external": + return None + directory = directory.parent + + +def array_end(text, i): + """The index after the TOML array whose `[` is at `i`.""" + depth = 0 + while i < len(text): + c = text[i] + if c == "#": + i = text.find("\n", i) + if i < 0: break + elif c in "\"'": + i += 1 + while i < len(text) and text[i] != c: + i += 2 if c == '"' and text[i] == "\\" else 1 + elif c == "[": + depth += 1 + elif c == "]": + depth -= 1 + if depth == 0: return i + 1 + i += 1 + raise ValueError("unterminated TOML array") + + +def staged_workspace(text, staged): + """The app's workspace manifest with `members` and `default-members` cut to the staged + package directories (relative to it). Cargo loads every member, and the build Mac has + only the app and its path dependencies.""" + workspace = tomllib.loads(text).get("workspace", {}) + norm = lambda m: str(PurePosixPath(m)) + excluded = {norm(m) for m in workspace.get("exclude", [])} + for key in ("default-members", "members"): + header = re.search(r"(?m)^[ \t]*\[workspace\][ \t]*(#.*)?$", text) + if key not in workspace or not header: + continue + end = re.compile(r"(?m)^[ \t]*\[").search(text, header.end()) + found = re.compile(rf"(?m)^[ \t]*{re.escape(key)}[ \t]*=[ \t]*(?=\[)").search(text, header.end(), end.start() if end else len(text)) + if not found: + continue + kept = sorted(d for d in staged if d not in excluded and any(PurePosixPath(d).full_match(norm(g)) for g in workspace[key])) + stop = array_end(text, found.end()) + text = text[:found.end()] + json.dumps(kept) + text[stop:] + return text + + +def mirror_overrides(crate, data): + """Mirror bytes that differ from the source: the app's workspace members.""" + key = crate and workspace_key(crate, data) + if not key: + return {} + root = PurePosixPath(key).parent + staged = [] + for k in data: + path = PurePosixPath(k) + if path.name == "Cargo.toml" and k != key and path.is_relative_to(root) and "package" in tomllib.loads(data[k].decode()): + staged.append(str(path.parent.relative_to(root))) + return {key: staged_workspace(data[key].decode(), staged).encode()} + + +def patchable(crate, globs): + """Keys of the app crate's Rust files that `--patch` names. Everything else restarts.""" + prefix = crate.rstrip("/") + "/" + def allowed(key): + if not key.startswith(prefix) or not key.endswith(".rs"): + return False + path = PurePosixPath(key.removeprefix(prefix)) + return any(path.full_match(glob) for glob in globs) + return allowed + + +def crate_settings(crate_dir, stop): + """(package name, whether a [profile.rune-hot] is defined) for an app crate on this machine.""" + doc = read_toml(crate_dir / "Cargo.toml") + if "hot" not in doc.get("features", {}): + raise SystemExit(f'rune-dev: add `hot = ["rune/hot"]` to [features] in {crate_dir / "Cargo.toml"}') + root = workspace_root(crate_dir, stop) or crate_dir + profiles = read_toml(root / "Cargo.toml").get("profile", {}) + return doc.get("package", {}).get("name"), "rune-hot" in profiles + + +def package_spec(crate_dir, stop): + """`name@version` for an app crate, or just its name when the manifest has no version.""" + package = read_toml(crate_dir / "Cargo.toml").get("package", {}) + version = package.get("version") + if isinstance(version, dict) and version.get("workspace"): + root = workspace_root(crate_dir, stop) or crate_dir + version = read_toml(root / "Cargo.toml").get("workspace", {}).get("package", {}).get("version") + return f"{package['name']}@{version}" if isinstance(version, str) else package.get("name") + + +CARGO_SHIM = """#!/usr/bin/env python3 +# dx builds with `cargo build -p NAME`, which Cargo rejects as ambiguous when a dependency +# shares the app's name; this names the app's version too. +import os, sys +real, name, spec = {real!r}, {name!r}, {spec!r} +args = sys.argv[1:] +for i, arg in enumerate(args): + if arg == name and i and args[i - 1] in ("-p", "--package"): + args[i] = spec + elif arg in ("-p" + name, "--package=" + name): + args[i] = arg[:-len(name)] + spec +os.execv(real, [real, *args]) +""" + + +def cargo_shim(directory, name, spec, path): + """A PATH whose `cargo` passes dx's `-p NAME` on as `-p NAME@VERSION`.""" + real = shutil.which("cargo", path=path) + if not real or spec == name: + return path + directory.mkdir(parents=True, exist_ok=True) + shim = directory / "cargo" + shim.write_text(CARGO_SHIM.format(real=real, name=name, spec=spec)) + shim.chmod(0o755) + return f"{directory}{os.pathsep}{path}" + + +def dx_command(dx, port, package, features, bin, cargo_config, app_args): + command = [str(dx), "serve", "--hot-patch", "--platform", "server", "--open", "false", "--interactive", "false", + "--addr", "127.0.0.1", "--port", str(port), "--package", package, "--features", ",".join(["hot", *filter(None, features.split(","))]), "--profile", "rune-hot"] + if bin: + command += ["--bin", bin] + if cargo_config: + command.append("--cargo-args=" + shlex.join(a for c in cargo_config for a in ("--config", c))) + if app_args: + # dx splits these on whitespace. + command.append("--args=" + " ".join(app_args)) + return command + + +# --- Remote build host ------------------------------------------------------------------------ + +def ssh_options(): + # One connection for every rsync, fetch and the tunnel. + return ["-o", "ControlMaster=auto", "-o", f"ControlPath=/tmp/rune-dev-{os.getuid()}-%C", "-o", "ControlPersist=60"] + + +def ssh(*args): + return ["ssh", *ssh_options(), *args] + + +def sha256(path): + digest = hashlib.sha256() + with open(path, "rb") as f: + for chunk in iter(lambda: f.read(1 << 20), b""): + digest.update(chunk) + return digest.hexdigest() + + +def platform_info(): + return {"system": platform.system(), "machine": platform.machine()} + + +def remote_argv(opts, desk): + """The build Mac's arguments: an external crate is named by its staging path.""" + argv = [opts.example] if opts.example else ["--manifest-path", EXTERNAL.crate + "/Cargo.toml"] + for flag in ("package", "bin"): + if getattr(opts, flag): + argv += ["--" + flag, getattr(opts, flag)] + if opts.features: + argv += ["--features", opts.features] + for glob in opts.patch: + argv += ["--patch", glob] + argv += ["--port", str(opts.port)] + if desk: + # The build Mac's copy only parks; the app's arguments are for the desk copy. + return argv + ["--desk"] + return argv + ["--", *opts.app_args] + + +def app_argv(opts, root): + """Arguments for the app process, with Rune's file flags resolved against `root`.""" + app_args = list(opts.app_args) + for flag in ("--snap-on-patch", "--hot-control", "--fixture"): + if flag in app_args: + i = app_args.index(flag) + 1 + if i == len(app_args): opts.parser.error(flag + " needs a path") + app_args[i] = str((root / app_args[i]).resolve()) + return (["--hot"] if opts.example else []) + app_args + + +def check_base(info, local): + if (info.get("system"), info.get("machine")) != (local["system"], local["machine"]): + return f"rune-dev: the build Mac built for {info.get('system')} {info.get('machine')}; this Mac is {local['system']} {local['machine']}" + return None + + +class Desk: + """The desk copy of the app: the build Mac's binary, byte for byte, and the patches built for it.""" + + def __init__(self, host, cache, argv, cwd, env, ready=lambda: None): + self.host, self.cache, self.argv, self.cwd, self.env = host, cache, argv, cwd, env + # Raises unless the app's devserver path works; the app connects once, at startup. + self.ready = ready + self.lock = threading.Lock() + self.app = None + self.remote_exe = None + self.sha = None + self.restarting = False + self.failed = None + + def base(self, info): + failure = check_base(info, platform_info()) + if failure: + self.failed = failure + print(failure, file=sys.stderr, flush=True) + return + with self.lock: + if info["sha256"] == self.sha and self.app and self.app.poll() is None: + return + exe = self.cache / info["sha256"][:16] / Path(info["exe"]).name + if not exe.exists() or sha256(exe) != info["sha256"]: + exe.parent.mkdir(parents=True, exist_ok=True) + temp = exe.with_suffix(".fetch") + subprocess.run(["scp", *ssh_options(), "-q", f"{self.host}:{info['exe']}", str(temp)], check=True) + if sha256(temp) != info["sha256"]: + temp.unlink() + self.failed = "rune-dev: the copied app binary does not match the build Mac's" + print(self.failed, file=sys.stderr, flush=True) + return + temp.chmod(0o755) + temp.replace(exe) + self.ready() + self.restarting = True + if self.app: + print("rune-dev: the build Mac rebuilt the app; restarting it here", flush=True) + stop(self.app) + self.remote_exe, self.sha = info["exe"], info["sha256"] + self.app = subprocess.Popen([str(exe), *self.argv], cwd=self.cwd, env=self.env, start_new_session=True) + self.restarting = False + print(f"rune-dev: running {exe.name} here (sha256 {self.sha[:12]}), pid {self.app.pid}", flush=True) + + def fetch_patch(self, lib): + """Copies a patch dylib, after checking the build Mac still has the binary this one runs.""" + with self.lock: + remote_exe, sha = self.remote_exe, self.sha + script = f"shasum -a 256 {shlex.quote(remote_exe)} | cut -c1-64 && cat {shlex.quote(lib)}" + out = subprocess.run(ssh(self.host, script), capture_output=True) + head, _, data = out.stdout.partition(b"\n") + if out.returncode or not data: + raise RuntimeError(f"rune-dev: could not fetch patch {lib}: {out.stderr.decode().strip()}") + built = head.decode().strip() + if built != sha: + raise RuntimeError(f"rune-dev: patch built against base {built[:12]}, but this Mac runs {sha[:12]}; not applying it") + dest = self.cache / sha[:16] / "patches" / PurePosixPath(lib).name + dest.parent.mkdir(parents=True, exist_ok=True) + temp = dest.with_suffix(".fetch") + temp.write_bytes(data) + temp.replace(dest) + return dest + + def exited(self): + with self.lock: + return self.app is not None and not self.restarting and self.app.poll() is not None + + +BASE = "rune-dev-base " + + +def base_message(line): + """The build Mac's base report in a line of its output; `ssh -tt` can prefix PTY bytes.""" + at = line.find(BASE) + return None if at < 0 else json.loads(line[at + len(BASE):]) + + +def tunnel_failure(tunnel): + if tunnel.poll() is not None: + return f"rune-dev: the SSH tunnel to dx exited ({tunnel.returncode}); edits can't reach the app. Rerun rune-dev." + return None + + +def answers(port): + """Whether something answers HTTP through a forwarded port. ssh accepts a forwarded + connection before its remote end exists, and closes it silently when that fails.""" + try: + with socket.create_connection(("127.0.0.1", port), timeout=2) as s: + s.sendall(b"GET / HTTP/1.0\r\nHost: 127.0.0.1\r\n\r\n") + return bool(s.recv(1)) + except OSError: + return False + + +def wait_forward(port, tunnel, timeout=60.0, interval=.25): + deadline = time.monotonic() + timeout + while not answers(port): + failure = tunnel_failure(tunnel) + if failure: + raise RuntimeError(failure) + if time.monotonic() > deadline: + raise RuntimeError(f"rune-dev: dx did not answer through the SSH tunnel within {timeout:.0f} s") + time.sleep(interval) + + +def rewrite_patch(text, pid, fetch): + """A devserver message with this process's patch dylib replaced by a local copy.""" + try: + msg = json.loads(text) + except ValueError: + return text + reload = msg.get("HotReload") if isinstance(msg, dict) else None + table = reload and reload.get("jump_table") + if not table or reload.get("for_pid") != pid: + return text + table["lib"] = str(fetch(table["lib"])) + return json.dumps(msg) + + +def read_exact(stream, n): + data = stream.read(n) + if len(data) != n: + raise EOFError + return data + + +def read_frame(stream): + b0, b1 = read_exact(stream, 2) + n = b1 & 0x7f + if n == 126: n = int.from_bytes(read_exact(stream, 2)) + elif n == 127: n = int.from_bytes(read_exact(stream, 8)) + mask = read_exact(stream, 4) if b1 & 0x80 else None + payload = read_exact(stream, n) + if mask: + payload = bytes(b ^ mask[i % 4] for i, b in enumerate(payload)) + return bool(b0 & 0x80), b0 & 0x0f, payload + + +def frame(opcode, payload, fin=True): + """An unmasked server-to-client frame.""" + n = len(payload) + head = bytes([(0x80 if fin else 0) | opcode]) + if n < 126: head += bytes([n]) + elif n < 1 << 16: head += bytes([126]) + n.to_bytes(2) + else: head += bytes([127]) + n.to_bytes(8) + return head + payload + + +class Prefixed: + def __init__(self, prefix, stream): + self.prefix, self.stream = prefix, stream + + def read(self, n): + head, self.prefix = self.prefix[:n], self.prefix[n:] + return head + self.stream.read(n - len(head)) if len(head) < n else head + + +def read_head(sock): + data = b"" + while b"\r\n\r\n" not in data: + chunk = sock.recv(4096) + if not chunk: + raise EOFError + data += chunk + head, _, rest = data.partition(b"\r\n\r\n") + return head + b"\r\n\r\n", rest + + +class PatchRelay: + """The desk app's devserver: forwards the websocket to dx through the tunnel, and swaps each + patch dylib path on the build Mac for a copy on this one before the app loads it.""" + + def __init__(self, upstream, fetch, attempts=40, interval=.25): + self.upstream, self.fetch = upstream, fetch + self.attempts, self.interval = attempts, interval + self.server = socket.create_server(("127.0.0.1", 0)) + self.port = self.server.getsockname()[1] + threading.Thread(target=self.accept, daemon=True).start() + + def accept(self): + while True: + try: + client, _ = self.server.accept() + except OSError: + return + threading.Thread(target=self.connection, args=(client,), daemon=True).start() + + def connection(self, client): + pid = None + try: + head, rest = read_head(client) + target = head.split(b"\r\n", 1)[0].split()[1].decode() + pid = int(parse_qs(urlsplit(target).query).get("pid", ["0"])[0]) + # The frame reader below handles plain frames only. + lines = [l for l in head.split(b"\r\n") if not l.lower().startswith(b"sec-websocket-extensions:")] + upstream, response, body = self.handshake(b"\r\n".join(lines) + rest) + if b" 101 " not in response.split(b"\r\n", 1)[0] + b" ": + client.sendall(response + body) + return + client.sendall(response) + print(f"rune-dev: app pid {pid} connected to the devserver", flush=True) + threading.Thread(target=self.pipe, args=(client, upstream), daemon=True).start() + # Frames that arrived with the handshake are parsed like the rest. + self.patches(Prefixed(body, upstream.makefile("rb")), client, pid) + except EOFError: + if pid is not None: + print(f"rune-dev: app pid {pid} left the devserver", flush=True) + except (OSError, ValueError, IndexError) as error: + print(f"rune-dev: the devserver relay failed for app pid {pid}: {error}; edits will not reach it", file=sys.stderr, flush=True) + finally: + client.close() + + def handshake(self, request): + """The upgrade through the tunnel, retried while its remote end isn't there yet: ssh + accepts the connection and then closes it.""" + failure = None + for _ in range(self.attempts): + upstream = None + try: + upstream = socket.create_connection(self.upstream, timeout=5) + upstream.sendall(request) + response, body = read_head(upstream) + upstream.settimeout(None) + return upstream, response, body + except (OSError, EOFError) as error: + failure = str(error) or "connection closed" + if upstream: upstream.close() + time.sleep(self.interval) + raise OSError(f"dx did not answer through the SSH tunnel ({failure})") + + @staticmethod + def pipe(source, dest): + try: + while chunk := source.recv(65536): + dest.sendall(chunk) + except OSError: + pass + finally: + for s in (source, dest): + try: s.shutdown(socket.SHUT_RDWR) + except OSError: pass + + def patches(self, stream, client, pid): + parts, binary = [], False + while True: + fin, op, payload = read_frame(stream) + if op >= 8 or op == 2 or (op == 0 and binary): + # Control and binary frames pass through as they came. + if op < 8: binary = not fin + client.sendall(frame(op, payload, fin)) + continue + if op == 1: + parts = [] + parts.append(payload) + if not fin: + continue + text = b"".join(parts).decode() + try: + text = rewrite_patch(text, pid, self.fetch) + except (RuntimeError, OSError) as error: + print(error, file=sys.stderr, flush=True) + continue + client.sendall(frame(1, text.encode())) + + def close(self): + self.server.close() + + +def free_port(): + with socket.socket() as s: + s.bind(("127.0.0.1", 0)) + return s.getsockname()[1] + + +def relay(argv): + """The desk Mac watches original files. The build Mac's guard sees a source staging area, never dx's mirror.""" + global EXTERNAL + opts = parse(argv) + host = opts.build_host + if opts.manifest_path: + EXTERNAL = external_layout(opts.manifest_path) + key = str(ROOT) if not EXTERNAL else f"{ROOT}\0{EXTERNAL.base}\0{EXTERNAL.crate}" + tag = hashlib.sha256(key.encode()).hexdigest()[:12] + remote = os.environ.get("RUNE_DEV_REMOTE", f"scratch/rune-dev-{tag}") + # The build queue's local admission requires a Git root. This is an empty staging + # repository, not a copy of the user's history; the manifest supplies its inputs. + subprocess.run(ssh(host, f"mkdir -p {shlex.quote(remote)} && if [ ! -e {shlex.quote(remote + '/.git')} ]; then git -C {shlex.quote(remote)} init -q; fi"), check=True) + rsh = "ssh " + " ".join(shlex.quote(o) for o in ssh_options()) + + def sync(keys, listing): + own = [p for p in keys if not p.startswith("external/")] + external = [p.removeprefix("external/") for p in keys if p.startswith("external/")] + for paths, local, dest in ((own, ROOT, remote), (external, EXTERNAL and EXTERNAL.base, remote + "/external")): + if paths: + listing.write_text("\n".join(paths) + "\n") + subprocess.run(["rsync", "-ac", "-e", rsh, "--files-from", str(listing), str(local) + "/", f"{host}:{dest}/"], check=True) + + with tempfile.TemporaryDirectory(prefix="rune-relay-") as tmp: + cache = {} + previous = inputs(cache) + manifest = Path(tmp) / ".rune-dev-files.json" + manifest.write_text(json.dumps(transfer_files(previous))) + listing = Path(tmp) / "files" + sync(transfer_files(previous), listing) + subprocess.run(["scp", *ssh_options(), "-q", str(manifest), f"{host}:{remote}/.rune-dev-files.json"], check=True) + command = f'export PATH="$HOME/.cargo/bin:$HOME/.local/bin:$HOME/bin:/opt/homebrew/bin:$PATH"; cd "$HOME/{remote}" && HIVEMIND_STRICT_PIN=1 hivemind run --worker {shlex.quote(worker(host))} --kind cargo --no-sync -- env RUNE_DEV_LEASE=1 python3 scripts/rune-dev ' + shlex.join(remote_argv(opts, opts.desk)) + process = subprocess.Popen(["ssh", "-tt", host, command], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, bufsize=1, start_new_session=True) + desk = tunnel = patch_relay = None + snap = control = None + if opts.desk: + local = free_port() + tunnel = subprocess.Popen(["ssh", "-N", "-o", "ExitOnForwardFailure=yes", "-L", f"127.0.0.1:{local}:127.0.0.1:{opts.port}", host], start_new_session=True) + cwd = source(EXTERNAL.crate) if EXTERNAL else ROOT / "examples" / opts.example + env = {k: v for k, v in os.environ.items() if k not in ("RUNE_HOT_PARK", "RUNE_DEV_LEASE")} + # The app connects to its devserver once, at startup: start it only once dx answers. + desk = Desk(host, ROOT / "target/rune-dev-desk" / tag, app_argv(opts, Path.cwd()), cwd, env, lambda: wait_forward(local, tunnel)) + patch_relay = PatchRelay(("127.0.0.1", local), desk.fetch_patch) + env.update(RUNE_DEV_GUARDED="1", RUNE_HOT="1", DIOXUS_DEVSERVER_IP="127.0.0.1", DIOXUS_DEVSERVER_PORT=str(patch_relay.port), + DIOXUS_BUILD_ID="0", CARGO_MANIFEST_DIR=str(cwd)) + else: + def path_arg(flag): + return Path(opts.app_args[opts.app_args.index(flag) + 1]) if flag in opts.app_args[:-1] else None + snap = path_arg("--snap-on-patch") + control = path_arg("--hot-control") + + def remote_path(path): + return str(path) if path.is_absolute() else f"{remote}/{path}" + if control: + subprocess.run(ssh(host, "mkdir -p " + shlex.quote(remote_path(control.parent))), check=True) + + def receive(): + for line in process.stdout: + if desk and BASE in line: + try: + desk.base(base_message(line)) + except (subprocess.CalledProcessError, OSError, ValueError, RuntimeError) as error: + desk.failed = f"rune-dev: could not start the app here: {error}" + print(desk.failed, file=sys.stderr, flush=True) + continue + complete = True + if snap and "rune-hot-pixels " in line: + for path in (snap, snap.with_suffix(".json")): + dest = ROOT / path + dest.parent.mkdir(parents=True, exist_ok=True) + temp = dest.with_suffix(dest.suffix + ".fetch") + fetched = subprocess.run(["scp", *ssh_options(), "-q", f"{host}:{remote_path(path)}", str(temp)]) + if fetched.returncode == 0: temp.replace(dest) + else: complete = False + if complete: + # A completion marker on the desk Mac means its local PNG/tree have arrived too. + print(line, end="", flush=True) + else: + print("rune-dev: snapshot fetch failed", file=sys.stderr, flush=True) + receiver = threading.Thread(target=receive, daemon=True) + receiver.start() + previous_control = None + def tick(): + nonlocal previous_control + if desk and not desk.failed and (failure := tunnel_failure(tunnel)): + desk.failed = failure + print(failure, file=sys.stderr, flush=True) + if desk and (desk.failed or desk.exited()): + if not desk.failed: + print(f"rune-dev: the app exited ({desk.app.returncode})", flush=True) + stop(process) + return + if control: + try: + data = (ROOT / control).read_bytes() + except OSError: + return + if data != previous_control: + subprocess.run(["scp", *ssh_options(), "-q", str(ROOT / control), f"{host}:{remote_path(control)}"], check=True) + previous_control = data + + def relay_source(current): + nonlocal previous + changed = [p for p, data in current.items() if previous.get(p) != data] + # Missing/new inputs are caught by the worker's manifest comparison. + sync(changed, listing) + manifest.write_text(json.dumps(transfer_files(current))) + subprocess.run(["scp", *ssh_options(), "-q", str(manifest), f"{host}:{remote}/.rune-dev-files.json"], check=True) + previous = current + + where = "the app runs here; patches arrive over SSH" if desk else "PNG/tree snapshots are fetched here" + print(f"rune-dev: {host} source ~/{remote}; edit this checkout. {where}.", flush=True) + try: + watch(relay_source, process, previous, cache, tick) + finally: + for child in (desk and desk.app, tunnel, process): + if child: stop(child) + if patch_relay: patch_relay.close() + receiver.join(timeout=15) + if desk and desk.failed: + return 1 + return process.returncode + + +class Restart(Exception): + """A local run's edit needs a new build.""" + + +def local(argv): + """Compiles and runs the app here, rebuilding and relaunching it after a restart-needed edit.""" + wrap = os.environ.get("RUNE_DEV_WRAP") + if wrap and not os.environ.get("RUNE_DEV_WRAPPED"): + os.environ["RUNE_DEV_WRAPPED"] = "1" + command = [*shlex.split(wrap), "python3", str(Path(__file__).resolve()), *argv] + os.execvp(command[0], command) + while True: + try: + return run(argv) + except Restart: + print("rune-dev: restarting with the new build", flush=True) + + +def run(args): + global EXTERNAL + opts = parse(args) + if not opts.local and "studio" in socket.gethostname().lower(): + raise SystemExit("rune-dev: compiler and renderer must stay on Pro; restart without RUNE_DEV_LEASE") + parser = opts.parser + # The build Mac's copy parks in desk mode, so it needs no app arguments. A local run's file + # flags are relative to where it was started. + app_args = app_argv(opts, Path.cwd() if opts.local else ROOT) if not opts.desk else (["--hot"] if opts.example else []) + env = dict(os.environ, RUSTC_WRAPPER="", CARGO_INCREMENTAL="1", CARGO_BUILD_JOBS="2", RUNE_DEV_GUARDED="1", RUNE_HOT="1", + CARGO_TARGET_DIR=str(ROOT / "target/live-edit-build")) + env.pop("RUNE_HOT_PARK", None) + guard_root = ROOT / "tools/rune-dev-guard" + subprocess.run(["cargo", "build", "--manifest-path", str(guard_root / "Cargo.toml")], env=env, check=True) + guard = Path(env.get("CARGO_TARGET_DIR", str(guard_root / "target"))) / "debug/rune-dev-guard" + if opts.example: + mirror = ROOT / "target/rune-dev" / opts.example + allowed = EXAMPLES[opts.example].__contains__ + package, crate, cargo_config = opts.example, None, [] + else: + if (ROOT / ".rune-dev-files.json").exists(): + # A relay staged the crate at its key. + crate = opts.manifest_path.parent.as_posix() + if crate != "external" and not crate.startswith("external/"): parser.error("a staged --manifest-path is external/…/Cargo.toml") + else: + EXTERNAL = external_layout(opts.manifest_path) + crate = EXTERNAL.crate + # Outside any checkout: Cargo would take an enclosing [workspace] for the app's. + mirror = Path(os.environ.get("XDG_CACHE_HOME", Path.home() / ".cache")) / "rune-dev" / hashlib.sha256(f"{ROOT}\0{crate}".encode()).hexdigest()[:12] + name, has_profile = crate_settings(source(crate), source("external")) + package = opts.package or name + if package == name: + spec = package_spec(source(crate), source("external")) + env["PATH"] = cargo_shim(mirror / ".rune-dev-bin", name, spec, env.get("PATH", os.defpath)) + cargo_config = [] if has_profile else PROFILE + allowed = patchable(crate, opts.patch) + cache = {} + baseline = inputs(cache) + if crate and not any(p.startswith(crate + "/") for p in baseline): + parser.error(f"no files staged for {crate}") + # Remove stale source files, but retain compiler artifacts between invocations. + old_manifest = mirror / ".inputs.json" + if old_manifest.exists(): + for p in set(json.loads(old_manifest.read_text())) - set(baseline): + (mirror / p).unlink(missing_ok=True) + overrides = mirror_overrides(crate, baseline) + for p, data in baseline.items(): + data = overrides.get(p, data) + dest = mirror / p + dest.parent.mkdir(parents=True, exist_ok=True) + if not dest.exists() or dest.read_bytes() != data: dest.write_bytes(data) + old_manifest.parent.mkdir(parents=True, exist_ok=True) + old_manifest.write_text(json.dumps(list(baseline))) + # Workspace excludes reference this independent tool; Cargo needn't see its source. + dx = Path(os.environ.get("RUNE_DX", str(Path.home() / ".cargo/bin/dx"))) + if not dx.exists(): parser.error("install dioxus-cli 0.7.10 (the Deno dx command is unrelated)") + park = mirror / ".rune-hot-park" + park.unlink(missing_ok=True) + if opts.desk: + env["RUNE_HOT_PARK"] = str(park) + command = dx_command(dx, opts.port, package, opts.features, opts.bin, cargo_config, app_args) + process = subprocess.Popen(command, cwd=mirror / crate if crate else mirror, env=env, start_new_session=True) + reported = None + def report_base(): + # Each build's parked copy names the binary the desk Mac must run. + nonlocal reported + try: + exe = park.read_text() + stamp = park.stat().st_mtime_ns + except FileNotFoundError: + return + if (exe, stamp) != reported: + reported = exe, stamp + print(BASE + json.dumps({"exe": exe, "sha256": sha256(exe), **platform_info()}), flush=True) + try: + with tempfile.TemporaryDirectory(prefix="rune-guard-") as tmp: + candidate = Path(tmp) / "candidate.rs" + def publish(current): + nonlocal baseline + changed = [p for p, data in current.items() if baseline.get(p) != data] + incompatible = (set(current) ^ set(baseline)) | {p for p in changed if not allowed(p)} + if incompatible: + print("rune-dev: restart needed: " + ", ".join(sorted(incompatible)), flush=True) + if opts.local: + raise Restart() + return + for p in changed: + candidate.write_bytes(current[p]) + if subprocess.run([str(guard), str(mirror / p), str(candidate)]).returncode: + return + # All files validated from immutable bytes before publishing any of them. + for p in changed: + dest = mirror / p + temp = dest.with_suffix(".rune-tmp") + temp.write_bytes(current[p]) + temp.replace(dest) + baseline = current + print("rune-dev: accepted " + ", ".join(changed), flush=True) + watch(publish, process, baseline, cache, report_base if opts.desk else None) + finally: + stop(process) + return process.returncode + + +if __name__ == "__main__": + def interrupted(signum, frame): + raise KeyboardInterrupt() + signal.signal(signal.SIGTERM, interrupted) + signal.signal(signal.SIGHUP, interrupted) + try: + ours = sys.argv[1:sys.argv.index("--")] if "--" in sys.argv else sys.argv[1:] + if "--local" in ours or os.environ.get("RUNE_DEV_LOCAL"): + sys.exit(local(sys.argv[1:])) + if not os.environ.get("RUNE_DEV_LEASE"): + if "--desk" in ours or "studio" in socket.gethostname().lower(): + sys.exit(relay(sys.argv[1:])) + os.environ["HIVEMIND_STRICT_PIN"] = "1" + host = os.environ.get("RUNE_DEV_BUILD_HOST", "pro") + os.execvp("hivemind", ["hivemind", "run", "--worker", worker(host), "--kind", "cargo", "--no-sync", "--", "env", "RUNE_DEV_LEASE=1", "python3", str(Path(__file__).resolve()), *sys.argv[1:]]) + sys.exit(run(sys.argv[1:])) + except KeyboardInterrupt: + sys.exit(130) diff --git a/app/vendor/rune/scripts/rune-hot b/app/vendor/rune/scripts/rune-hot new file mode 100644 index 0000000..caeffe5 --- /dev/null +++ b/app/vendor/rune/scripts/rune-hot @@ -0,0 +1,24 @@ +#!/usr/bin/env bash +# Hot reload for a Rune app, compiled and run on this machine: `scripts/rune-dev --local` under the +# flags apps already pass. Saved edits to function bodies in the --patch files patch into the open +# window; any other edit rebuilds and restarts the app, so apps should restore their own state +# (tabs, route, drafts) at launch. +# scripts/rune-hot --manifest app/Cargo.toml --patch src/view.rs [--patch …] [--port 18745] \ +# [-- APP ARGS] +# Needs Dioxus CLI 0.7.10 as `dx` in Cargo's bin directory (RUNE_DX overrides the path). +# RUNE_DEV_WRAP runs the build and the app under a command prefix (a build-queue lease, say); +# without it they run under plain cargo. +set -euo pipefail +here=$(cd "$(dirname "$0")" && pwd) +manifest="" port=18745 patches=() +while [[ $# -gt 0 ]]; do + case "$1" in + --manifest) manifest=$2; shift 2 ;; + --patch) patches+=(--patch "$2"); shift 2 ;; + --port) port=$2; shift 2 ;; + --) shift; break ;; + *) echo "rune-hot: unknown flag $1" >&2; exit 2 ;; + esac +done +[[ -n $manifest ]] || { echo "rune-hot: --manifest is required" >&2; exit 2; } +exec python3 "$here/rune-dev" --local --manifest-path "$manifest" ${patches[@]+"${patches[@]}"} --port "$port" -- "$@" diff --git a/app/vendor/rune/scripts/shortcut-recorder.json b/app/vendor/rune/scripts/shortcut-recorder.json new file mode 100644 index 0000000..2624e04 --- /dev/null +++ b/app/vendor/rune/scripts/shortcut-recorder.json @@ -0,0 +1,5 @@ +[ + {"t": 0.1, "key": "shortcut", "type": "click"}, + {"t": 0.3, "physical": "ctrl+alt+k"}, + {"t": 0.5, "shortcut": "ctrl+alt+k"} +] diff --git a/app/vendor/rune/scripts/snap-ui.py b/app/vendor/rune/scripts/snap-ui.py new file mode 100644 index 0000000..f7ee7ca --- /dev/null +++ b/app/vendor/rune/scripts/snap-ui.py @@ -0,0 +1,15 @@ +#!/usr/bin/env python3 +"""Pin headless regression images. Usage: snap-ui.py OUT [BIN_DIR]. No native windows.""" +import pathlib +import subprocess +import sys + +out = pathlib.Path(sys.argv[1]) +bin_dir = pathlib.Path(sys.argv[2]) if len(sys.argv) > 2 else pathlib.Path('target/release') +out.mkdir(parents=True, exist_ok=True) +cases = { + 'settings-dark': ('settings', ['--scene', 'dark']), + 'settings-light': ('settings', ['--scene', 'light']), +} +for name, (binary, args) in cases.items(): + subprocess.run([str(bin_dir / binary), *args, '--snap', str(out / f'{name}.png')], check=True) diff --git a/app/vendor/rune/scripts/test-rune-dev.py b/app/vendor/rune/scripts/test-rune-dev.py new file mode 100644 index 0000000..52d1c2c --- /dev/null +++ b/app/vendor/rune/scripts/test-rune-dev.py @@ -0,0 +1,412 @@ +#!/usr/bin/env python3 +"""Source-watch, external-crate and desk-relay regressions; no compiler, SSH, renderer or wall-clock waits.""" +import importlib.machinery +import importlib.util +import io +import json +import os +from pathlib import Path +import socket +import sys +import tempfile +import threading +import unittest +from unittest.mock import Mock, patch + +sys.dont_write_bytecode = True # no __pycache__ beside the script +loader = importlib.machinery.SourceFileLoader("rune_dev", str(Path(__file__).with_name("rune-dev"))) +spec = importlib.util.spec_from_loader(loader.name, loader) +dev = importlib.util.module_from_spec(spec) +loader.exec_module(dev) + + +class WatchTests(unittest.TestCase): + def setUp(self): + self.temp = tempfile.TemporaryDirectory() + self.addCleanup(self.temp.cleanup) + self.root = Path(self.temp.name) + self.names = ["Cargo.toml", "examples/settings/src/main.rs", "examples/settings/assets/font.ttf"] + for name in self.names: + path = self.root / name + path.parent.mkdir(parents=True, exist_ok=True) + path.write_bytes(b"original") + for mock in [patch.object(dev, "ROOT", self.root), patch.object(dev, "files", lambda: self.names)]: + mock.start() + self.addCleanup(mock.stop) + + def fresh(self): + return {p: (self.root / p).read_bytes() for p in self.names if (self.root / p).is_file()} + + def test_cache_matches_full_reads_through_saves_replacements_additions_and_deletions(self): + cache = {} + reads = [] + read = Path.read_bytes + + def counted(path): + reads.append(path) + return read(path) + + with patch.object(Path, "read_bytes", counted): + first = dev.inputs(cache) + self.assertEqual(len(reads), 3) + self.assertEqual(dev.inputs(cache), first) + self.assertEqual(len(reads), 3, "unchanged scans must not re-read assets or source") + source = self.root / self.names[1] + saved = source.stat() + source.write_bytes(b"modified") + os.utime(source, ns=(saved.st_atime_ns, saved.st_mtime_ns)) + changed = dev.inputs(cache) + self.assertEqual(changed[self.names[1]], b"modified") + self.assertEqual(reads[3:], [source], "same-size edits with restored mtime must be read") + replacement = self.root / "replacement" + replacement.write_bytes(b"replaced") + os.utime(replacement, ns=(saved.st_atime_ns, saved.st_mtime_ns)) + replacement.replace(source) + self.assertEqual(dev.inputs(cache)[self.names[1]], b"replaced") + (self.root / self.names[0]).unlink() + self.names.append("examples/settings/src/added.rs") + (self.root / self.names[-1]).write_bytes(b"new") + self.assertEqual(dev.inputs(cache), self.fresh()) + self.assertNotIn("Cargo.toml", cache) + + def test_partial_read_does_not_publish_a_new_cache(self): + cache = {} + original = dev.inputs(cache) + source = self.root / self.names[1] + source.write_bytes(b"edit") + read = Path.read_bytes + + def racing(path): + data = read(path) + if path == source: + path.write_bytes(b"finished edit") + return data + + with patch.object(Path, "read_bytes", racing): + with self.assertRaises(OSError): + dev.inputs(cache) + self.assertEqual({p: data for p, (_, data) in cache.items()}, original) + self.assertEqual(dev.inputs(cache), self.fresh()) + + def test_shared_watch_retries_read_races_and_reports_each_change_once(self): + initial = {"view.rs": b"old"} + edited = {"view.rs": b"new"} + process = Mock() + process.poll.side_effect = [None, None, None, None, None, 0] + on_change, on_tick = Mock(), Mock() + with patch.object(dev.select, "select"), patch.object(dev, "inputs", side_effect=[initial, OSError("save in progress"), edited, edited, {}]): + dev.watch(on_change, process, initial, {}, on_tick) + self.assertEqual([call.args[0] for call in on_change.call_args_list], [edited, {}]) + self.assertEqual(on_tick.call_count, 5) + + +class ArgumentTests(unittest.TestCase): + def test_examples_keep_their_old_command_lines(self): + opts = dev.parse(["settings", "--scene", "session", "--snap-on-patch", "a.png"]) + self.assertEqual((opts.example, opts.app_args), ("settings", ["--scene", "session", "--snap-on-patch", "a.png"])) + self.assertEqual(dev.parse(["settings", "--", "--port", "1"]).port, 18744, "after -- every flag is the app's") + + def test_external_crates_name_their_patchable_files(self): + opts = dev.parse(["--manifest-path", "../app/Cargo.toml", "--bin", "app", "--features", "fixture", "--patch", "src/ui/*.rs", "--desk", "--", "--hot-control", "c.json"]) + self.assertEqual((opts.manifest_path, opts.bin, opts.features, opts.patch, opts.desk), (Path("../app/Cargo.toml"), "app", "fixture", ["src/ui/*.rs"], True)) + self.assertEqual(opts.app_args, ["--hot-control", "c.json"]) + for bad in [[], ["settings", "--manifest-path", "x/Cargo.toml"], ["--manifest-path", "x/Cargo.toml"], ["settings", "--patch", "*.rs"]]: + with self.subTest(bad=bad), self.assertRaises(SystemExit), patch("sys.stderr"): + dev.parse(bad) + + def test_local_runs_take_the_flag_or_the_environment_but_not_desk(self): + argv = ["--manifest-path", "app/Cargo.toml", "--patch", "src/view.rs"] + with patch.dict(os.environ, {}, clear=False): + os.environ.pop("RUNE_DEV_LOCAL", None) + self.assertFalse(dev.parse(argv).local) + self.assertTrue(dev.parse([*argv, "--local"]).local) + os.environ["RUNE_DEV_LOCAL"] = "1" + self.assertTrue(dev.parse(argv).local) + with self.assertRaises(SystemExit), patch("sys.stderr"): + dev.parse([*argv, "--local", "--desk"]) + + def test_a_local_run_rebuilds_after_a_restart_and_returns_the_apps_exit(self): + with patch.dict(os.environ, {}, clear=False), patch.object(dev, "run", side_effect=[dev.Restart(), dev.Restart(), 3]) as run, patch("sys.stdout", io.StringIO()) as out: + os.environ.pop("RUNE_DEV_WRAP", None) + self.assertEqual(dev.local(["--local"]), 3) + self.assertEqual(run.call_count, 3) + self.assertEqual(out.getvalue().count("rune-dev: restarting with the new build"), 2) + + def test_a_local_run_execs_itself_once_under_the_wrap_prefix(self): + with patch.dict(os.environ, {"RUNE_DEV_WRAP": "lease --kind build --"}, clear=False), patch.object(dev.os, "execvp") as execvp: + os.environ.pop("RUNE_DEV_WRAPPED", None) + execvp.side_effect = SystemExit(0) + with self.assertRaises(SystemExit): + dev.local(["--local", "--", "a"]) + command = execvp.call_args.args[1] + self.assertEqual(command[:5], ["lease", "--kind", "build", "--", "python3"]) + self.assertEqual(command[-3:], ["--local", "--", "a"]) + self.assertEqual(os.environ["RUNE_DEV_WRAPPED"], "1") + + def test_remote_arguments_name_the_staged_crate_and_park_the_build_copy(self): + opts = dev.parse(["--manifest-path", "/w/app/Cargo.toml", "--patch", "src/ui/**/*.rs", "--port", "9", "--", "--fixture", "f.json"]) + with patch.object(dev, "EXTERNAL", dev.External(Path("/w"), "external/app", ["app"], [])): + self.assertEqual(dev.remote_argv(opts, False), ["--manifest-path", "external/app/Cargo.toml", "--patch", "src/ui/**/*.rs", "--port", "9", "--", "--fixture", "f.json"]) + self.assertEqual(dev.remote_argv(opts, True)[-1], "--desk") + self.assertNotIn("f.json", dev.remote_argv(opts, True)) + + def test_dx_gets_the_app_target_and_an_adhoc_profile(self): + command = dev.dx_command("dx", 7, "app", "fixture,", "app", dev.PROFILE, []) + self.assertEqual(command[command.index("--features") + 1], "hot,fixture") + self.assertEqual(command[command.index("--bin") + 1], "app") + cargo_args = next(a for a in command if a.startswith("--cargo-args=")) + self.assertIn("--config 'profile.rune-hot.inherits=\"dev\"'", cargo_args) + self.assertFalse(any(a.startswith("--args") for a in command), "no app arguments: RUNE_HOT enables Rune") + self.assertFalse(any(a.startswith("--cargo-args") for a in dev.dx_command("dx", 7, "app", "", None, [], ["--hot"]))) + + +class ExternalTests(unittest.TestCase): + def setUp(self): + self.temp = tempfile.TemporaryDirectory() + self.addCleanup(self.temp.cleanup) + self.root = Path(self.temp.name).resolve() + + def write(self, name, text=""): + path = self.root / name + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(text) + + def test_layout_mirrors_path_dependencies_and_their_workspace_files(self): + self.write("work/Cargo.toml", '[workspace]\nmembers = ["app", "ui"]\n[workspace.dependencies]\nshared = { path = "../shared" }\n') + self.write("work/Cargo.lock") + self.write("work/.cargo/config.toml") + self.write("work/app/Cargo.toml", '[package]\nname = "app"\n[features]\nhot = ["rune/hot"]\n[dependencies]\nui = { path = "../ui" }\nshared.workspace = true\nrune = { git = "https://example.com/rune" }\n[lib]\npath = "src/lib.rs"\n') + self.write("work/ui/Cargo.toml", '[package]\nname = "ui"\n[target.\'cfg(unix)\'.dev-dependencies]\nleaf = { path = "../../leaf" }\n') + self.write("shared/Cargo.toml", '[package]\nname = "shared"\n') + self.write("leaf/Cargo.toml", '[package]\nname = "leaf"\n') + layout = dev.external_layout(self.root / "work/app/Cargo.toml") + self.assertEqual(layout.base, self.root) + self.assertEqual(layout.crate, "external/work/app") + self.assertEqual(layout.dirs, ["leaf", "shared", "work/app", "work/ui"]) + self.assertEqual(sorted(layout.tops), ["work/.cargo/config.toml", "work/Cargo.lock", "work/Cargo.toml"]) + self.assertEqual(dev.crate_settings(self.root / "work/app", self.root), ("app", False)) + self.write("work/Cargo.toml", '[workspace]\n[profile.rune-hot]\ninherits = "dev"\n') + self.assertEqual(dev.crate_settings(self.root / "work/app", self.root), ("app", True)) + self.write("work/ui/Cargo.toml", '[package]\nname = "ui"\n') + with self.assertRaisesRegex(SystemExit, "hot"): + dev.crate_settings(self.root / "work/ui", self.root) + + def test_dx_names_the_app_by_version_when_a_dependency_shares_its_name(self): + self.write("work/Cargo.toml", '[workspace]\n[workspace.package]\nversion = "2.0.0"\n') + self.write("work/app/Cargo.toml", '[package]\nname = "codec"\nversion.workspace = true\n') + self.write("solo/Cargo.toml", '[package]\nname = "solo"\n') + self.assertEqual(dev.package_spec(self.root / "work/app", self.root), "codec@2.0.0") + self.assertEqual(dev.package_spec(self.root / "solo", self.root), "solo") + self.write("real/cargo", "#!/bin/sh\nprintf '%s\\n' \"$@\"\n") + (self.root / "real/cargo").chmod(0o755) + path = dev.cargo_shim(self.root / "bin", "codec", "codec@2.0.0", str(self.root / "real")) + self.assertEqual(path.split(os.pathsep)[0], str(self.root / "bin")) + run = lambda *args: dev.subprocess.run(["cargo", *args], env={"PATH": path + os.pathsep + os.defpath}, capture_output=True, text=True, check=True).stdout.split() + self.assertEqual(run("build", "-p", "codec", "--bin", "codec"), ["build", "-p", "codec@2.0.0", "--bin", "codec"]) + self.assertEqual(run("rustc", "--package=codec", "-pcodec"), ["rustc", "--package=codec@2.0.0", "-pcodec@2.0.0"]) + self.assertEqual(dev.cargo_shim(self.root / "none", "solo", "solo", str(self.root / "real")), str(self.root / "real")) + + def test_external_keys_read_the_original_files(self): + self.write("app/Cargo.toml", '[package]\nname = "app"\n') + self.write("app/src/ui/list.rs", "fn view() {}") + self.write("app/target/debug/app", "binary") + layout = dev.external_layout(self.root / "app/Cargo.toml") + self.assertEqual(layout.crate, "external") + with patch.object(dev, "EXTERNAL", layout): + keys = dev.files() + self.assertIn("external/src/ui/list.rs", keys) + self.assertIn("scripts/rune-dev", keys) + self.assertFalse(any("target/" in k for k in keys)) + self.assertEqual(dev.source("external/src/ui/list.rs").read_text(), "fn view() {}") + self.assertEqual(dev.source("scripts/rune-dev"), dev.ROOT / "scripts/rune-dev") + self.assertEqual(set(dev.inputs({})), {"external/Cargo.toml", "external/src/ui/list.rs"}) + + def test_the_mirrored_workspace_lists_only_staged_members(self): + manifest = ('[workspace]\nresolver = "2"\n# members below\nmembers = [\n "app", # the app\n "crates/*",\n "tools/[x]",\n]\n' + 'default-members = ["app", "tools/cli"]\nexclude = ["crates/old"]\n\n[workspace.dependencies]\nui = { path = "crates/ui" }\n') + self.write("ws/Cargo.toml", manifest) + self.write("ws/app/Cargo.toml", '[package]\nname = "app"\n[features]\nhot = ["rune/hot"]\n[dependencies]\nui.workspace = true\n') + self.write("ws/crates/ui/Cargo.toml", '[package]\nname = "ui"\n') + self.write("ws/crates/old/Cargo.toml", '[package]\nname = "old"\n') + self.write("ws/crates/other/Cargo.toml", '[package]\nname = "other"\n') + self.write("ws/tools/cli/Cargo.toml", '[package]\nname = "cli"\n') + layout = dev.external_layout(self.root / "ws/app/Cargo.toml") + self.assertEqual(layout.dirs, ["app", "crates/ui"], "unrelated members aren't staged") + with patch.object(dev, "EXTERNAL", layout): + data = dev.inputs({}) + # The build Mac has only these: a workspace naming crates/other or tools/cli fails to load. + self.assertNotIn("external/crates/other/Cargo.toml", data) + overrides = dev.mirror_overrides(layout.crate, data) + self.assertEqual(list(overrides), ["external/Cargo.toml"]) + staged = dev.tomllib.loads(overrides["external/Cargo.toml"].decode()) + self.assertEqual(staged["workspace"]["members"], ["app", "crates/ui"]) + self.assertEqual(staged["workspace"]["default-members"], ["app"]) + self.assertEqual(staged["workspace"]["dependencies"], {"ui": {"path": "crates/ui"}}) + self.assertIn("# members below", overrides["external/Cargo.toml"].decode(), "the rest of the file is kept") + self.write("ws/Cargo.toml", '[workspace]\n') + self.write("ws/app/Cargo.toml", '[package]\nname = "app"\nworkspace = ".."\n') + self.assertEqual(dev.workspace_key("external/app", {"external/Cargo.toml": b"[workspace]\n", "external/app/Cargo.toml": b'[package]\nworkspace = ".."\n'}), "external/Cargo.toml") + self.assertEqual(dev.mirror_overrides("external/app", {"external/app/Cargo.toml": b'[package]\nname = "app"\n'}), {}, "a lone crate is mirrored as is") + + def test_only_globbed_rust_files_in_the_app_crate_patch(self): + allowed = dev.patchable("external/work/app", ["src/ui/*.rs", "src/views/**/*.rs"]) + self.assertTrue(allowed("external/work/app/src/ui/list.rs")) + self.assertTrue(allowed("external/work/app/src/views/a/b/c.rs")) + for key in ["external/work/app/src/ui/nested/list.rs", "external/work/app/src/ui/icon.svg", "external/work/app/src/main.rs", + "external/work/app/Cargo.toml", "external/work/ui/src/ui/list.rs", "external/work/application/src/ui/list.rs", + "external/rune/crates/rune/src/runtime.rs"]: + self.assertFalse(allowed(key), key) + + +def ws_frame(opcode, payload, fin=True): + return dev.frame(opcode, payload, fin) + + +class DeskTests(unittest.TestCase): + def test_only_this_process_patch_is_fetched_and_rewritten(self): + message = {"HotReload": {"jump_table": {"lib": "/build/libserver-patch-1.dylib", "map": {"4294983856": 4295000000}, "aslr_reference": 1, "new_base_address": 2}, + "templates": [], "assets": [], "ms_elapsed": 1, "for_pid": 42, "for_build_id": 0}} + fetched = [] + def fetch(lib): + fetched.append(lib) + return Path("/desk/patches/libserver-patch-1.dylib") + rewritten = json.loads(dev.rewrite_patch(json.dumps(message), 42, fetch)) + self.assertEqual(rewritten["HotReload"]["jump_table"]["lib"], "/desk/patches/libserver-patch-1.dylib") + self.assertEqual(rewritten["HotReload"]["jump_table"]["map"], message["HotReload"]["jump_table"]["map"]) + self.assertEqual(fetched, ["/build/libserver-patch-1.dylib"]) + for other in [json.dumps(message).replace('"for_pid": 42', '"for_pid": 7'), '"HotPatchStart"', "not json", '{"HotReload": {"jump_table": null, "for_pid": 42}}']: + self.assertEqual(dev.rewrite_patch(other, 42, fetch), other) + self.assertEqual(len(fetched), 1) + + def test_a_patch_for_another_base_binary_is_refused(self): + with tempfile.TemporaryDirectory() as tmp: + desk = dev.Desk("build", Path(tmp), [], tmp, {}) + desk.remote_exe, desk.sha = "/build/server", "a" * 64 + result = Mock(returncode=0, stdout=b"b" * 64 + b"\nPATCH", stderr=b"") + with patch.object(dev.subprocess, "run", return_value=result), self.assertRaisesRegex(RuntimeError, "not applying"): + desk.fetch_patch("/build/libserver-patch-2.dylib") + result.stdout = b"a" * 64 + b"\nPATCH" + with patch.object(dev.subprocess, "run", return_value=result) as run: + local = desk.fetch_patch("/build/libserver-patch-2.dylib") + self.assertEqual(local.read_bytes(), b"PATCH") + self.assertEqual(local.name, "libserver-patch-2.dylib") + self.assertIn("shasum -a 256 /build/server", run.call_args.args[0][-1]) + + def test_a_base_for_another_platform_fails_before_copying(self): + local = {"system": "Darwin", "machine": "arm64"} + self.assertIsNone(dev.check_base({"system": "Darwin", "machine": "arm64"}, local)) + self.assertIn("x86_64", dev.check_base({"system": "Darwin", "machine": "x86_64"}, local)) + with tempfile.TemporaryDirectory() as tmp, patch.object(dev, "platform_info", return_value=local), patch.object(dev.subprocess, "run") as run, patch("sys.stderr"): + desk = dev.Desk("build", Path(tmp), [], tmp, {}) + desk.base({"exe": "/build/server", "sha256": "a" * 64, "system": "Linux", "machine": "arm64"}) + self.assertIn("Linux", desk.failed) + run.assert_not_called() + + def test_a_base_report_behind_pty_bytes_still_starts_the_desk_app(self): + info = {"exe": "/build/server", "sha256": "a" * 64, "system": "Darwin", "machine": "arm64"} + for line in [dev.BASE + json.dumps(info) + "\n", "\r\x1b[K" + dev.BASE + json.dumps(info) + "\r\n"]: + self.assertEqual(dev.base_message(line), info) + self.assertIsNone(dev.base_message("Compiling app\n")) + + def forwarded(self, behaviour): + """A stand-in for an `ssh -L` port: accepts, then answers or closes like a missing remote.""" + server = socket.create_server(("127.0.0.1", 0)) + self.addCleanup(server.close) + def serve(): + while True: + try: + conn, _ = server.accept() + except OSError: + return + with conn: + behaviour(conn) + threading.Thread(target=serve, daemon=True).start() + return server.getsockname()[1] + + def test_the_desk_app_waits_for_dx_through_the_tunnel_and_a_dead_tunnel_fails_loudly(self): + silent = self.forwarded(lambda conn: None) + self.assertFalse(dev.answers(silent), "ssh accepting a forward isn't dx answering") + tunnel = Mock(returncode=255) + tunnel.poll.side_effect = [None, None, 255] + with self.assertRaisesRegex(RuntimeError, "tunnel to dx exited"): + dev.wait_forward(silent, tunnel, timeout=30, interval=.01) + with self.assertRaisesRegex(RuntimeError, "did not answer"): + dev.wait_forward(silent, Mock(poll=Mock(return_value=None)), timeout=.05, interval=.01) + calls = [] + def dx(conn): + calls.append(1) + if len(calls) > 2: + conn.recv(1024) + conn.sendall(b"HTTP/1.1 404 Not Found\r\n\r\n") + dev.wait_forward(self.forwarded(dx), Mock(poll=Mock(return_value=None)), timeout=30, interval=.01) + self.assertEqual(len(calls), 3, "the app starts once dx answers, not before") + self.assertIsNone(dev.tunnel_failure(Mock(poll=Mock(return_value=None)))) + self.assertIn("Rerun", dev.tunnel_failure(Mock(poll=Mock(return_value=1), returncode=1))) + + def test_the_relay_retries_dx_while_the_forward_comes_up(self): + calls = [] + def dx(conn): + calls.append(1) + if len(calls) < 3: + return # ssh closing a forward whose remote end isn't listening yet + dev.read_head(conn) + conn.sendall(b"HTTP/1.1 101 Switching Protocols\r\n\r\n") + conn.recv(1) + relay = dev.PatchRelay(("127.0.0.1", self.forwarded(dx)), lambda lib: lib, interval=.01) + self.addCleanup(relay.close) + with socket.create_connection(("127.0.0.1", relay.port), timeout=10) as app: + app.sendall(b"GET /_dioxus?pid=7 HTTP/1.1\r\nHost: x\r\n\r\n") + response, _ = dev.read_head(app) + self.assertIn(b"101", response) + self.assertEqual(len(calls), 3) + + def test_relay_rewrites_fragmented_patches_and_passes_other_frames(self): + upstream = socket.create_server(("127.0.0.1", 0)) + self.addCleanup(upstream.close) + patch_message = json.dumps({"HotReload": {"jump_table": {"lib": "/build/p.dylib", "map": {}}, "for_pid": 42}}).encode() + long = json.dumps({"FullReloadStart": "x" * 70000}).encode() + seen = {} + def dx(): + conn, _ = upstream.accept() + head, _ = dev.read_head(conn) + seen["head"] = head + conn.sendall(b"HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n\r\n") + conn.sendall(ws_frame(9, b"ping") + ws_frame(1, patch_message[:10], False) + ws_frame(0, patch_message[10:]) + ws_frame(1, long)) + fin, op, payload = dev.read_frame(conn.makefile("rb")) + seen["client"] = (fin, op, payload) + conn.close() + server = threading.Thread(target=dx, daemon=True) + server.start() + relay = dev.PatchRelay(upstream.getsockname(), lambda lib: Path("/desk/p.dylib")) + self.addCleanup(relay.close) + with socket.create_connection(("127.0.0.1", relay.port)) as app: + app.sendall(b"GET /_dioxus?aslr_reference=1&build_id=0&pid=42 HTTP/1.1\r\nHost: x\r\nSec-WebSocket-Extensions: permessage-deflate\r\n\r\n") + response, rest = dev.read_head(app) + self.assertIn(b"101", response) + data = rest + def next_frame(): + nonlocal data + while True: + try: + frame = dev.read_frame(io.BytesIO(data)) + size = len(dev.frame(frame[1], frame[2], frame[0])) + data = data[size:] + return frame + except EOFError: + chunk = app.recv(65536) + if not chunk: raise + data += chunk + frames = [next_frame() for _ in range(3)] + mask = b"\x01\x02\x03\x04" + payload = b"pong" + app.sendall(bytes([0x8a, 0x80 | len(payload)]) + mask + bytes(b ^ mask[i % 4] for i, b in enumerate(payload))) + server.join(5) + self.assertNotIn(b"permessage-deflate", seen["head"].lower()) + self.assertEqual(frames[0], (True, 9, b"ping")) + self.assertEqual(json.loads(frames[1][2])["HotReload"]["jump_table"]["lib"], "/desk/p.dylib") + self.assertEqual(frames[2], (True, 1, long)) + self.assertEqual(seen["client"], (True, 10, b"pong"), "the app's frames reach dx unchanged") + + +if __name__ == "__main__": + unittest.main() diff --git a/app/vendor/rune/scripts/text-coverage-sweep.py b/app/vendor/rune/scripts/text-coverage-sweep.py new file mode 100644 index 0000000..21dc1bc --- /dev/null +++ b/app/vendor/rune/scripts/text-coverage-sweep.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +"""Offline hypothesis search; production GPU renders must validate any selected result. + +Fit on first two strings per size, report held-out last three. Never fit geometry. +""" +import argparse +import importlib.util +import json +from pathlib import Path +import numpy as np +from scipy.ndimage import maximum_filter + +spec=importlib.util.spec_from_file_location('quality',Path(__file__).with_name('text-quality.py')) +q=importlib.util.module_from_spec(spec); spec.loader.exec_module(q) + +p=argparse.ArgumentParser(); p.add_argument('directory',type=Path); a=p.parse_args() +results=[] +for scale in (1,2): + raw=q.read(a.directory/f'coverage-{scale}x.png') + expanded=maximum_filter(raw,size=3) + for mode in ('light','dark'): + m=json.loads((a.directory/f'{mode}-{scale}x.json').read_text()) + ref=q.read(a.directory/f'coretext-{mode}-{scale}x.png') + fg=m['fg']/255; bg=m['bg']/255 + train=np.zeros(raw.shape,dtype=bool); holdout=train.copy() + for i,row in enumerate(m['rows']): + y=int(row['top']); last=row['glyphs'][-1] + right=int(last['x']+last['advance']+4) + (train if i%5<2 else holdout)[y:y+42*scale,:right]=True + mask=((np.abs(ref-bg)>.005)|(raw>0)) + train &= mask; holdout &= mask + candidates=[] + for dilation in (0,.05,.1,.15,.2,.3): + cov=raw+dilation*(expanded-raw) + for gamma in np.arange(.4,2.01,.05): + rendered=q.encode(q.decode(bg)+(q.decode(fg)-q.decode(bg))*cov**gamma) + err=(rendered-ref)**2 + candidates.append({'gamma':round(float(gamma),3),'dilation':dilation, + 'train_rmse':float(np.sqrt(err[train].mean())), + 'holdout_rmse':float(np.sqrt(err[holdout].mean()))}) + candidates.sort(key=lambda c:c['train_rmse']) + result={'scale':scale,'mode':mode,'best':candidates[:5], + 'gamma_only':min((c for c in candidates if c['dilation']==0),key=lambda c:c['train_rmse'])} + results.append(result); print(json.dumps(result)) +(a.directory/'sweep.json').write_text(json.dumps(results,indent=2)+'\n') diff --git a/app/vendor/rune/scripts/text-goldens.py b/app/vendor/rune/scripts/text-goldens.py new file mode 100644 index 0000000..6460b4c --- /dev/null +++ b/app/vendor/rune/scripts/text-goldens.py @@ -0,0 +1,49 @@ +#!/usr/bin/env python3 +"""Refresh text-affected stills, reusing the committed Storybook reference columns. + +Run after building settings and kit-gallery in release mode. No browser. +Historical motion strips are separate captures; this updates only named stills. +""" +import importlib.util +import json +from pathlib import Path +import shutil +import subprocess + +from PIL import Image + +ROOT = Path(__file__).resolve().parents[1] +OUT = ROOT / 'perf/autoresearch/text/goldens' +OUT.mkdir(parents=True, exist_ok=True) +spec = importlib.util.spec_from_file_location('kit_diff', ROOT / 'scripts/kit-diff.py') +kit = importlib.util.module_from_spec(spec) +spec.loader.exec_module(kit) + + +def snap(binary, path, *args): + subprocess.run([str(ROOT / 'target/release' / binary), *args, '--snap', str(path)], + cwd=ROOT, check=True, capture_output=True) + + +snap('settings', ROOT / 'demo/settings-dark.png', '--theme', 'dark') +snap('settings', ROOT / 'demo/settings-light.png', '--scene', 'light') + +report = [] +for path in sorted((ROOT / 'demo/kit').glob('side-*.png')): + story, scheme = path.stem.removeprefix('side-').rsplit('-', 1) + directory = OUT / f'{story}-{scheme}' + directory.mkdir(exist_ok=True) + image = Image.open(path).convert('RGB') + width, height = (image.width - 16) // 3, image.height + image.crop((0, 0, width, height)).save(directory / 'web.png') + snap('kit-gallery', directory / 'rune.png', '--scene', story, '--theme', scheme, + '--size', f'{width // 2}x{height // 2}', '--scale', '2') + result = {'story': story, 'scheme': scheme, **kit.compare(directory / 'web.png', directory / 'rune.png', directory)} + report.append(result) + shutil.copyfile(directory / 'side.png', path) +for scheme in ('light', 'dark'): + snap('kit-gallery', ROOT / f'demo/kit/index-{scheme}.png', + '--theme', scheme, '--size', '720x1400', '--scale', '1') + +(ROOT / 'demo/text/kit-metrics.json').write_text(json.dumps(report, indent=2) + '\n') +print(json.dumps(report, indent=2)) diff --git a/app/vendor/rune/scripts/text-quality.py b/app/vendor/rune/scripts/text-quality.py new file mode 100644 index 0000000..7302c31 --- /dev/null +++ b/app/vendor/rune/scripts/text-quality.py @@ -0,0 +1,92 @@ +#!/usr/bin/env python3 +"""SSIM on ink-bounded row crops, signed ink weight, and per-glyph advance-cell errors. + +uv run --with numpy --with pillow --with scikit-image scripts/text-quality.py DIR +SSIM: Wang et al., IEEE TIP 2004. Gaussian sigma=1.5, population covariance, L=1. +No alignment search, rescaling, or full-page empty-background score inflation. +""" +import argparse +import json +from pathlib import Path +import numpy as np +from PIL import Image, ImageDraw +from skimage.metrics import structural_similarity + +def decode(x): + return np.where(x <= .04045, x/12.92, ((x+.055)/1.055)**2.4) + +def encode(x): + return np.where(x <= .0031308, x*12.92, 1.055*np.maximum(x,0)**(1/2.4)-.055) + +def read(path): + return np.asarray(Image.open(path).convert('RGB'),dtype=np.float64)[:,:,0]/255 + +def save(path, data): + Image.fromarray(np.uint8(np.clip(data*255+.5,0,255))).save(path) + +def analyze(root): + results=[] + for manifest in sorted(root.glob('[dl]*-?x.json')): + m=json.loads(manifest.read_text()); name=manifest.stem + a=read(root/f'rune-{name}.png'); b=read(root/f'coretext-{name}.png') + fg=m['fg']/255; bg=m['bg']/255 + ink_a=(a-bg)/(fg-bg); ink_b=(b-bg)/(fg-bg) + rows=[]; glyphs=[] + for ri,row in enumerate(m['rows']): + y0=int(row['top']); y1=min(a.shape[0],y0+int(42*m['scale'])) + mask=(np.abs(a[y0:y1]-bg)>.01)|(np.abs(b[y0:y1]-bg)>.01) + yy,xx=np.where(mask) + if not len(xx): continue + x0=max(0,int(xx.min())-6); x1=min(a.shape[1],int(xx.max())+7) + crop=(slice(y0,y1),slice(x0,x1)) + ssim=structural_similarity(a[crop],b[crop],data_range=1,gaussian_weights=True, + sigma=1.5,use_sample_covariance=False) + ia=ink_a[crop].sum(); ib=ink_b[crop].sum() + rows.append({'size':row['size'],'text':row['text'],'ssim':ssim, + 'weight_error_pct':100*(ia/ib-1),'ink_mae':float(np.abs(ink_a[crop]-ink_b[crop]).sum()/ib)}) + for gi,g in enumerate(row['glyphs']): + # Advance cells attribute overlapping side bearings consistently to each origin. + l=int(g['x']); r=int(row['glyphs'][gi+1]['x']) if gi+1<len(row['glyphs']) else int(g['x']+g['advance']+3) + ca=ink_a[y0:y1,l:r]; cb=ink_b[y0:y1,l:r] + if cb.sum()>.1: + glyphs.append({'row':ri,'glyph':g['id'],'x':g['x'],'coverage_rune':float(ca.sum()), + 'coverage_coretext':float(cb.sum()),'weight_error_pct':float(100*(ca.sum()/cb.sum()-1))}) + result={'name':name,'ssim':float(np.mean([r['ssim'] for r in rows])), + 'mean_abs_weight_error_pct':float(np.mean([abs(r['weight_error_pct']) for r in rows])), + 'signed_weight_error_pct':float(np.mean([r['weight_error_pct'] for r in rows])), + 'ink_mae':float(np.mean([r['ink_mae'] for r in rows])), 'rows':rows,'glyphs':glyphs} + results.append(result) + save(root/f'diff-{name}.png',np.abs(a-b)*4) + sheet=Image.new('RGB',(a.shape[1]*2,a.shape[0]+24),'#777777') + sheet.paste(Image.open(root/f'rune-{name}.png'),(0,24)) + sheet.paste(Image.open(root/f'coretext-{name}.png'),(a.shape[1],24)) + draw=ImageDraw.Draw(sheet); draw.text((8,5),'Rune',fill='white'); draw.text((a.shape[1]+8,5),'CoreText matched glyph positions',fill='white') + sheet.save(root/f'compare-{name}.png') + print(json.dumps({k:v for k,v in result.items() if k not in ('rows','glyphs')})) + for scale in (1,2): + path=root/f'phases-{scale}x.png' + if not path.exists(): continue + # White-on-black GPU sRGB output -> linear atlas coverage. + p=decode(read(path)).reshape(128,40,-1) + sums=p.sum(axis=(1,2)); mean=sums.mean() + shimmer={'scale':scale,'coverage_cv_pct':float(100*sums.std()/mean), + 'coverage_peak_to_peak_pct':float(100*np.ptp(sums)/mean), + 'frame_delta_rms_pct':float(100*np.sqrt(np.mean(np.diff(sums)**2))/mean)} + results.append({'motion':shimmer}); print(json.dumps(shimmer)) + for mode in ('light','dark'): + m=json.loads((root/f'{mode}-{scale}x.json').read_text()) + fg=m['fg']/255; bg=m['bg']/255 + gamma=m.get('gamma',.78+.22*fg) + pixels=encode(decode(bg)+(decode(fg)-decode(bg))*p**gamma) + ink=(pixels-bg)/(fg-bg); mass=ink.sum(axis=(1,2)) + brightness={'scale':scale,'mode':mode,'gamma':gamma, + 'brightness_cv_pct':float(100*mass.std()/mass.mean()), + 'frame_delta_rms_pct':float(100*np.sqrt(np.mean(np.diff(mass)**2))/mass.mean())} + results.append({'brightness':brightness}); print(json.dumps(brightness)) + strip=np.concatenate([p[i] for i in (0,8,16,24,32,40,48,56,64)],axis=0) + save(root/f'phase-strip-{scale}x.png',encode(strip)) + (root/'metrics.json').write_text(json.dumps(results,indent=2)+'\n') + +if __name__=='__main__': + parser=argparse.ArgumentParser(); parser.add_argument('directory',type=Path) + analyze(parser.parse_args().directory) diff --git a/app/vendor/rune/scripts/text-report.py b/app/vendor/rune/scripts/text-report.py new file mode 100644 index 0000000..c1bc300 --- /dev/null +++ b/app/vendor/rune/scripts/text-report.py @@ -0,0 +1,47 @@ +#!/usr/bin/env python3 +"""Publish compact comparison/phase strips and measurements; keep raw frames out of git.""" +import argparse +import json +from pathlib import Path +import numpy as np +from PIL import Image, ImageDraw + +p=argparse.ArgumentParser(); p.add_argument('runs',type=Path);p.add_argument('out',type=Path);a=p.parse_args() +a.out.mkdir(parents=True,exist_ok=True) +metrics={} +for font in ('inter','sf'): + before=a.runs/'before'/font;after=a.runs/'after'/font + # Keep only aggregates in the public report. text-quality.py regenerates the + # per-row and per-glyph data under the ignored run directory when needed. + metrics[font]={stage:[{k:v for k,v in result.items() if k not in ('rows','glyphs')} + for result in json.loads((a.runs/stage/font/'metrics.json').read_text())] + for stage in ('before','after')} + for scale in (1,2): + for mode in ('light','dark'): + name=f'{mode}-{scale}x';m=json.loads((after/f'{name}.json').read_text()) + width=400*scale;row_h=42*scale;gap=8 + sheet=Image.new('RGB',(width*3+gap*2,28+5*row_h),'#808080') + draw=ImageDraw.Draw(sheet) + for col,(directory,stem,title) in enumerate([(before,'rune','Before'),(after,'rune','After'),(after,'coretext','CoreText')]): + draw.text((col*(width+gap)+8,8),title,fill='white') + image=Image.open(directory/f'{stem}-{name}.png').convert('RGB') + for ri,row in enumerate(m['rows'][::5]): + y=int(row['top']);sheet.paste(image.crop((0,y,width,y+row_h)),(col*(width+gap),28+ri*row_h)) + sheet.save(a.out/f'{font}-{name}.png') + ref=np.array(Image.open(after/f'coretext-{name}.png').convert('RGB'),dtype=np.int16) + diffs=Image.new('RGB',(width*2+gap,28+5*row_h),'#808080');d=ImageDraw.Draw(diffs) + for col,directory in enumerate((before,after)): + d.text((col*(width+gap)+8,8),('Before' if col==0 else 'After')+' absolute error x4',fill='white') + image=np.array(Image.open(directory/f'rune-{name}.png').convert('RGB'),dtype=np.int16) + diff=Image.fromarray(np.uint8(np.clip(abs(image-ref)*4,0,255))) + for ri,row in enumerate(m['rows'][::5]): + y=int(row['top']);diffs.paste(diff.crop((0,y,width,y+row_h)),(col*(width+gap),28+ri*row_h)) + diffs.save(a.out/f'{font}-diff-{name}.png') + strip=Image.new('RGB',(648,28+40*9),'#808080');draw=ImageDraw.Draw(strip) + for col,directory in enumerate((before,after)): + draw.text((col*328+8,8),'Before' if col==0 else 'After',fill='white') + image=Image.open(directory/f'phases-{scale}x.png').convert('RGB') + for row,frame in enumerate((0,8,16,24,32,40,48,56,64)): + strip.paste(image.crop((0,frame*40,320,(frame+1)*40)),(col*328,28+row*40)) + strip.save(a.out/f'{font}-phases-{scale}x.png') +(a.out/'metrics.json').write_text(json.dumps(metrics,indent=2)+'\n') diff --git a/app/vendor/rune/scripts/trace-quality.py b/app/vendor/rune/scripts/trace-quality.py new file mode 100644 index 0000000..ce88822 --- /dev/null +++ b/app/vendor/rune/scripts/trace-quality.py @@ -0,0 +1,27 @@ +#!/usr/bin/env python3 +"""Research-15 metrics from Rune traces. Virtual cadence is not measured display cadence.""" +import json +import statistics +import sys + +for path in sys.argv[1:]: + rows = [json.loads(s) for s in open(path)] + header = rows[0] + frames = [r for r in rows if 'quality' in r] + period = 1000 / header['hz'] + intervals = [b['t'] - a['t'] for a, b in zip(frames, frames[1:])] + duration = frames[-1]['t'] - frames[0]['t'] + q = [r['quality'] for r in frames] + cpu = [r['quality']['cpu_ms'] for r in frames[1:]] + errors = sorted(r['position_error_px'] for r in q) + print(json.dumps({ + 'trace': path, 'clock': header['clock'], + 'position_frame_max_p99_px': errors[round((len(errors) - 1) * .99)], + 'position_max_px': max(errors), + 'retarget_lanes': sum(r['retarget_lanes'] for r in q), + 'retarget_velocity_max_pt_s': max(r['velocity_error_pt_s'] for r in q), + 'virtual_hitch_ms_s': sum(max(0, t - period) for t in intervals) / duration * 1000 if duration else 0, + 'virtual_cadence_sigma_periods': statistics.pstdev(t / period - 1 for t in intervals) if intervals else 0, + 'cpu_budget_excess_ms_s': sum(max(0, t - period) for t in cpu) / duration * 1000 if duration else 0, + 'animating_at_end': q[-1]['animating'], + }, indent=2)) diff --git a/app/vendor/rune/scripts/vendor-accesskit-macos.sh b/app/vendor/rune/scripts/vendor-accesskit-macos.sh new file mode 100644 index 0000000..82c7ec4 --- /dev/null +++ b/app/vendor/rune/scripts/vendor-accesskit-macos.sh @@ -0,0 +1,24 @@ +#!/usr/bin/env bash +# Re-makes vendor/accesskit_macos: the accesskit_macos crate exactly as published on crates.io at +# <version>, without its integration tests, plus vendor/accesskit_macos.patch (headings as AppKit's +# AXHeading with their level as the value, which the published adapter reports as a "Heading" role +# VoiceOver doesn't know, so VoiceOver's rotor and VO-Command-H found no heading; and accessibility +# children, focus and hit test reading the adapter's state only on the main thread, since AppKit +# calls them from a background thread while the process queries itself and the main thread may hold +# that borrow, which raced or aborted). Run it when +# AccessKit is bumped, then build: a patch that no longer applies fails here, and the change goes +# back in by hand. If upstream AccessKit takes the change, delete vendor/accesskit_macos and its +# `[patch.crates-io]` entry instead. +# Usage: scripts/vendor-accesskit-macos.sh <version> e.g. scripts/vendor-accesskit-macos.sh 0.27.2 +set -euo pipefail +cd "$(git rev-parse --show-toplevel)" +version="${1:?usage: scripts/vendor-accesskit-macos.sh <version>}" +tmp="$(mktemp -d)" +trap 'rm -rf "$tmp"' EXIT +curl -fsSL "https://static.crates.io/crates/accesskit_macos/accesskit_macos-$version.crate" -o "$tmp/crate.tar.gz" +tar -xzf "$tmp/crate.tar.gz" -C "$tmp" +rm -rf vendor/accesskit_macos +mv "$tmp/accesskit_macos-$version" vendor/accesskit_macos +rm -rf vendor/accesskit_macos/tests +git apply --directory=vendor/accesskit_macos vendor/accesskit_macos.patch +echo "vendor/accesskit_macos: accesskit_macos $version + vendor/accesskit_macos.patch" diff --git a/app/vendor/rune/scripts/vendor-accesskit-windows.sh b/app/vendor/rune/scripts/vendor-accesskit-windows.sh new file mode 100644 index 0000000..6a09007 --- /dev/null +++ b/app/vendor/rune/scripts/vendor-accesskit-windows.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Re-makes vendor/accesskit_windows: the accesskit_windows crate exactly as published on crates.io at +# <version>, plus vendor/accesskit_windows.patch (UI Automation's HeadingLevel, LandmarkType and +# LocalizedLandmarkType for headings and landmarks, which the published adapter doesn't report, so +# Narrator's and NVDA's heading and landmark navigation found none). Run it when AccessKit is +# bumped, then build: a patch that no longer applies fails here, and the change goes back in by +# hand. If upstream AccessKit takes the change, delete vendor/accesskit_windows and its +# `[patch.crates-io]` entry instead. +# Usage: scripts/vendor-accesskit-windows.sh <version> e.g. scripts/vendor-accesskit-windows.sh 0.35.2 +set -euo pipefail +cd "$(git rev-parse --show-toplevel)" +version="${1:?usage: scripts/vendor-accesskit-windows.sh <version>}" +tmp="$(mktemp -d)" +trap 'rm -rf "$tmp"' EXIT +curl -fsSL "https://static.crates.io/crates/accesskit_windows/accesskit_windows-$version.crate" -o "$tmp/crate.tar.gz" +tar -xzf "$tmp/crate.tar.gz" -C "$tmp" +rm -rf vendor/accesskit_windows +mv "$tmp/accesskit_windows-$version" vendor/accesskit_windows +git apply --directory=vendor/accesskit_windows vendor/accesskit_windows.patch +echo "vendor/accesskit_windows: accesskit_windows $version + vendor/accesskit_windows.patch" \ No newline at end of file diff --git a/app/vendor/rune/scripts/vendor-parley-engine.sh b/app/vendor/rune/scripts/vendor-parley-engine.sh new file mode 100644 index 0000000..38e155b --- /dev/null +++ b/app/vendor/rune/scripts/vendor-parley-engine.sh @@ -0,0 +1,30 @@ +#!/usr/bin/env bash +# Re-makes vendor/parley_engine: the parley_engine crate exactly as published on crates.io at +# <version>, plus vendor/parley_engine.patch (UAX #9 rule L1 for a paragraph's trailing +# whitespace, isolate initiators and PDIs, which parley_engine leaves at their resolved levels: +# with it, Unicode's BidiTest.txt passes 770,241 of 770,241, without it 644,283), and three caches +# of work shaping redid from the same inputs: `Analyzer` keeps the line and word segmenters it made +# (`analysis.rs` `Segmenters`; making one loads the ICU dictionaries), `Shaper` keeps each run's +# font metrics per font instance and size (`run_metrics_cache`), and `FontMetrics::from_font_instance` +# keeps a style's per thread (64 entries). Two hooks for a host without ICU's dictionaries or the +# fonts a script needs (Rune's web build): `dictionary::set_dictionary_segmenter` (the words, and +# Thai, Lao, Khmer and Burmese line breaks, of runs that need a dictionary; with the +# `line-dictionaries` feature, the words alone, the line segmenter keeping its Thai, Lao, Khmer and +# Burmese dictionaries: Rune's Windows build) and +# `platform::set_platform_face` (a face whose runs the host measures and draws, not HarfRust; +# `push_run` takes glyph infos and positions instead of a `GlyphBuffer` for it). Run it when +# parley is bumped, then build: a patch that no longer applies fails here, and the change goes +# back in by hand. If upstream parley takes the change, delete vendor/parley_engine and its +# `[patch.crates-io]` entry instead. +# Usage: scripts/vendor-parley-engine.sh <version> e.g. scripts/vendor-parley-engine.sh 0.12.0 +set -euo pipefail +cd "$(git rev-parse --show-toplevel)" +version="${1:?usage: scripts/vendor-parley-engine.sh <version>}" +tmp="$(mktemp -d)" +trap 'rm -rf "$tmp"' EXIT +curl -fsSL "https://static.crates.io/crates/parley_engine/parley_engine-$version.crate" -o "$tmp/crate.tar.gz" +tar -xzf "$tmp/crate.tar.gz" -C "$tmp" +rm -rf vendor/parley_engine +mv "$tmp/parley_engine-$version" vendor/parley_engine +git apply --directory=vendor/parley_engine vendor/parley_engine.patch +echo "vendor/parley_engine: parley_engine $version + vendor/parley_engine.patch" \ No newline at end of file diff --git a/app/vendor/rune/scripts/vendor-sctk-adwaita.sh b/app/vendor/rune/scripts/vendor-sctk-adwaita.sh new file mode 100644 index 0000000..279942e --- /dev/null +++ b/app/vendor/rune/scripts/vendor-sctk-adwaita.sh @@ -0,0 +1,21 @@ +#!/usr/bin/env bash +# Re-makes vendor/sctk-adwaita: the sctk-adwaita crate exactly as published on crates.io at +# <version>, plus vendor/sctk-adwaita.patch (the visible one-point border follows the window's +# rounded bottom corners, as the headerbar above them already rounds the top ones, instead of +# drawing a square L there; and `AdwaitaFrame::content_corner_radius` says what radius the content +# leaves its own bottom corners to, for the app to clear outside it). Run it when sctk-adwaita is +# bumped, then build: a patch that no longer applies fails here, and the change goes back in by +# hand. If upstream sctk-adwaita takes the change, delete vendor/sctk-adwaita and its +# `[patch.crates-io]` entry instead. +# Usage: scripts/vendor-sctk-adwaita.sh <version> e.g. scripts/vendor-sctk-adwaita.sh 0.10.1 +set -euo pipefail +cd "$(git rev-parse --show-toplevel)" +version="${1:?usage: scripts/vendor-sctk-adwaita.sh <version>}" +tmp="$(mktemp -d)" +trap 'rm -rf "$tmp"' EXIT +curl -fsSL "https://static.crates.io/crates/sctk-adwaita/sctk-adwaita-$version.crate" -o "$tmp/crate.tar.gz" +tar -xzf "$tmp/crate.tar.gz" -C "$tmp" +rm -rf vendor/sctk-adwaita +mv "$tmp/sctk-adwaita-$version" vendor/sctk-adwaita +git apply --directory=vendor/sctk-adwaita vendor/sctk-adwaita.patch +echo "vendor/sctk-adwaita: sctk-adwaita $version + vendor/sctk-adwaita.patch" diff --git a/app/vendor/rune/scripts/vendor-tiny-skia-path.sh b/app/vendor/rune/scripts/vendor-tiny-skia-path.sh new file mode 100644 index 0000000..efbaa49 --- /dev/null +++ b/app/vendor/rune/scripts/vendor-tiny-skia-path.sh @@ -0,0 +1,27 @@ +#!/usr/bin/env bash +# Re-makes vendor/tiny-skia-path: the tiny-skia-path crate exactly as published on crates.io at +# <version>, plus vendor/tiny-skia-path.patch, which puts back how Skia itself strokes and splits +# conics where tiny-skia's port has drifted (Rune's icons are covered as Chromium's Skia covers +# them: crates/rune-text/src/icon/area.rs): +# - a conic becomes quads a quarter of a *device* pixel from it (the stroker passes its +# resolution scale), and one quad when that's close enough, not at least two; +# - the stroker keeps each tangent as a vector, measures its distance to the tangent line as +# Skia's `pt_to_tangent_line` does, and, out of recursion, emits a line rather than giving up; +# - `set_point_length` multiplies in double and rounds once, as `SkPoint::setLength` does; +# - `PathBuilder::conic_to`, `set_conic_tolerance` and `AutoConicToQuads` are public. +# - `set_keep_conics` retains weighted conic segments for SVG arcs; the stroker fits the two +# contours against the conic itself instead of fitting against quadratic approximations. +# Run it when tiny-skia-path is bumped, then build: a patch that no longer applies fails here, +# and the changes go back in by hand. +# Usage: scripts/vendor-tiny-skia-path.sh <version> e.g. scripts/vendor-tiny-skia-path.sh 0.11.4 +set -euo pipefail +cd "$(git rev-parse --show-toplevel)" +version="${1:?usage: scripts/vendor-tiny-skia-path.sh <version>}" +tmp="$(mktemp -d)" +trap 'rm -rf "$tmp"' EXIT +curl -fsSL "https://static.crates.io/crates/tiny-skia-path/tiny-skia-path-$version.crate" -o "$tmp/crate.tar.gz" +tar -xzf "$tmp/crate.tar.gz" -C "$tmp" +rm -rf vendor/tiny-skia-path +mv "$tmp/tiny-skia-path-$version" vendor/tiny-skia-path +git apply --directory=vendor/tiny-skia-path vendor/tiny-skia-path.patch +echo "vendor/tiny-skia-path: tiny-skia-path $version + vendor/tiny-skia-path.patch" diff --git a/app/vendor/rune/scripts/vendor-wgpu-hal.sh b/app/vendor/rune/scripts/vendor-wgpu-hal.sh new file mode 100644 index 0000000..94f85db --- /dev/null +++ b/app/vendor/rune/scripts/vendor-wgpu-hal.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Re-makes vendor/wgpu-hal: the wgpu-hal crate exactly as published on crates.io at <version>, plus +# vendor/wgpu-hal.patch (`dx12::Instance::expose_adapter`, which `gpu/pick.rs` uses to hand wgpu the one +# adapter it picked through DXGI; FXC loaded on first use; `Surface::set_present_rects`, partial presents; +# Windows system DLLs loaded with `LOAD_LIBRARY_SEARCH_SYSTEM32`; a removed device's work stays pending, +# never finished; GPU-written drain markers on software adapters so releasing a removed WARP device waits for queued command lists). Run it when wgpu is bumped, then build: a patch +# that no longer applies fails here, and the function goes back in by hand. If upstream wgpu takes +# the function, delete vendor/ and the `[patch.crates-io]` entries instead. +# Usage: scripts/vendor-wgpu-hal.sh <version> e.g. scripts/vendor-wgpu-hal.sh 30.0.1 +set -euo pipefail +cd "$(git rev-parse --show-toplevel)" +version="${1:?usage: scripts/vendor-wgpu-hal.sh <version>}" +tmp="$(mktemp -d)" +trap 'rm -rf "$tmp"' EXIT +curl -fsSL "https://static.crates.io/crates/wgpu-hal/wgpu-hal-$version.crate" -o "$tmp/crate.tar.gz" +tar -xzf "$tmp/crate.tar.gz" -C "$tmp" +rm -rf vendor/wgpu-hal +mv "$tmp/wgpu-hal-$version" vendor/wgpu-hal +git apply --directory=vendor/wgpu-hal vendor/wgpu-hal.patch +echo "vendor/wgpu-hal: wgpu-hal $version + vendor/wgpu-hal.patch" diff --git a/app/vendor/rune/scripts/vendor-winit.sh b/app/vendor/rune/scripts/vendor-winit.sh new file mode 100644 index 0000000..5f72804 --- /dev/null +++ b/app/vendor/rune/scripts/vendor-winit.sh @@ -0,0 +1,26 @@ +#!/usr/bin/env bash +# Re-makes vendor/winit: the winit crate exactly as published on crates.io at <version>, plus +# vendor/winit.patch (Windows: a new window isn't added to the taskbar list it is already on, which +# cost every window CoInitializeEx and a TaskbarList COM object, about 7,800 µs and nine shell +# DLLs on its UI thread before its first frame; and a window given a position is made there, at +# its display's scale, not moved there and resized; and a new window's system menu, whose Close +# is already enabled, isn't copied for the window just to enable it again; and a window is made +# with the minimize and maximize boxes it asks for, not given them by a second style change; and winit's own +# helper window is cloaked, so screen readers and window pickers don't meet it; and Windows system DLLs +# load via `LoadLibraryExA` with `LOAD_LIBRARY_SEARCH_SYSTEM32`; and on macOS the input method reads the app's text around its selection, to convert it again, and its marked text's clauses reach the app, beside `Ime::Preedit`, through `platform::macos::{set_ime_text, take_ime_clauses, take_ime_replacement}`; and +# `platform::wayland::WindowExtWayland::content_corner_radius` says what radius a Wayland client-side frame +# leaves the window's content's bottom corners at, 0 when it draws none or draws it square). Run it when winit is bumped, then build: a patch +# that no longer applies fails here, and the change goes back in by hand. If upstream winit takes +# the change, delete vendor/winit and its `[patch.crates-io]` entry instead. +# Usage: scripts/vendor-winit.sh <version> e.g. scripts/vendor-winit.sh 0.30.13 +set -euo pipefail +cd "$(git rev-parse --show-toplevel)" +version="${1:?usage: scripts/vendor-winit.sh <version>}" +tmp="$(mktemp -d)" +trap 'rm -rf "$tmp"' EXIT +curl -fsSL "https://static.crates.io/crates/winit/winit-$version.crate" -o "$tmp/crate.tar.gz" +tar -xzf "$tmp/crate.tar.gz" -C "$tmp" +rm -rf vendor/winit +mv "$tmp/winit-$version" vendor/winit +git apply --directory=vendor/winit vendor/winit.patch +echo "vendor/winit: winit $version + vendor/winit.patch" diff --git a/app/vendor/rune/scripts/web-build.sh b/app/vendor/rune/scripts/web-build.sh new file mode 100644 index 0000000..ba9a6c0 --- /dev/null +++ b/app/vendor/rune/scripts/web-build.sh @@ -0,0 +1,243 @@ +#!/usr/bin/env bash +# Run from the app's Cargo workspace. Produces a static, HTTPS-hostable folder. +set -euo pipefail +usage="usage: web-build.sh PACKAGE [--example NAME] [--out DIR] [--opt] [--dev] [--watch] [--no-html] [--names]" +package=${1:?$usage} +shift +example= +out=target/web +opt=false +dev=false +watch=false +html=true +names=false +while (($#)); do + case "$1" in + --example) example=${2:?--example needs a name}; shift 2 ;; + --out) out=${2:?--out needs a directory}; shift 2 ;; + --opt) opt=true; shift ;; + --dev) dev=true; shift ;; + --watch) watch=true; shift ;; + --no-html) html=false; shift ;; + --names) names=true; shift ;; + -h|--help) echo "$usage"; exit 0 ;; + *) echo "unknown option: $1" >&2; echo "$usage" >&2; exit 2 ;; + esac +done +# Build with the toolchain's own cargo rather than a `cargo` wrapper on PATH, which may run +# the build on another machine and leave no wasm here. Set CARGO to choose a cargo binary. +cargo=${CARGO:-$(rustup which cargo 2>/dev/null || command -v cargo)} +# Calling the toolchain's cargo directly skips rustup's proxy, so pin the toolchain for the +# rustc it runs too: build scripts compile outside the repo, where rust-toolchain.toml can't reach. +if [[ -z ${RUSTUP_TOOLCHAIN:-} ]] && toolchain=$(rustup show active-toolchain 2>/dev/null); then + export RUSTUP_TOOLCHAIN=${toolchain%% *} +fi +# C and C++ dependencies (rune-luau's Luau) build for the web with WASI SDK's clang against WASI +# libc, using WebAssembly exception handling. Set WASI_SDK_PATH to an unpacked WASI SDK 33 or +# newer; rune-luau's build script links the SDK's libc and C++ runtime from it. +if [[ -n ${WASI_SDK_PATH:-} ]]; then + exe= + [[ -f $WASI_SDK_PATH/bin/clang.exe ]] && exe=.exe + export CC_wasm32_unknown_unknown="$WASI_SDK_PATH/bin/clang$exe" \ + CXX_wasm32_unknown_unknown="$WASI_SDK_PATH/bin/clang++$exe" \ + AR_wasm32_unknown_unknown="$WASI_SDK_PATH/bin/llvm-ar$exe" \ + CXXSTDLIB_wasm32_unknown_unknown=c++ \ + CFLAGS_wasm32_unknown_unknown=--target=wasm32-wasip1 \ + LUAU_CXXFLAGS="--target=wasm32-wasip1 -fexceptions -fwasm-exceptions -mllvm -wasm-use-legacy-eh=false" +fi +meta=$("$cargo" metadata --format-version 1 --no-deps) +selection=$(python3 -c ' +import json,sys +m=json.load(sys.stdin); p=next((p for p in m["packages"] if p["name"]==sys.argv[1]),None) +if p is None: sys.exit("package is not a workspace member") +targets=[t for t in p["targets"] if "example" in t["kind"] and t["name"]==sys.argv[2]] if sys.argv[2] else [t for t in p["targets"] if "cdylib" in t["crate_types"]] +if not targets and not sys.argv[2]: targets=[t for t in p["targets"] if "bin" in t["kind"]] +if len(targets)!=1: sys.exit("select one cdylib, binary, or --example target") +t=targets[0] +print(m["workspace_root"]); print(m["target_directory"]); print(t["name"]) +print("example" if sys.argv[2] else "lib" if "cdylib" in t["crate_types"] else "bin") +' "$package" "$example" <<< "$meta") +root=$(sed -n '1p' <<< "$selection") +target=$(sed -n '2p' <<< "$selection") +name=$(sed -n '3p' <<< "$selection") +kind=$(sed -n '4p' <<< "$selection") +if $dev; then + # The debug profile without debug info, with dependencies at opt-level 1: an edit rebuilds + # only this package, unoptimized, while Rune and the rest stay fast at run time. + profile=web-dev + build=(--profile web-dev --config 'profile.web-dev.inherits="dev"' --config 'profile.web-dev.debug=0' + --config 'profile.web-dev.package."*".opt-level=1') + # `"*"` covers only non-members, so name the workspace members this package depends on. + while IFS= read -r member; do + [[ -n $member ]] && build+=(--config "profile.web-dev.package.\"$member\".opt-level=1") + done < <(python3 -c ' +import json,sys +m=json.load(sys.stdin); by={p["name"]:p for p in m["packages"]} +todo=[sys.argv[1]]; seen=set() +while todo: + for d in by[todo.pop()]["dependencies"]: + if d.get("path") and d["name"] in by and d["name"] not in seen and d["kind"] is None: + seen.add(d["name"]); todo.append(d["name"]) +print("\n".join(sorted(seen - {sys.argv[1]}))) +' "$package" <<< "$meta") + opt=false +else + profile=release + build=(--release) + # Defaults for size; set any of these to override, e.g. CARGO_PROFILE_RELEASE_LTO=fat for a smaller, slower build. + export CARGO_PROFILE_RELEASE_OPT_LEVEL=${CARGO_PROFILE_RELEASE_OPT_LEVEL:-s} \ + CARGO_PROFILE_RELEASE_LTO=${CARGO_PROFILE_RELEASE_LTO:-thin} CARGO_PROFILE_RELEASE_CODEGEN_UNITS=1 \ + CARGO_PROFILE_RELEASE_DEBUG=0 CARGO_PROFILE_RELEASE_STRIP=debuginfo + # Panic messages carry source paths; keep the builder's home folder out of a wasm meant for the public. + # rustc applies the last matching prefix, so the narrower cargo home comes after the home folder. + export RUSTFLAGS="${RUSTFLAGS:-} --remap-path-prefix=$HOME=/home --remap-path-prefix=${CARGO_HOME:-$HOME/.cargo}=/cargo" +fi +args=(--lib) +artifact="$target/wasm32-unknown-unknown/$profile/${name//-/_}.wasm" +if [[ $kind == example ]]; then args=(--example "$name"); artifact="$target/wasm32-unknown-unknown/$profile/examples/$name.wasm"; fi +if [[ $kind == bin ]]; then args=(--bin "$name"); artifact="$target/wasm32-unknown-unknown/$profile/$name.wasm"; fi +version=$(python3 -c 'import sys,tomllib; print(next(p["version"] for p in tomllib.load(open(sys.argv[1],"rb"))["package"] if p["name"]=="wasm-bindgen"))' "$root/Cargo.lock") +if ! command -v wasm-bindgen >/dev/null || [[ $(wasm-bindgen --version) != "wasm-bindgen $version" ]]; then + echo "Install the matching CLI: cargo install wasm-bindgen-cli --version $version --locked" >&2 + exit 2 +fi +marker='<!-- generated by rune web-build.sh: delete this line to keep your own edits -->' + +write_html() { + local reload='' import="import init from './app.js';" load="await init();" + if $watch; then + import= + reload='<script src="reload.js"></script>' + load="const v = Date.now(); const { default: init } = await import('./app.js?v=' + v); await init({ module_or_path: './app_bg.wasm?v=' + v });" + fi + cat > "$out/index.html" <<HTML +<!doctype html> +$marker +<html lang="en"> +<meta charset="utf-8"> +<meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no,viewport-fit=cover"> +<meta name="color-scheme" content="light dark"> +<title>Rune</title> +<style>html,body{margin:0;width:100%;height:100%;overflow:hidden;overscroll-behavior:none;touch-action:none}#status{font:16px system-ui;padding:24px}</style> +<div id="status">Loading…</div> +$reload +<script type="module"> +$import +try { + if (!navigator.gpu) throw new Error('WebGPU requires a supported browser and HTTPS.'); + $load + document.querySelector('#status').remove(); +} catch (error) { + document.querySelector('#status').textContent = String(error); + console.error(error); +} +</script> +</html> +HTML +} + +build_once() { + local start=$SECONDS + "$cargo" build -p "$package" --target wasm32-unknown-unknown "${build[@]}" "${args[@]}" || return 1 + if [[ ! -f $artifact ]]; then + echo "cargo finished but $artifact is missing. If cargo ran on another machine, set CARGO to a local cargo binary." >&2 + return 1 + fi + # Build into a staging folder beside the output, then rename each file into place, so a + # page loading mid-build never gets app.js and app_bg.wasm from different builds. + local next="$out/.next" + rm -rf "$next" + mkdir -p "$next" + # A release build drops the function-name section (over 40% of an unoptimized wasm); a `--dev` + # build, or `--names` for profiling, keeps it so panics and profiles name their functions. + local bindgen=(--target web --out-dir "$next" --out-name app) + $dev || $names || bindgen+=(--remove-name-section) + wasm-bindgen "${bindgen[@]}" "$artifact" || return 1 + if $opt; then + local keep=() + $names && keep=(-g) + wasm-opt -Oz ${keep[@]+"${keep[@]}"} --enable-bulk-memory --enable-nontrapping-float-to-int --enable-sign-ext --enable-reference-types --enable-exception-handling \ + "$next/app_bg.wasm" -o "$next/app_bg.opt.wasm" || return 1 + mv "$next/app_bg.opt.wasm" "$next/app_bg.wasm" + fi + # Rune's default fonts embed Inter cut to Latin, Greek and Cyrillic text and fetch the full faces from beside + # app.js once the first frame is up: copy those of the Rune this build embedded the cut from. + local cut + cut=$(tr ' ' '\n' < "${artifact%.wasm}.d" 2>/dev/null | grep -m1 '/assets/web/first/Inter-Regular\.ttf$' || true) + if [[ -n $cut ]]; then cp "${cut%/first/*}"/Inter-*.ttf "$next/"; fi + local entry + for entry in "$next"/*; do + if [[ -d $entry ]]; then + rm -rf "${out:?}/$(basename "$entry")" + fi + mv -f "$entry" "$out/" + done + rmdir "$next" + if $html; then + if [[ ! -e $out/index.html ]] || grep -qF "$marker" "$out/index.html"; then + write_html + else + echo "Kept $out/index.html: it has no generated-by marker." + fi + fi + if $watch; then + cat > "$out/reload.js" <<'JS' +// Reloads the page when web-build.sh --watch finishes a build. +(() => { + const url = new URL('.stamp', document.currentScript?.src ?? location.href); + let last; + setInterval(async () => { + try { + const stamp = await (await fetch(url, { cache: 'no-store' })).text(); + if (last !== undefined && stamp !== last) location.reload(); + last = stamp; + } catch {} + }, 500); +})(); +JS + echo "$(date +%s)-$RANDOM" > "$out/.stamp" + else + rm -f "$out/reload.js" "$out/.stamp" + fi + $dev || python3 -c 'import gzip,pathlib,sys; p=pathlib.Path(sys.argv[1]); b=p.read_bytes(); print(f"{p}: {len(b):,} bytes raw, {len(gzip.compress(b,mtime=0)):,} bytes gzip")' "$out/app_bg.wasm" + echo "Built $profile in $((SECONDS - start)) s. Static folder: $out" +} + +if ! $watch; then + build_once + exit +fi +echo "Watching. Serve the folder with: python3 -m http.server 8000 -d $out (then open http://localhost:8000)" +# Poll the workspace members' files, skipping build output, and return once one changed after +# the build started (so an edit made during a build is not lost) or one appeared or went away. +wait_for_change() { + META=$meta python3 - "$out" "$1" <<'PY' +import json, os, sys, time +out, since = os.path.realpath(sys.argv[1]), float(sys.argv[2]) +m = json.loads(os.environ["META"]) +root = m["workspace_root"] +dirs = {os.path.dirname(p["manifest_path"]) for p in m["packages"]} +def scan(): + seen = {} + paths = [os.path.join(root, "Cargo.toml"), os.path.join(root, "Cargo.lock")] + for top in dirs: + for here, subdirs, files in os.walk(top): + subdirs[:] = [d for d in subdirs if d not in ("target", "node_modules") and not d.startswith(".") + and os.path.realpath(os.path.join(here, d)) != out] + paths += [os.path.join(here, f) for f in files] + for path in paths: + try: seen[path] = os.stat(path).st_mtime + except OSError: pass + return seen +first = scan() +while True: + now = scan() + if now.keys() != first.keys() or max(now.values(), default=0) >= since: break + time.sleep(0.3) +PY +} +while true; do + started=$(python3 -c 'import time; print(time.time())') + build_once || echo "Build failed; waiting for the next change." >&2 + wait_for_change "$started" +done diff --git a/app/vendor/rune/scripts/web-clock-smoke.mjs b/app/vendor/rune/scripts/web-clock-smoke.mjs new file mode 100644 index 0000000..f7dccc7 --- /dev/null +++ b/app/vendor/rune/scripts/web-clock-smoke.mjs @@ -0,0 +1,43 @@ +// A page's fake clock drives Rune's frames, even one installed after the app started +// (Playwright's `clock.install`): with the clock paused, a touch fling's momentum waits for +// `runFor` instead of finishing in real time. Chromium only (touch comes from CDP). +import assert from 'node:assert/strict'; + +export async function clockSmoke(browser, url) { + // Its own context: Playwright's clock belongs to a context, and would pause the other pages. + const context = await browser.newContext({ viewport: { width: 390, height: 760 }, deviceScaleFactor: 3, hasTouch: true, isMobile: true }); + const page = await context.newPage(); + try { + await page.addInitScript(() => { + window.__submits = 0; + const submit = GPUQueue.prototype.submit; + GPUQueue.prototype.submit = function (...args) { window.__submits++; return submit.apply(this, args); }; + }); + await page.goto(url); + await page.waitForFunction(() => window.__submits > 0, { timeout: 30000 }); + await page.waitForTimeout(1000); + await page.clock.install(); + await page.clock.pauseAt(await page.evaluate(() => Date.now() + 1000)); + const cdp = await context.newCDPSession(page); + const touch = (type, y) => cdp.send('Input.dispatchTouchEvent', { type, touchPoints: type === 'touchEnd' ? [] : [{ x: 180, y }] }); + await touch('touchStart', 180); + for (let i = 1; i <= 10; i++) { + await touch('touchMove', 180 + 30 * i); + await page.clock.runFor(16); + } + await touch('touchEnd', 480); + await page.clock.runFor(16); + // Two seconds of real time with the page clock paused: the fling must not move on. + await page.waitForTimeout(2000); + await page.clock.runFor(16); + const a = await page.screenshot(); + await page.clock.runFor(32); + assert.ok(!a.equals(await page.screenshot()), 'momentum follows the paused page clock, not real time'); + await page.clock.runFor(5000); + const settled = await page.screenshot(); + await page.clock.runFor(100); + assert.ok(settled.equals(await page.screenshot()), 'momentum settles as the page clock runs'); + } finally { + await context.close(); + } +} diff --git a/app/vendor/rune/scripts/web-fonts.sh b/app/vendor/rune/scripts/web-fonts.sh new file mode 100644 index 0000000..60d7d5f --- /dev/null +++ b/app/vendor/rune/scripts/web-fonts.sh @@ -0,0 +1,23 @@ +#!/usr/bin/env bash +# Regenerate crates/rune/assets/web/: the bundled Inter faces without TrueType hinting or glyph +# names, for the web, whose rasterizer reads neither. Every glyph, mapping, layout table and name +# stays. IBM Plex Mono ships as is: its licence reserves the name "Plex" for unmodified fonts. +# web/first/ holds the same faces cut to Latin, Greek and Cyrillic text, which a web app embeds +# for its first frame; it fetches the full faces after that. Needs HarfBuzz's hb-subset (brew +# install harfbuzz). Check with `cargo test -p rune --lib default_fonts full_faces`. +set -euo pipefail +cd "$(dirname "$0")/../crates/rune/assets" +mkdir -p web/first +# Basic Latin, Latin-1, Latin Extended-A, Romanian's comma-below letters, spacing accents, +# Greek, Cyrillic with Ukrainian's Ghe with upturn, general punctuation, the euro and trade mark +# signs, arrows and the Mac's key symbols. +first='U+0020-007E,U+00A0-017F,U+0192,U+0218-021B,U+02C6-02DD,U+0370-03FF,U+0400-045F,U+0490-0491,U+2000-206F,U+20AC,U+2122,U+2190-2193,U+21A9,U+21E7,U+2212,U+2303,U+2318,U+2325,U+232B,U+238B,U+23CE,U+FFFD' +for font in Inter-Regular Inter-Medium Inter-SemiBold; do + hb-subset "$font.ttf" --unicodes='*' --glyphs='*' --retain-gids --notdef-outline \ + --layout-features='*' --layout-scripts='*' --name-IDs='*' --name-languages='*' \ + --no-prune-unicode-ranges --no-hinting -o "web/$font.ttf" + hb-subset "$font.ttf" --unicodes="$first" --notdef-outline \ + --layout-features='*' --layout-scripts='*' --name-IDs='*' --name-languages='*' \ + --no-hinting -o "web/first/$font.ttf" + echo "web/$font.ttf: $(wc -c < "$font.ttf" | tr -d ' ') -> $(wc -c < "web/$font.ttf" | tr -d ' ') bytes, first $(wc -c < "web/first/$font.ttf" | tr -d ' ')" +done diff --git a/app/vendor/rune/scripts/web-input-smoke.mjs b/app/vendor/rune/scripts/web-input-smoke.mjs new file mode 100644 index 0000000..ece169f --- /dev/null +++ b/app/vendor/rune/scripts/web-input-smoke.mjs @@ -0,0 +1,126 @@ +import assert from 'node:assert/strict'; + +export async function inputSmoke(page, url) { + await page.goto(`${url}/?input-proof`); + await page.waitForFunction(() => window.__inputProof); + assert.equal(await page.title(), 'Input proof'); + assert.equal(await page.locator('pre').count(), 0, 'window requests must not replace the app'); + const snapshot = () => page.evaluate(() => window.__inputProof); + // The fixture reports from poll, before that frame drains queued keys. Wait for the + // host's next presented frame rather than guessing how long shader startup takes. + const settle = () => page.evaluate(() => new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve)))); + await page.touchscreen.tap(100, 36); + assert.equal(await page.evaluate(() => document.activeElement.tagName), 'TEXTAREA'); + await page.keyboard.insertText('hello '); + await settle(); + assert.equal((await snapshot()).plain, 'hello '); + + // A touch inside the same editor must never pass focus through the canvas/body. + await page.evaluate(() => { + window.__editorBlurs = 0; + document.querySelector('textarea').addEventListener('blur', () => window.__editorBlurs++); + }); + await page.touchscreen.tap(100, 36); + assert.equal(await page.evaluate(() => window.__editorBlurs), 0); + + // Gboard reopens an existing word: include its unchanged prefix in the preedit range. + await page.locator('textarea').evaluate(field => { + field.dispatchEvent(new CompositionEvent('compositionstart')); + field.value = 'hello'; field.setSelectionRange(5, 5); + field.dispatchEvent(new CompositionEvent('compositionupdate', { data: 'hello' })); + field.dispatchEvent(new InputEvent('input', { data: 'hello', inputType: 'insertCompositionText', isComposing: true })); + }); + await settle(); + assert.equal((await snapshot()).display, 'hello'); + assert.equal((await snapshot()).plain, 'hello '); + await page.locator('textarea').evaluate(field => field.dispatchEvent(new CompositionEvent('compositionend', { data: 'hello' }))); + await settle(); + assert.equal((await snapshot()).plain, 'hello'); + + // Enter with keyCode 229 may have no usable keydown; beforeinput is authoritative. + const lineBreak = async (inputType, shift = false) => page.locator('textarea').evaluate((field, { inputType, shift }) => { + field.dispatchEvent(new KeyboardEvent('keydown', { key: 'Unidentified', keyCode: 229, shiftKey: shift, bubbles: true })); + const event = new InputEvent('beforeinput', { inputType, cancelable: true, bubbles: true }); + field.dispatchEvent(event); + if (!event.defaultPrevented) { field.setRangeText('\n', field.selectionStart, field.selectionEnd, 'end'); field.dispatchEvent(new InputEvent('input')); } + field.dispatchEvent(new KeyboardEvent('keyup', { shiftKey: false })); + return event.defaultPrevented; + }, { inputType, shift }); + assert.equal(await lineBreak('insertParagraph'), true); + await settle(); + assert.equal((await snapshot()).submits, 1); + assert.equal(await lineBreak('insertLineBreak', true), true); + await settle(); + assert.equal((await snapshot()).plain, 'hello\n'); + assert.equal((await snapshot()).submits, 1); + + await page.keyboard.press('Tab'); // Single-line editor. + await page.keyboard.insertText('one line'); + assert.equal(await lineBreak('insertLineBreak', true), true); + await settle(); + assert.equal((await snapshot()).single, 'one line'); + assert.equal((await snapshot()).submits, 2); + + await page.keyboard.press('Tab'); // Secure editor must activate a password sink. + assert.equal(await page.evaluate(() => document.activeElement.type), 'password'); + const password = page.locator('input[type=password]'); + assert.equal(await password.getAttribute('autocomplete'), 'off'); + assert.equal(await password.getAttribute('autocorrect'), 'off'); + assert.equal(await password.evaluate(p => p.spellcheck), false); + await page.keyboard.insertText('sëcret'); + assert.equal(await password.inputValue(), '', 'the secret must not remain in the DOM'); + await settle(); + assert.equal((await snapshot()).secretLength, 6, 'secure input reaches the model'); + await password.evaluate(field => field.dispatchEvent(new InputEvent('beforeinput', { + inputType: 'deleteContentBackward', cancelable: true, bubbles: true, + }))); + await settle(); + assert.equal((await snapshot()).secretLength, 5); + await page.keyboard.press('Enter'); + await settle(); + assert.equal((await snapshot()).submits, 3); + + await page.keyboard.press('Tab'); // A non-editor control must return DOM focus to canvas. + assert.equal(await page.evaluate(() => document.activeElement.tagName), 'CANVAS'); + await page.keyboard.press('Meta+k'); + await settle(); + assert.equal((await snapshot()).shortcuts, 1, 'canvas shortcuts survive the editor-to-canvas focus handoff'); + await page.keyboard.press('Shift+Tab'); + assert.equal(await page.evaluate(() => document.activeElement.type), 'password'); + await page.keyboard.press('Escape'); + assert.equal(await page.evaluate(() => document.activeElement.tagName), 'CANVAS'); + await page.keyboard.press('Meta+k'); + await settle(); + assert.equal((await snapshot()).shortcuts, 2); + + await page.touchscreen.tap(100, 36); + await page.touchscreen.tap(300, 500); // Background tap dismisses the editor. + assert.equal(await page.evaluate(() => document.activeElement.tagName), 'CANVAS'); + // Dispatch a burst in one JS turn: movement/wheels must wait for rAF, not run frames. + const polls = await page.evaluate(() => { + const before = window.__inputProof.polls; + const canvas = document.querySelector('canvas'); + for (let i = 0; i < 20; i++) { + canvas.dispatchEvent(new PointerEvent('pointermove', { pointerType: 'mouse', pointerId: 1, + button: -1, buttons: 0, clientX: 100 + i, clientY: 500 })); + canvas.dispatchEvent(new WheelEvent('wheel', { deltaY: 1, clientX: 100, clientY: 500 })); + } + return window.__inputProof.polls - before; + }); + assert.equal(polls, 0, 'continuous pointer events must not run synchronous frames'); + await page.evaluate(() => { + Object.defineProperty(document, 'hidden', { configurable: true, value: true }); + document.dispatchEvent(new Event('visibilitychange')); + }); + await settle(); + assert.equal((await snapshot()).visible, false); + await page.evaluate(() => { + delete document.hidden; + document.dispatchEvent(new Event('visibilitychange')); + }); + await settle(); + assert.equal((await snapshot()).visible, true); + console.log(JSON.stringify({ inputRegressions: 'passed', checks: ['stable editor focus', 'recomposition range', + 'beforeinput Enter', 'multiline vs single-line', 'password sink and deletion', 'Tab to canvas', + 'Escape shortcuts', 'outside dismiss', 'coalesced pointer frames', 'visibility', 'app title', 'nonfatal window requests'] })); +} diff --git a/app/vendor/rune/scripts/web-smoke.mjs b/app/vendor/rune/scripts/web-smoke.mjs new file mode 100644 index 0000000..919cb01 --- /dev/null +++ b/app/vendor/rune/scripts/web-smoke.mjs @@ -0,0 +1,174 @@ +// Functional browser proof for web-hello. Requires Playwright and its Chromium browser. +import assert from 'node:assert/strict'; +import { createServer } from 'node:http'; +import { readFile, mkdir } from 'node:fs/promises'; +import { resolve, extname, sep } from 'node:path'; +import { inputSmoke } from './web-input-smoke.mjs'; +import { clockSmoke } from './web-clock-smoke.mjs'; +const { chromium, webkit } = await import(process.env.PLAYWRIGHT_MODULE || 'playwright'); +const engine = process.env.WEB_ENGINE || 'chromium'; +const root = resolve(process.argv[2] || 'target/web'); +const output = resolve(process.argv[3] || 'target/web-proof'); +await mkdir(output, { recursive: true }); +const server = createServer(async (request, response) => { + const path = resolve(root, '.' + new URL(request.url, 'http://localhost').pathname.replace(/\/$/, '/index.html')); + if (!path.startsWith(root + sep)) { response.writeHead(403).end(); return; } + try { + const bytes = await readFile(path); + response.setHeader('Content-Type', ({ '.wasm': 'application/wasm', '.js': 'text/javascript', '.html': 'text/html' })[extname(path)] || 'application/octet-stream'); + response.end(bytes); + } catch { response.writeHead(404).end(); } +}); +await new Promise(done => server.listen(0, '127.0.0.1', done)); +const browser = await (engine === 'webkit' ? webkit.launch({ headless: true }) : + chromium.launch({ headless: true, executablePath: process.env.CHROMIUM_PATH, + args: ['--enable-unsafe-webgpu', ...(process.platform === 'darwin' ? ['--use-angle=metal'] : [])] })); +const errors = []; +try { + const context = await browser.newContext({ viewport: { width: 390, height: 760 }, deviceScaleFactor: 3, + hasTouch: true, isMobile: true, + permissions: engine === 'chromium' ? ['clipboard-read', 'clipboard-write'] : [], colorScheme: 'dark' }); + const page = await context.newPage(); + page.on('pageerror', error => { errors.push(error.message); console.log(error.message); }); + page.on('console', message => { if (message.type() === 'error') { errors.push(message.text()); console.log(message.text()); } }); + await page.addInitScript(() => { + // Chromium's device emulation leaves devicePixelContentBoxSize at the host DPR. + // Exercise winit's Safari fallback (CSS content box × emulated DPR) instead. + delete ResizeObserverEntry.prototype.devicePixelContentBoxSize; + window.__proof = { submits: 0, rafs: 0, gpuErrors: [] }; + const raf = window.requestAnimationFrame; + window.requestAnimationFrame = callback => { window.__proof.rafs++; return raf.call(window, callback); }; + if (!globalThis.GPUQueue || !globalThis.GPUAdapter) return; + const submit = GPUQueue.prototype.submit; + GPUQueue.prototype.submit = function (...args) { window.__proof.submits++; return submit.apply(this, args); }; + const request = GPUAdapter.prototype.requestDevice; + GPUAdapter.prototype.requestDevice = async function (...args) { + const device = await request.apply(this, args); + device.addEventListener('uncapturederror', e => window.__proof.gpuErrors.push(e.error.message)); + return device; + }; + }); + const url = `http://127.0.0.1:${server.address().port}`; + await page.goto(url); + if (engine === 'webkit' && !await page.evaluate(async () => !!(await navigator.gpu?.requestAdapter()))) { + console.log(JSON.stringify({ engine, available: false, reason: 'Headless WebKit has no WebGPU adapter' })); + } else { + if (!process.env.WEB_INPUT_ONLY) { + await page.waitForFunction(() => window.__proof?.submits > 0, { timeout: 30000 }); + await page.waitForTimeout(1000); // Let the initial appearance finish before measuring idle. + assert.deepEqual(await page.locator('canvas').evaluate(c => [c.width, c.height]), [1170, 2280]); + const beforeIdle = await page.evaluate(() => window.__proof.submits); + const beforeIdleRaf = await page.evaluate(() => window.__proof.rafs); + await page.waitForTimeout(600); + assert.equal(await page.evaluate(() => window.__proof.submits), beforeIdle, 'idle must not submit frames'); + assert.equal(await page.evaluate(() => window.__proof.rafs), beforeIdleRaf, 'idle must not request animation frames'); + await page.screenshot({ path: `${output}/web-dark.png` }); + const beforePan = await page.screenshot(); + const cdp = engine === 'chromium' ? await context.newCDPSession(page) : null; + const touch = async (type, y) => cdp ? cdp.send('Input.dispatchTouchEvent', { + type, touchPoints: type === 'touchEnd' ? [] : [{ x: 180, y }], + }) : page.locator('canvas').dispatchEvent(({ touchStart: 'pointerdown', touchMove: 'pointermove', touchEnd: 'pointerup' })[type], + { pointerType: 'touch', pointerId: 1, isPrimary: true, clientX: 180, clientY: y, buttons: type === 'touchEnd' ? 0 : 1 }); + await touch('touchStart', 180); + for (let i = 1; i <= 10; i++) { + await touch('touchMove', 180 + 30 * i); + await page.waitForTimeout(16); + } + await touch('touchEnd', 480); + const releaseSubmits = await page.evaluate(() => window.__proof.submits); + await page.waitForTimeout(250); + assert.ok(await page.evaluate(() => window.__proof.submits) > releaseSubmits, 'touch release continues momentum'); + assert.ok(!beforePan.equals(await page.screenshot()), 'touch pan moves rendered content'); + assert.notEqual(await page.evaluate(() => document.activeElement?.tagName), 'TEXTAREA', 'a pan must not focus an editor'); + await page.touchscreen.tap(100, 720); + await page.waitForFunction(() => document.activeElement?.tagName === 'TEXTAREA'); + await page.keyboard.insertText('Bonjour 🦀'); + assert.equal(await page.locator('textarea').inputValue(), 'Bonjour 🦀'); + await page.keyboard.press('Enter'); + assert.equal(await page.locator('textarea').inputValue(), ''); + await page.touchscreen.tap(330, 36); + assert.equal(await page.evaluate(() => navigator.clipboard.readText()), 'Bonjour 🦀', 'send updates the actual model'); + await page.touchscreen.tap(100, 720); + await page.keyboard.insertText('x'.repeat(1200) + ' tail'); + assert.ok((await page.locator('textarea').inputValue()).length <= 1024, 'mirror is a sliding context'); + await page.locator('textarea').evaluate(field => { + field.setSelectionRange(field.value.length - 4, field.value.length); + field.setRangeText('corrected', field.selectionStart, field.selectionEnd, 'end'); + field.dispatchEvent(new InputEvent('input', { inputType: 'insertReplacementText', data: 'corrected' })); + }); + await page.keyboard.press('Enter'); + await page.touchscreen.tap(330, 36); + assert.equal(await page.evaluate(() => navigator.clipboard.readText()), 'x'.repeat(1200) + ' corrected'); + await page.touchscreen.tap(100, 720); + const beforeMissingGlyph = await page.evaluate(() => window.__proof.submits); + await page.locator('textarea').evaluate(field => { + field.dispatchEvent(new CompositionEvent('compositionstart', { data: '' })); + field.value = '日本語'; field.setSelectionRange(3, 3); + field.dispatchEvent(new CompositionEvent('compositionupdate', { data: '日本語' })); + field.dispatchEvent(new InputEvent('input', { data: '日本語', isComposing: true })); + field.dispatchEvent(new CompositionEvent('compositionend', { data: '日本語' })); + }); + assert.equal(await page.locator('textarea').inputValue(), '日本語'); + await page.waitForFunction(previous => window.__proof.submits > previous, beforeMissingGlyph); + await page.keyboard.press('Meta+A'); + await page.keyboard.insertText('replacement'); + assert.equal(await page.locator('textarea').inputValue(), 'replacement'); + // Browser paste is independent of async clipboard-read permission. + await page.locator('textarea').evaluate(field => { + const clipboardData = new DataTransfer(); clipboardData.setData('text/plain', ' pasted'); + field.dispatchEvent(new ClipboardEvent('paste', { clipboardData, bubbles: true })); + }); + assert.equal(await page.locator('textarea').inputValue(), 'replacement pasted'); + const popup = context.waitForEvent('page'); + await page.touchscreen.tap(90, 36); + const linked = await popup; + await linked.waitForLoadState('domcontentloaded'); + assert.ok(linked.url().includes('rust-lang.org')); + assert.equal(await linked.evaluate(() => window.opener), null); + await linked.close(); + await page.emulateMedia({ colorScheme: 'light', reducedMotion: 'reduce' }); + await page.setViewportSize({ width: 430, height: 540 }); + await page.waitForFunction(() => document.querySelector('canvas')?.height === 1620); + await page.waitForTimeout(400); + await page.screenshot({ path: `${output}/web-light-keyboard-size.png` }); + const gpuErrors = await page.evaluate(() => window.__proof.gpuErrors); + assert.deepEqual(gpuErrors, []); + assert.deepEqual(errors.filter(e => !e.includes('404')), []); + console.log(JSON.stringify({ ok: true, engine, idleSubmits: 0, idleRafs: 0, dpr: 3, sizingPath: 'Safari fallback', checks: ['WebGPU render', 'idle', 'touch focus', + 'touch momentum', 'Unicode input', 'send', 'clipboard copy', 'sliding context', 'predictive replacement', + 'composition', 'selection replacement', 'paste', 'noopener link', 'theme', 'resize'], gpuErrors })); + } + await page.setViewportSize({ width: 390, height: 760 }); + await inputSmoke(page, url); + // JPEG bytes go to the browser's codecs, PNG bytes to Rune's. + await page.goto(`${url}/?image-proof`); + await page.waitForFunction(() => window.__imageProof?.jpeg && window.__imageProof?.png); + assert.deepEqual(await page.evaluate(() => window.__imageProof), { jpeg: { width: 12, height: 6 }, png: { width: 12, height: 6 } }); + // The cursor over them is the PNG at 2x, which the browser decodes and sizes in points. + const cursor = () => page.evaluate(() => getComputedStyle(document.querySelector('canvas')).cursor); + await page.mouse.move(76, 114); + await page.waitForFunction(() => getComputedStyle(document.querySelector('canvas')).cursor.includes('image-set(')); + const css = await cursor(); + assert.match(css, /image-set\(url\("blob:[^"]+"\) 2(x|dppx)\) 1 2, auto$/, css); + const size = await page.evaluate(async (url) => { + const image = new Image(); + image.src = url; + await image.decode(); + return [image.naturalWidth, image.naturalHeight]; + }, css.match(/blob:[^"]+/)[0]); + assert.deepEqual(size, [12, 6]); + await page.mouse.move(300, 700); + await page.waitForFunction(() => getComputedStyle(document.querySelector('canvas')).cursor === 'auto'); + // Inter's full faces load from beside app.js once the first frame is up. + await page.waitForFunction(() => performance.getEntriesByType('resource').filter(e => /\/Inter-\w+\.ttf$/.test(e.name) && e.responseEnd > 0).length === 3); + assert.deepEqual(await page.evaluate(() => performance.getEntriesByType('resource') + .filter(e => /\/Inter-\w+\.ttf$/.test(e.name)).map(e => e.responseStatus ?? 200)), [200, 200, 200]); + console.log(JSON.stringify({ ok: true, checks: ['image bytes', 'image cursor', 'full Inter faces'] })); + assert.deepEqual(await page.evaluate(() => window.__proof.gpuErrors), []); + assert.deepEqual(errors.filter(e => !e.includes('404')), []); + if (engine === 'chromium') { await clockSmoke(browser, url); console.log(JSON.stringify({ ok: true, checks: ['page clock'] })); } + } +} finally { + await browser.close(); + await new Promise(done => server.close(done)); +} diff --git a/app/vendor/rune/site/.gitignore b/app/vendor/rune/site/.gitignore new file mode 100644 index 0000000..1484b48 --- /dev/null +++ b/app/vendor/rune/site/.gitignore @@ -0,0 +1,4 @@ +node_modules/ +dist/ +dist-ssr/ +.cloudflare/ diff --git a/app/vendor/rune/site/README.md b/app/vendor/rune/site/README.md new file mode 100644 index 0000000..810f4a6 --- /dev/null +++ b/app/vendor/rune/site/README.md @@ -0,0 +1,55 @@ +# Rune site + +The docs site for Rune: what it is, its principles, its architecture and its roadmap. Vite and React, prerendered to +static HTML. + +- `bun run dev`: dev server at `http://127.0.0.1:4241/team/rune/`. +- `bun run build`: typecheck, client and SSR builds, then prerender every route into + `.cloudflare/output/v0/workers/default/assets/` (Build Output for the `cf` CLI). `--mode dev` builds for + dev.anoma.ly. + +Content lives in `src/content.tsx` (principles, layers, decisions, milestones, risks) and `src/pages.tsx`. The +source of truth for all of it is `PLAN.md` at the repo root; update the plan first, then the site. + +Code examples are cut from Rune's source at build time. `scripts/snippets.ts` lists each one by file and marker, +highlights it with `scripts/highlight.ts` and serves the HTML as `virtual:snippets`; pages +render them with `<Code id="…" />`. A moved or renamed function fails the build with the snippet's name. The +how-it-works diagrams are plain HTML in `src/Diagram.tsx`. + +## Hosting and deploys + +The site is served at https://anoma.ly/team/rune and https://dev.anoma.ly/team/rune. + +- A push to `dev` that touches `site/` deploys https://dev.anoma.ly/team/rune (Worker `rune-dev-site`). +- A push to `production` that touches `site/` deploys https://anoma.ly/team/rune (Worker `rune-production-site`). To release, + fast-forward it to `dev`: `git push origin dev:production`. Never commit to `production` directly. + +Nothing else deploys. `.github/workflows/site.yml` runs `bun run deploy:<production|dev>` with the +`CLOUDFLARE_API_TOKEN` and `CLOUDFLARE_ACCOUNT_ID` secrets. The token needs Workers Scripts Write on the account and +Workers Routes Write on `anoma.ly`. + +`cloudflare.config.ts` defines both environments, selected by the build mode. `worker.ts` redirects other hosts to the +canonical one, strips the base path `/team/rune` (from `src/base.ts`) and serves the static files. Vite's `base`, the +links (`withBase`) and the client router (`stripBase`) use the same constant. + +`/team` on both hosts sits behind a Cloudflare Access app, so only Anomaly accounts get in. `workers.dev` and preview +URLs are off, so nothing bypasses Access. + +## Design system + +`src/system/` (`tokens.css`, `primitives.css`, `Frame.tsx`, `useScrollSpy.ts`) and the Geist fonts in +`public/fonts/` are copied unchanged, apart from the font URLs, from `@anomalyco/site` (Anomaly's docs +system, direction "Workbench"). `src/site.css` sets Rune's accent by overriding `--ink` and adds only what the system +lacks: the wordmark, the home page, the diagrams, the decisions table and the roadmap rows. Once `@anomalyco/site` is +published, import it instead of these copies; until then, copy changes across by hand rather than editing them here. + +The screenshots in `public/shots/` are Rune's own headless renders (`--snap`) of the examples, some resized. + +## Brand + +The logo is ᚱUNE on Anomaly's pixel grid, the R swapped for the rune ᚱ. `src/brand/pixels.ts` holds the letters; +`Wordmark.tsx` draws them in the sidebar (2 px a cell) and as the home masthead (12 px), and runs a light down the ᚱ's +strokes on hover, and every 5–9 s on the home page while the masthead is on screen (`motion.ts`). `bun run icons` +redraws the favicons, app icons and `og.png` in `public/` from the same pixels. + +The prerender also writes `404.html` (served by the Worker for missing paths) and `llms.txt`. diff --git a/app/vendor/rune/site/bun.lock b/app/vendor/rune/site/bun.lock new file mode 100644 index 0000000..eb1326d --- /dev/null +++ b/app/vendor/rune/site/bun.lock @@ -0,0 +1,430 @@ +{ + "lockfileVersion": 2, + "configVersion": 1, + "workspaces": { + "": { + "name": "rune-site", + "dependencies": { + "react": "19.2.7", + "react-dom": "19.2.7", + }, + "devDependencies": { + "@cloudflare/build-output-utils": "0.8.5", + "@cloudflare/vite-plugin": "2.0.0-beta.v.4", + "@types/bun": "1.3.13", + "@types/node": "25.5.0", + "@types/react": "19.2.17", + "@types/react-dom": "19.2.3", + "@vitejs/plugin-react": "6.0.3", + "cf": "1.0.0-beta.12", + "typescript": "6.0.2", + "vite": "8.1.3", + }, + }, + }, + "packages": { + "@cloudflare/build-output-utils": ["@cloudflare/build-output-utils@0.8.5", "", { "dependencies": { "@cloudflare/config": "0.23.0" } }, "sha512-xnwcDCyBSErZeOj5eUy1gTrmVjwIY51TZ0Pz9W7mZqLGA3IkIckud7dNtFdGhKSXL2szfxBRbGM4R4qFE4SoPA=="], + + "@cloudflare/codemods": ["@cloudflare/codemods@0.4.0", "", { "bin": { "cloudflare-codemods": "dist/bin.mjs" } }, "sha512-qeRpKNXtvqhTtagx/5cLmDaFx/voBhWJ1S6SdFdBkE3OtgcPVz+Q8MtIG26zltW9Z0Icsu2FGBxV5RFmuHI/Bg=="], + + "@cloudflare/config": ["@cloudflare/config@0.23.0", "", { "dependencies": { "zod": "4.4.3" } }, "sha512-oE0S7X54esZmJHr9hhCoqODR+yTxxkSYWCLtRiItQdPs0gQuqYw9a13zChhK+8DmdCUJIFBsMAR6t+mfu8g+9w=="], + + "@cloudflare/runtime-types": ["@cloudflare/runtime-types@0.1.15", "", { "dependencies": { "miniflare": "5.20261019.2-beta", "workerd": "1.20261019.1" } }, "sha512-E8WCMGir4IRp/ksqodMWGpxHJvgtfgW9lbVM5mNAdWrnonMNOtGocyxVt6hG8/RGW9sjFWR7F7Cp3SCF1Cz6zg=="], + + "@cloudflare/unenv-preset": ["@cloudflare/unenv-preset@2.16.2", "", { "peerDependencies": { "unenv": "2.0.0-rc.24", "workerd": ">1.20260305.0 <2.0.0-0" }, "optionalPeers": ["workerd"] }, "sha512-JBP1+Z7ZSNG/d4mRP+y8VC5dka3tZVMLEZRvS+rzQ4DGV1EoxRFQckcJTTkXbHSQiTj0DtNI01Zwb/V2fX0mvQ=="], + + "@cloudflare/vite-plugin": ["@cloudflare/vite-plugin@2.0.0-beta.v.4", "", { "dependencies": { "@cloudflare/build-output-utils": "0.9.4", "@cloudflare/config": "0.28.0", "@cloudflare/runtime-types": "0.1.15", "@cloudflare/unenv-preset": "2.16.2", "miniflare": "5.20261019.2-beta", "unenv": "2.0.0-rc.24", "ws": "8.21.0" }, "peerDependencies": { "vite": "^7.0.0 || ^8.0.0" }, "bin": { "cf-vite": "bin/cf-vite" } }, "sha512-VNlj5o1Uc3IbfoDIA03jD/vd7hGDgbnx/Sjof6xYVpvCW0CRug67dQN0nabyKKSa27tvdSp0l1i+veTuNurA6g=="], + + "@cloudflare/workerd-darwin-64": ["@cloudflare/workerd-darwin-64@1.20261019.1", "", { "os": "darwin", "cpu": "x64" }, "sha512-5ZILbAta/fBQvhmAYeCE7dKMMYIr7N9wJEX50fEGLKSIwGtvT0HzSfHNIK/O7cBQ4gHQ2WfIiPClvwcye6E0fA=="], + + "@cloudflare/workerd-darwin-arm64": ["@cloudflare/workerd-darwin-arm64@1.20261019.1", "", { "os": "darwin", "cpu": "arm64" }, "sha512-cww2Ab6lVMxpTiEEjKmPI58p5EMo0vYTZSH+3WkqXJdQgc3ES66GuL247+U2B2YWajhhu2tqj7jySrXneU749g=="], + + "@cloudflare/workerd-linux-64": ["@cloudflare/workerd-linux-64@1.20261019.1", "", { "os": "linux", "cpu": "x64" }, "sha512-4++VRi9vkQROYqrpZYOixIJuVDmujkwrT4kszsxNFlvcmsX6Mr2GumvxIN3gIixS3vJUh3Umdtkthqj5X0S3Xw=="], + + "@cloudflare/workerd-linux-arm64": ["@cloudflare/workerd-linux-arm64@1.20261019.1", "", { "os": "linux", "cpu": "arm64" }, "sha512-75PVtJOwfjScQ53sbLtQXI7D8yP1c21t+WEUPaYbqkzaz4ZqfR5wAd+zuWs8G5Q7kOj2SQIvEfY5Sn8Y+UVrnA=="], + + "@cloudflare/workerd-windows-64": ["@cloudflare/workerd-windows-64@1.20261019.1", "", { "os": "win32", "cpu": "x64" }, "sha512-z49fvKTETMCnG6wnMcQwxx9CpryFceiKz04FRjq26EkhCyzRNJ6c3UXhyZz3r5f1CXnnBZc5DcU8ZouPkUJCqw=="], + + "@cspotcode/source-map-support": ["@cspotcode/source-map-support@0.8.1", "", { "dependencies": { "@jridgewell/trace-mapping": "0.3.9" } }, "sha512-IchNf6dN4tHoMFIn/7OE8LWZ19Y6q/67Bmf6vnGREv8RSbBVb9LPJxEcnwrcwX6ixSvaiGoomAUvu4YSxXrVgw=="], + + "@emnapi/core": ["@emnapi/core@1.11.1", "", { "dependencies": { "@emnapi/wasi-threads": "1.2.2", "tslib": "^2.4.0" } }, "sha512-RSvbQmHzdKzNsLYa/wHrbc3KN4sYLKAdPZxqiM2HATqv/SBk2/ENSHpvXGaLOMcsAyz0poEGqkmmKYG3OWiJEQ=="], + + "@emnapi/runtime": ["@emnapi/runtime@1.11.1", "", { "dependencies": { "tslib": "^2.4.0" } }, "sha512-vgj7R3y3Wgx24IQaGPA/R6YFXLHVMOZ0uVEyIQPaWs+rd1AzfEMXlAC22FYwO1XkKR6NPsq7mUandH8oIRdZFw=="], + + "@emnapi/wasi-threads": ["@emnapi/wasi-threads@1.2.2", "", { "dependencies": { "tslib": "^2.4.0" } }, "sha512-c95qOXkHdydNKhscBTebqEC1CVAZpyqOfVfBzQ1qgzyl3gfeldUjIggDbIZgDKsHLgnsM+igH7TJ/eAasaVuMA=="], + + "@img/colour": ["@img/colour@1.1.0", "", {}, "sha512-Td76q7j57o/tLVdgS746cYARfSyxk8iEfRxewL9h4OMzYhbW4TAcppl0mT4eyqXddh6L/jwoM75mo7ixa/pCeQ=="], + + "@img/sharp-darwin-arm64": ["@img/sharp-darwin-arm64@0.35.5", "", { "optionalDependencies": { "@img/sharp-libvips-darwin-arm64": "1.3.4" }, "os": "darwin", "cpu": "arm64" }, "sha512-QRUlFQ0WxvdWyqqG/WtI3iupfD5rBzmCHXSdPsY91sAtVtTo7Q4cb6zOccZ3gqEqkr0f1As1ehLqmEpDsRf+lg=="], + + "@img/sharp-darwin-x64": ["@img/sharp-darwin-x64@0.35.5", "", { "optionalDependencies": { "@img/sharp-libvips-darwin-x64": "1.3.4" }, "os": "darwin", "cpu": "x64" }, "sha512-+BR255RhDlpygUpOc/Jdt1nT6DQ3XG/ERo5wbcdOf5Q320dKtPCKPLR1LJs9VGXRaMa8l1uUa0tkCNOXiAxZUw=="], + + "@img/sharp-freebsd-wasm32": ["@img/sharp-freebsd-wasm32@0.35.5", "", { "dependencies": { "@img/sharp-wasm32": "0.35.5" }, "os": "freebsd" }, "sha512-Y/z91nEZ4uIBX5X3nfTovjU9lHNKFYbL2lpHCLVNmXQK03VIZvXBBt0KxbPGp2SdGSF+2mQU4e+hQaWOt86iAw=="], + + "@img/sharp-libvips-darwin-arm64": ["@img/sharp-libvips-darwin-arm64@1.3.4", "", { "os": "darwin", "cpu": "arm64" }, "sha512-5R89nBYiRdUlSWJxPhO+GVtaXzXSxKnRu/xqMn3KTA3L9EB9Oy/P+Nn2f2vlhPuUdy/Zusb2DarbyTpGCfEDuw=="], + + "@img/sharp-libvips-darwin-x64": ["@img/sharp-libvips-darwin-x64@1.3.4", "", { "os": "darwin", "cpu": "x64" }, "sha512-iR2OKH80yi0U+dUplyh3/xdpFvps6YkCwsXenIJxqxR1v9o+xtKTGbS9H7cps+2Vxjc8B1j96p75NmTGjIhtpQ=="], + + "@img/sharp-libvips-linux-arm": ["@img/sharp-libvips-linux-arm@1.3.4", "", { "os": "linux", "cpu": "arm" }, "sha512-LmRtTsOHuvM2+wlO2Db37dx5MiZhB0FvSunciw48YjdOkZz9KAiRbm8ujeMOA1INqmei5NapFxYEK1D1ZSidmw=="], + + "@img/sharp-libvips-linux-arm64": ["@img/sharp-libvips-linux-arm64@1.3.4", "", { "os": "linux", "cpu": "arm64" }, "sha512-Y3dgX/6lE2QhQb+Gxy0WZxfg9MEm/JBjamZpS2IklP7xIQoKN4hzAm7KcMVGtaVDt3neE9OKBC7vAfonA/Lr1A=="], + + "@img/sharp-libvips-linux-ppc64": ["@img/sharp-libvips-linux-ppc64@1.3.4", "", { "os": "linux", "cpu": "ppc64" }, "sha512-Le6boB8Tai0Nis+gIxIpKx68UDVVIqdR8Tin5Yf1z2LJJQLDJvCDRqRu+jC2qCoD+eIomonmOwB4smBRxfVpYQ=="], + + "@img/sharp-libvips-linux-riscv64": ["@img/sharp-libvips-linux-riscv64@1.3.4", "", { "os": "linux", "cpu": "none" }, "sha512-aHkkIEHPRdQEegJN20MLmGtxYD9R2wQr3Cwpddnu5+YKMt6Uzax7S9h5gpZTo8wyrGuZSlfQ63OevL5mTyOC7Q=="], + + "@img/sharp-libvips-linux-s390x": ["@img/sharp-libvips-linux-s390x@1.3.4", "", { "os": "linux", "cpu": "s390x" }, "sha512-ra/mB6MikESDUO7Yg+Mi95bFBb9GsObURuhnOv3OqknjGe9sZrG8tCe9q0xSIGrtLgvgw0gKnFWcK4blSgQOuQ=="], + + "@img/sharp-libvips-linux-x64": ["@img/sharp-libvips-linux-x64@1.3.4", "", { "os": "linux", "cpu": "x64" }, "sha512-GJ//SSXbnwSDes02umB3nDJLFcQzw8a18V8fyhqr6tV515tOEMdImjjxj1AoafMRz56F3PHgftnj1QEKSU1zkw=="], + + "@img/sharp-libvips-linuxmusl-arm64": ["@img/sharp-libvips-linuxmusl-arm64@1.3.4", "", { "os": "linux", "cpu": "arm64" }, "sha512-hvulFwtjUcagsis6BBxHwGFwWoNZjgYmULGVrZcyfNbjA8hKILbRxGg15/7w5HDyXHXUos/j6baAWqnCyQ2DWA=="], + + "@img/sharp-libvips-linuxmusl-x64": ["@img/sharp-libvips-linuxmusl-x64@1.3.4", "", { "os": "linux", "cpu": "x64" }, "sha512-6zXKeE/p39I1AmA3cJG35eyBGNqNddLnUXjhwBnsGjFPWqf5VKkDBEqaEkPDoTEtkxwi2vv8Tcr2mDyP4So7Fg=="], + + "@img/sharp-linux-arm": ["@img/sharp-linux-arm@0.35.5", "", { "optionalDependencies": { "@img/sharp-libvips-linux-arm": "1.3.4" }, "os": "linux", "cpu": "arm" }, "sha512-LEaXK2WdXVK5ykcw0buWyPMsmLLL2vpHLD6yrNSW+JGEL3BZPA4tpKN6iaMc4AxTTAoaX/sU1rOL51lcIz48ZQ=="], + + "@img/sharp-linux-arm64": ["@img/sharp-linux-arm64@0.35.5", "", { "optionalDependencies": { "@img/sharp-libvips-linux-arm64": "1.3.4" }, "os": "linux", "cpu": "arm64" }, "sha512-LYVx5JTsOM2CBzmxreh+nl64/3H6Xb09iSLknqH47z2T2DFFxDeFLP5y4dJwe6H7uGQlHPyEEtIqyo3DYsRwdQ=="], + + "@img/sharp-linux-ppc64": ["@img/sharp-linux-ppc64@0.35.5", "", { "optionalDependencies": { "@img/sharp-libvips-linux-ppc64": "1.3.4" }, "os": "linux", "cpu": "ppc64" }, "sha512-QVxAAq8evVRI9ia2vqgwrmWucn5Dfv+JdWzj75pD8omHLPSP7f8p20O8jxzjCcuCEQEOtYOZUmX1hkiZ0kdevA=="], + + "@img/sharp-linux-riscv64": ["@img/sharp-linux-riscv64@0.35.5", "", { "optionalDependencies": { "@img/sharp-libvips-linux-riscv64": "1.3.4" }, "os": "linux", "cpu": "none" }, "sha512-LtdreXguaavKODPIfzJ4kffx7UNt1omwtK0rch4EBbbSTXPnxWmYSayXdLJw0fJzQ97kHt1gL/yh4tvU+nCyRQ=="], + + "@img/sharp-linux-s390x": ["@img/sharp-linux-s390x@0.35.5", "", { "optionalDependencies": { "@img/sharp-libvips-linux-s390x": "1.3.4" }, "os": "linux", "cpu": "s390x" }, "sha512-UZasTOFiYzotTsGOCu42BfUzP6Tu6Do/947iRm1RsLKvlllxwGcn4RN27LibGWceix4Y+Pmw3jsnTcCQIgWjqA=="], + + "@img/sharp-linux-x64": ["@img/sharp-linux-x64@0.35.5", "", { "optionalDependencies": { "@img/sharp-libvips-linux-x64": "1.3.4" }, "os": "linux", "cpu": "x64" }, "sha512-SxFtLTeJInhAA9Q836kux2vZNeOBQEx658qvbboZScr0wIARym3IcGmW7KpVD5sbVg0Ojy+udFQdayYIZyoNog=="], + + "@img/sharp-linuxmusl-arm64": ["@img/sharp-linuxmusl-arm64@0.35.5", "", { "optionalDependencies": { "@img/sharp-libvips-linuxmusl-arm64": "1.3.4" }, "os": "linux", "cpu": "arm64" }, "sha512-9HbMclmI1zlNkFRs3z9/eBtDjfD0sGlrX1z6b1qwmiFY5ElDLh4BC0LPBdVp7z1DXFiKlIcznf+ZlsuZzLxQqg=="], + + "@img/sharp-linuxmusl-x64": ["@img/sharp-linuxmusl-x64@0.35.5", "", { "optionalDependencies": { "@img/sharp-libvips-linuxmusl-x64": "1.3.4" }, "os": "linux", "cpu": "x64" }, "sha512-4KOphqB035HrVdqLZfCgMzzERrQkkzOwRhl4OAkRO1YCldbaFjySXMaK534Mo0V+LndnlJk+sbUyLeU0ULyD1A=="], + + "@img/sharp-wasm32": ["@img/sharp-wasm32@0.35.5", "", { "dependencies": { "@emnapi/runtime": "^1.11.3" } }, "sha512-Ptsga1su4tQx+LLF1ECS9U6nz5kmrXKo6XVbtR48Ke3ZRxxgaWBu7IDtEe1quo8hiupwm6WFqxVlXaSf7IINGQ=="], + + "@img/sharp-webcontainers-wasm32": ["@img/sharp-webcontainers-wasm32@0.35.5", "", { "dependencies": { "@img/sharp-wasm32": "0.35.5" }, "cpu": "none" }, "sha512-hfhF/FmoQyTUkA0bIKFOtw536BQSeBMe6BF6QyWlrPxT754+TFLaZ7sKKTfvvM0yJgKgaYTwnFCIZ/GuDw5SUA=="], + + "@img/sharp-win32-arm64": ["@img/sharp-win32-arm64@0.35.5", "", { "os": "win32", "cpu": "arm64" }, "sha512-X4t7g+7ZA5DKblCBEXGjUqqemj4vczING/5viFwAL8h4N3qYeyjwdCvRLHi4EdOUI+2Z7UFlp1VM+p/AuEtm6Q=="], + + "@img/sharp-win32-ia32": ["@img/sharp-win32-ia32@0.35.5", "", { "os": "win32", "cpu": "ia32" }, "sha512-5Zm82LoBc43nhwNybZlG7Y1KO//Zhsn306fQl29ZOuStHLGTo3BWL83q3cznX0poxSAMuYL1On/BHBxkBeKr6A=="], + + "@img/sharp-win32-x64": ["@img/sharp-win32-x64@0.35.5", "", { "os": "win32", "cpu": "x64" }, "sha512-x76eH0vEiHlcMQu8Y8IenntaACtddpT6W0wmXtWrnKcnKI7ME5DdgqhAD6SEWOEl1v2zDvkZDhFA9KnURwpfqg=="], + + "@jridgewell/resolve-uri": ["@jridgewell/resolve-uri@3.1.2", "", {}, "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw=="], + + "@jridgewell/sourcemap-codec": ["@jridgewell/sourcemap-codec@1.6.0", "", {}, "sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw=="], + + "@jridgewell/trace-mapping": ["@jridgewell/trace-mapping@0.3.9", "", { "dependencies": { "@jridgewell/resolve-uri": "^3.0.3", "@jridgewell/sourcemap-codec": "^1.4.10" } }, "sha512-3Belt6tdc8bPgAtbcmdtNJlirVoTmEb5e2gC94PnkwEW9jI6CAHUeoG85tjWP5WquqfavoMtMwiG4P926ZKKuQ=="], + + "@napi-rs/wasm-runtime": ["@napi-rs/wasm-runtime@1.2.5", "", { "dependencies": { "@tybys/wasm-util": "^0.10.3" }, "peerDependencies": { "@emnapi/core": "^1.7.1 || ^2.0.0-alpha.4", "@emnapi/runtime": "^1.7.1 || ^2.0.0-alpha.4" } }, "sha512-HshSvXzmBxNzqejd3k/KemgQ3hdREUYFRRrgxOZ+gPljDIsO2SDZrVZMd4Z/HsxudQbE62OVyVFE8z9BCurfjA=="], + + "@oxc-project/types": ["@oxc-project/types@0.139.0", "", {}, "sha512-r9gHphtCs+1M7J0pw6Sn/hh/Wpa/iQrOOkrNAlVLF/gHq+/CJmHIWKKUUhdWjcD6CIa8idarspCsASiXCXvFUw=="], + + "@poppinss/colors": ["@poppinss/colors@4.1.6", "", { "dependencies": { "kleur": "^4.1.5" } }, "sha512-H9xkIdFswbS8n1d6vmRd8+c10t2Qe+rZITbbDHHkQixH5+2x1FDGmi/0K+WgWiqQFKPSlIYB7jlH6Kpfn6Fleg=="], + + "@poppinss/dumper": ["@poppinss/dumper@0.6.5", "", { "dependencies": { "@poppinss/colors": "^4.1.5", "@sindresorhus/is": "^7.0.2", "supports-color": "^10.0.0" } }, "sha512-NBdYIb90J7LfOI32dOewKI1r7wnkiH6m920puQ3qHUeZkxNkQiFnXVWoE6YtFSv6QOiPPf7ys6i+HWWecDz7sw=="], + + "@poppinss/exception": ["@poppinss/exception@1.2.3", "", {}, "sha512-dCED+QRChTVatE9ibtoaxc+WkdzOSjYTKi/+uacHWIsfodVfpsueo3+DKpgU5Px8qXjgmXkSvhXvSCz3fnP9lw=="], + + "@rolldown/binding-android-arm64": ["@rolldown/binding-android-arm64@1.1.5", "", { "os": "android", "cpu": "arm64" }, "sha512-lZg8fqIv2v7FF237bwMgzGZEJvGL79/s5knJ/i6FmsGF4XXlzccZ4jb+TrFIxtSSxFtIpdsgrPZeMk1I9AFcyQ=="], + + "@rolldown/binding-darwin-arm64": ["@rolldown/binding-darwin-arm64@1.1.5", "", { "os": "darwin", "cpu": "arm64" }, "sha512-51Bnx9pNiMRKSUNtBfySkNJ9vMU9Hh3I1ozDd6gyPPYzaXCfnptUcEZxXGYFn+ul2dtcMUiqGR1Yai2K10uoTw=="], + + "@rolldown/binding-darwin-x64": ["@rolldown/binding-darwin-x64@1.1.5", "", { "os": "darwin", "cpu": "x64" }, "sha512-Tm+gbfC0aHu1tBA/JvKQh32S0K6YgCHkiAF4/W6xX0K0RmNuc94VeK419dJoE65R5aRxmo+noZQSWrAMF6yb6g=="], + + "@rolldown/binding-freebsd-x64": ["@rolldown/binding-freebsd-x64@1.1.5", "", { "os": "freebsd", "cpu": "x64" }, "sha512-JMzDKCCXq93YccG5gz3hvOs1oXRKAf0XYpfOS88e+wZrC8Iugj6j68867vrYZkvpDDpKn/KoKORThmchMpF6TA=="], + + "@rolldown/binding-linux-arm-gnueabihf": ["@rolldown/binding-linux-arm-gnueabihf@1.1.5", "", { "os": "linux", "cpu": "arm" }, "sha512-uML21j2K5TfPGutKxub+M+nLjZIrWjXQ5Grx4lCe/nimTj9B4L63zHpjXLl4y0L3mcm2htEQIb06oCG/szerNw=="], + + "@rolldown/binding-linux-arm64-gnu": ["@rolldown/binding-linux-arm64-gnu@1.1.5", "", { "os": "linux", "cpu": "arm64" }, "sha512-navSiuTMogvnQoZoM/v+l3ZWo50/NTwSHSzheABx/RCnmUPaKwq9qSo4Br2OYRs21+Fz8uFqITZM3H4opOB0/Q=="], + + "@rolldown/binding-linux-arm64-musl": ["@rolldown/binding-linux-arm64-musl@1.1.5", "", { "os": "linux", "cpu": "arm64" }, "sha512-lAryqH7IteztmCXQXk0etKj4wBQ7Gx5S6LjKhsgp9zb8I5bsuvU/2llH1hDQcjsFeqIsovMVN339/8pUDDBXxA=="], + + "@rolldown/binding-linux-ppc64-gnu": ["@rolldown/binding-linux-ppc64-gnu@1.1.5", "", { "os": "linux", "cpu": "ppc64" }, "sha512-fsK/sNBnxzBlL4O1JNrZakVQxPspqpED5dLtNsZS9oOKmtSpdNIzxH2kkol5HYTWJN47sE20ztMJPxfZ89qGOg=="], + + "@rolldown/binding-linux-s390x-gnu": ["@rolldown/binding-linux-s390x-gnu@1.1.5", "", { "os": "linux", "cpu": "s390x" }, "sha512-gLYb4BIadlfTOYT5gO503n8zQjXflgzpD0FcyKh0Mzx3rqCZKnHoJWV9xe1KXUJ5lx2JfcSHr/mhzS0PC/McAA=="], + + "@rolldown/binding-linux-x64-gnu": ["@rolldown/binding-linux-x64-gnu@1.1.5", "", { "os": "linux", "cpu": "x64" }, "sha512-FjcpEKUyJygHgs1o50VYNvkt5+7Le/VEdYt0AkRpkL33MnyQfwr8l5mXwMmfmTbyMPr5vJLC+8/Gd9gXnwU1QQ=="], + + "@rolldown/binding-linux-x64-musl": ["@rolldown/binding-linux-x64-musl@1.1.5", "", { "os": "linux", "cpu": "x64" }, "sha512-Me+PfPI2TMeOQk0gYWfLQZtTktrmzbr8cDboqX83XKc7UrgAi55gF+2dUkWdxd19n55Essp2yeca+O9N5rBxHg=="], + + "@rolldown/binding-openharmony-arm64": ["@rolldown/binding-openharmony-arm64@1.1.5", "", { "os": "none", "cpu": "arm64" }, "sha512-yc5WrLzXks6zCQfn9Oxr8pORKyl/pF+QjHmW/Qx3qu0oyrrNC+y2JLTU1E2rcWYAmzlnqngWXHQjy51VzW70Vw=="], + + "@rolldown/binding-wasm32-wasi": ["@rolldown/binding-wasm32-wasi@1.1.5", "", { "dependencies": { "@emnapi/core": "1.11.1", "@emnapi/runtime": "1.11.1", "@napi-rs/wasm-runtime": "^1.1.6" }, "cpu": "none" }, "sha512-VbQGPX2b4r48TAMIM2cjgluIM1HYutm4pcTEJsle7iEP7sB1dFqtPLBVbdLAZCxy1txCcPxf4QFf4v8uvltPqA=="], + + "@rolldown/binding-win32-arm64-msvc": ["@rolldown/binding-win32-arm64-msvc@1.1.5", "", { "os": "win32", "cpu": "arm64" }, "sha512-gHv82k63z4qpV5+Q1y/12KrK0ltWBukVDI8nZcbT7Tt/ZlOIVwppazneq0F93oDxTo3IgAMEDIoQh3E2n6mVsw=="], + + "@rolldown/binding-win32-x64-msvc": ["@rolldown/binding-win32-x64-msvc@1.1.5", "", { "os": "win32", "cpu": "x64" }, "sha512-tTZuDBPw85tEN5PQi1pnEBzDy0Z49HtScLAbD5t6hyeU92A95pRWaSMw1GZZi/RwgSgUIl0xrSlXIT/9QzvYSA=="], + + "@rolldown/pluginutils": ["@rolldown/pluginutils@1.0.1", "", {}, "sha512-2j9bGt5Jh8hj+vPtgzPtl72j0yRxHAyumoo6TNfAjsLB04UtpSvPbPcDcBMxz7n+9CYB0c1GxQFxYRg2jimqGw=="], + + "@sindresorhus/is": ["@sindresorhus/is@7.2.0", "", {}, "sha512-P1Cz1dWaFfR4IR+U13mqqiGsLFf1KbayybWwdd2vfctdV6hDpUkgCY0nKOLLTMSoRd/jJNjtbqzf13K8DCCXQw=="], + + "@speed-highlight/core": ["@speed-highlight/core@1.2.24", "", {}, "sha512-qeW2e1l78afw8VhRPfPQ1Gjj+KU5XFQ/OFV5ti6eTa9bruO7mJyZtA4vw0ofqmA3tKCkROE9xLk3VZoeRc98nw=="], + + "@tybys/wasm-util": ["@tybys/wasm-util@0.10.4", "", { "dependencies": { "tslib": "^2.4.0" } }, "sha512-W3c4gRigFS0T/Ma4qIYF3GDAc5AQdHb1yL5znJT1Zv1YaD9Kitx656wBjvr19qbiosmZT8lWDM5BEMynUqX65A=="], + + "@types/bun": ["@types/bun@1.3.13", "", { "dependencies": { "bun-types": "1.3.13" } }, "sha512-9fqXWk5YIHGGnUau9TEi+qdlTYDAnOj+xLCmSTwXfAIqXr2x4tytJb43E9uCvt09zJURKXwAtkoH4nLQfzeTXw=="], + + "@types/node": ["@types/node@25.5.0", "", { "dependencies": { "undici-types": "~7.18.0" } }, "sha512-jp2P3tQMSxWugkCUKLRPVUpGaL5MVFwF8RDuSRztfwgN1wmqJeMSbKlnEtQqU8UrhTmzEmZdu2I6v2dpp7XIxw=="], + + "@types/react": ["@types/react@19.2.17", "", { "dependencies": { "csstype": "^3.2.2" } }, "sha512-MXfmqaVPEVgkBT/aY0aGCkRWWtByiYQXo3xdQ8r5RzuFrPiRn8Gar2tQdXSUQ2GKV3bkXckek89V8wQBY2Q/Aw=="], + + "@types/react-dom": ["@types/react-dom@19.2.3", "", { "peerDependencies": { "@types/react": "^19.2.0" } }, "sha512-jp2L/eY6fn+KgVVQAOqYItbF0VY/YApe5Mz2F0aykSO8gx31bYCZyvSeYxCHKvzHG5eZjc+zyaS5BrBWya2+kQ=="], + + "@vitejs/plugin-react": ["@vitejs/plugin-react@6.0.3", "", { "dependencies": { "@rolldown/pluginutils": "^1.0.1" }, "peerDependencies": { "@rolldown/plugin-babel": "^0.1.7 || ^0.2.0", "babel-plugin-react-compiler": "^1.0.0", "vite": "^8.0.0" }, "optionalPeers": ["@rolldown/plugin-babel", "babel-plugin-react-compiler"] }, "sha512-vmFvco5/QuC2f9Oj+wTk0+9XeDFkHxSamwZKYc7MxYwKICfvUvlMhqKI0VuICPltGqh1neqBKDvO4kes1ya8vg=="], + + "blake3-wasm": ["blake3-wasm@2.1.5", "", {}, "sha512-F1+K8EbfOZE49dtoPtmxUQrpXaBIl3ICvasLh+nJta0xkz+9kF/7uet9fLnwKqhDrmj6g+6K3Tw9yQPUg2ka5g=="], + + "bun-types": ["bun-types@1.3.13", "", { "dependencies": { "@types/node": "*" } }, "sha512-QXKeHLlOLqQX9LgYaHJfzdBaV21T63HhFJnvuRCcjZiaUDpbs5ED1MgxbMra71CsryN/1dAoXuJJJwIv/2drVA=="], + + "cf": ["cf@1.0.0-beta.12", "", { "dependencies": { "@cloudflare/build-output-utils": "0.8.5", "@cloudflare/codemods": "0.4.0", "@cloudflare/config": "0.23.0", "@cloudflare/runtime-types": "0.1.7", "blake3-wasm": "2.1.5", "miniflare": "5.20260930.0-alpha", "minisearch": "7.2.0" }, "bin": { "cf": "./bin/cf", "cloudflare": "./bin/cf" } }, "sha512-tyQ+Jpnw+4NDwDtl7ZNteXBm7N0TeJ6gYww79kkabpcYoCEXkUUpmt9BlDUKH8ub17tjAeiuyqa9NQzH0vp2Aw=="], + + "cookie": ["cookie@1.1.1", "", {}, "sha512-ei8Aos7ja0weRpFzJnEA9UHJ/7XQmqglbRwnf2ATjcB9Wq874VKH9kfjjirM6UhU2/E5fFYadylyhFldcqSidQ=="], + + "csstype": ["csstype@3.2.3", "", {}, "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ=="], + + "detect-libc": ["detect-libc@2.1.2", "", {}, "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ=="], + + "error-stack-parser-es": ["error-stack-parser-es@1.0.5", "", {}, "sha512-5qucVt2XcuGMcEGgWI7i+yZpmpByQ8J1lHhcL7PwqCwu9FPP3VUXzT4ltHe5i2z9dePwEHcDVOAfSnHsOlCXRA=="], + + "fdir": ["fdir@6.5.0", "", { "peerDependencies": { "picomatch": "^3 || ^4" }, "optionalPeers": ["picomatch"] }, "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg=="], + + "fsevents": ["fsevents@2.3.3", "", { "os": "darwin" }, "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw=="], + + "kleur": ["kleur@4.1.5", "", {}, "sha512-o+NO+8WrRiQEE4/7nwRJhN1HWpVmJm511pBHUxPLtp0BUISzlBplORYSmTclCnJvQq2tKu/sgl3xVpkc7ZWuQQ=="], + + "lightningcss": ["lightningcss@1.33.0", "", { "dependencies": { "detect-libc": "^2.0.3" }, "optionalDependencies": { "lightningcss-android-arm64": "1.33.0", "lightningcss-darwin-arm64": "1.33.0", "lightningcss-darwin-x64": "1.33.0", "lightningcss-freebsd-x64": "1.33.0", "lightningcss-linux-arm-gnueabihf": "1.33.0", "lightningcss-linux-arm64-gnu": "1.33.0", "lightningcss-linux-arm64-musl": "1.33.0", "lightningcss-linux-x64-gnu": "1.33.0", "lightningcss-linux-x64-musl": "1.33.0", "lightningcss-win32-arm64-msvc": "1.33.0", "lightningcss-win32-x64-msvc": "1.33.0" } }, "sha512-WkUDrojuJs0xkgGf2udWxa3yGBRxPtxUkB79i6aCZLRgc7PM8fZe9TosfPDcvEpQZbuFASnHYmRLBLUbmLOIIA=="], + + "lightningcss-android-arm64": ["lightningcss-android-arm64@1.33.0", "", { "os": "android", "cpu": "arm64" }, "sha512-gEpRTalKdosp4Bb8qWtc2iOgE5SeIHlpS1up9bFq2wAyYhl1UdTObYiHe98zEM9SQvSoqQZ1IQD0JNpg3Ml5pg=="], + + "lightningcss-darwin-arm64": ["lightningcss-darwin-arm64@1.33.0", "", { "os": "darwin", "cpu": "arm64" }, "sha512-Sciaz8eenNTKn9b3t7+xr0ipTp9YxKQY4npwQ3mrRuL0BAVHBLyZxofhaKBAVtzmtRZ/zTyo0/to4B1uWG/Djg=="], + + "lightningcss-darwin-x64": ["lightningcss-darwin-x64@1.33.0", "", { "os": "darwin", "cpu": "x64" }, "sha512-Z5UPAxzrjlWNNyGy6i65cJzzvgJ5D3T6wMvs+gWpY9d7qRhANrxqAp6LhxIgZhWEw18RfJTGcRxjuLIBr+m8XQ=="], + + "lightningcss-freebsd-x64": ["lightningcss-freebsd-x64@1.33.0", "", { "os": "freebsd", "cpu": "x64" }, "sha512-QQM/Ti/hQajJwCY+RiWuCZ9sdtI/XQk7nDK5vC8kkdwixezOlDgvDx7+RT+QjK6FcFT4MpsuoBnHIo/O3StRRg=="], + + "lightningcss-linux-arm-gnueabihf": ["lightningcss-linux-arm-gnueabihf@1.33.0", "", { "os": "linux", "cpu": "arm" }, "sha512-N7FVBe6iS24MlM6R/4RBTxGhQheZGs7tiQ9U32UtF75NzP5Q7xWPRqLBCKxlRQRk3rY1jCIPLzx7WzOhuUIRLQ=="], + + "lightningcss-linux-arm64-gnu": ["lightningcss-linux-arm64-gnu@1.33.0", "", { "os": "linux", "cpu": "arm64" }, "sha512-j2v/itmy4HlNxlc6voKXYgBqNi0Ng2LShg4z7GufpEgs05P+2suBVyi9I6YHq5uoVFx9ETin3eCEhLVyXGQnKg=="], + + "lightningcss-linux-arm64-musl": ["lightningcss-linux-arm64-musl@1.33.0", "", { "os": "linux", "cpu": "arm64" }, "sha512-yiO5ROMuYQgXbC60yjZU5CYSFZGKXL0HFATXt9mHJn1+zW55oCtMI9NfcVhYLMFDL7gV7oBPon/EmMMGg2OvtQ=="], + + "lightningcss-linux-x64-gnu": ["lightningcss-linux-x64-gnu@1.33.0", "", { "os": "linux", "cpu": "x64" }, "sha512-ar+Ju7LmcN0Jo4FpL4hpFybwNG9/3A/Br5KW2n2jyODg3MEZXaDYADdemoNS+BDNfMgKvylJLj4S5tyRActuAg=="], + + "lightningcss-linux-x64-musl": ["lightningcss-linux-x64-musl@1.33.0", "", { "os": "linux", "cpu": "x64" }, "sha512-RYiYbkokw0trfKqqzfF55lginwEPrD3OJDfTuJzFs1MK6iFnDenaz1fqLLtX4ITG3OktJQXOeTaw1awrBAlZPw=="], + + "lightningcss-win32-arm64-msvc": ["lightningcss-win32-arm64-msvc@1.33.0", "", { "os": "win32", "cpu": "arm64" }, "sha512-1K+MPfLSFVpphzpdbfkhlWk6wBrTObBzS2T6db10PNOZgR9GoVsAWzwNyuhUYYbTp23j+4RrncfujZ4uAzXvwA=="], + + "lightningcss-win32-x64-msvc": ["lightningcss-win32-x64-msvc@1.33.0", "", { "os": "win32", "cpu": "x64" }, "sha512-OlEICDx/Xl0FqSp4bry8zFnCvGpig3Gl4gCquvYwHuqJKEC1+n9NgDniFvqHGmMv1ZkqDJrDqKKSykTDX+ehuA=="], + + "miniflare": ["miniflare@5.20261019.2-beta", "", { "dependencies": { "@cspotcode/source-map-support": "0.8.1", "sharp": "0.35.5", "undici": "7.29.1", "workerd": "1.20261019.1", "ws": "8.21.0", "youch": "4.1.0-beta.10" } }, "sha512-QNgCA/axizZ7kv7RV3nwbRoz+w4watBlwIsyXjwgYHw4eSw5BrR1F2152s3Kz+Bzy/YxjKFHrZl3LzBRbPgYoQ=="], + + "minisearch": ["minisearch@7.2.0", "", {}, "sha512-dqT2XBYUOZOiC5t2HRnwADjhNS2cecp9u+TJRiJ1Qp/f5qjkeT5APcGPjHw+bz89Ms8Jp+cG4AlE+QZ/QnDglg=="], + + "nanoid": ["nanoid@3.3.20", "", { "bin": { "nanoid": "bin/nanoid.cjs" } }, "sha512-uKdg2G3GNCKQn9byYOpxbGqrT2fGO5KRt5J/8b3pok8rT6qxGWF6hxMyJiEYtAf+FVyYuD9hRaDqX5uPFYJ4ZQ=="], + + "pathe": ["pathe@2.0.3", "", {}, "sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w=="], + + "picocolors": ["picocolors@1.1.1", "", {}, "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA=="], + + "picomatch": ["picomatch@4.0.7", "", {}, "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA=="], + + "postcss": ["postcss@8.5.31", "", { "dependencies": { "nanoid": "^3.3.20", "picocolors": "^1.1.1", "source-map-js": "^1.2.2" } }, "sha512-YUbWYCgErwnMAVkjUnYa+KlMBzGpHwiIt/DE7f0G33AuX2LH9UcTk6KgWxd3zRU+pN3u/C+Xl3EnMLM4Hea7Sg=="], + + "react": ["react@19.2.7", "", {}, "sha512-HNe9WslTbXmFK8o8cmwgAeJFSBvt1bPdHCVKtaaV+WlAN36mpT4hcRpwbf3fY56ar2oIXzsBpOAiIRHAdY0OlQ=="], + + "react-dom": ["react-dom@19.2.7", "", { "dependencies": { "scheduler": "^0.27.0" }, "peerDependencies": { "react": "^19.2.7" } }, "sha512-t0BRVXvbiE/o20Hfw669rLbMCDWtYZLvmJigy2f0MxsXF+71pxhR3xOkspmsO8h3ZlNzyibAmtCa3l4lYKk6gQ=="], + + "rolldown": ["rolldown@1.1.5", "", { "dependencies": { "@oxc-project/types": "=0.139.0", "@rolldown/pluginutils": "^1.0.0" }, "optionalDependencies": { "@rolldown/binding-android-arm64": "1.1.5", "@rolldown/binding-darwin-arm64": "1.1.5", "@rolldown/binding-darwin-x64": "1.1.5", "@rolldown/binding-freebsd-x64": "1.1.5", "@rolldown/binding-linux-arm-gnueabihf": "1.1.5", "@rolldown/binding-linux-arm64-gnu": "1.1.5", "@rolldown/binding-linux-arm64-musl": "1.1.5", "@rolldown/binding-linux-ppc64-gnu": "1.1.5", "@rolldown/binding-linux-s390x-gnu": "1.1.5", "@rolldown/binding-linux-x64-gnu": "1.1.5", "@rolldown/binding-linux-x64-musl": "1.1.5", "@rolldown/binding-openharmony-arm64": "1.1.5", "@rolldown/binding-wasm32-wasi": "1.1.5", "@rolldown/binding-win32-arm64-msvc": "1.1.5", "@rolldown/binding-win32-x64-msvc": "1.1.5" }, "bin": { "rolldown": "./bin/cli.mjs" } }, "sha512-t9z29cJjXf/vxQ8dyhCSpt6H6aSwHTk8cT5I3iy6SMXuFpk5mB6PL6XfC8PCwrPTx93udwKUm9HRteAlTGBLiA=="], + + "scheduler": ["scheduler@0.27.0", "", {}, "sha512-eNv+WrVbKu1f3vbYJT/xtiF5syA5HPIMtf9IgY/nKg0sWqzAUEvqY/xm7OcZc/qafLx/iO9FgOmeSAp4v5ti/Q=="], + + "semver": ["semver@7.8.5", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA=="], + + "sharp": ["sharp@0.35.5", "", { "dependencies": { "@img/colour": "^1.1.0", "detect-libc": "^2.1.2", "semver": "^7.8.5" }, "optionalDependencies": { "@img/sharp-darwin-arm64": "0.35.5", "@img/sharp-darwin-x64": "0.35.5", "@img/sharp-freebsd-wasm32": "0.35.5", "@img/sharp-libvips-darwin-arm64": "1.3.4", "@img/sharp-libvips-darwin-x64": "1.3.4", "@img/sharp-libvips-linux-arm": "1.3.4", "@img/sharp-libvips-linux-arm64": "1.3.4", "@img/sharp-libvips-linux-ppc64": "1.3.4", "@img/sharp-libvips-linux-riscv64": "1.3.4", "@img/sharp-libvips-linux-s390x": "1.3.4", "@img/sharp-libvips-linux-x64": "1.3.4", "@img/sharp-libvips-linuxmusl-arm64": "1.3.4", "@img/sharp-libvips-linuxmusl-x64": "1.3.4", "@img/sharp-linux-arm": "0.35.5", "@img/sharp-linux-arm64": "0.35.5", "@img/sharp-linux-ppc64": "0.35.5", "@img/sharp-linux-riscv64": "0.35.5", "@img/sharp-linux-s390x": "0.35.5", "@img/sharp-linux-x64": "0.35.5", "@img/sharp-linuxmusl-arm64": "0.35.5", "@img/sharp-linuxmusl-x64": "0.35.5", "@img/sharp-webcontainers-wasm32": "0.35.5", "@img/sharp-win32-arm64": "0.35.5", "@img/sharp-win32-ia32": "0.35.5", "@img/sharp-win32-x64": "0.35.5" }, "peerDependencies": { "@types/node": "*" }, "optionalPeers": ["@types/node"] }, "sha512-Ywn4OnzGukp7CDMrp08RQ50YKmuwG47brZgIVPTvBaaAfQlRlygrRqSrxdCiL9M+LlzLBiJ68IR1QqvzHyjC7g=="], + + "source-map-js": ["source-map-js@1.2.2", "", {}, "sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw=="], + + "supports-color": ["supports-color@10.2.2", "", {}, "sha512-SS+jx45GF1QjgEXQx4NJZV9ImqmO2NPz5FNsIHrsDjh2YsHnawpan7SNQ1o8NuhrbHZy9AZhIoCUiCeaW/C80g=="], + + "tinyglobby": ["tinyglobby@0.2.17", "", { "dependencies": { "fdir": "^6.5.0", "picomatch": "^4.0.4" } }, "sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g=="], + + "tslib": ["tslib@2.8.1", "", {}, "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w=="], + + "typescript": ["typescript@6.0.2", "", { "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" } }, "sha512-bGdAIrZ0wiGDo5l8c++HWtbaNCWTS4UTv7RaTH/ThVIgjkveJt83m74bBHMJkuCbslY8ixgLBVZJIOiQlQTjfQ=="], + + "undici": ["undici@7.29.1", "", {}, "sha512-RYONW2MeafgYlkVOKYKkA/Ag7BmXqgIWCa8t1m0JcxrQg9pI9lEqRhAOruOBCbAohOa/gkCF+iPi9hrgvTzu6Q=="], + + "undici-types": ["undici-types@7.18.2", "", {}, "sha512-AsuCzffGHJybSaRrmr5eHr81mwJU3kjw6M+uprWvCXiNeN9SOGwQ3Jn8jb8m3Z6izVgknn1R0FTCEAP2QrLY/w=="], + + "unenv": ["unenv@2.0.0-rc.24", "", { "dependencies": { "pathe": "^2.0.3" } }, "sha512-i7qRCmY42zmCwnYlh9H2SvLEypEFGye5iRmEMKjcGi7zk9UquigRjFtTLz0TYqr0ZGLZhaMHl/foy1bZR+Cwlw=="], + + "vite": ["vite@8.1.3", "", { "dependencies": { "lightningcss": "^1.32.0", "picomatch": "^4.0.4", "postcss": "^8.5.16", "rolldown": "~1.1.3", "tinyglobby": "^0.2.17" }, "optionalDependencies": { "fsevents": "~2.3.3" }, "peerDependencies": { "@types/node": "^20.19.0 || >=22.12.0", "@vitejs/devtools": "^0.3.0", "esbuild": "^0.27.0 || ^0.28.0", "jiti": ">=1.21.0", "less": "^4.0.0", "sass": "^1.70.0", "sass-embedded": "^1.70.0", "stylus": ">=0.54.8", "sugarss": "^5.0.0", "terser": "^5.16.0", "tsx": "^4.8.1", "yaml": "^2.4.2" }, "optionalPeers": ["@types/node", "@vitejs/devtools", "esbuild", "jiti", "less", "sass", "sass-embedded", "stylus", "sugarss", "terser", "tsx", "yaml"], "bin": { "vite": "bin/vite.js" } }, "sha512-Ds+gBRbj0lwRO2Y5hwnUBdxSwlAve9LeRyU4sNnAr0ewW0gWF0n5bgXgUzbgZ49MV9BVUAQUFYVcDUcilUExMA=="], + + "workerd": ["workerd@1.20261019.1", "", { "optionalDependencies": { "@cloudflare/workerd-darwin-64": "1.20261019.1", "@cloudflare/workerd-darwin-arm64": "1.20261019.1", "@cloudflare/workerd-linux-64": "1.20261019.1", "@cloudflare/workerd-linux-arm64": "1.20261019.1", "@cloudflare/workerd-windows-64": "1.20261019.1" }, "bin": { "workerd": "bin/workerd" } }, "sha512-UUYRUq/7DmeCl11YriNbcVbjUZVLtt8uuCXFu+nz77hGFf8d4DEVXoCYtnA+MlBatE4+wxoj47DVqzK3xGBAiw=="], + + "ws": ["ws@8.21.0", "", { "peerDependencies": { "bufferutil": "^4.0.1", "utf-8-validate": ">=5.0.2" }, "optionalPeers": ["bufferutil", "utf-8-validate"] }, "sha512-Vsp28b7DRcimFQvrqu2Wek3z1iYxDCWqHYB8Qsnk/S4RfaCQzPGPyBNuVjJV3cd6UiKtUtp6sNM77gWvzcCH+g=="], + + "youch": ["youch@4.1.0-beta.10", "", { "dependencies": { "@poppinss/colors": "^4.1.5", "@poppinss/dumper": "^0.6.4", "@speed-highlight/core": "^1.2.7", "cookie": "^1.0.2", "youch-core": "^0.3.3" } }, "sha512-rLfVLB4FgQneDr0dv1oddCVZmKjcJ6yX6mS4pU82Mq/Dt9a3cLZQ62pDBL4AUO+uVrCvtWz3ZFUL2HFAFJ/BXQ=="], + + "youch-core": ["youch-core@0.3.3", "", { "dependencies": { "@poppinss/exception": "^1.2.2", "error-stack-parser-es": "^1.0.5" } }, "sha512-ho7XuGjLaJ2hWHoK8yFnsUGy2Y5uDpqSTq1FkHLK4/oqKtyUU1AFbOOxY4IpC9f0fTLjwYbslUz0Po5BpD1wrA=="], + + "zod": ["zod@4.4.3", "", {}, "sha512-ytENFjIJFl2UwYglde2jchW2Hwm4GJFLDiSXWdTrJQBIN9Fcyp7n4DhxJEiWNAJMV1/BqWfW/kkg71UDcHJyTQ=="], + + "@cloudflare/vite-plugin/@cloudflare/build-output-utils": ["@cloudflare/build-output-utils@0.9.4", "", { "dependencies": { "@cloudflare/config": "0.28.0" } }, "sha512-5rVdn81HEP2Uugs/wSfXu5XbadaZQkgKZl1xwkKb3kgatSOpTH2vszBXWTRh4IlE1vHnc3LwHcnc2O4TcXVbuQ=="], + + "@cloudflare/vite-plugin/@cloudflare/config": ["@cloudflare/config@0.28.0", "", { "dependencies": { "zod": "4.6.5" } }, "sha512-2SaZn5rzNSxAR5VQYIlMm8+zHj2EGfLbaN+abYiPXDI42IFRCHSENpDxjAQpLj2NZnUVszHY4h6T1XljwHk5eQ=="], + + "@img/sharp-wasm32/@emnapi/runtime": ["@emnapi/runtime@1.11.3", "", { "dependencies": { "tslib": "^2.4.0" } }, "sha512-Xz4Tpyki7XyrpbUK1jR1AhdAdaXyhhY4lZ3neLodmhpuWfy2PAQN5B46sAiU4liOXGLkHypn/qU+jvfWSCYYLA=="], + + "cf/@cloudflare/runtime-types": ["@cloudflare/runtime-types@0.1.7", "", { "dependencies": { "miniflare": "5.20261001.0-alpha", "workerd": "1.20261001.1" } }, "sha512-avgC1wfTunbVea8HOq4ygiQ0WFQVNxcUHOQvH9TM47+0NTdsVTqB8rPQg6Tb5BfVkcWh/a0RAjk+Elr/h35mtQ=="], + + "cf/miniflare": ["miniflare@5.20260930.0-alpha", "", { "dependencies": { "@cspotcode/source-map-support": "0.8.1", "sharp": "0.35.4", "undici": "7.29.1", "workerd": "1.20260930.2", "ws": "8.21.0", "youch": "4.1.0-beta.10" } }, "sha512-vZljfRtOEeynbhJtuvYsnCU8t6zF5wIUm9ql4YFHB7zvYw2+F2tpT0BzXjzaa++eiUIml1gsODCf02qShBmJdg=="], + + "@cloudflare/vite-plugin/@cloudflare/config/zod": ["zod@4.6.5", "", {}, "sha512-v5l/aFXZQeai4awLbOpSoHecE9UiMrnfx75tEXLjNonXVARxQ5mOeipTjROUchszUNCqnE+hqAMujRsRHsut2Q=="], + + "cf/@cloudflare/runtime-types/miniflare": ["miniflare@5.20261001.0-alpha", "", { "dependencies": { "@cspotcode/source-map-support": "0.8.1", "sharp": "0.35.4", "undici": "7.29.1", "workerd": "1.20261001.1", "ws": "8.21.0", "youch": "4.1.0-beta.10" } }, "sha512-GaimS5mSIOMyvd16ga+e1/QkI8cmp3z35QPHFex0DktqNQf2RVZQwMPQXdyoUreUiFP/0Gpe2MoQInTyMAD5xA=="], + + "cf/@cloudflare/runtime-types/workerd": ["workerd@1.20261001.1", "", { "optionalDependencies": { "@cloudflare/workerd-darwin-64": "1.20261001.1", "@cloudflare/workerd-darwin-arm64": "1.20261001.1", "@cloudflare/workerd-linux-64": "1.20261001.1", "@cloudflare/workerd-linux-arm64": "1.20261001.1", "@cloudflare/workerd-windows-64": "1.20261001.1" }, "bin": { "workerd": "bin/workerd" } }, "sha512-d/SIYHFO0PT/wiFZg8in4NpRIxYuFwslX1HdylOtWkBIIUmSpkGFhK820cV84XACFylwJ48xuRoWW/8DWDPsPQ=="], + + "cf/miniflare/sharp": ["sharp@0.35.4", "", { "dependencies": { "@img/colour": "^1.1.0", "detect-libc": "^2.1.2", "semver": "^7.8.5" }, "optionalDependencies": { "@img/sharp-darwin-arm64": "0.35.4", "@img/sharp-darwin-x64": "0.35.4", "@img/sharp-freebsd-wasm32": "0.35.4", "@img/sharp-libvips-darwin-arm64": "1.3.3", "@img/sharp-libvips-darwin-x64": "1.3.3", "@img/sharp-libvips-linux-arm": "1.3.3", "@img/sharp-libvips-linux-arm64": "1.3.3", "@img/sharp-libvips-linux-ppc64": "1.3.3", "@img/sharp-libvips-linux-riscv64": "1.3.3", "@img/sharp-libvips-linux-s390x": "1.3.3", "@img/sharp-libvips-linux-x64": "1.3.3", "@img/sharp-libvips-linuxmusl-arm64": "1.3.3", "@img/sharp-libvips-linuxmusl-x64": "1.3.3", "@img/sharp-linux-arm": "0.35.4", "@img/sharp-linux-arm64": "0.35.4", "@img/sharp-linux-ppc64": "0.35.4", "@img/sharp-linux-riscv64": "0.35.4", "@img/sharp-linux-s390x": "0.35.4", "@img/sharp-linux-x64": "0.35.4", "@img/sharp-linuxmusl-arm64": "0.35.4", "@img/sharp-linuxmusl-x64": "0.35.4", "@img/sharp-webcontainers-wasm32": "0.35.4", "@img/sharp-win32-arm64": "0.35.4", "@img/sharp-win32-ia32": "0.35.4", "@img/sharp-win32-x64": "0.35.4" }, "peerDependencies": { "@types/node": "*" }, "optionalPeers": ["@types/node"] }, "sha512-n++8XWcj+jCOr2IOl7h8LbKnGBDY4aPbmprMONBNFdn0ImXqpGVv5zliDs0V9HbmbCQLpbuo2ej9rAoOQTvMDA=="], + + "cf/miniflare/workerd": ["workerd@1.20260930.2", "", { "optionalDependencies": { "@cloudflare/workerd-darwin-64": "1.20260930.2", "@cloudflare/workerd-darwin-arm64": "1.20260930.2", "@cloudflare/workerd-linux-64": "1.20260930.2", "@cloudflare/workerd-linux-arm64": "1.20260930.2", "@cloudflare/workerd-windows-64": "1.20260930.2" }, "bin": { "workerd": "bin/workerd" } }, "sha512-k1lQzEiGyCDqaRsR5+o9PBT5wVU5omtas6hXx3spbEHHMFo8a7tkAixVCMsWFeiT7xhrmg21Hd6a9jLNrkcUMg=="], + + "cf/@cloudflare/runtime-types/miniflare/sharp": ["sharp@0.35.4", "", { "dependencies": { "@img/colour": "^1.1.0", "detect-libc": "^2.1.2", "semver": "^7.8.5" }, "optionalDependencies": { "@img/sharp-darwin-arm64": "0.35.4", "@img/sharp-darwin-x64": "0.35.4", "@img/sharp-freebsd-wasm32": "0.35.4", "@img/sharp-libvips-darwin-arm64": "1.3.3", "@img/sharp-libvips-darwin-x64": "1.3.3", "@img/sharp-libvips-linux-arm": "1.3.3", "@img/sharp-libvips-linux-arm64": "1.3.3", "@img/sharp-libvips-linux-ppc64": "1.3.3", "@img/sharp-libvips-linux-riscv64": "1.3.3", "@img/sharp-libvips-linux-s390x": "1.3.3", "@img/sharp-libvips-linux-x64": "1.3.3", "@img/sharp-libvips-linuxmusl-arm64": "1.3.3", "@img/sharp-libvips-linuxmusl-x64": "1.3.3", "@img/sharp-linux-arm": "0.35.4", "@img/sharp-linux-arm64": "0.35.4", "@img/sharp-linux-ppc64": "0.35.4", "@img/sharp-linux-riscv64": "0.35.4", "@img/sharp-linux-s390x": "0.35.4", "@img/sharp-linux-x64": "0.35.4", "@img/sharp-linuxmusl-arm64": "0.35.4", "@img/sharp-linuxmusl-x64": "0.35.4", "@img/sharp-webcontainers-wasm32": "0.35.4", "@img/sharp-win32-arm64": "0.35.4", "@img/sharp-win32-ia32": "0.35.4", "@img/sharp-win32-x64": "0.35.4" }, "peerDependencies": { "@types/node": "*" }, "optionalPeers": ["@types/node"] }, "sha512-n++8XWcj+jCOr2IOl7h8LbKnGBDY4aPbmprMONBNFdn0ImXqpGVv5zliDs0V9HbmbCQLpbuo2ej9rAoOQTvMDA=="], + + "cf/@cloudflare/runtime-types/workerd/@cloudflare/workerd-darwin-64": ["@cloudflare/workerd-darwin-64@1.20261001.1", "", { "os": "darwin", "cpu": "x64" }, "sha512-4cgSgDf28JSw/P5Dj5GCS59hzVqS5XnmGAWNkvYHLI6ODU9idGaMMNEuhJXDkEG/lsABmlVlnCgsdh2VbKWepw=="], + + "cf/@cloudflare/runtime-types/workerd/@cloudflare/workerd-darwin-arm64": ["@cloudflare/workerd-darwin-arm64@1.20261001.1", "", { "os": "darwin", "cpu": "arm64" }, "sha512-8ulAWruEVouNmEIsQsy9WSSCS9zkLu93W2MTwp5esiFyoPp05BNSVFIFsYSPi1pkFmBBd7fsnwMpbLkaJLaVPQ=="], + + "cf/@cloudflare/runtime-types/workerd/@cloudflare/workerd-linux-64": ["@cloudflare/workerd-linux-64@1.20261001.1", "", { "os": "linux", "cpu": "x64" }, "sha512-kZbTZJGrhsMOdqZ2BIybjaBRLZjYsRLWj7mcNw/6Y3hodOhp5MrNzcz4iWGwNVWwyIV+7Pl+/LX5VcgnRqdHOg=="], + + "cf/@cloudflare/runtime-types/workerd/@cloudflare/workerd-linux-arm64": ["@cloudflare/workerd-linux-arm64@1.20261001.1", "", { "os": "linux", "cpu": "arm64" }, "sha512-oOk3Zj6k/8oP0FJgZBWDn7+BqbsqIMEMaV95pulHPVbwVu4wYoLfQq2hp0vkbCNsCFLqZb7cqixXdrwD54ZIow=="], + + "cf/@cloudflare/runtime-types/workerd/@cloudflare/workerd-windows-64": ["@cloudflare/workerd-windows-64@1.20261001.1", "", { "os": "win32", "cpu": "x64" }, "sha512-uRxm5W4VyBkoSaoP1BfOuH0873tE+vxsknF4sab6/5YIRvIAufChq3QDp+zlAn67PuGPGcn7W8QraA0t4ucmOQ=="], + + "cf/miniflare/sharp/@img/sharp-darwin-arm64": ["@img/sharp-darwin-arm64@0.35.4", "", { "optionalDependencies": { "@img/sharp-libvips-darwin-arm64": "1.3.3" }, "os": "darwin", "cpu": "arm64" }, "sha512-Uhfl4V4lhP2nbUVF9+hyH1+luj86f1gUFeo8ALYxFoULoU+G87D43BfeMP8XHsk9boxAnCY/bf2EHwhA7MuGsA=="], + + "cf/miniflare/sharp/@img/sharp-darwin-x64": ["@img/sharp-darwin-x64@0.35.4", "", { "optionalDependencies": { "@img/sharp-libvips-darwin-x64": "1.3.3" }, "os": "darwin", "cpu": "x64" }, "sha512-hWniXY3bG5qKpkKrAwPe4y+VTPmf086YQAnkxWh7uA1YrlRouWGa0M0Mxj3ZjnXFkv7/TD1bTy9lGUK26vRvWw=="], + + "cf/miniflare/sharp/@img/sharp-freebsd-wasm32": ["@img/sharp-freebsd-wasm32@0.35.4", "", { "dependencies": { "@img/sharp-wasm32": "0.35.4" }, "os": "freebsd" }, "sha512-lIsKw/BU+kjB4eZjxrYrZmwOJYi3Ajrv66iAlBmUPyKc3HpnloevB1g3wxGD9P/5BbQ1brBGl65VRRrCvQDEqA=="], + + "cf/miniflare/sharp/@img/sharp-libvips-darwin-arm64": ["@img/sharp-libvips-darwin-arm64@1.3.3", "", { "os": "darwin", "cpu": "arm64" }, "sha512-suTBPTDGrI9WodccaDdwZItTSaBYASlBk1NSfElSHrUfzu3szG6lvIF58+WiFvnfzuK8ZBFS5zE00PxqxnRiPg=="], + + "cf/miniflare/sharp/@img/sharp-libvips-darwin-x64": ["@img/sharp-libvips-darwin-x64@1.3.3", "", { "os": "darwin", "cpu": "x64" }, "sha512-FVJZ5mITMobmXIz/hPDTw0EintTW5H3WfrxwLqEqjiIihlu+hVRyGrFQ60xl0Lxn7Bt3zdpevPaQi0HEzqz9fw=="], + + "cf/miniflare/sharp/@img/sharp-libvips-linux-arm": ["@img/sharp-libvips-linux-arm@1.3.3", "", { "os": "linux", "cpu": "arm" }, "sha512-3rbU4vqXXc3hY/OiXdl52xZvT0F1yEngWfvqudtPJg/KkyiaQw2DRsFrNzpmLvfavbwOq3qXn36GP8obHRULQA=="], + + "cf/miniflare/sharp/@img/sharp-libvips-linux-arm64": ["@img/sharp-libvips-linux-arm64@1.3.3", "", { "os": "linux", "cpu": "arm64" }, "sha512-0DaL0A6Xu6sQSQFwe4iVCrKWU2cCTItnRsYsCdxAMm9NF6twAA9BKnoqy4hqz4+azQ0JHuA26qiUKsf1XJ/v5A=="], + + "cf/miniflare/sharp/@img/sharp-libvips-linux-ppc64": ["@img/sharp-libvips-linux-ppc64@1.3.3", "", { "os": "linux", "cpu": "ppc64" }, "sha512-cdn1OvUBwsXhbC0zSzJnNzf5MZ/mTrobawDvNXBTxe8VtqKAm0sRuEY2Evzovb/w9JMk4TvRxqt1mekSuJz64w=="], + + "cf/miniflare/sharp/@img/sharp-libvips-linux-riscv64": ["@img/sharp-libvips-linux-riscv64@1.3.3", "", { "os": "linux", "cpu": "none" }, "sha512-HjPVx7yKz+0lqdhDlTw1tt90wamBoxhiXpvl1XZpJLiHH4RCJ5yDTqH+VlYPv2fwFs89JFw4c1IexYOcQUi4IQ=="], + + "cf/miniflare/sharp/@img/sharp-libvips-linux-s390x": ["@img/sharp-libvips-linux-s390x@1.3.3", "", { "os": "linux", "cpu": "s390x" }, "sha512-neWLh+3yCNThxnfy3c4BbVBeGgt9aftno+XbT56iK28RgeDs3UOFWviLWlUu0bArYVYJaFDK+RRohbicUNCm8Q=="], + + "cf/miniflare/sharp/@img/sharp-libvips-linux-x64": ["@img/sharp-libvips-linux-x64@1.3.3", "", { "os": "linux", "cpu": "x64" }, "sha512-4vKmvAst9nrowcqquKFAyZJUDolUaIp8uRiN0mWFguJ1IplC9/pitXtlnnlU4aa/eJw3J7i67V+pwUL+wZGdsA=="], + + "cf/miniflare/sharp/@img/sharp-libvips-linuxmusl-arm64": ["@img/sharp-libvips-linuxmusl-arm64@1.3.3", "", { "os": "linux", "cpu": "arm64" }, "sha512-Y9kQaLMuNoB0bPYOOdcZMaseNrFpPodIWWMrx+CZyydf2xn68j9WYc6sWWRrDwNkzCQjKYfc68L7jKjGlHMibw=="], + + "cf/miniflare/sharp/@img/sharp-libvips-linuxmusl-x64": ["@img/sharp-libvips-linuxmusl-x64@1.3.3", "", { "os": "linux", "cpu": "x64" }, "sha512-fj8Mv0HHfD1Rr+4I68+3agJynxDWtBFgicTbSOb9Bke6pIwzGcJ+RX/yHjmiEGFMCavY/dxvem7MyNaJF+wDiw=="], + + "cf/miniflare/sharp/@img/sharp-linux-arm": ["@img/sharp-linux-arm@0.35.4", "", { "optionalDependencies": { "@img/sharp-libvips-linux-arm": "1.3.3" }, "os": "linux", "cpu": "arm" }, "sha512-7OAS8gI0EReKGVN2HssHlM6umJgxF5VI3xN0p9FA91p/YO+ou5hiNghLdZ5BEHztwaaK5+bLKRf8x/o2L2nk9A=="], + + "cf/miniflare/sharp/@img/sharp-linux-arm64": ["@img/sharp-linux-arm64@0.35.4", "", { "optionalDependencies": { "@img/sharp-libvips-linux-arm64": "1.3.3" }, "os": "linux", "cpu": "arm64" }, "sha512-De4jpEnAU8Hd5oT0j1G3uL4ZvTuipVMn7YC6vPaJhy6/7EwEae0SVAoBrUMYQbkLGDm85taVWwuPc1a44LTzCQ=="], + + "cf/miniflare/sharp/@img/sharp-linux-ppc64": ["@img/sharp-linux-ppc64@0.35.4", "", { "optionalDependencies": { "@img/sharp-libvips-linux-ppc64": "1.3.3" }, "os": "linux", "cpu": "ppc64" }, "sha512-2oYZJeIl4kCcMGk4ouZVjnkCtFrpQFlNEtJ6GbxzhHQchwH0NH/qEb9ykmOl29dqwMq+JhFdZn+1ak2FKhI9fQ=="], + + "cf/miniflare/sharp/@img/sharp-linux-riscv64": ["@img/sharp-linux-riscv64@0.35.4", "", { "optionalDependencies": { "@img/sharp-libvips-linux-riscv64": "1.3.3" }, "os": "linux", "cpu": "none" }, "sha512-cPbNChoRURAWdebDIHSenxRpgEdy7JkPydSnUxRm9VvKD7m0/xVaR/8Fzlu81pk5nHEvHH87UZUA7cTtwnbJSA=="], + + "cf/miniflare/sharp/@img/sharp-linux-s390x": ["@img/sharp-linux-s390x@0.35.4", "", { "optionalDependencies": { "@img/sharp-libvips-linux-s390x": "1.3.3" }, "os": "linux", "cpu": "s390x" }, "sha512-RY0JFY8Fd6RonCBtHz+DvadaPkXDSI1AUn6yWL9TipqkZ1vY8w8evqdgyDFnkm4/K1ve1TvZiaePP5oSd4+WVQ=="], + + "cf/miniflare/sharp/@img/sharp-linux-x64": ["@img/sharp-linux-x64@0.35.4", "", { "optionalDependencies": { "@img/sharp-libvips-linux-x64": "1.3.3" }, "os": "linux", "cpu": "x64" }, "sha512-9qvvEAuk8k89TfWUoX2htWjbAMX8p+NxCppjpcg5k6xMsjhBQPTsoIh36h9Qde4WRuGpJeYnOjdosDn/cnv+OA=="], + + "cf/miniflare/sharp/@img/sharp-linuxmusl-arm64": ["@img/sharp-linuxmusl-arm64@0.35.4", "", { "optionalDependencies": { "@img/sharp-libvips-linuxmusl-arm64": "1.3.3" }, "os": "linux", "cpu": "arm64" }, "sha512-KB5jxpfWQTr0nc3xdHtWChdbifHrBGsd2SM62Eyxrl8afikm+f5qGBU75SJIZBT/S1MC8XyacdlXBMSWq6OURA=="], + + "cf/miniflare/sharp/@img/sharp-linuxmusl-x64": ["@img/sharp-linuxmusl-x64@0.35.4", "", { "optionalDependencies": { "@img/sharp-libvips-linuxmusl-x64": "1.3.3" }, "os": "linux", "cpu": "x64" }, "sha512-f+eZJZIQNEEd26RPSW+76chwOf1XtA2Y/O+5ocVyLliHkeih3e+jhLVBdNTd2rS3IbNXK8+ug93Vf5ZXtF5Lxg=="], + + "cf/miniflare/sharp/@img/sharp-webcontainers-wasm32": ["@img/sharp-webcontainers-wasm32@0.35.4", "", { "dependencies": { "@img/sharp-wasm32": "0.35.4" }, "cpu": "none" }, "sha512-ESfNkywmCfPNyaZjxooddJQiQ+l/nTpGEOGthxiLnIHXC/CmcBixnfwUleX9mCz9ovrUUvKMap/pm8RYbzfwaA=="], + + "cf/miniflare/sharp/@img/sharp-win32-arm64": ["@img/sharp-win32-arm64@0.35.4", "", { "os": "win32", "cpu": "arm64" }, "sha512-iNdlBX9gLVvqe2I3uIJSIKTq6wckP/DYxZtcqxm09x5Gi24DnFBmPAWZmr60ZyYMG0xlzo6goG3670ar+RXvRw=="], + + "cf/miniflare/sharp/@img/sharp-win32-ia32": ["@img/sharp-win32-ia32@0.35.4", "", { "os": "win32", "cpu": "ia32" }, "sha512-kqRsbaa5CS6KHlpxnN7WhE6vAAugXyZButpRdvDWetlv6Qv4N9WTcrWzF7tXfB9T7MsoadqdI8hmwLq6UlLvtw=="], + + "cf/miniflare/sharp/@img/sharp-win32-x64": ["@img/sharp-win32-x64@0.35.4", "", { "os": "win32", "cpu": "x64" }, "sha512-XtmnYhBcrORsJ4XJngyzr/EWP0hRZLAZRFaApdKuviyqF78+ylxh2y06ZmtULAMOnObJ3ucpN0AcwSWnMowTRg=="], + + "cf/miniflare/workerd/@cloudflare/workerd-darwin-64": ["@cloudflare/workerd-darwin-64@1.20260930.2", "", { "os": "darwin", "cpu": "x64" }, "sha512-wxKsfekWeev6xkjHEMx3x7nz6WfWOn1/scQ8geqWQhUm8qRl1ZRZhjnj+rucIMLhLhP9RGSYMZIjEm3AV0zwVQ=="], + + "cf/miniflare/workerd/@cloudflare/workerd-darwin-arm64": ["@cloudflare/workerd-darwin-arm64@1.20260930.2", "", { "os": "darwin", "cpu": "arm64" }, "sha512-cviPpheZGQ2H5X+Ctxd3wfxhksNrdyoNprjSgg3br2+psetKacjdEvK8CILdN/2GF+u1KOExvr45amSL6lgzGA=="], + + "cf/miniflare/workerd/@cloudflare/workerd-linux-64": ["@cloudflare/workerd-linux-64@1.20260930.2", "", { "os": "linux", "cpu": "x64" }, "sha512-cwrJAC5y/avPd1OzGyhc5OvUUfPXBFc065TY5CjXp7Hb3dhiTx6JeB5Pc8L3G8L8M44HyAfRHSpoLtRr+SR3cQ=="], + + "cf/miniflare/workerd/@cloudflare/workerd-linux-arm64": ["@cloudflare/workerd-linux-arm64@1.20260930.2", "", { "os": "linux", "cpu": "arm64" }, "sha512-FHucB4gak1IuT+IxLx3KbtMBMapZhcqD9EdhHvBxk1FpHwD2QU5x26MRRVN53jIKG/O25HUmE9yffb3cMANQgw=="], + + "cf/miniflare/workerd/@cloudflare/workerd-windows-64": ["@cloudflare/workerd-windows-64@1.20260930.2", "", { "os": "win32", "cpu": "x64" }, "sha512-JHFMdGFMqP+M2QiVzZq1S8Ie66Gvxo7Og5EYz/KtmDvGCqge5L3lK+ksZxAhF3j/tpSLqdvlUvcTKoR9PkwTTQ=="], + + "cf/@cloudflare/runtime-types/miniflare/sharp/@img/sharp-darwin-arm64": ["@img/sharp-darwin-arm64@0.35.4", "", { "optionalDependencies": { "@img/sharp-libvips-darwin-arm64": "1.3.3" }, "os": "darwin", "cpu": "arm64" }, "sha512-Uhfl4V4lhP2nbUVF9+hyH1+luj86f1gUFeo8ALYxFoULoU+G87D43BfeMP8XHsk9boxAnCY/bf2EHwhA7MuGsA=="], + + "cf/@cloudflare/runtime-types/miniflare/sharp/@img/sharp-darwin-x64": ["@img/sharp-darwin-x64@0.35.4", "", { "optionalDependencies": { "@img/sharp-libvips-darwin-x64": "1.3.3" }, "os": "darwin", "cpu": "x64" }, "sha512-hWniXY3bG5qKpkKrAwPe4y+VTPmf086YQAnkxWh7uA1YrlRouWGa0M0Mxj3ZjnXFkv7/TD1bTy9lGUK26vRvWw=="], + + "cf/@cloudflare/runtime-types/miniflare/sharp/@img/sharp-freebsd-wasm32": ["@img/sharp-freebsd-wasm32@0.35.4", "", { "dependencies": { "@img/sharp-wasm32": "0.35.4" }, "os": "freebsd" }, "sha512-lIsKw/BU+kjB4eZjxrYrZmwOJYi3Ajrv66iAlBmUPyKc3HpnloevB1g3wxGD9P/5BbQ1brBGl65VRRrCvQDEqA=="], + + "cf/@cloudflare/runtime-types/miniflare/sharp/@img/sharp-libvips-darwin-arm64": ["@img/sharp-libvips-darwin-arm64@1.3.3", "", { "os": "darwin", "cpu": "arm64" }, "sha512-suTBPTDGrI9WodccaDdwZItTSaBYASlBk1NSfElSHrUfzu3szG6lvIF58+WiFvnfzuK8ZBFS5zE00PxqxnRiPg=="], + + "cf/@cloudflare/runtime-types/miniflare/sharp/@img/sharp-libvips-darwin-x64": ["@img/sharp-libvips-darwin-x64@1.3.3", "", { "os": "darwin", "cpu": "x64" }, "sha512-FVJZ5mITMobmXIz/hPDTw0EintTW5H3WfrxwLqEqjiIihlu+hVRyGrFQ60xl0Lxn7Bt3zdpevPaQi0HEzqz9fw=="], + + "cf/@cloudflare/runtime-types/miniflare/sharp/@img/sharp-libvips-linux-arm": ["@img/sharp-libvips-linux-arm@1.3.3", "", { "os": "linux", "cpu": "arm" }, "sha512-3rbU4vqXXc3hY/OiXdl52xZvT0F1yEngWfvqudtPJg/KkyiaQw2DRsFrNzpmLvfavbwOq3qXn36GP8obHRULQA=="], + + "cf/@cloudflare/runtime-types/miniflare/sharp/@img/sharp-libvips-linux-arm64": ["@img/sharp-libvips-linux-arm64@1.3.3", "", { "os": "linux", "cpu": "arm64" }, "sha512-0DaL0A6Xu6sQSQFwe4iVCrKWU2cCTItnRsYsCdxAMm9NF6twAA9BKnoqy4hqz4+azQ0JHuA26qiUKsf1XJ/v5A=="], + + "cf/@cloudflare/runtime-types/miniflare/sharp/@img/sharp-libvips-linux-ppc64": ["@img/sharp-libvips-linux-ppc64@1.3.3", "", { "os": "linux", "cpu": "ppc64" }, "sha512-cdn1OvUBwsXhbC0zSzJnNzf5MZ/mTrobawDvNXBTxe8VtqKAm0sRuEY2Evzovb/w9JMk4TvRxqt1mekSuJz64w=="], + + "cf/@cloudflare/runtime-types/miniflare/sharp/@img/sharp-libvips-linux-riscv64": ["@img/sharp-libvips-linux-riscv64@1.3.3", "", { "os": "linux", "cpu": "none" }, "sha512-HjPVx7yKz+0lqdhDlTw1tt90wamBoxhiXpvl1XZpJLiHH4RCJ5yDTqH+VlYPv2fwFs89JFw4c1IexYOcQUi4IQ=="], + + "cf/@cloudflare/runtime-types/miniflare/sharp/@img/sharp-libvips-linux-s390x": ["@img/sharp-libvips-linux-s390x@1.3.3", "", { "os": "linux", "cpu": "s390x" }, "sha512-neWLh+3yCNThxnfy3c4BbVBeGgt9aftno+XbT56iK28RgeDs3UOFWviLWlUu0bArYVYJaFDK+RRohbicUNCm8Q=="], + + "cf/@cloudflare/runtime-types/miniflare/sharp/@img/sharp-libvips-linux-x64": ["@img/sharp-libvips-linux-x64@1.3.3", "", { "os": "linux", "cpu": "x64" }, "sha512-4vKmvAst9nrowcqquKFAyZJUDolUaIp8uRiN0mWFguJ1IplC9/pitXtlnnlU4aa/eJw3J7i67V+pwUL+wZGdsA=="], + + "cf/@cloudflare/runtime-types/miniflare/sharp/@img/sharp-libvips-linuxmusl-arm64": ["@img/sharp-libvips-linuxmusl-arm64@1.3.3", "", { "os": "linux", "cpu": "arm64" }, "sha512-Y9kQaLMuNoB0bPYOOdcZMaseNrFpPodIWWMrx+CZyydf2xn68j9WYc6sWWRrDwNkzCQjKYfc68L7jKjGlHMibw=="], + + "cf/@cloudflare/runtime-types/miniflare/sharp/@img/sharp-libvips-linuxmusl-x64": ["@img/sharp-libvips-linuxmusl-x64@1.3.3", "", { "os": "linux", "cpu": "x64" }, "sha512-fj8Mv0HHfD1Rr+4I68+3agJynxDWtBFgicTbSOb9Bke6pIwzGcJ+RX/yHjmiEGFMCavY/dxvem7MyNaJF+wDiw=="], + + "cf/@cloudflare/runtime-types/miniflare/sharp/@img/sharp-linux-arm": ["@img/sharp-linux-arm@0.35.4", "", { "optionalDependencies": { "@img/sharp-libvips-linux-arm": "1.3.3" }, "os": "linux", "cpu": "arm" }, "sha512-7OAS8gI0EReKGVN2HssHlM6umJgxF5VI3xN0p9FA91p/YO+ou5hiNghLdZ5BEHztwaaK5+bLKRf8x/o2L2nk9A=="], + + "cf/@cloudflare/runtime-types/miniflare/sharp/@img/sharp-linux-arm64": ["@img/sharp-linux-arm64@0.35.4", "", { "optionalDependencies": { "@img/sharp-libvips-linux-arm64": "1.3.3" }, "os": "linux", "cpu": "arm64" }, "sha512-De4jpEnAU8Hd5oT0j1G3uL4ZvTuipVMn7YC6vPaJhy6/7EwEae0SVAoBrUMYQbkLGDm85taVWwuPc1a44LTzCQ=="], + + "cf/@cloudflare/runtime-types/miniflare/sharp/@img/sharp-linux-ppc64": ["@img/sharp-linux-ppc64@0.35.4", "", { "optionalDependencies": { "@img/sharp-libvips-linux-ppc64": "1.3.3" }, "os": "linux", "cpu": "ppc64" }, "sha512-2oYZJeIl4kCcMGk4ouZVjnkCtFrpQFlNEtJ6GbxzhHQchwH0NH/qEb9ykmOl29dqwMq+JhFdZn+1ak2FKhI9fQ=="], + + "cf/@cloudflare/runtime-types/miniflare/sharp/@img/sharp-linux-riscv64": ["@img/sharp-linux-riscv64@0.35.4", "", { "optionalDependencies": { "@img/sharp-libvips-linux-riscv64": "1.3.3" }, "os": "linux", "cpu": "none" }, "sha512-cPbNChoRURAWdebDIHSenxRpgEdy7JkPydSnUxRm9VvKD7m0/xVaR/8Fzlu81pk5nHEvHH87UZUA7cTtwnbJSA=="], + + "cf/@cloudflare/runtime-types/miniflare/sharp/@img/sharp-linux-s390x": ["@img/sharp-linux-s390x@0.35.4", "", { "optionalDependencies": { "@img/sharp-libvips-linux-s390x": "1.3.3" }, "os": "linux", "cpu": "s390x" }, "sha512-RY0JFY8Fd6RonCBtHz+DvadaPkXDSI1AUn6yWL9TipqkZ1vY8w8evqdgyDFnkm4/K1ve1TvZiaePP5oSd4+WVQ=="], + + "cf/@cloudflare/runtime-types/miniflare/sharp/@img/sharp-linux-x64": ["@img/sharp-linux-x64@0.35.4", "", { "optionalDependencies": { "@img/sharp-libvips-linux-x64": "1.3.3" }, "os": "linux", "cpu": "x64" }, "sha512-9qvvEAuk8k89TfWUoX2htWjbAMX8p+NxCppjpcg5k6xMsjhBQPTsoIh36h9Qde4WRuGpJeYnOjdosDn/cnv+OA=="], + + "cf/@cloudflare/runtime-types/miniflare/sharp/@img/sharp-linuxmusl-arm64": ["@img/sharp-linuxmusl-arm64@0.35.4", "", { "optionalDependencies": { "@img/sharp-libvips-linuxmusl-arm64": "1.3.3" }, "os": "linux", "cpu": "arm64" }, "sha512-KB5jxpfWQTr0nc3xdHtWChdbifHrBGsd2SM62Eyxrl8afikm+f5qGBU75SJIZBT/S1MC8XyacdlXBMSWq6OURA=="], + + "cf/@cloudflare/runtime-types/miniflare/sharp/@img/sharp-linuxmusl-x64": ["@img/sharp-linuxmusl-x64@0.35.4", "", { "optionalDependencies": { "@img/sharp-libvips-linuxmusl-x64": "1.3.3" }, "os": "linux", "cpu": "x64" }, "sha512-f+eZJZIQNEEd26RPSW+76chwOf1XtA2Y/O+5ocVyLliHkeih3e+jhLVBdNTd2rS3IbNXK8+ug93Vf5ZXtF5Lxg=="], + + "cf/@cloudflare/runtime-types/miniflare/sharp/@img/sharp-webcontainers-wasm32": ["@img/sharp-webcontainers-wasm32@0.35.4", "", { "dependencies": { "@img/sharp-wasm32": "0.35.4" }, "cpu": "none" }, "sha512-ESfNkywmCfPNyaZjxooddJQiQ+l/nTpGEOGthxiLnIHXC/CmcBixnfwUleX9mCz9ovrUUvKMap/pm8RYbzfwaA=="], + + "cf/@cloudflare/runtime-types/miniflare/sharp/@img/sharp-win32-arm64": ["@img/sharp-win32-arm64@0.35.4", "", { "os": "win32", "cpu": "arm64" }, "sha512-iNdlBX9gLVvqe2I3uIJSIKTq6wckP/DYxZtcqxm09x5Gi24DnFBmPAWZmr60ZyYMG0xlzo6goG3670ar+RXvRw=="], + + "cf/@cloudflare/runtime-types/miniflare/sharp/@img/sharp-win32-ia32": ["@img/sharp-win32-ia32@0.35.4", "", { "os": "win32", "cpu": "ia32" }, "sha512-kqRsbaa5CS6KHlpxnN7WhE6vAAugXyZButpRdvDWetlv6Qv4N9WTcrWzF7tXfB9T7MsoadqdI8hmwLq6UlLvtw=="], + + "cf/@cloudflare/runtime-types/miniflare/sharp/@img/sharp-win32-x64": ["@img/sharp-win32-x64@0.35.4", "", { "os": "win32", "cpu": "x64" }, "sha512-XtmnYhBcrORsJ4XJngyzr/EWP0hRZLAZRFaApdKuviyqF78+ylxh2y06ZmtULAMOnObJ3ucpN0AcwSWnMowTRg=="], + + "cf/miniflare/sharp/@img/sharp-freebsd-wasm32/@img/sharp-wasm32": ["@img/sharp-wasm32@0.35.4", "", { "dependencies": { "@emnapi/runtime": "^1.11.3" } }, "sha512-zQnl4Kwp7Q6NHsENtU2T/00Zi+w3AQNwz3+UaTyVBy2FpXrzXzGjndpK61onhZjRtRpQXxCTeqw19bVyXOh7jA=="], + + "cf/miniflare/sharp/@img/sharp-webcontainers-wasm32/@img/sharp-wasm32": ["@img/sharp-wasm32@0.35.4", "", { "dependencies": { "@emnapi/runtime": "^1.11.3" } }, "sha512-zQnl4Kwp7Q6NHsENtU2T/00Zi+w3AQNwz3+UaTyVBy2FpXrzXzGjndpK61onhZjRtRpQXxCTeqw19bVyXOh7jA=="], + + "cf/@cloudflare/runtime-types/miniflare/sharp/@img/sharp-freebsd-wasm32/@img/sharp-wasm32": ["@img/sharp-wasm32@0.35.4", "", { "dependencies": { "@emnapi/runtime": "^1.11.3" } }, "sha512-zQnl4Kwp7Q6NHsENtU2T/00Zi+w3AQNwz3+UaTyVBy2FpXrzXzGjndpK61onhZjRtRpQXxCTeqw19bVyXOh7jA=="], + + "cf/@cloudflare/runtime-types/miniflare/sharp/@img/sharp-webcontainers-wasm32/@img/sharp-wasm32": ["@img/sharp-wasm32@0.35.4", "", { "dependencies": { "@emnapi/runtime": "^1.11.3" } }, "sha512-zQnl4Kwp7Q6NHsENtU2T/00Zi+w3AQNwz3+UaTyVBy2FpXrzXzGjndpK61onhZjRtRpQXxCTeqw19bVyXOh7jA=="], + + "cf/miniflare/sharp/@img/sharp-freebsd-wasm32/@img/sharp-wasm32/@emnapi/runtime": ["@emnapi/runtime@1.11.3", "", { "dependencies": { "tslib": "^2.4.0" } }, "sha512-Xz4Tpyki7XyrpbUK1jR1AhdAdaXyhhY4lZ3neLodmhpuWfy2PAQN5B46sAiU4liOXGLkHypn/qU+jvfWSCYYLA=="], + + "cf/miniflare/sharp/@img/sharp-webcontainers-wasm32/@img/sharp-wasm32/@emnapi/runtime": ["@emnapi/runtime@1.11.3", "", { "dependencies": { "tslib": "^2.4.0" } }, "sha512-Xz4Tpyki7XyrpbUK1jR1AhdAdaXyhhY4lZ3neLodmhpuWfy2PAQN5B46sAiU4liOXGLkHypn/qU+jvfWSCYYLA=="], + + "cf/@cloudflare/runtime-types/miniflare/sharp/@img/sharp-freebsd-wasm32/@img/sharp-wasm32/@emnapi/runtime": ["@emnapi/runtime@1.11.3", "", { "dependencies": { "tslib": "^2.4.0" } }, "sha512-Xz4Tpyki7XyrpbUK1jR1AhdAdaXyhhY4lZ3neLodmhpuWfy2PAQN5B46sAiU4liOXGLkHypn/qU+jvfWSCYYLA=="], + + "cf/@cloudflare/runtime-types/miniflare/sharp/@img/sharp-webcontainers-wasm32/@img/sharp-wasm32/@emnapi/runtime": ["@emnapi/runtime@1.11.3", "", { "dependencies": { "tslib": "^2.4.0" } }, "sha512-Xz4Tpyki7XyrpbUK1jR1AhdAdaXyhhY4lZ3neLodmhpuWfy2PAQN5B46sAiU4liOXGLkHypn/qU+jvfWSCYYLA=="], + } +} diff --git a/app/vendor/rune/site/cloudflare.config.ts b/app/vendor/rune/site/cloudflare.config.ts new file mode 100644 index 0000000..4a1cb9c --- /dev/null +++ b/app/vendor/rune/site/cloudflare.config.ts @@ -0,0 +1,27 @@ +import { bindings, defineConfig, triggers } from "cf/config" +import { BASE_PATH, hostForMode } from "./src/base.ts" + +// `--mode dev` builds and deploys the dev Worker on dev.anoma.ly; any other mode is production +// on anoma.ly. Cloudflare Access protects /team on both hosts, so no other hostnames. +// The account comes from CLOUDFLARE_ACCOUNT_ID. +export default defineConfig(({ mode }) => { + const host = hostForMode(mode) + return { + worker: { + name: mode === "dev" ? "rune-dev-site" : "rune-production-site", + compatibilityDate: "2026-10-13", + entrypoint: "./worker.ts", + assets: { runWorkerFirst: true }, + env: { + ASSETS: bindings.assets(), + CANONICAL_HOST: bindings.text(host), + }, + triggers: [ + triggers.fetch({ pattern: `${host}${BASE_PATH}`, zone: host }), + triggers.fetch({ pattern: `${host}${BASE_PATH}/*`, zone: host }), + ], + workersDev: false, + previewUrls: false, + }, + } +}) diff --git a/app/vendor/rune/site/index.html b/app/vendor/rune/site/index.html new file mode 100644 index 0000000..4143d3e --- /dev/null +++ b/app/vendor/rune/site/index.html @@ -0,0 +1,35 @@ +<!doctype html> +<html lang="en"> + <head> + <meta charset="UTF-8" /> + <meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover" /> + <meta name="color-scheme" content="dark" /> + <meta name="theme-color" content="#000000" /> + <title>Rune</title> + <meta name="description" content="Rune is a Rust UI framework with its own GPU renderer, text, layout, spring animation and thin per-platform shells." /> + <link rel="canonical" href="__URL__" /> + <meta property="og:type" content="website" /> + <meta property="og:site_name" content="Rune" /> + <meta property="og:locale" content="en_US" /> + <meta property="og:title" content="__TITLE__" /> + <meta property="og:description" content="__DESCRIPTION__" /> + <meta property="og:url" content="__URL__" /> + <meta property="og:image" content="__ORIGIN__/og.png" /> + <meta property="og:image:type" content="image/png" /> + <meta property="og:image:width" content="1200" /> + <meta property="og:image:height" content="630" /> + <meta property="og:image:alt" content="ᚱUNE in blue pixel letters on black, the R the rune ᚱ" /> + <meta name="twitter:card" content="summary_large_image" /> + <link rel="icon" href="/favicon.ico" sizes="16x16 32x32" /> + <link rel="icon" type="image/svg+xml" href="/favicon.svg" /> + <link rel="apple-touch-icon" href="/apple-touch-icon.png" /> + <link rel="manifest" href="/site.webmanifest" crossorigin="use-credentials" /> + <link rel="alternate" type="text/plain" href="%BASE_URL%llms.txt" title="llms.txt" /> + <link rel="preload" href="/fonts/geist.woff2" as="font" type="font/woff2" crossorigin /> + <link rel="preload" href="/fonts/geist-mono.woff2" as="font" type="font/woff2" crossorigin /> + </head> + <body> + <div id="root"><!--app--></div> + <script type="module" src="/src/main.tsx"></script> + </body> +</html> diff --git a/app/vendor/rune/site/package.json b/app/vendor/rune/site/package.json new file mode 100644 index 0000000..a8c97b5 --- /dev/null +++ b/app/vendor/rune/site/package.json @@ -0,0 +1,31 @@ +{ + "name": "rune-site", + "version": "0.0.0", + "private": true, + "type": "module", + "scripts": { + "dev": "vite", + "build": "bun scripts/build.ts", + "preview": "vite preview", + "check": "tsc --noEmit", + "icons": "bun scripts/icons.ts", + "deploy:dev": "bun scripts/build.ts --mode dev && cf deploy --prebuilt --mode dev", + "deploy:production": "bun scripts/build.ts --mode production && cf deploy --prebuilt --mode production" + }, + "dependencies": { + "react": "19.2.7", + "react-dom": "19.2.7" + }, + "devDependencies": { + "@cloudflare/build-output-utils": "0.8.5", + "@cloudflare/vite-plugin": "2.0.0-beta.v.4", + "@types/bun": "1.3.13", + "@types/node": "25.5.0", + "@types/react": "19.2.17", + "@types/react-dom": "19.2.3", + "@vitejs/plugin-react": "6.0.3", + "cf": "1.0.0-beta.12", + "typescript": "6.0.2", + "vite": "8.1.3" + } +} diff --git a/app/vendor/rune/site/public/apple-touch-icon.png b/app/vendor/rune/site/public/apple-touch-icon.png new file mode 100644 index 0000000..b7c70fe Binary files /dev/null and b/app/vendor/rune/site/public/apple-touch-icon.png differ diff --git a/app/vendor/rune/site/public/favicon.ico b/app/vendor/rune/site/public/favicon.ico new file mode 100644 index 0000000..7a6671d Binary files /dev/null and b/app/vendor/rune/site/public/favicon.ico differ diff --git a/app/vendor/rune/site/public/favicon.svg b/app/vendor/rune/site/public/favicon.svg new file mode 100644 index 0000000..3dd9fc0 --- /dev/null +++ b/app/vendor/rune/site/public/favicon.svg @@ -0,0 +1 @@ +<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 16 16" shape-rendering="crispEdges" fill="#54b3fd"><rect x="3" y="1" width="4" height="1"/><rect x="3" y="2" width="5" height="1"/><rect x="3" y="3" width="6" height="1"/><rect x="3" y="4" width="3" height="1"/><rect x="7" y="4" width="3" height="1"/><rect x="3" y="5" width="3" height="1"/><rect x="8" y="5" width="3" height="1"/><rect x="3" y="6" width="3" height="1"/><rect x="8" y="6" width="3" height="1"/><rect x="3" y="7" width="3" height="1"/><rect x="7" y="7" width="3" height="1"/><rect x="3" y="8" width="6" height="1"/><rect x="3" y="9" width="5" height="1"/><rect x="3" y="10" width="6" height="1"/><rect x="3" y="11" width="3" height="1"/><rect x="7" y="11" width="3" height="1"/><rect x="3" y="12" width="3" height="1"/><rect x="8" y="12" width="3" height="1"/><rect x="3" y="13" width="3" height="1"/><rect x="9" y="13" width="3" height="1"/><rect x="3" y="14" width="3" height="1"/><rect x="10" y="14" width="3" height="1"/></svg> diff --git a/app/vendor/rune/site/public/fonts/geist-OFL.txt b/app/vendor/rune/site/public/fonts/geist-OFL.txt new file mode 100644 index 0000000..8d003fe --- /dev/null +++ b/app/vendor/rune/site/public/fonts/geist-OFL.txt @@ -0,0 +1,92 @@ +Copyright (c) 2023 Vercel, in collaboration with basement.studio + +This Font Software is licensed under the SIL Open Font License, Version 1.1. +This license is copied below, and is also available with a FAQ at: +http://scripts.sil.org/OFL + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION AND CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. diff --git a/app/vendor/rune/site/public/fonts/geist-mono.woff2 b/app/vendor/rune/site/public/fonts/geist-mono.woff2 new file mode 100644 index 0000000..37a4c17 Binary files /dev/null and b/app/vendor/rune/site/public/fonts/geist-mono.woff2 differ diff --git a/app/vendor/rune/site/public/fonts/geist.woff2 b/app/vendor/rune/site/public/fonts/geist.woff2 new file mode 100644 index 0000000..09082f6 Binary files /dev/null and b/app/vendor/rune/site/public/fonts/geist.woff2 differ diff --git a/app/vendor/rune/site/public/icon-192.png b/app/vendor/rune/site/public/icon-192.png new file mode 100644 index 0000000..3d0a4a0 Binary files /dev/null and b/app/vendor/rune/site/public/icon-192.png differ diff --git a/app/vendor/rune/site/public/icon-512.png b/app/vendor/rune/site/public/icon-512.png new file mode 100644 index 0000000..26eef21 Binary files /dev/null and b/app/vendor/rune/site/public/icon-512.png differ diff --git a/app/vendor/rune/site/public/og.png b/app/vendor/rune/site/public/og.png new file mode 100644 index 0000000..b0fe521 Binary files /dev/null and b/app/vendor/rune/site/public/og.png differ diff --git a/app/vendor/rune/site/public/shots/hello-on.png b/app/vendor/rune/site/public/shots/hello-on.png new file mode 100644 index 0000000..65482b7 Binary files /dev/null and b/app/vendor/rune/site/public/shots/hello-on.png differ diff --git a/app/vendor/rune/site/public/shots/settings.png b/app/vendor/rune/site/public/shots/settings.png new file mode 100644 index 0000000..c732e5e Binary files /dev/null and b/app/vendor/rune/site/public/shots/settings.png differ diff --git a/app/vendor/rune/site/public/shots/todo.png b/app/vendor/rune/site/public/shots/todo.png new file mode 100644 index 0000000..d40d8ac Binary files /dev/null and b/app/vendor/rune/site/public/shots/todo.png differ diff --git a/app/vendor/rune/site/public/site.webmanifest b/app/vendor/rune/site/public/site.webmanifest new file mode 100644 index 0000000..7a97a62 --- /dev/null +++ b/app/vendor/rune/site/public/site.webmanifest @@ -0,0 +1,13 @@ +{ + "name": "Rune", + "short_name": "Rune", + "description": "A Rust UI framework with its own GPU renderer, text, layout and spring animation.", + "start_url": "./", + "display": "browser", + "background_color": "#000000", + "theme_color": "#000000", + "icons": [ + { "src": "icon-192.png", "sizes": "192x192", "type": "image/png" }, + { "src": "icon-512.png", "sizes": "512x512", "type": "image/png" } + ] +} diff --git a/app/vendor/rune/site/scripts/build.ts b/app/vendor/rune/site/scripts/build.ts new file mode 100644 index 0000000..e18d945 --- /dev/null +++ b/app/vendor/rune/site/scripts/build.ts @@ -0,0 +1,13 @@ +#!/usr/bin/env bun +// `bun run build [--mode dev]`: typecheck, client build (Cloudflare Build Output), SSR build, then prerender every +// route to static HTML. +import { parseArgs } from "node:util" +import { $ } from "bun" + +const { values } = parseArgs({ options: { mode: { type: "string", default: "production" } } }) +const mode = values.mode + +await $`tsc --noEmit` +await $`vite build --mode ${mode}` +await $`vite build --mode ${mode} --ssr src/entry-server.tsx --outDir dist-ssr` +await $`bun scripts/prerender.ts --mode ${mode}` diff --git a/app/vendor/rune/site/scripts/highlight.ts b/app/vendor/rune/site/scripts/highlight.ts new file mode 100644 index 0000000..f5fb977 --- /dev/null +++ b/app/vendor/rune/site/scripts/highlight.ts @@ -0,0 +1,109 @@ +/** A small build-time highlighter: one regex pass per language, spans with `tk-*` classes. Copied from + * @anomalyco/site's content/highlight.ts until this site moves onto the shared package. Only scripts/snippets.ts + * imports it, at build time; the client gets finished HTML. */ + +export type CodeLang = "rust" | "toml" | "ts" | "css" | "shell" | "plain" +export const CODE_LANGS: readonly CodeLang[] = ["rust", "toml", "ts", "css", "shell", "plain"] + +type Role = "k" | "s" | "n" | "t" | "f" | "a" | "c" | "p" +type Rule = [RegExp, Role | null] + +const escape = (s: string) => s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;") +const words = (list: string) => new RegExp(`\\b(?:${list.split(" ").join("|")})\\b`, "y") + +const STRING: Rule = [/"(?:\\.|[^"\\\n])*"?/y, "s"] +const NUMBER: Rule = [/\b\d[\d_]*(?:\.\d+)?(?:[a-z%]+\d*)?\b|(?<![\w.])\.\d+\b/y, "n"] +const WORD: Rule = [/[A-Za-z_][\w]*/y, null] + +const RULES: Record<Exclude<CodeLang, "plain">, Rule[]> = { + rust: [ + [/\/\/[^\n]*/y, "c"], + STRING, + [/#!?\[[^\]\n]*\]/y, "a"], + [/'[a-z_]\w*\b(?!')/y, "a"], + [/[a-z_]\w*!/y, "f"], + NUMBER, + [words("as async await break const continue crate dyn else enum extern false fn for if impl in let loop match mod move mut pub ref return self Self static struct super trait true type unsafe use where while"), "k"], + [/[A-Z]\w*/y, "t"], + [/[a-z_]\w*(?=\s*(?:::<[^>]*>)?\()/y, "f"], + WORD, + [/::|->|=>|[{}()[\];,<>&|]/y, "p"], + ], + toml: [ + [/#[^\n]*/y, "c"], + STRING, + [/(?<=^|\n)\s*\[\[?[^\]\n]+\]\]?/y, "a"], + [words("true false"), "k"], + NUMBER, + [/[A-Za-z_][\w.:-]*(?=\s*=)/y, null], + WORD, + [/[{}[\],=]/y, "p"], + ], + ts: [ + [/\/\/[^\n]*|\/\*[\s\S]*?\*\//y, "c"], + STRING, + [/'(?:\\.|[^'\\\n])*'?|`(?:\\.|[^`\\])*`?/y, "s"], + NUMBER, + [words("as async await break case catch class const continue default else export extends false for from function if import in interface let new null of return satisfies switch this throw true try type typeof undefined var void while"), "k"], + [/[A-Z]\w*/y, "t"], + [/[a-z_$][\w$]*(?=\s*\()/y, "f"], + [/[\w$]+/y, null], + [/=>|[{}()[\];,<>=:|&?]/y, "p"], + ], + css: [ + [/\/\*[\s\S]*?\*\//y, "c"], + STRING, + [/@[\w-]+/y, "k"], + [/--[\w-]+/y, "a"], + [/[a-z-]+(?=\s*:(?!:))/y, null], + [/#[0-9a-fA-F]{3,8}\b/y, "n"], + NUMBER, + [/[a-z-]+(?=\()/y, "f"], + [/::?[a-z-]+/y, "a"], + [/[\w-]+/y, null], + [/[{}()[\];,:/]/y, "p"], + ], + shell: [ + [/#[^\n]*/y, "c"], + STRING, + [/'[^'\n]*'?/y, "s"], + [/(?<=^|[|;&]\s*)[\w./+-]+/y, "f"], + [/(?<=\s)--?[\w-]+/y, "a"], + [/<[\w-]+>/y, "c"], + [/[\w./:@+-]+/y, null], + [/[|;&=<>]/y, "p"], + ], +} + +export function highlight(code: string, lang: CodeLang): string { + if (lang === "plain") return escape(code) + const rules = RULES[lang] + const runs: { role: Role | null; text: string }[] = [] + const push = (role: Role | null, text: string) => { + const last = runs.at(-1) + // Whitespace joins the run before it, so `) -> (` stays one span. + if (last && (last.role === role || (last.role && /^\s+$/.test(text)))) last.text += text + else runs.push({ role, text }) + } + let i = 0 + outer: while (i < code.length) { + for (const [re, role] of rules) { + re.lastIndex = i + const m = re.exec(code) + if (m && m[0].length > 0) { + push(role, m[0]) + i += m[0].length + continue outer + } + } + push(null, code[i]!) + i++ + } + return runs + .map(({ role, text }) => { + if (!role) return escape(text) + const body = text.trimEnd() + return `<span class="tk-${role}">${escape(body)}</span>${escape(text.slice(body.length))}` + }) + .join("") +} diff --git a/app/vendor/rune/site/scripts/icons.ts b/app/vendor/rune/site/scripts/icons.ts new file mode 100644 index 0000000..901fe84 --- /dev/null +++ b/app/vendor/rune/site/scripts/icons.ts @@ -0,0 +1,94 @@ +#!/usr/bin/env bun +// `bun scripts/icons.ts`: draws the brand into public/: favicon.svg and favicon.ico (16 and 32) from the 16-cell ᚱ on +// transparent; apple-touch-icon.png (180), icon-192.png and icon-512.png from the wordmark's ᚱ on black; and og.png +// (1200 × 630), the whole wordmark on black. Every cell is a whole number of pixels, so the PNGs are written directly, +// with no browser. +import { writeFileSync } from "node:fs" +import { join, resolve } from "node:path" +import { deflateSync } from "node:zlib" +import { ICON16, INK, WORDMARK, oklch, runs, type Grid } from "../src/brand/pixels" + +const out = resolve(import.meta.dirname, "..", "public") +const ink = oklch(...INK).map(c => Math.round(c * 255)) as [number, number, number] +const hex = `#${ink.map(c => c.toString(16).padStart(2, "0")).join("")}` + +const crcTable = Array.from({ length: 256 }, (_, n) => { + let c = n + for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1 + return c >>> 0 +}) +const crc = (bytes: Uint8Array) => { + let c = 0xffffffff + for (const b of bytes) c = crcTable[(c ^ b) & 0xff]! ^ (c >>> 8) + return (c ^ 0xffffffff) >>> 0 +} +function chunk(type: string, data: Uint8Array) { + const body = new Uint8Array(4 + data.length) + body.set(new TextEncoder().encode(type)) + body.set(data, 4) + const out = new Uint8Array(12 + data.length) + const dv = new DataView(out.buffer) + dv.setUint32(0, data.length) + out.set(body, 4) + dv.setUint32(8 + data.length, crc(body)) + return out +} + +/** `rows` at `px` pixels a cell, centred in a `width` × `height` image on `background` (null for transparent), as an + * RGBA PNG. */ +function png(rows: Grid, px: number, background: [number, number, number] | null, width: number, height = width) { + const w = rows[0]!.length * px, h = rows.length * px + const ox = Math.floor((width - w) / 2), oy = Math.floor((height - h) / 2) + const raw = new Uint8Array(height * (width * 4 + 1)) + for (let y = 0; y < height; y++) { + const row = y * (width * 4 + 1) + for (let x = 0; x < width; x++) { + const cx = Math.floor((x - ox) / px), cy = Math.floor((y - oy) / px) + const on = x >= ox && y >= oy && rows[cy]?.[cx] === "#" + const rgb = on ? ink : background + if (rgb) raw.set([...rgb, 255], row + 1 + x * 4) + } + } + const header = new Uint8Array(13) + const dv = new DataView(header.buffer) + dv.setUint32(0, width) + dv.setUint32(4, height) + header.set([8, 6, 0, 0, 0], 8) + const parts = [new Uint8Array([137, 80, 78, 71, 13, 10, 26, 10]), chunk("IHDR", header), chunk("IDAT", deflateSync(raw)), chunk("IEND", new Uint8Array())] + return Buffer.concat(parts) +} + +/** An ICO holding PNGs, one entry per size. */ +function ico(images: { png: Uint8Array; size: number }[]) { + const header = 6 + 16 * images.length + const out = new Uint8Array(header + images.reduce((n, i) => n + i.png.length, 0)) + const dv = new DataView(out.buffer) + dv.setUint16(2, 1, true) + dv.setUint16(4, images.length, true) + let offset = header + images.forEach(({ png, size }, k) => { + const e = 6 + 16 * k + out[e] = size + out[e + 1] = size + dv.setUint16(e + 4, 1, true) + dv.setUint16(e + 6, 32, true) + dv.setUint32(e + 8, png.length, true) + dv.setUint32(e + 12, offset, true) + out.set(png, offset) + offset += png.length + }) + return out +} + +const rune = WORDMARK.glyphs[0]!.rows +const black: [number, number, number] = [0, 0, 0] +for (const [name, size, px] of [["icon-512.png", 512, 32], ["icon-192.png", 192, 12], ["apple-touch-icon.png", 180, 12]] as const) { + writeFileSync(join(out, name), png(rune, px, black, size)) +} +writeFileSync(join(out, "favicon.ico"), ico([32, 16].map(size => ({ size, png: png(ICON16, size / 16, null, size) })))) +const word = Array.from({ length: WORDMARK.height }, (_, y) => + Array.from({ length: WORDMARK.width }, (_, x) => (WORDMARK.glyphs.some(g => g.rows[y]?.[x - g.x] === "#") ? "#" : ".")).join("")) +writeFileSync(join(out, "og.png"), png(word, 24, black, 1200, 630)) +const rects = runs(ICON16).map(([x, y, w, h]) => `<rect x="${x}" y="${y}" width="${w}" height="${h}"/>`).join("") +writeFileSync(join(out, "favicon.svg"), `<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 16 16" shape-rendering="crispEdges" fill="${hex}">${rects}</svg>\n`) +console.log(`Icons in ${ink.join(",")} (${hex}) → ${out}`) diff --git a/app/vendor/rune/site/scripts/prerender.ts b/app/vendor/rune/site/scripts/prerender.ts new file mode 100644 index 0000000..9496024 --- /dev/null +++ b/app/vendor/rune/site/scripts/prerender.ts @@ -0,0 +1,97 @@ +import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs" +import { join, relative, resolve } from "node:path" +import { parseArgs } from "node:util" +import { getWorkerAssetsDir } from "@cloudflare/build-output-utils" +import { BASE_PATH, hostForMode } from "../src/base" +import { REPO, type Route } from "../src/routes" + +const { values } = parseArgs({ options: { mode: { type: "string", default: "production" } } }) +const origin = `https://${hostForMode(values.mode)}${BASE_PATH}` + +const root = resolve(import.meta.dirname, "..") +const distDir = getWorkerAssetsDir(root) +const distRel = relative(root, distDir) +const ssrDir = join(root, "dist-ssr") +const templatePath = join(distDir, "index.html") + +if (!existsSync(templatePath)) throw new Error(`${distRel}/index.html not found; run \`vite build\` first`) + +let template = readFileSync(templatePath, "utf8") +if (!template.includes("<!--app-->")) throw new Error(`${distRel}/index.html is missing the <!--app--> marker`) + +// Inline the one stylesheet so the first paint needs no extra request. +template = template.replace(new RegExp(`<link rel="stylesheet"[^>]*href="${BASE_PATH}/(assets/[^"]+\\.css)"[^>]*>`, "g"), (full, href: string) => { + const cssPath = join(distDir, href) + if (!existsSync(cssPath)) return full + return `<style>${readFileSync(cssPath, "utf8").replace(/<\/style/gi, "<\\/style")}</style>` +}) + +const escape = (s: string) => s.replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/</g, "&lt;").replace(/>/g, "&gt;") + +const ssr = (await import(join(ssrDir, "entry-server.js"))) as { + render: (pathname: string) => string + routes: Route[] +} + +const page = (route: Route) => + template + .replace(/<title>[\s\S]*?<\/title>/, `<title>${escape(route.title)}</title>`) + .replace(/<meta name="description" content="[^"]*" \/>/, `<meta name="description" content="${escape(route.description)}" />`) + .replaceAll("__URL__", `${origin}${route.path}`) + .replaceAll("__TITLE__", escape(route.title)) + .replaceAll("__DESCRIPTION__", escape(route.description)) + .replaceAll("__ORIGIN__", origin) + .replace("<!--app-->", ssr.render(route.path)) + +// The Worker serves this for any missing path under the base, with a 404. +const notFound = page({ path: "/404", label: "Not found", title: "Not found · Rune", description: "There's no page here." }) +writeFileSync(join(distDir, "404.html"), notFound.replace(/\s*<link rel="canonical"[^>]*>/, "")) + +// Every link into the repo names a file or folder that exists, so code references can't drift. +const repoRoot = resolve(root, "..") +const missing = new Set<string>() +const checkRepoLinks = (html: string) => { + for (const [, path] of html.matchAll(new RegExp(`${REPO}/(?:blob|tree)/dev/([^"#?]+)`, "g"))) { + if (!existsSync(join(repoRoot, decodeURIComponent(path!)))) missing.add(path!) + } +} + +for (const route of ssr.routes) { + const html = page(route) + checkRepoLinks(html) + if (route.path === "/") { + writeFileSync(templatePath, html) + } else { + // Both files, so /principles serves directly instead of redirecting to /principles/. + const dir = join(distDir, route.path.slice(1)) + mkdirSync(dir, { recursive: true }) + writeFileSync(join(dir, "index.html"), html) + writeFileSync(`${dir}.html`, html) + } +} + +if (missing.size) throw new Error(`Links to files that aren't in the repo:\n ${[...missing].join("\n ")}`) + +// llms.txt (llmstxt.org): what the site is and where each page lives, from the same routes. +const home = ssr.routes.find(r => r.path === "/")! +writeFileSync( + join(distDir, "llms.txt"), + [ + "# Rune", + "", + `> ${home.description}`, + "", + "## Pages", + "", + ...ssr.routes.map(r => `- [${r.label}](${origin}${r.path}): ${r.description}`), + "", + "## Source", + "", + `- [anomalyco/rune](${REPO}): the code`, + `- [PLAN.md](${REPO}/blob/dev/PLAN.md): the full plan, the source of truth for this site`, + "", + ].join("\n"), +) + +rmSync(ssrDir, { recursive: true, force: true }) +console.log(`Prerendered ${ssr.routes.length} routes into ${distRel}/`) diff --git a/app/vendor/rune/site/scripts/snippets.ts b/app/vendor/rune/site/scripts/snippets.ts new file mode 100644 index 0000000..07ff787 --- /dev/null +++ b/app/vendor/rune/site/scripts/snippets.ts @@ -0,0 +1,216 @@ +/** Code examples on the site, cut from Rune's own source at build time and highlighted there. + * + * Each snippet names files in this repo and where to cut. A piece starts at the first line beginning with `from` + * (attributes above it come along) and ends at `to`, just before `until`, after `lines` lines, or at the closing + * brace at the starting line's indent. A missing file or marker fails the build, so an example can't drift away from the code. + * The Vite plugin serves the result as `virtual:snippets`; the client gets HTML strings, not the highlighter. */ +import { readFileSync } from "node:fs" +import { resolve } from "node:path" +import type { Plugin } from "vite" +import { highlight, type CodeLang } from "./highlight" + +type Piece = { file: string; from?: string; to?: string; until?: string; lines?: number } +type Spec = { lang: CodeLang; label: string; pieces: Piece[] } + +export type Snippet = { html: string; label: string; file: string; start: number; end: number } + +const SETTINGS = "examples/settings/src/main.rs" +const HELLO = "examples/hello/src/main.rs" +const TODO = "examples/todo/src/main.rs" + +const specs: Record<string, Spec> = { + hello: { + lang: "rust", + label: "Rust", + pieces: [{ file: HELLO, from: "use rune::", until: "#[cfg(test)]" }], + }, + "hello-test": { + lang: "rust", + label: "Rust", + pieces: [{ file: HELLO, from: " fn a_tap_flips_the_switch" }], + }, + "todo-list": { + lang: "rust", + label: "Rust", + pieces: [{ file: TODO, from: "fn view(" }], + }, + "todo-spring": { + lang: "rust", + label: "Rust", + pieces: [{ file: TODO, from: "fn progress(" }], + }, + "overlay-windows": { + lang: "rust", + label: "Rust", + pieces: [{ file: "examples/overlay/src/main.rs", from: " rune::run_windows(", to: " });" }], + }, + "app-cargo": { + lang: "toml", + label: "TOML", + pieces: [{ file: "examples/settings/Cargo.toml" }], + }, + "app-main": { + lang: "rust", + label: "Rust", + pieces: [ + { file: SETTINGS, from: "fn view(", lines: 23 }, + { file: SETTINGS, from: "fn main() {" }, + ], + }, + toggle: { + lang: "rust", + label: "Rust", + pieces: [ + { file: SETTINGS, from: ' toggle_row(p, "login"', lines: 3 }, + { file: SETTINGS, from: "fn toggle_row(" }, + { file: SETTINGS, from: "fn toggle(" }, + ], + }, + "toggle-only": { + lang: "rust", + label: "Rust", + pieces: [{ file: SETTINGS, from: "fn toggle(" }], + }, + "motion-tokens": { + lang: "rust", + label: "Rust", + pieces: [ + { file: "crates/rune-motion/src/tokens.rs", from: "/// Small controls", lines: 3 }, + { file: "crates/rune-motion/src/tokens.rs", from: "pub const SNAPPY", lines: 1 }, + ], + }, + retarget: { + lang: "rust", + label: "Rust", + pieces: [ + { + file: "crates/rune-motion/tests/integration/spring.rs", + from: "fn animated_value_retargets_keeping_velocity", + to: " assert!((a.sample(5.0) + 50.0)", + }, + ], + }, + live: { + lang: "rust", + label: "Rust", + pieces: [ + { file: "crates/rune/tests/integration/live.rs", from: "fn view(" }, + { file: "crates/rune/tests/integration/live.rs", from: "fn properties_change_without_view", to: " assert_eq!(rt.stats.shaped, 0);" }, + ], + }, + "test-segmented": { + lang: "rust", + label: "Rust", + pieces: [ + { file: "crates/rune-kit/tests/integration/segmented.rs", from: "fn fitted(" }, + { file: "crates/rune-kit/tests/integration/segmented.rs", from: "fn fitted_segments_share" }, + ], + }, + "snap-commands": { + lang: "shell", + label: "Shell", + pieces: [{ file: "examples/live-values/README.md", from: "target/release/live-values --snap", lines: 2 }], + }, + "tap-script": { + lang: "ts", + label: "JSON", + pieces: [{ file: "examples/settings/scripts/toggle-retarget.json" }], + }, + "golden-hashes": { + lang: "rust", + label: "Rust", + pieces: [{ file: "crates/rune-ref/tests/reference.rs", from: "fn canonical_hashes" }], + }, + "rune-deps": { + lang: "toml", + label: "TOML", + pieces: [{ file: "crates/rune/Cargo.toml", from: "rune-core = ", to: "parley = " }], + }, +} + +const indentOf = (line: string) => line.match(/^\s*/)![0] + +function cut(root: string, id: string, piece: Piece): { text: string; start: number; end: number } { + const where = `snippet "${id}": ${piece.file}` + let source: string + try { + source = readFileSync(resolve(root, piece.file), "utf8") + } catch { + throw new Error(`${where} not found`) + } + const lines = source.replace(/\n$/, "").split("\n") + if (!piece.from) return { text: lines.join("\n"), start: 1, end: lines.length } + + const first = lines.findIndex(l => l.startsWith(piece.from!)) + if (first < 0) throw new Error(`${where}: no line starts with ${JSON.stringify(piece.from)}`) + let start = first + while (start > 0 && lines[start - 1]!.trim().startsWith("#[")) start-- + + let end: number + if (piece.lines) { + end = first + piece.lines - 1 + } else if (piece.until) { + end = lines.findIndex((l, i) => i > first && l.startsWith(piece.until!)) - 1 + if (end < 0) throw new Error(`${where}: no line starts with ${JSON.stringify(piece.until)} after ${JSON.stringify(piece.from)}`) + while (end > first && !lines[end]!.trim()) end-- + } else if (piece.to) { + end = lines.findIndex((l, i) => i >= first && l.startsWith(piece.to!)) + if (end < 0) throw new Error(`${where}: no line starts with ${JSON.stringify(piece.to)} after ${JSON.stringify(piece.from)}`) + } else { + const close = `${indentOf(lines[first]!)}}` + end = lines.findIndex((l, i) => i > first && l.trimEnd() === close) + if (end < 0) throw new Error(`${where}: no closing brace for ${JSON.stringify(piece.from)}`) + } + + const taken = lines.slice(start, end + 1) + const pad = Math.min(...taken.filter(l => l.trim()).map(l => indentOf(l).length)) + const out = taken.map(l => l.slice(pad)) + // A block cut short keeps its shape: an elision inside, then its closing brace. + const open = (out.join("\n").match(/\{/g)?.length ?? 0) - (out.join("\n").match(/\}/g)?.length ?? 0) + if (open > 0) { + const indent = indentOf(lines[first]!).slice(pad) + out.push(`${indent} // …`, `${indent}}`) + } + return { text: out.join("\n"), start: start + 1, end: end + 1 } +} + +export function buildSnippets(root: string): Record<string, Snippet> { + const out: Record<string, Snippet> = {} + for (const [id, spec] of Object.entries(specs)) { + const parts = spec.pieces.map(p => cut(root, id, p)) + const gap = spec.lang === "rust" || spec.lang === "ts" ? "\n\n// …\n\n" : "\n\n# …\n\n" + const code = parts.map(p => p.text).join(gap) + // One cut links to its lines; several cuts or a whole file link to the file. + const one = spec.pieces.length === 1 && spec.pieces[0]!.from ? parts[0]! : undefined + out[id] = { + html: highlight(code, spec.lang), + label: spec.label, + file: spec.pieces[0]!.file, + start: one?.start ?? 0, + end: one?.end ?? 0, + } + } + return out +} + +const ID = "virtual:snippets" + +/** Serves the snippets as a module and reloads the page when a cited file changes in dev. */ +export function snippets(root: string): Plugin { + const files = new Set(Object.values(specs).flatMap(s => s.pieces.map(p => resolve(root, p.file)))) + return { + name: "rune-snippets", + resolveId: id => (id === ID ? `\0${ID}` : undefined), + load(id) { + if (id !== `\0${ID}`) return + for (const f of files) this.addWatchFile(f) + return `export default ${JSON.stringify(buildSnippets(root))}` + }, + handleHotUpdate({ file, server }) { + if (!files.has(file)) return + const mod = server.moduleGraph.getModuleById(`\0${ID}`) + if (mod) server.moduleGraph.invalidateModule(mod) + server.ws.send({ type: "full-reload" }) + }, + } +} diff --git a/app/vendor/rune/site/src/App.tsx b/app/vendor/rune/site/src/App.tsx new file mode 100644 index 0000000..92ff584 --- /dev/null +++ b/app/vendor/rune/site/src/App.tsx @@ -0,0 +1,173 @@ +import { useEffect, useState, type JSX, type MouseEvent } from "react" +import { Wordmark } from "./brand/Wordmark" +import { layers, milestones, principles, risks } from "./content" +import { FastAppsView } from "./FastApps" +import { ArchitectureView, HomeView, HowItWorksView, LaunchFastView, NotFoundView, PrinciplesView, RoadmapView, num } from "./pages" +import { stripBase, withBase } from "./base" +import { REPO, normalizePath } from "./routes" +import signature from "./footer-signature.svg" +import { Frame, type NavGroup, type NavItem } from "./system/Frame" + +function Brand() { + return ( + <a className="brand" href={withBase("/")} aria-label="Rune, overview"> + <Wordmark /> + </a> + ) +} + +function navGroups(pathname: string): NavGroup[] { + const page = (path: string, label: string, children: NavItem[]): NavItem => ({ + href: withBase(path), + label, + current: pathname === path, + children: pathname === path ? children : undefined, + }) + const spy = (id: string, label: string, n?: string): NavItem => ({ href: `#${id}`, label, spy: id, num: n }) + const heading = (id: string, label: string): NavItem => ({ href: `#${id}`, label, heading: true }) + + return [ + { + label: "Rune", + items: [ + page("/", "Overview", [ + spy("app", "A Rune app"), + spy("frame", "From code to screen"), + spy("how", "How do I…"), + spy("build", "What you can build"), + spy("next", "Next"), + ]), + page("/how-it-works", "How it works", [ + spy("frame", "A frame"), + spy("app", "A window and a view"), + spy("state", "State changes in handlers"), + spy("springs", "Springs keep their velocity"), + spy("live", "Values that skip the view"), + spy("threads", "Threads"), + spy("testing", "Tests without a window"), + spy("crates", "Where the code lives"), + ]), + page("/launch-fast", "Launch fast", [ + spy("prewarm", "prewarm_gpu"), + spy("metallib", "Precompiled shaders"), + spy("first-frame", "First frame at creation"), + spy("defer", "Defer setup"), + spy("still", "Keep the first second still"), + spy("idle", "Draw nothing when idle"), + spy("reuse", "Reuse a hidden window"), + spy("measure", "Measure it"), + spy("numbers", "Measured"), + ]), + page("/fast-apps", "Fast apps", [ + spy("main-thread", "The main thread never waits"), + spy("first-frame", "The first frame comes first"), + spy("lists", "Long lists"), + spy("memo", "Memo whole panels"), + spy("idle", "An idle window"), + spy("poll", "poll is cheap"), + spy("reads", "Read the size"), + spy("live-only", "live_only"), + spy("scrolling", "Smooth scrolling"), + spy("caches", "Bounded caches"), + spy("audit", "Audit a repo"), + ]), + page("/architecture", "Architecture", [ + spy("overview", "Overview"), + spy("channel", "The command channel"), + heading("layers", "Layers"), + ...layers.map((l, i) => spy(l.slug, l.title, num(i))), + heading("choices", "Choices"), + spy("decisions", "Decisions"), + spy("gpui", "Why not fork GPUI"), + ]), + page( + "/principles", + "Principles", + principles.map((p, i) => spy(p.slug, p.title, num(i))), + ), + page("/roadmap", "Roadmap", [ + heading("milestones", "Milestones"), + ...milestones.map(m => spy(m.id, m.title)), + heading("risks", "Risks"), + ...risks.map(r => spy(r.slug, r.title)), + ]), + ], + }, + { + label: "Source", + items: [ + { href: REPO, label: "GitHub" }, + { href: `${REPO}/blob/dev/PLAN.md`, label: "Plan" }, + { href: `${REPO}/tree/dev/research`, label: "Research notes" }, + ], + }, + ] +} + +function Footer() { + return ( + <footer className="site-footer"> + <div className="copyright"> + <img src={signature} alt="" aria-hidden="true" width={163} height={64} /> + <p> + ©2026 <a href="https://anoma.ly">Anomaly</a>. MIT licence + </p> + </div> + </footer> + ) +} + +// The site path for a browser path under the base; paths outside it fall through to the not-found view. +function sitePath(pathname: string): string { + return normalizePath(stripBase(pathname) ?? pathname) +} + +export function App({ pathname: initial }: { pathname?: string }) { + const [pathname, setPathname] = useState(() => + sitePath(initial ?? (typeof window !== "undefined" ? window.location.pathname : "/")), + ) + + useEffect(() => { + const onPopState = () => setPathname(sitePath(window.location.pathname)) + window.addEventListener("popstate", onPopState) + return () => window.removeEventListener("popstate", onPopState) + }, []) + + const onClick = (e: MouseEvent<HTMLDivElement>) => { + if (e.defaultPrevented || e.button !== 0 || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) return + const href = (e.target as HTMLElement | null)?.closest("a")?.getAttribute("href") + if (!href || !href.startsWith("/") || /\.\w+$/.test(href)) return + const url = new URL(href, window.location.origin) + const next = sitePath(url.pathname) + if (next === pathname) return + e.preventDefault() + window.history.pushState(null, "", `${url.pathname}${url.hash}`) + setPathname(next) + if (url.hash) requestAnimationFrame(() => document.getElementById(url.hash.slice(1))?.scrollIntoView()) + else window.scrollTo(0, 0) + } + + const views: Record<string, () => JSX.Element> = { + "/": HomeView, + "/how-it-works": HowItWorksView, + "/launch-fast": LaunchFastView, + "/fast-apps": FastAppsView, + "/principles": PrinciplesView, + "/architecture": ArchitectureView, + "/roadmap": RoadmapView, + } + const View = views[pathname] ?? NotFoundView + + return ( + <div className="site" onClick={onClick}> + <Frame + brand={<Brand />} + groups={navGroups(pathname)} + revealBrandAfter={pathname === "/" ? "home-hero" : undefined} + footer={<Footer />} + > + <View /> + </Frame> + </div> + ) +} diff --git a/app/vendor/rune/site/src/Code.tsx b/app/vendor/rune/site/src/Code.tsx new file mode 100644 index 0000000..663919e --- /dev/null +++ b/app/vendor/rune/site/src/Code.tsx @@ -0,0 +1,23 @@ +import snippets from "virtual:snippets" +import { REPO } from "./routes" + +/** A code example cut from Rune's source at build time (scripts/snippets.ts), with a link to the lines it came from. */ +export function Code({ id }: { id: string }) { + const s = snippets[id] + if (!s) throw new Error(`Unknown snippet "${id}"; add it to scripts/snippets.ts`) + const href = `${REPO}/blob/dev/${s.file}${s.start ? `#L${s.start}-L${s.end}` : ""}` + return ( + <figure className="code-block"> + <figcaption className="code-head"> + <a href={href}> + {s.file} + {s.start > 0 && <span className="code-lines">:{s.start}–{s.end}</span>} + </a> + <span className="code-lang">{s.label}</span> + </figcaption> + <pre className="code"> + <code dangerouslySetInnerHTML={{ __html: s.html }} /> + </pre> + </figure> + ) +} diff --git a/app/vendor/rune/site/src/Diagram.tsx b/app/vendor/rune/site/src/Diagram.tsx new file mode 100644 index 0000000..7d869c6 --- /dev/null +++ b/app/vendor/rune/site/src/Diagram.tsx @@ -0,0 +1,374 @@ +import type { CSSProperties, ReactNode } from "react" + +/** The architecture in one figure: the app side and the render thread, the command channel between them, and the + * platform shell under both. Plain HTML so the text stays crisp and the layout can stack on a phone. */ +export function ArchitectureDiagram() { + return ( + <figure className="arch" aria-labelledby="arch-caption"> + <div className="arch-grid"> + <section className="arch-box" data-area="app"> + <p className="arch-kicker">Main thread</p> + <h3>App side</h3> + <ul> + <li>Models: typed state, keyed by stable ids</li> + <li>View functions → keyed tree → diff</li> + <li>Taffy layout at the target state</li> + <li>Parley shaping and line cache</li> + <li>Handlers, queued between frames</li> + <li>Accessibility tree updates</li> + </ul> + </section> + + <div className="arch-channel" data-area="channel"> + <p className="arch-channel-label">Command channel</p> + <div className="arch-flow" data-dir="fwd"> + <span className="arch-arrow" aria-hidden="true" /> + <span className="arch-flow-text">tree diffs, target rects, text runs, spring targets</span> + </div> + <div className="arch-flow" data-dir="back"> + <span className="arch-arrow" aria-hidden="true" /> + <span className="arch-flow-text">hits, gestures, settles, frame ids</span> + </div> + </div> + + <section className="arch-box" data-area="render"> + <p className="arch-kicker">Paced by the display</p> + <h3>Render thread</h3> + <ul> + <li>Presented tree: what's on screen now</li> + <li>Spring tracks that retarget with velocity</li> + <li>Exiting nodes, edge-by-edge layout motion</li> + <li>Scroll physics, drags applied 1:1</li> + </ul> + <div className="arch-inner"> + <p className="arch-inner-title">Renderer · wgpu</p> + <ul> + <li>One instanced pass: rects, shadows, glyphs, vectors</li> + <li>Soft-edge clip on every instance</li> + </ul> + </div> + </section> + + <section className="arch-box arch-shell" data-area="shell"> + <div> + <p className="arch-kicker">Per platform</p> + <h3>Shell</h3> + <p className="arch-line">Windows and panels, menus, clipboard, text input protocol, accessibility adapter, lifecycle</p> + </div> + <div data-optional> + <p className="arch-kicker">Apple, optional</p> + <h3>Native layers</h3> + <p className="arch-line">System glass and video behind Rune's layer, masked by the render thread each frame</p> + </div> + </section> + </div> + <figcaption id="arch-caption"> + The app side states targets and the render thread animates toward them. Everything that crosses between them + goes through the command channel. + </figcaption> + </figure> + ) +} + +type Step = { name: string; does: string; at: string } + +const everyFrameBefore: Step[] = [ + { name: "Input", does: "The window queues clicks, keys and scrolls; poll() reads outside data.", at: "window.rs" }, + { name: "Handlers", does: "Queued handlers run with &mut access to the app's state.", at: "runtime.rs" }, +] +const onChange: Step[] = [ + { name: "View", does: "The view function returns a keyed El tree, matched to the last one by key.", at: "fn view(&S, &mut Cx<S>) -> El" }, + { name: "Layout", does: "Taffy lays the tree out at its target state; Parley shapes the text.", at: "Taffy, Parley" }, + { name: "Targets", does: "Each changed rect, colour or opacity retargets its spring.", at: "rune-motion Scene" }, +] +const everyFrameAfter: Step[] = [ + { name: "Springs", does: "Every track is sampled at the frame's time; scroll and reveals step too.", at: "rune-motion" }, + { name: "Draw", does: "Rects, shadows and glyphs become instances in one wgpu pipeline.", at: "render.rs" }, +] + +function Steps({ steps, from }: { steps: Step[]; from: number }) { + return steps.map((s, i) => ( + <li key={s.name} className="dg-step"> + <span className="dg-num">{String(from + i).padStart(2, "0")}</span> + <span className="dg-name">{s.name}</span> + <span className="dg-does">{s.does}</span> + <code className="dg-at">{s.at}</code> + </li> + )) +} + +/** One frame, top to bottom, as `Runtime::frame` and the window's redraw run it today. */ +export function FrameDiagram() { + return ( + <figure className="dg" aria-labelledby="frame-caption"> + <ol className="dg-flow"> + <Steps steps={everyFrameBefore} from={1} /> + <li className="dg-group"> + <p className="dg-group-label">Only when state changed</p> + <ol className="dg-flow"> + <Steps steps={onChange} from={3} /> + </ol> + </li> + <Steps steps={everyFrameAfter} from={6} /> + </ol> + <figcaption id="frame-caption"> + Steps 3–5 run only after a handler or <code>poll()</code> changes state. A frame that is only animating runs + 1, 2, 6 and 7, and a settled window doesn't draw at all. + </figcaption> + </figure> + ) +} + +/** Who runs what: one thread today, and the split PLAN.md §3 describes. */ +export function ThreadDiagram() { + return ( + <figure className="dg" aria-labelledby="threads-caption"> + <div className="dg-pair"> + <section className="dg-panel"> + <p className="dg-kicker">Today</p> + <div className="dg-box"> + <h3>Main thread, winit event loop</h3> + <ul> + <li>Input and handlers</li> + <li>View, Taffy and Parley, on a change</li> + <li>Springs: the Runtime's Scene, sampled each frame</li> + <li>wgpu encode and present</li> + </ul> + </div> + <div className="dg-feeds"> + <div className="dg-box dg-small"> + <h3>Your threads</h3> + <p><code>Live&lt;T&gt;::set</code> writes an atomic and wakes the window, without re-running the view</p> + </div> + <div className="dg-box dg-small"> + <h3>rune-images</h3> + <p>Decodes images, then wakes the window</p> + </div> + </div> + </section> + <section className="dg-panel" data-planned> + <p className="dg-kicker">Planned</p> + <div className="dg-box"> + <h3>App side, main thread</h3> + <ul> + <li>Handlers, view, diff</li> + <li>Taffy and Parley</li> + </ul> + </div> + <p className="dg-link"> + <span className="dg-arrow" aria-hidden="true" /> + Command channel: diffs, rects, spring targets down; hits and settles back + </p> + <div className="dg-box"> + <h3>Render thread, paced by the display</h3> + <ul> + <li>Owns the springs, scroll and drags</li> + <li>wgpu encode and present</li> + </ul> + </div> + </section> + </div> + <figcaption id="threads-caption"> + Today one thread runs every step. Animation still skips app code, because the view only re-runs when state + changes. The plan moves springs and drawing to a render thread, so a slow handler can't stall an animation + that's already moving. + </figcaption> + </figure> + ) +} + +type Crate = { name: string; does: string } + +const crateRows: { label: string; crates: Crate[] }[] = [ + { + label: "Apps", + crates: [{ name: "examples/*", does: "settings, opencode, kit-gallery, live-values, shapes and others" }], + }, + { + label: "Components", + crates: [ + { name: "rune-kit", does: "Button, Switch, Select, Menu, TextField…, reading only semantic tokens" }, + { name: "themes/opencode", does: "OpenCode's tokens, fonts and icons as a rune-kit theme" }, + ], + }, + { + label: "Framework", + crates: [ + { + name: "rune", + does: "El tree, runtime, renderer, windows, overlays and headless tooling; re-exports the crates below", + }, + ], + }, + { + label: "Subsystems", + crates: [ + { name: "rune-text", does: "Parley shaping and layout, font discovery, glyph atlas, icons" }, + { name: "rune-media", does: "Video and audio playback, zero-copy native surfaces, recording" }, + { name: "rune-image", does: "Content-addressed image decoding, linear-light mips, SVG/AVIF, app icons" }, + { name: "rune-spell", does: "Platform spellchecking (Windows, macOS, web Hunspell)" }, + ], + }, + { + label: "Foundations", + crates: [ + { name: "rune-core", does: "Colour, tokens, themes, shapes, state machines, tasks, live values" }, + { name: "rune-gpu", does: "Adapter selection, backend dispatch, native Metal backend, GPU springs" }, + { name: "rune-motion · rune-staging · rune-taffy", does: "Springs and presence, GPU staging, compact layout store" }, + { name: "wgpu · winit · Taffy · Parley", does: "GPU, windows, layout, text" }, + ], + }, +] + +const crateSide: Crate[] = [ + { name: "rune-ref", does: "CPU reference renderer and golden hashes" }, + { name: "rune-fx", does: "Effect layers: glow, fire, motion blur" }, + { name: "rune-light", does: "Lighting: soft shadows, god rays, GI" }, +] + +/** The workspace: each row builds on the rows below it; the side column is optional. */ +export function CrateMap() { + return ( + <figure className="dg" aria-labelledby="crates-caption"> + <div className="dg-crates"> + <ol className="dg-layers"> + {crateRows.map(row => ( + <li key={row.label} className="dg-layer"> + <p className="dg-kicker">{row.label}</p> + <div className="dg-layer-row"> + {row.crates.map(c => ( + <div key={c.name} className="dg-box dg-small"> + <h3><code>{c.name}</code></h3> + <p>{c.does}</p> + </div> + ))} + </div> + </li> + ))} + </ol> + <aside className="dg-side"> + <p className="dg-kicker">Beside the core</p> + {crateSide.map(c => ( + <div key={c.name} className="dg-box dg-small"> + <h3><code>{c.name}</code></h3> + <p>{c.does}</p> + </div> + ))} + </aside> + </div> + <figcaption id="crates-caption"> + Apps depend on <code>rune</code>, which re-exports the subsystem and foundation crates below it. The crates + beside the core are optional. + </figcaption> + </figure> + ) +} + +/** How a test drives the same runtime the window uses, and what it can check. */ +export function TestDiagram() { + return ( + <figure className="dg" aria-labelledby="tests-caption"> + <div className="dg-test"> + <div className="dg-box dg-small" data-area="in"> + <h3>Start</h3> + <p>A state, often a named scene, and an optional <code>--script</code> of taps at exact times</p> + </div> + <span className="dg-arrow" data-area="a1" aria-hidden="true" /> + <div className="dg-box dg-small" data-area="rt"> + <h3><code>Runtime</code></h3> + <p>The window's runtime, stepped by <code>frame(dt)</code> on a virtual clock, with no window</p> + </div> + <span className="dg-arrow" data-area="a2" aria-hidden="true" /> + <ul className="dg-outs" data-area="out"> + <li className="dg-box dg-small"> + <h3><code>elements()</code></h3> + <p>Rects, text and opacity for <code>assert!</code> in <code>cargo test</code>, no GPU</p> + </li> + <li className="dg-box dg-small"> + <h3><code>--snap</code>, <code>--frames</code></h3> + <p>Offscreen wgpu to PNG, compared byte for byte with pinned images</p> + </li> + <li className="dg-box dg-small"> + <h3><code>--trace</code></h3> + <p>Per-frame rects and opacity as JSONL; motion-lint fails pops, jumps and jitter</p> + </li> + </ul> + </div> + <figcaption id="tests-caption"> + Tests and agents run the same code path as the window, minus the window. Time only moves when the test steps it, + so a run repeats exactly. + </figcaption> + </figure> + ) +} + +type Link = { name: ReactNode; does: ReactNode } + +/** Boxes left to right with an arrow between each (top to bottom on a phone), and an optional line back from the end + * to the start for a loop. */ +function Chain({ id, links, back, caption }: { id: string; links: Link[]; back?: ReactNode; caption: ReactNode }) { + return ( + <figure className="dg" aria-labelledby={`${id}-caption`}> + <ol className="dg-chain" style={{ "--links": links.length } as CSSProperties}> + {links.map((l, i) => ( + <li key={i} className="dg-box dg-small"> + <h3>{l.name}</h3> + <p>{l.does}</p> + </li> + ))} + </ol> + {back && ( + <p className="dg-back"> + <span className="dg-back-line" aria-hidden="true" /> + <span className="dg-back-label">{back}</span> + </p> + )} + <figcaption id={`${id}-caption`}>{caption}</figcaption> + </figure> + ) +} + +/** From the code you write to pixels, for one frame. */ +export function PipelineDiagram() { + return ( + <Chain + id="pipeline" + links={[ + { name: "Your state", does: <>A plain struct, changed only by handlers with <code>&amp;mut</code> access</> }, + { name: <code>view()</code>, does: <>Returns a keyed <code>El</code> tree: what should be on screen</> }, + { name: "Layout", does: "Taffy places every node at its target; Parley shapes the text" }, + { name: "Springs", does: "Each moved rect, colour or opacity animates from where it is now" }, + { name: "GPU", does: "Rects, shadows and glyphs as instances, usually one wgpu draw call" }, + ]} + back="A tap runs a handler, the state changes, and the view runs again" + caption={ + <> + Your code runs in the first two boxes. Rune does the rest, and while something animates it repeats only the + last two, so your view isn't called again until the state changes. + </> + } + /> + ) +} + +/** One state change, from the event to the spring targets. */ +export function StateLoopDiagram() { + return ( + <Chain + id="state-loop" + links={[ + { name: "Event", does: "A tap, key or poll() result is queued by the window" }, + { name: "Handler", does: <><code>|s: &amp;mut State|</code> runs between frames</> }, + { name: <code>view(&amp;State)</code>, does: "Builds the whole tree again from the new state" }, + { name: "Diff by key", does: "Nodes with the same key are the same node, so they move instead of popping" }, + { name: "Targets", does: <>Changed properties retarget their springs, using the node's <code>.motion()</code></> }, + ]} + caption={ + <> + A view never animates anything itself. It says where things are, and the diff turns the difference into + spring targets. + </> + } + /> + ) +} diff --git a/app/vendor/rune/site/src/FastApps.tsx b/app/vendor/rune/site/src/FastApps.tsx new file mode 100644 index 0000000..11ba49a --- /dev/null +++ b/app/vendor/rune/site/src/FastApps.tsx @@ -0,0 +1,396 @@ +import { withBase } from "./base" +import { PageHead, SectionHead } from "./system/Frame" +import { Pager, Sample } from "./pages" + +const blockingBefore = `// Before: a socket round trip on every keystroke, on the main thread. +.on_input_change(|s: &mut Search, _| { + s.hits = index.search(&s.query.text); // blocks the window for the whole round trip +})` + +const blockingAfter = `// After: init builds it once; the handler asks, poll collects. +results: Latest::default().debounce(Duration::from_millis(60)), // init +s.results.set_waker(waker); // setup + +.on_input_change(|s: &mut Search, _| { + let q = s.query.text.clone(); + s.results.request(q, move |q| index.search(&q)); // runs on a worker +}) +fn poll(s: &mut Search, _: f64, _: &mut Tx) -> bool { + let Some(hits) = s.results.take() else { return false }; // newest answer only + s.hits = hits; + true +}` + +const listBefore = `// Before: every message is built each commit, then virtualized. +col().key("rows").growth(GrowthSpec::default()) + .virtualize(72.0) + .children(s.messages.iter().map(|m| message(m)))` + +const listAfter = `// After: only the rows in the mounted window are built. +col().key("rows").growth(GrowthSpec::default()).virtual_rows( + s.messages.len(), + 72.0, + |s: &Chat, i| s.messages[i].id.as_str().into(), + |s: &Chat, i| { + let m = &s.messages[i]; + memo(&m.id, m.revision, || message(m)) + }, +)` + +const memoBefore = `// Before: the version is the whole document, hashed on every frame. +memo("reader", s.markdown.clone(), || render_markdown(&s.markdown))` + +const memoAfter = `// After: an id and a counter the edit bumps. +memo("reader", (s.note_id, s.edits), || render_markdown(&s.markdown))` + +const loopBefore = `// Before: asks for a frame every 16 ms for as long as the window is open. +fn poll(s: &mut App, _: f64, tx: &mut Tx) -> bool { + tx.wake_after(Duration::from_millis(16)); + s.tick(); + true +}` + +const loopAfter = `// After: the loop runs while something moves, then stops. +fn poll(s: &mut App, _: f64, tx: &mut Tx) -> bool { + if !s.recording { return false } + tx.wake_after(Duration::from_millis(16)); + s.tick(); + true +}` + +const pollBefore = `// Before: always "changed", so every wake draws. +fn poll(s: &mut App, _: f64, _: &mut Tx) -> bool { + s.reload_from_disk(); + true +}` + +const pollAfter = `// After: cheap when nothing happened, true only on a change. +fn poll(s: &mut App, _: f64, _: &mut Tx) -> bool { + let Some(next) = s.updates.take() else { return false }; + s.apply(next); + true +}` + +const rectBefore = `// Before: the view re-runs every frame the feed scrolls. +let height = cx.window_layout("feed").map(|r| r[3]);` + +const rectAfter = `// After: it re-runs when the height changes. +let height = cx.layout_size("feed").map(|[_, h]| h);` + +const liveBefore = `// Before: each scroll or zoom event re-runs the view. +.on_magnify(|s: &mut Canvas, e, _| { + s.camera.zoom_about(e.x, e.y, 1.0 + e.delta); + true +})` + +const liveAfter = `// After: the handler moves Live values and skips the view. +.on_magnify(|s: &mut Canvas, e, tx| { + s.camera.zoom_about(e.x, e.y, 1.0 + e.delta); // sets Live values only + tx.live_only(); + true +})` + +const cacheBefore = `// Before: one entry per size ever asked for. +thread_local! { static SIZES: RefCell<HashMap<String, [f32; 2]>> = Default::default(); }` + +const cacheAfter = `// After: a bound in entries; evict when it is passed. +const MAX: usize = 256; +fn remember(key: String, size: [f32; 2]) { + SIZES.with_borrow_mut(|m| { + if m.len() >= MAX { m.clear() } + m.insert(key, size); + }) +}` + +const hoverBefore = `// Before: every row the pointer crosses commits the view. +row().on_hover_change(move |s: &mut Inbox, inside, _| s.hovered = inside.then_some(id)) + .fill(if s.hovered == Some(id) { theme.hover } else { theme.row })` + +const hoverAfter = `// After: Rune paints the hover; no state, no commit. +row().fill(theme.row).hover(theme.hover)` + +const glideBefore = `// Before: the app steps its own glide, one commit a frame. +fn poll(s: &mut Reader, _: f64, tx: &mut Tx) -> bool { + if s.y == s.target { return false } + s.y += (s.target - s.y) * 0.2; + tx.scroll_to_instant("page", 0.0, s.y); + tx.wake_after(Duration::from_millis(16)); + true +}` + +const glideAfter = `// After: one request; Rune glides on its own clock. +tx.scroll_to_with("page", 0.0, target, Spring::smooth(0.35, 0.0));` + +const anchorBefore = `// Before: older messages load above and push the one being read down. +col().key("thread").scroll(ScrollSpec { stick_bottom: true }).child(messages(s))` + +const anchorAfter = `// After: the message at the top of the view stays put. +col().key("thread").scroll(ScrollSpec { stick_bottom: true }).scroll_anchor().child(messages(s))` + +function Pair({ before, after }: { before: string; after: string }) { + return ( + <div className="code-stack"> + <Sample>{before}</Sample> + <Sample>{after}</Sample> + </div> + ) +} + +export function FastAppsView() { + return ( + <> + <PageHead eyebrow={<span>Fast apps</span>} title="Fast apps"> + <p> + A Rune app feels fast when its main thread is free, its first frame is small, its lists build only what is on + screen and an idle window draws nothing. Each rule below is one way a slow app breaks it, with a before and + after. Where Rune can see the mistake, debug builds print a warning once per call site on stderr;{" "} + <code>RUNE_PERF_WARN=0</code> silences them, and release builds contain none of it. + </p> + <p> + Getting the first window up fast is its own page: <a href={withBase("/launch-fast")}>Launch fast</a>, which + has <code>rune::prewarm_gpu()</code> and the measured numbers. + </p> + </PageHead> + + <section className="doc-section"> + <SectionHead id="main-thread" title="The main thread never waits"> + <p> + A socket, an HTTP request, a database query, a spawned process or a large file read does not belong in{" "} + <code>view</code>, a handler, <code>poll</code> or <code>init</code>. The window stops for the whole wait. + </p> + </SectionHead> + <div className="prose"> + <p> + Debug builds warn when a handler, <code>poll</code> or <code>init</code> spends over 8 ms waiting rather + than computing: "blocked on the main thread". Do the work on a thread and bring the answer back through{" "} + <code>poll</code>. For a search box or any request where only the newest answer matters, use{" "} + <code>rune::Latest</code>: it supersedes older requests, debounces, and wakes the window once per answer. + </p> + </div> + <Pair before={blockingBefore} after={blockingAfter} /> + </section> + + <section className="doc-section"> + <SectionHead id="first-frame" title="The first frame comes first"> + <p> + <code>init</code> builds what the first frame shows from memory or a small file. Everything else, such as + status items, network and indexing, starts in <code>on_ready</code>, after the first frame. The details are + on <a href={withBase("/launch-fast#defer")}>Launch fast</a>. + </p> + </SectionHead> + <div className="prose"> + <p> + Debug builds warn when setup in <code>main</code> before <code>run</code>, <code>init</code> and the first{" "} + <code>view</code> take over 100 ms between them before the first frame, and name the slowest. Rune's own + window and GPU time doesn't count toward it. + </p> + </div> + </section> + + <section className="doc-section"> + <SectionHead id="lists" title="Long lists build only what is on screen"> + <p> + <code>virtualize</code> mounts only the visible rows, but it takes rows you have already built, so a + thousand-message list still builds a thousand messages on every commit.{" "} + <code>virtual_rows</code> takes a count and a closure and builds only the mounted window, with row content + built inside the closure. + </p> + </SectionHead> + <div className="prose"> + <p> + Debug builds warn when a <code>virtualize</code> list is handed over 200 rows and more than four times what + it mounts, and name the call site. Use <code>virtualize</code> for short lists only. Handlers in a row find + their item by key or id, never by index. + </p> + </div> + <Pair before={listBefore} after={listAfter} /> + </section> + + <section className="doc-section"> + <SectionHead id="memo" title="Memo whole panels, keyed small"> + <p> + <code>memo(id, version, build)</code> reuses a subtree until its version changes. A hit no longer deep + clones the subtree, and layout and apply are reused for unchanged subtrees, so wrapping a whole panel pays + off, not only the rows of a list. + </p> + </SectionHead> + <div className="prose"> + <p> + The version is hashed every frame, so keep it small: an id plus an edit counter that the edit bumps. Never + key a memo by a large value such as a Markdown source. Hashing or comparing it costs what the memo saves. + Anything the closure reads that can change belongs in the version, except <code>Cx::layout</code> reads, + which Rune tracks. + </p> + </div> + <Pair before={memoBefore} after={memoAfter} /> + </section> + + <section className="doc-section"> + <SectionHead id="idle" title="An idle window draws nothing"> + <p> + <code>poll</code> returns true only when visible state changed, and a <code>wake_after</code> loop has an + end condition. A wake on a resting window runs <code>poll</code> first and draws only if it returns true. + </p> + </SectionHead> + <Pair before={loopBefore} after={loopAfter} /> + <div className="prose prose-after"> + <p> + Debug builds warn when <code>poll</code> returns true for 30 frames in a row while nothing on screen + changes, and when a window draws 120 frames within 2 s with no input, motion or visible change; the warning + names what woke it, such as a <code>wake_after</code> loop. + </p> + <p> + Check it with <code>procwatch</code>: an app with its window shown and untouched should sit near zero CPU. + </p> + </div> + </section> + + <section className="doc-section"> + <SectionHead id="poll" title="poll is cheap, and honest"> + <p> + <code>poll</code> runs on every frame the window is awake. On a frame where nothing happened it should cost + microseconds and allocate nothing: drain a channel, compare a generation counter or an mtime. Never reload, + parse or scan in it. + </p> + </SectionHead> + <Pair before={pollBefore} after={pollAfter} /> + </section> + + <section className="doc-section"> + <SectionHead id="reads" title="Read the size, not the rect"> + <p> + A view that calls <code>Cx::window_layout</code> re-runs when the rect moves past half a point, and inside a + scroll view it moves every frame. <code>Cx::layout</code> reads the rect unscrolled, so only a commit moves it. + If you use only the size, read <code>Cx::layout_size</code>; for anything else, <code>Cx::layout_with</code>{' '} + and <code>Cx::window_layout_with</code> re-run the view only when your answer changes. + </p> + </SectionHead> + <Pair before={rectBefore} after={rectAfter} /> + </section> + + <section className="doc-section"> + <SectionHead id="live-only" title="Scroll and zoom handlers skip the view"> + <p> + A handler that only moves a <code>Live</code> value, such as a scroll position, a zoom or a transform, calls{" "} + <code>Tx::live_only()</code>, so the frame doesn't commit state and re-run the view. Debug builds check for + a handler that said <code>live_only</code> but changed what the view reads. + </p> + </SectionHead> + <Pair before={liveBefore} after={liveAfter} /> + </section> + + <section className="doc-section"> + <SectionHead id="scrolling" title="Smooth scrolling"> + <p> + A scroll costs Rune no commit: it moves the content, mounts <code>virtual_rows</code> and paints{" "} + <code>El::hover</code> styles without running <code>view</code>. A frame that commits while a viewport + scrolls is the app's, and on a long page one commit can take more than the 8 ms a 120 Hz frame has. + </p> + </SectionHead> + <div className="prose"> + <ul> + <li> + <code>poll</code> returns true only when visible state changed. To act on where a scroll stops, wait + until it has been still a moment with <code>Tx::wake_after</code>; follow it frame by frame with{" "} + <code>El::on_scroll_offset</code> and live values. + </li> + <li> + Hover is a style, not state: <code>El::hover</code>, <code>hover_group</code> and <code>group_*</code>{" "} + styles. A scroll moves rows under a still pointer, so state set from <code>on_hover_change</code> commits + for each one. + </li> + <li> + <code>on_layout</code> and <code>on_drawn_layout</code> report every frame of a scroll for an element + inside it. Use their <code>_tx</code> forms and say <code>Tx::live_only</code> when the handler only + moves live values or bookkeeping. + </li> + <li> + Read <code>Cx::layout_size</code> or <code>Cx::layout</code>, not <code>Cx::window_layout</code>, as + above. + </li> + <li> + Glide with <code>Tx::scroll_to_with</code> rather than an instant scroll stepped every frame. + </li> + </ul> + </div> + <Pair before={hoverBefore} after={hoverAfter} /> + <Pair before={glideBefore} after={glideAfter} /> + <div className="prose prose-after"> + <p> + Debug builds name the source when one keeps committing through a scroll: <code>poll</code>, a handler with + its element and where it was set, or the layout read that moved. Each warns once, when it commits on 6 or + more frames and a quarter of a scroll's frames. They also warn when an app steps a viewport with an + instant scroll on 8 committing frames in a row, and when one hover handler commits for 8 different elements. + </p> + <p> + <code>RUNE_COMMIT_BUDGET_MS=8</code> prints a line for each commit over 8 ms, in any build, release + included, with where its time went (view, layout, text, apply) and what made the frame commit, at most + once a second. + </p> + <p> + <code>El::scroll_anchor()</code> keeps the reading position when content above it changes: rows load + above, an image grows, a new width reflows the text. On a scroll viewport it holds the row at the top of + the view across each commit, like CSS <code>overflow-anchor</code>, while the viewport is still, off its + top and not following its bottom. <code>virtual_rows</code> lists already do this;{" "} + <code>Tx::keep_on_screen</code> holds a chosen element for one commit. + </p> + </div> + <Pair before={anchorBefore} after={anchorAfter} /> + </section> + + <section className="doc-section"> + <SectionHead id="caches" title="Every cache has a bound"> + <p> + A cache bounds its entries and its bytes, counting decoded pixels rather than encoded size, so a long + session can't grow it without end. A <code>static</code> map that only ever inserts is a leak with a + lookup. Evict by count, by age or by byte budget, and test the bound. + </p> + </SectionHead> + <Pair before={cacheBefore} after={cacheAfter} /> + </section> + + <section className="doc-section"> + <SectionHead id="audit" title="Audit a repo in seconds"> + <p> + <code>scripts/app-audit &lt;repo&gt;</code> greps an app's Rust files for the patterns above and prints one + line per finding with <code>file:line</code>. + </p> + </SectionHead> + <div className="prose"> + <ul> + <li> + <code>.virtualize(</code> next to a built <code>.children(</code>, <code>.child(</code> or push loop. + </li> + <li> + <code>Command::new</code>, <code>UnixStream</code>, <code>TcpStream</code>,{" "} + <code>reqwest::blocking</code>, <code>rusqlite</code> and <code>read_to_string</code> in a file that + defines <code>view</code>, <code>poll</code>, <code>init</code> or a handler. + </li> + <li> + A <code>wake_after</code> of 33 ms or less with no <code>if</code>, <code>match</code> or{" "} + <code>return</code> just before it. + </li> + <li> + <code>layout(..)</code> read only for <code>[2]</code> or <code>[3]</code>. + </li> + <li> + A <code>static</code> map in a file with no <code>retain</code>, <code>remove</code> or{" "} + <code>clear</code>. + </li> + <li> + <code>window_layout(</code>; <code>on_layout</code>, <code>on_drawn_layout</code>,{" "} + <code>on_hover</code> or <code>on_hover_change</code> with no <code>live_only</code> just after; and{" "} + <code>scroll_to_instant</code> near a <code>wake_after</code>. + </li> + </ul> + <p> + It is crude: a finding is a place to look, not a verdict. <code>--strict</code> exits 1 when there are + findings. The warnings above catch more, while the app runs; the audit also covers code a run didn't reach. + </p> + </div> + </section> + + <Pager prev={["/launch-fast", "Launch fast"]} next={["/architecture", "Architecture"]} /> + </> + ) +} diff --git a/app/vendor/rune/site/src/base.ts b/app/vendor/rune/site/src/base.ts new file mode 100644 index 0000000..edac1b8 --- /dev/null +++ b/app/vendor/rune/site/src/base.ts @@ -0,0 +1,20 @@ +// The site lives under /team/rune on anoma.ly (production) and dev.anoma.ly (dev). +// Pages and files keep root-relative paths internally ("/principles"); these helpers add and +// remove the prefix at the edges. +export const BASE_PATH = "/team/rune" + +// The build mode (`--mode dev`) picks the environment; every other mode builds production. +export function hostForMode(mode: string | undefined): string { + return mode === "dev" ? "dev.anoma.ly" : "anoma.ly" +} + +export function withBase(path: string): string { + return `${BASE_PATH}${path}` +} + +// Returns the site path for a request path, or undefined when it is outside the base. +export function stripBase(pathname: string): string | undefined { + if (pathname === BASE_PATH) return "/" + if (!pathname.startsWith(`${BASE_PATH}/`)) return undefined + return pathname.slice(BASE_PATH.length) +} diff --git a/app/vendor/rune/site/src/brand/Wordmark.tsx b/app/vendor/rune/site/src/brand/Wordmark.tsx new file mode 100644 index 0000000..c8411c0 --- /dev/null +++ b/app/vendor/rune/site/src/brand/Wordmark.tsx @@ -0,0 +1,41 @@ +import { useEffect, useRef, type CSSProperties } from "react" +import { attachTriggers, fadeSwap, glint } from "./motion" +import { WORDMARK, carveOrder, runs } from "./pixels" + +const { glyphs, width, height } = WORDMARK +const rune = glyphs[0]! +const carve = carveOrder(rune.rows) + +/** ᚱUNE in pixel letters. Hover runs a light down the ᚱ's strokes (a fade under reduced motion); `periodic`, the home + * masthead, also plays it every 5–9 s while it's on screen. */ +export function Wordmark({ periodic = false }: { periodic?: boolean }) { + const ref = useRef<HTMLSpanElement>(null) + + useEffect(() => { + const box = ref.current + if (!box) return + const print = box.querySelector<SVGGElement>(".wordmark-rune")! + const light = glint([...box.querySelectorAll<SVGRectElement>(".wordmark-glint rect")].map(el => ({ el, order: Number(el.dataset.order) }))) + return attachTriggers(box, reduced => (reduced ? fadeSwap(print, lit => print.classList.toggle("is-lit", lit)) : light()), { periodic }) + }, [periodic]) + + return ( + <span ref={ref} className="wordmark" style={{ "--cells": width, aspectRatio: `${width} / ${height}` } as CSSProperties}> + <svg viewBox={`0 0 ${width} ${height}`} shapeRendering="crispEdges" aria-hidden="true" focusable="false"> + <g className="wordmark-rune"> + {runs(rune.rows, rune.x).map(([x, y, w, h], i) => <rect key={i} x={x} y={y} width={w} height={h} />)} + <g className="wordmark-glint"> + {carve.map(([x, y, order]) => ( + <rect key={`${x},${y}`} x={rune.x + x} y={y} width={1} height={1} fillOpacity={0} data-order={order.toFixed(4)} /> + ))} + </g> + </g> + {glyphs.slice(1).map(g => ( + <g key={g.char}> + {runs(g.rows, g.x).map(([x, y, w, h], i) => <rect key={i} x={x} y={y} width={w} height={h} />)} + </g> + ))} + </svg> + </span> + ) +} diff --git a/app/vendor/rune/site/src/brand/motion.ts b/app/vendor/rune/site/src/brand/motion.ts new file mode 100644 index 0000000..e82f0f2 --- /dev/null +++ b/app/vendor/rune/site/src/brand/motion.ts @@ -0,0 +1,124 @@ +// The wordmark's motion: one shared frame loop that only runs while something moves, the carve glint, the reduced +// motion fade, and the hover and idle triggers. Nothing plays on first paint. + +type Tick = (dt: number) => boolean | void + +const ticks = new Set<Tick>() +let raf = 0 +let last = 0 + +/** Run `tick` every frame until it returns false. */ +export function animate(tick: Tick) { + ticks.add(tick) + if (!raf) { + last = performance.now() + raf = requestAnimationFrame(frame) + } + return () => ticks.delete(tick) +} + +function frame(now: number) { + const dt = Math.min(.05, (now - last) / 1000) + last = now + for (const tick of [...ticks]) if (tick(dt) === false) ticks.delete(tick) + raf = ticks.size ? requestAnimationFrame(frame) : 0 +} + +export const reducedMotion = () => matchMedia("(prefers-reduced-motion: reduce)").matches + +const easeInOut = (p: number) => (p < .5 ? 2 * p * p : 1 - (-2 * p + 2) ** 2 / 2) + +function invert(y: number, ease: (p: number) => number) { + let lo = 0, hi = 1 + for (let i = 0; i < 20; i++) { + const m = (lo + hi) / 2 + if (ease(m) < y) lo = m + else hi = m + } + return (lo + hi) / 2 +} + +/** A light runs along `cells` in carve order over `travel` s; each cell warms in 40 ms and cools with a 180 ms time + * constant, so nothing cuts out. A replay mid-run restarts the head. */ +export function glint(cells: { el: SVGElement; order: number }[], { travel = .7, rise = .04, tau = .18 } = {}) { + const at = cells.map(c => invert(c.order, easeInOut) * travel) + let t = -1 + const tick = (dt: number) => { + t += dt + let alive = false + cells.forEach((c, i) => { + const since = t - at[i]! + let h = since < 0 ? 0 : since < rise ? since / rise : Math.exp(-(since - rise) / tau) + if (since < 0 || h > .004) alive = true + else h = 0 + c.el.setAttribute("fill-opacity", h.toFixed(3)) + }) + if (!alive) t = -1 + return alive + } + return () => { + const idle = t < 0 + t = 0 + if (idle) animate(tick) + } +} + +/** Reduced motion: no travel. Fade `el` out, show the lit pose, fade in, hold, and back; 90 ms fades. */ +export function fadeSwap(el: SVGElement | HTMLElement, pose: (lit: boolean) => void, hold = .5) { + const FADE = .09 + const plan: [number, number, number, (() => void)?][] = [ + [FADE, 1, 0, () => pose(true)], + [FADE, 0, 1], + [hold, 1, 1], + [FADE, 1, 0, () => pose(false)], + [FADE, 0, 1], + ] + let i = 0, t = 0 + animate(dt => { + t += dt + while (i < plan.length && t >= plan[i]![0]) { + t -= plan[i]![0] + plan[i]![3]?.() + i++ + } + if (i >= plan.length) { + el.style.opacity = "" + return false + } + const [d, a, b] = plan[i]!, p = t / d + el.style.opacity = String(a + (b - a) * (b > a ? 1 - (1 - p) ** 2 : p * p)) + }) +} + +let lastScroll = -Infinity +if (typeof window !== "undefined") addEventListener("scroll", () => { lastScroll = performance.now() }, { passive: true, capture: true }) + +/** Play on hover; `periodic` adds an idle play every 5–9 s while `host` is on screen, the tab is visible, the page + * isn't scrolling and motion isn't reduced. The first one fires 5–9 s after load. Returns a cleanup. */ +export function attachTriggers(host: HTMLElement, play: (reduced: boolean) => void, { periodic = false } = {}) { + const enter = () => play(reducedMotion()) + host.addEventListener("pointerenter", enter) + if (!periodic) return () => host.removeEventListener("pointerenter", enter) + + let visible = false, timer = 0 + const schedule = () => { + clearTimeout(timer) + if (!visible || document.hidden) return + timer = window.setTimeout(() => { + if (!reducedMotion() && performance.now() - lastScroll > 500) play(false) + schedule() + }, (5 + Math.random() * 4) * 1000) + } + const observer = new IntersectionObserver(([entry]) => { + visible = entry!.isIntersecting + schedule() + }) + observer.observe(host) + document.addEventListener("visibilitychange", schedule) + return () => { + host.removeEventListener("pointerenter", enter) + observer.disconnect() + document.removeEventListener("visibilitychange", schedule) + clearTimeout(timer) + } +} diff --git a/app/vendor/rune/site/src/brand/pixels.ts b/app/vendor/rune/site/src/brand/pixels.ts new file mode 100644 index 0000000..8614922 --- /dev/null +++ b/app/vendor/rune/site/src/brand/pixels.ts @@ -0,0 +1,159 @@ +// ᚱUNE on Anomaly's pixel grid: letters 11 pixels tall, 2-pixel stems, notched corners, fitted one clear pixel apart. +// The R is the rune ᚱ (raidō), so the name is spelled with a real rune and still reads as RUNE. Plain data and string +// builders, so the site and the icon script draw the same pixels. + +export type Grid = readonly string[] +const grid = (s: string): Grid => s.trim().split("\n").map(row => row.trim()) + +const GLYPHS: Record<string, Grid> = { + // The stave, a pointed bowl and a straight leg, all on 45° steps two pixels thick. + ᚱ: grid(` +###.... +####... +##.##.. +##..##. +##..##. +##.##.. +####... +##.##.. +##..##. +##...## +##...##`), + U: grid(` +##...## +##...## +##...## +##...## +##...## +##...## +##...## +##...## +##...## +####### +.#####.`), + N: grid(` +###...## +####..## +####..## +####..## +##.##.## +##.##.## +##.##.## +##..#### +##..#### +##..#### +##...###`), + E: grid(` +###### +###### +##.... +##.... +#####. +#####. +##.... +##.... +##.... +###### +######`), +} + +export const CAP = 11 + +/** The ᚱ redrawn for 16 and 32 px favicons: 3-pixel stems, one or two device pixels per cell. */ +export const ICON16: Grid = grid(` +................ +...####......... +...#####........ +...######....... +...###.###...... +...###..###..... +...###..###..... +...###.###...... +...######....... +...#####........ +...######....... +...###.###...... +...###..###..... +...###...###.... +...###....###... +................`) + +/** A pixel rectangle: x, y, width, height. */ +export type Rect = readonly [number, number, number, number] +export interface Glyph { char: string; x: number; rows: Grid } + +const ink = (rows: Grid) => rows.flatMap((row, y) => [...row].flatMap((c, x) => (c === "#" ? [[x, y] as const] : []))) + +/** Where `next` starts after `prev` (placed at `at`): as far left as keeps one clear pixel between their ink in every + * direction, diagonals included. */ +function fit(prev: Grid, at: number, next: Grid) { + const a = ink(prev).map(([x, y]) => [x + at, y] as const), b = ink(next) + let x = at + 1 + while (a.some(([ax, ay]) => b.some(([bx, by]) => Math.abs(bx + x - ax) <= 1 && Math.abs(by - ay) <= 1))) x++ + return x +} + +export const WORDMARK = (() => { + const glyphs: Glyph[] = [] + for (const char of "ᚱUNE") { + const rows = GLYPHS[char]! + const last = glyphs[glyphs.length - 1] + glyphs.push({ char, x: last ? fit(last.rows, last.x, rows) : 0, rows }) + } + const last = glyphs[glyphs.length - 1]! + return { glyphs, width: last.x + last.rows[0]!.length, height: CAP } +})() + +/** Rows to rectangles, merging each row's runs so no seams show between pixels. */ +export function runs(rows: Grid, dx = 0, dy = 0): Rect[] { + const out: Rect[] = [] + rows.forEach((row, y) => { + for (let x = 0; x < row.length; x++) { + if (row[x] !== "#") continue + let end = x + while (row[end] === "#") end++ + out.push([dx + x, dy + y, end - x, 1]) + x = end + } + }) + return out +} + +/** ᚱ's carve order: the stave top to bottom, then the bowl out and back, then the leg. Each cell gets the arc length + * (0–1) of its nearest point on that path. */ +export function carveOrder(rows: Grid): [number, number, number][] { + const path = [[[1, .5], [1, 10.5]], [[1.5, .5], [5, 3.5]], [[5, 3.5], [1.5, 6.5]], [[2.5, 6.5], [6, 10.5]]] as const + const lens = path.map(([a, b]) => Math.hypot(b[0] - a[0], b[1] - a[1])) + const total = lens.reduce((s, l) => s + l, 0) + return ink(rows).map(([x, y]) => { + const c = [x + .5, y + .5] as const + let best = Infinity, arc = 0, acc = 0 + path.forEach(([a, b], i) => { + const dx = b[0] - a[0], dy = b[1] - a[1] + const p = Math.max(0, Math.min(1, ((c[0] - a[0]) * dx + (c[1] - a[1]) * dy) / (dx * dx + dy * dy))) + const d = Math.hypot(a[0] + dx * p - c[0], a[1] + dy * p - c[1]) + if (d < best - 1e-6) { best = d; arc = acc + p * lens[i]! } + acc += lens[i]! + }) + return [x, y, arc / total] + }) +} + +/** OKLCH to gamma-encoded sRGB, 0–1 per channel. */ +export function oklch(l: number, c: number, hDeg: number): [number, number, number] { + const h = (hDeg * Math.PI) / 180, a = c * Math.cos(h), b = c * Math.sin(h) + const l_ = (l + .3963377774 * a + .2158037573 * b) ** 3 + const m_ = (l - .1055613458 * a - .0638541728 * b) ** 3 + const s_ = (l - .0894841775 * a - 1.291485548 * b) ** 3 + const lin = [ + 4.0767416621 * l_ - 3.3077115913 * m_ + .2309699292 * s_, + -1.2684380046 * l_ + 2.6097574011 * m_ - .3413193965 * s_, + -.0041960863 * l_ - .7034186147 * m_ + 1.707614701 * s_, + ] + const gamma = (x: number) => { x = Math.min(1, Math.max(0, x)); return x <= .0031308 ? 12.92 * x : 1.055 * x ** (1 / 2.4) - .055 } + return [gamma(lin[0]!), gamma(lin[1]!), gamma(lin[2]!)] +} + +/** Rune's ink, `--ink` in site.css, and the light the carve runs. */ +export const INK: [number, number, number] = [.74, .14, 245] +export const HOT: [number, number, number] = [.97, .035, 245] diff --git a/app/vendor/rune/site/src/content.tsx b/app/vendor/rune/site/src/content.tsx new file mode 100644 index 0000000..1a29ef2 --- /dev/null +++ b/app/vendor/rune/site/src/content.tsx @@ -0,0 +1,584 @@ +import type { ReactNode } from "react" + +export type Spec = { label: string; values: ReactNode[]; mono?: boolean } +/** A file or folder in this repo that implements an idea. The prerender fails if the path doesn't exist. */ +export type CodeRef = { path: string; note?: string } +export type Entry = { slug: string; title: string; body: ReactNode; spec?: Spec[]; code?: CodeRef[] } + +const at = (path: string, note?: string): CodeRef => ({ path, note }) + +export const principles: Entry[] = [ + { + slug: "feel-first", + title: "Feel is the product", + body: ( + <> + <p> + Rune is judged first on how it feels in the hand: 120&nbsp;Hz, springs that can be interrupted at any point, and + nothing that pops, jumps or is cut off by a hard edge. The bar is SwiftUI on a ProMotion iPhone. + </p> + </> + ), + spec: [ + { label: "Frame", values: ["8.33 ms at 120 Hz"], mono: true }, + { label: "Target", values: ["event → frame p50 ≤ 8.3 ms"], mono: true }, + ], + code: [ + at("crates/rune-motion/src/spring.rs", "closed-form springs"), + at("examples/settings/src/main.rs", "the smoke test"), + ], + }, + { + slug: "motion-defaults", + title: "Motion rules are runtime defaults", + body: ( + <> + <p> + Kit's motion rules are what the framework does when the app says nothing. Nothing animates on first mount, + drags apply 1:1, removed elements play their exit before they unmount, stationary edges never move, and + reduced motion swaps travel for a short fade. + </p> + <p> + Animated properties change only through spring tracks, so a one-frame jump can't be written. In tests, the + motion-lint rules (pops, jumps, reversals, jitter, hard clips) are failures. + </p> + </> + ), + spec: [ + { label: "Spring", values: [<code>Spring::new(duration, bounce)</code>], mono: true }, + { label: "Default", values: ["bounce 0"], mono: true }, + ], + code: [ + at("crates/rune-motion/src/tokens.rs", "the motion palette"), + at("crates/rune-motion/src/transition.rs", "exits before unmount"), + ], + }, + { + slug: "animation-off-app", + title: "Animation never runs through app code", + body: ( + <p> + Views state targets and the render thread animates toward them. While a value animates, the app side does no + work: no view re-run, no layout, no diff. A slow handler can delay the next change but can't stall one that's + already moving. + </p> + ), + spec: [{ label: "Target", values: ["app work per animated frame: 0"], mono: true }], + code: [ + at("crates/rune-motion/src/scene.rs", "spring tracks"), + at("crates/rune/tests/integration/live.rs", "no view, layout or shaping"), + ], + }, + { + slug: "native-behaviour", + title: "Native behaviour, one look", + body: ( + <> + <p> + Text input, accessibility, scroll momentum, clipboard and window management behave the way each platform + expects. Controls, type, motion and materials come from the app's theme and look the same everywhere, Mac + included. + </p> + <p>The core ships no brand of its own. OpenCode's theme is the first theme built on it and the main example.</p> + </> + ), + spec: [ + { label: "Native", values: ["IME, accessibility, scrolling, clipboard, windows"] }, + { label: "Themed", values: ["controls, type, motion, materials"] }, + ], + code: [ + at("crates/rune-edit/src/lib.rs", "text input and IME"), + at("crates/rune/src/a11y/tree.rs", "the accessibility tree (AccessKit)"), + at("crates/rune-core/src/theme.rs", "themes as data"), + at("themes/opencode", "OpenCode's theme"), + ], + }, + { + slug: "agents", + title: "Written and checked by agents", + body: ( + <> + <p> + Agents write most of Rune and most Rune apps, so they need to see and test their own work without a person. + Every component has named scenes, every scene renders headless and deterministically, and an inspector + answers queries about nodes, rects, springs and timings. + </p> + <p> + The code is optimised for performance, correctness and speed of change rather than for a human reading it. + Comments state invariants for the next agent. + </p> + </> + ), + spec: [{ label: "Render", values: [<code>--snap out.png --at 0.25</code>], mono: true }], + code: [ + at("crates/rune/src/tooling.rs", "--snap, --scene, --script, --trace"), + ], + }, + { + slug: "one-way", + title: "One way to do things", + body: ( + <p> + Views are plain Rust functions that return a keyed tree. There is no view macro language, no second way to + hold state and no notify call to forget. Errors should name the fix, such as{" "} + <code>Text has no key inside a dynamic list; add .key(id)</code>. + </p> + ), + code: [at("crates/rune/src/el.rs", "the whole view API")], + }, + { + slug: "fast-and-reference", + title: "A fast path and a reference path", + body: ( + <p> + Layout, text, the renderer and springs each have a slow, obviously correct reference implementation and a fast + one. Every change tests the fast path against the reference on generated inputs, so the fast path can be + specialised, duplicated or unsafe where a measurement justifies it. + </p> + ), + spec: [{ label: "Reference", values: ["CPU renderer, no GPU tricks"] }], + code: [ + at("crates/rune-ref/src/shader.rs", "the CPU renderer"), + at("crates/rune-ref/tests/differential.rs", "GPU against CPU"), + ], + }, + { + slug: "observable", + title: "Everything is observable", + body: ( + <p> + Every frame, node, layout rect, spring and timing can be queried, traced and replayed. A pixel traces back to + the node and the <code>file:line</code> that drew it, and a recorded session replays to the same pixels. The + agent's view of the app is the accessibility tree, so every agent test exercises accessibility too. + </p> + ), + code: [ + at("crates/rune-motion/src/trace.rs", "motion traces"), + at("crates/rune/src/tooling.rs", "--tree, --trace"), + ], + }, + { + slug: "hot-reload", + title: "Edits reach the screen with state intact", + body: ( + <> + <p> + Tokens and literal edits apply live with no rebuild. Structural Rust edits hot-patch on the Mac in + about a second today, keeping app state, and the goal is 300&nbsp;ms. + </p> + <p> + A phone can't load new code, so in development the render thread runs on the iPhone and the app side runs on + the Mac, connected by the same channel the two threads use in production. + </p> + </> + ), + spec: [ + { + label: "Targets", + values: ["tokens ≤ 50 ms", "literals ≤ 100 ms", "Rust ≈ 1 s, goal 300 ms"], + mono: true, + }, + ], + code: [at("spikes/hot-patch", "989 ms median")], + }, + { + slug: "budgets", + title: "Performance budgets are gates", + body: ( + <p> + Each scene's cost is counted exactly: instructions, instances, glyphs, layout nodes and allocations. Counts are + bisectable, so CI can fail the change that pushed a scene over its frame budget. Once settled, an app does no + work at all. + </p> + ), + spec: [ + { label: "At rest", values: ["0 ticks, 0 GPU submissions"], mono: true }, + { label: "Per frame", values: ["0 allocations"], mono: true }, + ], + code: [at("crates/rune/tests/alloc.rs", "0 allocations a frame"), at("crates/rune-motion/tests/alloc.rs")], + }, + { + slug: "owned", + title: "Owned, not wrapped", + body: ( + <p> + Rune depends on foundational crates and never on another UI framework. It borrows the best parts of Zed's GPUI + (the rope, the line layout cache, the macOS and iOS text input code) under GPUI's Apache-2.0 licence instead of + forking it. + </p> + ), + spec: [{ label: "Uses", values: ["wgpu, Taffy, Parley, AccessKit"] }], + code: [at("crates/rune/Cargo.toml", "dependencies")], + }, +] + +export const layers: Entry[] = [ + { + slug: "tree", + title: "Core tree and state", + body: ( + <> + <p> + A view is a plain Rust function that returns an <code>El</code> tree with explicit keys. App state lives in + typed models outside any view. Handlers are queued and run between frames with <code>&mut</code> access to + the state, then the view re-runs and the new tree is diffed against the old one by key. + </p> + <p> + The toggle below, from the settings example, states where the knob should be and animates nothing itself. + The <code>.motion(motion::SNAPPY)</code> token tells the render thread how to get there. + </p> + </> + ), + spec: [ + { label: "Uses", values: ["keyed retained tree, typed models"] }, + { label: "Not", values: ["signals, GPUI entities, immediate mode"] }, + ], + code: [at("crates/rune/src/el.rs", "El, keys, handlers"), at("crates/rune/src/runtime.rs", "queue, view, diff")], + }, + { + slug: "layout", + title: "Layout", + body: ( + <p> + Taffy computes flexbox, grid and block layout over Rune's own node arena, so there is one tree. Layout runs once, + at the target state; moving between layouts is the render thread's job. Long lists build only the visible rows + plus overscan and keep the rest as estimated heights. + </p> + ), + spec: [ + { label: "Uses", values: ["Taffy"] }, + { label: "Not", values: ["own engine, SwiftUI-style proposals"] }, + ], + code: [ + at("crates/rune/src/runtime.rs", "Taffy on the node arena"), + at("crates/rune/src/el/virtual_list.rs", "visible rows only"), + ], + }, + { + slug: "text", + title: "Text", + body: ( + <p> + Parley handles shaping, bidi and line breaking, with shaped runs cached apart from wrap points so resizing never + re-shapes. Glyphs rasterise into a greyscale atlas with four horizontal subpixel positions, and coverage is + adjusted by luminance so dark text isn't thin. Text that overflows fades out rather than ending in an ellipsis. + </p> + ), + spec: [ + { label: "Uses", values: ["Parley, swash, skrifa"] }, + { label: "Not", values: ["CoreText only, cosmic-text"] }, + ], + code: [ + at("crates/rune-text/src/lib.rs", "Parley, swash, the atlas"), + at("research/23-text-quality.md", "against CoreText"), + ], + }, + { + slug: "render-thread", + title: "Render thread and spring tracks", + body: ( + <> + <p> + The render thread owns the presented tree, which is what's on screen this frame. Every animated property is a + track of analytic spring segments, so position and velocity are exact at any time and a retarget starts the + new spring from where the value really is. + </p> + <p> + Layout animates per edge, so an edge that isn't moving gets no track. Removed nodes leave the flow, play their + exit and unmount at opacity 0. Drags and scrolling are applied here, 1:1, and one clock with time scale and + stepping is shared by tests, traces and the inspector. + </p> + </> + ), + spec: [ + { label: "Spring", values: ["ω = 2π / duration", "ζ = 1 − bounce"], mono: true }, + { label: "Snap", values: ["both edges to 1/64 px"], mono: true }, + ], + code: [ + at("crates/rune-motion/src/spring.rs"), + at("crates/rune-motion/src/scene.rs", "today on the main thread"), + at("crates/rune-motion/src/transition.rs", "presence"), + ], + }, + { + slug: "renderer", + title: "Renderer", + body: ( + <> + <p> + One instanced pipeline draws rounded rects, borders, analytic shadows, glyphs and vector strokes and fills, so + a typical frame is one draw call. Every instance carries a clip with soft gradient edges, which makes "no + hard edges" free. Blending is in linear light. + </p> + <p> + Big or scaling text and icons will draw from curves with Slug, complex vectors with Vello's sparse strips, and + in-app blur with a backdrop pass. + </p> + </> + ), + spec: [ + { label: "Uses", values: ["wgpu on every platform"] }, + { label: "Not", values: ["Skia, compute Vello, raw Metal first"] }, + ], + code: [ + at("crates/rune/src/render.rs"), + at("crates/rune/src/shaders/shader.wgsl", "one uber-quad pipeline"), + at("crates/rune-core/src/shape.rs", "strokes and fills"), + ], + }, + { + slug: "shells", + title: "Platform shells", + body: ( + <p> + A shell owns windows and panels, menus, clipboard, drag and drop, the text input protocol, the accessibility + adapter and the app lifecycle. Rune runs on winit today. Once text input lands it moves to thin shells per + platform, implementing each one's text protocol directly (<code>NSTextInputClient</code>, TSF,{" "} + <code>text-input-v3</code>, <code>UITextInput</code>) and borrowing from Zed's shells. + </p> + ), + spec: [ + { label: "Uses", values: ["winit, then own shells; AccessKit"] }, + { label: "Not", values: ["winit's IME, SDL3"] }, + ], + code: [ + at("crates/rune/src/window.rs", "winit today"), + at("crates/rune/src/platform/macos.rs"), + at("crates/rune/src/platform/win32.rs", "overlays"), + at("crates/rune/src/platform/layer_shell.rs", "Wayland overlays"), + at("crates/rune/src/a11y/mod.rs", "UI Automation, NSAccessibility and AT-SPI adapters"), + ], + }, + { + slug: "native-layers", + title: "Native layers on Apple", + body: ( + <p> + Liquid Glass samples what's behind the window, so only the window server can draw it. For Mac surfaces that want + it, the Apple shell places system glass views behind transparent regions of Rune's layer and the render thread + updates their masks in the same transaction as the frame. This is optional; every platform gets Rune's own + blur and materials. + </p> + ), + spec: [{ label: "Uses", values: ["NSGlassEffectView, CATransaction"] }], + }, + { + slug: "tooling", + title: "Agent tooling", + body: ( + <p> + Scenes are named states with fixture data. They render in the app, offscreen in tests and in a gallery, with + pinned fonts and a fixed clock. The inspector speaks versioned JSON over a socket: query nodes by role, key or + text, read rects, springs and source locations, and inject input with exact timestamps. Motion traces come + straight from the render thread. + </p> + ), + code: [ + at("crates/rune/src/tooling.rs", "scenes and flags"), + at("crates/rune-motion/src/trace.rs", "motion traces"), + ], + }, + { + slug: "playground", + title: "Playground", + body: ( + <p> + A storybook built into the window, on ⌘⇧D. The app's scenes and its own stories, in a tree of groups nested by + their paths, show one at a time on a plain stage, live and interactive, with their triggers and controls beside + them. The keyboard is in one column at a time, the list, the stage or the controls, so a story's own keys work on + its stage. Each story has its own state, so the real one is never touched. R replays a story from the start, its + timed steps running on the logical clock, the same every time. + </p> + ), + code: [at("crates/rune/src/playground.rs", "stories, triggers and replay")], + }, +] + +export type Decision = { area: string; chose: string; rejected: string; why: string } + +export const decisions: Decision[] = [ + { + area: "Language", + chose: "Rust", + rejected: "Zig, C++, Swift", + why: "The only option with production text, layout and accessibility crates, no garbage collector, wasm, and a working hot-patcher.", + }, + { + area: "GPU", + chose: "wgpu everywhere", + rejected: "Raw Metal first, hand-written Vulkan and D3D12", + why: "One backend ships Mac, Windows, Linux and the web. Raw Metal comes later, only where a measurement asks for it.", + }, + { + area: "Renderer", + chose: "One instanced pass, glyph atlas", + rejected: "Skia, compute Vello", + why: "A typical frame is one draw call, and soft clip edges cost nothing extra.", + }, + { + area: "Look", + chose: "Token-driven themes", + rejected: "Per-OS look, a built-in brand", + why: "Apps carry their own design language on every platform. OpenCode's is one theme, kept outside the core.", + }, + { + area: "Text", + chose: "Parley, swash, skrifa", + rejected: "CoreText only, cosmic-text", + why: "The same text on every platform, and resizing never re-shapes.", + }, + { + area: "Layout", + chose: "Taffy on Rune's arena", + rejected: "An own engine, SwiftUI-style proposals", + why: "Agents already know flexbox, and there is one tree instead of two.", + }, + { + area: "State", + chose: "Keyed tree from plain functions", + rejected: "Signals, GPUI entities, immediate mode", + why: "Models outside views survive hot patches, and handlers never run inside render, so borrows can't collide.", + }, + { + area: "Animation", + chose: "Spring tracks on the render thread", + rejected: "Re-rendering views each frame", + why: "Animations keep running when the app is busy, and retargets keep velocity.", + }, + { + area: "Accessibility", + chose: "AccessKit", + rejected: "Own bridges", + why: "The same tree serves the inspector, so agent tests exercise it.", + }, + { + area: "Hot reload", + chose: "Live values, subsecond patches, split process on iPhone", + rejected: "A view language interpreter, loading code on the device", + why: "Views stay plain Rust, and iOS won't load new code on a device.", + }, +] + +export type Milestone = { id: string; title: string; status: "done" | "now" | "started" | "next" | "later"; body: ReactNode } + +export const milestones: Milestone[] = [ + { + id: "m0", + title: "Spikes", + status: "now", + body: ( + <p> + Short experiments that each answer one question with a number: hot-patch speed, glass underlay sync, frame + pacing, the iPhone split mode, and text quality against CoreText. Hot patching is done, at 989&nbsp;ms median from + save to new output. + </p> + ), + }, + { + id: "m0-5", + title: "Rendering smoke test", + status: "now", + body: ( + <p> + A small settings window that proves the basics: rounded rects, borders, shadows, soft edges, crisp text, Retina + scale, springs and clicks, checked by headless renders and then on a real window. + </p> + ), + }, + { + id: "m1", + title: "Theming, gallery and this site", + status: "now", + body: ( + <p> + The token schema and theme system, with OpenCode's theme generated from <code>@opencode/ui</code> as its first + consumer. A gallery of components with the same names as the web kit, each diffed against its web story. + </p> + ), + }, + { + id: "m2", + title: "Hex Settings", + status: "next", + body: ( + <p> + The first real screen, on Mac, Windows and Linux: forms, toggles, a keycap recorder, lists and a text field. Own + shells start here, along with AccessKit and goldens on all three platforms. + </p> + ), + }, + { + id: "m3", + title: "OpenCode Desktop", + status: "started", + body: ( + <p> + The main screens: sidebar and sessions, the streaming transcript, composer, diff view, command palette and + menus, against real data. Done when it looks like OpenCode Desktop side by side and feels clearly better on all + three desktops. + </p> + ), + }, + { + id: "m4", + title: "Kit's Mac surfaces", + status: "later", + body: <p>An app's pill, tray and launcher, and their settings windows, with optional Liquid Glass.</p>, + }, + { + id: "m5", + title: "Web", + status: "started", + body: ( + <p> + The same apps in the browser over WebGPU, starting with live demos on this site. An experimental target builds + and runs today (<code>WEB.md</code>, <code>examples/web-hello</code>). + </p> + ), + }, + { + id: "m6", + title: "iOS, then Android", + status: "later", + body: ( + <p> + An iOS shell with <code>UITextInput</code>, a view for embedding Rune in SwiftUI, and the split-process dev mode. + The first surface ships inside OpenCode iOS. Android follows. + </p> + ), + }, +] + +export const risks: Entry[] = [ + { + slug: "risk-text", + title: "Text input and text quality", + body: ( + <p> + Input methods on three desktops, then iOS selection, autocorrect and dictation, are where custom-rendered + frameworks most visibly fail. Rune implements each platform's protocol directly and gates text rendering on a + pixel diff against CoreText. + </p> + ), + }, + { + slug: "risk-look", + title: "Matching OpenCode Desktop", + body: ( + <p> + The bar is a Chromium-rendered app. Each component is diffed against its <code>@opencode/ui</code> story, + rendered by headless Chromium beside Rune's headless renderer. + </p> + ), + }, + { + slug: "risk-scope", + title: "Scope", + body: ( + <p> + A renderer, text, input methods, accessibility, six shells and tooling is years of work for a human team. Agents + write it inside a verification harness that was built first, and Rune ships one real surface at a time. + </p> + ), + }, +] diff --git a/app/vendor/rune/site/src/entry-server.tsx b/app/vendor/rune/site/src/entry-server.tsx new file mode 100644 index 0000000..a1a8840 --- /dev/null +++ b/app/vendor/rune/site/src/entry-server.tsx @@ -0,0 +1,13 @@ +import { StrictMode } from "react" +import { renderToString } from "react-dom/server" +import { App } from "./App" + +export { routes } from "./routes" + +export function render(pathname: string): string { + return renderToString( + <StrictMode> + <App pathname={pathname} /> + </StrictMode>, + ) +} diff --git a/app/vendor/rune/site/src/footer-signature.svg b/app/vendor/rune/site/src/footer-signature.svg new file mode 100644 index 0000000..83b0bb2 --- /dev/null +++ b/app/vendor/rune/site/src/footer-signature.svg @@ -0,0 +1,14 @@ +<svg preserveAspectRatio="none" overflow="visible" style="display: block;" width="163.057" height="64.1453" viewBox="0 0 163.057 64.1453" fill="none" xmlns="http://www.w3.org/2000/svg"> +<g id="Vector"> +<path d="M73.5238 4.95025L72.6833 6.74631C72.5771 6.97635 72.3603 7.2639 72.1745 7.45413L70.2811 11.3825C70.144 10.7631 70.6262 10.3296 70.8429 9.82528C71.1438 9.13075 71.4402 8.48929 71.595 7.79476L70.1617 10.9136C70.0201 11.2232 69.9582 11.4798 69.7281 11.7541L69.9361 10.8737L69.8918 10.803L69.3477 11.9974C69.1044 12.2141 68.9407 12.4044 68.8832 12.7406C68.8257 13.0856 68.5779 13.2891 68.4452 13.5988L67.6932 15.3506L67.8878 15.3595C67.9409 15.3595 67.9276 15.5364 67.9188 15.5895C67.9055 15.6382 67.7817 15.6028 67.6224 15.5586L67.1712 16.6247L67.0296 16.8238C67.0031 16.8636 66.9279 16.7397 66.8659 16.6468L66.3616 17.6422L66.6094 17.7395L65.6317 20.062C65.5211 20.323 64.9549 21.0972 64.7337 21.0972L65.322 19.5311L65.6538 19.3896L65.499 18.841L60.8363 29.9138C60.7168 28.5424 60.8097 27.2507 60.8363 25.897L60.9203 21.5218C60.6859 21.3847 60.6151 21.2166 60.6195 20.8317L60.4647 20.8406C60.3364 21.6059 60.6416 22.212 60.2346 22.8932L60.3275 18.987L60.8053 18.0359C61.0442 17.5625 60.7301 17.1511 60.3231 16.9476L60.3762 16.4699C60.3895 16.3548 60.1373 16.2487 59.9161 16.1779L59.7303 15.0542C59.664 14.9481 59.2703 14.8419 59.1287 14.8773C58.7792 15.125 58.4165 15.302 58.0316 15.4568L57.6733 15.6028C57.598 15.6338 57.514 15.5187 57.3415 15.3506L56.439 16.6026L57.0008 16.3946L55.8551 17.9607L56.2753 16.9388L54.7491 18.872L54.2227 19.5179V19.832L51.9931 23.6409L49.967 27.2241L47.5604 27.609L45.1804 27.9408L45.698 26.5031C45.7776 26.2819 45.9059 25.9368 45.9369 25.7377L46.0652 24.9636C46.0961 24.7645 46.4146 24.5876 46.5872 24.5256C47.0915 24.3531 46.6049 23.9019 46.5783 23.6763C46.4854 22.8888 46.742 22.0969 46.8924 21.4024L46.9499 21.3316L48.7195 15.647L49.1264 14.8021L50.7013 9.47581L51.6878 5.75981L51.7453 4.7556C51.763 4.43708 51.1393 3.80891 51.0773 2.6189C50.9535 2.59678 50.8473 2.59235 50.834 2.53042L50.7765 2.20306L50.1882 2.37559C49.7767 1.88454 48.8212 1.89782 48.3832 1.11922L48.3921 0.836107C48.3921 0.787445 48.255 0.756471 48.2328 0.800709L48.0913 1.07498L47.6577 0.694542L46.6845 0.787438L46.1935 1.15019L46.3969 0.345057L45.9236 0.822836L45.9457 0.243318L45.1185 1.22098L43.172 3.41518L39.7966 7.3745L39.9072 7.46297L41.6546 5.47668L42.9685 4.04337L43.1012 4.19378C42.6633 4.72021 42.0174 5.28203 41.6989 5.90136C41.5485 6.19776 41.4865 6.42781 41.2698 6.65785C40.761 7.20198 40.2877 7.7461 39.9293 8.33005C40.7743 7.68859 41.1149 6.75959 42.0085 6.23758L39.9161 8.79011C39.6374 9.12632 39.3808 9.34309 39.0578 9.62179C38.5624 10.0465 38.1554 10.6658 37.7395 11.2011L34.6694 15.1737L34.3111 14.979C34.3111 14.979 34.2846 14.9879 34.258 14.9525L34.665 14.7977L34.4925 14.5765L35.7975 12.8158L36.6336 11.7673L38.0536 9.91819L38.2394 10.1084C38.2394 10.1084 38.3545 9.96243 38.3589 9.97571C38.3589 9.98898 38.2571 9.82972 38.2041 9.75009L39.2835 8.1177C38.7438 8.63529 38.3102 9.17499 37.8634 9.76336L34.7933 13.8377L31.5728 18.0978C32.254 17.7483 32.5548 17.0803 32.9928 16.5185L34.143 15.041L34.2403 15.125C34.3996 15.7222 33.7537 16.5672 33.2007 16.7441L31.3737 19.3675L30.1748 21.0927L30.9888 20.4248L29.843 21.9864L29.1529 22.7871L29.0821 22.7207C29.0821 22.7207 29.0644 22.5438 29.0556 22.5084C29.0512 22.473 29.0202 22.473 28.9937 22.4951C28.9627 22.5172 28.8256 22.6322 28.799 22.6676L27.264 24.7026L27.379 24.8176L28.9671 22.7384L29.0998 22.8578L27.0959 25.6006L24.9813 28.5248L22.6367 31.8426C22.7296 31.0906 23.2737 30.6438 23.6586 30.1173L24.3089 29.0733C24.5743 28.6442 24.9105 28.3168 25.0476 27.7904L24.0257 29.1308L22.7119 30.949L21.1768 33.2051L20.9777 32.9839C20.9468 32.9486 20.8494 33.2671 20.8008 33.2803L18.6066 33.8333C18.3146 33.9041 18.2615 33.8997 18.0359 33.9793C16.9078 34.3686 15.7488 34.6031 14.5897 34.9216L13.267 35.2843L4.55653 37.8015L4.49902 37.8236L2.65429 38.3677C2.84894 38.642 2.91529 38.7349 2.82239 38.6066L2.42425 38.7305C2.38443 38.7438 2.48176 38.8455 2.51273 38.872L2.6764 39.018C3.75139 38.7349 4.81311 38.3854 5.8704 38.0315L4.99006 38.2881C4.29995 38.4872 3.64964 38.5889 2.9728 38.5049C3.52135 38.2262 4.0124 38.1244 4.56538 37.9829L4.64943 37.9254L6.60033 37.4653L10.6702 36.4743L10.7631 36.6071L8.29465 37.3237C8.56893 37.4255 8.63086 37.8944 8.27253 38.0006C6.11371 38.642 4.01682 39.4914 1.80491 39.9515C1.78722 40.0576 1.76952 40.1373 1.73413 40.1461L1.34041 40.2611C1.21212 40.2965 0.955542 40.4292 0.862642 40.5044C0.769742 40.5796 0.80071 40.8628 0.82283 40.9778L0 41.4157C0.398143 41.659 0.641452 41.7298 0.929 41.6502L2.32692 41.2476L2.34462 41.4511L0.597214 42.0218L0.552977 42.1943L2.43752 41.6767L2.44637 41.8714L0.716656 42.4775L0.663572 42.5792L1.33157 42.4376L1.91993 43.0791L0.871488 43.5923L3.22496 42.8977L4.98121 42.3359C5.14047 42.4465 5.33069 42.5173 5.43244 42.4951L6.04735 42.3492L5.89252 42.6102C5.8704 42.6456 5.92349 42.6677 6.06505 42.7606L5.56958 43.1145C5.98984 43.0127 6.22873 42.9641 6.56494 42.9641C7.14446 42.7208 7.79476 42.5084 8.42294 42.3801L9.53332 42.1545C9.60852 41.7962 9.87395 41.6281 10.2632 41.544L10.6216 41.4644C10.6879 41.4511 10.6879 41.6192 10.7056 41.7077L12.0903 41.2919L11.7452 41.0663L13.1078 40.615L12.8777 41.0884L16.0407 40.1328H16.2664C16.3062 40.1373 16.315 40.1903 16.2796 40.208L16.0629 40.3098L10.3517 49.5732L7.30814 54.8155C7.27717 54.8641 7.14446 55.0234 7.17543 55.0721L7.38335 55.3684L6.74632 56.3903L6.7994 56.7796L5.56515 58.6775L5.35724 59.0092C5.36609 59.0446 5.37936 59.0756 5.38378 59.1198C5.4059 59.4737 5.18471 59.8144 4.94582 60.1019C5.14047 60.416 5.09623 60.8982 5.0166 61.2521C4.97679 61.4423 4.91928 61.6237 4.85735 61.8051C4.87946 61.8803 4.91043 61.9599 4.93697 62.0351C4.99891 61.9378 5.05642 61.8449 5.11835 61.7476C5.22452 61.5795 5.42802 61.5264 5.60497 61.6193C5.77308 61.7078 5.83059 61.9467 5.73326 62.1059C5.60055 62.3183 5.47225 62.5306 5.32627 62.7385C5.30415 62.7695 5.28203 62.8004 5.25991 62.8314C5.31742 62.9332 5.39263 63.0305 5.52977 63.1765L6.39683 62.0042L6.56936 62.0794C6.16237 62.7385 5.71556 63.3623 5.44129 64.1453L7.25505 61.4866L8.46718 59.748L8.6574 59.9029L7.30371 62.2652C7.71513 62.159 7.79476 61.8892 7.90535 61.5972C8.09558 61.1061 8.41852 60.6151 8.71491 60.1639L8.90956 60.3098C9.11748 59.9559 9.25462 59.8011 9.54659 59.5888L9.81644 58.6553C9.87838 58.443 10.0642 58.3059 10.2588 58.1776C10.2721 58.1289 10.2854 58.0802 10.3031 58.036C10.4092 57.7131 10.5641 57.3193 10.7897 57.0008L10.7145 57.0097L11.2409 56.2974L13.4794 52.7761C12.8202 52.9796 12.9529 53.7095 12.2849 54.0103C12.5371 53.4574 12.8998 52.9088 13.2847 52.4045L15.7355 49.1574L16.6734 48.0603C16.346 48.7814 15.8638 49.3255 15.4126 49.936L14.5897 51.0597L15.1294 50.8606L14.7578 51.533L14.6782 51.679C14.6517 51.7276 14.7755 51.909 14.8109 51.8692L15.0144 51.6392L16.2531 49.7989L18.434 46.7155L21.8094 41.9289L23.4728 39.6639C24.6406 40.009 24.7866 38.9384 26.0209 39.0578C26.2465 38.872 26.6225 38.5226 26.9056 38.4075L29.5555 37.3414C30.3783 37.0096 31.3339 36.7796 32.2186 36.9654C32.546 37.0317 33.2096 37.3945 33.245 37.7263L33.705 41.6502L34.0147 44.7425L34.2978 44.3178L34.7048 48.2903C34.665 48.3479 34.6385 48.4098 34.6075 48.4673C34.6163 48.4983 34.6296 48.5248 34.634 48.5602V48.8522C34.6385 48.9362 34.6429 49.0203 34.634 49.1043C34.6296 49.1574 34.6119 49.2105 34.5898 49.2547C34.5898 49.2857 34.5898 49.3122 34.5898 49.3432C34.6163 49.3786 34.5898 49.299 34.5898 49.3432C34.6296 49.3919 34.5765 49.3432 34.634 49.3919C34.7225 49.4715 34.7623 49.6219 34.7269 49.7369C34.7269 49.7502 34.7225 49.7502 34.7181 49.7546C34.7181 49.7635 34.7181 49.7723 34.7181 49.7812C34.7269 49.821 34.7358 49.8608 34.7491 49.9006C34.7535 49.9139 34.7756 49.9537 34.7756 49.9537C34.7889 49.9802 34.8066 50.0068 34.8198 50.0333C34.8641 50.1041 34.8552 50.0908 34.8995 50.1395C34.9968 50.2457 35.0543 50.3032 35.1516 50.3607C35.1649 50.3695 35.1782 50.374 35.1914 50.3828C35.2843 50.3917 35.3728 50.4138 35.4613 50.4403C36.1558 50.5332 36.6115 50.3518 37.1202 50.4049C37.629 50.0643 38.1333 49.7281 38.527 49.2415C38.5358 49.2326 38.5403 49.2282 38.5491 49.2238C38.5137 49.1265 38.5137 49.0114 38.5712 48.9185C38.6995 48.715 38.757 48.4894 38.8942 48.2992C38.8942 48.2771 38.8897 48.255 38.8853 48.2328L38.8101 48.3479L38.6509 47.4941L39.6683 43.9594L40.0399 44.1187L40.27 42.911C40.0974 43.2605 40.0886 43.5524 39.7612 43.7206C40.208 41.7166 40.7389 39.8674 41.3494 37.9696L41.575 37.2618L42.1899 35.4303C42.4199 36.293 41.8006 36.9344 41.7121 37.7219C41.6237 38.5049 41.2034 38.4916 41.4202 38.8632L41.2255 39.1109C41.1769 39.1729 41.2698 39.3941 41.2521 39.4693L40.8406 41.2521C40.7654 41.5706 40.354 42.1545 40.646 43.1145L40.9911 41.5706C41.0795 41.1724 41.2609 40.7168 41.4379 40.3496C41.4069 40.2832 41.3317 40.1594 41.345 40.0974L41.4069 39.8187C41.46 39.5754 41.6281 39.3454 41.7873 39.2038L42.6898 36.1912L42.9641 35.333L43.7825 32.3646L45.8971 31.7497C46.4412 31.5905 46.7332 31.0729 47.0782 30.7234C47.3658 30.4314 47.4896 30.2722 47.7064 29.9005C47.901 29.5688 48.4496 29.2281 48.9849 29.0158L46.3837 34.028L45.4768 36.0629L45.1937 37.014L44.6894 38.0625L44.0568 39.3321C43.9152 39.6152 43.8798 39.8409 44.0302 40.1151L46.2554 35.8506C46.1536 36.6026 44.4726 39.3764 44.8973 39.0888L45.2202 38.872L44.8752 39.571L44.2072 41.1769C44.9194 40.1505 45.3662 39.0578 45.928 37.9873L46.0077 38.3279L47.1092 36.1868L47.2375 36.2841L46.5474 37.6865L44.4284 42.1678L44.3222 42.4288C44.2956 42.4996 44.4328 42.619 44.5168 42.7208L43.8842 44.2647C43.9329 44.3841 44.0125 44.5213 43.9948 44.6097L43.8886 45.1716L44.7159 44.1673L44.6319 45.2379L45.8396 43.0968L46.4235 41.8935C46.5252 41.7475 46.7066 41.4909 46.8084 41.2963L47.8966 39.2481L49.1309 37.2574C49.4051 36.815 49.56 36.1779 49.9581 35.8329C50.2855 35.5498 50.3563 35.2003 50.5553 34.8375L51.8958 32.3867L52.3116 31.6922L53.5856 29.3785L57.1734 23.4418L57.1026 26.304L57.0141 33.1919L57.0628 36.1027L57.1866 37.1025C57.3149 38.1642 56.6292 38.6686 57.4078 38.9738C57.368 39.018 57.3459 39.0623 57.3149 39.1065C57.4919 39.1773 57.5538 39.3808 57.4963 39.5533C57.7308 39.6993 57.952 39.863 58.151 40.0488L58.2572 40.0178C58.3412 39.9913 58.5934 39.8364 58.6465 39.9028L58.9473 40.2788C59.1552 40.3894 59.7701 40.4204 59.9869 40.2744C60.2435 40.093 60.4912 39.9338 60.7611 39.7966C60.7611 39.7878 60.7611 39.7789 60.7611 39.7701C60.7611 39.6595 60.8142 39.5577 60.9026 39.4914C60.938 39.4604 60.9778 39.4383 61.0221 39.4294C61.0575 39.4206 61.0929 39.4162 61.1327 39.4206C61.1858 39.4295 61.2388 39.4206 61.2919 39.4206C61.3229 39.4162 61.3494 39.4073 61.3804 39.4029C61.522 39.1154 61.6104 38.7084 61.7255 38.4297L63.9108 33.1875L62.4996 35.7842L64.0081 32.2496L64.1364 32.7406L66.7288 26.5385L67.2685 25.1096L66.9323 25.5652L66.8527 25.5033L67.441 24.1408L67.6711 24.3221L69.591 19.3011L69.33 19.2347L70.1174 17.3591C70.1794 17.2175 70.1882 17.0405 70.1749 16.7884C70.1086 16.6557 70.0643 16.6512 70.0068 16.7707L69.2592 18.5667C69.1707 18.7791 69.2592 19.164 68.8301 19.1861L69.9095 16.5141L70.2679 15.678C70.374 15.4347 70.4183 15.3197 70.4227 14.9879C70.4271 14.6738 70.7279 14.2403 70.8651 13.9173L71.7189 11.9266L73.192 8.38313L72.8823 8.46276C72.8513 8.4716 72.8823 8.35659 72.8867 8.31678L72.9487 8.06904C72.9575 8.02923 72.8381 8.02037 72.8204 8.05576L72.0153 9.58641L71.9047 9.51563L73.6609 4.95468C73.8069 4.97237 73.5061 4.93698 73.5017 4.93698L73.5238 4.95025ZM11.8779 40.8672L9.39175 41.6767C9.34309 41.69 9.12632 41.544 9.16171 41.5175C9.2148 41.4777 9.34309 41.3804 9.40502 41.3582L11.6479 40.7079L13.6386 40.1594C13.1122 40.6947 12.5282 40.6504 11.8779 40.8628V40.8672ZM42.2563 13.329L43.2472 12.2761L43.3357 12.3469L43.0702 12.7981C42.9198 13.1608 42.7385 13.3997 42.4996 13.6873L41.7564 14.5853L41.5396 14.8507C41.4821 14.9171 41.2565 14.8286 41.2122 14.7932L42.2563 13.329ZM37.5759 14.7048C37.828 14.3818 38.0404 14.05 38.4474 13.8642L35.9523 17.0582L35.7842 17.0184L37.5759 14.7048ZM35.2268 18.5137C35.2578 18.8499 35.0012 19.0091 34.7933 19.2569L33.2051 21.1281L33.0813 21.0175L35.2268 18.5137ZM28.7636 26.3615C29.4007 25.3352 30.104 24.3973 30.9092 23.4551C30.3385 24.5212 29.6528 25.4679 28.7636 26.3615ZM34.4128 44.3045C34.2226 43.6409 34.1386 43.026 34.1828 42.327C34.4925 42.9464 34.5411 43.6498 34.4128 44.3045ZM37.1645 39.3764L36.6424 36.9963C35.8417 36.4965 36.346 35.6913 35.0897 35.3905L38.3766 34.174L37.1645 39.3719V39.3764ZM38.3766 33.9307C38.3545 34.0501 38.0183 34.0855 37.8855 34.1253L34.3553 35.1162C34.1209 35.1826 33.8245 35.5188 33.5635 35.2268L36.0541 34.3598C36.1602 34.3244 36.3195 34.0324 36.3328 33.9572L38.4562 33.4263L38.3722 33.9351L38.3766 33.9307ZM42.7252 34.1872C42.6456 33.5767 42.8225 32.9839 43.1587 32.6123C43.0968 33.2671 42.9685 33.6741 42.7252 34.1872ZM43.3445 14.3066L42.7075 16.8149L42.0882 19.509L41.9068 20.2655C41.69 21.1724 41.4069 22.0439 41.2255 22.9596L40.6106 25.4767L39.686 29.0733L29.6042 31.2542L30.8871 29.4316L35.1516 23.5922C35.479 23.141 35.8019 22.6543 36.1912 22.296C36.4788 22.035 36.5717 21.8271 36.7973 21.5263L38.7703 18.9207L39.3941 18.0492L40.2832 17.6687C40.1726 17.1025 40.4469 16.9565 40.7035 16.6026L41.4555 15.5718L43.7958 12.5327L43.3357 14.3022L43.3445 14.3066ZM46.1935 19.9779C46.1581 20.6946 46.0652 21.3759 45.6051 22.0439C45.6847 21.3272 45.9103 20.6504 46.1935 19.9779ZM47.7506 16.1602L48.7371 13.3511C48.7725 14.3243 48.2992 15.1737 48.047 16.1027L47.3038 18.8101L47.3967 18.8808L47.9807 17.0892C47.8745 17.9651 47.6002 18.7835 47.3038 19.6019L47.1578 19.3232C47.2021 19.7125 47.2198 20.0045 47.1313 20.323L46.8615 21.283L46.8482 21.3449L46.711 20.8671L45.7865 24.0479L45.5653 23.9726L47.7551 16.1646L47.7506 16.1602ZM45.5343 24.2602C45.5564 24.185 45.7776 24.2071 45.7599 24.2602L45.4547 25.2688C45.3485 25.6183 45.3927 26.0651 44.9548 26.1845L45.5343 24.2602ZM44.3222 25.7333C44.3133 25.5166 44.6053 25.6095 44.5655 25.7864L44.0258 27.1888C43.9816 26.6446 44.1452 26.2907 44.3266 25.7333H44.3222ZM44.7469 27.8391C44.7336 27.8966 44.6319 28.0514 44.6053 28.0868C44.5788 28.1222 44.4461 28.0249 44.4593 27.985L44.5168 27.786C44.6584 27.2905 44.6628 26.7641 45.0919 26.3615L44.7469 27.8391ZM60.2169 30.9711L60.2081 26.4323L60.3187 26.3704L60.3275 30.9092L60.2169 30.9711Z" fill="#242424"/> +<path d="M115.616 12.6698C115.475 12.5238 115.24 12.3867 115.019 12.2628L115.236 11.2498C114.701 11.3648 114.002 11.3427 113.652 10.8737C113.219 10.2986 112.648 10.3561 111.94 10.6968C111.949 10.6614 112.02 10.4225 111.962 10.4225L111.608 10.4004L108.782 13.3953L106.508 16.1867C107.583 15.3152 108.264 14.1606 109.374 13.4395L106.154 17.0538L105.667 17.5935C105.632 17.6289 105.534 17.536 105.459 17.4564L103.026 20.6371L104.765 14.9967L105.375 13.4307L105.07 13.0414L105.486 11.3603L104.26 14.9392L103.579 16.9565L102.916 18.7614L102.739 18.6066C102.712 18.5844 102.774 18.4561 102.792 18.4163L103.345 16.9432L104.331 13.8952L104.721 12.6211L104.889 11.9178L105.127 10.9047L105.579 9.34309C105.738 8.79454 105.849 8.25483 105.995 7.72397C106.039 7.51163 106.105 7.31257 106.185 7.1135C106.269 6.88788 106.362 6.66226 106.481 6.44107C106.654 6.0562 106.813 5.6669 106.844 5.23779C106.879 4.71136 106.8 3.8266 107.22 3.39307C107.136 3.05244 107.158 2.68526 107.211 2.31809C107.083 2.06593 107.021 1.78722 107.083 1.51736C107.065 1.50852 107.043 1.49968 107.025 1.48641C106.968 1.44217 106.928 1.38908 106.893 1.32714C106.875 1.3183 106.857 1.30503 106.84 1.29176L106.565 1.2829L105.822 0.681271C105.738 0.614914 105.676 0.327362 105.574 0.331786L105.207 0.349485C104.698 0.110599 104.092 0.172529 103.747 0.650301L103.849 0.0619399L103.451 0.42911L103.42 0L102.54 1.34041L102.394 1.60585C102.376 1.63681 102.486 1.58816 102.522 1.58373H102.778L100.929 4.22032C100.85 3.63638 101.575 3.52578 101.429 2.95953L99.4252 5.95445L99.1067 6.12256C99.0447 6.15795 99.1067 6.34375 99.1332 6.4455L98.3237 7.64878L97.9786 8.2106L94.4882 14.2049L94.6342 14.3022L95.3243 13.1255L96.97 10.4402H97.315C97.6645 9.91819 97.9653 9.39619 98.3989 8.90957L96.5453 12.1434L94.5634 15.5895C93.8999 15.9257 93.776 16.7486 93.077 16.8636L91.396 19.9647L90.9094 20.9379L89.7238 23.3489L86.5475 30.02C84.2958 34.7446 82.2829 39.4693 80.4338 44.3885L80.8319 44.1585L79.8366 46.773L80.6461 46.1758L80.0799 47.6445C80.0843 47.7285 80.1153 48.0116 80.0799 48.1001L79.3499 49.9979L78.9695 50.7234L78.6819 51.6701L79.2526 51.7276C79.3544 51.7365 79.4694 51.5374 79.58 51.4136L79.4738 52.5903L80.2214 51.1924C80.332 50.9137 80.4426 50.3961 80.7169 50.3341L81.0487 49.3344L81.3583 49.4848C81.1637 49.8741 80.9204 50.2943 80.9602 50.8208L82.6589 46.7066C82.743 46.4987 83.035 46.2775 83.2075 46.1581L85.4681 41.2521C85.9149 40.2832 86.3794 39.4471 86.8572 38.5004L87.127 37.9652C87.0651 37.8944 86.9545 37.7926 86.9854 37.7484L87.1447 37.5095C87.2332 37.3724 87.4145 37.2175 87.5959 37.1512L92.0419 28.2505C92.0728 28.047 92.1657 27.9585 92.2542 27.7948L93.7583 25.0255L96.2179 20.5619L96.6603 19.7612C96.9434 19.2524 97.2044 18.7614 97.6468 18.2704C97.4168 19.0799 96.8727 19.7214 96.4745 20.4734L95.5367 22.2518L94.6254 24.1186L94.1033 25.1803L93.5769 26.0961C93.3646 26.4677 93.1832 26.8304 93.0593 27.1489C93.2274 27.0605 93.3292 26.9808 93.3602 27.0162L93.4973 27.1578C95.6119 23.2118 97.6734 19.3763 100.146 15.5497L98.2308 23.8001L97.2089 28.5203L97.6203 29.1441L97.5805 29.4759C97.6645 29.5776 97.7176 29.7015 97.7265 29.8563C97.7309 29.9492 97.7132 30.0421 97.6999 30.135C97.7043 30.1394 97.7132 30.1483 97.7176 30.1527C97.753 30.1881 97.7928 30.2191 97.8282 30.2545L98.6643 30.4845C98.6555 30.5862 98.6555 30.6791 98.6643 30.7588C98.7439 30.8074 98.8147 30.8605 98.8899 30.9092L99.4208 30.4403C99.9339 30.8428 100.646 30.3429 101.168 29.759C101.695 29.5113 102.093 29.1308 102.128 28.4894L105.362 23.7869L107.866 20.469C108.18 20.0532 108.467 19.6373 108.883 19.279L106.609 26.1492L104.535 33.4661C104.495 33.5989 104.375 33.8068 104.424 33.8997L104.61 34.2315L104.371 35.1649C104.371 35.1649 104.411 35.1693 104.424 35.1782L104.778 34.8773L104.65 35.3817C104.694 35.4569 104.729 35.5453 104.729 35.6427C104.729 35.8329 104.667 36.0187 104.597 36.1912C104.508 36.4168 104.406 36.638 104.309 36.8636C104.305 36.8725 104.3 36.8857 104.296 36.8946C104.287 36.9167 104.278 36.9388 104.269 36.961C104.26 36.9787 104.256 37.0008 104.247 37.0185C104.274 37.0317 104.3 37.045 104.327 37.0583C104.406 37.0981 104.389 37.0804 104.309 37.0716C104.539 37.0981 104.712 37.2795 104.65 37.5228C104.623 37.6378 104.597 37.7484 104.566 37.859C104.57 37.859 104.575 37.859 104.579 37.859C104.583 37.859 104.588 37.859 104.601 37.859C104.955 37.8723 105.061 38.3014 104.796 38.5049C104.844 38.5093 104.893 38.5226 104.937 38.5491L105.008 38.6066C105.052 38.6509 105.083 38.7039 105.101 38.7614C105.101 38.7924 105.11 38.8234 105.114 38.8544C105.114 38.8588 105.114 38.8632 105.114 38.8676C105.282 38.8765 105.49 38.6951 105.645 38.4739L105.773 37.9298L105.911 37.9121L105.928 38.872L106.999 35.6913L107.308 34.1563C107.317 34.1164 107.463 33.9572 107.477 33.9926L107.578 34.3376L107.724 32.9795C107.822 32.0594 108.459 31.1923 108.565 30.2456L108.706 29.0291C108.711 28.9804 108.804 28.8079 108.852 28.8035L109.056 28.7813L110.427 24.8618L111.98 20.208C112.068 19.9381 112.113 19.6904 112.378 19.54L111.201 23.1233L109.18 29.206C109.246 29.2857 109.335 29.3918 109.308 29.352L109.697 29.0158C109.817 28.914 109.414 28.3611 109.582 28.4186L109.843 28.5071L110.781 25.8439L111.055 25.0609L111.467 24.1231L111.21 24.039C111.148 24.0169 111.254 23.7249 111.321 23.7293L111.56 23.7426C111.56 23.7426 111.631 23.5745 111.653 23.5258C111.666 23.4949 111.622 23.5037 111.573 23.5037H111.423C111.431 23.3843 111.445 23.225 111.48 23.2427L111.754 23.3666L115.444 13.3953C115.528 13.1697 115.723 12.7937 115.594 12.661L115.616 12.6698ZM100.633 17.3369C100.615 16.607 100.845 15.4258 101.266 15.1693C101.133 15.9832 100.943 16.6247 100.633 17.3369ZM102.902 17.244C102.796 17.8811 102.632 18.4296 102.349 19.1109C102.252 18.5092 102.482 17.8501 102.902 17.244Z" fill="#242424"/> +<path d="M137.771 44.2249L136.767 45.6405C136.718 45.5786 136.607 45.3927 136.563 45.4237L136.302 45.6051L136.072 45.7909C136.032 45.8219 135.997 45.7909 135.802 45.6803L136.621 44.1187L135.979 44.7292L136.116 44.3974C136.152 44.3178 135.975 44.0966 136.001 44.0081L136.315 42.88L136.001 43.0393C135.696 42.4952 135.961 41.8449 136.351 41.3273L136.13 41.3051C136.085 41.3051 136.015 41.2122 136.037 41.1724L136.691 40.0488L136.152 40.3363C138.377 36.4566 140.62 32.6743 143.172 29.0114L145.888 25.1096C145.955 25.0122 146.203 24.7822 146.114 24.7158C145.986 24.6141 145.782 24.5522 145.57 24.5345L144.415 22.4066L143.013 19.5798L142.504 19.686L142.495 18.5933L141.451 15.3993C141.274 14.8552 141.168 14.3332 141.248 13.82C141.434 13.8819 141.69 13.9925 141.704 13.9085L141.757 13.5148L141.766 12.9264C141.766 12.8069 142.084 12.7715 142.177 12.7317L142.323 12.2186C142.354 12.1124 142.708 12.0195 142.779 12.108L143.659 13.183L144.353 14.5986C144.451 14.7269 144.827 14.4039 144.871 14.1739L145.362 14.7932C145.535 15.0144 146.034 15.302 146.11 15.5762C146.061 16.1071 146.441 16.5053 146.614 16.9167L147.123 18.1376L148.6 21.5263L149.879 19.8054L155.086 13.7581L155.055 13.3865C155.041 13.2184 156.466 13.1122 156.187 11.9045L156.722 11.5506C156.882 11.5506 157.187 11.4842 157.302 11.3736L159.421 9.38733C159.624 9.40945 159.819 9.37848 159.912 9.31655L160.682 8.79897L160.527 9.16614C160.5 9.22808 160.496 9.36522 160.483 9.55987L162.239 8.00268C162.509 7.76379 162.721 7.6532 163.057 7.87881L160.85 10.6437L160.899 11.002L159.315 12.8689H159.713L157.846 15.1383L155.612 17.8235C155.302 18.1951 154.997 18.5535 154.873 19.0136L157.09 16.3858L156.669 17.3281L159.324 14.2314C159.178 15.0542 158.443 15.4258 158.111 16.0142C157.625 16.8813 157.041 17.5581 156.435 18.3102L153.878 21.4599L150.272 26.2111L150.48 26.2553L151.427 25.1582L153.36 22.4863C153.475 22.327 153.621 22.2916 153.913 22.3181L154.112 21.5794L155.139 20.2611L155.869 19.4515C156.315 19.2967 156.448 18.9649 156.731 18.5933L157.705 17.2971L157.846 17.3856L156.351 19.801C156.245 19.9735 155.842 20.1593 155.718 20.3097L154.462 21.8094L151.016 26.3261C150.879 26.5031 150.764 26.7773 150.622 26.8968L150.14 27.3126L150.379 26.8172C150.401 26.7729 150.264 26.6668 150.237 26.7021L150.109 26.8835L149.613 27.5957L147.764 30.0156L144.455 34.7491L143.46 36.2001L143.65 36.4345L142.124 38.5757L140.045 41.4157L139.045 42.6721L139.151 42.243C139.169 42.1634 139.04 42.0351 138.939 41.9466L137.656 43.6453C137.275 44.1497 136.935 44.6584 136.629 45.3131L137.638 44.2116L137.775 44.2249H137.771ZM148.052 28.6929L147.826 28.6707L146.716 30.1925L146.844 30.281L148.052 28.6973V28.6929Z" fill="#242424"/> +<path d="M87.2951 23.6364C86.1361 25.5962 84.8355 27.4498 83.1544 29.06L80.8629 31.2542C79.81 32.2629 78.6289 33.0636 77.3681 33.7979C77.2044 34.0324 76.8461 34.5102 76.5851 34.4836L76.0763 34.435C75.9657 34.4261 75.8419 34.665 75.7799 34.7977C75.3862 35.1472 74.7934 35.1737 74.3643 34.842C74.0015 35.1959 73.5857 35.187 73.2495 34.9349C71.8737 34.8464 71.0155 33.9749 70.4094 34.4527C70.2546 33.997 69.8033 33.7758 69.4273 33.9837L68.7947 32.8911C68.3391 32.1036 67.8701 31.1392 67.8569 30.1837C67.7994 26.3527 70.812 21.7696 73.3247 18.9118C73.5415 18.6685 73.7052 18.4738 73.8423 18.1907L74.7403 17.4033C74.7624 17.3856 74.6828 17.1423 74.6518 17.1379C74.6076 17.1379 74.8509 17.1511 74.8819 17.1511L75.2269 16.523C75.3066 16.377 75.2668 16.0275 75.2181 15.8417L75.5764 15.448L76.4877 14.8463L77.0894 14.9348C77.3459 14.6296 77.7176 14.4791 78.1201 14.6296L78.3811 14.342C78.7881 14.4747 79.2349 14.5234 79.7127 14.4482C82.0086 14.081 84.3223 14.3066 86.4546 15.2445C87.2111 15.5762 87.8215 16.1867 88.3657 16.7972C88.7815 17.2661 88.8302 17.9518 89.016 18.5048C89.1443 18.8808 89.1531 19.0313 89.0691 19.4117C88.7461 20.9202 88.1887 22.3358 87.3526 23.5922L87.2951 23.6409V23.6364ZM72.2984 32.2938C73.4884 31.9178 74.4395 31.4622 75.2712 30.6924L76.8416 29.2414L78.0095 28.2903C80.1285 26.3615 82.566 23.4418 83.8313 20.8893C84.5877 19.3675 85.384 17.5006 84.0524 16.523C82.7518 16.5539 81.584 16.8017 80.363 17.0228C80.2037 16.9786 79.9516 16.9034 79.8277 16.9742C79.7215 17.0361 79.5711 17.3768 79.6508 17.4697L80.0533 17.9253L78.766 19.2923L78.1555 19.9426L76.3506 22.1633C75.311 23.4418 74.413 24.7689 73.7229 26.2642L72.7806 28.3036C72.2055 29.5467 71.6348 31.1304 72.2895 32.3027L72.2984 32.2938ZM88.0073 20.9114C88.578 19.9204 88.7107 18.8056 88.348 17.7351C88.2905 18.4562 88.3745 19.2038 88.1976 19.8939C88.1047 20.2566 87.9454 20.5486 88.0073 20.9114ZM86.1892 24.2823L87.1889 22.6986C87.503 22.1987 87.7729 21.6944 87.9498 21.0308L86.5608 23.4108C86.3971 23.694 86.2599 23.9328 86.1892 24.2823ZM87.2907 23.4816L87.1358 23.3754C86.4988 24.1717 85.9326 24.8751 85.5256 25.7112L87.2111 23.5745L87.2907 23.486V23.4816ZM68.6089 30.5332L68.6355 29.3034C68.6443 28.9008 68.7062 28.6088 68.662 28.2549L68.3568 29.8696C68.3081 30.1218 68.4939 30.604 68.5558 30.865C68.7018 31.4843 68.7859 32.0505 69.2725 32.4089C68.6487 31.2366 68.9673 30.5066 68.6089 30.5287V30.5332Z" fill="#242424"/> +<path d="M130.33 18.8941C129.967 18.7791 129.587 18.872 129.202 18.9428L126.41 19.4382L127.286 16.0806L127.477 16.0983L127.052 18.2173L127.207 18.2659L127.384 17.4696C127.397 17.4121 127.468 17.2308 127.521 17.2396L127.773 17.2794C128.291 14.9702 128.658 12.6698 128.941 10.25L128.653 10.4933L128.835 9.76779L128.963 10.2102L129.175 9.51563C129.282 9.17499 128.914 8.82994 128.574 8.75916C128.689 8.56451 128.821 8.24157 128.746 8.10443L128.304 7.29929V7.09137C128.207 7.05598 128.114 7.0029 128.038 6.91885C128.025 6.90115 128.007 6.88788 127.994 6.87018C127.99 6.87018 127.981 6.86577 127.976 6.86577C127.923 6.84365 127.879 6.81709 127.835 6.77286C127.822 6.75516 127.808 6.7419 127.8 6.7242C127.786 6.73305 127.777 6.73748 127.764 6.7419C127.755 6.75075 127.742 6.75959 127.738 6.76401C127.72 6.78171 127.702 6.79497 127.685 6.81267C127.631 6.86133 127.569 6.90557 127.508 6.94096C127.366 7.02059 127.198 7.06484 127.034 7.04272C126.906 7.02502 126.804 6.96751 126.742 6.87461L126.565 6.93212C126.269 7.03387 126.158 7.18427 125.787 7.05156L125.212 7.46297C125.105 7.432 124.902 7.35239 124.898 7.43201C124.844 8.10886 124.097 8.91399 123.495 9.54217L123.017 9.96685C122.672 10.2721 122.5 10.6216 122.279 11.0286L122.097 11.3603C122.066 11.4134 122.199 11.4931 122.323 11.5373C123.19 10.1792 124.075 8.94052 125.331 7.91862C125.349 8.21944 125.136 8.34332 124.959 8.56451L122.717 11.3515L121.115 13.3909L121.367 12.4663C118.903 16.0009 116.616 19.5134 114.44 23.2516L113.201 23.6586C113.037 23.7116 113.192 24.1629 113.236 24.3221L113.449 25.0565L110.746 30.1616L111.082 30.0952L110.157 31.7895L110.648 31.9267L110.909 31.4931L110.998 31.6037L110.75 32.2054L111.272 31.909L109.733 35.3197C109.963 35.4657 110.131 35.3241 110.241 35.1516L110.441 34.842C110.48 34.78 110.675 34.842 110.768 34.8597L111.285 34.1209L111.268 34.7314L112.21 34.028L112.838 33.0769L113.241 33.298C113.316 32.9663 113.281 32.7849 113.17 32.5858L114.121 30.865C115.108 31.2012 114.227 30.1173 114.922 29.9625C115.24 29.8917 115.121 29.4714 115.209 29.3122L116.886 26.2686L122.765 23.8665L122.075 28.653C122.031 28.9539 122.473 29.3343 122.699 29.4139C122.69 29.582 122.663 29.7634 122.752 29.7988L123.11 29.9492C123.172 29.9758 123.314 30.1925 123.362 30.1439L123.557 29.9448L123.708 30.5199C123.743 30.6526 124.048 30.6836 124.163 30.6968L124.353 31.0154C124.389 31.0773 124.632 30.8694 124.645 30.7897L125.066 28.7282C125.088 28.6176 125.163 28.5159 125.136 28.4628L125.017 28.193C125.309 27.7948 125.406 27.2374 125.163 26.742L125.796 25.9855L125.964 25.4767L126.335 24.154L126.636 22.4509L127.941 21.951H127.087L128.392 21.3626C128.481 21.3228 128.698 21.2741 128.751 21.3493L129.021 21.7121L129.481 21.0131C129.804 20.5221 130.272 20.1151 130.733 19.6594L130.321 18.9074L130.33 18.8941ZM122.748 23.7116L120.819 24.3973L120.721 24.2248L122.717 23.4639C122.809 23.4285 122.805 23.6939 122.748 23.7116ZM123.367 20.3628L119.952 21.3847L122.703 17.2706L124.619 14.6517L123.367 20.3628Z" fill="#242424"/> +<path d="M142.208 25.9722L142.973 25.8174L143.646 26.3792L142.292 27.003L136.408 30.1748C136.373 30.2589 136.302 30.4889 136.231 30.4845L135.908 30.458L132.321 32.692C132.069 32.8512 131.865 32.9441 131.591 33.1034L130.211 33.9174L129.228 34.4173L128.459 34.4084L128.198 33.8156C128.158 33.7227 127.923 33.4927 127.831 33.5325L127.401 33.7183C127.092 33.5015 126.932 33.2759 126.902 32.9574L126.764 31.5329L126.335 31.5418L127.424 28.914L129.666 23.4551L129.958 22.734L130.856 20.9246L131.821 18.8764C131.914 18.6818 132.002 18.5933 132.122 18.3721L132.807 17.1246L132.595 16.8813C132.546 16.8238 132.834 16.7574 132.905 16.7043C133.329 16.3814 133.453 15.7355 133.741 15.3152L134.369 14.3995L135.232 12.8954L139.085 6.69323L139.823 5.75538C140.164 5.32185 140.536 4.96352 140.983 4.62289L140.921 5.52535L140.328 6.76844L140.469 6.75959L142.916 2.81355L143.04 2.95069L141.925 5.06084L140.434 8.20618L140.722 8.14424C141.062 8.07346 139.576 9.87838 139.43 10.7631C139.89 10.2411 140.239 9.58198 140.584 8.97149L141.571 7.22409L141.681 7.31256L140.522 9.52447L140.576 9.58198C140.766 9.27674 140.947 8.98477 141.226 8.6751L140.142 10.7587C139.859 11.3073 139.567 11.7895 139.416 12.4088L140.058 11.3205L140.284 11.5771C140.337 11.6346 140.155 11.7895 140.111 11.8735L138.355 15.3639L135.307 21.4865C135.059 21.9819 134.829 22.5659 134.763 23.079C134.754 23.1542 134.802 23.4329 134.727 23.4197L134.36 23.3622L132.095 28.193L133.489 27.5073L136.156 26.2376C136.461 26.0916 136.669 25.6979 137.112 25.8882L137.824 25.49C137.846 25.4679 137.886 25.2379 137.912 25.2644L138.107 25.4944L141.801 24.3487L141.991 24.5876C140.558 24.968 139.293 25.4237 137.939 26.0164C137.713 26.1138 137.457 26.1049 137.412 26.3969L140.717 25.198C141.301 24.9857 141.854 24.8132 142.464 24.8486L142.787 25.5077L142.203 25.9766L142.208 25.9722ZM137.881 13.966C138.39 13.329 138.748 12.7052 138.877 11.9133C138.642 12.1434 138.549 12.4221 138.421 12.7406C138.253 13.1609 137.908 13.4838 137.881 13.966ZM127.3 30.0996C127.773 29.3653 128.038 28.684 128.246 27.9054C127.738 28.5734 127.41 29.321 127.3 30.0996Z" fill="#242424"/> +<path d="M70.9889 8.0071L70.5598 8.82108L70.4935 8.27695L70.7633 7.62223L71.4888 6.02523C71.7366 6.29951 71.7498 6.53397 71.6525 6.7994L71.0066 8.59989L70.9845 8.00268L70.9889 8.0071Z" fill="#242424"/> +<path d="M89.8786 33.9041L91.8605 29.9492L92.5064 28.7371L92.5771 28.914L90.8297 32.3912C90.5687 32.9132 90.321 33.4352 89.8786 33.9041Z" fill="#242424"/> +<path d="M89.1177 35.7179L88.2816 37.3503L88.1445 37.2662L89.1575 35.2711C89.1885 35.2357 89.1752 35.6073 89.1177 35.7179Z" fill="#242424"/> +<path d="M30.1041 20.2036C30.4403 19.5842 30.8428 19.0534 31.3471 18.5225C31.0596 19.1728 30.6924 19.7302 30.1041 20.2036Z" fill="#242424"/> +</g> +</svg> diff --git a/app/vendor/rune/site/src/main.tsx b/app/vendor/rune/site/src/main.tsx new file mode 100644 index 0000000..d630de6 --- /dev/null +++ b/app/vendor/rune/site/src/main.tsx @@ -0,0 +1,15 @@ +import { StrictMode } from "react" +import { createRoot, hydrateRoot } from "react-dom/client" +import { App } from "./App" +import "./system/tokens.css" +import "./site.css" + +const root = document.getElementById("root")! +const page = ( + <StrictMode> + <App /> + </StrictMode> +) + +if (root.firstElementChild) hydrateRoot(root, page) +else createRoot(root).render(page) diff --git a/app/vendor/rune/site/src/pages.tsx b/app/vendor/rune/site/src/pages.tsx new file mode 100644 index 0000000..ee1640a --- /dev/null +++ b/app/vendor/rune/site/src/pages.tsx @@ -0,0 +1,1092 @@ +import type { CSSProperties, ReactNode } from "react" +import { decisions, layers, milestones, principles, risks, type CodeRef, type Entry, type Milestone } from "./content" +import { Code } from "./Code" +import { + ArchitectureDiagram, + CrateMap, + FrameDiagram, + PipelineDiagram, + StateLoopDiagram, + TestDiagram, + ThreadDiagram, +} from "./Diagram" +import { withBase } from "./base" +import { Wordmark } from "./brand/Wordmark" +import { REPO } from "./routes" +import { PageHead, SectionHead } from "./system/Frame" + +export const num = (i: number) => String(i + 1).padStart(2, "0") + +function Rule({ entry, number, children }: { entry: Entry; number?: string; children?: ReactNode }) { + return ( + <article id={entry.slug} className="rule"> + <header className="rule-head"> + {number && ( + <a className="rule-num" href={`#${entry.slug}`} aria-label={`${entry.title}, ${number}`}> + {number} + </a> + )} + <h3 className="rule-title">{entry.title}</h3> + </header> + <div className="rule-body"> + <div className="rule-text">{entry.body}</div> + {(entry.spec || entry.code) && ( + <dl className="rule-spec"> + {entry.spec?.map(s => ( + <div key={s.label}> + <dt>{s.label}</dt> + <dd className={s.mono ? "mono" : undefined}> + {s.values.map((v, i) => ( + <span key={i}>{v}</span> + ))} + </dd> + </div> + ))} + {entry.code && ( + <div> + <dt>Code</dt> + <dd> + <CodeRefs refs={entry.code} /> + </dd> + </div> + )} + </dl> + )} + </div> + {children} + </article> + ) +} + +/** Files in this repo, crate (or folder) first so the names line up, each linked to GitHub. */ +function CodeRefs({ refs }: { refs: CodeRef[] }) { + return ( + <ul className="refs"> + {refs.map(({ path, note }) => { + const parts = path.split("/") + const inCrate = parts[0] === "crates" || parts[0] === "examples" + const label = inCrate ? parts[1]! : parts[0]! + const rest = parts.slice(inCrate ? 2 : 1) + const folder = !/\.\w+$/.test(path) + const name = (rest[0] === "src" ? rest.slice(1) : rest).join("/") + (folder ? "/" : "") + return ( + <li key={path}> + <a className="ref-link" href={`${REPO}/${folder ? "tree" : "blob"}/dev/${path}`} title={path}> + <span className="ref-label">{label}</span> + <span> + <span className="ref-name">{name}</span> + {note && <span className="ref-note">{note}</span>} + </span> + </a> + </li> + ) + })} + </ul> + ) +} + +export function Pager({ prev, next }: { prev?: [string, string]; next?: [string, string] }) { + return ( + <nav className="doc-pager" aria-label="Pages"> + {prev ? <a href={withBase(prev[0])}>← {prev[1]}</a> : <span />} + {next && <a href={withBase(next[0])}>{next[1]} →</a>} + </nav> + ) +} + +type Status = "works" | "partly" | "planned" + +const STATUS: Record<Status, { label: string; dot: Milestone["status"] }> = { + works: { label: "Works today", dot: "done" }, + partly: { label: "Partly", dot: "started" }, + planned: { label: "Planned", dot: "later" }, +} + +/** What Rune can build today, checked against the code; each row names where to see it. */ +const buildable: { title: string; text: ReactNode; status: Status; meta: string; href?: string }[] = [ + { + title: "Desktop apps on macOS", + text: ( + <> + Windows drawn entirely by Rune through winit and wgpu. The Settings window and a gallery of OpenCode's + components run today. + </> + ), + status: "works", + meta: "examples/settings", + }, + { + title: "Windows and Linux", + text: ( + <> + The same wgpu backend, with Win32, X11 and Wayland code for overlays already in. Running and checking apps on + both is the next milestone, with Hex's Settings as the first real screen. + </> + ), + status: "partly", + meta: "M2", + href: "/roadmap#m2", + }, + { + title: "Background and menu-bar apps", + text: ( + <> + An app can start with no window, keep running after its window closes, reopen it with the same state, and on + macOS run with no Dock icon. + </> + ), + status: "works", + meta: "examples/background", + }, + { + title: "Overlays and HUDs", + text: ( + <> + Transparent, click-through windows over every display, and HUD panels at a screen edge that never take focus, + fed from any thread. Built for Rooms. + </> + ), + status: "works", + meta: "examples/overlay", + }, + { + title: "Video", + text: ( + <> + Decoded frames drawn as ordinary Rune nodes: NV12 IOSurfaces on macOS, uploaded planes elsewhere, fed by a + background producer. The example uses synthetic frames. + </> + ), + status: "works", + meta: "examples/video-tiles", + }, + { + title: "Headless rendering", + text: ( + <> + Every app also runs with no window: PNG stills at a chosen moment, frame sequences, input scripts and motion + traces, for tests, CI goldens and agents. A CPU reference renderer checks the GPU one. + </> + ), + status: "works", + meta: "crates/rune-ref", + }, + { + title: "Effects and lighting", + text: ( + <> + Glow, fire, electricity, distortion and motion blur (<code>rune-fx</code>), and soft shadows and highlights from + a light you place (<code>rune-light</code>), drawn through the compositor hook. + </> + ), + status: "works", + meta: "examples/lab", + }, + { + title: "Web", + text: ( + <> + The same apps in a browser over WebGPU, in one canvas on the page's main thread. Experimental: Safari keyboard + checks, accessibility and a WebGL fallback are still to come. + </> + ), + status: "partly", + meta: "examples/web-hello", + }, + { + title: "iOS, then Android", + text: ( + <> + An iOS shell with native text input and a view for embedding Rune in SwiftUI. Nothing runs on a phone yet. + </> + ), + status: "planned", + meta: "M6", + href: "/roadmap#m6", + }, +] + +export function HomeView() { + return ( + <> + <header id="home-hero" className="home-hero"> + <h1 className="masthead"> + <span className="sr-only">Rune</span> + <Wordmark periodic /> + </h1> + <p className="home-lede"> + <strong> + Rune is a Rust UI framework with its own GPU renderer, text, layout, spring animation and thin shells for + each platform. + </strong>{" "} + It aims to feel like SwiftUI on a 120&nbsp;Hz iPhone on every platform, and to be written and checked by coding + agents. It's early, and its APIs will change. + </p> + </header> + + <section className="home-section"> + <SectionHead id="app" title="A Rune app"> + <p> + State is a plain struct, the view is a function of it, and a handler changes it. This is{" "} + <code>examples/hello</code> apart from its test, which is further down. The switch never animates itself: the view says where the knob is, and{" "} + <code>.motion(motion::SNAPPY)</code> names the spring that moves it. + </p> + </SectionHead> + <div className="app-demo"> + <Code id="hello" /> + <figure className="shot app-shot" style={{ "--shot-w": "320px" } as CSSProperties}> + <img + src={withBase("/shots/hello-on.png")} + alt="A dark window with the words Lights on above a blue switch, turned on" + width={320} + height={200} + /> + <figcaption> + Headless: <code>--snap hello.png --scene on</code> + </figcaption> + </figure> + </div> + </section> + + <section className="home-section"> + <SectionHead id="frame" title="From your code to the screen" /> + <PipelineDiagram /> + </section> + + <section className="home-section"> + <SectionHead id="how" title="How do I…"> + <p>Each of these is cut from a Rune example or test when the site builds, so it compiles and runs.</p> + </SectionHead> + <div className="howto-list"> + <article className="howto"> + <h3 id="how-list">Keep a list in state</h3> + <p> + Build a row per item with a stable key. Rows added or removed after the first frame animate in and out on + their own, and handlers capture the id they act on. + </p> + <div className="app-demo"> + <Code id="todo-list" /> + <figure className="shot app-shot" style={{ "--shot-w": "360px" } as CSSProperties}> + <img + src={withBase("/shots/todo.png")} + alt="A dark todo list with a progress bar, three rows with round checkboxes, and an Add a todo link" + width={360} + height={240} + loading="lazy" + /> + <figcaption> + Headless: <code>--snap todo.png</code> + </figcaption> + </figure> + </div> + </article> + <article className="howto"> + <h3 id="how-spring">Animate on a spring</h3> + <p> + Set the value the state implies and name a spring with <code>Spring::new(duration, bounce)</code>. When + a todo is ticked, the bar retargets from wherever it is, keeping its velocity. + </p> + <Code id="todo-spring" /> + </article> + <article className="howto"> + <h3 id="how-overlay">Open an overlay on every display</h3> + <p> + <code>run_windows</code> builds one window per <code>WindowSpec</code>, and{" "} + <code>WindowOptions::overlay</code> makes it transparent, borderless, on top and click-through. All the + windows can share one <code>Live</code> value fed from a background thread. + </p> + <Code id="overlay-windows" /> + </article> + <article className="howto"> + <h3 id="how-test">Test it without a window</h3> + <p> + A <code>Runtime</code> is the window's runtime with no window. The test taps the switch and steps the + clock to check the knob travels and lands. It runs in <code>cargo test</code> with no GPU. + </p> + <Code id="hello-test" /> + </article> + </div> + <p className="home-more"> + <a href={withBase("/how-it-works")}>How it works</a> follows one frame through the code, with more examples. + </p> + </section> + + <section className="home-section"> + <SectionHead id="build" title="What you can build" aside="October 2026"> + <p> + Native apps first, and anything that needs Rune's pixels without a window, since headless runs use the same + code. The web build is experimental, and phones are planned. + </p> + </SectionHead> + <ul className="index-list"> + {buildable.map(b => ( + <li key={b.title} className="index-row"> + <span className="index-title">{b.title}</span> + <p className="index-text">{b.text}</p> + <span className="index-meta build-meta"> + <span className="status" data-status={STATUS[b.status].dot}> + {STATUS[b.status].label} + </span> + {b.href ? ( + <a href={withBase(b.href)}>{b.meta}</a> + ) : ( + <a href={`${REPO}/tree/dev/${b.meta}`}>{b.meta}</a> + )} + </span> + </li> + ))} + </ul> + <div className="shots"> + <figure className="shot"> + <img src={withBase("/shots/settings.png")} alt="A dark Settings window with theme, accent, toggle and slider rows" width={1240} height={1040} loading="lazy" /> + <figcaption>examples/settings, rendered headless</figcaption> + </figure> + </div> + </section> + + <section className="home-section"> + <SectionHead id="next" title="Next"> + <p> + The first real screen is Hex's Settings on Mac, Windows and Linux, which brings Rune's own platform shells + and native text input. After that come OpenCode Desktop's main screens. That's the flagship test: it should + look like the current app side by side and feel clearly better. + </p> + </SectionHead> + </section> + + <Pager next={["/how-it-works", "How it works"]} /> + </> + ) +} + +export function HowItWorksView() { + return ( + <> + <PageHead eyebrow={<span>How it works</span>} title="How Rune works"> + <p> + You write a function from your app's state to a keyed tree of elements. Rune lays the tree out, animates + every change on springs and draws the frame with wgpu. + </p> + <p> + This page follows one frame through the code, then shows the code you write. Every example is cut from + Rune's source when the site builds and links to the lines it came from. + </p> + </PageHead> + + <section className="doc-section"> + <SectionHead id="frame" title="A frame"> + <p> + Each frame runs these steps in order, in <code>Runtime::frame</code> and the window's redraw. The view + function only runs when state changed, so animating costs your code nothing. + </p> + </SectionHead> + <FrameDiagram /> + </section> + + <section className="doc-section"> + <SectionHead id="app" title="A window and a view"> + <p> + An app is a state type, a view function and an <code>AppSpec</code>. <code>rune::run</code> opens the + window, or renders headless when given a flag like <code>--snap</code>. Scenes are named starting states + for those renders. This is the <a href={withBase("/")}>Settings window</a> from the overview. + </p> + </SectionHead> + <div className="code-stack"> + <Code id="app-cargo" /> + <Code id="app-main" /> + </div> + </section> + + <section className="doc-section"> + <SectionHead id="state" title="State changes in handlers"> + <p> + A handler is a plain function that gets <code>&amp;mut</code> state. Handlers are queued and run between + frames, then the view re-runs and the new tree is matched to the old one by key. The toggle never animates + anything itself. It says where the knob should be, and <code>.motion(motion::SNAPPY)</code> names the + spring that gets it there. + </p> + </SectionHead> + <StateLoopDiagram /> + <div className="code-stack"> + <Code id="toggle" /> + <Code id="motion-tokens" /> + </div> + </section> + + <section className="doc-section"> + <SectionHead id="springs" title="Springs keep their velocity"> + <p> + <code>Spring::new(duration, bounce)</code> uses SwiftUI's numbers: ω&nbsp;=&nbsp;2π&nbsp;/&nbsp;duration + and ζ&nbsp;=&nbsp;1&nbsp;−&nbsp;bounce. Each animated property is a track of closed-form spring segments, so + its position and velocity are exact at any time. When the target changes mid-flight, the new segment + starts from that position and velocity, so the value turns smoothly instead of jumping or stopping. This + test checks it. + </p> + </SectionHead> + <Code id="retarget" /> + </section> + + <section className="doc-section"> + <SectionHead id="live" title="Values that change every frame skip the view"> + <p> + Audio levels, remote cursors and drag positions change too often to go through state. + A <code>Live&lt;T&gt;</code> binds straight to a property, and any thread can set it. The test checks that + setting four of them runs no view, layout or text shaping. + </p> + </SectionHead> + <Code id="live" /> + </section> + + <section className="doc-section"> + <SectionHead id="threads" title="Threads"> + <p> + Springs belong to the runtime's <code>Scene</code>, which today lives on the main thread with everything + else. The <a href={withBase("/architecture")}>architecture</a> moves it to a render thread. + </p> + </SectionHead> + <ThreadDiagram /> + </section> + + <section className="doc-section"> + <SectionHead id="testing" title="Tests run without a window"> + <p> + A test builds a <code>Runtime</code> from a state and a view, steps it frame by frame and reads back what + it laid out. The same binaries take flags that render PNGs, play input scripts and write motion traces. + </p> + </SectionHead> + <TestDiagram /> + <div className="code-stack"> + <Code id="test-segmented" /> + <Code id="tap-script" /> + <Code id="snap-commands" /> + </div> + <div className="prose prose-after"> + <p> + The renderer is checked against a reference. <code>rune-ref</code> draws the same instances on the CPU + with strict float rules, and a hash of each generated scene is pinned in <code>goldens.json</code>. A + differential test then holds the GPU to within 2 levels per channel of the CPU image. + </p> + </div> + <Code id="golden-hashes" /> + </section> + + <section className="doc-section"> + <SectionHead id="crates" title="Where the code lives"> + <p> + The workspace is layered by responsibility. <code>rune</code> brings together the view tree, runtime, + renderer, windows and tooling, and re-exports the crates below it so apps depend on <code>rune</code> alone. + </p> + </SectionHead> + <CrateMap /> + <Code id="rune-deps" /> + </section> + + <Pager prev={["/", "Overview"]} next={["/launch-fast", "Launch fast"]} /> + </> + ) +} + +export function Sample({ lang = "Rust", children }: { lang?: string; children: string }) { + return ( + <figure className="code-block"> + <figcaption className="code-head"> + <span>{lang}</span> + </figcaption> + <pre className="code"> + <code>{children}</code> + </pre> + </figure> + ) +} + +const launchSetup = `let app = App::new(AppSpec::new("Notes", (520.0, 320.0), State::default, view)) + .accessory() + .keep_running(); +let handle = app.handle(); +app.on_ready(move |_window| { + handle.update(|state, tx| { + // First frame is on screen: now the menu bar item, indexing, network. + state.start_background_work(tx); + }); +}) +.run();` + +const launchHidden = `// Keep the window; hide it instead of closing it. +let app = App::new(spec).keep_running().windowless(); +let handle = app.handle(); + +// On the shortcut, the tray click or a Dock reopen: +handle.show(); // or handle.open() to also activate the app +// When the user dismisses it: +handle.hide();` + +const launchNumbers: { row: string; before: string; after: string }[] = [ + { row: "Cold shader cache, content on screen", before: "599", after: "312" }, + { row: "Cold shader cache, window on screen", before: "422", after: "277" }, + { row: "Warm shader cache, content on screen", before: "466", after: "299" }, + { row: "Cold shader cache, Renderer::new alone", before: "232", after: "85" }, +] + +export function LaunchFastView() { + return ( + <> + <PageHead eyebrow={<span>Launch fast</span>} title="Launch fast"> + <p> + A Rune app can put its first window, with its content drawn, on screen about 300 ms after{" "} + <code>open</code> on an Apple silicon Mac, including the first launch after an install or update. Four + things get it there: start the GPU on a thread, ship the shader precompiled, keep the main thread free until + the first frame, and reuse a window instead of rebuilding it. + </p> + <p> + Two of them need one line or nothing from the app. The rest is about what the app leaves out of its first + frame. The numbers are at the end. Keeping the app fast after launch is on{" "} + <a href={withBase("/fast-apps")}>Fast apps</a>. + </p> + </PageHead> + + <section className="doc-section"> + <SectionHead id="prewarm" title="Call prewarm_gpu first in main"> + <p> + A first frame needs a GPU adapter, a device and Rune's render pipeline, and making them is most of a cold + launch. <code>rune::prewarm_gpu()</code> starts that work on a thread. + </p> + </SectionHead> + <Sample>{`fn main() { + rune::prewarm_gpu(); + // ... build the App and run it +}`}</Sample> + <div className="prose prose-after"> + <p> + On macOS the thread makes the instance, adapter and device, then builds the uber pipeline, loading the + precompiled shader described below. The first window or overlay opened at launch takes the result, and + waits if the thread is still working. Rune's run functions call it too, but only once they start the event + loop, so calling it yourself in the first line of <code>main</code> gains the time your own setup takes + before that. + </p> + <ul> + <li>Calling it twice does nothing the second time.</li> + <li> + It starts on the backend a Mac app draws with by default: Rune's own Metal backend, from the{" "} + <code>metal-backend</code> feature, which is on by default. An app built with{" "} + <code>default-features = false</code> draws with wgpu unless it adds the feature. + </li> + <li> + An app that opts out with <code>App::gpu_backend(GpuBackend::Wgpu)</code> calls{" "} + <code>rune::prewarm_gpu_on(GpuBackend::Wgpu)</code> instead. It chooses the backend, then starts the + thread, so the work doesn't start on the native backend and start over when{" "} + <code>App::gpu_backend</code> runs; that call afterwards changes nothing. <code>RUNE_GPU_BACKEND=wgpu</code>{" "} + or <code>=metal</code> overrides both without a rebuild. + </li> + <li> + If the app opens no window at launch, the result is dropped and nothing stays in memory. A{" "} + <code>windowless</code> app that opens its window later makes the device then, as it always did. + </li> + <li> + If the first window needs GPU features the prewarmed device lacks, or the adapter can't present to its + surface, the window makes a new device on the same instance. The pipeline is built for the usual surface + format; a window with another one builds its own. + </li> + <li>On other platforms it does nothing, because the window's surface chooses the adapter there.</li> + </ul> + </div> + </section> + + <section className="doc-section"> + <SectionHead id="metallib" title="Precompiled Metal shaders"> + <p> + Without help, a launch translates the uber shader's WGSL to Metal source and has Metal compile it. Rune + commits the compiled library instead, as <code>crates/rune/src/shaders/uber.metallib</code> (about 33 KB), and on + macOS loads it through wgpu's passthrough shader support. This skips WGSL parsing, validation, translation + and Metal's compile on every launch. <code>Renderer::new</code> on a cold shader cache goes from 232 ms to + 85 ms, and from 3.4 ms to 0.6 ms on a warm one. Rune's own Metal backend loads{" "} + <code>uber_native.metallib</code> the same way, the Metal its translation emits, so it skips the same work. + </p> + </SectionHead> + <div className="prose"> + <p> + Apps need nothing and don't need Xcode: the library is a file in the crate. Rune falls back to the WGSL + path, which is slower but identical on screen, when: + </p> + <ul> + <li>the adapter lacks <code>PASSTHROUGH_SHADERS</code>;</li> + <li> + <code>RUNE_DISABLE_METALLIB=1</code> is set, which is also how to compare the two paths; + </li> + <li>the committed library's fingerprint doesn't match the shader the build generates;</li> + <li>Metal rejects the library or the pipeline made from it.</li> + </ul> + <h3>Changing the shader</h3> + <p> + Edit <code>clip.wgsl</code> or <code>shader.wgsl</code>, then run{" "} + <code>cargo test -p rune --lib --features metal-backend precompiled_uber_metallib_is_fresh</code> on a Mac. + The test compares the + library and the shader's fingerprints, and its failure message says what to do: + </p> + <ul> + <li> + <strong>"MSL is byte-identical; no Xcode or metallib regeneration needed"</strong> means only the + fingerprint changed, for example after a comment edit or a descriptor change that generates the same + Metal. Paste the three <code>pub(super) const</code> lines it prints into{" "} + <code>crates/rune/src/render/uber/metallib_hash.rs</code>. + </li> + <li> + <strong>"generated MSL or Metal compile flags changed"</strong> or{" "} + <strong>"does not match recorded hash"</strong> means the library is stale. Run{" "} + <code>scripts/precompile-metal-shaders.sh</code>. It needs Xcode's Metal toolchain ( + <code>xcrun -sdk macosx metal</code>), dumps the generated MSL, compiles it and rewrites{" "} + <code>uber.metallib</code>, <code>uber_native.metallib</code> and <code>uber/metallib_hash.rs</code>. + Commit all three. + </li> + </ul> + <p> + On other platforms the same test can only say the fingerprint changed, and tells you to run it on macOS for + the exact lines. + </p> + <h3>What it doesn't cover</h3> + <p> + Only the uber pipeline is precompiled. The effect, lighting and blur shaders still compile from WGSL the + first time they're used, so an app that draws them on its first frame still pays that on a cold cache. + iOS isn't covered. Metal binary archives could cover the rest, but they would need support in wgpu, which it doesn't have. + </p> + </div> + </section> + + <section className="doc-section"> + <SectionHead id="first-frame" title="The first frame is drawn while the window is created"> + <p> + On macOS a visible window draws its first frame during creation, before the window server reports it on + screen. Launcher windows and panels, which start hidden, are left out. + </p> + </SectionHead> + <div className="prose"> + <p> + There is nothing to turn on. Before this, a window opened empty and drew on a later display-link tick; now + content reaches the screen about 30 ms sooner on an idle Mac, and about 150 ms sooner on a busy one, where + the window server is slow to say a new window is visible. + </p> + <p> + It has one consequence for the app. The first view build and layout now run inside window creation, right + after the window-created callbacks (<code>App::on_window</code>, <code>WindowSpec::on_created</code>). The + window can't appear until they return, so the state's initial value, the first <code>view</code> call and + those callbacks should be cheap. Anything slow added there delays the whole window, not just its content. + </p> + </div> + </section> + + <section className="doc-section"> + <SectionHead id="defer" title="Start everything else after the first frame"> + <p> + The menu bar item, status item, HUDs, secondary windows, network requests and file indexing are all work + the user doesn't need to see the first window. Start them from <code>on_ready</code>. + </p> + </SectionHead> + <div className="prose"> + <p> + <code>App::on_ready</code> (and <code>WindowSpec::on_ready</code>) runs on the event thread once per native + window creation, after the first frame is ready. For a launcher it runs while the window is still hidden, + once its cached frame has finished on the GPU, which is the place to register a global shortcut. A window + that isn't on screen (covered, occluded, hidden or on another Space) doesn't wait to draw: it runs at the + first frame skipped for that, or a second after the window opens. It isn't called by headless tooling. The callback gets a <code>WindowHandle</code>, not the state, so capture an{" "} + <code>AppHandle</code> and hand the work to <code>update</code>, which runs on the UI thread with{" "} + <code>&amp;mut S</code> and a <code>Tx</code>. + </p> + </div> + <Sample>{launchSetup}</Sample> + <div className="prose prose-after"> + <p> + Rune has no separate "after first frame" hook for state today; this is how to do it. Updates run inside the + event loop even while no window shows, so an update may do main-thread native work such as creating a + status item. For work that doesn't need the main thread, spawn a thread from the update and report back + with <code>AppHandle::update</code> or <code>AppHandle::wake</code> and <code>AppSpec::poll</code>. + </p> + <p> + A launcher can wait for readiness. With <code>RUNE_READY_DIR</code> set, the process writes{" "} + <code>$RUNE_READY_DIR/&lt;bundle id&gt;.&lt;pid&gt;</code> right after its first <code>on_ready</code>{" "} + returns: one line of JSON with <code>pid</code>, <code>bundle_id</code>, <code>ready_ms</code> (since the + process started) and <code>rune</code> (its version). It removes the file when it exits normally; a + process killed outright leaves it, so treat one whose PID isn't running as stale. + </p> + </div> + </section> + + <section className="doc-section"> + <SectionHead id="still" title="Keep the first second still"> + <p> + Rune animates nothing in the first second after content shows, so every frame drawn then is the app's. + The usual cause is state that arrives a few milliseconds after launch, such as a system setting or a + first network answer, and animates in. + </p> + </SectionHead> + <div className="prose"> + <p> + Land that first answer with <code>tx.instant()</code>, or don't animate it. A settings row whose switch + faded in over a placeholder, and reflowed the row, kept its window drawing at 120 Hz for 0.7 s: about 85 + frames in the first second instead of 4 to 8. + </p> + <p> + It costs memory too. A window that draws back to back while it comes on screen makes macOS allocate an + extra window-sized drawable and keep it; that row cost 14 MB of settled footprint (91 MB instead of 77). + Rune now holds a new window to two drawables until it first rests, or for its first second, so launch + frames that wait on the window server or a shader compile no longer cause it. + </p> + </div> + </section> + + <section className="doc-section"> + <SectionHead id="idle" title="Draw nothing when idle"> + <p> + A window at rest should present no frames. Rune stops its display link when nothing moves, so what keeps + an idle window drawing is almost always the app's own timers, polls or compositor. + </p> + </SectionHead> + <div className="prose"> + <ul> + <li> + <strong>Return false from <code>poll</code> when nothing changed.</strong> A due{" "} + <code>wake_after</code> on a resting window runs <code>poll</code> first and builds, lays out and + draws only if it returns true. A poll that always returns true draws a frame on every tick. + </li> + <li> + <strong>A compositor reports <code>animating()</code> only while it moves.</strong> It defaults to false. + A window with a still compositor rests and gates its timers on <code>poll</code> like any other; one + that always reports true draws every display-link tick. + </li> + </ul> + <p> + A settings window that checked a system setting four times a second went from 77 presents per 20 s idle to + none, its CPU from 2.45% to 0.85%, and its footprint from 77 MB to 70 MB. + </p> + </div> + </section> + + <section className="doc-section"> + <SectionHead id="reuse" title="Reuse a hidden window"> + <p> + Showing a window that already exists costs a show. Rebuilding it costs a launch: the native window, the + surface, the first view and layout. An app that comes and goes, such as a launcher, a menu bar panel or a + settings window, should hide its window and show it again. + </p> + </SectionHead> + <div className="prose"> + <ul> + <li> + <code>App::keep_running</code> keeps the app, its state and its event loop alive when the window closes, + and <code>windowless</code> starts with no window. On macOS, Windows and X11 closing hides the window and + keeps its host; <code>AppHandle::open</code>, <code>show</code> and <code>activate</code> bring it back + with the same state, settled on its first frame. Wayland has no hidden toplevel, so it destroys and + recreates the window. + </li> + <li> + <code>AppHandle::hide</code> hides it without running the close callback. <code>show</code> shows it + without taking focus; <code>open</code> also restores a minimized window and activates the app.{" "} + <code>WindowHandle::show</code>, <code>hide</code> and <code>set_visible</code> do the same from window + callbacks. + </li> + <li> + <code>WindowOptions::launcher_panel()</code> makes a hidden, retained, nonactivating panel on macOS. It + prepares its first frame at alpha zero while hidden, keeps rendering changes into that cached frame, and + reveals the cached pixels on show, so a re-summon draws nothing new. + </li> + <li> + A hidden window runs updates, polls and timers as usual but skips view and layout, and the frame that + shows it builds once with the latest state. + </li> + <li> + Keep the GPU too. <code>release_gpu_when_closed</code> frees it for an app that idles for hours, but the + next open then pays for a device again. + </li> + </ul> + </div> + <Sample>{launchHidden}</Sample> + </section> + + <section className="doc-section"> + <SectionHead id="measure" title="Measure it"> + <p> + Launch time moves with the machine's load and Metal's cache, so a single run says little. This is the + method behind the numbers below. + </p> + </SectionHead> + <div className="prose"> + <ul> + <li> + <strong>Launch like a user does.</strong> Build the app into a bundle with its own bundle ID and start it + with <code>open</code>, from a script that takes the timestamp just before. Stop it between runs. Use a + Mac with nothing else running, and a release or <code>perf</code> build. + </li> + <li> + <strong>Interleave the builds.</strong> Alternate base and changed builds inside each round, 5 to 10 + rounds, and compare medians and the 10th to 90th percentile spread. Load drifts over minutes; interleaving + puts it on both sides. + </li> + <li> + <strong>Time two moments.</strong> The window is visible when the process's window shows up on screen, + which you can poll for in the window list. Content is visible at its first presented frame, which you can + timestamp in the app or read from a screen recording of the window's rectangle. They differ by the time the + app takes to draw after the window exists, which is what this page reduces. + </li> + <li> + <strong>Run cold and warm.</strong> A cold launch is the first after an install or update, when Metal + compiles shaders. To get one, delete the app's Metal shader caches, which sit in the user cache directory + (<code>getconf DARWIN_USER_CACHE_DIR</code>) under the bundle ID: <code>com.apple.metal/&lt;bundle + id&gt;</code>, and <code>&lt;bundle id&gt;/com.apple.metal</code>,{" "} + <code>&lt;bundle id&gt;/com.apple.metalfe</code> and <code>&lt;bundle id&gt;/com.apple.gpuarchiver</code>. + A warm launch follows an unmeasured one that fills the cache. + </li> + <li> + <strong>Read settled memory last.</strong> Record the process's physical footprint a few seconds after + launch. The <code>procwatch</code> crate reads it and counts allocations. A change that moves work earlier + can raise memory at the window and leave it equal once settled. + </li> + <li> + <strong>Count frames in the first second.</strong> After content shows, a still app draws a handful. Many + more means something animates at launch. + </li> + <li> + <strong>Measure idle too.</strong> Leave the window shown and untouched for 20 s, and count redraws and + presents, CPU, and settled RSS and footprint. Count <code>poll</code> calls and the ones that return true + separately from frames, so you can tell whether the app or the toolkit asked for each frame. + </li> + </ul> + <p> + In the repo, <code>--native --trace run.jsonl</code> writes wall-clock submission timestamps per frame for a + real window, <code>surface_stats</code> reports presents and failed drawable acquisitions, and the{" "} + <code>frame-profile</code> feature times view, layout, text and paint phases in headless runs. Run the app + with <code>RUNE_DISABLE_METALLIB=1</code> to see what the precompiled library saves on your machine. + </p> + </div> + </section> + + <section className="doc-section"> + <SectionHead id="numbers" title="Measured"> + <p> + Median milliseconds from <code>open</code> for a small app, on an Apple silicon laptop that was under heavy + load, 5 interleaved rounds (10 for <code>Renderer::new</code>). The absolute times are high because the machine + was busy. The differences are what matter. + </p> + </SectionHead> + <div className="table-wrap"> + <table className="decisions"> + <thead> + <tr> + <th scope="col">Launch</th> + <th scope="col">Before</th> + <th scope="col">After</th> + <th scope="col">Saved</th> + </tr> + </thead> + <tbody> + {launchNumbers.map(n => ( + <tr key={n.row}> + <th scope="row">{n.row}</th> + <td data-label="Before">{n.before} ms</td> + <td data-label="After">{n.after} ms</td> + <td data-label="Saved">{Number(n.before) - Number(n.after)} ms</td> + </tr> + ))} + </tbody> + </table> + </div> + <div className="prose prose-after"> + <p> + The first three rows are the first-frame and GPU prewarm changes together, in a hello-world app; a settings + window gave 308 ms cold and 291 ms warm. After the change, content lands 30 to 40 ms after the window; before, + 160 to 190 ms after. The precompiled shader helps most on a cold cache (the last row); a warm cache already + holds Metal's result, so warm launches gain little from it. Settled memory was the same, within 1 MB, in + every case. + </p> + </div> + </section> + + <Pager prev={["/how-it-works", "How it works"]} next={["/fast-apps", "Fast apps"]} /> + </> + ) +} + +export function PrinciplesView() { + return ( + <> + <PageHead eyebrow={<><span>Principles</span><span>{principles.length}</span></>} title="Principles"> + <p> + What Rune optimises for, most important first. Where it can, the framework enforces each one so that apps get + it by default. + </p> + </PageHead> + <div className="rules"> + {principles.map((p, i) => ( + <Rule key={p.slug} entry={p} number={num(i)} /> + ))} + </div> + <Pager prev={["/architecture", "Architecture"]} next={["/roadmap", "Roadmap"]} /> + </> + ) +} + +export function ArchitectureView() { + return ( + <> + <PageHead eyebrow={<span>Architecture</span>} title="How Rune is built"> + <p> + The design splits a Rune app across two threads. The app side turns state into a keyed tree and lays it out + at its target state. The render thread owns what's on screen and animates toward those targets. Everything + between them goes through one command channel. + </p> + <p> + This page is the target from <a href={`${REPO}/blob/dev/PLAN.md`}>PLAN.md</a>. Today both sides run on one + thread, in the order shown in <a href={withBase("/how-it-works#frame")}>How it works</a>. + </p> + </PageHead> + + <section className="doc-section"> + <SectionHead id="overview" title="Overview" /> + <ArchitectureDiagram /> + </section> + + <section className="doc-section"> + <SectionHead id="channel" title="The command channel" /> + <div className="prose"> + <p> + The channel carries tree diffs, target layout rects, shaped text runs and spring targets to the render + thread, and hits, gesture results, settles and presented-frame ids back. It's a real, serialisable protocol + rather than shared memory, and three things follow from that. + </p> + <ul> + <li> + <strong>Animations survive a busy app.</strong> When a value animates, the app side does no view re-run, + layout or diff. + </li> + <li> + <strong>Hot reload reaches the iPhone.</strong> In development the channel runs over USB, with the render + thread on the phone and the app side on the Mac, where it can be hot-patched. + </li> + <li> + <strong>Agents and tests read the same stream.</strong> Recording the channel gives deterministic replay, + frame traces and an inspector. + </li> + </ul> + </div> + </section> + + <section className="doc-section"> + <SectionHead id="layers" title="Layers" aside={`01–${num(layers.length - 1)}`} /> + <div className="rules"> + {layers.map((l, i) => ( + <Rule key={l.slug} entry={l} number={num(i)}> + {l.slug === "tree" && <Code id="toggle-only" />} + </Rule> + ))} + </div> + </section> + + <div id="choices"> + <section className="doc-section"> + <SectionHead id="decisions" title="Decisions"> + <p>What Rune chose for each layer, what it turned down, and why.</p> + </SectionHead> + <div className="table-wrap"> + <table className="decisions"> + <thead> + <tr> + <th scope="col">Area</th> + <th scope="col">Chose</th> + <th scope="col">Instead of</th> + <th scope="col">Why</th> + </tr> + </thead> + <tbody> + {decisions.map(d => ( + <tr key={d.area}> + <th scope="row">{d.area}</th> + <td data-label="Chose">{d.chose}</td> + <td className="rejected" data-label="Instead of">{d.rejected}</td> + <td>{d.why}</td> + </tr> + ))} + </tbody> + </table> + </div> + </section> + + <section className="doc-section"> + <SectionHead id="gpui" title="Why not fork GPUI" /> + <div className="prose"> + <p> + Zed's GPUI is the closest existing framework, and it has gained a wgpu backend, iOS and web shells, springs, + AccessKit and hot reload. It still redraws the whole window on every dirty frame, has no layer compositing + or group opacity, and runs animations by re-rendering views on the main thread. Those are architectural, and + they're the reasons Kit's apps kept leaving it for Apple frameworks. + </p> + <p> + So Rune starts fresh and borrows GPUI's best parts under its Apache-2.0 licence: the rope and sum tree, the + line layout cache, the macOS and iOS text input code and the web textarea bridge. + </p> + </div> + </section> + </div> + + <Pager prev={["/fast-apps", "Fast apps"]} next={["/principles", "Principles"]} /> + </> + ) +} + +const STATUS_LABEL: Record<Milestone["status"], string> = { + done: "Done", + now: "Now", + started: "Started", + next: "Next", + later: "Later", +} + +export function RoadmapView() { + return ( + <> + <PageHead eyebrow={<span>Roadmap</span>} title="Roadmap"> + <p> + Rune ships one real surface at a time, and each one replaces the code it was built for. The order puts the + three desktops together first, because one wgpu backend covers them. + </p> + </PageHead> + + <section className="doc-section"> + <SectionHead id="milestones" title="Milestones" /> + <ol className="index-list milestones"> + {milestones.map(m => ( + <li key={m.id} id={m.id} className="index-row"> + <span className="index-title"> + <span className="milestone-id">{m.id.toUpperCase().replace("-", ".")}</span> + {m.title} + </span> + <div className="index-text">{m.body}</div> + <span className="index-meta"> + <span className="status" data-status={m.status}> + {STATUS_LABEL[m.status]} + </span> + </span> + </li> + ))} + </ol> + </section> + + <section className="doc-section"> + <SectionHead id="risks" title="Risks" /> + <div className="rules"> + {risks.map(r => ( + <Rule key={r.slug} entry={r} /> + ))} + </div> + </section> + + <Pager prev={["/principles", "Principles"]} /> + </> + ) +} + +export function NotFoundView() { + return ( + <PageHead title="Not found"> + <p> + That page doesn't exist. Go to the <a href={withBase("/")}>overview</a>. + </p> + </PageHead> + ) +} diff --git a/app/vendor/rune/site/src/routes.ts b/app/vendor/rune/site/src/routes.ts new file mode 100644 index 0000000..237cc8c --- /dev/null +++ b/app/vendor/rune/site/src/routes.ts @@ -0,0 +1,57 @@ +export type Route = { path: string; label: string; title: string; description: string } + +export const REPO = "https://github.com/anomalyco/rune" + +export const routes: Route[] = [ + { + path: "/", + label: "Overview", + title: "Rune · Rust UI framework", + description: + "Rune is a Rust UI framework with its own GPU renderer, text, layout, spring animation and thin per-platform shells, written and checked by agents.", + }, + { + path: "/how-it-works", + label: "How it works", + title: "How it works · Rune", + description: + "How a Rune frame runs, from input and state through Taffy layout and springs to wgpu, with real code, the thread model, headless tests and the crate map.", + }, + { + path: "/launch-fast", + label: "Launch fast", + title: "Launch fast · Rune", + description: + "How to get a Rune app's first window on screen in about 300 ms: prewarm_gpu, precompiled Metal shaders, a first frame at creation, deferred setup, a still first second, an idle window that draws nothing, a reused hidden window, and how to measure it.", + }, + { + path: "/fast-apps", + label: "Fast apps", + title: "Fast apps · Rune", + description: + "How to keep a Rune app fast: a free main thread, long lists that build only what is on screen, memo keyed small, an idle window that draws nothing, cheap poll, bounded caches, and a script that audits a repo.", + }, + { + path: "/principles", + label: "Principles", + title: "Principles · Rune", + description: "What Rune optimises for and the rules it holds itself to.", + }, + { + path: "/architecture", + label: "Architecture", + title: "Architecture · Rune", + description: "How Rune is built: the app side, the command channel, the render thread, the renderer and the platform shells.", + }, + { + path: "/roadmap", + label: "Roadmap", + title: "Roadmap · Rune", + description: "Rune's milestones, from the first spikes to OpenCode Desktop, the web and iOS.", + }, +] + +export function normalizePath(path: string): string { + const trimmed = path.replace(/\/index\.html$/, "").replace(/\/+$/, "") + return trimmed === "" ? "/" : trimmed +} diff --git a/app/vendor/rune/site/src/site.css b/app/vendor/rune/site/src/site.css new file mode 100644 index 0000000..7890a05 --- /dev/null +++ b/app/vendor/rune/site/src/site.css @@ -0,0 +1,833 @@ +/* Rune on the Anomaly docs system (system/tokens.css, system/primitives.css): the accent, the wordmark, the home + page, the diagrams and the page parts the system doesn't have yet. */ +:root { + /* Rune's accent replaces the system's red ink; everything else is the shared system as is. */ + --ink: oklch(0.74 0.14 245); +} + +.sr-only { + position: absolute; + width: 1px; + height: 1px; + margin: -1px; + padding: 0; + overflow: hidden; + clip-path: inset(50%); + white-space: nowrap; +} + +/* Wordmark, ᚱUNE (src/brand): pixel letters, drawn at whole pixels a cell, 2 in the sidebar and 12 on the home page. */ +.wordmark { + position: relative; + display: block; + width: calc(var(--cells) * 2px); + color: var(--ink); +} +.wordmark svg { + display: block; + width: 100%; + height: 100%; + fill: currentColor; +} +.wordmark-glint { fill: oklch(0.97 0.035 245); } +.wordmark-rune.is-lit { fill: oklch(0.97 0.035 245); } +/* The lockup row stands as tall as the system's, whose search button sets it, so the nav starts on the same line. */ +.brand { + display: flex; + align-items: center; + min-height: 28px; + text-decoration: none; +} + +/* Home */ +.home-hero { + max-width: 40rem; + margin-bottom: var(--space-9); + container-type: inline-size; +} +.masthead { margin: 0; font: inherit; } +/* 12 px a cell, or the most whole pixels a cell that fit a narrow column. */ +.masthead .wordmark { + width: min(calc(var(--cells) * 12px), 100%); + width: min(calc(var(--cells) * 12px), round(down, 100cqw / var(--cells), 1px) * var(--cells)); +} +.home-lede { + margin: var(--space-7) 0 0; + font: var(--text-20); + font-weight: 400; + letter-spacing: var(--track-20); + color: var(--fg-2); + text-wrap: pretty; +} +.home-lede strong { color: var(--fg); font-weight: 400; } +.home-more { + margin: var(--space-4) 0 0; + font: var(--text-16); + color: var(--fg-2); + text-wrap: pretty; +} +@media (max-width: 900px) { + .home-hero { margin-bottom: var(--space-8); } +} + +/* Home: an app's code beside its headless render, and the how-do-I examples. */ +.app-demo { + display: grid; + grid-template-columns: minmax(0, 1fr) auto; + gap: var(--space-5); + align-items: start; + margin-top: var(--space-5); +} +.app-demo .code-block { max-width: none; margin: 0; } +.app-shot { width: var(--shot-w); max-width: 100%; } +.app-shot figcaption code { font: inherit; white-space: nowrap; } +.howto-list { display: grid; grid-template-columns: minmax(0, 1fr); gap: var(--space-8); } +.howto h3 { + margin: 0 0 var(--space-2); + font: var(--text-16); + font-weight: 500; + scroll-margin-top: var(--space-6); +} +.howto > p { + max-width: var(--measure); + margin: 0; + color: var(--fg-2); + text-wrap: pretty; +} +.howto > p code, .home-section .section-intro code { font: var(--mono-12); color: var(--fg); } +.howto-list + .home-more { margin-top: var(--space-7); } +.build-meta { + display: flex; + flex-direction: column; + align-items: flex-end; + gap: var(--space-1); +} +.build-meta a { color: var(--fg-3); text-decoration: none; } +@media (hover: hover) and (pointer: fine) { + .build-meta a:hover { color: var(--fg); } +} +.home-section .index-list + .shots { margin-top: var(--space-7); } +@media (max-width: 1100px) { + .app-demo { grid-template-columns: minmax(0, 1fr); } +} +@media (max-width: 900px) { + .howto h3 { scroll-margin-top: calc(var(--topbar) + var(--space-4)); } + .build-meta { flex-direction: row; align-items: baseline; gap: var(--space-3); } +} +@media (max-width: 760px) { + /* The status and where to see it go under the text, so the title keeps the row. */ + .index-row:has(.build-meta) { grid-template-columns: minmax(0, 1fr); } + .build-meta { grid-row: 3; justify-content: flex-start; } +} + +/* Page sections */ +.home-section + .home-section, +.doc-section + .doc-section, +.doc-section + #choices, +#choices .doc-section + .doc-section { margin-top: var(--space-9); } +.home-section .index-list { margin-bottom: var(--space-7); } + +/* Headless renders, two up; the columns follow each image's aspect so both stand the same height. */ +.shots { + display: grid; + grid-template-columns: 1.19fr 1.56fr; + gap: var(--space-5); + align-items: start; +} +.shot { margin: 0; } +.shot img { + display: block; + width: 100%; + height: auto; + border-radius: var(--radius-2); + outline: 1px solid var(--line); + outline-offset: -1px; +} +.shot figcaption { + margin-top: var(--space-2); + font: var(--mono-12); + color: var(--fg-3); +} + +/* Code, cut from Rune's source and highlighted at build time (scripts/snippets.ts); the token colours are the + system's. */ +.code-block { + max-width: 52rem; + margin: var(--space-5) 0 0; + border-radius: var(--radius-2); + background: var(--surface-1); + box-shadow: inset 0 0 0 1px var(--line); + overflow: hidden; +} +.code-stack { + display: grid; + gap: var(--space-4); + margin-top: var(--space-5); +} +.code-stack .code-block { margin: 0; } +.code-head { + display: flex; + justify-content: space-between; + gap: var(--space-4); + padding: var(--space-2) var(--space-4); + box-shadow: inset 0 -1px var(--line); + font: var(--mono-12); + color: var(--fg-3); +} +.code-head a { + min-width: 0; + overflow-wrap: anywhere; + color: var(--fg-2); + text-decoration: none; +} +.code-lines { color: var(--fg-3); } +.code-lang { flex: none; } +@media (hover: hover) and (pointer: fine) { + .code-head a:hover { color: var(--fg); } +} +.code { + margin: 0; + padding: var(--space-4); + overflow-x: auto; + font: var(--mono-12); + line-height: 20px; + color: var(--fg); + tab-size: 4; +} +.code code { font: inherit; } +.prose-after { margin-top: var(--space-6); } + +/* How-it-works diagrams: boxes on the surface, ink arrows, mono kickers; everything stacks on a phone. */ +.dg { max-width: 52rem; margin: 0; } +.dg figcaption { + max-width: var(--measure); + margin-top: var(--space-4); + font: var(--text-13); + color: var(--fg-3); + text-wrap: pretty; +} +.dg code, .dg figcaption code { font: var(--mono-12); color: var(--fg); white-space: nowrap; } +.dg-kicker { + margin: 0 0 6px; + font: var(--mono-12); + color: var(--fg-3); +} +.dg-box { + padding: var(--space-3) var(--space-4) var(--space-4); + border-radius: var(--radius-2); + background: var(--surface-1); + box-shadow: inset 0 0 0 1px var(--line); +} +.dg-box h3 { + margin: 0 0 var(--space-2); + font: var(--text-14); + font-weight: 500; +} +.dg-box h3 code { font: var(--mono-13); } +.dg-box ul { + display: grid; + gap: var(--space-1); + margin: 0; + padding: 0; + list-style: none; + font: var(--text-13); + color: var(--fg-2); +} +.dg-box li { position: relative; padding-left: var(--space-4); } +.dg-box li::before { + content: ""; + position: absolute; + top: 10px; + left: 0; + width: 6px; + height: 1px; + background: var(--fg-3); +} +.dg-small { padding: var(--space-3) var(--space-4); } +.dg-small h3 { margin-bottom: 2px; font: var(--text-13); font-weight: 500; } +.dg-small p { margin: 0; font: var(--text-13); color: var(--fg-2); text-wrap: pretty; } + +/* A vertical arrow in the gap above an element, centred, head pointing down. */ +.dg-flow > li + li::before, +.dg-layers > li + li::before { + content: ""; + position: absolute; + top: -20px; + left: 50%; + width: 1px; + height: 20px; + background: var(--ink-dim); +} +.dg-flow > li + li::after, +.dg-layers > li + li::after { + content: ""; + position: absolute; + top: -7px; + left: calc(50% - 2.5px); + width: 6px; + height: 6px; + border-right: 1px solid var(--ink); + border-bottom: 1px solid var(--ink); + transform: rotate(45deg); +} + +/* Chain: boxes left to right with arrows between, and a line back for a loop; top to bottom on a phone. */ +.dg-chain { + display: grid; + grid-template-columns: repeat(var(--links), minmax(0, 1fr)); + gap: 20px; + margin: 0; + padding: 0; + list-style: none; +} +.dg-chain > li { position: relative; } +.dg-chain > li + li::before { + content: ""; + position: absolute; + top: 50%; + left: -20px; + width: 20px; + height: 1px; + background: var(--ink-dim); +} +.dg-chain > li + li::after { + content: ""; + position: absolute; + top: calc(50% - 2.5px); + left: -8px; + width: 6px; + height: 6px; + border-top: 1px solid var(--ink); + border-right: 1px solid var(--ink); + transform: rotate(45deg); +} +.dg-chain h3 code { font: var(--mono-13); } +.dg-back { + position: relative; + margin: 0; + padding: var(--space-5) 0 0; + font: var(--mono-12); + color: var(--fg-3); + text-align: center; +} +/* From under the last box, along the bottom and up into the first; the head points up. */ +.dg-back-line { + position: absolute; + top: 0; + left: 10%; + right: 10%; + height: 12px; + border: 1px solid var(--ink-dim); + border-top: 0; + border-radius: 0 0 var(--radius-1) var(--radius-1); +} +.dg-back-line::after { + content: ""; + position: absolute; + top: -1px; + left: -3.5px; + width: 6px; + height: 6px; + border-top: 1px solid var(--ink); + border-left: 1px solid var(--ink); + transform: rotate(45deg); +} +.dg-back-label { position: relative; } + +/* Frame */ +.dg-flow { + display: grid; + gap: 20px; + max-width: 52rem; + margin: 0; + padding: 0; + list-style: none; +} +.dg-flow > li { position: relative; } +.dg-step { + display: grid; + grid-template-columns: 2.5ch 5.5rem minmax(0, 1fr) auto; + align-items: baseline; + gap: 0 var(--space-4); + padding: var(--space-3) var(--space-4); + border-radius: var(--radius-2); + background: var(--surface-1); + box-shadow: inset 0 0 0 1px var(--line); +} +.dg-num { font: var(--mono-12); color: var(--fg-3); font-variant-numeric: tabular-nums; } +.dg-name { font: var(--text-14); font-weight: 500; } +.dg-does { font: var(--text-13); color: var(--fg-2); text-wrap: pretty; } +.dg .dg-at { font: var(--mono-12); color: var(--fg-3); text-align: right; } +.dg-group { + padding: 36px var(--space-3) var(--space-3); + border-radius: calc(var(--radius-2) + 4px); + box-shadow: inset 0 0 0 1px var(--ink-dim); + background: color-mix(in srgb, var(--ink) 4%, transparent); +} +.dg-group-label { + position: absolute; + top: 10px; + left: var(--space-4); + margin: 0; + font: var(--mono-12); + color: var(--ink); +} + +/* Threads */ +.dg-pair { + display: grid; + grid-template-columns: repeat(2, minmax(0, 1fr)); + gap: var(--space-5); +} +.dg-panel { display: flex; flex-direction: column; } +.dg-panel[data-planned] .dg-box { box-shadow: inset 0 0 0 1px var(--line-2); background: none; } +.dg-panel[data-planned] .dg-kicker { color: var(--ink); } +.dg-feeds { + display: grid; + grid-template-columns: repeat(2, minmax(0, 1fr)); + gap: var(--space-3); + margin-top: 20px; +} +.dg-feeds > .dg-box { position: relative; } +/* Up into the main thread: these threads hand it data. */ +.dg-feeds > .dg-box::before { + content: ""; + position: absolute; + top: -20px; + left: 50%; + width: 1px; + height: 20px; + background: var(--ink-dim); +} +.dg-feeds > .dg-box::after { + content: ""; + position: absolute; + top: -19px; + left: calc(50% - 2.5px); + width: 6px; + height: 6px; + border-top: 1px solid var(--ink); + border-left: 1px solid var(--ink); + transform: rotate(45deg); +} +.dg-link { + display: flex; + align-items: center; + gap: var(--space-3); + margin: 0; + padding: 0 var(--space-4); + font: var(--mono-12); + color: var(--fg-3); + text-wrap: balance; +} +.dg-link .dg-arrow { flex: none; height: 56px; } +.dg-arrow { + position: relative; + display: block; + width: 1px; + background: var(--ink-dim); +} +/* Heads at both ends: the channel carries traffic both ways. */ +.dg-link .dg-arrow::before, +.dg-link .dg-arrow::after { + content: ""; + position: absolute; + left: -2.5px; + width: 6px; + height: 6px; + transform: rotate(45deg); +} +.dg-link .dg-arrow::before { top: 1px; border-top: 1px solid var(--ink); border-left: 1px solid var(--ink); } +.dg-link .dg-arrow::after { bottom: 1px; border-right: 1px solid var(--ink); border-bottom: 1px solid var(--ink); } + +/* Crates */ +.dg-crates { + display: grid; + grid-template-columns: minmax(0, 1fr) 13rem; + gap: var(--space-5); + align-items: start; +} +.dg-layers { + display: grid; + gap: 20px; + margin: 0; + padding: 0; + list-style: none; +} +.dg-layer { position: relative; } +.dg-layers > li + li::before { top: -20px; } +.dg-layer-row { display: flex; flex-wrap: wrap; gap: var(--space-2); } +.dg-layer-row > .dg-box { flex: 1 1 14rem; } +.dg-side { + display: grid; + gap: var(--space-2); + padding: var(--space-3); + border-radius: calc(var(--radius-2) + 4px); + box-shadow: inset 0 0 0 1px var(--line); +} +.dg-side .dg-kicker { margin-bottom: 0; } + +/* Tests */ +.dg-test { + display: grid; + grid-template-columns: minmax(0, 1fr) 40px minmax(0, 1fr) 40px minmax(0, 1.25fr); + align-items: center; +} +.dg-test > .dg-arrow { width: auto; height: 1px; } +.dg-test > .dg-arrow::after { + content: ""; + position: absolute; + top: -2.5px; + right: 1px; + width: 6px; + height: 6px; + border-top: 1px solid var(--ink); + border-right: 1px solid var(--ink); + transform: rotate(45deg); +} +.dg-outs { + display: grid; + gap: var(--space-2); + margin: 0; + padding: 0; + list-style: none; +} + +/* Architecture diagram: app side and render thread with the channel between, the shell under both. */ +.arch { margin: 0; } +.arch-grid { + --channel: 176px; + display: grid; + grid-template-columns: minmax(0, 1fr) var(--channel) minmax(0, 1fr); + grid-template-areas: + "app channel render" + "shell shell shell"; + gap: var(--space-5) 0; +} +[data-area="app"] { grid-area: app; } +[data-area="channel"] { grid-area: channel; } +[data-area="render"] { grid-area: render; } +[data-area="shell"] { grid-area: shell; } +.arch-box { + position: relative; + padding: var(--space-4) var(--space-5) var(--space-5); + border-radius: var(--radius-2); + background: var(--surface-1); + box-shadow: inset 0 0 0 1px var(--line); +} +.arch-box h3 { + margin: 0 0 var(--space-3); + font: var(--text-14); + font-weight: 500; +} +.arch-kicker { + margin: 0 0 2px; + font: var(--mono-12); + color: var(--fg-3); +} +.arch-box ul { + display: grid; + gap: var(--space-1); + margin: 0; + padding: 0; + list-style: none; + font: var(--text-13); + color: var(--fg-2); +} +.arch-box li { + position: relative; + padding-left: var(--space-4); +} +.arch-box li::before { + content: ""; + position: absolute; + top: 10px; + left: 0; + width: 6px; + height: 1px; + background: var(--fg-3); +} +.arch-line { + margin: 0; + font: var(--text-13); + color: var(--fg-2); + text-wrap: pretty; +} +.arch-inner { + margin-top: var(--space-4); + padding: var(--space-3) var(--space-4); + border-radius: var(--radius-1); + background: var(--surface-1); + box-shadow: inset 0 0 0 1px var(--line); +} +.arch-inner-title { + margin: 0 0 var(--space-2); + font: var(--text-13); + font-weight: 500; +} + +.arch-channel { + display: flex; + flex-direction: column; + justify-content: center; + gap: var(--space-5); + padding: 0 var(--space-3); + text-align: center; +} +.arch-channel-label { + margin: 0; + font: var(--mono-12); + color: var(--ink); +} +.arch-flow { + display: grid; + gap: var(--space-2); +} +.arch-flow-text { + font: var(--mono-12); + color: var(--fg-3); + text-wrap: balance; +} +/* The line runs edge to edge between the boxes; the head is a chevron drawn from two borders. */ +.arch-arrow { + position: relative; + display: block; + height: 1px; + margin-inline: calc(-1 * var(--space-3)); + background: var(--ink-dim); +} +.arch-arrow::after { + content: ""; + position: absolute; + top: -2.5px; + right: 2px; + width: 6px; + height: 6px; + border-top: 1px solid var(--ink); + border-right: 1px solid var(--ink); + transform: rotate(45deg); +} +.arch-flow[data-dir="back"] .arch-arrow::after { + right: auto; + left: 2px; + transform: rotate(-135deg); +} + +/* The shell lines its two parts up under the boxes above, with a connector from each. */ +.arch-shell { + display: grid; + grid-template-columns: minmax(0, 1fr) var(--channel) minmax(0, 1fr); + padding: 0; +} +.arch-shell > div { padding: var(--space-4) var(--space-5) var(--space-5); } +.arch-shell > div + div { grid-column: 3; } +.arch-shell::before, +.arch-shell::after { + content: ""; + position: absolute; + top: calc(-1 * var(--space-5)); + width: 1px; + height: var(--space-5); + background: var(--line-2); +} +.arch-shell::before { left: calc((100% - var(--channel)) / 4); } +.arch-shell::after { right: calc((100% - var(--channel)) / 4); } + +.arch figcaption { + max-width: var(--measure); + margin-top: var(--space-4); + font: var(--text-13); + color: var(--fg-3); + text-wrap: pretty; +} + +/* Decisions */ +.decisions { + width: 100%; + border-collapse: collapse; + font: var(--text-13); + text-align: left; +} +.decisions th, +.decisions td { + padding: var(--space-3) var(--space-5) var(--space-3) 0; + box-shadow: inset 0 -1px var(--line); + vertical-align: top; + text-wrap: pretty; +} +.decisions th:last-child, +.decisions td:last-child { padding-right: 0; } +.decisions thead th { + padding-top: 0; + padding-bottom: var(--space-2); + font: var(--text-12); + color: var(--fg-3); + white-space: nowrap; +} +.decisions tbody th { + width: 8.5rem; + font-weight: 500; + color: var(--fg); +} +.decisions td { color: var(--fg-2); } +.decisions td:nth-child(2) { width: 22%; color: var(--fg); } +.decisions td.rejected { width: 22%; color: var(--fg-3); } + +/* Roadmap */ +.milestones .index-title { + display: flex; + align-items: baseline; + gap: var(--space-3); +} +.milestone-id { + flex: none; + width: 4ch; + font: var(--mono-13); + color: var(--fg-3); + font-variant-numeric: tabular-nums; +} +.index-text p { margin: 0; } +.index-text code, +.prose li code { font: var(--mono-12); color: var(--fg); } +.milestones .index-row { scroll-margin-top: var(--space-6); } +.rule-text code { font: var(--mono-12); } + +.status { + display: inline-flex; + align-items: center; + gap: 6px; +} +.status::before { + content: ""; + width: 6px; + height: 6px; + border-radius: 50%; + box-shadow: inset 0 0 0 1px var(--fg-3); +} +.status[data-status="done"]::before { background: var(--fg); box-shadow: none; } +.status[data-status="now"] { color: var(--fg); } +.status[data-status="now"]::before { background: var(--ink); box-shadow: none; } +.status[data-status="started"]::before { background: linear-gradient(90deg, var(--fg-2) 50%, transparent 50%); } + +/* Pager and footer */ +.doc-pager { + display: flex; + flex-wrap: wrap; + justify-content: space-between; + gap: var(--space-4); + margin-top: var(--space-9); + padding-top: var(--space-4); + box-shadow: inset 0 1px var(--line); + font: var(--text-13); +} +.doc-pager a { color: var(--fg-2); text-decoration: none; } +@media (hover: hover) and (pointer: fine) { + .doc-pager a:hover { color: var(--fg); } +} +.site-footer { + width: 100%; + max-width: calc(var(--content) + 2 * var(--space-7)); + margin-inline: auto; + padding: 0 var(--space-7) var(--space-7); +} +.copyright { + position: relative; + display: inline-block; + font: var(--text-12); + color: var(--fg-3); +} +.copyright img { + position: absolute; + top: 50%; + left: 50%; + transform: translate(-50%, -50%); + opacity: .7; + pointer-events: none; +} +.copyright p { position: relative; margin: 0; } +.copyright a { color: inherit; } + +@media (max-width: 900px) { + .site-footer { padding: 0 var(--space-4) var(--space-6); } + .home-section + .home-section, + .doc-section + .doc-section, + .doc-section + #choices, + #choices .doc-section + .doc-section { margin-top: var(--space-8); } + .milestones .index-row { scroll-margin-top: calc(var(--topbar) + var(--space-4)); } +} + +/* Narrow: the diagram stacks, the channel turns vertical, the table becomes a list. */ +@media (max-width: 760px) { + .arch-grid { + grid-template-columns: minmax(0, 1fr); + grid-template-areas: "app" "channel" "render" "shell"; + row-gap: 0; + } + .arch-channel { + display: grid; + grid-template-columns: minmax(0, 1fr) auto minmax(0, 1fr); + align-items: center; + gap: 0 var(--space-3); + padding: 0; + } + .arch-channel-label { grid-column: 2; grid-row: 1; } + .arch-flow { + display: flex; + align-items: center; + gap: var(--space-3); + grid-row: 1; + } + .arch-flow[data-dir="fwd"] { grid-column: 1; flex-direction: row-reverse; text-align: right; } + .arch-flow[data-dir="back"] { grid-column: 3; text-align: left; } + .arch-arrow { + flex: none; + width: 1px; + height: 88px; + margin: 0; + } + .arch-arrow::after { top: auto; right: auto; bottom: 2px; left: -2.5px; transform: rotate(135deg); } + .arch-flow[data-dir="back"] .arch-arrow::after { top: 2px; bottom: auto; left: -2.5px; transform: rotate(-45deg); } + .arch-shell { + margin-top: var(--space-5); + grid-template-columns: minmax(0, 1fr); + } + .arch-shell > div + div { grid-column: 1; box-shadow: inset 0 1px var(--line); } + .arch-shell::before { left: 50%; } + .arch-shell::after { display: none; } + + .shots { grid-template-columns: minmax(0, 1fr); } + + .dg-chain { grid-template-columns: minmax(0, 1fr); } + .dg-chain > li + li::before { top: -20px; left: 50%; width: 1px; height: 20px; } + .dg-chain > li + li::after { top: -7px; left: calc(50% - 2.5px); transform: rotate(135deg); } + .dg-back { padding: var(--space-3) 0 0; text-align: left; } + .dg-back-line { display: none; } + + .dg-pair, .dg-crates { grid-template-columns: minmax(0, 1fr); } + .dg-pair { gap: var(--space-6); } + .dg-test { grid-template-columns: minmax(0, 1fr); } + .dg-test > .dg-arrow { justify-self: center; width: 1px; height: 24px; } + .dg-test > .dg-arrow::after { top: auto; right: auto; bottom: 1px; left: -2.5px; transform: rotate(135deg); } +} +@media (max-width: 640px) { + .dg-step { grid-template-columns: 2.5ch minmax(0, 1fr); row-gap: 2px; } + .dg-does, .dg .dg-at { grid-column: 2; text-align: left; } +} +@media (max-width: 640px) { + .decisions thead { display: none; } + .decisions, .decisions tbody, .decisions tr, .decisions th, .decisions td { display: block; width: auto !important; } + .decisions tr { padding: var(--space-3) 0; box-shadow: inset 0 -1px var(--line); } + .decisions th, .decisions td { padding: 0; box-shadow: none; } + .decisions tbody th { margin-bottom: var(--space-1); } + .decisions td + td { margin-top: var(--space-1); } + .decisions td[data-label]::before { + content: attr(data-label) " "; + color: var(--fg-3); + } +} + +/* The system's frame lets its two rows share spare height under 900 px, which drops a short page to the middle of the + screen; the top bar keeps its own height and the page takes the rest. */ +@media (max-width: 900px) { + .frame { grid-template-rows: auto minmax(0, 1fr); } +} diff --git a/app/vendor/rune/site/src/snippets.d.ts b/app/vendor/rune/site/src/snippets.d.ts new file mode 100644 index 0000000..56691a6 --- /dev/null +++ b/app/vendor/rune/site/src/snippets.d.ts @@ -0,0 +1,5 @@ +declare module "virtual:snippets" { + import type { Snippet } from "../scripts/snippets" + const snippets: Record<string, Snippet> + export default snippets +} diff --git a/app/vendor/rune/site/src/system/Frame.tsx b/app/vendor/rune/site/src/system/Frame.tsx new file mode 100644 index 0000000..4c48d03 --- /dev/null +++ b/app/vendor/rune/site/src/system/Frame.tsx @@ -0,0 +1,355 @@ +import { useEffect, useLayoutEffect, useRef, useState, useSyncExternalStore, type ReactNode } from "react" +import { useScrollSpy } from "./useScrollSpy" +import "./primitives.css" + +export type NavItem = { + href: string + label: string + /** Mono counter shown before the label, e.g. a rule number. */ + num?: string + /** Element id on this page that marks the item current while it is in view. */ + spy?: string + /** The page this item opens is the one being shown. */ + current?: boolean + children?: NavItem[] + /** A quiet label above a run of children, e.g. a guide's section. */ + heading?: boolean +} + +export type NavGroup = { label: string; items: NavItem[] } + +function spyIds(items: NavItem[]): string[] { + return items.flatMap(item => [...(item.spy ? [item.spy] : []), ...spyIds(item.children ?? [])]) +} + +/** Top-level items follow the one active section; children (a guide's rules) light up for everything in view. */ +function NavLinks({ items, active, inView, depth }: { items: NavItem[]; active: string | null; inView: string[]; depth: number }) { + const here = depth === 0 ? active : (inView[0] ?? null) + return ( + <ul className="nav-list" data-depth={depth}> + {items.map(item => + item.heading ? ( + <li key={item.href} className="nav-heading"> + <a href={item.href}>{item.label}</a> + </li> + ) : ( + <li key={item.href}> + <a + href={item.href} + className="nav-link" + data-parent={(item.children && item.children.length > 0) || undefined} + data-active={(item.spy ? (depth === 0 ? item.spy === active : inView.includes(item.spy)) : item.current) || undefined} + aria-current={item.current && !item.children ? "page" : item.spy && item.spy === here ? "location" : undefined} + > + {item.num && <span className="nav-num">{item.num}</span>} + <span className="nav-label">{item.label}</span> + </a> + {item.children && item.children.length > 0 && ( + <NavLinks items={item.children} active={active} inView={inView} depth={depth + 1} /> + )} + </li> + ), + )} + </ul> + ) +} + +/** One edge of the rail mark on a critically damped spring: position, velocity, and where it's headed. */ +type Edge = { x: number; v: number; target: number } +type RailMotion = { top: Edge; bottom: Edge; x: number; shown: boolean; frame: number; last: number } +const still = (): Edge => ({ x: 0, v: 0, target: 0 }) +/** .35 s, bounce 0. */ +const RAIL_OMEGA = (2 * Math.PI) / 0.35 +const RAIL_INSET = 2 +const grid = (v: number) => Math.round(v * 64) / 64 + +/** Advance an edge by dt seconds with the exact critically damped solution, so retargets keep their velocity. + * Returns whether it's still moving. */ +function step(s: Edge, dt: number): boolean { + const d = s.x - s.target + const c = s.v + RAIL_OMEGA * d + const e = Math.exp(-RAIL_OMEGA * dt) + s.x = s.target + (d + c * dt) * e + s.v = (s.v - RAIL_OMEGA * c * dt) * e + if (Math.abs(s.x - s.target) < 0.05 && Math.abs(s.v) < 1) { + s.x = s.target + s.v = 0 + return false + } + return true +} + +const noSubscribe = () => () => {} +/** "⌘" on Apple platforms, "Ctrl " elsewhere; "⌘" on the server and during hydration. */ +function useModKey(): string { + return useSyncExternalStore( + noSubscribe, + () => (/Mac|iPhone|iPad/.test(navigator.platform) ? "⌘" : "Ctrl "), + () => "⌘", + ) +} + +/** The persistent sidebar: brand, then groups of links. A current top-level item sits on a pill; a current child + * (a rule in view, a problem being read) lights its stretch of the guide line, and that mark travels as you scroll. + * The list fades at whichever edge has links scrolled under it. Under 900 px it folds into a top bar. */ +function Sidebar({ + brand, + groups, + revealBrandAfter, + onSearch, +}: { + brand: ReactNode + groups: NavGroup[] + revealBrandAfter?: string + onSearch?: () => void +}) { + const mod = useModKey() + const ids = groups.flatMap(g => spyIds(g.items)) + const { active, inView } = useScrollSpy(ids) + const [open, setOpen] = useState(false) + const [brandShown, setBrandShown] = useState(!revealBrandAfter) + + useEffect(() => { + const hero = revealBrandAfter && document.getElementById(revealBrandAfter) + if (!hero) return setBrandShown(true) + const observer = new IntersectionObserver(([entry]) => setBrandShown(!entry!.isIntersecting)) + observer.observe(hero) + return () => observer.disconnect() + }, [revealBrandAfter]) + const scroller = useRef<HTMLDivElement>(null) + const pill = useRef<HTMLSpanElement>(null) + const rail = useRef<HTMLSpanElement>(null) + + const fade = () => { + const el = scroller.current + if (!el) return + const below = el.scrollHeight - el.clientHeight - el.scrollTop + el.style.setProperty("--fade-top", String(Math.min(1, el.scrollTop / 15))) + el.style.setProperty("--fade-bottom", String(Math.min(1, Math.max(0, below) / 15))) + } + + const railMotion = useRef<RailMotion>({ top: still(), bottom: still(), x: 0, shown: false, frame: 0, last: 0 }) + useEffect(() => () => cancelAnimationFrame(railMotion.current.frame), []) + + useLayoutEffect(() => { + const el = scroller.current + const pillEl = pill.current + const railEl = rail.current + if (!el || !pillEl || !railEl) return + const m = railMotion.current + + const paint = () => { + const top = grid(m.top.x) + railEl.style.transform = `translate(${m.x}px, ${top}px)` + railEl.style.height = `${Math.max(0, grid(m.bottom.x) - top)}px` + } + const tick = (now: number) => { + const dt = m.last ? Math.min((now - m.last) / 1000, 1 / 20) : 1 / 60 + m.last = now + const moving = [m.top, m.bottom].map(s => step(s, dt)).some(Boolean) + paint() + m.frame = moving ? requestAnimationFrame(tick) : 0 + } + const showRail = (x: number, top: number, bottom: number) => { + m.x = x + m.top.target = top + m.bottom.target = bottom + // First paint and reduced motion place the mark directly; otherwise the spring carries it, velocity and all. + if (!m.shown || matchMedia("(prefers-reduced-motion: reduce)").matches) { + cancelAnimationFrame(m.frame) + m.frame = 0 + m.top = { x: top, v: 0, target: top } + m.bottom = { x: bottom, v: 0, target: bottom } + paint() + } else if (!m.frame) { + m.last = 0 + m.frame = requestAnimationFrame(tick) + } + m.shown = true + // Fade back in after hiding, but not on the page's first paint. + if (!railEl.dataset.placed) { + railEl.style.transition = "none" + railEl.style.opacity = "1" + void railEl.offsetHeight + railEl.style.transition = "" + railEl.dataset.placed = "" + } + railEl.style.opacity = "1" + } + const hideRail = () => { + m.shown = false + railEl.style.opacity = "0" + } + const showPill = (link: HTMLElement, top: number) => { + const first = !pillEl.dataset.placed + if (first) pillEl.style.transition = "none" + pillEl.style.transform = `translateY(${top}px)` + pillEl.style.height = `${link.offsetHeight}px` + if (first) { + void pillEl.offsetHeight + pillEl.style.transition = "" + pillEl.dataset.placed = "" + } + pillEl.style.opacity = "1" + } + const hidePill = () => { + pillEl.style.opacity = "0" + delete pillEl.dataset.placed + } + + const place = () => { + const box = el.getBoundingClientRect() + const offset = el.scrollTop - box.top + const leaves = [...el.querySelectorAll<HTMLElement>(".nav-link[data-active]:not([data-parent])")] + // The deepest current leaves win: the rules in view, not the guide that holds them. + const nested = leaves.filter(link => link.closest(".nav-list")?.getAttribute("data-depth") !== "0") + let span: [number, number] | null = null + if (nested.length > 0) { + hidePill() + const list = nested[0]!.closest<HTMLElement>(".nav-list")! + const top = nested[0]!.getBoundingClientRect().top + offset + const bottom = nested.at(-1)!.getBoundingClientRect().bottom + offset + // A 2 px bar centred on the 1 px guide line, running alongside the labels' text. + showRail(list.getBoundingClientRect().left - box.left - 0.5, top + RAIL_INSET, bottom - RAIL_INSET) + span = [top, bottom] + } else if (leaves.length > 0) { + hideRail() + const link = leaves.at(-1)! + const top = link.getBoundingClientRect().top + offset + showPill(link, top) + span = [top, top + link.offsetHeight] + } else { + hideRail() + hidePill() + } + // Keep the current items inside the list's viewport, without animating the list; the first wins if they don't fit. + if (span) { + const [top, bottom] = span + if (top - el.scrollTop < 24 || bottom - top > el.clientHeight - 48) el.scrollTop = top - 24 + else if (bottom - el.scrollTop > el.clientHeight - 24) el.scrollTop = bottom - el.clientHeight + 24 + } + fade() + } + place() + const observer = new ResizeObserver(place) + observer.observe(el) + return () => observer.disconnect() + }, [active, inView]) + + useEffect(() => { + if (!open) return + const onKey = (e: KeyboardEvent) => e.key === "Escape" && setOpen(false) + document.addEventListener("keydown", onKey) + return () => document.removeEventListener("keydown", onKey) + }, [open]) + + return ( + <aside className="sidebar" data-open={open || undefined}> + <div className="sidebar-scrim" aria-hidden="true" onClick={() => setOpen(false)} /> + <div className="sidebar-brand" data-brand-hidden={!brandShown || undefined}> + <div className="sidebar-lockup" inert={!brandShown}> + {brand} + </div> + <div className="sidebar-actions"> + {onSearch && ( + <button + type="button" + className="sidebar-search" + aria-label="Search" + aria-keyshortcuts="Meta+K Control+K /" + title={`Search (${mod}K)`} + onClick={() => { + setOpen(false) + onSearch() + }} + > + <svg className="sidebar-search-icon" width="16" height="16" viewBox="0 0 16 16" aria-hidden="true"> + <circle cx="7" cy="7" r="4.75" fill="none" stroke="currentColor" strokeWidth="1.5" /> + <path d="M10.5 10.5 14 14" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" /> + </svg> + <span className="sidebar-search-label">Search</span> + </button> + )} + <button + type="button" + className="sidebar-toggle" + aria-expanded={open} + aria-controls="sidebar-nav" + onClick={() => setOpen(o => !o)} + > + {open ? "Close" : "Menu"} + </button> + </div> + </div> + <div + ref={scroller} + id="sidebar-nav" + className="sidebar-scroll" + onScroll={fade} + onClick={e => (e.target as HTMLElement).closest("a") && setOpen(false)} + > + <span ref={pill} className="nav-pill" aria-hidden="true" /> + <span ref={rail} className="nav-rail" aria-hidden="true" /> + {groups.map(group => ( + <nav key={group.label} className="nav-group" aria-label={group.label}> + <p className="nav-group-label">{group.label}</p> + <NavLinks items={group.items} active={active} inView={inView} depth={0} /> + </nav> + ))} + </div> + </aside> + ) +} + +/** Page frame: sidebar on the left, a wide main column on the right, footer at the end of main. */ +export function Frame({ + brand, + groups, + revealBrandAfter, + onSearch, + footer, + children, +}: { + brand: ReactNode + groups: NavGroup[] + /** Shows a search button in the sidebar's top row. */ + onSearch?: () => void + /** Id of a hero that already shows the brand: the sidebar's lockup fades in once it scrolls away. */ + revealBrandAfter?: string + footer?: ReactNode + children: ReactNode +}) { + return ( + <div className="frame"> + <Sidebar brand={brand} groups={groups} revealBrandAfter={revealBrandAfter} onSearch={onSearch} /> + <div className="frame-main"> + <main className="frame-content">{children}</main> + {footer} + </div> + </div> + ) +} + +/** Eyebrow, title and lede at the top of a page. */ +export function PageHead({ eyebrow, title, children }: { eyebrow?: ReactNode; title: ReactNode; children?: ReactNode }) { + return ( + <header className="page-head"> + {eyebrow && <p className="eyebrow">{eyebrow}</p>} + <h1 className="page-title">{title}</h1> + {children && <div className="page-lede">{children}</div>} + </header> + ) +} + +/** A section's heading on a hairline, with an optional count or note on the right. */ +export function SectionHead({ id, title, aside, children }: { id?: string; title: ReactNode; aside?: ReactNode; children?: ReactNode }) { + return ( + <header className="section-head"> + <div className="section-head-row"> + <h2 id={id}>{title}</h2> + {aside && <span className="section-aside">{aside}</span>} + </div> + {children && <div className="section-intro">{children}</div>} + </header> + ) +} diff --git a/app/vendor/rune/site/src/system/primitives.css b/app/vendor/rune/site/src/system/primitives.css new file mode 100644 index 0000000..273d332 --- /dev/null +++ b/app/vendor/rune/site/src/system/primitives.css @@ -0,0 +1,753 @@ +/* Anomaly docs primitives: frame, sidebar nav, page head, section head, rule row, bench (specimen), prose, button. + Built only from tokens.css. */ + +/* Base */ +* { box-sizing: border-box; } +html { + background: var(--bg); + color-scheme: dark; + -webkit-font-smoothing: antialiased; + -webkit-text-size-adjust: 100%; + text-size-adjust: 100%; +} +body { + margin: 0; + background: var(--bg); + color: var(--fg); + font: var(--text-14); + font-feature-settings: "ss01" 0; +} +code, pre, kbd { font-family: var(--font-mono); } +::selection { background: var(--fg); color: var(--bg); } +a { + color: inherit; + text-decoration: underline var(--line-2); + text-decoration-thickness: 1px; + text-underline-offset: 3px; +} +@media (hover: hover) and (pointer: fine) { + a:hover { text-decoration-color: var(--fg); } +} +:focus-visible { outline: 1px solid var(--fg); outline-offset: 2px; } + +/* Frame: a fixed-width sidebar and a main column that takes the rest. */ +.frame { + display: grid; + grid-template-columns: var(--sidebar) minmax(0, 1fr); + min-height: 100vh; +} +.frame-main { + display: flex; + flex-direction: column; + min-width: 0; +} +/* The column centres in the space right of the sidebar once the window is wider than it. */ +.frame-content { + flex: 1; + width: 100%; + max-width: calc(var(--content) + 2 * var(--space-7)); + margin-inline: auto; + padding: var(--space-8) var(--space-7) var(--space-9); +} + +/* Sidebar */ +.sidebar { + position: sticky; + top: 0; + display: grid; + grid-template-rows: auto minmax(0, 1fr); + height: 100vh; + box-shadow: inset -1px 0 var(--line); +} +.sidebar-brand { + display: flex; + align-items: center; + justify-content: space-between; + gap: var(--space-3); + /* The lockup's left edge sits on the nav text, past the pill's bleed. */ + padding: var(--space-5) var(--space-5) var(--space-4) calc(var(--space-3) + var(--space-2)); +} +.sidebar-lockup { transition: opacity .2s var(--ease-out); } +.sidebar-brand[data-brand-hidden] .sidebar-lockup { opacity: 0; transition-timing-function: var(--ease-in); } +.sidebar-toggle, +.sidebar-scrim, +.sidebar-search-label { + display: none; +} +.sidebar-actions { + display: flex; + align-items: center; +} +/* Search: an icon beside the lockup whose hover box ends on the nav pill's right edge. */ +.sidebar-search { + display: grid; + place-items: center; + width: 28px; + height: 28px; + margin-right: calc(var(--space-3) - var(--space-5)); + padding: 0; + border: 0; + border-radius: var(--radius-1); + background: none; + color: var(--fg-3); + cursor: pointer; +} +@media (hover: hover) and (pointer: fine) { + .sidebar-search:hover { background: var(--surface-2); color: var(--fg); } +} +.sidebar-scroll { + position: relative; + min-height: 0; + padding: var(--space-2) var(--space-3) var(--space-7); + overflow-y: auto; + overscroll-behavior: contain; + scrollbar-width: none; + --edge: linear-gradient(to bottom, rgb(0 0 0 / calc(1 - var(--fade-top, 0))), #000 32px, #000 calc(100% - 32px), rgb(0 0 0 / calc(1 - var(--fade-bottom, 0)))); + -webkit-mask-image: var(--edge); + mask-image: var(--edge); +} +.sidebar-scroll::-webkit-scrollbar { display: none; } + +/* Nav: groups of links; the current one sits on a pill that travels. Text sits on the brand's edge, the pill bleeds. */ +.nav-group + .nav-group { margin-top: var(--space-5); } +.nav-group-label { + margin: 0 0 var(--space-1); + padding: 0 var(--space-2); + font: var(--text-12); + font-weight: 500; + color: var(--fg-3); +} +.nav-list { + margin: 0; + padding: 0; + list-style: none; +} +.nav-link { + position: relative; + z-index: 1; + display: flex; + gap: var(--space-2); + padding: 4px var(--space-2); + border-radius: var(--radius-1); + font: var(--text-13); + color: var(--fg-2); + text-decoration: none; + text-wrap: pretty; +} +.nav-link[data-active] { color: var(--fg); } +.nav-link[data-parent][data-active] { font-weight: 500; } +@media (hover: hover) and (pointer: fine) { + .nav-link:hover { color: var(--fg); } +} +.nav-link:focus-visible { outline-offset: -1px; } +.nav-num { + flex: none; + width: 2ch; + font: var(--mono-12); + line-height: inherit; + color: var(--fg-3); + font-variant-numeric: tabular-nums; +} +.nav-link[data-active] .nav-num { color: var(--ink); } + +/* Children hang off a thin guide line under their parent's text: one line each, smaller, with quiet group headers. + A label too long for the column fades out at its end rather than wrapping. */ +.nav-list[data-depth="1"] { + margin: 2px 0 var(--space-3) var(--space-2); + box-shadow: inset 1px 0 var(--line); +} +.nav-list[data-depth="1"] .nav-link { + padding: 2px var(--space-2) 2px var(--space-3); + border-radius: 0; + font: var(--text-12); + line-height: 16px; + white-space: nowrap; +} +.nav-list[data-depth="1"] .nav-label { + flex: 1; + min-width: 0; + overflow: hidden; + -webkit-mask-image: linear-gradient(to right, #000 calc(100% - 1.5em), transparent); + mask-image: linear-gradient(to right, #000 calc(100% - 1.5em), transparent); +} +.nav-heading { + margin: var(--space-3) 0 2px; + padding: 0 var(--space-2) 0 var(--space-3); + line-height: 16px; +} +.nav-heading:first-child { margin-top: var(--space-1); } +.nav-heading a { + font: var(--text-11); + letter-spacing: .02em; + color: var(--fg-3); + text-decoration: none; +} +@media (hover: hover) and (pointer: fine) { + .nav-heading a:hover { color: var(--fg-2); } +} +.nav-pill, +.nav-rail { + position: absolute; + top: 0; + left: 0; + opacity: 0; + pointer-events: none; +} +.nav-pill { + left: var(--space-3); + right: var(--space-3); + border-radius: var(--radius-1); + background: var(--surface-2); + transition: transform .25s var(--ease-out), height .25s var(--ease-out), opacity .15s; +} +/* The stretch of guide line beside every rule in view. A spring in Frame.tsx moves it; CSS only fades it. */ +.nav-rail { + z-index: 2; + width: 2px; + border-radius: 1px; + background: var(--fg-3); + transition: opacity .15s; +} +.nav-list[data-depth="1"] :is(.nav-link, .nav-num) { transition: color .2s; } +.nav-list[data-depth="1"] .nav-link[data-active] .nav-num { color: var(--fg-2); } +@media (hover: hover) and (pointer: fine) { + .nav-list[data-depth="1"] .nav-link:hover { transition-duration: 0s; } +} +@media (prefers-reduced-motion: reduce) { + .nav-pill { transition: opacity .15s; } +} + +/* Page head */ +.page-head { + max-width: var(--measure); + margin-bottom: var(--space-8); +} +.eyebrow { + display: flex; + flex-wrap: wrap; + gap: var(--space-1) var(--space-3); + margin: 0 0 var(--space-3); + font: var(--mono-12); + color: var(--fg-3); +} +.page-title { + margin: 0; + font: var(--text-28); + letter-spacing: var(--track-28); + text-wrap: balance; +} +.page-lede { + margin-top: var(--space-4); + font: var(--text-16); + color: var(--fg-2); + text-wrap: pretty; +} +.page-lede p { margin: 0 0 var(--space-3); } +.page-lede p:last-child { margin-bottom: 0; } + +/* Section head: a hairline, the heading, an aside on the same line. */ +.section-head { + padding-top: var(--space-5); + box-shadow: inset 0 1px var(--line); + margin-bottom: var(--space-7); +} +.section-head-row { + display: flex; + align-items: baseline; + justify-content: space-between; + gap: var(--space-4); +} +.section-head h2 { + margin: 0; + font: var(--text-20); + letter-spacing: var(--track-20); + scroll-margin-top: var(--space-7); +} +.section-aside { + font: var(--mono-12); + color: var(--fg-3); +} +.section-intro { + max-width: var(--measure); + margin-top: var(--space-2); + font: var(--text-14); + color: var(--fg-2); +} +.section-intro p { margin: 0; } +.section-intro code { font: var(--mono-12); color: var(--fg); } + +/* Rule row: number and title, then text beside a spec list, then the bench across the full width. */ +.rule { scroll-margin-top: var(--space-6); } +.rule + .rule { margin-top: var(--space-8); } +.rule-head { + display: flex; + align-items: baseline; + gap: var(--space-3); + margin: 0 0 var(--space-2); +} +.rule-num { + flex: none; + font: var(--mono-13); + color: var(--ink); + text-decoration: none; + font-variant-numeric: tabular-nums; +} +.rule-title { + margin: 0; + font: var(--text-16); + font-weight: 500; + text-wrap: balance; +} +.rule-title code { font-family: var(--font-mono); font-size: .875em; } +/* Quiet marker for a rule nobody has approved yet. */ +.rule-tag { + flex: none; + padding: 0 5px; + border: 1px solid var(--line); + border-radius: var(--radius-1); + font: var(--mono-12); + line-height: 18px; + color: var(--fg-3); +} +.rule-body { + display: grid; + grid-template-columns: minmax(0, var(--measure)) minmax(240px, 1fr); + gap: var(--space-3) var(--space-7); + align-items: start; +} +.rule-text { + color: var(--fg-2); + text-wrap: pretty; +} +.rule-text p { margin: 0 0 var(--space-2); } +.rule-text code { font: var(--mono-13); color: var(--fg); } +.rule-text :not(pre) > code { white-space: nowrap; } +.rule-text p:last-child { margin-bottom: 0; } +.rule-text pre { + margin: var(--space-3) 0; + padding: var(--space-3) var(--space-4); + border-radius: var(--radius-2); + background: var(--surface-1); + box-shadow: inset 0 0 0 1px var(--line); + overflow-x: auto; +} +.rule-text pre code { font: var(--mono-12); line-height: 20px; } +.rule-spec { + display: grid; + gap: var(--space-2); + margin: 0; + padding-top: 3px; +} +.rule-spec > div { + display: grid; + grid-template-columns: 56px minmax(0, 1fr); + gap: var(--space-3); +} +.rule-spec dt { + font: var(--text-12); + line-height: 18px; + color: var(--fg-3); +} +.rule-spec dd { + margin: 0; + font: var(--text-13); + color: var(--fg-2); +} +.rule-spec dd.mono { + font: var(--mono-12); + line-height: 18px; + color: var(--fg); +} +.rule-spec dd.mono code { font: inherit; } +.rule-spec dd.mono > span { display: block; } + +/* References: a file in one of our repos (crate, then file, then a note), a principle, or plain text. + Crates sit in one column so the files line up. */ +.refs { + display: grid; + grid-template-columns: max-content minmax(0, 1fr); + gap: 2px var(--space-3); + margin: 0; + padding: 0; + list-style: none; + font: var(--mono-12); + line-height: 18px; +} +.refs > li, +.ref-link { + display: grid; + grid-column: 1 / -1; + grid-template-columns: subgrid; +} +.ref-link { color: inherit; text-decoration: none; } +.ref-label { color: var(--fg-2); } +.ref-name { color: var(--fg); overflow-wrap: anywhere; } +.ref-name + .ref-note { margin-left: var(--space-2); } +.ref-note { color: var(--fg-3); } +.ref-note code { font: inherit; } +.ref-principle { font: var(--text-13); line-height: 18px; } +.refs > .ref-text { + display: block; + font: var(--text-13); + line-height: 18px; + color: var(--fg-2); +} +.ref-text code { font: var(--mono-12); color: var(--fg); } +a.ref-link .ref-name { + text-decoration: underline; + text-decoration-color: transparent; + text-underline-offset: 3px; + transition: text-decoration-color .15s; +} +@media (hover: hover) and (pointer: fine) { + a.ref-link:hover .ref-name { text-decoration-color: var(--line-2); } +} + +/* Code, highlighted at build time: keywords in soft red, strings sand, macros and attributes steel, the rest + neutral with dim punctuation. */ +.tk-k { color: var(--code-keyword); } +.tk-s, .tk-n { color: var(--code-string); } +.tk-f, .tk-a { color: var(--code-call); } +.tk-c { color: var(--fg-3); } +.tk-p { color: var(--fg-2); } +.rule-benches { + display: grid; + gap: var(--space-4); + margin-top: var(--space-5); +} + +/* Bench: bad and good side by side, each live, controls for both along the bottom. */ +.bench { + margin: 0; + border-radius: var(--radius-2); + background: var(--surface-1); + box-shadow: inset 0 0 0 1px var(--line); + font: var(--text-13); +} +.bench-sides { + display: grid; + grid-template-columns: repeat(2, minmax(0, 1fr)); +} +.bench-side { + display: grid; + grid-row: span 3; + grid-template-rows: subgrid; + min-width: 0; + padding: var(--space-4) var(--space-5) var(--space-4); +} +.bench-side + .bench-side { box-shadow: inset 1px 0 var(--line); } +.bench-label { + display: flex; + align-items: center; + gap: var(--space-2); + margin: 0 0 var(--space-4); + font: var(--text-12); + font-weight: 500; + color: var(--fg); +} +.bench-label::before { + content: ""; + width: 6px; + height: 6px; + border-radius: 50%; + background: var(--fg); +} +.bench-side[data-kind="bad"] .bench-label { color: var(--ink); } +.bench-side[data-kind="bad"] .bench-label::before { background: var(--ink); } +.bench-note { + margin: var(--space-4) 0 0; + font: var(--text-12); + color: var(--fg-3); + text-wrap: pretty; +} +.bench-note::first-letter { text-transform: uppercase; } +.bench-controls { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: var(--space-2); + padding: var(--space-3) var(--space-5); + box-shadow: inset 0 1px var(--line); +} + +/* Button: the one control shape. */ +.button { + height: 28px; + padding: 0 var(--space-3); + border: 0; + border-radius: var(--radius-1); + background: var(--surface-2); + box-shadow: inset 0 0 0 1px var(--line); + color: var(--fg); + font: var(--text-13); + font-weight: 500; + cursor: pointer; + transition: background-color 100ms ease-out; +} +.button::first-letter { text-transform: uppercase; } +@media (hover: hover) and (pointer: fine) { + .button:hover:not(:disabled) { background: var(--surface-3); transition-duration: 0ms; } +} +.button:disabled { opacity: .4; cursor: default; } + +/* Prose */ +.prose { max-width: var(--measure); color: var(--fg-2); text-wrap: pretty; } +.prose > :first-child { margin-top: 0; } +.prose h2 { margin: var(--space-7) 0 var(--space-3); font: var(--text-20); letter-spacing: var(--track-20); color: var(--fg); } +.prose h3 { margin: var(--space-6) 0 var(--space-2); font: var(--text-16); font-weight: 500; color: var(--fg); } +.prose p, .prose ul, .prose ol, .prose pre, .prose .table-wrap { margin: 0 0 var(--space-4); } +.prose ul, .prose ol { padding-left: var(--space-5); } +.prose li + li { margin-top: var(--space-1); } +.prose strong { color: var(--fg); font-weight: 500; } +.prose code { padding: 1px 4px; border-radius: 3px; background: var(--surface-2); font: var(--mono-12); color: var(--fg); } +.prose pre { padding: var(--space-4); border-radius: var(--radius-2); background: var(--surface-1); box-shadow: inset 0 0 0 1px var(--line); overflow-x: auto; } +.prose pre code { padding: 0; background: none; } +.prose table { width: 100%; border-collapse: collapse; font: var(--text-13); text-align: left; } +.prose th, .prose td { padding: var(--space-2) var(--space-4) var(--space-2) 0; box-shadow: inset 0 -1px var(--line); vertical-align: top; } +.prose th { font-weight: 500; color: var(--fg-3); white-space: nowrap; } +.table-wrap { width: 100%; overflow-x: auto; } + +/* Under 1100 px of window the rule's spec drops under its text. */ +@media (max-width: 1100px) { + .rule-body { grid-template-columns: minmax(0, var(--measure)); } +} + +/* Under 900 px the sidebar folds into a top bar with a menu. */ +@media (max-width: 900px) { + .frame { grid-template-columns: minmax(0, 1fr); } + .sidebar { + z-index: 10; + height: auto; + grid-template-rows: auto; + box-shadow: none; + } + /* The blur sits on the bar, not the sidebar, so the scrim stays fixed to the viewport. */ + .sidebar-brand { + position: relative; + height: var(--topbar); + padding: 0 var(--space-2) 0 var(--space-4); + background: rgb(0 0 0 / .86); + -webkit-backdrop-filter: blur(16px) saturate(1.4); + backdrop-filter: blur(16px) saturate(1.4); + box-shadow: inset 0 -1px var(--line); + } + .sidebar-scrim { + position: fixed; + inset: var(--topbar) 0 0; + display: block; + background: var(--bg); + opacity: 0; + visibility: hidden; + transition: opacity .11s var(--ease-in), visibility 0s .11s; + } + .sidebar[data-open] .sidebar-scrim { + opacity: 1; + visibility: visible; + transition: opacity .15s var(--ease-out), visibility 0s; + } + .sidebar-search-icon { display: none; } + .sidebar-search-label { display: inline; } + .sidebar-toggle, + .sidebar-search { + display: block; + width: auto; + margin: 0; + height: 36px; + padding: 0 var(--space-3); + border: 0; + border-radius: var(--radius-1); + background: none; + color: var(--fg-2); + font: var(--text-13); + font-weight: 500; + cursor: pointer; + } + .sidebar-scroll { + position: absolute; + top: var(--topbar); + left: 0; + right: 0; + height: calc(100dvh - var(--topbar)); + padding: var(--space-3) var(--space-2) var(--space-6); + opacity: 0; + visibility: hidden; + translate: 0 -4px; + transition: opacity .11s var(--ease-in), translate .11s var(--ease-in), visibility 0s .11s; + } + .sidebar[data-open] .sidebar-scroll { + opacity: 1; + visibility: visible; + translate: 0 0; + transition: opacity .15s var(--ease-out), translate .15s var(--ease-out), visibility 0s; + } + .nav-pill { left: var(--space-2); right: var(--space-2); } + .frame-content { padding: var(--space-7) var(--space-4) var(--space-8); } + .rule, .section-head h2 { scroll-margin-top: calc(var(--topbar) + var(--space-4)); } +} +@media (max-width: 900px) and (prefers-reduced-motion: reduce) { + .sidebar-scroll, .sidebar[data-open] .sidebar-scroll { translate: none; } +} +@media (max-width: 640px) { + .bench-sides { grid-template-columns: minmax(0, 1fr); } + .bench-side { padding: var(--space-4); } + .bench-side + .bench-side { box-shadow: inset 0 1px var(--line); } + .bench-controls { padding: var(--space-3) var(--space-4); } + .rule + .rule { margin-top: var(--space-7); } +} + +/* Index row: title, text and meta on one line at width; the list behind every collection page. */ +.index-list { + display: grid; + margin: 0; + padding: 0; + list-style: none; +} +.index-row { + display: grid; + grid-template-columns: minmax(160px, 15rem) minmax(0, 1fr) auto; + gap: var(--space-1) var(--space-6); + align-items: baseline; + padding: var(--space-3) 0; + box-shadow: inset 0 -1px var(--line); +} +.index-row:first-child { padding-top: 0; } +.index-title { + font: var(--text-14); + font-weight: 500; + color: var(--fg); + text-decoration: none; +} +@media (hover: hover) and (pointer: fine) { + a.index-title:hover { text-decoration: underline var(--line-2); text-underline-offset: 3px; } +} +.index-text { + margin: 0; + max-width: var(--measure); + font: var(--text-14); + color: var(--fg-2); + text-wrap: pretty; +} +.index-meta { + display: flex; + flex-wrap: wrap; + justify-content: flex-end; + gap: var(--space-1) var(--space-3); + font: var(--mono-12); + color: var(--fg-3); + white-space: nowrap; + font-variant-numeric: tabular-nums; +} +.index-meta a { color: inherit; } +@media (max-width: 760px) { + .index-row { grid-template-columns: minmax(0, 1fr) auto; } + .index-text { grid-column: 1 / -1; grid-row: 2; } +} + +/* Command menu: a search field over a list of one fixed height, centred near the top. Opens on the next frame; the + close fade is the component's. The selected row moves with no transition. */ +.cmdk { + position: fixed; + inset: 0; + z-index: 50; +} +.cmdk[inert] { pointer-events: none; } +.cmdk-scrim { + position: absolute; + inset: 0; + background: rgb(0 0 0 / .6); +} +.cmdk-panel { + position: relative; + width: min(560px, calc(100% - 2 * var(--space-2))); + margin: max(var(--space-4), 12vh) auto 0; + overflow: hidden; + border-radius: var(--radius-2); + background: color-mix(in srgb, var(--fg) 4%, var(--bg)); + box-shadow: inset 0 0 0 1px var(--line-2), 0 1px 2px rgb(0 0 0 / .5), 0 24px 64px rgb(0 0 0 / .6); +} +/* On a phone the keyboard takes the bottom half, so the panel sits at the top. */ +@media (max-width: 900px) { + .cmdk-panel { margin-top: var(--space-2); } +} +.cmdk-input { + display: block; + width: 100%; + height: 48px; + padding: 0 var(--space-4); + border: 0; + border-radius: 0; + background: none; + box-shadow: inset 0 -1px var(--line); + color: var(--fg); + font: var(--text-16); + outline: none; +} +.cmdk-input::placeholder { color: var(--fg-3); } +.cmdk-list { + position: relative; + height: min(344px, 52dvh); + padding: var(--space-1); + overflow-y: auto; + overscroll-behavior: contain; + scroll-padding-block: var(--space-5); + scrollbar-width: none; + --edge: linear-gradient(to bottom, rgb(0 0 0 / calc(1 - var(--fade-top, 0))), #000 24px, #000 calc(100% - 24px), rgb(0 0 0 / calc(1 - var(--fade-bottom, 0)))); + -webkit-mask-image: var(--edge); + mask-image: var(--edge); +} +.cmdk-list::-webkit-scrollbar { display: none; } +.cmdk-option { + display: flex; + align-items: center; + gap: var(--space-3); + height: 36px; + padding: 0 var(--space-3); + border-radius: var(--radius-1); + color: var(--fg-2); + font: var(--text-14); + cursor: pointer; + user-select: none; +} +.cmdk-option[aria-selected="true"] { background: var(--surface-2); } +.cmdk-title { + flex: 1; + min-width: 0; + overflow: hidden; + white-space: nowrap; + -webkit-mask-image: linear-gradient(to left, transparent, #000 24px); + mask-image: linear-gradient(to left, transparent, #000 24px); +} +.cmdk-title mark { + background: none; + color: var(--fg); +} +.cmdk-context { + margin-left: var(--space-2); + font: var(--text-13); + color: var(--fg-3); +} +.cmdk-tag { + margin-left: var(--space-2); + font: var(--mono-12); + color: var(--fg-3); +} +.cmdk-kind { + flex: none; + font: var(--mono-12); + color: var(--fg-3); +} +.cmdk-empty { + margin: 0; + padding: var(--space-2) var(--space-3); + font: var(--text-14); + color: var(--fg-3); +} +.cmdk-status { + position: absolute; + width: 1px; + height: 1px; + margin: -1px; + overflow: hidden; + clip-path: inset(50%); + white-space: nowrap; +} diff --git a/app/vendor/rune/site/src/system/tokens.css b/app/vendor/rune/site/src/system/tokens.css new file mode 100644 index 0000000..ce35ce2 --- /dev/null +++ b/app/vendor/rune/site/src/system/tokens.css @@ -0,0 +1,64 @@ +/* Anomaly docs tokens. Dark only. One sans for interface and prose, one mono for values, code and numbers. + Copied from @anomalyco/site. */ +@font-face { font-family: "Geist"; src: url("/fonts/geist.woff2") format("woff2"); font-weight: 100 900; font-display: swap; } +@font-face { font-family: "Geist Mono"; src: url("/fonts/geist-mono.woff2") format("woff2"); font-weight: 100 900; font-display: swap; } + +:root { + --font-sans: "Geist", ui-sans-serif, system-ui, -apple-system, "Segoe UI", sans-serif; + --font-mono: "Geist Mono", ui-monospace, "SF Mono", Menlo, monospace; + + /* Type: seven sizes (11 only for sidebar section labels), line heights on the 4 px grid. Mono only at 12 and 13, one step under the sans beside it. */ + --text-11: 500 11px/16px var(--font-sans); + --text-12: 400 12px/16px var(--font-sans); + --text-13: 400 13px/20px var(--font-sans); + --text-14: 400 14px/22px var(--font-sans); + --text-16: 400 16px/26px var(--font-sans); + --text-20: 500 20px/28px var(--font-sans); + --text-28: 500 28px/36px var(--font-sans); + --mono-12: 400 12px/16px var(--font-mono); + --mono-13: 400 13px/20px var(--font-mono); + --track-20: -.01em; + --track-28: -.02em; + + /* Space: a 4 px base. Tight inside a group, loose between groups. */ + --space-1: 4px; + --space-2: 8px; + --space-3: 12px; + --space-4: 16px; + --space-5: 24px; + --space-6: 32px; + --space-7: 48px; + --space-8: 64px; + --space-9: 96px; + + /* Colour: black, one neutral at four strengths, hairlines as translucent white, red ink as the only accent. */ + --bg: #000; + --fg: #ededed; + --fg-2: rgb(255 255 255 / .62); + --fg-3: rgb(255 255 255 / .4); + --surface-1: rgb(255 255 255 / .03); + --surface-2: rgb(255 255 255 / .06); + --surface-3: rgb(255 255 255 / .1); + --line: rgb(255 255 255 / .09); + --line-2: rgb(255 255 255 / .16); + --ink: #ff2a2a; + --ink-dim: color-mix(in srgb, var(--ink) 55%, transparent); + /* Code: three quiet hues at one lightness, red only for keywords. */ + --code-keyword: oklch(.74 .12 25); + --code-string: oklch(.84 .06 80); + --code-call: oklch(.84 .045 235); + + /* Radius: one family; a control nests inside a bench with 4 px to spare. */ + --radius-1: 4px; + --radius-2: 8px; + + /* Frame */ + --sidebar: 264px; + --content: 1120px; + --measure: 36rem; + --topbar: 52px; + + /* Motion (Kit's palette as CSS): enter, exit. */ + --ease-out: cubic-bezier(.2, .8, .2, 1); + --ease-in: cubic-bezier(.4, 0, 1, 1); +} diff --git a/app/vendor/rune/site/src/system/useScrollSpy.ts b/app/vendor/rune/site/src/system/useScrollSpy.ts new file mode 100644 index 0000000..6937902 --- /dev/null +++ b/app/vendor/rune/site/src/system/useScrollSpy.ts @@ -0,0 +1,55 @@ +import { useEffect, useMemo, useState } from "react" + +/** How much of an element has to be on screen to count as in view: enough to read its heading, or all of it. */ +const IN_VIEW_PX = 48 + +/** Scroll position against a list of element ids, measured once per frame. `active` is the last element whose top has + * passed a line a third of the way down the viewport. `inView` is every element showing at least a heading's worth + * on screen, in order, falling back to `active` when none is. Both are empty on the server and during hydration, so + * the first client render matches the prerendered HTML. */ +export function useScrollSpy(ids: string[]): { active: string | null; inView: string[] } { + const [active, setActive] = useState<string | null>(null) + const [visible, setVisible] = useState("") + const key = ids.join(" ") + + useEffect(() => { + if (ids.length === 0) return + let frame = 0 + const measure = () => { + frame = 0 + const height = window.innerHeight + const line = Math.min(height * 0.33, 280) + const atEnd = height + window.scrollY >= document.documentElement.scrollHeight - 2 + let current: string | null = null + let lastOnScreen: string | null = null + const shown: string[] = [] + for (const id of ids) { + const el = document.getElementById(id) + if (!el) continue + const rect = el.getBoundingClientRect() + if (rect.top <= line) current = id + if (rect.top < height) lastOnScreen = id + const overlap = Math.min(rect.bottom, height) - Math.max(rect.top, 0) + if (overlap >= Math.min(IN_VIEW_PX, rect.height)) shown.push(id) + } + // At the very end of the page the last item wins, even if it never reaches the line. + if (atEnd && lastOnScreen) current = lastOnScreen + setActive(current) + setVisible(shown.join(" ")) + } + const schedule = () => { + if (!frame) frame = requestAnimationFrame(measure) + } + measure() + window.addEventListener("scroll", schedule, { passive: true }) + window.addEventListener("resize", schedule) + return () => { + cancelAnimationFrame(frame) + window.removeEventListener("scroll", schedule) + window.removeEventListener("resize", schedule) + } + }, [key]) + + const inView = useMemo(() => (visible ? visible.split(" ") : active ? [active] : []), [visible, active]) + return { active, inView } +} diff --git a/app/vendor/rune/site/tsconfig.json b/app/vendor/rune/site/tsconfig.json new file mode 100644 index 0000000..46ec393 --- /dev/null +++ b/app/vendor/rune/site/tsconfig.json @@ -0,0 +1,21 @@ +{ + "compilerOptions": { + "target": "esnext", + "lib": ["es2023", "dom", "dom.iterable"], + "moduleDetection": "force", + "module": "esnext", + "moduleResolution": "bundler", + "resolveJsonModule": true, + "types": ["vite/client", "bun", "node"], + "jsx": "react-jsx", + "strict": true, + "noUnusedLocals": true, + "noEmit": true, + "allowImportingTsExtensions": true, + "esModuleInterop": true, + "isolatedModules": true, + "verbatimModuleSyntax": true, + "skipLibCheck": true + }, + "include": ["src", "scripts", "worker.ts", "vite.config.ts", "cloudflare.config.ts"] +} diff --git a/app/vendor/rune/site/vite.config.ts b/app/vendor/rune/site/vite.config.ts new file mode 100644 index 0000000..69d21f5 --- /dev/null +++ b/app/vendor/rune/site/vite.config.ts @@ -0,0 +1,29 @@ +import { cloudflare } from "@cloudflare/vite-plugin" +import react from "@vitejs/plugin-react" +import { resolve } from "node:path" +import { defineConfig } from "vite" +import { snippets } from "./scripts/snippets" +import { BASE_PATH } from "./src/base" + +// The Cloudflare plugin only shapes the client build into Build Output for `cf deploy`. +// Dev stays plain Vite, and the SSR build only feeds the prerender. +export default defineConfig(({ command, isSsrBuild }) => ({ + plugins: [react(), snippets(resolve(import.meta.dirname, "..")), ...(command === "build" && !isSsrBuild ? [cloudflare()] : [])], + base: `${BASE_PATH}/`, + build: { + outDir: "dist", + emptyOutDir: true, + }, + server: { + host: "127.0.0.1", + port: 4241, + strictPort: true, + allowedHosts: [".ts.net"], + }, + preview: { + host: "127.0.0.1", + port: 4241, + strictPort: true, + allowedHosts: [".ts.net"], + }, +})) diff --git a/app/vendor/rune/site/worker.ts b/app/vendor/rune/site/worker.ts new file mode 100644 index 0000000..cd8fd01 --- /dev/null +++ b/app/vendor/rune/site/worker.ts @@ -0,0 +1,51 @@ +import { BASE_PATH, stripBase, withBase } from "./src/base" + +type Env = { + ASSETS: { fetch(request: Request): Promise<Response> } + CANONICAL_HOST: string + ANY_HOST?: string +} + +export default { + async fetch(request: Request, env: Env): Promise<Response> { + const url = new URL(request.url) + + if (!env.ANY_HOST && (url.hostname !== env.CANONICAL_HOST || url.protocol !== "https:")) { + url.protocol = "https:" + url.hostname = env.CANONICAL_HOST + url.port = "" + return Response.redirect(url.toString(), 301) + } + + if (url.pathname === BASE_PATH) { + url.pathname = `${BASE_PATH}/` + return Response.redirect(url.toString(), 301) + } + + // The route also matches paths like /team/runes, which are not ours. + const path = stripBase(url.pathname) + if (path === undefined) return new Response("Not found", { status: 404 }) + + const assetUrl = new URL(url) + assetUrl.pathname = path + let response = await env.ASSETS.fetch(new Request(assetUrl, request)) + if (response.status === 404) { + const page = await env.ASSETS.fetch(new Request(new URL("/404", assetUrl))) + if (page.ok) response = new Response(page.body, { status: 404, headers: page.headers }) + } + const headers = new Headers(response.headers) + // Asset redirects (trailing slashes, /index.html) point at root-relative paths. + const location = headers.get("Location") + if (location?.startsWith("/")) headers.set("Location", withBase(location)) + if (path.startsWith("/assets/")) { + headers.set("Cache-Control", "public, max-age=31536000, immutable") + } + headers.set("X-Content-Type-Options", "nosniff") + headers.set("Referrer-Policy", "strict-origin-when-cross-origin") + return new Response(response.body, { + status: response.status, + statusText: response.statusText, + headers, + }) + }, +} diff --git a/app/vendor/rune/spikes/hot-patch/.gitignore b/app/vendor/rune/spikes/hot-patch/.gitignore new file mode 100644 index 0000000..3fb8dee --- /dev/null +++ b/app/vendor/rune/spikes/hot-patch/.gitignore @@ -0,0 +1,3 @@ +/target/ +/results/ +__pycache__/ diff --git a/app/vendor/rune/spikes/hot-patch/Cargo.lock b/app/vendor/rune/spikes/hot-patch/Cargo.lock new file mode 100644 index 0000000..d1f3eb9 --- /dev/null +++ b/app/vendor/rune/spikes/hot-patch/Cargo.lock @@ -0,0 +1,909 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "anyhow" +version = "1.0.104" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" + +[[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]] +name = "bumpalo" +version = "3.20.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649" + +[[package]] +name = "bytes" +version = "1.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "const_format" +version = "0.2.36" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4481a617ad9a412be3b97c5d403fef8ed023103368908b9c50af598ff467cc1e" +dependencies = [ + "const_format_proc_macros", + "konst", +] + +[[package]] +name = "const_format_proc_macros" +version = "0.2.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d57c2eccfb16dbac1f4e61e206105db5820c9d26c3c472bc17c774259ef7744" +dependencies = [ + "proc-macro2", + "quote", + "unicode-xid", +] + +[[package]] +name = "cpufeatures" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" +dependencies = [ + "libc", +] + +[[package]] +name = "crypto-common" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" +dependencies = [ + "generic-array", + "typenum", +] + +[[package]] +name = "data-encoding" +version = "2.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4583a4551df46e2792f82ceeac45e850d2e2d5debba0b91f102385cda5b11f06" + +[[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 = "dioxus-cli-config" +version = "0.7.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "322d10f47effebd85ee0662a2cb083ff920d40dd6295a4afd8cfa4f9bc2e05c6" + +[[package]] +name = "dioxus-core" +version = "0.7.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1b232228ada232c0adc151e41ebd9ef70cc04683db097fa0dc6015979fa01722" +dependencies = [ + "anyhow", + "const_format", + "dioxus-core-types", + "futures-channel", + "futures-util", + "generational-box", + "longest-increasing-subsequence", + "rustc-hash", + "rustversion", + "serde", + "slab", + "slotmap", + "subsecond", + "tracing", +] + +[[package]] +name = "dioxus-core-types" +version = "0.7.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "96007ed6cbad951dfed82d83c581aabd95bc591f351f5666d454ddbe7845b324" + +[[package]] +name = "dioxus-devtools" +version = "0.7.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "434cebb282b3f820a341582ebfd37dab907d5a25c3eeafd87802468afcd2a959" +dependencies = [ + "dioxus-cli-config", + "dioxus-core", + "dioxus-devtools-types", + "dioxus-signals", + "serde", + "serde_json", + "subsecond", + "thiserror", + "tracing", + "tungstenite", +] + +[[package]] +name = "dioxus-devtools-types" +version = "0.7.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dfd6f3475e38c93be245a664a9ce11679a8f2b99832620705cf7837f42aa39ce" +dependencies = [ + "dioxus-core", + "serde", + "subsecond-types", +] + +[[package]] +name = "dioxus-signals" +version = "0.7.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "95d85e36fcaf7abdc986836801bf248776da7d5961f5fac65fdbf5ed491afb4f" +dependencies = [ + "dioxus-core", + "futures-channel", + "futures-util", + "generational-box", + "parking_lot", + "rustc-hash", + "tracing", + "warnings", +] + +[[package]] +name = "errno" +version = "0.3.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" +dependencies = [ + "libc", + "windows-sys", +] + +[[package]] +name = "futures-channel" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1f9e3d69d39e4862ffed03ed071a76f9a13ba1d9109d355b0f0aa6b15e393c4" +dependencies = [ + "futures-core", +] + +[[package]] +name = "futures-core" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" + +[[package]] +name = "futures-task" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd" + +[[package]] +name = "futures-util" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" +dependencies = [ + "futures-core", + "futures-task", + "pin-project-lite", + "slab", +] + +[[package]] +name = "generational-box" +version = "0.7.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8b2dc9b873cd1a8adb80aa5dcef9a8205f781a8a313d5ffb867248cb3bcb764" +dependencies = [ + "parking_lot", + "tracing", +] + +[[package]] +name = "generic-array" +version = "0.14.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" +dependencies = [ + "typenum", + "version_check", +] + +[[package]] +name = "getrandom" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd" +dependencies = [ + "cfg-if", + "libc", + "r-efi", + "wasip2", +] + +[[package]] +name = "http" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0" +dependencies = [ + "bytes", + "itoa", +] + +[[package]] +name = "httparse" +version = "1.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" + +[[package]] +name = "itoa" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" + +[[package]] +name = "js-sys" +version = "0.3.106" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7883d941dae510fb2d978fc3fe018c71c9e2892fd38854de3e8b92c2e5ad9cc5" +dependencies = [ + "cfg-if", + "futures-util", + "wasm-bindgen", +] + +[[package]] +name = "konst" +version = "0.2.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "128133ed7824fcd73d6e7b17957c5eb7bacb885649bd8c69708b2331a10bcefb" +dependencies = [ + "konst_macro_rules", +] + +[[package]] +name = "konst_macro_rules" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4933f3f57a8e9d9da04db23fb153356ecaf00cbd14aee46279c33dc80925c37" + +[[package]] +name = "libc" +version = "0.2.191" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" + +[[package]] +name = "libloading" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d7c4b02199fee7c5d21a5ae7d8cfa79a6ef5bb2fc834d6e9058e89c825efdc55" +dependencies = [ + "cfg-if", + "windows-link", +] + +[[package]] +name = "linux-raw-sys" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" + +[[package]] +name = "lock_api" +version = "0.4.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965" +dependencies = [ + "scopeguard", +] + +[[package]] +name = "log" +version = "0.4.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6" + +[[package]] +name = "longest-increasing-subsequence" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b3bd0dd2cd90571056fdb71f6275fada10131182f84899f4b2a916e565d81d86" + +[[package]] +name = "rune-hot-patch" +version = "0.1.0" +dependencies = [ + "dioxus-devtools", + "subsecond", +] + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "memfd" +version = "0.6.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "57804b2c9b69967f1536a56f86297e367a33b19e98852ed624b84551cdbc0d90" +dependencies = [ + "rustix", +] + +[[package]] +name = "memmap2" +version = "0.9.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6b0ca1155a9ecc25aa12e8313a119f32edf0255fea2f44839c4ac0a12b2ac157" +dependencies = [ + "libc", +] + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +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]] +name = "pin-project" +version = "1.1.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2466b2336ed02bcdca6b294417127b90ec92038d1d5c4fbeac971a922e0e0924" +dependencies = [ + "pin-project-internal", +] + +[[package]] +name = "pin-project-internal" +version = "1.1.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c96395f0a926bc13b1c17622aaddda1ecb55d49c8f1bf9777e4d877800a43f8b" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "pin-project-lite" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" + +[[package]] +name = "ppv-lite86" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9" +dependencies = [ + "zerocopy", +] + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "r-efi" +version = "5.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f" + +[[package]] +name = "rand" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9ef1d0d795eb7d84685bca4f72f3649f064e6641543d3a8c415898726a57b41" +dependencies = [ + "rand_chacha", + "rand_core", +] + +[[package]] +name = "rand_chacha" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb" +dependencies = [ + "ppv-lite86", + "rand_core", +] + +[[package]] +name = "rand_core" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c" +dependencies = [ + "getrandom", +] + +[[package]] +name = "redox_syscall" +version = "0.5.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d" +dependencies = [ + "bitflags", +] + +[[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.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "891efababe418670775f199f0d233d84843c227a0949a883ce15b37c78d6629d" +dependencies = [ + "bitflags", + "errno", + "libc", + "linux-raw-sys", + "windows-sys", +] + +[[package]] +name = "rustversion" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" + +[[package]] +name = "scopeguard" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "serde_json" +version = "1.0.154" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "sha1" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a978451301f4db1d02937a4ab3ccce137717b81826e79b7d49ffe3244a13c3b8" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest", +] + +[[package]] +name = "slab" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" + +[[package]] +name = "slotmap" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bdd58c3c93c3d278ca835519292445cb4b0d4dc59ccfdf7ceadaab3f8aeb4038" +dependencies = [ + "serde", + "version_check", +] + +[[package]] +name = "smallvec" +version = "1.16.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5b3dc8af474f516a851ff4bd12db780f948b9250ad37211e4eec0bccea54e01b" + +[[package]] +name = "subsecond" +version = "0.7.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d350d5788fa94d560d92269266a50efc77b036bfca6675e420b64df7b3211f37" +dependencies = [ + "js-sys", + "libc", + "libloading", + "memfd", + "memmap2", + "serde", + "subsecond-types", + "thiserror", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", +] + +[[package]] +name = "subsecond-types" +version = "0.7.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dcf32d66269b5fbb8558334e8d22b657b2f7af0dd2ef56c231541099a862e464" +dependencies = [ + "serde", +] + +[[package]] +name = "syn" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "3.0.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d78c8dee4c7bf0e14673097256fed6142ce9d3b85a408189d07482442145823b" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "thiserror" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e" +dependencies = [ + "thiserror-impl", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "tokio" +version = "1.54.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b52fd3255258d26fac7264ab5a76b53c13367136dc011d3d6ad4f8ed070396a3" +dependencies = [ + "pin-project-lite", +] + +[[package]] +name = "tracing" +version = "0.1.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" +dependencies = [ + "pin-project-lite", + "tracing-attributes", + "tracing-core", +] + +[[package]] +name = "tracing-attributes" +version = "0.1.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "tracing-core" +version = "0.1.36" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" +dependencies = [ + "once_cell", +] + +[[package]] +name = "tungstenite" +version = "0.28.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8628dcc84e5a09eb3d8423d6cb682965dea9133204e8fb3efee74c2a0c259442" +dependencies = [ + "bytes", + "data-encoding", + "http", + "httparse", + "log", + "rand", + "sha1", + "thiserror", + "utf-8", +] + +[[package]] +name = "typenum" +version = "1.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" + +[[package]] +name = "unicode-ident" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" + +[[package]] +name = "unicode-xid" +version = "0.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853" + +[[package]] +name = "utf-8" +version = "0.7.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09cc8ee72d2a9becf2f2febe0205bbed8fc6615b7cb429ad062dc7b7ddd036a9" + +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + +[[package]] +name = "warnings" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "64f68998838dab65727c9b30465595c6f7c953313559371ca8bf31759b3680ad" +dependencies = [ + "pin-project", + "tracing", + "warnings-macro", +] + +[[package]] +name = "warnings-macro" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59195a1db0e95b920366d949ba5e0d3fc0e70b67c09be15ce5abb790106b0571" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "wasip2" +version = "1.0.4+wasi-0.2.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b67efb37e106e55ce722a510d6b5f9c17f083e5fc79afc2badeb12cc313d9487" +dependencies = [ + "wit-bindgen", +] + +[[package]] +name = "wasm-bindgen" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9bb54f33acc68fd454578d9820b0bde1a1a3d17aa17bb7b6595806d02886d409" +dependencies = [ + "cfg-if", + "once_cell", + "rustversion", + "wasm-bindgen-macro", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-futures" +version = "0.4.79" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3cbab34de2d982e9b48e18d216d04c4a6f641066ff19ffb699980f591ee3610e" +dependencies = [ + "js-sys", + "tokio", + "wasm-bindgen", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2e29d0c35b16e224a7eeb5cd2d25e3e1968fbd65604117b44d3b789d00ee8535" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6f501a8bc3719dba86ef8ae4728879c08001bea749eb1333ac5b91e040e2a6b7" +dependencies = [ + "bumpalo", + "proc-macro2", + "quote", + "syn 3.0.9", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23f0c9c52aa7cd7d77769a4cfe2a9adb1b331f489a41d912ce14513d5ab995c6" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "web-sys" +version = "0.3.106" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "88261b9deccee56594c11a3460c462c41f58d148598fe70ad77070126a68aba4" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + +[[package]] +name = "wit-bindgen" +version = "0.57.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e" + +[[package]] +name = "zerocopy" +version = "0.8.63" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5fe1f8f1b06191a00962174c61aa5005e0bb391a6d80d07e24d115c01a92ed8" +dependencies = [ + "zerocopy-derive", +] + +[[package]] +name = "zerocopy-derive" +version = "0.8.63" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "863ad3ac83293fb4d740aedbfdc9240dd8d1a50c1099acd76ce80ce7c7230c7f" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/app/vendor/rune/spikes/hot-patch/Cargo.toml b/app/vendor/rune/spikes/hot-patch/Cargo.toml new file mode 100644 index 0000000..03d28b4 --- /dev/null +++ b/app/vendor/rune/spikes/hot-patch/Cargo.toml @@ -0,0 +1,13 @@ +[package] +name = "rune-hot-patch" +version = "0.1.0" +edition = "2024" + +[dependencies] +subsecond = "=0.7.10" +dioxus-devtools = { version = "=0.7.10", default-features = false } + +[profile.dev] +opt-level = 0 +debug = 0 +incremental = true diff --git a/app/vendor/rune/spikes/hot-patch/README.md b/app/vendor/rune/spikes/hot-patch/README.md new file mode 100644 index 0000000..156f01f --- /dev/null +++ b/app/vendor/rune/spikes/hot-patch/README.md @@ -0,0 +1,57 @@ +# Headless Subsecond spike + +Measured on an Apple M2 Max build Mac. See [the research report](../../research/08-spike-hot-patch.md) for conclusions and qualifications. `evidence/` contains the recorded JSON results; `results/` contains disposable full logs from a run. + +This is a Rust terminal binary, with no Dioxus UI or window. `main` owns the state and runs a nominal 120 Hz loop. The patched function returns a string. The Python driver edits Rust source and consumes actual frame events, using timestamps from the same machine. + +## Run + +Copy this directory into its own scratch Git repository on the build machine, outside the Rune workspace: + +```sh +mkdir -p <scratch>/rune-hot-patch && git -C <scratch>/rune-hot-patch init +rsync -az --exclude target --exclude results --exclude evidence \ + spikes/hot-patch/ <scratch>/rune-hot-patch/ +``` + +If Dioxus CLI is missing, install the release used by this spike: + +```sh +cargo-binstall dioxus-cli --version 0.7.10 --no-confirm +"$HOME/.cargo/bin/dx" --version +``` + +Homebrew's `dx` is Deno's command, not Dioxus. The harness deliberately uses the absolute Dioxus path. + +Run each mode from the scratch repository, one at a time: + +```sh +for mode in builds benchmark probes extras; do + python3 run.py "$mode" +done +``` + +`builds` requires a fresh artifact directory; choose a new `RUNE_NORMAL_TARGET` if `target/normal` already exists. This prevents labeling a warm build as cold. For example, put `env RUNE_NORMAL_TARGET=target/normal-new` before `python3` in the command above. Each probe launches a fresh process, patches once, records its observations, stops the process group, and restores the source. Do not run modes concurrently. + +The boundary-signature probe can be run alone: + +```sh +python3 run.py extras --case explicit_hotfn_signature +``` + +The underlying headless command is: + +```sh +"$HOME/.cargo/bin/dx" serve --hot-patch --platform server \ + --open false --interactive false --addr 127.0.0.1 --port 18743 +``` + +The harness disables any inherited sccache wrapper, enables incremental compilation, and limits Cargo to two jobs. The measured runs used background scheduling priority, under which a nominal 120 Hz sleep loop runs in bursts; this is not a display-pacing benchmark. + +## Interpreting the probes + +- The benchmark uses a two-reference closure capture to work around 0.7.10's pointer-sized-closure dispatch bug. `extras` reproduces the broken single capture and verifies `HotFn::current(render).call((&state,))` as a cleaner integration. +- The layout probe adds a field but never explicitly reads it. It demonstrates that patches can cross incompatible layouts without a rejection or migration; it does not establish memory safety. +- A successful revision with unchanged PID, increasing counter, unchanged state/Vec addresses, and `vec0 == counter + 73` establishes preservation of this sample's main-owned state only. +- Private and exported tip-crate statics, thread locals, and cached trait objects have separate observations. Their behavior must not be inferred from the main-owned-state result. +- `p95_nearest_rank_ms` is the largest of ten samples. There is no statistical claim beyond this small run. diff --git a/app/vendor/rune/spikes/hot-patch/evidence/benchmark.json b/app/vendor/rune/spikes/hot-patch/evidence/benchmark.json new file mode 100644 index 0000000..e41346f --- /dev/null +++ b/app/vendor/rune/spikes/hot-patch/evidence/benchmark.json @@ -0,0 +1,442 @@ +{ + "command": [ + "~/.cargo/bin/dx", + "serve", + "--hot-patch", + "--platform", + "server", + "--open", + "false", + "--interactive", + "false", + "--addr", + "127.0.0.1", + "--port", + "18743" + ], + "launch_to_tick60_ms": 7001.939, + "rows": [ + { + "saved_ns": 1792642085506222000, + "latency_ms": 1150.117, + "before": { + "ns": 1792642085503443000, + "pid": 12294, + "counter": 60, + "vec0": 133, + "vec_ptr": 4313468912, + "state_addr": 6169897736, + "panel_width": 800, + "output": "rev=0;value=133;generic=g0:60;closure=70;trait=t0:800x600;static=1059;tls=2059;layout=48" + }, + "previous": { + "ns": 1792642086561740000, + "pid": 12294, + "counter": 202, + "vec0": 275, + "vec_ptr": 4313468912, + "state_addr": 6169897736, + "panel_width": 800, + "output": "rev=0;value=275;generic=g0:202;closure=212;trait=t0:800x600;static=1201;tls=2201;layout=48" + }, + "after": { + "ns": 1792642086656339000, + "pid": 12294, + "counter": 203, + "vec0": 276, + "vec_ptr": 4313468912, + "state_addr": 6169897736, + "panel_width": 800, + "output": "rev=1;value=276;generic=g0:203;closure=213;trait=t0:800x600;static=1000;tls=2000;layout=48" + }, + "same_pid": true, + "same_vec": true, + "same_state": true, + "counter_advanced": true, + "vector_invariant": true, + "patch_ns": [ + 1792642086605967000 + ] + }, + { + "saved_ns": 1792642086838981000, + "latency_ms": 712.42, + "before": { + "ns": 1792642086835450000, + "pid": 12294, + "counter": 233, + "vec0": 306, + "vec_ptr": 4313468912, + "state_addr": 6169897736, + "panel_width": 800, + "output": "rev=1;value=306;generic=g0:233;closure=243;trait=t0:800x600;static=1030;tls=2030;layout=48" + }, + "previous": { + "ns": 1792642087349187000, + "pid": 12294, + "counter": 297, + "vec0": 370, + "vec_ptr": 4313468912, + "state_addr": 6169897736, + "panel_width": 800, + "output": "rev=1;value=370;generic=g0:297;closure=307;trait=t0:800x600;static=1094;tls=2094;layout=48" + }, + "after": { + "ns": 1792642087551401000, + "pid": 12294, + "counter": 298, + "vec0": 371, + "vec_ptr": 4313468912, + "state_addr": 6169897736, + "panel_width": 800, + "output": "rev=2;value=371;generic=g0:298;closure=308;trait=t0:800x600;static=1000;tls=2000;layout=48" + }, + "same_pid": true, + "same_vec": true, + "same_state": true, + "counter_advanced": true, + "vector_invariant": true, + "patch_ns": [ + 1792642087501981000 + ] + }, + { + "saved_ns": 1792642087751298000, + "latency_ms": 998.195, + "before": { + "ns": 1792642087749279000, + "pid": 12294, + "counter": 328, + "vec0": 401, + "vec_ptr": 4313468912, + "state_addr": 6169897736, + "panel_width": 800, + "output": "rev=2;value=401;generic=g0:328;closure=338;trait=t0:800x600;static=1030;tls=2030;layout=48" + }, + "previous": { + "ns": 1792642088550413000, + "pid": 12294, + "counter": 441, + "vec0": 514, + "vec_ptr": 4313468912, + "state_addr": 6169897736, + "panel_width": 800, + "output": "rev=2;value=514;generic=g0:441;closure=451;trait=t0:800x600;static=1143;tls=2143;layout=48" + }, + "after": { + "ns": 1792642088749493000, + "pid": 12294, + "counter": 442, + "vec0": 515, + "vec_ptr": 4313468912, + "state_addr": 6169897736, + "panel_width": 800, + "output": "rev=3;value=515;generic=g0:442;closure=452;trait=t0:800x600;static=1000;tls=2000;layout=48" + }, + "same_pid": true, + "same_vec": true, + "same_state": true, + "counter_advanced": true, + "vector_invariant": true, + "patch_ns": [ + 1792642088559161000 + ] + }, + { + "saved_ns": 1792642088953242000, + "latency_ms": 867.826, + "before": { + "ns": 1792642088951300000, + "pid": 12294, + "counter": 472, + "vec0": 545, + "vec_ptr": 4313468912, + "state_addr": 6169897736, + "panel_width": 800, + "output": "rev=3;value=545;generic=g0:472;closure=482;trait=t0:800x600;static=1030;tls=2030;layout=48" + }, + "previous": { + "ns": 1792642089613359000, + "pid": 12294, + "counter": 569, + "vec0": 642, + "vec_ptr": 4313468912, + "state_addr": 6169897736, + "panel_width": 800, + "output": "rev=3;value=642;generic=g0:569;closure=579;trait=t0:800x600;static=1127;tls=2127;layout=48" + }, + "after": { + "ns": 1792642089821068000, + "pid": 12294, + "counter": 570, + "vec0": 643, + "vec_ptr": 4313468912, + "state_addr": 6169897736, + "panel_width": 800, + "output": "rev=4;value=643;generic=g0:570;closure=580;trait=t0:800x600;static=1000;tls=2000;layout=48" + }, + "same_pid": true, + "same_vec": true, + "same_state": true, + "counter_advanced": true, + "vector_invariant": true, + "patch_ns": [ + 1792642089665812000 + ] + }, + { + "saved_ns": 1792642090034248000, + "latency_ms": 753.253, + "before": { + "ns": 1792642090033362000, + "pid": 12294, + "counter": 600, + "vec0": 673, + "vec_ptr": 4313468912, + "state_addr": 6169897736, + "panel_width": 800, + "output": "rev=4;value=673;generic=g0:600;closure=610;trait=t0:800x600;static=1030;tls=2030;layout=48" + }, + "previous": { + "ns": 1792642090627389000, + "pid": 12294, + "counter": 690, + "vec0": 763, + "vec_ptr": 4313468912, + "state_addr": 6169897736, + "panel_width": 800, + "output": "rev=4;value=763;generic=g0:690;closure=700;trait=t0:800x600;static=1120;tls=2120;layout=48" + }, + "after": { + "ns": 1792642090787501000, + "pid": 12294, + "counter": 691, + "vec0": 764, + "vec_ptr": 4313468912, + "state_addr": 6169897736, + "panel_width": 800, + "output": "rev=5;value=764;generic=g0:691;closure=701;trait=t0:800x600;static=1000;tls=2000;layout=48" + }, + "same_pid": true, + "same_vec": true, + "same_state": true, + "counter_advanced": true, + "vector_invariant": true, + "patch_ns": [ + 1792642090786059000 + ] + }, + { + "saved_ns": 1792642091031835000, + "latency_ms": 1005.25, + "before": { + "ns": 1792642091029866000, + "pid": 12294, + "counter": 721, + "vec0": 794, + "vec_ptr": 4313468912, + "state_addr": 6169897736, + "panel_width": 800, + "output": "rev=5;value=794;generic=g0:721;closure=731;trait=t0:800x600;static=1030;tls=2030;layout=48" + }, + "previous": { + "ns": 1792642091830376000, + "pid": 12294, + "counter": 835, + "vec0": 908, + "vec_ptr": 4313468912, + "state_addr": 6169897736, + "panel_width": 800, + "output": "rev=5;value=908;generic=g0:835;closure=845;trait=t0:800x600;static=1144;tls=2144;layout=48" + }, + "after": { + "ns": 1792642092037085000, + "pid": 12294, + "counter": 836, + "vec0": 909, + "vec_ptr": 4313468912, + "state_addr": 6169897736, + "panel_width": 800, + "output": "rev=6;value=909;generic=g0:836;closure=846;trait=t0:800x600;static=1000;tls=2000;layout=48" + }, + "same_pid": true, + "same_vec": true, + "same_state": true, + "counter_advanced": true, + "vector_invariant": true, + "patch_ns": [ + 1792642091865846000 + ] + }, + { + "saved_ns": 1792642092106997000, + "latency_ms": 851.558, + "before": { + "ns": 1792642092105159000, + "pid": 12294, + "counter": 866, + "vec0": 939, + "vec_ptr": 4313468912, + "state_addr": 6169897736, + "panel_width": 800, + "output": "rev=6;value=939;generic=g0:866;closure=876;trait=t0:800x600;static=1030;tls=2030;layout=48" + }, + "previous": { + "ns": 1792642092920925000, + "pid": 12294, + "counter": 965, + "vec0": 1038, + "vec_ptr": 4313468912, + "state_addr": 6169897736, + "panel_width": 800, + "output": "rev=6;value=1038;generic=g0:965;closure=975;trait=t0:800x600;static=1129;tls=2129;layout=48" + }, + "after": { + "ns": 1792642092958555000, + "pid": 12294, + "counter": 966, + "vec0": 1039, + "vec_ptr": 4313468912, + "state_addr": 6169897736, + "panel_width": 800, + "output": "rev=7;value=1039;generic=g0:966;closure=976;trait=t0:800x600;static=1000;tls=2000;layout=48" + }, + "same_pid": true, + "same_vec": true, + "same_state": true, + "counter_advanced": true, + "vector_invariant": true, + "patch_ns": [ + 1792642092924546000 + ] + }, + { + "saved_ns": 1792642093312077000, + "latency_ms": 979.82, + "before": { + "ns": 1792642093311180000, + "pid": 12294, + "counter": 996, + "vec0": 1069, + "vec_ptr": 4313468912, + "state_addr": 6169897736, + "panel_width": 800, + "output": "rev=7;value=1069;generic=g0:996;closure=1006;trait=t0:800x600;static=1030;tls=2030;layout=48" + }, + "previous": { + "ns": 1792642094093259000, + "pid": 12294, + "counter": 1106, + "vec0": 1179, + "vec_ptr": 4313468912, + "state_addr": 6169897736, + "panel_width": 800, + "output": "rev=7;value=1179;generic=g0:1106;closure=1116;trait=t0:800x600;static=1140;tls=2140;layout=48" + }, + "after": { + "ns": 1792642094291897000, + "pid": 12294, + "counter": 1107, + "vec0": 1180, + "vec_ptr": 4313468912, + "state_addr": 6169897736, + "panel_width": 800, + "output": "rev=8;value=1180;generic=g0:1107;closure=1117;trait=t0:800x600;static=1000;tls=2000;layout=48" + }, + "same_pid": true, + "same_vec": true, + "same_state": true, + "counter_advanced": true, + "vector_invariant": true, + "patch_ns": [ + 1792642094172697000 + ] + }, + { + "saved_ns": 1792642094492841000, + "latency_ms": 1036.368, + "before": { + "ns": 1792642094490695000, + "pid": 12294, + "counter": 1137, + "vec0": 1210, + "vec_ptr": 4313468912, + "state_addr": 6169897736, + "panel_width": 800, + "output": "rev=8;value=1210;generic=g0:1137;closure=1147;trait=t0:800x600;static=1030;tls=2030;layout=48" + }, + "previous": { + "ns": 1792642095323670000, + "pid": 12294, + "counter": 1254, + "vec0": 1327, + "vec_ptr": 4313468912, + "state_addr": 6169897736, + "panel_width": 800, + "output": "rev=8;value=1327;generic=g0:1254;closure=1264;trait=t0:800x600;static=1147;tls=2147;layout=48" + }, + "after": { + "ns": 1792642095529209000, + "pid": 12294, + "counter": 1255, + "vec0": 1328, + "vec_ptr": 4313468912, + "state_addr": 6169897736, + "panel_width": 800, + "output": "rev=9;value=1328;generic=g0:1255;closure=1265;trait=t0:800x600;static=1000;tls=2000;layout=48" + }, + "same_pid": true, + "same_vec": true, + "same_state": true, + "counter_advanced": true, + "vector_invariant": true, + "patch_ns": [ + 1792642095408833000 + ] + }, + { + "saved_ns": 1792642095766266000, + "latency_ms": 1030.275, + "before": { + "ns": 1792642095763851000, + "pid": 12294, + "counter": 1285, + "vec0": 1358, + "vec_ptr": 4313468912, + "state_addr": 6169897736, + "panel_width": 800, + "output": "rev=9;value=1358;generic=g0:1285;closure=1295;trait=t0:800x600;static=1030;tls=2030;layout=48" + }, + "previous": { + "ns": 1792642096590552000, + "pid": 12294, + "counter": 1406, + "vec0": 1479, + "vec_ptr": 4313468912, + "state_addr": 6169897736, + "panel_width": 800, + "output": "rev=9;value=1479;generic=g0:1406;closure=1416;trait=t0:800x600;static=1151;tls=2151;layout=48" + }, + "after": { + "ns": 1792642096796541000, + "pid": 12294, + "counter": 1407, + "vec0": 1480, + "vec_ptr": 4313468912, + "state_addr": 6169897736, + "panel_width": 800, + "output": "rev=10;value=1480;generic=g0:1407;closure=1417;trait=t0:800x600;static=1000;tls=2000;layout=48" + }, + "same_pid": true, + "same_vec": true, + "same_state": true, + "counter_advanced": true, + "vector_invariant": true, + "patch_ns": [ + 1792642096704994000 + ] + } + ], + "median_ms": 989.0075, + "p95_nearest_rank_ms": 1150.117 +} \ No newline at end of file diff --git a/app/vendor/rune/spikes/hot-patch/evidence/builds.json b/app/vendor/rune/spikes/hot-patch/evidence/builds.json new file mode 100644 index 0000000..4b507a2 --- /dev/null +++ b/app/vendor/rune/spikes/hot-patch/evidence/builds.json @@ -0,0 +1,24 @@ +[ + { + "name": "cold", + "elapsed_ms": 71333.100958, + "exit": 0, + "command": [ + "cargo", + "build", + "--target-dir", + "target/normal-final" + ] + }, + { + "name": "incremental", + "elapsed_ms": 1846.435208, + "exit": 0, + "command": [ + "cargo", + "build", + "--target-dir", + "target/normal-final" + ] + } +] \ No newline at end of file diff --git a/app/vendor/rune/spikes/hot-patch/evidence/environment.json b/app/vendor/rune/spikes/hot-patch/evidence/environment.json new file mode 100644 index 0000000..ce36766 --- /dev/null +++ b/app/vendor/rune/spikes/hot-patch/evidence/environment.json @@ -0,0 +1,25 @@ +{ + "date": "2026-10-21", + "host": "macOS arm64", + "chip": "Apple M2 Max", + "cores": 12, + "ram_gib": 96, + "macos": "27.0.1 (26A434)", + "rustc": "rustc 1.99.0 (b940084d7 2026-09-28)", + "toolchain": "stable-aarch64-apple-darwin", + "dx": "dioxus 0.7.10 (57d6794)", + "dx_path": "~/.cargo/bin/dx", + "subsecond": "0.7.10", + "dioxus_devtools": "0.7.10", + "xcode": "27.1 (27A9275)", + "installed_rust_targets": ["aarch64-apple-darwin"], + "booted_simulators_at_inspection": 0, + "runner": "local: python3 run.py", + "cargo_jobs": 2, + "rustc_wrapper": "disabled because inherited sccache rejects CARGO_INCREMENTAL=1", + "dev_profile": {"opt_level": 0, "debug": 0, "incremental": true}, + "scheduler": "taskpolicy background/utility, nice 10", + "windows_opened": false, + "gpu_tested": false, + "ios_tested": false +} diff --git a/app/vendor/rune/spikes/hot-patch/evidence/extra-explicit_hotfn_signature.json b/app/vendor/rune/spikes/hot-patch/evidence/extra-explicit_hotfn_signature.json new file mode 100644 index 0000000..1f594d9 --- /dev/null +++ b/app/vendor/rune/spikes/hot-patch/evidence/extra-explicit_hotfn_signature.json @@ -0,0 +1,30 @@ +{ + "explicit_hotfn_signature": { + "saved_ns": 1792642443553528000, + "error": "Empty: ", + "before": { + "ns": 1792642443549997000, + "pid": 16842, + "counter": 60, + "vec0": 133, + "vec_ptr": 4356149072, + "state_addr": 6124137224, + "panel_width": 800, + "output": "rev=0;value=133;generic=g0:60;closure=70;trait=t0:800x600;static=1059;tls=2059;layout=48" + }, + "last": { + "ns": 1792642448698142000, + "pid": 16842, + "counter": 666, + "vec0": 739, + "vec_ptr": 4356149072, + "state_addr": 6124137224, + "panel_width": 800, + "output": "rev=0;value=739;generic=g0:666;closure=676;trait=t0:800x600;static=1665;tls=2665;layout=48" + }, + "dx_exit": null, + "all_patch_ns": [ + 1792642444347318000 + ] + } +} \ No newline at end of file diff --git a/app/vendor/rune/spikes/hot-patch/evidence/extras.json b/app/vendor/rune/spikes/hot-patch/evidence/extras.json new file mode 100644 index 0000000..eca064a --- /dev/null +++ b/app/vendor/rune/spikes/hot-patch/evidence/extras.json @@ -0,0 +1,165 @@ +{ + "single_capture": { + "saved_ns": 1792642220464464000, + "error": "Empty: ", + "before": { + "ns": 1792642220461332000, + "pid": 14121, + "counter": 60, + "vec0": 133, + "vec_ptr": 4387229680, + "state_addr": 6095825680, + "panel_width": 800, + "output": "rev=0;value=133;generic=g0:60;closure=70;trait=t0:800x600;static=1059;tls=2059;layout=48" + }, + "last": { + "ns": 1792642225604792000, + "pid": 14121, + "counter": 668, + "vec0": 741, + "vec_ptr": 4387229680, + "state_addr": 6095825680, + "panel_width": 800, + "output": "rev=0;value=741;generic=g0:668;closure=678;trait=t0:800x600;static=1667;tls=2667;layout=48" + }, + "dx_exit": null, + "all_patch_ns": [ + 1792642221450704000 + ] + }, + "explicit_hotfn": { + "saved_ns": 1792642231822687000, + "latency_ms": 918.212, + "before": { + "ns": 1792642231821365000, + "pid": 14252, + "counter": 60, + "vec0": 133, + "vec_ptr": 4309602288, + "state_addr": 6171896584, + "panel_width": 800, + "output": "rev=0;value=133;generic=g0:60;closure=70;trait=t0:800x600;static=1059;tls=2059;layout=48" + }, + "previous": { + "ns": 1792642232550510000, + "pid": 14252, + "counter": 162, + "vec0": 235, + "vec_ptr": 4309602288, + "state_addr": 6171896584, + "panel_width": 800, + "output": "rev=0;value=235;generic=g0:162;closure=172;trait=t0:800x600;static=1161;tls=2161;layout=48" + }, + "after": { + "ns": 1792642232740899000, + "pid": 14252, + "counter": 163, + "vec0": 236, + "vec_ptr": 4309602288, + "state_addr": 6171896584, + "panel_width": 800, + "output": "rev=93;value=236;generic=g0:163;closure=173;trait=t0:800x600;static=1000;tls=2000;layout=48" + }, + "same_pid": true, + "same_vec": true, + "same_state": true, + "counter_advanced": true, + "vector_invariant": true, + "patch_ns": [ + 1792642232682946000 + ], + "all_patch_ns": [ + 1792642232682946000 + ] + }, + "exported_static": { + "saved_ns": 1792642237684455000, + "latency_ms": 1103.955, + "before": { + "ns": 1792642237680850000, + "pid": 14373, + "counter": 60, + "vec0": 133, + "vec_ptr": 4326019056, + "state_addr": 6155168520, + "panel_width": 800, + "output": "rev=0;value=133;generic=g0:60;closure=70;trait=t0:800x600;static=1059;tls=2059;layout=48" + }, + "previous": { + "ns": 1792642238581962000, + "pid": 14373, + "counter": 182, + "vec0": 255, + "vec_ptr": 4326019056, + "state_addr": 6155168520, + "panel_width": 800, + "output": "rev=0;value=255;generic=g0:182;closure=192;trait=t0:800x600;static=1181;tls=2181;layout=48" + }, + "after": { + "ns": 1792642238788410000, + "pid": 14373, + "counter": 183, + "vec0": 256, + "vec_ptr": 4326019056, + "state_addr": 6155168520, + "panel_width": 800, + "output": "rev=93;value=256;generic=g0:183;closure=193;trait=t0:800x600;static=9000;tls=2000;layout=48" + }, + "same_pid": true, + "same_vec": true, + "same_state": true, + "counter_advanced": true, + "vector_invariant": true, + "patch_ns": [ + 1792642238700397000 + ], + "all_patch_ns": [ + 1792642238700397000 + ] + }, + "cached_trait_object": { + "saved_ns": 1792642243409971000, + "latency_ms": 837.707, + "before": { + "ns": 1792642243408744000, + "pid": 14490, + "counter": 60, + "vec0": 133, + "vec_ptr": 4389916656, + "state_addr": 6092237576, + "panel_width": 800, + "output": "rev=0;value=133;generic=g0:60;closure=70;trait=t0:42x24;static=1059;tls=2059;layout=64" + }, + "previous": { + "ns": 1792642244055695000, + "pid": 14490, + "counter": 152, + "vec0": 225, + "vec_ptr": 4389916656, + "state_addr": 6092237576, + "panel_width": 800, + "output": "rev=0;value=225;generic=g0:152;closure=162;trait=t0:42x24;static=1151;tls=2151;layout=64" + }, + "after": { + "ns": 1792642244247678000, + "pid": 14490, + "counter": 153, + "vec0": 226, + "vec_ptr": 4389916656, + "state_addr": 6092237576, + "panel_width": 800, + "output": "rev=93;value=226;generic=g0:153;closure=163;trait=t0:42x24;static=1000;tls=2000;layout=64" + }, + "same_pid": true, + "same_vec": true, + "same_state": true, + "counter_advanced": true, + "vector_invariant": true, + "patch_ns": [ + 1792642244210145000 + ], + "all_patch_ns": [ + 1792642244210145000 + ] + } +} \ No newline at end of file diff --git a/app/vendor/rune/spikes/hot-patch/evidence/initial-builds.json b/app/vendor/rune/spikes/hot-patch/evidence/initial-builds.json new file mode 100644 index 0000000..084d042 --- /dev/null +++ b/app/vendor/rune/spikes/hot-patch/evidence/initial-builds.json @@ -0,0 +1,24 @@ +[ + { + "name": "cold", + "elapsed_ms": 79599.681459, + "exit": 0, + "command": [ + "cargo", + "build", + "--target-dir", + "target/normal" + ] + }, + { + "name": "incremental", + "elapsed_ms": 1671.94775, + "exit": 0, + "command": [ + "cargo", + "build", + "--target-dir", + "target/normal" + ] + } +] \ No newline at end of file diff --git a/app/vendor/rune/spikes/hot-patch/evidence/pointer-capture-failure.json b/app/vendor/rune/spikes/hot-patch/evidence/pointer-capture-failure.json new file mode 100644 index 0000000..d17cbb8 --- /dev/null +++ b/app/vendor/rune/spikes/hot-patch/evidence/pointer-capture-failure.json @@ -0,0 +1,47 @@ +{ + "command": [ + "~/.cargo/bin/dx", + "serve", + "--hot-patch", + "--platform", + "server", + "--open", + "false", + "--interactive", + "false", + "--addr", + "127.0.0.1", + "--port", + "18743" + ], + "launch_to_tick60_ms": 139455.02, + "rows": [ + { + "saved_ns": 1792641351383807000, + "error": "Empty: ", + "before": { + "ns": 1792641351381246000, + "pid": 341, + "counter": 60, + "vec0": 133, + "vec_ptr": 4383383296, + "state_addr": 6091696912, + "panel_width": 800, + "output": "rev=0;value=133;generic=g0:60;closure=70;trait=t0:800x600;static=1059;tls=2059;layout=48" + }, + "last": { + "ns": 1792641381515163000, + "pid": 341, + "counter": 3665, + "vec0": 3738, + "vec_ptr": 4383383296, + "state_addr": 6091696912, + "panel_width": 800, + "output": "rev=0;value=3738;generic=g0:3665;closure=3675;trait=t0:800x600;static=4664;tls=5664;layout=48" + }, + "dx_exit": null + } + ], + "median_ms": null, + "p95_nearest_rank_ms": null +} \ No newline at end of file diff --git a/app/vendor/rune/spikes/hot-patch/evidence/probes.json b/app/vendor/rune/spikes/hot-patch/evidence/probes.json new file mode 100644 index 0000000..cdc3dc0 --- /dev/null +++ b/app/vendor/rune/spikes/hot-patch/evidence/probes.json @@ -0,0 +1,296 @@ +{ + "generic": { + "saved_ns": 1792642108306413000, + "latency_ms": 811.216, + "before": { + "ns": 1792642108304765000, + "pid": 12680, + "counter": 60, + "vec0": 133, + "vec_ptr": 4352643056, + "state_addr": 6131149576, + "panel_width": 800, + "output": "rev=0;value=133;generic=g0:60;closure=70;trait=t0:800x600;static=1059;tls=2059;layout=48" + }, + "previous": { + "ns": 1792642108913479000, + "pid": 12680, + "counter": 134, + "vec0": 207, + "vec_ptr": 4352643056, + "state_addr": 6131149576, + "panel_width": 800, + "output": "rev=0;value=207;generic=g0:134;closure=144;trait=t0:800x600;static=1133;tls=2133;layout=48" + }, + "after": { + "ns": 1792642109117629000, + "pid": 12680, + "counter": 135, + "vec0": 208, + "vec_ptr": 4352643056, + "state_addr": 6131149576, + "panel_width": 800, + "output": "rev=0;value=208;generic=g1:135;closure=145;trait=t0:800x600;static=1000;tls=2000;layout=48" + }, + "same_pid": true, + "same_vec": true, + "same_state": true, + "counter_advanced": true, + "vector_invariant": true, + "patch_ns": [ + 1792642108947293000 + ] + }, + "closure": { + "saved_ns": 1792642112595462000, + "latency_ms": 974.11, + "before": { + "ns": 1792642112592532000, + "pid": 12767, + "counter": 60, + "vec0": 133, + "vec_ptr": 4326526960, + "state_addr": 6155987720, + "panel_width": 800, + "output": "rev=0;value=133;generic=g0:60;closure=70;trait=t0:800x600;static=1059;tls=2059;layout=48" + }, + "previous": { + "ns": 1792642113416884000, + "pid": 12767, + "counter": 165, + "vec0": 238, + "vec_ptr": 4326526960, + "state_addr": 6155987720, + "panel_width": 800, + "output": "rev=0;value=238;generic=g0:165;closure=175;trait=t0:800x600;static=1164;tls=2164;layout=48" + }, + "after": { + "ns": 1792642113569572000, + "pid": 12767, + "counter": 166, + "vec0": 239, + "vec_ptr": 4326526960, + "state_addr": 6155987720, + "panel_width": 800, + "output": "rev=0;value=239;generic=g0:166;closure=186;trait=t0:800x600;static=1000;tls=2000;layout=48" + }, + "same_pid": true, + "same_vec": true, + "same_state": true, + "counter_advanced": true, + "vector_invariant": true, + "patch_ns": [ + 1792642113544560000 + ] + }, + "trait_impl": { + "saved_ns": 1792642118437453000, + "latency_ms": 1050.813, + "before": { + "ns": 1792642118436294000, + "pid": 12884, + "counter": 60, + "vec0": 133, + "vec_ptr": 4310493696, + "state_addr": 6171208456, + "panel_width": 800, + "output": "rev=0;value=133;generic=g0:60;closure=70;trait=t0:800x600;static=1059;tls=2059;layout=48" + }, + "previous": { + "ns": 1792642119283144000, + "pid": 12884, + "counter": 175, + "vec0": 248, + "vec_ptr": 4310493696, + "state_addr": 6171208456, + "panel_width": 800, + "output": "rev=0;value=248;generic=g0:175;closure=185;trait=t0:800x600;static=1174;tls=2174;layout=48" + }, + "after": { + "ns": 1792642119488266000, + "pid": 12884, + "counter": 176, + "vec0": 249, + "vec_ptr": 4310493696, + "state_addr": 6171208456, + "panel_width": 800, + "output": "rev=0;value=249;generic=g0:176;closure=186;trait=t1:800x600;static=1000;tls=2000;layout=48" + }, + "same_pid": true, + "same_vec": true, + "same_state": true, + "counter_advanced": true, + "vector_invariant": true, + "patch_ns": [ + 1792642119309418000 + ] + }, + "signature": { + "saved_ns": 1792642124824404000, + "latency_ms": 1351.378, + "before": { + "ns": 1792642124820861000, + "pid": 13003, + "counter": 60, + "vec0": 133, + "vec_ptr": 4386050032, + "state_addr": 6094072584, + "panel_width": 800, + "output": "rev=0;value=133;generic=g0:60;closure=70;trait=t0:800x600;static=1059;tls=2059;layout=48" + }, + "previous": { + "ns": 1792642125970919000, + "pid": 13003, + "counter": 203, + "vec0": 276, + "vec_ptr": 4386050032, + "state_addr": 6094072584, + "panel_width": 800, + "output": "rev=0;value=276;generic=g0:203;closure=213;trait=t0:800x600;static=1202;tls=2202;layout=48" + }, + "after": { + "ns": 1792642126175782000, + "pid": 13003, + "counter": 204, + "vec0": 277, + "vec_ptr": 4386050032, + "state_addr": 6094072584, + "panel_width": 800, + "output": "rev=99;value=277;generic=g0:204;closure=214;trait=t0:800x600;static=1000;tls=2000;layout=48" + }, + "same_pid": true, + "same_vec": true, + "same_state": true, + "counter_advanced": true, + "vector_invariant": true, + "patch_ns": [ + 1792642126059739000 + ] + }, + "state_field": { + "saved_ns": 1792642130972514000, + "latency_ms": 1449.457, + "before": { + "ns": 1792642130968977000, + "pid": 13107, + "counter": 60, + "vec0": 133, + "vec_ptr": 4325462000, + "state_addr": 6156331784, + "panel_width": 800, + "output": "rev=0;value=133;generic=g0:60;closure=70;trait=t0:800x600;static=1059;tls=2059;layout=48" + }, + "previous": { + "ns": 1792642132223222000, + "pid": 13107, + "counter": 213, + "vec0": 286, + "vec_ptr": 4325462000, + "state_addr": 6156331784, + "panel_width": 800, + "output": "rev=0;value=286;generic=g0:213;closure=223;trait=t0:800x600;static=1212;tls=2212;layout=48" + }, + "after": { + "ns": 1792642132421971000, + "pid": 13107, + "counter": 214, + "vec0": 287, + "vec_ptr": 4325462000, + "state_addr": 6156331784, + "panel_width": 800, + "output": "rev=0;value=287;generic=g0:214;closure=224;trait=t0:800x600;static=1000;tls=2000;layout=56" + }, + "same_pid": true, + "same_vec": true, + "same_state": true, + "counter_advanced": true, + "vector_invariant": true, + "patch_ns": [ + 1792642132340891000 + ] + }, + "static_initializer": { + "saved_ns": 1792642137926238000, + "latency_ms": 1122.501, + "before": { + "ns": 1792642137922447000, + "pid": 13229, + "counter": 60, + "vec0": 133, + "vec_ptr": 4383985648, + "state_addr": 6097857288, + "panel_width": 800, + "output": "rev=0;value=133;generic=g0:60;closure=70;trait=t0:800x600;static=1059;tls=2059;layout=48" + }, + "previous": { + "ns": 1792642138838994000, + "pid": 13229, + "counter": 190, + "vec0": 263, + "vec_ptr": 4383985648, + "state_addr": 6097857288, + "panel_width": 800, + "output": "rev=0;value=263;generic=g0:190;closure=200;trait=t0:800x600;static=1189;tls=2189;layout=48" + }, + "after": { + "ns": 1792642139048739000, + "pid": 13229, + "counter": 191, + "vec0": 264, + "vec_ptr": 4383985648, + "state_addr": 6097857288, + "panel_width": 800, + "output": "rev=91;value=264;generic=g0:191;closure=201;trait=t0:800x600;static=9000;tls=2000;layout=48" + }, + "same_pid": true, + "same_vec": true, + "same_state": true, + "counter_advanced": true, + "vector_invariant": true, + "patch_ns": [ + 1792642138897582000 + ] + }, + "tls_initializer": { + "saved_ns": 1792642143342964000, + "latency_ms": 871.657, + "before": { + "ns": 1792642143341740000, + "pid": 13330, + "counter": 60, + "vec0": 133, + "vec_ptr": 4315779056, + "state_addr": 6168128264, + "panel_width": 800, + "output": "rev=0;value=133;generic=g0:60;closure=70;trait=t0:800x600;static=1059;tls=2059;layout=48" + }, + "previous": { + "ns": 1792642144008965000, + "pid": 13330, + "counter": 143, + "vec0": 216, + "vec_ptr": 4315779056, + "state_addr": 6168128264, + "panel_width": 800, + "output": "rev=0;value=216;generic=g0:143;closure=153;trait=t0:800x600;static=1142;tls=2142;layout=48" + }, + "after": { + "ns": 1792642144214621000, + "pid": 13330, + "counter": 144, + "vec0": 217, + "vec_ptr": 4315779056, + "state_addr": 6168128264, + "panel_width": 800, + "output": "rev=92;value=217;generic=g0:144;closure=154;trait=t0:800x600;static=1000;tls=9000;layout=48" + }, + "same_pid": true, + "same_vec": true, + "same_state": true, + "counter_advanced": true, + "vector_invariant": true, + "patch_ns": [ + 1792642144108229000 + ] + } +} \ No newline at end of file diff --git a/app/vendor/rune/spikes/hot-patch/run.py b/app/vendor/rune/spikes/hot-patch/run.py new file mode 100644 index 0000000..4eb2301 --- /dev/null +++ b/app/vendor/rune/spikes/hot-patch/run.py @@ -0,0 +1,248 @@ +#!/usr/bin/env python3 +"""Run only on a build worker, inside a cargo lease on the build queue. + +Consumes actual frame events (no status polling). All clocks are on the worker. +The save timestamp is immediately after close; no network sync is in the metric. +""" +import argparse +import json +import math +import os +from pathlib import Path +import queue +import re +import signal +import statistics +import subprocess +import threading +import time + +ROOT = Path(__file__).resolve().parent +SOURCE = ROOT / "src/main.rs" +BASE = SOURCE.read_text() +RESULTS = ROOT / "results" +RESULTS.mkdir(exist_ok=True) +ENV = dict(os.environ, CARGO_BUILD_JOBS="2", CARGO_INCREMENTAL="1", NO_COLOR="1") +# The worker normally uses sccache, which rejects explicit incremental builds. +ENV["RUSTC_WRAPPER"] = "" +DX = str(Path.home() / ".cargo/bin/dx") +COMMAND = [DX, "serve", "--hot-patch", "--platform", "server", "--open", "false", + "--interactive", "false", "--addr", "127.0.0.1", "--port", "18743"] + + +def save(text): + SOURCE.write_text(text) + return time.time_ns() + + +def parse_output(frame): + return dict(part.split("=", 1) for part in frame["output"].split(";")) + + +class Session: + def __init__(self, name): + self.events = queue.Queue() + self.last = None + self.patch_ns = [] + self.log = (RESULTS / f"{name}.log").open("w") + self.started_ns = time.time_ns() + self.process = subprocess.Popen(COMMAND, cwd=ROOT, env=ENV, + stdout=subprocess.PIPE, stderr=subprocess.STDOUT, + text=True, bufsize=1, start_new_session=True) + self.reader = threading.Thread(target=self.read, daemon=True) + self.reader.start() + + def read(self): + for line in self.process.stdout: + self.log.write(line) + self.log.flush() + if "Build failed" in line or "could not compile" in line: + self.events.put(None) + patch = re.search(r'PATCH ns=(\d+)', line) + if patch: + self.patch_ns.append(int(patch.group(1))) + match = re.search(r'FRAME (\{[^\n]+\})', line) + if match: + try: + self.events.put(json.loads(match.group(1))) + except json.JSONDecodeError: + pass + self.events.put(None) + + def until(self, predicate, timeout=120): + deadline = time.monotonic() + timeout + while True: + item = self.events.get(timeout=max(0, deadline - time.monotonic())) + if item is None: + raise RuntimeError(f"dx exited: {self.process.poll()}") + previous, self.last = self.last, item + if predicate(item): + return previous, item + + def ready(self): + self.until(lambda f: f["counter"] >= 60, timeout=600) + return (self.last["ns"] - self.started_ns) / 1e6 + + def edit(self, text, predicate, timeout=30): + before = self.last + saved = save(text) + try: + previous, after = self.until(lambda f: f["ns"] >= saved and predicate(f), timeout) + result = { + "saved_ns": saved, "latency_ms": (after["ns"] - saved) / 1e6, + "before": before, "previous": previous, "after": after, + "same_pid": before["pid"] == after["pid"], + "same_vec": before["vec_ptr"] == after["vec_ptr"], + "same_state": before["state_addr"] == after["state_addr"], + "counter_advanced": after["counter"] > before["counter"], + "vector_invariant": after["vec0"] == after["counter"] + 73, + "patch_ns": [ns for ns in self.patch_ns if ns >= saved], + } + except (queue.Empty, RuntimeError) as exc: + result = {"saved_ns": saved, "error": type(exc).__name__ + ": " + str(exc), + "before": before, "last": self.last, + "dx_exit": self.process.poll()} + print(json.dumps(result), flush=True) + return result + + def close(self): + if self.process.poll() is None: + os.killpg(self.process.pid, signal.SIGTERM) + try: + self.process.wait(timeout=10) + except subprocess.TimeoutExpired: + os.killpg(self.process.pid, signal.SIGKILL) + self.process.wait() + self.reader.join(timeout=5) + self.log.close() + + +def benchmark(): + session = Session("benchmark") + rows = [] + try: + ready_ms = session.ready() + for revision in range(1, 11): + text = BASE.replace("let revision = 0;", f"let revision = {revision};") + row = session.edit(text, lambda f: parse_output(f)["rev"] == str(revision)) + rows.append(row) + if "error" in row: + break + # Let at least 30 real frames flow between saves; do not overlap builds. + counter = row["after"]["counter"] + session.until(lambda f: f["counter"] >= counter + 30) + times = sorted(r["latency_ms"] for r in rows if "latency_ms" in r) + result = {"command": COMMAND, "launch_to_tick60_ms": ready_ms, "rows": rows, + "median_ms": statistics.median(times) if times else None, + "p95_nearest_rank_ms": times[math.ceil(.95 * len(times)) - 1] if times else None} + (RESULTS / "benchmark.json").write_text(json.dumps(result, indent=2)) + finally: + session.close() + save(BASE) + + +def probes(): + changes = { + "generic": (BASE.replace('"g0:{value}"', '"g1:{value}"'), + lambda f: parse_output(f)["generic"].startswith("g1:")), + "closure": (BASE.replace("value + 10", "value + 20"), + lambda f: int(parse_output(f)["closure"]) == f["counter"] + 20), + "trait_impl": (BASE.replace('"t0:{}x{}"', '"t1:{}x{}"'), + lambda f: parse_output(f)["trait"].startswith("t1:")), + "signature": (BASE.replace("fn render(state: &AppState)", "fn render(state: &AppState, tone: u64)") + .replace("let revision = 0;", "let revision = tone;") + .replace(" render(&state)", " render(&state, 99)"), + lambda f: parse_output(f)["rev"] == "99"), + # Only compare sizes; NEVER read the new field through the old instance. + "state_field": (BASE.replace("// FIELD_PROBE", "extra: u64,") + .replace("// FIELD_INIT", "extra: 999,"), + lambda f: parse_output(f)["layout"] == "56"), + "static_initializer": (BASE.replace("AtomicU64::new(1000)", "AtomicU64::new(9000)") + .replace("let revision = 0;", "let revision = 91;"), + lambda f: parse_output(f)["rev"] == "91"), + "tls_initializer": (BASE.replace("Cell::new(2000)", "Cell::new(9000)") + .replace("let revision = 0;", "let revision = 92;"), + lambda f: parse_output(f)["rev"] == "92"), + } + rows = {} + for name, (text, predicate) in changes.items(): + save(BASE) + session = Session("probe-" + name) + try: + session.ready() + rows[name] = session.edit(text, predicate, timeout=15) + finally: + session.close() + save(BASE) + (RESULTS / "probes.json").write_text(json.dumps(rows, indent=2)) + + +def builds(): + target = os.environ.get("RUNE_NORMAL_TARGET", "target/normal") + if (ROOT / target).exists(): + raise RuntimeError(f"{target} already exists; select a fresh RUNE_NORMAL_TARGET for a cold build") + rows = [] + try: + for name, text in [("cold", BASE), + ("incremental", BASE.replace("let revision = 0;", "let revision = 1;"))]: + save(text) + command = ["cargo", "build", "--target-dir", target] + start = time.monotonic_ns() + with (RESULTS / f"build-{name}.log").open("w") as out: + run = subprocess.run(command, cwd=ROOT, env=ENV, stdout=out, stderr=subprocess.STDOUT) + rows.append({"name": name, "elapsed_ms": (time.monotonic_ns() - start) / 1e6, + "exit": run.returncode, "command": command}) + print(json.dumps(rows[-1]), flush=True) + if run.returncode: + break + (RESULTS / "builds.json").write_text(json.dumps(rows, indent=2)) + finally: + save(BASE) + + +def extras(): + closure = """subsecond::call(|| { + std::hint::black_box(&capture_guard); + render(&state) + })""" + cases = { + "single_capture": BASE.replace(closure, "subsecond::call(|| render(&state))"), + "explicit_hotfn": BASE.replace(closure, "subsecond::HotFn::current(render).call((&state,))"), + "explicit_hotfn_signature": BASE.replace(closure, "subsecond::HotFn::current(render).call((&state,))"), + "exported_static": BASE.replace("static GLOBAL:", "#[unsafe(no_mangle)]\npub static GLOBAL:"), + "cached_trait_object": BASE.replace("// FIELD_PROBE", "cached: Box<dyn Label>,") + .replace("// FIELD_INIT", "cached: Box::new(Panel { width: 42, height: 24 }),") + .replace("state.panel.label()", "state.cached.label()"), + } + rows = {} + for name, base in cases.items(): + if args.case and args.case != name: + continue + save(base) + session = Session("extra-" + name) + try: + session.ready() + text = base.replace("let revision = 0;", "let revision = 93;") + if name == "explicit_hotfn_signature": + text = text.replace("fn render(state: &AppState)", "fn render(state: &AppState, tone: u64)") + text = text.replace("let revision = 93;", "let revision = tone;") + text = text.replace(".call((&state,))", ".call((&state, 93))") + if name == "exported_static": + text = text.replace("AtomicU64::new(1000)", "AtomicU64::new(9000)") + if name == "cached_trait_object": + text = text.replace('"t0:{}x{}"', '"t1:{}x{}"') + rows[name] = session.edit(text, lambda f: parse_output(f)["rev"] == "93", timeout=5) + rows[name]["all_patch_ns"] = session.patch_ns + finally: + session.close() + save(BASE) + filename = f"extra-{args.case}.json" if args.case else "extras.json" + (RESULTS / filename).write_text(json.dumps(rows, indent=2)) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("mode", choices=["benchmark", "probes", "builds", "extras"]) + parser.add_argument("--case", help="Run only this extra probe") + args = parser.parse_args() + globals()[args.mode]() diff --git a/app/vendor/rune/spikes/hot-patch/src/main.rs b/app/vendor/rune/spikes/hot-patch/src/main.rs new file mode 100644 index 0000000..2636968 --- /dev/null +++ b/app/vendor/rune/spikes/hot-patch/src/main.rs @@ -0,0 +1,99 @@ +use std::{ + cell::Cell, + io::{self, Write}, + sync::atomic::{AtomicU64, Ordering}, + time::{Duration, Instant, SystemTime, UNIX_EPOCH}, +}; + +#[repr(C)] +struct Panel { + width: u64, + height: u64, +} + +// repr(C) makes the append-only layout probe deterministic. It does NOT make +// accessing a new field on an existing old-layout instance safe. +#[repr(C)] +struct AppState { + counter: u64, + values: Vec<u64>, + panel: Panel, + // FIELD_PROBE +} + +static GLOBAL: AtomicU64 = AtomicU64::new(1000); +thread_local! { + static LOCAL: Cell<u64> = const { Cell::new(2000) }; +} + +trait Label { + fn label(&self) -> String; +} + +impl Label for Panel { + fn label(&self) -> String { + format!("t0:{}x{}", self.width, self.height) + } +} + +fn generic<T: std::fmt::Display>(value: T) -> String { + format!("g0:{value}") +} + +fn render(state: &AppState) -> String { + let revision = 0; // REVISION + let closure = |value: u64| value + 10; + let global = GLOBAL.fetch_add(1, Ordering::Relaxed); + let local = LOCAL.with(|cell| { + let value = cell.get(); + cell.set(value + 1); + value + }); + format!( + "rev={revision};value={};generic={};closure={};trait={};static={global};tls={local};layout={}", + state.values[0], + generic(state.counter), + closure(state.counter), + state.panel.label(), + std::mem::size_of::<AppState>(), + ) +} + +fn epoch_ns() -> u128 { + SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_nanos() +} + +fn main() { + // The devtools connection includes the ASLR reference and PID handshake. + // This binary never creates a Dioxus VirtualDom, UI, renderer, or window. + subsecond::register_handler(std::sync::Arc::new(|| println!("PATCH ns={}", epoch_ns()))); + dioxus_devtools::connect_subsecond(); + let mut state = AppState { + counter: 0, + values: vec![73, 19, 41], + panel: Panel { width: 800, height: 600 }, + // FIELD_INIT + }; + let period = Duration::from_nanos(1_000_000_000 / 120); + let mut next_tick = Instant::now(); + let capture_guard = 123_u64; + loop { + state.counter += 1; + state.values[0] += 1; + // 0.7.10 mistakes pointer-sized closures for function pointers. Capture + // two references so this closure follows the closure dispatch path. + let output = subsecond::call(|| { + std::hint::black_box(&capture_guard); + render(&state) + }); + println!( + "FRAME {{\"ns\":{},\"pid\":{},\"counter\":{},\"vec0\":{},\"vec_ptr\":{},\"state_addr\":{},\"panel_width\":{},\"output\":\"{}\"}}", + epoch_ns(), std::process::id(), state.counter, state.values[0], + state.values.as_ptr() as usize, &state as *const AppState as usize, + state.panel.width, output, + ); + io::stdout().flush().unwrap(); + next_tick += period; + std::thread::sleep(next_tick.saturating_duration_since(Instant::now())); + } +} diff --git a/app/vendor/rune/themes/opencode/Cargo.toml b/app/vendor/rune/themes/opencode/Cargo.toml new file mode 100644 index 0000000..5458f23 --- /dev/null +++ b/app/vendor/rune/themes/opencode/Cargo.toml @@ -0,0 +1,18 @@ +[package] +name = "rune-theme-opencode" +version = "0.0.1" +edition.workspace = true +license.workspace = true +description = "OpenCode's design language (@opencode/ui tokens, fonts, icons) as a rune-kit theme." + +[dependencies] +rune = { workspace = true } +rune-kit = { workspace = true } +serde_json = { workspace = true } + +[dev-dependencies] +rune = { workspace = true, default-features = true } +rune-kit = { workspace = true, default-features = true } + +[lints] +workspace = true diff --git a/app/vendor/rune/themes/opencode/assets/fonts/IBMPlexMono-LICENSE.txt b/app/vendor/rune/themes/opencode/assets/fonts/IBMPlexMono-LICENSE.txt new file mode 100644 index 0000000..01497cc --- /dev/null +++ b/app/vendor/rune/themes/opencode/assets/fonts/IBMPlexMono-LICENSE.txt @@ -0,0 +1,93 @@ +Copyright © 2017 IBM Corp. with Reserved Font Name "Plex" + +This Font Software is licensed under the SIL Open Font License, Version 1.1. + +This license is copied below, and is also available with a FAQ at: http://scripts.sil.org/OFL + + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. diff --git a/app/vendor/rune/themes/opencode/assets/fonts/IBMPlexMono-Medium.ttf b/app/vendor/rune/themes/opencode/assets/fonts/IBMPlexMono-Medium.ttf new file mode 100644 index 0000000..f24cbab Binary files /dev/null and b/app/vendor/rune/themes/opencode/assets/fonts/IBMPlexMono-Medium.ttf differ diff --git a/app/vendor/rune/themes/opencode/assets/fonts/IBMPlexMono-Regular.ttf b/app/vendor/rune/themes/opencode/assets/fonts/IBMPlexMono-Regular.ttf new file mode 100644 index 0000000..f730099 Binary files /dev/null and b/app/vendor/rune/themes/opencode/assets/fonts/IBMPlexMono-Regular.ttf differ diff --git a/app/vendor/rune/themes/opencode/assets/fonts/Inter-LICENSE.txt b/app/vendor/rune/themes/opencode/assets/fonts/Inter-LICENSE.txt new file mode 100644 index 0000000..9b2ca37 --- /dev/null +++ b/app/vendor/rune/themes/opencode/assets/fonts/Inter-LICENSE.txt @@ -0,0 +1,92 @@ +Copyright (c) 2016 The Inter Project Authors (https://github.com/rsms/inter) + +This Font Software is licensed under the SIL Open Font License, Version 1.1. +This license is copied below, and is also available with a FAQ at: +http://scripts.sil.org/OFL + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION AND CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. diff --git a/app/vendor/rune/themes/opencode/assets/fonts/InterVariable.ttf b/app/vendor/rune/themes/opencode/assets/fonts/InterVariable.ttf new file mode 100644 index 0000000..e31b51e Binary files /dev/null and b/app/vendor/rune/themes/opencode/assets/fonts/InterVariable.ttf differ diff --git a/app/vendor/rune/themes/opencode/assets/theme.json b/app/vendor/rune/themes/opencode/assets/theme.json new file mode 100644 index 0000000..b280042 --- /dev/null +++ b/app/vendor/rune/themes/opencode/assets/theme.json @@ -0,0 +1,2521 @@ +{ + "name": "OpenCode", + "blend": { + "mode": "srgb", + "over": "v2-background-bg-base" + }, + "light": { + "amber-dark-1": "#1f1300ff", + "amber-dark-10": "#ffcb47ff", + "amber-dark-11": "#f1a10dff", + "amber-dark-12": "#fef3ddff", + "amber-dark-2": "#271700ff", + "amber-dark-3": "#341c00ff", + "amber-dark-4": "#3f2200ff", + "amber-dark-5": "#4a2900ff", + "amber-dark-6": "#573300ff", + "amber-dark-7": "#693f05ff", + "amber-dark-8": "#824e00ff", + "amber-dark-9": "#ffb224ff", + "amber-dark-alpha-1": "#00000000", + "amber-dark-alpha-10": "#ffce48f9", + "amber-dark-alpha-11": "#ffab0eef", + "amber-dark-alpha-12": "#fff8e1f9", + "amber-dark-alpha-2": "#ff80000a", + "amber-dark-alpha-3": "#ff740016", + "amber-dark-alpha-4": "#ff7c0023", + "amber-dark-alpha-5": "#ff850030", + "amber-dark-alpha-6": "#ff96003f", + "amber-dark-alpha-7": "#ff980f54", + "amber-dark-alpha-8": "#ff990070", + "amber-dark-alpha-9": "#ffb625f9", + "amber-darkalpha-1": "#00000000", + "amber-darkalpha-10": "#ffce48f9", + "amber-darkalpha-11": "#ffab0eef", + "amber-darkalpha-12": "#fff8e1f9", + "amber-darkalpha-2": "#ff80000a", + "amber-darkalpha-3": "#ff740016", + "amber-darkalpha-4": "#ff7c0023", + "amber-darkalpha-5": "#ff850030", + "amber-darkalpha-6": "#ff96003f", + "amber-darkalpha-7": "#ff980f54", + "amber-darkalpha-8": "#ff990070", + "amber-darkalpha-9": "#ffb625f9", + "amber-light-1": "#fefdfbff", + "amber-light-10": "#ffa01cff", + "amber-light-11": "#ad5700ff", + "amber-light-12": "#4e2009ff", + "amber-light-2": "#fff9edff", + "amber-light-3": "#fff4d5ff", + "amber-light-4": "#ffecbcff", + "amber-light-5": "#ffe3a2ff", + "amber-light-6": "#ffd386ff", + "amber-light-7": "#f3ba63ff", + "amber-light-8": "#ee9d2bff", + "amber-light-9": "#ffb224ff", + "amber-light-alpha-1": "#cc990005", + "amber-light-alpha-10": "#ff9500e2", + "amber-light-alpha-11": "#ab5300f9", + "amber-light-alpha-12": "#481800f4", + "amber-light-alpha-2": "#ffa50011", + "amber-light-alpha-3": "#ffbe002b", + "amber-light-alpha-4": "#ffb60042", + "amber-light-alpha-5": "#ffb3005e", + "amber-light-alpha-6": "#ffa30077", + "amber-light-alpha-7": "#eb8d009b", + "amber-light-alpha-8": "#ea8900d3", + "amber-light-alpha-9": "#ffa700db", + "amber-lightalpha-1": "#cc990005", + "amber-lightalpha-10": "#ff9500e2", + "amber-lightalpha-11": "#ab5300f9", + "amber-lightalpha-12": "#481800f4", + "amber-lightalpha-2": "#ffa50011", + "amber-lightalpha-3": "#ffbe002b", + "amber-lightalpha-4": "#ffb60042", + "amber-lightalpha-5": "#ffb3005e", + "amber-lightalpha-6": "#ffa30077", + "amber-lightalpha-7": "#eb8d009b", + "amber-lightalpha-8": "#ea8900d3", + "amber-lightalpha-9": "#ffa700db", + "apple-dark-1": "#0c140bff", + "apple-dark-10": "#17bb0dff", + "apple-dark-11": "#37db2eff", + "apple-dark-12": "#aff7a8ff", + "apple-dark-2": "#121b11ff", + "apple-dark-3": "#152d13ff", + "apple-dark-4": "#123d0fff", + "apple-dark-5": "#174b14ff", + "apple-dark-6": "#1d5b19ff", + "apple-dark-7": "#226c1eff", + "apple-dark-8": "#267f20ff", + "apple-dark-9": "#12c905ff", + "apple-dark-alpha-1": "#00bf0004", + "apple-dark-alpha-10": "#19fe0db7", + "apple-dark-alpha-11": "#3dfe33d9", + "apple-dark-alpha-12": "#b4feacf7", + "apple-dark-alpha-2": "#2eff170b", + "apple-dark-alpha-3": "#33ff221e", + "apple-dark-alpha-4": "#15fa0530", + "apple-dark-alpha-5": "#28fb1c3f", + "apple-dark-alpha-6": "#36fc2950", + "apple-dark-alpha-7": "#3eff3462", + "apple-dark-alpha-8": "#3fff3276", + "apple-dark-alpha-9": "#12fe03c6", + "apple-light-1": "#fafefaff", + "apple-light-10": "#00bd00ff", + "apple-light-11": "#008600ff", + "apple-light-12": "#184115ff", + "apple-light-2": "#f4fcf3ff", + "apple-light-3": "#e1fadeff", + "apple-light-4": "#cef6c9ff", + "apple-light-5": "#b9efb3ff", + "apple-light-6": "#9fe598ff", + "apple-light-7": "#7dd676ff", + "apple-light-8": "#43c23bff", + "apple-light-9": "#12c905ff", + "apple-light-alpha-1": "#00cc0005", + "apple-light-alpha-10": "#00bd00ff", + "apple-light-alpha-11": "#008600ff", + "apple-light-alpha-12": "#033000ea", + "apple-light-alpha-2": "#15bf000c", + "apple-light-alpha-3": "#17d80021", + "apple-light-alpha-4": "#18d40036", + "apple-light-alpha-5": "#14c9004c", + "apple-light-alpha-6": "#11bf0067", + "apple-light-alpha-7": "#0db30089", + "apple-light-alpha-8": "#0ab000c4", + "apple-light-alpha-9": "#0dc800fa", + "avatar-background-cyan": "#e7f9fbff", + "avatar-background-lime": "#eefadcff", + "avatar-background-mint": "#e1fbf4ff", + "avatar-background-orange": "#fff1e7ff", + "avatar-background-pink": "#feeef8ff", + "avatar-background-purple": "#f9f1feff", + "avatar-text-cyan": "#0894b3ff", + "avatar-text-lime": "#5d770dff", + "avatar-text-mint": "#147d6fff", + "avatar-text-orange": "#ed5f00ff", + "avatar-text-pink": "#cd1d8dff", + "avatar-text-purple": "#8445bcff", + "background-base": "#f8f8f8ff", + "background-strong": "#f8f8f8ff", + "background-stronger": "#fcfcfcff", + "background-weak": "#edededff", + "base": "#ebebebff", + "base2": "#ebebebff", + "base3": "#ebebebff", + "black": "#000000ff", + "blue-dark-1": "#0e161fff", + "blue-dark-10": "#389effff", + "blue-dark-11": "#51a8ffff", + "blue-dark-12": "#eaf6ffff", + "blue-dark-2": "#0f1b2dff", + "blue-dark-3": "#0f233cff", + "blue-dark-4": "#10294bff", + "blue-dark-5": "#0e2f57ff", + "blue-dark-6": "#0c3768ff", + "blue-dark-7": "#094280ff", + "blue-dark-8": "#0854a4ff", + "blue-dark-9": "#0091ffff", + "blue-dark-alpha-1": "#00000000", + "blue-dark-alpha-10": "#38a2fff9", + "blue-dark-alpha-11": "#51abfff9", + "blue-dark-alpha-12": "#effbfff9", + "blue-dark-alpha-2": "#1155ff0f", + "blue-dark-alpha-3": "#1675ff23", + "blue-dark-alpha-4": "#1478ff33", + "blue-dark-alpha-5": "#1079ff3f", + "blue-dark-alpha-6": "#097bff51", + "blue-dark-alpha-7": "#057dff70", + "blue-dark-alpha-8": "#057dff99", + "blue-dark-alpha-9": "#0094fff9", + "blue-light-1": "#f9fcffff", + "blue-light-10": "#007fefff", + "blue-light-11": "#0069dbff", + "blue-light-12": "#00254dff", + "blue-light-2": "#f5faffff", + "blue-light-3": "#eaf4ffff", + "blue-light-4": "#e0efffff", + "blue-light-5": "#cde6fdff", + "blue-light-6": "#b9d9f8ff", + "blue-light-7": "#96c7f2ff", + "blue-light-8": "#5cafeeff", + "blue-light-9": "#0091ffff", + "blue-light-alpha-1": "#0099ff05", + "blue-light-alpha-10": "#007feff9", + "blue-light-alpha-11": "#0066dbf9", + "blue-light-alpha-12": "#002047f9", + "blue-light-alpha-2": "#0080ff0a", + "blue-light-alpha-3": "#0078ff11", + "blue-light-alpha-4": "#007fff1e", + "blue-light-alpha-5": "#0080ef30", + "blue-light-alpha-6": "#0077e247", + "blue-light-alpha-7": "#0078df68", + "blue-light-alpha-8": "#0083e6a0", + "blue-light-alpha-9": "#0090fff9", + "border-active": "#a6a5a4ff", + "border-base": "#c1c0c0ff", + "border-color": "#ffffffff", + "border-critical-base": "#faaa9bff", + "border-critical-hover": "#ff806aff", + "border-critical-selected": "#fb543cff", + "border-disabled": "#cac9c9ff", + "border-focus": "#a6a5a4ff", + "border-hover": "#b4b2b2ff", + "border-info-base": "#f39cf9ff", + "border-info-hover": "#e37cebff", + "border-info-selected": "#b045b9ff", + "border-interactive-active": "#054dfdff", + "border-interactive-base": "#a3c1fdff", + "border-interactive-disabled": "#adacabff", + "border-interactive-focus": "#054dfdff", + "border-interactive-hover": "#83aaf7ff", + "border-interactive-selected": "#054dfdff", + "border-selected": "#054dfdfc", + "border-strong-active": "#8b8988ff", + "border-strong-base": "#a6a5a4ff", + "border-strong-disabled": "#d3d2d2ff", + "border-strong-focus": "#8b8988ff", + "border-strong-hover": "#999796ff", + "border-strong-selected": "#c0d4fc99", + "border-success-base": "#2ce822ff", + "border-success-hover": "#35cc2dff", + "border-success-selected": "#1ac90fff", + "border-warning-base": "#dec025ff", + "border-warning-hover": "#c3aa2eff", + "border-warning-selected": "#ffdc20ff", + "border-weak-active": "#c1c0c0ff", + "border-weak-base": "#dbdbdbff", + "border-weak-disabled": "#e1e0e0ff", + "border-weak-focus": "#c1c0c0ff", + "border-weak-hover": "#cfcecdff", + "border-weak-selected": "#d1e1fd80", + "border-weaker-active": "#0000001e", + "border-weaker-base": "#e8e8e8ff", + "border-weaker-disabled": "#00000009", + "border-weaker-focus": "#0000001e", + "border-weaker-hover": "#00000013", + "border-weaker-selected": "#004bff29", + "button-ghost-hover": "#ebebebff", + "button-ghost-hover2": "#e2e2e2ff", + "button-primary-base": "#1d1917ff", + "button-secondary-base": "#f8f8f8ff", + "button-secondary-hover": "#f2f2f2ff", + "cobalt-dark-1": "#091120ff", + "cobalt-dark-10": "#0038eeff", + "cobalt-dark-11": "#89b5ffff", + "cobalt-dark-12": "#cde2ffff", + "cobalt-dark-2": "#0d172bff", + "cobalt-dark-3": "#0c2255ff", + "cobalt-dark-4": "#0c2a74ff", + "cobalt-dark-5": "#113489ff", + "cobalt-dark-6": "#18409bff", + "cobalt-dark-7": "#204cb1ff", + "cobalt-dark-8": "#2558d0ff", + "cobalt-dark-9": "#034cffff", + "cobalt-dark-alpha-1": "#000ff011", + "cobalt-dark-alpha-10": "#003bffed", + "cobalt-dark-alpha-11": "#89b5ffff", + "cobalt-dark-alpha-12": "#cde2ffff", + "cobalt-dark-alpha-2": "#0049ff1c", + "cobalt-dark-alpha-3": "#004dff49", + "cobalt-dark-alpha-4": "#074cfd6b", + "cobalt-dark-alpha-5": "#1257ff81", + "cobalt-dark-alpha-6": "#1d62ff94", + "cobalt-dark-alpha-7": "#2768feac", + "cobalt-dark-alpha-8": "#2a6affcd", + "cobalt-dark-alpha-9": "#034cffff", + "cobalt-light-1": "#fcfdffff", + "cobalt-light-10": "#0443deff", + "cobalt-light-11": "#1251ecff", + "cobalt-light-12": "#0f2b6cff", + "cobalt-light-2": "#f5faffff", + "cobalt-light-3": "#eaf2ffff", + "cobalt-light-4": "#daeaffff", + "cobalt-light-5": "#c8e0ffff", + "cobalt-light-6": "#b4d2ffff", + "cobalt-light-7": "#98bfffff", + "cobalt-light-8": "#73a4ffff", + "cobalt-light-9": "#034cffff", + "cobalt-light-alpha-1": "#0055ff03", + "cobalt-light-alpha-10": "#0040ddfb", + "cobalt-light-alpha-11": "#0044ebed", + "cobalt-light-alpha-12": "#001e63f0", + "cobalt-light-alpha-2": "#0080ff0a", + "cobalt-light-alpha-3": "#0061ff15", + "cobalt-light-alpha-4": "#006eff25", + "cobalt-light-alpha-5": "#006fff37", + "cobalt-light-alpha-6": "#0066ff4b", + "cobalt-light-alpha-7": "#0061ff67", + "cobalt-light-alpha-8": "#0059ff8c", + "cobalt-light-alpha-9": "#004afffc", + "color-background-base": "#f8f8f8ff", + "color-background-stronger": "#fcfcfcff", + "color-base": "#ebebebff", + "color-border-base": "#c1c0c0ff", + "color-border-focus": "#a6a5a4ff", + "color-border-weak-base": "#dbdbdbff", + "color-border-weaker-base": "#e8e8e8ff", + "color-icon-base": "#8f8f8fff", + "color-icon-critical-base": "#fa3012ff", + "color-icon-info-active": "#912a9aff", + "color-icon-strong-base": "#1d1917ff", + "color-icon-success-base": "#0abe00ff", + "color-icon-warning-base": "#f9b13fff", + "color-icon-weak-base": "#c7c7c7ff", + "color-input-base": "#f8f8f8ff", + "color-surface-base": "#f8f8f8ff", + "color-surface-base-active": "#e2e2e2ff", + "color-surface-base-hover": "#0000000a", + "color-surface-raised-base": "#f3f3f3ff", + "color-surface-raised-base-hover": "#edededff", + "color-surface-raised-stronger-non-alpha": "#ffffffff", + "color-syntax-keyword": "#c83d8bff", + "color-syntax-property": "#d16427ff", + "color-syntax-type": "#5230c2ff", + "color-text-base": "#6f6f6fff", + "color-text-interactive-base": "#0445e6ff", + "color-text-on-critical-base": "#000000ff", + "color-text-strong": "#171717ff", + "color-text-weak": "#8f8f8fff", + "color-text-weaker": "#c7c7c7ff", + "color-v2-background-bg-base": "#ffffffff", + "color-v2-background-bg-deep": "#fafafaff", + "color-v2-background-bg-inverse": "#161616ff", + "color-v2-background-bg-layer-01": "#fafafaff", + "color-v2-background-bg-layer-02": "#f2f2f2ff", + "color-v2-background-bg-layer-03": "#eeeeeeff", + "color-v2-background-bg-layer-04": "#dbdbdbff", + "color-v2-border-border-base": "#0000001a", + "color-v2-border-border-focus": "#7698fdff", + "color-v2-border-border-muted": "#00000014", + "color-v2-border-border-strong": "#00000033", + "color-v2-icon-icon-accent": "#3b5cf6ff", + "color-v2-icon-icon-base": "#3a3a3aff", + "color-v2-icon-icon-contrast": "#fafafaff", + "color-v2-icon-icon-faint": "#aeaeaeff", + "color-v2-icon-icon-muted": "#808080ff", + "color-v2-overlay-simple-overlay-hover": "#0000000a", + "color-v2-overlay-simple-overlay-pressed": "#00000014", + "color-v2-state-fg-danger": "#b82d35ff", + "color-v2-text-text-accent": "#3b5cf6ff", + "color-v2-text-text-base": "#161616ff", + "color-v2-text-text-faint": "#808080ff", + "color-v2-text-text-muted": "#5c5c5cff", + "coral-dark-1": "#160f0eff", + "coral-dark-10": "#f5ccc6ff", + "coral-dark-11": "#e2a8a0ff", + "coral-dark-12": "#fcd3cdff", + "coral-dark-2": "#1f1413ff", + "coral-dark-3": "#391613ff", + "coral-dark-4": "#481b17ff", + "coral-dark-5": "#542621ff", + "coral-dark-6": "#63332dff", + "coral-dark-7": "#77453fff", + "coral-dark-8": "#935e57ff", + "coral-dark-9": "#ffd6d0ff", + "coral-dark-alpha-1": "#d4000006", + "coral-dark-alpha-10": "#fed3cdf5", + "coral-dark-alpha-11": "#ffbdb4e0", + "coral-dark-alpha-12": "#ffd6cffc", + "coral-dark-alpha-2": "#ff44330f", + "coral-dark-alpha-3": "#ff2f1e2b", + "coral-dark-alpha-4": "#ff3d2b3b", + "coral-dark-alpha-5": "#ff5c4a48", + "coral-dark-alpha-6": "#ff746358", + "coral-dark-alpha-7": "#fd897b6e", + "coral-dark-alpha-8": "#fd9d908c", + "coral-dark-alpha-9": "#ffd6d0ff", + "coral-light-1": "#fffcfcff", + "coral-light-10": "#a26c65ff", + "coral-light-11": "#9c665fff", + "coral-light-12": "#592a24ff", + "coral-light-2": "#fff8f7ff", + "coral-light-3": "#ffebe8ff", + "coral-light-4": "#ffdbd5ff", + "coral-light-5": "#ffcdc5ff", + "coral-light-6": "#f9beb5ff", + "coral-light-7": "#e9aea6ff", + "coral-light-8": "#d49b93ff", + "coral-light-9": "#af7871ff", + "coral-light-alpha-1": "#ff000003", + "coral-light-alpha-10": "#650c009a", + "coral-light-alpha-11": "#610b00a0", + "coral-light-alpha-12": "#3e0700db", + "coral-light-alpha-2": "#ff200008", + "coral-light-alpha-3": "#ff210017", + "coral-light-alpha-4": "#ff24002a", + "coral-light-alpha-5": "#ff23003a", + "coral-light-alpha-6": "#ea1f004a", + "coral-light-alpha-7": "#c0170059", + "coral-light-alpha-8": "#9913006c", + "coral-light-alpha-9": "#6f0d008e", + "cyan-dark-9": "#0091ffff", + "cyan-light-9": "#0091ffff", + "ember-dark-1": "#170f0dff", + "ember-dark-10": "#ee462dff", + "ember-dark-11": "#ff917bff", + "ember-dark-12": "#ffd1c8ff", + "ember-dark-2": "#201412ff", + "ember-dark-3": "#3c140dff", + "ember-dark-4": "#530e05ff", + "ember-dark-5": "#631409ff", + "ember-dark-6": "#742216ff", + "ember-dark-7": "#8d3324ff", + "ember-dark-8": "#b64330ff", + "ember-dark-9": "#fc533aff", + "ember-dark-alpha-1": "#db000007", + "ember-dark-alpha-10": "#ff4a2fed", + "ember-dark-alpha-11": "#ff917bff", + "ember-dark-alpha-12": "#ffd1c8ff", + "ember-dark-alpha-2": "#f03c1e11", + "ember-dark-alpha-3": "#fa21002f", + "ember-dark-alpha-4": "#ff070047", + "ember-dark-alpha-5": "#ff1a0058", + "ember-dark-alpha-6": "#fd391d6b", + "ember-dark-alpha-7": "#ff523685", + "ember-dark-alpha-8": "#ff593eb1", + "ember-dark-alpha-9": "#ff553bfc", + "ember-light-1": "#fffcfbff", + "ember-light-10": "#ef442aff", + "ember-light-11": "#da3319ff", + "ember-light-12": "#5c281fff", + "ember-light-2": "#fff6f3ff", + "ember-light-3": "#ffe9e4ff", + "ember-light-4": "#ffd7ccff", + "ember-light-5": "#ffc8baff", + "ember-light-6": "#ffb7a6ff", + "ember-light-7": "#ffa392ff", + "ember-light-8": "#f68975ff", + "ember-light-9": "#fc533aff", + "ember-light-alpha-1": "#ff400004", + "ember-light-alpha-10": "#ec1f00d5", + "ember-light-alpha-11": "#d61d00e6", + "ember-light-alpha-12": "#450a00e0", + "ember-light-alpha-2": "#ff40000c", + "ember-light-alpha-3": "#ff2f001b", + "ember-light-alpha-4": "#ff370033", + "ember-light-alpha-5": "#ff340045", + "ember-light-alpha-6": "#ff310059", + "ember-light-alpha-7": "#ff28006d", + "ember-light-alpha-8": "#ee25008a", + "ember-light-alpha-9": "#fb2200c5", + "gray-dark-1": "#131010ff", + "gray-dark-10": "#7f7979ff", + "gray-dark-11": "#b7b1b1ff", + "gray-dark-12": "#f1ececff", + "gray-dark-2": "#1b1818ff", + "gray-dark-3": "#252121ff", + "gray-dark-4": "#2d2828ff", + "gray-dark-5": "#343030ff", + "gray-dark-6": "#3e3939ff", + "gray-dark-7": "#4b4646ff", + "gray-dark-8": "#645f5fff", + "gray-dark-9": "#716c6bff", + "gray-dark-alpha-1": "#aa555503", + "gray-dark-alpha-10": "#fbf4f476", + "gray-dark-alpha-11": "#fcf9f9b2", + "gray-dark-alpha-12": "#fdfbfbf0", + "gray-dark-alpha-2": "#e8d1d10b", + "gray-dark-alpha-3": "#e8d1d116", + "gray-dark-alpha-4": "#eedddd1e", + "gray-dark-alpha-5": "#f8ebeb26", + "gray-dark-alpha-6": "#f5eaea31", + "gray-dark-alpha-7": "#f7ebeb3f", + "gray-dark-alpha-8": "#f9f6f659", + "gray-dark-alpha-9": "#faf5f567", + "gray-light-1": "#fdfcfcff", + "gray-light-10": "#848181ff", + "gray-light-11": "#656363ff", + "gray-light-12": "#211e1eff", + "gray-light-2": "#f9f8f8ff", + "gray-light-3": "#f1f0f0ff", + "gray-light-4": "#e9e8e8ff", + "gray-light-5": "#e2e0e0ff", + "gray-light-6": "#dad9d9ff", + "gray-light-7": "#cfcecdff", + "gray-light-8": "#bcbbbbff", + "gray-light-9": "#8e8b8bff", + "gray-light-alpha-1": "#55000003", + "gray-light-alpha-10": "#0300009c", + "gray-light-alpha-11": "#0600007e", + "gray-light-alpha-12": "#020000df", + "gray-light-alpha-2": "#24000007", + "gray-light-alpha-3": "#1100000f", + "gray-light-alpha-4": "#0b000017", + "gray-light-alpha-5": "#1000001f", + "gray-light-alpha-6": "#07000026", + "gray-light-alpha-7": "#0a050032", + "gray-light-alpha-8": "#04000044", + "gray-light-alpha-9": "#07000074", + "icon-active": "#070504ff", + "icon-agent-ask-base": "#2390f4ff", + "icon-agent-build-base": "#054dfdff", + "icon-agent-docs-base": "#fbb23cff", + "icon-agent-plan-base": "#b045b9ff", + "icon-base": "#8f8f8fff", + "icon-brand-base": "#1d1917ff", + "icon-critical-active": "#af210dff", + "icon-critical-base": "#fa3012ff", + "icon-critical-hover": "#fa3012ff", + "icon-diff-add-active": "#053005ff", + "icon-diff-add-base": "#167517ff", + "icon-diff-add-hover": "#053005ff", + "icon-diff-delete-base": "#fa3012ff", + "icon-diff-delete-hover": "#af210dff", + "icon-diff-modified-base": "#675912ff", + "icon-disabled": "#adacabff", + "icon-focus": "#070504ff", + "icon-hover": "#161210ff", + "icon-info-active": "#912a9aff", + "icon-info-base": "#f39cf9ff", + "icon-info-hover": "#e37cebff", + "icon-interactive-base": "#054dfdff", + "icon-invert-base": "#ffffffff", + "icon-on-brand-base": "#000000ff", + "icon-on-brand-hover": "#000000ff", + "icon-on-brand-selected": "#000000ff", + "icon-on-critical-base": "#000000ff", + "icon-on-critical-hover": "#ffffffff", + "icon-on-critical-selected": "#ffffffff", + "icon-on-info-base": "#000000ff", + "icon-on-info-hover": "#ffffffff", + "icon-on-info-selected": "#ffffffff", + "icon-on-interactive-base": "#000000ff", + "icon-on-success-base": "#000000ff", + "icon-on-success-hover": "#ffffffff", + "icon-on-success-selected": "#ffffffff", + "icon-on-warning-base": "#000000ff", + "icon-on-warning-hover": "#ffffffff", + "icon-on-warning-selected": "#ffffffff", + "icon-selected": "#070504ff", + "icon-strong-active": "#020202ff", + "icon-strong-base": "#1d1917ff", + "icon-strong-disabled": "#adacabff", + "icon-strong-focus": "#020202ff", + "icon-strong-hover": "#151313ff", + "icon-strong-selected": "#020202ff", + "icon-success-active": "#197414ff", + "icon-success-base": "#0abe00ff", + "icon-success-hover": "#21bb19ff", + "icon-warning-active": "#805711ff", + "icon-warning-base": "#f9b13fff", + "icon-warning-hover": "#f1a620ff", + "icon-weak-active": "#8d8b89ff", + "icon-weak-base": "#c7c7c7ff", + "icon-weak-disabled": "#d2d2d1ff", + "icon-weak-focus": "#8d8b89ff", + "icon-weak-hover": "#adacabff", + "icon-weak-selected": "#656260ff", + "ink-dark-1": "#101313ff", + "ink-dark-10": "#797f7fff", + "ink-dark-11": "#b1b7b7ff", + "ink-dark-12": "#ecf1f1ff", + "ink-dark-2": "#181b1bff", + "ink-dark-3": "#212525ff", + "ink-dark-4": "#282d2dff", + "ink-dark-5": "#303434ff", + "ink-dark-6": "#393e3eff", + "ink-dark-7": "#464b4bff", + "ink-dark-8": "#5f6464ff", + "ink-dark-9": "#6b7171ff", + "ink-dark-alpha-1": "#55aaaa03", + "ink-dark-alpha-10": "#f4fbfb76", + "ink-dark-alpha-11": "#f9fcfcb2", + "ink-dark-alpha-12": "#fbfdfdf0", + "ink-dark-alpha-2": "#d1e8e80b", + "ink-dark-alpha-3": "#d1e8e816", + "ink-dark-alpha-4": "#ddeeee1e", + "ink-dark-alpha-5": "#ebf8f826", + "ink-dark-alpha-6": "#eaf5f531", + "ink-dark-alpha-7": "#ebf7f73f", + "ink-dark-alpha-8": "#f6f9f959", + "ink-dark-alpha-9": "#f5fafa67", + "ink-light-1": "#fcfdfdff", + "ink-light-10": "#818484ff", + "ink-light-11": "#636565ff", + "ink-light-12": "#1e2121ff", + "ink-light-2": "#f8f9f9ff", + "ink-light-3": "#f0f1f1ff", + "ink-light-4": "#e8e9e9ff", + "ink-light-5": "#e0e2e2ff", + "ink-light-6": "#d9dadaff", + "ink-light-7": "#cdcfcfff", + "ink-light-8": "#bbbcbcff", + "ink-light-9": "#8b8e8eff", + "ink-light-alpha-1": "#00555503", + "ink-light-alpha-10": "#0003039c", + "ink-light-alpha-11": "#0006067e", + "ink-light-alpha-12": "#000202df", + "ink-light-alpha-2": "#00242407", + "ink-light-alpha-3": "#0011110f", + "ink-light-alpha-4": "#000b0b17", + "ink-light-alpha-5": "#0010101f", + "ink-light-alpha-6": "#00070726", + "ink-light-alpha-7": "#000a0a32", + "ink-light-alpha-8": "#00040444", + "ink-light-alpha-9": "#00070774", + "input-active": "#fcfdffff", + "input-base": "#f8f8f8ff", + "input-disabled": "#e6e6e6ff", + "input-focus": "#fcfdffff", + "input-hover": "#f2f2f2ff", + "input-selected": "#e0eafdff", + "lilac-dark-1": "#140f14ff", + "lilac-dark-10": "#e2a8e6ff", + "lilac-dark-11": "#dca2e0ff", + "lilac-dark-12": "#edd8efff", + "lilac-dark-2": "#1d141dff", + "lilac-dark-3": "#2f1e31ff", + "lilac-dark-4": "#3e2440ff", + "lilac-dark-5": "#4a2c4cff", + "lilac-dark-6": "#573859ff", + "lilac-dark-7": "#6c486eff", + "lilac-dark-8": "#8a5e8dff", + "lilac-dark-9": "#edb2f1ff", + "lilac-dark-alpha-1": "#bf00bf04", + "lilac-dark-alpha-10": "#f9b9fee5", + "lilac-dark-alpha-11": "#fab8ffde", + "lilac-dark-alpha-12": "#fde6ffee", + "lilac-dark-alpha-2": "#ff4eff0d", + "lilac-dark-alpha-3": "#e96df823", + "lilac-dark-alpha-4": "#f06efa33", + "lilac-dark-alpha-5": "#f37cfb40", + "lilac-dark-alpha-6": "#f590fc4e", + "lilac-dark-alpha-7": "#fa9eff64", + "lilac-dark-alpha-8": "#f9a5ff85", + "lilac-dark-alpha-9": "#fbbcfff0", + "lilac-light-1": "#fffcffff", + "lilac-light-10": "#9946a0ff", + "lilac-light-11": "#95429cff", + "lilac-light-12": "#590b60ff", + "lilac-light-2": "#fdf7feff", + "lilac-light-3": "#fceafdff", + "lilac-light-4": "#faddfbff", + "lilac-light-5": "#f5cff7ff", + "lilac-light-6": "#eebff1ff", + "lilac-light-7": "#e3a9e7ff", + "lilac-light-8": "#d78bddff", + "lilac-light-9": "#a753aeff", + "lilac-light-alpha-1": "#ff00ff03", + "lilac-light-alpha-10": "#72007cb9", + "lilac-light-alpha-11": "#700079bd", + "lilac-light-alpha-12": "#520059f4", + "lilac-light-alpha-2": "#bf00df08", + "lilac-light-alpha-3": "#db00e715", + "lilac-light-alpha-4": "#da00e122", + "lilac-light-alpha-5": "#ca00d430", + "lilac-light-alpha-6": "#bb00c740", + "lilac-light-alpha-7": "#ac00b856", + "lilac-light-alpha-8": "#a700b474", + "lilac-light-alpha-9": "#7d0087ac", + "markdown-block-quote": "#675912ff", + "markdown-code": "#166c11ff", + "markdown-code-block": "#6f6f6fff", + "markdown-emph": "#675912ff", + "markdown-heading": "#5e5e11ff", + "markdown-horizontal-rule": "#c1c0c0ff", + "markdown-image": "#0040dfff", + "markdown-image-text": "#8c1896ff", + "markdown-link": "#0040dfff", + "markdown-link-text": "#8c1896ff", + "markdown-list-enumeration": "#8c1896ff", + "markdown-list-item": "#0040dfff", + "markdown-strong": "#8c1896ff", + "markdown-text": "#6f6f6fff", + "mint-dark-1": "#0d130cff", + "mint-dark-10": "#bff5bbff", + "mint-dark-11": "#9dde99ff", + "mint-dark-12": "#c4fbc0ff", + "mint-dark-2": "#121a12ff", + "mint-dark-3": "#1a2a19ff", + "mint-dark-4": "#1f3a1eff", + "mint-dark-5": "#264824ff", + "mint-dark-6": "#2d572bff", + "mint-dark-7": "#356733ff", + "mint-dark-8": "#3d7b3bff", + "mint-dark-9": "#c8ffc4ff", + "mint-dark-alpha-1": "#00aa0003", + "mint-dark-alpha-10": "#c6fec2f5", + "mint-dark-alpha-11": "#b4ffafdb", + "mint-dark-alpha-12": "#c7ffc3fa", + "mint-dark-alpha-2": "#39ff3909", + "mint-dark-alpha-3": "#68ff5e1b", + "mint-dark-alpha-4": "#65ff5f2b", + "mint-dark-alpha-5": "#6cff633b", + "mint-dark-alpha-6": "#72ff6b4a", + "mint-dark-alpha-7": "#74fc6f5c", + "mint-dark-alpha-8": "#74ff7072", + "mint-dark-alpha-9": "#c8ffc4f5", + "mint-light-1": "#fafefaff", + "mint-light-10": "#98e793ff", + "mint-light-11": "#318430ff", + "mint-light-12": "#1f461dff", + "mint-light-2": "#f4fcf3ff", + "mint-light-3": "#dbfdd8ff", + "mint-light-4": "#c3fabfff", + "mint-light-5": "#adf2a8ff", + "mint-light-6": "#96e692ff", + "mint-light-7": "#81d47dff", + "mint-light-8": "#6abc67ff", + "mint-light-9": "#9ff29aff", + "mint-light-alpha-1": "#00cc0005", + "mint-light-alpha-10": "#0cc6006c", + "mint-light-alpha-11": "#016700cf", + "mint-light-alpha-12": "#022e00e2", + "mint-light-alpha-2": "#15bf000c", + "mint-light-alpha-3": "#14f20027", + "mint-light-alpha-4": "#10eb0040", + "mint-light-alpha-5": "#0fd90057", + "mint-light-alpha-6": "#09c5006d", + "mint-light-alpha-7": "#08ab0082", + "mint-light-alpha-8": "#058f0098", + "mint-light-alpha-9": "#0dde0065", + "purple-dark-9": "#edb2f1ff", + "purple-light-9": "#a753aeff", + "smoke-dark-1": "#131010ff", + "smoke-dark-10": "#7f7979ff", + "smoke-dark-11": "#b7b1b1ff", + "smoke-dark-12": "#f1ececff", + "smoke-dark-2": "#1b1818ff", + "smoke-dark-3": "#252121ff", + "smoke-dark-4": "#2d2828ff", + "smoke-dark-5": "#343030ff", + "smoke-dark-6": "#3e3939ff", + "smoke-dark-7": "#4b4646ff", + "smoke-dark-8": "#645f5fff", + "smoke-dark-9": "#716c6bff", + "smoke-dark-alpha-1": "#aa555503", + "smoke-dark-alpha-10": "#fbf4f476", + "smoke-dark-alpha-11": "#fcf9f9b2", + "smoke-dark-alpha-12": "#fdfbfbf0", + "smoke-dark-alpha-2": "#e8d1d10b", + "smoke-dark-alpha-3": "#e8d1d116", + "smoke-dark-alpha-4": "#eedddd1e", + "smoke-dark-alpha-5": "#f8ebeb26", + "smoke-dark-alpha-6": "#f5eaea31", + "smoke-dark-alpha-7": "#f7ebeb3f", + "smoke-dark-alpha-8": "#f9f6f659", + "smoke-dark-alpha-9": "#faf5f567", + "smoke-light-1": "#fdfcfcff", + "smoke-light-10": "#848181ff", + "smoke-light-11": "#656363ff", + "smoke-light-12": "#211e1eff", + "smoke-light-2": "#f9f8f8ff", + "smoke-light-3": "#f1f0f0ff", + "smoke-light-4": "#e9e8e8ff", + "smoke-light-5": "#e2e0e0ff", + "smoke-light-6": "#dad9d9ff", + "smoke-light-7": "#cfcecdff", + "smoke-light-8": "#bcbbbbff", + "smoke-light-9": "#8e8b8bff", + "smoke-light-alpha-1": "#55000003", + "smoke-light-alpha-10": "#0300009c", + "smoke-light-alpha-11": "#0600007e", + "smoke-light-alpha-12": "#020000df", + "smoke-light-alpha-2": "#24000007", + "smoke-light-alpha-3": "#1100000f", + "smoke-light-alpha-4": "#0b000017", + "smoke-light-alpha-5": "#1000001f", + "smoke-light-alpha-6": "#07000026", + "smoke-light-alpha-7": "#0a050032", + "smoke-light-alpha-8": "#04000044", + "smoke-light-alpha-9": "#07000074", + "solaris-dark-1": "#13110bff", + "solaris-dark-10": "#f2cb2aff", + "solaris-dark-11": "#fdd63cff", + "solaris-dark-12": "#faebb5ff", + "solaris-dark-2": "#1b180fff", + "solaris-dark-3": "#2a2307ff", + "solaris-dark-4": "#382b00ff", + "solaris-dark-5": "#443500ff", + "solaris-dark-6": "#514307ff", + "solaris-dark-7": "#64551aff", + "solaris-dark-8": "#7f6c25ff", + "solaris-dark-9": "#fcd53aff", + "solaris-dark-alpha-1": "#aa000003", + "solaris-dark-alpha-10": "#fed52bf2", + "solaris-dark-alpha-11": "#ffd83cfd", + "solaris-dark-alpha-12": "#fff0b9fa", + "solaris-dark-alpha-2": "#ffb9000b", + "solaris-dark-alpha-3": "#ffbd001b", + "solaris-dark-alpha-4": "#ffb0002a", + "solaris-dark-alpha-5": "#ffb90037", + "solaris-dark-alpha-6": "#ffcb0045", + "solaris-dark-alpha-7": "#ffd42b59", + "solaris-dark-alpha-8": "#ffd63d76", + "solaris-dark-alpha-9": "#ffd83bfc", + "solaris-light-1": "#fefdfaff", + "solaris-light-10": "#fad337ff", + "solaris-light-11": "#917500ff", + "solaris-light-12": "#433c22ff", + "solaris-light-2": "#fffbeaff", + "solaris-light-3": "#fff6beff", + "solaris-light-4": "#ffee9cff", + "solaris-light-5": "#ffe47cff", + "solaris-light-6": "#f2d775ff", + "solaris-light-7": "#e0c76fff", + "solaris-light-8": "#cdb047ff", + "solaris-light-9": "#ffdc17ff", + "solaris-light-alpha-1": "#cc990005", + "solaris-light-alpha-10": "#f9c700c8", + "solaris-light-alpha-11": "#917500ff", + "solaris-light-alpha-12": "#261e00dd", + "solaris-light-alpha-2": "#ffce0015", + "solaris-light-alpha-3": "#ffdc0041", + "solaris-light-alpha-4": "#ffd30063", + "solaris-light-alpha-5": "#ffca0083", + "solaris-light-alpha-6": "#e7b5008a", + "solaris-light-alpha-7": "#c89c0090", + "solaris-light-alpha-8": "#ba9200b8", + "solaris-light-alpha-9": "#ffd900e8", + "surface-base": "#f8f8f8ff", + "surface-base-active": "#e2e2e2ff", + "surface-base-hover": "#0000000a", + "surface-base-interactive-active": "#eef2ff4d", + "surface-brand-base": "#dddf79ff", + "surface-brand-hover": "#d2d369ff", + "surface-critical-base": "#fff2f0ff", + "surface-critical-strong": "#af210dff", + "surface-critical-weak": "#fde3deff", + "surface-diff-add-base": "#d9ffd6ff", + "surface-diff-add-strong": "#b0f5abff", + "surface-diff-add-stronger": "#8ff78aff", + "surface-diff-add-weak": "#efffeeff", + "surface-diff-add-weaker": "#f9fff8ff", + "surface-diff-delete-base": "#feeeebff", + "surface-diff-delete-strong": "#fec2b6ff", + "surface-diff-delete-stronger": "#fb543cff", + "surface-diff-delete-weak": "#fef8f6ff", + "surface-diff-delete-weaker": "#fffcfbff", + "surface-diff-hidden-base": "#e5e9f2ff", + "surface-diff-hidden-strong": "#d2dbecff", + "surface-diff-hidden-stronger": "#bfcce7ff", + "surface-diff-hidden-weak": "#ebeef4ff", + "surface-diff-hidden-weaker": "#dfe4f0ff", + "surface-diff-skip-base": "#f2f2f2ff", + "surface-diff-unchanged-base": "#00000000", + "surface-float-base": "#1d1917ff", + "surface-float-base-hover": "#3b3735ff", + "surface-info-base": "#fbcffeff", + "surface-info-strong": "#912a9aff", + "surface-info-weak": "#fcdffeff", + "surface-inset-base": "#ebebebff", + "surface-inset-base-hover": "#e2e2e2ff", + "surface-inset-strong": "#e9e9e917", + "surface-inset-strong-hover": "#e9e9e917", + "surface-interactive-base": "#d2e1fdff", + "surface-interactive-hover": "#bfd3fcff", + "surface-interactive-weak": "#f5faffff", + "surface-interactive-weak-hover": "#d2e1fdff", + "surface-raised-base": "#f3f3f3ff", + "surface-raised-base-active": "#e2e2e2ff", + "surface-raised-base-hover": "#edededff", + "surface-raised-strong": "#f8f8f8ff", + "surface-raised-strong-hover": "#ffffffff", + "surface-raised-stronger": "#ffffffff", + "surface-raised-stronger-hover": "#ffffffff", + "surface-raised-stronger-non-alpha": "#ffffffff", + "surface-strong": "#ffffffff", + "surface-stronger-non-alpha": "#ffffffff", + "surface-success-base": "#e6ffe5ff", + "surface-success-strong": "#197414ff", + "surface-success-weak": "#bbffb4ff", + "surface-warning-base": "#fce05aff", + "surface-warning-strong": "#6f6015ff", + "surface-warning-weak": "#feeb92ff", + "surface-weak": "#e2e2e2ff", + "surface-weaker": "#d8d8d7ff", + "syntax-comment": "#5c5c5cff", + "syntax-constant": "#007b80ff", + "syntax-critical": "#b82d35ff", + "syntax-diff-add": "#198b43ff", + "syntax-diff-delete": "#b82d35ff", + "syntax-diff-unknown": "#a753aeff", + "syntax-info": "#8c1896ff", + "syntax-keyword": "#c83d8bff", + "syntax-object": "#171717ff", + "syntax-operator": "#6f6f6fff", + "syntax-primitive": "#c83d8bff", + "syntax-property": "#d16427ff", + "syntax-punctuation": "#6f6f6fff", + "syntax-regexp": "#6f6f6fff", + "syntax-string": "#198b43ff", + "syntax-success": "#197414ff", + "syntax-type": "#5230c2ff", + "syntax-variable": "#171717ff", + "syntax-warning": "#805711ff", + "text-base": "#6f6f6fff", + "text-diff-add-base": "#198b43ff", + "text-diff-add-strong": "#053005ff", + "text-diff-delete-base": "#b82d35ff", + "text-diff-delete-strong": "#4c0903ff", + "text-interactive-base": "#0445e6ff", + "text-invert-base": "#f2f2f2ff", + "text-invert-strong": "#f8f8f8ff", + "text-invert-weak": "#edededff", + "text-invert-weaker": "#e6e6e6ff", + "text-on-brand-base": "#000000ff", + "text-on-brand-strong": "#000000ff", + "text-on-brand-weak": "#000000ff", + "text-on-brand-weaker": "#000000ff", + "text-on-critical-base": "#000000ff", + "text-on-critical-strong": "#ffffffff", + "text-on-critical-weak": "#000000ff", + "text-on-info-base": "#000000ff", + "text-on-info-strong": "#ffffffff", + "text-on-info-weak": "#000000ff", + "text-on-interactive-base": "#000000ff", + "text-on-interactive-weak": "#000000ff", + "text-on-success-base": "#000000ff", + "text-on-success-strong": "#ffffffff", + "text-on-success-weak": "#000000ff", + "text-on-warning-base": "#000000ff", + "text-on-warning-strong": "#ffffffff", + "text-on-warning-weak": "#000000ff", + "text-strong": "#171717ff", + "text-stronger": "#171717ff", + "text-weak": "#8f8f8fff", + "text-weaker": "#c7c7c7ff", + "tw-ring-offset-color": "#ffffffff", + "v2-agent-build-background": "#ebf5ff1a", + "v2-agent-build-border": "#2745c41a", + "v2-agent-build-solid": "#3250dfff", + "v2-agent-explore-background": "#fff5eb1a", + "v2-agent-explore-border": "#cda03233", + "v2-agent-explore-solid": "#ac8833ff", + "v2-agent-plan-background": "#ffebf51a", + "v2-agent-plan-border": "#c83c8c33", + "v2-agent-plan-solid": "#c83d8bff", + "v2-agent-review-solid": "#198b43ff", + "v2-agent-writer-solid": "#623be2ff", + "v2-alpha-dark-0": "#00000000", + "v2-alpha-dark-10": "#0000001a", + "v2-alpha-dark-100": "#000000ff", + "v2-alpha-dark-12": "#0000001f", + "v2-alpha-dark-14": "#00000024", + "v2-alpha-dark-16": "#00000029", + "v2-alpha-dark-2": "#00000005", + "v2-alpha-dark-20": "#00000033", + "v2-alpha-dark-24": "#0000003d", + "v2-alpha-dark-30": "#0000004d", + "v2-alpha-dark-4": "#0000000a", + "v2-alpha-dark-40": "#00000066", + "v2-alpha-dark-50": "#00000080", + "v2-alpha-dark-6": "#0000000f", + "v2-alpha-dark-60": "#00000099", + "v2-alpha-dark-70": "#000000b2", + "v2-alpha-dark-8": "#00000014", + "v2-alpha-dark-80": "#000000cc", + "v2-alpha-dark-90": "#000000e5", + "v2-alpha-light-0": "#00000000", + "v2-alpha-light-10": "#ffffff1a", + "v2-alpha-light-100": "#ffffffff", + "v2-alpha-light-12": "#ffffff1f", + "v2-alpha-light-14": "#ffffff24", + "v2-alpha-light-16": "#ffffff29", + "v2-alpha-light-2": "#ffffff05", + "v2-alpha-light-20": "#ffffff33", + "v2-alpha-light-24": "#ffffff3d", + "v2-alpha-light-30": "#ffffff4d", + "v2-alpha-light-4": "#ffffff0a", + "v2-alpha-light-40": "#ffffff66", + "v2-alpha-light-50": "#ffffff80", + "v2-alpha-light-6": "#ffffff0f", + "v2-alpha-light-60": "#ffffff99", + "v2-alpha-light-70": "#ffffffb2", + "v2-alpha-light-8": "#ffffff14", + "v2-alpha-light-80": "#ffffffcc", + "v2-alpha-light-90": "#ffffffe5", + "v2-avatar-bg-blue": "#3250dfff", + "v2-avatar-bg-cyan": "#0096b8ff", + "v2-avatar-bg-gray": "#5c5c5cff", + "v2-avatar-bg-green": "#2eaf5aff", + "v2-avatar-bg-orange": "#ee7330ff", + "v2-avatar-bg-pink": "#e4429eff", + "v2-avatar-bg-purple": "#623be2ff", + "v2-avatar-bg-red": "#d92e3cff", + "v2-avatar-bg-yellow": "#e7af36ff", + "v2-avatar-border-blue": "#2c47c8ff", + "v2-avatar-border-cyan": "#007d9bff", + "v2-avatar-border-gray": "#3a3a3aff", + "v2-avatar-border-green": "#198b43ff", + "v2-avatar-border-orange": "#d16427ff", + "v2-avatar-border-pink": "#c83d8bff", + "v2-avatar-border-purple": "#5230c2ff", + "v2-avatar-border-red": "#b82d35ff", + "v2-avatar-border-yellow": "#cb9f34ff", + "v2-avatar-fg": "#ffffffff", + "v2-background-bg-accent": "#3b5cf6ff", + "v2-background-bg-base": "#ffffffff", + "v2-background-bg-button-neutral": "#ffffffff", + "v2-background-bg-code-path": "#e2f7fbff", + "v2-background-bg-contrast": "#242424ff", + "v2-background-bg-deep": "#fafafaff", + "v2-background-bg-icon-button-contrast": "#242424ff", + "v2-background-bg-inverse": "#161616ff", + "v2-background-bg-layer-01": "#fafafaff", + "v2-background-bg-layer-02": "#f2f2f2ff", + "v2-background-bg-layer-03": "#eeeeeeff", + "v2-background-bg-layer-04": "#dbdbdbff", + "v2-blue-100": "#f5f8ffff", + "v2-blue-1000": "#263fa9ff", + "v2-blue-1100": "#22388fff", + "v2-blue-1200": "#021945ff", + "v2-blue-200": "#ecf1feff", + "v2-blue-300": "#c3d4fdff", + "v2-blue-400": "#a2bcffff", + "v2-blue-500": "#7698fdff", + "v2-blue-600": "#3b5cf6ff", + "v2-blue-700": "#0b34f4ff", + "v2-blue-800": "#3250dfff", + "v2-blue-900": "#2c47c8ff", + "v2-border-border-base": "#0000001a", + "v2-border-border-focus": "#7698fdff", + "v2-border-border-inverse": "#242424ff", + "v2-border-border-muted": "#00000014", + "v2-border-border-strong": "#00000033", + "v2-cyan-100": "#e2f7fbff", + "v2-cyan-1000": "#005a6eff", + "v2-cyan-1100": "#004756ff", + "v2-cyan-1200": "#00353fff", + "v2-cyan-200": "#c4edf4ff", + "v2-cyan-300": "#a3e4efff", + "v2-cyan-400": "#65d9ebff", + "v2-cyan-500": "#00c5dfff", + "v2-cyan-600": "#00abcfff", + "v2-cyan-700": "#0096b8ff", + "v2-cyan-800": "#007d9bff", + "v2-cyan-900": "#006c85ff", + "v2-green-100": "#e7f9eaff", + "v2-green-1000": "#196130ff", + "v2-green-1100": "#164c26ff", + "v2-green-1200": "#14361dff", + "v2-green-200": "#d0f0d5ff", + "v2-green-300": "#b8e9c1ff", + "v2-green-400": "#96e3a6ff", + "v2-green-500": "#6bd586ff", + "v2-green-600": "#49c970ff", + "v2-green-700": "#2eaf5aff", + "v2-green-800": "#198b43ff", + "v2-green-900": "#1d783cff", + "v2-grey-100": "#fafafaff", + "v2-grey-1000": "#242424ff", + "v2-grey-1100": "#161616ff", + "v2-grey-1200": "#080808ff", + "v2-grey-200": "#f2f2f2ff", + "v2-grey-300": "#eeeeeeff", + "v2-grey-400": "#dbdbdbff", + "v2-grey-50": "#ffffffff", + "v2-grey-500": "#aeaeaeff", + "v2-grey-600": "#808080ff", + "v2-grey-700": "#5c5c5cff", + "v2-grey-800": "#3a3a3aff", + "v2-grey-900": "#2e2e2eff", + "v2-icon-icon-accent": "#3b5cf6ff", + "v2-icon-icon-accent-hover": "#0b34f4ff", + "v2-icon-icon-base": "#3a3a3aff", + "v2-icon-icon-contrast": "#fafafaff", + "v2-icon-icon-faint": "#aeaeaeff", + "v2-icon-icon-inverse": "#ffffffff", + "v2-icon-icon-muted": "#808080ff", + "v2-illustration-illustration-layer-01": "#eeeeeeff", + "v2-illustration-illustration-layer-02": "#dbdbdbff", + "v2-illustration-illustration-layer-03": "#aeaeaeff", + "v2-orange-100": "#fdf2edff", + "v2-orange-1000": "#954c27ff", + "v2-orange-1100": "#723d22ff", + "v2-orange-1200": "#5a2c14ff", + "v2-orange-200": "#ffe7dcff", + "v2-orange-300": "#ffd8c6ff", + "v2-orange-400": "#ffc1a4ff", + "v2-orange-500": "#ffa478ff", + "v2-orange-600": "#ff8648ff", + "v2-orange-700": "#ee7330ff", + "v2-orange-800": "#d16427ff", + "v2-orange-900": "#b35624ff", + "v2-overlay-gradient-depth-overlay-depth-bot": "#00000000", + "v2-overlay-gradient-depth-overlay-depth-top": "#ffffffff", + "v2-overlay-simple-overlay-contrast-hover": "#ffffff1f", + "v2-overlay-simple-overlay-contrast-pressed": "#ffffff3d", + "v2-overlay-simple-overlay-hover": "#0000000a", + "v2-overlay-simple-overlay-pressed": "#00000014", + "v2-overlay-simple-overlay-scrim": "#00000066", + "v2-overlay-simple-tab-active-scrim": "#00000000", + "v2-overlay-simple-tab-hover-scrim": "#00000000", + "v2-overlay-simple-tab-scrim": "#00000000", + "v2-pink-100": "#fdecf3ff", + "v2-pink-1000": "#8c2d61ff", + "v2-pink-1100": "#6f284fff", + "v2-pink-1200": "#5c1d3fff", + "v2-pink-200": "#f7d5e4ff", + "v2-pink-300": "#fabcd8ff", + "v2-pink-400": "#f799c6ff", + "v2-pink-500": "#f26cb2ff", + "v2-pink-600": "#f64aabff", + "v2-pink-700": "#e4429eff", + "v2-pink-800": "#c83d8bff", + "v2-pink-900": "#aa3576ff", + "v2-purple-100": "#ebecfeff", + "v2-purple-1000": "#361f83ff", + "v2-purple-1100": "#2b1b6aff", + "v2-purple-1200": "#221358ff", + "v2-purple-200": "#d5d5fcff", + "v2-purple-300": "#b9b8f5ff", + "v2-purple-400": "#9e99f7ff", + "v2-purple-500": "#8271f8ff", + "v2-purple-600": "#7152f4ff", + "v2-purple-700": "#623be2ff", + "v2-purple-800": "#5230c2ff", + "v2-purple-900": "#442aa1ff", + "v2-red-100": "#fcecebff", + "v2-red-1000": "#7a1f23ff", + "v2-red-1100": "#5f1a1cff", + "v2-red-1200": "#461516ff", + "v2-red-200": "#f6d5d3ff", + "v2-red-300": "#f2bbb7ff", + "v2-red-400": "#f29b96ff", + "v2-red-500": "#f17471ff", + "v2-red-600": "#f1484fff", + "v2-red-700": "#d92e3cff", + "v2-red-800": "#b82d35ff", + "v2-red-900": "#97252bff", + "v2-state-bg-danger": "#fcecebff", + "v2-state-bg-info": "#ecf1feff", + "v2-state-bg-success": "#e7f9eaff", + "v2-state-bg-warning": "#fefaecff", + "v2-state-border-danger": "#f2bbb7ff", + "v2-state-border-info": "#c3d4fdff", + "v2-state-border-success": "#b8e9c1ff", + "v2-state-border-warning": "#f7e5b5ff", + "v2-state-fg-danger": "#b82d35ff", + "v2-state-fg-info": "#3250dfff", + "v2-state-fg-success": "#198b43ff", + "v2-state-fg-warning": "#cb9f34ff", + "v2-text-text-accent": "#3b5cf6ff", + "v2-text-text-accent-hover": "#0b34f4ff", + "v2-text-text-base": "#161616ff", + "v2-text-text-code-accent": "#2c47c8ff", + "v2-text-text-code-path": "#2c47c8ff", + "v2-text-text-contrast": "#ffffffff", + "v2-text-text-faint": "#808080ff", + "v2-text-text-inverse": "#ffffffff", + "v2-text-text-muted": "#5c5c5cff", + "v2-yellow-100": "#fefaecff", + "v2-yellow-1000": "#8e7231ff", + "v2-yellow-1100": "#68552bff", + "v2-yellow-1200": "#4b4025ff", + "v2-yellow-200": "#fcefd0ff", + "v2-yellow-300": "#f7e5b5ff", + "v2-yellow-400": "#f3da9bff", + "v2-yellow-500": "#f2cf76ff", + "v2-yellow-600": "#f6c251ff", + "v2-yellow-700": "#e7af36ff", + "v2-yellow-800": "#cb9f34ff", + "v2-yellow-900": "#ac8833ff", + "white": "#ffffffff", + "yuzu-dark-1": "#11120cff", + "yuzu-dark-10": "#f4f6c1ff", + "yuzu-dark-11": "#dbdda0ff", + "yuzu-dark-12": "#eff1bdff", + "yuzu-dark-2": "#181810ff", + "yuzu-dark-3": "#262614ff", + "yuzu-dark-4": "#313115ff", + "yuzu-dark-5": "#3d3d18ff", + "yuzu-dark-6": "#4a4a21ff", + "yuzu-dark-7": "#5a5b2cff", + "yuzu-dark-8": "#6f6f36ff", + "yuzu-dark-9": "#fdffcaff", + "yuzu-dark-alpha-1": "#00800002", + "yuzu-dark-alpha-10": "#fcfec7f6", + "yuzu-dark-alpha-11": "#fdffb8db", + "yuzu-dark-alpha-12": "#fdffc8f0", + "yuzu-dark-alpha-2": "#ffff0008", + "yuzu-dark-alpha-3": "#ffff3717", + "yuzu-dark-alpha-4": "#f8f82c23", + "yuzu-dark-alpha-5": "#fafa3530", + "yuzu-dark-alpha-6": "#fbfb523e", + "yuzu-dark-alpha-7": "#f9fc6650", + "yuzu-dark-alpha-8": "#ffff6f65", + "yuzu-dark-alpha-9": "#fdffcaff", + "yuzu-light-1": "#fdfdfbff", + "yuzu-light-10": "#d2d384ff", + "yuzu-light-11": "#7c7c2cff", + "yuzu-light-12": "#3d3d23ff", + "yuzu-light-2": "#fbfcebff", + "yuzu-light-3": "#f8fac5ff", + "yuzu-light-4": "#f2f4a5ff", + "yuzu-light-5": "#e9eb9aff", + "yuzu-light-6": "#dcde8eff", + "yuzu-light-7": "#cccd7eff", + "yuzu-light-8": "#b6b768ff", + "yuzu-light-9": "#dcde8dff", + "yuzu-light-alpha-1": "#80800004", + "yuzu-light-alpha-10": "#a2a4007b", + "yuzu-light-alpha-11": "#616100d3", + "yuzu-light-alpha-12": "#1e1e00dc", + "yuzu-light-alpha-2": "#ccd90014", + "yuzu-light-alpha-3": "#e0e9003a", + "yuzu-light-alpha-4": "#dae0005a", + "yuzu-light-alpha-5": "#c7cd0065", + "yuzu-light-alpha-6": "#b0b50071", + "yuzu-light-alpha-7": "#9a9c0081", + "yuzu-light-alpha-8": "#84850097", + "yuzu-light-alpha-9": "#b1b50072" + }, + "dark": { + "amber-dark-1": "#1f1300ff", + "amber-dark-10": "#ffcb47ff", + "amber-dark-11": "#f1a10dff", + "amber-dark-12": "#fef3ddff", + "amber-dark-2": "#271700ff", + "amber-dark-3": "#341c00ff", + "amber-dark-4": "#3f2200ff", + "amber-dark-5": "#4a2900ff", + "amber-dark-6": "#573300ff", + "amber-dark-7": "#693f05ff", + "amber-dark-8": "#824e00ff", + "amber-dark-9": "#ffb224ff", + "amber-dark-alpha-1": "#00000000", + "amber-dark-alpha-10": "#ffce48f9", + "amber-dark-alpha-11": "#ffab0eef", + "amber-dark-alpha-12": "#fff8e1f9", + "amber-dark-alpha-2": "#ff80000a", + "amber-dark-alpha-3": "#ff740016", + "amber-dark-alpha-4": "#ff7c0023", + "amber-dark-alpha-5": "#ff850030", + "amber-dark-alpha-6": "#ff96003f", + "amber-dark-alpha-7": "#ff980f54", + "amber-dark-alpha-8": "#ff990070", + "amber-dark-alpha-9": "#ffb625f9", + "amber-darkalpha-1": "#00000000", + "amber-darkalpha-10": "#ffce48f9", + "amber-darkalpha-11": "#ffab0eef", + "amber-darkalpha-12": "#fff8e1f9", + "amber-darkalpha-2": "#ff80000a", + "amber-darkalpha-3": "#ff740016", + "amber-darkalpha-4": "#ff7c0023", + "amber-darkalpha-5": "#ff850030", + "amber-darkalpha-6": "#ff96003f", + "amber-darkalpha-7": "#ff980f54", + "amber-darkalpha-8": "#ff990070", + "amber-darkalpha-9": "#ffb625f9", + "amber-light-1": "#fefdfbff", + "amber-light-10": "#ffa01cff", + "amber-light-11": "#ad5700ff", + "amber-light-12": "#4e2009ff", + "amber-light-2": "#fff9edff", + "amber-light-3": "#fff4d5ff", + "amber-light-4": "#ffecbcff", + "amber-light-5": "#ffe3a2ff", + "amber-light-6": "#ffd386ff", + "amber-light-7": "#f3ba63ff", + "amber-light-8": "#ee9d2bff", + "amber-light-9": "#ffb224ff", + "amber-light-alpha-1": "#cc990005", + "amber-light-alpha-10": "#ff9500e2", + "amber-light-alpha-11": "#ab5300f9", + "amber-light-alpha-12": "#481800f4", + "amber-light-alpha-2": "#ffa50011", + "amber-light-alpha-3": "#ffbe002b", + "amber-light-alpha-4": "#ffb60042", + "amber-light-alpha-5": "#ffb3005e", + "amber-light-alpha-6": "#ffa30077", + "amber-light-alpha-7": "#eb8d009b", + "amber-light-alpha-8": "#ea8900d3", + "amber-light-alpha-9": "#ffa700db", + "amber-lightalpha-1": "#cc990005", + "amber-lightalpha-10": "#ff9500e2", + "amber-lightalpha-11": "#ab5300f9", + "amber-lightalpha-12": "#481800f4", + "amber-lightalpha-2": "#ffa50011", + "amber-lightalpha-3": "#ffbe002b", + "amber-lightalpha-4": "#ffb60042", + "amber-lightalpha-5": "#ffb3005e", + "amber-lightalpha-6": "#ffa30077", + "amber-lightalpha-7": "#eb8d009b", + "amber-lightalpha-8": "#ea8900d3", + "amber-lightalpha-9": "#ffa700db", + "apple-dark-1": "#0c140bff", + "apple-dark-10": "#17bb0dff", + "apple-dark-11": "#37db2eff", + "apple-dark-12": "#aff7a8ff", + "apple-dark-2": "#121b11ff", + "apple-dark-3": "#152d13ff", + "apple-dark-4": "#123d0fff", + "apple-dark-5": "#174b14ff", + "apple-dark-6": "#1d5b19ff", + "apple-dark-7": "#226c1eff", + "apple-dark-8": "#267f20ff", + "apple-dark-9": "#12c905ff", + "apple-dark-alpha-1": "#00bf0004", + "apple-dark-alpha-10": "#19fe0db7", + "apple-dark-alpha-11": "#3dfe33d9", + "apple-dark-alpha-12": "#b4feacf7", + "apple-dark-alpha-2": "#2eff170b", + "apple-dark-alpha-3": "#33ff221e", + "apple-dark-alpha-4": "#15fa0530", + "apple-dark-alpha-5": "#28fb1c3f", + "apple-dark-alpha-6": "#36fc2950", + "apple-dark-alpha-7": "#3eff3462", + "apple-dark-alpha-8": "#3fff3276", + "apple-dark-alpha-9": "#12fe03c6", + "apple-light-1": "#fafefaff", + "apple-light-10": "#00bd00ff", + "apple-light-11": "#008600ff", + "apple-light-12": "#184115ff", + "apple-light-2": "#f4fcf3ff", + "apple-light-3": "#e1fadeff", + "apple-light-4": "#cef6c9ff", + "apple-light-5": "#b9efb3ff", + "apple-light-6": "#9fe598ff", + "apple-light-7": "#7dd676ff", + "apple-light-8": "#43c23bff", + "apple-light-9": "#12c905ff", + "apple-light-alpha-1": "#00cc0005", + "apple-light-alpha-10": "#00bd00ff", + "apple-light-alpha-11": "#008600ff", + "apple-light-alpha-12": "#033000ea", + "apple-light-alpha-2": "#15bf000c", + "apple-light-alpha-3": "#17d80021", + "apple-light-alpha-4": "#18d40036", + "apple-light-alpha-5": "#14c9004c", + "apple-light-alpha-6": "#11bf0067", + "apple-light-alpha-7": "#0db30089", + "apple-light-alpha-8": "#0ab000c4", + "apple-light-alpha-9": "#0dc800fa", + "avatar-background-cyan": "#0f3058ff", + "avatar-background-lime": "#2b3711ff", + "avatar-background-mint": "#033a34ff", + "avatar-background-orange": "#5f2a06ff", + "avatar-background-pink": "#501b3fff", + "avatar-background-purple": "#432155ff", + "avatar-text-cyan": "#369effff", + "avatar-text-lime": "#c4f042ff", + "avatar-text-mint": "#95f3d9ff", + "avatar-text-orange": "#ff802bff", + "avatar-text-pink": "#e34ba9ff", + "avatar-text-purple": "#9d5bd2ff", + "background-base": "#121212ff", + "background-strong": "#121212ff", + "background-stronger": "#151515ff", + "background-weak": "#191919ff", + "base": "#202020ff", + "base2": "#202020ff", + "base3": "#202020ff", + "black": "#000000ff", + "blue-dark-1": "#0e161fff", + "blue-dark-10": "#389effff", + "blue-dark-11": "#51a8ffff", + "blue-dark-12": "#eaf6ffff", + "blue-dark-2": "#0f1b2dff", + "blue-dark-3": "#0f233cff", + "blue-dark-4": "#10294bff", + "blue-dark-5": "#0e2f57ff", + "blue-dark-6": "#0c3768ff", + "blue-dark-7": "#094280ff", + "blue-dark-8": "#0854a4ff", + "blue-dark-9": "#0091ffff", + "blue-dark-alpha-1": "#00000000", + "blue-dark-alpha-10": "#38a2fff9", + "blue-dark-alpha-11": "#51abfff9", + "blue-dark-alpha-12": "#effbfff9", + "blue-dark-alpha-2": "#1155ff0f", + "blue-dark-alpha-3": "#1675ff23", + "blue-dark-alpha-4": "#1478ff33", + "blue-dark-alpha-5": "#1079ff3f", + "blue-dark-alpha-6": "#097bff51", + "blue-dark-alpha-7": "#057dff70", + "blue-dark-alpha-8": "#057dff99", + "blue-dark-alpha-9": "#0094fff9", + "blue-light-1": "#f9fcffff", + "blue-light-10": "#007fefff", + "blue-light-11": "#0069dbff", + "blue-light-12": "#00254dff", + "blue-light-2": "#f5faffff", + "blue-light-3": "#eaf4ffff", + "blue-light-4": "#e0efffff", + "blue-light-5": "#cde6fdff", + "blue-light-6": "#b9d9f8ff", + "blue-light-7": "#96c7f2ff", + "blue-light-8": "#5cafeeff", + "blue-light-9": "#0091ffff", + "blue-light-alpha-1": "#0099ff05", + "blue-light-alpha-10": "#007feff9", + "blue-light-alpha-11": "#0066dbf9", + "blue-light-alpha-12": "#002047f9", + "blue-light-alpha-2": "#0080ff0a", + "blue-light-alpha-3": "#0078ff11", + "blue-light-alpha-4": "#007fff1e", + "blue-light-alpha-5": "#0080ef30", + "blue-light-alpha-6": "#0077e247", + "blue-light-alpha-7": "#0078df68", + "blue-light-alpha-8": "#0083e6a0", + "blue-light-alpha-9": "#0090fff9", + "border-active": "#5f5d5cff", + "border-base": "#4d4c4aff", + "border-color": "#ffffffff", + "border-critical-base": "#7a1608ff", + "border-critical-hover": "#a22413ff", + "border-critical-selected": "#cb321cff", + "border-disabled": "#444342ff", + "border-focus": "#5f5d5cff", + "border-hover": "#565453ff", + "border-info-base": "#651b6cff", + "border-info-hover": "#83328bff", + "border-info-selected": "#cd73d5ff", + "border-interactive-active": "#1456f7ff", + "border-interactive-base": "#022fa6ff", + "border-interactive-disabled": "#4d4d4bff", + "border-interactive-focus": "#1456f7ff", + "border-interactive-hover": "#0643daff", + "border-interactive-selected": "#1456f7ff", + "border-selected": "#1456f7e6", + "border-strong-active": "#716e6dff", + "border-strong-base": "#5f5d5cff", + "border-strong-disabled": "#3f3e3eff", + "border-strong-focus": "#716e6dff", + "border-strong-hover": "#686664ff", + "border-strong-selected": "#00207d99", + "border-success-base": "#10500dff", + "border-success-hover": "#096e05ff", + "border-success-selected": "#089b00ff", + "border-warning-base": "#4e410bff", + "border-warning-hover": "#6c5903ff", + "border-warning-selected": "#bc9d1eff", + "border-weak-active": "#4d4c4aff", + "border-weak-base": "#282828ff", + "border-weak-disabled": "#373635ff", + "border-weak-focus": "#4d4c4aff", + "border-weak-hover": "#444342ff", + "border-weak-selected": "#02175899", + "border-weaker-active": "#0000001e", + "border-weaker-base": "#232323ff", + "border-weaker-disabled": "#00000009", + "border-weaker-focus": "#0000001e", + "border-weaker-hover": "#00000013", + "border-weaker-selected": "#004bff29", + "button-ghost-hover": "#202020ff", + "button-ghost-hover2": "#282727ff", + "button-primary-base": "#ede8e4ff", + "button-secondary-base": "#191919ff", + "button-secondary-hover": "#1d1d1dff", + "cobalt-dark-1": "#091120ff", + "cobalt-dark-10": "#0038eeff", + "cobalt-dark-11": "#89b5ffff", + "cobalt-dark-12": "#cde2ffff", + "cobalt-dark-2": "#0d172bff", + "cobalt-dark-3": "#0c2255ff", + "cobalt-dark-4": "#0c2a74ff", + "cobalt-dark-5": "#113489ff", + "cobalt-dark-6": "#18409bff", + "cobalt-dark-7": "#204cb1ff", + "cobalt-dark-8": "#2558d0ff", + "cobalt-dark-9": "#034cffff", + "cobalt-dark-alpha-1": "#000ff011", + "cobalt-dark-alpha-10": "#003bffed", + "cobalt-dark-alpha-11": "#89b5ffff", + "cobalt-dark-alpha-12": "#cde2ffff", + "cobalt-dark-alpha-2": "#0049ff1c", + "cobalt-dark-alpha-3": "#004dff49", + "cobalt-dark-alpha-4": "#074cfd6b", + "cobalt-dark-alpha-5": "#1257ff81", + "cobalt-dark-alpha-6": "#1d62ff94", + "cobalt-dark-alpha-7": "#2768feac", + "cobalt-dark-alpha-8": "#2a6affcd", + "cobalt-dark-alpha-9": "#034cffff", + "cobalt-light-1": "#fcfdffff", + "cobalt-light-10": "#0443deff", + "cobalt-light-11": "#1251ecff", + "cobalt-light-12": "#0f2b6cff", + "cobalt-light-2": "#f5faffff", + "cobalt-light-3": "#eaf2ffff", + "cobalt-light-4": "#daeaffff", + "cobalt-light-5": "#c8e0ffff", + "cobalt-light-6": "#b4d2ffff", + "cobalt-light-7": "#98bfffff", + "cobalt-light-8": "#73a4ffff", + "cobalt-light-9": "#034cffff", + "cobalt-light-alpha-1": "#0055ff03", + "cobalt-light-alpha-10": "#0040ddfb", + "cobalt-light-alpha-11": "#0044ebed", + "cobalt-light-alpha-12": "#001e63f0", + "cobalt-light-alpha-2": "#0080ff0a", + "cobalt-light-alpha-3": "#0061ff15", + "cobalt-light-alpha-4": "#006eff25", + "cobalt-light-alpha-5": "#006fff37", + "cobalt-light-alpha-6": "#0066ff4b", + "cobalt-light-alpha-7": "#0061ff67", + "cobalt-light-alpha-8": "#0059ff8c", + "cobalt-light-alpha-9": "#004afffc", + "color-background-base": "#121212ff", + "color-background-stronger": "#151515ff", + "color-base": "#202020ff", + "color-border-base": "#4d4c4aff", + "color-border-focus": "#5f5d5cff", + "color-border-weak-base": "#282828ff", + "color-border-weaker-base": "#232323ff", + "color-icon-base": "#7e7e7eff", + "color-icon-critical-base": "#cb321cff", + "color-icon-info-active": "#fabbffff", + "color-icon-strong-base": "#ede8e4ff", + "color-icon-success-base": "#089b00ff", + "color-icon-warning-base": "#c78b05ff", + "color-icon-weak-base": "#343434ff", + "color-input-base": "#151515ff", + "color-surface-base": "#1c1c1cff", + "color-surface-base-active": "#282727ff", + "color-surface-base-hover": "#ffffff0d", + "color-surface-raised-base": "#232323ff", + "color-surface-raised-base-hover": "#282828ff", + "color-surface-raised-stronger-non-alpha": "#191919ff", + "color-syntax-keyword": "#f799c6ff", + "color-syntax-property": "#ffc1a4ff", + "color-syntax-type": "#9e99f7ff", + "color-text-base": "#a0a0a0ff", + "color-text-interactive-base": "#c0d4fbff", + "color-text-on-critical-base": "#ffffffff", + "color-text-strong": "#edededff", + "color-text-weak": "#707070ff", + "color-text-weaker": "#505050ff", + "color-v2-background-bg-base": "#161616ff", + "color-v2-background-bg-deep": "#080808ff", + "color-v2-background-bg-inverse": "#ffffffff", + "color-v2-background-bg-layer-01": "#242424ff", + "color-v2-background-bg-layer-02": "#2e2e2eff", + "color-v2-background-bg-layer-03": "#3a3a3aff", + "color-v2-background-bg-layer-04": "#5c5c5cff", + "color-v2-border-border-base": "#ffffff1a", + "color-v2-border-border-focus": "#a2bcffff", + "color-v2-border-border-muted": "#ffffff14", + "color-v2-border-border-strong": "#ffffff33", + "color-v2-icon-icon-accent": "#a2bcffff", + "color-v2-icon-icon-base": "#dbdbdbff", + "color-v2-icon-icon-contrast": "#fafafaff", + "color-v2-icon-icon-faint": "#5c5c5cff", + "color-v2-icon-icon-muted": "#808080ff", + "color-v2-overlay-simple-overlay-hover": "#ffffff0f", + "color-v2-overlay-simple-overlay-pressed": "#ffffff1a", + "color-v2-state-fg-danger": "#f17471ff", + "color-v2-text-text-accent": "#a2bcffff", + "color-v2-text-text-base": "#fafafaff", + "color-v2-text-text-faint": "#808080ff", + "color-v2-text-text-muted": "#aeaeaeff", + "coral-dark-1": "#160f0eff", + "coral-dark-10": "#f5ccc6ff", + "coral-dark-11": "#e2a8a0ff", + "coral-dark-12": "#fcd3cdff", + "coral-dark-2": "#1f1413ff", + "coral-dark-3": "#391613ff", + "coral-dark-4": "#481b17ff", + "coral-dark-5": "#542621ff", + "coral-dark-6": "#63332dff", + "coral-dark-7": "#77453fff", + "coral-dark-8": "#935e57ff", + "coral-dark-9": "#ffd6d0ff", + "coral-dark-alpha-1": "#d4000006", + "coral-dark-alpha-10": "#fed3cdf5", + "coral-dark-alpha-11": "#ffbdb4e0", + "coral-dark-alpha-12": "#ffd6cffc", + "coral-dark-alpha-2": "#ff44330f", + "coral-dark-alpha-3": "#ff2f1e2b", + "coral-dark-alpha-4": "#ff3d2b3b", + "coral-dark-alpha-5": "#ff5c4a48", + "coral-dark-alpha-6": "#ff746358", + "coral-dark-alpha-7": "#fd897b6e", + "coral-dark-alpha-8": "#fd9d908c", + "coral-dark-alpha-9": "#ffd6d0ff", + "coral-light-1": "#fffcfcff", + "coral-light-10": "#a26c65ff", + "coral-light-11": "#9c665fff", + "coral-light-12": "#592a24ff", + "coral-light-2": "#fff8f7ff", + "coral-light-3": "#ffebe8ff", + "coral-light-4": "#ffdbd5ff", + "coral-light-5": "#ffcdc5ff", + "coral-light-6": "#f9beb5ff", + "coral-light-7": "#e9aea6ff", + "coral-light-8": "#d49b93ff", + "coral-light-9": "#af7871ff", + "coral-light-alpha-1": "#ff000003", + "coral-light-alpha-10": "#650c009a", + "coral-light-alpha-11": "#610b00a0", + "coral-light-alpha-12": "#3e0700db", + "coral-light-alpha-2": "#ff200008", + "coral-light-alpha-3": "#ff210017", + "coral-light-alpha-4": "#ff24002a", + "coral-light-alpha-5": "#ff23003a", + "coral-light-alpha-6": "#ea1f004a", + "coral-light-alpha-7": "#c0170059", + "coral-light-alpha-8": "#9913006c", + "coral-light-alpha-9": "#6f0d008e", + "cyan-dark-9": "#0091ffff", + "cyan-light-9": "#0091ffff", + "ember-dark-1": "#170f0dff", + "ember-dark-10": "#ee462dff", + "ember-dark-11": "#ff917bff", + "ember-dark-12": "#ffd1c8ff", + "ember-dark-2": "#201412ff", + "ember-dark-3": "#3c140dff", + "ember-dark-4": "#530e05ff", + "ember-dark-5": "#631409ff", + "ember-dark-6": "#742216ff", + "ember-dark-7": "#8d3324ff", + "ember-dark-8": "#b64330ff", + "ember-dark-9": "#fc533aff", + "ember-dark-alpha-1": "#db000007", + "ember-dark-alpha-10": "#ff4a2fed", + "ember-dark-alpha-11": "#ff917bff", + "ember-dark-alpha-12": "#ffd1c8ff", + "ember-dark-alpha-2": "#f03c1e11", + "ember-dark-alpha-3": "#fa21002f", + "ember-dark-alpha-4": "#ff070047", + "ember-dark-alpha-5": "#ff1a0058", + "ember-dark-alpha-6": "#fd391d6b", + "ember-dark-alpha-7": "#ff523685", + "ember-dark-alpha-8": "#ff593eb1", + "ember-dark-alpha-9": "#ff553bfc", + "ember-light-1": "#fffcfbff", + "ember-light-10": "#ef442aff", + "ember-light-11": "#da3319ff", + "ember-light-12": "#5c281fff", + "ember-light-2": "#fff6f3ff", + "ember-light-3": "#ffe9e4ff", + "ember-light-4": "#ffd7ccff", + "ember-light-5": "#ffc8baff", + "ember-light-6": "#ffb7a6ff", + "ember-light-7": "#ffa392ff", + "ember-light-8": "#f68975ff", + "ember-light-9": "#fc533aff", + "ember-light-alpha-1": "#ff400004", + "ember-light-alpha-10": "#ec1f00d5", + "ember-light-alpha-11": "#d61d00e6", + "ember-light-alpha-12": "#450a00e0", + "ember-light-alpha-2": "#ff40000c", + "ember-light-alpha-3": "#ff2f001b", + "ember-light-alpha-4": "#ff370033", + "ember-light-alpha-5": "#ff340045", + "ember-light-alpha-6": "#ff310059", + "ember-light-alpha-7": "#ff28006d", + "ember-light-alpha-8": "#ee25008a", + "ember-light-alpha-9": "#fb2200c5", + "gray-dark-1": "#131010ff", + "gray-dark-10": "#7f7979ff", + "gray-dark-11": "#b7b1b1ff", + "gray-dark-12": "#f1ececff", + "gray-dark-2": "#1b1818ff", + "gray-dark-3": "#252121ff", + "gray-dark-4": "#2d2828ff", + "gray-dark-5": "#343030ff", + "gray-dark-6": "#3e3939ff", + "gray-dark-7": "#4b4646ff", + "gray-dark-8": "#645f5fff", + "gray-dark-9": "#716c6bff", + "gray-dark-alpha-1": "#aa555503", + "gray-dark-alpha-10": "#fbf4f476", + "gray-dark-alpha-11": "#fcf9f9b2", + "gray-dark-alpha-12": "#fdfbfbf0", + "gray-dark-alpha-2": "#e8d1d10b", + "gray-dark-alpha-3": "#e8d1d116", + "gray-dark-alpha-4": "#eedddd1e", + "gray-dark-alpha-5": "#f8ebeb26", + "gray-dark-alpha-6": "#f5eaea31", + "gray-dark-alpha-7": "#f7ebeb3f", + "gray-dark-alpha-8": "#f9f6f659", + "gray-dark-alpha-9": "#faf5f567", + "gray-light-1": "#fdfcfcff", + "gray-light-10": "#848181ff", + "gray-light-11": "#656363ff", + "gray-light-12": "#211e1eff", + "gray-light-2": "#f9f8f8ff", + "gray-light-3": "#f1f0f0ff", + "gray-light-4": "#e9e8e8ff", + "gray-light-5": "#e2e0e0ff", + "gray-light-6": "#dad9d9ff", + "gray-light-7": "#cfcecdff", + "gray-light-8": "#bcbbbbff", + "gray-light-9": "#8e8b8bff", + "gray-light-alpha-1": "#55000003", + "gray-light-alpha-10": "#0300009c", + "gray-light-alpha-11": "#0600007e", + "gray-light-alpha-12": "#020000df", + "gray-light-alpha-2": "#24000007", + "gray-light-alpha-3": "#1100000f", + "gray-light-alpha-4": "#0b000017", + "gray-light-alpha-5": "#1000001f", + "gray-light-alpha-6": "#07000026", + "gray-light-alpha-7": "#0a050032", + "gray-light-alpha-8": "#04000044", + "gray-light-alpha-9": "#07000074", + "icon-active": "#ede8e4ff", + "icon-agent-ask-base": "#156ebeff", + "icon-agent-build-base": "#c0d4fbff", + "icon-agent-docs-base": "#c78b05ff", + "icon-agent-plan-base": "#cd73d5ff", + "icon-base": "#7e7e7eff", + "icon-brand-base": "#ffffffff", + "icon-critical-active": "#fec3b8ff", + "icon-critical-base": "#cb321cff", + "icon-critical-hover": "#ec2f14ff", + "icon-diff-add-active": "#c4ffc0ff", + "icon-diff-add-base": "#c4ffc0ff", + "icon-diff-add-hover": "#78d474ff", + "icon-diff-delete-base": "#ec2f14ff", + "icon-diff-delete-hover": "#fec3b8ff", + "icon-diff-modified-base": "#fde280ff", + "icon-disabled": "#393938ff", + "icon-focus": "#ede8e4ff", + "icon-hover": "#c9c6c2ff", + "icon-info-active": "#fabbffff", + "icon-info-base": "#cd73d5ff", + "icon-info-hover": "#e282eaff", + "icon-interactive-base": "#1456f7ff", + "icon-invert-base": "#121212ff", + "icon-on-brand-base": "#000000ff", + "icon-on-brand-hover": "#000000ff", + "icon-on-brand-selected": "#000000ff", + "icon-on-critical-base": "#ffffffff", + "icon-on-critical-hover": "#000000ff", + "icon-on-critical-selected": "#000000ff", + "icon-on-info-base": "#ffffffff", + "icon-on-info-hover": "#000000ff", + "icon-on-info-selected": "#000000ff", + "icon-on-interactive-base": "#ffffffff", + "icon-on-success-base": "#ffffffff", + "icon-on-success-hover": "#000000ff", + "icon-on-success-selected": "#000000ff", + "icon-on-warning-base": "#ffffffff", + "icon-on-warning-hover": "#000000ff", + "icon-on-warning-selected": "#000000ff", + "icon-selected": "#ede8e4ff", + "icon-strong-active": "#fcfcfcff", + "icon-strong-base": "#ede8e4ff", + "icon-strong-disabled": "#4d4d4bff", + "icon-strong-focus": "#fdfcfcff", + "icon-strong-hover": "#f6f3f3ff", + "icon-strong-selected": "#fdfcfcff", + "icon-success-active": "#25ff18ff", + "icon-success-base": "#089b00ff", + "icon-success-hover": "#18ab10ff", + "icon-warning-active": "#ffca76ff", + "icon-warning-base": "#c78b05ff", + "icon-warning-hover": "#db9b18ff", + "icon-weak-active": "#6e6c6aff", + "icon-weak-base": "#343434ff", + "icon-weak-disabled": "#1d1d1dff", + "icon-weak-focus": "#6e6c6aff", + "icon-weak-hover": "#ede8e4ff", + "icon-weak-selected": "#6e6c6aff", + "ink-dark-1": "#101313ff", + "ink-dark-10": "#797f7fff", + "ink-dark-11": "#b1b7b7ff", + "ink-dark-12": "#ecf1f1ff", + "ink-dark-2": "#181b1bff", + "ink-dark-3": "#212525ff", + "ink-dark-4": "#282d2dff", + "ink-dark-5": "#303434ff", + "ink-dark-6": "#393e3eff", + "ink-dark-7": "#464b4bff", + "ink-dark-8": "#5f6464ff", + "ink-dark-9": "#6b7171ff", + "ink-dark-alpha-1": "#55aaaa03", + "ink-dark-alpha-10": "#f4fbfb76", + "ink-dark-alpha-11": "#f9fcfcb2", + "ink-dark-alpha-12": "#fbfdfdf0", + "ink-dark-alpha-2": "#d1e8e80b", + "ink-dark-alpha-3": "#d1e8e816", + "ink-dark-alpha-4": "#ddeeee1e", + "ink-dark-alpha-5": "#ebf8f826", + "ink-dark-alpha-6": "#eaf5f531", + "ink-dark-alpha-7": "#ebf7f73f", + "ink-dark-alpha-8": "#f6f9f959", + "ink-dark-alpha-9": "#f5fafa67", + "ink-light-1": "#fcfdfdff", + "ink-light-10": "#818484ff", + "ink-light-11": "#636565ff", + "ink-light-12": "#1e2121ff", + "ink-light-2": "#f8f9f9ff", + "ink-light-3": "#f0f1f1ff", + "ink-light-4": "#e8e9e9ff", + "ink-light-5": "#e0e2e2ff", + "ink-light-6": "#d9dadaff", + "ink-light-7": "#cdcfcfff", + "ink-light-8": "#bbbcbcff", + "ink-light-9": "#8b8e8eff", + "ink-light-alpha-1": "#00555503", + "ink-light-alpha-10": "#0003039c", + "ink-light-alpha-11": "#0006067e", + "ink-light-alpha-12": "#000202df", + "ink-light-alpha-2": "#00242407", + "ink-light-alpha-3": "#0011110f", + "ink-light-alpha-4": "#000b0b17", + "ink-light-alpha-5": "#0010101f", + "ink-light-alpha-6": "#00070726", + "ink-light-alpha-7": "#000a0a32", + "ink-light-alpha-8": "#00040444", + "ink-light-alpha-9": "#00070774", + "input-active": "#022fa6ff", + "input-base": "#151515ff", + "input-disabled": "#1d1d1dff", + "input-focus": "#022fa6ff", + "input-hover": "#191919ff", + "input-selected": "#0643daff", + "lilac-dark-1": "#140f14ff", + "lilac-dark-10": "#e2a8e6ff", + "lilac-dark-11": "#dca2e0ff", + "lilac-dark-12": "#edd8efff", + "lilac-dark-2": "#1d141dff", + "lilac-dark-3": "#2f1e31ff", + "lilac-dark-4": "#3e2440ff", + "lilac-dark-5": "#4a2c4cff", + "lilac-dark-6": "#573859ff", + "lilac-dark-7": "#6c486eff", + "lilac-dark-8": "#8a5e8dff", + "lilac-dark-9": "#edb2f1ff", + "lilac-dark-alpha-1": "#bf00bf04", + "lilac-dark-alpha-10": "#f9b9fee5", + "lilac-dark-alpha-11": "#fab8ffde", + "lilac-dark-alpha-12": "#fde6ffee", + "lilac-dark-alpha-2": "#ff4eff0d", + "lilac-dark-alpha-3": "#e96df823", + "lilac-dark-alpha-4": "#f06efa33", + "lilac-dark-alpha-5": "#f37cfb40", + "lilac-dark-alpha-6": "#f590fc4e", + "lilac-dark-alpha-7": "#fa9eff64", + "lilac-dark-alpha-8": "#f9a5ff85", + "lilac-dark-alpha-9": "#fbbcfff0", + "lilac-light-1": "#fffcffff", + "lilac-light-10": "#9946a0ff", + "lilac-light-11": "#95429cff", + "lilac-light-12": "#590b60ff", + "lilac-light-2": "#fdf7feff", + "lilac-light-3": "#fceafdff", + "lilac-light-4": "#faddfbff", + "lilac-light-5": "#f5cff7ff", + "lilac-light-6": "#eebff1ff", + "lilac-light-7": "#e3a9e7ff", + "lilac-light-8": "#d78bddff", + "lilac-light-9": "#a753aeff", + "lilac-light-alpha-1": "#ff00ff03", + "lilac-light-alpha-10": "#72007cb9", + "lilac-light-alpha-11": "#700079bd", + "lilac-light-alpha-12": "#520059f4", + "lilac-light-alpha-2": "#bf00df08", + "lilac-light-alpha-3": "#db00e715", + "lilac-light-alpha-4": "#da00e122", + "lilac-light-alpha-5": "#ca00d430", + "lilac-light-alpha-6": "#bb00c740", + "lilac-light-alpha-7": "#ac00b856", + "lilac-light-alpha-8": "#a700b474", + "lilac-light-alpha-9": "#7d0087ac", + "markdown-block-quote": "#fde280ff", + "markdown-code": "#94fd8bff", + "markdown-code-block": "#a0a0a0ff", + "markdown-emph": "#fde280ff", + "markdown-heading": "#fed6bdff", + "markdown-horizontal-rule": "#4d4c4aff", + "markdown-image": "#cfdffdff", + "markdown-image-text": "#facffeff", + "markdown-link": "#cfdffdff", + "markdown-link-text": "#facffeff", + "markdown-list-enumeration": "#facffeff", + "markdown-list-item": "#cfdffdff", + "markdown-strong": "#facffeff", + "markdown-text": "#a0a0a0ff", + "mint-dark-1": "#0d130cff", + "mint-dark-10": "#bff5bbff", + "mint-dark-11": "#9dde99ff", + "mint-dark-12": "#c4fbc0ff", + "mint-dark-2": "#121a12ff", + "mint-dark-3": "#1a2a19ff", + "mint-dark-4": "#1f3a1eff", + "mint-dark-5": "#264824ff", + "mint-dark-6": "#2d572bff", + "mint-dark-7": "#356733ff", + "mint-dark-8": "#3d7b3bff", + "mint-dark-9": "#c8ffc4ff", + "mint-dark-alpha-1": "#00aa0003", + "mint-dark-alpha-10": "#c6fec2f5", + "mint-dark-alpha-11": "#b4ffafdb", + "mint-dark-alpha-12": "#c7ffc3fa", + "mint-dark-alpha-2": "#39ff3909", + "mint-dark-alpha-3": "#68ff5e1b", + "mint-dark-alpha-4": "#65ff5f2b", + "mint-dark-alpha-5": "#6cff633b", + "mint-dark-alpha-6": "#72ff6b4a", + "mint-dark-alpha-7": "#74fc6f5c", + "mint-dark-alpha-8": "#74ff7072", + "mint-dark-alpha-9": "#c8ffc4f5", + "mint-light-1": "#fafefaff", + "mint-light-10": "#98e793ff", + "mint-light-11": "#318430ff", + "mint-light-12": "#1f461dff", + "mint-light-2": "#f4fcf3ff", + "mint-light-3": "#dbfdd8ff", + "mint-light-4": "#c3fabfff", + "mint-light-5": "#adf2a8ff", + "mint-light-6": "#96e692ff", + "mint-light-7": "#81d47dff", + "mint-light-8": "#6abc67ff", + "mint-light-9": "#9ff29aff", + "mint-light-alpha-1": "#00cc0005", + "mint-light-alpha-10": "#0cc6006c", + "mint-light-alpha-11": "#016700cf", + "mint-light-alpha-12": "#022e00e2", + "mint-light-alpha-2": "#15bf000c", + "mint-light-alpha-3": "#14f20027", + "mint-light-alpha-4": "#10eb0040", + "mint-light-alpha-5": "#0fd90057", + "mint-light-alpha-6": "#09c5006d", + "mint-light-alpha-7": "#08ab0082", + "mint-light-alpha-8": "#058f0098", + "mint-light-alpha-9": "#0dde0065", + "purple-dark-9": "#edb2f1ff", + "purple-light-9": "#a753aeff", + "smoke-dark-1": "#131010ff", + "smoke-dark-10": "#7f7979ff", + "smoke-dark-11": "#b7b1b1ff", + "smoke-dark-12": "#f1ececff", + "smoke-dark-2": "#1b1818ff", + "smoke-dark-3": "#252121ff", + "smoke-dark-4": "#2d2828ff", + "smoke-dark-5": "#343030ff", + "smoke-dark-6": "#3e3939ff", + "smoke-dark-7": "#4b4646ff", + "smoke-dark-8": "#645f5fff", + "smoke-dark-9": "#716c6bff", + "smoke-dark-alpha-1": "#aa555503", + "smoke-dark-alpha-10": "#fbf4f476", + "smoke-dark-alpha-11": "#fcf9f9b2", + "smoke-dark-alpha-12": "#fdfbfbf0", + "smoke-dark-alpha-2": "#e8d1d10b", + "smoke-dark-alpha-3": "#e8d1d116", + "smoke-dark-alpha-4": "#eedddd1e", + "smoke-dark-alpha-5": "#f8ebeb26", + "smoke-dark-alpha-6": "#f5eaea31", + "smoke-dark-alpha-7": "#f7ebeb3f", + "smoke-dark-alpha-8": "#f9f6f659", + "smoke-dark-alpha-9": "#faf5f567", + "smoke-light-1": "#fdfcfcff", + "smoke-light-10": "#848181ff", + "smoke-light-11": "#656363ff", + "smoke-light-12": "#211e1eff", + "smoke-light-2": "#f9f8f8ff", + "smoke-light-3": "#f1f0f0ff", + "smoke-light-4": "#e9e8e8ff", + "smoke-light-5": "#e2e0e0ff", + "smoke-light-6": "#dad9d9ff", + "smoke-light-7": "#cfcecdff", + "smoke-light-8": "#bcbbbbff", + "smoke-light-9": "#8e8b8bff", + "smoke-light-alpha-1": "#55000003", + "smoke-light-alpha-10": "#0300009c", + "smoke-light-alpha-11": "#0600007e", + "smoke-light-alpha-12": "#020000df", + "smoke-light-alpha-2": "#24000007", + "smoke-light-alpha-3": "#1100000f", + "smoke-light-alpha-4": "#0b000017", + "smoke-light-alpha-5": "#1000001f", + "smoke-light-alpha-6": "#07000026", + "smoke-light-alpha-7": "#0a050032", + "smoke-light-alpha-8": "#04000044", + "smoke-light-alpha-9": "#07000074", + "solaris-dark-1": "#13110bff", + "solaris-dark-10": "#f2cb2aff", + "solaris-dark-11": "#fdd63cff", + "solaris-dark-12": "#faebb5ff", + "solaris-dark-2": "#1b180fff", + "solaris-dark-3": "#2a2307ff", + "solaris-dark-4": "#382b00ff", + "solaris-dark-5": "#443500ff", + "solaris-dark-6": "#514307ff", + "solaris-dark-7": "#64551aff", + "solaris-dark-8": "#7f6c25ff", + "solaris-dark-9": "#fcd53aff", + "solaris-dark-alpha-1": "#aa000003", + "solaris-dark-alpha-10": "#fed52bf2", + "solaris-dark-alpha-11": "#ffd83cfd", + "solaris-dark-alpha-12": "#fff0b9fa", + "solaris-dark-alpha-2": "#ffb9000b", + "solaris-dark-alpha-3": "#ffbd001b", + "solaris-dark-alpha-4": "#ffb0002a", + "solaris-dark-alpha-5": "#ffb90037", + "solaris-dark-alpha-6": "#ffcb0045", + "solaris-dark-alpha-7": "#ffd42b59", + "solaris-dark-alpha-8": "#ffd63d76", + "solaris-dark-alpha-9": "#ffd83bfc", + "solaris-light-1": "#fefdfaff", + "solaris-light-10": "#fad337ff", + "solaris-light-11": "#917500ff", + "solaris-light-12": "#433c22ff", + "solaris-light-2": "#fffbeaff", + "solaris-light-3": "#fff6beff", + "solaris-light-4": "#ffee9cff", + "solaris-light-5": "#ffe47cff", + "solaris-light-6": "#f2d775ff", + "solaris-light-7": "#e0c76fff", + "solaris-light-8": "#cdb047ff", + "solaris-light-9": "#ffdc17ff", + "solaris-light-alpha-1": "#cc990005", + "solaris-light-alpha-10": "#f9c700c8", + "solaris-light-alpha-11": "#917500ff", + "solaris-light-alpha-12": "#261e00dd", + "solaris-light-alpha-2": "#ffce0015", + "solaris-light-alpha-3": "#ffdc0041", + "solaris-light-alpha-4": "#ffd30063", + "solaris-light-alpha-5": "#ffca0083", + "solaris-light-alpha-6": "#e7b5008a", + "solaris-light-alpha-7": "#c89c0090", + "solaris-light-alpha-8": "#ba9200b8", + "solaris-light-alpha-9": "#ffd900e8", + "surface-base": "#1c1c1cff", + "surface-base-active": "#282727ff", + "surface-base-hover": "#ffffff0d", + "surface-base-interactive-active": "#000a324d", + "surface-brand-base": "#e27618ff", + "surface-brand-hover": "#f88524ff", + "surface-critical-base": "#1f0603ff", + "surface-critical-strong": "#fec3b8ff", + "surface-critical-weak": "#5a0c03ff", + "surface-diff-add-base": "#001401ff", + "surface-diff-add-strong": "#012902ff", + "surface-diff-add-stronger": "#c4ffc0ff", + "surface-diff-add-weak": "#011d02ff", + "surface-diff-add-weaker": "#001401ff", + "surface-diff-delete-base": "#240200ff", + "surface-diff-delete-strong": "#430501ff", + "surface-diff-delete-stronger": "#fec3b8ff", + "surface-diff-delete-weak": "#310401ff", + "surface-diff-delete-weaker": "#240200ff", + "surface-diff-hidden-base": "#181d2aff", + "surface-diff-hidden-strong": "#1c273eff", + "surface-diff-hidden-stronger": "#23345aff", + "surface-diff-hidden-weak": "#151820ff", + "surface-diff-hidden-weaker": "#192131ff", + "surface-diff-skip-base": "#1a1a1aff", + "surface-diff-unchanged-base": "#121212ff", + "surface-float-base": "#151515ff", + "surface-float-base-hover": "#191919ff", + "surface-info-base": "#651b6cff", + "surface-info-strong": "#fabbffff", + "surface-info-weak": "#4d0853ff", + "surface-inset-base": "#202020ff", + "surface-inset-base-hover": "#282727ff", + "surface-inset-strong": "#12121280", + "surface-inset-strong-hover": "#12121280", + "surface-interactive-base": "#022fa6ff", + "surface-interactive-hover": "#0643daff", + "surface-interactive-weak": "#0d172bff", + "surface-interactive-weak-hover": "#022fa6ff", + "surface-raised-base": "#232323ff", + "surface-raised-base-active": "#282727ff", + "surface-raised-base-hover": "#282828ff", + "surface-raised-strong": "#313030ff", + "surface-raised-strong-hover": "#494847ff", + "surface-raised-stronger": "#494847ff", + "surface-raised-stronger-hover": "#5b5958ff", + "surface-raised-stronger-non-alpha": "#191919ff", + "surface-strong": "#5b5958ff", + "surface-stronger-non-alpha": "#191919ff", + "surface-success-base": "#022b00ff", + "surface-success-strong": "#25ff18ff", + "surface-success-weak": "#083a05ff", + "surface-warning-base": "#4e410bff", + "surface-warning-strong": "#ffe179ff", + "surface-warning-weak": "#382e05ff", + "surface-weak": "#282727ff", + "surface-weaker": "#313030ff", + "syntax-comment": "#aeaeaeff", + "syntax-constant": "#93e9f6ff", + "syntax-critical": "#f29b96ff", + "syntax-diff-add": "#6bd586ff", + "syntax-diff-delete": "#f17471ff", + "syntax-diff-unknown": "#edb2f1ff", + "syntax-info": "#facffeff", + "syntax-keyword": "#f799c6ff", + "syntax-object": "#edededff", + "syntax-operator": "#707070ff", + "syntax-primitive": "#f799c6ff", + "syntax-property": "#ffc1a4ff", + "syntax-punctuation": "#707070ff", + "syntax-regexp": "#a0a0a0ff", + "syntax-string": "#96e3a6ff", + "syntax-success": "#25ff18ff", + "syntax-type": "#9e99f7ff", + "syntax-variable": "#edededff", + "syntax-warning": "#ffca76ff", + "text-base": "#a0a0a0ff", + "text-diff-add-base": "#6bd586ff", + "text-diff-add-strong": "#176d18ff", + "text-diff-delete-base": "#f17471ff", + "text-diff-delete-strong": "#fafafaff", + "text-interactive-base": "#c0d4fbff", + "text-invert-base": "#c9c6c2ff", + "text-invert-strong": "#ede8e4ff", + "text-invert-weak": "#6e6c6aff", + "text-invert-weaker": "#4d4d4bff", + "text-on-brand-base": "#000000ff", + "text-on-brand-strong": "#000000ff", + "text-on-brand-weak": "#000000ff", + "text-on-brand-weaker": "#000000ff", + "text-on-critical-base": "#ffffffff", + "text-on-critical-strong": "#000000ff", + "text-on-critical-weak": "#ffffffff", + "text-on-info-base": "#ffffffff", + "text-on-info-strong": "#000000ff", + "text-on-info-weak": "#ffffffff", + "text-on-interactive-base": "#ffffffff", + "text-on-interactive-weak": "#ffffffff", + "text-on-success-base": "#ffffffff", + "text-on-success-strong": "#000000ff", + "text-on-success-weak": "#ffffffff", + "text-on-warning-base": "#ffffffff", + "text-on-warning-strong": "#000000ff", + "text-on-warning-weak": "#ffffffff", + "text-strong": "#edededff", + "text-stronger": "#edededff", + "text-weak": "#707070ff", + "text-weaker": "#505050ff", + "tw-ring-offset-color": "#ffffffff", + "v2-agent-build-background": "#273bb10d", + "v2-agent-build-border": "#a0beff33", + "v2-agent-build-solid": "#c3d4fdff", + "v2-agent-explore-background": "#b1893b0d", + "v2-agent-explore-border": "#f5dc9b33", + "v2-agent-explore-solid": "#f7e5b5ff", + "v2-agent-plan-background": "#b13b760d", + "v2-agent-plan-border": "#f59bc833", + "v2-agent-plan-solid": "#f799c6ff", + "v2-agent-review-solid": "#b8e9c1ff", + "v2-agent-writer-solid": "#9e99f7ff", + "v2-alpha-dark-0": "#00000000", + "v2-alpha-dark-10": "#0000001a", + "v2-alpha-dark-100": "#000000ff", + "v2-alpha-dark-12": "#0000001f", + "v2-alpha-dark-14": "#00000024", + "v2-alpha-dark-16": "#00000029", + "v2-alpha-dark-2": "#00000005", + "v2-alpha-dark-20": "#00000033", + "v2-alpha-dark-24": "#0000003d", + "v2-alpha-dark-30": "#0000004d", + "v2-alpha-dark-4": "#0000000a", + "v2-alpha-dark-40": "#00000066", + "v2-alpha-dark-50": "#00000080", + "v2-alpha-dark-6": "#0000000f", + "v2-alpha-dark-60": "#00000099", + "v2-alpha-dark-70": "#000000b2", + "v2-alpha-dark-8": "#00000014", + "v2-alpha-dark-80": "#000000cc", + "v2-alpha-dark-90": "#000000e5", + "v2-alpha-light-0": "#00000000", + "v2-alpha-light-10": "#ffffff1a", + "v2-alpha-light-100": "#ffffffff", + "v2-alpha-light-12": "#ffffff1f", + "v2-alpha-light-14": "#ffffff24", + "v2-alpha-light-16": "#ffffff29", + "v2-alpha-light-2": "#ffffff05", + "v2-alpha-light-20": "#ffffff33", + "v2-alpha-light-24": "#ffffff3d", + "v2-alpha-light-30": "#ffffff4d", + "v2-alpha-light-4": "#ffffff0a", + "v2-alpha-light-40": "#ffffff66", + "v2-alpha-light-50": "#ffffff80", + "v2-alpha-light-6": "#ffffff0f", + "v2-alpha-light-60": "#ffffff99", + "v2-alpha-light-70": "#ffffffb2", + "v2-alpha-light-8": "#ffffff14", + "v2-alpha-light-80": "#ffffffcc", + "v2-alpha-light-90": "#ffffffe5", + "v2-avatar-bg-blue": "#263fa9ff", + "v2-avatar-bg-cyan": "#005a6eff", + "v2-avatar-bg-gray": "#5c5c5cff", + "v2-avatar-bg-green": "#196130ff", + "v2-avatar-bg-orange": "#723d22ff", + "v2-avatar-bg-pink": "#8c2d61ff", + "v2-avatar-bg-purple": "#361f83ff", + "v2-avatar-bg-red": "#7a1f23ff", + "v2-avatar-bg-yellow": "#68552bff", + "v2-avatar-border-blue": "#7698fdff", + "v2-avatar-border-cyan": "#0096b8ff", + "v2-avatar-border-gray": "#aeaeaeff", + "v2-avatar-border-green": "#49c970ff", + "v2-avatar-border-orange": "#ff8648ff", + "v2-avatar-border-pink": "#e4429eff", + "v2-avatar-border-purple": "#7152f4ff", + "v2-avatar-border-red": "#d92e3cff", + "v2-avatar-border-yellow": "#e7af36ff", + "v2-avatar-fg": "#ffffffff", + "v2-background-bg-accent": "#3b5cf6ff", + "v2-background-bg-base": "#161616ff", + "v2-background-bg-button-neutral": "#ffffff0f", + "v2-background-bg-code-path": "#00353fff", + "v2-background-bg-contrast": "#5c5c5cff", + "v2-background-bg-deep": "#080808ff", + "v2-background-bg-icon-button-contrast": "#dbdbdbff", + "v2-background-bg-inverse": "#ffffffff", + "v2-background-bg-layer-01": "#242424ff", + "v2-background-bg-layer-02": "#2e2e2eff", + "v2-background-bg-layer-03": "#3a3a3aff", + "v2-background-bg-layer-04": "#5c5c5cff", + "v2-blue-100": "#f5f8ffff", + "v2-blue-1000": "#263fa9ff", + "v2-blue-1100": "#22388fff", + "v2-blue-1200": "#021945ff", + "v2-blue-200": "#ecf1feff", + "v2-blue-300": "#c3d4fdff", + "v2-blue-400": "#a2bcffff", + "v2-blue-500": "#7698fdff", + "v2-blue-600": "#3b5cf6ff", + "v2-blue-700": "#0b34f4ff", + "v2-blue-800": "#3250dfff", + "v2-blue-900": "#2c47c8ff", + "v2-border-border-base": "#ffffff1a", + "v2-border-border-focus": "#a2bcffff", + "v2-border-border-inverse": "#fafafaff", + "v2-border-border-muted": "#ffffff14", + "v2-border-border-strong": "#ffffff33", + "v2-cyan-100": "#e2f7fbff", + "v2-cyan-1000": "#005a6eff", + "v2-cyan-1100": "#004756ff", + "v2-cyan-1200": "#00353fff", + "v2-cyan-200": "#c4edf4ff", + "v2-cyan-300": "#a3e4efff", + "v2-cyan-400": "#65d9ebff", + "v2-cyan-500": "#00c5dfff", + "v2-cyan-600": "#00abcfff", + "v2-cyan-700": "#0096b8ff", + "v2-cyan-800": "#007d9bff", + "v2-cyan-900": "#006c85ff", + "v2-green-100": "#e7f9eaff", + "v2-green-1000": "#196130ff", + "v2-green-1100": "#164c26ff", + "v2-green-1200": "#14361dff", + "v2-green-200": "#d0f0d5ff", + "v2-green-300": "#b8e9c1ff", + "v2-green-400": "#96e3a6ff", + "v2-green-500": "#6bd586ff", + "v2-green-600": "#49c970ff", + "v2-green-700": "#2eaf5aff", + "v2-green-800": "#198b43ff", + "v2-green-900": "#1d783cff", + "v2-grey-100": "#fafafaff", + "v2-grey-1000": "#242424ff", + "v2-grey-1100": "#161616ff", + "v2-grey-1200": "#080808ff", + "v2-grey-200": "#f2f2f2ff", + "v2-grey-300": "#eeeeeeff", + "v2-grey-400": "#dbdbdbff", + "v2-grey-50": "#ffffffff", + "v2-grey-500": "#aeaeaeff", + "v2-grey-600": "#808080ff", + "v2-grey-700": "#5c5c5cff", + "v2-grey-800": "#3a3a3aff", + "v2-grey-900": "#2e2e2eff", + "v2-icon-icon-accent": "#a2bcffff", + "v2-icon-icon-accent-hover": "#c3d4fdff", + "v2-icon-icon-base": "#dbdbdbff", + "v2-icon-icon-contrast": "#fafafaff", + "v2-icon-icon-faint": "#5c5c5cff", + "v2-icon-icon-inverse": "#161616ff", + "v2-icon-icon-muted": "#808080ff", + "v2-illustration-illustration-layer-01": "#2e2e2eff", + "v2-illustration-illustration-layer-02": "#3a3a3aff", + "v2-illustration-illustration-layer-03": "#5c5c5cff", + "v2-orange-100": "#fdf2edff", + "v2-orange-1000": "#954c27ff", + "v2-orange-1100": "#723d22ff", + "v2-orange-1200": "#5a2c14ff", + "v2-orange-200": "#ffe7dcff", + "v2-orange-300": "#ffd8c6ff", + "v2-orange-400": "#ffc1a4ff", + "v2-orange-500": "#ffa478ff", + "v2-orange-600": "#ff8648ff", + "v2-orange-700": "#ee7330ff", + "v2-orange-800": "#d16427ff", + "v2-orange-900": "#b35624ff", + "v2-overlay-gradient-depth-overlay-depth-bot": "#00000000", + "v2-overlay-gradient-depth-overlay-depth-top": "#ffffffff", + "v2-overlay-simple-overlay-contrast-hover": "#0000003d", + "v2-overlay-simple-overlay-contrast-pressed": "#00000066", + "v2-overlay-simple-overlay-hover": "#ffffff0f", + "v2-overlay-simple-overlay-pressed": "#ffffff1a", + "v2-overlay-simple-overlay-scrim": "#00000099", + "v2-overlay-simple-tab-active-scrim": "#00000000", + "v2-overlay-simple-tab-hover-scrim": "#00000000", + "v2-overlay-simple-tab-scrim": "#00000000", + "v2-pink-100": "#fdecf3ff", + "v2-pink-1000": "#8c2d61ff", + "v2-pink-1100": "#6f284fff", + "v2-pink-1200": "#5c1d3fff", + "v2-pink-200": "#f7d5e4ff", + "v2-pink-300": "#fabcd8ff", + "v2-pink-400": "#f799c6ff", + "v2-pink-500": "#f26cb2ff", + "v2-pink-600": "#f64aabff", + "v2-pink-700": "#e4429eff", + "v2-pink-800": "#c83d8bff", + "v2-pink-900": "#aa3576ff", + "v2-purple-100": "#ebecfeff", + "v2-purple-1000": "#361f83ff", + "v2-purple-1100": "#2b1b6aff", + "v2-purple-1200": "#221358ff", + "v2-purple-200": "#d5d5fcff", + "v2-purple-300": "#b9b8f5ff", + "v2-purple-400": "#9e99f7ff", + "v2-purple-500": "#8271f8ff", + "v2-purple-600": "#7152f4ff", + "v2-purple-700": "#623be2ff", + "v2-purple-800": "#5230c2ff", + "v2-purple-900": "#442aa1ff", + "v2-red-100": "#fcecebff", + "v2-red-1000": "#7a1f23ff", + "v2-red-1100": "#5f1a1cff", + "v2-red-1200": "#461516ff", + "v2-red-200": "#f6d5d3ff", + "v2-red-300": "#f2bbb7ff", + "v2-red-400": "#f29b96ff", + "v2-red-500": "#f17471ff", + "v2-red-600": "#f1484fff", + "v2-red-700": "#d92e3cff", + "v2-red-800": "#b82d35ff", + "v2-red-900": "#97252bff", + "v2-state-bg-danger": "#461516ff", + "v2-state-bg-info": "#021945ff", + "v2-state-bg-success": "#14361dff", + "v2-state-bg-warning": "#4b4025ff", + "v2-state-border-danger": "#97252bff", + "v2-state-border-info": "#2c47c8ff", + "v2-state-border-success": "#1d783cff", + "v2-state-border-warning": "#ac8833ff", + "v2-state-fg-danger": "#f17471ff", + "v2-state-fg-info": "#7698fdff", + "v2-state-fg-success": "#6bd586ff", + "v2-state-fg-warning": "#f2cf76ff", + "v2-text-text-accent": "#a2bcffff", + "v2-text-text-accent-hover": "#c3d4fdff", + "v2-text-text-base": "#fafafaff", + "v2-text-text-code-accent": "#a2bcffff", + "v2-text-text-code-path": "#c3d4fdff", + "v2-text-text-contrast": "#ffffffff", + "v2-text-text-faint": "#808080ff", + "v2-text-text-inverse": "#161616ff", + "v2-text-text-muted": "#aeaeaeff", + "v2-yellow-100": "#fefaecff", + "v2-yellow-1000": "#8e7231ff", + "v2-yellow-1100": "#68552bff", + "v2-yellow-1200": "#4b4025ff", + "v2-yellow-200": "#fcefd0ff", + "v2-yellow-300": "#f7e5b5ff", + "v2-yellow-400": "#f3da9bff", + "v2-yellow-500": "#f2cf76ff", + "v2-yellow-600": "#f6c251ff", + "v2-yellow-700": "#e7af36ff", + "v2-yellow-800": "#cb9f34ff", + "v2-yellow-900": "#ac8833ff", + "white": "#ffffffff", + "yuzu-dark-1": "#11120cff", + "yuzu-dark-10": "#f4f6c1ff", + "yuzu-dark-11": "#dbdda0ff", + "yuzu-dark-12": "#eff1bdff", + "yuzu-dark-2": "#181810ff", + "yuzu-dark-3": "#262614ff", + "yuzu-dark-4": "#313115ff", + "yuzu-dark-5": "#3d3d18ff", + "yuzu-dark-6": "#4a4a21ff", + "yuzu-dark-7": "#5a5b2cff", + "yuzu-dark-8": "#6f6f36ff", + "yuzu-dark-9": "#fdffcaff", + "yuzu-dark-alpha-1": "#00800002", + "yuzu-dark-alpha-10": "#fcfec7f6", + "yuzu-dark-alpha-11": "#fdffb8db", + "yuzu-dark-alpha-12": "#fdffc8f0", + "yuzu-dark-alpha-2": "#ffff0008", + "yuzu-dark-alpha-3": "#ffff3717", + "yuzu-dark-alpha-4": "#f8f82c23", + "yuzu-dark-alpha-5": "#fafa3530", + "yuzu-dark-alpha-6": "#fbfb523e", + "yuzu-dark-alpha-7": "#f9fc6650", + "yuzu-dark-alpha-8": "#ffff6f65", + "yuzu-dark-alpha-9": "#fdffcaff", + "yuzu-light-1": "#fdfdfbff", + "yuzu-light-10": "#d2d384ff", + "yuzu-light-11": "#7c7c2cff", + "yuzu-light-12": "#3d3d23ff", + "yuzu-light-2": "#fbfcebff", + "yuzu-light-3": "#f8fac5ff", + "yuzu-light-4": "#f2f4a5ff", + "yuzu-light-5": "#e9eb9aff", + "yuzu-light-6": "#dcde8eff", + "yuzu-light-7": "#cccd7eff", + "yuzu-light-8": "#b6b768ff", + "yuzu-light-9": "#dcde8dff", + "yuzu-light-alpha-1": "#80800004", + "yuzu-light-alpha-10": "#a2a4007b", + "yuzu-light-alpha-11": "#616100d3", + "yuzu-light-alpha-12": "#1e1e00dc", + "yuzu-light-alpha-2": "#ccd90014", + "yuzu-light-alpha-3": "#e0e9003a", + "yuzu-light-alpha-4": "#dae0005a", + "yuzu-light-alpha-5": "#c7cd0065", + "yuzu-light-alpha-6": "#b0b50071", + "yuzu-light-alpha-7": "#9a9c0081", + "yuzu-light-alpha-8": "#84850097", + "yuzu-light-alpha-9": "#b1b50072" + }, + "shadows": { + "light": { + "shadow-lg": "#0000000d 0px 16px 48px -6px, #00000006 0px 6px 12px -2px, #00000006 0px 1px 2.5px 0px", + "shadow-lg-border-base": "#dbdbdbff 0px 0px 0px 1px, #00000008 0px 36px 80px 0px, #0000000a 0px 13.141px 29.201px 0px, #0000000d 0px 6.38px 14.177px 0px, #0000000f 0px 3.127px 6.95px 0px, #00000017 0px 1.237px 2.748px 0px", + "shadow-md": "#00000013 0px 6px 12px -2px, #00000013 0px 4px 8px -2px, #0000001a 0px 1px 2px 0px", + "shadow-xs": "#0000000a 0px 1px 2px -0.5px, #00000006 0px 0.5px 1.5px 0px, #0000000d 0px 1px 3px 0px", + "shadow-xs-border": "#c1c0c0ff 0px 0px 0px 1px, #1a1a1a0a 0px 1px 2px -1px, #1111110f 0px 1px 2px 0px, #0d0d0d14 0px 1px 3px 0px", + "shadow-xs-border-base": "#dbdbdbff 0px 0px 0px 1px, #1a1a1a0a 0px 1px 2px -1px, #1111110f 0px 1px 2px 0px, #0d0d0d14 0px 1px 3px 0px", + "shadow-xs-border-critical-base": "#fb543cff 0px 0px 0px 1px", + "shadow-xs-border-critical-focus": "#f921002e 0px 0px 0px 3px, #fb543cff 0px 0px 0px 1px, #14101040 0px 1px 2px -1px, #0d0d0d14 0px 1px 2px 0px, #1010101f 0px 1px 3px 0px", + "shadow-xs-border-focus": "#c1c0c0ff 0px 0px 0px 1px, #14101040 0px 1px 2px -1px, #0d0d0d14 0px 1px 2px 0px, #1010101f 0px 1px 3px 0px, #edededff 0px 0px 0px 2px, #054dfdfc 0px 0px 0px 3px", + "shadow-xs-border-hover": "#d1e1fd80 0px 0px 0px 1px, #1a1a1a0a 0px 1px 2px -1px, #1111110f 0px 1px 2px 0px, #0d0d0d14 0px 1px 3px 0px", + "shadow-xs-border-select": "#d1e1fd80 0px 0px 0px 3px, #054dfdfc 0px 0px 0px 1px, #14101040 0px 1px 2px -1px, #0d0d0d14 0px 1px 2px 0px, #1010101f 0px 1px 3px 0px", + "shadow-xxs-border": "#dbdbdbff 0px 0px 0px 0.5px", + "v2-elevation-button-contrast": "#00000033 0px 1px 1.5px 0px, #3a3a3aff 0px 0px 0px 0.5px, #ffffff24 0px 1px 2px 0px inset, #0000000f 0px -1px 2px 0px inset, #00000000 0px 0px 0px 0px", + "v2-elevation-button-neutral": "#0000001a 0px 1px 1.5px 0px, #00000024 0px 0px 0px 0.5px, #00000000 0px 0px 0px 0px", + "v2-elevation-elements": "#00000066 0px 0.5px 0.5px 0px", + "v2-elevation-floating": "#0000000a 0px 8px 16px 0px, #00000014 0px 4px 8px 0px, #0000001f 0px 0px 0px 0.5px, #00000000 0px 0px 0px 0px", + "v2-elevation-input": "#0000001a 0px 1px 1.5px 0px, #00000024 0px 0px 0px 0.5px, #00000000 0px 0px 0px 0px", + "v2-elevation-overlay": "#0000000a 0px 16px 32px 0px, #00000014 0px 8px 16px 0px, #0000001f 0px 0px 0px 0.5px, #00000000 0px 0px 0px 0px", + "v2-elevation-raised": "#0000000a 0px 2px 4px 0px, #00000014 0px 1px 2px -1px, #0000001f 0px 0px 0px 0.5px, #00000000 0px 0px 0px 0px", + "v2-elevation-switch-off": "#00000014 0px 1px 1px 0px inset, #00000014 0px 0.5px 0.5px 0px inset, #0000001a 0px 0px 0px 0.5px inset", + "v2-elevation-switch-on": "#0000001a 0px 2px 2px 0px inset, #0000001a 0px 1px 1px 0px inset, #00000033 0px 0px 0px 0.5px inset" + }, + "dark": { + "shadow-lg": "#00000026 0px 16px 48px -6px, #0000001a 0px 6px 12px -2px, #0000001a 0px 1px 2.5px 0px", + "shadow-lg-border-base": "#282828ff 0px 0px 0px 1px, #00000008 0px 36px 80px 0px, #0000000a 0px 13.141px 29.201px 0px, #0000000d 0px 6.38px 14.177px 0px, #0000000f 0px 3.127px 6.95px 0px, #00000017 0px 1.237px 2.748px 0px", + "shadow-md": "#0000001a 0px 6px 12px -2px, #00000026 0px 4px 8px -2px, #00000026 0px 1px 2px 0px", + "shadow-xs": "#0000000f 0px 1px 2px -0.5px, #00000014 0px 0.5px 1.5px 0px, #0000001a 0px 1px 3px 0px", + "shadow-xs-border": "#4d4c4aff 0px 0px 0px 1px, #1a1a1a0a 0px 1px 2px -1px, #1111110f 0px 1px 2px 0px, #0d0d0d14 0px 1px 3px 0px", + "shadow-xs-border-base": "#282828ff 0px 0px 0px 1px, #1a1a1a0a 0px 1px 2px -1px, #1111110f 0px 1px 2px 0px, #0d0d0d14 0px 1px 3px 0px", + "shadow-xs-border-critical-base": "#cb321cff 0px 0px 0px 1px", + "shadow-xs-border-critical-focus": "#f921002e 0px 0px 0px 3px, #cb321cff 0px 0px 0px 1px, #14101040 0px 1px 2px -1px, #0d0d0d14 0px 1px 2px 0px, #1010101f 0px 1px 3px 0px", + "shadow-xs-border-focus": "#4d4c4aff 0px 0px 0px 1px, #14101040 0px 1px 2px -1px, #0d0d0d14 0px 1px 2px 0px, #1010101f 0px 1px 3px 0px, #191919ff 0px 0px 0px 2px, #1456f7e6 0px 0px 0px 3px", + "shadow-xs-border-hover": "#02175899 0px 0px 0px 1px, #1a1a1a0a 0px 1px 2px -1px, #1111110f 0px 1px 2px 0px, #0d0d0d14 0px 1px 3px 0px", + "shadow-xs-border-select": "#02175899 0px 0px 0px 3px, #1456f7e6 0px 0px 0px 1px, #14101040 0px 1px 2px -1px, #0d0d0d14 0px 1px 2px 0px, #1010101f 0px 1px 3px 0px", + "shadow-xxs-border": "#282828ff 0px 0px 0px 0.5px", + "v2-elevation-button-contrast": "#00000066 0px 1px 2px 0px, #ffffff66 0px 0px 0px 0.5px, #00000000 0px 0px 0px 0px inset, #00000000 0px 0px 0px 0px inset, #ffffff4d 0px -0.5px 0px 0px", + "v2-elevation-button-neutral": "#00000066 0px 1px 2px 0px, #ffffff33 0px 0px 0px 0.5px, #ffffff1a 0px -0.5px 0px 0px", + "v2-elevation-elements": "#00000066 0px 0.5px 0.5px 0px", + "v2-elevation-floating": "#0000004d 0px 8px 16px 0px, #0000004d 0px 4px 8px 0px, #ffffff29 0px 0px 0px 0.5px, #ffffff0f 0px -0.5px 0px 0px", + "v2-elevation-input": "#00000000 0px 1px 2px 0px, #ffffff29 0px 0px 0px 0.5px, #ffffff0f 0px -0.5px 0px 0px", + "v2-elevation-overlay": "#0000004d 0px 16px 32px 0px, #0000004d 0px 8px 16px 0px, #ffffff29 0px 0px 0px 0.5px, #ffffff0f 0px -0.5px 0px 0px", + "v2-elevation-raised": "#0000004d 0px 2px 4px 0px, #0000004d 0px 1px 2px 0px, #ffffff29 0px 0px 0px 0.5px, #ffffff0f 0px -0.5px 0px 0px", + "v2-elevation-switch-off": "#ffffff1a 0px -0.5px 0px 0px inset, #00000000 0px 0px 0px 0px inset, #ffffff29 0px 0px 0px 0.5px inset", + "v2-elevation-switch-on": "#ffffff1a 0px -0.5px 0px 0px inset, #00000000 0px 0px 0px 0px inset, #ffffff29 0px 0px 0px 0.5px inset" + } + }, + "numbers": { + "bottom-fade": 0, + "breakpoint-2xl": 1536, + "breakpoint-lg": 1024, + "breakpoint-md": 768, + "breakpoint-sm": 640, + "breakpoint-xl": 1280, + "container-2xl": 672, + "container-2xs": 288, + "container-3xl": 768, + "container-3xs": 256, + "container-4xl": 896, + "container-5xl": 1024, + "container-6xl": 1152, + "container-7xl": 1280, + "container-lg": 512, + "container-md": 448, + "container-session": 744, + "container-sm": 384, + "container-xl": 576, + "container-xs": 320, + "font-size-base": 14, + "font-size-large": 16, + "font-size-small": 13, + "font-size-x-large": 20, + "font-weight-bold": 670, + "font-weight-medium": 500, + "font-weight-regular": 400, + "leading-text-compact": 16, + "leading-text-tight": 12, + "letter-spacing-normal": 0, + "letter-spacing-tight": -0.16, + "letter-spacing-tightest": -0.32, + "line-height-base": 20, + "line-height-compact": 16, + "line-height-tight": 12, + "paragraph-spacing-base": 0, + "radius-lg": 8, + "radius-md": 6, + "radius-sm": 4, + "radius-xl": 10, + "radius-xs": 2, + "spacing": 4, + "text-lg": 16, + "text-sm": 13, + "text-xl": 20, + "tw-animation-iteration-count": 1, + "tw-divide-y-reverse": 0, + "tw-enter-blur": 0, + "tw-enter-opacity": 1, + "tw-enter-rotate": 0, + "tw-enter-scale": 1, + "tw-enter-translate-x": 0, + "tw-enter-translate-y": 0, + "tw-exit-blur": 0, + "tw-exit-opacity": 1, + "tw-exit-rotate": 0, + "tw-exit-scale": 1, + "tw-exit-translate-x": 0, + "tw-exit-translate-y": 0, + "tw-ring-offset-width": 0, + "tw-scale-x": 1, + "tw-scale-y": 1, + "tw-scale-z": 1, + "tw-translate-x": 0, + "tw-translate-y": 0, + "tw-translate-z": 0 + } +} diff --git a/app/vendor/rune/themes/opencode/rustfmt.toml b/app/vendor/rune/themes/opencode/rustfmt.toml new file mode 100644 index 0000000..c775577 --- /dev/null +++ b/app/vendor/rune/themes/opencode/rustfmt.toml @@ -0,0 +1,2 @@ +max_width = 120 +use_small_heuristics = "Max" diff --git a/app/vendor/rune/themes/opencode/src/app_icons.rs b/app/vendor/rune/themes/opencode/src/app_icons.rs new file mode 100644 index 0000000..461a812 --- /dev/null +++ b/app/vendor/rune/themes/opencode/src/app_icons.rs @@ -0,0 +1,36 @@ +//! Generated by tools/app-icons.py from @opencode/ui's app marks. Do not edit. +use rune::Icon; + +static VSCODE: Icon = Icon { name: "app-vscode", view: 40.0, body: r##"<g fill="none"><mask id="mask0_5437_79124" style="mask-type:alpha" maskUnits="userSpaceOnUse" x="5" y="5" width="30" height="30"><path fill-rule="evenodd" clip-rule="evenodd" d="M26.0227 34.1285C26.2519 34.2179 26.4969 34.2592 26.7427 34.2497C26.9884 34.2403 27.2296 34.1804 27.4512 34.0738L33.3809 31.2206C33.6863 31.0736 33.9439 30.8433 34.1243 30.5563C34.3046 30.2693 34.4002 29.9372 34.4001 29.5983V10.2522C34.4001 9.91323 34.3044 9.58119 34.1241 9.29424C33.9437 9.00729 33.686 8.77709 33.3806 8.63014L27.4518 5.77692C27.1167 5.6157 26.7398 5.56263 26.3733 5.62507C26.0067 5.6875 25.6687 5.86235 25.4059 6.1254L14.0543 16.4807L9.10994 12.7281C8.88691 12.5587 8.61163 12.4728 8.33186 12.4852C8.05209 12.4976 7.78549 12.6076 7.57835 12.7961L5.99262 14.2387C5.86908 14.3511 5.77035 14.488 5.70276 14.6408C5.63517 14.7935 5.60021 14.9587 5.6001 15.1257C5.59999 15.2928 5.63474 15.458 5.70213 15.6108C5.76952 15.7636 5.86807 15.9007 5.99147 16.0133L10.2792 19.9252L5.99176 23.8371C5.86836 23.9497 5.76981 24.0868 5.70242 24.2396C5.63503 24.3925 5.60028 24.5577 5.60039 24.7247C5.60049 24.8917 5.63546 25.0569 5.70305 25.2097C5.77064 25.3624 5.86936 25.4994 5.99291 25.6118L7.57864 27.0547C7.78578 27.2431 8.05237 27.3531 8.33214 27.3655C8.61191 27.3779 8.8872 27.292 9.11022 27.1226L14.0546 23.3694L25.4059 33.7253C25.5814 33.9011 25.7913 34.0384 26.0227 34.1285ZM27.2044 13.3876L18.5918 19.9252L27.2047 26.4631L27.2044 13.3876Z" fill="#ffffff"/></mask><g mask="url(#mask0_5437_79124)"><path d="M33.3807 8.6342L27.4467 5.77724C27.1116 5.61588 26.7346 5.56266 26.368 5.62494C26.0013 5.68722 25.663 5.86191 25.3999 6.12486L5.97403 23.8369C5.85059 23.9494 5.75201 24.0865 5.68459 24.2393C5.61718 24.3922 5.58241 24.5574 5.58252 24.7245C5.58263 24.8915 5.61761 25.0567 5.68522 25.2094C5.75284 25.3622 5.8516 25.4991 5.97518 25.6115L7.56206 27.0541C7.76938 27.2425 8.03605 27.3524 8.31587 27.3648C8.59569 27.3772 8.87105 27.2913 9.09422 27.1221L32.4879 9.37551C33.2727 8.78022 34.3999 9.3398 34.3999 10.3251V10.2559C34.3999 9.91713 34.3042 9.58524 34.1239 9.2984C33.9436 9.01157 33.686 8.78145 33.3807 8.63449V8.6342Z" fill="#0065A9"/><g filter="url(#filter0_d_5437_79124)"><path d="M33.3807 31.2161L27.4467 34.0731C27.1116 34.2345 26.7346 34.2877 26.3679 34.2255C26.0012 34.1632 25.663 33.9885 25.3999 33.7255L5.97403 16.0135C5.85059 15.9009 5.75201 15.7638 5.68459 15.611C5.61718 15.4582 5.58241 15.2929 5.58252 15.1259C5.58263 14.9588 5.61761 14.7937 5.68522 14.6409C5.75284 14.4882 5.8516 14.3512 5.97518 14.2388L7.56206 12.7962C7.76938 12.6079 8.03605 12.498 8.31587 12.4856C8.59569 12.4731 8.87105 12.559 9.09422 12.7282L32.4879 30.4748C33.2727 31.0701 34.3999 30.5105 34.3999 29.5253V29.5944C34.3999 29.9332 34.3042 30.2651 34.1239 30.5519C33.9436 30.8388 33.686 31.0692 33.3807 31.2161Z" fill="#007ACC"/></g><g filter="url(#filter1_d_5437_79124)"><path d="M27.447 34.0738C27.1118 34.235 26.7347 34.2881 26.3679 34.2257C26.0012 34.1633 25.6629 33.9884 25.3999 33.7253C26.064 34.3898 27.1999 33.9194 27.1999 32.98V6.87104C27.1999 5.93159 26.064 5.46128 25.3999 6.12541C25.6629 5.86234 26.0012 5.68749 26.3679 5.62506C26.7347 5.56263 27.1118 5.6157 27.447 5.77693L33.3798 8.63044C33.6853 8.77731 33.9432 9.00748 34.1236 9.29443C34.3041 9.58139 34.3999 9.91347 34.3999 10.2525V29.5986C34.3999 29.9376 34.3042 30.2697 34.1238 30.5567C33.9434 30.8437 33.6856 31.0739 33.3801 31.2209L27.447 34.0738Z" fill="#1F9CF0"/></g><path opacity="0.25" fill-rule="evenodd" clip-rule="evenodd" d="M26.0052 34.1285C26.2343 34.2179 26.4793 34.2591 26.7251 34.2497C26.9709 34.2403 27.212 34.1804 27.4336 34.0738L33.3633 31.2206C33.6687 31.0736 33.9265 30.8434 34.1068 30.5564C34.2872 30.2694 34.3829 29.9372 34.3828 29.5983V10.2522C34.3828 9.91323 34.2871 9.58119 34.1068 9.29424C33.9264 9.00729 33.6687 8.77709 33.3633 8.63014L27.4339 5.77692C27.0989 5.6157 26.722 5.56263 26.3554 5.62507C25.9889 5.6875 25.6508 5.86235 25.388 6.1254L14.0367 16.4807L9.09236 12.7281C8.86936 12.5588 8.59413 12.4729 8.31442 12.4853C8.03472 12.4977 7.76818 12.6077 7.56106 12.7961L5.97504 14.2387C5.8515 14.3511 5.75277 14.488 5.68518 14.6408C5.6176 14.7935 5.58263 14.9587 5.58252 15.1257C5.58241 15.2928 5.61716 15.458 5.68456 15.6108C5.75195 15.7636 5.85049 15.9007 5.97389 16.0133L10.2616 19.9252L5.97389 23.8371C5.85049 23.9497 5.75195 24.0868 5.68456 24.2396C5.61716 24.3925 5.58241 24.5577 5.58252 24.7247C5.58263 24.8917 5.6176 25.0569 5.68518 25.2097C5.75277 25.3624 5.8515 25.4994 5.97504 25.6118L7.56106 27.0544C7.76818 27.2428 8.03472 27.3527 8.31442 27.3651C8.59413 27.3775 8.86936 27.2916 9.09236 27.1223L14.0367 23.3697L25.388 33.7256C25.5635 33.9014 25.7737 34.0384 26.0052 34.1285ZM27.1868 13.3876L18.5739 19.9252L27.1868 26.4631V13.3876Z" fill="url(#paint0_linear_5437_79124)" style="mix-blend-mode:overlay"/></g><defs><filter id="filter0_d_5437_79124" x="-7.75188" y="-0.850024" width="55.4862" height="48.4354" filterUnits="userSpaceOnUse" color-interpolation-filters="sRGB"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feColorMatrix in="SourceAlpha" type="matrix" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0" result="hardAlpha"/><feOffset/><feGaussianBlur stdDeviation="6.6672"/><feColorMatrix type="matrix" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.25 0"/><feBlend mode="overlay" in2="BackgroundImageFix" result="effect1_dropShadow_5437_79124"/><feBlend mode="normal" in="SourceGraphic" in2="effect1_dropShadow_5437_79124" result="shape"/></filter><filter id="filter1_d_5437_79124" x="12.0655" y="-7.73479" width="35.6688" height="55.3202" filterUnits="userSpaceOnUse" color-interpolation-filters="sRGB"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feColorMatrix in="SourceAlpha" type="matrix" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0" result="hardAlpha"/><feOffset/><feGaussianBlur stdDeviation="6.6672"/><feColorMatrix type="matrix" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.25 0"/><feBlend mode="overlay" in2="BackgroundImageFix" result="effect1_dropShadow_5437_79124"/><feBlend mode="normal" in="SourceGraphic" in2="effect1_dropShadow_5437_79124" result="shape"/></filter><linearGradient id="paint0_linear_5437_79124" x1="19.9825" y1="5.59951" x2="19.9825" y2="34.2509" gradientUnits="userSpaceOnUse"><stop stop-color="#ffffff"/><stop offset="1" stop-color="#ffffff" stop-opacity="0"/></linearGradient></defs></g>"## }; +static CURSOR: Icon = Icon { name: "app-cursor", view: 40.0, body: r##"<g fill="none"><g clip-path="url(#clip0_5436_78947)"><mask id="mask0_5436_78947" style="mask-type:luminance" maskUnits="userSpaceOnUse" x="4" y="4" width="32" height="32"><path d="M4 4H36V36H4V4Z" fill="#ffffff"/></mask><g mask="url(#mask0_5436_78947)"><path d="M28.375 4H11.625C7.41383 4 4 7.41383 4 11.625V28.375C4 32.5862 7.41383 36 11.625 36H28.375C32.5862 36 36 32.5862 36 28.375V11.625C36 7.41383 32.5862 4 28.375 4Z" fill="#000000"/></g><path d="M29.6214 14.2072L20.9502 9.12249C20.6718 8.95917 20.3282 8.95917 20.0498 9.12249L11.3786 14.2072C11.1445 14.3445 11 14.5984 11 14.8733V25.1267C11 25.4012 11.1445 25.6555 11.3786 25.7928L20.0498 30.8775C20.3282 31.0408 20.6718 31.0408 20.9502 30.8775L29.6214 25.7928C29.8555 25.6555 30 25.4016 30 25.1267V14.8733C30 14.5988 29.8555 14.3445 29.6214 14.2072ZM29.0767 15.2843L20.706 30.0101C20.6494 30.1093 20.5 30.0688 20.5 29.9538V20.3115C20.5 20.1189 20.3986 19.9407 20.2342 19.8439L12.0124 15.0226C11.9147 14.9651 11.9546 14.8134 12.0678 14.8134H28.8093C29.047 14.8134 29.1956 15.0751 29.0767 15.2843Z" fill="#ffffff"/></g><defs><clipPath id="clip0_5436_78947"><rect width="32" height="32" fill="#ffffff" transform="translate(4 4)"/></clipPath></defs></g>"## }; +static ZED: Icon = Icon { name: "app-zed", view: 40.0, body: r##"<g fill="none"><g clip-path="url(#clip0_5437_79109)"><mask id="mask0_5437_79109" style="mask-type:luminance" maskUnits="userSpaceOnUse" x="5" y="5" width="30" height="30"><path d="M5.6001 5.59961H34.4001V34.3996H5.6001V5.59961Z" fill="#ffffff"/></mask><g mask="url(#mask0_5437_79109)"><path fill-rule="evenodd" clip-rule="evenodd" d="M8.3001 7.39961C8.0614 7.39961 7.83248 7.49443 7.6637 7.66321C7.49492 7.832 7.4001 8.06091 7.4001 8.29961V28.0996H5.6001V8.29961C5.6001 7.58352 5.88456 6.89677 6.39091 6.39042C6.89726 5.88407 7.58401 5.59961 8.3001 5.59961H32.4138C33.6165 5.59961 34.2186 7.05371 33.3684 7.90421L18.5166 22.7557H22.7001V20.8996H24.5001V23.206C24.5001 23.5641 24.3579 23.9074 24.1047 24.1606C23.8515 24.4138 23.5081 24.556 23.1501 24.556H16.7166L13.623 27.6496H27.6501V16.3996H29.4501V27.6496C29.4501 28.127 29.2605 28.5848 28.9229 28.9224C28.5853 29.26 28.1275 29.4496 27.6501 29.4496H11.823L8.673 32.5996H31.7001C31.9388 32.5996 32.1677 32.5048 32.3365 32.336C32.5053 32.1672 32.6001 31.9383 32.6001 31.6996V11.8996H34.4001V31.6996C34.4001 32.4157 34.1156 33.1024 33.6093 33.6088C33.1029 34.1151 32.4162 34.3996 31.7001 34.3996H7.5864C6.3837 34.3996 5.7816 32.9455 6.6318 32.095L21.4272 17.2996H17.3001V19.0996H15.5001V16.8496C15.5001 16.4916 15.6423 16.1482 15.8955 15.895C16.1487 15.6418 16.4921 15.4996 16.8501 15.4996H23.2272L26.3772 12.3496H12.3501V23.5996H10.5501V12.3496C10.5501 11.8722 10.7397 11.4144 11.0773 11.0768C11.4149 10.7393 11.8727 10.5496 12.3501 10.5496H28.1772L31.3272 7.39961H8.3001Z" fill="#000000"/></g></g><defs><clipPath id="clip0_5437_79109"><rect width="28.8" height="28.8" fill="#ffffff" transform="translate(5.6001 5.59961)"/></clipPath></defs></g>"## }; +static ZED_DARK: Icon = Icon { name: "app-zed-dark", view: 40.0, body: r##"<g fill="none"><g clip-path="url(#clip0_5437_79100)"><mask id="mask0_5437_79100" style="mask-type:luminance" maskUnits="userSpaceOnUse" x="5" y="5" width="30" height="30"><path d="M5.6001 5.59961H34.4001V34.3996H5.6001V5.59961Z" fill="#ffffff"/></mask><g mask="url(#mask0_5437_79100)"><path fill-rule="evenodd" clip-rule="evenodd" d="M8.3001 7.39961C8.0614 7.39961 7.83248 7.49443 7.6637 7.66321C7.49492 7.832 7.4001 8.06091 7.4001 8.29961V28.0996H5.6001V8.29961C5.6001 7.58352 5.88456 6.89677 6.39091 6.39042C6.89726 5.88407 7.58401 5.59961 8.3001 5.59961H32.4138C33.6165 5.59961 34.2186 7.05371 33.3684 7.90421L18.5166 22.7557H22.7001V20.8996H24.5001V23.206C24.5001 23.5641 24.3579 23.9074 24.1047 24.1606C23.8515 24.4138 23.5081 24.556 23.1501 24.556H16.7166L13.623 27.6496H27.6501V16.3996H29.4501V27.6496C29.4501 28.127 29.2605 28.5848 28.9229 28.9224C28.5853 29.26 28.1275 29.4496 27.6501 29.4496H11.823L8.673 32.5996H31.7001C31.9388 32.5996 32.1677 32.5048 32.3365 32.336C32.5053 32.1672 32.6001 31.9383 32.6001 31.6996V11.8996H34.4001V31.6996C34.4001 32.4157 34.1156 33.1024 33.6093 33.6088C33.1029 34.1151 32.4162 34.3996 31.7001 34.3996H7.5864C6.3837 34.3996 5.7816 32.9455 6.6318 32.095L21.4272 17.2996H17.3001V19.0996H15.5001V16.8496C15.5001 16.4916 15.6423 16.1482 15.8955 15.895C16.1487 15.6418 16.4921 15.4996 16.8501 15.4996H23.2272L26.3772 12.3496H12.3501V23.5996H10.5501V12.3496C10.5501 11.8722 10.7397 11.4144 11.0773 11.0768C11.4149 10.7393 11.8727 10.5496 12.3501 10.5496H28.1772L31.3272 7.39961H8.3001Z" fill="#ffffff"/></g></g><defs><clipPath id="clip0_5437_79100"><rect width="28.8" height="28.8" fill="#ffffff" transform="translate(5.6001 5.59961)"/></clipPath></defs></g>"## }; +static FILE_EXPLORER: Icon = Icon { name: "app-file-explorer", view: 40.0, body: r##"<g fill="none"><path d="M16.2414 8.05369L14.955 6.65636C14.7646 6.44946 14.5333 6.2843 14.2757 6.17133C14.0182 6.05836 13.7401 6.00002 13.4588 6H4.86684C4.753 5.99995 4.64025 6.02234 4.53506 6.06589C4.42987 6.10944 4.33429 6.17329 4.25379 6.25379C4.17329 6.33429 4.10944 6.42987 4.06589 6.53506C4.02234 6.64025 3.99995 6.753 4 6.86684V12.8779L4.04302 12.8825C4.10268 12.6706 4.22985 12.4839 4.40523 12.3508C4.5806 12.2177 4.7946 12.1455 5.01476 12.1451H13.189C14.3506 12.1451 15.4795 11.6366 16.1675 10.7004C16.5166 10.2255 16.9726 9.83942 17.4985 9.57327C18.0244 9.30713 18.6056 9.16842 19.195 9.16836H34.9852C35.2544 9.16836 35.5125 9.27527 35.7028 9.46557C35.8931 9.65587 36 9.91398 36 10.1831V8.99058C36 8.77152 35.913 8.56144 35.7581 8.40654C35.6032 8.25164 35.3931 8.16462 35.174 8.16462H16.4953C16.4476 8.16469 16.4004 8.15486 16.3567 8.13577C16.313 8.11667 16.2738 8.08873 16.2414 8.05369Z" fill="url(#paint0_linear_5437_79060)"/><path d="M16.2002 10.3751C15.8497 10.8375 15.397 11.2125 14.8774 11.4707C14.3579 11.7289 13.7855 11.8634 13.2053 11.8634H5.01476C4.88147 11.8634 4.74948 11.8897 4.62634 11.9407C4.5032 11.9917 4.39132 12.0665 4.29709 12.1608C4.20286 12.255 4.12812 12.3669 4.07714 12.4901C4.02617 12.6133 3.99995 12.7453 4 12.8785V32.4302C4 32.6993 4.10691 32.9574 4.29722 33.1477C4.48752 33.338 4.74563 33.4449 5.01476 33.4449H34.9852C35.2544 33.4449 35.5125 33.338 35.7028 33.1477C35.8931 32.9574 36 32.6993 36 32.4302V9.90147C36 9.63234 35.8931 9.37424 35.7028 9.18393C35.5125 8.99363 35.2544 8.88672 34.9852 8.88672H19.195C18.6148 8.88679 18.0425 9.0212 17.5229 9.27942C17.0033 9.53764 16.5506 9.91265 16.2002 10.3751Z" fill="url(#paint1_linear_5437_79060)"/><path d="M27.7632 23.2969H12.2368C11.7852 23.2968 11.3379 23.3857 10.9207 23.5585C10.5034 23.7312 10.1242 23.9846 9.80488 24.3039C9.48553 24.6233 9.23222 25.0024 9.05943 25.4197C8.88664 25.8369 8.79776 26.2842 8.79785 26.7358V33.4448H31.2025V26.7358C31.2021 24.8364 29.6626 23.2969 27.7632 23.2969Z" fill="url(#paint2_linear_5437_79060)"/><path d="M26.5965 29.7865H13.404C13.2154 29.7865 13.0345 29.7116 12.9012 29.5782C12.7678 29.4448 12.6929 29.264 12.6929 29.0754C12.6929 28.8868 12.7678 28.7059 12.9012 28.5725C13.0345 28.4392 13.2154 28.3643 13.404 28.3643H26.5965C26.7851 28.3643 26.966 28.4392 27.0993 28.5725C27.2327 28.7059 27.3076 28.8868 27.3076 29.0754C27.3076 29.264 27.2327 29.4448 27.0993 29.5782C26.966 29.7116 26.7851 29.7865 26.5965 29.7865Z" fill="#10498A"/><defs><linearGradient id="paint0_linear_5437_79060" x1="19.7682" y1="9.59964" x2="19.2608" y2="6.75804" gradientUnits="userSpaceOnUse"><stop stop-color="#CE9918"/><stop offset="0.5902" stop-color="#DF9E00"/></linearGradient><linearGradient id="paint1_linear_5437_79060" x1="26.3559" y1="28.492" x2="13.062" y2="13.1687" gradientUnits="userSpaceOnUse"><stop stop-color="#F5B509"/><stop offset="1" stop-color="#FECE49"/></linearGradient><linearGradient id="paint2_linear_5437_79060" x1="27.4873" y1="32.5737" x2="7.9015" y2="23.2375" gradientUnits="userSpaceOnUse"><stop stop-color="#0161B2"/><stop offset="1" stop-color="#1291DD"/></linearGradient></defs></g>"## }; +static ITERM2: Icon = Icon { name: "app-iterm2", view: 40.0, body: r##"<g fill="none"><rect x="4" y="4" width="32" height="32" rx="6.4" fill="url(#paint0_linear_5437_79079)"/><rect x="4.80005" y="4.7998" width="30.4" height="30.4" rx="5.6" fill="#000000"/><rect x="7.19995" y="7.2002" width="25.6" height="25.6" rx="3.2" fill="#202A2F"/><path d="M25.2454 8.85742H19.2454V20.8574H25.2454V8.85742Z" fill="#0EE827" fill-opacity="0.35"/><path d="M11.7895 18.9218C11.4758 18.8949 11.1817 18.85 10.9072 18.7872C10.6424 18.7154 10.3973 18.6392 10.1718 18.5584C9.95613 18.4776 9.76496 18.4014 9.59829 18.3296C9.44145 18.2488 9.32378 18.186 9.24536 18.1412L9.87771 16.9567C9.94631 17.0016 10.064 17.0644 10.2306 17.1452C10.3973 17.2259 10.5836 17.3111 10.7895 17.4009C11.0052 17.4816 11.2257 17.5534 11.4513 17.6162C11.6768 17.679 11.8875 17.7105 12.0836 17.7105C13.064 17.7105 13.5542 17.3381 13.5542 16.5933C13.5542 16.4138 13.5199 16.2658 13.4512 16.1492C13.3925 16.0325 13.2993 15.9338 13.1719 15.853C13.0542 15.7633 12.9071 15.687 12.7307 15.6242C12.564 15.5525 12.3729 15.4806 12.1571 15.4089C11.7453 15.2653 11.3777 15.1172 11.0542 14.9647C10.7405 14.8032 10.4708 14.6237 10.2454 14.4263C10.0199 14.2289 9.8483 14.0046 9.73063 13.7534C9.61303 13.5021 9.5542 13.2149 9.5542 12.8919C9.5542 12.6407 9.60812 12.3984 9.71596 12.1651C9.82379 11.9318 9.97572 11.7254 10.1718 11.546C10.3679 11.3576 10.6032 11.2005 10.8777 11.0749C11.1522 10.9403 11.4562 10.8461 11.7895 10.7922V8.85742H12.9954V10.7653C13.2503 10.7922 13.4954 10.8326 13.7307 10.8865C13.966 10.9403 14.1767 10.9986 14.363 11.0614C14.5493 11.1242 14.7062 11.1871 14.8336 11.2499C14.9709 11.3037 15.0689 11.3441 15.1278 11.371L14.5395 12.4747C14.4611 12.4388 14.3483 12.3939 14.2012 12.3401C14.064 12.2773 13.9072 12.2144 13.7307 12.1517C13.5542 12.0888 13.363 12.035 13.1571 11.9901C12.9513 11.9453 12.7454 11.9228 12.5395 11.9228C12.2062 11.9228 11.9071 11.9856 11.6424 12.1112C11.3875 12.2279 11.2601 12.4298 11.2601 12.7169C11.2601 12.8964 11.2944 13.058 11.363 13.2015C11.4414 13.3361 11.5493 13.4573 11.6865 13.5649C11.8336 13.6726 12.0101 13.7758 12.2159 13.8745C12.4316 13.9642 12.6768 14.054 12.9513 14.1437C13.314 14.2782 13.6376 14.4173 13.9218 14.5609C14.2062 14.7045 14.4463 14.866 14.6424 15.0455C14.8385 15.2249 14.9856 15.4313 15.0836 15.6646C15.1914 15.8979 15.2454 16.1715 15.2454 16.4856C15.2454 16.7548 15.1964 17.015 15.0983 17.2662C15.0101 17.5175 14.8679 17.7508 14.6718 17.9661C14.4856 18.1815 14.2503 18.3699 13.966 18.5315C13.6915 18.684 13.3679 18.7962 12.9954 18.8679V20.8574H11.7895V18.9218Z" fill="#0EE827"/><defs><linearGradient id="paint0_linear_5437_79079" x1="20" y1="4" x2="20" y2="36" gradientUnits="userSpaceOnUse"><stop stop-color="#D4E6E8"/><stop offset="1" stop-color="#767573"/></linearGradient></defs></g>"## }; +static GHOSTTY: Icon = Icon { name: "app-ghostty", view: 40.0, body: r##"<g fill="none"><g clip-path="url(#clip0_5437_79067)"><path d="M27.395 36C26.1435 35.9986 24.9203 35.6274 23.879 34.933C22.8374 35.6273 21.6139 35.9985 20.362 36C19.113 36 17.882 35.625 16.846 34.933C15.8189 35.6241 14.61 35.9954 13.372 36H13.334C12.4944 36.0006 11.6633 35.8321 10.8902 35.5047C10.1171 35.1772 9.41781 34.6975 8.83405 34.094C7.65642 32.8996 6.99679 31.2893 6.99805 29.612V17.362C7.00005 9.995 12.994 4 20.362 4C27.731 4 33.725 9.994 33.725 17.363V29.616C33.725 33.009 31.099 35.808 27.747 35.991C27.63 35.998 27.513 36 27.395 36Z" fill="#3551F3"/><path d="M27.395 34.5932C26.2752 34.5924 25.1889 34.2104 24.315 33.5102C24.1961 33.4145 24.0476 33.3632 23.895 33.3652C23.7174 33.367 23.5457 33.4291 23.408 33.5412C22.5392 34.2237 21.4668 34.5951 20.362 34.5962C19.2576 34.5949 18.1855 34.2234 17.317 33.5412C17.1835 33.4338 17.0174 33.3752 16.846 33.3752C16.6747 33.3752 16.5085 33.4338 16.375 33.5412C15.518 34.2199 14.4581 34.5914 13.365 34.5962H13.332C12.6806 34.5961 12.0359 34.4649 11.4362 34.2102C10.8366 33.9556 10.2945 33.5829 9.84201 33.1142C8.92225 32.1822 8.40639 30.9256 8.40601 29.6162V17.3672C8.40601 10.7702 13.77 5.40723 20.363 5.40723C26.955 5.40723 32.319 10.7702 32.319 17.3632V29.6162C32.319 32.2612 30.277 34.4432 27.669 34.5862C27.5777 34.5909 27.4864 34.5932 27.395 34.5932Z" fill="#000000"/><path d="M30.912 17.3635V29.6165C30.912 31.4925 29.465 33.0795 27.592 33.1825C26.725 33.2323 25.8704 32.9582 25.194 32.4135C24.416 31.7875 23.321 31.8155 22.536 32.4345C21.9163 32.9237 21.1495 33.1891 20.36 33.1875C19.5714 33.1889 18.8056 32.9235 18.187 32.4345C17.8057 32.1306 17.3326 31.9651 16.845 31.9651C16.3574 31.9651 15.8843 32.1306 15.503 32.4345C14.8904 32.9183 14.1336 33.1834 13.353 33.1875C11.405 33.2015 9.81299 31.5605 9.81299 29.6125V17.3625C9.81299 11.5375 14.537 6.81348 20.363 6.81348C26.188 6.81348 30.912 11.5375 30.912 17.3635Z" fill="#ffffff"/><path d="M18.28 16.4366L14.35 14.1666C14.104 14.0248 13.8117 13.9865 13.5374 14.06C13.2632 14.1335 13.0292 14.3128 12.887 14.5586C12.7452 14.8045 12.7067 15.0966 12.78 15.3709C12.8533 15.6452 13.0324 15.8792 13.278 16.0216L15.604 17.3646L13.278 18.7076C13.045 18.8559 12.8783 19.0886 12.8126 19.3569C12.7469 19.6252 12.7873 19.9085 12.9255 20.1478C13.0636 20.387 13.2887 20.5637 13.554 20.641C13.8192 20.7183 14.104 20.6902 14.349 20.5626L18.281 18.2926C18.4436 18.1985 18.5786 18.0633 18.6724 17.9006C18.7662 17.7379 18.8156 17.5534 18.8156 17.3656C18.8156 17.1777 18.7662 16.9932 18.6724 16.8305C18.5786 16.6678 18.4436 16.5326 18.281 16.4386V16.4366H18.28ZM27.182 16.2906H22.018C21.7338 16.2906 21.4613 16.4034 21.2604 16.6044C21.0594 16.8053 20.9465 17.0779 20.9465 17.3621C20.9465 17.6462 21.0594 17.9188 21.2604 18.1197C21.4613 18.3207 21.7338 18.4336 22.018 18.4336H27.182C27.4662 18.4336 27.7387 18.3207 27.9397 18.1197C28.1406 17.9188 28.2535 17.6462 28.2535 17.3621C28.2535 17.0779 28.1406 16.8053 27.9397 16.6044C27.7387 16.4034 27.4662 16.2906 27.182 16.2906Z" fill="#000000"/></g><defs><clipPath id="clip0_5437_79067"><rect width="27" height="32" fill="#ffffff" transform="translate(7 4)"/></clipPath></defs></g>"## }; +static ANDROID_STUDIO: Icon = Icon { name: "app-android-studio", view: 40.0, body: r##"<g fill="none"><mask id="mask0_5436_78784" style="mask-type:luminance" maskUnits="userSpaceOnUse" x="2" y="2" width="36" height="36"><path d="M36.5936 2H3.4064C2.62967 2 2 2.62967 2 3.4064V36.5936C2 37.3703 2.62967 38 3.4064 38H36.5936C37.3703 38 38 37.3703 38 36.5936V3.4064C38 2.62967 37.3703 2 36.5936 2Z" fill="#ffffff"/></mask><g mask="url(#mask0_5436_78784)"><path opacity="0.2" d="M15.7562 37.8478C15.1622 37.7074 14.666 37.378 13.9706 36.6652C12.8096 35.4736 11.867 34.978 10.229 34.696C8.53043 34.4032 7.77503 33.772 7.32143 32.2636C6.76103 30.4012 6.17543 29.5096 4.88843 28.5592C3.42863 27.481 3.05423 26.5306 3.41063 24.8074C3.74063 23.2114 3.61463 22.0774 2.94383 20.6182C2.14463 18.8782 2.24303 17.9482 3.37883 16.522C4.41983 15.214 4.74683 14.35 4.90283 12.4924C5.06003 10.6174 5.58203 9.84819 7.11803 9.22539C8.40083 8.70579 9.49763 7.80339 10.106 6.76899C10.8092 5.57199 10.9118 5.43519 11.3474 5.10999C12.0506 4.58559 12.6194 4.43979 13.7018 4.50759C15.5828 4.62579 16.5908 4.39959 17.8538 3.57759C19.5008 2.50539 20.4992 2.50539 22.1462 3.57759C23.4092 4.39959 24.4172 4.62579 26.2982 4.50759C28.0766 4.39659 28.8164 4.86339 29.9006 6.78099C30.4382 7.73139 31.5362 8.65599 32.7386 9.17019C34.4498 9.90279 34.9478 10.5718 35.0738 12.3094C35.2106 14.191 35.5964 15.2434 36.6188 16.5214C37.757 17.9452 37.856 18.8764 37.0556 20.6182C36.3854 22.0768 36.2594 23.2114 36.5894 24.8074C36.9452 26.5306 36.5714 27.481 35.111 28.5592C33.8246 29.5096 33.239 30.4012 32.6786 32.2636C32.2244 33.772 31.4696 34.4032 29.7704 34.696C28.1294 34.978 27.1856 35.476 26.0294 36.6688C24.7472 37.9912 23.8274 38.209 22.0352 37.6168C20.5694 37.132 19.4402 37.1302 17.9798 37.609C16.9574 37.945 16.412 38.0032 15.7562 37.8478Z" fill="#000000"/><path d="M15.7562 37.4962C15.1622 37.3558 14.666 37.0264 13.9706 36.3136C12.8096 35.122 11.867 34.6264 10.229 34.3444C8.53043 34.0516 7.77503 33.4204 7.32143 31.912C6.76103 30.0496 6.17543 29.158 4.88843 28.2076C3.42863 27.1294 3.05423 26.179 3.41063 24.4558C3.74063 22.8598 3.61463 21.7258 2.94383 20.2666C2.14463 18.5266 2.24303 17.5966 3.37883 16.1704C4.41983 14.8624 4.74683 13.9984 4.90283 12.1408C5.06003 10.2658 5.58203 9.49662 7.11803 8.87382C8.40083 8.35422 9.49763 7.45182 10.106 6.41742C10.8092 5.22042 10.9118 5.08362 11.3474 4.75842C12.0506 4.23402 12.6194 4.08822 13.7018 4.15602C15.5828 4.27422 16.5908 4.04802 17.8538 3.22602C19.5008 2.15383 20.4992 2.15383 22.1462 3.22602C23.4092 4.04802 24.4172 4.27422 26.2982 4.15602C28.0766 4.04502 28.8164 4.51182 29.9006 6.42942C30.4382 7.37982 31.5362 8.30442 32.7386 8.81862C34.4498 9.55122 34.9478 10.2202 35.0738 11.9578C35.2106 13.8394 35.5964 14.8918 36.6188 16.1698C37.757 17.5936 37.856 18.5248 37.0556 20.2666C36.3854 21.7258 36.2594 22.8604 36.5894 24.4558C36.9452 26.179 36.5714 27.1294 35.111 28.2076C33.8246 29.158 33.239 30.0496 32.6786 31.912C32.2244 33.4204 31.4696 34.0516 29.7704 34.3444C28.1294 34.6264 27.1856 35.1244 26.0294 36.3172C24.7472 37.6396 23.8274 37.8574 22.0352 37.2652C20.5694 36.7804 19.4402 36.7786 17.9798 37.2574C16.9574 37.5934 16.412 37.6516 15.7562 37.4962Z" fill="#ffffff"/><path d="M28.0543 30.5054C28.0876 30.6095 28.0808 30.7223 28.0352 30.8217C27.9896 30.9211 27.9086 30.9999 27.8079 31.0426C27.7073 31.0854 27.5943 31.089 27.4912 31.0527C27.388 31.0165 27.3021 30.9431 27.2503 30.8468L26.1937 28.8848C26.1508 28.8057 26.125 28.7185 26.1178 28.6288C26.1106 28.5392 26.1222 28.449 26.1519 28.3641C26.1816 28.2792 26.2287 28.2014 26.2902 28.1358C26.3517 28.0702 26.4263 28.0181 26.5091 27.983C26.5919 27.9478 26.6811 27.9304 26.7711 27.9317C26.861 27.9331 26.9497 27.9532 27.0314 27.9908C27.1131 28.0285 27.186 28.0827 27.2455 28.1502C27.305 28.2177 27.3497 28.2968 27.3769 28.3826L28.0543 30.5054Z" fill="#034ECA"/><path d="M28.0543 30.5054C28.0876 30.6095 28.0808 30.7223 28.0352 30.8217C27.9896 30.9211 27.9086 30.9999 27.8079 31.0426C27.7073 31.0854 27.5943 31.089 27.4912 31.0527C27.388 31.0165 27.3021 30.9431 27.2503 30.8468L26.1937 28.8848C26.1508 28.8057 26.125 28.7185 26.1178 28.6288C26.1106 28.5392 26.1222 28.449 26.1519 28.3641C26.1816 28.2792 26.2287 28.2014 26.2902 28.1358C26.3517 28.0702 26.4263 28.0181 26.5091 27.983C26.5919 27.9478 26.6811 27.9304 26.7711 27.9317C26.861 27.9331 26.9497 27.9532 27.0314 27.9908C27.1131 28.0285 27.186 28.0827 27.2455 28.1502C27.305 28.2177 27.3497 28.2968 27.3769 28.3826L28.0543 30.5054Z" fill="url(#paint0_linear_5436_78784)"/><mask id="mask1_5436_78784" style="mask-type:alpha" maskUnits="userSpaceOnUse" x="24" y="16" width="7" height="8"><path d="M27.2289 23.4656C27.6264 23.2061 27.9706 22.8729 28.2429 22.484C28.5285 22.0786 28.7308 21.6206 28.8381 21.1364L28.8459 21.1376L29.2899 21.2216C29.5379 21.2683 29.7859 21.3149 30.0339 21.3614C30.0861 21.3707 30.1397 21.368 30.1907 21.3535C30.2416 21.3389 30.2886 21.3129 30.3279 21.2774C30.3896 21.2221 30.4289 21.1461 30.4385 21.0638C30.4481 20.9815 30.4274 20.8985 30.3801 20.8304C30.3548 20.7933 30.3225 20.7616 30.2849 20.737C30.2473 20.7123 30.2053 20.6954 30.1611 20.687C30.0574 20.6676 29.9536 20.6482 29.8497 20.6288L29.4171 20.5472L28.9731 20.4632L28.9251 20.4548L28.9263 20.4176C28.9374 19.9613 28.8648 19.5068 28.7121 19.0766L28.6989 19.0406C28.544 18.6143 28.3128 18.2197 28.0167 17.876C28.0269 17.864 28.0365 17.852 28.0467 17.8412L28.3395 17.498L28.6251 17.1632L28.8303 16.9226C28.889 16.8533 28.9181 16.7636 28.9113 16.673C28.9079 16.6337 28.898 16.5951 28.8819 16.559C28.853 16.4945 28.8047 16.4406 28.7438 16.4047C28.6828 16.3688 28.6122 16.3527 28.5417 16.3586C28.4511 16.3657 28.367 16.4085 28.3077 16.4774L28.1025 16.718L27.8169 17.0534L27.5241 17.396L27.5211 17.399C26.8851 16.89 26.1015 16.6002 25.2873 16.5728C24.9589 16.5625 24.6305 16.5953 24.3105 16.6706L26.7969 23.708C26.9451 23.636 27.0903 23.5556 27.2289 23.4656Z" fill="#ffffff"/></mask><g mask="url(#mask1_5436_78784)"><path d="M31.0238 22.2636L28.3718 14.748L24.1436 16.2402L26.7956 23.7552L31.0238 22.2636Z" fill="#4FAF53"/><g opacity="0.8" filter="url(#filter0_f_5436_78784)"><path d="M28.5021 19.4415C28.2393 20.3715 27.4419 18.2955 26.0079 17.8911C24.5739 17.4861 22.8093 18.8391 23.0715 17.9091C23.5395 17.2263 24.7947 16.7049 26.2287 17.1099C27.6627 17.5143 28.5147 18.7263 28.5021 19.4415Z" fill="url(#paint1_linear_5436_78784)" fill-opacity="0.3"/></g><g opacity="0.7" filter="url(#filter1_f_5436_78784)"><path d="M28.3214 18.9303C27.533 18.3705 28.2152 20.4873 27.353 21.7023C26.4902 22.9173 24.2672 22.9719 25.055 23.5317C25.8482 23.7687 27.1526 23.3877 28.0148 22.1727C28.877 20.9577 28.7804 19.4787 28.3214 18.9303Z" fill="url(#paint2_linear_5436_78784)" fill-opacity="0.4"/></g><g opacity="0.6" filter="url(#filter2_f_5436_78784)"><path d="M25.2567 16.2322C24.2559 16.2634 23.4471 16.3834 23.4507 16.4992C23.4543 16.6156 24.2691 16.684 25.2699 16.6522C26.2707 16.621 27.6687 17.455 27.6651 17.3386C27.6615 17.2228 26.2575 16.2004 25.2567 16.2322Z" fill="#8BD8A0"/></g><g opacity="0.5" filter="url(#filter3_f_5436_78784)"><path d="M27.7943 23.4206C26.9945 24.0242 26.2901 24.4382 26.2199 24.3458C26.1503 24.2528 26.7413 23.6888 27.5399 23.0846C28.3391 22.481 28.9043 20.9546 28.9739 21.047C29.0441 21.14 28.5929 22.817 27.7937 23.4206H27.7943Z" fill="#8BD8A0"/></g><g opacity="0.7" filter="url(#filter4_f_5436_78784)"><path d="M28.1634 16.818C27.7974 17.2656 27.6198 17.4678 27.5802 17.436C27.5406 17.403 27.6546 17.148 28.02 16.701C28.245 16.14 28.914 16.413 28.9536 16.4454C28.9932 16.4778 28.6314 16.1796 28.1634 16.818Z" fill="#0D652D"/></g><g opacity="0.1" filter="url(#filter5_f_5436_78784)"><path d="M27.5104 17.3978C27.5446 17.4236 27.8152 17.1272 28.1146 16.7348C28.4146 16.343 28.6294 16.004 28.5952 15.9782C28.561 15.9518 28.2904 16.2482 27.991 16.6406C27.691 17.033 27.4762 17.3714 27.5104 17.3978Z" fill="#000000"/></g><g opacity="0.3" filter="url(#filter6_f_5436_78784)"><path d="M28.5244 17.0885C28.1422 17.5565 27.97 17.7797 28.0018 17.8055C28.0336 17.8313 28.2568 17.6501 28.639 17.1815C29.1886 16.6667 28.6186 16.2881 28.5658 16.3643C28.4098 16.5305 29.0728 16.4687 28.5244 17.0885Z" fill="#ffffff"/></g><path opacity="0.15" d="M28.3493 16.054C28.1837 16.1728 28.1621 16.4272 28.3013 16.6222C28.4417 16.8178 28.6889 16.8802 28.8551 16.7608C29.0207 16.642 29.0423 16.3876 28.9031 16.1926C28.7627 15.9976 28.5155 15.9358 28.3493 16.0546V16.054Z" fill="url(#paint3_radial_5436_78784)" fill-opacity="0.9"/><path opacity="0.15" d="M29.9893 20.5305C29.8237 20.6493 29.8021 20.9037 29.9419 21.0987C30.0817 21.2943 30.3289 21.3567 30.4951 21.2373C30.6607 21.1191 30.6823 20.8647 30.5431 20.6691C30.4033 20.4741 30.1555 20.4117 29.9893 20.5305Z" fill="url(#paint4_radial_5436_78784)" fill-opacity="0.9"/><g opacity="0.1" filter="url(#filter7_f_5436_78784)"><path d="M28.7985 21.1274C28.8081 21.0854 29.2065 21.1406 29.6871 21.2498C30.1683 21.359 30.5511 21.482 30.5409 21.5234C30.5313 21.5654 30.1341 21.5108 29.6529 21.4016C29.1717 21.2918 28.7889 21.1694 28.7985 21.1274Z" fill="#000000"/></g><mask id="mask2_5436_78784" style="mask-type:alpha" maskUnits="userSpaceOnUse" x="28" y="20" width="2" height="2"><path d="M28.8111 21.1823C28.8561 20.9783 28.9005 20.5349 28.9167 20.3387L29.3529 20.3105L29.2989 21.5609C29.1177 21.5195 28.7661 21.3857 28.8111 21.1823Z" fill="#000000"/></mask><g mask="url(#mask2_5436_78784)"><g style="mix-blend-mode:multiply" opacity="0.3" filter="url(#filter8_f_5436_78784)"><path d="M28.9099 21.2717C28.9315 20.9297 28.9135 20.6495 28.8709 20.6465C28.8277 20.6441 28.8031 20.9075 28.7821 21.2501C28.7611 21.5927 28.7521 21.8855 28.7953 21.8879C28.8379 21.8903 28.8895 21.6149 28.9105 21.2717H28.9099Z" fill="#0D652D"/></g><g style="mix-blend-mode:screen" opacity="0.3" filter="url(#filter9_f_5436_78784)"><path d="M28.9331 20.5775C28.9451 20.4803 28.9391 20.3993 28.9199 20.3975C28.9007 20.3945 28.8875 20.4695 28.8761 20.5667C28.8647 20.6645 28.8587 20.7479 28.8779 20.7503C28.8971 20.7521 28.9217 20.6753 28.9331 20.5775Z" fill="#81C995"/></g></g><mask id="mask3_5436_78784" style="mask-type:alpha" maskUnits="userSpaceOnUse" x="27" y="16" width="2" height="2"><path d="M27.4211 17.3477C27.5861 17.4737 27.9059 17.7857 28.0451 17.9249L28.3961 17.6663L27.5501 16.7441C27.4385 16.8923 27.2555 17.2205 27.4211 17.3477Z" fill="#000000"/></mask><g mask="url(#mask3_5436_78784)"><g style="mix-blend-mode:multiply" opacity="0.3" filter="url(#filter10_f_5436_78784)"><path d="M27.4388 17.2149C27.6758 17.4639 27.842 17.6889 27.8108 17.7189C27.7802 17.7489 27.5912 17.5629 27.3548 17.3139C27.1184 17.0649 26.9228 16.8471 26.9546 16.8177C26.9858 16.7877 27.2024 16.9659 27.4388 17.2149Z" fill="#0D652D"/></g><g style="mix-blend-mode:screen" opacity="0.3" filter="url(#filter11_f_5436_78784)"><path d="M27.9035 17.732C27.9749 17.7992 28.0223 17.8652 28.0091 17.879C27.9959 17.8928 27.9383 17.8442 27.8669 17.777C27.7949 17.7098 27.7367 17.6498 27.7499 17.6354C27.7631 17.6216 27.8321 17.6654 27.9035 17.732Z" fill="#81C995"/></g></g><g opacity="0.7" filter="url(#filter12_f_5436_78784)"><path d="M29.6884 21.2036C29.1202 21.098 28.8538 21.0584 28.8442 21.1082C28.8352 21.1586 29.0866 21.2798 29.6542 21.3854C30.1882 21.6686 30.523 21.0284 30.5326 20.9774C30.5422 20.9276 30.4576 21.3896 29.6884 21.2036Z" fill="#0D652D"/></g><g opacity="0.3" filter="url(#filter13_f_5436_78784)"><path d="M29.7868 20.7481C29.209 20.6401 28.9408 20.5819 28.9492 20.5393C28.957 20.4973 29.2372 20.4877 29.8156 20.5951C30.7612 20.6167 30.8716 21.2821 30.3796 21.3403C30.1636 21.3253 30.5842 20.8615 29.7868 20.7481Z" fill="#ffffff"/></g></g><path d="M26.4056 18.1092C26.3588 18.2244 26.3714 18.3396 26.4356 18.3654C26.4986 18.3912 26.5886 18.3186 26.636 18.2034C26.6828 18.0876 26.6696 17.973 26.606 17.9466C26.543 17.9208 26.453 17.994 26.4056 18.1092Z" fill="url(#paint5_radial_5436_78784)" fill-opacity="0.7"/><path d="M27.516 21.2687C27.4068 21.2087 27.345 21.1109 27.378 21.0509C27.411 20.9909 27.5268 20.9909 27.636 21.0509C27.7452 21.1109 27.807 21.2087 27.774 21.2687C27.741 21.3287 27.6252 21.3287 27.516 21.2687Z" fill="url(#paint6_radial_5436_78784)" fill-opacity="0.7"/><g style="mix-blend-mode:multiply" opacity="0.09" filter="url(#filter14_f_5436_78784)"><path d="M26.1009 18.4441C26.4009 18.4573 26.5251 18.2881 26.5491 18.2017C26.7249 17.9161 26.4399 17.7157 26.3067 17.6731C26.1735 17.6299 25.9479 17.5789 25.7337 17.7817C25.5201 17.9845 25.7259 18.4273 26.1009 18.4441Z" fill="#011B04"/></g><g style="mix-blend-mode:multiply" opacity="0.09" filter="url(#filter15_f_5436_78784)"><path d="M27.0688 21.2009C27.2926 21.0029 27.4948 21.0569 27.5674 21.1085C27.8818 21.2213 27.787 21.5555 27.7108 21.6725C27.6346 21.7895 27.4918 21.9701 27.199 21.9461C26.9068 21.9221 26.7892 21.4481 27.0688 21.2009Z" fill="#011B04"/></g><path d="M27.1155 21.8577C27.2835 21.9837 27.5439 21.9219 27.6963 21.7197C27.8487 21.5169 27.8355 21.2505 27.6675 21.1239C27.4995 20.9979 27.2391 21.0597 27.0867 21.2619C26.9343 21.4647 26.9469 21.7311 27.1155 21.8577Z" fill="#000000"/><g filter="url(#filter16_d_5436_78784)"><path d="M26.0792 18.3806C26.3252 18.443 26.5652 18.3326 26.6156 18.1328C26.666 17.9336 26.5076 17.7218 26.2616 17.66C26.0156 17.5976 25.7756 17.708 25.7252 17.9078C25.6748 18.107 25.8332 18.3188 26.0792 18.3806Z" fill="#000000"/></g><g filter="url(#filter17_d_5436_78784)"><path d="M27.0923 21.261C27.2441 21.0582 27.5009 20.994 27.6653 21.1176C27.8297 21.2412 27.8393 21.5052 27.6869 21.7074C27.5345 21.9102 27.2777 21.9744 27.1133 21.8514C26.9489 21.7278 26.9399 21.4632 27.0923 21.261Z" fill="#000000"/></g><mask id="mask4_5436_78784" style="mask-type:alpha" maskUnits="userSpaceOnUse" x="25" y="17" width="2" height="2"><path d="M26.0792 18.3809C26.3252 18.4433 26.5652 18.3323 26.6156 18.1331C26.666 17.9339 26.5076 17.7221 26.2616 17.6597C26.0156 17.5979 25.7756 17.7089 25.7252 17.9081C25.6748 18.1073 25.8332 18.3191 26.0792 18.3809Z" fill="#202124"/></mask><g mask="url(#mask4_5436_78784)"><g filter="url(#filter18_f_5436_78784)"><path d="M26.2887 17.7038C26.0889 17.6318 25.9029 17.6816 25.8315 17.7242C25.9701 17.639 26.1219 17.5982 26.3127 17.669C26.4195 17.7141 26.509 17.7923 26.5677 17.8922C26.5785 17.9102 26.5869 17.9246 26.5917 17.9354L26.5677 17.8922C26.5612 17.882 26.5544 17.872 26.5473 17.8622C26.5113 17.816 26.4435 17.7596 26.2887 17.7038Z" fill="#D8D8D8" fill-opacity="0.29"/></g><g opacity="0.8" filter="url(#filter19_f_5436_78784)"><path d="M26.4526 18.2893C26.6536 18.1591 26.6134 17.9719 26.5684 17.8945C26.6248 17.9551 26.6302 18.0979 26.587 18.1741C26.5545 18.2249 26.5078 18.2649 26.4526 18.2893Z" fill="url(#paint7_linear_5436_78784)"/></g></g><mask id="mask5_5436_78784" style="mask-type:alpha" maskUnits="userSpaceOnUse" x="26" y="21" width="2" height="1"><path d="M27.0922 21.261C27.2446 21.0582 27.5014 20.994 27.6658 21.1176C27.8302 21.2412 27.8398 21.5052 27.6874 21.7074C27.535 21.9102 27.2782 21.9744 27.1138 21.8514C26.9494 21.7278 26.9398 21.4632 27.0922 21.261Z" fill="#202124"/></mask><g mask="url(#mask5_5436_78784)"><path d="M27.7161 21.2765C27.6928 21.2133 27.6474 21.1606 27.5883 21.1282C27.5292 21.0958 27.4604 21.0858 27.3945 21.1001C27.4424 21.1052 27.4883 21.1214 27.5288 21.1473C27.5693 21.1732 27.6033 21.2082 27.6279 21.2495C27.6915 21.3605 27.6105 21.5669 27.5619 21.6557L27.6495 21.6917C27.6971 21.635 27.7284 21.5664 27.74 21.4933C27.7517 21.4201 27.7438 21.3452 27.7161 21.2765Z" fill="url(#paint8_linear_5436_78784)"/><g filter="url(#filter20_f_5436_78784)"><path d="M27.6788 21.6587C27.5684 21.8405 27.3926 21.9185 27.3098 21.9299C27.4718 21.9089 27.6146 21.8459 27.719 21.6713C27.7739 21.569 27.7943 21.4518 27.7772 21.3371C27.7754 21.3209 27.7726 21.3049 27.7688 21.2891C27.7706 21.3029 27.7748 21.3185 27.7772 21.3371L27.7808 21.3731C27.782 21.4319 27.7646 21.5183 27.6788 21.6587Z" fill="#D8D8D8" fill-opacity="0.29"/></g></g><g opacity="0.8" filter="url(#filter21_f_5436_78784)"><path d="M26.408 17.85C26.3666 17.7816 26.27 17.754 26.2268 17.748L26.1848 17.8044C26.2171 17.8098 26.2484 17.8197 26.2778 17.8338C26.3174 17.853 26.3648 17.886 26.384 17.8998L26.408 17.85Z" fill="#E2DCE1"/></g><g opacity="0.8" filter="url(#filter22_f_5436_78784)"><path d="M27.6807 21.4713C27.6927 21.5493 27.6375 21.6297 27.6087 21.6609L27.5427 21.6429C27.5637 21.6189 27.5811 21.592 27.5943 21.5631C27.6123 21.5241 27.6273 21.4695 27.6327 21.4473L27.6807 21.4713Z" fill="#E2DCE1"/></g><g opacity="0.8" filter="url(#filter23_f_5436_78784)"><path d="M26.1155 18.2938C26.0827 18.2638 26.0511 18.2326 26.0207 18.2002H25.9487C25.9764 18.2367 26.0116 18.2668 26.0519 18.2884L26.1155 18.2938ZM26.4335 18.3058C26.4505 18.2934 26.4664 18.2796 26.4809 18.2644L26.4557 18.2734C26.4374 18.2914 26.4168 18.3069 26.3945 18.3196C26.4005 18.3196 26.4173 18.3166 26.4335 18.3058Z" fill="#E2DCE1"/></g><g opacity="0.8" filter="url(#filter24_f_5436_78784)"><path d="M27.1711 21.303C27.1639 21.345 27.1579 21.4092 27.1561 21.4356L27.1003 21.4806C27.0988 21.4349 27.1072 21.3895 27.1249 21.3474L27.1711 21.303ZM27.4111 21.0942C27.4321 21.0931 27.4532 21.0939 27.4741 21.0966L27.4495 21.1056C27.4239 21.103 27.398 21.1038 27.3727 21.108C27.384 21.1001 27.3973 21.0954 27.4111 21.0942Z" fill="#E2DCE1"/></g><g opacity="0.3" filter="url(#filter25_f_5436_78784)"><path d="M27.8555 22.3678C26.9435 22.6894 28.1807 20.8414 27.6851 19.4362C27.1895 18.031 25.0667 17.3686 25.9781 17.047C26.8055 17.0362 27.9545 17.761 28.4501 19.1662C28.9463 20.5708 28.4465 21.9658 27.8555 22.3678Z" fill="url(#paint9_linear_5436_78784)" fill-opacity="0.4"/></g><g opacity="0.2" filter="url(#filter26_f_5436_78784)"><path d="M27.8555 22.3678C26.9435 22.6894 28.1807 20.8414 27.6851 19.4362C27.1895 18.031 25.0667 17.3686 25.9781 17.047C26.8055 17.0362 27.9545 17.761 28.4501 19.1662C28.9463 20.5708 28.4465 21.9658 27.8555 22.3678Z" fill="url(#paint10_linear_5436_78784)" fill-opacity="0.4"/></g><path d="M12.6298 18.5532C12.5306 18.3807 12.3969 18.2305 12.237 18.1121C12.077 17.9937 11.8944 17.9096 11.7004 17.865C11.2913 17.7705 10.8617 17.8339 10.4974 18.0426C10.1272 18.2526 9.84999 18.5904 9.72639 18.9828C9.60279 19.3746 9.67659 19.8486 9.87159 20.193L11.2984 19.4568L12.6298 18.5532Z" fill="#4386F5"/><path fill-rule="evenodd" clip-rule="evenodd" d="M12.6169 18.5322C14.6809 21.9498 19.0033 23.4126 22.7809 21.7986L24.0421 24.7488C18.7729 27.0006 12.7501 24.9588 9.87012 20.1912L12.6169 18.5322Z" fill="url(#paint11_linear_5436_78784)"/><path d="M12.0135 30.506C11.9802 30.6102 11.987 30.723 12.0326 30.8224C12.0782 30.9218 12.1592 31.0006 12.2598 31.0433C12.3605 31.086 12.4735 31.0896 12.5766 31.0534C12.6798 31.0172 12.7657 30.9437 12.8175 30.8474L13.8735 28.8854C13.9168 28.8063 13.9431 28.719 13.9506 28.6291C13.9581 28.5393 13.9468 28.4488 13.9172 28.3636C13.8876 28.2784 13.8405 28.2003 13.7789 28.1344C13.7173 28.0686 13.6426 28.0163 13.5596 27.981C13.4766 27.9458 13.3871 27.9283 13.297 27.9298C13.2068 27.9312 13.1179 27.9515 13.0361 27.9894C12.9542 28.0273 12.8812 28.0819 12.8218 28.1498C12.7623 28.2176 12.7177 28.2971 12.6909 28.3832L12.0135 30.506Z" fill="#034ECA"/><path d="M12.0135 30.506C11.9802 30.6102 11.987 30.723 12.0326 30.8224C12.0782 30.9218 12.1592 31.0006 12.2598 31.0433C12.3605 31.086 12.4735 31.0896 12.5766 31.0534C12.6798 31.0172 12.7657 30.9437 12.8175 30.8474L13.8735 28.8854C13.9168 28.8063 13.9431 28.719 13.9506 28.6291C13.9581 28.5393 13.9468 28.4488 13.9172 28.3636C13.8876 28.2784 13.8405 28.2003 13.7789 28.1344C13.7173 28.0686 13.6426 28.0163 13.5596 27.981C13.4766 27.9458 13.3871 27.9283 13.297 27.9298C13.2068 27.9312 13.1179 27.9515 13.0361 27.9894C12.9542 28.0273 12.8812 28.0819 12.8218 28.1498C12.7623 28.2176 12.7177 28.2971 12.6909 28.3832L12.0135 30.506Z" fill="url(#paint12_linear_5436_78784)"/><path d="M17.4046 12.0104C17.5693 11.5578 17.9072 11.1891 18.3438 10.9856C18.7804 10.782 19.2799 10.7602 19.7326 10.925C20.1852 11.0898 20.5539 11.4276 20.7574 11.8642C20.961 12.3008 20.9827 12.8004 20.818 13.253L15.4876 27.899C15.406 28.1232 15.2811 28.3291 15.12 28.505C14.9588 28.6809 14.7647 28.8233 14.5485 28.9241C14.3323 29.025 14.0984 29.0823 13.8601 29.0927C13.6218 29.1031 13.3837 29.0666 13.1596 28.985C12.9354 28.9034 12.7295 28.7785 12.5536 28.6174C12.3777 28.4563 12.2353 28.2621 12.1344 28.0459C12.0336 27.8297 11.9763 27.5958 11.9659 27.3575C11.9554 27.1192 11.992 26.8812 12.0736 26.657L17.404 12.011L17.4046 12.0104Z" fill="#4285F4"/><path d="M13.6444 29.0856C14.0452 29.1262 14.448 29.032 14.7892 28.8179C15.1305 28.6038 15.3906 28.2821 15.5284 27.9036L19.858 16.0068C19.98 15.6718 20.0004 15.3082 19.9166 14.9616C19.8328 14.615 19.6486 14.3009 19.387 14.0586L13.6444 29.0856Z" fill="url(#paint13_linear_5436_78784)"/><path d="M21.177 8.70422C21.177 8.40116 21.0566 8.11051 20.8423 7.89621C20.628 7.68191 20.3374 7.56152 20.0343 7.56152C19.7312 7.56152 19.4406 7.68191 19.2263 7.89621C19.012 8.11051 18.8916 8.40116 18.8916 8.70422V10.872C18.8916 11.1751 19.012 11.4657 19.2263 11.68C19.4406 11.8943 19.7312 12.0147 20.0343 12.0147C20.3374 12.0147 20.628 11.8943 20.8423 11.68C21.0566 11.4657 21.177 11.1751 21.177 10.872V8.70422Z" fill="#4285F4"/><path d="M21.177 8.70422C21.177 8.40116 21.0566 8.11051 20.8423 7.89621C20.628 7.68191 20.3374 7.56152 20.0343 7.56152C19.7312 7.56152 19.4406 7.68191 19.2263 7.89621C19.012 8.11051 18.8916 8.40116 18.8916 8.70422V10.872C18.8916 11.1751 19.012 11.4657 19.2263 11.68C19.4406 11.8943 19.7312 12.0147 20.0343 12.0147C20.3374 12.0147 20.628 11.8943 20.8423 11.68C21.0566 11.4657 21.177 11.1751 21.177 10.872V8.70422Z" fill="url(#paint14_linear_5436_78784)"/><g opacity="0.5" filter="url(#filter27_f_5436_78784)"><path d="M22.2981 25.2456C21.8517 25.284 22.5717 24.7314 22.4619 23.4462C22.3875 22.5798 22.6899 21.846 23.1363 21.8082C23.5827 21.7698 24.0051 22.4412 24.0795 23.3082C24.4497 24.696 22.7451 25.2078 22.2987 25.2462L22.2981 25.2456Z" fill="#044FCB"/></g><path d="M19.2144 13.2374C19.0565 12.7916 19.0808 12.3015 19.282 11.8736C19.4832 11.4456 19.8451 11.1143 20.2891 10.9515C20.7331 10.7887 21.2234 10.8077 21.6535 11.0043C22.0837 11.2008 22.4189 11.5591 22.5864 12.0014L27.963 26.675C28.0472 26.897 28.0864 27.1336 28.0785 27.3709C28.0706 27.6082 28.0158 27.8416 27.9171 28.0576C27.8184 28.2736 27.6778 28.4678 27.5035 28.6291C27.3293 28.7904 27.1247 28.9156 26.9018 28.9973C26.6788 29.079 26.4419 29.1157 26.2046 29.1053C25.9674 29.0948 25.7346 29.0374 25.5197 28.9364C25.3048 28.8353 25.1121 28.6927 24.9527 28.5167C24.7933 28.3407 24.6703 28.1348 24.591 27.911L19.2144 13.2374Z" fill="url(#paint15_linear_5436_78784)"/><path d="M18.5989 11.4307C18.2653 11.5153 17.9574 11.6802 17.7021 11.9112C17.4468 12.1421 17.2519 12.4319 17.1343 12.7555L12.0811 26.6329C11.7727 27.4789 12.0811 28.3933 12.7393 28.8037L18.5989 11.4307Z" fill="url(#paint16_linear_5436_78784)"/><path opacity="0.3" d="M19.0998 8.88428C19.3554 9.14048 19.8168 9.09428 20.1306 8.78048C20.4438 8.46728 20.4906 8.00528 20.2344 7.74908C19.9782 7.49348 19.5168 7.53968 19.203 7.85288C18.8898 8.16668 18.8436 8.62808 19.0998 8.88428Z" fill="url(#paint17_radial_5436_78784)" fill-opacity="0.9"/><path opacity="0.3" d="M16.7042 16.7332C17.4698 17.1754 18.65 16.5652 19.34 15.37C20.03 14.1748 19.9688 12.8476 19.2032 12.406C18.437 11.9632 17.2574 12.574 16.5674 13.7692C15.8774 14.9644 15.9386 16.2916 16.7042 16.7332Z" fill="url(#paint18_radial_5436_78784)" fill-opacity="0.9"/><path d="M20.0057 15.2384C20.5962 15.2384 21.1625 15.0038 21.5801 14.5862C21.9977 14.1686 22.2323 13.6023 22.2323 13.0118C22.2323 12.4212 21.9977 11.8549 21.5801 11.4373C21.1625 11.0197 20.5962 10.7852 20.0057 10.7852C19.4151 10.7852 18.8488 11.0197 18.4312 11.4373C18.0136 11.8549 17.7791 12.4212 17.7791 13.0118C17.7791 13.6023 18.0136 14.1686 18.4312 14.5862C18.8488 15.0038 19.4151 15.2384 20.0057 15.2384Z" fill="#ffffff"/><path fill-rule="evenodd" clip-rule="evenodd" d="M20.0057 11.3717C19.5705 11.3717 19.1531 11.5446 18.8453 11.8523C18.5376 12.1601 18.3647 12.5775 18.3647 13.0127C18.3647 13.4479 18.5376 13.8653 18.8453 14.1731C19.1531 14.4808 19.5705 14.6537 20.0057 14.6537C20.4409 14.6537 20.8583 14.4808 21.166 14.1731C21.4738 13.8653 21.6467 13.4479 21.6467 13.0127C21.6467 12.5775 21.4738 12.1601 21.166 11.8523C20.8583 11.5446 20.4409 11.3717 20.0057 11.3717ZM17.1929 13.0127C17.1929 12.6434 17.2656 12.2776 17.407 11.9364C17.5483 11.5952 17.7555 11.2851 18.0166 11.024C18.2778 10.7628 18.5878 10.5556 18.9291 10.4143C19.2703 10.2729 19.636 10.2002 20.0054 10.2002C20.3747 10.2002 20.7404 10.2729 21.0817 10.4143C21.4229 10.5556 21.7329 10.7628 21.9941 11.024C22.2553 11.2851 22.4624 11.5952 22.6038 11.9364C22.7451 12.2776 22.8179 12.6434 22.8179 13.0127C22.8179 13.7586 22.5216 14.474 21.9941 15.0014C21.4667 15.5289 20.7513 15.8252 20.0054 15.8252C19.2594 15.8252 18.5441 15.5289 18.0166 15.0014C17.4892 14.474 17.1929 13.7586 17.1929 13.0127Z" fill="#202124"/></g><defs><filter id="filter0_f_5436_78784" x="22.6242" y="16.5466" width="6.29919" height="3.55334" filterUnits="userSpaceOnUse" color-interpolation-filters="sRGB"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend mode="normal" in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur stdDeviation="0.2106" result="effect1_foregroundBlur_5436_78784"/></filter><filter id="filter1_f_5436_78784" x="24.2553" y="18.2043" width="5.04503" height="6.02794" filterUnits="userSpaceOnUse" color-interpolation-filters="sRGB"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend mode="normal" in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur stdDeviation="0.3168" result="effect1_foregroundBlur_5436_78784"/></filter><filter id="filter2_f_5436_78784" x="23.1339" y="15.9146" width="4.84796" height="1.75176" filterUnits="userSpaceOnUse" color-interpolation-filters="sRGB"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend mode="normal" in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur stdDeviation="0.1584" result="effect1_foregroundBlur_5436_78784"/></filter><filter id="filter3_f_5436_78784" x="25.8976" y="20.7262" width="3.4002" height="3.94903" filterUnits="userSpaceOnUse" color-interpolation-filters="sRGB"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend mode="normal" in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur stdDeviation="0.1584" result="effect1_foregroundBlur_5436_78784"/></filter><filter id="filter4_f_5436_78784" x="27.1516" y="15.9294" width="2.22619" height="1.93127" filterUnits="userSpaceOnUse" color-interpolation-filters="sRGB"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend mode="normal" in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur stdDeviation="0.2106" result="effect1_foregroundBlur_5436_78784"/></filter><filter id="filter5_f_5436_78784" x="27.4024" y="15.8722" width="1.30084" height="1.63165" filterUnits="userSpaceOnUse" color-interpolation-filters="sRGB"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend mode="normal" in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur stdDeviation="0.0522" result="effect1_foregroundBlur_5436_78784"/></filter><filter id="filter6_f_5436_78784" x="27.6812" y="16.0377" width="1.51177" height="2.08672" filterUnits="userSpaceOnUse" color-interpolation-filters="sRGB"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend mode="normal" in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur stdDeviation="0.1584" result="effect1_foregroundBlur_5436_78784"/></filter><filter id="filter7_f_5436_78784" x="28.6939" y="21.0089" width="1.95148" height="0.632628" filterUnits="userSpaceOnUse" color-interpolation-filters="sRGB"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend mode="normal" in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur stdDeviation="0.0522" result="effect1_foregroundBlur_5436_78784"/></filter><filter id="filter8_f_5436_78784" x="28.5522" y="20.4341" width="0.579341" height="1.66601" filterUnits="userSpaceOnUse" color-interpolation-filters="sRGB"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend mode="normal" in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur stdDeviation="0.1062" result="effect1_foregroundBlur_5436_78784"/></filter><filter id="filter9_f_5436_78784" x="28.7395" y="20.2715" width="0.32573" height="0.604539" filterUnits="userSpaceOnUse" color-interpolation-filters="sRGB"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend mode="normal" in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur stdDeviation="0.063" result="effect1_foregroundBlur_5436_78784"/></filter><filter id="filter10_f_5436_78784" x="26.7388" y="16.6021" width="1.28808" height="1.33203" filterUnits="userSpaceOnUse" color-interpolation-filters="sRGB"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend mode="normal" in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur stdDeviation="0.1062" result="effect1_foregroundBlur_5436_78784"/></filter><filter id="filter11_f_5436_78784" x="27.622" y="17.5068" width="0.515184" height="0.500047" filterUnits="userSpaceOnUse" color-interpolation-filters="sRGB"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend mode="normal" in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur stdDeviation="0.063" result="effect1_foregroundBlur_5436_78784"/></filter><filter id="filter12_f_5436_78784" x="28.4228" y="20.5524" width="2.53161" height="1.3258" filterUnits="userSpaceOnUse" color-interpolation-filters="sRGB"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend mode="normal" in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur stdDeviation="0.2106" result="effect1_foregroundBlur_5436_78784"/></filter><filter id="filter13_f_5436_78784" x="28.6322" y="20.193" width="2.35137" height="1.46368" filterUnits="userSpaceOnUse" color-interpolation-filters="sRGB"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend mode="normal" in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur stdDeviation="0.1584" result="effect1_foregroundBlur_5436_78784"/></filter><filter id="filter14_f_5436_78784" x="25.5827" y="17.569" width="1.08688" height="0.940147" filterUnits="userSpaceOnUse" color-interpolation-filters="sRGB"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend mode="normal" in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur stdDeviation="0.0324" result="effect1_foregroundBlur_5436_78784"/></filter><filter id="filter15_f_5436_78784" x="26.8449" y="20.9957" width="1.00606" height="1.0173" filterUnits="userSpaceOnUse" color-interpolation-filters="sRGB"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend mode="normal" in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur stdDeviation="0.0324" result="effect1_foregroundBlur_5436_78784"/></filter><filter id="filter16_d_5436_78784" x="25.6834" y="17.6426" width="0.95238" height="0.799059" filterUnits="userSpaceOnUse" color-interpolation-filters="sRGB"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feColorMatrix in="SourceAlpha" type="matrix" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0" result="hardAlpha"/><feOffset dx="-0.0108" dy="0.0216"/><feGaussianBlur stdDeviation="0.0108"/><feComposite in2="hardAlpha" operator="out"/><feColorMatrix type="matrix" values="0 0 0 0 0.0156863 0 0 0 0 0.231373 0 0 0 0 0.0666667 0 0 0 0.7 0"/><feBlend mode="normal" in2="BackgroundImageFix" result="effect1_dropShadow_5436_78784"/><feBlend mode="normal" in="SourceGraphic" in2="effect1_dropShadow_5436_78784" result="shape"/></filter><filter id="filter17_d_5436_78784" x="26.9512" y="21.0547" width="0.854723" height="0.902575" filterUnits="userSpaceOnUse" color-interpolation-filters="sRGB"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feColorMatrix in="SourceAlpha" type="matrix" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0" result="hardAlpha"/><feOffset dx="-0.0108" dy="0.0216"/><feGaussianBlur stdDeviation="0.0108"/><feComposite in2="hardAlpha" operator="out"/><feColorMatrix type="matrix" values="0 0 0 0 0.0156863 0 0 0 0 0.231373 0 0 0 0 0.0666667 0 0 0 0.7 0"/><feBlend mode="normal" in2="BackgroundImageFix" result="effect1_dropShadow_5436_78784"/><feBlend mode="normal" in="SourceGraphic" in2="effect1_dropShadow_5436_78784" result="shape"/></filter><filter id="filter18_f_5436_78784" x="25.8099" y="17.6112" width="0.803454" height="0.345934" filterUnits="userSpaceOnUse" color-interpolation-filters="sRGB"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend mode="normal" in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur stdDeviation="0.0108" result="effect1_foregroundBlur_5436_78784"/></filter><filter id="filter19_f_5436_78784" x="26.449" y="17.8909" width="0.170286" height="0.401731" filterUnits="userSpaceOnUse" color-interpolation-filters="sRGB"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend mode="normal" in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur stdDeviation="0.0018" result="effect1_foregroundBlur_5436_78784"/></filter><filter id="filter20_f_5436_78784" x="27.2882" y="21.2675" width="0.516589" height="0.683825" filterUnits="userSpaceOnUse" color-interpolation-filters="sRGB"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend mode="normal" in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur stdDeviation="0.0108" result="effect1_foregroundBlur_5436_78784"/></filter><filter id="filter21_f_5436_78784" x="26.1632" y="17.7264" width="0.266345" height="0.194567" filterUnits="userSpaceOnUse" color-interpolation-filters="sRGB"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend mode="normal" in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur stdDeviation="0.0108" result="effect1_foregroundBlur_5436_78784"/></filter><filter id="filter22_f_5436_78784" x="27.5211" y="21.4257" width="0.182848" height="0.257067" filterUnits="userSpaceOnUse" color-interpolation-filters="sRGB"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend mode="normal" in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur stdDeviation="0.0108" result="effect1_foregroundBlur_5436_78784"/></filter><filter id="filter23_f_5436_78784" x="25.9379" y="18.1894" width="0.553827" height="0.140741" filterUnits="userSpaceOnUse" color-interpolation-filters="sRGB"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend mode="normal" in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur stdDeviation="0.0054" result="effect1_foregroundBlur_5436_78784"/></filter><filter id="filter24_f_5436_78784" x="27.0893" y="21.0829" width="0.395623" height="0.408319" filterUnits="userSpaceOnUse" color-interpolation-filters="sRGB"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend mode="normal" in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur stdDeviation="0.0054" result="effect1_foregroundBlur_5436_78784"/></filter><filter id="filter25_f_5436_78784" x="25.3322" y="16.6257" width="3.74157" height="6.19982" filterUnits="userSpaceOnUse" color-interpolation-filters="sRGB"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend mode="normal" in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur stdDeviation="0.2106" result="effect1_foregroundBlur_5436_78784"/></filter><filter id="filter26_f_5436_78784" x="25.3322" y="16.6257" width="3.74157" height="6.19982" filterUnits="userSpaceOnUse" color-interpolation-filters="sRGB"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend mode="normal" in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur stdDeviation="0.2106" result="effect1_foregroundBlur_5436_78784"/></filter><filter id="filter27_f_5436_78784" x="21.625" y="21.281" width="3.03216" height="4.49163" filterUnits="userSpaceOnUse" color-interpolation-filters="sRGB"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend mode="normal" in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur stdDeviation="0.2628" result="effect1_foregroundBlur_5436_78784"/></filter><linearGradient id="paint0_linear_5436_78784" x1="27.7687" y1="30.9686" x2="26.6119" y2="30.3122" gradientUnits="userSpaceOnUse"><stop stop-color="#4285F4"/><stop offset="1" stop-color="#034ECA"/></linearGradient><linearGradient id="paint1_linear_5436_78784" x1="26.2425" y1="17.0595" x2="25.8759" y2="18.3591" gradientUnits="userSpaceOnUse"><stop stop-color="#A8F0B9"/><stop offset="1" stop-color="#ADEEBC" stop-opacity="0"/></linearGradient><linearGradient id="paint2_linear_5436_78784" x1="28.0568" y1="22.2021" x2="26.9558" y2="21.4209" gradientUnits="userSpaceOnUse"><stop stop-color="#A8F0B9"/><stop offset="1" stop-color="#ADEEBC" stop-opacity="0"/></linearGradient><radialGradient id="paint3_radial_5436_78784" cx="0" cy="0" r="1" gradientTransform="matrix(-0.160932 -0.220716 0.159942 -0.116616 28.6025 16.4074)" gradientUnits="userSpaceOnUse"><stop stop-color="#ffffff"/><stop offset="0.948" stop-color="#ffffff" stop-opacity="0"/></radialGradient><radialGradient id="paint4_radial_5436_78784" cx="0" cy="0" r="1" gradientTransform="matrix(-0.160931 -0.220715 0.15994 -0.116617 30.2426 20.8847)" gradientUnits="userSpaceOnUse"><stop stop-color="#ffffff"/><stop offset="0.948" stop-color="#ffffff" stop-opacity="0"/></radialGradient><radialGradient id="paint5_radial_5436_78784" cx="0" cy="0" r="1" gradientUnits="userSpaceOnUse" gradientTransform="translate(26.5204 18.155) rotate(-156.205) scale(0.106566 0.1941)"><stop stop-color="#93E19F"/><stop offset="1" stop-color="#93E19F" stop-opacity="0"/></radialGradient><radialGradient id="paint6_radial_5436_78784" cx="0" cy="0" r="1" gradientTransform="matrix(-0.0489 0.0946378 -0.172362 -0.0890638 27.576 21.1601)" gradientUnits="userSpaceOnUse"><stop stop-color="#93E19F"/><stop offset="1" stop-color="#93E19F" stop-opacity="0"/></radialGradient><linearGradient id="paint7_linear_5436_78784" x1="26.6638" y1="17.8861" x2="26.3572" y2="18.0097" gradientUnits="userSpaceOnUse"><stop stop-color="#E2DDE2"/><stop offset="1" stop-color="#E2DDE2" stop-opacity="0"/></linearGradient><linearGradient id="paint8_linear_5436_78784" x1="27.7329" y1="21.3215" x2="27.4761" y2="21.4121" gradientUnits="userSpaceOnUse"><stop stop-color="#373637"/><stop offset="1" stop-color="#373637" stop-opacity="0"/></linearGradient><linearGradient id="paint9_linear_5436_78784" x1="28.4993" y1="19.1488" x2="27.2261" y2="19.5982" gradientUnits="userSpaceOnUse"><stop stop-color="#A8F0B9"/><stop offset="1" stop-color="#ADEEBC" stop-opacity="0"/></linearGradient><linearGradient id="paint10_linear_5436_78784" x1="28.4993" y1="19.1488" x2="27.2261" y2="19.5982" gradientUnits="userSpaceOnUse"><stop stop-color="#A8F0B9"/><stop offset="1" stop-color="#ADEEBC" stop-opacity="0"/></linearGradient><linearGradient id="paint11_linear_5436_78784" x1="18.8629" y1="23.325" x2="24.4291" y2="22.8858" gradientUnits="userSpaceOnUse"><stop stop-color="#4285F4"/><stop offset="0.703" stop-color="#044FCB"/></linearGradient><linearGradient id="paint12_linear_5436_78784" x1="12.5055" y1="30.6758" x2="13.7055" y2="29.9678" gradientUnits="userSpaceOnUse"><stop stop-color="#4285F4"/><stop offset="1" stop-color="#034ECA"/></linearGradient><linearGradient id="paint13_linear_5436_78784" x1="18.0118" y1="20.5998" x2="17.3722" y2="20.3778" gradientUnits="userSpaceOnUse"><stop stop-color="#73A7FF"/><stop offset="1" stop-color="#5893F6" stop-opacity="0"/></linearGradient><linearGradient id="paint14_linear_5436_78784" x1="20.0346" y1="8.83982" x2="21.0402" y2="9.74462" gradientUnits="userSpaceOnUse"><stop stop-color="#4285F4"/><stop offset="1" stop-color="#034ECA"/></linearGradient><linearGradient id="paint15_linear_5436_78784" x1="21.1596" y1="14.7602" x2="24.201" y2="21.1166" gradientUnits="userSpaceOnUse"><stop stop-color="#034DC9"/><stop offset="1" stop-color="#4285F4"/></linearGradient><linearGradient id="paint16_linear_5436_78784" x1="13.8001" y1="19.9981" x2="15.4021" y2="20.5483" gradientUnits="userSpaceOnUse"><stop stop-color="#9BC0FF"/><stop offset="1" stop-color="#5893F6" stop-opacity="0"/></linearGradient><radialGradient id="paint17_radial_5436_78784" cx="0" cy="0" r="1" gradientTransform="matrix(-0.353622 0.35982 -0.25068 -0.24636 19.6668 8.31668)" gradientUnits="userSpaceOnUse"><stop stop-color="#ffffff"/><stop offset="0.948" stop-color="#ffffff" stop-opacity="0"/></radialGradient><radialGradient id="paint18_radial_5436_78784" cx="0" cy="0" r="1" gradientUnits="userSpaceOnUse" gradientTransform="translate(17.9541 14.5691) rotate(119.61) scale(1.57072 0.858126)"><stop stop-color="#ffffff"/><stop offset="0.948" stop-color="#ffffff" stop-opacity="0"/></radialGradient></defs></g>"## }; +static ANTIGRAVITY: Icon = Icon { name: "app-antigravity", view: 40.0, body: r##"<g fill="none"><mask id="mask0_5436_78917" style="mask-type:alpha" maskUnits="userSpaceOnUse" x="4" y="4" width="32" height="32"><path d="M33.0017 34.7292C34.7884 36.1587 37.4682 35.2056 35.0115 32.5854C27.6419 24.9626 29.2053 4 20.049 4C10.8927 4 12.456 24.9626 5.08629 32.5854C2.40641 35.4438 5.3096 36.1587 7.09621 34.7292C14.0192 29.7269 13.5726 20.913 20.049 20.913C26.5253 20.913 26.0787 29.7269 33.0017 34.7292Z" fill="#000000"/></mask><g mask="url(#mask0_5436_78917)"><g filter="url(#filter0_f_5436_78917)"><path d="M2.6428 -3.09688C2.0994 2.00961 6.22486 6.70203 11.8573 7.38397C17.4897 8.06591 22.4962 4.47909 23.0395 -0.627401C23.5829 -5.73389 19.4575 -10.4263 13.8251 -11.1082C8.19268 -11.7902 3.1862 -8.20337 2.6428 -3.09688Z" fill="#FFE432"/></g><g filter="url(#filter1_f_5436_78917)"><path d="M24.359 13.5949C25.7702 20.0758 31.9478 24.0825 38.1572 22.5441C44.3666 21.0058 48.2563 14.5049 46.8451 8.0241C45.4339 1.54324 39.2563 -2.46345 33.0469 -0.925119C26.8375 0.613209 22.9479 7.11405 24.359 13.5949Z" fill="#FC413D"/></g><g filter="url(#filter2_f_5436_78917)"><path d="M-12.5892 17.9443C-10.8061 24.6327 -2.77556 28.0574 5.34752 25.5933C13.4706 23.1294 18.6101 15.7099 16.827 9.02145C15.0439 2.33301 7.0133 -1.09159 -1.10977 1.3724C-9.23284 3.83637 -14.3724 11.2559 -12.5892 17.9443Z" fill="#00B95C"/></g><g filter="url(#filter3_f_5436_78917)"><path d="M-12.5892 17.9443C-10.8061 24.6327 -2.77556 28.0574 5.34752 25.5933C13.4706 23.1294 18.6101 15.7099 16.827 9.02145C15.0439 2.33301 7.0133 -1.09159 -1.10977 1.3724C-9.23284 3.83637 -14.3724 11.2559 -12.5892 17.9443Z" fill="#00B95C"/></g><g filter="url(#filter4_f_5436_78917)"><path d="M-6.1442 23.4854C-1.67415 28.3554 6.02429 28.048 11.0507 22.7989C16.0772 17.5497 16.5282 9.34639 12.0581 4.47628C7.58808 -0.39381 -0.110356 -0.0864739 -5.13679 5.16274C-10.1632 10.412 -10.6143 18.6153 -6.1442 23.4854Z" fill="#00B95C"/></g><g filter="url(#filter5_f_5436_78917)"><path d="M17.2432 41.8532C18.6312 48.2281 24.4218 52.24 30.1768 50.8142C35.9317 49.3883 39.4718 43.0649 38.0837 36.6901C36.6958 30.3153 30.9053 26.3034 25.1501 27.7291C19.3952 29.155 15.8551 35.4784 17.2432 41.8532Z" fill="#3186FF"/></g><g filter="url(#filter6_f_5436_78917)"><path d="M7.43056 -9.06427C4.52402 -2.15801 7.70398 6.09157 14.5332 9.36164C21.3624 12.6317 29.2548 9.68399 32.1612 2.77772C35.0679 -4.12855 31.8879 -12.3781 25.0588 -15.6482C18.2295 -18.9183 10.3371 -15.9705 7.43056 -9.06427Z" fill="#FBBC04"/></g><g filter="url(#filter7_f_5436_78917)"><path d="M-0.355758 57.5976C-7.3922 54.6515 4.6329 30.4094 7.6231 22.2847C10.6134 14.1599 18.7416 9.96211 25.778 12.9086C32.8145 15.855 41.1549 32.0836 38.1644 40.2085C35.1742 48.3331 6.6807 60.544 -0.355758 57.5976Z" fill="#3186FF"/></g><g filter="url(#filter8_f_5436_78917)"><path d="M42.2801 27.4246C40.3961 29.7697 35.48 28.5738 31.2997 24.7533C27.1193 20.9328 25.2575 15.9345 27.1413 13.5892C29.0251 11.244 33.9411 12.4399 38.1215 16.2604C42.3019 20.0809 44.1638 25.0792 42.2801 27.4246Z" fill="#749BFF"/></g><g filter="url(#filter9_f_5436_78917)"><path d="M28.2171 15.4855C35.9652 21.076 44.8873 21.4433 48.1454 16.3058C51.4034 11.1683 47.7636 2.47155 40.0155 -3.11898C32.2675 -8.7095 23.3454 -9.07676 20.0874 -3.93929C16.8293 1.19821 20.4691 9.89496 28.2171 15.4855Z" fill="#FC413D"/></g><g filter="url(#filter10_f_5436_78917)"><path d="M2.78038 6.39313C0.860867 11.3323 1.48778 16.3015 4.18063 17.4922C6.87347 18.6829 10.6125 15.6442 12.5321 10.7051C14.4516 5.76593 13.8246 0.796692 11.1318 -0.394021C8.43895 -1.58473 4.69989 1.45397 2.78038 6.39313Z" fill="#FFEE48"/></g></g><defs><filter id="filter0_f_5436_78917" x="0.0242057" y="-13.7619" width="25.634" height="23.7992" filterUnits="userSpaceOnUse" color-interpolation-filters="sRGB"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend mode="normal" in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur stdDeviation="1.28526" result="effect1_foregroundBlur_5436_78917"/></filter><filter id="filter1_f_5436_78917" x="11.6427" y="-13.681" width="47.9187" height="48.9812" filterUnits="userSpaceOnUse" color-interpolation-filters="sRGB"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend mode="normal" in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur stdDeviation="6.21356" result="effect1_foregroundBlur_5436_78917"/></filter><filter id="filter2_f_5436_78917" x="-23.5069" y="-9.99099" width="51.2515" height="46.9478" filterUnits="userSpaceOnUse" color-interpolation-filters="sRGB"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend mode="normal" in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur stdDeviation="5.28212" result="effect1_foregroundBlur_5436_78917"/></filter><filter id="filter3_f_5436_78917" x="-23.5069" y="-9.99099" width="51.2515" height="46.9478" filterUnits="userSpaceOnUse" color-interpolation-filters="sRGB"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend mode="normal" in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur stdDeviation="5.28212" result="effect1_foregroundBlur_5436_78917"/></filter><filter id="filter4_f_5436_78917" x="-19.7869" y="-9.54861" width="45.4878" height="47.0591" filterUnits="userSpaceOnUse" color-interpolation-filters="sRGB"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend mode="normal" in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur stdDeviation="5.28212" result="effect1_foregroundBlur_5436_78917"/></filter><filter id="filter5_f_5436_78917" x="6.90275" y="17.4023" width="41.5214" height="43.7384" filterUnits="userSpaceOnUse" color-interpolation-filters="sRGB"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend mode="normal" in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur stdDeviation="5.01957" result="effect1_foregroundBlur_5436_78917"/></filter><filter id="filter6_f_5436_78917" x="-2.74455" y="-26.0807" width="45.0809" height="45.8753" filterUnits="userSpaceOnUse" color-interpolation-filters="sRGB"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend mode="normal" in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur stdDeviation="4.54916" result="effect1_foregroundBlur_5436_78917"/></filter><filter id="filter7_f_5436_78917" x="-10.6564" y="3.84164" width="57.5706" height="62.3304" filterUnits="userSpaceOnUse" color-interpolation-filters="sRGB"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend mode="normal" in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur stdDeviation="4.06258" result="effect1_foregroundBlur_5436_78917"/></filter><filter id="filter8_f_5436_78917" x="19.1357" y="5.11809" width="31.15" height="30.7775" filterUnits="userSpaceOnUse" color-interpolation-filters="sRGB"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend mode="normal" in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur stdDeviation="3.63529" result="effect1_foregroundBlur_5436_78917"/></filter><filter id="filter9_f_5436_78917" x="12.7527" y="-13.7053" width="42.7273" height="39.7769" filterUnits="userSpaceOnUse" color-interpolation-filters="sRGB"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend mode="normal" in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur stdDeviation="3.07044" result="effect1_foregroundBlur_5436_78917"/></filter><filter id="filter10_f_5436_78917" x="-5.93239" y="-8.2527" width="27.1773" height="33.604" filterUnits="userSpaceOnUse" color-interpolation-filters="sRGB"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend mode="normal" in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur stdDeviation="3.80018" result="effect1_foregroundBlur_5436_78917"/></filter></defs></g>"## }; +static POWERSHELL: Icon = Icon { name: "app-powershell", view: 40.0, body: r##"<g fill="none"><path fill-rule="evenodd" clip-rule="evenodd" d="M34.9013 7.2002H10.604C9.83641 7.2002 9.09532 7.84723 8.91004 8.66305L4.03999 31.3373C3.85472 32.1532 4.33113 32.8002 5.0987 32.8002H29.396C30.1636 32.8002 30.9047 32.1532 31.09 31.3373L35.96 8.69118C36.1453 7.87536 35.6689 7.2002 34.9013 7.2002Z" fill="url(#paint0_linear_5437_79143)"/><path fill-rule="evenodd" clip-rule="evenodd" d="M19.7489 26.5009H25.2421C25.8826 26.5009 26.3999 27.0942 26.3999 27.8223C26.3999 28.5505 25.8826 29.1438 25.2421 29.1438H19.7489C19.1085 29.1438 18.5912 28.5505 18.5912 27.8223C18.5912 27.0942 19.1085 26.5009 19.7489 26.5009ZM23.3208 20.6216C23.2222 20.8374 23.0252 21.0531 22.6803 21.3228L12.4575 29.3596C11.8909 29.7911 11.1027 29.6293 10.6593 28.982C10.2405 28.3347 10.339 27.4448 10.881 27.0133L20.0938 19.7047V19.5429L14.305 12.8006C13.837 12.2612 13.8862 11.3713 14.4035 10.8049C14.9455 10.2655 15.7584 10.2655 16.2264 10.8049L23.173 18.8956C23.5917 19.408 23.6163 20.1092 23.3208 20.6216Z" fill="#2C5591"/><path fill-rule="evenodd" clip-rule="evenodd" d="M23.2368 20.6216C23.1387 20.8374 22.9426 21.0531 22.5993 21.3228L12.448 29.3596C11.8841 29.7911 11.0994 29.6293 10.6581 28.982C10.2412 28.3347 10.3393 27.4448 10.8788 27.0133L20.0492 19.7047V19.5429L14.287 12.8006C13.8212 12.2612 13.8702 11.3713 14.3851 10.8049C14.9246 10.2655 15.7337 10.2655 16.1996 10.8049L23.1142 18.8956C23.5311 19.3811 23.5556 20.0822 23.2368 20.6216ZM19.7795 26.6357H25.2475C25.885 26.6357 26.3999 27.202 26.3999 27.8763C26.3999 28.5775 25.885 29.1168 25.2475 29.1168H19.7795C19.142 29.1168 18.6271 28.5505 18.6271 27.8763C18.6271 27.1751 19.142 26.6357 19.7795 26.6357Z" fill="#ffffff"/><defs><linearGradient id="paint0_linear_5437_79143" x1="9.76654" y1="10.3425" x2="29.068" y2="26.4694" gradientUnits="userSpaceOnUse"><stop stop-color="#2D4664"/><stop offset="0.169" stop-color="#29405B"/><stop offset="0.445" stop-color="#1E2F43"/><stop offset="0.79" stop-color="#0C131B"/><stop offset="1"/></linearGradient></defs></g>"## }; +static WINDOWS_TERMINAL: Icon = Icon { name: "app-windows-terminal", view: 40.0, body: r##"<g fill="none"><rect x="4" y="7" width="32" height="26" rx="3" fill="#1F1F1F"/><path d="M4 10C4 8.34315 5.34315 7 7 7H33C34.6569 7 36 8.34315 36 10V13H4V10Z" fill="url(#paint0_linear_wt)"/><rect x="4.5" y="7.5" width="31" height="25" rx="2.5" stroke="#000000" stroke-opacity="0.3"/><path d="M11 18.5L16 22L11 25.5" stroke="#ffffff" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/><path d="M18.5 26.5H27.5" stroke="#ffffff" stroke-width="2" stroke-linecap="round"/><defs><linearGradient id="paint0_linear_wt" x1="4" y1="7" x2="36" y2="13" gradientUnits="userSpaceOnUse"><stop stop-color="#3A96DD"/><stop offset="1" stop-color="#2F66C4"/></linearGradient></defs></g>"## }; +static SUBLIME_TEXT: Icon = Icon { name: "app-sublime-text", view: 40.0, body: r##"<g fill="none"><g clip-path="url(#clip0_5436_78897)"><path d="M35.911 20.0773C35.911 19.7026 35.552 19.4866 35.1114 19.5939L4.79962 27.0055C4.35812 27.1135 4 27.5052 4 27.8792V35.4541C4 35.8288 4.35812 36.0455 4.79962 35.9375L35.1114 28.5266C35.552 28.4187 35.911 28.0269 35.911 27.6523V20.0774V20.0773Z" fill="url(#paint0_linear_5436_78897)"/><path d="M4 19.8353C4 20.21 4.35812 20.6016 4.79962 20.7097L35.1159 28.1219C35.5573 28.2299 35.9155 28.0133 35.9155 27.6393V20.0637C35.9155 19.6897 35.5573 19.298 35.1159 19.19L4.79962 11.7778C4.35812 11.6699 4 11.8858 4 12.2603V19.8353V19.8353Z" fill="#FF9800"/><path d="M35.911 4.51106C35.911 4.1365 35.552 3.91973 35.1114 4.02778L4.79962 11.4387C4.35812 11.5466 4 11.9383 4 12.313V19.8879C4 20.2626 4.35812 20.4786 4.79962 20.3712L35.1114 12.9596C35.552 12.8517 35.911 12.46 35.911 12.086V4.51106Z" fill="#FF9800"/></g><defs><linearGradient id="paint0_linear_5436_78897" x1="1762.84" y1="981.852" x2="1845.15" y2="624.882" gradientUnits="userSpaceOnUse"><stop stop-color="#FF9700"/><stop offset="0.53" stop-color="#F48E00"/><stop offset="1" stop-color="#D06F00"/></linearGradient><clipPath id="clip0_5436_78897"><rect width="32" height="32" fill="#ffffff" transform="translate(4 4)"/></clipPath></defs></g>"## }; + +/// Desktop's mark for app `id` (`AppIcon`'s ids: "vscode", "file-explorer", ...), in the +/// variant for a dark or light appearance; None for the marks Desktop draws from PNGs. Windows +/// Terminal isn't one of Desktop's: its mark here is drawn for Rune (a console window with a prompt). +pub fn named(id: &str, dark: bool) -> Option<&'static Icon> { + Some(match id { + "zed" if dark => &ZED_DARK, + "vscode" => &VSCODE, + "cursor" => &CURSOR, + "zed" => &ZED, + "file-explorer" => &FILE_EXPLORER, + "iterm2" => &ITERM2, + "ghostty" => &GHOSTTY, + "android-studio" => &ANDROID_STUDIO, + "antigravity" => &ANTIGRAVITY, + "powershell" => &POWERSHELL, + "windows-terminal" => &WINDOWS_TERMINAL, + "sublime-text" => &SUBLIME_TEXT, + _ => return None, + }) +} diff --git a/app/vendor/rune/themes/opencode/src/file_icons.rs b/app/vendor/rune/themes/opencode/src/file_icons.rs new file mode 100644 index 0000000..e124557 --- /dev/null +++ b/app/vendor/rune/themes/opencode/src/file_icons.rs @@ -0,0 +1,46 @@ +//! `@opencode/ui`'s `FileIcon`: the colour file-type badge Desktop shows beside a path in the +//! command palette, the `@` mention list, tool rows, review headers and file tabs, chosen as its +//! `chooseIconName` does. The badges paint their own colours, so `rune::icon` draws them as they +//! are in either appearance; draw them at 16 points (`file-icon.css`). +//! +//! ```ignore +//! row().gap(8.0).child(icon(file_icons::file("src/util/format.ts"), 16.0)).child(text("format.ts")) +//! ``` + +mod catalog; + +use rune::Icon; + +/// The badge for a file at `path` (`/` or `\` separated, or just a name): its whole name first +/// (`package.json`, `Dockerfile`), then its dotted suffixes longest first (`d.ts` before `ts`), else +/// the plain document. +pub fn file(path: &str) -> &'static Icon { + let name = basename(path).to_lowercase(); + if let Some(icon) = catalog::by_file_name(&name) { + return icon; + } + // The whole name counts as a suffix too, so `dockerfile` matches without a dot. + std::iter::once(0) + .chain(name.match_indices('.').map(|(i, _)| i + 1).filter(|&i| i < name.len())) + .find_map(|i| catalog::by_extension(&name[i..])) + .unwrap_or(&catalog::DOCUMENT) +} + +/// The icon for a folder at `path`, open or closed: by its name as written, or with a leading +/// `.` or `_`, or wrapped in `__` (`src`, `.github`, `__tests__`), else the plain folder. +pub fn folder(path: &str, expanded: bool) -> &'static Icon { + let name = basename(path).to_lowercase(); + let variants = [name.clone(), format!(".{name}"), format!("_{name}"), format!("__{name}__")]; + let (closed, open) = + variants.iter().find_map(|v| catalog::by_folder_name(v)).unwrap_or((&catalog::FOLDER, &catalog::FOLDER_OPEN)); + if expanded { open } else { closed } +} + +/// Every badge and folder icon, for a gallery. +pub fn all() -> &'static [&'static Icon] { + catalog::ALL +} + +fn basename(path: &str) -> &str { + path.rsplit(['/', '\\']).find(|s| !s.is_empty()).unwrap_or("") +} diff --git a/app/vendor/rune/themes/opencode/src/file_icons/catalog.rs b/app/vendor/rune/themes/opencode/src/file_icons/catalog.rs new file mode 100644 index 0000000..667ffd0 --- /dev/null +++ b/app/vendor/rune/themes/opencode/src/file_icons/catalog.rs @@ -0,0 +1,2311 @@ +//! Generated by tools/file-icons.py from @opencode/ui's file-type icons and `chooseIconName`. Do not edit. +use rune::Icon; + +pub(super) static ANGULAR: Icon = Icon { + name: "angular", + view: 24.0, + body: r##"<path fill="#e53935" d="M9.87 2.5 3.022 5.666l.645 10.178zm4.26 0 6.202 13.344.645-10.178zM12 7.563l-2.451 5.964h4.906zm-3.73 8.959-.954 2.308L12 21.5l4.683-2.67-.953-2.308z"/>"##, +}; +pub(super) static APPVEYOR: Icon = Icon { + name: "appveyor", + view: 256.0, + body: r##"<path fill="#00b8d4" fill-rule="evenodd" d="M127.646 17.356c61.588 0 110.999 49.414 110.999 110.29a110.64 110.64 0 0 1-110.999 110.999c-60.873 0-110.29-49.414-110.29-110.999 0-60.873 49.414-110.29 110.29-110.29m27.213 131.77c-12.174 15.756-34.375 18.62-49.414 6.446-15.039-11.459-17.187-33.66-5.013-49.414 12.891-15.039 35.091-17.904 50.131-6.445 15.039 12.174 17.187 34.375 4.297 49.414zm-58.723 72.331 42.252-40.82c-15.756 3.58-32.227.716-45.117-10.026-15.039-11.459-21.484-30.795-19.336-48.699L35.98 163.45s-5.013-9.31-6.446-26.498l66.602-52.278c20.052-14.323 47.266-15.04 66.602 0 21.484 17.187 25.781 48.698 10.027 72.33l-48.699 69.466c-7.161 0-21.484-2.149-27.93-5.013"/>"##, +}; +pub(super) static ASTRO_CONFIG: Icon = Icon { + name: "astro-config", + view: 32.0, + body: r##"<path fill="#757575" d="M15 2H6a2.006 2.006 0 0 0-2 2v22a2.006 2.006 0 0 0 2 2h6v-4H6v-2h6v-2H6v-2h6v-2H6v-2h6v-2h2V4l8 8h2v-1Z"/><path fill="#7c4dff" d="M12 12v18h18V12Zm10 16c-.9 0-2.025-1.267-2.025-3.005-.914 0-.975.464-.975 1.005-.881-.213-1-1.15-1-2h6c0 1.919-2 1.787-2 4m2.542-6a2.5 2.5 0 0 1-2.308-1.641l-.946-2.42a.305.305 0 0 0-.576 0l-.946 2.42A2.5 2.5 0 0 1 17.458 22H16l2.965-7.59a.63.63 0 0 1 .577-.41h2.916a.63.63 0 0 1 .577.41L26 22Z"/>"##, +}; +pub(super) static AUDIO: Icon = Icon { + name: "audio", + view: 32.0, + body: r##"<path fill="#ef5350" d="M16 2a14 14 0 1 0 14 14A14 14 0 0 0 16 2m6 10h-4v8a4 4 0 1 1-4-4 3.96 3.96 0 0 1 2 .555V8h6Z"/>"##, +}; +pub(super) static AUTHORS: Icon = Icon { + name: "authors", + view: 24.0, + body: r##"<path fill="#f44336" d="M15.787 13.71c-.275 0-.587 0-.918.047 1.098.796 1.865 1.847 1.865 3.267v2.367h5.68v-2.367c0-2.206-4.42-3.314-6.627-3.314m-7.575 0c-2.206 0-6.628 1.108-6.628 3.314v2.367H14.84v-2.367c0-2.206-4.421-3.314-6.628-3.314m0-1.894a2.84 2.84 0 0 0 2.841-2.84 2.84 2.84 0 0 0-2.84-2.84 2.84 2.84 0 0 0-2.841 2.84 2.84 2.84 0 0 0 2.84 2.84m7.575 0a2.84 2.84 0 0 0 2.84-2.84 2.84 2.84 0 0 0-2.84-2.84 2.84 2.84 0 0 0-2.84 2.84 2.84 2.84 0 0 0 2.84 2.84"/>"##, +}; +pub(super) static BABEL: Icon = Icon { + name: "babel", + view: 24.0, + body: r##"<path fill="#fdd835" d="M18.23 11.21q-.045-.24-1.32-1.65c-.02-.19.29-.45.9-.8l1.74-1.55c.39-.5.62-1.28.69-2.38l-.02-.26c-.07-.78-.63-1.4-1.69-1.89-.63-.42-1.76-.65-3.38-.68-1.35.11-3.11.59-5.28 1.43-.6.43-1.28.86-2.04 1.28l.01.14.21-.08c.08-.01.13.03.14.11l.13-.07.07-.01.01.06c0 .07-.47.44-1.76 1.35l-.06.12c-.31.02-.61.25-.91.67l.08.12.25-.09.18.24c.32-.33.66-.62 1.03-.87.19.05.29.11.44.16 1.02-.75 2.03-1.3 3.04-1.64l.01.14c-.2.27-.32.42-.38.42l.1.23c.01.19-2.55 7-6.66 14.44l.08.19c.35-.08.58-.17.75-.26l.01.13.4-.03-.67 1.76.14.06c.57-.64 1-1.29 1.3-1.88 1.67-.49 2.94-.97 3.82-1.44.88-.08 1.56-.31 2.02-.7l.92-.47c1.27-.98 2.22-1.67 2.87-2.08 1.33-.98 2.2-1.93 2.6-2.85zm-3.46 2.31L13 14.91c-1.29.85-2 1.3-2.09 1.3-2.07 1.13-3.36 1.72-3.86 1.76l-.05.01c.04-.23.96-2.12 2.75-5.67.78-.06 2.02-.43 3.71-1.1l.41-.03c.85-.08 1.49.09 1.91.49l.03.26c-.31.9-.67 1.44-1.04 1.59m1.09-5.78q-.27.33-1.5 1.11c-.27.03-1.27.42-3.01 1.18l-.28-.05-.01-.12c-.02-.25.09-.57.34-.95.13-.7.28-1.12.44-1.2l1.45-3.28c-.02-.22.29-.35.93-.46l.21-.02.01.18 1.16-.16c1.15-.1 1.75.14 1.8.7l.13-.02-.03-.32.15-.02c.35.19.52.4.54.68.02.18-.08.41-.29.68-.09.01-.14-.06-.15-.18l-.14.01-.03.4c-.58.87-1.01 1.31-1.27 1.34z"/>"##, +}; +pub(super) static BROWSERLIST: Icon = Icon { + name: "browserlist", + view: 140.0, + body: r##"<path fill="#ffca28" d="M70 10.172A59.83 59.83 0 0 0 10.172 70 59.83 59.83 0 0 0 70 129.828 59.83 59.83 0 0 0 129.828 70 59.83 59.83 0 0 0 70 10.172m-4.836 8.785C65.66 23 66.516 26.28 67.736 29.18c4.779-4.287 10.265-7.546 16.041-9.02-.981 3.938-1.357 7.295-1.261 10.43 6.026-2.314 12.349-3.404 18.3-2.706-3.182 2.413-5.482 4.717-7.128 7.015-2.201 12.074 6.858 20.43 14.779 24.551a5.13 5.13 0 0 1 5.183-3.888 5.128 5.128 0 0 1 3.7 8.435V64c-.487 1.055-2.002 2.343-3.496 3.219-4.076 2.39-11.173 5.736-20.915 7.39.045 1.214.077 2.453.077 3.747 0 4.817-.485 8.291-1.385 10.699-3.3 13.313-12.648 26.76-24.695 31.95.357-4.082.197-7.484-.402-10.591-5.582 3.219-11.646 5.278-17.623 5.52h-.002c1.785-3.662 2.855-6.878 3.412-9.976-6.347.996-12.727.742-18.377-1.17 2.93-2.732 5.054-5.314 6.673-7.96-6.292-1.344-12.169-3.87-16.766-7.686 3.822-1.544 6.795-3.239 9.3-5.197-5.426-3.517-10.034-7.998-12.972-13.23 4.012-.07 7.321-.568 10.3-1.453-3.786-5.215-6.468-11.032-7.333-16.951 3.861 1.405 7.196 2.133 10.36 2.355-1.662-6.22-2.081-12.605-.768-18.436 3.03 2.634 5.824 4.48 8.63 5.815.677-6.406 2.576-12.52 5.893-17.496 1.926 3.622 3.914 6.392 6.111 8.672 2.93-5.754 6.9-10.798 11.791-14.262zM91.63 38.514c-2.395 5.514-1.665 11.297-.555 18.732a2.138 2.138 0 0 0 .28-4.178 3.419 3.419 0 1 1 .092 6.704c.574 3.882 1.157 8.18 1.421 13.125a67 67 0 0 0 3.25-.649c6.616-1.487 12.258-3.801 16.871-6.506.45-.264.884-.563 1.276-.867.366-.557.333-.957.035-1.285-4.831-1.245-10.891-4.53-15.258-8.795-4.764-4.653-7.427-10.164-7.412-16.281"/>"##, +}; +pub(super) static BUN: Icon = Icon { + name: "bun", + view: 32.0, + body: r##"<path fill="#fff8e1" d="M30 17.045a9.8 9.8 0 0 0-.32-2.306l-.004.034a11.2 11.2 0 0 0-5.762-6.786c-3.495-1.89-5.243-3.326-6.8-3.811h.003c-1.95-.695-3.949.82-5.825 1.927-4.52 2.481-9.573 5.45-9.28 11.417.008-.029.017-.052.026-.08a9.97 9.97 0 0 0 3.934 7.257l-.01-.006C13.747 31.473 30.05 27.292 30 17.045"/><path fill="#37474f" d="M19.855 20.236A.8.8 0 0 0 19.26 20h-6.514a.8.8 0 0 0-.596.236.51.51 0 0 0-.137.463 4.37 4.37 0 0 0 1.641 2.339 4.2 4.2 0 0 0 2.349.926 4.2 4.2 0 0 0 2.343-.926 4.37 4.37 0 0 0 1.642-2.339.5.5 0 0 0-.132-.463Z"/><ellipse cx="22.5" cy="18.5" fill="#f8bbd0" rx="2.5" ry="1.5"/><ellipse cx="9.5" cy="18.5" fill="#f8bbd0" rx="2.5" ry="1.5"/><circle cx="10" cy="16" r="2" fill="#37474f"/><circle cx="22" cy="16" r="2" fill="#37474f"/><path fill="#455a64" d="M9.996 18A2 2 0 1 0 8 15.996V16a2 2 0 0 0 1.996 2"/><circle cx="9" cy="15" r="1" fill="#fafafa"/><circle cx="21" cy="15" r="1" fill="#fafafa"/>"##, +}; +pub(super) static C: Icon = Icon { + name: "c", + view: 32.0, + body: r##"<path fill="#0288d1" d="M19.563 22A5.57 5.57 0 0 1 14 16.437v-2.873A5.57 5.57 0 0 1 19.563 8H24V2h-4.437A11.563 11.563 0 0 0 8 13.563v2.873A11.564 11.564 0 0 0 19.563 28H24v-6Z"/>"##, +}; +pub(super) static CAPACITOR: Icon = Icon { + name: "capacitor", + view: 24.0, + body: r##"<path fill="#4fc3f7" d="m19.081 2.35-4.795 4.795L9.62 2.482 7.05 5.05l4.664 4.665 2.57 2.57 4.705 4.705 2.57-2.57-4.705-4.705 4.795-4.797zM5.052 7.05l-2.57 2.57 4.665 4.664L2.35 19.08l2.57 2.57 4.796-4.796 4.704 4.705 2.57-2.57-7.274-7.274z" paint-order="fill markers stroke"/>"##, +}; +pub(super) static CERTIFICATE: Icon = Icon { + name: "certificate", + view: 32.0, + body: r##"<path fill="#ff5722" d="M4 6v14a2 2 0 0 0 2 2h12v6l3-2 3 2v-6h4a2 2 0 0 0 2-2V6a2 2 0 0 0-2-2H6a2 2 0 0 0-2 2m2 0h8v2H6Zm0 4h6v2H6Zm0 4h8v2H6Zm10 6H6v-2h10Zm8-6v4l-3-2-3 2v-4l-4-2 4-2V6l3 2 3-2v4.2l4 1.8Z"/>"##, +}; +pub(super) static CHANGELOG: Icon = Icon { + name: "changelog", + view: 24.0, + body: r##"<g fill="none"><path d="M0 0h24v24H0z"/><path fill="#8bc34a" d="M13 3a9 9 0 0 0-9 9H1l4 4 4-4H6c0-3.87 3.13-7 7-7s7 3.13 7 7-3.13 7-7 7c-1.93 0-3.68-.79-4.94-2.06l-1.42 1.42A8.95 8.95 0 0 0 13 21a9 9 0 0 0 0-18m-1 5v5l4.25 2.52.77-1.28-3.52-2.09V8z"/></g>"##, +}; +pub(super) static CIRCLECI: Icon = Icon { + name: "circleci", + view: 32.0, + body: r##"<circle cx="16" cy="16" r="4" fill="#fafafa"/><path fill="#fafafa" d="M17.73 2.104a14 14 0 0 0-14.927 9.234.504.504 0 0 0 .48.662h5.525a.49.49 0 0 0 .416-.235 8 8 0 1 1 0 8.47A.49.49 0 0 0 8.81 20H3.28a.503.503 0 0 0-.479.66 14 14 0 1 0 14.93-18.556Z"/>"##, +}; +pub(super) static CLOJURE: Icon = Icon { + name: "clojure", + view: 256.0, + body: r##"<path fill="#64dd17" d="M123.456 129.975a507 507 0 0 0-3.54 7.846c-4.406 9.981-9.284 22.127-11.066 29.908-.64 2.77-1.037 6.205-1.03 10.013 0 1.506.081 3.09.21 4.702a58.1 58.1 0 0 0 19.98 3.559 58.2 58.2 0 0 0 18.29-2.98c-1.352-1.237-2.642-2.554-3.816-4.038-7.796-9.942-12.146-24.512-19.028-49.01m-28.784-49.39C79.782 91.08 70.039 108.387 70.002 128c.037 19.32 9.487 36.403 24.002 46.94 3.56-14.83 12.485-28.41 25.868-55.63a219 219 0 0 0-2.714-7.083c-3.708-9.3-9.059-20.102-13.834-24.993-2.435-2.555-5.389-4.763-8.652-6.648"/><path fill="#7cb342" d="M178.532 194.535c-7.683-.963-14.023-2.124-19.57-4.081a69.4 69.4 0 0 1-30.958 7.249c-38.491 0-69.693-31.198-69.698-69.7 0-20.891 9.203-39.62 23.764-52.392-3.895-.94-7.956-1.49-12.104-1.482-20.45.193-42.037 11.51-51.025 42.075-.84 4.45-.64 7.813-.64 11.8 0 60.591 49.12 109.715 109.705 109.715 37.104 0 69.882-18.437 89.732-46.633-10.736 2.675-21.06 3.955-29.902 3.982-3.314 0-6.425-.177-9.305-.53"/><path fill="#29b6f6" d="M157.922 173.271c.678.336 2.213.884 4.35 1.49 14.375-10.553 23.717-27.552 23.754-46.764h-.005c-.055-32.03-25.974-57.945-58.011-58.009a58.2 58.2 0 0 0-18.213 2.961c11.779 13.426 17.443 32.613 22.922 53.6l.01.025c.01.017 1.752 5.828 4.743 13.538 2.97 7.7 7.203 17.231 11.818 24.178 3.03 4.655 6.363 8 8.632 8.981"/><path fill="#1e88e5" d="M128.009 18.29c-36.746 0-69.25 18.089-89.16 45.826 10.361-6.49 20.941-8.83 30.174-8.747 12.753.037 22.779 3.991 27.589 6.696a51 51 0 0 1 3.345 2.131 69.4 69.4 0 0 1 28.049-5.894c38.496.004 69.703 31.202 69.709 69.698h-.006c0 19.409-7.938 36.957-20.736 49.594 3.142.352 6.492.571 9.912.554 12.15.006 25.284-2.675 35.13-10.956 6.42-5.408 11.798-13.327 14.78-25.199.584-4.586.92-9.247.92-13.991 0-60.588-49.116-109.715-109.705-109.715"/>"##, +}; +pub(super) static CMAKE: Icon = Icon { + name: "cmake", + view: 24.0, + body: r##"<path fill="#1e88e5" d="M11.94 2.984 2.928 21.017l9.875-8.47z"/><path fill="#e53935" d="m11.958 2.982.002.29 1.312 14.499-.002.006.023.26 7.363 2.978h.415l-.158-.31-.114-.228h-.001l-8.84-17.494z"/><path fill="#7cb342" d="m8.558 16.13-5.627 4.884h17.743v-.016z"/>"##, +}; +pub(super) static CONDUCT: Icon = Icon { + name: "conduct", + view: 24.0, + body: r##"<path fill="#cddc39" d="m10 17-4-4 1.41-1.41L10 14.17l6.59-6.59L18 9m-6-6a1 1 0 0 1 1 1 1 1 0 0 1-1 1 1 1 0 0 1-1-1 1 1 0 0 1 1-1m7 0h-4.18C14.4 1.84 13.3 1 12 1s-2.4.84-2.82 2H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V5a2 2 0 0 0-2-2"/>"##, +}; +pub(super) static CONSOLE: Icon = Icon { + name: "console", + view: 24.0, + body: r##"<path fill="#ff7043" d="M20 19V7H4v12zm0-16a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2zm-7 14v-2h5v2zm-3.42-4L5.57 9H8.4l3.3 3.3c.39.39.39 1.03 0 1.42L8.42 17H5.59z"/>"##, +}; +pub(super) static CONTRIBUTING: Icon = Icon { + name: "contributing", + view: 24.0, + body: r##"<path fill="#ffca28" d="M17 9H7V7h10m0 6H7v-2h10m-3 6H7v-2h7M12 3a1 1 0 0 1 1 1 1 1 0 0 1-1 1 1 1 0 0 1-1-1 1 1 0 0 1 1-1m7 0h-4.18C14.4 1.84 13.3 1 12 1s-2.4.84-2.82 2H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V5a2 2 0 0 0-2-2"/>"##, +}; +pub(super) static CPP: Icon = Icon { + name: "cpp", + view: 32.0, + body: r##"<path fill="#0288d1" d="M28 14v-4h-2v4h-6v-4h-2v4h-4v2h4v4h2v-4h6v4h2v-4h4v-2z"/><path fill="#0288d1" d="M13.563 22A5.57 5.57 0 0 1 8 16.437v-2.873A5.57 5.57 0 0 1 13.563 8H18V2h-4.437A11.563 11.563 0 0 0 2 13.563v2.873A11.564 11.564 0 0 0 13.563 28H18v-6Z"/>"##, +}; +pub(super) static CREDITS: Icon = Icon { + name: "credits", + view: 32.0, + body: r##"<path fill="#9ccc65" d="M4 2h24v4H4zm6 6h12v4H10zm-6 6h24v4H4zm6 6h12v4H10zm-6 6h24v4H4z"/>"##, +}; +pub(super) static CSHARP: Icon = Icon { + name: "csharp", + view: 32.0, + body: r##"<path fill="#0288d1" d="M30 14v-2h-2V8h-2v4h-2V8h-2v4h-2v2h2v2h-2v2h2v4h2v-4h2v4h2v-4h2v-2h-2v-2Zm-4 2h-2v-2h2Zm-12.437 6A5.57 5.57 0 0 1 8 16.437v-2.873A5.57 5.57 0 0 1 13.563 8H18V2h-4.437A11.563 11.563 0 0 0 2 13.563v2.873A11.564 11.564 0 0 0 13.563 28H18v-6Z"/>"##, +}; +pub(super) static CSS: Icon = Icon { + name: "css", + view: 32.0, + body: r##"<path fill="#7e57c2" d="M20 18h-2v-2h-2v2c0 .193 0 .703 1.254 1.033A3.345 3.345 0 0 1 20 22h2v2h2v-2c0-.388-.562-.851-1.254-1.034C20.356 20.34 20 18.84 20 18m-3.254 2.966C14.356 20.34 14 18.84 14 18h-2v-2h-2v8h2v-2h4v2h2v-2c0-.388-.562-.851-1.254-1.034"/><path fill="#7e57c2" d="M24 4H4v20a4 4 0 0 0 4 4h16.16A3.84 3.84 0 0 0 28 24.16V8a4 4 0 0 0-4-4m2 14h-2v-2h-2v2c0 .193 0 .703 1.254 1.033A3.345 3.345 0 0 1 26 22v2a2 2 0 0 1-2 2h-2a2 2 0 0 1-2-2 2 2 0 0 1-2 2h-2a2 2 0 0 1-2-2 2 2 0 0 1-2 2h-2a2 2 0 0 1-2-2v-8a2 2 0 0 1 2-2h2a2 2 0 0 1 2 2 2 2 0 0 1 2-2h2a2 2 0 0 1 2 2 2 2 0 0 1 2-2h2a2 2 0 0 1 2 2Z"/>"##, +}; +pub(super) static CYPRESS: Icon = Icon { + name: "cypress", + view: 24.0, + body: r##"<path fill="#00bfa5" d="M11.998 2A9.993 9.993 0 0 0 2 12a9.993 9.993 0 0 0 10 10c5.528 0 10-4.473 10-10-.001-5.527-4.51-10-10.002-10m-4.69 12.146c.327.436.763.618 1.381.618.292 0 .583-.037.837-.146.255-.108.546-.255.908-.473l1.019 1.454c-.836.692-1.782 1.018-2.873 1.018-.873 0-1.6-.182-2.254-.545a3.66 3.66 0 0 1-1.454-1.599c-.327-.691-.509-1.491-.509-2.437 0-.908.182-1.745.508-2.436a3.85 3.85 0 0 1 1.457-1.672c.617-.4 1.38-.582 2.217-.582.583 0 1.128.072 1.564.254.49.19.944.46 1.345.8l-1.018 1.382a4 4 0 0 0-.836-.474c-.254-.108-.582-.145-.873-.145-1.236 0-1.854.945-1.854 2.872-.036.983.146 1.673.437 2.11zm10 2.254c-.363 1.128-.909 1.964-1.673 2.582-.763.619-1.782.946-3.054 1.055l-.254-1.708c.836-.11 1.454-.292 1.854-.583.145-.108.437-.436.437-.436l-3.019-9.673h2.508l1.746 7.236 1.855-7.236h2.436z"/>"##, +}; +pub(super) static DART: Icon = Icon { + name: "dart", + view: 32.0, + body: r##"<path fill="#4fc3f7" d="M16.83 2a1.3 1.3 0 0 0-.916.377l-.013.01L7.323 7.34l8.556 8.55v.005l10.283 10.277 1.96-3.529-7.068-16.96-3.299-3.297A1.3 1.3 0 0 0 16.828 2Z"/><path fill="#01579b" d="m7.343 7.32-4.955 8.565-.01.013a1.297 1.297 0 0 0 .004 1.835l.005.005 4.106 4.107 16.064 6.314 3.632-2.015-.098-.098-.025.002L15.995 15.97h-.012z"/><path fill="#01579b" d="m7.321 7.324 8.753 8.755h.013L26.16 26.156l3.835-.73L30 14.089l-4.049-3.965a6.5 6.5 0 0 0-3.618-1.612l.002-.043L7.323 7.325Z"/><path fill="#64b5f6" d="m7.332 7.335 8.758 8.75v.013l10.079 10.071L25.436 30H14.09l-3.967-4.048a6.5 6.5 0 0 1-1.611-3.618l-.045.004Z"/>"##, +}; +pub(super) static DATABASE: Icon = Icon { + name: "database", + view: 32.0, + body: r##"<path fill="#ffca28" d="M16 24c-5.525 0-10-.9-10-2v4c0 1.1 4.475 2 10 2s10-.9 10-2v-4c0 1.1-4.475 2-10 2m0-8c-5.525 0-10-.9-10-2v4c0 1.1 4.475 2 10 2s10-.9 10-2v-4c0 1.1-4.475 2-10 2m0-12C10.477 4 6 4.895 6 6v4c0 1.1 4.475 2 10 2s10-.9 10-2V6c0-1.105-4.477-2-10-2"/>"##, +}; +pub(super) static DENO: Icon = Icon { + name: "deno", + view: 32.0, + body: r##"<path fill="#cfd8dc" d="M3.069 10.688C3.069 5.873 7.859 2 14 2a11.9 11.9 0 0 1 7.49 2.378 10.64 10.64 0 0 1 3.593 5.236l.015.049.017.057.034.108.048.198.134.463.14.529.238.875.38 1.386.613 2.28.692 2.593 1.116 4.168.42 1.571-.09.1A18.98 18.98 0 0 1 17.337 30l-.04-.273-.074-.545-.066-.395-.076-.52-.097-.634-.042-.25-.091-.602-.057-.356-.074-.462-.076-.444-.074-.432-.074-.422-.066-.413-.074-.395-.068-.38-.048-.281-.057-.271-.034-.173-.066-.35-.05-.246-.057-.305-.049-.215-.042-.205-.043-.2-.023-.132-.059-.248-.042-.181-.04-.182-.032-.114-.042-.167-.032-.157-.042-.156-.043-.148-.023-.091-.042-.142-.032-.13-.025-.092-.034-.084-.023-.072-.034-.116-.025-.085-.017-.049q-.067-.196-.148-.386l-.026-.051.19-.495-.75.026-.207.008c-6.82.14-11.222-2.759-11.222-7.301Zm14.345-4.101a2 2 0 1 0 0 2.827 2 2 0 0 0 0-2.827"/><path fill="#cfd8dc" d="M3.069 10.688c.95-12.027 21.388-11.423 22.64 1.205 1.027 3.74 2.21 8.244 3.222 11.998A18.98 18.98 0 0 1 17.337 30c-.407-2.79-.84-5.602-1.41-8.364a27 27 0 0 0-.505-2.123c-.104-.536-.523-1.043-.173-1.56-6.665.529-12.374-2.428-12.18-7.267Zm14.345-4.101c-1.807-1.861-4.689 1.02-2.827 2.828 1.807 1.86 4.689-1.021 2.827-2.828"/>"##, +}; +pub(super) static DEPENDABOT: Icon = Icon { + name: "dependabot", + view: 32.0, + body: r##"<path fill="#448aff" d="M29.5 16H28v-4a2 2 0 0 0-2-2h-6V2.5a.5.5 0 0 0-.5-.5h-5a.5.5 0 0 0-.5.5v3a.5.5 0 0 0 .5.5H18v4H6a2 2 0 0 0-2 2v4H2.5a.5.5 0 0 0-.5.5v7a.5.5 0 0 0 .5.5H4v2a2 2 0 0 0 2 2h20a2 2 0 0 0 2-2v-2h1.5a.5.5 0 0 0 .5-.5v-7a.5.5 0 0 0-.5-.5m-15.533 2.647-3.106 3.106a.6.6 0 0 1-.84 0l-1.867-1.866a.6.6 0 0 1 0-.84l.627-.64a.6.6 0 0 1 .848-.005l.005.005.8.8 2.053-2.04a.6.6 0 0 1 .84 0l.64.64a.58.58 0 0 1 0 .84m9.88 0-3.106 3.106a.6.6 0 0 1-.84 0l-1.867-1.866a.6.6 0 0 1 0-.84l.627-.64a.6.6 0 0 1 .84 0l.813.8 2.053-2.04a.6.6 0 0 1 .84 0l.64.64a.604.604 0 0 1 0 .84"/>"##, +}; +pub(super) static DOCKER: Icon = Icon { + name: "docker", + view: 24.0, + body: r##"<path fill="#0288d1" d="M21.81 10.25c-.06-.04-.56-.43-1.64-.43-.28 0-.56.03-.84.08-.21-1.4-1.38-2.11-1.43-2.14l-.29-.17-.18.27c-.24.36-.43.77-.51 1.19-.2.8-.08 1.56.33 2.21-.49.28-1.29.35-1.46.35H2.62c-.34 0-.62.28-.62.63 0 1.15.18 2.3.58 3.38.45 1.19 1.13 2.07 2 2.61.98.6 2.59.94 4.42.94.79 0 1.61-.07 2.42-.22 1.12-.2 2.2-.59 3.19-1.16A8.3 8.3 0 0 0 16.78 16c1.05-1.17 1.67-2.5 2.12-3.65h.19c1.14 0 1.85-.46 2.24-.85.26-.24.45-.53.59-.87l.08-.24zm-17.96.99h1.76c.08 0 .16-.07.16-.16V9.5c0-.08-.07-.16-.16-.16H3.85c-.09 0-.16.07-.16.16v1.58c.01.09.07.16.16.16m2.43 0h1.76c.08 0 .16-.07.16-.16V9.5c0-.08-.07-.16-.16-.16H6.28c-.09 0-.16.07-.16.16v1.58c.01.09.07.16.16.16m2.47 0h1.75c.1 0 .17-.07.17-.16V9.5c0-.08-.06-.16-.17-.16H8.75c-.08 0-.15.07-.15.16v1.58c0 .09.06.16.15.16m2.44 0h1.77c.08 0 .15-.07.15-.16V9.5c0-.08-.06-.16-.15-.16h-1.77c-.08 0-.15.07-.15.16v1.58c0 .09.07.16.15.16M6.28 9h1.76c.08 0 .16-.09.16-.18V7.25c0-.09-.07-.16-.16-.16H6.28c-.09 0-.16.06-.16.16v1.57c.01.09.07.18.16.18m2.47 0h1.75c.1 0 .17-.09.17-.18V7.25c0-.09-.06-.16-.17-.16H8.75c-.08 0-.15.06-.15.16v1.57c0 .09.06.18.15.18m2.44 0h1.77c.08 0 .15-.09.15-.18V7.25c0-.09-.07-.16-.15-.16h-1.77c-.08 0-.15.06-.15.16v1.57c0 .09.07.18.15.18m0-2.28h1.77c.08 0 .15-.07.15-.16V5c0-.1-.07-.17-.15-.17h-1.77c-.08 0-.15.06-.15.17v1.56c0 .08.07.16.15.16m2.46 4.52h1.76c.09 0 .16-.07.16-.16V9.5c0-.08-.07-.16-.16-.16h-1.76c-.08 0-.15.07-.15.16v1.58c0 .09.07.16.15.16"/>"##, +}; +pub(super) static DOCUMENT: Icon = Icon { + name: "document", + view: 24.0, + body: r##"<g fill="none"><path d="M0 0h24v24H0z"/><path fill="#42a5f5" d="M8 16h8v2H8zm0-4h8v2H8zm6-10H6c-1.1 0-2 .9-2 2v16c0 1.1.89 2 1.99 2H18c1.1 0 2-.9 2-2V8zm4 18H6V4h7v5h5z"/></g>"##, +}; +pub(super) static EDITORCONFIG: Icon = Icon { + name: "editorconfig", + view: 3473.0, + body: r##"<g clip-rule="evenodd" image-rendering="optimizeQuality" shape-rendering="geometricPrecision" text-rendering="geometricPrecision"><path fill="#ede7f6" d="M989.342 1977.409c41.146-26.835 75.137-93.922 54.564-141.33-56.353 24.151-53.67 79.61-54.564 141.33m636.877 153.851c44.724-14.311 87.66-64.402 63.509-116.283-34.886 24.151-57.248 57.247-63.51 116.284z"/><g fill="#fafafa"><path d="M374.827 2871.899c0 56.352 14.312 117.178 53.67 138.645 144.907 81.4 652.977 17.89 825.614-20.573 90.343-20.573 163.692-87.66 248.668-124.334 191.421-83.187 330.067-150.274 483.025-262.085 110.916-81.399 287.131-310.388 305.915-447.245l-151.169-33.991c-3.578 153.852-38.463 188.737-175.32 224.517-92.132 25.046-271.925 30.413-365.846 14.312-124.334-20.574-180.687-85.871-237.04-160.114-109.128-144.907 24.151-245.985-148.485-255.824-181.582 222.728-501.81 62.614-642.244 40.252-59.93 86.765-200.366 650.294-198.577 779.1 86.766-29.517 141.33 2.684 219.15 33.097 275.503 106.444 34.885 200.366-75.137 172.636-75.137-17.89-98.394-67.086-142.224-98.393m360.48-1285.383c111.81 21.468 211.1 67.982 305.915 115.39 154.747 76.926 182.476 66.192 196.788 173.53 1.789 19.68-1.789 30.413 54.564 48.303 94.816 29.518-54.564-23.257 199.471-22.362 151.169.894 497.337 61.72 609.148 132.384 46.513 29.519 37.568 67.087 194.999 62.615-1.79-185.16-50.986-461.557-123.44-631.51-88.554-205.733-205.733-237.04-444.561-313.966-139.54-44.725-549.217-93.922-676.235-15.207-118.967 74.243-141.33 162.798-252.246 318.439-32.202 45.619-43.83 80.504-64.403 132.384"/><path d="M1720.14 1966.675c89.45 36.674-4.472 273.714-128.806 216.466-40.252-113.6 55.458-178.003 81.398-228.99-53.67-8.05-206.627-32.2-252.246-15.206-59.036 22.363-72.454 148.486-42.041 207.522 143.118 280.87 775.523 220.94 708.436 2.684-26.835-88.555-51.88-102.867-142.224-133.28-72.454-24.15-144.907-49.196-224.517-49.196m-1124.374-31.307c71.56 68.875 233.462 79.61 338.117 84.976 13.418-138.646 25.046-242.407 135.963-234.356 54.564 74.242 25.94 161.902-31.307 218.255 97.5-.894 153.852-74.242 139.54-180.687-82.293-59.036-331.856-177.109-457.084-194.104-34.885 37.569-120.756 243.301-125.229 305.916"/></g><path d="M427.602 2820.913c59.036-5.367 212.889 39.357 225.412 89.449-95.71 11.628-217.361 2.683-225.412-89.45zm-52.775 50.986c43.83 31.307 67.087 80.504 142.224 98.393 110.022 27.73 350.64-66.192 75.137-172.636-77.82-30.413-132.384-62.614-219.15-33.096-1.789-128.807 138.646-692.336 198.577-779.101 140.435 22.362 460.662 182.476 642.244-40.252 172.636 9.84 39.357 110.917 148.485 255.824 56.353 74.243 112.706 139.54 237.04 160.114 93.921 16.1 273.714 10.734 365.846-14.312 136.857-35.78 171.742-70.665 175.32-224.517l151.17 33.99c-18.785 136.858-195 365.847-305.916 447.246-152.958 111.81-291.604 178.898-483.025 262.085-84.976 36.674-158.325 103.761-248.668 124.334-172.637 38.463-680.707 101.972-825.614 20.574-39.358-21.468-53.67-82.294-53.67-138.646M1626.22 2131.26c6.261-59.037 28.623-92.133 63.508-116.284 24.152 51.88-18.784 101.972-63.508 116.284m93.921-164.586c79.61 0 152.063 25.045 224.517 49.197 90.344 30.412 115.39 44.724 142.224 133.279 67.087 218.255-565.318 278.186-708.436-2.684-30.413-59.036-16.995-185.16 42.041-207.522 45.619-16.995 198.577 7.156 252.246 15.207-25.94 50.986-121.65 115.389-81.398 228.99 124.334 57.247 218.255-179.793 128.806-216.467m-730.798 10.734c.894-61.72-1.79-117.179 54.564-141.33 20.573 47.408-13.418 114.495-54.564 141.33m-393.576-42.041c4.473-62.615 90.344-268.347 125.229-305.916 125.228 16.995 374.791 135.068 457.084 194.104 14.312 106.445-42.04 179.793-139.54 180.687 57.247-56.353 85.87-144.013 31.307-218.255-110.917-8.05-122.545 95.71-135.963 234.356-104.655-5.367-266.558-16.1-338.117-84.976m-89.449-71.56c-33.096-91.238-33.096-233.462 107.339-245.09l-71.56 199.471c-18.783 42.936-18.783 33.096-35.779 45.62zm228.99-277.292c20.573-51.88 32.201-86.765 64.403-132.384 110.917-155.641 133.279-244.196 252.246-318.439 127.018-78.715 536.694-29.518 676.235 15.207 238.828 76.926 356.007 108.233 444.561 313.966 72.454 169.953 121.65 446.35 123.44 631.51-157.43 4.472-148.486-33.096-195-62.615-111.81-70.664-457.978-131.49-609.147-132.384-254.035-.895-104.655 51.88-199.471 22.362-56.353-17.89-52.775-28.624-54.564-48.302-14.312-107.34-42.041-96.605-196.788-173.531-94.816-47.408-194.104-93.922-305.915-115.39m1583.247-43.83c-16.995-56.352 14.312-52.775 68.876-91.238 31.307-22.362 56.353-45.619 94.816-67.086 144.013-80.504 412.36-93.922 526.854 1.789 46.514 38.463 122.545 113.6 110.917 211.994-24.151 195.893-158.325 303.232-268.347 392.68-111.811 91.239-297.865 185.16-490.18 122.546-16.101-39.358-3.578-288.92-22.363-381.053-16.995-82.293-8.05-91.238 39.358-140.435 139.54-144.907 441.878-250.457 613.62-126.123 72.454 53.67 51.88 74.243 89.449 115.39 46.513-50.092-40.252-218.256-360.48-207.522-217.36 7.156-311.282 177.109-402.52 169.058m-1302.377-508.964c4.472-124.335 118.967-381.948 233.461-471.397 138.646-107.338 283.554-208.416 496.442-87.66 52.775 29.519 50.092 44.725 55.459 118.073 4.472 70.665-1.79 96.605-19.679 153.852-141.33 456.19-259.402 194.105-712.014 302.338 16.995-148.485 145.802-280.87 217.361-349.746 122.545-118.967 211.1-195.893 395.365-170.847 50.986 84.976 56.352 138.646-5.367 237.934-82.293 132.385-102.867 124.334-90.344 214.678 64.403-16.101 84.082-78.715 113.6-141.33 179.793-375.686-81.398-421.305-241.512-352.429-107.339 45.62-298.76 256.719-361.374 383.736-12.523 25.046-25.94 57.248-37.568 84.977zm708.436 18.784c18.784-111.811 129.7-139.54 129.7-483.92 0-148.485-182.475-281.764-421.304-182.475-204.838 84.082-236.145 148.485-345.273 313.071-102.867 155.642-99.289 326.49-187.843 470.502-25.94 41.147-49.197 55.458-77.82 96.605-20.574 30.413-35.78 68.876-56.354 104.655-42.04 68.876-84.976 118.968-118.967 201.26-107.339 2.684-197.682 4.473-208.416 115.39-14.312 152.063 57.247 189.632 57.247 246.879-.894 61.72-251.351 684.285-181.581 1055.498 19.679 101.972 86.765 102.867 194.104 115.39 258.508 31.307 593.942 20.573 825.614-72.454l420.41-201.26c106.445-59.931 285.343-173.532 364.953-256.72 56.353-58.141 85.87-107.338 134.173-176.214 66.192-96.605 67.981-94.816 82.293-226.306 87.66 16.101 251.352 54.564 305.916 101.972-6.262 61.72-36.674 32.202-36.674 87.66 34.885.895 93.027-42.935 107.339-91.238-36.675-53.67-75.138-44.724-127.913-87.66 42.042-33.096 118.073-48.302 176.215-72.453 125.229-51.88 339.012-209.311 391.787-352.43 42.04-115.389 10.734-307.704-57.248-382.841-71.559-78.715-237.934-118.967-373.897-118.967-161.902 0-329.172 116.283-459.767 166.375-50.092-43.83-53.67-93.922-90.344-142.224-42.04-57.248-315.755-200.366-446.35-228.095"/><path fill="#efebe9" d="M2318.554 1542.686c91.238 8.05 185.16-161.902 402.52-169.058 320.228-10.734 406.993 157.43 360.48 207.521-37.569-41.146-16.995-61.72-89.45-115.389-171.741-124.334-474.079-18.784-613.62 126.123-47.407 49.197-56.352 58.142-39.357 140.435 18.785 92.133 6.262 341.695 22.362 381.053 192.316 62.614 378.37-31.307 490.181-122.545 110.022-89.45 244.196-196.788 268.347-392.681 11.628-98.394-64.403-173.531-110.917-211.994-114.494-95.71-382.841-82.293-526.854-1.79-38.463 21.468-63.51 44.725-94.816 67.087-54.564 38.464-85.871 34.886-68.876 91.238m-1302.377-508.964 43.83-77.821c11.628-27.73 25.045-59.93 37.568-84.977 62.614-127.017 254.035-338.117 361.374-383.736 160.114-68.876 421.305-23.257 241.512 352.43-29.518 62.614-49.197 125.228-113.6 141.329-12.523-90.344 8.05-82.293 90.344-214.678 61.72-99.288 56.353-152.958 5.367-237.934-184.265-25.046-272.82 51.88-395.365 170.847-71.56 68.876-200.366 201.26-217.361 349.746 452.612-108.233 570.685 153.852 712.014-302.338 17.89-57.247 24.151-83.187 19.679-153.852-5.367-73.348-2.684-88.554-55.459-118.073-212.888-120.756-357.796-19.678-496.442 87.66-114.494 89.45-228.989 347.062-233.461 471.397"/><path fill="#eee" d="M506.317 1863.808c16.996-12.523 16.996-2.683 35.78-45.619l71.559-199.47c-140.435 11.627-140.435 153.851-107.339 245.09z"/><path fill="#efebe9" d="M653.014 2910.362c-12.523-50.092-166.376-94.816-225.412-89.45 8.05 92.133 129.701 101.078 225.412 89.45"/></g>"##, +}; +pub(super) static ELIXIR: Icon = Icon { + name: "elixir", + view: 24.0, + body: r##"<path fill="#9575cd" d="M12.173 22.681c-3.86 0-6.99-3.64-6.99-8.13 0-3.678 2.773-8.172 4.916-10.91 1.014-1.296 2.93-2.322 2.93-2.322s-.982 5.239 1.683 7.319c2.366 1.847 4.106 4.25 4.106 6.363 0 4.232-2.784 7.68-6.645 7.68"/>"##, +}; +pub(super) static ELM: Icon = Icon { + name: "elm", + view: 323.0, + body: r##"<path fill="#ffb300" d="m106.716 99.763 54.785 54.782 54.779-54.782z"/><path fill="#64dd17" d="M96.881 89.93H216.83l-55.18-55.184H41.7zm131.546 11.593 59.705 59.704L228.16 221.2l-59.705-59.704z"/><path fill="#00b8d4" d="m175.552 34.746 112.703 112.695V34.746z"/><path fill="#455a64" d="m34.746 281.3 119.8-119.8-119.8-119.8z"/><path fill="#ffb300" d="m288.255 175.01-53.148 53.149 53.148 53.14z"/><path fill="#00b8d4" d="M281.3 288.254 161.5 168.455l-119.8 119.8z"/>"##, +}; +pub(super) static ERLANG: Icon = Icon { + name: "erlang", + view: 30.0, + body: r##"<path fill="#f44336" d="M5.207 4.33q-.072.075-.143.153Q1.5 8.476 1.5 15.33c0 4.418 1.155 7.862 3.459 10.34h19.415c2.553-1.152 4.127-3.43 4.127-3.43l-3.147-2.52L23.9 21.1c-.867.773-.845.931-2.315 1.78-1.495.674-3.04.966-4.634.966-2.515 0-4.423-.909-5.723-2.059-1.286-1.15-1.985-4.511-2.096-6.68l17.458.067-.183-1.472s-.847-7.129-2.541-9.372zm8.76.846c1.565 0 3.22.535 3.961 1.471.74.937.931 1.667.973 3.524H9.11c.112-1.955.436-2.81 1.373-3.698.936-.887 2.03-1.297 3.484-1.297"/>"##, +}; +pub(super) static ESLINT: Icon = Icon { + name: "eslint", + view: 32.0, + body: r##"<path fill="#3f51b5" d="M22.713 4H9.287a.5.5 0 0 0-.432.248l-6.708 11.5a.5.5 0 0 0 0 .504l6.708 11.5a.5.5 0 0 0 .432.248h13.426a.5.5 0 0 0 .432-.248l6.708-11.5a.5.5 0 0 0 0-.504l-6.708-11.5A.5.5 0 0 0 22.713 4m-6.937 20.888-7.5-3.75A.5.5 0 0 1 8 20.691v-9.382a.5.5 0 0 1 .276-.447l7.5-3.75a.5.5 0 0 1 .448 0l7.5 3.75a.5.5 0 0 1 .276.447v9.382a.5.5 0 0 1-.276.447l-7.5 3.75a.5.5 0 0 1-.448 0"/><path fill="#7986cb" d="M22 19.441v-6.882a.5.5 0 0 0-.276-.447l-5.5-2.75a.5.5 0 0 0-.448 0l-5.5 2.75a.5.5 0 0 0-.276.447v6.882a.5.5 0 0 0 .276.447l5.5 2.75a.5.5 0 0 0 .448 0l5.5-2.75a.5.5 0 0 0 .276-.447"/>"##, +}; +pub(super) static FAVICON: Icon = Icon { + name: "favicon", + view: 32.0, + body: r##"<path fill="#ffd54f" d="m16 24 10 6-4-10 8-8-10-.032L16 2l-4 10H2l8 8-4 10Z"/>"##, +}; +pub(super) static FIREBASE: Icon = Icon { + name: "firebase", + view: 24.0, + body: r##"<path fill="#ff9100" d="M18.217 8.974c-.45-.623-1.482-1.904-3.07-3.808-.689-.825-1.28-1.526-1.57-1.87l-.408-.48-.173-.205-.094-.11-.018-.027-.008-.004-.4-.47-.509.407a11.1 11.1 0 0 0-3.069 3.866 9.5 9.5 0 0 0-.87 2.647q-.06.303-.1.615a9 9 0 0 0-.577-.03 6.2 6.2 0 0 0-1.901.229l-.265.074-.136.238a8 8 0 0 0-1.044 3.68 8 8 0 0 0 5.006 7.697l.197.079.06.02h.002a8 8 0 0 0 2.452.473q.143.005.286.005a7.9 7.9 0 0 0 3.076-.618l.007.003.261-.12a7.99 7.99 0 0 0 4.643-6.981 8.5 8.5 0 0 0-1.778-5.31M9.837 19.82l-.192-.074-.051-.02a6.31 6.31 0 0 1-3.897-6.048 6.2 6.2 0 0 1 .697-2.667 4.6 4.6 0 0 1 .759-.103l.065-.002a8 8 0 0 1 .378 0c.108.005.215.021.322.034a13 13 0 0 0 .918 4.007 10.1 10.1 0 0 0 2.474 3.61 6.4 6.4 0 0 1-1.473 1.263m.351-5.486a11.4 11.4 0 0 1-.767-3.125 4.6 4.6 0 0 1 .95.461 4.73 4.73 0 0 1 1.94 2.884 5 5 0 0 1 .12.649 4.2 4.2 0 0 1-.288 2.023 8.3 8.3 0 0 1-1.955-2.892m1.741 5.858a8 8 0 0 0 .553-.62c.233.177.485.332.73.495a6.3 6.3 0 0 1-1.283.125m5.432-2.97a6.34 6.34 0 0 1-2.212 2.138 12.4 12.4 0 0 1-1.851-1.15 5.84 5.84 0 0 0 .309-3.998 6.02 6.02 0 0 0-2.504-3.664 6.1 6.1 0 0 0-1.679-.74 8 8 0 0 1 .064-.496 9 9 0 0 1 .465-1.598q.117-.298.253-.584l.004-.007c.14-.282.296-.567.481-.872l.073-.12h-.002a9.2 9.2 0 0 1 1.534-1.824l.227.269c.53.628 1.03 1.222 1.483 1.765 1.02 1.223 2.342 2.828 2.852 3.536a6.8 6.8 0 0 1 1.446 4.242 6.3 6.3 0 0 1-.943 3.104"/>"##, +}; +pub(super) static FOLDER: Icon = Icon { + name: "folder", + view: 16.0, + body: r##"<path d="m6.922 3.768-.644-.536A1 1 0 0 0 5.638 3H2a1 1 0 0 0-1 1v8a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1V5a1 1 0 0 0-1-1H7.562a1 1 0 0 1-.64-.232" fill="currentColor" />"##, +}; +pub(super) static FOLDER_ANDROID: Icon = Icon { + name: "folder-android", + view: 32.0, + body: r##"<path fill="#8bc34a" d="m13.844 7.536-1.288-1.072A2 2 0 0 0 11.276 6H4a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h24a2 2 0 0 0 2-2V10a2 2 0 0 0-2-2H15.124a2 2 0 0 1-1.28-.464"/><path fill="#dcedc8" d="M27.943 19.471 32 15.414 30.586 14l-4.333 4.333a11.01 11.01 0 0 0-10.505 0L11.414 14 10 15.414l4.057 4.057A10.98 10.98 0 0 0 10 28h22a10.98 10.98 0 0 0-4.057-8.529M18 26h-4v-4h4Zm10 0h-4v-4h4Z"/>"##, +}; +pub(super) static FOLDER_ANDROID_OPEN: Icon = Icon { + name: "folder-android-open", + view: 32.0, + body: r##"<path fill="#8bc34a" d="M28.967 12H9.442a2 2 0 0 0-1.898 1.368L4 24V10h24a2 2 0 0 0-2-2H15.124a2 2 0 0 1-1.28-.464l-1.288-1.072A2 2 0 0 0 11.276 6H4a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h22l4.805-11.212A2 2 0 0 0 28.967 12"/><path fill="#dcedc8" d="M27.943 19.471 32 15.414 30.586 14l-4.333 4.333a11.01 11.01 0 0 0-10.505 0L11.414 14 10 15.414l4.057 4.057A10.98 10.98 0 0 0 10 28h22a10.98 10.98 0 0 0-4.057-8.529M18 26h-4v-4h4Zm10 0h-4v-4h4Z"/>"##, +}; +pub(super) static FOLDER_API: Icon = Icon { + name: "folder-api", + view: 32.0, + body: r##"<path fill="#fbc02d" d="m13.844 7.536-1.288-1.072A2 2 0 0 0 11.276 6H4a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h24a2 2 0 0 0 2-2V10a2 2 0 0 0-2-2H15.124a2 2 0 0 1-1.28-.464"/><path fill="#fffde7" d="M20 18h-4v2h6v-6h-2zm8 0v-4h-2v6h6v-2zm-12 8h4v4h2v-6h-6zm10 0v4h2v-4h4v-2h-6z"/>"##, +}; +pub(super) static FOLDER_API_OPEN: Icon = Icon { + name: "folder-api-open", + view: 32.0, + body: r##"<path fill="#fbc02d" d="M28.967 12H9.442a2 2 0 0 0-1.898 1.368L4 24V10h24a2 2 0 0 0-2-2H15.124a2 2 0 0 1-1.28-.464l-1.288-1.072A2 2 0 0 0 11.276 6H4a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h22l4.805-11.212A2 2 0 0 0 28.967 12"/><path fill="#fffde7" d="M20 18h-4v2h6v-6h-2zm8 0v-4h-2v6h6v-2zm-12 8h4v4h2v-6h-6zm10 0v4h2v-4h4v-2h-6z"/>"##, +}; +pub(super) static FOLDER_AWS: Icon = Icon { + name: "folder-aws", + view: 32.0, + body: r##"<path fill="#ffb300" d="m13.844 7.536-1.288-1.072A2 2 0 0 0 11.276 6H4a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h24a2 2 0 0 0 2-2V10a2 2 0 0 0-2-2H15.124a2 2 0 0 1-1.28-.464"/><path fill="#ffecb3" d="M27.881 19.23a6.591 6.591 0 0 0-12.308-1.76 5.278 5.278 0 0 0 .572 10.525h11.428a4.388 4.388 0 0 0 .308-8.766Z"/>"##, +}; +pub(super) static FOLDER_AWS_OPEN: Icon = Icon { + name: "folder-aws-open", + view: 32.0, + body: r##"<path fill="#ffb300" d="M28.967 12H9.442a2 2 0 0 0-1.898 1.368L4 24V10h24a2 2 0 0 0-2-2H15.124a2 2 0 0 1-1.28-.464l-1.288-1.072A2 2 0 0 0 11.276 6H4a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h22l4.805-11.212A2 2 0 0 0 28.967 12"/><path fill="#ffecb3" d="M27.881 19.23a6.591 6.591 0 0 0-12.308-1.76 5.278 5.278 0 0 0 .572 10.525h11.428a4.388 4.388 0 0 0 .308-8.766Z"/>"##, +}; +pub(super) static FOLDER_AZURE_PIPELINES: Icon = Icon { + name: "folder-azure-pipelines", + view: 32.0, + body: r##"<path fill="#1e88e5" d="m13.844 7.536-1.288-1.072A2 2 0 0 0 11.276 6H4a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h24a2 2 0 0 0 2-2V10a2 2 0 0 0-2-2H15.124a2 2 0 0 1-1.28-.464"/><path fill="#bbdefb" d="m28 22 3.724-1.862a.5.5 0 0 0 .276-.447V12.5a.5.5 0 0 0-.5-.5h-7.191a.5.5 0 0 0-.447.276L22 16h-5.5a.5.5 0 0 0-.5.5V20l1.172 1.172 1.414-1.415L20 21.172l-1.414 1.414 2.828 2.828L22.828 24l1.415 1.414-1.415 1.414L24 28h3.5a.5.5 0 0 0 .5-.5Zm0-4a2 2 0 1 1 2-2 2 2 0 0 1-2 2M16 28v-4h-2v6h6v-2z"/>"##, +}; +pub(super) static FOLDER_AZURE_PIPELINES_OPEN: Icon = Icon { + name: "folder-azure-pipelines-open", + view: 32.0, + body: r##"<path fill="#1e88e5" d="M28.967 12H9.442a2 2 0 0 0-1.898 1.368L4 24V10h24a2 2 0 0 0-2-2H15.124a2 2 0 0 1-1.28-.464l-1.288-1.072A2 2 0 0 0 11.276 6H4a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h22l4.805-11.212A2 2 0 0 0 28.967 12"/><path fill="#bbdefb" d="m28 22 3.724-1.862a.5.5 0 0 0 .276-.447V12.5a.5.5 0 0 0-.5-.5h-7.191a.5.5 0 0 0-.447.276L22 16h-5.5a.5.5 0 0 0-.5.5V20l1.172 1.172 1.414-1.415L20 21.172l-1.414 1.414 2.828 2.828L22.828 24l1.415 1.414-1.415 1.414L24 28h3.5a.5.5 0 0 0 .5-.5Zm0-4a2 2 0 1 1 2-2 2 2 0 0 1-2 2M16 28v-4h-2v6h6v-2z"/>"##, +}; +pub(super) static FOLDER_BACKUP: Icon = Icon { + name: "folder-backup", + view: 32.0, + body: r##"<path fill="#8d6e63" d="m13.844 7.536-1.288-1.072A2 2 0 0 0 11.276 6H4a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h24a2 2 0 0 0 2-2V10a2 2 0 0 0-2-2H15.124a2 2 0 0 1-1.28-.464"/><path fill="#d7ccc8" d="M25.375 24.781 20 20.48V14h2v5.52l4.625 3.699z"/><path fill="#d7ccc8" d="M22 30a10 10 0 1 1 10-10 10.01 10.01 0 0 1-10 10m0-18a8 8 0 1 0 8 8 8.01 8.01 0 0 0-8-8"/>"##, +}; +pub(super) static FOLDER_BACKUP_OPEN: Icon = Icon { + name: "folder-backup-open", + view: 32.0, + body: r##"<path fill="#8d6e63" d="M28.967 12H9.442a2 2 0 0 0-1.898 1.368L4 24V10h24a2 2 0 0 0-2-2H15.124a2 2 0 0 1-1.28-.464l-1.288-1.072A2 2 0 0 0 11.276 6H4a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h22l4.805-11.212A2 2 0 0 0 28.967 12"/><path fill="#d7ccc8" d="M25.375 24.781 20 20.48V14h2v5.52l4.625 3.699z"/><path fill="#d7ccc8" d="M22 30a10 10 0 1 1 10-10 10.01 10.01 0 0 1-10 10m0-18a8 8 0 1 0 8 8 8.01 8.01 0 0 0-8-8"/>"##, +}; +pub(super) static FOLDER_BUILDKITE: Icon = Icon { + name: "folder-buildkite", + view: 32.0, + body: r##"<path fill="#4caf50" d="m13.844 7.536-1.288-1.072A2 2 0 0 0 11.276 6H4a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h24a2 2 0 0 0 2-2V10a2 2 0 0 0-2-2H15.124a2 2 0 0 1-1.28-.464"/><path fill="#c8e6c9" d="m20 24-6-2v-6l6 2zm10-2h-4v-6l6 4z"/><path fill="#a5d6a7" d="m20 24 6-2v-6l-6 2zm6 4 6-2v-6l-6 2z"/>"##, +}; +pub(super) static FOLDER_BUILDKITE_OPEN: Icon = Icon { + name: "folder-buildkite-open", + view: 32.0, + body: r##"<path fill="#4caf50" d="M28.967 12H9.442a2 2 0 0 0-1.898 1.368L4 24V10h24a2 2 0 0 0-2-2H15.124a2 2 0 0 1-1.28-.464l-1.288-1.072A2 2 0 0 0 11.276 6H4a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h22l4.805-11.212A2 2 0 0 0 28.967 12"/><path fill="#c8e6c9" d="m20 24-6-2v-6l6 2zm10-2h-4v-6l6 4z"/><path fill="#a5d6a7" d="m20 24 6-2v-6l-6 2zm6 4 6-2v-6l-6 2z"/>"##, +}; +pub(super) static FOLDER_CI: Icon = Icon { + name: "folder-ci", + view: 32.0, + body: r##"<path fill="#0288d1" d="m13.844 7.536-1.288-1.072A2 2 0 0 0 11.276 6H4a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h24a2 2 0 0 0 2-2V10a2 2 0 0 0-2-2H15.124a2 2 0 0 1-1.28-.464"/><path fill="#b3e5fc" d="M23.998 12.978v2.986l4-3.981-4-3.983v2.986A7.98 7.98 0 0 0 16 18.95v.002a7.9 7.9 0 0 0 1.239 4.24l1.46-1.455a5.86 5.86 0 0 1-.7-2.785 5.987 5.987 0 0 1 6-5.974m6.759 1.732-1.46 1.454a5.968 5.968 0 0 1-5.3 8.76v-2.985l-4 3.983 4 3.981v-2.986a7.98 7.98 0 0 0 7.999-7.964v-.001a7.87 7.87 0 0 0-1.24-4.24Z"/>"##, +}; +pub(super) static FOLDER_CIRCLECI: Icon = Icon { + name: "folder-circleci", + view: 32.0, + body: r##"<path fill="currentColor" d="m13.844 7.536-1.288-1.072A2 2 0 0 0 11.276 6H4a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h24a2 2 0 0 0 2-2V10a2 2 0 0 0-2-2H15.124a2 2 0 0 1-1.28-.464" /><path fill="#eceff1" d="M22.954 10a9 9 0 0 0-8.555 6.367.5.5 0 0 0 .486.633h3.23a.5.5 0 0 0 .442-.28 5 5 0 1 1-.001 4.557.5.5 0 0 0-.439-.277h-3.232a.5.5 0 0 0-.486.633 8.997 8.997 0 0 0 17.597-2.892A9.103 9.103 0 0 0 22.954 10" /><circle cx="23" cy="19" r="2" fill="#eceff1" />"##, +}; +pub(super) static FOLDER_CIRCLECI_OPEN: Icon = Icon { + name: "folder-circleci-open", + view: 32.0, + body: r##"<path fill="currentColor" d="M28.967 12H9.442a2 2 0 0 0-1.898 1.368L4 24V10h24a2 2 0 0 0-2-2H15.124a2 2 0 0 1-1.28-.464l-1.288-1.072A2 2 0 0 0 11.276 6H4a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h22l4.805-11.212A2 2 0 0 0 28.967 12" /><path fill="#eceff1" d="M22.954 10a9 9 0 0 0-8.555 6.367.5.5 0 0 0 .486.633h3.23a.5.5 0 0 0 .442-.28 5 5 0 1 1-.001 4.557.5.5 0 0 0-.439-.277h-3.232a.5.5 0 0 0-.486.633 8.997 8.997 0 0 0 17.597-2.892A9.103 9.103 0 0 0 22.954 10" /><circle cx="23" cy="19" r="2" fill="#eceff1" />"##, +}; +pub(super) static FOLDER_CI_OPEN: Icon = Icon { + name: "folder-ci-open", + view: 32.0, + body: r##"<path fill="#0288d1" d="M28.967 12H9.442a2 2 0 0 0-1.898 1.368L4 24V10h24a2 2 0 0 0-2-2H15.124a2 2 0 0 1-1.28-.464l-1.288-1.072A2 2 0 0 0 11.276 6H4a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h22l4.805-11.212A2 2 0 0 0 28.967 12"/><path fill="#b3e5fc" d="M23.998 12.978v2.986l4-3.981-4-3.983v2.986A7.98 7.98 0 0 0 16 18.95v.002a7.9 7.9 0 0 0 1.239 4.24l1.46-1.455a5.86 5.86 0 0 1-.7-2.785 5.987 5.987 0 0 1 6-5.974m6.759 1.732-1.46 1.454a5.968 5.968 0 0 1-5.3 8.76v-2.985l-4 3.983 4 3.981v-2.986a7.98 7.98 0 0 0 7.999-7.964v-.001a7.87 7.87 0 0 0-1.24-4.24Z"/>"##, +}; +pub(super) static FOLDER_COMPONENTS: Icon = Icon { + name: "folder-components", + view: 32.0, + body: r##"<path fill="#c0ca33" d="m13.844 7.536-1.288-1.072A2 2 0 0 0 11.276 6H4a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h24a2 2 0 0 0 2-2V10a2 2 0 0 0-2-2H15.124a2 2 0 0 1-1.28-.464"/><path fill="#f0f4c3" d="M12 20h8v8h-8zm10 0h8v8h-8zM12 10h8v8h-8zm8.343 4L26 8.343 31.657 14 26 19.657z"/>"##, +}; +pub(super) static FOLDER_COMPONENTS_OPEN: Icon = Icon { + name: "folder-components-open", + view: 32.0, + body: r##"<path fill="#c0ca33" d="M28.967 12H9.442a2 2 0 0 0-1.898 1.368L4 24V10h24a2 2 0 0 0-2-2H15.124a2 2 0 0 1-1.28-.464l-1.288-1.072A2 2 0 0 0 11.276 6H4a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h22l4.805-11.212A2 2 0 0 0 28.967 12"/><path fill="#f0f4c3" d="M12 20h8v8h-8zm10 0h8v8h-8zM12 10h8v8h-8zm8.343 4L26 8.343 31.657 14 26 19.657z"/>"##, +}; +pub(super) static FOLDER_CONFIG: Icon = Icon { + name: "folder-config", + view: 32.0, + body: r##"<path fill="#00acc1" d="m13.844 7.536-1.288-1.072A2 2 0 0 0 11.276 6H4a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h24a2 2 0 0 0 2-2V10a2 2 0 0 0-2-2H15.124a2 2 0 0 1-1.28-.464"/><path fill="#80deea" d="M23.001 24.15A3.195 3.195 0 0 1 19.762 21a3.24 3.24 0 1 1 3.239 3.15m6.875-2.277a7 7 0 0 0 .064-.874 8 8 0 0 0-.064-.9l1.951-1.467a.446.446 0 0 0 .113-.576l-1.853-3.112a.46.46 0 0 0-.564-.199l-2.302.9a6.8 6.8 0 0 0-1.565-.882l-.342-2.385A.464.464 0 0 0 24.85 12h-3.7a.464.464 0 0 0-.463.378l-.341 2.385a6.8 6.8 0 0 0-1.563.881l-2.304-.899a.46.46 0 0 0-.564.198l-1.851 3.113a.436.436 0 0 0 .112.576l1.95 1.468a8 8 0 0 0-.064.9 7 7 0 0 0 .064.873l-1.95 1.493a.436.436 0 0 0-.112.576l1.85 3.115a.47.47 0 0 0 .565.198l2.304-.91a6.4 6.4 0 0 0 1.563.892l.342 2.385a.464.464 0 0 0 .463.378h3.7a.464.464 0 0 0 .464-.378l.34-2.385a6.8 6.8 0 0 0 1.566-.891l2.302.909a.475.475 0 0 0 .566-.198l1.85-3.115a.446.446 0 0 0-.112-.576Z"/>"##, +}; +pub(super) static FOLDER_CONFIG_OPEN: Icon = Icon { + name: "folder-config-open", + view: 32.0, + body: r##"<path fill="#00acc1" d="M28.967 12H9.442a2 2 0 0 0-1.898 1.368L4 24V10h24a2 2 0 0 0-2-2H15.124a2 2 0 0 1-1.28-.464l-1.288-1.072A2 2 0 0 0 11.276 6H4a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h22l4.805-11.212A2 2 0 0 0 28.967 12"/><path fill="#80deea" d="M23.001 24.15A3.195 3.195 0 0 1 19.762 21a3.24 3.24 0 1 1 3.239 3.15m6.875-2.277a7 7 0 0 0 .064-.874 8 8 0 0 0-.064-.9l1.951-1.467a.446.446 0 0 0 .113-.576l-1.853-3.112a.46.46 0 0 0-.564-.199l-2.302.9a6.8 6.8 0 0 0-1.565-.882l-.342-2.385A.464.464 0 0 0 24.85 12h-3.7a.464.464 0 0 0-.463.378l-.341 2.385a6.8 6.8 0 0 0-1.563.881l-2.304-.899a.46.46 0 0 0-.564.198l-1.851 3.113a.436.436 0 0 0 .112.576l1.95 1.468a8 8 0 0 0-.064.9 7 7 0 0 0 .064.873l-1.95 1.493a.436.436 0 0 0-.112.576l1.85 3.115a.47.47 0 0 0 .565.198l2.304-.91a6.4 6.4 0 0 0 1.563.892l.342 2.385a.464.464 0 0 0 .463.378h3.7a.464.464 0 0 0 .464-.378l.34-2.385a6.8 6.8 0 0 0 1.566-.891l2.302.909a.475.475 0 0 0 .566-.198l1.85-3.115a.446.446 0 0 0-.112-.576Z"/>"##, +}; +pub(super) static FOLDER_CONTAINER: Icon = Icon { + name: "folder-container", + view: 32.0, + body: r##"<path fill="#0288d1" d="m13.844 7.536-1.288-1.072A2 2 0 0 0 11.276 6H4a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h24a2 2 0 0 0 2-2V10a2 2 0 0 0-2-2H15.124a2 2 0 0 1-1.28-.464"/><path fill="#b3e5fc" d="m31.532 14.153-8.085-4.048a1 1 0 0 0-.894 0l-8.085 4.048A1 1 0 0 0 14 15v10a1 1 0 0 0 .553.895l8.046 4.01a.9.9 0 0 0 .802 0l8.046-4.01A1 1 0 0 0 32 25V15a1 1 0 0 0-.468-.847M22 27.382l-6-3v-7.79l6 2.887Zm1-9.64-5.73-2.759L23 12.118l5.73 2.865Zm7 6.64-6 3v-7.903l6-2.888Z"/>"##, +}; +pub(super) static FOLDER_CONTAINER_OPEN: Icon = Icon { + name: "folder-container-open", + view: 32.0, + body: r##"<path fill="#0288d1" d="M28.967 12H9.442a2 2 0 0 0-1.898 1.368L4 24V10h24a2 2 0 0 0-2-2H15.124a2 2 0 0 1-1.28-.464l-1.288-1.072A2 2 0 0 0 11.276 6H4a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h22l4.805-11.212A2 2 0 0 0 28.967 12"/><path fill="#b3e5fc" d="m31.532 14.153-8.085-4.048a1 1 0 0 0-.894 0l-8.085 4.048A1 1 0 0 0 14 15v10a1 1 0 0 0 .553.895l8.046 4.01a.9.9 0 0 0 .802 0l8.046-4.01A1 1 0 0 0 32 25V15a1 1 0 0 0-.468-.847M22 27.382l-6-3v-7.79l6 2.887Zm1-9.64-5.73-2.759L23 12.118l5.73 2.865Zm7 6.64-6 3v-7.903l6-2.888Z"/>"##, +}; +pub(super) static FOLDER_CONTENT: Icon = Icon { + name: "folder-content", + view: 32.0, + body: r##"<path fill="#00bcd4" d="m13.844 7.536-1.288-1.072A2 2 0 0 0 11.276 6H4a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h24a2 2 0 0 0 2-2V10a2 2 0 0 0-2-2H15.124a2 2 0 0 1-1.28-.464"/><path fill="#b2ebf2" d="M22 18h6v2h-6zm0 4h6v2h-6z"/><path fill="#b2ebf2" d="M10 15v12a1 1 0 0 0 1 1h20a1 1 0 0 0 1-1V15a1 1 0 0 0-1-1H11a1 1 0 0 0-1 1m20 11H20V16h10Z"/>"##, +}; +pub(super) static FOLDER_CONTENT_OPEN: Icon = Icon { + name: "folder-content-open", + view: 32.0, + body: r##"<path fill="#00bcd4" d="M28.967 12H9.442a2 2 0 0 0-1.898 1.368L4 24V10h24a2 2 0 0 0-2-2H15.124a2 2 0 0 1-1.28-.464l-1.288-1.072A2 2 0 0 0 11.276 6H4a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h22l4.805-11.212A2 2 0 0 0 28.967 12"/><path fill="#b2ebf2" d="M22 18h6v2h-6zm0 4h6v2h-6z"/><path fill="#b2ebf2" d="M10 15v12a1 1 0 0 0 1 1h20a1 1 0 0 0 1-1V15a1 1 0 0 0-1-1H11a1 1 0 0 0-1 1m20 11H20V16h10Z"/>"##, +}; +pub(super) static FOLDER_CONTROLLER: Icon = Icon { + name: "folder-controller", + view: 32.0, + body: r##"<path fill="#ffc107" d="m13.844 7.536-1.288-1.072A2 2 0 0 0 11.276 6H4a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h24a2 2 0 0 0 2-2V10a2 2 0 0 0-2-2H15.124a2 2 0 0 1-1.28-.464"/><path fill="#fff9c4" d="M23.001 24.15A3.195 3.195 0 0 1 19.762 21a3.24 3.24 0 1 1 3.239 3.15m6.875-2.277a7 7 0 0 0 .064-.874 8 8 0 0 0-.064-.9l1.951-1.467a.446.446 0 0 0 .113-.576l-1.853-3.112a.46.46 0 0 0-.564-.199l-2.302.9a6.8 6.8 0 0 0-1.565-.882l-.342-2.385A.464.464 0 0 0 24.85 12h-3.7a.464.464 0 0 0-.463.378l-.341 2.385a6.8 6.8 0 0 0-1.563.881l-2.304-.899a.46.46 0 0 0-.564.198l-1.851 3.113a.436.436 0 0 0 .112.576l1.95 1.468a8 8 0 0 0-.064.9 7 7 0 0 0 .064.873l-1.95 1.493a.436.436 0 0 0-.112.576l1.85 3.115a.47.47 0 0 0 .565.198l2.304-.91a6.4 6.4 0 0 0 1.563.892l.342 2.385a.464.464 0 0 0 .463.378h3.7a.464.464 0 0 0 .464-.378l.34-2.385a6.8 6.8 0 0 0 1.566-.891l2.302.909a.475.475 0 0 0 .566-.198l1.85-3.115a.446.446 0 0 0-.112-.576Z"/>"##, +}; +pub(super) static FOLDER_CONTROLLER_OPEN: Icon = Icon { + name: "folder-controller-open", + view: 32.0, + body: r##"<path fill="#ffc107" d="M28.967 12H9.442a2 2 0 0 0-1.898 1.368L4 24V10h24a2 2 0 0 0-2-2H15.124a2 2 0 0 1-1.28-.464l-1.288-1.072A2 2 0 0 0 11.276 6H4a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h22l4.805-11.212A2 2 0 0 0 28.967 12"/><path fill="#fff9c4" d="M23.057 23.715a3.077 3.077 0 0 1-3.077-3.078 3.077 3.077 0 1 1 3.077 3.078m6.532-2.224a7 7 0 0 0 .062-.854 8 8 0 0 0-.062-.878l1.855-1.434a.444.444 0 0 0 .107-.562l-1.76-3.04a.43.43 0 0 0-.536-.195l-2.188.88a6.4 6.4 0 0 0-1.487-.863l-.325-2.329a.444.444 0 0 0-.44-.37h-3.516a.444.444 0 0 0-.44.37l-.324 2.33a6.4 6.4 0 0 0-1.486.86l-2.189-.878a.43.43 0 0 0-.536.193l-1.759 3.042a.433.433 0 0 0 .107.562l1.853 1.434a8 8 0 0 0-.061.88 7 7 0 0 0 .061.852l-1.853 1.458a.433.433 0 0 0-.107.563l1.759 3.043a.44.44 0 0 0 .536.193l2.19-.888a6 6 0 0 0 1.485.87l.325 2.33a.444.444 0 0 0 .44.37h3.516a.444.444 0 0 0 .44-.37l.324-2.33a6.4 6.4 0 0 0 1.487-.87l2.188.888a.445.445 0 0 0 .537-.193l1.757-3.043a.444.444 0 0 0-.105-.563Z"/>"##, +}; +pub(super) static FOLDER_CSS: Icon = Icon { + name: "folder-css", + view: 32.0, + body: r##"<defs><path id="a" fill="#d1c4e9" d="M14 20v-2h-2v8h2v-2h2v2a2 2 0 0 1-2 2h-2a2 2 0 0 1-2-2v-8a2 2 0 0 1 2-2h2a2 2 0 0 1 2 2v2Zm10 0v-2a2 2 0 0 0-2-2h-2a2 2 0 0 0-2 2v2c0 .839.357 2.34 2.746 2.966C21.438 23.15 22 23.612 22 24v2h-2v-2h-2v2a2 2 0 0 0 2 2h2a2 2 0 0 0 2-2v-2a3.345 3.345 0 0 0-2.746-2.967C20 20.703 20 20.193 20 20v-2h2v2Zm8 0v-2a2 2 0 0 0-2-2h-2a2 2 0 0 0-2 2v2c0 .839.357 2.34 2.746 2.966C29.438 23.15 30 23.612 30 24v2h-2v-2h-2v2a2 2 0 0 0 2 2h2a2 2 0 0 0 2-2v-2a3.345 3.345 0 0 0-2.746-2.967C28 20.703 28 20.193 28 20v-2h2v2Z"/></defs><path fill="#7e57c2" d="m13.844 7.536-1.288-1.072A2 2 0 0 0 11.276 6H4a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h24a2 2 0 0 0 2-2V10a2 2 0 0 0-2-2H15.124a2 2 0 0 1-1.28-.464"/><use xlink:href="#a"/><use xlink:href="#a"/>"##, +}; +pub(super) static FOLDER_CSS_OPEN: Icon = Icon { + name: "folder-css-open", + view: 32.0, + body: r##"<defs><path id="a" fill="#d1c4e9" d="M14 20v-2h-2v8h2v-2h2v2a2 2 0 0 1-2 2h-2a2 2 0 0 1-2-2v-8a2 2 0 0 1 2-2h2a2 2 0 0 1 2 2v2Zm10 0v-2a2 2 0 0 0-2-2h-2a2 2 0 0 0-2 2v2c0 .839.357 2.34 2.746 2.966C21.437 23.15 22 23.612 22 24v2h-2v-2h-2v2a2 2 0 0 0 2 2h2a2 2 0 0 0 2-2v-2a3.345 3.345 0 0 0-2.746-2.967C20 20.703 20 20.193 20 20v-2h2v2Zm8 0v-2a2 2 0 0 0-2-2h-2a2 2 0 0 0-2 2v2c0 .839.357 2.34 2.746 2.966C29.437 23.15 30 23.612 30 24v2h-2v-2h-2v2a2 2 0 0 0 2 2h2a2 2 0 0 0 2-2v-2a3.345 3.345 0 0 0-2.746-2.967C28 20.703 28 20.193 28 20v-2h2v2Z"/></defs><path fill="#7e57c2" d="M28.967 12H9.442a2 2 0 0 0-1.898 1.368L4 24V10h24a2 2 0 0 0-2-2H15.124a2 2 0 0 1-1.28-.464l-1.288-1.072A2 2 0 0 0 11.276 6H4a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h22l4.805-11.212A2 2 0 0 0 28.967 12"/><use xlink:href="#a"/><use xlink:href="#a"/>"##, +}; +pub(super) static FOLDER_CURSOR: Icon = Icon { + name: "folder-cursor", + view: 32.0, + body: r##"<path d="M13.844,7.536,12.556,6.464A2,2,0,0,0,11.276,6H4A2,2,0,0,0,2,8V24a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2H15.124a2,2,0,0,1-1.28-.464" style="fill:#e0e0e0"/><path d="M22,28l8-14V24Z" style="fill:#424242;fill-rule:evenodd"/><path d="M14,14l8-4.675L30,14Z" style="fill:#424242;fill-rule:evenodd"/><path d="M14,14l8,4V28l-8-4Z" style="fill:#424242;fill-rule:evenodd"/>"##, +}; +pub(super) static FOLDER_CURSOR_OPEN: Icon = Icon { + name: "folder-cursor-open", + view: 32.0, + body: r##"<path d="M28.967,12H9.442a2,2,0,0,0-1.898,1.368L4,24V10H28a2,2,0,0,0-2-2H15.124a2,2,0,0,1-1.28-.464L12.556,6.464A2,2,0,0,0,11.276,6H4A2,2,0,0,0,2,8V24a2,2,0,0,0,2,2H26l4.805-11.212A2,2,0,0,0,28.967,12" style="fill:#e0e0e0"/><path d="M22,28l8-14V24Z" style="fill:#424242;fill-rule:evenodd"/><path d="M14,14l8-4.675L30,14Z" style="fill:#424242;fill-rule:evenodd"/><path d="M14,14l8,4V28l-8-4Z" style="fill:#424242;fill-rule:evenodd"/>"##, +}; +pub(super) static FOLDER_CYPRESS: Icon = Icon { + name: "folder-cypress", + view: 32.0, + body: r##"<path fill="#009688" d="m13.844 7.536-1.288-1.072A2 2 0 0 0 11.276 6H4a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h24a2 2 0 0 0 2-2V10a2 2 0 0 0-2-2H15.124a2 2 0 0 1-1.28-.464"/><path fill="#b2dfdb" d="M22.999 10A8.994 8.994 0 0 0 14 18.99V19a8.994 8.994 0 0 0 8.988 9H23a8.994 8.994 0 0 0 9-8.988V19a9.017 9.017 0 0 0-9.001-9m-4.222 10.931a1.41 1.41 0 0 0 1.242.557 1.9 1.9 0 0 0 .755-.133 6.4 6.4 0 0 0 .817-.425l.916 1.31a3.9 3.9 0 0 1-2.585.916 4.05 4.05 0 0 1-2.028-.49 3.3 3.3 0 0 1-1.31-1.44 5.04 5.04 0 0 1-.457-2.194 5.2 5.2 0 0 1 .456-2.193 3.46 3.46 0 0 1 1.312-1.503 3.6 3.6 0 0 1 1.996-.525 3.7 3.7 0 0 1 1.407.23 4.2 4.2 0 0 1 1.21.72l-.915 1.243a3.6 3.6 0 0 0-.754-.427 2.1 2.1 0 0 0-.785-.131c-1.112 0-1.669.852-1.669 2.585a3.24 3.24 0 0 0 .393 1.899Zm9 2.03a4.7 4.7 0 0 1-1.505 2.323 4.9 4.9 0 0 1-2.75.95l-.228-1.537a3.74 3.74 0 0 0 1.67-.526 4 4 0 0 0 .391-.391l-2.716-8.707h2.257l1.572 6.513 1.67-6.513h2.193Z"/>"##, +}; +pub(super) static FOLDER_CYPRESS_OPEN: Icon = Icon { + name: "folder-cypress-open", + view: 32.0, + body: r##"<path fill="#009688" d="M28.967 12H9.442a2 2 0 0 0-1.898 1.368L4 24V10h24a2 2 0 0 0-2-2H15.124a2 2 0 0 1-1.28-.464l-1.288-1.072A2 2 0 0 0 11.276 6H4a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h22l4.805-11.212A2 2 0 0 0 28.967 12"/><path fill="#b2dfdb" d="M22.999 10A8.994 8.994 0 0 0 14 18.99V19a8.994 8.994 0 0 0 8.988 9H23a8.994 8.994 0 0 0 9-8.988V19a9.017 9.017 0 0 0-9.001-9m-4.222 10.931a1.41 1.41 0 0 0 1.242.557 1.9 1.9 0 0 0 .755-.133 6.4 6.4 0 0 0 .817-.425l.916 1.31a3.9 3.9 0 0 1-2.585.916 4.05 4.05 0 0 1-2.028-.49 3.3 3.3 0 0 1-1.31-1.44 5.04 5.04 0 0 1-.457-2.194 5.2 5.2 0 0 1 .456-2.193 3.46 3.46 0 0 1 1.312-1.503 3.6 3.6 0 0 1 1.996-.525 3.7 3.7 0 0 1 1.407.23 4.2 4.2 0 0 1 1.21.72l-.915 1.243a3.6 3.6 0 0 0-.754-.427 2.1 2.1 0 0 0-.785-.131c-1.112 0-1.669.852-1.669 2.585a3.24 3.24 0 0 0 .393 1.899Zm9 2.03a4.7 4.7 0 0 1-1.505 2.323 4.9 4.9 0 0 1-2.75.95l-.228-1.537a3.74 3.74 0 0 0 1.67-.526 4 4 0 0 0 .391-.391l-2.716-8.707h2.257l1.572 6.513 1.67-6.513h2.193Z"/>"##, +}; +pub(super) static FOLDER_DATABASE: Icon = Icon { + name: "folder-database", + view: 32.0, + body: r##"<path fill="#ffca28" d="m13.844 7.536-1.288-1.072A2 2 0 0 0 11.276 6H4a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h24a2 2 0 0 0 2-2V10a2 2 0 0 0-2-2H15.124a2 2 0 0 1-1.28-.464"/><ellipse cx="24" cy="14" fill="#ffecb3" rx="8" ry="4"/><path fill="#ffecb3" d="M24 26c-4.418 0-8-1.79-8-4v4c0 2.21 3.582 4 8 4s8-1.79 8-4v-4c0 2.21-3.582 4-8 4"/><path fill="#ffecb3" d="M24 20c-4.418 0-8-1.79-8-4v4c0 2.21 3.582 4 8 4s8-1.79 8-4v-4c0 2.21-3.582 4-8 4"/>"##, +}; +pub(super) static FOLDER_DATABASE_OPEN: Icon = Icon { + name: "folder-database-open", + view: 32.0, + body: r##"<path fill="#ffca28" d="M28.967 12H9.442a2 2 0 0 0-1.898 1.368L4 24V10h24a2 2 0 0 0-2-2H15.124a2 2 0 0 1-1.28-.464l-1.288-1.072A2 2 0 0 0 11.276 6H4a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h22l4.805-11.212A2 2 0 0 0 28.967 12"/><ellipse cx="24" cy="14" fill="#ffecb3" rx="8" ry="4"/><path fill="#ffecb3" d="M24 26c-4.418 0-8-1.79-8-4v4c0 2.21 3.582 4 8 4s8-1.79 8-4v-4c0 2.21-3.582 4-8 4"/><path fill="#ffecb3" d="M24 20c-4.418 0-8-1.79-8-4v4c0 2.21 3.582 4 8 4s8-1.79 8-4v-4c0 2.21-3.582 4-8 4"/>"##, +}; +pub(super) static FOLDER_DESKTOP: Icon = Icon { + name: "folder-desktop", + view: 32.0, + body: r##"<path fill="#039be5" d="m13.844 7.536-1.288-1.072A2 2 0 0 0 11.276 6H4a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h24a2 2 0 0 0 2-2V10a2 2 0 0 0-2-2H15.124a2 2 0 0 1-1.28-.464"/><path fill="#b3e5fc" d="M30 12H14a2 2 0 0 0-2 2v10a2 2 0 0 0 2 2h6v2h-2v2h8v-2h-2v-2h6a2 2 0 0 0 2-2V14a2 2 0 0 0-2-2m0 12H14V14h16Z"/>"##, +}; +pub(super) static FOLDER_DESKTOP_OPEN: Icon = Icon { + name: "folder-desktop-open", + view: 32.0, + body: r##"<path fill="#039be5" d="M28.967 12H9.442a2 2 0 0 0-1.898 1.368L4 24V10h24a2 2 0 0 0-2-2H15.124a2 2 0 0 1-1.28-.464l-1.288-1.072A2 2 0 0 0 11.276 6H4a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h22l4.805-11.212A2 2 0 0 0 28.967 12"/><path fill="#b3e5fc" d="M30 12H14a2 2 0 0 0-2 2v10a2 2 0 0 0 2 2h6v2h-2v2h8v-2h-2v-2h6a2 2 0 0 0 2-2V14a2 2 0 0 0-2-2m0 12H14V14h16Z"/>"##, +}; +pub(super) static FOLDER_DIST: Icon = Icon { + name: "folder-dist", + view: 32.0, + body: r##"<path fill="#e57373" d="m13.844 7.536-1.288-1.072A2 2 0 0 0 11.276 6H4a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h24a2 2 0 0 0 2-2V10a2 2 0 0 0-2-2H15.124a2 2 0 0 1-1.28-.464"/><path fill="#ffcdd2" d="M30 14h-4v-2l-2-2h-4l-2 2v2h-4a2 2 0 0 0-2 2v10a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2V16a2 2 0 0 0-2-2m-10 0v-2h4v2Z"/>"##, +}; +pub(super) static FOLDER_DIST_OPEN: Icon = Icon { + name: "folder-dist-open", + view: 32.0, + body: r##"<path fill="#e57373" d="M28.967 12H9.442a2 2 0 0 0-1.898 1.368L4 24V10h24a2 2 0 0 0-2-2H15.124a2 2 0 0 1-1.28-.464l-1.288-1.072A2 2 0 0 0 11.276 6H4a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h22l4.805-11.212A2 2 0 0 0 28.967 12"/><path fill="#ffcdd2" d="M30 14h-4v-2l-2-2h-4l-2 2v2h-4a2 2 0 0 0-2 2v10a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2V16a2 2 0 0 0-2-2m-10 0v-2h4v2Z"/>"##, +}; +pub(super) static FOLDER_DOCKER: Icon = Icon { + name: "folder-docker", + view: 32.0, + body: r##"<path fill="#039be5" d="m13.844 7.536-1.288-1.072A2 2 0 0 0 11.276 6H4a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h24a2 2 0 0 0 2-2V10a2 2 0 0 0-2-2H15.124a2 2 0 0 1-1.28-.464"/><path fill="#b3e5fc" d="M14 16h4v4h-4zm-6 0h4v4H8zm12 0h4v4h-4zm0-6h4v4h-4z"/><path fill="#b3e5fc" d="M31.667 19.81a3.65 3.65 0 0 0-3.067-.377 4.6 4.6 0 0 0-1.667-2.945l-.333-.302-.267.378a4.44 4.44 0 0 0-.667 2.793 5 5 0 0 0 .233 1.101l-.62 1.283A5.1 5.1 0 0 1 23.6 22H6a15.3 15.3 0 0 0 .865 4.757l.267.528v.076a8.22 8.22 0 0 0 7.6 4.38c6 0 10.934-2.945 13.268-9.288a3.605 3.605 0 0 0 3.8-2.039l.2-.377ZM12 28a2 2 0 1 1 2-2 2 2 0 0 1-2 2"/>"##, +}; +pub(super) static FOLDER_DOCKER_OPEN: Icon = Icon { + name: "folder-docker-open", + view: 32.0, + body: r##"<path fill="#039be5" d="M28.967 12H9.442a2 2 0 0 0-1.898 1.368L4 24V10h24a2 2 0 0 0-2-2H15.124a2 2 0 0 1-1.28-.464l-1.288-1.072A2 2 0 0 0 11.276 6H4a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h22l4.805-11.212A2 2 0 0 0 28.967 12"/><path fill="#b3e5fc" d="M14 16h4v4h-4zm-6 0h4v4H8zm12 0h4v4h-4zm0-6h4v4h-4z"/><path fill="#b3e5fc" d="M31.667 19.81a3.65 3.65 0 0 0-3.067-.377 4.6 4.6 0 0 0-1.667-2.945l-.333-.302-.267.378a4.44 4.44 0 0 0-.667 2.793 5 5 0 0 0 .233 1.101l-.62 1.283A5.1 5.1 0 0 1 23.6 22H6a15.3 15.3 0 0 0 .865 4.757l.267.528v.076a8.22 8.22 0 0 0 7.6 4.38c6 0 10.934-2.945 13.268-9.288a3.605 3.605 0 0 0 3.8-2.039l.2-.377ZM12 28a2 2 0 1 1 2-2 2 2 0 0 1-2 2"/>"##, +}; +pub(super) static FOLDER_DOCS: Icon = Icon { + name: "folder-docs", + view: 32.0, + body: r##"<path fill="#0277bd" d="m13.844 7.536-1.288-1.072A2 2 0 0 0 11.276 6H4a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h24a2 2 0 0 0 2-2V10a2 2 0 0 0-2-2H15.124a2 2 0 0 1-1.28-.464"/><path fill="#b3e5fc" d="M24 10h-7a1 1 0 0 0-1 1v16a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1V16Zm0 16h-6v-2h6Zm4-4H18v-2h10Zm-4.828-5.172V12L28 16.828Z"/>"##, +}; +pub(super) static FOLDER_DOCS_OPEN: Icon = Icon { + name: "folder-docs-open", + view: 32.0, + body: r##"<path fill="#0277bd" d="M28.967 12H9.442a2 2 0 0 0-1.898 1.368L4 24V10h24a2 2 0 0 0-2-2H15.124a2 2 0 0 1-1.28-.464l-1.288-1.072A2 2 0 0 0 11.276 6H4a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h22l4.805-11.212A2 2 0 0 0 28.967 12"/><path fill="#b3e5fc" d="M24 10h-7a1 1 0 0 0-1 1v16a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1V16Zm0 16h-6v-2h6Zm4-4H18v-2h10Zm-4.828-5.172V12L28 16.828Z"/>"##, +}; +pub(super) static FOLDER_DRIZZLE: Icon = Icon { + name: "folder-drizzle", + view: 32.0, + body: r##"<path fill="#4caf50" d="m13.844 7.536-1.288-1.072A2 2 0 0 0 11.276 6H4a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h24a2 2 0 0 0 2-2V10a2 2 0 0 0-2-2H15.124a2 2 0 0 1-1.28-.464"/><path fill="#c8e6c9" d="m10.752 27.217 3.127-5.764a1.51 1.51 0 0 0-.573-2.034 1.45 1.45 0 0 0-1.995.586l-3.127 5.763a1.51 1.51 0 0 0 .573 2.034 1.44 1.44 0 0 0 .71.187 1.46 1.46 0 0 0 1.285-.772m10.305 0 3.127-5.764a1.51 1.51 0 0 0-.574-2.034 1.45 1.45 0 0 0-1.995.586l-3.127 5.763a1.51 1.51 0 0 0 .574 2.034 1.44 1.44 0 0 0 .709.187 1.46 1.46 0 0 0 1.286-.772m-2.896-5.21 3.326-5.76a1.507 1.507 0 0 0-.518-2.04 1.447 1.447 0 0 0-2.002.527l-3.326 5.76a1.51 1.51 0 0 0 .519 2.041 1.43 1.43 0 0 0 .74.206 1.46 1.46 0 0 0 1.261-.734m10.31 0 3.327-5.76a1.507 1.507 0 0 0-.518-2.04 1.447 1.447 0 0 0-2.002.527l-3.326 5.76a1.51 1.51 0 0 0 .518 2.041 1.43 1.43 0 0 0 .74.206 1.46 1.46 0 0 0 1.262-.734Z"/>"##, +}; +pub(super) static FOLDER_DRIZZLE_OPEN: Icon = Icon { + name: "folder-drizzle-open", + view: 32.0, + body: r##"<path fill="#4caf50" d="M28.967 12H9.442a2 2 0 0 0-1.898 1.368L4 24V10h24a2 2 0 0 0-2-2H15.124a2 2 0 0 1-1.28-.464l-1.288-1.072A2 2 0 0 0 11.276 6H4a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h22l4.805-11.212A2 2 0 0 0 28.967 12"/><path fill="#c8e6c9" d="m10.752 27.217 3.127-5.764a1.51 1.51 0 0 0-.573-2.034 1.45 1.45 0 0 0-1.995.586l-3.127 5.763a1.51 1.51 0 0 0 .573 2.034 1.44 1.44 0 0 0 .71.187 1.46 1.46 0 0 0 1.285-.772m10.305 0 3.127-5.764a1.51 1.51 0 0 0-.574-2.034 1.45 1.45 0 0 0-1.995.586l-3.127 5.763a1.51 1.51 0 0 0 .574 2.034 1.44 1.44 0 0 0 .709.187 1.46 1.46 0 0 0 1.286-.772m-2.896-5.21 3.326-5.76a1.507 1.507 0 0 0-.518-2.04 1.447 1.447 0 0 0-2.002.527l-3.326 5.76a1.51 1.51 0 0 0 .519 2.041 1.43 1.43 0 0 0 .74.206 1.46 1.46 0 0 0 1.261-.734m10.31 0 3.327-5.76a1.507 1.507 0 0 0-.518-2.04 1.447 1.447 0 0 0-2.002.527l-3.326 5.76a1.51 1.51 0 0 0 .518 2.041 1.43 1.43 0 0 0 .74.206 1.46 1.46 0 0 0 1.262-.734Z"/>"##, +}; +pub(super) static FOLDER_ENVIRONMENT: Icon = Icon { + name: "folder-environment", + view: 32.0, + body: r##"<path fill="#66bb6a" d="m13.844 7.536-1.288-1.072A2 2 0 0 0 11.276 6H4a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h24a2 2 0 0 0 2-2V10a2 2 0 0 0-2-2H15.124a2 2 0 0 1-1.28-.464"/><path fill="#c8e6c9" d="m23 16-3.749 5 2.85 3.798L20.5 26l-4.499-6L10 28h22Z"/>"##, +}; +pub(super) static FOLDER_ENVIRONMENT_OPEN: Icon = Icon { + name: "folder-environment-open", + view: 32.0, + body: r##"<path fill="#66bb6a" d="M28.967 12H9.442a2 2 0 0 0-1.898 1.368L4 24V10h24a2 2 0 0 0-2-2H15.124a2 2 0 0 1-1.28-.464l-1.288-1.072A2 2 0 0 0 11.276 6H4a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h22l4.805-11.212A2 2 0 0 0 28.967 12"/><path fill="#c8e6c9" d="m23 16-3.749 5 2.85 3.798L20.5 26l-4.499-6L10 28h22Z"/>"##, +}; +pub(super) static FOLDER_EXAMPLES: Icon = Icon { + name: "folder-examples", + view: 32.0, + body: r##"<path fill="#009688" d="m13.844 7.536-1.288-1.072A2 2 0 0 0 11.276 6H4a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h24a2 2 0 0 0 2-2V10a2 2 0 0 0-2-2H15.124a2 2 0 0 1-1.28-.464"/><path fill="#b2dfdb" d="M16 14v12a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V14a2 2 0 0 0-2-2H18a2 2 0 0 0-2 2m2 0h2a2 2 0 0 1-2 2Zm0 4a4 4 0 0 0 4-4h2a6.005 6.005 0 0 1-6 6Zm0 8 4-4 1.6 1.6L26 20l4 6Z"/>"##, +}; +pub(super) static FOLDER_EXAMPLES_OPEN: Icon = Icon { + name: "folder-examples-open", + view: 32.0, + body: r##"<path fill="#009688" d="M28.967 12H9.442a2 2 0 0 0-1.898 1.368L4 24V10h24a2 2 0 0 0-2-2H15.124a2 2 0 0 1-1.28-.464l-1.288-1.072A2 2 0 0 0 11.276 6H4a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h22l4.805-11.212A2 2 0 0 0 28.967 12"/><path fill="#b2dfdb" d="M16 14v12a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V14a2 2 0 0 0-2-2H18a2 2 0 0 0-2 2m2 0h2a2 2 0 0 1-2 2Zm0 4a4 4 0 0 0 4-4h2a6.005 6.005 0 0 1-6 6Zm0 8 4-4 1.6 1.6L26 20l4 6Z"/>"##, +}; +pub(super) static FOLDER_FIREBASE: Icon = Icon { + name: "folder-firebase", + view: 32.0, + body: r##"<g fill-rule="evenodd" stroke-linejoin="round" stroke-miterlimit="2" clip-rule="evenodd"><path fill="#ff9100" fill-rule="nonzero" d="m13.844 7.536-1.288-1.072A2 2 0 0 0 11.276 6H4c-1.097 0-2 .903-2 2v16c0 1.097.903 2 2 2h24c1.097 0 2-.903 2-2V10c0-1.097-.903-2-2-2H15.124c-.468 0-.921-.164-1.28-.464"/><path fill="#ffe0b2" d="M24 28.014s-4.584.213-7-4.014c-.66-1.156-1.006-2.805-1-4 .012-2.264.962-3.881 1.038-4 .117-.181 2.954-.867 4.962 0s3.979 3.215 4 6-2.275 4.565-2.691 4.881.691 1.133.691 1.133M22 25.5c2.051-1.646 1.875-2.063 2-3.5s-1.007-3.071-2-4-2.934-.65-3.5-.5c-2.418 5.405 3.5 8 3.5 8"/><path fill="#ffe0b2" d="m24 28.014 2.527-.941s-1.988-1.265-2.909-2.168C21.381 22.71 20.021 20.085 20 16s4-8 4-8 8.063 6.276 8 12c-.644 8.183-8 8.014-8 8.014m4-3.023c1.044-1.135 1.95-2.042 2-4.991.075-4.381-6-9.5-6-9.5s-1.856 2.393-2 5.5c-.338 7.273 6 8.991 6 8.991"/><path fill="#ffe0b2" d="M22.34 25.64s3.453-.086 5.66-.649c3.451-.879-1.022 2.191-1.022 2.191L24 28.015l-1.313-.536z"/></g>"##, +}; +pub(super) static FOLDER_FIREBASE_OPEN: Icon = Icon { + name: "folder-firebase-open", + view: 32.0, + body: r##"<path fill="#ff9100" d="M28.967 12H9.442a2 2 0 0 0-1.898 1.368L4 24V10h24a2 2 0 0 0-2-2H15.124a2 2 0 0 1-1.28-.464l-1.288-1.072A2 2 0 0 0 11.276 6H4a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h22l4.805-11.212A2 2 0 0 0 28.967 12"/><path fill="#ffe0b2" d="M24 28.014s-4.584.213-7-4.014c-.66-1.156-1.006-2.805-1-4 .012-2.264.962-3.881 1.038-4 .117-.181 2.954-.867 4.962 0s3.979 3.215 4 6-2.275 4.565-2.691 4.881.691 1.133.691 1.133M22 25.5c2.051-1.646 1.875-2.063 2-3.5s-1.007-3.071-2-4-2.934-.65-3.5-.5c-2.418 5.405 3.5 8 3.5 8"/><path fill="#ffe0b2" d="m24 28.014 2.527-.941s-1.988-1.265-2.909-2.168C21.381 22.71 20.021 20.085 20 16s4-8 4-8 8.063 6.276 8 12c-.644 8.183-8 8.014-8 8.014m4-3.023c1.044-1.135 1.95-2.042 2-4.991.075-4.381-6-9.5-6-9.5s-1.856 2.393-2 5.5c-.338 7.273 6 8.991 6 8.991"/><path fill="#ffe0b2" d="M22.34 25.64s3.453-.086 5.66-.649c3.451-.879-1.022 2.191-1.022 2.191L24 28.015l-1.313-.536z"/>"##, +}; +pub(super) static FOLDER_FLUTTER: Icon = Icon { + name: "folder-flutter", + view: 32.0, + body: r##"<path fill="#03a9f4" d="m13.8 7.5-1.2-1a2 2 0 0 0-1.3-.5H4a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h24a2 2 0 0 0 2-2V10a2 2 0 0 0-2-2H15.1a2 2 0 0 1-1.3-.5"/><path fill="#b3e5fc" d="m20 10-8 8 4 4 12-12zm4 8-6 6 6 6h8l-6-6 6-6z"/>"##, +}; +pub(super) static FOLDER_FLUTTER_OPEN: Icon = Icon { + name: "folder-flutter-open", + view: 32.0, + body: r##"<path fill="#03a9f4" d="M29 12H9.4a2 2 0 0 0-1.9 1.4L4 24V10h24a2 2 0 0 0-2-2H15.1a2 2 0 0 1-1.3-.5l-1.2-1a2 2 0 0 0-1.3-.5H4a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h22l4.8-11.2A2 2 0 0 0 29 12"/><path fill="#b3e5fc" d="m20 10-8 8 4 4 12-12zm4 8-6 6 6 6h8l-6-6 6-6z"/>"##, +}; +pub(super) static FOLDER_FONT: Icon = Icon { + name: "folder-font", + view: 32.0, + body: r##"<path fill="#ff5252" d="m13.844 7.536-1.288-1.072A2 2 0 0 0 11.276 6H4a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h24a2 2 0 0 0 2-2V10a2 2 0 0 0-2-2H15.124a2 2 0 0 1-1.28-.464"/><path fill="#ffcdd2" d="M24.077 12h-2.154L16 28h2.423L20 24h6l1.577 4H30Zm-3.64 10L23 14.764 25.552 22Z"/>"##, +}; +pub(super) static FOLDER_FONT_OPEN: Icon = Icon { + name: "folder-font-open", + view: 32.0, + body: r##"<path fill="#ff5252" d="M28.967 12H9.442a2 2 0 0 0-1.898 1.368L4 24V10h24a2 2 0 0 0-2-2H15.124a2 2 0 0 1-1.28-.464l-1.288-1.072A2 2 0 0 0 11.276 6H4a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h22l4.805-11.212A2 2 0 0 0 28.967 12"/><path fill="#ffcdd2" d="M24.077 12h-2.154L16 28h2.423L20 24h6l1.577 4H30Zm-3.64 10L23 14.764 25.552 22Z"/>"##, +}; +pub(super) static FOLDER_FUNCTIONS: Icon = Icon { + name: "folder-functions", + view: 32.0, + body: r##"<path fill="#0288d1" d="m13.844 7.536-1.288-1.072A2 2 0 0 0 11.276 6H4a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h24a2 2 0 0 0 2-2V10a2 2 0 0 0-2-2H15.124a2 2 0 0 1-1.28-.464"/><path fill="#b3e5fc" d="M24 16h-2.982l.14-1.676.002-.01a1.945 1.945 0 0 1 3.848-.485l1.475-1.687a3.9 3.9 0 0 0-3.01-2.126 4.143 4.143 0 0 0-4.263 4.105L19.048 16H16v2h2.87l-.529 5.874a2.05 2.05 0 0 1-1.348 1.776l-.026.009a1.92 1.92 0 0 1-2.451-1.465l-1.477 1.687a3.91 3.91 0 0 0 2.99 2.1 4.13 4.13 0 0 0 4.274-4.08L20.839 18H24Zm8 4.929-1.414-1.414-2.829 2.828-2.828-2.828-1.414 1.414 2.828 2.828-2.828 2.829L24.929 28l2.828-2.828L30.586 28 32 26.586l-2.828-2.829z"/>"##, +}; +pub(super) static FOLDER_FUNCTIONS_OPEN: Icon = Icon { + name: "folder-functions-open", + view: 32.0, + body: r##"<path fill="#0288d1" d="M28.967 12H9.442a2 2 0 0 0-1.898 1.368L4 24V10h24a2 2 0 0 0-2-2H15.124a2 2 0 0 1-1.28-.464l-1.288-1.072A2 2 0 0 0 11.276 6H4a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h22l4.805-11.212A2 2 0 0 0 28.967 12"/><path fill="#b3e5fc" d="M24 16h-2.982l.14-1.676.002-.01a1.945 1.945 0 0 1 3.848-.485l1.475-1.687a3.9 3.9 0 0 0-3.01-2.126 4.143 4.143 0 0 0-4.263 4.105L19.048 16H16v2h2.87l-.529 5.874a2.05 2.05 0 0 1-1.348 1.776l-.026.009a1.92 1.92 0 0 1-2.451-1.465l-1.477 1.687a3.91 3.91 0 0 0 2.99 2.1 4.13 4.13 0 0 0 4.274-4.08L20.839 18H24Zm8 4.929-1.414-1.414-2.829 2.828-2.828-2.828-1.414 1.414 2.828 2.828-2.828 2.829L24.929 28l2.828-2.828L30.586 28 32 26.586l-2.828-2.829z"/>"##, +}; +pub(super) static FOLDER_GH_WORKFLOWS: Icon = Icon { + name: "folder-gh-workflows", + view: 32.0, + body: r##"<path fill="currentColor" d="m13.844 7.536-1.288-1.072A2 2 0 0 0 11.276 6H4a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h24a2 2 0 0 0 2-2V10a2 2 0 0 0-2-2H15.124a2 2 0 0 1-1.28-.464" /><path fill="#eceff1" d="M24 22v2h-2a2 2 0 0 1-2-2v-4h2v-6h-6v6h2v4a4.004 4.004 0 0 0 4 4h2v2h6v-6Zm-6-6v-2h2v2Zm10 10h-2v-2h2Z" />"##, +}; +pub(super) static FOLDER_GH_WORKFLOWS_OPEN: Icon = Icon { + name: "folder-gh-workflows-open", + view: 32.0, + body: r##"<path fill="currentColor" d="M28.967 12H9.442a2 2 0 0 0-1.898 1.368L4 24V10h24a2 2 0 0 0-2-2H15.124a2 2 0 0 1-1.28-.464l-1.288-1.072A2 2 0 0 0 11.276 6H4a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h22l4.805-11.212A2 2 0 0 0 28.967 12" /><path fill="#eceff1" d="M24 22v2h-2a2 2 0 0 1-2-2v-4h2v-6h-6v6h2v4a4.004 4.004 0 0 0 4 4h2v2h6v-6Zm-6-6v-2h2v2Zm10 10h-2v-2h2Z" />"##, +}; +pub(super) static FOLDER_GIT: Icon = Icon { + name: "folder-git", + view: 32.0, + body: r##"<path fill="#ff7043" d="m13.844 7.536-1.288-1.072A2 2 0 0 0 11.276 6H4a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h24a2 2 0 0 0 2-2V10a2 2 0 0 0-2-2H15.124a2 2 0 0 1-1.28-.464"/><path fill="#ffccbc" d="m12.593 18.589 5.784-5.794 1.692 1.7a1.98 1.98 0 0 0 .93 2.233v5.544a1.99 1.99 0 0 0-1 1.731 2.002 2.002 0 0 0 4.003 0A1.99 1.99 0 0 0 23 22.272v-4.864l2.071 2.092a1.2 1.2 0 0 0-.07.5 2.002 2.002 0 1 0 2.002-2.002 1.2 1.2 0 0 0-.5.07l-2.573-2.571a1.98 1.98 0 0 0-1.15-2.342 2.1 2.1 0 0 0-1.281-.09l-1.702-1.692.791-.78a1.975 1.975 0 0 1 2.822 0l7.996 7.996a1.975 1.975 0 0 1 0 2.822l-7.996 7.996a1.975 1.975 0 0 1-2.822 0l-7.996-7.996a1.975 1.975 0 0 1 0-2.822Z"/>"##, +}; +pub(super) static FOLDER_GITHUB: Icon = Icon { + name: "folder-github", + view: 32.0, + body: r##"<path fill="currentColor" d="m13.844 7.536-1.288-1.072A2 2 0 0 0 11.276 6H4a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h24a2 2 0 0 0 2-2V10a2 2 0 0 0-2-2H15.124a2 2 0 0 1-1.28-.464" /><path fill="#eceff1" d="M23 10a9.03 9.03 0 0 0-9 9.063 9.08 9.08 0 0 0 6.157 8.609c.45.072.593-.21.593-.453v-1.532c-2.493.544-3.024-1.214-3.024-1.214a2.42 2.42 0 0 0-.998-1.333c-.82-.561.062-.544.062-.544a1.9 1.9 0 0 1 1.377.933 1.925 1.925 0 0 0 2.62.754 1.96 1.96 0 0 1 .566-1.215c-1.998-.227-4.094-1.007-4.094-4.459a3.52 3.52 0 0 1 .927-2.456 3.26 3.26 0 0 1 .09-2.392s.754-.245 2.474.924a8.6 8.6 0 0 1 4.5 0c1.718-1.169 2.476-.924 2.476-.924a3.26 3.26 0 0 1 .088 2.392 3.52 3.52 0 0 1 .927 2.456c0 3.462-2.105 4.223-4.112 4.45a2.17 2.17 0 0 1 .622 1.676v2.484c0 .244.143.533.602.453A9.08 9.08 0 0 0 23 10" />"##, +}; +pub(super) static FOLDER_GITHUB_OPEN: Icon = Icon { + name: "folder-github-open", + view: 32.0, + body: r##"<path fill="currentColor" d="M28.967 12H9.442a2 2 0 0 0-1.898 1.368L4 24V10h24a2 2 0 0 0-2-2H15.124a2 2 0 0 1-1.28-.464l-1.288-1.072A2 2 0 0 0 11.276 6H4a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h22l4.805-11.212A2 2 0 0 0 28.967 12" /><path fill="#eceff1" d="M23 10a9.03 9.03 0 0 0-9 9.063 9.08 9.08 0 0 0 6.157 8.609c.45.072.593-.21.593-.453v-1.532c-2.493.544-3.024-1.214-3.024-1.214a2.42 2.42 0 0 0-.998-1.333c-.82-.561.062-.544.062-.544a1.9 1.9 0 0 1 1.377.933 1.925 1.925 0 0 0 2.62.754 1.96 1.96 0 0 1 .566-1.215c-1.998-.227-4.094-1.007-4.094-4.459a3.52 3.52 0 0 1 .927-2.456 3.26 3.26 0 0 1 .09-2.392s.754-.245 2.474.924a8.6 8.6 0 0 1 4.5 0c1.718-1.169 2.476-.924 2.476-.924a3.26 3.26 0 0 1 .088 2.392 3.52 3.52 0 0 1 .927 2.456c0 3.462-2.105 4.223-4.112 4.45a2.17 2.17 0 0 1 .622 1.676v2.484c0 .244.143.533.602.453A9.08 9.08 0 0 0 23 10" />"##, +}; +pub(super) static FOLDER_GITLAB: Icon = Icon { + name: "folder-gitlab", + view: 32.0, + body: r##"<path fill="#757575" d="m13.844 7.536-1.288-1.072A2 2 0 0 0 11.276 6H4a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h24a2 2 0 0 0 2-2V10a2 2 0 0 0-2-2H15.124a2 2 0 0 1-1.28-.464"/><g data-mit-no-recolor="true"><path fill="#e53935" d="m31.35 17.703-.022-.063-2.339-6.097a.6.6 0 0 0-.24-.291.617.617 0 0 0-.928.353l-1.577 4.831h-6.39l-1.58-4.83a.62.62 0 0 0-.926-.354.6.6 0 0 0-.24.29l-2.337 6.1-.024.06a4.34 4.34 0 0 0 1.44 5.017l.009.006.02.015 3.556 2.667 1.764 1.333 1.072.81a.724.724 0 0 0 .873 0l1.072-.811 1.764-1.334 3.583-2.68.01-.008a4.34 4.34 0 0 0 1.44-5.014"/><path fill="#ef6c00" d="m31.35 17.703-.022-.063a7.9 7.9 0 0 0-3.143 1.413l-5.133 3.883 3.268 2.47 3.581-2.68.011-.009a4.34 4.34 0 0 0 1.44-5.014Z"/><path fill="#f9a825" d="m19.772 25.405 1.764 1.334 1.072.81a.724.724 0 0 0 .873 0l1.072-.81 1.766-1.334-3.27-2.469Z"/><path fill="#ef6c00" d="M17.912 19.053a7.9 7.9 0 0 0-3.141-1.412l-.024.062a4.34 4.34 0 0 0 1.44 5.016l.009.006.02.016 3.556 2.666 3.27-2.471Z"/></g>"##, +}; +pub(super) static FOLDER_GITLAB_OPEN: Icon = Icon { + name: "folder-gitlab-open", + view: 32.0, + body: r##"<path fill="#757575" d="M28.967 12H9.442a2 2 0 0 0-1.898 1.368L4 24V10h24a2 2 0 0 0-2-2H15.124a2 2 0 0 1-1.28-.464l-1.288-1.072A2 2 0 0 0 11.276 6H4a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h22l4.805-11.212A2 2 0 0 0 28.967 12"/><g data-mit-no-recolor="true"><path fill="#e53935" d="m31.35 17.703-.022-.063-2.339-6.097a.6.6 0 0 0-.24-.291.617.617 0 0 0-.928.353l-1.577 4.831h-6.39l-1.58-4.83a.62.62 0 0 0-.926-.354.6.6 0 0 0-.24.29l-2.337 6.1-.024.06a4.34 4.34 0 0 0 1.44 5.017l.009.006.02.015 3.556 2.667 1.764 1.333 1.072.81a.724.724 0 0 0 .873 0l1.072-.811 1.764-1.334 3.583-2.68.01-.008a4.34 4.34 0 0 0 1.44-5.014"/><path fill="#ef6c00" d="m31.35 17.703-.022-.063a7.9 7.9 0 0 0-3.143 1.413l-5.133 3.883 3.268 2.47 3.581-2.68.011-.009a4.34 4.34 0 0 0 1.44-5.014Z"/><path fill="#f9a825" d="m19.772 25.407 1.764 1.333 1.072.81a.724.724 0 0 0 .873 0l1.072-.81 1.766-1.333-3.27-2.471Z"/><path fill="#ef6c00" d="M17.912 19.053a7.9 7.9 0 0 0-3.141-1.412l-.024.062a4.34 4.34 0 0 0 1.44 5.016l.009.006.02.016 3.556 2.666 3.27-2.471Z"/></g>"##, +}; +pub(super) static FOLDER_GIT_OPEN: Icon = Icon { + name: "folder-git-open", + view: 32.0, + body: r##"<path fill="#ff7043" d="M28.967 12H9.442a2 2 0 0 0-1.898 1.368L4 24V10h24a2 2 0 0 0-2-2H15.124a2 2 0 0 1-1.28-.464l-1.288-1.072A2 2 0 0 0 11.276 6H4a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h22l4.805-11.212A2 2 0 0 0 28.967 12"/><path fill="#ffccbc" d="m12.593 18.589 5.784-5.794 1.692 1.7a1.98 1.98 0 0 0 .93 2.233v5.544a1.99 1.99 0 0 0-1 1.731 2.002 2.002 0 0 0 4.003 0A1.99 1.99 0 0 0 23 22.272v-4.864l2.071 2.092a1.2 1.2 0 0 0-.07.5 2.002 2.002 0 1 0 2.002-2.002 1.2 1.2 0 0 0-.5.07l-2.573-2.571a1.98 1.98 0 0 0-1.15-2.342 2.1 2.1 0 0 0-1.281-.09l-1.702-1.692.791-.78a1.975 1.975 0 0 1 2.822 0l7.996 7.996a1.975 1.975 0 0 1 0 2.822l-7.996 7.996a1.975 1.975 0 0 1-2.822 0l-7.996-7.996a1.975 1.975 0 0 1 0-2.822Z"/>"##, +}; +pub(super) static FOLDER_HELPER: Icon = Icon { + name: "folder-helper", + view: 32.0, + body: r##"<path fill="#afb42b" d="m13.844 7.536-1.288-1.072A2 2 0 0 0 11.276 6H4a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h24a2 2 0 0 0 2-2V10a2 2 0 0 0-2-2H15.124a2 2 0 0 1-1.28-.464"/><path fill="#f0f4c3" d="M28.178 12a1.57 1.57 0 0 0-1.138.467l-4.62 4.691 4.493 4.555 4.628-4.684a1.646 1.646 0 0 0 0-2.28l-2.259-2.282A1.54 1.54 0 0 0 28.178 12m-6.521 5.924-4.739 4.803a1.635 1.635 0 0 0 .008 2.291l.008.008C15.963 26.017 14.978 27.01 14 28h4.5l.684-.693a1.58 1.58 0 0 0 2.234-.016l4.732-4.803"/>"##, +}; +pub(super) static FOLDER_HELPER_OPEN: Icon = Icon { + name: "folder-helper-open", + view: 32.0, + body: r##"<path fill="#afb42b" d="M28.967 12H9.442a2 2 0 0 0-1.898 1.368L4 24V10h24a2 2 0 0 0-2-2H15.124a2 2 0 0 1-1.28-.464l-1.288-1.072A2 2 0 0 0 11.276 6H4a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h22l4.805-11.212A2 2 0 0 0 28.967 12"/><path fill="#f0f4c3" d="M28.178 12a1.57 1.57 0 0 0-1.138.467l-4.62 4.691 4.493 4.555 4.628-4.684a1.646 1.646 0 0 0 0-2.28l-2.259-2.282A1.54 1.54 0 0 0 28.178 12m-6.521 5.924-4.739 4.803a1.635 1.635 0 0 0 .008 2.291l.008.008C15.963 26.017 14.978 27.01 14 28h4.5l.684-.693a1.58 1.58 0 0 0 2.234-.016l4.732-4.803"/>"##, +}; +pub(super) static FOLDER_HOOK: Icon = Icon { + name: "folder-hook", + view: 1024.0, + body: r##"<path fill="#7e57c2" d="m443.008 241.152-41.216-34.304A64 64 0 0 0 360.832 192H128a64 64 0 0 0-64 64v512a64 64 0 0 0 64 64h768a64 64 0 0 0 64-64V320a64 64 0 0 0-64-64H483.968a64 64 0 0 1-40.96-14.848"/><path fill="#d1c4e9" d="M800 320c-53.02 0-96 42.98-96 96 .104 40.593 25.729 76.733 64 90.264V768c0 35.346-28.654 64-64 64s-64-28.654-64-64v-64h64L576 576v192c0 70.692 57.308 128 128 128s128-57.308 128-128V506.264c38.271-13.531 63.896-49.671 64-90.264 0-53.02-42.98-96-96-96m0 64c17.673 0 32 14.327 32 32s-14.327 32-32 32-32-14.327-32-32 14.327-32 32-32"/>"##, +}; +pub(super) static FOLDER_HOOK_OPEN: Icon = Icon { + name: "folder-hook-open", + view: 1024.0, + body: r##"<path fill="#7e57c2" d="M926.944 384h-624.8a64 64 0 0 0-60.736 43.776L128 768V320h768a64 64 0 0 0-64-64H483.968a64 64 0 0 1-40.96-14.848l-41.216-34.304A64 64 0 0 0 360.832 192H128a64 64 0 0 0-64 64v512a64 64 0 0 0 64 64h704l153.76-358.784A64 64 0 0 0 926.944 384"/><path fill="#d1c4e9" d="M800 320c-53.02 0-96 42.98-96 96 .104 40.593 25.729 76.733 64 90.264V768c0 35.346-28.654 64-64 64s-64-28.654-64-64v-64h64L576 576v192c0 70.692 57.308 128 128 128s128-57.308 128-128V506.264c38.271-13.531 63.896-49.671 64-90.264 0-53.02-42.98-96-96-96m0 64c17.673 0 32 14.327 32 32s-14.327 32-32 32-32-14.327-32-32 14.327-32 32-32"/>"##, +}; +pub(super) static FOLDER_I18N: Icon = Icon { + name: "folder-i18n", + view: 32.0, + body: r##"<path fill="#5c6bc0" d="m13.844 7.536-1.288-1.072A2 2 0 0 0 11.276 6H4a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h24a2 2 0 0 0 2-2V10a2 2 0 0 0-2-2H15.124a2 2 0 0 1-1.28-.464"/><path fill="#c5cae9" d="m22.79 23.762-2.308-2.259.027-.026a15.7 15.7 0 0 0 3.373-5.877h2.663v-1.8h-6.363V12h-1.819v1.8H12v1.8h10.155a14.2 14.2 0 0 1-2.882 4.814 14 14 0 0 1-2.1-3.014h-1.819a15.8 15.8 0 0 0 2.71 4.103l-4.629 4.518 1.292 1.278 4.545-4.5 2.828 2.799zm5.12-4.562h-1.82L22 30h1.818l1.017-2.7h4.32l1.025 2.699H32zm-2.384 6.3L27 21.602l1.473 3.897Z"/>"##, +}; +pub(super) static FOLDER_I18N_OPEN: Icon = Icon { + name: "folder-i18n-open", + view: 32.0, + body: r##"<path fill="#5c6bc0" d="M28.967 12H9.442a2 2 0 0 0-1.898 1.368L4 24V10h24a2 2 0 0 0-2-2H15.124a2 2 0 0 1-1.28-.464l-1.288-1.072A2 2 0 0 0 11.276 6H4a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h22l4.805-11.212A2 2 0 0 0 28.967 12"/><path fill="#c5cae9" d="m22.79 23.762-2.308-2.259.027-.026a15.7 15.7 0 0 0 3.373-5.877h2.663v-1.8h-6.363V12h-1.819v1.8H12v1.8h10.155a14.2 14.2 0 0 1-2.882 4.814 14 14 0 0 1-2.1-3.014h-1.819a15.8 15.8 0 0 0 2.71 4.103l-4.629 4.518 1.292 1.278 4.545-4.5 2.828 2.799zm5.12-4.562h-1.82L22 30h1.818l1.017-2.7h4.32l1.025 2.699H32zm-2.384 6.3L27 21.602l1.473 3.897Z"/>"##, +}; +pub(super) static FOLDER_IMAGES: Icon = Icon { + name: "folder-images", + view: 32.0, + body: r##"<path fill="#009688" d="m13.844 7.536-1.288-1.072A2 2 0 0 0 11.276 6H4a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h24a2 2 0 0 0 2-2V10a2 2 0 0 0-2-2H15.124a2 2 0 0 1-1.28-.464"/><path fill="#b2dfdb" d="M24 10h-7a1 1 0 0 0-1 1v16a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1V16Zm-4 6a2 2 0 1 1-2 2 2.01 2.01 0 0 1 2-2m8 10H18l4-4 2 2 4-4Zm-4.828-9.172V12L28 16.828Z"/>"##, +}; +pub(super) static FOLDER_IMAGES_OPEN: Icon = Icon { + name: "folder-images-open", + view: 32.0, + body: r##"<path fill="#009688" d="M28.967 12H9.442a2 2 0 0 0-1.898 1.368L4 24V10h24a2 2 0 0 0-2-2H15.124a2 2 0 0 1-1.28-.464l-1.288-1.072A2 2 0 0 0 11.276 6H4a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h22l4.805-11.212A2 2 0 0 0 28.967 12"/><path fill="#b2dfdb" d="M24 10h-7a1 1 0 0 0-1 1v16a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1V16Zm-4 6a2 2 0 1 1-2 2 2.01 2.01 0 0 1 2-2m8 10H18l4-4 2 2 4-4Zm-4.828-9.172V12L28 16.828Z"/>"##, +}; +pub(super) static FOLDER_INTELLIJ: Icon = Icon { + name: "folder-intellij", + view: 32.0, + body: r##"<defs data-mit-no-recolor="true"><linearGradient id="a" x1="-338.646" x2="-234.114" y1="3272.835" y2="3209.742" gradientTransform="translate(55.497 -331.024)scale(.11021)" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="#fdd835" /><stop offset="1" stop-color="#f57c00" /></linearGradient><linearGradient id="b" x1="-316.541" x2="-221.129" y1="3121.343" y2="3204.873" gradientTransform="translate(55.497 -331.024)scale(.11021)" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="#ef5350" /><stop offset=".57" stop-color="#ff6e40" /><stop offset="1" stop-color="#f57c00" /></linearGradient><linearGradient id="c" x1="-310.483" x2="-367.028" y1="3197.064" y2="3161.75" gradientTransform="translate(55.497 -331.024)scale(.11021)" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="#8e24aa" /><stop offset=".385" stop-color="#ab47bc" /><stop offset=".765" stop-color="#ec407a" /><stop offset=".957" stop-color="#ec407a" /></linearGradient><linearGradient id="d" x1="-311.503" x2="-366.707" y1="3117.085" y2="3162.678" gradientTransform="translate(55.497 -331.024)scale(.11021)" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="#ef5350" /><stop offset=".364" stop-color="#ec407a" /><stop offset="1" stop-color="#ec407a" /></linearGradient></defs><path fill="currentColor" d="m13.844 7.536-1.288-1.072A2 2 0 0 0 11.276 6H4a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h24a2 2 0 0 0 2-2V10a2 2 0 0 0-2-2H15.124a2 2 0 0 1-1.28-.464" /><path fill="url(#a)" d="M30.93 22.519a.68.68 0 0 0 .22-.47.69.69 0 0 0-.647-.72.72.72 0 0 0-.485.161l-12.314 6.745a1.44 1.44 0 0 0-.69.602 1.48 1.48 0 0 0 .506 2.03l.022.013a1.51 1.51 0 0 0 1.573-.03c.03-.029.073-.043.103-.073l11.461-8.053a2 2 0 0 0 .25-.205Z" /><path fill="url(#b)" d="m30.959 21.534-9.376-9.199a1.133 1.133 0 1 0-1.66 1.543 2 2 0 0 0 .176.147l9.904 8.48a.76.76 0 0 0 .441.19.69.69 0 0 0 .72-.646.73.73 0 0 0-.205-.515" /><path fill="url(#c)" d="M21.892 20.711c-.015 0-5.79-4.555-5.907-4.628l-.265-.133a1.644 1.644 0 0 0-1.44 2.94 1.3 1.3 0 0 0 .294.131c.059.03 6.671 2.763 6.671 2.763a.63.63 0 0 0 .647-1.073" /><path fill="url(#d)" d="M20.746 11.968a1.2 1.2 0 0 0-.676.22l-5.849 3.939c-.014.014-.03.014-.03.029h-.014a1.638 1.638 0 0 0 .397 2.865 1.61 1.61 0 0 0 1.528-.205 1.4 1.4 0 0 0 .265-.235l5.084-4.585a1.132 1.132 0 0 0-.705-2.028" />"##, +}; +pub(super) static FOLDER_INTELLIJ_OPEN: Icon = Icon { + name: "folder-intellij-open", + view: 32.0, + body: r##"<defs data-mit-no-recolor="true"><linearGradient id="a" x1=".445" x2="104.977" y1="3272.835" y2="3209.742" gradientTransform="translate(18.126 -331.024)scale(.11021)" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="#fdd835" /><stop offset="1" stop-color="#f57c00" /></linearGradient><linearGradient id="b" x1="22.55" x2="117.962" y1="3121.343" y2="3204.873" gradientTransform="translate(18.126 -331.024)scale(.11021)" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="#ef5350" /><stop offset=".57" stop-color="#ff6e40" /><stop offset="1" stop-color="#f57c00" /></linearGradient><linearGradient id="c" x1="28.608" x2="-27.937" y1="3197.064" y2="3161.75" gradientTransform="translate(18.126 -331.024)scale(.11021)" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="#8e24aa" /><stop offset=".385" stop-color="#ab47bc" /><stop offset=".765" stop-color="#ec407a" /><stop offset=".957" stop-color="#ec407a" /></linearGradient><linearGradient id="d" x1="27.588" x2="-27.616" y1="3117.085" y2="3162.678" gradientTransform="translate(18.126 -331.024)scale(.11021)" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="#ef5350" /><stop offset=".364" stop-color="#ec407a" /><stop offset="1" stop-color="#ec407a" /></linearGradient></defs><path fill="currentColor" d="M28.967 12H9.442a2 2 0 0 0-1.898 1.368L4 24V10h24a2 2 0 0 0-2-2H15.124a2 2 0 0 1-1.28-.464l-1.288-1.072A2 2 0 0 0 11.276 6H4a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h22l4.805-11.212A2 2 0 0 0 28.967 12" /><path fill="url(#a)" d="M30.93 22.519a.68.68 0 0 0 .22-.47.69.69 0 0 0-.647-.72.72.72 0 0 0-.485.161l-12.314 6.745a1.44 1.44 0 0 0-.69.602 1.48 1.48 0 0 0 .506 2.03l.022.013a1.51 1.51 0 0 0 1.573-.03c.03-.029.073-.043.103-.073l11.461-8.053a2 2 0 0 0 .25-.205Z" /><path fill="url(#b)" d="m30.959 21.534-9.376-9.199a1.133 1.133 0 1 0-1.66 1.543 2 2 0 0 0 .176.147l9.904 8.48a.76.76 0 0 0 .441.19.69.69 0 0 0 .72-.646.73.73 0 0 0-.205-.515" /><path fill="url(#c)" d="M21.892 20.711c-.015 0-5.79-4.555-5.907-4.628l-.265-.133a1.644 1.644 0 0 0-1.44 2.94 1.3 1.3 0 0 0 .294.131c.059.03 6.671 2.763 6.671 2.763a.63.63 0 0 0 .647-1.073" /><path fill="url(#d)" d="M20.746 11.968a1.2 1.2 0 0 0-.676.22l-5.849 3.939c-.014.014-.03.014-.03.029h-.014a1.638 1.638 0 0 0 .397 2.865 1.61 1.61 0 0 0 1.528-.205 1.4 1.4 0 0 0 .265-.235l5.084-4.585a1.132 1.132 0 0 0-.705-2.028" />"##, +}; +pub(super) static FOLDER_INTERFACE: Icon = Icon { + name: "folder-interface", + view: 32.0, + body: r##"<path fill="#1976d2" d="m13.844 7.536-1.288-1.072A2 2 0 0 0 11.276 6H4a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h24a2 2 0 0 0 2-2V10a2 2 0 0 0-2-2H15.124a2 2 0 0 1-1.28-.464"/><path fill="#bbdefb" d="M16 12v14a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V12a2 2 0 0 0-2-2H18a2 2 0 0 0-2 2m14 14H18v-4h12Zm0-6H18v-4h12Z"/>"##, +}; +pub(super) static FOLDER_INTERFACE_OPEN: Icon = Icon { + name: "folder-interface-open", + view: 32.0, + body: r##"<path fill="#1976d2" d="M28.967 12H9.442a2 2 0 0 0-1.898 1.368L4 24V10h24a2 2 0 0 0-2-2H15.124a2 2 0 0 1-1.28-.464l-1.288-1.072A2 2 0 0 0 11.276 6H4a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h22l4.805-11.212A2 2 0 0 0 28.967 12"/><path fill="#bbdefb" d="M16 12v14a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V12a2 2 0 0 0-2-2H18a2 2 0 0 0-2 2m14 14H18v-4h12Zm0-6H18v-4h12Z"/>"##, +}; +pub(super) static FOLDER_IOS: Icon = Icon { + name: "folder-ios", + view: 32.0, + body: r##"<path fill="#78909c" d="m13.844 7.536-1.288-1.072A2 2 0 0 0 11.276 6H4a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h24a2 2 0 0 0 2-2V10a2 2 0 0 0-2-2H15.124a2 2 0 0 1-1.28-.464"/><path fill="#cfd8dc" d="M12 18h2v10h-2zm0-4h2v2h-2zm4 1v12a1 1 0 0 0 1 1h6a1 1 0 0 0 1-1V15a1 1 0 0 0-1-1h-6a1 1 0 0 0-1 1m6 11h-4V16h4Zm10-10v-2h-5a1 1 0 0 0-1 1v6a1 1 0 0 0 1 1h3v4h-4v2h5a1 1 0 0 0 1-1v-6a1 1 0 0 0-1-1h-3v-4Z"/>"##, +}; +pub(super) static FOLDER_IOS_OPEN: Icon = Icon { + name: "folder-ios-open", + view: 32.0, + body: r##"<path fill="#78909c" d="M28.967 12H9.442a2 2 0 0 0-1.898 1.368L4 24V10h24a2 2 0 0 0-2-2H15.124a2 2 0 0 1-1.28-.464l-1.288-1.072A2 2 0 0 0 11.276 6H4a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h22l4.805-11.212A2 2 0 0 0 28.967 12"/><path fill="#cfd8dc" d="M12 18h2v10h-2zm0-4h2v2h-2zm4 1v12a1 1 0 0 0 1 1h6a1 1 0 0 0 1-1V15a1 1 0 0 0-1-1h-6a1 1 0 0 0-1 1m6 11h-4V16h4Zm10-10v-2h-5a1 1 0 0 0-1 1v6a1 1 0 0 0 1 1h3v4h-4v2h5a1 1 0 0 0 1-1v-6a1 1 0 0 0-1-1h-3v-4Z"/>"##, +}; +pub(super) static FOLDER_JOB: Icon = Icon { + name: "folder-job", + view: 32.0, + body: r##"<path fill="#ffa000" d="m13.844 7.536-1.288-1.072A2 2 0 0 0 11.276 6H4a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h24a2 2 0 0 0 2-2V10a2 2 0 0 0-2-2H15.124a2 2 0 0 1-1.28-.464"/><path fill="#ffecb3" d="M30 14h-4v-2l-2-2h-4l-2 2v2h-4a2 2 0 0 0-2 2v10a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2V16a2 2 0 0 0-2-2m-10-2h4v2h-4Zm6 10-7.023 4-1.014-1.725 5.558-3.27-5.558-3.269 1.014-1.724L26 20Z"/>"##, +}; +pub(super) static FOLDER_JOB_OPEN: Icon = Icon { + name: "folder-job-open", + view: 32.0, + body: r##"<path fill="#ffa000" d="M28.967 12H9.442a2 2 0 0 0-1.898 1.368L4 24V10h24a2 2 0 0 0-2-2H15.124a2 2 0 0 1-1.28-.464l-1.288-1.072A2 2 0 0 0 11.276 6H4a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h22l4.805-11.212A2 2 0 0 0 28.967 12"/><path fill="#ffecb3" d="M30 14h-4v-2l-2-2h-4l-2 2v2h-4a2 2 0 0 0-2 2v10a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2V16a2 2 0 0 0-2-2m-10-2h4v2h-4Zm6 10-7.023 4-1.014-1.725 5.558-3.27-5.558-3.269 1.014-1.724L26 20Z"/>"##, +}; +pub(super) static FOLDER_KEYS: Icon = Icon { + name: "folder-keys", + view: 32.0, + body: r##"<path fill="#26a69a" d="m13.844 7.536-1.288-1.072A2 2 0 0 0 11.276 6H4a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h24a2 2 0 0 0 2-2V10a2 2 0 0 0-2-2H15.124a2 2 0 0 1-1.28-.464"/><path fill="#b2dfdb" d="M21.651 20a6 6 0 1 0 0 4H26v4h4v-4h2v-4ZM16 24a2 2 0 1 1 2-2 2 2 0 0 1-2 2"/>"##, +}; +pub(super) static FOLDER_KEYS_OPEN: Icon = Icon { + name: "folder-keys-open", + view: 32.0, + body: r##"<path fill="#26a69a" d="M28.967 12H9.442a2 2 0 0 0-1.898 1.368L4 24V10h24a2 2 0 0 0-2-2H15.124a2 2 0 0 1-1.28-.464l-1.288-1.072A2 2 0 0 0 11.276 6H4a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h22l4.805-11.212A2 2 0 0 0 28.967 12"/><path fill="#b2dfdb" d="M21.651 20a6 6 0 1 0 0 4H26v4h4v-4h2v-4ZM16 24a2 2 0 1 1 2-2 2 2 0 0 1-2 2"/>"##, +}; +pub(super) static FOLDER_KUBERNETES: Icon = Icon { + name: "folder-kubernetes", + view: 32.0, + body: r##"<path fill="#448aff" d="m13.844 7.536-1.288-1.072A2 2 0 0 0 11.276 6H4a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h24a2 2 0 0 0 2-2V10a2 2 0 0 0-2-2H15.124a2 2 0 0 1-1.28-.464"/><path fill="#bbdefb" d="M22.069 10.463a.6.6 0 0 0-.116.003.59.59 0 0 0-.517.635v.16a3.6 3.6 0 0 0 .08.543 5.2 5.2 0 0 1 .065 1.018.6.6 0 0 1-.186.305l-.013.238a7 7 0 0 0-1.031.157 7.27 7.27 0 0 0-3.706 2.117l-.196-.145a.52.52 0 0 1-.346-.039 5.4 5.4 0 0 1-.765-.69 5 5 0 0 0-.372-.395l-.12-.093a.75.75 0 0 0-.397-.158.6.6 0 0 0-.463.197.61.61 0 0 0 .148.834l.013.013c.026.027.079.067.106.093a4 4 0 0 0 .475.277 5.4 5.4 0 0 1 .848.597.6.6 0 0 1 .106.33l.183.158a7.22 7.22 0 0 0-1.137 5.121l-.25.065a.8.8 0 0 1-.254.253 4.4 4.4 0 0 1-1.018.158 2 2 0 0 0-.543.051l-.144.029h-.013v.013c-.04 0-.08.013-.106.013a.57.57 0 1 0 .339 1.086l.004-.001a1 1 0 0 0 .174-.041 2.7 2.7 0 0 0 .488-.197 7 7 0 0 1 1.018-.292.5.5 0 0 1 .305.119l.263-.039a7.43 7.43 0 0 0 3.27 4.088l-.094.238a.7.7 0 0 1 .042.33 4.2 4.2 0 0 1-.517.913c-.106.159-.199.304-.318.462a.17.17 0 0 1-.052.148c-.013.04-.04.066-.054.106a.57.57 0 0 0 1.072.382c.027-.04.051-.132.078-.132a5 5 0 0 0 .16-.53 5 5 0 0 1 .437-1.017.45.45 0 0 1 .25-.12l.132-.237a7.4 7.4 0 0 0 5.254.013l.105.212a.5.5 0 0 1 .277.183 6 6 0 0 1 .398.954c.04.172.094.344.16.542.027 0 .051.08.078.12.013.039.028.065.041.105a.568.568 0 0 0 .984-.569l-.007-.012a1 1 0 0 1-.052-.16c-.106-.146-.212-.305-.318-.45a7.4 7.4 0 0 1-.501-.9.44.44 0 0 1 .039-.343 1 1 0 0 1-.093-.225 7.44 7.44 0 0 0 3.268-4.113c.08.013.158.025.251.038a.33.33 0 0 1 .305-.106 4.7 4.7 0 0 1 1.018.28 2.6 2.6 0 0 0 .475.196.7.7 0 0 0 .187.028v.013c0 .013.053.013.093.026a.585.585 0 0 0 .635-.491.57.57 0 0 0-.483-.645l-.008-.001a.34.34 0 0 1-.157-.067h-.543a6.6 6.6 0 0 1-1.018-.186.55.55 0 0 1-.253-.238l-.251-.064a7.2 7.2 0 0 0-1.165-5.109l.211-.184a.4.4 0 0 1 .106-.317 5 5 0 0 1 .848-.597 3.3 3.3 0 0 0 .462-.277 1 1 0 0 0 .12-.093c.039-.026.08-.053.08-.08a.556.556 0 0 0-.78-.793c-.04 0-.093.054-.133.08a10 10 0 0 0-.372.395 4.8 4.8 0 0 1-.767.69.5.5 0 0 1-.344.039l-.212.158a7.37 7.37 0 0 0-4.708-2.274l-.013-.253a.45.45 0 0 1-.186-.29 5.2 5.2 0 0 1 .065-1.018 3.6 3.6 0 0 0 .08-.543v-.292a.57.57 0 0 0-.504-.506m-.778 4.408-.16 2.977h-.013a.5.5 0 0 1-.106.28.5.5 0 0 1-.687.118h-.013l-2.434-1.734a5.75 5.75 0 0 1 2.803-1.535c.212-.04.412-.08.61-.106m1.427 0a5.9 5.9 0 0 1 3.4 1.641l-2.421 1.734h-.013a.6.6 0 0 1-.277.067.494.494 0 0 1-.516-.47v-.008Zm-5.727 2.713 2.223 2.024v.013a.34.34 0 0 1 .144.253.483.483 0 0 1-.323.602l-.02.005v.013l-2.858.822a5.9 5.9 0 0 1 .834-3.732m10.013.04a6.18 6.18 0 0 1 .86 3.679l-2.87-.822-.013-.013a.47.47 0 0 1-.238-.157.49.49 0 0 1 .042-.694l.01-.01-.013-.038Zm-5.462 2.144h.912l.568.7-.199.886-.819.398-.819-.398-.212-.886Zm-2.132 2.447h.106a.55.55 0 0 1 .504.382.5.5 0 0 1-.052.28v.038l-1.127 2.74a5.84 5.84 0 0 1-2.366-2.952Zm4.87 0h.319l2.948.475a5.85 5.85 0 0 1-2.367 2.977l-1.14-2.79a.53.53 0 0 1 .24-.662m-2.327 1.199a.51.51 0 0 1 .488.256h.013l1.442 2.607a5 5 0 0 1-.569.157 5.9 5.9 0 0 1-3.214-.157l1.442-2.607h.012c.04-.093.107-.133.2-.2a.5.5 0 0 1 .186-.056"/>"##, +}; +pub(super) static FOLDER_KUBERNETES_OPEN: Icon = Icon { + name: "folder-kubernetes-open", + view: 32.0, + body: r##"<path fill="#448aff" d="M28.967 12H9.442a2 2 0 0 0-1.898 1.368L4 24V10h24a2 2 0 0 0-2-2H15.124a2 2 0 0 1-1.28-.464l-1.288-1.072A2 2 0 0 0 11.276 6H4a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h22l4.805-11.212A2 2 0 0 0 28.967 12"/><path fill="#bbdefb" d="M22.069 10.463a.6.6 0 0 0-.116.003.59.59 0 0 0-.517.635v.16a3.6 3.6 0 0 0 .08.543 5.2 5.2 0 0 1 .065 1.018.6.6 0 0 1-.186.305l-.013.238a7 7 0 0 0-1.031.157 7.27 7.27 0 0 0-3.706 2.117l-.196-.145a.52.52 0 0 1-.346-.039 5.4 5.4 0 0 1-.765-.69 5 5 0 0 0-.372-.395l-.12-.093a.75.75 0 0 0-.397-.158.6.6 0 0 0-.463.197.61.61 0 0 0 .148.834l.013.013c.026.027.079.067.106.093a4 4 0 0 0 .475.277 5.4 5.4 0 0 1 .848.597.6.6 0 0 1 .106.33l.183.158a7.22 7.22 0 0 0-1.137 5.121l-.25.065a.8.8 0 0 1-.254.253 4.4 4.4 0 0 1-1.018.158 2 2 0 0 0-.543.051l-.144.029h-.013v.013c-.04 0-.08.013-.106.013a.57.57 0 1 0 .339 1.086l.004-.001a1 1 0 0 0 .174-.041 2.7 2.7 0 0 0 .488-.197 7 7 0 0 1 1.018-.292.5.5 0 0 1 .305.119l.263-.039a7.43 7.43 0 0 0 3.27 4.088l-.094.238a.7.7 0 0 1 .042.33 4.2 4.2 0 0 1-.517.913c-.106.159-.199.304-.318.462a.17.17 0 0 1-.052.148c-.013.04-.04.066-.054.106a.57.57 0 0 0 1.072.382c.027-.04.051-.132.078-.132a5 5 0 0 0 .16-.53 5 5 0 0 1 .437-1.017.45.45 0 0 1 .25-.12l.132-.237a7.4 7.4 0 0 0 5.254.013l.105.212a.5.5 0 0 1 .277.183 6 6 0 0 1 .398.954c.04.172.094.344.16.542.027 0 .051.08.078.12.013.039.028.065.041.105a.568.568 0 0 0 .984-.569l-.007-.012a1 1 0 0 1-.052-.16c-.106-.146-.212-.305-.318-.45a7.4 7.4 0 0 1-.501-.9.44.44 0 0 1 .039-.343 1 1 0 0 1-.093-.225 7.44 7.44 0 0 0 3.268-4.113c.08.013.158.025.251.038a.33.33 0 0 1 .305-.106 4.7 4.7 0 0 1 1.018.28 2.6 2.6 0 0 0 .475.196.7.7 0 0 0 .187.028v.013c0 .013.053.013.093.026a.585.585 0 0 0 .635-.491.57.57 0 0 0-.483-.645l-.008-.001a.34.34 0 0 1-.157-.067h-.543a6.6 6.6 0 0 1-1.018-.186.55.55 0 0 1-.253-.238l-.251-.064a7.2 7.2 0 0 0-1.165-5.109l.211-.184a.4.4 0 0 1 .106-.317 5 5 0 0 1 .848-.597 3.3 3.3 0 0 0 .462-.277 1 1 0 0 0 .12-.093c.039-.026.08-.053.08-.08a.556.556 0 0 0-.78-.793c-.04 0-.093.054-.133.08a10 10 0 0 0-.372.395 4.8 4.8 0 0 1-.767.69.5.5 0 0 1-.344.039l-.212.158a7.37 7.37 0 0 0-4.708-2.274l-.013-.253a.45.45 0 0 1-.186-.29 5.2 5.2 0 0 1 .065-1.018 3.6 3.6 0 0 0 .08-.543v-.292a.57.57 0 0 0-.504-.506m-.778 4.408-.16 2.977h-.013a.5.5 0 0 1-.106.28.5.5 0 0 1-.687.118h-.013l-2.434-1.734a5.75 5.75 0 0 1 2.803-1.535c.212-.04.412-.08.61-.106m1.427 0a5.9 5.9 0 0 1 3.4 1.641l-2.421 1.734h-.013a.6.6 0 0 1-.277.067.494.494 0 0 1-.516-.47v-.008Zm-5.727 2.713 2.223 2.024v.013a.34.34 0 0 1 .144.253.483.483 0 0 1-.323.602l-.02.005v.013l-2.858.822a5.9 5.9 0 0 1 .834-3.732m10.013.04a6.18 6.18 0 0 1 .86 3.679l-2.87-.822-.013-.013a.47.47 0 0 1-.238-.157.49.49 0 0 1 .042-.694l.01-.01-.013-.038Zm-5.462 2.144h.912l.568.7-.199.886-.819.398-.819-.398-.212-.886Zm-2.132 2.447h.106a.55.55 0 0 1 .504.382.5.5 0 0 1-.052.28v.038l-1.127 2.74a5.84 5.84 0 0 1-2.366-2.952Zm4.87 0h.319l2.948.475a5.85 5.85 0 0 1-2.367 2.977l-1.14-2.79a.53.53 0 0 1 .24-.662m-2.327 1.199a.51.51 0 0 1 .488.256h.013l1.442 2.607a5 5 0 0 1-.569.157 5.9 5.9 0 0 1-3.214-.157l1.442-2.607h.012c.04-.093.107-.133.2-.2a.5.5 0 0 1 .186-.056"/>"##, +}; +pub(super) static FOLDER_LAYOUT: Icon = Icon { + name: "folder-layout", + view: 32.0, + body: r##"<path fill="#039be5" d="m13.844 7.536-1.288-1.072A2 2 0 0 0 11.276 6H4a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h24a2 2 0 0 0 2-2V10a2 2 0 0 0-2-2H15.124a2 2 0 0 1-1.28-.464"/><path fill="#b3e5fc" d="M10 16h6v14h-6zm8 8h6v6h-6zm8 0h6v6h-6zm-8-8h14v6H18z"/>"##, +}; +pub(super) static FOLDER_LAYOUT_OPEN: Icon = Icon { + name: "folder-layout-open", + view: 32.0, + body: r##"<path fill="#039be5" d="M28.967 12H9.442a2 2 0 0 0-1.898 1.368L4 24V10h24a2 2 0 0 0-2-2H15.124a2 2 0 0 1-1.28-.464l-1.288-1.072A2 2 0 0 0 11.276 6H4a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h22l4.805-11.212A2 2 0 0 0 28.967 12"/><path fill="#b3e5fc" d="M10 16h6v14h-6zm8 8h6v6h-6zm8 0h6v6h-6zm-8-8h14v6H18z"/>"##, +}; +pub(super) static FOLDER_LESS: Icon = Icon { + name: "folder-less", + view: 32.0, + body: r##"<path fill="#0277bd" d="m13.844 7.536-1.288-1.072A2 2 0 0 0 11.276 6H4a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h24a2 2 0 0 0 2-2V10a2 2 0 0 0-2-2H15.124a2 2 0 0 1-1.28-.464"/><path fill="#b3e5fc" d="M20 21a1 1 0 0 0-1-1 1 1 0 0 0 1-1v-5h2v-2h-2a2 2 0 0 0-2 2v4a1 1 0 0 1-1 1h-1v2h1a1 1 0 0 1 1 1v4a2 2 0 0 0 2 2h2v-2h-2Zm11-2a1 1 0 0 1-1-1v-4a2 2 0 0 0-2-2h-2v2h2v5a1 1 0 0 0 1 1 1 1 0 0 0-1 1v5h-2v2h2a2 2 0 0 0 2-2v-4a1 1 0 0 1 1-1h1v-2Z"/>"##, +}; +pub(super) static FOLDER_LESS_OPEN: Icon = Icon { + name: "folder-less-open", + view: 32.0, + body: r##"<path fill="#0277bd" d="M28.967 12H9.442a2 2 0 0 0-1.898 1.368L4 24V10h24a2 2 0 0 0-2-2H15.124a2 2 0 0 1-1.28-.464l-1.288-1.072A2 2 0 0 0 11.276 6H4a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h22l4.805-11.212A2 2 0 0 0 28.967 12"/><path fill="#b3e5fc" d="M20 21a1 1 0 0 0-1-1 1 1 0 0 0 1-1v-5h2v-2h-2a2 2 0 0 0-2 2v4a1 1 0 0 1-1 1h-1v2h1a1 1 0 0 1 1 1v4a2 2 0 0 0 2 2h2v-2h-2Zm11-2a1 1 0 0 1-1-1v-4a2 2 0 0 0-2-2h-2v2h2v5a1 1 0 0 0 1 1 1 1 0 0 0-1 1v5h-2v2h2a2 2 0 0 0 2-2v-4a1 1 0 0 1 1-1h1v-2Z"/>"##, +}; +pub(super) static FOLDER_LIB: Icon = Icon { + name: "folder-lib", + view: 32.0, + body: r##"<path fill="#c0ca33" d="m13.844 7.536-1.288-1.072A2 2 0 0 0 11.276 6H4a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h24a2 2 0 0 0 2-2V10a2 2 0 0 0-2-2H15.124a2 2 0 0 1-1.28-.464"/><path fill="#f0f4c3" d="M22.931 16a3 3 0 0 0 .003-6h-.003a3 3 0 0 0-3 2.999V13a3 3 0 0 0 2.999 3zm0 3.973c-2.225-2.078-5.955-3.978-9-3.973v10c3.19 0 6.85 2.004 9 4 2.226-2.078 5.955-4.005 9-4V16c-3.044-.005-6.774 1.895-9 3.973"/>"##, +}; +pub(super) static FOLDER_LIB_OPEN: Icon = Icon { + name: "folder-lib-open", + view: 32.0, + body: r##"<path fill="#c0ca33" d="M28.967 12H9.442a2 2 0 0 0-1.898 1.368L4 24V10h24a2 2 0 0 0-2-2H15.124a2 2 0 0 1-1.28-.464l-1.288-1.072A2 2 0 0 0 11.276 6H4a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h22l4.805-11.212A2 2 0 0 0 28.967 12"/><path fill="#f0f4c3" d="M23 16a3 3 0 0 0 .003-6H23a3 3 0 0 0-3 2.999V13a3 3 0 0 0 2.999 3zm0 3.973c-2.225-2.078-5.955-3.978-9-3.973v10c3.19 0 6.85 2.004 9 4 2.225-2.078 5.955-4.005 9-4V16c-3.045-.005-6.775 1.895-9 3.973"/>"##, +}; +pub(super) static FOLDER_LINUX: Icon = Icon { + name: "folder-linux", + view: 32.0, + body: r##"<path fill="#f9a825" d="m13.844 7.536-1.288-1.072A2 2 0 0 0 11.276 6H4a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h24a2 2 0 0 0 2-2V10a2 2 0 0 0-2-2H15.124a2 2 0 0 1-1.28-.464"/><path fill="#ffecb3" d="M24.62 16.35c-.42.28-1.75 1.04-1.95 1.19a.825.825 0 0 1-1.14-.01c-.2-.16-1.53-.92-1.95-1.19-.48-.309-.45-.699.08-.919a6.16 6.16 0 0 1 4.91.03c.49.21.51.6.05.9Zm7.218 7.279A19.1 19.1 0 0 0 28 17.971a4.3 4.3 0 0 1-1.06-1.88c-.1-.33-.17-.67-.24-1.01a11.3 11.3 0 0 0-.7-2.609 4.06 4.06 0 0 0-3.839-2.47 4.2 4.2 0 0 0-3.95 2.4 6 6 0 0 0-.46 1.34c-.17.76-.32 1.55-.5 2.319a3.4 3.4 0 0 1-.959 1.71 19.5 19.5 0 0 0-3.88 5.348 6 6 0 0 0-.37.88c-.19.66.29 1.12.99.96.44-.09.88-.18 1.3-.31.41-.15.57-.05.67.35a6.73 6.73 0 0 0 4.24 4.498c4.119 1.56 8.928-.66 9.968-4.578.07-.27.17-.37.47-.27.46.14.93.24 1.4.35a.724.724 0 0 0 .92-.64 1.44 1.44 0 0 0-.16-.73Z"/>"##, +}; +pub(super) static FOLDER_LINUX_OPEN: Icon = Icon { + name: "folder-linux-open", + view: 32.0, + body: r##"<path fill="#f9a825" d="M28.967 12H9.442a2 2 0 0 0-1.898 1.368L4 24V10h24a2 2 0 0 0-2-2H15.124a2 2 0 0 1-1.28-.464l-1.288-1.072A2 2 0 0 0 11.276 6H4a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h22l4.805-11.212A2 2 0 0 0 28.967 12"/><path fill="#ffecb3" d="M24.62 16.35c-.42.28-1.75 1.04-1.95 1.19a.825.825 0 0 1-1.14-.01c-.2-.16-1.53-.92-1.95-1.19-.48-.309-.45-.699.08-.919a6.16 6.16 0 0 1 4.91.03c.49.21.51.6.05.9Zm7.218 7.279A19.1 19.1 0 0 0 28 17.971a4.3 4.3 0 0 1-1.06-1.88c-.1-.33-.17-.67-.24-1.01a11.3 11.3 0 0 0-.7-2.609 4.06 4.06 0 0 0-3.839-2.47 4.2 4.2 0 0 0-3.95 2.4 6 6 0 0 0-.46 1.34c-.17.76-.32 1.55-.5 2.319a3.4 3.4 0 0 1-.959 1.71 19.5 19.5 0 0 0-3.88 5.348 6 6 0 0 0-.37.88c-.19.66.29 1.12.99.96.44-.09.88-.18 1.3-.31.41-.15.57-.05.67.35a6.73 6.73 0 0 0 4.24 4.498c4.119 1.56 8.928-.66 9.968-4.578.07-.27.17-.37.47-.27.46.14.93.24 1.4.35a.724.724 0 0 0 .92-.64 1.44 1.44 0 0 0-.16-.73Z"/>"##, +}; +pub(super) static FOLDER_LOG: Icon = Icon { + name: "folder-log", + view: 32.0, + body: r##"<path fill="#afb42b" d="m13.844 7.536-1.288-1.072A2 2 0 0 0 11.276 6H4a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h24a2 2 0 0 0 2-2V10a2 2 0 0 0-2-2H15.124a2 2 0 0 1-1.28-.464"/><path fill="#afb42b" d="M20 14h8v2h-8zm0 4h8v2h-8zm0 4h6v2h-6z"/><path fill="#f0f4c3" d="M30.337 14H17.663A1.663 1.663 0 0 0 16 15.663v10.674A1.663 1.663 0 0 0 17.663 28h12.674A1.663 1.663 0 0 0 32 26.337V15.663A1.663 1.663 0 0 0 30.337 14M26 26h-6v-2h6Zm2-4h-8v-2h8Zm0-4h-8v-2h8Z"/>"##, +}; +pub(super) static FOLDER_LOG_OPEN: Icon = Icon { + name: "folder-log-open", + view: 32.0, + body: r##"<path fill="#afb42b" d="M28.967 12H9.442a2 2 0 0 0-1.898 1.368L4 24V10h24a2 2 0 0 0-2-2H15.124a2 2 0 0 1-1.28-.464l-1.288-1.072A2 2 0 0 0 11.276 6H4a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h22l4.805-11.212A2 2 0 0 0 28.967 12"/><path fill="#f0f4c3" d="M30.337 14H17.663A1.663 1.663 0 0 0 16 15.663v10.674A1.663 1.663 0 0 0 17.663 28h12.674A1.663 1.663 0 0 0 32 26.337V15.663A1.663 1.663 0 0 0 30.337 14M26 26h-6v-2h6Zm2-4h-8v-2h8Zm0-4h-8v-2h8Z"/>"##, +}; +pub(super) static FOLDER_MACOS: Icon = Icon { + name: "folder-macos", + view: 32.0, + body: r##"<path fill="currentColor" d="m13.844 7.536-1.288-1.072A2 2 0 0 0 11.276 6H4a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h24a2 2 0 0 0 2-2V10a2 2 0 0 0-2-2H15.124a2 2 0 0 1-1.28-.464" /><path fill="#cfd8dc" d="M30.64 27.499c-.82 1.24-1.687 2.45-3.008 2.47-1.322.03-1.746-.79-3.245-.79-1.508 0-1.972.77-3.224.82-1.292.05-2.268-1.32-3.096-2.53-1.687-2.47-2.979-7.02-1.243-10.08a4.81 4.81 0 0 1 4.063-2.51c1.262-.02 2.465.87 3.244.87.77 0 2.229-1.07 3.757-.91a4.56 4.56 0 0 1 3.59 1.98 4.57 4.57 0 0 0-2.12 3.81A4.41 4.41 0 0 0 32 24.67a11.1 11.1 0 0 1-1.36 2.83Zm-5.632-16a4.46 4.46 0 0 1 2.9-1.499 4.42 4.42 0 0 1-1.026 3.19 3.58 3.58 0 0 1-2.91 1.42 4.3 4.3 0 0 1 1.036-3.11Z" />"##, +}; +pub(super) static FOLDER_MACOS_OPEN: Icon = Icon { + name: "folder-macos-open", + view: 32.0, + body: r##"<path fill="currentColor" d="M28.967 12H9.442a2 2 0 0 0-1.898 1.368L4 24V10h24a2 2 0 0 0-2-2H15.124a2 2 0 0 1-1.28-.464l-1.288-1.072A2 2 0 0 0 11.276 6H4a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h22l4.805-11.212A2 2 0 0 0 28.967 12" /><path fill="#cfd8dc" d="M30.64 27.499c-.82 1.24-1.687 2.45-3.008 2.47-1.322.03-1.746-.79-3.245-.79-1.508 0-1.972.77-3.224.82-1.292.05-2.268-1.32-3.096-2.53-1.687-2.47-2.979-7.02-1.243-10.08a4.81 4.81 0 0 1 4.063-2.51c1.262-.02 2.465.87 3.244.87.77 0 2.229-1.07 3.757-.91a4.56 4.56 0 0 1 3.59 1.98 4.57 4.57 0 0 0-2.12 3.81A4.41 4.41 0 0 0 32 24.67a11.1 11.1 0 0 1-1.36 2.83Zm-5.632-16a4.46 4.46 0 0 1 2.9-1.499 4.42 4.42 0 0 1-1.026 3.19 3.58 3.58 0 0 1-2.91 1.42 4.3 4.3 0 0 1 1.036-3.11Z" />"##, +}; +pub(super) static FOLDER_MIDDLEWARE: Icon = Icon { + name: "folder-middleware", + view: 32.0, + body: r##"<path fill="#5c6bc0" d="m13.844 7.536-1.288-1.072A2 2 0 0 0 11.276 6H4a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h24a2 2 0 0 0 2-2V10a2 2 0 0 0-2-2H15.124a2 2 0 0 1-1.28-.464"/><path fill="#c5cae9" d="M30.107 20H32v-4a2 2 0 0 0-2-2h-4v-2a2 2 0 0 0-4 0v2h-4a2 2 0 0 0-2 2v4h-2a2 2 0 0 0 0 4h2v4a2 2 0 0 0 2 2h4v-1.893a2.074 2.074 0 0 1 1.664-2.08A2 2 0 0 1 26 28v2h4a2 2 0 0 0 2-2v-4h-2a2 2 0 0 1-1.973-2.336A2.074 2.074 0 0 1 30.107 20"/>"##, +}; +pub(super) static FOLDER_MIDDLEWARE_OPEN: Icon = Icon { + name: "folder-middleware-open", + view: 32.0, + body: r##"<path fill="#5c6bc0" d="M28.967 12H9.442a2 2 0 0 0-1.898 1.368L4 24V10h24a2 2 0 0 0-2-2H15.124a2 2 0 0 1-1.28-.464l-1.288-1.072A2 2 0 0 0 11.276 6H4a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h22l4.805-11.212A2 2 0 0 0 28.967 12"/><path fill="#c5cae9" d="M30.107 20H32v-4a2 2 0 0 0-2-2h-4v-2a2 2 0 0 0-4 0v2h-4a2 2 0 0 0-2 2v4h-2a2 2 0 0 0 0 4h2v4a2 2 0 0 0 2 2h4v-1.893a2.074 2.074 0 0 1 1.664-2.08A2 2 0 0 1 26 28v2h4a2 2 0 0 0 2-2v-4h-2a2 2 0 0 1-1.973-2.336A2.074 2.074 0 0 1 30.107 20"/>"##, +}; +pub(super) static FOLDER_MOBILE: Icon = Icon { + name: "folder-mobile", + view: 32.0, + body: r##"<path fill="#ff5252" d="m13.844 7.536-1.288-1.072A2 2 0 0 0 11.276 6H4a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h24a2 2 0 0 0 2-2V10a2 2 0 0 0-2-2H15.124a2 2 0 0 1-1.28-.464"/><path fill="#ffcdd2" d="M12 14v10a2 2 0 0 0 2 2h8v-2h-6V14h12v2h4v-2a2 2 0 0 0-2-2H14a2 2 0 0 0-2 2"/><path fill="#ffcdd2" d="M24 19v8a1 1 0 0 0 1 1h6a1 1 0 0 0 1-1v-8a1 1 0 0 0-1-1h-6a1 1 0 0 0-1 1m6 7h-4v-6h4Z"/>"##, +}; +pub(super) static FOLDER_MOBILE_OPEN: Icon = Icon { + name: "folder-mobile-open", + view: 32.0, + body: r##"<path fill="#ff5252" d="M28.967 12H9.442a2 2 0 0 0-1.898 1.368L4 24V10h24a2 2 0 0 0-2-2H15.124a2 2 0 0 1-1.28-.464l-1.288-1.072A2 2 0 0 0 11.276 6H4a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h22l4.805-11.212A2 2 0 0 0 28.967 12"/><path fill="#ffcdd2" d="M12 14v10a2 2 0 0 0 2 2h8v-2h-6V14h12v2h4v-2a2 2 0 0 0-2-2H14a2 2 0 0 0-2 2"/><path fill="#ffcdd2" d="M24 19v8a1 1 0 0 0 1 1h6a1 1 0 0 0 1-1v-8a1 1 0 0 0-1-1h-6a1 1 0 0 0-1 1m6 7h-4v-6h4Z"/>"##, +}; +pub(super) static FOLDER_MOCK: Icon = Icon { + name: "folder-mock", + view: 32.0, + body: r##"<path fill="#8d6e63" d="m13.844 7.536-1.288-1.072A2 2 0 0 0 11.276 6H4a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h24a2 2 0 0 0 2-2V10a2 2 0 0 0-2-2H15.124a2 2 0 0 1-1.28-.464"/><path fill="#d7ccc8" d="M16 24.667V28h3.333l9.83-9.83-3.333-3.333Zm15.74-9.074a.885.885 0 0 0 .001-1.252v-.001l-2.08-2.08a.885.885 0 0 0-1.253-.001l-1.627 1.627 3.333 3.333Z"/>"##, +}; +pub(super) static FOLDER_MOCK_OPEN: Icon = Icon { + name: "folder-mock-open", + view: 32.0, + body: r##"<path fill="#8d6e63" d="M28.967 12H9.442a2 2 0 0 0-1.898 1.368L4 24V10h24a2 2 0 0 0-2-2H15.124a2 2 0 0 1-1.28-.464l-1.288-1.072A2 2 0 0 0 11.276 6H4a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h22l4.805-11.212A2 2 0 0 0 28.967 12"/><path fill="#d7ccc8" d="M16 24.667V28h3.333l9.83-9.83-3.333-3.333Zm15.74-9.074a.885.885 0 0 0 .001-1.252v-.001l-2.08-2.08a.885.885 0 0 0-1.253-.001l-1.627 1.627 3.333 3.333Z"/>"##, +}; +pub(super) static FOLDER_NETLIFY: Icon = Icon { + name: "folder-netlify", + view: 32.0, + body: r##"<path fill="#26a69a" d="m13.844 7.536-1.288-1.072A2 2 0 0 0 11.276 6H4a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h24a2 2 0 0 0 2-2V10a2 2 0 0 0-2-2H15.124a2 2 0 0 1-1.28-.464"/><path fill="#a7ffeb" d="M22 16h-4v6h2v-4h1.5a.5.5 0 0 1 .5.5V22h2v-4a2 2 0 0 0-2-2"/><rect width="6" height="2" x="26" y="18" fill="#a7ffeb" rx=".5"/><rect width="2" height="6" x="20" y="8" fill="#a7ffeb" rx=".5"/><rect width="6" height="2" x="10" y="18" fill="#a7ffeb" rx=".5"/><rect width="2" height="6" x="20" y="24" fill="#a7ffeb" rx=".5"/><path fill="#a7ffeb" d="m13 12.172 1.414-1.414 2.828 2.828L15.828 15zM15.828 23l1.414 1.414-2.828 2.828L13 25.828z"/>"##, +}; +pub(super) static FOLDER_NETLIFY_OPEN: Icon = Icon { + name: "folder-netlify-open", + view: 32.0, + body: r##"<path fill="#26a69a" d="M28.967 12H9.442a2 2 0 0 0-1.898 1.368L4 24V10h24a2 2 0 0 0-2-2H15.124a2 2 0 0 1-1.28-.464l-1.288-1.072A2 2 0 0 0 11.276 6H4a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h22l4.805-11.212A2 2 0 0 0 28.967 12"/><path fill="#a7ffeb" d="M22 16h-4v6h2v-4h1.5a.5.5 0 0 1 .5.5V22h2v-4a2 2 0 0 0-2-2"/><rect width="6" height="2" x="26" y="18" fill="#a7ffeb" rx=".5"/><rect width="2" height="6" x="20" y="8" fill="#a7ffeb" rx=".5"/><rect width="6" height="2" x="10" y="18" fill="#a7ffeb" rx=".5"/><rect width="2" height="6" x="20" y="24" fill="#a7ffeb" rx=".5"/><path fill="#a7ffeb" d="m13 12.172 1.414-1.414 2.828 2.828L15.828 15zM15.828 23l1.414 1.414-2.828 2.828L13 25.828z"/>"##, +}; +pub(super) static FOLDER_NGRX_STORE: Icon = Icon { + name: "folder-ngrx-store", + view: 32.0, + body: r##"<path fill="#8bc34a" d="m13.844 7.536-1.288-1.072A2 2 0 0 0 11.276 6H4a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h24a2 2 0 0 0 2-2V10a2 2 0 0 0-2-2H15.124a2 2 0 0 1-1.28-.464"/><path fill="#dcedc8" d="m23 9-9 3 1 12 8 4 8-4 1-12Zm-1.869 2.785a2.3 2.3 0 0 1 1.124.324 5.3 5.3 0 0 0 1.214.305 6.63 6.63 0 0 1 4.433 2.834c.448.875.356 1.348-.33 1.7-.59.303-1.799.157-3.554-.432l-1.481-.497-.527.199a3.53 3.53 0 0 0-1.84 1.73 2.9 2.9 0 0 0-.218 1.622 2.9 2.9 0 0 0 .41 1.645c.35.613 1.15 1.395 1.287 1.259.038-.038-.044-.287-.182-.553a1.1 1.1 0 0 1-.178-.595c.038-.061.4.165.802.504a5.6 5.6 0 0 0 2.898 1.333c.787.081.967-.064.377-.307a1.8 1.8 0 0 1-.547-.363c-.23-.252-.243-.244.738-.462a4.6 4.6 0 0 0 1.887-.996c.023-.073-.173-.102-.495-.077-.292.023-.53-.006-.53-.067a3 3 0 0 1 .53-.656 4.93 4.93 0 0 0 1.585-3.596l.08-1.114.258.53a3.2 3.2 0 0 1 .133 2.148c-.168.605-.056.672.253.152.382-.644.505-.543.438.364a3.95 3.95 0 0 1-1.183 2.561c-.627.68-.551.803.207.34.731-.449.83-.379.453.325a6.08 6.08 0 0 1-3.782 2.831 6.2 6.2 0 0 1-2.487.16 7.33 7.33 0 0 1-5.44-3.849 13 13 0 0 0-.836-1.437c-.403-.542-.436-.785-.166-1.197a.92.92 0 0 0 .111-.73c-.257-1.451-.248-1.496.337-2.088.512-.513.543-.581.543-1.182 0-.52.052-.69.29-.925a1 1 0 0 1 .561-.291 2.88 2.88 0 0 0 1.624-.865 1.67 1.67 0 0 1 1.203-.587"/>"##, +}; +pub(super) static FOLDER_NGRX_STORE_OPEN: Icon = Icon { + name: "folder-ngrx-store-open", + view: 32.0, + body: r##"<path fill="#8bc34a" d="M28.967 12H9.442a2 2 0 0 0-1.898 1.368L4 24V10h24a2 2 0 0 0-2-2H15.124a2 2 0 0 1-1.28-.464l-1.288-1.072A2 2 0 0 0 11.276 6H4a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h22l4.805-11.212A2 2 0 0 0 28.967 12"/><path fill="#dcedc8" d="m23 9-9 3 1 12 8 4 8-4 1-12Zm-1.869 2.785a2.3 2.3 0 0 1 1.124.324 5.3 5.3 0 0 0 1.214.305 6.63 6.63 0 0 1 4.433 2.834c.448.875.356 1.348-.33 1.7-.59.303-1.799.157-3.554-.432l-1.481-.497-.527.199a3.53 3.53 0 0 0-1.84 1.73 2.9 2.9 0 0 0-.218 1.622 2.9 2.9 0 0 0 .41 1.645c.35.613 1.15 1.395 1.287 1.259.038-.038-.044-.287-.182-.553a1.1 1.1 0 0 1-.178-.595c.038-.061.4.165.802.504a5.6 5.6 0 0 0 2.898 1.333c.787.081.967-.064.377-.307a1.8 1.8 0 0 1-.547-.363c-.23-.252-.243-.244.738-.462a4.6 4.6 0 0 0 1.887-.996c.023-.073-.173-.102-.495-.077-.292.023-.53-.006-.53-.067a3 3 0 0 1 .53-.656 4.93 4.93 0 0 0 1.585-3.596l.08-1.114.258.53a3.2 3.2 0 0 1 .133 2.148c-.168.605-.056.672.253.152.382-.644.505-.543.438.364a3.95 3.95 0 0 1-1.183 2.561c-.627.68-.551.803.207.34.731-.449.83-.379.453.325a6.08 6.08 0 0 1-3.782 2.831 6.2 6.2 0 0 1-2.487.16 7.33 7.33 0 0 1-5.44-3.849 13 13 0 0 0-.836-1.437c-.403-.542-.436-.785-.166-1.197a.92.92 0 0 0 .111-.73c-.257-1.451-.248-1.496.337-2.088.512-.513.543-.581.543-1.182 0-.52.052-.69.29-.925a1 1 0 0 1 .561-.291 2.88 2.88 0 0 0 1.624-.865 1.67 1.67 0 0 1 1.203-.587"/>"##, +}; +pub(super) static FOLDER_NODE: Icon = Icon { + name: "folder-node", + view: 32.0, + body: r##"<path fill="#8bc34a" d="m13.844 7.536-1.288-1.072A2 2 0 0 0 11.276 6H4a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h24a2 2 0 0 0 2-2V10a2 2 0 0 0-2-2H15.124a2 2 0 0 1-1.28-.464"/><path fill="#dcedc8" d="m25 12-7 4.072v7.854L25 28l7-4.074v-7.854Z"/>"##, +}; +pub(super) static FOLDER_NODE_OPEN: Icon = Icon { + name: "folder-node-open", + view: 32.0, + body: r##"<path fill="#8bc34a" d="M28.967 12H9.442a2 2 0 0 0-1.898 1.368L4 24V10h24a2 2 0 0 0-2-2H15.124a2 2 0 0 1-1.28-.464l-1.288-1.072A2 2 0 0 0 11.276 6H4a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h22l4.805-11.212A2 2 0 0 0 28.967 12"/><path fill="#dcedc8" d="m25 12-7 4.072v7.854L25 28l7-4.074v-7.854Z"/>"##, +}; +pub(super) static FOLDER_OPEN: Icon = Icon { + name: "folder-open", + view: 16.0, + body: r##"<path d="M14.483 6H4.721a1 1 0 0 0-.949.684L2 12V5h12a1 1 0 0 0-1-1H7.562a1 1 0 0 1-.64-.232l-.644-.536A1 1 0 0 0 5.638 3H2a1 1 0 0 0-1 1v8a1 1 0 0 0 1 1h11l2.403-5.606A1 1 0 0 0 14.483 6" fill="currentColor" />"##, +}; +pub(super) static FOLDER_PACKAGES: Icon = Icon { + name: "folder-packages", + view: 32.0, + body: r##"<path fill="#1e88e5" d="m13.844 7.536-1.288-1.072A2 2 0 0 0 11.276 6H4a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h24a2 2 0 0 0 2-2V10a2 2 0 0 0-2-2H15.124a2 2 0 0 1-1.28-.464"/><path fill="#bbdefb" d="M31.2 12.933 29.6 10.8A2 2 0 0 0 28 10h-8a2 2 0 0 0-1.6.8l-1.6 2.133a4 4 0 0 0-.8 2.4V26a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V15.333a4 4 0 0 0-.8-2.4M20 12h8l1.5 2h-11Zm6 10v4h-4v-4h-4l6-6 6 6Z"/>"##, +}; +pub(super) static FOLDER_PACKAGES_OPEN: Icon = Icon { + name: "folder-packages-open", + view: 32.0, + body: r##"<path fill="#1e88e5" d="M28.967 12H9.442a2 2 0 0 0-1.898 1.368L4 24V10h24a2 2 0 0 0-2-2H15.124a2 2 0 0 1-1.28-.464l-1.288-1.072A2 2 0 0 0 11.276 6H4a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h22l4.805-11.212A2 2 0 0 0 28.967 12"/><path fill="#bbdefb" d="M31.2 12.933 29.6 10.8A2 2 0 0 0 28 10h-8a2 2 0 0 0-1.6.8l-1.6 2.133a4 4 0 0 0-.8 2.4V26a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V15.333a4 4 0 0 0-.8-2.4M20 12h8l1.5 2h-11Zm6 10v4h-4v-4h-4l6-6 6 6Z"/>"##, +}; +pub(super) static FOLDER_PRISMA: Icon = Icon { + name: "folder-prisma", + view: 32.0, + body: r##"<path fill="#00bfa5" d="m13.844 7.536-1.288-1.072A2 2 0 0 0 11.276 6H4a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h24a2 2 0 0 0 2-2V10a2 2 0 0 0-2-2H15.124a2 2 0 0 1-1.28-.464"/><path fill="#a7ffeb" d="m30.209 26.275-9.76 2.39a.42.42 0 0 1-.51-.224.3.3 0 0 1-.012-.165l3.486-13.827a.35.35 0 0 1 .412-.21.34.34 0 0 1 .221.15l6.457 11.352a.362.362 0 0 1-.218.51zm1.672-.564-7.475-13.144a1.335 1.335 0 0 0-1.647-.453 1.2 1.2 0 0 0-.468.357l-8.106 10.873a.87.87 0 0 0 .014 1.092l3.964 5.083a1.41 1.41 0 0 0 1.432.435l11.503-2.816a1.22 1.22 0 0 0 .79-.567.86.86 0 0 0-.007-.86"/>"##, +}; +pub(super) static FOLDER_PRISMA_OPEN: Icon = Icon { + name: "folder-prisma-open", + view: 32.0, + body: r##"<path fill="#00bfa5" d="M28.967 12H9.442a2 2 0 0 0-1.898 1.368L4 24V10h24a2 2 0 0 0-2-2H15.124a2 2 0 0 1-1.28-.464l-1.288-1.072A2 2 0 0 0 11.276 6H4a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h22l4.805-11.212A2 2 0 0 0 28.967 12"/><path fill="#a7ffeb" d="m30.209 26.275-9.76 2.39a.42.42 0 0 1-.51-.224.3.3 0 0 1-.012-.165l3.486-13.827a.35.35 0 0 1 .412-.21.34.34 0 0 1 .221.15l6.457 11.352a.362.362 0 0 1-.218.51zm1.672-.564-7.475-13.144a1.335 1.335 0 0 0-1.647-.453 1.2 1.2 0 0 0-.468.357l-8.106 10.873a.87.87 0 0 0 .014 1.092l3.964 5.083a1.41 1.41 0 0 0 1.432.435l11.503-2.816a1.22 1.22 0 0 0 .79-.567.86.86 0 0 0-.007-.86"/>"##, +}; +pub(super) static FOLDER_PUBLIC: Icon = Icon { + name: "folder-public", + view: 32.0, + body: r##"<path fill="#039be5" d="m13.844 7.536-1.288-1.072A2 2 0 0 0 11.276 6H4a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h24a2 2 0 0 0 2-2V10a2 2 0 0 0-2-2H15.124a2 2 0 0 1-1.28-.464"/><path fill="#b3e5fc" d="M22 10a10 10 0 1 0 10 10 10 10 0 0 0-10-10m6.918 6H25.96a15.8 15.8 0 0 0-1.342-3.54 8.04 8.04 0 0 1 4.3 3.54M22 12a14.1 14.1 0 0 1 1.89 4h-3.78A14.1 14.1 0 0 1 22 12m-2.618.46A15.8 15.8 0 0 0 18.04 16h-2.958a8.04 8.04 0 0 1 4.3-3.54M14.263 22a7.7 7.7 0 0 1 0-4h3.407a15.5 15.5 0 0 0 0 4Zm.82 2h2.957a15.8 15.8 0 0 0 1.342 3.54 8.04 8.04 0 0 1-4.3-3.54ZM22 28a14.1 14.1 0 0 1-1.89-4h3.78A14.1 14.1 0 0 1 22 28m2.31-6h-4.62a13.4 13.4 0 0 1 0-4h4.62a13.4 13.4 0 0 1 0 4m.308 5.54A15.8 15.8 0 0 0 25.96 24h2.958a8.04 8.04 0 0 1-4.3 3.54M29.737 22H26.33a15.5 15.5 0 0 0 0-4h3.407a7.7 7.7 0 0 1 0 4"/>"##, +}; +pub(super) static FOLDER_PUBLIC_OPEN: Icon = Icon { + name: "folder-public-open", + view: 32.0, + body: r##"<path fill="#039be5" d="M28.967 12H9.442a2 2 0 0 0-1.898 1.368L4 24V10h24a2 2 0 0 0-2-2H15.124a2 2 0 0 1-1.28-.464l-1.288-1.072A2 2 0 0 0 11.276 6H4a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h22l4.805-11.212A2 2 0 0 0 28.967 12"/><path fill="#b3e5fc" d="M22 10a10 10 0 1 0 10 10 10 10 0 0 0-10-10m6.918 6H25.96a15.8 15.8 0 0 0-1.342-3.54 8.04 8.04 0 0 1 4.3 3.54M22 12a14.1 14.1 0 0 1 1.89 4h-3.78A14.1 14.1 0 0 1 22 12m-2.618.46A15.8 15.8 0 0 0 18.04 16h-2.958a8.04 8.04 0 0 1 4.3-3.54M14.263 22a7.7 7.7 0 0 1 0-4h3.407a15.5 15.5 0 0 0 0 4Zm.82 2h2.957a15.8 15.8 0 0 0 1.342 3.54 8.04 8.04 0 0 1-4.3-3.54ZM22 28a14.1 14.1 0 0 1-1.89-4h3.78A14.1 14.1 0 0 1 22 28m2.31-6h-4.62a13.4 13.4 0 0 1 0-4h4.62a13.4 13.4 0 0 1 0 4m.308 5.54A15.8 15.8 0 0 0 25.96 24h2.958a8.04 8.04 0 0 1-4.3 3.54M29.737 22H26.33a15.5 15.5 0 0 0 0-4h3.407a7.7 7.7 0 0 1 0 4"/>"##, +}; +pub(super) static FOLDER_QUEUE: Icon = Icon { + name: "folder-queue", + view: 32.0, + body: r##"<path fill="#039be5" d="m13.844 7.536-1.288-1.072A2 2 0 0 0 11.276 6H4a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h24a2 2 0 0 0 2-2V10a2 2 0 0 0-2-2H15.124a2 2 0 0 1-1.28-.464"/><path fill="#b3e5fc" d="M24 16v-2h-3a1 1 0 0 0-1 1v10a1 1 0 0 0 1 1h3v-2h-2v-8Zm8-2v-2h-5a1 1 0 0 0-1 1v14a1 1 0 0 0 1 1h5v-2h-4V14Zm-16 2h2v8h-2z"/>"##, +}; +pub(super) static FOLDER_QUEUE_OPEN: Icon = Icon { + name: "folder-queue-open", + view: 32.0, + body: r##"<path fill="#039be5" d="M28.967 12H9.442a2 2 0 0 0-1.898 1.368L4 24V10h24a2 2 0 0 0-2-2H15.124a2 2 0 0 1-1.28-.464l-1.288-1.072A2 2 0 0 0 11.276 6H4a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h22l4.805-11.212A2 2 0 0 0 28.967 12"/><path fill="#b3e5fc" d="M24 16v-2h-3a1 1 0 0 0-1 1v10a1 1 0 0 0 1 1h3v-2h-2v-8Zm8-2v-2h-5a1 1 0 0 0-1 1v14a1 1 0 0 0 1 1h5v-2h-4V14Zm-16 2h2v8h-2z"/>"##, +}; +pub(super) static FOLDER_REDUX_REDUCER: Icon = Icon { + name: "folder-redux-reducer", + view: 32.0, + body: r##"<path fill="#ef5350" d="m13.844 7.536-1.288-1.072A2 2 0 0 0 11.276 6H4a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h24a2 2 0 0 0 2-2V10a2 2 0 0 0-2-2H15.124a2 2 0 0 1-1.28-.464"/><path fill="#ffcdd2" stroke="#ffcdd2" stroke-linejoin="round" stroke-width=".293" d="M25.948 24.114a1.65 1.65 0 0 0 .97-.6 1.8 1.8 0 0 0 .381-1.274 1.72 1.72 0 0 0-1.69-1.596h-.06a1.724 1.724 0 0 0-1.61 1.814 1.85 1.85 0 0 0 .34.985 8.85 8.85 0 0 1-3.863 3.799 6.15 6.15 0 0 1-3.876.771 3.13 3.13 0 0 1-2.32-1.411 3.67 3.67 0 0 1-.18-3.738 5.8 5.8 0 0 1 1.605-1.986.3.3 0 0 0 .098-.313 14 14 0 0 1-.315-1.298.29.29 0 0 0-.172-.213.28.28 0 0 0-.272.036c-3.731 2.836-3.326 6.763-2.188 8.579a5.36 5.36 0 0 0 4.294 2.229q.125 0 .24-.005h.04a6 6 0 0 0 1.5-.188 9.88 9.88 0 0 0 7.078-5.591Z"/><path fill="#ffcdd2" stroke="#ffcdd2" stroke-linejoin="round" stroke-width=".293" d="M30.327 20.428a10.12 10.12 0 0 0-7.774-3.69q-.133 0-.265.003h-.234a1.61 1.61 0 0 0-1.377-.78h-.053a1.62 1.62 0 0 0-1.175.535 1.806 1.806 0 0 0 .039 2.466 1.67 1.67 0 0 0 1.19.494h.064a1.68 1.68 0 0 0 1.375-.886h.27a8.83 8.83 0 0 1 5.126 1.646 6.6 6.6 0 0 1 2.522 3.202 3.48 3.48 0 0 1-.046 2.831 3.39 3.39 0 0 1-3.137 1.97 5.8 5.8 0 0 1-2.32-.522.27.27 0 0 0-.304.054 14 14 0 0 1-1.088.912.294.294 0 0 0 .039.495 7.7 7.7 0 0 0 3.313.84l.192.002a5.66 5.66 0 0 0 4.886-2.948 6.39 6.39 0 0 0-1.243-6.624Z"/><path fill="#ffcdd2" stroke="#ffcdd2" stroke-linejoin="round" stroke-width=".293" d="m17.249 24.295.123-.01-.123.02a1.705 1.705 0 0 0 1.67 1.682h.053a1.715 1.715 0 0 0 1.64-1.778 1.78 1.78 0 0 0-.507-1.224 1.6 1.6 0 0 0-1.187-.493h-.076a9.6 9.6 0 0 1-1.154-5.448 6.83 6.83 0 0 1 1.39-3.853 3.97 3.97 0 0 1 2.842-1.363h.055c2.438 0 3.415 3.34 3.477 4.491a.29.29 0 0 0 .216.265c.299.073.822.246 1.213.384a.27.27 0 0 0 .266-.048.3.3 0 0 0 .105-.247C26.928 12.088 24.204 10 21.804 10a5.96 5.96 0 0 0-5.36 4.39 11.38 11.38 0 0 0 .936 9.155 1.5 1.5 0 0 0-.131.75Z"/>"##, +}; +pub(super) static FOLDER_REDUX_REDUCER_OPEN: Icon = Icon { + name: "folder-redux-reducer-open", + view: 32.0, + body: r##"<path fill="#ef5350" d="M28.967 12H9.442a2 2 0 0 0-1.898 1.368L4 24V10h24a2 2 0 0 0-2-2H15.124a2 2 0 0 1-1.28-.464l-1.288-1.072A2 2 0 0 0 11.276 6H4a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h22l4.805-11.212A2 2 0 0 0 28.967 12"/><path fill="#ffcdd2" stroke="#ffcdd2" stroke-linejoin="round" stroke-width=".293" d="M25.948 24.114a1.65 1.65 0 0 0 .97-.6 1.8 1.8 0 0 0 .381-1.274 1.72 1.72 0 0 0-1.69-1.596h-.06a1.724 1.724 0 0 0-1.61 1.814 1.85 1.85 0 0 0 .34.985 8.85 8.85 0 0 1-3.863 3.799 6.15 6.15 0 0 1-3.876.771 3.13 3.13 0 0 1-2.32-1.411 3.67 3.67 0 0 1-.18-3.738 5.8 5.8 0 0 1 1.605-1.986.3.3 0 0 0 .098-.313 14 14 0 0 1-.315-1.298.29.29 0 0 0-.172-.213.28.28 0 0 0-.272.036c-3.731 2.836-3.326 6.763-2.188 8.579a5.36 5.36 0 0 0 4.294 2.229q.125 0 .24-.005h.04a6 6 0 0 0 1.5-.188 9.88 9.88 0 0 0 7.078-5.591Z"/><path fill="#ffcdd2" stroke="#ffcdd2" stroke-linejoin="round" stroke-width=".293" d="M30.327 20.428a10.12 10.12 0 0 0-7.774-3.69q-.133 0-.265.003h-.234a1.61 1.61 0 0 0-1.377-.78h-.053a1.62 1.62 0 0 0-1.175.535 1.806 1.806 0 0 0 .039 2.466 1.67 1.67 0 0 0 1.19.494h.064a1.68 1.68 0 0 0 1.375-.886h.27a8.83 8.83 0 0 1 5.126 1.646 6.6 6.6 0 0 1 2.522 3.202 3.48 3.48 0 0 1-.046 2.831 3.39 3.39 0 0 1-3.137 1.97 5.8 5.8 0 0 1-2.32-.522.27.27 0 0 0-.304.054 14 14 0 0 1-1.088.912.294.294 0 0 0 .039.495 7.7 7.7 0 0 0 3.313.84l.192.002a5.66 5.66 0 0 0 4.886-2.948 6.39 6.39 0 0 0-1.243-6.624Z"/><path fill="#ffcdd2" stroke="#ffcdd2" stroke-linejoin="round" stroke-width=".293" d="m17.249 24.295.123-.01-.123.02a1.705 1.705 0 0 0 1.67 1.682h.053a1.715 1.715 0 0 0 1.64-1.778 1.78 1.78 0 0 0-.507-1.224 1.6 1.6 0 0 0-1.187-.493h-.076a9.6 9.6 0 0 1-1.154-5.448 6.83 6.83 0 0 1 1.39-3.853 3.97 3.97 0 0 1 2.842-1.363h.055c2.438 0 3.415 3.34 3.477 4.491a.29.29 0 0 0 .216.265c.299.073.822.246 1.213.384a.27.27 0 0 0 .266-.048.3.3 0 0 0 .105-.247C26.928 12.088 24.204 10 21.804 10a5.96 5.96 0 0 0-5.36 4.39 11.38 11.38 0 0 0 .936 9.155 1.5 1.5 0 0 0-.131.75Z"/>"##, +}; +pub(super) static FOLDER_ROUTES: Icon = Icon { + name: "folder-routes", + view: 32.0, + body: r##"<path fill="#43a047" d="m13.844 7.536-1.288-1.072A2 2 0 0 0 11.276 6H4a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h24a2 2 0 0 0 2-2V10a2 2 0 0 0-2-2H15.124a2 2 0 0 1-1.28-.464"/><path fill="#c8e6c9" d="M17.414 14.586 20 12h-8v8l2.586-2.586 4.91 4.91A1.7 1.7 0 0 1 20 23.541V28h4v-4.459a5.68 5.68 0 0 0-1.676-4.045ZM29.36 12l-5.61 4.93.57.57a5.6 5.6 0 0 1 1.56 2.89L32 15.01Z"/>"##, +}; +pub(super) static FOLDER_ROUTES_OPEN: Icon = Icon { + name: "folder-routes-open", + view: 32.0, + body: r##"<path fill="#43a047" d="M28.967 12H9.442a2 2 0 0 0-1.898 1.368L4 24V10h24a2 2 0 0 0-2-2H15.124a2 2 0 0 1-1.28-.464l-1.288-1.072A2 2 0 0 0 11.276 6H4a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h22l4.805-11.212A2 2 0 0 0 28.967 12"/><path fill="#c8e6c9" d="M17.414 14.586 20 12h-8v8l2.586-2.586 4.91 4.91A1.7 1.7 0 0 1 20 23.541V28h4v-4.459a5.68 5.68 0 0 0-1.676-4.045ZM29.36 12l-5.61 4.93.57.57a5.6 5.6 0 0 1 1.56 2.89L32 15.01Z"/>"##, +}; +pub(super) static FOLDER_SASS: Icon = Icon { + name: "folder-sass", + view: 32.0, + body: r##"<path fill="#f06292" d="m13.844 7.536-1.288-1.072A2 2 0 0 0 11.276 6H4a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h24a2 2 0 0 0 2-2V10a2 2 0 0 0-2-2H15.124a2 2 0 0 1-1.28-.464"/><path fill="#fce4ec" d="M31.897 12.592a3 3 0 0 0-1.53-1.912 7.95 7.95 0 0 0-6.348-.05 17.4 17.4 0 0 0-5.864 3.557c-1.83 1.81-2.288 3.496-2.124 4.39.346 1.89 2.181 3.227 3.658 4.3.314.23.618.45.876.657-.92.513-2.916 1.749-3.483 3.074a2.9 2.9 0 0 0-.074 2.347 1.57 1.57 0 0 0 .874.903 3.5 3.5 0 0 0 .986.142 4.14 4.14 0 0 0 3.438-2.025 5.03 5.03 0 0 0 .55-3.886 4.5 4.5 0 0 1 1.46-.034 2.64 2.64 0 0 1 1.927.96 1.44 1.44 0 0 1 .304.968 1.2 1.2 0 0 1-.55.805c-.159.104-.356.233-.31.504.028.151.13.393.532.313a1.99 1.99 0 0 0 1.392-1.841 2.9 2.9 0 0 0-.801-2.051 3.9 3.9 0 0 0-2.897-1.135 6.5 6.5 0 0 0-1.813.226 13 13 0 0 0-1.498-1.346c-1.165-.947-2.265-1.842-2.2-3.125.085-1.654 1.672-3.306 4.716-4.909 2.7-1.422 4.894-1.47 6.04-1.041a1.44 1.44 0 0 1 .858.674 2.23 2.23 0 0 1-.257 1.866 6.57 6.57 0 0 1-5.023 3.105 2.56 2.56 0 0 1-2.225-.565c-.189-.219-.37-.423-.65-.263-.332.196-.175.625-.123.768a2.6 2.6 0 0 0 1.578 1.342 7.32 7.32 0 0 0 4.752-.482c2.631-1.078 4.384-3.933 3.83-6.236ZM21.301 26.118a3 3 0 0 1-.13.345 3.4 3.4 0 0 1-.517.795c-.648.743-1.499.978-1.776.808a.27.27 0 0 1-.088-.187 2.5 2.5 0 0 1 .742-1.704 7.8 7.8 0 0 1 1.865-1.445 3.05 3.05 0 0 1-.096 1.388"/>"##, +}; +pub(super) static FOLDER_SASS_OPEN: Icon = Icon { + name: "folder-sass-open", + view: 32.0, + body: r##"<path fill="#f06292" d="M28.967 12H9.442a2 2 0 0 0-1.898 1.368L4 24V10h24a2 2 0 0 0-2-2H15.124a2 2 0 0 1-1.28-.464l-1.288-1.072A2 2 0 0 0 11.276 6H4a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h22l4.805-11.212A2 2 0 0 0 28.967 12"/><path fill="#fce4ec" d="M31.897 12.592a3 3 0 0 0-1.53-1.912 7.95 7.95 0 0 0-6.348-.05 17.4 17.4 0 0 0-5.864 3.557c-1.83 1.81-2.288 3.496-2.124 4.39.346 1.89 2.181 3.227 3.658 4.3.314.23.618.45.876.657-.92.513-2.916 1.749-3.483 3.074a2.9 2.9 0 0 0-.074 2.347 1.57 1.57 0 0 0 .874.903 3.5 3.5 0 0 0 .986.142 4.14 4.14 0 0 0 3.438-2.025 5.03 5.03 0 0 0 .55-3.886 4.5 4.5 0 0 1 1.46-.034 2.64 2.64 0 0 1 1.927.96 1.44 1.44 0 0 1 .304.968 1.2 1.2 0 0 1-.55.805c-.159.104-.356.233-.31.504.028.151.13.393.532.313a1.99 1.99 0 0 0 1.392-1.841 2.9 2.9 0 0 0-.801-2.051 3.9 3.9 0 0 0-2.897-1.135 6.5 6.5 0 0 0-1.813.226 13 13 0 0 0-1.498-1.346c-1.165-.947-2.265-1.842-2.2-3.125.085-1.654 1.672-3.306 4.716-4.909 2.7-1.422 4.894-1.47 6.04-1.041a1.44 1.44 0 0 1 .858.674 2.23 2.23 0 0 1-.257 1.866 6.57 6.57 0 0 1-5.023 3.105 2.56 2.56 0 0 1-2.225-.565c-.189-.219-.37-.423-.65-.263-.332.196-.175.625-.123.768a2.6 2.6 0 0 0 1.578 1.342 7.32 7.32 0 0 0 4.752-.482c2.631-1.078 4.384-3.933 3.83-6.236ZM21.301 26.118a3 3 0 0 1-.13.345 3.4 3.4 0 0 1-.517.795c-.648.743-1.499.978-1.776.808a.27.27 0 0 1-.088-.187 2.5 2.5 0 0 1 .742-1.704 7.8 7.8 0 0 1 1.865-1.445 3.05 3.05 0 0 1-.096 1.388"/>"##, +}; +pub(super) static FOLDER_SCRIPTS: Icon = Icon { + name: "folder-scripts", + view: 32.0, + body: r##"<path fill="currentColor" d="m13.844 7.536-1.288-1.072A2 2 0 0 0 11.276 6H4a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h24a2 2 0 0 0 2-2V10a2 2 0 0 0-2-2H15.124a2 2 0 0 1-1.28-.464" /><path fill="#cfd8dc" d="M28 12h-6a4 4 0 0 0-4 4v8h2v-8h8v9.893a2.074 2.074 0 0 1-1.664 2.08A2 2 0 0 1 24 26h-8a4 4 0 0 0 4 4h6a4 4 0 0 0 4-4V16h2a4 4 0 0 0-4-4" />"##, +}; +pub(super) static FOLDER_SCRIPTS_OPEN: Icon = Icon { + name: "folder-scripts-open", + view: 32.0, + body: r##"<path fill="currentColor" d="M28.967 12H9.442a2 2 0 0 0-1.898 1.368L4 24V10h24a2 2 0 0 0-2-2H15.124a2 2 0 0 1-1.28-.464l-1.288-1.072A2 2 0 0 0 11.276 6H4a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h22l4.805-11.212A2 2 0 0 0 28.967 12" /><path fill="#cfd8dc" d="M28 12h-6a4 4 0 0 0-4 4v8h2v-8h8v9.893a2.074 2.074 0 0 1-1.664 2.08A2 2 0 0 1 24 26h-8a4 4 0 0 0 4 4h6a4 4 0 0 0 4-4V16h2a4 4 0 0 0-4-4" />"##, +}; +pub(super) static FOLDER_SECURE: Icon = Icon { + name: "folder-secure", + view: 32.0, + body: r##"<path fill="#f9a825" d="m13.844 7.536-1.288-1.072A2 2 0 0 0 11.276 6H4a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h24a2 2 0 0 0 2-2V10a2 2 0 0 0-2-2H15.124a2 2 0 0 1-1.28-.464"/><path fill="#fff9c4" d="M28 16v-3.828a4.116 4.116 0 0 0-3.607-4.153A4 4 0 0 0 20 12v4h-2a2 2 0 0 0-2 2v8a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-8a2 2 0 0 0-2-2Zm-4 8a2 2 0 1 1 2-2 2 2 0 0 1-2 2m2-8h-4v-4a2 2 0 0 1 4 0Z"/>"##, +}; +pub(super) static FOLDER_SECURE_OPEN: Icon = Icon { + name: "folder-secure-open", + view: 32.0, + body: r##"<path fill="#f9a825" d="M28.967 12H9.442a2 2 0 0 0-1.898 1.368L4 24V10h24a2 2 0 0 0-2-2H15.124a2 2 0 0 1-1.28-.464l-1.288-1.072A2 2 0 0 0 11.276 6H4a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h22l4.805-11.212A2 2 0 0 0 28.967 12"/><path fill="#fff9c4" d="M28 16v-3.828a4.116 4.116 0 0 0-3.607-4.153A4 4 0 0 0 20 12v4h-2a2 2 0 0 0-2 2v8a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-8a2 2 0 0 0-2-2Zm-4 8a2 2 0 1 1 2-2 2 2 0 0 1-2 2m2-8h-4v-4a2 2 0 0 1 4 0Z"/>"##, +}; +pub(super) static FOLDER_SEEDERS: Icon = Icon { + name: "folder-seeders", + view: 3200.0, + body: r##"<g clip-rule="evenodd" image-rendering="optimizeQuality" shape-rendering="geometricPrecision" text-rendering="geometricPrecision"><path fill="#43a047" d="M2999.5 1165.5c-30.43-3.18-61.1-6.35-92-9.5-167.75-14.9-334.08-5.57-499 28a1455 1455 0 0 0-207 61c-79.51 31.74-154.18 71.74-224 120a896 896 0 0 0-55 43c-1 .33-2 .67-3 1-46.92 39.92-90.09 83.42-129.5 130.5a1986 1986 0 0 1-45 60c-61.77 91.89-109.44 190.89-143 297a1660.6 1660.6 0 0 0-53 246c-14.98 118.89-19.98 238.22-15 358 1.34 33.03 3.17 66.03 5.5 99-386.33.17-772.67 0-1159-.5q-122.657-16.17-169.5-130.5a230.2 230.2 0 0 1-11-49c-.667-546.67-.667-1093.3 0-1640 9.834-76.145 49.334-130.64 118.5-163.5q29.688-12.892 62-16c255.33-.667 510.67-.667 766 0 43.68 4.875 82.01 21.541 115 50 45.37 38.377 91.04 76.377 137 114 28.54 18.847 59.87 30.181 94 34q662.985 1.986 1326 2c77.31 10.044 132.48 50.211 165.5 120.5a220.4 220.4 0 0 1 15 60c.5 61.67.67 123.33.5 185"/><path fill="#a5d6a7" d="M2999.5 1165.5c17.69 2.74 35.36 5.91 53 9.5 1.08.67 1.75 1.67 2 3 28.18 168.19 32.68 337.02 13.5 506.5-11.97 104.19-34.8 205.86-68.5 305-33.03 92.41-76.87 179.07-131.5 260a1694 1694 0 0 1-77 97 2240 2240 0 0 1-80.5 78.5c-46.48 38.13-95.48 72.8-147 104a1457 1457 0 0 1-145 70.5c-24.7 9.85-49.7 19.01-75 27.5-149 44.89-301.33 68.89-457 72-64.06 1.52-128.06.19-192-4-49.39-3.53-98.73-7.7-148-12.5a1745 1745 0 0 1-7-83 3304 3304 0 0 1-5.5-99c-4.98-119.78.02-239.11 15-358a1660.6 1660.6 0 0 1 53-246c33.56-106.11 81.23-205.11 143-297q23.07-29.58 45-60c39.41-47.08 82.58-90.58 129.5-130.5 1-.33 2-.67 3-1a896 896 0 0 1 55-43c69.82-48.26 144.49-88.26 224-120a1455 1455 0 0 1 207-61c164.92-33.57 331.25-42.9 499-28 30.9 3.15 61.57 6.32 92 9.5" opacity=".999"/><path fill="#43a047" d="M2709.5 1494.5c7.67-.17 15.34 0 23 .5a825 825 0 0 0-130 61c-97.27 54.78-187.6 119.12-271 193-15.7 14.7-31.7 29.04-48 43a4541 4541 0 0 0-111.5 115.5 2730 2730 0 0 1-57 68c-93.1 116.73-172.93 242.4-239.5 377-.5 1.02-1.17 1.19-2 .5 6.63-168.23 50.47-326.06 131.5-473.5 116.36-197.54 287.53-319.37 513.5-365.5 24.5-4.98 49.17-8.98 74-12q58.635-5.25 117-7.5"/><path fill="#43a047" d="M2999.5 1989.5c.17 143 0 286-.5 429-8.62 70.79-43.78 123.62-105.5 158.5q-31.365 15.615-66 21c-136.31 1.48-272.65 1.98-409 1.5 49.63-20.82 97.96-44.32 145-70.5 51.52-31.2 100.52-65.87 147-104a2240 2240 0 0 0 80.5-78.5c26.87-31.42 52.54-63.76 77-97 54.63-80.93 98.47-167.59 131.5-260" opacity=".999"/></g>"##, +}; +pub(super) static FOLDER_SEEDERS_OPEN: Icon = Icon { + name: "folder-seeders-open", + view: 3200.0, + body: r##"<g clip-rule="evenodd" image-rendering="optimizeQuality" shape-rendering="geometricPrecision" text-rendering="geometricPrecision"><path fill="#43a047" d="M2340.5 1199.5c-18.05 5.55-36.72 11.21-56 17a565 565 0 0 0-62 21q-441.75 165.75-603 609c-2.04 4.44-3.7 9.11-5 14-1.4 3.2-2.4 6.53-3 10-3.64 7.59-6.31 15.59-8 24-2.11 4-3.44 8.34-4 13-.61.89-.94 1.89-1 3-1.78 3-2.78 6.34-3 10-.67 2.67-1.33 5.33-2 8-1.57 1.6-2.24 3.6-2 6-.92 2.92-1.58 5.92-2 9-1.9 2.2-2.9 4.86-3 8-.33 2-.67 4-1 6-1.42 2.01-2.09 4.35-2 7v1c-.62.11-1.12.44-1.5 1a103 103 0 0 0-3.5 17c-21.96 92.4-35.63 186.07-41 281a821 821 0 0 0-4 73v2c-1.16 46.16-1.33 92.5-.5 139 .89 16.16 1.73 32.16 2.5 48v11c.18 7.19.85 14.19 2 21 .47 13.68 1.13 27.34 2 41-386.33.17-772.67 0-1159-.5q-122.657-16.17-169.5-130.5a230.2 230.2 0 0 1-11-49c-.667-546.67-.667-1093.3 0-1640 9.834-76.145 49.334-130.64 118.5-163.5q29.688-12.892 62-16 387.03-1.49 774 1c40.68 5.845 76.34 22.178 107 49 45.37 38.377 91.04 76.377 137 114 33.84 22.572 71.17 34.238 112 35l1108 1q101.4 12.037 154.5 98.5c17.74 31.305 26.58 64.972 26.5 101h-2400c-.167 465.67 0 931.33.5 1397l357-1071c28.15-65.48 76.984-106.31 146.5-122.5a307 307 0 0 1 20-3c472.33-.5 944.67-.67 1417-.5" opacity=".999"/><path fill="#a5d6a7" d="M3071.5 1301.5c-1.15 5.48-1.32 11.15-.5 17 .28.92.78 1.58 1.5 2v4c-.17 6.34 0 12.68.5 19q.345 1.86 1.5 3v5c-.32 9.22.34 18.22 2 27v10c.15 12.67.49 25.34 1 38-.17 19 0 38 .5 57 .28-.92.78-1.58 1.5-2q.585 196.035-43.5 387c-27.87 114.37-71.2 222.37-130 324-21.76 34.53-44.76 68.2-69 101a1351 1351 0 0 1-82.5 92.5c-16.67 15-33.33 30-50 45a2628 2628 0 0 1-49 38.5c-73.84 51.95-153.18 95.28-238 130-60.65 24.38-122.99 43.88-187 58.5-113.01 24.48-227.35 38.15-343 41-68.76 1.79-137.42.13-206-5-45.06-3.26-90.06-7.1-135-11.5-3.11-27.6-5.45-55.26-7-83-.87-13.66-1.53-27.32-2-41 .24-7.23-.43-14.23-2-21v-11c-1.58-62.32-2.25-124.66-2-187v-2c.82-2.47 1.32-5.14 1.5-8 1.01-21.66 1.84-43.33 2.5-65 5.37-94.93 19.04-188.6 41-281 1.96-5.81 3.62-11.81 5-18v-1c1.42-2.01 2.09-4.35 2-7 .33-2 .67-4 1-6 1.6-2.35 2.6-5.01 3-8 .42-3.08 1.08-6.08 2-9 1.57-1.6 2.24-3.6 2-6 .67-2.67 1.33-5.33 2-8 1.78-3 2.78-6.34 3-10 .06-1.11.39-2.11 1-3 2.11-4 3.44-8.34 4-13a169 169 0 0 0 8-24c.6-3.47 1.6-6.8 3-10 2.82-4.13 4.49-8.8 5-14q161.25-443.25 603-609c20.86-6.62 41.53-13.62 62-21 19.28-5.79 37.95-11.45 56-17 29.89-8.48 60.22-15.65 91-21.5 191.75-33.99 384.08-37.66 577-11 14.64 2.55 29.3 4.88 44 7 1.2.9 2.03 2.07 2.5 3.5 6.67 41.19 12.17 82.52 16.5 124"/><path fill="#43a047" d="M3071.5 1303.5c19.44 34.7 27.61 72.03 24.5 112-1.77 22.43-7.27 43.77-16.5 64 .23-17.69-.1-35.35-1-53 .06-12.86-.61-25.53-2-38v-10c-.22-9.18-.88-18.18-2-27v-5c-.13-7.53-.79-14.86-2-22v-4c-.26-5.67-.59-11.34-1-17m-398 192h1c17.51-.33 34.84 0 52 1-1.33.67-2.67 1.33-4 2-3.65.77-6.98 2.1-10 4a950 950 0 0 0-105 50.5c-121.59 68.07-232.26 150.91-332 248.5a178.3 178.3 0 0 0-23 22c-96.64 96.09-181.81 201.09-255.5 315a2166 2166 0 0 0-119.5 210c-1.41.47-2.07 1.47-2 3v1q-1.17-19.245 0-39v-2c1.45-5.77 2.11-11.77 2-18 .24-7.06.91-14.06 2-21 1.75-6.43 2.75-13.09 3-20v-1c2.07-8.76 3.4-17.76 4-27v-2c1.72-3.34 2.38-7.01 2-11 2.57-6.3 3.9-12.97 4-20 .03-4.14.7-8.14 2-12 1.42-2.01 2.09-4.35 2-7v-2c2.54-3.85 3.54-8.19 3-13 17.15-76.63 42.32-150.3 75.5-221 51.76-109.33 124.93-201.83 219.5-277.5 91.03-69.67 193.03-116.5 306-140.5 4.81.54 9.15-.46 13-3 9.03-.41 17.7-2.07 26-5 8.58-.59 16.91-1.92 25-4 6.91-.25 13.57-1.25 20-3 6.26-1.24 12.59-1.91 19-2 14.8-1.38 29.47-2.72 44-4h2c8.18-.28 16.18-.94 24-2"/></g>"##, +}; +pub(super) static FOLDER_SERVERLESS: Icon = Icon { + name: "folder-serverless", + view: 32.0, + body: r##"<path fill="#ef5350" d="m13.844 7.536-1.288-1.072A2 2 0 0 0 11.276 6H4a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h24a2 2 0 0 0 2-2V10a2 2 0 0 0-2-2H15.124a2 2 0 0 1-1.28-.464"/><path fill="#ffcdd2" d="M14 14h6l-.8 3H14zm18 0v3h-9.8l.8-3zm-18 6h4.4l-.8 3H14zm18 0v3H20.6l.8-3zm-18 6h2.8l-.8 3h-2zm18 0v3H19l.8-3z"/>"##, +}; +pub(super) static FOLDER_SERVERLESS_OPEN: Icon = Icon { + name: "folder-serverless-open", + view: 32.0, + body: r##"<path fill="#ef5350" d="M28.967 12H9.442a2 2 0 0 0-1.898 1.368L4 24V10h24a2 2 0 0 0-2-2H15.124a2 2 0 0 1-1.28-.464l-1.288-1.072A2 2 0 0 0 11.276 6H4a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h22l4.805-11.212A2 2 0 0 0 28.967 12"/><path fill="#ffcdd2" d="M14 14h6l-.8 3H14zm18 0v3h-9.8l.8-3zm-18 6h4.4l-.8 3H14zm18 0v3H20.6l.8-3zm-18 6h2.8l-.8 3h-2zm18 0v3H19l.8-3z"/>"##, +}; +pub(super) static FOLDER_SRC: Icon = Icon { + name: "folder-src", + view: 32.0, + body: r##"<path fill="#4caf50" d="m13.844 7.536-1.288-1.072A2 2 0 0 0 11.276 6H4a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h24a2 2 0 0 0 2-2V10a2 2 0 0 0-2-2H15.124a2 2 0 0 1-1.28-.464"/><path fill="#c8e6c9" d="M18.435 30a1 1 0 0 1-.238-.028 1.137 1.137 0 0 1-.828-1.323l3.093-15.744a1.13 1.13 0 0 1 .507-.744 1.06 1.06 0 0 1 .8-.134 1.14 1.14 0 0 1 .828 1.324l-3.1 15.744a1.12 1.12 0 0 1-.505.743 1.06 1.06 0 0 1-.557.162m6.2-2h-.077a1.08 1.08 0 0 1-.762-.412 1.164 1.164 0 0 1 .113-1.548l5.32-4.967-5.297-4.623a1.165 1.165 0 0 1-.162-1.544 1.08 1.08 0 0 1 .754-.437 1.06 1.06 0 0 1 .81.258l6.244 5.455a1.156 1.156 0 0 1 .004 1.723l-6.22 5.808a1.07 1.07 0 0 1-.728.289Zm-9.31 0a1.07 1.07 0 0 1-.728-.292l-6.225-5.811a1.16 1.16 0 0 1-.01-1.692l.02-.018 6.246-5.454a1.03 1.03 0 0 1 .8-.26 1.08 1.08 0 0 1 .758.436 1.165 1.165 0 0 1-.16 1.547l-5.293 4.62 5.32 4.964a1.156 1.156 0 0 1 .112 1.548 1.07 1.07 0 0 1-.762.412Z"/>"##, +}; +pub(super) static FOLDER_SRC_OPEN: Icon = Icon { + name: "folder-src-open", + view: 32.0, + body: r##"<path fill="#4caf50" d="M28.967 12H9.442a2 2 0 0 0-1.898 1.368L4 24V10h24a2 2 0 0 0-2-2H15.124a2 2 0 0 1-1.28-.464l-1.288-1.072A2 2 0 0 0 11.276 6H4a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h22l4.805-11.212A2 2 0 0 0 28.967 12"/><path fill="#c8e6c9" d="M18.473 30a1 1 0 0 1-.238-.028 1.137 1.137 0 0 1-.828-1.323L20.5 12.905a1.13 1.13 0 0 1 .507-.744 1.06 1.06 0 0 1 .8-.134 1.14 1.14 0 0 1 .828 1.324l-3.101 15.744a1.12 1.12 0 0 1-.504.743 1.06 1.06 0 0 1-.557.162m6.2-2h-.077a1.08 1.08 0 0 1-.762-.412 1.164 1.164 0 0 1 .113-1.548l5.319-4.967-5.296-4.623a1.165 1.165 0 0 1-.162-1.544 1.08 1.08 0 0 1 .754-.437 1.06 1.06 0 0 1 .81.258l6.244 5.455a1.156 1.156 0 0 1 .003 1.723l-6.218 5.808a1.07 1.07 0 0 1-.729.289Zm-9.31 0a1.07 1.07 0 0 1-.728-.292l-6.226-5.811a1.16 1.16 0 0 1-.01-1.692l.02-.018 6.246-5.454a1.03 1.03 0 0 1 .8-.26 1.08 1.08 0 0 1 .76.436 1.165 1.165 0 0 1-.16 1.547l-5.294 4.62 5.32 4.964a1.156 1.156 0 0 1 .112 1.548 1.07 1.07 0 0 1-.762.412Z"/>"##, +}; +pub(super) static FOLDER_STORE: Icon = Icon { + name: "folder-store", + view: 32.0, + body: r##"<path fill="#ff7043" d="m13.844 7.536-1.288-1.072A2 2 0 0 0 11.276 6H4a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h24a2 2 0 0 0 2-2V10a2 2 0 0 0-2-2H15.124a2 2 0 0 1-1.28-.464"/><path fill="#ffccbc" d="M22 26h-6v-6h6m10 0v-2l-2-4H14l-2 4v2h2v8h10v-8h4v8h2v-8m0-10H14v2h16z"/>"##, +}; +pub(super) static FOLDER_STORE_OPEN: Icon = Icon { + name: "folder-store-open", + view: 32.0, + body: r##"<path fill="#ff7043" d="M28.967 12H9.442a2 2 0 0 0-1.898 1.368L4 24V10h24a2 2 0 0 0-2-2H15.124a2 2 0 0 1-1.28-.464l-1.288-1.072A2 2 0 0 0 11.276 6H4a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h22l4.805-11.212A2 2 0 0 0 28.967 12"/><path fill="#ffccbc" d="M22 26h-6v-6h6m10 0v-2l-2-4H14l-2 4v2h2v8h10v-8h4v8h2v-8m0-10H14v2h16z"/>"##, +}; +pub(super) static FOLDER_STORYBOOK: Icon = Icon { + name: "folder-storybook", + view: 32.0, + body: r##"<path fill="#ff4081" d="m13.844 7.536-1.288-1.072A2 2 0 0 0 11.276 6H4a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h24a2 2 0 0 0 2-2V10a2 2 0 0 0-2-2H15.124a2 2 0 0 1-1.28-.464"/><path fill="#ffcdd2" d="M23.506 15.814c0 .543 3.755.286 4.262-.1 0-3.743-2.044-5.714-5.784-5.714-3.726 0-5.814 2-5.814 5 0 5.214 7.147 5.314 7.147 8.157a1.147 1.147 0 0 1-1.275 1.286c-1.146 0-1.595-.572-1.537-2.529 0-.428-4.35-.557-4.48 0C15.692 26.63 18.678 28 22.1 28c3.29 0 5.9-1.743 5.9-4.886 0-5.6-7.248-5.443-7.248-8.214a1.193 1.193 0 0 1 1.348-1.286c.522 0 1.478.1 1.391 2.2ZM6 10.492l.192-4.673h3.654L10 10.34a.288.288 0 0 1-.462.23L8.135 9.454l-1.673 1.27A.288.288 0 0 1 6 10.491Z"/>"##, +}; +pub(super) static FOLDER_STORYBOOK_OPEN: Icon = Icon { + name: "folder-storybook-open", + view: 32.0, + body: r##"<path fill="#ff4081" d="M28.967 12H9.442a2 2 0 0 0-1.898 1.368L4 24V10h24a2 2 0 0 0-2-2H15.124a2 2 0 0 1-1.28-.464l-1.288-1.072A2 2 0 0 0 11.276 6H4a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h22l4.805-11.212A2 2 0 0 0 28.967 12"/><path fill="#ffcdd2" d="M23.506 15.814c0 .543 3.755.286 4.262-.1 0-3.743-2.044-5.714-5.784-5.714-3.726 0-5.814 2-5.814 5 0 5.214 7.147 5.314 7.147 8.157a1.147 1.147 0 0 1-1.275 1.286c-1.146 0-1.595-.572-1.537-2.529 0-.428-4.35-.557-4.48 0C15.692 26.63 18.678 28 22.1 28c3.29 0 5.9-1.743 5.9-4.886 0-5.6-7.248-5.443-7.248-8.214a1.193 1.193 0 0 1 1.348-1.286c.522 0 1.478.1 1.391 2.2ZM6 10.492l.192-4.673h3.654L10 10.34a.288.288 0 0 1-.462.23L8.135 9.454l-1.673 1.27A.288.288 0 0 1 6 10.491Z"/>"##, +}; +pub(super) static FOLDER_SUPABASE: Icon = Icon { + name: "folder-supabase", + view: 32.0, + body: r##"<path fill="#66bb6a" d="m13.844 7.536-1.288-1.072A2 2 0 0 0 11.276 6H4a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h24a2 2 0 0 0 2-2V10a2 2 0 0 0-2-2H15.124a2 2 0 0 1-1.28-.464"/><path fill="#c8e6c9" d="M30 18h-6v-6.499a.5.5 0 0 0-.9-.3l-6.3 8.4a1.5 1.5 0 0 0 1.2 2.4h6V28.5a.5.5 0 0 0 .9.3l6.3-8.4A1.5 1.5 0 0 0 30 18"/>"##, +}; +pub(super) static FOLDER_SUPABASE_OPEN: Icon = Icon { + name: "folder-supabase-open", + view: 32.0, + body: r##"<path fill="#66bb6a" d="M28.967 12H9.442a2 2 0 0 0-1.898 1.368L4 24V10h24a2 2 0 0 0-2-2H15.124a2 2 0 0 1-1.28-.464l-1.288-1.072A2 2 0 0 0 11.276 6H4a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h22l4.805-11.212A2 2 0 0 0 28.967 12"/><path fill="#c8e6c9" d="M30 18h-6v-6.499a.5.5 0 0 0-.9-.3l-6.3 8.4a1.5 1.5 0 0 0 1.2 2.4h6V28.5a.5.5 0 0 0 .9.3l6.3-8.4A1.5 1.5 0 0 0 30 18"/>"##, +}; +pub(super) static FOLDER_TARGET: Icon = Icon { + name: "folder-target", + view: 32.0, + body: r##"<path fill="currentColor" d="m13.844 7.536-1.288-1.072A2 2 0 0 0 11.276 6H4a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h24a2 2 0 0 0 2-2V10a2 2 0 0 0-2-2H15.124a2 2 0 0 1-1.28-.464" /><path fill="#cfd8dc" d="m31.304 16.347-1.584 1.584a8 8 0 1 1-5.657-5.657l1.584-1.583a10 10 0 1 0 5.657 5.656" /><path fill="#cfd8dc" d="m22.437 16.022.22-1.987a6 6 0 1 0 5.302 5.304l-1.987.219a4 4 0 1 1-3.535-3.536" /><path fill="#cfd8dc" d="m24.827 14.34-.707 2.12-1.61 1.611a2 2 0 0 0-.99-.01q-.037.01-.072.022a2 2 0 0 0-.367.146q-.054.027-.107.057a2 2 0 1 0 2.735 2.735q.03-.053.056-.108a2 2 0 0 0 .147-.366l.021-.072a2 2 0 0 0-.01-.99l1.611-1.61 2.121-.707 4.243-4.243H29.07v-2.828Z" />"##, +}; +pub(super) static FOLDER_TARGET_OPEN: Icon = Icon { + name: "folder-target-open", + view: 32.0, + body: r##"<path fill="currentColor" d="M28.967 12H9.442a2 2 0 0 0-1.898 1.368L4 24V10h24a2 2 0 0 0-2-2H15.124a2 2 0 0 1-1.28-.464l-1.288-1.072A2 2 0 0 0 11.276 6H4a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h22l4.805-11.212A2 2 0 0 0 28.967 12" /><path fill="#cfd8dc" d="m31.304 16.347-1.584 1.584a8 8 0 1 1-5.657-5.657l1.584-1.583a10 10 0 1 0 5.657 5.656" /><path fill="#cfd8dc" d="m22.437 16.022.22-1.987a6 6 0 1 0 5.302 5.304l-1.987.219a4 4 0 1 1-3.535-3.536" /><path fill="#cfd8dc" d="m24.827 14.34-.707 2.12-1.61 1.611a2 2 0 0 0-.99-.01q-.037.01-.072.022a2 2 0 0 0-.367.146q-.054.027-.107.057a2 2 0 1 0 2.735 2.735q.03-.053.056-.108a2 2 0 0 0 .147-.366l.021-.072a2 2 0 0 0-.01-.99l1.611-1.61 2.121-.707 4.243-4.243H29.07v-2.828Z" />"##, +}; +pub(super) static FOLDER_TASKS: Icon = Icon { + name: "folder-tasks", + view: 32.0, + body: r##"<path fill="#5c6bc0" d="m13.844 7.536-1.288-1.072A2 2 0 0 0 11.276 6H4a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h24a2 2 0 0 0 2-2V10a2 2 0 0 0-2-2H15.124a2 2 0 0 1-1.28-.464"/><path fill="#c5cae9" d="M23.08 24 20 21.108l1.378-1.465 1.718 1.612L26.638 18 28 19.48z"/><path fill="#c5cae9" d="M30 12v-2h-2v2h-8v-2h-2v2a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V14a2 2 0 0 0-2-2m0 14H18V16h12Z"/>"##, +}; +pub(super) static FOLDER_TASKS_OPEN: Icon = Icon { + name: "folder-tasks-open", + view: 32.0, + body: r##"<path fill="#5c6bc0" d="M28.967 12H9.442a2 2 0 0 0-1.898 1.368L4 24V10h24a2 2 0 0 0-2-2H15.124a2 2 0 0 1-1.28-.464l-1.288-1.072A2 2 0 0 0 11.276 6H4a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h22l4.805-11.212A2 2 0 0 0 28.967 12"/><path fill="#c5cae9" d="M23.08 24 20 21.108l1.378-1.465 1.718 1.612L26.638 18 28 19.48z"/><path fill="#c5cae9" d="M30 12v-2h-2v2h-8v-2h-2v2a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V14a2 2 0 0 0-2-2m0 14H18V16h12Z"/>"##, +}; +pub(super) static FOLDER_TEMP: Icon = Icon { + name: "folder-temp", + view: 32.0, + body: r##"<path fill="#0097a7" d="m13.844 7.536-1.288-1.072A2 2 0 0 0 11.276 6H4a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h24a2 2 0 0 0 2-2V10a2 2 0 0 0-2-2H15.124a2 2 0 0 1-1.28-.464"/><path fill="#b2ebf2" d="M25.375 24.781 20 20.48V14h2v5.52l4.625 3.699z"/><path fill="#b2ebf2" d="M22 30a10 10 0 1 1 10-10 10.01 10.01 0 0 1-10 10m0-18a8 8 0 1 0 8 8 8.01 8.01 0 0 0-8-8"/>"##, +}; +pub(super) static FOLDER_TEMPLATE: Icon = Icon { + name: "folder-template", + view: 32.0, + body: r##"<path fill="#8d6e63" d="m13.844 7.536-1.288-1.072A2 2 0 0 0 11.276 6H4a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h24a2 2 0 0 0 2-2V10a2 2 0 0 0-2-2H15.124a2 2 0 0 1-1.28-.464"/><path fill="#d7ccc8" d="M12 26h8v2h-8zm0-4h8v2h-8zm0-4h8v2h-8zm0-4h8v2h-8zm10 0h8v14h-8z"/>"##, +}; +pub(super) static FOLDER_TEMPLATE_OPEN: Icon = Icon { + name: "folder-template-open", + view: 32.0, + body: r##"<path fill="#8d6e63" d="M28.967 12H9.442a2 2 0 0 0-1.898 1.368L4 24V10h24a2 2 0 0 0-2-2H15.124a2 2 0 0 1-1.28-.464l-1.288-1.072A2 2 0 0 0 11.276 6H4a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h22l4.805-11.212A2 2 0 0 0 28.967 12"/><path fill="#d7ccc8" d="M12 26h8v2h-8zm0-4h8v2h-8zm0-4h8v2h-8zm0-4h8v2h-8zm10 0h8v14h-8z"/>"##, +}; +pub(super) static FOLDER_TEMP_OPEN: Icon = Icon { + name: "folder-temp-open", + view: 32.0, + body: r##"<path fill="#0097a7" d="M28.967 12H9.442a2 2 0 0 0-1.898 1.368L4 24V10h24a2 2 0 0 0-2-2H15.124a2 2 0 0 1-1.28-.464l-1.288-1.072A2 2 0 0 0 11.276 6H4a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h22l4.805-11.212A2 2 0 0 0 28.967 12"/><path fill="#b2ebf2" d="M25.375 24.781 20 20.48V14h2v5.52l4.625 3.699z"/><path fill="#b2ebf2" d="M22 30a10 10 0 1 1 10-10 10.01 10.01 0 0 1-10 10m0-18a8 8 0 1 0 8 8 8.01 8.01 0 0 0-8-8"/>"##, +}; +pub(super) static FOLDER_TERRAFORM: Icon = Icon { + name: "folder-terraform", + view: 32.0, + body: r##"<path fill="#5c6bc0" d="m13.844 7.536-1.288-1.072A2 2 0 0 0 11.276 6H4a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h24a2 2 0 0 0 2-2V10a2 2 0 0 0-2-2H15.124a2 2 0 0 1-1.28-.464"/><path fill="#c5cae9" d="M27.03 22.993 32 19.84v-6.316l-4.97 3.16m-5.516-3.16 4.97 3.16v6.31l-4.969-3.157M16 16.313l4.97 3.156v-6.313L16 10m5.516 16.844L26.486 30v-6.313l-4.97-3.156"/>"##, +}; +pub(super) static FOLDER_TERRAFORM_OPEN: Icon = Icon { + name: "folder-terraform-open", + view: 32.0, + body: r##"<path fill="#5c6bc0" d="M28.967 12H9.442a2 2 0 0 0-1.898 1.368L4 24V10h24a2 2 0 0 0-2-2H15.124a2 2 0 0 1-1.28-.464l-1.288-1.072A2 2 0 0 0 11.276 6H4a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h22l4.805-11.212A2 2 0 0 0 28.967 12"/><path fill="#c5cae9" d="M27.03 22.993 32 19.84v-6.316l-4.97 3.16m-5.516-3.16 4.97 3.16v6.31l-4.969-3.157M16 16.313l4.97 3.156v-6.313L16 10m5.516 16.844L26.486 30v-6.313l-4.97-3.156"/>"##, +}; +pub(super) static FOLDER_TEST: Icon = Icon { + name: "folder-test", + view: 32.0, + body: r##"<path fill="#00bfa5" d="m13.844 7.536-1.288-1.072A2 2 0 0 0 11.276 6H4a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h24a2 2 0 0 0 2-2V10a2 2 0 0 0-2-2H15.124a2 2 0 0 1-1.28-.464"/><path fill="#a7ffeb" d="M16 12v2h2v12a4 4 0 0 0 8 0V14h2v-2Zm5 14a1 1 0 1 1 1-1 1 1 0 0 1-1 1m2-4a1 1 0 1 1 1-1 1 1 0 0 1-1 1m1-4h-4v-4h4Z"/>"##, +}; +pub(super) static FOLDER_TEST_OPEN: Icon = Icon { + name: "folder-test-open", + view: 32.0, + body: r##"<path fill="#00bfa5" d="M28.967 12H9.442a2 2 0 0 0-1.898 1.368L4 24V10h24a2 2 0 0 0-2-2H15.124a2 2 0 0 1-1.28-.464l-1.288-1.072A2 2 0 0 0 11.276 6H4a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h22l4.805-11.212A2 2 0 0 0 28.967 12"/><path fill="#a7ffeb" d="M16 12v2h2v12a4 4 0 0 0 8 0V14h2v-2Zm5 14a1 1 0 1 1 1-1 1 1 0 0 1-1 1m2-4a1 1 0 1 1 1-1 1 1 0 0 1-1 1m1-4h-4v-4h4Z"/>"##, +}; +pub(super) static FOLDER_TOOLS: Icon = Icon { + name: "folder-tools", + view: 32.0, + body: r##"<path fill="#1e88e5" d="m13.844 7.536-1.288-1.072A2 2 0 0 0 11.276 6H4a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h24a2 2 0 0 0 2-2V10a2 2 0 0 0-2-2H15.124a2 2 0 0 1-1.28-.464"/><path fill="#bbdefb" d="M24.363 19.012 13.364 30 12 28.638l10.988-11zm4.365-2.815.574-.576-.77-.77.624-.623-1.384-1.383-.623.624-.77-.77-.574.575A20.5 20.5 0 0 0 20.155 10l-.81 1.744a24.5 24.5 0 0 1 4.736 3.253l-.488.488 2.923 2.923.488-.488a24.5 24.5 0 0 1 3.252 4.736L32 21.848a20.5 20.5 0 0 0-3.272-5.651"/>"##, +}; +pub(super) static FOLDER_TOOLS_OPEN: Icon = Icon { + name: "folder-tools-open", + view: 32.0, + body: r##"<path fill="#1e88e5" d="M28.967 12H9.442a2 2 0 0 0-1.898 1.368L4 24V10h24a2 2 0 0 0-2-2H15.124a2 2 0 0 1-1.28-.464l-1.288-1.072A2 2 0 0 0 11.276 6H4a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h22l4.805-11.212A2 2 0 0 0 28.967 12"/><path fill="#bbdefb" d="M24.363 19.012 13.364 30 12 28.638l10.988-11zm4.365-2.815.574-.576-.77-.77.624-.623-1.384-1.383-.623.624-.77-.77-.574.575A20.5 20.5 0 0 0 20.155 10l-.81 1.744a24.5 24.5 0 0 1 4.736 3.253l-.488.488 2.923 2.923.488-.488a24.5 24.5 0 0 1 3.252 4.736L32 21.848a20.5 20.5 0 0 0-3.272-5.651"/>"##, +}; +pub(super) static FOLDER_TYPESCRIPT: Icon = Icon { + name: "folder-typescript", + view: 32.0, + body: r##"<path fill="#0288d1" d="m13.844 7.536-1.288-1.072A2 2 0 0 0 11.276 6H4a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h24a2 2 0 0 0 2-2V10a2 2 0 0 0-2-2H15.124a2 2 0 0 1-1.28-.464"/><path fill="#90caf9" d="M24 19.06a1.33 1.33 0 0 0 .3 1.04 2.5 2.5 0 0 0 .61.28c.54.18 1.33.37 2.09.62 2.64.88 2.96 2.32 2.99 3.49.01.16.01.31.01.46V25c0 1.06-.46 2.79-3.44 2.98-.13.01-.25.01-.37.01A1 1 0 0 1 26 28h-4v-1.76l.24-.24H26a2 2 0 0 0 .25-.01h.17c.18-.01.33-.03.47-.04a2 2 0 0 0 .27-.06c.07-.02.13-.04.19-.06a.04.04 0 0 0 .03-.01c.49-.18.59-.45.61-.66A1 1 0 0 0 28 25c0-.32-.68-1.23-3-2-2.74-.91-2.98-2.42-2.99-3.61a.6.6 0 0 1-.01-.13V19a2.85 2.85 0 0 1 .45-1.59c.04-.06.07-.11.11-.16.01-.01.01-.02.02-.03a1 1 0 0 1 .18-.2A4.3 4.3 0 0 1 25.91 16H30v2h-4c-.13 0-.26 0-.39.01-1.18.06-1.49.4-1.58.7a.13.13 0 0 0-.01.06A1 1 0 0 0 24 19ZM18 28h-2V18h-4v-2h10v2h-4Z"/>"##, +}; +pub(super) static FOLDER_TYPESCRIPT_OPEN: Icon = Icon { + name: "folder-typescript-open", + view: 32.0, + body: r##"<path fill="#0288d1" d="M28.967 12H9.442a2 2 0 0 0-1.898 1.368L4 24V10h24a2 2 0 0 0-2-2H15.124a2 2 0 0 1-1.28-.464l-1.288-1.072A2 2 0 0 0 11.276 6H4a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h22l4.805-11.212A2 2 0 0 0 28.967 12"/><path fill="#90caf9" d="M24 19.06a1.33 1.33 0 0 0 .3 1.04 2.5 2.5 0 0 0 .61.28c.54.18 1.33.37 2.09.62 2.64.88 2.96 2.32 2.99 3.49.01.16.01.31.01.46V25c0 1.06-.46 2.79-3.44 2.98-.13.01-.25.01-.37.01A1 1 0 0 1 26 28h-4v-1.76l.24-.24H26a2 2 0 0 0 .25-.01h.17c.18-.01.33-.03.47-.04a2 2 0 0 0 .27-.06c.07-.02.13-.04.19-.06a.04.04 0 0 0 .03-.01c.49-.18.59-.45.61-.66A1 1 0 0 0 28 25c0-.32-.68-1.23-3-2-2.74-.91-2.98-2.42-2.99-3.61a.6.6 0 0 1-.01-.13V19a2.85 2.85 0 0 1 .45-1.59c.04-.06.07-.11.11-.16.01-.01.01-.02.02-.03a1 1 0 0 1 .18-.2A4.3 4.3 0 0 1 25.91 16H30v2h-4c-.13 0-.26 0-.39.01-1.18.06-1.49.4-1.58.7a.13.13 0 0 0-.01.06A1 1 0 0 0 24 19ZM18 28h-2V18h-4v-2h10v2h-4Z"/>"##, +}; +pub(super) static FOLDER_UTILS: Icon = Icon { + name: "folder-utils", + view: 32.0, + body: r##"<path fill="#7cb342" d="m13.844 7.536-1.288-1.072A2 2 0 0 0 11.276 6H4a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h24a2 2 0 0 0 2-2V10a2 2 0 0 0-2-2H15.124a2 2 0 0 1-1.28-.464"/><path fill="#dcedc8" d="M31 12H19a1 1 0 0 0-1 1v12a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1V13a1 1 0 0 0-1-1m-1 8h-4v4h-2v-4h-4v-2h4v-4h2v4h4Z"/><path fill="#dcedc8" d="M16 28V16h-2v13a1 1 0 0 0 1 1h13v-2Z"/>"##, +}; +pub(super) static FOLDER_UTILS_OPEN: Icon = Icon { + name: "folder-utils-open", + view: 32.0, + body: r##"<path fill="#7cb342" d="M28.967 12H9.442a2 2 0 0 0-1.898 1.368L4 24V10h24a2 2 0 0 0-2-2H15.124a2 2 0 0 1-1.28-.464l-1.288-1.072A2 2 0 0 0 11.276 6H4a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h22l4.805-11.212A2 2 0 0 0 28.967 12"/><path fill="#dcedc8" d="M31 12H19a1 1 0 0 0-1 1v12a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1V13a1 1 0 0 0-1-1m-1 8h-4v4h-2v-4h-4v-2h4v-4h2v4h4Z"/><path fill="#dcedc8" d="M16 28V16h-2v13a1 1 0 0 0 1 1h13v-2Z"/>"##, +}; +pub(super) static FOLDER_VERCEL: Icon = Icon { + name: "folder-vercel", + view: 32.0, + body: r##"<path fill="currentColor" d="m13.844 7.536-1.288-1.072A2 2 0 0 0 11.276 6H4a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h24a2 2 0 0 0 2-2V10a2 2 0 0 0-2-2H15.124a2 2 0 0 1-1.28-.464" /><path fill="#cfd8dc" d="m22 12 10 16H12Z" />"##, +}; +pub(super) static FOLDER_VERCEL_OPEN: Icon = Icon { + name: "folder-vercel-open", + view: 32.0, + body: r##"<path fill="currentColor" d="M28.967 12H9.442a2 2 0 0 0-1.898 1.368L4 24V10h24a2 2 0 0 0-2-2H15.124a2 2 0 0 1-1.28-.464l-1.288-1.072A2 2 0 0 0 11.276 6H4a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h22l4.805-11.212A2 2 0 0 0 28.967 12" /><path fill="#cfd8dc" d="m22 12 10 16H12Z" />"##, +}; +pub(super) static FOLDER_VIEWS: Icon = Icon { + name: "folder-views", + view: 32.0, + body: r##"<path fill="#ff7043" d="m13.844 7.536-1.288-1.072A2 2 0 0 0 11.276 6H4a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h24a2 2 0 0 0 2-2V10a2 2 0 0 0-2-2H15.124a2 2 0 0 1-1.28-.464"/><path fill="#ffccbc" d="m14 12 2 16 7 2 7-2 2-16Zm8 5.899L18.66 20 22 22.102V24l-5.235-3.386v-1.227L22 16Zm7.235 2.728L24 24v-1.898L27.363 20 24 17.899V16l5.235 3.373Z"/>"##, +}; +pub(super) static FOLDER_VIEWS_OPEN: Icon = Icon { + name: "folder-views-open", + view: 32.0, + body: r##"<path fill="#ff7043" d="M28.967 12H9.442a2 2 0 0 0-1.898 1.368L4 24V10h24a2 2 0 0 0-2-2H15.124a2 2 0 0 1-1.28-.464l-1.288-1.072A2 2 0 0 0 11.276 6H4a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h22l4.805-11.212A2 2 0 0 0 28.967 12"/><path fill="#ffccbc" d="m14 12 2 16 7 2 7-2 2-16Zm8 5.899L18.66 20 22 22.102V24l-5.235-3.386v-1.227L22 16Zm7.235 2.728L24 24v-1.898L27.363 20 24 17.899V16l5.235 3.373Z"/>"##, +}; +pub(super) static FOLDER_VSCODE: Icon = Icon { + name: "folder-vscode", + view: 32.0, + body: r##"<path fill="#42a5f5" d="m13.844 7.536-1.288-1.072A2 2 0 0 0 11.276 6H4a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h24a2 2 0 0 0 2-2V10a2 2 0 0 0-2-2H15.124a2 2 0 0 1-1.28-.464"/><path fill="#bbdefb" d="m28.145 10-7.903 7.267-4.417-3.329L14 15.001l4.353 3.998L14 23.001l1.825 1.065 4.417-3.329L28.145 28 32 26.127V11.874ZM28 14.78v8.441l-5.603-4.22Z"/>"##, +}; +pub(super) static FOLDER_VSCODE_OPEN: Icon = Icon { + name: "folder-vscode-open", + view: 32.0, + body: r##"<path fill="#42a5f5" d="M28.967 12H9.442a2 2 0 0 0-1.898 1.368L4 24V10h24a2 2 0 0 0-2-2H15.124a2 2 0 0 1-1.28-.464l-1.288-1.072A2 2 0 0 0 11.276 6H4a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h22l4.805-11.212A2 2 0 0 0 28.967 12"/><path fill="#bbdefb" d="m28.145 10-7.903 7.267-4.417-3.329L14 15.001l4.353 3.998L14 23.001l1.825 1.065 4.417-3.329L28.145 28 32 26.127V11.874ZM28 14.78v8.441l-5.603-4.22Z"/>"##, +}; +pub(super) static FOLDER_WINDOWS: Icon = Icon { + name: "folder-windows", + view: 32.0, + body: r##"<path fill="#2196f3" d="M12.667 6h-8A2.657 2.657 0 0 0 2 8.648v16.019a2.68 2.68 0 0 0 2.667 2.666H26a2.68 2.68 0 0 0 2.667-2.666V11.333A2.667 2.667 0 0 0 26 8.667H15.333z"/><path fill="#bbdefb" d="M14 12h8v8h-8zm10 0h8v8h-8zm0 10h8v8h-8zm-10 0h8v8h-8z"/>"##, +}; +pub(super) static FOLDER_WINDOWS_OPEN: Icon = Icon { + name: "folder-windows-open", + view: 32.0, + body: r##"<path fill="#2196f3" d="M24.667 27.333h-20A2.667 2.667 0 0 1 2 24.667v-16A2.657 2.657 0 0 1 4.648 6h8.019l2.666 2.667h9.334a2.68 2.68 0 0 1 2.666 2.666H4.667v13.334L7.52 14h22.76l-3.04 11.333a2.67 2.67 0 0 1-2.573 2"/><path fill="#bbdefb" d="M14 12h8v8h-8zm10 0h8v8h-8zm0 10h8v8h-8zm-10 0h8v8h-8z"/>"##, +}; +pub(super) static FSHARP: Icon = Icon { + name: "fsharp", + view: 500.0, + body: r##"<path fill="#0288d1" d="m236.249 36.066-213.94 213.94 213.94 213.94v-84.36l-129.7-129.7 129.7-129.7z"/><path fill="#0288d1" d="m236.249 156.017-93.622 93.62 93.622 93.622z"/><path fill="#00b8d4" d="m263.759 36.047 213.94 213.94-213.94 213.94v-84.36l129.7-129.7-129.7-129.7z"/>"##, +}; +pub(super) static GATSBY: Icon = Icon { + name: "gatsby", + view: 28.0, + body: r##"<path fill="#fafafa" d="M23.835 14h-6.259v1.788h4.292c-.626 2.682-2.593 4.918-5.186 5.812L6.4 11.318c1.073-3.13 4.113-5.365 7.6-5.365 2.682 0 5.096 1.342 6.616 3.398l1.341-1.162C20.17 5.775 17.308 4.165 14 4.165c-4.65 0-8.583 3.308-9.566 7.69l11.801 11.801c4.292-1.073 7.6-5.007 7.6-9.656m-19.67.09c0 2.503.984 4.917 2.861 6.794s4.381 2.861 6.795 2.861z"/><path fill="#6a1b9a" d="M14 1.483C7.116 1.483 1.483 7.116 1.483 14S7.116 26.517 14 26.517 26.517 20.884 26.517 14 20.884 1.483 14 1.483m-6.974 19.49c-1.877-1.877-2.86-4.38-2.86-6.794l9.745 9.656c-2.504-.09-5.007-.984-6.885-2.861zm9.12 2.594L4.433 11.854C5.417 7.474 9.351 4.165 14 4.165c3.308 0 6.17 1.61 7.957 4.024l-1.34 1.162C19.096 7.294 16.681 5.953 14 5.953c-3.487 0-6.437 2.236-7.6 5.365L16.682 21.6c2.593-.894 4.56-3.13 5.186-5.812h-4.292V14h6.259c0 4.65-3.308 8.583-7.69 9.567z"/>"##, +}; +pub(super) static GEMFILE: Icon = Icon { + name: "gemfile", + view: 32.0, + body: r##"<path fill="#e53935" d="M21.184 10.016V10H10.881l.016.033-.016-.017L8 14l8.032 10L24 14z"/><path fill="#e53935" d="m16 3.455 11 6.286v12.518l-11 6.286-11-6.286V9.741zM16 0 2 8v16l14 8 14-8V8z"/>"##, +}; +pub(super) static GIT: Icon = Icon { + name: "git", + view: 32.0, + body: r##"<path fill="#e64a19" d="M13.172 2.828 11.78 4.22l1.91 1.91 2 2A2.986 2.986 0 0 1 20 10.81a3.25 3.25 0 0 1-.31 1.31l2.06 2a2.68 2.68 0 0 1 3.37.57 2.86 2.86 0 0 1 .88 2.117 3.02 3.02 0 0 1-.856 2.109A2.9 2.9 0 0 1 23 19.81a2.93 2.93 0 0 1-2.13-.87 2.694 2.694 0 0 1-.56-3.38l-2-2.06a3 3 0 0 1-.31.12V20a3 3 0 0 1 1.44 1.09 2.92 2.92 0 0 1 .56 1.72 2.88 2.88 0 0 1-.878 2.128 2.98 2.98 0 0 1-2.048.871 2.981 2.981 0 0 1-2.514-4.719A3 3 0 0 1 16 20v-6.38a2.96 2.96 0 0 1-1.44-1.09 2.9 2.9 0 0 1-.56-1.72 2.9 2.9 0 0 1 .31-1.31l-3.9-3.9-7.579 7.572a4 4 0 0 0-.001 5.658l10.342 10.342a4 4 0 0 0 5.656 0l10.344-10.344a4 4 0 0 0 0-5.656L18.828 2.828a4 4 0 0 0-5.656 0"/>"##, +}; +pub(super) static GITPOD: Icon = Icon { + name: "gitpod", + view: 32.0, + body: r##"<path fill="#ffa726" d="M18.258 4.156a2.6 2.6 0 0 1-.951 3.538l-.016.01-7.757 4.428a.66.66 0 0 0-.331.57v6.953a.66.66 0 0 0 .331.57l6.14 3.507a.66.66 0 0 0 .652 0l6.14-3.506a.66.66 0 0 0 .331-.571v-4.323l-5.52 3.11a2.6 2.6 0 0 1-2.57-4.518l.014-.009 7.898-4.452A3.61 3.61 0 0 1 28 12.603v7.58a4.95 4.95 0 0 1-2.495 4.295l-7.048 4.024a4.95 4.95 0 0 1-4.914 0l-7.048-4.024A4.95 4.95 0 0 1 4 20.182v-8.007A4.95 4.95 0 0 1 6.495 7.88l8.214-4.692a2.603 2.603 0 0 1 3.55.968Z"/>"##, +}; +pub(super) static GLEAM: Icon = Icon { + name: "gleam", + view: 24.0, + body: r##"<path fill="#ea80fc" d="m12.717 2.53-.027.005-.438.092-.22.334.04.41-.187.307.041.052s.063.077.031.196c-.016.06-.114.318-.205.543s-.176.43-.176.43l-.017.042.021.038a.55.55 0 0 0 .026.517c.057.1.035.2-.006.287a.6.6 0 0 1-.1.147l-.013.015-.147.432-.023.182.029.066-.057.045-.304.945-.036.283-.097.399-.196.56-.05.293-.082.342-.118.27-.084.156-.152.46-.111.49.492.349.85-.123.584-.766.28-.771.182-.852.112-.63.066-.339.174-.806.053-.473.127-.39.021-.329.082-.576.037-.476.084-.274.055-.625-.031-.146.119-.368-.078-.093.03-.17-.144-.31zM2.059 5.442l-.04.018-.575.227-.258.283.893 1.142.326.032.267.453.457.172.069.16.357.285.932.678.664.433 1.312 1.055.112.209.365.201.467.399.588.517.101.223.625.043.656-.85-.006-.605-1.738-1.395-1.27-.922-1.245-.838-.954-.515-.056-.14-1.065-.628-.406-.324zm17.912 5.528-.152.134-.233-.062-.959.14-.47-.109.02.131c-.116-.065-.24-.049-.343-.035-.105.014-.187.019-.232-.006-.124-.069-.261-.034-.361.004-.07.026-.09.043-.12.06l-.263-.15-.373.166-.4-.04-.42-.018-.45.08-.252-.063-.617.067-.326-.084-.04.048s-.027.036-.062.063a.2.2 0 0 1-.047.025c-.01.003-.004.002-.004.002-.087-.05-.178-.04-.253-.031-.075.008-.135.021-.135.021l-.008.004-.248.118-.795.132-.021.028s-.12.143-.227.304a1.5 1.5 0 0 0-.133.246.4.4 0 0 0-.031.124.17.17 0 0 0 .053.132c-.002-.001.01.02.011.065a1 1 0 0 1-.021.164 2 2 0 0 1-.068.226l-.026.063.461.367.47.063.29-.094.95-.174.185-.076.107.037.588-.053.19.106.124-.108.116.037.918-.138.402.125-.027-.147c.04.018.076.027.12.03q.08.004.182-.002c.134-.008.293-.028.448-.05.295-.04.548-.089.57-.093l.19.066.853-.127.527-.156.363.117.407-.058.224-.215.54.135-.018-.135s-.003-.062.027-.106c.015-.021.034-.04.084-.054a.6.6 0 0 1 .25.01c.276.058.45.023.557-.043a.3.3 0 0 0 .107-.106.3.3 0 0 0 .03-.066l.01-.043-.122-.158.053-.19-.338-.45-.576-.11-.358.005-.039-.062-.047-.002s-.247-.022-.449.045c-.107.036-.234-.072-.234-.072l-.139.127zM9.03 13.117l-.033.018-.658.35-.23.22-.173.356.203.572.319.295.306.465-3.802 3.158-.12.17-.798.615-.328.334-.559.422-.09.135-.152.445.385.531.459-.31.207.093.166-.199.101.047.729-.572.238-.133.287-.068.344-.266-.04-.05.206-.07.416-.359.273-.076.328-.224.141-.268.031-.021.112.048.52-.546.54-.292 1.102-.923.457 1.283.252.375.146.629.213.082-.012.033.112.75.193.18-.08.326.316.164a.25.25 0 0 0 .016.156c.026.067.072.147.148.254.164.23.369.29.522.277a.6.6 0 0 0 .262-.09l.023-.015.186-.445-.256-1.391-.225-1.092-.275-.592-.194-.552v-.002c0-.002-.051-.155-.105-.336a4 4 0 0 1-.12-.487 1.1 1.1 0 0 0-.103-.373l-.002-.003-.142-.301.19-.178.558-.648.08-.729-.688-.762-.484.196-.379.406-.582-.867z"/>"##, +}; +pub(super) static GO: Icon = Icon { + name: "go", + view: 32.0, + body: r##"<path fill="#00acc1" d="M2 12h4v2H2zm-2 4h6v2H0zm4 4h2v2H4zm16.954-5H14v3h3.239a4.42 4.42 0 0 1-3.531 2 2.65 2.65 0 0 1-2.053-.858 2.86 2.86 0 0 1-.628-2.28A4.515 4.515 0 0 1 15.292 13a2.73 2.73 0 0 1 1.749.584l2.962-1.185A5.6 5.6 0 0 0 15.292 10a7.526 7.526 0 0 0-7.243 6.5 5.614 5.614 0 0 0 5.659 6.5 7.526 7.526 0 0 0 7.243-6.5 6.4 6.4 0 0 0 .003-1.5"/><path fill="#00acc1" d="M26.292 10a7.526 7.526 0 0 0-7.243 6.5 5.614 5.614 0 0 0 5.659 6.5 7.526 7.526 0 0 0 7.243-6.5 5.614 5.614 0 0 0-5.659-6.5m2.681 6.137A4.515 4.515 0 0 1 24.708 20a2.65 2.65 0 0 1-2.053-.858 2.86 2.86 0 0 1-.628-2.28A4.515 4.515 0 0 1 26.292 13a2.65 2.65 0 0 1 2.053.858 2.86 2.86 0 0 1 .628 2.28Z"/>"##, +}; +pub(super) static GO_MOD: Icon = Icon { + name: "go-mod", + view: 32.0, + body: r##"<path fill="#ec407a" d="M2 12h4v2H2zm-2 4h6v2H0zm4 4h2v2H4zm16.954-5H14v3h3.239a4.42 4.42 0 0 1-3.531 2 2.65 2.65 0 0 1-2.053-.858 2.86 2.86 0 0 1-.628-2.28A4.515 4.515 0 0 1 15.292 13a2.73 2.73 0 0 1 1.749.584l2.962-1.185A5.6 5.6 0 0 0 15.292 10a7.526 7.526 0 0 0-7.243 6.5 5.614 5.614 0 0 0 5.659 6.5 7.526 7.526 0 0 0 7.243-6.5 6.4 6.4 0 0 0 .003-1.5"/><path fill="#ec407a" d="M26.292 10a7.526 7.526 0 0 0-7.243 6.5 5.614 5.614 0 0 0 5.659 6.5 7.526 7.526 0 0 0 7.243-6.5 5.614 5.614 0 0 0-5.659-6.5m2.681 6.137A4.515 4.515 0 0 1 24.708 20a2.65 2.65 0 0 1-2.053-.858 2.86 2.86 0 0 1-.628-2.28A4.515 4.515 0 0 1 26.292 13a2.65 2.65 0 0 1 2.053.858 2.86 2.86 0 0 1 .628 2.28Z"/>"##, +}; +pub(super) static GRADLE: Icon = Icon { + name: "gradle", + view: 32.0, + body: r##"<path fill="#0097a7" d="M16 10v2h6c-2 0-3-2-6-2"/><path fill="#0097a7" d="M26 4h-2a4 4 0 0 0-4 4h4a1 1 0 0 1 2 0v4H16v-2h-5.317A2.683 2.683 0 0 0 8 12.683v2.634A2.683 2.683 0 0 0 10.683 18H16v2h-5.98A4.02 4.02 0 0 1 6 16v-2c-2 0-4 4-4 8 0 5 1 6 2 6h4v-4h4v4h4v-4h4v4h4v-6a2 2 0 0 0 2-2v-2a4 4 0 0 0 4-4V8a4 4 0 0 0-4-4m-4 12h-2a2 2 0 0 1-2-2h6a2 2 0 0 1-2 2"/>"##, +}; +pub(super) static GRAIN: Icon = Icon { + name: "grain", + view: 32.0, + body: r##"<path fill="#ffa726" d="m16 2-4.97 9.782L16 16l5.094-4.218Z"/><path fill="#f57f17" d="M2 6.848V18.64L16 30l7.228-5.844Z"/><path fill="#f57c00" d="M30 18.645V6.71L17.334 17.235l7.284 5.808Z"/>"##, +}; +pub(super) static GRAPHQL: Icon = Icon { + name: "graphql", + view: 32.0, + body: r##"<path fill="#ec407a" d="M6 20h20v2H6z"/><circle cx="7" cy="21" r="3" fill="#ec407a"/><circle cx="16" cy="27" r="3" fill="#ec407a"/><circle cx="25" cy="21" r="3" fill="#ec407a"/><path fill="#ec407a" d="M6 10h20v2H6z"/><circle cx="7" cy="11" r="3" fill="#ec407a"/><circle cx="16" cy="5" r="3" fill="#ec407a"/><circle cx="25" cy="11" r="3" fill="#ec407a"/><path fill="#ec407a" d="M6 12h2v10H6zm18-2h2v12h-2z"/><path fill="#ec407a" d="m5.014 19.41 11.674 6.866L15.674 28 4 21.134z"/><path fill="#ec407a" d="M26.688 21.724 15.014 28.59 14 26.866 25.674 20zM5.124 10.382l11.415-7.29 1.077 1.686L6.2 12.068z"/><path fill="#ec407a" d="m25.798 12.067-11.415-7.29 1.077-1.685 11.415 7.29zM6.2 19.932l11.416 7.29-1.077 1.686-11.415-7.29z"/><path fill="#ec407a" d="m26.875 21.619-11.415 7.29-1.077-1.687 11.415-7.289zM5.877 22.6 16.04 3.686l1.762.946L7.638 23.546z"/><path fill="#ec407a" d="M24.361 23.545 14.197 4.633l1.761-.947 10.165 18.913z"/>"##, +}; +pub(super) static GRUNT: Icon = Icon { + name: "grunt", + view: 300.0, + body: r##"<path fill="#f9a825" d="M61.045 79.22s4.718 18.193 5.39 24.259c.675 6.064-12.128 19.54-12.128 26.279s2.691 18.87 17.518 24.935 16.847 21.563 16.847 31c0 9.433-5.39 27.626-5.39 27.626s-3.368 45.148 14.825 53.234 14.151 8.086 18.192 8.086c4.037 0 33.688 12.136 51.21 7.416 17.523-4.711 22.234-10.105 22.234-10.105s17.523 1.348 22.908-14.151c5.394-15.492 8.757-47.84 6.735-62.665s-4.72-34.362 7.408-41.105c12.129-6.734 24.931-14.825 22.908-21.56S236.9 116.297 236.9 116.297s-2.697-16.84-.683-20.885c2.023-4.038 14.151-14.152 7.409-21.56-6.734-7.409-18.871-7.409-18.871-7.409l-15.491 1.34s-26.27-23.59-60.641-22.242c-34.346 1.348-55.914 22.234-55.914 22.234s-11.454-4.044-21.562 0c-10.114 4.045-12.128 0-10.106 11.454z"/><g fill="#e78724"><path d="M122.623 179.552s-13.345 20.404-23.133 34.884c-1.514 2.24 9.788 2.395 9.788 2.395l13.346-37.28zm6.353-42.303s-4.022 10.035-6.226 15.355c-2.392 5.783-11.511 8.66-11.511 8.66s4.728-4.958 4.728-17.519c0-5.262 6.802-7.359 6.802-7.359l6.208.872z"/><path d="M124.909 142.92s-8.242 9.81-23.544 4.317c-15.306-5.493-16.874-25.117-16.874-30.611s29.04 5.494 32.964 7.849 11.378 11.772 7.454 18.445M67.104 38.09s14.126-2.75 23.544 4.707c9.422 7.456 12.165 13.344 12.165 13.344L86.939 68.724s-7.67-3.557-10.026-13.761c-2.353-10.203-.783-14.911-9.81-16.873z"/><path d="M120.79 114.585c-6.084-8.634-16.107-12.4-24.11-13.025-13.646-1.066-20.125 3.758-20.125 3.758s22.349.946 28.79 9.407c11.992 15.746 29.487 17.025 32.284 13.567-3.235.161-6.793-1.442-10.602-5.043-2.38-2.253-4.309-5.924-6.239-8.664zm-37.73 30.528s-24.795-8.525-20.084-17.156c4.71-8.635.962-13.34.962-13.34s-13.847 10.337-10.32 21.324c2.17 6.742 5.808 11.626 25.783 20.984 9.58 17.793 1.978 49.829 2.434 49.977.759.246 13.452-6.274 12.585-36.246-.263-9.209-.995-21.765-11.355-25.555zm32.495-91.666c-10.398 5.283-24.642 12.638-24.642 12.638l5.606 2.804c-.534.868-.793 1.385-.793 1.385l5.748 2.616s14.044 10.176 22.653 16.717c-2.87-8.835-11.298-22.717-11.298-22.717s-2.393-6.378 2.713-13.444zm34.54 215.317c-31.958 0-42.783-16.223-42.783-16.223l4.995 12.161c1.888 5.263 22.027 21.634 37.74 21.634"/><path d="M110.815 241.575s2.94 17.97 14.713 17.97c10.004 0 12.952-15.179 12.952-18.316l-27.666.346zm-19.593-27.1c1.046-2.88 4.709-14.522 5.885-25.116 1.406-12.69.897-31.249.897-31.249s-3.141 12.166-5.896 14.132c-2.746 1.96-7.853 15.302-7.853 15.302s-2.738 19.862-4.037 26.538c3.602.722 6.628-1.4 10.986.393zm-28.43-78.732s6.668-2.356 8.634-16.874c1.96-14.521-2.357-27.079-2.357-27.079s.392 20.014-1.961 23.94c-2.357 3.922-4.317 5.1-7.065 10.204-2.749 5.103 1.176 8.239 2.749 9.81z"/></g><path fill="#ffcc80" d="m70.755 41.524-1.361-.864c-4.015.137 1.362.864 1.362.864z"/><path fill="#f9a825" d="M120.987 49.146s-6.278-1.046-9.419-5.754c-3.14-4.71-12.034-14.13-26.213-14.235-14.176-.107-28.204 3.768-28.204 3.768l12.244 7.73c1.296-.042 3.56-.025 7.305.098 15.366.51 17.732 15.705 17.732 15.705l54.162-7.457"/><path fill="#fafafa" d="M126.216 133.094s-7.326 7.326-18.576 4.97c-11.251-2.354-18.055-7.325-18.578-15.96-.523-8.634 2.357-12.034 2.357-12.034s12.564 3.93 18.583 9.16c6.019 5.238 10.467 13.608 16.223 13.871z"/><path fill="#bdbdbd" d="M117.352 130.48s-6.353 2.902-13.455.537c-9.297-3.1-9.917-12.77-9.917-12.77s-5.702 16.737 10.287 19.959c12.825 2.583 20.41-4.848 20.41-4.848z"/><g fill="#4e342e"><path d="M121.866 45.596c-.684-14.354 11.083-25.787 15.16-26.272.225 2.432-.227 11.919 3.848 14.836 1.187-7.746 5.2-16.29 21.045-21.889-3.394 9-.453 16.54.947 20.034 10.82-9.82 18.11-8.198 18.11-8.198s-7.518 12.973-4.577 21.486c-21.721-1.704-54.427 2.307-54.533.003M75.817 67.459c-5.182-4.3-1.32-8.29-1.729-13.175-.222-2.599-.427-5.052-1.285-6.406-4.77-7.53-16.018-9.815-16.133-9.839l-5.279-1.034 3.495-4.09c.452-.53 14.809-14.225 37.026-7.055 15.541 5.013 27.044 22.007 27.472 22.695l-7.787 3.663c-.09-.145-9.184-16.119-22.513-20.417-10.772-3.478-20.705-.17-24.964 1.998 4.522 1.806 10.434 5.094 14.003 10.72 1.686 2.655 1.965 6.002 2.237 9.24.361 4.288.698 8.336 3.856 10.957l-8.387 2.743zm-13.842 62.765s6.53-8.097 8.464-23.852c.76-6.206-.59-18.446-2.749-23.155.392 11.578-2.55 23.155-2.55 23.155s-1.982 21.497-3.158 23.852z"/><path d="M96.41 59.281c-.004-.016-2.096-9.158-7.894-13.773-8.182-6.507-18.17-3.045-18.267-3.015l-1.447-4.481c.485-.156 11.906-3.754 22.423 3.642 10.582 7.439 11.857 14.181 11.964 14.926l-6.776 2.701zm-13.923 65.136s-3.426-4.904-2.81-10.297c.307-2.664 1.541-5.397 3.745-6.367 4.094-1.793 5.912 2.845 5.912 2.845s-5.764 1.422-6.842 13.822z"/><path d="M120.099 131.893c.143.268.216.417.216.417s-10.685 8.019-21.634-.118c-5.863-4.358-5.308-15.138-3.513-19.71 4.67 1.061 8.63 2.969 11.941 5.197-4.183-3.733-7.846-6.48-7.836-6.545l-4.755-1.349-9.242-3.165c-.119.707-3.49 16.51 6.24 27.274 4.314 4.777 24.533 15.467 34.133-2.812l-5.55.83z"/><path d="M119.095 133.07c6.016 9.155 21.194 3.923 20.933-5.757 0 0-10.142 5.598-19.101-4.708-5.232-6.01-21.996-22.604-44.727-17.086 15.698 3.453 36.48 17.793 42.895 27.562z"/><path d="M74.077 158.905c1.447.836 6.55 6.121 6.553 14.027 0 3.964-.395 23.879-2.357 36.044 2.952 1.918 5.008 2.325 7.946 4.28 1.472-14.09 2.526-34.512 2.034-42.756-.559-9.398-5.591-15.705-10.253-18.394a187 187 0 0 0-4.523-2.498c-7.992-4.318-16.256-8.786-16.256-16.414 0-5.967 2.319-7.833 4.777-9.812l.264-.214c1.628-1.317 3.478-2.81 4.571-5.262 2.985-6.704 3.47-23.78 0-28.116-1.726-2.162-6.364-9.43-5.032-14.307.51-1.866 1.686-3.248 3.593-4.226 2.023-1.036 4.753-1.563 8.116-1.563 6.603 0 13.93 2.007 17.703 3.207 13.502 4.276 29.79 16.61 34.461 20.294l.23.172 2.985 2.08-1.866-3.132c-.115-.198-11.948-19.66-33.113-26.798-4.12-1.39-12.202-3.716-20.153-3.716-4.728 0-8.75.822-11.931 2.45-3.873 1.982-6.496 5.147-7.59 9.144-2.672 9.8 6.036 20.712 6.332 21.066 1.02 1.809 1.447 14.965-.897 20.236-.32.723-1.2 1.439-2.327 2.343-.345.28-.74.576-1.159.888-3.305 2.492-8.305 6.266-8.305 14.957 0 11.89 12.063 18.345 21.749 23.525 1.595.855 3.108 1.66 4.481 2.45z"/><path d="M75.817 67.459c-5.182-4.3-1.32-8.29-1.729-13.175-.222-2.599-.427-5.052-1.285-6.406-4.77-7.53-16.018-9.815-16.133-9.839l-5.279-1.034 3.495-4.09c.452-.53 14.809-14.225 37.026-7.055 15.541 5.013 27.044 22.007 27.472 22.695l-7.787 3.663c-.09-.145-9.184-16.119-22.513-20.417-10.772-3.478-20.705-.17-24.964 1.998 4.522 1.806 10.434 5.094 14.003 10.72 1.686 2.655 1.965 6.002 2.237 9.24.361 4.288.698 8.336 3.856 10.957l-8.387 2.743z"/><path d="m75.649 68.34-.335-.278c-3.843-3.182-3.161-6.331-2.501-9.365.3-1.398.617-2.854.488-4.342-.21-2.5-.41-4.86-1.164-6.052-4.539-7.17-15.516-9.464-15.623-9.489l-6.595-1.299 4.375-5.106c.082-.09 9.3-9.398 24.906-9.398 4.26 0 8.617.707 12.95 2.113 16.216 5.23 27.793 22.85 27.9 23.023l.469.748-9.218 4.342-.37-.584c-.987-1.686-9.727-16.1-22.094-20.088-3.034-.987-6.233-1.48-9.505-1.48-5.92 0-10.723 1.62-13.28 2.697 4.276 1.924 9.448 5.164 12.729 10.336 1.784 2.82 2.072 6.257 2.351 9.58.346 4.135.675 8.025 3.577 10.434l1.094.904-10.147 3.33z"/><path d="M96.41 59.281c-.004-.016-2.096-9.158-7.894-13.773-8.182-6.507-18.17-3.045-18.267-3.015l-1.447-4.481c.485-.156 11.906-3.754 22.423 3.642 10.582 7.439 11.857 14.181 11.964 14.926l-6.776 2.701z"/><path d="m95.842 60.35-.204-.9c-.021-.087-2.072-8.916-7.62-13.326-3.16-2.516-6.972-3.79-11.322-3.79-3.396 0-5.92.814-6.195.904l-.75.255-1.94-5.978.747-.238c.338-.107 3.364-1.053 7.656-1.053 5.657 0 11.002 1.661 15.466 4.802 10.854 7.63 12.178 14.678 12.293 15.459l.099.616-8.206 3.273zM76.696 40.762c4.648 0 8.905 1.43 12.301 4.131 4.926 3.923 7.242 10.846 7.943 13.33l5.337-2.128c-.483-1.885-2.61-7.54-11.512-13.798-4.257-2.993-9.156-4.509-14.562-4.509-2.967 0-5.27.472-6.41.76l.962 2.977a23.3 23.3 0 0 1 5.941-.763m48.339 214.47c-2.32 0-4.686-.84-6.326-2.26-1.256-1.083-5.501-4.984-7.374-9.761-.699-1.787-.543-3.215.472-4.245.699-.704 2.15-1.547 5.094-1.547l2.095-.003c2.5-.003 6.701-.003 10.295-.003h3.445c2.245 0 3.848.485 4.769 1.43 1.184 1.218.806 2.772.477 3.586-.576 1.43-2.96 6.085-7.006 10.402-1.447 1.554-3.552 2.409-5.928 2.409zm2.43-121.628-8.371-.539s2.14 3.773 3.526 8.652c1.565 5.517-1.431 13.584-1.431 13.584s11.162-12.638 6.276-21.7zm-10.452 143.73c-29.797-2.29-40.28-30.446-40.28-36.31l7.781.003h-3.89 3.89c.04 2.54 7.958 26.625 33.096 28.557l-.596 7.762z"/></g><path fill="#fafafa" d="M108.644 226.897c-.465-2.691-.513-5.243.055-7.751-2.265-1.702-6.328-2.335-9.377-3.33-2.5-1.579-15.253 1.611-24.512-9.588-11.602-14.028-9.16-22.406-9.16-22.406-2.976 3.305-5.854 2.039-10.393 17.448s2.13 26.148 14.562 36.928c5.87 5.09 14.176 7.186 21.313 7.992-2.393-2.401 4.087-2.648 8.551-4.317-.361-3.61.239-7.104 2.928-9.925 1.62-1.702 3.708-2.713 5.87-3.527.124-.28.223-.535.338-.806a7 7 0 0 1-.19-.756z"/><path fill="#bdbdbd" d="M99.632 241.805c-.257-.757-.452-1.53-.643-2.305-.206-.847-1.234-3.25.033-.507a10.2 10.2 0 0 1-.696-2.155c-20.129-.026-37.643-13.846-34.255-42.905-2.632-3.499-6.324 7.055-6.324 7.055S47.675 230.25 73.7 241.59c8.675 3.782 16.339 6.494 18.148 5.4 3.765.765 7.17-1.86 8.444-3.588-.238-.53-.452-1.06-.641-1.599z"/><path fill="#4e342e" d="M108.283 222.68c.03-2.454.532-4.83 1.718-7.196.082-.164.179-.32.267-.478-7.745-.066-16.667-.809-24.264-3.848-8.346-3.341-18.79-14.768-20.59-28.194 0 0-15.721 12.135-11.1 38.108 4.333 24.39 24.741 32.342 48.02 33.687.016-.158-2.615-5.592-1.785-8.918-13.213.962-27.998-4.144-35.127-15.886-6.528-10.738-4.695-29.083-2.014-31.772 6.553 20.664 30.111 24.865 44.887 24.504z"/><path fill="#4e342e" d="M110.717 207.887c-4.189 12.292-12.745 22.24-12.745 22.24s11.77-.543 12.419-2.624c.481-1.537 10.627-25.284 14.521-53.11-3.663 6.02-13.837 32.43-14.195 33.483z"/><g fill="#e78724"><path d="M177.394 179.552s13.34 20.404 23.132 34.884c1.515 2.24-9.791 2.395-9.791 2.395zm-6.356-42.303s4.024 10.035 6.224 15.355c2.393 5.783 11.512 8.66 11.512 8.66s-4.728-4.958-4.728-17.519c0-5.262-6.802-7.359-6.802-7.359l-6.2.872z"/><path d="M175.1 142.92s8.241 9.81 23.547 4.317 16.875-25.117 16.875-30.611-29.04 5.494-32.965 7.849-11.38 11.772-7.457 18.445m57.804-104.83s-14.126-2.75-23.546 4.707c-9.423 7.456-12.17 13.344-12.17 13.344l15.87 12.582s7.672-3.556 10.024-13.76c2.351-10.203.78-14.911 9.81-16.873z"/><path d="M179.227 114.585c6.083-8.634 16.103-12.4 24.109-13.025 13.647-1.066 20.122 3.758 20.122 3.758s-22.349.946-28.791 9.407c-11.993 15.746-29.481 17.025-32.279 13.567 3.232.161 6.792-1.442 10.6-5.043 2.375-2.253 4.308-5.924 6.232-8.664zm37.727 30.528s24.795-8.525 20.086-17.157c-4.709-8.642-.964-13.345-.964-13.345s13.85 10.336 10.318 21.321c-2.169 6.743-5.806 11.627-25.782 20.984-9.587 17.794-1.981 49.83-2.433 49.977-.765.247-13.453-6.273-12.59-36.245.264-9.2.996-21.765 11.356-25.556zm-32.492-91.666a5329 5329 0 0 1 24.64 12.638l-5.6 2.804c.535.868.798 1.385.798 1.385l-5.747 2.616S184.509 83.066 175.9 89.607c2.87-8.835 11.29-22.717 11.29-22.717s2.392-6.378-2.714-13.444zm-34.54 215.317c31.953 0 42.778-16.223 42.778-16.223l-4.991 12.161c-1.888 5.263-22.028 21.634-37.739 21.634"/><path d="M189.201 241.575s-2.943 17.97-14.713 17.97c-10.003 0-12.95-15.179-12.95-18.316zm19.592-27.1c-1.046-2.88-4.708-14.522-5.887-25.116-1.411-12.69-.894-31.249-.894-31.249s3.141 12.166 5.884 14.132c2.75 1.96 7.85 15.302 7.85 15.302s2.733 19.862 4.033 26.538c-3.599.722-6.627-1.4-10.985.393zm28.434-78.732s-6.673-2.356-8.634-16.874c-1.962-14.521 2.355-27.079 2.355-27.079s-.394 20.014 1.957 23.94c2.352 3.924 4.317 5.1 7.063 10.204 2.747 5.102-1.184 8.239-2.746 9.81z"/></g><path fill="#ffcc80" d="m229.254 41.524 1.365-.864c4.015.137-1.365.864-1.365.864"/><path fill="#f9a825" d="M179.03 49.146s6.28-1.046 9.418-5.754c3.141-4.71 12.038-14.13 26.216-14.235 14.178-.107 28.204 3.768 28.204 3.768l-12.244 7.73c-1.296-.042-3.56-.025-7.308.098-15.364.51-17.73 15.705-17.73 15.705l-54.154-7.457"/><path fill="#fafafa" d="M173.8 133.094s7.327 7.326 18.575 4.97c11.252-2.354 18.055-7.325 18.578-15.96.522-8.634-2.354-12.034-2.354-12.034s-12.56 3.93-18.577 9.16-10.464 13.608-16.222 13.871z"/><path fill="#bdbdbd" d="M182.664 130.48s6.356 2.902 13.456.537c9.3-3.1 9.918-12.77 9.918-12.77s5.7 16.737-10.29 19.959c-12.822 2.583-20.408-4.848-20.408-4.848z"/><g fill="#4e342e"><path d="M224.197 67.459c5.182-4.3 1.322-8.29 1.731-13.175.22-2.599.425-5.052 1.283-6.406 4.77-7.53 16.02-9.815 16.135-9.839l5.28-1.034-3.495-4.09c-.453-.53-14.81-14.225-37.027-7.055-15.54 5.013-27.044 22.007-27.471 22.695l7.786 3.663c.09-.145 9.185-16.119 22.522-20.417 10.772-3.478 20.705-.17 24.956 1.998-4.523 1.806-10.435 5.094-14.003 10.72-1.686 2.655-1.966 6.002-2.237 9.24-.362 4.288-.707 8.336-3.865 10.957l8.38 2.743zm13.838 62.765s-6.526-8.097-8.46-23.852c-.76-6.206.587-18.446 2.746-23.155-.393 11.578 2.553 23.155 2.553 23.155s1.985 21.497 3.161 23.852"/><path d="M203.607 59.281c.004-.016 2.097-9.158 7.896-13.773 8.18-6.507 18.17-3.045 18.263-3.015l1.455-4.481c-.485-.156-11.901-3.754-22.426 3.642-10.59 7.439-11.857 14.181-11.972 14.926l6.775 2.701zm13.924 65.136s3.425-4.904 2.806-10.297c-.304-2.664-1.538-5.397-3.741-6.367-4.095-1.793-5.91 2.845-5.91 2.845s5.763 1.422 6.845 13.822z"/><path d="M179.918 131.893c-.142.268-.216.417-.216.417s10.68 8.019 21.63-.118c5.866-4.358 5.313-15.138 3.512-19.71-4.666 1.061-8.626 2.969-11.94 5.197 4.186-3.733 7.848-6.48 7.835-6.545l4.759-1.349 9.234-3.165c.115.707 3.486 16.51-6.25 27.274-4.316 4.777-24.536 15.467-34.132-2.812l5.55.83z"/><path d="M180.913 133.07c-6.016 9.155-21.19 3.923-20.927-5.757 0 0 10.139 5.598 19.098-4.708 5.231-6.01 21.997-22.604 44.729-17.086-15.697 3.453-36.482 17.793-42.9 27.562z"/><path d="M225.94 158.905c-1.447.836-6.554 6.121-6.554 14.027-.003 3.964.393 23.879 2.357 36.044-2.952 1.918-5.008 2.325-7.946 4.28-1.472-14.09-2.53-34.512-2.035-42.756.562-9.398 5.592-15.705 10.257-18.394 1.461-.84 2.99-1.667 4.531-2.498 7.992-4.318 16.256-8.786 16.256-16.414 0-5.967-2.322-7.833-4.777-9.812l-.263-.214c-1.628-1.317-3.477-2.81-4.566-5.262-2.985-6.704-3.479-23.78-.009-28.116 1.727-2.162 6.365-9.43 5.033-14.307-.51-1.866-1.686-3.248-3.594-4.226-2.022-1.036-4.752-1.563-8.115-1.563-6.603 0-13.93 2.007-17.704 3.207-13.501 4.276-29.79 16.61-34.469 20.294-.131.098-.214.164-.23.172l-2.993 2.08 1.866-3.132c.116-.198 11.948-19.66 33.113-26.798 4.12-1.39 12.202-3.716 20.153-3.716 4.728 0 8.741.822 11.923 2.45 3.873 1.982 6.496 5.147 7.59 9.144 2.672 9.8-6.027 20.712-6.332 21.066-1.02 1.809-1.447 14.965.897 20.236.32.723 1.208 1.439 2.327 2.343q.53.42 1.159.888c3.305 2.492 8.305 6.266 8.305 14.957 0 11.89-12.055 18.345-21.74 23.525-1.588.855-3.109 1.66-4.474 2.45z"/><path d="M211.559 66.06c-1.918-3.249-6.822-9.52-18.125-15.032-12.613-6.147-27.212-9.267-43.396-9.275v-.003h-.058v.008c-16.182.008-30.785 3.133-43.399 9.275-11.297 5.518-16.198 11.783-18.122 15.031l-.822 1.094 9.677 2.153.31-.386.163-.357c.148-.642 1.447-4.095 12.238-9.357 11.536-5.626 24.989-8.478 39.987-8.486 14.998.006 28.45 2.859 39.986 8.486 10.788 5.262 12.095 8.715 12.243 9.355l.157.356.304.387 9.678-2.155-.822-1.088z"/><path d="M224.197 67.459c5.182-4.3 1.322-8.29 1.731-13.175.22-2.599.425-5.052 1.283-6.406 4.77-7.53 16.02-9.815 16.135-9.839l5.28-1.034-3.495-4.09c-.453-.53-14.81-14.225-37.027-7.055-15.54 5.013-27.044 22.007-27.471 22.695l7.786 3.663c.09-.145 9.185-16.119 22.522-20.417 10.772-3.478 20.705-.17 24.956 1.998-4.523 1.806-10.435 5.094-14.003 10.72-1.686 2.655-1.966 6.002-2.237 9.24-.362 4.288-.707 8.336-3.865 10.957l8.38 2.743z"/><path d="m214.223 65.017 1.09-.908c2.903-2.408 3.228-6.296 3.578-10.43.282-3.33.572-6.767 2.354-9.587 3.274-5.172 8.458-8.404 12.728-10.336-2.557-1.086-7.36-2.697-13.284-2.697-3.273 0-6.465.493-9.502 1.472-12.367 3.988-21.104 18.394-22.094 20.087l-.37.584-9.218-4.333.469-.748c.11-.173 11.676-17.794 27.895-23.024 4.342-1.406 8.7-2.113 12.959-2.113 15.615 0 24.832 9.308 24.906 9.399l4.375 5.114-6.595 1.291c-.107.017-11.084 2.319-15.623 9.489-.748 1.192-.946 3.552-1.16 6.052-.123 1.488.19 2.935.494 4.341.658 3.034 1.34 6.184-2.5 9.366l-.329.271-10.146-3.33z"/><path d="M203.607 59.281c.004-.016 2.097-9.158 7.896-13.773 8.18-6.507 18.17-3.045 18.263-3.015l1.455-4.481c-.485-.156-11.901-3.754-22.426 3.642-10.59 7.439-11.857 14.181-11.972 14.926l6.775 2.701z"/><path d="m195.968 57.08.09-.615c.116-.778 1.442-7.828 12.29-15.454 4.465-3.136 9.818-4.795 15.467-4.795 4.292 0 7.318.946 7.655 1.053l.749.246-1.94 5.978-.75-.247c-.279-.09-2.803-.904-6.19-.904-4.35 0-8.158 1.283-11.315 3.799-5.542 4.415-7.598 13.238-7.614 13.329l-.198.904-8.206-3.273zm33.294-15.557.966-2.975c-1.14-.29-3.447-.76-6.414-.76-5.405 0-10.305 1.518-14.562 4.51-8.903 6.257-11.03 11.912-11.513 13.797l5.342 2.127c.699-2.483 3.013-9.408 7.94-13.329 3.404-2.702 7.655-4.13 12.3-4.13 2.673 0 4.827.46 5.946.76zm-60.209 211.304c-4.043-4.323-6.435-8.975-7.013-10.404-.33-.814-.708-2.365.479-3.585.924-.943 2.526-1.427 4.766-1.427h3.453c3.594 0 7.795 0 10.295.008l2.097.008c2.943 0 4.399.847 5.09 1.546 1.02 1.028 1.175 2.459.476 4.251-1.874 4.777-6.117 8.683-7.375 9.76-1.645 1.423-4.005 2.262-6.323 2.262-2.377 0-4.482-.856-5.929-2.401zm3.5-119.227 8.367-.539s-2.138 3.773-3.523 8.652c-1.57 5.517 1.43 13.584 1.43 13.584s-11.166-12.639-6.281-21.7z"/></g><path fill="#e78724" d="M150.004 103.715c-5.336 0-12.293-.146-17.512-3.898 0 0 6.834 11.982 17.503 11.982l.008-1.516.01 1.516c10.67 0 17.504-11.98 17.504-11.98-5.22 3.75-12.182 3.897-17.513 3.897z"/><path fill="#4e342e" d="M164.698 103.657c-5.353 3.24-10.132 4.362-14.691 4.462-4.56-.1-9.339-1.222-14.692-4.461 0 0 7.795 9.513 14.653 9.587v.009h.038c.012 0 .024.008.038.008 6.858-.074 14.661-9.58 14.661-9.58zm18.3 173.686-.598-7.758c25.137-1.932 33.055-26.019 33.096-28.554h7.787c.008 5.863-10.484 34.022-40.274 36.311z"/><path fill="#fafafa" d="M191.372 226.897c.467-2.691.512-5.243-.055-7.751 2.268-1.702 6.328-2.335 9.377-3.33 2.493-1.579 15.255 1.611 24.512-9.588 11.596-14.028 9.151-22.406 9.151-22.406 2.977 3.305 5.856 2.039 10.392 17.448 4.539 15.41-2.134 26.148-14.564 36.928-5.87 5.09-14.174 7.186-21.314 7.992 2.392-2.401-4.079-2.648-8.544-4.317.362-3.61-.238-7.104-2.927-9.925-1.612-1.702-3.7-2.713-5.863-3.527-.123-.28-.222-.535-.337-.806.074-.247.14-.493.19-.756z"/><path fill="#bdbdbd" d="M200.376 241.805c.261-.757.452-1.53.644-2.305.21-.847 1.238-3.25-.03-.507a10.2 10.2 0 0 0 .695-2.155c20.13-.026 37.643-13.846 34.257-42.905 2.635-3.499 6.328 7.055 6.328 7.055s10.078 29.262-15.95 40.603c-8.672 3.782-16.335 6.494-18.144 5.4-3.77.765-7.17-1.86-8.442-3.588.238-.53.46-1.06.65-1.599z"/><g fill="#4e342e"><path d="M191.734 222.68c-.028-2.454-.532-4.83-1.715-7.196-.083-.164-.18-.32-.268-.478 7.746-.066 16.668-.809 24.265-3.848 8.35-3.341 18.795-14.768 20.59-28.194 0 0 15.726 12.135 11.105 38.108-4.341 24.39-24.747 32.342-48.023 33.687-.013-.158 2.619-5.592 1.787-8.918 13.213.962 27.998-4.144 35.135-15.886 6.529-10.738 4.695-29.083 2.014-31.772-6.545 20.664-30.11 24.865-44.887 24.504z"/><path d="M201.132 228.797c-2.78-3.006-7.893-6.59-19.682-6.59l-31.394-.019h-.074c-9.045.007-31.402.02-31.402.02-11.783 0-16.898 3.584-19.677 6.589-4.054 4.374-4.687 10.461-1.883 18.069 7.45 20.249 17.925 40.821 52.97 40.85v.003h.041c.017 0 .025.008.041.008 35.045-.024 45.52-20.597 52.97-40.85 2.804-7.606 2.171-13.69-1.883-18.065zm-5.456 16.649c-3.55 10.168-13.09 34.78-45.669 34.823-32.58-.043-42.117-24.654-45.668-34.823-1.963-5.64-1.814-9.816.46-12.41 1.555-1.772 5.123-3.889 13.255-3.889l8.497-.002c6.268-.006 14.138-.013 23.459-.017 9.316.004 17.19.01 23.457.017l8.493.003c8.135 0 11.703 2.113 13.257 3.88 2.272 2.591 2.423 6.768.459 12.409z"/><path d="M189.292 207.887c4.188 12.292 12.743 22.24 12.743 22.24s-11.766-.543-12.416-2.624c-.477-1.537-10.624-25.284-14.513-53.11 3.667 6.02 13.839 32.43 14.2 33.483z"/></g>"##, +}; +pub(super) static GULP: Icon = Icon { + name: "gulp", + view: 32.0, + body: r##"<path fill="#e53935" d="M17.5 12V7.75l3.4-2.55a1.5 1.5 0 0 0-1.8-2.4l-4.6 3.45V12H8v2h2l1.38 16h9.255L22 14h2v-2Z"/>"##, +}; +pub(super) static H: Icon = Icon { + name: "h", + view: 32.0, + body: r##"<path fill="#0288d1" d="M18.5 11a5.49 5.49 0 0 0-4.5 2.344V4H8v24h6V17a2 2 0 0 1 4 0v11h6V16.5a5.5 5.5 0 0 0-5.5-5.5"/>"##, +}; +pub(super) static HASKELL: Icon = Icon { + name: "haskell", + view: 300.0, + body: r##"<g stroke-width="2.422"><path fill="#ef5350" d="m23.928 240.5 59.94-89.852-59.94-89.855h44.955l59.94 89.855-59.94 89.852z"/><path fill="#ffa726" d="m83.869 240.5 59.94-89.852-59.94-89.855h44.955l119.88 179.71h-44.95l-37.46-56.156-37.468 56.156z"/><path fill="#ffee58" d="m228.72 188.08-19.98-29.953h69.93v29.956h-49.95zm-29.97-44.924-19.98-29.953h99.901v29.953z"/></g>"##, +}; +pub(super) static HJSON: Icon = Icon { + name: "hjson", + view: 24.0, + body: r##"<path fill="#78909c" d="M11.652 3.92a1.1 1.1 0 0 0-.626-.014 1.11 1.11 0 0 0-.786 1.359 1.11 1.11 0 0 0 1.362.788 1.11 1.11 0 0 0 .786-1.363 1.11 1.11 0 0 0-.736-.771zm-3.6-.229a1 1 0 0 0-.246-.027h-.002a418 418 0 0 1-3.02-.096.84.84 0 0 0-.38.089.69.69 0 0 0-.339.506v.001a.68.68 0 0 0 .168.553.9.9 0 0 0 .41.235l.002.001c1.275.388 2.552.766 3.923 1.179l.496.15-.133-.5c-.16-.6-.314-1.098-.423-1.592a.67.67 0 0 0-.292-.434.6.6 0 0 0-.164-.065m2.613 3.73a.56.56 0 0 0-.274.003l-.362.097a.554.554 0 0 0-.392.678l1.105 4.123a.55.55 0 0 0 .677.39l.364-.098a.55.55 0 0 0 .392-.676L11.07 7.816a.55.55 0 0 0-.404-.396z"/><path fill="#8bc34a" d="m21.578 9.77-2.203.59.59 2.203-5.508 1.476a2.28 2.28 0 0 0-1.612 2.793 2.28 2.28 0 0 0-2.79-1.61l-5.508 1.475-.59-2.205-2.203.59.59 2.205A2.28 2.28 0 0 0 5.138 18.9l4.406-1.18a2.28 2.28 0 0 1 2.792 1.61l.295 1.102 2.203-.59-.295-1.103a2.28 2.28 0 0 1 1.613-2.79l4.405-1.18a2.28 2.28 0 0 0 1.612-2.794v-.002z"/>"##, +}; +pub(super) static HPP: Icon = Icon { + name: "hpp", + view: 32.0, + body: r##"<path fill="#0288d1" d="M28 6V2h-2v4h-6V2h-2v4h-4v2h4v4h2V8h6v4h2V8h4V6zm-15.5 5A5.49 5.49 0 0 0 8 13.344V4H2v24h6V17a2 2 0 0 1 4 0v11h6V16.5a5.5 5.5 0 0 0-5.5-5.5"/>"##, +}; +pub(super) static HTML: Icon = Icon { + name: "html", + view: 32.0, + body: r##"<path fill="#e65100" d="m4 4 2 22 10 2 10-2 2-22Zm19.72 7H11.28l.29 3h11.86l-.802 9.335L15.99 25l-6.635-1.646L8.93 19h3.02l.19 2 3.86.77 3.84-.77.29-4H8.84L8 8h16Z"/>"##, +}; +pub(super) static IMAGE: Icon = Icon { + name: "image", + view: 16.0, + body: r##"<path fill="#26a69a" d="M8.5 6h4l-4-4zM3.875 1H9.5l4 4v8.6c0 .773-.616 1.4-1.375 1.4h-8.25c-.76 0-1.375-.627-1.375-1.4V2.4c0-.777.612-1.4 1.375-1.4M4 13.6h8V8l-2.625 2.8L8 9.4zm1.25-7.7c-.76 0-1.375.627-1.375 1.4s.616 1.4 1.375 1.4c.76 0 1.375-.627 1.375-1.4S6.009 5.9 5.25 5.9"/>"##, +}; +pub(super) static INSTALLATION: Icon = Icon { + name: "installation", + view: 16.0, + body: r##"<path fill="#ff5722" d="M12 7h-2V2H6v5H4l4 4zm-9 5.5V14h10v-1.5z"/>"##, +}; +pub(super) static IONIC: Icon = Icon { + name: "ionic", + view: 512.0, + body: r##"<g fill="#448aff"><path d="M423.59 132.8a31.86 31.86 0 0 0 5.408-17.804c0-17.675-14.33-32-32-32a31.85 31.85 0 0 0-17.805 5.409c-34.486-25.394-77.085-40.409-123.2-40.409-114.88 0-208 93.125-208 208 0 114.88 93.125 208 208 208 114.87 0 208-93.123 208-208 0-46.111-15.016-88.71-40.408-123.2zm-31.762 259.03c-17.646 17.646-38.191 31.499-61.064 41.174-23.672 10.012-48.826 15.089-74.766 15.089s-51.095-5.077-74.767-15.089c-22.873-9.675-43.417-23.527-61.064-41.174s-31.5-38.191-41.174-61.064c-10.013-23.672-15.09-48.828-15.09-74.768s5.077-51.095 15.089-74.767c9.674-22.873 23.527-43.417 41.174-61.064s38.191-31.5 61.064-41.174c23.673-10.013 48.828-15.09 74.768-15.09s51.094 5.077 74.766 15.089a191.2 191.2 0 0 1 37.802 21.327 31.85 31.85 0 0 0-3.568 14.679c0 17.675 14.327 32 32 32 5.293 0 10.28-1.293 14.678-3.568a191 191 0 0 1 21.327 37.801c10.013 23.672 15.09 48.827 15.09 74.767s-5.077 51.096-15.09 74.768c-9.675 22.873-23.527 43.418-41.175 61.064"/><circle cx="256" cy="256" r="96"/></g>"##, +}; +pub(super) static JAVA: Icon = Icon { + name: "java", + view: 32.0, + body: r##"<path fill="#f44336" d="M4 26h24v2H4zM28 4H7a1 1 0 0 0-1 1v13a4 4 0 0 0 4 4h10a4 4 0 0 0 4-4v-4h4a2 2 0 0 0 2-2V6a2 2 0 0 0-2-2m0 8h-4V6h4Z"/>"##, +}; +pub(super) static JAVASCRIPT: Icon = Icon { + name: "javascript", + view: 16.0, + body: r##"<path fill="#ffca28" d="M2 2v12h12V2zm6 6h1v4a1.003 1.003 0 0 1-1 1H7a1.003 1.003 0 0 1-1-1v-1h1v1h1zm3 0h2v1h-2v1h1a1.003 1.003 0 0 1 1 1v1a1.003 1.003 0 0 1-1 1h-2v-1h2v-1h-1a1.003 1.003 0 0 1-1-1V9a1.003 1.003 0 0 1 1-1"/>"##, +}; +pub(super) static JAVASCRIPT_MAP: Icon = Icon { + name: "javascript-map", + view: 16.0, + body: r##"<g fill="#ffca28"><path d="M12 5v1h1v7H6v-1H5l-.069 2 9.069.001V5z"/><path d="M2 2v9h9V2zm3 3h1v4a1.003 1.003 0 0 1-1 1H4a1.003 1.003 0 0 1-1-1V8h1v1h1zm3 0h2v1H8v1h1a1.003 1.003 0 0 1 1 1v1a1.003 1.003 0 0 1-1 1H7V9h2V8H8a1.003 1.003 0 0 1-1-1V6a1.003 1.003 0 0 1 1-1"/></g>"##, +}; +pub(super) static JEST: Icon = Icon { + name: "jest", + view: 32.0, + body: r##"<path fill="#f4511e" d="m21.032 8-1.878 4L20 13.998h2L22.928 12z"/><path fill="#f4511e" d="m14 2 2 8h2l3.032-6L24 10h2l2-8zm14 18h-2a4.34 4.34 0 0 1-4-4h-2a4.17 4.17 0 0 1-4.23 3.87c-1.522 2.38-5.155 4.283-7.77 5.148A4.724 4.724 0 0 1 5 20H4c-4.718 7.978 3.064 13.219 10.955 7.895C18.85 24.497 29.658 27.487 28 20"/><circle cx="7" cy="15" r="3" fill="#f4511e"/><circle cx="27" cy="15" r="3" fill="#f4511e"/><circle cx="16" cy="16" r="2" fill="#f4511e"/>"##, +}; +pub(super) static JSCONFIG: Icon = Icon { + name: "jsconfig", + view: 32.0, + body: r##"<path fill="#757575" d="M15 2H6a2.006 2.006 0 0 0-2 2v22a2.006 2.006 0 0 0 2 2h6v-4H6v-2h6v-2H6v-2h6v-2H6v-2h6v-2h2V4l8 8h2v-1Z" data-mit-no-recolor="true"/><path fill="#ffca28" d="M12 12v18h18V12zm8 12a2.006 2.006 0 0 1-2 2h-2a2.006 2.006 0 0 1-2-2v-2h2v2h2v-8h2zm8-6h-4v2h2a2.006 2.006 0 0 1 2 2v2a2.006 2.006 0 0 1-2 2h-4v-2h4v-2h-2a2.006 2.006 0 0 1-2-2v-2a2.006 2.006 0 0 1 2-2h4z"/>"##, +}; +pub(super) static JSON: Icon = Icon { + name: "json", + view: 960.0, + body: r##"<g transform="translate(-0 960)"><path fill="#f9a825" d="M560-160v-80h120q17 0 28.5-11.5T720-280v-80q0-38 22-69t58-44v-14q-36-13-58-44t-22-69v-80q0-17-11.5-28.5T680-720H560v-80h120q50 0 85 35t35 85v80q0 17 11.5 28.5T840-560h40v160h-40q-17 0-28.5 11.5T800-360v80q0 50-35 85t-85 35zm-280 0q-50 0-85-35t-35-85v-80q0-17-11.5-28.5T120-400H80v-160h40q17 0 28.5-11.5T160-600v-80q0-50 35-85t85-35h120v80H280q-17 0-28.5 11.5T240-680v80q0 38-22 69t-58 44v14q36 13 58 44t22 69v80q0 17 11.5 28.5T280-240h120v80z"/></g>"##, +}; +pub(super) static JULIA: Icon = Icon { + name: "julia", + view: 50.0, + body: r##"<g transform="translate(.21 -247.01)"><circle cx="13.497" cy="281.63" r="9.555" fill="#c62828"/><circle cx="36.081" cy="281.63" r="9.555" fill="#7e57c2"/><circle cx="24.722" cy="262.39" r="9.555" fill="#388e3c"/></g>"##, +}; +pub(super) static KEY: Icon = Icon { + name: "key", + view: 32.0, + body: r##"<path fill="#26a69a" d="M30 14H17.738a8 8 0 1 0 0 4H24v4h4v-4h2Zm-20 5a3 3 0 1 1 3-3 3.003 3.003 0 0 1-3 3"/>"##, +}; +pub(super) static KOTLIN: Icon = Icon { + name: "kotlin", + view: 24.0, + body: r##"<defs><linearGradient id="a" x1="1.725" x2="22.185" y1="22.67" y2="1.982" gradientTransform="translate(1.306 1.129)scale(.89324)" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="#7c4dff"/><stop offset=".5" stop-color="#d500f9"/><stop offset="1" stop-color="#ef5350"/></linearGradient></defs><path fill="url(#a)" d="M2.975 2.976v18.048h18.05v-.03l-4.478-4.511-4.48-4.515 4.48-4.515 4.443-4.477z"/>"##, +}; +pub(super) static KUBERNETES: Icon = Icon { + name: "kubernetes", + view: 24.0, + body: r##"<path fill="#448aff" d="M12.074 1.424a.638.638 0 0 0-.686.691v.173c.015.2.044.402.087.588.058.358.085.73.07 1.102a.65.65 0 0 1-.201.33l-.014.258a7 7 0 0 0-1.117.17 7.9 7.9 0 0 0-4.012 2.292l-.213-.157a.56.56 0 0 1-.374-.042 6 6 0 0 1-.829-.747c-.129-.143-.26-.299-.403-.428l-.128-.1a.8.8 0 0 0-.431-.171c-.2 0-.372.07-.501.212-.2.301-.127.675.16.904l.013.014c.03.029.087.072.115.1q.258.172.515.3c.33.186.631.403.918.647a.63.63 0 0 1 .114.358l.2.17a7.82 7.82 0 0 0-1.232 5.546l-.271.07a.84.84 0 0 1-.275.274c-.358.086-.73.17-1.102.17-.186 0-.387 0-.588.057l-.156.03h-.014v.015c-.043 0-.086.014-.115.014a.62.62 0 0 0-.4.789.625.625 0 0 0 .772.386 1 1 0 0 0 .188-.045c.186-.057.37-.127.528-.213a7.4 7.4 0 0 1 1.103-.316c.114 0 .244.057.33.129l.285-.042a8.04 8.04 0 0 0 3.54 4.426l-.1.258a.8.8 0 0 1 .044.358c-.143.344-.33.687-.56.987-.114.172-.215.33-.344.501 0 .043.001.117-.056.16-.014.043-.044.072-.059.114a.615.615 0 0 0 .372.787.62.62 0 0 0 .79-.372c.028-.043.055-.143.083-.143.072-.2.131-.387.174-.574a5.4 5.4 0 0 1 .473-1.102.5.5 0 0 1 .271-.129l.143-.257c1.82.702 3.84.701 5.688.014l.115.23a.53.53 0 0 1 .3.198c.186.33.301.674.43 1.032.043.187.102.373.174.588.028 0 .055.086.084.129.014.043.03.071.044.114a.61.61 0 0 0 .845.216.614.614 0 0 0 .213-.845c-.014-.057-.056-.13-.056-.174-.115-.157-.23-.329-.344-.486-.215-.316-.371-.63-.543-.974a.48.48 0 0 1 .042-.372 1.2 1.2 0 0 1-.1-.244c1.661-1.002 2.951-2.577 3.539-4.454.086.014.17.028.271.042.086-.115.201-.115.33-.115.387.057.73.16 1.103.302q.235.128.514.213c.058.014.116.03.202.03v.015c0 .014.058.013.1.028.344.043.617-.202.689-.532a.617.617 0 0 0-.532-.7c-.057-.014-.127-.03-.17-.072h-.588a7 7 0 0 1-1.102-.202.6.6 0 0 1-.274-.257l-.272-.07a7.8 7.8 0 0 0-1.262-5.531l.23-.2a.44.44 0 0 1 .114-.343c.273-.244.589-.46.918-.647a3.6 3.6 0 0 0 .5-.3 1 1 0 0 0 .13-.1c.043-.028.086-.058.086-.087.258-.243.273-.63 0-.859-.214-.257-.601-.257-.845 0-.043 0-.1.059-.142.087a11 11 0 0 0-.403.428c-.244.272-.53.532-.831.747a.55.55 0 0 1-.372.042l-.23.171a7.98 7.98 0 0 0-5.098-2.462l-.014-.274a.5.5 0 0 1-.201-.314 5.6 5.6 0 0 1 .07-1.102 4 4 0 0 0 .087-.588v-.316a.62.62 0 0 0-.546-.548m-.842 4.773-.174 3.223h-.014a.56.56 0 0 1-.114.302.543.543 0 0 1-.745.13h-.014L7.536 7.973a6.23 6.23 0 0 1 3.035-1.662c.23-.043.446-.086.66-.115zm1.544 0a6.38 6.38 0 0 1 3.682 1.777L13.837 9.85h-.014a.66.66 0 0 1-.3.073.535.535 0 0 1-.56-.518zm-6.2 2.938 2.406 2.19v.015c.086.071.157.16.157.274a.523.523 0 0 1-.372.657v.014l-3.095.89a6.4 6.4 0 0 1 .904-4.04m10.842.042c.73 1.189 1.032 2.595.932 3.984l-3.109-.89-.014-.014a.5.5 0 0 1-.257-.17.53.53 0 0 1 .056-.761l-.014-.042zm-5.915 2.322h.988l.615.758-.215.96-.887.431-.887-.43-.23-.96zm-2.308 2.65h.115c.243 0 .46.17.545.414 0 .1.001.23-.056.302v.042l-1.22 2.966a6.33 6.33 0 0 1-2.563-3.195zm5.274 0h.344l3.193.515a6.34 6.34 0 0 1-2.563 3.223l-1.234-3.022c-.115-.258.002-.558.26-.716m-2.521 1.298a.55.55 0 0 1 .529.277h.014l1.561 2.823a5 5 0 0 1-.615.171 6.4 6.4 0 0 1-3.481-.17l1.561-2.824h.014c.043-.1.115-.144.216-.215a.5.5 0 0 1 .201-.062"/>"##, +}; +pub(super) static LERNA: Icon = Icon { + name: "lerna", + view: 24.0, + body: r##"<path fill="#448aff" d="M7.57 8.21c-.41.08-.99.06-1.26.06-.4 0-1.27-.48-1.75-.98-.25-.26-.71-.82-1.01-1.25-.31-.43-.62-.78-.71-.78-.17 0-.28.6-.29 1.6 0 .12-.01.22-.01.31l.01.03-.14 8.47c.27.07.54.13.82.19.58.12 1.06.22 1.08.23.01.02-.19.34-.45.71-.95 1.35-1.14 2-.6 2 .17 0 .53-.07.82-.17.33-.1.93-.16 1.58-.16 1.34 0 2.68.33 4.37 1.08 1.61.71 2.14.88 4 1.25.85.18 1.59.37 1.64.41.05.05-.07.22-.28.38s-.38.33-.38.37.22.04.51-.01c.27-.04.89-.14 1.36-.19 1.43-.18 2.45-.82 2.47-1.56.04-.94-.25-3.03-.43-3.14-.02-.01-.38.11-.46.24-.07.13-.16.33-.25.56-.18.46-.15.56-1.57.66-1.03.05-2.02-.19-2.82-.65-.67-.39-1.66-.74-2.18-1.54-.42-.65-.86-1.72-.78-1.87.03-.04.17-.03.32.02.39.15.96.38 2.73.15 1.54-.2 3-.04 3.39.16s.92.47.94.99c.01.52.33.63.36.63.17-.03.59-1.42.83-1.83.2-.32.31-.5 1.1-1.04.62-.43 1.13-.83 1.11-.9-.01-.06-.36-.47-.77-.92-.65-.7-.83-.82-1.42-1.02-2.05-.67-4.23-2.12-5.36-3.54-1.25-1.58-1.6-1.94-2.5-2.53-1.01-.67-2.32-1.24-3.3-1.43-1-.19-.72.13-.29.8 1.53 1.75 1.49 1.81 1.49 2.97-.16.9-1 1.03-1.92 1.24m3.17 1.03c.17 0 .58.11 1.29.35 1.74.58 1.84.85 2.41 1.85.13.22.22.41.21.42s-.17.05-.35.09c-.45.09-1.16.09-1.58 0-.76-.16-.72-.19-1.11-.57-.16-.16-.35-.42-.41-.56-.04-.1-.03-.12.19-.3.05-.04.1-.11.1-.15 0-.07-.22-.37-.34-.47-.13-.11-.49-.54-.49-.59 0-.03.03-.05.1-.05z"/>"##, +}; +pub(super) static LESS: Icon = Icon { + name: "less", + view: 24.0, + body: r##"<path fill="#0277bd" d="M8 3a2 2 0 0 0-2 2v4a2 2 0 0 1-2 2H3v2h1a2 2 0 0 1 2 2v4a2 2 0 0 0 2 2h2v-2H8v-5a2 2 0 0 0-2-2 2 2 0 0 0 2-2V5h2V3m6 0a2 2 0 0 1 2 2v4a2 2 0 0 0 2 2h1v2h-1a2 2 0 0 0-2 2v4a2 2 0 0 1-2 2h-2v-2h2v-5a2 2 0 0 1 2-2 2 2 0 0 1-2-2V5h-2V3z"/>"##, +}; +pub(super) static LOCK: Icon = Icon { + name: "lock", + view: 32.0, + body: r##"<path fill="#ffd54f" d="M25 12h-3V8a6 6 0 0 0-12 0v4H7a1 1 0 0 0-1 1v16a1 1 0 0 0 1 1h18a1 1 0 0 0 1-1V13a1 1 0 0 0-1-1M14 8a2 2 0 0 1 4 0v4h-4Zm2 17a4 4 0 1 1 4-4 4 4 0 0 1-4 4"/>"##, +}; +pub(super) static LOG: Icon = Icon { + name: "log", + view: 24.0, + body: r##"<g fill="none"><path d="M0 0h24v24H0z"/><path fill="#afb42b" d="M19 5v9h-5v5H5V5zm0-2H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h10l6-6V5c0-1.1-.9-2-2-2m-7 11H7v-2h5zm5-4H7V8h10z"/></g>"##, +}; +pub(super) static LUA: Icon = Icon { + name: "lua", + view: 32.0, + body: r##"<path fill="#42a5f5" d="M30 6a3.86 3.86 0 0 1-1.167 2.833 4.024 4.024 0 0 1-5.666 0A3.86 3.86 0 0 1 22 6a3.86 3.86 0 0 1 1.167-2.833 4.024 4.024 0 0 1 5.666 0A3.86 3.86 0 0 1 30 6m-9.208 5.208A10.6 10.6 0 0 0 13 8a10.6 10.6 0 0 0-7.792 3.208A10.6 10.6 0 0 0 2 19a10.6 10.6 0 0 0 3.208 7.792A10.6 10.6 0 0 0 13 30a10.6 10.6 0 0 0 7.792-3.208A10.6 10.6 0 0 0 24 19a10.6 10.6 0 0 0-3.208-7.792m-1.959 7.625a4.024 4.024 0 0 1-5.666 0 4.024 4.024 0 0 1 0-5.666 4.024 4.024 0 0 1 5.666 0 4.024 4.024 0 0 1 0 5.666"/>"##, +}; +pub(super) static MAKEFILE: Icon = Icon { + name: "makefile", + view: 32.0, + body: r##"<path fill="#ef5350" d="m29.5 24.02-1.6-.92a4.4 4.4 0 0 0 .09-.9A1.3 1.3 0 0 0 28 22a5.6 5.6 0 0 0-.1-1.1l1.6-.92a.493.493 0 0 0 .18-.68l-1.5-2.6a.45.45 0 0 0-.18-.18V6.01a2.006 2.006 0 0 0-2-2H4a2.006 2.006 0 0 0-2 2V22a2.006 2.006 0 0 0 2 2h10.53l-.03.02a.493.493 0 0 0-.18.68l1.5 2.6a.493.493 0 0 0 .68.18l1.6-.92a5.9 5.9 0 0 0 1.9 1.09v1.85a.495.495 0 0 0 .5.5h3a.495.495 0 0 0 .5-.5v-1.85a5.9 5.9 0 0 0 1.9-1.09l1.6.92a.493.493 0 0 0 .68-.18l1.5-2.6a.493.493 0 0 0-.18-.68M24 22.01a1.99 1.99 0 0 1-.88 1.65l-.18.11a2.04 2.04 0 0 1-1.88 0l-.18-.11a1.99 1.99 0 0 1-.88-1.65V22a2 2 0 0 1 .88-1.66l.18-.11a2.04 2.04 0 0 1 1.88 0l.18.11A2 2 0 0 1 24 22Zm2-4.63-.1.06a5.9 5.9 0 0 0-1.9-1.09V14.5a.495.495 0 0 0-.5-.5h-3a.495.495 0 0 0-.5.5v1.85a5.9 5.9 0 0 0-1.9 1.09l-1.6-.92a.493.493 0 0 0-.68.18l-1.5 2.6a.493.493 0 0 0 .18.68l1.6.92A5.6 5.6 0 0 0 16 22v.01L4 22V10.01h22Z"/>"##, +}; +pub(super) static MARKDOWN: Icon = Icon { + name: "markdown", + view: 32.0, + body: r##"<path fill="#42a5f5" d="m14 10-4 3.5L6 10H4v12h4v-6l2 2 2-2v6h4V10zm12 6v-6h-4v6h-4l6 8 6-8z"/>"##, +}; +pub(super) static MAVEN: Icon = Icon { + name: "maven", + view: 24.0, + body: r##"<defs><linearGradient id="a" x1=".125" x2="0" y1="1" y2="0"><stop offset="0%" stop-color="#ab47bc"/><stop offset="37.5%" stop-color="#ab47bc"/><stop offset="37.501%" stop-color="#d32f2f"/><stop offset="54.25%" stop-color="#d32f2f"/><stop offset="54.251%" stop-color="#ff7043"/><stop offset="69.75%" stop-color="#ff7043"/><stop offset="69.751%" stop-color="#ffa726"/><stop offset="100%" stop-color="#ffa726"/></linearGradient></defs><path fill="url(#a)" d="M22 2s-7.64-.37-13.66 7.88C3.72 16.21 2 22 2 22l1.94-1c1.44-2.5 2.19-3.53 3.6-5 2.53.74 5.17.65 7.46-2-2-.56-3.6-.43-5.96-.19C11.69 12 13.5 11.6 16 12l1-2c-1.8-.34-3-.37-4.78.04C14.19 8.65 15.56 7.87 18 8l1.11-1.73c-1.53-.06-2.4-.02-4.19.3 1.61-1.46 3.08-2.12 5.22-2.25 0 0 1.05-1.89 1.86-2.32"/>"##, +}; +pub(super) static MDX: Icon = Icon { + name: "mdx", + view: 32.0, + body: r##"<path fill="#ffca28" d="m14 10-4 3.5L6 10H4v12h4v-6l2 2 2-2v6h4V10zm12 6v-6h-4v6h-4l6 8 6-8z"/>"##, +}; +pub(super) static NETLIFY: Icon = Icon { + name: "netlify", + view: 24.0, + body: r##"<path fill="#00bfa5" d="m11.25 2.232-.127.127v4.567l.127.129h1.526l.126-.13V2.36l-.126-.127H11.25zM6.69 5.455 5.643 6.5v.21l1.6 1.6h1.108l.148-.148V7.055l-1.6-1.6zM1.026 11.11l-.127.127v1.528l.127.127h6.09l.127-.127v-1.528l-.127-.127zm15.858 0-.127.127v1.528l.127.127h6.09l.127-.127v-1.528l-.127-.127zm-9.64 4.58-1.6 1.6v.21l1.045 1.046h.21l1.6-1.6v-1.109l-.148-.146zm4.005 1.256-.127.13v4.566l.127.127h1.526l.126-.127v-4.567l-.126-.129z"/><path fill="#cfd8dc" d="M14.855 15.172h-1.523l-.127-.127V11.48c0-.634-.249-1.125-1.013-1.142-.394-.01-.844 0-1.325.019l-.072.074v4.61l-.127.128H9.146l-.128-.127V8.956l.128-.127h3.425a2.41 2.41 0 0 1 2.41 2.41v3.806z"/>"##, +}; +pub(super) static NEXT: Icon = Icon { + name: "next", + view: 32.0, + body: r##"<path fill="#cfd8dc" d="M16 2a14 14 0 1 0 5.816 26.723L12 14v9a1 1 0 0 1-1 1H9a1 1 0 0 1-1-1V9a1 1 0 0 1 1-1h2.434a1 1 0 0 1 .857.486l11.491 19.15A14 14 0 0 0 16 2m8 16h-4V9a1 1 0 0 1 1-1h2a1 1 0 0 1 1 1Z"/>"##, +}; +pub(super) static NIM: Icon = Icon { + name: "nim", + view: 32.0, + body: r##"<path fill="#ffca28" d="M6 24h20v2a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2zM30 6l-9 9-5-11-5 11-9-9 4 14h20z"/>"##, +}; +pub(super) static NODEJS: Icon = Icon { + name: "nodejs", + view: 32.0, + body: r##"<path fill="#8bc34a" d="M16 20.003v2h4a2 2 0 0 0 2-2v-2a2 2 0 0 0-2-2h-2v-2h4v-2h-4a2 2 0 0 0-2 2v2a2 2 0 0 0 2 2h2v2Z"/><path fill="#8bc34a" d="m16 3.003-12 7v14l4 2h6v-13.5a.5.5 0 0 0-.5-.5h-1a.5.5 0 0 0-.5.5v11.5H8l-2-1.034V11.15l10-5.833 10 5.833v11.703l-10 5.833-1.745-1.022L13 29.253l3 1.75 12-7v-14Z"/>"##, +}; +pub(super) static NUXT: Icon = Icon { + name: "nuxt", + view: 32.0, + body: r##"<path fill="#00e676" d="m30.27 23-6.93-12a1.98 1.98 0 0 0-1.73-1 1.96 1.96 0 0 0-1.73 1l-2.27 3.93-3.88-6.71a1.996 1.996 0 0 0-3.46 0L1.73 23a2 2 0 0 0 1.73 3h8.915a6 6 0 0 0 5.197-3.001L21.61 16l3.46 6h-2.31l-2.31 4h8.09a2 2 0 0 0 1.73-3m-17.896-1H6.93L12 13.22l3.3 5.71-1.193 2.069A2 2 0 0 1 12.374 22"/>"##, +}; +pub(super) static NX: Icon = Icon { + name: "nx", + view: 24.0, + body: r##"<path fill="#039be5" d="m12 13.862-2.749 4.434-4.61-7.537v7.891H1.36V5.35h3.28l4.611 7.892V9.695l2.66 4.168zm.532-5.054V5.35h-3.28v3.458zm4.966 3.635a1.77 1.77 0 0 0-1.774 1.153 1.77 1.77 0 0 1 2.128-.62c.355.177.887.354 1.153.265a1.86 1.86 0 0 0-1.507-.798m3.014.887c-.354 0-.709-.177-.975-.532l-.177-.266a1.9 1.9 0 0 0-.444-.532 1.77 1.77 0 0 0-1.064-.266 2.22 2.22 0 0 0-2.04 1.33 2.04 2.04 0 0 1 3.548.355.71.71 0 0 0 .798.266c.443 0 .354.354 1.064.443v-.089c0-.354-.266-.443-.71-.62zm1.774 1.153a.62.62 0 0 0 .354-.532c0-2.66-2.128-4.877-4.788-4.877a4.79 4.79 0 0 0-3.99 2.128l-1.33-2.128h-3.28l3.103 4.788L9.34 18.65h3.192l1.241-2.216 1.42 2.128h3.102l-2.748-4.434a.6.6 0 0 1 0-.266 2.394 2.394 0 0 1 2.305-2.394c1.33 0 1.507.798 1.773 1.153.621.71 1.774.443 1.774 1.33a.62.62 0 0 0 .887.532m.354.177c-.177.266-.532.266-.709.532-.089.266.089.355.089.355s.354.177.532-.266v-.621z"/>"##, +}; +pub(super) static OBJECTIVE_C: Icon = Icon { + name: "objective-c", + view: 32.0, + body: r##"<path fill="#ffab40" d="M19.563 22A5.57 5.57 0 0 1 14 16.437v-2.873A5.57 5.57 0 0 1 19.563 8H24V2h-4.437A11.563 11.563 0 0 0 8 13.563v2.873A11.564 11.564 0 0 0 19.563 28H24v-6Z"/>"##, +}; +pub(super) static OBJECTIVE_CPP: Icon = Icon { + name: "objective-cpp", + view: 32.0, + body: r##"<path fill="#ffab40" d="M28 14v-4h-2v4h-6v-4h-2v4h-4v2h4v4h2v-4h6v4h2v-4h4v-2z"/><path fill="#ffab40" d="M13.563 22A5.57 5.57 0 0 1 8 16.437v-2.873A5.57 5.57 0 0 1 13.563 8H18V2h-4.437A11.563 11.563 0 0 0 2 13.563v2.873A11.564 11.564 0 0 0 13.563 28H18v-6Z"/>"##, +}; +pub(super) static OCAML: Icon = Icon { + name: "ocaml", + view: 24.0, + body: r##"<path d="m12.019 15.021.003-.008c-.005-.021-.006-.026-.003.008"/><path fill="#ff9800" d="M4.51 3.273a2.523 2.523 0 0 0-2.524 2.523V11.3c.361-.13.88-.898 1.043-1.085.285-.327.337-.743.478-1.006C3.83 8.612 3.886 8.2 4.62 8.2c.342 0 .478.08.71.39.16.216.438.615.568.882.15.307.396.724.503.808q.122.095.233.137c.119.044.218-.037.297-.1.102-.082.145-.247.24-.467.135-.317.283-.697.367-.83.146-.23.195-.501.352-.633.232-.195.535-.208.618-.225.466-.092.677.225.907.43.15.133.355.403.5.765.114.283.26.544.32.707.059.158.203.41.289.713.077.275.286.486.365.616 0 0 .121.34.858.65.16.067.482.176.674.246.32.116.63.101 1.025.054.281 0 .434-.408.562-.734.075-.193.148-.745.197-.902.048-.153-.064-.27.031-.405.112-.156.178-.164.242-.368.138-.436.936-.458 1.384-.458.374 0 .327.363.96.239.364-.072.714.046 1.1.149.324.086.63.184.812.398.119.139.412.834.113.863.029.035.05.099.104.134-.067.262-.357.075-.518.041-.217-.045-.37.007-.583.101-.363.162-.894.143-1.21.407-.27.223-.269.721-.394 1 0 0-.348.895-1.106 1.443-.194.14-.574.477-1.4.605a5.3 5.3 0 0 1-1.1.043c-.186-.009-.362-.018-.549-.02-.11-.002-.48-.013-.461.022l-.041.103.024.138c.015.083.019.149.022.225.006.157-.013.32-.005.478.017.328.138.627.154.958.017.368.199.758.375 1.059.067.114.169.128.213.269.052.161.003.333.028.505.1.668.292 1.366.592 1.97l.008.014c.371-.062.743-.196 1.226-.267.885-.132 2.115-.064 2.906-.138 2-.188 3.085.82 4.882.407V5.796a2.523 2.523 0 0 0-2.523-2.523zm-.907 11.144q-.022 0-.046.003c-.159.025-.313.08-.412.24-.08.13-.108.355-.164.505-.064.175-.176.338-.274.505-.18.305-.504.581-.644.879-.028.06-.053.13-.076.2v3.402c.163.028.333.062.524.113 1.407.375 1.75.407 3.13.25l.13-.018c.105-.22.187-.968.255-1.2.054-.178.127-.32.155-.5.026-.173-.003-.337-.017-.493-.04-.393.285-.533.44-.87.14-.304.22-.651.336-.963.11-.298.284-.721.579-.872-.036-.041-.617-.06-.772-.076a5 5 0 0 1-.5-.07c-.314-.064-.656-.126-.965-.2a10 10 0 0 1-.947-.328c-.298-.138-.503-.497-.732-.507m5.737.83c-.74.149-.97.876-1.32 1.451-.192.319-.396.59-.548.928-.14.312-.128.657-.368.924a2.55 2.55 0 0 0-.528.922c-.023.067-.088.776-.158.943l1.101-.078c1.026.07.73.464 2.332.378l2.529-.078a7 7 0 0 0-.228-.588c-.07-.147-.16-.434-.218-.56a3.5 3.5 0 0 0-.309-.526c-.184-.215-.227-.23-.28-.503-.095-.473-.344-1.33-.637-1.923-.151-.306-.403-.562-.634-.784-.2-.195-.655-.522-.734-.505z"/>"##, +}; +pub(super) static ODIN: Icon = Icon { + name: "odin", + view: 260.0, + body: r##"<g stroke-linejoin="round" stroke-miterlimit="2" clip-rule="evenodd"><path fill="#448aff" d="M73.123 212.264a99 99 0 0 1-6.865-5.18l98.605-170.789s4.059 1.506 7.412 3.113c4.226 2.026 7.726 4 7.726 4 47.796 27.596 64.198 88.805 36.602 136.6-27.595 47.798-88.804 64.198-136.6 36.603 0 0-3.347-1.924-6.879-4.346zm98.545-154.422L88.336 202.177c39.831 22.997 90.838 9.329 113.834-30.5 22.995-39.832 9.33-90.838-30.5-113.835zM47.944 187.19c-3.35-4.852-4.543-7.18-4.543-7.18-17.227-29.922-18.49-67.972 0-100s52.075-49.958 86.603-50c0 0 4.661-.011 8.543.36 5.847.56 9.735 1.315 9.735 1.315L53.986 195.011s-2.237-2.316-6.04-7.82zm72.084-139.903c-25.13 3.054-48.573 17.467-62.193 41.058-13.62 23.589-14.378 51.098-4.459 74.39z"/></g>"##, +}; +pub(super) static PDF: Icon = Icon { + name: "pdf", + view: 24.0, + body: r##"<path fill="#ef5350" d="M13 9h5.5L13 3.5zM6 2h8l6 6v12a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2m4.93 10.44c.41.9.93 1.64 1.53 2.15l.41.32c-.87.16-2.07.44-3.34.93l-.11.04.5-1.04c.45-.87.78-1.66 1.01-2.4m6.48 3.81c.18-.18.27-.41.28-.66.03-.2-.02-.39-.12-.55-.29-.47-1.04-.69-2.28-.69l-1.29.07-.87-.58c-.63-.52-1.2-1.43-1.6-2.56l.04-.14c.33-1.33.64-2.94-.02-3.6a.85.85 0 0 0-.61-.24h-.24c-.37 0-.7.39-.79.77-.37 1.33-.15 2.06.22 3.27v.01c-.25.88-.57 1.9-1.08 2.93l-.96 1.8-.89.49c-1.2.75-1.77 1.59-1.88 2.12-.04.19-.02.36.05.54l.03.05.48.31.44.11c.81 0 1.73-.95 2.97-3.07l.18-.07c1.03-.33 2.31-.56 4.03-.75 1.03.51 2.24.74 3 .74.44 0 .74-.11.91-.3m-.41-.71.09.11c-.01.1-.04.11-.09.13h-.04l-.19.02c-.46 0-1.17-.19-1.9-.51.09-.1.13-.1.23-.1 1.4 0 1.8.25 1.9.35M7.83 17c-.65 1.19-1.24 1.85-1.69 2 .05-.38.5-1.04 1.21-1.69zm3.02-6.91c-.23-.9-.24-1.63-.07-2.05l.07-.12.15.05c.17.24.19.56.09 1.1l-.03.16-.16.82z"/>"##, +}; +pub(super) static PERL: Icon = Icon { + name: "perl", + view: 24.0, + body: r##"<path fill="#ba68c8" d="M11.057 2.981c.537.735.028 1.653.141 2.472a3.42 3.42 0 0 1-1.03 2.415c-1.414 1.625-3.165 3.038-4.097 5.03a5.28 5.28 0 0 0 1.412 5.847c.706.735 1.54 1.342 2.472 1.738.17.805-1.088.184-1.455 0A6.7 6.7 0 0 1 4.361 16.4a5.44 5.44 0 0 1 .904-5.368c1.272-1.61 3.136-2.543 4.662-3.857.565-.55 1.003-1.3.932-2.119.156-.678-.254-1.469.212-2.09zm-.07 18.929c-.17.198-.467.325-.495.24-.042-.085.212-.127.381-.325.17-.183.127-.522.24-.522.1 0 .043.395-.14.607zm2.16 0c.17.198.453.31.495.24.028-.085-.212-.141-.395-.339-.156-.184-.113-.523-.24-.523-.085 0-.029.41.14.608zm-1.03.48c-.1 0-.071-.296-.071-.65 0-.367-.028-.663.07-.663.085 0 .057.296.057.663 0 .354.014.65-.057.65m-.495-20.765c.34.24.254 2.077.254 3.136 0 1.653.184 3.376-.805 4.916-.96 1.497-2.048 3.108-1.95 4.972.1 1.837.99 3.504 2.148 5.043.664.876-.353.509-.876.085a7.2 7.2 0 0 1-2.755-5.664c.142-1.907 1.597-3.348 2.628-4.803.805-1.13 1.186-1.879 1.215-3.645.028-1.412-.142-3.531.042-3.983.014-.043.07-.1.099-.057m.537 2.232c-.085 0-.043.396.028.72.424 2.26-.198 4.52-.749 6.682a12.77 12.77 0 0 0 .283 7.826c.607 1.568 1.71.791 2.161 1.568.34.593 1.272.198 1.978-.141 2.232-1.102 4.012-3.108 4.11-5.566.029-.494 0-.989-.07-1.497-.283-1.837-1.78-3.065-3.15-4.083-1.215-.89-2.74-1.483-3.659-2.613-.523-.65-.297-1.638-.381-2.458-.043-.452-.255-.042-.382-.268-.084-.127-.14-.17-.17-.17zm.72 3.616c.057 0 .17.071.325.226a20 20 0 0 0 2.161 1.921c1.272.961 2.43 2.091 2.967 3.504.339.875.339 1.836.226 2.74-.184 1.384-1.187 2.444-2.119 3.404-.339.354-1.06.791-1.074.678-.084-.367.763-1.172 1.159-1.695A5.93 5.93 0 0 0 16 10.962c-1.102-1.214-2.317-1.907-2.995-3.08-.14-.253-.183-.409-.113-.409z"/>"##, +}; +pub(super) static PHP: Icon = Icon { + name: "php", + view: 24.0, + body: r##"<path fill="#1e88e5" d="M12 18.08c-6.63 0-12-2.72-12-6.08s5.37-6.08 12-6.08S24 8.64 24 12s-5.37 6.08-12 6.08m-5.19-7.95c.54 0 .91.1 1.09.31.18.2.22.56.13 1.03-.1.53-.29.87-.58 1.09q-.42.33-1.29.33h-.87l.53-2.76zm-3.5 5.55h1.44l.34-1.75h1.23c.54 0 .98-.06 1.33-.17.35-.12.67-.31.96-.58.24-.22.43-.46.58-.73.15-.26.26-.56.31-.88.16-.78.05-1.39-.33-1.82-.39-.44-.99-.65-1.82-.65H4.59zm7.25-8.33-1.28 6.58h1.42l.74-3.77h1.14c.36 0 .6.06.71.18s.13.34.07.66l-.57 2.93h1.45l.59-3.07c.13-.62.03-1.07-.27-1.36-.3-.27-.85-.4-1.65-.4h-1.27L12 7.35zM18 10.13c.55 0 .91.1 1.09.31.18.2.22.56.13 1.03-.1.53-.29.87-.57 1.09-.29.22-.72.33-1.3.33h-.85l.5-2.76zm-3.5 5.55h1.44l.34-1.75h1.22c.55 0 1-.06 1.35-.17.35-.12.65-.31.95-.58.24-.22.44-.46.58-.73.15-.26.26-.56.32-.88.15-.78.04-1.39-.34-1.82-.36-.44-.99-.65-1.82-.65h-2.75z"/>"##, +}; +pub(super) static PLAYWRIGHT: Icon = Icon { + name: "playwright", + view: 24.0, + body: r##"<path fill="#ef5350" d="M9.708 15.968v-1.429l-3.97 1.125s.294-1.703 2.364-2.291a3.45 3.45 0 0 1 1.605-.091v-5.86h1.988a12 12 0 0 0-.601-1.541c-.291-.591-.589-.2-1.266.367-.477.398-1.682 1.248-3.495 1.737s-3.278.359-3.89.253c-.867-.15-1.321-.341-1.278.32.037.58.175 1.483.492 2.673.688 2.58 2.957 7.55 7.245 6.395 1.12-.302 1.91-.898 2.459-1.66H9.708zm-6.404-4.701 3.047-.803s-.09 1.173-1.232 1.474-1.816-.671-1.816-.671z"/><path fill="#4caf50" d="M21.178 7.49c-.792.14-2.694.312-5.042-.318-2.35-.63-3.908-1.729-4.526-2.246-.876-.733-1.26-1.244-1.64-.473-.335.68-.763 1.786-1.178 3.337-.898 3.354-1.57 10.432 3.985 11.921s8.512-4.978 9.41-8.333c.416-1.548.597-2.72.647-3.477.058-.857-.53-.608-1.656-.41zm-11.162 2.776s.875-1.363 2.36-.94c1.486.422 1.6 2.065 1.6 2.065zm3.624 6.11c-2.611-.765-3.014-2.848-3.014-2.848l7.016 1.962s-1.416 1.64-4.002.886m2.482-4.28s.874-1.362 2.358-.938 1.602 2.065 1.602 2.065z"/>"##, +}; +pub(super) static PNPM: Icon = Icon { + name: "pnpm", + view: 32.0, + body: r##"<path fill="#e0e0e0" d="M2 22h8v8H2zm10 0h8v8h-8zm10 0h8v8h-8zM12 12h8v8h-8z"/><path fill="#ffb300" d="M2 2h8v8H2zm10 0h8v8h-8zm10 0h8v8h-8zm0 10h8v8h-8z"/>"##, +}; +pub(super) static POETRY: Icon = Icon { + name: "poetry", + view: 32.0, + body: r##"<path fill="#3f51b5" d="M20.137 17.834A18.52 18.52 0 0 1 6 24l5 6a25.1 25.1 0 0 0 13-8Z"/><path fill="#1976d2" d="M6 2v22a18.52 18.52 0 0 0 14.137-6.166Z"/><path fill="#29b6f6" d="m6 2 14.137 15.834A23.7 23.7 0 0 0 26 2Z"/>"##, +}; +pub(super) static POWERPOINT: Icon = Icon { + name: "powerpoint", + view: 24.0, + body: r##"<path fill="#e64a19" d="M6 2h8l6 6v12a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2m7 1.5V9h5.5zM8 11v2h1v6H8v1h4v-1h-1v-2h2a3 3 0 0 0 3-3 3 3 0 0 0-3-3zm5 2a1 1 0 0 1 1 1 1 1 0 0 1-1 1h-2v-2z"/>"##, +}; +pub(super) static POWERSHELL: Icon = Icon { + name: "powershell", + view: 32.0, + body: r##"<path fill="#03a9f4" d="M29.07 6H7.677A1.535 1.535 0 0 0 6.24 7.113l-4.2 17.774A.852.852 0 0 0 2.93 26h21.393a1.535 1.535 0 0 0 1.436-1.113L29.96 7.112A.852.852 0 0 0 29.07 6M8.626 23.797a1.4 1.4 0 0 1-1.814-.31l-.007-.009a1.075 1.075 0 0 1 .315-1.599l9.6-6.061-6.102-5.852-.01-.01a1.068 1.068 0 0 1 .084-1.625l.037-.03a1.38 1.38 0 0 1 1.8.07l7.233 6.957a1.1 1.1 0 0 1 .236.739 1.08 1.08 0 0 1-.412.79c-.074.04-.146.119-10.951 6.935ZM24 22.94A1.135 1.135 0 0 1 22.803 24h-5.634a1.061 1.061 0 1 1 .001-2.112h5.633A1.134 1.134 0 0 1 24 22.938Z"/>"##, +}; +pub(super) static PRETTIER: Icon = Icon { + name: "prettier", + view: 16.0, + body: r##"<path fill="#f44336" d="M2 8h4v1H2zm0 6h4v1H2zm9-10h3v1h-3zM2 2h3v1H2z"/><path fill="#f9a825" d="M9 2h3v1H9zm1 4h4v1h-4zm-5 6h1v1H5zm-3-2h6v1H2z"/><path fill="#26a69a" d="M2 12h3v1H2zm7-4h5v1H9zM2 4h4v1H2zm3-2h4v1H5z"/><path fill="#ba68c8" d="M2 6h3v1H2zm7-2h2v1H9zm-1 6h4v1H8z"/>"##, +}; +pub(super) static PRISMA: Icon = Icon { + name: "prisma", + view: 32.0, + body: r##"<path fill="#00bfa5" d="m27.777 22.617-.459-.946L18.43 3.26a2.25 2.25 0 0 0-1.914-1.256A2 2 0 0 0 16.379 2a2.23 2.23 0 0 0-1.891 1.042L4.348 19.056a2.2 2.2 0 0 0 .025 2.417l4.957 7.488A2.34 2.34 0 0 0 11.29 30a2.4 2.4 0 0 0 .655-.092l14.387-4.149a2.32 2.32 0 0 0 1.458-1.234 2.21 2.21 0 0 0-.013-1.908m-3.538.604-11.268 3.25 4.075-19.033 7.568 15.671-.376.098Z"/>"##, +}; +pub(super) static PROTO: Icon = Icon { + name: "proto", + view: 32.0, + body: r##"<path fill="#00bfa5" d="M16 27 2 19v-5l14 8z"/><path fill="#ffeb3b" d="m30 14-14 8v5l14-8z"/><path fill="#ff5722" d="M16 6 2 14v5l14-8z"/><path fill="#00e676" d="m30 19-14-8V6l14 8z"/><path fill="#03a9f4" d="M16 27 2 19v-5l14 8z"/>"##, +}; +pub(super) static PUPPETEER: Icon = Icon { + name: "puppeteer", + view: 24.0, + body: r##"<path fill="#00bfa5" d="M2.822 19.073q-.159 0-.159-.292l-.013-2.138q0-.16.013-.173.066-.2 3.307-2.298 3.24-2.085 3.254-2.152-.173-.239-3.413-2.35-3.148-2.033-3.148-2.232V5.233q0-.305.213-.305h1.912q.252 0 3.56 2.497 3.32 2.497 3.586 2.497.292 0 3.639-2.484t3.546-2.484h2.045q.186 0 .186.36 0 .37-.026 1.115t-.027 1.115q0 .067-.61.492-1.966 1.248-5.871 3.772-.093.066-.2.226.094.186 3.414 2.297 3.267 2.085 3.267 2.271v2.099q0 .345-.186.345h-2.045q-.332 0-3.626-2.484-3.294-2.47-3.466-2.47-.213 0-3.613 2.484-3.387 2.497-3.626 2.497z" aria-label="X"/>"##, +}; +pub(super) static PYTHON: Icon = Icon { + name: "python", + view: 24.0, + body: r##"<path fill="#0288d1" d="M9.86 2A2.86 2.86 0 0 0 7 4.86v1.68h4.29c.39 0 .71.57.71.96H4.86A2.86 2.86 0 0 0 2 10.36v3.781a2.86 2.86 0 0 0 2.86 2.86h1.18v-2.68a2.85 2.85 0 0 1 2.85-2.86h5.25c1.58 0 2.86-1.271 2.86-2.851V4.86A2.86 2.86 0 0 0 14.14 2zm-.72 1.61c.4 0 .72.12.72.71s-.32.891-.72.891c-.39 0-.71-.3-.71-.89s.32-.711.71-.711"/><path fill="#fdd835" d="M17.959 7v2.68a2.85 2.85 0 0 1-2.85 2.859H9.86A2.85 2.85 0 0 0 7 15.389v3.75a2.86 2.86 0 0 0 2.86 2.86h4.28A2.86 2.86 0 0 0 17 19.14v-1.68h-4.291c-.39 0-.709-.57-.709-.96h7.14A2.86 2.86 0 0 0 22 13.64V9.86A2.86 2.86 0 0 0 19.14 7zM8.32 11.513l-.004.004.038-.004zm6.54 7.276c.39 0 .71.3.71.89a.71.71 0 0 1-.71.71c-.4 0-.72-.12-.72-.71s.32-.89.72-.89"/>"##, +}; +pub(super) static R: Icon = Icon { + name: "r", + view: 24.0, + body: r##"<path fill="#1976d2" d="M11.956 4.05c-5.694 0-10.354 3.106-10.354 6.947 0 3.396 3.686 6.212 8.531 6.813v2.205h3.53V17.82c.88-.093 1.699-.259 2.475-.497l1.43 2.692h3.996l-2.402-4.048c1.936-1.263 3.147-3.034 3.147-4.97 0-3.841-4.659-6.947-10.354-6.947m1.584 2.712c4.349 0 7.558 1.45 7.558 4.753 0 1.77-.952 3.013-2.505 3.779a1 1 0 0 1-.228-.156c-.373-.165-.994-.352-.994-.352s3.085-.227 3.085-3.302-3.23-3.127-3.23-3.127h-7.092v7.413c-2.64-.766-4.462-2.392-4.462-4.255 0-2.63 3.52-4.753 7.868-4.753m.156 4.12h2.143s.983-.05.983.974c0 1.004-.983 1.004-.983 1.004h-2.143v-1.977m-.031 4.566h.952c.186 0 .28.052.445.207.135.103.28.3.404.476-.57.073-1.17.104-1.801.104z"/>"##, +}; +pub(super) static REACT: Icon = Icon { + name: "react", + view: 32.0, + body: r##"<path fill="#00bcd4" d="M16 12c7.444 0 12 2.59 12 4s-4.556 4-12 4-12-2.59-12-4 4.556-4 12-4m0-2c-7.732 0-14 2.686-14 6s6.268 6 14 6 14-2.686 14-6-6.268-6-14-6"/><path fill="#00bcd4" d="M16 14a2 2 0 1 0 2 2 2 2 0 0 0-2-2"/><path fill="#00bcd4" d="M10.458 5.507c2.017 0 5.937 3.177 9.006 8.493 3.722 6.447 3.757 11.687 2.536 12.392a.9.9 0 0 1-.457.1c-2.017 0-5.938-3.176-9.007-8.492C8.814 11.553 8.779 6.313 10 5.608a.9.9 0 0 1 .458-.1m-.001-2A2.87 2.87 0 0 0 9 3.875C6.13 5.532 6.938 12.304 10.804 19c3.284 5.69 7.72 9.493 10.74 9.493A2.87 2.87 0 0 0 23 28.124c2.87-1.656 2.062-8.428-1.804-15.124-3.284-5.69-7.72-9.493-10.74-9.493Z"/><path fill="#00bcd4" d="M21.543 5.507a.9.9 0 0 1 .457.1c1.221.706 1.186 5.946-2.536 12.393-3.07 5.316-6.99 8.493-9.007 8.493a.9.9 0 0 1-.457-.1C8.779 25.686 8.814 20.446 12.536 14c3.07-5.316 6.99-8.493 9.007-8.493m0-2c-3.02 0-7.455 3.804-10.74 9.493C6.939 19.696 6.13 26.468 9 28.124a2.87 2.87 0 0 0 1.457.369c3.02 0 7.455-3.804 10.74-9.493C25.061 12.304 25.87 5.532 23 3.876a2.87 2.87 0 0 0-1.457-.369"/>"##, +}; +pub(super) static REACT_TS: Icon = Icon { + name: "react_ts", + view: 32.0, + body: r##"<path fill="#0288d1" d="M16 12c7.444 0 12 2.59 12 4s-4.556 4-12 4-12-2.59-12-4 4.556-4 12-4m0-2c-7.732 0-14 2.686-14 6s6.268 6 14 6 14-2.686 14-6-6.268-6-14-6"/><path fill="#0288d1" d="M16 14a2 2 0 1 0 2 2 2 2 0 0 0-2-2"/><path fill="#0288d1" d="M10.458 5.507c2.017 0 5.937 3.177 9.006 8.493 3.722 6.447 3.757 11.687 2.536 12.392a.9.9 0 0 1-.457.1c-2.017 0-5.938-3.176-9.007-8.492C8.814 11.553 8.779 6.313 10 5.608a.9.9 0 0 1 .458-.1m-.001-2A2.87 2.87 0 0 0 9 3.875C6.13 5.532 6.938 12.304 10.804 19c3.284 5.69 7.72 9.493 10.74 9.493A2.87 2.87 0 0 0 23 28.124c2.87-1.656 2.062-8.428-1.804-15.124-3.284-5.69-7.72-9.493-10.74-9.493Z"/><path fill="#0288d1" d="M21.543 5.507a.9.9 0 0 1 .457.1c1.221.706 1.186 5.946-2.536 12.393-3.07 5.316-6.99 8.493-9.007 8.493a.9.9 0 0 1-.457-.1C8.779 25.686 8.814 20.446 12.536 14c3.07-5.316 6.99-8.493 9.007-8.493m0-2c-3.02 0-7.455 3.804-10.74 9.493C6.939 19.696 6.13 26.468 9 28.124a2.87 2.87 0 0 0 1.457.369c3.02 0 7.455-3.804 10.74-9.493C25.061 12.304 25.87 5.532 23 3.876a2.87 2.87 0 0 0-1.457-.369"/>"##, +}; +pub(super) static README: Icon = Icon { + name: "readme", + view: 16.0, + body: r##"<g fill="none"><path d="M0 0h24v24H0z"/><path fill="#42a5f5" d="M8 1C4.136 1 1 4.136 1 8s3.136 7 7 7 7-3.136 7-7-3.136-7-7-7m1 11H7V7.5h2zm0-6H7V4h2z"/></g>"##, +}; +pub(super) static REMIX: Icon = Icon { + name: "remix", + view: 32.0, + body: r##"<path fill="#b0bec5" d="M28 12v-2a8 8 0 0 0-8-8H4v6h12.83a3.114 3.114 0 0 1 3.166 2.839A3 3 0 0 1 17 14H4v6h12a4 4 0 0 1 4 4v6h8v-5a7 7 0 0 0-7-7h1a6 6 0 0 0 6-6M12 26H4v4h10v-2a2 2 0 0 0-2-2"/>"##, +}; +pub(super) static RENOVATE: Icon = Icon { + name: "renovate", + view: 24.0, + body: r##"<path fill="#ffb300" d="m13.061 3.722-.707-.707a1 1 0 0 0-1.414 0L2.454 11.5a1 1 0 0 0 0 1.414l2.829 2.829a1 1 0 0 0 1.414 0l8.485-8.486a1 1 0 0 0 0-1.414l-.707-.707.707-.707 2.829 2.828-7.071 7.071 7.778 7.779a1 1 0 0 0 1.414 0l1.414-1.415a1 1 0 0 0 0-1.414l-6.364-6.364 5.657-5.657L15.182 1.6z"/>"##, +}; +pub(super) static ROBOTS: Icon = Icon { + name: "robots", + view: 32.0, + body: r##"<path fill="#ff5252" d="M28.586 18H28a8 8 0 0 0-8-8h-2V8.445a4 4 0 1 0-4 0V10h-2a8 8 0 0 0-8 8h-.586A1.414 1.414 0 0 0 2 19.414v3.172A1.414 1.414 0 0 0 3.414 24H4v1a3 3 0 0 0 3 3h18a3 3 0 0 0 3-3v-1h.586A1.414 1.414 0 0 0 30 22.586v-3.172A1.414 1.414 0 0 0 28.586 18M11 22a3 3 0 1 1 3-3 3 3 0 0 1-3 3m10 0a3 3 0 1 1 3-3 3 3 0 0 1-3 3"/>"##, +}; +pub(super) static ROCKET: Icon = Icon { + name: "rocket", + view: 32.0, + body: r##"<path fill="#ef5350" d="M12 26c-1.71 1.905-7.64 2.149-7.93 1.937l-.004.003-.002-.005-.005-.002.004-.003C3.85 27.64 4.1 21.715 6 20ZM29.64 7.908c-.655 2.69-1.681 5.64-5.64 10.092l-.789 4.749a4 4 0 0 1-1.116 2.171l-4.863 4.868A.72.72 0 0 1 16 29.277v-6.23L9 16H2.723a.721.721 0 0 1-.511-1.232L7.08 9.905A4 4 0 0 1 9.25 8.79L14 8c4.453-3.959 7.402-4.985 10.092-5.64a11.1 11.1 0 0 1 3.642-.329 3.1 3.1 0 0 1 1.72.515 3.1 3.1 0 0 1 .515 1.72 11.1 11.1 0 0 1-.33 3.642ZM26 10a4 4 0 1 0-4 4 4 4 0 0 0 4-4"/>"##, +}; +pub(super) static ROLLUP: Icon = Icon { + name: "rollup", + view: 800.0, + body: r##"<g transform="translate(-100 -100)"><path fill="#f44336" d="M733.79 394.71c0 77.407-42.308 144.79-104.67 180.51-3.76 3.134-5.954 8.148-3.76 12.849l106.87 211.22c2.82 6.581-1.568 14.103-8.776 14.103h-408.35l2.194-1.254c15.356-8.774 121.91-219.06 225.95-318.72 104.05-99.658 117.21-66.439 59.857-174.87 0 0 44.188 86.182 6.581 92.763-29.459 5.328-97.15-60.17-72.08-119.09 25.071-57.664 123.79-46.695 169.23.314 17.236 30.085 26.952 64.872 26.952 102.17m-385.47 140.71c-41.367 76.154-67.692 131.62-82.108 170.48v-509.57c0-5.328 4.388-9.715 9.715-9.715h252.91c73.333 1.253 137.58 40.114 173.62 98.718-26.325-32.906-67.692-51.71-108.43-51.71-77.407 0-96.837 28.206-245.7 301.79z"/></g>"##, +}; +pub(super) static RUBY: Icon = Icon { + name: "ruby", + view: 24.0, + body: r##"<path fill="#f44336" d="M18.041 3.177c2.24.382 2.879 1.919 2.843 3.527V6.67l-1.013 13.266-13.132.897h.008c-1.093-.044-3.518-.151-3.634-3.545l1.217-2.222 2.462 5.74 2.097-6.77-.045.009.018-.018 6.85 2.186L13.945 9.3l6.53-.409-5.144-4.212 2.71-1.51v.009M3.113 17.252v.017zM6.916 6.874c2.63-2.622 6.033-4.168 7.34-2.844 1.297 1.306-.072 4.523-2.702 7.135-2.666 2.613-6.015 4.248-7.322 2.933-1.306-1.324.036-4.612 2.675-7.224z"/>"##, +}; +pub(super) static RUST: Icon = Icon { + name: "rust", + view: 32.0, + body: r##"<path fill="#ff7043" d="m30 12-4-2V6h-4l-2-4-4 2-4-2-2 4H6v4l-4 2 2 4-2 4 4 2v4h4l2 4 4-2 4 2 2-4h4v-4l4-2-2-4ZM6 16a9.9 9.9 0 0 1 .842-4H10v8H6.842A9.9 9.9 0 0 1 6 16m10 10a9.98 9.98 0 0 1-7.978-4H16v-2h-2v-2h4c.819.819.297 2.308 1.179 3.37a1.89 1.89 0 0 0 1.46.63h3.34A9.98 9.98 0 0 1 16 26m-2-12v-2h4a1 1 0 0 1 0 2Zm11.158 6H24a2.006 2.006 0 0 1-2-2 2 2 0 0 0-2-2 3 3 0 0 0 3-3q0-.08-.004-.161A3.115 3.115 0 0 0 19.83 10H8.022a9.986 9.986 0 0 1 17.136 10"/>"##, +}; +pub(super) static SASS: Icon = Icon { + name: "sass", + view: 32.0, + body: r##"<path fill="#ec407a" d="M27.837 5.673a4.33 4.33 0 0 0-2.293-2.701c-2.362-1.261-6.11-1.298-9.548-.092a26.3 26.3 0 0 0-8.76 4.966c-2.752 2.542-3.438 4.925-3.189 6.194.523 2.668 3.274 4.539 5.485 6.042.418.284.822.559 1.175.816-1.429.76-4.261 2.444-5.088 4.248a3.88 3.88 0 0 0-.118 3.332A2.37 2.37 0 0 0 6.869 29.8a5.6 5.6 0 0 0 1.49.2 6.35 6.35 0 0 0 5.19-2.856 6.74 6.74 0 0 0 .864-5.382 7.3 7.3 0 0 1 2.044-.03 3.92 3.92 0 0 1 2.816 1.311 1.82 1.82 0 0 1 .423 1.262 1.55 1.55 0 0 1-.772 1.05c-.234.14-.586.355-.504.803.036.194.198.633.894.512a2.93 2.93 0 0 0 2.145-2.651 4 4 0 0 0-1.197-2.904 5.94 5.94 0 0 0-4.396-1.626 10.6 10.6 0 0 0-2.672.304 20 20 0 0 0-2.203-1.846c-1.712-1.3-3.33-2.529-3.235-4.26.125-2.263 2.468-4.532 6.964-6.744 4.016-1.976 7.254-2.037 8.944-1.438a2 2 0 0 1 1.204.883 2.77 2.77 0 0 1-.36 2.47 9.71 9.71 0 0 1-7.425 4.304 3.86 3.86 0 0 1-3.238-.757c-.278-.302-.593-.645-1.074-.383q-.565.31-.225 1.189a3.9 3.9 0 0 0 2.407 1.92 11.7 11.7 0 0 0 7.128-.671c3.527-1.35 6.681-5.202 5.756-8.787M11.895 24.475a4 4 0 0 1-.192.468 4.5 4.5 0 0 1-.753 1.081 2.83 2.83 0 0 1-2.533 1.107c-.056-.032-.078-.146-.085-.193a3.28 3.28 0 0 1 1.076-2.284 11.3 11.3 0 0 1 2.644-1.933 3.85 3.85 0 0 1-.157 1.754"/>"##, +}; +pub(super) static SCALA: Icon = Icon { + name: "scala", + view: 32.0, + body: r##"<path fill="#f44336" d="m6.457 9.894 12.523 5.163-.456 1.211L6 11.105Zm7.02-3.091L26 11.966l-.457 1.21L13.02 8.015ZM6.465 18.885l12.524 5.163-.457 1.21L6.01 20.097Zm7.007-3.086 12.524 5.163-.456 1.21-12.524-5.162Z"/><path fill="#f44336" d="M6 24.07V30l19.997-3.106V20.96zM6 5.11v5.99l20-3.11V2zm0 9.96v5.03l20-3.11v-5.03z"/>"##, +}; +pub(super) static SETTINGS: Icon = Icon { + name: "settings", + view: 24.0, + body: r##"<g fill="none"><path d="M0 0h24v24H0z"/><path fill="#42a5f5" d="M19.43 12.98c.04-.32.07-.64.07-.98s-.03-.66-.07-.98l2.11-1.65c.19-.15.24-.42.12-.64l-2-3.46a.5.5 0 0 0-.61-.22l-2.49 1c-.52-.4-1.08-.73-1.69-.98l-.38-2.65A.49.49 0 0 0 14 2h-4c-.25 0-.46.18-.49.42l-.38 2.65c-.61.25-1.17.59-1.69.98l-2.49-1a.6.6 0 0 0-.18-.03c-.17 0-.34.09-.43.25l-2 3.46c-.13.22-.07.49.12.64l2.11 1.65c-.04.32-.07.65-.07.98s.03.66.07.98l-2.11 1.65c-.19.15-.24.42-.12.64l2 3.46a.5.5 0 0 0 .61.22l2.49-1c.52.4 1.08.73 1.69.98l.38 2.65c.03.24.24.42.49.42h4c.25 0 .46-.18.49-.42l.38-2.65c.61-.25 1.17-.59 1.69-.98l2.49 1q.09.03.18.03c.17 0 .34-.09.43-.25l2-3.46c.12-.22.07-.49-.12-.64zm-1.98-1.71c.04.31.05.52.05.73s-.02.43-.05.73l-.14 1.13.89.7 1.08.84-.7 1.21-1.27-.51-1.04-.42-.9.68c-.43.32-.84.56-1.25.73l-1.06.43-.16 1.13-.2 1.35h-1.4l-.19-1.35-.16-1.13-1.06-.43c-.43-.18-.83-.41-1.23-.71l-.91-.7-1.06.43-1.27.51-.7-1.21 1.08-.84.89-.7-.14-1.13c-.03-.31-.05-.54-.05-.74s.02-.43.05-.73l.14-1.13-.89-.7-1.08-.84.7-1.21 1.27.51 1.04.42.9-.68c.43-.32.84-.56 1.25-.73l1.06-.43.16-1.13.2-1.35h1.39l.19 1.35.16 1.13 1.06.43c.43.18.83.41 1.23.71l.91.7 1.06-.43 1.27-.51.7 1.21-1.07.85-.89.7zM12 8c-2.21 0-4 1.79-4 4s1.79 4 4 4 4-1.79 4-4-1.79-4-4-4m0 6c-1.1 0-2-.9-2-2s.9-2 2-2 2 .9 2 2-.9 2-2 2"/></g>"##, +}; +pub(super) static STORYBOOK: Icon = Icon { + name: "storybook", + view: 32.0, + body: r##"<path fill="#ff4081" d="m24.95 28.948-18-.9a1 1 0 0 1-.95-1V6.906a1 1 0 0 1 .9-.995l18-1.905A1 1 0 0 1 26 5v22.949a1 1 0 0 1-1.05.998Z"/><path fill="#fafafa" d="m20 8.52.19-4.242 3.649-.275.16 4.37a.28.28 0 0 1-.276.283.3.3 0 0 1-.188-.063L22.123 7.52l-1.668 1.23a.29.29 0 0 1-.398-.055A.27.27 0 0 1 20 8.52m-2.128 6.647c0 .487 3.448.25 3.912-.094 0-3.324-1.87-5.073-5.298-5.073-3.421 0-5.345 1.774-5.345 4.436 0 4.642 6.561 4.735 6.561 7.266a1.022 1.022 0 0 1-1.164 1.13c-1.047 0-1.459-.512-1.413-2.242 0-.375-3.984-.494-4.101 0-.308 4.198 2.426 5.41 5.56 5.41C19.619 26 22 24.45 22 21.658c0-4.973-6.653-4.842-6.653-7.31a1.08 1.08 0 0 1 1.243-1.13c.478 0 1.354.08 1.282 1.949"/>"##, +}; +pub(super) static STYLUS: Icon = Icon { + name: "stylus", + view: 200.0, + body: r##"<path fill="#c0ca33" d="M127.22 155.91c14.639-17.51 16.362-35.594 5.023-69.178-7.176-21.241-19.089-37.603-10.334-50.807 9.33-14.065 29.135-.43 12.63 18.371l3.301 2.296c19.806 2.297 29.566-24.83 14.783-32.58-39.038-20.38-73.197 18.802-58.127 64.155 6.459 19.232 15.501 39.613 8.181 55.831-6.315 13.922-18.515 22.103-26.695 22.39-17.079.862-5.74-38.32 13.922-48.08 1.722-.86 4.162-2.009 1.866-4.88-24.255-2.726-38.464 8.468-46.645 24.113-23.825 45.497 45.21 62.289 82.096 18.37z"/>"##, +}; +pub(super) static SUPABASE: Icon = Icon { + name: "supabase", + view: 32.0, + body: r##"<path fill="#66bb6a" d="M29.92 12H16V2.85a1 1 0 0 0-1.78-.624L1.3 18.376A1 1 0 0 0 2.08 20H16v9.15a1 1 0 0 0 1.78.624l12.92-16.15A1 1 0 0 0 29.92 12"/>"##, +}; +pub(super) static SVELTE: Icon = Icon { + name: "svelte", + view: 300.0, + body: r##"<path fill="#ff5722" d="M175.94 24.328c-13.037.252-26.009 3.872-37.471 11.174L79.912 72.818a67.13 67.13 0 0 0-30.355 44.906 70.8 70.8 0 0 0 6.959 45.445 67.2 67.2 0 0 0-10.035 25.102 71.54 71.54 0 0 0 12.236 54.156c23.351 33.41 69.468 43.311 102.81 22.07l58.559-37.158a67.36 67.36 0 0 0 30.355-44.906 70.77 70.77 0 0 0-6.982-45.422 67.65 67.65 0 0 0 10.059-25.102 71.63 71.63 0 0 0-12.236-54.156v-.18c-15.324-21.925-40.453-33.727-65.342-33.246zm5.137 28.68a46.5 46.5 0 0 1 36.09 19.969 42.98 42.98 0 0 1 7.365 32.557 45 45 0 0 1-1.393 5.455l-1.123 3.37-2.986-2.247a75.9 75.9 0 0 0-22.902-11.45l-2.244-.651.201-2.246a13.16 13.16 0 0 0-2.379-8.711 13.99 13.99 0 0 0-14.953-5.412 12.8 12.8 0 0 0-3.594 1.572l-58.578 37.25a12.24 12.24 0 0 0-5.502 8.15 13.1 13.1 0 0 0 2.246 9.834 14.03 14.03 0 0 0 14.93 5.569 13.5 13.5 0 0 0 3.594-1.573l22.453-14.234a41.8 41.8 0 0 1 11.898-5.232 46.48 46.48 0 0 1 49.914 18.502 43.02 43.02 0 0 1 7.363 32.557 40.42 40.42 0 0 1-18.254 27.078l-58.58 37.316a43 43 0 0 1-11.898 5.23A46.545 46.545 0 0 1 82.81 227.14a42.98 42.98 0 0 1-7.341-32.557 38 38 0 0 1 1.39-5.41l1.102-3.37 3.008 2.246a75.9 75.9 0 0 0 22.836 11.361l2.244.65-.201 2.247a13.25 13.25 0 0 0 2.447 8.644 14.03 14.03 0 0 0 15.043 5.569 13.1 13.1 0 0 0 3.592-1.573l58.467-37.316a12.17 12.17 0 0 0 5.502-8.173 12.96 12.96 0 0 0-2.246-9.811 14.03 14.03 0 0 0-15.043-5.568 12.8 12.8 0 0 0-3.592 1.57l-22.453 14.258a42.9 42.9 0 0 1-11.877 5.209 46.52 46.52 0 0 1-49.846-18.5 43.02 43.02 0 0 1-7.297-32.557A40.42 40.42 0 0 1 96.798 96.98l58.646-37.316a42.8 42.8 0 0 1 11.811-5.21 46.5 46.5 0 0 1 13.822-1.444z"/>"##, +}; +pub(super) static SVG: Icon = Icon { + name: "svg", + view: 32.0, + body: r##"<path fill="#ffb300" d="M29.168 14.03a2.7 2.7 0 0 0-1.968-.83 2.51 2.51 0 0 0-1.929.8h-4.443l3.078-3.078a2.835 2.835 0 0 0 2.857-2.842 2.6 2.6 0 0 0-.831-1.969 2.82 2.82 0 0 0-2.014-.788 2.67 2.67 0 0 0-1.968.788 2.36 2.36 0 0 0-.812 1.922L18 11.17V6.726a2.51 2.51 0 0 0 .8-1.929 2.7 2.7 0 0 0-.832-1.968 2.745 2.745 0 0 0-3.936 0 2.7 2.7 0 0 0-.832 1.968 2.51 2.51 0 0 0 .8 1.93v4.443l-3.138-3.138a2.36 2.36 0 0 0-.812-1.922 2.66 2.66 0 0 0-1.968-.788 2.83 2.83 0 0 0-2.014.788 2.6 2.6 0 0 0-.831 1.969 2.74 2.74 0 0 0 .831 2.013 2.8 2.8 0 0 0 2.026.829l3.078 3.078H6.729a2.51 2.51 0 0 0-1.929-.8 2.7 2.7 0 0 0-1.968.831 2.745 2.745 0 0 0 0 3.937 2.7 2.7 0 0 0 1.968.832 2.51 2.51 0 0 0 1.929-.8h4.443l-3.078 3.077a2.835 2.835 0 0 0-2.857 2.842 2.6 2.6 0 0 0 .831 1.969 2.82 2.82 0 0 0 2.014.788 2.67 2.67 0 0 0 1.968-.788 2.36 2.36 0 0 0 .812-1.922L14 20.827v4.444a2.51 2.51 0 0 0-.8 1.929 2.784 2.784 0 0 0 4.768 1.968A2.7 2.7 0 0 0 18.8 27.2a2.51 2.51 0 0 0-.8-1.929v-4.444l3.138 3.138a2.36 2.36 0 0 0 .812 1.922 2.66 2.66 0 0 0 1.968.788 2.83 2.83 0 0 0 2.014-.788 2.6 2.6 0 0 0 .831-1.969 2.74 2.74 0 0 0-.831-2.013 2.8 2.8 0 0 0-2.026-.829L20.828 18h4.443a2.51 2.51 0 0 0 1.93.8 2.784 2.784 0 0 0 1.967-4.769Z"/>"##, +}; +pub(super) static SWIFT: Icon = Icon { + name: "swift", + view: 24.0, + body: r##"<path fill="#ff6e40" d="M17.087 19.721c-2.36 1.36-5.59 1.5-8.86.1a13.8 13.8 0 0 1-6.23-5.32c.67.55 1.46 1 2.3 1.4 3.37 1.57 6.73 1.46 9.1 0-3.37-2.59-6.24-5.96-8.37-8.71-.45-.45-.78-1.01-1.12-1.51 8.28 6.05 7.92 7.59 2.41-1.01 4.89 4.94 9.43 7.74 9.43 7.74.16.09.25.16.36.22.1-.25.19-.51.26-.78.79-2.85-.11-6.12-2.08-8.81 4.55 2.75 7.25 7.91 6.12 12.24-.03.11-.06.22-.05.39 2.24 2.83 1.64 5.78 1.35 5.22-1.21-2.39-3.48-1.65-4.62-1.17"/>"##, +}; +pub(super) static TAILWINDCSS: Icon = Icon { + name: "tailwindcss", + view: 32.0, + body: r##"<path fill="#4db6ac" d="M23.5 12H8c.89-2.3 4.02-4 7.75-4s6.86 1.7 7.75 4M14 12h15.5c-.89 2.3-4.02 4-7.75 4s-6.86-1.7-7.75-4m3.5 8H2c.89-2.3 4.02-4 7.75-4s6.86 1.7 7.75 4M8 20h15.5c-.89 2.3-4.02 4-7.75 4S8.89 22.3 8 20"/>"##, +}; +pub(super) static TERRAFORM: Icon = Icon { + name: "terraform", + view: 32.0, + body: r##"<path fill="#5c6bc0" d="m2 10 8 4V6L2 2zm10 5 8 4v-8l-8-4zm0 11 8 4v-8l-8-4zm10-14v8l8-4V8z"/>"##, +}; +pub(super) static TEST_JS: Icon = Icon { + name: "test-js", + view: 32.0, + body: r##"<path fill="#ffca28" d="M20 4v2h-2v4.531l.264.461 7.473 13.078a2 2 0 0 1 .263.992V26a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2v-.938a2 2 0 0 1 .264-.992l7.473-13.078.263-.46V6h-2V4zm0-2h-8a2 2 0 0 0-2 2v2a2 2 0 0 0 2 2v2L4.527 23.078A4 4 0 0 0 4 25.062V26a4 4 0 0 0 4 4h16a4 4 0 0 0 4-4v-.938a4 4 0 0 0-.527-1.984L20 10V8a2 2 0 0 0 2-2V4a2 2 0 0 0-2-2"/><circle cx="17" cy="17" r="1" fill="#ffca28"/><path fill="#ffca28" d="M19.72 20.715a1 1 0 0 0-1.134-.318 5 5 0 0 1-1.18.262 3.95 3.95 0 0 1-1.862-.292 2.74 2.74 0 0 0-3.371.489 2 2 0 0 0-.237.35L10 24h12Z"/>"##, +}; +pub(super) static TEST_JSX: Icon = Icon { + name: "test-jsx", + view: 32.0, + body: r##"<path fill="#00bcd4" d="M20 4v2h-2v4.531l.264.461 7.473 13.078a2 2 0 0 1 .263.992V26a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2v-.938a2 2 0 0 1 .264-.992l7.473-13.078.263-.46V6h-2V4zm0-2h-8a2 2 0 0 0-2 2v2a2 2 0 0 0 2 2v2L4.527 23.078A4 4 0 0 0 4 25.062V26a4 4 0 0 0 4 4h16a4 4 0 0 0 4-4v-.938a4 4 0 0 0-.527-1.984L20 10V8a2 2 0 0 0 2-2V4a2 2 0 0 0-2-2"/><circle cx="17" cy="17" r="1" fill="#00bcd4"/><path fill="#00bcd4" d="M19.72 20.715a1 1 0 0 0-1.134-.318 5 5 0 0 1-1.18.262 3.95 3.95 0 0 1-1.862-.292 2.74 2.74 0 0 0-3.371.489 2 2 0 0 0-.237.35L10 24h12Z"/>"##, +}; +pub(super) static TEST_TS: Icon = Icon { + name: "test-ts", + view: 32.0, + body: r##"<path fill="#0288d1" d="M20 4v2h-2v4.531l.264.461 7.473 13.078a2 2 0 0 1 .263.992V26a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2v-.938a2 2 0 0 1 .264-.992l7.473-13.078.263-.46V6h-2V4zm0-2h-8a2 2 0 0 0-2 2v2a2 2 0 0 0 2 2v2L4.527 23.078A4 4 0 0 0 4 25.062V26a4 4 0 0 0 4 4h16a4 4 0 0 0 4-4v-.938a4 4 0 0 0-.527-1.984L20 10V8a2 2 0 0 0 2-2V4a2 2 0 0 0-2-2"/><circle cx="17" cy="17" r="1" fill="#0288d1"/><path fill="#0288d1" d="M19.72 20.715a1 1 0 0 0-1.134-.318 5 5 0 0 1-1.18.262 3.95 3.95 0 0 1-1.862-.292 2.74 2.74 0 0 0-3.371.489 2 2 0 0 0-.237.35L10 24h12Z"/>"##, +}; +pub(super) static TEX: Icon = Icon { + name: "tex", + view: 1024.0, + body: r##"<path fill="#2196f3" d="M80 192 64 320h32c16-80 16-96 63.242-96H176c8.837 0 16 7.163 16 16v352c0 8.837 0 16-32 16h-32v32h192v-32h-32c-32 0-32-7.163-32-16V240c0-8.837 7.163-16 16-16h16c48 0 48 16 64 96h32l-16-128zm560 0v32c16 0 45.713 0 52.57 16L776 434.666 708.57 592c-6.857 16-52.57 16-68.57 16v32h128v-32s-34.285 0-27.428-16L792 472l51.428 120c3.103 7.24-1.52 16-11.428 16v32h128v-32c-16 0-45.713 0-52.57-16L824 397.334 891.43 240c6.857-16 52.57-16 68.57-16v-32H832v32s34.285 0 27.428 16L808 360l-51.428-120c-3.103-7.24 1.52-16 11.428-16v-32zM320 384v32h32c32 0 32 7.163 32 16v352c0 8.837 0 16-32 16h-32v32h304l16-128h-32c-16 80-16 96-64 96h-64c-32 0-32-7.163-32-16V624h80c8.837 0 16 0 16 32v16h32V544h-32v16c0 32-7.163 32-16 32h-80V432c0-8.837 0-16 32-16h64c48 0 48 16 64 96h32l-16-128z"/>"##, +}; +pub(super) static TOML: Icon = Icon { + name: "toml", + view: 16.0, + body: r##"<path fill="#cfd8dc" d="M4 6V4h8v2H9v7H7V6z"/><path fill="#ef5350" d="M4 1v1H2v12h2v1H1V1zm8 0v1h2v12h-2v1h3V1z"/>"##, +}; +pub(super) static TRAVIS: Icon = Icon { + name: "travis", + view: 200.0, + body: r##"<path fill="#cb3349" d="M53.341 89.17s-27.564 19.4-28.641 26.791l2.068-.425S59.776 93.66 85.942 90.991l.592-3.321zm43.27-2.773-21.712 15.4 1.174.941c.885-.714 38.567-12.222 38.567-12.222l7.944-4.981c-5.33.664-25.973.862-25.973.862m18.869 18.627c15.417 0 38.527-15.1 38.527-15.1l-7.47-1.422c-.37.37-12.047-.409-12.047-.409l-5.544-1.54-13.243 15.091-1.078 2.619c.952-.387.854.76.854.76zm50.313 48.152-4.763 1.34-22.006-.475-13.766-10.705-16.64 4.163-19.244-1.665-10.777 11.776-20.22 6.04-10.097-3.13-.509-.438 4.532 11.097s10.265 11.005 15.999 12.299c5.733 1.294 16.09-.093 23.859-1.296 7.767-1.202 13.963-3.976 16.46-8.506 2.496-4.533 2.866-5.827 2.866-5.827s7.4 10.45 13.78 11.653c6.38 1.202 25.338-5.273 25.338-5.273s11.56-3.143 13.593-7.12c2.035-3.976 7.4-17.015 7.4-17.015zM50.4 162.216l-.32-.147c-.758-.655-1.378-1.19-1.783-1.538z"/><path fill="#f4edae" d="M184.483 74.565a43 43 0 0 0-.186-1.78 24 24 0 0 0-.19-1.26c-1.588-1.337-3.394-2.526-5.273-3.607-2.036-1.19-4.166-2.255-6.341-3.244-2.16-1.02-4.378-1.941-6.609-2.841q-1.672-.68-3.364-1.309c-1.124-.438-2.259-.846-3.397-1.26 2.389.395 4.753.937 7.1 1.541 1.526.395 3.044.837 4.552 1.309-10.728-28.04-36.38-46.301-64.386-46.301-28.01 0-53.659 18.26-64.385 46.3a97 97 0 0 1 4.55-1.308c2.35-.604 4.716-1.146 7.103-1.542-1.142.415-2.274.823-3.402 1.261q-1.685.63-3.364 1.309c-2.231.9-4.443 1.822-6.608 2.84-2.17.99-4.302 2.056-6.339 3.245-1.879 1.08-3.682 2.27-5.277 3.606-.066.405-.133.843-.186 1.262-.071.59-.137 1.185-.186 1.78a46 46 0 0 0-.156 3.597 52.5 52.5 0 0 0 .443 7.183c.327 2.385.765 4.754 1.412 7.043.32 1.147.68 2.279 1.099 3.373a29 29 0 0 0 1.042 2.374l.153.291c.176.09.361.18.537.266l1.067.509c.594.27 1.417.66 2.097.966a2 2 0 0 0 .11-.101l-1.98-7.541c.42-.115 4.179-1.085 10.658-2.318a32 32 0 0 1-5.91-1.723c-.7-.295-1.388-.618-2.045-.988-.657-.377-1.304-.804-1.804-1.371 7.118 2.322 21.826 1.27 34.9-.08 11.957-1.233 23.942-2.032 35.99-2.056 12.048.024 24.037.823 35.99 2.055 13.08 1.351 27.787 2.403 34.904.08-.5.568-1.145.996-1.802 1.372a20 20 0 0 1-2.045.988 32 32 0 0 1-4.34 1.385q-.328.077-.657.147c7.104 1.318 11.24 2.39 11.682 2.508l-1.894 7.184c.38-.172.765-.338 1.142-.509l1.065-.51q.266-.129.538-.265l.147-.29q.194-.372.371-.766c.24-.523.468-1.062.677-1.608a37 37 0 0 0 1.1-3.373c.647-2.29 1.084-4.659 1.412-7.043.306-2.379.466-4.782.444-7.184-.01-1.201-.053-2.4-.159-3.596"/><path fill="#e6ccad" d="M114.47 174.284c-.943.142-1.885.262-2.823.332-.604.03-1.243.09-1.823.09l-.215.005a516 516 0 0 0 1.7-3.844c.853.957 1.938 2.141 3.16 3.417zm2.046 2.091c2.926 2.898 6.553 4.558 10.544 4.853-6.704 2.723-13.023 3.774-17.89 4.101-4.853.325-9.772-.247-14.593-1.568.404-.073.7-.125 1.057-.168.396-.048 9.04-1.175 12.937-6.97l.366.009.957-.008c.647 0 1.235-.053 1.854-.077a39 39 0 0 0 4.321-.623q.22.226.447.45z"/><path fill="#656c67" d="M124.807 89.611c-.28.366-.595.77-.928 1.19-1.713 2.165-4.088 4.934-6.904 7.642a327 327 0 0 0-10.102-.157c-5.722 0-11.21.152-16.42.405 7.362-3.055 16.206-6.04 25.785-7.832 2.797-.53 5.66-.953 8.569-1.248m-43.085 3.297c-2.627 1.846-5.595 4.202-8.473 7.06a319 319 0 0 0-19.104 2.49c8.155-3.75 17.462-7.2 27.577-9.55m90.05 15.216-2.998 20.975-14.36 10.058-37.454-4.258-5.639-18.567a1.23 1.23 0 0 0-.981-.86c-1.388-.225-2.616-.339-3.639-.339-1.027 0-2.25.114-3.645.339a1.24 1.24 0 0 0-.98.86l-5.5 18.114-37.245 8.289-14.759-10.34-2.908-23.537q.95-.537 1.927-1.07 1.372-.296 3.079-.624l2.74 22.21c.043.347.234.656.52.856l10.152 7.115a1.26 1.26 0 0 0 .976.188l30.622-6.813a1.23 1.23 0 0 0 .909-.842l5.514-18.158c1.479-.38 5.268-1.266 8.597-1.266 3.321 0 7.113.885 8.593 1.266l5.514 18.157c.143.472.553.808 1.042.866l30.622 3.478c.297.033.6-.044.844-.214l10.159-7.109c.274-.195.46-.501.507-.838l2.713-18.974c2.038.393 3.741.75 5.078 1.038m3.782-13.155-2.636 10c-5.39-1.188-17.234-3.52-33.354-5.09 5.267-2.246 10.63-5.063 15.53-8.584 9.592 1.356 16.635 2.807 20.46 3.674"/><path fill="#e5caa3" d="M67.567 126.256c2.088-1.128 4.448-.96 8.14-.956.397.01.805.005 1.232-.004.363-.004.728-.01 1.114-.02 3.806-.037 6.97.325 6.915-5.652-.058-5.975-2.712-10.805-6.514-10.767-3.806.033-7.489 4.929-7.261 10.9.062 1.556.29 2.679.657 3.488-3.317.831-4.231 2.883-4.283 3.011m45.758-24.58a41 41 0 0 1-4.65 3.288l-5.4 3.26a46 46 0 0 0-6.494 1.3 1.25 1.25 0 0 0-.838.827l-5.5 18.123-29.395 6.537-9.259-6.485-2.693-21.82c5.258-.966 12.29-2.084 20.736-3.03a50 50 0 0 0-2.617 3.415l-5.029 7.218 7.322-4.881c.11-.076 4.772-3.144 12.4-6.875a334 334 0 0 1 31.417-.877m32.192 22.135c-.037-.141-.837-2.545-4.378-2.123.409-.888.59-2.087.462-3.73-.468-5.961-3.936-10.7-7.738-10.568-3.802.135-6.238 5.077-6.028 11.053.21 5.972 3.402 5.93 7.204 5.796 5.11-.095 7.918-1.665 10.478-.428m18.761-17.17-2.65 18.551-9.336 6.537-29.356-3.336-5.477-18.038a1.25 1.25 0 0 0-.837-.827c-.182-.053-3.816-1.09-7.67-1.424l.704-.047c.609-.043 10.734-1.285 22.825-5.453 13.388 1.028 24.322 2.675 31.797 4.036z"/><path fill="#c7b39a" d="M67.567 126.256c2.088-1.128 4.448-.96 8.14-.956.397.01.805.005 1.232-.004.363-.004.728-.01 1.114-.02 3.806-.037 6.97.325 6.915-5.652-.058-5.975-2.712-10.805-6.514-10.767-3.806.033-7.489 4.929-7.261 10.9.062 1.556.29 2.679.657 3.488-3.317.831-4.231 2.883-4.283 3.011m45.758-24.58a41 41 0 0 1-4.65 3.288l-5.4 3.26a46 46 0 0 0-6.494 1.3 1.25 1.25 0 0 0-.838.827l-5.5 18.123-29.395 6.537-9.259-6.485-2.693-21.82c5.258-.966 12.29-2.084 20.736-3.03a50 50 0 0 0-2.617 3.415l-5.029 7.218 7.322-4.881c.11-.076 4.772-3.144 12.4-6.875a334 334 0 0 1 31.417-.877m32.192 22.135c-.037-.141-.837-2.545-4.378-2.123.409-.888.59-2.087.462-3.73-.468-5.961-3.936-10.7-7.738-10.568-3.802.135-6.238 5.077-6.028 11.053.21 5.972 3.402 5.93 7.204 5.796 5.11-.095 7.918-1.665 10.478-.428m18.761-17.17-2.65 18.551-9.336 6.537-29.356-3.336-5.477-18.038a1.25 1.25 0 0 0-.837-.827c-.182-.053-3.816-1.09-7.67-1.424l.704-.047c.609-.043 10.734-1.285 22.825-5.453 13.388 1.028 24.322 2.675 31.797 4.036z"/><g fill="#e6ccad"><path d="M177.087 114.794c.45.371.807 1.332.404 5.809-.495 5.481-2.8 15.102-4.226 16.653-1.575.305-4.877-.057-6.89-.527.348-1.381.447-2.043.728-3.455l3.521-2.463c.28-.195.466-.501.514-.834l2.46-17.243c1.494.808 3.03 1.683 3.489 2.06M47.279 137.302q.265.938.553 1.86c-1.895.557-5.754 1.09-7.499.785-1.446-1.457-4.144-11.485-4.734-16.81-.481-4.315-.144-5.248.295-5.611.51-.428 2.416-1.513 4.068-2.398l2.232 18.114c.042.348.227.656.519.856zm71.23.248-.134 1.156s-4.058 3.763-10.59 4.605c-6.533.842-11.667-3.173-11.667-3.173.214.698.519 2.274 1.998 3.62a47 47 0 0 0-5.592-.348c-.712 0-1.432.02-2.127.054-4.02.21-9.676 6.289-13.654 12.413-1.951.618-8.05 2.554-15.111 4.64-6.59-9.132-9.831-18.463-10.16-19.428l.005-.005c-.133-.372-.267-.744-.39-1.124l1.694 1.186v.004l4.186 2.931 1.4.975c.209.148.456.224.703.224q.135 0 .27-.027l38.475-8.566c.431-.094.78-.419.908-.841l5.486-18.062a19 19 0 0 1 2.493-.195c.71 0 1.547.067 2.494.195l5.646 18.6c.143.47.552.814 1.037.865z"/><path d="m162.427 136.558 1.242-.872a77 77 0 0 1-.662 2.566c-1.726 5.534-3.765 10.43-6.028 14.754-.5.034-1.028.054-1.594.054-1.747 0-3.531-.148-5.506-.33-3.426-.314-8.864-.936-10.581-1.136-1.48-1.18-6.542-5.202-10.754-8.517-.166-.133-.308-.257-.447-.372-.742-.627-1.585-1.34-3.293-1.34-1.55 0-3.816.565-9.29 2.222 2.844-2.127 2.863-4.872 2.863-4.872l.134-1.156 36.094 4.1c.294.034.599-.042.846-.213l3.627-2.54z"/></g><path fill="#ebd599" d="M135.862 60.616c.11 3.21.029 9.03-1.466 14.478a1.2 1.2 0 0 0 0 .624 234 234 0 0 0-5.71-.524c2.136-4.477 2.602-9.244 2.703-10.923 1.64-1.167 3.274-2.566 4.473-3.655M81.4 64.27c.098 1.68.564 6.437 2.697 10.91q-2.856.228-5.705.528a1.2 1.2 0 0 0 0-.615c-1.494-5.438-1.57-11.262-1.465-14.478 1.198 1.09 2.825 2.489 4.472 3.655z"/><path fill="#2d3136" d="M145.517 123.811c-2.56-1.236-5.367.334-10.477.43-3.802.133-6.995.174-7.204-5.797-.21-5.976 2.226-10.918 6.028-11.053 3.802-.133 7.27 4.606 7.738 10.569.128 1.642-.054 2.84-.462 3.729 3.54-.423 4.34 1.98 4.377 2.122m-11.948-8.75a1.95 1.95 0 0 0 1.908-1.98 1.937 1.937 0 0 0-1.98-1.906 1.944 1.944 0 0 0 .072 3.887z"/><circle cx="131.439" cy="115.529" r="1.943" fill="#edf6fa" transform="rotate(-1.049)"/><path fill="#2d3136" d="M84.967 119.622c.056 5.976-3.108 5.615-6.914 5.652-.386.01-.752.014-1.115.02q-.64.017-1.231.003c-3.692-.004-6.053-.172-8.14.956.05-.128.965-2.18 4.282-3.012-.366-.81-.596-1.932-.657-3.487-.228-5.971 3.455-10.868 7.261-10.9 3.802-.038 6.457 4.792 6.514 10.767zm-5.876-3.126a1.944 1.944 0 1 0-.109-3.887 1.944 1.944 0 0 0 .109 3.887"/><circle cx="76.07" cy="116.551" r="1.944" fill="#edf6fa" transform="rotate(-1.473)"/><path fill="#ebd599" fill-opacity=".8" d="M55.92 79.056s.59-7.7 1.797-10.65c.622-1.52 4.426-2.489 7.331-3.18 2.904-.692 7.537-2.075 8.437 2.005s2.35 7.053 3.318 8.367l-1.244-16.803-19.985 4.84-1.315 14.869.623 1.175 1.037-.623m101.131 0s-.59-7.7-1.797-10.65c-.623-1.52-4.427-2.489-7.33-3.18-2.906-.692-7.538-2.075-8.438 2.005-.898 4.08-2.351 7.053-3.32 8.367l1.246-16.803 19.985 4.84 1.314 14.869-.623 1.175z" opacity=".8"/><path fill="#ebd599" fill-opacity=".75" d="M128.793 28.763s-.53 40.295-9.942 40.295H94.379c-9.413 0-10.173-40.277-10.173-40.277l-4.624 13.675.076 18.764 3.283 2.61 1.493 8.058 2.088 4.7 40.288.075 1.864-3.358 1.567-5.67.225-3.58 4.45-12.704zm29.647 37.572s1.938 13.9 7.064 16.407l-7.178-2.165zm-104.1 0s-1.938 13.9-7.065 16.407l7.179-2.165z" opacity=".75"/><path fill="#2d3136" d="M159.823 80.513c2.44.8 4.894 1.646 7.118 2.946-1.19-.472-2.418-.809-3.655-1.114a62 62 0 0 0-3.721-.818 116 116 0 0 0-7.528-1.176 169 169 0 0 0-7.57-.818c-2.531-.214-5.057-.428-7.594-.576-10.139-.624-20.306-.78-30.48-.79-10.172.005-20.34.196-30.48.795-2.535.147-5.062.362-7.593.576s-5.058.486-7.57.818c-2.522.305-5.03.705-7.527 1.175q-1.871.35-3.726.814c-1.232.305-2.465.642-3.655 1.114 2.223-1.299 4.677-2.15 7.123-2.95.205-.067.414-.124.623-.19-.014-.053-.029-.1-.038-.157-.043-.281-.947-6.962.628-16.516.076-.457.404-.828.852-.952l2.584-.736c.561-20.042 8.815-29.467 9.073-29.758-7.375 11.867-7.308 25.942-7.18 29.22l16.057-4.565.038-.008q.1-.022.2-.029c.018 0 .043-.005.066-.005.082-.004.173.005.263.024.014 0 .028.01.047.014.067.014.129.037.199.066.029.015.047.03.076.044q.078.044.157.1c.014.009.03.013.043.028l.028.029c.015.014.033.024.048.039.01.014.438.436 1.118 1.07-.161-5.29.09-20.469 7.319-33.049-.153.441-5.887 17.21-3.911 36.004a30 30 0 0 0 1.974 1.46c.318.22.514.58.518.966.006.062.143 6.053 2.789 11.149q.054.115.09.237c6.58-.447 13.18-.628 19.764-.632 6.587.004 13.18.194 19.76.647.024-.086.053-.17.096-.252 2.645-5.096 2.784-11.087 2.784-11.15.009-.385.204-.746.523-.965a32 32 0 0 0 1.97-1.46c1.979-18.794-3.756-35.563-3.907-36.004 7.222 12.58 7.48 27.758 7.318 33.05a55 55 0 0 0 1.117-1.071c.014-.015.035-.024.047-.04.01-.008.016-.018.03-.028.014-.014.029-.02.043-.029l.157-.104.071-.039c.072-.029.138-.052.21-.07.014 0 .029-.01.043-.01.085-.019.177-.028.262-.024.024 0 .043.005.062.005.066.005.138.014.205.029.01.005.024.005.037.009l16.058 4.563c.13-3.277.196-17.353-7.178-29.219.256.29 8.512 9.717 9.068 29.758l2.588.736c.442.124.775.495.852.952 1.574 9.554.666 16.235.627 16.516q-.015.085-.037.161c.212.062.417.123.627.19m-2.92-.857c.123-1.07.698-6.917-.524-14.882l-18.177-5.167c.163 3.078.235 9.754-1.512 16.12a1.4 1.4 0 0 1-.09.229c.18.019.362.033.537.057 5.11.585 10.197 1.403 15.226 2.507 1.517.352 3.035.729 4.539 1.136zm-22.508-4.563c1.495-5.447 1.576-11.267 1.466-14.478-1.199 1.09-2.832 2.488-4.473 3.654-.1 1.68-.567 6.447-2.703 10.923 1.903.154 3.807.325 5.71.524a1.2 1.2 0 0 1 0-.623m-50.296.087c-2.133-4.473-2.599-9.232-2.698-10.91-1.646-1.166-3.274-2.565-4.473-3.654-.105 3.216-.028 9.04 1.466 14.478.057.21.051.42 0 .615q2.85-.301 5.705-.529m-7.913.765a1.5 1.5 0 0 1-.087-.218c-1.75-6.367-1.673-13.042-1.516-16.121l-18.171 5.167c-1.223 7.956-.652 13.803-.53 14.879 1.51-.41 3.022-.786 4.546-1.138 2.511-.556 5.043-1.022 7.579-1.45 2.541-.424 5.09-.747 7.64-1.057.182-.024.358-.037.54-.062z"/><path fill="#2d3136" d="M125.542 29.29v15.081h-10.69v-4.406h-2.41v20.357h3.64v11.382H97.385V60.322h3.625V39.966h-2.401v4.406H87.925V29.29zm-3.212 11.877v-8.671h-31.2v8.671h4.266v-4.406h8.826v26.773h-3.632V68.5h12.282v-4.966h-3.632V36.761h8.826v4.406z"/><path fill="#cb3349" d="M104.22 36.761h-8.823v4.406h-4.266v-8.672h31.205v8.672h-4.27v-4.406h-8.823v26.773h3.632V68.5H100.59v-4.966h3.632z"/><path fill="#656c67" d="M38.206 94.969c1.558-.354 3.663-.804 6.246-1.302a93 93 0 0 0-5.512 4.072z"/><g fill="#c7b39a"><path d="M95.266 136.301s.436 2.804-3.488 4.003c-3.922 1.2-28.773 8.606-31.607 8.205s-10.026-5.203-10.026-5.203l-1.745-6.204 10.644 6.636zm22.26-.541s-.314 2.82 3.659 3.85c3.972 1.028 29.12 7.347 31.933 6.824s9.79-5.635 9.79-5.635l1.474-6.275-9.784 5.836z"/><path d="M36.184 131.146s3.443 6.887 9.005 4.502l3.973 1.457-.397 2.915-8.343 1.058-2.25-1.323zm140.965-1.896s-5.628 7.188-11.19 4.805l-1.788 1.153.397 2.913 8.343 1.06 2.25-1.324zM90.1 183.355s20.4 10.285 43.498-3.71l-7.417-.506s-16.186 6.406-29 2.866z"/></g><path fill="#2d3136" d="m110.785 164.408 1.412 1.682c.032.04 3.168 3.773 7.003 7.575 2.55 2.527 5.63 3.806 9.162 3.806a16 16 0 0 0 3.751-.463c1.187-.289 2.477-.596 3.797-.912 4.77-1.14 10.171-2.435 12.79-3.169a35 35 0 0 1 1.705-.418c3.485-.805 8.263-1.916 10.795-6.988 1.904-3.806 4.47-8.746 6.375-12.367-1.65.761-3.38 1.586-4.609 2.233-1.894.994-4.374 1.476-7.58 1.476-1.907 0-3.78-.16-5.851-.344-4.141-.381-11.149-1.206-11.22-1.216l-.537-.06-.424-.338c-.063-.046-6.203-4.939-11.166-8.842q-.302-.247-.55-.454c-.523-.446-.523-.446-.835-.446-1.591 0-6.218 1.435-16.353 4.577l-.623.198-.61-.23c-.07-.023-6.72-2.49-14.688-2.49-.652 0-1.302.017-1.935.05-.798.041-5.278 2.169-11.006 11.232l-.371.582-.657.21c-.095.034-9.954 3.216-20.41 6.206l-.679.193-.642-.298c-.068-.028-4.16-1.926-8.053-3.716 2.123 3.137 4.838 7.05 7.227 10.118 4.173 5.374 9.433 10.34 19.518 10.34 1.265 0 2.609-.077 3.989-.234 10.258-1.16 12.9-1.627 14.321-1.875.481-.082.862-.152 1.349-.21.077-.01 8.478-1.097 10.835-6.384 2.43-5.433 2.921-6.728 2.94-6.777l.857-2.288s.106-.593.28-.777q-.001.005.005.004l.017.014c.27.194.67.8.67.8zM46.895 61.832c-2.23.898-4.444 1.825-6.609 2.842-2.169.992-4.301 2.056-6.337 3.242-1.88 1.083-3.683 2.27-5.274 3.611a34 34 0 0 0-.187 1.26 46 46 0 0 0-.344 5.376 53 53 0 0 0 .445 7.185c.33 2.385.765 4.756 1.412 7.044a37 37 0 0 0 1.1 3.37c.207.551.436 1.087.676 1.61.118.26.242.518.365.765l.153.29c.178.091.362.182.536.265l1.068.508c.596.276 1.417.666 2.096.968.04-.032.078-.069.11-.1l-1.977-7.54c.418-.114 4.179-1.086 10.658-2.32a30 30 0 0 1-1.572-.335 32.5 32.5 0 0 1-4.339-1.385 20 20 0 0 1-2.045-.99c-.656-.377-1.303-.803-1.803-1.371 7.118 2.324 21.824 1.27 34.9-.078 11.958-1.234 23.94-2.031 35.988-2.06 12.046.028 24.038.825 35.99 2.06 13.083 1.348 27.79 2.403 34.905.078-.5.568-1.145.994-1.801 1.37-.655.372-1.348.693-2.046.991a33 33 0 0 1-4.343 1.385q-.325.076-.656.147c7.104 1.316 11.24 2.389 11.68 2.508l-1.894 7.182c.381-.17.766-.334 1.141-.509l1.07-.508a21 21 0 0 0 .536-.266l.147-.289a18 18 0 0 0 .371-.765q.361-.785.68-1.61c.417-1.09.778-2.224 1.095-3.37.647-2.288 1.087-4.66 1.412-7.044.307-2.38.468-4.783.445-7.186a47 47 0 0 0-.156-3.595 46 46 0 0 0-.188-1.78 26 26 0 0 0-.19-1.26c-1.591-1.34-3.393-2.527-5.273-3.61-2.037-1.188-4.167-2.251-6.342-3.243-2.16-1.017-4.378-1.944-6.608-2.842a126 126 0 0 0-3.367-1.308c-1.122-.435-2.26-.846-3.397-1.26 2.388.394 4.756.939 7.098 1.54 1.527.395 3.05.84 4.554 1.312-10.727-28.043-36.38-46.302-64.384-46.302-28.011 0-53.658 18.26-64.384 46.302a96 96 0 0 1 4.549-1.312c2.348-.6 4.714-1.146 7.104-1.54-1.143.413-2.275.825-3.403 1.26-1.123.417-2.246.857-3.365 1.307m141.223 16.224c.129 2.581.06 5.167-.229 7.736a49 49 0 0 1-1.434 7.622 40 40 0 0 1-1.244 3.719 34 34 0 0 1-.788 1.834c-.143.302-.293.6-.463.908l-.252.454a8 8 0 0 1-.308.508l-.26.405-.409.21c-.436.225-.793.394-1.189.578l-1.15.519c-.77.33-1.545.64-2.32.943-.541.212-1.019.405-1.472.597l-1.28 4.86a94 94 0 0 0-1.136-.279l-.07.509c1.413.738 4.187 2.234 5.132 3.014 1.903 1.572 2.037 4.063 1.615 8.717-.216 2.39-1.009 7.039-2.109 11.31-1.9 7.35-2.908 8.213-4.21 8.546-.66.17-1.678.34-2.665.34-2.007 0-4.741.055-6.58-.39-.472 1.673-1.82 6.035-4.49 11.483.134-.065.266-.12.386-.184 3.292-1.729 9.62-4.485 9.887-4.605l4.999-2.172-2.56 4.814c-.06.105-5.549 10.429-8.91 17.17-3.34 6.677-9.598 8.13-13.345 8.992-.564.133-1.1.257-1.535.376-2.689.756-8.132 2.054-12.932 3.21-.057.013-.115.028-.174.036a56.7 56.7 0 0 1-9.704 4.793c-12.905 4.888-26.506 4.614-38.837.082-2.003.258-4.637.573-8.144.972a40 40 0 0 1-4.415.257c-11.75 0-17.977-5.966-22.522-11.808-4.865-6.256-10.817-15.542-11.07-15.931l-3.45-5.383 5.832 2.623c2.792 1.257 11.094 5.1 13.469 6.2q.287-.082.569-.165c-3.948-5.63-7.186-12.05-9.474-19.163-1.944.586-4.94 1.04-7.269 1.04-.851 0-1.614-.063-2.2-.201-1.303-.298-2.789-1.554-4.811-8.676-1.174-4.135-2.05-8.65-2.306-10.973-.505-4.536-.413-6.966 1.472-8.535 1.137-.95 4.97-2.963 5.764-3.374l-.17-1.4c-12.18 7.157-19.48 13.482-19.626 13.611l-8.71 7.644 6.205-9.786c4.91-7.755 10.583-14.024 15.802-18.853-.216-.087-.417-.174-.629-.26l-1.15-.519a31 31 0 0 1-1.187-.578l-.409-.21-.261-.405c-.147-.22-.21-.344-.307-.508l-.257-.454c-.16-.307-.317-.606-.46-.908q-.433-.914-.787-1.834a40 40 0 0 1-1.244-3.719 48.5 48.5 0 0 1-1.435-7.622 48.4 48.4 0 0 1-.23-7.736q.105-1.935.372-3.857c.092-.642.188-1.284.317-1.922.133-.65.262-1.256.459-1.967l.137-.5.358-.28c2.032-1.597 4.223-2.802 6.452-3.87a70 70 0 0 1 5.59-2.318C43.622 48.733 52.674 35.78 64.57 26.75c12.3-9.332 26.762-14.266 41.827-14.266s29.527 4.934 41.825 14.267c11.897 9.029 20.949 21.984 26.21 36.59a69 69 0 0 1 5.594 2.32c2.228 1.069 4.42 2.274 6.451 3.87l.358.281.138.5c.201.711.33 1.317.458 1.967.13.638.23 1.28.317 1.922.18 1.278.308 2.566.37 3.855m-10.626 42.546c.404-4.475.052-5.438-.403-5.805-.454-.381-1.99-1.251-3.485-2.063l-2.462 17.24a1.23 1.23 0 0 1-.514.835l-3.522 2.464c-.28 1.41-.38 2.077-.724 3.457 2.013.468 5.314.83 6.887.527 1.428-1.548 3.733-11.17 4.223-16.655m-4.571-15.633 2.637-10c-3.825-.867-10.869-2.317-20.462-3.674-4.899 3.521-10.26 6.337-15.528 8.584 16.12 1.569 27.965 3.903 33.353 5.09m-4.146 24.127 2.999-20.972c-1.334-.289-3.04-.646-5.077-1.036l-2.71 18.976c-.05.335-.234.642-.509.835l-10.162 7.107a1.23 1.23 0 0 1-.839.215l-30.623-3.48a1.23 1.23 0 0 1-1.042-.862l-5.516-18.159c-1.477-.382-5.27-1.267-8.589-1.267-3.334 0-7.122.885-8.599 1.267l-5.517 18.16a1.23 1.23 0 0 1-.908.838l-30.624 6.814a1.3 1.3 0 0 1-.27.029c-.248 0-.496-.074-.702-.222l-10.158-7.112a1.24 1.24 0 0 1-.518-.857l-2.738-22.21c-1.137.221-2.164.432-3.082.624q-.976.537-1.925 1.074l2.906 23.534 14.763 10.342 37.245-8.286 5.498-18.114a1.23 1.23 0 0 1 .982-.863c1.394-.224 2.613-.339 3.646-.339 1.02 0 2.246.115 3.636.339.467.073.847.408.981.863l5.64 18.563 37.453 4.259zm-7.148-3.907 2.65-18.556c-7.475-1.36-18.407-3.006-31.797-4.034-12.089 4.17-22.214 5.41-22.824 5.452l-.706.05c3.856.332 7.489 1.368 7.671 1.422.4.12.712.426.836.827l5.48 18.04 29.354 3.334zm2.04 10.492-1.244.87-3.347 2.35-3.628 2.54c-.247.17-.55.248-.845.215l-36.092-4.104-2.628-.299a1.23 1.23 0 0 1-1.037-.865l-5.649-18.6a19 19 0 0 0-2.489-.194q-1.076 0-2.495.194l-5.485 18.063a1.23 1.23 0 0 1-.908.838l-38.475 8.568a1.4 1.4 0 0 1-.27.026c-.247 0-.495-.073-.707-.224l-1.397-.973-4.187-2.929v-.01l-1.692-1.182c.12.38.256.752.391 1.123l-.005.005c.326.967 3.568 10.295 10.157 19.424a774 774 0 0 0 15.11-4.636c3.975-6.127 9.634-12.203 13.657-12.413a45 45 0 0 1 2.127-.054c1.968 0 3.848.141 5.59.348-1.48-1.344-1.784-2.922-1.999-3.619 0 0 5.132 4.013 11.666 3.175 6.536-.844 10.594-4.61 10.594-4.61s-.02 2.748-2.867 4.875c5.476-1.656 7.741-2.224 9.291-2.224 1.71 0 2.554.715 3.293 1.345.142.114.285.237.449.371 4.21 3.315 9.272 7.337 10.754 8.516 1.715.201 7.153.82 10.58 1.137 1.975.178 3.76.33 5.506.33.565 0 1.093-.024 1.592-.057 2.266-4.322 4.303-9.222 6.03-14.75.232-.851.458-1.709.659-2.57M150.35 89.98q-.014-.009-.028-.01a489 489 0 0 0-8.704-.577 803 803 0 0 0-12.106-.592 65 65 0 0 1-1.394 1.97c-2.196 2.973-6.553 8.425-12.14 13.048 7.908-1.417 21.622-4.925 33.487-13.203.297-.21.592-.43.885-.636m-26.464.82c.334-.417.645-.82.924-1.187a99 99 0 0 0-8.565 1.247c-9.58 1.793-18.426 4.774-25.786 7.828a340 340 0 0 1 16.423-.403c3.462 0 6.828.06 10.101.156 2.816-2.707 5.192-5.476 6.903-7.64zm3.177 90.423c-3.989-.294-7.616-1.953-10.544-4.852l-.444-.453a39 39 0 0 1-4.324.623c-.618.023-1.206.077-1.852.077l-.96.01-.365-.01c-3.894 5.793-12.542 6.921-12.937 6.972-.357.04-.65.09-1.055.164 4.82 1.321 9.74 1.894 14.592 1.568 4.865-.325 11.185-1.38 17.889-4.1zm-15.413-6.61a40 40 0 0 0 2.82-.334 123 123 0 0 1-3.16-3.417c-.417.959-.97 2.22-1.7 3.844h.214c.583 0 1.221-.063 1.826-.092zm-2.97-69.651a42 42 0 0 0 4.649-3.289c-2.115-.036-4.26-.063-6.447-.063-8.98 0-17.367.367-24.97.94-7.627 3.728-12.29 6.795-12.4 6.873l-7.323 4.885 5.03-7.219a47 47 0 0 1 2.619-3.416c-8.447.944-15.481 2.063-20.737 3.03l2.691 21.82 9.26 6.485 29.394-6.536 5.502-18.127a1.24 1.24 0 0 1 .556-.702 1 1 0 0 1 .279-.124c.17-.046 3.109-.885 6.498-1.298zm3.38-16.643q-3.072-.048-6.142-.055h-.004q-4.505.007-9.025.097l-5.553 2.631c-.005.005-.037.02-.078.043-.835.407-8.127 4.086-14.987 10.648 6.15-3.233 15.188-7.456 25.823-10.731a128 128 0 0 1 9.966-2.633M73.248 99.962c2.88-2.857 5.85-5.214 8.474-7.057-10.111 2.348-19.42 5.796-27.573 9.547a320 320 0 0 1 19.099-2.49m1.912-8.813a132 132 0 0 1 10.464-2.476c-5.136.187-10.275.426-15.406.715-2.982.165-5.949.367-8.916.591a138 138 0 0 0-4.435.394c-.422.041-.835.087-1.256.142-3.87 2.315-18.715 11.634-28.905 23.818 9.903-6.881 27.153-17.222 48.454-23.184m-27.327 48.008a61 61 0 0 1-.55-1.862l-4.572-3.2a1.23 1.23 0 0 1-.52-.858l-2.228-18.114c-1.651.885-3.558 1.971-4.068 2.398-.44.363-.775 1.294-.297 5.61.592 5.323 3.288 15.353 4.737 16.81 1.743.308 5.605-.228 7.498-.784m-3.379-45.495c-2.582.5-4.688.949-6.246 1.302l.735 2.77a92 92 0 0 1 5.511-4.072"/>"##, +}; +pub(super) static TSCONFIG: Icon = Icon { + name: "tsconfig", + view: 32.0, + body: r##"<path fill="#757575" d="M15 2H6a2.006 2.006 0 0 0-2 2v22a2.006 2.006 0 0 0 2 2h6v-4H6v-2h6v-2H6v-2h6v-2H6v-2h6v-2h2V4l8 8h2v-1Z" data-mit-no-recolor="true"/><path fill="#0288d1" d="M12 12v18h18V12Zm8 6h-2v8h-2v-8h-2v-2h6Zm8 0h-4v2h2a2.006 2.006 0 0 1 2 2v2a2.006 2.006 0 0 1-2 2h-4v-2h4v-2h-2a2.006 2.006 0 0 1-2-2v-2a2.006 2.006 0 0 1 2-2h4Z"/>"##, +}; +pub(super) static TUNE: Icon = Icon { + name: "tune", + view: 32.0, + body: r##"<path fill="#fbc02d" d="M12 10h10v2H12z"/><path fill="#fbc02d" d="M16 4h2v8h-2zm4 18h10v2H20zm4 2h2v4h-2zm0-20h2v14h-2zM2 18h10v2H2z"/><path fill="#fbc02d" d="M6 18h2v10H6zM6 4h2v10H6zm10 12h2v12h-2z"/>"##, +}; +pub(super) static TURBOREPO: Icon = Icon { + name: "turborepo", + view: 32.0, + body: r##"<defs><linearGradient id="a" x1="27.349" x2="7.613" y1="26.455" y2="6.719" gradientTransform="matrix(1 0 0 -1 0 34)" gradientUnits="userSpaceOnUse"><stop offset=".15" stop-color="#2196f3"/><stop offset=".85" stop-color="#f50057"/></linearGradient></defs><path fill="#cfd8dc" d="M16 8a8 8 0 1 0 8 8 8 8 0 0 0-8-8m0 12a4 4 0 1 1 4-4 4 4 0 0 1-4 4"/><path fill="url(#a)" d="M4.281 23.647A13.9 13.9 0 0 1 2 16h4a9.95 9.95 0 0 0 1.192 4.736ZM14 29.84v-4.042a9.9 9.9 0 0 1-3.892-1.732l-2.854 2.855A13.9 13.9 0 0 0 14 29.84M16 2v4a10 10 0 0 1 2 19.8v4.04A13.992 13.992 0 0 0 16 2"/>"##, +}; +pub(super) static TYPESCRIPT: Icon = Icon { + name: "typescript", + view: 16.0, + body: r##"<path fill="#0288d1" d="M2 2v12h12V2zm4 6h3v1H8v4H7V9H6zm5 0h2v1h-2v1h1a1.003 1.003 0 0 1 1 1v1a1.003 1.003 0 0 1-1 1h-2v-1h2v-1h-1a1.003 1.003 0 0 1-1-1V9a1.003 1.003 0 0 1 1-1"/>"##, +}; +pub(super) static TYPESCRIPT_DEF: Icon = Icon { + name: "typescript-def", + view: 16.0, + body: r##"<g fill="#0288d1"><path d="M2 2v12h12V2zm1 1h10v10H3z"/><path d="M5 7v1h1v4h1V8h1V7zm5 0a1.003 1.003 0 0 0-1 1v1a1.003 1.003 0 0 0 1 1h1v1H9v1h2a1.003 1.003 0 0 0 1-1v-1a1.003 1.003 0 0 0-1-1h-1V8h2V7z"/></g>"##, +}; +pub(super) static VERCEL: Icon = + Icon { name: "vercel", view: 32.0, body: r##"<path fill="#cfd8dc" d="m16 6 12 20H4Z"/>"## }; +pub(super) static VIDEO: Icon = Icon { + name: "video", + view: 32.0, + body: r##"<path fill="#ff9800" d="m24 6 2 6h-4l-2-6h-3l2 6h-4l-2-6h-3l2 6H8L6 6H5a3 3 0 0 0-3 3v14a3 3 0 0 0 3 3h22a3 3 0 0 0 3-3V6Z"/>"##, +}; +pub(super) static VISUALSTUDIO: Icon = Icon { + name: "visualstudio", + view: 32.0, + body: r##"<path fill="#ab47bc" d="m22 11.8-5.7 4.584L22 20.8zM7.24 23.68 4 21.64v-10.8l3.6-1.2 5.16 3.996L23.2 4 28 7v18.6L22 28l-9.192-8.808zm.36-5.28 2.232-2.064L7.6 14.2Z"/>"##, +}; +pub(super) static VITE: Icon = + Icon { name: "vite", view: 32.0, body: r##"<path fill="#ffab00" d="M10 2v16h4v12l9-16h-6l5-12Z"/>"## }; +pub(super) static VITEST: Icon = Icon { + name: "vitest", + view: 32.0, + body: r##"<path fill="#689f38" d="M16.094 30.074a1.4 1.4 0 0 1-1.003-.416l-6.622-6.622a1.42 1.42 0 0 1 2.006-2.006l5.62 5.618 12.24-12.24a1.419 1.419 0 0 1 2.007 2.006L17.098 29.658a1.4 1.4 0 0 1-1.004.416"/><path fill="#689f38" fill-opacity=".502" d="M16.089 30.074a1.4 1.4 0 0 0 1.003-.416l6.622-6.622a1.42 1.42 0 0 0-2.006-2.006l-5.62 5.618-12.24-12.24a1.42 1.42 0 0 0-2.007 2.006l13.244 13.244a1.4 1.4 0 0 0 1.004.416"/><path fill="#ffca28" d="M24 10h-6V2l-8 12h6v8z"/>"##, +}; +pub(super) static VLANG: Icon = Icon { + name: "vlang", + view: 500.0, + body: r##"<g style="isolation:isolate"><path fill="currentColor" d="m311.64 433.372 130.885-363.97c2.22-6.173-1.28-10.674-7.809-10.044l-102.93 9.915c-6.529.63-13.582 6.17-15.739 12.363L194.901 429.48c-2.158 6.194 1.416 11.223 7.975 11.223h100.191c3.28 0 6.843-2.505 7.953-5.592z" /><path fill="#039be5" d="m65.278 59.359 102.93 9.915c6.529.63 13.59 6.167 15.757 12.358l123.714 353.456c1.083 3.097-.7 5.608-3.98 5.608H202.877c-6.56 0-13.688-5.01-15.907-11.183L57.472 69.398c-2.22-6.173 1.28-10.674 7.809-10.044z" /></g>"##, +}; +pub(super) static VSCODE: Icon = Icon { + name: "vscode", + view: 16.0, + body: r##"<path fill="#2196f3" d="M11.5 11.19V4.8L7.3 7.99M1.17 6.07a.6.6 0 0 1-.01-.81L2 4.48c.14-.13.48-.18.73 0l2.39 1.83 5.55-5.09c.22-.22.61-.32 1.05-.08l2.8 1.34c.25.15.49.38.49.81v9.49c0 .28-.2.58-.42.7l-3.08 1.48c-.22.09-.64 0-.79-.14L5.11 9.69l-2.38 1.83c-.27.18-.6.13-.74 0l-.84-.77c-.22-.23-.2-.61.04-.84l2.1-1.9"/>"##, +}; +pub(super) static WEBASSEMBLY: Icon = Icon { + name: "webassembly", + view: 32.0, + body: r##"<path fill="#7c4dff" d="M22 18h4v4h-4z"/><path fill="#7c4dff" d="M20 2a4 4 0 0 1-8 0H2v28h28V2Zm-2 24h-2v2h-4v-2h-2v2H6v-2H4V16h2v10h4V16h2v10h4V16h2Zm10 2h-2v-4h-4v4h-2V18h2v-2h4v2h2Z"/>"##, +}; +pub(super) static WEBPACK: Icon = Icon { + name: "webpack", + view: 24.0, + body: r##"<path fill="#fafafa" fill-opacity=".785" d="m19.376 15.988-7.708 4.45-7.709-4.45v-8.9l7.709-4.451 7.708 4.45z"/><path fill="#90caf9" d="M12.286 1.98c-.21 0-.41.059-.57.179l-7.9 4.44c-.32.17-.53.5-.53.88v9c0 .38.21.711.53.881l7.9 4.44c.16.12.36.18.57.18s.41-.06.57-.18l7.9-4.44c.32-.17.53-.5.53-.88v-9c0-.38-.21-.712-.53-.882l-7.9-4.44a.95.95 0 0 0-.57-.179zm0 2.15 7 3.94v2.103h-.016v5.177h.016v.54l-7 3.939-7-3.94V8.07zm0 2.08-4.9 2.83 4.9 2.83 4.9-2.83zm-5 5.08v3.58l4 2.309v-3.58l-4-2.31zm10 0-4 2.308v3.58l4-2.308z"/><path fill="#0277bd" d="m12.286 6.21-4.9 2.83 4.9 2.83 4.9-2.83zm-5 5.08v3.58l4 2.309v-3.58l-4-2.31zm10 0-4 2.308v3.58l4-2.308z"/>"##, +}; +pub(super) static WORD: Icon = Icon { + name: "word", + view: 24.0, + body: r##"<path fill="#01579b" d="M6 2h8l6 6v12a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2m7 1.5V9h5.5zM7 13l1.5 7h2l1.5-3 1.5 3h2l1.5-7h1v-2h-4v2h1l-.9 4.2L13 15h-2l-1.1 2.2L9 13h1v-2H6v2z"/>"##, +}; +pub(super) static WRANGLER: Icon = Icon { + name: "wrangler", + view: 32.0, + body: r##"<path fill="#f57f17" d="M22 20H10.5a.5.5 0 0 1-.5-.5v-1a.5.5 0 0 1 .5-.5H22v-6.449A5.95 5.95 0 0 0 18 10h-2a5.98 5.98 0 0 0-4.463 2H10a4 4 0 0 0-4 4 4 4 0 0 0-4 4v1.5a.5.5 0 0 0 .5.5H22Z"/><path fill="#ffab40" d="M24 14v4h1.5a.5.5 0 0 1 .5.5v1a.5.5 0 0 1-.5.5H24v2h5.5a.5.5 0 0 0 .5-.5V20a6 6 0 0 0-6-6"/>"##, +}; +pub(super) static XML: Icon = Icon { + name: "xml", + view: 24.0, + body: r##"<path fill="#8bc34a" d="M13 9h5.5L13 3.5zM6 2h8l6 6v12a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V4c0-1.11.89-2 2-2m.12 13.5 3.74 3.74 1.42-1.41-2.33-2.33 2.33-2.33-1.42-1.41zm11.16 0-3.74-3.74-1.42 1.41 2.33 2.33-2.33 2.33 1.42 1.41z"/>"##, +}; +pub(super) static YAML: Icon = Icon { + name: "yaml", + view: 24.0, + body: r##"<path fill="#ff5252" d="M13 9h5.5L13 3.5zM6 2h8l6 6v12c0 1.1-.9 2-2 2H6c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2m12 16v-2H9v2zm-4-4v-2H6v2z"/>"##, +}; +pub(super) static YARN: Icon = Icon { + name: "yarn", + view: 32.0, + body: r##"<path fill="#0288d1" d="M27.575 23.967a9.9 9.9 0 0 0-3.751 1.726 22.6 22.6 0 0 1-5.537 2.504 1.55 1.55 0 0 1-.931.52 59 59 0 0 1-6.11.548c-1.102.008-1.777-.282-1.965-.735a1.49 1.49 0 0 1 .82-1.965 3.6 3.6 0 0 1-.486-.359c-.163-.162-.334-.487-.385-.367-.213.52-.324 1.794-.897 2.366-.786.795-2.273.53-3.153.069-.965-.513.069-1.718.069-1.718a.69.69 0 0 1-.94-.324 4.6 4.6 0 0 1-.632-2.794 5.2 5.2 0 0 1 1.674-2.76 8.84 8.84 0 0 1 .624-4.17 9.9 9.9 0 0 1 3-3.469S7.136 11.015 7.82 9.177c.444-1.196.623-1.187.769-1.239a3.44 3.44 0 0 0 1.375-.811 4.99 4.99 0 0 1 4.178-1.607s1.094-3.357 2.12-2.7a17.4 17.4 0 0 1 1.452 2.735s1.213-.71 1.35-.445a10.74 10.74 0 0 1 .495 5.81 13.3 13.3 0 0 1-2.46 5.127c-.129.214 1.47.889 2.477 3.683.932 2.554.103 4.699.248 4.938.026.043.034.06.034.06s1.068.085 3.213-1.24a8.05 8.05 0 0 1 4.05-1.52 1.026 1.026 0 0 1 .453 2Z"/>"##, +}; +pub(super) static ZIG: Icon = Icon { + name: "zig", + view: 32.0, + body: r##"<path fill="#f9a825" d="M2 8h6v4H2zm8 0h12v4H10zm0 12h12v4H10zm14 0h2v4h-2zM8 20l-3 4H2V12h4v8zm14-8h-6l-6 8h6z"/><path fill="#f9a825" d="M16 20h-6l-6 8m12-16h6l6-8m2 4v16h-4V12h-2l3-4z"/>"##, +}; +pub(super) static ZIP: Icon = Icon { + name: "zip", + view: 24.0, + body: r##"<path fill="#afb42b" d="M14 17h-2v-2h-2v-2h2v2h2m0-6h-2v2h2v2h-2v-2h-2V9h2V7h-2V5h2v2h2m5-4H5c-1.11 0-2 .89-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V5a2 2 0 0 0-2-2"/>"##, +}; + +/// A whole lower-case file name's badge (`fileNames`). +pub(super) fn by_file_name(key: &str) -> Option<&'static Icon> { + Some(match key { + "readme.md" => &README, + "changelog.md" => &CHANGELOG, + "contributing.md" => &CONTRIBUTING, + "conduct.md" => &CONDUCT, + "license" => &CERTIFICATE, + "authors" => &AUTHORS, + "credits" => &CREDITS, + "install" => &INSTALLATION, + "package.json" => &NODEJS, + "package-lock.json" => &NODEJS, + "yarn.lock" => &YARN, + "pnpm-lock.yaml" => &PNPM, + "bun.lock" => &BUN, + "bun.lockb" => &BUN, + "bunfig.toml" => &BUN, + ".nvmrc" => &NODEJS, + ".node-version" => &NODEJS, + "dockerfile" => &DOCKER, + "docker-compose.yml" => &DOCKER, + "docker-compose.yaml" => &DOCKER, + ".dockerignore" => &DOCKER, + "jest.config.js" => &JEST, + "jest.config.ts" => &JEST, + "jest.config.mjs" => &JEST, + "vitest.config.js" => &VITEST, + "vitest.config.ts" => &VITEST, + "tailwind.config.js" => &TAILWINDCSS, + "tailwind.config.ts" => &TAILWINDCSS, + "turbo.json" => &TURBOREPO, + "tsconfig.json" => &TSCONFIG, + "jsconfig.json" => &JSCONFIG, + ".eslintrc" => &ESLINT, + ".eslintrc.js" => &ESLINT, + ".eslintrc.json" => &ESLINT, + ".prettierrc" => &PRETTIER, + ".prettierrc.js" => &PRETTIER, + ".prettierrc.json" => &PRETTIER, + "vite.config.js" => &VITE, + "vite.config.ts" => &VITE, + "webpack.config.js" => &WEBPACK, + "rollup.config.js" => &ROLLUP, + "astro.config.mjs" => &ASTRO_CONFIG, + "astro.config.js" => &ASTRO_CONFIG, + "next.config.js" => &NEXT, + "next.config.mjs" => &NEXT, + "nuxt.config.js" => &NUXT, + "nuxt.config.ts" => &NUXT, + "svelte.config.js" => &SVELTE, + "gatsby-config.js" => &GATSBY, + "remix.config.js" => &REMIX, + "prisma.schema" => &PRISMA, + ".gitignore" => &GIT, + ".gitattributes" => &GIT, + "makefile" => &MAKEFILE, + "cmake" => &CMAKE, + "cargo.toml" => &RUST, + "go.mod" => &GO_MOD, + "go.sum" => &GO_MOD, + "requirements.txt" => &PYTHON, + "pyproject.toml" => &PYTHON, + "pipfile" => &PYTHON, + "poetry.lock" => &POETRY, + "gemfile" => &GEMFILE, + "rakefile" => &RUBY, + "composer.json" => &PHP, + "build.gradle" => &GRADLE, + "pom.xml" => &MAVEN, + "deno.json" => &DENO, + "deno.jsonc" => &DENO, + "vercel.json" => &VERCEL, + "netlify.toml" => &NETLIFY, + ".env" => &TUNE, + ".env.local" => &TUNE, + ".env.development" => &TUNE, + ".env.production" => &TUNE, + ".env.example" => &TUNE, + ".editorconfig" => &EDITORCONFIG, + "robots.txt" => &ROBOTS, + "favicon.ico" => &FAVICON, + "browserlist" => &BROWSERLIST, + ".babelrc" => &BABEL, + "babel.config.js" => &BABEL, + "gulpfile.js" => &GULP, + "gruntfile.js" => &GRUNT, + "capacitor.config.json" => &CAPACITOR, + "ionic.config.json" => &IONIC, + "angular.json" => &ANGULAR, + ".storybook" => &STORYBOOK, + "storybook.config.js" => &STORYBOOK, + "cypress.config.js" => &CYPRESS, + "playwright.config.js" => &PLAYWRIGHT, + "puppeteer.config.js" => &PUPPETEER, + "wrangler.toml" => &WRANGLER, + "firebase.json" => &FIREBASE, + "supabase" => &SUPABASE, + "terraform" => &TERRAFORM, + "kubernetes" => &KUBERNETES, + ".gitpod.yml" => &GITPOD, + ".devcontainer" => &VSCODE, + "travis.yml" => &TRAVIS, + "appveyor.yml" => &APPVEYOR, + ".circleci" => &CIRCLECI, + "renovate.json" => &RENOVATE, + "dependabot.yml" => &DEPENDABOT, + "lerna.json" => &LERNA, + "nx.json" => &NX, + _ => return None, + }) +} + +/// A lower-case dotted suffix's badge (`fileExtensions`), `d.ts` as well as `ts`. +pub(super) fn by_extension(key: &str) -> Option<&'static Icon> { + Some(match key { + "spec.ts" => &TEST_TS, + "test.ts" => &TEST_TS, + "spec.tsx" => &TEST_JSX, + "test.tsx" => &TEST_JSX, + "spec.js" => &TEST_JS, + "test.js" => &TEST_JS, + "spec.jsx" => &TEST_JSX, + "test.jsx" => &TEST_JSX, + "js.map" => &JAVASCRIPT_MAP, + "d.ts" => &TYPESCRIPT_DEF, + "ts" => &TYPESCRIPT, + "tsx" => &REACT_TS, + "js" => &JAVASCRIPT, + "jsx" => &REACT, + "mjs" => &JAVASCRIPT, + "cjs" => &JAVASCRIPT, + "html" => &HTML, + "htm" => &HTML, + "css" => &CSS, + "scss" => &SASS, + "sass" => &SASS, + "less" => &LESS, + "styl" => &STYLUS, + "json" => &JSON, + "jsonc" => &JSON, + "xml" => &XML, + "yml" => &YAML, + "yaml" => &YAML, + "toml" => &TOML, + "hjson" => &HJSON, + "md" => &MARKDOWN, + "mdx" => &MDX, + "tex" => &TEX, + "py" => &PYTHON, + "pyx" => &PYTHON, + "pyw" => &PYTHON, + "rs" => &RUST, + "go" => &GO, + "java" => &JAVA, + "kt" => &KOTLIN, + "scala" => &SCALA, + "php" => &PHP, + "rb" => &RUBY, + "cs" => &CSHARP, + "vb" => &VISUALSTUDIO, + "cpp" => &CPP, + "cc" => &CPP, + "cxx" => &CPP, + "c" => &C, + "h" => &H, + "hpp" => &HPP, + "swift" => &SWIFT, + "m" => &OBJECTIVE_C, + "mm" => &OBJECTIVE_CPP, + "dart" => &DART, + "lua" => &LUA, + "pl" => &PERL, + "r" => &R, + "jl" => &JULIA, + "hs" => &HASKELL, + "elm" => &ELM, + "ml" => &OCAML, + "clj" => &CLOJURE, + "cljs" => &CLOJURE, + "erl" => &ERLANG, + "ex" => &ELIXIR, + "exs" => &ELIXIR, + "nim" => &NIM, + "zig" => &ZIG, + "v" => &VLANG, + "odin" => &ODIN, + "gleam" => &GLEAM, + "grain" => &GRAIN, + "roc" => &ROCKET, + "fs" => &FSHARP, + "sh" => &CONSOLE, + "bash" => &CONSOLE, + "zsh" => &CONSOLE, + "fish" => &CONSOLE, + "ps1" => &POWERSHELL, + "cfg" => &SETTINGS, + "ini" => &SETTINGS, + "conf" => &SETTINGS, + "properties" => &SETTINGS, + "svg" => &SVG, + "png" => &IMAGE, + "jpg" => &IMAGE, + "jpeg" => &IMAGE, + "gif" => &IMAGE, + "webp" => &IMAGE, + "bmp" => &IMAGE, + "ico" => &FAVICON, + "mp4" => &VIDEO, + "mov" => &VIDEO, + "avi" => &VIDEO, + "webm" => &VIDEO, + "mp3" => &AUDIO, + "wav" => &AUDIO, + "flac" => &AUDIO, + "zip" => &ZIP, + "tar" => &ZIP, + "gz" => &ZIP, + "rar" => &ZIP, + "7z" => &ZIP, + "pdf" => &PDF, + "doc" => &WORD, + "docx" => &WORD, + "ppt" => &POWERPOINT, + "pptx" => &POWERPOINT, + "xls" => &DOCUMENT, + "xlsx" => &DOCUMENT, + "sql" => &DATABASE, + "db" => &DATABASE, + "sqlite" => &DATABASE, + "env" => &TUNE, + "log" => &LOG, + "lock" => &LOCK, + "key" => &KEY, + "pem" => &CERTIFICATE, + "crt" => &CERTIFICATE, + "proto" => &PROTO, + "graphql" => &GRAPHQL, + "gql" => &GRAPHQL, + "wasm" => &WEBASSEMBLY, + "dockerfile" => &DOCKER, + _ => return None, + }) +} + +/// A lower-case folder name's closed and open icons (`folderNames`). +pub(super) fn by_folder_name(key: &str) -> Option<(&'static Icon, &'static Icon)> { + Some(match key { + "src" => (&FOLDER_SRC, &FOLDER_SRC_OPEN), + "source" => (&FOLDER_SRC, &FOLDER_SRC_OPEN), + "lib" => (&FOLDER_LIB, &FOLDER_LIB_OPEN), + "libs" => (&FOLDER_LIB, &FOLDER_LIB_OPEN), + "test" => (&FOLDER_TEST, &FOLDER_TEST_OPEN), + "tests" => (&FOLDER_TEST, &FOLDER_TEST_OPEN), + "testing" => (&FOLDER_TEST, &FOLDER_TEST_OPEN), + "spec" => (&FOLDER_TEST, &FOLDER_TEST_OPEN), + "specs" => (&FOLDER_TEST, &FOLDER_TEST_OPEN), + "__tests__" => (&FOLDER_TEST, &FOLDER_TEST_OPEN), + "e2e" => (&FOLDER_TEST, &FOLDER_TEST_OPEN), + "integration" => (&FOLDER_TEST, &FOLDER_TEST_OPEN), + "unit" => (&FOLDER_TEST, &FOLDER_TEST_OPEN), + "cypress" => (&FOLDER_CYPRESS, &FOLDER_CYPRESS_OPEN), + "node_modules" => (&FOLDER_NODE, &FOLDER_NODE_OPEN), + "vendor" => (&FOLDER_PACKAGES, &FOLDER_PACKAGES_OPEN), + "packages" => (&FOLDER_PACKAGES, &FOLDER_PACKAGES_OPEN), + "deps" => (&FOLDER_PACKAGES, &FOLDER_PACKAGES_OPEN), + "build" => (&FOLDER_BUILDKITE, &FOLDER_BUILDKITE_OPEN), + "dist" => (&FOLDER_DIST, &FOLDER_DIST_OPEN), + "out" => (&FOLDER_DIST, &FOLDER_DIST_OPEN), + "output" => (&FOLDER_DIST, &FOLDER_DIST_OPEN), + "target" => (&FOLDER_TARGET, &FOLDER_TARGET_OPEN), + "config" => (&FOLDER_CONFIG, &FOLDER_CONFIG_OPEN), + "configs" => (&FOLDER_CONFIG, &FOLDER_CONFIG_OPEN), + "configuration" => (&FOLDER_CONFIG, &FOLDER_CONFIG_OPEN), + "settings" => (&FOLDER_CONFIG, &FOLDER_CONFIG_OPEN), + "env" => (&FOLDER_ENVIRONMENT, &FOLDER_ENVIRONMENT_OPEN), + "environments" => (&FOLDER_ENVIRONMENT, &FOLDER_ENVIRONMENT_OPEN), + "docker" => (&FOLDER_DOCKER, &FOLDER_DOCKER_OPEN), + "dockerfiles" => (&FOLDER_DOCKER, &FOLDER_DOCKER_OPEN), + "containers" => (&FOLDER_DOCKER, &FOLDER_DOCKER_OPEN), + "docs" => (&FOLDER_DOCS, &FOLDER_DOCS_OPEN), + "doc" => (&FOLDER_DOCS, &FOLDER_DOCS_OPEN), + "documentation" => (&FOLDER_DOCS, &FOLDER_DOCS_OPEN), + "readme" => (&FOLDER_DOCS, &FOLDER_DOCS_OPEN), + "public" => (&FOLDER_PUBLIC, &FOLDER_PUBLIC_OPEN), + "static" => (&FOLDER_PUBLIC, &FOLDER_PUBLIC_OPEN), + "assets" => (&FOLDER_IMAGES, &FOLDER_IMAGES_OPEN), + "images" => (&FOLDER_IMAGES, &FOLDER_IMAGES_OPEN), + "img" => (&FOLDER_IMAGES, &FOLDER_IMAGES_OPEN), + "icons" => (&FOLDER_IMAGES, &FOLDER_IMAGES_OPEN), + "media" => (&FOLDER_IMAGES, &FOLDER_IMAGES_OPEN), + "fonts" => (&FOLDER_FONT, &FOLDER_FONT_OPEN), + "styles" => (&FOLDER_CSS, &FOLDER_CSS_OPEN), + "stylesheets" => (&FOLDER_CSS, &FOLDER_CSS_OPEN), + "css" => (&FOLDER_CSS, &FOLDER_CSS_OPEN), + "sass" => (&FOLDER_SASS, &FOLDER_SASS_OPEN), + "scss" => (&FOLDER_SASS, &FOLDER_SASS_OPEN), + "less" => (&FOLDER_LESS, &FOLDER_LESS_OPEN), + "scripts" => (&FOLDER_SCRIPTS, &FOLDER_SCRIPTS_OPEN), + "script" => (&FOLDER_SCRIPTS, &FOLDER_SCRIPTS_OPEN), + "tools" => (&FOLDER_TOOLS, &FOLDER_TOOLS_OPEN), + "utils" => (&FOLDER_UTILS, &FOLDER_UTILS_OPEN), + "utilities" => (&FOLDER_UTILS, &FOLDER_UTILS_OPEN), + "helpers" => (&FOLDER_HELPER, &FOLDER_HELPER_OPEN), + "components" => (&FOLDER_COMPONENTS, &FOLDER_COMPONENTS_OPEN), + "component" => (&FOLDER_COMPONENTS, &FOLDER_COMPONENTS_OPEN), + "views" => (&FOLDER_VIEWS, &FOLDER_VIEWS_OPEN), + "view" => (&FOLDER_VIEWS, &FOLDER_VIEWS_OPEN), + "layouts" => (&FOLDER_LAYOUT, &FOLDER_LAYOUT_OPEN), + "layout" => (&FOLDER_LAYOUT, &FOLDER_LAYOUT_OPEN), + "templates" => (&FOLDER_TEMPLATE, &FOLDER_TEMPLATE_OPEN), + "template" => (&FOLDER_TEMPLATE, &FOLDER_TEMPLATE_OPEN), + "hooks" => (&FOLDER_HOOK, &FOLDER_HOOK_OPEN), + "hook" => (&FOLDER_HOOK, &FOLDER_HOOK_OPEN), + "store" => (&FOLDER_STORE, &FOLDER_STORE_OPEN), + "stores" => (&FOLDER_STORE, &FOLDER_STORE_OPEN), + "state" => (&FOLDER_NGRX_STORE, &FOLDER_NGRX_STORE_OPEN), + "reducers" => (&FOLDER_REDUX_REDUCER, &FOLDER_REDUX_REDUCER_OPEN), + "reducer" => (&FOLDER_REDUX_REDUCER, &FOLDER_REDUX_REDUCER_OPEN), + "services" => (&FOLDER_API, &FOLDER_API_OPEN), + "service" => (&FOLDER_API, &FOLDER_API_OPEN), + "api" => (&FOLDER_API, &FOLDER_API_OPEN), + "apis" => (&FOLDER_API, &FOLDER_API_OPEN), + "routes" => (&FOLDER_ROUTES, &FOLDER_ROUTES_OPEN), + "route" => (&FOLDER_ROUTES, &FOLDER_ROUTES_OPEN), + "routing" => (&FOLDER_ROUTES, &FOLDER_ROUTES_OPEN), + "middleware" => (&FOLDER_MIDDLEWARE, &FOLDER_MIDDLEWARE_OPEN), + "middlewares" => (&FOLDER_MIDDLEWARE, &FOLDER_MIDDLEWARE_OPEN), + "controllers" => (&FOLDER_CONTROLLER, &FOLDER_CONTROLLER_OPEN), + "controller" => (&FOLDER_CONTROLLER, &FOLDER_CONTROLLER_OPEN), + "models" => (&FOLDER_DATABASE, &FOLDER_DATABASE_OPEN), + "model" => (&FOLDER_DATABASE, &FOLDER_DATABASE_OPEN), + "schemas" => (&FOLDER_DATABASE, &FOLDER_DATABASE_OPEN), + "schema" => (&FOLDER_DATABASE, &FOLDER_DATABASE_OPEN), + "migrations" => (&FOLDER_DATABASE, &FOLDER_DATABASE_OPEN), + "migration" => (&FOLDER_DATABASE, &FOLDER_DATABASE_OPEN), + "seeders" => (&FOLDER_SEEDERS, &FOLDER_SEEDERS_OPEN), + "seeder" => (&FOLDER_SEEDERS, &FOLDER_SEEDERS_OPEN), + "types" => (&FOLDER_TYPESCRIPT, &FOLDER_TYPESCRIPT_OPEN), + "typing" => (&FOLDER_TYPESCRIPT, &FOLDER_TYPESCRIPT_OPEN), + "typings" => (&FOLDER_TYPESCRIPT, &FOLDER_TYPESCRIPT_OPEN), + "@types" => (&FOLDER_TYPESCRIPT, &FOLDER_TYPESCRIPT_OPEN), + "interfaces" => (&FOLDER_INTERFACE, &FOLDER_INTERFACE_OPEN), + "interface" => (&FOLDER_INTERFACE, &FOLDER_INTERFACE_OPEN), + "android" => (&FOLDER_ANDROID, &FOLDER_ANDROID_OPEN), + "ios" => (&FOLDER_IOS, &FOLDER_IOS_OPEN), + "mobile" => (&FOLDER_MOBILE, &FOLDER_MOBILE_OPEN), + "flutter" => (&FOLDER_FLUTTER, &FOLDER_FLUTTER_OPEN), + "kubernetes" => (&FOLDER_KUBERNETES, &FOLDER_KUBERNETES_OPEN), + "k8s" => (&FOLDER_KUBERNETES, &FOLDER_KUBERNETES_OPEN), + "terraform" => (&FOLDER_TERRAFORM, &FOLDER_TERRAFORM_OPEN), + "aws" => (&FOLDER_AWS, &FOLDER_AWS_OPEN), + "azure" => (&FOLDER_AZURE_PIPELINES, &FOLDER_AZURE_PIPELINES_OPEN), + "firebase" => (&FOLDER_FIREBASE, &FOLDER_FIREBASE_OPEN), + "supabase" => (&FOLDER_SUPABASE, &FOLDER_SUPABASE_OPEN), + "vercel" => (&FOLDER_VERCEL, &FOLDER_VERCEL_OPEN), + "netlify" => (&FOLDER_NETLIFY, &FOLDER_NETLIFY_OPEN), + ".github" => (&FOLDER_GITHUB, &FOLDER_GITHUB_OPEN), + ".gitlab" => (&FOLDER_GITLAB, &FOLDER_GITLAB_OPEN), + ".circleci" => (&FOLDER_CIRCLECI, &FOLDER_CIRCLECI_OPEN), + "ci" => (&FOLDER_CI, &FOLDER_CI_OPEN), + ".ci" => (&FOLDER_CI, &FOLDER_CI_OPEN), + "workflows" => (&FOLDER_GH_WORKFLOWS, &FOLDER_GH_WORKFLOWS_OPEN), + ".git" => (&FOLDER_GIT, &FOLDER_GIT_OPEN), + ".vscode" => (&FOLDER_VSCODE, &FOLDER_VSCODE_OPEN), + ".idea" => (&FOLDER_INTELLIJ, &FOLDER_INTELLIJ_OPEN), + ".cursor" => (&FOLDER_CURSOR, &FOLDER_CURSOR_OPEN), + ".devcontainer" => (&FOLDER_CONTAINER, &FOLDER_CONTAINER_OPEN), + ".storybook" => (&FOLDER_STORYBOOK, &FOLDER_STORYBOOK_OPEN), + "i18n" => (&FOLDER_I18N, &FOLDER_I18N_OPEN), + "locales" => (&FOLDER_I18N, &FOLDER_I18N_OPEN), + "locale" => (&FOLDER_I18N, &FOLDER_I18N_OPEN), + "lang" => (&FOLDER_I18N, &FOLDER_I18N_OPEN), + "languages" => (&FOLDER_I18N, &FOLDER_I18N_OPEN), + "temp" => (&FOLDER_TEMP, &FOLDER_TEMP_OPEN), + "tmp" => (&FOLDER_TEMP, &FOLDER_TEMP_OPEN), + "logs" => (&FOLDER_LOG, &FOLDER_LOG_OPEN), + "log" => (&FOLDER_LOG, &FOLDER_LOG_OPEN), + "backup" => (&FOLDER_BACKUP, &FOLDER_BACKUP_OPEN), + "backups" => (&FOLDER_BACKUP, &FOLDER_BACKUP_OPEN), + "examples" => (&FOLDER_EXAMPLES, &FOLDER_EXAMPLES_OPEN), + "example" => (&FOLDER_EXAMPLES, &FOLDER_EXAMPLES_OPEN), + "demo" => (&FOLDER_EXAMPLES, &FOLDER_EXAMPLES_OPEN), + "demos" => (&FOLDER_EXAMPLES, &FOLDER_EXAMPLES_OPEN), + "samples" => (&FOLDER_EXAMPLES, &FOLDER_EXAMPLES_OPEN), + "sample" => (&FOLDER_EXAMPLES, &FOLDER_EXAMPLES_OPEN), + "fixtures" => (&FOLDER_TEST, &FOLDER_TEST_OPEN), + "mocks" => (&FOLDER_MOCK, &FOLDER_MOCK_OPEN), + "mock" => (&FOLDER_MOCK, &FOLDER_MOCK_OPEN), + "data" => (&FOLDER_DATABASE, &FOLDER_DATABASE_OPEN), + "database" => (&FOLDER_DATABASE, &FOLDER_DATABASE_OPEN), + "db" => (&FOLDER_DATABASE, &FOLDER_DATABASE_OPEN), + "sql" => (&FOLDER_DATABASE, &FOLDER_DATABASE_OPEN), + "prisma" => (&FOLDER_PRISMA, &FOLDER_PRISMA_OPEN), + "drizzle" => (&FOLDER_DRIZZLE, &FOLDER_DRIZZLE_OPEN), + "security" => (&FOLDER_SECURE, &FOLDER_SECURE_OPEN), + "auth" => (&FOLDER_SECURE, &FOLDER_SECURE_OPEN), + "authentication" => (&FOLDER_SECURE, &FOLDER_SECURE_OPEN), + "authorization" => (&FOLDER_SECURE, &FOLDER_SECURE_OPEN), + "keys" => (&FOLDER_KEYS, &FOLDER_KEYS_OPEN), + "certs" => (&FOLDER_KEYS, &FOLDER_KEYS_OPEN), + "certificates" => (&FOLDER_KEYS, &FOLDER_KEYS_OPEN), + "content" => (&FOLDER_CONTENT, &FOLDER_CONTENT_OPEN), + "posts" => (&FOLDER_CONTENT, &FOLDER_CONTENT_OPEN), + "articles" => (&FOLDER_CONTENT, &FOLDER_CONTENT_OPEN), + "blog" => (&FOLDER_CONTENT, &FOLDER_CONTENT_OPEN), + "functions" => (&FOLDER_FUNCTIONS, &FOLDER_FUNCTIONS_OPEN), + "function" => (&FOLDER_FUNCTIONS, &FOLDER_FUNCTIONS_OPEN), + "lambda" => (&FOLDER_FUNCTIONS, &FOLDER_FUNCTIONS_OPEN), + "lambdas" => (&FOLDER_FUNCTIONS, &FOLDER_FUNCTIONS_OPEN), + "serverless" => (&FOLDER_SERVERLESS, &FOLDER_SERVERLESS_OPEN), + "jobs" => (&FOLDER_JOB, &FOLDER_JOB_OPEN), + "job" => (&FOLDER_JOB, &FOLDER_JOB_OPEN), + "tasks" => (&FOLDER_TASKS, &FOLDER_TASKS_OPEN), + "task" => (&FOLDER_TASKS, &FOLDER_TASKS_OPEN), + "cron" => (&FOLDER_TASKS, &FOLDER_TASKS_OPEN), + "queue" => (&FOLDER_QUEUE, &FOLDER_QUEUE_OPEN), + "queues" => (&FOLDER_QUEUE, &FOLDER_QUEUE_OPEN), + "desktop" => (&FOLDER_DESKTOP, &FOLDER_DESKTOP_OPEN), + "windows" => (&FOLDER_WINDOWS, &FOLDER_WINDOWS_OPEN), + "macos" => (&FOLDER_MACOS, &FOLDER_MACOS_OPEN), + "linux" => (&FOLDER_LINUX, &FOLDER_LINUX_OPEN), + _ => return None, + }) +} + +/// Every badge, for a gallery. +pub(super) static ALL: &[&Icon] = &[ + &ANGULAR, + &APPVEYOR, + &ASTRO_CONFIG, + &AUDIO, + &AUTHORS, + &BABEL, + &BROWSERLIST, + &BUN, + &C, + &CAPACITOR, + &CERTIFICATE, + &CHANGELOG, + &CIRCLECI, + &CLOJURE, + &CMAKE, + &CONDUCT, + &CONSOLE, + &CONTRIBUTING, + &CPP, + &CREDITS, + &CSHARP, + &CSS, + &CYPRESS, + &DART, + &DATABASE, + &DENO, + &DEPENDABOT, + &DOCKER, + &DOCUMENT, + &EDITORCONFIG, + &ELIXIR, + &ELM, + &ERLANG, + &ESLINT, + &FAVICON, + &FIREBASE, + &FOLDER, + &FOLDER_ANDROID, + &FOLDER_ANDROID_OPEN, + &FOLDER_API, + &FOLDER_API_OPEN, + &FOLDER_AWS, + &FOLDER_AWS_OPEN, + &FOLDER_AZURE_PIPELINES, + &FOLDER_AZURE_PIPELINES_OPEN, + &FOLDER_BACKUP, + &FOLDER_BACKUP_OPEN, + &FOLDER_BUILDKITE, + &FOLDER_BUILDKITE_OPEN, + &FOLDER_CI, + &FOLDER_CIRCLECI, + &FOLDER_CIRCLECI_OPEN, + &FOLDER_CI_OPEN, + &FOLDER_COMPONENTS, + &FOLDER_COMPONENTS_OPEN, + &FOLDER_CONFIG, + &FOLDER_CONFIG_OPEN, + &FOLDER_CONTAINER, + &FOLDER_CONTAINER_OPEN, + &FOLDER_CONTENT, + &FOLDER_CONTENT_OPEN, + &FOLDER_CONTROLLER, + &FOLDER_CONTROLLER_OPEN, + &FOLDER_CSS, + &FOLDER_CSS_OPEN, + &FOLDER_CURSOR, + &FOLDER_CURSOR_OPEN, + &FOLDER_CYPRESS, + &FOLDER_CYPRESS_OPEN, + &FOLDER_DATABASE, + &FOLDER_DATABASE_OPEN, + &FOLDER_DESKTOP, + &FOLDER_DESKTOP_OPEN, + &FOLDER_DIST, + &FOLDER_DIST_OPEN, + &FOLDER_DOCKER, + &FOLDER_DOCKER_OPEN, + &FOLDER_DOCS, + &FOLDER_DOCS_OPEN, + &FOLDER_DRIZZLE, + &FOLDER_DRIZZLE_OPEN, + &FOLDER_ENVIRONMENT, + &FOLDER_ENVIRONMENT_OPEN, + &FOLDER_EXAMPLES, + &FOLDER_EXAMPLES_OPEN, + &FOLDER_FIREBASE, + &FOLDER_FIREBASE_OPEN, + &FOLDER_FLUTTER, + &FOLDER_FLUTTER_OPEN, + &FOLDER_FONT, + &FOLDER_FONT_OPEN, + &FOLDER_FUNCTIONS, + &FOLDER_FUNCTIONS_OPEN, + &FOLDER_GH_WORKFLOWS, + &FOLDER_GH_WORKFLOWS_OPEN, + &FOLDER_GIT, + &FOLDER_GITHUB, + &FOLDER_GITHUB_OPEN, + &FOLDER_GITLAB, + &FOLDER_GITLAB_OPEN, + &FOLDER_GIT_OPEN, + &FOLDER_HELPER, + &FOLDER_HELPER_OPEN, + &FOLDER_HOOK, + &FOLDER_HOOK_OPEN, + &FOLDER_I18N, + &FOLDER_I18N_OPEN, + &FOLDER_IMAGES, + &FOLDER_IMAGES_OPEN, + &FOLDER_INTELLIJ, + &FOLDER_INTELLIJ_OPEN, + &FOLDER_INTERFACE, + &FOLDER_INTERFACE_OPEN, + &FOLDER_IOS, + &FOLDER_IOS_OPEN, + &FOLDER_JOB, + &FOLDER_JOB_OPEN, + &FOLDER_KEYS, + &FOLDER_KEYS_OPEN, + &FOLDER_KUBERNETES, + &FOLDER_KUBERNETES_OPEN, + &FOLDER_LAYOUT, + &FOLDER_LAYOUT_OPEN, + &FOLDER_LESS, + &FOLDER_LESS_OPEN, + &FOLDER_LIB, + &FOLDER_LIB_OPEN, + &FOLDER_LINUX, + &FOLDER_LINUX_OPEN, + &FOLDER_LOG, + &FOLDER_LOG_OPEN, + &FOLDER_MACOS, + &FOLDER_MACOS_OPEN, + &FOLDER_MIDDLEWARE, + &FOLDER_MIDDLEWARE_OPEN, + &FOLDER_MOBILE, + &FOLDER_MOBILE_OPEN, + &FOLDER_MOCK, + &FOLDER_MOCK_OPEN, + &FOLDER_NETLIFY, + &FOLDER_NETLIFY_OPEN, + &FOLDER_NGRX_STORE, + &FOLDER_NGRX_STORE_OPEN, + &FOLDER_NODE, + &FOLDER_NODE_OPEN, + &FOLDER_OPEN, + &FOLDER_PACKAGES, + &FOLDER_PACKAGES_OPEN, + &FOLDER_PRISMA, + &FOLDER_PRISMA_OPEN, + &FOLDER_PUBLIC, + &FOLDER_PUBLIC_OPEN, + &FOLDER_QUEUE, + &FOLDER_QUEUE_OPEN, + &FOLDER_REDUX_REDUCER, + &FOLDER_REDUX_REDUCER_OPEN, + &FOLDER_ROUTES, + &FOLDER_ROUTES_OPEN, + &FOLDER_SASS, + &FOLDER_SASS_OPEN, + &FOLDER_SCRIPTS, + &FOLDER_SCRIPTS_OPEN, + &FOLDER_SECURE, + &FOLDER_SECURE_OPEN, + &FOLDER_SEEDERS, + &FOLDER_SEEDERS_OPEN, + &FOLDER_SERVERLESS, + &FOLDER_SERVERLESS_OPEN, + &FOLDER_SRC, + &FOLDER_SRC_OPEN, + &FOLDER_STORE, + &FOLDER_STORE_OPEN, + &FOLDER_STORYBOOK, + &FOLDER_STORYBOOK_OPEN, + &FOLDER_SUPABASE, + &FOLDER_SUPABASE_OPEN, + &FOLDER_TARGET, + &FOLDER_TARGET_OPEN, + &FOLDER_TASKS, + &FOLDER_TASKS_OPEN, + &FOLDER_TEMP, + &FOLDER_TEMPLATE, + &FOLDER_TEMPLATE_OPEN, + &FOLDER_TEMP_OPEN, + &FOLDER_TERRAFORM, + &FOLDER_TERRAFORM_OPEN, + &FOLDER_TEST, + &FOLDER_TEST_OPEN, + &FOLDER_TOOLS, + &FOLDER_TOOLS_OPEN, + &FOLDER_TYPESCRIPT, + &FOLDER_TYPESCRIPT_OPEN, + &FOLDER_UTILS, + &FOLDER_UTILS_OPEN, + &FOLDER_VERCEL, + &FOLDER_VERCEL_OPEN, + &FOLDER_VIEWS, + &FOLDER_VIEWS_OPEN, + &FOLDER_VSCODE, + &FOLDER_VSCODE_OPEN, + &FOLDER_WINDOWS, + &FOLDER_WINDOWS_OPEN, + &FSHARP, + &GATSBY, + &GEMFILE, + &GIT, + &GITPOD, + &GLEAM, + &GO, + &GO_MOD, + &GRADLE, + &GRAIN, + &GRAPHQL, + &GRUNT, + &GULP, + &H, + &HASKELL, + &HJSON, + &HPP, + &HTML, + &IMAGE, + &INSTALLATION, + &IONIC, + &JAVA, + &JAVASCRIPT, + &JAVASCRIPT_MAP, + &JEST, + &JSCONFIG, + &JSON, + &JULIA, + &KEY, + &KOTLIN, + &KUBERNETES, + &LERNA, + &LESS, + &LOCK, + &LOG, + &LUA, + &MAKEFILE, + &MARKDOWN, + &MAVEN, + &MDX, + &NETLIFY, + &NEXT, + &NIM, + &NODEJS, + &NUXT, + &NX, + &OBJECTIVE_C, + &OBJECTIVE_CPP, + &OCAML, + &ODIN, + &PDF, + &PERL, + &PHP, + &PLAYWRIGHT, + &PNPM, + &POETRY, + &POWERPOINT, + &POWERSHELL, + &PRETTIER, + &PRISMA, + &PROTO, + &PUPPETEER, + &PYTHON, + &R, + &REACT, + &REACT_TS, + &README, + &REMIX, + &RENOVATE, + &ROBOTS, + &ROCKET, + &ROLLUP, + &RUBY, + &RUST, + &SASS, + &SCALA, + &SETTINGS, + &STORYBOOK, + &STYLUS, + &SUPABASE, + &SVELTE, + &SVG, + &SWIFT, + &TAILWINDCSS, + &TERRAFORM, + &TEST_JS, + &TEST_JSX, + &TEST_TS, + &TEX, + &TOML, + &TRAVIS, + &TSCONFIG, + &TUNE, + &TURBOREPO, + &TYPESCRIPT, + &TYPESCRIPT_DEF, + &VERCEL, + &VIDEO, + &VISUALSTUDIO, + &VITE, + &VITEST, + &VLANG, + &VSCODE, + &WEBASSEMBLY, + &WEBPACK, + &WORD, + &WRANGLER, + &XML, + &YAML, + &YARN, + &ZIG, + &ZIP, +]; diff --git a/app/vendor/rune/themes/opencode/src/icons.rs b/app/vendor/rune/themes/opencode/src/icons.rs new file mode 100644 index 0000000..538383b --- /dev/null +++ b/app/vendor/rune/themes/opencode/src/icons.rs @@ -0,0 +1,351 @@ +//! Generated by tools/icons.py from @opencode/ui's icon catalog. Do not edit. +#![allow(dead_code)] +use rune::Icon; +pub static ALIGN_RIGHT: Icon = Icon { name: "align-right", view: 20.0, body: r#"<path d="M12.292 6.04167L16.2503 9.99998L12.292 13.9583M2.91699 9.99998H15.6253M17.0837 3.75V16.25" stroke="currentColor" stroke-linecap="square"/>"# }; +pub static ARROW_UP: Icon = Icon { name: "arrow-up", view: 16.0, body: r#"<path d="M8 12.5V3.5M11.5 7L8 3.5L4.5 7" stroke-linecap="round" stroke-linejoin="round" stroke="currentColor"/>"# }; +pub static ARROW_LEFT: Icon = Icon { name: "arrow-left", view: 16.0, body: r#"<g transform="rotate(270 8 8)"><path d="M8 12.5V3.5M11.5 7L8 3.5L4.5 7" stroke-linecap="round" stroke-linejoin="round" stroke="currentColor"/></g>"# }; +pub static ARROW_RIGHT: Icon = Icon { name: "arrow-right", view: 16.0, body: r#"<g transform="rotate(90 8 8)"><path d="M8 12.5V3.5M11.5 7L8 3.5L4.5 7" stroke-linecap="round" stroke-linejoin="round" stroke="currentColor"/></g>"# }; +pub static ARCHIVE: Icon = Icon { name: "archive", view: 16.0, body: r#"<path d="M2.5 5.5V13.5H13.5V5.5M2.5 5.5H1.5V2.5H14.5V5.5H13.5M2.5 5.5H13.5M6.5 7.5H9.5" stroke-linecap="round" stroke-linejoin="round" stroke="currentColor"/>"# }; +pub static PROMPT: Icon = Icon { name: "prompt", view: 20.0, body: r#"<path d="M14.5841 12.0807H17.9193V2.91406H5.6276V6.2474M14.5859 6.2474H2.08594V15.4141H5.0026V17.4974L8.7526 15.4141H14.5859V6.2474Z" stroke="currentColor" stroke-linecap="square"/>"# }; +pub static BRAIN: Icon = Icon { name: "brain", view: 20.0, body: r#"<path d="M13.332 8.7487C11.4911 8.7487 9.9987 7.25631 9.9987 5.41536M6.66536 11.2487C8.50631 11.2487 9.9987 12.7411 9.9987 14.582M9.9987 2.78209L9.9987 17.0658M16.004 15.0475C17.1255 14.5876 17.9154 13.4849 17.9154 12.1978C17.9154 11.3363 17.5615 10.5575 16.9913 9.9987C17.5615 9.43991 17.9154 8.66108 17.9154 7.79962C17.9154 6.21199 16.7136 4.90504 15.1702 4.73878C14.7858 3.21216 13.4039 2.08203 11.758 2.08203C11.1171 2.08203 10.5162 2.25337 9.9987 2.55275C9.48117 2.25337 8.88032 2.08203 8.23944 2.08203C6.59353 2.08203 5.21157 3.21216 4.82722 4.73878C3.28377 4.90504 2.08203 6.21199 2.08203 7.79962C2.08203 8.66108 2.43585 9.43991 3.00609 9.9987C2.43585 10.5575 2.08203 11.3363 2.08203 12.1978C2.08203 13.4849 2.87191 14.5876 3.99339 15.0475C4.46688 16.7033 5.9917 17.9154 7.79962 17.9154C8.61335 17.9154 9.36972 17.6698 9.9987 17.2488C10.6277 17.6698 11.384 17.9154 12.1978 17.9154C14.0057 17.9154 15.5305 16.7033 16.004 15.0475Z" stroke="currentColor"/>"# }; +pub static FORK: Icon = Icon { name: "fork", view: 16.0, body: r#"<path d="M8.39211 13.5L8.39211 8.10506C8.39211 8.03787 8.36505 7.9735 8.31705 7.92648L2.77783 2.50007M6.77783 2.50007L2.77783 2.50007L2.77783 6.50007M13.5002 6.50007L13.5002 2.50007L9.5002 2.50007M13.5002 2.50007L10 6" stroke-linecap="round" stroke-linejoin="round" stroke="currentColor"/>"# }; +pub static WORKSPACE_ISOLATED: Icon = Icon { name: "workspace-isolated", view: 16.0, body: r#"<path d="M10.5 10.5V5.5H5.5V10.5H10.5Z" fill="currentColor"/><rect x="2.5" y="2.5" width="11" height="11" stroke="currentColor"/>"# }; +pub static BULLET_LIST: Icon = Icon { name: "bullet-list", view: 16.0, body: r#"<path d="M8.5 4.5H14.5M8.5 11.5H14.5M1.5 2.5V6.5H5.5V2.5H1.5ZM1.5 9.5V13.5H5.5V9.5H1.5Z" stroke-linecap="round" stroke-linejoin="round" stroke="currentColor"/>"# }; +pub static CHEVRON_DOWN: Icon = Icon { name: "chevron-down", view: 16.0, body: r#"<g transform="rotate(180 8 8)"><path d="M4.5 9.5L8 6.5L11.5 9.5" stroke-linecap="round" stroke-linejoin="round" stroke="currentColor"/></g>"# }; +pub static CHEVRON_LEFT: Icon = Icon { name: "chevron-left", view: 16.0, body: r#"<g transform="rotate(270 8 8)"><path d="M4.5 9.5L8 6.5L11.5 9.5" stroke-linecap="round" stroke-linejoin="round" stroke="currentColor"/></g>"# }; +pub static CHEVRON_RIGHT: Icon = Icon { name: "chevron-right", view: 16.0, body: r#"<g transform="rotate(90 8 8)"><path d="M4.5 9.5L8 6.5L11.5 9.5" stroke-linecap="round" stroke-linejoin="round" stroke="currentColor"/></g>"# }; +pub static CHEVRON_GRABBER_VERTICAL: Icon = Icon { name: "chevron-grabber-vertical", view: 16.0, body: r#"<path d="M5 6L8 3.5L11 6M5 10L8 12.5L11 10" stroke-linecap="round" stroke-linejoin="round" stroke="currentColor"/>"# }; +pub static CHEVRON_DOUBLE_RIGHT: Icon = Icon { name: "chevron-double-right", view: 20.0, body: r#"<path d="M11.6654 13.3346L14.9987 10.0013L11.6654 6.66797M5.83203 13.3346L9.16536 10.0013L5.83203 6.66797" stroke="currentColor" stroke-linecap="square"/>"# }; +pub static CIRCLE_X: Icon = Icon { name: "circle-x", view: 20.0, body: r#"<path fill-rule="evenodd" clip-rule="evenodd" d="M1.6665 10.0003C1.6665 5.39795 5.39746 1.66699 9.99984 1.66699C14.6022 1.66699 18.3332 5.39795 18.3332 10.0003C18.3332 14.6027 14.6022 18.3337 9.99984 18.3337C5.39746 18.3337 1.6665 14.6027 1.6665 10.0003ZM7.49984 6.91107L6.91058 7.50033L9.41058 10.0003L6.91058 12.5003L7.49984 13.0896L9.99984 10.5896L12.4998 13.0896L13.0891 12.5003L10.5891 10.0003L13.0891 7.50033L12.4998 6.91107L9.99984 9.41107L7.49984 6.91107Z" fill="currentColor"/>"# }; +pub static CLOSE: Icon = Icon { name: "close", view: 16.0, body: r#"<path d="M4.5 11.5L8 8M8 8L11.5 4.5M8 8L4.5 4.5M8 8L11.5 11.5" stroke-linecap="round" stroke="currentColor"/>"# }; +pub static CHECKLIST: Icon = Icon { name: "checklist", view: 20.0, body: r#"<path d="M9.58342 13.7498H17.0834M9.58342 6.24984H17.0834M2.91675 6.6665L4.58341 7.9165L7.08341 4.1665M2.91675 14.1665L4.58341 15.4165L7.08341 11.6665" stroke="currentColor" stroke-linecap="square"/>"# }; +pub static TERMINAL: Icon = Icon { name: "terminal", view: 16.0, body: r#"<path d="M4.5 11.5L7.5 8.5L4.5 5.5M11.5 11.5H8.5" stroke-linecap="round" stroke-linejoin="round" stroke="currentColor"/><path d="M1.5 14.25V1.75C1.5 1.61193 1.61193 1.5 1.75 1.5H14.25C14.3881 1.5 14.5 1.61193 14.5 1.75V14.25C14.5 14.3881 14.3881 14.5 14.25 14.5H1.75C1.61193 14.5 1.5 14.3881 1.5 14.25Z" stroke-linecap="round" stroke="currentColor"/>"# }; +pub static TERMINAL_ACTIVE: Icon = Icon { name: "terminal-active", view: 20.0, body: r#"<path d="M2 18H18V2H2V18Z" fill="currentColor" fill-opacity="0.1"/> +<path d="M6.5 8L8.64286 10L6.5 12M10.9286 12H13.5M2 18H18V2H2V18Z" stroke="currentColor" stroke-linecap="square"/>"# }; +pub static REVIEW: Icon = Icon { name: "review", view: 16.0, body: r#"<path d="M4.5 6.5H8M8 6.5H11.5M8 6.5V3M8 6.5V10" stroke-linecap="round" stroke-linejoin="round" stroke="currentColor"/><path d="M4.5 12.5H11.5" stroke-linecap="round" stroke-linejoin="round" stroke="currentColor"/>"# }; +pub static REVIEW_ACTIVE: Icon = Icon { name: "review-active", view: 20.0, body: r#"<path d="M18 18V2L2 2L2 18H18Z" fill="currentColor" fill-opacity="0.1"/> +<path d="M7 14.5H13M7 7.99512H10.0049M10.0049 7.99512H13M10.0049 7.99512V5M10.0049 7.99512V11M18 18V2L2 2L2 18H18Z" stroke="currentColor"/>"# }; +pub static EXPAND: Icon = Icon { name: "expand", view: 16.0, body: r#"<path d="M10.5 4.5L8 2L5.5 4.5M10.5 11.5L8 14L5.5 11.5" stroke-linecap="round" stroke-linejoin="round" stroke="currentColor"/><path d="M2.5 8H13.5" stroke-linecap="round" stroke-linejoin="round" stroke="currentColor"/>"# }; +pub static COLLAPSE: Icon = Icon { name: "collapse", view: 16.0, body: r#"<path d="M5.5 2.5L8 5L10.5 2.5M5.5 13.5L8 11L10.5 13.5" stroke-linecap="round" stroke-linejoin="round" stroke="currentColor"/><path d="M2.5 8H13.5" stroke-linecap="round" stroke-linejoin="round" stroke="currentColor"/>"# }; +pub static CODE: Icon = Icon { name: "code", view: 16.0, body: r#"<path d="M4.5 4.5L1.5 8L4.5 11.5M11.5 4.5L14.5 8L11.5 11.5" stroke-linecap="round" stroke-linejoin="round" stroke="currentColor"/><path d="M6.5 13.5L9.5 2.5" stroke-linecap="round" stroke="currentColor"/>"# }; +pub static CODE_LINES: Icon = Icon { name: "code-lines", view: 20.0, body: r#"<path d="M2.08325 3.75H11.2499M14.5833 3.75H17.9166M2.08325 10L7.08325 10M10.4166 10L17.9166 10M2.08325 16.25L8.74992 16.25M12.0833 16.25L17.9166 16.25" stroke="currentColor" stroke-linecap="square" stroke-linejoin="round"/>"# }; +pub static CIRCLE_BAN_SIGN: Icon = Icon { name: "circle-ban-sign", view: 16.0, body: r#"<path d="M14.5 8C14.5 11.5899 11.5899 14.5 8 14.5C4.41015 14.5 1.5 11.5899 1.5 8C1.5 4.41015 4.41015 1.5 8 1.5C11.5899 1.5 14.5 4.41015 14.5 8Z" stroke="currentColor"/><path d="M3.5 12.5L12.5 3.5" stroke-linecap="round" stroke-linejoin="round" stroke="currentColor"/>"# }; +pub static CIRCLE_BAN_SIGN_BOLD: Icon = Icon { name: "circle-ban-sign-bold", view: 16.0, body: r#"<path d="M14.5 8C14.5 11.5899 11.5899 14.5 8 14.5C4.41015 14.5 1.5 11.5899 1.5 8C1.5 4.41015 4.41015 1.5 8 1.5C11.5899 1.5 14.5 4.41015 14.5 8Z" stroke="currentColor" stroke-width="1.5"/><path d="M3.5 12.5L12.5 3.5" stroke-linecap="round" stroke-linejoin="round" stroke="currentColor" stroke-width="1.5"/>"# }; +pub static EDIT_SMALL_2: Icon = Icon { name: "edit-small-2", view: 20.0, body: r#"<path d="M17.0834 17.0833V17.5833H17.5834V17.0833H17.0834ZM2.91675 17.0833H2.41675V17.5833H2.91675V17.0833ZM2.91675 2.91659V2.41659H2.41675V2.91659H2.91675ZM9.58341 3.41659H10.0834V2.41659H9.58341V2.91659V3.41659ZM17.5834 10.4166V9.91659H16.5834V10.4166H17.0834H17.5834ZM10.4167 7.08325L10.0632 6.7297L9.91675 6.87615V7.08325H10.4167ZM10.4167 9.58325H9.91675V10.0833H10.4167V9.58325ZM12.9167 9.58325V10.0833H13.1239L13.2703 9.93681L12.9167 9.58325ZM15.4167 2.08325L15.7703 1.7297L15.4167 1.37615L15.0632 1.7297L15.4167 2.08325ZM17.9167 4.58325L18.2703 4.93681L18.6239 4.58325L18.2703 4.2297L17.9167 4.58325ZM17.0834 17.0833V16.5833H2.91675V17.0833V17.5833H17.0834V17.0833ZM2.91675 17.0833H3.41675V2.91659H2.91675H2.41675V17.0833H2.91675ZM2.91675 2.91659V3.41659H9.58341V2.91659V2.41659H2.91675V2.91659ZM17.0834 10.4166H16.5834V17.0833H17.0834H17.5834V10.4166H17.0834ZM10.4167 7.08325H9.91675V9.58325H10.4167H10.9167V7.08325H10.4167ZM10.4167 9.58325V10.0833H12.9167V9.58325V9.08325H10.4167V9.58325ZM10.4167 7.08325L10.7703 7.43681L15.7703 2.43681L15.4167 2.08325L15.0632 1.7297L10.0632 6.7297L10.4167 7.08325ZM15.4167 2.08325L15.0632 2.43681L17.5632 4.93681L17.9167 4.58325L18.2703 4.2297L15.7703 1.7297L15.4167 2.08325ZM17.9167 4.58325L17.5632 4.2297L12.5632 9.2297L12.9167 9.58325L13.2703 9.93681L18.2703 4.93681L17.9167 4.58325Z" fill="currentColor"/>"# }; +pub static EYE: Icon = Icon { name: "eye", view: 16.0, body: r#"<path d="M1.5 8C2.5 6.5 4.5 4 8 4C11.5 4 13.5 6.5 14.5 8C13.5 9.5 11.5 12 8 12C4.5 12 2.5 9.5 1.5 8Z" stroke-linecap="round" stroke-linejoin="round" stroke="currentColor"/><path d="M9.5 8C9.5 8.82843 8.82843 9.5 8 9.5C7.17157 9.5 6.5 8.82843 6.5 8C6.5 7.17157 7.17157 6.5 8 6.5C8.82843 6.5 9.5 7.17157 9.5 8Z" fill="currentColor"/>"# }; +pub static ENTER: Icon = Icon { name: "enter", view: 16.0, body: r#"<path d="M2.5 9.5H12.5C13.0523 9.5 13.5 9.05228 13.5 8.5V5.5C13.5 4.94772 13.0523 4.5 12.5 4.5H8.5M5.5 12.5L2.5 9.5L5.5 6.5" stroke-linecap="round" stroke-linejoin="round" stroke="currentColor"/>"# }; +pub static FOLDER: Icon = Icon { name: "folder", view: 16.0, body: r#"<path d="M1.5 13.5V2.5H5.5L8.5 5.5H14.5V13.5H1.5Z" stroke-linecap="round" stroke-linejoin="round" stroke="currentColor"/>"# }; +pub static FILE_TREE_ACTIVE: Icon = Icon { name: "file-tree-active", view: 20.0, body: r#"<path d="M2 2L2 18H5L6.5 8.5H18V5H9.5L7.5 2H2Z" fill="currentColor" fill-opacity="0.1"/> +<path d="M5 18H18L19.5 8.5H18M5 18H2L2 2H7.5L9.5 5H18V8.5M5 18L6.5 8.5H18" stroke="currentColor" stroke-linecap="square"/>"# }; +pub static MAGNIFYING_GLASS: Icon = Icon { name: "magnifying-glass", view: 16.0, body: r#"<path d="M11.5 7C11.5 9.48528 9.48528 11.5 7 11.5C4.51472 11.5 2.5 9.48528 2.5 7C2.5 4.51472 4.51472 2.5 7 2.5C9.48528 2.5 11.5 4.51472 11.5 7Z" stroke="currentColor"/><path d="M13.5 13.5L10.5 10.5" stroke-linecap="round" stroke="currentColor"/>"# }; +pub static PLUS: Icon = Icon { name: "plus", view: 16.0, body: r#"<path d="M8 2.5V8M8 8V13.5M8 8H2.5M8 8H13.5" stroke-linecap="round" stroke-linejoin="round" stroke="currentColor"/>"# }; +pub static NEW_SESSION: Icon = Icon { name: "new-session", view: 20.0, body: r#"<path d="M12 2H2V18H18V8M6 11.3818V14H8.61818L18 4.61818L15.3818 2L6 11.3818Z" stroke="currentColor"/>"# }; +pub static NEW_SESSION_ACTIVE: Icon = Icon { name: "new-session-active", view: 20.0, body: r#"<path d="M6 11.3818V14H8.61818L18 4.61818L15.3818 2L6 11.3818Z" fill="currentColor" fill-opacity="0.1"/> +<path d="M12 2H2V18H18V8M6 11.3818V14H8.61818L18 4.61818L15.3818 2L6 11.3818Z" stroke="currentColor"/>"# }; +pub static PENCIL_LINE: Icon = Icon { name: "pencil-line", view: 20.0, body: r#"<path d="M9.58301 17.9166H17.9163M17.9163 5.83325L14.1663 2.08325L2.08301 14.1666V17.9166H5.83301L17.9163 5.83325Z" stroke="currentColor" stroke-linecap="square"/>"# }; +pub static MCP: Icon = Icon { name: "mcp", view: 20.0, body: r#"<g><path d="M0.972656 9.37176L9.5214 1.60019C10.7018 0.527151 12.6155 0.527151 13.7957 1.60019C14.9761 2.67321 14.9761 4.41295 13.7957 5.48599L7.3397 11.3552" stroke="currentColor" stroke-linecap="round"/><path d="M7.42871 11.2747L13.7957 5.48643C14.9761 4.41338 16.8898 4.41338 18.0702 5.48643L18.1147 5.52688C19.2951 6.59993 19.2951 8.33966 18.1147 9.4127L10.3831 16.4414C9.98966 16.7991 9.98966 17.379 10.3831 17.7366L11.9707 19.1799" stroke="currentColor" stroke-linecap="round"/><path d="M11.6587 3.54346L5.33619 9.29119C4.15584 10.3642 4.15584 12.1039 5.33619 13.177C6.51649 14.25 8.43019 14.25 9.61054 13.177L15.9331 7.42923" stroke="currentColor" stroke-linecap="round"/></g>"# }; +pub static GLASSES: Icon = Icon { name: "glasses", view: 20.0, body: r#"<path d="M0.416626 7.91667H1.66663M19.5833 7.91667H18.3333M11.866 7.57987C11.3165 7.26398 10.6793 7.08333 9.99996 7.08333C9.32061 7.08333 8.68344 7.26398 8.13389 7.57987M8.74996 10C8.74996 12.0711 7.07103 13.75 4.99996 13.75C2.92889 13.75 1.24996 12.0711 1.24996 10C1.24996 7.92893 2.92889 6.25 4.99996 6.25C7.07103 6.25 8.74996 7.92893 8.74996 10ZM18.75 10C18.75 12.0711 17.071 13.75 15 13.75C12.9289 13.75 11.25 12.0711 11.25 10C11.25 7.92893 12.9289 6.25 15 6.25C17.071 6.25 18.75 7.92893 18.75 10Z" stroke="currentColor" stroke-linecap="square"/>"# }; +pub static MAGNIFYING_GLASS_MENU: Icon = Icon { name: "magnifying-glass-menu", view: 20.0, body: r#"<path d="M2.08325 10.0002H4.58325M2.08325 5.41683H5.41659M2.08325 14.5835H5.41659M16.4583 13.9585L18.7499 16.2502M17.9166 10.0002C17.9166 12.9917 15.4915 15.4168 12.4999 15.4168C9.50838 15.4168 7.08325 12.9917 7.08325 10.0002C7.08325 7.00862 9.50838 4.5835 12.4999 4.5835C15.4915 4.5835 17.9166 7.00862 17.9166 10.0002Z" stroke="currentColor" stroke-linecap="square"/>"# }; +pub static TASK: Icon = Icon { name: "task", view: 20.0, body: r#"<path d="M9.99992 2.0835V17.9168M7.08325 3.75016H2.08325V16.2502H7.08325M12.9166 16.2502H17.9166V3.75016H12.9166" stroke="currentColor" stroke-linecap="square"/>"# }; +pub static STOP: Icon = Icon { name: "stop", view: 16.0, body: r#"<path d="M13 3H3V13H13V3Z" fill="currentColor"/>"# }; +pub static STATUS: Icon = Icon { name: "status", view: 20.0, body: r#"<path d="M2 10V18H18V10M2 10V2H18V10M2 10H18M5 6H9M5 14H9" stroke="currentColor"/>"# }; +pub static STATUS_ACTIVE: Icon = Icon { name: "status-active", view: 20.0, body: r#"<path d="M18 2H2V10H18V2Z" fill="currentColor" fill-opacity="0.1"/><path d="M2 18H18V10H2V18Z" fill="currentColor" fill-opacity="0.1"/><path d="M2 10V18H18V10M2 10V2H18V10M2 10H18M5 6H9M5 14H9" stroke="currentColor"/>"# }; +pub static SIDEBAR: Icon = Icon { name: "sidebar", view: 20.0, body: r#"<path d="M7.86667 2H5.2H2V18H5.2H7.86667M7.86667 2H18V18H7.86667M7.86667 2V18" stroke="currentColor"/>"# }; +pub static SIDEBAR_ACTIVE: Icon = Icon { name: "sidebar-active", view: 20.0, body: r#"<path d="M2 2V18H5.2H7.86667V2H5.2H2Z" fill="currentColor" fill-opacity="0.1"/> +<path d="M7.86667 2H5.2H2V18H5.2H7.86667M7.86667 2H18V18H7.86667M7.86667 2V18" stroke="currentColor"/>"# }; +pub static LAYOUT_LEFT: Icon = Icon { name: "layout-left", view: 20.0, body: r#"<path d="M2.91675 2.91699L2.91675 2.41699L2.41675 2.41699L2.41675 2.91699L2.91675 2.91699ZM17.0834 2.91699L17.5834 2.91699L17.5834 2.41699L17.0834 2.41699L17.0834 2.91699ZM17.0834 17.0837L17.0834 17.5837L17.5834 17.5837L17.5834 17.0837L17.0834 17.0837ZM2.91675 17.0837L2.41675 17.0837L2.41675 17.5837L2.91675 17.5837L2.91675 17.0837ZM7.41674 17.0837L7.41674 17.5837L8.41674 17.5837L8.41674 17.0837L7.91674 17.0837L7.41674 17.0837ZM8.41674 2.91699L8.41674 2.41699L7.41674 2.41699L7.41674 2.91699L7.91674 2.91699L8.41674 2.91699ZM2.91675 2.91699L2.91675 3.41699L17.0834 3.41699L17.0834 2.91699L17.0834 2.41699L2.91675 2.41699L2.91675 2.91699ZM17.0834 2.91699L16.5834 2.91699L16.5834 17.0837L17.0834 17.0837L17.5834 17.0837L17.5834 2.91699L17.0834 2.91699ZM17.0834 17.0837L17.0834 16.5837L2.91675 16.5837L2.91675 17.0837L2.91675 17.5837L17.0834 17.5837L17.0834 17.0837ZM2.91675 17.0837L3.41675 17.0837L3.41675 2.91699L2.91675 2.91699L2.41675 2.91699L2.41675 17.0837L2.91675 17.0837ZM7.91674 17.0837L8.41674 17.0837L8.41674 2.91699L7.91674 2.91699L7.41674 2.91699L7.41674 17.0837L7.91674 17.0837Z" fill="currentColor"/>"# }; +pub static LAYOUT_LEFT_PARTIAL: Icon = Icon { name: "layout-left-partial", view: 20.0, body: r#"<path d="M2.91732 2.91602L7.91732 2.91602L7.91732 17.0827H2.91732L2.91732 2.91602Z" fill="currentColor" fill-opacity="16%" /><path d="M2.91732 2.91602L17.084 2.91602M2.91732 2.91602L2.91732 17.0827M2.91732 2.91602L7.91732 2.91602M17.084 2.91602L17.084 17.0827M17.084 2.91602L7.91732 2.91602M17.084 17.0827L2.91732 17.0827M17.084 17.0827L7.91732 17.0827M2.91732 17.0827H7.91732M7.91732 17.0827L7.91732 2.91602" stroke="currentColor" stroke-linecap="square"/>"# }; +pub static LAYOUT_LEFT_FULL: Icon = Icon { name: "layout-left-full", view: 20.0, body: r#"<path d="M2.91732 2.91602L7.91732 2.91602L7.91732 17.0827H2.91732L2.91732 2.91602Z" fill="currentColor"/><path d="M2.91732 2.91602L17.084 2.91602M2.91732 2.91602L2.91732 17.0827M2.91732 2.91602L7.91732 2.91602M17.084 2.91602L17.084 17.0827M17.084 2.91602L7.91732 2.91602M17.084 17.0827L2.91732 17.0827M17.084 17.0827L7.91732 17.0827M2.91732 17.0827H7.91732M7.91732 17.0827L7.91732 2.91602" stroke="currentColor" stroke-linecap="square"/>"# }; +pub static LAYOUT_RIGHT: Icon = Icon { name: "layout-right", view: 20.0, body: r#"<g transform="matrix(-1 0 0 1 20 0)"><path d="M2.91675 2.91699L2.91675 2.41699L2.41675 2.41699L2.41675 2.91699L2.91675 2.91699ZM17.0834 2.91699L17.5834 2.91699L17.5834 2.41699L17.0834 2.41699L17.0834 2.91699ZM17.0834 17.0837L17.0834 17.5837L17.5834 17.5837L17.5834 17.0837L17.0834 17.0837ZM2.91675 17.0837L2.41675 17.0837L2.41675 17.5837L2.91675 17.5837L2.91675 17.0837ZM7.41674 17.0837L7.41674 17.5837L8.41674 17.5837L8.41674 17.0837L7.91674 17.0837L7.41674 17.0837ZM8.41674 2.91699L8.41674 2.41699L7.41674 2.41699L7.41674 2.91699L7.91674 2.91699L8.41674 2.91699ZM2.91675 2.91699L2.91675 3.41699L17.0834 3.41699L17.0834 2.91699L17.0834 2.41699L2.91675 2.41699L2.91675 2.91699ZM17.0834 2.91699L16.5834 2.91699L16.5834 17.0837L17.0834 17.0837L17.5834 17.0837L17.5834 2.91699L17.0834 2.91699ZM17.0834 17.0837L17.0834 16.5837L2.91675 16.5837L2.91675 17.0837L2.91675 17.5837L17.0834 17.5837L17.0834 17.0837ZM2.91675 17.0837L3.41675 17.0837L3.41675 2.91699L2.91675 2.91699L2.41675 2.91699L2.41675 17.0837L2.91675 17.0837ZM7.91674 17.0837L8.41674 17.0837L8.41674 2.91699L7.91674 2.91699L7.41674 2.91699L7.41674 17.0837L7.91674 17.0837Z" fill="currentColor"/></g>"# }; +pub static LAYOUT_RIGHT_PARTIAL: Icon = Icon { name: "layout-right-partial", view: 20.0, body: r#"<g transform="matrix(-1 0 0 1 20 0)"><path d="M2.91732 2.91602L7.91732 2.91602L7.91732 17.0827H2.91732L2.91732 2.91602Z" fill="currentColor" fill-opacity="16%" /><path d="M2.91732 2.91602L17.084 2.91602M2.91732 2.91602L2.91732 17.0827M2.91732 2.91602L7.91732 2.91602M17.084 2.91602L17.084 17.0827M17.084 2.91602L7.91732 2.91602M17.084 17.0827L2.91732 17.0827M17.084 17.0827L7.91732 17.0827M2.91732 17.0827H7.91732M7.91732 17.0827L7.91732 2.91602" stroke="currentColor" stroke-linecap="square"/></g>"# }; +pub static LAYOUT_RIGHT_FULL: Icon = Icon { name: "layout-right-full", view: 20.0, body: r#"<g transform="matrix(-1 0 0 1 20 0)"><path d="M2.91732 2.91602L7.91732 2.91602L7.91732 17.0827H2.91732L2.91732 2.91602Z" fill="currentColor"/><path d="M2.91732 2.91602L17.084 2.91602M2.91732 2.91602L2.91732 17.0827M2.91732 2.91602L7.91732 2.91602M17.084 2.91602L17.084 17.0827M17.084 2.91602L7.91732 2.91602M17.084 17.0827L2.91732 17.0827M17.084 17.0827L7.91732 17.0827M2.91732 17.0827H7.91732M7.91732 17.0827L7.91732 2.91602" stroke="currentColor" stroke-linecap="square"/></g>"# }; +pub static OPEN_FILE: Icon = Icon { name: "open-file", view: 20.0, body: r#"<path d="M7.91602 2.91406H2.91602V17.0807H17.0827V12.0807M12.0827 2.91406H17.0827V7.91406M9.58268 10.4141L16.666 3.33073" stroke="currentColor" stroke-linecap="square"/>"# }; +pub static COMMENT: Icon = Icon { name: "comment", view: 16.0, body: r#"<path d="M1.5 2.5V10.5H5.5L8 13.5L10.5 10.5H14.5V2.5H1.5Z" stroke-linecap="round" stroke-linejoin="round" stroke="currentColor"/>"# }; +pub static FOLDER_ADD_LEFT: Icon = Icon { name: "folder-add-left", view: 16.0, body: r#"<path d="M7.5 13.5H1.5V2.5H5.5L8.5 5.5H14.5V6.5" stroke-linecap="round" stroke-linejoin="round" stroke="currentColor"/><path d="M9.5 11.5H12.5M12.5 11.5H15.5M12.5 11.5V8.5M12.5 11.5V14.5" stroke-linecap="round" stroke-linejoin="round" stroke="currentColor"/>"# }; +pub static GITHUB: Icon = Icon { name: "github", view: 20.0, body: r#"<path d="M10.0001 1.62549C14.6042 1.62549 18.3334 5.35465 18.3334 9.95882C18.333 11.7049 17.785 13.4068 16.7666 14.8251C15.7482 16.2434 14.3107 17.3066 12.6563 17.8651C12.2397 17.9484 12.0834 17.688 12.0834 17.4692C12.0834 17.188 12.0938 16.2922 12.0938 15.1776C12.0938 14.3963 11.8334 13.8963 11.5313 13.6359C13.3855 13.4276 15.3334 12.7192 15.3334 9.52132C15.3334 8.60465 15.0105 7.86507 14.4792 7.28174C14.5626 7.0734 14.8542 6.21924 14.3959 5.0734C14.3959 5.0734 13.698 4.84424 12.1042 5.92757C11.4376 5.74007 10.7292 5.64632 10.0209 5.64632C9.31258 5.64632 8.60425 5.74007 7.93758 5.92757C6.34383 4.85465 5.64592 5.0734 5.64592 5.0734C5.18758 6.21924 5.47925 7.0734 5.56258 7.28174C5.03133 7.86507 4.70842 8.61507 4.70842 9.52132C4.70842 12.7088 6.64592 13.4276 8.50008 13.6359C8.2605 13.8442 8.04175 14.2088 7.96883 14.7505C7.48967 14.9692 6.29175 15.3234 5.54175 14.063C5.3855 13.813 4.91675 13.1984 4.2605 13.2088C3.56258 13.2192 3.97925 13.6047 4.27092 13.7609C4.62508 13.9588 5.03133 14.6984 5.12508 14.938C5.29175 15.4067 5.83342 16.3026 7.92717 15.9172C7.92717 16.6151 7.93758 17.2713 7.93758 17.4692C7.93758 17.688 7.78133 17.938 7.36467 17.8651C5.70491 17.3126 4.26126 16.2515 3.23851 14.8324C2.21576 13.4133 1.66583 11.7081 1.66675 9.95882C1.66675 5.35465 5.39592 1.62549 10.0001 1.62549Z" fill="currentColor"/>"# }; +pub static DISCORD: Icon = Icon { name: "discord", view: 20.0, body: r#"<path d="M16.0742 4.45014C14.9244 3.92097 13.7106 3.54556 12.4638 3.3335C12.2932 3.64011 12.1388 3.95557 12.0013 4.27856C10.6732 4.07738 9.32261 4.07738 7.99451 4.27856C7.85694 3.9556 7.70257 3.64014 7.53203 3.3335C6.28441 3.54735 5.06981 3.92365 3.91889 4.45291C1.63401 7.85128 1.01462 11.1652 1.32431 14.4322C2.6624 15.426 4.16009 16.1819 5.7523 16.6668C6.11082 16.1821 6.42806 15.6678 6.70066 15.1295C6.18289 14.9351 5.68315 14.6953 5.20723 14.4128C5.33249 14.3215 5.45499 14.2274 5.57336 14.136C6.95819 14.7907 8.46965 15.1302 9.99997 15.1302C11.5303 15.1302 13.0418 14.7907 14.4266 14.136C14.5463 14.2343 14.6688 14.3284 14.7927 14.4128C14.3159 14.6957 13.8152 14.9361 13.2965 15.1309C13.5688 15.669 13.8861 16.1828 14.2449 16.6668C15.8385 16.1838 17.3373 15.4283 18.6756 14.4335C19.039 10.645 18.0549 7.36145 16.0742 4.45014ZM7.09294 12.423C6.22992 12.423 5.51693 11.6357 5.51693 10.6671C5.51693 9.69852 6.20514 8.90427 7.09019 8.90427C7.97524 8.90427 8.68272 9.69852 8.66758 10.6671C8.65244 11.6357 7.97248 12.423 7.09294 12.423ZM12.907 12.423C12.0426 12.423 11.3324 11.6357 11.3324 10.6671C11.3324 9.69852 12.0206 8.90427 12.907 8.90427C13.7934 8.90427 14.4954 9.69852 14.4803 10.6671C14.4651 11.6357 13.7865 12.423 12.907 12.423Z" fill="currentColor"/>"# }; +pub static LAYOUT_BOTTOM: Icon = Icon { name: "layout-bottom", view: 20.0, body: r#"<path d="M2.91699 17.0832L2.41699 17.0832L2.41699 17.5832L2.91699 17.5832L2.91699 17.0832ZM2.91699 2.91653L2.91699 2.41653L2.41699 2.41653L2.41699 2.91653L2.91699 2.91653ZM17.0837 2.91653L17.5837 2.91653L17.5837 2.41653L17.0837 2.41653L17.0837 2.91653ZM17.0837 17.0832L17.5837 17.0832L17.5837 17.5832L17.0837 17.5832L17.0837 17.0832ZM17.0837 12.5827L17.5837 12.5827L17.5837 11.5827L17.0837 11.5827L17.0837 12.0827L17.0837 12.5827ZM2.91699 11.5827L2.41699 11.5827L2.41699 12.5827L2.91699 12.5827L2.91699 12.0827L2.91699 11.5827ZM2.91699 17.0832L3.41699 17.0832L3.41699 2.91653L2.91699 2.91653L2.41699 2.91653L2.41699 17.0832L2.91699 17.0832ZM2.91699 2.91653L2.91699 3.41653L17.0837 3.41653L17.0837 2.91653L17.0837 2.41653L2.91699 2.41653L2.91699 2.91653ZM17.0837 2.91653L16.5837 2.91653L16.5837 17.0832L17.0837 17.0832L17.5837 17.0832L17.5837 2.91653L17.0837 2.91653ZM17.0837 17.0832L17.0837 16.5832L2.91699 16.5832L2.91699 17.0832L2.91699 17.5832L17.0837 17.5832L17.0837 17.0832ZM17.0837 12.0827L17.0837 11.5827L2.91699 11.5827L2.91699 12.0827L2.91699 12.5827L17.0837 12.5827L17.0837 12.0827Z" fill="currentColor"/>"# }; +pub static LAYOUT_BOTTOM_PARTIAL: Icon = Icon { name: "layout-bottom-partial", view: 20.0, body: r#"<path d="M2.91732 12.0827L17.084 12.0827L17.084 17.0827H2.91732L2.91732 12.0827Z" fill="currentColor" fill-opacity="16%" /><path d="M2.91732 2.91602L17.084 2.91602M2.91732 2.91602L2.91732 17.0827M17.084 2.91602L17.084 17.0827M17.084 17.0827L2.91732 17.0827M2.91732 12.0827L17.084 12.0827" stroke="currentColor" stroke-linecap="square"/>"# }; +pub static LAYOUT_BOTTOM_FULL: Icon = Icon { name: "layout-bottom-full", view: 20.0, body: r#"<path d="M2.91732 12.0827L17.084 12.0827L17.084 17.0827H2.91732L2.91732 12.0827Z" fill="currentColor"/><path d="M2.91732 2.91602L17.084 2.91602M2.91732 2.91602L2.91732 17.0827M17.084 2.91602L17.084 17.0827M17.084 17.0827L2.91732 17.0827M2.91732 12.0827L17.084 12.0827" stroke="currentColor" stroke-linecap="square"/>"# }; +pub static DOT_GRID: Icon = Icon { name: "dot-grid", view: 20.0, body: r#"<path d="M2.08398 9.16602H3.75065V10.8327H2.08398V9.16602Z" fill="currentColor"/><path d="M10.834 9.16602H9.16732V10.8327H10.834V9.16602Z" fill="currentColor"/><path d="M16.2507 9.16602H17.9173V10.8327H16.2507V9.16602Z" fill="currentColor"/><path d="M2.08398 9.16602H3.75065V10.8327H2.08398V9.16602Z" stroke="currentColor"/><path d="M10.834 9.16602H9.16732V10.8327H10.834V9.16602Z" stroke="currentColor"/><path d="M16.2507 9.16602H17.9173V10.8327H16.2507V9.16602Z" stroke="currentColor"/>"# }; +pub static CIRCLE_CHECK: Icon = Icon { name: "circle-check", view: 16.0, body: r#"<path d="M5 8L7.5 11L11 5.5" stroke-linecap="round" stroke-linejoin="round" stroke="currentColor"/><path d="M14.5 8C14.5 11.5899 11.5899 14.5 8 14.5C4.41015 14.5 1.5 11.5899 1.5 8C1.5 4.41015 4.41015 1.5 8 1.5C11.5899 1.5 14.5 4.41015 14.5 8Z" stroke="currentColor"/>"# }; +pub static CIRCLE_CHECK_BOLD: Icon = Icon { name: "circle-check-bold", view: 16.0, body: r#"<path d="M5 8L7.5 11L11 5.5" stroke-linecap="round" stroke-linejoin="round" stroke="currentColor" stroke-width="1.5"/><path d="M14.5 8C14.5 11.5899 11.5899 14.5 8 14.5C4.41015 14.5 1.5 11.5899 1.5 8C1.5 4.41015 4.41015 1.5 8 1.5C11.5899 1.5 14.5 4.41015 14.5 8Z" stroke="currentColor" stroke-width="1.5"/>"# }; +pub static COPY: Icon = Icon { name: "copy", view: 16.0, body: r#"<path d="M9.5 3.5V1.5H1.5V10.5H4.5" stroke-linecap="round" stroke-linejoin="round" stroke="currentColor"/><path d="M6.5 14.5V5.5H14.5V14.5H6.5Z" stroke-linecap="round" stroke-linejoin="round" stroke="currentColor"/>"# }; +pub static CHECK: Icon = Icon { name: "check", view: 16.0, body: r#"<path d="M4.5 7.5L7 11.5L11.5 4.5" stroke-linecap="round" stroke-linejoin="round" stroke="currentColor"/>"# }; +pub static PHOTO: Icon = Icon { name: "photo", view: 20.0, body: r#"<path d="M16.6665 16.6666L11.6665 11.6666L9.99984 13.3333L6.6665 9.99996L3.08317 13.5833M2.9165 2.91663H17.0832V17.0833H2.9165V2.91663ZM13.3332 7.49996C13.3332 8.30537 12.6803 8.95829 11.8748 8.95829C11.0694 8.95829 10.4165 8.30537 10.4165 7.49996C10.4165 6.69454 11.0694 6.04163 11.8748 6.04163C12.6803 6.04163 13.3332 6.69454 13.3332 7.49996Z" stroke="currentColor" stroke-linecap="square"/>"# }; +pub static SHARE: Icon = Icon { name: "share", view: 20.0, body: r#"<path d="M10.0013 12.0846L10.0013 3.33464M13.7513 6.66797L10.0013 2.91797L6.2513 6.66797M17.0846 10.418V17.0846H2.91797V10.418" stroke="currentColor" stroke-linecap="square"/>"# }; +pub static SHIELD: Icon = Icon { name: "shield", view: 20.0, body: r#"<path d="M7.49935 9.3737L9.16602 11.0404L12.4994 7.70703M9.99935 2.08203L17.0827 4.3737V9.92565C17.0827 14.0694 13.3327 16.2487 9.99935 18.047C6.66602 16.2487 2.91602 14.0694 2.91602 9.92565V4.3737L9.99935 2.08203Z" stroke="currentColor" stroke-linecap="square"/>"# }; +pub static DOWNLOAD: Icon = Icon { name: "download", view: 16.0, body: r#"<path d="M8 2.5L8 10.5M4.5 7L8 10.5L11.5 7" stroke-linecap="round" stroke-linejoin="round" stroke="currentColor"/><path d="M1.5 10.5V13.5H14.5V10.5" stroke-linecap="round" stroke-linejoin="round" stroke="currentColor"/>"# }; +pub static MENU: Icon = Icon { name: "menu", view: 16.0, body: r#"<path d="M2 8.00006H14M2 4.5H14M2 11.5H14" stroke="currentColor"/>"# }; +pub static SERVER: Icon = Icon { name: "server", view: 16.0, body: r#"<path d="M1.5 10.5V14.5H14.5V10.5M1.5 10.5H14.5M14.5 10.5V6.5L11.5 1.5H4.5L1.5 6.5V10.5M1.5 6.5H14.5" stroke-linecap="square" stroke-linejoin="round" stroke="currentColor"/><path d="M12.5 12.5H11.5M12.5 8.5H11.5" stroke-linecap="round" stroke="currentColor"/>"# }; +pub static BRANCH: Icon = Icon { name: "branch", view: 16.0, body: r#"<circle cx="5" cy="12" r="1.5" stroke="currentColor"/><path d="M5.22983 10.4384V5.43842M6.55305 11.8019H8.83276C9.94392 11.8019 10.8421 10.8962 10.8327 9.78506L10.7966 5.50012" stroke-linecap="round" stroke-linejoin="round" stroke="currentColor"/><circle cx="5" cy="4" r="1.5" stroke="currentColor"/><circle cx="11" cy="4" r="1.5" stroke="currentColor"/>"# }; +pub static EDIT: Icon = Icon { name: "edit", view: 16.0, body: r#"<path d="M8.5 2.5H2.5V13.5H13.5V7.5M7.5 8.5V6.5L12.5 1.5L14.5 3.5L9.5 8.5H7.5Z" stroke-linecap="round" stroke-linejoin="round" stroke="currentColor"/>"# }; +pub static HELP: Icon = Icon { name: "help", view: 16.0, body: r#"<path d="M14.5 8C14.5 11.5899 11.5899 14.5 8 14.5C4.41015 14.5 1.5 11.5899 1.5 8C1.5 4.41015 4.41015 1.5 8 1.5C11.5899 1.5 14.5 4.41015 14.5 8Z" stroke="currentColor"/><path d="M7.22461 9.50977V9.43555C7.22982 8.95117 7.27799 8.77279 7.36914 8.48633C7.46289 8.19987 7.5957 7.9681 7.76758 7.79102C7.93945 7.61393 8.14648 7.45247 8.38867 7.30664C8.54492 7.20768 8.68555 7.09701 8.81055 6.97461C8.93555 6.85221 9.03451 6.71159 9.10742 6.55273C9.18034 6.39388 9.2168 6.2181 9.2168 6.02539C9.2168 5.79362 9.16211 5.5931 9.05273 5.42383C8.94336 5.25456 8.79753 5.12435 8.61523 5.0332C8.43555 4.93945 8.23503 4.89258 8.01367 4.89258C7.81315 4.89258 7.62174 4.93424 7.43945 5.01758C7.25716 5.10091 7.10612 5.23112 6.98633 5.4082C6.86654 5.58268 6.79753 5.72591 6.7793 6.00195H5.5918C5.61003 5.5332 5.72852 5.2194 5.94727 4.89648C6.16602 4.57096 6.45508 4.32487 6.81445 4.1582C7.17643 3.99154 7.57617 3.9082 8.01367 3.9082C8.49284 3.9082 8.91211 3.99805 9.27148 4.17773C9.63086 4.35482 9.90951 4.60352 10.1074 4.92383C10.3079 5.24154 10.4082 5.61263 10.4082 6.03711C10.4082 6.32878 10.3626 6.5918 10.2715 6.82617C10.1803 7.05794 10.0501 7.26497 9.88086 7.44727C9.71419 7.62956 9.51367 7.79102 9.2793 7.93164C9.05794 8.06966 8.87826 8.21289 8.74023 8.36133C8.60482 8.50977 8.50586 8.68555 8.44336 8.88867C8.38086 9.0918 8.34701 9.13607 8.3418 9.43555V9.50977H7.22461Z" fill="currentColor"/><rect x="6.99902" y="10.6675" width="1.42432" height="1.42432" fill="currentColor"/>"# }; +pub static HELP_BOLD: Icon = Icon { name: "help-bold", view: 16.0, body: r#"<path d="M14.5 8C14.5 11.5899 11.5899 14.5 8 14.5C4.41015 14.5 1.5 11.5899 1.5 8C1.5 4.41015 4.41015 1.5 8 1.5C11.5899 1.5 14.5 4.41015 14.5 8Z" stroke="currentColor" stroke-width="1.5"/><path d="M7.22461 9.50977V9.43555C7.22982 8.95117 7.27799 8.77279 7.36914 8.48633C7.46289 8.19987 7.5957 7.9681 7.76758 7.79102C7.93945 7.61393 8.14648 7.45247 8.38867 7.30664C8.54492 7.20768 8.68555 7.09701 8.81055 6.97461C8.93555 6.85221 9.03451 6.71159 9.10742 6.55273C9.18034 6.39388 9.2168 6.2181 9.2168 6.02539C9.2168 5.79362 9.16211 5.5931 9.05273 5.42383C8.94336 5.25456 8.79753 5.12435 8.61523 5.0332C8.43555 4.93945 8.23503 4.89258 8.01367 4.89258C7.81315 4.89258 7.62174 4.93424 7.43945 5.01758C7.25716 5.10091 7.10612 5.23112 6.98633 5.4082C6.86654 5.58268 6.79753 5.72591 6.7793 6.00195H5.5918C5.61003 5.5332 5.72852 5.2194 5.94727 4.89648C6.16602 4.57096 6.45508 4.32487 6.81445 4.1582C7.17643 3.99154 7.57617 3.9082 8.01367 3.9082C8.49284 3.9082 8.91211 3.99805 9.27148 4.17773C9.63086 4.35482 9.90951 4.60352 10.1074 4.92383C10.3079 5.24154 10.4082 5.61263 10.4082 6.03711C10.4082 6.32878 10.3626 6.5918 10.2715 6.82617C10.1803 7.05794 10.0501 7.26497 9.88086 7.44727C9.71419 7.62956 9.51367 7.79102 9.2793 7.93164C9.05794 8.06966 8.87826 8.21289 8.74023 8.36133C8.60482 8.50977 8.50586 8.68555 8.44336 8.88867C8.38086 9.0918 8.34701 9.13607 8.3418 9.43555V9.50977H7.22461Z" fill="currentColor"/><rect x="6.99902" y="10.6675" width="1.42432" height="1.42432" fill="currentColor"/>"# }; +pub static SETTINGS_GEAR: Icon = Icon { name: "settings-gear", view: 16.0, body: r#"<path d="M1.5 11V5L8 1.5L14.5 5V11L8 14.5L1.5 11Z" stroke-linecap="round" stroke-linejoin="round" stroke="currentColor"/><path d="M10.5 8C10.5 9.38071 9.38071 10.5 8 10.5C6.61929 10.5 5.5 9.38071 5.5 8C5.5 6.61929 6.61929 5.5 8 5.5C9.38071 5.5 10.5 6.61929 10.5 8Z" stroke="currentColor"/>"# }; +pub static CLOUD_UPLOAD: Icon = Icon { name: "cloud-upload", view: 20.0, body: r#"<path d="M12.0833 16.25H15C17.0711 16.25 18.75 14.5711 18.75 12.5C18.75 10.5649 17.2843 8.97217 15.4025 8.77133C15.2 6.13103 12.8586 4.08333 10 4.08333C7.71532 4.08333 5.76101 5.49781 4.96501 7.49881C2.84892 7.90461 1.25 9.76559 1.25 11.6667C1.25 13.9813 3.30203 16.25 5.83333 16.25H7.91667M10 16.25V10.4167M12.0833 11.875L10 9.79167L7.91667 11.875" stroke="currentColor" stroke-linecap="square"/>"# }; +pub static TRASH: Icon = Icon { name: "trash", view: 16.0, body: r#"<path d="M5.5 4.5H2.5L4 14.5H12L13.5 4.5H10.5M5.5 4.5V1.5H10.5V4.5M5.5 4.5H10.5M6.5 11.5L6 7M9.5 11.5L10 7" stroke-linecap="round" stroke-linejoin="round" stroke="currentColor"/>"# }; +pub static SLIDERS: Icon = Icon { name: "sliders", view: 16.0, body: r#"<path d="M7.5 11.5C7.5 12.6046 6.60457 13.5 5.5 13.5C4.39543 13.5 3.5 12.6046 3.5 11.5C3.5 10.3954 4.39543 9.5 5.5 9.5C6.60457 9.5 7.5 10.3954 7.5 11.5Z" stroke="currentColor"/><path d="M12.5 4.5C12.5 5.60457 11.6046 6.5 10.5 6.5C9.39543 6.5 8.5 5.60457 8.5 4.5C8.5 3.39543 9.39543 2.5 10.5 2.5C11.6046 2.5 12.5 3.39543 12.5 4.5Z" stroke="currentColor"/><path d="M8.0498 4C8.01702 4.16154 8 4.32878 8 4.5C8 4.67122 8.01702 4.83846 8.0498 5H1.5C1.22386 5 1 4.77614 1 4.5C1 4.22386 1.22386 4 1.5 4H8.0498ZM14.5 4C14.7761 4 15 4.22386 15 4.5C15 4.77614 14.7761 5 14.5 5H12.9502C12.983 4.83846 13 4.67122 13 4.5C13 4.32878 12.983 4.16154 12.9502 4H14.5Z" fill="currentColor"/><path d="M3.0498 11C3.01702 11.1615 3 11.3288 3 11.5C3 11.6712 3.01702 11.8385 3.0498 12H1.5C1.22386 12 1 11.7761 1 11.5C1 11.2239 1.22386 11 1.5 11H3.0498ZM14.5 11C14.7761 11 15 11.2239 15 11.5C15 11.7761 14.7761 12 14.5 12H7.9502C7.98298 11.8385 8 11.6712 8 11.5C8 11.3288 7.98298 11.1615 7.9502 11H14.5Z" fill="currentColor"/>"# }; +pub static KEYBOARD: Icon = Icon { name: "keyboard", view: 16.0, body: r#"<path d="M5.5 13.5H10.5V8.5H13.5L8 2.5L2.5 8.5H5.5V13.5Z" stroke-linejoin="round" stroke="currentColor"/>"# }; +pub static SELECTOR: Icon = Icon { name: "selector", view: 20.0, body: r#"<path d="M6.66626 12.5033L9.99959 15.8366L13.3329 12.5033M6.66626 7.50326L9.99959 4.16992L13.3329 7.50326" stroke="currentColor" stroke-linecap="square"/>"# }; +pub static ARROW_DOWN_TO_LINE: Icon = Icon { name: "arrow-down-to-line", view: 20.0, body: r#"<path d="M15.2083 11.6667L10 16.875L4.79167 11.6667M10 16.25V3.125" stroke="currentColor" stroke-width="1.25" stroke-linecap="square"/>"# }; +pub static WARNING: Icon = Icon { name: "warning", view: 20.0, body: r#"<path d="M10 7.91667V11.6667M10 13.7417V13.75M10 2.5L1.875 16.25H18.125L10 2.5Z" stroke="currentColor" stroke-linecap="square"/>"# }; +pub static WARNING_BOLD: Icon = Icon { name: "warning-bold", view: 20.0, body: r#"<path d="M10 7.91667V11.6667M10 13.7417V13.75M10 2.5L1.875 16.25H18.125L10 2.5Z" stroke="currentColor" stroke-width="1.5" stroke-linecap="square"/>"# }; +pub static RESET: Icon = Icon { name: "reset", view: 16.0, body: r#"<path d="M2.5 6.5H12.5C13.0523 6.5 13.5 6.94772 13.5 7.5V10.5C13.5 11.0523 13.0523 11.5 12.5 11.5H8.5M5.5 9.5L2.5 6.5L5.5 3.5" stroke-linecap="round" stroke-linejoin="round" stroke="currentColor"/>"# }; +pub static LINK: Icon = Icon { name: "link", view: 20.0, body: r#"<path d="M2.08334 12.0833L1.72979 11.7298L1.37624 12.0833L1.72979 12.4369L2.08334 12.0833ZM7.91668 17.9167L7.56312 18.2702L7.91668 18.6238L8.27023 18.2702L7.91668 17.9167ZM17.9167 7.91666L18.2702 8.27022L18.6238 7.91666L18.2702 7.56311L17.9167 7.91666ZM12.0833 2.08333L12.4369 1.72977L12.0833 1.37622L11.7298 1.72977L12.0833 2.08333ZM8.39646 5.06311L8.0429 5.41666L8.75001 6.12377L9.10356 5.77021L8.75001 5.41666L8.39646 5.06311ZM5.77023 9.10355L6.12378 8.74999L5.41668 8.04289L5.06312 8.39644L5.41668 8.74999L5.77023 9.10355ZM14.2298 10.8964L13.8762 11.25L14.5833 11.9571L14.9369 11.6035L14.5833 11.25L14.2298 10.8964ZM11.6036 14.9369L11.9571 14.5833L11.25 13.8762L10.8965 14.2298L11.25 14.5833L11.6036 14.9369ZM7.14646 12.1464L6.7929 12.5L7.50001 13.2071L7.85356 12.8535L7.50001 12.5L7.14646 12.1464ZM12.8536 7.85355L13.2071 7.49999L12.5 6.79289L12.1465 7.14644L12.5 7.49999L12.8536 7.85355ZM2.08334 12.0833L1.72979 12.4369L7.56312 18.2702L7.91668 17.9167L8.27023 17.5631L2.4369 11.7298L2.08334 12.0833ZM17.9167 7.91666L18.2702 7.56311L12.4369 1.72977L12.0833 2.08333L11.7298 2.43688L17.5631 8.27022L17.9167 7.91666ZM12.0833 2.08333L11.7298 1.72977L8.39646 5.06311L8.75001 5.41666L9.10356 5.77021L12.4369 2.43688L12.0833 2.08333ZM5.41668 8.74999L5.06312 8.39644L1.72979 11.7298L2.08334 12.0833L2.4369 12.4369L5.77023 9.10355L5.41668 8.74999ZM14.5833 11.25L14.9369 11.6035L18.2702 8.27022L17.9167 7.91666L17.5631 7.56311L14.2298 10.8964L14.5833 11.25ZM7.91668 17.9167L8.27023 18.2702L11.6036 14.9369L11.25 14.5833L10.8965 14.2298L7.56312 17.5631L7.91668 17.9167ZM7.50001 12.5L7.85356 12.8535L12.8536 7.85355L12.5 7.49999L12.1465 7.14644L7.14646 12.1464L7.50001 12.5Z" fill="currentColor"/>"# }; +pub static PROVIDERS: Icon = Icon { name: "providers", view: 16.0, body: r#"<path d="M13.5 4.5V2.5H11.5M13.5 4.5H15.5M13.5 4.5V8M13.5 8H15.5M13.5 8V8.5V11.5M13.5 11.5V13.5H11.5M13.5 11.5H15.5M2.5 8H0.5M2.5 8V4.5M2.5 8V11.5M2.5 4.5V2.5H4.5M2.5 4.5H0.5M2.5 11.5V13.5H4.5M2.5 11.5H0.5M4.5 13.5V15.5M4.5 13.5H8M8 13.5V15.5M8 13.5H11.5M11.5 13.5V15.5M11.5 2.5V0.5M11.5 2.5H8M8 2.5V0.5M8 2.5H4.5M4.5 2.5V0.5M5.5 10.5V5.5H10.5V10.5H5.5Z" stroke-linecap="round" stroke-linejoin="round" stroke="currentColor"/>"# }; +pub static MODELS: Icon = Icon { name: "models", view: 16.0, body: r#"<path fill-rule="evenodd" clip-rule="evenodd" d="M14 8C9.83336 8 8 9.83336 8 14C8 9.83336 6.16666 8 2 8C6.16666 8 8 6.16666 8 2C8 6.16666 9.83336 8 14 8Z" stroke="currentColor"/>"# }; +pub static APPEARANCE: Icon = Icon { name: "appearance", view: 16.0, body: r#"<path d="M1.5 4.5L4.5 1.5M1.5 14.5L14.5 1.5M11.5 14.5L14.5 11.5M1.5 9.5L9.5 1.5M6.5 14.5L14.5 6.5" stroke-linecap="round" stroke="currentColor"/>"# }; +pub static NOTIFICATIONS: Icon = Icon { name: "notifications", view: 16.0, body: r#"<path d="M4.5 14.5H11.5" stroke-linecap="round" stroke="currentColor"/><path d="M8 12V14" stroke-linecap="square" stroke="currentColor"/><path d="M16 3.5C16 4.88071 14.8807 6 13.5 6C12.1193 6 11 4.88071 11 3.5C11 2.11929 12.1193 1 13.5 1C14.8807 1 16 2.11929 16 3.5Z" fill="currentColor"/><path d="M10.3369 2C10.1892 2.31084 10.0866 2.64695 10.0361 3H2V11H14V6.96387C14.3531 6.91336 14.6892 6.81075 15 6.66309V11.5C15 11.7761 14.7761 12 14.5 12H1.5C1.22386 12 1 11.7761 1 11.5V2.5C1 2.22386 1.22386 2 1.5 2H10.3369Z" fill="currentColor"/>"# }; +pub static EXTENSIONS: Icon = Icon { name: "extensions", view: 16.0, body: r#"<path d="M1.5 2.5V13.5H14.5V2.5H1.5Z" stroke-linecap="round" stroke-linejoin="round" stroke="currentColor"/><path d="M4.5 6.5V9.5M8 6.5V9.5M11.5 6.5V9.5" stroke-linecap="round" stroke="currentColor"/>"# }; +pub static CUBE: Icon = Icon { name: "cube", view: 16.0, body: r#"<path d="M8 14.5L14.5 11V5L8 1.5L1.5 5V11L8 14.5ZM1.5 5L8 8.5M14.5 5L8 8.5M8 8.5V14.5" stroke-linecap="square" stroke-linejoin="round" stroke="currentColor"/>"# }; +pub static POST_SKILL: Icon = Icon { name: "post-skill", view: 16.0, body: r#"<path d="M3 2.5C3.5 2.5 4.5 2.8 4.5 4L4.5 5.5V12C4.5 12.5 4.8 13.5 6 13.5M6 13.5C7.2 13.5 7.5 12.5 7.5 12V10.5H14.5V12C14.5 12.5 14.2 13.5 13 13.5H6ZM4.5 5.5H1.5V4C1.5 3.5 1.8 2.5 3 2.5M12.5 8.5V4.5C12.5 3.39543 11.6046 2.5 10.5 2.5H3" stroke-linecap="round" stroke-linejoin="round" stroke="currentColor"/><path d="M6.5 5.5H10.5M6.5 7.5H9" stroke-linecap="square" stroke-linejoin="round" stroke="currentColor"/>"# }; +pub static OUTLINE_LIST_CHANGELOG: Icon = Icon { name: "outline-list-changelog", view: 16.0, body: r#"<path d="M3 14.5V15H4V14.5H3.5H3ZM4 1.5V1H3V1.5H3.5H4ZM8.5 1.5V1H8V1.5H8.5ZM14.5 1.5H15V1H14.5V1.5ZM14.5 6.5V7H15V6.5H14.5ZM8.5 6.5H8V7H8.5V6.5ZM8.5 9.5V9H8V9.5H8.5ZM14.5 9.5H15V9H14.5V9.5ZM14.5 14.5V15H15V14.5H14.5ZM8.5 14.5H8V15H8.5V14.5ZM3.5 6H4V1.5H3.5H3V6H3.5ZM8.5 1.5V2H14.5V1.5V1H8.5V1.5ZM14.5 1.5H14V6.5H14.5H15V1.5H14.5ZM14.5 6.5V6H8.5V6.5V7H14.5V6.5ZM8.5 6.5H9V1.5H8.5H8V6.5H8.5ZM8.5 9.5V10H14.5V9.5V9H8.5V9.5ZM14.5 9.5H14V14.5H14.5H15V9.5H14.5ZM14.5 14.5V14H8.5V14.5V15H14.5V14.5ZM8.5 14.5H9V9.5H8.5H8V14.5H8.5ZM3.5 10V10.5C4.8807 10.5 6 9.38075 6 8H5.5H5C5 8.82845 4.32843 9.5 3.5 9.5V10ZM5.5 8H6C6 6.61925 4.8807 5.5 3.5 5.5V6V6.5C4.32843 6.5 5 7.17155 5 8H5.5ZM3.5 6V5.5C2.1193 5.5 1 6.61925 1 8H1.5H2C2 7.17155 2.67157 6.5 3.5 6.5V6ZM1.5 8H1C1 9.38075 2.1193 10.5 3.5 10.5V10V9.5C2.67157 9.5 2 8.82845 2 8H1.5ZM3.5 14.5H4V10H3.5H3V14.5H3.5Z" fill="currentColor"/>"# }; +pub static OUTLINE_PAIR: Icon = Icon { name: "outline-pair", view: 16.0, body: r#"<path d="M2.5 9V2.5H13.5V3.5M2.5 9L0.5 12.5H7.5M2.5 9H7.5" stroke-linecap="square" stroke-linejoin="round" stroke="currentColor"/><path d="M11.5 12.5H13.5M9.5 5.5V14.5H15.5V5.5H9.5Z" stroke-linecap="round" stroke-linejoin="round" stroke="currentColor"/>"# }; +pub static LOCK: Icon = Icon { name: "lock", view: 16.0, body: r#"<path d="M2.5 14.5V7.5H13.5V14.5H2.5Z" stroke-linecap="round" stroke-linejoin="round" stroke="currentColor"/><path d="M5.5 7.5V4C5.5 2.61929 6.61929 1.5 8 1.5C9.38071 1.5 10.5 2.61929 10.5 4V7.5" stroke-linecap="round" stroke-linejoin="round" stroke="currentColor"/><path d="M7.5 10.5C7.5 10.2239 7.72386 10 8 10C8.27614 10 8.5 10.2239 8.5 10.5V12.5C8.5 12.7761 8.27614 13 8 13C7.72386 13 7.5 12.7761 7.5 12.5V10.5Z" fill="currentColor"/>"# }; +pub static GLOBE: Icon = Icon { name: "globe", view: 16.0, body: r#"<path d="M14.5 8C14.5 11.5899 11.5899 14.5 8 14.5C4.41015 14.5 1.5 11.5899 1.5 8C1.5 4.41015 4.41015 1.5 8 1.5C11.5899 1.5 14.5 4.41015 14.5 8Z" stroke="currentColor"/><path d="M1.5 8H14.5" stroke-linecap="round" stroke-linejoin="round" stroke="currentColor"/><path d="M8 1.5C6.5 3 5.5 5.5 5.5 8C5.5 10.5 6.5 13 8 14.5C9.5 13 10.5 10.5 10.5 8C10.5 5.5 9.5 3 8 1.5Z" stroke-linecap="round" stroke-linejoin="round" stroke="currentColor"/>"# }; +pub static SELECT_ELEMENT: Icon = Icon { name: "select-element", view: 16.0, body: r#"<path d="M8.5 14.5V5.5L14.5 11.5H11L8.5 14.5Z" stroke-linecap="round" stroke-linejoin="round" stroke="currentColor"/><path d="M5.5 13.5H1.5V2.5H14.5V7.5" stroke-linecap="round" stroke-linejoin="round" stroke="currentColor"/>"# }; +pub static FLASK: Icon = Icon { name: "flask", view: 16.0, body: r#"<path d="M10.5 2.5V6.5L11.3571 8.5M10.5 2.5H5.5M10.5 2.5H12.5M5.5 2.5V6.5L4.21429 9.5M5.5 2.5H3.5M4.21429 9.5L2.5 13.5H13.5L11.3571 8.5M4.21429 9.5L11.3571 8.5" stroke-linecap="round" stroke-linejoin="round" stroke="currentColor"/>"# }; +pub static GRID_PLUS: Icon = Icon { name: "grid-plus", view: 16.0, body: r#"<path d="M13.9948 11.668H9.32812M11.6641 9.33203V13.9987M6.66667 9.33203V13.9987H2V9.33203H6.66667ZM6.66667 2V6.66667H2V2H6.66667ZM13.9948 2V6.66667H9.32812V2H13.9948Z" stroke="currentColor" stroke-miterlimit="10" stroke-linecap="square"/>"# }; +pub static INFO: Icon = Icon { name: "info", view: 16.0, body: r#"<g transform="translate(2 2)"><path d="M12 12H0V0H12V12ZM1 1V11H11V1H1ZM6.5791 4.81641V9.37207H5.5791V5.81641H4.46777V4.81641H6.5791ZM6.85645 2.62891V3.62891H5.30078V2.62891H6.85645Z" fill="currentColor"/></g>"# }; +pub static CIRCLE_EXCLAMATION: Icon = Icon { name: "circle-exclamation", view: 16.0, body: r#"<path d="M8.75 11.75H7.25V10.25H8.75V11.75Z" fill="currentColor"/><path d="M8.75 9.25H7.25V4.25H8.75V9.25Z" fill="currentColor"/><path fill-rule="evenodd" clip-rule="evenodd" d="M8 1C9.93286 1 11.684 1.7836 12.9502 3.0498C14.2164 4.31601 15 6.06714 15 8C15 11.866 11.866 15 8 15C6.06714 15 4.31601 14.2164 3.0498 12.9502C1.7836 11.684 1 9.93286 1 8C1 4.13401 4.13401 1 8 1ZM8 2C4.68629 2 2 4.68629 2 8C2 9.65699 2.67148 11.1559 3.75781 12.2422C4.84415 13.3285 6.34301 14 8 14C11.3137 14 14 11.3137 14 8C14 6.34301 13.3285 4.84415 12.2422 3.75781C11.1559 2.67148 9.65699 2 8 2Z" fill="currentColor"/>"# }; +pub static OUTLINE_MAGNIFIER_MINUS: Icon = Icon { name: "outline-magnifier-minus", view: 16.0, body: r#"<path d="M12.5 7.5C12.5 10.2614 10.2614 12.5 7.5 12.5C4.73858 12.5 2.5 10.2614 2.5 7.5C2.5 4.73858 4.73858 2.5 7.5 2.5C10.2614 2.5 12.5 4.73858 12.5 7.5Z" stroke="currentColor"/><path d="M13.5 13.5L11.5 11.5" stroke-linecap="round" stroke="currentColor"/><path d="M5.5 7.5H9.5" stroke-linecap="round" stroke-linejoin="round" stroke="currentColor"/>"# }; +pub static OUTLINE_MAGNIFIER_PLUS: Icon = Icon { name: "outline-magnifier-plus", view: 16.0, body: r#"<path d="M12.5 7.5C12.5 10.2614 10.2614 12.5 7.5 12.5C4.73858 12.5 2.5 10.2614 2.5 7.5C2.5 4.73858 4.73858 2.5 7.5 2.5C10.2614 2.5 12.5 4.73858 12.5 7.5Z" stroke="currentColor"/><path d="M13.5 13.5L11.5 11.5" stroke-linecap="round" stroke="currentColor"/><path d="M5 7.5H7.5M7.5 7.5H10M7.5 7.5V5M7.5 7.5V10" stroke-linecap="round" stroke-linejoin="round" stroke="currentColor"/>"# }; +pub static MINUS: Icon = Icon { name: "minus", view: 16.0, body: r#"<path d="M2.5 8H13.5" stroke-linecap="round" stroke-linejoin="round" stroke="currentColor"/>"# }; +pub static MONITOR: Icon = Icon { name: "monitor", view: 16.0, body: r#"<path d="M4.5 14.5H11.5" stroke-linecap="round" stroke="currentColor"/><path d="M8 12V14" stroke-linecap="square" stroke="currentColor"/><path d="M1.5 11.5V2.5H14.5V11.5H1.5Z" stroke-linecap="round" stroke-linejoin="round" stroke="currentColor"/>"# }; +pub static WORKSPACE_NEW: Icon = Icon { name: "workspace-new", view: 16.0, body: r#"<path d="M2 10.7578V14.0011H5.24324M13.9991 5.24324V2H10.7559M13.9991 10.7578V14.0011H10.7559M2 5.24324V2H5.24324" stroke="currentColor" stroke-miterlimit="10" stroke-linecap="square"/><path d="M8 4.5V11.5M4.5 8H11.5" stroke="currentColor" stroke-linejoin="round"/>"# }; +pub static WORKSPACE: Icon = Icon { name: "workspace", view: 16.0, body: r#"<path d="M2 10.668V14.0013H10.6667M13.9974 10.6667V2H2.66406M13.9974 10.668V14.0013H10.6641M2 10V2H5.33333" stroke="currentColor" stroke-miterlimit="10" stroke-linecap="square"/><path d="M10.6693 10.6654V5.33203H5.33594V10.6654H10.6693Z" fill="currentColor"/>"# }; +pub static OUTLINE_WORKTREE: Icon = Icon { name: "outline-worktree", view: 16.0, body: r#"<path d="M1.5 11.5H5L9.5 5.5H14.5M12 8L14.5 5.5L12 3M9 11.5H14.5" stroke-linecap="round" stroke-linejoin="round" stroke="currentColor"/>"# }; +pub static OUTLINE_DOTS: Icon = Icon { name: "outline-dots", view: 16.0, body: r#"<path d="M5 8C5 8.55228 4.55228 9 4 9C3.44772 9 3 8.55228 3 8C3 7.44772 3.44772 7 4 7C4.55228 7 5 7.44772 5 8Z" fill="currentColor"/><path d="M9 8C9 8.55228 8.55228 9 8 9C7.44772 9 7 8.55228 7 8C7 7.44772 7.44772 7 8 7C8.55228 7 9 7.44772 9 8Z" fill="currentColor"/><path d="M13 8C13 8.55228 12.5523 9 12 9C11.4477 9 11 8.55228 11 8C11 7.44772 11.4477 7 12 7C12.5523 7 13 7.44772 13 8Z" fill="currentColor"/>"# }; +pub static OUTLINE_EXPAND: Icon = Icon { name: "outline-expand", view: 16.0, body: r#"<path d="M3.5 8V12.25C3.5 12.3881 3.61193 12.5 3.75 12.5H8" stroke-linecap="round" stroke="currentColor"/><path d="M12.5 8L12.5 3.75C12.5 3.61193 12.3881 3.5 12.25 3.5L8 3.5" stroke-linecap="round" stroke="currentColor"/>"# }; +pub static FILETREE: Icon = Icon { name: "filetree", view: 16.0, body: r#"<path d="M2.5 1.5V12.2484H6.75M2.5 4.74838H6.75" stroke="currentColor"/><rect x="8.5" y="3.2168" width="6" height="3" fill="none" stroke="currentColor"/><rect x="8.5" y="10.75" width="6" height="3" fill="none" stroke="currentColor"/>"# }; +pub static SPLIT: Icon = Icon { name: "split", view: 16.0, body: r#"<path d="M14.5 13.5H1.5V2.5H14.5V13.5Z" stroke-linecap="round" stroke-linejoin="round" stroke="currentColor"/><rect opacity="0.5" x="3" y="4" width="4" height="8" fill="currentColor"/><rect opacity="0.5" x="9" y="4" width="4" height="8" fill="currentColor"/>"# }; +pub static UNIFIED: Icon = Icon { name: "unified", view: 16.0, body: r#"<path d="M14.5 13.5H1.5V2.5H14.5V13.5Z" stroke-linecap="round" stroke-linejoin="round" stroke="currentColor"/><rect opacity="0.5" x="3" y="4" width="10" height="3" fill="currentColor"/><rect opacity="0.5" x="3" y="9" width="10" height="3" fill="currentColor"/>"# }; +pub static WINDOW_ANALYTICS: Icon = Icon { name: "window-analytics", view: 16.0, body: r#"<path d="M6.5 2.5H1.5V13.5H14.5V10.5M9.5 2.5H14.5V7.5H9.5V2.5Z" stroke-linecap="round" stroke-linejoin="round" stroke="currentColor"/>"# }; +pub static OUTLINE_CODE_BRACKETS: Icon = Icon { name: "outline-code-brackets", view: 16.0, body: r#"<path d="M5 4L1 8L5 12M11 4L15 8L11 12M9 1L7 15" stroke="currentColor"/>"# }; +pub static OUTLINE_QUOTE: Icon = Icon { name: "outline-quote", view: 16.0, body: r#"<path d="M9.5 8.49927C10.8333 8.49927 12.1667 8.49927 13.5 8.49927C13.5 9.74927 13.5 11.2493 13.5 12.4993C12.1667 12.4993 10.8333 12.4993 9.5 12.4993V7C9.5 5 10.5 3.5 13 3.5001" stroke="currentColor"/><path d="M2.5 8.49927C3.83333 8.49927 5.16667 8.49927 6.5 8.49927C6.5 9.74927 6.5 11.2493 6.5 12.4993C5.16667 12.4993 3.83333 12.4993 2.5 12.4993V7C2.5 5 3.5 3.5 6 3.5001" stroke="currentColor"/>"# }; +pub static OUTLINE_ARROW_UP_RIGHT: Icon = Icon { name: "outline-arrow-up-right", view: 16.0, body: r#"<path d="M12.5 3.5L3.5 12.5M12.5 9.62L12.5 3.5L6.38 3.5" stroke="currentColor"/>"# }; +pub static OUTLINE_ROTATE_CLOCKWISE: Icon = Icon { name: "outline-rotate-clockwise", view: 16.0, body: r#"<path d="M14.1992 8C14.1992 9.18669 13.8473 10.3467 13.188 11.3334C12.5288 12.3201 11.5917 13.0892 10.4953 13.5433C9.39897 13.9974 8.19257 14.1162 7.02868 13.8847C5.86479 13.6532 4.7957 13.0818 3.95658 12.2426C3.11747 11.4035 2.54602 10.3344 2.31451 9.17054C2.083 8.00666 2.20182 6.80026 2.65594 5.7039C3.11007 4.60754 3.87911 3.67047 4.8658 3.01118C5.85249 2.35189 7.01253 2 8.19922 2C9.87922 2 11.4859 2.66667 12.6926 3.82667L14.1992 5.33333M10.866 5.33333L14.1992 5.33333L14.1993 2" stroke="currentColor" stroke-linecap="square" stroke-linejoin="round"/>"# }; +pub static OUTLINE_GLOBE_PLUS: Icon = Icon { name: "outline-globe-plus", view: 16.0, body: r#"<path d="M9.5 11.5H12.5M12.5 11.5H15.5M12.5 11.5V8.5M12.5 11.5V14.5" stroke-linecap="round" stroke-linejoin="round" stroke="currentColor"/><path d="M8 1C11.866 1 15 4.13401 15 8C15 8.11231 14.9964 8.22395 14.9912 8.33496C14.9358 7.48617 14.4589 6.75503 13.7656 6.34668C13.1525 4.20296 11.3791 2.55021 9.16602 2.11426C10.0489 3.35264 10.6663 4.93158 10.8975 6.58105C10.3489 7.03965 10 7.72909 10 8.5H6.01465C6.13241 10.6267 6.98934 12.6854 8.20996 13.9941C8.44758 13.986 8.68133 13.9618 8.91113 13.9268C9.10021 13.9725 9.29688 14 9.5 14H10V14.5C10 14.5691 10.0043 14.6374 10.0098 14.7051C9.37302 14.8957 8.69876 15 8 15C4.13401 15 1 11.866 1 8C1 4.13401 4.13401 1 8 1ZM2.02246 8.5C2.24434 11.1886 4.23728 13.3729 6.83301 13.8848C5.78755 12.4178 5.11145 10.4737 5.0127 8.5H2.02246ZM6.83301 2.11426C4.23719 2.62603 2.24434 4.81135 2.02246 7.5H5.0127C5.11147 5.52603 5.78728 3.58126 6.83301 2.11426ZM8 2.24219C6.89188 3.55495 6.12676 5.49755 6.01562 7.5H9.98438C9.87324 5.49755 9.10812 3.55495 8 2.24219Z" fill="currentColor"/>"# }; +pub static OUTLINE_COOKIE: Icon = Icon { name: "outline-cookie", view: 16.0, body: r#"<path d="M14 8.5A6 6 0 1 1 7.5 2a2 2 0 0 0 2.5 2.5 2 2 0 0 0 2.5 2.5c.4.6.9 1.1 1.5 1.5Z" stroke="currentColor" stroke-linejoin="round"/><path d="M5.5 6.5h.01M5.5 10h.01M8.5 9h.01M10.5 11.5h.01" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"/>"# }; +pub static ARROW_UP_RIGHT: Icon = Icon { name: "arrow-up-right", view: 16.0, body: r#"<path d="M11 9.56V5H6.44M11 5L5 11" stroke="currentColor"/>"# }; +pub static OUTLINE_SQUARE_ARROW: Icon = Icon { name: "outline-square-arrow", view: 16.0, body: r#"<path d="M5.5 2.5H2.5V13.5H13.5V10.5M8.5 7.5L13.5 2.5M13.5 7.5V2.5H8.5" stroke-linecap="round" stroke-linejoin="round" stroke="currentColor"/>"# }; +pub static OUTLINE_ARROW_TO_CORNER_TOP_RIGHT: Icon = Icon { name: "outline-arrow-to-corner-top-right", view: 16.0, body: r#"<path d="M2 8.5V2H14V14H8M5 5.66667H10.3333V11M3.66797 12.333L9.94292 6.05806" stroke="currentColor" stroke-linecap="square"/>"# }; +pub static OUTLINE_MAXIMIZE: Icon = Icon { name: "outline-maximize", view: 16.0, body: r#"<path d="M2.5 6V2.5H6M10 2.5H13.5V6M13.5 10V13.5H10M6 13.5H2.5V10" stroke="currentColor" stroke-linecap="square"/>"# }; +pub static OUTLINE_HEXAGONAL_WARNING: Icon = Icon { name: "outline-hexagonal-warning", view: 16.0, body: r#"<path d="M10.6667 1.33325H5.33272L1.33334 5.33325L1.33342 10.6917L5.3327 14.691L10.6667 14.6909L14.6911 10.6917V5.33255L10.6667 1.33325Z" stroke="currentColor"/><path d="M8 10.6667H8.00667" stroke="currentColor" stroke-linecap="square"/><path d="M8 7.99992V5.33325" stroke="currentColor" stroke-linecap="square"/>"# }; +pub static OUTLINE_SHARE: Icon = Icon { name: "outline-share", view: 16.0, body: r#"<path d="M13.5554 10.4445V13.5556C13.5554 13.5556 12.7599 13.5556 11.7777 13.5556H4.22211C3.23989 13.5556 2.44434 13.5556 2.44434 13.5556V10.4445M4.88878 5.55557L7.99989 2.44446L11.111 5.55557M7.99989 2.44446L7.99989 9.11112" stroke="currentColor"/>"# }; +pub static OUTLINE_EYE_SLASH: Icon = Icon { name: "outline-eye-slash", view: 16.0, body: r#"<path d="M8 9.5V11.5M13 7.70453C12.3728 8.24287 11.6002 8.73156 10.6609 9.06269C9.8902 9.33437 9.00721 9.5 8 9.5M8 9.5C6.99279 9.5 6.1098 9.33437 5.33912 9.06269M10.6609 9.06269L11.5 11M5.33912 9.06269L4.5 11M1.5 6C1.86147 6.5422 2.3536 7.14974 3 7.70453C3.62725 8.24287 4.39976 8.73156 5.33912 9.06269M14.5 6C14.1385 6.5422 13.6464 7.14974 13 7.70453M13 7.70453L14.5 9.06269M3 7.70453L1.5 9.06269" stroke-linecap="round" stroke-linejoin="round" stroke="currentColor"/>"# }; +pub static REFRESH: Icon = Icon { name: "refresh", view: 20.0, body: r#"<path d="M16.25 7.5A6.5 6.5 0 1 0 16.5 11M16.25 3.5v4h-4" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round"/>"# }; +pub static FILL_TRIANGLE_DOWN: Icon = Icon { name: "fill-triangle-down", view: 16.0, body: r#"<path d="M5.37624 6.75194C5.18184 6.41861 5.42224 6 5.80814 6H10.1921C10.578 6 10.8184 6.41861 10.624 6.75194L8.43203 10.5096C8.23909 10.8404 7.76119 10.8404 7.56825 10.5096L5.37624 6.75194Z" fill="currentColor"/>"# }; +pub static WAVEFORM: Icon = Icon { name: "waveform", view: 16.0, body: r#"<path d="M2 7V9M4.5 5V11M7 2.5V13.5M9.5 4.5V11.5M12 6V10M14.5 7.25V8.75" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"/>"# }; +pub static OUTLINE_STEER: Icon = Icon { name: "outline-steer", view: 16.0, body: r#"<path d="M8 14C11.3137 14 14 11.3137 14 8C14 4.68634 11.3137 2 8 2C4.68626 2 2 4.68634 2 8C2 11.3137 4.68626 14 8 14Z" stroke-linecap="round" stroke-linejoin="round" stroke="currentColor"/><path d="M8 3.86328V12.1391C10.2854 12.1391 12.1379 10.2863 12.1379 8.00121C12.1379 5.71608 10.2854 3.86328 8 3.86328Z" fill="currentColor"/>"# }; +pub static OUTLINE_WAVE_AUDIO: Icon = Icon { name: "outline-wave-audio", view: 16.0, body: r#"<path d="M14.5 8.01193V8" stroke-linecap="square" stroke="currentColor"/><path d="M1.5 8.00607V7.99414" stroke-linecap="square" stroke="currentColor"/><path d="M3.66699 10.5141V5.48438" stroke-linecap="square" stroke="currentColor"/><path d="M10.167 10.5141V5.48438" stroke-linecap="square" stroke="currentColor"/><path d="M8 11.6004V4.39844" stroke-linecap="square" stroke="currentColor"/><path d="M12.333 9.20144V6.80078" stroke-linecap="square" stroke="currentColor"/><path d="M5.83301 13.5323V2.4668" stroke-linecap="square" stroke="currentColor"/>"# }; +pub static OUTLINE_TEXT: Icon = Icon { name: "outline-text", view: 14.0, body: r#"<path d="M6.99997 11.5938V2.40625M6.99997 11.5938H9.04164M6.99997 11.5938H4.95831M6.99997 2.40625H2.40622V4.95833M6.99997 2.40625H11.5937V4.95833" stroke="currentColor"/>"# }; +pub static OUTLINE_PHOTO: Icon = Icon { name: "outline-photo", view: 14.0, body: r#"<path d="M11.6666 11.6666L8.16663 8.16663L6.99997 9.33332L4.66663 6.99998L2.1583 9.50832M2.04163 2.04165H11.9583V11.9583H2.04163V2.04165ZM9.33332 5.24998C9.33332 5.81377 8.87629 6.27081 8.31244 6.27081C7.74866 6.27081 7.29163 5.81377 7.29163 5.24998C7.29163 4.68619 7.74866 4.22915 8.31244 4.22915C8.87629 4.22915 9.33332 4.68619 9.33332 5.24998Z" stroke="currentColor" stroke-linecap="square"/>"# }; +pub static FILE_DOCUMENT: Icon = Icon { name: "file-document", view: 16.0, body: r#"<path d="M3.5 13.25V2.75C3.5 2.61193 3.61193 2.5 3.75 2.5H8.39645C8.46275 2.5 8.52634 2.52634 8.57322 2.57322L12.4268 6.42678C12.4737 6.47366 12.5 6.53725 12.5 6.60355V13.25C12.5 13.3881 12.3881 13.5 12.25 13.5H3.75C3.61193 13.5 3.5 13.3881 3.5 13.25Z" stroke-linecap="round" stroke="currentColor"/>"# }; +pub static OUTLINE_AUDIO: Icon = Icon { name: "outline-audio", view: 14.0, body: r#"<path d="M2.29546 5.62775V8.37207M5.4318 1.96875V12.0312M8.56815 4.40801V9.59173M11.7045 5.62775V8.37207" stroke="currentColor" stroke-linecap="square"/>"# }; +pub static OUTLINE_VIDEO: Icon = Icon { name: "outline-video", view: 14.0, body: r#"<path d="M10.7412 7L3.99997 11.333V2.66602L10.7412 7Z" stroke="currentColor"/>"# }; +pub static OUTLINE_BRAIN: Icon = Icon { name: "outline-brain", view: 14.0, body: r#"<path d="M6.99997 3.5C6.99997 2.53322 7.7832 1.75 8.74997 1.75C9.71675 1.75 10.5 2.53322 10.5 3.5C10.5 3.57233 10.4875 3.64156 10.479 3.71156C11.4706 3.80022 12.25 4.62389 12.25 5.63889C12.25 6.43222 11.7732 7.11278 11.0919 7.41456C11.55 7.68522 11.8611 8.17911 11.8611 8.75C11.8611 9.54956 11.2552 10.2006 10.479 10.2884C10.4875 10.3584 10.5 10.4277 10.5 10.5C10.5 11.4668 9.71675 12.25 8.74997 12.25C7.7832 12.25 6.99997 11.4668 6.99997 10.5M6.99997 3.5C6.99997 2.53322 6.21675 1.75 5.24997 1.75C4.2832 1.75 3.49997 2.53322 3.49997 3.5C3.49997 3.57233 3.51241 3.64156 3.52097 3.71156C2.5293 3.80022 1.74997 4.62389 1.74997 5.63889C1.74997 6.43222 2.22675 7.11278 2.90808 7.41456C2.44997 7.68522 2.13886 8.17911 2.13886 8.75C2.13886 9.54956 2.74474 10.2006 3.52097 10.2884C3.51241 10.3584 3.49997 10.4277 3.49997 10.5C3.49997 11.4668 4.2832 12.25 5.24997 12.25C6.21675 12.25 6.99997 11.4668 6.99997 10.5M6.99997 3.5V10.5M4.27773 7.58334H3.6944C3.41362 7.58334 3.14607 7.52345 2.90496 7.4169M11.095 7.4169C10.8539 7.52345 10.5863 7.58334 10.3055 7.58334H9.7222" stroke="currentColor" stroke-linecap="square"/>"# }; +pub static CLOSE_SMALL: Icon = Icon { name: "close-small", ..CLOSE }; +pub static XMARK_SMALL: Icon = Icon { name: "xmark-small", ..CLOSE }; +pub static OUTLINE_XMARK: Icon = Icon { name: "outline-xmark", ..CLOSE }; +pub static CIRCLE_XMARK: Icon = Icon { name: "circle-xmark", ..CLOSE }; +pub static CHECK_SMALL: Icon = Icon { name: "check-small", ..CHECK }; +pub static OUTLINE_COPY: Icon = Icon { name: "outline-copy", ..COPY }; +pub static CODE_SLASH: Icon = Icon { name: "code-slash", ..CODE }; +pub static OUTLINE_SLIDERS: Icon = Icon { name: "outline-sliders", ..SLIDERS }; +pub static OUTLINE_TRASH: Icon = Icon { name: "outline-trash", ..TRASH }; +pub static OUTLINE_GLOBE: Icon = Icon { name: "outline-globe", ..GLOBE }; +pub static ARROW_UNDO_DOWN: Icon = Icon { name: "arrow-undo-down", ..ENTER }; +pub static OUTLINE_RESET: Icon = Icon { name: "outline-reset", ..RESET }; +pub static OUTLINE_UNDO: Icon = Icon { name: "outline-undo", ..RESET }; +pub static WINDOW_CURSOR: Icon = Icon { name: "window-cursor", ..SELECT_ELEMENT }; +pub static OUTLINE_BROWSER_ANNOTATE: Icon = Icon { name: "outline-browser-annotate", ..SELECT_ELEMENT }; +pub static GRADUATION_CAP: Icon = Icon { name: "graduation-cap", ..POST_SKILL }; +pub static OUTLINE_EYE: Icon = Icon { name: "outline-eye", ..EYE }; +pub static BRANCH_OUT: Icon = Icon { name: "branch-out", ..OUTLINE_WORKTREE }; +pub static PLUS_SMALL: Icon = Icon { name: "plus-small", ..PLUS }; +pub static DASH: Icon = Icon { name: "dash", ..MINUS }; +pub static DASH_BOLD: Icon = Icon { name: "dash-bold", view: 16.0, body: r#"<path d="M2.5 8H13.5" stroke-linecap="round" stroke-linejoin="round" stroke="currentColor" stroke-width="1.5"/>"# }; +pub static FILE_TREE: Icon = Icon { name: "file-tree", ..FOLDER }; +pub static BUBBLE_5: Icon = Icon { name: "bubble-5", ..COMMENT }; +pub static SPEECH_BUBBLE: Icon = Icon { name: "speech-bubble", ..COMMENT }; +pub static SQUARE_ARROW_TOP_RIGHT: Icon = Icon { name: "square-arrow-top-right", ..OUTLINE_SQUARE_ARROW }; +pub static CONSOLE: Icon = Icon { name: "console", ..TERMINAL }; +pub static OUTLINE_CONSOLE: Icon = Icon { name: "outline-console", ..TERMINAL }; +pub static OUTLINE_CHEVRON_DOWN: Icon = Icon { name: "outline-chevron-down", ..CHEVRON_DOWN }; +pub static OUTLINE_CHEVRON_RIGHT: Icon = Icon { name: "outline-chevron-right", ..CHEVRON_RIGHT }; +pub static OUTLINE_ARROW_LEFT: Icon = Icon { name: "outline-arrow-left", ..ARROW_LEFT }; +pub static OUTLINE_ARROW_RIGHT: Icon = Icon { name: "outline-arrow-right", ..ARROW_RIGHT }; +pub static TEXT_WRAP: Icon = Icon { name: "text-wrap", view: 16.0, body: r#"<path d="M1.5 3.5H14.5M1.5 8H11.5C12.8807 8 14 9.11929 14 10.5C14 11.8807 12.8807 13 11.5 13H8.5M10 11.5L8.5 13L10 14.5M1.5 12.5H5" stroke-linecap="round" stroke-linejoin="round" stroke="currentColor"/>"# }; + +/// Every icon by its catalog name, for a gallery or a name read from data. +pub static ALL: &[&Icon] = &[ + &ALIGN_RIGHT, + &ARROW_UP, + &ARROW_LEFT, + &ARROW_RIGHT, + &ARCHIVE, + &PROMPT, + &BRAIN, + &FORK, + &WORKSPACE_ISOLATED, + &BULLET_LIST, + &CHEVRON_DOWN, + &CHEVRON_LEFT, + &CHEVRON_RIGHT, + &CHEVRON_GRABBER_VERTICAL, + &CHEVRON_DOUBLE_RIGHT, + &CIRCLE_X, + &CLOSE, + &CHECKLIST, + &TERMINAL, + &TERMINAL_ACTIVE, + &REVIEW, + &REVIEW_ACTIVE, + &EXPAND, + &COLLAPSE, + &CODE, + &CODE_LINES, + &CIRCLE_BAN_SIGN, + &EDIT_SMALL_2, + &EYE, + &ENTER, + &FOLDER, + &FILE_TREE_ACTIVE, + &MAGNIFYING_GLASS, + &PLUS, + &NEW_SESSION, + &NEW_SESSION_ACTIVE, + &PENCIL_LINE, + &MCP, + &GLASSES, + &MAGNIFYING_GLASS_MENU, + &TASK, + &STOP, + &STATUS, + &STATUS_ACTIVE, + &SIDEBAR, + &SIDEBAR_ACTIVE, + &LAYOUT_LEFT, + &LAYOUT_LEFT_PARTIAL, + &LAYOUT_LEFT_FULL, + &LAYOUT_RIGHT, + &LAYOUT_RIGHT_PARTIAL, + &LAYOUT_RIGHT_FULL, + &OPEN_FILE, + &COMMENT, + &FOLDER_ADD_LEFT, + &GITHUB, + &DISCORD, + &LAYOUT_BOTTOM, + &LAYOUT_BOTTOM_PARTIAL, + &LAYOUT_BOTTOM_FULL, + &DOT_GRID, + &CIRCLE_CHECK, + &COPY, + &CHECK, + &PHOTO, + &SHARE, + &SHIELD, + &DOWNLOAD, + &MENU, + &SERVER, + &BRANCH, + &EDIT, + &HELP, + &SETTINGS_GEAR, + &CLOUD_UPLOAD, + &TRASH, + &SLIDERS, + &KEYBOARD, + &SELECTOR, + &ARROW_DOWN_TO_LINE, + &WARNING, + &RESET, + &LINK, + &PROVIDERS, + &MODELS, + &APPEARANCE, + &NOTIFICATIONS, + &EXTENSIONS, + &CUBE, + &POST_SKILL, + &OUTLINE_LIST_CHANGELOG, + &OUTLINE_PAIR, + &LOCK, + &GLOBE, + &SELECT_ELEMENT, + &FLASK, + &GRID_PLUS, + &INFO, + &CIRCLE_EXCLAMATION, + &OUTLINE_MAGNIFIER_MINUS, + &OUTLINE_MAGNIFIER_PLUS, + &MINUS, + &MONITOR, + &WORKSPACE_NEW, + &WORKSPACE, + &OUTLINE_WORKTREE, + &OUTLINE_DOTS, + &OUTLINE_EXPAND, + &FILETREE, + &SPLIT, + &UNIFIED, + &WINDOW_ANALYTICS, + &OUTLINE_CODE_BRACKETS, + &OUTLINE_QUOTE, + &OUTLINE_ARROW_UP_RIGHT, + &OUTLINE_ROTATE_CLOCKWISE, + &OUTLINE_GLOBE_PLUS, + &OUTLINE_COOKIE, + &ARROW_UP_RIGHT, + &OUTLINE_SQUARE_ARROW, + &OUTLINE_ARROW_TO_CORNER_TOP_RIGHT, + &OUTLINE_MAXIMIZE, + &OUTLINE_HEXAGONAL_WARNING, + &OUTLINE_SHARE, + &OUTLINE_EYE_SLASH, + &REFRESH, + &FILL_TRIANGLE_DOWN, + &WAVEFORM, + &OUTLINE_STEER, + &OUTLINE_WAVE_AUDIO, + &OUTLINE_TEXT, + &OUTLINE_PHOTO, + &FILE_DOCUMENT, + &OUTLINE_AUDIO, + &OUTLINE_VIDEO, + &OUTLINE_BRAIN, + &CLOSE_SMALL, + &XMARK_SMALL, + &OUTLINE_XMARK, + &CIRCLE_XMARK, + &CHECK_SMALL, + &OUTLINE_COPY, + &CODE_SLASH, + &OUTLINE_SLIDERS, + &OUTLINE_TRASH, + &OUTLINE_GLOBE, + &ARROW_UNDO_DOWN, + &OUTLINE_RESET, + &OUTLINE_UNDO, + &WINDOW_CURSOR, + &OUTLINE_BROWSER_ANNOTATE, + &GRADUATION_CAP, + &OUTLINE_EYE, + &BRANCH_OUT, + &PLUS_SMALL, + &DASH, + &FILE_TREE, + &BUBBLE_5, + &SPEECH_BUBBLE, + &SQUARE_ARROW_TOP_RIGHT, + &CONSOLE, + &OUTLINE_CONSOLE, + &OUTLINE_CHEVRON_DOWN, + &OUTLINE_CHEVRON_RIGHT, + &OUTLINE_ARROW_LEFT, + &OUTLINE_ARROW_RIGHT, + &TEXT_WRAP, +]; diff --git a/app/vendor/rune/themes/opencode/src/lib.rs b/app/vendor/rune/themes/opencode/src/lib.rs new file mode 100644 index 0000000..b2c7d44 --- /dev/null +++ b/app/vendor/rune/themes/opencode/src/lib.rs @@ -0,0 +1,323 @@ +//! OpenCode's design language as a Rune theme: `@opencode/ui`'s tokens (as the browser resolves +//! them, `assets/theme.json`, regenerated by `tools/theme.mjs`), its fonts and its icon catalog, +//! mapped onto rune-kit's semantic schema. Nothing here is compiled into Rune's core. +//! +//! ```ignore +//! let k = rune_theme_opencode::kit(cx.system_dark()); +//! rune_kit::Button::new("Save").build(k) +//! ``` + +#![forbid(unsafe_code)] + +pub mod app_icons; +pub mod file_icons; +pub mod icons; +pub mod provider_icons; +pub mod tree_icons; + +use std::sync::OnceLock; + +use rune::{Color, TextStyle, Theme}; +use rune_kit::{Elevation, Glyphs, Kit, Motion, Palette, Radius, StateColors, Type, css, glyphs}; +use serde_json::Value; + +/// The theme as data: palette, light and dark tokens, computed shadows and numbers. +pub const THEME: &str = include_str!("../assets/theme.json"); + +/// Inter (variable) and IBM Plex Mono, for `AppSpec::fonts`. +pub const FONTS: &[&[u8]] = &[ + include_bytes!("../assets/fonts/InterVariable.ttf"), + include_bytes!("../assets/fonts/IBMPlexMono-Regular.ttf"), + include_bytes!("../assets/fonts/IBMPlexMono-Medium.ttf"), +]; + +/// `AppSpec::families`: (sans, mono). +pub const FAMILIES: (&str, &str) = ("Inter", "IBM Plex Mono"); + +/// The resolved `rune::Theme` for one appearance (every `--*` colour token by name, without `--`). +/// Translucent tokens resolve for the current blend mode as they are read (`rune::theme::blends_srgb`). +pub fn theme(dark: bool) -> &'static Theme { + static DARK: OnceLock<Theme> = OnceLock::new(); + static LIGHT: OnceLock<Theme> = OnceLock::new(); + let load = || Theme::from_value(document(), dark).unwrap_or_else(|e| panic!("{e}")); + if dark { DARK.get_or_init(load) } else { LIGHT.get_or_init(load) } +} + +/// `theme.json`, parsed once for both appearances and the kit's shadows. +fn document() -> &'static Value { + static DOC: OnceLock<Value> = OnceLock::new(); + DOC.get_or_init(|| serde_json::from_str(THEME).expect("theme.json")) +} + +/// The brand's hot colour for one appearance: ember step 9, for marks like a logo or a +/// highlight that should read as the brand rather than the interactive accent. +pub fn brand(dark: bool) -> Color { + ember(dark, 9) +} + +/// One step of the ember scale for one appearance, the same colour as the token +/// `ember-dark-<step>` or `ember-light-<step>`. `step` is 1 to 12; anything else panics. +#[track_caller] +pub fn ember(dark: bool, step: u8) -> Color { + scale("ember", dark, step) +} + +/// One step (1 to 12, else panics) of a named colour scale (`"amber"`, `"apple"`, `"blue"`, +/// `"cobalt"`, `"coral"`, `"ember"`, `"gray"`, `"ink"`, `"lilac"`, `"mint"`, `"smoke"`, +/// `"solaris"`, `"yuzu"`): the token `<name>-dark-<step>` or `<name>-light-<step>`. Panics if +/// the theme has no such token. +#[track_caller] +pub fn scale(name: &str, dark: bool, step: u8) -> Color { + assert!((1..=12).contains(&step), "colour scale steps run 1 to 12, got {step}"); + theme(dark).color(&format!("{name}-{}-{step}", if dark { "dark" } else { "light" })) +} + +/// Token `name` as the theme authors it, without sRGB re-solving: translucent tokens keep their +/// authored alpha. +#[track_caller] +fn authored(dark: bool, name: &str) -> Color { + theme(dark).authored(name).unwrap_or_else(|| panic!("theme.json has no {name:?}")) +} + +/// The kit tokens for one appearance, resolved for the blend mode of the window building the +/// view (`rune::theme::blends_srgb`): translucent tokens as authored when it blends in sRGB, +/// re-solved over `bg_base` when it blends in linear light. Get it in the view rather than +/// keeping it across a `Tx::set_srgb_blend`. +pub fn kit(dark: bool) -> &'static Kit { + static KITS: [[OnceLock<Kit>; 2]; 2] = [const { [const { OnceLock::new() }; 2] }; 2]; + let srgb = rune::theme::blends_srgb(); + KITS[dark as usize][srgb as usize].get_or_init(|| rune::theme::with_blend(srgb, || build(dark))) +} + +/// Inter at a variable weight with the kit's tracking (`-0.04px` at 13, `0.05px` at 11). +const fn inter(size: f32, weight: f32, line: f32, tracking: f32) -> TextStyle { + TextStyle::new(size, weight).lh(line).tracking(tracking) +} + +pub const GLYPHS: Glyphs = Glyphs { + copy: &icons::COPY, + search: &icons::MAGNIFYING_GLASS, + circle_x: &icons::CIRCLE_X, + triangle_down: &icons::FILL_TRIANGLE_DOWN, + clear: &icons::XMARK_SMALL, + close: &icons::CLOSE, + ..glyphs::DEFAULT +}; + +fn build(dark: bool) -> Kit { + let t = theme(dark); + let c = |n: &str| t.color(n); + let v = |n: &str| t.color(&format!("v2-{n}")); + let raw = |n: &str| authored(dark, &format!("v2-{n}")); + let state = |n: &str, icon: Color| StateColors { + bg: v(&format!("state-bg-{n}")), + fg: v(&format!("state-fg-{n}")), + border: v(&format!("state-border-{n}")), + icon, + }; + let blend = v("background-bg-base"); + let solve = |x: Color| rune::theme::for_blend(x, blend); + let data = document(); + let mode = if dark { "dark" } else { "light" }; + let sh = |n: &str| { + let src = data["shadows"][mode][n].as_str().unwrap_or_else(|| panic!("theme.json has no {mode} shadow {n:?}")); + css::box_shadows(src, solve) + }; + let opaque = |n: &str| t.color(n).alpha(1.0); + // Tokens some components read but the kit never defines resolve as CSS does: no colour + // (transparent backgrounds) or the inherited text colour. + let or = |n: &str, fallback: Color| t.try_color(n).unwrap_or(fallback); + let palette = Palette { + page: c("background-base"), + bg_base: blend, + bg_deep: v("background-bg-deep"), + layer_01: v("background-bg-layer-01"), + layer_02: v("background-bg-layer-02"), + layer_03: v("background-bg-layer-03"), + layer_04: v("background-bg-layer-04"), + bg_inverse: v("background-bg-inverse"), + bg_contrast: v("background-bg-contrast"), + bg_button_neutral: v("background-bg-button-neutral"), + bg_icon_button_contrast: v("background-bg-icon-button-contrast"), + bg_accent: v("background-bg-accent"), + submit_highlight: if dark { raw("alpha-light-60") } else { raw("alpha-light-20") }, + submit_hover: if dark { raw("alpha-dark-8") } else { raw("overlay-simple-overlay-contrast-hover") }, + submit_fg: if dark { v("text-text-inverse") } else { v("text-text-contrast") }, + submit_icon: if dark { v("icon-icon-inverse") } else { v("text-text-contrast") }, + text_base: v("text-text-base"), + text_muted: v("text-text-muted"), + text_faint: v("text-text-faint"), + text_inverse: v("text-text-inverse"), + text_contrast: v("text-text-contrast"), + text_accent: v("text-text-accent"), + icon_base: v("icon-icon-base"), + icon_muted: v("icon-icon-muted"), + icon_faint: v("icon-icon-faint"), + icon_inverse: v("icon-icon-inverse"), + icon_contrast: v("icon-icon-contrast"), + icon_accent: v("icon-icon-accent"), + border_muted: v("border-border-muted"), + border_base: v("border-border-base"), + border_strong: v("border-border-strong"), + border_focus: v("border-border-focus"), + hover: v("overlay-simple-overlay-hover"), + pressed: v("overlay-simple-overlay-pressed"), + contrast_hover: raw("overlay-simple-overlay-contrast-hover"), + contrast_pressed: raw("overlay-simple-overlay-contrast-pressed"), + scrim: v("overlay-simple-overlay-scrim"), + depth_top: raw("overlay-gradient-depth-overlay-depth-top"), + depth_bottom: raw("overlay-gradient-depth-overlay-depth-bot"), + white: opaque("v2-alpha-light-100"), + black: opaque("v2-alpha-dark-100"), + knob: v("grey-200"), + knob_on: v("grey-300"), + success: state("success", c("icon-success-active")), + warning: state("warning", c("icon-warning-active")), + danger: state("danger", v("state-fg-danger")), + info: state("info", c("icon-info-active")), + surface_base: c("surface-base"), + surface_weak: c("surface-weak"), + surface_hover: or("surface-hover", Color::TRANSPARENT), + surface_raised: c("surface-raised-stronger-non-alpha"), + surface_raised_base: c("surface-raised-base"), + surface_raised_hover: c("surface-raised-base-hover"), + surface_float: c("surface-float-base"), + surface_disabled: or("surface-disabled", Color::TRANSPARENT), + border_weak: c("border-weak-base"), + border_hover: c("border-hover"), + border_active: c("border-active"), + border_disabled: c("border-disabled"), + text_strong: c("text-strong"), + text_weak: c("text-weak"), + text_invert_strong: c("text-invert-strong"), + icon_weaker: or("icon-weaker", c("text-base")), + std_border: c("border-base"), + std_icon: c("icon-base"), + std_icon_invert: c("icon-invert-base"), + std_icon_strong: c("icon-strong-base"), + std_text: c("text-base"), + }; + let mut elevation = Elevation::default().with_input(sh("v2-elevation-input")); + elevation.raised = sh("v2-elevation-raised"); + elevation.floating = sh("v2-elevation-floating"); + elevation.overlay = sh("v2-elevation-overlay"); + elevation.button_neutral = sh("v2-elevation-button-neutral"); + elevation.button_contrast = sh("v2-elevation-button-contrast"); + elevation.elements = sh("v2-elevation-elements"); + elevation.switch_off = sh("v2-elevation-switch-off"); + elevation.switch_on = sh("v2-elevation-switch-on"); + elevation.md = sh("shadow-md"); + // switch.css, standard appearance: rgba(19, 16, 16, .04/.06/.08). + elevation.knob = css::box_shadows("#1310100a 0px 1px 2px -1px, #1310100f 0px 1px 2px 0px, #13101014 0px 1px 3px 0px", solve); + // `line-height-large` is 150%; the older text styles derive their line from it. + let ty = Type { + ui: inter(13.0, 440.0, 20.0, -0.04), + ui_medium: inter(13.0, 530.0, 20.0, -0.04), + ui_compact: inter(13.0, 440.0, 16.0, -0.04), + small: inter(11.0, 440.0, 12.0, 0.05), + small_medium: inter(11.0, 530.0, 12.0, 0.05), + body: inter(14.0, 400.0, 21.0, 0.0), + body_medium: inter(14.0, 500.0, 21.0, 0.0), + text_small: inter(13.0, 400.0, 19.5, 0.0), + text_small_medium: inter(13.0, 500.0, 19.5, 0.0), + text_xsmall: inter(12.0, 400.0, 18.0, 0.0), + text_xsmall_medium: inter(12.0, 500.0, 18.0, 0.0), + mono: TextStyle::new(12.0, 400.0).mono().lh(18.0), + }; + Kit { + dark, + c: palette, + elevation, + glyph: GLYPHS, + ty, + radius: Radius { xs: 2.0, sm: 4.0, md: 6.0, lg: 8.0, xl: 10.0 }, + // The web's 85–170 ms ease-outs, as critically damped springs of similar feel. + motion: Motion { + control: rune::Spring::new(0.2, 0.0), + overlay: rune::Spring::new(0.24, 0.0), + disclosure: rune::Spring::new(0.3, 0.0), + }, + blend_over: Some(blend), + ring: None, + invalid_text: true, + forced: None, + } +} + +#[cfg(test)] +mod tests { + #[test] + fn provider_marks_are_square_tintable_icons() { + use super::provider_icons::{FALLBACK, NAMES, named}; + assert!(NAMES.contains(&"anthropic") && NAMES.contains(&"openai")); + for id in NAMES { + let icon = named(id).unwrap_or_else(|| panic!("no mark for {id}")); + assert_eq!(icon.name, *id); + // A few marks paint in their own colours, as Desktop draws them. + let paints = icon.body.contains("currentColor") || icon.body.contains("fill=\"#"); + assert!(icon.view > 0.0 && paints, "{id} takes the text colour or its own"); + assert!(!icon.body.contains("transform") && !icon.body.contains("<g"), "{id} is flat"); + } + assert!(named("not-a-provider").is_none()); + assert_eq!(FALLBACK.name, "synthetic"); + } + + #[test] + fn both_appearances_resolve() { + for dark in [false, true] { + let k = super::kit(dark); + assert!(!k.elevation.button_neutral.is_empty()); + assert_eq!(k.dark, dark); + let b = super::brand(dark); + assert!(b.a > 0.99 && b.r > b.g && b.r > b.b, "ember is opaque and warm: {b:?}"); + } + } + + #[test] + fn translucent_tokens_follow_the_blend_mode() { + for dark in [false, true] { + let srgb = rune::theme::with_blend(true, || super::kit(dark)); + let linear = rune::theme::with_blend(false, || super::kit(dark)); + let authored = super::authored(dark, "v2-overlay-simple-overlay-hover"); + assert_eq!(srgb.c.hover, authored, "sRGB blending paints the authored alpha"); + assert_eq!(linear.c.hover, rune::theme::srgb_equivalent(authored, linear.c.bg_base)); + assert_ne!(linear.c.hover.a, authored.a); + assert!(std::ptr::eq(super::kit(dark), srgb), "windows blend in sRGB by default"); + // Shadows too: light's floating elevation is `#0000000a 0px 8px 16px 0px, #00000014 …`. + if !dark { + let alphas: Vec<u8> = srgb.elevation.floating.iter().map(|s| (s.color.a * 255.0).round() as u8).collect(); + assert_eq!(alphas[..3], [0x0a, 0x14, 0x1f], "sRGB blending paints the authored shadow alpha"); + } + } + } + + #[test] + fn ember_steps_match_the_token_strings() { + for dark in [false, true] { + let mode = if dark { "dark" } else { "light" }; + for step in 1..=12u8 { + assert_eq!(super::ember(dark, step), super::theme(dark).color(&format!("ember-{mode}-{step}"))); + } + assert_eq!(super::brand(dark), super::ember(dark, 9)); + assert_eq!(super::scale("blue", dark, 5), super::theme(dark).color(&format!("blue-{mode}-5"))); + } + } + + #[test] + #[should_panic(expected = "1 to 12")] + fn ember_rejects_step_zero() { + super::ember(true, 0); + } + + #[test] + #[should_panic(expected = "1 to 12")] + fn ember_rejects_step_thirteen() { + super::ember(false, 13); + } + + #[test] + #[should_panic(expected = "has no colour")] + fn scale_rejects_unknown_name() { + super::scale("unknown", true, 5); + } +} diff --git a/app/vendor/rune/themes/opencode/src/provider_icons.rs b/app/vendor/rune/themes/opencode/src/provider_icons.rs new file mode 100644 index 0000000..cde0474 --- /dev/null +++ b/app/vendor/rune/themes/opencode/src/provider_icons.rs @@ -0,0 +1,323 @@ +//! Generated by tools/provider-icons.py from @opencode/ui's provider marks. Do not edit. +use rune::Icon; + +static P302AI: Icon = Icon { name: "302ai", view: 2048.0, body: r##"<path d="M 388.193 1682.23 C 380.878 1674.23 349.014 1650.79 338.487 1642.13 C 148.161 1485.91 28.1107 1260.14 5.01063 1015 C -18.4493 771.014 55.9168 527.694 211.767 338.509 C 367.861 148.455 593.42 28.6444 838.288 5.7197 C 1092.75 -18.7181 1345.95 63.524 1537.48 232.828 C 1567.76 259.726 1596.32 288.496 1623 318.968 C 1631.78 329.058 1640.32 339.36 1648.6 349.865 C 1654.15 356.824 1662.64 368.871 1669.4 374.06 C 1866.4 518.124 1998.49 734.204 2036.88 975.222 C 2041.98 1007.66 2045.11 1039.38 2046.62 1072.12 C 2046.85 1077.09 2047.16 1082.22 2048 1087.12 L 2048 1155.79 L 2047.85 1156.71 C 2045.71 1170.93 2045.27 1196.57 2043.86 1212.22 C 2040.62 1246.59 2035.38 1280.75 2028.17 1314.51 C 1981.27 1534.16 1856.1 1729.25 1675.99 1863.43 C 1479.61 2010.02 1232.99 2072.49 990.498 2037.07 C 801.767 2009.86 626.135 1924.74 487.842 1793.46 C 455.956 1763.37 418.158 1722.72 392.022 1687.5 C 390.729 1685.76 389.452 1684 388.193 1682.23 z" fill="#9c9b9b"/><path d="M 1669.4 374.06 C 1866.4 518.124 1998.49 734.204 2036.88 975.222 C 2041.98 1007.66 2045.11 1039.38 2046.62 1072.12 C 2046.85 1077.09 2047.16 1082.22 2048 1087.12 L 2048 1155.79 L 2047.85 1156.71 C 2045.71 1170.93 2045.27 1196.57 2043.86 1212.22 C 2040.62 1246.59 2035.38 1280.75 2028.17 1314.51 C 1981.27 1534.16 1856.1 1729.25 1675.99 1863.43 C 1479.61 2010.02 1232.99 2072.49 990.498 2037.07 C 801.767 2009.86 626.135 1924.74 487.842 1793.46 C 455.956 1763.37 418.158 1722.72 392.022 1687.5 C 390.729 1685.76 389.452 1684 388.193 1682.23 C 394.373 1684.07 421.092 1702.62 428.047 1707.15 C 439.611 1714.6 451.324 1721.83 463.177 1728.82 C 490.564 1744.99 528.003 1763.59 557.361 1776.32 C 782.899 1873.92 1037.96 1878.01 1266.51 1787.69 C 1495.36 1696.62 1678.57 1518.24 1775.72 1291.9 C 1877.79 1053.06 1875.1 782.375 1768.31 545.611 C 1753.03 511.993 1733.8 474.565 1714.15 443.177 C 1706.81 431.355 1699.2 419.704 1691.32 408.231 C 1685.67 400.055 1672.56 382.889 1669.4 374.06 z" fill="#757474"/><path d="M 907.581 300.401 C 923.66 299.084 947.483 300.532 962.897 302.556 C 1041.39 313.102 1112.41 354.577 1160.17 417.755 C 1202.42 473.452 1228.57 555 1218.78 624.854 C 1256.03 619.819 1285.79 618.643 1323.38 625.442 C 1401.3 639.582 1470.3 684.357 1514.95 749.754 C 1560.04 815.479 1576.85 896.56 1561.6 974.792 C 1546.59 1052.29 1501.28 1120.59 1435.71 1164.55 C 1366.19 1211.67 1287.89 1223.85 1206.7 1207.99 L 1208.16 1225.92 C 1213.72 1304.44 1187.72 1381.94 1135.93 1441.23 C 1080.14 1505.71 1008.69 1536.8 924.661 1542.84 C 910.37 1543.02 898.883 1543.12 884.551 1541.84 C 806.009 1534.5 733.606 1496.24 683.294 1435.48 C 630.495 1371.76 609.152 1293.49 617.004 1211.82 C 577.182 1218.28 543.704 1219.15 503.598 1211.31 C 425.862 1195.87 357.514 1150.02 313.752 1083.94 C 269.997 1017.95 254.398 937.224 270.419 859.682 C 286.452 782.387 332.522 714.62 398.502 671.28 C 468.674 625.191 546.96 613.555 628.149 630.32 C 625.459 583.013 627.036 545.389 643.173 499.662 C 684.204 383.394 785.737 308.984 907.581 300.401 z" fill="#fefefe"/><path d="M 907.659 407.406 C 928.022 404.422 959.425 408.947 978.901 414.989 C 1028.11 429.972 1069.15 464.261 1092.65 510.025 C 1116.27 555.792 1120.24 609.2 1103.65 657.957 C 1098.74 672.384 1090.33 686.336 1086.3 699.186 C 1082.14 712.53 1083.57 726.994 1090.26 739.265 C 1100.24 757.657 1118.84 768.259 1139.57 767.119 C 1155.78 766.227 1164.63 759.273 1178.02 751.678 C 1221.56 726.903 1273.23 720.668 1321.41 734.376 C 1370.6 748.209 1412.18 781.215 1436.82 825.985 C 1461.35 870.569 1467.02 923.112 1452.58 971.905 C 1438.06 1020.82 1404.54 1061.88 1359.51 1085.9 C 1280.31 1128.12 1181.39 1108.75 1124.87 1039.74 C 1113.7 1026.12 1105.83 1013.42 1087.4 1008.03 C 1041 993.798 1000.36 1044.75 1026.36 1086.49 C 1041.95 1111.53 1062.76 1127.17 1078.18 1153.03 C 1090.26 1175.57 1097.84 1197.66 1100.84 1223.2 C 1107.04 1273.73 1092.65 1324.64 1060.9 1364.44 C 1029.42 1404.28 983.238 1429.79 932.752 1435.23 C 882.189 1440.86 831.491 1425.87 792.121 1393.65 C 752.588 1361.54 727.605 1314.91 722.781 1264.21 C 718.894 1225.82 727.653 1167.83 758.478 1141.35 C 771.141 1130.47 781.921 1118.81 792.404 1105.84 C 869.373 1010.12 879.456 876.886 817.771 770.669 C 809.316 756.055 799.574 742.224 788.661 729.342 C 782.235 721.815 773.191 712.791 767.461 705.187 C 749.008 680.699 737.483 646.859 734.444 616.659 C 729.188 565.849 744.584 515.06 777.168 475.721 C 810.289 435.451 856.055 412.394 907.659 407.406 z" fill="#9c9b9b"/><path d="M 554.228 729.711 C 659.104 725.931 747.227 807.802 751.164 912.672 C 755.1 1017.54 673.362 1105.79 568.498 1109.88 C 463.411 1113.98 374.937 1032.03 370.992 926.942 C 367.047 821.849 449.129 733.498 554.228 729.711 z" fill="#9c9b9b"/>"## }; +static ABACUS: Icon = Icon { name: "abacus", view: 40.0, body: r##"<path d="M6.93433 9.57807C6.93433 8.92952 7.46008 8.40376 8.10864 8.40376C8.75719 8.40376 9.28295 8.92952 9.28295 9.57807V16.6239C9.28295 17.2725 8.75719 17.7983 8.10864 17.7983C7.46008 17.7983 6.93433 17.2725 6.93433 16.6239V9.57807Z" fill="currentColor"/><path d="M30.7144 25.1377C30.7144 24.4891 31.2402 23.9634 31.8887 23.9634C32.5373 23.9634 33.063 24.4891 33.063 25.1377V31.0092C33.063 31.6578 32.5373 32.1836 31.8887 32.1836C31.2402 32.1836 30.7144 31.6578 30.7144 31.0093V25.1377Z" fill="currentColor"/><path d="M22.7875 30.422C22.7875 29.7735 23.3132 29.2477 23.9618 29.2477C24.6103 29.2477 25.1361 29.7735 25.1361 30.422V34.8257C25.1361 35.4742 24.6103 36 23.9618 36C23.3132 36 22.7875 35.4742 22.7875 34.8257V30.422Z" fill="currentColor"/><path d="M6.93433 28.367C6.93433 27.7185 7.46008 27.1927 8.10864 27.1927C8.75719 27.1927 9.28295 27.7185 9.28295 28.367V31.5964C9.28295 32.245 8.75719 32.7707 8.10864 32.7707C7.46008 32.7707 6.93433 32.245 6.93433 31.5964V28.367Z" fill="currentColor"/><path d="M14.8617 5.46787C14.8617 4.81931 15.3874 4.29355 16.036 4.29355C16.6845 4.29355 17.2103 4.81931 17.2103 5.46787V9.87153C17.2103 10.5201 16.6845 11.0458 16.036 11.0458C15.3874 11.0458 14.8617 10.5201 14.8617 9.87153V5.46787Z" fill="currentColor"/><path d="M30.7144 9.28437C30.7144 8.63582 31.2402 8.11006 31.8887 8.11006C32.5373 8.11006 33.063 8.63582 33.063 9.28437V13.688C33.063 14.3366 32.5373 14.8623 31.8887 14.8623C31.2402 14.8623 30.7144 14.3366 30.7144 13.688V9.28437Z" fill="currentColor"/><path d="M22.7875 5.17431C22.7875 4.52576 23.3132 4 23.9618 4C24.6103 4 25.1361 4.52576 25.1361 5.17431V18.3853C25.1361 19.0339 24.6103 19.5596 23.9618 19.5596C23.3132 19.5596 22.7875 19.0339 22.7875 18.3853V5.17431Z" fill="currentColor"/><path d="M14.8617 21.3212C14.8617 20.6726 15.3874 20.1469 16.036 20.1469C16.6845 20.1469 17.2103 20.6726 17.2103 21.3212V34.5322C17.2103 35.1807 16.6845 35.7065 16.036 35.7065C15.3874 35.7065 14.8617 35.1807 14.8617 34.5322V21.3212Z" fill="currentColor"/><path d="M10.4577 21.9083C10.4577 23.2055 9.40623 24.257 8.10912 24.257C6.81201 24.257 5.7605 23.2055 5.7605 21.9083C5.7605 20.6112 6.81201 19.5597 8.10912 19.5597C9.40623 19.5597 10.4577 20.6112 10.4577 21.9083Z" fill="currentColor"/><path d="M18.3843 14.8624C18.3843 16.1596 17.3328 17.2111 16.0357 17.2111C14.7386 17.2111 13.6871 16.1596 13.6871 14.8624C13.6871 13.5653 14.7386 12.5138 16.0357 12.5138C17.3328 12.5138 18.3843 13.5653 18.3843 14.8624Z" fill="currentColor"/><path d="M26.3101 24.2569C26.3101 25.554 25.2586 26.6056 23.9615 26.6056C22.6644 26.6056 21.6128 25.554 21.6128 24.2569C21.6128 22.9598 22.6644 21.9083 23.9615 21.9083C25.2586 21.9083 26.3101 22.9598 26.3101 24.2569Z" fill="currentColor"/><path d="M34.2378 19.5597C34.2378 20.8568 33.1863 21.9083 31.8892 21.9083C30.5921 21.9083 29.5406 20.8568 29.5406 19.5597C29.5406 18.2626 30.5921 17.2111 31.8892 17.2111C33.1863 17.2111 34.2378 18.2626 34.2378 19.5597Z" fill="currentColor"/>"## }; +static AIHUBMIX: Icon = Icon { name: "aihubmix", view: 40.0, body: r##"<path d="M18.7344 13.9883C18.8906 12.9154 19.237 11.5378 19.7734 9.85547L20 9.16016L20.2266 9.85547C20.763 11.5378 21.1094 12.9154 21.2656 13.9883C21.3854 14.7748 21.3854 15.7747 21.2656 16.9883C21.1458 18.207 21.1458 19.2148 21.2656 20.0117C21.4427 21.1784 21.9766 22.1471 22.8672 22.918C23.7734 23.7044 24.8229 24.0977 26.0156 24.0977C27.3385 24.0977 28.4688 23.6315 29.4062 22.6992C30.3385 21.7669 30.8099 20.6419 30.8203 19.3242C30.8255 18.1576 30.9453 16.8711 31.1797 15.4648C31.2944 14.7617 31.4116 14.1732 31.5313 13.6992L31.6875 13.0586L31.9688 13.6523C32.776 15.3607 33.1978 17.1628 33.2344 19.0586V19.3242C33.2344 21.1211 32.8882 22.8372 32.1953 24.4727C31.5235 26.0612 30.5781 27.4648 29.3594 28.6836C28.1354 29.9023 26.7318 30.8477 25.1484 31.5197C23.513 32.2122 21.7969 32.5588 20 32.5588C18.2031 32.5588 16.487 32.2122 14.8516 31.5197C13.2682 30.8477 11.8646 29.9023 10.6406 28.6836C9.42187 27.4648 8.47656 26.0612 7.80469 24.4727C7.11197 22.8372 6.76562 21.1211 6.76562 19.3242V19.0586C6.80209 17.1628 7.22397 15.3607 8.03125 13.6523L8.3125 13.0586L8.46875 13.6992C8.58853 14.1732 8.70572 14.7617 8.82031 15.4648C9.05469 16.8711 9.17447 18.1576 9.17969 19.3242C9.19009 20.6419 9.66147 21.7669 10.5937 22.6992C11.5312 23.6315 12.6615 24.0977 13.9844 24.0977C15.1771 24.0977 16.2266 23.7044 17.1328 22.918C18.0234 22.1471 18.5573 21.1784 18.7344 20.0117C18.8542 19.2148 18.8542 18.207 18.7344 16.9883C18.6146 15.7747 18.6146 14.7748 18.7344 13.9883ZM20 30.1445C21.8281 30.1445 23.5417 29.7122 25.1406 28.8477C26.2738 28.2378 27.2578 27.461 28.0927 26.5172C28.1969 26.3995 28.0742 26.2202 27.9224 26.2614C27.3073 26.4283 26.6717 26.5117 26.0156 26.5117C24.7135 26.5117 23.5026 26.1836 22.3828 25.5273C21.478 24.9999 20.7282 24.3152 20.1336 23.4732C20.0689 23.3815 19.9311 23.3815 19.8664 23.4732C19.2718 24.3152 18.522 24.9999 17.6172 25.5273C16.4974 26.1836 15.2865 26.5117 13.9844 26.5117C13.3283 26.5117 12.6927 26.4283 12.0776 26.2614C11.9258 26.2202 11.8031 26.3995 11.9072 26.5172C12.7422 27.461 13.7262 28.2378 14.8594 28.8477C16.4583 29.7122 18.1719 30.1445 20 30.1445Z" fill="currentColor" fill-rule="evenodd"/>"## }; +static ALIBABA: Icon = Icon { name: "alibaba", view: 40.0, body: r##"<path d="M37.9998 23.021C33.7998 25.2889 29.5698 27.3649 24.8614 28.3069C23.8114 28.5154 22.6474 28.5154 21.5809 28.3714C20.5639 28.2439 20.0554 27.3484 20.4169 26.4064C20.7619 25.5289 21.2209 24.635 21.8119 23.9C23.0899 22.3025 24.5329 20.849 25.8289 19.268C26.6203 18.2991 27.3335 17.2689 27.9618 16.187C28.4208 15.4205 28.2078 14.4935 27.4038 14.111C26.0584 13.4556 24.6154 12.9936 23.1889 12.4986C23.0239 12.4341 22.7779 12.6096 22.4509 12.7221C22.8604 13.0881 23.1559 13.3596 23.5654 13.727C19.3339 14.447 15.3305 15.467 11.4455 16.874C11.4275 16.9535 11.396 17.0165 11.411 17.0495C11.9855 17.927 11.723 18.5975 10.886 19.1405C10.5611 19.3531 10.2732 19.6176 10.034 19.9235C12.593 20.6735 14.873 20.243 17.0539 18.821C16.9234 18.6305 16.7914 18.455 16.6609 18.263C17.4799 18.407 17.9719 18.854 18.0379 19.556C18.0544 19.7165 17.9569 19.8755 17.9074 20.036C17.7919 19.907 17.6449 19.781 17.5474 19.6355C17.4799 19.5395 17.4634 19.4285 17.4154 19.268C14.8235 20.993 12.035 21.425 8.96751 20.531C8.96751 21.137 8.93451 21.6485 8.98401 22.1435C9.01701 22.574 8.83701 22.766 8.44401 22.9895C7.55752 23.5325 6.63803 24.092 5.90003 24.8105C5.01504 25.6879 5.34354 26.7589 6.54053 27.2059C7.90102 27.7159 9.329 27.7309 10.7555 27.5569C12.4445 27.3484 14.1005 27.0769 15.9394 26.8219C13.79 27.8269 11.6735 28.5319 9.4445 28.8169C7.88452 29.0269 6.32753 29.1379 4.78554 28.6909C2.57156 28.0684 1.58607 26.4394 2.16057 24.251C2.70206 22.2065 4.01455 20.5775 5.42454 19.076C10.133 14.078 16.0864 11.5401 22.9744 11.0286C24.5824 10.9176 26.2069 11.1246 27.7143 11.7951C29.8308 12.7536 30.7173 14.78 29.6838 16.826C29.0118 18.1835 28.0758 19.4285 27.1413 20.6585C26.2234 21.872 25.1899 22.9895 24.2224 24.155C23.9434 24.506 23.6809 24.875 23.4679 25.2724C23.0569 26.0224 23.3359 26.5174 24.2059 26.4394C26.0254 26.2624 27.8808 26.1199 29.6358 25.6729C32.2098 25.0174 34.7193 24.092 37.2618 23.2775C37.5243 23.213 37.7703 23.117 37.9998 23.0225V23.021Z" fill="currentColor"/>"## }; +static ALIBABA_CN: Icon = Icon { name: "alibaba-cn", view: 40.0, body: r##"<path d="M38 23.021C33.8 25.289 29.5701 27.365 24.8616 28.307C23.8116 28.5154 22.6476 28.5154 21.5811 28.3715C20.5641 28.244 20.0557 27.3485 20.4172 26.4065C20.7621 25.529 21.2211 24.635 21.8121 23.9C23.0901 22.3025 24.5331 20.849 25.8291 19.268C26.6206 18.2991 27.3338 17.2689 27.9621 16.1871C28.4211 15.4206 28.2081 14.4936 27.4041 14.1111C26.0586 13.4556 24.6156 12.9936 23.1891 12.4986C23.0241 12.4341 22.7781 12.6096 22.4511 12.7221C22.8606 13.0881 23.1561 13.3596 23.5656 13.7271C19.3342 14.4471 15.3307 15.4671 11.4457 16.8741C11.4277 16.9536 11.3962 17.0166 11.4112 17.0496C11.9857 17.927 11.7232 18.5975 10.8862 19.1405C10.5613 19.3531 10.2735 19.6177 10.0342 19.9235C12.5932 20.6735 14.8732 20.243 17.0542 18.821C16.9237 18.6305 16.7917 18.455 16.6612 18.263C17.4802 18.407 17.9722 18.854 18.0382 19.556C18.0547 19.7165 17.9572 19.8755 17.9077 20.036C17.7922 19.907 17.6452 19.781 17.5477 19.6355C17.4802 19.5395 17.4637 19.4285 17.4157 19.268C14.8237 20.993 12.0352 21.425 8.96775 20.531C8.96775 21.137 8.93475 21.6485 8.98425 22.1435C9.01725 22.574 8.83725 22.766 8.44426 22.9895C7.55776 23.5325 6.63827 24.092 5.90028 24.8105C5.01528 25.688 5.34378 26.759 6.54077 27.206C7.90126 27.716 9.32925 27.731 10.7557 27.557C12.4447 27.3485 14.1007 27.077 15.9397 26.822C13.7902 27.827 11.6737 28.5319 9.44475 28.8169C7.88476 29.0269 6.32777 29.1379 4.78579 28.6909C2.57181 28.0685 1.58631 26.4395 2.16081 24.251C2.7023 22.2065 4.01479 20.5775 5.42478 19.076C10.1332 14.0781 16.0867 11.5401 22.9746 11.0286C24.5826 10.9176 26.2071 11.1246 27.7146 11.7951C29.8311 12.7536 30.7176 14.7801 29.6841 16.8261C29.0121 18.1835 28.0761 19.4285 27.1416 20.6585C26.2236 21.872 25.1901 22.9895 24.2226 24.155C23.9436 24.506 23.6811 24.875 23.4681 25.2725C23.0571 26.0225 23.3361 26.5175 24.2061 26.4395C26.0256 26.2625 27.8811 26.12 29.6361 25.673C32.2101 25.0175 34.7195 24.092 37.262 23.2775C37.5245 23.213 37.7705 23.117 38 23.0225V23.021Z" fill="currentColor"/>"## }; +static AMAZON_BEDROCK: Icon = Icon { name: "amazon-bedrock", view: 40.0, body: r##"<path d="M21.5835 24.7904H25.7835C26.0754 24.7904 26.314 25.0318 26.314 25.3277V27.8096C26.8199 27.9343 27.2691 28.2255 27.5896 28.6362C27.9102 29.047 28.0833 29.5536 28.0813 30.0746C28.0813 31.3605 27.0517 32.4037 25.7835 32.4037C24.514 32.4037 23.4844 31.3605 23.4844 30.0746C23.4844 28.9741 24.2399 28.0509 25.2531 27.8082V25.865H21.5849V32.2237C21.5852 32.3161 21.5618 32.407 21.5169 32.4877C21.4721 32.5684 21.4072 32.6362 21.3285 32.6846L17.6603 34.9224C17.577 34.9733 17.4813 35 17.3837 34.9995C17.2862 34.999 17.1907 34.9714 17.108 34.9197L10.3906 30.7114C10.3131 30.6628 10.2493 30.5952 10.2052 30.515C10.161 30.4348 10.138 30.3447 10.1384 30.2532V25.8636L6.78241 23.9136C6.70609 23.8694 6.64181 23.8071 6.59521 23.7322C6.5486 23.6573 6.52111 23.5721 6.51514 23.4841V23.4472V16.4626C6.51514 16.2717 6.61468 16.0944 6.77696 15.999L10.1384 14.0053V9.70163C10.1384 9.52572 10.2229 9.36208 10.3634 9.26253L10.392 9.24344L17.1107 5.07885C17.194 5.027 17.2901 4.99951 17.3882 4.99951C17.4863 4.99951 17.5824 5.027 17.6657 5.07885L21.3339 7.36296C21.4115 7.41162 21.4753 7.47921 21.5194 7.55938C21.5636 7.63955 21.5866 7.72964 21.5862 7.82115V13.9999H26.8445V11.3857C26.3384 11.2609 25.8889 10.9696 25.5684 10.5585C25.2479 10.1475 25.0749 9.6406 25.0772 9.11935C25.0772 7.83342 26.1067 6.79023 27.3749 6.79023C28.6445 6.79023 29.6727 7.83342 29.6727 9.11935C29.6727 10.2198 28.9186 11.143 27.9054 11.3857V14.5371C27.9059 14.6073 27.8926 14.6768 27.8662 14.7418C27.8399 14.8068 27.8009 14.8659 27.7516 14.9158C27.7024 14.9658 27.6437 15.0055 27.5791 15.0327C27.5144 15.0599 27.4451 15.0741 27.3749 15.0744H21.5862V17.5372H30.6191C30.7351 17.0302 31.0192 16.5773 31.4252 16.2522C31.8313 15.9271 32.3353 15.749 32.8554 15.7467C34.1236 15.7467 35.1532 16.7885 35.1532 18.0745C35.1532 19.3604 34.125 20.4036 32.8554 20.4036C32.3351 20.4012 31.8309 20.2229 31.4249 19.8975C31.0188 19.5722 30.7348 19.119 30.6191 18.6117H21.5835V21.2531H28.3377L29.5854 22.8622C29.9329 22.659 30.3283 22.5522 30.7309 22.5527C32.0004 22.5527 33.0286 23.5945 33.0286 24.8804C33.0286 26.1664 32.0004 27.2096 30.7309 27.2096C29.4627 27.2096 28.4331 26.1664 28.4331 24.8804C28.4331 24.4086 28.5722 23.9695 28.8095 23.6027L27.8222 22.3277H21.5835V24.7904ZM17.3875 6.16704L14.6016 7.89342V11.9407H13.5407V8.55071L11.1993 10.003V14.019L14.0766 15.8735L17.0316 14.0135V10.9098H18.0925V14.3135C18.0925 14.499 17.9971 14.6721 17.8416 14.7703L14.6466 16.779V19.6167L16.5857 20.9927L15.9775 21.8736L14.0602 20.5127L11.9738 21.8831L11.397 20.9831L13.5857 19.5445V16.8308L10.6579 14.9408L7.57606 16.7681V19.0536L10.2652 17.4322L10.8079 18.3554L7.57606 20.304V23.1363L10.5297 24.8518L13.6252 22.9863L14.1666 23.9095L11.1993 25.6973V29.9546L13.7575 31.5569L16.9825 29.6123L17.5253 30.5369L14.7748 32.1951L17.3903 33.8328L20.5239 31.9196V24.0377L14.0357 27.9828L13.4902 27.0623L20.5239 22.7859V8.12115L17.3875 6.16704ZM25.7835 28.8228C25.6198 28.8237 25.4579 28.8568 25.307 28.9204C25.1561 28.984 25.0192 29.0767 24.9042 29.1932C24.7892 29.3097 24.6983 29.4478 24.6367 29.5995C24.5751 29.7512 24.5441 29.9136 24.5453 30.0773C24.5453 30.7687 25.099 31.3292 25.7835 31.3292C25.947 31.3281 26.1087 31.2948 26.2594 31.2313C26.41 31.1677 26.5467 31.0751 26.6615 30.9587C26.7764 30.8424 26.8672 30.7045 26.9287 30.553C26.9903 30.4016 27.0215 30.2395 27.0204 30.076C27.0216 29.9123 26.9906 29.7501 26.9291 29.5985C26.8676 29.4468 26.7769 29.3088 26.662 29.1923C26.5471 29.0758 26.4104 28.9831 26.2597 28.9194C26.109 28.8558 25.9472 28.8238 25.7835 28.8228ZM30.7336 23.6272C30.5699 23.6281 30.4079 23.6613 30.257 23.7249C30.1062 23.7884 29.9693 23.8811 29.8543 23.9977C29.7393 24.1142 29.6484 24.2523 29.5868 24.404C29.5252 24.5557 29.4942 24.7181 29.4954 24.8818C29.4954 25.5745 30.0491 26.1364 30.7322 26.1364C30.896 26.1355 31.0579 26.1023 31.2088 26.0387C31.3597 25.9752 31.4966 25.8825 31.6116 25.7659C31.7266 25.6494 31.8175 25.5113 31.8791 25.3596C31.9406 25.2079 31.9717 25.0455 31.9704 24.8818C31.9717 24.7181 31.9406 24.5557 31.8791 24.404C31.8175 24.2523 31.7266 24.1142 31.6116 23.9977C31.4966 23.8811 31.3597 23.7884 31.2088 23.7249C31.0579 23.6613 30.8973 23.6281 30.7336 23.6272ZM32.8541 16.8226C32.6904 16.8235 32.5284 16.8567 32.3775 16.9203C32.2266 16.9838 32.0898 17.0765 31.9747 17.1931C31.8597 17.3096 31.7688 17.4477 31.7073 17.5994C31.6457 17.7511 31.6146 17.9135 31.6159 18.0772C31.6159 18.7686 32.1709 19.329 32.8541 19.329C33.0176 19.3279 33.1793 19.2947 33.3299 19.2311C33.4806 19.1676 33.6172 19.075 33.7321 18.9586C33.8469 18.8422 33.9377 18.7044 33.9993 18.5529C34.0609 18.4014 34.092 18.2393 34.0909 18.0758C34.0922 17.9122 34.0612 17.7499 33.9997 17.5983C33.9382 17.4467 33.8474 17.3087 33.7325 17.1922C33.6177 17.0757 33.481 16.9829 33.3302 16.9193C33.1795 16.8556 33.0177 16.8223 32.8541 16.8213V16.8226ZM27.3736 7.86342C27.2099 7.86449 27.0482 7.8978 26.8974 7.96145C26.7467 8.02509 26.61 8.11783 26.4951 8.23434C26.3802 8.35086 26.2895 8.48887 26.228 8.64049C26.1665 8.79212 26.1355 8.95437 26.1367 9.11798C26.1367 9.81072 26.6904 10.3725 27.3736 10.3725C27.5373 10.3717 27.6992 10.3385 27.8501 10.2749C28.001 10.2113 28.1379 10.1186 28.2529 10.0021C28.3679 9.88558 28.4588 9.7475 28.5204 9.59579C28.582 9.44408 28.613 9.28171 28.6118 9.11798C28.613 8.95426 28.582 8.79189 28.5204 8.64018C28.4588 8.48847 28.3679 8.35039 28.2529 8.23386C28.1379 8.11733 28.001 8.02462 27.8501 7.96106C27.6992 7.89749 27.5373 7.86432 27.3736 7.86342Z" fill="currentColor"/>"## }; +static ANTHROPIC: Icon = Icon { name: "anthropic", view: 40.0, body: r##"<path d="M26.9568 9.88184H22.1265L30.7753 31.7848H35.4917L26.9568 9.88184ZM13.028 9.88184L4.4917 31.7848H9.32203L11.2305 27.1793H20.2166L22.0126 31.6724H26.8444L18.0832 9.88184H13.028ZM12.5783 23.1361L15.4987 15.3853L18.5315 23.1361H12.5783Z" fill="currentColor"/>"## }; +static AZURE: Icon = Icon { name: "azure", view: 40.0, body: r##"<path d="M21.68 7.58398L11.296 29.68L4 29.6L12.144 15.584L21.68 7.58398ZM22.8 9.32798L36 32.416H11.584L26.464 29.76L18.672 20.496L22.8 9.32798Z" fill="currentColor"/>"## }; +static AZURE_COGNITIVE_SERVICES: Icon = Icon { name: "azure-cognitive-services", view: 24.0, body: r##"<path d="M9.8132 15.9038L9 18.75L8.1868 15.9038C7.75968 14.4089 6.59112 13.2403 5.09619 12.8132L2.25 12L5.09619 11.1868C6.59113 10.7597 7.75968 9.59112 8.1868 8.09619L9 5.25L9.8132 8.09619C10.2403 9.59113 11.4089 10.7597 12.9038 11.1868L15.75 12L12.9038 12.8132C11.4089 13.2403 10.2403 14.4089 9.8132 15.9038Z" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/><path d="M18.2589 8.71454L18 9.75L17.7411 8.71454C17.4388 7.50533 16.4947 6.56117 15.2855 6.25887L14.25 6L15.2855 5.74113C16.4947 5.43883 17.4388 4.49467 17.7411 3.28546L18 2.25L18.2589 3.28546C18.5612 4.49467 19.5053 5.43883 20.7145 5.74113L21.75 6L20.7145 6.25887C19.5053 6.56117 18.5612 7.50533 18.2589 8.71454Z" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/><path d="M16.8942 20.5673L16.5 21.75L16.1058 20.5673C15.8818 19.8954 15.3546 19.3682 14.6827 19.1442L13.5 18.75L14.6827 18.3558C15.3546 18.1318 15.8818 17.6046 16.1058 16.9327L16.5 15.75L16.8942 16.9327C17.1182 17.6046 17.6454 18.1318 18.3173 18.3558L19.5 18.75L18.3173 19.1442C17.6454 19.3682 17.1182 19.8954 16.8942 20.5673Z" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>"## }; +static BAILING: Icon = Icon { name: "bailing", view: 24.0, body: r##"<path d="M8.28591 2.75588C8.41369 2.67957 8.5746 2.67841 8.69528 2.76629L10.9527 3.82546C11.0568 3.90177 11.0403 4.05441 10.9267 4.11569C7.84815 5.76573 5.98825 7.3753 5.01215 8.93746C4.38154 9.94807 3.21851 12.7058 4.27032 15.1942C5.35882 17.7681 7.82804 18.6978 9.65599 18.6978C11.0367 18.6978 11.975 18.2908 12.9286 17.6571C15.5126 15.9377 15.8107 12.5833 13.8869 10.2776C13.8869 10.2753 14.942 11.1609 15.6175 12.5083C15.4903 12.0228 15.2913 11.5573 15.0227 11.1252L14.8975 10.9308C14.3412 10.0984 13.6072 9.3999 12.6008 8.90277C10.1896 7.71294 5.15531 8.28646 4.36261 13.4112C4.44306 9.85672 6.84011 7.62622 9.01236 6.93706C10.218 6.55317 11.4946 6.48032 12.7002 6.69193C14.1795 5.51643 15.8019 4.93598 16.5477 4.71377L16.7217 4.66378C16.8696 4.62215 17.0282 4.66378 17.1358 4.77016C17.318 4.95054 17.6363 5.26274 18.0409 5.65588C18.164 5.77267 18.1001 5.97502 17.9333 6.00624C16.3692 6.3011 15.302 6.5948 14.1721 7.10704C15.541 7.65166 16.7134 8.6056 17.4281 9.92032C17.5121 10.0753 17.4399 10.2672 17.2707 10.3273L16.3135 10.6673C17.1548 12.071 17.3701 13.7916 16.9584 15.555C16.2579 18.5509 13.9118 20.6727 10.9149 21.1769C10.8848 21.1819 10.8548 21.1869 10.8248 21.1917C10.575 21.2366 10.3246 21.2675 10.0759 21.2843L9.79858 21.2974L9.52348 21.2995C9.34364 21.296 9.20758 21.1353 9.23953 20.9618L9.42173 19.9501C8.58525 19.8934 7.80201 19.757 7.0164 19.4448C2.356 17.5924 1.86736 13.0712 2.53583 10.3308C3.40308 6.77749 6.06988 4.08678 8.28591 2.75588Z" fill="currentColor" fill-rule="evenodd"/>"## }; +static BASETEN: Icon = Icon { name: "baseten", view: 24.0, body: r##"<path d="M4.97934 6.78009H15.6237V10.26H8.59995C8.57096 10.2595 8.54214 10.2647 8.51516 10.2753C8.48819 10.286 8.4636 10.3019 8.44283 10.3221C8.42205 10.3423 8.40551 10.3665 8.39415 10.3932C8.38279 10.4199 8.37684 10.4485 8.37665 10.4775V13.5225C8.37665 13.6465 8.47815 13.74 8.59995 13.74H15.6237V17.22H12.2264C12.1974 17.2194 12.1685 17.2246 12.1416 17.2352C12.1146 17.2459 12.09 17.2618 12.0692 17.282C12.0485 17.3023 12.0319 17.3264 12.0206 17.3531C12.0092 17.3798 12.0032 17.4085 12.0031 17.4375V20.4824C12.0031 20.6064 12.1053 20.6999 12.2264 20.6999H15.4004C15.4295 20.701 15.4585 20.6962 15.4857 20.6857C15.5129 20.6752 15.5377 20.6593 15.5586 20.639C15.5795 20.6187 15.596 20.5943 15.6072 20.5674C15.6184 20.5405 15.624 20.5116 15.6237 20.4824V17.22H19.0268C19.0558 17.2205 19.0846 17.2154 19.1116 17.2047C19.1385 17.194 19.1631 17.1781 19.1839 17.1579C19.2047 17.1377 19.2212 17.1135 19.2326 17.0868C19.2439 17.0601 19.2499 17.0315 19.2501 17.0025V13.9575C19.2501 13.8335 19.1486 13.74 19.0268 13.74H15.6237V10.26H19.0268C19.0558 10.2606 19.0846 10.2554 19.1116 10.2448C19.1385 10.2341 19.1631 10.2182 19.1839 10.198C19.2047 10.1777 19.2212 10.1536 19.2326 10.1269C19.2439 10.1002 19.2499 10.0715 19.2501 10.0425V6.99758C19.2501 6.87361 19.1486 6.78009 19.0268 6.78009H15.6237V3.51762C15.6237 3.39365 15.5222 3.30012 15.4004 3.30012H4.97934C4.92022 3.29895 4.86302 3.32112 4.82014 3.36183C4.77725 3.40255 4.75214 3.45852 4.75024 3.51762V6.56259C4.75024 6.68656 4.85174 6.78009 4.97934 6.78009Z" fill="currentColor"/>"## }; +static BERGET: Icon = Icon { name: "berget", view: 463.0, body: r##"<path d="M208.739 39L255.261 39L446 425L398 425L313.5 277L261.5 198L233.163 118.1677L237.815 120.6522L226.185 120.6522L230.837 118.1677L113 353L64.5 425L18 425L208.739 39Z" fill="currentColor"/>"## }; +static CEREBRAS: Icon = Icon { name: "cerebras", view: 40.0, body: r##"<path d="M22.9846 6.52999C19.4122 6.52999 15.9861 7.94913 13.46 10.4752C10.9339 13.0013 9.51474 16.4274 9.51474 19.9999C9.51474 23.5723 10.9339 26.9984 13.46 29.5245C15.9861 32.0506 19.4122 33.4698 22.9846 33.4698V35.4991C14.4238 35.4991 7.48535 28.5592 7.48535 19.9984C7.48535 11.4376 14.4224 4.49915 22.9832 4.49915V6.52854L22.9846 6.52999ZM29.868 11.8562C28.7978 10.9477 27.5586 10.2598 26.2216 9.83189C24.8846 9.40401 23.4761 9.24465 22.0773 9.36298C20.6785 9.48132 19.3169 9.875 18.0707 10.5214C16.8246 11.1678 15.7185 12.0542 14.8162 13.1295C13.9138 14.2049 13.2329 15.448 12.8126 16.7875C12.3923 18.1269 12.241 19.5362 12.3673 20.9343C12.4936 22.3324 12.895 23.6918 13.5485 24.9342C14.202 26.1767 15.0946 27.2777 16.1751 28.1739L14.87 29.7296C13.594 28.6594 12.5414 27.3482 11.7722 25.871C11.003 24.3939 10.5323 22.7797 10.3871 21.1206C10.2418 19.4615 10.4247 17.7901 10.9255 16.2017C11.4263 14.6134 12.235 13.1392 13.3055 11.8635C14.376 10.5875 15.6873 9.5348 17.1645 8.7656C18.6418 7.99639 20.2561 7.52572 21.9153 7.38045C23.5745 7.23517 25.2461 7.41815 26.8345 7.91893C28.423 8.41971 29.8973 9.22848 31.1732 10.2991L29.868 11.8562ZM26.6016 13.0788C24.7668 12.1311 22.6319 11.9464 20.6616 12.5649C18.6913 13.1834 17.045 14.5551 16.0809 16.3813C15.1169 18.2076 14.9132 20.3408 15.514 22.3165C16.1149 24.2923 17.4718 25.9508 19.2894 26.9311L18.3392 28.7273C16.0689 27.4824 14.3791 25.3948 13.6343 22.915C12.8896 20.4352 13.1498 17.762 14.3586 15.4723C15.5674 13.1826 17.628 11.46 20.0957 10.6762C22.5635 9.89232 25.2404 10.1101 27.5489 11.2826L26.6016 13.0788ZM22.9832 14.9865C21.6536 14.9865 20.3784 15.5147 19.4382 16.4549C18.498 17.3951 17.9698 18.6702 17.9698 19.9999C17.9698 21.3295 18.498 22.6047 19.4382 23.5449C20.3784 24.485 21.6536 25.0132 22.9832 25.0132V27.0441C21.1149 27.0441 19.3232 26.3019 18.0022 24.9809C16.6811 23.6598 15.939 21.8681 15.939 19.9999C15.939 18.1316 16.6811 16.3399 18.0022 15.0189C19.3232 13.6978 21.1149 12.9557 22.9832 12.9557V14.9865Z" fill="currentColor"/><path d="M24.8474 18.3138C24.6315 18.0812 24.3826 17.8816 24.1087 17.7213C23.8701 17.5796 23.5982 17.5036 23.3207 17.5011C22.9513 17.5011 22.621 17.5692 22.3299 17.7039C22.0485 17.8307 21.7956 18.0131 21.5865 18.2401C21.3774 18.4672 21.2164 18.7341 21.1131 19.025C21.0059 19.319 20.9538 19.6276 20.9538 19.939C20.9538 20.2548 21.0059 20.5619 21.1131 20.853C21.2172 21.1436 21.3786 21.4104 21.5876 21.6375C21.7966 21.8647 22.049 22.0476 22.3299 22.1756C22.6196 22.3103 22.9528 22.3783 23.3207 22.3783C23.6336 22.3783 23.9247 22.3117 24.1927 22.1828C24.465 22.0524 24.6997 21.8569 24.8808 21.615L26.225 23.0722C26.0222 23.275 25.7904 23.4503 25.5268 23.598C25.0392 23.8699 24.5086 24.0561 23.958 24.1484C23.7118 24.1861 23.4989 24.2064 23.3207 24.2064C22.7362 24.21 22.156 24.107 21.6085 23.9022C21.0909 23.7108 20.6174 23.4166 20.2165 23.0374C19.8178 22.6565 19.5004 22.1987 19.2836 21.6917C19.0481 21.1378 18.9306 20.5409 18.9389 19.939C18.9389 19.2959 19.0548 18.7121 19.2836 18.1863C19.5009 17.6793 19.8167 17.2216 20.215 16.8406C20.6177 16.4625 21.0914 16.1685 21.6085 15.9773C22.156 15.7725 22.7362 15.6694 23.3207 15.6731C23.8349 15.6731 24.352 15.7716 24.8735 15.9686C25.3964 16.1685 25.8658 16.4901 26.2409 16.9087L24.8474 18.3138Z" fill="currentColor"/>"## }; +static CHUTES: Icon = Icon { name: "chutes", view: 24.0, body: r##"<path d="M9.8132 15.9038L9 18.75L8.1868 15.9038C7.75968 14.4089 6.59112 13.2403 5.09619 12.8132L2.25 12L5.09619 11.1868C6.59113 10.7597 7.75968 9.59112 8.1868 8.09619L9 5.25L9.8132 8.09619C10.2403 9.59113 11.4089 10.7597 12.9038 11.1868L15.75 12L12.9038 12.8132C11.4089 13.2403 10.2403 14.4089 9.8132 15.9038Z" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/><path d="M18.2589 8.71454L18 9.75L17.7411 8.71454C17.4388 7.50533 16.4947 6.56117 15.2855 6.25887L14.25 6L15.2855 5.74113C16.4947 5.43883 17.4388 4.49467 17.7411 3.28546L18 2.25L18.2589 3.28546C18.5612 4.49467 19.5053 5.43883 20.7145 5.74113L21.75 6L20.7145 6.25887C19.5053 6.56117 18.5612 7.50533 18.2589 8.71454Z" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/><path d="M16.8942 20.5673L16.5 21.75L16.1058 20.5673C15.8818 19.8954 15.3546 19.3682 14.6827 19.1442L13.5 18.75L14.6827 18.3558C15.3546 18.1318 15.8818 17.6046 16.1058 16.9327L16.5 15.75L16.8942 16.9327C17.1182 17.6046 17.6454 18.1318 18.3173 18.3558L19.5 18.75L18.3173 19.1442C17.6454 19.3682 17.1182 19.8954 16.8942 20.5673Z" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>"## }; +static CLAUDE_AGENT: Icon = Icon { name: "claude-agent", view: 123.0, body: r##"<path d="M31.1 78L50.8 67L51.1 66L50.8 65.5L49.8 65.5L46.5 65.3L35.3 65L25.5 64.5L16 64L13.6 63.5L11.5 60.5L11.7 59L13.7 57.7L16.6 57.9L22.9 58.4L32.4 59L39.3 59.4L49.5 60.6L51.1 60.6L51.3 59.9L50.8 59.5L50.4 59.1L40.5 52.5L29.9 45.5L24.3 41.4L21.3 39.4L19.8 37.4L19.2 33.2L21.9 30.2L25.6 30.5L26.5 30.7L30.2 33.6L38.2 39.7L48.5 47.5L50 48.7L50.6 48.3L50.7 48L50 46.9L44.5 36.5L38.5 26.1L35.8 21.8L35.1 19.2C34.8 18.2 34.7 17.2 34.7 16.2L37.7 12L39.5 11.5L43.7 12.1L45.3 13.5L47.9 19.5L52 28.8L58.5 41.4L60.5 45.2L61.5 48.6L61.8 49.6L62.5 49.6L62.5 49.1L63 41.9L64 33.2L65 22L65.3 18.8L66.9 15L69.9 13L72.5 14.1L74.5 17L74.2 18.8L73.1 26.5L70.5 38.6L69 46.8L69.9 46.8L70.9 45.7L75 40.3L81.9 31.7L84.9 28.2L88.5 24.5L90.8 22.7L95.1 22.7L98.2 27.4L96.8 32.3L92.4 37.9L88.7 42.6L83.4 49.7L80.2 55.4L80.5 55.8L81.2 55.8L93.2 53.2L99.6 52.1L107.2 50.8L110.7 52.4L111.1 54L109.7 57.4L101.5 59.4L91.9 61.4L77.6 64.7L77.4 64.8L77.6 65.1L84 65.7L86.8 65.9L93.6 65.9L106.2 66.9L109.5 68.9L111.4 71.6L111.1 73.6L106 76.2L99.2 74.6L83.2 70.8L77.8 69.5L77 69.5L77 69.9L81.6 74.4L89.9 81.9L100.5 91.6L101 94L99.7 96L98.3 95.8L89.1 88.8L85.5 85.8L77.5 79L77 79L77 79.7L78.8 82.4L88.6 97.1L89.1 101.6L88.4 103L85.8 104L83.1 103.4L77.3 95.4L71.3 86.4L66.6 78.2L66.1 78.6L63.2 108.8L61.9 110.3L58.9 111.5L56.4 109.5L55 106.5L56.4 100.3L58 92.3L59.3 85.9L60.5 78L61.2 75.4L61.2 75.2L60.5 75.2L54.5 83.5L45.5 95.8L38.3 103.4L36.6 104.1L33.6 102.6L33.9 99.8L35.5 97.5L45.5 84.7L51.5 76.8L55.5 72.2L55.4 71.7L55.1 71.7L28.7 88.9L24 89.5L22 87.5L22.2 84.5L23.2 83.5L31.2 78Z" fill="currentColor"/>"## }; +static CLOUDFERRO_SHERLOCK: Icon = Icon { name: "cloudferro-sherlock", view: 24.0, body: r##"<path d="M12,24l-8.996,-8.996l8.996,-8.997l2.996,2.997l-5.999,6l2.996,2.997l6,-5.999l2.997,2.996l-8.99,8.996Z" fill="currentColor" opacity="0.01"/><path d="M9,15l6,-6l-3,-3l-9,9l-3,-3l12,-12l12,12l-3,3l-3,-3l-6,6l-3,-3Z" fill="currentColor"/><path d="M0,12L12,0L24,12L12,24L0,12Z" fill="none" stroke="currentColor" stroke-width="0.2"/>"## }; +static CLOUDFLARE_AI_GATEWAY: Icon = Icon { name: "cloudflare-ai-gateway", view: 24.0, body: r##"<path d="M17.6323 11.3946C17.57 11.3946 17.5085 11.3968 17.447 11.3988C17.437 11.3993 17.4272 11.4017 17.4181 11.4057C17.4018 11.4113 17.3872 11.4208 17.3755 11.4333C17.3639 11.446 17.3555 11.4612 17.3512 11.4779L17.0876 12.3986C16.9739 12.7945 17.0162 13.16 17.2072 13.4284C17.3823 13.6766 17.6737 13.8223 18.0274 13.8393L19.4572 13.926C19.4998 13.9282 19.5366 13.9487 19.559 13.9824C19.5707 14.0004 19.5781 14.0209 19.5806 14.0422C19.5832 14.0636 19.5807 14.0852 19.5735 14.1054C19.562 14.1383 19.5412 14.1672 19.5138 14.1886C19.4862 14.21 19.4532 14.2231 19.4185 14.2261L17.9328 14.3128C17.1256 14.3502 16.2572 15.0088 15.9525 15.8119L15.8454 16.0953C15.8409 16.107 15.8391 16.1197 15.8404 16.1322C15.8417 16.1448 15.8459 16.1569 15.8528 16.1675C15.8596 16.1781 15.8689 16.1869 15.8799 16.1931C15.8908 16.1994 15.9031 16.203 15.9157 16.2035H21.0325C21.0623 16.2037 21.0912 16.1941 21.115 16.1761C21.1387 16.1583 21.156 16.133 21.164 16.1043C21.2549 15.7778 21.3007 15.4403 21.3 15.1012C21.3 13.0552 19.6593 11.3969 17.6346 11.3969" fill="currentColor"/><path d="M15.3989 16.0845L15.4936 15.7515C15.6075 15.3556 15.5653 14.9901 15.3745 14.7218C15.1989 14.4735 14.9078 14.3278 14.5538 14.3108L7.84677 14.2241C7.82591 14.2238 7.80543 14.2185 7.78701 14.2087C7.76859 14.1988 7.75274 14.1848 7.74077 14.1678C7.729 14.1498 7.72153 14.1293 7.71898 14.108C7.71642 14.0867 7.71883 14.065 7.72602 14.0447C7.73763 14.0116 7.75859 13.9826 7.78637 13.9612C7.81415 13.9398 7.84755 13.9268 7.88252 13.924L14.6521 13.8373C15.4559 13.8002 16.3243 13.1413 16.6289 12.3382L17.015 11.3181C17.0305 11.2748 17.0346 11.2282 17.0263 11.183C16.5864 9.19291 14.827 7.70273 12.7236 7.70273C10.7843 7.70273 9.13918 8.96716 8.54878 10.7249C8.15131 10.4228 7.65356 10.2835 7.15697 10.3356C6.22734 10.4291 5.47905 11.1863 5.38671 12.126C5.36282 12.3607 5.38008 12.5978 5.43771 12.8266C3.91861 12.8719 2.69995 14.1295 2.69995 15.675C2.69995 15.8147 2.70991 15.9524 2.72996 16.0867C2.73831 16.1519 2.79382 16.2008 2.8595 16.2007H15.2459C15.2808 16.2001 15.3145 16.1882 15.3421 16.1669C15.3697 16.1455 15.3896 16.1159 15.3989 16.0822" fill="currentColor"/>"## }; +static CLOUDFLARE_WORKERS_AI: Icon = Icon { name: "cloudflare-workers-ai", view: 24.0, body: r##"<path d="M17.6323 11.3946C17.57 11.3946 17.5085 11.3968 17.447 11.3988C17.437 11.3993 17.4272 11.4017 17.4181 11.4057C17.4018 11.4113 17.3872 11.4208 17.3755 11.4333C17.3639 11.446 17.3555 11.4612 17.3512 11.4779L17.0876 12.3986C16.9739 12.7945 17.0162 13.16 17.2072 13.4284C17.3823 13.6766 17.6737 13.8223 18.0274 13.8393L19.4572 13.926C19.4998 13.9282 19.5366 13.9487 19.559 13.9824C19.5707 14.0004 19.5781 14.0209 19.5806 14.0422C19.5832 14.0636 19.5807 14.0852 19.5735 14.1054C19.562 14.1383 19.5412 14.1672 19.5138 14.1886C19.4862 14.21 19.4532 14.2231 19.4185 14.2261L17.9328 14.3128C17.1256 14.3502 16.2572 15.0088 15.9525 15.8119L15.8454 16.0953C15.8409 16.107 15.8391 16.1197 15.8404 16.1322C15.8417 16.1448 15.8459 16.1569 15.8528 16.1675C15.8596 16.1781 15.8689 16.1869 15.8799 16.1931C15.8908 16.1994 15.9031 16.203 15.9157 16.2035H21.0325C21.0623 16.2037 21.0912 16.1941 21.115 16.1761C21.1387 16.1583 21.156 16.133 21.164 16.1043C21.2549 15.7778 21.3007 15.4403 21.3 15.1012C21.3 13.0552 19.6593 11.3969 17.6346 11.3969" fill="currentColor"/><path d="M15.3989 16.0845L15.4936 15.7515C15.6075 15.3556 15.5653 14.9901 15.3745 14.7218C15.1989 14.4735 14.9078 14.3278 14.5538 14.3108L7.84677 14.2241C7.82591 14.2238 7.80543 14.2185 7.78701 14.2087C7.76859 14.1988 7.75274 14.1848 7.74077 14.1678C7.729 14.1498 7.72153 14.1293 7.71898 14.108C7.71642 14.0867 7.71883 14.065 7.72602 14.0447C7.73763 14.0116 7.75859 13.9826 7.78637 13.9612C7.81415 13.9398 7.84755 13.9268 7.88252 13.924L14.6521 13.8373C15.4559 13.8002 16.3243 13.1413 16.6289 12.3382L17.015 11.3181C17.0305 11.2748 17.0346 11.2282 17.0263 11.183C16.5864 9.19291 14.827 7.70273 12.7236 7.70273C10.7843 7.70273 9.13918 8.96716 8.54878 10.7249C8.15131 10.4228 7.65356 10.2835 7.15697 10.3356C6.22734 10.4291 5.47905 11.1863 5.38671 12.126C5.36282 12.3607 5.38008 12.5978 5.43771 12.8266C3.91861 12.8719 2.69995 14.1295 2.69995 15.675C2.69995 15.8147 2.70991 15.9524 2.72996 16.0867C2.73831 16.1519 2.79382 16.2008 2.8595 16.2007H15.2459C15.2808 16.2001 15.3145 16.1882 15.3421 16.1669C15.3697 16.1455 15.3896 16.1159 15.3989 16.0822" fill="currentColor"/>"## }; +static COHERE: Icon = Icon { name: "cohere", view: 24.0, body: r##"<path d="M9.14882 13.5552C9.58082 13.5552 10.4448 13.5336 11.6544 13.0368C13.0584 12.4536 15.8232 11.4168 17.832 10.3368C19.236 9.5808 19.8408 8.5872 19.8408 7.248C19.8408 5.412 18.3504 3.9 16.4928 3.9H8.71682C6.06002 3.9 3.90002 6.06 3.90002 8.7168C3.90002 11.3736 5.93042 13.5552 9.14882 13.5552Z" fill="currentColor"/><path d="M10.4664 16.86C10.4664 15.564 11.244 14.376 12.4536 13.8792L14.8944 12.864C17.3784 11.8488 20.1 13.6632 20.1 16.3416C20.1 18.4152 18.4152 20.1 16.3416 20.1H13.6848C11.9136 20.1 10.4664 18.6528 10.4664 16.86Z" fill="currentColor"/><path d="M6.68642 14.1816C5.15282 14.1816 3.90002 15.4344 3.90002 16.968V17.3352C3.90002 18.8472 5.15282 20.1 6.68642 20.1C8.22003 20.1 9.47283 18.8472 9.47283 17.3136V16.9464C9.45123 15.4344 8.22003 14.1816 6.68642 14.1816Z" fill="currentColor"/>"## }; +static CORTECS: Icon = Icon { name: "cortecs", view: 24.0, body: r##"<path d="M9.8132 15.9038L9 18.75L8.1868 15.9038C7.75968 14.4089 6.59112 13.2403 5.09619 12.8132L2.25 12L5.09619 11.1868C6.59113 10.7597 7.75968 9.59112 8.1868 8.09619L9 5.25L9.8132 8.09619C10.2403 9.59113 11.4089 10.7597 12.9038 11.1868L15.75 12L12.9038 12.8132C11.4089 13.2403 10.2403 14.4089 9.8132 15.9038Z" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/><path d="M18.2589 8.71454L18 9.75L17.7411 8.71454C17.4388 7.50533 16.4947 6.56117 15.2855 6.25887L14.25 6L15.2855 5.74113C16.4947 5.43883 17.4388 4.49467 17.7411 3.28546L18 2.25L18.2589 3.28546C18.5612 4.49467 19.5053 5.43883 20.7145 5.74113L21.75 6L20.7145 6.25887C19.5053 6.56117 18.5612 7.50533 18.2589 8.71454Z" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/><path d="M16.8942 20.5673L16.5 21.75L16.1058 20.5673C15.8818 19.8954 15.3546 19.3682 14.6827 19.1442L13.5 18.75L14.6827 18.3558C15.3546 18.1318 15.8818 17.6046 16.1058 16.9327L16.5 15.75L16.8942 16.9327C17.1182 17.6046 17.6454 18.1318 18.3173 18.3558L19.5 18.75L18.3173 19.1442C17.6454 19.3682 17.1182 19.8954 16.8942 20.5673Z" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>"## }; +static DEEPINFRA: Icon = Icon { name: "deepinfra", view: 24.0, body: r##"<path d="M5.47441 8.86575C5.01828 8.86515 4.58101 8.6837 4.25849 8.36117C3.93596 8.03864 3.7545 7.60137 3.75391 7.14525C3.7543 6.689 3.93567 6.25154 4.25822 5.92885C4.58077 5.60616 5.01815 5.4246 5.47441 5.424C5.93092 5.4242 6.36869 5.60558 6.69156 5.92832C7.01443 6.25105 7.19601 6.68874 7.19641 7.14525C7.19561 7.6015 7.01386 8.03881 6.69103 8.36121C6.3682 8.68362 5.93066 8.86555 5.47441 8.86575ZM5.47441 6.09975C5.20378 6.11 4.94765 6.22471 4.75981 6.4198C4.57197 6.61489 4.46703 6.87518 4.46703 7.146C4.46703 7.41682 4.57197 7.67711 4.75981 7.8722C4.94765 8.06729 5.20378 8.182 5.47441 8.19225C5.74503 8.182 6.00116 8.06729 6.189 7.8722C6.37684 7.67711 6.48178 7.41682 6.48178 7.146C6.48178 6.87518 6.37684 6.61489 6.189 6.4198C6.00116 6.22471 5.74503 6.11 5.47441 6.09975ZM5.47441 13.7198C5.01815 13.7192 4.58077 13.5376 4.25822 13.2149C3.93567 12.8922 3.7543 12.4548 3.75391 11.9985C3.7545 11.5424 3.93596 11.1051 4.25849 10.7826C4.58101 10.4601 5.01828 10.2786 5.47441 10.278C5.93066 10.2784 6.36812 10.4598 6.69081 10.7823C7.0135 11.1049 7.19506 11.5422 7.19566 11.9985C7.19526 12.4549 7.01379 12.8925 6.69107 13.2152C6.36836 13.5379 5.93079 13.7194 5.47441 13.7198ZM5.47441 10.9537C5.20398 10.964 4.94803 11.0786 4.76033 11.2736C4.57263 11.4685 4.46776 11.7286 4.46776 11.9992C4.46776 12.2699 4.57263 12.53 4.76033 12.7249C4.94803 12.9199 5.20398 13.0345 5.47441 13.0447C5.61504 13.0501 5.75529 13.027 5.88679 12.9768C6.01828 12.9267 6.13831 12.8505 6.23969 12.7529C6.34106 12.6553 6.42171 12.5383 6.47679 12.4088C6.53187 12.2793 6.56026 12.14 6.56026 11.9992C6.56026 11.8585 6.53187 11.7192 6.47679 11.5897C6.42171 11.4602 6.34106 11.3432 6.23969 11.2456C6.13831 11.148 6.01828 11.0718 5.88679 11.0217C5.75529 10.9715 5.61504 10.9484 5.47441 10.9537ZM5.47441 18.5707C5.01828 18.5702 4.58101 18.3887 4.25849 18.0662C3.93596 17.7436 3.7545 17.3064 3.75391 16.8502C3.7543 16.394 3.93567 15.9565 4.25822 15.6338C4.58077 15.3112 5.01815 15.1296 5.47441 15.129C5.93079 15.1294 6.36836 15.3109 6.69107 15.6336C7.01379 15.9563 7.19526 16.3939 7.19566 16.8502C7.19506 17.3065 7.0135 17.7439 6.69081 18.0664C6.36812 18.389 5.93066 18.5704 5.47441 18.5707ZM5.47441 15.8047C5.20378 15.815 4.94765 15.9297 4.75981 16.1248C4.57197 16.3199 4.46703 16.5802 4.46703 16.851C4.46703 17.1218 4.57197 17.3821 4.75981 17.5772C4.94765 17.7723 5.20378 17.887 5.47441 17.8973C5.74503 17.887 6.00116 17.7723 6.189 17.5772C6.37684 17.3821 6.48178 17.1218 6.48178 16.851C6.48178 16.5802 6.37684 16.3199 6.189 16.1248C6.00116 15.9297 5.74503 15.815 5.47441 15.8047ZM18.5574 8.86575C18.1012 8.86535 17.6637 8.68398 17.341 8.36143C17.0183 8.03889 16.8368 7.6015 16.8362 7.14525C16.8366 6.689 17.0179 6.25154 17.3405 5.92885C17.663 5.60616 18.1004 5.4246 18.5567 5.424C19.013 5.4244 19.4506 5.60587 19.7733 5.92858C20.096 6.25129 20.2775 6.68887 20.2779 7.14525C20.2773 7.60137 20.0959 8.03864 19.7733 8.36117C19.4508 8.6837 19.0135 8.86515 18.5574 8.86575ZM18.5574 6.09975C18.3503 6.0996 18.1477 6.1609 17.9754 6.27589C17.8031 6.39088 17.6688 6.55439 17.5895 6.74573C17.5102 6.93708 17.4894 7.14766 17.5297 7.35083C17.5701 7.55399 17.6698 7.74062 17.8163 7.88709C17.9628 8.03356 18.1494 8.13329 18.3526 8.17367C18.5557 8.21404 18.7663 8.19325 18.9577 8.11391C19.149 8.03457 19.3125 7.90026 19.4275 7.72796C19.5425 7.55567 19.6038 7.35314 19.6037 7.146C19.6037 6.5685 19.1342 6.09975 18.5574 6.09975ZM18.5574 13.7198C18.101 13.7194 17.6634 13.5379 17.3407 13.2152C17.018 12.8925 16.8366 12.4549 16.8362 11.9985C16.8368 11.5424 17.0182 11.1051 17.3407 10.7826C17.6633 10.4601 18.1005 10.2786 18.5567 10.278C19.0129 10.2784 19.4504 10.4598 19.7731 10.7823C20.0957 11.1049 20.2773 11.5422 20.2779 11.9985C20.2775 12.4548 20.0961 12.8922 19.7736 13.2149C19.451 13.5376 19.0137 13.7192 18.5574 13.7198ZM18.5574 10.9537C17.9807 10.9537 17.5112 11.4225 17.5112 11.9985C17.5214 12.2691 17.6361 12.5253 17.8312 12.7131C18.0263 12.9009 18.2866 13.0059 18.5574 13.0059C18.8282 13.0059 19.0885 12.9009 19.2836 12.7131C19.4787 12.5253 19.5934 12.2691 19.6037 11.9985C19.6037 11.421 19.1342 10.9537 18.5574 10.9537ZM18.5574 18.5707C18.1012 18.5704 17.6637 18.389 17.341 18.0664C17.0183 17.7439 16.8368 17.3065 16.8362 16.8502C16.8366 16.394 17.0179 15.9565 17.3405 15.6338C17.663 15.3112 18.1004 15.1296 18.5567 15.129C19.013 15.1294 19.4506 15.3109 19.7733 15.6336C20.096 15.9563 20.2775 16.3939 20.2779 16.8502C20.2773 17.3064 20.0959 17.7436 19.7733 18.0662C19.4508 18.3887 19.0135 18.5702 18.5574 18.5707ZM18.5574 15.8047C18.3503 15.8046 18.1477 15.8659 17.9754 15.9809C17.8031 16.0959 17.6688 16.2594 17.5895 16.4507C17.5102 16.6421 17.4894 16.8527 17.5297 17.0558C17.5701 17.259 17.6698 17.4456 17.8163 17.5921C17.9628 17.7386 18.1494 17.8383 18.3526 17.8787C18.5557 17.919 18.7663 17.8982 18.9577 17.8189C19.149 17.7396 19.3125 17.6053 19.4275 17.433C19.5425 17.2607 19.6038 17.0581 19.6037 16.851C19.6037 16.2735 19.1342 15.8047 18.5574 15.8047ZM12.0159 11.2928C11.5598 11.2922 11.1225 11.1107 10.8 10.7882C10.4775 10.4656 10.296 10.0284 10.2954 9.57225C10.2958 9.116 10.4772 8.67854 10.7997 8.35585C11.1223 8.03316 11.5597 7.8516 12.0159 7.851C12.4723 7.8514 12.9099 8.03287 13.2326 8.35558C13.5553 8.67829 13.7368 9.11587 13.7372 9.57225C13.7366 10.0285 13.555 10.4659 13.2323 10.7884C12.9096 11.111 12.4722 11.2924 12.0159 11.2928ZM12.0159 8.52675C11.8088 8.5266 11.6062 8.5879 11.4339 8.70289C11.2616 8.81788 11.1273 8.98139 11.048 9.17273C10.9687 9.36408 10.9479 9.57466 10.9882 9.77783C11.0286 9.98099 11.1283 10.1676 11.2748 10.3141C11.4213 10.4606 11.6079 10.5603 11.8111 10.6007C12.0142 10.641 12.2248 10.6202 12.4162 10.5409C12.6075 10.4616 12.771 10.3273 12.886 10.155C13.001 9.98267 13.0623 9.78014 13.0622 9.573C13.0622 8.9955 12.5934 8.52675 12.0159 8.52675ZM12.0167 6.44175C11.5603 6.44135 11.1227 6.25988 10.8 5.93717C10.4773 5.61446 10.2958 5.17688 10.2954 4.7205C10.296 4.26425 10.4776 3.82686 10.8003 3.50432C11.1229 3.18177 11.5604 3.0004 12.0167 3C12.4728 3.0006 12.91 3.18205 13.2326 3.50458C13.5551 3.82711 13.7366 4.26438 13.7372 4.7205C13.7368 5.17675 13.5554 5.61421 13.2328 5.9369C12.9103 6.25959 12.4729 6.44115 12.0167 6.44175ZM12.0167 3.67575C11.8095 3.6756 11.607 3.7369 11.4347 3.85189C11.2624 3.96688 11.1281 4.13039 11.0487 4.32173C10.9694 4.51308 10.9486 4.72366 10.989 4.92683C11.0294 5.12999 11.1291 5.31662 11.2756 5.46309C11.422 5.60956 11.6087 5.70929 11.8118 5.74967C12.015 5.79004 12.2256 5.76925 12.4169 5.68991C12.6083 5.61057 12.7718 5.47626 12.8868 5.30396C13.0018 5.13167 13.0631 4.92914 13.0629 4.722C13.0629 4.1445 12.5934 3.67575 12.0167 3.67575ZM12.0167 16.1467C11.5603 16.1464 11.1227 15.9649 10.8 15.6422C10.4773 15.3195 10.2958 14.8819 10.2954 14.4255C10.296 13.9692 10.4776 13.5319 10.8003 13.2093C11.1229 12.8868 11.5604 12.7054 12.0167 12.705C12.4728 12.7056 12.91 12.8871 13.2326 13.2096C13.5551 13.5321 13.7366 13.9694 13.7372 14.4255C13.7368 14.8818 13.5554 15.3192 13.2328 15.6419C12.9103 15.9646 12.4729 16.1462 12.0167 16.1467ZM12.0167 13.3807C11.8095 13.3806 11.607 13.4419 11.4347 13.5569C11.2624 13.6719 11.1281 13.8354 11.0487 14.0267C10.9694 14.2181 10.9486 14.4287 10.989 14.6318C11.0294 14.835 11.1291 15.0216 11.2756 15.1681C11.422 15.3146 11.6087 15.4143 11.8118 15.4547C12.015 15.495 12.2256 15.4742 12.4169 15.3949C12.6083 15.3156 12.7718 15.1813 12.8868 15.009C13.0018 14.8367 13.0631 14.6341 13.0629 14.427C13.0629 13.8495 12.5934 13.3807 12.0167 13.3807ZM12.0159 21C11.5597 20.9994 11.1223 20.8178 10.7997 20.4952C10.4772 20.1725 10.2958 19.735 10.2954 19.2787C10.296 18.8226 10.4775 18.3854 10.8 18.0628C11.1225 17.7403 11.5598 17.5588 12.0159 17.5582C12.4722 17.5586 12.9096 17.74 13.2323 18.0626C13.555 18.3851 13.7366 18.8225 13.7372 19.2787C13.7368 19.7351 13.5553 20.1727 13.2326 20.4954C12.9099 20.8181 12.4723 20.9996 12.0159 21ZM12.0159 18.234C11.8088 18.2339 11.6062 18.2952 11.4339 18.4101C11.2616 18.5251 11.1273 18.6886 11.048 18.88C10.9687 19.0713 10.9479 19.2819 10.9882 19.4851C11.0286 19.6882 11.1283 19.8749 11.2748 20.0213C11.4213 20.1678 11.6079 20.2675 11.8111 20.3079C12.0142 20.3483 12.2248 20.3275 12.4162 20.2482C12.6075 20.1688 12.771 20.0345 12.886 19.8622C13.001 19.6899 13.0623 19.4874 13.0622 19.2803C13.0622 18.7028 12.5934 18.234 12.0159 18.234Z" fill="currentColor"/><path d="M9.27627 9.16647C9.20512 9.16662 9.13459 9.15313 9.06852 9.12672L7.94802 8.67972C7.87728 8.65388 7.81245 8.6141 7.75737 8.56274C7.70229 8.51138 7.65809 8.44948 7.62738 8.38072C7.59667 8.31195 7.58008 8.23772 7.5786 8.16242C7.57712 8.08713 7.59077 8.0123 7.61875 7.94238C7.64673 7.87246 7.68846 7.80887 7.74148 7.75538C7.79449 7.70189 7.85771 7.65959 7.92738 7.63099C7.99704 7.60239 8.07175 7.58807 8.14705 7.58888C8.22236 7.5897 8.29674 7.60562 8.36577 7.63572L9.48552 8.08197C9.60669 8.13061 9.70717 8.2199 9.76971 8.33452C9.83226 8.44913 9.85298 8.58194 9.82833 8.71017C9.80368 8.83839 9.73519 8.95404 9.6346 9.0373C9.53401 9.12055 9.40759 9.16622 9.27702 9.16647H9.27627ZM9.27627 13.9245C9.20512 13.9246 9.1346 13.9111 9.06852 13.8847L7.94802 13.4385C7.80948 13.3831 7.69862 13.2749 7.63982 13.1378C7.58103 13.0006 7.57912 12.8458 7.63452 12.7072C7.68992 12.5687 7.79808 12.4578 7.93522 12.399C8.07235 12.3402 8.22723 12.3383 8.36577 12.3937L9.48552 12.8407C9.60622 12.8897 9.70618 12.979 9.76836 13.0934C9.83054 13.2079 9.85108 13.3403 9.82648 13.4682C9.80187 13.5961 9.73364 13.7115 9.63344 13.7947C9.53323 13.8779 9.40726 13.9238 9.27702 13.9245H9.27627ZM15.847 11.5477C15.7758 11.5476 15.7053 11.5339 15.6393 11.5072L14.5195 11.061C14.4478 11.036 14.3819 10.9967 14.3258 10.9455C14.2697 10.8944 14.2245 10.8324 14.193 10.7633C14.1615 10.6942 14.1443 10.6194 14.1424 10.5435C14.1406 10.4676 14.1542 10.3921 14.1823 10.3215C14.2104 10.251 14.2525 10.1869 14.3061 10.133C14.3597 10.0792 14.4236 10.0368 14.494 10.0083C14.5644 9.97988 14.6398 9.96597 14.7158 9.96745C14.7917 9.96894 14.8665 9.98578 14.9358 10.017L16.0555 10.4632C16.1767 10.5119 16.2772 10.6012 16.3397 10.7158C16.4023 10.8304 16.423 10.9632 16.3983 11.0914C16.3737 11.2196 16.3052 11.3353 16.2046 11.4185C16.104 11.5018 15.9776 11.5475 15.847 11.5477ZM15.847 6.78747C15.7758 6.78734 15.7053 6.7736 15.6393 6.74697L14.5195 6.29997C14.3874 6.24045 14.2833 6.13224 14.229 5.99787C14.1747 5.86351 14.1743 5.71338 14.228 5.57876C14.2817 5.44414 14.3852 5.33544 14.5171 5.2753C14.649 5.21516 14.7989 5.20824 14.9358 5.25597L16.0555 5.70297C16.1762 5.75192 16.2762 5.84124 16.3384 5.95568C16.4005 6.07012 16.4211 6.20259 16.3965 6.33049C16.3719 6.45839 16.3036 6.57379 16.2034 6.65699C16.1032 6.74019 15.9773 6.78604 15.847 6.78672V6.78747ZM15.847 16.3042C15.7759 16.3044 15.7053 16.2909 15.6393 16.2645L14.5188 15.8175C14.4475 15.7921 14.3821 15.7526 14.3265 15.7013C14.2708 15.65 14.2261 15.5881 14.1949 15.5191C14.1638 15.4502 14.1469 15.3757 14.1452 15.3C14.1435 15.2244 14.1571 15.1492 14.1852 15.0789C14.2133 15.0087 14.2552 14.9448 14.3085 14.8911C14.3619 14.8375 14.4255 14.7951 14.4955 14.7666C14.5656 14.7381 14.6407 14.724 14.7163 14.7252C14.792 14.7263 14.8666 14.7428 14.9358 14.7735L16.0555 15.2205C16.1762 15.2694 16.2762 15.3587 16.3384 15.4732C16.4005 15.5876 16.4211 15.7201 16.3965 15.848C16.3719 15.9759 16.3036 16.0913 16.2034 16.1745C16.1032 16.2577 15.9773 16.3035 15.847 16.3042ZM8.18652 16.4745C8.05622 16.474 7.93013 16.4282 7.82979 16.3451C7.72946 16.2619 7.6611 16.1466 7.6364 16.0186C7.61169 15.8907 7.63218 15.7581 7.69435 15.6436C7.75652 15.5291 7.85652 15.4397 7.97727 15.3907L9.09777 14.9445C9.23621 14.8892 9.39095 14.8911 9.52795 14.9499C9.66494 15.0087 9.77297 15.1195 9.82827 15.258C9.88357 15.3964 9.88161 15.5511 9.82281 15.6881C9.76402 15.8251 9.65321 15.9332 9.51477 15.9885L8.39502 16.4347C8.32894 16.4611 8.25767 16.4746 8.18652 16.4745ZM8.18652 11.745C8.05589 11.7449 7.92935 11.6993 7.82863 11.6162C7.72791 11.533 7.65928 11.4173 7.63453 11.289C7.60979 11.1608 7.63045 11.0279 7.69299 10.9132C7.75553 10.7985 7.85604 10.7091 7.97727 10.6605L9.09777 10.2142C9.23484 10.1654 9.38551 10.1716 9.51812 10.2315C9.65073 10.2913 9.75497 10.4003 9.80894 10.5354C9.86292 10.6706 9.86243 10.8214 9.80757 10.9561C9.75272 11.0909 9.64777 11.1992 9.51477 11.2582L8.39502 11.7045C8.32894 11.7309 8.25842 11.7444 8.18727 11.7442L8.18652 11.745ZM8.18652 6.77472C8.05589 6.77464 7.92935 6.7291 7.82863 6.6459C7.72791 6.56271 7.65928 6.44705 7.63453 6.31878C7.60979 6.19051 7.63045 6.05763 7.69299 5.94293C7.75553 5.82824 7.85604 5.73889 7.97727 5.69022L9.09777 5.24397C9.23484 5.19513 9.38551 5.2013 9.51812 5.2612C9.65073 5.3211 9.75497 5.43006 9.80894 5.56519C9.86292 5.70032 9.86243 5.85111 9.80757 5.98588C9.75272 6.12066 9.64777 6.22893 9.51477 6.28797L8.39502 6.73497C8.32894 6.76134 8.25767 6.77483 8.18652 6.77472ZM9.27627 19.023C9.20512 19.0231 9.1346 19.0096 9.06852 18.9832L7.94802 18.5362C7.81588 18.4767 7.71181 18.3685 7.65751 18.2341C7.6032 18.0998 7.60284 17.9496 7.65652 17.815C7.71019 17.6804 7.81375 17.5717 7.9456 17.5115C8.07746 17.4514 8.22743 17.4445 8.36427 17.4922L9.48477 17.9385C9.60594 17.9871 9.70642 18.0764 9.76896 18.191C9.83151 18.3056 9.85223 18.4384 9.82758 18.5667C9.80293 18.6949 9.73444 18.8105 9.63385 18.8938C9.53326 18.977 9.40684 19.0227 9.27627 19.023ZM14.7265 9.16722C14.5956 9.1674 14.4687 9.12193 14.3678 9.03862C14.2668 8.95532 14.198 8.8394 14.1733 8.71084C14.1486 8.58229 14.1695 8.44914 14.2325 8.33435C14.2954 8.21956 14.3964 8.1303 14.518 8.08197L15.6385 7.63572C15.7766 7.58277 15.9299 7.58632 16.0654 7.64559C16.2009 7.70486 16.3075 7.81508 16.3624 7.9524C16.4172 8.08973 16.4157 8.24312 16.3583 8.37937C16.3009 8.51563 16.1921 8.62379 16.0555 8.68047L14.935 9.12672C14.8692 9.15325 14.799 9.167 14.728 9.16722H14.7265ZM14.7265 13.9252C14.596 13.925 14.4695 13.8793 14.3689 13.796C14.2684 13.7128 14.1999 13.5971 14.1752 13.4689C14.1506 13.3407 14.1713 13.2079 14.2338 13.0933C14.2964 12.9787 14.3969 12.8894 14.518 12.8407L15.6385 12.3937C15.7772 12.3384 15.9321 12.3405 16.0692 12.3994C16.2064 12.4583 16.3145 12.5693 16.3698 12.708C16.4251 12.8466 16.423 13.0015 16.3641 13.1387C16.3052 13.2758 16.1942 13.3839 16.0555 13.4392L14.935 13.8855C14.8692 13.9118 14.7989 13.9253 14.728 13.9252H14.7265ZM14.7265 19.0222C14.5958 19.0224 14.4691 18.9771 14.3682 18.8939C14.2673 18.8107 14.1986 18.695 14.1739 18.5666C14.1492 18.4382 14.1701 18.3052 14.2329 18.1906C14.2957 18.0759 14.3965 17.9868 14.518 17.9385L15.6385 17.4922C15.7078 17.461 15.7826 17.4442 15.8585 17.4427C15.9345 17.4412 16.0099 17.4551 16.0803 17.4836C16.1507 17.512 16.2146 17.5545 16.2682 17.6083C16.3218 17.6621 16.3639 17.7262 16.392 17.7968C16.4201 17.8673 16.4337 17.9428 16.4319 18.0187C16.43 18.0947 16.4128 18.1694 16.3813 18.2385C16.3498 18.3076 16.3046 18.3696 16.2485 18.4208C16.1924 18.4719 16.1265 18.5112 16.0548 18.5362L14.9343 18.9825C14.8682 19.0089 14.7977 19.0224 14.7265 19.0222Z" fill="currentColor"/>"## }; +static DEEPSEEK: Icon = Icon { name: "deepseek", view: 40.0, body: r##"<path d="M35.6638 9.91965C35.3251 9.75432 35.1785 10.0703 34.9811 10.2316C34.9131 10.2836 34.8558 10.3516 34.7985 10.413C34.3025 10.9423 33.7238 11.289 32.9678 11.2476C31.8625 11.1863 30.9186 11.533 30.0839 12.3783C29.9066 11.3356 29.3173 10.7143 28.4213 10.3143C27.9519 10.1063 27.4773 9.89965 27.148 9.44766C26.9186 9.12633 26.856 8.76767 26.7413 8.41568C26.668 8.20235 26.5946 7.98502 26.3506 7.94902C26.084 7.90769 25.98 8.13035 25.876 8.31702C25.4587 9.07967 25.2973 9.91965 25.3133 10.7703C25.3493 12.6849 26.1573 14.2102 27.764 15.2942C27.9466 15.4182 27.9933 15.5435 27.9359 15.7249C27.8266 16.0982 27.696 16.4609 27.5813 16.8355C27.508 17.0742 27.3986 17.1248 27.1426 17.0222C26.2777 16.6504 25.4919 16.1164 24.828 15.4489C23.6854 14.3449 22.6534 13.1263 21.3654 12.1716C21.067 11.9511 20.7606 11.7416 20.4468 11.5436C19.1335 10.2676 20.6201 9.21967 20.9641 9.09567C21.3241 8.965 21.0881 8.51968 19.9254 8.52501C18.7628 8.53035 17.6988 8.91834 16.3428 9.43699C16.1413 9.51421 15.934 9.57529 15.7229 9.61966C14.4557 9.38091 13.1598 9.33506 11.8789 9.48366C9.36565 9.76365 7.35902 10.953 5.88305 12.9809C4.10975 15.4182 3.69243 18.1888 4.20308 21.0768C4.74041 24.122 6.29504 26.6433 8.683 28.6139C11.1603 30.6579 14.0122 31.6592 17.2668 31.4672C19.2428 31.3539 21.4441 31.0886 23.9254 28.9873C24.552 29.2993 25.208 29.4233 26.2986 29.5166C27.1386 29.5953 27.9466 29.4766 28.5719 29.3459C29.5519 29.1379 29.4839 28.23 29.1306 28.0646C26.2573 26.726 26.888 27.2713 26.3133 26.83C27.7746 25.102 29.9746 23.3074 30.8359 17.4928C30.9026 17.0302 30.8452 16.7395 30.8359 16.3662C30.8306 16.1395 30.8826 16.0502 31.1426 16.0249C31.8639 15.95 32.5637 15.7349 33.2025 15.3915C35.0638 14.3742 35.8158 12.7049 35.9931 10.7023C36.0198 10.3956 35.9878 10.081 35.6638 9.91965ZM19.4414 27.9433C16.6562 25.754 15.3055 25.0327 14.7482 25.0634C14.2256 25.0954 14.3202 25.6913 14.4349 26.0807C14.5549 26.4647 14.7109 26.7286 14.9295 27.066C15.0815 27.2886 15.1855 27.6206 14.7789 27.87C13.8816 28.4246 12.3229 27.6833 12.2496 27.6473C10.435 26.578 8.91632 25.1673 7.84834 23.2381C6.81637 21.3808 6.21638 19.3888 6.11771 17.2622C6.09105 16.7475 6.24171 16.5662 6.7537 16.4729C7.42583 16.3442 8.11451 16.3267 8.79233 16.4209C11.6349 16.8368 14.0536 18.1075 16.0828 20.1194C17.2402 21.2661 18.1161 22.6354 19.0188 23.974C19.9788 25.3953 21.0108 26.75 22.3254 27.8593C22.7894 28.2486 23.1587 28.5446 23.5134 28.7619C22.4441 28.8819 20.6601 28.9086 19.4414 27.9433ZM20.7748 19.3568C20.7745 19.2906 20.7904 19.2253 20.8211 19.1666C20.8517 19.1078 20.8962 19.0575 20.9507 19.0198C21.0052 18.9821 21.068 18.9583 21.1337 18.9503C21.1995 18.9424 21.2662 18.9505 21.3281 18.9741C21.407 19.0024 21.475 19.0546 21.5228 19.1235C21.5706 19.1923 21.5958 19.2743 21.5947 19.3581C21.5949 19.4123 21.5843 19.4659 21.5636 19.5159C21.5428 19.5659 21.5123 19.6113 21.4738 19.6494C21.4354 19.6875 21.3897 19.7176 21.3395 19.7378C21.2893 19.7581 21.2356 19.7682 21.1814 19.7675C21.1277 19.7676 21.0745 19.7571 21.0248 19.7365C20.9752 19.7158 20.9302 19.6855 20.8925 19.6473C20.8548 19.609 20.825 19.5636 20.805 19.5138C20.785 19.4639 20.7739 19.4105 20.7748 19.3568ZM24.9213 21.4848C24.6547 21.5928 24.3893 21.6861 24.1347 21.6981C23.7516 21.7114 23.3756 21.5918 23.0707 21.3594C22.7054 21.0528 22.4441 20.8821 22.3347 20.3488C22.297 20.0881 22.3042 19.823 22.3561 19.5648C22.4494 19.1288 22.3454 18.8488 22.0374 18.5955C21.7881 18.3875 21.4694 18.3302 21.1201 18.3302C21.0005 18.3232 20.8843 18.2875 20.7814 18.2262C20.6348 18.1542 20.5148 17.9728 20.6294 17.7488C20.6668 17.6768 20.8428 17.5008 20.8854 17.4688C21.3601 17.1995 21.9081 17.2875 22.4134 17.4902C22.8827 17.6822 23.2374 18.0342 23.748 18.5328C24.2694 19.1341 24.364 19.3008 24.6613 19.7515C24.896 20.1048 25.1093 20.4674 25.2547 20.8821C25.344 21.1421 25.2293 21.3541 24.9213 21.4848Z" fill="currentColor"/>"## }; +static DIGITALOCEAN: Icon = Icon { name: "digitalocean", view: 100.8, body: r##"<path d="M50.4 72.7L36.4 72.7L36.4 58.6L36.4 58.6L50.4 58.6L50.4 58.6L50.4 72.7Z" fill="currentColor" fill-rule="evenodd"/><path d="M36.4 83.5L25.6 83.5L25.6 83.5L25.6 72.7L36.4 72.7L36.4 83.5Z" fill="currentColor" fill-rule="evenodd"/><path d="M25.6 72.7L16.5 72.7L16.5 72.7L16.5 63.6L16.5 63.6L25.5 63.6L25.6 63.6L25.6 72.7Z" fill="currentColor" fill-rule="evenodd"/><path d="M50.4 14C30.3 14 14 30.3 14 50.4L28.1 50.4C28.1 38.1 38.1 28.1 50.4 28.1S72.7 38.1 72.7 50.4S62.7 72.7 50.4 72.7L50.4 72.7L50.4 86.8L50.4 86.8C70.5 86.8 86.8 70.5 86.8 50.4S70.5 14 50.4 14Z" fill="currentColor"/>"## }; +static EVROC: Icon = Icon { name: "evroc", view: 100.0, body: r##"<path d="M79.01 43.363C74.944 43.363 72.499 46.283 72.499 49.898C72.499 53.533 74.944 56.453 79.01 56.453C83.056 56.453 85.522 53.533 85.522 49.898S83.056 43.363 79.01 43.363ZM79.01 54.331C76.377 54.331 74.838 52.398 74.838 49.898S76.377 45.443 79.01 45.443C81.645 45.443 83.161 47.376 83.161 49.877C83.161 52.398 81.645 54.331 79.011 54.331ZM93.403 56.427C96.796 56.427 98.945 54.619 99.24 51.888L96.88 51.888C96.564 53.443 95.363 54.325 93.403 54.325C90.98 54.325 89.525 52.645 89.525 49.892C89.525 47.118 91.001 45.458 93.403 45.458C95.363 45.458 96.543 46.32 96.88 47.958L99.24 47.958C98.945 45.185 96.796 43.336 93.403 43.336C89.547 43.336 87.186 46.005 87.186 49.871C87.186 53.758 89.546 56.427 93.403 56.427ZM63.86 56.116L66.22 56.116L66.22 50.106C66.22 47.354 67.568 45.862 69.992 45.862L72.268 45.862L72.268 43.677L70.013 43.677C67.885 43.677 66.725 44.412 66.115 46.282L65.672 46.219L66.199 43.677L63.839 43.677L63.839 56.116L63.859 56.116ZM39.415 48.784C39.521 46.683 40.932 45.254 43.208 45.254C45.484 45.254 46.854 46.599 46.854 48.784L39.415 48.784ZM49.193 49.184C49.193 45.758 46.812 43.363 43.25 43.363C39.52 43.363 37.076 45.926 37.076 49.898C37.076 53.911 39.499 56.453 43.356 56.453C46.285 56.453 48.603 54.856 49.025 52.566L46.665 52.566C46.158 53.722 44.999 54.394 43.355 54.394C40.975 54.394 39.478 52.986 39.415 50.591L49.109 50.591C49.151 50.003 49.193 49.73 49.193 49.183ZM54.883 56.116L56.822 56.116L62.322 43.676L59.793 43.676L56 53.49L55.684 53.511L51.891 43.678L49.383 43.678L54.883 56.117ZM32.23 49.85C32.23 48.968 31.871 48.149 31.24 47.413A8.594 8.594 0 0 1 29.743 48.506C30.08 48.926 30.27 49.367 30.27 49.851C30.27 52.582 24.433 54.662 16.13 54.662C7.849 54.683 2.012 52.603 2.012 49.851C2.012 49.388 2.18 48.926 2.517 48.506A8.13 8.13 0 0 1 1.042 47.413C0.41 48.149 0.052 48.968 0.052 49.851C0.052 53.885 7.259 56.385 16.152 56.385C25.022 56.406 32.23 53.885 32.23 49.85ZM28.879 51.384C27.973 50.922 26.919 50.523 25.719 50.187C24.349 50.565 22.81 50.859 21.166 51.048C23.484 51.342 25.507 51.826 27.066 52.456C27.826 52.12 28.436 51.763 28.879 51.384ZM11.03 51.027A31.902 31.902 0 0 1 6.563 50.187C5.383 50.523 4.308 50.922 3.403 51.384C3.823 51.763 4.413 52.099 5.151 52.434C6.69 51.804 8.671 51.321 11.031 51.027ZM32.23 44.219C32.23 40.206 25.023 37.685 16.151 37.685C7.26 37.685 0.051 40.206 0.051 44.219C0.051 48.254 7.259 50.754 16.151 50.754C25.023 50.775 32.23 48.254 32.23 44.219ZM30.29 44.219C30.29 46.951 24.454 49.031 16.151 49.031C7.849 49.052 2.011 46.971 2.011 44.219C2.011 41.488 7.849 39.408 16.151 39.408C24.011 39.408 30.291 41.488 30.291 44.219ZM27.067 46.783C27.825 46.447 28.437 46.089 28.879 45.711C25.929 44.198 21.335 43.358 16.151 43.358S6.352 44.198 3.423 45.711C3.845 46.089 4.435 46.426 5.173 46.761C7.68 45.711 11.536 45.081 16.151 45.081C20.555 45.081 24.475 45.732 27.067 46.783ZM1.042 53.128C0.41 53.864 0.052 54.662 0.052 55.566C0.052 59.6 7.259 62.1 16.152 62.1C25.044 62.1 32.251 59.579 32.251 55.566C32.251 54.683 31.892 53.864 31.261 53.128C30.839 53.528 30.354 53.885 29.764 54.221C30.101 54.641 30.291 55.082 30.291 55.566C30.291 58.297 24.454 60.377 16.151 60.377C7.849 60.377 2.011 58.297 2.011 55.566C2.011 55.103 2.181 54.641 2.517 54.221A10.73 10.73 0 0 1 1.042 53.128Z" fill="currentColor"/>"## }; +static FASTROUTER: Icon = Icon { name: "fastrouter", view: 40.0, body: r##"<path d="M31.8828 10.4098L28.0164 16.8684V13.3842H20.2592L17.7616 17.6895C17.6127 17.9132 17.6127 18.2116 17.7243 18.4353C17.8733 18.6591 18.0966 18.8083 18.3944 18.8083H26.6951L15.491 36L17.6499 25.7073C17.6871 25.4836 17.6499 25.2598 17.501 25.0733C17.3521 24.8869 17.1288 24.8123 16.9055 24.8123H8.19531L14.1496 7.42506H18.3261V7.41479L28.0164 7.42506V4L31.8828 10.4098Z" fill="currentColor"/>"## }; +static FIREWORKS_AI: Icon = Icon { name: "fireworks-ai", view: 24.0, body: r##"<path d="M14.45 5.74999L11.9991 11.6956L9.54562 5.74999H7.97237L10.6604 12.2495C10.7678 12.5138 10.9515 12.7402 11.1882 12.8996C11.4248 13.059 11.7036 13.1442 11.9889 13.1444C12.2742 13.1446 12.5531 13.0597 12.79 12.9006C13.0268 12.7415 13.2109 12.5154 13.3186 12.2512L16.0232 5.74999H14.45ZM15.4965 14.808L19.98 10.2195L19.3684 8.75911L14.4719 13.7807C14.272 13.9856 14.1369 14.2448 14.0835 14.5261C14.0301 14.8073 14.0608 15.098 14.1718 15.3619C14.2807 15.624 14.4648 15.848 14.7008 16.0056C14.9369 16.1632 15.2144 16.2473 15.4983 16.2474L15.5 16.25L22.5 16.2325L21.8884 14.7721L15.4983 14.808H15.4965ZM4.02 10.216L4.63162 8.75561L9.52813 13.7772C9.93763 14.1964 10.0557 14.8176 9.82825 15.3584C9.71925 15.6204 9.53511 15.8443 9.29905 16.0019C9.06299 16.1595 8.78557 16.2437 8.50175 16.2439L1.50175 16.2281L1.5 16.2299L2.11163 14.7695L8.50175 14.8062L4.02 10.216Z" fill="currentColor"/>"## }; +static FIRMWARE: Icon = Icon { name: "firmware", view: 40.0, body: r##"<path d="M31.884 37.9851L39.9946 37.9851L38.3089 34.7734L35.4336 34.1265L32.6063 28.4919L36.2972 22.2893L34.8327 19.4034L35.9145 19.4034L37.8692 18.1418L37.8692 16.9877L38.6868 16.9877L38.6868 12.665L34.9188 11.4848L33.9477 10.1479L29.107 10.1479L25.4482 14.2264L21.8016 6.9593L0.0406 2.0465L14.5193 18.3093L12.8597 18.3093L6.9235 22.5198L3.9223 28.3331L2.6561 28.6912L2.6561 23.7953L3.9176 22.967L1.1438 18.7396L1.1438 30.6874L4.9641 29.6101L8.0959 23.5402L11.4012 21.1956L6.5747 30.9041L6.5747 34.7289L7.8991 37.9851L13.0224 37.9851L13.0224 36.3425L12.4034 35.0409L10.9573 34.1571L10.9573 33.4012L13.9351 28.4792L13.9351 31.6909L16.5414 34.698L17.671 36.7097L17.671 37.9851L23.601 37.9851L23.601 36.3517L22.9493 34.8842L21.399 34.0467L19.561 31.3251L20.972 28.7084L25.2563 29.3797L24.2497 34.9118L24.2372 37.9851L30.1998 37.9851L30.1998 36.4178L29.9216 35.3173L29.0732 34.4893L29.7198 33.1979L31.884 36.5544ZM34.0661 17.8929L35.4689 17.8929L36.3572 17.3197L36.3572 16.9877L35.6289 16.9877L35.6289 15.4772L37.1763 15.4772L37.1763 13.7745L33.9892 12.7772L33.1778 11.6585L30.9024 11.6585ZM29.4155 12.0652L28.3541 13.249L33.6411 23.7977L34.5729 22.2309ZM26.1765 15.6778L27.2702 14.4578L32.7242 25.3394L31.8021 26.8894ZM13.7721 19.8199L8.0852 31.2575L8.0852 34.4338L8.915 36.4731L11.4121 36.4731L11.2322 36.0966L9.4467 35.0056L9.4467 32.9802L13.6494 26.0312L28.3849 28.3409L33.3945 36.1088L33.3945 36.4731L37.4945 36.4731L37.2962 36.0949L34.404 35.4435L34.2428 35.1238L24.8983 16.499L16.3448 19.8199ZM24.2176 15.1419L20.772 8.2747L17.0831 7.442L22.5697 15.7817ZM21.1295 16.341L14.9597 6.9627L10.5622 5.9701L19.4359 16.9987ZM17.9584 17.5723L8.1932 5.4353L4.2973 4.5559L16.3956 18.1464L16.3302 18.2046ZM15.4459 31.1283L15.4459 27.8427L19.3893 28.4605L17.7984 31.4127L20.354 35.1992L21.7769 35.9675L22.0014 36.4731L19.1816 36.4731L19.1816 36.3148L17.783 33.8252ZM28.7686 31.7225L27.4827 29.7285L26.7492 29.6135L25.7495 35.1161L25.7495 36.4731L28.6554 36.4731L28.5615 36.0996L27.2276 34.7996ZM29.1085 6.6197L29.1073 6.6197L29.1073 9.1414L33.9477 9.1414L33.9477 6.6197L33.9443 6.6197L32.738 7.8275L31.53 6.6197L31.5243 6.6197L30.3163 7.8275Z" fill="currentColor" fill-rule="evenodd"/>"## }; +static FRIENDLI: Icon = Icon { name: "friendli", view: 40.0, body: r##"<path d="M15.1484 16.5153V16.5238C14.5325 17.3971 14.4945 18.6923 14.5114 19.3925V21.4091C14.5114 22.7379 13.4272 23.8221 12.1067 23.8221H9.24219C7.91327 23.8221 6.8375 22.7423 6.8375 21.4091V18.5952C6.8375 17.262 7.91327 16.182 9.24219 16.182H10.9339C11.2376 16.182 11.9717 16.1694 12.2923 16.1061C12.5666 16.0513 13.4525 15.853 14.2963 15.2201C14.3891 15.1526 14.4734 15.0852 14.5451 15.0219C14.5451 15.0219 14.7392 14.8574 14.9122 14.6759C15.3889 14.1824 15.7559 13.4778 15.7559 13.4778C15.8741 13.2584 16.1441 12.7016 16.3044 11.9295C16.3803 11.5541 16.4141 11.2039 16.4394 10.917L16.528 9.24219C16.528 7.91327 17.6079 6.83329 18.9369 6.83329H21.7339C23.0629 6.83329 24.1427 7.91327 24.1427 9.24219V12.0603C24.1427 13.3892 23.0629 14.4692 21.7339 14.4692H19.4346C18.9073 14.4819 18.4686 14.5367 18.1438 14.5958C17.5489 14.7055 17.2409 14.832 17.1481 14.87M10.6428 14.8109C8.35625 14.8109 6.5 12.9505 6.5 10.6555C6.5 8.36046 8.35625 6.5 10.6428 6.5C12.9294 6.5 14.7856 8.36046 14.7856 10.6555C14.7856 12.9505 12.9294 14.8109 10.6428 14.8109ZM10.6428 25.1891C12.9294 25.1891 14.7856 27.0496 14.7856 29.3446C14.7856 31.6396 12.9294 33.5 10.6428 33.5C8.35625 33.5 6.5 31.6396 6.5 29.3446C6.5 27.0496 8.35625 25.1891 10.6428 25.1891ZM33.5 12.1405C33.5 13.4272 32.4538 14.4734 31.1671 14.4734C30.4963 14.4355 29.9352 14.4566 29.526 14.4819C28.8341 14.5283 28.429 14.5536 27.8933 14.7181C27.29 14.9037 26.8598 15.1611 26.615 15.3087C26.5096 15.372 26.0919 15.6294 25.6067 16.0597C25.3325 16.3044 25.0709 16.5364 24.8009 16.9076C24.4254 17.4265 24.261 17.899 24.1766 18.1521C23.9487 18.8356 23.9066 19.7848 23.9192 20.2448L23.8939 21.4808C23.8939 22.7717 22.8519 23.8179 21.5652 23.8179H18.6079C17.3211 23.8179 16.2791 22.7717 16.2791 21.4808V18.515C16.2791 17.2241 17.3211 16.1778 18.6079 16.1778H20.3965C21.0294 16.1778 22.2865 16.2326 23.3539 15.8403C24.2694 15.507 25.1848 14.5789 25.5434 13.5622C25.8852 12.5286 25.8767 11.1533 25.8767 11.1533L25.8852 9.16625C25.8852 7.87952 26.9314 6.83329 28.2181 6.83329H31.1671C32.4538 6.83329 33.5 7.87952 33.5 9.16625V12.1405Z" fill="currentColor"/>"## }; +static GITHUB_COPILOT: Icon = Icon { name: "github-copilot", view: 40.0, body: r##"<path d="M35.3993 26.4544C34.2871 28.3855 27.8314 32.9425 20 32.9425C12.1686 32.9425 5.71288 28.3855 4.60075 26.4544C4.5427 26.3532 4.50826 26.2401 4.5 26.1237V22.418C4.51199 22.3209 4.53496 22.2256 4.56846 22.1338C5.04896 20.9261 6.30833 19.1733 7.93325 18.7031C8.14896 18.149 8.468 17.3404 8.76508 16.7437C8.71727 16.2776 8.69485 15.8094 8.69792 15.3409C8.69792 13.6217 9.06217 12.113 10.1601 10.9906C10.6729 10.4662 11.3097 10.0644 12.064 9.76091C13.871 8.29357 16.4453 7.05745 19.9716 7.05745C23.4978 7.05745 26.129 8.29357 27.936 9.76091C28.6903 10.0644 29.3271 10.4662 29.8399 10.9906C30.9378 12.113 31.3021 13.6217 31.3021 15.3409C31.3021 15.8162 31.284 16.2877 31.2349 16.7437C31.532 17.3404 31.851 18.149 32.0667 18.7031C33.6917 19.1733 34.951 20.9261 35.4315 22.1338C35.4677 22.2248 35.4908 22.3205 35.5 22.418V26.1237C35.4917 26.2401 35.4573 26.3532 35.3993 26.4544ZM20.2222 18.7147H19.7778C19.6422 18.945 19.4889 19.1644 19.3193 19.3709C18.3247 20.5941 16.8419 21.2981 14.7881 21.2981C12.56 21.2981 10.9273 20.8344 9.90304 19.6719C9.86495 19.6283 9.82833 19.5835 9.79325 19.5375L9.66667 19.6719V28.1775C11.5202 29.1837 15.4972 30.992 20 30.992C24.5028 30.992 28.4798 29.1837 30.3333 28.1775V19.6719L30.2067 19.5375C30.2067 19.5375 30.1641 19.5957 30.097 19.6719C29.0727 20.8344 27.44 21.2981 25.2119 21.2981C23.1581 21.2981 21.6753 20.5941 20.6807 19.3709C20.5111 19.1644 20.3578 18.945 20.2222 18.7147ZM23.2292 22.9127C23.9383 22.9127 24.5208 23.4952 24.5208 24.2043V26.7877C24.5208 27.4968 23.9383 28.0793 23.2292 28.0793C22.52 28.0793 21.9375 27.4968 21.9375 26.7877V24.2043C21.9375 23.4952 22.52 22.9127 23.2292 22.9127ZM16.7708 22.9127C17.48 22.9127 18.0625 23.4952 18.0625 24.2043V26.7877C18.0625 27.4968 17.48 28.0793 16.7708 28.0793C16.0617 28.0793 15.4792 27.4968 15.4792 26.7877V24.2043C15.4792 23.4952 16.0617 22.9127 16.7708 22.9127ZM21.0501 14.9237C21.2258 16.289 21.5707 17.3947 22.1842 18.149C22.7551 18.8517 23.649 19.3606 25.2119 19.3606C27.2437 19.3606 28.1724 18.9253 28.6438 18.3905C29.1398 17.8287 29.3646 16.9051 29.3646 15.3409C29.3646 13.8684 29.0507 12.9552 28.454 12.3455C27.8378 11.7152 26.7502 11.2321 24.8063 11.0216C22.8856 10.8136 21.975 11.1998 21.5345 11.7049C21.187 12.1014 20.97 12.7485 20.9688 13.7431V13.7702C20.9688 14.1121 20.9959 14.4966 21.0501 14.9237ZM18.9499 14.9237C19.0041 14.4966 19.0312 14.1117 19.0312 13.7689V13.7431C19.03 12.7485 18.813 12.1014 18.4655 11.7049C18.025 11.1998 17.1144 10.8136 15.1937 11.0216C13.2498 11.2321 12.1622 11.7152 11.546 12.3455C10.9493 12.9552 10.6354 13.8684 10.6354 15.3409C10.6354 16.9051 10.8615 17.8287 11.3562 18.3905C11.8276 18.9253 12.7563 19.3606 14.7881 19.3606C16.351 19.3606 17.2449 18.8517 17.8158 18.149C18.4293 17.3947 18.7742 16.289 18.9499 14.9237Z" fill="currentColor"/>"## }; +static GITHUB_MODELS: Icon = Icon { name: "github-models", view: 40.0, body: r##"<path d="M20.0015 4.4704C11.4373 4.4704 4.50074 11.407 4.50074 19.9712C4.49793 23.2252 5.52031 26.3975 7.42272 29.0376C9.32512 31.6776 12.0109 33.6513 15.0986 34.6783C15.8737 34.8132 16.1651 34.3481 16.1651 33.9405C16.1651 33.5731 16.1449 32.3532 16.1449 31.0542C12.2511 31.7719 11.2436 30.1056 10.9336 29.2329C10.7584 28.7865 10.0035 27.4115 9.34473 27.0426C8.8022 26.7528 8.02716 26.0351 9.32458 26.0165C10.546 25.9963 11.4172 27.1403 11.7086 27.6053C13.1037 29.949 15.3311 29.2902 16.2224 28.8841C16.3588 27.8766 16.7649 27.1992 17.2114 26.8117C13.7624 26.4241 10.1585 25.0864 10.1585 19.1574C10.1585 17.4709 10.7584 16.0774 11.7473 14.9923C11.5923 14.6048 11.0498 13.016 11.9024 10.8846C11.9024 10.8846 13.1998 10.4769 16.1651 12.4719C17.4271 12.1226 18.7308 11.9468 20.0403 11.9495C21.3578 11.9495 22.6754 12.1231 23.9155 12.4719C26.8808 10.4568 28.1782 10.8846 28.1782 10.8846C29.0307 13.016 28.4882 14.6048 28.3332 14.9923C29.3206 16.0774 29.922 17.4523 29.922 19.1574C29.922 25.1066 26.2995 26.4241 22.8506 26.8117C23.4117 27.2953 23.8969 28.2253 23.8969 29.6793C23.8969 31.7518 23.8767 33.4181 23.8767 33.942C23.8767 34.3481 24.1681 34.8318 24.9432 34.6768C28.0193 33.6368 30.6922 31.6589 32.5859 29.0211C34.4796 26.3833 35.499 23.2183 35.5007 19.9712C35.5007 11.407 28.5641 4.4704 20 4.4704" fill="currentColor"/>"## }; +static GITLAB: Icon = Icon { name: "gitlab", view: 380.0, body: r##"<path d="M265.26416,174.37243l-.2134-.55822-21.19899-55.30908c-.4236-1.08359-1.18542-1.99642-2.17699-2.62689-.98837-.63373-2.14749-.93253-3.32305-.87014-1.1689.06239-2.29195.48925-3.20809,1.21821-.90957.73554-1.56629,1.73047-1.87493,2.85346l-14.31327,43.80662h-57.90965l-14.31327-43.80662c-.30864-1.12299-.96536-2.11791-1.87493-2.85346-.91614-.72895-2.03911-1.15582-3.20809-1.21821-1.17548-.06239-2.33468.23641-3.32297.87014-.99166.63047-1.75348,1.5433-2.17707,2.62689l-21.19891,55.31237-.21348.55493c-6.28158,16.38521-.92929,34.90803,13.05891,45.48782.02621.01641.04922.03611.07552.05582l.18719.14119,32.29094,24.17392,15.97151,12.09024,9.71951,7.34871c2.34117,1.77316,5.57877,1.77316,7.92002,0l9.71943-7.34871,15.96822-12.09024,32.48142-24.31511c.02958-.02299.05588-.04269.08538-.06568,13.97834-10.57977,19.32735-29.09604,13.04905-45.47796Z" fill="currentColor"/>"## }; +static GOOGLE: Icon = Icon { name: "google", view: 40.0, body: r##"<path d="M37 20.034C27.8809 20.5837 20.5808 27.8809 20.0326 37H19.966C19.4163 27.8809 12.1177 20.5837 3 20.034V19.9674C12.1191 19.4163 19.4163 12.1191 19.966 3H20.0326C20.5822 12.1191 27.8809 19.4163 37 19.9674V20.034Z" fill="currentColor"/>"## }; +static GOOGLE_VERTEX: Icon = Icon { name: "google-vertex", view: 24.0, body: r##"<path d="M11.9959 18.3671C11.6069 18.3671 11.2339 18.5216 10.9589 18.7966C10.6838 19.0716 10.5293 19.4447 10.5293 19.8336C10.5293 20.2226 10.6838 20.5956 10.9589 20.8707C11.2339 21.1457 11.6069 21.3002 11.9959 21.3002C12.3849 21.3002 12.7579 21.1457 13.0329 20.8707C13.308 20.5956 13.4625 20.2226 13.4625 19.8336C13.4625 19.4447 13.308 19.0716 13.0329 18.7966C12.7579 18.5216 12.3849 18.3671 11.9959 18.3671ZM11.9959 20.5416C11.8534 20.5415 11.7141 20.4991 11.5958 20.4198C11.4774 20.3404 11.3853 20.2276 11.3313 20.0957C11.2772 19.9639 11.2636 19.8189 11.2921 19.6793C11.3207 19.5397 11.3901 19.4117 11.4916 19.3116C11.5931 19.2116 11.722 19.144 11.862 19.1174C12.002 19.0908 12.1468 19.1065 12.2778 19.1624C12.4089 19.2183 12.5204 19.312 12.5981 19.4314C12.6758 19.5509 12.7163 19.6908 12.7143 19.8333C12.7143 19.9271 12.6956 20.0201 12.6594 20.1067C12.6232 20.1933 12.5701 20.2718 12.5033 20.3377C12.4364 20.4036 12.3571 20.4556 12.27 20.4906C12.1829 20.5256 12.0897 20.5429 11.9959 20.5416Z" fill="currentColor"/><path d="M19.5066 13.6615C19.6903 13.691 19.8569 13.7855 19.9755 13.9281C20.0812 14.0834 20.1256 14.2725 20.0998 14.4587C20.074 14.6449 19.98 14.8148 19.836 14.9356L13.4504 19.6488C13.418 19.3931 13.3188 19.1504 13.1628 18.9452C13.0067 18.74 12.7993 18.5796 12.5615 18.4802L18.9781 13.7685C19.1355 13.6701 19.3233 13.6321 19.5066 13.6615Z" fill="currentColor"/><path d="M10.5444 19.6271L4.17667 14.9262C4.02822 14.8115 3.92907 14.6444 3.89941 14.4592C3.86975 14.2739 3.91182 14.0842 4.01703 13.9289C4.13459 13.7843 4.30127 13.6881 4.48524 13.6587C4.66922 13.6293 4.85759 13.6686 5.01439 13.7692L11.431 18.4809C11.1966 18.5789 10.9917 18.736 10.8363 18.9369C10.6809 19.1378 10.5803 19.3756 10.5444 19.6271Z" fill="currentColor"/><path d="M6.01169 6.16856C5.81417 6.16595 5.62547 6.08633 5.48578 5.94664C5.3461 5.80696 5.26647 5.61826 5.26387 5.42073V3.54536C5.25156 3.43918 5.26186 3.3316 5.29408 3.22968C5.3263 3.12776 5.37971 3.03381 5.45081 2.95399C5.52191 2.87418 5.60909 2.81031 5.70662 2.76657C5.80416 2.72284 5.90984 2.70023 6.01673 2.70023C6.12362 2.70023 6.2293 2.72284 6.32683 2.76657C6.42437 2.81031 6.51155 2.87418 6.58265 2.95399C6.65375 3.03381 6.70716 3.12776 6.73938 3.22968C6.7716 3.3316 6.78189 3.43918 6.76959 3.54536V5.42073C6.76694 5.61999 6.68592 5.81019 6.54408 5.95015C6.40223 6.09011 6.21096 6.16858 6.01169 6.16856ZM5.99154 12.8013C6.19255 12.8013 6.38532 12.7215 6.52746 12.5794C6.66959 12.4372 6.74944 12.2445 6.74944 12.0434C6.74944 11.8424 6.66959 11.6497 6.52746 11.5075C6.38532 11.3654 6.19255 11.2855 5.99154 11.2855C5.79053 11.2855 5.59776 11.3654 5.45563 11.5075C5.31349 11.6497 5.23364 11.8424 5.23364 12.0434C5.23364 12.2445 5.31349 12.4372 5.45563 12.5794C5.59776 12.7215 5.79053 12.8013 5.99154 12.8013ZM5.99154 10.5974C6.09107 10.5974 6.18962 10.5778 6.28158 10.5397C6.37353 10.5016 6.45708 10.4458 6.52746 10.3754C6.59784 10.305 6.65366 10.2215 6.69175 10.1295C6.72984 10.0376 6.74944 9.93902 6.74944 9.83949C6.74944 9.73996 6.72984 9.64141 6.69175 9.54945C6.65366 9.4575 6.59784 9.37395 6.52746 9.30357C6.45708 9.2332 6.37353 9.17737 6.28158 9.13928C6.18962 9.10119 6.09107 9.08159 5.99154 9.08159C5.79053 9.08159 5.59776 9.16144 5.45563 9.30357C5.31349 9.44571 5.23364 9.63848 5.23364 9.83949C5.23364 10.0405 5.31349 10.2333 5.45563 10.3754C5.59776 10.5175 5.79053 10.5974 5.99154 10.5974ZM5.99154 8.38259C6.19255 8.38259 6.38532 8.30274 6.52746 8.1606C6.66959 8.01847 6.74944 7.8257 6.74944 7.62469C6.74944 7.42368 6.66959 7.23091 6.52746 7.08877C6.38532 6.94664 6.19255 6.86679 5.99154 6.86679C5.79053 6.86679 5.59776 6.94664 5.45563 7.08877C5.31349 7.23091 5.23364 7.42368 5.23364 7.62469C5.23364 7.8257 5.31349 8.01847 5.45563 8.1606C5.59776 8.30274 5.79053 8.38259 5.99154 8.38259Z" fill="currentColor"/><path d="M17.9807 8.36321C17.7813 8.36056 17.591 8.27944 17.451 8.13742C17.3111 7.99541 17.2327 7.80395 17.2329 7.60454V5.72916C17.2329 5.53083 17.3117 5.34062 17.4519 5.20037C17.5922 5.06013 17.7824 4.98134 17.9807 4.98134C18.1791 4.98134 18.3693 5.06013 18.5095 5.20037C18.6498 5.34062 18.7286 5.53083 18.7286 5.72916V7.60454C18.7301 7.70368 18.7119 7.80214 18.675 7.89417C18.6381 7.98621 18.5832 8.06997 18.5136 8.14059C18.444 8.21121 18.3611 8.26726 18.2696 8.30548C18.1781 8.3437 18.0799 8.36333 17.9807 8.36321ZM18.0001 12.8114C18.0996 12.8114 18.1982 12.7918 18.2901 12.7537C18.3821 12.7156 18.4656 12.6598 18.536 12.5894C18.6064 12.5191 18.6622 12.4355 18.7003 12.3436C18.7384 12.2516 18.758 12.153 18.758 12.0535C18.758 11.954 18.7384 11.8554 18.7003 11.7635C18.6622 11.6715 18.6064 11.588 18.536 11.5176C18.4656 11.4472 18.3821 11.3914 18.2901 11.3533C18.1982 11.3152 18.0996 11.2956 18.0001 11.2956C17.7991 11.2956 17.6063 11.3755 17.4642 11.5176C17.3221 11.6597 17.2422 11.8525 17.2422 12.0535C17.2422 12.2545 17.3221 12.4473 17.4642 12.5894C17.6063 12.7316 17.7991 12.8114 18.0001 12.8114ZM18.0001 10.5672C18.2011 10.5672 18.3939 10.4873 18.536 10.3452C18.6782 10.203 18.758 10.0103 18.758 9.80927C18.758 9.60826 18.6782 9.41548 18.536 9.27335C18.3939 9.13122 18.2011 9.05137 18.0001 9.05137C17.7991 9.05137 17.6063 9.13122 17.4642 9.27335C17.3221 9.41548 17.2422 9.60826 17.2422 9.80927C17.2422 10.0103 17.3221 10.203 17.4642 10.3452C17.6063 10.4873 17.7991 10.5672 18.0001 10.5672ZM18.0001 4.30326C18.0996 4.30326 18.1982 4.28366 18.2901 4.24557C18.3821 4.20748 18.4656 4.15165 18.536 4.08128C18.6064 4.0109 18.6622 3.92735 18.7003 3.8354C18.7384 3.74344 18.758 3.64489 18.758 3.54536C18.758 3.44583 18.7384 3.34728 18.7003 3.25532C18.6622 3.16337 18.6064 3.07982 18.536 3.00944C18.4656 2.93907 18.3821 2.88324 18.2901 2.84515C18.1982 2.80706 18.0996 2.78746 18.0001 2.78746C17.7991 2.78746 17.6063 2.86731 17.4642 3.00944C17.3221 3.15158 17.2422 3.34435 17.2422 3.54536C17.2422 3.74637 17.3221 3.93914 17.4642 4.08128C17.6063 4.22341 17.7991 4.30326 18.0001 4.30326Z" fill="currentColor"/><path d="M11.9957 15.0355C11.7982 15.0329 11.6095 14.9533 11.4698 14.8136C11.3301 14.6739 11.2505 14.4852 11.2479 14.2877V12.3821C11.2693 12.1974 11.3578 12.0271 11.4966 11.9034C11.6354 11.7798 11.8148 11.7114 12.0007 11.7114C12.1866 11.7114 12.366 11.7798 12.5049 11.9034C12.6437 12.0271 12.7322 12.1974 12.7536 12.3821V14.2675C12.7551 14.368 12.7367 14.4677 12.6992 14.5609C12.6618 14.6541 12.6062 14.739 12.5357 14.8104C12.4651 14.8819 12.381 14.9387 12.2883 14.9773C12.1956 15.0159 12.0961 15.0357 11.9957 15.0355ZM11.9957 17.2402C12.1967 17.2402 12.3895 17.1604 12.5316 17.0183C12.6737 16.8761 12.7536 16.6834 12.7536 16.4824C12.7536 16.2813 12.6737 16.0886 12.5316 15.9464C12.3895 15.8043 12.1967 15.7245 11.9957 15.7245C11.7947 15.7245 11.6019 15.8043 11.4598 15.9464C11.3176 16.0886 11.2378 16.2813 11.2378 16.4824C11.2378 16.6834 11.3176 16.8761 11.4598 17.0183C11.6019 17.1604 11.7947 17.2402 11.9957 17.2402ZM11.9957 10.9461C12.1967 10.9461 12.3895 10.8663 12.5316 10.7241C12.6737 10.582 12.7536 10.3892 12.7536 10.1882C12.7536 9.98721 12.6737 9.79444 12.5316 9.6523C12.3895 9.51017 12.1967 9.43032 11.9957 9.43032C11.7947 9.43032 11.6019 9.51017 11.4598 9.6523C11.3176 9.79444 11.2378 9.98721 11.2378 10.1882C11.2378 10.3892 11.3176 10.582 11.4598 10.7241C11.6019 10.8663 11.7947 10.9461 11.9957 10.9461ZM11.9957 8.73209C12.1967 8.73209 12.3895 8.65224 12.5316 8.51011C12.6737 8.36797 12.7536 8.1752 12.7536 7.97419C12.7536 7.77319 12.6737 7.58041 12.5316 7.43828C12.3895 7.29614 12.1967 7.21629 11.9957 7.21629C11.7947 7.21629 11.6019 7.29614 11.4598 7.43828C11.3176 7.58041 11.2378 7.77319 11.2378 7.97419C11.2378 8.1752 11.3176 8.36797 11.4598 8.51011C11.6019 8.65224 11.7947 8.73209 11.9957 8.73209Z" fill="currentColor"/><path d="M14.988 10.5873C14.7905 10.5847 14.6018 10.5051 14.4621 10.3654C14.3224 10.2257 14.2428 10.037 14.2402 9.83949V7.96411C14.2211 7.80387 14.2536 7.64171 14.3332 7.50128C14.4127 7.36086 14.535 7.24951 14.6823 7.1835C14.8295 7.11748 14.994 7.10025 15.1518 7.13431C15.3095 7.16836 15.4523 7.25194 15.5592 7.37283C15.6302 7.45267 15.6835 7.54662 15.7157 7.64852C15.7479 7.75042 15.7582 7.85796 15.7459 7.96411V9.83949C15.7433 10.0387 15.6623 10.2289 15.5204 10.3689C15.3786 10.5089 15.1873 10.5873 14.988 10.5873ZM14.9981 6.50799C15.0976 6.50799 15.1962 6.48838 15.2881 6.45029C15.3801 6.41221 15.4636 6.35638 15.534 6.286C15.6044 6.21563 15.6602 6.13207 15.6983 6.04012C15.7364 5.94817 15.756 5.84962 15.756 5.75009C15.756 5.65056 15.7364 5.552 15.6983 5.46005C15.6602 5.3681 15.6044 5.28455 15.534 5.21417C15.4636 5.14379 15.3801 5.08797 15.2881 5.04988C15.1962 5.01179 15.0976 4.99219 14.9981 4.99219C14.7971 4.99219 14.6043 5.07204 14.4622 5.21417C14.3201 5.3563 14.2402 5.54908 14.2402 5.75009C14.2402 5.95109 14.3201 6.14387 14.4622 6.286C14.6043 6.42814 14.7971 6.50799 14.9981 6.50799ZM14.9981 14.9859C15.1991 14.9859 15.3919 14.9061 15.534 14.7639C15.6762 14.6218 15.756 14.429 15.756 14.228C15.756 14.027 15.6762 13.8342 15.534 13.6921C15.3919 13.55 15.1991 13.4701 14.9981 13.4701C14.7971 13.4701 14.6043 13.55 14.4622 13.6921C14.3201 13.8342 14.2402 14.027 14.2402 14.228C14.2402 14.429 14.3201 14.6218 14.4622 14.7639C14.6043 14.9061 14.7971 14.9859 14.9981 14.9859ZM14.9981 12.7719C15.1991 12.7719 15.3919 12.692 15.534 12.5499C15.6762 12.4078 15.756 12.215 15.756 12.014C15.756 11.813 15.6762 11.6202 15.534 11.4781C15.3919 11.3359 15.1991 11.2561 14.9981 11.2561C14.7971 11.2561 14.6043 11.3359 14.4622 11.4781C14.3201 11.6202 14.2402 11.813 14.2402 12.014C14.2402 12.215 14.3201 12.4078 14.4622 12.5499C14.6043 12.692 14.7971 12.7719 14.9981 12.7719Z" fill="currentColor"/><path d="M8.99364 14.9859C9.19465 14.9859 9.38742 14.9061 9.52955 14.764C9.67169 14.6218 9.75154 14.4291 9.75154 14.228C9.75154 14.027 9.67169 13.8343 9.52955 13.6921C9.38742 13.55 9.19465 13.4701 8.99364 13.4701C8.79263 13.4701 8.59986 13.55 8.45772 13.6921C8.31559 13.8343 8.23574 14.027 8.23574 14.228C8.23574 14.4291 8.31559 14.6218 8.45772 14.764C8.59986 14.9061 8.79263 14.9859 8.99364 14.9859ZM8.99364 8.73211C9.19465 8.73211 9.38742 8.65227 9.52955 8.51013C9.67169 8.368 9.75154 8.17522 9.75154 7.97422C9.75154 7.77321 9.67169 7.58043 9.52955 7.4383C9.38742 7.29617 9.19465 7.21632 8.99364 7.21632C8.79263 7.21632 8.59986 7.29617 8.45772 7.4383C8.31559 7.58043 8.23574 7.77321 8.23574 7.97422C8.23574 8.17522 8.31559 8.368 8.45772 8.51013C8.59986 8.65227 8.79263 8.73211 8.99364 8.73211ZM8.99364 6.50801C9.19475 6.50801 9.38762 6.42812 9.52983 6.28592C9.67203 6.14371 9.75192 5.95084 9.75192 5.74973C9.75192 5.54862 9.67203 5.35574 9.52983 5.21354C9.38762 5.07133 9.19475 4.99144 8.99364 4.99144C8.79253 4.99144 8.59966 5.07133 8.45745 5.21354C8.31524 5.35574 8.23535 5.54862 8.23535 5.74973C8.23535 5.95084 8.31524 6.14371 8.45745 6.28592C8.59966 6.42812 8.79253 6.50801 8.99364 6.50801ZM9.00371 12.7719C8.8077 12.7721 8.61926 12.6963 8.47795 12.5604C8.33663 12.4246 8.25343 12.2393 8.24581 12.0435V10.1487C8.24581 9.95038 8.3246 9.76017 8.46485 9.61993C8.60509 9.47968 8.7953 9.4009 8.99364 9.4009C9.19197 9.4009 9.38219 9.47968 9.52243 9.61993C9.66267 9.76017 9.74146 9.95038 9.74146 10.1487V12.0435C9.73628 12.2366 9.65661 12.4203 9.5191 12.5561C9.3816 12.6918 9.19693 12.7692 9.00371 12.7719Z" fill="currentColor"/>"## }; +static GOOGLE_VERTEX_ANTHROPIC: Icon = Icon { name: "google-vertex-anthropic", view: 24.0, body: r##"<path d="M9.8132 15.9038L9 18.75L8.1868 15.9038C7.75968 14.4089 6.59112 13.2403 5.09619 12.8132L2.25 12L5.09619 11.1868C6.59113 10.7597 7.75968 9.59112 8.1868 8.09619L9 5.25L9.8132 8.09619C10.2403 9.59113 11.4089 10.7597 12.9038 11.1868L15.75 12L12.9038 12.8132C11.4089 13.2403 10.2403 14.4089 9.8132 15.9038Z" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/><path d="M18.2589 8.71454L18 9.75L17.7411 8.71454C17.4388 7.50533 16.4947 6.56117 15.2855 6.25887L14.25 6L15.2855 5.74113C16.4947 5.43883 17.4388 4.49467 17.7411 3.28546L18 2.25L18.2589 3.28546C18.5612 4.49467 19.5053 5.43883 20.7145 5.74113L21.75 6L20.7145 6.25887C19.5053 6.56117 18.5612 7.50533 18.2589 8.71454Z" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/><path d="M16.8942 20.5673L16.5 21.75L16.1058 20.5673C15.8818 19.8954 15.3546 19.3682 14.6827 19.1442L13.5 18.75L14.6827 18.3558C15.3546 18.1318 15.8818 17.6046 16.1058 16.9327L16.5 15.75L16.8942 16.9327C17.1182 17.6046 17.6454 18.1318 18.3173 18.3558L19.5 18.75L18.3173 19.1442C17.6454 19.3682 17.1182 19.8954 16.8942 20.5673Z" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>"## }; +static GROQ: Icon = Icon { name: "groq", view: 40.0, body: r##"<path d="M20.056 4.50022C14.0839 4.44597 9.20616 9.15015 9.15036 15.0106C9.09611 20.8726 13.8855 25.6621 19.8576 25.7163H23.6085V21.7391H20.056C16.3252 21.7825 13.2671 18.8468 13.2237 15.1827C13.1787 11.5216 16.1702 8.52086 19.901 8.47746H20.056C23.7868 8.47746 26.8108 11.4457 26.8216 15.1083V24.8809C26.8216 28.5109 23.8085 31.4683 20.1211 31.5132C18.3617 31.5007 16.6759 30.8049 15.42 29.5726L12.551 32.3905C14.5529 34.3571 17.239 35.4715 20.0451 35.4998H20.1877C26.0823 35.413 30.8175 30.7212 30.85 24.9351V14.8603C30.7059 9.0928 25.9165 4.50022 20.056 4.50022Z" fill="currentColor"/>"## }; +static HELICONE: Icon = Icon { name: "helicone", view: 24.0, body: r##"<path d="M18.3697 8.08776L12 10.8745V11.7289V17.8656L18.3697 8.08776Z" fill="currentColor" fill-opacity="0.25"/><path d="M3.30005 7.06824V14.9138L10.047 10.02L3.30005 7.06824Z" fill="currentColor" fill-opacity="0.25"/><path d="M11.8755 3.31646L3.30005 7.06824L10.047 10.02L12 10.8745L18.3697 8.08776L20.7 7.06824L12.1246 3.31646C12.0452 3.28173 11.9549 3.28173 11.8755 3.31646Z" fill="currentColor" fill-opacity="0.35"/><path d="M3.30005 7.06824L11.8755 3.31646C11.9549 3.28173 12.0452 3.28173 12.1246 3.31646L20.7 7.06824M3.30005 7.06824V14.9138M3.30005 7.06824L10.047 10.02M20.7 7.06824L18.3697 8.08776M20.7 7.06824V9.08787M3.30005 14.9138V16.8822C3.30005 17.0073 3.37512 17.1203 3.49053 17.1687L4.07684 17.4148M3.30005 14.9138L10.047 10.02M10.047 10.02L12 10.8745M18.3697 8.08776L12 10.8745M18.3697 8.08776L12 17.8656M20.7 9.08787V16.8822C20.7 17.0073 20.625 17.1203 20.5096 17.1687L13.942 19.9247M20.7 9.08787L13.942 19.9247M12 20.7397V17.8656M12 20.7397L13.942 19.9247M12 20.7397L4.07684 17.4148M12 17.8656V11.7289M4.07684 17.4148L12 11.7289M12 10.8745V11.7289" fill="none" stroke="currentColor" stroke-width="0.6214" stroke-linecap="round" stroke-linejoin="round"/>"## }; +static HUGGINGFACE: Icon = Icon { name: "huggingface", view: 40.0, body: r##"<path d="M26.7365 7.70867C30.9594 10.1097 33.562 14.5441 33.562 19.3448C33.562 20.7468 33.3436 22.0995 32.9378 23.3705C33.2276 23.3346 33.5219 23.3669 33.7971 23.4647C34.0723 23.5626 34.3208 23.7233 34.523 23.9341C34.8338 24.2495 35.0303 24.6597 35.0814 25.0996C35.1324 25.5394 35.0351 25.9837 34.8048 26.3619C35.0922 26.5944 35.3008 26.9044 35.4079 27.2525L35.4318 27.3398C35.5164 27.6526 35.6009 28.3121 35.15 28.9828C35.4938 29.5042 35.5431 30.1608 35.2811 30.7244C34.9217 31.5276 34.0228 32.1588 32.2826 32.838L31.9979 32.9479L31.8133 33.0156C31.1398 33.2593 30.5593 33.4312 30.3183 33.5017L30.1971 33.5355C28.9431 33.8779 27.6495 34.0639 26.3476 34.0907C24.4876 34.0907 23.1067 33.5834 22.2289 32.5872C20.7465 32.8382 19.2331 32.8468 17.748 32.6126C16.8688 33.5933 15.4935 34.0907 13.6504 34.0907C12.4424 34.0666 11.2411 33.9044 10.07 33.6074L9.75858 33.5228L9.37391 33.4101C8.81508 33.2406 8.26281 33.0503 7.71825 32.8394C5.97523 32.1588 5.07625 31.529 4.71693 30.7244C4.45485 30.1608 4.50416 29.5028 4.84798 28.9828C4.68566 28.7453 4.57646 28.4756 4.52782 28.1921C4.47919 27.9085 4.49227 27.6178 4.56616 27.3398C4.66339 26.9552 4.88461 26.6127 5.19602 26.3619C4.96607 25.9839 4.86892 25.5399 4.91997 25.1003C4.97102 24.6607 5.16735 24.2508 5.47783 23.9355C5.80614 23.5861 6.26268 23.3846 6.76995 23.362L6.87985 23.3606C6.46754 22.0619 6.2584 20.7073 6.25986 19.3448C6.25986 14.5441 8.86242 10.1097 13.0854 7.70867C15.1666 6.52898 17.518 5.90889 19.9102 5.90889C22.3025 5.90889 24.6553 6.52898 26.7365 7.70867ZM8.99205 23.8862C9.16818 24.8542 12.3132 27.1975 12.0075 27.7006C11.7397 28.1444 10.8858 27.3638 10.6717 27.1566L10.6139 27.1003L10.3772 26.8932C9.58668 26.2182 7.13067 24.2159 6.51631 24.8754C5.91041 25.5235 6.68399 26.0858 8.00288 26.8762L9.10759 27.5343L9.29923 27.6512C10.7717 28.5573 10.8774 28.8349 10.6378 29.2195C10.3729 29.6352 6.312 26.2605 5.93155 27.6935C5.5511 29.1181 10.077 29.5309 9.79804 30.5201C9.51622 31.5064 6.60649 28.6545 6.01469 29.7634C5.41583 30.8766 10.1193 32.1842 10.1574 32.1941L10.3828 32.2504L10.6294 32.3096C12.3583 32.7098 15.6527 33.2255 16.8786 31.4585C17.8269 30.0875 17.7804 29.0504 16.5292 27.7809L16.4488 27.7006C15.1173 26.3929 14.3423 24.4766 14.3423 24.4766L14.3183 24.3949L14.2831 24.2934C14.1676 23.9834 13.8829 23.393 13.3954 23.4705C12.7472 23.5734 12.271 25.1755 13.5645 26.1943L13.6349 26.2478C15.0116 27.2637 13.3602 27.9528 12.8275 27.0002L12.7458 26.8537L12.5443 26.5014C11.8919 25.3756 10.7379 23.5269 10.0939 23.1239C9.34432 22.6561 8.81592 22.9154 8.99205 23.8862ZM29.9055 23.1239C29.1544 23.5959 27.7031 26.0463 27.1719 27.0002C27.0805 27.1684 26.9358 27.3014 26.7606 27.3785C26.5854 27.4555 26.3895 27.4721 26.2038 27.4258C26.1115 27.3997 26.0266 27.3525 25.9558 27.2877C25.9293 27.2626 25.9061 27.2342 25.8868 27.2031L25.8671 27.1637L25.8558 27.1355L25.8459 27.1087L25.8417 27.0904L25.8375 27.0665C25.8337 27.0441 25.8318 27.0215 25.8318 26.9988C25.8318 26.8297 25.9319 26.624 26.1841 26.3972C26.2207 26.3633 26.2602 26.3309 26.3025 26.2985L26.3687 26.2478C26.3997 26.2253 26.4293 26.2027 26.4575 26.1788C27.7017 25.1783 27.2649 23.6283 26.6421 23.4776L26.5984 23.4691L26.5195 23.4635C26.4902 23.4638 26.4609 23.4667 26.4321 23.4719L26.3927 23.479L26.3335 23.4987L26.2785 23.5227L26.2391 23.5438L26.1996 23.5706L26.1489 23.6086L26.1165 23.6368C25.8727 23.8594 25.7318 24.2399 25.6797 24.4005L25.6571 24.4766C25.6571 24.4766 24.9103 26.3211 23.6295 27.6245L23.5534 27.7006C23.0391 28.205 22.7136 28.6728 22.5642 29.135C22.3627 29.7507 22.4712 30.3581 22.8601 31.0415C22.9376 31.1781 23.025 31.3162 23.1236 31.4585C24.3664 33.2551 27.7482 32.6929 29.456 32.2899L29.859 32.1913L30.2112 32.087C30.6001 31.9686 31.2483 31.7587 31.9021 31.4952L32.167 31.3867L32.2586 31.3472L32.3488 31.3078L32.5235 31.2289L32.6376 31.1753C33.383 30.8202 33.996 30.4102 34.0383 30.01L34.0397 29.9593C34.0385 29.8907 34.0206 29.8235 33.9875 29.7634C33.8551 29.5154 33.6057 29.4647 33.2957 29.5267L33.2323 29.5408C33.1703 29.5549 33.1055 29.5746 33.0406 29.5972L32.904 29.6465L32.8279 29.6775C32.0402 30.0016 31.0834 30.6709 30.5635 30.7272H30.572C30.5486 30.7299 30.525 30.7314 30.5015 30.7315H30.4677L30.4339 30.7272L30.4015 30.7202C30.3056 30.6976 30.238 30.6356 30.2042 30.5201C30.191 30.4743 30.1886 30.4261 30.1971 30.3792C30.2845 29.8931 31.547 29.5408 32.6109 29.0969L32.7039 29.0575C33.4479 28.7419 34.0707 28.3769 34.0918 27.8851V27.8288C34.0892 27.7821 34.0816 27.7358 34.0693 27.6907C34.0016 27.4371 33.8227 27.337 33.562 27.337C32.4559 27.337 29.9689 29.2533 29.4475 29.2533C29.4123 29.2533 29.3799 29.2435 29.3658 29.2195C29.3408 29.1801 29.3191 29.1386 29.301 29.0955C29.1601 28.7602 29.3968 28.4445 30.7946 27.5935L31.0891 27.4159C31.8472 26.965 32.5122 26.5874 32.9786 26.245C33.3873 25.9463 33.648 25.6729 33.6874 25.3995L33.6916 25.3601C33.7029 25.2009 33.6381 25.0402 33.4845 24.8754C33.4561 24.8447 33.4228 24.819 33.3859 24.7993L33.338 24.7781L33.3196 24.7711C33.2605 24.7517 33.1987 24.7422 33.1365 24.7429C32.9082 24.7429 32.6165 24.8415 32.2981 24.9965C31.4005 25.4376 30.2817 26.338 29.7251 26.8072L29.3742 27.1101L29.3277 27.1566C29.215 27.2666 28.9219 27.5371 28.6331 27.7006L28.533 27.7527L28.4753 27.7795C28.4202 27.8031 28.3625 27.8202 28.3034 27.8302H28.3104C28.2959 27.8322 28.2813 27.8337 28.2667 27.8344L28.2808 27.833L28.2625 27.8344C28.1512 27.8415 28.0582 27.8048 27.9948 27.7006C27.9792 27.6727 27.9723 27.6408 27.975 27.609C28.0131 26.9537 30.8411 24.8035 31.0074 23.8862L31.02 23.8186C31.1609 22.9027 30.6382 22.6674 29.9055 23.1239ZM19.9123 7.29581C13.1516 7.29581 7.67034 12.6911 7.67034 19.3434C7.67034 20.3184 7.7873 21.2653 8.00852 22.1728L8.01979 22.1601C8.37488 21.7402 8.88214 21.5119 9.45282 21.5119C9.95304 21.5232 10.4378 21.6768 10.852 21.9515C11.162 22.1488 11.5072 22.4926 11.8595 22.9294C12.2273 22.4053 12.8318 22.0868 13.4799 22.077C14.6805 22.077 15.4061 23.1028 15.6809 24.0257L15.7471 24.1736L15.8317 24.3526C16.1022 24.9106 16.6701 25.9575 17.4422 26.7198C18.9359 28.1853 19.3078 29.7 18.5695 31.3219C19.5178 31.4242 20.4747 31.4176 21.4215 31.3021C20.7099 29.724 21.0551 28.2444 22.4642 26.8128L22.5572 26.7198C23.5365 25.756 24.1875 24.3385 24.3213 24.0257C24.5961 23.1028 25.3189 22.077 26.5195 22.077C27.1676 22.0868 27.7721 22.4053 28.1399 22.9294C28.4922 22.4926 28.8374 22.1502 29.1516 21.9515C29.5658 21.6763 30.0494 21.5239 30.5466 21.5119C31.0496 21.5119 31.5076 21.6895 31.85 22.0192C32.0472 21.1596 32.1529 20.2649 32.1529 19.3448C32.1529 12.6911 26.6716 7.29581 19.9123 7.29581ZM22.529 19.8732L23.1476 19.5744C23.9268 19.2025 24.4016 19.0348 24.4016 19.7886C24.4016 21.3287 23.3152 24.3089 19.956 24.385H19.6968C16.4207 24.3117 15.3061 21.4823 15.2497 19.9112L15.2483 19.7886C15.2483 18.2288 17.2943 20.6143 19.8278 20.6143C20.8367 20.6143 21.7709 20.2311 22.529 19.8732ZM28.1892 15.4445C28.8233 15.4445 29.3348 15.9489 29.3348 16.5717C29.3348 17.1931 28.8219 17.699 28.1892 17.699C28.0401 17.7001 27.8922 17.6718 27.754 17.6158C27.6157 17.5597 27.4899 17.477 27.3837 17.3723C27.2774 17.2676 27.1928 17.1431 27.1347 17.0057C27.0766 16.8683 27.0462 16.7209 27.0451 16.5717C27.0451 15.9489 27.558 15.4445 28.1892 15.4445ZM11.8102 15.4445C12.4415 15.4445 12.9544 15.9489 12.9544 16.5717C12.9544 17.1931 12.4415 17.699 11.8102 17.699C11.6609 17.7003 11.5129 17.6721 11.3745 17.6162C11.2361 17.5602 11.1101 17.4775 11.0037 17.3728C10.8973 17.2681 10.8126 17.1435 10.7544 17.006C10.6962 16.8686 10.6657 16.721 10.6646 16.5717C10.6646 15.9489 11.1775 15.4445 11.8102 15.4445ZM22.7868 14.2594C23.2377 13.7184 23.9789 13.4985 24.6609 13.7043C25.3415 13.91 25.8304 14.499 25.8981 15.1979C25.9657 15.8954 25.5993 16.5647 24.9695 16.893C24.5158 17.1297 24.3396 16.2209 23.8887 16.0687L23.8916 16.0645C23.4872 15.9264 22.8038 16.5745 22.5882 16.1758C22.425 15.8734 22.3565 15.529 22.3917 15.1872C22.4269 14.8455 22.5655 14.5222 22.7868 14.2594ZM16.6954 14.2594C17.1492 14.8005 17.2267 15.5558 16.8927 16.1758C16.6785 16.5745 15.9909 15.9264 15.5893 16.0645L15.5935 16.0687C15.4414 16.1194 15.3202 16.2575 15.2089 16.4069L15.0426 16.6394C14.8876 16.8507 14.7326 17.0085 14.5114 16.893C14.2053 16.7349 13.9535 16.4889 13.7882 16.1866C13.623 15.8843 13.552 15.5395 13.5842 15.1965C13.6518 14.499 14.1408 13.91 14.8214 13.7043C15.1538 13.6037 15.5085 13.6026 15.8415 13.7013C16.1746 13.7999 16.4714 13.994 16.6954 14.2594Z" fill="currentColor"/>"## }; +static IFLOWCN: Icon = Icon { name: "iflowcn", view: 40.0, body: r##"<path d="M35.0356 18.815C34.5351 11.6351 29.0168 5.81669 21.8733 4.93723C14.7298 4.05778 7.96501 8.36391 5.73799 15.208C5.16042 16.988 6.47614 18.815 8.34735 18.815C9.52767 18.8156 10.5763 18.0618 10.9517 16.9428C11.9438 13.9776 14.796 8.53613 22.3627 8.53613C29.2955 8.53613 33.5198 11.9624 35.0356 18.815ZM13.4901 21.2625V17.2359C13.4901 17.1828 13.4953 17.1302 13.5057 17.0781C13.5161 17.0259 13.5314 16.9753 13.5518 16.9262C13.5721 16.8771 13.597 16.8305 13.6265 16.7863C13.6561 16.7421 13.6896 16.7012 13.7272 16.6636C13.7648 16.626 13.8057 16.5925 13.8499 16.563C13.894 16.5334 13.9407 16.5085 13.9898 16.4882C14.0389 16.4679 14.0895 16.4525 14.1416 16.4421C14.1937 16.4317 14.2464 16.4266 14.2995 16.4266H15.3127C15.3658 16.4266 15.4185 16.4317 15.4706 16.4421C15.5227 16.4525 15.5733 16.4679 15.6225 16.4882C15.6715 16.5085 15.7182 16.5334 15.7624 16.563C15.8066 16.5925 15.8475 16.626 15.885 16.6636C15.9226 16.7012 15.9561 16.7421 15.9857 16.7863C16.0152 16.8305 16.0401 16.8771 16.0605 16.9262C16.0808 16.9753 16.0961 17.0259 16.1065 17.0781C16.1169 17.1302 16.1221 17.1828 16.1221 17.2359V21.2625C16.1221 21.3156 16.1169 21.3682 16.1065 21.4203C16.0961 21.4725 16.0808 21.5231 16.0605 21.5722C16.0401 21.6213 16.0152 21.668 15.9857 21.7122C15.9561 21.7563 15.9226 21.7972 15.885 21.8348C15.8475 21.8724 15.8066 21.9059 15.7624 21.9354C15.7182 21.965 15.6715 21.9899 15.6225 22.0102C15.5733 22.0305 15.5227 22.0459 15.4706 22.0563C15.4185 22.0666 15.3658 22.0718 15.3127 22.0718H14.2995C14.2464 22.0718 14.1937 22.0666 14.1416 22.0563C14.0895 22.0459 14.0389 22.0305 13.9898 22.0102C13.9407 21.9899 13.894 21.965 13.8499 21.9354C13.8057 21.9059 13.7648 21.8724 13.7272 21.8348C13.6896 21.7972 13.6561 21.7563 13.6265 21.7122C13.597 21.668 13.5721 21.6213 13.5518 21.5722C13.5314 21.5231 13.5161 21.4725 13.5057 21.4203C13.4953 21.3682 13.4901 21.3156 13.4901 21.2625ZM21.2165 21.2607C21.2156 21.7084 21.5782 22.0718 22.0259 22.0718H23.2414C23.6877 22.0718 24.0498 21.7105 24.0508 21.2642L24.0552 19.251V19.2474L24.0508 17.2342C24.0498 16.7878 23.6877 16.4266 23.2414 16.4266H22.0259C21.5782 16.4266 21.2156 16.79 21.2165 17.2377L21.2209 19.2474V19.251L21.2165 21.2607ZM17.7081 31.4312C25.2748 31.4312 28.127 25.9897 29.1196 23.0251C29.4948 21.9059 30.5436 21.1521 31.7239 21.1528C33.5946 21.1528 34.9108 22.9794 34.3333 24.7593C33.8114 26.3725 33.0183 27.8849 31.9878 29.2314L33.418 33.4906L28.3318 32.6556C18.7242 39.0155 5.82732 32.6475 5.03564 21.1528C6.55142 28.0051 10.7756 31.4312 17.7081 31.4312Z" fill="currentColor" fill-rule="evenodd"/>"## }; +static INCEPTION: Icon = Icon { name: "inception", view: 24.0, body: r##"<path d="M14.3794 2.99999H8.71219L3.04492 8.66725V14.3345H8.71219V8.66725H14.3794V2.99999Z" fill="currentColor"/><path d="M15.2877 9.66548V15.3327H9.62048V21H15.2877L20.955 15.3327V9.66548H15.2877Z" fill="currentColor"/>"## }; +static INFERENCE: Icon = Icon { name: "inference", view: 40.0, body: r##"<path d="M34.625 33.7119H27.4734V6.28124H34.625V33.7119ZM23.703 33.7119H18.6296V6.28124H23.703V33.7119ZM15.2674 33.7119H11.3771V6.28124H15.2674V33.7119ZM8.15814 33.7119H5.375V6.28124H8.15814V33.7119Z" fill="currentColor"/>"## }; +static IO_NET: Icon = Icon { name: "io-net", view: 24.0, body: r##"<path d="M2.3999 9.60101L4.41977 10.9695H2.3999V16.0618H4.41977V10.9695V7.91422H2.3999V9.60101Z" fill="currentColor"/><path d="M16.0739 9.9477C16.3586 9.9477 16.58 10.1701 16.58 10.4561V11.6317L18.6044 12.9979V9.9477C18.6044 8.83564 17.6871 7.91422 16.58 7.91422H4.46533L7.50191 9.9477H16.1055H16.0739Z" fill="currentColor"/><path d="M9.99142 14.0283C9.70673 14.0283 9.48532 13.8059 9.48532 13.5199V12.3443L7.46094 10.9781V14.0283C7.46094 15.1403 8.37823 16.0618 9.48532 16.0618H21.6L18.5634 14.0283H9.95978H9.99142Z" fill="currentColor"/>"## }; +static JIEKOU: Icon = Icon { name: "jiekou", view: 24.0, body: r##"<path d="M16 4H4V20H16C18.2091 20 20 18.2091 20 16V8H24V16C24 20.4183 20.4183 24 16 24H4C1.79086 24 1.61064e-08 22.2091 0 20V0H16V4Z" fill="currentColor"/><path d="M20 4H24V0H20V4Z" fill="currentColor"/>"## }; +static KILO: Icon = Icon { name: "kilo", view: 24.0, body: r##"<path d="M5 3v18" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round"/><path d="M17.5 4.5 9.5 12l8 7.5" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round"/>"## }; +static KIMI_FOR_CODING: Icon = Icon { name: "kimi-for-coding", view: 24.0, body: r##"<path d="M3.51531 15.81L10.908 17.7878C10.8981 18.3134 10.9136 18.8392 10.9545 19.3633L15.5704 20.5979C14.2013 21.163 12.7171 21.3928 11.2413 21.2683L11.1018 21.2559L11.0677 21.2528L11.0026 21.2458L10.9297 21.238C10.8891 21.2332 10.8486 21.228 10.808 21.2225L10.7251 21.2117L10.6399 21.1993C10.557 21.1872 10.4743 21.1741 10.3919 21.1598L10.3593 21.1536L10.3012 21.1435L10.2183 21.128L10.164 21.1164L10.0919 21.1016L10.0338 21.0892L9.96019 21.0737L9.88501 21.0559L9.81216 21.0389L9.75946 21.0257L9.69126 21.0086L9.62151 20.99L9.54789 20.9707L9.48434 20.9528L9.39986 20.9296L9.35181 20.9141L9.28671 20.8947L9.21464 20.873L9.13326 20.8467L9.08831 20.8319L9.02631 20.8118L8.95656 20.7878L8.90541 20.7692C8.89403 20.7653 8.88267 20.7615 8.87131 20.7575L8.81861 20.7382L8.74034 20.7095L8.69617 20.6924L8.63417 20.6692L8.56674 20.6421L8.49854 20.6149L8.43732 20.5901L8.36369 20.5591L8.31487 20.5374L8.26604 20.5165C8.25543 20.5119 8.24484 20.5073 8.23427 20.5026L8.18312 20.4793L8.10329 20.4429L8.06299 20.4243L7.98859 20.3886L7.94054 20.3654L7.87544 20.3344L7.80879 20.3003L7.73672 20.2639L7.69642 20.2429L7.61659 20.2003L7.57242 20.1771L7.52747 20.1523C7.51556 20.1456 7.50367 20.1389 7.49182 20.1321L7.41897 20.091L7.37247 20.0647L7.33294 20.0414L7.27714 20.0097L7.21359 19.9709L7.14152 19.9275L7.10122 19.9027L7.03612 19.8616L6.98885 19.8314L6.92762 19.7927L6.87337 19.7562L6.8323 19.7291C6.81831 19.7199 6.80436 19.7106 6.79045 19.7012L6.75635 19.678L6.72225 19.6547C6.71188 19.6475 6.70155 19.6403 6.69125 19.633L6.64707 19.602L6.58817 19.5602L6.5347 19.5214L6.47735 19.4796L6.43395 19.447L6.37505 19.4028L6.31615 19.3571L6.2495 19.3052L6.21462 19.2781L6.16502 19.2378L6.10767 19.1913L6.0387 19.1347L6.00305 19.1045L5.9674 19.0742C5.95625 19.0647 5.94515 19.0552 5.93407 19.0456L5.8992 19.0146L5.85192 18.9735L5.79767 18.9255L5.74497 18.8789L5.69692 18.834L5.645 18.786L5.60392 18.7472L5.53572 18.6821C5.51002 18.6572 5.48444 18.6321 5.459 18.6069L5.43653 18.5852L5.40475 18.5527L5.35128 18.4984L5.31253 18.4589L5.27378 18.4178C5.2295 18.3724 5.18609 18.3262 5.14358 18.2791L5.08158 18.2109L5.03353 18.1567L4.9785 18.0947L4.94595 18.0567L4.90488 18.0086L4.85993 17.9559L4.82428 17.9125C4.81728 17.904 4.8103 17.8955 4.80335 17.887L4.76848 17.8443L4.71733 17.7808L4.68555 17.7405L4.6468 17.6909L4.6313 17.6715C4.18786 17.0967 3.81331 16.4719 3.51531 15.81ZM2.72481 11.3196L11.5234 13.6733C11.3761 14.1864 11.2547 14.7065 11.1599 15.2318L19.543 17.4747C19.1266 18.0449 18.6469 18.5662 18.1132 19.0285L3.20918 15.0404L3.19678 15.0047L3.16966 14.9241C3.15647 14.8847 3.14356 14.8452 3.13091 14.8056L3.12548 14.7877C3.06583 14.5981 3.01233 14.4066 2.96506 14.2135L2.94181 14.1158L2.92786 14.0538L2.91158 13.9786L2.89763 13.9159L2.88368 13.8461L2.87051 13.781L2.85656 13.7082C2.83641 13.5989 2.81781 13.4888 2.80153 13.378L2.78836 13.2866L2.77983 13.2222L2.76976 13.1432C2.76457 13.1016 2.75966 13.06 2.75503 13.0184L2.75116 12.982C2.69326 12.4297 2.68444 11.8734 2.72481 11.3196ZM3.95938 7.32839L13.2191 9.80528C12.9339 10.2742 12.6727 10.7593 12.4363 11.2584L21.1899 13.6004C21.0799 14.2359 20.9047 14.8497 20.6722 15.4333L11.721 13.0386L2.79611 10.6516L2.80773 10.5741L2.81393 10.5361L2.82168 10.4842L2.83331 10.4168L2.84726 10.3408C2.86741 10.2261 2.89066 10.1122 2.91546 9.99825L2.93716 9.90215L2.95266 9.83628L2.97126 9.7611C2.98831 9.69135 3.00613 9.6216 3.02551 9.5534L3.04721 9.47435L3.06503 9.41003L3.08828 9.33253L3.10766 9.26898L3.13091 9.19458L3.15106 9.13103L3.17508 9.05741C3.37577 8.45541 3.63808 7.87573 3.95783 7.32761L3.95938 7.32839ZM7.40192 3.9184L16.1478 6.25734C15.6862 6.67623 15.2494 7.12157 14.8396 7.59111L20.9024 9.21318C21.1093 9.87348 21.2449 10.5648 21.3 11.2785L4.33215 6.74016L4.36703 6.68979L4.38795 6.65879L4.41895 6.61616L4.4546 6.56579L4.49723 6.50689L4.53908 6.45109L4.58868 6.38444L4.62743 6.33406L4.6716 6.27749L4.71423 6.22324L4.76073 6.16589L4.80335 6.11241L4.85373 6.05274L4.89558 6.00159L4.94673 5.94192L4.9878 5.89542L5.0436 5.83187L5.08468 5.78537L5.1366 5.72802L5.17845 5.68307L5.23503 5.62262L5.27998 5.57612L5.3288 5.52419L5.459 5.39244L5.5365 5.31649L5.58222 5.27309L5.64112 5.21807C6.17525 4.71752 6.76621 4.28132 7.40192 3.9184ZM12.0132 2.7001H12.0883L12.1519 2.70088L12.2054 2.70165L12.2472 2.7032L12.2999 2.70475L12.3356 2.70553L12.3945 2.70785L12.4309 2.7094L12.4774 2.71173L12.5192 2.71328L12.5867 2.71715L12.668 2.72258L12.7796 2.7311L12.8478 2.73653L12.8819 2.73963L12.9416 2.74583L13.0052 2.75203L13.0416 2.7559L13.1206 2.7652L13.1594 2.76985L13.2431 2.7807L13.3059 2.78845L13.3384 2.7931L13.3888 2.80085L13.5492 2.82565L13.6035 2.83495L13.6538 2.84348L13.7623 2.86363L13.8336 2.87758L13.9189 2.89462L13.9545 2.90237L14.0126 2.91477L14.0444 2.92252L14.0925 2.9326L14.125 2.94035L14.1754 2.95197L14.2134 2.96127L14.2684 2.97445L14.3428 2.99305L14.4296 3.0163L14.5172 3.03955L14.6047 3.06435L14.6435 3.07597L14.6977 3.09147L14.7582 3.11007L14.8148 3.1279L14.8535 3.1403L14.8923 3.1527L14.9512 3.17207L15.0279 3.19765L15.1069 3.22555L15.1441 3.23872L15.1937 3.25655L15.2658 3.2829L15.3511 3.31467L15.441 3.34955L15.5185 3.38055L15.5549 3.39605L15.6014 3.41465L15.6332 3.4286L15.682 3.44875L15.713 3.4627L15.7572 3.48207L15.8424 3.51927L15.9199 3.55492L15.9773 3.58205L16.0354 3.60995L16.0819 3.63165L16.1532 3.6673L16.2237 3.70217L16.3028 3.74247L16.3438 3.76417L16.3818 3.78432L16.4175 3.80292L16.464 3.8285L16.4957 3.84555L16.536 3.86802L16.6042 3.90677L16.6864 3.95327L16.7538 3.9928L16.798 4.01915L16.8391 4.04395L16.9135 4.08967L16.9817 4.1323L17.0576 4.18035L17.0855 4.19895L17.1351 4.23072L17.2002 4.27412L17.2312 4.29505L17.2793 4.3276L17.3273 4.36092L17.3451 4.3741C17.387 4.40277 17.4288 4.43222 17.4699 4.46244L17.5342 4.50894L17.5846 4.54614L17.628 4.57947L17.6947 4.62984L17.7582 4.67944L17.7892 4.70269L17.828 4.73447L17.8946 4.78794L17.9558 4.83832L18.0217 4.89334C18.5735 5.35834 19.0703 5.88767 19.5012 6.46736L8.29704 3.47045L8.34509 3.44952L8.39547 3.42782L8.45824 3.40147L8.52489 3.37435C8.61247 3.33947 8.70082 3.3046 8.78916 3.27282L8.86356 3.2457L8.93564 3.22012L9.00074 3.19687L9.07514 3.17285C9.14256 3.1496 9.21154 3.1279 9.27974 3.10697L9.35026 3.08605L9.41691 3.06667L9.49596 3.04342L9.56184 3.0256L9.63934 3.00545L9.70599 2.98685L9.77574 2.96902L9.84626 2.95197L9.91989 2.93492L9.98964 2.91942L10.0656 2.90315L10.1361 2.88765L10.2097 2.8737L10.281 2.85975L10.3585 2.8458L10.4291 2.8334L10.505 2.82023L10.5763 2.80938L10.6515 2.79775L10.7228 2.78768L10.8018 2.7776L10.8724 2.7683L10.9537 2.759L11.0235 2.75125L11.1049 2.7435C11.1769 2.73575 11.249 2.72955 11.3219 2.7249L11.404 2.7187L11.4738 2.71483L11.559 2.71018L11.6311 2.70708L11.7086 2.70398L11.7838 2.70243L11.8605 2.70088L12.0132 2.69933V2.7001Z" fill="currentColor"/>"## }; +static KUAE_CLOUD_CODING_PLAN: Icon = Icon { name: "kuae-cloud-coding-plan", view: 40.0, body: r##"<path d="M20.1312 7.5L17.4088 11.1912H5.81625L8.5375 7.5H20.1325H20.1312ZM34.0675 28.81L31.3475 32.5H19.795L22.5125 28.81H34.0675ZM35 7.5L16.58 32.5H5L23.42 7.5H35Z" fill="currentColor"/>"## }; +static LLAMA: Icon = Icon { name: "llama", view: 40.0, body: r##"<path d="M27.1942 9.03509C24.4881 9.03509 22.3726 11.0731 20.4574 13.6623C17.8258 10.3114 15.6255 9.03509 12.9925 9.03509C7.62404 9.03509 3.51001 16.0234 3.51001 23.4181C3.51001 28.0453 5.74831 30.9649 9.49831 30.9649C12.1971 30.9649 14.1387 29.693 17.5904 23.6594C17.5904 23.6594 19.029 21.1199 20.0173 19.3699C20.3643 19.9293 20.7298 20.5327 21.1138 21.1798L22.7322 23.902C25.8843 29.1769 27.6416 30.9649 30.8229 30.9649C34.4778 30.9649 36.51 28.0058 36.51 23.2822C36.51 15.538 32.3039 9.03509 27.1942 9.03509ZM14.9574 22.0263C12.1606 26.4123 11.1928 27.3962 9.63574 27.3962C8.03194 27.3962 7.07872 25.9883 7.07872 23.4781C7.07872 18.1096 9.75562 12.6199 12.9471 12.6199C14.6752 12.6199 16.1197 13.617 18.3316 16.7836C16.2308 20.0058 14.9574 22.0263 14.9574 22.0263ZM25.5202 21.4751L23.5831 18.2456C23.0969 17.4514 22.5938 16.6676 22.0743 15.8947C23.8185 13.2032 25.2556 11.8611 26.9676 11.8611C30.5202 11.8611 33.3638 17.095 33.3638 23.5219C33.3638 25.9722 32.5612 27.3947 30.8989 27.3947C29.3053 27.3947 28.5451 26.3421 25.5188 21.4737" fill="currentColor"/>"## }; +static LMSTUDIO: Icon = Icon { name: "lmstudio", view: 24.0, body: r##"<path d="M9.8132 15.9038L9 18.75L8.1868 15.9038C7.75968 14.4089 6.59112 13.2403 5.09619 12.8132L2.25 12L5.09619 11.1868C6.59113 10.7597 7.75968 9.59112 8.1868 8.09619L9 5.25L9.8132 8.09619C10.2403 9.59113 11.4089 10.7597 12.9038 11.1868L15.75 12L12.9038 12.8132C11.4089 13.2403 10.2403 14.4089 9.8132 15.9038Z" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/><path d="M18.2589 8.71454L18 9.75L17.7411 8.71454C17.4388 7.50533 16.4947 6.56117 15.2855 6.25887L14.25 6L15.2855 5.74113C16.4947 5.43883 17.4388 4.49467 17.7411 3.28546L18 2.25L18.2589 3.28546C18.5612 4.49467 19.5053 5.43883 20.7145 5.74113L21.75 6L20.7145 6.25887C19.5053 6.56117 18.5612 7.50533 18.2589 8.71454Z" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/><path d="M16.8942 20.5673L16.5 21.75L16.1058 20.5673C15.8818 19.8954 15.3546 19.3682 14.6827 19.1442L13.5 18.75L14.6827 18.3558C15.3546 18.1318 15.8818 17.6046 16.1058 16.9327L16.5 15.75L16.8942 16.9327C17.1182 17.6046 17.6454 18.1318 18.3173 18.3558L19.5 18.75L18.3173 19.1442C17.6454 19.3682 17.1182 19.8954 16.8942 20.5673Z" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>"## }; +static LUCIDQUERY: Icon = Icon { name: "lucidquery", view: 24.0, body: r##"<path d="M9.60783 3.46101C9.64016 3.48017 9.67275 3.49889 9.70534 3.51763C9.71858 3.52526 9.73182 3.53289 9.74507 3.54052C9.75164 3.54431 9.75822 3.5481 9.76499 3.552C9.79789 3.57096 9.83078 3.58994 9.86367 3.60892C9.8768 3.61649 9.88993 3.62407 9.90307 3.63165C10.4152 3.9271 10.4152 3.9271 10.9273 4.22255C10.9338 4.2263 10.9403 4.23005 10.947 4.23392C10.9601 4.24149 10.9732 4.24906 10.9864 4.25663C11.0193 4.27565 11.0523 4.29467 11.0853 4.31367C11.1486 4.35017 11.2119 4.38677 11.275 4.42369C11.3276 4.45444 11.3804 4.48481 11.4334 4.51497C11.4923 4.54855 11.551 4.58245 11.6095 4.61669C11.6731 4.65387 11.7369 4.69064 11.8008 4.72741C11.8223 4.73983 11.8438 4.75228 11.8654 4.76473C11.8762 4.771 11.887 4.77726 11.8979 4.78352C11.9081 4.78946 11.9184 4.79541 11.9287 4.80136C11.9349 4.80495 11.9411 4.80855 11.9475 4.81225C11.953 4.81542 11.9585 4.81858 11.9641 4.82184C11.9689 4.82458 11.9738 4.82731 11.9788 4.83012C11.9828 4.83281 11.9868 4.8355 11.9909 4.83827C12.0035 4.84381 12.0035 4.84381 12.0178 4.83672C12.0232 4.83342 12.0287 4.83013 12.0343 4.82674C12.0406 4.82307 12.0468 4.81939 12.0532 4.81561C12.0599 4.81152 12.0666 4.80744 12.0735 4.80323C12.0806 4.79902 12.0876 4.79482 12.0947 4.79063C12.1094 4.78192 12.1241 4.77315 12.1388 4.76436C12.1721 4.74444 12.2058 4.7252 12.2394 4.70588C12.2525 4.69831 12.2657 4.69073 12.2788 4.68315C13.303 4.09225 13.303 4.09225 13.3227 4.08088C13.3359 4.07331 13.349 4.06574 13.3621 4.05817C13.3951 4.03915 13.4281 4.02013 13.461 4.00113C13.5244 3.96463 13.5877 3.92803 13.6508 3.89111C13.7069 3.85826 13.7634 3.82587 13.8199 3.79365C13.8752 3.76213 13.9303 3.73025 13.9853 3.69811C14.049 3.66081 14.1131 3.62393 14.1771 3.58705C14.2034 3.57187 14.2298 3.55667 14.2561 3.54147C14.2692 3.53393 14.2822 3.5264 14.2953 3.51888C14.329 3.49945 14.3627 3.47993 14.3963 3.46025C14.568 3.35985 14.7407 3.28118 14.9451 3.33127C14.9606 3.33546 14.9756 3.34022 14.9909 3.34528C14.9968 3.3472 15.0026 3.34911 15.0086 3.35108C15.1125 3.39027 15.2095 3.45509 15.3049 3.51115C15.3433 3.53371 15.3819 3.556 15.4205 3.57824C15.427 3.58201 15.4335 3.58578 15.4403 3.58967C15.4536 3.59732 15.4668 3.60496 15.4801 3.61261C15.513 3.63157 15.5459 3.65055 15.5788 3.66952C15.5919 3.6771 15.605 3.68468 15.6182 3.69225C15.697 3.73771 15.7758 3.78316 15.8545 3.82861C15.861 3.83236 15.8675 3.83612 15.8742 3.83998C15.8874 3.84755 15.9005 3.85512 15.9136 3.86269C15.9466 3.88172 15.9796 3.90073 16.0125 3.91974C16.0759 3.95623 16.1392 3.99284 16.2023 4.02975C16.2549 4.06051 16.3077 4.09087 16.3606 4.12104C16.4195 4.15461 16.4782 4.18851 16.5368 4.22275C16.6005 4.26005 16.6646 4.29694 16.7286 4.33382C16.7615 4.35277 16.7944 4.37175 16.8273 4.39073C16.8404 4.39831 16.8535 4.40588 16.8667 4.41346C17.103 4.54982 17.3394 4.68618 17.5757 4.82255C17.5855 4.82817 17.5855 4.82817 17.5954 4.83392C17.6085 4.84147 17.6216 4.84903 17.6347 4.85658C17.6681 4.87587 17.7016 4.89512 17.735 4.91431C17.768 4.93322 17.8009 4.95222 17.8337 4.97131C17.8451 4.9779 17.8564 4.98447 17.8678 4.99101C17.9298 5.02675 17.9832 5.06351 18.0333 5.11497C18.04 5.12167 18.04 5.12167 18.0468 5.12851C18.1733 5.26233 18.1988 5.43146 18.1986 5.60719C18.1987 5.61939 18.1987 5.63159 18.1987 5.64379C18.1988 5.6771 18.1989 5.71041 18.1989 5.74372C18.1989 5.77972 18.199 5.81572 18.1991 5.85173C18.1992 5.91808 18.1993 5.98443 18.1994 6.05079C18.1994 6.11204 18.1995 6.17329 18.1996 6.23455C18.1996 6.23861 18.1996 6.24268 18.1996 6.24688C18.1997 6.26754 18.1997 6.28821 18.1998 6.30887C18.2 6.45503 18.2003 6.60119 18.2004 6.74736C18.2006 6.8893 18.2008 7.03125 18.2011 7.17319C18.2011 7.17757 18.2011 7.18195 18.2011 7.18647C18.2012 7.23045 18.2013 7.27443 18.2013 7.31842C18.2015 7.40801 18.2016 7.4976 18.2018 7.58719C18.2018 7.59131 18.2018 7.59543 18.2018 7.59967C18.2023 7.87446 18.2026 8.14925 18.203 8.42404C18.2078 8.42675 18.2125 8.42946 18.2174 8.43226C18.2354 8.44254 18.2535 8.45283 18.2715 8.46311C18.2792 8.46753 18.2869 8.47194 18.2947 8.47635C18.3453 8.50525 18.3958 8.53436 18.4462 8.56381C18.4524 8.56744 18.4586 8.57107 18.465 8.57481C18.4706 8.57807 18.4761 8.58133 18.4819 8.58469C18.5397 8.61849 18.5978 8.65187 18.6558 8.6853C18.6887 8.70426 18.7216 8.72324 18.7545 8.74222C18.7676 8.74979 18.7808 8.75737 18.7939 8.76494C19.1878 8.99221 19.5818 9.21949 19.9757 9.44676C19.9822 9.45051 19.9887 9.45426 19.9954 9.45812C20.0085 9.46569 20.0217 9.47326 20.0348 9.48083C20.0678 9.49986 20.1007 9.51888 20.1337 9.53788C20.1971 9.57438 20.2603 9.61098 20.3234 9.64789C20.3725 9.67655 20.4216 9.7049 20.471 9.73301C20.5029 9.7512 20.5347 9.76943 20.5666 9.78766C20.5734 9.79151 20.5801 9.79536 20.587 9.79933C20.7794 9.90961 20.925 10.0179 20.9862 10.241C20.9954 10.2793 20.9978 10.315 20.9977 10.3541C20.9978 10.3599 20.9978 10.3657 20.9978 10.3716C20.9978 10.391 20.9978 10.4104 20.9978 10.4297C20.9978 10.4437 20.9979 10.4578 20.9979 10.4718C20.9979 10.5103 20.998 10.5489 20.998 10.5874C20.998 10.6247 20.9981 10.662 20.9981 10.6993C20.9982 10.7992 20.9983 10.8991 20.9983 10.999C20.9984 11.0463 20.9984 11.0936 20.9984 11.1409C20.9985 11.3028 20.9986 11.4648 20.9987 11.6267C20.9987 11.6368 20.9987 11.647 20.9987 11.6572C20.9987 11.6647 20.9987 11.6647 20.9987 11.6724C20.9987 11.698 20.9987 11.7235 20.9987 11.7491C20.9987 11.7541 20.9987 11.7592 20.9987 11.7644C20.9988 11.9286 20.9989 12.0929 20.9991 12.2571C20.9993 12.4308 20.9994 12.6045 20.9995 12.7782C20.9995 12.7973 20.9995 12.8164 20.9995 12.8355C20.9995 12.8425 20.9995 12.8425 20.9995 12.8497C20.9995 12.9252 20.9996 13.0007 20.9997 13.0762C20.9998 13.1522 20.9999 13.2281 20.9998 13.3041C20.9998 13.3452 20.9998 13.3863 20.9999 13.4275C21 13.4651 21 13.5028 20.9999 13.5405C20.9999 13.5541 20.9999 13.5677 21 13.5813C21.0009 13.7615 20.9511 13.9105 20.8238 14.0422C20.7544 14.1113 20.667 14.1549 20.582 14.202C20.5443 14.2228 20.5071 14.2443 20.47 14.266C20.4198 14.2955 20.3694 14.3248 20.3189 14.3539C20.3124 14.3577 20.3058 14.3615 20.2991 14.3654C20.2858 14.373 20.2725 14.3806 20.2592 14.3883C20.2263 14.4072 20.1935 14.4262 20.1606 14.4452C20.1474 14.4528 20.1343 14.4604 20.1212 14.4679C20.1147 14.4717 20.1082 14.4754 20.1015 14.4793C18.9394 15.1497 18.9394 15.1497 18.9197 15.1611C18.9065 15.1687 18.8934 15.1763 18.8803 15.1838C18.8473 15.2028 18.8144 15.2219 18.7814 15.2409C18.718 15.2774 18.6547 15.314 18.5916 15.3509C18.5327 15.3853 18.4735 15.4193 18.4142 15.453C18.401 15.4606 18.3879 15.4684 18.375 15.4764C18.3548 15.4882 18.335 15.4951 18.3127 15.502C18.2683 15.5181 18.2316 15.5368 18.203 15.5755C18.1723 15.6528 18.1842 15.7509 18.1859 15.8322C18.1865 15.8679 18.1862 15.9037 18.1861 15.9395C18.1859 16.0014 18.1863 16.0634 18.1871 16.1253C18.1878 16.1903 18.1883 16.2553 18.1884 16.3203C18.1884 16.3244 18.1884 16.3284 18.1884 16.3326C18.1884 16.3532 18.1884 16.3738 18.1884 16.3944C18.1885 16.54 18.1893 16.6857 18.1904 16.8314C18.1916 16.9726 18.1924 17.1138 18.1929 17.255C18.1929 17.2594 18.1929 17.2637 18.193 17.2682C18.1933 17.3548 18.1935 17.4415 18.1938 17.5281C18.1939 17.5703 18.194 17.6124 18.1942 17.6545C18.1942 17.667 18.1943 17.6795 18.1943 17.6919C18.1946 17.8054 18.1953 17.9189 18.196 18.0324C18.1963 18.0779 18.1966 18.1234 18.1969 18.1689C18.1971 18.2109 18.1974 18.253 18.1978 18.2951C18.198 18.3208 18.1982 18.3464 18.1983 18.3721C18.1983 18.3837 18.1984 18.3954 18.1986 18.407C18.2006 18.5819 18.1645 18.739 18.0454 18.8724C18.041 18.8774 18.0366 18.8824 18.0321 18.8875C17.9613 18.9628 17.8686 19.0086 17.7792 19.0581C17.7496 19.0744 17.7203 19.0912 17.6913 19.1084C17.649 19.1335 17.6066 19.1581 17.564 19.1827C17.5539 19.1885 17.5539 19.1885 17.5437 19.1944C17.5299 19.2023 17.5161 19.2102 17.5024 19.2182C17.4692 19.2373 17.4361 19.2564 17.403 19.2755C17.3899 19.2831 17.3768 19.2906 17.3636 19.2982C17.3571 19.302 17.3506 19.3057 17.3439 19.3096C17.2848 19.3437 17.2848 19.3437 17.2651 19.355C17.252 19.3626 17.2389 19.3702 17.2258 19.3777C17.1928 19.3968 17.1598 19.4158 17.1268 19.4348C17.0635 19.4713 17.0002 19.5079 16.9371 19.5448C16.8809 19.5776 16.8245 19.61 16.7679 19.6423C16.7126 19.6738 16.6576 19.7057 16.6026 19.7378C16.5388 19.7751 16.4748 19.812 16.4108 19.8489C16.3779 19.8678 16.345 19.8868 16.3121 19.9058C16.299 19.9133 16.2858 19.9209 16.2727 19.9285C16.2662 19.9323 16.2597 19.936 16.253 19.9399C15.8295 20.1842 15.8295 20.1842 15.4061 20.4285C15.3996 20.4323 15.393 20.436 15.3863 20.4399C15.3733 20.4474 15.3602 20.455 15.3471 20.4625C15.3135 20.4818 15.28 20.5012 15.2466 20.5207C15.2079 20.5431 15.1691 20.5654 15.1303 20.5876C15.1253 20.5905 15.1203 20.5934 15.1151 20.5964C14.9819 20.6727 14.8302 20.7018 14.6777 20.6717C14.6648 20.6682 14.6521 20.6644 14.6394 20.6603C14.6323 20.6582 14.6252 20.6561 14.6179 20.654C14.5453 20.6308 14.482 20.5901 14.417 20.551C14.3861 20.5326 14.3549 20.5149 14.3236 20.4971C14.3057 20.4869 14.2877 20.4767 14.2698 20.4664C14.2662 20.4644 14.2627 20.4624 14.259 20.4603C14.2023 20.4279 14.1458 20.3952 14.0892 20.3625C14.0564 20.3436 14.0237 20.3247 13.9909 20.3058C13.9778 20.2982 13.9647 20.2906 13.9515 20.283C13.9418 20.2774 13.9418 20.2774 13.9318 20.2717C13.8071 20.1997 13.6823 20.1277 13.5576 20.0558C13.5478 20.0501 13.5478 20.0501 13.5379 20.0444C13.5248 20.0368 13.5116 20.0293 13.4985 20.0217C13.4655 20.0027 13.4326 19.9837 13.3996 19.9647C13.3362 19.9282 13.273 19.8916 13.2099 19.8546C13.1573 19.8239 13.1045 19.7935 13.0515 19.7633C12.9926 19.7298 12.9339 19.6959 12.8754 19.6616C12.8116 19.6243 12.7476 19.5874 12.6835 19.5506C12.6506 19.5316 12.6178 19.5126 12.5849 19.4937C12.5717 19.4861 12.5586 19.4785 12.5455 19.4709C12.3091 19.3346 12.3091 19.3346 12.2894 19.3232C12.2764 19.3157 12.2633 19.3081 12.2503 19.3006C12.2196 19.2829 12.1889 19.2652 12.1583 19.2475C12.1438 19.2391 12.1294 19.2308 12.115 19.2224C12.1048 19.2165 12.0947 19.2107 12.0846 19.2048C12.0784 19.2012 12.0722 19.1976 12.0658 19.1939C12.0604 19.1908 12.055 19.1877 12.0494 19.1844C12.0441 19.1815 12.0388 19.1785 12.0334 19.1755C12.0273 19.1718 12.0212 19.1682 12.015 19.1644C11.9977 19.1555 11.9977 19.1555 11.982 19.1616C11.9771 19.1646 11.9722 19.1677 11.9672 19.1709C11.9615 19.1743 11.9559 19.1777 11.9501 19.1812C11.9441 19.1851 11.938 19.1889 11.9318 19.1929C11.9187 19.2009 11.9056 19.2089 11.8925 19.2169C11.8823 19.2232 11.8823 19.2232 11.872 19.2296C11.8395 19.2495 11.8065 19.2683 11.7735 19.2872C11.7603 19.2948 11.747 19.3025 11.7338 19.3101C11.7272 19.3139 11.7206 19.3177 11.7139 19.3216C11.681 19.3405 11.6481 19.3595 11.6152 19.3785C11.602 19.3861 11.5889 19.3937 11.5758 19.4012C11.5693 19.405 11.5628 19.4087 11.5561 19.4126C11.0243 19.7194 11.0243 19.7194 11.0046 19.7308C10.9914 19.7383 10.9783 19.7459 10.9652 19.7535C10.9322 19.7725 10.8993 19.7915 10.8663 19.8105C10.8029 19.847 10.7396 19.8836 10.6765 19.9205C10.6204 19.9534 10.5639 19.9858 10.5074 20.018C10.4521 20.0495 10.397 20.0814 10.3421 20.1136C10.2783 20.1508 10.2143 20.1877 10.1502 20.2246C10.1173 20.2436 10.0844 20.2626 10.0515 20.2815C10.0384 20.2891 10.0253 20.2967 10.0122 20.3043C10.0057 20.308 9.99916 20.3118 9.99246 20.3156C9.92024 20.3573 9.84802 20.399 9.77579 20.4406C9.76929 20.4444 9.76278 20.4481 9.75608 20.452C9.74301 20.4595 9.72994 20.4671 9.71686 20.4746C9.68309 20.4941 9.64935 20.5136 9.61566 20.5332C9.43912 20.636 9.26685 20.7189 9.05648 20.669C8.95425 20.6416 8.86572 20.5864 8.77526 20.5331C8.74223 20.5137 8.70901 20.4946 8.6758 20.4755C8.66267 20.4679 8.64954 20.4603 8.63641 20.4527C8.62666 20.4471 8.62666 20.4471 8.61671 20.4414C8.22934 20.2179 7.84197 19.9944 7.4546 19.7709C7.44485 19.7653 7.44485 19.7653 7.4349 19.7596C7.42178 19.752 7.40866 19.7444 7.39553 19.7368C7.36256 19.7178 7.32958 19.6988 7.2966 19.6798C7.23325 19.6433 7.16998 19.6067 7.10687 19.5698C7.05428 19.539 7.00147 19.5087 6.94854 19.4785C6.88963 19.4449 6.83091 19.411 6.77238 19.3768C6.7086 19.3395 6.64458 19.3026 6.58056 19.2657C6.54766 19.2468 6.51477 19.2278 6.48188 19.2088C6.46875 19.2012 6.45562 19.1937 6.44248 19.1861C6.41622 19.1709 6.38996 19.1558 6.3637 19.1406C6.35719 19.1369 6.35068 19.1331 6.34398 19.1293C6.33092 19.1217 6.31786 19.1142 6.30481 19.1066C6.27447 19.0891 6.24411 19.0716 6.21365 19.0543C6.20298 19.0483 6.19233 19.0422 6.18168 19.0361C6.16841 19.0285 6.15512 19.021 6.14181 19.0135C5.98413 18.9234 5.87421 18.804 5.82405 18.6286C5.81287 18.5874 5.80827 18.5489 5.80841 18.5063C5.8084 18.5012 5.8084 18.4961 5.80839 18.4909C5.80837 18.4738 5.8084 18.4568 5.80843 18.4397C5.80842 18.4274 5.80842 18.4151 5.80841 18.4027C5.8084 18.3688 5.80842 18.3349 5.80845 18.301C5.80848 18.2644 5.80847 18.2279 5.80847 18.1913C5.80846 18.1279 5.80848 18.0646 5.80852 18.0012C5.80855 17.9348 5.80857 17.8683 5.80858 17.8019C5.80858 17.7978 5.80858 17.7936 5.80858 17.7894C5.80858 17.7684 5.80859 17.7474 5.80859 17.7264C5.8086 17.5778 5.80864 17.4292 5.8087 17.2806C5.80875 17.1362 5.8088 16.9918 5.80882 16.8475C5.80882 16.843 5.80882 16.8386 5.80883 16.834C5.80883 16.7893 5.80884 16.7446 5.80885 16.6999C5.80886 16.6089 5.80888 16.5178 5.8089 16.4268C5.8089 16.4226 5.8089 16.4184 5.8089 16.4141C5.80896 16.1346 5.80905 15.855 5.80916 15.5755C5.80217 15.5728 5.80217 15.5728 5.79504 15.57C5.77715 15.5627 5.76106 15.5538 5.74431 15.5442C5.73757 15.5403 5.73082 15.5364 5.72387 15.5325C5.71656 15.5282 5.70926 15.524 5.70196 15.5198C5.69434 15.5154 5.68672 15.5111 5.67911 15.5067C5.65954 15.4955 5.63999 15.4842 5.62045 15.4729C5.60313 15.4629 5.58579 15.453 5.56846 15.443C5.53599 15.4243 5.50353 15.4055 5.47108 15.3868C5.43833 15.3678 5.40556 15.3489 5.3728 15.33C5.35966 15.3225 5.34653 15.3149 5.3334 15.3073C5.3269 15.3036 5.3204 15.2998 5.3137 15.296C5.24148 15.2543 5.16926 15.2126 5.09704 15.171C5.09054 15.1672 5.08404 15.1635 5.07734 15.1596C5.06422 15.152 5.0511 15.1445 5.03798 15.1369C5.005 15.1179 4.97203 15.0988 4.93904 15.0798C4.8757 15.0433 4.81242 15.0067 4.74932 14.9698C4.69672 14.9391 4.64392 14.9087 4.59098 14.8785C4.53207 14.845 4.47335 14.8111 4.41482 14.7768C4.35104 14.7395 4.28702 14.7026 4.223 14.6658C4.1901 14.6468 4.15721 14.6278 4.12432 14.6088C4.11119 14.6013 4.09806 14.5937 4.08493 14.5861C3.95361 14.5104 3.8223 14.4346 3.69099 14.3588C3.68449 14.3551 3.67799 14.3513 3.67129 14.3475C3.65817 14.3399 3.64505 14.3323 3.63193 14.3248C3.59232 14.3019 3.55271 14.2791 3.51308 14.2563C3.49342 14.2449 3.47378 14.2336 3.45413 14.2222C3.42807 14.2071 3.40194 14.1922 3.37577 14.1773C3.20758 14.0813 3.07753 13.9697 3.02023 13.7781C3.0083 13.7285 3.00131 13.681 3.00156 13.63C3.00153 13.6242 3.00151 13.6184 3.00149 13.6125C3.00144 13.5933 3.00147 13.5742 3.00149 13.555C3.00147 13.5411 3.00144 13.5271 3.00141 13.5132C3.00134 13.475 3.00134 13.4368 3.00135 13.3986C3.00136 13.3616 3.0013 13.3246 3.00125 13.2876C3.00113 13.2027 3.0011 13.1177 3.00109 13.0327C3.00109 12.9671 3.00106 12.9014 3.00102 12.8358C3.00101 12.8168 3.001 12.7979 3.00099 12.779C3.00099 12.7743 3.00098 12.7696 3.00098 12.7648C3.00091 12.6325 3.00086 12.5003 3.00086 12.368C3.00086 12.3631 3.00086 12.3581 3.00086 12.3529C3.00087 12.3277 3.00087 12.3024 3.00087 12.2772C3.00087 12.2722 3.00087 12.2671 3.00087 12.262C3.00087 12.2518 3.00087 12.2417 3.00087 12.2316C3.00088 12.0738 3.00079 11.916 3.00062 11.7583C3.00043 11.5809 3.00033 11.4036 3.00034 11.2262C3.00034 11.2073 3.00034 11.1884 3.00034 11.1695C3.00034 11.1648 3.00034 11.1601 3.00034 11.1553C3.00034 11.0805 3.00027 11.0056 3.00016 10.9308C3.00006 10.8555 3.00005 10.7802 3.00013 10.7049C3.00017 10.6642 3.00017 10.6234 3.00006 10.5826C2.99997 10.5453 2.99999 10.5079 3.00009 10.4706C3.00011 10.4571 3.00009 10.4436 3.00002 10.4302C2.99919 10.2527 3.0432 10.0969 3.16909 9.96714C3.21289 9.92334 3.25865 9.89154 3.3122 9.86039C3.31763 9.85723 3.32306 9.85408 3.32865 9.85082C3.36862 9.82762 3.40868 9.80457 3.44876 9.78156C3.4823 9.76229 3.51581 9.74297 3.54932 9.72365C3.55586 9.71988 3.56239 9.71612 3.56912 9.71223C3.61261 9.68714 3.65599 9.66188 3.69932 9.63653C3.7555 9.60367 3.81195 9.57129 3.86849 9.53906C3.92379 9.50754 3.97887 9.47566 4.03382 9.44352C4.0976 9.40623 4.16162 9.36934 4.22564 9.33246C4.25854 9.3135 4.29143 9.29452 4.32432 9.27555C4.33745 9.26797 4.35058 9.26039 4.36371 9.25282C4.37346 9.24719 4.37346 9.24719 4.38341 9.24146C5.38795 8.66191 5.38795 8.66191 5.40765 8.65055C5.42076 8.64298 5.43387 8.63542 5.44698 8.62785C5.4801 8.60874 5.51323 8.58964 5.54637 8.57058C5.55973 8.56289 5.57308 8.55521 5.58643 8.54752C5.59289 8.54381 5.59934 8.54009 5.606 8.53626C5.63839 8.51758 5.67068 8.49874 5.70281 8.4796C5.70899 8.47592 5.71517 8.47224 5.72153 8.46845C5.73323 8.46147 5.74491 8.45446 5.75658 8.44742C5.76432 8.4428 5.76432 8.4428 5.77222 8.43808C5.77674 8.43535 5.78126 8.43263 5.78592 8.42983C5.79703 8.42404 5.79703 8.42404 5.80916 8.42404C5.80915 8.41462 5.80915 8.41462 5.80913 8.40501C5.80883 8.12828 5.80855 7.85154 5.80839 7.5748C5.80838 7.57061 5.80838 7.56642 5.80838 7.5621C5.80832 7.47099 5.80827 7.37989 5.80823 7.28878C5.8082 7.2441 5.80818 7.19942 5.80816 7.15474C5.80815 7.15029 5.80815 7.14584 5.80815 7.14126C5.80807 6.99723 5.80794 6.8532 5.80777 6.70917C5.8076 6.56112 5.80749 6.41308 5.80745 6.26503C5.80744 6.2441 5.80744 6.22317 5.80743 6.20224C5.80743 6.19813 5.80743 6.19401 5.80743 6.18976C5.80741 6.12355 5.80732 6.05735 5.80721 5.99114C5.80711 5.92452 5.80707 5.8579 5.80709 5.79129C5.8071 5.75522 5.80709 5.71914 5.80699 5.68307C5.8069 5.65001 5.8069 5.61696 5.80696 5.5839C5.80697 5.57197 5.80694 5.56004 5.80689 5.54812C5.80609 5.37288 5.85858 5.2276 5.9816 5.09949C6.05754 5.0265 6.15464 4.97945 6.24556 4.92783C6.28815 4.90364 6.33053 4.87913 6.37279 4.85436C6.42512 4.82372 6.47767 4.79348 6.53036 4.76346C6.58928 4.72988 6.64799 4.69598 6.70652 4.66174C6.77031 4.62444 6.83432 4.58756 6.89835 4.55068C6.93125 4.53172 6.96414 4.51274 6.99703 4.49376C7.01016 4.48619 7.02329 4.47861 7.03642 4.47103C7.04292 4.46728 7.04942 4.46353 7.05612 4.45967C8.21823 3.78922 8.21823 3.78922 8.23793 3.77786C8.25105 3.77029 8.26417 3.76271 8.27729 3.75514C8.31027 3.73612 8.34324 3.7171 8.37623 3.6981C8.43957 3.6616 8.50285 3.625 8.56595 3.58809C8.62611 3.55291 8.6865 3.51817 8.74707 3.48372C8.77982 3.4651 8.81251 3.4464 8.84498 3.42729C8.90419 3.39256 8.96182 3.36053 9.02731 3.33922C9.03341 3.33718 9.0395 3.33515 9.04578 3.33305C9.25469 3.27614 9.43305 3.3568 9.60783 3.46101ZM9.15359 4.59833C9.14426 4.60378 9.14426 4.60378 9.13474 4.60934C9.12804 4.61332 9.12134 4.61731 9.11444 4.62141C9.10738 4.62556 9.10031 4.62969 9.09325 4.63383C9.07856 4.64243 9.06388 4.65105 9.04921 4.65969C9.01554 4.6795 8.98164 4.69891 8.94777 4.71838C8.89767 4.74725 8.84768 4.77631 8.79777 4.8055C8.74159 4.83836 8.68515 4.87074 8.6286 4.90297C8.5733 4.93449 8.51822 4.96637 8.46328 4.99851C8.3995 5.0358 8.33548 5.07269 8.27145 5.10957C8.23855 5.12853 8.20566 5.14751 8.17278 5.16648C8.15964 5.17406 8.14651 5.18164 8.13338 5.18921C8.12688 5.19296 8.12038 5.19671 8.11368 5.20057C7.26672 5.68921 7.26672 5.68921 7.24699 5.70059C7.23397 5.7081 7.22095 5.71561 7.20794 5.72312C7.17711 5.74092 7.14627 5.7587 7.11542 5.77645C7.10081 5.78486 7.0862 5.79328 7.0716 5.80169C7.06126 5.80764 7.05092 5.81359 7.04057 5.81953C7.03434 5.82313 7.0281 5.82672 7.02167 5.83042C7.01617 5.83359 7.01066 5.83676 7.00499 5.84002C6.99405 5.84648 6.98336 5.85337 6.97278 5.86042C6.97003 5.87925 6.97003 5.87925 6.97055 5.90195C6.97053 5.90629 6.9705 5.91063 6.97048 5.91511C6.97043 5.92981 6.97052 5.9445 6.9706 5.9592C6.97059 5.96979 6.97057 5.98037 6.97055 5.99096C6.97051 6.02016 6.97058 6.04936 6.97067 6.07856C6.97075 6.11001 6.97073 6.14146 6.97071 6.1729C6.9707 6.22743 6.97076 6.28195 6.97086 6.33647C6.97101 6.4153 6.97106 6.49413 6.97108 6.57297C6.97112 6.70085 6.97124 6.82874 6.97141 6.95663C6.97158 7.08089 6.97171 7.20515 6.97179 7.32941C6.97179 7.33706 6.97179 7.34472 6.9718 7.3526C6.97182 7.391 6.97185 7.4294 6.97187 7.4678C6.97206 7.78654 6.97238 8.10529 6.97278 8.42404C6.97987 8.42808 6.97987 8.42808 6.9871 8.43221C7.00504 8.44246 7.02298 8.4527 7.04092 8.46295C7.0486 8.46734 7.05629 8.47173 7.06398 8.47612C7.13629 8.51741 7.20845 8.55898 7.28055 8.60065C7.30674 8.61577 7.33293 8.63088 7.35912 8.64599C7.37881 8.65735 7.3985 8.66871 7.41819 8.68007C7.4446 8.69531 7.47102 8.71054 7.49745 8.72576C7.56079 8.76226 7.62407 8.79886 7.68717 8.83578C7.73976 8.86653 7.79257 8.8969 7.8455 8.92706C7.90442 8.96064 7.96313 8.99454 8.02167 9.02878C8.08545 9.06608 8.14946 9.10296 8.21349 9.13984C8.24639 9.1588 8.27928 9.17778 8.31217 9.19676C8.3253 9.20433 8.33843 9.21191 8.35156 9.21949C8.90307 9.53766 8.90307 9.53767 8.9228 9.54905C8.93582 9.55656 8.94885 9.56407 8.96187 9.57157C8.9927 9.58933 9.0235 9.60713 9.05422 9.62507C9.06876 9.63355 9.08331 9.64202 9.09786 9.65048C9.10815 9.65647 9.11842 9.6625 9.12869 9.66852C9.13491 9.67214 9.14112 9.67575 9.14753 9.67947C9.15574 9.68427 9.15574 9.68427 9.16411 9.68916C9.18278 9.69882 9.18278 9.69882 9.20307 9.70282C9.21687 9.69779 9.21687 9.69779 9.23082 9.68916C9.23628 9.68602 9.24174 9.68288 9.24736 9.67965C9.25324 9.67617 9.25913 9.67269 9.26519 9.6691C9.27137 9.66553 9.27755 9.66195 9.28391 9.65827C9.30347 9.64693 9.32297 9.63548 9.34246 9.62403C9.35446 9.61704 9.36647 9.61005 9.37847 9.60308C9.40253 9.58908 9.42656 9.57505 9.45058 9.56098C9.50876 9.52696 9.5672 9.49337 9.6256 9.45973C9.6585 9.44078 9.69139 9.4218 9.72428 9.40282C9.73741 9.39524 9.75054 9.38767 9.76367 9.38009C9.77342 9.37447 9.77342 9.37447 9.78337 9.36873C10.7879 8.78919 10.7879 8.78919 10.8076 8.77782C10.8207 8.77025 10.8339 8.76268 10.847 8.75511C10.8799 8.73608 10.9129 8.71707 10.9459 8.69806C11.0151 8.65817 11.0843 8.61811 11.1532 8.57774C11.187 8.55806 11.2208 8.53855 11.2547 8.51923C11.2585 8.51704 11.2624 8.51485 11.2663 8.51259C11.2851 8.5019 11.3039 8.49122 11.3227 8.48057C11.3329 8.47478 11.3329 8.47478 11.3433 8.46887C11.3492 8.46548 11.3552 8.46208 11.3614 8.45859C11.3672 8.45518 11.3729 8.45178 11.3788 8.44828C11.3882 8.44426 11.3882 8.44426 11.3978 8.44017C11.4178 8.42156 11.418 8.41775 11.4197 8.39162C11.4198 8.3776 11.4198 8.36358 11.4195 8.34957C11.4196 8.34185 11.4196 8.33413 11.4196 8.32618C11.4197 8.30474 11.4196 8.28331 11.4194 8.26187C11.4192 8.23876 11.4193 8.21565 11.4193 8.19254C11.4193 8.1525 11.4192 8.11245 11.419 8.07241C11.4187 8.01451 11.4186 7.95661 11.4186 7.89872C11.4185 7.80478 11.4183 7.71085 11.4179 7.61692C11.4176 7.52567 11.4173 7.43441 11.4172 7.34316C11.4172 7.33753 11.4172 7.33191 11.4171 7.32612C11.4171 7.29791 11.4171 7.26969 11.417 7.24148C11.4166 7.00739 11.416 6.77329 11.4152 6.5392C11.3923 6.54811 11.3716 6.55829 11.3503 6.57052C11.3436 6.57439 11.3368 6.57826 11.3299 6.58224C11.3226 6.58646 11.3153 6.59067 11.308 6.59488C11.3004 6.59926 11.2927 6.60363 11.2851 6.60801C11.2656 6.61925 11.246 6.63051 11.2265 6.64178C11.2091 6.65177 11.1918 6.66175 11.1745 6.67173C11.142 6.69044 11.1096 6.70918 11.0771 6.72793C11.0444 6.74686 11.0116 6.76575 10.9788 6.78465C10.9723 6.7884 10.9658 6.79215 10.9591 6.79601C10.9262 6.81503 10.8932 6.83405 10.8602 6.85305C10.7969 6.88955 10.7336 6.92615 10.6705 6.96306C10.6179 6.99382 10.5651 7.02418 10.5122 7.05435C10.4567 7.08595 10.4014 7.11771 10.3462 7.1498C10.3403 7.15327 10.3343 7.15674 10.3281 7.16031C10.3226 7.16356 10.317 7.16681 10.3113 7.17016C10.3064 7.17297 10.3016 7.17578 10.2966 7.17868C10.2893 7.18314 10.2893 7.18314 10.2819 7.18768C10.2756 7.19082 10.2693 7.19396 10.2629 7.19719C10.2431 7.21065 10.2431 7.21065 10.242 7.23466C10.2423 7.244 10.2428 7.25333 10.2435 7.26265C10.2438 7.27031 10.2438 7.27031 10.2441 7.27813C10.2446 7.28923 10.2451 7.30032 10.2457 7.31142C10.2469 7.33512 10.2474 7.35883 10.248 7.38256C10.249 7.4267 10.2504 7.47079 10.2528 7.51488C10.2636 7.71511 10.2636 7.71511 10.2321 7.76229C10.195 7.80348 10.1426 7.82261 10.0914 7.84016C10.0572 7.85299 10.0272 7.87189 9.99625 7.89109C9.98436 7.89808 9.97247 7.90504 9.96055 7.91197C9.95462 7.91543 9.9487 7.91889 9.94259 7.92246C9.89071 7.95269 9.83863 7.9826 9.7866 8.01258C9.75369 8.03153 9.72081 8.05052 9.68792 8.06949C9.67478 8.07707 9.66165 8.08465 9.64852 8.09222C9.63877 8.09785 9.63877 8.09785 9.62883 8.10358C9.56973 8.13767 9.56973 8.13767 9.55002 8.14905C9.53694 8.15659 9.52387 8.16414 9.51079 8.17169C9.47715 8.1911 9.44349 8.2105 9.40982 8.22986C9.40296 8.23381 9.39611 8.23775 9.38905 8.24182C9.37559 8.24956 9.36213 8.25729 9.34866 8.265C9.32045 8.28122 9.29241 8.29754 9.26496 8.31502C9.26075 8.31767 9.25654 8.32032 9.25221 8.32306C9.24154 8.32986 9.23095 8.3368 9.22038 8.34376C9.20307 8.35131 9.20307 8.35131 9.18887 8.34682C9.17229 8.33896 9.15629 8.33056 9.14029 8.32158C9.13408 8.3181 9.12787 8.31462 9.12148 8.31104C9.11162 8.30547 9.11162 8.30547 9.10156 8.29979C9.09473 8.29595 9.0879 8.29211 9.08086 8.28816C9.03971 8.26495 8.99877 8.24141 8.95813 8.21731C8.91988 8.19463 8.88138 8.17238 8.84285 8.15017C8.83278 8.14437 8.83278 8.14437 8.82251 8.13846C8.80875 8.13053 8.79499 8.1226 8.78123 8.11468C8.74809 8.09559 8.71498 8.07648 8.68186 8.05737C8.66873 8.0498 8.6556 8.04222 8.64247 8.03465C8.61621 8.01949 8.58994 8.00434 8.56368 7.98919C8.55393 7.98356 8.55393 7.98356 8.54398 7.97782C8.53087 7.97026 8.51776 7.96269 8.50464 7.95513C8.47153 7.93602 8.4384 7.91692 8.40525 7.89786C8.3919 7.89017 8.37855 7.88248 8.3652 7.8748C8.35874 7.87108 8.35228 7.86737 8.34563 7.86354C8.31323 7.84486 8.28095 7.82602 8.24882 7.80688C8.24264 7.8032 8.23646 7.79952 8.2301 7.79573C8.2184 7.78875 8.20671 7.78174 8.19505 7.7747C8.18988 7.77162 8.18472 7.76853 8.1794 7.76535C8.17262 7.76127 8.17262 7.76127 8.16571 7.7571C8.15489 7.75038 8.15489 7.75038 8.14247 7.75131C8.14547 7.14832 8.14547 7.14832 8.14853 6.53314C8.18453 6.51314 8.22053 6.49314 8.25762 6.47254C8.28092 6.45911 8.30416 6.44564 8.32732 6.43201C8.33977 6.42471 8.35222 6.41742 8.36468 6.41013C8.37098 6.40644 8.37729 6.40275 8.38379 6.39894C8.41616 6.38005 8.44863 6.36133 8.48111 6.34261C8.48765 6.33884 8.49419 6.33507 8.50093 6.33118C8.51421 6.32354 8.52748 6.31589 8.54076 6.30824C8.57366 6.28928 8.60655 6.2703 8.63944 6.25132C8.65257 6.24375 8.6657 6.23617 8.67883 6.2286C8.68533 6.22485 8.69183 6.2211 8.69853 6.21723C8.80686 6.15473 8.80686 6.15473 8.91519 6.09223C8.9217 6.08848 8.92821 6.08472 8.93492 6.08085C8.94794 6.07334 8.96097 6.06585 8.974 6.05837C9.00489 6.04063 9.03568 6.02275 9.06618 6.00436C9.08064 5.99566 9.09514 5.98704 9.10965 5.97842C9.11991 5.97229 9.13009 5.96603 9.14028 5.95978C9.14647 5.95611 9.15267 5.95243 9.15906 5.94865C9.16722 5.94371 9.16722 5.94371 9.17555 5.93867C9.19095 5.93314 9.19095 5.93315 9.20616 5.93719C9.21114 5.93985 9.21612 5.94252 9.22125 5.94527C9.22622 5.94785 9.23118 5.95043 9.23629 5.95308C9.24156 5.95604 9.24682 5.95899 9.25224 5.96203C9.25823 5.96538 9.26422 5.96873 9.27039 5.97219C9.2768 5.9758 9.28321 5.97942 9.28981 5.98314C9.29986 5.9888 9.29987 5.9888 9.31012 5.99457C9.35582 6.02035 9.40131 6.04648 9.44663 6.07292C9.45254 6.07636 9.45846 6.0798 9.46455 6.08335C9.4952 6.10127 9.52565 6.11945 9.55591 6.13802C9.56199 6.14172 9.56806 6.14541 9.57432 6.14922C9.58589 6.15626 9.59741 6.16338 9.60888 6.17059C9.61405 6.17372 9.61922 6.17686 9.62454 6.18009C9.63129 6.18428 9.63129 6.18428 9.63818 6.18855C9.65572 6.19537 9.66403 6.19345 9.68186 6.18769C9.69358 6.1819 9.70509 6.17565 9.7164 6.16908C9.72314 6.16519 9.72989 6.16131 9.73684 6.1573C9.74414 6.15304 9.75145 6.14877 9.75875 6.14451C9.76636 6.1401 9.77398 6.1357 9.7816 6.1313C9.79729 6.12224 9.81296 6.11315 9.82861 6.10405C9.85629 6.08796 9.88403 6.07199 9.91177 6.05602C9.93774 6.04106 9.96368 6.02607 9.98962 6.01108C10.0224 5.99216 10.0551 5.97326 10.0879 5.95436C10.101 5.94678 10.1142 5.93921 10.1273 5.93163C10.5212 5.70436 10.5212 5.70436 10.541 5.69298C10.554 5.68546 10.567 5.67794 10.5801 5.67041C10.6107 5.65269 10.6415 5.635 10.6722 5.61742C10.6867 5.60914 10.7012 5.60084 10.7157 5.59254C10.7259 5.58671 10.7361 5.5809 10.7463 5.5751C10.7525 5.57154 10.7587 5.56799 10.7651 5.56433C10.7705 5.56122 10.776 5.55812 10.7816 5.55492C10.7979 5.54471 10.8125 5.53331 10.8273 5.52103C10.7942 5.49724 10.7596 5.47696 10.7239 5.45739C10.6802 5.43341 10.637 5.40872 10.594 5.38353C10.5428 5.35356 10.4916 5.32374 10.4402 5.29413C10.4336 5.29036 10.4271 5.28659 10.4204 5.28271C10.4071 5.27506 10.3938 5.26741 10.3805 5.25976C10.3476 5.24081 10.3147 5.22183 10.2819 5.20285C10.2687 5.19527 10.2556 5.1877 10.2425 5.18012C10.0061 5.04376 9.76973 4.90739 9.53337 4.77103C9.52686 4.76728 9.52035 4.76352 9.51365 4.75965C9.5006 4.75213 9.48756 4.7446 9.47452 4.73707C9.44398 4.71945 9.41343 4.70183 9.38285 4.68425C9.37205 4.67805 9.36126 4.67184 9.35047 4.66562C9.33694 4.65784 9.32342 4.65007 9.30989 4.6423C9.27917 4.62462 9.24886 4.6068 9.21957 4.5868C9.19374 4.57403 9.17595 4.58513 9.15359 4.59833ZM14.7698 4.59589C14.7643 4.59901 14.7589 4.60212 14.7532 4.60533C14.7473 4.60876 14.7413 4.6122 14.7352 4.61573C14.7259 4.62105 14.7259 4.62105 14.7164 4.62648C14.6606 4.65849 14.605 4.69096 14.5495 4.72347C14.4913 4.7575 14.4328 4.79108 14.3744 4.82472C14.3415 4.84368 14.3087 4.86266 14.2758 4.88164C14.2626 4.88921 14.2495 4.89679 14.2364 4.90436C14.2299 4.90811 14.2234 4.91186 14.2167 4.91573C13.2121 5.49527 13.2121 5.49527 13.1924 5.50663C13.1793 5.5142 13.1662 5.52178 13.1531 5.52935C13.1201 5.54837 13.0871 5.56739 13.0541 5.58639C12.9849 5.62629 12.9158 5.66635 12.8468 5.70671C12.8131 5.7264 12.7793 5.7459 12.7454 5.76522C12.7415 5.76742 12.7377 5.76961 12.7337 5.77187C12.7149 5.78256 12.6962 5.79323 12.6774 5.80388C12.6672 5.80967 12.6672 5.80967 12.6568 5.81558C12.6508 5.81898 12.6448 5.82237 12.6386 5.82587C12.6329 5.82927 12.6271 5.83267 12.6212 5.83618C12.615 5.83951 12.6087 5.84284 12.6023 5.84627C12.5832 5.85888 12.5832 5.85888 12.5802 5.87977C12.5801 5.8875 12.5801 5.89523 12.58 5.9032C12.5799 5.90753 12.5798 5.91186 12.5797 5.91633C12.5795 5.93092 12.5795 5.94549 12.5795 5.96009C12.5794 5.97062 12.5793 5.98116 12.5791 5.99169C12.5787 6.0207 12.5786 6.04971 12.5785 6.07872C12.5784 6.10999 12.578 6.14126 12.5777 6.17252C12.577 6.24807 12.5766 6.32362 12.5763 6.39917C12.5761 6.43475 12.5759 6.47033 12.5758 6.50591C12.5751 6.6242 12.5746 6.74249 12.5743 6.86078C12.5743 6.89148 12.5742 6.92218 12.5741 6.95288C12.5741 6.96051 12.5741 6.96814 12.5741 6.97601C12.5738 7.09958 12.5729 7.22314 12.5717 7.34671C12.5705 7.47359 12.5698 7.60046 12.5697 7.72734C12.5696 7.79858 12.5693 7.8698 12.5684 7.94103C12.5676 8.00172 12.5673 8.06238 12.5676 8.12306C12.5678 8.15402 12.5677 8.18493 12.567 8.21589C12.5592 8.33505 12.5592 8.33505 12.5993 8.44212C12.6336 8.47119 12.6712 8.48835 12.7135 8.50285C12.7355 8.51074 12.7537 8.52143 12.7735 8.53386C12.7851 8.54056 12.7967 8.54726 12.8083 8.55396C12.8216 8.56159 12.8348 8.56922 12.8481 8.57685C12.8546 8.58064 12.8612 8.58443 12.868 8.58833C12.9009 8.60729 12.9338 8.62627 12.9667 8.64525C12.9798 8.65282 12.9929 8.6604 13.0061 8.66797C13.2424 8.80434 13.4788 8.9407 13.7152 9.07706C13.7217 9.08081 13.7282 9.08456 13.7349 9.08843C13.748 9.096 13.7611 9.10357 13.7742 9.11114C13.8072 9.13016 13.8402 9.14918 13.8732 9.16818C13.9365 9.20468 13.9998 9.24128 14.0629 9.2782C14.1155 9.30896 14.1683 9.33932 14.2212 9.36948C14.2801 9.40306 14.3388 9.43696 14.3974 9.4712C14.4678 9.51236 14.5384 9.55303 14.6091 9.59373C14.6345 9.60838 14.66 9.62304 14.6854 9.6377C14.6956 9.64358 14.7058 9.64946 14.716 9.65534C14.7222 9.65891 14.7284 9.66248 14.7348 9.66617C14.7429 9.67087 14.7429 9.67087 14.7513 9.67567C14.7619 9.68188 14.7725 9.6883 14.7829 9.6949C14.7964 9.70405 14.7964 9.70405 14.8113 9.70248C14.8328 9.69479 14.8515 9.68363 14.8708 9.67175C14.8801 9.6662 14.8893 9.66065 14.8986 9.65511C14.9036 9.65207 14.9087 9.64904 14.9139 9.64591C14.9443 9.62781 14.975 9.61023 15.0057 9.59259C15.0193 9.58474 15.0329 9.57689 15.0466 9.56903C15.0568 9.56312 15.0568 9.56312 15.0673 9.55709C15.1004 9.53801 15.1335 9.5189 15.1667 9.49979C15.1798 9.49221 15.1929 9.48463 15.2061 9.47706C15.2158 9.47143 15.2158 9.47143 15.2258 9.4657C15.4424 9.3407 15.4424 9.3407 15.4621 9.32933C15.4752 9.32176 15.4884 9.31419 15.5015 9.30662C15.5345 9.28759 15.5674 9.26858 15.6004 9.24958C15.6638 9.21308 15.727 9.17648 15.7901 9.13956C15.8463 9.1067 15.9028 9.07432 15.9593 9.0421C16.0146 9.0106 16.0696 8.97875 16.1245 8.94662C16.1696 8.92023 16.2149 8.89406 16.2602 8.86797C16.3201 8.83346 16.3799 8.79865 16.4394 8.76343C16.4194 8.74672 16.3994 8.73295 16.3766 8.72039C16.3673 8.71523 16.3673 8.71523 16.3578 8.70997C16.3512 8.70636 16.3446 8.70275 16.3379 8.69903C16.2938 8.6746 16.2498 8.65016 16.2064 8.62441C16.1642 8.59935 16.1217 8.57469 16.0792 8.55017C16.0691 8.54437 16.0691 8.54437 16.0588 8.53845C16.0451 8.53053 16.0313 8.5226 16.0175 8.51468C15.9844 8.49559 15.9513 8.47648 15.9182 8.45737C15.905 8.44979 15.8919 8.44222 15.8788 8.43464C15.8 8.38919 15.7212 8.34373 15.6424 8.29828C15.6359 8.29453 15.6294 8.29077 15.6227 8.28691C15.6096 8.27936 15.5966 8.27182 15.5835 8.26427C15.5498 8.24485 15.5162 8.22546 15.4825 8.20609C15.4132 8.16622 15.344 8.12622 15.2758 8.08464C15.2714 8.08716 15.267 8.08968 15.2625 8.09227C15.2212 8.11598 15.1797 8.13939 15.1381 8.16259C15.0856 8.19189 15.0331 8.22139 14.9812 8.25175C14.9688 8.25897 14.9565 8.26615 14.9441 8.27329C14.9183 8.2882 14.893 8.30317 14.8685 8.3202C14.8629 8.32392 14.8629 8.32392 14.8572 8.32772C14.8479 8.33402 14.8388 8.34061 14.8296 8.34724C14.7939 8.35432 14.7667 8.33262 14.7364 8.31495C14.7308 8.31179 14.7252 8.30864 14.7194 8.30539C14.7025 8.29574 14.6857 8.28587 14.6689 8.27593C14.6562 8.26842 14.6434 8.2609 14.6306 8.25339C14.6241 8.24955 14.6175 8.24571 14.6108 8.24175C14.5782 8.22268 14.5456 8.20385 14.5129 8.18502C14.5031 8.17937 14.5031 8.17937 14.4931 8.1736C14.4798 8.16595 14.4665 8.1583 14.4532 8.15065C14.4203 8.13169 14.3874 8.11271 14.3545 8.09374C14.3414 8.08616 14.3283 8.07858 14.3152 8.07101C14.0788 7.93465 14.0788 7.93465 14.0591 7.92327C14.046 7.91574 14.033 7.90822 14.02 7.9007C13.9893 7.88304 13.9587 7.86538 13.9281 7.84771C13.9173 7.84145 13.9064 7.8352 13.8956 7.82894C13.882 7.82109 13.8684 7.81324 13.8548 7.80539C13.8486 7.80183 13.8425 7.79828 13.8361 7.79461C13.8307 7.79151 13.8254 7.78841 13.8198 7.78521C13.8001 7.77387 13.7804 7.7626 13.7606 7.75131C13.7606 7.34932 13.7606 6.94732 13.7606 6.53314C13.8166 6.50114 13.8726 6.46914 13.9303 6.43617C13.9849 6.40436 13.9849 6.40436 14.0395 6.37249C14.0973 6.33869 14.1554 6.30531 14.2134 6.27188C14.2463 6.25292 14.2792 6.23394 14.3121 6.21496C14.3253 6.20739 14.3384 6.19981 14.3515 6.19223C14.358 6.18848 14.3645 6.18473 14.3712 6.18087C14.4303 6.14678 14.4303 6.14678 14.45 6.13541C14.4631 6.12786 14.4762 6.12032 14.4893 6.11277C14.5229 6.09335 14.5565 6.07396 14.5902 6.05459C14.5971 6.05065 14.6039 6.0467 14.611 6.04264C14.6245 6.03489 14.6379 6.02716 14.6514 6.01945C14.6796 6.00327 14.7075 5.98699 14.7349 5.96944C14.7411 5.96546 14.7411 5.96546 14.7475 5.9614C14.7581 5.9546 14.7686 5.94766 14.7791 5.9407C14.8025 5.93081 14.8101 5.93597 14.8333 5.94527C14.8443 5.95092 14.8551 5.9569 14.8658 5.96314C14.872 5.96673 14.8782 5.97033 14.8845 5.97403C14.8911 5.97791 14.8977 5.9818 14.9045 5.9858C14.9116 5.98989 14.9186 5.99398 14.9256 5.99806C14.9402 6.00654 14.9547 6.01503 14.9693 6.02354C15.0027 6.04305 15.0362 6.06233 15.0697 6.08163C15.0828 6.0892 15.096 6.09678 15.1091 6.10436C15.1188 6.10998 15.1188 6.10998 15.1288 6.11572C15.2535 6.18769 15.3783 6.25966 15.503 6.33163C15.5095 6.33538 15.516 6.33913 15.5227 6.343C15.5358 6.35054 15.5489 6.35807 15.5619 6.36561C15.5923 6.38311 15.6226 6.40061 15.6529 6.41809C15.6635 6.42421 15.6741 6.43033 15.6847 6.43644C15.698 6.44406 15.7112 6.45168 15.7244 6.45929C15.7362 6.46609 15.7479 6.47299 15.7595 6.48003C15.7783 6.4911 15.7783 6.4911 15.798 6.49778C15.8204 6.50711 15.8347 6.51544 15.8515 6.53314C15.8629 6.56593 15.8599 6.60221 15.8587 6.63641C15.858 6.65423 15.8578 6.672 15.8577 6.68983C15.8574 6.72764 15.8566 6.76542 15.8557 6.80321C15.8547 6.84705 15.854 6.89087 15.8537 6.93471C15.8535 6.95224 15.8529 6.96974 15.8523 6.98726C15.8492 7.04052 15.8492 7.04052 15.8691 7.08753C15.8833 7.09716 15.8961 7.10312 15.9121 7.10889C15.9202 7.11337 15.9283 7.11796 15.9362 7.12272C15.9444 7.12722 15.9527 7.1317 15.961 7.13617C16.0044 7.15998 16.0474 7.18458 16.0901 7.20965C16.1437 7.24106 16.1975 7.27209 16.2515 7.30283C16.3104 7.3364 16.3691 7.37031 16.4277 7.40455C16.4914 7.44185 16.5555 7.47873 16.6195 7.51561C16.6589 7.53831 16.6983 7.56104 16.7376 7.58377C16.7681 7.60133 16.7985 7.61889 16.829 7.63642C16.8397 7.64258 16.8504 7.64875 16.8611 7.65491C16.8745 7.66261 16.8878 7.67031 16.9012 7.678C16.9355 7.69778 16.9696 7.71789 17.0033 7.73878C17.0147 7.74622 17.0147 7.74622 17.0273 7.74525C17.0303 7.50648 17.0327 7.26771 17.0341 7.02893C17.0342 7.00072 17.0344 6.9725 17.0346 6.94429C17.0346 6.93868 17.0347 6.93306 17.0347 6.92727C17.0353 6.83642 17.0363 6.74557 17.0375 6.65472C17.0388 6.56146 17.0395 6.46819 17.0398 6.37491C17.04 6.31738 17.0406 6.25988 17.0416 6.20236C17.0424 6.16287 17.0426 6.1234 17.0424 6.08391C17.0423 6.06114 17.0424 6.03842 17.0432 6.01565C17.0491 5.92484 17.0491 5.92484 17.0141 5.84551C16.9822 5.8199 16.9474 5.8031 16.9096 5.78806C16.889 5.7796 16.8709 5.76892 16.852 5.75725C16.8402 5.75047 16.8284 5.7437 16.8167 5.73693C16.8033 5.72925 16.7899 5.72156 16.7766 5.71388C16.7666 5.70814 16.7666 5.70814 16.7564 5.70228C16.7235 5.68331 16.6905 5.66429 16.6576 5.64527C16.6444 5.63769 16.6313 5.63012 16.6182 5.62254C16.1848 5.37254 16.1848 5.37254 15.7515 5.12254C15.745 5.11879 15.7385 5.11504 15.7318 5.11118C15.7187 5.10361 15.7056 5.09604 15.6924 5.08847C15.6595 5.06944 15.6265 5.05042 15.5935 5.03142C15.5302 4.99492 15.4669 4.95832 15.4038 4.92141C15.3512 4.89065 15.2984 4.86029 15.2455 4.83012C15.1866 4.7966 15.128 4.76275 15.0695 4.72855C15.0231 4.70139 14.9765 4.67442 14.9299 4.64755C14.9233 4.64374 14.9167 4.63994 14.9099 4.63602C14.8978 4.62901 14.8856 4.62202 14.8734 4.61504C14.8637 4.6094 14.854 4.60371 14.8443 4.59791C14.8137 4.57963 14.8005 4.57829 14.7698 4.59589ZM11.9675 9.45284C11.9612 9.45647 11.9549 9.46011 11.9484 9.46385C11.9416 9.46783 11.9347 9.47182 11.9277 9.47592C11.9205 9.48007 11.9134 9.48421 11.9062 9.48835C11.8913 9.49697 11.8764 9.5056 11.8616 9.51423C11.8279 9.53371 11.7943 9.55311 11.7606 9.57251C11.7475 9.58009 11.7344 9.58766 11.7212 9.59524C10.697 10.1861 10.697 10.1861 10.6773 10.1975C10.6642 10.2051 10.6511 10.2127 10.6379 10.2202C10.605 10.2392 10.572 10.2583 10.539 10.2773C10.4757 10.3138 10.4124 10.3504 10.3493 10.3873C10.2931 10.4201 10.2366 10.4525 10.1801 10.4847C10.1249 10.5162 10.0699 10.548 10.0151 10.5801C9.98259 10.5991 9.95005 10.618 9.91741 10.6368C9.912 10.6399 9.912 10.6399 9.90647 10.643C9.88893 10.6531 9.87138 10.6632 9.85382 10.6732C9.84754 10.6768 9.84126 10.6804 9.83479 10.6841C9.82924 10.6873 9.82369 10.6905 9.81798 10.6937C9.81306 10.6967 9.80814 10.6997 9.80307 10.7028C9.7967 10.7063 9.7967 10.7063 9.79021 10.7098C9.77701 10.7206 9.77701 10.7206 9.77575 10.7396C9.77573 10.7473 9.77571 10.7551 9.77569 10.7631C9.77564 10.7674 9.7756 10.7717 9.77556 10.7762C9.77544 10.7908 9.77549 10.8054 9.77554 10.82C9.77549 10.8306 9.77543 10.8411 9.77536 10.8516C9.7752 10.8807 9.77519 10.9097 9.77521 10.9388C9.7752 10.9701 9.77506 11.0014 9.77493 11.0327C9.77471 11.094 9.77462 11.1554 9.77458 11.2167C9.77455 11.2666 9.77449 11.3164 9.7744 11.3663C9.77415 11.5075 9.77401 11.6487 9.774 11.79C9.774 11.7976 9.774 11.8052 9.774 11.8131C9.774 11.8207 9.774 11.8283 9.774 11.8362C9.77398 11.9598 9.7737 12.0835 9.7733 12.2072C9.7729 12.334 9.7727 12.4609 9.77271 12.5878C9.77271 12.6591 9.77262 12.7303 9.77232 12.8016C9.77206 12.8623 9.77199 12.923 9.77216 12.9836C9.77224 13.0146 9.77224 13.0456 9.772 13.0766C9.77178 13.1049 9.77181 13.1332 9.77204 13.1616C9.77208 13.1719 9.77203 13.1821 9.77188 13.1924C9.76919 13.246 9.76919 13.246 9.79083 13.2925C9.80474 13.3019 9.81781 13.3086 9.83337 13.3149C9.84163 13.3199 9.84163 13.3199 9.85005 13.3249C9.85699 13.3288 9.85699 13.3288 9.86407 13.3327C9.86944 13.3357 9.8748 13.3387 9.88032 13.3418C9.88595 13.3449 9.89158 13.3481 9.89738 13.3513C9.9464 13.3787 9.99514 13.4066 10.0436 13.435C10.0966 13.466 10.1497 13.4966 10.2031 13.527C10.262 13.5606 10.3207 13.5945 10.3792 13.6287C10.443 13.666 10.507 13.7029 10.571 13.7398C10.6039 13.7588 10.6368 13.7777 10.6697 13.7967C10.6829 13.8043 10.696 13.8119 10.7091 13.8195C10.998 13.9861 11.2869 14.1528 11.5758 14.3194C11.5823 14.3232 11.5888 14.327 11.5955 14.3308C11.6086 14.3384 11.6217 14.346 11.6348 14.3535C11.6678 14.3726 11.7008 14.3916 11.7338 14.4106C11.7404 14.4144 11.7469 14.4182 11.7537 14.4221C11.7668 14.4296 11.7799 14.4371 11.7931 14.4446C11.8265 14.4636 11.8591 14.4833 11.8912 14.5044C11.8977 14.5085 11.9041 14.5126 11.9107 14.5169C11.923 14.5247 11.935 14.5327 11.9469 14.541C11.964 14.5518 11.9773 14.5591 11.997 14.5634C12.0245 14.5563 12.0461 14.5424 12.0697 14.527C12.0808 14.5207 12.0919 14.5144 12.1031 14.5081C12.1145 14.5014 12.1258 14.4947 12.1371 14.488C12.1499 14.4805 12.1627 14.473 12.1755 14.4655C12.182 14.4616 12.1886 14.4578 12.1953 14.4538C12.2278 14.4348 12.2605 14.4159 12.2932 14.3971C12.2997 14.3933 12.3063 14.3896 12.313 14.3857C12.3263 14.378 12.3396 14.3704 12.3529 14.3627C12.3858 14.3438 12.4186 14.3248 12.4515 14.3058C12.4647 14.2982 12.4778 14.2907 12.4909 14.2831C12.5007 14.2775 12.5007 14.2775 12.5106 14.2717C13.2 13.874 13.2 13.874 13.2197 13.8626C13.2328 13.8551 13.246 13.8475 13.2591 13.8399C13.292 13.8209 13.325 13.8019 13.358 13.7829C13.4214 13.7464 13.4846 13.7098 13.5477 13.6729C13.6039 13.64 13.6604 13.6076 13.7169 13.5754C13.7722 13.5439 13.8272 13.512 13.8822 13.4799C13.9268 13.4538 13.9715 13.4279 14.0163 13.402C14.0222 13.3986 14.0281 13.3952 14.0341 13.3917C14.0964 13.3558 14.1588 13.3203 14.2212 13.2846C14.2212 12.4366 14.2212 11.5886 14.2212 10.7149C14.1462 10.6729 14.1462 10.6729 14.0697 10.6301C14.0186 10.6002 14.0186 10.6002 13.9941 10.5857C13.96 10.5655 13.9256 10.5457 13.8913 10.5259C13.8812 10.5201 13.8812 10.5201 13.871 10.5142C13.8572 10.5063 13.8434 10.4983 13.8297 10.4904C13.7965 10.4713 13.7634 10.4522 13.7303 10.4331C13.7172 10.4255 13.704 10.418 13.6909 10.4104C13.6647 10.3952 13.6384 10.3801 13.6121 10.3649C13.6056 10.3612 13.5991 10.3574 13.5924 10.3536C13.5793 10.346 13.5662 10.3384 13.5531 10.3309C13.5201 10.3118 13.4871 10.2928 13.4541 10.2738C13.3908 10.2373 13.3275 10.2007 13.2644 10.1638C13.2118 10.133 13.159 10.1027 13.1061 10.0725C13.0472 10.0389 12.9884 10.005 12.9299 9.97079C12.8661 9.93349 12.8021 9.89661 12.7381 9.85973C12.7052 9.84077 12.6723 9.82179 12.6394 9.80281C12.6263 9.79524 12.6131 9.78766 12.6 9.78009C12.3637 9.64372 12.3637 9.64372 12.3439 9.63235C12.3309 9.62481 12.3178 9.61727 12.3047 9.60973C12.271 9.59027 12.2373 9.5708 12.2035 9.55132C12.1706 9.53233 12.1377 9.51336 12.1048 9.49439C12.0942 9.48825 12.0835 9.48211 12.0729 9.47597C12.0606 9.46887 12.0483 9.46179 12.036 9.45471C12.0296 9.45103 12.0232 9.44735 12.0167 9.44356C11.9945 9.43149 11.989 9.44034 11.9675 9.45284ZM17.5933 9.44053C17.5881 9.44364 17.5829 9.44675 17.5775 9.44995C17.5715 9.4534 17.5656 9.45685 17.5594 9.4604C17.5499 9.46621 17.5499 9.46621 17.5401 9.47214C17.5334 9.47605 17.5267 9.47996 17.5199 9.484C17.5059 9.49219 17.4919 9.50043 17.478 9.50876C17.459 9.52012 17.4399 9.5313 17.4208 9.5424C17.3968 9.55629 17.3729 9.57024 17.349 9.58426C17.3108 9.60665 17.2725 9.62881 17.2341 9.65092C17.2243 9.65658 17.2243 9.65658 17.2142 9.66235C17.201 9.67 17.1877 9.67765 17.1744 9.68529C17.1415 9.70425 17.1086 9.72323 17.0757 9.74221C17.0626 9.74978 17.0495 9.75736 17.0363 9.76494C17.0298 9.76869 17.0233 9.77244 17.0167 9.7763C16.9576 9.81039 16.9576 9.81039 16.9379 9.82176C16.9247 9.82933 16.9116 9.8369 16.8985 9.84447C16.8655 9.86349 16.8325 9.88251 16.7996 9.90151C16.7362 9.93801 16.6729 9.97461 16.6098 10.0115C16.5537 10.0444 16.4972 10.0768 16.4407 10.109C16.3854 10.1405 16.3303 10.1724 16.2753 10.2045C16.2116 10.2418 16.1475 10.2787 16.0835 10.3156C16.0506 10.3345 16.0177 10.3535 15.9848 10.3725C15.9717 10.3801 15.9586 10.3877 15.9454 10.3952C15.9357 10.4009 15.9357 10.4009 15.9258 10.4066C15.8535 10.4483 15.7813 10.4899 15.7091 10.5316C15.6993 10.5372 15.6993 10.5372 15.6894 10.543C15.6763 10.5505 15.6633 10.558 15.6502 10.5655C15.6196 10.5832 15.589 10.6009 15.5584 10.6185C15.5476 10.6248 15.5367 10.631 15.5259 10.6373C15.5123 10.6452 15.4987 10.653 15.4851 10.6609C15.4789 10.6644 15.4727 10.668 15.4664 10.6716C15.461 10.6747 15.4556 10.6778 15.4501 10.681C15.4304 10.6924 15.4106 10.7036 15.3909 10.7149C15.3909 11.5629 15.3909 12.4109 15.3909 13.2846C15.4469 13.3166 15.5029 13.3486 15.5606 13.3816C15.6066 13.4081 15.6527 13.4346 15.6987 13.4612C15.7314 13.4801 15.7642 13.499 15.797 13.5179C15.8101 13.5255 15.8232 13.5331 15.8364 13.5407C15.8429 13.5444 15.8494 13.5482 15.8561 13.552C16.0333 13.6543 16.2106 13.7566 16.3879 13.8588C16.3944 13.8626 16.4009 13.8663 16.4076 13.8702C16.4207 13.8778 16.4338 13.8854 16.4469 13.8929C16.4799 13.9119 16.5129 13.931 16.5459 13.95C16.6092 13.9865 16.6725 14.0231 16.7356 14.06C16.7865 14.0897 16.8376 14.1193 16.8887 14.1486C16.8961 14.1528 16.9035 14.1571 16.9109 14.1613C16.9213 14.1673 16.9317 14.1732 16.942 14.1792C16.948 14.1826 16.9539 14.1859 16.96 14.1894C16.9746 14.1975 16.9893 14.2051 17.0042 14.2125C17.0085 14.2147 17.0129 14.2168 17.0173 14.2191C17.0206 14.2207 17.0239 14.2223 17.0273 14.224C17.0285 14.0492 17.0295 13.8744 17.0301 13.6996C17.0301 13.6835 17.0302 13.6673 17.0303 13.6512C17.0303 13.6471 17.0303 13.6431 17.0303 13.639C17.0305 13.578 17.0309 13.5171 17.0314 13.4561C17.0319 13.3854 17.0323 13.3147 17.0324 13.2439C17.0325 13.2065 17.0326 13.169 17.033 13.1316C17.0334 13.0963 17.0335 13.0611 17.0334 13.0258C17.0334 13.0129 17.0336 12.9999 17.0338 12.987C17.0379 12.9216 17.0379 12.9216 17.0155 12.8631C17.0014 12.8534 16.9889 12.8477 16.9727 12.8422C16.9646 12.8377 16.9566 12.8331 16.9486 12.8284C16.9404 12.8239 16.9321 12.8194 16.9238 12.8149C16.8799 12.7908 16.8364 12.766 16.7932 12.7407C16.7841 12.7354 16.7841 12.7354 16.7749 12.73C16.7422 12.7109 16.7096 12.6917 16.677 12.6724C16.6703 12.6685 16.6636 12.6646 16.6567 12.6606C16.6439 12.653 16.631 12.6454 16.6181 12.6377C16.6123 12.6344 16.6066 12.631 16.6006 12.6275C16.5929 12.6229 16.5929 12.6229 16.5851 12.6183C16.5733 12.611 16.5733 12.611 16.5606 12.6119C16.5606 12.2079 16.5606 11.8039 16.5606 11.3877C16.5706 11.3837 16.5806 11.3797 16.5909 11.3755C16.6018 11.3698 16.6126 11.3639 16.6234 11.3579C16.6296 11.3544 16.6358 11.351 16.6422 11.3474C16.6488 11.3437 16.6553 11.34 16.6621 11.3361C16.6689 11.3323 16.6758 11.3285 16.6828 11.3245C16.724 11.3013 16.7649 11.2778 16.8055 11.2536C16.8438 11.231 16.8823 11.2087 16.9208 11.1865C16.9275 11.1827 16.9342 11.1788 16.9412 11.1748C16.9549 11.1669 16.9687 11.1589 16.9824 11.151C17.0156 11.1319 17.0487 11.1128 17.0818 11.0937C17.0949 11.0861 17.1081 11.0786 17.1212 11.071C17.1277 11.0672 17.1342 11.0635 17.1409 11.0596C17.1606 11.0483 17.1803 11.0369 17.2 11.0255C17.2065 11.0218 17.213 11.018 17.2197 11.0142C17.2328 11.0066 17.2459 10.999 17.259 10.9915C17.299 10.9684 17.3389 10.9454 17.3788 10.9223C17.392 10.9147 17.4053 10.9071 17.4185 10.8995C17.4501 10.8813 17.4816 10.863 17.5129 10.8444C17.5187 10.8409 17.5245 10.8375 17.5305 10.8339C17.5414 10.8275 17.5523 10.821 17.5631 10.8144C17.5704 10.8102 17.5704 10.8102 17.5778 10.8058C17.584 10.8021 17.584 10.8021 17.5904 10.7983C17.6072 10.7922 17.6163 10.7945 17.6333 10.7998C17.6476 10.8068 17.6476 10.8068 17.6626 10.8157C17.6682 10.8191 17.6739 10.8224 17.6797 10.8259C17.6858 10.8295 17.6918 10.8331 17.6981 10.8369C17.7113 10.8447 17.7244 10.8525 17.7376 10.8603C17.7444 10.8643 17.7512 10.8683 17.7582 10.8725C17.7909 10.8918 17.8239 10.9108 17.8568 10.9297C17.87 10.9373 17.8833 10.945 17.8965 10.9526C17.9064 10.9583 17.9064 10.9583 17.9165 10.9641C17.9494 10.983 17.9822 11.002 18.0151 11.021C18.0283 11.0286 18.0414 11.0361 18.0545 11.0437C18.1333 11.0892 18.2121 11.1346 18.2909 11.1801C18.2974 11.1838 18.3039 11.1876 18.3106 11.1915C18.3237 11.199 18.3368 11.2065 18.3498 11.2141C18.3835 11.2335 18.4171 11.2529 18.4508 11.2723C18.4577 11.2762 18.4646 11.2802 18.4717 11.2843C18.4847 11.2918 18.4977 11.2992 18.5106 11.3067C18.5225 11.3135 18.5342 11.3204 18.5459 11.3275C18.5607 11.3358 18.5743 11.3426 18.5898 11.3492C18.6495 11.3762 18.6495 11.3762 18.6629 11.4052C18.6716 11.4396 18.6701 11.475 18.6695 11.5102C18.6696 11.5221 18.6698 11.5339 18.67 11.5458C18.6705 11.5779 18.6704 11.6099 18.6702 11.642C18.67 11.6688 18.6702 11.6957 18.6703 11.7225C18.6706 11.7858 18.6705 11.8491 18.6701 11.9124C18.6696 11.9776 18.6699 12.0428 18.6705 12.108C18.671 12.1641 18.6712 12.2202 18.6709 12.2762C18.6708 12.3097 18.6708 12.3431 18.6712 12.3766C18.6716 12.4081 18.6714 12.4395 18.6709 12.471C18.6707 12.4825 18.6708 12.494 18.6711 12.5055C18.6725 12.5764 18.6725 12.5764 18.6575 12.6058C18.6324 12.6319 18.6 12.6467 18.5671 12.6608C18.549 12.6689 18.5325 12.6788 18.5155 12.689C18.5034 12.696 18.4913 12.703 18.4791 12.71C18.4657 12.7178 18.4522 12.7255 18.4387 12.7333C18.4319 12.7372 18.4251 12.7411 18.418 12.7452C18.3964 12.7576 18.3749 12.7701 18.3533 12.7825C18.3497 12.7846 18.3462 12.7866 18.3425 12.7888C18.3254 12.7986 18.3082 12.8085 18.2911 12.8184C18.285 12.822 18.2788 12.8255 18.2724 12.8292C18.2644 12.8338 18.2644 12.8338 18.2562 12.8386C18.2364 12.8499 18.2167 12.8612 18.1969 12.8725C18.1969 13.3185 18.1969 13.7645 18.1969 14.224C18.2914 14.1725 18.3857 14.1206 18.4783 14.0657C18.5165 14.0431 18.555 14.0208 18.5935 13.9986C18.6002 13.9948 18.607 13.9909 18.6139 13.9869C18.6276 13.979 18.6414 13.971 18.6552 13.9631C18.6883 13.944 18.7214 13.9249 18.7545 13.9058C18.7676 13.8982 18.7808 13.8907 18.7939 13.8831C18.8037 13.8775 18.8037 13.8775 18.8136 13.8717C19.1878 13.6558 19.1878 13.6558 19.2075 13.6445C19.2207 13.6369 19.2338 13.6293 19.2469 13.6217C19.2799 13.6027 19.3129 13.5837 19.3458 13.5647C19.4151 13.5248 19.4843 13.4847 19.5532 13.4443C19.5867 13.4248 19.6203 13.4054 19.654 13.3863C19.6597 13.383 19.6597 13.383 19.6655 13.3797C19.684 13.3692 19.7025 13.3587 19.721 13.3483C19.7278 13.3444 19.7345 13.3406 19.7414 13.3367C19.7473 13.3334 19.7532 13.33 19.7593 13.3266C19.7657 13.3227 19.7721 13.3189 19.7788 13.3149C19.7832 13.3131 19.7877 13.3113 19.7923 13.3094C19.8098 13.3009 19.8206 13.2933 19.8333 13.2785C19.8418 13.245 19.8407 13.2118 19.8402 13.1773C19.8403 13.1668 19.8404 13.1562 19.8405 13.1457C19.8407 13.1166 19.8406 13.0876 19.8404 13.0586C19.8403 13.0274 19.8405 12.9961 19.8406 12.9648C19.8409 12.9035 19.8408 12.8422 19.8407 12.7809C19.8406 12.7311 19.8405 12.6813 19.8406 12.6315C19.8406 12.6245 19.8406 12.6174 19.8406 12.6101C19.8406 12.5957 19.8407 12.5813 19.8407 12.5669C19.8408 12.4319 19.8407 12.297 19.8404 12.162C19.8401 12.0462 19.8402 11.9303 19.8404 11.8144C19.8407 11.68 19.8408 11.5455 19.8406 11.411C19.8406 11.3967 19.8406 11.3823 19.8406 11.368C19.8406 11.3574 19.8406 11.3574 19.8406 11.3466C19.8405 11.2969 19.8406 11.2471 19.8407 11.1974C19.8409 11.1368 19.8408 11.0761 19.8406 11.0155C19.8404 10.9846 19.8404 10.9537 19.8405 10.9227C19.8407 10.8944 19.8406 10.8661 19.8403 10.8378C19.8403 10.8276 19.8403 10.8173 19.8404 10.8071C19.843 10.7535 19.843 10.7535 19.8213 10.7071C19.8074 10.6976 19.7943 10.6909 19.7788 10.6846C19.7696 10.6792 19.7696 10.6792 19.7603 10.6737C19.7549 10.6707 19.7495 10.6677 19.7439 10.6646C19.7378 10.6612 19.7316 10.6578 19.7253 10.6543C19.719 10.6508 19.7126 10.6473 19.706 10.6437C19.6625 10.6195 19.619 10.5953 19.5761 10.5699C19.5339 10.5448 19.4914 10.5201 19.4488 10.4956C19.4388 10.4898 19.4388 10.4898 19.4285 10.4839C19.4147 10.476 19.401 10.468 19.3872 10.4601C19.3541 10.441 19.321 10.4219 19.2878 10.4028C19.2747 10.3952 19.2616 10.3877 19.2485 10.3801C18.9727 10.221 18.9727 10.221 18.6969 10.0619C18.6904 10.0582 18.6839 10.0544 18.6772 10.0505C18.6641 10.043 18.651 10.0354 18.6379 10.0278C18.6049 10.0088 18.5719 9.98978 18.5389 9.97078C18.4756 9.93428 18.4123 9.89768 18.3492 9.86077C18.2966 9.83001 18.2438 9.79965 18.1909 9.76948C18.132 9.73591 18.0733 9.702 18.0147 9.66776C17.9577 9.63443 17.9005 9.60142 17.8433 9.56846C17.819 9.55444 17.7946 9.54039 17.7703 9.5263C17.7559 9.51795 17.7415 9.50961 17.7271 9.50127C17.7169 9.4954 17.7068 9.48951 17.6966 9.48363C17.6905 9.48006 17.6843 9.47648 17.6779 9.4728C17.6725 9.46966 17.6671 9.46653 17.6615 9.4633C17.6562 9.46034 17.6509 9.45738 17.6454 9.45433C17.6394 9.45067 17.6334 9.447 17.6272 9.44322C17.6097 9.43429 17.6097 9.43429 17.5933 9.44053ZM5.76957 9.79091C5.76101 9.79594 5.76101 9.79594 5.75227 9.80108C5.74604 9.80478 5.73982 9.80848 5.7334 9.81228C5.72006 9.82013 5.70673 9.82798 5.69339 9.83582C5.68822 9.83886 5.68822 9.83886 5.68294 9.84197C5.64661 9.86336 5.61009 9.88443 5.57355 9.90547C5.56375 9.91111 5.56375 9.91111 5.55375 9.91688C5.54047 9.92453 5.52718 9.93219 5.5139 9.93984C5.481 9.95879 5.44811 9.97777 5.41522 9.99675C5.37569 10.0196 5.33616 10.0424 5.29661 10.0651C5.23327 10.1016 5.16999 10.1382 5.10689 10.1752C5.05071 10.208 4.99426 10.2404 4.93772 10.2726C4.88242 10.3041 4.82734 10.336 4.77239 10.3682C4.70861 10.4055 4.6446 10.4423 4.58057 10.4792C4.54767 10.4982 4.51478 10.5172 4.48189 10.5361C4.44506 10.5574 4.40823 10.5786 4.37139 10.5999C4.36078 10.606 4.35017 10.6121 4.33956 10.6182C4.32636 10.6258 4.31314 10.6335 4.29993 10.6411C4.28816 10.6479 4.27643 10.6547 4.26478 10.6617C4.24553 10.6725 4.24553 10.6725 4.22641 10.6802C4.20498 10.6897 4.1897 10.6986 4.1728 10.7149C4.16188 10.749 4.16328 10.7821 4.16406 10.8176C4.16403 10.8282 4.16396 10.8389 4.16387 10.8495C4.16371 10.8787 4.164 10.9079 4.16436 10.9371C4.16468 10.9686 4.16457 11.0001 4.16452 11.0316C4.16448 11.0862 4.16471 11.1407 4.16511 11.1953C4.16571 11.2742 4.1659 11.3531 4.16599 11.432C4.16615 11.56 4.16663 11.688 4.16732 11.816C4.16799 11.9404 4.1685 12.0647 4.16881 12.1891C4.16883 12.1967 4.16885 12.2044 4.16887 12.2123C4.16896 12.2507 4.16905 12.2892 4.16914 12.3276C4.1699 12.6466 4.17118 12.9656 4.1728 13.2846C4.17756 13.2873 4.18232 13.29 4.18722 13.2928C4.20524 13.3031 4.22325 13.3134 4.24127 13.3237C4.249 13.3281 4.25673 13.3325 4.26445 13.3369C4.31511 13.3658 4.36564 13.3949 4.41598 13.4244C4.42219 13.428 4.4284 13.4316 4.4348 13.4354C4.44037 13.4386 4.44594 13.4419 4.45168 13.4453C4.50952 13.4791 4.56759 13.5124 4.62564 13.5459C4.65854 13.5648 4.69143 13.5838 4.72432 13.6028C4.73745 13.6104 4.75058 13.6179 4.76371 13.6255C5.10512 13.8225 5.44653 14.0195 5.78794 14.2164C5.79445 14.2202 5.80095 14.2239 5.80764 14.2278C5.82077 14.2354 5.83389 14.2429 5.84701 14.2505C5.87998 14.2695 5.91296 14.2885 5.94594 14.3075C6.00333 14.3406 6.0607 14.3737 6.11787 14.4071C6.14172 14.4211 6.1656 14.435 6.18949 14.4489C6.20354 14.4571 6.21758 14.4653 6.23161 14.4735C6.25109 14.4849 6.2706 14.4962 6.29014 14.5075C6.29771 14.5119 6.30527 14.5163 6.31282 14.5207C6.32335 14.5269 6.33391 14.533 6.34447 14.5391C6.35356 14.5444 6.35356 14.5444 6.36283 14.5498C6.37955 14.559 6.37955 14.559 6.40309 14.5573C6.41924 14.5495 6.43454 14.5413 6.45006 14.5323C6.45481 14.5296 6.45957 14.5269 6.46447 14.5242C6.51631 14.4947 6.56776 14.4645 6.61924 14.4343C6.65795 14.4117 6.69679 14.3892 6.73566 14.3668C6.74221 14.363 6.74875 14.3593 6.75549 14.3554C6.76877 14.3477 6.78204 14.3401 6.79532 14.3324C6.82822 14.3135 6.86111 14.2945 6.894 14.2755C6.90713 14.2679 6.92026 14.2604 6.93339 14.2528C6.94314 14.2472 6.94314 14.2472 6.95309 14.2414C8.1152 13.571 8.1152 13.571 8.1349 13.5596C8.14802 13.552 8.16114 13.5445 8.17426 13.5369C8.20724 13.5179 8.24021 13.4988 8.2732 13.4798C8.39639 13.4095 8.39639 13.4095 8.51839 13.3372C8.53641 13.327 8.53641 13.327 8.55527 13.3195C8.57678 13.3099 8.59215 13.301 8.60914 13.2846C8.62008 13.2506 8.61866 13.2174 8.61788 13.182C8.61791 13.1713 8.61798 13.1607 8.61807 13.15C8.61823 13.1208 8.61794 13.0916 8.61758 13.0624C8.61726 13.0309 8.61737 12.9994 8.61742 12.9679C8.61746 12.9134 8.61723 12.8588 8.61683 12.8042C8.61623 12.7253 8.61604 12.6464 8.61595 12.5675C8.61579 12.4395 8.61531 12.3115 8.61462 12.1835C8.61395 12.0592 8.61344 11.9348 8.61313 11.8105C8.6131 11.799 8.6131 11.799 8.61307 11.7873C8.61298 11.7488 8.61289 11.7104 8.6128 11.6719C8.61204 11.3529 8.61076 11.0339 8.60914 10.7149C8.60477 10.7124 8.60041 10.7099 8.59592 10.7073C8.42962 10.6114 8.26332 10.5154 8.09702 10.4195C8.09052 10.4157 8.08402 10.412 8.07732 10.4081C8.0642 10.4005 8.05108 10.393 8.03795 10.3854C8.00498 10.3664 7.972 10.3474 7.93902 10.3284C7.87567 10.2919 7.8124 10.2553 7.74929 10.2183C7.6967 10.1876 7.64389 10.1572 7.59096 10.1271C7.53205 10.0935 7.47333 10.0596 7.4148 10.0253C7.37083 9.99962 7.32676 9.97409 7.28263 9.94865C7.27615 9.94491 7.26968 9.94118 7.263 9.93733C7.23593 9.92173 7.20885 9.90613 7.18177 9.89054C7.16749 9.88232 7.15321 9.8741 7.13893 9.86587C7.12557 9.85818 7.11221 9.85049 7.09885 9.8428C7.06452 9.82302 7.03046 9.80291 6.99679 9.78202C6.98539 9.77458 6.98539 9.77458 6.97278 9.77554C6.97066 9.95002 6.96906 10.1245 6.96807 10.299C6.96798 10.3151 6.96789 10.3313 6.96779 10.3474C6.96777 10.3514 6.96774 10.3554 6.96772 10.3595C6.96735 10.4204 6.96671 10.4812 6.96593 10.542C6.96502 10.6127 6.96443 10.6833 6.96423 10.7539C6.96411 10.7913 6.96383 10.8287 6.96317 10.866C6.96255 10.9013 6.96236 10.9364 6.9625 10.9717C6.96248 10.9846 6.9623 10.9975 6.96195 11.0104C6.95778 11.0745 6.95778 11.0745 6.98159 11.1314C7.00304 11.1491 7.02659 11.1605 7.05229 11.1707C7.06966 11.178 7.08542 11.1878 7.1015 11.1975C7.11377 11.2046 7.12604 11.2117 7.13831 11.2187C7.15193 11.2265 7.16554 11.2344 7.17915 11.2422C7.18964 11.2483 7.20014 11.2543 7.21063 11.2603C7.23561 11.2747 7.26058 11.2891 7.28555 11.3035C7.29886 11.3111 7.31217 11.3188 7.32549 11.3264C7.33159 11.33 7.3377 11.3335 7.34399 11.3371C7.34927 11.3401 7.35456 11.3432 7.36 11.3463C7.36622 11.35 7.37243 11.3536 7.37884 11.3573C7.38374 11.359 7.38865 11.3606 7.3937 11.3623C7.41349 11.3705 7.42505 11.3777 7.43945 11.3937C7.44876 11.432 7.44711 11.4699 7.44633 11.5091C7.44631 11.5211 7.44632 11.533 7.44635 11.545C7.44637 11.5774 7.44602 11.6098 7.44559 11.6422C7.44521 11.676 7.44518 11.7099 7.44511 11.7438C7.44492 11.8079 7.44442 11.8721 7.44381 11.9362C7.44313 12.0092 7.4428 12.0822 7.4425 12.1552C7.44186 12.3054 7.4408 12.4556 7.43945 12.6058C7.43285 12.6096 7.43285 12.6096 7.42612 12.6135C7.40944 12.6231 7.39276 12.6327 7.37608 12.6424C7.36546 12.6485 7.35483 12.6546 7.34421 12.6607C7.29935 12.6866 7.25459 12.7126 7.2099 12.7388C7.15371 12.7716 7.09728 12.804 7.04073 12.8362C6.98543 12.8678 6.93035 12.8996 6.87541 12.9318C6.83144 12.9575 6.78737 12.983 6.74324 13.0085C6.73673 13.0122 6.73022 13.016 6.72352 13.0198C6.6967 13.0353 6.66989 13.0507 6.64307 13.0662C6.6293 13.0741 6.61554 13.082 6.60178 13.09C6.58841 13.0977 6.57504 13.1054 6.56166 13.113C6.53235 13.1299 6.50319 13.1469 6.4744 13.1646C6.46728 13.1689 6.46728 13.1689 6.46002 13.1734C6.45142 13.1787 6.44286 13.184 6.43436 13.1894C6.40694 13.2062 6.40694 13.2062 6.38863 13.2044C6.37133 13.1993 6.35748 13.1925 6.3418 13.1836C6.33581 13.1802 6.32982 13.1768 6.32365 13.1734C6.31724 13.1697 6.31083 13.166 6.30423 13.1623C6.29751 13.1585 6.29079 13.1546 6.28387 13.1507C6.22655 13.1182 6.1696 13.085 6.11273 13.0517C6.07451 13.0293 6.03617 13.0071 5.99779 12.985C5.99124 12.9812 5.9847 12.9774 5.97795 12.9736C5.96468 12.9659 5.95141 12.9583 5.93814 12.9506C5.90524 12.9317 5.87235 12.9127 5.83946 12.8937C5.82633 12.8861 5.8132 12.8786 5.80007 12.871C5.7738 12.8558 5.74754 12.8407 5.72128 12.8255C5.71477 12.8218 5.70827 12.818 5.70156 12.8141C5.68849 12.8066 5.67541 12.7991 5.66233 12.7915C5.62869 12.7721 5.59503 12.7527 5.56136 12.7333C5.54762 12.7254 5.53388 12.7175 5.52014 12.7096C5.51029 12.7039 5.51029 12.7039 5.50024 12.6982C5.45983 12.6749 5.41962 12.6513 5.37998 12.6266C5.36253 12.6153 5.36253 12.6153 5.34249 12.6119C5.34249 12.2079 5.34249 11.8039 5.34249 11.3877C5.35249 11.3837 5.36249 11.3797 5.3728 11.3755C5.38441 11.3693 5.39592 11.3629 5.40734 11.3563C5.41409 11.3525 5.42084 11.3486 5.42779 11.3446C5.43509 11.3404 5.44239 11.3362 5.44969 11.332C5.45727 11.3276 5.46484 11.3233 5.47242 11.3189C5.49197 11.3077 5.5115 11.2964 5.53102 11.2852C5.54904 11.2748 5.56707 11.2644 5.5851 11.2541C5.64387 11.2202 5.70257 11.1863 5.76105 11.152C5.76531 11.1496 5.76957 11.1471 5.77396 11.1445C5.79263 11.1342 5.79263 11.1342 5.80916 11.121C5.80975 11.1037 5.80994 11.0865 5.80988 11.0692C5.80989 11.0637 5.8099 11.0582 5.8099 11.0525C5.80991 11.0339 5.80988 11.0154 5.80984 10.9968C5.80984 10.9835 5.80984 10.9703 5.80985 10.957C5.80985 10.9209 5.80981 10.8848 5.80977 10.8487C5.80973 10.811 5.80973 10.7733 5.80972 10.7356C5.80971 10.6723 5.80967 10.609 5.80961 10.5457C5.80956 10.4805 5.80951 10.4153 5.80949 10.35C5.80949 10.346 5.80949 10.342 5.80948 10.3379C5.80948 10.3177 5.80947 10.2976 5.80946 10.2774C5.8094 10.1101 5.80929 9.94283 5.80916 9.77554C5.79244 9.77554 5.78396 9.78239 5.76957 9.79091ZM9.16174 14.3123C9.15569 14.3157 9.14964 14.3191 9.14341 14.3226C9.13357 14.3282 9.13357 14.3282 9.12353 14.3338C9.11672 14.3377 9.10992 14.3415 9.10292 14.3455C9.04524 14.378 8.98802 14.4113 8.93089 14.4448C8.89267 14.4672 8.85433 14.4894 8.81595 14.5115C8.80613 14.5172 8.80613 14.5172 8.79611 14.5229C8.78284 14.5306 8.76957 14.5382 8.7563 14.5459C8.7234 14.5648 8.69051 14.5838 8.65762 14.6028C8.64449 14.6104 8.63136 14.6179 8.61823 14.6255C8.61173 14.6293 8.60523 14.633 8.59853 14.6369C7.90914 15.0346 7.90914 15.0346 7.88942 15.046C7.87636 15.0535 7.8633 15.061 7.85024 15.0686C7.81991 15.0861 7.78958 15.1036 7.75925 15.1211C7.74864 15.1272 7.73803 15.1333 7.72742 15.1394C7.71421 15.147 7.701 15.1546 7.68779 15.1623C7.64533 15.1867 7.60297 15.2114 7.56066 15.2361C7.57841 15.25 7.59666 15.2616 7.6162 15.2728C7.62242 15.2763 7.62864 15.2799 7.63504 15.2836C7.64175 15.2874 7.64845 15.2913 7.65535 15.2952C7.66243 15.2993 7.6695 15.3033 7.67657 15.3074C7.69125 15.3158 7.70594 15.3242 7.72063 15.3327C7.75421 15.3519 7.78773 15.3713 7.82126 15.3907C7.83439 15.3982 7.84752 15.4058 7.86066 15.4134C8.13641 15.5725 8.13641 15.5725 8.41217 15.7316C8.41868 15.7353 8.42519 15.7391 8.4319 15.7429C8.44492 15.7505 8.45795 15.758 8.47098 15.7655C8.5017 15.7832 8.53243 15.8009 8.56316 15.8187C8.57765 15.827 8.59214 15.8354 8.60662 15.8437C8.61683 15.8496 8.62704 15.8555 8.63725 15.8614C8.64345 15.8649 8.64965 15.8685 8.65603 15.8722C8.66147 15.8753 8.66691 15.8785 8.67252 15.8817C8.68319 15.8879 8.69374 15.8943 8.70419 15.9009C8.71759 15.91 8.71759 15.91 8.73231 15.9085C8.75496 15.9005 8.77505 15.8893 8.79588 15.8774C8.80061 15.8747 8.80535 15.8721 8.81023 15.8693C8.8553 15.8438 8.89999 15.8176 8.94469 15.7914C8.99094 15.7643 9.03729 15.7375 9.08377 15.7108C9.09128 15.7065 9.09878 15.7022 9.10627 15.6979C9.11677 15.6918 9.12729 15.6858 9.1378 15.6798C9.14383 15.6763 9.14985 15.6728 9.15606 15.6693C9.17168 15.6609 9.18611 15.6534 9.20307 15.6482C9.21911 15.6554 9.23206 15.6626 9.24663 15.6721C9.25587 15.6778 9.26512 15.6835 9.27438 15.6892C9.27944 15.6924 9.28449 15.6955 9.28971 15.6988C9.31992 15.7173 9.35074 15.7348 9.38148 15.7524C9.39511 15.7602 9.40874 15.7681 9.42236 15.7759C9.42921 15.7799 9.43605 15.7838 9.4431 15.7879C9.47623 15.807 9.50935 15.8261 9.54246 15.8452C9.55559 15.8528 9.56872 15.8603 9.58186 15.8679C9.66064 15.9134 9.73943 15.9588 9.81822 16.0043C9.82472 16.008 9.83122 16.0118 9.83792 16.0157C9.85104 16.0232 9.86416 16.0308 9.87728 16.0384C9.91025 16.0574 9.94323 16.0764 9.97622 16.0954C9.98287 16.0992 9.98953 16.1031 9.99639 16.107C10.0087 16.1141 10.0209 16.1212 10.0332 16.1282C10.0452 16.1352 10.0571 16.1424 10.0689 16.1498C10.0884 16.1614 10.1077 16.168 10.1293 16.1748C10.1737 16.1911 10.2106 16.2098 10.2394 16.2482C10.2704 16.324 10.2601 16.42 10.259 16.5C10.2586 16.5337 10.2589 16.5673 10.2592 16.601C10.2594 16.6575 10.2591 16.7139 10.2584 16.7704C10.2576 16.8356 10.2579 16.9007 10.2587 16.9658C10.2593 17.0219 10.2594 17.078 10.259 17.1341C10.2588 17.1676 10.2588 17.201 10.2593 17.2344C10.2618 17.4366 10.2618 17.4366 10.2249 17.4857C10.1908 17.5155 10.1536 17.5321 10.1108 17.5456C10.0885 17.5531 10.0707 17.5637 10.0508 17.5762C10.0392 17.5829 10.0276 17.5896 10.0159 17.5963C10.0027 17.604 9.98946 17.6116 9.97622 17.6192C9.96964 17.623 9.96307 17.6268 9.95629 17.6307C9.92339 17.6496 9.8905 17.6686 9.85761 17.6876C9.84448 17.6952 9.83135 17.7028 9.81822 17.7103C9.80847 17.716 9.80847 17.716 9.79852 17.7217C9.58186 17.8467 9.58186 17.8467 9.56215 17.8581C9.54906 17.8656 9.53597 17.8732 9.52289 17.8807C9.48939 17.9001 9.45588 17.9194 9.42236 17.9387C9.41557 17.9426 9.40878 17.9465 9.40178 17.9505C9.38841 17.9582 9.37502 17.9659 9.36162 17.9736C9.33232 17.9904 9.30321 18.0074 9.27459 18.0254C9.26751 18.0298 9.26751 18.0298 9.26029 18.0342C9.25175 18.0396 9.24327 18.045 9.23488 18.0505C9.21752 18.0613 9.20676 18.0669 9.18621 18.0642C9.15729 18.0495 9.1294 18.0334 9.10156 18.0168C9.08844 18.009 9.07533 18.0013 9.06221 17.9936C9.05545 17.9896 9.04868 17.9856 9.04171 17.9815C9.009 17.9622 8.97612 17.9433 8.94322 17.9243C8.92998 17.9167 8.91674 17.9091 8.9035 17.9015C8.89692 17.8977 8.89035 17.8939 8.88357 17.89C8.85067 17.871 8.81778 17.852 8.78489 17.8331C8.77176 17.8255 8.75863 17.8179 8.7455 17.8103C8.50914 17.674 8.50914 17.674 8.48942 17.6626C8.47635 17.6551 8.46328 17.6475 8.45021 17.64C8.41999 17.6225 8.38977 17.6051 8.35955 17.5877C8.34904 17.5816 8.33852 17.5755 8.32801 17.5694C8.31495 17.5619 8.3019 17.5544 8.28885 17.5468C8.27981 17.5416 8.27981 17.5416 8.2706 17.5363C8.26499 17.5329 8.25938 17.5295 8.25361 17.526C8.23357 17.5144 8.23357 17.5144 8.21152 17.5065C8.15503 17.4825 8.15503 17.4825 8.14371 17.4545C8.1359 17.4175 8.13791 17.3799 8.13892 17.3423C8.13894 17.3302 8.13893 17.318 8.13888 17.3059C8.13884 17.274 8.13932 17.2421 8.1399 17.2102C8.1404 17.1776 8.14042 17.1451 8.14048 17.1125C8.14068 17.0486 8.1414 16.9848 8.14247 16.9209C8.1378 16.9184 8.1378 16.9184 8.13304 16.9157C8.11876 16.9078 8.10448 16.8999 8.09021 16.892C8.08286 16.8879 8.08286 16.8879 8.07537 16.8837C8.0381 16.863 8.00117 16.8418 7.96444 16.8202C7.91086 16.7888 7.85705 16.7578 7.80308 16.727C7.74416 16.6934 7.68545 16.6595 7.62692 16.6253C7.56314 16.588 7.49912 16.5511 7.4351 16.5142C7.4022 16.4953 7.36931 16.4763 7.33642 16.4573C7.29653 16.4343 7.25664 16.4113 7.21675 16.3883C7.21001 16.3844 7.20328 16.3805 7.19635 16.3765C7.18306 16.3689 7.16977 16.3612 7.15648 16.3535C7.12593 16.3359 7.09541 16.3183 7.06499 16.3004C7.05963 16.2973 7.05426 16.2941 7.04873 16.2909C7.03877 16.2851 7.02882 16.2792 7.01889 16.2734C6.99729 16.2593 6.99729 16.2593 6.97278 16.2543C6.96945 16.493 6.96689 16.7316 6.96536 16.9703C6.96517 16.9985 6.96499 17.0267 6.96479 17.0549C6.96476 17.0605 6.96472 17.0661 6.96468 17.0719C6.96405 17.1627 6.9629 17.2535 6.96156 17.3443C6.9602 17.4376 6.95939 17.5308 6.9591 17.6241C6.9589 17.6816 6.95827 17.739 6.95709 17.7965C6.95632 17.836 6.95609 17.8755 6.95627 17.9149C6.95637 17.9377 6.95623 17.9604 6.95545 17.9832C6.94961 18.0752 6.94961 18.0752 6.98716 18.1546C7.02221 18.1819 7.0604 18.2003 7.10138 18.2169C7.12276 18.2259 7.14166 18.2368 7.16137 18.2489C7.173 18.2556 7.18463 18.2623 7.19627 18.269C7.20951 18.2767 7.22275 18.2843 7.23599 18.2919C7.24257 18.2957 7.24914 18.2995 7.25592 18.3034C7.28882 18.3224 7.32171 18.3414 7.3546 18.3603C7.36773 18.3679 7.38086 18.3755 7.39399 18.3831C7.84045 18.6406 8.28692 18.8982 8.73338 19.1558C8.73988 19.1595 8.74638 19.1633 8.75308 19.1671C8.7662 19.1747 8.77932 19.1823 8.79244 19.1899C8.82541 19.2089 8.85839 19.2279 8.89138 19.2469C8.95761 19.2851 9.02378 19.3233 9.08981 19.3618C9.09589 19.3654 9.10196 19.3689 9.10822 19.3726C9.15401 19.3993 9.15401 19.3993 9.16967 19.4103C9.18434 19.4192 9.18434 19.4192 9.20016 19.4169C9.21585 19.4116 9.22916 19.4052 9.24353 19.397C9.24897 19.3939 9.25441 19.3908 9.26001 19.3876C9.26585 19.3842 9.27168 19.3808 9.27769 19.3774C9.28693 19.3721 9.28693 19.3721 9.29635 19.3667C9.34555 19.3385 9.39452 19.3099 9.44345 19.2812C9.49042 19.2537 9.53761 19.2267 9.58489 19.1997C9.6438 19.1661 9.70252 19.1322 9.76105 19.098C9.82483 19.0607 9.88885 19.0238 9.95287 18.9869C9.98577 18.968 10.0187 18.949 10.0515 18.93C10.0647 18.9224 10.0778 18.9149 10.0909 18.9073C10.1007 18.9017 10.1007 18.9017 10.1106 18.8959C11.1152 18.3164 11.1152 18.3164 11.1349 18.305C11.1479 18.2975 11.161 18.29 11.174 18.2825C11.2047 18.2647 11.2355 18.247 11.2663 18.2293C11.2809 18.221 11.2954 18.2126 11.31 18.2042C11.3202 18.1983 11.3305 18.1925 11.3408 18.1866C11.347 18.183 11.3532 18.1794 11.3596 18.1758C11.3651 18.1726 11.3706 18.1695 11.3762 18.1663C11.3811 18.1633 11.3859 18.1603 11.3909 18.1573C11.3952 18.155 11.3994 18.1527 11.4038 18.1503C11.417 18.1395 11.417 18.1395 11.4183 18.1205C11.4183 18.1127 11.4184 18.105 11.4184 18.097C11.4185 18.0927 11.4185 18.0883 11.4186 18.0839C11.4187 18.0692 11.4187 18.0546 11.4187 18.04C11.4188 18.0294 11.4189 18.0189 11.419 18.0083C11.4192 17.9792 11.4193 17.9502 11.4193 17.9211C11.4194 17.8897 11.4196 17.8584 11.4198 17.8271C11.4203 17.7514 11.4205 17.6756 11.4207 17.5999C11.4208 17.5643 11.4209 17.5287 11.421 17.493C11.4214 17.3746 11.4217 17.2561 11.4219 17.1377C11.4219 17.1069 11.422 17.0762 11.422 17.0454C11.422 17.034 11.422 17.034 11.422 17.0223C11.4222 16.8985 11.4228 16.7746 11.4235 16.6508C11.4242 16.5237 11.4246 16.3967 11.4247 16.2696C11.4248 16.1982 11.425 16.1269 11.4255 16.0555C11.426 15.9947 11.4262 15.9339 11.426 15.8732C11.4259 15.8421 11.4259 15.8111 11.4263 15.7801C11.4267 15.7517 11.4267 15.7233 11.4264 15.6949C11.4263 15.6847 11.4264 15.6744 11.4267 15.6641C11.4292 15.6114 11.4292 15.6114 11.4063 15.5662C11.3846 15.5492 11.3608 15.5373 11.3357 15.5262C11.3185 15.5183 11.3026 15.5086 11.2865 15.4989C11.2742 15.4919 11.2619 15.4848 11.2496 15.4778C11.2359 15.4699 11.2222 15.462 11.2084 15.4541C11.2015 15.4501 11.1946 15.4461 11.1875 15.442C11.1543 15.4229 11.1211 15.4037 11.0879 15.3846C11.0748 15.377 11.0616 15.3694 11.0485 15.3619C10.7071 15.1649 10.3657 14.9679 10.0243 14.771C10.0178 14.7672 10.0113 14.7635 10.0046 14.7596C9.99146 14.752 9.97833 14.7445 9.96521 14.7369C9.93224 14.7179 9.89926 14.6988 9.86628 14.6798C9.80293 14.6433 9.73965 14.6067 9.67655 14.5698C9.6204 14.537 9.56398 14.5046 9.50745 14.4724C9.45659 14.4434 9.40589 14.4142 9.35534 14.3846C9.34639 14.3794 9.34639 14.3794 9.33726 14.374C9.2917 14.3474 9.2917 14.3474 9.27364 14.3369C9.2615 14.3298 9.24933 14.3227 9.23716 14.3157C9.23074 14.3119 9.22432 14.3082 9.2177 14.3043C9.19343 14.2917 9.18454 14.2995 9.16174 14.3123ZM14.7663 14.3134C14.76 14.317 14.7538 14.3207 14.7474 14.3244C14.7372 14.3304 14.7372 14.3304 14.7269 14.3365C14.7198 14.3406 14.7127 14.3448 14.7056 14.3489C14.6908 14.3575 14.6761 14.3662 14.6613 14.3748C14.6279 14.3944 14.5942 14.4137 14.5606 14.4331C14.5475 14.4407 14.5343 14.4482 14.5212 14.4558C14.1273 14.6831 14.1273 14.6831 14.1076 14.6944C14.0945 14.702 14.0813 14.7096 14.0682 14.7172C14.0352 14.7362 14.0023 14.7552 13.9693 14.7742C13.9059 14.8107 13.8427 14.8473 13.7796 14.8842C13.7234 14.9171 13.6669 14.9495 13.6104 14.9817C13.5551 15.0132 13.5 15.0451 13.4451 15.0772C13.3813 15.1145 13.3173 15.1514 13.2532 15.1883C13.2203 15.2072 13.1874 15.2262 13.1546 15.2452C13.1414 15.2528 13.1283 15.2604 13.1152 15.2679C13.1054 15.2736 13.1054 15.2736 13.0955 15.2793C12.8788 15.4043 12.8788 15.4043 12.8591 15.4157C12.8461 15.4232 12.833 15.4307 12.82 15.4382C12.7892 15.456 12.7584 15.4738 12.7275 15.4915C12.7129 15.4999 12.6983 15.5084 12.6837 15.5168C12.6733 15.5227 12.663 15.5287 12.6527 15.5346C12.6464 15.5382 12.6402 15.5418 12.6338 15.5455C12.6282 15.5487 12.6227 15.5518 12.6171 15.5551C12.6061 15.5616 12.5954 15.5685 12.5849 15.5755C12.5821 15.5896 12.5821 15.5896 12.5826 15.6064C12.5826 15.613 12.5826 15.6196 12.5825 15.6264C12.5826 15.6337 12.5826 15.641 12.5827 15.6485C12.5827 15.6562 12.5826 15.6639 12.5826 15.6719C12.5826 15.6933 12.5827 15.7148 12.5828 15.7363C12.5828 15.7594 12.5828 15.7825 12.5828 15.8056C12.5828 15.8457 12.5828 15.8858 12.5829 15.9258C12.5831 15.9838 12.5831 16.0417 12.5832 16.0997C12.5832 16.1937 12.5833 16.2877 12.5835 16.3817C12.5837 16.473 12.5838 16.5644 12.5839 16.6557C12.5839 16.6613 12.5839 16.667 12.5839 16.6728C12.5839 16.701 12.5839 16.7292 12.584 16.7574C12.5841 16.9917 12.5845 17.226 12.5849 17.4603C12.6028 17.4533 12.62 17.4461 12.6369 17.4368C12.643 17.4334 12.643 17.4334 12.6492 17.4299C12.6536 17.4275 12.658 17.425 12.6625 17.4225C12.6673 17.4198 12.672 17.4172 12.6769 17.4144C12.7221 17.3891 12.7668 17.3629 12.8116 17.3367C12.8591 17.3089 12.9068 17.2815 12.9546 17.2543C13.0135 17.2207 13.0722 17.1868 13.1307 17.1526C13.1945 17.1153 13.2585 17.0784 13.3225 17.0415C13.362 17.0188 13.4014 16.996 13.4408 16.9733C13.4744 16.9539 13.5081 16.9345 13.5417 16.9151C13.6274 16.8659 13.6274 16.8659 13.7125 16.8156C13.7162 16.8134 13.7199 16.8112 13.7237 16.809C13.74 16.7995 13.74 16.7995 13.7546 16.7876C13.7553 16.7708 13.7557 16.7542 13.7558 16.7374C13.7559 16.7321 13.7559 16.7269 13.756 16.7215C13.7562 16.704 13.7563 16.6865 13.7565 16.669C13.7566 16.6569 13.7567 16.6449 13.7569 16.6328C13.7572 16.6009 13.7575 16.569 13.7578 16.5372C13.7581 16.5047 13.7584 16.4722 13.7588 16.4397C13.7594 16.3759 13.76 16.312 13.7606 16.2482C13.7649 16.2458 13.7693 16.2434 13.7737 16.2409C13.79 16.2318 13.8063 16.2227 13.8225 16.2136C13.8329 16.2078 13.8434 16.202 13.8538 16.1962C13.8905 16.1756 13.9271 16.1549 13.9633 16.1335C13.9675 16.1309 13.9717 16.1284 13.9761 16.1259C13.9799 16.1236 13.9837 16.1213 13.9877 16.119C14.0218 16.0988 14.0562 16.079 14.0905 16.0592C14.0972 16.0553 14.104 16.0515 14.1109 16.0475C14.1246 16.0396 14.1384 16.0316 14.1522 16.0237C14.1853 16.0046 14.2184 15.9855 14.2515 15.9664C14.2647 15.9588 14.2778 15.9513 14.2909 15.9437C14.2974 15.9399 14.3039 15.9362 14.3106 15.9323C14.4189 15.8698 14.4189 15.8698 14.5273 15.8073C14.5338 15.8036 14.5403 15.7998 14.547 15.7959C14.56 15.7884 14.5731 15.7809 14.5862 15.7735C14.617 15.7559 14.6474 15.7381 14.6772 15.7188C14.6912 15.7098 14.7053 15.701 14.7194 15.6922C14.7293 15.6859 14.739 15.6793 14.7486 15.6727C14.7671 15.6613 14.7819 15.6531 14.803 15.6482C14.8308 15.6553 14.8522 15.6687 14.8758 15.6846C14.8838 15.6892 14.8918 15.6937 14.8999 15.6982C14.9072 15.7026 14.9146 15.707 14.922 15.7115C14.9308 15.7168 14.9397 15.722 14.9486 15.7273C14.9533 15.7301 14.9581 15.733 14.9631 15.7359C14.9933 15.7538 15.0237 15.7712 15.0542 15.7888C15.0609 15.7926 15.0676 15.7965 15.0745 15.8005C15.0882 15.8084 15.102 15.8163 15.1158 15.8243C15.1489 15.8433 15.182 15.8624 15.2151 15.8816C15.2283 15.8891 15.2414 15.8967 15.2545 15.9043C15.2808 15.9194 15.3071 15.9346 15.3333 15.9497C15.3398 15.9535 15.3463 15.9572 15.353 15.9611C15.3662 15.9687 15.3793 15.9762 15.3924 15.9838C15.4254 16.0028 15.4583 16.0219 15.4913 16.0409C15.5618 16.0815 15.6322 16.1222 15.7023 16.1633C15.7517 16.1923 15.8016 16.2201 15.8515 16.2482C15.8515 16.6502 15.8515 17.0522 15.8515 17.4664C15.7675 17.5144 15.7675 17.5144 15.6818 17.5634C15.6052 17.6075 15.5286 17.6517 15.4523 17.6963C15.3961 17.7292 15.3396 17.7616 15.2831 17.7938C15.2278 17.8253 15.1728 17.8571 15.1179 17.8892C15.0595 17.9234 15.001 17.9573 14.9424 17.9909C14.92 18.0038 14.8977 18.0168 14.8756 18.0301C14.8712 18.0328 14.8667 18.0354 14.8621 18.0382C14.8541 18.0429 14.8461 18.0478 14.8382 18.0527C14.8277 18.0588 14.8277 18.0588 14.8091 18.0664C14.7856 18.0591 14.7651 18.047 14.7438 18.0349C14.7336 18.029 14.7336 18.029 14.7232 18.023C14.7158 18.0188 14.7085 18.0146 14.7011 18.0103C14.6935 18.006 14.6859 18.0016 14.6783 17.9972C14.6297 17.9693 14.5813 17.9412 14.533 17.913C14.5271 17.9096 14.5212 17.9061 14.5151 17.9026C14.4866 17.886 14.4583 17.8692 14.4301 17.8521C14.4248 17.849 14.4195 17.8458 14.4141 17.8426C14.4042 17.8367 14.3944 17.8307 14.3847 17.8246C14.3803 17.8221 14.376 17.8195 14.3715 17.8168C14.3678 17.8145 14.364 17.8122 14.3602 17.8099C14.3439 17.8042 14.3346 17.8068 14.3182 17.8118C14.3024 17.8194 14.3024 17.8194 14.2863 17.8291C14.2801 17.8327 14.2739 17.8364 14.2675 17.8401C14.2609 17.844 14.2542 17.8479 14.2474 17.852C14.2403 17.8561 14.2333 17.8602 14.2262 17.8643C14.2116 17.8729 14.197 17.8814 14.1824 17.89C14.149 17.9096 14.1154 17.9289 14.0818 17.9482C14.0687 17.9558 14.0556 17.9634 14.0424 17.9709C13.8061 18.1073 13.8061 18.1073 13.7864 18.1187C13.7732 18.1262 13.7601 18.1338 13.747 18.1414C13.714 18.1604 13.6811 18.1794 13.6481 18.1984C13.5847 18.2349 13.5214 18.2715 13.4583 18.3084C13.3833 18.3523 13.3078 18.3954 13.2322 18.4385C13.2124 18.4498 13.1926 18.4611 13.1727 18.4725C13.1874 18.4887 13.2031 18.4985 13.2221 18.5093C13.2284 18.5129 13.2347 18.5165 13.2411 18.5202C13.2479 18.5241 13.2547 18.5279 13.2618 18.5319C13.2725 18.5381 13.2833 18.5442 13.2941 18.5504C13.3014 18.5546 13.3088 18.5588 13.3162 18.563C13.3511 18.583 13.3858 18.6033 13.4205 18.6236C13.4731 18.6543 13.5259 18.6847 13.5788 18.7149C13.6377 18.7484 13.6964 18.7823 13.755 18.8166C13.8187 18.8539 13.8828 18.8908 13.9468 18.9277C13.9797 18.9466 14.0126 18.9656 14.0455 18.9846C14.0586 18.9921 14.0717 18.9997 14.0849 19.0073C14.4788 19.2346 14.4788 19.2346 14.4985 19.2459C14.5116 19.2535 14.5246 19.261 14.5376 19.2685C14.5682 19.2862 14.5989 19.3038 14.6295 19.3215C14.6403 19.3278 14.6512 19.334 14.662 19.3403C14.6756 19.3481 14.6892 19.356 14.7028 19.3638C14.7148 19.3708 14.7269 19.3777 14.7389 19.3846C14.7485 19.3901 14.758 19.3959 14.7673 19.4018C14.7878 19.4149 14.7878 19.4149 14.8113 19.4165C14.8292 19.4113 14.8431 19.404 14.8592 19.3946C14.8654 19.3909 14.8716 19.3873 14.8779 19.3836C14.8846 19.3797 14.8913 19.3757 14.8981 19.3717C14.9051 19.3676 14.9122 19.3635 14.9192 19.3593C14.9339 19.3508 14.9485 19.3422 14.9631 19.3337C14.9965 19.3141 15.0301 19.2948 15.0636 19.2755C15.0768 19.2679 15.0899 19.2603 15.103 19.2527C15.3394 19.1164 15.3394 19.1164 15.3591 19.105C15.3722 19.0974 15.3853 19.0899 15.3985 19.0823C15.4314 19.0633 15.4644 19.0443 15.4974 19.0253C15.5607 18.9888 15.624 18.9522 15.6871 18.9152C15.7433 18.8824 15.7997 18.85 15.8563 18.8178C15.9116 18.7863 15.9667 18.7544 16.0216 18.7222C16.0854 18.6849 16.1494 18.6481 16.2134 18.6112C16.2463 18.5922 16.2792 18.5732 16.3121 18.5543C16.3252 18.5467 16.3384 18.5391 16.3515 18.5315C16.3613 18.5259 16.3613 18.5259 16.3712 18.5202C16.7454 18.3043 16.7454 18.3043 16.7652 18.2929C16.7782 18.2854 16.7912 18.2779 16.8042 18.2704C16.8351 18.2525 16.8661 18.2347 16.8971 18.2169C16.9118 18.2084 16.9265 18.1999 16.9412 18.1915C16.9517 18.1854 16.9622 18.1794 16.9727 18.1734C16.9789 18.1698 16.9852 18.1662 16.9917 18.1625C17 18.1577 17 18.1577 17.0085 18.1528C17.0207 18.1462 17.0207 18.1462 17.0273 18.1391C17.0279 18.1255 17.028 18.1119 17.028 18.0983C17.028 18.0918 17.028 18.0918 17.028 18.0852C17.028 18.0705 17.028 18.0558 17.028 18.0411C17.028 18.0305 17.028 18.0199 17.028 18.0093C17.028 17.9801 17.028 17.9509 17.028 17.9217C17.0279 17.8902 17.0279 17.8588 17.0279 17.8273C17.028 17.7728 17.0279 17.7182 17.0279 17.6637C17.0278 17.5849 17.0278 17.506 17.0278 17.4271C17.0278 17.2992 17.0278 17.1713 17.0277 17.0434C17.0277 16.9191 17.0276 16.7948 17.0276 16.6705C17.0276 16.6628 17.0276 16.6552 17.0276 16.6473C17.0276 16.6089 17.0276 16.5705 17.0276 16.532C17.0275 16.2132 17.0274 15.8943 17.0273 15.5755C17.0229 15.573 17.0185 15.5704 17.0139 15.5678C16.9973 15.5582 16.9806 15.5486 16.9639 15.539C16.9533 15.5328 16.9426 15.5267 16.932 15.5206C16.8872 15.4947 16.8424 15.4687 16.7977 15.4425C16.7451 15.4118 16.6923 15.3814 16.6394 15.3513C16.5805 15.3177 16.5218 15.2838 16.4632 15.2495C16.3994 15.2122 16.3354 15.1754 16.2714 15.1385C16.2385 15.1195 16.2056 15.1005 16.1727 15.0816C16.1596 15.074 16.1465 15.0664 16.1333 15.0588C15.7919 14.8619 15.4505 14.6649 15.1091 14.4679C15.1026 14.4642 15.0961 14.4604 15.0894 14.4566C15.0763 14.449 15.0633 14.4415 15.0503 14.434C15.0195 14.4162 14.9886 14.3984 14.9578 14.3807C14.9432 14.3723 14.9286 14.3639 14.914 14.3555C14.9036 14.3495 14.8933 14.3436 14.8829 14.3376C14.8767 14.334 14.8705 14.3304 14.864 14.3267C14.8585 14.3236 14.853 14.3204 14.8474 14.3171C14.8364 14.3107 14.8257 14.3038 14.8152 14.2967C14.7933 14.2967 14.785 14.3024 14.7663 14.3134Z" fill="currentColor"/>"## }; +static MEGANOVA: Icon = Icon { name: "meganova", view: 1000.0, body: r##"<path d="M534 154C541.732 154 548 160.268 548 168C548 170.518 547.334 172.881 546.17 174.923L602.021 240.338C603.835 239.48 605.861 239 608 239C615.732 239 622 245.268 622 253C622 254.065 621.88 255.102 621.655 256.099L706.818 300.431C709.276 298.294 712.487 297 716 297C723.732 297 730 303.268 730 311C730 311.443 729.978 311.882 729.938 312.314L863.375 379.883C865.943 376.893 869.75 375 874 375C881.732 375 888 381.268 888 389C888 391.789 887.183 394.387 885.777 396.569L946.472 464.134C948.168 463.404 950.037 463 952 463C959.732 463 966 469.268 966 477C966 484.732 959.732 491 952 491C945.627 491 940.248 486.741 938.555 480.914L856.912 472.417C854.794 477.459 849.811 481 844 481C839.112 481 834.811 478.495 832.307 474.699L729.884 506.808C728.997 513.686 723.119 519 716 519C713.249 519 710.684 518.206 708.52 516.835L621.863 571.045C621.953 571.684 622 572.336 622 573C622 580.732 615.732 587 608 587C606.913 587 605.854 586.876 604.838 586.642L545.427 672.909C547.047 675.194 548 677.986 548 681C548 685.573 545.806 689.633 542.415 692.188L562.436 761.104C567.278 761.8 571 765.965 571 771C571 772.011 570.848 772.986 570.569 773.906L603.281 804.182C604.687 803.428 606.293 803 608 803C611.041 803 613.763 804.359 615.597 806.5L702.076 770.468C702.026 769.985 702 769.496 702 769C702 761.268 708.268 755 716 755C723.732 755 730 761.268 730 769C730 776.732 723.732 783 716 783C712.501 783 709.301 781.716 706.847 779.594L617.979 836.371C617.991 836.579 618 836.789 618 837C618 842.523 613.523 847 608 847C602.477 847 598 842.523 598 837C598 836.723 598.014 836.449 598.036 836.178L513.258 779.798C511.544 781.175 509.369 782 507 782C501.477 782 497 777.523 497 772C497 769.373 498.014 766.983 499.671 765.198L467.477 694.922C466.991 694.973 466.499 695 466 695C458.268 695 452 688.732 452 681C452 677.846 453.043 674.935 454.803 672.595L395.197 586.633C394.17 586.873 393.1 587 392 587C384.268 587 378 580.732 378 573C378 572.271 378.055 571.555 378.162 570.856L292.756 515.923C290.358 517.847 287.314 519 284 519C276.58 519 270.509 513.228 270.031 505.929L167.816 474.509C165.332 478.411 160.969 481 156 481C150.213 481 145.246 477.489 143.113 472.48L61.3994 481.062C59.6582 486.813 54.319 491 48 491C40.268 491 34 484.732 34 477C34 469.268 40.268 463 48 463C50.289 463 52.4497 463.549 54.3574 464.523L113.915 396.071C112.698 393.996 112 391.58 112 389C112 381.268 118.268 375 126 375C130.139 375 133.858 376.796 136.421 379.651L270.236 313.574C270.081 312.74 270 311.879 270 311C270 303.268 276.268 297 284 297C287.987 297 291.584 298.667 294.134 301.341L378.38 256.251C378.132 255.208 378 254.119 378 253C378 245.268 384.268 239 392 239C394.155 239 396.197 239.487 398.021 240.357L454.009 175.23C452.734 173.12 452 170.646 452 168C452 160.268 458.268 154 466 154C473.732 154 480 160.268 480 168C480 175.732 473.732 182 466 182C465.903 182 465.806 181.997 465.71 181.995L456.335 215.262C458.572 217.096 460 219.881 460 223C460 223.476 459.964 223.943 459.899 224.401L490.157 243.044C492.686 240.544 496.163 239 500 239C503.689 239 507.043 240.427 509.544 242.759L540.088 224.312C540.032 223.882 540 223.445 540 223C540 219.852 541.455 217.045 543.729 215.212L534.666 181.983C534.445 181.994 534.223 182 534 182C526.268 182 520 175.732 520 168C520 160.268 526.268 154 534 154ZM601.857 829.11C603.553 827.789 605.684 827 608 827C610.386 827 612.575 827.836 614.294 829.23L675.14 790.358L617.926 814.197C617.334 819.155 613.118 823 608 823C602.477 823 598 818.523 598 813C598 812.133 598.11 811.291 598.317 810.488L565.37 779.995C564.05 780.638 562.567 781 561 781C556.709 781 553.05 778.296 551.631 774.5H519.738L601.857 829.11ZM534.745 694.979L512.811 763.863C513.81 764.579 514.673 765.473 515.351 766.5H552.07C552.714 765.226 553.62 764.108 554.72 763.219L534.893 694.97C534.843 694.973 534.794 694.977 534.745 694.979ZM479.419 685C478.611 687.716 477.001 690.086 474.863 691.836L505.827 759.428L526.949 693.097C523.912 691.323 521.604 688.438 520.581 685H479.419ZM472.819 668.771C475.97 670.531 478.37 673.475 479.419 677H520.581C521.664 673.363 524.184 670.345 527.483 668.606L499.583 566.045L472.819 668.771ZM506.869 556.264C506.448 556.662 505.992 557.025 505.507 557.346L535.354 667.064C536.67 667.191 537.934 667.499 539.119 667.965L597.867 582.66C596.132 580.841 594.883 578.555 594.325 576.011L506.869 556.264ZM405.68 575.984C405.128 578.527 403.885 580.811 402.158 582.632L461.236 667.831C462.425 667.401 463.689 667.128 465.003 667.035L493.727 556.786C493.457 556.568 493.198 556.338 492.952 556.094L405.68 575.984ZM508.761 544.178C509.515 545.545 509.956 547.106 509.994 548.769L594.938 567.95C595.639 566.14 596.705 564.512 598.046 563.156L557.757 476.993C557.023 476.976 556.309 476.88 555.622 476.713L508.761 544.178ZM445.066 476.519C444.466 476.712 443.841 476.849 443.197 476.926L402.037 563.241C403.332 564.573 404.364 566.161 405.05 567.922L490.011 548.559C490.068 547.243 490.38 545.994 490.898 544.857L445.066 476.519ZM565.856 473.183C565.642 473.455 565.413 473.716 565.172 473.965L605.076 559.306C606.019 559.105 606.997 559 608 559C612.173 559 615.919 560.826 618.483 563.723L703.216 510.716C702.671 509.5 702.295 508.192 702.117 506.822L565.856 473.183ZM297.766 507.556C297.653 508.166 297.501 508.762 297.312 509.342L381.642 563.581C384.202 560.766 387.895 559 392 559C393.044 559 394.061 559.114 395.039 559.331L435.461 474.562C435.054 474.21 434.675 473.828 434.329 473.415L297.766 507.556ZM451.235 463.162C451.727 464.344 452 465.64 452 467C452 468.48 451.675 469.884 451.098 471.148L496.927 539.482C497.895 539.17 498.928 539 500 539C500.832 539 501.64 539.103 502.412 539.294L549.257 471.854C548.457 470.416 548 468.762 548 467C548 465.371 548.392 463.834 549.083 462.475L501.213 398.924C500.815 398.972 500.411 399 500 399C499.329 399 498.673 398.933 498.039 398.807L451.235 463.162ZM346.938 397.694C345.907 398.281 344.763 398.691 343.546 398.88L295.016 496.359C295.772 497.322 296.404 498.386 296.89 499.528L432.083 465.729C432.175 465.006 432.341 464.306 432.579 463.639L346.938 397.694ZM567.637 464.329C567.737 464.692 567.819 465.062 567.878 465.44L703.396 498.896C704.247 497.143 705.453 495.595 706.92 494.344L659.017 398.948C658.682 398.982 658.343 399 658 399C656.789 399 655.629 398.785 654.555 398.391L567.637 464.329ZM773.415 398.4C772.743 398.645 772.037 398.816 771.307 398.911L726.722 495.999C727.447 496.862 728.07 497.814 728.572 498.836L830 467.039C830 467.026 830 467.013 830 467C830 464.574 830.617 462.293 831.702 460.304L773.415 398.4ZM168.537 460.766C169.446 462.59 169.968 464.64 169.997 466.811L271.812 498.106C272.696 496.546 273.872 495.173 275.265 494.06L230.778 398.967C230.521 398.987 230.262 399 230 399C229.342 399 228.699 398.934 228.076 398.812L168.537 460.766ZM667.337 385.418C667.764 386.53 668 387.737 668 389C668 391.257 667.252 393.338 665.991 395.012L713.5 489.621V324.776C713.053 324.696 712.614 324.594 712.184 324.473L667.337 385.418ZM290.106 323.6C289.907 323.697 289.705 323.789 289.5 323.877V489.49L335.673 396.743C333.431 394.909 332 392.122 332 389C332 386.919 332.636 384.987 333.724 383.387L290.106 323.6ZM239.209 385.098C239.718 386.297 240 387.615 240 389C240 391.341 239.194 393.492 237.847 395.195L281.5 488.509V324.776C281.224 324.727 280.951 324.668 280.681 324.603L239.209 385.098ZM721.5 323.877V488.205L763.549 396.639C761.379 394.804 760 392.064 760 389C760 386.918 760.637 384.985 761.726 383.384L721.64 323.815C721.593 323.836 721.547 323.857 721.5 323.877ZM60.1543 470.048C60.6859 470.975 61.113 471.97 61.4229 473.015L142.217 464.529C142.869 460.867 144.945 457.698 147.852 455.614L125.642 402.995C123.533 402.942 121.541 402.422 119.764 401.536L60.1543 470.048ZM879.71 401.785C877.966 402.565 876.034 403 874 403C873.859 403 873.72 402.996 873.58 402.992L852.339 455.754C855.128 457.825 857.119 460.91 857.77 464.463L938.617 472.877C939.015 471.584 939.595 470.37 940.328 469.267L879.71 401.785ZM508.659 394C508.497 394.28 508.321 394.551 508.133 394.813L555.263 457.382C556.133 457.135 557.051 457 558 457C559.655 457 561.215 457.404 562.59 458.116L647.109 394H508.659ZM438.096 457.791C439.295 457.282 440.615 457 442 457C443.192 457 444.335 457.209 445.396 457.592L491.476 394.23C491.429 394.155 491.385 394.077 491.341 394H355.251L438.096 457.791ZM139.08 394C137.987 396.857 135.986 399.263 133.429 400.867L155.438 453.012C155.624 453.004 155.812 453 156 453C158.578 453 160.993 453.698 163.067 454.913L221.44 394.174C221.406 394.117 221.374 394.058 221.341 394H139.08ZM837.377 454.662C839.349 453.601 841.604 453 844 453C844.273 453 844.544 453.008 844.812 453.023L865.972 400.47C863.702 398.878 861.926 396.63 860.92 394H780.261L837.377 454.662ZM561.53 324.356C560.432 324.771 559.243 325 558 325C557.329 325 556.673 324.933 556.039 324.807L508.931 384.504C509.172 384.982 509.379 385.481 509.542 386H646.656L561.53 324.356ZM768.495 379.112C768.986 379.038 769.489 379 770 379C774.478 379 778.268 381.943 779.542 386H857.747L729.39 321.004L768.495 379.112ZM355.696 386H490.458C490.55 385.708 490.655 385.423 490.771 385.144L444.67 324.637C443.82 324.872 442.925 325 442 325C441.036 325 440.105 324.861 439.223 324.606L355.696 386ZM141.636 386H220.458C221.732 381.943 225.522 379 230 379C231.159 379 232.271 379.199 233.306 379.562L273.545 320.864L141.636 386ZM617.724 263.07C617.275 263.503 616.799 263.906 616.296 264.276L659.187 379.072C660.037 379.173 660.854 379.38 661.625 379.68L705.419 320.167C703.289 317.711 702 314.506 702 311C702 309.687 702.18 308.415 702.519 307.21L617.724 263.07ZM451.826 313.151C451.938 313.751 452 314.368 452 315C452 316.655 451.595 318.215 450.883 319.59L496.599 379.593C497.66 379.209 498.806 379 500 379C500.963 379 501.893 379.139 502.773 379.393L549.469 320.219C548.537 318.699 548 316.913 548 315C548 314.117 548.115 313.26 548.33 312.444L505.47 265.89C503.789 266.604 501.941 267 500 267C497.866 267 495.844 266.521 494.034 265.667L451.826 313.151ZM297.771 308.468C297.921 309.289 298 310.135 298 311C298 313.614 297.283 316.06 296.035 318.154L340.507 379.111C340.994 379.038 341.493 379 342 379C342.385 379 342.765 379.024 343.139 379.066L383.879 264.404C383.354 264.03 382.857 263.62 382.39 263.179L297.771 308.468ZM397.089 266.046C395.512 266.662 393.795 267 392 267C391.816 267 391.634 266.994 391.452 266.987L351.633 379.058L432.961 319.28C432.345 317.983 432 316.532 432 315C432 313.273 432.437 311.648 433.208 310.23L397.089 266.046ZM567.117 310.896C567.682 312.148 568 313.537 568 315C568 316.293 567.751 317.527 567.305 318.661L650.615 378.989L608.765 266.979C608.511 266.992 608.257 267 608 267C606.25 267 604.576 266.678 603.031 266.092L567.117 310.896ZM405.818 250.75C405.937 251.483 406 252.234 406 253C406 256.03 405.037 258.836 403.4 261.127L439.519 305.31C440.312 305.107 441.143 305 442 305C443.87 305 445.62 305.515 447.117 306.408L488.073 260.334C486.759 258.201 486 255.689 486 253C486 251.995 486.106 251.014 486.308 250.069L455.703 231.212C454.085 232.338 452.12 233 450 233C447.634 233 445.462 232.177 443.75 230.804L405.818 250.75ZM556.249 230.805C554.537 232.177 552.365 233 550 233C547.847 233 545.855 232.317 544.224 231.16L513.598 249.657C513.86 250.728 514 251.848 514 253C514 255.88 513.129 258.556 511.639 260.781L553.387 306.128C554.767 305.409 556.336 305 558 305C559.11 305 560.177 305.183 561.175 305.517L596.675 261.23C594.993 258.92 594 256.076 594 253C594 252.234 594.061 251.483 594.18 250.751L556.249 230.805ZM551.447 213.105C556.284 213.807 560 217.969 560 223C560 223.243 559.988 223.485 559.971 223.724L591.452 240.279L543.561 184.188L551.447 213.105ZM408.715 240.19L440.028 223.724C440.011 223.485 440 223.243 440 223C440 217.94 443.758 213.761 448.635 213.095L456.745 184.319L408.715 240.19Z" fill="currentColor"/>"## }; +static MEITUAN: Icon = Icon { name: "meituan", view: 36.0, body: r##"<path d="M1.6654 29.9998C1.1899 29.9998 0.8449 29.5469 0.9713 29.0884L7.0438 7.0649C7.3033 6.1234 8.4049 5.7079 9.2216 6.2434L17.2117 11.4829C17.6905 11.7968 18.3098 11.7973 18.7891 11.4841L26.8132 6.2406C27.6306 5.7064 28.7313 6.1234 28.9896 7.0651L35.0303 29.0893C35.156 29.5476 34.8111 29.9998 34.3359 29.9998L26.6236 29.9998C28.0276 28.3742 28.8 26.2979 28.8 24.15L28.8 23.8993C28.8 21.7983 28.0358 19.7691 26.6498 18.19L25.66 13.2219C25.6019 12.93 25.3457 12.7198 25.0481 12.7198C24.913 12.7198 24.7816 12.7636 24.6736 12.8446L20.9419 15.6434C20.6761 15.8427 20.3324 15.9062 20.013 15.8149C18.6973 15.439 17.3027 15.439 15.9871 15.8149C15.6676 15.9062 15.3239 15.8427 15.0582 15.6434L11.3248 12.8434C11.2179 12.7631 11.0878 12.7198 10.9541 12.7198C10.6562 12.7198 10.4007 12.9323 10.3465 13.2252L9.3863 18.4166C7.9852 19.8413 7.2001 21.7596 7.2001 23.7578L7.2001 24.2327C7.2001 26.328 7.9496 28.3543 9.3132 29.9452L9.3601 29.9998L1.6654 29.9998Z" fill="currentColor" fill-rule="evenodd"/><path d="M14.04 25.68L16.2 25.68L16.2 20.64L14.3673 20.64L14.04 25.68ZM21.96 25.68L19.8 25.68L19.8 20.64L21.6327 20.64L21.96 25.68Z" fill="currentColor"/>"## }; +static META: Icon = Icon { name: "meta", view: 40.0, body: r##"<path d="M27.1942 9.03509C24.4881 9.03509 22.3726 11.0731 20.4574 13.6623C17.8258 10.3114 15.6255 9.03509 12.9925 9.03509C7.62404 9.03509 3.51001 16.0234 3.51001 23.4181C3.51001 28.0453 5.74831 30.9649 9.49831 30.9649C12.1971 30.9649 14.1387 29.693 17.5904 23.6594C17.5904 23.6594 19.029 21.1199 20.0173 19.3699C20.3643 19.9293 20.7298 20.5327 21.1138 21.1798L22.7322 23.902C25.8843 29.1769 27.6416 30.9649 30.8229 30.9649C34.4778 30.9649 36.51 28.0058 36.51 23.2822C36.51 15.538 32.3039 9.03509 27.1942 9.03509ZM14.9574 22.0263C12.1606 26.4123 11.1928 27.3962 9.63574 27.3962C8.03194 27.3962 7.07872 25.9883 7.07872 23.4781C7.07872 18.1096 9.75562 12.6199 12.9471 12.6199C14.6752 12.6199 16.1197 13.617 18.3316 16.7836C16.2308 20.0058 14.9574 22.0263 14.9574 22.0263ZM25.5202 21.4751L23.5831 18.2456C23.0969 17.4514 22.5938 16.6676 22.0743 15.8947C23.8185 13.2032 25.2556 11.8611 26.9676 11.8611C30.5202 11.8611 33.3638 17.095 33.3638 23.5219C33.3638 25.9722 32.5612 27.3947 30.8989 27.3947C29.3053 27.3947 28.5451 26.3421 25.5188 21.4737" fill="currentColor"/>"## }; +static MINIMAX: Icon = Icon { name: "minimax", view: 40.0, body: r##"<path d="M17.8758 9.20865C17.8758 8.59461 17.3777 8.09634 16.7663 8.09634C16.155 8.09634 15.6567 8.59575 15.6567 9.20865V27.6446C15.6567 29.0714 14.4985 30.2324 13.0755 30.2324C11.6523 30.2324 10.4941 29.0714 10.4941 27.6446V15.8167C10.4941 15.2027 9.99591 14.7044 9.38453 14.7044C8.77316 14.7044 8.275 15.2038 8.275 15.8167V20.8301C8.275 22.2567 7.11678 23.4179 5.69364 23.4179C4.2705 23.4179 3.1123 22.2567 3.1123 20.8301V19.0129C3.1123 18.6054 3.44177 18.2752 3.84822 18.2752C4.25467 18.2752 4.58413 18.6054 4.58413 19.0129V20.8301C4.58413 21.4441 5.08227 21.9424 5.69364 21.9424C6.30502 21.9424 6.80317 21.443 6.80317 20.8301V15.8167C6.80317 14.39 7.96139 13.2289 9.38453 13.2289C10.8077 13.2289 11.9659 14.39 11.9659 15.8167V27.6446C11.9659 28.2587 12.4641 28.7569 13.0755 28.7569C13.6868 28.7569 14.1849 28.2575 14.1849 27.6446V20.4123V9.20865C14.1849 7.78194 15.3431 6.62082 16.7663 6.62082C18.1894 6.62082 19.3476 7.78194 19.3476 9.20865V24.4746C19.3476 24.8821 19.0182 25.2123 18.6117 25.2123C18.2053 25.2123 17.8758 24.8821 17.8758 24.4746V9.20865ZM31.531 13.2289C30.1079 13.2289 28.9496 14.39 28.9496 15.8167V25.6969C28.9496 26.311 28.4515 26.8093 27.8401 26.8093C27.2287 26.8093 26.7306 26.3099 26.7306 25.6969V9.20865C26.7306 7.78194 25.5723 6.62082 24.1492 6.62082C22.7261 6.62082 21.5679 7.78194 21.5679 9.20865V30.1383C21.5679 30.7523 21.0697 31.2506 20.4583 31.2506C19.8469 31.2506 19.3488 30.7511 19.3488 30.1383V27.5471C19.3488 27.1396 19.0194 26.8093 18.6129 26.8093C18.2065 26.8093 17.877 27.1396 17.877 27.5471V30.1383C17.877 31.565 19.0352 32.7261 20.4583 32.7261C21.8815 32.7261 23.0397 31.565 23.0397 30.1383V9.20865C23.0397 8.59461 23.5378 8.09634 24.1492 8.09634C24.7605 8.09634 25.2587 8.59575 25.2587 9.20865V25.6969C25.2587 27.1237 26.417 28.2848 27.8401 28.2848C29.2632 28.2848 30.4215 27.1237 30.4215 25.6969V15.8167C30.4215 15.2027 30.9196 14.7044 31.531 14.7044C32.1424 14.7044 32.6405 15.2038 32.6405 15.8167V24.4746C32.6405 24.8821 32.97 25.2123 33.3764 25.2123C33.7829 25.2123 34.1123 24.8821 34.1123 24.4746V15.8167C34.1123 14.39 32.9541 13.2289 31.531 13.2289Z" fill="currentColor"/>"## }; +static MINIMAX_CN: Icon = Icon { name: "minimax-cn", view: 40.0, body: r##"<path d="M17.8758 9.20865C17.8758 8.59461 17.3777 8.09634 16.7663 8.09634C16.155 8.09634 15.6567 8.59575 15.6567 9.20865V27.6446C15.6567 29.0714 14.4985 30.2324 13.0755 30.2324C11.6523 30.2324 10.4941 29.0714 10.4941 27.6446V15.8167C10.4941 15.2027 9.99591 14.7044 9.38453 14.7044C8.77316 14.7044 8.275 15.2038 8.275 15.8167V20.8301C8.275 22.2567 7.11678 23.4179 5.69364 23.4179C4.2705 23.4179 3.1123 22.2567 3.1123 20.8301V19.0129C3.1123 18.6054 3.44177 18.2752 3.84822 18.2752C4.25467 18.2752 4.58413 18.6054 4.58413 19.0129V20.8301C4.58413 21.4441 5.08227 21.9424 5.69364 21.9424C6.30502 21.9424 6.80317 21.443 6.80317 20.8301V15.8167C6.80317 14.39 7.96139 13.2289 9.38453 13.2289C10.8077 13.2289 11.9659 14.39 11.9659 15.8167V27.6446C11.9659 28.2587 12.4641 28.7569 13.0755 28.7569C13.6868 28.7569 14.1849 28.2575 14.1849 27.6446V20.4123V9.20865C14.1849 7.78194 15.3431 6.62082 16.7663 6.62082C18.1894 6.62082 19.3476 7.78194 19.3476 9.20865V24.4746C19.3476 24.8821 19.0182 25.2123 18.6117 25.2123C18.2053 25.2123 17.8758 24.8821 17.8758 24.4746V9.20865ZM31.531 13.2289C30.1079 13.2289 28.9496 14.39 28.9496 15.8167V25.6969C28.9496 26.311 28.4515 26.8093 27.8401 26.8093C27.2287 26.8093 26.7306 26.3099 26.7306 25.6969V9.20865C26.7306 7.78194 25.5723 6.62082 24.1492 6.62082C22.7261 6.62082 21.5679 7.78194 21.5679 9.20865V30.1383C21.5679 30.7523 21.0697 31.2506 20.4583 31.2506C19.8469 31.2506 19.3488 30.7511 19.3488 30.1383V27.5471C19.3488 27.1396 19.0194 26.8093 18.6129 26.8093C18.2065 26.8093 17.877 27.1396 17.877 27.5471V30.1383C17.877 31.565 19.0352 32.7261 20.4583 32.7261C21.8815 32.7261 23.0397 31.565 23.0397 30.1383V9.20865C23.0397 8.59461 23.5378 8.09634 24.1492 8.09634C24.7605 8.09634 25.2587 8.59575 25.2587 9.20865V25.6969C25.2587 27.1237 26.417 28.2848 27.8401 28.2848C29.2632 28.2848 30.4215 27.1237 30.4215 25.6969V15.8167C30.4215 15.2027 30.9196 14.7044 31.531 14.7044C32.1424 14.7044 32.6405 15.2038 32.6405 15.8167V24.4746C32.6405 24.8821 32.97 25.2123 33.3764 25.2123C33.7829 25.2123 34.1123 24.8821 34.1123 24.4746V15.8167C34.1123 14.39 32.9541 13.2289 31.531 13.2289Z" fill="currentColor"/>"## }; +static MINIMAX_CN_CODING_PLAN: Icon = Icon { name: "minimax-cn-coding-plan", view: 24.0, body: r##"<path d="M9.8132 15.9038L9 18.75L8.1868 15.9038C7.75968 14.4089 6.59112 13.2403 5.09619 12.8132L2.25 12L5.09619 11.1868C6.59113 10.7597 7.75968 9.59112 8.1868 8.09619L9 5.25L9.8132 8.09619C10.2403 9.59113 11.4089 10.7597 12.9038 11.1868L15.75 12L12.9038 12.8132C11.4089 13.2403 10.2403 14.4089 9.8132 15.9038Z" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/><path d="M18.2589 8.71454L18 9.75L17.7411 8.71454C17.4388 7.50533 16.4947 6.56117 15.2855 6.25887L14.25 6L15.2855 5.74113C16.4947 5.43883 17.4388 4.49467 17.7411 3.28546L18 2.25L18.2589 3.28546C18.5612 4.49467 19.5053 5.43883 20.7145 5.74113L21.75 6L20.7145 6.25887C19.5053 6.56117 18.5612 7.50533 18.2589 8.71454Z" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/><path d="M16.8942 20.5673L16.5 21.75L16.1058 20.5673C15.8818 19.8954 15.3546 19.3682 14.6827 19.1442L13.5 18.75L14.6827 18.3558C15.3546 18.1318 15.8818 17.6046 16.1058 16.9327L16.5 15.75L16.8942 16.9327C17.1182 17.6046 17.6454 18.1318 18.3173 18.3558L19.5 18.75L18.3173 19.1442C17.6454 19.3682 17.1182 19.8954 16.8942 20.5673Z" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>"## }; +static MINIMAX_CODING_PLAN: Icon = Icon { name: "minimax-coding-plan", view: 24.0, body: r##"<path d="M9.8132 15.9038L9 18.75L8.1868 15.9038C7.75968 14.4089 6.59112 13.2403 5.09619 12.8132L2.25 12L5.09619 11.1868C6.59113 10.7597 7.75968 9.59112 8.1868 8.09619L9 5.25L9.8132 8.09619C10.2403 9.59113 11.4089 10.7597 12.9038 11.1868L15.75 12L12.9038 12.8132C11.4089 13.2403 10.2403 14.4089 9.8132 15.9038Z" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/><path d="M18.2589 8.71454L18 9.75L17.7411 8.71454C17.4388 7.50533 16.4947 6.56117 15.2855 6.25887L14.25 6L15.2855 5.74113C16.4947 5.43883 17.4388 4.49467 17.7411 3.28546L18 2.25L18.2589 3.28546C18.5612 4.49467 19.5053 5.43883 20.7145 5.74113L21.75 6L20.7145 6.25887C19.5053 6.56117 18.5612 7.50533 18.2589 8.71454Z" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/><path d="M16.8942 20.5673L16.5 21.75L16.1058 20.5673C15.8818 19.8954 15.3546 19.3682 14.6827 19.1442L13.5 18.75L14.6827 18.3558C15.3546 18.1318 15.8818 17.6046 16.1058 16.9327L16.5 15.75L16.8942 16.9327C17.1182 17.6046 17.6454 18.1318 18.3173 18.3558L19.5 18.75L18.3173 19.1442C17.6454 19.3682 17.1182 19.8954 16.8942 20.5673Z" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>"## }; +static MISTRAL: Icon = Icon { name: "mistral", view: 40.0, body: r##"<path d="M8.92783 8.88101H13.357V13.3088H17.7861V17.738H17.7835H22.2152V13.3088H26.6418V8.88101H31.0722V26.5949H35.5V31.0241H22.2139V26.5962H17.7861V22.1671H13.3557V26.5949L17.7861 26.5962V31.0241H4.5V26.5949H8.92783V8.88101ZM22.2139 26.5962H26.6418V22.1671H22.2152V26.5962H22.2139Z" fill="currentColor"/>"## }; +static MOARK: Icon = Icon { name: "moark", view: 40.0, body: r##"<path d="M25.132 24.3947C25.497 25.7527 25.8984 27.1413 26.3334 28.5834C26.7302 29.8992 25.5459 30.4167 25.0752 29.1758C24.571 27.8466 24.0885 26.523 23.6347 25.1729C21.065 26.4654 18.5025 27.5424 15.5961 28.7541C16.7581 33.0256 17.8309 36.5984 19.4952 39.9935C19.4953 39.9936 19.4953 39.9937 19.4954 39.9938C19.6631 39.9979 19.8313 40 20 40C31.0457 40 40 31.0457 40 20C40 16.0335 38.8453 12.3366 36.8537 9.22729C31.6585 9.69534 27.0513 10.4562 22.8185 11.406C22.8882 12.252 22.9677 13.0739 23.0555 13.855C23.3824 16.7604 23.9112 19.5281 24.6137 22.3836C27.0581 21.2848 29.084 20.3225 30.6816 19.522C32.2154 18.7535 33.6943 18.7062 31.2018 20.6594C29.0388 22.1602 27.0644 23.3566 25.132 24.3947ZM36.1559 8.20846C33.0001 3.89184 28.1561 0.887462 22.5955 0.166882C22.4257 2.86234 22.4785 6.26344 22.681 9.50447C26.7473 8.88859 31.1721 8.46032 36.1559 8.20846ZM19.9369 9.73661e-05C19.7594 2.92694 19.8384 6.65663 20.19 9.91293C17.3748 10.4109 14.7225 11.0064 12.1592 11.7038C12.0486 10.4257 11.9927 9.25764 11.9927 8.24178C11.9927 7.5054 11.3957 6.90844 10.6593 6.90844C9.92296 6.90844 9.32601 7.5054 9.32601 8.24178C9.32601 9.47868 9.42873 10.898 9.61402 12.438C8.33567 12.8278 7.07397 13.2443 5.81918 13.688C5.12493 13.9336 4.76118 14.6954 5.0067 15.3896C5.25223 16.0839 6.01406 16.4476 6.7083 16.2021C7.7931 15.8185 8.88482 15.4388 9.98927 15.0659C10.5222 18.3344 11.3344 21.9428 12.2703 25.4156C12.4336 26.0218 12.6062 26.6262 12.7863 27.2263C9.34168 28.4135 5.82612 29.3782 2.61128 29.8879C0.949407 26.9716 0 23.5967 0 20C0 8.97534 8.92023 0.0341108 19.9369 9.73661e-05ZM4.19152 32.2527C7.45069 36.4516 12.3458 39.3173 17.9204 39.8932C16.5916 37.455 14.9338 33.717 13.5405 29.5901C10.4404 30.7762 7.25883 31.6027 4.19152 32.2527ZM22.9735 23.1135C22.1479 20.41 21.4462 17.5441 20.9225 14.277C20.746 13.5841 20.5918 12.8035 20.4593 11.9636C17.6508 12.6606 14.9992 13.4372 12.4356 14.2598C12.8479 17.4766 13.5448 21.1334 14.5118 24.7218C14.662 25.2792 14.8081 25.8248 14.9514 26.3594L14.9516 26.3603L14.9524 26.3634L14.9526 26.3639L14.973 26.4401C16.1833 25.9872 17.3746 25.5123 18.53 25.0259C20.1235 24.3552 21.6051 23.7165 22.9735 23.1135Z" fill="currentColor" fill-rule="evenodd"/>"## }; +static MODELSCOPE: Icon = Icon { name: "modelscope", view: 40.0, body: r##"<path d="M6.77825 10.4999H14.3333V14.2782H10.5551V18.055H6.77825V14.9865H3.70833V18.055H6.77825V21.8333H3V14.2782H6.77825V10.4999ZM6.77825 21.8333H10.5551V25.6115H14.3333V29.3884H6.77825V21.8333ZM14.3333 18.055H18.1116V21.8333H14.3333V18.055ZM21.8884 21.8333V25.6115H18.1116V21.8333H21.8884ZM21.8884 21.8333V18.055H25.6667V21.8333H21.8884Z" fill="currentColor"/><path d="M33.2218 21.8333V18.055H29.445V14.2782H25.6667V10.4999H33.2218V14.2782H37.0001V21.8333H33.2218ZM33.2218 18.055H36.2918V14.9865H33.2218V18.055Z" fill="currentColor"/><path d="M33.2218 21.8333V29.3884H25.6667V25.6116H29.445V21.8333H33.2218Z" fill="currentColor"/>"## }; +static MOONSHOTAI: Icon = Icon { name: "moonshotai", view: 40.0, body: r##"<path d="M5.85893 26.3499L18.1801 29.6463C18.1635 30.5223 18.1894 31.3987 18.2576 32.2722L25.9507 34.3298C23.669 35.2716 21.1952 35.6547 18.7355 35.4471L18.503 35.4265L18.4462 35.4213L18.3377 35.4097L18.2163 35.3968C18.1486 35.3886 18.081 35.38 18.0135 35.3709L17.8753 35.3528L17.7332 35.3322C17.5951 35.3121 17.4573 35.2901 17.3198 35.2663L17.2656 35.256L17.1687 35.2392L17.0305 35.2133L16.9401 35.194L16.82 35.1694L16.7231 35.1488L16.6004 35.1229L16.4751 35.0932L16.3537 35.0648L16.2659 35.0428L16.1522 35.0144L16.0359 34.9834L15.9132 34.9511L15.8073 34.9214L15.6665 34.8827L15.5864 34.8568L15.4779 34.8245L15.3578 34.7884L15.2222 34.7445L15.1473 34.7199L15.0439 34.6863L14.9277 34.6463L14.8424 34.6153C14.8235 34.6089 14.8045 34.6025 14.7856 34.5959L14.6978 34.5636L14.5673 34.5158L14.4937 34.4874L14.3904 34.4487L14.278 34.4035L14.1643 34.3583L14.0623 34.3169L13.9396 34.2653L13.8582 34.2291L13.7768 34.1942C13.7591 34.1865 13.7415 34.1788 13.7239 34.171L13.6386 34.1322L13.5056 34.0715L13.4384 34.0405L13.3144 33.9811L13.2343 33.9423L13.1258 33.8907L13.0147 33.8338L12.8946 33.7731L12.8274 33.7383L12.6944 33.6672L12.6208 33.6285L12.5459 33.5871C12.526 33.576 12.5062 33.5648 12.4864 33.5536L12.365 33.4851L12.2875 33.4412L12.2217 33.4024L12.1287 33.3495L12.0227 33.2849L11.9026 33.2126L11.8354 33.1712L11.7269 33.1028L11.6482 33.0524L11.5461 32.9878L11.4557 32.9271L11.3872 32.8819C11.3639 32.8665 11.3407 32.851 11.3175 32.8354L11.2607 32.7966L11.2038 32.7579C11.1866 32.7459 11.1693 32.7338 11.1522 32.7217L11.0785 32.6701L10.9804 32.6003L10.8912 32.5357L10.7957 32.466L10.7233 32.4117L10.6252 32.3381L10.527 32.2619L10.4159 32.1753L10.3578 32.1301L10.2751 32.063L10.1795 31.9855L10.0646 31.8912L10.0052 31.8408L9.94575 31.7904C9.92717 31.7746 9.90866 31.7586 9.8902 31.7426L9.83208 31.691L9.75329 31.6225L9.66287 31.5424L9.57504 31.4649L9.49496 31.39L9.40841 31.3099L9.33996 31.2453L9.22629 31.1368C9.18345 31.0953 9.14082 31.0535 9.09842 31.0116L9.06096 30.9754L9.008 30.9211L8.91887 30.8307L8.85429 30.7648L8.78971 30.6964C8.71592 30.6207 8.64357 30.5436 8.57271 30.4652L8.46938 30.3515L8.38929 30.2611L8.29758 30.1578L8.24333 30.0945L8.17488 30.0144L8.09996 29.9266L8.04054 29.8542C8.02888 29.8401 8.01725 29.8258 8.00567 29.8116L7.94754 29.7406L7.86229 29.6346L7.80934 29.5675L7.74475 29.4848L7.71892 29.4525C6.97985 28.4945 6.3556 27.4532 5.85893 26.3499ZM4.54143 18.8661L19.2057 22.7888C18.9602 23.6439 18.758 24.5109 18.5999 25.3864L32.5718 29.1244C31.8777 30.0748 31.0782 30.9436 30.1887 31.7142L5.34872 25.0673L5.32805 25.0079L5.28284 24.8736C5.26087 24.8078 5.23934 24.742 5.21826 24.676L5.20922 24.6462C5.1098 24.3302 5.02063 24.011 4.94184 23.6891L4.90309 23.5264L4.87984 23.423L4.85272 23.2978L4.82947 23.1931L4.80622 23.0769L4.78426 22.9684L4.76101 22.847C4.72743 22.6648 4.69643 22.4814 4.6693 22.2967L4.64735 22.1443L4.63314 22.0371L4.61635 21.9053C4.6077 21.8361 4.59952 21.7668 4.5918 21.6974L4.58535 21.6367C4.48884 20.7162 4.47414 19.7891 4.54143 18.8661ZM6.59905 12.214L22.0318 16.3421C21.5565 17.1236 21.1212 17.9322 20.7273 18.764L35.3166 22.6674C35.1332 23.7266 34.8413 24.7496 34.4538 25.7222L19.5351 21.731L4.66026 17.7526L4.67964 17.6235L4.68997 17.5602L4.70289 17.4736L4.72226 17.3613L4.74551 17.2347C4.7791 17.0435 4.81785 16.8536 4.85918 16.6638L4.89534 16.5036L4.92118 16.3938L4.95218 16.2685C4.98059 16.1523 5.0103 16.036 5.04259 15.9224L5.07876 15.7906L5.10847 15.6834L5.14722 15.5542L5.17951 15.4483L5.21826 15.3243L5.25184 15.2184L5.29189 15.0957C5.62637 14.0924 6.06355 13.1262 6.59646 12.2127L6.59905 12.214ZM12.3366 6.53068L26.913 10.4289C26.1438 11.1271 25.4158 11.8693 24.7327 12.6519L34.8374 15.3553C35.1823 16.4558 35.4083 17.608 35.5 18.7976L7.22034 11.2336L7.27846 11.1497L7.31334 11.098L7.365 11.027L7.42442 10.943L7.49546 10.8448L7.56521 10.7518L7.64788 10.6407L7.71246 10.5568L7.78609 10.4625L7.85713 10.3721L7.93463 10.2765L8.00567 10.1874L8.08963 10.0879L8.15938 10.0027L8.24463 9.90321L8.31308 9.82571L8.40608 9.71979L8.47454 9.64229L8.56108 9.54671L8.63083 9.47179L8.72512 9.37104L8.80004 9.29354L8.88142 9.207L9.09842 8.98742L9.22758 8.86084L9.30379 8.7885L9.40196 8.69679C10.2922 7.86254 11.2771 7.13554 12.3366 6.53068ZM20.022 4.50018H20.1473L20.2532 4.50147L20.3423 4.50277L20.4121 4.50535L20.4999 4.50793L20.5593 4.50922L20.6575 4.5131L20.7182 4.51568L20.7957 4.51956L20.8655 4.52214L20.9778 4.5286L21.1135 4.53764L21.2995 4.55185L21.4131 4.56089L21.47 4.56606L21.5694 4.57639L21.6753 4.58672L21.736 4.59318L21.8678 4.60868L21.9324 4.61643L22.0719 4.63452L22.1765 4.64743L22.2308 4.65518L22.3147 4.6681L22.5821 4.70943L22.6725 4.72493L22.7565 4.73914L22.9373 4.77272L23.0561 4.79597L23.1982 4.82439L23.2576 4.83731L23.3545 4.85797L23.4075 4.87089L23.4875 4.88768L23.5418 4.9006L23.6257 4.91997L23.689 4.93547L23.7807 4.95743L23.9047 4.98843L24.0494 5.02718L24.1954 5.06593L24.3413 5.10726L24.4059 5.12664L24.4963 5.15247L24.5971 5.18347L24.6914 5.21318L24.756 5.23385L24.8205 5.25451L24.9187 5.28681L25.0466 5.32943L25.1783 5.37593L25.2403 5.39789L25.323 5.4276L25.4431 5.47151L25.5852 5.52447L25.735 5.5826L25.8642 5.63426L25.9249 5.6601L26.0024 5.6911L26.0554 5.71435L26.1367 5.74793L26.1884 5.77118L26.262 5.80347L26.4041 5.86547L26.5333 5.92489L26.6289 5.97009L26.7257 6.01659L26.8032 6.05276L26.9221 6.11218L27.0396 6.1703L27.1714 6.23747L27.2398 6.27364L27.3031 6.30722L27.3625 6.33822L27.44 6.38084L27.493 6.40926L27.5602 6.44672L27.6738 6.5113L27.8107 6.5888L27.9231 6.65468L27.9967 6.69859L28.0652 6.73993L28.1892 6.81613L28.3029 6.88718L28.4294 6.96726L28.4759 6.99826L28.5586 7.05122L28.6671 7.12355L28.7188 7.15842L28.7989 7.21267L28.8789 7.26822L28.9086 7.29017C28.9784 7.33797 29.0481 7.38705 29.1166 7.43742L29.2238 7.51492L29.3078 7.57692L29.3801 7.63246L29.4912 7.71642L29.5971 7.79909L29.6488 7.83784L29.7134 7.8908L29.8244 7.97992L29.9265 8.06388L30.0363 8.15559C30.9559 8.93059 31.7839 9.81279 32.5021 10.779L13.8285 5.7841L13.9086 5.74922L13.9925 5.71305L14.0971 5.66914L14.2082 5.62393C14.3542 5.5658 14.5014 5.50768 14.6487 5.45472L14.7727 5.40951L14.8928 5.36689L15.0013 5.32814L15.1253 5.2881C15.2377 5.24935 15.3526 5.21318 15.4663 5.17831L15.5839 5.14343L15.6949 5.11114L15.8267 5.07239L15.9365 5.04268L16.0656 5.0091L16.1767 4.9781L16.293 4.94839L16.4105 4.91997L16.5332 4.89156L16.6495 4.86572L16.7761 4.8386L16.8936 4.81276L17.0163 4.78951L17.1351 4.76627L17.2643 4.74302L17.3818 4.72235L17.5084 4.70039L17.6273 4.68231L17.7526 4.66293L17.8714 4.64614L18.0031 4.62935L18.1207 4.61385L18.2563 4.59835L18.3726 4.58543L18.5082 4.57252C18.6283 4.5596 18.7484 4.54927 18.8698 4.54152L19.0068 4.53118L19.123 4.52472L19.2651 4.51697L19.3852 4.51181L19.5144 4.50664L19.6397 4.50406L19.7675 4.50147L20.022 4.49889V4.50018Z" fill="currentColor"/>"## }; +static MOONSHOTAI_CN: Icon = Icon { name: "moonshotai-cn", view: 40.0, body: r##"<path d="M5.85893 26.3499L18.1801 29.6463C18.1635 30.5223 18.1894 31.3987 18.2576 32.2722L25.9507 34.3298C23.669 35.2716 21.1952 35.6547 18.7355 35.4471L18.503 35.4265L18.4462 35.4213L18.3377 35.4097L18.2163 35.3968C18.1486 35.3886 18.081 35.38 18.0135 35.3709L17.8753 35.3528L17.7332 35.3322C17.5951 35.3121 17.4573 35.2901 17.3198 35.2663L17.2656 35.256L17.1687 35.2392L17.0305 35.2133L16.9401 35.194L16.82 35.1694L16.7231 35.1488L16.6004 35.1229L16.4751 35.0932L16.3537 35.0648L16.2659 35.0428L16.1522 35.0144L16.0359 34.9834L15.9132 34.9511L15.8073 34.9214L15.6665 34.8827L15.5864 34.8568L15.4779 34.8245L15.3578 34.7884L15.2222 34.7445L15.1473 34.7199L15.0439 34.6863L14.9277 34.6463L14.8424 34.6153C14.8235 34.6089 14.8045 34.6025 14.7856 34.5959L14.6978 34.5636L14.5673 34.5158L14.4937 34.4874L14.3904 34.4487L14.278 34.4035L14.1643 34.3583L14.0623 34.3169L13.9396 34.2653L13.8582 34.2291L13.7768 34.1942C13.7591 34.1865 13.7415 34.1788 13.7239 34.171L13.6386 34.1322L13.5056 34.0715L13.4384 34.0405L13.3144 33.9811L13.2343 33.9423L13.1258 33.8907L13.0147 33.8338L12.8946 33.7731L12.8274 33.7383L12.6944 33.6672L12.6208 33.6285L12.5459 33.5871C12.526 33.576 12.5062 33.5648 12.4864 33.5536L12.365 33.4851L12.2875 33.4412L12.2217 33.4024L12.1287 33.3495L12.0227 33.2849L11.9026 33.2126L11.8354 33.1712L11.7269 33.1028L11.6482 33.0524L11.5461 32.9878L11.4557 32.9271L11.3872 32.8819C11.3639 32.8665 11.3407 32.851 11.3175 32.8354L11.2607 32.7966L11.2038 32.7579C11.1866 32.7459 11.1693 32.7338 11.1522 32.7217L11.0785 32.6701L10.9804 32.6003L10.8912 32.5357L10.7957 32.466L10.7233 32.4117L10.6252 32.3381L10.527 32.2619L10.4159 32.1753L10.3578 32.1301L10.2751 32.063L10.1795 31.9855L10.0646 31.8912L10.0052 31.8408L9.94575 31.7904C9.92717 31.7746 9.90866 31.7586 9.8902 31.7426L9.83208 31.691L9.75329 31.6225L9.66287 31.5424L9.57504 31.4649L9.49496 31.39L9.40841 31.3099L9.33996 31.2453L9.22629 31.1368C9.18345 31.0953 9.14082 31.0535 9.09842 31.0116L9.06096 30.9754L9.008 30.9211L8.91887 30.8307L8.85429 30.7648L8.78971 30.6964C8.71592 30.6207 8.64357 30.5436 8.57271 30.4652L8.46938 30.3515L8.38929 30.2611L8.29758 30.1578L8.24333 30.0945L8.17488 30.0144L8.09996 29.9266L8.04054 29.8542C8.02888 29.8401 8.01725 29.8258 8.00567 29.8116L7.94754 29.7406L7.86229 29.6346L7.80934 29.5675L7.74475 29.4848L7.71892 29.4525C6.97985 28.4945 6.3556 27.4532 5.85893 26.3499ZM4.54143 18.8661L19.2057 22.7888C18.9602 23.6439 18.758 24.5109 18.5999 25.3864L32.5718 29.1244C31.8777 30.0748 31.0782 30.9436 30.1887 31.7142L5.34872 25.0673L5.32805 25.0079L5.28284 24.8736C5.26087 24.8078 5.23934 24.742 5.21826 24.676L5.20922 24.6462C5.1098 24.3302 5.02063 24.011 4.94184 23.6891L4.90309 23.5264L4.87984 23.423L4.85272 23.2978L4.82947 23.1931L4.80622 23.0769L4.78426 22.9684L4.76101 22.847C4.72743 22.6648 4.69643 22.4814 4.6693 22.2967L4.64735 22.1443L4.63314 22.0371L4.61635 21.9053C4.6077 21.8361 4.59952 21.7668 4.5918 21.6974L4.58535 21.6367C4.48884 20.7162 4.47414 19.7891 4.54143 18.8661ZM6.59905 12.214L22.0318 16.3421C21.5565 17.1236 21.1212 17.9322 20.7273 18.764L35.3166 22.6674C35.1332 23.7266 34.8413 24.7496 34.4538 25.7222L19.5351 21.731L4.66026 17.7526L4.67964 17.6235L4.68997 17.5602L4.70289 17.4736L4.72226 17.3613L4.74551 17.2347C4.7791 17.0435 4.81785 16.8536 4.85918 16.6638L4.89534 16.5036L4.92118 16.3938L4.95218 16.2685C4.98059 16.1523 5.0103 16.036 5.04259 15.9224L5.07876 15.7906L5.10847 15.6834L5.14722 15.5542L5.17951 15.4483L5.21826 15.3243L5.25184 15.2184L5.29189 15.0957C5.62637 14.0924 6.06355 13.1262 6.59646 12.2127L6.59905 12.214ZM12.3366 6.53068L26.913 10.4289C26.1438 11.1271 25.4158 11.8693 24.7327 12.6519L34.8374 15.3553C35.1823 16.4558 35.4083 17.608 35.5 18.7976L7.22034 11.2336L7.27846 11.1497L7.31334 11.098L7.365 11.027L7.42442 10.943L7.49546 10.8448L7.56521 10.7518L7.64788 10.6407L7.71246 10.5568L7.78609 10.4625L7.85713 10.3721L7.93463 10.2765L8.00567 10.1874L8.08963 10.0879L8.15938 10.0027L8.24463 9.90321L8.31308 9.82571L8.40608 9.71979L8.47454 9.64229L8.56108 9.54671L8.63083 9.47179L8.72512 9.37104L8.80004 9.29354L8.88142 9.207L9.09842 8.98742L9.22758 8.86084L9.30379 8.7885L9.40196 8.69679C10.2922 7.86254 11.2771 7.13554 12.3366 6.53068ZM20.022 4.50018H20.1473L20.2532 4.50147L20.3423 4.50277L20.4121 4.50535L20.4999 4.50793L20.5593 4.50922L20.6575 4.5131L20.7182 4.51568L20.7957 4.51956L20.8655 4.52214L20.9778 4.5286L21.1135 4.53764L21.2995 4.55185L21.4131 4.56089L21.47 4.56606L21.5694 4.57639L21.6753 4.58672L21.736 4.59318L21.8678 4.60868L21.9324 4.61643L22.0719 4.63452L22.1765 4.64743L22.2308 4.65518L22.3147 4.6681L22.5821 4.70943L22.6725 4.72493L22.7565 4.73914L22.9373 4.77272L23.0561 4.79597L23.1982 4.82439L23.2576 4.83731L23.3545 4.85797L23.4075 4.87089L23.4875 4.88768L23.5418 4.9006L23.6257 4.91997L23.689 4.93547L23.7807 4.95743L23.9047 4.98843L24.0494 5.02718L24.1954 5.06593L24.3413 5.10726L24.4059 5.12664L24.4963 5.15247L24.5971 5.18347L24.6914 5.21318L24.756 5.23385L24.8205 5.25451L24.9187 5.28681L25.0466 5.32943L25.1783 5.37593L25.2403 5.39789L25.323 5.4276L25.4431 5.47151L25.5852 5.52447L25.735 5.5826L25.8642 5.63426L25.9249 5.6601L26.0024 5.6911L26.0554 5.71435L26.1367 5.74793L26.1884 5.77118L26.262 5.80347L26.4041 5.86547L26.5333 5.92489L26.6289 5.97009L26.7257 6.01659L26.8032 6.05276L26.9221 6.11218L27.0396 6.1703L27.1714 6.23747L27.2398 6.27364L27.3031 6.30722L27.3625 6.33822L27.44 6.38084L27.493 6.40926L27.5602 6.44672L27.6738 6.5113L27.8107 6.5888L27.9231 6.65468L27.9967 6.69859L28.0652 6.73993L28.1892 6.81613L28.3029 6.88718L28.4294 6.96726L28.4759 6.99826L28.5586 7.05122L28.6671 7.12355L28.7188 7.15842L28.7989 7.21267L28.8789 7.26822L28.9086 7.29017C28.9784 7.33797 29.0481 7.38705 29.1166 7.43742L29.2238 7.51492L29.3078 7.57692L29.3801 7.63246L29.4912 7.71642L29.5971 7.79909L29.6488 7.83784L29.7134 7.8908L29.8244 7.97992L29.9265 8.06388L30.0363 8.15559C30.9559 8.93059 31.7839 9.81279 32.5021 10.779L13.8285 5.7841L13.9086 5.74922L13.9925 5.71305L14.0971 5.66914L14.2082 5.62393C14.3542 5.5658 14.5014 5.50768 14.6487 5.45472L14.7727 5.40951L14.8928 5.36689L15.0013 5.32814L15.1253 5.2881C15.2377 5.24935 15.3526 5.21318 15.4663 5.17831L15.5839 5.14343L15.6949 5.11114L15.8267 5.07239L15.9365 5.04268L16.0656 5.0091L16.1767 4.9781L16.293 4.94839L16.4105 4.91997L16.5332 4.89156L16.6495 4.86572L16.7761 4.8386L16.8936 4.81276L17.0163 4.78951L17.1351 4.76627L17.2643 4.74302L17.3818 4.72235L17.5084 4.70039L17.6273 4.68231L17.7526 4.66293L17.8714 4.64614L18.0031 4.62935L18.1207 4.61385L18.2563 4.59835L18.3726 4.58543L18.5082 4.57252C18.6283 4.5596 18.7484 4.54927 18.8698 4.54152L19.0068 4.53118L19.123 4.52472L19.2651 4.51697L19.3852 4.51181L19.5144 4.50664L19.6397 4.50406L19.7675 4.50147L20.022 4.49889V4.50018Z" fill="currentColor"/>"## }; +static MORPH: Icon = Icon { name: "morph", view: 24.0, body: r##"<path d="M9.8132 15.9038L9 18.75L8.1868 15.9038C7.75968 14.4089 6.59112 13.2403 5.09619 12.8132L2.25 12L5.09619 11.1868C6.59113 10.7597 7.75968 9.59112 8.1868 8.09619L9 5.25L9.8132 8.09619C10.2403 9.59113 11.4089 10.7597 12.9038 11.1868L15.75 12L12.9038 12.8132C11.4089 13.2403 10.2403 14.4089 9.8132 15.9038Z" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/><path d="M18.2589 8.71454L18 9.75L17.7411 8.71454C17.4388 7.50533 16.4947 6.56117 15.2855 6.25887L14.25 6L15.2855 5.74113C16.4947 5.43883 17.4388 4.49467 17.7411 3.28546L18 2.25L18.2589 3.28546C18.5612 4.49467 19.5053 5.43883 20.7145 5.74113L21.75 6L20.7145 6.25887C19.5053 6.56117 18.5612 7.50533 18.2589 8.71454Z" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/><path d="M16.8942 20.5673L16.5 21.75L16.1058 20.5673C15.8818 19.8954 15.3546 19.3682 14.6827 19.1442L13.5 18.75L14.6827 18.3558C15.3546 18.1318 15.8818 17.6046 16.1058 16.9327L16.5 15.75L16.8942 16.9327C17.1182 17.6046 17.6454 18.1318 18.3173 18.3558L19.5 18.75L18.3173 19.1442C17.6454 19.3682 17.1182 19.8954 16.8942 20.5673Z" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>"## }; +static NANO_GPT: Icon = Icon { name: "nano-gpt", view: 40.0, body: r##"<path d="M26.7,5.25l2.14-1.53,10.49,13.29-16.23,19.43-2.65,3L0.42,16.83l6.87-8.64,5.78,2.21,1.79-4.46L23.3,0.1l3.42,5.15ZM31.13,13.98L22.91,1.78l-7.1,4.95-5.45,13.53,20.77-6.28ZM36.74,15.57l-8.03-10.1-0.14-0.1-1.14,0.89,5.03,7.58,4.28,1.73ZM9.06,20.35l3.53-8.84-4.89-1.92-5.62,7.1,6.98,3.66ZM37.62,17.19l-5.3-2.14-9.22,19.52,14.52-17.38ZM30.95,15.24l-20.63,6.22,10.1,15.93,10.53-22.15ZM15.79,32.41l-6.86-10.82c-1.61-0.84-3.2-1.73-4.81-2.57-0.1-0.05-0.21-0.12-0.32-0.13l11.99,13.52Z" fill="currentColor"/>"## }; +static NEBIUS: Icon = Icon { name: "nebius", view: 40.0, body: r##"<path d="M30.3333 7.53622V29.2323C30.3333 29.2323 35.5 28.9198 35.5 23.013V7.53622H30.3333ZM9.66667 32.9756V11.2795C9.66667 11.2795 4.5 11.5921 4.5 17.5001V32.9743L9.66667 32.9756Z" fill="currentColor"/><path d="M25.5776 25.883L19.078 10.9384C18.0136 8.5204 16.2776 7.15898 13.8118 7.15898C11.3473 7.15898 9.66431 9.14815 9.66431 11.2794C9.66431 11.2794 12.7708 10.8493 14.4176 14.6287L20.9225 29.5733C21.9829 31.9887 23.7228 33.3527 26.186 33.3527C28.6466 33.3527 30.3336 31.3622 30.3336 29.2323C30.3336 29.2323 27.2258 29.6637 25.5776 25.883Z" fill="currentColor"/>"## }; +static NOVA: Icon = Icon { name: "nova", view: 24.0, body: r##"<path d="M13.48 17.46L14.64 18.62C14.69 18.67 14.71 18.75 14.68 18.82L12.87 23.41C12.73 23.76 12.38 24 12 24C11.62 24 11.27 23.76 11.13 23.41L8.52 16.80L4.31 21.02C4.24 21.09 4.12 21.09 4.05 21.02L2.98 19.95C2.91 19.88 2.91 19.76 2.98 19.69L8.18 14.49C8.35 14.32 8.58 14.21 8.81 14.19C9.23 14.17 9.60 14.42 9.74 14.78L12.00 20.51L13.18 17.52C13.23 17.40 13.39 17.37 13.49 17.46H13.48ZM19.69 2.98L15.48 7.20L12.87 0.59C12.71 0.17 12.26 -0.08 11.79 0.02C11.48 0.09 11.23 0.33 11.12 0.63L9.32 5.18C9.29 5.25 9.31 5.33 9.36 5.38L10.52 6.54C10.61 6.63 10.77 6.60 10.82 6.47L12 3.49L14.26 9.21C14.37 9.51 14.63 9.72 14.94 9.79C15.00 9.80 15.07 9.81 15.13 9.81C15.38 9.81 15.62 9.71 15.79 9.53L21.02 4.31C21.09 4.24 21.09 4.12 21.02 4.04L19.96 2.98C19.88 2.91 19.76 2.91 19.69 2.98L19.69 2.98ZM6.47 13.17L3.49 12.00L9.21 9.74C9.58 9.59 9.83 9.23 9.81 8.81C9.79 8.57 9.68 8.35 9.51 8.18L4.31 2.98C4.24 2.91 4.12 2.91 4.05 2.98L2.98 4.05C2.91 4.12 2.91 4.24 2.98 4.31L7.20 8.52L0.59 11.13C0.24 11.27 0 11.62 0 12.00C0 12.38 0.24 12.73 0.59 12.87L5.18 14.68C5.25 14.71 5.33 14.69 5.38 14.64L6.54 13.48C6.64 13.39 6.60 13.23 6.48 13.17H6.47ZM23.41 11.13L18.82 9.32C18.75 9.29 18.67 9.31 18.62 9.36L17.46 10.52C17.36 10.61 17.40 10.77 17.52 10.82L20.51 12.00L14.78 14.26C14.42 14.40 14.17 14.77 14.19 15.19C14.21 15.42 14.32 15.65 14.49 15.82L19.69 21.02C19.76 21.09 19.88 21.09 19.95 21.02L21.02 19.95C21.09 19.88 21.09 19.76 21.02 19.69L16.80 15.48L23.41 12.87C23.76 12.73 24 12.38 24 12.00C24 11.62 23.76 11.27 23.41 11.13V11.13Z" fill="currentColor"/>"## }; +static NOVITA_AI: Icon = Icon { name: "novita-ai", view: 40.0, body: r##"<path d="M15.5564 8.26172V16.5239L2.1875 29.8928H15.5564V21.6302L23.8194 29.8928H37.1875L15.5564 8.26172Z" fill="#000000"/>"## }; +static NVIDIA: Icon = Icon { name: "nvidia", view: 40.0, body: r##"<path d="M16.1801 15.8791V14.0283C16.3472 14.0155 16.5271 14.0026 16.7199 14.0026C21.7966 13.8356 25.1254 18.3596 25.1254 18.3596C25.1254 18.3596 21.5267 23.3463 17.671 23.3463C17.1569 23.3463 16.6557 23.2692 16.1801 23.1021V17.4728C18.1465 17.7298 18.545 18.591 19.7274 20.5702L22.375 18.3468C22.375 18.3468 20.4343 15.8277 17.1955 15.8277C16.8356 15.8277 16.5014 15.8405 16.1801 15.8791ZM16.1801 9.75492V12.5246C16.3472 12.5118 16.5271 12.4989 16.7199 12.4861C23.763 12.2547 28.377 18.2696 28.377 18.2696C28.377 18.2696 23.0819 24.683 17.5939 24.683C17.0798 24.683 16.6171 24.6444 16.1801 24.5545V26.2767C16.5528 26.3152 16.9384 26.341 17.3625 26.341C22.4649 26.341 26.1664 23.7448 29.7523 20.6473C30.3435 21.1229 32.7597 22.2796 33.261 22.7937C29.8679 25.6341 21.9251 27.9346 17.4396 27.9346C17.0155 27.9346 16.5914 27.9089 16.1801 27.8704V30.2866H35.6001V9.75492H16.1801ZM16.1801 23.1021V24.5545C11.4376 23.7191 10.1266 18.7966 10.1266 18.7966C10.1266 18.7966 12.4015 16.2775 16.1801 15.8791V17.4728H16.1673C14.188 17.2414 12.6329 19.0922 12.6329 19.0922C12.6329 19.0922 13.5068 22.2025 16.1801 23.1021ZM7.77464 18.591C7.77464 18.591 10.5765 14.4525 16.1801 14.0283V12.5246C9.9724 13.0259 4.6001 18.2696 4.6001 18.2696C4.6001 18.2696 7.64612 27.0735 16.1801 27.8575V26.2767C9.90814 25.4798 7.77464 18.591 7.77464 18.591Z" fill="currentColor"/>"## }; +static OLLAMA_CLOUD: Icon = Icon { name: "ollama-cloud", view: 40.0, body: r##"<path d="M12.1766 4.57738C12.7424 4.45248 13.3253 4.4821 13.8719 4.64802C14.3313 4.78771 14.7467 5.0176 15.1232 5.32158C15.7506 5.82452 16.2805 6.54484 16.6847 7.39778C17.0911 8.25589 17.3555 9.20672 17.4555 10.1602C18.7946 9.57485 20.2806 9.21797 21.8134 9.11449L21.9219 9.10819C23.7727 8.99312 25.6026 9.25154 27.1981 9.88772C27.4129 9.97483 27.6238 10.0679 27.8301 10.1665C27.9364 9.23136 28.196 8.30283 28.5958 7.46464C28.9999 6.60982 29.5307 5.89059 30.1561 5.38591C30.5055 5.09396 30.9329 4.86411 31.4086 4.71235C31.9551 4.54805 32.5357 4.5182 33.1014 4.64297C33.9545 4.83037 34.6868 5.24855 35.2633 5.85515C35.3459 5.94188 35.4243 6.03325 35.5005 6.12759V15.9511C35.3966 15.8807 35.2901 15.8126 35.18 15.748C33.9142 15.0017 32.2379 14.6416 30.117 14.7452C29.8396 14.7591 29.5632 14.7076 29.3236 14.5989C29.084 14.4902 28.8918 14.3286 28.7724 14.1347C28.1043 13.0417 27.1301 12.2596 25.9154 11.7747C24.7492 11.325 23.443 11.1355 22.1451 11.2285C19.4969 11.3914 17.161 12.5451 16.4653 13.9998C16.3668 14.2045 16.1901 14.3819 15.9582 14.5068C15.7263 14.6316 15.4499 14.6982 15.1673 14.6986C12.8978 14.7019 11.1405 15.1127 9.85572 15.854C8.74521 16.4951 7.98775 17.3916 7.58779 18.4649C7.22593 19.4754 7.17595 20.5375 7.44274 21.5654C7.68101 22.4825 8.14742 23.2424 8.68139 23.6517L8.69905 23.6631C9.14965 24.0034 9.24462 24.5344 8.92988 24.9534C8.16414 25.9759 7.59183 27.5 7.49823 28.9645C7.39192 30.6379 7.89443 32.0911 9.02827 33.1334L9.06232 33.1649C9.23327 33.3188 9.34304 33.5076 9.37893 33.7085C9.41476 33.9096 9.37497 34.1146 9.26414 34.2988C9.01373 34.7141 8.79967 35.1146 8.61959 35.4996H5.70206C5.88367 35.0312 6.10757 34.5494 6.37562 34.0555L6.40463 33.9973L6.38824 33.9785C5.81212 33.3209 5.38162 32.5935 5.11552 31.8266L5.10543 31.7951C4.78254 30.8384 4.65491 29.8484 4.72828 28.8612C4.82189 27.3653 5.31963 25.8324 6.05146 24.6028L6.07795 24.5599L6.0729 24.5573C5.4496 23.8702 4.98861 22.99 4.73333 22.0169L4.72198 21.9779C4.37027 20.6205 4.43825 19.2181 4.92001 17.8847C5.47739 16.3806 6.5735 15.0886 8.18819 14.1549C8.31563 14.0811 8.44921 14.0069 8.58301 13.9379C8.24476 11.4838 8.33005 9.45005 8.82141 7.90485C9.09153 7.05352 9.48977 6.34345 10.0172 5.78955C10.5916 5.18463 11.3236 4.76644 12.1766 4.57738ZM12.8767 6.64096C12.6303 6.7238 12.4193 6.8594 12.27 7.03199L12.2599 7.04208C11.9664 7.35278 11.7109 7.80949 11.5195 8.4094C11.1578 9.54695 11.0601 11.091 11.2558 12.9831C12.1706 12.7727 13.1684 12.641 14.2427 12.5933L14.2642 12.5908L14.3045 12.5353C14.4022 12.4008 14.5061 12.271 14.6186 12.143C14.8802 10.8758 14.6661 9.36166 14.0813 8.12559C13.7963 7.52741 13.4494 7.05655 13.1176 6.78855C13.0491 6.73286 12.972 6.68361 12.8893 6.64096L12.883 6.63719L12.8767 6.64096ZM32.3963 6.70403C32.3135 6.74667 32.2365 6.79719 32.1679 6.85288C31.8361 7.12084 31.4873 7.5929 31.2043 8.19118C30.5875 9.49635 30.3808 11.1109 30.7149 12.4193L30.8385 12.5782L30.8549 12.6009H30.9192C31.975 12.6011 33.0258 12.7194 34.0385 12.9503C34.2214 11.1026 34.1192 9.59119 33.7661 8.47499C33.5745 7.87507 33.3189 7.41836 33.0231 7.10767L33.0143 7.09758C32.8652 6.92452 32.6555 6.78729 32.4088 6.70403L32.4 6.70278L32.3963 6.70403Z" fill="currentColor" fill-rule="evenodd"/><path d="M21.5208 22.8469C21.7175 22.8312 21.9155 22.876 22.0695 22.9718L22.5262 23.2555L22.9941 22.9692C23.1476 22.8755 23.343 22.8314 23.5378 22.8469C23.7324 22.8626 23.912 22.9364 24.0373 23.0525L24.046 23.0601C24.3009 23.3081 24.2473 23.6677 23.9262 23.8648L23.3057 24.2432V24.9761C23.3045 25.1391 23.2194 25.295 23.0698 25.41C22.92 25.5248 22.717 25.5894 22.5059 25.5891C22.2946 25.5895 22.0908 25.5249 21.9408 25.41C21.7912 25.295 21.706 25.1391 21.705 24.9761V24.2205L21.1285 23.8623C21.0527 23.8153 20.9899 23.7567 20.9432 23.6907C20.8964 23.6247 20.8663 23.5512 20.8561 23.4763C20.8459 23.4017 20.8551 23.3262 20.8826 23.2542C20.9103 23.182 20.9572 23.1146 21.0188 23.0562C21.1443 22.9384 21.3244 22.8627 21.5208 22.8469Z" fill="currentColor"/><path d="M22.6284 19.5913C24.6195 19.5913 26.4584 20.1055 27.8327 20.9965C29.1727 21.8626 29.9705 23.0264 29.9707 24.1853C29.9707 25.6448 29.1066 26.7822 27.5602 27.5089C26.2412 28.1253 24.4732 28.4247 22.4479 28.4247C20.3014 28.4247 18.4671 27.9996 17.1439 27.2188C15.8314 26.4461 15.0955 25.3604 15.0955 24.1853C15.0957 23.0232 15.9423 21.8558 17.3419 20.9864C18.763 20.1036 20.6394 19.5914 22.6284 19.5913ZM22.6284 21.0634C21.1527 21.0534 19.716 21.4302 18.5529 22.1317C17.5721 22.7399 17.0165 23.5056 17.0165 24.1877C17.0168 24.8911 17.4639 25.5495 18.3144 26.0508C19.2825 26.6211 20.7055 26.9526 22.4479 26.9526C24.1473 26.9526 25.581 26.7109 26.5575 26.2525C27.5425 25.7922 28.0472 25.1239 28.0472 24.1853C28.0469 23.4898 27.5235 22.7218 26.5941 22.1203C25.5644 21.4547 24.1684 21.0634 22.6284 21.0634Z" fill="currentColor" fill-rule="evenodd"/><path d="M13.3142 19.8978C14.331 19.8978 15.1595 20.54 15.1595 21.3308C15.1599 21.7093 14.9655 22.0727 14.6197 22.3411C14.2735 22.6095 13.8033 22.7614 13.3129 22.7624C12.8231 22.7611 12.3531 22.6091 12.0074 22.3411C11.6621 22.0731 11.4676 21.7101 11.4675 21.332C11.4664 20.9532 11.6605 20.5891 12.0061 20.3204C12.3519 20.0516 12.8239 19.8994 13.3142 19.8978Z" fill="currentColor"/><path d="M31.8364 19.8978C32.8574 19.8978 33.683 20.54 33.683 21.3308C33.6834 21.7095 33.4892 22.0727 33.1431 22.3411C32.7968 22.6095 32.3267 22.7615 31.8364 22.7624C31.3466 22.7611 30.8779 22.6091 30.5321 22.3411C30.1866 22.0731 29.9923 21.7104 29.9922 21.332C29.991 20.9532 30.184 20.5891 30.5295 20.3204C30.8753 20.0516 31.3458 19.8992 31.8364 19.8978Z" fill="currentColor"/>"## }; +static OPENAI: Icon = Icon { name: "openai", view: 40.0, body: r##"<path d="M32.8377 17.282C33.2127 16.25 33.3072 15.218 33.2127 14.1875C33.1197 13.1571 32.7447 12.1251 32.2752 11.1876C31.4322 9.78209 30.2127 8.6571 28.8072 8.0001C27.3072 7.34461 25.7127 7.15711 24.1197 7.53211C23.3698 6.78212 22.5253 6.12512 21.5878 5.65713C20.6503 5.18913 19.5253 5.00013 18.4948 5.00013C16.8851 4.99074 15.3125 5.48246 13.9948 6.40712C12.6824 7.34311 11.7449 8.6571 11.2754 10.1571C10.1504 10.4376 9.21289 10.9071 8.27539 11.4696C7.4324 12.1251 6.77541 12.9696 6.21291 13.8126C5.36992 15.2195 5.08792 16.8125 5.27542 18.407C5.46399 19.9968 6.11605 21.496 7.1504 22.718C6.79608 23.7086 6.66795 24.7659 6.77541 25.8124C6.86991 26.8444 7.2449 27.8749 7.7129 28.8124C8.55739 30.2194 9.77538 31.3444 11.1824 31.9999C12.6824 32.6569 14.2753 32.8444 15.8698 32.4694C16.6198 33.2194 17.4628 33.8749 18.4003 34.3444C19.3378 34.8139 20.4628 34.9999 21.4948 34.9999C23.1043 35.0097 24.6769 34.5185 25.9947 33.5944C27.3072 32.6569 28.2447 31.3444 28.7127 29.8444C29.7719 29.6432 30.7682 29.1934 31.6197 28.5319C32.4627 27.8749 33.2127 27.1249 33.6822 26.1874C34.5251 24.7819 34.8071 23.1875 34.6196 21.5945C34.4322 20 33.8697 18.5015 32.8377 17.282ZM21.5878 33.0304C20.0878 33.0304 18.9628 32.5609 17.9323 31.7179C17.9323 31.7179 18.0253 31.6234 18.1198 31.6234L24.1197 28.1554C24.2862 28.0803 24.4196 27.9469 24.4947 27.7804C24.5698 27.636 24.6021 27.4731 24.5877 27.3109V18.875L27.1197 20.375V27.3124C27.1455 28.0547 27.0215 28.7945 26.755 29.4878C26.4885 30.181 26.085 30.8134 25.5687 31.3473C25.0523 31.8811 24.4337 32.3054 23.7497 32.5949C23.0658 32.8843 22.3305 33.0314 21.5878 33.0304ZM9.49488 27.8749C8.83789 26.7499 8.55739 25.4374 8.83789 24.125C8.83789 24.125 8.93239 24.2195 9.02539 24.2195L15.0253 27.6874C15.1693 27.7638 15.3325 27.7966 15.4948 27.7819C15.6823 27.7819 15.8698 27.7819 15.9628 27.6874L23.2753 23.4695V26.3749L17.1823 29.9374C16.5506 30.3042 15.8527 30.5427 15.1287 30.6393C14.4046 30.7358 13.6686 30.6884 12.9629 30.4999C11.4629 30.1249 10.2449 29.1874 9.49488 27.8749ZM7.9004 14.8445C8.56239 13.7234 9.58826 12.8627 10.8074 12.4056V19.532C10.8074 19.718 10.8074 19.907 10.9004 20C10.9755 20.1665 11.1089 20.2998 11.2754 20.375L18.5878 24.5944L16.0573 26.0944L10.0574 22.625C9.41842 22.2639 8.85742 21.7797 8.40684 21.2004C7.95627 20.6211 7.62506 19.9582 7.4324 19.25C7.05741 17.8445 7.1504 16.157 7.9004 14.8445ZM28.6197 19.625L21.3073 15.407L23.8377 13.9071L29.8377 17.375C30.7752 17.9375 31.5252 18.6875 31.9947 19.625C32.4642 20.5625 32.7447 21.5945 32.6502 22.7195C32.5603 23.7755 32.1699 24.7837 31.5252 25.6249C30.8697 26.4694 30.0252 27.1249 28.9947 27.4999V20.375C28.9947 20.1875 28.9947 20 28.9002 19.907C28.9002 19.907 28.8072 19.718 28.6197 19.625ZM31.1502 15.875C31.1502 15.875 31.0572 15.782 30.9627 15.782L24.9627 12.3126C24.7752 12.2196 24.6822 12.2196 24.4947 12.2196C24.3072 12.2196 24.1197 12.2196 24.0252 12.3126L16.7128 16.532V13.6251L22.8073 10.0626C23.7448 9.50009 24.7752 9.31259 25.9002 9.31259C26.9322 9.31259 27.9627 9.68759 28.9002 10.3446C29.7447 11.0001 30.4947 11.8446 30.8697 12.7821C31.2447 13.7196 31.3377 14.8445 31.1502 15.875ZM15.4003 21.125L12.8699 19.625V12.5946C12.8699 11.5626 13.1503 10.4376 13.7128 9.59459C14.2753 8.6571 15.1198 8.0001 16.0573 7.53211C17.0127 7.05249 18.0956 6.88812 19.1503 7.06261C20.1823 7.15711 21.2128 7.62511 22.0573 8.2821C22.0573 8.2821 21.9628 8.3751 21.8698 8.3751L15.8698 11.8446C15.7033 11.9197 15.57 12.0531 15.4948 12.2196C15.4003 12.4071 15.4003 12.5001 15.4003 12.6876V21.125ZM16.7128 18.125L19.9948 16.25L23.2753 18.125V21.875L19.9948 23.75L16.7128 21.875V18.125Z" fill="currentColor"/>"## }; +static OPENCODE: Icon = Icon { name: "opencode", view: 24.0, body: r##"<path d="M15.6 17.4H8.4V10.2H15.6V17.4Z" fill="currentColor" fill-opacity="0.4"/><path d="M15.6 6.6H8.4V17.4H15.6V6.6ZM19.2 21H4.8V3H19.2V21Z" fill="currentColor"/>"## }; +static OPENCODE_GO: Icon = Icon { name: "opencode-go", view: 24.0, body: r##"<path d="M19.4004 21H5V3H19.4004V6.59961H8.59961V17.4004H15.7998V13.7998H12.2002V10.2002H19.4004V21Z" fill="currentColor"/>"## }; +static OPENROUTER: Icon = Icon { name: "openrouter", view: 24.0, body: r##"<path d="M17.0634 5.4844C19.2029 5.4844 20.9373 7.2333 20.9373 9.3907C20.9373 11.548 19.2029 13.2969 17.0634 13.2969L20.9059 17.1716C21.394 17.6638 21.0483 18.5053 20.3581 18.5053L9.3157 18.5053C5.75 18.5053 2.8594 15.5905 2.8594 11.9948C2.8594 8.3992 5.75 5.4844 9.3157 5.4844L17.0634 5.4844ZM9.3157 8.0886C7.1763 8.0886 5.4419 9.8375 5.4419 11.9948C5.4419 14.1522 7.1763 15.9011 9.3157 15.9011C11.4552 15.9011 13.1896 14.1522 13.1896 11.9948C13.1896 9.8375 11.4552 8.0886 9.3157 8.0886Z" fill="currentColor"/>"## }; +static OVHCLOUD: Icon = Icon { name: "ovhcloud", view: 40.0, body: r##"<path d="M33.5005 11.7092C36.6343 17.3422 36.0393 24.3239 32.0327 29.3619H23.5039L26.122 24.7206H22.6708L26.7567 17.5405H30.2476L33.5005 11.7092ZM16.7205 29.3619H8.03298C3.94707 24.3239 3.35203 17.3025 6.52555 11.6695L12.1586 21.4281L18.3469 10.6381H27.4708L16.7205 29.3619Z" fill="currentColor" fill-rule="evenodd"/>"## }; +static PERPLEXITY: Icon = Icon { name: "perplexity", view: 24.0, body: r##"<path d="M17.2642 2.8689L12.042 8.0961M17.2642 2.8689V8.0961H12.042M17.2642 2.8689V4.30027M12.042 8.0961L6.81809 2.8689V8.0961H12.042ZM12.042 8.0961L17.2642 13.3225V20.8159L12.042 15.5887M12.042 8.0961V15.5887M12.042 8.0961L6.81892 13.3225M12.0296 2.1V21.9M12.042 15.5887L6.81892 20.8159V13.3225M6.81892 13.3225L6.81809 15.559H4.57739V8.09527H12.0412L6.81892 13.3225ZM11.9859 8.09527L17.2081 13.3225V15.559H19.4497V8.09527H11.9859Z" fill="none" stroke="currentColor" stroke-width="0.825"/>"## }; +static POE: Icon = Icon { name: "poe", view: 40.0, body: r##"<path d="M31.4739 11.8771C31.0962 11.4991 30.5979 11.3159 30.1031 11.3246L30.0936 11.3248C28.6012 11.3248 27.4017 10.115 27.4017 8.62262V8.62092C27.407 8.12944 27.2234 7.63665 26.8488 7.26144C26.485 6.89774 26.0103 6.714 25.5339 6.70853L10.3566 6.70834C9.87999 6.714 9.40529 6.89774 9.04177 7.26126C8.66693 7.63608 8.48319 8.12926 8.48885 8.62054L8.4883 8.61998C8.4883 10.1125 7.27826 11.3225 5.78592 11.3225L5.78781 11.3246C5.29275 11.3158 4.79487 11.4991 4.41684 11.8771C4.04672 12.2473 3.86223 12.7325 3.86279 13.2176V18.0722C3.86223 18.5573 4.04672 19.0422 4.41665 19.4123C4.79468 19.7903 5.29256 19.9735 5.78762 19.9648H5.78913C7.27844 19.9648 8.48359 21.1694 8.48867 22.6576V27.585C8.48867 28.2139 9.28073 28.4918 9.67383 28.0007L12.4096 24.5809L25.5347 24.5807C26.0113 24.5751 26.4858 24.3913 26.8495 24.0278C27.2243 23.653 27.4081 23.1598 27.4024 22.6685V22.6657C27.4024 21.1732 28.6072 19.9647 30.1002 19.9647H30.1036C30.5984 19.9735 31.0967 19.7901 31.4744 19.4121C31.8446 19.042 32.0293 18.5568 32.0285 18.072V13.2178C32.0287 12.7325 31.8438 12.2473 31.4739 11.8771ZM28.2471 18.1246C28.2314 19.604 27.0289 20.7983 25.546 20.7983H10.3445C8.86162 20.7983 7.65912 19.6036 7.64348 18.1246C7.64385 18.1071 7.64385 13.1827 7.64348 13.165C7.65912 11.6857 8.86162 10.4913 10.3445 10.4913L10.3428 10.4896C10.3474 10.4896 10.3519 10.4902 10.3566 10.4902V10.4913H25.5458C27.0287 10.4913 28.2314 11.6861 28.2469 13.1652C28.2465 13.1827 28.2467 18.1071 28.2471 18.1246Z" fill="currentColor"/><path d="M13.7473 12.8011C12.7003 12.8011 11.8513 13.6497 11.8513 14.6971V16.5931C11.8513 17.6402 12.6999 18.4891 13.7473 18.4891C14.7947 18.4891 15.6433 17.6405 15.6433 16.5931V14.697C15.6431 13.6499 14.7943 12.8011 13.7473 12.8011Z" fill="currentColor"/><path d="M22.1431 12.8011C21.096 12.8011 20.2471 13.6497 20.2471 14.6971V16.5931C20.2471 17.6402 21.0957 18.4891 22.1431 18.4891C23.1905 18.4891 24.0391 17.6405 24.0391 16.5931V14.697C24.0389 13.6499 23.1901 12.8011 22.1431 12.8011Z" fill="currentColor"/><path d="M13.5857 32.8994L16.2438 29.5775L29.369 29.5773C29.8455 29.5716 30.32 29.3879 30.6839 29.0244C31.0585 28.6496 31.2424 28.1564 31.2366 27.6651C31.2351 26.1767 32.438 24.9676 33.9259 24.9612H33.938C34.4328 24.9701 34.9308 24.7867 35.3088 24.4087C35.6787 24.0386 35.8634 23.5533 35.8628 23.0686V18.2745C35.8628 17.8169 35.7117 17.3718 35.4332 17.0085L34.9025 16.3159V21.8183C34.9033 22.3033 34.7186 22.7882 34.3484 23.1583C33.9707 23.5364 33.4727 23.7195 32.9779 23.7109H32.9658C31.4774 23.7173 30.2747 24.9265 30.2765 26.4147C30.2818 26.906 30.0981 27.399 29.7236 27.774C29.3599 28.1377 28.8852 28.3213 28.4088 28.3269L15.2836 28.3271L12.3915 31.9437C12.1718 32.2186 12.168 32.6078 12.3825 32.8868C12.6851 33.2806 13.2759 33.2863 13.5857 32.8994Z" fill="currentColor" fill-opacity="0.4"/><path d="M10.5362 29.3653L13.3635 25.83L26.4886 25.8298C26.9652 25.8242 27.4397 25.6404 27.8035 25.2769C28.1783 24.9021 28.362 24.4089 28.3564 23.9174V23.9146C28.3549 22.4277 29.5562 21.2199 31.043 21.2135H31.0577C31.5528 21.2224 32.0508 21.039 32.4285 20.661C32.7987 20.2909 32.9833 19.8058 32.9826 19.3209V13.8141L33.6775 14.7194C33.9563 15.0831 34.1074 15.5284 34.1074 15.9863V20.778C34.1079 21.2631 33.9235 21.748 33.5534 22.1181C33.1756 22.4961 32.6776 22.6793 32.1825 22.6706H32.1705C30.6823 22.677 29.4795 23.8863 29.4814 25.3745C29.4867 25.8658 29.3032 26.3588 28.9285 26.7338C28.5648 27.0975 28.0901 27.281 27.6137 27.2867L14.4885 27.2869L11.9332 30.4823C11.5706 30.9355 10.8794 30.9287 10.5255 30.4685C10.2746 30.1421 10.2792 29.6866 10.5362 29.3653Z" fill="currentColor" fill-opacity="0.6"/>"## }; +static PRIVATEMODE_AI: Icon = Icon { name: "privatemode-ai", view: 63.0, body: r##"<path d="M14.2167 6.7188C14.2167 10.4296 11.258 13.4377 7.6083 13.4377C3.9587 13.4377 1 10.4296 1 6.7188C1 3.0081 3.9587 0 7.6083 0C11.258 0 14.2167 3.0081 14.2167 6.7188Z" fill="currentColor"/><path d="M17.2667 22.7407L29.4667 22.7407L29.4667 62.0201L17.2667 62.0201L17.2667 22.7407Z" fill="currentColor"/><path d="M39.6333 33.0774C45.2482 33.0774 49.8 28.4495 49.8 22.7407C49.8 17.0319 45.2482 12.404 39.6333 12.404C34.0184 12.404 29.4667 17.0319 29.4667 22.7407C29.4667 28.4495 34.0184 33.0774 39.6333 33.0774ZM39.6333 45.4814C51.9861 45.4814 62 35.3 62 22.7407C62 10.1814 51.9861 0 39.6333 0C27.2806 0 17.2667 10.1814 17.2667 22.7407C17.2667 35.3 27.2806 45.4814 39.6333 45.4814Z" fill="currentColor" fill-rule="evenodd"/>"## }; +static QIHANG_AI: Icon = Icon { name: "qihang-ai", view: 40.0, body: r##"<path d="M20 2L36.4 11V29L20 38L3.6 29V11L20 2Z M20 20V2 M20 20L36.4 11 M20 20L36.4 29 M20 20V38 M20 20L3.6 29 M20 20L3.6 11" fill="none" stroke="currentColor" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"/>"## }; +static QINIU_AI: Icon = Icon { name: "qiniu-ai", view: 24.0, body: r##"<path d="M23.568,4.37284513 C23.180619,4.24052218 22.8592977,4.40224993 22.6756964,4.54008596 C20.1236928,7.55961616 16.310265,9.47645197 12.0489207,9.47645197 C10.5856349,9.47645197 9.17375432,9.25040654 7.84814258,8.82954254 C7.5029753,7.57615888 7.25878488,6.68481809 7.25878488,6.68481809 C7.25878488,6.68481809 6.97237307,5.81185554 6.00112785,5.96071698 L6.28019714,8.22306831 C4.39829587,7.36296976 2.74038351,6.09854994 1.42029592,4.53641031 C1.23669698,4.39857428 0.915396329,4.23684654 0.528,4.36916956 C1.62959981,7.32069904 3.8328071,9.73559053 6.63638202,11.1121076 L7.40015707,17.309184 C7.40015707,17.309184 7.74165693,19.68 9.96508874,19.68 L14.7184659,19.68 C16.9418594,19.68 17.2833592,17.309184 17.2833592,17.309184 L17.8212733,12.8690689 C16.3782427,12.7514113 15.4693667,13.7585665 15.1829548,14.7509761 C14.7001288,16.4233728 14.7001288,16.5318144 14.6046071,16.8221952 C14.4100343,17.4194688 13.7692329,17.4912 13.7692329,17.4912 L10.9179278,17.4912 C10.9179278,17.4912 10.2772032,17.4194688 10.0825536,16.8221952 C9.95772321,16.4381184 9.32981155,14.1868033 8.69821712,11.9023719 C9.76307366,12.2037505 10.8885424,12.3654913 12.0507621,12.3654913 C17.3237162,12.3710209 21.8219851,9.04456718 23.568,4.37284513 Z" fill="currentColor" fill-rule="nonzero"/>"## }; +static REFLECTION: Icon = Icon { name: "reflection", view: 272.0, body: r##"<path d="M65.274 83.769C93.85 83.769 117.099 107.018 117.099 135.594C117.099 164.17 93.85 187.419 65.274 187.419C36.697 187.419 13.4483 164.17 13.4483 135.594C13.4483 107.018 36.697 83.769 65.274 83.769ZM65.274 71.047C29.6209 71.047 0.7266 99.941 0.7266 135.594C0.7266 171.247 29.6209 200.141 65.274 200.141C100.926 200.141 129.821 171.247 129.821 135.594C129.821 99.941 100.926 71.047 65.274 71.047ZM207.09 71.047C171.437 71.047 142.542 99.941 142.542 135.594C142.542 171.247 171.437 200.141 207.09 200.141C242.742 200.141 271.637 171.247 271.637 135.594C271.637 99.941 242.742 71.047 207.09 71.047Z" fill="currentColor"/>"## }; +static REQUESTY: Icon = Icon { name: "requesty", view: 24.0, body: r##"<path d="M9.8132 15.9038L9 18.75L8.1868 15.9038C7.75968 14.4089 6.59112 13.2403 5.09619 12.8132L2.25 12L5.09619 11.1868C6.59113 10.7597 7.75968 9.59112 8.1868 8.09619L9 5.25L9.8132 8.09619C10.2403 9.59113 11.4089 10.7597 12.9038 11.1868L15.75 12L12.9038 12.8132C11.4089 13.2403 10.2403 14.4089 9.8132 15.9038Z" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/><path d="M18.2589 8.71454L18 9.75L17.7411 8.71454C17.4388 7.50533 16.4947 6.56117 15.2855 6.25887L14.25 6L15.2855 5.74113C16.4947 5.43883 17.4388 4.49467 17.7411 3.28546L18 2.25L18.2589 3.28546C18.5612 4.49467 19.5053 5.43883 20.7145 5.74113L21.75 6L20.7145 6.25887C19.5053 6.56117 18.5612 7.50533 18.2589 8.71454Z" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/><path d="M16.8942 20.5673L16.5 21.75L16.1058 20.5673C15.8818 19.8954 15.3546 19.3682 14.6827 19.1442L13.5 18.75L14.6827 18.3558C15.3546 18.1318 15.8818 17.6046 16.1058 16.9327L16.5 15.75L16.8942 16.9327C17.1182 17.6046 17.6454 18.1318 18.3173 18.3558L19.5 18.75L18.3173 19.1442C17.6454 19.3682 17.1182 19.8954 16.8942 20.5673Z" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>"## }; +static SAP_AI_CORE: Icon = Icon { name: "sap-ai-core", view: 24.0, body: r##"<path d="M9.8132 15.9038L9 18.75L8.1868 15.9038C7.75968 14.4089 6.59112 13.2403 5.09619 12.8132L2.25 12L5.09619 11.1868C6.59113 10.7597 7.75968 9.59112 8.1868 8.09619L9 5.25L9.8132 8.09619C10.2403 9.59113 11.4089 10.7597 12.9038 11.1868L15.75 12L12.9038 12.8132C11.4089 13.2403 10.2403 14.4089 9.8132 15.9038Z" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/><path d="M18.2589 8.71454L18 9.75L17.7411 8.71454C17.4388 7.50533 16.4947 6.56117 15.2855 6.25887L14.25 6L15.2855 5.74113C16.4947 5.43883 17.4388 4.49467 17.7411 3.28546L18 2.25L18.2589 3.28546C18.5612 4.49467 19.5053 5.43883 20.7145 5.74113L21.75 6L20.7145 6.25887C19.5053 6.56117 18.5612 7.50533 18.2589 8.71454Z" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/><path d="M16.8942 20.5673L16.5 21.75L16.1058 20.5673C15.8818 19.8954 15.3546 19.3682 14.6827 19.1442L13.5 18.75L14.6827 18.3558C15.3546 18.1318 15.8818 17.6046 16.1058 16.9327L16.5 15.75L16.8942 16.9327C17.1182 17.6046 17.6454 18.1318 18.3173 18.3558L19.5 18.75L18.3173 19.1442C17.6454 19.3682 17.1182 19.8954 16.8942 20.5673Z" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>"## }; +static SCALEWAY: Icon = Icon { name: "scaleway", view: 24.0, body: r##"<path d="M12.6809 6.96139H9.61812C8.9461 7.03911 8.42917 7.59607 8.40332 8.26961V12.6994C8.40332 12.9973 8.51964 13.2564 8.71349 13.4507C8.90733 13.645 9.1658 13.7615 9.46304 13.7615C10.0446 13.7615 10.5228 13.2823 10.5228 12.6994V9.88869C10.5228 9.4483 10.8846 9.08562 11.324 9.08562H12.7068C13.004 9.08562 13.2625 8.96905 13.4563 8.77476C13.6502 8.58048 13.7665 8.30847 13.7665 8.01056C13.7665 7.42769 13.2625 6.96139 12.6809 6.96139Z" fill="currentColor"/><path d="M11.2982 17.0645H14.361C15.033 16.9867 15.55 16.4298 15.5758 15.7563V11.3265C15.5758 11.0285 15.4595 10.7695 15.2657 10.5752C15.0718 10.3809 14.8133 10.2643 14.5161 10.2643C13.9346 10.2643 13.4564 10.7436 13.4564 11.3265V14.1372C13.4564 14.5776 13.0945 14.9402 12.6551 14.9402H11.2724C10.9751 14.9402 10.7167 15.0568 10.5228 15.2511C10.329 15.4454 10.2126 15.7174 10.2126 16.0153C10.2256 16.5982 10.7167 17.0645 11.2982 17.0645Z" fill="currentColor"/><path d="M7.62793 2.7H13.1979C16.8681 2.7 19.8275 5.66616 19.8147 9.34471V18.1655C19.6466 19.8364 18.2896 21.1575 16.6096 21.3H10.7425C7.08515 21.3 4.11279 18.3209 4.11279 14.6553V6.22312C4.11279 4.28023 5.68944 2.7 7.62793 2.7ZM17.7081 9.34471C17.7081 6.8578 15.6792 4.82424 13.1979 4.82424H7.64085C6.86545 4.82424 6.24514 5.44597 6.24514 6.22312V14.6553C6.24514 17.1552 8.26117 19.1757 10.7554 19.1757H16.5192C17.1266 19.0981 17.6048 18.6318 17.7081 18.036V9.34471Z" fill="currentColor" fill-rule="evenodd"/>"## }; +static SILICONFLOW: Icon = Icon { name: "siliconflow", view: 40.0, body: r##"<path d="M34.1033 12.3605H20.6227C19.8778 12.3605 19.2764 12.9839 19.2764 13.7501V17.9223C19.2764 18.2909 19.1346 18.6451 18.8823 18.9058C18.6292 19.1658 18.2869 19.3127 17.9293 19.3118H5.7933C5.04839 19.3118 4.44703 19.9353 4.44703 20.7014V26.2658C4.44618 26.6344 4.58887 26.9886 4.84114 27.2485C5.09341 27.5093 5.43656 27.6562 5.7933 27.6562H19.273C19.6306 27.6562 19.9729 27.5093 20.226 27.2485C20.4783 26.9886 20.6202 26.6344 20.6202 26.2658V22.0944C20.6193 21.7258 20.7612 21.3716 21.0143 21.1108C21.2665 20.8501 21.6097 20.704 21.9673 20.7048H34.0999C34.8457 20.7048 35.447 20.0805 35.447 19.3152V13.7501C35.447 12.9814 34.8423 12.3605 34.0999 12.3605H34.1033Z" fill="currentColor"/>"## }; +static SILICONFLOW_CN: Icon = Icon { name: "siliconflow-cn", view: 40.0, body: r##"<path d="M34.1033 12.3605H20.6227C19.8778 12.3605 19.2764 12.9839 19.2764 13.7501V17.9223C19.2764 18.2909 19.1346 18.6451 18.8823 18.9058C18.6292 19.1658 18.2869 19.3127 17.9293 19.3118H5.7933C5.04839 19.3118 4.44703 19.9353 4.44703 20.7014V26.2658C4.44618 26.6344 4.58887 26.9886 4.84114 27.2485C5.09341 27.5093 5.43656 27.6562 5.7933 27.6562H19.273C19.6306 27.6562 19.9729 27.5093 20.226 27.2485C20.4783 26.9886 20.6202 26.6344 20.6202 26.2658V22.0944C20.6193 21.7258 20.7612 21.3716 21.0143 21.1108C21.2665 20.8501 21.6097 20.704 21.9673 20.7048H34.0999C34.8457 20.7048 35.447 20.0805 35.447 19.3152V13.7501C35.447 12.9814 34.8423 12.3605 34.0999 12.3605H34.1033Z" fill="currentColor"/>"## }; +static STACKIT: Icon = Icon { name: "stackit", view: 41.536063, body: r##"<path d="M13.9510149,10.4421038h20.8374634l-1.1608887,5.4412842h-14.5545654l-1.3522339,6.3352661h-6.2828369l2.5130615-11.7765503ZM22.5114397,25.652614H7.9081072l-1.1605225,5.4413452h20.8855591l2.5210571-11.8130493h-6.2828979l-1.3598633,6.3717041Z" fill="currentColor"/>"## }; +static STEPFUN: Icon = Icon { name: "stepfun", view: 28.0, body: r##"<path d="M14 0C6.272 0 0 6.272 0 14C0 21.728 6.272 28 14 28C21.728 28 28 21.728 28 14C28 6.272 21.728 0 14 0ZM10.22 22.876H5.11V17.766H10.22V22.876ZM16.548 22.876H11.438V17.766H16.548V22.876ZM16.548 16.562H11.438V11.438H16.548V16.562ZM16.548 10.234H11.438V5.124H16.548V10.234ZM22.876 10.234H17.766V5.11H22.876V10.234Z" fill="currentColor"/>"## }; +static SUBMODEL: Icon = Icon { name: "submodel", view: 24.0, body: r##"<path d="M8.69514 3.98663C3.44358 6.10184 1.69306 13.7604 5.55879 17.6261L7.60106 19.5954L9.86215 17.4802C11.1021 16.2403 12.415 14.5627 12.7797 13.6145C13.2173 12.5204 13.9467 12.0098 14.6761 12.1557C16.4266 12.5204 16.7913 14.8544 15.1137 15.4379C13.1444 16.0944 10.5186 18.6472 10.5186 19.8872C10.5186 21.7106 15.6243 20.3977 18.1771 17.8449C20.0006 15.9485 20.3653 15.0732 20.3653 12.0098C20.3653 9.09231 20.0006 7.99823 18.4689 6.53947L16.5725 4.64307L14.2384 6.61241C12.9256 7.70648 11.5397 9.38406 11.175 10.3323C10.7374 11.4993 10.081 12.0098 9.27864 11.864C7.52813 11.4993 7.16343 9.16524 8.84101 8.65468C10.7374 7.92529 14.1655 4.64307 13.7279 3.84075C13.2902 3.11137 10.6645 3.18431 8.69514 3.98663Z" fill="currentColor"/>"## }; +static SYNTHETIC: Icon = Icon { name: "synthetic", view: 24.0, body: r##"<path d="M9.8132 15.9038L9 18.75L8.1868 15.9038C7.75968 14.4089 6.59112 13.2403 5.09619 12.8132L2.25 12L5.09619 11.1868C6.59113 10.7597 7.75968 9.59112 8.1868 8.09619L9 5.25L9.8132 8.09619C10.2403 9.59113 11.4089 10.7597 12.9038 11.1868L15.75 12L12.9038 12.8132C11.4089 13.2403 10.2403 14.4089 9.8132 15.9038Z" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/><path d="M18.2589 8.71454L18 9.75L17.7411 8.71454C17.4388 7.50533 16.4947 6.56117 15.2855 6.25887L14.25 6L15.2855 5.74113C16.4947 5.43883 17.4388 4.49467 17.7411 3.28546L18 2.25L18.2589 3.28546C18.5612 4.49467 19.5053 5.43883 20.7145 5.74113L21.75 6L20.7145 6.25887C19.5053 6.56117 18.5612 7.50533 18.2589 8.71454Z" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/><path d="M16.8942 20.5673L16.5 21.75L16.1058 20.5673C15.8818 19.8954 15.3546 19.3682 14.6827 19.1442L13.5 18.75L14.6827 18.3558C15.3546 18.1318 15.8818 17.6046 16.1058 16.9327L16.5 15.75L16.8942 16.9327C17.1182 17.6046 17.6454 18.1318 18.3173 18.3558L19.5 18.75L18.3173 19.1442C17.6454 19.3682 17.1182 19.8954 16.8942 20.5673Z" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>"## }; +static TOGETHERAI: Icon = Icon { name: "togetherai", view: 40.0, body: r##"<path d="M27.539 18.922C29.2526 18.922 30.8959 18.2413 32.1076 17.0296C33.3193 15.8179 34 14.1746 34 12.461C34 10.7474 33.3193 9.10406 32.1076 7.89238C30.8959 6.68071 29.2526 6 27.539 6C25.8254 6 24.1821 6.68071 22.9704 7.89238C21.7587 9.10406 21.078 10.7474 21.078 12.461C21.078 14.1746 21.7587 15.8179 22.9704 17.0296C24.1821 18.2413 25.8254 18.922 27.539 18.922ZM27.539 34C29.2526 34 30.8959 33.3193 32.1076 32.1076C33.3193 30.8959 34 29.2526 34 27.539C34 25.8254 33.3193 24.1821 32.1076 22.9704C30.8959 21.7587 29.2526 21.078 27.539 21.078C25.8254 21.078 24.1821 21.7587 22.9704 22.9704C21.7587 24.1821 21.078 25.8254 21.078 27.539C21.078 29.2526 21.7587 30.8959 22.9704 32.1076C24.1821 33.3193 25.8254 34 27.539 34ZM12.461 34C14.1746 34 15.8179 33.3193 17.0296 32.1076C18.2413 30.8959 18.922 29.2526 18.922 27.539C18.922 25.8254 18.2413 24.1821 17.0296 22.9704C15.8179 21.7587 14.1746 21.078 12.461 21.078C10.7474 21.078 9.10406 21.7587 7.89238 22.9704C6.68071 24.1821 6 25.8254 6 27.539C6 29.2526 6.68071 30.8959 7.89238 32.1076C9.10406 33.3193 10.7474 34 12.461 34Z" fill="currentColor" opacity="0.25"/><path d="M12.461 18.922C16.0293 18.922 18.922 16.0293 18.922 12.461C18.922 8.89269 16.0293 6 12.461 6C8.89269 6 6 8.89269 6 12.461C6 16.0293 8.89269 18.922 12.461 18.922Z" fill="currentColor"/>"## }; +static UPSTAGE: Icon = Icon { name: "upstage", view: 24.0, body: r##"<path d="M9.8132 15.9038L9 18.75L8.1868 15.9038C7.75968 14.4089 6.59112 13.2403 5.09619 12.8132L2.25 12L5.09619 11.1868C6.59113 10.7597 7.75968 9.59112 8.1868 8.09619L9 5.25L9.8132 8.09619C10.2403 9.59113 11.4089 10.7597 12.9038 11.1868L15.75 12L12.9038 12.8132C11.4089 13.2403 10.2403 14.4089 9.8132 15.9038Z" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/><path d="M18.2589 8.71454L18 9.75L17.7411 8.71454C17.4388 7.50533 16.4947 6.56117 15.2855 6.25887L14.25 6L15.2855 5.74113C16.4947 5.43883 17.4388 4.49467 17.7411 3.28546L18 2.25L18.2589 3.28546C18.5612 4.49467 19.5053 5.43883 20.7145 5.74113L21.75 6L20.7145 6.25887C19.5053 6.56117 18.5612 7.50533 18.2589 8.71454Z" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/><path d="M16.8942 20.5673L16.5 21.75L16.1058 20.5673C15.8818 19.8954 15.3546 19.3682 14.6827 19.1442L13.5 18.75L14.6827 18.3558C15.3546 18.1318 15.8818 17.6046 16.1058 16.9327L16.5 15.75L16.8942 16.9327C17.1182 17.6046 17.6454 18.1318 18.3173 18.3558L19.5 18.75L18.3173 19.1442C17.6454 19.3682 17.1182 19.8954 16.8942 20.5673Z" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>"## }; +static V0: Icon = Icon { name: "v0", view: 40.0, body: r##"<path d="M22.6686 12.2861V15.1536H30.0685C30.1331 15.1528 30.1968 15.1549 30.2597 15.1601L22.6996 22.5897C22.6789 22.4577 22.6686 22.3243 22.6686 22.1906V15.1523H19.6293V22.1919C19.6293 25.1912 22.1287 27.6453 25.1292 27.6453H32.4594V24.7778H25.1292C25.1034 24.7778 25.078 24.7765 25.053 24.774L32.453 17.5032C32.4581 17.5738 32.4607 17.6452 32.4607 17.7176V24.7765H35.5V17.7176C35.5002 17.0043 35.3598 16.2979 35.0869 15.6388C34.814 14.9798 34.4139 14.381 33.9095 13.8766C33.4051 13.3722 32.8063 12.9721 32.1473 12.6992C31.4882 12.4263 30.7819 12.2859 30.0685 12.2861H22.6686ZM4.5 15.1497L15.195 27.1183C16.2787 28.3325 18.2898 27.5652 18.2898 25.9377V15.1497H15.0787V22.1764L8.80125 15.1497H4.5Z" fill="currentColor"/>"## }; +static VENICE: Icon = Icon { name: "venice", view: 40.0, body: r##"<path d="M15.2746 25.1631C14.7812 24.7962 14.1856 24.4889 13.527 24.3022C12.8684 24.1155 12.1468 24.0494 11.4412 24.1277C10.7355 24.2059 10.0459 24.4285 9.44426 24.7551C8.8426 25.0815 8.32886 25.512 7.92778 25.9781C7.5256 26.4433 7.17523 27.0146 6.94055 27.6577C6.70588 28.3008 6.58691 29.0155 6.61306 29.725C6.63919 30.4345 6.81044 31.1386 7.09179 31.7626C7.37314 32.3867 7.76461 32.9307 8.19994 33.3651C8.63423 33.8004 9.17824 34.1918 9.8023 34.4732C10.4264 34.7545 11.1305 34.9257 11.84 34.952C12.5494 34.9781 13.2642 34.8591 13.9073 34.6244C14.5504 34.3897 15.1218 34.0393 15.5869 33.6372C16.053 33.2362 16.4834 32.7224 16.8099 32.1207C17.1364 31.5191 17.359 30.8294 17.4373 30.1238C17.5156 29.4182 17.4496 28.6966 17.2628 28.038C17.0761 27.3794 16.7687 26.7838 16.4019 26.2903L17.6136 25.0785L18.4957 25.9605H18.9967L19.6013 25.3559V24.855L18.7193 23.9729L19.9998 22.6924L21.2804 23.9729L20.3983 24.855V25.3559L21.003 25.9605H21.504L22.386 25.0785L23.5978 26.2903C23.231 26.7838 22.9236 27.3794 22.7368 28.038C22.5501 28.6966 22.4841 29.4182 22.5623 30.1238C22.6406 30.8294 22.8633 31.5191 23.1897 32.1207C23.5163 32.7224 23.9467 33.2362 24.4128 33.6372C24.8779 34.0393 25.4493 34.3897 26.0923 34.6244C26.7354 34.8591 27.4503 34.9781 28.1597 34.952C28.8692 34.9257 29.5733 34.7545 30.1974 34.4732C30.8215 34.1918 31.3655 33.8004 31.7997 33.3651C32.235 32.9307 32.6265 32.3867 32.9079 31.7626C33.1892 31.1386 33.3605 30.4345 33.3866 29.725C33.4127 29.0155 33.2938 28.3008 33.0592 27.6577C32.8244 27.0146 32.4741 26.4433 32.0719 25.9781C31.6708 25.512 31.157 25.0815 30.5554 24.7551C29.9537 24.4285 29.2641 24.2059 28.5585 24.1277C27.8529 24.0494 27.1313 24.1155 26.4727 24.3022C25.8141 24.4889 25.2185 24.7962 24.725 25.1631L23.5357 23.9719L24.4173 23.0904V22.5894L23.7911 21.9632H23.2901L22.4081 22.8452L21.127 21.5651L27.8429 14.8492L30.5616 17.5678V14.7392H33.3903L30.6717 12.0205L33.3903 9.30188V8.80091L32.7641 8.17468H32.2631L19.9998 20.4379L7.73657 8.17468H7.2356L6.60938 8.80091V9.30188L9.328 12.0205L6.60938 14.7392H9.43806V17.5678L12.1567 14.8492L18.8727 21.5651L17.5916 22.8452L16.7096 21.9632H16.2085L15.5823 22.5894V23.0904L16.4639 23.9719L15.2746 25.1631ZM26.1729 31.3844C25.8964 31.9517 25.9538 32.7377 26.3099 33.2588C26.637 33.7984 27.3289 34.1757 27.9598 34.1585C28.5906 34.1757 29.2825 33.7984 29.6097 33.2588C29.9657 32.7377 30.0231 31.9517 29.7466 31.3844L29.8155 31.3102C30.3827 31.5882 31.1699 31.532 31.6918 31.176C32.2323 30.8492 32.6105 30.1565 32.5932 29.525C32.6105 28.8936 32.2323 28.2009 31.6918 27.8741C31.1699 27.5182 30.3827 27.4618 29.8155 27.7399L29.7466 27.6657C30.0231 27.0985 29.9657 26.3124 29.6097 25.7914C29.2825 25.2518 28.5906 24.8744 27.9598 24.8916C27.3289 24.8744 26.637 25.2518 26.3099 25.7914C25.9538 26.3124 25.8964 27.0985 26.1729 27.6657L26.1041 27.7399C25.5368 27.4618 24.7496 27.5182 24.2278 27.8741C23.6872 28.2009 23.309 28.8936 23.3263 29.525C23.309 30.1565 23.6872 30.8492 24.2278 31.176C24.7496 31.532 25.5368 31.5882 26.1041 31.3102L26.1729 31.3844ZM13.6895 33.2588C14.0456 32.7377 14.103 31.9517 13.8265 31.3844L13.8954 31.3102C14.4626 31.5882 15.2498 31.532 15.7717 31.176C16.3121 30.8492 16.6904 30.1565 16.6731 29.525C16.6904 28.8936 16.3121 28.2009 15.7717 27.8741C15.2498 27.5182 14.4626 27.4618 13.8954 27.7399L13.8265 27.6657C14.103 27.0985 14.0456 26.3124 13.6895 25.7914C13.3624 25.2518 12.6705 24.8744 12.0396 24.8916C11.4088 24.8744 10.7169 25.2518 10.3898 25.7914C10.0337 26.3124 9.97627 27.0985 10.2528 27.6657L10.1839 27.7399C9.61674 27.4618 8.82952 27.5182 8.30767 27.8741C7.76713 28.2009 7.3889 28.8936 7.40618 29.525C7.3889 30.1565 7.76713 30.8492 8.30767 31.176C8.82952 31.532 9.61674 31.5882 10.1839 31.3102L10.2528 31.3844C9.97627 31.9517 10.0337 32.7377 10.3898 33.2588C10.7169 33.7984 11.4088 34.1757 12.0396 34.1585C12.6705 34.1757 13.3624 33.7984 13.6895 33.2588Z" fill="currentColor" fill-rule="evenodd"/><path d="M19.9907 8.17464L23.21 4.95547L24.804 6.54957V11.923L20.3893 16.3378H19.5922L15.1775 11.923V6.54957L16.7716 4.95547L19.9907 8.17464ZM16.7716 6.08268L19.5922 8.90334V14.0833L16.7716 11.2627V6.08268ZM20.3894 8.90334L23.21 6.08268V11.2627L20.3894 14.0833V8.90334Z" fill="currentColor" fill-rule="evenodd"/>"## }; +static VERCEL: Icon = Icon { name: "vercel", view: 40.0, body: r##"<path d="M35.5 33.5949H4.5L20 6.40511L35.5 33.5949Z" fill="currentColor"/>"## }; +static VIVGRID: Icon = Icon { name: "vivgrid", view: 24.0, body: r##"<path d="M 10.921 1.266 C 11.477 0.952 12.161 0.952 12.717 1.266 L 14.079 2.037 C 12.108 3.127 9.934 4.437 8.274 5.788 C 7.425 6.479 6.706 7.185 6.216 7.879 C 5.727 8.574 5.458 9.268 5.53 9.935 C 5.625 10.839 6.133 11.432 6.825 11.858 C 7.512 12.283 8.388 12.55 9.232 12.809 C 9.968 13.033 10.681 13.253 11.245 13.56 C 11.808 13.868 12.214 14.257 12.353 14.819 C 12.492 15.384 12.369 16.145 11.825 17.206 C 11.286 18.255 10.342 19.586 8.861 21.293 L 2.91 17.924 C 2.356 17.608 2.013 17.028 2.013 16.398 L 2.013 7.327 C 2.013 6.697 2.356 6.116 2.91 5.802 L 10.921 1.266 Z" fill="currentColor" stroke="currentColor" stroke-width="1"/><path d="M 21.122 6.009 C 21.677 6.324 22.019 6.904 22.019 7.534 L 22.019 16.606 C 22.019 17.235 21.677 17.816 21.122 18.131 L 13.11 22.667 C 12.555 22.981 11.872 22.981 11.314 22.667 L 10.388 22.142 C 10.772 21.78 11.159 21.413 11.55 21.047 C 12.722 19.945 13.901 18.834 14.928 17.765 C 15.953 16.698 16.825 15.667 17.382 14.721 C 17.936 13.778 18.187 12.902 17.93 12.154 C 17.671 11.401 16.913 10.813 15.54 10.415 C 13.986 9.966 12.92 9.457 12.272 8.908 C 11.628 8.362 11.403 7.78 11.507 7.17 C 11.617 6.55 12.069 5.883 12.824 5.18 C 13.572 4.488 14.606 3.77 15.874 3.039 L 21.122 6.009 Z" fill="currentColor" stroke="currentColor" stroke-width="1"/>"## }; +static VULTR: Icon = Icon { name: "vultr", view: 40.0, body: r##"<path d="M15.2983 4.60669C15.1614 4.38264 14.9695 4.19726 14.7409 4.06809C14.5123 3.93893 14.2545 3.87026 13.9919 3.86859H6.05C5.63892 3.86859 5.24467 4.03189 4.95399 4.32258C4.6633 4.61326 4.5 5.00751 4.5 5.41859C4.5 5.7108 4.58182 5.99716 4.73619 6.24526L6.78072 9.24931L17.0034 7.03502L15.2983 4.60669Z" fill="currentColor"/><path d="M17.0474 7.09406C16.9088 6.86991 16.7155 6.68462 16.4857 6.55553C16.256 6.42643 15.9972 6.35777 15.7336 6.35596H7.82122C7.53681 6.34284 7.25431 6.40869 7.00501 6.54622C6.75571 6.68375 6.54934 6.88758 6.40874 7.13516C6.26814 7.38274 6.1988 7.6644 6.2084 7.94895C6.218 8.23351 6.30616 8.50985 6.46312 8.74739L8.74384 12.3641L19.306 10.7107L17.0474 7.09406Z" fill="currentColor"/><path d="M8.64826 12.2164C8.52024 12.0113 8.44101 11.7795 8.4167 11.5389C8.39238 11.2984 8.42363 11.0554 8.50803 10.8288C8.62388 10.5331 8.82738 10.2799 9.09123 10.1031C9.35508 9.92633 9.66667 9.83444 9.98422 9.83977H17.8966C18.1603 9.84089 18.4194 9.90926 18.6493 10.0384C18.8792 10.1676 19.0723 10.3532 19.2104 10.5779L26.3183 21.8486C26.4727 22.0967 26.5545 22.3831 26.5545 22.6753C26.5533 22.9673 26.4716 23.2534 26.3183 23.5019L22.3473 29.7979C22.2067 30.0189 22.0125 30.2008 21.7829 30.3269C21.5532 30.4529 21.2955 30.519 21.0335 30.519C20.7716 30.519 20.5138 30.4529 20.2842 30.3269C20.0545 30.2008 19.8604 30.0189 19.7197 29.7979L8.64826 12.2164Z" fill="currentColor"/><path d="M28.6652 15.8184C28.8059 16.0394 29.0001 16.2213 29.2297 16.3474C29.4594 16.4734 29.7171 16.5395 29.9791 16.5395C30.241 16.5395 30.4988 16.4734 30.7284 16.3474C30.9581 16.2213 31.1522 16.0394 31.2929 15.8184L32.6583 13.6557L35.2638 9.52241C35.4182 9.27431 35.5 8.98794 35.5 8.69574C35.4989 8.4037 35.4171 8.11765 35.2638 7.86907L33.1972 4.60669C33.0585 4.38254 32.8652 4.19724 32.6355 4.06815C32.4057 3.93906 32.1469 3.8704 31.8833 3.86859H23.9414C23.7379 3.86859 23.5363 3.90868 23.3483 3.98658C23.1602 4.06447 22.9893 4.17865 22.8454 4.32258C22.7015 4.46651 22.5873 4.63738 22.5094 4.82543C22.4315 5.01349 22.3914 5.21504 22.3914 5.41859C22.3886 5.71224 22.4734 6.00007 22.635 6.24526L28.6652 15.8184Z" fill="currentColor"/>"## }; +static WANDB: Icon = Icon { name: "wandb", view: 24.0, body: r##"<path d="M9.8132 15.9038L9 18.75L8.1868 15.9038C7.75968 14.4089 6.59112 13.2403 5.09619 12.8132L2.25 12L5.09619 11.1868C6.59113 10.7597 7.75968 9.59112 8.1868 8.09619L9 5.25L9.8132 8.09619C10.2403 9.59113 11.4089 10.7597 12.9038 11.1868L15.75 12L12.9038 12.8132C11.4089 13.2403 10.2403 14.4089 9.8132 15.9038Z" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/><path d="M18.2589 8.71454L18 9.75L17.7411 8.71454C17.4388 7.50533 16.4947 6.56117 15.2855 6.25887L14.25 6L15.2855 5.74113C16.4947 5.43883 17.4388 4.49467 17.7411 3.28546L18 2.25L18.2589 3.28546C18.5612 4.49467 19.5053 5.43883 20.7145 5.74113L21.75 6L20.7145 6.25887C19.5053 6.56117 18.5612 7.50533 18.2589 8.71454Z" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/><path d="M16.8942 20.5673L16.5 21.75L16.1058 20.5673C15.8818 19.8954 15.3546 19.3682 14.6827 19.1442L13.5 18.75L14.6827 18.3558C15.3546 18.1318 15.8818 17.6046 16.1058 16.9327L16.5 15.75L16.8942 16.9327C17.1182 17.6046 17.6454 18.1318 18.3173 18.3558L19.5 18.75L18.3173 19.1442C17.6454 19.3682 17.1182 19.8954 16.8942 20.5673Z" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>"## }; +static XAI: Icon = Icon { name: "xai", view: 40.0, body: r##"<path d="M12.4579 15.6036L26.1529 35H20.0656L6.37059 15.6036H12.4579ZM12.4524 26.3764L15.4974 30.6909L12.4551 35H6.36377L12.4524 26.3764ZM33.6365 7.15727V35H28.647V14.2236L33.6365 7.15727ZM33.6365 5L20.0656 24.2205L17.0206 19.9073L27.5451 5H33.6365Z" fill="currentColor"/>"## }; +static XIAOMI: Icon = Icon { name: "xiaomi", view: 40.0, body: r##"<path d="M17.3598 5.03522C13.6378 5.20577 11.3905 5.78765 9.47432 7.07179C8.10992 7.97471 7.10668 9.14849 6.38435 10.6935C5.59179 12.389 5.24066 14.255 5.09017 17.7262C4.90959 21.6087 5.17043 25.4812 5.75231 27.5378C6.27399 29.4039 7.10668 30.8285 8.38079 32.0223C9.95588 33.487 11.7216 34.2595 14.4604 34.6709C16.9685 35.0421 22.7773 35.0621 25.3154 34.711C28.4054 34.2896 30.3718 33.4168 31.987 31.7414C32.7896 30.9187 33.1608 30.377 33.6824 29.2835C34.4951 27.5679 34.8261 25.7922 34.9867 22.2407C35.107 19.7026 34.9867 16.0909 34.7358 14.4055C34.1439 10.4527 32.4585 7.88441 29.519 6.39962C27.964 5.62713 25.6766 5.17567 22.4963 5.02519C20.0986 4.91483 19.7776 4.91483 17.3598 5.03522ZM21.0617 14.3854C22.386 14.6964 23.0281 15.1378 23.4494 16.0407C23.8808 16.9637 23.951 17.7262 23.951 21.8896V25.8022L22.5264 25.7721L21.0918 25.742L21.0417 21.9297C20.9915 17.7663 20.9714 17.6359 20.3895 17.1844C19.8679 16.7731 19.4264 16.7229 16.5772 16.7129H13.8685L13.8183 21.2275L13.7682 25.742H10.9591L10.929 20.0336C10.909 15.5291 10.939 14.2951 11.0293 14.2349C11.0996 14.1847 13.2365 14.1647 15.7747 14.1847C19.4967 14.2249 20.52 14.265 21.0617 14.3854ZM28.9472 14.3252C29.0174 14.4657 29.0475 25.3708 28.9773 25.722C28.9773 25.7621 28.3252 25.7822 27.5426 25.7721L26.108 25.742L26.0779 20.0838C26.0679 15.9906 26.0879 14.3854 26.1682 14.2951C26.2585 14.1847 26.6096 14.1546 27.5727 14.1546C28.6964 14.1546 28.8669 14.1747 28.9472 14.3252ZM18.9349 22.2307V25.8022L17.4601 25.7721L15.9753 25.742L15.9452 22.331C15.9352 20.455 15.9452 18.8598 15.9753 18.7996C16.0054 18.6993 16.3967 18.6692 17.4802 18.6692H18.9349V22.2307Z" fill="currentColor"/>"## }; +static ZAI: Icon = Icon { name: "zai", view: 40.0, body: r##"<path d="M20.1312 7.50002L17.4088 11.1913H5.81625L8.5375 7.50002H20.1325H20.1312ZM34.0675 28.81L31.3475 32.5H19.795L22.5125 28.81H34.0675ZM35 7.50002L16.58 32.5H5L23.42 7.50002H35Z" fill="currentColor"/>"## }; +static ZAI_CODING_PLAN: Icon = Icon { name: "zai-coding-plan", view: 40.0, body: r##"<path d="M20.1312 7.50002L17.4088 11.1913H5.81625L8.5375 7.50002H20.1325H20.1312ZM34.0675 28.81L31.3475 32.5H19.795L22.5125 28.81H34.0675ZM35 7.50002L16.58 32.5H5L23.42 7.50002H35Z" fill="currentColor"/>"## }; +static ZENMUX: Icon = Icon { name: "zenmux", view: 40.0, body: r##"<path d="M19.2587 5.29983C20.814 5.24008 23.9615 5.44575 26.4795 7.70668C28.5451 9.56134 29.2567 12.9997 28.7754 15.6659C28.3341 18.1098 27.2944 20.1094 27.7016 21.9609C28.1088 23.8124 29.1453 24.7252 30.027 25.1086C30.8787 25.4787 31.7019 25.3677 31.5452 26.0712C31.3884 26.7747 30.3233 27.0341 29.5455 27.0341C29.1191 27.0341 27.8294 26.9228 27.2572 26.5525C26.581 26.1149 26.4303 25.7228 26.1729 25.4075C26.1292 25.354 26.0521 25.3913 26.0624 25.4595C26.1797 26.2351 26.503 27.551 27.0276 28.3672C27.4521 29.0274 27.6275 29.5089 28.6 30.3236C29.5726 31.1381 30.0268 31.8787 29.0813 32.4033C28.2412 32.8691 26.4152 31.9159 25.3414 30.737C24.3749 29.6759 23.7019 28.367 23.4358 27.5154C23.2935 27.0601 23.151 26.2768 23.0087 25.6362C22.99 25.5519 22.8746 25.5655 22.8721 25.6518C22.8249 27.2822 22.5686 28.8393 22.1939 30.5087C21.9241 31.7105 21.2681 33.1747 20.6756 34.0635C19.9532 35.1471 18.8808 35.4853 18.0836 35.1891C17.446 34.952 17.8985 34.1463 18.0836 33.4487C18.2687 32.7513 18.6391 31.2923 18.8886 29.694C19.1144 28.2472 19.1741 26.8151 19.0735 25.4582C19.0673 25.3754 18.9402 25.3627 18.9144 25.4416C18.7066 26.078 18.3149 27.133 18.0292 27.7747C17.4332 29.1128 16.9922 29.7001 15.7702 31.1073C14.6712 32.3727 11.5105 34.1622 11.1045 32.4033C10.9935 31.922 11.5755 31.7112 12.1122 31.2923C12.9191 30.6629 13.5933 29.5459 14.2325 28.1819C14.8065 26.9571 15.0983 25.7724 15.1429 25.016C15.1472 24.943 15.0556 24.9155 15.0145 24.9758C14.7488 25.3656 14.3575 25.893 13.9266 26.3303C13.2067 27.0611 12.4083 27.8134 11.4824 28.1819C9.99368 28.7744 8.47556 28.367 8.58655 27.2934C8.67931 26.3963 9.68069 26.582 10.9272 25.222C12.1492 23.889 12.5564 22.8519 12.6305 21.704C12.6896 20.7857 11.7912 18.606 11.3345 17.6309C10.6063 16.0756 10.0681 11.6617 12.2603 8.81785C15.0004 5.26311 18.2959 5.33684 19.2587 5.29983ZM14.9842 11.5161C13.9647 11.5161 13.4549 12.2987 13.4549 13.2639C13.4549 14.2292 14.0213 15.0117 14.9842 15.0117C15.9471 15.0117 16.5135 14.2292 16.5135 13.2639C16.5135 12.2987 16.0038 11.5161 14.9842 11.5161Z" fill="currentColor" fill-rule="evenodd"/>"## }; +static ZHIPUAI: Icon = Icon { name: "zhipuai", view: 40.0, body: r##"<path d="M20.1312 7.50002L17.4088 11.1913H5.81625L8.5375 7.50002H20.1325H20.1312ZM34.0675 28.81L31.3475 32.5H19.795L22.5125 28.81H34.0675ZM35 7.50002L16.58 32.5H5L23.42 7.50002H35Z" fill="currentColor"/>"## }; +static ZHIPUAI_CODING_PLAN: Icon = Icon { name: "zhipuai-coding-plan", view: 40.0, body: r##"<path d="M20.1312 7.5L17.4088 11.1912H5.81625L8.5375 7.5H20.1325H20.1312ZM34.0675 28.81L31.3475 32.5H19.795L22.5125 28.81H34.0675ZM35 7.5L16.58 32.5H5L23.42 7.5H35Z" fill="currentColor"/>"## }; + +/// Desktop's mark for provider `id`, if it ships one. +pub fn named(id: &str) -> Option<&'static Icon> { + Some(match id { + "302ai" => &P302AI, + "abacus" => &ABACUS, + "aihubmix" => &AIHUBMIX, + "alibaba" => &ALIBABA, + "alibaba-cn" => &ALIBABA_CN, + "amazon-bedrock" => &AMAZON_BEDROCK, + "anthropic" => &ANTHROPIC, + "azure" => &AZURE, + "azure-cognitive-services" => &AZURE_COGNITIVE_SERVICES, + "bailing" => &BAILING, + "baseten" => &BASETEN, + "berget" => &BERGET, + "cerebras" => &CEREBRAS, + "chutes" => &CHUTES, + "claude-agent" => &CLAUDE_AGENT, + "cloudferro-sherlock" => &CLOUDFERRO_SHERLOCK, + "cloudflare-ai-gateway" => &CLOUDFLARE_AI_GATEWAY, + "cloudflare-workers-ai" => &CLOUDFLARE_WORKERS_AI, + "cohere" => &COHERE, + "cortecs" => &CORTECS, + "deepinfra" => &DEEPINFRA, + "deepseek" => &DEEPSEEK, + "digitalocean" => &DIGITALOCEAN, + "evroc" => &EVROC, + "fastrouter" => &FASTROUTER, + "fireworks-ai" => &FIREWORKS_AI, + "firmware" => &FIRMWARE, + "friendli" => &FRIENDLI, + "github-copilot" => &GITHUB_COPILOT, + "github-models" => &GITHUB_MODELS, + "gitlab" => &GITLAB, + "google" => &GOOGLE, + "google-vertex" => &GOOGLE_VERTEX, + "google-vertex-anthropic" => &GOOGLE_VERTEX_ANTHROPIC, + "groq" => &GROQ, + "helicone" => &HELICONE, + "huggingface" => &HUGGINGFACE, + "iflowcn" => &IFLOWCN, + "inception" => &INCEPTION, + "inference" => &INFERENCE, + "io-net" => &IO_NET, + "jiekou" => &JIEKOU, + "kilo" => &KILO, + "kimi-for-coding" => &KIMI_FOR_CODING, + "kuae-cloud-coding-plan" => &KUAE_CLOUD_CODING_PLAN, + "llama" => &LLAMA, + "lmstudio" => &LMSTUDIO, + "lucidquery" => &LUCIDQUERY, + "meganova" => &MEGANOVA, + "meituan" => &MEITUAN, + "meta" => &META, + "minimax" => &MINIMAX, + "minimax-cn" => &MINIMAX_CN, + "minimax-cn-coding-plan" => &MINIMAX_CN_CODING_PLAN, + "minimax-coding-plan" => &MINIMAX_CODING_PLAN, + "mistral" => &MISTRAL, + "moark" => &MOARK, + "modelscope" => &MODELSCOPE, + "moonshotai" => &MOONSHOTAI, + "moonshotai-cn" => &MOONSHOTAI_CN, + "morph" => &MORPH, + "nano-gpt" => &NANO_GPT, + "nebius" => &NEBIUS, + "nova" => &NOVA, + "novita-ai" => &NOVITA_AI, + "nvidia" => &NVIDIA, + "ollama-cloud" => &OLLAMA_CLOUD, + "openai" => &OPENAI, + "opencode" => &OPENCODE, + "opencode-go" => &OPENCODE_GO, + "openrouter" => &OPENROUTER, + "ovhcloud" => &OVHCLOUD, + "perplexity" => &PERPLEXITY, + "poe" => &POE, + "privatemode-ai" => &PRIVATEMODE_AI, + "qihang-ai" => &QIHANG_AI, + "qiniu-ai" => &QINIU_AI, + "reflection" => &REFLECTION, + "requesty" => &REQUESTY, + "sap-ai-core" => &SAP_AI_CORE, + "scaleway" => &SCALEWAY, + "siliconflow" => &SILICONFLOW, + "siliconflow-cn" => &SILICONFLOW_CN, + "stackit" => &STACKIT, + "stepfun" => &STEPFUN, + "submodel" => &SUBMODEL, + "synthetic" => &SYNTHETIC, + "togetherai" => &TOGETHERAI, + "upstage" => &UPSTAGE, + "v0" => &V0, + "venice" => &VENICE, + "vercel" => &VERCEL, + "vivgrid" => &VIVGRID, + "vultr" => &VULTR, + "wandb" => &WANDB, + "xai" => &XAI, + "xiaomi" => &XIAOMI, + "zai" => &ZAI, + "zai-coding-plan" => &ZAI_CODING_PLAN, + "zenmux" => &ZENMUX, + "zhipuai" => &ZHIPUAI, + "zhipuai-coding-plan" => &ZHIPUAI_CODING_PLAN, + _ => return None, + }) +} + +/// The providers that have a mark of their own, in `named`. +pub const NAMES: &[&str] = &[ + "302ai", + "abacus", + "aihubmix", + "alibaba", + "alibaba-cn", + "amazon-bedrock", + "anthropic", + "azure", + "azure-cognitive-services", + "bailing", + "baseten", + "berget", + "cerebras", + "chutes", + "claude-agent", + "cloudferro-sherlock", + "cloudflare-ai-gateway", + "cloudflare-workers-ai", + "cohere", + "cortecs", + "deepinfra", + "deepseek", + "digitalocean", + "evroc", + "fastrouter", + "fireworks-ai", + "firmware", + "friendli", + "github-copilot", + "github-models", + "gitlab", + "google", + "google-vertex", + "google-vertex-anthropic", + "groq", + "helicone", + "huggingface", + "iflowcn", + "inception", + "inference", + "io-net", + "jiekou", + "kilo", + "kimi-for-coding", + "kuae-cloud-coding-plan", + "llama", + "lmstudio", + "lucidquery", + "meganova", + "meituan", + "meta", + "minimax", + "minimax-cn", + "minimax-cn-coding-plan", + "minimax-coding-plan", + "mistral", + "moark", + "modelscope", + "moonshotai", + "moonshotai-cn", + "morph", + "nano-gpt", + "nebius", + "nova", + "novita-ai", + "nvidia", + "ollama-cloud", + "openai", + "opencode", + "opencode-go", + "openrouter", + "ovhcloud", + "perplexity", + "poe", + "privatemode-ai", + "qihang-ai", + "qiniu-ai", + "reflection", + "requesty", + "sap-ai-core", + "scaleway", + "siliconflow", + "siliconflow-cn", + "stackit", + "stepfun", + "submodel", + "synthetic", + "togetherai", + "upstage", + "v0", + "venice", + "vercel", + "vivgrid", + "vultr", + "wandb", + "xai", + "xiaomi", + "zai", + "zai-coding-plan", + "zenmux", + "zhipuai", + "zhipuai-coding-plan", +]; + +/// Desktop's stand-in for a provider with no mark of its own. +pub static FALLBACK: &Icon = &SYNTHETIC; diff --git a/app/vendor/rune/themes/opencode/src/tree_icons.rs b/app/vendor/rune/themes/opencode/src/tree_icons.rs new file mode 100644 index 0000000..d5d2db9 --- /dev/null +++ b/app/vendor/rune/themes/opencode/src/tree_icons.rs @@ -0,0 +1,94 @@ +//! The file icons of Desktop's file trees and file lists (Files, Review, the files filter): the +//! monochrome "complete" set of `@pierre/trees`, which Desktop draws in `--v2-icon-icon-muted` and, +//! on the selected row, in the file type's colour (`file-tree.css`). Folders show only the +//! [`CHEVRON`], turned a quarter clockwise while open. +//! +//! ```ignore +//! let t = tree_icons::file(&node.path); +//! icon(t.icon(), 16.0).color(if selected { t.color(dark) } else { k.c.icon_muted }) +//! ``` + +mod catalog; + +use rune::{Color, Icon, TextStyle}; +use rune_kit::{Kit, TreeItem, TreeStyle}; + +/// A folder row's disclosure (`outline-chevron-right`, 16 points), drawn 1 point low. +pub static CHEVRON: &Icon = &crate::icons::OUTLINE_CHEVRON_RIGHT; + +/// A file's icon in a file tree and its type (`typescript`, `json`, `default`). +#[derive(Clone, Copy, Debug)] +pub struct TreeIcon { + token: &'static str, +} + +impl TreeIcon { + pub fn icon(&self) -> &'static Icon { + catalog::icon(self.token) + } + /// The file type, as `@pierre/trees` names it (`data-icon-token`). + pub fn token(&self) -> &'static str { + self.token + } + /// The type's colour for one appearance (`--trees-file-icon-color-<token>`), which a selected + /// row draws its icon in. + pub fn color(&self, dark: bool) -> Color { + let (light, night) = catalog::tint(self.token); + rune::color::hex(if dark { night } else { light }).unwrap_or(Color::TRANSPARENT) + } +} + +/// The icon for a file at `path` (`/` or `\` separated, or just a name): its whole name first +/// (`bun.lock`, `Dockerfile`), then each dotted suffix from the first dot (`config.ts`, then `ts`), +/// `.tsx` and `.jsx` as React and `.scss` and `.sass` as Sass, else the plain file. +pub fn file(path: &str) -> TreeIcon { + let name = path.rsplit(['/', '\\']).find(|s| !s.is_empty()).unwrap_or("").to_lowercase(); + let suffix = || { + name.match_indices('.') + .map(|(i, _)| &name[i + 1..]) + .find_map(|s| catalog::complete_override(s).or_else(|| catalog::by_extension(s))) + }; + TreeIcon { token: catalog::by_file_name(&name).or_else(suffix).unwrap_or("default") } +} + +/// Desktop's file tree rows (`pierre-tree.tsx` over `@pierre/trees`): 28 points tall with 8 at +/// the ends, 6 between the chevron or icon and the name, 21.5 per level, 6-point corners, 12-point +/// medium names in `text-muted` (`text-base` and the pressed overlay when selected, the hover +/// overlay under the pointer), chevron-only folders with the chevron 1 point low, guides at 0.75 +/// only while the pointer is over the tree, and long names fading out over 16 points. +pub fn style(k: &Kit) -> TreeStyle { + let t = crate::theme(k.dark); + let v = |n: &str| t.color(&format!("v2-{n}")); + let mut s = TreeStyle::from_kit(k) + .hover(v("overlay-simple-overlay-hover")) + .gap(6.0) + .radius(6.0) + .label(TextStyle::new(12.0, 500.0).lh(28.0), v("text-text-muted"), v("text-text-base")) + .fade_long_labels(16.0) + .chevron_only_folders(true) + .chevron(&crate::icons::CHEVRON_DOWN) + .chevron_nudge(1.0) + .chevron_colors(v("icon-icon-muted"), v("text-text-base")) + .guides_on_hover(0.75); + (s.row_height, s.indent, s.padding) = (28.0, 21.5, 8.0); + s.guide = v("border-border-muted").alpha(v("border-border-muted").a * 0.5); + s.selected = v("overlay-simple-overlay-pressed"); + s +} + +/// A file tree row as Desktop draws it under [`style`]: the name, and for a file its icon in +/// `icon-muted`, or in its type's colour while selected. Folders show only the chevron. +pub fn item(name: &str, path: &str, folder: bool, selected: bool, dark: bool) -> TreeItem { + let item = TreeItem::new(name); + if folder { + return item; + } + let t = file(path); + let muted = crate::theme(dark).color("v2-icon-icon-muted"); + item.icon(t.icon()).icon_color(if selected { t.color(dark) } else { muted }) +} + +/// Every file type with an icon of its own, for a gallery. +pub fn all() -> impl Iterator<Item = TreeIcon> { + catalog::TOKENS.iter().map(|&token| TreeIcon { token }) +} diff --git a/app/vendor/rune/themes/opencode/src/tree_icons/catalog.rs b/app/vendor/rune/themes/opencode/src/tree_icons/catalog.rs new file mode 100644 index 0000000..3773e7c --- /dev/null +++ b/app/vendor/rune/themes/opencode/src/tree_icons/catalog.rs @@ -0,0 +1,677 @@ +//! Generated by tools/tree-icons.py from @pierre/trees's complete icon set. Do not edit. +use rune::Icon; + +static ASTRO: Icon = Icon { + name: "file-tree-astro", + view: 16.0, + body: r#"<path fill="currentColor" d="M6.08 13.92c-.63-.57-.81-1.79-.55-2.67.45.56 1.08.73 1.73.83 1 .15 1.99.1 2.92-.37l.32-.19q.13.38.08.78a2.1 2.1 0 0 1-.9 1.5q-.3.24-.61.43c-.64.44-.81.95-.57 1.69l.02.08a1.7 1.7 0 0 1-.74-.64 2 2 0 0 1-.3-.98q0-.27-.02-.52-.07-.61-.61-.62a.7.7 0 0 0-.75.6z" opacity=".6"/><path fill="currentColor" d="M2.5 11.1s1.86-.9 3.72-.9l1.4-4.39c.05-.21.2-.36.38-.36s.33.15.38.36l1.4 4.38c2.2 0 3.72.92 3.72.92l-3.16-8.69q-.13-.4-.45-.42H6.11q-.3.02-.45.42z"/>"#, +}; +static BABEL: Icon = Icon { + name: "file-tree-babel", + view: 16.0, + body: r#"<path fill="currentColor" fill-rule="evenodd" d="M9.49.5q1.92.05 2.66.54 1.27.6 1.35 1.52v.23a4 4 0 0 1-.53 1.9l-1.38 1.24q-.74.38-.72.63c.77.82 1.33 1.29.85 2.42q-.47 1.1-2.04 2.28c-.5.32-1.88 1.35-2.96 1.86-1.64.77-3.1 1.4-4.65 1.89-.51.16-1.5.16-1.5.16L.5 15A76 76 0 0 0 5.76 3.49q-.1-.08-.1-.2.1 0 .32-.35l-.03-.09q-1.17.39-2.38 1.3l-.13.03q0-.1-.21-.16-.46.31-.82.7l-.13-.19.16-.06-.03-.16-.34.29L2 4.5q.36-.48.72-.54l.04-.1V3.8q.16 0 .15-.06l.13-.06a6 6 0 0 0 1.13-.9v-.03H4.1l-.12.07q0-.1-.1-.1l-.15.07-.04-.1q.93-.52 1.63-1.05Q7.89.65 9.5.5M8.46 7.83l-.32.04c-1.31.54-2.31.82-2.91.88a71 71 0 0 0-2.2 4.54h.07q.58-.04 3.04-1.42.13 0 1.66-1.05L9.18 9.7v.03q.45-.2.81-1.3v-.2q-.5-.46-1.53-.4m.28-5.75c-.5.1-.75.19-.72.38l-1.16 2.6q-.17.1-.34.95-.3.48-.25.77v.1l.22.05A15 15 0 0 1 8.86 6c1.1-.71 2.12-1.38 2.8-2.54q.24-.33.21-.54-.02-.33-.4-.54c-.54 0-1.07-.34-1.63-.28l-.94-.03z" clip-rule="evenodd"/>"#, +}; +static BASH: Icon = Icon { + name: "file-tree-bash", + view: 16.0, + body: r#"<path fill="currentColor" d="M8 1C2.24 1 1 2.24 1 8s1.24 7 7 7 7-1.24 7-7-1.24-7-7-7" opacity=".2"/><path fill="currentColor" d="M11.5 11a.5.5 0 0 1 0 1h-3a.5.5 0 0 1 0-1zM7 6.75C7 6.42 6.64 6 6 6s-1 .42-1 .75q-.01.25.22.41.26.21.89.35.74.14 1.28.53c.37.29.61.7.61 1.21 0 .87-.68 1.5-1.5 1.7v.55a.5.5 0 0 1-1 0v-.56c-.82-.18-1.5-.82-1.5-1.69a.5.5 0 0 1 1 0c0 .33.36.75 1 .75s1-.42 1-.75q.01-.25-.22-.41a2 2 0 0 0-.89-.35q-.74-.14-1.28-.53A1.5 1.5 0 0 1 4 6.75c0-.87.68-1.5 1.5-1.7V4.5a.5.5 0 0 1 1 0v.56c.82.18 1.5.82 1.5 1.69a.5.5 0 0 1-1 0"/>"#, +}; +static BIOME: Icon = Icon { + name: "file-tree-biome", + view: 16.0, + body: r#"<path fill="currentColor" d="M8 2 4.88 7.35a7 7 0 0 1 3.7-.13l1.04.25-.99 4.16-1.05-.25a2.7 2.7 0 0 0-3.07 1.45l-.98-.47a4 4 0 0 1 1.07-1.31 3.8 3.8 0 0 1 3.23-.71l.5-2.08a6 6 0 0 0-5.07 1.12A5.9 5.9 0 0 0 1 14h14z"/>"#, +}; +static BOOTSTRAP: Icon = Icon { + name: "file-tree-bootstrap", + view: 16.0, + body: r#"<path fill="currentColor" fill-rule="evenodd" d="M11.72 1.5A2.5 2.5 0 0 1 14.2 4q.02 1.08.3 2.09c.22.73.56 1.24 1.08 1.45.22.08.4.27.4.5s-.18.43-.4.51q-.76.34-1.08 1.45c-.2.65-.27 1.32-.3 2a2.5 2.5 0 0 1-2.48 2.5H4.25A2.6 2.6 0 0 1 1.7 12c-.04-.85-.1-1.68-.22-2.04C1.26 9.23.92 8.7.4 8.5.18 8.42 0 8.23 0 8s.18-.42.4-.5q.77-.35 1.09-1.46c.1-.36.17-1.19.2-2.04a2.6 2.6 0 0 1 2.56-2.5z" clip-rule="evenodd" opacity=".2"/><path fill="currentColor" fill-rule="evenodd" d="M8.47 4.54c1.23 0 2.04.68 2.04 1.73 0 .73-.55 1.39-1.24 1.5v.04c.94.1 1.58.77 1.58 1.7 0 1.2-.9 1.95-2.37 1.95H5.97a.3.3 0 0 1-.2-.08.3.3 0 0 1-.08-.2V4.82a.3.3 0 0 1 .08-.2.3.3 0 0 1 .2-.08zm-1.7 6.04h1.49q1.47-.01 1.49-1.15Q9.74 8.31 8.2 8.3H6.77zm0-5.16v2.06h1.21c.93 0 1.45-.38 1.45-1.06 0-.65-.44-1-1.22-1z" clip-rule="evenodd"/>"#, +}; +static BROWSERSLIST: Icon = Icon { + name: "file-tree-browserslist", + view: 16.0, + body: r#"<path fill="currentColor" d="M8.88 6.96c0 3.82 3.72 4.7 5.7 3.74-.23.9-1.04 1.67-2.35 1.93-.02.4.42 1.28.82 1.63-.9.35-1.94-.12-2.51-.48a5 5 0 0 0-.32 1.87c-.68 0-1.57-1-1.8-1.37-.3.18-.85 1.15-.96 1.72a2.4 2.4 0 0 1-.81-.86 2.4 2.4 0 0 1-.3-1.15c-.38.27-1.48.95-1.99 1.18-.25-.58-.15-1.3 0-2.06-.21.12-1.8.27-2.43.12.32-.36.75-1.19.94-1.57A4.5 4.5 0 0 1 .44 10.6c.48-.22.97-.53 1.49-1.06C1.26 9.17.24 8.64 0 7.7a6 6 0 0 0 1.79-.32C1.28 7.08.44 6.15.6 5.01c.42.21 1.3.37 1.73.3a3.4 3.4 0 0 1-.25-2.75 5 5 0 0 0 1.48 1c-.08-.8.3-2.31.8-2.71.2.46.73 1.21 1.08 1.4.09-.61.87-2.06 1.57-2.25 0 .5.27 1.4.5 1.67.51-.54 2.25-1.44 3.64-1.13-.43.45-.75.61-.86.98 1.05 0 2.78.34 4.27 1.93-2.34-.89-5.69.56-5.69 3.5" opacity=".5"/><path fill="currentColor" d="M11.21 3.59a4.1 4.1 0 0 0 2.47 2.89c.24-.22.61-.38.95-.19.76.44.2 1.26-.34 1.66l-.07.06a13 13 0 0 1-4.49 1.61l-.3-.43a10.5 10.5 0 0 0 4.13-1.31 1 1 0 0 0 .23-.25.5.5 0 0 0-.21-.69l-.15-.06a4.5 4.5 0 0 1-1.77-1.31 4.5 4.5 0 0 1-.88-1.77q.2-.12.43-.21"/><path fill="currentColor" d="M10.36 5.18a.4.4 0 0 0-.03.38c.09.2.3.3.46.23s.24-.3.15-.5l-.01-.02q.23.13.34.39a.83.83 0 0 1-.43 1.08.8.8 0 0 1-1.08-.43.83.83 0 0 1 .6-1.13"/>"#, +}; +static BUN: Icon = Icon { + name: "file-tree-bun", + view: 16.0, + body: r#"<path fill="currentColor" d="M8 14c3.87 0 7-2.46 7-5.49 0-1.88-1.2-3.53-3.04-4.52q-1.1-.61-1.84-1.07C9.2 2.35 8.64 2 8 2s-1.36.45-2.31 1.03A29 29 0 0 1 4.04 4C2.2 4.98 1 6.63 1 8.51 1 11.54 4.13 14 8 14M7.18 3.88q.3-.66.3-1.37c0-.08.11-.1.13-.01.38 1.57-.53 2.35-1.2 2.61-.08.03-.12-.07-.06-.12a3 3 0 0 0 .83-1.12m1.2-.05a3 3 0 0 0-.45-1.3V2.5c-.04-.07.05-.15.1-.1 1.15 1.2.77 2.3.33 2.87-.05.05-.13 0-.11-.08q.21-.67.13-1.37m1.04-.32a3 3 0 0 0-.94-1.02v-.01c-.06-.05-.01-.16.07-.12 1.51.61 1.61 1.8 1.43 2.5l-.03.03a.07.07 0 0 1-.1-.06 3 3 0 0 0-.43-1.32m-2.97.32c-.36.3-.74.43-1.2.56q-.11 0-.1-.1a3.5 3.5 0 0 0 1.76-1.57s.09-.07.1.04c0 .18-.2.76-.56 1.07m2.89 6.36q-.13.52-.55.88a1.3 1.3 0 0 1-.75.35 1.3 1.3 0 0 1-.77-.35 1.7 1.7 0 0 1-.54-.88.13.13 0 0 1 .15-.15h2.31a.14.14 0 0 1 .15.15M6.15 8.95a1.1 1.1 0 0 1-1.39-.14A1.1 1.1 0 0 1 5.12 7a1.1 1.1 0 0 1 1.2.25 1.1 1.1 0 0 1-.17 1.69m4.96 0a1.1 1.1 0 0 1-1.4-.14 1.1 1.1 0 0 1 .37-1.8 1.1 1.1 0 0 1 1.2.25 1.1 1.1 0 0 1 .24 1.2 1 1 0 0 1-.41.5"/>"#, +}; +static C: Icon = Icon { + name: "file-tree-c", + view: 16.0, + body: r#"<path fill="currentColor" fill-rule="evenodd" d="M8 1q.084 0 .166.021.098.023.186.075c1.055.624 4.22 2.486 5.277 3.11.085.05.15.112.209.192h-.002l.028.037a.5.5 0 0 1 .103.21q.031.102.033.21v6.29a.71.71 0 0 1-.347.616l-5.307 3.144a.68.68 0 0 1-.693 0l-5.307-3.144A.72.72 0 0 1 2 11.145V4.832a.71.71 0 0 1 .346-.612l5.288-3.126A.7.7 0 0 1 7.992 1zm2.901 4.349a3.75 3.75 0 1 0 0 5.302l-1.06-1.06a2.25 2.25 0 1 1 0-3.182z" clip-rule="evenodd"/>"#, +}; +static CLAUDE: Icon = Icon { + name: "file-tree-claude", + view: 16.0, + body: r#"<path fill="currentColor" d="M3.75 10.31 6.5 8.77l.04-.14-.04-.07h-.14l-.46-.03-1.57-.04-1.38-.07-1.33-.07-.34-.07L1 7.86l.03-.21.28-.18.4.03.89.07 1.33.08.97.06 1.43.16h.22l.03-.1-.07-.05-.06-.06-1.39-.92-1.48-.98-.79-.57-.42-.28-.2-.28-.1-.6.39-.41.52.04.12.03.52.4 1.12.86L6.2 6.04l.2.17.09-.06.01-.04-.1-.15-.76-1.46-.85-1.46-.37-.6-.1-.36a1 1 0 0 1-.06-.42l.42-.59.25-.07.6.08.22.2.36.84.58 1.3.9 1.77.29.53.14.47.04.14h.1v-.07l.07-1 .14-1.22.14-1.57.04-.45.23-.53.42-.28.36.15.28.41-.04.25-.16 1.08-.36 1.7-.21 1.14h.12l.14-.15.58-.76.97-1.2.42-.5.5-.51.32-.25h.6l.44.66-.2.68-.61.79-.52.65-.74 1-.45.8.04.05h.1l1.68-.36.9-.16 1.06-.18.5.23.05.22-.2.48-1.15.28-1.34.28-2 .46-.04.01.03.04.9.09.4.03h.94l1.77.14.46.28.27.37-.04.28-.72.37-.95-.23-2.24-.53-.76-.18h-.11v.06l.64.63L12 10.86l1.48 1.35.07.34-.18.28-.2-.03-1.29-.98-.5-.42-1.12-.95h-.07v.1l.25.38 1.37 2.05.07.63-.1.2-.36.14-.38-.08-.8-1.12-.85-1.26-.66-1.15-.07.05-.4 4.23-.19.21-.42.17-.35-.28-.2-.42.2-.87.23-1.12.18-.9.17-1.1.1-.36v-.03h-.1l-.84 1.16-1.27 1.72-1 1.07-.24.1-.42-.22.04-.39.22-.32 1.4-1.8.84-1.1.57-.64-.02-.07h-.04l-3.7 2.4-.66.09-.28-.28.03-.42.14-.14 1.12-.77z"/>"#, +}; +static CPP: Icon = Icon { + name: "file-tree-cpp", + view: 16.0, + body: r#"<path fill="currentColor" fill-rule="evenodd" d="M8 1q.084 0 .166.021.098.023.186.075c1.055.624 4.22 2.486 5.277 3.11.085.05.15.112.209.192h-.002l.028.037a.5.5 0 0 1 .103.21q.031.102.033.21v6.29a.71.71 0 0 1-.347.616l-5.307 3.144a.68.68 0 0 1-.693 0l-5.307-3.144A.72.72 0 0 1 2 11.145V4.832a.71.71 0 0 1 .346-.612l5.288-3.126A.7.7 0 0 1 7.992 1zm2.901 4.349a3.75 3.75 0 1 0 0 5.302l-1.06-1.06a2.25 2.25 0 1 1 0-3.182z" clip-rule="evenodd"/>"#, +}; +static CSS: Icon = Icon { + name: "file-tree-css", + view: 16.0, + body: r#"<path fill="currentColor" d="M8 15c-5.76 0-7-1.24-7-7V2a1 1 0 0 1 1-1h6c5.77 0 7 1.24 7 7s-1.24 7-7 7" opacity=".2"/><path fill="currentColor" d="M10.1 9.19h.73c.03.49.22.6 1 .6.76 0 .93-.12.93-.68 0-.52-.17-.67-.94-.85-1.38-.3-1.68-.56-1.68-1.47 0-1.05.3-1.29 1.67-1.29 1.29 0 1.57.2 1.6 1.13h-.74c-.01-.34-.17-.42-.85-.42-.77 0-.94.1-.94.58 0 .42.17.55.96.73 1.36.3 1.66.58 1.66 1.59 0 1.14-.31 1.39-1.73 1.39-1.39 0-1.69-.24-1.67-1.31m-3.9 0h.74c.03.49.21.6.99.6.76 0 .93-.12.93-.68 0-.52-.17-.67-.93-.85-1.39-.3-1.69-.56-1.69-1.47 0-1.05.3-1.29 1.67-1.29 1.3 0 1.58.2 1.6 1.13h-.73c-.02-.34-.18-.42-.85-.42-.78 0-.95.1-.95.58 0 .42.17.55.96.73 1.37.3 1.67.58 1.67 1.59 0 1.14-.32 1.39-1.74 1.39-1.38 0-1.68-.24-1.66-1.31m-1.22 0h.75c-.09 1.07-.37 1.31-1.56 1.31-1.37 0-1.68-.45-1.68-2.5 0-1.96.36-2.5 1.68-2.5 1.16 0 1.44.25 1.52 1.35h-.76c-.08-.52-.22-.64-.76-.64-.74 0-.9.33-.9 1.78 0 1.47.16 1.8.9 1.8.58 0 .74-.11.8-.6"/>"#, +}; +static DATABASE: Icon = Icon { + name: "file-tree-database", + view: 16.0, + body: r#"<path fill="currentColor" d="M14.953 9.733a12.4 12.4 0 0 1-.244 1.936c-.207.933-.532 1.58-.996 2.044s-1.11.789-2.044.996C10.73 14.918 9.533 15 8 15s-2.73-.082-3.669-.291c-.933-.207-1.58-.532-2.044-.996s-.789-1.11-.996-2.044c-.122-.547-.2-1.182-.244-1.92q.23.364.532.667c.64.639 1.482 1.031 2.533 1.265 1.046.232 2.33.315 3.884.315 1.555 0 2.838-.083 3.884-.315 1.051-.234 1.893-.626 2.532-1.265a4 4 0 0 0 .541-.683"/><path fill="currentColor" d="M14.93 5.924c-.046.663-.118 1.24-.23 1.743-.207.932-.532 1.579-.995 2.042s-1.11.789-2.042.996c-.938.209-2.135.291-3.667.291-1.531 0-2.729-.082-3.667-.29-.932-.208-1.579-.534-2.042-.997s-.789-1.11-.996-2.042a12 12 0 0 1-.227-1.683l.016-.188a4 4 0 0 0 .5.62c.638.639 1.48 1.031 2.532 1.265 1.046.232 2.33.315 3.884.315 1.555 0 2.838-.083 3.884-.315 1.051-.234 1.893-.626 2.532-1.265.192-.192.357-.404.506-.633z"/><path fill="currentColor" d="M8 1c1.533 0 2.73.082 3.669.291.933.207 1.58.533 2.044.996.403.404.904.944.91 1.695.004.764-.509 1.318-.918 1.727-.463.463-1.11.789-2.042.996-.938.209-2.135.291-3.667.291-1.531 0-2.729-.082-3.667-.29-.932-.208-1.579-.534-2.042-.997-.406-.406-.915-.953-.915-1.71 0-.758.509-1.305.915-1.712.464-.463 1.11-.789 2.044-.996C5.27 1.082 6.467 1 8 1"/>"#, +}; +static DEFAULT: Icon = Icon { + name: "file-tree-default", + view: 16.0, + body: r#"<path fill="currentColor" d="M8 1v3a3 3 0 0 0 3 3h3v5.5a2.5 2.5 0 0 1-2.5 2.5h-7A2.5 2.5 0 0 1 2 12.5v-9A2.5 2.5 0 0 1 4.5 1z" opacity=".4"/><path fill="currentColor" d="M9.5 1a.5.5 0 0 1 .354.146l4 4A.5.5 0 0 1 14 5.5V6h-3a2 2 0 0 1-2-2V1z"/>"#, +}; +static DOCKER: Icon = Icon { + name: "file-tree-docker", + view: 16.0, + body: r#"<path fill="currentColor" d="M15.85 6.54c-.05-.04-.45-.36-1.31-.36q-.34 0-.68.06a2.7 2.7 0 0 0-1.14-1.79l-.23-.14-.15.23a3 3 0 0 0-.4 1q-.24 1.01.26 1.84c-.4.24-1.03.3-1.17.3H.5a.5.5 0 0 0-.5.52q-.01 1.46.46 2.83.55 1.5 1.6 2.18c.79.5 2.08.79 3.54.79q.96 0 1.94-.18a8 8 0 0 0 2.55-.97 7 7 0 0 0 1.73-1.5 10 10 0 0 0 1.7-3.06h.15a2.4 2.4 0 0 0 1.8-.7 2 2 0 0 0 .47-.74l.06-.2z"/><path fill="currentColor" d="M1.48 7.36h1.4a.14.14 0 0 0 .14-.13V5.91q-.01-.12-.13-.14H1.48a.13.13 0 0 0-.13.14v1.32q.02.13.13.13m1.94 0h1.41a.14.14 0 0 0 .13-.13V5.91q-.01-.12-.13-.14h-1.4a.13.13 0 0 0-.13.14v1.32q0 .13.12.13m1.98 0h1.4q.13 0 .14-.13V5.91a.13.13 0 0 0-.14-.14H5.4q-.1.01-.12.14v1.32q0 .13.12.13m1.95 0h1.42q.1 0 .12-.13V5.91q0-.12-.12-.14H7.35q-.1.01-.12.14v1.32q.01.13.12.13M3.42 5.5h1.41c.07 0 .13-.08.13-.15V4.03a.13.13 0 0 0-.13-.14h-1.4q-.12 0-.13.14v1.31q0 .13.12.15m1.98 0h1.4c.08 0 .14-.08.14-.15V4.03q0-.13-.14-.14H5.4q-.1 0-.12.14v1.31q0 .13.12.15m1.95 0h1.42c.06 0 .12-.08.12-.15V4.03q-.01-.13-.12-.14H7.35q-.1 0-.12.14v1.31q.01.13.12.15m0-1.9h1.42q.1-.02.12-.14v-1.3Q8.88 2 8.77 2H7.35q-.1 0-.12.14v1.3q.01.13.12.14m1.97 3.78h1.4a.13.13 0 0 0 .14-.13V5.91q-.01-.12-.13-.14H9.32q-.1.01-.12.14v1.32q.01.13.12.13" opacity=".5"/>"#, +}; +static ESLINT: Icon = Icon { + name: "file-tree-eslint", + view: 16.0, + body: r#"<path fill="currentColor" d="M11.16 6.1 8.12 4.35a.3.3 0 0 0-.24 0L4.84 6.1a.3.3 0 0 0-.12.2v3.5q0 .14.12.22l3.04 1.74q.12.08.24 0l3.04-1.74a.2.2 0 0 0 .13-.22V6.3a.3.3 0 0 0-.13-.2" opacity=".5"/><path fill="currentColor" d="m.1 7.69 3.63-6.3A.8.8 0 0 1 4.37 1h7.26c.26 0 .5.17.64.4l3.63 6.27a.8.8 0 0 1 0 .75l-3.63 6.24a.7.7 0 0 1-.64.34H4.37a.7.7 0 0 1-.64-.34L.1 8.41a.7.7 0 0 1 0-.72m3 3.02q.01.15.14.23l4.63 2.66q.13.06.26 0l4.63-2.66a.3.3 0 0 0 .14-.23V5.4a.3.3 0 0 0-.14-.23L8.13 2.52a.3.3 0 0 0-.26 0L3.24 5.17a.3.3 0 0 0-.14.23z"/>"#, +}; +static FONT: Icon = Icon { + name: "file-tree-font", + view: 16.0, + body: r#"<path fill="currentColor" d="M12.3 13c-1.59 0-2.68-.99-2.68-2.5 0-1.43 1-2.34 2.88-2.35h2.16v-.83c0-1.08-.62-1.68-1.73-1.68-1.05 0-1.66.54-1.73 1.36H9.93c.09-1.43 1.06-2.48 3.05-2.48 1.75 0 3.02.95 3.02 2.68v5.66h-1.29v-1.02h-.04c-.41.66-1.16 1.16-2.37 1.16m.36-1.12c1.14 0 2-.72 2-1.74v-.96H12.6c-1.12 0-1.6.54-1.6 1.28 0 .97.8 1.42 1.66 1.42m-11.24.98H0L3.8 2h1.39l3.8 10.86H7.54l-1.08-3.2H2.5zm3.09-9.25h-.04l-1.6 4.95H6.1z"/>"#, +}; +static GIT: Icon = Icon { + name: "file-tree-git", + view: 16.0, + body: r#"<path fill="currentColor" d="M14.74 7.38 8.62 1.26a.9.9 0 0 0-1.27 0L6.08 2.53l1.61 1.61a1.07 1.07 0 0 1 1.36 1.37l1.55 1.55a1.07 1.07 0 0 1 1.1 1.77 1.07 1.07 0 0 1-1.74-1.16L8.5 6.22v3.8a1.07 1.07 0 1 1-.89-.02V6.15a1.07 1.07 0 0 1-.58-1.4l-1.58-1.6-4.2 4.2a.9.9 0 0 0 0 1.27l6.12 6.12a.9.9 0 0 0 1.27 0l6.09-6.09a.9.9 0 0 0 0-1.27"/>"#, +}; +static GO: Icon = Icon { + name: "file-tree-go", + view: 16.0, + body: r#"<path fill="currentColor" fill-rule="evenodd" d="M4.41 4.57A3.2 3.2 0 0 1 6.87 5q.74.49 1.08 1.29.08.12-.1.16l-1.55.4c-.14.03-.15.04-.27-.1a1 1 0 0 0-.44-.34 1.6 1.6 0 0 0-1.68.14q-.95.61-.94 1.73c0 .73.52 1.33 1.25 1.43q.95.1 1.58-.6l.25-.34h-1.8c-.19 0-.24-.12-.17-.27.12-.28.34-.76.47-1a.3.3 0 0 1 .24-.14h2.98a4 4 0 0 1 .64-1.19 4 4 0 0 1 2.6-1.52 3.5 3.5 0 0 1 2.64.46q1.13.73 1.31 2.04a3.5 3.5 0 0 1-1.06 3.09q-.93.92-2.23 1.17l-.74.08a3.5 3.5 0 0 1-2.27-.8 3 3 0 0 1-.93-1.42 4 4 0 0 1-.39.61 4 4 0 0 1-2.64 1.56 3.3 3.3 0 0 1-2.5-.6 3 3 0 0 1-1.18-2.03 3.5 3.5 0 0 1 .8-2.67 4 4 0 0 1 2.6-1.58M13.1 7.5a1.53 1.53 0 0 0-1.9-1.21q-1.3.3-1.62 1.59a1.5 1.5 0 0 0 .85 1.72q.77.33 1.52-.05a2 2 0 0 0 1.18-1.74q0-.17-.03-.3" clip-rule="evenodd"/>"#, +}; +static GRAPHQL: Icon = Icon { + name: "file-tree-graphql", + view: 16.0, + body: r#"<path fill="currentColor" fill-rule="evenodd" d="M8 1a1.25 1.25 0 0 1 1.18 1.65l2.8 1.61q.33-.25.77-.26a1.25 1.25 0 0 1 .48 2.4v3.2a1.25 1.25 0 1 1-1.25 2.13l-2.8 1.62A1.25 1.25 0 0 1 8 15a1.25 1.25 0 0 1-1.18-1.65l-2.8-1.62q-.33.26-.77.27a1.25 1.25 0 0 1-.48-2.4V6.4a1.25 1.25 0 1 1 1.25-2.14l2.8-1.61A1.25 1.25 0 0 1 8 1M4.44 11.14l-.06.13 2.75 1.58a1.25 1.25 0 0 1 1.74 0l2.74-1.58-.05-.13zm3.89-7.68a1.3 1.3 0 0 1-.66 0L4.03 9.77q.37.3.45.78h7.04q.08-.48.45-.78zM4.38 4.73a1.24 1.24 0 0 1-1.02 1.76v3.02l.13.01 3.67-6.35-.03-.02zm4.46-1.56 3.67 6.35.13-.01V6.49a1.25 1.25 0 0 1-1.03-1.76L8.87 3.15z" clip-rule="evenodd"/>"#, +}; +static HTML: Icon = Icon { + name: "file-tree-html", + view: 16.0, + body: r#"<path fill="currentColor" d="M8 1C2.24 1 1 2.24 1 8s1.24 7 7 7 7-1.24 7-7-1.24-7-7-7" opacity=".2"/><path fill="currentColor" d="M10.48 3.76a.5.5 0 0 1 .4.58L10.6 5.8h1.14a.5.5 0 0 1 0 1h-1.32L10 9.2h1.08a.5.5 0 0 1 0 1H9.8l-.3 1.64a.5.5 0 1 1-.98-.18l.27-1.46H6.4l-.3 1.64a.5.5 0 1 1-.98-.18l.27-1.46H4.25a.5.5 0 0 1 0-1h1.32L6 6.8H4.93a.5.5 0 0 1 0-1H6.2l.3-1.64a.5.5 0 1 1 .98.18L7.2 5.8h2.4l.3-1.64a.5.5 0 0 1 .58-.4M6.58 9.2h2.4l.44-2.4h-2.4z"/>"#, +}; +static IMAGE: Icon = Icon { + name: "file-tree-image", + view: 16.0, + body: r#"<path fill="currentColor" d="M12.5 2A2.5 2.5 0 0 1 15 4.5v4.67l-4.05-3.54-4.08 4.08-3-2L1 10.6V4.5A2.5 2.5 0 0 1 3.5 2z" opacity=".3"/><path fill="currentColor" d="M15 10.5v1a2.5 2.5 0 0 1-2.5 2.5h-9a2.5 2.5 0 0 1-2.46-2.04L4 9l3 2 4-4zm-7-5a1.5 1.5 0 1 1-3 0 1.5 1.5 0 0 1 3 0"/>"#, +}; +static JAVASCRIPT: Icon = Icon { + name: "file-tree-javascript", + view: 16.0, + body: r#"<path fill="currentColor" d="M8 1C2.24 1 1 2.24 1 8s1.24 7 7 7 7-1.24 7-7-1.24-7-7-7" opacity=".2"/><path fill="currentColor" d="M8.1 9.64h.95c.04.62.28.76 1.28.76s1.2-.14 1.2-.85c0-.66-.2-.85-1.2-1.07-1.79-.38-2.18-.7-2.18-1.86C8.15 5.3 8.54 5 10.31 5c1.67 0 2.04.26 2.07 1.42h-.95c-.02-.43-.23-.53-1.1-.53-1 0-1.22.14-1.22.74 0 .52.22.7 1.24.92 1.76.38 2.15.73 2.15 2 0 1.44-.4 1.75-2.24 1.75-1.8 0-2.18-.3-2.15-1.66M3.5 9.5h.98c0 .76.15.92.85.92.77 0 .94-.18.94-1.02V5.1h1v4.34c0 1.54-.35 1.87-1.92 1.87-1.55 0-1.89-.32-1.86-1.8"/>"#, +}; +static JSON: Icon = Icon { + name: "file-tree-json", + view: 16.0, + body: r#"<path fill="currentColor" d="M13.25 11.5V9.75a.5.5 0 0 1 .36-.48l.55-.15a1.16 1.16 0 0 0 0-2.24l-.55-.15a.5.5 0 0 1-.36-.48V4.5a2.5 2.5 0 0 0-2.5-2.5h-.25a.5.5 0 0 0 0 1h.25a1.5 1.5 0 0 1 1.5 1.5v1.75a1.5 1.5 0 0 0 1.09 1.44l.54.15a.16.16 0 0 1 0 .32l-.54.15a1.5 1.5 0 0 0-1.09 1.44v1.75a1.5 1.5 0 0 1-1.5 1.5h-.25a.5.5 0 0 0 0 1h.25a2.5 2.5 0 0 0 2.5-2.5m-10.5 0V9.75a.5.5 0 0 0-.36-.48l-.55-.15a1.16 1.16 0 0 1 0-2.24l.55-.15a.5.5 0 0 0 .36-.48V4.5A2.5 2.5 0 0 1 5.25 2h.25a.5.5 0 0 1 0 1h-.25a1.5 1.5 0 0 0-1.5 1.5v1.75a1.5 1.5 0 0 1-1.09 1.44l-.54.15a.16.16 0 0 0 0 .32l.54.15a1.5 1.5 0 0 1 1.09 1.45v1.74a1.5 1.5 0 0 0 1.5 1.5h.25a.5.5 0 0 1 0 1h-.25a2.5 2.5 0 0 1-2.5-2.5"/>"#, +}; +static MARKDOWN: Icon = Icon { + name: "file-tree-markdown", + view: 16.0, + body: r#"<path fill="currentColor" d="M1 12V4h2l2 2.5L7 4h2v8H7V7.5l-2 2-2-2V12zm9-3 3 3.5L16 9h-2V4h-2v5z"/>"#, +}; +static MCP: Icon = Icon { + name: "file-tree-mcp", + view: 16.0, + body: r#"<path fill="currentColor" d="M9.26-.04a3 3 0 0 1 2 .82 2.8 2.8 0 0 1 .8 2.35 2.9 2.9 0 0 1 2.41.8l.03.02a2.74 2.74 0 0 1 0 3.94l-5.8 5.69-.04.06-.02.07q0 .04.02.07.01.04.04.06l1.2 1.17a.55.55 0 0 1 0 .79.6.6 0 0 1-.81 0l-1.2-1.17a1.3 1.3 0 0 1 0-1.84L13.7 7.1a1.65 1.65 0 0 0 .37-1.82 2 2 0 0 0-.37-.54l-.03-.03a1.73 1.73 0 0 0-2.4 0L6.47 9.4l-.07.06a.58.58 0 0 1-.92-.18.6.6 0 0 1 .12-.6l4.85-4.76a1.65 1.65 0 0 0 0-2.36 1.73 1.73 0 0 0-2.4 0l-6.43 6.3a.6.6 0 0 1-.8 0 .55.55 0 0 1 0-.8L7.25.79a3 3 0 0 1 2-.82"/><path fill="currentColor" d="M9.26 2.19a.6.6 0 0 1 .52.34.6.6 0 0 1 0 .43l-.12.18L4.9 7.79a1.65 1.65 0 0 0 0 2.36 1.73 1.73 0 0 0 2.4 0l4.75-4.66a.58.58 0 0 1 .93.18.6.6 0 0 1-.12.61l-4.75 4.66a2.9 2.9 0 0 1-4.01 0 2.75 2.75 0 0 1-.62-3.04A3 3 0 0 1 4.1 7l4.74-4.65a.6.6 0 0 1 .4-.16"/>"#, +}; +static NEXTJS: Icon = Icon { + name: "file-tree-nextjs", + view: 16.0, + body: r#"<defs><linearGradient id="a" x1="4.522" x2="14" y1="3.943" y2="16" gradientUnits="userSpaceOnUse"><stop stop-color="currentColor"/><stop offset="1" stop-color="currentColor" stop-opacity="0"/></linearGradient></defs><path fill="currentColor" d="M3 2h1.522v9.09H3z"/><path fill="url(#a)" d="M4.903 2 15 15.075q-.565.5-1.195.925L4.522 3.943z"/><path fill="currentColor" d="M12.172 2h-1.508v9.094h1.508z"/>"#, +}; +static OXC: Icon = Icon { + name: "file-tree-oxc", + view: 16.0, + body: r#"<path fill="currentColor" d="M9.5 1a.5.5 0 0 1 .5.5V3h3.5a.5.5 0 0 1 .38.83L10.5 7.69v1.44q.41.04.95-.16a4 4 0 0 0 .72-.35l.04-.03h.01a.5.5 0 0 1 .67.1l2 2.5a.5.5 0 0 1 0 .62c-.76.96-3.14 2.69-6.89 2.69s-6.13-1.73-6.89-2.69a.5.5 0 0 1 0-.62l2-2.5a.5.5 0 0 1 .67-.1l.05.03.16.09q.22.13.56.26.54.2.95.16V7.69L2.12 3.83A.5.5 0 0 1 2.5 3H6V1.5a.5.5 0 0 1 .5-.5zM7 3.5a.5.5 0 0 1-.5.5H3.6l2.78 3.17a.5.5 0 0 1 .12.33v2a.5.5 0 0 1-.28.45c-.7.35-1.5.15-2.02-.05a5 5 0 0 1-.58-.26l-1.46 1.84c.82.78 2.8 2.02 5.84 2.02s5.02-1.24 5.84-2.02l-1.46-1.83a5 5 0 0 1-.58.26c-.52.2-1.33.39-2.02.04a.5.5 0 0 1-.28-.45v-2a.5.5 0 0 1 .12-.33L12.4 4H9.5a.5.5 0 0 1-.5-.5V2H7z"/>"#, +}; +static POSTCSS: Icon = Icon { + name: "file-tree-postcss", + view: 16.0, + body: r#"<path fill="currentColor" d="M14.5 8a6.5 6.5 0 0 0-5.9-6.47l5.42 8.93A7 7 0 0 0 14.5 8M2.88 12A6.5 6.5 0 0 0 8 14.5c2.08 0 3.93-.98 5.12-2.5zm8.62-1h1.68L11.5 8.24zm-1-.55a4 4 0 0 1-.7.55h.7zM8 5.5a2.5 2.5 0 1 0 0 5 2.5 2.5 0 0 0 0-5M5.5 11h.7a4 4 0 0 1-.7-.55zm-2.68 0H4.5V8.24zm3.76-6.2A4 4 0 0 1 8 4.5q.76 0 1.42.3L8 2.46zM1.5 8q0 1.31.48 2.46L7.4 1.53A6.5 6.5 0 0 0 1.5 8m14 0a7.5 7.5 0 0 1-.99 3.72l-.01.03-.02.03A7.5 7.5 0 0 1 8 15.5a7.5 7.5 0 0 1-6.5-3.75l-.01-.03A7.5 7.5 0 1 1 15.5 8"/>"#, +}; +static PRETTIER: Icon = Icon { + name: "file-tree-prettier", + view: 16.0, + body: r#"<path fill="currentColor" d="M6 12v1H4.93v-1zm1-2v1H2v-1zm6-4v1h-3V6zm-1-4v1H9V2z"/><path fill="currentColor" d="M11.5 10v1H8v-1zM5 6v1H2V6zm5-2v1H9V4z" opacity=".8"/><path fill="currentColor" d="M6 14v1H2v-1zm-.5-6v1H2V8zM13 4v1h-3V4zM4.93 2v1H2V2z" opacity=".6"/><path fill="currentColor" d="M4.93 12v1H2v-1zM13 8v1H9V8zM5.5 4v1H2V4zM9 2v1H4.93V2z" opacity=".4"/>"#, +}; +static PYTHON: Icon = Icon { + name: "file-tree-python", + view: 16.0, + body: r#"<path fill="currentColor" d="M8.33 8.4H10c1.16 0 1.9-.73 1.9-1.86V5.08q0-.24.25-.24h.74c.75 0 1.33.32 1.66.97q.4.73.41 1.46c.09.9.09 1.78-.24 2.67-.25.73-.75 1.3-1.58 1.46h-4.8c-.08 0-.25 0-.25.08v.4s.17.09.25.09h2.82q.34-.02.33.32v1.06c0 .56-.25.97-.75 1.13-.41.16-.83.33-1.24.4a7 7 0 0 1-2.98-.07 3 3 0 0 1-1.16-.49c-.33-.32-.58-.65-.5-1.14v-2.91c0-1.13.67-1.78 1.82-1.78q.89-.1 1.66-.08m2.32 4.86a.65.65 0 0 0-.66-.65c-.34 0-.67.33-.67.65s.33.57.67.65a.65.65 0 0 0 .66-.65" opacity=".8"/><path fill="currentColor" d="M7.67 7.6H6c-1.16 0-1.9.73-1.9 1.86v1.46q0 .24-.25.24h-.74c-.75 0-1.33-.32-1.66-.97a3 3 0 0 1-.41-1.46 6 6 0 0 1 .24-2.67c.25-.73.75-1.3 1.58-1.46h4.8c.08 0 .25 0 .25-.08v-.4s-.17-.09-.25-.09H4.85c-.24 0-.33-.08-.33-.32V2.65c0-.56.25-.97.75-1.13.41-.16.83-.33 1.24-.4a7 7 0 0 1 2.98.07c.41.09.83.25 1.16.49.33.32.58.65.5 1.13v2.92c0 1.14-.67 1.78-1.82 1.78-.58.08-1.16.08-1.66.08M5.35 2.73c0 .33.25.65.66.65.33 0 .66-.32.66-.65 0-.32-.33-.56-.66-.64a.65.65 0 0 0-.66.64"/>"#, +}; +static REACT: Icon = Icon { + name: "file-tree-react", + view: 16.0, + body: r#"<path fill="currentColor" d="M8 6.65c.73 0 1.31.6 1.31 1.35S8.73 9.35 8 9.35 6.69 8.75 6.69 8 7.27 6.65 8 6.65"/><path fill="currentColor" fill-rule="evenodd" d="M8 2.55c1.3-.99 2.59-1.34 3.5-.8.92.55 1.27 1.87 1.08 3.53C14.06 5.94 15 6.9 15 8s-.94 2.06-2.42 2.72c.19 1.65-.16 2.98-1.08 3.52-.91.55-2.2.2-3.5-.8-1.3 1-2.58 1.35-3.5.8-.91-.54-1.27-1.87-1.08-3.52C1.94 10.06 1 9.1 1 8s.94-2.06 2.42-2.72c-.19-1.66.17-2.98 1.08-3.52s2.2-.2 3.5.8M4.26 11.2c-.08 1.34.28 2.03.68 2.26s1.15.22 2.25-.52l.11-.09a12 12 0 0 1-1.24-1.39 11 11 0 0 1-1.8-.41zm7.47-.15q-.83.27-1.79.41-.6.8-1.24 1.4l.11.08c1.1.74 1.86.76 2.25.52.4-.23.76-.92.68-2.26zm-3.04.54a14 14 0 0 1-1.38 0q.34.38.69.7.35-.32.7-.7M8 5.29q-.76 0-1.47.1A13 13 0 0 0 5.07 8a14 14 0 0 0 1.46 2.62 13 13 0 0 0 2.94 0A13 13 0 0 0 10.93 8a14 14 0 0 0-1.46-2.62A13 13 0 0 0 8 5.3M4.64 9.18q-.15.5-.25.96.44.16.94.27a15 15 0 0 1-.7-1.23m6.73 0a15 15 0 0 1-.7 1.23q.5-.11.95-.27a10 10 0 0 0-.25-.96M3.44 6.26C2.27 6.86 1.87 7.53 1.87 8s.4 1.14 1.57 1.74l.13.07q.18-.88.55-1.81a12 12 0 0 1-.55-1.8q-.07.02-.13.06m8.99-.07A12 12 0 0 1 11.88 8q.36.94.55 1.8l.13-.06c1.17-.6 1.56-1.27 1.56-1.74s-.39-1.14-1.56-1.74zm-7.1-.6q-.5.11-.94.27.1.46.25.96a15 15 0 0 1 .69-1.23m5.34 0a15 15 0 0 1 .7 1.23q.14-.5.24-.96-.44-.15-.94-.27M7.18 3.06c-1.09-.74-1.85-.76-2.24-.52s-.76.92-.69 2.26l.01.15a11 11 0 0 1 1.8-.41q.6-.8 1.24-1.4zm3.88-.52c-.4-.24-1.15-.22-2.25.52l-.12.08q.65.6 1.25 1.4.96.15 1.8.41v-.14c.08-1.35-.28-2.04-.68-2.27M8 3.7a10 10 0 0 0-.7.7 14 14 0 0 1 1.4 0 10 10 0 0 0-.7-.7" clip-rule="evenodd"/>"#, +}; +static RUBY: Icon = Icon { + name: "file-tree-ruby", + view: 16.0, + body: r#"<path fill="currentColor" fill-rule="evenodd" d="M11.04 2c.48 0 .92.23 1.18.6l2.54 3.65c.37.52.3 1.23-.15 1.69l-5.58 5.64a1.47 1.47 0 0 1-2.06 0L1.39 7.94a1.3 1.3 0 0 1-.15-1.7l2.54-3.63q.2-.3.5-.45.33-.16.68-.16zm.84 2.17a.5.5 0 0 0-.7-.05L8 6.84 4.83 4.12a.5.5 0 0 0-.65.76L6.65 7H3.5a.5.5 0 0 0 0 1h9a.5.5 0 0 0 0-1H9.35l2.48-2.12a.5.5 0 0 0 .05-.7" clip-rule="evenodd"/>"#, +}; +static RUST: Icon = Icon { + name: "file-tree-rust", + view: 16.0, + body: r#"<path fill="currentColor" fill-rule="evenodd" d="M8 .8a.2.2 0 0 1 .18.1l.38.6.16.02.5-.53.01-.01a.2.2 0 0 1 .33.08l.25.68.16.05.59-.43h.02a.2.2 0 0 1 .3.14l.12.71.15.08.65-.3a.2.2 0 0 1 .2.02.2.2 0 0 1 .1.18l-.03.72.12.1.71-.16a.2.2 0 0 1 .25.25l-.17.7q.06.06.1.13l.73-.03A.2.2 0 0 1 14 4a.2.2 0 0 1 .02.2l-.3.66.08.14.71.12a.2.2 0 0 1 .14.32l-.43.59.05.16.68.25a.2.2 0 0 1 .07.35l-.53.49.01.16.62.38a.2.2 0 0 1 0 .36l-.62.38-.01.16.53.5a.2.2 0 0 1-.07.34l-.68.25-.05.16.43.59a.2.2 0 0 1-.14.32l-.72.12-.07.15.3.65a.2.2 0 0 1-.02.2.2.2 0 0 1-.18.1l-.72-.03-.1.13.16.7a.2.2 0 0 1-.25.25l-.7-.17-.13.1.03.73a.2.2 0 0 1-.1.18.2.2 0 0 1-.2.02l-.66-.3-.14.08-.12.71a.2.2 0 0 1-.32.14l-.59-.43-.16.05-.25.68a.2.2 0 0 1-.34.07l-.5-.53-.16.01-.38.62a.2.2 0 0 1-.36 0l-.38-.62-.16-.01-.5.53a.2.2 0 0 1-.34-.07l-.25-.68-.16-.05-.59.43a.2.2 0 0 1-.32-.14L5 13.78l-.15-.07-.65.3a.2.2 0 0 1-.2-.02.2.2 0 0 1-.1-.18l.03-.72-.13-.1-.7.16a.2.2 0 0 1-.25-.25l.17-.7-.1-.13-.73.03a.2.2 0 0 1-.2-.3l.3-.66-.08-.14-.71-.12a.2.2 0 0 1-.14-.32l.43-.59-.05-.16-.68-.25A.2.2 0 0 1 1 9.22l.53-.5-.02-.16-.6-.38A.2.2 0 0 1 .8 8a.2.2 0 0 1 .1-.18l.6-.38.02-.16-.53-.5a.2.2 0 0 1 .07-.34l.68-.25.05-.16-.43-.59a.2.2 0 0 1 .14-.32L2.2 5l.08-.15L2 4.2a.2.2 0 0 1 .2-.3l.72.03.1-.13-.16-.7a.2.2 0 0 1 .25-.25l.7.16.13-.1-.03-.72A.2.2 0 0 1 4 2a.2.2 0 0 1 .2-.02l.65.3L5 2.2l.12-.71v-.03a.2.2 0 0 1 .32-.1l.59.41.16-.04.25-.68.01-.02A.2.2 0 0 1 6.8.99l.49.53.16-.02.38-.61.02-.02A.2.2 0 0 1 8 .79M6.8 9.45h1.26l.06.01q.03.01.03.05v1.52q0 .07-.09.06h-4.5A5.4 5.4 0 0 0 8 13.42a5.4 5.4 0 0 0 4.45-2.33h-2.42c-.36 0-.68-.5-.77-.75-.08-.22-.2-.91-.25-1.12-.15-.61-.59-.71-.78-.73H6.8zM8 2.58a5.4 5.4 0 0 0-4.07 1.85h5.74l.17.02c.23.03.6.12.96.35.34.23.83.68.83 1.4 0 .66-.55 1.16-1.08 1.5.42.33.7.53.86 1.44.04.17.34.32.62.29.29-.03.62-.16.62-.75v-.24q0-.1.07-.1h.68A5.43 5.43 0 0 0 8 2.59M2.96 6.03a5.4 5.4 0 0 0-.19 3.37h1.66V6.03zM6.8 7.06h1.66c.35 0 .77-.12.77-.47 0-.42-.55-.53-.65-.53H6.8z" clip-rule="evenodd"/>"#, +}; +static SASS: Icon = Icon { + name: "file-tree-sass", + view: 16.0, + body: r#"<path fill="currentColor" fill-rule="evenodd" d="M8.08 1.44c2.41-.91 4.96-.37 5.35 1.27.39 1.62-.92 3.56-2.6 4.25a5 5 0 0 1-3.26.35c-.58-.2-.92-.62-1-.85-.03-.09-.09-.24 0-.3.05-.03.08-.02.22.15s.7.6 1.75.48c2.78-.34 4.45-2.64 3.92-3.88-.37-.87-2.5-1.26-5.18.16C4.03 4.81 3.85 6.24 3.82 6.8c-.08 1.5 1.73 2.28 2.7 3.4q.04.03.07.08c.3-.12.7-.19 1.35-.2 1.58-.03 2.47 1.08 2.43 2.08-.03.78-.7 1.1-.82 1.13-.1.01-.14.02-.15-.06q-.03-.06.13-.15c.16-.09.42-.3.48-.72.05-.43-.24-1.44-1.76-1.63a3 3 0 0 0-1.33.08c.27.62.32 1.87-.29 2.83-.63 1-1.8 1.61-2.93 1.27-.37-.1-.93-.92-.45-2.05.46-1.07 2.4-2.12 2.66-2.26-.9-.83-3.08-1.95-3.4-3.65-.08-.49.13-1.65 1.46-2.98a12 12 0 0 1 4.11-2.52m-1.88 9.7c-.01.01-.9.47-1.52 1.17-.59.66-.75 1.48-.43 1.69.3.18 1-.04 1.51-.62a3 3 0 0 0 .5-.9q.2-.64.02-1.39z" clip-rule="evenodd"/>"#, +}; +static STYLELINT: Icon = Icon { + name: "file-tree-stylelint", + view: 16.0, + body: r#"<path fill="currentColor" d="M4 3v3.5l1.5-1L7 15 .5 6l1-1.5L0 3l2.5-2h1zm12 0-1.5 1.5 1 1.5L9 15l1.5-9.5 1.5 1V3l.5-2h1zm-8 8.5a.5.5 0 1 1 0 1 .5.5 0 0 1 0-1m0-3a.5.5 0 1 1 0 1 .5.5 0 0 1 0-1m0-3a.5.5 0 1 1 0 1 .5.5 0 0 1 0-1"/><path fill="currentColor" d="M6.5 2.5V4l-2 1.5v-4zm5 3L9.5 4V2.5l2-1zM9 4H7V2.5h2z"/>"#, +}; +static SVELTE: Icon = Icon { + name: "file-tree-svelte", + view: 16.0, + body: r#"<path fill="currentColor" d="m3.98 3.7 3.36-2.08a4.5 4.5 0 0 1 5.9 1.23 4 4 0 0 1 .7 3.02q-.16.75-.58 1.4c.42.77.56 1.66.4 2.52a3.7 3.7 0 0 1-1.57 2.4l-.17.1-3.36 2.09a4.5 4.5 0 0 1-5.9-1.23 4 4 0 0 1-.66-1.44 4 4 0 0 1-.04-1.58 4 4 0 0 1 .58-1.4 4 4 0 0 1-.4-2.52 3.7 3.7 0 0 1 1.57-2.4zl3.36-2.08zm7.87 0a2.7 2.7 0 0 0-1.26-.95 2.7 2.7 0 0 0-1.6-.07 3 3 0 0 0-.52.2l-.16.09-3.36 2.08a2 2 0 0 0-.69.64 2 2 0 0 0-.36.86 2.3 2.3 0 0 0 .42 1.81A2.7 2.7 0 0 0 7.18 9.4q.28-.06.53-.2l.16-.09 1.28-.79.2-.09a.8.8 0 0 1 .87.31.7.7 0 0 1 .13.55.7.7 0 0 1-.24.4l-.08.05-3.36 2.08-.2.09a1 1 0 0 1-.49-.02 1 1 0 0 1-.38-.3 1 1 0 0 1-.13-.37v-.1l.01-.13-.13-.03a4 4 0 0 1-1.1-.5l-.2-.14-.18-.12-.07.18-.08.3a2.3 2.3 0 0 0 .43 1.82q.45.64 1.19.93.73.28 1.51.14l.16-.04q.27-.07.52-.2l.16-.09 3.36-2.08q.4-.25.69-.64.27-.4.36-.86a2.3 2.3 0 0 0-.42-1.82 2.7 2.7 0 0 0-1.27-.95 2.7 2.7 0 0 0-1.6-.08q-.27.07-.52.2l-.16.1-1.28.79-.2.09a1 1 0 0 1-.49-.03 1 1 0 0 1-.38-.29.7.7 0 0 1-.13-.54.7.7 0 0 1 .24-.4l.08-.06L9.33 4.4l.2-.1a.8.8 0 0 1 .87.32 1 1 0 0 1 .13.38v.22l.11.04q.6.18 1.12.5l.2.14.17.12.06-.19.08-.3a2.3 2.3 0 0 0-.42-1.81z"/>"#, +}; +static SVG: Icon = Icon { + name: "file-tree-svg", + view: 16.0, + body: r#"<path fill="currentColor" d="M5 7a2 2 0 0 1 2-2h6a2 2 0 0 1 2 2v6a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2z"/><path fill="currentColor" d="M6 1a5 5 0 0 1 4.58 3H7a3 3 0 0 0-3 3v3.58A5 5 0 0 1 6 1" opacity=".5"/>"#, +}; +static SVGO: Icon = Icon { + name: "file-tree-svgo", + view: 16.0, + body: r#"<path fill="currentColor" d="M9.43 4.8A.6.6 0 1 1 9.19 6l-.56.96a1.2 1.2 0 0 1 .32 1.58l.7.53a.89.89 0 1 1-.17.22l-.7-.52a1.2 1.2 0 0 1-1.4.25l-.56.87a.75.75 0 1 1-.57-.2 1 1 0 0 1 .32.05l.56-.87a1.2 1.2 0 0 1-.4-1.24l-1.2-.47a.56.56 0 1 1 .1-.28v.02l1.2.47a1.2 1.2 0 0 1 1.56-.55l.56-.97a.6.6 0 0 1-.15-.64.6.6 0 0 1 .63-.4"/><path fill="currentColor" fill-rule="evenodd" d="M9.17 1q.16.63.27 1.26a6 6 0 0 1 1.61.67q.52-.38 1.08-.71l1.65 1.64q-.32.56-.68 1.05.48.78.72 1.67.6.09 1.18.25v2.32q-.55.15-1.11.24a6 6 0 0 1-.7 1.82q.31.44.59.91l-1.65 1.65-.85-.55a6 6 0 0 1-1.9.83q-.08.47-.2.95H6.84q-.12-.46-.2-.93a6 6 0 0 1-1.96-.81q-.39.27-.8.51l-1.65-1.65q.25-.43.53-.84a6 6 0 0 1-.75-1.9L1 9.16V6.83q.54-.14 1.09-.24a6 6 0 0 1 .77-1.74q-.33-.47-.63-.98l1.65-1.65q.54.32 1.03.68a6 6 0 0 1 1.66-.66q.1-.61.26-1.24zM7.96 3.73a4 4 0 0 0-1.74.36 4.5 4.5 0 0 0-2.3 2.3 4.4 4.4 0 0 0-.1 3.29l.03.06a4.4 4.4 0 0 0 2.4 2.47 4.4 4.4 0 0 0 3.48-.02l.03-.02a4.4 4.4 0 0 0 2.3-2.42l.06-.14a4.4 4.4 0 0 0-.2-3.4 4.4 4.4 0 0 0-2.13-2.07L9.47 4a4 4 0 0 0-1.51-.27" clip-rule="evenodd"/>"#, +}; +static SWIFT: Icon = Icon { + name: "file-tree-swift", + view: 16.0, + body: r#"<path fill="currentColor" d="M9.63 1c6.15 4.35 4.16 9.15 4.16 9.15s1.75 2.05 1.04 3.85c0 0-.72-1.26-1.93-1.26-1.17 0-1.85 1.26-4.2 1.26C3.47 14 1 9.46 1 9.46c4.71 3.22 7.93.94 7.93.94C6.8 9.12 2.29 3 2.29 3c3.93 3.47 5.63 4.39 5.63 4.39-1.01-.87-3.86-5.13-3.86-5.13C6.34 4.66 10.86 8 10.86 8c1.28-3.7-1.23-7-1.23-7"/>"#, +}; +static TABLE: Icon = Icon { + name: "file-tree-table", + view: 16.0, + body: r#"<path fill="currentColor" d="M8 4a3 3 0 0 0 3 3h3v5.5a2.5 2.5 0 0 1-2.5 2.5h-7A2.5 2.5 0 0 1 2 12.5v-9A2.5 2.5 0 0 1 4.5 1H8z" opacity=".4"/><path fill="currentColor" d="M11.5 8a.5.5 0 0 1 .5.5v4a.5.5 0 0 1-.5.5h-7a.5.5 0 0 1-.5-.5v-4a.5.5 0 0 1 .5-.5zM5 12h2.5v-1H5zm3.5 0H11v-1H8.5zM5 10h2.5V9H5zm3.5 0H11V9H8.5zm1-9a.5.5 0 0 1 .354.146l4 4A.5.5 0 0 1 14 5.5V6h-3a2 2 0 0 1-2-2V1z"/>"#, +}; +static TAILWIND: Icon = Icon { + name: "file-tree-tailwind", + view: 16.0, + body: r#"<path fill="currentColor" fill-rule="evenodd" d="M8 4Q5.2 4 4.5 6.67q1.05-1.34 2.45-1c.53.12.91.5 1.33.9C8.98 7.23 9.77 8 11.5 8q2.8 0 3.5-2.67-1.05 1.34-2.45 1c-.53-.12-.91-.5-1.33-.9C10.52 4.77 9.73 4 8 4M4.5 8Q1.7 8 1 10.67q1.05-1.34 2.45-1c.53.12.91.5 1.33.9C5.48 11.23 6.26 12 8 12q2.8 0 3.5-2.67-1.05 1.34-2.45 1c-.53-.12-.91-.5-1.33-.9C7.02 8.77 6.24 8 4.5 8" clip-rule="evenodd"/>"#, +}; +static TERRAFORM: Icon = Icon { + name: "file-tree-terraform", + view: 16.0, + body: r#"<path fill="currentColor" d="M1 0v5.05l4.35 2.53V2.53zm9.18 5.34L5.83 2.82v5.05l4.35 2.53zm.47 5.06V5.34L15 2.82v5.05zm-.48 5.6-4.35-2.53V8.42l4.35 2.53z"/>"#, +}; +static TEXT: Icon = Icon { + name: "file-tree-text", + view: 16.0, + body: r#"<path fill="currentColor" fill-rule="evenodd" d="M8 4a3 3 0 0 0 3 3h3v5.5a2.5 2.5 0 0 1-2.5 2.5h-7A2.5 2.5 0 0 1 2 12.5v-9A2.5 2.5 0 0 1 4.5 1H8z" clip-rule="evenodd" opacity=".4"/><path fill="currentColor" d="M8.5 11a.5.5 0 0 1 0 1h-3a.5.5 0 0 1 0-1zm2-2a.5.5 0 0 1 0 1h-5a.5.5 0 0 1 0-1zm-1-8a.5.5 0 0 1 .354.146l4 4A.5.5 0 0 1 14 5.5V6h-3a2 2 0 0 1-2-2V1z"/>"#, +}; +static TYPESCRIPT: Icon = Icon { + name: "file-tree-typescript", + view: 16.0, + body: r#"<path fill="currentColor" d="M8 1C2.24 1 1 2.24 1 8s1.24 7 7 7 7-1.24 7-7-1.24-7-7-7" opacity=".2"/><path fill="currentColor" d="M8.1 9.64h.95c.04.62.28.76 1.28.76s1.2-.14 1.2-.85c0-.66-.2-.85-1.2-1.07-1.79-.38-2.18-.7-2.18-1.86C8.15 5.3 8.54 5 10.31 5c1.67 0 2.04.26 2.07 1.42h-.95c-.02-.43-.23-.53-1.1-.53-1 0-1.22.14-1.22.74 0 .52.22.7 1.24.92 1.76.38 2.15.73 2.15 2 0 1.44-.4 1.75-2.24 1.75-1.8 0-2.18-.3-2.15-1.66m-3 1.57V5.99H3.5v-.9h4.21v.9H6.1v5.22z"/>"#, +}; +static VITE: Icon = Icon { + name: "file-tree-vite", + view: 16.0, + body: r#"<path fill="currentColor" d="M8.57 14.87c-.18.26-.55.11-.55-.22v-3.18l-.05-.27-.13-.22-.2-.15-.24-.06H4.29c-.26 0-.4-.32-.26-.55L6.08 7c.3-.46 0-1.1-.5-1.1H1.8c-.25 0-.4-.32-.25-.56l2.65-4.2A.3.3 0 0 1 4.46 1h7.9c.26 0 .4.32.26.55l-2.05 3.23c-.29.46 0 1.1.5 1.1h3.12c.26 0 .4.34.24.57z"/>"#, +}; +static VSCODE: Icon = Icon { + name: "file-tree-vscode", + view: 16.0, + body: r#"<path fill="currentColor" d="m5.11 9.68-2.4 1.84a.6.6 0 0 1-.75-.04l-.77-.7a.6.6 0 0 1 0-.87L3.28 8zm5.52-8.42a.51.51 0 0 1 .87.36V4.8L7.32 8 5.1 6.32z" opacity=".75"/><path fill="currentColor" d="M11.1 14.99h.03zM1.96 4.52a.6.6 0 0 1 .75-.04l8.8 6.71v3.19a.51.51 0 0 1-.88.36L1.19 6.1a.6.6 0 0 1 0-.87z" opacity=".65"/><path fill="currentColor" d="M11.62 14.91a.9.9 0 0 1-1-.17.51.51 0 0 0 .88-.36V1.62a.51.51 0 0 0-.87-.36.9.9 0 0 1 1-.17l2.87 1.39a.9.9 0 0 1 .5.8v9.44a.9.9 0 0 1-.5.8z"/>"#, +}; +static VUE: Icon = Icon { + name: "file-tree-vue", + view: 16.0, + body: r#"<path fill="currentColor" d="M9.62 2.25 8 5.02 6.38 2.25H1l7 12 7-12z" opacity=".5"/><path fill="currentColor" d="M9.54 2.25 8 4.95l-1.54-2.7H4l4 7 4-7z"/>"#, +}; +static WASM: Icon = Icon { + name: "file-tree-wasm", + view: 16.0, + body: r#"<path fill="currentColor" d="M13 1a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2H3a2 2 0 0 1-2-2V3a2 2 0 0 1 2-2h3a2 2 0 1 0 4 0z" opacity=".2"/><path fill="currentColor" d="M4.64 11.4h.02l.8-3.4h.91l.73 3.45L7.88 8h.96l-1.25 5h-.97L5.9 9.6 5.1 13h-1L3 8h.98z"/><path fill="currentColor" fill-rule="evenodd" d="M13 13h-1.02l-.33-1.11H9.9L9.64 13h-.97l1.26-5h1.54zm-2.49-3.77-.42 1.84h1.32l-.49-1.84z" clip-rule="evenodd"/>"#, +}; +static WEBPACK: Icon = Icon { + name: "file-tree-webpack", + view: 16.0, + body: r#"<path fill="currentColor" d="M14.1 11.79 8.26 15v-2.5l3.64-1.94zm.4-.35V4.73l-2.14 1.2v4.3zm-12.6.35L7.74 15v-2.5L4.1 10.56zm-.4-.35V4.73l2.14 1.2v4.3zm.25-7.15 6-3.29v2.42L3.9 5.47l-.03.01zm12.5 0L8.25 1v2.42l3.85 2.05.03.01z" opacity=".4"/><path fill="currentColor" d="m7.74 11.93-3.59-1.92v-3.8l3.6 2.02zm.52 0 3.59-1.92v-3.8l-3.6 2.02zM4.4 5.77 8 3.85l3.6 1.93L8 7.8z"/>"#, +}; +static YML: Icon = Icon { + name: "file-tree-yml", + view: 16.0, + body: r#"<path fill="currentColor" d="M7.5 2A1.5 1.5 0 0 1 9 3.5v3A1.5 1.5 0 0 1 7.5 8h-2v2A1.5 1.5 0 0 0 7 11.5v-1A1.5 1.5 0 0 1 8.5 9h5a1.5 1.5 0 0 1 1.5 1.5v3a1.5 1.5 0 0 1-1.5 1.5h-5A1.5 1.5 0 0 1 7 13.5v-1A2.5 2.5 0 0 1 4.5 10V8h-2A1.5 1.5 0 0 1 1 6.5v-3A1.5 1.5 0 0 1 2.5 2zm1 8a.5.5 0 0 0-.5.5v3a.5.5 0 0 0 .5.5h5a.5.5 0 0 0 .5-.5v-3a.5.5 0 0 0-.5-.5zm-6-7a.5.5 0 0 0-.5.5v3a.5.5 0 0 0 .5.5h5a.5.5 0 0 0 .5-.5v-3a.5.5 0 0 0-.5-.5z"/>"#, +}; +static ZIG: Icon = Icon { + name: "file-tree-zig", + view: 16.0, + body: r#"<path fill="currentColor" d="m14.73 1.5-7.29 8.82h4.17l-1.73 2.04H5.76L1.27 14.5l7.3-8.91H4.39l1.73-2.05h4.12z"/><path fill="currentColor" d="M5.21 3.54 3.56 5.6h-.55v4.73h.83L2.1 12.36H1V3.54zm9.79 0v8.82h-4.3l1.74-2.04h.55V5.68h-.83l1.74-2.14z"/>"#, +}; +static ZIP: Icon = Icon { + name: "file-tree-zip", + view: 16.0, + body: r#"<path fill="currentColor" d="M4.585 2a2 2 0 0 1 1.028.285l1.788 1.072a1 1 0 0 0 .514.143H12A2 2 0 0 1 13.935 5H0V4a2 2 0 0 1 2-2z" opacity=".5"/><path fill="currentColor" fill-rule="evenodd" d="M14 12a2 2 0 0 1-2 2H2a2 2 0 0 1-2-2v-1.25h1v-1H0V6h14zM9.9 8.25c-.883 0-1.9.5-1.9.5H7v1h1v1s1.017.5 1.9.5c.884 0 1.6-.672 1.6-1.5s-.716-1.5-1.6-1.5M2 9.75v1h1v-1zm2 0v1h1v-1zm2 0v1h1v-1zm-5-1v1h1v-1zm2 0v1h1v-1zm2 0v1h1v-1z" clip-rule="evenodd"/>"#, +}; + +/// The icon for a token (`file-tree-builtin-<token>`). +pub(super) fn icon(token: &str) -> &'static Icon { + match token { + "astro" => &ASTRO, + "babel" => &BABEL, + "bash" => &BASH, + "biome" => &BIOME, + "bootstrap" => &BOOTSTRAP, + "browserslist" => &BROWSERSLIST, + "bun" => &BUN, + "c" => &C, + "claude" => &CLAUDE, + "cpp" => &CPP, + "css" => &CSS, + "database" => &DATABASE, + "docker" => &DOCKER, + "eslint" => &ESLINT, + "font" => &FONT, + "git" => &GIT, + "go" => &GO, + "graphql" => &GRAPHQL, + "html" => &HTML, + "image" => &IMAGE, + "javascript" => &JAVASCRIPT, + "json" => &JSON, + "markdown" => &MARKDOWN, + "mcp" => &MCP, + "nextjs" => &NEXTJS, + "oxc" => &OXC, + "postcss" => &POSTCSS, + "prettier" => &PRETTIER, + "python" => &PYTHON, + "react" => &REACT, + "ruby" => &RUBY, + "rust" => &RUST, + "sass" => &SASS, + "stylelint" => &STYLELINT, + "svelte" => &SVELTE, + "svg" => &SVG, + "svgo" => &SVGO, + "swift" => &SWIFT, + "table" => &TABLE, + "tailwind" => &TAILWIND, + "terraform" => &TERRAFORM, + "text" => &TEXT, + "typescript" => &TYPESCRIPT, + "vite" => &VITE, + "vscode" => &VSCODE, + "vue" => &VUE, + "wasm" => &WASM, + "webpack" => &WEBPACK, + "yml" => &YML, + "zig" => &ZIG, + "zip" => &ZIP, + _ => &DEFAULT, + } +} + +/// A whole lower-case file name's token (`BUILT_IN_FILE_NAME_TOKENS`). +pub(super) fn by_file_name(key: &str) -> Option<&'static str> { + Some(match key { + ".babelrc" => "babel", + ".babelrc.json" => "babel", + ".bash_profile" => "bash", + ".bashrc" => "bash", + ".browserslistrc" => "browserslist", + ".dockerignore" => "docker", + ".eslintignore" => "eslint", + ".eslintrc" => "eslint", + ".eslintrc.cjs" => "eslint", + ".eslintrc.js" => "eslint", + ".eslintrc.json" => "eslint", + ".eslintrc.yaml" => "eslint", + ".eslintrc.yml" => "eslint", + ".gitattributes" => "git", + ".gitignore" => "git", + ".gitkeep" => "git", + ".gitmodules" => "git", + ".oxlintrc.json" => "oxc", + ".postcssrc" => "postcss", + ".postcssrc.json" => "postcss", + ".postcssrc.yaml" => "postcss", + ".postcssrc.yml" => "postcss", + ".prettierignore" => "prettier", + ".prettierrc" => "prettier", + ".prettierrc.cjs" => "prettier", + ".prettierrc.js" => "prettier", + ".prettierrc.json" => "prettier", + ".prettierrc.mjs" => "prettier", + ".prettierrc.toml" => "prettier", + ".prettierrc.yaml" => "prettier", + ".prettierrc.yml" => "prettier", + ".stylelintignore" => "stylelint", + ".stylelintrc" => "stylelint", + ".stylelintrc.cjs" => "stylelint", + ".stylelintrc.js" => "stylelint", + ".stylelintrc.json" => "stylelint", + ".stylelintrc.mjs" => "stylelint", + ".stylelintrc.yaml" => "stylelint", + ".stylelintrc.yml" => "stylelint", + ".terraform.lock.hcl" => "terraform", + ".zprofile" => "bash", + ".zshenv" => "bash", + ".zshrc" => "bash", + "babel.config.cjs" => "babel", + "babel.config.js" => "babel", + "babel.config.json" => "babel", + "babel.config.mjs" => "babel", + "biome.json" => "biome", + "biome.jsonc" => "biome", + "bootstrap.bundle.js" => "bootstrap", + "bootstrap.bundle.min.js" => "bootstrap", + "bootstrap.css" => "bootstrap", + "bootstrap.js" => "bootstrap", + "bootstrap.min.css" => "bootstrap", + "bootstrap.min.js" => "bootstrap", + "bun.lock" => "bun", + "bun.lockb" => "bun", + "bunfig.toml" => "bun", + "claude.md" => "claude", + "compose.yaml" => "docker", + "compose.yml" => "docker", + "docker-compose.override.yml" => "docker", + "docker-compose.yaml" => "docker", + "docker-compose.yml" => "docker", + "dockerfile" => "docker", + "eslint.config.cjs" => "eslint", + "eslint.config.js" => "eslint", + "eslint.config.mjs" => "eslint", + "eslint.config.mts" => "eslint", + "eslint.config.ts" => "eslint", + "gemfile" => "ruby", + "next.config.js" => "nextjs", + "next.config.mjs" => "nextjs", + "next.config.mts" => "nextjs", + "next.config.ts" => "nextjs", + "postcss.config.cjs" => "postcss", + "postcss.config.js" => "postcss", + "postcss.config.mjs" => "postcss", + "postcss.config.ts" => "postcss", + "prettier.config.cjs" => "prettier", + "prettier.config.js" => "prettier", + "prettier.config.mjs" => "prettier", + "rakefile" => "ruby", + "readme.md" => "markdown", + "stylelint.config.cjs" => "stylelint", + "stylelint.config.js" => "stylelint", + "stylelint.config.mjs" => "stylelint", + "svgo.config.cjs" => "svgo", + "svgo.config.js" => "svgo", + "svgo.config.mjs" => "svgo", + "svgo.config.ts" => "svgo", + "tailwind.config.cjs" => "tailwind", + "tailwind.config.js" => "tailwind", + "tailwind.config.mjs" => "tailwind", + "tailwind.config.ts" => "tailwind", + "vite.config.js" => "vite", + "vite.config.mjs" => "vite", + "vite.config.mts" => "vite", + "vite.config.ts" => "vite", + "webpack.config.babel.js" => "webpack", + "webpack.config.cjs" => "webpack", + "webpack.config.js" => "webpack", + "webpack.config.mjs" => "webpack", + "webpack.config.ts" => "webpack", + _ => return None, + }) +} + +/// A lower-case suffix's token (`BUILT_IN_FILE_EXTENSION_TOKENS`). +pub(super) fn by_extension(key: &str) -> Option<&'static str> { + Some(match key { + "7z" => "zip", + "astro" => "astro", + "avif" => "image", + "bash" => "bash", + "bmp" => "image", + "bz2" => "zip", + "c" => "c", + "cc" => "cpp", + "cfg" => "text", + "cjs" => "javascript", + "code-workspace" => "vscode", + "conf" => "text", + "cpp" => "cpp", + "csh" => "bash", + "css" => "css", + "csv" => "table", + "cts" => "typescript", + "cxx" => "cpp", + "db" => "database", + "editorconfig" => "text", + "env" => "text", + "env.development" => "text", + "env.local" => "text", + "env.production" => "text", + "eot" => "font", + "erb" => "ruby", + "fish" => "bash", + "gemspec" => "ruby", + "gif" => "image", + "go" => "go", + "gql" => "graphql", + "graphql" => "graphql", + "gz" => "zip", + "h" => "c", + "hh" => "cpp", + "hpp" => "cpp", + "htm" => "html", + "html" => "html", + "hxx" => "cpp", + "icns" => "image", + "ico" => "image", + "ini" => "text", + "inl" => "cpp", + "jar" => "zip", + "jpeg" => "image", + "jpg" => "image", + "js" => "javascript", + "json" => "json", + "json5" => "json", + "jsonc" => "json", + "jsonl" => "json", + "jsx" => "javascript", + "ksh" => "bash", + "less" => "css", + "log" => "text", + "markdown" => "markdown", + "mcp" => "mcp", + "md" => "markdown", + "mdx" => "markdown", + "mdx.tsx" => "markdown", + "mjs" => "javascript", + "mm" => "cpp", + "mts" => "typescript", + "ods" => "table", + "otf" => "font", + "png" => "image", + "postcss" => "css", + "py" => "python", + "pyi" => "python", + "pyw" => "python", + "pyx" => "python", + "rake" => "ruby", + "rar" => "zip", + "rb" => "ruby", + "rs" => "rust", + "rst" => "text", + "rtf" => "text", + "sass" => "css", + "scss" => "css", + "sh" => "bash", + "sql" => "database", + "sqlite" => "database", + "sqlite3" => "database", + "styl" => "css", + "svelte" => "svelte", + "svg" => "svg", + "swift" => "swift", + "tar" => "zip", + "tf" => "terraform", + "tfstate" => "terraform", + "tfvars" => "terraform", + "tgz" => "zip", + "tif" => "image", + "tiff" => "image", + "ts" => "typescript", + "tsv" => "table", + "tsx" => "typescript", + "ttf" => "font", + "txt" => "text", + "vue" => "vue", + "war" => "zip", + "wasm" => "wasm", + "wast" => "wasm", + "wat" => "wasm", + "webp" => "image", + "woff" => "font", + "woff2" => "font", + "xhtml" => "html", + "xls" => "table", + "xlsx" => "table", + "xz" => "zip", + "yaml" => "yml", + "yml" => "yml", + "zig" => "zig", + "zip" => "zip", + "zsh" => "bash", + _ => return None, + }) +} + +/// The complete set's suffix overrides (`COMPLETE_EXTENSION_OVERRIDES`). +pub(super) fn complete_override(key: &str) -> Option<&'static str> { + Some(match key { + "jsx" => "react", + "sass" => "sass", + "scss" => "sass", + "tsx" => "react", + _ => return None, + }) +} + +/// A token's colour as `#rrggbb` (light, dark), from `--trees-file-icon-color-<token>`. +pub(super) fn tint(token: &str) -> (&'static str, &'static str) { + match token { + "astro" => ("#a631be", "#d568ea"), + "babel" => ("#d5a910", "#ffd452"), + "bash" => ("#199f43", "#5ecc71"), + "biome" => ("#1a85d4", "#69b1ff"), + "bootstrap" => ("#693acf", "#9d6afb"), + "browserslist" => ("#d5a910", "#ffd452"), + "bun" => ("#594c5b", "#79697b"), + "c" => ("#1a85d4", "#69b1ff"), + "claude" => ("#d47628", "#ffa359"), + "cpp" => ("#1a85d4", "#69b1ff"), + "css" => ("#693acf", "#9d6afb"), + "database" => ("#a631be", "#d568ea"), + "docker" => ("#1a85d4", "#69b1ff"), + "eslint" => ("#693acf", "#9d6afb"), + "git" => ("#ff8c5b", "#d5512f"), + "go" => ("#1ca1c7", "#68cdf2"), + "graphql" => ("#d32a61", "#ff678d"), + "html" => ("#d47628", "#ffa359"), + "image" => ("#d32a61", "#ff678d"), + "javascript" => ("#d5a910", "#ffd452"), + "json" => ("#d47628", "#ffa359"), + "markdown" => ("#199f43", "#5ecc71"), + "mcp" => ("#17a5af", "#64d1db"), + "oxc" => ("#1ca1c7", "#68cdf2"), + "postcss" => ("#d52c36", "#ff6762"), + "prettier" => ("#17a5af", "#64d1db"), + "python" => ("#1a85d4", "#69b1ff"), + "react" => ("#1ca1c7", "#68cdf2"), + "ruby" => ("#d52c36", "#ff6762"), + "rust" => ("#d47628", "#ffa359"), + "sass" => ("#d32a61", "#ff678d"), + "svelte" => ("#d52c36", "#ff6762"), + "svg" => ("#d47628", "#ffa359"), + "svgo" => ("#199f43", "#5ecc71"), + "swift" => ("#d47628", "#ffa359"), + "table" => ("#17a5af", "#64d1db"), + "tailwind" => ("#1ca1c7", "#68cdf2"), + "terraform" => ("#693acf", "#9d6afb"), + "text" => ("#84848a", "#adadb1"), + "typescript" => ("#1a85d4", "#69b1ff"), + "vite" => ("#a631be", "#d568ea"), + "vscode" => ("#1a85d4", "#69b1ff"), + "vue" => ("#199f43", "#5ecc71"), + "wasm" => ("#693acf", "#9d6afb"), + "webpack" => ("#1a85d4", "#69b1ff"), + "yml" => ("#d52c36", "#ff6762"), + "zig" => ("#d47628", "#ffa359"), + "zip" => ("#d47628", "#ffa359"), + _ => ("#84848a", "#adadb1"), + } +} + +/// Every token, for a gallery. +pub(super) const TOKENS: &[&str] = &[ + "astro", + "babel", + "bash", + "biome", + "bootstrap", + "browserslist", + "bun", + "c", + "claude", + "cpp", + "css", + "database", + "default", + "docker", + "eslint", + "font", + "git", + "go", + "graphql", + "html", + "image", + "javascript", + "json", + "markdown", + "mcp", + "nextjs", + "oxc", + "postcss", + "prettier", + "python", + "react", + "ruby", + "rust", + "sass", + "stylelint", + "svelte", + "svg", + "svgo", + "swift", + "table", + "tailwind", + "terraform", + "text", + "typescript", + "vite", + "vscode", + "vue", + "wasm", + "webpack", + "yml", + "zig", + "zip", +]; diff --git a/app/vendor/rune/themes/opencode/tools/app-icons.py b/app/vendor/rune/themes/opencode/tools/app-icons.py new file mode 100644 index 0000000..d367142 --- /dev/null +++ b/app/vendor/rune/themes/opencode/tools/app-icons.py @@ -0,0 +1,71 @@ +#!/usr/bin/env python3 +"""Regenerates src/app_icons.rs: the app marks Desktop's Open in menus draw (@opencode/ui's +components/app-icon.tsx, from assets/icons/app), as Rune icons. + +usage: tools/app-icons.py <opencode>/packages/ui/src > src/app_icons.rs + +Each mark is its SVG's body in a group carrying the root's paint (`fill="none"`), so it draws in +its own colours as the browser does. Named colours are written as #rrggbb, which is how Rune tells +a colour icon from a monochrome one. The PNG marks (Finder, Terminal, TextMate, Warp, Xcode) aren't +icons and stay out. +""" +import re +import sys +from pathlib import Path + +# Desktop's ids (app-icon.tsx) and the files they draw; Zed has a dark variant. +FILES = { + "vscode": "vscode", + "cursor": "cursor", + "zed": "zed", + "zed-dark": "zed-dark", + "file-explorer": "file-explorer", + "iterm2": "iterm2", + "ghostty": "ghostty", + "android-studio": "android-studio", + "antigravity": "antigravity", + "powershell": "powershell", + "sublime-text": "sublimetext", +} +NAMED = {"white": "#ffffff", "black": "#000000"} + + +def body(svg): + root = re.search(r"<svg([^>]*)>", svg) + inner = svg[root.end():svg.rindex("</svg>")] + fill = re.search(r'\sfill="([^"]*)"', root.group(1)) + inner = re.sub(r'((?:fill|stroke|stop-color|flood-color)=")(white|black)"', lambda m: m.group(1) + NAMED[m.group(2)] + '"', inner) + inner = re.sub(r">\s+<", "><", inner.strip()) + inner = re.sub(r"\s+", " ", inner) + assert '"##' not in inner + return f'<g fill="{fill.group(1)}">{inner}</g>' if fill else inner + + +def main(): + src = Path(sys.argv[1]) / "assets" / "icons" / "app" + print("//! Generated by tools/app-icons.py from @opencode/ui's app marks. Do not edit.") + print("use rune::Icon;") + print() + idents = [] + for name, file in FILES.items(): + svg = (src / f"{file}.svg").read_text() + view = re.search(r'viewBox="0 0 ([\d.]+) ([\d.]+)"', svg) + assert view and view.group(1) == view.group(2), file + ident = name.upper().replace("-", "_") + idents.append((name, ident)) + print(f'static {ident}: Icon = Icon {{ name: "app-{name}", view: {float(view.group(1))}, body: r##"{body(svg)}"## }};') + print() + print("/// Desktop's mark for app `id` (`AppIcon`'s ids: \"vscode\", \"file-explorer\", ...), in the") + print("/// variant for a dark or light appearance; None for the marks Desktop draws from PNGs.") + print("pub fn named(id: &str, dark: bool) -> Option<&'static Icon> {") + print(" Some(match id {") + print(' "zed" if dark => &ZED_DARK,') + for name, ident in idents: + if name != "zed-dark": + print(f' "{name}" => &{ident},') + print(" _ => return None,") + print(" })") + print("}") + + +main() diff --git a/app/vendor/rune/themes/opencode/tools/file-icons.py b/app/vendor/rune/themes/opencode/tools/file-icons.py new file mode 100644 index 0000000..0334109 --- /dev/null +++ b/app/vendor/rune/themes/opencode/tools/file-icons.py @@ -0,0 +1,118 @@ +#!/usr/bin/env python3 +"""Regenerates src/file_icons/catalog.rs: @opencode/ui's FileIcon badges (assets/icons/file-types) +for every icon its `chooseIconName` can pick, with that function's name, extension and folder maps. + +usage: tools/file-icons.py <opencode>/packages/ui/src > src/file_icons/catalog.rs + +Each SVG keeps its own colours, gradients, groups and transforms (Rune draws an icon that names its +colours as full SVG). Presentation attributes on the root move to a group, and a viewBox that doesn't +start at 0 0 becomes a translate. +""" +import re +import sys +from pathlib import Path + +root = Path(sys.argv[1]) +chooser = (root / "components" / "file-icons" / "choose-icon-name.ts").read_text() +assets = root / "assets" / "icons" / "file-types" + + +def icon_name(stem): + # file-icon.tsx's `toIconName`: `folder-src-open` is `FolderSrcOpen`. + return "".join(w[:1].upper() + w[1:] for w in stem.split("-")) + + +files = {icon_name(p.stem): p for p in sorted(assets.glob("*.svg"))} + + +def block(name): + body = re.search(name + r": \{(.*?)\n \}", chooser, re.S).group(1) + pairs = re.findall(r'^\s*(?:"([^"]+)"|([\w@.$-]+)):\s*"(\w+)",', body, re.M) + # A later duplicate key wins, as in the object literal. + return list({(q or b): v for q, b, v in pairs}.items()) + + +file_names, extensions, folders = block("fileNames"), block("fileExtensions"), block("folderNames") + + +def open_variant(name): + # `toOpenVariant`; a missing variant falls back as FileIcon's failed load does. + name = name.replace("_light", "Open_light") if name.endswith("_light") else name if name.endswith("Open") else name + "Open" + return name if name in files else "FolderOpen" + + +def resolve(name, fallback): + return name if name in files else fallback + + +wanted = {"Document", "Folder", "FolderOpen"} +wanted |= {resolve(v, "Document") for _, v in file_names + extensions} +for _, v in folders: + wanted |= {resolve(v, "Folder"), open_variant(resolve(v, "Folder"))} + +DROP = re.compile(r"^(xmlns(:\w+)?|viewBox|width|height|version|class|id|xml:space|data-[\w-]+|aria-[\w-]+|preserveAspectRatio|x|y|enable-background)$") + + +def body_of(path): + svg = path.read_text() + svg = re.sub(r"<!--.*?-->", "", svg, flags=re.S) + head, inner = re.search(r"<svg\b([^>]*)>(.*)</svg>", svg, re.S).groups() + attrs = re.findall(r'([\w:-]+)="([^"]*)"', head) + x, y, w, h = (float(v) for v in dict(attrs)["viewBox"].replace(",", " ").split()) + assert w == h, f"{path.name}: viewBox is not square" + inner = re.sub(r"\s+", " ", inner).strip() + inner = re.sub(r">\s+<", "><", inner) + kept = " ".join(f'{k}="{v}"' for k, v in attrs if not DROP.match(k)) + if kept: + inner = f"<g {kept}>{inner}</g>" + if x or y: + inner = f'<g transform="translate({-x:g} {-y:g})">{inner}</g>' + assert '"##' not in inner, f"{path.name}: body would end the raw string" + return w, inner + + +def ident(name): + return re.sub(r"[^A-Z0-9]", "_", files[name].stem.upper()) + + +idents = {} +for name in sorted(wanted): + assert ident(name) not in idents.values(), f"{name}: identifier collides" + idents[name] = ident(name) + +print("//! Generated by tools/file-icons.py from @opencode/ui's file-type icons and `chooseIconName`. Do not edit.") +print("use rune::Icon;") +print() +for name in sorted(wanted, key=lambda n: idents[n]): + view, body = body_of(files[name]) + print(f'pub(super) static {idents[name]}: Icon = Icon {{ name: "{files[name].stem}", view: {view:.1f}, body: r##"{body}"## }};') +print() + + +def lookup(fn, doc, pairs, fallback): + print(f"/// {doc}") + print(f"pub(super) fn {fn}(key: &str) -> Option<&'static Icon> {{") + print(" Some(match key {") + for k, v in pairs: + print(f' "{k}" => &{idents[resolve(v, fallback)]},') + print(" _ => return None,") + print(" })") + print("}") + print() + + +lookup("by_file_name", "A whole lower-case file name's badge (`fileNames`).", file_names, "Document") +lookup("by_extension", "A lower-case dotted suffix's badge (`fileExtensions`), `d.ts` as well as `ts`.", extensions, "Document") + +print("/// A lower-case folder name's closed and open icons (`folderNames`).") +print("pub(super) fn by_folder_name(key: &str) -> Option<(&'static Icon, &'static Icon)> {") +print(" Some(match key {") +for k, v in folders: + closed = resolve(v, "Folder") + print(f' "{k}" => (&{idents[closed]}, &{idents[open_variant(closed)]}),') +print(" _ => return None,") +print(" })") +print("}") +print() +print("/// Every badge, for a gallery.") +print("pub(super) static ALL: &[&Icon] = &[" + ", ".join(f"&{idents[n]}" for n in sorted(wanted, key=lambda n: idents[n])) + "];") diff --git a/app/vendor/rune/themes/opencode/tools/icons.py b/app/vendor/rune/themes/opencode/tools/icons.py new file mode 100644 index 0000000..a80d865 --- /dev/null +++ b/app/vendor/rune/themes/opencode/tools/icons.py @@ -0,0 +1,39 @@ +#!/usr/bin/env python3 +"""Regenerates src/icons.rs: @opencode/ui's artwork and compatibility names in catalog order. + +usage: tools/icons.py <opencode>/packages/ui/src/icons > src/icons.rs +""" +import re +import sys +from pathlib import Path + +# Card title icons draw at stroke-width 1.5 (card.css); these get a `_BOLD` twin. +BOLD = ["circle-ban-sign", "warning", "circle-check", "help", "dash"] + +root = Path(sys.argv[1]) +catalog = (root / "catalog.ts").read_text() + +icons = {} +for m in re.finditer(r'\n "?([a-z0-9-]+)"?: \{\s*viewBox: "0 0 (\d+) \d+",\s*body: `([^`]*)`', catalog): + icons[m.group(1)] = (int(m.group(2)), m.group(3)) +alias_block = catalog.split("const aliases = {", 1)[1].split("}", 1)[0] +aliases = dict(re.findall(r'\n "?([a-z0-9-]+)"?: "([a-z0-9-]+)",', alias_block)) + +print("//! Generated by tools/icons.py from @opencode/ui's icon catalog. Do not edit.") +print("#![allow(dead_code)]") +print("use rune::Icon;") +for name in [*icons, *aliases]: + target = aliases.get(name, name) + view, body = icons[target] + ident = name.upper().replace("-", "_") + value = f'..{target.upper().replace("-", "_")}' if name in aliases else f'view: {view}.0, body: r#"{body}"#' + print(f'pub static {ident}: Icon = Icon {{ name: "{name}", {value} }};') + if name in BOLD: + bold = body.replace('stroke="currentColor"', 'stroke="currentColor" stroke-width="1.5"') + print(f'pub static {ident}_BOLD: Icon = Icon {{ name: "{name}-bold", view: {view}.0, body: r#"{bold}"# }};') +print() +print("/// Every icon by its catalog name, for a gallery or a name read from data.") +print("pub static ALL: &[&Icon] = &[") +for name in [*icons, *aliases]: + print(f' &{name.upper().replace("-", "_")},') +print("];") diff --git a/app/vendor/rune/themes/opencode/tools/provider-icons.py b/app/vendor/rune/themes/opencode/tools/provider-icons.py new file mode 100644 index 0000000..ad829a8 --- /dev/null +++ b/app/vendor/rune/themes/opencode/tools/provider-icons.py @@ -0,0 +1,257 @@ +#!/usr/bin/env python3 +"""Regenerates src/provider_icons.rs: every provider mark Desktop draws (@opencode/ui's +components/provider-icons/sprite.svg, the sheet its ProviderIcon uses), as Rune icons. + +usage: tools/provider-icons.py <opencode>/packages/ui/src > src/provider_icons.rs + +Rune's icons take one square viewBox from 0. Each mark is flattened here, so every one is a flat +list of shapes, each carrying its own paint: a viewBox that isn't square from 0 is +centred in a square one (as the browser's xMidYMid meet places it), group and transform are baked +into the path data (strokes scale with them), the paint a shape inherits is written on it, and +clip paths are dropped (every clip here holds its whole mark). A mark that names its own colours +keeps them, written as #rrggbb so Rune draws it in colour as Desktop does. +""" +import math +import re +import sys +import xml.etree.ElementTree as ET +from pathlib import Path + +SVG = "{http://www.w3.org/2000/svg}" +SHAPES = {"path", "rect", "circle", "ellipse", "line", "polygon", "polyline"} +# Paint read from each element; the ones that inherit pass down through groups and the symbol. +PAINT = ["fill", "fill-rule", "stroke", "stroke-width", "stroke-linecap", "stroke-linejoin"] +OWN = ["opacity", "fill-opacity", "stroke-opacity"] +NAMED = {"black": "#000000", "white": "#ffffff"} + + +def main(): + sprite = ET.parse(Path(sys.argv[1]) / "components" / "provider-icons" / "sprite.svg").getroot() + symbols = sorted(sprite.iter(SVG + "symbol"), key=lambda s: s.get("id")) + print("//! Generated by tools/provider-icons.py from @opencode/ui's provider marks. Do not edit.") + print("use rune::Icon;") + print() + idents = [] + for symbol in symbols: + name = symbol.get("id") + view, body = flatten(symbol) + ident = re.sub(r"[^A-Z0-9]", "_", name.upper()) + if ident[0].isdigit(): + ident = "P" + ident + idents.append((name, ident)) + print(f'static {ident}: Icon = Icon {{ name: "{name}", view: {fmt_view(view)}, body: r##"{body}"## }};') + print() + print("/// Desktop's mark for provider `id`, if it ships one.") + print("pub fn named(id: &str) -> Option<&'static Icon> {") + print(" Some(match id {") + for name, ident in idents: + print(f' "{name}" => &{ident},') + print(" _ => return None,") + print(" })") + print("}") + print() + print("/// The providers that have a mark of their own, in `named`.") + print("pub const NAMES: &[&str] = &[") + for name, _ in idents: + print(f' "{name}",') + print("];") + print() + print("/// Desktop's stand-in for a provider with no mark of its own.") + print("pub static FALLBACK: &Icon = &SYNTHETIC;") + + +def flatten(symbol): + x, y, w, h = [float(v) for v in symbol.get("viewBox").replace(",", " ").split()] + side = max(w, h) + start = (1.0, 0.0, 0.0, 1.0, (side - w) / 2 - x, (side - h) / 2 - y) + out = [] + walk(symbol, start, {k: v for k in PAINT if (v := symbol.get(k)) not in (None, "inherit")}, out) + return side, "".join(out) + + +def walk(node, m, inherited, out): + for child in node: + tag = child.tag.replace(SVG, "") + if tag in ("defs", "clipPath", "mask", "title", "desc"): + continue + here = mul(m, parse_transform(child.get("transform", ""))) + paint = dict(inherited) + for k in PAINT: + v = child.get(k) + if v is not None and v != "inherit": + paint[k] = v + if tag == "g": + walk(child, here, paint, out) + elif tag in SHAPES: + out.append(shape(tag, child, here, paint)) + else: + raise SystemExit(f"unhandled <{tag}>") + + +def shape(tag, el, m, paint): + d = shape_path(tag, el) + if m != IDENTITY: + d = transform_path(d, m) + attrs = [("d", d)] + fill = paint.get("fill", "currentColor") + stroke = paint.get("stroke", "none") + attrs.append(("fill", colour(fill))) + if paint.get("fill-rule") and fill != "none": + attrs.append(("fill-rule", paint["fill-rule"])) + if stroke != "none": + attrs.append(("stroke", colour(stroke))) + width = float(paint.get("stroke-width", "1").replace("px", "")) * scale_of(m) + attrs.append(("stroke-width", num(width))) + for k in ("stroke-linecap", "stroke-linejoin"): + if paint.get(k): + attrs.append((k, paint[k])) + for k in OWN: + if el.get(k) is not None: + attrs.append((k, el.get(k))) + return "<path " + " ".join(f'{k}="{v}"' for k, v in attrs) + "/>" + + +def colour(v): + v = v.strip() + if v in NAMED: + return NAMED[v] + rgb = re.fullmatch(r"rgb\((\d+),\s*(\d+),\s*(\d+)\)", v) + if rgb: + return "#" + "".join(f"{int(c):02x}" for c in rgb.groups()) + if v.startswith("#") and len(v) == 4: + return "#" + "".join(c * 2 for c in v[1:]).lower() + return v.lower() if v.startswith("#") else v + + +def shape_path(tag, el): + n = lambda k: float((el.get(k) or "0").replace("px", "")) + if tag == "path": + return el.get("d") + if tag == "rect": + x, y, w, h = n("x"), n("y"), n("width"), n("height") + rx = el.get("rx") or el.get("ry") + r = min(float(rx), w / 2, h / 2) if rx else 0.0 + if r <= 0: + return f"M{num(x)} {num(y)}H{num(x + w)}V{num(y + h)}H{num(x)}Z" + return (f"M{num(x + r)} {num(y)}H{num(x + w - r)}A{num(r)} {num(r)} 0 0 1 {num(x + w)} {num(y + r)}" + f"V{num(y + h - r)}A{num(r)} {num(r)} 0 0 1 {num(x + w - r)} {num(y + h)}H{num(x + r)}" + f"A{num(r)} {num(r)} 0 0 1 {num(x)} {num(y + h - r)}V{num(y + r)}A{num(r)} {num(r)} 0 0 1 {num(x + r)} {num(y)}Z") + if tag in ("circle", "ellipse"): + cx, cy = n("cx"), n("cy") + rx, ry = (n("r"), n("r")) if tag == "circle" else (n("rx"), n("ry")) + return f"M{num(cx - rx)} {num(cy)}A{num(rx)} {num(ry)} 0 1 0 {num(cx + rx)} {num(cy)}A{num(rx)} {num(ry)} 0 1 0 {num(cx - rx)} {num(cy)}Z" + if tag == "line": + return f"M{num(n('x1'))} {num(n('y1'))}L{num(n('x2'))} {num(n('y2'))}" + pts = [float(v) for v in re.split(r"[\s,]+", el.get("points").strip())] + d = "M" + " ".join(num(v) for v in pts[:2]) + "L" + " ".join(num(v) for v in pts[2:]) + return d + ("Z" if tag == "polygon" else "") + + +IDENTITY = (1.0, 0.0, 0.0, 1.0, 0.0, 0.0) + + +def mul(a, b): + return (a[0] * b[0] + a[2] * b[1], a[1] * b[0] + a[3] * b[1], a[0] * b[2] + a[2] * b[3], + a[1] * b[2] + a[3] * b[3], a[0] * b[4] + a[2] * b[5] + a[4], a[1] * b[4] + a[3] * b[5] + a[5]) + + +def parse_transform(t): + m = IDENTITY + for op, args in re.findall(r"(\w+)\s*\(([^)]*)\)", t): + v = [float(a) for a in re.split(r"[\s,]+", args.strip()) if a] + if op == "translate": + step = (1, 0, 0, 1, v[0], v[1] if len(v) > 1 else 0) + elif op == "scale": + step = (v[0], 0, 0, v[1] if len(v) > 1 else v[0], 0, 0) + elif op == "rotate": + a = math.radians(v[0]) + step = (math.cos(a), math.sin(a), -math.sin(a), math.cos(a), 0, 0) + if len(v) == 3: + step = mul(mul((1, 0, 0, 1, v[1], v[2]), step), (1, 0, 0, 1, -v[1], -v[2])) + elif op == "matrix": + step = tuple(v) + else: + raise SystemExit(f"unhandled transform {op}") + m = mul(m, step) + return tuple(float(c) for c in m) + + +def scale_of(m): + return math.sqrt(abs(m[0] * m[3] - m[1] * m[2])) + + +def transform_path(d, m): + """`d` with every point through `m`, a similarity (uniform scale, turn, shift), in absolute + commands; arcs keep their shape as such a transform keeps circles circles.""" + if abs(m[0] - m[3]) > 1e-6 or abs(m[1] + m[2]) > 1e-6: + raise SystemExit(f"transform {m} is not a similarity") + s, turn = scale_of(m), math.degrees(math.atan2(m[1], m[0])) + pt = lambda x, y: (m[0] * x + m[2] * y + m[4], m[1] * x + m[3] * y + m[5]) + out, cur, start = [], (0.0, 0.0), (0.0, 0.0) + for cmd, args in commands(d): + rel, up = cmd.islower(), cmd.upper() + if up == "Z": + out.append("Z") + cur = start + continue + size = {"M": 2, "L": 2, "H": 1, "V": 1, "C": 6, "S": 4, "Q": 4, "T": 2, "A": 7}[up] + for i in range(0, len(args), size): + a = args[i:i + size] + ox, oy = cur if rel else (0.0, 0.0) + if up == "H": + up_, pts = "L", [(a[0] + (cur[0] if rel else 0), cur[1])] + elif up == "V": + up_, pts = "L", [(cur[0], a[0] + (cur[1] if rel else 0))] + elif up == "A": + end = (a[5] + ox, a[6] + oy) + p = pt(*end) + out.append(f"A{num(a[0] * s)} {num(a[1] * s)} {num(a[2] + turn)} {int(a[3])} {int(a[4])} {num(p[0])} {num(p[1])}") + cur = end + continue + else: + up_, pts = up, [(a[j] + ox, a[j + 1] + oy) for j in range(0, size, 2)] + if up == "M" and i > 0: + up_ = "L" + out.append(up_ + " ".join(f"{num(px)} {num(py)}" for px, py in map(lambda q: pt(*q), pts))) + cur = pts[-1] + if up == "M" and i == 0: + start = cur + return "".join(out) + + +NUMBER = re.compile(r"[-+]?(?:\d*\.\d+|\d+\.?)(?:[eE][-+]?\d+)?") + + +def commands(d): + """`d`'s commands and their numbers. An arc's two flags are one character each, as they may + run into what follows them ("a1 1 0 01.5.5").""" + out, i = [], 0 + while i < len(d): + c = d[i] + if c.isalpha(): + out.append((c, [])) + i += 1 + elif c in " ,\t\r\n": + i += 1 + else: + cmd, args = out[-1] + if cmd in "Aa" and len(args) % 7 in (3, 4): + args.append(float(c)) + i += 1 + continue + m = NUMBER.match(d, i) + args.append(float(m.group())) + i = m.end() + return out + + +def num(v): + s = f"{v:.4f}".rstrip("0").rstrip(".") + return "0" if s in ("-0", "") else s + + +def fmt_view(v): + return f"{v:.6f}".rstrip("0") if v != int(v) else f"{v:.1f}" + + +main() diff --git a/app/vendor/rune/themes/opencode/tools/theme.mjs b/app/vendor/rune/themes/opencode/tools/theme.mjs new file mode 100644 index 0000000..669d130 --- /dev/null +++ b/app/vendor/rune/themes/opencode/tools/theme.mjs @@ -0,0 +1,93 @@ +#!/usr/bin/env node +// Regenerates assets/theme.json from @opencode/ui as the browser resolves it. +// +// usage: OPENCODE=<opencode checkout> node themes/opencode/tools/theme.mjs > themes/opencode/assets/theme.json +// +// It opens a Storybook story in light and dark, collects every custom property the kit's +// stylesheets and ThemeProvider define (the v2 tokens and the v1 tokens the older components +// still read), and resolves each through the browser: colours to #rrggbbaa (color-mix, rgba() +// and var() chains included), shadows to their computed box-shadow lists. The result is plain +// Rune theme data; nothing here is compiled into Rune. + +import { openStory, playwright, serve } from "../../../scripts/kit/storybook.mjs" + +const STORY = "ui-button--playground" + +async function collect(page) { + return page.evaluate(() => { + const names = new Set() + const walk = (rules) => { + for (const r of rules) { + if (r.style) for (const n of r.style) if (n.startsWith("--")) names.add(n) + if (r.cssRules) walk(r.cssRules) + } + } + for (const sheet of document.styleSheets) { + try { + walk(sheet.cssRules) + } catch {} + } + for (const el of [document.documentElement, document.body]) for (const n of el.style) if (n.startsWith("--")) names.add(n) + + const canvas = document.createElement("canvas") + canvas.width = canvas.height = 1 + const ctx = canvas.getContext("2d", { willReadFrequently: true }) + const hex = (css) => { + ctx.clearRect(0, 0, 1, 1) + ctx.fillStyle = "rgba(0,0,0,0)" + ctx.fillStyle = css + ctx.fillRect(0, 0, 1, 1) + const [r, g, b, a] = ctx.getImageData(0, 0, 1, 1).data + return "#" + [r, g, b, a].map((v) => v.toString(16).padStart(2, "0")).join("") + } + const probe = document.createElement("div") + document.body.append(probe) + const root = getComputedStyle(document.documentElement) + const colors = {} + const shadows = {} + const numbers = {} + for (const name of [...names].sort()) { + const raw = root.getPropertyValue(name).trim() + if (!raw) continue + const key = name.slice(2) + if (/shadow|elevation/.test(name) && /px/.test(raw)) { + probe.style.boxShadow = "none" + probe.style.boxShadow = `var(${name})` + const v = getComputedStyle(probe).boxShadow + if (v && v !== "none") shadows[key] = v.replace(/rgba?\([^)]*\)|color\([^)]*\)|oklch\([^)]*\)/g, (c) => hex(c)) + continue + } + if (CSS.supports("color", raw)) { + probe.style.color = `var(${name})` + const c = getComputedStyle(probe).color + colors[key] = hex(c) + continue + } + const px = raw.match(/^(-?[\d.]+)(px)?$/) + if (px) numbers[key] = Number(px[1]) + else if (/^-?[\d.]+rem$/.test(raw)) numbers[key] = parseFloat(raw) * 16 + } + probe.remove() + return { colors, shadows, numbers } + }) +} + +const server = await serve() +const browser = await playwright().chromium.launch() +const out = { name: "OpenCode", blend: { mode: "srgb", over: "v2-background-bg-base" } } +let numbers = {} +const shadows = {} +for (const scheme of ["light", "dark"]) { + const page = await browser.newPage() + await openStory(page, server.url, STORY, scheme) + const got = await collect(page) + out[scheme] = got.colors + shadows[scheme] = got.shadows + numbers = { ...got.numbers, ...numbers } + await page.close() +} +out.shadows = shadows +out.numbers = numbers +await browser.close() +server.close() +process.stdout.write(JSON.stringify(out, null, 1) + "\n") diff --git a/app/vendor/rune/themes/opencode/tools/tree-icons.py b/app/vendor/rune/themes/opencode/tools/tree-icons.py new file mode 100644 index 0000000..6e65210 --- /dev/null +++ b/app/vendor/rune/themes/opencode/tools/tree-icons.py @@ -0,0 +1,95 @@ +#!/usr/bin/env python3 +"""Regenerates src/tree_icons/catalog.rs: the "complete" file icon set of @pierre/trees, which +Desktop's file trees and file lists draw (gui-plugins `pierre-tree.tsx`, `list.tsx`), with its file +name and extension tokens and each token's light and dark colour. + +usage: tools/tree-icons.py <opencode>/node_modules/@pierre/trees/dist > src/tree_icons/catalog.rs + +Run `bun install` in the opencode checkout first. The icons are monochrome (`currentColor` with +`opacity` layers). Next.js's fading stroke is a gradient, which a monochrome icon draws solid. +""" +import re +import sys +from pathlib import Path + +dist = Path(sys.argv[1]) +js = (dist / "builtInIcons.js").read_text() +css = (dist / "style.js").read_text() + +symbols = {} +for name, view, body in re.findall(r'<symbol id="([^"]+)" viewBox="0 0 (\d+) \d+">(.*?)</symbol>', js, re.S): + body = re.sub(r'\s(class)="[^"]*"', "", body) + body = re.sub(r"\s+", " ", body).strip() + body = re.sub(r">\s+<", "><", body).replace('"currentcolor"', '"currentColor"') + symbols[name] = (int(view), body) + + +def table(name): + body = re.search(r"const " + name + r" = \{(.*?)\n\};", js, re.S).group(1) + pairs = re.findall(r'^\s*(?:"([^"]+)"|([\w$-]+)):\s*"([\w-]+)"', body, re.M) + # Pierre lower-cases names and suffixes before it looks them up, so upper-case keys never match. + return [(q or b, v) for q, b, v in pairs if (q or b) == (q or b).lower()] + + +names, extensions, overrides = table("BUILT_IN_FILE_NAME_TOKENS"), table("BUILT_IN_FILE_EXTENSION_TOKENS"), table("COMPLETE_EXTENSION_OVERRIDES") +palette = {k: (light, dark) for k, light, dark in re.findall(r"--trees-icon-(\w+): light-dark\((#\w+), (#\w+)\)", css)} +tints = {t: palette[c] for t, c in re.findall(r"--trees-file-icon-color-([\w-]+): var\(--trees-file-icon-[\w-]+, var\(--trees-icon-(\w+)\)\)", css)} + +tokens = sorted({t for _, t in names + extensions + overrides} | {"default"}) +for t in tokens: + assert f"file-tree-builtin-{t}" in symbols, f"no icon for token {t}" + + +def ident(name): + return re.sub(r"[^A-Z0-9]", "_", name.upper()) + + +print("//! Generated by tools/tree-icons.py from @pierre/trees's complete icon set. Do not edit.") +print("use rune::Icon;") +print() +for t in tokens: + view, body = symbols[f"file-tree-builtin-{t}"] + print(f'static {ident(t)}: Icon = Icon {{ name: "file-tree-{t}", view: {view:.1f}, body: r#"{body}"# }};') +print() +print("/// The icon for a token (`file-tree-builtin-<token>`).") +print("pub(super) fn icon(token: &str) -> &'static Icon {") +print(" match token {") +for t in tokens: + if t != "default": + print(f' "{t}" => &{ident(t)},') +print(" _ => &DEFAULT,") +print(" }") +print("}") +print() + + +def lookup(fn, doc, pairs): + print(f"/// {doc}") + print(f"pub(super) fn {fn}(key: &str) -> Option<&'static str> {{") + print(" Some(match key {") + for k, v in dict(pairs).items(): + print(f' "{k}" => "{v}",') + print(" _ => return None,") + print(" })") + print("}") + print() + + +lookup("by_file_name", "A whole lower-case file name's token (`BUILT_IN_FILE_NAME_TOKENS`).", names) +lookup("by_extension", "A lower-case suffix's token (`BUILT_IN_FILE_EXTENSION_TOKENS`).", extensions) +lookup("complete_override", "The complete set's suffix overrides (`COMPLETE_EXTENSION_OVERRIDES`).", overrides) + +print("/// A token's colour as `#rrggbb` (light, dark), from `--trees-file-icon-color-<token>`.") +print("pub(super) fn tint(token: &str) -> (&'static str, &'static str) {") +print(" match token {") +for t in tokens: + if t in tints and t != "default": + light, dark = tints[t] + print(f' "{t}" => ("{light}", "{dark}"),') +light, dark = tints["default"] +print(f' _ => ("{light}", "{dark}"),') +print(" }") +print("}") +print() +print("/// Every token, for a gallery.") +print("pub(super) const TOKENS: &[&str] = &[" + ", ".join(f'"{t}"' for t in tokens) + "];") diff --git a/app/vendor/rune/tools/ratex-math-wasm/.gitignore b/app/vendor/rune/tools/ratex-math-wasm/.gitignore new file mode 100644 index 0000000..b49996d --- /dev/null +++ b/app/vendor/rune/tools/ratex-math-wasm/.gitignore @@ -0,0 +1,3 @@ +target-repro/ +pack/target/ + diff --git a/app/vendor/rune/tools/ratex-math-wasm/Cargo.lock b/app/vendor/rune/tools/ratex-math-wasm/Cargo.lock new file mode 100644 index 0000000..93e6542 --- /dev/null +++ b/app/vendor/rune/tools/ratex-math-wasm/Cargo.lock @@ -0,0 +1,273 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "fastrand" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" + +[[package]] +name = "itoa" +version = "1.0.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4" + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "phf" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c1562dc717473dbaa4c1f85a36410e03c047b2e7df7f45ee938fbef64ae7fadf" +dependencies = [ + "phf_macros", + "phf_shared", + "serde", +] + +[[package]] +name = "phf_generator" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "135ace3a761e564ec88c03a77317a7c6b80bb7f7135ef2544dbe054243b89737" +dependencies = [ + "fastrand", + "phf_shared", +] + +[[package]] +name = "phf_macros" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "812f032b54b1e759ccd5f8b6677695d5268c588701effba24601f6932f8269ef" +dependencies = [ + "phf_generator", + "phf_shared", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "phf_shared" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e57fef6bc5981e38c2ce2d63bfa546861309f875b8a75f092d1d54ae2d64f266" +dependencies = [ + "siphasher", +] + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "ratex-font" +version = "0.1.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c3599bafdf0e0637d1bb9cf97c01528eaa46fab0c6810c3959c2da5f66b2242" +dependencies = [ + "phf", + "ratex-types", +] + +[[package]] +name = "ratex-layout" +version = "0.1.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "667f0b07c558d07d77c53208d90a5bd1918cbe5f76c1c36f3547bf08bc3d625a" +dependencies = [ + "ratex-font", + "ratex-parser", + "ratex-types", + "serde_json", +] + +[[package]] +name = "ratex-lexer" +version = "0.1.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d0fb77ea76a6f650f382f9660949cddc8afd695901f1c9293f92175a3d9e62f" +dependencies = [ + "ratex-types", + "serde", + "thiserror", +] + +[[package]] +name = "ratex-math-wasm" +version = "0.1.0" +dependencies = [ + "ratex-layout", + "ratex-parser", + "ratex-types", +] + +[[package]] +name = "ratex-parser" +version = "0.1.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1dbc57077b89566bde9fc17f468b83d6b17df90930874f8a3d0e7ef988f1ae9c" +dependencies = [ + "ratex-font", + "ratex-lexer", + "ratex-types", + "regex-lite", + "serde", + "serde_json", + "thiserror", + "unicode-normalization", +] + +[[package]] +name = "ratex-types" +version = "0.1.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "74b856c4a2c1d4b9669a10f03b207f97e16a53119bf607501732b97b5c87007f" +dependencies = [ + "serde", +] + +[[package]] +name = "regex-lite" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cab834c73d247e67f4fae452806d17d3c7501756d98c8808d7c9c7aa7d18f973" + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "serde_json" +version = "1.0.154" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "siphasher" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33f4fe9184a62d842c9ef383018f3306d8ba224fd9d836f56d7288308847c256" + +[[package]] +name = "syn" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "3.0.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "thiserror" +version = "1.0.69" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52" +dependencies = [ + "thiserror-impl", +] + +[[package]] +name = "thiserror-impl" +version = "1.0.69" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "tinyvec" +version = "1.13.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee" + +[[package]] +name = "unicode-ident" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" + +[[package]] +name = "unicode-normalization" +version = "0.1.26" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "75cd3fb03d5288b3ba9a1ee103ac7e9cbb59f0b03d64f8ddfcc04dd42758a85d" +dependencies = [ + "tinyvec", +] + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/app/vendor/rune/tools/ratex-math-wasm/Cargo.toml b/app/vendor/rune/tools/ratex-math-wasm/Cargo.toml new file mode 100644 index 0000000..33d4819 --- /dev/null +++ b/app/vendor/rune/tools/ratex-math-wasm/Cargo.toml @@ -0,0 +1,24 @@ +[workspace] + +[package] +name = "ratex-math-wasm" +version = "0.1.0" +edition = "2021" +license = "MIT" +publish = false +description = "Sandboxed wasm32-unknown-unknown LaTeX math parser and layout guest for rune-kit" + +[lib] +crate-type = ["cdylib"] + +[dependencies] +ratex-layout = { version = "=0.1.16", default-features = false } +ratex-parser = { version = "=0.1.16", default-features = false } +ratex-types = { version = "=0.1.16", default-features = false } + +[profile.release] +opt-level = "z" +lto = true +codegen-units = 1 +panic = "abort" +strip = true diff --git a/app/vendor/rune/tools/ratex-math-wasm/pack/Cargo.lock b/app/vendor/rune/tools/ratex-math-wasm/pack/Cargo.lock new file mode 100644 index 0000000..c501393 --- /dev/null +++ b/app/vendor/rune/tools/ratex-math-wasm/pack/Cargo.lock @@ -0,0 +1,32 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "adler2" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" + +[[package]] +name = "miniz_oxide" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b63fbc4a50860e98e7b2aa7804ded1db5cbc3aff9193adaff57a6931bf7c4b4c" +dependencies = [ + "adler2", +] + +[[package]] +name = "ratex-katex-fonts" +version = "0.1.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "575eb89e2ab455fe9618b5f06d1838dff40064642d8ec454fedf14852d2ed0a3" + +[[package]] +name = "ratex-math-pack" +version = "0.1.0" +dependencies = [ + "miniz_oxide", + "ratex-katex-fonts", +] diff --git a/app/vendor/rune/tools/ratex-math-wasm/pack/Cargo.toml b/app/vendor/rune/tools/ratex-math-wasm/pack/Cargo.toml new file mode 100644 index 0000000..89c4547 --- /dev/null +++ b/app/vendor/rune/tools/ratex-math-wasm/pack/Cargo.toml @@ -0,0 +1,12 @@ +[workspace] + +[package] +name = "ratex-math-pack" +version = "0.1.0" +edition = "2021" +license = "MIT" +publish = false + +[dependencies] +miniz_oxide = "0.9" +ratex-katex-fonts = "=0.1.16" diff --git a/app/vendor/rune/tools/ratex-math-wasm/pack/src/main.rs b/app/vendor/rune/tools/ratex-math-wasm/pack/src/main.rs new file mode 100644 index 0000000..f0a42a2 --- /dev/null +++ b/app/vendor/rune/tools/ratex-math-wasm/pack/src/main.rs @@ -0,0 +1,230 @@ +//! Deterministic builder and freshness verifier for `crates/rune-kit/assets/math/*` and +//! `crates/rune-kit/src/math/wasm_hash.rs`. + +use std::path::{Path, PathBuf}; +use std::process::Command; + +const FONT_NAMES: [&str; 20] = [ + "AMS-Regular", + "Caligraphic-Bold", + "Caligraphic-Regular", + "Fraktur-Bold", + "Fraktur-Regular", + "Main-Bold", + "Main-BoldItalic", + "Main-Italic", + "Main-Regular", + "Math-BoldItalic", + "Math-Italic", + "SansSerif-Bold", + "SansSerif-Italic", + "SansSerif-Regular", + "Script-Regular", + "Size1-Regular", + "Size2-Regular", + "Size3-Regular", + "Size4-Regular", + "Typewriter-Regular", +]; + +fn sha256(data: &[u8]) -> [u8; 32] { + const K: [u32; 64] = [ + 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, + 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, + 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, + 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, + 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, + 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, + 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, + 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2, + ]; + let mut h: [u32; 8] = [ + 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, + 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19, + ]; + let bit_len = (data.len() as u64).wrapping_mul(8); + let mut msg = Vec::with_capacity(((data.len() + 9 + 63) / 64) * 64); + msg.extend_from_slice(data); + msg.push(0x80); + while (msg.len() % 64) != 56 { + msg.push(0); + } + msg.extend_from_slice(&bit_len.to_be_bytes()); + for chunk in msg.chunks_exact(64) { + let mut w = [0u32; 64]; + for i in 0..16 { + w[i] = u32::from_be_bytes([chunk[4 * i], chunk[4 * i + 1], chunk[4 * i + 2], chunk[4 * i + 3]]); + } + for i in 16..64 { + let s0 = w[i - 15].rotate_right(7) ^ w[i - 15].rotate_right(18) ^ (w[i - 15] >> 3); + let s1 = w[i - 2].rotate_right(17) ^ w[i - 2].rotate_right(19) ^ (w[i - 2] >> 10); + w[i] = w[i - 16].wrapping_add(s0).wrapping_add(w[i - 7]).wrapping_add(s1); + } + let [mut a, mut b, mut c, mut d, mut e, mut f, mut g, mut hh] = h; + for i in 0..64 { + let s1 = e.rotate_right(6) ^ e.rotate_right(11) ^ e.rotate_right(25); + let ch = (e & f) ^ ((!e) & g); + let t1 = hh.wrapping_add(s1).wrapping_add(ch).wrapping_add(K[i]).wrapping_add(w[i]); + let s0 = a.rotate_right(2) ^ a.rotate_right(13) ^ a.rotate_right(22); + let maj = (a & b) ^ (a & c) ^ (b & c); + let t2 = s0.wrapping_add(maj); + hh = g; + g = f; + f = e; + e = d.wrapping_add(t1); + d = c; + c = b; + b = a; + a = t1.wrapping_add(t2); + } + for (slot, delta) in h.iter_mut().zip([a, b, c, d, e, f, g, hh]) { + *slot = slot.wrapping_add(delta); + } + } + let mut out = [0u8; 32]; + for (i, word) in h.iter().enumerate() { + out[4 * i..4 * i + 4].copy_from_slice(&word.to_be_bytes()); + } + out +} + +fn hex(bytes: &[u8; 32]) -> String { + let mut s = String::with_capacity(64); + for b in bytes { + s.push_str(&format!("{b:02x}")); + } + s +} + +fn hash_guest_sources(guest_dir: &Path) -> String { + let mut buf = Vec::new(); + for rel in ["rust-toolchain.toml", "Cargo.toml", "Cargo.lock", "src/lib.rs"] { + let p = guest_dir.join(rel); + let raw = std::fs::read(&p).unwrap_or_else(|e| panic!("read {}: {e}", p.display())); + buf.extend_from_slice(rel.as_bytes()); + buf.push(0); + // Normalize CRLF -> LF so Windows and Unix checkouts hash identically. + for &b in &raw { + if b != b'\r' { + buf.push(b); + } + } + buf.push(0); + } + hex(&sha256(&buf)) +} + +fn build_wasm_deflate(repo_root: &Path, guest_dir: &Path) -> Vec<u8> { + let remap_repo = format!("--remap-path-prefix={}=/rune", repo_root.display()); + let cargo_home = std::env::var("CARGO_HOME").unwrap_or_else(|_| { + let home = std::env::var("USERPROFILE") + .or_else(|_| std::env::var("HOME")) + .unwrap_or_default(); + format!("{home}/.cargo") + }); + let remap_cargo = format!("--remap-path-prefix={cargo_home}=/cargo"); + // Hard-cap linear memory at 16 MiB (256 pages) inside the wasm binary itself as well as + // host-side `StoreLimits`, so browser Web Workers also enforce the 16 MiB memory cap. + let rustflags = format!("{remap_repo} {remap_cargo} -C link-arg=--max-memory=16777216"); + let target_dir = guest_dir.join("target-repro"); + let mut cmd = Command::new("cargo"); + cmd.arg("build") + .arg("--release") + .arg("--target") + .arg("wasm32-unknown-unknown") + .arg("--manifest-path") + .arg(guest_dir.join("Cargo.toml")) + .arg("--target-dir") + .arg(&target_dir) + .env("RUSTFLAGS", rustflags); + if guest_dir.join("Cargo.lock").exists() { + cmd.arg("--locked"); + } + let status = cmd.status().expect("spawn cargo build for ratex-math-wasm"); + assert!(status.success(), "cargo build for ratex-math-wasm failed"); + let wasm_path = target_dir + .join("wasm32-unknown-unknown") + .join("release") + .join("ratex_math_wasm.wasm"); + let wasm = std::fs::read(&wasm_path).expect("read compiled ratex_math_wasm.wasm"); + let deflated = miniz_oxide::deflate::compress_to_vec(&wasm, 9); + eprintln!( + "ratex_math_wasm.wasm: raw={} B, deflated={} B", + wasm.len(), + deflated.len() + ); + deflated +} + +fn build_fonts_pack_deflate() -> Vec<u8> { + let mut pack = Vec::with_capacity(520 * 1024); + pack.extend_from_slice(b"KF01"); + pack.extend_from_slice(&(FONT_NAMES.len() as u32).to_le_bytes()); + let mut raw_total = 0usize; + for name in FONT_NAMES { + let file = format!("KaTeX_{name}.ttf"); + let data = ratex_katex_fonts::ttf_bytes(&file) + .unwrap_or_else(|| panic!("missing KaTeX font {file}")); + let data = data.as_ref(); + raw_total += data.len(); + pack.push(name.len() as u8); + pack.extend_from_slice(name.as_bytes()); + pack.extend_from_slice(&(data.len() as u32).to_le_bytes()); + pack.extend_from_slice(data); + } + let deflated = miniz_oxide::deflate::compress_to_vec(&pack, 9); + eprintln!( + "katex-fonts.pack: {} fonts, raw={} B, pack={} B, deflated={} B", + FONT_NAMES.len(), + raw_total, + pack.len(), + deflated.len() + ); + deflated +} + +fn main() { + let check_only = std::env::args().any(|a| a == "--check"); + let manifest_dir = PathBuf::from(env!("CARGO_MANIFEST_DIR")); + let guest_dir = manifest_dir.parent().expect("tools/ratex-math-wasm"); + let repo_root = guest_dir + .parent() + .and_then(Path::parent) + .expect("repo root"); + + let wasm_deflate = build_wasm_deflate(repo_root, guest_dir); + let fonts_deflate = build_fonts_pack_deflate(); + let guest_src_sha = hash_guest_sources(guest_dir); + let wasm_sha = hex(&sha256(&wasm_deflate)); + let fonts_sha = hex(&sha256(&fonts_deflate)); + + let assets_dir = repo_root.join("crates/rune-kit/assets/math"); + let wasm_out = assets_dir.join("ratex-math.wasm.deflate"); + let fonts_out = assets_dir.join("katex-fonts.pack.deflate"); + let hash_rs_out = repo_root.join("crates/rune-kit/src/math/wasm_hash.rs"); + let hash_rs = format!( + "// Generated by `scripts/build-math-wasm.sh` from `tools/ratex-math-wasm/` and `ratex-katex-fonts 0.1.16`.\n\ + // Do not edit by hand; `crates/rune-kit/build.rs` verifies these digests when `feature = \"math\"` is enabled.\n\ + pub(crate) const GUEST_SOURCE_SHA256: &str = \"{guest_src_sha}\";\n\ + pub(crate) const WASM_DEFLATE_SHA256: &str = \"{wasm_sha}\";\n\ + pub(crate) const KATEX_FONTS_SHA256: &str = \"{fonts_sha}\";\n" + ); + + if check_only { + let cur_wasm = std::fs::read(&wasm_out).expect("read committed ratex-math.wasm.deflate"); + let cur_fonts = std::fs::read(&fonts_out).expect("read committed katex-fonts.pack.deflate"); + let cur_hash = std::fs::read_to_string(&hash_rs_out).expect("read committed wasm_hash.rs"); + assert_eq!(cur_wasm, wasm_deflate, "ratex-math.wasm.deflate differs from fresh build"); + assert_eq!(cur_fonts, fonts_deflate, "katex-fonts.pack.deflate differs from fresh build"); + assert_eq!(cur_hash.replace("\r\n", "\n"), hash_rs, "wasm_hash.rs differs from fresh build"); + println!("OK: ratex-math.wasm.deflate, katex-fonts.pack.deflate, and wasm_hash.rs match byte-for-byte."); + return; + } + + std::fs::create_dir_all(&assets_dir).expect("create assets/math"); + std::fs::create_dir_all(hash_rs_out.parent().unwrap()).expect("create src/math"); + std::fs::write(&wasm_out, &wasm_deflate).expect("write ratex-math.wasm.deflate"); + std::fs::write(&fonts_out, &fonts_deflate).expect("write katex-fonts.pack.deflate"); + std::fs::write(&hash_rs_out, &hash_rs).expect("write wasm_hash.rs"); + println!("Wrote assets and wasm_hash.rs (guest={guest_src_sha}, wasm={wasm_sha}, fonts={fonts_sha})"); +} diff --git a/app/vendor/rune/tools/ratex-math-wasm/rust-toolchain.toml b/app/vendor/rune/tools/ratex-math-wasm/rust-toolchain.toml new file mode 100644 index 0000000..cc6b8d5 --- /dev/null +++ b/app/vendor/rune/tools/ratex-math-wasm/rust-toolchain.toml @@ -0,0 +1,3 @@ +[toolchain] +channel = "1.99.1" +targets = ["wasm32-unknown-unknown"] diff --git a/app/vendor/rune/tools/ratex-math-wasm/src/lib.rs b/app/vendor/rune/tools/ratex-math-wasm/src/lib.rs new file mode 100644 index 0000000..f1fa2d8 --- /dev/null +++ b/app/vendor/rune/tools/ratex-math-wasm/src/lib.rs @@ -0,0 +1,196 @@ +//! Sandboxed `wasm32-unknown-unknown` LaTeX display-math parser & layout module for `rune-kit`. +//! +//! All security limits (fuel, linear memory, wall-clock deadline, and full binary wire validation) +//! are enforced on the host outside this module. This guest is kept minimal and emits a compact +//! little-endian `RM01` display list for host-side `skrifa` + `tiny-skia` rasterisation. + +use core::cell::RefCell; + +use ratex_layout::{layout, to_display_list, LayoutOptions}; +use ratex_types::{DisplayItem, PathCommand}; + +const MAX_INPUT_BYTES: usize = 16 * 1024; +const MAX_ITEMS: usize = 4096; +const MAX_PATH_COMMANDS: usize = 16_384; +const MAX_WIRE_BYTES: usize = 1024 * 1024; + +struct State { + input: Vec<u8>, + output: Vec<u8>, +} + +struct SingleThread<T>(RefCell<T>); + +// SAFETY: `wasm32-unknown-unknown` without atomics is strictly single-threaded. +unsafe impl<T> Sync for SingleThread<T> {} + +static STATE: SingleThread<State> = SingleThread(RefCell::new(State { + input: Vec::new(), + output: Vec::new(), +})); + +/// Allocates/resizes the guest input buffer to `len` bytes and returns its linear-memory pointer, +/// or `0` if `len` exceeds the input cap. +#[no_mangle] +pub extern "C" fn alloc_input(len: u32) -> u32 { + let n = len as usize; + if n == 0 || n > MAX_INPUT_BYTES { + return 0; + } + let mut st = STATE.0.borrow_mut(); + st.input.clear(); + st.input.resize(n, 0); + st.input.as_mut_ptr() as u32 +} + +/// Returns the linear-memory pointer of the most recent `RM01` output buffer. +#[no_mangle] +pub extern "C" fn out_ptr() -> u32 { + let st = STATE.0.borrow(); + st.output.as_ptr() as u32 +} + +fn push_f32(out: &mut Vec<u8>, v: f64) { + out.extend_from_slice(&(v as f32).to_le_bytes()); +} + +fn push_color(out: &mut Vec<u8>, c: ratex_types::Color) { + out.push((c.r.clamp(0.0, 1.0) * 255.0).round() as u8); + out.push((c.g.clamp(0.0, 1.0) * 255.0).round() as u8); + out.push((c.b.clamp(0.0, 1.0) * 255.0).round() as u8); + out.push((c.a.clamp(0.0, 1.0) * 255.0).round() as u8); +} + +/// Parses and lays out the `len`-byte UTF-8 TeX source written into `alloc_input(len)`. +/// Returns the byte length of the `RM01` binary display list in `out_ptr()`, or `0` on failure. +#[no_mangle] +pub extern "C" fn render_tex(len: u32) -> u32 { + let mut st = STATE.0.borrow_mut(); + let n = (len as usize).min(st.input.len()).min(MAX_INPUT_BYTES); + let trimmed = match core::str::from_utf8(&st.input[..n]) { + Ok(s) => s.trim(), + Err(_) => return 0, + }; + if trimmed.is_empty() { + return 0; + } + let nodes = match ratex_parser::parse(trimmed) { + Ok(nodes) => nodes, + Err(_) => return 0, + }; + let opts = LayoutOptions::default(); + let root = layout(&nodes, &opts); + let dl = to_display_list(&root); + if dl.items.is_empty() || dl.items.len() > MAX_ITEMS { + return 0; + } + if !dl.width.is_finite() + || !dl.height.is_finite() + || !dl.depth.is_finite() + || dl.width < 0.0 + || dl.height < 0.0 + || dl.depth < 0.0 + { + return 0; + } + let out = &mut st.output; + out.clear(); + out.extend_from_slice(b"RM01"); + push_f32(out, dl.width); + push_f32(out, dl.height); + push_f32(out, dl.depth); + out.extend_from_slice(&(dl.items.len() as u32).to_le_bytes()); + + let mut total_cmds = 0usize; + for item in &dl.items { + if out.len() > MAX_WIRE_BYTES { + out.clear(); + return 0; + } + match item { + DisplayItem::GlyphPath { x, y, scale, font, char_code, color } => { + let fb = font.as_bytes(); + if fb.is_empty() || fb.len() > 64 { + out.clear(); + return 0; + } + out.push(0); + push_f32(out, *x); + push_f32(out, *y); + push_f32(out, *scale); + out.extend_from_slice(&char_code.to_le_bytes()); + push_color(out, *color); + out.push(fb.len() as u8); + out.extend_from_slice(fb); + } + DisplayItem::Line { x, y, width, thickness, color, dashed } => { + out.push(1); + push_f32(out, *x); + push_f32(out, *y); + push_f32(out, *width); + push_f32(out, *thickness); + push_color(out, *color); + out.push(u8::from(*dashed)); + } + DisplayItem::Rect { x, y, width, height, color } => { + out.push(2); + push_f32(out, *x); + push_f32(out, *y); + push_f32(out, *width); + push_f32(out, *height); + push_color(out, *color); + } + DisplayItem::Path { x, y, commands, fill, color } => { + total_cmds = total_cmds.saturating_add(commands.len()); + if total_cmds > MAX_PATH_COMMANDS { + out.clear(); + return 0; + } + out.push(3); + push_f32(out, *x); + push_f32(out, *y); + out.push(u8::from(*fill)); + push_color(out, *color); + out.extend_from_slice(&(commands.len() as u32).to_le_bytes()); + for cmd in commands { + match cmd { + PathCommand::MoveTo { x, y } => { + out.push(0); + push_f32(out, *x); + push_f32(out, *y); + } + PathCommand::LineTo { x, y } => { + out.push(1); + push_f32(out, *x); + push_f32(out, *y); + } + PathCommand::QuadTo { x1, y1, x, y } => { + out.push(2); + push_f32(out, *x1); + push_f32(out, *y1); + push_f32(out, *x); + push_f32(out, *y); + } + PathCommand::CubicTo { x1, y1, x2, y2, x, y } => { + out.push(3); + push_f32(out, *x1); + push_f32(out, *y1); + push_f32(out, *x2); + push_f32(out, *y2); + push_f32(out, *x); + push_f32(out, *y); + } + PathCommand::Close => { + out.push(4); + } + } + } + } + } + } + if out.len() > MAX_WIRE_BYTES { + out.clear(); + return 0; + } + out.len() as u32 +} diff --git a/app/vendor/rune/tools/rune-dev-guard/Cargo.lock b/app/vendor/rune/tools/rune-dev-guard/Cargo.lock new file mode 100644 index 0000000..56a4035 --- /dev/null +++ b/app/vendor/rune/tools/rune-dev-guard/Cargo.lock @@ -0,0 +1,46 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "rune-dev-guard" +version = "0.0.1" +dependencies = [ + "quote", + "syn", +] + +[[package]] +name = "syn" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "unicode-ident" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" diff --git a/app/vendor/rune/tools/rune-dev-guard/Cargo.toml b/app/vendor/rune/tools/rune-dev-guard/Cargo.toml new file mode 100644 index 0000000..122d03d --- /dev/null +++ b/app/vendor/rune/tools/rune-dev-guard/Cargo.toml @@ -0,0 +1,14 @@ +[package] +name = "rune-dev-guard" +version = "0.0.1" +edition = "2024" +publish = false + +[workspace] + +[dependencies] +syn = { version = "2", features = ["full", "visit", "visit-mut"] } +quote = "1" + +[profile.dev] +debug = 0 diff --git a/app/vendor/rune/tools/rune-dev-guard/src/main.rs b/app/vendor/rune/tools/rune-dev-guard/src/main.rs new file mode 100644 index 0000000..85f146b --- /dev/null +++ b/app/vendor/rune/tools/rune-dev-guard/src/main.rs @@ -0,0 +1,114 @@ +//! A syntax guard, not a size_of guess: same-size field/type/signature edits are incompatible too. +use quote::ToTokens; +use syn::{parse::Parser, visit::Visit, visit_mut::VisitMut}; + +#[derive(Default)] +struct Contracts(Vec<String>); +impl<'ast> Visit<'ast> for Contracts { + fn visit_item(&mut self, item: &'ast syn::Item) { + // Local types, statics, functions and imports are also contracts. Do not erase them. + self.0.push(item.to_token_stream().to_string()); + } + fn visit_macro(&mut self, m: &'ast syn::Macro) { + // Unknown macros could expand to persistent types/statics. Keep their entire invocation. + let safe = ["format", "format_args", "vec", "matches", "println", "eprintln", "assert", "assert_eq", "debug_assert", "panic", "unreachable", "todo"]; + if m.path.get_ident().is_some_and(|i| safe.iter().any(|s| i == s)) { + // syn does not visit macro tokens. Parse their expressions explicitly so a + // local type/static or nested unknown macro cannot hide inside vec!/format!. + if m.path.is_ident("vec") { + let tokens = &m.tokens; + if let Ok(expr) = syn::parse2::<syn::Expr>(quote::quote!([#tokens])) { + self.visit_expr(&expr); + return; + } + } else if let Ok(args) = syn::punctuated::Punctuated::<syn::Expr, syn::Token![,]>::parse_terminated.parse2(m.tokens.clone()) { + for arg in args { self.visit_expr(&arg); } + return; + } + } + self.0.push(m.to_token_stream().to_string()); + } +} + +#[derive(Default)] +struct Scrub(Contracts); +impl VisitMut for Scrub { + fn visit_item_fn_mut(&mut self, f: &mut syn::ItemFn) { + // Const bodies can determine persistent layouts. Unknown attributes can + // expand the body into types or statics, even on an ordinary function. + let inert = ["doc", "inline", "cold", "allow"]; + if f.sig.ident == "main" || f.sig.constness.is_some() + || f.attrs.iter().any(|a| !a.path().get_ident().is_some_and(|i| inert.iter().any(|s| i == s))) + { return; } + self.0.visit_block(&f.block); + f.block = syn::parse_quote!({}); + } + // Impl methods, initializers, constants, attributes and module declarations stay byte-token exact. + fn visit_impl_item_fn_mut(&mut self, _: &mut syn::ImplItemFn) {} +} + +fn contract(src: &str) -> Result<String, syn::Error> { + let mut ast = syn::parse_file(src)?; + let mut scrub = Scrub::default(); + scrub.visit_file_mut(&mut ast); + Ok(format!("{}\n{:?}", ast.to_token_stream(), scrub.0.0)) +} + +fn main() { + let args: Vec<_> = std::env::args().skip(1).collect(); + assert_eq!(args.len(), 2, "rune-dev-guard BEFORE.rs AFTER.rs"); + let read = |p: &str| contract(&std::fs::read_to_string(p).expect("read source")); + match (read(&args[0]), read(&args[1])) { + (Ok(a), Ok(b)) if a == b => {} + (Ok(_), Ok(_)) => { eprintln!("restart needed: declaration, state schema, signature, startup code or persistent macro changed"); std::process::exit(3); } + (_, Err(e)) | (Err(e), _) => { eprintln!("edit not ready: {e}"); std::process::exit(2); } + } +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn compatible_bodies_but_not_state_or_boundary_changes() { + let base = "struct S { a: u32, b: u32 } fn view(s: &S) -> u32 { s.a + 1 } fn main() { let s = S { a: 1, b: 2 }; }"; + assert_eq!(contract(base).unwrap(), contract(&base.replace("s.a + 1", "s.b + 20")).unwrap()); + for edit in [base.replace("a: u32, b: u32", "b: u32, a: u32"), base.replace("s: &S", "s: &mut S"), base.replace("a: 1", "a: 9"), base.replace("s.a + 1", "static X: u32 = 3; s.a + X"), base.replace("s.a + 1", "mystery!(s)")] { + assert_ne!(contract(base).unwrap(), contract(&edit).unwrap()); + } + } + #[test] + fn nested_types_and_impls_cannot_change() { + let base = "fn view() { struct S { x: u32 } } impl S { fn init() -> u32 { 1 } }"; + assert_ne!(contract(base).unwrap(), contract(&base.replace("x: u32", "x: f32")).unwrap()); + assert_ne!(contract(base).unwrap(), contract(&base.replace("{ 1 }", "{ 2 }")).unwrap()); + assert!(contract("fn view( {").is_err()); + } + + #[test] + fn const_function_bodies_are_layout_contracts() { + for layout in ["struct S { buf: [u8; cap()] }", "const N: usize = cap(); struct S { buf: [u8; N] }"] { + let base = format!("const fn cap() -> usize {{ 8 }} {layout} fn view() {{}}"); + assert_ne!(contract(&base).unwrap(), contract(&base.replace("{ 8 }", "{ 16 }")).unwrap()); + } + } + + #[test] + fn unknown_attributes_keep_bodies_but_inert_attributes_allow_edits() { + for attribute in ["#[persistent]", "#[some::macro_attr]", "#[cfg_attr(feature = \"x\", persistent)]"] { + let base = format!("{attribute} fn view() {{ let n = 1; }}"); + assert_ne!(contract(&base).unwrap(), contract(&base.replace("n = 1", "n = 2")).unwrap()); + } + let base = "#[doc = \"view\"] #[inline(never)] #[cold] #[allow(unused)] fn view() { let n = 1; }"; + assert_eq!(contract(base).unwrap(), contract(&base.replace("n = 1", "n = 2")).unwrap()); + assert_ne!(contract(base).unwrap(), contract(&base.replace("inline(never)", "inline(always)")).unwrap()); + } + + #[test] + fn macro_arguments_cannot_hide_persistent_contracts() { + for body in ["vec![{ static X: u32 = 1; X }]", "format!(\"{}\", { struct S { x: u32 } 1 })", "vec![unknown!(1)]"] { + let base = format!("fn view() {{ {body}; }}"); + assert_ne!(contract(&base).unwrap(), contract(&base.replace("u32", "f32").replace("unknown!(1)", "unknown!(2)")).unwrap()); + } + assert_eq!(contract("fn view() { vec![1, 2]; }").unwrap(), contract("fn view() { vec![3; 4]; }").unwrap()); + } +} diff --git a/app/vendor/rune/vendor/accesskit_macos.patch b/app/vendor/rune/vendor/accesskit_macos.patch new file mode 100644 index 0000000..a93de22 --- /dev/null +++ b/app/vendor/rune/vendor/accesskit_macos.patch @@ -0,0 +1,1176 @@ +diff --git a/src/event.rs b/src/event.rs +index 445419c..a7b4389 100644 +--- a/src/event.rs ++++ b/src/event.rs +@@ -14,6 +14,7 @@ use std::{collections::VecDeque, rc::Rc}; + use crate::{ + context::Context, + filters::filter, ++ long_text::long_text, + node::{NodeWrapper, Value}, + }; + +@@ -288,8 +289,8 @@ impl TreeChangeHandler for EventGenerator { + }); + } + } +- if old_wrapper.supports_text_ranges() +- && new_wrapper.supports_text_ranges() ++ if (old_wrapper.supports_text_ranges() || long_text(old_node).is_some()) ++ && (new_wrapper.supports_text_ranges() || long_text(new_node).is_some()) + && old_wrapper.raw_text_selection() != new_wrapper.raw_text_selection() + { + self.events.push(QueuedEvent::Generic { +diff --git a/src/lib.rs b/src/lib.rs +index 5b79542..fbd7b8b 100644 +--- a/src/lib.rs ++++ b/src/lib.rs +@@ -7,6 +7,7 @@ + + mod context; + mod filters; ++mod long_text; + mod node; + mod util; + +diff --git a/src/long_text.rs b/src/long_text.rs +new file mode 100644 +index 0000000..ae053e0 +--- /dev/null ++++ b/src/long_text.rs +@@ -0,0 +1,796 @@ ++// Rune (vendor/accesskit_macos.patch): a text field too long for its toolkit to publish text ++// runs (Rune stops at 64 KiB) keeps its text ranges. The toolkit marks such a field by putting its ++// selection on the field itself, as byte offsets into its value, and publishes a single ++// GenericContainer (`class_name = "\x1frune-lines"`) holding one GenericContainer child ++// (`class_name = "\x1frune-line"`, `author_id = "<start>:<end>"`) per drawn visual line. Ranges ++// are answered from the value when a reader asks, and screen rectangles, hit-testing and wrapped ++// visual lines are answered in the drawn band without shaping off-screen rows. ++// The same file is in accesskit_windows and accesskit_macos; each uses part of it. ++#![allow(dead_code)] ++ ++use std::cell::RefCell; ++ ++use accesskit::{Point, Rect, Role, TextDirection, TextSelection}; ++use accesskit_consumer::NodeRef; ++ ++const LINES_BOX_CLASS: &str = "\x1frune-lines"; ++const LINE_CLASS: &str = "\x1frune-line"; ++const CHECKPOINT_STRIDE: usize = 65_536; ++ ++#[derive(Clone, Copy, PartialEq, Eq)] ++pub(crate) enum Unit { ++ Character, ++ Word, ++ Line, ++ Paragraph, ++ Document, ++} ++ ++/// One visual line currently drawn on screen for a long field. ++#[derive(Clone, Copy)] ++pub(crate) struct DrawnLine<'a> { ++ pub(crate) start: usize, ++ pub(crate) end: usize, ++ pub(crate) node: NodeRef<'a>, ++} ++ ++/// All drawn-line metadata published on `node` for the current tree snapshot. ++pub(crate) struct DrawnState<'a> { ++ pub(crate) lines: Vec<DrawnLine<'a>>, ++ pub(crate) content_key: u64, ++ pub(crate) upstream_caret: bool, ++ pub(crate) caret_byte: usize, ++} ++ ++struct Band { ++ start: usize, ++ end: usize, ++ first: usize, ++ count: usize, ++} ++ ++#[derive(Clone, Copy)] ++struct Mark { ++ byte: usize, ++ utf16: usize, ++ newlines: usize, ++} ++ ++struct Checkpoints { ++ content_key: u64, ++ len: usize, ++ edge: [u8; 32], ++ marks: Vec<Mark>, ++} ++ ++const CHECKPOINT_SLOTS: usize = 4; ++ ++struct CheckpointRing { ++ slots: [Option<Checkpoints>; CHECKPOINT_SLOTS], ++ next: usize, ++} ++ ++thread_local! { ++ static CHECKPOINTS: RefCell<CheckpointRing> = const { ++ RefCell::new(CheckpointRing { ++ slots: [None, None, None, None], ++ next: 0, ++ }) ++ }; ++} ++ ++fn edge_sample(s: &str) -> [u8; 32] { ++ let mut out = [0u8; 32]; ++ let b = s.as_bytes(); ++ let head = b.len().min(16); ++ out[..head].copy_from_slice(&b[..head]); ++ let tail = b.len().min(16); ++ out[16..16 + tail].copy_from_slice(&b[b.len() - tail..]); ++ out ++} ++ ++fn with_checkpoints<R>(s: &str, content_key: u64, f: impl FnOnce(&[Mark]) -> R) -> R { ++ if s.len() <= CHECKPOINT_STRIDE { ++ return f(&[Mark { byte: 0, utf16: 0, newlines: 0 }]); ++ } ++ let edge = edge_sample(s); ++ CHECKPOINTS.with(|cell| { ++ let mut ring = cell.borrow_mut(); ++ if let Some(hit) = ring.slots.iter().flatten().find(|c| { ++ c.content_key == content_key && c.len == s.len() && c.edge == edge ++ }) { ++ return f(hit.marks.as_slice()); ++ } ++ let mut marks = Vec::with_capacity(s.len() / CHECKPOINT_STRIDE + 2); ++ marks.push(Mark { byte: 0, utf16: 0, newlines: 0 }); ++ let mut utf16 = 0usize; ++ let mut newlines = 0usize; ++ let mut next_at = CHECKPOINT_STRIDE; ++ for (k, ch) in s.char_indices() { ++ if k >= next_at { ++ marks.push(Mark { byte: k, utf16, newlines }); ++ next_at = k + CHECKPOINT_STRIDE; ++ } ++ utf16 += ch.len_utf16(); ++ if ch == '\n' { ++ newlines += 1; ++ } ++ } ++ let idx = ring.next % CHECKPOINT_SLOTS; ++ ring.next = ring.next.wrapping_add(1); ++ ring.slots[idx] = Some(Checkpoints { content_key, len: s.len(), edge, marks }); ++ let marks = ring.slots[idx].as_ref().map_or(&[][..], |c| c.marks.as_slice()); ++ f(marks) ++ }) ++} ++ ++/// The value and selection a long field's text ranges are answered from. ++pub(crate) fn long_text<'a>(node: &NodeRef<'a>) -> Option<(Text<'a>, &'a TextSelection)> { ++ if !node.is_text_input() || node.is_password_input() || node.supports_text_ranges() { ++ return None; ++ } ++ let data = node.data(); ++ let selection = data.text_selection()?; ++ let (id, _) = node.locate(); ++ if selection.anchor.node != id || selection.focus.node != id { ++ return None; ++ } ++ Some((Text(data.value().unwrap_or("")), selection)) ++} ++ ++/// Drawn visual lines Rune attached to `node` inside its `\x1frune-lines` container, sorted and ++/// strictly non-overlapping. ++pub(crate) fn drawn_state<'a>(node: &NodeRef<'a>, text: Text<'a>) -> DrawnState<'a> { ++ let caret_byte = node ++ .data() ++ .text_selection() ++ .map_or(0, |s| text.clamp(s.focus.character_index)); ++ let Some(box_node) = node ++ .children() ++ .find(|c| c.role() == Role::GenericContainer && c.data().class_name() == Some(LINES_BOX_CLASS)) ++ else { ++ return DrawnState { ++ lines: Vec::new(), ++ content_key: 0, ++ upstream_caret: false, ++ caret_byte, ++ }; ++ }; ++ let (content_key, upstream_caret) = box_node ++ .author_id() ++ .and_then(|s| s.split_once(':')) ++ .map_or((0, false), |(k, u)| (u64::from_str_radix(k, 16).unwrap_or(0), u == "1")); ++ ++ let mut raw = Vec::new(); ++ for child in box_node.children() { ++ if child.role() != Role::GenericContainer || child.data().class_name() != Some(LINE_CLASS) { ++ continue; ++ } ++ let Some((a, b)) = child.author_id().and_then(|id| id.split_once(':')) else { ++ continue; ++ }; ++ let (Ok(a), Ok(b)) = (a.parse::<usize>(), b.parse::<usize>()) else { ++ continue; ++ }; ++ let start = text.clamp(a); ++ let end = text.clamp(b).max(start); ++ raw.push(DrawnLine { start, end, node: child }); ++ } ++ raw.sort_by_key(|d| (d.start, d.end)); ++ let mut lines: Vec<DrawnLine<'a>> = Vec::new(); ++ for d in raw { ++ if let Some(prev) = lines.last() ++ && (d.start < prev.end || (d.start == prev.start && d.end == prev.end)) ++ { ++ continue; ++ } ++ lines.push(d); ++ } ++ DrawnState { lines, content_key, upstream_caret, caret_byte } ++} ++ ++pub(crate) fn drawn_lines<'a>(node: &NodeRef<'a>, text: Text<'a>) -> Vec<DrawnLine<'a>> { ++ drawn_state(node, text).lines ++} ++ ++fn bands(drawn: &[DrawnLine]) -> Vec<Band> { ++ let mut out: Vec<Band> = Vec::new(); ++ for (idx, d) in drawn.iter().enumerate() { ++ if let Some(last) = out.last_mut() ++ && last.end == d.start ++ { ++ last.end = d.end; ++ last.count += 1; ++ continue; ++ } ++ out.push(Band { start: d.start, end: d.end, first: idx, count: 1 }); ++ } ++ out ++} ++ ++fn line_is_rtl(line: &NodeRef) -> bool { ++ line.data().text_direction() == Some(TextDirection::RightToLeft) ++} ++ ++fn line_is_hard_end(text: Text, end: usize) -> bool { ++ end > 0 && text.0.as_bytes().get(end - 1) == Some(&b'\n') ++} ++ ++fn caret_x_in_line(line: &NodeRef, rel_byte: usize, trailing_edge: bool) -> f64 { ++ let data = line.data(); ++ let rtl = line_is_rtl(line); ++ let w = data.bounds().map_or(0.0, |r| r.width()); ++ if trailing_edge { ++ return if rtl { 0.0 } else { w }; ++ } ++ let lengths = data.character_lengths(); ++ let positions = data.character_positions().unwrap_or(&[]); ++ let widths = data.character_widths().unwrap_or(&[]); ++ if lengths.is_empty() || positions.len() < lengths.len() || widths.len() < lengths.len() { ++ return if (rel_byte == 0) != rtl { 0.0 } else { w }; ++ } ++ let mut seen = 0usize; ++ for (k, &len) in lengths.iter().enumerate() { ++ let next = seen + usize::from(len); ++ if rel_byte < next || (rel_byte == seen && len == 0) { ++ let x0 = f64::from(positions[k]); ++ let x1 = x0 + f64::from(widths[k]); ++ let cluster_rtl = if k + 1 < lengths.len() && widths[k] > 0.0 && widths[k + 1] > 0.0 { ++ positions[k + 1] < positions[k] ++ } else if k > 0 && widths[k] > 0.0 && widths[k - 1] > 0.0 { ++ positions[k] < positions[k - 1] ++ } else { ++ rtl ++ }; ++ return if cluster_rtl { x1 } else { x0 }; ++ } ++ seen = next; ++ } ++ if rtl { 0.0 } else { w } ++} ++ ++fn span_x_in_line(line: &NodeRef, rel_start: usize, rel_end: usize) -> (f64, f64) { ++ let data = line.data(); ++ let w = data.bounds().map_or(0.0, |r| r.width()); ++ let lengths = data.character_lengths(); ++ let positions = data.character_positions().unwrap_or(&[]); ++ let widths = data.character_widths().unwrap_or(&[]); ++ if lengths.is_empty() || positions.len() < lengths.len() || widths.len() < lengths.len() { ++ return (0.0, w); ++ } ++ let mut seen = 0usize; ++ let mut min_x = f64::INFINITY; ++ let mut max_x = f64::NEG_INFINITY; ++ for (k, &len) in lengths.iter().enumerate() { ++ let next = seen + usize::from(len); ++ if next > rel_start && seen < rel_end { ++ let x0 = f64::from(positions[k]); ++ let x1 = x0 + f64::from(widths[k]).max(0.0); ++ min_x = min_x.min(x0); ++ max_x = max_x.max(x1); ++ } ++ seen = next; ++ } ++ if min_x.is_finite() && max_x.is_finite() { ++ (min_x, max_x.max(min_x)) ++ } else { ++ let x = caret_x_in_line(line, rel_start, false); ++ (x, x) ++ } ++} ++ ++/// Transformed bounding boxes (in root/window coordinates, matching AccessKit's `Range::bounding_boxes`) ++/// for the drawn portion of `a..b`. Off-screen bytes have no box, matching Chromium. ++pub(crate) fn bounding_boxes(node: &NodeRef, text: Text, a: usize, b: usize) -> Vec<Rect> { ++ let (a, b) = (text.clamp(a.min(b)), text.clamp(a.max(b))); ++ let state = drawn_state(node, text); ++ let drawn = &state.lines; ++ if drawn.is_empty() { ++ return Vec::new(); ++ } ++ if a == b { ++ if state.upstream_caret && a == state.caret_byte { ++ if let Some(d) = drawn ++ .iter() ++ .find(|d| a == d.end && d.start < d.end && !line_is_hard_end(text, d.end)) ++ && let Some(mut rect) = d.node.data().bounds() ++ { ++ let x = caret_x_in_line(&d.node, a - d.start, true); ++ let left = rect.x0 + x; ++ rect.x0 = left; ++ rect.x1 = left; ++ return vec![d.node.transform().transform_rect_bbox(rect)]; ++ } ++ } ++ let hit = drawn.iter().enumerate().find(|&(k, d)| { ++ (d.start <= a && a < d.end) ++ || (d.start == a && d.end == a) ++ || (a == d.end ++ && !line_is_hard_end(text, d.end) ++ && drawn.get(k + 1).is_none_or(|nx| nx.start != a)) ++ }); ++ let Some((_, d)) = hit else { ++ return Vec::new(); ++ }; ++ let Some(mut rect) = d.node.data().bounds() else { ++ return Vec::new(); ++ }; ++ let x = caret_x_in_line(&d.node, a.saturating_sub(d.start), false); ++ let left = rect.x0 + x; ++ rect.x0 = left; ++ rect.x1 = left; ++ return vec![d.node.transform().transform_rect_bbox(rect)]; ++ } ++ let mut out = Vec::new(); ++ for d in drawn { ++ let ov_start = a.max(d.start); ++ let ov_end = b.min(d.end); ++ if ov_start >= ov_end { ++ continue; ++ } ++ let Some(mut rect) = d.node.data().bounds() else { ++ continue; ++ }; ++ if ov_start > d.start || ov_end < d.end { ++ let orig_left = rect.x0; ++ let (x0, x1) = span_x_in_line(&d.node, ov_start - d.start, ov_end - d.start); ++ rect.x0 = orig_left + x0; ++ rect.x1 = orig_left + x1; ++ } ++ out.push(d.node.transform().transform_rect_bbox(rect)); ++ } ++ out ++} ++ ++/// Byte offset in `text` at `point` (in `node`'s local coordinate space), using containment inside ++/// the nearest drawn visual line. When `for_char` is true (macOS `accessibilityRangeForPosition:`), ++/// a point past the trailing edge of a soft-wrapped line clamps to that line's last character. ++pub(crate) fn byte_at_point(node: &NodeRef, text: Text, point: Point, for_char: bool) -> Option<usize> { ++ let drawn = drawn_lines(node, text); ++ let d = drawn.iter().min_by(|a, b| { ++ let dist = |ln: &DrawnLine| match ln.node.data().bounds() { ++ Some(r) if point.y < r.y0 => r.y0 - point.y, ++ Some(r) if point.y > r.y1 => point.y - r.y1, ++ Some(_) => 0.0, ++ None => f64::INFINITY, ++ }; ++ dist(a).total_cmp(&dist(b)) ++ })?; ++ let bounds = d.node.data().bounds()?; ++ let rel_x = (point.x - bounds.x0) as f32; ++ let data = d.node.data(); ++ let rtl = line_is_rtl(&d.node); ++ let lengths = data.character_lengths(); ++ let positions = data.character_positions().unwrap_or(&[]); ++ let widths = data.character_widths().unwrap_or(&[]); ++ if lengths.is_empty() || positions.len() < lengths.len() || widths.len() < lengths.len() { ++ return Some(d.start); ++ } ++ let mut byte_off = 0usize; ++ let mut min_x = f32::INFINITY; ++ let mut max_x = f32::NEG_INFINITY; ++ for k in 0..lengths.len() { ++ let w = widths[k]; ++ let x0 = positions[k]; ++ let x1 = x0 + w; ++ if w > 0.0 { ++ min_x = min_x.min(x0); ++ max_x = max_x.max(x1); ++ if rel_x >= x0 && rel_x < x1 { ++ return Some(text.clamp(d.start + byte_off)); ++ } ++ } ++ byte_off += usize::from(lengths[k]); ++ } ++ let trim = if d.end >= d.start + 2 && text.0.as_bytes().get(d.end - 2..d.end) == Some(b"\r\n") { ++ 2 ++ } else if d.end > d.start && text.0.as_bytes().get(d.end - 1) == Some(&b'\n') { ++ 1 ++ } else { ++ 0 ++ }; ++ let line_end = text.clamp(d.end.saturating_sub(trim)).max(d.start); ++ let leading = if rtl { rel_x >= max_x } else { rel_x <= min_x }; ++ if leading { ++ return Some(d.start); ++ } ++ if for_char && trim == 0 && line_end > d.start { ++ return Some(text.prev(line_end, Unit::Character).max(d.start)); ++ } ++ Some(line_end) ++} ++ ++fn utf16_len(s: &str) -> usize { ++ if s.is_ascii() { s.len() } else { s.chars().map(char::len_utf16).sum() } ++} ++ ++fn count_newlines_slice(s: &str) -> usize { ++ s.as_bytes().iter().filter(|&&b| b == b'\n').count() ++} ++ ++fn count_newlines_between(s: &str, a: usize, b: usize, marks: &[Mark]) -> usize { ++ if a >= b || b > s.len() { ++ return 0; ++ } ++ if b - a <= CHECKPOINT_STRIDE || marks.len() <= 1 { ++ return s.get(a..b).map_or(0, count_newlines_slice); ++ } ++ let ma = marks.partition_point(|m| m.byte <= a).saturating_sub(1); ++ let mb = marks.partition_point(|m| m.byte <= b).saturating_sub(1); ++ if mb <= ma { ++ return s.get(a..b).map_or(0, count_newlines_slice); ++ } ++ let head_sub = s.get(marks[ma].byte..a).map_or(0, count_newlines_slice); ++ let tail_add = s.get(marks[mb].byte..b).map_or(0, count_newlines_slice); ++ (marks[mb].newlines + tail_add).saturating_sub(marks[ma].newlines + head_sub) ++} ++ ++fn nth_newline_after(s: &str, from: usize, limit: usize, nth: usize, marks: &[Mark]) -> Option<usize> { ++ let sub = s.get(from..limit)?; ++ if limit - from <= CHECKPOINT_STRIDE || marks.len() <= 1 { ++ return sub.match_indices('\n').nth(nth).map(|(p, _)| from + p); ++ } ++ let m_from = marks.partition_point(|m| m.byte <= from).saturating_sub(1); ++ let base_nl = marks[m_from].newlines + s.get(marks[m_from].byte..from).map_or(0, count_newlines_slice); ++ let target_nl = base_nl + nth + 1; ++ let m_hit = marks.partition_point(|m| m.newlines < target_nl).saturating_sub(1); ++ let scan_start = marks[m_hit].byte.max(from); ++ if scan_start >= limit { ++ return None; ++ } ++ let already = if scan_start == from { ++ 0 ++ } else { ++ (marks[m_hit].newlines).saturating_sub(base_nl) ++ }; ++ let rem = nth.checked_sub(already)?; ++ s.get(scan_start..limit)? ++ .match_indices('\n') ++ .nth(rem) ++ .map(|(p, _)| scan_start + p) ++} ++ ++/// Byte offsets into a field's value. ++#[derive(Clone, Copy)] ++pub(crate) struct Text<'a>(pub(crate) &'a str); ++ ++impl<'a> Text<'a> { ++ pub(crate) fn len(self) -> usize { ++ self.0.len() ++ } ++ ++ /// `i`, within the text and on a character's start. ++ pub(crate) fn clamp(self, i: usize) -> usize { ++ self.0.floor_char_boundary(i.min(self.0.len())) ++ } ++ ++ pub(crate) fn slice(self, a: usize, b: usize) -> &'a str { ++ let (a, b) = (self.clamp(a.min(b)), self.clamp(a.max(b))); ++ self.0.get(a..b).unwrap_or("") ++ } ++ ++ fn line_start(self, i: usize) -> usize { ++ let i = self.clamp(i); ++ self.0.get(..i).and_then(|s| s.rfind('\n')).map_or(0, |p| p + 1) ++ } ++ ++ pub(crate) fn is_start(self, i: usize, unit: Unit) -> bool { ++ let i = self.clamp(i); ++ let s = self.0; ++ match unit { ++ Unit::Character => true, ++ Unit::Word => { ++ i == 0 ++ || (s.get(i..).and_then(|r| r.chars().next()).is_some_and(|c| !c.is_whitespace()) ++ && s.get(..i).and_then(|l| l.chars().next_back()).is_some_and(char::is_whitespace)) ++ } ++ Unit::Line | Unit::Paragraph => i == 0 || s.as_bytes().get(i - 1) == Some(&b'\n'), ++ Unit::Document => i == 0, ++ } ++ } ++ ++ pub(crate) fn is_start_in(self, i: usize, unit: Unit, state: &DrawnState) -> bool { ++ let i = self.clamp(i); ++ if unit == Unit::Line && !state.lines.is_empty() { ++ if state.upstream_caret ++ && i == state.caret_byte ++ && state ++ .lines ++ .iter() ++ .any(|d| i == d.end && d.start < d.end && !line_is_hard_end(self, d.end)) ++ { ++ return false; ++ } ++ if let Some(d) = state ++ .lines ++ .iter() ++ .find(|d| (d.start <= i && i < d.end) || (d.start == i && d.end == i)) ++ { ++ return i == d.start; ++ } ++ } ++ self.is_start(i, unit) ++ } ++ ++ /// The start of the unit holding `i`. ++ pub(crate) fn start_of(self, i: usize, unit: Unit) -> usize { ++ let i = self.clamp(i); ++ if self.is_start(i, unit) { i } else { self.prev(i, unit) } ++ } ++ ++ pub(crate) fn start_of_in(self, i: usize, unit: Unit, state: &DrawnState) -> usize { ++ let i = self.clamp(i); ++ if self.is_start_in(i, unit, state) { ++ i ++ } else { ++ self.prev_in(i, unit, &state.lines) ++ } ++ } ++ ++ /// The first unit start after `i`, or the text's end. ++ pub(crate) fn next(self, i: usize, unit: Unit) -> usize { ++ let i = self.clamp(i); ++ let s = self.0; ++ let tail = s.get(i..).unwrap_or(""); ++ match unit { ++ Unit::Character => tail.chars().next().map_or(i, |c| i + c.len_utf8()), ++ Unit::Word => { ++ let mut space = false; ++ for (k, c) in tail.char_indices() { ++ if c.is_whitespace() { ++ space = true; ++ } else if space { ++ return i + k; ++ } ++ } ++ s.len() ++ } ++ Unit::Line | Unit::Paragraph => tail.find('\n').map_or(s.len(), |p| i + p + 1), ++ Unit::Document => s.len(), ++ } ++ } ++ ++ pub(crate) fn next_in(self, i: usize, unit: Unit, drawn: &[DrawnLine]) -> usize { ++ let i = self.clamp(i); ++ if unit != Unit::Line || drawn.is_empty() { ++ return self.next(i, unit); ++ } ++ if let Some(d) = drawn.iter().find(|d| d.start <= i && i < d.end) { ++ return d.end; ++ } ++ let nl = self.next(i, Unit::Line); ++ drawn ++ .iter() ++ .find(|d| d.start > i && d.start < nl) ++ .map_or(nl, |d| d.start) ++ } ++ ++ /// The last unit start before `i`, or the text's start. ++ pub(crate) fn prev(self, i: usize, unit: Unit) -> usize { ++ let i = self.clamp(i); ++ let s = self.0; ++ let head = s.get(..i).unwrap_or(""); ++ match unit { ++ Unit::Character => head.chars().next_back().map_or(0, |c| i - c.len_utf8()), ++ Unit::Word => { ++ let mut word = None; ++ for (k, c) in head.char_indices().rev() { ++ if !c.is_whitespace() { ++ word = Some(k); ++ } else if let Some(k) = word { ++ return k; ++ } ++ } ++ 0 ++ } ++ Unit::Line | Unit::Paragraph => { ++ if i == 0 { ++ return 0; ++ } ++ let at = self.line_start(i); ++ if at < i { ++ at ++ } else { ++ self.line_start(self.clamp(i - 1)) ++ } ++ } ++ Unit::Document => 0, ++ } ++ } ++ ++ pub(crate) fn prev_in(self, i: usize, unit: Unit, drawn: &[DrawnLine]) -> usize { ++ let i = self.clamp(i); ++ if unit != Unit::Line || drawn.is_empty() || i == 0 { ++ return self.prev(i, unit); ++ } ++ if let Some(d) = drawn.iter().rfind(|d| d.start < i && i <= d.end) { ++ return d.start; ++ } ++ if drawn.iter().any(|d| d.start == i) { ++ if let Some(prev_d) = drawn.iter().rfind(|d| d.end == i && d.start < i) { ++ return prev_d.start; ++ } ++ return self.prev(i, Unit::Line); ++ } ++ let p = self.prev(i, Unit::Line); ++ drawn ++ .iter() ++ .rfind(|d| d.start >= p && d.start < i) ++ .map_or(p, |d| d.start) ++ } ++ ++ /// Moves `i` by `count` unit starts, stopping at either end of the text. ++ pub(crate) fn step_in(self, i: usize, unit: Unit, count: i32, drawn: &[DrawnLine]) -> (usize, i32) { ++ let mut i = self.clamp(i); ++ if count == 0 { ++ return (i, 0); ++ } ++ let mut moved = 0i32; ++ let steps = count.unsigned_abs(); ++ for _ in 0..steps { ++ if (count > 0 && i == self.len()) || (count < 0 && i == 0) { ++ break; ++ } ++ let next_i = if count > 0 { ++ self.next_in(i, unit, drawn) ++ } else { ++ self.prev_in(i, unit, drawn) ++ }; ++ if next_i == i { ++ break; ++ } ++ i = next_i; ++ moved = moved.saturating_add(1); ++ } ++ (i, if count < 0 { -moved } else { moved }) ++ } ++ ++ /// The zero-based line holding byte `i`, counting drawn wrapped lines visually. ++ pub(crate) fn line_of_in(self, i: usize, state: &DrawnState) -> usize { ++ let i = self.clamp(i); ++ let s = self.0; ++ let drawn = &state.lines; ++ let bs = bands(drawn); ++ with_checkpoints(s, state.content_key, |marks| { ++ if bs.is_empty() { ++ return count_newlines_between(s, 0, i, marks); ++ } ++ let mut lines = 0usize; ++ let mut cursor = 0usize; ++ for b in &bs { ++ if i < b.start { ++ return lines + count_newlines_between(s, cursor, i, marks); ++ } ++ lines += count_newlines_between(s, cursor, b.start, marks); ++ let band_slice = &drawn[b.first..b.first + b.count]; ++ let has_trailing_empty = ++ band_slice.last().is_some_and(|d| d.start == b.end && d.end == b.end); ++ let in_band_at_end = i == b.end ++ && b.end == s.len() ++ && (has_trailing_empty || !line_is_hard_end(self, b.end)); ++ if i < b.end ++ || in_band_at_end ++ || (state.upstream_caret ++ && i == state.caret_byte ++ && i == b.end ++ && b.start < b.end ++ && !line_is_hard_end(self, b.end)) ++ { ++ if state.upstream_caret && i == state.caret_byte { ++ if let Some(sub) = band_slice ++ .iter() ++ .position(|d| i == d.end && d.start < d.end && !line_is_hard_end(self, d.end)) ++ { ++ return lines + sub; ++ } ++ } ++ let sub = band_slice.iter().rposition(|d| d.start <= i).unwrap_or(0); ++ return lines + sub; ++ } ++ lines += b.count; ++ cursor = b.end; ++ } ++ lines + count_newlines_between(s, cursor, i, marks) ++ }) ++ } ++ ++ /// Line `n`'s bytes, counting drawn wrapped lines visually. ++ pub(crate) fn line_in(self, n: usize, state: &DrawnState) -> Option<(usize, usize)> { ++ let s = self.0; ++ let drawn = &state.lines; ++ let bs = bands(drawn); ++ with_checkpoints(s, state.content_key, |marks| { ++ if bs.is_empty() { ++ let start = if n == 0 { ++ 0 ++ } else { ++ nth_newline_after(s, 0, s.len(), n - 1, marks)? + 1 ++ }; ++ return Some((start, self.next(start, Unit::Line))); ++ } ++ let mut rem = n; ++ let mut cursor = 0usize; ++ for b in &bs { ++ let gap_lines = count_newlines_between(s, cursor, b.start, marks); ++ if rem < gap_lines { ++ let start = if rem == 0 { ++ cursor ++ } else { ++ nth_newline_after(s, cursor, b.start, rem - 1, marks)? + 1 ++ }; ++ return Some((start, self.next(start, Unit::Line).min(b.start))); ++ } ++ rem -= gap_lines; ++ if rem < b.count { ++ let d = &drawn[b.first + rem]; ++ return Some((d.start, d.end)); ++ } ++ rem -= b.count; ++ cursor = b.end; ++ } ++ let drawn_has_end_empty = ++ drawn.last().is_some_and(|d| d.start == s.len() && d.end == s.len()); ++ if cursor >= s.len() { ++ if !drawn_has_end_empty && line_is_hard_end(self, s.len()) && rem == 0 { ++ return Some((s.len(), s.len())); ++ } ++ return None; ++ } ++ let start = if rem == 0 { ++ cursor ++ } else { ++ nth_newline_after(s, cursor, s.len(), rem - 1, marks)? + 1 ++ }; ++ Some((start, self.next(start, Unit::Line))) ++ }) ++ } ++ ++ pub(crate) fn utf16_with(self, i: usize, key: u64) -> usize { ++ let i = self.clamp(i); ++ with_checkpoints(self.0, key, |marks| { ++ let idx = marks.partition_point(|m| m.byte <= i).saturating_sub(1); ++ let m = marks.get(idx).copied().unwrap_or(Mark { byte: 0, utf16: 0, newlines: 0 }); ++ m.utf16 + self.0.get(m.byte..i).map_or(0, utf16_len) ++ }) ++ } ++ ++ pub(crate) fn utf16(self, i: usize) -> usize { ++ self.utf16_with(i, 0) ++ } ++ ++ /// Bytes `a..b` as a UTF-16 start and length. ++ pub(crate) fn utf16_span_with(self, a: usize, b: usize, key: u64) -> (usize, usize) { ++ let (a, b) = (self.clamp(a.min(b)), self.clamp(a.max(b))); ++ let start = self.utf16_with(a, key); ++ let len = if b - a <= CHECKPOINT_STRIDE { ++ self.0.get(a..b).map_or(0, utf16_len) ++ } else { ++ self.utf16_with(b, key).saturating_sub(start) ++ }; ++ (start, len) ++ } ++ ++ pub(crate) fn utf16_span(self, a: usize, b: usize) -> (usize, usize) { ++ self.utf16_span_with(a, b, 0) ++ } ++ ++ pub(crate) fn from_utf16_with(self, units: usize, key: u64) -> usize { ++ with_checkpoints(self.0, key, |marks| { ++ let idx = marks.partition_point(|m| m.utf16 <= units).saturating_sub(1); ++ let m = marks.get(idx).copied().unwrap_or(Mark { byte: 0, utf16: 0, newlines: 0 }); ++ let mut seen = m.utf16; ++ let tail = self.0.get(m.byte..).unwrap_or(""); ++ for (k, c) in tail.char_indices() { ++ if seen >= units { ++ return m.byte + k; ++ } ++ seen += c.len_utf16(); ++ } ++ self.0.len() ++ }) ++ } ++ ++ pub(crate) fn from_utf16(self, units: usize) -> usize { ++ self.from_utf16_with(units, 0) ++ } ++} +diff --git a/src/node.rs b/src/node.rs +index 7be2e59..7322204 100644 +--- a/src/node.rs ++++ b/src/node.rs +@@ -29,7 +29,32 @@ use objc2_foundation::{ + }; + use std::rc::{Rc, Weak}; + +-use crate::{context::Context, filters::filter, util::*}; ++use crate::{ ++ context::Context, ++ filters::filter, ++ long_text::{Text, Unit, bounding_boxes, byte_at_point, drawn_state, long_text}, ++ util::*, ++}; ++ ++/// Rune: bytes `a..b` of a long field's value ([`long_text`]) as AppKit's range. ++fn long_ns_range(text: Text, a: usize, b: usize, key: u64) -> NSRange { ++ let (start, len) = text.utf16_span_with(a, b, key); ++ NSRange::new(start, len) ++} ++ ++/// Rune: AppKit's range in a long field's value as bytes. ++fn long_bytes(text: Text, range: NSRange, key: u64) -> (usize, usize) { ++ ( ++ text.from_utf16_with(range.location, key), ++ text.from_utf16_with(range.location.saturating_add(range.length), key), ++ ) ++} ++ ++/// Rune: the character at `index` (UTF-16) in a long field's value. ++fn long_char(text: Text, index: usize, key: u64) -> NSRange { ++ let at = text.from_utf16_with(index, key); ++ long_ns_range(text, at, text.next(at, Unit::Character), key) ++} + + const SCROLL_TO_VISIBLE_ACTION: &str = "AXScrollToVisible"; + +@@ -122,7 +147,10 @@ fn ns_role(node: &NodeRef) -> &'static NSAccessibilityRole { + Role::Grid => NSAccessibilityTableRole, + Role::Group => NSAccessibilityGroupRole, + Role::Header => NSAccessibilityGroupRole, +- Role::Heading => ns_string!("Heading"), ++ // Rune (vendor/accesskit_macos.patch): AppKit's heading role, which VoiceOver's ++ // rotor and VO-Command-H find, as WebKit and Chromium give it. The published ++ // "Heading" is no role VoiceOver knows. ++ Role::Heading => ns_string!("AXHeading"), + Role::Iframe => NSAccessibilityGroupRole, + Role::IframePresentational => NSAccessibilityGroupRole, + Role::ImeCandidate => NSAccessibilityUnknownRole, +@@ -355,6 +383,12 @@ impl NodeWrapper<'_> { + return Some(Value::String(label)); + } + } ++ // Rune (vendor/accesskit_macos.patch): a heading's value is its level, as WebKit and ++ // Chromium give VoiceOver ("heading level 2"); Rune sets AccessKit's level one less ++ // (`a11y/node.rs`), and ARIA's default is 2. ++ if self.0.role() == Role::Heading { ++ return Some(Value::Number(self.0.level().map_or(2, |l| l + 1).clamp(1, 9) as f64)); ++ } + if let Some(value) = self.0.value() { + return Some(Value::String(value)); + } +@@ -755,6 +789,10 @@ declare_class!( + #[method(accessibilityNumberOfCharacters)] + fn number_of_characters(&self) -> NSInteger { + self.resolve(|node| { ++ if let Some((text, _)) = long_text(node) { ++ let state = drawn_state(node, text); ++ return text.utf16_with(text.len(), state.content_key) as _; ++ } + if node.supports_text_ranges() { + node.document_range().end().to_global_utf16_index() as _ + } else { +@@ -767,6 +805,9 @@ declare_class!( + #[method_id(accessibilitySelectedText)] + fn selected_text(&self) -> Option<Id<NSString>> { + self.resolve(|node| { ++ if let Some((text, s)) = long_text(node) { ++ return Some(NSString::from_str(text.slice(s.anchor.character_index, s.focus.character_index))); ++ } + if node.supports_text_ranges() { + if let Some(range) = node.text_selection() { + let text = range.text(); +@@ -781,6 +822,10 @@ declare_class!( + #[method(accessibilitySelectedTextRange)] + fn selected_text_range(&self) -> NSRange { + self.resolve(|node| { ++ if let Some((text, s)) = long_text(node) { ++ let state = drawn_state(node, text); ++ return long_ns_range(text, s.anchor.character_index, s.focus.character_index, state.content_key); ++ } + if node.supports_text_ranges() { + if let Some(range) = node.text_selection() { + return to_ns_range(&range); +@@ -794,6 +839,10 @@ declare_class!( + #[method(accessibilityInsertionPointLineNumber)] + fn insertion_point_line_number(&self) -> NSInteger { + self.resolve(|node| { ++ if let Some((text, s)) = long_text(node) { ++ let state = drawn_state(node, text); ++ return text.line_of_in(text.clamp(s.focus.character_index), &state) as _; ++ } + if node.supports_text_ranges() { + if let Some(pos) = node.text_selection_focus() { + return pos.to_line_index() as _; +@@ -807,6 +856,11 @@ declare_class!( + #[method(accessibilityRangeForLine:)] + fn range_for_line(&self, line_index: NSInteger) -> NSRange { + self.resolve(|node| { ++ if let Some((text, _)) = long_text(node) { ++ let state = drawn_state(node, text); ++ let line = usize::try_from(line_index).ok().and_then(|n| text.line_in(n, &state)); ++ return line.map_or_else(|| NSRange::new(0, 0), |(a, b)| long_ns_range(text, a, b, state.content_key)); ++ } + if node.supports_text_ranges() && line_index >= 0 { + if let Some(range) = node.line_range_from_index(line_index as _) { + return to_ns_range(&range); +@@ -827,6 +881,12 @@ declare_class!( + } + }; + ++ if let Some((text, s)) = long_text(node) { ++ let state = drawn_state(node, text); ++ let pt = from_ns_point(&view, node, point); ++ let at = byte_at_point(node, text, pt, true).unwrap_or_else(|| text.clamp(s.focus.character_index)); ++ return long_ns_range(text, at, text.next(at, Unit::Character), state.content_key); ++ } + if node.supports_text_ranges() { + let point = from_ns_point(&view, node, point); + let pos = node.text_position_at_point(point); +@@ -840,6 +900,11 @@ declare_class!( + #[method_id(accessibilityStringForRange:)] + fn string_for_range(&self, range: NSRange) -> Option<Id<NSString>> { + self.resolve(|node| { ++ if let Some((text, _)) = long_text(node) { ++ let state = drawn_state(node, text); ++ let (a, b) = long_bytes(text, range, state.content_key); ++ return Some(NSString::from_str(text.slice(a, b))); ++ } + if node.supports_text_ranges() { + if let Some(range) = from_ns_range(node, range) { + let text = range.text(); +@@ -854,6 +919,12 @@ declare_class!( + #[method_id(accessibilityAttributedStringForRange:)] + fn attributed_string_for_range(&self, range: NSRange) -> Option<Id<NSAttributedString>> { + self.resolve(|node| { ++ if let Some((text, _)) = long_text(node) { ++ let state = drawn_state(node, text); ++ let (a, b) = long_bytes(text, range, state.content_key); ++ let plain = NSAttributedString::from_nsstring(&NSString::from_str(text.slice(a, b))); ++ return Some(plain); ++ } + if node.supports_text_ranges() { + if let Some(range) = from_ns_range(node, range) { + let mut result = NSMutableAttributedString::new(); +@@ -967,6 +1038,15 @@ declare_class!( + } + }; + ++ if let Some((text, _)) = long_text(node) { ++ let state = drawn_state(node, text); ++ let (a, b) = long_bytes(text, range, state.content_key); ++ let rects = bounding_boxes(node, text, a, b); ++ if let Some(rect) = rects.into_iter().reduce(|r1, r2| r1.union(r2)) { ++ return to_ns_rect(&view, rect); ++ } ++ return NSRect::ZERO; ++ } + if node.supports_text_ranges() { + if let Some(range) = from_ns_range(node, range) { + let rects = range.bounding_boxes(); +@@ -985,6 +1065,10 @@ declare_class!( + #[method(accessibilityLineForIndex:)] + fn line_for_index(&self, index: NSInteger) -> NSInteger { + self.resolve(|node| { ++ if let Some((text, _)) = long_text(node) { ++ let state = drawn_state(node, text); ++ return text.line_of_in(text.from_utf16_with(index.max(0) as _, state.content_key), &state) as _; ++ } + if node.supports_text_ranges() && index >= 0 { + if let Some(pos) = node.text_position_from_global_utf16_index(index as _) { + return pos.to_line_index() as _; +@@ -998,6 +1082,10 @@ declare_class!( + #[method(accessibilityRangeForIndex:)] + fn range_for_index(&self, index: NSInteger) -> NSRange { + self.resolve(|node| { ++ if let Some((text, _)) = long_text(node) { ++ let state = drawn_state(node, text); ++ return long_char(text, index.max(0) as _, state.content_key); ++ } + if node.supports_text_ranges() && index >= 0 { + if let Some(pos) = node.text_position_from_global_utf16_index(index as _) { + return to_ns_range_for_character(&pos); +@@ -1011,6 +1099,11 @@ declare_class!( + #[method(accessibilityStyleRangeForIndex:)] + fn style_range_for_index(&self, index: NSInteger) -> NSRange { + self.resolve(|node| { ++ // A long field's text is one style. ++ if let Some((text, _)) = long_text(node) { ++ let state = drawn_state(node, text); ++ return long_ns_range(text, 0, text.len(), state.content_key); ++ } + if node.supports_text_ranges() && index >= 0 { + if let Some(pos) = node.text_position_from_global_utf16_index(index as _) { + let start = if pos.is_format_start() { +@@ -1031,6 +1124,19 @@ declare_class!( + #[method(setAccessibilitySelectedTextRange:)] + fn set_selected_text_range(&self, range: NSRange) { + self.resolve_with_context(|node, tree, context| { ++ if let Some((text, _)) = long_text(node) { ++ let state = drawn_state(node, text); ++ let (a, b) = long_bytes(text, range, state.content_key); ++ let (target_node, target_tree) = node.locate(); ++ let at = |character_index| accesskit::TextPosition { node: target_node, character_index }; ++ context.do_action(ActionRequest { ++ action: Action::SetTextSelection, ++ target_tree, ++ target_node, ++ data: Some(ActionData::SetTextSelection(TextSelection { anchor: at(a), focus: at(b) })), ++ }); ++ return; ++ } + if node.supports_text_ranges() { + if let Some(range) = from_ns_range(node, range) { + if let Some((target_node, target_tree)) = tree.state().locate_node(node.id()) { +@@ -1260,7 +1366,7 @@ declare_class!( + || selector == sel!(accessibilityStyleRangeForIndex:) + || selector == sel!(setAccessibilitySelectedTextRange:) + { +- return node.supports_text_ranges(); ++ return node.supports_text_ranges() || long_text(node).is_some(); + } + if selector == sel!(setAccessibilityValue:) { + return (node.supports_text_ranges() && !node.is_read_only()) || node.supports_action(Action::SetValue, &filter); +@@ -1341,11 +1447,15 @@ impl PlatformNode { + where + F: FnOnce(&NodeRef, &Tree, &Rc<Context>) -> T, + { +- let context = self.ivars().context.upgrade()?; +- let tree = context.tree.borrow(); +- let state = tree.state(); +- let node = state.node_by_id(self.ivars().node_id)?; +- Some(f(&node, &tree, &context)) ++ std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { ++ let context = self.ivars().context.upgrade()?; ++ let tree = context.tree.borrow(); ++ let state = tree.state(); ++ let node = state.node_by_id(self.ivars().node_id)?; ++ Some(f(&node, &tree, &context)) ++ })) ++ .ok() ++ .flatten() + } + + fn resolve<F, T>(&self, f: F) -> Option<T> +diff --git a/src/subclass.rs b/src/subclass.rs +index f4ebc19..6e10394 100644 +--- a/src/subclass.rs ++++ b/src/subclass.rs +@@ -19,7 +19,7 @@ use objc2::{ + sel, + }; + use objc2_app_kit::{NSView, NSWindow}; +-use objc2_foundation::{NSArray, NSObject, NSPoint}; ++use objc2_foundation::{MainThreadMarker, NSArray, NSObject, NSPoint}; + use std::{cell::RefCell, ffi::c_void, sync::Mutex}; + + use crate::{Adapter, event::QueuedEvents}; +@@ -80,6 +80,16 @@ fn associated_object(view: &NSView) -> Option<&AssociatedObject> { + } + } + ++// Rune (vendor/accesskit_macos.patch): AppKit can call the accessibility methods below from a ++// background thread, while this process asks the system about itself (a hit test, or the focused ++// application), and the main thread may hold the adapter's `RefCell` borrow at that moment. ++// Borrowing off the main thread would race, or panic inside `extern "C"` and abort, so answer as ++// though the view had no adapter and let the superclass's own answer through. ++fn associated_object_on_main_thread(view: &NSView) -> Option<&AssociatedObject> { ++ MainThreadMarker::new()?; ++ associated_object(view) ++} ++ + // Unlike `[view class]`, this sees the subclass that key-value observing + // hides by overriding `class`. + fn runtime_class(view: &NSView) -> &'static AnyClass { +@@ -119,7 +129,7 @@ unsafe extern "C" fn superclass(this: &NSView, _cmd: Sel) -> Option<&AnyClass> { + } + + unsafe extern "C" fn children(this: &NSView, _cmd: Sel) -> *mut NSArray<NSObject> { +- let Some(associated) = associated_object(this) else { ++ let Some(associated) = associated_object_on_main_thread(this) else { + return unsafe { msg_send![super(this, prev_class(this)), accessibilityChildren] }; + }; + let mut state = associated.ivars().state.borrow_mut(); +@@ -130,7 +140,7 @@ unsafe extern "C" fn children(this: &NSView, _cmd: Sel) -> *mut NSArray<NSObject + } + + unsafe extern "C" fn focus(this: &NSView, _cmd: Sel) -> *mut NSObject { +- let Some(associated) = associated_object(this) else { ++ let Some(associated) = associated_object_on_main_thread(this) else { + return unsafe { msg_send![super(this, prev_class(this)), accessibilityFocusedUIElement] }; + }; + let mut state = associated.ivars().state.borrow_mut(); +@@ -139,7 +149,7 @@ unsafe extern "C" fn focus(this: &NSView, _cmd: Sel) -> *mut NSObject { + } + + unsafe extern "C" fn hit_test(this: &NSView, _cmd: Sel, point: NSPoint) -> *mut NSObject { +- let Some(associated) = associated_object(this) else { ++ let Some(associated) = associated_object_on_main_thread(this) else { + return unsafe { msg_send![super(this, prev_class(this)), accessibilityHitTest: point] }; + }; + let mut state = associated.ivars().state.borrow_mut(); +diff --git a/src/util.rs b/src/util.rs +index f5146a7..8197676 100644 +--- a/src/util.rs ++++ b/src/util.rs +@@ -36,7 +36,9 @@ pub(crate) fn to_ns_range_for_character(pos: &TextPosition) -> NSRange { + } + + pub(crate) fn from_ns_point(view: &NSView, node: &NodeRef, point: NSPoint) -> Point { +- let window = view.window().unwrap(); ++ let Some(window) = view.window() else { ++ return Point::ZERO; ++ }; + let point = window.convertPointFromScreen(point); + let point = view.convertPoint_fromView(point, None); + // AccessKit coordinates are in physical (DPI-dependent) pixels, but +@@ -55,7 +57,9 @@ pub(crate) fn from_ns_point(view: &NSView, node: &NodeRef, point: NSPoint) -> Po + } + + pub(crate) fn to_ns_rect(view: &NSView, rect: Rect) -> NSRect { +- let window = view.window().unwrap(); ++ let Some(window) = view.window() else { ++ return NSRect::ZERO; ++ }; + // AccessKit coordinates are in physical (DPI-dependent) + // pixels, but macOS expects logical (DPI-independent) + // coordinates here. diff --git a/app/vendor/rune/vendor/accesskit_macos/.cargo_vcs_info.json b/app/vendor/rune/vendor/accesskit_macos/.cargo_vcs_info.json new file mode 100644 index 0000000..7d590be --- /dev/null +++ b/app/vendor/rune/vendor/accesskit_macos/.cargo_vcs_info.json @@ -0,0 +1,6 @@ +{ + "git": { + "sha1": "f3026222559c7f5f46d8f25cb7404de68eb149f0" + }, + "path_in_vcs": "adapters/macos" +} \ No newline at end of file diff --git a/app/vendor/rune/vendor/accesskit_macos/CHANGELOG.md b/app/vendor/rune/vendor/accesskit_macos/CHANGELOG.md new file mode 100644 index 0000000..32f3065 --- /dev/null +++ b/app/vendor/rune/vendor/accesskit_macos/CHANGELOG.md @@ -0,0 +1,816 @@ +# Changelog + +* The following workspace dependencies were updated + * dependencies + * accesskit_consumer bumped from 0.11.0 to 0.12.0 + +* The following workspace dependencies were updated + * dependencies + * accesskit_consumer bumped from 0.12.0 to 0.12.1 + +* The following workspace dependencies were updated + * dependencies + * accesskit bumped from 0.10.0 to 0.10.1 + * accesskit_consumer bumped from 0.14.0 to 0.14.1 + +* The following workspace dependencies were updated + * dependencies + * accesskit bumped from 0.12.0 to 0.12.1 + * accesskit_consumer bumped from 0.16.0 to 0.16.1 + +* The following workspace dependencies were updated + * dependencies + * accesskit bumped from 0.12.2 to 0.12.3 + * accesskit_consumer bumped from 0.17.0 to 0.17.1 + +* The following workspace dependencies were updated + * dependencies + * accesskit_consumer bumped from 0.19.0 to 0.19.1 + +* The following workspace dependencies were updated + * dependencies + * accesskit bumped from 0.16.0 to 0.16.1 + * accesskit_consumer bumped from 0.24.0 to 0.24.1 + +* The following workspace dependencies were updated + * dependencies + * accesskit bumped from 0.16.2 to 0.16.3 + * accesskit_consumer bumped from 0.24.2 to 0.24.3 + +## [0.27.2](https://github.com/AccessKit/accesskit/compare/accesskit_macos-v0.27.1...accesskit_macos-v0.27.2) (2026-10-25) + + +### Bug Fixes + +* Fully drop macOS SubclassingAdapter if KVO is detected ([#835](https://github.com/AccessKit/accesskit/issues/835)) ([451885c](https://github.com/AccessKit/accesskit/commit/451885c1850ec1800cea1d0660bf8ba62e0f410d)) + + +### Dependencies + +* The following workspace dependencies were updated + * dependencies + * accesskit bumped from 0.25.1 to 0.25.2 + * accesskit_consumer bumped from 0.39.1 to 0.39.2 + +## [0.27.1](https://github.com/AccessKit/accesskit/compare/accesskit_macos-v0.27.0...accesskit_macos-v0.27.1) (2026-09-25) + + +### Dependencies + +* The following workspace dependencies were updated + * dependencies + * accesskit bumped from 0.25.0 to 0.25.1 + * accesskit_consumer bumped from 0.39.0 to 0.39.1 + +## [0.27.0](https://github.com/AccessKit/accesskit/compare/accesskit_macos-v0.26.3...accesskit_macos-v0.27.0) (2026-08-29) + + +### Features + +* Add html_id node property ([#776](https://github.com/AccessKit/accesskit/issues/776)) ([5332ac0](https://github.com/AccessKit/accesskit/commit/5332ac0927b7fb78eff6b8b68c21ef4c801aae7c)) + + +### Bug Fixes + +* Improve macOS subrole mapping ([#775](https://github.com/AccessKit/accesskit/issues/775)) ([04b3513](https://github.com/AccessKit/accesskit/commit/04b351345825a8de5325c9b391696411d0c7207b)) +* Label via accessibilityValue for some roles on macOS ([#756](https://github.com/AccessKit/accesskit/issues/756)) ([cc49415](https://github.com/AccessKit/accesskit/commit/cc49415fa144d365af2337e869f86b953cfc239d)) +* Support live updates for non-label nodes on macOS and iOS ([#782](https://github.com/AccessKit/accesskit/issues/782)) ([e6ae72f](https://github.com/AccessKit/accesskit/commit/e6ae72f38ba06f082fac951726cf330c52566c83)) + + +### Dependencies + +* The following workspace dependencies were updated + * dependencies + * accesskit bumped from 0.24.1 to 0.25.0 + * accesskit_consumer bumped from 0.38.0 to 0.39.0 + +## [0.26.3](https://github.com/AccessKit/accesskit/compare/accesskit_macos-v0.26.2...accesskit_macos-v0.26.3) (2026-07-14) + + +### Dependencies + +* The following workspace dependencies were updated + * dependencies + * accesskit_consumer bumped from 0.37.0 to 0.38.0 + +## [0.26.2](https://github.com/AccessKit/accesskit/compare/accesskit_macos-v0.26.1...accesskit_macos-v0.26.2) (2026-06-12) + + +### Dependencies + +* The following workspace dependencies were updated + * dependencies + * accesskit bumped from 0.24.0 to 0.24.1 + * accesskit_consumer bumped from 0.36.0 to 0.37.0 + +## [0.26.1](https://github.com/AccessKit/accesskit/compare/accesskit_macos-v0.26.0...accesskit_macos-v0.26.1) (2026-05-11) + + +### Dependencies + +* The following workspace dependencies were updated + * dependencies + * accesskit_consumer bumped from 0.35.0 to 0.36.0 + +## [0.26.0](https://github.com/AccessKit/accesskit/compare/accesskit_macos-v0.25.0...accesskit_macos-v0.26.0) (2026-03-04) + + +### Features + +* Expose text attributes on macOS ([#691](https://github.com/AccessKit/accesskit/issues/691)) ([641b05b](https://github.com/AccessKit/accesskit/commit/641b05b10d3d55631a73d10a1f753111dde372e8)) + + +### Dependencies + +* The following workspace dependencies were updated + * dependencies + * accesskit_consumer bumped from 0.34.0 to 0.35.0 + +## [0.25.0](https://github.com/AccessKit/accesskit/compare/accesskit_macos-v0.24.1...accesskit_macos-v0.25.0) (2026-02-01) + + +### ⚠ BREAKING CHANGES + +* Update minimum supported Rust version to 1.85 ([#683](https://github.com/AccessKit/accesskit/issues/683)) + +### Bug Fixes + +* Update minimum supported Rust version to 1.85 ([#683](https://github.com/AccessKit/accesskit/issues/683)) ([f8c22cb](https://github.com/AccessKit/accesskit/commit/f8c22cbb53ce6b1859adeff3c0b7154ad9e1f25e)) + + +### Dependencies + +* The following workspace dependencies were updated + * dependencies + * accesskit bumped from 0.23.0 to 0.24.0 + * accesskit_consumer bumped from 0.33.1 to 0.34.0 + +## [0.24.1](https://github.com/AccessKit/accesskit/compare/accesskit_macos-v0.24.0...accesskit_macos-v0.24.1) (2026-01-18) + + +### Bug Fixes + +* Emit initial focus event for active descendant node ([#681](https://github.com/AccessKit/accesskit/issues/681)) ([13a37d1](https://github.com/AccessKit/accesskit/commit/13a37d144e2fafceaf26e7645f6acc679ccb2f34)) + + +### Dependencies + +* The following workspace dependencies were updated + * dependencies + * accesskit_consumer bumped from 0.33.0 to 0.33.1 + +## [0.24.0](https://github.com/AccessKit/accesskit/compare/accesskit_macos-v0.23.0...accesskit_macos-v0.24.0) (2026-01-15) + + +### ⚠ BREAKING CHANGES + +* Multiple tree support ([#655](https://github.com/AccessKit/accesskit/issues/655)) + +### Features + +* Implement the `url` property ([#669](https://github.com/AccessKit/accesskit/issues/669)) ([6202e63](https://github.com/AccessKit/accesskit/commit/6202e63c667e73216a306b3dd45ff25c364a4f45)) +* Multiple tree support ([#655](https://github.com/AccessKit/accesskit/issues/655)) ([c16eb80](https://github.com/AccessKit/accesskit/commit/c16eb80c49d14f39e8a7defb1694bf22b8ceed6f)) + + +### Dependencies + +* The following workspace dependencies were updated + * dependencies + * accesskit bumped from 0.22.0 to 0.23.0 + * accesskit_consumer bumped from 0.32.0 to 0.33.0 + +## [0.23.0](https://github.com/AccessKit/accesskit/compare/accesskit_macos-v0.22.2...accesskit_macos-v0.23.0) (2025-12-23) + + +### ⚠ BREAKING CHANGES + +* Drop deprecated roles ([#642](https://github.com/AccessKit/accesskit/issues/642)) +* Infrastructure for supporting text formatting changes ([#626](https://github.com/AccessKit/accesskit/issues/626)) + +### Features + +* Add GridCell role ([#643](https://github.com/AccessKit/accesskit/issues/643)) ([1e5abca](https://github.com/AccessKit/accesskit/commit/1e5abca737d1ee942c0804fec2c06d3cb08faa94)) +* Implement BrailleLabel and BrailleRoleDescription roles ([#638](https://github.com/AccessKit/accesskit/issues/638)) ([0fdcebb](https://github.com/AccessKit/accesskit/commit/0fdcebb55e308e039ec99fbc31e94e8087a69f2d)) +* Rename HeaderAsNonLandmark to SectionHeader, FooterAsNonLandmark to SectionFooter ([#635](https://github.com/AccessKit/accesskit/issues/635)) ([dd69526](https://github.com/AccessKit/accesskit/commit/dd695260877cb862ece4c2b7d8607308f5fed608)) + + +### Bug Fixes + +* Expose dialogs in the platform adapters ([1576a94](https://github.com/AccessKit/accesskit/commit/1576a940ec3e9066fc5e181419dae6899bf2db46)) +* Upgrade hashbrown, indexmap ([#653](https://github.com/AccessKit/accesskit/issues/653)) ([fd73a85](https://github.com/AccessKit/accesskit/commit/fd73a85e57a6591a449b0a1880025fb940873c66)) + + +### Code Refactoring + +* Drop deprecated roles ([#642](https://github.com/AccessKit/accesskit/issues/642)) ([4d46c27](https://github.com/AccessKit/accesskit/commit/4d46c2740631c5fe4f057707b949d12b26931d0b)) +* Infrastructure for supporting text formatting changes ([#626](https://github.com/AccessKit/accesskit/issues/626)) ([ea23ec4](https://github.com/AccessKit/accesskit/commit/ea23ec424c7dbb8841e03d71b6a15b74264850a9)) + + +### Dependencies + +* The following workspace dependencies were updated + * dependencies + * accesskit bumped from 0.21.1 to 0.22.0 + * accesskit_consumer bumped from 0.31.0 to 0.32.0 + +## [0.22.2](https://github.com/AccessKit/accesskit/compare/accesskit_macos-v0.22.1...accesskit_macos-v0.22.2) (2025-10-20) + + +### Bug Fixes + +* Implement setting values on macOS ([#615](https://github.com/AccessKit/accesskit/issues/615)) ([9e07b15](https://github.com/AccessKit/accesskit/commit/9e07b158c34d6df3a0a08f1cc1ecdd1a0b7a943f)) + + +### Dependencies + +* The following workspace dependencies were updated + * dependencies + * accesskit_consumer bumped from 0.30.1 to 0.31.0 + +## [0.22.1](https://github.com/AccessKit/accesskit/compare/accesskit_macos-v0.22.0...accesskit_macos-v0.22.1) (2025-10-02) + + +### Dependencies + +* The following workspace dependencies were updated + * dependencies + * accesskit bumped from 0.21.0 to 0.21.1 + * accesskit_consumer bumped from 0.30.0 to 0.30.1 + +## [0.22.0](https://github.com/AccessKit/accesskit/compare/accesskit_macos-v0.21.0...accesskit_macos-v0.22.0) (2025-07-16) + + +### ⚠ BREAKING CHANGES + +* Implement refactored `ScrollIntoView` action across desktop platforms ([#594](https://github.com/AccessKit/accesskit/issues/594)) + +### Features + +* Implement refactored `ScrollIntoView` action across desktop platforms ([#594](https://github.com/AccessKit/accesskit/issues/594)) ([1d9b74c](https://github.com/AccessKit/accesskit/commit/1d9b74c057051509b3ffbf63afeacfb16f544ff8)) +* Let parents declare actions supported on their children ([#593](https://github.com/AccessKit/accesskit/issues/593)) ([70b534b](https://github.com/AccessKit/accesskit/commit/70b534bed168a84b84cc35199588aa8ab784fb43)) + + +### Bug Fixes + +* Panic if the subclassing adapter is double-instantiated ([#596](https://github.com/AccessKit/accesskit/issues/596)) ([0598573](https://github.com/AccessKit/accesskit/commit/05985732f0611a9ac96eb458e586c6dd3c1a131d)) + + +### Dependencies + +* The following workspace dependencies were updated + * dependencies + * accesskit bumped from 0.20.0 to 0.21.0 + * accesskit_consumer bumped from 0.29.0 to 0.30.0 + +## [0.21.0](https://github.com/AccessKit/accesskit/compare/accesskit_macos-v0.20.0...accesskit_macos-v0.21.0) (2025-06-26) + + +### ⚠ BREAKING CHANGES + +* Force a semver-breaking release ([#589](https://github.com/AccessKit/accesskit/issues/589)) + +### Bug Fixes + +* Destroy nodes that become filtered out on macOS ([#569](https://github.com/AccessKit/accesskit/issues/569)) ([29584d4](https://github.com/AccessKit/accesskit/commit/29584d46ff1b2faa23195f69913f0e193b2e883a)) +* Force a semver-breaking release ([#589](https://github.com/AccessKit/accesskit/issues/589)) ([2887cdd](https://github.com/AccessKit/accesskit/commit/2887cddde817ba3851688068d8d10de5cef7c624)) +* Resolve new clippy warning about using variables directly in format strings ([#590](https://github.com/AccessKit/accesskit/issues/590)) ([ccc62b7](https://github.com/AccessKit/accesskit/commit/ccc62b7f1dd32f0c372ba127a1e65c377048f670)) + + +### Dependencies + +* The following workspace dependencies were updated + * dependencies + * accesskit bumped from 0.19.0 to 0.20.0 + * accesskit_consumer bumped from 0.28.0 to 0.29.0 + +## [0.20.0](https://github.com/AccessKit/accesskit/compare/accesskit_macos-v0.19.0...accesskit_macos-v0.20.0) (2025-05-06) + + +### ⚠ BREAKING CHANGES + +* Drop redundant `HasPopup::True` ([#550](https://github.com/AccessKit/accesskit/issues/550)) + +### Features + +* Expose tabs in consumer and atspi-common ([b1fb5b3](https://github.com/AccessKit/accesskit/commit/b1fb5b3de12c001e34021263038b66a6e3a7dd1e)) + + +### Bug Fixes + +* Expose tabs in the platform adapters ([341a11b](https://github.com/AccessKit/accesskit/commit/341a11bca2c8a29682c11ddcfe91fa58776ea11d)) + + +### Code Refactoring + +* Drop redundant `HasPopup::True` ([#550](https://github.com/AccessKit/accesskit/issues/550)) ([56abf17](https://github.com/AccessKit/accesskit/commit/56abf17356e4c7f13f64aaeaca6a63c8f7ede553)) + + +### Dependencies + +* The following workspace dependencies were updated + * dependencies + * accesskit bumped from 0.18.0 to 0.19.0 + * accesskit_consumer bumped from 0.27.0 to 0.28.0 + +## [0.19.0](https://github.com/AccessKit/accesskit/compare/accesskit_macos-v0.18.1...accesskit_macos-v0.19.0) (2025-03-06) + + +### ⚠ BREAKING CHANGES + +* Optimize simple string getters ([#493](https://github.com/AccessKit/accesskit/issues/493)) +* Drop `Tree::app_name` ([#492](https://github.com/AccessKit/accesskit/issues/492)) + +### Features + +* Expose the `is_required` property ([#497](https://github.com/AccessKit/accesskit/issues/497)) ([46ed99b](https://github.com/AccessKit/accesskit/commit/46ed99bb958ddb32cbf1bee2fcfb7b328bcbe0ab)) + + +### Bug Fixes + +* Add list box support to the platform adapters ([6c622cf](https://github.com/AccessKit/accesskit/commit/6c622cff4c0c989d9a5f16b775adff9cdacf534c)) +* Derive `Debug` for adapters ([#513](https://github.com/AccessKit/accesskit/issues/513)) ([753d904](https://github.com/AccessKit/accesskit/commit/753d90473cf57682568c7a17c82474c8e5d00b25)) +* Remove unnecessary explicit lifetimes ([#488](https://github.com/AccessKit/accesskit/issues/488)) ([d2bcd6d](https://github.com/AccessKit/accesskit/commit/d2bcd6d3048d23df4e132bee6171eb247b2dc2c8)) + + +### Code Refactoring + +* Drop `Tree::app_name` ([#492](https://github.com/AccessKit/accesskit/issues/492)) ([089794c](https://github.com/AccessKit/accesskit/commit/089794c8f74957e91a19ae3df508e2a892f39ebc)) +* Optimize simple string getters ([#493](https://github.com/AccessKit/accesskit/issues/493)) ([484fd7c](https://github.com/AccessKit/accesskit/commit/484fd7cbfb778222369d3f57d31dd998f6fa80d8)) + + +### Dependencies + +* The following workspace dependencies were updated + * dependencies + * accesskit bumped from 0.17.1 to 0.18.0 + * accesskit_consumer bumped from 0.26.0 to 0.27.0 + +## [0.18.1](https://github.com/AccessKit/accesskit/compare/accesskit_macos-v0.18.0...accesskit_macos-v0.18.1) (2024-11-23) + + +### Bug Fixes + +* Add sub roles to MacOS adapter ([#480](https://github.com/AccessKit/accesskit/issues/480)) ([40ad828](https://github.com/AccessKit/accesskit/commit/40ad828a8f95c94f3079310d95c94ab7b16e0887)) +* Optimize use of hash tables in platform adapters ([#485](https://github.com/AccessKit/accesskit/issues/485)) ([f4f0bfb](https://github.com/AccessKit/accesskit/commit/f4f0bfbf21b8e22e80ab07deb432f9e7e16469ab)) + + +### Dependencies + +* The following workspace dependencies were updated + * dependencies + * accesskit bumped from 0.17.0 to 0.17.1 + * accesskit_consumer bumped from 0.25.0 to 0.26.0 + +## [0.18.0](https://github.com/AccessKit/accesskit/compare/accesskit_macos-v0.17.4...accesskit_macos-v0.18.0) (2024-10-31) + + +### ⚠ BREAKING CHANGES + +* Rename `name` to `label` and use `value` for label content ([#475](https://github.com/AccessKit/accesskit/issues/475)) +* Rename `NodeBuilder` to `Node` and the old `Node` to `FrozenNode` ([#476](https://github.com/AccessKit/accesskit/issues/476)) +* Rename `Role::InlineTextBox` to `TextRun` ([#473](https://github.com/AccessKit/accesskit/issues/473)) +* Drop `DefaultActionVerb` ([#472](https://github.com/AccessKit/accesskit/issues/472)) +* Make the core crate no-std ([#468](https://github.com/AccessKit/accesskit/issues/468)) + +### Features + +* Make the core crate no-std ([#468](https://github.com/AccessKit/accesskit/issues/468)) ([2fa0d3f](https://github.com/AccessKit/accesskit/commit/2fa0d3f5b2b7ac11ef1751c133706f29e548bd6d)) + + +### Bug Fixes + +* Implement the `isAccessibilityEnabled` property on MacOS ([#474](https://github.com/AccessKit/accesskit/issues/474)) ([61e4817](https://github.com/AccessKit/accesskit/commit/61e48174ed1dd57b7dd919ecaef908f157357ec0)) + + +### Code Refactoring + +* Drop `DefaultActionVerb` ([#472](https://github.com/AccessKit/accesskit/issues/472)) ([ef3b003](https://github.com/AccessKit/accesskit/commit/ef3b0038224459094f650368412650bc3b69526b)) +* Rename `name` to `label` and use `value` for label content ([#475](https://github.com/AccessKit/accesskit/issues/475)) ([e0053a5](https://github.com/AccessKit/accesskit/commit/e0053a5399929e8e0d4f07aa18de604ed8766ace)) +* Rename `NodeBuilder` to `Node` and the old `Node` to `FrozenNode` ([#476](https://github.com/AccessKit/accesskit/issues/476)) ([7d8910e](https://github.com/AccessKit/accesskit/commit/7d8910e35f7bc0543724cc124941a3bd0304bcc0)) +* Rename `Role::InlineTextBox` to `TextRun` ([#473](https://github.com/AccessKit/accesskit/issues/473)) ([29fa341](https://github.com/AccessKit/accesskit/commit/29fa34125a811bd3a0f9da579a9f35c9da90bf29)) + + +### Dependencies + +* The following workspace dependencies were updated + * dependencies + * accesskit bumped from 0.16.3 to 0.17.0 + * accesskit_consumer bumped from 0.24.3 to 0.25.0 + +## [0.17.4](https://github.com/AccessKit/accesskit/compare/accesskit_macos-v0.17.3...accesskit_macos-v0.17.4) (2024-10-21) + + +### Bug Fixes + +* Add properties needed by the Xcode Accessibility Inspector ([#466](https://github.com/AccessKit/accesskit/issues/466)) ([295b188](https://github.com/AccessKit/accesskit/commit/295b1881936dd097d82a10317ff14d1369f7e4bd)) + +## [0.17.2](https://github.com/AccessKit/accesskit/compare/accesskit_macos-v0.17.1...accesskit_macos-v0.17.2) (2024-10-07) + + +### Bug Fixes + +* Update minimum supported Rust version to 1.75 ([#457](https://github.com/AccessKit/accesskit/issues/457)) ([fc622fe](https://github.com/AccessKit/accesskit/commit/fc622fe7657c80a4eedad6f6cded11d2538b54d5)) + + +### Dependencies + +* The following workspace dependencies were updated + * dependencies + * accesskit bumped from 0.16.1 to 0.16.2 + * accesskit_consumer bumped from 0.24.1 to 0.24.2 + +## [0.17.0](https://github.com/AccessKit/accesskit/compare/accesskit_macos-v0.16.0...accesskit_macos-v0.17.0) (2024-06-29) + + +### ⚠ BREAKING CHANGES + +* Rename the `StaticText` role to `Label` ([#434](https://github.com/AccessKit/accesskit/issues/434)) + +### Code Refactoring + +* Rename the `StaticText` role to `Label` ([#434](https://github.com/AccessKit/accesskit/issues/434)) ([7086bc0](https://github.com/AccessKit/accesskit/commit/7086bc0fad446d3ed4a0fd5eff641a1e75f6c599)) + + +### Dependencies + +* The following workspace dependencies were updated + * dependencies + * accesskit bumped from 0.15.0 to 0.16.0 + * accesskit_consumer bumped from 0.23.0 to 0.24.0 + +## [0.16.0](https://github.com/AccessKit/accesskit/compare/accesskit_macos-v0.15.0...accesskit_macos-v0.16.0) (2024-06-09) + + +### Features + +* Add `author_id` property ([#424](https://github.com/AccessKit/accesskit/issues/424)) ([0d1c56f](https://github.com/AccessKit/accesskit/commit/0d1c56f0bdde58715e1c69f6015df600cb7cb8c1)) + + +### Dependencies + +* The following workspace dependencies were updated + * dependencies + * accesskit bumped from 0.14.0 to 0.15.0 + * accesskit_consumer bumped from 0.22.0 to 0.23.0 + +## [0.15.0](https://github.com/AccessKit/accesskit/compare/accesskit_macos-v0.14.0...accesskit_macos-v0.15.0) (2024-05-27) + + +### Features + +* Expose the `orientation` property ([#421](https://github.com/AccessKit/accesskit/issues/421)) ([590aada](https://github.com/AccessKit/accesskit/commit/590aada070dc812f9b8f171fb9e43ac984fad2a1)) + + +### Dependencies + +* The following workspace dependencies were updated + * dependencies + * accesskit_consumer bumped from 0.21.0 to 0.22.0 + +## [0.14.0](https://github.com/AccessKit/accesskit/compare/accesskit_macos-v0.13.2...accesskit_macos-v0.14.0) (2024-05-26) + + +### Features + +* Expose the `placeholder` property ([#417](https://github.com/AccessKit/accesskit/issues/417)) ([8f4a0a1](https://github.com/AccessKit/accesskit/commit/8f4a0a1c10f83fcc8580a37d8013fec2d110865b)) + + +### Dependencies + +* The following workspace dependencies were updated + * dependencies + * accesskit_consumer bumped from 0.20.0 to 0.21.0 + +## [0.13.2](https://github.com/AccessKit/accesskit/compare/accesskit_macos-v0.13.1...accesskit_macos-v0.13.2) (2024-05-13) + + +### Bug Fixes + +* Fix platform adapters to support copy-on-write tree snapshots again ([#411](https://github.com/AccessKit/accesskit/issues/411)) ([d3a130a](https://github.com/AccessKit/accesskit/commit/d3a130a5ec8ae1d9edf0bf85a44f35f0e365242c)) + + +### Dependencies + +* The following workspace dependencies were updated + * dependencies + * accesskit_consumer bumped from 0.19.1 to 0.20.0 + +## [0.13.0](https://github.com/AccessKit/accesskit/compare/accesskit_macos-v0.12.0...accesskit_macos-v0.13.0) (2024-04-30) + + +### ⚠ BREAKING CHANGES + +* Clean up table roles and properties ([#393](https://github.com/AccessKit/accesskit/issues/393)) +* Drop `NodeClassSet` ([#389](https://github.com/AccessKit/accesskit/issues/389)) +* Rename `Checked` to `Toggled`; drop `ToggleButton` role ([#388](https://github.com/AccessKit/accesskit/issues/388)) + +### Features + +* Implement the `description` property ([#382](https://github.com/AccessKit/accesskit/issues/382)) ([d49f406](https://github.com/AccessKit/accesskit/commit/d49f40660b5dc23ed074cd72a91e511b130756ae)) + + +### Bug Fixes + +* Increase minimum supported Rust version to `1.70` ([#396](https://github.com/AccessKit/accesskit/issues/396)) ([a8398b8](https://github.com/AccessKit/accesskit/commit/a8398b847aa003de91042ac45e33126fc2cae053)) +* Use new objc2 crates ([#384](https://github.com/AccessKit/accesskit/issues/384)) ([b3484c0](https://github.com/AccessKit/accesskit/commit/b3484c0fb1fef3ecd41ff9592978336c20b8b4f8)) + + +### Code Refactoring + +* Clean up table roles and properties ([#393](https://github.com/AccessKit/accesskit/issues/393)) ([e34dad9](https://github.com/AccessKit/accesskit/commit/e34dad94448a5321ece9def3f2e054aa5f62dd79)) +* Drop `NodeClassSet` ([#389](https://github.com/AccessKit/accesskit/issues/389)) ([1b153ed](https://github.com/AccessKit/accesskit/commit/1b153ed51f8421cdba2dc98beca2e8f5f8c781bc)) +* Rename `Checked` to `Toggled`; drop `ToggleButton` role ([#388](https://github.com/AccessKit/accesskit/issues/388)) ([6bc040b](https://github.com/AccessKit/accesskit/commit/6bc040b7cf75cdbd6a019cc380d8dbce804b3c81)) + + +### Dependencies + +* The following workspace dependencies were updated + * dependencies + * accesskit bumped from 0.13.0 to 0.14.0 + * accesskit_consumer bumped from 0.18.0 to 0.19.0 + +## [0.12.0](https://github.com/AccessKit/accesskit/compare/accesskit_macos-v0.11.1...accesskit_macos-v0.12.0) (2024-04-14) + + +### ⚠ BREAKING CHANGES + +* New approach to lazy initialization ([#375](https://github.com/AccessKit/accesskit/issues/375)) + +### Bug Fixes + +* Fix new compiler warning in Rust 1.77 ([#376](https://github.com/AccessKit/accesskit/issues/376)) ([1de7c63](https://github.com/AccessKit/accesskit/commit/1de7c63e7db12bc7eda57a191e913fef0e572f43)) + + +### Code Refactoring + +* New approach to lazy initialization ([#375](https://github.com/AccessKit/accesskit/issues/375)) ([9baebdc](https://github.com/AccessKit/accesskit/commit/9baebdceed7300389b6768815d7ae48f1ce401e4)) + + +### Dependencies + +* The following workspace dependencies were updated + * dependencies + * accesskit bumped from 0.12.3 to 0.13.0 + * accesskit_consumer bumped from 0.17.1 to 0.18.0 + +## [0.11.0](https://github.com/AccessKit/accesskit/compare/accesskit_macos-v0.10.1...accesskit_macos-v0.11.0) (2024-01-03) + + +### Features + +* Support custom role descriptions ([#316](https://github.com/AccessKit/accesskit/issues/316)) ([c8d1a56](https://github.com/AccessKit/accesskit/commit/c8d1a5638fa6c33adfa059815c04f7e043c56026)) + + +### Bug Fixes + +* Bump objc2 to 0.5.0; bring icrate 0.1.0 ([#323](https://github.com/AccessKit/accesskit/issues/323)) ([23b3f2f](https://github.com/AccessKit/accesskit/commit/23b3f2f93b9452c80374d1da3e9abeaec60ba9bf)) + + +### Dependencies + +* The following workspace dependencies were updated + * dependencies + * accesskit bumped from 0.12.1 to 0.12.2 + * accesskit_consumer bumped from 0.16.1 to 0.17.0 + +## [0.10.0](https://github.com/AccessKit/accesskit/compare/accesskit_macos-v0.9.0...accesskit_macos-v0.10.0) (2023-09-27) + + +### ⚠ BREAKING CHANGES + +* Make `ActionHandler::do_action` take `&mut self` ([#296](https://github.com/AccessKit/accesskit/issues/296)) +* Clean up roles and properties ([#289](https://github.com/AccessKit/accesskit/issues/289)) +* Decouple in-tree focus from host window/view focus ([#278](https://github.com/AccessKit/accesskit/issues/278)) +* Switch to simple unsigned 64-bit integer for node IDs ([#276](https://github.com/AccessKit/accesskit/issues/276)) + +### Features + +* Add role for terminals ([#282](https://github.com/AccessKit/accesskit/issues/282)) ([ddbef37](https://github.com/AccessKit/accesskit/commit/ddbef37158b57f56217317b480e40d58f83a9c24)) + + +### Bug Fixes + +* Support text fields without a value property ([#274](https://github.com/AccessKit/accesskit/issues/274)) ([5ae557b](https://github.com/AccessKit/accesskit/commit/5ae557b40d395b4a9966a90a2d80e7d97ad50bf9)) +* Use common filters across platform adapters ([#287](https://github.com/AccessKit/accesskit/issues/287)) ([09c1204](https://github.com/AccessKit/accesskit/commit/09c12045ff4ccdb22f0cf643077a27465013572d)) + + +### Code Refactoring + +* Clean up roles and properties ([#289](https://github.com/AccessKit/accesskit/issues/289)) ([4fc9c55](https://github.com/AccessKit/accesskit/commit/4fc9c55c91812472593923d93ff89d75ff305ee4)) +* Decouple in-tree focus from host window/view focus ([#278](https://github.com/AccessKit/accesskit/issues/278)) ([d360d20](https://github.com/AccessKit/accesskit/commit/d360d20cf951e7643b81a5303006c9f7daa5bd56)) +* Make `ActionHandler::do_action` take `&mut self` ([#296](https://github.com/AccessKit/accesskit/issues/296)) ([4fc7846](https://github.com/AccessKit/accesskit/commit/4fc7846d732d61fb45c023060ebab96801a0053e)) +* Switch to simple unsigned 64-bit integer for node IDs ([#276](https://github.com/AccessKit/accesskit/issues/276)) ([3eadd48](https://github.com/AccessKit/accesskit/commit/3eadd48ec47854faa94a94ebf910ec08f514642f)) + + +### Dependencies + +* The following workspace dependencies were updated + * dependencies + * accesskit bumped from 0.11.2 to 0.12.0 + * accesskit_consumer bumped from 0.15.2 to 0.16.0 + +## [0.9.0](https://github.com/AccessKit/accesskit/compare/accesskit_macos-v0.8.0...accesskit_macos-v0.9.0) (2023-08-08) + + +### Features + +* Workaround for libraries that put the macOS keyboard focus on the window rather than the content view ([#266](https://github.com/AccessKit/accesskit/issues/266)) ([c2db1b0](https://github.com/AccessKit/accesskit/commit/c2db1b0424e905d87691f8148f28b77405f29926)) + + +### Dependencies + +* The following workspace dependencies were updated + * dependencies + * accesskit bumped from 0.11.1 to 0.11.2 + * accesskit_consumer bumped from 0.15.1 to 0.15.2 + +## [0.8.0](https://github.com/AccessKit/accesskit/compare/accesskit_macos-v0.7.1...accesskit_macos-v0.8.0) (2023-07-30) + + +### Features + +* Add window-based constructor to macOS subclassing adapter ([#253](https://github.com/AccessKit/accesskit/issues/253)) ([022ef04](https://github.com/AccessKit/accesskit/commit/022ef045b9f28262b738ee1ca29a4c7303061fb3)) + + +### Dependencies + +* The following workspace dependencies were updated + * dependencies + * accesskit bumped from 0.11.0 to 0.11.1 + * accesskit_consumer bumped from 0.15.0 to 0.15.1 + +## [0.7.1](https://github.com/AccessKit/accesskit/compare/accesskit_macos-v0.7.0...accesskit_macos-v0.7.1) (2023-06-20) + + +### Bug Fixes + +* Set proper target to build accesskit_macos documentation ([#226](https://github.com/AccessKit/accesskit/issues/226)) ([9cd6bb1](https://github.com/AccessKit/accesskit/commit/9cd6bb14d60bf85027b330a51afe912c37723902)) + +## [0.7.0](https://github.com/AccessKit/accesskit/compare/accesskit_macos-v0.6.3...accesskit_macos-v0.7.0) (2023-03-30) + + +### ⚠ BREAKING CHANGES + +* Force a semver-breaking version bump in downstream crates ([#234](https://github.com/AccessKit/accesskit/issues/234)) + +### Bug Fixes + +* Force a semver-breaking version bump in downstream crates ([#234](https://github.com/AccessKit/accesskit/issues/234)) ([773389b](https://github.com/AccessKit/accesskit/commit/773389bff857fa18edf15de426e029251fc34591)) + + +### Dependencies + +* The following workspace dependencies were updated + * dependencies + * accesskit_consumer bumped from 0.14.2 to 0.15.0 + +## [0.6.3](https://github.com/AccessKit/accesskit/compare/accesskit_macos-v0.6.2...accesskit_macos-v0.6.3) (2023-03-29) + + +### Bug Fixes + +* Fix problems related to the root node ([#231](https://github.com/AccessKit/accesskit/issues/231)) ([7228494](https://github.com/AccessKit/accesskit/commit/7228494361c4f131af6a7fc2af8a98406cd9a63e)) + + +### Dependencies + +* The following workspace dependencies were updated + * dependencies + * accesskit bumped from 0.10.1 to 0.11.0 + * accesskit_consumer bumped from 0.14.1 to 0.14.2 + +## [0.6.2](https://github.com/AccessKit/accesskit/compare/accesskit_macos-v0.6.1...accesskit_macos-v0.6.2) (2023-03-14) + + +### Bug Fixes + +* Fix macOS leaks ([e8537fc](https://github.com/AccessKit/accesskit/commit/e8537fcbdf4a68f39c9bc51cf9fe6960903e26f2)) + +## [0.6.0](https://github.com/AccessKit/accesskit/compare/accesskit_macos-v0.5.0...accesskit_macos-v0.6.0) (2023-02-12) + + +### ⚠ BREAKING CHANGES + +* Move thread synchronization into platform adapters; drop parking_lot ([#212](https://github.com/AccessKit/accesskit/issues/212)) + +### Code Refactoring + +* Move thread synchronization into platform adapters; drop parking_lot ([#212](https://github.com/AccessKit/accesskit/issues/212)) ([5df52e5](https://github.com/AccessKit/accesskit/commit/5df52e5545faddf6a51905409013c2f5be23981e)) + + +### Dependencies + +* The following workspace dependencies were updated + * dependencies + * accesskit bumped from 0.9.0 to 0.10.0 + * accesskit_consumer bumped from 0.13.0 to 0.14.0 + +## [0.5.0](https://github.com/AccessKit/accesskit/compare/accesskit_macos-v0.4.2...accesskit_macos-v0.5.0) (2023-02-05) + + +### ⚠ BREAKING CHANGES + +* Make `Node` opaque and optimize it for size ([#205](https://github.com/AccessKit/accesskit/issues/205)) + +### Code Refactoring + +* Make `Node` opaque and optimize it for size ([#205](https://github.com/AccessKit/accesskit/issues/205)) ([4811152](https://github.com/AccessKit/accesskit/commit/48111521439b76c1a8687418a4b20f9b705eac6d)) + + +### Dependencies + +* The following workspace dependencies were updated + * dependencies + * accesskit bumped from 0.8.1 to 0.9.0 + * accesskit_consumer bumped from 0.12.1 to 0.13.0 + +## [0.4.0](https://github.com/AccessKit/accesskit/compare/accesskit_macos-v0.3.0...accesskit_macos-v0.4.0) (2022-12-27) + + +### Features + +* Live regions on macOS ([#196](https://github.com/AccessKit/accesskit/issues/196)) ([47d8d9f](https://github.com/AccessKit/accesskit/commit/47d8d9f6a567dfe909aa4065886cace07084efb7)) + + +### Bug Fixes + +* Pin objc2 dependency to 0.3.0-beta.3 ([#201](https://github.com/AccessKit/accesskit/issues/201)) ([0adfed1](https://github.com/AccessKit/accesskit/commit/0adfed1192ee255fba34ad82e8483ab9296ac2df)) + +## [0.3.0](https://github.com/AccessKit/accesskit/compare/accesskit_macos-v0.2.1...accesskit_macos-v0.3.0) (2022-12-17) + + +### Features + +* Text support on macOS ([#191](https://github.com/AccessKit/accesskit/issues/191)) ([3a35dbe](https://github.com/AccessKit/accesskit/commit/3a35dbe02122c789fe682995c5b7e022aef5cc36)) + + +### Bug Fixes + +* Don't expose the window title in our root element on macOS ([#187](https://github.com/AccessKit/accesskit/issues/187)) ([9739b74](https://github.com/AccessKit/accesskit/commit/9739b7424328da45c1c43b6db49af142a8789aa5)) +* Expose which accessibility selectors are actually allowed for a particular node ([#181](https://github.com/AccessKit/accesskit/issues/181)) ([c4cbb23](https://github.com/AccessKit/accesskit/commit/c4cbb23156749d513df4e520dcb9be0a74c697d3)) +* More reliable handling of the edge case for wrapped lines ([#192](https://github.com/AccessKit/accesskit/issues/192)) ([c626d2c](https://github.com/AccessKit/accesskit/commit/c626d2c3028085b076ada7dd31242cf3ca3c0f08)) + + +### Dependencies + +* The following workspace dependencies were updated + * dependencies + * accesskit_consumer bumped from 0.10.0 to 0.11.0 + +## [0.2.1](https://github.com/AccessKit/accesskit/compare/accesskit_macos-v0.2.0...accesskit_macos-v0.2.1) (2022-12-04) + + +### Bug Fixes + +* Correctly apply the DPI scale factor to coordinates ([#185](https://github.com/AccessKit/accesskit/issues/185)) ([d263938](https://github.com/AccessKit/accesskit/commit/d263938d68bb63567853a340d3466ff27e076d87)) +* Expose static text as the value rather than the title on macOS ([#186](https://github.com/AccessKit/accesskit/issues/186)) ([e3720c8](https://github.com/AccessKit/accesskit/commit/e3720c8e2d7c5e8c8601c52ad620dcfcacebc570)) + + +### Dependencies + +* The following workspace dependencies were updated + * dependencies + * accesskit bumped from 0.8.0 to 0.8.1 + * accesskit_consumer bumped from 0.9.1 to 0.10.0 + +## [0.2.0](https://github.com/AccessKit/accesskit/compare/accesskit_macos-v0.1.5...accesskit_macos-v0.2.0) (2022-11-29) + + +### ⚠ BREAKING CHANGES + +* Move lazy initialization from the core platform adapter to the caller ([#179](https://github.com/AccessKit/accesskit/issues/179)) + +### Code Refactoring + +* Move lazy initialization from the core platform adapter to the caller ([#179](https://github.com/AccessKit/accesskit/issues/179)) ([f35c941](https://github.com/AccessKit/accesskit/commit/f35c941f395f3162db376a69cfaaaf770d376267)) + +## [0.1.5](https://github.com/AccessKit/accesskit/compare/accesskit_macos-v0.1.4...accesskit_macos-v0.1.5) (2022-11-27) + + +### Bug Fixes + +* Handle views with flipped coordinates ([#174](https://github.com/AccessKit/accesskit/issues/174)) ([d14484c](https://github.com/AccessKit/accesskit/commit/d14484cdcfdd99a497354aa3e012a0e130cc3d64)) +* Make VoiceOver move through nodes in logical order ([#176](https://github.com/AccessKit/accesskit/issues/176)) ([f060be4](https://github.com/AccessKit/accesskit/commit/f060be409945296ed100cd63ecb3d2bb6bbad89e)) + +### [0.1.4](https://www.github.com/AccessKit/accesskit/compare/accesskit_macos-v0.1.3...accesskit_macos-v0.1.4) (2022-11-25) + + +### Bug Fixes + +* Re-export types from objc2 ([#172](https://www.github.com/AccessKit/accesskit/issues/172)) ([1ac67ad](https://www.github.com/AccessKit/accesskit/commit/1ac67ad17587d79b5338cb71e2bc07612fc10c44)) + +### [0.1.3](https://www.github.com/AccessKit/accesskit/compare/accesskit_macos-v0.1.2...accesskit_macos-v0.1.3) (2022-11-25) + + +### Dependencies + +* The following workspace dependencies were updated + * dependencies + * accesskit_consumer bumped from 0.9.0 to 0.9.1 + +### [0.1.2](https://www.github.com/AccessKit/accesskit/compare/accesskit_macos-v0.1.1...accesskit_macos-v0.1.2) (2022-11-24) + + +### Bug Fixes + +* **platforms/macos:** Add the macOS crate to the release-please configuration ([#164](https://www.github.com/AccessKit/accesskit/issues/164)) ([da83f63](https://www.github.com/AccessKit/accesskit/commit/da83f63d279a10c5a7199a9145ca9eb9e27d7b56)) diff --git a/app/vendor/rune/vendor/accesskit_macos/Cargo.lock b/app/vendor/rune/vendor/accesskit_macos/Cargo.lock new file mode 100644 index 0000000..0b17c11 --- /dev/null +++ b/app/vendor/rune/vendor/accesskit_macos/Cargo.lock @@ -0,0 +1,394 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "accesskit" +version = "0.25.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e883d1d28c5fd5568c79ed2d2bd48d9f2fd3945c8974ed0f53690ceddb051be" +dependencies = [ + "uuid", +] + +[[package]] +name = "accesskit_consumer" +version = "0.39.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f3da8f27636015191b2264ee1df681503170a632cafd832fdc1edfdd4e3a2fd3" +dependencies = [ + "accesskit", + "hashbrown", +] + +[[package]] +name = "accesskit_macos" +version = "0.27.2" +dependencies = [ + "accesskit", + "accesskit_consumer", + "hashbrown", + "libtest-mimic", + "objc2", + "objc2-app-kit", + "objc2-foundation", +] + +[[package]] +name = "anstream" +version = "0.6.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "43d5b281e737544384e969a5ccad3f1cdd24b48086a0fc1b2a5262a26b8f4f4a" +dependencies = [ + "anstyle", + "anstyle-parse 0.2.7", + "anstyle-query", + "anstyle-wincon", + "colorchoice", + "is_terminal_polyfill", + "utf8parse", +] + +[[package]] +name = "anstream" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "824a212faf96e9acacdbd09febd34438f8f711fb84e09a8916013cd7815ca28d" +dependencies = [ + "anstyle", + "anstyle-parse 1.0.0", + "anstyle-query", + "anstyle-wincon", + "colorchoice", + "is_terminal_polyfill", + "utf8parse", +] + +[[package]] +name = "anstyle" +version = "1.0.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000" + +[[package]] +name = "anstyle-parse" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7644824f0aa2c7b9384579234ef10eb7efb6a0deb83f9630a49594dd9c15c2" +dependencies = [ + "utf8parse", +] + +[[package]] +name = "anstyle-parse" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52ce7f38b242319f7cabaa6813055467063ecdc9d355bbb4ce0c68908cd8130e" +dependencies = [ + "utf8parse", +] + +[[package]] +name = "anstyle-query" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc" +dependencies = [ + "windows-sys", +] + +[[package]] +name = "anstyle-wincon" +version = "3.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d" +dependencies = [ + "anstyle", + "once_cell_polyfill", + "windows-sys", +] + +[[package]] +name = "bitflags" +version = "2.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f68f53c83ab957f72c32642f3868eec03eb974d1fb82e453128456482613d36" + +[[package]] +name = "block2" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2c132eebf10f5cad5289222520a4a058514204aed6d791f1cf4fe8088b82d15f" +dependencies = [ + "objc2", +] + +[[package]] +name = "clap" +version = "4.5.60" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2797f34da339ce31042b27d23607e051786132987f595b02ba4f6a6dffb7030a" +dependencies = [ + "clap_builder", + "clap_derive", +] + +[[package]] +name = "clap_builder" +version = "4.5.60" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24a241312cea5059b13574bb9b3861cabf758b879c15190b37b6d6fd63ab6876" +dependencies = [ + "anstream 0.6.21", + "anstyle", + "clap_lex", + "strsim", +] + +[[package]] +name = "clap_derive" +version = "4.5.55" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a92793da1a46a5f2a02a6f4c46c6496b28c43638adea8306fcb0caa1634f24e5" +dependencies = [ + "heck", + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "clap_lex" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c133bc6a41be0d194c306b5506d15e6feeea7b1d6604bd3f8310dfb2ca96486" + +[[package]] +name = "colorchoice" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570" + +[[package]] +name = "escape8259" +version = "0.5.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f1f0d310082fd5de539d4f41601182241147498444a7695c520288a0cdbead6" + +[[package]] +name = "foldhash" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" + +[[package]] +name = "hashbrown" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" +dependencies = [ + "foldhash", +] + +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + +[[package]] +name = "is_terminal_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695" + +[[package]] +name = "libc" +version = "0.2.189" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2" + +[[package]] +name = "libtest-mimic" +version = "0.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "14e6ba06f0ade6e504aff834d7c34298e5155c6baca353cc6a4aaff2f9fd7f33" +dependencies = [ + "anstream 1.0.0", + "anstyle", + "clap", + "escape8259", +] + +[[package]] +name = "objc-sys" +version = "0.3.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cdb91bdd390c7ce1a8607f35f3ca7151b65afc0ff5ff3b34fa350f7d7c7e4310" + +[[package]] +name = "objc2" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "46a785d4eeff09c14c487497c162e92766fbb3e4059a71840cecc03d9a50b804" +dependencies = [ + "objc-sys", + "objc2-encode", +] + +[[package]] +name = "objc2-app-kit" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e4e89ad9e3d7d297152b17d39ed92cd50ca8063a89a9fa569046d41568891eff" +dependencies = [ + "bitflags", + "block2", + "libc", + "objc2", + "objc2-core-data", + "objc2-core-image", + "objc2-foundation", + "objc2-quartz-core", +] + +[[package]] +name = "objc2-core-data" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "617fbf49e071c178c0b24c080767db52958f716d9eabdf0890523aeae54773ef" +dependencies = [ + "bitflags", + "block2", + "objc2", + "objc2-foundation", +] + +[[package]] +name = "objc2-core-image" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "55260963a527c99f1819c4f8e3b47fe04f9650694ef348ffd2227e8196d34c80" +dependencies = [ + "block2", + "objc2", + "objc2-foundation", + "objc2-metal", +] + +[[package]] +name = "objc2-encode" +version = "4.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ef25abbcd74fb2609453eb695bd2f860d389e457f67dc17cafc8b8cbc89d0c33" + +[[package]] +name = "objc2-foundation" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ee638a5da3799329310ad4cfa62fbf045d5f56e3ef5ba4149e7452dcf89d5a8" +dependencies = [ + "bitflags", + "block2", + "libc", + "objc2", +] + +[[package]] +name = "objc2-metal" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dd0cba1276f6023976a406a14ffa85e1fdd19df6b0f737b063b95f6c8c7aadd6" +dependencies = [ + "bitflags", + "block2", + "objc2", + "objc2-foundation", +] + +[[package]] +name = "objc2-quartz-core" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e42bee7bff906b14b167da2bac5efe6b6a07e6f7c0a21a7308d40c960242dc7a" +dependencies = [ + "bitflags", + "block2", + "objc2", + "objc2-foundation", + "objc2-metal", +] + +[[package]] +name = "once_cell_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" + +[[package]] +name = "proc-macro2" +version = "1.0.106" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.37" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b5b9d34b8991d19d98081b46eacdd8eb58c6f2b201139f7c5f643cc155a633af" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "strsim" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" + +[[package]] +name = "syn" +version = "2.0.87" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "25aa4ce346d03a6dcd68dd8b4010bcb74e54e62c90c573f394c46eae99aba32d" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "unicode-ident" +version = "1.0.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5464a87b239f13a63a501f2701565754bae92d243d4bb7eb12f6d57d2269bf4" + +[[package]] +name = "utf8parse" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" + +[[package]] +name = "uuid" +version = "1.18.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f87b8aa10b915a06587d0dec516c282ff295b475d94abf425d62b57710070a2" + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] diff --git a/app/vendor/rune/vendor/accesskit_macos/Cargo.toml b/app/vendor/rune/vendor/accesskit_macos/Cargo.toml new file mode 100644 index 0000000..2704a74 --- /dev/null +++ b/app/vendor/rune/vendor/accesskit_macos/Cargo.toml @@ -0,0 +1,77 @@ +# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO +# +# When uploading crates to the registry Cargo will automatically +# "normalize" Cargo.toml files for maximal compatibility +# with all versions of Cargo and also rewrite `path` dependencies +# to registry (e.g., crates.io) dependencies. +# +# If you are reading this file be aware that the original Cargo.toml +# will likely look very different (and much more reasonable). +# See Cargo.toml.orig for the original contents. + +[package] +edition = "2024" +rust-version = "1.87" +name = "accesskit_macos" +version = "0.27.2" +authors = ["The AccessKit contributors"] +build = false +autolib = false +autobins = false +autoexamples = false +autotests = false +autobenches = false +description = "AccessKit UI accessibility infrastructure: macOS adapter" +readme = "README.md" +keywords = [ + "gui", + "ui", + "accessibility", +] +categories = ["gui"] +license = "MIT OR Apache-2.0" +repository = "https://github.com/AccessKit/accesskit" + +[package.metadata.docs.rs] +default-target = "x86_64-apple-darwin" + +[lib] +name = "accesskit_macos" +path = "src/lib.rs" + +[dependencies.accesskit] +version = "0.25.2" + +[dependencies.accesskit_consumer] +version = "0.39.2" + +[dependencies.hashbrown] +version = "0.17" +features = ["default-hasher"] +default-features = false + +[dependencies.objc2] +version = "0.5.1" + +[dependencies.objc2-app-kit] +version = "0.2.0" +features = [ + "NSAccessibility", + "NSAccessibilityConstants", + "NSAccessibilityElement", + "NSAccessibilityProtocols", + "NSColor", + "NSResponder", + "NSText", + "NSView", + "NSWindow", +] + +[dependencies.objc2-foundation] +version = "0.2.0" +features = [ + "NSArray", + "NSDictionary", + "NSValue", + "NSThread", +] diff --git a/app/vendor/rune/vendor/accesskit_macos/Cargo.toml.orig b/app/vendor/rune/vendor/accesskit_macos/Cargo.toml.orig new file mode 100644 index 0000000..4153793 --- /dev/null +++ b/app/vendor/rune/vendor/accesskit_macos/Cargo.toml.orig @@ -0,0 +1,46 @@ +[package] +name = "accesskit_macos" +version = "0.27.2" +authors.workspace = true +license.workspace = true +description = "AccessKit UI accessibility infrastructure: macOS adapter" +categories.workspace = true +keywords = ["gui", "ui", "accessibility"] +repository.workspace = true +readme = "README.md" +edition.workspace = true +rust-version.workspace = true + +[package.metadata.docs.rs] +default-target = "x86_64-apple-darwin" + +[dependencies] +accesskit = { version = "0.25.2", path = "../../accesskit" } +accesskit_consumer = { version = "0.39.2", path = "../../accesskit_consumer" } +hashbrown.workspace = true +objc2 = "0.5.1" +objc2-foundation = { version = "0.2.0", features = [ + "NSArray", + "NSDictionary", + "NSValue", + "NSThread", +] } +objc2-app-kit = { version = "0.2.0", features = [ + "NSAccessibility", + "NSAccessibilityConstants", + "NSAccessibilityElement", + "NSAccessibilityProtocols", + "NSColor", + "NSResponder", + "NSText", + "NSView", + "NSWindow", +] } + +[dev-dependencies] +libtest-mimic = "0.8.2" + +# AppKit must be used from the main thread, where libtest doesn't run tests. +[[test]] +name = "integration" +harness = false diff --git a/app/vendor/rune/vendor/accesskit_macos/README.md b/app/vendor/rune/vendor/accesskit_macos/README.md new file mode 100644 index 0000000..4a7bbef --- /dev/null +++ b/app/vendor/rune/vendor/accesskit_macos/README.md @@ -0,0 +1,7 @@ +# AccessKit macOS adapter + +This is the macOS adapter for [AccessKit](https://accesskit.dev/). It exposes an AccessKit accessibility tree through the Cocoa `NSAccessibility` protocol. + +## Known issues + +- The selected state of ListBox items is not reported ([#520](https://github.com/AccessKit/accesskit/issues/520)) diff --git a/app/vendor/rune/vendor/accesskit_macos/src/adapter.rs b/app/vendor/rune/vendor/accesskit_macos/src/adapter.rs new file mode 100644 index 0000000..86b4b00 --- /dev/null +++ b/app/vendor/rune/vendor/accesskit_macos/src/adapter.rs @@ -0,0 +1,295 @@ +// Copyright 2022 The AccessKit Authors. All rights reserved. +// Licensed under the Apache License, Version 2.0 (found in +// the LICENSE-APACHE file) or the MIT license (found in +// the LICENSE-MIT file), at your option. + +use crate::{ + context::{ActionHandlerNoMut, ActionHandlerWrapper, Context}, + event::{EventGenerator, QueuedEvents, focus_event}, + filters::filter, + node::can_be_focused, + util::*, +}; +use accesskit::{ + ActionHandler, ActionRequest, ActivationHandler, Node, NodeId, Role, TreeId, TreeInfo, + TreeUpdate, +}; +use accesskit_consumer::{FilterResult, Tree}; +use objc2::rc::{Id, WeakId}; +use objc2_app_kit::NSView; +use objc2_foundation::{MainThreadMarker, NSArray, NSObject, NSPoint}; +use std::fmt::{Debug, Formatter}; +use std::{ffi::c_void, ptr::null_mut, rc::Rc}; + +const PLACEHOLDER_ROOT_ID: NodeId = NodeId(0); + +enum State { + Inactive { + view: WeakId<NSView>, + is_view_focused: bool, + action_handler: Rc<dyn ActionHandlerNoMut>, + mtm: MainThreadMarker, + }, + Placeholder { + placeholder_context: Rc<Context>, + is_view_focused: bool, + action_handler: Rc<dyn ActionHandlerNoMut>, + }, + Active(Rc<Context>), +} + +impl Debug for State { + fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { + match self { + State::Inactive { + view, + is_view_focused, + action_handler: _, + mtm, + } => f + .debug_struct("Inactive") + .field("view", view) + .field("is_view_focused", is_view_focused) + .field("mtm", mtm) + .finish(), + State::Placeholder { + placeholder_context, + is_view_focused, + action_handler: _, + } => f + .debug_struct("Placeholder") + .field("placeholder_context", placeholder_context) + .field("is_view_focused", is_view_focused) + .finish(), + State::Active(context) => f.debug_struct("Active").field("context", context).finish(), + } + } +} + +struct PlaceholderActionHandler; + +impl ActionHandler for PlaceholderActionHandler { + fn do_action(&mut self, _request: ActionRequest) {} +} + +#[derive(Debug)] +pub struct Adapter { + state: State, +} + +impl Adapter { + /// Create a new macOS adapter. This function must be called on + /// the main thread. + /// + /// The action handler will always be called on the main thread. + /// + /// # Safety + /// + /// `view` must be a valid, unreleased pointer to an `NSView`. + pub unsafe fn new( + view: *mut c_void, + is_view_focused: bool, + action_handler: impl 'static + ActionHandler, + ) -> Self { + let view = unsafe { Id::retain(view as *mut NSView) }.unwrap(); + let view = WeakId::from_id(&view); + let mtm = MainThreadMarker::new().unwrap(); + let state = State::Inactive { + view, + is_view_focused, + action_handler: Rc::new(ActionHandlerWrapper::new(action_handler)), + mtm, + }; + Self { state } + } + + /// If and only if the tree has been initialized, call the provided function + /// and apply the resulting update. Note: If the caller's implementation of + /// [`ActivationHandler::request_initial_tree`] initially returned `None`, + /// the [`TreeUpdate`] returned by the provided function must contain + /// a full tree. + /// + /// If a [`QueuedEvents`] instance is returned, the caller must call + /// [`QueuedEvents::raise`] on it. + pub fn update_if_active( + &mut self, + update_factory: impl FnOnce() -> TreeUpdate, + ) -> Option<QueuedEvents> { + match &self.state { + State::Inactive { .. } => None, + State::Placeholder { + placeholder_context, + is_view_focused, + action_handler, + } => { + let tree = Tree::new(update_factory(), *is_view_focused); + let context = Context::new( + placeholder_context.view.clone(), + tree, + Rc::clone(action_handler), + placeholder_context.mtm, + ); + let result = context.tree.borrow().state().focus().map(|node| { + QueuedEvents::new(Rc::clone(&context), vec![focus_event(node.id())]) + }); + self.state = State::Active(context); + result + } + State::Active(context) => { + let mut event_generator = EventGenerator::new(context.clone()); + let mut tree = context.tree.borrow_mut(); + tree.update_and_process_changes(update_factory(), &mut event_generator); + Some(event_generator.into_result()) + } + } + } + + /// Update the tree state based on whether the window is focused. + /// + /// If a [`QueuedEvents`] instance is returned, the caller must call + /// [`QueuedEvents::raise`] on it. + pub fn update_view_focus_state(&mut self, is_focused: bool) -> Option<QueuedEvents> { + match &mut self.state { + State::Inactive { + is_view_focused, .. + } => { + *is_view_focused = is_focused; + None + } + State::Placeholder { + is_view_focused, .. + } => { + *is_view_focused = is_focused; + None + } + State::Active(context) => { + let mut event_generator = EventGenerator::new(context.clone()); + let mut tree = context.tree.borrow_mut(); + tree.update_host_focus_state_and_process_changes(is_focused, &mut event_generator); + Some(event_generator.into_result()) + } + } + } + + fn get_or_init_context<H: ActivationHandler + ?Sized>( + &mut self, + activation_handler: &mut H, + ) -> Rc<Context> { + match &self.state { + State::Inactive { + view, + is_view_focused, + action_handler, + mtm, + } => match activation_handler.request_initial_tree() { + Some(initial_state) => { + let tree = Tree::new(initial_state, *is_view_focused); + let context = Context::new(view.clone(), tree, Rc::clone(action_handler), *mtm); + let result = Rc::clone(&context); + self.state = State::Active(context); + result + } + None => { + let placeholder_update = TreeUpdate { + nodes: vec![(PLACEHOLDER_ROOT_ID, Node::new(Role::Window))], + tree: Some(TreeInfo::new(PLACEHOLDER_ROOT_ID)), + tree_id: TreeId::ROOT, + focus: PLACEHOLDER_ROOT_ID, + }; + let placeholder_tree = Tree::new(placeholder_update, false); + let placeholder_context = Context::new( + view.clone(), + placeholder_tree, + Rc::new(ActionHandlerWrapper::new(PlaceholderActionHandler {})), + *mtm, + ); + let result = Rc::clone(&placeholder_context); + self.state = State::Placeholder { + placeholder_context, + is_view_focused: *is_view_focused, + action_handler: Rc::clone(action_handler), + }; + result + } + }, + State::Placeholder { + placeholder_context, + .. + } => Rc::clone(placeholder_context), + State::Active(context) => Rc::clone(context), + } + } + + pub fn view_children<H: ActivationHandler + ?Sized>( + &mut self, + activation_handler: &mut H, + ) -> *mut NSArray<NSObject> { + let context = self.get_or_init_context(activation_handler); + let tree = context.tree.borrow(); + let state = tree.state(); + let node = state.root(); + let platform_nodes = if filter(&node) == FilterResult::Include { + vec![Id::into_super(Id::into_super( + context.get_or_create_platform_node(node.id()), + ))] + } else { + node.filtered_children(filter) + .map(|node| { + Id::into_super(Id::into_super( + context.get_or_create_platform_node(node.id()), + )) + }) + .collect::<Vec<Id<NSObject>>>() + }; + let array = NSArray::from_vec(platform_nodes); + Id::autorelease_return(array) + } + + pub fn focus<H: ActivationHandler + ?Sized>( + &mut self, + activation_handler: &mut H, + ) -> *mut NSObject { + let context = self.get_or_init_context(activation_handler); + let tree = context.tree.borrow(); + let state = tree.state(); + if let Some(node) = state.focus() { + if can_be_focused(&node) { + return Id::autorelease_return(context.get_or_create_platform_node(node.id())) + as *mut _; + } + } + null_mut() + } + + fn weak_view(&self) -> &WeakId<NSView> { + match &self.state { + State::Inactive { view, .. } => view, + State::Placeholder { + placeholder_context, + .. + } => &placeholder_context.view, + State::Active(context) => &context.view, + } + } + + pub fn hit_test<H: ActivationHandler + ?Sized>( + &mut self, + point: NSPoint, + activation_handler: &mut H, + ) -> *mut NSObject { + let view = match self.weak_view().load() { + Some(view) => view, + None => { + return null_mut(); + } + }; + + let context = self.get_or_init_context(activation_handler); + let tree = context.tree.borrow(); + let state = tree.state(); + let root = state.root(); + let point = from_ns_point(&view, &root, point); + let node = root.node_at_point(point, &filter).unwrap_or(root); + Id::autorelease_return(context.get_or_create_platform_node(node.id())) as *mut _ + } +} diff --git a/app/vendor/rune/vendor/accesskit_macos/src/context.rs b/app/vendor/rune/vendor/accesskit_macos/src/context.rs new file mode 100644 index 0000000..fe2f100 --- /dev/null +++ b/app/vendor/rune/vendor/accesskit_macos/src/context.rs @@ -0,0 +1,103 @@ +// Copyright 2022 The AccessKit Authors. All rights reserved. +// Licensed under the Apache License, Version 2.0 (found in +// the LICENSE-APACHE file) or the MIT license (found in +// the LICENSE-MIT file), at your option. + +use crate::node::PlatformNode; +use accesskit::{ActionHandler, ActionRequest}; +use accesskit_consumer::{FullNodeId, Tree}; +use hashbrown::HashMap; +use objc2::rc::{Id, WeakId}; +use objc2_app_kit::*; +use objc2_foundation::MainThreadMarker; +use std::fmt::Debug; +use std::{cell::RefCell, rc::Rc}; + +pub(crate) trait ActionHandlerNoMut { + fn do_action(&self, request: ActionRequest); +} + +pub(crate) struct ActionHandlerWrapper<H: ActionHandler>(RefCell<H>); + +impl<H: 'static + ActionHandler> ActionHandlerWrapper<H> { + pub(crate) fn new(inner: H) -> Self { + Self(RefCell::new(inner)) + } +} + +impl<H: ActionHandler> ActionHandlerNoMut for ActionHandlerWrapper<H> { + fn do_action(&self, request: ActionRequest) { + self.0.borrow_mut().do_action(request) + } +} + +pub(crate) struct Context { + pub(crate) view: WeakId<NSView>, + pub(crate) tree: RefCell<Tree>, + pub(crate) action_handler: Rc<dyn ActionHandlerNoMut>, + platform_nodes: RefCell<HashMap<FullNodeId, Id<PlatformNode>>>, + pub(crate) mtm: MainThreadMarker, +} + +impl Debug for Context { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("Context") + .field("view", &self.view) + .field("tree", &self.tree) + .field("action_handler", &"ActionHandler") + .field("platform_nodes", &self.platform_nodes) + .field("mtm", &self.mtm) + .finish() + } +} + +impl Context { + pub(crate) fn new( + view: WeakId<NSView>, + tree: Tree, + action_handler: Rc<dyn ActionHandlerNoMut>, + mtm: MainThreadMarker, + ) -> Rc<Self> { + Rc::new(Self { + view, + tree: RefCell::new(tree), + action_handler, + platform_nodes: RefCell::new(HashMap::new()), + mtm, + }) + } + + pub(crate) fn get_or_create_platform_node(self: &Rc<Self>, id: FullNodeId) -> Id<PlatformNode> { + let mut platform_nodes = self.platform_nodes.borrow_mut(); + if let Some(result) = platform_nodes.get(&id) { + return result.clone(); + } + + let result = PlatformNode::new(Rc::downgrade(self), id); + platform_nodes.insert(id, result.clone()); + result + } + + pub(crate) fn remove_platform_node(&self, id: FullNodeId) -> Option<Id<PlatformNode>> { + let mut platform_nodes = self.platform_nodes.borrow_mut(); + platform_nodes.remove(&id) + } + + pub(crate) fn do_action(&self, request: ActionRequest) { + self.action_handler.do_action(request); + } +} + +impl Drop for Context { + fn drop(&mut self) { + let platform_nodes = self.platform_nodes.borrow(); + for platform_node in platform_nodes.values() { + unsafe { + NSAccessibilityPostNotification( + platform_node, + NSAccessibilityUIElementDestroyedNotification, + ) + }; + } + } +} diff --git a/app/vendor/rune/vendor/accesskit_macos/src/event.rs b/app/vendor/rune/vendor/accesskit_macos/src/event.rs new file mode 100644 index 0000000..a7b4389 --- /dev/null +++ b/app/vendor/rune/vendor/accesskit_macos/src/event.rs @@ -0,0 +1,336 @@ +// Copyright 2022 The AccessKit Authors. All rights reserved. +// Licensed under the Apache License, Version 2.0 (found in +// the LICENSE-APACHE file) or the MIT license (found in +// the LICENSE-MIT file), at your option. + +use accesskit::{Live, Role}; +use accesskit_consumer::{FilterResult, FullNodeId, NodeRef, TreeChangeHandler}; +use hashbrown::HashSet; +use objc2::runtime::{AnyObject, ProtocolObject}; +use objc2_app_kit::*; +use objc2_foundation::{NSMutableDictionary, NSNumber, NSString}; +use std::{collections::VecDeque, rc::Rc}; + +use crate::{ + context::Context, + filters::filter, + long_text::long_text, + node::{NodeWrapper, Value}, +}; + +// This type is designed to be safe to create on a non-main thread +// and send to the main thread. This ability isn't yet used though. +pub(crate) enum QueuedEvent { + Generic { + node_id: FullNodeId, + notification: &'static NSAccessibilityNotificationName, + }, + NodeDestroyed(FullNodeId), + Announcement { + text: String, + priority: NSAccessibilityPriorityLevel, + }, +} + +impl QueuedEvent { + fn live_region_announcement(text: String, live: Live) -> Self { + Self::Announcement { + text, + priority: if live == Live::Assertive { + NSAccessibilityPriorityLevel::NSAccessibilityPriorityHigh + } else { + NSAccessibilityPriorityLevel::NSAccessibilityPriorityMedium + }, + } + } + + fn raise(self, context: &Rc<Context>) { + match self { + Self::Generic { + node_id, + notification, + } => { + let platform_node = context.get_or_create_platform_node(node_id); + unsafe { NSAccessibilityPostNotification(&platform_node, notification) }; + } + Self::NodeDestroyed(node_id) => { + if let Some(platform_node) = context.remove_platform_node(node_id) { + unsafe { + NSAccessibilityPostNotification( + &platform_node, + NSAccessibilityUIElementDestroyedNotification, + ) + }; + } + } + Self::Announcement { text, priority } => { + let view = match context.view.load() { + Some(view) => view, + None => { + return; + } + }; + + let window = match view.window() { + Some(window) => window, + None => { + return; + } + }; + + let mut user_info = NSMutableDictionary::<_, AnyObject>::new(); + let text = NSString::from_str(&text); + unsafe { + user_info.setObject_forKey( + &*text, + ProtocolObject::from_ref(NSAccessibilityAnnouncementKey), + ) + }; + let priority = NSNumber::new_isize(priority.0); + unsafe { + user_info.setObject_forKey( + &*priority, + ProtocolObject::from_ref(NSAccessibilityPriorityKey), + ) + }; + + unsafe { + NSAccessibilityPostNotificationWithUserInfo( + &window, + NSAccessibilityAnnouncementRequestedNotification, + Some(&**user_info), + ) + }; + } + } + } +} + +/// Events generated by a tree update. +#[must_use = "events must be explicitly raised"] +pub struct QueuedEvents { + context: Rc<Context>, + events: Vec<QueuedEvent>, +} + +impl QueuedEvents { + pub(crate) fn new(context: Rc<Context>, events: Vec<QueuedEvent>) -> Self { + Self { context, events } + } + + /// Raise all queued events synchronously. + /// + /// It is unknown whether accessibility methods on the view may be + /// called while events are being raised. This means that any locks + /// or runtime borrows required to access the adapter must not + /// be held while this method is called. + pub fn raise(self) { + for event in self.events { + event.raise(&self.context); + } + } +} + +pub(crate) fn focus_event(node_id: FullNodeId) -> QueuedEvent { + QueuedEvent::Generic { + node_id, + notification: unsafe { NSAccessibilityFocusedUIElementChangedNotification }, + } +} + +pub(crate) struct EventGenerator { + context: Rc<Context>, + events: Vec<QueuedEvent>, + text_changed: HashSet<FullNodeId>, + selected_rows_changed: HashSet<FullNodeId>, +} + +impl EventGenerator { + pub(crate) fn new(context: Rc<Context>) -> Self { + Self { + context, + events: Vec::new(), + text_changed: HashSet::new(), + selected_rows_changed: HashSet::new(), + } + } + + pub(crate) fn into_result(self) -> QueuedEvents { + QueuedEvents::new(self.context, self.events) + } + + fn remove_subtree(&mut self, node: &NodeRef) { + let mut to_remove = VecDeque::new(); + to_remove.push_back(*node); + + while let Some(node) = to_remove.pop_front() { + for child in node.filtered_children(&filter) { + to_remove.push_back(child); + } + + self.events.push(QueuedEvent::NodeDestroyed(node.id())); + } + } + + fn insert_text_change_if_needed_parent(&mut self, node: NodeRef) { + if !node.supports_text_ranges() { + return; + } + let id = node.id(); + if self.text_changed.contains(&id) { + return; + } + // Text change events must come before selection change + // events. It doesn't matter if text change events come + // before other events. + self.events.insert( + 0, + QueuedEvent::Generic { + node_id: id, + notification: unsafe { NSAccessibilityValueChangedNotification }, + }, + ); + self.text_changed.insert(id); + } + + fn insert_text_change_if_needed(&mut self, node: &NodeRef) { + if node.role() != Role::TextRun { + return; + } + if let Some(node) = node.filtered_parent(&filter) { + self.insert_text_change_if_needed_parent(node); + } + } + + fn enqueue_selected_rows_change_if_needed_parent(&mut self, node: NodeRef) { + let id = node.id(); + if self.selected_rows_changed.contains(&id) { + return; + } + self.events.push(QueuedEvent::Generic { + node_id: id, + notification: unsafe { NSAccessibilitySelectedRowsChangedNotification }, + }); + self.selected_rows_changed.insert(id); + } + + fn enqueue_selected_rows_change_if_needed(&mut self, node: &NodeRef) { + let wrapper = NodeWrapper(node); + if !wrapper.is_item_like() { + return; + } + if let Some(node) = node.selection_container(&filter) { + self.enqueue_selected_rows_change_if_needed_parent(node); + } + } +} + +impl TreeChangeHandler for EventGenerator { + fn node_added(&mut self, node: &NodeRef) { + self.insert_text_change_if_needed(node); + if filter(node) != FilterResult::Include { + return; + } + if let Some(true) = node.is_selected() { + self.enqueue_selected_rows_change_if_needed(node); + } + if let Some(label) = NodeWrapper(node).label() { + if node.live() != Live::Off { + self.events + .push(QueuedEvent::live_region_announcement(label, node.live())); + } + } + } + + fn node_updated(&mut self, old_node: &NodeRef, new_node: &NodeRef) { + if old_node.raw_value() != new_node.raw_value() { + self.insert_text_change_if_needed(new_node); + } + let old_filter_result = filter(old_node); + let new_filter_result = filter(new_node); + if new_filter_result != FilterResult::Include { + if old_filter_result == FilterResult::Include && old_node.is_selected() == Some(true) { + self.enqueue_selected_rows_change_if_needed(old_node); + } + if new_filter_result == FilterResult::ExcludeSubtree { + self.remove_subtree(old_node); + } else { + self.events.push(QueuedEvent::NodeDestroyed(new_node.id())); + } + return; + } + let node_id = new_node.id(); + let old_wrapper = NodeWrapper(old_node); + let new_wrapper = NodeWrapper(new_node); + if old_wrapper.title() != new_wrapper.title() { + self.events.push(QueuedEvent::Generic { + node_id, + notification: unsafe { NSAccessibilityTitleChangedNotification }, + }); + } + let new_value = new_wrapper.value(); + if old_wrapper.value() != new_value { + if !new_node.is_focused() && new_value.is_some_and(|v| matches!(v, Value::Bool(_))) { + // Bool value changed event for the focused node must come last + // in order for VoiceOver to announce it. Otherwise, if we raise + // bool value changed events for other nodes after this one, VoiceOver + // will announce them instead. + self.events.insert( + 0, + QueuedEvent::Generic { + node_id, + notification: unsafe { NSAccessibilityValueChangedNotification }, + }, + ); + } else { + self.events.push(QueuedEvent::Generic { + node_id, + notification: unsafe { NSAccessibilityValueChangedNotification }, + }); + } + } + if (old_wrapper.supports_text_ranges() || long_text(old_node).is_some()) + && (new_wrapper.supports_text_ranges() || long_text(new_node).is_some()) + && old_wrapper.raw_text_selection() != new_wrapper.raw_text_selection() + { + self.events.push(QueuedEvent::Generic { + node_id, + notification: unsafe { NSAccessibilitySelectedTextChangedNotification }, + }); + } + if let Some(new_label) = new_wrapper.label() { + if new_node.live() != Live::Off + && (Some(&new_label) != old_wrapper.label().as_ref() + || new_node.live() != old_node.live() + || old_filter_result != FilterResult::Include) + { + self.events.push(QueuedEvent::live_region_announcement( + new_label, + new_node.live(), + )); + } + } + if new_node.is_selected() != old_node.is_selected() + || (old_filter_result != FilterResult::Include && new_node.is_selected() == Some(true)) + { + self.enqueue_selected_rows_change_if_needed(new_node); + } + } + + fn focus_moved(&mut self, _old_node: Option<&NodeRef>, new_node: Option<&NodeRef>) { + if let Some(new_node) = new_node { + if filter(new_node) != FilterResult::Include { + return; + } + self.events.push(focus_event(new_node.id())); + } + } + + fn node_removed(&mut self, node: &NodeRef) { + self.insert_text_change_if_needed(node); + if let Some(true) = node.is_selected() { + self.enqueue_selected_rows_change_if_needed(node); + } + self.events.push(QueuedEvent::NodeDestroyed(node.id())); + } +} diff --git a/app/vendor/rune/vendor/accesskit_macos/src/filters.rs b/app/vendor/rune/vendor/accesskit_macos/src/filters.rs new file mode 100644 index 0000000..2802d57 --- /dev/null +++ b/app/vendor/rune/vendor/accesskit_macos/src/filters.rs @@ -0,0 +1,6 @@ +// Copyright 2023 The AccessKit Authors. All rights reserved. +// Licensed under the Apache License, Version 2.0 (found in +// the LICENSE-APACHE file) or the MIT license (found in +// the LICENSE-MIT file), at your option. + +pub(crate) use accesskit_consumer::common_filter as filter; diff --git a/app/vendor/rune/vendor/accesskit_macos/src/lib.rs b/app/vendor/rune/vendor/accesskit_macos/src/lib.rs new file mode 100644 index 0000000..fbd7b8b --- /dev/null +++ b/app/vendor/rune/vendor/accesskit_macos/src/lib.rs @@ -0,0 +1,26 @@ +// Copyright 2022 The AccessKit Authors. All rights reserved. +// Licensed under the Apache License, Version 2.0 (found in +// the LICENSE-APACHE file) or the MIT license (found in +// the LICENSE-MIT file), at your option. + +#![deny(unsafe_op_in_unsafe_fn)] + +mod context; +mod filters; +mod long_text; +mod node; +mod util; + +mod adapter; +pub use adapter::Adapter; + +mod event; +pub use event::QueuedEvents; + +mod patch; +pub use patch::add_focus_forwarder_to_window_class; + +mod subclass; +pub use subclass::SubclassingAdapter; + +pub use objc2_foundation::{NSArray, NSObject, NSPoint}; diff --git a/app/vendor/rune/vendor/accesskit_macos/src/long_text.rs b/app/vendor/rune/vendor/accesskit_macos/src/long_text.rs new file mode 100644 index 0000000..ae053e0 --- /dev/null +++ b/app/vendor/rune/vendor/accesskit_macos/src/long_text.rs @@ -0,0 +1,796 @@ +// Rune (vendor/accesskit_macos.patch): a text field too long for its toolkit to publish text +// runs (Rune stops at 64 KiB) keeps its text ranges. The toolkit marks such a field by putting its +// selection on the field itself, as byte offsets into its value, and publishes a single +// GenericContainer (`class_name = "\x1frune-lines"`) holding one GenericContainer child +// (`class_name = "\x1frune-line"`, `author_id = "<start>:<end>"`) per drawn visual line. Ranges +// are answered from the value when a reader asks, and screen rectangles, hit-testing and wrapped +// visual lines are answered in the drawn band without shaping off-screen rows. +// The same file is in accesskit_windows and accesskit_macos; each uses part of it. +#![allow(dead_code)] + +use std::cell::RefCell; + +use accesskit::{Point, Rect, Role, TextDirection, TextSelection}; +use accesskit_consumer::NodeRef; + +const LINES_BOX_CLASS: &str = "\x1frune-lines"; +const LINE_CLASS: &str = "\x1frune-line"; +const CHECKPOINT_STRIDE: usize = 65_536; + +#[derive(Clone, Copy, PartialEq, Eq)] +pub(crate) enum Unit { + Character, + Word, + Line, + Paragraph, + Document, +} + +/// One visual line currently drawn on screen for a long field. +#[derive(Clone, Copy)] +pub(crate) struct DrawnLine<'a> { + pub(crate) start: usize, + pub(crate) end: usize, + pub(crate) node: NodeRef<'a>, +} + +/// All drawn-line metadata published on `node` for the current tree snapshot. +pub(crate) struct DrawnState<'a> { + pub(crate) lines: Vec<DrawnLine<'a>>, + pub(crate) content_key: u64, + pub(crate) upstream_caret: bool, + pub(crate) caret_byte: usize, +} + +struct Band { + start: usize, + end: usize, + first: usize, + count: usize, +} + +#[derive(Clone, Copy)] +struct Mark { + byte: usize, + utf16: usize, + newlines: usize, +} + +struct Checkpoints { + content_key: u64, + len: usize, + edge: [u8; 32], + marks: Vec<Mark>, +} + +const CHECKPOINT_SLOTS: usize = 4; + +struct CheckpointRing { + slots: [Option<Checkpoints>; CHECKPOINT_SLOTS], + next: usize, +} + +thread_local! { + static CHECKPOINTS: RefCell<CheckpointRing> = const { + RefCell::new(CheckpointRing { + slots: [None, None, None, None], + next: 0, + }) + }; +} + +fn edge_sample(s: &str) -> [u8; 32] { + let mut out = [0u8; 32]; + let b = s.as_bytes(); + let head = b.len().min(16); + out[..head].copy_from_slice(&b[..head]); + let tail = b.len().min(16); + out[16..16 + tail].copy_from_slice(&b[b.len() - tail..]); + out +} + +fn with_checkpoints<R>(s: &str, content_key: u64, f: impl FnOnce(&[Mark]) -> R) -> R { + if s.len() <= CHECKPOINT_STRIDE { + return f(&[Mark { byte: 0, utf16: 0, newlines: 0 }]); + } + let edge = edge_sample(s); + CHECKPOINTS.with(|cell| { + let mut ring = cell.borrow_mut(); + if let Some(hit) = ring.slots.iter().flatten().find(|c| { + c.content_key == content_key && c.len == s.len() && c.edge == edge + }) { + return f(hit.marks.as_slice()); + } + let mut marks = Vec::with_capacity(s.len() / CHECKPOINT_STRIDE + 2); + marks.push(Mark { byte: 0, utf16: 0, newlines: 0 }); + let mut utf16 = 0usize; + let mut newlines = 0usize; + let mut next_at = CHECKPOINT_STRIDE; + for (k, ch) in s.char_indices() { + if k >= next_at { + marks.push(Mark { byte: k, utf16, newlines }); + next_at = k + CHECKPOINT_STRIDE; + } + utf16 += ch.len_utf16(); + if ch == '\n' { + newlines += 1; + } + } + let idx = ring.next % CHECKPOINT_SLOTS; + ring.next = ring.next.wrapping_add(1); + ring.slots[idx] = Some(Checkpoints { content_key, len: s.len(), edge, marks }); + let marks = ring.slots[idx].as_ref().map_or(&[][..], |c| c.marks.as_slice()); + f(marks) + }) +} + +/// The value and selection a long field's text ranges are answered from. +pub(crate) fn long_text<'a>(node: &NodeRef<'a>) -> Option<(Text<'a>, &'a TextSelection)> { + if !node.is_text_input() || node.is_password_input() || node.supports_text_ranges() { + return None; + } + let data = node.data(); + let selection = data.text_selection()?; + let (id, _) = node.locate(); + if selection.anchor.node != id || selection.focus.node != id { + return None; + } + Some((Text(data.value().unwrap_or("")), selection)) +} + +/// Drawn visual lines Rune attached to `node` inside its `\x1frune-lines` container, sorted and +/// strictly non-overlapping. +pub(crate) fn drawn_state<'a>(node: &NodeRef<'a>, text: Text<'a>) -> DrawnState<'a> { + let caret_byte = node + .data() + .text_selection() + .map_or(0, |s| text.clamp(s.focus.character_index)); + let Some(box_node) = node + .children() + .find(|c| c.role() == Role::GenericContainer && c.data().class_name() == Some(LINES_BOX_CLASS)) + else { + return DrawnState { + lines: Vec::new(), + content_key: 0, + upstream_caret: false, + caret_byte, + }; + }; + let (content_key, upstream_caret) = box_node + .author_id() + .and_then(|s| s.split_once(':')) + .map_or((0, false), |(k, u)| (u64::from_str_radix(k, 16).unwrap_or(0), u == "1")); + + let mut raw = Vec::new(); + for child in box_node.children() { + if child.role() != Role::GenericContainer || child.data().class_name() != Some(LINE_CLASS) { + continue; + } + let Some((a, b)) = child.author_id().and_then(|id| id.split_once(':')) else { + continue; + }; + let (Ok(a), Ok(b)) = (a.parse::<usize>(), b.parse::<usize>()) else { + continue; + }; + let start = text.clamp(a); + let end = text.clamp(b).max(start); + raw.push(DrawnLine { start, end, node: child }); + } + raw.sort_by_key(|d| (d.start, d.end)); + let mut lines: Vec<DrawnLine<'a>> = Vec::new(); + for d in raw { + if let Some(prev) = lines.last() + && (d.start < prev.end || (d.start == prev.start && d.end == prev.end)) + { + continue; + } + lines.push(d); + } + DrawnState { lines, content_key, upstream_caret, caret_byte } +} + +pub(crate) fn drawn_lines<'a>(node: &NodeRef<'a>, text: Text<'a>) -> Vec<DrawnLine<'a>> { + drawn_state(node, text).lines +} + +fn bands(drawn: &[DrawnLine]) -> Vec<Band> { + let mut out: Vec<Band> = Vec::new(); + for (idx, d) in drawn.iter().enumerate() { + if let Some(last) = out.last_mut() + && last.end == d.start + { + last.end = d.end; + last.count += 1; + continue; + } + out.push(Band { start: d.start, end: d.end, first: idx, count: 1 }); + } + out +} + +fn line_is_rtl(line: &NodeRef) -> bool { + line.data().text_direction() == Some(TextDirection::RightToLeft) +} + +fn line_is_hard_end(text: Text, end: usize) -> bool { + end > 0 && text.0.as_bytes().get(end - 1) == Some(&b'\n') +} + +fn caret_x_in_line(line: &NodeRef, rel_byte: usize, trailing_edge: bool) -> f64 { + let data = line.data(); + let rtl = line_is_rtl(line); + let w = data.bounds().map_or(0.0, |r| r.width()); + if trailing_edge { + return if rtl { 0.0 } else { w }; + } + let lengths = data.character_lengths(); + let positions = data.character_positions().unwrap_or(&[]); + let widths = data.character_widths().unwrap_or(&[]); + if lengths.is_empty() || positions.len() < lengths.len() || widths.len() < lengths.len() { + return if (rel_byte == 0) != rtl { 0.0 } else { w }; + } + let mut seen = 0usize; + for (k, &len) in lengths.iter().enumerate() { + let next = seen + usize::from(len); + if rel_byte < next || (rel_byte == seen && len == 0) { + let x0 = f64::from(positions[k]); + let x1 = x0 + f64::from(widths[k]); + let cluster_rtl = if k + 1 < lengths.len() && widths[k] > 0.0 && widths[k + 1] > 0.0 { + positions[k + 1] < positions[k] + } else if k > 0 && widths[k] > 0.0 && widths[k - 1] > 0.0 { + positions[k] < positions[k - 1] + } else { + rtl + }; + return if cluster_rtl { x1 } else { x0 }; + } + seen = next; + } + if rtl { 0.0 } else { w } +} + +fn span_x_in_line(line: &NodeRef, rel_start: usize, rel_end: usize) -> (f64, f64) { + let data = line.data(); + let w = data.bounds().map_or(0.0, |r| r.width()); + let lengths = data.character_lengths(); + let positions = data.character_positions().unwrap_or(&[]); + let widths = data.character_widths().unwrap_or(&[]); + if lengths.is_empty() || positions.len() < lengths.len() || widths.len() < lengths.len() { + return (0.0, w); + } + let mut seen = 0usize; + let mut min_x = f64::INFINITY; + let mut max_x = f64::NEG_INFINITY; + for (k, &len) in lengths.iter().enumerate() { + let next = seen + usize::from(len); + if next > rel_start && seen < rel_end { + let x0 = f64::from(positions[k]); + let x1 = x0 + f64::from(widths[k]).max(0.0); + min_x = min_x.min(x0); + max_x = max_x.max(x1); + } + seen = next; + } + if min_x.is_finite() && max_x.is_finite() { + (min_x, max_x.max(min_x)) + } else { + let x = caret_x_in_line(line, rel_start, false); + (x, x) + } +} + +/// Transformed bounding boxes (in root/window coordinates, matching AccessKit's `Range::bounding_boxes`) +/// for the drawn portion of `a..b`. Off-screen bytes have no box, matching Chromium. +pub(crate) fn bounding_boxes(node: &NodeRef, text: Text, a: usize, b: usize) -> Vec<Rect> { + let (a, b) = (text.clamp(a.min(b)), text.clamp(a.max(b))); + let state = drawn_state(node, text); + let drawn = &state.lines; + if drawn.is_empty() { + return Vec::new(); + } + if a == b { + if state.upstream_caret && a == state.caret_byte { + if let Some(d) = drawn + .iter() + .find(|d| a == d.end && d.start < d.end && !line_is_hard_end(text, d.end)) + && let Some(mut rect) = d.node.data().bounds() + { + let x = caret_x_in_line(&d.node, a - d.start, true); + let left = rect.x0 + x; + rect.x0 = left; + rect.x1 = left; + return vec![d.node.transform().transform_rect_bbox(rect)]; + } + } + let hit = drawn.iter().enumerate().find(|&(k, d)| { + (d.start <= a && a < d.end) + || (d.start == a && d.end == a) + || (a == d.end + && !line_is_hard_end(text, d.end) + && drawn.get(k + 1).is_none_or(|nx| nx.start != a)) + }); + let Some((_, d)) = hit else { + return Vec::new(); + }; + let Some(mut rect) = d.node.data().bounds() else { + return Vec::new(); + }; + let x = caret_x_in_line(&d.node, a.saturating_sub(d.start), false); + let left = rect.x0 + x; + rect.x0 = left; + rect.x1 = left; + return vec![d.node.transform().transform_rect_bbox(rect)]; + } + let mut out = Vec::new(); + for d in drawn { + let ov_start = a.max(d.start); + let ov_end = b.min(d.end); + if ov_start >= ov_end { + continue; + } + let Some(mut rect) = d.node.data().bounds() else { + continue; + }; + if ov_start > d.start || ov_end < d.end { + let orig_left = rect.x0; + let (x0, x1) = span_x_in_line(&d.node, ov_start - d.start, ov_end - d.start); + rect.x0 = orig_left + x0; + rect.x1 = orig_left + x1; + } + out.push(d.node.transform().transform_rect_bbox(rect)); + } + out +} + +/// Byte offset in `text` at `point` (in `node`'s local coordinate space), using containment inside +/// the nearest drawn visual line. When `for_char` is true (macOS `accessibilityRangeForPosition:`), +/// a point past the trailing edge of a soft-wrapped line clamps to that line's last character. +pub(crate) fn byte_at_point(node: &NodeRef, text: Text, point: Point, for_char: bool) -> Option<usize> { + let drawn = drawn_lines(node, text); + let d = drawn.iter().min_by(|a, b| { + let dist = |ln: &DrawnLine| match ln.node.data().bounds() { + Some(r) if point.y < r.y0 => r.y0 - point.y, + Some(r) if point.y > r.y1 => point.y - r.y1, + Some(_) => 0.0, + None => f64::INFINITY, + }; + dist(a).total_cmp(&dist(b)) + })?; + let bounds = d.node.data().bounds()?; + let rel_x = (point.x - bounds.x0) as f32; + let data = d.node.data(); + let rtl = line_is_rtl(&d.node); + let lengths = data.character_lengths(); + let positions = data.character_positions().unwrap_or(&[]); + let widths = data.character_widths().unwrap_or(&[]); + if lengths.is_empty() || positions.len() < lengths.len() || widths.len() < lengths.len() { + return Some(d.start); + } + let mut byte_off = 0usize; + let mut min_x = f32::INFINITY; + let mut max_x = f32::NEG_INFINITY; + for k in 0..lengths.len() { + let w = widths[k]; + let x0 = positions[k]; + let x1 = x0 + w; + if w > 0.0 { + min_x = min_x.min(x0); + max_x = max_x.max(x1); + if rel_x >= x0 && rel_x < x1 { + return Some(text.clamp(d.start + byte_off)); + } + } + byte_off += usize::from(lengths[k]); + } + let trim = if d.end >= d.start + 2 && text.0.as_bytes().get(d.end - 2..d.end) == Some(b"\r\n") { + 2 + } else if d.end > d.start && text.0.as_bytes().get(d.end - 1) == Some(&b'\n') { + 1 + } else { + 0 + }; + let line_end = text.clamp(d.end.saturating_sub(trim)).max(d.start); + let leading = if rtl { rel_x >= max_x } else { rel_x <= min_x }; + if leading { + return Some(d.start); + } + if for_char && trim == 0 && line_end > d.start { + return Some(text.prev(line_end, Unit::Character).max(d.start)); + } + Some(line_end) +} + +fn utf16_len(s: &str) -> usize { + if s.is_ascii() { s.len() } else { s.chars().map(char::len_utf16).sum() } +} + +fn count_newlines_slice(s: &str) -> usize { + s.as_bytes().iter().filter(|&&b| b == b'\n').count() +} + +fn count_newlines_between(s: &str, a: usize, b: usize, marks: &[Mark]) -> usize { + if a >= b || b > s.len() { + return 0; + } + if b - a <= CHECKPOINT_STRIDE || marks.len() <= 1 { + return s.get(a..b).map_or(0, count_newlines_slice); + } + let ma = marks.partition_point(|m| m.byte <= a).saturating_sub(1); + let mb = marks.partition_point(|m| m.byte <= b).saturating_sub(1); + if mb <= ma { + return s.get(a..b).map_or(0, count_newlines_slice); + } + let head_sub = s.get(marks[ma].byte..a).map_or(0, count_newlines_slice); + let tail_add = s.get(marks[mb].byte..b).map_or(0, count_newlines_slice); + (marks[mb].newlines + tail_add).saturating_sub(marks[ma].newlines + head_sub) +} + +fn nth_newline_after(s: &str, from: usize, limit: usize, nth: usize, marks: &[Mark]) -> Option<usize> { + let sub = s.get(from..limit)?; + if limit - from <= CHECKPOINT_STRIDE || marks.len() <= 1 { + return sub.match_indices('\n').nth(nth).map(|(p, _)| from + p); + } + let m_from = marks.partition_point(|m| m.byte <= from).saturating_sub(1); + let base_nl = marks[m_from].newlines + s.get(marks[m_from].byte..from).map_or(0, count_newlines_slice); + let target_nl = base_nl + nth + 1; + let m_hit = marks.partition_point(|m| m.newlines < target_nl).saturating_sub(1); + let scan_start = marks[m_hit].byte.max(from); + if scan_start >= limit { + return None; + } + let already = if scan_start == from { + 0 + } else { + (marks[m_hit].newlines).saturating_sub(base_nl) + }; + let rem = nth.checked_sub(already)?; + s.get(scan_start..limit)? + .match_indices('\n') + .nth(rem) + .map(|(p, _)| scan_start + p) +} + +/// Byte offsets into a field's value. +#[derive(Clone, Copy)] +pub(crate) struct Text<'a>(pub(crate) &'a str); + +impl<'a> Text<'a> { + pub(crate) fn len(self) -> usize { + self.0.len() + } + + /// `i`, within the text and on a character's start. + pub(crate) fn clamp(self, i: usize) -> usize { + self.0.floor_char_boundary(i.min(self.0.len())) + } + + pub(crate) fn slice(self, a: usize, b: usize) -> &'a str { + let (a, b) = (self.clamp(a.min(b)), self.clamp(a.max(b))); + self.0.get(a..b).unwrap_or("") + } + + fn line_start(self, i: usize) -> usize { + let i = self.clamp(i); + self.0.get(..i).and_then(|s| s.rfind('\n')).map_or(0, |p| p + 1) + } + + pub(crate) fn is_start(self, i: usize, unit: Unit) -> bool { + let i = self.clamp(i); + let s = self.0; + match unit { + Unit::Character => true, + Unit::Word => { + i == 0 + || (s.get(i..).and_then(|r| r.chars().next()).is_some_and(|c| !c.is_whitespace()) + && s.get(..i).and_then(|l| l.chars().next_back()).is_some_and(char::is_whitespace)) + } + Unit::Line | Unit::Paragraph => i == 0 || s.as_bytes().get(i - 1) == Some(&b'\n'), + Unit::Document => i == 0, + } + } + + pub(crate) fn is_start_in(self, i: usize, unit: Unit, state: &DrawnState) -> bool { + let i = self.clamp(i); + if unit == Unit::Line && !state.lines.is_empty() { + if state.upstream_caret + && i == state.caret_byte + && state + .lines + .iter() + .any(|d| i == d.end && d.start < d.end && !line_is_hard_end(self, d.end)) + { + return false; + } + if let Some(d) = state + .lines + .iter() + .find(|d| (d.start <= i && i < d.end) || (d.start == i && d.end == i)) + { + return i == d.start; + } + } + self.is_start(i, unit) + } + + /// The start of the unit holding `i`. + pub(crate) fn start_of(self, i: usize, unit: Unit) -> usize { + let i = self.clamp(i); + if self.is_start(i, unit) { i } else { self.prev(i, unit) } + } + + pub(crate) fn start_of_in(self, i: usize, unit: Unit, state: &DrawnState) -> usize { + let i = self.clamp(i); + if self.is_start_in(i, unit, state) { + i + } else { + self.prev_in(i, unit, &state.lines) + } + } + + /// The first unit start after `i`, or the text's end. + pub(crate) fn next(self, i: usize, unit: Unit) -> usize { + let i = self.clamp(i); + let s = self.0; + let tail = s.get(i..).unwrap_or(""); + match unit { + Unit::Character => tail.chars().next().map_or(i, |c| i + c.len_utf8()), + Unit::Word => { + let mut space = false; + for (k, c) in tail.char_indices() { + if c.is_whitespace() { + space = true; + } else if space { + return i + k; + } + } + s.len() + } + Unit::Line | Unit::Paragraph => tail.find('\n').map_or(s.len(), |p| i + p + 1), + Unit::Document => s.len(), + } + } + + pub(crate) fn next_in(self, i: usize, unit: Unit, drawn: &[DrawnLine]) -> usize { + let i = self.clamp(i); + if unit != Unit::Line || drawn.is_empty() { + return self.next(i, unit); + } + if let Some(d) = drawn.iter().find(|d| d.start <= i && i < d.end) { + return d.end; + } + let nl = self.next(i, Unit::Line); + drawn + .iter() + .find(|d| d.start > i && d.start < nl) + .map_or(nl, |d| d.start) + } + + /// The last unit start before `i`, or the text's start. + pub(crate) fn prev(self, i: usize, unit: Unit) -> usize { + let i = self.clamp(i); + let s = self.0; + let head = s.get(..i).unwrap_or(""); + match unit { + Unit::Character => head.chars().next_back().map_or(0, |c| i - c.len_utf8()), + Unit::Word => { + let mut word = None; + for (k, c) in head.char_indices().rev() { + if !c.is_whitespace() { + word = Some(k); + } else if let Some(k) = word { + return k; + } + } + 0 + } + Unit::Line | Unit::Paragraph => { + if i == 0 { + return 0; + } + let at = self.line_start(i); + if at < i { + at + } else { + self.line_start(self.clamp(i - 1)) + } + } + Unit::Document => 0, + } + } + + pub(crate) fn prev_in(self, i: usize, unit: Unit, drawn: &[DrawnLine]) -> usize { + let i = self.clamp(i); + if unit != Unit::Line || drawn.is_empty() || i == 0 { + return self.prev(i, unit); + } + if let Some(d) = drawn.iter().rfind(|d| d.start < i && i <= d.end) { + return d.start; + } + if drawn.iter().any(|d| d.start == i) { + if let Some(prev_d) = drawn.iter().rfind(|d| d.end == i && d.start < i) { + return prev_d.start; + } + return self.prev(i, Unit::Line); + } + let p = self.prev(i, Unit::Line); + drawn + .iter() + .rfind(|d| d.start >= p && d.start < i) + .map_or(p, |d| d.start) + } + + /// Moves `i` by `count` unit starts, stopping at either end of the text. + pub(crate) fn step_in(self, i: usize, unit: Unit, count: i32, drawn: &[DrawnLine]) -> (usize, i32) { + let mut i = self.clamp(i); + if count == 0 { + return (i, 0); + } + let mut moved = 0i32; + let steps = count.unsigned_abs(); + for _ in 0..steps { + if (count > 0 && i == self.len()) || (count < 0 && i == 0) { + break; + } + let next_i = if count > 0 { + self.next_in(i, unit, drawn) + } else { + self.prev_in(i, unit, drawn) + }; + if next_i == i { + break; + } + i = next_i; + moved = moved.saturating_add(1); + } + (i, if count < 0 { -moved } else { moved }) + } + + /// The zero-based line holding byte `i`, counting drawn wrapped lines visually. + pub(crate) fn line_of_in(self, i: usize, state: &DrawnState) -> usize { + let i = self.clamp(i); + let s = self.0; + let drawn = &state.lines; + let bs = bands(drawn); + with_checkpoints(s, state.content_key, |marks| { + if bs.is_empty() { + return count_newlines_between(s, 0, i, marks); + } + let mut lines = 0usize; + let mut cursor = 0usize; + for b in &bs { + if i < b.start { + return lines + count_newlines_between(s, cursor, i, marks); + } + lines += count_newlines_between(s, cursor, b.start, marks); + let band_slice = &drawn[b.first..b.first + b.count]; + let has_trailing_empty = + band_slice.last().is_some_and(|d| d.start == b.end && d.end == b.end); + let in_band_at_end = i == b.end + && b.end == s.len() + && (has_trailing_empty || !line_is_hard_end(self, b.end)); + if i < b.end + || in_band_at_end + || (state.upstream_caret + && i == state.caret_byte + && i == b.end + && b.start < b.end + && !line_is_hard_end(self, b.end)) + { + if state.upstream_caret && i == state.caret_byte { + if let Some(sub) = band_slice + .iter() + .position(|d| i == d.end && d.start < d.end && !line_is_hard_end(self, d.end)) + { + return lines + sub; + } + } + let sub = band_slice.iter().rposition(|d| d.start <= i).unwrap_or(0); + return lines + sub; + } + lines += b.count; + cursor = b.end; + } + lines + count_newlines_between(s, cursor, i, marks) + }) + } + + /// Line `n`'s bytes, counting drawn wrapped lines visually. + pub(crate) fn line_in(self, n: usize, state: &DrawnState) -> Option<(usize, usize)> { + let s = self.0; + let drawn = &state.lines; + let bs = bands(drawn); + with_checkpoints(s, state.content_key, |marks| { + if bs.is_empty() { + let start = if n == 0 { + 0 + } else { + nth_newline_after(s, 0, s.len(), n - 1, marks)? + 1 + }; + return Some((start, self.next(start, Unit::Line))); + } + let mut rem = n; + let mut cursor = 0usize; + for b in &bs { + let gap_lines = count_newlines_between(s, cursor, b.start, marks); + if rem < gap_lines { + let start = if rem == 0 { + cursor + } else { + nth_newline_after(s, cursor, b.start, rem - 1, marks)? + 1 + }; + return Some((start, self.next(start, Unit::Line).min(b.start))); + } + rem -= gap_lines; + if rem < b.count { + let d = &drawn[b.first + rem]; + return Some((d.start, d.end)); + } + rem -= b.count; + cursor = b.end; + } + let drawn_has_end_empty = + drawn.last().is_some_and(|d| d.start == s.len() && d.end == s.len()); + if cursor >= s.len() { + if !drawn_has_end_empty && line_is_hard_end(self, s.len()) && rem == 0 { + return Some((s.len(), s.len())); + } + return None; + } + let start = if rem == 0 { + cursor + } else { + nth_newline_after(s, cursor, s.len(), rem - 1, marks)? + 1 + }; + Some((start, self.next(start, Unit::Line))) + }) + } + + pub(crate) fn utf16_with(self, i: usize, key: u64) -> usize { + let i = self.clamp(i); + with_checkpoints(self.0, key, |marks| { + let idx = marks.partition_point(|m| m.byte <= i).saturating_sub(1); + let m = marks.get(idx).copied().unwrap_or(Mark { byte: 0, utf16: 0, newlines: 0 }); + m.utf16 + self.0.get(m.byte..i).map_or(0, utf16_len) + }) + } + + pub(crate) fn utf16(self, i: usize) -> usize { + self.utf16_with(i, 0) + } + + /// Bytes `a..b` as a UTF-16 start and length. + pub(crate) fn utf16_span_with(self, a: usize, b: usize, key: u64) -> (usize, usize) { + let (a, b) = (self.clamp(a.min(b)), self.clamp(a.max(b))); + let start = self.utf16_with(a, key); + let len = if b - a <= CHECKPOINT_STRIDE { + self.0.get(a..b).map_or(0, utf16_len) + } else { + self.utf16_with(b, key).saturating_sub(start) + }; + (start, len) + } + + pub(crate) fn utf16_span(self, a: usize, b: usize) -> (usize, usize) { + self.utf16_span_with(a, b, 0) + } + + pub(crate) fn from_utf16_with(self, units: usize, key: u64) -> usize { + with_checkpoints(self.0, key, |marks| { + let idx = marks.partition_point(|m| m.utf16 <= units).saturating_sub(1); + let m = marks.get(idx).copied().unwrap_or(Mark { byte: 0, utf16: 0, newlines: 0 }); + let mut seen = m.utf16; + let tail = self.0.get(m.byte..).unwrap_or(""); + for (k, c) in tail.char_indices() { + if seen >= units { + return m.byte + k; + } + seen += c.len_utf16(); + } + self.0.len() + }) + } + + pub(crate) fn from_utf16(self, units: usize) -> usize { + self.from_utf16_with(units, 0) + } +} diff --git a/app/vendor/rune/vendor/accesskit_macos/src/node.rs b/app/vendor/rune/vendor/accesskit_macos/src/node.rs new file mode 100644 index 0000000..7322204 --- /dev/null +++ b/app/vendor/rune/vendor/accesskit_macos/src/node.rs @@ -0,0 +1,1477 @@ +// Copyright 2022 The AccessKit Authors. All rights reserved. +// Licensed under the Apache License, Version 2.0 (found in +// the LICENSE-APACHE file) or the MIT license (found in +// the LICENSE-MIT file), at your option. + +// Derived from Chromium's accessibility abstraction. +// Copyright 2018 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE.chromium file. + +#![allow(non_upper_case_globals)] + +use accesskit::{ + Action, ActionData, ActionRequest, Orientation, Role, TextAlign, TextSelection, Toggled, +}; +use accesskit_consumer::{FilterResult, FullNodeId, NodeRef, Tree}; +use objc2::{ + ClassType, DeclaredClass, declare_class, msg_send_id, + mutability::InteriorMutable, + rc::Id, + runtime::{AnyObject, Sel}, + sel, +}; +use objc2_app_kit::*; +use objc2_foundation::{ + NSArray, NSAttributedString, NSCopying, NSInteger, NSMutableAttributedString, + NSMutableDictionary, NSNumber, NSObject, NSObjectProtocol, NSPoint, NSRange, NSRect, NSString, + NSURL, ns_string, +}; +use std::rc::{Rc, Weak}; + +use crate::{ + context::Context, + filters::filter, + long_text::{Text, Unit, bounding_boxes, byte_at_point, drawn_state, long_text}, + util::*, +}; + +/// Rune: bytes `a..b` of a long field's value ([`long_text`]) as AppKit's range. +fn long_ns_range(text: Text, a: usize, b: usize, key: u64) -> NSRange { + let (start, len) = text.utf16_span_with(a, b, key); + NSRange::new(start, len) +} + +/// Rune: AppKit's range in a long field's value as bytes. +fn long_bytes(text: Text, range: NSRange, key: u64) -> (usize, usize) { + ( + text.from_utf16_with(range.location, key), + text.from_utf16_with(range.location.saturating_add(range.length), key), + ) +} + +/// Rune: the character at `index` (UTF-16) in a long field's value. +fn long_char(text: Text, index: usize, key: u64) -> NSRange { + let at = text.from_utf16_with(index, key); + long_ns_range(text, at, text.next(at, Unit::Character), key) +} + +const SCROLL_TO_VISIBLE_ACTION: &str = "AXScrollToVisible"; + +fn ns_role(node: &NodeRef) -> &'static NSAccessibilityRole { + let role = node.role(); + // TODO: Handle special cases. + unsafe { + match role { + Role::Unknown => NSAccessibilityUnknownRole, + Role::TextRun => NSAccessibilityUnknownRole, + Role::Cell | Role::GridCell => NSAccessibilityCellRole, + Role::Label => NSAccessibilityStaticTextRole, + Role::Image => NSAccessibilityImageRole, + Role::Link => NSAccessibilityLinkRole, + Role::Row => NSAccessibilityRowRole, + Role::ListItem => NSAccessibilityGroupRole, + Role::ListMarker => ns_string!("AXListMarker"), + Role::TreeItem => NSAccessibilityRowRole, + Role::ListBoxOption => NSAccessibilityStaticTextRole, + Role::MenuItem => NSAccessibilityMenuItemRole, + Role::MenuListOption => NSAccessibilityMenuItemRole, + Role::Paragraph => NSAccessibilityGroupRole, + Role::GenericContainer => NSAccessibilityUnknownRole, + Role::CheckBox => NSAccessibilityCheckBoxRole, + Role::RadioButton => NSAccessibilityRadioButtonRole, + Role::TextInput + | Role::SearchInput + | Role::EmailInput + | Role::NumberInput + | Role::PasswordInput + | Role::PhoneNumberInput + | Role::UrlInput => NSAccessibilityTextFieldRole, + Role::Button => { + if node.toggled().is_some() { + NSAccessibilityCheckBoxRole + } else { + NSAccessibilityButtonRole + } + } + Role::DefaultButton => NSAccessibilityButtonRole, + Role::Pane => NSAccessibilityUnknownRole, + Role::RowHeader => NSAccessibilityCellRole, + Role::ColumnHeader => NSAccessibilityCellRole, + Role::RowGroup => NSAccessibilityGroupRole, + Role::List => NSAccessibilityListRole, + Role::Table => NSAccessibilityTableRole, + Role::LayoutTableCell => NSAccessibilityGroupRole, + Role::LayoutTableRow => NSAccessibilityGroupRole, + Role::LayoutTable => NSAccessibilityGroupRole, + Role::Switch => NSAccessibilityCheckBoxRole, + Role::Menu => NSAccessibilityMenuRole, + Role::MultilineTextInput => NSAccessibilityTextAreaRole, + Role::DateInput | Role::DateTimeInput | Role::WeekInput | Role::MonthInput => { + ns_string!("AXDateField") + } + Role::TimeInput => ns_string!("AXTimeField"), + Role::Abbr => NSAccessibilityGroupRole, + Role::Alert => NSAccessibilityGroupRole, + Role::AlertDialog => NSAccessibilityWindowRole, + Role::Application => NSAccessibilityGroupRole, + Role::Article => NSAccessibilityGroupRole, + Role::Audio => NSAccessibilityGroupRole, + Role::Banner => NSAccessibilityGroupRole, + Role::Blockquote => NSAccessibilityGroupRole, + Role::Canvas => NSAccessibilityImageRole, + Role::Caption => NSAccessibilityGroupRole, + Role::Caret => NSAccessibilityUnknownRole, + Role::Code => NSAccessibilityGroupRole, + Role::ColorWell => NSAccessibilityColorWellRole, + Role::ComboBox => NSAccessibilityPopUpButtonRole, + Role::EditableComboBox => NSAccessibilityComboBoxRole, + Role::Complementary => NSAccessibilityGroupRole, + Role::Comment => NSAccessibilityGroupRole, + Role::ContentDeletion => NSAccessibilityGroupRole, + Role::ContentInsertion => NSAccessibilityGroupRole, + Role::ContentInfo => NSAccessibilityGroupRole, + Role::Definition => NSAccessibilityGroupRole, + Role::DescriptionList => NSAccessibilityListRole, + Role::Details => NSAccessibilityGroupRole, + Role::Dialog => NSAccessibilityWindowRole, + Role::DisclosureTriangle => NSAccessibilityButtonRole, + Role::Document => NSAccessibilityGroupRole, + Role::EmbeddedObject => NSAccessibilityGroupRole, + Role::Emphasis => NSAccessibilityGroupRole, + Role::Feed => NSAccessibilityUnknownRole, + Role::FigureCaption => NSAccessibilityGroupRole, + Role::Figure => NSAccessibilityGroupRole, + Role::Footer => NSAccessibilityGroupRole, + Role::Form => NSAccessibilityGroupRole, + Role::Grid => NSAccessibilityTableRole, + Role::Group => NSAccessibilityGroupRole, + Role::Header => NSAccessibilityGroupRole, + // Rune (vendor/accesskit_macos.patch): AppKit's heading role, which VoiceOver's + // rotor and VO-Command-H find, as WebKit and Chromium give it. The published + // "Heading" is no role VoiceOver knows. + Role::Heading => ns_string!("AXHeading"), + Role::Iframe => NSAccessibilityGroupRole, + Role::IframePresentational => NSAccessibilityGroupRole, + Role::ImeCandidate => NSAccessibilityUnknownRole, + Role::Keyboard => NSAccessibilityUnknownRole, + Role::Legend => NSAccessibilityGroupRole, + Role::LineBreak => NSAccessibilityGroupRole, + Role::ListBox => NSAccessibilityListRole, + Role::Log => NSAccessibilityGroupRole, + Role::Main => NSAccessibilityGroupRole, + Role::Mark => NSAccessibilityGroupRole, + Role::Marquee => NSAccessibilityGroupRole, + Role::Math => NSAccessibilityGroupRole, + Role::MenuBar => NSAccessibilityMenuBarRole, + Role::MenuItemCheckBox => NSAccessibilityMenuItemRole, + Role::MenuItemRadio => NSAccessibilityMenuItemRole, + Role::MenuListPopup => NSAccessibilityMenuRole, + Role::Meter => NSAccessibilityLevelIndicatorRole, + Role::Navigation => NSAccessibilityGroupRole, + Role::Note => NSAccessibilityGroupRole, + Role::PluginObject => NSAccessibilityGroupRole, + Role::ProgressIndicator => NSAccessibilityProgressIndicatorRole, + Role::RadioGroup => NSAccessibilityRadioGroupRole, + Role::Region => NSAccessibilityGroupRole, + Role::RootWebArea => ns_string!("AXWebArea"), + Role::Ruby => NSAccessibilityGroupRole, + Role::RubyAnnotation => NSAccessibilityUnknownRole, + Role::ScrollBar => NSAccessibilityScrollBarRole, + Role::ScrollView => NSAccessibilityUnknownRole, + Role::Search => NSAccessibilityGroupRole, + Role::Section => NSAccessibilityGroupRole, + Role::SectionFooter => NSAccessibilityGroupRole, + Role::SectionHeader => NSAccessibilityGroupRole, + Role::Slider => NSAccessibilitySliderRole, + Role::SpinButton => NSAccessibilityIncrementorRole, + Role::Splitter => NSAccessibilitySplitterRole, + Role::Status => NSAccessibilityGroupRole, + Role::Strong => NSAccessibilityGroupRole, + Role::Suggestion => NSAccessibilityGroupRole, + Role::SvgRoot => NSAccessibilityGroupRole, + Role::Tab => NSAccessibilityRadioButtonRole, + Role::TabList => NSAccessibilityTabGroupRole, + Role::TabPanel => NSAccessibilityGroupRole, + Role::Term => NSAccessibilityGroupRole, + Role::Time => NSAccessibilityGroupRole, + Role::Timer => NSAccessibilityGroupRole, + Role::TitleBar => NSAccessibilityStaticTextRole, + Role::Toolbar => NSAccessibilityToolbarRole, + Role::Tooltip => NSAccessibilityGroupRole, + Role::Tree => NSAccessibilityOutlineRole, + Role::TreeGrid => NSAccessibilityTableRole, + Role::Video => NSAccessibilityGroupRole, + Role::WebView => NSAccessibilityUnknownRole, + // Use the group role for Role::Window, since the NSWindow + // provides the top-level accessibility object for the window. + Role::Window => NSAccessibilityGroupRole, + Role::PdfActionableHighlight => NSAccessibilityButtonRole, + Role::PdfRoot => NSAccessibilityGroupRole, + Role::GraphicsDocument => NSAccessibilityGroupRole, + Role::GraphicsObject => NSAccessibilityGroupRole, + Role::GraphicsSymbol => NSAccessibilityImageRole, + Role::DocAbstract => NSAccessibilityGroupRole, + Role::DocAcknowledgements => NSAccessibilityGroupRole, + Role::DocAfterword => NSAccessibilityGroupRole, + Role::DocAppendix => NSAccessibilityGroupRole, + Role::DocBackLink => NSAccessibilityLinkRole, + Role::DocBiblioEntry => NSAccessibilityGroupRole, + Role::DocBibliography => NSAccessibilityGroupRole, + Role::DocBiblioRef => NSAccessibilityGroupRole, + Role::DocChapter => NSAccessibilityGroupRole, + Role::DocColophon => NSAccessibilityGroupRole, + Role::DocConclusion => NSAccessibilityGroupRole, + Role::DocCover => NSAccessibilityImageRole, + Role::DocCredit => NSAccessibilityGroupRole, + Role::DocCredits => NSAccessibilityGroupRole, + Role::DocDedication => NSAccessibilityGroupRole, + Role::DocEndnote => NSAccessibilityGroupRole, + Role::DocEndnotes => NSAccessibilityGroupRole, + Role::DocEpigraph => NSAccessibilityGroupRole, + Role::DocEpilogue => NSAccessibilityGroupRole, + Role::DocErrata => NSAccessibilityGroupRole, + Role::DocExample => NSAccessibilityGroupRole, + Role::DocFootnote => NSAccessibilityGroupRole, + Role::DocForeword => NSAccessibilityGroupRole, + Role::DocGlossary => NSAccessibilityGroupRole, + Role::DocGlossRef => NSAccessibilityLinkRole, + Role::DocIndex => NSAccessibilityGroupRole, + Role::DocIntroduction => NSAccessibilityGroupRole, + Role::DocNoteRef => NSAccessibilityLinkRole, + Role::DocNotice => NSAccessibilityGroupRole, + Role::DocPageBreak => NSAccessibilitySplitterRole, + Role::DocPageFooter => NSAccessibilityGroupRole, + Role::DocPageHeader => NSAccessibilityGroupRole, + Role::DocPageList => NSAccessibilityGroupRole, + Role::DocPart => NSAccessibilityGroupRole, + Role::DocPreface => NSAccessibilityGroupRole, + Role::DocPrologue => NSAccessibilityGroupRole, + Role::DocPullquote => NSAccessibilityGroupRole, + Role::DocQna => NSAccessibilityGroupRole, + Role::DocSubtitle => ns_string!("AXHeading"), + Role::DocTip => NSAccessibilityGroupRole, + Role::DocToc => NSAccessibilityGroupRole, + Role::ListGrid => NSAccessibilityUnknownRole, + Role::Terminal => NSAccessibilityTextAreaRole, + } + } +} + +fn label_is_exposed_in_value(role: Role) -> bool { + matches!( + role, + Role::Label + | Role::ListBoxOption + | Role::ListMarker + | Role::MenuListOption + | Role::TitleBar + ) +} + +fn ns_sub_role(node: &NodeRef) -> Option<&'static NSAccessibilitySubrole> { + let role = node.role(); + + unsafe { + match role { + Role::Alert => Some(ns_string!("AXApplicationAlert")), + Role::AlertDialog => Some(NSAccessibilityDialogSubrole), + Role::Application => Some(ns_string!("AXWebApplication")), + Role::Article => Some(ns_string!("AXDocumentArticle")), + Role::Banner => Some(ns_string!("AXLandmarkBanner")), + Role::Button if node.toggled().is_some() => Some(NSAccessibilityToggleSubrole), + Role::Code => Some(ns_string!("AXCodeStyleGroup")), + Role::Complementary => Some(ns_string!("AXLandmarkComplementary")), + Role::ContentDeletion => Some(ns_string!("AXDeleteStyleGroup")), + Role::ContentInsertion => Some(ns_string!("AXInsertStyleGroup")), + Role::ContentInfo => Some(ns_string!("AXLandmarkContentInfo")), + Role::Definition => Some(ns_string!("AXDefinition")), + Role::Dialog => Some(NSAccessibilityDialogSubrole), + Role::Document => Some(ns_string!("AXDocument")), + Role::Emphasis => Some(ns_string!("AXEmphasisStyleGroup")), + Role::Feed => Some(ns_string!("AXApplicationGroup")), + Role::Footer => Some(ns_string!("AXLandmarkContentInfo")), + Role::Form => Some(ns_string!("AXLandmarkForm")), + Role::GraphicsDocument => Some(ns_string!("AXDocument")), + Role::Group => Some(ns_string!("AXApplicationGroup")), + Role::Header => Some(ns_string!("AXLandmarkBanner")), + Role::Log => Some(ns_string!("AXApplicationLog")), + Role::Main => Some(ns_string!("AXLandmarkMain")), + Role::Marquee => Some(ns_string!("AXApplicationMarquee")), + Role::Math => Some(ns_string!("AXDocumentMath")), + Role::Meter => Some(ns_string!("AXMeter")), + Role::Navigation => Some(ns_string!("AXLandmarkNavigation")), + Role::Note => Some(ns_string!("AXDocumentNote")), + Role::PasswordInput => Some(NSAccessibilitySecureTextFieldSubrole), + Role::Region => Some(ns_string!("AXLandmarkRegion")), + Role::Search => Some(ns_string!("AXLandmarkSearch")), + Role::SearchInput => Some(NSAccessibilitySearchFieldSubrole), + Role::SectionFooter => Some(ns_string!("AXSectionFooter")), + Role::SectionHeader => Some(ns_string!("AXSectionHeader")), + Role::Status => Some(ns_string!("AXApplicationStatus")), + Role::Strong => Some(ns_string!("AXStrongStyleGroup")), + Role::Switch => Some(NSAccessibilitySwitchSubrole), + Role::Tab => Some(NSAccessibilityTabButtonSubrole), + Role::TabPanel => Some(ns_string!("AXTabPanel")), + Role::Term => Some(ns_string!("AXTerm")), + Role::Time => Some(ns_string!("AXTimeGroup")), + Role::Timer => Some(ns_string!("AXApplicationTimer")), + Role::TreeItem => Some(NSAccessibilityOutlineRowSubrole), + Role::Tooltip => Some(ns_string!("AXUserInterfaceTooltip")), + _ => None, + } + } +} + +pub(crate) fn can_be_focused(node: &NodeRef) -> bool { + filter(node) == FilterResult::Include && node.role() != Role::Window +} + +#[derive(PartialEq)] +pub(crate) enum Value { + Bool(bool), + Number(f64), + String(String), +} + +pub(crate) struct NodeWrapper<'a>(pub(crate) &'a NodeRef<'a>); + +impl NodeWrapper<'_> { + fn is_root(&self) -> bool { + self.0.is_root() + } + + pub(crate) fn title(&self) -> Option<String> { + if self.is_root() && self.0.role() == Role::Window { + // If the group element that we expose for the top-level window + // includes a title, VoiceOver behavior is broken. + return None; + } + if label_is_exposed_in_value(self.0.role()) { + return None; + } + self.0.label() + } + + pub(crate) fn label(&self) -> Option<String> { + if self.0.label_comes_from_value() { + self.0.value() + } else { + self.0.label() + } + } + + pub(crate) fn description(&self) -> Option<String> { + self.0.description() + } + + pub(crate) fn placeholder(&self) -> Option<&str> { + self.0.placeholder() + } + + pub(crate) fn value(&self) -> Option<Value> { + if let Some(toggled) = self.0.toggled() { + return Some(Value::Bool(toggled != Toggled::False)); + } + if self.0.role() == Role::Tab { + // On Mac, tabs are exposed as radio buttons, and are treated as checkable. + // Also, `Node::is_selected` is mapped to checked via `accessibilityValue`. + return Some(Value::Bool(self.0.is_selected().unwrap_or(false))); + } + if label_is_exposed_in_value(self.0.role()) { + if let Some(label) = self.0.label() { + return Some(Value::String(label)); + } + } + // Rune (vendor/accesskit_macos.patch): a heading's value is its level, as WebKit and + // Chromium give VoiceOver ("heading level 2"); Rune sets AccessKit's level one less + // (`a11y/node.rs`), and ARIA's default is 2. + if self.0.role() == Role::Heading { + return Some(Value::Number(self.0.level().map_or(2, |l| l + 1).clamp(1, 9) as f64)); + } + if let Some(value) = self.0.value() { + return Some(Value::String(value)); + } + if let Some(value) = self.0.numeric_value() { + return Some(Value::Number(value)); + } + None + } + + pub(crate) fn supports_text_ranges(&self) -> bool { + self.0.supports_text_ranges() + } + + pub(crate) fn raw_text_selection(&self) -> Option<&TextSelection> { + self.0.raw_text_selection() + } + + fn is_container_with_selectable_children(&self) -> bool { + self.0.is_container_with_selectable_children() && self.0.role() != Role::TabList + } + + pub(crate) fn is_item_like(&self) -> bool { + self.0.is_item_like() && self.0.role() != Role::Tab + } +} + +// derived from objc2 0.6 `AnyObject::downcast_ref` +// TODO: can be removed after updating objc2 to 0.6 which has `AnyObject::downcast_ref` +fn downcast_ref<T: ClassType>(obj: &NSObject) -> Option<&T> { + obj.is_kind_of::<T>() + .then(|| unsafe { &*(obj as *const NSObject).cast::<T>() }) +} + +pub(crate) struct PlatformNodeIvars { + context: Weak<Context>, + node_id: FullNodeId, +} + +declare_class!( + #[derive(Debug)] + pub(crate) struct PlatformNode; + + unsafe impl ClassType for PlatformNode { + #[inherits(NSObject)] + type Super = NSAccessibilityElement; + type Mutability = InteriorMutable; + const NAME: &'static str = "AccessKitNode"; + } + + impl DeclaredClass for PlatformNode { + type Ivars = PlatformNodeIvars; + } + + unsafe impl PlatformNode { + #[method_id(accessibilityParent)] + fn parent(&self) -> Option<Id<AnyObject>> { + self.resolve_with_context(|node, _, context| { + if let Some(parent) = node.filtered_parent(&filter) { + Some(Id::into_super(Id::into_super(Id::into_super(context.get_or_create_platform_node(parent.id()))))) + } else { + context + .view + .load() + .and_then(|view| unsafe { NSAccessibility::accessibilityParent(&*view) }) + } + }) + .flatten() + } + + #[method_id(accessibilityWindow)] + fn window(&self) -> Option<Id<AnyObject>> { + self.resolve_with_context(|_, _, context| { + context + .view + .load() + .and_then(|view| unsafe { NSAccessibility::accessibilityParent(&*view) }) + }) + .flatten() + } + + #[method_id(accessibilityTopLevelUIElement)] + fn top_level(&self) -> Option<Id<AnyObject>> { + self.resolve_with_context(|_, _, context| { + context + .view + .load() + .and_then(|view| unsafe { NSAccessibility::accessibilityParent(&*view) }) + }) + .flatten() + } + + #[method_id(accessibilityChildren)] + fn children(&self) -> Option<Id<NSArray<PlatformNode>>> { + self.children_internal() + } + + #[method_id(accessibilityChildrenInNavigationOrder)] + fn children_in_navigation_order(&self) -> Option<Id<NSArray<PlatformNode>>> { + // For now, we assume the children are in navigation order. + self.children_internal() + } + + #[method_id(accessibilitySelectedChildren)] + fn selected_children(&self) -> Option<Id<NSArray<PlatformNode>>> { + self.resolve_with_context(|node, _, context| { + let wrapper = NodeWrapper(node); + if !wrapper.is_container_with_selectable_children() { + return None; + } + let platform_nodes = node + .items(filter) + .filter(|item| item.is_selected() == Some(true)) + .map(|child| context.get_or_create_platform_node(child.id())) + .collect::<Vec<Id<PlatformNode>>>(); + Some(NSArray::from_vec(platform_nodes)) + }) + .flatten() + } + + #[method(accessibilityFrame)] + fn frame(&self) -> NSRect { + self.resolve_with_context(|node, _, context| { + let view = match context.view.load() { + Some(view) => view, + None => { + return NSRect::ZERO; + } + }; + + node.bounding_box().map_or_else( + || { + if node.is_root() { + unsafe { NSAccessibility::accessibilityFrame(&*view) } + } else { + NSRect::ZERO + } + }, + |rect| to_ns_rect(&view, rect), + ) + }) + .unwrap_or(NSRect::ZERO) + } + + #[method_id(accessibilityRole)] + fn role(&self) -> Id<NSAccessibilityRole> { + self.resolve(ns_role) + .unwrap_or(unsafe { NSAccessibilityUnknownRole }) + .copy() + } + + #[method_id(accessibilitySubrole)] + fn sub_role(&self) -> Option<Id<NSAccessibilitySubrole>> { + self.resolve(|node| ns_sub_role(node).map(|sub_role| sub_role.copy())) + .flatten() + } + + #[method_id(accessibilityRoleDescription)] + fn role_description(&self) -> Option<Id<NSString>> { + self.resolve(|node| { + if let Some(role_description) = node.role_description() { + Some(NSString::from_str(role_description)) + } else { + unsafe { msg_send_id![super(self), accessibilityRoleDescription] } + } + }) + .flatten() + } + + #[method_id(accessibilityIdentifier)] + fn identifier(&self) -> Option<Id<NSString>> { + self.resolve(|node| { + node.author_id().map(NSString::from_str) + }) + .flatten() + } + + #[method_id(accessibilityTitle)] + fn title(&self) -> Option<Id<NSString>> { + self.resolve(|node| { + let wrapper = NodeWrapper(node); + wrapper.title().map(|title| NSString::from_str(&title)) + }) + .flatten() + } + + #[method_id(accessibilityHelp)] + fn description(&self) -> Option<Id<NSString>> { + self.resolve(|node| { + let wrapper = NodeWrapper(node); + wrapper.description().map(|description| NSString::from_str(&description)) + }) + .flatten() + } + + #[method_id(accessibilityPlaceholderValue)] + fn placeholder(&self) -> Option<Id<NSString>> { + self.resolve(|node| { + let wrapper = NodeWrapper(node); + wrapper.placeholder().map(NSString::from_str) + }) + .flatten() + } + + #[method_id(accessibilityValue)] + fn value(&self) -> Option<Id<NSObject>> { + self.resolve(|node| { + let wrapper = NodeWrapper(node); + wrapper.value().map(|value| match value { + Value::Bool(value) => { + Id::into_super(Id::into_super(NSNumber::new_bool(value))) + } + Value::Number(value) => { + Id::into_super(Id::into_super(NSNumber::new_f64(value))) + } + Value::String(value) => { + Id::into_super(NSString::from_str(&value)) + } + }) + }) + .flatten() + } + + #[method(setAccessibilityValue:)] + fn set_value(&self, value: &NSObject) { + if let Some(string) = downcast_ref::<NSString>(value) { + self.resolve_with_context(|node, tree, context| { + if let Some((target_node, target_tree)) = tree.state().locate_node(node.id()) { + context.do_action(ActionRequest { + action: Action::SetValue, + target_tree, + target_node, + data: Some(ActionData::Value(string.to_string().into())), + }); + } + }); + } else if let Some(number) = downcast_ref::<NSNumber>(value) { + self.resolve_with_context(|node, tree, context| { + if let Some((target_node, target_tree)) = tree.state().locate_node(node.id()) { + context.do_action(ActionRequest { + action: Action::SetValue, + target_tree, + target_node, + data: Some(ActionData::NumericValue(number.doubleValue())), + }); + } + }); + } + } + + #[method_id(accessibilityMinValue)] + fn min_value(&self) -> Option<Id<NSNumber>> { + self.resolve(|node| { + node.min_numeric_value().map(NSNumber::new_f64) + }) + .flatten() + } + + #[method_id(accessibilityMaxValue)] + fn max_value(&self) -> Option<Id<NSNumber>> { + self.resolve(|node| { + node.max_numeric_value().map(NSNumber::new_f64) + }) + .flatten() + } + + #[method_id(accessibilityURL)] + fn url(&self) -> Option<Id<NSURL>> { + self.resolve(|node| { + node.supports_url().then(|| node.url()).flatten().and_then(|url| { + let ns_string = NSString::from_str(url); + unsafe { NSURL::URLWithString(&ns_string) } + }) + }) + .flatten() + } + + #[method(accessibilityOrientation)] + fn orientation(&self) -> NSAccessibilityOrientation { + self.resolve(|node| { + match node.orientation() { + Some(Orientation::Horizontal) => NSAccessibilityOrientation::Horizontal, + Some(Orientation::Vertical) => NSAccessibilityOrientation::Vertical, + None => NSAccessibilityOrientation::Unknown, + } + }) + .unwrap_or(NSAccessibilityOrientation::Unknown) + } + + #[method(isAccessibilityElement)] + fn is_accessibility_element(&self) -> bool { + self.resolve(|node| filter(node) == FilterResult::Include) + .unwrap_or(false) + } + + #[method(isAccessibilityFocused)] + fn is_focused(&self) -> bool { + self.resolve(|node| node.is_focused() && can_be_focused(node)) + .unwrap_or(false) + } + + #[method(isAccessibilityEnabled)] + fn is_enabled(&self) -> bool { + self.resolve(|node| !node.is_disabled()).unwrap_or(false) + } + + #[method(setAccessibilityFocused:)] + fn set_focused(&self, focused: bool) { + self.resolve_with_context(|node, tree, context| { + if focused { + if node.is_focusable(&filter) { + if let Some((target_node, target_tree)) = tree.state().locate_node(node.id()) { + context.do_action(ActionRequest { + action: Action::Focus, + target_tree, + target_node, + data: None, + }); + } + } + } else { + let root = tree.state().root(); + if root.is_focusable(&filter) { + if let Some((target_node, target_tree)) = tree.state().locate_node(root.id()) { + context.do_action(ActionRequest { + action: Action::Focus, + target_tree, + target_node, + data: None, + }); + } + } + } + }); + } + + #[method(accessibilityPerformPress)] + fn press(&self) -> bool { + self.resolve_with_context(|node, tree, context| { + let clickable = node.is_clickable(&filter); + if clickable { + if let Some((target_node, target_tree)) = tree.state().locate_node(node.id()) { + context.do_action(ActionRequest { + action: Action::Click, + target_tree, + target_node, + data: None, + }); + } + } + clickable + }) + .unwrap_or(false) + } + + #[method(accessibilityPerformIncrement)] + fn increment(&self) -> bool { + self.resolve_with_context(|node, tree, context| { + let supports_increment = node.supports_increment(&filter); + if supports_increment { + if let Some((target_node, target_tree)) = tree.state().locate_node(node.id()) { + context.do_action(ActionRequest { + action: Action::Increment, + target_tree, + target_node, + data: None, + }); + } + } + supports_increment + }) + .unwrap_or(false) + } + + #[method(accessibilityPerformDecrement)] + fn decrement(&self) -> bool { + self.resolve_with_context(|node, tree, context| { + let supports_decrement = node.supports_decrement(&filter); + if supports_decrement { + if let Some((target_node, target_tree)) = tree.state().locate_node(node.id()) { + context.do_action(ActionRequest { + action: Action::Decrement, + target_tree, + target_node, + data: None, + }); + } + } + supports_decrement + }) + .unwrap_or(false) + } + + #[method(accessibilityNotifiesWhenDestroyed)] + fn notifies_when_destroyed(&self) -> bool { + true + } + + #[method(accessibilityNumberOfCharacters)] + fn number_of_characters(&self) -> NSInteger { + self.resolve(|node| { + if let Some((text, _)) = long_text(node) { + let state = drawn_state(node, text); + return text.utf16_with(text.len(), state.content_key) as _; + } + if node.supports_text_ranges() { + node.document_range().end().to_global_utf16_index() as _ + } else { + 0 + } + }) + .unwrap_or(0) + } + + #[method_id(accessibilitySelectedText)] + fn selected_text(&self) -> Option<Id<NSString>> { + self.resolve(|node| { + if let Some((text, s)) = long_text(node) { + return Some(NSString::from_str(text.slice(s.anchor.character_index, s.focus.character_index))); + } + if node.supports_text_ranges() { + if let Some(range) = node.text_selection() { + let text = range.text(); + return Some(NSString::from_str(&text)); + } + } + None + }) + .flatten() + } + + #[method(accessibilitySelectedTextRange)] + fn selected_text_range(&self) -> NSRange { + self.resolve(|node| { + if let Some((text, s)) = long_text(node) { + let state = drawn_state(node, text); + return long_ns_range(text, s.anchor.character_index, s.focus.character_index, state.content_key); + } + if node.supports_text_ranges() { + if let Some(range) = node.text_selection() { + return to_ns_range(&range); + } + } + NSRange::new(0, 0) + }) + .unwrap_or_else(|| NSRange::new(0, 0)) + } + + #[method(accessibilityInsertionPointLineNumber)] + fn insertion_point_line_number(&self) -> NSInteger { + self.resolve(|node| { + if let Some((text, s)) = long_text(node) { + let state = drawn_state(node, text); + return text.line_of_in(text.clamp(s.focus.character_index), &state) as _; + } + if node.supports_text_ranges() { + if let Some(pos) = node.text_selection_focus() { + return pos.to_line_index() as _; + } + } + 0 + }) + .unwrap_or(0) + } + + #[method(accessibilityRangeForLine:)] + fn range_for_line(&self, line_index: NSInteger) -> NSRange { + self.resolve(|node| { + if let Some((text, _)) = long_text(node) { + let state = drawn_state(node, text); + let line = usize::try_from(line_index).ok().and_then(|n| text.line_in(n, &state)); + return line.map_or_else(|| NSRange::new(0, 0), |(a, b)| long_ns_range(text, a, b, state.content_key)); + } + if node.supports_text_ranges() && line_index >= 0 { + if let Some(range) = node.line_range_from_index(line_index as _) { + return to_ns_range(&range); + } + } + NSRange::new(0, 0) + }) + .unwrap_or_else(|| NSRange::new(0, 0)) + } + + #[method(accessibilityRangeForPosition:)] + fn range_for_position(&self, point: NSPoint) -> NSRange { + self.resolve_with_context(|node, _, context| { + let view = match context.view.load() { + Some(view) => view, + None => { + return NSRange::new(0, 0); + } + }; + + if let Some((text, s)) = long_text(node) { + let state = drawn_state(node, text); + let pt = from_ns_point(&view, node, point); + let at = byte_at_point(node, text, pt, true).unwrap_or_else(|| text.clamp(s.focus.character_index)); + return long_ns_range(text, at, text.next(at, Unit::Character), state.content_key); + } + if node.supports_text_ranges() { + let point = from_ns_point(&view, node, point); + let pos = node.text_position_at_point(point); + return to_ns_range_for_character(&pos); + } + NSRange::new(0, 0) + }) + .unwrap_or_else(|| NSRange::new(0, 0)) + } + + #[method_id(accessibilityStringForRange:)] + fn string_for_range(&self, range: NSRange) -> Option<Id<NSString>> { + self.resolve(|node| { + if let Some((text, _)) = long_text(node) { + let state = drawn_state(node, text); + let (a, b) = long_bytes(text, range, state.content_key); + return Some(NSString::from_str(text.slice(a, b))); + } + if node.supports_text_ranges() { + if let Some(range) = from_ns_range(node, range) { + let text = range.text(); + return Some(NSString::from_str(&text)); + } + } + None + }) + .flatten() + } + + #[method_id(accessibilityAttributedStringForRange:)] + fn attributed_string_for_range(&self, range: NSRange) -> Option<Id<NSAttributedString>> { + self.resolve(|node| { + if let Some((text, _)) = long_text(node) { + let state = drawn_state(node, text); + let (a, b) = long_bytes(text, range, state.content_key); + let plain = NSAttributedString::from_nsstring(&NSString::from_str(text.slice(a, b))); + return Some(plain); + } + if node.supports_text_ranges() { + if let Some(range) = from_ns_range(node, range) { + let mut result = NSMutableAttributedString::new(); + unsafe { result.beginEditing() }; + range.traverse_text::<_, ()>(|node, text| { + let ns_text = NSString::from_str(text); + let mut attrs = NSMutableDictionary::new(); + if let Some(color) = node.background_color() { + attrs.insert_id( + unsafe { NSAccessibilityBackgroundColorTextAttribute }, + to_color_attribute(color) + ); + } + if let Some(color) = node.foreground_color() { + attrs.insert_id( + unsafe { NSAccessibilityForegroundColorTextAttribute }, + to_color_attribute(color) + ); + } + let mut font_attrs = NSMutableDictionary::<NSAccessibilityFontAttributeKey, AnyObject>::new(); + if let Some(family) = node.font_family() { + font_attrs.insert_id( + unsafe { NSAccessibilityFontFamilyKey }, + Id::into_super(Id::into_super(NSString::from_str(family))) + ); + } + if let Some(size) = node.font_size() { + font_attrs.insert_id( + unsafe { NSAccessibilityFontSizeKey }, + Id::into_super(Id::into_super(Id::into_super(NSNumber::new_f32(size)))) + ); + } + if let Some(weight) = node.font_weight() { + if weight >= 700.0 { + font_attrs.insert_id( + ns_string!("AXFontBold"), + Id::into_super(Id::into_super(Id::into_super(NSNumber::new_bool(true)))) + ); + } + } + if node.is_italic() { + font_attrs.insert_id( + ns_string!("AXFontItalic"), + Id::into_super(Id::into_super(Id::into_super(NSNumber::new_bool(true)))) + ); + } + if !font_attrs.is_empty() { + attrs.insert_id( + unsafe { NSAccessibilityFontTextAttribute }, + Id::into_super(Id::into_super(Id::into_super(font_attrs))) + ); + } + if let Some(deco) = node.underline() { + attrs.insert_id( + unsafe { NSAccessibilityUnderlineTextAttribute }, + Id::into_super(Id::into_super(Id::into_super(NSNumber::new_bool(true)))) + ); + attrs.insert_id( + unsafe { NSAccessibilityUnderlineColorTextAttribute }, + to_color_attribute(deco.color) + ); + } + if let Some(deco) = node.strikethrough() { + attrs.insert_id( + unsafe { NSAccessibilityStrikethroughTextAttribute }, + Id::into_super(Id::into_super(Id::into_super(NSNumber::new_bool(true)))) + ); + attrs.insert_id( + unsafe { NSAccessibilityStrikethroughColorTextAttribute }, + to_color_attribute(deco.color) + ); + } + if let Some(language) = node.language() { + attrs.insert_id( + unsafe { NSAccessibilityLanguageTextAttribute }, + Id::into_super(Id::into_super(NSString::from_str(language))) + ); + } + if let Some(align) = node.text_align() { + let ns_align = match align { + TextAlign::Left => NSTextAlignment::Left, + TextAlign::Center => NSTextAlignment::Center, + TextAlign::Right => NSTextAlignment::Right, + TextAlign::Justify => NSTextAlignment::Justified, + }; + attrs.insert_id( + unsafe { NSAccessibilityTextAlignmentAttribute }, + Id::into_super(Id::into_super(Id::into_super(NSNumber::new_isize(ns_align.0)))) + ); + } + let part = unsafe { NSAttributedString::new_with_attributes(&ns_text, &attrs) }; + unsafe { result.appendAttributedString(&part) }; + None + }); + unsafe { result.endEditing() }; + return Some(Id::into_super(result)); + } + } + None + }) + .flatten() + } + + #[method(accessibilityFrameForRange:)] + fn frame_for_range(&self, range: NSRange) -> NSRect { + self.resolve_with_context(|node, _, context| { + let view = match context.view.load() { + Some(view) => view, + None => { + return NSRect::ZERO; + } + }; + + if let Some((text, _)) = long_text(node) { + let state = drawn_state(node, text); + let (a, b) = long_bytes(text, range, state.content_key); + let rects = bounding_boxes(node, text, a, b); + if let Some(rect) = rects.into_iter().reduce(|r1, r2| r1.union(r2)) { + return to_ns_rect(&view, rect); + } + return NSRect::ZERO; + } + if node.supports_text_ranges() { + if let Some(range) = from_ns_range(node, range) { + let rects = range.bounding_boxes(); + if let Some(rect) = + rects.into_iter().reduce(|rect1, rect2| rect1.union(rect2)) + { + return to_ns_rect(&view, rect); + } + } + } + NSRect::ZERO + }) + .unwrap_or(NSRect::ZERO) + } + + #[method(accessibilityLineForIndex:)] + fn line_for_index(&self, index: NSInteger) -> NSInteger { + self.resolve(|node| { + if let Some((text, _)) = long_text(node) { + let state = drawn_state(node, text); + return text.line_of_in(text.from_utf16_with(index.max(0) as _, state.content_key), &state) as _; + } + if node.supports_text_ranges() && index >= 0 { + if let Some(pos) = node.text_position_from_global_utf16_index(index as _) { + return pos.to_line_index() as _; + } + } + 0 + }) + .unwrap_or(0) + } + + #[method(accessibilityRangeForIndex:)] + fn range_for_index(&self, index: NSInteger) -> NSRange { + self.resolve(|node| { + if let Some((text, _)) = long_text(node) { + let state = drawn_state(node, text); + return long_char(text, index.max(0) as _, state.content_key); + } + if node.supports_text_ranges() && index >= 0 { + if let Some(pos) = node.text_position_from_global_utf16_index(index as _) { + return to_ns_range_for_character(&pos); + } + } + NSRange::new(0, 0) + }) + .unwrap_or_else(|| NSRange::new(0, 0)) + } + + #[method(accessibilityStyleRangeForIndex:)] + fn style_range_for_index(&self, index: NSInteger) -> NSRange { + self.resolve(|node| { + // A long field's text is one style. + if let Some((text, _)) = long_text(node) { + let state = drawn_state(node, text); + return long_ns_range(text, 0, text.len(), state.content_key); + } + if node.supports_text_ranges() && index >= 0 { + if let Some(pos) = node.text_position_from_global_utf16_index(index as _) { + let start = if pos.is_format_start() { + pos + } else { + pos.backward_to_format_start() + }; + let mut range = start.to_degenerate_range(); + range.set_end(pos.forward_to_format_end()); + return to_ns_range(&range); + } + } + NSRange::new(0, 0) + }) + .unwrap_or_else(|| NSRange::new(0, 0)) + } + + #[method(setAccessibilitySelectedTextRange:)] + fn set_selected_text_range(&self, range: NSRange) { + self.resolve_with_context(|node, tree, context| { + if let Some((text, _)) = long_text(node) { + let state = drawn_state(node, text); + let (a, b) = long_bytes(text, range, state.content_key); + let (target_node, target_tree) = node.locate(); + let at = |character_index| accesskit::TextPosition { node: target_node, character_index }; + context.do_action(ActionRequest { + action: Action::SetTextSelection, + target_tree, + target_node, + data: Some(ActionData::SetTextSelection(TextSelection { anchor: at(a), focus: at(b) })), + }); + return; + } + if node.supports_text_ranges() { + if let Some(range) = from_ns_range(node, range) { + if let Some((target_node, target_tree)) = tree.state().locate_node(node.id()) { + context.do_action(ActionRequest { + action: Action::SetTextSelection, + target_tree, + target_node, + data: Some(ActionData::SetTextSelection(range.to_text_selection())), + }); + } + } + } + }); + } + + #[method(isAccessibilityRequired)] + fn is_required(&self) -> bool { + self.resolve(|node| node.is_required()) + .unwrap_or(false) + } + + #[method(isAccessibilitySelected)] + fn is_selected(&self) -> bool { + self.resolve(|node| { + let wrapper = NodeWrapper(node); + wrapper.is_item_like() + && node.is_selectable() + && node.is_selected().unwrap_or(false) + }) + .unwrap_or(false) + } + + #[method(setAccessibilitySelected:)] + fn set_selected(&self, selected: bool) { + self.resolve_with_context(|node, tree, context| { + let wrapper = NodeWrapper(node); + if !node.is_clickable(&filter) + || !wrapper.is_item_like() + || !node.is_selectable() + { + return; + } + if node.is_selected() == Some(selected) { + return; + } + if let Some((target_node, target_tree)) = tree.state().locate_node(node.id()) { + context.do_action(ActionRequest { + action: Action::Click, + target_tree, + target_node, + data: None, + }); + } + }); + } + + #[method_id(accessibilityAttributeValue:)] + fn accessibility_attribute_value(&self, attr: &NSString) -> Option<Id<NSString>> { + self.resolve(|node| { + if attr == ns_string!("AXBrailleLabel") && node.has_braille_label() { + return Some(NSString::from_str(node.braille_label().unwrap())) + } else if attr == ns_string!("AXBrailleRoleDescription") && node.has_braille_role_description() { + return Some(NSString::from_str(node.braille_role_description().unwrap())) + } else if attr == ns_string!("AXDOMIdentifier") && node.has_html_id() { + return Some(NSString::from_str(node.html_id().unwrap())) + } + + None + }) + .flatten() + } + + #[method_id(accessibilityRows)] + fn rows(&self) -> Option<Id<NSArray<PlatformNode>>> { + self.resolve_with_context(|node, _, context| { + let wrapper = NodeWrapper(node); + if !wrapper.is_container_with_selectable_children() { + return None; + } + let platform_nodes = node + .items(filter) + .map(|child| context.get_or_create_platform_node(child.id())) + .collect::<Vec<Id<PlatformNode>>>(); + Some(NSArray::from_vec(platform_nodes)) + }) + .flatten() + } + + #[method_id(accessibilitySelectedRows)] + fn selected_rows(&self) -> Option<Id<NSArray<PlatformNode>>> { + self.resolve_with_context(|node, _, context| { + let wrapper = NodeWrapper(node); + if !wrapper.is_container_with_selectable_children() { + return None; + } + let platform_nodes = node + .items(filter) + .filter(|item| item.is_selected() == Some(true)) + .map(|child| context.get_or_create_platform_node(child.id())) + .collect::<Vec<Id<PlatformNode>>>(); + Some(NSArray::from_vec(platform_nodes)) + }) + .flatten() + } + + #[method(accessibilityPerformPick)] + fn pick(&self) -> bool { + self.resolve_with_context(|node, tree, context| { + let wrapper = NodeWrapper(node); + let selectable = node.is_clickable(&filter) + && wrapper.is_item_like() + && node.is_selectable(); + if selectable { + if let Some((target_node, target_tree)) = tree.state().locate_node(node.id()) { + context.do_action(ActionRequest { + action: Action::Click, + target_tree, + target_node, + data: None, + }); + } + } + selectable + }) + .unwrap_or(false) + } + + #[method_id(accessibilityLinkedUIElements)] + fn linked_ui_elements(&self) -> Option<Id<NSArray<PlatformNode>>> { + self.resolve_with_context(|node, _, context| { + let platform_nodes: Vec<Id<PlatformNode>> = node + .controls() + .filter(|controlled| filter(controlled) == FilterResult::Include) + .map(|controlled| context.get_or_create_platform_node(controlled.id())) + .collect(); + if platform_nodes.is_empty() { + None + } else { + Some(NSArray::from_vec(platform_nodes)) + } + }) + .flatten() + } + + #[method_id(accessibilityTabs)] + fn tabs(&self) -> Option<Id<NSArray<PlatformNode>>> { + self.resolve_with_context(|node, _, context| { + if node.role() != Role::TabList { + return None; + } + let platform_nodes = node + .filtered_children(filter) + .filter(|child| child.role() == Role::Tab) + .map(|tab| context.get_or_create_platform_node(tab.id())) + .collect::<Vec<Id<PlatformNode>>>(); + Some(NSArray::from_vec(platform_nodes)) + }) + .flatten() + } + + #[method(isAccessibilityModal)] + fn is_modal(&self) -> bool { + self.resolve(|node| node.is_modal()) + .unwrap_or(false) + } + + // We discovered through experimentation that when mixing the newer + // NSAccessibility protocols with the older informal protocol, + // the platform uses both protocols to discover which actions are + // available and then perform actions. That means our implementation + // of the legacy methods below only needs to cover actions not already + // handled by the newer methods. + + #[method_id(accessibilityActionNames)] + fn action_names(&self) -> Id<NSArray<NSString>> { + let mut result = vec![]; + self.resolve(|node| { + if node.supports_action(Action::ScrollIntoView, &filter) { + result.push(ns_string!(SCROLL_TO_VISIBLE_ACTION).copy()); + } + }); + NSArray::from_vec(result) + } + + #[method(accessibilityPerformAction:)] + fn perform_action(&self, action: &NSString) { + self.resolve_with_context(|node, tree, context| { + if action == ns_string!(SCROLL_TO_VISIBLE_ACTION) { + if let Some((target_node, target_tree)) = tree.state().locate_node(node.id()) { + context.do_action(ActionRequest { + action: Action::ScrollIntoView, + target_tree, + target_node, + data: None, + }); + } + } + }); + } + + #[method(isAccessibilitySelectorAllowed:)] + fn is_selector_allowed(&self, selector: Sel) -> bool { + self.resolve(|node| { + if selector == sel!(setAccessibilityFocused:) { + return node.is_focusable(&filter); + } + if selector == sel!(accessibilityPerformPress) { + return node.is_clickable(&filter); + } + if selector == sel!(accessibilityPerformIncrement) { + return node.supports_increment(&filter); + } + if selector == sel!(accessibilityPerformDecrement) { + return node.supports_decrement(&filter); + } + if selector == sel!(accessibilityNumberOfCharacters) + || selector == sel!(accessibilitySelectedText) + || selector == sel!(accessibilitySelectedTextRange) + || selector == sel!(accessibilityInsertionPointLineNumber) + || selector == sel!(accessibilityRangeForLine:) + || selector == sel!(accessibilityRangeForPosition:) + || selector == sel!(accessibilityStringForRange:) + || selector == sel!(accessibilityAttributedStringForRange:) + || selector == sel!(accessibilityFrameForRange:) + || selector == sel!(accessibilityLineForIndex:) + || selector == sel!(accessibilityRangeForIndex:) + || selector == sel!(accessibilityStyleRangeForIndex:) + || selector == sel!(setAccessibilitySelectedTextRange:) + { + return node.supports_text_ranges() || long_text(node).is_some(); + } + if selector == sel!(setAccessibilityValue:) { + return (node.supports_text_ranges() && !node.is_read_only()) || node.supports_action(Action::SetValue, &filter); + } + if selector == sel!(isAccessibilitySelected) { + let wrapper = NodeWrapper(node); + return wrapper.is_item_like(); + } + if selector == sel!(accessibilityRows) + || selector == sel!(accessibilitySelectedRows) + { + let wrapper = NodeWrapper(node); + return wrapper.is_container_with_selectable_children() + } + if selector == sel!(setAccessibilitySelected:) + || selector == sel!(accessibilityPerformPick) + { + let wrapper = NodeWrapper(node); + return node.is_clickable(&filter) + && wrapper.is_item_like() + && node.is_selectable(); + } + if selector == sel!(accessibilityTabs) { + return node.role() == Role::TabList; + } + if selector == sel!(isAccessibilityModal) { + return node.is_dialog(); + } + if selector == sel!(accessibilityAttributeValue:) { + return node.has_braille_label() + || node.has_braille_role_description() + || node.has_html_id() + } + if selector == sel!(accessibilityURL) { + return node.supports_url(); + } + selector == sel!(accessibilityParent) + || selector == sel!(accessibilityChildren) + || selector == sel!(accessibilityChildrenInNavigationOrder) + || selector == sel!(accessibilitySelectedChildren) + || selector == sel!(accessibilityFrame) + || selector == sel!(accessibilityRole) + || selector == sel!(accessibilitySubrole) + || selector == sel!(isAccessibilityEnabled) + || selector == sel!(accessibilityWindow) + || selector == sel!(accessibilityTopLevelUIElement) + || selector == sel!(accessibilityLinkedUIElements) + || selector == sel!(accessibilityRoleDescription) + || selector == sel!(accessibilityIdentifier) + || selector == sel!(accessibilityTitle) + || selector == sel!(accessibilityHelp) + || selector == sel!(accessibilityPlaceholderValue) + || selector == sel!(accessibilityValue) + || selector == sel!(accessibilityMinValue) + || selector == sel!(accessibilityMaxValue) + || selector == sel!(isAccessibilityRequired) + || selector == sel!(accessibilityOrientation) + || selector == sel!(isAccessibilityElement) + || selector == sel!(isAccessibilityFocused) + || selector == sel!(accessibilityNotifiesWhenDestroyed) + || selector == sel!(isAccessibilitySelectorAllowed:) + || selector == sel!(accessibilityActionNames) + || selector == sel!(accessibilityPerformAction:) + }) + .unwrap_or(false) + } + } +); + +impl PlatformNode { + pub(crate) fn new(context: Weak<Context>, node_id: FullNodeId) -> Id<Self> { + let this = Self::alloc().set_ivars(PlatformNodeIvars { context, node_id }); + + unsafe { msg_send_id![super(this), init] } + } + + fn resolve_with_context<F, T>(&self, f: F) -> Option<T> + where + F: FnOnce(&NodeRef, &Tree, &Rc<Context>) -> T, + { + std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + let context = self.ivars().context.upgrade()?; + let tree = context.tree.borrow(); + let state = tree.state(); + let node = state.node_by_id(self.ivars().node_id)?; + Some(f(&node, &tree, &context)) + })) + .ok() + .flatten() + } + + fn resolve<F, T>(&self, f: F) -> Option<T> + where + F: FnOnce(&NodeRef) -> T, + { + self.resolve_with_context(|node, _, _| f(node)) + } + + fn children_internal(&self) -> Option<Id<NSArray<PlatformNode>>> { + self.resolve_with_context(|node, _, context| { + let platform_nodes = node + .filtered_children(filter) + .map(|child| context.get_or_create_platform_node(child.id())) + .collect::<Vec<Id<PlatformNode>>>(); + NSArray::from_vec(platform_nodes) + }) + } +} diff --git a/app/vendor/rune/vendor/accesskit_macos/src/patch.rs b/app/vendor/rune/vendor/accesskit_macos/src/patch.rs new file mode 100644 index 0000000..1b4732e --- /dev/null +++ b/app/vendor/rune/vendor/accesskit_macos/src/patch.rs @@ -0,0 +1,93 @@ +// Copyright 2023 The AccessKit Authors. All rights reserved. +// Licensed under the Apache License, Version 2.0 (found in +// the LICENSE-APACHE file) or the MIT license (found in +// the LICENSE-MIT file), at your option. + +use objc2::{ + Message, + encode::{Encode, EncodeArguments, EncodeReturn, Encoding}, + ffi::class_addMethod, + msg_send, + runtime::{AnyClass, AnyObject, Bool, MethodImplementation, Sel}, + sel, +}; +use objc2_app_kit::NSWindow; +use std::{ffi::CString, ptr::null_mut}; + +extern "C" fn focus_forwarder(this: &NSWindow, _cmd: Sel) -> *mut AnyObject { + unsafe { + this.contentView().map_or_else(null_mut, |view| { + msg_send![&*view, accessibilityFocusedUIElement] + }) + } +} + +/// Modifies the specified class, which must be a subclass of `NSWindow`, +/// to include an `accessibilityFocusedUIElement` method that calls +/// the corresponding method on the window's content view. This is needed +/// for windowing libraries such as SDL that place the keyboard focus +/// directly on the window rather than the content view. +/// +/// # Safety +/// +/// This function is declared unsafe because the caller must ensure that the +/// code for this crate is never unloaded from the application process, +/// since it's not possible to reverse this operation. It's safest +/// if this crate is statically linked into the application's main executable. +/// Also, this function assumes that the specified class is a subclass +/// of `NSWindow`. +pub unsafe fn add_focus_forwarder_to_window_class(class_name: &str) { + let class = AnyClass::get(class_name).unwrap(); + unsafe { + add_method( + class as *const AnyClass as *mut AnyClass, + sel!(accessibilityFocusedUIElement), + focus_forwarder as unsafe extern "C" fn(_, _) -> _, + ) + }; +} + +// The rest of this file is copied from objc2 with only minor adaptations, +// to allow a method to be added to an existing class. + +unsafe fn add_method<T, F>(class: *mut AnyClass, sel: Sel, func: F) +where + T: Message + ?Sized, + F: MethodImplementation<Callee = T>, +{ + let encs = F::Arguments::ENCODINGS; + let sel_args = count_args(sel); + assert_eq!( + sel_args, + encs.len(), + "Selector {:?} accepts {} arguments, but function accepts {}", + sel, + sel_args, + encs.len(), + ); + + let types = method_type_encoding(&F::Return::ENCODING_RETURN, encs); + let success = Bool::from_raw(unsafe { + class_addMethod( + class as *mut _, + sel.as_ptr(), + Some(func.__imp()), + types.as_ptr(), + ) + }); + assert!(success.as_bool(), "Failed to add method {sel:?}"); +} + +fn count_args(sel: Sel) -> usize { + sel.name().chars().filter(|&c| c == ':').count() +} + +fn method_type_encoding(ret: &Encoding, args: &[Encoding]) -> CString { + // First two arguments are always self and the selector + let mut types = format!("{}{}{}", ret, <*mut AnyObject>::ENCODING, Sel::ENCODING); + for enc in args { + use core::fmt::Write; + write!(&mut types, "{enc}").unwrap(); + } + CString::new(types).unwrap() +} diff --git a/app/vendor/rune/vendor/accesskit_macos/src/subclass.rs b/app/vendor/rune/vendor/accesskit_macos/src/subclass.rs new file mode 100644 index 0000000..6e10394 --- /dev/null +++ b/app/vendor/rune/vendor/accesskit_macos/src/subclass.rs @@ -0,0 +1,360 @@ +// Copyright 2022 The AccessKit Authors. All rights reserved. +// Licensed under the Apache License, Version 2.0 (found in +// the LICENSE-APACHE file) or the MIT license (found in +// the LICENSE-MIT file), at your option. + +use accesskit::{ActionHandler, ActivationHandler, TreeUpdate}; +use objc2::{ + ClassType, DeclaredClass, + declare::ClassBuilder, + declare_class, + ffi::{ + OBJC_ASSOCIATION_RETAIN_NONATOMIC, objc_getAssociatedObject, objc_setAssociatedObject, + object_setClass, + }, + msg_send, msg_send_id, + mutability::InteriorMutable, + rc::Id, + runtime::{AnyClass, AnyObject, Sel}, + sel, +}; +use objc2_app_kit::{NSView, NSWindow}; +use objc2_foundation::{MainThreadMarker, NSArray, NSObject, NSPoint}; +use std::{cell::RefCell, ffi::c_void, sync::Mutex}; + +use crate::{Adapter, event::QueuedEvents}; + +static SUBCLASSES: Mutex<Vec<(&'static AnyClass, &'static AnyClass)>> = Mutex::new(Vec::new()); + +static ASSOCIATED_OBJECT_KEY: u8 = 0; + +fn associated_object_key() -> *const c_void { + (&ASSOCIATED_OBJECT_KEY as *const u8).cast() +} + +struct AssociatedObjectState { + adapter: Adapter, + activation_handler: Box<dyn ActivationHandler>, +} + +struct AssociatedObjectIvars { + state: RefCell<AssociatedObjectState>, + prev_class: &'static AnyClass, +} + +declare_class!( + struct AssociatedObject; + + unsafe impl ClassType for AssociatedObject { + type Super = NSObject; + type Mutability = InteriorMutable; + const NAME: &'static str = "AccessKitSubclassAssociatedObject"; + } + + impl DeclaredClass for AssociatedObject { + type Ivars = AssociatedObjectIvars; + } +); + +impl AssociatedObject { + fn new( + adapter: Adapter, + activation_handler: impl 'static + ActivationHandler, + prev_class: &'static AnyClass, + ) -> Id<Self> { + let state = RefCell::new(AssociatedObjectState { + adapter, + activation_handler: Box::new(activation_handler), + }); + let this = Self::alloc().set_ivars(AssociatedObjectIvars { state, prev_class }); + + unsafe { msg_send_id![super(this), init] } + } +} + +fn associated_object(view: &NSView) -> Option<&AssociatedObject> { + unsafe { + (objc_getAssociatedObject(view as *const NSView as *const _, associated_object_key()) + as *const AssociatedObject) + .as_ref() + } +} + +// Rune (vendor/accesskit_macos.patch): AppKit can call the accessibility methods below from a +// background thread, while this process asks the system about itself (a hit test, or the focused +// application), and the main thread may hold the adapter's `RefCell` borrow at that moment. +// Borrowing off the main thread would race, or panic inside `extern "C"` and abort, so answer as +// though the view had no adapter and let the superclass's own answer through. +fn associated_object_on_main_thread(view: &NSView) -> Option<&AssociatedObject> { + MainThreadMarker::new()?; + associated_object(view) +} + +// Unlike `[view class]`, this sees the subclass that key-value observing +// hides by overriding `class`. +fn runtime_class(view: &NSView) -> &'static AnyClass { + let object: &AnyObject = view; + object.class() +} + +// Key-value observing may have subclassed our subclass in turn. +fn installed_subclass(view: &NSView) -> Option<(&'static AnyClass, &'static AnyClass)> { + let subclasses = SUBCLASSES.lock().unwrap(); + let mut class: Option<&AnyClass> = Some(runtime_class(view)); + while let Some(current) = class { + if let Some(entry) = subclasses + .iter() + .find(|entry| std::ptr::eq(entry.1, current)) + { + return Some(*entry); + } + class = current.superclass(); + } + None +} + +fn prev_class(view: &NSView) -> &'static AnyClass { + installed_subclass(view).unwrap().0 +} + +// Some view classes, like the one in winit 0.27, assume that they are the +// lowest subclass, and call [self superclass] to get their superclass. +// Give them the answer they need. +unsafe extern "C" fn superclass(this: &NSView, _cmd: Sel) -> Option<&AnyClass> { + let prev_class = match associated_object(this) { + Some(associated) => associated.ivars().prev_class, + None => prev_class(this), + }; + prev_class.superclass() +} + +unsafe extern "C" fn children(this: &NSView, _cmd: Sel) -> *mut NSArray<NSObject> { + let Some(associated) = associated_object_on_main_thread(this) else { + return unsafe { msg_send![super(this, prev_class(this)), accessibilityChildren] }; + }; + let mut state = associated.ivars().state.borrow_mut(); + let state_mut = &mut *state; + state_mut + .adapter + .view_children(&mut *state_mut.activation_handler) +} + +unsafe extern "C" fn focus(this: &NSView, _cmd: Sel) -> *mut NSObject { + let Some(associated) = associated_object_on_main_thread(this) else { + return unsafe { msg_send![super(this, prev_class(this)), accessibilityFocusedUIElement] }; + }; + let mut state = associated.ivars().state.borrow_mut(); + let state_mut = &mut *state; + state_mut.adapter.focus(&mut *state_mut.activation_handler) +} + +unsafe extern "C" fn hit_test(this: &NSView, _cmd: Sel, point: NSPoint) -> *mut NSObject { + let Some(associated) = associated_object_on_main_thread(this) else { + return unsafe { msg_send![super(this, prev_class(this)), accessibilityHitTest: point] }; + }; + let mut state = associated.ivars().state.borrow_mut(); + let state_mut = &mut *state; + state_mut + .adapter + .hit_test(point, &mut *state_mut.activation_handler) +} + +fn subclass_of(prev_class: &'static AnyClass) -> &'static AnyClass { + let mut subclasses = SUBCLASSES.lock().unwrap(); + match subclasses + .iter() + .find(|entry| std::ptr::eq(entry.0, prev_class)) + { + Some(entry) => entry.1, + None => { + let name = format!("AccessKitSubclassOf{}", prev_class.name()); + let mut builder = ClassBuilder::new(&name, prev_class).unwrap(); + unsafe { + builder.add_method( + sel!(superclass), + superclass as unsafe extern "C" fn(_, _) -> _, + ); + builder.add_method( + sel!(accessibilityChildren), + children as unsafe extern "C" fn(_, _) -> _, + ); + builder.add_method( + sel!(accessibilityFocusedUIElement), + focus as unsafe extern "C" fn(_, _) -> _, + ); + builder.add_method( + sel!(accessibilityHitTest:), + hit_test as unsafe extern "C" fn(_, _, _) -> _, + ); + } + let class = builder.register(); + subclasses.push((prev_class, class)); + class + } + } +} + +/// Uses dynamic Objective-C subclassing to implement the `NSView` +/// accessibility methods when normal subclassing isn't an option. +pub struct SubclassingAdapter { + view: Id<NSView>, + associated: Id<AssociatedObject>, +} + +impl SubclassingAdapter { + /// Create an adapter that dynamically subclasses the specified view. + /// This must be done before the view is shown or focused for + /// the first time, and before anything observes the view with + /// key-value observing. + /// + /// The action handler will always be called on the main thread. + /// + /// # Safety + /// + /// `view` must be a valid, unreleased pointer to an `NSView`. + pub unsafe fn new( + view: *mut c_void, + activation_handler: impl 'static + ActivationHandler, + action_handler: impl 'static + ActionHandler, + ) -> Self { + let view = view as *mut NSView; + let retained_view = unsafe { Id::retain(view) }.unwrap(); + Self::new_internal(retained_view, activation_handler, action_handler) + } + + fn new_internal( + retained_view: Id<NSView>, + activation_handler: impl 'static + ActivationHandler, + action_handler: impl 'static + ActionHandler, + ) -> Self { + let view = Id::as_ptr(&retained_view) as *mut NSView; + if !unsafe { + objc_getAssociatedObject(view as *const NSView as *const _, associated_object_key()) + } + .is_null() + { + panic!("subclassing adapter already instantiated on view {view:?}"); + } + // A previous adapter may have left its subclass on the view, + // if key-value observing had subclassed it in turn. + let installed = installed_subclass(unsafe { &*view }); + if installed.is_none() { + // Key-value observing crashes when it adds or removes an observer + // while our subclass sits on top of its own. + let reported_class: &AnyClass = unsafe { msg_send![view, class] }; + let actual_class = runtime_class(unsafe { &*view }); + if !std::ptr::eq(reported_class, actual_class) { + panic!( + "view {view:?} is already observed with key-value observing (its class {} reports itself as {}); create the subclassing adapter before anything observes the view", + actual_class.name(), + reported_class.name() + ); + } + } + let adapter = unsafe { Adapter::new(view as *mut c_void, false, action_handler) }; + let (prev_class, subclass) = installed.unwrap_or_else(|| { + let prev_class = runtime_class(unsafe { &*view }); + (prev_class, subclass_of(prev_class)) + }); + let associated = AssociatedObject::new(adapter, activation_handler, prev_class); + unsafe { + objc_setAssociatedObject( + view as *mut _, + associated_object_key(), + Id::as_ptr(&associated) as *mut _, + OBJC_ASSOCIATION_RETAIN_NONATOMIC, + ) + }; + // SAFETY: Changing the view's class is only safe because + // the subclass doesn't add any instance variables; + // it uses an associated object instead. + if installed.is_none() { + unsafe { object_setClass(view as *mut _, (subclass as *const AnyClass).cast()) }; + } + Self { + view: retained_view, + associated, + } + } + + /// Create an adapter that dynamically subclasses the content view + /// of the specified window. + /// + /// The action handler will always be called on the main thread. + /// + /// # Safety + /// + /// `window` must be a valid, unreleased pointer to an `NSWindow`. + /// + /// # Panics + /// + /// This function panics if the specified window doesn't currently have + /// a content view. + pub unsafe fn for_window( + window: *mut c_void, + activation_handler: impl 'static + ActivationHandler, + action_handler: impl 'static + ActionHandler, + ) -> Self { + let window = unsafe { &*(window as *const NSWindow) }; + let retained_view = window.contentView().unwrap(); + Self::new_internal(retained_view, activation_handler, action_handler) + } + + /// If and only if the tree has been initialized, call the provided function + /// and apply the resulting update. Note: If the caller's implementation of + /// [`ActivationHandler::request_initial_tree`] initially returned `None`, + /// the [`TreeUpdate`] returned by the provided function must contain + /// a full tree. + /// + /// If a [`QueuedEvents`] instance is returned, the caller must call + /// [`QueuedEvents::raise`] on it. + pub fn update_if_active( + &mut self, + update_factory: impl FnOnce() -> TreeUpdate, + ) -> Option<QueuedEvents> { + let mut state = self.associated.ivars().state.borrow_mut(); + state.adapter.update_if_active(update_factory) + } + + /// Update the tree state based on whether the window is focused. + /// + /// If a [`QueuedEvents`] instance is returned, the caller must call + /// [`QueuedEvents::raise`] on it. + pub fn update_view_focus_state(&mut self, is_focused: bool) -> Option<QueuedEvents> { + let mut state = self.associated.ivars().state.borrow_mut(); + state.adapter.update_view_focus_state(is_focused) + } +} + +impl Drop for SubclassingAdapter { + fn drop(&mut self) { + let prev_class = self.associated.ivars().prev_class; + let view = Id::as_ptr(&self.view) as *mut NSView; + unsafe { + objc_setAssociatedObject( + view as *mut _, + associated_object_key(), + std::ptr::null_mut(), + OBJC_ASSOCIATION_RETAIN_NONATOMIC, + ) + }; + // Key-value observing may have subclassed our subclass in turn + // (AppKit observes the first responder), and resetting the class + // would then break those observers. Our subclass is harmless + // without the associated object. + let view = unsafe { &*view }; + let is_our_subclass = SUBCLASSES + .lock() + .unwrap() + .iter() + .any(|entry| std::ptr::eq(entry.1, runtime_class(view))); + if is_our_subclass { + unsafe { + object_setClass( + view as *const _ as *mut _, + (prev_class as *const AnyClass).cast(), + ) + }; + } + } +} diff --git a/app/vendor/rune/vendor/accesskit_macos/src/util.rs b/app/vendor/rune/vendor/accesskit_macos/src/util.rs new file mode 100644 index 0000000..8197676 --- /dev/null +++ b/app/vendor/rune/vendor/accesskit_macos/src/util.rs @@ -0,0 +1,112 @@ +// Copyright 2022 The AccessKit Authors. All rights reserved. +// Licensed under the Apache License, Version 2.0 (found in +// the LICENSE-APACHE file) or the MIT license (found in +// the LICENSE-MIT file), at your option. + +use accesskit::{Color, Point, Rect}; +use accesskit_consumer::{NodeRef, TextPosition, TextRange}; +use objc2::encode::{Encoding, RefEncode}; +use objc2::{msg_send, rc::Id, runtime::AnyObject}; +use objc2_app_kit::*; +use objc2_foundation::{NSPoint, NSRange, NSRect, NSSize}; + +pub(crate) fn from_ns_range<'a>(node: &'a NodeRef<'a>, ns_range: NSRange) -> Option<TextRange<'a>> { + let pos = node.text_position_from_global_utf16_index(ns_range.location)?; + let mut range = pos.to_degenerate_range(); + if ns_range.length > 0 { + let end = + node.text_position_from_global_utf16_index(ns_range.location + ns_range.length)?; + range.set_end(end); + } + Some(range) +} + +pub(crate) fn to_ns_range(range: &TextRange) -> NSRange { + let start = range.start().to_global_utf16_index(); + let end = range.end().to_global_utf16_index(); + NSRange::from(start..end) +} + +pub(crate) fn to_ns_range_for_character(pos: &TextPosition) -> NSRange { + let mut range = pos.to_degenerate_range(); + if !pos.is_document_end() { + range.set_end(pos.forward_to_character_end()); + } + to_ns_range(&range) +} + +pub(crate) fn from_ns_point(view: &NSView, node: &NodeRef, point: NSPoint) -> Point { + let Some(window) = view.window() else { + return Point::ZERO; + }; + let point = window.convertPointFromScreen(point); + let point = view.convertPoint_fromView(point, None); + // AccessKit coordinates are in physical (DPI-dependent) pixels, but + // macOS provides logical (DPI-independent) coordinates here. + let factor = window.backingScaleFactor(); + let point = Point::new( + point.x * factor, + if view.isFlipped() { + point.y * factor + } else { + let view_bounds = view.bounds(); + (view_bounds.size.height - point.y) * factor + }, + ); + node.transform().inverse() * point +} + +pub(crate) fn to_ns_rect(view: &NSView, rect: Rect) -> NSRect { + let Some(window) = view.window() else { + return NSRect::ZERO; + }; + // AccessKit coordinates are in physical (DPI-dependent) + // pixels, but macOS expects logical (DPI-independent) + // coordinates here. + let factor = window.backingScaleFactor(); + let rect = NSRect { + origin: NSPoint { + x: rect.x0 / factor, + y: if view.isFlipped() { + rect.y0 / factor + } else { + let view_bounds = view.bounds(); + view_bounds.size.height - rect.y1 / factor + }, + }, + size: NSSize { + width: rect.width() / factor, + height: rect.height() / factor, + }, + }; + let rect = view.convertRect_toView(rect, None); + let window = view.window().unwrap(); + window.convertRectToScreen(rect) +} + +fn color_channel_to_f64(channel: u8) -> f64 { + (channel as f64) / 255.0 +} + +// TODO: can be removed after updating objc2 to 0.6 which has proper `CGColor` support +#[repr(C)] +struct CGColor { + _private: [u8; 0], +} + +unsafe impl RefEncode for CGColor { + const ENCODING_REF: Encoding = Encoding::Pointer(&Encoding::Struct("CGColor", &[])); +} + +pub(crate) fn to_color_attribute(color: Color) -> Id<AnyObject> { + let ns_color = unsafe { + NSColor::colorWithSRGBRed_green_blue_alpha( + color_channel_to_f64(color.red), + color_channel_to_f64(color.green), + color_channel_to_f64(color.blue), + color_channel_to_f64(color.alpha), + ) + }; + let cg_color: *const CGColor = unsafe { msg_send![&ns_color, CGColor] }; + unsafe { Id::retain(cg_color as *mut AnyObject).unwrap() } +} diff --git a/app/vendor/rune/vendor/accesskit_windows.patch b/app/vendor/rune/vendor/accesskit_windows.patch new file mode 100644 index 0000000..0b29a00 --- /dev/null +++ b/app/vendor/rune/vendor/accesskit_windows.patch @@ -0,0 +1,1785 @@ +diff --git a/src/adapter.rs b/src/adapter.rs +index 38044d3..5e28b6c 100644 +--- a/src/adapter.rs ++++ b/src/adapter.rs +@@ -18,6 +18,7 @@ use windows::Win32::{ + use crate::{ + context::{ActionHandlerNoMut, ActionHandlerWrapper, Context}, + filters::filter, ++ long_text::long_text, + node::{NodeWrapper, PlatformNode}, + util::{QueuedEvent, StringBuffer}, + window_handle::WindowHandle, +@@ -52,7 +53,7 @@ impl<'a> AdapterChangeHandler<'a> { + + impl AdapterChangeHandler<'_> { + fn insert_text_change_if_needed_parent(&mut self, node: NodeRef) { +- if !node.supports_text_ranges() { ++ if !node.supports_text_ranges() && long_text(&node).is_none() { + return; + } + let id = node.id(); +@@ -75,6 +76,10 @@ impl AdapterChangeHandler<'_> { + } + + fn insert_text_change_if_needed(&mut self, node: &NodeRef) { ++ // Rune: a long field's text is its value. ++ if long_text(node).is_some() { ++ return self.insert_text_change_if_needed_parent(*node); ++ } + if node.role() != Role::TextRun { + return; + } +@@ -469,7 +474,7 @@ impl Adapter { + State::Placeholder(context) => { + let is_window_focused = context.read_tree().state().is_host_focused(); + let tree = Tree::new(update_factory(), is_window_focused); +- *context.tree.write().unwrap() = tree; ++ *context.tree.write().unwrap_or_else(|e| e.into_inner()) = tree; + context.is_placeholder.store(false, Ordering::SeqCst); + let result = context + .read_tree() +@@ -481,7 +486,7 @@ impl Adapter { + } + State::Active(context) => { + let mut handler = AdapterChangeHandler::new(context); +- let mut tree = context.tree.write().unwrap(); ++ let mut tree = context.tree.write().unwrap_or_else(|e| e.into_inner()); + tree.update_and_process_changes(update_factory(), &mut handler); + handler.enqueue_selection_changes(&tree); + Some(QueuedEvents(handler.queue)) +@@ -507,13 +512,13 @@ impl Adapter { + } + State::Placeholder(context) => { + let mut handler = AdapterChangeHandler::new(context); +- let mut tree = context.tree.write().unwrap(); ++ let mut tree = context.tree.write().unwrap_or_else(|e| e.into_inner()); + tree.update_host_focus_state_and_process_changes(is_focused, &mut handler); + Some(QueuedEvents(handler.queue)) + } + State::Active(context) => { + let mut handler = AdapterChangeHandler::new(context); +- let mut tree = context.tree.write().unwrap(); ++ let mut tree = context.tree.write().unwrap_or_else(|e| e.into_inner()); + tree.update_host_focus_state_and_process_changes(is_focused, &mut handler); + Some(QueuedEvents(handler.queue)) + } +diff --git a/src/context.rs b/src/context.rs +index 54cd3ed..799d59e 100644 +--- a/src/context.rs ++++ b/src/context.rs +@@ -26,7 +26,7 @@ impl<H: 'static + ActionHandler + Send> ActionHandlerWrapper<H> { + + impl<H: ActionHandler + Send> ActionHandlerNoMut for ActionHandlerWrapper<H> { + fn do_action(&self, request: ActionRequest) { +- self.0.lock().unwrap().do_action(request) ++ self.0.lock().unwrap_or_else(|e| e.into_inner()).do_action(request) + } + } + +@@ -66,7 +66,7 @@ impl Context { + } + + pub(crate) fn read_tree(&self) -> RwLockReadGuard<'_, Tree> { +- self.tree.read().unwrap() ++ self.tree.read().unwrap_or_else(|e| e.into_inner()) + } + + pub(crate) fn client_top_left(&self) -> Point { +@@ -81,7 +81,7 @@ impl Context { + self: &Arc<Self>, + id: FullNodeId, + ) -> ComObject<PlatformNode> { +- let mut platform_nodes = self.platform_nodes.lock().unwrap(); ++ let mut platform_nodes = self.platform_nodes.lock().unwrap_or_else(|e| e.into_inner()); + if let Some(result) = platform_nodes.get(&id) { + return result.clone(); + } +@@ -92,7 +92,7 @@ impl Context { + } + + pub(crate) fn remove_platform_node(&self, id: FullNodeId) { +- let mut platform_nodes = self.platform_nodes.lock().unwrap(); ++ let mut platform_nodes = self.platform_nodes.lock().unwrap_or_else(|e| e.into_inner()); + platform_nodes.remove(&id); + } + } +diff --git a/src/lib.rs b/src/lib.rs +index 7aee09b..890b9b3 100644 +--- a/src/lib.rs ++++ b/src/lib.rs +@@ -5,6 +5,7 @@ + + mod context; + mod filters; ++mod long_text; + mod node; + mod text; + mod util; +diff --git a/src/long_text.rs b/src/long_text.rs +new file mode 100644 +index 0000000..dcadab3 +--- /dev/null ++++ b/src/long_text.rs +@@ -0,0 +1,796 @@ ++// Rune (vendor/accesskit_windows.patch): a text field too long for its toolkit to publish text ++// runs (Rune stops at 64 KiB) keeps its text ranges. The toolkit marks such a field by putting its ++// selection on the field itself, as byte offsets into its value, and publishes a single ++// GenericContainer (`class_name = "\x1frune-lines"`) holding one GenericContainer child ++// (`class_name = "\x1frune-line"`, `author_id = "<start>:<end>"`) per drawn visual line. Ranges ++// are answered from the value when a reader asks, and screen rectangles, hit-testing and wrapped ++// visual lines are answered in the drawn band without shaping off-screen rows. ++// The same file is in accesskit_windows and accesskit_macos; each uses part of it. ++#![allow(dead_code)] ++ ++use std::cell::RefCell; ++ ++use accesskit::{Point, Rect, Role, TextDirection, TextSelection}; ++use accesskit_consumer::NodeRef; ++ ++const LINES_BOX_CLASS: &str = "\x1frune-lines"; ++const LINE_CLASS: &str = "\x1frune-line"; ++const CHECKPOINT_STRIDE: usize = 65_536; ++ ++#[derive(Clone, Copy, PartialEq, Eq)] ++pub(crate) enum Unit { ++ Character, ++ Word, ++ Line, ++ Paragraph, ++ Document, ++} ++ ++/// One visual line currently drawn on screen for a long field. ++#[derive(Clone, Copy)] ++pub(crate) struct DrawnLine<'a> { ++ pub(crate) start: usize, ++ pub(crate) end: usize, ++ pub(crate) node: NodeRef<'a>, ++} ++ ++/// All drawn-line metadata published on `node` for the current tree snapshot. ++pub(crate) struct DrawnState<'a> { ++ pub(crate) lines: Vec<DrawnLine<'a>>, ++ pub(crate) content_key: u64, ++ pub(crate) upstream_caret: bool, ++ pub(crate) caret_byte: usize, ++} ++ ++struct Band { ++ start: usize, ++ end: usize, ++ first: usize, ++ count: usize, ++} ++ ++#[derive(Clone, Copy)] ++struct Mark { ++ byte: usize, ++ utf16: usize, ++ newlines: usize, ++} ++ ++struct Checkpoints { ++ content_key: u64, ++ len: usize, ++ edge: [u8; 32], ++ marks: Vec<Mark>, ++} ++ ++const CHECKPOINT_SLOTS: usize = 4; ++ ++struct CheckpointRing { ++ slots: [Option<Checkpoints>; CHECKPOINT_SLOTS], ++ next: usize, ++} ++ ++thread_local! { ++ static CHECKPOINTS: RefCell<CheckpointRing> = const { ++ RefCell::new(CheckpointRing { ++ slots: [None, None, None, None], ++ next: 0, ++ }) ++ }; ++} ++ ++fn edge_sample(s: &str) -> [u8; 32] { ++ let mut out = [0u8; 32]; ++ let b = s.as_bytes(); ++ let head = b.len().min(16); ++ out[..head].copy_from_slice(&b[..head]); ++ let tail = b.len().min(16); ++ out[16..16 + tail].copy_from_slice(&b[b.len() - tail..]); ++ out ++} ++ ++fn with_checkpoints<R>(s: &str, content_key: u64, f: impl FnOnce(&[Mark]) -> R) -> R { ++ if s.len() <= CHECKPOINT_STRIDE { ++ return f(&[Mark { byte: 0, utf16: 0, newlines: 0 }]); ++ } ++ let edge = edge_sample(s); ++ CHECKPOINTS.with(|cell| { ++ let mut ring = cell.borrow_mut(); ++ if let Some(hit) = ring.slots.iter().flatten().find(|c| { ++ c.content_key == content_key && c.len == s.len() && c.edge == edge ++ }) { ++ return f(hit.marks.as_slice()); ++ } ++ let mut marks = Vec::with_capacity(s.len() / CHECKPOINT_STRIDE + 2); ++ marks.push(Mark { byte: 0, utf16: 0, newlines: 0 }); ++ let mut utf16 = 0usize; ++ let mut newlines = 0usize; ++ let mut next_at = CHECKPOINT_STRIDE; ++ for (k, ch) in s.char_indices() { ++ if k >= next_at { ++ marks.push(Mark { byte: k, utf16, newlines }); ++ next_at = k + CHECKPOINT_STRIDE; ++ } ++ utf16 += ch.len_utf16(); ++ if ch == '\n' { ++ newlines += 1; ++ } ++ } ++ let idx = ring.next % CHECKPOINT_SLOTS; ++ ring.next = ring.next.wrapping_add(1); ++ ring.slots[idx] = Some(Checkpoints { content_key, len: s.len(), edge, marks }); ++ let marks = ring.slots[idx].as_ref().map_or(&[][..], |c| c.marks.as_slice()); ++ f(marks) ++ }) ++} ++ ++/// The value and selection a long field's text ranges are answered from. ++pub(crate) fn long_text<'a>(node: &NodeRef<'a>) -> Option<(Text<'a>, &'a TextSelection)> { ++ if !node.is_text_input() || node.is_password_input() || node.supports_text_ranges() { ++ return None; ++ } ++ let data = node.data(); ++ let selection = data.text_selection()?; ++ let (id, _) = node.locate(); ++ if selection.anchor.node != id || selection.focus.node != id { ++ return None; ++ } ++ Some((Text(data.value().unwrap_or("")), selection)) ++} ++ ++/// Drawn visual lines Rune attached to `node` inside its `\x1frune-lines` container, sorted and ++/// strictly non-overlapping. ++pub(crate) fn drawn_state<'a>(node: &NodeRef<'a>, text: Text<'a>) -> DrawnState<'a> { ++ let caret_byte = node ++ .data() ++ .text_selection() ++ .map_or(0, |s| text.clamp(s.focus.character_index)); ++ let Some(box_node) = node ++ .children() ++ .find(|c| c.role() == Role::GenericContainer && c.data().class_name() == Some(LINES_BOX_CLASS)) ++ else { ++ return DrawnState { ++ lines: Vec::new(), ++ content_key: 0, ++ upstream_caret: false, ++ caret_byte, ++ }; ++ }; ++ let (content_key, upstream_caret) = box_node ++ .author_id() ++ .and_then(|s| s.split_once(':')) ++ .map_or((0, false), |(k, u)| (u64::from_str_radix(k, 16).unwrap_or(0), u == "1")); ++ ++ let mut raw = Vec::new(); ++ for child in box_node.children() { ++ if child.role() != Role::GenericContainer || child.data().class_name() != Some(LINE_CLASS) { ++ continue; ++ } ++ let Some((a, b)) = child.author_id().and_then(|id| id.split_once(':')) else { ++ continue; ++ }; ++ let (Ok(a), Ok(b)) = (a.parse::<usize>(), b.parse::<usize>()) else { ++ continue; ++ }; ++ let start = text.clamp(a); ++ let end = text.clamp(b).max(start); ++ raw.push(DrawnLine { start, end, node: child }); ++ } ++ raw.sort_by_key(|d| (d.start, d.end)); ++ let mut lines: Vec<DrawnLine<'a>> = Vec::new(); ++ for d in raw { ++ if let Some(prev) = lines.last() ++ && (d.start < prev.end || (d.start == prev.start && d.end == prev.end)) ++ { ++ continue; ++ } ++ lines.push(d); ++ } ++ DrawnState { lines, content_key, upstream_caret, caret_byte } ++} ++ ++pub(crate) fn drawn_lines<'a>(node: &NodeRef<'a>, text: Text<'a>) -> Vec<DrawnLine<'a>> { ++ drawn_state(node, text).lines ++} ++ ++fn bands(drawn: &[DrawnLine]) -> Vec<Band> { ++ let mut out: Vec<Band> = Vec::new(); ++ for (idx, d) in drawn.iter().enumerate() { ++ if let Some(last) = out.last_mut() ++ && last.end == d.start ++ { ++ last.end = d.end; ++ last.count += 1; ++ continue; ++ } ++ out.push(Band { start: d.start, end: d.end, first: idx, count: 1 }); ++ } ++ out ++} ++ ++fn line_is_rtl(line: &NodeRef) -> bool { ++ line.data().text_direction() == Some(TextDirection::RightToLeft) ++} ++ ++fn line_is_hard_end(text: Text, end: usize) -> bool { ++ end > 0 && text.0.as_bytes().get(end - 1) == Some(&b'\n') ++} ++ ++fn caret_x_in_line(line: &NodeRef, rel_byte: usize, trailing_edge: bool) -> f64 { ++ let data = line.data(); ++ let rtl = line_is_rtl(line); ++ let w = data.bounds().map_or(0.0, |r| r.width()); ++ if trailing_edge { ++ return if rtl { 0.0 } else { w }; ++ } ++ let lengths = data.character_lengths(); ++ let positions = data.character_positions().unwrap_or(&[]); ++ let widths = data.character_widths().unwrap_or(&[]); ++ if lengths.is_empty() || positions.len() < lengths.len() || widths.len() < lengths.len() { ++ return if (rel_byte == 0) != rtl { 0.0 } else { w }; ++ } ++ let mut seen = 0usize; ++ for (k, &len) in lengths.iter().enumerate() { ++ let next = seen + usize::from(len); ++ if rel_byte < next || (rel_byte == seen && len == 0) { ++ let x0 = f64::from(positions[k]); ++ let x1 = x0 + f64::from(widths[k]); ++ let cluster_rtl = if k + 1 < lengths.len() && widths[k] > 0.0 && widths[k + 1] > 0.0 { ++ positions[k + 1] < positions[k] ++ } else if k > 0 && widths[k] > 0.0 && widths[k - 1] > 0.0 { ++ positions[k] < positions[k - 1] ++ } else { ++ rtl ++ }; ++ return if cluster_rtl { x1 } else { x0 }; ++ } ++ seen = next; ++ } ++ if rtl { 0.0 } else { w } ++} ++ ++fn span_x_in_line(line: &NodeRef, rel_start: usize, rel_end: usize) -> (f64, f64) { ++ let data = line.data(); ++ let w = data.bounds().map_or(0.0, |r| r.width()); ++ let lengths = data.character_lengths(); ++ let positions = data.character_positions().unwrap_or(&[]); ++ let widths = data.character_widths().unwrap_or(&[]); ++ if lengths.is_empty() || positions.len() < lengths.len() || widths.len() < lengths.len() { ++ return (0.0, w); ++ } ++ let mut seen = 0usize; ++ let mut min_x = f64::INFINITY; ++ let mut max_x = f64::NEG_INFINITY; ++ for (k, &len) in lengths.iter().enumerate() { ++ let next = seen + usize::from(len); ++ if next > rel_start && seen < rel_end { ++ let x0 = f64::from(positions[k]); ++ let x1 = x0 + f64::from(widths[k]).max(0.0); ++ min_x = min_x.min(x0); ++ max_x = max_x.max(x1); ++ } ++ seen = next; ++ } ++ if min_x.is_finite() && max_x.is_finite() { ++ (min_x, max_x.max(min_x)) ++ } else { ++ let x = caret_x_in_line(line, rel_start, false); ++ (x, x) ++ } ++} ++ ++/// Transformed bounding boxes (in root/window coordinates, matching AccessKit's `Range::bounding_boxes`) ++/// for the drawn portion of `a..b`. Off-screen bytes have no box, matching Chromium. ++pub(crate) fn bounding_boxes(node: &NodeRef, text: Text, a: usize, b: usize) -> Vec<Rect> { ++ let (a, b) = (text.clamp(a.min(b)), text.clamp(a.max(b))); ++ let state = drawn_state(node, text); ++ let drawn = &state.lines; ++ if drawn.is_empty() { ++ return Vec::new(); ++ } ++ if a == b { ++ if state.upstream_caret && a == state.caret_byte { ++ if let Some(d) = drawn ++ .iter() ++ .find(|d| a == d.end && d.start < d.end && !line_is_hard_end(text, d.end)) ++ && let Some(mut rect) = d.node.data().bounds() ++ { ++ let x = caret_x_in_line(&d.node, a - d.start, true); ++ let left = rect.x0 + x; ++ rect.x0 = left; ++ rect.x1 = left; ++ return vec![d.node.transform().transform_rect_bbox(rect)]; ++ } ++ } ++ let hit = drawn.iter().enumerate().find(|&(k, d)| { ++ (d.start <= a && a < d.end) ++ || (d.start == a && d.end == a) ++ || (a == d.end ++ && !line_is_hard_end(text, d.end) ++ && drawn.get(k + 1).is_none_or(|nx| nx.start != a)) ++ }); ++ let Some((_, d)) = hit else { ++ return Vec::new(); ++ }; ++ let Some(mut rect) = d.node.data().bounds() else { ++ return Vec::new(); ++ }; ++ let x = caret_x_in_line(&d.node, a.saturating_sub(d.start), false); ++ let left = rect.x0 + x; ++ rect.x0 = left; ++ rect.x1 = left; ++ return vec![d.node.transform().transform_rect_bbox(rect)]; ++ } ++ let mut out = Vec::new(); ++ for d in drawn { ++ let ov_start = a.max(d.start); ++ let ov_end = b.min(d.end); ++ if ov_start >= ov_end { ++ continue; ++ } ++ let Some(mut rect) = d.node.data().bounds() else { ++ continue; ++ }; ++ if ov_start > d.start || ov_end < d.end { ++ let orig_left = rect.x0; ++ let (x0, x1) = span_x_in_line(&d.node, ov_start - d.start, ov_end - d.start); ++ rect.x0 = orig_left + x0; ++ rect.x1 = orig_left + x1; ++ } ++ out.push(d.node.transform().transform_rect_bbox(rect)); ++ } ++ out ++} ++ ++/// Byte offset in `text` at `point` (in `node`'s local coordinate space), using containment inside ++/// the nearest drawn visual line. When `for_char` is true (macOS `accessibilityRangeForPosition:`), ++/// a point past the trailing edge of a soft-wrapped line clamps to that line's last character. ++pub(crate) fn byte_at_point(node: &NodeRef, text: Text, point: Point, for_char: bool) -> Option<usize> { ++ let drawn = drawn_lines(node, text); ++ let d = drawn.iter().min_by(|a, b| { ++ let dist = |ln: &DrawnLine| match ln.node.data().bounds() { ++ Some(r) if point.y < r.y0 => r.y0 - point.y, ++ Some(r) if point.y > r.y1 => point.y - r.y1, ++ Some(_) => 0.0, ++ None => f64::INFINITY, ++ }; ++ dist(a).total_cmp(&dist(b)) ++ })?; ++ let bounds = d.node.data().bounds()?; ++ let rel_x = (point.x - bounds.x0) as f32; ++ let data = d.node.data(); ++ let rtl = line_is_rtl(&d.node); ++ let lengths = data.character_lengths(); ++ let positions = data.character_positions().unwrap_or(&[]); ++ let widths = data.character_widths().unwrap_or(&[]); ++ if lengths.is_empty() || positions.len() < lengths.len() || widths.len() < lengths.len() { ++ return Some(d.start); ++ } ++ let mut byte_off = 0usize; ++ let mut min_x = f32::INFINITY; ++ let mut max_x = f32::NEG_INFINITY; ++ for k in 0..lengths.len() { ++ let w = widths[k]; ++ let x0 = positions[k]; ++ let x1 = x0 + w; ++ if w > 0.0 { ++ min_x = min_x.min(x0); ++ max_x = max_x.max(x1); ++ if rel_x >= x0 && rel_x < x1 { ++ return Some(text.clamp(d.start + byte_off)); ++ } ++ } ++ byte_off += usize::from(lengths[k]); ++ } ++ let trim = if d.end >= d.start + 2 && text.0.as_bytes().get(d.end - 2..d.end) == Some(b"\r\n") { ++ 2 ++ } else if d.end > d.start && text.0.as_bytes().get(d.end - 1) == Some(&b'\n') { ++ 1 ++ } else { ++ 0 ++ }; ++ let line_end = text.clamp(d.end.saturating_sub(trim)).max(d.start); ++ let leading = if rtl { rel_x >= max_x } else { rel_x <= min_x }; ++ if leading { ++ return Some(d.start); ++ } ++ if for_char && trim == 0 && line_end > d.start { ++ return Some(text.prev(line_end, Unit::Character).max(d.start)); ++ } ++ Some(line_end) ++} ++ ++fn utf16_len(s: &str) -> usize { ++ if s.is_ascii() { s.len() } else { s.chars().map(char::len_utf16).sum() } ++} ++ ++fn count_newlines_slice(s: &str) -> usize { ++ s.as_bytes().iter().filter(|&&b| b == b'\n').count() ++} ++ ++fn count_newlines_between(s: &str, a: usize, b: usize, marks: &[Mark]) -> usize { ++ if a >= b || b > s.len() { ++ return 0; ++ } ++ if b - a <= CHECKPOINT_STRIDE || marks.len() <= 1 { ++ return s.get(a..b).map_or(0, count_newlines_slice); ++ } ++ let ma = marks.partition_point(|m| m.byte <= a).saturating_sub(1); ++ let mb = marks.partition_point(|m| m.byte <= b).saturating_sub(1); ++ if mb <= ma { ++ return s.get(a..b).map_or(0, count_newlines_slice); ++ } ++ let head_sub = s.get(marks[ma].byte..a).map_or(0, count_newlines_slice); ++ let tail_add = s.get(marks[mb].byte..b).map_or(0, count_newlines_slice); ++ (marks[mb].newlines + tail_add).saturating_sub(marks[ma].newlines + head_sub) ++} ++ ++fn nth_newline_after(s: &str, from: usize, limit: usize, nth: usize, marks: &[Mark]) -> Option<usize> { ++ let sub = s.get(from..limit)?; ++ if limit - from <= CHECKPOINT_STRIDE || marks.len() <= 1 { ++ return sub.match_indices('\n').nth(nth).map(|(p, _)| from + p); ++ } ++ let m_from = marks.partition_point(|m| m.byte <= from).saturating_sub(1); ++ let base_nl = marks[m_from].newlines + s.get(marks[m_from].byte..from).map_or(0, count_newlines_slice); ++ let target_nl = base_nl + nth + 1; ++ let m_hit = marks.partition_point(|m| m.newlines < target_nl).saturating_sub(1); ++ let scan_start = marks[m_hit].byte.max(from); ++ if scan_start >= limit { ++ return None; ++ } ++ let already = if scan_start == from { ++ 0 ++ } else { ++ (marks[m_hit].newlines).saturating_sub(base_nl) ++ }; ++ let rem = nth.checked_sub(already)?; ++ s.get(scan_start..limit)? ++ .match_indices('\n') ++ .nth(rem) ++ .map(|(p, _)| scan_start + p) ++} ++ ++/// Byte offsets into a field's value. ++#[derive(Clone, Copy)] ++pub(crate) struct Text<'a>(pub(crate) &'a str); ++ ++impl<'a> Text<'a> { ++ pub(crate) fn len(self) -> usize { ++ self.0.len() ++ } ++ ++ /// `i`, within the text and on a character's start. ++ pub(crate) fn clamp(self, i: usize) -> usize { ++ self.0.floor_char_boundary(i.min(self.0.len())) ++ } ++ ++ pub(crate) fn slice(self, a: usize, b: usize) -> &'a str { ++ let (a, b) = (self.clamp(a.min(b)), self.clamp(a.max(b))); ++ self.0.get(a..b).unwrap_or("") ++ } ++ ++ fn line_start(self, i: usize) -> usize { ++ let i = self.clamp(i); ++ self.0.get(..i).and_then(|s| s.rfind('\n')).map_or(0, |p| p + 1) ++ } ++ ++ pub(crate) fn is_start(self, i: usize, unit: Unit) -> bool { ++ let i = self.clamp(i); ++ let s = self.0; ++ match unit { ++ Unit::Character => true, ++ Unit::Word => { ++ i == 0 ++ || (s.get(i..).and_then(|r| r.chars().next()).is_some_and(|c| !c.is_whitespace()) ++ && s.get(..i).and_then(|l| l.chars().next_back()).is_some_and(char::is_whitespace)) ++ } ++ Unit::Line | Unit::Paragraph => i == 0 || s.as_bytes().get(i - 1) == Some(&b'\n'), ++ Unit::Document => i == 0, ++ } ++ } ++ ++ pub(crate) fn is_start_in(self, i: usize, unit: Unit, state: &DrawnState) -> bool { ++ let i = self.clamp(i); ++ if unit == Unit::Line && !state.lines.is_empty() { ++ if state.upstream_caret ++ && i == state.caret_byte ++ && state ++ .lines ++ .iter() ++ .any(|d| i == d.end && d.start < d.end && !line_is_hard_end(self, d.end)) ++ { ++ return false; ++ } ++ if let Some(d) = state ++ .lines ++ .iter() ++ .find(|d| (d.start <= i && i < d.end) || (d.start == i && d.end == i)) ++ { ++ return i == d.start; ++ } ++ } ++ self.is_start(i, unit) ++ } ++ ++ /// The start of the unit holding `i`. ++ pub(crate) fn start_of(self, i: usize, unit: Unit) -> usize { ++ let i = self.clamp(i); ++ if self.is_start(i, unit) { i } else { self.prev(i, unit) } ++ } ++ ++ pub(crate) fn start_of_in(self, i: usize, unit: Unit, state: &DrawnState) -> usize { ++ let i = self.clamp(i); ++ if self.is_start_in(i, unit, state) { ++ i ++ } else { ++ self.prev_in(i, unit, &state.lines) ++ } ++ } ++ ++ /// The first unit start after `i`, or the text's end. ++ pub(crate) fn next(self, i: usize, unit: Unit) -> usize { ++ let i = self.clamp(i); ++ let s = self.0; ++ let tail = s.get(i..).unwrap_or(""); ++ match unit { ++ Unit::Character => tail.chars().next().map_or(i, |c| i + c.len_utf8()), ++ Unit::Word => { ++ let mut space = false; ++ for (k, c) in tail.char_indices() { ++ if c.is_whitespace() { ++ space = true; ++ } else if space { ++ return i + k; ++ } ++ } ++ s.len() ++ } ++ Unit::Line | Unit::Paragraph => tail.find('\n').map_or(s.len(), |p| i + p + 1), ++ Unit::Document => s.len(), ++ } ++ } ++ ++ pub(crate) fn next_in(self, i: usize, unit: Unit, drawn: &[DrawnLine]) -> usize { ++ let i = self.clamp(i); ++ if unit != Unit::Line || drawn.is_empty() { ++ return self.next(i, unit); ++ } ++ if let Some(d) = drawn.iter().find(|d| d.start <= i && i < d.end) { ++ return d.end; ++ } ++ let nl = self.next(i, Unit::Line); ++ drawn ++ .iter() ++ .find(|d| d.start > i && d.start < nl) ++ .map_or(nl, |d| d.start) ++ } ++ ++ /// The last unit start before `i`, or the text's start. ++ pub(crate) fn prev(self, i: usize, unit: Unit) -> usize { ++ let i = self.clamp(i); ++ let s = self.0; ++ let head = s.get(..i).unwrap_or(""); ++ match unit { ++ Unit::Character => head.chars().next_back().map_or(0, |c| i - c.len_utf8()), ++ Unit::Word => { ++ let mut word = None; ++ for (k, c) in head.char_indices().rev() { ++ if !c.is_whitespace() { ++ word = Some(k); ++ } else if let Some(k) = word { ++ return k; ++ } ++ } ++ 0 ++ } ++ Unit::Line | Unit::Paragraph => { ++ if i == 0 { ++ return 0; ++ } ++ let at = self.line_start(i); ++ if at < i { ++ at ++ } else { ++ self.line_start(self.clamp(i - 1)) ++ } ++ } ++ Unit::Document => 0, ++ } ++ } ++ ++ pub(crate) fn prev_in(self, i: usize, unit: Unit, drawn: &[DrawnLine]) -> usize { ++ let i = self.clamp(i); ++ if unit != Unit::Line || drawn.is_empty() || i == 0 { ++ return self.prev(i, unit); ++ } ++ if let Some(d) = drawn.iter().rfind(|d| d.start < i && i <= d.end) { ++ return d.start; ++ } ++ if drawn.iter().any(|d| d.start == i) { ++ if let Some(prev_d) = drawn.iter().rfind(|d| d.end == i && d.start < i) { ++ return prev_d.start; ++ } ++ return self.prev(i, Unit::Line); ++ } ++ let p = self.prev(i, Unit::Line); ++ drawn ++ .iter() ++ .rfind(|d| d.start >= p && d.start < i) ++ .map_or(p, |d| d.start) ++ } ++ ++ /// Moves `i` by `count` unit starts, stopping at either end of the text. ++ pub(crate) fn step_in(self, i: usize, unit: Unit, count: i32, drawn: &[DrawnLine]) -> (usize, i32) { ++ let mut i = self.clamp(i); ++ if count == 0 { ++ return (i, 0); ++ } ++ let mut moved = 0i32; ++ let steps = count.unsigned_abs(); ++ for _ in 0..steps { ++ if (count > 0 && i == self.len()) || (count < 0 && i == 0) { ++ break; ++ } ++ let next_i = if count > 0 { ++ self.next_in(i, unit, drawn) ++ } else { ++ self.prev_in(i, unit, drawn) ++ }; ++ if next_i == i { ++ break; ++ } ++ i = next_i; ++ moved = moved.saturating_add(1); ++ } ++ (i, if count < 0 { -moved } else { moved }) ++ } ++ ++ /// The zero-based line holding byte `i`, counting drawn wrapped lines visually. ++ pub(crate) fn line_of_in(self, i: usize, state: &DrawnState) -> usize { ++ let i = self.clamp(i); ++ let s = self.0; ++ let drawn = &state.lines; ++ let bs = bands(drawn); ++ with_checkpoints(s, state.content_key, |marks| { ++ if bs.is_empty() { ++ return count_newlines_between(s, 0, i, marks); ++ } ++ let mut lines = 0usize; ++ let mut cursor = 0usize; ++ for b in &bs { ++ if i < b.start { ++ return lines + count_newlines_between(s, cursor, i, marks); ++ } ++ lines += count_newlines_between(s, cursor, b.start, marks); ++ let band_slice = &drawn[b.first..b.first + b.count]; ++ let has_trailing_empty = ++ band_slice.last().is_some_and(|d| d.start == b.end && d.end == b.end); ++ let in_band_at_end = i == b.end ++ && b.end == s.len() ++ && (has_trailing_empty || !line_is_hard_end(self, b.end)); ++ if i < b.end ++ || in_band_at_end ++ || (state.upstream_caret ++ && i == state.caret_byte ++ && i == b.end ++ && b.start < b.end ++ && !line_is_hard_end(self, b.end)) ++ { ++ if state.upstream_caret && i == state.caret_byte { ++ if let Some(sub) = band_slice ++ .iter() ++ .position(|d| i == d.end && d.start < d.end && !line_is_hard_end(self, d.end)) ++ { ++ return lines + sub; ++ } ++ } ++ let sub = band_slice.iter().rposition(|d| d.start <= i).unwrap_or(0); ++ return lines + sub; ++ } ++ lines += b.count; ++ cursor = b.end; ++ } ++ lines + count_newlines_between(s, cursor, i, marks) ++ }) ++ } ++ ++ /// Line `n`'s bytes, counting drawn wrapped lines visually. ++ pub(crate) fn line_in(self, n: usize, state: &DrawnState) -> Option<(usize, usize)> { ++ let s = self.0; ++ let drawn = &state.lines; ++ let bs = bands(drawn); ++ with_checkpoints(s, state.content_key, |marks| { ++ if bs.is_empty() { ++ let start = if n == 0 { ++ 0 ++ } else { ++ nth_newline_after(s, 0, s.len(), n - 1, marks)? + 1 ++ }; ++ return Some((start, self.next(start, Unit::Line))); ++ } ++ let mut rem = n; ++ let mut cursor = 0usize; ++ for b in &bs { ++ let gap_lines = count_newlines_between(s, cursor, b.start, marks); ++ if rem < gap_lines { ++ let start = if rem == 0 { ++ cursor ++ } else { ++ nth_newline_after(s, cursor, b.start, rem - 1, marks)? + 1 ++ }; ++ return Some((start, self.next(start, Unit::Line).min(b.start))); ++ } ++ rem -= gap_lines; ++ if rem < b.count { ++ let d = &drawn[b.first + rem]; ++ return Some((d.start, d.end)); ++ } ++ rem -= b.count; ++ cursor = b.end; ++ } ++ let drawn_has_end_empty = ++ drawn.last().is_some_and(|d| d.start == s.len() && d.end == s.len()); ++ if cursor >= s.len() { ++ if !drawn_has_end_empty && line_is_hard_end(self, s.len()) && rem == 0 { ++ return Some((s.len(), s.len())); ++ } ++ return None; ++ } ++ let start = if rem == 0 { ++ cursor ++ } else { ++ nth_newline_after(s, cursor, s.len(), rem - 1, marks)? + 1 ++ }; ++ Some((start, self.next(start, Unit::Line))) ++ }) ++ } ++ ++ pub(crate) fn utf16_with(self, i: usize, key: u64) -> usize { ++ let i = self.clamp(i); ++ with_checkpoints(self.0, key, |marks| { ++ let idx = marks.partition_point(|m| m.byte <= i).saturating_sub(1); ++ let m = marks.get(idx).copied().unwrap_or(Mark { byte: 0, utf16: 0, newlines: 0 }); ++ m.utf16 + self.0.get(m.byte..i).map_or(0, utf16_len) ++ }) ++ } ++ ++ pub(crate) fn utf16(self, i: usize) -> usize { ++ self.utf16_with(i, 0) ++ } ++ ++ /// Bytes `a..b` as a UTF-16 start and length. ++ pub(crate) fn utf16_span_with(self, a: usize, b: usize, key: u64) -> (usize, usize) { ++ let (a, b) = (self.clamp(a.min(b)), self.clamp(a.max(b))); ++ let start = self.utf16_with(a, key); ++ let len = if b - a <= CHECKPOINT_STRIDE { ++ self.0.get(a..b).map_or(0, utf16_len) ++ } else { ++ self.utf16_with(b, key).saturating_sub(start) ++ }; ++ (start, len) ++ } ++ ++ pub(crate) fn utf16_span(self, a: usize, b: usize) -> (usize, usize) { ++ self.utf16_span_with(a, b, 0) ++ } ++ ++ pub(crate) fn from_utf16_with(self, units: usize, key: u64) -> usize { ++ with_checkpoints(self.0, key, |marks| { ++ let idx = marks.partition_point(|m| m.utf16 <= units).saturating_sub(1); ++ let m = marks.get(idx).copied().unwrap_or(Mark { byte: 0, utf16: 0, newlines: 0 }); ++ let mut seen = m.utf16; ++ let tail = self.0.get(m.byte..).unwrap_or(""); ++ for (k, c) in tail.char_indices() { ++ if seen >= units { ++ return m.byte + k; ++ } ++ seen += c.len_utf16(); ++ } ++ self.0.len() ++ }) ++ } ++ ++ pub(crate) fn from_utf16(self, units: usize) -> usize { ++ self.from_utf16_with(units, 0) ++ } ++} +diff --git a/src/node.rs b/src/node.rs +index f4a97e3..26fa8be 100644 +--- a/src/node.rs ++++ b/src/node.rs +@@ -12,7 +12,7 @@ + + use accesskit::{ + Action, ActionData, ActionRequest, AriaCurrent, HasPopup, Live, NodeId, Orientation, Point, +- Role, SortDirection, Toggled, TreeId, ++ Role, SortDirection, TextSelection, Toggled, TreeId, + }; + use accesskit_consumer::{FilterResult, FullNodeId, NodeRef, Tree, TreeState}; + use std::{ +@@ -31,6 +31,7 @@ use windows::{ + use crate::{ + context::Context, + filters::{filter, filter_with_root_exception}, ++ long_text::{Text, byte_at_point, long_text}, + text::PlatformRange as PlatformTextRange, + util::*, + }; +@@ -708,7 +709,7 @@ impl NodeWrapper<'_> { + } + + fn is_text_pattern_supported(&self) -> bool { +- self.node.supports_text_ranges() ++ self.node.supports_text_ranges() || long_text(&self.node).is_some() + } + + fn is_expand_collapse_pattern_supported(&self) -> bool { +@@ -732,6 +733,41 @@ impl NodeWrapper<'_> { + self.node.is_dialog() + } + ++ // Rune (vendor/accesskit_windows.patch): headings and landmarks as UIA reports them, which ++ // Narrator's and NVDA's heading and landmark navigation read, as Chromium maps ARIA's. ++ fn heading_level(&self) -> Option<i32> { ++ if self.node.role() != Role::Heading { ++ return None; ++ } ++ // ARIA's default heading level is 2. ++ let level = self.node.level().map_or(2, |l| l + 1).clamp(1, 9) as i32; ++ Some(HeadingLevel1.0 + level - 1) ++ } ++ ++ fn landmark_type(&self) -> Option<i32> { ++ let id = match self.node.role() { ++ Role::Main => UIA_MainLandmarkTypeId, ++ Role::Navigation => UIA_NavigationLandmarkTypeId, ++ Role::Search => UIA_SearchLandmarkTypeId, ++ Role::Form if self.node.label().is_some() => UIA_FormLandmarkTypeId, ++ Role::Banner | Role::Header | Role::Complementary | Role::ContentInfo | Role::Footer => UIA_CustomLandmarkTypeId, ++ Role::Region if self.node.label().is_some() => UIA_CustomLandmarkTypeId, ++ _ => return None, ++ }; ++ Some(id.0) ++ } ++ ++ fn localized_landmark_type(&mut self) -> Option<StrWrapper<'_>> { ++ let name = match self.node.role() { ++ Role::Banner | Role::Header => "banner", ++ Role::Complementary => "complementary", ++ Role::ContentInfo | Role::Footer => "content information", ++ Role::Region if self.node.label().is_some() => "region", ++ _ => return None, ++ }; ++ Some(StrWrapper::new(name, self.string_buffer)) ++ } ++ + fn is_window_pattern_supported(&self) -> bool { + self.node.is_dialog() + } +@@ -770,6 +806,10 @@ impl NodeWrapper<'_> { + } + } + ++fn long_value_unchanged(new: &NodeRef, old: &NodeRef) -> bool { ++ long_text(new).is_some() && long_text(old).is_some() && new.raw_value() == old.raw_value() ++} ++ + fn enqueue_property_change( + queue: &mut Vec<QueuedEvent>, + element: &IRawElementProviderSimple, +@@ -799,6 +839,7 @@ fn enqueue_property_change( + ISelectionItemProvider, + ISelectionProvider, + ITextProvider, ++ ITextProvider2, + IExpandCollapseProvider, + IWindowProvider + )] +@@ -839,9 +880,12 @@ impl PlatformNode { + where + F: FnOnce(&Tree, &Arc<Context>) -> Result<T>, + { +- let context = self.upgrade_context()?; +- let tree = context.read_tree(); +- f(&tree, &context) ++ std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { ++ let context = self.upgrade_context()?; ++ let tree = context.read_tree(); ++ f(&tree, &context) ++ })) ++ .unwrap_or_else(|_| Err(element_not_available())) + } + + fn node<'a>(&self, tree: &'a Tree) -> Result<NodeRef<'a>> { +@@ -907,6 +951,18 @@ impl PlatformNode { + }) + } + ++ /// Rune: if this node is a long field ([`long_text`]), its range `f` picks, in its value's ++ /// bytes. ++ fn long_range(&self, f: impl FnOnce(Text, &TextSelection) -> (usize, usize)) -> Result<Option<ITextRangeProvider>> { ++ self.resolve(|node| { ++ Ok(long_text(&node).map(|(text, selection)| { ++ let (a, b) = f(text, selection); ++ let (a, b) = (text.clamp(a.min(b)), text.clamp(a.max(b))); ++ PlatformTextRange::new_long(&self.context, node.id(), a, b).into() ++ })) ++ }) ++ } ++ + fn resolve_for_text_pattern<F, T>(&self, f: F) -> Result<T> + where + for<'a> F: FnOnce(NodeRef<'a>) -> Result<T>, +@@ -918,17 +974,20 @@ impl PlatformNode { + where + for<'a> F: FnOnce(NodeRef<'a>, NodeId, TreeId) -> Result<Option<ActionRequest>>, + { +- let context = self.upgrade_context()?; +- if context.is_placeholder.load(Ordering::SeqCst) { +- return Err(element_not_enabled()); +- } +- let tree = context.read_tree(); +- let (node, target_node, target_tree) = self.node_with_location(&tree)?; +- if let Some(request) = f(node, target_node, target_tree)? { +- drop(tree); +- context.do_action(request); +- } +- Ok(()) ++ std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { ++ let context = self.upgrade_context()?; ++ if context.is_placeholder.load(Ordering::SeqCst) { ++ return Err(element_not_enabled()); ++ } ++ let tree = context.read_tree(); ++ let (node, target_node, target_tree) = self.node_with_location(&tree)?; ++ if let Some(request) = f(node, target_node, target_tree)? { ++ drop(tree); ++ context.do_action(request); ++ } ++ Ok(()) ++ })) ++ .unwrap_or_else(|_| Err(element_not_available())) + } + + fn do_action<F>(&self, f: F) -> Result<()> +@@ -1272,7 +1331,10 @@ macro_rules! patterns { + old: &mut NodeWrapper, + ) { + $(if self.$is_supported() && old.$is_supported() { +- $({ ++ $( ++ // Rune: a long field's unchanged value isn't copied twice to UTF-16 to find ++ // it unchanged (14.5 MB each way at 200,000 lines, on every caret move). ++ if !(stringify!($getter) == "value" && long_value_unchanged(&self.node, &old.node)) { + let old_value = old.$getter(); + let new_value = self.$getter(); + if old_value != new_value { +@@ -1326,7 +1388,10 @@ properties! { + (UIA_PositionInSetPropertyId, position_in_set), + (UIA_SizeOfSetPropertyId, size_of_set), + (UIA_AriaPropertiesPropertyId, aria_properties), +- (UIA_IsDialogPropertyId, is_dialog) ++ (UIA_IsDialogPropertyId, is_dialog), ++ (UIA_HeadingLevelPropertyId, heading_level), ++ (UIA_LandmarkTypePropertyId, landmark_type), ++ (UIA_LocalizedLandmarkTypePropertyId, localized_landmark_type) + } + + patterns! { +@@ -1431,6 +1496,9 @@ patterns! { + )), + (UIA_TextPatternId, ITextProvider, ITextProvider_Impl, is_text_pattern_supported, (), ( + fn GetSelection(&self) -> Result<*mut SAFEARRAY> { ++ if let Some(range) = self.long_range(|_, s| (s.anchor.character_index, s.focus.character_index))? { ++ return Ok(safe_array_from_com_slice(&[range.cast::<IUnknown>()?])); ++ } + self.resolve_for_text_pattern(|node| { + if let Some(range) = node.text_selection() { + let platform_range: ITextRangeProvider = PlatformTextRange::new(&self.context, range).into(); +@@ -1455,6 +1523,21 @@ patterns! { + }, + + fn RangeFromPoint(&self, point: &UiaPoint) -> Result<ITextRangeProvider> { ++ let hit = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { ++ self.resolve_with_context(|node, context| { ++ Ok(long_text(&node).map(|(text, s)| { ++ let client_top_left = context.client_top_left(); ++ let pt = Point::new(point.x - client_top_left.x, point.y - client_top_left.y); ++ let pt = node.transform().inverse() * pt; ++ let at = byte_at_point(&node, text, pt, false).unwrap_or_else(|| text.clamp(s.focus.character_index)); ++ PlatformTextRange::new_long(&self.context, node.id(), at, at).into() ++ })) ++ }) ++ })) ++ .unwrap_or_else(|_| Err(element_not_available()))?; ++ if let Some(range) = hit { ++ return Ok(range); ++ } + self.resolve_with_context_for_text_pattern(|node, context| { + let client_top_left = context.client_top_left(); + let point = Point::new(point.x - client_top_left.x, point.y - client_top_left.y); +@@ -1466,6 +1549,9 @@ patterns! { + }, + + fn DocumentRange(&self) -> Result<ITextRangeProvider> { ++ if let Some(range) = self.long_range(|text, _| (0, text.len()))? { ++ return Ok(range); ++ } + self.resolve_for_text_pattern(|node| { + let range = node.document_range(); + Ok(PlatformTextRange::new(&self.context, range).into()) +@@ -1473,6 +1559,9 @@ patterns! { + }, + + fn SupportedTextSelection(&self) -> Result<SupportedTextSelection> { ++ if self.long_range(|_, _| (0, 0))?.is_some() { ++ return Ok(SupportedTextSelection_Single); ++ } + self.resolve_for_text_pattern(|node| { + if node.has_text_selection() { + Ok(SupportedTextSelection_Single) +@@ -1482,6 +1571,36 @@ patterns! { + }) + } + )), ++ (UIA_TextPattern2Id, ITextProvider2, ITextProvider2_Impl, is_text_pattern_supported, (), ( ++ fn RangeFromAnnotation(&self, _annotation: Ref<IRawElementProviderSimple>) -> Result<ITextRangeProvider> { ++ Err(not_supported()) ++ }, ++ ++ fn GetCaretRange(&self, is_active: *mut BOOL) -> Result<ITextRangeProvider> { ++ std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { ++ let long_caret = self.resolve(|node| { ++ Ok(long_text(&node).map(|(text, s)| { ++ if !is_active.is_null() { ++ unsafe { *is_active = node.is_focused().into() }; ++ } ++ let at = text.clamp(s.focus.character_index); ++ PlatformTextRange::new_long(&self.context, node.id(), at, at).into() ++ })) ++ })?; ++ if let Some(range) = long_caret { ++ return Ok(range); ++ } ++ self.resolve_for_text_pattern(|node| { ++ if !is_active.is_null() { ++ unsafe { *is_active = node.is_focused().into() }; ++ } ++ let pos = node.text_selection_focus().unwrap_or_else(|| node.document_start()); ++ Ok(PlatformTextRange::new(&self.context, pos.to_degenerate_range()).into()) ++ }) ++ })) ++ .unwrap_or_else(|_| Err(element_not_available())) ++ } ++ )), + (UIA_ExpandCollapsePatternId, IExpandCollapseProvider, IExpandCollapseProvider_Impl, is_expand_collapse_pattern_supported, ( + (UIA_ExpandCollapseExpandCollapseStatePropertyId, ExpandCollapseState, expand_collapse_state, ExpandCollapseState) + ), ( +diff --git a/src/text.rs b/src/text.rs +index 6b18382..c7dfc79 100644 +--- a/src/text.rs ++++ b/src/text.rs +@@ -5,9 +5,12 @@ + + #![allow(non_upper_case_globals)] + +-use accesskit::{Action, ActionData, ActionRequest, ScrollHint, VerticalOffset}; ++use accesskit::{ ++ Action, ActionData, ActionRequest, ScrollHint, TextPosition as WeakPosition, TextSelection, ++ VerticalOffset, ++}; + use accesskit_consumer::{ +- NodeRef, TextPosition as Position, TextRange as Range, Tree, TreeState, ++ FullNodeId, NodeRef, TextPosition as Position, TextRange as Range, Tree, TreeState, + WeakTextRange as WeakRange, + }; + use std::sync::{Arc, RwLock, Weak}; +@@ -19,7 +22,51 @@ use windows::{ + core::*, + }; + +-use crate::{context::Context, util::*}; ++use crate::{ ++ context::Context, ++ long_text::{Text, Unit, bounding_boxes, drawn_lines, drawn_state, long_text}, ++ util::*, ++}; ++ ++/// A range in published text runs, or (Rune) in a long field's value ([`long_text`]). ++#[derive(Clone, PartialEq)] ++enum State { ++ Runs(WeakRange), ++ Long { ++ node: FullNodeId, ++ start: usize, ++ end: usize, ++ }, ++} ++ ++fn runs(state: &State) -> Result<&WeakRange> { ++ match state { ++ State::Runs(range) => Ok(range), ++ State::Long { .. } => Err(invalid_arg()), ++ } ++} ++ ++/// Moves one end of a long field's range, taking the other along if they'd cross. ++fn set_long_endpoint(start: &mut usize, end: &mut usize, endpoint: TextPatternRangeEndpoint, at: usize) { ++ if endpoint == TextPatternRangeEndpoint_Start { ++ *start = at; ++ *end = (*end).max(at); ++ } else { ++ *end = at; ++ *start = (*start).min(at); ++ } ++} ++ ++fn long_unit(unit: TextUnit) -> Result<Unit> { ++ match unit { ++ TextUnit_Character => Ok(Unit::Character), ++ TextUnit_Word => Ok(Unit::Word), ++ TextUnit_Line => Ok(Unit::Line), ++ TextUnit_Paragraph => Ok(Unit::Paragraph), ++ TextUnit_Format | TextUnit_Page | TextUnit_Document => Ok(Unit::Document), ++ _ => Err(invalid_arg()), ++ } ++} + + fn upgrade_range<'a>(weak: &WeakRange, tree_state: &'a TreeState) -> Result<Range<'a>> { + if let Some(range) = weak.upgrade(tree_state) { +@@ -209,17 +256,86 @@ fn move_position( + #[implement(ITextRangeProvider)] + pub(crate) struct PlatformRange { + context: Weak<Context>, +- state: RwLock<WeakRange>, ++ state: RwLock<State>, + } + + impl PlatformRange { + pub(crate) fn new(context: &Weak<Context>, range: Range) -> Self { + Self { + context: context.clone(), +- state: RwLock::new(range.downgrade()), ++ state: RwLock::new(State::Runs(range.downgrade())), ++ } ++ } ++ ++ /// Bytes `start..end` of long field `node`'s value. ++ pub(crate) fn new_long(context: &Weak<Context>, node: FullNodeId, start: usize, end: usize) -> Self { ++ Self { ++ context: context.clone(), ++ state: RwLock::new(State::Long { node, start, end }), ++ } ++ } ++ ++ fn read_state(&self) -> std::sync::RwLockReadGuard<'_, State> { ++ self.state.read().unwrap_or_else(|e| e.into_inner()) ++ } ++ ++ fn write_state(&self) -> std::sync::RwLockWriteGuard<'_, State> { ++ self.state.write().unwrap_or_else(|e| e.into_inner()) ++ } ++ ++ fn is_long(&self) -> bool { ++ matches!(*self.read_state(), State::Long { .. }) ++ } ++ ++ /// Runs `f` on this long field range's text, node and endpoints, which it may move. ++ /// Computes without holding `self.state`'s lock and catches any panic so neither a poisoned ++ /// lock nor an unwind can reach UIA's `extern "system"` ABI. ++ fn long<F, T>(&self, f: F) -> Result<T> ++ where ++ F: FnOnce(Text, NodeRef, &Arc<Context>, &mut usize, &mut usize) -> Result<T>, ++ { ++ uia_catch(|| { ++ let context = self.upgrade_context()?; ++ let tree = context.read_tree(); ++ let (node_id, mut start, mut end) = match *self.read_state() { ++ State::Long { node, start, end } => (node, start, end), ++ State::Runs(_) => return Err(invalid_arg()), ++ }; ++ let node = tree.state().node_by_id(node_id).ok_or_else(element_not_available)?; ++ let (text, _) = long_text(&node).ok_or_else(element_not_available)?; ++ // The value may have changed since the range was made. ++ start = text.clamp(start); ++ end = text.clamp(end).max(start); ++ let res = f(text, node, &context, &mut start, &mut end)?; ++ if let State::Long { start: s, end: e, .. } = &mut *self.write_state() { ++ *s = start; ++ *e = end; ++ } ++ Ok(res) ++ }) ++ } ++ ++ fn long_endpoints(&self) -> Option<(FullNodeId, usize, usize)> { ++ match *self.read_state() { ++ State::Long { node, start, end } => Some((node, start, end)), ++ State::Runs(_) => None, + } + } + ++ fn long_action(&self, action: Action, data: impl FnOnce(NodeRef, usize, usize) -> Option<ActionData>) -> Result<()> { ++ uia_catch(|| { ++ let context = self.upgrade_context()?; ++ let tree = context.read_tree(); ++ let (id, start, end) = self.long_endpoints().ok_or_else(invalid_arg)?; ++ let node = tree.state().node_by_id(id).ok_or_else(element_not_available)?; ++ let (target_node, target_tree) = node.locate(); ++ let data = data(node, start, end); ++ drop(tree); ++ context.do_action(ActionRequest { action, target_tree, target_node, data }); ++ Ok(()) ++ }) ++ } ++ + fn upgrade_context(&self) -> Result<Arc<Context>> { + upgrade(&self.context) + } +@@ -228,9 +344,11 @@ impl PlatformRange { + where + F: FnOnce(&TreeState, &Context) -> Result<T>, + { +- let context = self.upgrade_context()?; +- let tree = context.read_tree(); +- f(tree.state(), &context) ++ uia_catch(|| { ++ let context = self.upgrade_context()?; ++ let tree = context.read_tree(); ++ f(tree.state(), &context) ++ }) + } + + fn with_tree_state<F, T>(&self, f: F) -> Result<T> +@@ -241,13 +359,13 @@ impl PlatformRange { + } + + fn upgrade_node<'a>(&self, tree_state: &'a TreeState) -> Result<NodeRef<'a>> { +- let state = self.state.read().unwrap(); +- upgrade_range_node(&state, tree_state) ++ let state = self.read_state(); ++ upgrade_range_node(runs(&state)?, tree_state) + } + + fn upgrade_for_read<'a>(&self, tree_state: &'a TreeState) -> Result<Range<'a>> { +- let state = self.state.read().unwrap(); +- upgrade_range(&state, tree_state) ++ let state = self.read_state(); ++ upgrade_range(runs(&state)?, tree_state) + } + + fn read_with_context<F, T>(&self, f: F) -> Result<T> +@@ -272,10 +390,10 @@ impl PlatformRange { + F: FnOnce(&mut Range) -> Result<T>, + { + self.with_tree_state(|tree_state| { +- let mut state = self.state.write().unwrap(); +- let mut range = upgrade_range(&state, tree_state)?; ++ let mut state = self.write_state(); ++ let mut range = upgrade_range(runs(&state)?, tree_state)?; + let result = f(&mut range); +- *state = range.downgrade(); ++ *state = State::Runs(range.downgrade()); + result + }) + } +@@ -284,13 +402,15 @@ impl PlatformRange { + where + for<'a> F: FnOnce(Range<'a>, &Tree) -> ActionRequest, + { +- let context = self.upgrade_context()?; +- let tree = context.read_tree(); +- let range = self.upgrade_for_read(tree.state())?; +- let request = f(range, &tree); +- drop(tree); +- context.do_action(request); +- Ok(()) ++ uia_catch(|| { ++ let context = self.upgrade_context()?; ++ let tree = context.read_tree(); ++ let range = self.upgrade_for_read(tree.state())?; ++ let request = f(range, &tree); ++ drop(tree); ++ context.do_action(request); ++ Ok(()) ++ }) + } + + fn require_same_context(&self, other: &PlatformRange) -> Result<()> { +@@ -302,11 +422,16 @@ impl PlatformRange { + } + } + ++fn uia_catch<T>(f: impl FnOnce() -> Result<T>) -> Result<T> { ++ std::panic::catch_unwind(std::panic::AssertUnwindSafe(f)) ++ .unwrap_or_else(|_| Err(element_not_available())) ++} ++ + impl Clone for PlatformRange { + fn clone(&self) -> Self { + PlatformRange { + context: self.context.clone(), +- state: RwLock::new(self.state.read().unwrap().clone()), ++ state: RwLock::new(self.read_state().clone()), + } + } + } +@@ -319,14 +444,16 @@ impl Clone for PlatformRange { + #[allow(non_snake_case)] + impl ITextRangeProvider_Impl for PlatformRange_Impl { + fn Clone(&self) -> Result<ITextRangeProvider> { +- Ok(self.this.clone().into()) ++ uia_catch(|| Ok(self.this.clone().into())) + } + + fn Compare(&self, other: Ref<ITextRangeProvider>) -> Result<BOOL> { +- let other = unsafe { required_param(&other)?.as_impl() }; +- Ok((self.context.ptr_eq(&other.context) +- && *self.state.read().unwrap() == *other.state.read().unwrap()) +- .into()) ++ uia_catch(|| { ++ let other = unsafe { required_param(&other)?.as_impl() }; ++ Ok((self.context.ptr_eq(&other.context) ++ && *self.read_state() == *other.read_state()) ++ .into()) ++ }) + } + + fn CompareEndpoints( +@@ -335,42 +462,73 @@ impl ITextRangeProvider_Impl for PlatformRange_Impl { + other: Ref<ITextRangeProvider>, + other_endpoint: TextPatternRangeEndpoint, + ) -> Result<i32> { +- let other = unsafe { required_param(&other)?.as_impl() }; +- if std::ptr::eq(other as *const _, &self.this as *const _) { +- // Comparing endpoints within the same range can be done +- // safely without upgrading the range. This allows ATs +- // to determine whether an old range is degenerate even if +- // that range is no longer valid. +- let state = self.state.read().unwrap(); +- let other_state = other.state.read().unwrap(); +- let pos = weak_comparable_position_from_endpoint(&state, endpoint)?; +- let other_pos = weak_comparable_position_from_endpoint(&other_state, other_endpoint)?; +- let result = pos.cmp(other_pos); +- return Ok(result as i32); +- } +- self.require_same_context(other)?; +- self.with_tree_state(|tree_state| { +- let range = self.upgrade_for_read(tree_state)?; +- let other_range = other.upgrade_for_read(tree_state)?; +- if range.node().id() != other_range.node().id() { +- return Err(invalid_arg()); ++ uia_catch(|| { ++ let other = unsafe { required_param(&other)?.as_impl() }; ++ if self.is_long() || other.is_long() { ++ let (Some(mine), Some(theirs)) = (self.long_endpoints(), other.long_endpoints()) else { ++ return Err(invalid_arg()); ++ }; ++ let at = |e: TextPatternRangeEndpoint, (node, start, end): (FullNodeId, usize, usize)| match e { ++ _ if node != mine.0 => Err(invalid_arg()), ++ TextPatternRangeEndpoint_Start => Ok(start), ++ TextPatternRangeEndpoint_End => Ok(end), ++ _ => Err(invalid_arg()), ++ }; ++ return Ok(at(endpoint, mine)?.cmp(&at(other_endpoint, theirs)?) as i32); ++ } ++ if std::ptr::eq(other as *const _, &self.this as *const _) { ++ // Comparing endpoints within the same range can be done ++ // safely without upgrading the range. This allows ATs ++ // to determine whether an old range is degenerate even if ++ // that range is no longer valid. ++ let state = self.read_state(); ++ let other_state = other.read_state(); ++ let pos = weak_comparable_position_from_endpoint(runs(&state)?, endpoint)?; ++ let other_pos = weak_comparable_position_from_endpoint(runs(&other_state)?, other_endpoint)?; ++ let result = pos.cmp(other_pos); ++ return Ok(result as i32); + } +- let pos = position_from_endpoint(&range, endpoint)?; +- let other_pos = position_from_endpoint(&other_range, other_endpoint)?; +- let result = pos.partial_cmp(&other_pos).unwrap(); +- Ok(result as i32) ++ self.require_same_context(other)?; ++ self.with_tree_state(|tree_state| { ++ let range = self.upgrade_for_read(tree_state)?; ++ let other_range = other.upgrade_for_read(tree_state)?; ++ if range.node().id() != other_range.node().id() { ++ return Err(invalid_arg()); ++ } ++ let pos = position_from_endpoint(&range, endpoint)?; ++ let other_pos = position_from_endpoint(&other_range, other_endpoint)?; ++ let result = pos.partial_cmp(&other_pos).ok_or_else(invalid_arg)?; ++ Ok(result as i32) ++ }) + }) + } + + fn ExpandToEnclosingUnit(&self, unit: TextUnit) -> Result<()> { ++ if self.is_long() { ++ return self.long(|text, node, _, start, end| { ++ let unit = long_unit(unit)?; ++ if unit == Unit::Character && *start == text.len() { ++ return Ok(()); ++ } ++ if unit == Unit::Line { ++ let state = drawn_state(&node, text); ++ *start = text.start_of_in(*start, unit, &state); ++ *end = if *start == text.len() { *start } else { text.next_in(*start, unit, &state.lines) }; ++ } else { ++ *start = text.start_of(*start, unit); ++ *end = if *start == text.len() { *start } else { text.next(*start, unit) }; ++ } ++ Ok(()) ++ }); ++ } + if unit == TextUnit_Document { + // Handle document as a special case so we can get to a document + // range even if the current endpoints are now invalid. + // Based on observed behavior, Narrator needs this ability. + return self.with_tree_state(|tree_state| { +- let mut state = self.state.write().unwrap(); +- let node = upgrade_range_node(&state, tree_state)?; +- *state = node.document_range().downgrade(); ++ let mut state = self.write_state(); ++ let node = upgrade_range_node(runs(&state)?, tree_state)?; ++ *state = State::Runs(node.document_range().downgrade()); + Ok(()) + }); + } +@@ -417,6 +575,33 @@ impl ITextRangeProvider_Impl for PlatformRange_Impl { + } + + fn GetAttributeValue(&self, id: UIA_TEXTATTRIBUTE_ID) -> Result<VARIANT> { ++ if self.is_long() { ++ return self.long(|text, node, _, start, end| { ++ Ok(match id { ++ UIA_IsReadOnlyAttributeId => node.is_read_only().into(), ++ UIA_CaretPositionAttributeId => { ++ let at = *start; ++ let state = drawn_state(&node, text); ++ let at_hard_end = at == text.len() ++ || text.0.as_bytes().get(at) == Some(&b'\n') ++ || text.0.as_bytes().get(at..at + 2) == Some(b"\r\n"); ++ let value = if at != *end { ++ CaretPosition_Unknown ++ } else if text.is_start_in(at, Unit::Line, &state) { ++ CaretPosition_BeginningOfLine ++ } else if at_hard_end ++ || state.lines.iter().any(|d| d.end == at && d.start < at) ++ { ++ CaretPosition_EndOfLine ++ } else { ++ CaretPosition_Unknown ++ }; ++ value.0.into() ++ } ++ _ => unsafe { UiaGetReservedNotSupportedValue() }.unwrap().into(), ++ }) ++ }); ++ } + self.read(|range| match id { + UIA_IsReadOnlyAttributeId => { + // TBD: do we ever want to support mixed read-only/editable text? +@@ -492,6 +677,23 @@ impl ITextRangeProvider_Impl for PlatformRange_Impl { + } + + fn GetBoundingRectangles(&self) -> Result<*mut SAFEARRAY> { ++ if self.is_long() { ++ return self.long(|text, node, context, start, end| { ++ let rects = bounding_boxes(&node, text, *start, *end); ++ if rects.is_empty() { ++ return Ok(std::ptr::null_mut()); ++ } ++ let client_top_left = context.client_top_left(); ++ let mut result = Vec::<f64>::with_capacity(rects.len() * 4); ++ for rect in rects { ++ result.push(rect.x0 + client_top_left.x); ++ result.push(rect.y0 + client_top_left.y); ++ result.push(rect.width()); ++ result.push(rect.height()); ++ } ++ Ok(safe_array_from_f64_slice(&result)) ++ }); ++ } + self.read_with_context(|range, context| { + let rects = range.bounding_boxes(); + if rects.is_empty() { +@@ -511,13 +713,30 @@ impl ITextRangeProvider_Impl for PlatformRange_Impl { + + fn GetEnclosingElement(&self) -> Result<IRawElementProviderSimple> { + // Revisit this if we eventually support embedded objects. +- let context = self.upgrade_context()?; +- let tree = context.read_tree(); +- let id = self.upgrade_node(tree.state())?.id(); +- Ok(context.get_or_create_platform_node(id).into_interface()) ++ if self.is_long() { ++ return self.long(|_, node, context, _, _| { ++ Ok(context.get_or_create_platform_node(node.id()).into_interface()) ++ }); ++ } ++ uia_catch(|| { ++ let context = self.upgrade_context()?; ++ let tree = context.read_tree(); ++ let id = self.upgrade_node(tree.state())?.id(); ++ Ok(context.get_or_create_platform_node(id).into_interface()) ++ }) + } + +- fn GetText(&self, _max_length: i32) -> Result<BSTR> { ++ fn GetText(&self, max_length: i32) -> Result<BSTR> { ++ if self.is_long() { ++ return self.long(|text, _, _, start, end| { ++ let s = text.slice(*start, *end); ++ let s = match usize::try_from(max_length) { ++ Ok(n) => s.char_indices().nth(n).map_or(s, |(k, _)| &s[..k]), ++ Err(_) => s, ++ }; ++ Ok(BSTR::from(s)) ++ }); ++ } + // The Microsoft docs imply that the provider isn't _required_ + // to truncate text at the max length, so we just ignore it. + self.read(|range| { +@@ -529,6 +748,27 @@ impl ITextRangeProvider_Impl for PlatformRange_Impl { + } + + fn Move(&self, unit: TextUnit, count: i32) -> Result<i32> { ++ if self.is_long() { ++ return self.long(|text, node, _, start, end| { ++ let unit = long_unit(unit)?; ++ let state = (unit == Unit::Line).then(|| drawn_state(&node, text)); ++ let drawn = state.as_ref().map_or(&[][..], |s| s.lines.as_slice()); ++ let degenerate = start == end; ++ let from = if degenerate { ++ *start ++ } else if let Some(st) = &state { ++ text.start_of_in(*start, unit, st) ++ } else { ++ text.start_of(*start, unit) ++ }; ++ let (at, moved) = text.step_in(from, unit, count, drawn); ++ if moved != 0 { ++ *start = at; ++ *end = if degenerate || at == text.len() { at } else { text.next_in(at, unit, drawn) }; ++ } ++ Ok(moved) ++ }); ++ } + self.write(|range| { + let degenerate = range.is_degenerate(); + let start = range.start(); +@@ -557,6 +797,20 @@ impl ITextRangeProvider_Impl for PlatformRange_Impl { + unit: TextUnit, + count: i32, + ) -> Result<i32> { ++ if self.is_long() { ++ return self.long(|text, node, _, start, end| { ++ let unit = long_unit(unit)?; ++ let drawn = if unit == Unit::Line { drawn_lines(&node, text) } else { Vec::new() }; ++ let at = match endpoint { ++ TextPatternRangeEndpoint_Start => *start, ++ TextPatternRangeEndpoint_End => *end, ++ _ => return Err(invalid_arg()), ++ }; ++ let (at, moved) = text.step_in(at, unit, count, &drawn); ++ set_long_endpoint(start, end, endpoint, at); ++ Ok(moved) ++ }); ++ } + self.write(|range| { + let pos = position_from_endpoint(range, endpoint)?; + let (pos, moved) = +@@ -572,26 +826,54 @@ impl ITextRangeProvider_Impl for PlatformRange_Impl { + other: Ref<ITextRangeProvider>, + other_endpoint: TextPatternRangeEndpoint, + ) -> Result<()> { +- let other = unsafe { required_param(&other)?.as_impl() }; +- self.require_same_context(other)?; +- // We have to obtain the tree state and ranges manually to avoid +- // lifetime issues, and work with the two locks in a specific order +- // to avoid deadlock. +- self.with_tree_state(|tree_state| { +- let other_range = other.upgrade_for_read(tree_state)?; +- let mut state = self.state.write().unwrap(); +- let mut range = upgrade_range(&state, tree_state)?; +- if range.node().id() != other_range.node().id() { +- return Err(invalid_arg()); ++ uia_catch(|| { ++ let other = unsafe { required_param(&other)?.as_impl() }; ++ self.require_same_context(other)?; ++ if self.is_long() || other.is_long() { ++ // Read the other range first: it may be this one. ++ let (mine, theirs) = (self.long_endpoints(), other.long_endpoints()); ++ let (Some(mine), Some((node, a, b))) = (mine, theirs) else { ++ return Err(invalid_arg()); ++ }; ++ if node != mine.0 { ++ return Err(invalid_arg()); ++ } ++ let at = match other_endpoint { ++ TextPatternRangeEndpoint_Start => a, ++ TextPatternRangeEndpoint_End => b, ++ _ => return Err(invalid_arg()), ++ }; ++ return self.long(|text, _, _, start, end| { ++ set_long_endpoint(start, end, endpoint, text.clamp(at)); ++ Ok(()) ++ }); + } +- let pos = position_from_endpoint(&other_range, other_endpoint)?; +- set_endpoint_position(&mut range, endpoint, pos)?; +- *state = range.downgrade(); +- Ok(()) ++ // We have to obtain the tree state and ranges manually to avoid ++ // lifetime issues, and work with the two locks in a specific order ++ // to avoid deadlock. ++ self.with_tree_state(|tree_state| { ++ let other_range = other.upgrade_for_read(tree_state)?; ++ let mut state = self.write_state(); ++ let mut range = upgrade_range(runs(&state)?, tree_state)?; ++ if range.node().id() != other_range.node().id() { ++ return Err(invalid_arg()); ++ } ++ let pos = position_from_endpoint(&other_range, other_endpoint)?; ++ set_endpoint_position(&mut range, endpoint, pos)?; ++ *state = State::Runs(range.downgrade()); ++ Ok(()) ++ }) + }) + } + + fn Select(&self) -> Result<()> { ++ if self.is_long() { ++ return self.long_action(Action::SetTextSelection, |node, start, end| { ++ let (id, _) = node.locate(); ++ let at = |character_index| WeakPosition { node: id, character_index }; ++ Some(ActionData::SetTextSelection(TextSelection { anchor: at(start), focus: at(end) })) ++ }); ++ } + self.do_action(|range, tree| { + let (target_node, target_tree) = tree.state().locate_node(range.node().id()).unwrap(); + ActionRequest { +@@ -614,6 +896,9 @@ impl ITextRangeProvider_Impl for PlatformRange_Impl { + } + + fn ScrollIntoView(&self, align_to_top: BOOL) -> Result<()> { ++ if self.is_long() { ++ return self.long_action(Action::ScrollIntoView, |_, _, _| None); ++ } + self.do_action(|range, tree| { + let position = if align_to_top.into() { + range.start() diff --git a/app/vendor/rune/vendor/accesskit_windows/.cargo_vcs_info.json b/app/vendor/rune/vendor/accesskit_windows/.cargo_vcs_info.json new file mode 100644 index 0000000..2c49e39 --- /dev/null +++ b/app/vendor/rune/vendor/accesskit_windows/.cargo_vcs_info.json @@ -0,0 +1,6 @@ +{ + "git": { + "sha1": "f3026222559c7f5f46d8f25cb7404de68eb149f0" + }, + "path_in_vcs": "adapters/windows" +} \ No newline at end of file diff --git a/app/vendor/rune/vendor/accesskit_windows/CHANGELOG.md b/app/vendor/rune/vendor/accesskit_windows/CHANGELOG.md new file mode 100644 index 0000000..5f8d79a --- /dev/null +++ b/app/vendor/rune/vendor/accesskit_windows/CHANGELOG.md @@ -0,0 +1,1056 @@ +# Changelog + +* The following workspace dependencies were updated + * dependencies + * accesskit bumped from 0.8.0 to 0.8.1 + * accesskit_consumer bumped from 0.9.1 to 0.10.0 + +* The following workspace dependencies were updated + * dependencies + * accesskit_consumer bumped from 0.11.0 to 0.12.0 + +* The following workspace dependencies were updated + * dependencies + * accesskit_consumer bumped from 0.12.0 to 0.12.1 + +* The following workspace dependencies were updated + * dependencies + * accesskit bumped from 0.10.1 to 0.11.0 + * accesskit_consumer bumped from 0.14.1 to 0.14.2 + +* The following workspace dependencies were updated + * dependencies + * accesskit bumped from 0.11.0 to 0.11.1 + * accesskit_consumer bumped from 0.15.0 to 0.15.1 + +* The following workspace dependencies were updated + * dependencies + * accesskit bumped from 0.11.1 to 0.11.2 + * accesskit_consumer bumped from 0.15.1 to 0.15.2 + +* The following workspace dependencies were updated + * dependencies + * accesskit bumped from 0.12.2 to 0.12.3 + * accesskit_consumer bumped from 0.17.0 to 0.17.1 + +* The following workspace dependencies were updated + * dependencies + * accesskit bumped from 0.16.2 to 0.16.3 + * accesskit_consumer bumped from 0.24.2 to 0.24.3 + +## [0.35.2](https://github.com/AccessKit/accesskit/compare/accesskit_windows-v0.35.1...accesskit_windows-v0.35.2) (2026-10-25) + + +### Bug Fixes + +* Avoid disclosing the content of password inputs ([#841](https://github.com/AccessKit/accesskit/issues/841)) ([d62a496](https://github.com/AccessKit/accesskit/commit/d62a49614ffbb0d85ce2d34e0340df711eb86e46)) + + +### Dependencies + +* The following workspace dependencies were updated + * dependencies + * accesskit bumped from 0.25.1 to 0.25.2 + * accesskit_consumer bumped from 0.39.1 to 0.39.2 + +## [0.35.1](https://github.com/AccessKit/accesskit/compare/accesskit_windows-v0.35.0...accesskit_windows-v0.35.1) (2026-09-25) + + +### Bug Fixes + +* Update minimum supported Rust version to 1.87 ([#808](https://github.com/AccessKit/accesskit/issues/808)) ([08c6ada](https://github.com/AccessKit/accesskit/commit/08c6ada3594ab12f57844c25d6a16dc8955ff640)) + + +### Dependencies + +* The following workspace dependencies were updated + * dependencies + * accesskit bumped from 0.25.0 to 0.25.1 + * accesskit_consumer bumped from 0.39.0 to 0.39.1 + +## [0.35.0](https://github.com/AccessKit/accesskit/compare/accesskit_windows-v0.34.0...accesskit_windows-v0.35.0) (2026-08-29) + + +### Features + +* Add html_id node property ([#776](https://github.com/AccessKit/accesskit/issues/776)) ([5332ac0](https://github.com/AccessKit/accesskit/commit/5332ac0927b7fb78eff6b8b68c21ef4c801aae7c)) + + +### Bug Fixes + +* Fix imports in Windows tests ([#769](https://github.com/AccessKit/accesskit/issues/769)) ([edbd0ff](https://github.com/AccessKit/accesskit/commit/edbd0ff9a18c3df836a3cee42aac02f9e82fcf8b)) + + +### Dependencies + +* The following workspace dependencies were updated + * dependencies + * accesskit bumped from 0.24.1 to 0.25.0 + * accesskit_consumer bumped from 0.38.0 to 0.39.0 + +## [0.34.0](https://github.com/AccessKit/accesskit/compare/accesskit_windows-v0.33.1...accesskit_windows-v0.34.0) (2026-07-14) + + +### Features + +* Cache Windows node COM objects ([#725](https://github.com/AccessKit/accesskit/issues/725)) ([d7480d9](https://github.com/AccessKit/accesskit/commit/d7480d91212b5ef35203c9cddc962e08d762548b)) + + +### Bug Fixes + +* Avoid spurious wakeups in the Windows adapter test harness ([#722](https://github.com/AccessKit/accesskit/issues/722)) ([b3c109e](https://github.com/AccessKit/accesskit/commit/b3c109ed9271dace83cd5611b0c62af39e3de73d)) +* Update Tree::toolkit_name call sites in the adapters ([27734d8](https://github.com/AccessKit/accesskit/commit/27734d8409d9e03f51caefe1c13ae4ff74e3c6b2)) + + +### Dependencies + +* The following workspace dependencies were updated + * dependencies + * accesskit_consumer bumped from 0.37.0 to 0.38.0 + +## [0.33.1](https://github.com/AccessKit/accesskit/compare/accesskit_windows-v0.33.0...accesskit_windows-v0.33.1) (2026-06-12) + + +### Dependencies + +* The following workspace dependencies were updated + * dependencies + * accesskit bumped from 0.24.0 to 0.24.1 + * accesskit_consumer bumped from 0.36.0 to 0.37.0 + +## [0.33.0](https://github.com/AccessKit/accesskit/compare/accesskit_windows-v0.32.1...accesskit_windows-v0.33.0) (2026-05-11) + + +### ⚠ BREAKING CHANGES + +* Prepare consumer crate and Windows adapter for 2024 edition + +### Features + +* Support tree views on Windows ([#698](https://github.com/AccessKit/accesskit/issues/698)) ([1d3b189](https://github.com/AccessKit/accesskit/commit/1d3b18912ea5f4b0abd37ddb0a771768155fbd7b)) + + +### Code Refactoring + +* Prepare consumer crate and Windows adapter for 2024 edition ([258b2e6](https://github.com/AccessKit/accesskit/commit/258b2e66b741b142c84563ef00f70bf6bc8da9d8)) + + +### Dependencies + +* The following workspace dependencies were updated + * dependencies + * accesskit_consumer bumped from 0.35.0 to 0.36.0 + +## [0.32.1](https://github.com/AccessKit/accesskit/compare/accesskit_windows-v0.32.0...accesskit_windows-v0.32.1) (2026-03-04) + + +### Dependencies + +* The following workspace dependencies were updated + * dependencies + * accesskit_consumer bumped from 0.34.0 to 0.35.0 + +## [0.32.0](https://github.com/AccessKit/accesskit/compare/accesskit_windows-v0.31.1...accesskit_windows-v0.32.0) (2026-02-01) + + +### ⚠ BREAKING CHANGES + +* Update minimum supported Rust version to 1.85 ([#683](https://github.com/AccessKit/accesskit/issues/683)) + +### Bug Fixes + +* Update minimum supported Rust version to 1.85 ([#683](https://github.com/AccessKit/accesskit/issues/683)) ([f8c22cb](https://github.com/AccessKit/accesskit/commit/f8c22cbb53ce6b1859adeff3c0b7154ad9e1f25e)) + + +### Dependencies + +* The following workspace dependencies were updated + * dependencies + * accesskit bumped from 0.23.0 to 0.24.0 + * accesskit_consumer bumped from 0.33.1 to 0.34.0 + +## [0.31.1](https://github.com/AccessKit/accesskit/compare/accesskit_windows-v0.31.0...accesskit_windows-v0.31.1) (2026-01-18) + + +### Bug Fixes + +* Emit initial focus event for active descendant node ([#681](https://github.com/AccessKit/accesskit/issues/681)) ([13a37d1](https://github.com/AccessKit/accesskit/commit/13a37d144e2fafceaf26e7645f6acc679ccb2f34)) + + +### Dependencies + +* The following workspace dependencies were updated + * dependencies + * accesskit_consumer bumped from 0.33.0 to 0.33.1 + +## [0.31.0](https://github.com/AccessKit/accesskit/compare/accesskit_windows-v0.30.0...accesskit_windows-v0.31.0) (2026-01-15) + + +### ⚠ BREAKING CHANGES + +* Multiple tree support ([#655](https://github.com/AccessKit/accesskit/issues/655)) + +### Features + +* Implement the `url` property ([#669](https://github.com/AccessKit/accesskit/issues/669)) ([6202e63](https://github.com/AccessKit/accesskit/commit/6202e63c667e73216a306b3dd45ff25c364a4f45)) +* More text attributes on Windows ([#676](https://github.com/AccessKit/accesskit/issues/676)) ([259e832](https://github.com/AccessKit/accesskit/commit/259e83271371007d7564588939c6aafd0b7b3ac0)) +* Multiple tree support ([#655](https://github.com/AccessKit/accesskit/issues/655)) ([c16eb80](https://github.com/AccessKit/accesskit/commit/c16eb80c49d14f39e8a7defb1694bf22b8ceed6f)) + + +### Dependencies + +* The following workspace dependencies were updated + * dependencies + * accesskit bumped from 0.22.0 to 0.23.0 + * accesskit_consumer bumped from 0.32.0 to 0.33.0 + +## [0.30.0](https://github.com/AccessKit/accesskit/compare/accesskit_windows-v0.29.2...accesskit_windows-v0.30.0) (2025-12-23) + + +### ⚠ BREAKING CHANGES + +* Drop deprecated roles ([#642](https://github.com/AccessKit/accesskit/issues/642)) +* Infrastructure for supporting text formatting changes ([#626](https://github.com/AccessKit/accesskit/issues/626)) + +### Features + +* Add GridCell role ([#643](https://github.com/AccessKit/accesskit/issues/643)) ([1e5abca](https://github.com/AccessKit/accesskit/commit/1e5abca737d1ee942c0804fec2c06d3cb08faa94)) +* Add simple text attributes on Windows ([#659](https://github.com/AccessKit/accesskit/issues/659)) ([f2bfa63](https://github.com/AccessKit/accesskit/commit/f2bfa6322c737be695438d728fdd2d9451b3b7e9)) +* Implement BrailleLabel and BrailleRoleDescription roles ([#638](https://github.com/AccessKit/accesskit/issues/638)) ([0fdcebb](https://github.com/AccessKit/accesskit/commit/0fdcebb55e308e039ec99fbc31e94e8087a69f2d)) +* Implement the UIA `Culture` property ([#631](https://github.com/AccessKit/accesskit/issues/631)) ([06fc934](https://github.com/AccessKit/accesskit/commit/06fc934d96e4ca0f0610edcbe9add3abec3486cd)) +* Rename HeaderAsNonLandmark to SectionHeader, FooterAsNonLandmark to SectionFooter ([#635](https://github.com/AccessKit/accesskit/issues/635)) ([dd69526](https://github.com/AccessKit/accesskit/commit/dd695260877cb862ece4c2b7d8607308f5fed608)) + + +### Bug Fixes + +* Cast font size to `f64` on Windows ([#664](https://github.com/AccessKit/accesskit/issues/664)) ([a45124d](https://github.com/AccessKit/accesskit/commit/a45124d6824b31fe720cc711ca2646017f63f7f1)) +* Expose dialogs in the platform adapters ([1576a94](https://github.com/AccessKit/accesskit/commit/1576a940ec3e9066fc5e181419dae6899bf2db46)) +* expose more node data to UIA in aria_properties ([fa15c84](https://github.com/AccessKit/accesskit/commit/fa15c84fecbe97da889ec75d26fae98fce93b500)) +* Extend AriaRoleProperty in Windows adapter ([#648](https://github.com/AccessKit/accesskit/issues/648)) ([4b8e01a](https://github.com/AccessKit/accesskit/commit/4b8e01a4c5c4373d8a4ce9721418c719cfe5a7a0)) +* Upgrade hashbrown, indexmap ([#653](https://github.com/AccessKit/accesskit/issues/653)) ([fd73a85](https://github.com/AccessKit/accesskit/commit/fd73a85e57a6591a449b0a1880025fb940873c66)) + + +### Code Refactoring + +* Drop deprecated roles ([#642](https://github.com/AccessKit/accesskit/issues/642)) ([4d46c27](https://github.com/AccessKit/accesskit/commit/4d46c2740631c5fe4f057707b949d12b26931d0b)) +* Infrastructure for supporting text formatting changes ([#626](https://github.com/AccessKit/accesskit/issues/626)) ([ea23ec4](https://github.com/AccessKit/accesskit/commit/ea23ec424c7dbb8841e03d71b6a15b74264850a9)) + + +### Dependencies + +* The following workspace dependencies were updated + * dependencies + * accesskit bumped from 0.21.1 to 0.22.0 + * accesskit_consumer bumped from 0.31.0 to 0.32.0 + +## [0.29.2](https://github.com/AccessKit/accesskit/compare/accesskit_windows-v0.29.1...accesskit_windows-v0.29.2) (2025-10-20) + + +### Dependencies + +* The following workspace dependencies were updated + * dependencies + * accesskit_consumer bumped from 0.30.1 to 0.31.0 + +## [0.29.1](https://github.com/AccessKit/accesskit/compare/accesskit_windows-v0.29.0...accesskit_windows-v0.29.1) (2025-10-02) + + +### Dependencies + +* The following workspace dependencies were updated + * dependencies + * accesskit bumped from 0.21.0 to 0.21.1 + * accesskit_consumer bumped from 0.30.0 to 0.30.1 + +## [0.29.0](https://github.com/AccessKit/accesskit/compare/accesskit_windows-v0.28.0...accesskit_windows-v0.29.0) (2025-07-16) + + +### ⚠ BREAKING CHANGES + +* Implement refactored `ScrollIntoView` action across desktop platforms ([#594](https://github.com/AccessKit/accesskit/issues/594)) + +### Features + +* Implement refactored `ScrollIntoView` action across desktop platforms ([#594](https://github.com/AccessKit/accesskit/issues/594)) ([1d9b74c](https://github.com/AccessKit/accesskit/commit/1d9b74c057051509b3ffbf63afeacfb16f544ff8)) +* Let parents declare actions supported on their children ([#593](https://github.com/AccessKit/accesskit/issues/593)) ([70b534b](https://github.com/AccessKit/accesskit/commit/70b534bed168a84b84cc35199588aa8ab784fb43)) + + +### Bug Fixes + +* Panic if the subclassing adapter is double-instantiated ([#596](https://github.com/AccessKit/accesskit/issues/596)) ([0598573](https://github.com/AccessKit/accesskit/commit/05985732f0611a9ac96eb458e586c6dd3c1a131d)) + + +### Dependencies + +* The following workspace dependencies were updated + * dependencies + * accesskit bumped from 0.20.0 to 0.21.0 + * accesskit_consumer bumped from 0.29.0 to 0.30.0 + +## [0.28.0](https://github.com/AccessKit/accesskit/compare/accesskit_windows-v0.27.0...accesskit_windows-v0.28.0) (2025-06-26) + + +### ⚠ BREAKING CHANGES + +* Force a semver-breaking release ([#589](https://github.com/AccessKit/accesskit/issues/589)) + +### Bug Fixes + +* Force a semver-breaking release ([#589](https://github.com/AccessKit/accesskit/issues/589)) ([2887cdd](https://github.com/AccessKit/accesskit/commit/2887cddde817ba3851688068d8d10de5cef7c624)) + + +### Dependencies + +* The following workspace dependencies were updated + * dependencies + * accesskit bumped from 0.19.0 to 0.20.0 + * accesskit_consumer bumped from 0.28.0 to 0.29.0 + +## [0.27.0](https://github.com/AccessKit/accesskit/compare/accesskit_windows-v0.26.0...accesskit_windows-v0.27.0) (2025-05-06) + + +### ⚠ BREAKING CHANGES + +* Drop redundant `HasPopup::True` ([#550](https://github.com/AccessKit/accesskit/issues/550)) + +### Bug Fixes + +* Expose tabs in the platform adapters ([341a11b](https://github.com/AccessKit/accesskit/commit/341a11bca2c8a29682c11ddcfe91fa58776ea11d)) +* Update windows-rs to 0.61 ([#541](https://github.com/AccessKit/accesskit/issues/541)) ([2f86c45](https://github.com/AccessKit/accesskit/commit/2f86c453a776956ca36c06c9689be22323646421)) + + +### Code Refactoring + +* Drop redundant `HasPopup::True` ([#550](https://github.com/AccessKit/accesskit/issues/550)) ([56abf17](https://github.com/AccessKit/accesskit/commit/56abf17356e4c7f13f64aaeaca6a63c8f7ede553)) + + +### Dependencies + +* The following workspace dependencies were updated + * dependencies + * accesskit bumped from 0.18.0 to 0.19.0 + * accesskit_consumer bumped from 0.27.0 to 0.28.0 + +## [0.26.0](https://github.com/AccessKit/accesskit/compare/accesskit_windows-v0.25.0...accesskit_windows-v0.26.0) (2025-03-17) + + +### ⚠ BREAKING CHANGES + +* Panic if the window is visible when the adapter is created, for adapters where this is a problem ([#529](https://github.com/AccessKit/accesskit/issues/529)) + +### Bug Fixes + +* Eliminate the dependency on `paste` ([#528](https://github.com/AccessKit/accesskit/issues/528)) ([4aef05d](https://github.com/AccessKit/accesskit/commit/4aef05d0b34b434c0f0ce2e7583adef3e73bda4d)) +* Panic if the window is visible when the adapter is created, for adapters where this is a problem ([#529](https://github.com/AccessKit/accesskit/issues/529)) ([c43c37b](https://github.com/AccessKit/accesskit/commit/c43c37ba2502656fcae4fd726b9b7db0bb520f31)) + +## [0.25.0](https://github.com/AccessKit/accesskit/compare/accesskit_windows-v0.24.1...accesskit_windows-v0.25.0) (2025-03-06) + + +### ⚠ BREAKING CHANGES + +* Optimize simple string getters ([#493](https://github.com/AccessKit/accesskit/issues/493)) +* Drop `Tree::app_name` ([#492](https://github.com/AccessKit/accesskit/issues/492)) + +### Features + +* Expose the `is_required` property ([#497](https://github.com/AccessKit/accesskit/issues/497)) ([46ed99b](https://github.com/AccessKit/accesskit/commit/46ed99bb958ddb32cbf1bee2fcfb7b328bcbe0ab)) + + +### Bug Fixes + +* Add list box support to the platform adapters ([6c622cf](https://github.com/AccessKit/accesskit/commit/6c622cff4c0c989d9a5f16b775adff9cdacf534c)) +* Derive `Debug` for adapters ([#513](https://github.com/AccessKit/accesskit/issues/513)) ([753d904](https://github.com/AccessKit/accesskit/commit/753d90473cf57682568c7a17c82474c8e5d00b25)) +* Expose password input fields on Windows ([#516](https://github.com/AccessKit/accesskit/issues/516)) ([19514da](https://github.com/AccessKit/accesskit/commit/19514dabc40bcfc01bee1b1efa77355ec5b0822b)) +* Fix some clippy warnings ([#509](https://github.com/AccessKit/accesskit/issues/509)) ([579b9c1](https://github.com/AccessKit/accesskit/commit/579b9c12dd8abc44ecab41fa3c326a1d8999871d)) +* Optimize dynamic string building ([#491](https://github.com/AccessKit/accesskit/issues/491)) ([a86901d](https://github.com/AccessKit/accesskit/commit/a86901ddea5d5ba72ab237e98b53d6adcc6087bb)) +* Remove unnecessary explicit lifetimes ([#488](https://github.com/AccessKit/accesskit/issues/488)) ([d2bcd6d](https://github.com/AccessKit/accesskit/commit/d2bcd6d3048d23df4e132bee6171eb247b2dc2c8)) + + +### Code Refactoring + +* Drop `Tree::app_name` ([#492](https://github.com/AccessKit/accesskit/issues/492)) ([089794c](https://github.com/AccessKit/accesskit/commit/089794c8f74957e91a19ae3df508e2a892f39ebc)) +* Optimize simple string getters ([#493](https://github.com/AccessKit/accesskit/issues/493)) ([484fd7c](https://github.com/AccessKit/accesskit/commit/484fd7cbfb778222369d3f57d31dd998f6fa80d8)) + + +### Dependencies + +* The following workspace dependencies were updated + * dependencies + * accesskit bumped from 0.17.1 to 0.18.0 + * accesskit_consumer bumped from 0.26.0 to 0.27.0 + +## [0.24.1](https://github.com/AccessKit/accesskit/compare/accesskit_windows-v0.24.0...accesskit_windows-v0.24.1) (2024-11-23) + + +### Bug Fixes + +* Optimize use of hash tables in platform adapters ([#485](https://github.com/AccessKit/accesskit/issues/485)) ([f4f0bfb](https://github.com/AccessKit/accesskit/commit/f4f0bfbf21b8e22e80ab07deb432f9e7e16469ab)) +* Tell docs.rs to only build accesskit_windows on Windows ([#483](https://github.com/AccessKit/accesskit/issues/483)) ([1fead29](https://github.com/AccessKit/accesskit/commit/1fead296ed012f83afb482021051ccc1d4946167)) + + +### Dependencies + +* The following workspace dependencies were updated + * dependencies + * accesskit bumped from 0.17.0 to 0.17.1 + * accesskit_consumer bumped from 0.25.0 to 0.26.0 + +## [0.24.0](https://github.com/AccessKit/accesskit/compare/accesskit_windows-v0.23.2...accesskit_windows-v0.24.0) (2024-10-31) + + +### ⚠ BREAKING CHANGES + +* Rename `name` to `label` and use `value` for label content ([#475](https://github.com/AccessKit/accesskit/issues/475)) +* Rename `NodeBuilder` to `Node` and the old `Node` to `FrozenNode` ([#476](https://github.com/AccessKit/accesskit/issues/476)) +* Rename `Role::InlineTextBox` to `TextRun` ([#473](https://github.com/AccessKit/accesskit/issues/473)) +* Drop `DefaultActionVerb` ([#472](https://github.com/AccessKit/accesskit/issues/472)) +* Make the core crate no-std ([#468](https://github.com/AccessKit/accesskit/issues/468)) + +### Features + +* Make the core crate no-std ([#468](https://github.com/AccessKit/accesskit/issues/468)) ([2fa0d3f](https://github.com/AccessKit/accesskit/commit/2fa0d3f5b2b7ac11ef1751c133706f29e548bd6d)) + + +### Code Refactoring + +* Drop `DefaultActionVerb` ([#472](https://github.com/AccessKit/accesskit/issues/472)) ([ef3b003](https://github.com/AccessKit/accesskit/commit/ef3b0038224459094f650368412650bc3b69526b)) +* Rename `name` to `label` and use `value` for label content ([#475](https://github.com/AccessKit/accesskit/issues/475)) ([e0053a5](https://github.com/AccessKit/accesskit/commit/e0053a5399929e8e0d4f07aa18de604ed8766ace)) +* Rename `NodeBuilder` to `Node` and the old `Node` to `FrozenNode` ([#476](https://github.com/AccessKit/accesskit/issues/476)) ([7d8910e](https://github.com/AccessKit/accesskit/commit/7d8910e35f7bc0543724cc124941a3bd0304bcc0)) +* Rename `Role::InlineTextBox` to `TextRun` ([#473](https://github.com/AccessKit/accesskit/issues/473)) ([29fa341](https://github.com/AccessKit/accesskit/commit/29fa34125a811bd3a0f9da579a9f35c9da90bf29)) + + +### Dependencies + +* The following workspace dependencies were updated + * dependencies + * accesskit bumped from 0.16.3 to 0.17.0 + * accesskit_consumer bumped from 0.24.3 to 0.25.0 + +## [0.23.1](https://github.com/AccessKit/accesskit/compare/accesskit_windows-v0.23.0...accesskit_windows-v0.23.1) (2024-10-07) + + +### Bug Fixes + +* Update minimum supported Rust version to 1.75 ([#457](https://github.com/AccessKit/accesskit/issues/457)) ([fc622fe](https://github.com/AccessKit/accesskit/commit/fc622fe7657c80a4eedad6f6cded11d2538b54d5)) + + +### Dependencies + +* The following workspace dependencies were updated + * dependencies + * accesskit bumped from 0.16.1 to 0.16.2 + * accesskit_consumer bumped from 0.24.1 to 0.24.2 + +## [0.23.0](https://github.com/AccessKit/accesskit/compare/accesskit_windows-v0.22.0...accesskit_windows-v0.23.0) (2024-09-24) + + +### ⚠ BREAKING CHANGES + +* Update windows to 0.58 on accesskit_windows ([#453](https://github.com/AccessKit/accesskit/issues/453)) + +### Bug Fixes + +* Update windows to 0.58 on accesskit_windows ([#453](https://github.com/AccessKit/accesskit/issues/453)) ([cda35e7](https://github.com/AccessKit/accesskit/commit/cda35e77a78f72386c2bfd88e9fd29000106f7e6)) +* Use the new HWND type on accesskit_winit ([#453](https://github.com/AccessKit/accesskit/issues/453)) ([68a2462](https://github.com/AccessKit/accesskit/commit/68a24629381f0b18f6ed1ee008fe72ce9330092e)) + + +### Dependencies + +* The following workspace dependencies were updated + * dependencies + * accesskit bumped from 0.16.0 to 0.16.1 + * accesskit_consumer bumped from 0.24.0 to 0.24.1 + +## [0.22.0](https://github.com/AccessKit/accesskit/compare/accesskit_windows-v0.21.0...accesskit_windows-v0.22.0) (2024-06-29) + + +### ⚠ BREAKING CHANGES + +* Rename the `StaticText` role to `Label` ([#434](https://github.com/AccessKit/accesskit/issues/434)) + +### Code Refactoring + +* Rename the `StaticText` role to `Label` ([#434](https://github.com/AccessKit/accesskit/issues/434)) ([7086bc0](https://github.com/AccessKit/accesskit/commit/7086bc0fad446d3ed4a0fd5eff641a1e75f6c599)) + + +### Dependencies + +* The following workspace dependencies were updated + * dependencies + * accesskit bumped from 0.15.0 to 0.16.0 + * accesskit_consumer bumped from 0.23.0 to 0.24.0 + +## [0.21.0](https://github.com/AccessKit/accesskit/compare/accesskit_windows-v0.20.0...accesskit_windows-v0.21.0) (2024-06-09) + + +### Features + +* Add `author_id` property ([#424](https://github.com/AccessKit/accesskit/issues/424)) ([0d1c56f](https://github.com/AccessKit/accesskit/commit/0d1c56f0bdde58715e1c69f6015df600cb7cb8c1)) + + +### Dependencies + +* The following workspace dependencies were updated + * dependencies + * accesskit bumped from 0.14.0 to 0.15.0 + * accesskit_consumer bumped from 0.22.0 to 0.23.0 + +## [0.20.0](https://github.com/AccessKit/accesskit/compare/accesskit_windows-v0.19.0...accesskit_windows-v0.20.0) (2024-05-27) + + +### Features + +* Expose the `orientation` property ([#421](https://github.com/AccessKit/accesskit/issues/421)) ([590aada](https://github.com/AccessKit/accesskit/commit/590aada070dc812f9b8f171fb9e43ac984fad2a1)) + + +### Dependencies + +* The following workspace dependencies were updated + * dependencies + * accesskit_consumer bumped from 0.21.0 to 0.22.0 + +## [0.19.0](https://github.com/AccessKit/accesskit/compare/accesskit_windows-v0.18.2...accesskit_windows-v0.19.0) (2024-05-26) + + +### Features + +* Expose the `placeholder` property ([#417](https://github.com/AccessKit/accesskit/issues/417)) ([8f4a0a1](https://github.com/AccessKit/accesskit/commit/8f4a0a1c10f83fcc8580a37d8013fec2d110865b)) + + +### Dependencies + +* The following workspace dependencies were updated + * dependencies + * accesskit_consumer bumped from 0.20.0 to 0.21.0 + +## [0.18.2](https://github.com/AccessKit/accesskit/compare/accesskit_windows-v0.18.1...accesskit_windows-v0.18.2) (2024-05-13) + + +### Bug Fixes + +* Fix platform adapters to support copy-on-write tree snapshots again ([#411](https://github.com/AccessKit/accesskit/issues/411)) ([d3a130a](https://github.com/AccessKit/accesskit/commit/d3a130a5ec8ae1d9edf0bf85a44f35f0e365242c)) + + +### Dependencies + +* The following workspace dependencies were updated + * dependencies + * accesskit_consumer bumped from 0.19.1 to 0.20.0 + +## [0.18.1](https://github.com/AccessKit/accesskit/compare/accesskit_windows-v0.18.0...accesskit_windows-v0.18.1) (2024-05-11) + + +### Bug Fixes + +* Make the transition from placeholder to real tree more robust ([#405](https://github.com/AccessKit/accesskit/issues/405)) ([928e11d](https://github.com/AccessKit/accesskit/commit/928e11d00e7c60b3cafcc0ac623f6377b36f7ea7)) + + +### Dependencies + +* The following workspace dependencies were updated + * dependencies + * accesskit_consumer bumped from 0.19.0 to 0.19.1 + +## [0.18.0](https://github.com/AccessKit/accesskit/compare/accesskit_windows-v0.17.0...accesskit_windows-v0.18.0) (2024-04-30) + + +### ⚠ BREAKING CHANGES + +* Update winit to 0.30 ([#397](https://github.com/AccessKit/accesskit/issues/397)) +* Clean up table roles and properties ([#393](https://github.com/AccessKit/accesskit/issues/393)) +* Drop `NodeClassSet` ([#389](https://github.com/AccessKit/accesskit/issues/389)) +* Rename `Checked` to `Toggled`; drop `ToggleButton` role ([#388](https://github.com/AccessKit/accesskit/issues/388)) + +### Features + +* Expose the class name property ([#385](https://github.com/AccessKit/accesskit/issues/385)) ([53dcf2a](https://github.com/AccessKit/accesskit/commit/53dcf2ae47546273590c46a9b31b708aa1409837)) +* Implement the `description` property ([#382](https://github.com/AccessKit/accesskit/issues/382)) ([d49f406](https://github.com/AccessKit/accesskit/commit/d49f40660b5dc23ed074cd72a91e511b130756ae)) + + +### Bug Fixes + +* Increase minimum supported Rust version to `1.70` ([#396](https://github.com/AccessKit/accesskit/issues/396)) ([a8398b8](https://github.com/AccessKit/accesskit/commit/a8398b847aa003de91042ac45e33126fc2cae053)) +* Update winit to 0.30 ([#397](https://github.com/AccessKit/accesskit/issues/397)) ([de93be3](https://github.com/AccessKit/accesskit/commit/de93be387c03a438fbf598670207e578686e6bcf)) + + +### Code Refactoring + +* Clean up table roles and properties ([#393](https://github.com/AccessKit/accesskit/issues/393)) ([e34dad9](https://github.com/AccessKit/accesskit/commit/e34dad94448a5321ece9def3f2e054aa5f62dd79)) +* Drop `NodeClassSet` ([#389](https://github.com/AccessKit/accesskit/issues/389)) ([1b153ed](https://github.com/AccessKit/accesskit/commit/1b153ed51f8421cdba2dc98beca2e8f5f8c781bc)) +* Rename `Checked` to `Toggled`; drop `ToggleButton` role ([#388](https://github.com/AccessKit/accesskit/issues/388)) ([6bc040b](https://github.com/AccessKit/accesskit/commit/6bc040b7cf75cdbd6a019cc380d8dbce804b3c81)) + + +### Dependencies + +* The following workspace dependencies were updated + * dependencies + * accesskit bumped from 0.13.0 to 0.14.0 + * accesskit_consumer bumped from 0.18.0 to 0.19.0 + +## [0.17.0](https://github.com/AccessKit/accesskit/compare/accesskit_windows-v0.16.4...accesskit_windows-v0.17.0) (2024-04-14) + + +### ⚠ BREAKING CHANGES + +* New approach to lazy initialization ([#375](https://github.com/AccessKit/accesskit/issues/375)) + +### Code Refactoring + +* New approach to lazy initialization ([#375](https://github.com/AccessKit/accesskit/issues/375)) ([9baebdc](https://github.com/AccessKit/accesskit/commit/9baebdceed7300389b6768815d7ae48f1ce401e4)) + + +### Dependencies + +* The following workspace dependencies were updated + * dependencies + * accesskit bumped from 0.12.3 to 0.13.0 + * accesskit_consumer bumped from 0.17.1 to 0.18.0 + +## [0.16.4](https://github.com/AccessKit/accesskit/compare/accesskit_windows-v0.16.3...accesskit_windows-v0.16.4) (2024-03-18) + + +### Bug Fixes + +* Update `windows` to `0.54` ([#373](https://github.com/AccessKit/accesskit/issues/373)) ([50f112f](https://github.com/AccessKit/accesskit/commit/50f112f0085a03f0180f86915d2ac4e5845f6b63)) + +## [0.16.2](https://github.com/AccessKit/accesskit/compare/accesskit_windows-v0.16.1...accesskit_windows-v0.16.2) (2024-02-25) + + +### Bug Fixes + +* Bump windows-rs dependency to 0.52 ([#359](https://github.com/AccessKit/accesskit/issues/359)) ([69d74f6](https://github.com/AccessKit/accesskit/commit/69d74f6947922b76d4aee683eb53d8fbdd2259f2)) + +## [0.16.1](https://github.com/AccessKit/accesskit/compare/accesskit_windows-v0.16.0...accesskit_windows-v0.16.1) (2024-02-24) + + +### Bug Fixes + +* Avoid `unnecessary_literal_unwrap` clippy lint ([#346](https://github.com/AccessKit/accesskit/issues/346)) ([59a6eae](https://github.com/AccessKit/accesskit/commit/59a6eae40ba35069b90d4cc0b765d838f8477c66)) + +## [0.16.0](https://github.com/AccessKit/accesskit/compare/accesskit_windows-v0.15.1...accesskit_windows-v0.16.0) (2024-01-03) + + +### Features + +* Support custom role descriptions ([#316](https://github.com/AccessKit/accesskit/issues/316)) ([c8d1a56](https://github.com/AccessKit/accesskit/commit/c8d1a5638fa6c33adfa059815c04f7e043c56026)) + + +### Dependencies + +* The following workspace dependencies were updated + * dependencies + * accesskit bumped from 0.12.1 to 0.12.2 + * accesskit_consumer bumped from 0.16.1 to 0.17.0 + +## [0.15.1](https://github.com/AccessKit/accesskit/compare/accesskit_windows-v0.15.0...accesskit_windows-v0.15.1) (2023-11-04) + + +### Bug Fixes + +* Make the test focus event handler thread-safe again ([#306](https://github.com/AccessKit/accesskit/issues/306)) ([bb479c6](https://github.com/AccessKit/accesskit/commit/bb479c69bddff77a1102549a7ff6ea5c7155d90d)) +* Make the Windows subclassing test more robust ([#308](https://github.com/AccessKit/accesskit/issues/308)) ([0078f79](https://github.com/AccessKit/accesskit/commit/0078f7997f11a3bb1f3c33dc7a91f427b1a60db8)) + + +### Dependencies + +* The following workspace dependencies were updated + * dependencies + * accesskit bumped from 0.12.0 to 0.12.1 + * accesskit_consumer bumped from 0.16.0 to 0.16.1 + +## [0.15.0](https://github.com/AccessKit/accesskit/compare/accesskit_windows-v0.14.3...accesskit_windows-v0.15.0) (2023-09-27) + + +### ⚠ BREAKING CHANGES + +* Allow providing app_name, toolkit_name and toolkit_version in Tree, remove parameters from unix adapter constructor ([#291](https://github.com/AccessKit/accesskit/issues/291)) +* Make `ActionHandler::do_action` take `&mut self` ([#296](https://github.com/AccessKit/accesskit/issues/296)) +* Clean up roles and properties ([#289](https://github.com/AccessKit/accesskit/issues/289)) +* Decouple in-tree focus from host window/view focus ([#278](https://github.com/AccessKit/accesskit/issues/278)) +* Switch to simple unsigned 64-bit integer for node IDs ([#276](https://github.com/AccessKit/accesskit/issues/276)) + +### Features + +* Add role for terminals ([#282](https://github.com/AccessKit/accesskit/issues/282)) ([ddbef37](https://github.com/AccessKit/accesskit/commit/ddbef37158b57f56217317b480e40d58f83a9c24)) +* Allow providing app_name, toolkit_name and toolkit_version in Tree, remove parameters from unix adapter constructor ([#291](https://github.com/AccessKit/accesskit/issues/291)) ([5313860](https://github.com/AccessKit/accesskit/commit/531386023257150f49b5e4be942f359855fb7cb6)) + + +### Bug Fixes + +* Support text fields without a value property ([#274](https://github.com/AccessKit/accesskit/issues/274)) ([5ae557b](https://github.com/AccessKit/accesskit/commit/5ae557b40d395b4a9966a90a2d80e7d97ad50bf9)) +* Use common filters across platform adapters ([#287](https://github.com/AccessKit/accesskit/issues/287)) ([09c1204](https://github.com/AccessKit/accesskit/commit/09c12045ff4ccdb22f0cf643077a27465013572d)) + + +### Code Refactoring + +* Clean up roles and properties ([#289](https://github.com/AccessKit/accesskit/issues/289)) ([4fc9c55](https://github.com/AccessKit/accesskit/commit/4fc9c55c91812472593923d93ff89d75ff305ee4)) +* Decouple in-tree focus from host window/view focus ([#278](https://github.com/AccessKit/accesskit/issues/278)) ([d360d20](https://github.com/AccessKit/accesskit/commit/d360d20cf951e7643b81a5303006c9f7daa5bd56)) +* Make `ActionHandler::do_action` take `&mut self` ([#296](https://github.com/AccessKit/accesskit/issues/296)) ([4fc7846](https://github.com/AccessKit/accesskit/commit/4fc7846d732d61fb45c023060ebab96801a0053e)) +* Switch to simple unsigned 64-bit integer for node IDs ([#276](https://github.com/AccessKit/accesskit/issues/276)) ([3eadd48](https://github.com/AccessKit/accesskit/commit/3eadd48ec47854faa94a94ebf910ec08f514642f)) + + +### Dependencies + +* The following workspace dependencies were updated + * dependencies + * accesskit bumped from 0.11.2 to 0.12.0 + * accesskit_consumer bumped from 0.15.2 to 0.16.0 + +## [0.14.3](https://github.com/AccessKit/accesskit/compare/accesskit_windows-v0.14.2...accesskit_windows-v0.14.3) (2023-08-08) + + +### Bug Fixes + +* Update windows crate to v0.48 ([#257](https://github.com/AccessKit/accesskit/issues/257)) ([cc703ed](https://github.com/AccessKit/accesskit/commit/cc703ed33d535aa1803e423a53beff9354b5b0df)) + +## [0.14.0](https://github.com/AccessKit/accesskit/compare/accesskit_windows-v0.13.3...accesskit_windows-v0.14.0) (2023-03-30) + + +### ⚠ BREAKING CHANGES + +* Force a semver-breaking version bump in downstream crates ([#234](https://github.com/AccessKit/accesskit/issues/234)) + +### Bug Fixes + +* Force a semver-breaking version bump in downstream crates ([#234](https://github.com/AccessKit/accesskit/issues/234)) ([773389b](https://github.com/AccessKit/accesskit/commit/773389bff857fa18edf15de426e029251fc34591)) + + +### Dependencies + +* The following workspace dependencies were updated + * dependencies + * accesskit_consumer bumped from 0.14.2 to 0.15.0 + +## [0.13.2](https://github.com/AccessKit/accesskit/compare/accesskit_windows-v0.13.1...accesskit_windows-v0.13.2) (2023-02-23) + + +### Bug Fixes + +* Fix Windows 32-bit build errors ([#223](https://github.com/AccessKit/accesskit/issues/223)) ([41f28b6](https://github.com/AccessKit/accesskit/commit/41f28b670ac457b2d067bbc4ba40aa0fc8842e4d)) + +## [0.13.1](https://github.com/AccessKit/accesskit/compare/accesskit_windows-v0.13.0...accesskit_windows-v0.13.1) (2023-02-20) + + +### Bug Fixes + +* Update windows-rs to 0.44 ([#220](https://github.com/AccessKit/accesskit/issues/220)) ([a6b0a12](https://github.com/AccessKit/accesskit/commit/a6b0a124e7511e37760d769b517fd5fc9050160b)) + + +### Dependencies + +* The following workspace dependencies were updated + * dependencies + * accesskit bumped from 0.10.0 to 0.10.1 + * accesskit_consumer bumped from 0.14.0 to 0.14.1 + +## [0.13.0](https://github.com/AccessKit/accesskit/compare/accesskit_windows-v0.12.0...accesskit_windows-v0.13.0) (2023-02-12) + + +### ⚠ BREAKING CHANGES + +* Move thread synchronization into platform adapters; drop parking_lot ([#212](https://github.com/AccessKit/accesskit/issues/212)) + +### Code Refactoring + +* Move thread synchronization into platform adapters; drop parking_lot ([#212](https://github.com/AccessKit/accesskit/issues/212)) ([5df52e5](https://github.com/AccessKit/accesskit/commit/5df52e5545faddf6a51905409013c2f5be23981e)) + + +### Dependencies + +* The following workspace dependencies were updated + * dependencies + * accesskit bumped from 0.9.0 to 0.10.0 + * accesskit_consumer bumped from 0.13.0 to 0.14.0 + +## [0.12.0](https://github.com/AccessKit/accesskit/compare/accesskit_windows-v0.11.0...accesskit_windows-v0.12.0) (2023-02-05) + + +### ⚠ BREAKING CHANGES + +* Make `Node` opaque and optimize it for size ([#205](https://github.com/AccessKit/accesskit/issues/205)) + +### Code Refactoring + +* Make `Node` opaque and optimize it for size ([#205](https://github.com/AccessKit/accesskit/issues/205)) ([4811152](https://github.com/AccessKit/accesskit/commit/48111521439b76c1a8687418a4b20f9b705eac6d)) + + +### Dependencies + +* The following workspace dependencies were updated + * dependencies + * accesskit bumped from 0.8.1 to 0.9.0 + * accesskit_consumer bumped from 0.12.1 to 0.13.0 + +## [0.11.0](https://github.com/AccessKit/accesskit/compare/accesskit_windows-v0.10.4...accesskit_windows-v0.11.0) (2023-02-02) + + +### ⚠ BREAKING CHANGES + +* Update winit to 0.28 ([#207](https://github.com/AccessKit/accesskit/issues/207)) + +### Miscellaneous Chores + +* Update winit to 0.28 ([#207](https://github.com/AccessKit/accesskit/issues/207)) ([3ff0cf5](https://github.com/AccessKit/accesskit/commit/3ff0cf59f982af504499142a3804f7aeeb4defe0)) + +## [0.10.2](https://github.com/AccessKit/accesskit/compare/accesskit_windows-v0.10.1...accesskit_windows-v0.10.2) (2022-12-17) + + +### Bug Fixes + +* Correct broken UIA method implementation that was incompatible with Windows 11 ATs ([#193](https://github.com/AccessKit/accesskit/issues/193)) ([3c527c7](https://github.com/AccessKit/accesskit/commit/3c527c76cb4139402d2b5550d2eb1ad12e07ebe5)) +* More reliable handling of the edge case for wrapped lines ([#192](https://github.com/AccessKit/accesskit/issues/192)) ([c626d2c](https://github.com/AccessKit/accesskit/commit/c626d2c3028085b076ada7dd31242cf3ca3c0f08)) +* Provide fallback property implementations for the window root ([#194](https://github.com/AccessKit/accesskit/issues/194)) ([f3d30b9](https://github.com/AccessKit/accesskit/commit/f3d30b9ba2f66e08fb7f78c304ab8a9e83e1aeca)) + + +### Dependencies + +* The following workspace dependencies were updated + * dependencies + * accesskit_consumer bumped from 0.10.0 to 0.11.0 + +## [0.10.0](https://github.com/AccessKit/accesskit/compare/accesskit_windows-v0.9.3...accesskit_windows-v0.10.0) (2022-11-29) + + +### ⚠ BREAKING CHANGES + +* Move lazy initialization from the core platform adapter to the caller ([#179](https://github.com/AccessKit/accesskit/issues/179)) + +### Code Refactoring + +* Move lazy initialization from the core platform adapter to the caller ([#179](https://github.com/AccessKit/accesskit/issues/179)) ([f35c941](https://github.com/AccessKit/accesskit/commit/f35c941f395f3162db376a69cfaaaf770d376267)) + +### [0.9.3](https://www.github.com/AccessKit/accesskit/compare/accesskit_windows-v0.9.2...accesskit_windows-v0.9.3) (2022-11-25) + + +### Bug Fixes + +* Gracefully handle nodes that only support text ranges some of the time ([#169](https://www.github.com/AccessKit/accesskit/issues/169)) ([1f50df6](https://www.github.com/AccessKit/accesskit/commit/1f50df6820b9d23fe2e579f043f4981acf285de2)) +* **platforms/windows:** Change default minimum and maximum for range value pattern ([#166](https://www.github.com/AccessKit/accesskit/issues/166)) ([176ec58](https://www.github.com/AccessKit/accesskit/commit/176ec5853ca127b1e12f9a992b75478177a4acce)) + + +### Dependencies + +* The following workspace dependencies were updated + * dependencies + * accesskit_consumer bumped from 0.9.0 to 0.9.1 + +### [0.9.2](https://www.github.com/AccessKit/accesskit/compare/accesskit_windows-v0.9.1...accesskit_windows-v0.9.2) (2022-11-24) + + +### Bug Fixes + +* **platforms/windows:** Re-export more types from windows-rs ([#162](https://www.github.com/AccessKit/accesskit/issues/162)) ([eed692b](https://www.github.com/AccessKit/accesskit/commit/eed692b27407e1ddd5f200464f0e2d52a272b958)) + +### [0.9.1](https://www.github.com/AccessKit/accesskit/compare/accesskit_windows-v0.9.0...accesskit_windows-v0.9.1) (2022-11-23) + + +### Bug Fixes + +* **platforms/windows:** Re-export the windows-rs HWND type ([#159](https://www.github.com/AccessKit/accesskit/issues/159)) ([389187a](https://www.github.com/AccessKit/accesskit/commit/389187ac5e96895ed1763d14d315d2f8f4256460)) + + +### Dependencies + +* The following workspace dependencies were updated + * dependencies + * accesskit_consumer bumped from 0.8.0 to 0.9.0 + +## [0.9.0](https://www.github.com/AccessKit/accesskit/compare/accesskit_windows-v0.8.0...accesskit_windows-v0.9.0) (2022-11-17) + + +### ⚠ BREAKING CHANGES + +* **consumer:** Eliminate the dependency on `im` due to licensing (#153) + +### Code Refactoring + +* **consumer:** Eliminate the dependency on `im` due to licensing ([#153](https://www.github.com/AccessKit/accesskit/issues/153)) ([b4c4cb5](https://www.github.com/AccessKit/accesskit/commit/b4c4cb5713d4833d8ee7979e4f4e39c7e96a3ed4)) + + +### Dependencies + +* The following workspace dependencies were updated + * dependencies + * accesskit bumped from 0.7.0 to 0.8.0 + * accesskit_consumer bumped from 0.7.1 to 0.8.0 + +## [0.8.0](https://www.github.com/AccessKit/accesskit/compare/accesskit_windows-v0.7.0...accesskit_windows-v0.8.0) (2022-11-12) + + +### ⚠ BREAKING CHANGES + +* **platforms/windows:** Update to windows-rs 0.42.0 (#148) + +### Bug Fixes + +* **consumer, platforms/windows, platforms/winit:** Update to parking_lot 0.12.1 ([#146](https://www.github.com/AccessKit/accesskit/issues/146)) ([6772855](https://www.github.com/AccessKit/accesskit/commit/6772855a7b540fd728faad15d8d208b05c1bbd8a)) +* **platforms/windows:** Update to windows-rs 0.42.0 ([#148](https://www.github.com/AccessKit/accesskit/issues/148)) ([70d1a89](https://www.github.com/AccessKit/accesskit/commit/70d1a89f51fd6c3a32b7192d9d7f3937db09d196)) + + +### Dependencies + +* The following workspace dependencies were updated + * dependencies + * accesskit_consumer bumped from 0.7.0 to 0.7.1 + +## [0.7.0](https://www.github.com/AccessKit/accesskit/compare/accesskit_windows-v0.6.1...accesskit_windows-v0.7.0) (2022-11-11) + + +### ⚠ BREAKING CHANGES + +* Text range support (#145) +* Drop the `ignored` field and implement generic filtered tree traversal (#143) + +### Features + +* Text range support ([#145](https://www.github.com/AccessKit/accesskit/issues/145)) ([455e6f7](https://www.github.com/AccessKit/accesskit/commit/455e6f73bc058644d299c06eeeda9cc4cbe8844f)) + + +### Code Refactoring + +* Drop the `ignored` field and implement generic filtered tree traversal ([#143](https://www.github.com/AccessKit/accesskit/issues/143)) ([a4befe6](https://www.github.com/AccessKit/accesskit/commit/a4befe6e8a5afbe4a52dfd09eb87fdf2078d6c1d)) + + +### Dependencies + +* The following workspace dependencies were updated + * dependencies + * accesskit bumped from 0.6.1 to 0.7.0 + * accesskit_consumer bumped from 0.6.1 to 0.7.0 + +### [0.6.1](https://www.github.com/AccessKit/accesskit/compare/accesskit_windows-v0.6.0...accesskit_windows-v0.6.1) (2022-10-10) + + +### Dependencies + +* The following workspace dependencies were updated + * dependencies + * accesskit bumped from 0.6.0 to 0.6.1 + * accesskit_consumer bumped from 0.6.0 to 0.6.1 + +## [0.6.0](https://www.github.com/AccessKit/accesskit/compare/accesskit_windows-v0.5.1...accesskit_windows-v0.6.0) (2022-10-09) + + +### ⚠ BREAKING CHANGES + +* **consumer:** Optimize tree access and change handling (#134) +* Wrap `TreeUpdate` nodes in `Arc` (#135) +* **consumer:** Make `Node::data` private to the crate (#137) +* Store node ID in `TreeUpdate`, not `accesskit::Node` (#132) + +### Code Refactoring + +* **consumer:** Make `Node::data` private to the crate ([#137](https://www.github.com/AccessKit/accesskit/issues/137)) ([adb372d](https://www.github.com/AccessKit/accesskit/commit/adb372dda78d183c7189966e3bbc2d3780070513)) +* **consumer:** Optimize tree access and change handling ([#134](https://www.github.com/AccessKit/accesskit/issues/134)) ([765ab74](https://www.github.com/AccessKit/accesskit/commit/765ab74efcf10a3b3871dc901d28f3cf1ff6020c)) +* Store node ID in `TreeUpdate`, not `accesskit::Node` ([#132](https://www.github.com/AccessKit/accesskit/issues/132)) ([0bb86dd](https://www.github.com/AccessKit/accesskit/commit/0bb86ddb298cb5a253a91f07be0bad8b84b2fda3)) +* Wrap `TreeUpdate` nodes in `Arc` ([#135](https://www.github.com/AccessKit/accesskit/issues/135)) ([907bc18](https://www.github.com/AccessKit/accesskit/commit/907bc1820b80d95833b6c5c3acaa2a8a4e93a6c2)) + + +### Dependencies + +* The following workspace dependencies were updated + * dependencies + * accesskit bumped from 0.5.1 to 0.6.0 + * accesskit_consumer bumped from 0.5.1 to 0.6.0 + +### [0.5.1](https://www.github.com/AccessKit/accesskit/compare/accesskit_windows-v0.5.0...accesskit_windows-v0.5.1) (2022-10-03) + + +### Dependencies + +* The following workspace dependencies were updated + * dependencies + * accesskit bumped from 0.5.0 to 0.5.1 + * accesskit_consumer bumped from 0.5.0 to 0.5.1 + +## [0.5.0](https://www.github.com/AccessKit/accesskit/compare/accesskit_windows-v0.4.0...accesskit_windows-v0.5.0) (2022-09-23) + + +### ⚠ BREAKING CHANGES + +* Basic live regions (#128) +* **platforms/windows:** Bump windows-rs dependency (#126) + +### Features + +* Basic live regions ([#128](https://www.github.com/AccessKit/accesskit/issues/128)) ([03d745b](https://www.github.com/AccessKit/accesskit/commit/03d745b891147175bde2693cc10b96a2f6e31f39)) + + +### Miscellaneous Chores + +* **platforms/windows:** Bump windows-rs dependency ([#126](https://www.github.com/AccessKit/accesskit/issues/126)) ([472a75e](https://www.github.com/AccessKit/accesskit/commit/472a75e4214b90396f3282f247df08100ed8362d)) + + +### Dependencies + +* The following workspace dependencies were updated + * dependencies + * accesskit bumped from 0.4.0 to 0.5.0 + * accesskit_consumer bumped from 0.4.0 to 0.5.0 + +## [0.4.0](https://www.github.com/AccessKit/accesskit/compare/accesskit_windows-v0.3.0...accesskit_windows-v0.4.0) (2022-07-22) + + +### ⚠ BREAKING CHANGES + +* String indices are always in UTF-8 code units (#114) +* **platforms/windows:** Refactor window subclassing to avoid lifetime issue (#120) +* **platforms/windows:** Simplify the adapter API by always boxing the tree source (#119) +* Drop unused tree IDs (#113) +* **platforms/windows:** Migrate to windows-rs 0.37 (#109) +* Switch to NonZeroU128 for NodeIDs (#99) + +### Features + +* **platforms/windows:** Win32 subclassing support ([#118](https://www.github.com/AccessKit/accesskit/issues/118)) ([60c69b7](https://www.github.com/AccessKit/accesskit/commit/60c69b7b8a18ca8db62a84495b9e71a6e8140204)) +* **platforms/winit:** New winit adapter ([#121](https://www.github.com/AccessKit/accesskit/issues/121)) ([fdc274e](https://www.github.com/AccessKit/accesskit/commit/fdc274e7d3a901873d2ad0c7a4824a19111787ef)) + + +### Bug Fixes + +* **consumer, platforms/windows:** Resolve new clippy warning ([#100](https://www.github.com/AccessKit/accesskit/issues/100)) ([e8cd95c](https://www.github.com/AccessKit/accesskit/commit/e8cd95c3741b39b77e4ddc8ce82efdc20f93f096)) +* Migrate to 2021 edition ([#115](https://www.github.com/AccessKit/accesskit/issues/115)) ([f2333c8](https://www.github.com/AccessKit/accesskit/commit/f2333c8ce17d46aab6fc190338ab4cfcf8569f9e)) +* **platforms/windows:** Print usage text to the terminal from the Windows example ([#103](https://www.github.com/AccessKit/accesskit/issues/103)) ([7fba3ce](https://www.github.com/AccessKit/accesskit/commit/7fba3ce55345d7787f08d2ae60d841dd13b27693)) +* **platforms/windows:** Restore the optimization of the FragmentRoot method ([#116](https://www.github.com/AccessKit/accesskit/issues/116)) ([d48c31b](https://www.github.com/AccessKit/accesskit/commit/d48c31b41f35baebe59bb654b38dd48265062b14)) +* Switch to NonZeroU128 for NodeIDs ([#99](https://www.github.com/AccessKit/accesskit/issues/99)) ([25a1a52](https://www.github.com/AccessKit/accesskit/commit/25a1a52c4562b163bfcc8c625a233c00a41aacf2)) + + +### Miscellaneous Chores + +* **platforms/windows:** Migrate to windows-rs 0.37 ([#109](https://www.github.com/AccessKit/accesskit/issues/109)) ([1065e11](https://www.github.com/AccessKit/accesskit/commit/1065e11421176a8abc37ef579cb47d973c968462)) + + +### Code Refactoring + +* Drop unused tree IDs ([#113](https://www.github.com/AccessKit/accesskit/issues/113)) ([ca60770](https://www.github.com/AccessKit/accesskit/commit/ca607702cee13c93fe538d2faec88e474261f7ab)) +* **platforms/windows:** Refactor window subclassing to avoid lifetime issue ([#120](https://www.github.com/AccessKit/accesskit/issues/120)) ([37579aa](https://www.github.com/AccessKit/accesskit/commit/37579aa8dd0c019ffaf4eac1b0bf1f7a8c719323)) +* **platforms/windows:** Simplify the adapter API by always boxing the tree source ([#119](https://www.github.com/AccessKit/accesskit/issues/119)) ([27d5c78](https://www.github.com/AccessKit/accesskit/commit/27d5c78afa0f8d1ae3b626265da8bccd3e5b09d1)) +* String indices are always in UTF-8 code units ([#114](https://www.github.com/AccessKit/accesskit/issues/114)) ([386ca0a](https://www.github.com/AccessKit/accesskit/commit/386ca0a89c42fd201843f617b2fd6b6d1de77f59)) + + +### Dependencies + +* The following workspace dependencies were updated + * dependencies + * accesskit bumped from 0.3.0 to 0.4.0 + * accesskit_consumer bumped from 0.3.0 to 0.4.0 + +## [0.3.0](https://www.github.com/AccessKit/accesskit/compare/accesskit_windows-v0.2.0...accesskit_windows-v0.3.0) (2021-12-29) + + +### ⚠ BREAKING CHANGES + +* Drop `TreeUpdate::clear` (#96) + +### Code Refactoring + +* Drop `TreeUpdate::clear` ([#96](https://www.github.com/AccessKit/accesskit/issues/96)) ([38f520b](https://www.github.com/AccessKit/accesskit/commit/38f520b960c6db7b3927b369aee206ee6bc5e8aa)) + + + +### Dependencies + +* The following workspace dependencies were updated + * dependencies + * accesskit bumped from 0.2.0 to 0.3.0 + * accesskit_consumer bumped from 0.2.0 to 0.3.0 diff --git a/app/vendor/rune/vendor/accesskit_windows/Cargo.lock b/app/vendor/rune/vendor/accesskit_windows/Cargo.lock new file mode 100644 index 0000000..8d24c9b --- /dev/null +++ b/app/vendor/rune/vendor/accesskit_windows/Cargo.lock @@ -0,0 +1,1928 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "ab_glyph" +version = "0.2.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe21446ad43aa56417a767f3e2f3d7c4ca522904de1dd640529a76e9c5c3b33c" +dependencies = [ + "ab_glyph_rasterizer", + "owned_ttf_parser", +] + +[[package]] +name = "ab_glyph_rasterizer" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c71b1793ee61086797f5c80b6efa2b8ffa6d5dd703f118545808a7f2e27f7046" + +[[package]] +name = "accesskit" +version = "0.25.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e883d1d28c5fd5568c79ed2d2bd48d9f2fd3945c8974ed0f53690ceddb051be" +dependencies = [ + "uuid", +] + +[[package]] +name = "accesskit_consumer" +version = "0.39.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f3da8f27636015191b2264ee1df681503170a632cafd832fdc1edfdd4e3a2fd3" +dependencies = [ + "accesskit", + "hashbrown", +] + +[[package]] +name = "accesskit_windows" +version = "0.35.2" +dependencies = [ + "accesskit", + "accesskit_consumer", + "hashbrown", + "parking_lot", + "raw-window-handle", + "scopeguard", + "static_assertions", + "windows", + "windows-core", + "winit", +] + +[[package]] +name = "ahash" +version = "0.8.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e89da841a80418a9b391ebaea17f5c112ffaaa96f621d2c285b5174da76b9011" +dependencies = [ + "cfg-if", + "getrandom", + "once_cell", + "version_check", + "zerocopy", +] + +[[package]] +name = "android-activity" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ef6978589202a00cd7e118380c448a08b6ed394c3a8df3a430d0898e3a42d046" +dependencies = [ + "android-properties", + "bitflags 2.8.0", + "cc", + "cesu8", + "jni", + "jni-sys", + "libc", + "log", + "ndk", + "ndk-context", + "ndk-sys", + "num_enum", + "thiserror", +] + +[[package]] +name = "android-properties" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc7eb209b1518d6bb87b283c20095f5228ecda460da70b44f0802523dea6da04" + +[[package]] +name = "arrayref" +version = "0.3.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4c527152e37cf757a3f78aae5a06fbeefdb07ccc535c980a3208ee3060dd544" + +[[package]] +name = "arrayvec" +version = "0.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8da52d66c7071e2e3fa2a1e5c6d088fec47b593032b254f5e980de8ea54454d6" + +[[package]] +name = "as-raw-xcb-connection" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2d5f312b0a56c5cdf967c0aeb67f6289603354951683bc97ddc595ab974ba9aa" + +[[package]] +name = "atomic-waker" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" + +[[package]] +name = "autocfg" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d468802bab17cbc0cc575e9b053f41e72aa36bfa6b7f55e3529ffa43161b97fa" + +[[package]] +name = "bitflags" +version = "1.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" + +[[package]] +name = "bitflags" +version = "2.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f68f53c83ab957f72c32642f3868eec03eb974d1fb82e453128456482613d36" + +[[package]] +name = "block2" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2c132eebf10f5cad5289222520a4a058514204aed6d791f1cf4fe8088b82d15f" +dependencies = [ + "objc2", +] + +[[package]] +name = "bumpalo" +version = "3.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d261e256854913907f67ed06efbc3338dfe6179796deefc1ff763fc1aee5535" + +[[package]] +name = "bytemuck" +version = "1.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "17febce684fd15d89027105661fec94afb475cb995fbc59d2865198446ba2eea" + +[[package]] +name = "bytes" +version = "1.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e748733b7cbc798e1434b6ac524f0c1ff2ab456fe201501e6497c8417a4fc33" + +[[package]] +name = "calloop" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b99da2f8558ca23c71f4fd15dc57c906239752dd27ff3c00a1d56b685b7cbfec" +dependencies = [ + "bitflags 2.8.0", + "log", + "polling", + "rustix", + "slab", + "thiserror", +] + +[[package]] +name = "calloop-wayland-source" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "95a66a987056935f7efce4ab5668920b5d0dac4a7c99991a67395f13702ddd20" +dependencies = [ + "calloop", + "rustix", + "wayland-backend", + "wayland-client", +] + +[[package]] +name = "cc" +version = "1.0.79" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "50d30906286121d95be3d479533b458f87493b30a4b5f79a607db8f5d11aa91f" +dependencies = [ + "jobserver", +] + +[[package]] +name = "cesu8" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6d43a04d8753f35258c91f8ec639f792891f748a1edbd759cf1dcea3382ad83c" + +[[package]] +name = "cfg-if" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" + +[[package]] +name = "cfg_aliases" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "613afe47fcd5fac7ccf1db93babcb082c5994d996f20b8b159f2ad1658eb5724" + +[[package]] +name = "combine" +version = "4.6.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "35ed6e9d84f0b51a7f52daf1c7d71dd136fd7a3f41a8462b8cdb8c78d920fad4" +dependencies = [ + "bytes", + "memchr", +] + +[[package]] +name = "concurrent-queue" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ca0197aee26d1ae37445ee532fefce43251d24cc7c166799f4d46817f1d3973" +dependencies = [ + "crossbeam-utils", +] + +[[package]] +name = "core-foundation" +version = "0.9.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "194a7a9e6de53fa55116934067c844d9d749312f75c6f6d0980e8c252f8c2146" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "core-foundation-sys" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5827cebf4670468b8772dd191856768aedcb1b0278a04f989f7766351917b9dc" + +[[package]] +name = "core-graphics" +version = "0.23.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "970a29baf4110c26fedbc7f82107d42c23f7e88e404c4577ed73fe99ff85a212" +dependencies = [ + "bitflags 1.3.2", + "core-foundation", + "core-graphics-types", + "foreign-types", + "libc", +] + +[[package]] +name = "core-graphics-types" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2bb142d41022986c1d8ff29103a1411c8a3dfad3552f87a4f8dc50d61d4f4e33" +dependencies = [ + "bitflags 1.3.2", + "core-foundation", + "libc", +] + +[[package]] +name = "crossbeam-utils" +version = "0.8.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c063cd8cc95f5c377ed0d4b49a4b21f632396ff690e8470c29b3359b346984b" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "cursor-icon" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "96a6ac251f4a2aca6b3f91340350eab87ae57c3f127ffeb585e92bd336717991" + +[[package]] +name = "dispatch" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bd0c93bb4b0c6d9b77f4435b0ae98c24d17f1c45b2ff844c6151a07256ca923b" + +[[package]] +name = "dlib" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "330c60081dcc4c72131f8eb70510f1ac07223e5d4163db481a04a0befcffa412" +dependencies = [ + "libloading", +] + +[[package]] +name = "downcast-rs" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ea835d29036a4087793836fa931b08837ad5e957da9e23886b29586fb9b6650" + +[[package]] +name = "dpi" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f25c0e292a7ca6d6498557ff1df68f32c99850012b6ea401cf8daf771f22ff53" + +[[package]] +name = "equivalent" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5443807d6dff69373d433ab9ef5378ad8df50ca6298caf15de6e52e24aaf54d5" + +[[package]] +name = "errno" +version = "0.3.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33d852cb9b869c2a9b3df2f71a3074817f01e1844f839a144f5fcef059a4eb5d" +dependencies = [ + "libc", + "windows-sys 0.59.0", +] + +[[package]] +name = "foldhash" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" + +[[package]] +name = "foreign-types" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d737d9aa519fb7b749cbc3b962edcf310a8dd1f4b67c91c4f83975dbdd17d965" +dependencies = [ + "foreign-types-macros", + "foreign-types-shared", +] + +[[package]] +name = "foreign-types-macros" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1a5c6c585bc94aaf2c7b51dd4c2ba22680844aba4c687be581871a6f518c5742" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "foreign-types-shared" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aa9a19cbb55df58761df49b23516a86d432839add4af60fc256da840f66ed35b" + +[[package]] +name = "gethostname" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0176e0459c2e4a1fe232f984bca6890e681076abb9934f6cea7c326f3fc47818" +dependencies = [ + "libc", + "windows-targets 0.48.1", +] + +[[package]] +name = "getrandom" +version = "0.2.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c05aeb6a22b8f62540c194aac980f2115af067bfe15a0734d7277a768d396b31" +dependencies = [ + "cfg-if", + "libc", + "wasi", +] + +[[package]] +name = "hashbrown" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" +dependencies = [ + "foldhash", +] + +[[package]] +name = "hermit-abi" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fbf6a919d6cf397374f7dfeeea91d974c7c0a7221d0d0f4f20d859d329e53fcc" + +[[package]] +name = "indexmap" +version = "2.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d466e9454f08e4a911e14806c24e16fba1b4c121d1ea474396f396069cf949d9" +dependencies = [ + "equivalent", + "hashbrown", +] + +[[package]] +name = "jni" +version = "0.21.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1a87aa2bb7d2af34197c04845522473242e1aa17c12f4935d5856491a7fb8c97" +dependencies = [ + "cesu8", + "cfg-if", + "combine", + "jni-sys", + "log", + "thiserror", + "walkdir", + "windows-sys 0.45.0", +] + +[[package]] +name = "jni-sys" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8eaf4bc02d17cbdd7ff4c7438cafcdf7fb9a4613313ad11b4f8fefe7d3fa0130" + +[[package]] +name = "jobserver" +version = "0.1.26" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "936cfd212a0155903bcbc060e316fb6cc7cbf2e1907329391ebadc1fe0ce77c2" +dependencies = [ + "libc", +] + +[[package]] +name = "js-sys" +version = "0.3.77" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1cfaf33c695fc6e08064efbc1f72ec937429614f25eef83af942d0e227c3a28f" +dependencies = [ + "once_cell", + "wasm-bindgen", +] + +[[package]] +name = "libc" +version = "0.2.189" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2" + +[[package]] +name = "libloading" +version = "0.8.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc2f4eb4bc735547cfed7c0a4922cbd04a4655978c09b54f1f7b228750664c34" +dependencies = [ + "cfg-if", + "windows-targets 0.52.6", +] + +[[package]] +name = "libredox" +version = "0.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3af92c55d7d839293953fcd0fda5ecfe93297cfde6ffbdec13b41d99c0ba6607" +dependencies = [ + "bitflags 2.8.0", + "libc", + "redox_syscall 0.4.1", +] + +[[package]] +name = "linux-raw-sys" +version = "0.4.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d26c52dbd32dccf2d10cac7725f8eae5296885fb5703b261f7d0a0739ec807ab" + +[[package]] +name = "lock_api" +version = "0.4.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "96936507f153605bddfcda068dd804796c84324ed2510809e5b2a624c81da765" +dependencies = [ + "autocfg", + "scopeguard", +] + +[[package]] +name = "log" +version = "0.4.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "abb12e687cfb44aa40f41fc3978ef76448f9b6038cad6aef4259d3c095a2382e" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "memmap2" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "deaba38d7abf1d4cca21cc89e932e542ba2b9258664d2a9ef0e61512039c9375" +dependencies = [ + "libc", +] + +[[package]] +name = "minimal-lexical" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a" + +[[package]] +name = "ndk" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3f42e7bbe13d351b6bead8286a43aac9534b82bd3cc43e47037f012ebfd62d4" +dependencies = [ + "bitflags 2.8.0", + "jni-sys", + "log", + "ndk-sys", + "num_enum", + "raw-window-handle", + "thiserror", +] + +[[package]] +name = "ndk-context" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27b02d87554356db9e9a873add8782d4ea6e3e58ea071a9adb9a2e8ddb884a8b" + +[[package]] +name = "ndk-sys" +version = "0.6.0+11769913" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee6cda3051665f1fb8d9e08fc35c96d5a244fb1be711a03b71118828afc9a873" +dependencies = [ + "jni-sys", +] + +[[package]] +name = "nom" +version = "7.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d273983c5a657a70a3e8f2a01329822f3b8c8172b73826411a55751e404a0a4a" +dependencies = [ + "memchr", + "minimal-lexical", +] + +[[package]] +name = "num_enum" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e613fc340b2220f734a8595782c551f1250e969d87d3be1ae0579e8d4065179" +dependencies = [ + "num_enum_derive", +] + +[[package]] +name = "num_enum_derive" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af1844ef2428cc3e1cb900be36181049ef3d3193c63e43026cfe202983b27a56" +dependencies = [ + "proc-macro-crate", + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "objc-sys" +version = "0.3.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cdb91bdd390c7ce1a8607f35f3ca7151b65afc0ff5ff3b34fa350f7d7c7e4310" + +[[package]] +name = "objc2" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "46a785d4eeff09c14c487497c162e92766fbb3e4059a71840cecc03d9a50b804" +dependencies = [ + "objc-sys", + "objc2-encode", +] + +[[package]] +name = "objc2-app-kit" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e4e89ad9e3d7d297152b17d39ed92cd50ca8063a89a9fa569046d41568891eff" +dependencies = [ + "bitflags 2.8.0", + "block2", + "libc", + "objc2", + "objc2-core-data", + "objc2-core-image", + "objc2-foundation", + "objc2-quartz-core", +] + +[[package]] +name = "objc2-cloud-kit" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "74dd3b56391c7a0596a295029734d3c1c5e7e510a4cb30245f8221ccea96b009" +dependencies = [ + "bitflags 2.8.0", + "block2", + "objc2", + "objc2-core-location", + "objc2-foundation", +] + +[[package]] +name = "objc2-contacts" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a5ff520e9c33812fd374d8deecef01d4a840e7b41862d849513de77e44aa4889" +dependencies = [ + "block2", + "objc2", + "objc2-foundation", +] + +[[package]] +name = "objc2-core-data" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "617fbf49e071c178c0b24c080767db52958f716d9eabdf0890523aeae54773ef" +dependencies = [ + "bitflags 2.8.0", + "block2", + "objc2", + "objc2-foundation", +] + +[[package]] +name = "objc2-core-image" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "55260963a527c99f1819c4f8e3b47fe04f9650694ef348ffd2227e8196d34c80" +dependencies = [ + "block2", + "objc2", + "objc2-foundation", + "objc2-metal", +] + +[[package]] +name = "objc2-core-location" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "000cfee34e683244f284252ee206a27953279d370e309649dc3ee317b37e5781" +dependencies = [ + "block2", + "objc2", + "objc2-contacts", + "objc2-foundation", +] + +[[package]] +name = "objc2-encode" +version = "4.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ef25abbcd74fb2609453eb695bd2f860d389e457f67dc17cafc8b8cbc89d0c33" + +[[package]] +name = "objc2-foundation" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ee638a5da3799329310ad4cfa62fbf045d5f56e3ef5ba4149e7452dcf89d5a8" +dependencies = [ + "bitflags 2.8.0", + "block2", + "dispatch", + "libc", + "objc2", +] + +[[package]] +name = "objc2-link-presentation" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a1a1ae721c5e35be65f01a03b6d2ac13a54cb4fa70d8a5da293d7b0020261398" +dependencies = [ + "block2", + "objc2", + "objc2-app-kit", + "objc2-foundation", +] + +[[package]] +name = "objc2-metal" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dd0cba1276f6023976a406a14ffa85e1fdd19df6b0f737b063b95f6c8c7aadd6" +dependencies = [ + "bitflags 2.8.0", + "block2", + "objc2", + "objc2-foundation", +] + +[[package]] +name = "objc2-quartz-core" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e42bee7bff906b14b167da2bac5efe6b6a07e6f7c0a21a7308d40c960242dc7a" +dependencies = [ + "bitflags 2.8.0", + "block2", + "objc2", + "objc2-foundation", + "objc2-metal", +] + +[[package]] +name = "objc2-symbols" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0a684efe3dec1b305badae1a28f6555f6ddd3bb2c2267896782858d5a78404dc" +dependencies = [ + "objc2", + "objc2-foundation", +] + +[[package]] +name = "objc2-ui-kit" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8bb46798b20cd6b91cbd113524c490f1686f4c4e8f49502431415f3512e2b6f" +dependencies = [ + "bitflags 2.8.0", + "block2", + "objc2", + "objc2-cloud-kit", + "objc2-core-data", + "objc2-core-image", + "objc2-core-location", + "objc2-foundation", + "objc2-link-presentation", + "objc2-quartz-core", + "objc2-symbols", + "objc2-uniform-type-identifiers", + "objc2-user-notifications", +] + +[[package]] +name = "objc2-uniform-type-identifiers" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "44fa5f9748dbfe1ca6c0b79ad20725a11eca7c2218bceb4b005cb1be26273bfe" +dependencies = [ + "block2", + "objc2", + "objc2-foundation", +] + +[[package]] +name = "objc2-user-notifications" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "76cfcbf642358e8689af64cee815d139339f3ed8ad05103ed5eaf73db8d84cb3" +dependencies = [ + "bitflags 2.8.0", + "block2", + "objc2", + "objc2-core-location", + "objc2-foundation", +] + +[[package]] +name = "once_cell" +version = "1.21.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "42f5e15c9953c5e4ccceeb2e7382a716482c34515315f7b03532b8b4e8393d2d" + +[[package]] +name = "orbclient" +version = "0.3.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52f0d54bde9774d3a51dcf281a5def240c71996bc6ca05d2c847ec8b2b216166" +dependencies = [ + "libredox", +] + +[[package]] +name = "owned_ttf_parser" +version = "0.18.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e25e9fb15717794fae58ab55c26e044103aad13186fbb625893f9a3bbcc24228" +dependencies = [ + "ttf-parser", +] + +[[package]] +name = "parking_lot" +version = "0.12.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "70d58bf43669b5795d1576d0641cfb6fbb2057bf629506267a92807158584a13" +dependencies = [ + "lock_api", + "parking_lot_core", +] + +[[package]] +name = "parking_lot_core" +version = "0.9.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bc838d2a56b5b1a6c25f55575dfc605fabb63bb2365f6c2353ef9159aa69e4a5" +dependencies = [ + "cfg-if", + "libc", + "redox_syscall 0.5.13", + "smallvec", + "windows-targets 0.52.6", +] + +[[package]] +name = "percent-encoding" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "478c572c3d73181ff3c2539045f6eb99e5491218eae919370993b890cdbdd98e" + +[[package]] +name = "pin-project" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6bf43b791c5b9e34c3d182969b4abb522f9343702850a2e57f460d00d09b4b3" +dependencies = [ + "pin-project-internal", +] + +[[package]] +name = "pin-project-internal" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f38a4412a78282e09a2cf38d195ea5420d15ba0602cb375210efbc877243965" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "pin-project-lite" +version = "0.2.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8afb450f006bf6385ca15ef45d71d2288452bc3683ce2e2cacc0d18e4be60b58" + +[[package]] +name = "pkg-config" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7edddbd0b52d732b21ad9a5fab5c704c14cd949e5e9a1ec5929a24fded1b904c" + +[[package]] +name = "polling" +version = "3.7.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a604568c3202727d1507653cb121dbd627a58684eb09a820fd746bee38b4442f" +dependencies = [ + "cfg-if", + "concurrent-queue", + "hermit-abi", + "pin-project-lite", + "rustix", + "tracing", + "windows-sys 0.59.0", +] + +[[package]] +name = "proc-macro-crate" +version = "3.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e67ba7e9b2b56446f1d419b1d807906278ffa1a658a8a5d8a39dcb1f5a78614f" +dependencies = [ + "toml_edit", +] + +[[package]] +name = "proc-macro2" +version = "1.0.106" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quick-xml" +version = "0.41.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e660451e55124f798a69a5af3f49ccfbefbd41910eefd25caf2393e1f3473ec1" +dependencies = [ + "memchr", +] + +[[package]] +name = "quote" +version = "1.0.37" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b5b9d34b8991d19d98081b46eacdd8eb58c6f2b201139f7c5f643cc155a633af" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "raw-window-handle" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20675572f6f24e9e76ef639bc5552774ed45f1c30e2951e1e99c59888861c539" + +[[package]] +name = "redox_syscall" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4722d768eff46b75989dd134e5c353f0d6296e5aaa3132e776cbdb56be7731aa" +dependencies = [ + "bitflags 1.3.2", +] + +[[package]] +name = "redox_syscall" +version = "0.5.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d04b7d0ee6b4a0207a0a7adb104d23ecb0b47d6beae7152d0fa34b692b29fd6" +dependencies = [ + "bitflags 2.8.0", +] + +[[package]] +name = "rustix" +version = "0.38.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fdb5bc1ae2baa591800df16c9ca78619bf65c0488b41b96ccec5d11220d8c154" +dependencies = [ + "bitflags 2.8.0", + "errno", + "libc", + "linux-raw-sys", + "windows-sys 0.59.0", +] + +[[package]] +name = "rustversion" +version = "1.0.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f7c45b9784283f1b2e7fb61b42047c2fd678ef0960d4f6f1eba131594cc369d4" + +[[package]] +name = "same-file" +version = "1.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502" +dependencies = [ + "winapi-util", +] + +[[package]] +name = "scoped-tls" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e1cf6437eb19a8f4a6cc0f7dca544973b0b78843adbfeb3683d1a94a0024a294" + +[[package]] +name = "scopeguard" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d29ab0c6d3fc0ee92fe66e2d99f700eab17a8d57d1c1d3b748380fb20baa78cd" + +[[package]] +name = "sctk-adwaita" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6277f0217056f77f1d8f49f2950ac6c278c0d607c45f5ee99328d792ede24ec" +dependencies = [ + "ab_glyph", + "log", + "memmap2", + "smithay-client-toolkit", + "tiny-skia", +] + +[[package]] +name = "serde" +version = "1.0.228" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a8e94ea7f378bd32cbbd37198a4a91436180c5bb472411e48b5ec2e2124ae9e" +dependencies = [ + "serde_core", +] + +[[package]] +name = "serde_core" +version = "1.0.228" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41d385c7d4ca58e59fc732af25c3983b67ac852c1a25000afe1175de458b67ad" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.228" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "slab" +version = "0.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6528351c9bc8ab22353f9d776db39a20288e8d6c37ef8cfe3317cf875eecfc2d" +dependencies = [ + "autocfg", +] + +[[package]] +name = "smallvec" +version = "1.15.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ed6a63f02c8539c91a8685a86f4099661ba3da017932f6ebbea6de3f0fa7c90" + +[[package]] +name = "smithay-client-toolkit" +version = "0.19.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3457dea1f0eb631b4034d61d4d8c32074caa6cd1ab2d59f2327bd8461e2c0016" +dependencies = [ + "bitflags 2.8.0", + "calloop", + "calloop-wayland-source", + "cursor-icon", + "libc", + "log", + "memmap2", + "rustix", + "thiserror", + "wayland-backend", + "wayland-client", + "wayland-csd-frame", + "wayland-cursor", + "wayland-protocols", + "wayland-protocols-wlr", + "wayland-scanner", + "xkeysym", +] + +[[package]] +name = "smol_str" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "74212e6bbe9a4352329b2f68ba3130c15a3f26fe88ff22dbdc6cdd58fa85e99c" +dependencies = [ + "serde", +] + +[[package]] +name = "static_assertions" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f" + +[[package]] +name = "strict-num" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9df65f20698aeed245efdde3628a6b559ea1239bbb871af1b6e3b58c413b2bd1" + +[[package]] +name = "syn" +version = "2.0.87" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "25aa4ce346d03a6dcd68dd8b4010bcb74e54e62c90c573f394c46eae99aba32d" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "thiserror" +version = "1.0.64" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d50af8abc119fb8bb6dbabcfa89656f46f84aa0ac7688088608076ad2b459a84" +dependencies = [ + "thiserror-impl", +] + +[[package]] +name = "thiserror-impl" +version = "1.0.64" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08904e7672f5eb876eaaf87e0ce17857500934f4981c4a0ab2b4aa98baac7fc3" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "tiny-skia" +version = "0.11.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b72a92a05db376db09fe6d50b7948d106011761c05a6a45e23e17ee9b556222" +dependencies = [ + "arrayref", + "arrayvec", + "bytemuck", + "cfg-if", + "log", + "tiny-skia-path", +] + +[[package]] +name = "tiny-skia-path" +version = "0.11.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ac3865b9708fc7e1961a65c3a4fa55e984272f33092d3c859929f887fceb647" +dependencies = [ + "arrayref", + "bytemuck", + "strict-num", +] + +[[package]] +name = "toml_datetime" +version = "1.1.1+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3165f65f62e28e0115a00b2ebdd37eb6f3b641855f9d636d3cd4103767159ad7" +dependencies = [ + "serde_core", +] + +[[package]] +name = "toml_edit" +version = "0.25.15+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1340ea94a5856333492c9064b02c778b191dd2c853778d9609debdcdfea3a614" +dependencies = [ + "indexmap", + "toml_datetime", + "toml_parser", + "winnow", +] + +[[package]] +name = "toml_parser" +version = "1.1.3+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d38ac1cf9b95face32296c0a3ede1fdc270627c9d9c02a7274dd6d960dc4d56" +dependencies = [ + "winnow", +] + +[[package]] +name = "tracing" +version = "0.1.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" +dependencies = [ + "pin-project-lite", + "tracing-core", +] + +[[package]] +name = "tracing-core" +version = "0.1.36" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" + +[[package]] +name = "ttf-parser" +version = "0.18.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0609f771ad9c6155384897e1df4d948e692667cc0588548b68eb44d052b27633" + +[[package]] +name = "unicode-ident" +version = "1.0.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5464a87b239f13a63a501f2701565754bae92d243d4bb7eb12f6d57d2269bf4" + +[[package]] +name = "unicode-segmentation" +version = "1.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1dd624098567895118886609431a7c3b8f516e41d30e0643f03d94592a147e36" + +[[package]] +name = "uuid" +version = "1.18.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f87b8aa10b915a06587d0dec516c282ff295b475d94abf425d62b57710070a2" + +[[package]] +name = "version_check" +version = "0.9.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "49874b5167b65d7193b8aba1567f5c7d93d001cafc34600cee003eda787e483f" + +[[package]] +name = "walkdir" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d71d857dc86794ca4c280d616f7da00d2dbfd8cd788846559a6813e6aa4b54ee" +dependencies = [ + "same-file", + "winapi-util", +] + +[[package]] +name = "wasi" +version = "0.11.0+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423" + +[[package]] +name = "wasm-bindgen" +version = "0.2.100" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1edc8929d7499fc4e8f0be2262a241556cfc54a0bea223790e71446f2aab1ef5" +dependencies = [ + "cfg-if", + "once_cell", + "rustversion", + "wasm-bindgen-macro", +] + +[[package]] +name = "wasm-bindgen-backend" +version = "0.2.100" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f0a0651a5c2bc21487bde11ee802ccaf4c51935d0d3d42a6101f98161700bc6" +dependencies = [ + "bumpalo", + "log", + "proc-macro2", + "quote", + "syn", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-futures" +version = "0.4.50" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "555d470ec0bc3bb57890405e5d4322cc9ea83cebb085523ced7be4144dac1e61" +dependencies = [ + "cfg-if", + "js-sys", + "once_cell", + "wasm-bindgen", + "web-sys", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.100" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7fe63fc6d09ed3792bd0897b314f53de8e16568c2b3f7982f468c0bf9bd0b407" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.100" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ae87ea40c9f689fc23f209965b6fb8a99ad69aeeb0231408be24920604395de" +dependencies = [ + "proc-macro2", + "quote", + "syn", + "wasm-bindgen-backend", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.100" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1a05d73b933a847d6cccdda8f838a22ff101ad9bf93e33684f39c1f5f0eece3d" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "wayland-backend" +version = "0.3.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b7208998eaa3870dad37ec8836979581506e0c5c64c20c9e79e9d2a10d6f47bf" +dependencies = [ + "cc", + "downcast-rs", + "rustix", + "scoped-tls", + "smallvec", + "wayland-sys", +] + +[[package]] +name = "wayland-client" +version = "0.31.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2120de3d33638aaef5b9f4472bff75f07c56379cf76ea320bd3a3d65ecaf73f" +dependencies = [ + "bitflags 2.8.0", + "rustix", + "wayland-backend", + "wayland-scanner", +] + +[[package]] +name = "wayland-csd-frame" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "625c5029dbd43d25e6aa9615e88b829a5cad13b2819c4ae129fdbb7c31ab4c7e" +dependencies = [ + "bitflags 2.8.0", + "cursor-icon", + "wayland-backend", +] + +[[package]] +name = "wayland-cursor" +version = "0.31.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a93029cbb6650748881a00e4922b076092a6a08c11e7fbdb923f064b23968c5d" +dependencies = [ + "rustix", + "wayland-client", + "xcursor", +] + +[[package]] +name = "wayland-protocols" +version = "0.32.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0781cf46869b37e36928f7b432273c0995aa8aed9552c556fb18754420541efc" +dependencies = [ + "bitflags 2.8.0", + "wayland-backend", + "wayland-client", + "wayland-scanner", +] + +[[package]] +name = "wayland-protocols-plasma" +version = "0.3.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7ccaacc76703fefd6763022ac565b590fcade92202492381c95b2edfdf7d46b3" +dependencies = [ + "bitflags 2.8.0", + "wayland-backend", + "wayland-client", + "wayland-protocols", + "wayland-scanner", +] + +[[package]] +name = "wayland-protocols-wlr" +version = "0.3.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "248a02e6f595aad796561fa82d25601bd2c8c3b145b1c7453fc8f94c1a58f8b2" +dependencies = [ + "bitflags 2.8.0", + "wayland-backend", + "wayland-client", + "wayland-protocols", + "wayland-scanner", +] + +[[package]] +name = "wayland-scanner" +version = "0.31.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "338e30461b3a2b67d70eb30a6d89f8e0c93a833e07d2ae89085cd070c4a00ac0" +dependencies = [ + "proc-macro2", + "quick-xml", + "quote", +] + +[[package]] +name = "wayland-sys" +version = "0.31.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dbcebb399c77d5aa9fa5db874806ee7b4eba4e73650948e8f93963f128896615" +dependencies = [ + "dlib", + "log", + "once_cell", + "pkg-config", +] + +[[package]] +name = "web-sys" +version = "0.3.77" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33b6dd2ef9186f1f2072e409e99cd22a975331a6b3591b12c764e0e55c60d5d2" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "web-time" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a6580f308b1fad9207618087a65c04e7a10bc77e02c8e84e9b00dd4b12fa0bb" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "winapi" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" +dependencies = [ + "winapi-i686-pc-windows-gnu", + "winapi-x86_64-pc-windows-gnu", +] + +[[package]] +name = "winapi-i686-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" + +[[package]] +name = "winapi-util" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f29e6f9198ba0d26b4c9f07dbe6f9ed633e1f3d5b8b414090084349e46a52596" +dependencies = [ + "winapi", +] + +[[package]] +name = "winapi-x86_64-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" + +[[package]] +name = "windows" +version = "0.62.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "527fadee13e0c05939a6a05d5bd6eec6cd2e3dbd648b9f8e447c6518133d8580" +dependencies = [ + "windows-collections", + "windows-core", + "windows-future", + "windows-numerics", +] + +[[package]] +name = "windows-collections" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23b2d95af1a8a14a3c7367e1ed4fc9c20e0a26e79551b1454d72583c97cc6610" +dependencies = [ + "windows-core", +] + +[[package]] +name = "windows-core" +version = "0.62.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb" +dependencies = [ + "windows-implement", + "windows-interface", + "windows-link", + "windows-result", + "windows-strings", +] + +[[package]] +name = "windows-future" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e1d6f90251fe18a279739e78025bd6ddc52a7e22f921070ccdc67dde84c605cb" +dependencies = [ + "windows-core", + "windows-link", + "windows-threading", +] + +[[package]] +name = "windows-implement" +version = "0.60.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "windows-interface" +version = "0.59.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-numerics" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e2e40844ac143cdb44aead537bbf727de9b044e107a0f1220392177d15b0f26" +dependencies = [ + "windows-core", + "windows-link", +] + +[[package]] +name = "windows-result" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-strings" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-sys" +version = "0.45.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "75283be5efb2831d37ea142365f009c02ec203cd29a3ebecbc093d52315b66d0" +dependencies = [ + "windows-targets 0.42.2", +] + +[[package]] +name = "windows-sys" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" +dependencies = [ + "windows-targets 0.52.6", +] + +[[package]] +name = "windows-sys" +version = "0.59.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b" +dependencies = [ + "windows-targets 0.52.6", +] + +[[package]] +name = "windows-targets" +version = "0.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e5180c00cd44c9b1c88adb3693291f1cd93605ded80c250a75d472756b4d071" +dependencies = [ + "windows_aarch64_gnullvm 0.42.2", + "windows_aarch64_msvc 0.42.2", + "windows_i686_gnu 0.42.2", + "windows_i686_msvc 0.42.2", + "windows_x86_64_gnu 0.42.2", + "windows_x86_64_gnullvm 0.42.2", + "windows_x86_64_msvc 0.42.2", +] + +[[package]] +name = "windows-targets" +version = "0.48.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "05d4b17490f70499f20b9e791dcf6a299785ce8af4d709018206dc5b4953e95f" +dependencies = [ + "windows_aarch64_gnullvm 0.48.0", + "windows_aarch64_msvc 0.48.0", + "windows_i686_gnu 0.48.0", + "windows_i686_msvc 0.48.0", + "windows_x86_64_gnu 0.48.0", + "windows_x86_64_gnullvm 0.48.0", + "windows_x86_64_msvc 0.48.0", +] + +[[package]] +name = "windows-targets" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" +dependencies = [ + "windows_aarch64_gnullvm 0.52.6", + "windows_aarch64_msvc 0.52.6", + "windows_i686_gnu 0.52.6", + "windows_i686_gnullvm", + "windows_i686_msvc 0.52.6", + "windows_x86_64_gnu 0.52.6", + "windows_x86_64_gnullvm 0.52.6", + "windows_x86_64_msvc 0.52.6", +] + +[[package]] +name = "windows-threading" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3949bd5b99cafdf1c7ca86b43ca564028dfe27d66958f2470940f73d86d75b37" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "597a5118570b68bc08d8d59125332c54f1ba9d9adeedeef5b99b02ba2b0698f8" + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.48.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "91ae572e1b79dba883e0d315474df7305d12f569b400fcf90581b06062f7e1bc" + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e08e8864a60f06ef0d0ff4ba04124db8b0fb3be5776a5cd47641e942e58c4d43" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.48.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b2ef27e0d7bdfcfc7b868b317c1d32c641a6fe4629c171b8928c7b08d98d7cf3" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" + +[[package]] +name = "windows_i686_gnu" +version = "0.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c61d927d8da41da96a81f029489353e68739737d3beca43145c8afec9a31a84f" + +[[package]] +name = "windows_i686_gnu" +version = "0.48.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "622a1962a7db830d6fd0a69683c80a18fda201879f0f447f065a3b7467daa241" + +[[package]] +name = "windows_i686_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" + +[[package]] +name = "windows_i686_msvc" +version = "0.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "44d840b6ec649f480a41c8d80f9c65108b92d89345dd94027bfe06ac444d1060" + +[[package]] +name = "windows_i686_msvc" +version = "0.48.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4542c6e364ce21bf45d69fdd2a8e455fa38d316158cfd43b3ac1c5b1b19f8e00" + +[[package]] +name = "windows_i686_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8de912b8b8feb55c064867cf047dda097f92d51efad5b491dfb98f6bbb70cb36" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.48.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca2b8a661f7628cbd23440e50b05d705db3686f894fc9580820623656af974b1" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "26d41b46a36d453748aedef1486d5c7a85db22e56aff34643984ea85514e94a3" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.48.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7896dbc1f41e08872e9d5e8f8baa8fdd2677f29468c4e156210174edc7f7b953" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9aec5da331524158c6d1a4ac0ab1541149c0b9505fde06423b02f5ef0106b9f0" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.48.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1a515f5799fe4961cb532f983ce2b23082366b898e52ffbce459c86f67c8378a" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" + +[[package]] +name = "winit" +version = "0.30.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a809eacf18c8eca8b6635091543f02a5a06ddf3dad846398795460e6e0ae3cc0" +dependencies = [ + "ahash", + "android-activity", + "atomic-waker", + "bitflags 2.8.0", + "block2", + "bytemuck", + "calloop", + "cfg_aliases", + "concurrent-queue", + "core-foundation", + "core-graphics", + "cursor-icon", + "dpi", + "js-sys", + "libc", + "memmap2", + "ndk", + "objc2", + "objc2-app-kit", + "objc2-foundation", + "objc2-ui-kit", + "orbclient", + "percent-encoding", + "pin-project", + "raw-window-handle", + "redox_syscall 0.4.1", + "rustix", + "sctk-adwaita", + "smithay-client-toolkit", + "smol_str", + "tracing", + "unicode-segmentation", + "wasm-bindgen", + "wasm-bindgen-futures", + "wayland-backend", + "wayland-client", + "wayland-protocols", + "wayland-protocols-plasma", + "web-sys", + "web-time", + "windows-sys 0.52.0", + "x11-dl", + "x11rb", + "xkbcommon-dl", +] + +[[package]] +name = "winnow" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23b97319f7b8343df12cc98938e5c3eb436064524c8d2b4e30a1d3a36eecdf81" +dependencies = [ + "memchr", +] + +[[package]] +name = "x11-dl" +version = "2.21.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38735924fedd5314a6e548792904ed8c6de6636285cb9fec04d5b1db85c1516f" +dependencies = [ + "libc", + "once_cell", + "pkg-config", +] + +[[package]] +name = "x11rb" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8f25ead8c7e4cba123243a6367da5d3990e0d3affa708ea19dce96356bd9f1a" +dependencies = [ + "as-raw-xcb-connection", + "gethostname", + "libc", + "libloading", + "once_cell", + "rustix", + "x11rb-protocol", +] + +[[package]] +name = "x11rb-protocol" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e63e71c4b8bd9ffec2c963173a4dc4cbde9ee96961d4fcb4429db9929b606c34" + +[[package]] +name = "xcursor" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "463705a63313cd4301184381c5e8042f0a7e9b4bb63653f216311d4ae74690b7" +dependencies = [ + "nom", +] + +[[package]] +name = "xkbcommon-dl" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d039de8032a9a8856a6be89cea3e5d12fdd82306ab7c94d74e6deab2460651c5" +dependencies = [ + "bitflags 2.8.0", + "dlib", + "log", + "once_cell", + "xkeysym", +] + +[[package]] +name = "xkeysym" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "054a8e68b76250b253f671d1268cb7f1ae089ec35e195b2efb2a4e9a836d0621" + +[[package]] +name = "zerocopy" +version = "0.7.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "74d4d3961e53fa4c9a25a8637fc2bfaf2595b3d3ae34875568a5cf64787716be" +dependencies = [ + "zerocopy-derive", +] + +[[package]] +name = "zerocopy-derive" +version = "0.7.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ce1b18ccd8e73a9321186f97e46f9f04b778851177567b1975109d26a08d2a6" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] diff --git a/app/vendor/rune/vendor/accesskit_windows/Cargo.toml b/app/vendor/rune/vendor/accesskit_windows/Cargo.toml new file mode 100644 index 0000000..af3df80 --- /dev/null +++ b/app/vendor/rune/vendor/accesskit_windows/Cargo.toml @@ -0,0 +1,86 @@ +# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO +# +# When uploading crates to the registry Cargo will automatically +# "normalize" Cargo.toml files for maximal compatibility +# with all versions of Cargo and also rewrite `path` dependencies +# to registry (e.g., crates.io) dependencies. +# +# If you are reading this file be aware that the original Cargo.toml +# will likely look very different (and much more reasonable). +# See Cargo.toml.orig for the original contents. + +[package] +edition = "2024" +rust-version = "1.87" +name = "accesskit_windows" +version = "0.35.2" +authors = ["The AccessKit contributors"] +build = false +exclude = ["examples"] +autolib = false +autobins = false +autoexamples = false +autotests = false +autobenches = false +description = "AccessKit UI accessibility infrastructure: Windows adapter" +readme = "README.md" +keywords = [ + "gui", + "ui", + "accessibility", +] +categories = ["gui"] +license = "MIT OR Apache-2.0" +repository = "https://github.com/AccessKit/accesskit" + +[package.metadata.docs.rs] +default-target = "x86_64-pc-windows-msvc" +targets = [] + +[lib] +name = "accesskit_windows" +path = "src/lib.rs" + +[dependencies.accesskit] +version = "0.25.2" + +[dependencies.accesskit_consumer] +version = "0.39.2" + +[dependencies.hashbrown] +version = "0.17" +features = ["default-hasher"] +default-features = false + +[dependencies.static_assertions] +version = "1.1.0" + +[dependencies.windows] +version = "0.62.0" +features = [ + "Win32_Foundation", + "Win32_Globalization", + "Win32_Graphics_Gdi", + "Win32_System_Com", + "Win32_System_LibraryLoader", + "Win32_System_Ole", + "Win32_System_Variant", + "Win32_UI_Accessibility", + "Win32_UI_Input_KeyboardAndMouse", + "Win32_UI_WindowsAndMessaging", +] + +[dependencies.windows-core] +version = "0.62.0" + +[dev-dependencies.parking_lot] +version = "0.12.4" + +[dev-dependencies.raw-window-handle] +version = "0.6.2" + +[dev-dependencies.scopeguard] +version = "1.1.0" + +[dev-dependencies.winit] +version = "0.30" diff --git a/app/vendor/rune/vendor/accesskit_windows/Cargo.toml.orig b/app/vendor/rune/vendor/accesskit_windows/Cargo.toml.orig new file mode 100644 index 0000000..1d6e8a0 --- /dev/null +++ b/app/vendor/rune/vendor/accesskit_windows/Cargo.toml.orig @@ -0,0 +1,46 @@ +[package] +name = "accesskit_windows" +version = "0.35.2" +authors.workspace = true +license.workspace = true +description = "AccessKit UI accessibility infrastructure: Windows adapter" +categories.workspace = true +keywords = ["gui", "ui", "accessibility"] +repository.workspace = true +readme = "README.md" +exclude = ["examples"] +edition.workspace = true +rust-version.workspace = true + +[package.metadata.docs.rs] +default-target = "x86_64-pc-windows-msvc" +targets = [] + +[dependencies] +accesskit = { version = "0.25.2", path = "../../accesskit" } +accesskit_consumer = { version = "0.39.2", path = "../../accesskit_consumer" } +hashbrown.workspace = true +static_assertions = "1.1.0" +windows-core = "0.62.0" + +[dependencies.windows] +version = "0.62.0" +features = [ + "Win32_Foundation", + "Win32_Globalization", + "Win32_Graphics_Gdi", + "Win32_System_Com", + "Win32_System_LibraryLoader", + "Win32_System_Ole", + "Win32_System_Variant", + "Win32_UI_Accessibility", + "Win32_UI_Input_KeyboardAndMouse", + "Win32_UI_WindowsAndMessaging", +] + +[dev-dependencies] +example_common = { path = "../../example_common" } +parking_lot = "0.12.4" +raw-window-handle = "0.6.2" +scopeguard = "1.1.0" +winit = "0.30" diff --git a/app/vendor/rune/vendor/accesskit_windows/README.md b/app/vendor/rune/vendor/accesskit_windows/README.md new file mode 100644 index 0000000..d717120 --- /dev/null +++ b/app/vendor/rune/vendor/accesskit_windows/README.md @@ -0,0 +1,3 @@ +# AccessKit Windows adapter + +This is the Windows adapter for [AccessKit](https://accesskit.dev/). It exposes an AccessKit accessibility tree through the UI Automation API. diff --git a/app/vendor/rune/vendor/accesskit_windows/src/adapter.rs b/app/vendor/rune/vendor/accesskit_windows/src/adapter.rs new file mode 100644 index 0000000..5e28b6c --- /dev/null +++ b/app/vendor/rune/vendor/accesskit_windows/src/adapter.rs @@ -0,0 +1,678 @@ +// Copyright 2022 The AccessKit Authors. All rights reserved. +// Licensed under the Apache License, Version 2.0 (found in +// the LICENSE-APACHE file) or the MIT license (found in +// the LICENSE-MIT file), at your option. + +use accesskit::{ + ActionHandler, ActivationHandler, Live, Node, NodeId, Role, TreeId, TreeInfo, TreeUpdate, +}; +use accesskit_consumer::{FilterResult, FullNodeId, NodeRef, Tree, TreeChangeHandler, TreeState}; +use hashbrown::{HashMap, HashSet}; +use std::fmt::{Debug, Formatter}; +use std::sync::{Arc, atomic::Ordering}; +use windows::Win32::{ + Foundation::*, + UI::{Accessibility::*, WindowsAndMessaging::*}, +}; + +use crate::{ + context::{ActionHandlerNoMut, ActionHandlerWrapper, Context}, + filters::filter, + long_text::long_text, + node::{NodeWrapper, PlatformNode}, + util::{QueuedEvent, StringBuffer}, + window_handle::WindowHandle, +}; + +fn focus_event(context: &Arc<Context>, node_id: FullNodeId) -> QueuedEvent { + let platform_node = context.get_or_create_platform_node(node_id); + let element: IRawElementProviderSimple = platform_node.into_interface(); + QueuedEvent::Simple { + element, + event_id: UIA_AutomationFocusChangedEventId, + } +} + +struct AdapterChangeHandler<'a> { + context: &'a Arc<Context>, + queue: Vec<QueuedEvent>, + text_changed: HashSet<FullNodeId>, + selection_changed: HashMap<FullNodeId, SelectionChanges>, +} + +impl<'a> AdapterChangeHandler<'a> { + fn new(context: &'a Arc<Context>) -> Self { + Self { + context, + queue: Vec::new(), + text_changed: HashSet::new(), + selection_changed: HashMap::new(), + } + } +} + +impl AdapterChangeHandler<'_> { + fn insert_text_change_if_needed_parent(&mut self, node: NodeRef) { + if !node.supports_text_ranges() && long_text(&node).is_none() { + return; + } + let id = node.id(); + if self.text_changed.contains(&id) { + return; + } + let platform_node = self.context.get_or_create_platform_node(node.id()); + let element: IRawElementProviderSimple = platform_node.into_interface(); + // Text change events must come before selection change + // events. It doesn't matter if text change events come + // before other events. + self.queue.insert( + 0, + QueuedEvent::Simple { + element, + event_id: UIA_Text_TextChangedEventId, + }, + ); + self.text_changed.insert(id); + } + + fn insert_text_change_if_needed(&mut self, node: &NodeRef) { + // Rune: a long field's text is its value. + if long_text(node).is_some() { + return self.insert_text_change_if_needed_parent(*node); + } + if node.role() != Role::TextRun { + return; + } + if let Some(node) = node.filtered_parent(&filter) { + self.insert_text_change_if_needed_parent(node); + } + } + + fn element_for_possibly_removed_node( + &self, + tree_state: &TreeState, + id: FullNodeId, + ) -> IRawElementProviderSimple { + if tree_state.node_by_id(id).is_some() { + self.context + .get_or_create_platform_node(id) + .into_interface() + } else { + PlatformNode::new(self.context, id).into_interface() + } + } + + fn handle_selection_state_change(&mut self, node: &NodeRef, is_selected: bool) { + // If `node` belongs to a selection container, then map the events with the + // selection container as the key because |FinalizeSelectionEvents| needs to + // determine whether or not there is only one element selected in order to + // optimize what platform events are sent. + let key = if let Some(container) = node.selection_container(&filter) { + container.id() + } else { + node.id() + }; + + let changes = self + .selection_changed + .entry(key) + .or_insert_with(|| SelectionChanges { + added_items: HashSet::new(), + removed_items: HashSet::new(), + }); + if is_selected { + changes.added_items.insert(node.id()); + } else { + changes.removed_items.insert(node.id()); + } + } + + fn enqueue_selection_changes(&mut self, tree: &Tree) { + let tree_state = tree.state(); + for (id, changes) in self.selection_changed.iter() { + let Some(node) = tree_state.node_by_id(*id) else { + continue; + }; + // Determine if `node` is a selection container with one selected child in + // order to optimize what platform events are sent. + let mut container = None; + let mut only_selected_child = None; + if node.is_container_with_selectable_children() { + container = Some(node); + for child in node.filtered_children(filter) { + if let Some(true) = child.is_selected() { + if only_selected_child.is_none() { + only_selected_child = Some(child); + } else { + only_selected_child = None; + break; + } + } + } + } + + if let Some(only_selected_child) = only_selected_child { + self.queue.push(QueuedEvent::Simple { + element: self + .context + .get_or_create_platform_node(only_selected_child.id()) + .into_interface(), + event_id: UIA_SelectionItem_ElementSelectedEventId, + }); + self.queue.push(QueuedEvent::PropertyChanged { + element: self + .context + .get_or_create_platform_node(only_selected_child.id()) + .into_interface(), + property_id: UIA_SelectionItemIsSelectedPropertyId, + old_value: false.into(), + new_value: true.into(), + }); + for child_id in changes.removed_items.iter() { + let element = self.element_for_possibly_removed_node(tree_state, *child_id); + self.queue.push(QueuedEvent::PropertyChanged { + element, + property_id: UIA_SelectionItemIsSelectedPropertyId, + old_value: true.into(), + new_value: false.into(), + }); + } + } else { + // Per UIA documentation, beyond the "invalidate limit" we're supposed to + // fire a 'SelectionInvalidated' event. The exact value isn't specified, + // but System.Windows.Automation.Provider uses a value of 20. + const INVALIDATE_LIMIT: usize = 20; + if let Some(container) = container.filter(|_| { + changes.added_items.len() + changes.removed_items.len() > INVALIDATE_LIMIT + }) { + let platform_node = self.context.get_or_create_platform_node(container.id()); + self.queue.push(QueuedEvent::Simple { + element: platform_node.into_interface(), + event_id: UIA_Selection_InvalidatedEventId, + }); + } else { + let container_is_multiselectable = + container.is_some_and(|c| c.is_multiselectable()); + for added_id in changes.added_items.iter() { + self.queue.push(QueuedEvent::Simple { + element: self + .context + .get_or_create_platform_node(*added_id) + .into_interface(), + event_id: match container_is_multiselectable { + true => UIA_SelectionItem_ElementAddedToSelectionEventId, + false => UIA_SelectionItem_ElementSelectedEventId, + }, + }); + self.queue.push(QueuedEvent::PropertyChanged { + element: self + .context + .get_or_create_platform_node(*added_id) + .into_interface(), + property_id: UIA_SelectionItemIsSelectedPropertyId, + old_value: false.into(), + new_value: true.into(), + }); + } + for removed_id in changes.removed_items.iter() { + let element = + self.element_for_possibly_removed_node(tree_state, *removed_id); + self.queue.push(QueuedEvent::Simple { + element: element.clone(), + event_id: UIA_SelectionItem_ElementRemovedFromSelectionEventId, + }); + self.queue.push(QueuedEvent::PropertyChanged { + element, + property_id: UIA_SelectionItemIsSelectedPropertyId, + old_value: true.into(), + new_value: false.into(), + }); + } + } + } + } + } +} + +struct SelectionChanges { + added_items: HashSet<FullNodeId>, + removed_items: HashSet<FullNodeId>, +} + +impl TreeChangeHandler for AdapterChangeHandler<'_> { + fn node_added(&mut self, node: &NodeRef) { + self.insert_text_change_if_needed(node); + if filter(node) != FilterResult::Include { + return; + } + let mut buffer = StringBuffer::acquire(); + let mut wrapper = NodeWrapper { + node, + string_buffer: &mut buffer, + }; + if node.is_dialog() { + let platform_node = self.context.get_or_create_platform_node(node.id()); + let element: IRawElementProviderSimple = platform_node.into_interface(); + self.queue.push(QueuedEvent::Simple { + element, + event_id: UIA_Window_WindowOpenedEventId, + }); + } + if wrapper.name().is_some() && node.live() != Live::Off { + let platform_node = self.context.get_or_create_platform_node(node.id()); + let element: IRawElementProviderSimple = platform_node.into_interface(); + self.queue.push(QueuedEvent::Simple { + element, + event_id: UIA_LiveRegionChangedEventId, + }); + } + if wrapper.is_selection_item_pattern_supported() && wrapper.is_selected() { + self.handle_selection_state_change(node, true); + } + } + + fn node_updated(&mut self, old_node: &NodeRef, new_node: &NodeRef) { + if old_node.raw_value() != new_node.raw_value() { + self.insert_text_change_if_needed(new_node); + } + let old_node_was_filtered_out = filter(old_node) != FilterResult::Include; + if filter(new_node) != FilterResult::Include { + if !old_node_was_filtered_out { + if old_node.is_dialog() { + let platform_node = self.context.get_or_create_platform_node(old_node.id()); + let element: IRawElementProviderSimple = platform_node.into_interface(); + self.queue.push(QueuedEvent::Simple { + element, + event_id: UIA_Window_WindowClosedEventId, + }); + } + let mut old_buffer = StringBuffer::acquire(); + let old_wrapper = NodeWrapper { + node: old_node, + string_buffer: &mut old_buffer, + }; + if old_wrapper.is_selection_item_pattern_supported() && old_wrapper.is_selected() { + self.handle_selection_state_change(old_node, false); + } + } + return; + } + let platform_node = self.context.get_or_create_platform_node(new_node.id()); + let element: IRawElementProviderSimple = platform_node.into_interface(); + let mut old_buffer = StringBuffer::acquire(); + let mut old_wrapper = NodeWrapper { + node: old_node, + string_buffer: &mut old_buffer, + }; + let mut new_buffer = StringBuffer::acquire(); + let mut new_wrapper = NodeWrapper { + node: new_node, + string_buffer: &mut new_buffer, + }; + new_wrapper.enqueue_property_changes( + &mut self.queue, + self.context, + &element, + &mut old_wrapper, + ); + let new_name = new_wrapper.name(); + if new_name.is_some() + && new_node.live() != Live::Off + && (new_node.live() != old_node.live() + || old_node_was_filtered_out + || new_name != old_wrapper.name()) + { + self.queue.push(QueuedEvent::Simple { + element, + event_id: UIA_LiveRegionChangedEventId, + }); + } + if old_node_was_filtered_out && new_node.is_dialog() { + let platform_node = self.context.get_or_create_platform_node(new_node.id()); + let element: IRawElementProviderSimple = platform_node.into_interface(); + self.queue.push(QueuedEvent::Simple { + element, + event_id: UIA_Window_WindowOpenedEventId, + }); + } + if new_wrapper.is_selection_item_pattern_supported() + && (new_wrapper.is_selected() != old_wrapper.is_selected() + || (old_node_was_filtered_out && new_wrapper.is_selected())) + { + self.handle_selection_state_change(new_node, new_wrapper.is_selected()); + } + } + + fn focus_moved(&mut self, _old_node: Option<&NodeRef>, new_node: Option<&NodeRef>) { + if let Some(new_node) = new_node { + self.queue.push(focus_event(self.context, new_node.id())); + } + } + + fn node_removed(&mut self, node: &NodeRef) { + self.insert_text_change_if_needed(node); + self.context.remove_platform_node(node.id()); + if filter(node) != FilterResult::Include { + return; + } + if node.is_dialog() { + let platform_node = PlatformNode::new(self.context, node.id()); + let element: IRawElementProviderSimple = platform_node.into_interface(); + self.queue.push(QueuedEvent::Simple { + element, + event_id: UIA_Window_WindowClosedEventId, + }); + } + let mut buffer = StringBuffer::acquire(); + let wrapper = NodeWrapper { + node, + string_buffer: &mut buffer, + }; + if wrapper.is_selection_item_pattern_supported() { + self.handle_selection_state_change(node, false); + } + } + + // TODO: handle other events (#20) +} + +const PLACEHOLDER_ROOT_ID: NodeId = NodeId(0); + +enum State { + Inactive { + hwnd: WindowHandle, + is_window_focused: bool, + action_handler: Arc<dyn ActionHandlerNoMut + Send + Sync>, + }, + Placeholder(Arc<Context>), + Active(Arc<Context>), +} + +impl Debug for State { + fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { + match self { + State::Inactive { + hwnd, + is_window_focused, + action_handler: _, + } => f + .debug_struct("Inactive") + .field("hwnd", hwnd) + .field("is_window_focused", is_window_focused) + .field("action_handler", &"ActionHandler") + .finish(), + State::Placeholder(context) => f.debug_tuple("Placeholder").field(context).finish(), + State::Active(context) => f.debug_tuple("Active").field(context).finish(), + } + } +} + +#[derive(Debug)] +pub struct Adapter { + state: State, +} + +impl Adapter { + /// Creates a new Windows platform adapter. + /// + /// The action handler may or may not be called on the thread that owns + /// the window. + /// + /// This must not be called while handling the `WM_GETOBJECT` message, + /// because this function must initialize UI Automation before + /// that message is handled. This is necessary to prevent a race condition + /// that leads to nested `WM_GETOBJECT` messages and, in some cases, + /// assistive technologies not realizing that the window natively implements. + /// UIA. See [AccessKit issue #37](https://github.com/AccessKit/accesskit/issues/37) + /// for more details. + pub fn new( + hwnd: HWND, + is_window_focused: bool, + action_handler: impl 'static + ActionHandler + Send, + ) -> Self { + Self::with_wrapped_action_handler( + hwnd, + is_window_focused, + Arc::new(ActionHandlerWrapper::new(action_handler)), + ) + } + + // Currently required by the test infrastructure + pub(crate) fn with_wrapped_action_handler( + hwnd: HWND, + is_window_focused: bool, + action_handler: Arc<dyn ActionHandlerNoMut + Send + Sync>, + ) -> Self { + init_uia(); + + let state = State::Inactive { + hwnd: hwnd.into(), + is_window_focused, + action_handler, + }; + Self { state } + } + + /// If and only if the tree has been initialized, call the provided function + /// and apply the resulting update. Note: If the caller's implementation of + /// [`ActivationHandler::request_initial_tree`] initially returned `None`, + /// the [`TreeUpdate`] returned by the provided function must contain + /// a full tree. + /// + /// If a [`QueuedEvents`] instance is returned, the caller must call + /// [`QueuedEvents::raise`] on it. + /// + /// This method may be safely called on any thread, but refer to + /// [`QueuedEvents::raise`] for restrictions on the context in which + /// it should be called. + pub fn update_if_active( + &mut self, + update_factory: impl FnOnce() -> TreeUpdate, + ) -> Option<QueuedEvents> { + match &self.state { + State::Inactive { .. } => None, + State::Placeholder(context) => { + let is_window_focused = context.read_tree().state().is_host_focused(); + let tree = Tree::new(update_factory(), is_window_focused); + *context.tree.write().unwrap_or_else(|e| e.into_inner()) = tree; + context.is_placeholder.store(false, Ordering::SeqCst); + let result = context + .read_tree() + .state() + .focus() + .map(|node| QueuedEvents(vec![focus_event(context, node.id())])); + self.state = State::Active(Arc::clone(context)); + result + } + State::Active(context) => { + let mut handler = AdapterChangeHandler::new(context); + let mut tree = context.tree.write().unwrap_or_else(|e| e.into_inner()); + tree.update_and_process_changes(update_factory(), &mut handler); + handler.enqueue_selection_changes(&tree); + Some(QueuedEvents(handler.queue)) + } + } + } + + /// Update the tree state based on whether the window is focused. + /// + /// If a [`QueuedEvents`] instance is returned, the caller must call + /// [`QueuedEvents::raise`] on it. + /// + /// This method may be safely called on any thread, but refer to + /// [`QueuedEvents::raise`] for restrictions on the context in which + /// it should be called. + pub fn update_window_focus_state(&mut self, is_focused: bool) -> Option<QueuedEvents> { + match &mut self.state { + State::Inactive { + is_window_focused, .. + } => { + *is_window_focused = is_focused; + None + } + State::Placeholder(context) => { + let mut handler = AdapterChangeHandler::new(context); + let mut tree = context.tree.write().unwrap_or_else(|e| e.into_inner()); + tree.update_host_focus_state_and_process_changes(is_focused, &mut handler); + Some(QueuedEvents(handler.queue)) + } + State::Active(context) => { + let mut handler = AdapterChangeHandler::new(context); + let mut tree = context.tree.write().unwrap_or_else(|e| e.into_inner()); + tree.update_host_focus_state_and_process_changes(is_focused, &mut handler); + Some(QueuedEvents(handler.queue)) + } + } + } + + /// Handle the `WM_GETOBJECT` window message. The accessibility tree + /// is lazily initialized if necessary using the provided + /// [`ActivationHandler`] implementation. + /// + /// This returns an `Option` so the caller can pass the message + /// to `DefWindowProc` if AccessKit decides not to handle it. + /// The optional value is an `Into<LRESULT>` rather than simply an `LRESULT` + /// so the necessary call to UIA, which may lead to a nested `WM_GETOBJECT` + /// message, can be done outside of any lock that the caller might hold + /// on the `Adapter` or window state, while still abstracting away + /// the details of that call to UIA. + pub fn handle_wm_getobject<H: ActivationHandler + ?Sized>( + &mut self, + wparam: WPARAM, + lparam: LPARAM, + activation_handler: &mut H, + ) -> Option<impl Into<LRESULT> + use<H>> { + // Don't bother with MSAA object IDs that are asking for something other + // than the client area of the window. DefWindowProc can handle those. + // First, cast the lparam to i32, to handle inconsistent conversion + // behavior in senders. + let objid = normalize_objid(lparam); + if objid < 0 && objid != UiaRootObjectId && objid != OBJID_CLIENT.0 { + return None; + } + + let (hwnd, platform_node) = match &self.state { + State::Inactive { + hwnd, + is_window_focused, + action_handler, + } => match activation_handler.request_initial_tree() { + Some(initial_state) => { + let hwnd = *hwnd; + let tree = Tree::new(initial_state, *is_window_focused); + let context = Context::new(hwnd, tree, Arc::clone(action_handler), false); + let node_id = context.read_tree().state().root_id(); + let platform_node = context.get_or_create_platform_node(node_id); + self.state = State::Active(context); + (hwnd, platform_node) + } + None => { + let hwnd = *hwnd; + let placeholder_update = TreeUpdate { + nodes: vec![(PLACEHOLDER_ROOT_ID, Node::new(Role::Window))], + tree: Some(TreeInfo::new(PLACEHOLDER_ROOT_ID)), + tree_id: TreeId::ROOT, + focus: PLACEHOLDER_ROOT_ID, + }; + let placeholder_tree = Tree::new(placeholder_update, *is_window_focused); + let context = + Context::new(hwnd, placeholder_tree, Arc::clone(action_handler), true); + let platform_node = PlatformNode::unspecified_root(&context); + self.state = State::Placeholder(context); + (hwnd, platform_node) + } + }, + State::Placeholder(context) => (context.hwnd, PlatformNode::unspecified_root(context)), + State::Active(context) => { + let node_id = context.read_tree().state().root_id(); + (context.hwnd, context.get_or_create_platform_node(node_id)) + } + }; + let el: IRawElementProviderSimple = platform_node.into_interface(); + Some(WmGetObjectResult { + hwnd, + wparam, + lparam, + el, + }) + } +} + +fn init_uia() { + // `UiaLookupId` is a cheap way of forcing UIA to initialize itself. + unsafe { + UiaLookupId( + AutomationIdentifierType_Property, + &ControlType_Property_GUID, + ) + }; +} + +#[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] +fn normalize_objid(lparam: LPARAM) -> i32 { + (lparam.0 & 0xFFFFFFFF) as _ +} +#[cfg(not(any(target_arch = "x86_64", target_arch = "aarch64")))] +fn normalize_objid(lparam: LPARAM) -> i32 { + lparam.0 as _ +} + +struct WmGetObjectResult { + hwnd: WindowHandle, + wparam: WPARAM, + lparam: LPARAM, + el: IRawElementProviderSimple, +} + +impl From<WmGetObjectResult> for LRESULT { + fn from(this: WmGetObjectResult) -> Self { + unsafe { UiaReturnRawElementProvider(this.hwnd.0, this.wparam, this.lparam, &this.el) } + } +} + +/// Events generated by a tree update. +#[must_use = "events must be explicitly raised"] +pub struct QueuedEvents(Vec<QueuedEvent>); + +impl QueuedEvents { + /// Raise all queued events synchronously. + /// + /// The window may receive `WM_GETOBJECT` messages during this call. + /// This means that any locks required by the `WM_GETOBJECT` handler + /// must not be held when this method is called. + /// + /// This method should be called on the thread that owns the window. + /// It's not clear whether this is a strict requirement of UIA itself, + /// but based on the known behavior of UIA, MSAA, and some ATs, + /// it's strongly recommended. + pub fn raise(self) { + for event in self.0 { + match event { + QueuedEvent::Simple { element, event_id } => { + unsafe { UiaRaiseAutomationEvent(&element, event_id) }.unwrap(); + } + QueuedEvent::PropertyChanged { + element, + property_id, + old_value, + new_value, + } => { + unsafe { + UiaRaiseAutomationPropertyChangedEvent( + &element, + property_id, + &old_value, + &new_value, + ) + } + .unwrap(); + } + } + } + } +} + +// We explicitly want to allow the queued events to be sent to the UI thread, +// so implement Send even though windows-rs doesn't implement it for all +// contained types. This is safe because we're not using COM threading. +unsafe impl Send for QueuedEvents {} diff --git a/app/vendor/rune/vendor/accesskit_windows/src/context.rs b/app/vendor/rune/vendor/accesskit_windows/src/context.rs new file mode 100644 index 0000000..799d59e --- /dev/null +++ b/app/vendor/rune/vendor/accesskit_windows/src/context.rs @@ -0,0 +1,98 @@ +// Copyright 2023 The AccessKit Authors. All rights reserved. +// Licensed under the Apache License, Version 2.0 (found in +// the LICENSE-APACHE file) or the MIT license (found in +// the LICENSE-MIT file), at your option. + +use accesskit::{ActionHandler, ActionRequest, Point}; +use accesskit_consumer::{FullNodeId, Tree}; +use hashbrown::HashMap; +use std::fmt::{Debug, Formatter}; +use std::sync::{Arc, Mutex, RwLock, RwLockReadGuard, atomic::AtomicBool}; +use windows::core::ComObject; + +use crate::{node::PlatformNode, util::*, window_handle::WindowHandle}; + +pub(crate) trait ActionHandlerNoMut { + fn do_action(&self, request: ActionRequest); +} + +pub(crate) struct ActionHandlerWrapper<H: ActionHandler + Send>(Mutex<H>); + +impl<H: 'static + ActionHandler + Send> ActionHandlerWrapper<H> { + pub(crate) fn new(inner: H) -> Self { + Self(Mutex::new(inner)) + } +} + +impl<H: ActionHandler + Send> ActionHandlerNoMut for ActionHandlerWrapper<H> { + fn do_action(&self, request: ActionRequest) { + self.0.lock().unwrap_or_else(|e| e.into_inner()).do_action(request) + } +} + +pub(crate) struct Context { + pub(crate) hwnd: WindowHandle, + pub(crate) tree: RwLock<Tree>, + pub(crate) action_handler: Arc<dyn ActionHandlerNoMut + Send + Sync>, + pub(crate) is_placeholder: AtomicBool, + platform_nodes: Mutex<HashMap<FullNodeId, ComObject<PlatformNode>>>, +} + +impl Debug for Context { + fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { + f.debug_struct("Context") + .field("hwnd", &self.hwnd) + .field("tree", &self.tree) + .field("action_handler", &"ActionHandler") + .field("is_placeholder", &self.is_placeholder) + .finish() + } +} + +impl Context { + pub(crate) fn new( + hwnd: WindowHandle, + tree: Tree, + action_handler: Arc<dyn ActionHandlerNoMut + Send + Sync>, + is_placeholder: bool, + ) -> Arc<Self> { + Arc::new(Self { + hwnd, + tree: RwLock::new(tree), + action_handler, + is_placeholder: AtomicBool::new(is_placeholder), + platform_nodes: Mutex::new(HashMap::new()), + }) + } + + pub(crate) fn read_tree(&self) -> RwLockReadGuard<'_, Tree> { + self.tree.read().unwrap_or_else(|e| e.into_inner()) + } + + pub(crate) fn client_top_left(&self) -> Point { + client_top_left(self.hwnd) + } + + pub(crate) fn do_action(&self, request: ActionRequest) { + self.action_handler.do_action(request); + } + + pub(crate) fn get_or_create_platform_node( + self: &Arc<Self>, + id: FullNodeId, + ) -> ComObject<PlatformNode> { + let mut platform_nodes = self.platform_nodes.lock().unwrap_or_else(|e| e.into_inner()); + if let Some(result) = platform_nodes.get(&id) { + return result.clone(); + } + + let result = PlatformNode::new(self, id); + platform_nodes.insert(id, result.clone()); + result + } + + pub(crate) fn remove_platform_node(&self, id: FullNodeId) { + let mut platform_nodes = self.platform_nodes.lock().unwrap_or_else(|e| e.into_inner()); + platform_nodes.remove(&id); + } +} diff --git a/app/vendor/rune/vendor/accesskit_windows/src/filters.rs b/app/vendor/rune/vendor/accesskit_windows/src/filters.rs new file mode 100644 index 0000000..e8614e8 --- /dev/null +++ b/app/vendor/rune/vendor/accesskit_windows/src/filters.rs @@ -0,0 +1,8 @@ +// Copyright 2023 The AccessKit Authors. All rights reserved. +// Licensed under the Apache License, Version 2.0 (found in +// the LICENSE-APACHE file) or the MIT license (found in +// the LICENSE-MIT file), at your option. + +pub(crate) use accesskit_consumer::{ + common_filter as filter, common_filter_with_root_exception as filter_with_root_exception, +}; diff --git a/app/vendor/rune/vendor/accesskit_windows/src/lib.rs b/app/vendor/rune/vendor/accesskit_windows/src/lib.rs new file mode 100644 index 0000000..890b9b3 --- /dev/null +++ b/app/vendor/rune/vendor/accesskit_windows/src/lib.rs @@ -0,0 +1,23 @@ +// Copyright 2021 The AccessKit Authors. All rights reserved. +// Licensed under the Apache License, Version 2.0 (found in +// the LICENSE-APACHE file) or the MIT license (found in +// the LICENSE-MIT file), at your option. + +mod context; +mod filters; +mod long_text; +mod node; +mod text; +mod util; +mod window_handle; + +mod adapter; +pub use adapter::{Adapter, QueuedEvents}; + +mod subclass; +pub use subclass::SubclassingAdapter; + +pub use windows::Win32::Foundation::{HWND, LPARAM, LRESULT, WPARAM}; + +#[cfg(test)] +mod tests; diff --git a/app/vendor/rune/vendor/accesskit_windows/src/long_text.rs b/app/vendor/rune/vendor/accesskit_windows/src/long_text.rs new file mode 100644 index 0000000..dcadab3 --- /dev/null +++ b/app/vendor/rune/vendor/accesskit_windows/src/long_text.rs @@ -0,0 +1,796 @@ +// Rune (vendor/accesskit_windows.patch): a text field too long for its toolkit to publish text +// runs (Rune stops at 64 KiB) keeps its text ranges. The toolkit marks such a field by putting its +// selection on the field itself, as byte offsets into its value, and publishes a single +// GenericContainer (`class_name = "\x1frune-lines"`) holding one GenericContainer child +// (`class_name = "\x1frune-line"`, `author_id = "<start>:<end>"`) per drawn visual line. Ranges +// are answered from the value when a reader asks, and screen rectangles, hit-testing and wrapped +// visual lines are answered in the drawn band without shaping off-screen rows. +// The same file is in accesskit_windows and accesskit_macos; each uses part of it. +#![allow(dead_code)] + +use std::cell::RefCell; + +use accesskit::{Point, Rect, Role, TextDirection, TextSelection}; +use accesskit_consumer::NodeRef; + +const LINES_BOX_CLASS: &str = "\x1frune-lines"; +const LINE_CLASS: &str = "\x1frune-line"; +const CHECKPOINT_STRIDE: usize = 65_536; + +#[derive(Clone, Copy, PartialEq, Eq)] +pub(crate) enum Unit { + Character, + Word, + Line, + Paragraph, + Document, +} + +/// One visual line currently drawn on screen for a long field. +#[derive(Clone, Copy)] +pub(crate) struct DrawnLine<'a> { + pub(crate) start: usize, + pub(crate) end: usize, + pub(crate) node: NodeRef<'a>, +} + +/// All drawn-line metadata published on `node` for the current tree snapshot. +pub(crate) struct DrawnState<'a> { + pub(crate) lines: Vec<DrawnLine<'a>>, + pub(crate) content_key: u64, + pub(crate) upstream_caret: bool, + pub(crate) caret_byte: usize, +} + +struct Band { + start: usize, + end: usize, + first: usize, + count: usize, +} + +#[derive(Clone, Copy)] +struct Mark { + byte: usize, + utf16: usize, + newlines: usize, +} + +struct Checkpoints { + content_key: u64, + len: usize, + edge: [u8; 32], + marks: Vec<Mark>, +} + +const CHECKPOINT_SLOTS: usize = 4; + +struct CheckpointRing { + slots: [Option<Checkpoints>; CHECKPOINT_SLOTS], + next: usize, +} + +thread_local! { + static CHECKPOINTS: RefCell<CheckpointRing> = const { + RefCell::new(CheckpointRing { + slots: [None, None, None, None], + next: 0, + }) + }; +} + +fn edge_sample(s: &str) -> [u8; 32] { + let mut out = [0u8; 32]; + let b = s.as_bytes(); + let head = b.len().min(16); + out[..head].copy_from_slice(&b[..head]); + let tail = b.len().min(16); + out[16..16 + tail].copy_from_slice(&b[b.len() - tail..]); + out +} + +fn with_checkpoints<R>(s: &str, content_key: u64, f: impl FnOnce(&[Mark]) -> R) -> R { + if s.len() <= CHECKPOINT_STRIDE { + return f(&[Mark { byte: 0, utf16: 0, newlines: 0 }]); + } + let edge = edge_sample(s); + CHECKPOINTS.with(|cell| { + let mut ring = cell.borrow_mut(); + if let Some(hit) = ring.slots.iter().flatten().find(|c| { + c.content_key == content_key && c.len == s.len() && c.edge == edge + }) { + return f(hit.marks.as_slice()); + } + let mut marks = Vec::with_capacity(s.len() / CHECKPOINT_STRIDE + 2); + marks.push(Mark { byte: 0, utf16: 0, newlines: 0 }); + let mut utf16 = 0usize; + let mut newlines = 0usize; + let mut next_at = CHECKPOINT_STRIDE; + for (k, ch) in s.char_indices() { + if k >= next_at { + marks.push(Mark { byte: k, utf16, newlines }); + next_at = k + CHECKPOINT_STRIDE; + } + utf16 += ch.len_utf16(); + if ch == '\n' { + newlines += 1; + } + } + let idx = ring.next % CHECKPOINT_SLOTS; + ring.next = ring.next.wrapping_add(1); + ring.slots[idx] = Some(Checkpoints { content_key, len: s.len(), edge, marks }); + let marks = ring.slots[idx].as_ref().map_or(&[][..], |c| c.marks.as_slice()); + f(marks) + }) +} + +/// The value and selection a long field's text ranges are answered from. +pub(crate) fn long_text<'a>(node: &NodeRef<'a>) -> Option<(Text<'a>, &'a TextSelection)> { + if !node.is_text_input() || node.is_password_input() || node.supports_text_ranges() { + return None; + } + let data = node.data(); + let selection = data.text_selection()?; + let (id, _) = node.locate(); + if selection.anchor.node != id || selection.focus.node != id { + return None; + } + Some((Text(data.value().unwrap_or("")), selection)) +} + +/// Drawn visual lines Rune attached to `node` inside its `\x1frune-lines` container, sorted and +/// strictly non-overlapping. +pub(crate) fn drawn_state<'a>(node: &NodeRef<'a>, text: Text<'a>) -> DrawnState<'a> { + let caret_byte = node + .data() + .text_selection() + .map_or(0, |s| text.clamp(s.focus.character_index)); + let Some(box_node) = node + .children() + .find(|c| c.role() == Role::GenericContainer && c.data().class_name() == Some(LINES_BOX_CLASS)) + else { + return DrawnState { + lines: Vec::new(), + content_key: 0, + upstream_caret: false, + caret_byte, + }; + }; + let (content_key, upstream_caret) = box_node + .author_id() + .and_then(|s| s.split_once(':')) + .map_or((0, false), |(k, u)| (u64::from_str_radix(k, 16).unwrap_or(0), u == "1")); + + let mut raw = Vec::new(); + for child in box_node.children() { + if child.role() != Role::GenericContainer || child.data().class_name() != Some(LINE_CLASS) { + continue; + } + let Some((a, b)) = child.author_id().and_then(|id| id.split_once(':')) else { + continue; + }; + let (Ok(a), Ok(b)) = (a.parse::<usize>(), b.parse::<usize>()) else { + continue; + }; + let start = text.clamp(a); + let end = text.clamp(b).max(start); + raw.push(DrawnLine { start, end, node: child }); + } + raw.sort_by_key(|d| (d.start, d.end)); + let mut lines: Vec<DrawnLine<'a>> = Vec::new(); + for d in raw { + if let Some(prev) = lines.last() + && (d.start < prev.end || (d.start == prev.start && d.end == prev.end)) + { + continue; + } + lines.push(d); + } + DrawnState { lines, content_key, upstream_caret, caret_byte } +} + +pub(crate) fn drawn_lines<'a>(node: &NodeRef<'a>, text: Text<'a>) -> Vec<DrawnLine<'a>> { + drawn_state(node, text).lines +} + +fn bands(drawn: &[DrawnLine]) -> Vec<Band> { + let mut out: Vec<Band> = Vec::new(); + for (idx, d) in drawn.iter().enumerate() { + if let Some(last) = out.last_mut() + && last.end == d.start + { + last.end = d.end; + last.count += 1; + continue; + } + out.push(Band { start: d.start, end: d.end, first: idx, count: 1 }); + } + out +} + +fn line_is_rtl(line: &NodeRef) -> bool { + line.data().text_direction() == Some(TextDirection::RightToLeft) +} + +fn line_is_hard_end(text: Text, end: usize) -> bool { + end > 0 && text.0.as_bytes().get(end - 1) == Some(&b'\n') +} + +fn caret_x_in_line(line: &NodeRef, rel_byte: usize, trailing_edge: bool) -> f64 { + let data = line.data(); + let rtl = line_is_rtl(line); + let w = data.bounds().map_or(0.0, |r| r.width()); + if trailing_edge { + return if rtl { 0.0 } else { w }; + } + let lengths = data.character_lengths(); + let positions = data.character_positions().unwrap_or(&[]); + let widths = data.character_widths().unwrap_or(&[]); + if lengths.is_empty() || positions.len() < lengths.len() || widths.len() < lengths.len() { + return if (rel_byte == 0) != rtl { 0.0 } else { w }; + } + let mut seen = 0usize; + for (k, &len) in lengths.iter().enumerate() { + let next = seen + usize::from(len); + if rel_byte < next || (rel_byte == seen && len == 0) { + let x0 = f64::from(positions[k]); + let x1 = x0 + f64::from(widths[k]); + let cluster_rtl = if k + 1 < lengths.len() && widths[k] > 0.0 && widths[k + 1] > 0.0 { + positions[k + 1] < positions[k] + } else if k > 0 && widths[k] > 0.0 && widths[k - 1] > 0.0 { + positions[k] < positions[k - 1] + } else { + rtl + }; + return if cluster_rtl { x1 } else { x0 }; + } + seen = next; + } + if rtl { 0.0 } else { w } +} + +fn span_x_in_line(line: &NodeRef, rel_start: usize, rel_end: usize) -> (f64, f64) { + let data = line.data(); + let w = data.bounds().map_or(0.0, |r| r.width()); + let lengths = data.character_lengths(); + let positions = data.character_positions().unwrap_or(&[]); + let widths = data.character_widths().unwrap_or(&[]); + if lengths.is_empty() || positions.len() < lengths.len() || widths.len() < lengths.len() { + return (0.0, w); + } + let mut seen = 0usize; + let mut min_x = f64::INFINITY; + let mut max_x = f64::NEG_INFINITY; + for (k, &len) in lengths.iter().enumerate() { + let next = seen + usize::from(len); + if next > rel_start && seen < rel_end { + let x0 = f64::from(positions[k]); + let x1 = x0 + f64::from(widths[k]).max(0.0); + min_x = min_x.min(x0); + max_x = max_x.max(x1); + } + seen = next; + } + if min_x.is_finite() && max_x.is_finite() { + (min_x, max_x.max(min_x)) + } else { + let x = caret_x_in_line(line, rel_start, false); + (x, x) + } +} + +/// Transformed bounding boxes (in root/window coordinates, matching AccessKit's `Range::bounding_boxes`) +/// for the drawn portion of `a..b`. Off-screen bytes have no box, matching Chromium. +pub(crate) fn bounding_boxes(node: &NodeRef, text: Text, a: usize, b: usize) -> Vec<Rect> { + let (a, b) = (text.clamp(a.min(b)), text.clamp(a.max(b))); + let state = drawn_state(node, text); + let drawn = &state.lines; + if drawn.is_empty() { + return Vec::new(); + } + if a == b { + if state.upstream_caret && a == state.caret_byte { + if let Some(d) = drawn + .iter() + .find(|d| a == d.end && d.start < d.end && !line_is_hard_end(text, d.end)) + && let Some(mut rect) = d.node.data().bounds() + { + let x = caret_x_in_line(&d.node, a - d.start, true); + let left = rect.x0 + x; + rect.x0 = left; + rect.x1 = left; + return vec![d.node.transform().transform_rect_bbox(rect)]; + } + } + let hit = drawn.iter().enumerate().find(|&(k, d)| { + (d.start <= a && a < d.end) + || (d.start == a && d.end == a) + || (a == d.end + && !line_is_hard_end(text, d.end) + && drawn.get(k + 1).is_none_or(|nx| nx.start != a)) + }); + let Some((_, d)) = hit else { + return Vec::new(); + }; + let Some(mut rect) = d.node.data().bounds() else { + return Vec::new(); + }; + let x = caret_x_in_line(&d.node, a.saturating_sub(d.start), false); + let left = rect.x0 + x; + rect.x0 = left; + rect.x1 = left; + return vec![d.node.transform().transform_rect_bbox(rect)]; + } + let mut out = Vec::new(); + for d in drawn { + let ov_start = a.max(d.start); + let ov_end = b.min(d.end); + if ov_start >= ov_end { + continue; + } + let Some(mut rect) = d.node.data().bounds() else { + continue; + }; + if ov_start > d.start || ov_end < d.end { + let orig_left = rect.x0; + let (x0, x1) = span_x_in_line(&d.node, ov_start - d.start, ov_end - d.start); + rect.x0 = orig_left + x0; + rect.x1 = orig_left + x1; + } + out.push(d.node.transform().transform_rect_bbox(rect)); + } + out +} + +/// Byte offset in `text` at `point` (in `node`'s local coordinate space), using containment inside +/// the nearest drawn visual line. When `for_char` is true (macOS `accessibilityRangeForPosition:`), +/// a point past the trailing edge of a soft-wrapped line clamps to that line's last character. +pub(crate) fn byte_at_point(node: &NodeRef, text: Text, point: Point, for_char: bool) -> Option<usize> { + let drawn = drawn_lines(node, text); + let d = drawn.iter().min_by(|a, b| { + let dist = |ln: &DrawnLine| match ln.node.data().bounds() { + Some(r) if point.y < r.y0 => r.y0 - point.y, + Some(r) if point.y > r.y1 => point.y - r.y1, + Some(_) => 0.0, + None => f64::INFINITY, + }; + dist(a).total_cmp(&dist(b)) + })?; + let bounds = d.node.data().bounds()?; + let rel_x = (point.x - bounds.x0) as f32; + let data = d.node.data(); + let rtl = line_is_rtl(&d.node); + let lengths = data.character_lengths(); + let positions = data.character_positions().unwrap_or(&[]); + let widths = data.character_widths().unwrap_or(&[]); + if lengths.is_empty() || positions.len() < lengths.len() || widths.len() < lengths.len() { + return Some(d.start); + } + let mut byte_off = 0usize; + let mut min_x = f32::INFINITY; + let mut max_x = f32::NEG_INFINITY; + for k in 0..lengths.len() { + let w = widths[k]; + let x0 = positions[k]; + let x1 = x0 + w; + if w > 0.0 { + min_x = min_x.min(x0); + max_x = max_x.max(x1); + if rel_x >= x0 && rel_x < x1 { + return Some(text.clamp(d.start + byte_off)); + } + } + byte_off += usize::from(lengths[k]); + } + let trim = if d.end >= d.start + 2 && text.0.as_bytes().get(d.end - 2..d.end) == Some(b"\r\n") { + 2 + } else if d.end > d.start && text.0.as_bytes().get(d.end - 1) == Some(&b'\n') { + 1 + } else { + 0 + }; + let line_end = text.clamp(d.end.saturating_sub(trim)).max(d.start); + let leading = if rtl { rel_x >= max_x } else { rel_x <= min_x }; + if leading { + return Some(d.start); + } + if for_char && trim == 0 && line_end > d.start { + return Some(text.prev(line_end, Unit::Character).max(d.start)); + } + Some(line_end) +} + +fn utf16_len(s: &str) -> usize { + if s.is_ascii() { s.len() } else { s.chars().map(char::len_utf16).sum() } +} + +fn count_newlines_slice(s: &str) -> usize { + s.as_bytes().iter().filter(|&&b| b == b'\n').count() +} + +fn count_newlines_between(s: &str, a: usize, b: usize, marks: &[Mark]) -> usize { + if a >= b || b > s.len() { + return 0; + } + if b - a <= CHECKPOINT_STRIDE || marks.len() <= 1 { + return s.get(a..b).map_or(0, count_newlines_slice); + } + let ma = marks.partition_point(|m| m.byte <= a).saturating_sub(1); + let mb = marks.partition_point(|m| m.byte <= b).saturating_sub(1); + if mb <= ma { + return s.get(a..b).map_or(0, count_newlines_slice); + } + let head_sub = s.get(marks[ma].byte..a).map_or(0, count_newlines_slice); + let tail_add = s.get(marks[mb].byte..b).map_or(0, count_newlines_slice); + (marks[mb].newlines + tail_add).saturating_sub(marks[ma].newlines + head_sub) +} + +fn nth_newline_after(s: &str, from: usize, limit: usize, nth: usize, marks: &[Mark]) -> Option<usize> { + let sub = s.get(from..limit)?; + if limit - from <= CHECKPOINT_STRIDE || marks.len() <= 1 { + return sub.match_indices('\n').nth(nth).map(|(p, _)| from + p); + } + let m_from = marks.partition_point(|m| m.byte <= from).saturating_sub(1); + let base_nl = marks[m_from].newlines + s.get(marks[m_from].byte..from).map_or(0, count_newlines_slice); + let target_nl = base_nl + nth + 1; + let m_hit = marks.partition_point(|m| m.newlines < target_nl).saturating_sub(1); + let scan_start = marks[m_hit].byte.max(from); + if scan_start >= limit { + return None; + } + let already = if scan_start == from { + 0 + } else { + (marks[m_hit].newlines).saturating_sub(base_nl) + }; + let rem = nth.checked_sub(already)?; + s.get(scan_start..limit)? + .match_indices('\n') + .nth(rem) + .map(|(p, _)| scan_start + p) +} + +/// Byte offsets into a field's value. +#[derive(Clone, Copy)] +pub(crate) struct Text<'a>(pub(crate) &'a str); + +impl<'a> Text<'a> { + pub(crate) fn len(self) -> usize { + self.0.len() + } + + /// `i`, within the text and on a character's start. + pub(crate) fn clamp(self, i: usize) -> usize { + self.0.floor_char_boundary(i.min(self.0.len())) + } + + pub(crate) fn slice(self, a: usize, b: usize) -> &'a str { + let (a, b) = (self.clamp(a.min(b)), self.clamp(a.max(b))); + self.0.get(a..b).unwrap_or("") + } + + fn line_start(self, i: usize) -> usize { + let i = self.clamp(i); + self.0.get(..i).and_then(|s| s.rfind('\n')).map_or(0, |p| p + 1) + } + + pub(crate) fn is_start(self, i: usize, unit: Unit) -> bool { + let i = self.clamp(i); + let s = self.0; + match unit { + Unit::Character => true, + Unit::Word => { + i == 0 + || (s.get(i..).and_then(|r| r.chars().next()).is_some_and(|c| !c.is_whitespace()) + && s.get(..i).and_then(|l| l.chars().next_back()).is_some_and(char::is_whitespace)) + } + Unit::Line | Unit::Paragraph => i == 0 || s.as_bytes().get(i - 1) == Some(&b'\n'), + Unit::Document => i == 0, + } + } + + pub(crate) fn is_start_in(self, i: usize, unit: Unit, state: &DrawnState) -> bool { + let i = self.clamp(i); + if unit == Unit::Line && !state.lines.is_empty() { + if state.upstream_caret + && i == state.caret_byte + && state + .lines + .iter() + .any(|d| i == d.end && d.start < d.end && !line_is_hard_end(self, d.end)) + { + return false; + } + if let Some(d) = state + .lines + .iter() + .find(|d| (d.start <= i && i < d.end) || (d.start == i && d.end == i)) + { + return i == d.start; + } + } + self.is_start(i, unit) + } + + /// The start of the unit holding `i`. + pub(crate) fn start_of(self, i: usize, unit: Unit) -> usize { + let i = self.clamp(i); + if self.is_start(i, unit) { i } else { self.prev(i, unit) } + } + + pub(crate) fn start_of_in(self, i: usize, unit: Unit, state: &DrawnState) -> usize { + let i = self.clamp(i); + if self.is_start_in(i, unit, state) { + i + } else { + self.prev_in(i, unit, &state.lines) + } + } + + /// The first unit start after `i`, or the text's end. + pub(crate) fn next(self, i: usize, unit: Unit) -> usize { + let i = self.clamp(i); + let s = self.0; + let tail = s.get(i..).unwrap_or(""); + match unit { + Unit::Character => tail.chars().next().map_or(i, |c| i + c.len_utf8()), + Unit::Word => { + let mut space = false; + for (k, c) in tail.char_indices() { + if c.is_whitespace() { + space = true; + } else if space { + return i + k; + } + } + s.len() + } + Unit::Line | Unit::Paragraph => tail.find('\n').map_or(s.len(), |p| i + p + 1), + Unit::Document => s.len(), + } + } + + pub(crate) fn next_in(self, i: usize, unit: Unit, drawn: &[DrawnLine]) -> usize { + let i = self.clamp(i); + if unit != Unit::Line || drawn.is_empty() { + return self.next(i, unit); + } + if let Some(d) = drawn.iter().find(|d| d.start <= i && i < d.end) { + return d.end; + } + let nl = self.next(i, Unit::Line); + drawn + .iter() + .find(|d| d.start > i && d.start < nl) + .map_or(nl, |d| d.start) + } + + /// The last unit start before `i`, or the text's start. + pub(crate) fn prev(self, i: usize, unit: Unit) -> usize { + let i = self.clamp(i); + let s = self.0; + let head = s.get(..i).unwrap_or(""); + match unit { + Unit::Character => head.chars().next_back().map_or(0, |c| i - c.len_utf8()), + Unit::Word => { + let mut word = None; + for (k, c) in head.char_indices().rev() { + if !c.is_whitespace() { + word = Some(k); + } else if let Some(k) = word { + return k; + } + } + 0 + } + Unit::Line | Unit::Paragraph => { + if i == 0 { + return 0; + } + let at = self.line_start(i); + if at < i { + at + } else { + self.line_start(self.clamp(i - 1)) + } + } + Unit::Document => 0, + } + } + + pub(crate) fn prev_in(self, i: usize, unit: Unit, drawn: &[DrawnLine]) -> usize { + let i = self.clamp(i); + if unit != Unit::Line || drawn.is_empty() || i == 0 { + return self.prev(i, unit); + } + if let Some(d) = drawn.iter().rfind(|d| d.start < i && i <= d.end) { + return d.start; + } + if drawn.iter().any(|d| d.start == i) { + if let Some(prev_d) = drawn.iter().rfind(|d| d.end == i && d.start < i) { + return prev_d.start; + } + return self.prev(i, Unit::Line); + } + let p = self.prev(i, Unit::Line); + drawn + .iter() + .rfind(|d| d.start >= p && d.start < i) + .map_or(p, |d| d.start) + } + + /// Moves `i` by `count` unit starts, stopping at either end of the text. + pub(crate) fn step_in(self, i: usize, unit: Unit, count: i32, drawn: &[DrawnLine]) -> (usize, i32) { + let mut i = self.clamp(i); + if count == 0 { + return (i, 0); + } + let mut moved = 0i32; + let steps = count.unsigned_abs(); + for _ in 0..steps { + if (count > 0 && i == self.len()) || (count < 0 && i == 0) { + break; + } + let next_i = if count > 0 { + self.next_in(i, unit, drawn) + } else { + self.prev_in(i, unit, drawn) + }; + if next_i == i { + break; + } + i = next_i; + moved = moved.saturating_add(1); + } + (i, if count < 0 { -moved } else { moved }) + } + + /// The zero-based line holding byte `i`, counting drawn wrapped lines visually. + pub(crate) fn line_of_in(self, i: usize, state: &DrawnState) -> usize { + let i = self.clamp(i); + let s = self.0; + let drawn = &state.lines; + let bs = bands(drawn); + with_checkpoints(s, state.content_key, |marks| { + if bs.is_empty() { + return count_newlines_between(s, 0, i, marks); + } + let mut lines = 0usize; + let mut cursor = 0usize; + for b in &bs { + if i < b.start { + return lines + count_newlines_between(s, cursor, i, marks); + } + lines += count_newlines_between(s, cursor, b.start, marks); + let band_slice = &drawn[b.first..b.first + b.count]; + let has_trailing_empty = + band_slice.last().is_some_and(|d| d.start == b.end && d.end == b.end); + let in_band_at_end = i == b.end + && b.end == s.len() + && (has_trailing_empty || !line_is_hard_end(self, b.end)); + if i < b.end + || in_band_at_end + || (state.upstream_caret + && i == state.caret_byte + && i == b.end + && b.start < b.end + && !line_is_hard_end(self, b.end)) + { + if state.upstream_caret && i == state.caret_byte { + if let Some(sub) = band_slice + .iter() + .position(|d| i == d.end && d.start < d.end && !line_is_hard_end(self, d.end)) + { + return lines + sub; + } + } + let sub = band_slice.iter().rposition(|d| d.start <= i).unwrap_or(0); + return lines + sub; + } + lines += b.count; + cursor = b.end; + } + lines + count_newlines_between(s, cursor, i, marks) + }) + } + + /// Line `n`'s bytes, counting drawn wrapped lines visually. + pub(crate) fn line_in(self, n: usize, state: &DrawnState) -> Option<(usize, usize)> { + let s = self.0; + let drawn = &state.lines; + let bs = bands(drawn); + with_checkpoints(s, state.content_key, |marks| { + if bs.is_empty() { + let start = if n == 0 { + 0 + } else { + nth_newline_after(s, 0, s.len(), n - 1, marks)? + 1 + }; + return Some((start, self.next(start, Unit::Line))); + } + let mut rem = n; + let mut cursor = 0usize; + for b in &bs { + let gap_lines = count_newlines_between(s, cursor, b.start, marks); + if rem < gap_lines { + let start = if rem == 0 { + cursor + } else { + nth_newline_after(s, cursor, b.start, rem - 1, marks)? + 1 + }; + return Some((start, self.next(start, Unit::Line).min(b.start))); + } + rem -= gap_lines; + if rem < b.count { + let d = &drawn[b.first + rem]; + return Some((d.start, d.end)); + } + rem -= b.count; + cursor = b.end; + } + let drawn_has_end_empty = + drawn.last().is_some_and(|d| d.start == s.len() && d.end == s.len()); + if cursor >= s.len() { + if !drawn_has_end_empty && line_is_hard_end(self, s.len()) && rem == 0 { + return Some((s.len(), s.len())); + } + return None; + } + let start = if rem == 0 { + cursor + } else { + nth_newline_after(s, cursor, s.len(), rem - 1, marks)? + 1 + }; + Some((start, self.next(start, Unit::Line))) + }) + } + + pub(crate) fn utf16_with(self, i: usize, key: u64) -> usize { + let i = self.clamp(i); + with_checkpoints(self.0, key, |marks| { + let idx = marks.partition_point(|m| m.byte <= i).saturating_sub(1); + let m = marks.get(idx).copied().unwrap_or(Mark { byte: 0, utf16: 0, newlines: 0 }); + m.utf16 + self.0.get(m.byte..i).map_or(0, utf16_len) + }) + } + + pub(crate) fn utf16(self, i: usize) -> usize { + self.utf16_with(i, 0) + } + + /// Bytes `a..b` as a UTF-16 start and length. + pub(crate) fn utf16_span_with(self, a: usize, b: usize, key: u64) -> (usize, usize) { + let (a, b) = (self.clamp(a.min(b)), self.clamp(a.max(b))); + let start = self.utf16_with(a, key); + let len = if b - a <= CHECKPOINT_STRIDE { + self.0.get(a..b).map_or(0, utf16_len) + } else { + self.utf16_with(b, key).saturating_sub(start) + }; + (start, len) + } + + pub(crate) fn utf16_span(self, a: usize, b: usize) -> (usize, usize) { + self.utf16_span_with(a, b, 0) + } + + pub(crate) fn from_utf16_with(self, units: usize, key: u64) -> usize { + with_checkpoints(self.0, key, |marks| { + let idx = marks.partition_point(|m| m.utf16 <= units).saturating_sub(1); + let m = marks.get(idx).copied().unwrap_or(Mark { byte: 0, utf16: 0, newlines: 0 }); + let mut seen = m.utf16; + let tail = self.0.get(m.byte..).unwrap_or(""); + for (k, c) in tail.char_indices() { + if seen >= units { + return m.byte + k; + } + seen += c.len_utf16(); + } + self.0.len() + }) + } + + pub(crate) fn from_utf16(self, units: usize) -> usize { + self.from_utf16_with(units, 0) + } +} diff --git a/app/vendor/rune/vendor/accesskit_windows/src/node.rs b/app/vendor/rune/vendor/accesskit_windows/src/node.rs new file mode 100644 index 0000000..26fa8be --- /dev/null +++ b/app/vendor/rune/vendor/accesskit_windows/src/node.rs @@ -0,0 +1,1658 @@ +// Copyright 2022 The AccessKit Authors. All rights reserved. +// Licensed under the Apache License, Version 2.0 (found in +// the LICENSE-APACHE file) or the MIT license (found in +// the LICENSE-MIT file), at your option. + +// Derived from Chromium's accessibility abstraction. +// Copyright 2021 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE.chromium file. + +#![allow(non_upper_case_globals)] + +use accesskit::{ + Action, ActionData, ActionRequest, AriaCurrent, HasPopup, Live, NodeId, Orientation, Point, + Role, SortDirection, TextSelection, Toggled, TreeId, +}; +use accesskit_consumer::{FilterResult, FullNodeId, NodeRef, Tree, TreeState}; +use std::{ + fmt::Write, + sync::{Arc, Weak, atomic::Ordering}, +}; +use windows::{ + Win32::{ + Foundation::*, + System::{Com::*, Variant::*}, + UI::Accessibility::*, + }, + core::*, +}; + +use crate::{ + context::Context, + filters::{filter, filter_with_root_exception}, + long_text::{Text, byte_at_point, long_text}, + text::PlatformRange as PlatformTextRange, + util::*, +}; + +const RUNTIME_ID_SIZE: usize = 5; + +fn runtime_id_from_node_id(id: FullNodeId) -> [i32; RUNTIME_ID_SIZE] { + static_assertions::assert_eq_size!(FullNodeId, u128); + let id: u128 = id.into(); + [ + UiaAppendRuntimeId as _, + ((id >> 96) & 0xFFFFFFFF) as _, + ((id >> 64) & 0xFFFFFFFF) as _, + ((id >> 32) & 0xFFFFFFFF) as _, + (id & 0xFFFFFFFF) as _, + ] +} + +pub(crate) struct NodeWrapper<'a> { + pub(crate) node: &'a NodeRef<'a>, + pub(crate) string_buffer: &'a mut Vec<u16>, +} + +impl NodeWrapper<'_> { + fn control_type(&self) -> UIA_CONTROLTYPE_ID { + let role = self.node.role(); + // TODO: Handle special cases. (#14) + match role { + Role::Unknown => UIA_CustomControlTypeId, + Role::TextRun => UIA_CustomControlTypeId, + Role::Cell | Role::GridCell => UIA_DataItemControlTypeId, + Role::Label => UIA_TextControlTypeId, + Role::Image => UIA_ImageControlTypeId, + Role::Link => UIA_HyperlinkControlTypeId, + Role::Row => UIA_DataItemControlTypeId, + Role::ListItem => UIA_ListItemControlTypeId, + Role::ListMarker => UIA_GroupControlTypeId, + Role::TreeItem => UIA_TreeItemControlTypeId, + Role::ListBoxOption => UIA_ListItemControlTypeId, + Role::MenuItem => UIA_MenuItemControlTypeId, + Role::MenuListOption => UIA_ListItemControlTypeId, + Role::Paragraph => UIA_GroupControlTypeId, + Role::GenericContainer => UIA_GroupControlTypeId, + Role::CheckBox => UIA_CheckBoxControlTypeId, + Role::RadioButton => UIA_RadioButtonControlTypeId, + Role::TextInput + | Role::MultilineTextInput + | Role::SearchInput + | Role::DateInput + | Role::DateTimeInput + | Role::WeekInput + | Role::MonthInput + | Role::TimeInput + | Role::EmailInput + | Role::NumberInput + | Role::PasswordInput + | Role::PhoneNumberInput + | Role::UrlInput => UIA_EditControlTypeId, + Role::Button | Role::DefaultButton => UIA_ButtonControlTypeId, + Role::Pane => UIA_PaneControlTypeId, + Role::RowHeader => UIA_DataItemControlTypeId, + Role::ColumnHeader => UIA_DataItemControlTypeId, + Role::RowGroup => UIA_GroupControlTypeId, + Role::List => UIA_ListControlTypeId, + Role::Table => UIA_TableControlTypeId, + Role::LayoutTableCell => UIA_DataItemControlTypeId, + Role::LayoutTableRow => UIA_DataItemControlTypeId, + Role::LayoutTable => UIA_TableControlTypeId, + Role::Switch => UIA_ButtonControlTypeId, + Role::Menu => UIA_MenuControlTypeId, + Role::Abbr => UIA_TextControlTypeId, + Role::Alert => UIA_TextControlTypeId, + Role::AlertDialog => { + // Documentation suggests the use of UIA_PaneControlTypeId, + // but Chromium's implementation uses UIA_WindowControlTypeId + // instead. + UIA_WindowControlTypeId + } + Role::Application => UIA_PaneControlTypeId, + Role::Article => UIA_GroupControlTypeId, + Role::Audio => UIA_GroupControlTypeId, + Role::Banner => UIA_GroupControlTypeId, + Role::Blockquote => UIA_GroupControlTypeId, + Role::Canvas => UIA_ImageControlTypeId, + Role::Caption => UIA_TextControlTypeId, + Role::Caret => UIA_GroupControlTypeId, + Role::Code => UIA_TextControlTypeId, + Role::ColorWell => UIA_ButtonControlTypeId, + Role::ComboBox | Role::EditableComboBox => UIA_ComboBoxControlTypeId, + Role::Complementary => UIA_GroupControlTypeId, + Role::Comment => UIA_GroupControlTypeId, + Role::ContentDeletion => UIA_GroupControlTypeId, + Role::ContentInsertion => UIA_GroupControlTypeId, + Role::ContentInfo => UIA_GroupControlTypeId, + Role::Definition => UIA_GroupControlTypeId, + Role::DescriptionList => UIA_ListControlTypeId, + Role::Details => UIA_GroupControlTypeId, + Role::Dialog => { + // Documentation suggests the use of UIA_PaneControlTypeId, + // but Chromium's implementation uses UIA_WindowControlTypeId + // instead. + UIA_WindowControlTypeId + } + Role::DisclosureTriangle => UIA_ButtonControlTypeId, + Role::Document | Role::Terminal => UIA_DocumentControlTypeId, + Role::EmbeddedObject => UIA_PaneControlTypeId, + Role::Emphasis => UIA_TextControlTypeId, + Role::Feed => UIA_GroupControlTypeId, + Role::FigureCaption => UIA_TextControlTypeId, + Role::Figure => UIA_GroupControlTypeId, + Role::Footer => UIA_GroupControlTypeId, + Role::Form => UIA_GroupControlTypeId, + Role::Grid => UIA_DataGridControlTypeId, + Role::Group => UIA_GroupControlTypeId, + Role::Header => UIA_GroupControlTypeId, + Role::Heading => UIA_TextControlTypeId, + Role::Iframe => UIA_DocumentControlTypeId, + Role::IframePresentational => UIA_GroupControlTypeId, + Role::ImeCandidate => UIA_PaneControlTypeId, + Role::Keyboard => UIA_PaneControlTypeId, + Role::Legend => UIA_TextControlTypeId, + Role::LineBreak => UIA_TextControlTypeId, + Role::ListBox => UIA_ListControlTypeId, + Role::Log => UIA_GroupControlTypeId, + Role::Main => UIA_GroupControlTypeId, + Role::Mark => UIA_TextControlTypeId, + Role::Marquee => UIA_TextControlTypeId, + Role::Math => UIA_GroupControlTypeId, + Role::MenuBar => UIA_MenuBarControlTypeId, + Role::MenuItemCheckBox => UIA_CheckBoxControlTypeId, + Role::MenuItemRadio => UIA_RadioButtonControlTypeId, + Role::MenuListPopup => UIA_ListControlTypeId, + Role::Meter => UIA_ProgressBarControlTypeId, + Role::Navigation => UIA_GroupControlTypeId, + Role::Note => UIA_GroupControlTypeId, + Role::PluginObject => UIA_GroupControlTypeId, + Role::ProgressIndicator => UIA_ProgressBarControlTypeId, + Role::RadioGroup => UIA_GroupControlTypeId, + Role::Region => UIA_GroupControlTypeId, + Role::RootWebArea => UIA_DocumentControlTypeId, + Role::Ruby => UIA_GroupControlTypeId, + Role::RubyAnnotation => { + // Generally exposed as description on <ruby> (Role::Ruby) + // element, not as its own object in the tree. + // However, it's possible to make a RubyAnnotation element + // show up in the AX tree, for example by adding tabindex="0" + // to the source <rp> or <rt> element or making the source element + // the target of an aria-owns. Therefore, browser side needs to + // gracefully handle it if it actually shows up in the tree. + UIA_TextControlTypeId + } + Role::ScrollBar => UIA_ScrollBarControlTypeId, + Role::ScrollView => UIA_PaneControlTypeId, + Role::Search => UIA_GroupControlTypeId, + Role::Section => UIA_GroupControlTypeId, + Role::SectionFooter => UIA_GroupControlTypeId, + Role::SectionHeader => UIA_GroupControlTypeId, + Role::Slider => UIA_SliderControlTypeId, + Role::SpinButton => UIA_SpinnerControlTypeId, + Role::Splitter => UIA_SeparatorControlTypeId, + Role::Status => UIA_StatusBarControlTypeId, + Role::Strong => UIA_TextControlTypeId, + Role::Suggestion => UIA_GroupControlTypeId, + Role::SvgRoot => UIA_ImageControlTypeId, + Role::Tab => UIA_TabItemControlTypeId, + Role::TabList => UIA_TabControlTypeId, + Role::TabPanel => UIA_PaneControlTypeId, + Role::Term => UIA_ListItemControlTypeId, + Role::Time => UIA_TextControlTypeId, + Role::Timer => UIA_PaneControlTypeId, + Role::TitleBar => UIA_PaneControlTypeId, + Role::Toolbar => UIA_ToolBarControlTypeId, + Role::Tooltip => UIA_ToolTipControlTypeId, + Role::Tree => UIA_TreeControlTypeId, + Role::TreeGrid => UIA_DataGridControlTypeId, + Role::Video => UIA_GroupControlTypeId, + Role::WebView => UIA_DocumentControlTypeId, + Role::Window => { + // TODO: determine whether to use Window or Pane. + // It may be good to use Pane for nested windows, + // as Chromium does. (#14) + UIA_WindowControlTypeId + } + Role::PdfActionableHighlight => UIA_CustomControlTypeId, + Role::PdfRoot => UIA_DocumentControlTypeId, + Role::GraphicsDocument => UIA_DocumentControlTypeId, + Role::GraphicsObject => UIA_PaneControlTypeId, + Role::GraphicsSymbol => UIA_ImageControlTypeId, + Role::DocAbstract => UIA_GroupControlTypeId, + Role::DocAcknowledgements => UIA_GroupControlTypeId, + Role::DocAfterword => UIA_GroupControlTypeId, + Role::DocAppendix => UIA_GroupControlTypeId, + Role::DocBackLink => UIA_HyperlinkControlTypeId, + Role::DocBiblioEntry => UIA_ListItemControlTypeId, + Role::DocBibliography => UIA_GroupControlTypeId, + Role::DocBiblioRef => UIA_HyperlinkControlTypeId, + Role::DocChapter => UIA_GroupControlTypeId, + Role::DocColophon => UIA_GroupControlTypeId, + Role::DocConclusion => UIA_GroupControlTypeId, + Role::DocCover => UIA_ImageControlTypeId, + Role::DocCredit => UIA_GroupControlTypeId, + Role::DocCredits => UIA_GroupControlTypeId, + Role::DocDedication => UIA_GroupControlTypeId, + Role::DocEndnote => UIA_ListItemControlTypeId, + Role::DocEndnotes => UIA_GroupControlTypeId, + Role::DocEpigraph => UIA_GroupControlTypeId, + Role::DocEpilogue => UIA_GroupControlTypeId, + Role::DocErrata => UIA_GroupControlTypeId, + Role::DocExample => UIA_GroupControlTypeId, + Role::DocFootnote => UIA_ListItemControlTypeId, + Role::DocForeword => UIA_GroupControlTypeId, + Role::DocGlossary => UIA_GroupControlTypeId, + Role::DocGlossRef => UIA_HyperlinkControlTypeId, + Role::DocIndex => UIA_GroupControlTypeId, + Role::DocIntroduction => UIA_GroupControlTypeId, + Role::DocNoteRef => UIA_HyperlinkControlTypeId, + Role::DocNotice => UIA_GroupControlTypeId, + Role::DocPageBreak => UIA_SeparatorControlTypeId, + Role::DocPageFooter => UIA_GroupControlTypeId, + Role::DocPageHeader => UIA_GroupControlTypeId, + Role::DocPageList => UIA_GroupControlTypeId, + Role::DocPart => UIA_GroupControlTypeId, + Role::DocPreface => UIA_GroupControlTypeId, + Role::DocPrologue => UIA_GroupControlTypeId, + Role::DocPullquote => UIA_GroupControlTypeId, + Role::DocQna => UIA_GroupControlTypeId, + Role::DocSubtitle => UIA_GroupControlTypeId, + Role::DocTip => UIA_GroupControlTypeId, + Role::DocToc => UIA_GroupControlTypeId, + Role::ListGrid => UIA_DataGridControlTypeId, + } + } + + fn localized_control_type(&mut self) -> Option<StrWrapper<'_>> { + self.node + .role_description() + .map(|s| StrWrapper::new(s, self.string_buffer)) + } + + fn aria_role(&mut self) -> Option<StrWrapper<'_>> { + match self.node.role() { + Role::Alert => Some("alert"), + Role::AlertDialog => Some("alertdialog"), + Role::Application => Some("application"), + Role::Article => Some("article"), + Role::Banner | Role::Header => Some("banner"), + Role::Button | Role::DefaultButton => Some("button"), + Role::Blockquote => Some("blockquote"), + Role::Caption | Role::FigureCaption => Some("caption"), + Role::Cell => Some("cell"), + Role::CheckBox => Some("checkbox"), + Role::Code => Some("code"), + Role::ColumnHeader => Some("columnheader"), + Role::ComboBox | Role::EditableComboBox => Some("combobox"), + Role::Comment => Some("comment"), + Role::Complementary => Some("complementary"), + Role::ContentInfo | Role::Footer => Some("contentinfo"), + Role::Definition => Some("definition"), + Role::ContentDeletion => Some("deletion"), + Role::Dialog => Some("dialog"), + Role::Document + | Role::Iframe + | Role::WebView + | Role::RootWebArea + | Role::Terminal + | Role::PdfRoot => Some("document"), + Role::Emphasis => Some("emphasis"), + Role::Feed => Some("feed"), + Role::Figure => Some("figure"), + Role::Form => Some("form"), + Role::GenericContainer => Some("generic"), + Role::GraphicsDocument => Some("graphics-document"), + Role::GraphicsObject => Some("graphics-object"), + Role::GraphicsSymbol => Some("graphics-symbol"), + Role::Grid | Role::ListGrid => Some("grid"), + Role::GridCell => Some("gridcell"), + Role::Group + | Role::Details + | Role::IframePresentational + | Role::TitleBar + | Role::LayoutTable + | Role::LayoutTableCell + | Role::LayoutTableRow + | Role::Audio + | Role::Video + | Role::ListMarker + | Role::EmbeddedObject + | Role::ImeCandidate => Some("group"), + Role::Heading => Some("heading"), + Role::Image | Role::Canvas => Some("img"), + Role::ContentInsertion => Some("insertion"), + Role::Link => Some("link"), + Role::List | Role::DescriptionList | Role::MenuListPopup => Some("list"), + Role::ListBox => Some("listbox"), + Role::ListItem => Some("listitem"), + Role::Log => Some("log"), + Role::Main => Some("main"), + Role::Mark => Some("marker"), + Role::Marquee => Some("marquee"), + Role::Math => Some("math"), + Role::Menu => Some("menu"), + Role::MenuBar => Some("menubar"), + Role::MenuItem => Some("menuitem"), + Role::MenuItemCheckBox => Some("menuitemcheckbox"), + Role::MenuItemRadio => Some("menuitemradio"), + Role::Meter => Some("meter"), + Role::Navigation => Some("navigation"), + Role::Note => Some("note"), + Role::ListBoxOption | Role::MenuListOption => Some("option"), + Role::Paragraph => Some("paragraph"), + Role::ProgressIndicator => Some("progressbar"), + Role::RadioButton => Some("radio"), + Role::RadioGroup => Some("radiogroup"), + Role::Region + | Role::Pane + | Role::Window + | Role::Keyboard + | Role::Unknown + | Role::ScrollView + | Role::Caret => Some("region"), + Role::Row => Some("row"), + Role::RowGroup => Some("rowgroup"), + Role::RowHeader => Some("rowheader"), + Role::ScrollBar => Some("scrollbar"), + Role::Search => Some("search"), + Role::SearchInput => Some("searchbox"), + Role::SectionFooter => Some("sectionfooter"), + Role::SectionHeader => Some("sectionheader"), + Role::Splitter => Some("separator"), + Role::Slider => Some("slider"), + Role::SpinButton => Some("spinbutton"), + Role::Status => Some("status"), + Role::Strong => Some("strong"), + // subscript + Role::Suggestion => Some("suggestion"), + // superscript + Role::Switch => Some("switch"), + Role::Tab => Some("tab"), + Role::Table => Some("table"), + Role::TabList => Some("tablist"), + Role::TabPanel => Some("tabpanel"), + Role::Term => Some("term"), + Role::TextInput + | Role::MultilineTextInput + | Role::DateInput + | Role::DateTimeInput + | Role::WeekInput + | Role::MonthInput + | Role::TimeInput + | Role::EmailInput + | Role::NumberInput + | Role::PasswordInput + | Role::PhoneNumberInput + | Role::UrlInput + | Role::ColorWell => Some("textbox"), + Role::Time => Some("time"), + Role::Timer => Some("timer"), + Role::Toolbar => Some("toolbar"), + Role::Tooltip => Some("tooltip"), + Role::Tree => Some("tree"), + Role::TreeGrid => Some("treegrid"), + Role::TreeItem => Some("treeitem"), + _ => { + // TODO: Expose more ARIA roles. + None + } + } + .map(|s| StrWrapper::new(s, self.string_buffer)) + } + + pub(crate) fn name(&mut self) -> Option<WideString<'_>> { + let mut result = WideString::new(self.string_buffer); + if self.node.label_comes_from_value() { + self.node.write_value(&mut result) + } else { + self.node.write_label(&mut result) + } + .unwrap() + .then_some(result) + } + + fn description(&mut self) -> Option<WideString<'_>> { + self.node.description().map(|s| { + let mut result = WideString::new(self.string_buffer); + result.write_str(&s).unwrap(); + result + }) + } + + fn culture(&self) -> Option<LocaleName<'_>> { + self.node.language().map(LocaleName) + } + + fn placeholder(&mut self) -> Option<StrWrapper<'_>> { + self.node + .placeholder() + .map(|s| StrWrapper::new(s, self.string_buffer)) + } + + fn is_content_element(&self) -> bool { + filter(self.node) == FilterResult::Include + } + + fn aria_properties(&mut self) -> Option<WideString<'_>> { + let mut result = WideString::new(self.string_buffer); + let mut properties = AriaProperties::new(&mut result); + + // TODO: Atomic, and busy flags should include false when explicitly set to that + if self.node.is_live_atomic() { + properties.write_bool_property("atomic", true).unwrap(); + } + + if let Some(label) = self.node.braille_label() { + properties.write_property("braillelabel", label).unwrap(); + } + + if let Some(description) = self.node.braille_role_description() { + properties + .write_property("brailleroledescription", description) + .unwrap(); + } + + if self.node.is_busy() { + properties.write_bool_property("busy", true).unwrap(); + } + + if let Some(colindextext) = self.node.column_index_text() { + properties + .write_property("colindextext", colindextext) + .unwrap(); + } + + if let Some(current) = self.node.aria_current() { + if current != AriaCurrent::False { + properties + .write_property( + "current", + match current { + AriaCurrent::True => "true", + AriaCurrent::Page => "page", + AriaCurrent::Step => "step", + AriaCurrent::Location => "location", + AriaCurrent::Date => "date", + AriaCurrent::Time => "time", + AriaCurrent::False => unreachable!(), + }, + ) + .unwrap(); + } + } + + if let Some(has_popup) = self.node.has_popup() { + properties + .write_property( + "haspopup", + match has_popup { + HasPopup::Menu => "menu", + HasPopup::Listbox => "listbox", + HasPopup::Tree => "tree", + HasPopup::Grid => "grid", + HasPopup::Dialog => "dialog", + }, + ) + .unwrap(); + } + + if let Some(level) = self.node.level() { + properties.write_usize_property("level", level).unwrap(); + } + + if self.node.is_multiline() { + properties.write_bool_property("multiline", true).unwrap(); + } + + if let Some(rowindextext) = self.node.row_index_text() { + properties + .write_property("rowindextext", rowindextext) + .unwrap(); + } + + if let Some(sort_direction) = self.node.sort_direction() { + properties + .write_property( + "sort", + match sort_direction { + SortDirection::Ascending => "ascending", + SortDirection::Descending => "descending", + SortDirection::Other => "other", + }, + ) + .unwrap(); + } + + if properties.has_properties() { + Some(result) + } else { + None + } + } + + fn is_enabled(&self) -> bool { + !self.node.is_disabled() + } + + fn is_focusable(&self) -> bool { + self.node.is_focusable(&filter) + } + + fn is_focused(&self) -> bool { + self.node.is_focused() + } + + fn live_setting(&self) -> LiveSetting { + let live = self.node.live(); + match live { + Live::Off => Off, + Live::Polite => Polite, + Live::Assertive => Assertive, + } + } + + fn automation_id(&mut self) -> Option<StrWrapper<'_>> { + self.node + .html_id() + .or_else(|| self.node.author_id()) + .map(|s| StrWrapper::new(s, self.string_buffer)) + } + + fn class_name(&mut self) -> Option<StrWrapper<'_>> { + self.node + .class_name() + .map(|s| StrWrapper::new(s, self.string_buffer)) + } + + fn orientation(&self) -> OrientationType { + match self.node.orientation() { + Some(Orientation::Horizontal) => OrientationType_Horizontal, + Some(Orientation::Vertical) => OrientationType_Vertical, + None => OrientationType_None, + } + } + + fn is_toggle_pattern_supported(&self) -> bool { + self.node.toggled().is_some() && !self.is_selection_item_pattern_supported() + } + + fn toggle_state(&self) -> ToggleState { + match self.node.toggled().unwrap() { + Toggled::False => ToggleState_Off, + Toggled::True => ToggleState_On, + Toggled::Mixed => ToggleState_Indeterminate, + } + } + + fn is_invoke_pattern_supported(&self) -> bool { + self.node.is_invocable(&filter) + } + + fn is_value_pattern_supported(&self) -> bool { + if self.node.supports_url() { + return true; + } + self.node.has_value() && !self.node.label_comes_from_value() + } + + fn is_range_value_pattern_supported(&self) -> bool { + self.node.numeric_value().is_some() + } + + fn value(&mut self) -> WideString<'_> { + if let Some(url) = self.node.supports_url().then(|| self.node.url()).flatten() { + let mut result = WideString::new(self.string_buffer); + result.write_str(url).unwrap(); + return result; + } + let mut result = WideString::new(self.string_buffer); + self.node.write_value(&mut result).unwrap(); + result + } + + fn is_read_only(&self) -> bool { + self.node.is_read_only() + } + + fn numeric_value(&self) -> f64 { + self.node.numeric_value().unwrap() + } + + fn min_numeric_value(&self) -> f64 { + self.node.min_numeric_value().unwrap_or(0.0) + } + + fn max_numeric_value(&self) -> f64 { + self.node.max_numeric_value().unwrap_or(0.0) + } + + fn numeric_value_step(&self) -> f64 { + self.node.numeric_value_step().unwrap_or(0.0) + } + + fn numeric_value_jump(&self) -> f64 { + self.node + .numeric_value_jump() + .unwrap_or_else(|| self.numeric_value_step()) + } + + fn is_required(&self) -> bool { + self.node.is_required() + } + + fn is_scroll_item_pattern_supported(&self) -> bool { + self.node.supports_action(Action::ScrollIntoView, &filter) + } + + pub(crate) fn is_selection_item_pattern_supported(&self) -> bool { + match self.node.role() { + // TODO: tables (#29) + // https://www.w3.org/TR/core-aam-1.1/#mapping_state-property_table + // SelectionItem.IsSelected is exposed when aria-checked is True or + // False, for 'radio' and 'menuitemradio' roles. + Role::RadioButton | Role::MenuItemRadio => { + matches!(self.node.toggled(), Some(Toggled::True | Toggled::False)) + } + // https://www.w3.org/TR/wai-aria-1.1/#aria-selected + // SelectionItem.IsSelected is exposed when aria-select is True or False. + Role::ListBoxOption + | Role::ListItem + | Role::MenuListOption + | Role::Tab + | Role::TreeItem => self.node.is_selected().is_some(), + Role::GridCell => true, + _ => false, + } + } + + pub(crate) fn is_selected(&self) -> bool { + match self.node.role() { + // https://www.w3.org/TR/core-aam-1.1/#mapping_state-property_table + // SelectionItem.IsSelected is set according to the True or False + // value of aria-checked for 'radio' and 'menuitemradio' roles. + Role::RadioButton | Role::MenuItemRadio => self.node.toggled() == Some(Toggled::True), + // https://www.w3.org/TR/wai-aria-1.1/#aria-selected + // SelectionItem.IsSelected is set according to the True or False + // value of aria-selected. + _ => self.node.is_selected().unwrap_or(false), + } + } + + fn position_in_set(&self) -> Option<i32> { + self.node + .position_in_set() + .and_then(|p| p.try_into().ok()) + .map(|p: i32| p + 1) + } + + fn size_of_set(&self) -> Option<i32> { + self.node + .size_of_set_from_container(&filter) + .and_then(|s| s.try_into().ok()) + } + + fn level(&self) -> Option<i32> { + self.node + .level() + .and_then(|level| level.checked_add(1)) + .and_then(|level| level.try_into().ok()) + } + + fn is_selection_pattern_supported(&self) -> bool { + self.node.is_container_with_selectable_children() + } + + fn is_multiselectable(&self) -> bool { + self.node.is_multiselectable() + } + + fn is_text_pattern_supported(&self) -> bool { + self.node.supports_text_ranges() || long_text(&self.node).is_some() + } + + fn is_expand_collapse_pattern_supported(&self) -> bool { + self.node.supports_expand_collapse() + } + + fn expand_collapse_state(&self) -> ExpandCollapseState { + match self.node.data().is_expanded() { + Some(true) => ExpandCollapseState_Expanded, + Some(false) => ExpandCollapseState_Collapsed, + // TODO: Handle the menu button case. (#27) + None => ExpandCollapseState_LeafNode, + } + } + + fn is_password(&self) -> bool { + self.node.is_password_input() + } + + fn is_dialog(&self) -> bool { + self.node.is_dialog() + } + + // Rune (vendor/accesskit_windows.patch): headings and landmarks as UIA reports them, which + // Narrator's and NVDA's heading and landmark navigation read, as Chromium maps ARIA's. + fn heading_level(&self) -> Option<i32> { + if self.node.role() != Role::Heading { + return None; + } + // ARIA's default heading level is 2. + let level = self.node.level().map_or(2, |l| l + 1).clamp(1, 9) as i32; + Some(HeadingLevel1.0 + level - 1) + } + + fn landmark_type(&self) -> Option<i32> { + let id = match self.node.role() { + Role::Main => UIA_MainLandmarkTypeId, + Role::Navigation => UIA_NavigationLandmarkTypeId, + Role::Search => UIA_SearchLandmarkTypeId, + Role::Form if self.node.label().is_some() => UIA_FormLandmarkTypeId, + Role::Banner | Role::Header | Role::Complementary | Role::ContentInfo | Role::Footer => UIA_CustomLandmarkTypeId, + Role::Region if self.node.label().is_some() => UIA_CustomLandmarkTypeId, + _ => return None, + }; + Some(id.0) + } + + fn localized_landmark_type(&mut self) -> Option<StrWrapper<'_>> { + let name = match self.node.role() { + Role::Banner | Role::Header => "banner", + Role::Complementary => "complementary", + Role::ContentInfo | Role::Footer => "content information", + Role::Region if self.node.label().is_some() => "region", + _ => return None, + }; + Some(StrWrapper::new(name, self.string_buffer)) + } + + fn is_window_pattern_supported(&self) -> bool { + self.node.is_dialog() + } + + fn is_modal(&self) -> bool { + self.node.is_modal() + } + + pub(crate) fn enqueue_property_changes( + &mut self, + queue: &mut Vec<QueuedEvent>, + context: &Arc<Context>, + element: &IRawElementProviderSimple, + old: &mut NodeWrapper, + ) { + self.enqueue_simple_property_changes(queue, context, element, old); + self.enqueue_pattern_property_changes(queue, element, old); + self.enqueue_property_implied_events(queue, element, old); + } + + fn enqueue_property_implied_events( + &self, + queue: &mut Vec<QueuedEvent>, + element: &IRawElementProviderSimple, + old: &NodeWrapper, + ) { + if self.is_text_pattern_supported() + && old.is_text_pattern_supported() + && self.node.raw_text_selection() != old.node.raw_text_selection() + { + queue.push(QueuedEvent::Simple { + element: element.clone(), + event_id: UIA_Text_TextSelectionChangedEventId, + }); + } + } +} + +fn long_value_unchanged(new: &NodeRef, old: &NodeRef) -> bool { + long_text(new).is_some() && long_text(old).is_some() && new.raw_value() == old.raw_value() +} + +fn enqueue_property_change( + queue: &mut Vec<QueuedEvent>, + element: &IRawElementProviderSimple, + property_id: UIA_PROPERTY_ID, + old_value: Variant, + new_value: Variant, +) { + let old_value: VARIANT = old_value.into(); + let new_value: VARIANT = new_value.into(); + queue.push(QueuedEvent::PropertyChanged { + element: element.clone(), + property_id, + old_value, + new_value, + }); +} + +#[implement( + IRawElementProviderSimple, + IRawElementProviderFragment, + IRawElementProviderFragmentRoot, + IToggleProvider, + IInvokeProvider, + IValueProvider, + IRangeValueProvider, + IScrollItemProvider, + ISelectionItemProvider, + ISelectionProvider, + ITextProvider, + ITextProvider2, + IExpandCollapseProvider, + IWindowProvider +)] +pub(crate) struct PlatformNode { + pub(crate) context: Weak<Context>, + pub(crate) node_id: Option<FullNodeId>, +} + +impl PlatformNode { + pub(crate) fn new(context: &Arc<Context>, node_id: FullNodeId) -> ComObject<Self> { + Self { + context: Arc::downgrade(context), + node_id: Some(node_id), + } + .into_object() + } + + pub(crate) fn unspecified_root(context: &Arc<Context>) -> ComObject<Self> { + Self { + context: Arc::downgrade(context), + node_id: None, + } + .into_object() + } + + fn upgrade_context(&self) -> Result<Arc<Context>> { + upgrade(&self.context) + } + + fn with_tree_state_and_context<F, T>(&self, f: F) -> Result<T> + where + F: FnOnce(&TreeState, &Arc<Context>) -> Result<T>, + { + self.with_tree_and_context(|tree, context| f(tree.state(), context)) + } + + fn with_tree_and_context<F, T>(&self, f: F) -> Result<T> + where + F: FnOnce(&Tree, &Arc<Context>) -> Result<T>, + { + std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + let context = self.upgrade_context()?; + let tree = context.read_tree(); + f(&tree, &context) + })) + .unwrap_or_else(|_| Err(element_not_available())) + } + + fn node<'a>(&self, tree: &'a Tree) -> Result<NodeRef<'a>> { + let state = tree.state(); + if let Some(id) = self.node_id { + if let Some(node) = state.node_by_id(id) { + Ok(node) + } else { + Err(element_not_available()) + } + } else { + Ok(state.root()) + } + } + + fn node_with_location<'a>(&self, tree: &'a Tree) -> Result<(NodeRef<'a>, NodeId, TreeId)> { + let node = self.node(tree)?; + let (local_id, tree_id) = tree + .state() + .locate_node(node.id()) + .ok_or_else(element_not_available)?; + Ok((node, local_id, tree_id)) + } + + fn resolve_with_context<F, T>(&self, f: F) -> Result<T> + where + for<'a> F: FnOnce(NodeRef<'a>, &Arc<Context>) -> Result<T>, + { + self.with_tree_and_context(|tree, context| { + let node = self.node(tree)?; + f(node, context) + }) + } + + fn resolve_with_tree_state_and_context<F, T>(&self, f: F) -> Result<T> + where + for<'a> F: FnOnce(NodeRef<'a>, &TreeState, &Arc<Context>) -> Result<T>, + { + self.with_tree_and_context(|tree, context| { + let node = self.node(tree)?; + f(node, tree.state(), context) + }) + } + + fn resolve<F, T>(&self, f: F) -> Result<T> + where + for<'a> F: FnOnce(NodeRef<'a>) -> Result<T>, + { + self.resolve_with_context(|node, _| f(node)) + } + + fn resolve_with_context_for_text_pattern<F, T>(&self, f: F) -> Result<T> + where + for<'a> F: FnOnce(NodeRef<'a>, &Arc<Context>) -> Result<T>, + { + self.with_tree_and_context(|tree, context| { + let node = self.node(tree)?; + if node.supports_text_ranges() { + f(node, context) + } else { + Err(element_not_available()) + } + }) + } + + /// Rune: if this node is a long field ([`long_text`]), its range `f` picks, in its value's + /// bytes. + fn long_range(&self, f: impl FnOnce(Text, &TextSelection) -> (usize, usize)) -> Result<Option<ITextRangeProvider>> { + self.resolve(|node| { + Ok(long_text(&node).map(|(text, selection)| { + let (a, b) = f(text, selection); + let (a, b) = (text.clamp(a.min(b)), text.clamp(a.max(b))); + PlatformTextRange::new_long(&self.context, node.id(), a, b).into() + })) + }) + } + + fn resolve_for_text_pattern<F, T>(&self, f: F) -> Result<T> + where + for<'a> F: FnOnce(NodeRef<'a>) -> Result<T>, + { + self.resolve_with_context_for_text_pattern(|node, _| f(node)) + } + + fn do_complex_action<F>(&self, f: F) -> Result<()> + where + for<'a> F: FnOnce(NodeRef<'a>, NodeId, TreeId) -> Result<Option<ActionRequest>>, + { + std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + let context = self.upgrade_context()?; + if context.is_placeholder.load(Ordering::SeqCst) { + return Err(element_not_enabled()); + } + let tree = context.read_tree(); + let (node, target_node, target_tree) = self.node_with_location(&tree)?; + if let Some(request) = f(node, target_node, target_tree)? { + drop(tree); + context.do_action(request); + } + Ok(()) + })) + .unwrap_or_else(|_| Err(element_not_available())) + } + + fn do_action<F>(&self, f: F) -> Result<()> + where + F: FnOnce() -> (Action, Option<ActionData>), + { + self.do_complex_action(|node, target_node, target_tree| { + if node.is_disabled() { + return Err(element_not_enabled()); + } + let (action, data) = f(); + Ok(Some(ActionRequest { + action, + target_tree, + target_node, + data, + })) + }) + } + + fn click(&self) -> Result<()> { + self.do_action(|| (Action::Click, None)) + } + + fn set_expanded(&self, expanded: bool) -> Result<()> { + self.do_complex_action(|node, target_node, target_tree| { + if node.is_disabled() { + return Err(element_not_enabled()); + } + let Some(current) = node.data().is_expanded() else { + return Err(invalid_operation()); + }; + if current == expanded { + return Err(invalid_operation()); + } + Ok(Some(ActionRequest { + action: if expanded { + Action::Expand + } else { + Action::Collapse + }, + target_tree, + target_node, + data: None, + })) + }) + } + + fn set_selected(&self, selected: bool) -> Result<()> { + self.do_complex_action(|node, target_node, target_tree| { + if node.is_disabled() { + return Err(element_not_enabled()); + } + let mut buffer = StringBuffer::acquire(); + let wrapper = NodeWrapper { + node: &node, + string_buffer: &mut buffer, + }; + if selected == wrapper.is_selected() { + return Ok(None); + } + Ok(Some(ActionRequest { + action: Action::Click, + target_tree, + target_node, + data: None, + })) + }) + } + + fn is_root(&self, state: &TreeState) -> bool { + self.node_id.is_some_and(|id| id == state.root_id()) + } +} + +#[allow(non_snake_case)] +impl IRawElementProviderSimple_Impl for PlatformNode_Impl { + fn ProviderOptions(&self) -> Result<ProviderOptions> { + Ok(ProviderOptions_ServerSideProvider) + } + + fn GetPatternProvider(&self, pattern_id: UIA_PATTERN_ID) -> Result<IUnknown> { + self.pattern_provider(pattern_id) + } + + fn GetPropertyValue(&self, property_id: UIA_PROPERTY_ID) -> Result<VARIANT> { + self.resolve_with_tree_state_and_context(|node, state, context| { + let mut buffer = StringBuffer::acquire(); + let mut wrapper = NodeWrapper { + node: &node, + string_buffer: &mut buffer, + }; + let mut result = wrapper.get_property_value(property_id); + if result.is_empty() { + if node.is_root() { + match property_id { + UIA_NamePropertyId => { + result = window_title(context.hwnd, &mut buffer).into(); + } + UIA_NativeWindowHandlePropertyId => { + result = (context.hwnd.0.0 as i32).into(); + } + _ => (), + } + } + match property_id { + UIA_FrameworkIdPropertyId => { + result = StrWrapper::new(state.toolkit_name(), &mut buffer).into() + } + UIA_ProviderDescriptionPropertyId => { + result = toolkit_description(state, &mut buffer).into() + } + UIA_ControllerForPropertyId => { + let controlled: Vec<IUnknown> = node + .controls() + .filter(|controlled| filter(controlled) == FilterResult::Include) + .map(|controlled| context.get_or_create_platform_node(controlled.id())) + .map(|result| result.into_interface::<IRawElementProviderSimple>()) + .filter_map(|controlled| controlled.cast::<IUnknown>().ok()) + .collect(); + result = controlled.into(); + } + _ => (), + } + } + Ok(result.into()) + }) + } + + fn HostRawElementProvider(&self) -> Result<IRawElementProviderSimple> { + self.with_tree_state_and_context(|state, context| { + if self.is_root(state) { + unsafe { UiaHostProviderFromHwnd(context.hwnd.0) } + } else { + Err(Error::empty()) + } + }) + } +} + +#[allow(non_snake_case)] +impl IRawElementProviderFragment_Impl for PlatformNode_Impl { + fn Navigate(&self, direction: NavigateDirection) -> Result<IRawElementProviderFragment> { + self.resolve_with_context(|node, context| { + let result = match direction { + NavigateDirection_Parent => node.filtered_parent(&filter_with_root_exception), + NavigateDirection_NextSibling => node.following_filtered_siblings(&filter).next(), + NavigateDirection_PreviousSibling => { + node.preceding_filtered_siblings(&filter).next() + } + NavigateDirection_FirstChild => node.filtered_children(&filter).next(), + NavigateDirection_LastChild => node.filtered_children(&filter).next_back(), + _ => None, + }; + match result { + Some(result) => Ok(context + .get_or_create_platform_node(result.id()) + .into_interface()), + None => Err(Error::empty()), + } + }) + } + + fn GetRuntimeId(&self) -> Result<*mut SAFEARRAY> { + let node_id = if let Some(id) = self.node_id { + id + } else { + // Since this `PlatformNode` isn't associated with a specific + // node ID, but always uses whatever node is currently the root, + // we shouldn't return a UIA runtime ID calculated from an + // AccessKit node ID, as we normally do. Fortunately, + // UIA doesn't seem to actually call `GetRuntimeId` on the root. + return Err(not_implemented()); + }; + let runtime_id = runtime_id_from_node_id(node_id); + Ok(safe_array_from_i32_slice(&runtime_id)) + } + + fn BoundingRectangle(&self) -> Result<UiaRect> { + self.resolve_with_context(|node, context| { + let rect = node.bounding_box().map_or(UiaRect::default(), |rect| { + let client_top_left = context.client_top_left(); + UiaRect { + left: rect.x0 + client_top_left.x, + top: rect.y0 + client_top_left.y, + width: rect.width(), + height: rect.height(), + } + }); + Ok(rect) + }) + } + + fn GetEmbeddedFragmentRoots(&self) -> Result<*mut SAFEARRAY> { + Ok(std::ptr::null_mut()) + } + + fn SetFocus(&self) -> Result<()> { + self.do_action(|| (Action::Focus, None)) + } + + fn FragmentRoot(&self) -> Result<IRawElementProviderFragmentRoot> { + self.with_tree_state_and_context(|state, context| { + if self.is_root(state) { + Ok(self.to_interface()) + } else { + let root_id = state.root_id(); + Ok(context + .get_or_create_platform_node(root_id) + .into_interface()) + } + }) + } +} + +#[allow(non_snake_case)] +impl IRawElementProviderFragmentRoot_Impl for PlatformNode_Impl { + fn ElementProviderFromPoint(&self, x: f64, y: f64) -> Result<IRawElementProviderFragment> { + self.resolve_with_context(|node, context| { + let client_top_left = context.client_top_left(); + let point = Point::new(x - client_top_left.x, y - client_top_left.y); + let point = node.transform().inverse() * point; + node.node_at_point(point, &filter).map_or_else( + || Err(Error::empty()), + |node| { + Ok(context + .get_or_create_platform_node(node.id()) + .into_interface()) + }, + ) + }) + } + + fn GetFocus(&self) -> Result<IRawElementProviderFragment> { + self.with_tree_state_and_context(|state, context| { + if let Some(node) = state.focus() { + let id = node.id(); + let self_id = if let Some(id) = self.node_id { + id + } else { + state.root_id() + }; + if id != self_id { + return Ok(context.get_or_create_platform_node(id).into_interface()); + } + } + Err(Error::empty()) + }) + } +} + +macro_rules! properties { + ($(($id:ident, $m:ident)),+) => { + impl NodeWrapper<'_> { + fn get_property_value(&mut self, property_id: UIA_PROPERTY_ID) -> Variant { + match property_id { + $($id => { + self.$m().into() + })* + _ => Variant::empty() + } + } + fn enqueue_simple_property_changes( + &mut self, + queue: &mut Vec<QueuedEvent>, + context: &Arc<Context>, + element: &IRawElementProviderSimple, + old: &mut NodeWrapper, + ) { + $({ + let old_value = old.$m(); + let new_value = self.$m(); + if old_value != new_value { + enqueue_property_change( + queue, + element, + $id, + old_value.into(), + new_value.into(), + ); + } + })* + + let mut old_controls = old.node.controls().filter(|controlled| filter(controlled) == FilterResult::Include); + let mut new_controls = self.node.controls().filter(|controlled| filter(controlled) == FilterResult::Include); + let mut are_equal = true; + let mut controls: Vec<IUnknown> = Vec::new(); + loop { + let old_controlled = old_controls.next(); + let new_controlled = new_controls.next(); + match (old_controlled, new_controlled) { + (Some(a), Some(b)) => { + are_equal = are_equal && a.id() == b.id(); + controls.push(context.get_or_create_platform_node(b.id()).into_interface::<IRawElementProviderSimple>().into()); + } + (None, None) => break, + _ => are_equal = false, + } + } + if !are_equal { + enqueue_property_change( + queue, + &element, + UIA_ControllerForPropertyId, + Variant::empty(), + controls.into(), + ); + } + } + } + }; +} + +macro_rules! patterns { + ($(($pattern_id:ident, $provider_interface:ident, $provider_interface_impl:ident, $is_supported:ident, ( + $(($property_id:ident, $com_getter:ident, $getter:ident, $com_type:ident)),* + ), ( + $($extra_trait_method:item),* + ))),+) => { + impl PlatformNode_Impl { + fn pattern_provider(&self, pattern_id: UIA_PATTERN_ID) -> Result<IUnknown> { + self.resolve(|node| { + let mut buffer = StringBuffer::acquire(); + let wrapper = NodeWrapper { node: &node, string_buffer: &mut buffer }; + match pattern_id { + $($pattern_id if wrapper.$is_supported() => { + let intermediate: $provider_interface = self.to_interface(); + return intermediate.cast(); + })* + _ => (), + } + Err(Error::empty()) + }) + } + } + impl NodeWrapper<'_> { + fn enqueue_pattern_property_changes( + &mut self, + queue: &mut Vec<QueuedEvent>, + element: &IRawElementProviderSimple, + old: &mut NodeWrapper, + ) { + $(if self.$is_supported() && old.$is_supported() { + $( + // Rune: a long field's unchanged value isn't copied twice to UTF-16 to find + // it unchanged (14.5 MB each way at 200,000 lines, on every caret move). + if !(stringify!($getter) == "value" && long_value_unchanged(&self.node, &old.node)) { + let old_value = old.$getter(); + let new_value = self.$getter(); + if old_value != new_value { + enqueue_property_change( + queue, + element, + $property_id, + old_value.into(), + new_value.into(), + ); + } + })* + })* + } + } + $(#[allow(non_snake_case)] + impl $provider_interface_impl for PlatformNode_Impl { + $(fn $com_getter(&self) -> Result<$com_type> { + self.resolve(|node| { + let mut buffer = StringBuffer::acquire(); + #[allow(unused_mut)] + let mut wrapper = NodeWrapper { node: &node, string_buffer: &mut buffer }; + Ok(wrapper.$getter().into()) + }) + })* + $($extra_trait_method)* + })* + }; +} + +properties! { + (UIA_ControlTypePropertyId, control_type), + (UIA_LocalizedControlTypePropertyId, localized_control_type), + (UIA_AriaRolePropertyId, aria_role), + (UIA_NamePropertyId, name), + (UIA_FullDescriptionPropertyId, description), + (UIA_CulturePropertyId, culture), + (UIA_HelpTextPropertyId, placeholder), + (UIA_IsContentElementPropertyId, is_content_element), + (UIA_IsControlElementPropertyId, is_content_element), + (UIA_IsEnabledPropertyId, is_enabled), + (UIA_IsKeyboardFocusablePropertyId, is_focusable), + (UIA_HasKeyboardFocusPropertyId, is_focused), + (UIA_LiveSettingPropertyId, live_setting), + (UIA_AutomationIdPropertyId, automation_id), + (UIA_ClassNamePropertyId, class_name), + (UIA_OrientationPropertyId, orientation), + (UIA_IsRequiredForFormPropertyId, is_required), + (UIA_IsPasswordPropertyId, is_password), + (UIA_LevelPropertyId, level), + (UIA_PositionInSetPropertyId, position_in_set), + (UIA_SizeOfSetPropertyId, size_of_set), + (UIA_AriaPropertiesPropertyId, aria_properties), + (UIA_IsDialogPropertyId, is_dialog), + (UIA_HeadingLevelPropertyId, heading_level), + (UIA_LandmarkTypePropertyId, landmark_type), + (UIA_LocalizedLandmarkTypePropertyId, localized_landmark_type) +} + +patterns! { + (UIA_TogglePatternId, IToggleProvider, IToggleProvider_Impl, is_toggle_pattern_supported, ( + (UIA_ToggleToggleStatePropertyId, ToggleState, toggle_state, ToggleState) + ), ( + fn Toggle(&self) -> Result<()> { + self.click() + } + )), + (UIA_InvokePatternId, IInvokeProvider, IInvokeProvider_Impl, is_invoke_pattern_supported, (), ( + fn Invoke(&self) -> Result<()> { + self.click() + } + )), + (UIA_ValuePatternId, IValueProvider, IValueProvider_Impl, is_value_pattern_supported, ( + (UIA_ValueValuePropertyId, Value, value, BSTR), + (UIA_ValueIsReadOnlyPropertyId, IsReadOnly, is_read_only, BOOL) + ), ( + fn SetValue(&self, value: &PCWSTR) -> Result<()> { + self.do_action(|| { + let value = unsafe { value.to_string() }.unwrap(); + (Action::SetValue, Some(ActionData::Value(value.into()))) + }) + } + )), + (UIA_RangeValuePatternId, IRangeValueProvider, IRangeValueProvider_Impl, is_range_value_pattern_supported, ( + (UIA_RangeValueValuePropertyId, Value, numeric_value, f64), + (UIA_RangeValueIsReadOnlyPropertyId, IsReadOnly, is_read_only, BOOL), + (UIA_RangeValueMinimumPropertyId, Minimum, min_numeric_value, f64), + (UIA_RangeValueMaximumPropertyId, Maximum, max_numeric_value, f64), + (UIA_RangeValueSmallChangePropertyId, SmallChange, numeric_value_step, f64), + (UIA_RangeValueLargeChangePropertyId, LargeChange, numeric_value_jump, f64) + ), ( + fn SetValue(&self, value: f64) -> Result<()> { + self.do_action(|| { + (Action::SetValue, Some(ActionData::NumericValue(value))) + }) + } + )), + (UIA_ScrollItemPatternId, IScrollItemProvider, IScrollItemProvider_Impl, is_scroll_item_pattern_supported, (), ( + fn ScrollIntoView(&self) -> Result<()> { + self.do_complex_action(|_node, target_node, target_tree| { + Ok(Some(ActionRequest { + action: Action::ScrollIntoView, + target_tree, + target_node, + data: None, + })) + }) + } + )), + (UIA_SelectionItemPatternId, ISelectionItemProvider, ISelectionItemProvider_Impl, is_selection_item_pattern_supported, (), ( + fn IsSelected(&self) -> Result<BOOL> { + self.resolve(|node| { + let mut buffer = StringBuffer::acquire(); + let wrapper = NodeWrapper { + node: &node, + string_buffer: &mut buffer, + }; + Ok(wrapper.is_selected().into()) + }) + }, + + fn Select(&self) -> Result<()> { + self.set_selected(true) + }, + + fn AddToSelection(&self) -> Result<()> { + self.set_selected(true) + }, + + fn RemoveFromSelection(&self) -> Result<()> { + self.set_selected(false) + }, + + fn SelectionContainer(&self) -> Result<IRawElementProviderSimple> { + self.resolve_with_context(|node, context| { + if let Some(container) = node.selection_container(&filter) { + Ok(context.get_or_create_platform_node(container.id()).into_interface()) + } else { + Err(E_FAIL.into()) + } + }) + } + )), + (UIA_SelectionPatternId, ISelectionProvider, ISelectionProvider_Impl, is_selection_pattern_supported, ( + (UIA_SelectionCanSelectMultiplePropertyId, CanSelectMultiple, is_multiselectable, BOOL), + (UIA_SelectionIsSelectionRequiredPropertyId, IsSelectionRequired, is_required, BOOL) + ), ( + fn GetSelection(&self) -> Result<*mut SAFEARRAY> { + self.resolve_with_context(|node, context| { + let selection: Vec<_> = node + .items(&filter) + .filter(|item| item.is_selected() == Some(true)) + .map(|item| context.get_or_create_platform_node(item.id()).into_interface::<IRawElementProviderSimple>()) + .filter_map(|item| item.cast::<IUnknown>().ok()) + .collect(); + Ok(safe_array_from_com_slice(&selection)) + }) + } + )), + (UIA_TextPatternId, ITextProvider, ITextProvider_Impl, is_text_pattern_supported, (), ( + fn GetSelection(&self) -> Result<*mut SAFEARRAY> { + if let Some(range) = self.long_range(|_, s| (s.anchor.character_index, s.focus.character_index))? { + return Ok(safe_array_from_com_slice(&[range.cast::<IUnknown>()?])); + } + self.resolve_for_text_pattern(|node| { + if let Some(range) = node.text_selection() { + let platform_range: ITextRangeProvider = PlatformTextRange::new(&self.context, range).into(); + let iunknown: IUnknown = platform_range.cast()?; + Ok(safe_array_from_com_slice(&[iunknown])) + } else { + Ok(std::ptr::null_mut()) + } + }) + }, + + fn GetVisibleRanges(&self) -> Result<*mut SAFEARRAY> { + // TBD: Do we need this? The Quorum GUI toolkit, which is our + // current point of comparison for text functionality, + // doesn't implement it. + Ok(std::ptr::null_mut()) + }, + + fn RangeFromChild(&self, _child: Ref<IRawElementProviderSimple>) -> Result<ITextRangeProvider> { + // We don't support embedded objects in text. + Err(not_implemented()) + }, + + fn RangeFromPoint(&self, point: &UiaPoint) -> Result<ITextRangeProvider> { + let hit = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + self.resolve_with_context(|node, context| { + Ok(long_text(&node).map(|(text, s)| { + let client_top_left = context.client_top_left(); + let pt = Point::new(point.x - client_top_left.x, point.y - client_top_left.y); + let pt = node.transform().inverse() * pt; + let at = byte_at_point(&node, text, pt, false).unwrap_or_else(|| text.clamp(s.focus.character_index)); + PlatformTextRange::new_long(&self.context, node.id(), at, at).into() + })) + }) + })) + .unwrap_or_else(|_| Err(element_not_available()))?; + if let Some(range) = hit { + return Ok(range); + } + self.resolve_with_context_for_text_pattern(|node, context| { + let client_top_left = context.client_top_left(); + let point = Point::new(point.x - client_top_left.x, point.y - client_top_left.y); + let point = node.transform().inverse() * point; + let pos = node.text_position_at_point(point); + let range = pos.to_degenerate_range(); + Ok(PlatformTextRange::new(&self.context, range).into()) + }) + }, + + fn DocumentRange(&self) -> Result<ITextRangeProvider> { + if let Some(range) = self.long_range(|text, _| (0, text.len()))? { + return Ok(range); + } + self.resolve_for_text_pattern(|node| { + let range = node.document_range(); + Ok(PlatformTextRange::new(&self.context, range).into()) + }) + }, + + fn SupportedTextSelection(&self) -> Result<SupportedTextSelection> { + if self.long_range(|_, _| (0, 0))?.is_some() { + return Ok(SupportedTextSelection_Single); + } + self.resolve_for_text_pattern(|node| { + if node.has_text_selection() { + Ok(SupportedTextSelection_Single) + } else { + Ok(SupportedTextSelection_None) + } + }) + } + )), + (UIA_TextPattern2Id, ITextProvider2, ITextProvider2_Impl, is_text_pattern_supported, (), ( + fn RangeFromAnnotation(&self, _annotation: Ref<IRawElementProviderSimple>) -> Result<ITextRangeProvider> { + Err(not_supported()) + }, + + fn GetCaretRange(&self, is_active: *mut BOOL) -> Result<ITextRangeProvider> { + std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + let long_caret = self.resolve(|node| { + Ok(long_text(&node).map(|(text, s)| { + if !is_active.is_null() { + unsafe { *is_active = node.is_focused().into() }; + } + let at = text.clamp(s.focus.character_index); + PlatformTextRange::new_long(&self.context, node.id(), at, at).into() + })) + })?; + if let Some(range) = long_caret { + return Ok(range); + } + self.resolve_for_text_pattern(|node| { + if !is_active.is_null() { + unsafe { *is_active = node.is_focused().into() }; + } + let pos = node.text_selection_focus().unwrap_or_else(|| node.document_start()); + Ok(PlatformTextRange::new(&self.context, pos.to_degenerate_range()).into()) + }) + })) + .unwrap_or_else(|_| Err(element_not_available())) + } + )), + (UIA_ExpandCollapsePatternId, IExpandCollapseProvider, IExpandCollapseProvider_Impl, is_expand_collapse_pattern_supported, ( + (UIA_ExpandCollapseExpandCollapseStatePropertyId, ExpandCollapseState, expand_collapse_state, ExpandCollapseState) + ), ( + fn Expand(&self) -> Result<()> { + self.set_expanded(true) + }, + + fn Collapse(&self) -> Result<()> { + self.set_expanded(false) + } + )), + (UIA_WindowPatternId, IWindowProvider, IWindowProvider_Impl, is_window_pattern_supported, ( + (UIA_WindowIsModalPropertyId, IsModal, is_modal, BOOL) + ), ( + fn SetVisualState(&self, _: WindowVisualState) -> Result<()> { + Err(invalid_operation()) + }, + + fn Close(&self) -> Result<()> { + Err(not_supported()) + }, + + fn WaitForInputIdle(&self, _: i32) -> Result<BOOL> { + Err(not_supported()) + }, + + fn CanMaximize(&self) -> Result<BOOL> { + Err(not_supported()) + }, + + fn CanMinimize(&self) -> Result<BOOL> { + Err(not_supported()) + }, + + fn WindowVisualState(&self) -> Result<WindowVisualState> { + Err(not_supported()) + }, + + fn WindowInteractionState(&self) -> Result<WindowInteractionState> { + Ok(WindowInteractionState_ReadyForUserInteraction) + }, + + fn IsTopmost(&self) -> Result<BOOL> { + Err(not_supported()) + } + )) +} + +// Ensures that `PlatformNode` is actually safe to use in the free-threaded +// manner that we advertise via `ProviderOptions`. +#[test] +fn platform_node_impl_send_sync() { + fn assert_send_sync<T: Send + Sync>() {} + assert_send_sync::<PlatformNode>(); +} diff --git a/app/vendor/rune/vendor/accesskit_windows/src/subclass.rs b/app/vendor/rune/vendor/accesskit_windows/src/subclass.rs new file mode 100644 index 0000000..db2d2b6 --- /dev/null +++ b/app/vendor/rune/vendor/accesskit_windows/src/subclass.rs @@ -0,0 +1,204 @@ +// Copyright 2022 The AccessKit Authors. All rights reserved. +// Licensed under the Apache License, Version 2.0 (found in +// the LICENSE-APACHE file) or the MIT license (found in +// the LICENSE-MIT file), at your option. + +use accesskit::{ActionHandler, ActivationHandler, TreeUpdate}; +use std::{ + cell::{Cell, RefCell}, + ffi::c_void, + mem::transmute, +}; +use windows::{ + Win32::{Foundation::*, UI::WindowsAndMessaging::*}, + core::*, +}; + +use crate::{Adapter, QueuedEvents}; + +fn win32_error() -> ! { + panic!("{}", Error::from_thread()) +} + +// Work around a difference between the SetWindowLongPtrW API definition +// in windows-rs on 32-bit and 64-bit Windows. +#[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] +type LongPtr = isize; +#[cfg(not(any(target_arch = "x86_64", target_arch = "aarch64")))] +type LongPtr = i32; + +const PROP_NAME: PCWSTR = w!("AccessKitAdapter"); + +struct SubclassState { + adapter: Adapter, + activation_handler: Box<dyn ActivationHandler>, +} + +struct SubclassImpl { + hwnd: HWND, + state: RefCell<SubclassState>, + prev_wnd_proc: WNDPROC, + window_destroyed: Cell<bool>, +} + +extern "system" fn wnd_proc(window: HWND, message: u32, wparam: WPARAM, lparam: LPARAM) -> LRESULT { + let handle = unsafe { GetPropW(window, PROP_NAME) }; + let impl_ptr = handle.0 as *const SubclassImpl; + assert!(!impl_ptr.is_null()); + let r#impl = unsafe { &*impl_ptr }; + match message { + WM_GETOBJECT => { + let mut state = r#impl.state.borrow_mut(); + let state_mut = &mut *state; + if let Some(result) = state_mut.adapter.handle_wm_getobject( + wparam, + lparam, + &mut *state_mut.activation_handler, + ) { + drop(state); + return result.into(); + } + } + WM_SETFOCUS | WM_EXITMENULOOP | WM_EXITSIZEMOVE => { + r#impl.update_window_focus_state(true); + } + WM_KILLFOCUS | WM_ENTERMENULOOP | WM_ENTERSIZEMOVE => { + r#impl.update_window_focus_state(false); + } + WM_NCDESTROY => { + r#impl.window_destroyed.set(true); + } + _ => (), + } + unsafe { CallWindowProcW(r#impl.prev_wnd_proc, window, message, wparam, lparam) } +} + +impl SubclassImpl { + fn new( + hwnd: HWND, + activation_handler: impl 'static + ActivationHandler, + action_handler: impl 'static + ActionHandler + Send, + ) -> Box<Self> { + let adapter = Adapter::new(hwnd, false, action_handler); + let state = RefCell::new(SubclassState { + adapter, + activation_handler: Box::new(activation_handler), + }); + Box::new(Self { + hwnd, + state, + prev_wnd_proc: None, + window_destroyed: Cell::new(false), + }) + } + + fn install(&mut self) { + if !unsafe { GetPropW(self.hwnd, PROP_NAME) }.0.is_null() { + panic!( + "subclassing adapter already instantiated on window {:?}", + self.hwnd.0 + ); + } + unsafe { + SetPropW( + self.hwnd, + PROP_NAME, + Some(HANDLE(self as *const SubclassImpl as _)), + ) + } + .unwrap(); + let result = + unsafe { SetWindowLongPtrW(self.hwnd, GWLP_WNDPROC, wnd_proc as *const c_void as _) }; + if result == 0 { + win32_error(); + } + self.prev_wnd_proc = unsafe { transmute::<LongPtr, WNDPROC>(result) }; + } + + fn update_window_focus_state(&self, is_focused: bool) { + let mut state = self.state.borrow_mut(); + if let Some(events) = state.adapter.update_window_focus_state(is_focused) { + drop(state); + events.raise(); + } + } + + fn uninstall(&self) { + if self.window_destroyed.get() { + return; + } + let result = unsafe { + SetWindowLongPtrW( + self.hwnd, + GWLP_WNDPROC, + transmute::<WNDPROC, LongPtr>(self.prev_wnd_proc), + ) + }; + if result == 0 { + win32_error(); + } + unsafe { RemovePropW(self.hwnd, PROP_NAME) }.unwrap(); + } +} + +/// Uses [Win32 subclassing] to handle `WM_GETOBJECT` messages on a window +/// that provides no other way of adding custom message handlers. +/// +/// [Win32 subclassing]: https://docs.microsoft.com/en-us/windows/win32/controls/subclassing-overview +pub struct SubclassingAdapter(Box<SubclassImpl>); + +impl SubclassingAdapter { + /// Creates a new Windows platform adapter using window subclassing. + /// This must be done before the window is shown or focused + /// for the first time. + /// + /// This must be called on the thread that owns the window. The activation + /// handler will always be called on that thread. The action handler + /// may or may not be called on that thread. + /// + /// # Panics + /// + /// Panics if the window is already visible. + pub fn new( + hwnd: HWND, + activation_handler: impl 'static + ActivationHandler, + action_handler: impl 'static + ActionHandler + Send, + ) -> Self { + if unsafe { IsWindowVisible(hwnd) }.into() { + panic!( + "The AccessKit Windows subclassing adapter must be created before the window is shown (made visible) for the first time." + ); + } + + let mut r#impl = SubclassImpl::new(hwnd, activation_handler, action_handler); + r#impl.install(); + Self(r#impl) + } + + /// If and only if the tree has been initialized, call the provided function + /// and apply the resulting update. Note: If the caller's implementation of + /// [`ActivationHandler::request_initial_tree`] initially returned `None`, + /// the [`TreeUpdate`] returned by the provided function must contain + /// a full tree. + /// + /// If a [`QueuedEvents`] instance is returned, the caller must call + /// [`QueuedEvents::raise`] on it. + pub fn update_if_active( + &mut self, + update_factory: impl FnOnce() -> TreeUpdate, + ) -> Option<QueuedEvents> { + // SAFETY: We use `RefCell::borrow_mut` here, even though + // `RefCell::get_mut` is allowed (because this method takes + // a mutable self reference), just in case there's some way + // this method can be called from within the subclassed window + // procedure, e.g. via `ActivationHandler`. + let mut state = self.0.state.borrow_mut(); + state.adapter.update_if_active(update_factory) + } +} + +impl Drop for SubclassingAdapter { + fn drop(&mut self) { + self.0.uninstall(); + } +} diff --git a/app/vendor/rune/vendor/accesskit_windows/src/tests/mod.rs b/app/vendor/rune/vendor/accesskit_windows/src/tests/mod.rs new file mode 100644 index 0000000..ff939e4 --- /dev/null +++ b/app/vendor/rune/vendor/accesskit_windows/src/tests/mod.rs @@ -0,0 +1,337 @@ +// Copyright 2022 The AccessKit Authors. All rights reserved. +// Licensed under the Apache License, Version 2.0 (found in +// the LICENSE-APACHE file) or the MIT license (found in +// the LICENSE-MIT file), at your option. + +use accesskit::{ActionHandler, ActivationHandler}; +use std::{ + cell::RefCell, + sync::{Arc, Condvar, LazyLock, Mutex}, + thread, + time::Duration, +}; +use windows as Windows; +use windows::{ + Win32::{ + Foundation::*, + Graphics::Gdi::ValidateRect, + System::{Com::*, LibraryLoader::GetModuleHandleW}, + UI::{Accessibility::*, WindowsAndMessaging::*}, + }, + core::*, +}; + +use crate::window_handle::WindowHandle; + +use super::{ + Adapter, + context::{ActionHandlerNoMut, ActionHandlerWrapper}, +}; + +const DEFAULT_TIMEOUT: Duration = Duration::from_secs(5); + +static WINDOW_CLASS_ATOM: LazyLock<u16> = LazyLock::new(|| { + let class_name = w!("AccessKitTest"); + + let wc = WNDCLASSW { + hCursor: unsafe { LoadCursorW(None, IDC_ARROW) }.unwrap(), + hInstance: unsafe { GetModuleHandleW(None) }.unwrap().into(), + lpszClassName: class_name, + style: CS_HREDRAW | CS_VREDRAW, + lpfnWndProc: Some(wndproc), + ..Default::default() + }; + + let atom = unsafe { RegisterClassW(&wc) }; + if atom == 0 { + panic!("{}", Error::from_thread()); + } + atom +}); + +struct WindowState { + activation_handler: RefCell<Box<dyn ActivationHandler>>, + adapter: RefCell<Adapter>, +} + +unsafe fn get_window_state(window: HWND) -> *const WindowState { + unsafe { GetWindowLongPtrW(window, GWLP_USERDATA) as _ } +} + +fn update_window_focus_state(window: HWND, is_focused: bool) { + let state = unsafe { &*get_window_state(window) }; + let mut adapter = state.adapter.borrow_mut(); + if let Some(events) = adapter.update_window_focus_state(is_focused) { + drop(adapter); + events.raise(); + } +} + +struct WindowCreateParams { + activation_handler: Box<dyn ActivationHandler>, + action_handler: Arc<dyn ActionHandlerNoMut + Send + Sync>, +} + +extern "system" fn wndproc(window: HWND, message: u32, wparam: WPARAM, lparam: LPARAM) -> LRESULT { + match message { + WM_NCCREATE => { + let create_struct: &CREATESTRUCTW = unsafe { &mut *(lparam.0 as *mut _) }; + let create_params: Box<WindowCreateParams> = + unsafe { Box::from_raw(create_struct.lpCreateParams as _) }; + let WindowCreateParams { + activation_handler, + action_handler, + } = *create_params; + let adapter = Adapter::with_wrapped_action_handler(window, false, action_handler); + let state = Box::new(WindowState { + activation_handler: RefCell::new(activation_handler), + adapter: RefCell::new(adapter), + }); + unsafe { SetWindowLongPtrW(window, GWLP_USERDATA, Box::into_raw(state) as _) }; + unsafe { DefWindowProcW(window, message, wparam, lparam) } + } + WM_PAINT => { + unsafe { ValidateRect(Some(window), None) }.unwrap(); + LRESULT(0) + } + WM_DESTROY => { + let ptr = unsafe { SetWindowLongPtrW(window, GWLP_USERDATA, 0) }; + if ptr != 0 { + drop(unsafe { Box::<WindowState>::from_raw(ptr as _) }); + } + unsafe { PostQuitMessage(0) }; + LRESULT(0) + } + WM_GETOBJECT => { + let state_ptr = unsafe { get_window_state(window) }; + if state_ptr.is_null() { + // We need to be prepared to gracefully handle WM_GETOBJECT + // while the window is being destroyed; this can happen if + // the thread is using a COM STA. + return unsafe { DefWindowProcW(window, message, wparam, lparam) }; + } + let state = unsafe { &*state_ptr }; + let mut adapter = state.adapter.borrow_mut(); + let mut activation_handler = state.activation_handler.borrow_mut(); + let result = adapter.handle_wm_getobject(wparam, lparam, &mut **activation_handler); + drop(activation_handler); + drop(adapter); + result.map_or_else( + || unsafe { DefWindowProcW(window, message, wparam, lparam) }, + |result| result.into(), + ) + } + WM_SETFOCUS | WM_EXITMENULOOP | WM_EXITSIZEMOVE => { + update_window_focus_state(window, true); + LRESULT(0) + } + WM_KILLFOCUS | WM_ENTERMENULOOP | WM_ENTERSIZEMOVE => { + update_window_focus_state(window, false); + LRESULT(0) + } + _ => unsafe { DefWindowProcW(window, message, wparam, lparam) }, + } +} + +fn create_window( + title: &str, + activation_handler: impl 'static + ActivationHandler, + action_handler: impl 'static + ActionHandler + Send, +) -> Result<HWND> { + let create_params = Box::new(WindowCreateParams { + activation_handler: Box::new(activation_handler), + action_handler: Arc::new(ActionHandlerWrapper::new(action_handler)), + }); + let module = HINSTANCE::from(unsafe { GetModuleHandleW(None)? }); + + let window = unsafe { + CreateWindowExW( + Default::default(), + PCWSTR(*WINDOW_CLASS_ATOM as usize as _), + &HSTRING::from(title), + WS_OVERLAPPEDWINDOW, + CW_USEDEFAULT, + CW_USEDEFAULT, + CW_USEDEFAULT, + CW_USEDEFAULT, + None, + None, + Some(module), + Some(Box::into_raw(create_params) as _), + )? + }; + if window.is_invalid() { + return Err(Error::from_thread()); + } + + Ok(window) +} + +pub(crate) struct Scope { + pub(crate) uia: IUIAutomation, + pub(crate) window: WindowHandle, +} + +impl Scope { + pub(crate) fn show_and_focus_window(&self) { + let _ = unsafe { ShowWindow(self.window.0, SW_SHOW) }; + let _ = unsafe { SetForegroundWindow(self.window.0) }; + } +} + +// It's not safe to run these UI-related tests concurrently. +// We need a non-poisoning mutex here because the subclassing adapter's +// double-instantiation test intentionally panics. +pub(crate) static MUTEX: parking_lot::Mutex<()> = parking_lot::const_mutex(()); + +pub(crate) fn scope<F>( + window_title: &str, + activation_handler: impl 'static + ActivationHandler + Send, + action_handler: impl 'static + ActionHandler + Send, + f: F, +) -> Result<()> +where + F: FnOnce(&Scope) -> Result<()>, +{ + let _lock_guard = MUTEX.lock(); + + let window_mutex: Mutex<Option<WindowHandle>> = Mutex::new(None); + let window_cv = Condvar::new(); + + thread::scope(|thread_scope| { + thread_scope.spawn(|| { + // We explicitly don't want to initialize COM on the provider thread, + // because we want to make sure that the provider side of UIA works + // even if COM is never initialized on the provider thread + // (as is the case if the window is never shown), or if COM is + // initialized after the window is shown (as is the case, + // at least on some Windows 10 machines, due to IME support). + + let window = create_window(window_title, activation_handler, action_handler).unwrap(); + + { + let mut state = window_mutex.lock().unwrap(); + *state = Some(window.into()); + window_cv.notify_one(); + } + + let mut message = MSG::default(); + while unsafe { GetMessageW(&mut message, None, 0, 0) }.into() { + let _ = unsafe { TranslateMessage(&message) }; + unsafe { DispatchMessageW(&message) }; + } + }); + + let window = { + let mut state = window_mutex.lock().unwrap(); + while state.is_none() { + state = window_cv.wait(state).unwrap(); + } + state.take().unwrap() + }; + + let _window_guard = scopeguard::guard((), |_| { + unsafe { PostMessageW(Some(window.0), WM_CLOSE, WPARAM(0), LPARAM(0)) }.unwrap() + }); + + // We must initialize COM before creating the UIA client. The MTA option + // is cleaner by far, especially when we want to wait for a UIA event + // handler to be called, and there's no reason not to use it here. + // Note that we don't initialize COM this way on the provider thread, + // as explained above. It's also important that we let the provider + // thread do its forced initialization of UIA, in an environment + // where COM has not been initialized, before we create the UIA client, + // which also triggers UIA initialization, in a thread where COM + // _has_ been initialized. This way, we ensure that the provider side + // of UIA works even if it is set up in an environment where COM + // has not been initialized, and that this sequence of events + // doesn't prevent the UIA client from working. + unsafe { CoInitializeEx(None, COINIT_MULTITHREADED) }.unwrap(); + let _com_guard = scopeguard::guard((), |_| unsafe { CoUninitialize() }); + + let uia: IUIAutomation = + unsafe { CoCreateInstance(&CUIAutomation8, None, CLSCTX_INPROC_SERVER) }?; + + let s = Scope { uia, window }; + f(&s) + }) +} + +/// This must only be used to wrap UIA elements returned by a UIA client +/// that was created in the MTA. Those are safe to send between threads. +struct SendableUiaElement(IUIAutomationElement); +unsafe impl Send for SendableUiaElement {} + +pub(crate) struct ReceivedFocusEvent { + mutex: Mutex<Option<SendableUiaElement>>, + cv: Condvar, +} + +impl ReceivedFocusEvent { + fn new() -> Arc<Self> { + Arc::new(Self { + mutex: Mutex::new(None), + cv: Condvar::new(), + }) + } + + pub(crate) fn wait<F>(&self, f: F) -> IUIAutomationElement + where + F: Fn(&IUIAutomationElement) -> bool, + { + let mut received = self.mutex.lock().unwrap(); + loop { + if let Some(SendableUiaElement(element)) = received.take() { + if f(&element) { + return element; + } + } + let (lock, result) = self.cv.wait_timeout(received, DEFAULT_TIMEOUT).unwrap(); + assert!(!result.timed_out()); + received = lock; + } + } + + fn put(&self, element: IUIAutomationElement) { + let mut received = self.mutex.lock().unwrap(); + *received = Some(SendableUiaElement(element)); + self.cv.notify_one(); + } +} + +#[implement(Windows::Win32::UI::Accessibility::IUIAutomationFocusChangedEventHandler)] +pub(crate) struct FocusEventHandler { + received: Arc<ReceivedFocusEvent>, +} +// Because we create a UIA client in the COM MTA, this event handler +// _will_ be called from a different thread, and possibly multiple threads +// at once. +static_assertions::assert_impl_all!(FocusEventHandler: Send, Sync); + +impl FocusEventHandler { + #[allow(clippy::new_ret_no_self)] // it does return self, but wrapped + pub(crate) fn new() -> ( + IUIAutomationFocusChangedEventHandler, + Arc<ReceivedFocusEvent>, + ) { + let received = ReceivedFocusEvent::new(); + ( + Self { + received: Arc::clone(&received), + } + .into(), + received, + ) + } +} + +#[allow(non_snake_case)] +impl IUIAutomationFocusChangedEventHandler_Impl for FocusEventHandler_Impl { + fn HandleFocusChangedEvent(&self, sender: Ref<IUIAutomationElement>) -> Result<()> { + self.received.put(sender.unwrap().clone()); + Ok(()) + } +} + +mod simple; +mod subclassed; diff --git a/app/vendor/rune/vendor/accesskit_windows/src/tests/simple.rs b/app/vendor/rune/vendor/accesskit_windows/src/tests/simple.rs new file mode 100644 index 0000000..f72f0b3 --- /dev/null +++ b/app/vendor/rune/vendor/accesskit_windows/src/tests/simple.rs @@ -0,0 +1,198 @@ +// Copyright 2022 The AccessKit Authors. All rights reserved. +// Licensed under the Apache License, Version 2.0 (found in +// the LICENSE-APACHE file) or the MIT license (found in +// the LICENSE-MIT file), at your option. + +use accesskit::{ + Action, ActionHandler, ActionRequest, ActivationHandler, Node, NodeId, Role, TreeId, TreeInfo, + TreeUpdate, +}; +use windows::{Win32::UI::Accessibility::*, core::*}; + +use super::{FocusEventHandler, Scope}; + +const WINDOW_TITLE: &str = "Simple test"; + +const WINDOW_ID: NodeId = NodeId(0); +const BUTTON_1_ID: NodeId = NodeId(1); +const BUTTON_2_ID: NodeId = NodeId(2); + +fn make_button(label: &str) -> Node { + let mut node = Node::new(Role::Button); + node.set_label(label); + node.add_action(Action::Focus); + node +} + +fn get_initial_state() -> TreeUpdate { + let mut root = Node::new(Role::Window); + root.set_children(vec![BUTTON_1_ID, BUTTON_2_ID]); + let button_1 = make_button("Button 1"); + let button_2 = make_button("Button 2"); + TreeUpdate { + nodes: vec![ + (WINDOW_ID, root), + (BUTTON_1_ID, button_1), + (BUTTON_2_ID, button_2), + ], + tree: Some(TreeInfo::new(WINDOW_ID)), + tree_id: TreeId::ROOT, + focus: BUTTON_1_ID, + } +} + +pub struct NullActionHandler; + +impl ActionHandler for NullActionHandler { + fn do_action(&mut self, _request: ActionRequest) {} +} + +struct SimpleActivationHandler; + +impl ActivationHandler for SimpleActivationHandler { + fn request_initial_tree(&mut self) -> Option<TreeUpdate> { + Some(get_initial_state()) + } +} + +fn scope<F>(f: F) -> Result<()> +where + F: FnOnce(&Scope) -> Result<()>, +{ + super::scope( + WINDOW_TITLE, + SimpleActivationHandler {}, + NullActionHandler {}, + f, + ) +} + +#[test] +fn has_native_uia() -> Result<()> { + scope(|s| { + let has_native_uia: bool = unsafe { UiaHasServerSideProvider(s.window.0) }.into(); + assert!(has_native_uia); + Ok(()) + }) +} + +fn is_button_named(element: &IUIAutomationElement, expected_name: &str) -> bool { + let control_type = unsafe { element.CurrentControlType() }.unwrap(); + let name = unsafe { element.CurrentName() }.unwrap(); + let name: String = name.try_into().unwrap(); + control_type == UIA_ButtonControlTypeId && name == expected_name +} + +fn is_button_1(element: &IUIAutomationElement) -> bool { + is_button_named(element, "Button 1") +} + +fn is_button_2(element: &IUIAutomationElement) -> bool { + is_button_named(element, "Button 2") +} + +#[test] +fn navigation() -> Result<()> { + scope(|s| { + let root = unsafe { s.uia.ElementFromHandle(s.window.0) }?; + let walker = unsafe { s.uia.ControlViewWalker() }?; + + // The children of the window include the children that we provide, + // but also the title bar provided by the OS. We know that our own + // children are in the order we specified, but we don't know + // their position relative to the title bar. In fact, Windows + // has changed this in the past. + // + // Note that a UIA client would normally use the UIA condition feature + // to traverse the tree looking for an element that meets + // some condition. But we want to be explicit about navigating + // forward (and backward below) through only the immediate children. + // We'll accept the performance hit of multiple cross-thread calls + // (insignificant in this case) to achieve that. + let mut button_1_forward: Option<IUIAutomationElement> = None; + let mut wrapped_child = unsafe { walker.GetFirstChildElement(&root) }; + while let Ok(child) = wrapped_child { + if is_button_1(&child) { + button_1_forward = Some(child); + break; + } + wrapped_child = unsafe { walker.GetNextSiblingElement(&child) }; + } + let button_1_forward = button_1_forward.unwrap(); + + let mut button_2_forward: Option<IUIAutomationElement> = None; + let wrapped_child = unsafe { walker.GetNextSiblingElement(&button_1_forward) }; + if let Ok(child) = wrapped_child { + if is_button_2(&child) { + button_2_forward = Some(child); + } + } + let _button_2_forward = button_2_forward.unwrap(); + + let mut button_2_backward: Option<IUIAutomationElement> = None; + let mut wrapped_child = unsafe { walker.GetLastChildElement(&root) }; + while let Ok(child) = wrapped_child { + if is_button_2(&child) { + button_2_backward = Some(child); + break; + } + wrapped_child = unsafe { walker.GetPreviousSiblingElement(&child) }; + } + let button_2_backward = button_2_backward.unwrap(); + + let mut button_1_backward: Option<IUIAutomationElement> = None; + let wrapped_child = unsafe { walker.GetPreviousSiblingElement(&button_2_backward) }; + if let Ok(child) = wrapped_child { + if is_button_1(&child) { + button_1_backward = Some(child); + } + } + let button_1_backward = button_1_backward.unwrap(); + + let equal: bool = + unsafe { s.uia.CompareElements(&button_1_forward, &button_1_backward) }?.into(); + assert!(equal); + + let parent = unsafe { walker.GetParentElement(&button_1_forward) }?; + let equal: bool = unsafe { s.uia.CompareElements(&parent, &root) }?.into(); + assert!(equal); + + let desktop_root = unsafe { s.uia.GetRootElement() }?; + let parent = unsafe { walker.GetParentElement(&root) }?; + let equal: bool = unsafe { s.uia.CompareElements(&parent, &desktop_root) }?.into(); + assert!(equal); + + let wrapped_child = unsafe { walker.GetFirstChildElement(&button_1_forward) }; + assert_eq!(Err(Error::empty()), wrapped_child); + + let wrapped_child = unsafe { walker.GetLastChildElement(&button_1_forward) }; + assert_eq!(Err(Error::empty()), wrapped_child); + + Ok(()) + }) +} + +#[test] +fn focus() -> Result<()> { + scope(|s| { + let (focus_event_handler, received_focus_event) = FocusEventHandler::new(); + unsafe { + s.uia + .AddFocusChangedEventHandler(None, &focus_event_handler) + }?; + + s.show_and_focus_window(); + let focus_from_event = received_focus_event.wait(is_button_1); + let has_focus: bool = unsafe { focus_from_event.CurrentHasKeyboardFocus() }?.into(); + assert!(has_focus); + let is_focusable: bool = unsafe { focus_from_event.CurrentIsKeyboardFocusable() }?.into(); + assert!(is_focusable); + + let focus_on_demand = unsafe { s.uia.GetFocusedElement() }?; + let equal: bool = + unsafe { s.uia.CompareElements(&focus_from_event, &focus_on_demand) }?.into(); + assert!(equal); + + Ok(()) + }) +} diff --git a/app/vendor/rune/vendor/accesskit_windows/src/tests/subclassed.rs b/app/vendor/rune/vendor/accesskit_windows/src/tests/subclassed.rs new file mode 100644 index 0000000..ed485ee --- /dev/null +++ b/app/vendor/rune/vendor/accesskit_windows/src/tests/subclassed.rs @@ -0,0 +1,177 @@ +// Copyright 2022 The AccessKit Authors. All rights reserved. +// Licensed under the Apache License, Version 2.0 (found in +// the LICENSE-APACHE file) or the MIT license (found in +// the LICENSE-MIT file), at your option. + +use accesskit::{ + Action, ActionHandler, ActionRequest, ActivationHandler, Node, NodeId, Role, TreeId, TreeInfo, + TreeUpdate, +}; +use std::sync::LazyLock; +use windows::{ + Win32::{ + Foundation::*, + System::LibraryLoader::GetModuleHandleW, + UI::{Accessibility::*, WindowsAndMessaging::*}, + }, + core::*, +}; +use winit::{ + application::ApplicationHandler, + event::WindowEvent, + event_loop::{ActiveEventLoop, EventLoop}, + platform::windows::EventLoopBuilderExtWindows, + raw_window_handle::{HasWindowHandle, RawWindowHandle}, + window::{Window, WindowId}, +}; + +use super::MUTEX; +use crate::SubclassingAdapter; + +const WINDOW_TITLE: &str = "Simple test"; + +const WINDOW_ID: NodeId = NodeId(0); +const BUTTON_1_ID: NodeId = NodeId(1); +const BUTTON_2_ID: NodeId = NodeId(2); + +fn make_button(label: &str) -> Node { + let mut node = Node::new(Role::Button); + node.set_label(label); + node.add_action(Action::Focus); + node +} + +fn get_initial_state() -> TreeUpdate { + let mut root = Node::new(Role::Window); + root.set_children(vec![BUTTON_1_ID, BUTTON_2_ID]); + let button_1 = make_button("Button 1"); + let button_2 = make_button("Button 2"); + TreeUpdate { + nodes: vec![ + (WINDOW_ID, root), + (BUTTON_1_ID, button_1), + (BUTTON_2_ID, button_2), + ], + tree: Some(TreeInfo::new(WINDOW_ID)), + tree_id: TreeId::ROOT, + focus: BUTTON_1_ID, + } +} + +pub struct NullActionHandler; + +impl ActionHandler for NullActionHandler { + fn do_action(&mut self, _request: ActionRequest) {} +} + +struct SimpleActivationHandler; + +impl ActivationHandler for SimpleActivationHandler { + fn request_initial_tree(&mut self) -> Option<TreeUpdate> { + Some(get_initial_state()) + } +} + +// This module uses winit for the purpose of testing with a real third-party +// window implementation that we don't control. However, only one test +// can use winit, because winit only allows an event loop to be created +// once per process. So we end up creating our own window anyway for the +// double-instantiation test. +// +// Also, while these tests don't use the main test harness or show the window, +// they still need to run with the main harness's mutex, to avoid disturbing +// other tests, particularly the focus test. + +struct TestApplication; + +impl ApplicationHandler<()> for TestApplication { + fn window_event(&mut self, _: &ActiveEventLoop, _: WindowId, _: WindowEvent) {} + + fn resumed(&mut self, event_loop: &ActiveEventLoop) { + let window_attributes = Window::default_attributes() + .with_title(WINDOW_TITLE) + .with_visible(false); + + let window = event_loop.create_window(window_attributes).unwrap(); + let hwnd = match window.window_handle().unwrap().as_raw() { + RawWindowHandle::Win32(handle) => HWND(handle.hwnd.get() as *mut core::ffi::c_void), + RawWindowHandle::WinRt(_) => unimplemented!(), + _ => unreachable!(), + }; + let adapter = + SubclassingAdapter::new(hwnd, SimpleActivationHandler {}, NullActionHandler {}); + assert!(unsafe { UiaHasServerSideProvider(hwnd) }.as_bool()); + drop(window); + drop(adapter); + event_loop.exit(); + } +} + +#[test] +fn has_native_uia() { + let _lock_guard = MUTEX.lock(); + let event_loop = EventLoop::builder().with_any_thread(true).build().unwrap(); + let mut state = TestApplication {}; + event_loop.run_app(&mut state).unwrap(); +} + +extern "system" fn wndproc(window: HWND, message: u32, wparam: WPARAM, lparam: LPARAM) -> LRESULT { + unsafe { DefWindowProcW(window, message, wparam, lparam) } +} + +static WINDOW_CLASS_ATOM: LazyLock<u16> = LazyLock::new(|| { + let class_name = w!("AccessKitSubclassTest"); + + let wc = WNDCLASSW { + hCursor: unsafe { LoadCursorW(None, IDC_ARROW) }.unwrap(), + hInstance: unsafe { GetModuleHandleW(None) }.unwrap().into(), + lpszClassName: class_name, + style: CS_HREDRAW | CS_VREDRAW, + lpfnWndProc: Some(wndproc), + ..Default::default() + }; + + let atom = unsafe { RegisterClassW(&wc) }; + if atom == 0 { + panic!("{}", Error::from_thread()); + } + atom +}); + +fn create_window(title: &str) -> HWND { + let module = HINSTANCE::from(unsafe { GetModuleHandleW(None).unwrap() }); + + let window = unsafe { + CreateWindowExW( + Default::default(), + PCWSTR(*WINDOW_CLASS_ATOM as usize as _), + &HSTRING::from(title), + WS_OVERLAPPEDWINDOW, + CW_USEDEFAULT, + CW_USEDEFAULT, + CW_USEDEFAULT, + CW_USEDEFAULT, + None, + None, + Some(module), + None, + ) + } + .unwrap(); + if window.is_invalid() { + panic!("{}", Error::from_thread()); + } + + window +} + +#[test] +#[should_panic(expected = "already instantiated")] +fn double_instantiate() { + let _lock_guard = MUTEX.lock(); + let window = create_window(WINDOW_TITLE); + let _adapter1 = + SubclassingAdapter::new(window, SimpleActivationHandler {}, NullActionHandler {}); + let _adapter2 = + SubclassingAdapter::new(window, SimpleActivationHandler {}, NullActionHandler {}); +} diff --git a/app/vendor/rune/vendor/accesskit_windows/src/text.rs b/app/vendor/rune/vendor/accesskit_windows/src/text.rs new file mode 100644 index 0000000..c7dfc79 --- /dev/null +++ b/app/vendor/rune/vendor/accesskit_windows/src/text.rs @@ -0,0 +1,937 @@ +// Copyright 2022 The AccessKit Authors. All rights reserved. +// Licensed under the Apache License, Version 2.0 (found in +// the LICENSE-APACHE file) or the MIT license (found in +// the LICENSE-MIT file), at your option. + +#![allow(non_upper_case_globals)] + +use accesskit::{ + Action, ActionData, ActionRequest, ScrollHint, TextPosition as WeakPosition, TextSelection, + VerticalOffset, +}; +use accesskit_consumer::{ + FullNodeId, NodeRef, TextPosition as Position, TextRange as Range, Tree, TreeState, + WeakTextRange as WeakRange, +}; +use std::sync::{Arc, RwLock, Weak}; +use windows::{ + Win32::{ + System::{Com::*, Variant::*}, + UI::Accessibility::*, + }, + core::*, +}; + +use crate::{ + context::Context, + long_text::{Text, Unit, bounding_boxes, drawn_lines, drawn_state, long_text}, + util::*, +}; + +/// A range in published text runs, or (Rune) in a long field's value ([`long_text`]). +#[derive(Clone, PartialEq)] +enum State { + Runs(WeakRange), + Long { + node: FullNodeId, + start: usize, + end: usize, + }, +} + +fn runs(state: &State) -> Result<&WeakRange> { + match state { + State::Runs(range) => Ok(range), + State::Long { .. } => Err(invalid_arg()), + } +} + +/// Moves one end of a long field's range, taking the other along if they'd cross. +fn set_long_endpoint(start: &mut usize, end: &mut usize, endpoint: TextPatternRangeEndpoint, at: usize) { + if endpoint == TextPatternRangeEndpoint_Start { + *start = at; + *end = (*end).max(at); + } else { + *end = at; + *start = (*start).min(at); + } +} + +fn long_unit(unit: TextUnit) -> Result<Unit> { + match unit { + TextUnit_Character => Ok(Unit::Character), + TextUnit_Word => Ok(Unit::Word), + TextUnit_Line => Ok(Unit::Line), + TextUnit_Paragraph => Ok(Unit::Paragraph), + TextUnit_Format | TextUnit_Page | TextUnit_Document => Ok(Unit::Document), + _ => Err(invalid_arg()), + } +} + +fn upgrade_range<'a>(weak: &WeakRange, tree_state: &'a TreeState) -> Result<Range<'a>> { + if let Some(range) = weak.upgrade(tree_state) { + Ok(range) + } else { + Err(element_not_available()) + } +} + +fn upgrade_range_node<'a>(weak: &WeakRange, tree_state: &'a TreeState) -> Result<NodeRef<'a>> { + if let Some(node) = weak.upgrade_node(tree_state) { + Ok(node) + } else { + Err(element_not_available()) + } +} + +fn weak_comparable_position_from_endpoint( + range: &WeakRange, + endpoint: TextPatternRangeEndpoint, +) -> Result<&(Vec<usize>, usize)> { + match endpoint { + TextPatternRangeEndpoint_Start => Ok(range.start_comparable()), + TextPatternRangeEndpoint_End => Ok(range.end_comparable()), + _ => Err(invalid_arg()), + } +} + +fn position_from_endpoint<'a>( + range: &Range<'a>, + endpoint: TextPatternRangeEndpoint, +) -> Result<Position<'a>> { + match endpoint { + TextPatternRangeEndpoint_Start => Ok(range.start()), + TextPatternRangeEndpoint_End => Ok(range.end()), + _ => Err(invalid_arg()), + } +} + +fn set_endpoint_position<'a>( + range: &mut Range<'a>, + endpoint: TextPatternRangeEndpoint, + pos: Position<'a>, +) -> Result<()> { + match endpoint { + TextPatternRangeEndpoint_Start => { + range.set_start(pos); + } + TextPatternRangeEndpoint_End => { + range.set_end(pos); + } + _ => { + return Err(invalid_arg()); + } + } + Ok(()) +} + +fn back_to_unit_start(start: Position, unit: TextUnit) -> Result<Position> { + match unit { + TextUnit_Character => { + // If we get here, this position is at the start of a non-degenerate + // range, so it's always at the start of a character. + debug_assert!(!start.is_document_end()); + Ok(start) + } + TextUnit_Format => { + if start.is_format_start() { + Ok(start) + } else { + Ok(start.backward_to_format_start()) + } + } + TextUnit_Word => { + if start.is_word_start() { + Ok(start) + } else { + Ok(start.backward_to_word_start()) + } + } + TextUnit_Line => { + if start.is_line_start() { + Ok(start) + } else { + Ok(start.backward_to_line_start()) + } + } + TextUnit_Paragraph => { + if start.is_paragraph_start() { + Ok(start) + } else { + Ok(start.backward_to_paragraph_start()) + } + } + TextUnit_Page => { + if start.is_page_start() { + Ok(start) + } else { + Ok(start.backward_to_page_start()) + } + } + TextUnit_Document => { + if start.is_document_start() { + Ok(start) + } else { + Ok(start.document_start()) + } + } + _ => Err(invalid_arg()), + } +} + +fn move_forward_to_start(pos: Position, unit: TextUnit) -> Result<Position> { + match unit { + TextUnit_Character => Ok(pos.forward_to_character_start()), + TextUnit_Format => Ok(pos.forward_to_format_start()), + TextUnit_Word => Ok(pos.forward_to_word_start()), + TextUnit_Line => Ok(pos.forward_to_line_start()), + TextUnit_Paragraph => Ok(pos.forward_to_paragraph_start()), + TextUnit_Page => Ok(pos.forward_to_page_start()), + TextUnit_Document => Ok(pos.document_end()), + _ => Err(invalid_arg()), + } +} + +fn move_forward_to_end(pos: Position, unit: TextUnit) -> Result<Position> { + match unit { + TextUnit_Character => Ok(pos.forward_to_character_end()), + TextUnit_Format => Ok(pos.forward_to_format_end()), + TextUnit_Word => Ok(pos.forward_to_word_end()), + TextUnit_Line => Ok(pos.forward_to_line_end()), + TextUnit_Paragraph => Ok(pos.forward_to_paragraph_end()), + TextUnit_Page => Ok(pos.forward_to_page_end()), + TextUnit_Document => Ok(pos.document_end()), + _ => Err(invalid_arg()), + } +} + +fn move_backward(pos: Position, unit: TextUnit) -> Result<Position> { + match unit { + TextUnit_Character => Ok(pos.backward_to_character_start()), + TextUnit_Format => Ok(pos.backward_to_format_start()), + TextUnit_Word => Ok(pos.backward_to_word_start()), + TextUnit_Line => Ok(pos.backward_to_line_start()), + TextUnit_Paragraph => Ok(pos.backward_to_paragraph_start()), + TextUnit_Page => Ok(pos.backward_to_page_start()), + TextUnit_Document => Ok(pos.document_start()), + _ => Err(invalid_arg()), + } +} + +fn move_position( + mut pos: Position, + unit: TextUnit, + to_end: bool, + count: i32, +) -> Result<(Position, i32)> { + let forward = count > 0; + let count = count.abs(); + let mut moved = 0i32; + for _ in 0..count { + let at_end = if forward { + pos.is_document_end() + } else { + pos.is_document_start() + }; + if at_end { + break; + } + pos = if forward { + if to_end { + move_forward_to_end(pos, unit) + } else { + move_forward_to_start(pos, unit) + } + } else { + move_backward(pos, unit) + }?; + moved += 1; + } + if !forward { + moved = -moved; + } + Ok((pos, moved)) +} + +#[implement(ITextRangeProvider)] +pub(crate) struct PlatformRange { + context: Weak<Context>, + state: RwLock<State>, +} + +impl PlatformRange { + pub(crate) fn new(context: &Weak<Context>, range: Range) -> Self { + Self { + context: context.clone(), + state: RwLock::new(State::Runs(range.downgrade())), + } + } + + /// Bytes `start..end` of long field `node`'s value. + pub(crate) fn new_long(context: &Weak<Context>, node: FullNodeId, start: usize, end: usize) -> Self { + Self { + context: context.clone(), + state: RwLock::new(State::Long { node, start, end }), + } + } + + fn read_state(&self) -> std::sync::RwLockReadGuard<'_, State> { + self.state.read().unwrap_or_else(|e| e.into_inner()) + } + + fn write_state(&self) -> std::sync::RwLockWriteGuard<'_, State> { + self.state.write().unwrap_or_else(|e| e.into_inner()) + } + + fn is_long(&self) -> bool { + matches!(*self.read_state(), State::Long { .. }) + } + + /// Runs `f` on this long field range's text, node and endpoints, which it may move. + /// Computes without holding `self.state`'s lock and catches any panic so neither a poisoned + /// lock nor an unwind can reach UIA's `extern "system"` ABI. + fn long<F, T>(&self, f: F) -> Result<T> + where + F: FnOnce(Text, NodeRef, &Arc<Context>, &mut usize, &mut usize) -> Result<T>, + { + uia_catch(|| { + let context = self.upgrade_context()?; + let tree = context.read_tree(); + let (node_id, mut start, mut end) = match *self.read_state() { + State::Long { node, start, end } => (node, start, end), + State::Runs(_) => return Err(invalid_arg()), + }; + let node = tree.state().node_by_id(node_id).ok_or_else(element_not_available)?; + let (text, _) = long_text(&node).ok_or_else(element_not_available)?; + // The value may have changed since the range was made. + start = text.clamp(start); + end = text.clamp(end).max(start); + let res = f(text, node, &context, &mut start, &mut end)?; + if let State::Long { start: s, end: e, .. } = &mut *self.write_state() { + *s = start; + *e = end; + } + Ok(res) + }) + } + + fn long_endpoints(&self) -> Option<(FullNodeId, usize, usize)> { + match *self.read_state() { + State::Long { node, start, end } => Some((node, start, end)), + State::Runs(_) => None, + } + } + + fn long_action(&self, action: Action, data: impl FnOnce(NodeRef, usize, usize) -> Option<ActionData>) -> Result<()> { + uia_catch(|| { + let context = self.upgrade_context()?; + let tree = context.read_tree(); + let (id, start, end) = self.long_endpoints().ok_or_else(invalid_arg)?; + let node = tree.state().node_by_id(id).ok_or_else(element_not_available)?; + let (target_node, target_tree) = node.locate(); + let data = data(node, start, end); + drop(tree); + context.do_action(ActionRequest { action, target_tree, target_node, data }); + Ok(()) + }) + } + + fn upgrade_context(&self) -> Result<Arc<Context>> { + upgrade(&self.context) + } + + fn with_tree_state_and_context<F, T>(&self, f: F) -> Result<T> + where + F: FnOnce(&TreeState, &Context) -> Result<T>, + { + uia_catch(|| { + let context = self.upgrade_context()?; + let tree = context.read_tree(); + f(tree.state(), &context) + }) + } + + fn with_tree_state<F, T>(&self, f: F) -> Result<T> + where + F: FnOnce(&TreeState) -> Result<T>, + { + self.with_tree_state_and_context(|state, _| f(state)) + } + + fn upgrade_node<'a>(&self, tree_state: &'a TreeState) -> Result<NodeRef<'a>> { + let state = self.read_state(); + upgrade_range_node(runs(&state)?, tree_state) + } + + fn upgrade_for_read<'a>(&self, tree_state: &'a TreeState) -> Result<Range<'a>> { + let state = self.read_state(); + upgrade_range(runs(&state)?, tree_state) + } + + fn read_with_context<F, T>(&self, f: F) -> Result<T> + where + F: FnOnce(Range, &Context) -> Result<T>, + { + self.with_tree_state_and_context(|tree_state, context| { + let range = self.upgrade_for_read(tree_state)?; + f(range, context) + }) + } + + fn read<F, T>(&self, f: F) -> Result<T> + where + F: FnOnce(Range) -> Result<T>, + { + self.read_with_context(|range, _| f(range)) + } + + fn write<F, T>(&self, f: F) -> Result<T> + where + F: FnOnce(&mut Range) -> Result<T>, + { + self.with_tree_state(|tree_state| { + let mut state = self.write_state(); + let mut range = upgrade_range(runs(&state)?, tree_state)?; + let result = f(&mut range); + *state = State::Runs(range.downgrade()); + result + }) + } + + fn do_action<F>(&self, f: F) -> Result<()> + where + for<'a> F: FnOnce(Range<'a>, &Tree) -> ActionRequest, + { + uia_catch(|| { + let context = self.upgrade_context()?; + let tree = context.read_tree(); + let range = self.upgrade_for_read(tree.state())?; + let request = f(range, &tree); + drop(tree); + context.do_action(request); + Ok(()) + }) + } + + fn require_same_context(&self, other: &PlatformRange) -> Result<()> { + if self.context.ptr_eq(&other.context) { + Ok(()) + } else { + Err(invalid_arg()) + } + } +} + +fn uia_catch<T>(f: impl FnOnce() -> Result<T>) -> Result<T> { + std::panic::catch_unwind(std::panic::AssertUnwindSafe(f)) + .unwrap_or_else(|_| Err(element_not_available())) +} + +impl Clone for PlatformRange { + fn clone(&self) -> Self { + PlatformRange { + context: self.context.clone(), + state: RwLock::new(self.read_state().clone()), + } + } +} + +// Some text range methods take another text range interface pointer as a +// parameter. We need to cast these interface pointers to their underlying +// implementations. We assume that AccessKit is the only UIA provider +// within this process. This seems a safe assumption for most AccessKit users. + +#[allow(non_snake_case)] +impl ITextRangeProvider_Impl for PlatformRange_Impl { + fn Clone(&self) -> Result<ITextRangeProvider> { + uia_catch(|| Ok(self.this.clone().into())) + } + + fn Compare(&self, other: Ref<ITextRangeProvider>) -> Result<BOOL> { + uia_catch(|| { + let other = unsafe { required_param(&other)?.as_impl() }; + Ok((self.context.ptr_eq(&other.context) + && *self.read_state() == *other.read_state()) + .into()) + }) + } + + fn CompareEndpoints( + &self, + endpoint: TextPatternRangeEndpoint, + other: Ref<ITextRangeProvider>, + other_endpoint: TextPatternRangeEndpoint, + ) -> Result<i32> { + uia_catch(|| { + let other = unsafe { required_param(&other)?.as_impl() }; + if self.is_long() || other.is_long() { + let (Some(mine), Some(theirs)) = (self.long_endpoints(), other.long_endpoints()) else { + return Err(invalid_arg()); + }; + let at = |e: TextPatternRangeEndpoint, (node, start, end): (FullNodeId, usize, usize)| match e { + _ if node != mine.0 => Err(invalid_arg()), + TextPatternRangeEndpoint_Start => Ok(start), + TextPatternRangeEndpoint_End => Ok(end), + _ => Err(invalid_arg()), + }; + return Ok(at(endpoint, mine)?.cmp(&at(other_endpoint, theirs)?) as i32); + } + if std::ptr::eq(other as *const _, &self.this as *const _) { + // Comparing endpoints within the same range can be done + // safely without upgrading the range. This allows ATs + // to determine whether an old range is degenerate even if + // that range is no longer valid. + let state = self.read_state(); + let other_state = other.read_state(); + let pos = weak_comparable_position_from_endpoint(runs(&state)?, endpoint)?; + let other_pos = weak_comparable_position_from_endpoint(runs(&other_state)?, other_endpoint)?; + let result = pos.cmp(other_pos); + return Ok(result as i32); + } + self.require_same_context(other)?; + self.with_tree_state(|tree_state| { + let range = self.upgrade_for_read(tree_state)?; + let other_range = other.upgrade_for_read(tree_state)?; + if range.node().id() != other_range.node().id() { + return Err(invalid_arg()); + } + let pos = position_from_endpoint(&range, endpoint)?; + let other_pos = position_from_endpoint(&other_range, other_endpoint)?; + let result = pos.partial_cmp(&other_pos).ok_or_else(invalid_arg)?; + Ok(result as i32) + }) + }) + } + + fn ExpandToEnclosingUnit(&self, unit: TextUnit) -> Result<()> { + if self.is_long() { + return self.long(|text, node, _, start, end| { + let unit = long_unit(unit)?; + if unit == Unit::Character && *start == text.len() { + return Ok(()); + } + if unit == Unit::Line { + let state = drawn_state(&node, text); + *start = text.start_of_in(*start, unit, &state); + *end = if *start == text.len() { *start } else { text.next_in(*start, unit, &state.lines) }; + } else { + *start = text.start_of(*start, unit); + *end = if *start == text.len() { *start } else { text.next(*start, unit) }; + } + Ok(()) + }); + } + if unit == TextUnit_Document { + // Handle document as a special case so we can get to a document + // range even if the current endpoints are now invalid. + // Based on observed behavior, Narrator needs this ability. + return self.with_tree_state(|tree_state| { + let mut state = self.write_state(); + let node = upgrade_range_node(runs(&state)?, tree_state)?; + *state = State::Runs(node.document_range().downgrade()); + Ok(()) + }); + } + self.write(|range| { + let start = range.start(); + if unit == TextUnit_Character && start.is_document_end() { + // We know from experimentation that some Windows ATs + // expect ExpandToEnclosingUnit(TextUnit_Character) + // to do nothing if the range is degenerate at the end + // of the document. + return Ok(()); + } + let start = back_to_unit_start(start, unit)?; + range.set_start(start); + if !start.is_document_end() { + let end = move_forward_to_end(start, unit)?; + range.set_end(end); + } + Ok(()) + }) + } + + fn FindAttribute( + &self, + _id: UIA_TEXTATTRIBUTE_ID, + _value: &VARIANT, + _backward: BOOL, + ) -> Result<ITextRangeProvider> { + // TODO: implement when we support variable formatting (part of rich text) + // Justification: JUCE doesn't implement this. + Err(Error::empty()) + } + + fn FindText( + &self, + _text: &BSTR, + _backward: BOOL, + _ignore_case: BOOL, + ) -> Result<ITextRangeProvider> { + // TODO: implement when there's a real-world use case that requires it + // Justification: Quorum doesn't implement this and is being used + // by blind students. + Err(Error::empty()) + } + + fn GetAttributeValue(&self, id: UIA_TEXTATTRIBUTE_ID) -> Result<VARIANT> { + if self.is_long() { + return self.long(|text, node, _, start, end| { + Ok(match id { + UIA_IsReadOnlyAttributeId => node.is_read_only().into(), + UIA_CaretPositionAttributeId => { + let at = *start; + let state = drawn_state(&node, text); + let at_hard_end = at == text.len() + || text.0.as_bytes().get(at) == Some(&b'\n') + || text.0.as_bytes().get(at..at + 2) == Some(b"\r\n"); + let value = if at != *end { + CaretPosition_Unknown + } else if text.is_start_in(at, Unit::Line, &state) { + CaretPosition_BeginningOfLine + } else if at_hard_end + || state.lines.iter().any(|d| d.end == at && d.start < at) + { + CaretPosition_EndOfLine + } else { + CaretPosition_Unknown + }; + value.0.into() + } + _ => unsafe { UiaGetReservedNotSupportedValue() }.unwrap().into(), + }) + }); + } + self.read(|range| match id { + UIA_IsReadOnlyAttributeId => { + // TBD: do we ever want to support mixed read-only/editable text? + let value = range.node().is_read_only(); + Ok(value.into()) + } + UIA_CaretPositionAttributeId => { + let mut value = CaretPosition_Unknown; + if range.is_degenerate() { + let pos = range.start(); + if pos.is_line_start() { + value = CaretPosition_BeginningOfLine; + } else if pos.is_line_end() { + value = CaretPosition_EndOfLine; + } + } + Ok(value.0.into()) + } + UIA_CultureAttributeId => Ok(Variant::from(range.language().map(LocaleName)).into()), + UIA_FontNameAttributeId => { + let mut buffer = StringBuffer::acquire(); + Ok( + Variant::from(range.font_family().map(|s| StrWrapper::new(s, &mut buffer))) + .into(), + ) + } + UIA_FontSizeAttributeId => { + Ok(Variant::from(range.font_size().map(|value| value as f64)).into()) + } + UIA_FontWeightAttributeId => { + Ok(Variant::from(range.font_weight().map(|value| value as i32)).into()) + } + UIA_IsItalicAttributeId => Ok(Variant::from(range.is_italic()).into()), + UIA_BackgroundColorAttributeId => Ok(Variant::from(range.background_color()).into()), + UIA_ForegroundColorAttributeId => Ok(Variant::from(range.foreground_color()).into()), + UIA_OverlineStyleAttributeId => { + Ok(Variant::from(range.overline().map(|d| d.style)).into()) + } + UIA_OverlineColorAttributeId => { + Ok(Variant::from(range.overline().map(|d| d.color)).into()) + } + UIA_StrikethroughStyleAttributeId => { + Ok(Variant::from(range.strikethrough().map(|d| d.style)).into()) + } + UIA_StrikethroughColorAttributeId => { + Ok(Variant::from(range.strikethrough().map(|d| d.color)).into()) + } + UIA_UnderlineStyleAttributeId => { + Ok(Variant::from(range.underline().map(|d| d.style)).into()) + } + UIA_UnderlineColorAttributeId => { + Ok(Variant::from(range.underline().map(|d| d.color)).into()) + } + UIA_HorizontalTextAlignmentAttributeId => Ok(Variant::from(range.text_align()).into()), + UIA_IsSubscriptAttributeId => Ok(Variant::from( + range + .vertical_offset() + .map(|o| o == VerticalOffset::Subscript), + ) + .into()), + UIA_IsSuperscriptAttributeId => Ok(Variant::from( + range + .vertical_offset() + .map(|o| o == VerticalOffset::Superscript), + ) + .into()), + // TODO: implement more attributes + _ => { + let value = unsafe { UiaGetReservedNotSupportedValue() }.unwrap(); + Ok(value.into()) + } + }) + } + + fn GetBoundingRectangles(&self) -> Result<*mut SAFEARRAY> { + if self.is_long() { + return self.long(|text, node, context, start, end| { + let rects = bounding_boxes(&node, text, *start, *end); + if rects.is_empty() { + return Ok(std::ptr::null_mut()); + } + let client_top_left = context.client_top_left(); + let mut result = Vec::<f64>::with_capacity(rects.len() * 4); + for rect in rects { + result.push(rect.x0 + client_top_left.x); + result.push(rect.y0 + client_top_left.y); + result.push(rect.width()); + result.push(rect.height()); + } + Ok(safe_array_from_f64_slice(&result)) + }); + } + self.read_with_context(|range, context| { + let rects = range.bounding_boxes(); + if rects.is_empty() { + return Ok(std::ptr::null_mut()); + } + let client_top_left = context.client_top_left(); + let mut result = Vec::<f64>::with_capacity(rects.len() * 4); + for rect in rects { + result.push(rect.x0 + client_top_left.x); + result.push(rect.y0 + client_top_left.y); + result.push(rect.width()); + result.push(rect.height()); + } + Ok(safe_array_from_f64_slice(&result)) + }) + } + + fn GetEnclosingElement(&self) -> Result<IRawElementProviderSimple> { + // Revisit this if we eventually support embedded objects. + if self.is_long() { + return self.long(|_, node, context, _, _| { + Ok(context.get_or_create_platform_node(node.id()).into_interface()) + }); + } + uia_catch(|| { + let context = self.upgrade_context()?; + let tree = context.read_tree(); + let id = self.upgrade_node(tree.state())?.id(); + Ok(context.get_or_create_platform_node(id).into_interface()) + }) + } + + fn GetText(&self, max_length: i32) -> Result<BSTR> { + if self.is_long() { + return self.long(|text, _, _, start, end| { + let s = text.slice(*start, *end); + let s = match usize::try_from(max_length) { + Ok(n) => s.char_indices().nth(n).map_or(s, |(k, _)| &s[..k]), + Err(_) => s, + }; + Ok(BSTR::from(s)) + }); + } + // The Microsoft docs imply that the provider isn't _required_ + // to truncate text at the max length, so we just ignore it. + self.read(|range| { + let mut buffer = StringBuffer::acquire(); + let mut result = WideString::new(&mut buffer); + range.write_text(&mut result).unwrap(); + Ok(result.into()) + }) + } + + fn Move(&self, unit: TextUnit, count: i32) -> Result<i32> { + if self.is_long() { + return self.long(|text, node, _, start, end| { + let unit = long_unit(unit)?; + let state = (unit == Unit::Line).then(|| drawn_state(&node, text)); + let drawn = state.as_ref().map_or(&[][..], |s| s.lines.as_slice()); + let degenerate = start == end; + let from = if degenerate { + *start + } else if let Some(st) = &state { + text.start_of_in(*start, unit, st) + } else { + text.start_of(*start, unit) + }; + let (at, moved) = text.step_in(from, unit, count, drawn); + if moved != 0 { + *start = at; + *end = if degenerate || at == text.len() { at } else { text.next_in(at, unit, drawn) }; + } + Ok(moved) + }); + } + self.write(|range| { + let degenerate = range.is_degenerate(); + let start = range.start(); + let start = if degenerate { + start + } else { + back_to_unit_start(start, unit)? + }; + let (start, moved) = move_position(start, unit, false, count)?; + if moved != 0 { + range.set_start(start); + let end = if degenerate || start.is_document_end() { + start + } else { + move_forward_to_end(start, unit)? + }; + range.set_end(end); + } + Ok(moved) + }) + } + + fn MoveEndpointByUnit( + &self, + endpoint: TextPatternRangeEndpoint, + unit: TextUnit, + count: i32, + ) -> Result<i32> { + if self.is_long() { + return self.long(|text, node, _, start, end| { + let unit = long_unit(unit)?; + let drawn = if unit == Unit::Line { drawn_lines(&node, text) } else { Vec::new() }; + let at = match endpoint { + TextPatternRangeEndpoint_Start => *start, + TextPatternRangeEndpoint_End => *end, + _ => return Err(invalid_arg()), + }; + let (at, moved) = text.step_in(at, unit, count, &drawn); + set_long_endpoint(start, end, endpoint, at); + Ok(moved) + }); + } + self.write(|range| { + let pos = position_from_endpoint(range, endpoint)?; + let (pos, moved) = + move_position(pos, unit, endpoint == TextPatternRangeEndpoint_End, count)?; + set_endpoint_position(range, endpoint, pos)?; + Ok(moved) + }) + } + + fn MoveEndpointByRange( + &self, + endpoint: TextPatternRangeEndpoint, + other: Ref<ITextRangeProvider>, + other_endpoint: TextPatternRangeEndpoint, + ) -> Result<()> { + uia_catch(|| { + let other = unsafe { required_param(&other)?.as_impl() }; + self.require_same_context(other)?; + if self.is_long() || other.is_long() { + // Read the other range first: it may be this one. + let (mine, theirs) = (self.long_endpoints(), other.long_endpoints()); + let (Some(mine), Some((node, a, b))) = (mine, theirs) else { + return Err(invalid_arg()); + }; + if node != mine.0 { + return Err(invalid_arg()); + } + let at = match other_endpoint { + TextPatternRangeEndpoint_Start => a, + TextPatternRangeEndpoint_End => b, + _ => return Err(invalid_arg()), + }; + return self.long(|text, _, _, start, end| { + set_long_endpoint(start, end, endpoint, text.clamp(at)); + Ok(()) + }); + } + // We have to obtain the tree state and ranges manually to avoid + // lifetime issues, and work with the two locks in a specific order + // to avoid deadlock. + self.with_tree_state(|tree_state| { + let other_range = other.upgrade_for_read(tree_state)?; + let mut state = self.write_state(); + let mut range = upgrade_range(runs(&state)?, tree_state)?; + if range.node().id() != other_range.node().id() { + return Err(invalid_arg()); + } + let pos = position_from_endpoint(&other_range, other_endpoint)?; + set_endpoint_position(&mut range, endpoint, pos)?; + *state = State::Runs(range.downgrade()); + Ok(()) + }) + }) + } + + fn Select(&self) -> Result<()> { + if self.is_long() { + return self.long_action(Action::SetTextSelection, |node, start, end| { + let (id, _) = node.locate(); + let at = |character_index| WeakPosition { node: id, character_index }; + Some(ActionData::SetTextSelection(TextSelection { anchor: at(start), focus: at(end) })) + }); + } + self.do_action(|range, tree| { + let (target_node, target_tree) = tree.state().locate_node(range.node().id()).unwrap(); + ActionRequest { + action: Action::SetTextSelection, + target_tree, + target_node, + data: Some(ActionData::SetTextSelection(range.to_text_selection())), + } + }) + } + + fn AddToSelection(&self) -> Result<()> { + // AccessKit doesn't support multiple text selections. + Err(invalid_operation()) + } + + fn RemoveFromSelection(&self) -> Result<()> { + // AccessKit doesn't support multiple text selections. + Err(invalid_operation()) + } + + fn ScrollIntoView(&self, align_to_top: BOOL) -> Result<()> { + if self.is_long() { + return self.long_action(Action::ScrollIntoView, |_, _, _| None); + } + self.do_action(|range, tree| { + let position = if align_to_top.into() { + range.start() + } else { + range.end() + }; + let (target_node, target_tree) = tree + .state() + .locate_node(position.inner_node().id()) + .unwrap(); + ActionRequest { + action: Action::ScrollIntoView, + target_tree, + target_node, + data: Some(ActionData::ScrollHint(if align_to_top.into() { + ScrollHint::TopEdge + } else { + ScrollHint::BottomEdge + })), + } + }) + } + + fn GetChildren(&self) -> Result<*mut SAFEARRAY> { + // We don't support embedded objects in text. + Ok(safe_array_from_com_slice(&[])) + } +} + +// Ensures that `PlatformRange` is actually safe to use in the free-threaded +// manner that we advertise via `ProviderOptions`. +#[test] +fn platform_range_impl_send_sync() { + fn assert_send_sync<T: Send + Sync>() {} + assert_send_sync::<PlatformRange>(); +} diff --git a/app/vendor/rune/vendor/accesskit_windows/src/util.rs b/app/vendor/rune/vendor/accesskit_windows/src/util.rs new file mode 100644 index 0000000..45b1d47 --- /dev/null +++ b/app/vendor/rune/vendor/accesskit_windows/src/util.rs @@ -0,0 +1,536 @@ +// Copyright 2022 The AccessKit Authors. All rights reserved. +// Licensed under the Apache License, Version 2.0 (found in +// the LICENSE-APACHE file) or the MIT license (found in +// the LICENSE-MIT file), at your option. + +use accesskit::{Color, Point, TextAlign, TextDecorationStyle}; +use accesskit_consumer::{TextRangePropertyValue, TreeState}; +use std::{ + cell::RefCell, + fmt::{self, Write}, + mem::ManuallyDrop, + ops::{Deref, DerefMut}, + sync::{Arc, Weak}, +}; +use windows::{ + Win32::{ + Foundation::*, + Globalization::*, + Graphics::Gdi::*, + System::{Com::*, Ole::*, Variant::*}, + UI::{Accessibility::*, WindowsAndMessaging::*}, + }, + core::*, +}; + +use crate::window_handle::WindowHandle; + +thread_local! { + static STRING_SCRATCH: RefCell<Vec<Vec<u16>>> = const { RefCell::new(Vec::new()) }; +} + +const MAX_RETAINED_SCRATCH_CAPACITY: usize = 4096; +const MAX_POOLED_BUFFERS: usize = 2; + +/// A scratch buffer for wide-string conversion, leased from a thread-local pool. +pub(crate) struct StringBuffer(Vec<u16>); + +impl StringBuffer { + pub(crate) fn acquire() -> Self { + Self(STRING_SCRATCH.with(|c| c.borrow_mut().pop().unwrap_or_default())) + } +} + +impl Drop for StringBuffer { + fn drop(&mut self) { + let mut buf = std::mem::take(&mut self.0); + if buf.capacity() > MAX_RETAINED_SCRATCH_CAPACITY { + buf.clear(); + buf.shrink_to(MAX_RETAINED_SCRATCH_CAPACITY); + } + STRING_SCRATCH.with(|c| { + let mut pool = c.borrow_mut(); + if pool.len() < MAX_POOLED_BUFFERS { + pool.push(buf); + } + }); + } +} + +impl Deref for StringBuffer { + type Target = Vec<u16>; + fn deref(&self) -> &Vec<u16> { + &self.0 + } +} + +impl DerefMut for StringBuffer { + fn deref_mut(&mut self) -> &mut Vec<u16> { + &mut self.0 + } +} + +pub(crate) struct WideString<'a>(&'a mut Vec<u16>); + +impl<'a> WideString<'a> { + pub(crate) fn new(buffer: &'a mut Vec<u16>) -> Self { + buffer.clear(); + Self(buffer) + } +} + +impl Write for WideString<'_> { + fn write_str(&mut self, s: &str) -> fmt::Result { + self.0.extend(s.encode_utf16()); + Ok(()) + } + + fn write_char(&mut self, c: char) -> fmt::Result { + self.0.extend_from_slice(c.encode_utf16(&mut [0; 2])); + Ok(()) + } +} + +impl PartialEq for WideString<'_> { + fn eq(&self, other: &Self) -> bool { + *self.0 == *other.0 + } +} + +impl From<WideString<'_>> for BSTR { + fn from(value: WideString) -> Self { + Self::from_wide(value.0) + } +} + +#[derive(Debug, PartialEq, Eq)] +pub(crate) struct LocaleName<'a>(pub(crate) &'a str); + +impl From<LocaleName<'_>> for Variant { + fn from(value: LocaleName) -> Self { + let lcid = unsafe { LocaleNameToLCID(&HSTRING::from(value.0), LOCALE_ALLOW_NEUTRAL_NAMES) }; + (lcid != 0).then_some(lcid.cast_signed()).into() + } +} + +pub(crate) struct Variant(VARIANT); + +impl From<Variant> for VARIANT { + fn from(variant: Variant) -> Self { + variant.0 + } +} + +impl Variant { + pub(crate) fn empty() -> Self { + Self(VARIANT::default()) + } + + pub(crate) fn is_empty(&self) -> bool { + self.0.is_empty() + } +} + +impl From<BSTR> for Variant { + fn from(value: BSTR) -> Self { + Self(value.into()) + } +} + +impl From<WideString<'_>> for Variant { + fn from(value: WideString) -> Self { + BSTR::from(value).into() + } +} + +#[derive(Debug)] +pub(crate) struct StrWrapper<'a> { + value: &'a str, + buffer: &'a mut Vec<u16>, +} + +impl<'a> StrWrapper<'a> { + pub(crate) fn new(value: &'a str, buffer: &'a mut Vec<u16>) -> Self { + Self { value, buffer } + } +} + +impl PartialEq for StrWrapper<'_> { + fn eq(&self, other: &Self) -> bool { + self.value == other.value + } +} + +impl From<StrWrapper<'_>> for Variant { + fn from(w: StrWrapper) -> Self { + let mut result = WideString::new(w.buffer); + result.write_str(w.value).unwrap(); + result.into() + } +} + +impl From<IUnknown> for Variant { + fn from(value: IUnknown) -> Self { + Self(value.into()) + } +} + +impl From<i32> for Variant { + fn from(value: i32) -> Self { + Self(value.into()) + } +} + +impl From<f64> for Variant { + fn from(value: f64) -> Self { + Self(value.into()) + } +} + +impl From<ToggleState> for Variant { + fn from(value: ToggleState) -> Self { + Self(value.0.into()) + } +} + +impl From<ExpandCollapseState> for Variant { + fn from(value: ExpandCollapseState) -> Self { + Self(value.0.into()) + } +} + +impl From<LiveSetting> for Variant { + fn from(value: LiveSetting) -> Self { + Self(value.0.into()) + } +} + +impl From<CaretPosition> for Variant { + fn from(value: CaretPosition) -> Self { + Self(value.0.into()) + } +} + +impl From<UIA_CONTROLTYPE_ID> for Variant { + fn from(value: UIA_CONTROLTYPE_ID) -> Self { + Self(value.0.into()) + } +} + +impl From<OrientationType> for Variant { + fn from(value: OrientationType) -> Self { + Self(value.0.into()) + } +} + +impl From<Color> for Variant { + fn from(value: Color) -> Self { + let rgb: i32 = + (value.red as i32) | ((value.green as i32) << 8) | ((value.blue as i32) << 16); + Self(rgb.into()) + } +} + +impl From<TextDecorationStyle> for Variant { + fn from(value: TextDecorationStyle) -> Self { + let value = match value { + TextDecorationStyle::Solid => TextDecorationLineStyle_Single, + TextDecorationStyle::Dotted => TextDecorationLineStyle_Dot, + TextDecorationStyle::Dashed => TextDecorationLineStyle_Dash, + TextDecorationStyle::Double => TextDecorationLineStyle_Double, + TextDecorationStyle::Wavy => TextDecorationLineStyle_Wavy, + }; + Self::from(value.0) + } +} + +impl From<TextAlign> for Variant { + fn from(value: TextAlign) -> Self { + let value = match value { + TextAlign::Left => HorizontalTextAlignment_Left, + TextAlign::Right => HorizontalTextAlignment_Right, + TextAlign::Center => HorizontalTextAlignment_Centered, + TextAlign::Justify => HorizontalTextAlignment_Justified, + }; + Self::from(value.0) + } +} + +impl From<bool> for Variant { + fn from(value: bool) -> Self { + Self(value.into()) + } +} + +impl<T: Into<Variant>> From<Option<T>> for Variant { + fn from(value: Option<T>) -> Self { + value.map_or_else(Self::empty, T::into) + } +} + +impl<T: Into<Variant> + std::fmt::Debug + PartialEq> From<TextRangePropertyValue<T>> for Variant { + fn from(value: TextRangePropertyValue<T>) -> Self { + match value { + TextRangePropertyValue::Single(value) => value.into(), + TextRangePropertyValue::Mixed => unsafe { UiaGetReservedMixedAttributeValue() } + .unwrap() + .into(), + } + } +} + +impl From<Vec<IUnknown>> for Variant { + fn from(value: Vec<IUnknown>) -> Self { + if value.is_empty() { + Variant::empty() + } else { + let parray = safe_array_from_com_slice(&value); + Self(VARIANT { + Anonymous: VARIANT_0 { + Anonymous: ManuallyDrop::new(VARIANT_0_0 { + vt: VT_ARRAY | VT_UNKNOWN, + wReserved1: 0, + wReserved2: 0, + wReserved3: 0, + Anonymous: VARIANT_0_0_0 { parray }, + }), + }, + }) + } + } +} + +fn safe_array_from_primitive_slice<T>(vt: VARENUM, slice: &[T]) -> *mut SAFEARRAY { + let sa = unsafe { SafeArrayCreateVector(VARENUM(vt.0), 0, slice.len().try_into().unwrap()) }; + if sa.is_null() { + panic!("SAFEARRAY allocation failed"); + } + for (i, item) in slice.iter().enumerate() { + let i: i32 = i.try_into().unwrap(); + unsafe { SafeArrayPutElement(&*sa, &i, (item as *const T) as *const _) }.unwrap(); + } + sa +} + +pub(crate) fn safe_array_from_i32_slice(slice: &[i32]) -> *mut SAFEARRAY { + safe_array_from_primitive_slice(VT_I4, slice) +} + +pub(crate) fn safe_array_from_f64_slice(slice: &[f64]) -> *mut SAFEARRAY { + safe_array_from_primitive_slice(VT_R8, slice) +} + +pub(crate) fn safe_array_from_com_slice(slice: &[IUnknown]) -> *mut SAFEARRAY { + let sa = unsafe { SafeArrayCreateVector(VT_UNKNOWN, 0, slice.len().try_into().unwrap()) }; + if sa.is_null() { + panic!("SAFEARRAY allocation failed"); + } + for (i, item) in slice.iter().enumerate() { + let i: i32 = i.try_into().unwrap(); + unsafe { SafeArrayPutElement(&*sa, &i, std::mem::transmute_copy(item)) }.unwrap(); + } + sa +} + +pub(crate) enum QueuedEvent { + Simple { + element: IRawElementProviderSimple, + event_id: UIA_EVENT_ID, + }, + PropertyChanged { + element: IRawElementProviderSimple, + property_id: UIA_PROPERTY_ID, + old_value: VARIANT, + new_value: VARIANT, + }, +} + +pub(crate) fn not_implemented() -> Error { + E_NOTIMPL.into() +} + +pub(crate) fn invalid_arg() -> Error { + E_INVALIDARG.into() +} + +pub(crate) fn required_param<'a, T: Interface>(param: &'a Ref<T>) -> Result<&'a T> { + param.ok().map_err(|_| invalid_arg()) +} + +pub(crate) fn element_not_available() -> Error { + HRESULT(UIA_E_ELEMENTNOTAVAILABLE as _).into() +} + +pub(crate) fn element_not_enabled() -> Error { + HRESULT(UIA_E_ELEMENTNOTENABLED as _).into() +} + +pub(crate) fn invalid_operation() -> Error { + HRESULT(UIA_E_INVALIDOPERATION as _).into() +} + +pub(crate) fn not_supported() -> Error { + HRESULT(UIA_E_NOTSUPPORTED as _).into() +} + +pub(crate) fn client_top_left(hwnd: WindowHandle) -> Point { + let mut result = POINT::default(); + // If ClientToScreen fails, that means the window is gone. + // That's an unexpected condition, so we should fail loudly. + unsafe { ClientToScreen(hwnd.0, &mut result) }.unwrap(); + Point::new(result.x.into(), result.y.into()) +} + +pub(crate) fn window_title(hwnd: WindowHandle, buffer: &mut Vec<u16>) -> Option<BSTR> { + // The following is an old hack to get the window caption without ever + // sending messages to the window itself, even if the window is in + // the same process but possibly a separate thread. This prevents + // possible hangs and sluggishness. This hack has been proven to work + // over nearly 20 years on every version of Windows back to XP. + let result = unsafe { DefWindowProcW(hwnd.0, WM_GETTEXTLENGTH, WPARAM(0), LPARAM(0)) }; + if result.0 <= 0 { + return None; + } + let capacity = (result.0 as usize) + 1; // make room for the null + buffer.clear(); + buffer.reserve(capacity); + let result = unsafe { + DefWindowProcW( + hwnd.0, + WM_GETTEXT, + WPARAM(capacity), + LPARAM(buffer.as_mut_ptr() as _), + ) + }; + if result.0 <= 0 { + return None; + } + let len = result.0 as usize; + unsafe { buffer.set_len(len) }; + Some(BSTR::from_wide(buffer)) +} + +pub(crate) fn toolkit_description<'a>( + state: &TreeState, + buffer: &'a mut Vec<u16>, +) -> WideString<'a> { + let mut result = WideString::new(buffer); + result.write_str(state.toolkit_name()).unwrap(); + if let Some(version) = state.toolkit_version() { + result.write_char(' ').unwrap(); + result.write_str(version).unwrap(); + } + result +} + +pub(crate) fn upgrade<T>(weak: &Weak<T>) -> Result<Arc<T>> { + match weak.upgrade() { + Some(strong) => Ok(strong), + _ => Err(element_not_available()), + } +} + +pub(crate) struct AriaProperties<W: Write> { + inner: W, + need_separator: bool, +} + +impl<W: Write> AriaProperties<W> { + pub(crate) fn new(inner: W) -> Self { + Self { + inner, + need_separator: false, + } + } + + pub(crate) fn write_property(&mut self, name: &str, value: &str) -> fmt::Result { + if self.need_separator { + self.inner.write_char(';')?; + } + self.inner.write_str(name)?; + self.inner.write_char('=')?; + self.inner.write_str(value)?; + self.need_separator = true; + Ok(()) + } + + pub(crate) fn write_bool_property(&mut self, name: &str, value: bool) -> fmt::Result { + self.write_property(name, if value { "true" } else { "false" }) + } + + pub(crate) fn write_usize_property(&mut self, name: &str, value: usize) -> fmt::Result { + self.write_property(name, &value.to_string()) + } + + pub(crate) fn has_properties(&self) -> bool { + self.need_separator + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn on_fresh_thread(f: impl FnOnce() + Send + 'static) { + std::thread::spawn(f).join().unwrap(); + } + + #[test] + fn acquire_reuses_dropped_allocation() { + on_fresh_thread(|| { + let ptr = { + let mut buf = StringBuffer::acquire(); + buf.extend(std::iter::repeat_n(0u16, 64)); + buf.as_ptr() + }; + let buf = StringBuffer::acquire(); + assert_eq!(buf.as_ptr(), ptr); + assert!(buf.capacity() >= 64); + }); + } + + #[test] + fn simultaneous_leases_are_distinct() { + on_fresh_thread(|| { + let mut a = StringBuffer::acquire(); + let mut b = StringBuffer::acquire(); + a.push(1); + b.push(2); + assert_ne!(a.as_ptr(), b.as_ptr()); + assert_eq!(a[0], 1); + assert_eq!(b[0], 2); + }); + } + + #[test] + fn outsized_allocation_is_released_on_drop() { + on_fresh_thread(|| { + { + let mut buf = StringBuffer::acquire(); + buf.reserve(MAX_RETAINED_SCRATCH_CAPACITY * 4); + assert!(buf.capacity() > MAX_RETAINED_SCRATCH_CAPACITY); + } + let buf = StringBuffer::acquire(); + assert!(buf.capacity() <= MAX_RETAINED_SCRATCH_CAPACITY); + }); + } + + #[test] + fn pool_retains_at_most_max_pooled_buffers() { + on_fresh_thread(|| { + let bufs: Vec<_> = (0..MAX_POOLED_BUFFERS + 1) + .map(|_| { + let mut buf = StringBuffer::acquire(); + buf.reserve(64); + buf + }) + .collect(); + drop(bufs); + let reacquired: Vec<_> = (0..MAX_POOLED_BUFFERS + 1) + .map(|_| StringBuffer::acquire()) + .collect(); + let reused = reacquired.iter().filter(|buf| buf.capacity() >= 64).count(); + assert_eq!(reused, MAX_POOLED_BUFFERS); + }); + } +} diff --git a/app/vendor/rune/vendor/accesskit_windows/src/window_handle.rs b/app/vendor/rune/vendor/accesskit_windows/src/window_handle.rs new file mode 100644 index 0000000..0538d5b --- /dev/null +++ b/app/vendor/rune/vendor/accesskit_windows/src/window_handle.rs @@ -0,0 +1,32 @@ +// Copyright 2024 The AccessKit Authors. All rights reserved. +// Licensed under the Apache License, Version 2.0 (found in +// the LICENSE-APACHE file) or the MIT license (found in +// the LICENSE-MIT file), at your option. + +use windows::Win32::Foundation::HWND; + +#[repr(transparent)] +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct WindowHandle(pub HWND); + +unsafe impl Send for WindowHandle {} +unsafe impl Sync for WindowHandle {} + +impl From<HWND> for WindowHandle { + fn from(value: HWND) -> Self { + Self(value) + } +} + +impl From<WindowHandle> for HWND { + fn from(value: WindowHandle) -> Self { + value.0 + } +} + +#[cfg(test)] +mod tests { + use super::*; + + static_assertions::assert_impl_all!(WindowHandle: Send, Sync); +} diff --git a/app/vendor/rune/vendor/parley_engine.patch b/app/vendor/rune/vendor/parley_engine.patch new file mode 100644 index 0000000..3989a98 --- /dev/null +++ b/app/vendor/rune/vendor/parley_engine.patch @@ -0,0 +1,708 @@ +diff --git a/Cargo.toml b/Cargo.toml +index 68a28c1..c09da2b 100644 +--- a/Cargo.toml ++++ b/Cargo.toml +@@ -43,6 +43,7 @@ bytemuck = [ + "parlance/bytemuck", + ] + complex-scripts = [] ++line-dictionaries = [] + default = ["std"] + libm = [ + "fontique/libm", +diff --git a/src/analysis.rs b/src/analysis.rs +index 7d871af..31cf0dc 100644 +--- a/src/analysis.rs ++++ b/src/analysis.rs +@@ -150,13 +150,43 @@ impl AnalysisDataSources { + } + } + +-#[cfg(feature = "complex-scripts")] ++/// The segmenters an [`Analyzer`] has made, kept for its next texts (Rune: ++/// vendor/parley_engine.patch). Making one looks up its rule data and, with `complex-scripts`, ++/// loads the dictionaries; they're `'static` and `Copy`, so a kept one is the same value a new ++/// one would be. ++#[derive(Default)] ++pub(crate) struct Segmenters { ++ line: Vec<(SegmenterKey, LineSegmenterBorrowed<'static>)>, ++ word: Option<WordSegmenterBorrowed<'static>>, ++} ++ ++impl Segmenters { ++ fn line(&mut self, key: SegmenterKey) -> LineSegmenterBorrowed<'static> { ++ if let Some((_, segmenter)) = self.line.iter().find(|(k, _)| *k == key) { ++ return *segmenter; ++ } ++ let segmenter = AnalysisDataSources::new().line_segmenter(key); ++ self.line.push((key, segmenter)); ++ segmenter ++ } ++ ++ fn word(&mut self) -> WordSegmenterBorrowed<'static> { ++ *self ++ .word ++ .get_or_insert_with(|| AnalysisDataSources::new().word_segmenter()) ++ } ++} ++ ++// `line-dictionaries` (Rune: vendor/parley_engine.patch): the line segmenter's Thai, Lao, Khmer and ++// Burmese dictionaries without the word segmenter's (Chinese and Japanese words come from the host's ++// `dictionary` segmenter instead). ++#[cfg(any(feature = "complex-scripts", feature = "line-dictionaries"))] + #[inline(always)] + fn line_segmenter_impl(opt: LineBreakOptions<'_>) -> LineSegmenterBorrowed<'static> { + LineSegmenter::new_dictionary(opt) + } + +-#[cfg(not(feature = "complex-scripts"))] ++#[cfg(not(any(feature = "complex-scripts", feature = "line-dictionaries")))] + #[inline(always)] + fn line_segmenter_impl(opt: LineBreakOptions<'_>) -> LineSegmenterBorrowed<'static> { + LineSegmenter::new_for_non_complex_scripts(opt) +@@ -558,8 +588,9 @@ pub(crate) fn analyze_text( + for (substring_index, (substring, segmenter_key, last)) in contiguous_substrings.enumerate() { + // Fast path for text with a single segmenter configuration. + if substring_index == 0 && last { +- let mut lb_iter = data_sources +- .line_segmenter(segmenter_key) ++ let mut lb_iter = analyzer ++ .segmenters ++ .line(segmenter_key) + .segment_str(substring); + + let _first = lb_iter.next(); +@@ -580,8 +611,9 @@ pub(crate) fn analyze_text( + break; + } + +- let line_boundaries_iter = data_sources +- .line_segmenter(segmenter_key) ++ let line_boundaries_iter = analyzer ++ .segmenters ++ .line(segmenter_key) + .segment_str(substring); + + let mut substring_chars = substring.chars(); +@@ -613,8 +645,18 @@ pub(crate) fn analyze_text( + } + } + ++ // Words, and in Thai, Lao, Khmer and Burmese line breaks, that the host's dictionary finds ++ // (`dictionary`; Rune: vendor/parley_engine.patch). ++ let mut dictionary = crate::dictionary::Words::of(text, |c| data_sources.properties(c)); ++ let before = line_boundary_positions.len(); ++ line_boundary_positions.extend(dictionary.line_breaks()); ++ if line_boundary_positions.len() > before { ++ line_boundary_positions.sort_unstable(); ++ line_boundary_positions.dedup(); ++ } ++ + // Collect boundary byte positions compactly +- let mut wb_iter = data_sources.word_segmenter().segment_str(text).peekable(); ++ let mut wb_iter = analyzer.segmenters.word().segment_str(text).peekable(); + let mut gb_iter = data_sources + .grapheme_segmenter() + .segment_str(text) +@@ -679,8 +721,11 @@ pub(crate) fn analyze_text( + let properties = data_sources.properties(ch); + + // For characters requiring a dictionary for deciding word boundaries, apply +- // UAX #29 Rule WB999 in case there's no dictionary (because ICU4X does not). +- if !is_word ++ // UAX #29 Rule WB999 in case there's no dictionary (because ICU4X does not); inside a run ++ // the host's dictionary segmented, its boundaries decide. ++ if let Some(bound) = dictionary.word_at(byte_pos) { ++ is_word = bound; ++ } else if !is_word + && is_grapheme_start + && properties.needs_dictionary_word_break() + && !has_word_dictionary(properties.script()) +diff --git a/src/analyzer.rs b/src/analyzer.rs +index b9ae430..647dd76 100644 +--- a/src/analyzer.rs ++++ b/src/analyzer.rs +@@ -15,6 +15,7 @@ use crate::analysis::{Analysis, analyze_text}; + #[derive(Default)] + pub struct Analyzer { + pub(crate) bidi: BidiResolver, ++ pub(crate) segmenters: crate::analysis::Segmenters, + } + + impl core::fmt::Debug for Analyzer { +diff --git a/src/bidi.rs b/src/bidi.rs +index 25aa622..fd44780 100644 +--- a/src/bidi.rs ++++ b/src/bidi.rs +@@ -142,7 +142,9 @@ impl BidiResolver { + || is_isolate_initiator(t) + || t == BidiClass::PopDirectionalIsolate + { +- //self.levels[i] = self.base_level; ++ // UAX #9 L1: whitespace, isolate initiators and PDIs that end the paragraph take ++ // the paragraph's level (Rune: vendor/parley_engine.patch). ++ self.levels[i] = self.base_level; + } else { + break; + } +diff --git a/src/dictionary.rs b/src/dictionary.rs +new file mode 100644 +index 0000000..5032d35 +--- /dev/null ++++ b/src/dictionary.rs +@@ -0,0 +1,134 @@ ++// Copyright 2026 the Parley Authors ++// SPDX-License-Identifier: Apache-2.0 OR MIT ++ ++//! Word boundaries for the scripts whose words need a dictionary (Thai, Lao, Khmer, Burmese, ++//! Chinese and Japanese), from outside Parley (Rune: vendor/parley_engine.patch). A build without ++//! `complex-scripts` links none of ICU's dictionaries; a host that has its own (a browser's ++//! `Intl.Segmenter`) gives them here. Its boundaries are the words inside each such run and, in ++//! Thai, Lao, Khmer and Burmese, the run's line break opportunities too, as ICU's dictionary ++//! line segmenter makes them (UAX #14 breaks class SA at word boundaries). ++ ++use alloc::vec::Vec; ++ ++use icu_properties::props::{GeneralCategory, Script}; ++use parley_data::Properties; ++ ++/// Appends to `out` the word boundaries strictly inside `text`, as ascending byte offsets, for a ++/// `text` all in one dictionary language: `language` is `th`, `lo`, `km`, `my` or `ja` (Han, ++/// hiragana and katakana, whose dictionary Chinese and Japanese share). ++pub type DictionarySegmenter = fn(text: &str, language: &str, out: &mut Vec<usize>); ++ ++#[cfg(feature = "std")] ++static SEGMENTER: std::sync::OnceLock<DictionarySegmenter> = std::sync::OnceLock::new(); ++ ++/// Gives Parley the host's dictionary word boundaries, once (a second call changes nothing). ++/// Without `complex-scripts` and without this, a Thai phrase has no break opportunity and a ++/// Chinese sentence's words are its characters. Needs `std`. ++pub fn set_dictionary_segmenter(segmenter: DictionarySegmenter) { ++ #[cfg(feature = "std")] ++ let _ = SEGMENTER.set(segmenter); ++ #[cfg(not(feature = "std"))] ++ let _ = segmenter; ++} ++ ++fn segmenter() -> Option<DictionarySegmenter> { ++ #[cfg(all(feature = "std", not(feature = "complex-scripts")))] ++ return SEGMENTER.get().copied(); ++ #[cfg(not(all(feature = "std", not(feature = "complex-scripts"))))] ++ None ++} ++ ++/// The dictionary language a character's script asks for, and whether its words are its line ++/// break opportunities (class SA). ++fn language(script: Script) -> Option<(&'static str, bool)> { ++ Some(match script { ++ Script::Thai => ("th", true), ++ Script::Lao => ("lo", true), ++ Script::Khmer => ("km", true), ++ Script::Myanmar => ("my", true), ++ Script::Han | Script::Hiragana | Script::Katakana => ("ja", false), ++ _ => return None, ++ }) ++} ++ ++/// A mark, a joiner or a length mark (ー) carries on the run before it. ++fn continues(properties: Properties, ch: char) -> bool { ++ matches!(properties.script(), Script::Inherited) ++ || matches!( ++ properties.general_category(), ++ GeneralCategory::NonspacingMark | GeneralCategory::SpacingMark | GeneralCategory::EnclosingMark ++ ) ++ || matches!(ch, '\u{200C}' | '\u{200D}' | '\u{30FC}') ++} ++ ++/// The text's dictionary runs and the host's word boundaries inside them. ++#[derive(Default)] ++pub(crate) struct Words { ++ /// `(start, end, sa)` byte ranges, ascending. ++ runs: Vec<(usize, usize, bool)>, ++ /// Boundaries strictly inside the runs, ascending. ++ bounds: Vec<usize>, ++ run: usize, ++ bound: usize, ++} ++ ++impl Words { ++ pub(crate) fn of(text: &str, properties: impl Fn(char) -> Properties) -> Self { ++ let Some(segment) = segmenter() else { return Self::default() }; ++ let mut words = Self::default(); ++ let mut open: Option<(usize, &'static str, bool)> = None; ++ let close = |words: &mut Self, start: usize, end: usize, lang: &'static str, sa: bool| { ++ let run = &text[start..end]; ++ // A single character has no boundary inside it. ++ if run.chars().nth(1).is_none() { ++ return; ++ } ++ let mut found = Vec::new(); ++ segment(run, lang, &mut found); ++ words.bounds.extend(found.into_iter().filter(|&b| b > 0 && b < run.len() && run.is_char_boundary(b)).map(|b| b + start)); ++ words.runs.push((start, end, sa)); ++ }; ++ for (at, ch) in text.char_indices() { ++ let props = properties(ch); ++ if let Some((start, lang, sa)) = open { ++ if continues(props, ch) || language(props.script()).is_some_and(|(l, _)| l == lang) { ++ continue; ++ } ++ close(&mut words, start, at, lang, sa); ++ } ++ open = language(props.script()).map(|(lang, sa)| (at, lang, sa)); ++ } ++ if let Some((start, lang, sa)) = open { ++ close(&mut words, start, text.len(), lang, sa); ++ } ++ words ++ } ++ ++ /// The boundaries inside Thai, Lao, Khmer and Burmese runs: their line break opportunities. ++ /// None with `line-dictionaries`, whose line segmenter finds them itself. ++ pub(crate) fn line_breaks(&self) -> impl Iterator<Item = usize> + '_ { ++ let mut run = if cfg!(feature = "line-dictionaries") { self.runs.len() } else { 0 }; ++ self.bounds.iter().copied().filter(move |&b| { ++ while self.runs.get(run).is_some_and(|r| r.1 <= b) { ++ run += 1; ++ } ++ self.runs.get(run).is_some_and(|r| r.0 < b && r.2) ++ }) ++ } ++ ++ /// Inside a run (past its first character), whether `at` is a word boundary; `None` outside ++ /// one, where the rule-based segmenter decides. Asked in ascending order. ++ pub(crate) fn word_at(&mut self, at: usize) -> Option<bool> { ++ while self.runs.get(self.run).is_some_and(|r| r.1 <= at) { ++ self.run += 1; ++ } ++ let run = self.runs.get(self.run)?; ++ if at <= run.0 { ++ return None; ++ } ++ while self.bounds.get(self.bound).is_some_and(|&b| b < at) { ++ self.bound += 1; ++ } ++ Some(self.bounds.get(self.bound) == Some(&at)) ++ } ++} +diff --git a/src/lib.rs b/src/lib.rs +index 647f360..ea7d79b 100644 +--- a/src/lib.rs ++++ b/src/lib.rs +@@ -110,6 +110,8 @@ mod analysis; + mod analyzer; + mod bidi; + pub mod break_overrides; ++pub mod dictionary; ++pub mod platform; + mod glyph; + pub mod itemize; + mod lru_cache; +diff --git a/src/platform.rs b/src/platform.rs +new file mode 100644 +index 0000000..041b9b9 +--- /dev/null ++++ b/src/platform.rs +@@ -0,0 +1,70 @@ ++// Copyright 2026 the Parley Authors ++// SPDX-License-Identifier: Apache-2.0 OR MIT ++ ++//! A face of last resort that the platform draws (Rune: vendor/parley_engine.patch). A host that ++//! can shape and draw text itself (a browser's canvas, with the system's fonts, shaping and ++//! colour emoji) registers a font that covers every character and gives its runs a shaper here. ++//! A run in that font isn't shaped by HarfRust: the host gives one glyph per grapheme, its ++//! advance measured as the platform lays the run out, and the glyph ids are the host's own, for ++//! it to draw them. ++ ++use alloc::vec::Vec; ++ ++/// A run in the platform's face, for its shaper. ++#[derive(Debug)] ++pub struct PlatformText<'a> { ++ /// The run's text. ++ pub text: &'a str, ++ /// Byte offsets into `text` where each grapheme starts, ascending, the first 0. ++ pub graphemes: &'a [u32], ++ /// Byte offsets where each unit the platform draws whole starts (at grapheme starts, between ++ /// break opportunities), ascending, the first 0. A line never breaks inside one. ++ pub units: &'a [u32], ++ /// The font size, in the layout's units. ++ pub size: f32, ++ /// The weight asked for (`wght`, 100 to 900). ++ pub weight: f32, ++ /// Italic asked for. ++ pub italic: bool, ++ /// The run is right to left. ++ pub rtl: bool, ++ /// The run's language tag, if it has one. ++ pub language: Option<&'a str>, ++} ++ ++/// One glyph per grapheme of a [`PlatformText`], in logical order. ++#[derive(Clone, Copy, Debug, Default)] ++pub struct PlatformGlyph { ++ /// The host's id for what this glyph draws. ++ pub id: u32, ++ /// The grapheme's advance, in the layout's units. ++ pub advance: f32, ++ /// How far right of its pen the glyph draws, in the layout's units. ++ pub x_offset: f32, ++} ++ ++/// Fills `out` with one glyph per grapheme of the run, in logical order. ++pub type PlatformShaper = fn(run: &PlatformText<'_>, out: &mut Vec<PlatformGlyph>); ++ ++#[cfg(feature = "std")] ++static PLATFORM: std::sync::OnceLock<(u64, PlatformShaper)> = std::sync::OnceLock::new(); ++ ++/// Makes the font whose data has id `font` (`Blob::id`) the platform's face, shaped by `shaper`, ++/// once (a second call changes nothing). Needs `std`. ++pub fn set_platform_face(font: u64, shaper: PlatformShaper) { ++ #[cfg(feature = "std")] ++ let _ = PLATFORM.set((font, shaper)); ++ #[cfg(not(feature = "std"))] ++ let _ = (font, shaper); ++} ++ ++/// The shaper for the font with data id `font`, if it's the platform's face. ++pub(crate) fn shaper(font: u64) -> Option<PlatformShaper> { ++ #[cfg(feature = "std")] ++ return PLATFORM.get().filter(|(id, _)| *id == font).map(|(_, shaper)| *shaper); ++ #[cfg(not(feature = "std"))] ++ { ++ let _ = font; ++ None ++ } ++} +diff --git a/src/shape/cache.rs b/src/shape/cache.rs +index cb8d3c5..530b919 100644 +--- a/src/shape/cache.rs ++++ b/src/shape/cache.rs +@@ -92,6 +92,43 @@ impl<'a> From<ShapeInstanceKey<'a>> for ShapeInstanceId { + } + } + ++/// A shaped run's font metrics: its font instance at a size (Rune: vendor/parley_engine.patch). ++pub(crate) struct RunMetricsId { ++ instance: ShapeInstanceId, ++ font_size: u32, ++} ++ ++pub(crate) struct RunMetricsKey<'a> { ++ instance: ShapeInstanceKey<'a>, ++ font_size: f32, ++} ++ ++impl<'a> RunMetricsKey<'a> { ++ pub(crate) const fn new(instance: ShapeInstanceKey<'a>, font_size: f32) -> Self { ++ Self { ++ instance, ++ font_size, ++ } ++ } ++} ++ ++impl<'a> Equivalent<RunMetricsId> for RunMetricsKey<'a> { ++ #[inline(always)] ++ fn equivalent(&self, key: &RunMetricsId) -> bool { ++ self.font_size.to_bits() == key.font_size && self.instance.equivalent(&key.instance) ++ } ++} ++ ++impl<'a> From<RunMetricsKey<'a>> for RunMetricsId { ++ #[inline(always)] ++ fn from(key: RunMetricsKey<'a>) -> Self { ++ Self { ++ instance: key.instance.into(), ++ font_size: key.font_size.to_bits(), ++ } ++ } ++} ++ + pub(crate) struct ShapePlanId { + /// The font collection's blob ID. + font_blob_id: u64, +diff --git a/src/shape/shaped_text.rs b/src/shape/shaped_text.rs +index 63afadd..1ec9ddc 100644 +--- a/src/shape/shaped_text.rs ++++ b/src/shape/shaped_text.rs +@@ -78,6 +78,40 @@ impl FontMetrics { + font: &FontInstance, + font_size: f32, + variations: &[parlance::FontVariation], ++ ) -> Option<Self> { ++ // A style's metrics depend on its font instance, size and variations alone; a style ++ // table asks for the same few again in every layout (Rune: vendor/parley_engine.patch). ++ #[cfg(feature = "std")] ++ { ++ type Memo = Vec<(u64, u32, fontique::Synthesis, u32, Vec<parlance::FontVariation>, Option<FontMetrics>)>; ++ std::thread_local! { ++ static MEMO: core::cell::RefCell<Memo> = const { core::cell::RefCell::new(Vec::new()) }; ++ } ++ let (id, index, size) = (font.font.data.id(), font.font.index, font_size.to_bits()); ++ let found = MEMO.with_borrow(|memo| { ++ memo.iter() ++ .find(|m| m.0 == id && m.1 == index && m.2 == font.synthesis && m.3 == size && m.4 == variations) ++ .map(|m| m.5) ++ }); ++ if let Some(metrics) = found { ++ return metrics; ++ } ++ let metrics = Self::compute_from_font_instance(font, font_size, variations); ++ MEMO.with_borrow_mut(|memo| { ++ if memo.len() >= 64 { ++ memo.remove(0); ++ } ++ memo.push((id, index, font.synthesis, size, variations.to_vec(), metrics)); ++ }); ++ return metrics; ++ } ++ Self::compute_from_font_instance(font, font_size, variations) ++ } ++ ++ fn compute_from_font_instance( ++ font: &FontInstance, ++ font_size: f32, ++ variations: &[parlance::FontVariation], + ) -> Option<Self> { + let font_ref = + skrifa::FontRef::from_index(font.font.data.as_ref(), font.font.index).ok()?; +@@ -102,7 +136,7 @@ impl FontMetrics { + )) + } + +- fn from_skrifa_metrics(metrics: &skrifa::metrics::Metrics, font_size: f32) -> Self { ++ pub(crate) fn from_skrifa_metrics(metrics: &skrifa::metrics::Metrics, font_size: f32) -> Self { + // Default values from HarfBuzz: https://github.com/harfbuzz/harfbuzz/blob/12ee77ee00514c442bcd28f9aa9d56b708c37382/src/hb-ot-metrics.cc#L355-L372 + let fallback_decoration_size = font_size / 18.0; + +@@ -271,8 +305,10 @@ impl ShapedText { + char_info: &[CharInfo], + char_style_indices: &[u16], + font: &FontInstance, +- glyph_buffer: &harfrust::GlyphBuffer, ++ glyph_infos: &[harfrust::GlyphInfo], ++ glyph_positions: &[harfrust::GlyphPosition], + normalized_coords: &[harfrust::NormalizedCoord], ++ (font_metrics, units_per_em): (FontMetrics, f32), + ) { + debug_assert_eq!( + range.char_range.len(), +@@ -280,8 +316,6 @@ impl ShapedText { + "The claimed character range and the text's covered byte range should agree" + ); + +- let glyph_infos = glyph_buffer.glyph_infos(); +- + let normalized_coords_range = { + let start = self.normalized_coords.len(); + self.normalized_coords.extend( +@@ -302,23 +336,9 @@ impl ShapedText { + index + }); + +- let metrics = { +- let font = &self.fonts[font_index]; +- let font_ref = +- skrifa::FontRef::from_index(font.font.data.as_ref(), font.font.index).unwrap(); +- skrifa::metrics::Metrics::new( +- &font_ref, +- skrifa::prelude::Size::new(options.font_size), +- normalized_coords, +- ) +- }; +- let units_per_em = metrics.units_per_em as f32; +- let font_metrics = FontMetrics::from_skrifa_metrics(&metrics, options.font_size); +- + // `HarfRust` returns glyphs in visual order, so we need to process them as such while + // maintaining logical ordering of clusters. + +- let glyph_positions = glyph_buffer.glyph_positions(); + let scale_factor = options.font_size / units_per_em; + let shaped_clusters_start = self.shaped_clusters.len(); + +diff --git a/src/shape/shaper.rs b/src/shape/shaper.rs +index f1ad855..42594db 100644 +--- a/src/shape/shaper.rs ++++ b/src/shape/shaper.rs +@@ -9,6 +9,7 @@ use harfrust::ShapeOptions as HarfShapeOptions; + use linebender_resource_handle::{Blob, FontData}; + use parlance::{FontFeature, FontVariation, Language}; + ++use crate::shape::shaped_text::FontMetrics; + use crate::{ + Analysis, CharInfo, ShapedText, + itemize::{Item, Segment, TextRange}, +@@ -88,6 +89,8 @@ pub struct Shaper { + shape_data_cache: LruCache<cache::ShapeDataKey, harfrust::ShaperData>, + shape_instance_cache: LruCache<cache::ShapeInstanceId, harfrust::ShaperInstance>, + shape_plan_cache: LruCache<cache::ShapePlanId, harfrust::ShapePlan>, ++ /// Each run's font metrics and units per em (Rune: vendor/parley_engine.patch). ++ run_metrics_cache: LruCache<cache::RunMetricsId, (FontMetrics, f32)>, + unicode_buffer: Option<harfrust::UnicodeBuffer>, + features: Vec<harfrust::Feature>, + char_cluster: CharCluster, +@@ -100,6 +103,7 @@ impl Default for Shaper { + shape_data_cache: LruCache::new(MAX_ENTRIES), + shape_instance_cache: LruCache::new(MAX_ENTRIES), + shape_plan_cache: LruCache::new(MAX_ENTRIES), ++ run_metrics_cache: LruCache::new(MAX_ENTRIES), + unicode_buffer: Some(harfrust::UnicodeBuffer::new()), + features: Vec::new(), + char_cluster: CharCluster::default(), +@@ -273,6 +277,11 @@ fn shape_segment( + + // Shape a run of the segment with a single font, appending it to `shaped_text`. + let mut shape_run = |font: &FontInstance, range: TextRange| { ++ // The platform's face: its host measures the run and draws it (`platform`). ++ if let Some(platform) = crate::platform::shaper(font.font.data.id()) { ++ shape_platform_run(platform, text, range, segment, options, char_info, char_style_indices, font, shaped_text); ++ return; ++ } + // TODO: How do we want to handle errors like this? + let font_ref = + harfrust::FontRef::from_index(font.font.data.as_ref(), font.font.index).unwrap(); +@@ -360,6 +369,31 @@ fn shape_segment( + .point_size(Some(options.font_size)), + ); + ++ // A run's metrics depend on its font instance and size alone: made once for each. ++ let metrics = *scx.run_metrics_cache.entry( ++ cache::RunMetricsKey::new( ++ cache::ShapeInstanceKey::new( ++ font.font.data.id(), ++ font.font.index, ++ &font.synthesis, ++ Some(options.variations), ++ ), ++ options.font_size, ++ ), ++ || { ++ let font_ref = ++ skrifa::FontRef::from_index(font.font.data.as_ref(), font.font.index).unwrap(); ++ let metrics = skrifa::metrics::Metrics::new( ++ &font_ref, ++ skrifa::prelude::Size::new(options.font_size), ++ harf_shaper.coords(), ++ ); ++ ( ++ FontMetrics::from_skrifa_metrics(&metrics, options.font_size), ++ metrics.units_per_em as f32, ++ ) ++ }, ++ ); + shaped_text.push_run( + text, + range, +@@ -368,8 +402,10 @@ fn shape_segment( + char_info, + char_style_indices, + font, +- &glyph_buffer, ++ glyph_buffer.glyph_infos(), ++ glyph_buffer.glyph_positions(), + harf_shaper.coords(), ++ metrics, + ); + + // Replace buffer to reuse allocation in the next run. +@@ -447,6 +483,99 @@ fn variations_iter<'a>( + })) + } + ++/// A run in the platform's face (`platform`), appended to `shaped_text`: its host gives a glyph ++/// per grapheme, with units it draws whole between the run's break opportunities. ++#[expect(clippy::too_many_arguments, reason = "the shape_run closure's inputs")] ++fn shape_platform_run( ++ shaper: crate::platform::PlatformShaper, ++ text: &str, ++ range: TextRange, ++ segment: &Segment, ++ options: &ShapeOptions<'_>, ++ char_info: &[CharInfo], ++ char_style_indices: &[u16], ++ font: &FontInstance, ++ shaped_text: &mut ShapedText, ++) { ++ let run_text = &text[range.byte_range.clone()]; ++ let (mut graphemes, mut units, mut clusters) = (Vec::new(), Vec::new(), Vec::new()); ++ let mut after_newline = false; ++ for (i, ((at, ch), info)) in run_text.char_indices().zip(&char_info[range.char_range.clone()]).enumerate() { ++ let newline = matches!(ch, '\n' | '\r' | '\u{0B}' | '\u{0C}' | '\u{85}' | '\u{2028}' | '\u{2029}'); ++ let grapheme = i == 0 || info.is_grapheme_start() || newline || after_newline; ++ if grapheme { ++ #[expect(clippy::cast_possible_truncation, reason = "a run is under 4 GiB")] ++ { ++ if i == 0 || info.is_soft_wrap_opportunity() || newline || after_newline { ++ units.push(at as u32); ++ } ++ graphemes.push(at as u32); ++ clusters.push(i as u32); ++ } ++ } ++ after_newline = newline; ++ } ++ let wght = harfrust::Tag::new(b"wght"); ++ let weight = variations_iter(&font.synthesis, options.variations) ++ .filter(|v| v.tag == wght) ++ .last() ++ .map_or(if font.synthesis.embolden() { 700. } else { 400. }, |v| v.value); ++ let rtl = segment.bidi_level.is_rtl(); ++ let mut glyphs = Vec::with_capacity(graphemes.len()); ++ shaper( ++ &crate::platform::PlatformText { ++ text: run_text, ++ graphemes: &graphemes, ++ units: &units, ++ size: options.font_size, ++ weight, ++ italic: font.synthesis.skew().is_some(), ++ rtl, ++ language: options.language.as_ref().map(|l| l.as_str()), ++ }, ++ &mut glyphs, ++ ); ++ glyphs.resize(graphemes.len(), crate::platform::PlatformGlyph::default()); ++ let font_ref = skrifa::FontRef::from_index(font.font.data.as_ref(), font.font.index).unwrap(); ++ let metrics = skrifa::metrics::Metrics::new( ++ &font_ref, ++ skrifa::prelude::Size::new(options.font_size), ++ skrifa::instance::LocationRef::default(), ++ ); ++ let upem = metrics.units_per_em as f32; ++ let units_of = |px: f32| (px * upem / options.font_size.max(1e-3)).round() as i32; ++ let mut infos: Vec<harfrust::GlyphInfo> = Vec::with_capacity(glyphs.len()); ++ let mut positions: Vec<harfrust::GlyphPosition> = Vec::with_capacity(glyphs.len()); ++ for (glyph, &cluster) in glyphs.iter().zip(&clusters) { ++ let mut info = harfrust::GlyphInfo::default(); ++ info.glyph_id = glyph.id; ++ info.cluster = cluster; ++ infos.push(info); ++ let mut position = harfrust::GlyphPosition::default(); ++ position.x_advance = units_of(glyph.advance); ++ position.x_offset = units_of(glyph.x_offset); ++ positions.push(position); ++ } ++ // In visual order, as HarfRust gives them. ++ if rtl { ++ infos.reverse(); ++ positions.reverse(); ++ } ++ shaped_text.push_run( ++ text, ++ range, ++ segment, ++ options, ++ char_info, ++ char_style_indices, ++ font, ++ &infos, ++ &positions, ++ &[], ++ (FontMetrics::from_skrifa_metrics(&metrics, options.font_size), upem), ++ ); ++} ++ + pub(crate) fn script_to_harfrust(script: fontique::Script) -> harfrust::Script { + harfrust::Script::from_iso15924_tag(harfrust::Tag::new(&script.to_bytes())) + .unwrap_or(harfrust::script::UNKNOWN) diff --git a/app/vendor/rune/vendor/parley_engine/.cargo_vcs_info.json b/app/vendor/rune/vendor/parley_engine/.cargo_vcs_info.json new file mode 100644 index 0000000..6a1c21c --- /dev/null +++ b/app/vendor/rune/vendor/parley_engine/.cargo_vcs_info.json @@ -0,0 +1,6 @@ +{ + "git": { + "sha1": "6e1143dda817360dd3a2a64f9133c6e5dfabd881" + }, + "path_in_vcs": "parley_engine" +} \ No newline at end of file diff --git a/app/vendor/rune/vendor/parley_engine/Cargo.lock b/app/vendor/rune/vendor/parley_engine/Cargo.lock new file mode 100644 index 0000000..51c6c81 --- /dev/null +++ b/app/vendor/rune/vendor/parley_engine/Cargo.lock @@ -0,0 +1,545 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "bitflags" +version = "2.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b4388bee8683e3d04af747c73422af53102d2bd24d9eadb6cbc100baef4b43f8" + +[[package]] +name = "bytemuck" +version = "1.25.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "95832e849adfb21180ccb6826a99da14e5d266ae5c2e668e1602cf234f153797" +dependencies = [ + "bytemuck_derive", +] + +[[package]] +name = "bytemuck_derive" +version = "1.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9abbd1bc6865053c427f7198e6af43bfdedc55ab791faed4fbd361d789575ff" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.118", +] + +[[package]] +name = "core_maths" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77745e017f5edba1a9c1d854f6f3a52dac8a12dd5af5d2f54aecf61e43d80d30" +dependencies = [ + "libm", +] + +[[package]] +name = "displaydoc" +version = "0.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ac70aa55017e108007fbaf5aa0f54b021c98f92ff8af59d42eda9da96e3dd4f" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.118", +] + +[[package]] +name = "foldhash" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" + +[[package]] +name = "font-types" +version = "0.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "81bf886368962a7d8456f136073ed33ed1b0770c690d2063731bb6a776e99f33" +dependencies = [ + "bytemuck", +] + +[[package]] +name = "fontique" +version = "0.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbf1df16263783918b7da396077521f92b729ef7c429444dfcf03581f1448b77" +dependencies = [ + "hashbrown", + "linebender_resource_handle", + "memmap2", + "parlance", + "read-fonts", + "smallvec", +] + +[[package]] +name = "harfrust" +version = "0.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c03d949a14aa089bbb282f7dd76a498a7f684428e4257202efc119ec010376f9" +dependencies = [ + "bitflags", + "bytemuck", + "core_maths", + "read-fonts", + "smallvec", +] + +[[package]] +name = "hashbrown" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" +dependencies = [ + "foldhash", +] + +[[package]] +name = "icu_collections" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fa68d21081c4a05d5a901a1c62add574c77048b6a1c67be3b50ce0b60d4ca513" +dependencies = [ + "displaydoc", + "potential_utf", + "utf8_iter", + "yoke", + "zerofrom", + "zerovec", +] + +[[package]] +name = "icu_locale_core" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d56e28588da92eee5c3201a6eff33fabdd49b62269c8938d4ff050ce4d900deb" +dependencies = [ + "displaydoc", + "litemap", + "serde", + "tinystr", + "writeable", + "zerovec", +] + +[[package]] +name = "icu_locale_fallback" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "251af8e57c9400e3eb58242fe5b8b1152b2a64fdf4cf632f923c38ccee6f2fa9" +dependencies = [ + "icu_locale_core", + "icu_locale_fallback_data", + "icu_provider", + "potential_utf", + "tinystr", + "zerovec", +] + +[[package]] +name = "icu_locale_fallback_data" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "decf2a22ec8fa68f1a0c1129a3f8583f8f8bc24e8b9ccbe98ead99f62a4dc3a8" + +[[package]] +name = "icu_normalizer" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "12f9cf5f235641ed274641dd81c3f28d870e276763d0797aeeab72317b1c646f" +dependencies = [ + "icu_collections", + "icu_normalizer_data", + "icu_properties", + "icu_provider", + "smallvec", + "zerovec", +] + +[[package]] +name = "icu_normalizer_data" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1563da1ed3e0b3bf3d74c9b85917ac9c56464d2f57242270c09c9e752f8021a0" + +[[package]] +name = "icu_properties" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e7ca276ad3145661a65914e6daf131ca5120cd3dcee8f8f3214b8875184a148" +dependencies = [ + "displaydoc", + "icu_collections", + "icu_locale_core", + "icu_properties_data", + "icu_provider", + "zerotrie", + "zerovec", +] + +[[package]] +name = "icu_properties_data" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e590f038c1464a96894fd6d10127e90a8be4509f56ff7ecef851b15cee0b7caa" + +[[package]] +name = "icu_provider" +version = "2.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d27bbb9d3abbefac45d55f647c9de1d44aafcd1186eb91879afef17c396c3e73" +dependencies = [ + "displaydoc", + "icu_locale_core", + "serde", + "stable_deref_trait", + "writeable", + "yoke", + "zerofrom", + "zerotrie", + "zerovec", +] + +[[package]] +name = "icu_segmenter" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "82d07aafccd67af15d02512a6adf5896fbc5ed00f2e99b471d2efa14016db3db" +dependencies = [ + "icu_collections", + "icu_locale_fallback", + "icu_provider", + "icu_segmenter_data", + "potential_utf", + "smallvec", + "utf8_iter", + "zerovec", +] + +[[package]] +name = "icu_segmenter_data" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae293c039020f9ec10710af98d29ce6aa2051486638b49c9a6409f3b4a9e98ad" + +[[package]] +name = "libc" +version = "0.2.186" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "68ab91017fe16c622486840e4c83c9a37afeff978bd239b5293d61ece587de66" + +[[package]] +name = "libm" +version = "0.2.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981" + +[[package]] +name = "linebender_resource_handle" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d4a5ff6bcca6c4867b1c4fd4ef63e4db7436ef363e0ad7531d1558856bae64f4" + +[[package]] +name = "litemap" +version = "0.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92daf443525c4cce67b150400bc2316076100ce0b3686209eb8cf3c31612e6f0" + +[[package]] +name = "memmap2" +version = "0.9.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d1219ed1b7f229ee7104d281dd01d6802fe28bb6e95d292942c4daacdeb798c0" +dependencies = [ + "libc", +] + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "parlance" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "73072a9470554c8e794778acece2312661218aaabb635600957d952cf01c716e" +dependencies = [ + "bytemuck", +] + +[[package]] +name = "parley_data" +version = "0.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c43b63f808f6cc8f4a3b07de0d62a977bddd2e0bb5c232bd9e93ba8ef92e5e4b" +dependencies = [ + "icu_collections", + "icu_properties", +] + +[[package]] +name = "parley_emoji" +version = "0.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9c4482d912d7671a7cd2089794f90ef3bb5f5f8c738230fb0fcd50fa020f0ed3" + +[[package]] +name = "parley_engine" +version = "0.12.0" +dependencies = [ + "fontique", + "harfrust", + "hashbrown", + "icu_locale_core", + "icu_normalizer", + "icu_properties", + "icu_segmenter", + "linebender_resource_handle", + "parlance", + "parley_data", + "parley_emoji", + "skrifa", +] + +[[package]] +name = "potential_utf" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0103b1cef7ec0cf76490e969665504990193874ea05c85ff9bab8b911d0a0564" +dependencies = [ + "serde_core", + "writeable", + "zerovec", +] + +[[package]] +name = "proc-macro2" +version = "1.0.106" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dfbc457d0c7a0759a614551b11a6409e5951f6c7537be1f1b7682b9ae9230368" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "read-fonts" +version = "0.41.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "046a7d674daf459825b32f5062056d6882db0d2f5a479fbd76ccfc870ac18709" +dependencies = [ + "bytemuck", + "core_maths", + "font-types", + "once_cell", +] + +[[package]] +name = "serde" +version = "1.0.228" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a8e94ea7f378bd32cbbd37198a4a91436180c5bb472411e48b5ec2e2124ae9e" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.228" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41d385c7d4ca58e59fc732af25c3983b67ac852c1a25000afe1175de458b67ad" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.228" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.118", +] + +[[package]] +name = "skrifa" +version = "0.44.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "819ab7d62b1d3e72d9d9dea5650bac30424f9111364bb94928dbf5ecad1baa68" +dependencies = [ + "bytemuck", + "core_maths", + "read-fonts", +] + +[[package]] +name = "smallvec" +version = "1.16.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9395f0f0eee849a9b707b2f06bb92a6a422090e2123bb2ef8e87a0e61892a8e" + +[[package]] +name = "stable_deref_trait" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" + +[[package]] +name = "syn" +version = "2.0.118" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1b9ae57f904213ebb649ce6895b8a66c66f0203b9319718f69a5612a065b1422" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "3.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8593e8e72159ed2257d083c7a454a85cbf854f37a0966d8d483aff8c8a3ebcee" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "synstructure" +version = "0.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "728a70f3dbaf5bab7f0c4b1ac8d7ae5ea60a4b5549c8a5914361c99147a709d2" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.118", +] + +[[package]] +name = "tinystr" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1e27c91459209c2986af3dcf603a5a74a4368754ce37414f59acc971167f643" +dependencies = [ + "displaydoc", + "serde_core", + "zerovec", +] + +[[package]] +name = "unicode-ident" +version = "1.0.24" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75" + +[[package]] +name = "utf8_iter" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be" + +[[package]] +name = "writeable" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc" + +[[package]] +name = "yoke" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "709fe23a0424b6a435d82152b1bd3fdfb0833487d5fa90d05d42762a9891fef5" +dependencies = [ + "stable_deref_trait", + "yoke-derive", + "zerofrom", +] + +[[package]] +name = "yoke-derive" +version = "0.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "de844c262c8848816172cef550288e7dc6c7b7814b4ee56b3e1553f275f1858e" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.118", + "synstructure", +] + +[[package]] +name = "zerofrom" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272" +dependencies = [ + "zerofrom-derive", +] + +[[package]] +name = "zerofrom-derive" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "11532158c46691caf0f2593ea8358fed6bbf68a0315e80aae9bd41fbade684a1" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.118", + "synstructure", +] + +[[package]] +name = "zerotrie" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ea269c3bd32f0a32c321907a2ae912ba6f4649bb0fc764a15627e99a7095a3f" +dependencies = [ + "displaydoc", + "yoke", + "zerofrom", + "zerovec", +] + +[[package]] +name = "zerovec" +version = "0.11.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb0464e17806c1d976d5cba29399c7f08e516e279e2ba493f63123b5fca67dd8" +dependencies = [ + "serde", + "yoke", + "zerofrom", + "zerovec-derive", +] + +[[package]] +name = "zerovec-derive" +version = "0.11.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "34df6fc39dbd26ddc9c10e6a2984476e13acce22e64e4487636ef494369225da" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.6", +] diff --git a/app/vendor/rune/vendor/parley_engine/Cargo.toml b/app/vendor/rune/vendor/parley_engine/Cargo.toml new file mode 100644 index 0000000..c09da2b --- /dev/null +++ b/app/vendor/rune/vendor/parley_engine/Cargo.toml @@ -0,0 +1,162 @@ +# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO +# +# When uploading crates to the registry Cargo will automatically +# "normalize" Cargo.toml files for maximal compatibility +# with all versions of Cargo and also rewrite `path` dependencies +# to registry (e.g., crates.io) dependencies. +# +# If you are reading this file be aware that the original Cargo.toml +# will likely look very different (and much more reasonable). +# See Cargo.toml.orig for the original contents. + +[package] +edition = "2024" +rust-version = "1.88" +name = "parley_engine" +version = "0.12.0" +build = false +autolib = false +autobins = false +autoexamples = false +autotests = false +autobenches = false +description = "Parley Engine provides low level APIs for implementing text layout." +readme = "README.md" +keywords = [ + "text", + "layout", +] +categories = [ + "gui", + "graphics", +] +license = "Apache-2.0 OR MIT" +repository = "https://github.com/linebender/parley" +resolver = "2" + +[package.metadata.docs.rs] +all-features = true + +[features] +bytemuck = [ + "fontique/bytemuck", + "parlance/bytemuck", +] +complex-scripts = [] +line-dictionaries = [] +default = ["std"] +libm = [ + "fontique/libm", + "harfrust/libm", + "skrifa/libm", +] +std = [ + "fontique/std", + "harfrust/std", + "parlance/std", + "parley_emoji/std", + "skrifa/std", +] + +[lib] +name = "parley_engine" +path = "src/lib.rs" + +[dependencies.fontique] +version = "0.12.0" +default-features = false + +[dependencies.harfrust] +version = "0.12.0" +default-features = false + +[dependencies.hashbrown] +version = "0.17.1" +features = [ + "default-hasher", + "raw-entry", +] +default-features = false + +[dependencies.icu_locale_core] +version = "2.3.0" +default-features = false + +[dependencies.icu_normalizer] +version = "2.3.0" +features = ["compiled_data"] +default-features = false + +[dependencies.icu_properties] +version = "2.3.0" +features = ["compiled_data"] +default-features = false + +[dependencies.icu_segmenter] +version = "2.3.0" +features = ["compiled_data"] +default-features = false + +[dependencies.linebender_resource_handle] +version = "0.1.1" +default-features = false + +[dependencies.parlance] +version = "0.1.1" +default-features = false + +[dependencies.parley_data] +version = "0.12.0" +features = ["baked"] +default-features = false + +[dependencies.parley_emoji] +version = "0.12.0" +default-features = false + +[dependencies.skrifa] +version = "0.44.0" +default-features = false + +[lints.clippy] +allow_attributes_without_reason = "warn" +cargo_common_metadata = "warn" +cast_possible_truncation = "warn" +collection_is_never_read = "warn" +dbg_macro = "warn" +debug_assert_with_mut_call = "warn" +default_trait_access = "warn" +doc_markdown = "warn" +fn_to_numeric_cast_any = "warn" +infinite_loop = "warn" +large_stack_arrays = "warn" +mismatching_type_param_order = "warn" +missing_assert_message = "warn" +missing_fields_in_debug = "warn" +negative_feature_names = "warn" +redundant_feature_names = "warn" +same_functions_in_if_condition = "warn" +semicolon_if_nothing_returned = "warn" +should_panic_without_expect = "warn" +todo = "warn" +too_many_arguments = "allow" +unseparated_literal_suffix = "warn" +use_self = "warn" +wildcard_dependencies = "warn" + +[lints.rust] +elided_lifetimes_in_paths = "warn" +keyword_idents_2024 = "forbid" +missing_debug_implementations = "warn" +missing_docs = "warn" +non_ascii_idents = "forbid" +non_local_definitions = "forbid" +trivial_numeric_casts = "warn" +unnameable_types = "warn" +unreachable_pub = "warn" +unsafe_code = "deny" +unsafe_op_in_unsafe_fn = "forbid" +unused_import_braces = "warn" +unused_lifetimes = "warn" +unused_macro_rules = "warn" +unused_qualifications = "warn" diff --git a/app/vendor/rune/vendor/parley_engine/Cargo.toml.orig b/app/vendor/rune/vendor/parley_engine/Cargo.toml.orig new file mode 100644 index 0000000..5039911 --- /dev/null +++ b/app/vendor/rune/vendor/parley_engine/Cargo.toml.orig @@ -0,0 +1,40 @@ +[package] +name = "parley_engine" +version.workspace = true +description = "Parley Engine provides low level APIs for implementing text layout." +keywords = ["text", "layout"] +categories = ["gui", "graphics"] +edition.workspace = true +rust-version.workspace = true +license.workspace = true +repository.workspace = true + +[package.metadata.docs.rs] +all-features = true + +[features] +default = ["std"] +std = ["fontique/std", "harfrust/std", "parlance/std", "parley_emoji/std", "skrifa/std"] +libm = ["fontique/libm", "harfrust/libm", "skrifa/libm"] +bytemuck = ["fontique/bytemuck", "parlance/bytemuck"] +# Enables dictionary-based line and word breaking for complex scripts (CJK, Thai, Khmer, Lao, Myanmar). +# When disabled, a lightweight segmenter is used that falls back to character-level breaks for those scripts. +complex-scripts = [] + +[dependencies] +fontique = { workspace = true } +parlance = { workspace = true } +parley_data = { workspace = true, features = ["baked"] } +parley_emoji = { workspace = true } + +harfrust = { workspace = true } +hashbrown = { workspace = true } +icu_locale_core = { workspace = true } +icu_normalizer = { workspace = true, features = ["compiled_data"] } +icu_properties = { workspace = true, features = ["compiled_data"] } +icu_segmenter = { workspace = true, features = ["compiled_data"] } +linebender_resource_handle = { workspace = true } +skrifa = { workspace = true } + +[lints] +workspace = true diff --git a/app/vendor/rune/vendor/parley_engine/LICENSE-APACHE b/app/vendor/rune/vendor/parley_engine/LICENSE-APACHE new file mode 100644 index 0000000..1b5ec8b --- /dev/null +++ b/app/vendor/rune/vendor/parley_engine/LICENSE-APACHE @@ -0,0 +1,176 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS diff --git a/app/vendor/rune/vendor/parley_engine/LICENSE-MIT b/app/vendor/rune/vendor/parley_engine/LICENSE-MIT new file mode 100644 index 0000000..ba1df1d --- /dev/null +++ b/app/vendor/rune/vendor/parley_engine/LICENSE-MIT @@ -0,0 +1,25 @@ +Copyright 2025 the Parley Authors + +Permission is hereby granted, free of charge, to any +person obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the +Software without restriction, including without +limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software +is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice +shall be included in all copies or substantial portions +of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT +SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. diff --git a/app/vendor/rune/vendor/parley_engine/README.md b/app/vendor/rune/vendor/parley_engine/README.md new file mode 100644 index 0000000..6d65005 --- /dev/null +++ b/app/vendor/rune/vendor/parley_engine/README.md @@ -0,0 +1,137 @@ +<div align="center"> + +# Parley Engine + +**Low level text layout** + +[![Latest published version.](https://img.shields.io/crates/v/parley_engine.svg)](https://crates.io/crates/parley_engine) +[![Documentation build status.](https://img.shields.io/docsrs/parley_engine.svg)](https://docs.rs/parley_engine) +[![Apache 2.0 or MIT license.](https://img.shields.io/badge/license-Apache--2.0_OR_MIT-blue.svg)](#license) +\ +[![Linebender Zulip chat.](https://img.shields.io/badge/Linebender-%23parley-blue?logo=Zulip)](https://xi.zulipchat.com/#narrow/channel/205635-parley) +[![GitHub Actions CI status.](https://img.shields.io/github/actions/workflow/status/linebender/parley/ci.yml?logo=github&label=CI)](https://github.com/linebender/parley/actions) +[![Dependency staleness status.](https://deps.rs/crate/parley_engine/latest/status.svg)](https://deps.rs/crate/parley_engine) + +</div> + +<!-- We use cargo-rdme to update the README with the contents of lib.rs. +To edit the following section, update it in lib.rs, then run: +cargo rdme --workspace-project=parley_engine --heading-base-level=0 +Full documentation at https://github.com/orium/cargo-rdme --> + +<!-- Intra-doc links used in lib.rs should be evaluated here. +See https://linebender.org/blog/doc-include/ for related discussion. --> + +<!-- cargo-rdme start --> + +Parley Engine provides low level APIs for shaping paragraphs of text. + +## Usage + +Use [`Analyzer`], [`Analysis`], [`Shaper`] and [`ShapedText`] to shape a paragraph of text into +glyphs. Correct reshaping of lines is in progress; in the meantime you can break text at +[`Atom`] or [`ShapedCluster`][crate::shape::ShapedCluster] boundaries. + +Text analysis is performed before shaping, and the same source string must be passed to each +stage. + +Higher-level users may prefer using [`parley`][parley], which uses this crate and implements +layout and styling. + +```rust +let mut analysis = Analysis::default(); +let mut analyzer = Analyzer::default(); +let mut shaped_text = ShapedText::default(); +let mut shaper = Shaper::default(); + +let text = "The quick brown ثعلب jumps over the lazy dog."; +let char_count = text.chars().count(); +let char_style_indices = vec![0; char_count]; + +analyzer.analyze(text, &AnalysisOptions::default(), &mut analysis); +shaper.shape_text( + text, + &analysis, + &char_style_indices, + [Item { + char_end: char_count.try_into().unwrap(), + options: ShapeOptions { + font_size: 16.0, + language: None, + features: &[], + variations: &[], + }, + }], + select_font, // Selects fonts covering each cluster. + &mut shaped_text, +); + +for (run_idx, run) in shaped_text.runs().iter().enumerate() { + let slice = shaped_text.run_slice(run_idx as u32); + // You can, for example, measure grapheme advances for hit-testing or + // placing carets. + for atom in slice.atoms_start() { + for grapheme in atom.graphemes_start() { + std::dbg!(grapheme); + } + } + + // Or get glyphs for rendering (for simplicity, this iterates clusters in + // logical order, but for rendering you'd want to reorder runs and clusters + // according to their `run.bidi_level`). + for cluster in slice.shaped_clusters_range() { + for glyph in slice.shaped_cluster_glyphs(cluster) { + std::dbg!(glyph); + } + } +} +``` + +## Features + +- `std` (enabled by default): This is currently unused and is provided for forward compatibility. +- `bytemuck`: Forwarded to [`parlance`], which then implements traits from `bytemuck` on its + types. + +[parley]: https://docs.rs/parley + +<!-- cargo-rdme end --> + +## Minimum supported Rust Version (MSRV) + +This version of Parley Engine has been verified to compile with **Rust 1.88** and later. + +Future versions of Parley Engine might increase the Rust version requirement. +It will not be treated as a breaking change and as such can even happen with small patch releases. + +<details> +<summary>Click here if compiling fails.</summary> + +As time has passed, some of Parley Engine's dependencies could have released versions with a higher Rust requirement. +If you encounter a compilation issue due to a dependency and don't want to upgrade your Rust toolchain, then you could downgrade the dependency. + +```sh +# Use the problematic dependency's name and version +cargo update -p package_name --precise 0.1.1 +``` +</details> + +## Community + +Discussion of Parley Engine development happens in the [Linebender Zulip](https://xi.zulipchat.com/), specifically the [#parley channel](https://xi.zulipchat.com/#narrow/channel/205635-parley). +All public content can be read without logging in. + +Contributions are welcome by pull request. The [Rust code of conduct] applies. + +Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache 2.0 license, shall be licensed as noted in the [License](#license) section, without any additional terms or conditions. + +## License + +Licensed under either of + +- Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or <http://www.apache.org/licenses/LICENSE-2.0>) +- MIT license ([LICENSE-MIT](LICENSE-MIT) or <http://opensource.org/licenses/MIT>) + +at your option. + +[Rust code of conduct]: https://www.rust-lang.org/policies/code-of-conduct diff --git a/app/vendor/rune/vendor/parley_engine/src/analysis.rs b/app/vendor/rune/vendor/parley_engine/src/analysis.rs new file mode 100644 index 0000000..31cf0dc --- /dev/null +++ b/app/vendor/rune/vendor/parley_engine/src/analysis.rs @@ -0,0 +1,934 @@ +// Copyright 2025 the Parley Authors +// SPDX-License-Identifier: Apache-2.0 OR MIT + +//! Text analysis. +//! +//! Analysis is performed prior to shaping and is independent of fonts, turning a `&str` into +//! [`Analysis`]. + +use alloc::vec::Vec; +use core::ops::Range; + +use icu_locale_core::{LanguageIdentifier, langid}; +use icu_normalizer::properties::{ + CanonicalComposition, CanonicalCompositionBorrowed, CanonicalDecomposition, + CanonicalDecompositionBorrowed, +}; +use icu_properties::props::{BidiMirroringGlyph, GeneralCategory, GraphemeClusterBreak, Script}; +use icu_properties::{ + CodePointMapData, CodePointMapDataBorrowed, PropertyNamesShort, PropertyNamesShortBorrowed, +}; +use icu_segmenter::options::{ + LineBreakOptions, LineBreakStrictness, LineBreakWordOption, WordBreakInvariantOptions, +}; +use icu_segmenter::{ + GraphemeClusterSegmenter, GraphemeClusterSegmenterBorrowed, LineSegmenter, + LineSegmenterBorrowed, WordSegmenter, WordSegmenterBorrowed, +}; +use parlance::{BaseDirection, BidiLevel, LineBreak, WordBreak}; +use parley_data::Properties; + +use crate::bidi; +use crate::break_overrides::LineBreakContext; +use crate::{AnalysisOptions, Analyzer, LineBreakConfig}; + +/// The result of [`Analyzer::analyze`]. +#[derive(Debug, Default)] +pub struct Analysis { + /// Info for each character. + pub(crate) info: Vec<CharInfo>, + + /// Bidi level for each character, parallel to `info`. + /// + /// Empty if the text is all LTR. + pub(crate) levels: Vec<BidiLevel>, + + /// The base bidi level of the paragraph of text. + pub(crate) paragraph_level: BidiLevel, +} + +impl Analysis { + /// Create a reusable [`Analysis`]. + /// + /// Pass this to [`Analyzer::analyze`]. + #[inline] + pub fn new() -> Self { + Self::default() + } + + /// Clear the result while retaining capacity. + pub(crate) fn clear(&mut self) { + self.info.clear(); + self.levels.clear(); + self.paragraph_level = BidiLevel::new(0); + } + + /// The per-character info in source order. + #[inline(always)] + pub fn char_info(&self) -> &[CharInfo] { + &self.info + } + + /// The bidi level for each character, parallel to [`Self::char_info`]. + /// + /// Empty when the whole paragraph is left-to-right. + #[inline(always)] + pub fn bidi_levels(&self) -> &[BidiLevel] { + &self.levels + } + + /// The base bidi level of the paragraph of text. + #[inline(always)] + pub fn paragraph_level(&self) -> BidiLevel { + self.paragraph_level + } +} + +// TODO: Make `pub(crate)` once `parley_engine` owns shaping. +#[doc(hidden)] +#[expect(missing_debug_implementations, reason = "Will become private")] +pub struct AnalysisDataSources; + +impl AnalysisDataSources { + #[expect(clippy::new_without_default, reason = "Will become private")] + pub fn new() -> Self { + Self + } + + #[inline(always)] + pub fn properties(&self, c: char) -> Properties { + Properties::get(c) + } + + #[inline(always)] + pub fn grapheme_segmenter(&self) -> GraphemeClusterSegmenterBorrowed<'_> { + const { GraphemeClusterSegmenter::new() } + } + + #[inline(always)] + fn word_segmenter(&self) -> WordSegmenterBorrowed<'static> { + #[cfg(feature = "complex-scripts")] + { + WordSegmenter::new_dictionary(WordBreakInvariantOptions::default()) + } + #[cfg(not(feature = "complex-scripts"))] + { + const { WordSegmenter::new_for_non_complex_scripts(WordBreakInvariantOptions::default()) } + } + } + + #[inline(always)] + fn line_segmenter(&self, key: SegmenterKey) -> LineSegmenterBorrowed<'static> { + // We use Japanese arbitrarily; see `SegmenterKey::ja_zh`. + static JA: LanguageIdentifier = langid!("ja"); + + let mut opt = LineBreakOptions::default(); + opt.word_option = Some(key.word_option); + opt.strictness = Some(key.strictness); + opt.content_locale = key.ja_zh.then_some(&JA); + line_segmenter_impl(opt) + } + + #[inline(always)] + pub fn composing_normalizer(&self) -> CanonicalCompositionBorrowed<'_> { + const { CanonicalComposition::new() } + } + + #[inline(always)] + pub fn decomposing_normalizer(&self) -> CanonicalDecompositionBorrowed<'_> { + const { CanonicalDecomposition::new() } + } + + #[inline(always)] + pub fn script_short_name(&self) -> PropertyNamesShortBorrowed<'static, Script> { + PropertyNamesShort::new() + } + + #[inline(always)] + fn brackets(&self) -> CodePointMapDataBorrowed<'_, BidiMirroringGlyph> { + const { CodePointMapData::new() } + } +} + +/// The segmenters an [`Analyzer`] has made, kept for its next texts (Rune: +/// vendor/parley_engine.patch). Making one looks up its rule data and, with `complex-scripts`, +/// loads the dictionaries; they're `'static` and `Copy`, so a kept one is the same value a new +/// one would be. +#[derive(Default)] +pub(crate) struct Segmenters { + line: Vec<(SegmenterKey, LineSegmenterBorrowed<'static>)>, + word: Option<WordSegmenterBorrowed<'static>>, +} + +impl Segmenters { + fn line(&mut self, key: SegmenterKey) -> LineSegmenterBorrowed<'static> { + if let Some((_, segmenter)) = self.line.iter().find(|(k, _)| *k == key) { + return *segmenter; + } + let segmenter = AnalysisDataSources::new().line_segmenter(key); + self.line.push((key, segmenter)); + segmenter + } + + fn word(&mut self) -> WordSegmenterBorrowed<'static> { + *self + .word + .get_or_insert_with(|| AnalysisDataSources::new().word_segmenter()) + } +} + +// `line-dictionaries` (Rune: vendor/parley_engine.patch): the line segmenter's Thai, Lao, Khmer and +// Burmese dictionaries without the word segmenter's (Chinese and Japanese words come from the host's +// `dictionary` segmenter instead). +#[cfg(any(feature = "complex-scripts", feature = "line-dictionaries"))] +#[inline(always)] +fn line_segmenter_impl(opt: LineBreakOptions<'_>) -> LineSegmenterBorrowed<'static> { + LineSegmenter::new_dictionary(opt) +} + +#[cfg(not(any(feature = "complex-scripts", feature = "line-dictionaries")))] +#[inline(always)] +fn line_segmenter_impl(opt: LineBreakOptions<'_>) -> LineSegmenterBorrowed<'static> { + LineSegmenter::new_for_non_complex_scripts(opt) +} + +/// The line segmenter configuration for a [`LineBreakConfig`]. +/// +/// Configurations which result in the same segmentation map to the same key. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +struct SegmenterKey { + word_option: LineBreakWordOption, + strictness: LineBreakStrictness, + /// See [`LineBreakConfig::language`]; the only languages which impact segmentation are + /// Chinese and Japanese. These impact it in the same way, and only under + /// [`LineBreak::Normal`] and [`LineBreak::Loose`], so we only track whether one of them + /// applies. + ja_zh: bool, +} + +impl SegmenterKey { + const DEFAULT: Self = Self { + word_option: LineBreakWordOption::Normal, + strictness: LineBreakStrictness::Strict, + ja_zh: false, + }; + + fn new(config: &LineBreakConfig) -> Self { + let strictness = match config.line_break { + LineBreak::Strict => LineBreakStrictness::Strict, + LineBreak::Normal => LineBreakStrictness::Normal, + LineBreak::Loose => LineBreakStrictness::Loose, + // We add opportunities per grapheme ourselves. + LineBreak::Anywhere => return Self::DEFAULT, + }; + let word_option = match config.word_break { + WordBreak::Normal => LineBreakWordOption::Normal, + WordBreak::BreakAll => LineBreakWordOption::BreakAll, + WordBreak::KeepAll => LineBreakWordOption::KeepAll, + }; + let ja_zh = match strictness { + LineBreakStrictness::Normal | LineBreakStrictness::Loose => config + .language + .is_some_and(|language| matches!(language.language(), "ja" | "zh")), + _ => false, + }; + Self { + word_option, + strictness, + ja_zh, + } + } +} + +/// Per-character analysis info. +#[derive(Copy, Clone, Debug, PartialEq, Eq)] +pub struct CharInfo { + /// The Unicode script this character belongs to. + pub script: Script, + flags: u16, +} + +impl CharInfo { + const VARIATION_SELECTOR_SHIFT: u16 = 0; + const REGION_INDICATOR_SHIFT: u16 = 1; + const CONTROL_SHIFT: u16 = 2; + const EMOJI_OR_PICTOGRAPH_SHIFT: u16 = 3; + const CONTRIBUTES_TO_SHAPING_SHIFT: u16 = 4; + const FORCE_NORMALIZE_SHIFT: u16 = 5; + const GRAPHEME_START_SHIFT: u16 = 6; + const WORD_BOUNDARY_SHIFT: u8 = 7; + const SOFT_WRAP_OPPORTUNITY_SHIFT: u16 = 8; + const EMOJI_SHIFT: u16 = 9; + const EMOJI_PRESENTATION_SHIFT: u16 = 10; + const EMOJI_MODIFIER_SHIFT: u16 = 11; + const EMOJI_MODIFIER_BASE_SHIFT: u16 = 12; + + const VARIATION_SELECTOR_MASK: u16 = 1 << Self::VARIATION_SELECTOR_SHIFT; + const REGION_INDICATOR_MASK: u16 = 1 << Self::REGION_INDICATOR_SHIFT; + const CONTROL_MASK: u16 = 1 << Self::CONTROL_SHIFT; + const EMOJI_OR_PICTOGRAPH_MASK: u16 = 1 << Self::EMOJI_OR_PICTOGRAPH_SHIFT; + const CONTRIBUTES_TO_SHAPING_MASK: u16 = 1 << Self::CONTRIBUTES_TO_SHAPING_SHIFT; + const FORCE_NORMALIZE_MASK: u16 = 1 << Self::FORCE_NORMALIZE_SHIFT; + const GRAPHEME_START_MASK: u16 = 1 << Self::GRAPHEME_START_SHIFT; + const WORD_BOUNDARY_MASK: u16 = 1 << Self::WORD_BOUNDARY_SHIFT; + const SOFT_WRAP_OPPORTUNITY_MASK: u16 = 1 << Self::SOFT_WRAP_OPPORTUNITY_SHIFT; + const EMOJI_MASK: u16 = 1 << Self::EMOJI_SHIFT; + const EMOJI_PRESENTATION_MASK: u16 = 1 << Self::EMOJI_PRESENTATION_SHIFT; + const EMOJI_MODIFIER_MASK: u16 = 1 << Self::EMOJI_MODIFIER_SHIFT; + const EMOJI_MODIFIER_BASE_MASK: u16 = 1 << Self::EMOJI_MODIFIER_BASE_SHIFT; + + fn new( + script: Script, + is_variation_selector: bool, + is_region_indicator: bool, + is_control: bool, + is_emoji_or_pictograph: bool, + contributes_to_shaping: bool, + force_normalize: bool, + is_grapheme_start: bool, + is_word_boundary: bool, + is_soft_wrap_opportunity: bool, + is_emoji: bool, + is_emoji_presentation: bool, + is_emoji_modifier: bool, + is_emoji_modifier_base: bool, + ) -> Self { + Self { + script, + flags: (is_variation_selector as u16) << Self::VARIATION_SELECTOR_SHIFT + | (is_region_indicator as u16) << Self::REGION_INDICATOR_SHIFT + | (is_control as u16) << Self::CONTROL_SHIFT + | (is_emoji_or_pictograph as u16) << Self::EMOJI_OR_PICTOGRAPH_SHIFT + | (contributes_to_shaping as u16) << Self::CONTRIBUTES_TO_SHAPING_SHIFT + | (force_normalize as u16) << Self::FORCE_NORMALIZE_SHIFT + | (is_grapheme_start as u16) << Self::GRAPHEME_START_SHIFT + | (is_word_boundary as u16) << Self::WORD_BOUNDARY_SHIFT + | (is_soft_wrap_opportunity as u16) << Self::SOFT_WRAP_OPPORTUNITY_SHIFT + | (is_emoji as u16) << Self::EMOJI_SHIFT + | (is_emoji_presentation as u16) << Self::EMOJI_PRESENTATION_SHIFT + | (is_emoji_modifier as u16) << Self::EMOJI_MODIFIER_SHIFT + | (is_emoji_modifier_base as u16) << Self::EMOJI_MODIFIER_BASE_SHIFT, + } + } + + /// Whether this character is a variation selector. + #[inline(always)] + pub fn is_variation_selector(self) -> bool { + self.flags & Self::VARIATION_SELECTOR_MASK != 0 + } + + /// Whether this character is a regional indicator symbol. + #[inline(always)] + pub fn is_region_indicator(self) -> bool { + self.flags & Self::REGION_INDICATOR_MASK != 0 + } + + /// Whether this character is a control character. + #[inline(always)] + pub fn is_control(self) -> bool { + self.flags & Self::CONTROL_MASK != 0 + } + + /// Returns whether the character has either of the `Emoji` or`Extended_Pictographic` properties. + /// + /// Parley Engine uses this to determine whether a character might be part of an Emoji, and so whether to do + /// more stringent checks. + /// + /// [UTS #51]: https://www.unicode.org/reports/tr51/tr51-29.html#Emoji_Properties + #[inline(always)] + pub fn is_emoji_or_pictograph(self) -> bool { + self.flags & Self::EMOJI_OR_PICTOGRAPH_MASK != 0 + } + + /// Whether this character has the `Emoji` property ([UTS #51][]). + /// + /// [UTS #51]: https://www.unicode.org/reports/tr51/tr51-29.html#Emoji_Properties + #[inline(always)] + pub fn is_emoji(self) -> bool { + self.flags & Self::EMOJI_MASK != 0 + } + + /// Whether this character has the `Emoji_Presentation` property ([UTS #51][]), i.e. it is + /// displayed as an emoji by default. + /// + /// [UTS #51]: https://www.unicode.org/reports/tr51/tr51-29.html#Emoji_Properties + #[inline(always)] + pub fn is_emoji_presentation(self) -> bool { + self.flags & Self::EMOJI_PRESENTATION_MASK != 0 + } + + /// Whether this character has the `Emoji_Modifier` property ([UTS #51][]), i.e. it is a + /// skin tone modifier. + /// + /// [UTS #51]: https://www.unicode.org/reports/tr51/tr51-29.html#Emoji_Properties + #[inline(always)] + pub fn is_emoji_modifier(self) -> bool { + self.flags & Self::EMOJI_MODIFIER_MASK != 0 + } + + /// Whether this character has the `Emoji_Modifier_Base` property ([UTS #51][]), i.e. it can + /// be followed by a skin tone modifier. + /// + /// [UTS #51]: https://www.unicode.org/reports/tr51/tr51-29.html#Emoji_Properties + #[inline(always)] + pub fn is_emoji_modifier_base(self) -> bool { + self.flags & Self::EMOJI_MODIFIER_BASE_MASK != 0 + } + + /// Whether this character contributes glyphs to shaping (`false` for control characters and + /// most format characters). + #[inline(always)] + pub fn contributes_to_shaping(self) -> bool { + self.flags & Self::CONTRIBUTES_TO_SHAPING_MASK != 0 + } + + /// Whether this character should be normalized before glyph mapping during shaping. + #[inline(always)] + pub fn force_normalize(self) -> bool { + self.flags & Self::FORCE_NORMALIZE_MASK != 0 + } + + /// Whether this character begins a grapheme cluster ([UAX #29 § 3][graphemes]). + /// + /// [graphemes]: https://www.unicode.org/reports/tr29/#Grapheme_Cluster_Boundaries + #[inline(always)] + pub fn is_grapheme_start(self) -> bool { + self.flags & Self::GRAPHEME_START_MASK != 0 + } + + /// Whether there is a word boundary before this character ([UAX #29 § 4][words]). + /// + /// [words]: https://www.unicode.org/reports/tr29/#Word_Boundaries + #[inline(always)] + pub fn is_word_boundary(self) -> bool { + self.flags & Self::WORD_BOUNDARY_MASK != 0 + } + + /// Whether there is a soft wrap opportunity before this character ([UAX #14][line-breaking]). + /// + /// Note mandatory breaks (like `\n`) are encoded as [`Whitespace`](crate::shape::Whitespace). + /// + /// [line-breaking]: https://www.unicode.org/reports/tr14/ + #[inline(always)] + pub fn is_soft_wrap_opportunity(self) -> bool { + self.flags & Self::SOFT_WRAP_OPPORTUNITY_MASK != 0 + } +} + +pub(crate) fn analyze_text( + analyzer: &mut Analyzer, + text: &str, + options: &AnalysisOptions<'_>, + analysis: &mut Analysis, +) { + /// Turns the sparse, sorted, non-overlapping `options.line_break` into a contiguous sequence of + /// `(range, segmenter key)` segments covering all of `text`. + /// + /// Any region not covered by an override takes the default configuration. + struct DenseLineBreaks<'a> { + line_break: &'a [(Range<usize>, LineBreakConfig)], + /// Index of the next word break to emit. + next: usize, + /// Start of the next segment to emit. + cursor: usize, + text_len: usize, + } + + impl<'a> DenseLineBreaks<'a> { + fn new(line_break: &'a [(Range<usize>, LineBreakConfig)], text_len: usize) -> Self { + Self { + line_break, + next: 0, + cursor: 0, + text_len, + } + } + } + + impl Iterator for DenseLineBreaks<'_> { + type Item = (Range<usize>, SegmenterKey); + + fn next(&mut self) -> Option<Self::Item> { + if self.cursor >= self.text_len { + return None; + } + + // Ignore empty ranges. + while self + .line_break + .get(self.next) + .is_some_and(|(range, _)| range.is_empty()) + { + self.next += 1; + } + + match self.line_break.get(self.next) { + // A gap before the next override: fill it with the default up to its start. + Some((range, _)) if self.cursor < range.start => { + let segment = self.cursor..range.start; + self.cursor = range.start; + Some((segment, SegmenterKey::DEFAULT)) + } + // At the next override: emit it. + Some((range, config)) => { + self.cursor = range.end; + self.next += 1; + Some((range.start..range.end, SegmenterKey::new(config))) + } + // No overrides remain: fill the default to the end. + None => { + let segment = self.cursor..self.text_len; + self.cursor = self.text_len; + Some((segment, SegmenterKey::DEFAULT)) + } + } + } + } + + struct LineBreakSegmentIter<'a, I: Iterator> { + text: &'a str, + segments: I, + char_indices: core::str::CharIndices<'a>, + current_char: (usize, char), + building_range_start: usize, + previous_key: SegmenterKey, + done: bool, + } + + impl<'a, I> LineBreakSegmentIter<'a, I> + where + I: Iterator<Item = (Range<usize>, SegmenterKey)>, + { + fn new(text: &'a str, segments: I, first_segment: (Range<usize>, SegmenterKey)) -> Self { + let mut char_indices = text.char_indices(); + let current_char_len = char_indices.next().unwrap(); + + Self { + text, + segments, + char_indices, + current_char: current_char_len, + building_range_start: first_segment.0.start, + previous_key: first_segment.1, + done: false, + } + } + } + + impl<'a, I> Iterator for LineBreakSegmentIter<'a, I> + where + I: Iterator<Item = (Range<usize>, SegmenterKey)>, + { + type Item = (&'a str, SegmenterKey, bool); + + fn next(&mut self) -> Option<Self::Item> { + if self.done { + return None; + } + + for (range, key) in self.segments.by_ref() { + assert!(range.start < range.end, "Segments must not be empty"); + + let style_start_index = range.start; + let mut prev_char_index = self.current_char; + + // Find the character at the style boundary. + while self.current_char.0 < style_start_index { + prev_char_index = self.current_char; + self.current_char = self.char_indices.next().unwrap(); + } + + let current_key = key; + if self.previous_key == current_key { + continue; + } + + // Produce one substring for each different segmenter key run + let prev_size = prev_char_index.1.len_utf8(); + let size = self.current_char.1.len_utf8(); + + let substring = &self.text[self.building_range_start..style_start_index + size]; + let result_style = self.previous_key; + + self.building_range_start = style_start_index - prev_size; + self.previous_key = current_key; + + return Some((substring, result_style, false)); + } + + // Final segment + self.done = true; + let last_substring = &self.text[self.building_range_start..self.text.len()]; + Some((last_substring, self.previous_key, true)) + } + } + + if text.is_empty() { + analyzer + .bidi + .resolve(core::iter::empty(), options.base_direction); + analysis.paragraph_level = analyzer.bidi.base_level(); + return; + } + + // Line boundaries (word break naming refers to the line boundary determination config). + // + // This breaks text into sequences with similar line boundary config (part of style + // information). If this config is consistent for all text, we use a fast path through this. + let mut segments = DenseLineBreaks::new(options.line_break, text.len()); + // `text` is non-empty (checked above), so there is always at least one segment. + let first_segment = segments.next().unwrap(); + let contiguous_substrings = LineBreakSegmentIter::new(text, segments, first_segment); + + let mut global_offset = 0; + let mut line_boundary_positions: Vec<usize> = Vec::new(); + + let data_sources = AnalysisDataSources::new(); + + for (substring_index, (substring, segmenter_key, last)) in contiguous_substrings.enumerate() { + // Fast path for text with a single segmenter configuration. + if substring_index == 0 && last { + let mut lb_iter = analyzer + .segmenters + .line(segmenter_key) + .segment_str(substring); + + let _first = lb_iter.next(); + let second = lb_iter.next(); + if second.is_none() { + continue; + } + let third = lb_iter.next(); + if third.is_none() { + continue; + } + + let iter = [second.unwrap(), third.unwrap()].into_iter().chain(lb_iter); + + line_boundary_positions.extend(iter); + // Remove the unnecessary boundary at the end added by ICU4X. + line_boundary_positions.pop(); + break; + } + + let line_boundaries_iter = analyzer + .segmenters + .line(segmenter_key) + .segment_str(substring); + + let mut substring_chars = substring.chars(); + if substring_index != 0 { + global_offset -= substring_chars.next().unwrap().len_utf8(); + } + // There will always be at least two characters if we are not taking the fast path for + // a single word break style substring. + let last_len = substring_chars.next_back().unwrap().len_utf8(); + + // Mark line boundaries (overriding word boundaries where present). + for (index, pos) in line_boundaries_iter.enumerate() { + // icu adds leading and trailing line boundaries, which we don't use. + if index == 0 || pos == substring.len() { + continue; + } + + // For all but the last substring, we ignore line boundaries caused by the last + // character, as this character is carried back from the next substring, and will be + // accounted for there. + if !last && pos == substring.len() - last_len { + continue; + } + line_boundary_positions.push(pos + global_offset); + } + + if !last { + global_offset += substring.len() - last_len; + } + } + + // Words, and in Thai, Lao, Khmer and Burmese line breaks, that the host's dictionary finds + // (`dictionary`; Rune: vendor/parley_engine.patch). + let mut dictionary = crate::dictionary::Words::of(text, |c| data_sources.properties(c)); + let before = line_boundary_positions.len(); + line_boundary_positions.extend(dictionary.line_breaks()); + if line_boundary_positions.len() > before { + line_boundary_positions.sort_unstable(); + line_boundary_positions.dedup(); + } + + // Collect boundary byte positions compactly + let mut wb_iter = analyzer.segmenters.word().segment_str(text).peekable(); + let mut gb_iter = data_sources + .grapheme_segmenter() + .segment_str(text) + .peekable(); + + // Merge boundaries - line takes precedence over word + let mut lb_iter = line_boundary_positions.iter().peekable(); + let mut prev_char = None; + let mut prev_prev_char = None; + // Whether the preceding character is a mandatory break. + let mut prev_is_mandatory_linebreak = false; + // Whether the preceding character is a break-space, i.e. a space, tab or ideographic space in + // a `break_spaces` range. + let mut prev_is_break_space = false; + let mut break_spaces_iter = options.break_spaces.iter().peekable(); + let mut break_anywhere_iter = options + .line_break + .iter() + .filter(|(_, config)| config.line_break == LineBreak::Anywhere) + .map(|(range, _)| range) + .peekable(); + let boundary_iter = text.char_indices().map(|(byte_pos, ch)| { + // advance any stale word boundary positions + while let Some(&w) = wb_iter.peek() { + if w < byte_pos { + _ = wb_iter.next(); + } else { + break; + } + } + // advance any stale grapheme boundary positions + while let Some(&g) = gb_iter.peek() { + if g < byte_pos { + _ = gb_iter.next(); + } else { + break; + } + } + // advance any stale line boundary positions + while let Some(&l) = lb_iter.peek() { + if *l < byte_pos { + _ = lb_iter.next(); + } else { + break; + } + } + + let mut is_word = false; + if let Some(&w) = wb_iter.peek() + && w == byte_pos + { + is_word = true; + _ = wb_iter.next(); + } + let mut is_grapheme_start = false; + if let Some(&g) = gb_iter.peek() + && g == byte_pos + { + is_grapheme_start = true; + _ = gb_iter.next(); + } + let properties = data_sources.properties(ch); + + // For characters requiring a dictionary for deciding word boundaries, apply + // UAX #29 Rule WB999 in case there's no dictionary (because ICU4X does not); inside a run + // the host's dictionary segmented, its boundaries decide. + if let Some(bound) = dictionary.word_at(byte_pos) { + is_word = bound; + } else if !is_word + && is_grapheme_start + && properties.needs_dictionary_word_break() + && !has_word_dictionary(properties.script()) + { + is_word = true; + } + + let is_icu_line = if let Some(&l) = lb_iter.peek() + && *l == byte_pos + { + _ = lb_iter.next(); + true + } else { + false + }; + + // CSS Text 4 § 4.3.1 `break-spaces`: a soft wrap opportunity exists after each preserved + // space or tab (but never directly before a mandatory break, UAX #14 LB6). + while break_spaces_iter + .peek() + .is_some_and(|range| range.end <= byte_pos) + { + _ = break_spaces_iter.next(); + } + let after_break_space = prev_is_break_space; + prev_is_break_space = break_spaces_iter + .peek() + .is_some_and(|range| range.contains(&byte_pos)) + && matches!(ch, ' ' | '\t' | '\u{3000}'); + + while break_anywhere_iter + .peek() + .is_some_and(|range| range.end <= byte_pos) + { + _ = break_anywhere_iter.next(); + } + let is_break_anywhere = break_anywhere_iter + .peek() + .is_some_and(|range| range.contains(&byte_pos)); + + let is_mandatory_linebreak = properties.is_mandatory_linebreak(); + + // We never have a soft wrap opportunity before a mandatory break (following UAX #14 LB6), + // and we never have one right after a mandatory break: the mandatory break is handled + // separately. + let is_soft_wrap_opportunity = if is_mandatory_linebreak || prev_is_mandatory_linebreak { + false + } else { + let mut opportunity = if is_break_anywhere { + // `line-break: anywhere`: an opportunity around every grapheme. + prev_char.is_some() && is_grapheme_start + } else { + is_icu_line || after_break_space + }; + // Consumers can override soft wrap opportunities, except around a mandatory + // break. + if let (Some(prev), Some(lb_override)) = (prev_char, options.line_break_override) { + let forced = lb_override(LineBreakContext { + before_before: prev_prev_char, + before: prev, + after: ch, + }); + if let Some(forced) = forced { + opportunity = forced; + } + } + opportunity + }; + + prev_prev_char = prev_char; + prev_char = Some(ch); + prev_is_mandatory_linebreak = is_mandatory_linebreak; + + ( + is_soft_wrap_opportunity, + is_word, + is_grapheme_start, + ch, + properties, + ) + }); + + let mut needs_bidi_resolution = false; + + analysis.info.reserve(text.len()); + for (is_soft_wrap_opportunity, is_word, is_grapheme_start, ch, properties) in boundary_iter { + let script = properties.script(); + let grapheme_cluster_break = properties.grapheme_cluster_break(); + let bidi_class = properties.bidi_class(); + let general_category = properties.general_category(); + let is_emoji_or_pictograph = properties.is_emoji_or_pictograph(); + let is_variation_selector = properties.is_variation_selector(); + let is_region_indicator = properties.is_region_indicator(); + + let force_normalize = { + // "Extend" break chars should be normalized first, with two exceptions + if matches!(grapheme_cluster_break, GraphemeClusterBreak::Extend) && + ch as u32 != 0x200C && // Is not a Zero Width Non-Joiner && + !is_variation_selector + { + true + } else { + // All spacing mark break chars should be normalized first. + matches!(grapheme_cluster_break, GraphemeClusterBreak::SpacingMark) + } + }; + + needs_bidi_resolution |= bidi::needs_bidi_resolution(bidi_class); + + analysis.info.push(CharInfo::new( + script, + is_variation_selector, + is_region_indicator, + general_category == GeneralCategory::Control, + is_emoji_or_pictograph, + contributes_to_shaping(general_category, script), + force_normalize, + is_grapheme_start, + is_word, + is_soft_wrap_opportunity, + properties.is_emoji(), + properties.is_emoji_presentation(), + properties.is_emoji_modifier(), + properties.is_emoji_modifier_base(), + )); + } + + if needs_bidi_resolution || options.base_direction == BaseDirection::Rtl { + analyzer.bidi.resolve( + text.chars().map(|ch| { + let bidi_class = data_sources.properties(ch).bidi_class(); + // TODO: maybe extend Properties to u64 to fit BidiMirroringGlyph + let bracket = data_sources.brackets().get(ch); + (ch, (bidi_class, bracket)) + }), + options.base_direction, + ); + core::mem::swap(&mut analysis.levels, &mut analyzer.bidi.levels); + analysis.paragraph_level = analyzer.bidi.base_level(); + } +} + +/// All characters contribute to shaping except: +/// - Control characters +/// - Format characters, unless they use the "Inherited" script +#[inline(always)] +pub(crate) fn contributes_to_shaping(general_category: GeneralCategory, script: Script) -> bool { + if matches!( + general_category, + GeneralCategory::Control + | GeneralCategory::LineSeparator + | GeneralCategory::ParagraphSeparator + ) { + return false; + } + + !(general_category == GeneralCategory::Format && script != Script::Inherited) +} + +/// Whether ICU4X has a word-segmentation dictionary for this script. +/// +/// If it does not, we need to apply UAX #29 Rule WB999 manually, because ICU4X does not. +/// +/// This is approximate, because ICU4X actually decides based on a table of code point ranges: e.g., +/// some Han characters do not get a dictionary check. That's only a problem if there's a run of +/// repeated such characters, which is probably not too likely to be a problem in practice. +/// +/// If ICU4X does implement WB999 in the future, we can stop doing it manually (and this method can +/// be removed). +#[inline(always)] +fn has_word_dictionary(script: Script) -> bool { + cfg!(feature = "complex-scripts") + && matches!( + script, + Script::Han + | Script::Hiragana + | Script::Thai + | Script::Lao + | Script::Khmer + | Script::Myanmar + ) +} + +#[cfg(test)] +mod test { + use alloc::vec::Vec; + use icu_segmenter::WordSegmenter; + use icu_segmenter::options::WordBreakInvariantOptions; + + /// For some characters, determining word boundaries requires a dictionary lookup. + /// + /// Without dictionaries, ICU4X reports such runs as being a single word. But note + /// UAX #29 Rule WB999 says that, without a dictionary, there should be word boundaries. + /// + /// We do that patchup ourselves. Once this test starts failing, it's likely ICU4X now follows + /// that rule, and we can drop the patchup (the code calling [`super::has_word_dictionary`]). + /// Once that's the case, [`parley_data::Properties::needs_dictionary_word_break`] can also be + /// dropped. + #[test] + fn icu4x_word_segmentation_patchup_required() { + let segmenter = + WordSegmenter::new_for_non_complex_scripts(WordBreakInvariantOptions::default()); + let breaks: Vec<_> = segmenter.segment_str("中文文本测试").collect(); + assert_eq!(breaks, &[0, 18]); + } +} diff --git a/app/vendor/rune/vendor/parley_engine/src/analyzer.rs b/app/vendor/rune/vendor/parley_engine/src/analyzer.rs new file mode 100644 index 0000000..647dd76 --- /dev/null +++ b/app/vendor/rune/vendor/parley_engine/src/analyzer.rs @@ -0,0 +1,174 @@ +// Copyright 2026 the Parley Authors +// SPDX-License-Identifier: Apache-2.0 OR MIT + +//! The analyzer API. + +use core::ops::Range; + +use parlance::{BaseDirection, Language, LineBreak, WordBreak}; + +use crate::{bidi::BidiResolver, break_overrides::LineBreakOverrideFn}; + +use crate::analysis::{Analysis, analyze_text}; + +/// Reusable scratch for [`Analyzer::analyze`]. +#[derive(Default)] +pub struct Analyzer { + pub(crate) bidi: BidiResolver, + pub(crate) segmenters: crate::analysis::Segmenters, +} + +impl core::fmt::Debug for Analyzer { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + f.debug_struct("Analyzer").finish_non_exhaustive() + } +} + +impl Analyzer { + /// Creates a new analyzer. + pub fn new() -> Self { + Self::default() + } + + /// Analyze `text`, overwriting `analysis`. + /// + /// This reuses the allocations of `analysis`. + pub fn analyze(&mut self, text: &str, options: &AnalysisOptions<'_>, analysis: &mut Analysis) { + analysis.clear(); + analyze_text(self, text, options, analysis); + } +} + +/// Configuration of line break opportunities for a range of text. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)] +pub struct LineBreakConfig { + /// CSS `word-break`. + pub word_break: WordBreak, + /// CSS `line-break`. + pub line_break: LineBreak, + /// The content language. + /// + /// Chinese and Japanese content uses tailored line breaking rules, which for example allow + /// breaks before small kana and some punctuation under [`LineBreak::Normal`] and + /// [`LineBreak::Loose`]. + pub language: Option<Language>, +} + +/// Options controlling [`Analyzer::analyze`]. +#[derive(Clone, Copy, Default)] +pub struct AnalysisOptions<'a> { + /// The paragraph's base direction. + /// + /// Defaults to [`BaseDirection::Auto`], which infers the direction from the text. + pub base_direction: BaseDirection, + + /// Line breaking configuration for ranges of the source text. + /// + /// Ranges must be sorted and non-overlapping, and must start and end on character boundaries of + /// the text. Empty ranges are ignored. Gaps use [`LineBreakConfig::default`]. + pub line_break: &'a [(Range<usize>, LineBreakConfig)], + + /// Ranges of the source text in which a soft wrap opportunity follows every space, tab, and + /// ideographic space. + /// + /// This implements the additional soft wrap opportunities of + /// [CSS's white-space-collapse: break-spaces][css-break-spaces]. + /// + /// Outside these ranges, [UAX #14 § 6][uax-14-algorithm] is followed, which defines where soft + /// wrap opportunities exist. For example, rules LB7 and LB18 give a sequence of spaces an + /// opportunity only at its end. The ranges specified here add an opportunity after every space, + /// tab, and ideographic space, except directly before a mandatory break. This overrides the + /// "non-tailorable" UAX #14 Rule LB7, and so deviates from Unicode's line breaking algorithm. + /// + /// Ranges must be sorted and non-overlapping, and must start and end on character boundaries + /// of the text. Empty ranges are ignored. Gaps apply the default rules. + /// + /// [css-break-spaces]: https://www.w3.org/TR/css-text-4/#valdef-white-space-collapse-break-spaces + /// [uax-14-algorithm]: https://unicode.org/reports/tr14/#Algorithm + pub break_spaces: &'a [Range<usize>], + + /// The callback which will be called as a first provider of line breaking decisions. + /// + /// See [`LineBreakOverrideFn`] for more details. + pub line_break_override: Option<&'a LineBreakOverrideFn>, +} + +impl core::fmt::Debug for AnalysisOptions<'_> { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + f.debug_struct("AnalysisOptions") + .field("base_direction", &self.base_direction) + .field("line_break", &self.line_break) + .field("break_spaces", &self.break_spaces) + .finish_non_exhaustive() + } +} + +#[cfg(test)] +mod tests { + use parlance::BidiLevel; + + use super::{AnalysisOptions, Analyzer}; + use crate::{Analysis, BaseDirection}; + + fn analyze(text: &str, base_direction: BaseDirection) -> Analysis { + let mut analyzer = Analyzer::new(); + let mut analysis = Analysis::new(); + analyzer.analyze( + text, + &AnalysisOptions { + base_direction, + ..AnalysisOptions::default() + }, + &mut analysis, + ); + analysis + } + + #[test] + fn explicit_rtl_resolves_numeric_and_neutral_text() { + let text = "123 / 456"; + let auto = analyze(text, BaseDirection::Auto); + let rtl = analyze(text, BaseDirection::Rtl); + + assert_eq!(auto.paragraph_level(), BidiLevel::new(0)); + assert!(auto.paragraph_level().is_ltr()); + assert!(auto.bidi_levels().is_empty()); + + assert_eq!(rtl.paragraph_level(), BidiLevel::new(1)); + assert!(rtl.paragraph_level().is_rtl()); + assert_eq!(rtl.bidi_levels().len(), text.chars().count()); + for (ch, level) in text.chars().zip(rtl.bidi_levels()) { + if ch.is_ascii_digit() { + assert!(level.is_ltr()); + } + } + assert!(rtl.bidi_levels().iter().any(|level| level.is_rtl())); + } + + #[test] + fn explicit_ltr_takes_precedence_over_first_strong_direction() { + let text = "مرحبا hello"; + let auto = analyze(text, BaseDirection::Auto); + let ltr = analyze(text, BaseDirection::Ltr); + + assert!(auto.paragraph_level().is_rtl()); + assert!(ltr.paragraph_level().is_ltr()); + assert_ne!(auto.bidi_levels(), ltr.bidi_levels()); + } + + #[test] + fn explicit_rtl_preserves_ltr_run_direction() { + let analysis = analyze("hello", BaseDirection::Rtl); + + assert!(analysis.paragraph_level().is_rtl()); + assert!(analysis.bidi_levels().iter().all(|level| level.is_ltr())); + } + + #[test] + fn explicit_direction_applies_to_empty_text() { + let analysis = analyze("", BaseDirection::Rtl); + + assert!(analysis.paragraph_level().is_rtl()); + assert!(analysis.bidi_levels().is_empty()); + } +} diff --git a/app/vendor/rune/vendor/parley_engine/src/bidi.rs b/app/vendor/rune/vendor/parley_engine/src/bidi.rs new file mode 100644 index 0000000..fd44780 --- /dev/null +++ b/app/vendor/rune/vendor/parley_engine/src/bidi.rs @@ -0,0 +1,917 @@ +// Copyright 2021 the Parley Authors +// SPDX-License-Identifier: Apache-2.0 OR MIT + +//! Unicode bidirectional algorithm. + +use alloc::vec::Vec; +use icu_properties::props::{BidiClass, BidiMirroringGlyph, BidiPairedBracketType}; +use parlance::{BaseDirection, BidiLevel}; + +/// Resolver for the Unicode bidirectional algorithm. +#[derive(Clone, Default)] +pub(crate) struct BidiResolver { + base_level: BidiLevel, + pub(crate) levels: Vec<BidiLevel>, + initial_types: Vec<BidiClass>, + types: Vec<BidiClass>, + brackets: Vec<(usize, char, BidiMirroringGlyph)>, + bracket_pairs: Vec<(usize, usize)>, + runs: Vec<Run>, + indices: Vec<usize>, + flags: u16, +} + +impl core::fmt::Debug for BidiResolver { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + f.debug_struct("BidiResolver") + .field("base_level", &self.base_level) + .field("levels", &self.levels) + .finish_non_exhaustive() + } +} + +impl BidiResolver { + /// Returns the base level of the text. + pub(crate) fn base_level(&self) -> BidiLevel { + self.base_level + } + + /// Clears the resolver state. + pub(crate) fn clear(&mut self) { + self.initial_types.clear(); + self.levels.clear(); + self.types.clear(); + self.brackets.clear(); + self.bracket_pairs.clear(); + self.flags = 0; + self.base_level = BidiLevel::new(0); + } + + /// Resolves a paragraph with the specified base direction and + /// precomputed types. + pub(crate) fn resolve( + &mut self, + chars: impl Iterator<Item = (char, (BidiClass, BidiMirroringGlyph))>, + base_direction: BaseDirection, + ) { + self.clear(); + let mut needs_bidi = false; + let mut len = 0; + for (i, (ch, (t, bracket))) in chars.enumerate() { + self.initial_types.push(t); + + if bracket.paired_bracket_type != BidiPairedBracketType::None { + self.brackets.push((i, ch, bracket)); + } + + needs_bidi = needs_bidi || mask(t) & BIDI_MASK != 0; + len += 1; + } + self.base_level = match base_direction { + BaseDirection::Auto => Self::default_level(&self.initial_types), + BaseDirection::Ltr => BidiLevel::new(0), + BaseDirection::Rtl => BidiLevel::new(1), + }; + if !needs_bidi && self.base_level == BidiLevel::new(0) { + self.flags |= 1; + self.levels.resize(len, self.base_level); + return; + } + self.types.extend_from_slice(&self.initial_types); + self.resolve_levels(); + self.resolve_runs(); + //self.dump_sequences(); + for i in 0..self.runs.len() { + if self.runs[i].in_sequence { + continue; + } + self.types.truncate(len); + self.indices.clear(); + let mut cur = i; + let level = self.runs[i].level; + let sos = self.runs[i].sos; + let mut eos; + loop { + let run = &self.runs[cur]; + for i in run.start..run.end { + let ty = self.types[i]; + if !is_removed_by_x9(ty) { + self.types.push(ty); + self.indices.push(i); + } + } + eos = run.eos; + cur = match run.next { + Some(i) => i, + None => break, + }; + } + self.resolve_sequence(level.to_u8(), sos, eos, self.indices.len()); + } + for i in 0..len { + let t = self.initial_types[i]; + if t == BidiClass::SegmentSeparator || t == BidiClass::ParagraphSeparator { + self.levels[i] = self.base_level; + for j in (0..i).rev() { + let t = self.initial_types[j]; + if is_removed_by_x9(t) { + continue; + } else if t == BidiClass::WhiteSpace + || is_isolate_initiator(t) + || t == BidiClass::PopDirectionalIsolate + { + self.levels[j] = self.base_level; + } else { + break; + } + } + } else if is_removed_by_x9(t) { + if i == 0 { + self.levels[i] = self.base_level; + } else { + self.levels[i] = self.levels[i - 1]; + } + //self.levels[i] = 0xFF; + } + } + for i in (0..len).rev() { + let t = self.initial_types[i]; + if is_removed_by_x9(t) { + continue; + } else if t == BidiClass::WhiteSpace + || is_isolate_initiator(t) + || t == BidiClass::PopDirectionalIsolate + { + // UAX #9 L1: whitespace, isolate initiators and PDIs that end the paragraph take + // the paragraph's level (Rune: vendor/parley_engine.patch). + self.levels[i] = self.base_level; + } else { + break; + } + } + } + + fn default_level(types: &[BidiClass]) -> BidiLevel { + let mut isolates = 0; + for ty in types { + let ty = *ty; + match ty { + BidiClass::RightToLeftIsolate + | BidiClass::LeftToRightIsolate + | BidiClass::FirstStrongIsolate => isolates += 1, + BidiClass::PopDirectionalIsolate if isolates > 0 => isolates -= 1, + BidiClass::LeftToRight | BidiClass::RightToLeft | BidiClass::ArabicLetter + if isolates == 0 => + { + return if ty == BidiClass::LeftToRight { + BidiLevel::new(0) + } else { + BidiLevel::new(1) + }; + } + _ => {} + } + } + BidiLevel::new(0) + } + + fn default_level_until_pdi(types: &[BidiClass]) -> u8 { + let mut isolates = 0; + for ty in types { + let ty = *ty; + match ty { + BidiClass::RightToLeftIsolate + | BidiClass::LeftToRightIsolate + | BidiClass::FirstStrongIsolate => isolates += 1, + BidiClass::PopDirectionalIsolate => { + if isolates > 0 { + isolates -= 1; + } else { + return 0; + } + } + BidiClass::LeftToRight | BidiClass::RightToLeft | BidiClass::ArabicLetter + if isolates == 0 => + { + return if ty == BidiClass::LeftToRight { 0 } else { 1 }; + } + _ => {} + } + } + 0 + } + + fn resolve_levels(&mut self) { + let base = self.base_level; + let len = self.types.len(); + self.levels.clear(); + self.levels.resize(len, BidiLevel::new(0)); + let mut stack = Stack::new(); + let mut overflow_isolates = 0; + let mut overflow_embedding = 0; + let mut valid_isolates = 0; + stack.push(base, BidiClass::OtherNeutral, false); + for i in 0..len { + let t = self.types[i]; + let tmask = mask(t); + if tmask & EXPLICIT_MASK != 0 { + let is_isolate = tmask & ISOLATE_MASK != 0; + let is_rtl = if t == BidiClass::FirstStrongIsolate && i + 1 < len { + Self::default_level_until_pdi(&self.types[i + 1..]) == 1 + } else { + tmask & RTL_MASK != 0 + }; + if is_isolate { + self.levels[i] = stack.embedding_level(); + let os = stack.override_status(); + if os != BidiClass::OtherNeutral { + self.types[i] = os; + } + } + let new_level = if is_rtl { + stack.embedding_level().next_odd() + } else { + stack.embedding_level().next_even() + }; + if new_level <= BidiLevel::MAX && overflow_isolates == 0 && overflow_embedding == 0 + { + if is_isolate { + valid_isolates += 1; + } + stack.push( + new_level, + if t == BidiClass::LeftToRightOverride { + BidiClass::LeftToRight + } else if t == BidiClass::RightToLeftOverride { + BidiClass::RightToLeft + } else { + BidiClass::OtherNeutral + }, + is_isolate, + ); + } else if is_isolate { + overflow_isolates += 1; + } else if overflow_isolates == 0 { + overflow_embedding += 1; + } + } else if t == BidiClass::PopDirectionalIsolate { + if overflow_isolates > 0 { + overflow_isolates -= 1; + } else if valid_isolates == 0 { + // empty + } else { + overflow_embedding = 0; + while !stack.isolate_status() { + stack.pop(); + } + stack.pop(); + valid_isolates -= 1; + } + self.levels[i] = stack.embedding_level(); + if stack.override_status() != BidiClass::OtherNeutral { + self.types[i] = stack.override_status(); + } + } else if t == BidiClass::PopDirectionalFormat { + self.levels[i] = stack.embedding_level(); + if overflow_isolates > 0 { + // empty + } else if overflow_embedding > 0 { + overflow_embedding -= 1; + } else if !stack.isolate_status() && stack.depth >= 2 { + stack.pop(); + } + } else if t == BidiClass::ParagraphSeparator { + stack.depth = 1; + overflow_isolates = 0; + overflow_embedding = 0; + valid_isolates = 0; + self.levels[i] = base; + } else if t != BidiClass::BoundaryNeutral { + self.levels[i] = stack.embedding_level(); + if stack.override_status() != BidiClass::OtherNeutral { + self.types[i] = stack.override_status(); + } + } + } + } + + fn resolve_runs(&mut self) { + let len = self.types.len(); + self.runs.clear(); + let mut start = 0; + while start < len { + if !is_removed_by_x9(self.types[start]) { + break; + } + start += 1; + } + if start == len { + return; + } + let mut level = self.levels[start]; + let mut offset = 0; + for i in start + 1..len { + if is_removed_by_x9(self.types[i]) { + continue; + } + if self.levels[i] != level { + self.runs.push(Run::new(level, offset, i)); + offset = i; + level = self.levels[i]; + } + } + if offset < len { + self.runs.push(Run::new(level, offset, len)); + } + for run in &mut self.runs { + while run.start < run.end { + if is_removed_by_x9(self.types[run.start]) { + run.start += 1; + } else { + break; + } + } + while run.end > run.start { + if is_removed_by_x9(self.types[run.end - 1]) { + run.end -= 1; + } else { + break; + } + } + if run.start == run.end { + continue; + } + if self.types[run.start] == BidiClass::PopDirectionalIsolate { + run.starts_with_pdi = true; + } + let mut prev_level = self.base_level; + for i in (0..run.start).rev() { + if !is_removed_by_x9(self.types[i]) { + prev_level = self.levels[i]; + break; + } + } + run.sos = type_from_level(prev_level.max(run.level)); + if is_isolate_initiator(self.initial_types[run.end - 1]) { + run.ends_with_isolate = true; + run.eos = type_from_level(self.base_level.max(run.level)); + } else { + let mut next_level = self.base_level; + for i in run.end..len { + if !is_removed_by_x9(self.types[i]) { + next_level = self.levels[i]; + break; + } + } + run.eos = type_from_level(next_level.max(run.level)); + } + } + for i in 0..self.runs.len() { + if self.runs[i].ends_with_isolate { + let level = self.runs[i].level; + for j in i + 1..self.runs.len() { + if self.runs[j].starts_with_pdi && self.runs[j].level == level { + self.runs[i].next = Some(j); + self.runs[j].in_sequence = true; + break; + } + } + } + } + } + + #[expect(clippy::needless_range_loop, reason = "Deferred")] + fn resolve_sequence(&mut self, level: u8, sos: BidiClass, eos: BidiClass, len: usize) { + if len == 0 { + return; + } + const W1_MASK: u32 = mask(BidiClass::LeftToRightIsolate) + | mask(BidiClass::RightToLeftIsolate) + | mask(BidiClass::FirstStrongIsolate) + | mask(BidiClass::PopDirectionalIsolate); + const W2_MASK: u32 = mask(BidiClass::LeftToRight) + | mask(BidiClass::RightToLeft) + | mask(BidiClass::ArabicLetter); + const W4_MASK: u32 = mask(BidiClass::EuropeanSeparator) | mask(BidiClass::CommonSeparator); + let mut prev = sos; + let mut prev_strong = prev; + let types = &mut self.types[self.initial_types.len()..]; + for i in 0..len { + let mut t = types[i]; + let tmask = mask(t); + if t == BidiClass::NonspacingMark { + // W1 + types[i] = prev; + } else { + if tmask & W1_MASK != 0 { + prev = BidiClass::OtherNeutral; + continue; + } + if t == BidiClass::EuropeanNumber { + // W2 + if prev_strong == BidiClass::ArabicLetter { + t = BidiClass::ArabicNumber; + types[i] = t; + } + } else if tmask & W2_MASK != 0 { + prev_strong = t; + // W3 + if t == BidiClass::ArabicLetter { + t = BidiClass::RightToLeft; + types[i] = t; + } + } else if tmask & W4_MASK != 0 && i < (len - 1) { + // W4 + let mut next = types[i + 1]; + if next == BidiClass::EuropeanNumber && prev_strong == BidiClass::ArabicLetter { + next = BidiClass::ArabicNumber; + } + if prev == BidiClass::EuropeanNumber && next == BidiClass::EuropeanNumber { + t = BidiClass::EuropeanNumber; + types[i] = t; + } else if t == BidiClass::CommonSeparator + && prev == BidiClass::ArabicNumber + && next == BidiClass::ArabicNumber + { + t = BidiClass::ArabicNumber; + types[i] = t; + } + } + prev = t; + } + } + // W5 + let mut i = 0; + while i < len { + if types[i] == BidiClass::EuropeanTerminator { + let limit = find_limit(types, i, BidiClass::EuropeanTerminator); + let mut t = if i == 0 { sos } else { types[i - 1] }; + if t != BidiClass::EuropeanNumber { + t = if limit == len { eos } else { types[limit] }; + } + if t == BidiClass::EuropeanNumber { + for j in i..limit { + types[j] = BidiClass::EuropeanNumber; + } + } + i = limit; + } + i += 1; + } + // W6, W7 + const W6_MASK: u32 = mask(BidiClass::EuropeanSeparator) + | mask(BidiClass::EuropeanTerminator) + | mask(BidiClass::CommonSeparator); + prev_strong = sos; + for i in 0..len { + let t = types[i]; + if mask(t) & W6_MASK != 0 { + // W6 + types[i] = BidiClass::OtherNeutral; + } else if t == BidiClass::EuropeanNumber { + // W7 + if prev_strong == BidiClass::LeftToRight { + types[i] = BidiClass::LeftToRight; + } + } else if t == BidiClass::LeftToRight || t == BidiClass::RightToLeft { + prev_strong = t; + } + } + // N0 + if !self.brackets.is_empty() { + let base_brackets = self.bracket_pairs.len(); + let mut bracket_stack = BracketStack::new(); + for i in 0..len { + if types[i] != BidiClass::OtherNeutral { + continue; + } + let index = self.indices[i]; + if let Ok(index) = self.brackets.binary_search_by(|x| x.0.cmp(&index)) { + let (_, ch, bracket) = self.brackets[index]; + match bracket.paired_bracket_type { + BidiPairedBracketType::Open => { + if bracket_stack.depth == MAX_BRACKET_STACK { + break; + } + bracket_stack.push(i, bracket.mirroring_glyph.unwrap()); + } + BidiPairedBracketType::Close => { + if let Some(open) = bracket_stack.find_and_pop(ch) { + self.bracket_pairs.push((open, i)); + } + } + _ => {} + } + } + } + if self.bracket_pairs.len() > base_brackets { + let embed_dir = if level & 1 != 0 { + BidiClass::RightToLeft + } else { + BidiClass::LeftToRight + }; + let bracket_pairs = &mut self.bracket_pairs[base_brackets..]; + bracket_pairs.sort_unstable_by_key(|a| a.0); + for pair in bracket_pairs { + let mut pair_dir = BidiClass::OtherNeutral; + for i in pair.0 + 1..pair.1 { + let dir = match types[i] { + BidiClass::EuropeanNumber + | BidiClass::ArabicNumber + | BidiClass::ArabicLetter + | BidiClass::RightToLeft => BidiClass::RightToLeft, + BidiClass::LeftToRight => BidiClass::LeftToRight, + _ => BidiClass::OtherNeutral, + }; + if dir == BidiClass::OtherNeutral { + continue; + } + pair_dir = dir; + if dir == embed_dir { + break; + } + } + if pair_dir == BidiClass::OtherNeutral { + pair.0 = self.indices[pair.0]; + pair.1 = self.indices[pair.1]; + continue; + } + if pair_dir != embed_dir { + pair_dir = sos; + for i in (0..pair.0).rev() { + let dir = match types[i] { + BidiClass::EuropeanNumber + | BidiClass::ArabicNumber + | BidiClass::ArabicLetter + | BidiClass::RightToLeft => BidiClass::RightToLeft, + BidiClass::LeftToRight => BidiClass::LeftToRight, + _ => BidiClass::OtherNeutral, + }; + if dir != BidiClass::OtherNeutral { + pair_dir = dir; + break; + } + } + if pair_dir == embed_dir || pair_dir == BidiClass::OtherNeutral { + pair_dir = embed_dir; + } + } + types[pair.0] = pair_dir; + types[pair.1] = pair_dir; + for i in pair.0 + 1..pair.1 { + let index = self.indices[i]; + if self.initial_types[index] == BidiClass::NonspacingMark { + types[i] = pair_dir; + } else { + break; + } + } + for i in pair.1 + 1..len { + let index = self.indices[i]; + if self.initial_types[index] == BidiClass::NonspacingMark { + types[i] = pair_dir; + } else { + break; + } + } + pair.0 = self.indices[pair.0]; + pair.1 = self.indices[pair.1]; + } + } + } + // N1, N2 + const N_MASK: u32 = mask(BidiClass::ParagraphSeparator) + | mask(BidiClass::SegmentSeparator) + | mask(BidiClass::WhiteSpace) + | mask(BidiClass::OtherNeutral) + | mask(BidiClass::RightToLeftIsolate) + | mask(BidiClass::LeftToRightIsolate) + | mask(BidiClass::FirstStrongIsolate) + | mask(BidiClass::PopDirectionalIsolate); + let mut i = 0; + while i < len { + let t = types[i]; + if mask(t) & N_MASK != 0 { + let offset = i; + let limit = find_limit_by_mask(types, offset, N_MASK); + let mut leading; + let mut trailing; + if offset == 0 { + leading = sos; + } else { + leading = types[offset - 1]; + if leading == BidiClass::ArabicNumber || leading == BidiClass::EuropeanNumber { + leading = BidiClass::RightToLeft; + } + } + if limit == len { + trailing = eos; + } else { + trailing = types[limit]; + if trailing == BidiClass::ArabicNumber || trailing == BidiClass::EuropeanNumber + { + trailing = BidiClass::RightToLeft; + } + } + let resolved = if leading == trailing { + // N1 + leading + } else { + // N2 + if level & 1 != 0 { + BidiClass::RightToLeft + } else { + BidiClass::LeftToRight + } + }; + for j in offset..limit { + types[j] = resolved; + } + i = limit - 1; + } + i += 1; + } + // Implicit levels + if level & 1 == 0 { + // I1 + for i in 0..len { + let index = self.indices[i]; + let t = types[i]; + if t == BidiClass::RightToLeft { + self.levels[index] = BidiLevel::new(level + 1); + } else if t != BidiClass::LeftToRight { + self.levels[index] = BidiLevel::new(level + 2); + } else { + self.levels[index] = BidiLevel::new(level); + } + } + } else { + // I2 + for i in 0..len { + let index = self.indices[i]; + let t = types[i]; + if t != BidiClass::RightToLeft { + self.levels[index] = BidiLevel::new(level + 1); + } else { + self.levels[index] = BidiLevel::new(level); + } + } + } + } +} + +/// Returns a default bidi type for a level. +pub(crate) fn type_from_level(level: BidiLevel) -> BidiClass { + if level.is_ltr() { + BidiClass::LeftToRight + } else { + BidiClass::RightToLeft + } +} + +/// Computes an ordering for a sequence of bidi runs based on levels. +pub(crate) fn _reorder<F>(order: &mut [usize], levels: F) +where + F: Fn(usize) -> u8, +{ + let mut max_level = 0; + let mut lowest_odd_level = 255; + for (i, o) in order.iter_mut().enumerate() { + *o = i; + let level = levels(i); + if level > max_level { + max_level = level; + } + if level & 1 != 0 && level < lowest_odd_level { + lowest_odd_level = level; + } + } + let len = order.len(); + for level in (lowest_odd_level..=max_level).rev() { + let mut i = 0; + while i < len { + if levels(i) >= level { + let mut end = i + 1; + while end < len && levels(end) >= level { + end += 1; + } + let mut j = i; + let mut k = end - 1; + while j < k { + order.swap(j, k); + j += 1; + k -= 1; + } + i = end; + } + i += 1; + } + } +} + +/// Returns whether the character needs bidirectional resolution. +#[inline(always)] +pub(crate) fn needs_bidi_resolution(bidi_class: BidiClass) -> bool { + mask(bidi_class) & BIDI_MASK != 0 +} + +const OVERRIDE_MASK: u32 = mask(BidiClass::RightToLeftEmbedding) + | mask(BidiClass::LeftToRightEmbedding) + | mask(BidiClass::RightToLeftOverride) + | mask(BidiClass::LeftToRightOverride); +const ISOLATE_MASK: u32 = mask(BidiClass::RightToLeftIsolate) + | mask(BidiClass::LeftToRightIsolate) + | mask(BidiClass::FirstStrongIsolate); +const EXPLICIT_MASK: u32 = OVERRIDE_MASK | ISOLATE_MASK; +const RTL_MASK: u32 = mask(BidiClass::RightToLeftEmbedding) + | mask(BidiClass::RightToLeftOverride) + | mask(BidiClass::RightToLeftIsolate); +const REMOVED_BY_X9_MASK: u32 = + OVERRIDE_MASK | mask(BidiClass::PopDirectionalFormat) | mask(BidiClass::BoundaryNeutral); +const BIDI_MASK: u32 = EXPLICIT_MASK + | mask(BidiClass::RightToLeft) + | mask(BidiClass::ArabicLetter) + | mask(BidiClass::ArabicNumber); +const _RESET_MASK: u32 = + ISOLATE_MASK | mask(BidiClass::PopDirectionalIsolate) | mask(BidiClass::WhiteSpace); + +fn is_isolate_initiator(ty: BidiClass) -> bool { + mask(ty) & ISOLATE_MASK != 0 +} + +pub(crate) fn is_removed_by_x9(ty: BidiClass) -> bool { + mask(ty) & REMOVED_BY_X9_MASK != 0 +} + +pub(crate) fn _is_reset(ty: BidiClass) -> bool { + mask(ty) & _RESET_MASK != 0 +} + +fn find_limit(types: &[BidiClass], offset: usize, ty: BidiClass) -> usize { + let mut len = offset; + for &t in &types[offset..] { + if t != ty { + break; + } + len += 1; + } + len +} + +fn find_limit_by_mask(types: &[BidiClass], offset: usize, mask: u32) -> usize { + let mut len = offset; + for &t in &types[offset..] { + if self::mask(t) & mask == 0 { + break; + } + len += 1; + } + len +} + +#[derive(Clone)] +struct Run { + level: BidiLevel, + ends_with_isolate: bool, + starts_with_pdi: bool, + sos: BidiClass, + eos: BidiClass, + start: usize, + end: usize, + in_sequence: bool, + next: Option<usize>, +} + +impl Run { + fn new(level: BidiLevel, start: usize, end: usize) -> Self { + Self { + level, + ends_with_isolate: false, + starts_with_pdi: false, + sos: BidiClass::OtherNeutral, + eos: BidiClass::OtherNeutral, + start, + end, + in_sequence: false, + next: None, + } + } +} + +const MAX_STACK: usize = BidiLevel::MAX.to_u8() as usize; + +struct Stack { + embedding_level: [BidiLevel; MAX_STACK + 1], + override_status: [BidiClass; MAX_STACK + 1], + isolate_status: [bool; MAX_STACK + 1], + depth: usize, +} + +impl Stack { + fn new() -> Self { + Self { + depth: 0, + embedding_level: [BidiLevel::new(0); MAX_STACK + 1], + override_status: [BidiClass::OtherNeutral; MAX_STACK + 1], + isolate_status: [false; MAX_STACK + 1], + } + } + + fn push(&mut self, level: BidiLevel, override_status: BidiClass, isolate_status: bool) { + let d = self.depth; + self.embedding_level[d] = level; + self.override_status[d] = override_status; + self.isolate_status[d] = isolate_status; + self.depth += 1; + } + + fn pop(&mut self) { + if self.depth > 1 { + self.depth -= 1; + } + } + + fn embedding_level(&self) -> BidiLevel { + self.embedding_level[self.depth - 1] + } + + fn override_status(&self) -> BidiClass { + self.override_status[self.depth - 1] + } + + fn isolate_status(&self) -> bool { + self.isolate_status[self.depth - 1] + } +} + +const MAX_BRACKET_STACK: usize = 63; + +struct BracketStack { + openers: [(usize, char); MAX_BRACKET_STACK], + depth: usize, +} + +impl BracketStack { + fn new() -> Self { + Self { + openers: [(0, '\0'); MAX_BRACKET_STACK], + depth: 0, + } + } + + fn push(&mut self, offset: usize, closer: char) { + self.openers[self.depth] = (offset, closer); + self.depth += 1; + } + + fn find_and_pop(&mut self, closer: char) -> Option<usize> { + if self.depth == 0 { + return None; + } + for i in (0..self.depth).rev() { + let c = self.openers[i].1; + if c == closer + || (c == '\u{232A}' && closer == '\u{3009}') + || (c == '\u{3009}' && closer == '\u{232A}') + { + self.depth = i; + return Some(self.openers[i].0); + } + } + None + } +} + +/// Turns a bidi class into a single bit, for cheap set membership testing. +const fn mask(t: BidiClass) -> u32 { + let bit = match t { + BidiClass::LeftToRight => 0, + BidiClass::RightToLeft => 1, + BidiClass::EuropeanNumber => 2, + BidiClass::EuropeanSeparator => 3, + BidiClass::EuropeanTerminator => 4, + BidiClass::ArabicNumber => 5, + BidiClass::CommonSeparator => 6, + BidiClass::ParagraphSeparator => 7, + BidiClass::SegmentSeparator => 8, + BidiClass::WhiteSpace => 9, + BidiClass::OtherNeutral => 10, + BidiClass::LeftToRightEmbedding => 11, + BidiClass::LeftToRightOverride => 12, + BidiClass::ArabicLetter => 13, + BidiClass::RightToLeftEmbedding => 14, + BidiClass::RightToLeftOverride => 15, + BidiClass::PopDirectionalFormat => 16, + BidiClass::NonspacingMark => 17, + BidiClass::BoundaryNeutral => 18, + BidiClass::FirstStrongIsolate => 19, + BidiClass::LeftToRightIsolate => 20, + BidiClass::RightToLeftIsolate => 21, + BidiClass::PopDirectionalIsolate => 22, + _ => { + debug_assert!(false, "unhandled Bidi_Class"); + return 0; + } + }; + 1 << bit +} diff --git a/app/vendor/rune/vendor/parley_engine/src/break_overrides.rs b/app/vendor/rune/vendor/parley_engine/src/break_overrides.rs new file mode 100644 index 0000000..88107b7 --- /dev/null +++ b/app/vendor/rune/vendor/parley_engine/src/break_overrides.rs @@ -0,0 +1,436 @@ +// Copyright 2026 the Parley Authors +// SPDX-License-Identifier: Apache-2.0 OR MIT + +//! Overrides for line-break opportunities. + +use core::ops::RangeInclusive; + +/// Context for a potential line break opportunity between two adjacent code points. +#[derive(Clone, Copy, Debug)] +#[non_exhaustive] +pub struct LineBreakContext { + /// The code point before the `before` code point, if any. + pub before_before: Option<char>, + /// The code point before the potential break. + pub before: char, + /// The code point after the potential break. + pub after: char, +} + +/// Line break opportunity override. +/// +/// Called for each adjacent pair of Unicode code points in the text, in order, except for pairs +/// containing a mandatory break character. The [`LineBreakContext`] describes the potential break. +/// +/// Returning: +/// - `Some(true)` : forces a line break opportunity between the pair +/// - `Some(false)` : suppresses any opportunity +/// - `None` : defers to the default (ICU) behavior +/// +/// Note that pairs with a mandatory break aren't soft wrap opportunities. Mandatory breaks are +/// reported as [`Whitespace`][crate::shape::Whitespace]. +/// +/// This is typically used to force preferential line breaking decisions when it +/// comes to ASCII punctuation like `/`, `-`, etc. For example, to prevent break +/// opportunities within "1/2". +/// +/// A separate use case is to match the line breaking behavior of existing systems +/// such as web browsers. See [`CHROMIUM_LINE_BREAK_OVERRIDE`] for a ready-made +/// override function that mirrors Chromium's behavior. +pub type LineBreakOverrideFn = dyn Fn(LineBreakContext) -> Option<bool> + Send + Sync; + +/// A line break override function mirroring Chromium's preferred line breaking behavior. +/// +/// See: <https://source.chromium.org/chromium/chromium/src/+/main:third_party/blink/renderer/platform/text/character_property_data_generator.cc;l=449-495> +/// +/// # Differences from other browsers +/// +/// ## Compared to Safari +/// +/// Chromium (and this table) differs from Safari in 9 cases: +/// - A "-" followed by one of "!|$|)|/|:|;|?|]|}" is suppressed in Chromium, but broken in Safari. +/// +/// ## Compared to Firefox +/// +/// Firefox always defers to the default ICU behavior. +pub static CHROMIUM_LINE_BREAK_OVERRIDE: &LineBreakOverrideFn = + &(chromium_override as fn(LineBreakContext) -> Option<bool>); + +fn chromium_override(cx: LineBreakContext) -> Option<bool> { + let LineBreakContext { + before_before, + before, + after, + .. + } = cx; + // CSS "does not fully define where soft wrap opportunities occur". + // (https://www.w3.org/TR/css-text-3/#line-breaking) + // We find that Chrome always treats the position after a space sequence + // as a line break opportunity, despite this not matching UAX-14 + // (see LB13: https://www.unicode.org/reports/tr14/#LB13; we're not currently + // aware of any others). + // + // See also https://github.com/linebender/parley/pull/485, and https://github.com/linebender/parley/issues/619. + // + // See `LazyLineBreakIterator::NextBreakablePosition` + // <https://source.chromium.org/chromium/chromium/src/+/main:third_party/blink/renderer/platform/text/text_break_iterator.cc;l=282-303> + if before == ' ' && after != ' ' { + return Some(true); + } + // Before consulting 'before' / 'after' pair table, check for the special "-" case. + // + // Chromium doesn't allow breaking when it looks like the minus sign is for a negative + // number like "Subtract -5 from X". But, Chromium does allow breaking when the minus + // sign is part of a long URL like "AAAA-2222". + // + // See <https://github.com/chromium/chromium/blob/c6bee15e8f336c8feabf539d8bbb540c134ec20a/third_party/blink/renderer/platform/text/text_break_iterator.cc#L224-L240> + if before == '-' && after.is_ascii_digit() { + return Some(before_before.is_some_and(|c| c.is_ascii_alphanumeric())); + } + CHROMIUM_LINE_BREAK_TABLE.lookup(before, after) +} + +/// A static table mirroring Chromium's preferred line breaking behavior for `before` / `after` +/// printable ASCII code points. +static CHROMIUM_LINE_BREAK_TABLE: AsciiLineBreakTable<5> = + AsciiLineBreakTableBuilder::chromium().build::<5>(); + +/// A line break override table for ASCII character pairs. +/// +/// See [`LineBreakOverrideFn`] for more details. +/// +/// All table operations are `const`, which means that derived tables don't +/// need a runtime construction step. +/// +/// The table is row-deduplicated. Each `before` character maps to +/// one of `N` distinct rows, so tables can be kept tiny. +/// +/// # Example +/// +/// ``` +/// # use parley_engine::break_overrides::CHROMIUM_LINE_BREAK_OVERRIDE; +/// # use parley_engine::{Analysis, AnalysisOptions, Analyzer}; +/// # let mut analyzer = Analyzer::new(); +/// # let mut analysis = Analysis::new(); +/// let text = "Hello there!"; +/// let options = AnalysisOptions { +/// // Emulate Chromium: +/// line_break_override: Some(CHROMIUM_LINE_BREAK_OVERRIDE), +/// ..AnalysisOptions::default() +/// }; +/// analyzer.analyze(text, &options, &mut analysis); +/// ``` +#[derive(Clone, Debug)] +pub struct AsciiLineBreakTable<const N: usize> { + /// Maps each `before` character (`0..128`) to a row in `rows`. + row_of: [u8; 128], + /// The distinct rows. + rows: [Row; N], +} + +impl<const N: usize> AsciiLineBreakTable<N> { + /// Look up the break override for a `(before, after)` pair. + /// + /// Return semantics copied from [`LineBreakOverrideFn`]. + pub const fn lookup(&self, before: char, after: char) -> Option<bool> { + let (b, a) = (before as u32, after as u32); + if b >= 128 || a >= 128 { + return None; + } + let row = &self.rows[self.row_of[b as usize] as usize]; + if row.overridden & (1_u128 << a) == 0 { + return None; + } + Some(row.allow & (1_u128 << a) != 0) + } +} + +/// A single deduplicated row of a [`AsciiLineBreakTable`]. +#[derive(Clone, Copy, Debug)] +struct Row { + /// Bits set means the pair has an override. + overridden: u128, + /// Bits set means a break is allowed. + allow: u128, +} + +/// A builder for an [`AsciiLineBreakTable`]. +/// +/// Construction is `const`. We create a dense `128 x 128` grid of overrides, +/// then compress it into a row-deduplicated table via [`AsciiLineBreakTableBuilder::build`]. +#[derive(Clone, Debug)] +pub struct AsciiLineBreakTableBuilder { + /// Bit `after` set in row `before` means the pair has an explicit override. + overridden: [u128; 128], + /// Bit `after` set in row `before` means a break is allowed for that pair. + allow: [u128; 128], +} + +impl AsciiLineBreakTableBuilder { + /// A builder that defers every pair to the default ICU behavior. + pub const fn new() -> Self { + Self { + overridden: [0; 128], + allow: [0; 128], + } + } + + /// Override every pair in the cartesian product of the two inclusive ASCII + /// ranges. + /// + /// # Panics + /// + /// All range bounds must be printable ASCII (`<= '\u{7f}'`). + pub const fn with_pairs( + mut self, + before: RangeInclusive<char>, + after: RangeInclusive<char>, + allow_break: bool, + ) -> Self { + assert!( + *before.end() as u32 <= 0x7f && *after.end() as u32 <= 0x7f, + "only printable ASCII is supported", + ); + let mut before_pos = *before.start() as u32; + while before_pos <= *before.end() as u32 { + let mut after_pos = *after.start() as u32; + while after_pos <= *after.end() as u32 { + let bit = 1_u128 << after_pos; + self.overridden[before_pos as usize] |= bit; + if allow_break { + self.allow[before_pos as usize] |= bit; + } else { + self.allow[before_pos as usize] &= !bit; + } + after_pos += 1; + } + before_pos += 1; + } + self + } + + /// Compress the dense grid into a row-deduplicated [`AsciiLineBreakTable`] + /// with at most `N` distinct rows. + /// + /// # Panics + /// + /// Panics if `N` does not exactly match the number of distinct rows required. + pub const fn build<const N: usize>(&self) -> AsciiLineBreakTable<N> { + // Row 0 is reserved as the "defer everything" row. + let mut rows = [Row { + overridden: 0, + allow: 0, + }; N]; + let mut len = 1_usize; + let mut row_of = [0_u8; 128]; + + let mut b = 0; + while b < 128 { + let (ov, al) = (self.overridden[b], self.allow[b]); + let mut idx = 0; + let mut found = usize::MAX; + while idx < len { + if rows[idx].overridden == ov && rows[idx].allow == al { + found = idx; + break; + } + idx += 1; + } + let r = if found != usize::MAX { + found + } else { + assert!( + len < N, + "N is too small to contain table. Repeat with a larger N." + ); + rows[len] = Row { + overridden: ov, + allow: al, + }; + len += 1; + len - 1 + }; + #[expect( + clippy::cast_possible_truncation, + reason = "TODO: fix this (`N` should be `u8`, or `row_of` should contain `usize`)" + )] + { + row_of[b] = r as u8; + } + b += 1; + } + + assert!( + len == N, + "N is larger than required. Repeat with a smaller N." + ); + + AsciiLineBreakTable { row_of, rows } + } + + /// See [`CHROMIUM_LINE_BREAK_TABLE`] for more details. + const fn chromium() -> Self { + // The printable ASCII range `'!'..=0x7F`. + const ALL: RangeInclusive<char> = '!'..='\u{7f}'; + + Self::new() + .with_pairs(ALL, ALL, false) + .with_pairs(ALL, '('..='(', true) + .with_pairs(ALL, '<'..='<', true) + .with_pairs(ALL, '['..='[', true) + .with_pairs(ALL, '{'..='{', true) + .with_pairs('-'..='-', ALL, true) + .with_pairs('?'..='?', ALL, true) + .with_pairs('-'..='-', '$'..='$', false) + .with_pairs(ALL, '!'..='!', false) + .with_pairs('?'..='?', '"'..='"', false) + .with_pairs('?'..='?', '\''..='\'', false) + .with_pairs(ALL, ')'..=')', false) + .with_pairs(ALL, ','..=',', false) + .with_pairs(ALL, '.'..='.', false) + .with_pairs(ALL, '/'..='/', false) + .with_pairs('-'..='-', '0'..='9', false) + .with_pairs(ALL, ':'..=':', false) + .with_pairs(ALL, ';'..=';', false) + .with_pairs(ALL, '?'..='?', false) + .with_pairs(ALL, ']'..=']', false) + .with_pairs(ALL, '}'..='}', false) + .with_pairs('$'..='$', ALL, false) + .with_pairs('\''..='\'', ALL, false) + .with_pairs('('..='(', ALL, false) + .with_pairs('/'..='/', ALL, false) + .with_pairs('0'..='9', ALL, false) + .with_pairs('<'..='<', ALL, false) + .with_pairs('@'..='@', ALL, false) + .with_pairs('A'..='Z', ALL, false) + .with_pairs('['..='[', ALL, false) + .with_pairs('^'..='`', ALL, false) + .with_pairs('a'..='z', ALL, false) + .with_pairs('{'..='{', ALL, false) + .with_pairs('\u{7f}'..='\u{7f}', ALL, false) + } +} + +impl Default for AsciiLineBreakTableBuilder { + fn default() -> Self { + Self::new() + } +} + +#[cfg(test)] +mod tests { + use super::AsciiLineBreakTableBuilder; + use super::CHROMIUM_LINE_BREAK_TABLE; + use super::LineBreakContext; + use super::chromium_override; + + fn cx(before_before: Option<char>, before: char, after: char) -> LineBreakContext { + LineBreakContext { + before_before, + before, + after, + } + } + + #[test] + fn chromium_hyphen_digit_depends_on_preceding_char() { + // A break between '-' and a digit is allowed only when the character + // preceding the '-' is ASCII alphanumeric. + assert_eq!(chromium_override(cx(Some('D'), '-', '1')), Some(true)); + assert_eq!(chromium_override(cx(Some('4'), '-', '5')), Some(true)); + // Otherwise the '-' may be a minus sign, so the break is suppressed. + assert_eq!(chromium_override(cx(Some(' '), '-', '1')), Some(false)); + assert_eq!(chromium_override(cx(Some('('), '-', '1')), Some(false)); + // No preceding character (start of text) behaves like a non-alphanumeric + // context, matching Chromium's `last_last_ch == 0`. + assert_eq!(chromium_override(cx(None, '-', '1')), Some(false)); + } + + #[test] + fn chromium_ignores_uax_14_lb13() { + // Blink allows a break after a space run unconditionally. + // See comment in non-test code for more details. + for after in ['}', ')', ']', '!', '.', ',', '/', ':', ';', '?', 'b', '('] { + assert_eq!( + chromium_override(cx(None, ' ', after)), + Some(true), + "expected a break after the space, before {after:?}" + ); + } + } + + #[test] + fn chromium_hyphen_non_digit_defers_to_table() { + // '-' followed by a non-digit ignores `before_before` and uses the table. + assert_eq!(chromium_override(cx(Some('D'), '-', 'b')), Some(true)); + assert_eq!(chromium_override(cx(None, '-', 'b')), Some(true)); + // Non-ASCII after '-' defers to ICU. + assert_eq!(chromium_override(cx(Some('D'), '-', 'é')), None); + } + + #[test] + fn chromium_suppresses_ascii_punctuation_breaks() { + let t = &CHROMIUM_LINE_BREAK_TABLE; + // No break before or after a slash. + assert_eq!(t.lookup('a', '/'), Some(false)); + assert_eq!(t.lookup('/', 'b'), Some(false)); + // No break around other punctuation. + assert_eq!(t.lookup('a', '.'), Some(false)); + assert_eq!(t.lookup('a', ':'), Some(false)); + // No break between letters. + assert_eq!(t.lookup('a', 'b'), Some(false)); + } + + #[test] + fn chromium_allows_some_breaks() { + let t = &CHROMIUM_LINE_BREAK_TABLE; + // Break allowed before opening punctuation, but only when the preceding + // character's row was not later suppressed. + assert_eq!(t.lookup(')', '('), Some(true)); + assert_eq!(t.lookup(')', '<'), Some(true)); + assert_eq!(t.lookup('a', '('), Some(false)); + // Break allowed after '-' and '?' except when... + assert_eq!(t.lookup('-', 'b'), Some(true)); + assert_eq!(t.lookup('?', 'b'), Some(true)); + // ...break not allowed after '-' before a digit, or '?' before a quote. + assert_eq!(t.lookup('-', '5'), Some(false)); + assert_eq!(t.lookup('?', '"'), Some(false)); + } + + #[test] + fn non_ascii_pairs_defer_to_icu() { + let t = &CHROMIUM_LINE_BREAK_TABLE; + assert_eq!(t.lookup('a', 'é'), None); + assert_eq!(t.lookup('é', 'a'), None); + // Space (0x20) is below the printable range, so it defers too. + assert_eq!(t.lookup('a', ' '), None); + } + + #[test] + fn empty_table_defers_to_icu() { + let t = AsciiLineBreakTableBuilder::new().build::<1>(); + assert_eq!(t.lookup('a', '/'), None); + assert_eq!(t.lookup('a', '('), None); + } + + #[test] + fn dedup_matches_dense_for_chromium() { + let builder = AsciiLineBreakTableBuilder::chromium(); + for b in 0..128_u32 { + for a in 0..128_u32 { + let bit = 1_u128 << a; + let dense = if builder.overridden[b as usize] & bit == 0 { + None + } else { + Some(builder.allow[b as usize] & bit != 0) + }; + let (before, after) = (char::from_u32(b).unwrap(), char::from_u32(a).unwrap()); + assert_eq!( + CHROMIUM_LINE_BREAK_TABLE.lookup(before, after), + dense, + "mismatch at (before={b:#04x}, after={a:#04x})", + ); + } + } + } +} diff --git a/app/vendor/rune/vendor/parley_engine/src/dictionary.rs b/app/vendor/rune/vendor/parley_engine/src/dictionary.rs new file mode 100644 index 0000000..5032d35 --- /dev/null +++ b/app/vendor/rune/vendor/parley_engine/src/dictionary.rs @@ -0,0 +1,134 @@ +// Copyright 2026 the Parley Authors +// SPDX-License-Identifier: Apache-2.0 OR MIT + +//! Word boundaries for the scripts whose words need a dictionary (Thai, Lao, Khmer, Burmese, +//! Chinese and Japanese), from outside Parley (Rune: vendor/parley_engine.patch). A build without +//! `complex-scripts` links none of ICU's dictionaries; a host that has its own (a browser's +//! `Intl.Segmenter`) gives them here. Its boundaries are the words inside each such run and, in +//! Thai, Lao, Khmer and Burmese, the run's line break opportunities too, as ICU's dictionary +//! line segmenter makes them (UAX #14 breaks class SA at word boundaries). + +use alloc::vec::Vec; + +use icu_properties::props::{GeneralCategory, Script}; +use parley_data::Properties; + +/// Appends to `out` the word boundaries strictly inside `text`, as ascending byte offsets, for a +/// `text` all in one dictionary language: `language` is `th`, `lo`, `km`, `my` or `ja` (Han, +/// hiragana and katakana, whose dictionary Chinese and Japanese share). +pub type DictionarySegmenter = fn(text: &str, language: &str, out: &mut Vec<usize>); + +#[cfg(feature = "std")] +static SEGMENTER: std::sync::OnceLock<DictionarySegmenter> = std::sync::OnceLock::new(); + +/// Gives Parley the host's dictionary word boundaries, once (a second call changes nothing). +/// Without `complex-scripts` and without this, a Thai phrase has no break opportunity and a +/// Chinese sentence's words are its characters. Needs `std`. +pub fn set_dictionary_segmenter(segmenter: DictionarySegmenter) { + #[cfg(feature = "std")] + let _ = SEGMENTER.set(segmenter); + #[cfg(not(feature = "std"))] + let _ = segmenter; +} + +fn segmenter() -> Option<DictionarySegmenter> { + #[cfg(all(feature = "std", not(feature = "complex-scripts")))] + return SEGMENTER.get().copied(); + #[cfg(not(all(feature = "std", not(feature = "complex-scripts"))))] + None +} + +/// The dictionary language a character's script asks for, and whether its words are its line +/// break opportunities (class SA). +fn language(script: Script) -> Option<(&'static str, bool)> { + Some(match script { + Script::Thai => ("th", true), + Script::Lao => ("lo", true), + Script::Khmer => ("km", true), + Script::Myanmar => ("my", true), + Script::Han | Script::Hiragana | Script::Katakana => ("ja", false), + _ => return None, + }) +} + +/// A mark, a joiner or a length mark (ー) carries on the run before it. +fn continues(properties: Properties, ch: char) -> bool { + matches!(properties.script(), Script::Inherited) + || matches!( + properties.general_category(), + GeneralCategory::NonspacingMark | GeneralCategory::SpacingMark | GeneralCategory::EnclosingMark + ) + || matches!(ch, '\u{200C}' | '\u{200D}' | '\u{30FC}') +} + +/// The text's dictionary runs and the host's word boundaries inside them. +#[derive(Default)] +pub(crate) struct Words { + /// `(start, end, sa)` byte ranges, ascending. + runs: Vec<(usize, usize, bool)>, + /// Boundaries strictly inside the runs, ascending. + bounds: Vec<usize>, + run: usize, + bound: usize, +} + +impl Words { + pub(crate) fn of(text: &str, properties: impl Fn(char) -> Properties) -> Self { + let Some(segment) = segmenter() else { return Self::default() }; + let mut words = Self::default(); + let mut open: Option<(usize, &'static str, bool)> = None; + let close = |words: &mut Self, start: usize, end: usize, lang: &'static str, sa: bool| { + let run = &text[start..end]; + // A single character has no boundary inside it. + if run.chars().nth(1).is_none() { + return; + } + let mut found = Vec::new(); + segment(run, lang, &mut found); + words.bounds.extend(found.into_iter().filter(|&b| b > 0 && b < run.len() && run.is_char_boundary(b)).map(|b| b + start)); + words.runs.push((start, end, sa)); + }; + for (at, ch) in text.char_indices() { + let props = properties(ch); + if let Some((start, lang, sa)) = open { + if continues(props, ch) || language(props.script()).is_some_and(|(l, _)| l == lang) { + continue; + } + close(&mut words, start, at, lang, sa); + } + open = language(props.script()).map(|(lang, sa)| (at, lang, sa)); + } + if let Some((start, lang, sa)) = open { + close(&mut words, start, text.len(), lang, sa); + } + words + } + + /// The boundaries inside Thai, Lao, Khmer and Burmese runs: their line break opportunities. + /// None with `line-dictionaries`, whose line segmenter finds them itself. + pub(crate) fn line_breaks(&self) -> impl Iterator<Item = usize> + '_ { + let mut run = if cfg!(feature = "line-dictionaries") { self.runs.len() } else { 0 }; + self.bounds.iter().copied().filter(move |&b| { + while self.runs.get(run).is_some_and(|r| r.1 <= b) { + run += 1; + } + self.runs.get(run).is_some_and(|r| r.0 < b && r.2) + }) + } + + /// Inside a run (past its first character), whether `at` is a word boundary; `None` outside + /// one, where the rule-based segmenter decides. Asked in ascending order. + pub(crate) fn word_at(&mut self, at: usize) -> Option<bool> { + while self.runs.get(self.run).is_some_and(|r| r.1 <= at) { + self.run += 1; + } + let run = self.runs.get(self.run)?; + if at <= run.0 { + return None; + } + while self.bounds.get(self.bound).is_some_and(|&b| b < at) { + self.bound += 1; + } + Some(self.bounds.get(self.bound) == Some(&at)) + } +} diff --git a/app/vendor/rune/vendor/parley_engine/src/glyph.rs b/app/vendor/rune/vendor/parley_engine/src/glyph.rs new file mode 100644 index 0000000..f7fd6c0 --- /dev/null +++ b/app/vendor/rune/vendor/parley_engine/src/glyph.rs @@ -0,0 +1,12 @@ +// Copyright 2025 the Parley Authors +// SPDX-License-Identifier: Apache-2.0 OR MIT + +/// Glyph with an offset and advance. +#[derive(Copy, Clone, Default, Debug, PartialEq)] +#[expect(missing_docs, reason = "Deferred")] +pub struct Glyph { + pub id: u32, + pub x: f32, + pub y: f32, + pub advance: f32, +} diff --git a/app/vendor/rune/vendor/parley_engine/src/itemize.rs b/app/vendor/rune/vendor/parley_engine/src/itemize.rs new file mode 100644 index 0000000..1c51d6a --- /dev/null +++ b/app/vendor/rune/vendor/parley_engine/src/itemize.rs @@ -0,0 +1,331 @@ +// Copyright 2026 the Parley Authors +// SPDX-License-Identifier: Apache-2.0 OR MIT + +//! Itemization breaks text into individually-shapeable items. + +use core::{ops::Range, str::CharIndices}; + +use icu_properties::props::Script as IcuScript; +use parlance::{BidiLevel, Script}; + +use crate::{Analysis, CharInfo, ShapeOptions}; + +/// A range of text. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct TextRange { + /// The range of byte offsets. + pub byte_range: Range<usize>, + + /// The range of character indices. + pub char_range: Range<usize>, +} + +/// A span of text inside an [`Item`] with constant script and bidirectional embedding level. +#[derive(Clone, Debug)] +pub struct Segment { + /// The text range of this item. + pub range: TextRange, + + /// The bidi level of characters in this item. + pub bidi_level: BidiLevel, + + /// The script of characters in this item. + /// + /// Characters in the source text that do not have a particular script (i.e., they are one of + /// [`Script::COMMON`], [`Script::UNKNOWN`] or [`Script::INHERITED`]) get their script from + /// surrounding context. Currently, these just inherit the script of the preceding characters. + /// Leading characters without a particular script inherit the script of the first character + /// *with* a particular script. These heuristics may change in the future. For more, see UAX 24 + /// (<https://www.unicode.org/reports/tr24/>) Section 5. + pub script: Script, +} + +/// A span of text shaped with specific [`ShapeOptions`]. +/// +/// An [`Item`] represents a sequence of constant [`ShapeOptions`], but cannot always be passed to +/// the shaper as a single unit. Within an item, the script or bidirectional text embedding level +/// may change, which requires further splitting the item into segments of constant script and bidi +/// level (see [`Segment`]). +#[derive(Debug)] +pub struct Item<'a> { + /// The character offset in the source text which this item ends. + /// + /// This must be strictly greater than the previous item's end. For the first item, it must be + /// greater than 0. + pub char_end: u32, + + /// The options to shape this item with. + // + // TODO: should users instead be allowed to build `options` at the `Segment` level (i.e., + // through some callback)? The motivation is for users to have access to the segment's `Script` + // and be able to set font features based on that. If the entirety of `ShapeOptions` moves + // there, it would allow users to set, e.g., a font size per segment, even though it's not + // necessarily an item boundary; and note an item then doesn't mean a whole lot anymore. We + // could also allow only some options to be per-segment. In any case, we're probably moving + // towards a future where items reset grapheme segmentation, but segments do not (note Gecko and + // Blink also reset grapheme segmentation when something like font size changes, but not when + // the script changes). + pub options: ShapeOptions<'a>, + // TODO: we probably should allow users to pass in some data (like we allow passing + // style_indices elsewhere), which we copy onto `ShapedRun`. That allows users to easily + // correlate `ShapedRun`s with some data they themselves hold. + // + // This is potentially important for better correctness in `parley`: it itemizes based on + // `nearly_eq` of shaping-relevant styles like font size, i.e., it should then read that item's + // style to know the font size, even though it may be different for the run. + // /// Opaque data copied onto every `ShapedRun` produced from this item. + // pub user_data: u16, +} + +/// Produces the items in a text via [`Self::next`]; created by [`Analysis::itemize`]. +#[derive(Debug)] +pub(crate) struct Itemizer<'a> { + /// Our underlying iterator over the input text. + char_indices: CharIndices<'a>, + /// The per-char info, parallel to [`Self::char_indices`]. + char_info: &'a [CharInfo], + /// The per-char bidi level, parallel to [`Self::char_indices`]. + bidi_levels: &'a [BidiLevel], + + /// The paragraph's base bidi level. + /// + /// If [`Self::bidi_levels`] is empty as a special case, this is the bidi level of each + /// character. + paragraph_bidi_level: BidiLevel, + + /// The running character offset of the last-processed item. + current_char_offset: usize, + /// The running script of the last-processed item. + current_script: IcuScript, +} + +impl Analysis { + /// Divide the `text` into individually-shapeable segments. + /// + /// The `text` passed in must be the same as used for producing the `self` analysis. + /// + /// The text is divided into items produced by a predicate passed to [`Itemizer::next`] and + /// further divided into segments of constant bidi level and script. + /// + /// Characters that don't have a particular script have their script resolved based on + /// surrounding context (see [`Segment::script`]). + pub(crate) fn itemize<'a>(&'a self, text: &'a str) -> Itemizer<'a> { + let first_real_script = self + .char_info() + .iter() + .map(|x| x.script) + .find(|&script| real_script(script)) + .unwrap_or(IcuScript::Latin); + + Itemizer { + char_indices: text.char_indices(), + char_info: self.char_info(), + bidi_levels: self.bidi_levels(), + paragraph_bidi_level: self.paragraph_level(), + + current_char_offset: 0, + current_script: first_real_script, + } + } +} + +impl Itemizer<'_> { + /// Produce the next segment, if any. + /// + /// For consecutive characters where the bidi level and script are unchanging, the `split_after` + /// predicate is called with the growing item range, and can be used to split on additional + /// properties like shaping-relevant style changes (e.g., font size) or properties like + /// language. + /// + /// The predicate is given a range encoding the current item and considers whether to split + /// after that item based on the next character. Iff the predicate returns `true`, the text is + /// split after that item; i.e., given a range of `start..end`, the predicate controls whether + /// that item is now finished, or whether it is extended to include the character at `end` (at + /// which point the item spans `start..end+1`). + // + // TODO: currently the items from `split_after` have the same effect as a change in bidi or + // script. This is not how browsers handle things. In particular, `split_after` should reset + // grapheme segmentation, whereas bidi and script should produce separately-shaped segments. + #[inline] + pub(crate) fn next( + &mut self, + mut split_after: impl FnMut(TextRange) -> bool, + ) -> Option<Segment> { + if self.char_info.is_empty() { + // We're already finished. + debug_assert!( + self.char_indices.next().is_none() && self.bidi_levels.is_empty(), + "`char_info`, `bidi_levels`, and `char_indices` should now all be empty \ + (though note `bidi_levels` may already have been empty as a special-case)" + ); + return None; + } + + let mut item_bidi_level = BidiLevel::new(0); // Initialized in the loop. + + let start_byte_offset = self.char_indices.offset(); + let mut item_char_len = 0; + loop { + let byte_offset = self.char_indices.offset(); + + let bidi_level = if self.bidi_levels.is_empty() { + self.paragraph_bidi_level + } else { + self.bidi_levels[0] + }; + let mut script = self.char_info[0].script; + + if !real_script(script) { + // This is a very simple heuristic, where if a character does not have a "real + // script," it inherits the script of the preceding character. UAX 24 paragraph + // 5.1 says this "works well in many cases", but also suggests performing, e.g., + // bracket matching (for example, the parentheses in `hello (αβγ)` should ideally + // both be marked as being `Latin`). At that point, `Itemizer` would probably like + // to have reusable scratch for the bracket stack. + script = self.current_script; + } + + // First iteration of the loop, initialize item properties. + if item_char_len == 0 { + item_bidi_level = bidi_level; + self.current_script = script; + } + + if bidi_level != item_bidi_level || script != self.current_script { + break; + } + + if item_char_len > 0 + && split_after(TextRange { + byte_range: start_byte_offset..byte_offset, + char_range: self.current_char_offset..self.current_char_offset + item_char_len, + }) + { + break; + } + + self.char_indices.next().expect("The passed in `text` was not of the same length as the text used to generate `Analysis`"); + self.char_info = &self.char_info[1..]; + if !self.bidi_levels.is_empty() { + self.bidi_levels = &self.bidi_levels[1..]; + } + + item_char_len += 1; + + if self.char_info.is_empty() { + // The text is now empty, so we're finished. + break; + } + } + + let start_char_offset = self.current_char_offset; + self.current_char_offset += item_char_len; + + Some(Segment { + range: TextRange { + byte_range: start_byte_offset..self.char_indices.offset(), + char_range: start_char_offset..self.current_char_offset, + }, + script: icu_script_to_parlance_script(self.current_script), + bidi_level: item_bidi_level, + }) + } +} + +fn real_script(script: IcuScript) -> bool { + script != IcuScript::Common && script != IcuScript::Unknown && script != IcuScript::Inherited +} + +/// Convert an ICU script into a [`Script`]. +#[inline] +fn icu_script_to_parlance_script(script: IcuScript) -> Script { + static SHORT_NAMES: icu_properties::PropertyNamesShortBorrowed<'static, IcuScript> = + icu_properties::PropertyNamesShort::new(); + + SHORT_NAMES + .get(script) + .and_then(|name| Script::parse(name).ok()) + .unwrap_or(Script::UNKNOWN) +} + +#[cfg(test)] +mod tests { + use alloc::vec::Vec; + use parlance::Script; + + use crate::{Analysis, AnalysisOptions, Analyzer}; + + use super::Segment; + + const LATN: Script = Script::from_bytes(*b"Latn"); + const GREK: Script = Script::from_bytes(*b"Grek"); + const ARAB: Script = Script::from_bytes(*b"Arab"); + + fn analyze(text: &str) -> Analysis { + let mut analyzer = Analyzer::new(); + let mut analysis = Analysis::new(); + let options = AnalysisOptions::default(); + analyzer.analyze(text, &options, &mut analysis); + analysis + } + + fn items(text: &str) -> Vec<Segment> { + let analysis = analyze(text); + let mut itemizer = analysis.itemize(text); + core::iter::from_fn(|| itemizer.next(|_| false)).collect() + } + + #[test] + fn empty() { + assert!(items("").is_empty()); + } + + #[test] + fn mixed_direction() { + let text = "hello مرحبا"; + let items = items(text); + assert!(items.len() >= 2); + assert_eq!(items[0].script, LATN); + assert!(items[0].bidi_level.is_ltr()); + assert!( + items + .iter() + .any(|item| item.script == ARAB && item.bidi_level.is_rtl()) + ); + + // Items tile the text contiguously. + let mut cursor = 0; + for item in &items { + assert_eq!(item.range.byte_range.start, cursor); + cursor = item.range.byte_range.end; + } + assert_eq!(cursor, text.len()); + } + + #[test] + fn predicate() { + let text = "abcdef"; + let analysis = analyze(text); + let mut itemizer = analysis.itemize(text); + let items: Vec<_> = + core::iter::from_fn(|| itemizer.next(|range| range.char_range.end == 3)).collect(); + assert_eq!(items.len(), 2); + assert_eq!(items[0].range.byte_range, 0..3); + assert_eq!(items[0].range.char_range, 0..3); + assert_eq!(items[1].range.byte_range, 3..6); + assert_eq!(items[1].range.char_range, 3..6); + } + + #[test] + fn neutral_backward() { + // Latin, a space (`Common`), then Greek. + let text = "abc αβγ"; + let items = items(text); + assert_eq!(items.len(), 2); + // The space attaches to the Latin run. + assert_eq!(&text[items[0].range.byte_range.clone()], "abc "); + assert_eq!(items[0].script, LATN); + assert_eq!(&text[items[1].range.byte_range.clone()], "αβγ"); + assert_eq!(items[1].script, GREK); + } +} diff --git a/app/vendor/rune/vendor/parley_engine/src/lib.rs b/app/vendor/rune/vendor/parley_engine/src/lib.rs new file mode 100644 index 0000000..ea7d79b --- /dev/null +++ b/app/vendor/rune/vendor/parley_engine/src/lib.rs @@ -0,0 +1,128 @@ +// Copyright 2025 the Parley Authors +// SPDX-License-Identifier: Apache-2.0 OR MIT + +//! Parley Engine provides low level APIs for shaping paragraphs of text. +//! +//! ## Usage +//! +//! Use [`Analyzer`], [`Analysis`], [`Shaper`] and [`ShapedText`] to shape a paragraph of text into +//! glyphs. Correct reshaping of lines is in progress; in the meantime you can break text at +//! [`Atom`] or [`ShapedCluster`][crate::shape::ShapedCluster] boundaries. +//! +//! Text analysis is performed before shaping, and the same source string must be passed to each +//! stage. +//! +//! Higher-level users may prefer using [`parley`][parley], which uses this crate and implements +//! layout and styling. +//! +//! ```rust,no_run +//! # // We only compile this doctest because we don't have a font available. +//! # use parley_engine::{Analysis, AnalysisOptions, Analyzer, FontInstanceRef, FontSelector, ShapedText, ShapeOptions, Shaper}; +//! # use parley_engine::shape::CharCluster; +//! # use parley_engine::itemize::{Item, Segment}; +//! # +//! # struct NoFont; +//! # impl FontSelector for NoFont { +//! # fn select_font( +//! # &mut self, +//! # _segment: &Segment, +//! # _options: &ShapeOptions<'_>, +//! # _cluster: &mut CharCluster, +//! # ) -> Option<FontInstanceRef<'_>> { +//! # unimplemented!() +//! # } +//! # } +//! # +//! # let select_font = NoFont; +//! let mut analysis = Analysis::default(); +//! let mut analyzer = Analyzer::default(); +//! let mut shaped_text = ShapedText::default(); +//! let mut shaper = Shaper::default(); +//! +//! let text = "The quick brown ثعلب jumps over the lazy dog."; +//! let char_count = text.chars().count(); +//! let char_style_indices = vec![0; char_count]; +//! +//! analyzer.analyze(text, &AnalysisOptions::default(), &mut analysis); +//! shaper.shape_text( +//! text, +//! &analysis, +//! &char_style_indices, +//! [Item { +//! char_end: char_count.try_into().unwrap(), +//! options: ShapeOptions { +//! font_size: 16.0, +//! language: None, +//! features: &[], +//! variations: &[], +//! }, +//! }], +//! select_font, // Selects fonts covering each cluster. +//! &mut shaped_text, +//! ); +//! +//! for (run_idx, run) in shaped_text.runs().iter().enumerate() { +//! let slice = shaped_text.run_slice(run_idx as u32); +//! // You can, for example, measure grapheme advances for hit-testing or +//! // placing carets. +//! for atom in slice.atoms_start() { +//! for grapheme in atom.graphemes_start() { +//! std::dbg!(grapheme); +//! } +//! } +//! +//! // Or get glyphs for rendering (for simplicity, this iterates clusters in +//! // logical order, but for rendering you'd want to reorder runs and clusters +//! // according to their `run.bidi_level`). +//! for cluster in slice.shaped_clusters_range() { +//! for glyph in slice.shaped_cluster_glyphs(cluster) { +//! std::dbg!(glyph); +//! } +//! } +//! } +//! ``` +//! +//! ## Features +//! +//! - `std` (enabled by default): This is currently unused and is provided for forward compatibility. +//! - `bytemuck`: Forwarded to [`parlance`], which then implements traits from `bytemuck` on its +//! types. +//! +//! [parley]: https://docs.rs/parley + +// LINEBENDER LINT SET - lib.rs - v3 +// See https://linebender.org/wiki/canonical-lints/ +// These lints shouldn't apply to examples or tests. +#![cfg_attr(not(test), warn(unused_crate_dependencies))] +// These lints shouldn't apply to examples. +#![warn(clippy::print_stdout, clippy::print_stderr)] +// Targeting e.g. 32-bit means structs containing usize can give false positives for 64-bit. +#![cfg_attr(target_pointer_width = "64", warn(clippy::trivially_copy_pass_by_ref))] +// END LINEBENDER LINT SET +#![cfg_attr(docsrs, feature(doc_cfg))] +#![no_std] +#[cfg(feature = "std")] +extern crate std; + +extern crate alloc; + +mod analysis; +mod analyzer; +mod bidi; +pub mod break_overrides; +pub mod dictionary; +pub mod platform; +mod glyph; +pub mod itemize; +mod lru_cache; +pub mod shape; + +pub use linebender_resource_handle::FontData; +pub use parlance::{BaseDirection, NormalizedCoord}; + +pub use analysis::{Analysis, AnalysisDataSources, CharInfo}; +pub use analyzer::{AnalysisOptions, Analyzer, LineBreakConfig}; +pub use glyph::Glyph; +pub use shape::atom::{Atom, Atoms, Grapheme, Graphemes, ShapedClusterGlyphs, ShapedSlice}; +pub use shape::shaped_text::{FontMetrics, ShapedRun, ShapedText}; +pub use shape::shaper::{FontInstance, FontInstanceRef, FontSelector, ShapeOptions, Shaper}; diff --git a/app/vendor/rune/vendor/parley_engine/src/lru_cache.rs b/app/vendor/rune/vendor/parley_engine/src/lru_cache.rs new file mode 100644 index 0000000..592576b --- /dev/null +++ b/app/vendor/rune/vendor/parley_engine/src/lru_cache.rs @@ -0,0 +1,208 @@ +// Copyright 2025 the Parley Authors +// SPDX-License-Identifier: Apache-2.0 OR MIT + +use alloc::vec::Vec; +use hashbrown::Equivalent; + +/// An entry in the cache. +pub(crate) struct Entry<ID, T> { + pub epoch: u64, + pub id: ID, + pub data: T, +} + +/// A least-recently-used cache. This cache uses a linear scan of its entries +/// to find a given entry - it is optimised for a low number of entries. Preferably +/// keep `max_entries` low - in the order of tens. +pub(crate) struct LruCache<ID, T> { + entries: Vec<Entry<ID, T>>, + epoch: u64, + max_entries: usize, +} + +impl<ID, T> LruCache<ID, T> { + pub(crate) fn new(max_entries: usize) -> Self { + Self { + entries: Vec::default(), + epoch: 0, + max_entries, + } + } + + /// Returns a reference to the entry with the given ID. If the entry is not + /// found, it is created and returned using `make_data`. + /// + /// The lookup key must be `Equivalent` to ID for lookups and convertible `Into<ID>` + /// for creating new entries. + pub(crate) fn entry<K>(&mut self, id: K, make_data: impl FnOnce() -> T) -> &T + where + K: Equivalent<ID> + Into<ID>, + { + let index = self.find_entry(id, make_data); + self.epoch += 1; + let entry = &mut self.entries[index]; + entry.epoch = self.epoch; + &entry.data + } + + fn find_entry<K>(&mut self, id: K, make_data: impl FnOnce() -> T) -> usize + where + K: Equivalent<ID> + Into<ID>, + { + let epoch = self.epoch; + let mut lowest_serial = epoch; + let mut lowest_index = 0; + for (i, entry) in self.entries.iter().enumerate() { + if id.equivalent(&entry.id) { + return i; + } + if entry.epoch < lowest_serial { + lowest_serial = entry.epoch; + lowest_index = i; + } + } + if self.entries.len() < self.max_entries { + lowest_index = self.entries.len(); + self.entries.push(Entry { + epoch, + id: id.into(), + data: make_data(), + }); + } else { + let entry = &mut self.entries[lowest_index]; + entry.epoch = epoch; + entry.id = id.into(); + entry.data = make_data(); + } + lowest_index + } +} + +#[cfg(test)] +mod tests { + use super::*; + use alloc::string::{String, ToString}; + + #[derive(Debug, Clone, PartialEq)] + struct TestId(String); + struct TestLookupKey<'a>(&'a str); + + impl<'a> Equivalent<TestId> for TestLookupKey<'a> { + fn equivalent(&self, key: &TestId) -> bool { + self.0 == key.0.as_str() + } + } + + impl<'a> From<TestLookupKey<'a>> for TestId { + fn from(key: TestLookupKey<'a>) -> Self { + Self(key.0.to_string()) + } + } + + impl Equivalent<Self> for TestId { + fn equivalent(&self, key: &Self) -> bool { + self.0 == key.0 + } + } + + #[test] + fn test_retrieve_existing_entry() { + let mut cache = LruCache::new(3); + + // Insert an entry + let value1 = cache.entry(TestLookupKey("key1"), || 42); + assert_eq!(*value1, 42); + + // Retrieve the same entry - make_data should not be called + let value2 = cache.entry(TestLookupKey("key1"), || { + panic!("Should not create new data") + }); + assert_eq!(*value2, 42); + assert_eq!(cache.entries.len(), 1); + } + + #[test] + fn test_multiple_entries() { + let mut cache = LruCache::new(3); + + let value1 = cache.entry(TestLookupKey("key1"), || 1); + assert_eq!(*value1, 1); + + let value2 = cache.entry(TestLookupKey("key2"), || 2); + assert_eq!(*value2, 2); + + let value3 = cache.entry(TestLookupKey("key3"), || 3); + assert_eq!(*value3, 3); + + assert_eq!(cache.entries.len(), 3); + assert_eq!(cache.epoch, 3); + } + + #[test] + fn test_lru_eviction() { + let mut cache = LruCache::new(3); + + // Add three entries + cache.entry(TestLookupKey("key1"), || 1); + cache.entry(TestLookupKey("key2"), || 2); + cache.entry(TestLookupKey("key3"), || 3); + + // Access key1 to update its epoch + cache.entry(TestLookupKey("key1"), || panic!("Should not create")); + + // Add key4 - should evict key2 (oldest untouched) + cache.entry(TestLookupKey("key4"), || 4); + + // Verify key1 is still present + let value1 = cache.entry(TestLookupKey("key1"), || { + panic!("key1 should still be present") + }); + assert_eq!(*value1, 1); + + // Verify key2 was evicted + let mut was_created = false; + cache.entry(TestLookupKey("key2"), || { + was_created = true; + 20 + }); + assert!(was_created, "key2 should have been evicted"); + } + + #[test] + fn test_lru_eviction_after_multiple_hits() { + let mut cache = LruCache::new(3); + + cache.entry(TestLookupKey("key1"), || 1); + cache.entry(TestLookupKey("key2"), || 2); + cache.entry(TestLookupKey("key3"), || 3); + + // Hit all three in order: key3 first (making it LRU among hits), + // then key1, then key2 (most recently used). + cache.entry(TestLookupKey("key3"), || panic!("Should not create")); + cache.entry(TestLookupKey("key1"), || panic!("Should not create")); + cache.entry(TestLookupKey("key2"), || panic!("Should not create")); + + // Insert key4 — should evict key3 (least recently accessed) + cache.entry(TestLookupKey("key4"), || 4); + + // key1 and key2 should still be present with original values + // (check these first since verifying key3 eviction will trigger another eviction) + let v1 = cache.entry(TestLookupKey("key1"), || { + panic!("key1 should still be present") + }); + assert_eq!(*v1, 1); + + let v2 = cache.entry(TestLookupKey("key2"), || { + panic!("key2 should still be present") + }); + assert_eq!(*v2, 2); + + // key3 should have been evicted + let mut key3_recreated = false; + cache.entry(TestLookupKey("key3"), || { + key3_recreated = true; + 30 + }); + assert!(key3_recreated, "key3 should have been evicted as the LRU"); + } +} diff --git a/app/vendor/rune/vendor/parley_engine/src/platform.rs b/app/vendor/rune/vendor/parley_engine/src/platform.rs new file mode 100644 index 0000000..041b9b9 --- /dev/null +++ b/app/vendor/rune/vendor/parley_engine/src/platform.rs @@ -0,0 +1,70 @@ +// Copyright 2026 the Parley Authors +// SPDX-License-Identifier: Apache-2.0 OR MIT + +//! A face of last resort that the platform draws (Rune: vendor/parley_engine.patch). A host that +//! can shape and draw text itself (a browser's canvas, with the system's fonts, shaping and +//! colour emoji) registers a font that covers every character and gives its runs a shaper here. +//! A run in that font isn't shaped by HarfRust: the host gives one glyph per grapheme, its +//! advance measured as the platform lays the run out, and the glyph ids are the host's own, for +//! it to draw them. + +use alloc::vec::Vec; + +/// A run in the platform's face, for its shaper. +#[derive(Debug)] +pub struct PlatformText<'a> { + /// The run's text. + pub text: &'a str, + /// Byte offsets into `text` where each grapheme starts, ascending, the first 0. + pub graphemes: &'a [u32], + /// Byte offsets where each unit the platform draws whole starts (at grapheme starts, between + /// break opportunities), ascending, the first 0. A line never breaks inside one. + pub units: &'a [u32], + /// The font size, in the layout's units. + pub size: f32, + /// The weight asked for (`wght`, 100 to 900). + pub weight: f32, + /// Italic asked for. + pub italic: bool, + /// The run is right to left. + pub rtl: bool, + /// The run's language tag, if it has one. + pub language: Option<&'a str>, +} + +/// One glyph per grapheme of a [`PlatformText`], in logical order. +#[derive(Clone, Copy, Debug, Default)] +pub struct PlatformGlyph { + /// The host's id for what this glyph draws. + pub id: u32, + /// The grapheme's advance, in the layout's units. + pub advance: f32, + /// How far right of its pen the glyph draws, in the layout's units. + pub x_offset: f32, +} + +/// Fills `out` with one glyph per grapheme of the run, in logical order. +pub type PlatformShaper = fn(run: &PlatformText<'_>, out: &mut Vec<PlatformGlyph>); + +#[cfg(feature = "std")] +static PLATFORM: std::sync::OnceLock<(u64, PlatformShaper)> = std::sync::OnceLock::new(); + +/// Makes the font whose data has id `font` (`Blob::id`) the platform's face, shaped by `shaper`, +/// once (a second call changes nothing). Needs `std`. +pub fn set_platform_face(font: u64, shaper: PlatformShaper) { + #[cfg(feature = "std")] + let _ = PLATFORM.set((font, shaper)); + #[cfg(not(feature = "std"))] + let _ = (font, shaper); +} + +/// The shaper for the font with data id `font`, if it's the platform's face. +pub(crate) fn shaper(font: u64) -> Option<PlatformShaper> { + #[cfg(feature = "std")] + return PLATFORM.get().filter(|(id, _)| *id == font).map(|(_, shaper)| *shaper); + #[cfg(not(feature = "std"))] + { + let _ = font; + None + } +} diff --git a/app/vendor/rune/vendor/parley_engine/src/shape/atom.rs b/app/vendor/rune/vendor/parley_engine/src/shape/atom.rs new file mode 100644 index 0000000..fda89d7 --- /dev/null +++ b/app/vendor/rune/vendor/parley_engine/src/shape/atom.rs @@ -0,0 +1,1008 @@ +// Copyright 2026 the Parley Authors +// SPDX-License-Identifier: Apache-2.0 OR MIT + +use core::ops::Range; + +use crate::{Glyph, shape::Whitespace}; + +use super::data::{Character, ShapedCluster}; + +/// A slice of shaped text. +/// +/// Note that character and cluster indices (including those given out by [`Atom`] and [`Grapheme`]) +/// are absolute into the underlying storage. +/// +// NOTE: The motivation for this type, is that once `parley_engine` supports reshaping, this can +// hold reshaped slices that don't depend on `ShapedText`. +#[derive(Copy, Clone, Debug)] +pub struct ShapedSlice<'a> { + /// Characters of shaped text. + /// + /// Most character indices (like [`ShapedCluster::chars_range`]) index into this array. + pub(crate) characters: &'a [Character], + + pub(crate) shaped_clusters: &'a [ShapedCluster], + pub(crate) glyphs: &'a [Glyph], + + /// The range of [`Self::shaped_clusters`] this slice covers. + pub(crate) clusters: (u32, u32), +} + +impl<'a> ShapedSlice<'a> { + /// The character range of this slice. + /// + /// This indexes into [`Self::characters`]. + #[inline(always)] + pub fn char_range(&self) -> Range<u32> { + if self.clusters.0 == self.clusters.1 { + 0..0 + } else { + self.shaped_clusters[self.clusters.0 as usize] + .chars_range() + .start + ..self.shaped_clusters[self.clusters.1 as usize - 1] + .chars_range() + .end + } + } + + /// The [`Character`]s spanned by this shaped slice. + #[inline(always)] + pub fn characters(&self) -> &'a [Character] { + self.characters_in(self.char_range()) + } + + /// The [`Character`]s within this slice spanned by `chars_range`. + /// + /// Note that `chars_range` is an absolute range over the source text. + #[inline(always)] + pub fn characters_in(&self, chars_range: Range<u32>) -> &'a [Character] { + debug_assert!( + chars_range.is_empty() + || (self.char_range().start <= chars_range.start + && chars_range.end <= self.char_range().end), + "character range out of this slice's range" + ); + &self.characters[chars_range.start as usize..chars_range.end as usize] + } + + /// The cluster range of this slice. + /// + /// This indexes into [`Self::shaped_clusters`]. + #[inline(always)] + pub fn shaped_clusters_range(&self) -> Range<u32> { + self.clusters.0..self.clusters.1 + } + + /// The [`ShapedCluster`]s spanned by this shaped slice. + #[inline(always)] + pub fn shaped_clusters(&self) -> &'a [ShapedCluster] { + self.shaped_clusters_in(self.shaped_clusters_range()) + } + + /// The [`ShapedCluster`]s spanned by `clusters_range`. + #[inline(always)] + pub fn shaped_clusters_in(&self, clusters_range: Range<u32>) -> &'a [ShapedCluster] { + debug_assert!( + clusters_range.is_empty() + || (self.clusters.0 <= clusters_range.start + && clusters_range.end <= self.clusters.1), + "cluster range out of this slice's range" + ); + &self.shaped_clusters[clusters_range.start as usize..clusters_range.end as usize] + } + + /// The byte range in the source text of the given range of [`Self::characters`]. + /// + /// If `chars` is empty, this is the empty range at the byte position of `chars.start`; see + /// [`Self::text_byte_at`]. + pub fn text_byte_range(&self, chars: Range<u32>) -> Range<usize> { + if chars.is_empty() { + let pos = self.text_byte_at(chars.start); + return pos..pos; + } + let first = &self.characters[chars.start as usize]; + let last = &self.characters[chars.end as usize - 1]; + first.text_byte_start as usize..last.text_byte_range().end + } + + /// The byte position in the source text of the character boundary at `char_idx`. + /// + /// `char_idx` must be within this slice's [`Self::char_range`]. + #[inline] + pub fn text_byte_at(&self, char_idx: u32) -> usize { + let char_range = self.char_range(); + debug_assert!( + !char_range.is_empty(), + "called `text_byte_at` on an empty slice" + ); + debug_assert!( + char_range.start <= char_idx && char_idx <= char_range.end, + "called `text_byte_at` with a character index out of the slice's range" + ); + if char_idx == char_range.end { + // The character after this boundary is outside this slice. Note that `Self::characters` + // is the full slice of characters that were shaped, so the character after + // `char_range.end` is not necessarily the next character in the source text. We use the + // boundary behind the last character of this slice instead. + self.characters[char_idx as usize - 1].text_byte_range().end + } else { + self.characters[char_idx as usize].text_byte_start as usize + } + } + + /// Get an iterator over glyphs in visual left-to-right order of the shaped cluster with the + /// given index. + #[inline] + pub fn shaped_cluster_glyphs(&self, cluster_idx: u32) -> ShapedClusterGlyphs<'a> { + debug_assert!( + self.clusters.0 <= cluster_idx && cluster_idx < self.clusters.1, + "cluster index out of this slice's range" + ); + + let shaped_cluster = self.shaped_clusters[cluster_idx as usize]; + + if shaped_cluster.has_inline_glyph() { + ShapedClusterGlyphs { + inline: Some(Glyph { + id: shaped_cluster.glyph_offset, + x: 0., + y: 0., + advance: shaped_cluster.advance, + }), + stored: [].iter(), + } + } else { + let start = shaped_cluster.glyph_offset as usize; + ShapedClusterGlyphs { + inline: None, + stored: self.glyphs[start..start + usize::from(shaped_cluster.glyph_len())].iter(), + } + } + } + + /// Get a cursor to walk atoms from the logical start of this slice. + /// + /// The cursor cannot go outside this slice, so the first step can only be taken forwards. + /// Immediately going backwards will return `None`. + #[inline(always)] + pub fn atoms_start(&self) -> Atoms<'a> { + self.atoms_from(self.clusters.0) + } + + /// Get a cursor to walk atoms from the logical end of this slice. + /// + /// The cursor cannot go outside this slice, so the first step can only be taken backwards. + /// Immediately going forwards will return `None`. + #[inline(always)] + pub fn atoms_end(&self) -> Atoms<'a> { + self.atoms_from(self.clusters.1) + } + + /// Get a cursor to walk atoms of this slice, starting at the atom boundary at `cluster`. + /// + /// `cluster` indexes into [`Self::shaped_clusters`], must be either a cluster of this slice or + /// the end of the slice, and must be an atom boundary (i.e., + /// [`ShapedCluster::is_grapheme_start`] must be `true`). + /// + /// To find the atom containing an arbitrary position, use [`Self::atom_at_char`] or + /// [`Self::atom_at_text_byte`] instead. + #[inline(always)] + pub fn atoms_from(&self, cluster: u32) -> Atoms<'a> { + debug_assert!( + self.clusters.0 <= cluster && cluster <= self.clusters.1, + "cluster out of this slice's range" + ); + debug_assert!( + cluster == self.clusters.0 + || cluster == self.clusters.1 + || self.shaped_clusters[cluster as usize].is_grapheme_start(), + "cluster is not an atom boundary" + ); + Atoms { + slice: *self, + cluster_idx: cluster, + } + } + + /// Get the atom containing the character at `char_index`. + /// + /// `char_index` is a character index into the source text (in the Unicode scalar value sense). + /// + /// To start walking from the returned atom, call [`Atom::cursor_before`] or + /// [`Atom::cursor_after`]. + #[inline] + #[expect(clippy::cast_possible_truncation, reason = "deferred")] + pub fn atom_at_char(&self, char_index: u32) -> Option<Atom<'a>> { + let shaped_clusters = + &self.shaped_clusters[self.clusters.0 as usize..self.clusters.1 as usize]; + + let idx = shaped_clusters + .partition_point(|cluster| cluster.chars_range().start <= char_index) + .checked_sub(1)?; + if shaped_clusters[idx].chars_range().end <= char_index { + return None; + } + + let mut idx = idx as u32; + idx += self.clusters.0; + while idx > self.clusters.0 && !self.shaped_clusters[idx as usize].is_grapheme_start() { + idx -= 1; + } + + Some(self.atoms_from(idx).next().unwrap()) + } + + /// Get the atom containing the character at `text_byte`. + /// + /// `text_byte` is a byte into the source text. + /// + /// To start walking from the returned atom, call [`Atom::cursor_before`] or + /// [`Atom::cursor_after`]. + #[inline] + #[expect(clippy::cast_possible_truncation, reason = "deferred")] + pub fn atom_at_text_byte(&self, text_byte: u32) -> Option<Atom<'a>> { + let shaped_clusters = + &self.shaped_clusters[self.clusters.0 as usize..self.clusters.1 as usize]; + + let idx = shaped_clusters + .partition_point(|cluster| { + self.characters[cluster.chars_range().start as usize].text_byte_start <= text_byte + }) + .checked_sub(1)?; + let last_character = self.characters[shaped_clusters[idx].chars_range().end as usize - 1]; + if last_character.text_byte_range().end <= text_byte as usize { + return None; + } + + let mut idx = idx as u32; + idx += self.clusters.0; + while idx > self.clusters.0 && !self.shaped_clusters[idx as usize].is_grapheme_start() { + idx -= 1; + } + + Some(self.atoms_from(idx).next().unwrap()) + } + + /// Narrow the shaped slice to the given range of clusters. + /// + /// The range indexes into [`Self::shaped_clusters`], must be a subrange of + /// [`Self::shaped_clusters_range`], and both bounds must be an atom boundary (i.e., + /// [`ShapedCluster::is_grapheme_start`] must be `true`). + #[inline(always)] + pub fn narrow(&self, clusters: Range<u32>) -> Self { + debug_assert!( + clusters.start <= clusters.end, + "narrowed cluster range is inverted" + ); + debug_assert!( + self.clusters.0 <= clusters.start && clusters.end <= self.clusters.1, + "narrowed cluster range out of this slice's range" + ); + debug_assert!( + clusters.is_empty() + || ((clusters.start == self.clusters.0 + || self.shaped_clusters[clusters.start as usize].is_grapheme_start()) + && (clusters.end == self.clusters.1 + || self.shaped_clusters[clusters.end as usize].is_grapheme_start())), + "narrowed cluster range is not atom-aligned" + ); + Self { + clusters: (clusters.start, clusters.end), + ..*self + } + } + + /// Get a cursor to walk graphemes from the logical start of this slice. + #[inline] + pub fn graphemes_start(&self) -> Graphemes<'a> { + let char_range = self.char_range(); + let cluster_idx = self.clusters.0; + Graphemes { + slice: *self, + char_idx: char_range.start, + cluster_idx, + partial_advance: self.partial_advance_at(cluster_idx), + } + } + + /// Get a cursor to walk graphemes from the logical end of this slice. + #[inline] + pub fn graphemes_end(&self) -> Graphemes<'a> { + let char_range = self.char_range(); + let cluster_idx = self.clusters.1.max(self.clusters.0 + 1) - 1; + Graphemes { + slice: *self, + // char_range, + char_idx: char_range.end, + cluster_idx, + partial_advance: self.partial_advance_at(cluster_idx), + } + } + + #[inline(always)] + fn partial_advance_at(&self, cluster_idx: u32) -> f32 { + if self.clusters.0 == self.clusters.1 { + return 0.0; + } + let cluster = &self.shaped_clusters[cluster_idx as usize]; + cluster.advance / cluster.graphemes_overlapped(self.characters) as f32 + } +} + +/// An iterator over the glyphs of a single [`ShapedCluster`], in visual left-to-right order. +/// +/// See [`ShapedSlice::shaped_cluster_glyphs`]. The default value yields no glyphs. +#[derive(Clone, Debug)] +pub struct ShapedClusterGlyphs<'a> { + /// The cluster's glyph if it is stored inline. + inline: Option<Glyph>, + /// The cluster's glyphs in the glyph array. + stored: core::slice::Iter<'a, Glyph>, +} + +impl ShapedClusterGlyphs<'static> { + /// An empty iterator that does not return any glyphs. + /// + /// This can be used to store a value of this type before actually having access to any shaped + /// clusters. + pub fn empty() -> Self { + Self { + inline: None, + stored: [].iter(), + } + } +} + +impl Iterator for ShapedClusterGlyphs<'_> { + type Item = Glyph; + + #[inline] + fn next(&mut self) -> Option<Glyph> { + if let Some(glyph) = self.inline.take() { + return Some(glyph); + } + self.stored.next().copied() + } + + #[inline] + fn nth(&mut self, n: usize) -> Option<Glyph> { + match self.inline.take() { + Some(glyph) if n == 0 => Some(glyph), + Some(_) => self.stored.nth(n - 1).copied(), + None => self.stored.nth(n).copied(), + } + } + + #[inline] + fn size_hint(&self) -> (usize, Option<usize>) { + let len = usize::from(self.inline.is_some()) + self.stored.len(); + (len, Some(len)) + } +} + +impl ExactSizeIterator for ShapedClusterGlyphs<'_> {} + +/// An [`Atom`] cursor. +/// +/// This cursor can walk forwards and backwards over atoms. +#[derive(Copy, Clone, Debug)] +pub struct Atoms<'a> { + slice: ShapedSlice<'a>, + + /// The gap we're pointing at. + cluster_idx: u32, +} + +impl<'a> Atoms<'a> { + /// Get the atom logically preceding the cursor. + /// + /// See also [`Self::next`]. + #[inline] + pub fn prev(&mut self) -> Option<Atom<'a>> { + let end = self.cluster_idx; + let bound = self.slice.clusters.0; + if end == bound { + return None; + } + + let mut idx = end - 1; + let mut advance = self.slice.shaped_clusters[idx as usize].advance; + while idx > bound && !self.slice.shaped_clusters[idx as usize].is_grapheme_start() { + idx -= 1; + advance += self.slice.shaped_clusters[idx as usize].advance; + } + self.cluster_idx = idx; + Some(Atom { + slice: self.slice, + clusters: (idx, end), + chars: ( + self.slice.shaped_clusters[idx as usize].chars_range().start, + self.slice.shaped_clusters[end as usize - 1] + .chars_range() + .end, + ), + advance, + }) + } + + /// Walk the cursor backwards as an iterator. + #[inline(always)] + pub fn rev(mut self) -> impl Iterator<Item = Atom<'a>> + Clone + use<'a> { + core::iter::from_fn(move || self.prev()) + } +} + +impl<'a> Iterator for Atoms<'a> { + type Item = Atom<'a>; + + /// Get the atom logically following the cursor. + /// + /// See also [`Self::prev`]. + #[inline] + fn next(&mut self) -> Option<Atom<'a>> { + let start = self.cluster_idx; + let bound = self.slice.clusters.1; + if start == bound { + return None; + } + + let mut advance = self.slice.shaped_clusters[start as usize].advance; + let mut idx = start + 1; + while idx < bound && !self.slice.shaped_clusters[idx as usize].is_grapheme_start() { + advance += self.slice.shaped_clusters[idx as usize].advance; + idx += 1; + } + self.cluster_idx = idx; + Some(Atom { + slice: self.slice, + clusters: (start, idx), + chars: ( + self.slice.shaped_clusters[start as usize] + .chars_range() + .start, + self.slice.shaped_clusters[idx as usize - 1] + .chars_range() + .end, + ), + advance, + }) + } +} + +/// An atom of shaped text. +/// +/// This is smallest span of text where both edges are a [`Grapheme`] boundary and [`ShapedCluster`] +/// boundary. +/// +/// An atom cannot be broken without reshaping. Check [`Self::is_safe_to_break_before`] to see if +/// you can break the text before this atom without requiring reshaping. +#[derive(Copy, Clone, Debug)] +pub struct Atom<'a> { + slice: ShapedSlice<'a>, + + /// The clusters this atom spans inside [`ShapedSlice::shaped_clusters`]. + clusters: (u32, u32), + + /// The characters this atom spans inside [`ShapedSlice::characters`]. + chars: (u32, u32), + + advance: f32, +} +impl<'a> Atom<'a> { + /// The range of characters into the underlying [`ShapedSlice`] this atom spans. + /// + /// You can use [`ShapedSlice::text_byte_range`] to turn this into a byte range of the source + /// text. + pub fn char_range(&self) -> Range<u32> { + self.chars.0..self.chars.1 + } + + /// The [`Character`]s from the underlying [`ShapedSlice`] this atom spans. + #[inline(always)] + pub fn characters(&self) -> &'a [Character] { + self.slice.characters_in(self.char_range()) + } + + /// The range of [`ShapedCluster`] into the underlying [`ShapedSlice`] this atom spans. + #[inline(always)] + pub fn shaped_clusters_range(&self) -> Range<u32> { + self.clusters.0..self.clusters.1 + } + + /// The [`ShapedCluster`]s from the underlying [`ShapedSlice`] this atom spans. + #[inline(always)] + pub fn shaped_clusters(&self) -> &'a [ShapedCluster] { + self.slice.shaped_clusters_in(self.shaped_clusters_range()) + } + + /// This atom as a [`ShapedSlice`]. + #[inline(always)] + pub fn slice(&self) -> ShapedSlice<'a> { + ShapedSlice { + clusters: self.clusters, + ..self.slice + } + } + + /// Get a cursor to walk graphemes from the logical start of this atom. + #[inline(always)] + pub fn graphemes_start(&self) -> Graphemes<'a> { + self.slice().graphemes_start() + } + + /// Get a cursor to walk graphemes from the logical end of this atom. + #[inline(always)] + pub fn graphemes_end(&self) -> Graphemes<'a> { + self.slice().graphemes_end() + } + + /// Whether there is a soft wrap opportunity logically before this atom. + #[inline(always)] + pub fn is_soft_wrap_opportunity_before(&self) -> bool { + self.slice.characters[self.chars.0 as usize] + .flags + .is_soft_wrap_opportunity() + } + + /// Whether the atom can be broken + #[inline(always)] + pub fn is_safe_to_break_before(&self) -> bool { + self.slice.shaped_clusters[self.clusters.0 as usize].is_safe_to_break_before() + } + + /// The atom's total advance. + /// + /// This is the sum of the atom's clusters' advances. + #[inline(always)] + pub fn advance(&self) -> f32 { + self.advance + } + + /// Get a cursor to walk atoms, starting logically before this atom. + pub fn cursor_before(&self) -> Atoms<'a> { + Atoms { + slice: self.slice, + cluster_idx: self.clusters.0, + } + } + + /// Get a cursor to walk atoms, starting logically after this atom. + pub fn cursor_after(&self) -> Atoms<'a> { + Atoms { + slice: self.slice, + cluster_idx: self.clusters.1, + } + } +} + +/// A [`Grapheme`] cursor. +/// +/// This cursor can walk forwards and backwards over graphemes. +#[derive(Copy, Clone, Debug)] +pub struct Graphemes<'a> { + slice: ShapedSlice<'a>, + + /// The gap we're pointing at into [`ShapedSlice::characters`]. + char_idx: u32, + + /// The gap we're pointing at into [`ShapedSlice::shaped_clusters`]. + cluster_idx: u32, + + /// The partial advance of `cluster_idx` shared among the graphemes it overlaps. + partial_advance: f32, +} + +impl<'a> Graphemes<'a> { + /// Get the grapheme logically preceding the cursor. + /// + /// See also [`Self::next`]. + #[inline] + pub fn prev(&mut self) -> Option<Grapheme> { + let char_start = self.slice.char_range().start; + if self.char_idx == char_start { + return None; + } + let grapheme_end = self.char_idx; + let mut idx = grapheme_end - 1; + if idx + < self.slice.shaped_clusters[self.cluster_idx as usize] + .chars_range() + .start + { + self.cluster_idx -= 1; + self.partial_advance = self.slice.partial_advance_at(self.cluster_idx); + } + let is_atom_end = grapheme_end + == self.slice.shaped_clusters[self.cluster_idx as usize] + .chars_range() + .end; + let mut advance = self.partial_advance; + while idx > char_start && !self.slice.characters[idx as usize].grapheme_start { + idx -= 1; + if idx + < self.slice.shaped_clusters[self.cluster_idx as usize] + .chars_range() + .start + { + // The grapheme continues into the preceding cluster. + self.cluster_idx -= 1; + self.partial_advance = self.slice.partial_advance_at(self.cluster_idx); + advance += self.partial_advance; + } + } + let is_atom_start = idx == char_start + || idx + == self.slice.shaped_clusters[self.cluster_idx as usize] + .chars_range() + .start; + let first_char = self.slice.characters[idx as usize]; + self.char_idx = idx; + Some(Grapheme { + chars: (idx, grapheme_end), + advance, + flags: GraphemeFlags::new( + first_char.flags.is_soft_wrap_opportunity(), + first_char.whitespace, + is_atom_start, + is_atom_end, + ), + }) + } +} + +impl<'a> Iterator for Graphemes<'a> { + type Item = Grapheme; + + /// Get the grapheme logically following the cursor. + /// + /// See also [`Self::prev`]. + fn next(&mut self) -> Option<Grapheme> { + let char_end = self.slice.char_range().end; + if self.char_idx == char_end { + return None; + } + let grapheme_start = self.char_idx; + let is_atom_start = grapheme_start + == self.slice.shaped_clusters[self.cluster_idx as usize] + .chars_range() + .start; + + let mut advance = self.partial_advance; + let mut idx = grapheme_start + 1; + while idx < char_end && !self.slice.characters[idx as usize].grapheme_start { + if idx + == self.slice.shaped_clusters[self.cluster_idx as usize] + .chars_range() + .end + { + // The grapheme continues into the next cluster. + self.cluster_idx += 1; + self.partial_advance = self.slice.partial_advance_at(self.cluster_idx); + advance += self.partial_advance; + } + idx += 1; + } + // If we stopped exactly on a cluster edge, the next cluster's share + // belongs to the *next* grapheme: advance the lockstep without taking it. + let is_atom_end = idx == char_end + || idx + == self.slice.shaped_clusters[self.cluster_idx as usize] + .chars_range() + .end; + if idx < char_end + && idx + == self.slice.shaped_clusters[self.cluster_idx as usize] + .chars_range() + .end + { + self.cluster_idx += 1; + self.partial_advance = self.slice.partial_advance_at(self.cluster_idx); + } + let first_char = self.slice.characters[grapheme_start as usize]; + self.char_idx = idx; + Some(Grapheme { + chars: (grapheme_start, idx), + advance, + flags: GraphemeFlags::new( + first_char.flags.is_soft_wrap_opportunity(), + first_char.whitespace, + is_atom_start, + is_atom_end, + ), + }) + } + + #[inline] + fn size_hint(&self) -> (usize, Option<usize>) { + ( + 0, + Some(self.slice.characters.len() - self.char_idx as usize), + ) + } +} + +#[derive(Clone, Copy, Debug, PartialEq)] +struct GraphemeFlags(u16); + +impl GraphemeFlags { + const SOFT_WRAP_OPPORTUNITY: u16 = 1 << 0; + const WHITESPACE_SHIFT: u16 = 1; + const WHITESPACE_MASK: u16 = 0b111 << Self::WHITESPACE_SHIFT; + const ATOM_START: u16 = 1 << 4; + const ATOM_END: u16 = 1 << 5; + + // TODO: do we want to expose safe to break? + // const SAFE_TO_BREAK_BEFORE: u16 = 1 << 6; +} + +impl GraphemeFlags { + #[inline(always)] + fn new( + is_soft_wrap_opportunity: bool, + whitespace: Whitespace, + atom_start: bool, + atom_end: bool, + ) -> Self { + Self( + if is_soft_wrap_opportunity { + Self::SOFT_WRAP_OPPORTUNITY + } else { + 0 + } | ((whitespace as u16) << Self::WHITESPACE_SHIFT) + | if atom_start { Self::ATOM_START } else { 0 } + | if atom_end { Self::ATOM_END } else { 0 }, + ) + } + + #[inline(always)] + fn is_soft_wrap_opportunity_before(self) -> bool { + self.0 & Self::SOFT_WRAP_OPPORTUNITY != 0 + } + + #[inline(always)] + fn whitespace(self) -> Whitespace { + match (self.0 & Self::WHITESPACE_MASK) >> Self::WHITESPACE_SHIFT { + 0 => Whitespace::None, + 1 => Whitespace::Space, + 2 => Whitespace::NoBreakSpace, + 3 => Whitespace::IdeographicSpace, + 4 => Whitespace::OtherSpaceSeparator, + 5 => Whitespace::Tab, + 6 => Whitespace::Newline, + 7 => Whitespace::ControlWhitespace, + _ => unreachable!("0..8 are the only valid values"), + } + } + + #[inline(always)] + fn is_atom_start(self) -> bool { + self.0 & Self::ATOM_START != 0 + } + + #[inline(always)] + fn is_atom_end(self) -> bool { + self.0 & Self::ATOM_END != 0 + } +} + +/// A grapheme of shaped text. +/// +/// This encodes extended grapheme clusters as in [UAX #29 § 3][uax-grapheme]. +/// +/// Graphemes usually are the units of caret movement, selection, and hit testing. A grapheme's +/// edges are not necessarily [`ShapedCluster`] edges: +/// +/// - a cluster can span multiple graphemes (e.g. a ligature) +/// - where [`ShapedCluster::advance`] is split evenly over the graphemes it overlaps. +/// - a grapheme can span multiple shaped clusters, due to shaping with `harfrust`'s +/// [monotone characters cluster level][monotone-characters] +/// - where [`Self::advance`] is the sum of shaped cluster advances. +/// +/// A combination of these is also possible, e.g., a grapheme containing multiple shaped clusters +/// and crossing a shaped cluster boundary on one or both sides. +/// +/// [uax-grapheme]: https://www.unicode.org/reports/tr29/#Grapheme_Cluster_Boundaries +/// [monotone-characters]: https://harfbuzz.github.io/working-with-harfbuzz-clusters.html +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Grapheme { + /// The characters this grapheme spans inside [`ShapedSlice::characters`]. + chars: (u32, u32), + + advance: f32, + flags: GraphemeFlags, +} + +impl Grapheme { + /// The range of characters into the underlying [`ShapedSlice`] this grapheme spans. + pub fn char_range(&self) -> Range<u32> { + self.chars.0..self.chars.1 + } + + /// The advance of the grapheme. + /// + /// This is the sum of the grapheme's clusters advances. If clusters cross the boundaries of + /// this grapheme, this includes partial cluster advances. A cluster's advance is split evenly + /// over the graphemes it overlaps. + #[inline(always)] + pub fn advance(&self) -> f32 { + self.advance + } + + /// Whether there is a soft wrap opportunity logically before this grapheme. + #[inline(always)] + pub fn is_soft_wrap_opportunity_before(&self) -> bool { + self.flags.is_soft_wrap_opportunity_before() + } + + /// The whitespace class of this grapheme's first logical character. + #[inline(always)] + pub fn whitespace(&self) -> Whitespace { + self.flags.whitespace() + } + + /// Whether this grapheme's logical start is also the logical start of an [`Atom`]. + #[inline(always)] + pub fn is_atom_start(&self) -> bool { + self.flags.is_atom_start() + } + + /// Whether this grapheme's logical end is also the logical end of an [`Atom`]. + #[inline(always)] + pub fn is_atom_end(&self) -> bool { + self.flags.is_atom_end() + } +} + +#[cfg(test)] +mod tests { + use alloc::{sync::Arc, vec}; + + use fontique::Synthesis; + use linebender_resource_handle::{Blob, FontData}; + + use crate::{ + Analysis, AnalysisOptions, Analyzer, FontInstance, FontInstanceRef, FontSelector, + ShapeOptions, ShapedText, Shaper, + itemize::{Item, Segment}, + shape::CharCluster, + }; + + const ROBOTO: &[u8] = + include_bytes!("../../../parley_dev/assets/fonts/roboto_fonts/Roboto-Regular.ttf"); + + /// A [`FontSelector`] shaping everything with a single font. + struct SingleFont(FontInstance); + + impl FontSelector for SingleFont { + fn select_font( + &mut self, + _segment: &Segment, + _options: &ShapeOptions<'_>, + _cluster: &mut CharCluster, + ) -> Option<FontInstanceRef<'_>> { + Some(self.0.as_ref()) + } + } + + fn analyze(text: &str) -> Analysis { + let mut analysis = Analysis::new(); + Analyzer::new().analyze( + text, + &AnalysisOptions { + line_break: &[], + line_break_override: None, + ..AnalysisOptions::default() + }, + &mut analysis, + ); + analysis + } + + fn font_instance(font_data: &'static [u8]) -> FontInstance { + FontInstance { + font: FontData::new(Blob::new(Arc::new(font_data)), 0), + synthesis: Synthesis::default(), + } + } + + fn shape_with_font(text: &str, font_data: &'static [u8]) -> ShapedText { + let analysis = analyze(text); + let font = font_instance(font_data); + let mut shaper = Shaper::default(); + let mut shaped = ShapedText::new(); + + let char_style_indices = vec![0; text.chars().count()]; + let items = [Item { + char_end: text.chars().count().try_into().unwrap(), + options: ShapeOptions { + font_size: 32.0, + language: None, + features: &[], + variations: &[], + }, + }]; + shaper.shape_text( + text, + &analysis, + &char_style_indices, + items, + SingleFont(font), + &mut shaped, + ); + shaped + } + + #[test] + fn select_atom_at() { + let shaped = shape_with_font("ffi éa\u{0301}", ROBOTO); + // byte offsets: 0123467 ..9 + // chars: 0123456 ..7 + // clusters: 0001233 ..4 + + let slice = shaped.run_slice(0); + assert_eq!(slice.atom_at_char(0).unwrap().shaped_clusters_range(), 0..1); + assert_eq!(slice.atom_at_char(1).unwrap().shaped_clusters_range(), 0..1); + assert_eq!(slice.atom_at_char(2).unwrap().shaped_clusters_range(), 0..1); + assert_eq!(slice.atom_at_char(3).unwrap().shaped_clusters_range(), 1..2); + assert!(slice.atom_at_char(8).is_none()); + + assert_eq!( + slice.atom_at_text_byte(0).unwrap().shaped_clusters_range(), + 0..1 + ); + assert_eq!( + slice.atom_at_text_byte(1).unwrap().shaped_clusters_range(), + 0..1 + ); + assert_eq!( + slice.atom_at_text_byte(2).unwrap().shaped_clusters_range(), + 0..1 + ); + assert_eq!( + slice.atom_at_text_byte(3).unwrap().shaped_clusters_range(), + 1..2 + ); + assert_eq!( + slice.atom_at_text_byte(4).unwrap().shaped_clusters_range(), + 2..3 + ); + assert_eq!( + slice.atom_at_text_byte(5).unwrap().shaped_clusters_range(), + 2..3 + ); + assert_eq!( + slice.atom_at_text_byte(6).unwrap().shaped_clusters_range(), + 3..4 + ); + assert_eq!( + slice.atom_at_text_byte(7).unwrap().shaped_clusters_range(), + 3..4 + ); + assert_eq!( + slice.atom_at_text_byte(8).unwrap().shaped_clusters_range(), + 3..4 + ); + assert!(slice.atom_at_text_byte(9).is_none()); + } + + #[test] + fn text_byte_positions() { + let shaped = shape_with_font("ffi éa\u{0301}", ROBOTO); + // byte offsets: 0123467 ..9 + // chars: 0123456 ..7 + + let slice = shaped.run_slice(0); + assert_eq!(slice.text_byte_range(0..3), 0..3); + assert_eq!(slice.text_byte_range(4..5), 4..6); + assert_eq!(slice.text_byte_range(0..7), 0..9); + + assert_eq!(slice.text_byte_range(3..3), 3..3); + assert_eq!(slice.text_byte_range(7..7), 9..9); + + assert_eq!(slice.text_byte_at(0), 0); + assert_eq!(slice.text_byte_at(4), 4); + assert_eq!(slice.text_byte_at(6), 7); + assert_eq!(slice.text_byte_at(7), 9); + } +} diff --git a/app/vendor/rune/vendor/parley_engine/src/shape/cache.rs b/app/vendor/rune/vendor/parley_engine/src/shape/cache.rs new file mode 100644 index 0000000..530b919 --- /dev/null +++ b/app/vendor/rune/vendor/parley_engine/src/shape/cache.rs @@ -0,0 +1,215 @@ +// Copyright 2025 the Parley Authors +// SPDX-License-Identifier: Apache-2.0 OR MIT + +use alloc::boxed::Box; +use hashbrown::Equivalent; +use parlance::FontVariation; + +#[derive(PartialEq, Copy, Clone)] +pub(crate) struct ShapeDataKey { + /// The font collection's blob ID. + font_blob_id: u64, + /// The font's index in the font collection. + font_index: u32, +} + +impl ShapeDataKey { + pub(crate) const fn new(font_blob_id: u64, font_index: u32) -> Self { + Self { + font_blob_id, + font_index, + } + } +} + +impl Equivalent<Self> for ShapeDataKey { + #[inline(always)] + fn equivalent(&self, key: &Self) -> bool { + self == key + } +} + +impl From<&Self> for ShapeDataKey { + #[inline(always)] + fn from(key: &Self) -> Self { + *key + } +} + +pub(crate) struct ShapeInstanceId { + /// The font collection's blob ID. + font_blob_id: u64, + /// The font's index in the font collection. + font_index: u32, + synthesis: fontique::Synthesis, + variations: Option<Box<[FontVariation]>>, +} + +pub(crate) struct ShapeInstanceKey<'a> { + /// The font collection's blob ID. + font_blob_id: u64, + /// The font's index in the font collection. + font_index: u32, + synthesis: &'a fontique::Synthesis, + variations: Option<&'a [FontVariation]>, +} + +impl<'a> ShapeInstanceKey<'a> { + pub(crate) const fn new( + font_blob_id: u64, + font_index: u32, + synthesis: &'a fontique::Synthesis, + variations: Option<&'a [FontVariation]>, + ) -> Self { + Self { + font_blob_id, + font_index, + synthesis, + variations, + } + } +} + +impl<'a> Equivalent<ShapeInstanceId> for ShapeInstanceKey<'a> { + #[inline(always)] + fn equivalent(&self, key: &ShapeInstanceId) -> bool { + self.font_blob_id == key.font_blob_id + && self.font_index == key.font_index + && *self.synthesis == key.synthesis + && self.variations == key.variations.as_deref() + } +} + +impl<'a> From<ShapeInstanceKey<'a>> for ShapeInstanceId { + #[inline(always)] + fn from(key: ShapeInstanceKey<'a>) -> Self { + Self { + font_blob_id: key.font_blob_id, + font_index: key.font_index, + synthesis: *key.synthesis, + variations: key.variations.map(|v| v.to_vec().into()), + } + } +} + +/// A shaped run's font metrics: its font instance at a size (Rune: vendor/parley_engine.patch). +pub(crate) struct RunMetricsId { + instance: ShapeInstanceId, + font_size: u32, +} + +pub(crate) struct RunMetricsKey<'a> { + instance: ShapeInstanceKey<'a>, + font_size: f32, +} + +impl<'a> RunMetricsKey<'a> { + pub(crate) const fn new(instance: ShapeInstanceKey<'a>, font_size: f32) -> Self { + Self { + instance, + font_size, + } + } +} + +impl<'a> Equivalent<RunMetricsId> for RunMetricsKey<'a> { + #[inline(always)] + fn equivalent(&self, key: &RunMetricsId) -> bool { + self.font_size.to_bits() == key.font_size && self.instance.equivalent(&key.instance) + } +} + +impl<'a> From<RunMetricsKey<'a>> for RunMetricsId { + #[inline(always)] + fn from(key: RunMetricsKey<'a>) -> Self { + Self { + instance: key.instance.into(), + font_size: key.font_size.to_bits(), + } + } +} + +pub(crate) struct ShapePlanId { + /// The font collection's blob ID. + font_blob_id: u64, + /// The font's index in the font collection. + font_index: u32, + synthesis: fontique::Synthesis, + direction: harfrust::Direction, + script: harfrust::Script, + language: Option<harfrust::Language>, + features: Box<[harfrust::Feature]>, + variations: Option<Box<[FontVariation]>>, +} + +pub(crate) struct ShapePlanKey<'a> { + /// The font collection's blob ID. + font_blob_id: u64, + /// The font's index in the font collection. + font_index: u32, + synthesis: &'a fontique::Synthesis, + direction: harfrust::Direction, + script: harfrust::Script, + language: Option<harfrust::Language>, + features: &'a [harfrust::Feature], + variations: Option<&'a [FontVariation]>, +} + +impl<'a> ShapePlanKey<'a> { + pub(crate) const fn new( + font_blob_id: u64, + font_index: u32, + synthesis: &'a fontique::Synthesis, + direction: harfrust::Direction, + script: harfrust::Script, + language: Option<harfrust::Language>, + features: &'a [harfrust::Feature], + variations: Option<&'a [FontVariation]>, + ) -> Self { + Self { + font_blob_id, + font_index, + synthesis, + direction, + script, + language, + features, + variations, + } + } +} + +impl<'a> Equivalent<ShapePlanId> for ShapePlanKey<'a> { + #[inline(always)] + fn equivalent(&self, key: &ShapePlanId) -> bool { + self.font_blob_id == key.font_blob_id + && self.font_index == key.font_index + && *self.synthesis == key.synthesis + && self.direction == key.direction + && self.script == key.script + && self.language == key.language + && self.features.len() == key.features.len() + && self.variations == key.variations.as_deref() + && self + .features + .iter() + .zip(key.features.iter()) + .all(|(a, b)| a == b) + } +} + +impl<'a> From<ShapePlanKey<'a>> for ShapePlanId { + #[inline(always)] + fn from(key: ShapePlanKey<'a>) -> Self { + Self { + font_blob_id: key.font_blob_id, + font_index: key.font_index, + synthesis: *key.synthesis, + direction: key.direction, + script: key.script, + language: key.language, + features: key.features.to_vec().into(), + variations: key.variations.map(|v| v.to_vec().into()), + } + } +} diff --git a/app/vendor/rune/vendor/parley_engine/src/shape/cluster.rs b/app/vendor/rune/vendor/parley_engine/src/shape/cluster.rs new file mode 100644 index 0000000..51856bb --- /dev/null +++ b/app/vendor/rune/vendor/parley_engine/src/shape/cluster.rs @@ -0,0 +1,638 @@ +// Copyright 2025 the Parley Authors +// SPDX-License-Identifier: Apache-2.0 OR MIT + +#![expect(missing_docs, reason = "Deferred")] +#![expect(missing_debug_implementations, reason = "Deferred")] + +use core::cmp::Ordering; + +use alloc::vec::Vec; +use icu_normalizer::properties::Decomposed; +use parley_emoji::{EmojiDFA, EmojiPresentationStyle, EmojiSegmentationCategory}; + +use crate::{CharInfo, analysis::AnalysisDataSources}; + +#[derive(Debug, Default)] +pub struct CharCluster { + chars: Vec<Char>, + map_len: u8, + start: u32, + end: u32, + force_normalize: bool, + comp: Form, + decomp: Form, + emoji_presentation_style: EmojiPresentationStyle, +} + +impl CharCluster { + #[inline] + pub fn range(&self) -> SourceRange { + SourceRange { + start: self.start, + end: self.end, + } + } + + #[inline(always)] + pub fn chars(&self) -> &[Char] { + &self.chars + } + + #[inline(always)] + pub fn is_emoji(&self) -> bool { + self.emoji_presentation_style.is_emoji() + } +} + +/// Source range of a cluster in code units. +#[derive(Copy, Clone)] +pub struct SourceRange { + pub start: u32, + pub end: u32, +} + +#[derive(Copy, Clone, Debug, Default)] +pub struct Char { + /// The character. + pub ch: char, + /// Whether the character + pub is_control_character: bool, + /// True if the character should be considered when mapping glyphs. + pub contributes_to_shaping: bool, + /// Indexes into the list of styles for the containing text run, to find the style applicable + /// to this character. + pub style_index: u16, +} + +/// Whitespace class of a character. +/// +/// All white space characters as defined +/// [by Unicode](https://www.unicode.org/Public/UCD/latest/ucd/PropList.txt) map to a variant of +/// this enum. The variants are based on the various sets of white space as in +/// [CSS Text 4][css-text-4]. +/// +/// A character maps to [`Whitespace::None`] if and only if that character's [`char::is_whitespace`] +/// is `false`. +/// +/// [css-text-4]: https://www.w3.org/TR/css-text-4/ +#[derive(Copy, Clone, PartialOrd, Ord, PartialEq, Eq, Debug)] +#[repr(u8)] +pub enum Whitespace { + /// Not white space. + None = 0, + + /// Standard space. + Space = 1, + + /// Non-breaking space (U+00A0). + NoBreakSpace = 2, + + /// Ideographic space (U+3000). + /// + /// Note CSS Text 4 doesn't treat this space any differently from [`Self::OtherSpaceSeparator`], + /// but some applications do. + IdeographicSpace = 3, + + /// The Unicode "space separators" (category `Zs`), except for the standard space, non-breaking + /// space and ideographic space. + /// + /// Applications may want to treat those three space separators differently from the general + /// class of space separators. + OtherSpaceSeparator = 4, + + /// Horizontal tab. + Tab = 5, + + /// Newline (CR, LF, CRLF, LS, or PS). + Newline = 6, + + /// Vertical tab, form feed and next line. + /// + /// These are Unicode `White_Space`, but CSS Text 4 § 4 says to treat them as visible glyphs. + /// + /// Note [`Self::Tab`] and some of [`Self::Newline`] are also in the Unicode `Cc` category. + /// There are also `Cc` characters that aren't `White_Space` (those would be + /// [`Whitespace::None`]). + ControlWhitespace = 7, + // NOTE: if you grow these variants more than eight, ensure you also update the encoding in + // `GraphemeFlags`. +} + +impl Whitespace { + #[inline] + pub(crate) const fn from_char(c: char) -> Self { + // See https://www.unicode.org/Public/UCD/latest/ucd/PropList.txt. + match c { + ' ' => Self::Space, + '\u{00A0}' => Self::NoBreakSpace, + '\u{3000}' => Self::IdeographicSpace, + // Ogham space mark, en quad through hair space, narrow no-break space, medium + // mathematical space. + '\u{1680}' | '\u{2000}'..='\u{200A}' | '\u{202F}' | '\u{205F}' => { + Self::OtherSpaceSeparator + } + '\t' => Self::Tab, + // Newline, carriage return, line separator, paragraph separator. + '\n' | '\r' | '\u{2028}' | '\u{2029}' => Self::Newline, + // Vertical tab, form feed, next line. These are `White_Space` that CSS says to render + // as control characters. + '\u{000b}' | '\u{000c}' | '\u{0085}' => Self::ControlWhitespace, + _ => Self::None, + } + } + + /// Returns true for space or no break space. + #[inline] + pub fn is_space_or_nbsp(self) -> bool { + matches!(self, Self::Space | Self::NoBreakSpace) + } +} + +/// A font's coverage of a character cluster. +/// +/// This is the fraction `covered / total` of characters covered by a font. Coverages are ordered by +/// the value of the fraction (with `0 / 0` considered to be completely covered). Use, e.g., +/// [`Self::cmp`] to compare coverages. +/// +/// In the unlikely event there are more characters than this in the character cluster, the counts +/// are saturated to [`u8::MAX`]. +#[derive(Copy, Clone, Eq, Debug)] +pub struct Coverage { + /// The number of characters covered by the font. + pub covered: u8, + + /// The number of characters counting towards coverage. + pub total: u8, +} + +impl Coverage { + /// Zero coverage. + /// + /// Useful, for example, as a starting "best coverage," in case you're searching for a + /// best-covering font. + pub const NONE: Self = Self { + covered: 0, + total: u8::MAX, + }; + + /// Complete coverage, meaning all characters contributing to shaping are covered. + /// + /// A coverage compares equal to `COMPLETE` exactly when it is complete, see also + /// [`Self::is_complete`]. + pub const COMPLETE: Self = Self { + covered: u8::MAX, + total: u8::MAX, + }; + + /// Returns `true` iff all characters are covered. + #[inline(always)] + #[must_use] + pub fn is_complete(self) -> bool { + self.covered >= self.total + } +} + +impl PartialEq for Coverage { + #[inline] + fn eq(&self, other: &Self) -> bool { + self.cmp(other) == Ordering::Equal + } +} + +impl PartialOrd for Coverage { + #[inline] + fn partial_cmp(&self, other: &Self) -> Option<Ordering> { + Some(self.cmp(other)) + } +} + +impl Ord for Coverage { + /// Coverages are ordered by the value of the fraction `covered / total`. + #[inline] + fn cmp(&self, other: &Self) -> Ordering { + // We check `is_complete` explicitly, such that fractions of `x / 0`, which are considered + // complete, are ordered identically to other complete fractions. Cases other than those + // with a denominator of 0 would have already been correctly ordered by value through the + // cross-multiplication in the `(false, false)` arm, but note we now order all complete + // fractions as `Ordering::Equal`. + match (self.is_complete(), other.is_complete()) { + (true, true) => Ordering::Equal, + (true, false) => Ordering::Greater, + (false, true) => Ordering::Less, + (false, false) => (u16::from(self.covered) * u16::from(other.total)) + .cmp(&(u16::from(other.covered) * u16::from(self.total))), + } + } +} + +impl CharCluster { + #[inline] + pub(crate) fn clear(&mut self) { + self.chars.clear(); + self.map_len = 0; + self.start = 0; + self.end = 0; + self.force_normalize = false; + self.comp.clear(); + self.decomp.clear(); + self.emoji_presentation_style = EmojiPresentationStyle::Default; + } + + #[inline(always)] + fn len(&self) -> usize { + self.chars.len() + } + + /// Returns the primary style index for the cluster. + #[inline(always)] + pub fn style_index(&self) -> u16 { + self.chars[0].style_index + } + + #[inline(always)] + fn contributes_to_shaping(ch: char, analysis_data_sources: &AnalysisDataSources) -> bool { + let props = analysis_data_sources.properties(ch); + crate::analysis::contributes_to_shaping(props.general_category(), props.script()) + } + + fn decomposed(&mut self, analysis_data_sources: &AnalysisDataSources) -> Option<&[Char]> { + match self.decomp.state { + FormState::Invalid => None, + FormState::None => { + self.decomp.state = FormState::Invalid; + + // Only attempt pairwise normalization (1 <-> 2 characters) + if self.chars.len() != 1 { + return None; + } + + let decomposer = analysis_data_sources.decomposing_normalizer(); + let decomp = decomposer.decompose(self.chars[0].ch); + match decomp { + Decomposed::Default | Decomposed::Singleton(_) => { + return None; + } + Decomposed::Expansion(a, b) => { + let mut copy = self.chars[0]; + copy.ch = a; + copy.contributes_to_shaping = + Self::contributes_to_shaping(a, analysis_data_sources); + self.decomp.chars[0] = copy; + + copy.ch = b; + copy.contributes_to_shaping = + Self::contributes_to_shaping(b, analysis_data_sources); + self.decomp.chars[1] = copy; + + self.decomp.len = 2; + } + } + + self.decomp.state = FormState::Valid; + self.decomp.setup(); + Some(self.decomp.chars()) + } + FormState::Valid => Some(self.decomp.chars()), + } + } + + fn composed(&mut self, analysis_data_sources: &AnalysisDataSources) -> Option<&[Char]> { + match self.comp.state { + FormState::Invalid => None, + FormState::None => { + self.comp.state = FormState::Invalid; + + // Only attempt pairwise normalization (1 <-> 2 characters) + if self.chars.len() != 2 { + return None; + } + + let composer = analysis_data_sources.composing_normalizer(); + let ch = composer.compose(self.chars[0].ch, self.chars[1].ch)?; + + let mut copy = self.chars[0]; + copy.ch = ch; + copy.contributes_to_shaping = + Self::contributes_to_shaping(ch, analysis_data_sources); + self.comp.chars[0] = copy; + self.comp.len = 1; + + self.comp.state = FormState::Valid; + self.comp.setup(); + Some(self.comp.chars()) + } + FormState::Valid => Some(self.comp.chars()), + } + } + + /// Calculate a candidate font's coverage of this character cluster. + /// + /// The callback `covers` should return whether the character is covered by the font under + /// consideration. The coverage returned is the best coverage of the character cluster's + /// characters, or the characters of its normalized forms (see + /// <https://www.unicode.org/reports/tr15/>). + /// + /// Coverages are ordered by how much of the cluster they cover, see [`Coverage`]. Note + /// [`Coverage::total`] may be different from the count of [`Self::chars`], and may also differ + /// between subsequent calls due to returning the best coverage of either the original + /// characters or one of the normalized forms. + pub fn calculate_coverage( + &mut self, + covers: impl Fn(char) -> bool, + analysis_data_sources: &AnalysisDataSources, + ) -> Coverage { + let len = self.len(); + let mut best_coverage = Mapper { + chars: &self.chars[..len], + map_len: self.map_len, + } + .coverage(&covers); + if best_coverage.is_complete() { + return best_coverage; + } + if self.force_normalize && self.composed(analysis_data_sources).is_some() { + let coverage = self.comp.coverage(&covers); + if coverage > best_coverage { + best_coverage = coverage; + if coverage.is_complete() { + return best_coverage; + } + } + } + if self.decomposed(analysis_data_sources).is_some() { + let coverage = self.decomp.coverage(&covers); + if coverage > best_coverage { + best_coverage = coverage; + if coverage.is_complete() { + return best_coverage; + } + } + if !self.force_normalize && self.composed(analysis_data_sources).is_some() { + let coverage = self.comp.coverage(&covers); + if coverage > best_coverage { + best_coverage = coverage; + if coverage.is_complete() { + return best_coverage; + } + } + } + } + + best_coverage + } + + /// Rebuilds `self` in-place using the existing allocation for the given grapheme. + /// + /// `chars` must yield the grapheme's characters with associated analysis info, and style index. + /// + /// `code_unit_offset_in_string` must be the byte offset of the grapheme's first character in the + /// source string. When this method returns, its value is the byte offset just past the end of + /// the grapheme in the source string. + #[expect(clippy::cast_possible_truncation, reason = "Deferred")] + #[inline] + pub(crate) fn fill( + &mut self, + chars: impl Iterator<Item = (char, CharInfo, u16)>, + code_unit_offset_in_string: &mut usize, + ) { + // Reset cluster but keep allocation + self.clear(); + + let mut force_normalize = false; + let mut is_emoji = false; + let mut map_len: u8 = 0; + let mut emoji_dfa = EmojiDFA::new(); + let mut leading_is_emoji_presentation = false; + let start = *code_unit_offset_in_string as u32; + + for (i, (ch, info, style_index)) in chars.enumerate() { + *code_unit_offset_in_string += ch.len_utf8(); + force_normalize |= info.force_normalize(); + + is_emoji |= info.is_emoji_or_pictograph(); + + let mut is_emoji_presentation_selector = false; + + if is_emoji { + if i == 0 { + leading_is_emoji_presentation = info.is_emoji_presentation(); + } + + let category = EmojiSegmentationCategory::from_codepoint( + ch as u32, + info.is_emoji(), + info.is_emoji_presentation(), + info.is_emoji_modifier(), + info.is_emoji_modifier_base(), + info.is_region_indicator(), + ); + + is_emoji_presentation_selector = category.is_presentation_selector(); + + emoji_dfa.step_record(category); + } + + // Variation selectors don't impact font coverage, and are default ignorable. + // TODO: Is there a default ignorable flag we should be using instead? + let contributes_to_shaping = + info.contributes_to_shaping() && !is_emoji_presentation_selector; + if contributes_to_shaping { + map_len = map_len.saturating_add(1); + } + + self.chars.push(Char { + ch, + contributes_to_shaping, + style_index, + is_control_character: info.is_control(), + }); + } + + // Finalize cluster metadata + let end = *code_unit_offset_in_string as u32; + self.map_len = map_len; + self.start = start; + self.end = end; + self.force_normalize = force_normalize; + + if is_emoji { + self.emoji_presentation_style = + emoji_dfa.presentation_style(leading_is_emoji_presentation); + } + } +} + +#[derive(Copy, Clone, Debug, PartialEq, Eq)] +enum FormState { + None, + Valid, + Invalid, +} + +#[derive(Clone, Debug)] +pub(crate) struct Form { + chars: [Char; 2], + len: u8, + map_len: u8, + state: FormState, +} + +impl Default for Form { + fn default() -> Self { + Self::new() + } +} + +impl Form { + fn new() -> Self { + Self { + chars: [Char::default(), Char::default()], + len: 0, + map_len: 0, + state: FormState::None, + } + } + + fn clear(&mut self) { + self.chars = [Char::default(), Char::default()]; + self.len = 0; + self.map_len = 0; + self.state = FormState::None; + } + + #[inline(always)] + fn chars(&self) -> &[Char] { + &self.chars[..self.len as usize] + } + + #[inline(always)] + #[expect(clippy::cast_possible_truncation, reason = "Deferred")] + fn setup(&mut self) { + self.map_len = self + .chars() + .iter() + .filter(|c| !c.is_control_character) + .count() as u8; + } + + #[inline(always)] + fn coverage(&self, covers: &impl Fn(char) -> bool) -> Coverage { + Mapper { + chars: &self.chars[..self.len as usize], + map_len: self.map_len, + } + .coverage(covers) + } +} + +struct Mapper<'a> { + chars: &'a [Char], + map_len: u8, +} + +impl<'a> Mapper<'a> { + /// Returns the coverage of characters contributing to shaping. + fn coverage(&self, covers: &impl Fn(char) -> bool) -> Coverage { + let mut mapped: u8 = 0; + for c in self.chars.iter() { + if c.contributes_to_shaping && covers(c.ch) { + mapped = mapped.saturating_add(1); + } + } + + // If this assert is hit, some bookkeeping is wrong somewhere, but the returned coverage is + // then simply considered to be complete. + debug_assert!( + mapped <= self.map_len, + "Counted more covered characters than the number of characters we consider to be contributing." + ); + + Coverage { + covered: mapped, + total: self.map_len, + } + } +} + +#[cfg(test)] +mod tests { + use crate::shape::Whitespace; + + use super::Coverage; + + #[test] + fn ordering() { + assert!(Coverage::NONE < Coverage::COMPLETE); + + assert_eq!( + Coverage { + covered: 0, + total: 0, + }, + Coverage::COMPLETE + ); + assert_eq!( + Coverage { + covered: 5, + total: 5, + }, + Coverage::COMPLETE + ); + assert_eq!( + Coverage { + // `covered` is greater than `total`, which shouldn't be produced by us, but is + // possible because `Coverage`'s fields are `pub`. + covered: 3, + total: 2, + }, + Coverage::COMPLETE + ); + assert_eq!( + Coverage { + covered: 255, + total: 255, + }, + Coverage::COMPLETE + ); + + assert!( + Coverage { + covered: 4, + total: 5, + } > Coverage::NONE + ); + assert!( + Coverage { + covered: 4, + total: 5, + } < Coverage::COMPLETE + ); + + assert!( + Coverage { + covered: 254, + total: 255, + } > Coverage::NONE + ); + assert!( + Coverage { + covered: 254, + total: 255, + } < Coverage::COMPLETE + ); + } + + #[test] + fn whitespace() { + // Test all code points from `NUL` up to the last `White_Space` character as defined in + // https://www.unicode.org/Public/UCD/latest/ucd/PropList.txt. + for c in '\u{0000}'..='\u{3000}' { + let ws = Whitespace::from_char(c); + assert!( + c.is_whitespace() && ws != Whitespace::None + || !c.is_whitespace() && ws == Whitespace::None, + "`Whitespace` should encode exactly all of Unicode's `White_Space` characters." + ); + } + } +} diff --git a/app/vendor/rune/vendor/parley_engine/src/shape/data.rs b/app/vendor/rune/vendor/parley_engine/src/shape/data.rs new file mode 100644 index 0000000..6d760b7 --- /dev/null +++ b/app/vendor/rune/vendor/parley_engine/src/shape/data.rs @@ -0,0 +1,393 @@ +// Copyright 2026 the Parley Authors +// SPDX-License-Identifier: Apache-2.0 OR MIT + +#![expect(missing_docs, reason = "Deferred")] + +use core::ops::Range; + +use crate::shape::Whitespace; + +/// Data for a single character of the source text. +/// +/// This is a character in the Unicode scalar value sense, i.e., it corresponds to a single `char` +/// of the source text. +#[derive(Copy, Clone, Debug, PartialEq)] +pub struct Character { + pub text_byte_start: u32, + /// Style index for this character. + pub style_index: u16, + /// The whitespace class of this character. + pub whitespace: Whitespace, + /// Properties of this character. + pub flags: CharacterFlags, + /// Whether this character begins a grapheme cluster. + pub grapheme_start: bool, +} + +impl Character { + /// The byte range of this character in the source text. + #[inline(always)] + pub fn text_byte_range(&self) -> Range<usize> { + self.text_byte_start as usize..self.text_byte_start as usize + self.flags.len_utf8() + } + + /// Returns if this character is any whitespace. + #[inline(always)] + pub fn is_whitespace(self) -> bool { + self.whitespace != Whitespace::None + } +} + +#[derive(Copy, Clone, Debug, PartialEq, Eq)] +pub(crate) struct ShapedClusterFlags(u16); + +impl ShapedClusterFlags { + const GLYPH_LEN_MASK: u16 = 0x00FF; + const INLINE_GLYPH: u16 = 1 << 8; + const GRAPHEME_START: u16 = 1 << 9; + const SAFE_TO_BREAK_BEFORE: u16 = 1 << 10; + /// Whether a soft wrap opportunity exists before the cluster's first character. + const SOFT_WRAP_BEFORE: u16 = 1 << 11; + /// [`Whitespace`] class of the cluster's first character (3 bits). + const WHITESPACE_SHIFT: u16 = 12; + const WHITESPACE_MASK: u16 = 0b111 << Self::WHITESPACE_SHIFT; + + #[inline(always)] + pub(crate) const fn new(glyph_len: u8) -> Self { + Self(glyph_len as u16) + } + + #[inline(always)] + pub(crate) const fn with_inline_glyph(mut self, set: bool) -> Self { + self.0 = self.0 & !Self::INLINE_GLYPH | if set { Self::INLINE_GLYPH } else { 0 }; + self + } + + #[inline(always)] + pub(crate) const fn with_grapheme_start(mut self, set: bool) -> Self { + self.0 = self.0 & !Self::GRAPHEME_START | if set { Self::GRAPHEME_START } else { 0 }; + self + } + + #[inline(always)] + pub(crate) const fn with_safe_to_break_before(mut self, set: bool) -> Self { + self.0 = + self.0 & !Self::SAFE_TO_BREAK_BEFORE | if set { Self::SAFE_TO_BREAK_BEFORE } else { 0 }; + self + } + + #[inline(always)] + pub(crate) const fn with_first_char( + mut self, + soft_wrap_opportunity: bool, + whitespace: Whitespace, + ) -> Self { + self.0 = self.0 & !(Self::SOFT_WRAP_BEFORE | Self::WHITESPACE_MASK) + | if soft_wrap_opportunity { + Self::SOFT_WRAP_BEFORE + } else { + 0 + } + | ((whitespace as u16) << Self::WHITESPACE_SHIFT); + self + } + + #[inline(always)] + const fn is_soft_wrap_opportunity_before(self) -> bool { + self.0 & Self::SOFT_WRAP_BEFORE != 0 + } + + #[inline(always)] + const fn whitespace(self) -> Whitespace { + match (self.0 & Self::WHITESPACE_MASK) >> Self::WHITESPACE_SHIFT { + 1 => Whitespace::Space, + 2 => Whitespace::NoBreakSpace, + 3 => Whitespace::IdeographicSpace, + 4 => Whitespace::OtherSpaceSeparator, + 5 => Whitespace::Tab, + 6 => Whitespace::Newline, + 7 => Whitespace::ControlWhitespace, + _ => Whitespace::None, + } + } + + #[inline(always)] + const fn glyph_len(self) -> u8 { + (self.0 & Self::GLYPH_LEN_MASK) as u8 + } + + #[inline(always)] + const fn has_inline_glyph(self) -> bool { + self.0 & Self::INLINE_GLYPH != 0 + } + + #[inline(always)] + const fn is_grapheme_start(self) -> bool { + self.0 & Self::GRAPHEME_START != 0 + } + + #[inline(always)] + const fn is_safe_to_break_before(self) -> bool { + self.0 & Self::SAFE_TO_BREAK_BEFORE != 0 + } +} + +/// A span of characters and the glyphs they shaped into. +/// +/// Shaping may reorder, compose, decompose, etc.; there is no finer-grained correspondence between +/// characters and glyphs. For example, a base letter with a combining mark may shape into a single +/// glyph, a single character may shape into multiple glyphs, and a ligature may combine multiple +/// characters into shared glyphs. +/// +/// Shaped cluster boundaries are not necessarily [`Grapheme`][crate::Grapheme] boundaries. The +/// shared boundaries are encoded by [`Atom`][crate::Atom]s. +/// +/// For more information about clusters, see [HarfBuzz's documentation][harfbuzz]. +/// +/// [harfbuzz]: https://harfbuzz.github.io/working-with-harfbuzz-clusters.html +#[derive(Copy, Clone, Debug, PartialEq)] +pub struct ShapedCluster { + /// The characters of this cluster, as a range into + /// [`ShapedText::characters`](crate::ShapedText::characters). + // + // TODO: this currently stores the full range, but perhaps we could store only the start index. + // See <https://github.com/linebender/parley/pull/715#discussion_r3693794119>. + pub(crate) chars_range: (u32, u32), + + /// Style index for this cluster. + pub style_index: u16, + + /// The index into the glyph array where this cluster's glyphs start. + /// + /// If [`Self::has_inline_glyph`] is `true`, this is a glyph identifier instead. For more, see + /// the documentation on that method. + pub glyph_offset: u32, + + // /// Number of glyphs in this cluster (0xFF = single glyph stored inline) + // pub glyph_len: u8, + pub(crate) flags: ShapedClusterFlags, + + /// Advance width for this cluster + pub advance: f32, +} + +impl ShapedCluster { + /// The characters of this cluster, as a range into [`ShapedText::characters`](crate::ShapedText::characters). + /// + /// This is also the range of character positions in the source text (in the Unicode scalar + /// value sense). + #[inline(always)] + pub fn chars_range(&self) -> Range<u32> { + self.chars_range.0..self.chars_range.1 + } + + /// The number of glyphs of this cluster. + #[inline(always)] + pub fn glyph_len(self) -> u8 { + if self.has_inline_glyph() { + 1 + } else { + self.flags.glyph_len() + } + } + + /// Whether this cluster's glyph is stored inline in [`Self::glyph_offset`]. + /// + /// This is only possible if [`Self::glyph_len`] is one, and the glyph has no offset. + /// [`Self::glyph_offset`] then encodes the glyph identifier rather than an index into the glyph + /// array. The glyph's advance then is this cluster's advance. + #[inline(always)] + pub fn has_inline_glyph(self) -> bool { + self.flags.has_inline_glyph() + } + + /// Whether this shaped cluster's logical start also starts a grapheme. + #[inline(always)] + pub fn is_grapheme_start(self) -> bool { + self.flags.is_grapheme_start() + } + + /// Whether breaking logically before this shaped cluster requires reshaping. + /// + /// Note that if this shaped cluster does not start a grapheme (see + /// [`Self::is_grapheme_start`]), you have to reshape regardless of this value. + #[inline(always)] + pub fn is_safe_to_break_before(self) -> bool { + self.flags.is_safe_to_break_before() + } + + /// Whether a soft wrap opportunity exists before this cluster's first character. + /// + /// This is [`Character::flags`]' soft-wrap bit of the first character of [`Self::chars_range`], + /// cached here so that measuring text does not need to touch the character array. + #[inline(always)] + pub fn is_soft_wrap_opportunity_before(self) -> bool { + self.flags.is_soft_wrap_opportunity_before() + } + + /// The [`Whitespace`] class of this cluster's first character. + /// + /// See [`Self::is_soft_wrap_opportunity_before`]. + #[inline(always)] + pub fn whitespace(self) -> Whitespace { + self.flags.whitespace() + } + + /// The number of characters in this cluster. + #[inline(always)] + pub fn char_len(self) -> u32 { + self.chars_range.1 - self.chars_range.0 + } + + /// The number of graphemes this cluster overlaps. + pub(crate) fn graphemes_overlapped(&self, characters: &[Character]) -> u32 { + let start = self.chars_range().start as usize + 1; + let end = self.chars_range().end as usize; + let mut graphemes = 1; + for character in &characters[start..end] { + graphemes += u32::from(character.grapheme_start); + } + graphemes + } +} + +/// Properties of a [`Character`]. +#[derive(Copy, Clone, Debug, PartialEq, Eq)] +pub struct CharacterFlags(u8); + +impl CharacterFlags { + /// Bits 0..2: the UTF-8 length of the source character minus one. + /// + /// (Note the UTF-8 length of any character is between 1 and 4 inclusive.) + const LEN_UTF8_MASK: u8 = 0b11; + /// Whether the source character is an emoji. + const EMOJI: u8 = 1 << 2; + /// Whether there is a word boundary before the character. + const WORD_BOUNDARY: u8 = 1 << 3; + /// Whether there is a soft wrap opportunity before the character. + const SOFT_WRAP_OPPORTUNITY: u8 = 1 << 4; + + #[inline(always)] + pub fn new(source_char: char, is_word_boundary: bool, is_soft_wrap_opportunity: bool) -> Self { + // TODO: Defer to ICU4X properties (see: https://docs.rs/icu/latest/icu/properties/props/struct.Emoji.html). + let is_emoji = matches!(source_char as u32, 0x1F600..=0x1F64F | 0x1F300..=0x1F5FF | 0x1F680..=0x1F6FF | 0x2600..=0x26FF | 0x2700..=0x27BF); + #[expect( + clippy::cast_possible_truncation, + reason = "`len_utf8` is between 1 and 4 inclusive" + )] + let len_utf8 = source_char.len_utf8() as u8; + Self( + (len_utf8 - 1) + | if is_emoji { Self::EMOJI } else { 0 } + | if is_word_boundary { + Self::WORD_BOUNDARY + } else { + 0 + } + | if is_soft_wrap_opportunity { + Self::SOFT_WRAP_OPPORTUNITY + } else { + 0 + }, + ) + } + + /// Whether there is a soft wrap opportunity before this character ([UAX #14][line-breaking]). + /// + /// Note mandatory breaks (like `\n`) are encoded as [`Whitespace`]. + /// + /// [line-breaking]: https://www.unicode.org/reports/tr14/ + #[inline(always)] + pub fn is_soft_wrap_opportunity(self) -> bool { + self.0 & Self::SOFT_WRAP_OPPORTUNITY != 0 + } + + /// Returns if there is a word boundary before the character. + #[inline(always)] + pub fn is_word_boundary(self) -> bool { + self.0 & Self::WORD_BOUNDARY != 0 + } + + /// Returns if the character is an emoji. + #[inline(always)] + pub fn is_emoji(self) -> bool { + self.0 & Self::EMOJI != 0 + } + + /// Returns the number of bytes the source character would need if encoded in UTF-8. + /// + /// That number of bytes is always between 1 and 4, inclusive. + #[inline(always)] + pub fn len_utf8(self) -> usize { + (self.0 & Self::LEN_UTF8_MASK) as usize + 1 + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn character_flags() { + for (ch, len, emoji) in [ + ('a', 1, false), + (' ', 1, false), + ('\t', 1, false), + ('\r', 1, false), + ('\n', 1, false), + ('\u{00e9}', 2, false), + ('\u{2028}', 3, false), + ('\u{2600}', 3, true), + ('\u{1F600}', 4, true), + ] { + for (is_word_boundary, is_soft_wrap_opportunity) in + [(false, false), (true, false), (false, true), (true, true)] + { + let flags = CharacterFlags::new(ch, is_word_boundary, is_soft_wrap_opportunity); + assert_eq!(flags.len_utf8(), len, "{ch:?}"); + assert_eq!(flags.is_emoji(), emoji, "{ch:?}"); + assert_eq!(flags.is_word_boundary(), is_word_boundary, "{ch:?}"); + assert_eq!( + flags.is_soft_wrap_opportunity(), + is_soft_wrap_opportunity, + "{ch:?}" + ); + } + + let character = Character { + text_byte_start: 3, + style_index: 7, + whitespace: Whitespace::from_char(ch), + flags: CharacterFlags::new(ch, false, false), + grapheme_start: true, + }; + assert_eq!(character.text_byte_range(), 3..3 + len, "{ch:?}"); + } + } + + #[test] + fn first_char_flags_round_trip() { + let soft_wraps = [false, true]; + let whitespaces = [ + Whitespace::None, + Whitespace::Space, + Whitespace::NoBreakSpace, + Whitespace::IdeographicSpace, + Whitespace::OtherSpaceSeparator, + Whitespace::Tab, + Whitespace::Newline, + Whitespace::ControlWhitespace, + ]; + for soft_wrap in soft_wraps { + for whitespace in whitespaces { + let flags = ShapedClusterFlags::new(3) + .with_grapheme_start(true) + .with_first_char(soft_wrap, whitespace); + assert_eq!(flags.is_soft_wrap_opportunity_before(), soft_wrap); + assert_eq!(flags.whitespace(), whitespace); + assert_eq!(flags.glyph_len(), 3); + assert!(flags.is_grapheme_start()); + } + } + } +} diff --git a/app/vendor/rune/vendor/parley_engine/src/shape/mod.rs b/app/vendor/rune/vendor/parley_engine/src/shape/mod.rs new file mode 100644 index 0000000..9ab03ce --- /dev/null +++ b/app/vendor/rune/vendor/parley_engine/src/shape/mod.rs @@ -0,0 +1,16 @@ +// Copyright 2026 the Parley Authors +// SPDX-License-Identifier: Apache-2.0 OR MIT + +//! Text shaping utilities. + +pub(crate) mod atom; +mod cache; +mod cluster; +mod data; +pub(crate) mod shaped_text; +pub(crate) mod shaper; + +pub use cluster::{Char, CharCluster, Coverage, SourceRange, Whitespace}; +pub use data::{Character, CharacterFlags, ShapedCluster}; + +pub(crate) use data::ShapedClusterFlags; diff --git a/app/vendor/rune/vendor/parley_engine/src/shape/shaped_text.rs b/app/vendor/rune/vendor/parley_engine/src/shape/shaped_text.rs new file mode 100644 index 0000000..1ec9ddc --- /dev/null +++ b/app/vendor/rune/vendor/parley_engine/src/shape/shaped_text.rs @@ -0,0 +1,859 @@ +// Copyright 2026 the Parley Authors +// SPDX-License-Identifier: Apache-2.0 OR MIT + +//! Data structures to store the result of shaping. + +use core::ops::Range; + +use alloc::vec::Vec; +use parlance::{BidiLevel, NormalizedCoord}; +use skrifa::MetadataProvider; + +use crate::{ + CharInfo, FontInstance, Glyph, + itemize::{Segment, TextRange}, +}; + +use super::{ + Character, CharacterFlags, ShapedCluster, ShapedClusterFlags, Whitespace, atom::ShapedSlice, + shaper::ShapeOptions, +}; + +/// Metrics that apply to the glyphs of a font. +/// +/// These metrics are scaled by the font size. +/// +/// The `underline_*` and `strikethrough_*` fields are derived if not set by the font. +/// +// TODO: Perhaps it'd be nicer if we exposed unscaled metrics (design units) instead. This currently +// just follows what `parley` used to do in its `RunMetrics`. If we go unscaled, we should then +// either also store units per em, or em-normalize the values like CSS does. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct FontMetrics { + /// Distance from the baseline to the top of the alignment box. + pub ascent: f32, + /// Distance from the baseline to the bottom of the alignment box. + pub descent: f32, + /// Recommended additional spacing between lines. + pub leading: f32, + /// Offset of the top of underline decoration from the baseline. + pub underline_offset: f32, + /// Thickness of the underline decoration. + pub underline_size: f32, + /// Offset of the top of strikethrough decoration from the baseline. + pub strikethrough_offset: f32, + /// Thickness of the strikethrough decoration. + pub strikethrough_size: f32, + /// Distance from the baseline to the top of a typical English capital. + pub cap_height: Option<f32>, + /// Distance from the baseline to the top of the lowercase "x" or + /// similar character. + pub x_height: Option<f32>, +} + +impl FontMetrics { + /// Metrics to use when no font is available at all. + /// + /// These roughly match common Latin fonts, so that a layout without fonts still has plausible + /// line heights. + pub const fn fallback(font_size: f32) -> Self { + Self { + ascent: font_size * 0.8, + descent: font_size * 0.2, + leading: 0., + underline_offset: 0., + underline_size: 0., + strikethrough_offset: 0., + strikethrough_size: 0., + cap_height: None, + x_height: None, + } + } + + /// Compute the metrics of `font` at `font_size`, positioned at the variable font location + /// given by the `synthesis` and `variations` axis settings. + /// + /// Returns `None` if the font data cannot be parsed. + pub fn from_font_instance( + font: &FontInstance, + font_size: f32, + variations: &[parlance::FontVariation], + ) -> Option<Self> { + // A style's metrics depend on its font instance, size and variations alone; a style + // table asks for the same few again in every layout (Rune: vendor/parley_engine.patch). + #[cfg(feature = "std")] + { + type Memo = Vec<(u64, u32, fontique::Synthesis, u32, Vec<parlance::FontVariation>, Option<FontMetrics>)>; + std::thread_local! { + static MEMO: core::cell::RefCell<Memo> = const { core::cell::RefCell::new(Vec::new()) }; + } + let (id, index, size) = (font.font.data.id(), font.font.index, font_size.to_bits()); + let found = MEMO.with_borrow(|memo| { + memo.iter() + .find(|m| m.0 == id && m.1 == index && m.2 == font.synthesis && m.3 == size && m.4 == variations) + .map(|m| m.5) + }); + if let Some(metrics) = found { + return metrics; + } + let metrics = Self::compute_from_font_instance(font, font_size, variations); + MEMO.with_borrow_mut(|memo| { + if memo.len() >= 64 { + memo.remove(0); + } + memo.push((id, index, font.synthesis, size, variations.to_vec(), metrics)); + }); + return metrics; + } + Self::compute_from_font_instance(font, font_size, variations) + } + + fn compute_from_font_instance( + font: &FontInstance, + font_size: f32, + variations: &[parlance::FontVariation], + ) -> Option<Self> { + let font_ref = + skrifa::FontRef::from_index(font.font.data.as_ref(), font.font.index).ok()?; + let location = font_ref.axes().location( + font.synthesis + .variation_settings() + .iter() + .map(|(tag, value)| (skrifa::Tag::new(&tag.to_be_bytes()), *value)) + .chain( + variations + .iter() + .map(|v| (skrifa::Tag::new(&v.tag.to_bytes()), v.value)), + ), + ); + Some(Self::from_skrifa_metrics( + &skrifa::metrics::Metrics::new( + &font_ref, + skrifa::prelude::Size::new(font_size), + &location, + ), + font_size, + )) + } + + pub(crate) fn from_skrifa_metrics(metrics: &skrifa::metrics::Metrics, font_size: f32) -> Self { + // Default values from HarfBuzz: https://github.com/harfbuzz/harfbuzz/blob/12ee77ee00514c442bcd28f9aa9d56b708c37382/src/hb-ot-metrics.cc#L355-L372 + let fallback_decoration_size = font_size / 18.0; + + let (underline_offset, underline_size) = if let Some(underline) = metrics.underline { + (underline.offset, underline.thickness) + } else { + (-fallback_decoration_size, fallback_decoration_size) + }; + let (strikethrough_offset, strikethrough_size) = if let Some(strikeout) = metrics.strikeout + { + (strikeout.offset, strikeout.thickness) + } else { + (metrics.ascent / 2.0, fallback_decoration_size) + }; + + Self { + ascent: metrics.ascent, + descent: -metrics.descent, + leading: metrics.leading, + underline_offset, + underline_size, + strikethrough_offset, + strikethrough_size, + x_height: metrics.x_height, + cap_height: metrics.cap_height, + } + } +} + +/// The result of shaping. +/// +/// After [analyzing][crate::Analysis] your text, [shape the text][crate::Shaper::shape_text], +/// writing the result into this [`ShapedText`]. This then holds your shaped paragraph of text. +/// +/// This shaped text holds spans of the source text's characters that were shaped into +/// [`ShapedCluster`]s. Note that the boundaries of shaped clusters and graphemes need not coincide; +/// see [`ShapedCluster`]s documentation for more information. +/// +/// Use [`Self::run_slice`] to get a run's [`ShapedSlice`]. From there, you can interact with slices +/// of shaped text, such as walking [atoms](crate::Atom) (e.g., [`ShapedSlice::atoms_start`]) and +/// [graphemes](crate::Grapheme) (e.g., [`ShapedSlice::graphemes_start`]). +#[derive(Clone, Debug, Default, PartialEq)] +pub struct ShapedText { + runs: Vec<ShapedRun>, + characters: Vec<Character>, + shaped_clusters: Vec<ShapedCluster>, + glyphs: Vec<Glyph>, + fonts: Vec<FontInstance>, + normalized_coords: Vec<NormalizedCoord>, +} + +impl ShapedText { + /// Create a reusable [`ShapedText`]. + pub fn new() -> Self { + Self::default() + } + + /// Reserve capacity for at least `additional_chars` more characters. + /// + /// This speculatively reserves capacity for `additional_chars` more clusters and glyphs. + #[inline] + pub(crate) fn reserve(&mut self, additional_chars: usize) { + self.characters.reserve(additional_chars); + self.shaped_clusters.reserve(additional_chars); + self.glyphs.reserve(additional_chars); + } + + /// Clear the result while retaining capacity. + #[inline] + pub fn clear(&mut self) { + self.runs.clear(); + self.characters.clear(); + self.shaped_clusters.clear(); + self.glyphs.clear(); + self.fonts.clear(); + self.normalized_coords.clear(); + } + + /// Get a [`ShapedSlice`] of the run at `run_index`. + pub fn run_slice(&self, run_index: u32) -> ShapedSlice<'_> { + let run = &self.runs[run_index as usize]; + ShapedSlice { + characters: &self.characters, + + shaped_clusters: &self.shaped_clusters, + glyphs: &self.glyphs, + + clusters: ( + run.shaped_clusters_range.start, + run.shaped_clusters_range.end, + ), + } + } + + /// The shaped runs. + /// + /// Each run contains glyphs that can be rendered with a single font. + #[inline(always)] + pub fn runs(&self) -> &[ShapedRun] { + &self.runs + } + + /// Escape hatch for `parley` tests that remap style indices to check whether layouts are + /// otherwise identical. This is not for public consumption! + #[doc(hidden)] + #[inline(always)] + pub fn remap_styles(&mut self, remap: &[u16]) { + for character in self.characters.iter_mut() { + character.style_index = remap[character.style_index as usize]; + } + for shaped_cluster in self.shaped_clusters.iter_mut() { + shaped_cluster.style_index = remap[shaped_cluster.style_index as usize]; + } + } + + /// The character data of the text, in logical order. + /// + /// [`ShapedRun::characters_range`] indexes into this. The nth [`Character`] corresponds exactly + /// to the nth character of the source text (in the Unicode scalar value sense). This contains + /// every character of the source text unless shaping was aborted due to + /// [`FontSelector::select_font`][crate::FontSelector::select_font] failing to return a font. + #[inline(always)] + pub fn characters(&self) -> &[Character] { + &self.characters + } + + /// The shaped clusters. + /// + /// [`ShapedRun::shaped_clusters_range`] indexes into this. + #[inline(always)] + pub fn shaped_clusters(&self) -> &[ShapedCluster] { + &self.shaped_clusters + } + + /// The shaped glyphs. + /// + /// [`ShapedRun::glyphs_range`] indexes into this. + #[inline(always)] + pub fn glyphs(&self) -> &[Glyph] { + &self.glyphs + } + + /// The fonts. + /// + /// [`ShapedRun::font_index`] indexes into this. + #[inline(always)] + pub fn fonts(&self) -> &[FontInstance] { + &self.fonts + } + + /// The normalized font coordinates used by runs in this shaped text. + /// + /// [`ShapedRun::normalized_coords_range`] splits this into per-run slices. + #[inline(always)] + pub fn normalized_coords(&self) -> &[NormalizedCoord] { + &self.normalized_coords + } + + #[expect(clippy::cast_possible_truncation, reason = "Deferred")] + pub(crate) fn push_run( + &mut self, + text: &str, + range: TextRange, + segment: &Segment, + options: &ShapeOptions<'_>, + char_info: &[CharInfo], + char_style_indices: &[u16], + font: &FontInstance, + glyph_infos: &[harfrust::GlyphInfo], + glyph_positions: &[harfrust::GlyphPosition], + normalized_coords: &[harfrust::NormalizedCoord], + (font_metrics, units_per_em): (FontMetrics, f32), + ) { + debug_assert_eq!( + range.char_range.len(), + text[range.byte_range.clone()].chars().count(), + "The claimed character range and the text's covered byte range should agree" + ); + + let normalized_coords_range = { + let start = self.normalized_coords.len(); + self.normalized_coords.extend( + normalized_coords + .iter() + .map(|c| NormalizedCoord::from_bits(c.to_bits())), + ); + start..self.normalized_coords.len() + }; + + let font_index = self + .fonts + .iter() + .position(|f| f == font) + .unwrap_or_else(|| { + let index = self.fonts.len(); + self.fonts.push(font.clone()); + index + }); + + // `HarfRust` returns glyphs in visual order, so we need to process them as such while + // maintaining logical ordering of clusters. + + let scale_factor = options.font_size / units_per_em; + let shaped_clusters_start = self.shaped_clusters.len(); + + // Push all characters. + let characters_start = self.characters.len(); + for (((byte_offset, ch), info), style_index) in text[range.byte_range.clone()] + .char_indices() + .zip(&char_info[range.char_range.clone()]) + .zip(&char_style_indices[range.char_range.clone()]) + { + self.characters.push(Character { + text_byte_start: (range.byte_range.start + byte_offset) as u32, + style_index: *style_index, + whitespace: Whitespace::from_char(ch), + flags: CharacterFlags::new( + ch, + info.is_word_boundary(), + info.is_soft_wrap_opportunity(), + ), + grapheme_start: info.is_grapheme_start(), + }); + } + // TODO: we force a grapheme break at the start of the run, as itemization could have split + // a grapheme into two. Ideally, grapheme segmentation should be performed after + // itemization, at which case this will always be true. + self.characters[characters_start].grapheme_start = true; + + let glyphs_start = self.glyphs.len(); + if segment.bidi_level.is_ltr() { + process_shaped_clusters( + &mut self.shaped_clusters, + &mut self.glyphs, + scale_factor, + glyph_infos.iter(), + glyph_positions.iter(), + &self.characters, + characters_start, + ); + } else { + process_shaped_clusters( + &mut self.shaped_clusters, + &mut self.glyphs, + scale_factor, + glyph_infos.iter().rev(), + glyph_positions.iter().rev(), + &self.characters, + characters_start, + ); + // Reverse each cluster's glyphs, such that they are in paint order. + // + // TODO: could this become a single `reverse` over the range? + for cluster in &self.shaped_clusters[shaped_clusters_start..] { + if !cluster.has_inline_glyph() && cluster.glyph_len() > 1 { + let start = cluster.glyph_offset as usize; + self.glyphs[start..start + cluster.glyph_len() as usize].reverse(); + } + } + } + + let shaped_clusters_range = shaped_clusters_start as u32..self.shaped_clusters.len() as u32; + let run_advance = self.shaped_clusters[shaped_clusters_start..] + .iter() + .map(|cluster| cluster.advance) + .sum(); + + self.runs.push(ShapedRun { + range, + font_size: options.font_size, + font_index, + characters_range: characters_start as u32..self.characters.len() as u32, + shaped_clusters_range, + glyphs_range: glyphs_start..self.glyphs.len(), + normalized_coords_range, + bidi_level: segment.bidi_level, + advance: run_advance, + font_metrics, + }); + } +} + +/// One shaped run, belonging to a [`ShapedText`]. +#[derive(Clone, Debug, PartialEq)] +pub struct ShapedRun { + /// The range of text this run corresponds to. + pub range: TextRange, + /// Font size. + pub font_size: f32, + /// This run's font, as an index into [`ShapedText::fonts`]. + // + // Note: We carry the font index instead of having `ShapedRun` carry `Arc<FontInstance>`, + // meaning `ShapedRun` could become `Copy` once we have access to `core::range::Range`. + pub font_index: usize, + /// This run's characters, as a range into [`ShapedText::characters`]. + pub characters_range: Range<u32>, + /// This run's shaped clusters, as a range into [`ShapedText::shaped_clusters`]. + pub shaped_clusters_range: Range<u32>, + /// This run's glyphs, as a range into [`ShapedText::glyphs`]. + pub glyphs_range: Range<usize>, + /// The normalized variation coords of this run, as a range into [`ShapedText::normalized_coords`]. + pub normalized_coords_range: Range<usize>, + /// The bidi level of the run. + pub bidi_level: BidiLevel, + /// Total advance of the run. + pub advance: f32, + /// The font metrics of this run. + pub font_metrics: FontMetrics, +} + +/// Processes shaped glyphs from `HarfRust` and converts them into `ShapedCluster` and `Glyph`. +/// +/// # Parameters +/// +/// ## Output Parameters (mutated by this function): +/// * `shaped_clusters` - Vector where new `ShapedCluster` entries will be pushed. +/// * `glyphs` - Vector where new `Glyph` entries will be pushed. Note: single-glyph clusters +/// with zero offsets are inlined directly into `ShapedCluster`. +/// +/// ## Input Parameters: +/// * `scale_factor` - Scaling factor used to convert font units to the target size. +/// * `glyph_infos` - `HarfRust` glyph information in logical order (i.e., reversed for RTL runs). +/// * `glyph_positions` - `HarfRust` glyph positioning data in logical order (i.e., reversed for RTL +/// runs). +/// * `characters` must contain the shaped characters whose clusters we're now processing, starting at +/// index `characters_start`. +/// * `characters_start` - See `characters`. +fn process_shaped_clusters<'a>( + shaped_clusters: &mut Vec<ShapedCluster>, + glyphs: &mut Vec<Glyph>, + scale_factor: f32, + glyph_infos: impl Iterator<Item = &'a harfrust::GlyphInfo>, + glyph_positions: impl Iterator<Item = &'a harfrust::GlyphPosition>, + characters: &[Character], + characters_start: usize, +) { + struct Cluster { + id: u32, + characters_start: usize, + glyphs_start: usize, + glyphs: u32, + inline_glyph: Option<Glyph>, + advance: f32, + } + + /// Flush `cluster`, whose characters end at `char_end`, onto `shaped_clusters`. + #[expect(clippy::cast_possible_truncation, reason = "Deferred")] + fn flush( + cluster: &mut Cluster, + char_end: usize, + characters: &[Character], + shaped_clusters: &mut Vec<ShapedCluster>, + ) { + let first_character = &characters[cluster.characters_start]; + let is_newline = first_character.whitespace == Whitespace::Newline; + let (glyph_offset, glyph_len, inline_glyph, advance) = if is_newline { + // Elide glyphs of newlines. + (cluster.glyphs_start as u32, 0, false, 0.) + } else if let Some(inline_glyph) = cluster.inline_glyph.take() { + (inline_glyph.id, 1, true, cluster.advance) + } else { + ( + cluster.glyphs_start as u32, + cluster.glyphs as u8, + false, + cluster.advance, + ) + }; + + shaped_clusters.push(ShapedCluster { + chars_range: (cluster.characters_start as u32, char_end as u32), + style_index: first_character.style_index, + flags: ShapedClusterFlags::new(glyph_len) + .with_grapheme_start(first_character.grapheme_start) + // TODO: fill with actual shaping data (`parley` currently just ignores this) + .with_safe_to_break_before(false) + .with_inline_glyph(inline_glyph) + .with_first_char( + first_character.flags.is_soft_wrap_opportunity(), + first_character.whitespace, + ), + glyph_offset, + advance, + }); + } + + let mut cluster = Cluster { + id: 0, + characters_start, + glyphs_start: glyphs.len(), + glyphs: 0, + inline_glyph: None, + advance: 0., + }; + + for (glyph_info, glyph_pos) in glyph_infos.zip(glyph_positions) { + if glyph_info.cluster != cluster.id { + let char_end = characters_start + glyph_info.cluster as usize; + flush(&mut cluster, char_end, characters, shaped_clusters); + + cluster = Cluster { + id: glyph_info.cluster, + characters_start: char_end, + glyphs_start: glyphs.len(), + glyphs: 0, + inline_glyph: None, + advance: 0., + }; + } + + let glyph = Glyph { + id: glyph_info.glyph_id, + x: (glyph_pos.x_offset as f32) * scale_factor, + // Convert from font space (Y-up) to layout space (Y-down) + y: -(glyph_pos.y_offset as f32) * scale_factor, + advance: (glyph_pos.x_advance as f32) * scale_factor, + }; + if cluster.glyphs == 0 && glyph.x == 0. && glyph.y == 0. { + // Defer this potential zero-offset, single glyph cluster + cluster.inline_glyph = Some(glyph); + } else { + if let Some(pending_glyph) = cluster.inline_glyph.take() { + glyphs.push(pending_glyph); + } + glyphs.push(glyph); + } + cluster.advance += glyph.advance; + cluster.glyphs += 1; + } + + // Flush the final cluster. + flush(&mut cluster, characters.len(), characters, shaped_clusters); +} + +#[cfg(test)] +mod tests { + use alloc::{sync::Arc, vec, vec::Vec}; + + use fontique::Synthesis; + use linebender_resource_handle::{Blob, FontData}; + + use crate::{ + Analysis, AnalysisOptions, Analyzer, FontInstance, FontInstanceRef, FontSelector, + ShapeOptions, Shaper, + itemize::{Item, Segment}, + shape::CharCluster, + }; + + use super::ShapedText; + + const ROBOTO: &[u8] = + include_bytes!("../../../parley_dev/assets/fonts/roboto_fonts/Roboto-Regular.ttf"); + const NOTO_KUFI_ARABIC: &[u8] = + include_bytes!("../../../parley_dev/assets/fonts/noto_fonts/NotoKufiArabic-Regular.otf"); + const NOTO_COLOR_EMOJI: &[u8] = include_bytes!( + "../../../parley_dev/assets/fonts/noto_color_emoji/NotoColorEmoji-Subset.ttf" + ); + + /// A [`FontSelector`] shaping everything with a single font. + struct SingleFont(FontInstance); + + impl FontSelector for SingleFont { + fn select_font( + &mut self, + _item: &Segment, + _options: &ShapeOptions<'_>, + _cluster: &mut CharCluster, + ) -> Option<FontInstanceRef<'_>> { + Some(self.0.as_ref()) + } + } + + /// A [`FontSelector`] shaping clusters starting with a particular character with one font, and + /// all other clusters with another, to split the text into runs at that character. + struct FontForChar { + ch: char, + font: FontInstance, + other_font: FontInstance, + } + + impl FontSelector for FontForChar { + fn select_font( + &mut self, + _segment: &Segment, + _options: &ShapeOptions<'_>, + cluster: &mut CharCluster, + ) -> Option<FontInstanceRef<'_>> { + if cluster.chars()[0].ch == self.ch { + Some(self.font.as_ref()) + } else { + Some(self.other_font.as_ref()) + } + } + } + + fn analyze(text: &str) -> Analysis { + let mut analysis = Analysis::new(); + Analyzer::new().analyze( + text, + &AnalysisOptions { + line_break: &[], + line_break_override: None, + ..AnalysisOptions::default() + }, + &mut analysis, + ); + analysis + } + + fn font_instance(font_data: &'static [u8]) -> FontInstance { + FontInstance { + font: FontData::new(Blob::new(Arc::new(font_data)), 0), + synthesis: Synthesis::default(), + } + } + + fn shape_with_font(text: &str, font_data: &'static [u8]) -> ShapedText { + shape_with_font_selector(text, SingleFont(font_instance(font_data))) + } + + fn shape_with_font_selector(text: &str, select_font: impl FontSelector) -> ShapedText { + let analysis = analyze(text); + let mut shaper = Shaper::default(); + let mut shaped = ShapedText::new(); + + let char_style_indices = vec![0; text.chars().count()]; + let items = [Item { + char_end: text.chars().count().try_into().unwrap(), + options: ShapeOptions { + font_size: 32.0, + language: None, + features: &[], + variations: &[], + }, + }]; + shaper.shape_text( + text, + &analysis, + &char_style_indices, + items, + select_font, + &mut shaped, + ); + shaped + } + + /// A run can shape into no glyphs at all: `HarfRust` normally shapes `default-ignorable` + /// characters (like a soft-hyphen) into a space glyph with zero advance, but if the space glyph + /// is not available, it just deletes the character. + /// + /// This checks whether we handle that. + #[test] + fn run_without_glyphs_is_kept() { + // The soft hyphen is `default-ignorable`, and is a grapheme of its own, so font selection + // gives it a run of its own. + let shaped = shape_with_font_selector( + "a\u{00AD}b", + FontForChar { + ch: '\u{00AD}', + // Our Noto Color Emoji subset has no space character. + font: font_instance(NOTO_COLOR_EMOJI), + other_font: font_instance(ROBOTO), + }, + ); + + assert_eq!( + shaped.characters().iter().count(), + 3, + "the characters of a run without glyphs are shaped" + ); + let [a, soft_hyphen, b] = shaped.runs() else { + panic!("expected three runs, got {}", shaped.runs().len()); + }; + assert_eq!(a.characters_range, 0..1); + assert_eq!(soft_hyphen.characters_range, 1..2); + assert_eq!(b.characters_range, 2..3); + + assert!(soft_hyphen.glyphs_range.is_empty()); + assert_eq!(soft_hyphen.advance, 0.); + + // The soft-hyphen's run should have a single cluster, and it must be without glyphs. + let clusters = shaped.run_slice(1).shaped_clusters(); + assert_eq!(clusters.len(), 1); + assert_eq!(clusters[0].glyph_len(), 0); + assert_eq!(clusters[0].chars_range(), 1..2); + } + + #[test] + fn single_cluster_run_advance_matches_its_cluster() { + let shaped = shape_with_font("A", ROBOTO); + let run = &shaped.runs()[0]; + let cluster = &shaped.shaped_clusters()[run.shaped_clusters_range.start as usize]; + + assert!(cluster.advance > 0.0); + assert_eq!(run.advance, cluster.advance); + } + + /// [U+0600 U+0623 U+064F] is a single grapheme in text-wide segmentation, but U+0600 has + /// bidi class AN while the following characters resolve to a different bidi level, so + /// itemization splits the grapheme into the items [U+0600] [U+0623 U+064F]. The item + /// boundary forces a grapheme start on U+0623. + #[test] + fn one_grapheme_split_across_items() { + let shaped = shape_with_font("\u{0600}\u{0623}\u{064F}", NOTO_KUFI_ARABIC); + + let grapheme_starts: Vec<bool> = + shaped.characters.iter().map(|c| c.grapheme_start).collect(); + assert_eq!(grapheme_starts, [true, true, false]); + + let clusters: Vec<(u32, u32, bool)> = shaped + .shaped_clusters + .iter() + .map(|c| { + ( + c.chars_range().start, + c.chars_range().end, + c.is_grapheme_start(), + ) + }) + .collect(); + assert_eq!(clusters, [(0, 1, true), (1, 3, true)]); + } + + /// "ffi" is three graphemes but shapes into one cluster. + #[test] + fn three_graphemes_one_cluster() { + let shaped = shape_with_font("ffi", ROBOTO); + + let grapheme_starts: Vec<bool> = + shaped.characters.iter().map(|c| c.grapheme_start).collect(); + assert_eq!(grapheme_starts, [true, true, true]); + + let clusters: Vec<(u32, u32, bool)> = shaped + .shaped_clusters + .iter() + .map(|c| { + ( + c.chars_range().start, + c.chars_range().end, + c.is_grapheme_start(), + ) + }) + .collect(); + assert_eq!(clusters, [(0, 3, true)]); + } + + #[test] + fn newlines_removed() { + for newline in ["\n", "\r", "\u{2028}", "\u{2029}"] { + let shaped = shape_with_font(&alloc::format!("a{newline}b"), ROBOTO); + + let index = shaped + .shaped_clusters + .iter() + .position(|cluster| cluster.chars_range().start == 1) + .unwrap(); + let newline_cluster = &shaped.shaped_clusters[index]; + assert_eq!(newline_cluster.glyph_len(), 0, "newline glyphs are removed"); + assert_eq!(newline_cluster.advance, 0., "newline advance is set to 0"); + } + } + + /// An itemization boundary forces a cluster break in shaping, and must force a grapheme start. + #[test] + fn item_boundaries_force_grapheme_start() { + // Two regional indicators forming a single flag grapheme... + let text = "\u{1F1E6}\u{1F1E7}"; + let char_style_indices = vec![0; text.chars().count()]; + let analysis = analyze(text); + assert_eq!( + analysis + .char_info() + .iter() + .map(|info| info.is_grapheme_start()) + .collect::<Vec<_>>(), + [true, false] + ); + + let font = font_instance(ROBOTO); + let mut shaper = Shaper::default(); + let mut shaped = ShapedText::new(); + + // ...split over two items. + let items = [ + Item { + char_end: 1, + options: ShapeOptions { + font_size: 32.0, + language: None, + features: &[], + variations: &[], + }, + }, + Item { + char_end: text.chars().count().try_into().unwrap(), + options: ShapeOptions { + font_size: 32.0, + language: None, + features: &[], + variations: &[], + }, + }, + ]; + shaper.shape_text( + text, + &analysis, + &char_style_indices, + items, + SingleFont(font), + &mut shaped, + ); + + let grapheme_starts: Vec<bool> = + shaped.characters.iter().map(|c| c.grapheme_start).collect(); + assert_eq!(grapheme_starts, [true, true]); + + // But note that, had we had three regional indicator symbols, like `[R0 R1 R2]` itemized as + // `[R0] [R1 R2]`, the last pair should form a single grapheme. We don't do that currently. + } +} diff --git a/app/vendor/rune/vendor/parley_engine/src/shape/shaper.rs b/app/vendor/rune/vendor/parley_engine/src/shape/shaper.rs new file mode 100644 index 0000000..42594db --- /dev/null +++ b/app/vendor/rune/vendor/parley_engine/src/shape/shaper.rs @@ -0,0 +1,605 @@ +// Copyright 2026 the Parley Authors +// SPDX-License-Identifier: Apache-2.0 OR MIT + +//! Shaping of text. + +use alloc::vec::Vec; +use core::mem; +use harfrust::ShapeOptions as HarfShapeOptions; +use linebender_resource_handle::{Blob, FontData}; +use parlance::{FontFeature, FontVariation, Language}; + +use crate::shape::shaped_text::FontMetrics; +use crate::{ + Analysis, CharInfo, ShapedText, + itemize::{Item, Segment, TextRange}, + lru_cache::LruCache, + shape::{CharCluster, cache}, +}; + +/// Shaping options for one item. +/// +/// These are styling options relevant for shaping. They're styling, in that they're not derived +/// from the underlying text. When you [shape the text][`Shaper::shape_text`], you should split the +/// text into [`Item`]s at the points where these options change. +#[derive(Debug)] +pub struct ShapeOptions<'a> { + /// The font size to shape the item with. + pub font_size: f32, + /// The language to shape the item with. + pub language: Option<Language>, + /// The font features to shape the item with. + /// + /// If there are font features with duplicate [tags][`FontFeature::tag`], later values override + /// earlier values. + pub features: &'a [FontFeature], + /// The font variations that are constant over an item. + pub variations: &'a [FontVariation], +} + +/// The font instance to shape an item with. +#[derive(Clone, Debug, PartialEq)] +pub struct FontInstance { + /// The font. + pub font: FontData, + /// Font synthesis suggestions. + // TODO: Synthesis carries more than we need, and ties us to `fontique`. We can likely change + // this to opaque user data. + pub synthesis: fontique::Synthesis, +} + +impl FontInstance { + /// Borrow this font instance. + #[inline] + pub fn as_ref(&self) -> FontInstanceRef<'_> { + FontInstanceRef { + data: &self.font.data, + index: self.font.index, + synthesis: &self.synthesis, + } + } +} + +/// A borrowed [`FontInstance`]. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct FontInstanceRef<'a> { + /// Blob containing the content of the font file. + pub data: &'a Blob<u8>, + /// Index of the font in a collection, or 0 for a single font. + pub index: u32, + /// Font synthesis suggestions. + pub synthesis: &'a fontique::Synthesis, +} + +impl From<FontInstanceRef<'_>> for FontInstance { + #[inline] + fn from(font: FontInstanceRef<'_>) -> Self { + Self { + font: FontData { + data: font.data.clone(), + index: font.index, + }, + synthesis: *font.synthesis, + } + } +} + +/// Reusable scratch to shape text using [`Self::shape_text`]. +pub struct Shaper { + shape_data_cache: LruCache<cache::ShapeDataKey, harfrust::ShaperData>, + shape_instance_cache: LruCache<cache::ShapeInstanceId, harfrust::ShaperInstance>, + shape_plan_cache: LruCache<cache::ShapePlanId, harfrust::ShapePlan>, + /// Each run's font metrics and units per em (Rune: vendor/parley_engine.patch). + run_metrics_cache: LruCache<cache::RunMetricsId, (FontMetrics, f32)>, + unicode_buffer: Option<harfrust::UnicodeBuffer>, + features: Vec<harfrust::Feature>, + char_cluster: CharCluster, +} + +impl Default for Shaper { + fn default() -> Self { + const MAX_ENTRIES: usize = 16; + Self { + shape_data_cache: LruCache::new(MAX_ENTRIES), + shape_instance_cache: LruCache::new(MAX_ENTRIES), + shape_plan_cache: LruCache::new(MAX_ENTRIES), + run_metrics_cache: LruCache::new(MAX_ENTRIES), + unicode_buffer: Some(harfrust::UnicodeBuffer::new()), + features: Vec::new(), + char_cluster: CharCluster::default(), + } + } +} + +impl core::fmt::Debug for Shaper { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + f.debug_struct("Shaper").finish_non_exhaustive() + } +} + +impl Shaper { + /// Shape text into glyphs, overwriting `shaped_text`. + /// + /// The `text` passed in must be the same as used for producing `analysis`. + /// + /// This uses the items returned by `items`, and further itemizes the text into + /// individually-shapeable segments of constant bidi level and script. `items` should be used to + /// split on properties like shaping-relevant style changes (e.g., font size) or properties like + /// language. + /// + /// `char_style_indices` holds per-character style indices; these are copied onto + /// [`Character`][super::Character`] and [`ShapedCluster`][super::ShapedCluster]. A shaped + /// cluster's style index is that of its logically first constituent character. + /// + /// Characters that don't have a particular script have their script resolved based on + /// surrounding context (see [`Segment::script`]). + /// + /// Each segment is then broken into runs of maximal sequences of character clusters for which + /// `select_font` returns the same font. + /// + /// # Panics + /// + /// Panics if `items` does not cover the entire source text, or the font returned by + /// `select_font` is malformed. + pub fn shape_text<'options>( + &mut self, + text: &str, + analysis: &Analysis, + // TODO: rename to something like `user_data` (s.t. we don't assume it's a style per se). + char_style_indices: &[u16], + items: impl IntoIterator<Item = Item<'options>>, + mut select_font: impl FontSelector, + shaped_text: &mut ShapedText, + ) { + shaped_text.clear(); + shaped_text.reserve(text.len()); + + let char_count = analysis.char_info().len(); + debug_assert_eq!( + char_style_indices.len(), + char_count, + "The number of character style indices must be equal to the character count" + ); + + let mut previous_item_end = 0; + let mut itemizer = analysis.itemize(text); + + for item in items { + assert!( + item.char_end > previous_item_end, + "item ends must be strictly increasing" + ); + assert!( + item.char_end as usize <= char_count, + "items must not span past the text" + ); + + loop { + let segment = itemizer + .next( + #[inline(always)] + |text_range| text_range.char_range.end == item.char_end as usize, + ) + .expect("A segment must be yielded, given items tile the full text exactly"); + + if shape_segment( + self, + text, + &segment, + &item.options, + &mut select_font, + analysis.char_info(), + char_style_indices, + shaped_text, + ) + .is_err() + { + // Abort on error. This happens iff `FontSelector::select_font` failed to return a + // font. By aborting we ensure `ShapedText` covers the source text contiguously (as + // we need a font to construct `ShapedRun`). + return; + }; + + debug_assert!( + segment.range.char_range.end <= item.char_end as usize, + "Segments must not span past the item." + ); + if segment.range.char_range.end == item.char_end as usize { + break; + } + } + + previous_item_end = item.char_end; + } + + assert_eq!( + previous_item_end as usize, char_count, + "`items` does not cover the entire source text" + ); + debug_assert_eq!( + shaped_text.characters().len(), + char_count, + "All characters must have been processed" + ); + } +} + +/// Shape one segment. +/// +/// Returns `Err(())` if shaping should be aborted, which happens iff [`FontSelector::select_font`] +/// returned `None`. +fn shape_segment( + scx: &mut Shaper, + text: &str, + segment: &Segment, + options: &ShapeOptions<'_>, + select_font: &mut impl FontSelector, + char_info: &[CharInfo], + char_style_indices: &[u16], + shaped_text: &mut ShapedText, +) -> Result<(), ()> { + select_font.begin_segment(segment, options); + + let text_range = &segment.range.byte_range; + let char_range = &segment.range.char_range; + + let segment_text = &text[text_range.clone()]; + + // Only process current segment + let segment_char_info = &char_info[char_range.start..char_range.end]; + let segment_char_style_indices = &char_style_indices[char_range.start..char_range.end]; + + if segment_text.is_empty() { + return Ok(()); // No clusters + } + + let char_cluster = &mut scx.char_cluster; + + // Shaping inputs that are constant over the segment. + let direction = if segment.bidi_level.is_rtl() { + harfrust::Direction::RightToLeft + } else { + harfrust::Direction::LeftToRight + }; + let hb_script = script_to_harfrust(segment.script); + let language = options + .language + .as_ref() + .and_then(|lang| lang.as_str().parse::<harfrust::Language>().ok()); + scx.features.clear(); + scx.features.extend(options.features.iter().map(|feature| { + harfrust::Feature::new( + harfrust::Tag::new(&feature.tag.to_bytes()), + feature.value as u32, + .., + ) + })); + + // Shape a run of the segment with a single font, appending it to `shaped_text`. + let mut shape_run = |font: &FontInstance, range: TextRange| { + // The platform's face: its host measures the run and draws it (`platform`). + if let Some(platform) = crate::platform::shaper(font.font.data.id()) { + shape_platform_run(platform, text, range, segment, options, char_info, char_style_indices, font, shaped_text); + return; + } + // TODO: How do we want to handle errors like this? + let font_ref = + harfrust::FontRef::from_index(font.font.data.as_ref(), font.font.index).unwrap(); + + // Create harfrust shaper + let shaper_data = scx.shape_data_cache.entry( + cache::ShapeDataKey::new(font.font.data.id(), font.font.index), + || harfrust::ShaperData::new(&font_ref), + ); + let instance = scx.shape_instance_cache.entry( + cache::ShapeInstanceKey::new( + font.font.data.id(), + font.font.index, + &font.synthesis, + Some(options.variations), + ), + || { + harfrust::ShaperInstance::from_variations( + &font_ref, + variations_iter(&font.synthesis, options.variations), + ) + }, + ); + + let harf_shaper = shaper_data + .shaper(&font_ref) + .instance(Some(instance)) + .build(); + let shaper_plan = scx.shape_plan_cache.entry( + cache::ShapePlanKey::new( + font.font.data.id(), + font.font.index, + &font.synthesis, + direction, + hb_script, + language.clone(), + &scx.features, + Some(options.variations), + ), + || { + harfrust::ShapePlan::new( + &harf_shaper, + direction, + Some(hb_script), + language.as_ref(), + &scx.features, + ) + }, + ); + + // Prepare harfrust buffer + let mut buffer = mem::take(&mut scx.unicode_buffer).unwrap(); + buffer.clear(); + buffer.set_cluster_level(harfrust::BufferClusterLevel::MonotoneCharacters); + + // Use the entire run text including newlines. + let run_text = &text[range.byte_range.clone()]; + buffer.reserve(run_text.len()); + #[expect(clippy::cast_possible_truncation, reason = "Deferred")] + for (i, ch) in run_text.chars().enumerate() { + // Ensure that each cluster's index matches the index into `infos`. This is required + // for efficient cluster lookup within `data.rs`. + // + // In other words, instead of using `buffer.push_str`, which iterates `run_text` + // with `char_indices`, push each char individually via `.chars` with a cluster index + // that matches its `infos` counterpart. This allows us to lookup `infos` via cluster + // index in `data.rs`. + buffer.add(ch, i as u32); + } + + buffer.set_pre_context(&text[..range.byte_range.start]); + buffer.set_post_context(&text[range.byte_range.end..]); + buffer.set_direction(direction); + buffer.set_script(hb_script); + + if let Some(lang) = &language { + buffer.set_language(lang.clone()); + } + + let glyph_buffer = harf_shaper.shape( + buffer, + HarfShapeOptions::new() + .plan(Some(shaper_plan)) + .features(&scx.features) + .point_size(Some(options.font_size)), + ); + + // A run's metrics depend on its font instance and size alone: made once for each. + let metrics = *scx.run_metrics_cache.entry( + cache::RunMetricsKey::new( + cache::ShapeInstanceKey::new( + font.font.data.id(), + font.font.index, + &font.synthesis, + Some(options.variations), + ), + options.font_size, + ), + || { + let font_ref = + skrifa::FontRef::from_index(font.font.data.as_ref(), font.font.index).unwrap(); + let metrics = skrifa::metrics::Metrics::new( + &font_ref, + skrifa::prelude::Size::new(options.font_size), + harf_shaper.coords(), + ); + ( + FontMetrics::from_skrifa_metrics(&metrics, options.font_size), + metrics.units_per_em as f32, + ) + }, + ); + shaped_text.push_run( + text, + range, + segment, + options, + char_info, + char_style_indices, + font, + glyph_buffer.glyph_infos(), + glyph_buffer.glyph_positions(), + harf_shaper.coords(), + metrics, + ); + + // Replace buffer to reuse allocation in the next run. + scx.unicode_buffer = Some(glyph_buffer.clear()); + }; + + // This is the run being accumulated, i.e., consecutive graphemes for which `select_font` + // returns the same font. + let mut run: Option<(FontInstance, TextRange)> = None; + + // The segment's characters with their analysis data and style indices. + let mut chars = segment_text + .chars() + .zip(segment_char_info) + .zip(segment_char_style_indices) + .map(|((ch, &info), &style_index)| (ch, info, style_index)); + + // The lengths of the segment's graphemes in characters. + let grapheme_lengths = segment_char_info + .chunk_by(|_, info| !info.is_grapheme_start()) + .map(<[_]>::len); + + // The end of the previous grapheme. + let mut byte_end = text_range.start; + let mut char_end = char_range.start; + + for grapheme_length in grapheme_lengths { + let (byte_start, char_start) = (byte_end, char_end); + char_cluster.fill(chars.by_ref().take(grapheme_length), &mut byte_end); + char_end += grapheme_length; + let grapheme = TextRange { + byte_range: byte_start..byte_end, + char_range: char_start..char_end, + }; + + let font = select_font + .select_font(segment, options, char_cluster) + .ok_or(())?; + + if let Some((run_font, run_range)) = &mut run + && run_font.as_ref() == font + { + run_range.byte_range.end = byte_end; + run_range.char_range.end = char_end; + } else { + if let Some((run_font, run_range)) = run.take() { + // The font changed: shape the previous run. + shape_run(&run_font, run_range); + } + run = Some((font.into(), grapheme)); + } + } + if let Some((run_font, run_range)) = run { + shape_run(&run_font, run_range); + } + + Ok(()) +} + +#[inline] +fn variations_iter<'a>( + synthesis: &'a fontique::Synthesis, + item: &'a [FontVariation], +) -> impl Iterator<Item = harfrust::Variation> + 'a { + synthesis + .variation_settings() + .iter() + .map(|(tag, value)| harfrust::Variation { + tag: *tag, + value: *value, + }) + .chain(item.iter().map(|variation| harfrust::Variation { + tag: harfrust::Tag::new(&variation.tag.to_bytes()), + value: variation.value, + })) +} + +/// A run in the platform's face (`platform`), appended to `shaped_text`: its host gives a glyph +/// per grapheme, with units it draws whole between the run's break opportunities. +#[expect(clippy::too_many_arguments, reason = "the shape_run closure's inputs")] +fn shape_platform_run( + shaper: crate::platform::PlatformShaper, + text: &str, + range: TextRange, + segment: &Segment, + options: &ShapeOptions<'_>, + char_info: &[CharInfo], + char_style_indices: &[u16], + font: &FontInstance, + shaped_text: &mut ShapedText, +) { + let run_text = &text[range.byte_range.clone()]; + let (mut graphemes, mut units, mut clusters) = (Vec::new(), Vec::new(), Vec::new()); + let mut after_newline = false; + for (i, ((at, ch), info)) in run_text.char_indices().zip(&char_info[range.char_range.clone()]).enumerate() { + let newline = matches!(ch, '\n' | '\r' | '\u{0B}' | '\u{0C}' | '\u{85}' | '\u{2028}' | '\u{2029}'); + let grapheme = i == 0 || info.is_grapheme_start() || newline || after_newline; + if grapheme { + #[expect(clippy::cast_possible_truncation, reason = "a run is under 4 GiB")] + { + if i == 0 || info.is_soft_wrap_opportunity() || newline || after_newline { + units.push(at as u32); + } + graphemes.push(at as u32); + clusters.push(i as u32); + } + } + after_newline = newline; + } + let wght = harfrust::Tag::new(b"wght"); + let weight = variations_iter(&font.synthesis, options.variations) + .filter(|v| v.tag == wght) + .last() + .map_or(if font.synthesis.embolden() { 700. } else { 400. }, |v| v.value); + let rtl = segment.bidi_level.is_rtl(); + let mut glyphs = Vec::with_capacity(graphemes.len()); + shaper( + &crate::platform::PlatformText { + text: run_text, + graphemes: &graphemes, + units: &units, + size: options.font_size, + weight, + italic: font.synthesis.skew().is_some(), + rtl, + language: options.language.as_ref().map(|l| l.as_str()), + }, + &mut glyphs, + ); + glyphs.resize(graphemes.len(), crate::platform::PlatformGlyph::default()); + let font_ref = skrifa::FontRef::from_index(font.font.data.as_ref(), font.font.index).unwrap(); + let metrics = skrifa::metrics::Metrics::new( + &font_ref, + skrifa::prelude::Size::new(options.font_size), + skrifa::instance::LocationRef::default(), + ); + let upem = metrics.units_per_em as f32; + let units_of = |px: f32| (px * upem / options.font_size.max(1e-3)).round() as i32; + let mut infos: Vec<harfrust::GlyphInfo> = Vec::with_capacity(glyphs.len()); + let mut positions: Vec<harfrust::GlyphPosition> = Vec::with_capacity(glyphs.len()); + for (glyph, &cluster) in glyphs.iter().zip(&clusters) { + let mut info = harfrust::GlyphInfo::default(); + info.glyph_id = glyph.id; + info.cluster = cluster; + infos.push(info); + let mut position = harfrust::GlyphPosition::default(); + position.x_advance = units_of(glyph.advance); + position.x_offset = units_of(glyph.x_offset); + positions.push(position); + } + // In visual order, as HarfRust gives them. + if rtl { + infos.reverse(); + positions.reverse(); + } + shaped_text.push_run( + text, + range, + segment, + options, + char_info, + char_style_indices, + font, + &infos, + &positions, + &[], + (FontMetrics::from_skrifa_metrics(&metrics, options.font_size), upem), + ); +} + +pub(crate) fn script_to_harfrust(script: fontique::Script) -> harfrust::Script { + harfrust::Script::from_iso15924_tag(harfrust::Tag::new(&script.to_bytes())) + .unwrap_or(harfrust::script::UNKNOWN) +} + +/// Implements font selection for shaping. +pub trait FontSelector { + /// Called when a new segment starts. + /// + /// This can be useful to inspect, e.g., the segment's script. + fn begin_segment(&mut self, segment: &Segment, options: &ShapeOptions<'_>) { + let _ = (segment, options); + } + + /// Called once per character cluster within the current segment. + /// + /// A character cluster will usually be a grapheme, though if text direction or script changes + /// mid-grapheme, it will be split over segments. + /// + /// Shaping is aborted if this returns `None`; [`ShapedText`] then contains a partial result. + fn select_font( + &mut self, + segment: &Segment, + options: &ShapeOptions<'_>, + cluster: &mut CharCluster, + ) -> Option<FontInstanceRef<'_>>; +} diff --git a/app/vendor/rune/vendor/sctk-adwaita.patch b/app/vendor/rune/vendor/sctk-adwaita.patch new file mode 100644 index 0000000..f4a54ab --- /dev/null +++ b/app/vendor/rune/vendor/sctk-adwaita.patch @@ -0,0 +1,917 @@ +diff --git a/src/lib.rs b/src/lib.rs +index a50e538..c39ed71 100644 +--- a/src/lib.rs ++++ b/src/lib.rs +@@ -5,8 +5,8 @@ use std::sync::Arc; + use std::time::Duration; + + use tiny_skia::{ +- Color, FillRule, Mask, Path, PathBuilder, Pixmap, PixmapMut, PixmapPaint, Point, Rect, +- Transform, ++ BlendMode, Color, FillRule, Mask, Paint, Path, PathBuilder, Pixmap, PixmapMut, PixmapPaint, ++ Point, Rect, Shader, Transform, + }; + + use smithay_client_toolkit::reexports::client::backend::ObjectId; +@@ -27,6 +27,8 @@ use smithay_client_toolkit::subcompositor::SubsurfaceData; + mod buttons; + mod config; + mod parts; ++#[cfg(test)] ++mod tests; + mod pointer; + mod shadow; + pub mod theme; +@@ -143,6 +145,14 @@ where + self.dirty = true; + } + ++ /// The radius, in logical points, of the arc this frame leaves the window's content at its ++ /// bottom corners: the visible border is drawn within one point outside it. Zero when the ++ /// frame draws the window square, as a maximized, tiled or fullscreen one is (and as the ++ /// headerbar's top corners are). ++ pub fn content_corner_radius(&self) -> f32 { ++ content_radius(self.state) ++ } ++ + fn precise_location( + &self, + location: Location, +@@ -225,7 +235,6 @@ where + } else { + true + }; +- let border_paint = colors.border_paint(); + + // Draw the borders. + for (idx, part) in decorations +@@ -265,12 +274,22 @@ where + // do invisible borders to enlarge the input zone. + pixmap.fill(Color::TRANSPARENT); + +- if !self.state.intersects(WindowState::TILED) { ++ // The bottom and side parts draw their shadow along with their border: the bottom one ++ // is the part that reaches over the window, so its corners are cut out of the shadow it ++ // draws there, and a side part's border stops where the bottom corner's arc takes over. ++ if !matches!( ++ idx, ++ DecorationParts::BOTTOM | DecorationParts::LEFT | DecorationParts::RIGHT ++ ) && !self.state.intersects(WindowState::TILED) ++ { + self.shadow.draw( + &mut pixmap, + scale, + self.state.contains(WindowState::ACTIVATED), + idx, ++ // The other parts have no rounded corners of their own to reach over the ++ // window with. ++ 0., + ); + } + +@@ -292,51 +311,23 @@ where + self.mouse.location, + ); + } +- border => { +- // The visible border is one pt. +- let visible_border_size = VISIBLE_BORDER_SIZE * scale; +- +- // XXX we do all the match using integral types and then convert to f32 in the +- // end to ensure that result is finite. +- let border_rect = match border { +- DecorationParts::LEFT => { +- let x = (rect.x.unsigned_abs() * scale) - visible_border_size; +- let y = rect.y.unsigned_abs() * scale; +- Rect::from_xywh( +- x as f32, +- y as f32, +- visible_border_size as f32, +- (rect.height - y) as f32, +- ) +- } +- DecorationParts::RIGHT => { +- let y = rect.y.unsigned_abs() * scale; +- Rect::from_xywh( +- 0., +- y as f32, +- visible_border_size as f32, +- (rect.height - y) as f32, +- ) +- } +- // We draw small visible border only bellow the window surface, no need to +- // handle `TOP`. +- DecorationParts::BOTTOM => { +- let x = (rect.x.unsigned_abs() * scale) - visible_border_size; +- Rect::from_xywh( +- x as f32, +- 0., +- (rect.width - 2 * x) as f32, +- visible_border_size as f32, +- ) +- } +- _ => None, +- }; +- +- // Fill the visible border, if present. +- if let Some(border_rect) = border_rect { +- pixmap.fill_rect(border_rect, &border_paint, Transform::identity(), None); +- } ++ DecorationParts::BOTTOM => { ++ draw_bottom( ++ &mut pixmap, ++ &mut self.shadow, ++ colors, ++ &self.state, ++ scale, ++ rect.width, ++ ); ++ } ++ DecorationParts::LEFT => { ++ draw_side(&mut pixmap, &mut self.shadow, colors, &self.state, scale, false); ++ } ++ DecorationParts::RIGHT => { ++ draw_side(&mut pixmap, &mut self.shadow, colors, &self.state, scale, true); + } ++ _ => {} + }; + + if should_sync { +@@ -770,6 +761,212 @@ fn rounded_headerbar_shape(x: f32, y: f32, width: f32, height: f32, radius: f32) + pb.finish() + } + ++/// The radius, in logical points, of the arc a frame leaves the window's content at its bottom ++/// corners. The frame's one-point visible border is drawn just outside that arc, so the window's ++/// own corners are [`VISIBLE_BORDER_SIZE`] more, and the shadow's rounded cut-out is the same ++/// disc. ++pub const CONTENT_CORNER_RADIUS: u32 = CORNER_RADIUS - VISIBLE_BORDER_SIZE; ++ ++/// The radius, in logical points, of the arc this frame leaves the window's content at its bottom ++/// corners in `state`: zero when the window is square, as a maximized, tiled or fullscreen one is. ++fn content_radius(state: WindowState) -> f32 { ++ if square(state) { ++ 0. ++ } else { ++ CONTENT_CORNER_RADIUS as f32 ++ } ++} ++ ++/// The radius, in logical points, of the visible border's outer edge around the window's bottom ++/// corners in `state`: [`CORNER_RADIUS`], or zero when the window is square. ++fn border_radius(state: WindowState) -> f32 { ++ if square(state) { ++ 0. ++ } else { ++ CORNER_RADIUS as f32 ++ } ++} ++ ++/// Whether `state` draws the window's corners square, as the headerbar's top ones are: maximized, ++/// tiled and fullscreen windows have no corners to round. ++fn square(state: WindowState) -> bool { ++ state.intersects(WindowState::MAXIMIZED | WindowState::TILED | WindowState::FULLSCREEN) ++} ++ ++/// Draws the bottom part: its shadow, the arcs cut out of it where the content's own rounded ++/// corners show through, and the visible border around them. ++fn draw_bottom( ++ pixmap: &mut PixmapMut, ++ shadow: &mut Shadow, ++ colors: &ColorMap, ++ state: &WindowState, ++ scale: u32, ++ width: u32, ++) { ++ let border = (VISIBLE_BORDER_SIZE * scale) as f32; ++ // The part is placed one corner radius above the window's bottom edge, and spans it plus the ++ // shadow and border around the window: `left` and `right` are the window's outer edges. ++ let left = (BORDER_SIZE * scale) as f32 - border; ++ let right = width as f32 - left; ++ let bottom = (CORNER_RADIUS * scale) as f32; ++ let radius = border_radius(*state) * scale as f32; ++ ++ if !state.intersects(WindowState::TILED) { ++ shadow.draw(pixmap, scale, state.contains(WindowState::ACTIVATED), DecorationParts::BOTTOM, radius); ++ } ++ ++ if radius < border { ++ if let Some(rect) = Rect::from_xywh(left, bottom, (right - left).max(0.), border) { ++ pixmap.fill_rect(rect, &colors.border_paint(), Transform::identity(), None); ++ } ++ return; ++ } ++ // The band above the window's bottom edge carries the shadow's corner crescents, so the arcs ++ // are cleared out of it before the border is drawn along them: the shadow stays outside the ++ // arcs the content leaves, and nothing stays where the content shows through. ++ clear_bottom_corner_holes(pixmap, left, right, bottom, border, radius); ++ if let Some(shape) = bottom_border_shape(left, right, bottom, border, radius) { ++ pixmap.fill_path(&shape, &colors.border_paint(), FillRule::EvenOdd, Transform::identity(), None); ++ } ++} ++ ++/// Draws a side part (`LEFT` or `RIGHT`): the shadow down that side of the window, and the visible ++/// border along it, from under the headerbar to where the bottom corner's arc takes over. ++fn draw_side( ++ pixmap: &mut PixmapMut, ++ shadow: &mut Shadow, ++ colors: &ColorMap, ++ state: &WindowState, ++ scale: u32, ++ right: bool, ++) { ++ let idx = if right { DecorationParts::RIGHT } else { DecorationParts::LEFT }; ++ if !state.intersects(WindowState::TILED) { ++ shadow.draw(pixmap, scale, state.contains(WindowState::ACTIVATED), idx, 0.); ++ } ++ let border = (VISIBLE_BORDER_SIZE * scale) as f32; ++ let top = (HEADER_SIZE * scale) as f32; ++ let corner = (border_radius(*state) * scale as f32 - border).max(0.); ++ let height = (pixmap.height() as f32 - top - corner).max(0.); ++ let x = if right { 0. } else { (BORDER_SIZE * scale) as f32 - border }; ++ if let Some(rect) = Rect::from_xywh(x, top, border, height) { ++ pixmap.fill_rect(rect, &colors.border_paint(), Transform::identity(), None); ++ } ++} ++ ++/// Clears the two discs of radius `radius` the bottom part's shadow is cut out of, so the part ++/// leaves the content's rounded corners alone. ++fn clear_bottom_corner_holes(pixmap: &mut PixmapMut, left: f32, right: f32, bottom: f32, border: f32, radius: f32) { ++ // Each arc's centre is the content's: `border` up from the content's bottom edge, `radius` in ++ // from the window's edge. ++ let centre_y = bottom + border - radius; ++ let paint = Paint { ++ shader: Shader::SolidColor(Color::TRANSPARENT), ++ blend_mode: BlendMode::Clear, ++ anti_alias: true, ++ ..Paint::default() ++ }; ++ for centre_x in [left + radius, right - radius] { ++ if let Some(circle) = circle_path(centre_x, centre_y, radius) { ++ pixmap.fill_path(&circle, &paint, FillRule::Winding, Transform::identity(), None); ++ } ++ } ++} ++ ++/// A circle of `radius` around `(cx, cy)`, as four cubic arcs. ++fn circle_path(cx: f32, cy: f32, radius: f32) -> Option<Path> { ++ if radius <= 0. { ++ return None; ++ } ++ // https://stackoverflow.com/a/27863181, as `rounded_headerbar_shape`. ++ let k = 0.552_284_8 * radius; ++ let mut pb = PathBuilder::new(); ++ pb.move_to(cx + radius, cy); ++ pb.cubic_to(cx + radius, cy + k, cx + k, cy + radius, cx, cy + radius); ++ pb.cubic_to(cx - k, cy + radius, cx - radius, cy + k, cx - radius, cy); ++ pb.cubic_to(cx - radius, cy - k, cx - k, cy - radius, cx, cy - radius); ++ pb.cubic_to(cx + k, cy - radius, cx + radius, cy - k, cx + radius, cy); ++ pb.close(); ++ pb.finish() ++} ++ ++/// The visible border under a window whose bottom corners are rounded with `radius`: a one-point ++/// band along `bottom`, the content's bottom edge, from `left` to `right`, the window's outer ++/// edges, curving around each corner outside the arc the content leaves (centred one radius inside ++/// the window's corner, so the band sits between that arc and the shadow). A window too narrow for ++/// both arcs rounds them as far as it can. ++fn bottom_border_shape( ++ left: f32, ++ right: f32, ++ bottom: f32, ++ border: f32, ++ radius: f32, ++) -> Option<Path> { ++ if !(left.is_finite() && right.is_finite() && bottom.is_finite() && border.is_finite() && radius.is_finite()) ++ || border <= 0. ++ || right <= left ++ { ++ return None; ++ } ++ // https://stackoverflow.com/a/27863181, as `rounded_headerbar_shape`. ++ let k = 0.552_284_8; ++ let radius = radius.min((right - left) / 2.).max(border); ++ let outer = bottom + border; ++ let (outer_radius, inner_radius) = (radius, radius - border); ++ // One disc per corner: its centre is the content's arc centre, `outer` less the outer radius. ++ let centre_y = outer - outer_radius; ++ let (left_centre, right_centre) = (left + outer_radius, right - outer_radius); ++ ++ let mut pb = PathBuilder::new(); ++ // The window's outline: down the left edge, around the corner, along the bottom, around the ++ // other corner, and up the right edge. ++ pb.move_to(left, 0.); ++ pb.line_to(left, centre_y); ++ pb.cubic_to( ++ left, ++ centre_y + k * outer_radius, ++ left_centre - k * outer_radius, ++ outer, ++ left_centre, ++ outer, ++ ); ++ pb.line_to(right_centre, outer); ++ pb.cubic_to( ++ right_centre + k * outer_radius, ++ outer, ++ right, ++ centre_y + k * outer_radius, ++ right, ++ centre_y, ++ ); ++ pb.line_to(right, 0.); ++ pb.close(); ++ // And the content's, one point inside it: filling both even-odd leaves the border between. ++ pb.move_to(left + border, 0.); ++ pb.line_to(left + border, centre_y); ++ pb.cubic_to( ++ left + border, ++ centre_y + k * inner_radius, ++ left_centre - k * inner_radius, ++ bottom, ++ left_centre, ++ bottom, ++ ); ++ pb.line_to(right_centre, bottom); ++ pb.cubic_to( ++ right_centre + k * inner_radius, ++ bottom, ++ right - border, ++ centre_y + k * inner_radius, ++ right - border, ++ centre_y, ++ ); ++ pb.line_to(right - border, 0.); ++ pb.close(); ++ ++ pb.finish() ++} ++ + // returns horizontal margin, logical points + fn get_margin_h_lp(state: &WindowState) -> f32 { + if state.intersects(WindowState::MAXIMIZED | WindowState::TILED) { +diff --git a/src/parts.rs b/src/parts.rs +index 7ae54ed..4d92a72 100644 +--- a/src/parts.rs ++++ b/src/parts.rs +@@ -9,9 +9,23 @@ use smithay_client_toolkit::{ + subcompositor::{SubcompositorState, SubsurfaceData}, + }; + +-use crate::theme::{BORDER_SIZE, HEADER_SIZE, RESIZE_HANDLE_SIZE}; ++use crate::theme::{BORDER_SIZE, CORNER_RADIUS, HEADER_SIZE, RESIZE_HANDLE_SIZE}; + use crate::{pointer::Location, wl_typed::WlTyped}; + ++/// The bottom part's input zone, which is its resize handle: it starts at the window's bottom ++/// edge, not at the part's top, since the part reaches a corner radius above the edge and must not ++/// take input there from the content. ++pub(crate) fn bottom_input_rect(surface_width: u32) -> Rect { ++ Rect { ++ x: BORDER_SIZE as i32 - RESIZE_HANDLE_SIZE as i32, ++ y: CORNER_RADIUS as i32, ++ width: surface_width ++ .saturating_sub(BORDER_SIZE * 2) ++ .saturating_add(RESIZE_HANDLE_SIZE * 2), ++ height: RESIZE_HANDLE_SIZE, ++ } ++} ++ + /// The decoration's 'parts'. + #[derive(Debug)] + pub struct DecorationParts { +@@ -101,14 +115,11 @@ impl DecorationParts { + x: -(BORDER_SIZE as i32), + y: 0, // Defined by `Self::resize`. + width: 0, // Defined by `Self::resize`. +- height: BORDER_SIZE, ++ // Reaches above the window's bottom edge, so the visible border can follow the ++ // rounded corners the content leaves it (`Self::resize`). ++ height: BORDER_SIZE + CORNER_RADIUS, + }, +- Some(Rect { +- x: BORDER_SIZE as i32 - RESIZE_HANDLE_SIZE as i32, +- y: 0, +- width: 0, // Defined by `Self::resize`, +- height: RESIZE_HANDLE_SIZE, +- }), ++ Some(bottom_input_rect(0)), + ), + // Header. + Part::new( +@@ -154,10 +165,11 @@ impl DecorationParts { + self.parts[Self::HEADER].surface_rect.width = width; + + self.parts[Self::BOTTOM].surface_rect.width = width + 2 * BORDER_SIZE; +- self.parts[Self::BOTTOM].surface_rect.y = height as i32; +- self.parts[Self::BOTTOM].input_rect.as_mut().unwrap().width = +- self.parts[Self::BOTTOM].surface_rect.width - (BORDER_SIZE * 2) +- + (RESIZE_HANDLE_SIZE * 2); ++ // `CORNER_RADIUS` above the window's bottom edge, where its rounded corners are: the ++ // visible border is drawn in that part of it. ++ self.parts[Self::BOTTOM].surface_rect.y = height as i32 - CORNER_RADIUS as i32; ++ *self.parts[Self::BOTTOM].input_rect.as_mut().unwrap() = ++ bottom_input_rect(self.parts[Self::BOTTOM].surface_rect.width); + + self.parts[Self::TOP].surface_rect.width = self.parts[Self::BOTTOM].surface_rect.width; + self.parts[Self::TOP].input_rect.as_mut().unwrap().width = +diff --git a/src/shadow.rs b/src/shadow.rs +index efa9133..669736b 100644 +--- a/src/shadow.rs ++++ b/src/shadow.rs +@@ -8,7 +8,9 @@ pub const SHADOW_SIZE: u32 = 43; + const SHADOW_PARAMS_ACTIVE: (f32, f32, f32) = (0.206_505_5, 0.104_617_53, -0.000_542_446_2); + const SHADOW_PARAMS_INACTIVE: (f32, f32, f32) = (0.168_297_29, 0.204_299_8, 0.001_769_798_6); + +-fn shadow(pixel_dist: f32, scale: u32, active: bool) -> f32 { ++/// The shadow's alpha at `pixel_dist` from the window's outline: the frame's own model of it, ++/// which `tests` reads as its reference. ++pub(crate) fn shadow(pixel_dist: f32, scale: u32, active: bool) -> f32 { + let (a, b, c) = if active { + SHADOW_PARAMS_ACTIVE + } else { +@@ -146,7 +148,7 @@ impl RenderedShadow { + } + } + +- fn draw(&self, dst_pixmap: &mut PixmapMut, scale: u32, part_idx: usize) { ++ fn draw(&self, dst_pixmap: &mut PixmapMut, scale: u32, part_idx: usize, corners: f32) { + let shadow_size = (SHADOW_SIZE * scale) as usize; + let visible_border_size = (theme::VISIBLE_BORDER_SIZE * scale) as usize; + let corner_radius = (theme::CORNER_RADIUS * scale) as usize; +@@ -211,13 +213,16 @@ impl RenderedShadow { + + self.side_draw(true, false, side_height, dst_pixmap, 0, top_edge_height); + ++ // The bottom corner's piece reaches the border's own column: below the arc's ++ // tangent the side part draws no border there, and the shadow continues to the ++ // window's edge (`draw_side`). + self.edges_draw( + 0, + edges_half as isize, + dst_pixmap, + 0, + top_edge_height + side_height, +- dst_width.saturating_sub(visible_border_size), ++ dst_width, + bottom_edge_height, + ); + } +@@ -247,13 +252,17 @@ impl RenderedShadow { + top_edge_height, + ); + ++ // The bottom corner's piece reaches the border's own column, where the side part ++ // draws no border below the arc's tangent: its source keeps the disc's centre where ++ // the top piece puts it (a corner radius outside this part, so `+ corner_radius`, ++ // less the column the piece now starts at). + self.edges_draw( +- edges_half as isize + corner_radius as isize, ++ edges_half as isize + (corner_radius - visible_border_size) as isize, + edges_half as isize, + dst_pixmap, +- visible_border_size, ++ 0, + top_edge_height + side_height, +- dst_width.saturating_sub(visible_border_size), ++ dst_width, + bottom_edge_height, + ); + } +@@ -264,12 +273,17 @@ impl RenderedShadow { + .saturating_sub(left_edge_width) + .saturating_sub(right_edge_width); + ++ // Below the window's bottom edge the shadow is a square frame's, whatever the ++ // corners, and the discs sit `visible_border_size` up from that edge: the source ++ // row puts them on the same pixel here and in the square part. ++ let corner_src_y = ++ edges_half as isize + (corner_radius - visible_border_size) as isize; + self.edges_draw( + 0, +- edges_half as isize + (corner_radius - visible_border_size) as isize, ++ corner_src_y, + dst_pixmap, + 0, +- 0, ++ corner_radius, + left_edge_width, + dst_height, + ); +@@ -280,18 +294,36 @@ impl RenderedShadow { + side_width, + dst_pixmap, + left_edge_width, +- visible_border_size, ++ corner_radius + visible_border_size, + ); + + self.edges_draw( + edges_half as isize, +- edges_half as isize + (corner_radius - visible_border_size) as isize, ++ corner_src_y, + dst_pixmap, + left_edge_width + side_width, +- 0, ++ corner_radius, + right_edge_width, + dst_height, + ); ++ ++ if corners > 0. { ++ // The band above that edge carries the crescents the arcs cut out of the ++ // shadow, and only inside the content's own corner squares: outside them the ++ // side parts already draw the shadow down to the edge, and a second copy here ++ // would composite over theirs (the parts stack) and double it. ++ // ++ // The band's source keeps the disc's centre where the corner piece above puts ++ // it: `edges_half` in the image, `centre_x` in the part. ++ let band_src_y = edges_half as isize - visible_border_size as isize; ++ let margin = theme::BORDER_SIZE as usize * scale as usize; ++ let centres = [edges_half, dst_width.saturating_sub(edges_half)]; ++ let bands = [margin, dst_width.saturating_sub(margin + corner_radius)]; ++ for (centre_x, band_left) in centres.into_iter().zip(bands) { ++ let src_x = band_left as isize - centre_x as isize + edges_half as isize; ++ self.edges_draw(src_x, band_src_y, dst_pixmap, band_left, 0, corner_radius, corner_radius); ++ } ++ } + } + DecorationParts::HEADER => { + self.edges_draw( +@@ -324,6 +356,8 @@ struct CachedPart { + pixmap: Pixmap, + scale: u32, + active: bool, ++ /// Whether it was drawn for round bottom corners, whose shadow reaches over the window. ++ corners: bool, + } + + impl CachedPart { +@@ -333,23 +367,26 @@ impl CachedPart { + scale: u32, + active: bool, + part_idx: usize, ++ corners: f32, + ) -> CachedPart { + #[allow(clippy::unwrap_used)] + let mut pixmap = Pixmap::new(dst_pixmap.width(), dst_pixmap.height()).unwrap(); +- rendered.draw(&mut pixmap.as_mut(), scale, part_idx); ++ rendered.draw(&mut pixmap.as_mut(), scale, part_idx, corners); + + CachedPart { + pixmap, + scale, + active, ++ corners: corners > 0., + } + } + +- fn matches(&self, dst_pixmap: &PixmapRef, dst_scale: u32, dst_active: bool) -> bool { ++ fn matches(&self, dst_pixmap: &PixmapRef, dst_scale: u32, dst_active: bool, corners: bool) -> bool { + self.pixmap.width() == dst_pixmap.width() + && self.pixmap.height() == dst_pixmap.height() + && self.scale == dst_scale + && self.active == dst_active ++ && self.corners == corners + } + + fn draw(&self, dst_pixmap: &mut PixmapMut) { +@@ -366,11 +403,15 @@ pub struct Shadow { + } + + impl Shadow { +- pub fn draw(&mut self, pixmap: &mut PixmapMut, scale: u32, active: bool, part_idx: usize) { ++ /// Draws part `part_idx`'s shadow. `corners` is the radius, in the part's pixels, of the round ++ /// bottom corners it is drawn for (zero for square ones): the bottom part reaches that far ++ /// above the window's bottom edge, so with round corners its shadow starts at the part's top. ++ pub fn draw(&mut self, pixmap: &mut PixmapMut, scale: u32, active: bool, part_idx: usize, corners: f32) { + let cache = &mut self.part_cache[part_idx]; ++ let round = corners > 0.; + + if let Some(cache_value) = cache { +- if !cache_value.matches(&pixmap.as_ref(), scale, active) { ++ if !cache_value.matches(&pixmap.as_ref(), scale, active, round) { + *cache = None; + } + } +@@ -387,6 +428,7 @@ impl Shadow { + scale, + active, + part_idx, ++ corners, + )); + } + +diff --git a/src/tests.rs b/src/tests.rs +new file mode 100644 +index 0000000..15b61f0 +--- /dev/null ++++ b/src/tests.rs +@@ -0,0 +1,308 @@ ++//! The frame's rounded bottom corners: the radius each state gets, the border along the arcs, the ++//! shadow the arcs cut out of the part that reaches over the window, and the bottom part's input ++//! zone. Everything here draws into a `Pixmap` the way `redraw_inner` does, so it needs no ++//! compositor. ++ ++use crate::parts::{bottom_input_rect, DecorationParts}; ++use crate::theme::{ColorTheme, BORDER_SIZE, CORNER_RADIUS, HEADER_SIZE, RESIZE_HANDLE_SIZE, VISIBLE_BORDER_SIZE}; ++use crate::{ ++ border_radius, bottom_border_shape, content_radius, draw_bottom, draw_side, CONTENT_CORNER_RADIUS, ++}; ++use smithay_client_toolkit::reexports::csd_frame::WindowState; ++use tiny_skia::{FillRule, Pixmap, PixmapPaint, Transform}; ++ ++/// A pixel's alpha. ++fn alpha(pixmap: &Pixmap, x: u32, y: u32) -> u8 { ++ pixmap ++ .pixel(x, y) ++ .unwrap_or_else(|| panic!("({x}, {y}) is outside {}x{}", pixmap.width(), pixmap.height())) ++ .alpha() ++} ++ ++/// Asserts the pixel is the light theme's border colour, within the antialiasing of the arcs, and ++/// covered at least `min_alpha` of the way (the band is a point wide, so a pixel on the diagonal ++/// is only part of it). ++fn assert_border(pixmap: &Pixmap, x: u32, y: u32, min_alpha: u8, what: &str) { ++ let pixel = pixmap.pixel(x, y).expect("inside the pixmap").demultiply(); ++ let got = [pixel.red(), pixel.green(), pixel.blue()]; ++ let want = [220, 220, 220]; ++ assert!( ++ got.iter().zip(want).all(|(a, b)| a.abs_diff(b) <= 4), ++ "{what}: {got:?} at ({x}, {y}) is not the border colour {want:?}", ++ ); ++ assert!(pixel.alpha() >= min_alpha, "{what}: the band covers {}, not {min_alpha}", pixel.alpha()); ++} ++ ++/// The bottom part's pixmap as a window `width` points wide draws it: the shadow, the arcs cleared ++/// out of it, and the border along them. ++fn bottom_part(width: u32, state: WindowState) -> Pixmap { ++ let surface = (width + 2 * BORDER_SIZE, BORDER_SIZE + CORNER_RADIUS); ++ let mut pixmap = Pixmap::new(surface.0, surface.1).expect("a pixmap"); ++ draw_bottom( ++ &mut pixmap.as_mut(), ++ &mut Default::default(), ++ &ColorTheme::light().active, ++ &state, ++ 1, ++ surface.0, ++ ); ++ pixmap ++} ++ ++/// The frame's radius follows the window's state: round while it floats, square when the window ++/// fills the screen or is tiled, and square in fullscreen, where the frame hides its borders. ++#[test] ++fn the_radius_follows_the_window_state() { ++ assert_eq!(content_radius(WindowState::empty()), CONTENT_CORNER_RADIUS as f32); ++ assert_eq!(border_radius(WindowState::empty()), CORNER_RADIUS as f32); ++ // An active window rounds the same as an inactive one. ++ assert_eq!(content_radius(WindowState::ACTIVATED), CONTENT_CORNER_RADIUS as f32); ++ for square in [ ++ WindowState::MAXIMIZED, ++ WindowState::TILED, ++ WindowState::FULLSCREEN, ++ WindowState::MAXIMIZED | WindowState::ACTIVATED, ++ WindowState::TILED | WindowState::FULLSCREEN, ++ ] { ++ assert_eq!(content_radius(square), 0., "{square:?} squares the content"); ++ assert_eq!(border_radius(square), 0., "{square:?} squares the border"); ++ } ++} ++ ++/// The border is a one-point band along the arc the content leaves: the content's side of it is ++/// clear, the band is the border colour, and the shadow's side of it is the shadow's. ++#[test] ++fn the_border_follows_the_bottom_arcs() { ++ let (left, right, bottom, border, radius) = (43., 243., 10., 1., 10.); ++ let shape = bottom_border_shape(left, right, bottom, border, radius).expect("a border shape"); ++ let mut pixmap = Pixmap::new(288, 54).expect("a pixmap"); ++ pixmap ++ .as_mut() ++ .fill_path(&shape, &ColorTheme::light().active.border_paint(), FillRule::EvenOdd, Transform::identity(), None); ++ ++ // (46, 7) is 9.2 from the arc's centre (53, 1): inside the one-point band. ++ assert_border(&pixmap, 46, 7, 150, "the band on the arc"); ++ // (50, 5) is 5 from the centre: the content's own corner, which the band leaves clear. ++ assert_eq!(alpha(&pixmap, 50, 5), 0, "inside the arc is the content's"); ++ // The straight band runs the window's whole width, just under its bottom edge. ++ assert_border(&pixmap, 100, 10, 250, "the bottom band between the arcs"); ++ // Nothing is drawn below the band: that is the shadow's and the window's outside. ++ assert_eq!(alpha(&pixmap, 100, 12), 0, "below the band the shadow draws"); ++} ++ ++/// The shadow below the window's edge is the square frame's, pixel for pixel: round corners only ++/// add the crescents above that edge, and nothing else about the shadow moves. ++#[test] ++fn a_round_frames_shadow_below_the_window_is_the_square_frames() { ++ let round = bottom_part(200, WindowState::empty()); ++ let square = bottom_part(200, WindowState::MAXIMIZED); ++ // The window's bottom edge is a corner radius into the part; the one-point band is just below ++ // it, and the shadow below the window starts under that. ++ let below = (CORNER_RADIUS + VISIBLE_BORDER_SIZE) as u32; ++ for y in below..round.height() { ++ for x in 0..round.width() { ++ let (rounded, squared) = (alpha(&round, x, y), alpha(&square, x, y)); ++ assert!( ++ rounded.abs_diff(squared) <= 1, ++ "({x}, {y}): round corners give {rounded}, the square frame {squared}", ++ ); ++ } ++ } ++ // And the content's corner is left alone: inside the arc nothing is drawn. ++ assert_eq!(alpha(&round, 50, 5), 0, "inside the arc is the content's"); ++} ++ ++/// The last corner column and the first plain one below the window's edge carry the same shadow: the ++/// corner's crescent and the straight band meet without a step, at every depth. ++#[test] ++fn the_shadow_is_smooth_across_the_corner_and_plain_columns() { ++ let pixmap = bottom_part(200, WindowState::empty()); ++ // The corner's columns end where the straight band's begin: `left` plus the corner radius. ++ let plain = (BORDER_SIZE - VISIBLE_BORDER_SIZE + CORNER_RADIUS) as u32; ++ let corner = plain - 1; ++ for y in [11, 15, 20, 30, 40] { ++ let (corner_alpha, plain_alpha) = (alpha(&pixmap, corner, y), alpha(&pixmap, plain, y)); ++ if y <= 30 { ++ assert!(plain_alpha > 0, "({plain}, {y}) has the straight band's shadow"); ++ } ++ assert!( ++ corner_alpha.abs_diff(plain_alpha) <= 2, ++ "row {y}: the corner column has {corner_alpha}, the plain one {plain_alpha}", ++ ); ++ } ++ // The crescent above the edge, outside the arc, keeps its shadow too. ++ assert!(alpha(&pixmap, 45, 10) > 0, "the crescent outside the arc keeps its shadow"); ++ // And the mirror corner reads the same. ++ let width = pixmap.width() as u32; ++ for y in [11, 20, 40] { ++ let (corner_alpha, plain_alpha) = (alpha(&pixmap, width - 1 - corner, y), alpha(&pixmap, width - 1 - plain, y)); ++ assert!(corner_alpha.abs_diff(plain_alpha) <= 2, "row {y} on the right"); ++ } ++} ++ ++/// A square window (maximized, tiled or fullscreen) draws a straight band and no shadow over the ++/// window at all: nothing is cut out of the content's corners. ++#[test] ++fn a_square_window_keeps_its_corners() { ++ let pixmap = bottom_part(200, WindowState::MAXIMIZED); ++ assert_border(&pixmap, 46, 10, 250, "the band straight across the corner"); ++ assert_eq!(alpha(&pixmap, 45, 9), 0, "no shadow over the window's corner"); ++ assert_eq!(alpha(&pixmap, 50, 5), 0, "nothing is cut out of the content"); ++ ++ assert!(alpha(&pixmap, 45, 12) > 0, "the shadow below the window is still drawn"); ++ ++ let tiled = bottom_part(200, WindowState::TILED); ++ assert_border(&tiled, 46, 10, 250, "a tiled window's straight border"); ++} ++ ++/// The bottom part reaches a corner radius above the window's bottom edge, so its input zone — its ++/// resize handle — starts at that edge instead, and never takes input from the content. ++#[test] ++fn the_bottom_input_zone_starts_at_the_windows_edge() { ++ let surface = 200 + 2 * BORDER_SIZE; ++ let input = bottom_input_rect(surface); ++ assert_eq!(input.y, CORNER_RADIUS as i32, "the part's top is a corner radius above the edge"); ++ assert_eq!(input.height, RESIZE_HANDLE_SIZE); ++ assert_eq!(input.width, surface - BORDER_SIZE * 2 + RESIZE_HANDLE_SIZE * 2); ++ assert!(input.x >= BORDER_SIZE as i32 - RESIZE_HANDLE_SIZE as i32); ++} ++ ++/// A window narrower than two corner radii still gets a border: the arcs are rounded as far as ++/// they fit and nothing runs outside the part. ++#[test] ++fn a_narrow_window_still_gets_a_border() { ++ let (left, right, bottom, border, radius) = (43., 53., 10., 1., 10.); ++ let shape = bottom_border_shape(left, right, bottom, border, radius).expect("a border shape"); ++ let mut pixmap = Pixmap::new((right + left) as u32, 54).expect("a pixmap"); ++ pixmap ++ .as_mut() ++ .fill_path(&shape, &ColorTheme::light().active.border_paint(), FillRule::EvenOdd, Transform::identity(), None); ++ assert_border(&pixmap, (left as u32 + right as u32) / 2, 10, 250, "the narrow window's band"); ++ // Degenerate shapes draw nothing rather than panicking. ++ assert!(bottom_border_shape(43., 43., 10., 1., 10.).is_none(), "no width, no shape"); ++ assert!(bottom_border_shape(43., 53., 10., 0., 10.).is_none(), "no border, no shape"); ++ assert!(bottom_border_shape(f32::NAN, 53., 10., 1., 10.).is_none(), "not a number, no shape"); ++} ++ ++/// The side and bottom parts composited as the compositor stacks them (left and right below the ++/// bottom one), over a window `width` points wide and `height` tall, with `state`. The canvas is in ++/// window coordinates: its top left is the window's `(-BORDER_SIZE, -HEADER_SIZE)`, and every part ++/// sits at its `surface_rect`. ++fn composite(width: u32, height: u32, state: WindowState) -> Pixmap { ++ let mut canvas = Pixmap::new(width + 2 * BORDER_SIZE, height + HEADER_SIZE + BORDER_SIZE).expect("a canvas"); ++ let colors = ColorTheme::light().active; ++ let mut shadow = Default::default(); ++ let parts: [(bool, (u32, u32), (i32, i32), usize); 3] = [ ++ (false, (BORDER_SIZE, height + HEADER_SIZE), (-(BORDER_SIZE as i32), -(HEADER_SIZE as i32)), DecorationParts::LEFT), ++ (true, (BORDER_SIZE, height + HEADER_SIZE), (width as i32, -(HEADER_SIZE as i32)), DecorationParts::RIGHT), ++ (false, (width + 2 * BORDER_SIZE, BORDER_SIZE + CORNER_RADIUS), (-(BORDER_SIZE as i32), height as i32 - CORNER_RADIUS as i32), DecorationParts::BOTTOM), ++ ]; ++ for (right, size, at, part) in parts { ++ let mut pixmap = Pixmap::new(size.0, size.1).expect("a part"); ++ match part { ++ DecorationParts::BOTTOM => draw_bottom(&mut pixmap.as_mut(), &mut shadow, &colors, &state, 1, size.0), ++ _ => draw_side(&mut pixmap.as_mut(), &mut shadow, &colors, &state, 1, right), ++ } ++ let (x, y) = (at.0 - (-(BORDER_SIZE as i32)), at.1 - (-(HEADER_SIZE as i32))); ++ canvas ++ .as_mut() ++ .draw_pixmap(x, y, pixmap.as_ref(), &PixmapPaint::default(), Transform::identity(), None); ++ } ++ canvas ++} ++ ++/// A pixel's alpha in window coordinates, from a canvas `composite` drew. ++fn window_alpha(canvas: &Pixmap, (x, y): (i32, i32)) -> u8 { ++ let cx = (x + BORDER_SIZE as i32) as u32; ++ let cy = (y + HEADER_SIZE as i32) as u32; ++ alpha(canvas, cx, cy) ++} ++ ++/// Whether `(x, y)` in window coordinates is inside one of the two corner squares the bottom ++/// corners round: `x` in `[-1, r]` or `[width - r, width + 1]`, `y` in `[height - r, height]`. ++fn in_corner_square(width: u32, height: u32, (x, y): (i32, i32)) -> bool { ++ let r = CONTENT_CORNER_RADIUS as i32; ++ let (width, height) = (width as i32, height as i32); ++ y >= height - r && y <= height && (x >= -1 && x <= r || x >= width - r && x <= width + 1) ++} ++ ++/// Beside the bottom corners the composite is a square frame's: the side parts already draw the ++/// shadow down to the window's edge, and the bottom part adds nothing over it. ++#[test] ++fn the_side_and_bottom_parts_composite_like_a_square_frame() { ++ let (width, height) = (200, 120); ++ let round = composite(width, height, WindowState::empty()); ++ let square = composite(width, height, WindowState::MAXIMIZED); ++ let mut compared = 0; ++ let mut worst = (0, (0, 0), 0, 0); ++ for cy in 0..round.height() { ++ for cx in 0..round.width() { ++ let at = (cx as i32 - BORDER_SIZE as i32, cy as i32 - HEADER_SIZE as i32); ++ let (x, y) = at; ++ // Outside the content rect, and not in a corner square, where the arcs' ring and the ++ // shadow's crescents are the intended difference. ++ let outside = x < 0 || x >= width as i32 || y < 0 || y >= height as i32; ++ if !outside || in_corner_square(width, height, at) { ++ continue; ++ } ++ let (rounded, squared) = (alpha(&round, cx, cy), alpha(&square, cx, cy)); ++ let off = rounded.abs_diff(squared); ++ if off > worst.0 { ++ worst = (off, at, rounded, squared); ++ } ++ compared += 1; ++ } ++ } ++ let (off, at, rounded, squared) = worst; ++ assert!( ++ off <= 2, ++ "the worst pixel is {at:?}: round corners composite {rounded}, the square frame {squared}", ++ ); ++ assert!(compared > 10_000, "the whole frame around the content was compared ({compared})"); ++} ++ ++/// The crescent the bottom part adds inside a corner square meets its neighbours without a step: ++/// the shadow on the other side of the window's edge (the side part's own, which a square frame ++/// draws) and the straight band just below the edge carry the same shadow at those distances. The ++/// bound is the shadow's own gradient over a pixel — a hole (0 against ~29) or a doubled copy ++/// (~58) is far past it. ++#[test] ++fn the_crescent_continues_the_shadow_around_it() { ++ let (width, height) = (200, 120); ++ let canvas = composite(width, height, WindowState::empty()); ++ for corner in [(0, height as i32 - 1), (width as i32 - 1, height as i32 - 1)] { ++ let crescent = window_alpha(&canvas, corner); ++ assert!(crescent > 0, "{corner:?}: the crescent keeps its shadow"); ++ // Outward, across the window's side edge, and down, across its bottom edge. ++ let outward = if corner.0 == 0 { (-1, corner.1) } else { (width as i32, corner.1) }; ++ let below = (corner.0, height as i32); ++ for neighbour in [outward, below] { ++ let other = window_alpha(&canvas, neighbour); ++ assert!( ++ crescent.abs_diff(other) <= 8, ++ "{corner:?} has {crescent}, its neighbour {neighbour:?} {other}", ++ ); ++ } ++ } ++} ++ ++/// The straight bands' shadow is the frame's own shadow model, which no patch touched: the ++/// composite tests above compare their rounded frame against a square one drawn by the same code, ++/// and this pins that reference to the model itself. ++#[test] ++fn the_straight_bands_shadow_is_the_shadow_model() { ++ let (width, height) = (200, 120); ++ let square = composite(width, height, WindowState::MAXIMIZED); ++ for dy in [1, 3, 8, 20] { ++ let y = height as i32 + dy; ++ let want = (crate::shadow::shadow(dy as f32 - 0.5, 1, false) * 255.).round() as u8; ++ let got = window_alpha(&square, (100, y)); ++ assert!(got.abs_diff(want) <= 2, "y {y}: the band draws {got}, the model says {want}"); ++ } ++ // The rounded frame's own band, at the same depths, is the same. ++ let round = composite(width, height, WindowState::empty()); ++ for dy in [1, 3, 8, 20] { ++ let y = height as i32 + dy; ++ assert_eq!(window_alpha(&round, (100, y)), window_alpha(&square, (100, y)), "y {y}"); ++ } ++} diff --git a/app/vendor/rune/vendor/sctk-adwaita/.cargo_vcs_info.json b/app/vendor/rune/vendor/sctk-adwaita/.cargo_vcs_info.json new file mode 100644 index 0000000..3572f43 --- /dev/null +++ b/app/vendor/rune/vendor/sctk-adwaita/.cargo_vcs_info.json @@ -0,0 +1,6 @@ +{ + "git": { + "sha1": "d5f343c45c04d4a026db57f76760819b7325db00" + }, + "path_in_vcs": "" +} \ No newline at end of file diff --git a/app/vendor/rune/vendor/sctk-adwaita/.github/workflows/changelog.yml b/app/vendor/rune/vendor/sctk-adwaita/.github/workflows/changelog.yml new file mode 100644 index 0000000..5b91fd7 --- /dev/null +++ b/app/vendor/rune/vendor/sctk-adwaita/.github/workflows/changelog.yml @@ -0,0 +1,15 @@ +name: Changelog check + +on: + pull_request: + branches: [ master ] + types: [ opened, synchronize, reopened, labeled, unlabeled ] + +jobs: + Changelog-Entry-Check: + name: Check Changelog Action + runs-on: ubuntu-latest + steps: + - uses: tarides/changelog-check-action@v2 + with: + changelog: CHANGELOG.md diff --git a/app/vendor/rune/vendor/sctk-adwaita/.github/workflows/rust.yml b/app/vendor/rune/vendor/sctk-adwaita/.github/workflows/rust.yml new file mode 100644 index 0000000..55ca2be --- /dev/null +++ b/app/vendor/rune/vendor/sctk-adwaita/.github/workflows/rust.yml @@ -0,0 +1,101 @@ +on: [push, pull_request] + +name: Continuous integration + +jobs: + fmt: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + - uses: actions-rs/toolchain@v1 + with: + profile: minimal + toolchain: stable + override: true + components: rustfmt + + - uses: actions-rs/cargo@v1 + with: + command: fmt + args: --all -- --check + + clippy: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + - uses: actions-rs/toolchain@v1 + with: + profile: minimal + toolchain: stable + override: true + components: clippy + + - name: Run cargo clippy + uses: actions-rs/clippy-check@v1 + with: + token: ${{ secrets.GITHUB_TOKEN }} + args: -- -D clippy::print_stderr -D clippy::print_stdout -D clippy::dbg_macro -D clippy::exit -D clippy::unwrap_used -D clippy::expect_used -D clippy::panic + + default-build: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + - uses: actions-rs/toolchain@v1 + with: + profile: minimal + toolchain: stable + override: true + + - uses: actions-rs/cargo@v1 + with: + command: build + + no-default-build: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + - uses: actions-rs/toolchain@v1 + with: + profile: minimal + toolchain: stable + override: true + + - uses: actions-rs/cargo@v1 + with: + command: build + args: --no-default-features + + crossfont-build: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + + - name: System dependencies + run: sudo apt-get update && sudo apt-get install pkg-config cmake libfreetype6-dev libfontconfig1-dev + + - uses: actions-rs/toolchain@v1 + with: + profile: minimal + toolchain: stable + override: true + + - uses: actions-rs/cargo@v1 + with: + command: build + args: --no-default-features --features crossfont + + ab-glyph-build: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + + - uses: actions-rs/toolchain@v1 + with: + profile: minimal + toolchain: stable + override: true + + - uses: actions-rs/cargo@v1 + with: + command: build + args: --no-default-features --features ab_glyph diff --git a/app/vendor/rune/vendor/sctk-adwaita/.gitignore b/app/vendor/rune/vendor/sctk-adwaita/.gitignore new file mode 100644 index 0000000..869df07 --- /dev/null +++ b/app/vendor/rune/vendor/sctk-adwaita/.gitignore @@ -0,0 +1,2 @@ +/target +Cargo.lock \ No newline at end of file diff --git a/app/vendor/rune/vendor/sctk-adwaita/CHANGELOG.md b/app/vendor/rune/vendor/sctk-adwaita/CHANGELOG.md new file mode 100644 index 0000000..061a9bc --- /dev/null +++ b/app/vendor/rune/vendor/sctk-adwaita/CHANGELOG.md @@ -0,0 +1,67 @@ +## [Unreleased] + +## 0.10.1 +- Panic hardening of ab-glyph (#64) + +## 0.10.0 +- Bump sctk to 0.19 + +## 0.9.0 +- Bump crossfont to 0.8.0 (#60) + +## 0.8.1 +- Fix `ab_glyph` renderer panicking with integer scale factor 3 (#50) +- Improved roundness of headerbar (#51) + +## 0.8.0 +- **Breaking:** `AdwaitaFrame::new` now takes `Arc<CompositorState>` as an argument +- Fix leftmost title pixel sometimes being cut off (#45) +- Fix transparency in ab_glyph renderer (#44) +- Extended resize corners (#47) +- Center maximize icon (#46) +- Window shadows (#43) + +### Dependencies updates +- Bump crossfont to 0.6.0 (#52) + +## 0.7.0 +- **Breaking:** `wayland-csd-frame` is now used as a part of the public interface. + +## 0.6.1 +- Bump tiny-skia to v0.11 (#32) +- cleanup: Remove debug println (#29) +- Support custom header buttons layouts (#30) +- The double click threshold value was raised to `400ms` + +## 0.6.0 +- Update the `smithay-client-toolkit` to `0.17.0` +- Don't use tiny-skia's default features + +## 0.5.4 +- Timeout dbus call to settings portal (100ms) + +## 0.5.3 +- `ab_glyph` titles will read the system title font using memory mapped buffers instead of reading to heap. + Lowers RAM usage. +- Improve titlebar-font config parsing to correctly handle more font names. + +## 0.5.2 +- `ab_glyph` & `crossfont` titles will use gnome "titlebar-font" config if available. +- `ab_glyph` titles are now more consistent with `crossfont` titles both using system sans + if no better font config is available. +- Rounded corners are now disabled on maximized and tiled windows. +- Double click interval is now 400ms (as previous 1s interval was caused by bug fixed in 0.5.1) + +## 0.5.1 +- Use dbus org.freedesktop.portal.Settings to automatically choose light or dark theming. +- Double click detection fix. +- Apply button click on release instead of press. + +## 0.5.0 +- `title` feature got removed +- `ab_glyph` default feature got added (for `ab_glyph` based title rendering) +- `crossfont` feature got added (for `crossfont` based title rendering) + - Can be enable like this: + ```toml + sctk-adwaita = { default-features = false, features = ["crossfont"] } + ``` diff --git a/app/vendor/rune/vendor/sctk-adwaita/Cargo.toml b/app/vendor/rune/vendor/sctk-adwaita/Cargo.toml new file mode 100644 index 0000000..fe8e00e --- /dev/null +++ b/app/vendor/rune/vendor/sctk-adwaita/Cargo.toml @@ -0,0 +1,57 @@ +# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO +# +# When uploading crates to the registry Cargo will automatically +# "normalize" Cargo.toml files for maximal compatibility +# with all versions of Cargo and also rewrite `path` dependencies +# to registry (e.g., crates.io) dependencies. +# +# If you are reading this file be aware that the original Cargo.toml +# will likely look very different (and much more reasonable). +# See Cargo.toml.orig for the original contents. + +[package] +edition = "2021" +name = "sctk-adwaita" +version = "0.10.1" +authors = ["Poly <marynczak.bartlomiej@gmail.com>"] +description = "Adwaita-like SCTK Frame" +documentation = "https://docs.rs/sctk-adwaita" +readme = "README.md" +keywords = ["sctk"] +license = "MIT" +repository = "https://github.com/PolyMeilex/sctk-adwaita" + +[dependencies.ab_glyph] +version = "0.2.17" +optional = true + +[dependencies.crossfont] +version = "0.8.0" +optional = true + +[dependencies.log] +version = "0.4" + +[dependencies.memmap2] +version = "0.9.0" +optional = true + +[dependencies.smithay-client-toolkit] +version = "0.19.0" +default_features = false + +[dependencies.tiny-skia] +version = "0.11" +features = [ + "std", + "simd", +] +default-features = false + +[features] +ab_glyph = [ + "dep:ab_glyph", + "memmap2", +] +crossfont = ["dep:crossfont"] +default = ["ab_glyph"] diff --git a/app/vendor/rune/vendor/sctk-adwaita/Cargo.toml.orig b/app/vendor/rune/vendor/sctk-adwaita/Cargo.toml.orig new file mode 100644 index 0000000..7ce5efe --- /dev/null +++ b/app/vendor/rune/vendor/sctk-adwaita/Cargo.toml.orig @@ -0,0 +1,29 @@ +[package] +name = "sctk-adwaita" +version = "0.10.1" +edition = "2021" +authors = ["Poly <marynczak.bartlomiej@gmail.com>"] +keywords = ["sctk"] +license = "MIT" +repository = "https://github.com/PolyMeilex/sctk-adwaita" +documentation = "https://docs.rs/sctk-adwaita" +description = "Adwaita-like SCTK Frame" + +[dependencies] +log = "0.4" +memmap2 = { version = "0.9.0", optional = true } +tiny-skia = { version = "0.11", default-features = false, features = [ + "std", + "simd", +] } +smithay-client-toolkit = { version = "0.19.0", default_features = false } + +# Draw title text using crossfont `--features crossfont` +crossfont = { version = "0.8.0", optional = true } +# Draw title text using ab_glyph `--features ab_glyph` +ab_glyph = { version = "0.2.17", optional = true } + +[features] +default = ["ab_glyph"] +crossfont = ["dep:crossfont"] +ab_glyph = ["dep:ab_glyph", "memmap2"] diff --git a/app/vendor/rune/vendor/sctk-adwaita/LICENSE b/app/vendor/rune/vendor/sctk-adwaita/LICENSE new file mode 100644 index 0000000..cef2bab --- /dev/null +++ b/app/vendor/rune/vendor/sctk-adwaita/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2022 Bartłomiej Maryńczak + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/app/vendor/rune/vendor/sctk-adwaita/README.md b/app/vendor/rune/vendor/sctk-adwaita/README.md new file mode 100644 index 0000000..ea4f8aa --- /dev/null +++ b/app/vendor/rune/vendor/sctk-adwaita/README.md @@ -0,0 +1,19 @@ +# Adwaita-like SCTK Frame + +| | | +|---|---| +|![active](https://i.imgur.com/WdO8e0i.png)|![hover](https://i.imgur.com/TkUq2WF.png)| +![inactive](https://i.imgur.com/MTFdSjK.png)| + +### Dark mode: +![image](https://user-images.githubusercontent.com/20758186/169424673-3b9fa022-f112-4928-8360-305a714ba979.png) + +## Title text: ab_glyph +By default title text is drawn with _ab_glyph_ crate. This can be disabled by disabling default features. + +## Title text: crossfont +Alternatively title text may be drawn with _crossfont_ crate. This adds a requirement on _freetype_. + +```toml +sctk-adwaita = { default-features = false, features = ["crossfont"] } +``` diff --git a/app/vendor/rune/vendor/sctk-adwaita/examples/window.rs b/app/vendor/rune/vendor/sctk-adwaita/examples/window.rs new file mode 100644 index 0000000..3f66f07 --- /dev/null +++ b/app/vendor/rune/vendor/sctk-adwaita/examples/window.rs @@ -0,0 +1,620 @@ +// Based on https://github.com/Smithay/client-toolkit/blob/master/examples/themed_window.rs. + +use std::sync::Arc; +use std::time::Duration; +use std::{convert::TryInto, num::NonZeroU32}; + +use smithay_client_toolkit::reexports::client::{ + globals::registry_queue_init, + protocol::{wl_output, wl_pointer, wl_seat, wl_shm, wl_surface}, + Connection, Proxy, QueueHandle, +}; +use smithay_client_toolkit::reexports::csd_frame::{ + CursorIcon, DecorationsFrame, FrameAction, FrameClick, ResizeEdge, +}; +use smithay_client_toolkit::reexports::protocols::xdg::shell::client::xdg_toplevel::ResizeEdge as XdgResizeEdge; +use smithay_client_toolkit::{ + compositor::{CompositorHandler, CompositorState}, + delegate_compositor, delegate_output, delegate_pointer, delegate_registry, delegate_seat, + delegate_shm, delegate_subcompositor, delegate_xdg_shell, delegate_xdg_window, + output::{OutputHandler, OutputState}, + registry::{ProvidesRegistryState, RegistryState}, + registry_handlers, + seat::{ + pointer::{ + PointerData, PointerEvent, PointerEventKind, PointerHandler, ThemeSpec, ThemedPointer, + }, + Capability, SeatHandler, SeatState, + }, + shell::{ + xdg::{ + window::{DecorationMode, Window, WindowConfigure, WindowDecorations, WindowHandler}, + XdgShell, XdgSurface, + }, + WaylandSurface, + }, + shm::{ + slot::{Buffer, SlotPool}, + Shm, ShmHandler, + }, + subcompositor::SubcompositorState, +}; + +use sctk_adwaita::{AdwaitaFrame, FrameConfig}; + +fn main() { + let conn = Connection::connect_to_env().unwrap(); + + let (globals, mut event_queue) = registry_queue_init(&conn).unwrap(); + let qh = event_queue.handle(); + let registry_state = RegistryState::new(&globals); + let seat_state = SeatState::new(&globals, &qh); + let output_state = OutputState::new(&globals, &qh); + let compositor_state = + CompositorState::bind(&globals, &qh).expect("wl_compositor not available"); + let subcompositor_state = + SubcompositorState::bind(compositor_state.wl_compositor().clone(), &globals, &qh) + .expect("wl_subcompositor not available"); + let shm_state = Shm::bind(&globals, &qh).expect("wl_shm not available"); + let xdg_shell_state = XdgShell::bind(&globals, &qh).expect("xdg shell not available"); + + let width = 256; + let height = 256; + let pool = SlotPool::new(width as usize * height as usize * 4, &shm_state) + .expect("Failed to create pool"); + + let window_surface = compositor_state.create_surface(&qh); + + let window = + xdg_shell_state.create_window(window_surface, WindowDecorations::ServerDefault, &qh); + window.set_title("A wayland window"); + // GitHub does not let projects use the `org.github` domain but the `io.github` domain is fine. + window.set_app_id("simple-window"); + window.set_min_size(Some((2, 1))); + + // In order for the window to be mapped, we need to perform an initial commit with no attached buffer. + // For more info, see WaylandSurface::commit + // + // The compositor will respond with an initial configure that we can then use to present to the window with + // the correct options. + window.commit(); + + let mut simple_window = SimpleWindow { + title: String::from("/usr/lib/xorg/modules/input"), + registry_state, + seat_state, + output_state, + compositor_state: Arc::new(compositor_state), + subcompositor_state: Arc::new(subcompositor_state), + shm_state, + _xdg_shell_state: xdg_shell_state, + + exit: false, + first_configure: true, + pool, + width: NonZeroU32::new(width).unwrap(), + height: NonZeroU32::new(height).unwrap(), + shift: None, + buffer: None, + window, + window_frame: None, + themed_pointer: None, + set_cursor: false, + cursor_icon: CursorIcon::Crosshair, + }; + + // We don't draw immediately, the configure will notify us when to first draw. + + loop { + event_queue.blocking_dispatch(&mut simple_window).unwrap(); + + if simple_window.exit { + println!("exiting example"); + break; + } + } +} + +struct SimpleWindow { + title: String, + registry_state: RegistryState, + seat_state: SeatState, + output_state: OutputState, + compositor_state: Arc<CompositorState>, + subcompositor_state: Arc<SubcompositorState>, + shm_state: Shm, + _xdg_shell_state: XdgShell, + + exit: bool, + first_configure: bool, + pool: SlotPool, + width: NonZeroU32, + height: NonZeroU32, + shift: Option<u32>, + buffer: Option<Buffer>, + window: Window, + window_frame: Option<AdwaitaFrame<Self>>, + themed_pointer: Option<ThemedPointer>, + set_cursor: bool, + cursor_icon: CursorIcon, +} + +impl CompositorHandler for SimpleWindow { + fn scale_factor_changed( + &mut self, + _conn: &Connection, + _qh: &QueueHandle<Self>, + surface: &wl_surface::WlSurface, + new_factor: i32, + ) { + if self.window.wl_surface() == surface { + if let Some(frame) = self.window_frame.as_mut() { + frame.set_scaling_factor(new_factor as f64); + } + } + } + + fn transform_changed( + &mut self, + _: &Connection, + _: &QueueHandle<Self>, + _: &wl_surface::WlSurface, + _: wl_output::Transform, + ) { + // Not needed for this example. + } + + fn frame( + &mut self, + conn: &Connection, + qh: &QueueHandle<Self>, + _surface: &wl_surface::WlSurface, + _time: u32, + ) { + self.draw(conn, qh); + } + + fn surface_enter( + &mut self, + _conn: &Connection, + _qh: &QueueHandle<Self>, + _surface: &wl_surface::WlSurface, + _output: &wl_output::WlOutput, + ) { + } + + fn surface_leave( + &mut self, + _conn: &Connection, + _qh: &QueueHandle<Self>, + _surface: &wl_surface::WlSurface, + _output: &wl_output::WlOutput, + ) { + } +} + +impl OutputHandler for SimpleWindow { + fn output_state(&mut self) -> &mut OutputState { + &mut self.output_state + } + + fn new_output( + &mut self, + _conn: &Connection, + _qh: &QueueHandle<Self>, + _output: wl_output::WlOutput, + ) { + } + + fn update_output( + &mut self, + _conn: &Connection, + _qh: &QueueHandle<Self>, + _output: wl_output::WlOutput, + ) { + } + + fn output_destroyed( + &mut self, + _conn: &Connection, + _qh: &QueueHandle<Self>, + _output: wl_output::WlOutput, + ) { + } +} + +impl WindowHandler for SimpleWindow { + fn request_close(&mut self, _: &Connection, _: &QueueHandle<Self>, _: &Window) { + self.exit = true; + } + + fn configure( + &mut self, + conn: &Connection, + qh: &QueueHandle<Self>, + window: &Window, + configure: WindowConfigure, + _serial: u32, + ) { + self.buffer = None; + + println!( + "Configure size {:?}, decorations: {:?}", + configure.new_size, configure.decoration_mode + ); + + let (width, height) = if configure.decoration_mode == DecorationMode::Client { + let window_frame = self.window_frame.get_or_insert_with(|| { + let mut frame = AdwaitaFrame::new( + &self.window, + &self.shm_state, + self.compositor_state.clone(), + self.subcompositor_state.clone(), + qh.clone(), + FrameConfig::auto(), + ) + .expect("failed to create client side decorations frame."); + frame.set_title(self.title.clone()); + frame + }); + + // Un-hide the frame. + window_frame.set_hidden(false); + + // Configure state before touching any resizing. + window_frame.update_state(configure.state); + + // Configure the button state. + window_frame.update_wm_capabilities(configure.capabilities); + + let (width, height) = match configure.new_size { + (Some(width), Some(height)) => { + // The size could be 0. + window_frame.subtract_borders(width, height) + } + _ => { + // You might want to consider checking for configure bounds. + (Some(self.width), Some(self.height)) + } + }; + + // Clamp the size to at least one pixel. + let width = width.unwrap_or(NonZeroU32::new(1).unwrap()); + let height = height.unwrap_or(NonZeroU32::new(1).unwrap()); + + window_frame.resize(width, height); + + let (x, y) = window_frame.location(); + let outer_size = window_frame.add_borders(width.get(), height.get()); + window.xdg_surface().set_window_geometry( + x, + y, + outer_size.0 as i32, + outer_size.1 as i32, + ); + + (width, height) + } else { + // Hide the frame, if any. + if let Some(frame) = self.window_frame.as_mut() { + frame.set_hidden(true) + } + let width = configure.new_size.0.unwrap_or(self.width); + let height = configure.new_size.1.unwrap_or(self.height); + self.window.xdg_surface().set_window_geometry( + 0, + 0, + width.get() as i32, + height.get() as i32, + ); + (width, height) + }; + + // Update new width and height; + self.width = width; + self.height = height; + + // Initiate the first draw. + if self.first_configure { + self.first_configure = false; + self.draw(conn, qh); + } + } +} + +impl SeatHandler for SimpleWindow { + fn seat_state(&mut self) -> &mut SeatState { + &mut self.seat_state + } + + fn new_seat(&mut self, _: &Connection, _: &QueueHandle<Self>, _: wl_seat::WlSeat) {} + + fn new_capability( + &mut self, + _conn: &Connection, + qh: &QueueHandle<Self>, + seat: wl_seat::WlSeat, + capability: Capability, + ) { + if capability == Capability::Pointer && self.themed_pointer.is_none() { + println!("Set pointer capability"); + println!("Creating pointer theme"); + let surface = self.compositor_state.create_surface(qh); + let themed_pointer = self + .seat_state + .get_pointer_with_theme( + qh, + &seat, + self.shm_state.wl_shm(), + surface, + ThemeSpec::default(), + ) + .expect("Failed to create pointer"); + self.themed_pointer.replace(themed_pointer); + } + } + + fn remove_capability( + &mut self, + _conn: &Connection, + _: &QueueHandle<Self>, + _: wl_seat::WlSeat, + capability: Capability, + ) { + if capability == Capability::Pointer && self.themed_pointer.is_some() { + println!("Unset pointer capability"); + self.themed_pointer.take().unwrap().pointer().release(); + } + } + + fn remove_seat(&mut self, _: &Connection, _: &QueueHandle<Self>, _: wl_seat::WlSeat) {} +} + +impl PointerHandler for SimpleWindow { + fn pointer_frame( + &mut self, + _conn: &Connection, + _qh: &QueueHandle<Self>, + pointer: &wl_pointer::WlPointer, + events: &[PointerEvent], + ) { + use PointerEventKind::*; + for event in events { + let (x, y) = event.position; + match event.kind { + Enter { .. } => { + self.set_cursor = true; + self.cursor_icon = self + .window_frame + .as_mut() + .and_then(|frame| { + frame.click_point_moved(Duration::ZERO, &event.surface.id(), x, y) + }) + .unwrap_or(CursorIcon::Crosshair) + .to_owned(); + + if &event.surface == self.window.wl_surface() { + println!("Pointer entered @{:?}", event.position); + } + } + Leave { .. } => { + if &event.surface != self.window.wl_surface() { + if let Some(window_frame) = self.window_frame.as_mut() { + window_frame.click_point_left(); + } + } + println!("Pointer left"); + } + Motion { time } => { + if let Some(new_cursor) = self.window_frame.as_mut().and_then(|frame| { + frame.click_point_moved( + Duration::from_millis(time as u64), + &event.surface.id(), + x, + y, + ) + }) { + self.set_cursor = true; + self.cursor_icon = new_cursor.to_owned(); + } + } + Press { + button, + serial, + time, + } + | Release { + button, + serial, + time, + } => { + let pressed = if matches!(event.kind, Press { .. }) { + true + } else { + false + }; + if &event.surface != self.window.wl_surface() { + let click = match button { + 0x110 => FrameClick::Normal, + 0x111 => FrameClick::Alternate, + _ => continue, + }; + + if let Some(action) = self.window_frame.as_mut().and_then(|frame| { + frame.on_click(Duration::from_millis(time as u64), click, pressed) + }) { + self.frame_action(pointer, serial, action); + } + } else if pressed { + println!("Press {:x} @ {:?}", button, event.position); + self.shift = self.shift.xor(Some(0)); + } + } + Axis { + horizontal, + vertical, + .. + } => { + if &event.surface == self.window.wl_surface() { + println!("Scroll H:{horizontal:?}, V:{vertical:?}"); + } + } + } + } + } +} +impl SimpleWindow { + fn frame_action(&mut self, pointer: &wl_pointer::WlPointer, serial: u32, action: FrameAction) { + let pointer_data = pointer.data::<PointerData>().unwrap(); + let seat = pointer_data.seat(); + match action { + FrameAction::Close => self.exit = true, + FrameAction::Minimize => self.window.set_minimized(), + FrameAction::Maximize => self.window.set_maximized(), + FrameAction::UnMaximize => self.window.unset_maximized(), + FrameAction::ShowMenu(x, y) => self.window.show_window_menu(seat, serial, (x, y)), + FrameAction::Resize(edge) => { + let edge = match edge { + ResizeEdge::None => XdgResizeEdge::None, + ResizeEdge::Top => XdgResizeEdge::Top, + ResizeEdge::Bottom => XdgResizeEdge::Bottom, + ResizeEdge::Left => XdgResizeEdge::Left, + ResizeEdge::TopLeft => XdgResizeEdge::TopLeft, + ResizeEdge::BottomLeft => XdgResizeEdge::BottomLeft, + ResizeEdge::Right => XdgResizeEdge::Right, + ResizeEdge::TopRight => XdgResizeEdge::TopRight, + ResizeEdge::BottomRight => XdgResizeEdge::BottomRight, + _ => return, + }; + self.window.resize(seat, serial, edge); + } + FrameAction::Move => self.window.move_(seat, serial), + _ => (), + } + } +} + +impl ShmHandler for SimpleWindow { + fn shm_state(&mut self) -> &mut Shm { + &mut self.shm_state + } +} + +impl SimpleWindow { + pub fn draw(&mut self, conn: &Connection, qh: &QueueHandle<Self>) { + if self.set_cursor { + let _ = self + .themed_pointer + .as_mut() + .unwrap() + .set_cursor(conn, self.cursor_icon); + self.set_cursor = false; + } + + let width = self.width.get(); + let height = self.height.get(); + let stride = width as i32 * 4; + + let buffer = self.buffer.get_or_insert_with(|| { + self.pool + .create_buffer( + width as i32, + height as i32, + stride, + wl_shm::Format::Argb8888, + ) + .expect("create buffer") + .0 + }); + + let canvas = match self.pool.canvas(buffer) { + Some(canvas) => canvas, + None => { + // This should be rare, but if the compositor has not released the previous + // buffer, we need double-buffering. + let (second_buffer, canvas) = self + .pool + .create_buffer( + width as i32, + height as i32, + stride, + wl_shm::Format::Argb8888, + ) + .expect("create buffer"); + *buffer = second_buffer; + canvas + } + }; + + // Draw to the window: + { + let shift = self.shift.unwrap_or(0); + canvas + .chunks_exact_mut(4) + .enumerate() + .for_each(|(index, chunk)| { + let x = ((index + shift as usize) % width as usize) as u32; + let y = (index / width as usize) as u32; + + let a = 0xFF; + let r = u32::min(((width - x) * 0xFF) / width, ((height - y) * 0xFF) / height); + let g = u32::min((x * 0xFF) / width, ((height - y) * 0xFF) / height); + let b = u32::min(((width - x) * 0xFF) / width, (y * 0xFF) / height); + let color = (a << 24) + (r << 16) + (g << 8) + b; + + let array: &mut [u8; 4] = chunk.try_into().unwrap(); + *array = color.to_le_bytes(); + }); + + if let Some(shift) = &mut self.shift { + *shift = (*shift + 1) % width; + } + } + + // Draw the decorations frame. + self.window_frame.as_mut().map(|frame| { + if frame.is_dirty() && !frame.is_hidden() { + frame.draw(); + } + }); + + // Damage the entire window + self.window.wl_surface().damage_buffer( + 0, + 0, + self.width.get() as i32, + self.height.get() as i32, + ); + + // Request our next frame + self.window + .wl_surface() + .frame(qh, self.window.wl_surface().clone()); + + // Attach and commit to present. + buffer + .attach_to(self.window.wl_surface()) + .expect("buffer attach"); + self.window.wl_surface().commit(); + } +} + +delegate_compositor!(SimpleWindow); +delegate_subcompositor!(SimpleWindow); +delegate_output!(SimpleWindow); +delegate_shm!(SimpleWindow); + +delegate_seat!(SimpleWindow); +delegate_pointer!(SimpleWindow); + +delegate_xdg_shell!(SimpleWindow); +delegate_xdg_window!(SimpleWindow); + +delegate_registry!(SimpleWindow); + +impl ProvidesRegistryState for SimpleWindow { + fn registry(&mut self) -> &mut RegistryState { + &mut self.registry_state + } + registry_handlers![OutputState, SeatState,]; +} diff --git a/app/vendor/rune/vendor/sctk-adwaita/src/buttons.rs b/app/vendor/rune/vendor/sctk-adwaita/src/buttons.rs new file mode 100644 index 0000000..ee62f48 --- /dev/null +++ b/app/vendor/rune/vendor/sctk-adwaita/src/buttons.rs @@ -0,0 +1,382 @@ +use log::{debug, warn}; +use smithay_client_toolkit::reexports::csd_frame::{WindowManagerCapabilities, WindowState}; +use tiny_skia::{FillRule, PathBuilder, PixmapMut, Rect, Stroke, Transform}; + +use crate::{theme::ColorMap, Location, SkiaResult}; + +/// The size of the button on the header bar in logical points. +const BUTTON_SIZE: f32 = 24.; +const BUTTON_MARGIN: f32 = 5.; +const BUTTON_SPACING: f32 = 13.; + +#[derive(Debug)] +pub(crate) struct Buttons { + // Sorted by order vec of buttons for the left and right sides + buttons_left: Vec<Button>, + buttons_right: Vec<Button>, + layout_config: Option<(String, String)>, +} + +type ButtonLayout = (Vec<Button>, Vec<Button>); + +impl Default for Buttons { + fn default() -> Self { + let (buttons_left, buttons_right) = Buttons::get_default_buttons_layout(); + + Self { + buttons_left, + buttons_right, + layout_config: None, + } + } +} + +impl Buttons { + pub fn new(layout_config: Option<(String, String)>) -> Self { + match Buttons::parse_button_layout(layout_config.clone()) { + Some((buttons_left, buttons_right)) => Self { + buttons_left, + buttons_right, + layout_config, + }, + _ => Self::default(), + } + } + + /// Rearrange the buttons with the new width. + pub fn arrange(&mut self, width: u32, margin_h: f32) { + let mut left_x = BUTTON_MARGIN + margin_h; + let mut right_x = width as f32 - BUTTON_MARGIN; + + for button in &mut self.buttons_left { + button.offset = left_x; + + // Add the button size plus spacing + left_x += BUTTON_SIZE + BUTTON_SPACING; + } + + for button in &mut self.buttons_right { + // Subtract the button size. + right_x -= BUTTON_SIZE; + + // Update it + button.offset = right_x; + + // Subtract spacing for the next button. + right_x -= BUTTON_SPACING; + } + } + + /// Find the coordinate of the button. + pub fn find_button(&self, x: f64, y: f64) -> Location { + let x = x as f32; + let y = y as f32; + let buttons = self.buttons_left.iter().chain(self.buttons_right.iter()); + + for button in buttons { + if button.contains(x, y) { + return Location::Button(button.kind); + } + } + + Location::Head + } + + pub fn update_wm_capabilities(&mut self, wm_capabilites: WindowManagerCapabilities) { + let supports_maximize = wm_capabilites.contains(WindowManagerCapabilities::MAXIMIZE); + let supports_minimize = wm_capabilites.contains(WindowManagerCapabilities::MINIMIZE); + + self.update_buttons(supports_maximize, supports_minimize); + } + + pub fn update_buttons(&mut self, supports_maximize: bool, supports_minimize: bool) { + let is_supported = |button: &Button| match button.kind { + ButtonKind::Close => true, + ButtonKind::Maximize => supports_maximize, + ButtonKind::Minimize => supports_minimize, + }; + + let (buttons_left, buttons_right) = + Buttons::parse_button_layout(self.layout_config.clone()) + .unwrap_or_else(Buttons::get_default_buttons_layout); + + self.buttons_left = buttons_left.into_iter().filter(is_supported).collect(); + self.buttons_right = buttons_right.into_iter().filter(is_supported).collect(); + } + + pub fn right_buttons_start_x(&self) -> Option<f32> { + self.buttons_right.last().map(|button| button.x()) + } + + pub fn left_buttons_end_x(&self) -> Option<f32> { + self.buttons_left.last().map(|button| button.end_x()) + } + + #[allow(clippy::too_many_arguments)] + pub fn draw( + &self, + start_x: f32, + end_x: f32, + scale: f32, + colors: &ColorMap, + mouse_location: Location, + pixmap: &mut PixmapMut, + resizable: bool, + state: &WindowState, + ) { + let left_buttons_right_limit = + self.right_buttons_start_x().unwrap_or(end_x).min(end_x) - BUTTON_SPACING; + let buttons_left = self.buttons_left.iter().map(|x| (x, Side::Left)); + let buttons_right = self.buttons_right.iter().map(|x| (x, Side::Right)); + + for (button, side) in buttons_left.chain(buttons_right) { + let is_visible = button.x() > start_x && button.end_x() < end_x + // If we have buttons from both sides and they overlap, prefer the right side + && (side == Side::Right || button.end_x() < left_buttons_right_limit); + + if is_visible { + button.draw(scale, colors, mouse_location, pixmap, resizable, state); + } + } + } + + fn parse_button_layout(sides: Option<(String, String)>) -> Option<ButtonLayout> { + let Some((left_side, right_side)) = sides else { + return None; + }; + + let buttons_left = Buttons::parse_button_layout_side(left_side, Side::Left); + let buttons_right = Buttons::parse_button_layout_side(right_side, Side::Right); + + if buttons_left.is_empty() && buttons_right.is_empty() { + warn!("No valid buttons found in configuration"); + return None; + } + + Some((buttons_left, buttons_right)) + } + + fn parse_button_layout_side(config: String, side: Side) -> Vec<Button> { + let mut buttons: Vec<Button> = vec![]; + + for button in config.split(',').take(3) { + let button_kind = match button { + "close" => ButtonKind::Close, + "maximize" => ButtonKind::Maximize, + "minimize" => ButtonKind::Minimize, + "appmenu" => { + debug!("Ignoring \"appmenu\" button"); + continue; + } + _ => { + warn!("Ignoring unknown button type: {button}"); + continue; + } + }; + + buttons.push(Button::new(button_kind)); + } + + // For the right side, we need to revert the order + if side == Side::Right { + buttons.into_iter().rev().collect() + } else { + buttons + } + } + + fn get_default_buttons_layout() -> ButtonLayout { + ( + vec![], + vec![ + Button::new(ButtonKind::Close), + Button::new(ButtonKind::Maximize), + Button::new(ButtonKind::Minimize), + ], + ) + } +} + +#[derive(Debug, Clone)] +pub(crate) struct Button { + /// The button offset into the header bar canvas. + offset: f32, + /// The kind of the button. + kind: ButtonKind, +} + +impl Button { + pub fn new(kind: ButtonKind) -> Self { + Self { offset: 0., kind } + } + + pub fn radius(&self) -> f32 { + BUTTON_SIZE / 2.0 + } + + pub fn x(&self) -> f32 { + self.offset + } + + pub fn center_x(&self) -> f32 { + self.offset + self.radius() + } + + pub fn center_y(&self) -> f32 { + BUTTON_MARGIN + self.radius() + } + + pub fn end_x(&self) -> f32 { + self.offset + BUTTON_SIZE + } + + fn contains(&self, x: f32, y: f32) -> bool { + x > self.offset + && x < self.offset + BUTTON_SIZE + && y > BUTTON_MARGIN + && y < BUTTON_MARGIN + BUTTON_SIZE + } + + pub fn draw( + &self, + scale: f32, + colors: &ColorMap, + mouse_location: Location, + pixmap: &mut PixmapMut, + resizable: bool, + state: &WindowState, + ) -> SkiaResult { + let button_bg = if mouse_location == Location::Button(self.kind) + && (resizable || self.kind != ButtonKind::Maximize) + { + colors.button_hover_paint() + } else { + colors.button_idle_paint() + }; + + // Convert to pixels. + let x = self.center_x() * scale; + let y = self.center_y() * scale; + let radius = self.radius() * scale; + + // Draw the button background. + let circle = PathBuilder::from_circle(x, y, radius)?; + pixmap.fill_path( + &circle, + &button_bg, + FillRule::Winding, + Transform::identity(), + None, + ); + + let mut button_icon_paint = colors.button_icon_paint(); + // Do AA only for diagonal lines. + button_icon_paint.anti_alias = self.kind == ButtonKind::Close; + + // Draw the icon. + match self.kind { + ButtonKind::Close => { + let x_icon = { + let size = 3.5 * scale; + let mut pb = PathBuilder::new(); + + { + let sx = x - size; + let sy = y - size; + let ex = x + size; + let ey = y + size; + + pb.move_to(sx, sy); + pb.line_to(ex, ey); + pb.close(); + } + + { + let sx = x - size; + let sy = y + size; + let ex = x + size; + let ey = y - size; + + pb.move_to(sx, sy); + pb.line_to(ex, ey); + pb.close(); + } + + pb.finish()? + }; + + pixmap.stroke_path( + &x_icon, + &button_icon_paint, + &Stroke { + width: 1.1 * scale, + ..Default::default() + }, + Transform::identity(), + None, + ); + } + ButtonKind::Maximize => { + let path2 = { + let size = 8.0 * scale; + let hsize = size / 2.0; + let mut pb = PathBuilder::new(); + + let x = x - hsize; + let y = y - hsize; + if state.contains(WindowState::MAXIMIZED) { + let offset = 2.0 * scale; + if let Some(rect) = + Rect::from_xywh(x, y + offset, size - offset, size - offset) + { + pb.push_rect(rect); + pb.move_to(rect.left() + offset, rect.top() - offset); + pb.line_to(rect.right() + offset, rect.top() - offset); + pb.line_to(rect.right() + offset, rect.bottom() - offset + 0.5); + } + } else if let Some(rect) = Rect::from_xywh(x, y, size, size) { + pb.push_rect(rect); + } + + pb.finish()? + }; + + pixmap.stroke_path( + &path2, + &button_icon_paint, + &Stroke { + width: 1.0 * scale, + ..Default::default() + }, + Transform::identity(), + None, + ); + } + ButtonKind::Minimize => { + let len = 8.0 * scale; + let hlen = len / 2.0; + pixmap.fill_rect( + Rect::from_xywh(x - hlen, y + hlen, len, scale)?, + &button_icon_paint, + Transform::identity(), + None, + ); + } + } + + Some(()) + } +} + +#[derive(Debug, Copy, Clone, PartialEq, Eq)] +pub enum ButtonKind { + Close, + Maximize, + Minimize, +} + +#[derive(Debug, Copy, Clone, PartialEq, Eq)] +pub enum Side { + Left, + Right, +} diff --git a/app/vendor/rune/vendor/sctk-adwaita/src/config.rs b/app/vendor/rune/vendor/sctk-adwaita/src/config.rs new file mode 100644 index 0000000..3299790 --- /dev/null +++ b/app/vendor/rune/vendor/sctk-adwaita/src/config.rs @@ -0,0 +1,56 @@ +//! System configuration. +use std::process::Command; + +/// Query system to see if dark theming should be preferred. +pub(crate) fn prefer_dark() -> bool { + // outputs something like: `variant variant uint32 1` + let stdout = Command::new("dbus-send") + .arg("--reply-timeout=100") + .arg("--print-reply=literal") + .arg("--dest=org.freedesktop.portal.Desktop") + .arg("/org/freedesktop/portal/desktop") + .arg("org.freedesktop.portal.Settings.Read") + .arg("string:org.freedesktop.appearance") + .arg("string:color-scheme") + .output() + .ok() + .and_then(|out| String::from_utf8(out.stdout).ok()); + + if matches!(stdout, Some(ref s) if s.is_empty()) { + log::error!("XDG Settings Portal did not return response in time: timeout: 100ms, key: color-scheme"); + } + + matches!(stdout, Some(s) if s.trim().ends_with("uint32 1")) +} + +/// Query system configuration for buttons layout. +/// Should be updated to use standard xdg-desktop-portal specs once available +/// https://github.com/flatpak/xdg-desktop-portal/pull/996 +pub(crate) fn get_button_layout_config() -> Option<(String, String)> { + let config_string = Command::new("dbus-send") + .arg("--reply-timeout=100") + .arg("--print-reply=literal") + .arg("--dest=org.freedesktop.portal.Desktop") + .arg("/org/freedesktop/portal/desktop") + .arg("org.freedesktop.portal.Settings.Read") + .arg("string:org.gnome.desktop.wm.preferences") + .arg("string:button-layout") + .output() + .ok() + .and_then(|out| String::from_utf8(out.stdout).ok())?; + + let sides_split: Vec<_> = config_string + // Taking last word + .rsplit(' ') + .next()? + // Split by left/right side + .split(':') + // Only two sides + .take(2) + .collect(); + + match sides_split.as_slice() { + [left, right] => Some((left.to_string(), right.to_string())), + _ => None, + } +} diff --git a/app/vendor/rune/vendor/sctk-adwaita/src/lib.rs b/app/vendor/rune/vendor/sctk-adwaita/src/lib.rs new file mode 100644 index 0000000..c39ed71 --- /dev/null +++ b/app/vendor/rune/vendor/sctk-adwaita/src/lib.rs @@ -0,0 +1,977 @@ +use std::error::Error; +use std::mem; +use std::num::NonZeroU32; +use std::sync::Arc; +use std::time::Duration; + +use tiny_skia::{ + BlendMode, Color, FillRule, Mask, Paint, Path, PathBuilder, Pixmap, PixmapMut, PixmapPaint, + Point, Rect, Shader, Transform, +}; + +use smithay_client_toolkit::reexports::client::backend::ObjectId; +use smithay_client_toolkit::reexports::client::protocol::wl_shm; +use smithay_client_toolkit::reexports::client::protocol::wl_subsurface::WlSubsurface; +use smithay_client_toolkit::reexports::client::protocol::wl_surface::WlSurface; +use smithay_client_toolkit::reexports::client::{Dispatch, Proxy, QueueHandle}; +use smithay_client_toolkit::reexports::csd_frame::{ + CursorIcon, DecorationsFrame, FrameAction, FrameClick, WindowManagerCapabilities, WindowState, +}; + +use smithay_client_toolkit::compositor::{CompositorState, Region, SurfaceData}; +use smithay_client_toolkit::shell::WaylandSurface; +use smithay_client_toolkit::shm::{slot::SlotPool, Shm}; +use smithay_client_toolkit::subcompositor::SubcompositorState; +use smithay_client_toolkit::subcompositor::SubsurfaceData; + +mod buttons; +mod config; +mod parts; +#[cfg(test)] +mod tests; +mod pointer; +mod shadow; +pub mod theme; +mod title; +mod wl_typed; + +use crate::theme::{ + ColorMap, ColorTheme, BORDER_SIZE, CORNER_RADIUS, HEADER_SIZE, RESIZE_HANDLE_CORNER_SIZE, + VISIBLE_BORDER_SIZE, +}; + +use buttons::Buttons; +use config::get_button_layout_config; +use parts::DecorationParts; +use pointer::{Location, MouseState}; +use shadow::Shadow; +use title::TitleText; +use wl_typed::WlTyped; + +/// XXX this is not result, so `must_use` when needed. +type SkiaResult = Option<()>; + +/// A simple set of decorations +#[derive(Debug)] +pub struct AdwaitaFrame<State> { + /// The base surface used to create the window. + base_surface: WlTyped<WlSurface, SurfaceData>, + + compositor: Arc<CompositorState>, + + /// Subcompositor to create/drop subsurfaces ondemand. + subcompositor: Arc<SubcompositorState>, + + /// Queue handle to perform object creation. + queue_handle: QueueHandle<State>, + + /// The drawable decorations, `None` when hidden. + decorations: Option<DecorationParts>, + + /// Memory pool to allocate the buffers for the decorations. + pool: SlotPool, + + /// Whether the frame should be redrawn. + dirty: bool, + + /// Whether the drawing should be synced with the main surface. + should_sync: bool, + + /// Scale factor used for the surface. + scale_factor: u32, + + /// Wether the frame is resizable. + resizable: bool, + + buttons: Buttons, + state: WindowState, + wm_capabilities: WindowManagerCapabilities, + mouse: MouseState, + theme: ColorTheme, + title: Option<String>, + title_text: Option<TitleText>, + shadow: Shadow, +} + +impl<State> AdwaitaFrame<State> +where + State: Dispatch<WlSurface, SurfaceData> + Dispatch<WlSubsurface, SubsurfaceData> + 'static, +{ + pub fn new( + base_surface: &impl WaylandSurface, + shm: &Shm, + compositor: Arc<CompositorState>, + subcompositor: Arc<SubcompositorState>, + queue_handle: QueueHandle<State>, + frame_config: FrameConfig, + ) -> Result<Self, Box<dyn Error>> { + let base_surface = WlTyped::wrap::<State>(base_surface.wl_surface().clone()); + + let pool = SlotPool::new(1, shm)?; + + let decorations = Some(DecorationParts::new( + &base_surface, + &subcompositor, + &queue_handle, + )); + + let theme = frame_config.theme; + + Ok(AdwaitaFrame { + base_surface, + decorations, + pool, + compositor, + subcompositor, + queue_handle, + dirty: true, + scale_factor: 1, + should_sync: true, + title: None, + title_text: TitleText::new(theme.active.font_color), + theme, + buttons: Buttons::new(get_button_layout_config()), + mouse: Default::default(), + state: WindowState::empty(), + wm_capabilities: WindowManagerCapabilities::all(), + resizable: true, + shadow: Shadow::default(), + }) + } + + /// Update the current frame config. + pub fn set_config(&mut self, config: FrameConfig) { + self.theme = config.theme; + self.dirty = true; + } + + /// The radius, in logical points, of the arc this frame leaves the window's content at its + /// bottom corners: the visible border is drawn within one point outside it. Zero when the + /// frame draws the window square, as a maximized, tiled or fullscreen one is (and as the + /// headerbar's top corners are). + pub fn content_corner_radius(&self) -> f32 { + content_radius(self.state) + } + + fn precise_location( + &self, + location: Location, + decoration: &DecorationParts, + x: f64, + y: f64, + ) -> Location { + let header_width = decoration.header().surface_rect.width; + let side_height = decoration.side_height(); + + let left_corner_x = BORDER_SIZE + RESIZE_HANDLE_CORNER_SIZE; + let right_corner_x = (header_width + BORDER_SIZE).saturating_sub(RESIZE_HANDLE_CORNER_SIZE); + let top_corner_y = RESIZE_HANDLE_CORNER_SIZE; + let bottom_corner_y = side_height.saturating_sub(RESIZE_HANDLE_CORNER_SIZE); + match location { + Location::Head | Location::Button(_) => self.buttons.find_button(x, y), + Location::Top | Location::TopLeft | Location::TopRight => { + if x <= f64::from(left_corner_x) { + Location::TopLeft + } else if x >= f64::from(right_corner_x) { + Location::TopRight + } else { + Location::Top + } + } + Location::Bottom | Location::BottomLeft | Location::BottomRight => { + if x <= f64::from(left_corner_x) { + Location::BottomLeft + } else if x >= f64::from(right_corner_x) { + Location::BottomRight + } else { + Location::Bottom + } + } + Location::Left => { + if y <= f64::from(top_corner_y) { + Location::TopLeft + } else if y >= f64::from(bottom_corner_y) { + Location::BottomLeft + } else { + Location::Left + } + } + Location::Right => { + if y <= f64::from(top_corner_y) { + Location::TopRight + } else if y >= f64::from(bottom_corner_y) { + Location::BottomRight + } else { + Location::Right + } + } + other => other, + } + } + + fn redraw_inner(&mut self) -> Option<bool> { + let decorations = self.decorations.as_mut()?; + + // Reset the dirty bit. + self.dirty = false; + let should_sync = mem::take(&mut self.should_sync); + + // Don't draw borders if the frame explicitly hidden or fullscreened. + if self.state.contains(WindowState::FULLSCREEN) { + decorations.hide(); + return Some(true); + } + + let colors = if self.state.contains(WindowState::ACTIVATED) { + &self.theme.active + } else { + &self.theme.inactive + }; + + let draw_borders = if self.state.contains(WindowState::MAXIMIZED) { + // Don't draw the borders. + decorations.hide_borders(); + false + } else { + true + }; + + // Draw the borders. + for (idx, part) in decorations + .parts() + .filter(|(idx, _)| *idx == DecorationParts::HEADER || draw_borders) + { + let scale = self.scale_factor; + + let mut rect = part.surface_rect; + // XXX to perfectly align the visible borders we draw them with + // the header, otherwise rounded corners won't look 'smooth' at the + // start. To achieve that, we enlargen the width of the header by + // 2 * `VISIBLE_BORDER_SIZE`, and move `x` by `VISIBLE_BORDER_SIZE` + // to the left. + if idx == DecorationParts::HEADER && draw_borders { + rect.width += 2 * VISIBLE_BORDER_SIZE; + rect.x -= VISIBLE_BORDER_SIZE as i32; + } + + rect.width *= scale; + rect.height *= scale; + + let (buffer, canvas) = match self.pool.create_buffer( + rect.width as i32, + rect.height as i32, + rect.width as i32 * 4, + wl_shm::Format::Argb8888, + ) { + Ok((buffer, canvas)) => (buffer, canvas), + Err(_) => continue, + }; + + // Create the pixmap and fill with transparent color. + let mut pixmap = PixmapMut::from_bytes(canvas, rect.width, rect.height)?; + + // Fill everything with transparent background, since we draw rounded corners and + // do invisible borders to enlarge the input zone. + pixmap.fill(Color::TRANSPARENT); + + // The bottom and side parts draw their shadow along with their border: the bottom one + // is the part that reaches over the window, so its corners are cut out of the shadow it + // draws there, and a side part's border stops where the bottom corner's arc takes over. + if !matches!( + idx, + DecorationParts::BOTTOM | DecorationParts::LEFT | DecorationParts::RIGHT + ) && !self.state.intersects(WindowState::TILED) + { + self.shadow.draw( + &mut pixmap, + scale, + self.state.contains(WindowState::ACTIVATED), + idx, + // The other parts have no rounded corners of their own to reach over the + // window with. + 0., + ); + } + + match idx { + DecorationParts::HEADER => { + if let Some(title_text) = self.title_text.as_mut() { + title_text.update_scale(scale); + title_text.update_color(colors.font_color); + } + + draw_headerbar( + &mut pixmap, + self.title_text.as_ref().map(|t| t.pixmap()).unwrap_or(None), + scale as f32, + self.resizable, + &self.state, + &self.theme, + &self.buttons, + self.mouse.location, + ); + } + DecorationParts::BOTTOM => { + draw_bottom( + &mut pixmap, + &mut self.shadow, + colors, + &self.state, + scale, + rect.width, + ); + } + DecorationParts::LEFT => { + draw_side(&mut pixmap, &mut self.shadow, colors, &self.state, scale, false); + } + DecorationParts::RIGHT => { + draw_side(&mut pixmap, &mut self.shadow, colors, &self.state, scale, true); + } + _ => {} + }; + + if should_sync { + part.subsurface.set_sync(); + } else { + part.subsurface.set_desync(); + } + + part.surface.set_buffer_scale(scale as i32); + + part.subsurface.set_position(rect.x, rect.y); + buffer.attach_to(&part.surface).ok()?; + + if part.surface.version() >= 4 { + part.surface.damage_buffer(0, 0, i32::MAX, i32::MAX); + } else { + part.surface.damage(0, 0, i32::MAX, i32::MAX); + } + + if let Some(input_rect) = part.input_rect { + let input_region = Region::new(&*self.compositor).ok()?; + input_region.add( + input_rect.x, + input_rect.y, + input_rect.width as i32, + input_rect.height as i32, + ); + + part.surface + .set_input_region(Some(input_region.wl_region())); + } + + part.surface.commit(); + } + + Some(should_sync) + } +} + +impl<State> DecorationsFrame for AdwaitaFrame<State> +where + State: Dispatch<WlSurface, SurfaceData> + Dispatch<WlSubsurface, SubsurfaceData> + 'static, +{ + fn update_state(&mut self, state: WindowState) { + let difference = self.state.symmetric_difference(state); + self.state = state; + self.dirty |= difference.intersects( + WindowState::ACTIVATED + | WindowState::FULLSCREEN + | WindowState::MAXIMIZED + | WindowState::TILED, + ); + } + + fn update_wm_capabilities(&mut self, wm_capabilities: WindowManagerCapabilities) { + self.dirty |= self.wm_capabilities != wm_capabilities; + self.wm_capabilities = wm_capabilities; + self.buttons.update_wm_capabilities(wm_capabilities); + } + + fn set_hidden(&mut self, hidden: bool) { + if hidden { + self.dirty = false; + let _ = self.pool.resize(1); + self.decorations = None; + } else if self.decorations.is_none() { + self.decorations = Some(DecorationParts::new( + &self.base_surface, + &self.subcompositor, + &self.queue_handle, + )); + self.dirty = true; + self.should_sync = true; + } + } + + fn set_resizable(&mut self, resizable: bool) { + self.dirty |= self.resizable != resizable; + self.resizable = resizable; + } + + fn resize(&mut self, width: NonZeroU32, height: NonZeroU32) { + let Some(decorations) = self.decorations.as_mut() else { + log::error!("trying to resize the hidden frame."); + return; + }; + + decorations.resize(width.get(), height.get()); + self.buttons + .arrange(width.get(), get_margin_h_lp(&self.state)); + self.dirty = true; + self.should_sync = true; + } + + fn draw(&mut self) -> bool { + self.redraw_inner().unwrap_or(true) + } + + fn subtract_borders( + &self, + width: NonZeroU32, + height: NonZeroU32, + ) -> (Option<NonZeroU32>, Option<NonZeroU32>) { + if self.decorations.is_none() || self.state.contains(WindowState::FULLSCREEN) { + (Some(width), Some(height)) + } else { + ( + Some(width), + NonZeroU32::new(height.get().saturating_sub(HEADER_SIZE)), + ) + } + } + + fn add_borders(&self, width: u32, height: u32) -> (u32, u32) { + if self.decorations.is_none() || self.state.contains(WindowState::FULLSCREEN) { + (width, height) + } else { + (width, height + HEADER_SIZE) + } + } + + fn location(&self) -> (i32, i32) { + if self.decorations.is_none() || self.state.contains(WindowState::FULLSCREEN) { + (0, 0) + } else { + (0, -(HEADER_SIZE as i32)) + } + } + + fn set_title(&mut self, title: impl Into<String>) { + let new_title = title.into(); + if let Some(title_text) = self.title_text.as_mut() { + title_text.update_title(new_title.clone()); + } + + self.title = Some(new_title); + self.dirty = true; + } + + fn on_click( + &mut self, + timestamp: Duration, + click: FrameClick, + pressed: bool, + ) -> Option<FrameAction> { + match click { + FrameClick::Normal => self.mouse.click( + timestamp, + pressed, + self.resizable, + &self.state, + &self.wm_capabilities, + ), + FrameClick::Alternate => self.mouse.alternate_click(pressed, &self.wm_capabilities), + _ => None, + } + } + + fn set_scaling_factor(&mut self, scale_factor: f64) { + // NOTE: Clamp it just in case to some ok-ish range. + self.scale_factor = scale_factor.clamp(0.1, 64.).ceil() as u32; + self.dirty = true; + self.should_sync = true; + } + + fn click_point_moved( + &mut self, + _timestamp: Duration, + surface: &ObjectId, + x: f64, + y: f64, + ) -> Option<CursorIcon> { + let decorations = self.decorations.as_ref()?; + let location = decorations.find_surface(surface); + if location == Location::None { + return None; + } + + let old_location = self.mouse.location; + + let location = self.precise_location(location, decorations, x, y); + let new_cursor = self.mouse.moved(location, x, y, self.resizable); + + // Set dirty if we moved the cursor between the buttons. + self.dirty |= (matches!(old_location, Location::Button(_)) + || matches!(self.mouse.location, Location::Button(_))) + && old_location != self.mouse.location; + + Some(new_cursor) + } + + fn click_point_left(&mut self) { + self.mouse.left() + } + + fn is_dirty(&self) -> bool { + self.dirty + } + + fn is_hidden(&self) -> bool { + self.decorations.is_none() + } +} + +/// The configuration for the [`AdwaitaFrame`] frame. +#[derive(Debug, Clone)] +pub struct FrameConfig { + pub theme: ColorTheme, +} + +impl FrameConfig { + /// Create the new configuration with the given `theme`. + pub fn new(theme: ColorTheme) -> Self { + Self { theme } + } + + /// This is equivalent of calling `FrameConfig::new(ColorTheme::auto())`. + /// + /// For details see [`ColorTheme::auto`]. + pub fn auto() -> Self { + Self { + theme: ColorTheme::auto(), + } + } + + /// This is equivalent of calling `FrameConfig::new(ColorTheme::light())`. + /// + /// For details see [`ColorTheme::light`]. + pub fn light() -> Self { + Self { + theme: ColorTheme::light(), + } + } + + /// This is equivalent of calling `FrameConfig::new(ColorTheme::dark())`. + /// + /// For details see [`ColorTheme::dark`]. + pub fn dark() -> Self { + Self { + theme: ColorTheme::dark(), + } + } +} + +#[allow(clippy::too_many_arguments)] +fn draw_headerbar( + pixmap: &mut PixmapMut, + text_pixmap: Option<&Pixmap>, + scale: f32, + resizable: bool, + state: &WindowState, + theme: &ColorTheme, + buttons: &Buttons, + mouse: Location, +) { + let colors = theme.for_state(state.contains(WindowState::ACTIVATED)); + + let _ = draw_headerbar_bg(pixmap, scale, colors, state); + + // Horizontal margin. + let margin_h = get_margin_h_lp(state) * 2.0; + + let canvas_w = pixmap.width() as f32; + let canvas_h = pixmap.height() as f32; + + let header_w = canvas_w - margin_h * 2.0; + let header_h = canvas_h; + + if let Some(text_pixmap) = text_pixmap { + const TEXT_OFFSET: f32 = 10.; + let offset_x = TEXT_OFFSET * scale; + + let text_w = text_pixmap.width() as f32; + let text_h = text_pixmap.height() as f32; + + let x = margin_h + header_w / 2. - text_w / 2.; + let y = header_h / 2. - text_h / 2.; + + let left_buttons_end_x = buttons.left_buttons_end_x().unwrap_or(0.0) * scale; + let right_buttons_start_x = + buttons.right_buttons_start_x().unwrap_or(header_w / scale) * scale; + + { + // We have enough space to center text + let (x, y, text_canvas_start_x) = if (x + text_w < right_buttons_start_x - offset_x) + && (x > left_buttons_end_x + offset_x) + { + let text_canvas_start_x = x; + + (x, y, text_canvas_start_x) + } else { + let x = left_buttons_end_x + offset_x; + let text_canvas_start_x = left_buttons_end_x + offset_x; + + (x, y, text_canvas_start_x) + }; + + let text_canvas_end_x = right_buttons_start_x - x - offset_x; + // Ensure that text start within the bounds. + let x = x.max(margin_h + offset_x); + + if let Some(clip) = + Rect::from_xywh(text_canvas_start_x, 0., text_canvas_end_x, canvas_h) + { + if let Some(mut mask) = Mask::new(canvas_w as u32, canvas_h as u32) { + mask.fill_path( + &PathBuilder::from_rect(clip), + FillRule::Winding, + false, + Transform::identity(), + ); + pixmap.draw_pixmap( + x.round() as i32, + y as i32, + text_pixmap.as_ref(), + &PixmapPaint::default(), + Transform::identity(), + Some(&mask), + ); + } else { + log::error!( + "Invalid mask width and height: w: {}, h: {}", + canvas_w as u32, + canvas_h as u32 + ); + } + } + } + } + + // Draw the buttons. + buttons.draw( + margin_h, header_w, scale, colors, mouse, pixmap, resizable, state, + ); +} + +#[must_use] +fn draw_headerbar_bg( + pixmap: &mut PixmapMut, + scale: f32, + colors: &ColorMap, + state: &WindowState, +) -> SkiaResult { + let w = pixmap.width() as f32; + let h = pixmap.height() as f32; + + let radius = if state.intersects(WindowState::MAXIMIZED | WindowState::TILED) { + 0. + } else { + CORNER_RADIUS as f32 * scale + }; + + let bg = rounded_headerbar_shape(0., 0., w, h, radius)?; + + pixmap.fill_path( + &bg, + &colors.headerbar_paint(), + FillRule::Winding, + Transform::identity(), + None, + ); + + pixmap.fill_rect( + Rect::from_xywh(0., h - 1., w, h)?, + &colors.border_paint(), + Transform::identity(), + None, + ); + + Some(()) +} + +fn rounded_headerbar_shape(x: f32, y: f32, width: f32, height: f32, radius: f32) -> Option<Path> { + // https://stackoverflow.com/a/27863181 + let cubic_bezier_circle = 0.552_284_8 * radius; + + let mut pb = PathBuilder::new(); + let mut cursor = Point::from_xy(x, y); + + // !!! + // This code is heavily "inspired" by https://gitlab.com/snakedye/snui/ + // So technically it should be licensed under MPL-2.0, sorry about that 🥺 👉👈 + // !!! + + // Positioning the cursor + cursor.y += radius; + pb.move_to(cursor.x, cursor.y); + + // Drawing the outline + let next = Point::from_xy(cursor.x + radius, cursor.y - radius); + pb.cubic_to( + cursor.x, + cursor.y - cubic_bezier_circle, + next.x - cubic_bezier_circle, + next.y, + next.x, + next.y, + ); + cursor = next; + pb.line_to( + { + cursor.x = x + width - radius; + cursor.x + }, + cursor.y, + ); + let next = Point::from_xy(cursor.x + radius, cursor.y + radius); + pb.cubic_to( + cursor.x + cubic_bezier_circle, + cursor.y, + next.x, + next.y - cubic_bezier_circle, + next.x, + next.y, + ); + cursor = next; + pb.line_to(cursor.x, { + cursor.y = y + height; + cursor.y + }); + pb.line_to( + { + cursor.x = x; + cursor.x + }, + cursor.y, + ); + + pb.close(); + + pb.finish() +} + +/// The radius, in logical points, of the arc a frame leaves the window's content at its bottom +/// corners. The frame's one-point visible border is drawn just outside that arc, so the window's +/// own corners are [`VISIBLE_BORDER_SIZE`] more, and the shadow's rounded cut-out is the same +/// disc. +pub const CONTENT_CORNER_RADIUS: u32 = CORNER_RADIUS - VISIBLE_BORDER_SIZE; + +/// The radius, in logical points, of the arc this frame leaves the window's content at its bottom +/// corners in `state`: zero when the window is square, as a maximized, tiled or fullscreen one is. +fn content_radius(state: WindowState) -> f32 { + if square(state) { + 0. + } else { + CONTENT_CORNER_RADIUS as f32 + } +} + +/// The radius, in logical points, of the visible border's outer edge around the window's bottom +/// corners in `state`: [`CORNER_RADIUS`], or zero when the window is square. +fn border_radius(state: WindowState) -> f32 { + if square(state) { + 0. + } else { + CORNER_RADIUS as f32 + } +} + +/// Whether `state` draws the window's corners square, as the headerbar's top ones are: maximized, +/// tiled and fullscreen windows have no corners to round. +fn square(state: WindowState) -> bool { + state.intersects(WindowState::MAXIMIZED | WindowState::TILED | WindowState::FULLSCREEN) +} + +/// Draws the bottom part: its shadow, the arcs cut out of it where the content's own rounded +/// corners show through, and the visible border around them. +fn draw_bottom( + pixmap: &mut PixmapMut, + shadow: &mut Shadow, + colors: &ColorMap, + state: &WindowState, + scale: u32, + width: u32, +) { + let border = (VISIBLE_BORDER_SIZE * scale) as f32; + // The part is placed one corner radius above the window's bottom edge, and spans it plus the + // shadow and border around the window: `left` and `right` are the window's outer edges. + let left = (BORDER_SIZE * scale) as f32 - border; + let right = width as f32 - left; + let bottom = (CORNER_RADIUS * scale) as f32; + let radius = border_radius(*state) * scale as f32; + + if !state.intersects(WindowState::TILED) { + shadow.draw(pixmap, scale, state.contains(WindowState::ACTIVATED), DecorationParts::BOTTOM, radius); + } + + if radius < border { + if let Some(rect) = Rect::from_xywh(left, bottom, (right - left).max(0.), border) { + pixmap.fill_rect(rect, &colors.border_paint(), Transform::identity(), None); + } + return; + } + // The band above the window's bottom edge carries the shadow's corner crescents, so the arcs + // are cleared out of it before the border is drawn along them: the shadow stays outside the + // arcs the content leaves, and nothing stays where the content shows through. + clear_bottom_corner_holes(pixmap, left, right, bottom, border, radius); + if let Some(shape) = bottom_border_shape(left, right, bottom, border, radius) { + pixmap.fill_path(&shape, &colors.border_paint(), FillRule::EvenOdd, Transform::identity(), None); + } +} + +/// Draws a side part (`LEFT` or `RIGHT`): the shadow down that side of the window, and the visible +/// border along it, from under the headerbar to where the bottom corner's arc takes over. +fn draw_side( + pixmap: &mut PixmapMut, + shadow: &mut Shadow, + colors: &ColorMap, + state: &WindowState, + scale: u32, + right: bool, +) { + let idx = if right { DecorationParts::RIGHT } else { DecorationParts::LEFT }; + if !state.intersects(WindowState::TILED) { + shadow.draw(pixmap, scale, state.contains(WindowState::ACTIVATED), idx, 0.); + } + let border = (VISIBLE_BORDER_SIZE * scale) as f32; + let top = (HEADER_SIZE * scale) as f32; + let corner = (border_radius(*state) * scale as f32 - border).max(0.); + let height = (pixmap.height() as f32 - top - corner).max(0.); + let x = if right { 0. } else { (BORDER_SIZE * scale) as f32 - border }; + if let Some(rect) = Rect::from_xywh(x, top, border, height) { + pixmap.fill_rect(rect, &colors.border_paint(), Transform::identity(), None); + } +} + +/// Clears the two discs of radius `radius` the bottom part's shadow is cut out of, so the part +/// leaves the content's rounded corners alone. +fn clear_bottom_corner_holes(pixmap: &mut PixmapMut, left: f32, right: f32, bottom: f32, border: f32, radius: f32) { + // Each arc's centre is the content's: `border` up from the content's bottom edge, `radius` in + // from the window's edge. + let centre_y = bottom + border - radius; + let paint = Paint { + shader: Shader::SolidColor(Color::TRANSPARENT), + blend_mode: BlendMode::Clear, + anti_alias: true, + ..Paint::default() + }; + for centre_x in [left + radius, right - radius] { + if let Some(circle) = circle_path(centre_x, centre_y, radius) { + pixmap.fill_path(&circle, &paint, FillRule::Winding, Transform::identity(), None); + } + } +} + +/// A circle of `radius` around `(cx, cy)`, as four cubic arcs. +fn circle_path(cx: f32, cy: f32, radius: f32) -> Option<Path> { + if radius <= 0. { + return None; + } + // https://stackoverflow.com/a/27863181, as `rounded_headerbar_shape`. + let k = 0.552_284_8 * radius; + let mut pb = PathBuilder::new(); + pb.move_to(cx + radius, cy); + pb.cubic_to(cx + radius, cy + k, cx + k, cy + radius, cx, cy + radius); + pb.cubic_to(cx - k, cy + radius, cx - radius, cy + k, cx - radius, cy); + pb.cubic_to(cx - radius, cy - k, cx - k, cy - radius, cx, cy - radius); + pb.cubic_to(cx + k, cy - radius, cx + radius, cy - k, cx + radius, cy); + pb.close(); + pb.finish() +} + +/// The visible border under a window whose bottom corners are rounded with `radius`: a one-point +/// band along `bottom`, the content's bottom edge, from `left` to `right`, the window's outer +/// edges, curving around each corner outside the arc the content leaves (centred one radius inside +/// the window's corner, so the band sits between that arc and the shadow). A window too narrow for +/// both arcs rounds them as far as it can. +fn bottom_border_shape( + left: f32, + right: f32, + bottom: f32, + border: f32, + radius: f32, +) -> Option<Path> { + if !(left.is_finite() && right.is_finite() && bottom.is_finite() && border.is_finite() && radius.is_finite()) + || border <= 0. + || right <= left + { + return None; + } + // https://stackoverflow.com/a/27863181, as `rounded_headerbar_shape`. + let k = 0.552_284_8; + let radius = radius.min((right - left) / 2.).max(border); + let outer = bottom + border; + let (outer_radius, inner_radius) = (radius, radius - border); + // One disc per corner: its centre is the content's arc centre, `outer` less the outer radius. + let centre_y = outer - outer_radius; + let (left_centre, right_centre) = (left + outer_radius, right - outer_radius); + + let mut pb = PathBuilder::new(); + // The window's outline: down the left edge, around the corner, along the bottom, around the + // other corner, and up the right edge. + pb.move_to(left, 0.); + pb.line_to(left, centre_y); + pb.cubic_to( + left, + centre_y + k * outer_radius, + left_centre - k * outer_radius, + outer, + left_centre, + outer, + ); + pb.line_to(right_centre, outer); + pb.cubic_to( + right_centre + k * outer_radius, + outer, + right, + centre_y + k * outer_radius, + right, + centre_y, + ); + pb.line_to(right, 0.); + pb.close(); + // And the content's, one point inside it: filling both even-odd leaves the border between. + pb.move_to(left + border, 0.); + pb.line_to(left + border, centre_y); + pb.cubic_to( + left + border, + centre_y + k * inner_radius, + left_centre - k * inner_radius, + bottom, + left_centre, + bottom, + ); + pb.line_to(right_centre, bottom); + pb.cubic_to( + right_centre + k * inner_radius, + bottom, + right - border, + centre_y + k * inner_radius, + right - border, + centre_y, + ); + pb.line_to(right - border, 0.); + pb.close(); + + pb.finish() +} + +// returns horizontal margin, logical points +fn get_margin_h_lp(state: &WindowState) -> f32 { + if state.intersects(WindowState::MAXIMIZED | WindowState::TILED) { + 0. + } else { + VISIBLE_BORDER_SIZE as f32 + } +} diff --git a/app/vendor/rune/vendor/sctk-adwaita/src/parts.rs b/app/vendor/rune/vendor/sctk-adwaita/src/parts.rs new file mode 100644 index 0000000..4d92a72 --- /dev/null +++ b/app/vendor/rune/vendor/sctk-adwaita/src/parts.rs @@ -0,0 +1,272 @@ +use smithay_client_toolkit::reexports::client::{ + backend::ObjectId, + protocol::{wl_subsurface::WlSubsurface, wl_surface::WlSurface}, + Dispatch, Proxy, QueueHandle, +}; + +use smithay_client_toolkit::{ + compositor::SurfaceData, + subcompositor::{SubcompositorState, SubsurfaceData}, +}; + +use crate::theme::{BORDER_SIZE, CORNER_RADIUS, HEADER_SIZE, RESIZE_HANDLE_SIZE}; +use crate::{pointer::Location, wl_typed::WlTyped}; + +/// The bottom part's input zone, which is its resize handle: it starts at the window's bottom +/// edge, not at the part's top, since the part reaches a corner radius above the edge and must not +/// take input there from the content. +pub(crate) fn bottom_input_rect(surface_width: u32) -> Rect { + Rect { + x: BORDER_SIZE as i32 - RESIZE_HANDLE_SIZE as i32, + y: CORNER_RADIUS as i32, + width: surface_width + .saturating_sub(BORDER_SIZE * 2) + .saturating_add(RESIZE_HANDLE_SIZE * 2), + height: RESIZE_HANDLE_SIZE, + } +} + +/// The decoration's 'parts'. +#[derive(Debug)] +pub struct DecorationParts { + parts: [Part; 5], +} + +impl DecorationParts { + // XXX keep in sync with `Self;:new`. + // Order is important. The lower the number, the earlier the part gets drawn. + // Because the header can overlap other parts, we draw it last. + pub const TOP: usize = 0; + pub const LEFT: usize = 1; + pub const RIGHT: usize = 2; + pub const BOTTOM: usize = 3; + pub const HEADER: usize = 4; + + pub fn new<State>( + base_surface: &WlTyped<WlSurface, SurfaceData>, + subcompositor: &SubcompositorState, + queue_handle: &QueueHandle<State>, + ) -> Self + where + State: Dispatch<WlSurface, SurfaceData> + Dispatch<WlSubsurface, SubsurfaceData> + 'static, + { + // XXX the order must be in sync with associated constants. + let parts = [ + // Top. + Part::new( + base_surface, + subcompositor, + queue_handle, + Rect { + x: -(BORDER_SIZE as i32), + y: -(HEADER_SIZE as i32 + BORDER_SIZE as i32), + width: 0, // Defined by `Self::resize`. + height: BORDER_SIZE, + }, + Some(Rect { + x: BORDER_SIZE as i32 - RESIZE_HANDLE_SIZE as i32, + y: BORDER_SIZE as i32 - RESIZE_HANDLE_SIZE as i32, + width: 0, // Defined by `Self::resize`. + height: RESIZE_HANDLE_SIZE, + }), + ), + // Left. + Part::new( + base_surface, + subcompositor, + queue_handle, + Rect { + x: -(BORDER_SIZE as i32), + y: -(HEADER_SIZE as i32), + width: BORDER_SIZE, + height: 0, // Defined by `Self::resize`. + }, + Some(Rect { + x: BORDER_SIZE as i32 - RESIZE_HANDLE_SIZE as i32, + y: 0, + width: RESIZE_HANDLE_SIZE, + height: 0, // Defined by `Self::resize`. + }), + ), + // Right. + Part::new( + base_surface, + subcompositor, + queue_handle, + Rect { + x: 0, // Defined by `Self::resize`. + y: -(HEADER_SIZE as i32), + width: BORDER_SIZE, + height: 0, // Defined by `Self::resize`. + }, + Some(Rect { + x: 0, + y: 0, + width: RESIZE_HANDLE_SIZE, + height: 0, // Defined by `Self::resize`. + }), + ), + // Bottom. + Part::new( + base_surface, + subcompositor, + queue_handle, + Rect { + x: -(BORDER_SIZE as i32), + y: 0, // Defined by `Self::resize`. + width: 0, // Defined by `Self::resize`. + // Reaches above the window's bottom edge, so the visible border can follow the + // rounded corners the content leaves it (`Self::resize`). + height: BORDER_SIZE + CORNER_RADIUS, + }, + Some(bottom_input_rect(0)), + ), + // Header. + Part::new( + base_surface, + subcompositor, + queue_handle, + Rect { + x: 0, + y: -(HEADER_SIZE as i32), + width: 0, // Defined by `Self::resize`. + height: HEADER_SIZE, + }, + None, + ), + ]; + + Self { parts } + } + + pub fn parts(&self) -> std::iter::Enumerate<std::slice::Iter<Part>> { + self.parts.iter().enumerate() + } + + pub fn hide(&self) { + for part in self.parts.iter() { + part.subsurface.set_sync(); + part.surface.attach(None, 0, 0); + part.surface.commit(); + } + } + + pub fn hide_borders(&self) { + for (_, part) in self.parts().filter(|(idx, _)| *idx != Self::HEADER) { + part.surface.attach(None, 0, 0); + part.surface.commit(); + } + } + + // These unwraps are guaranteed to succeed because the affected options are filled above + // and then never emptied afterwards. + #[allow(clippy::unwrap_used)] + pub fn resize(&mut self, width: u32, height: u32) { + self.parts[Self::HEADER].surface_rect.width = width; + + self.parts[Self::BOTTOM].surface_rect.width = width + 2 * BORDER_SIZE; + // `CORNER_RADIUS` above the window's bottom edge, where its rounded corners are: the + // visible border is drawn in that part of it. + self.parts[Self::BOTTOM].surface_rect.y = height as i32 - CORNER_RADIUS as i32; + *self.parts[Self::BOTTOM].input_rect.as_mut().unwrap() = + bottom_input_rect(self.parts[Self::BOTTOM].surface_rect.width); + + self.parts[Self::TOP].surface_rect.width = self.parts[Self::BOTTOM].surface_rect.width; + self.parts[Self::TOP].input_rect.as_mut().unwrap().width = + self.parts[Self::TOP].surface_rect.width - (BORDER_SIZE * 2) + (RESIZE_HANDLE_SIZE * 2); + + self.parts[Self::LEFT].surface_rect.height = height + HEADER_SIZE; + self.parts[Self::LEFT].input_rect.as_mut().unwrap().height = + self.parts[Self::LEFT].surface_rect.height; + + self.parts[Self::RIGHT].surface_rect.height = self.parts[Self::LEFT].surface_rect.height; + self.parts[Self::RIGHT].surface_rect.x = width as i32; + self.parts[Self::RIGHT].input_rect.as_mut().unwrap().height = + self.parts[Self::RIGHT].surface_rect.height; + } + + pub fn header(&self) -> &Part { + &self.parts[Self::HEADER] + } + + pub fn side_height(&self) -> u32 { + self.parts[Self::LEFT].surface_rect.height + } + + pub fn find_surface(&self, surface: &ObjectId) -> Location { + let pos = match self + .parts + .iter() + .position(|part| &part.surface.id() == surface) + { + Some(pos) => pos, + None => return Location::None, + }; + + match pos { + Self::HEADER => Location::Head, + Self::TOP => Location::Top, + Self::BOTTOM => Location::Bottom, + Self::LEFT => Location::Left, + Self::RIGHT => Location::Right, + _ => unreachable!(), + } + } +} + +#[derive(Debug, Clone, Copy)] +pub struct Rect { + pub x: i32, + pub y: i32, + pub width: u32, + pub height: u32, +} + +#[derive(Debug)] +pub struct Part { + pub surface: WlTyped<WlSurface, SurfaceData>, + pub subsurface: WlTyped<WlSubsurface, SubsurfaceData>, + + /// Positioned relative to the main surface. + pub surface_rect: Rect, + /// Positioned relative to the local surface, aka. `surface_rect`. + /// + /// `None` if it fully covers `surface_rect`. + pub input_rect: Option<Rect>, +} + +impl Part { + fn new<State>( + parent: &WlTyped<WlSurface, SurfaceData>, + subcompositor: &SubcompositorState, + queue_handle: &QueueHandle<State>, + surface_rect: Rect, + input_rect: Option<Rect>, + ) -> Part + where + State: Dispatch<WlSurface, SurfaceData> + Dispatch<WlSubsurface, SubsurfaceData> + 'static, + { + let (subsurface, surface) = + subcompositor.create_subsurface(parent.inner().clone(), queue_handle); + + let subsurface = WlTyped::wrap::<State>(subsurface); + let surface = WlTyped::wrap::<State>(surface); + + // Sync with the parent surface. + subsurface.set_sync(); + + Part { + surface, + subsurface, + surface_rect, + input_rect, + } + } +} + +impl Drop for Part { + fn drop(&mut self) { + self.subsurface.destroy(); + self.surface.destroy(); + } +} diff --git a/app/vendor/rune/vendor/sctk-adwaita/src/pointer.rs b/app/vendor/rune/vendor/sctk-adwaita/src/pointer.rs new file mode 100644 index 0000000..9a512c7 --- /dev/null +++ b/app/vendor/rune/vendor/sctk-adwaita/src/pointer.rs @@ -0,0 +1,142 @@ +use std::time::Duration; + +use smithay_client_toolkit::reexports::csd_frame::{ + CursorIcon, FrameAction, ResizeEdge, WindowManagerCapabilities, WindowState, +}; + +use crate::{ + buttons::ButtonKind, + theme::{BORDER_SIZE, HEADER_SIZE}, +}; + +/// Time to register the next click as a double click. +/// +/// The value is the same as the default in gtk4. +const DOUBLE_CLICK_DURATION: Duration = Duration::from_millis(400); + +/// The state of the mouse input inside the decorations frame. +#[derive(Debug, Default)] +pub(crate) struct MouseState { + pub location: Location, + + /// The surface local location inside the surface. + position: (f64, f64), + + /// The instant of the last click. + last_normal_click: Option<Duration>, +} + +impl MouseState { + /// The normal click on decorations frame was made. + pub fn click( + &mut self, + timestamp: Duration, + pressed: bool, + resizable: bool, + state: &WindowState, + wm_capabilities: &WindowManagerCapabilities, + ) -> Option<FrameAction> { + let maximized = state.contains(WindowState::MAXIMIZED); + let action = match self.location { + Location::Top if resizable => FrameAction::Resize(ResizeEdge::Top), + Location::TopLeft if resizable => FrameAction::Resize(ResizeEdge::TopLeft), + Location::Left if resizable => FrameAction::Resize(ResizeEdge::Left), + Location::BottomLeft if resizable => FrameAction::Resize(ResizeEdge::BottomLeft), + Location::Bottom if resizable => FrameAction::Resize(ResizeEdge::Bottom), + Location::BottomRight if resizable => FrameAction::Resize(ResizeEdge::BottomRight), + Location::Right if resizable => FrameAction::Resize(ResizeEdge::Right), + Location::TopRight if resizable => FrameAction::Resize(ResizeEdge::TopRight), + Location::Button(ButtonKind::Close) if !pressed => FrameAction::Close, + Location::Button(ButtonKind::Maximize) if !pressed && !maximized => { + FrameAction::Maximize + } + Location::Button(ButtonKind::Maximize) if !pressed && maximized => { + FrameAction::UnMaximize + } + Location::Button(ButtonKind::Minimize) if !pressed => FrameAction::Minimize, + Location::Head + if pressed && wm_capabilities.contains(WindowManagerCapabilities::MAXIMIZE) => + { + match self.last_normal_click.replace(timestamp) { + Some(last) if timestamp.saturating_sub(last) < DOUBLE_CLICK_DURATION => { + if maximized { + FrameAction::UnMaximize + } else { + FrameAction::Maximize + } + } + _ => FrameAction::Move, + } + } + Location::Head if pressed => FrameAction::Move, + _ => return None, + }; + + Some(action) + } + + /// Alternative click on decorations frame was made. + pub fn alternate_click( + &mut self, + pressed: bool, + wm_capabilities: &WindowManagerCapabilities, + ) -> Option<FrameAction> { + // Invalidate the normal click. + self.last_normal_click = None; + + match self.location { + Location::Head | Location::Button(_) + if pressed && wm_capabilities.contains(WindowManagerCapabilities::WINDOW_MENU) => + { + Some(FrameAction::ShowMenu( + // XXX this could be one 1pt off when the frame is not maximized, but it's not + // like it really matters in the end. + self.position.0 as i32 - BORDER_SIZE as i32, + // We must offset it by header size for precise position. + self.position.1 as i32 - HEADER_SIZE as i32, + )) + } + _ => None, + } + } + + /// The mouse moved inside the decorations frame. + pub fn moved(&mut self, location: Location, x: f64, y: f64, resizable: bool) -> CursorIcon { + self.location = location; + self.position = (x, y); + match self.location { + _ if !resizable => CursorIcon::Default, + Location::Top => CursorIcon::NResize, + Location::TopRight => CursorIcon::NeResize, + Location::Right => CursorIcon::EResize, + Location::BottomRight => CursorIcon::SeResize, + Location::Bottom => CursorIcon::SResize, + Location::BottomLeft => CursorIcon::SwResize, + Location::Left => CursorIcon::WResize, + Location::TopLeft => CursorIcon::NwResize, + _ => CursorIcon::Default, + } + } + + /// The mouse left the decorations frame. + pub fn left(&mut self) { + // Reset only the location. + self.location = Location::None; + } +} + +#[derive(Debug, Copy, Clone, PartialEq, Eq, Default)] +pub enum Location { + #[default] + None, + Head, + Top, + TopRight, + Right, + BottomRight, + Bottom, + BottomLeft, + Left, + TopLeft, + Button(ButtonKind), +} diff --git a/app/vendor/rune/vendor/sctk-adwaita/src/shadow.rs b/app/vendor/rune/vendor/sctk-adwaita/src/shadow.rs new file mode 100644 index 0000000..669736b --- /dev/null +++ b/app/vendor/rune/vendor/sctk-adwaita/src/shadow.rs @@ -0,0 +1,439 @@ +use crate::{parts::DecorationParts, theme}; +use std::collections::BTreeMap; +use tiny_skia::{Pixmap, PixmapMut, PixmapRef, Point, PremultipliedColorU8}; + +// These values were generated from a screenshot of an libadwaita window using a script. +// For more details see: https://github.com/PolyMeilex/sctk-adwaita/pull/43 +pub const SHADOW_SIZE: u32 = 43; +const SHADOW_PARAMS_ACTIVE: (f32, f32, f32) = (0.206_505_5, 0.104_617_53, -0.000_542_446_2); +const SHADOW_PARAMS_INACTIVE: (f32, f32, f32) = (0.168_297_29, 0.204_299_8, 0.001_769_798_6); + +/// The shadow's alpha at `pixel_dist` from the window's outline: the frame's own model of it, +/// which `tests` reads as its reference. +pub(crate) fn shadow(pixel_dist: f32, scale: u32, active: bool) -> f32 { + let (a, b, c) = if active { + SHADOW_PARAMS_ACTIVE + } else { + SHADOW_PARAMS_INACTIVE + }; + + a * (-b * (pixel_dist / scale as f32)).exp() + c +} + +#[derive(Debug)] +struct RenderedShadow { + side: Pixmap, + edges: Pixmap, +} + +impl RenderedShadow { + fn new(scale: u32, active: bool) -> RenderedShadow { + let shadow_size = SHADOW_SIZE * scale; + let corner_radius = theme::CORNER_RADIUS * scale; + + #[allow(clippy::unwrap_used)] + let mut side = Pixmap::new(shadow_size, 1).unwrap(); + for x in 0..side.width() as usize { + let alpha = (shadow(x as f32 + 0.5, scale, active) * u8::MAX as f32).round() as u8; + + #[allow(clippy::unwrap_used)] + let color = PremultipliedColorU8::from_rgba(0, 0, 0, alpha).unwrap(); + side.pixels_mut()[x] = color; + } + + let edges_size = (corner_radius + shadow_size) * 2; + #[allow(clippy::unwrap_used)] + let mut edges = Pixmap::new(edges_size, edges_size).unwrap(); + let edges_middle = Point::from_xy(edges_size as f32 / 2.0, edges_size as f32 / 2.0); + for y in 0..edges_size as usize { + let y_pos = y as f32 + 0.5; + for x in 0..edges_size as usize { + let dist = edges_middle.distance(Point::from_xy(x as f32 + 0.5, y_pos)) + - corner_radius as f32; + let alpha = (shadow(dist, scale, active) * u8::MAX as f32).round() as u8; + + #[allow(clippy::unwrap_used)] + let color = PremultipliedColorU8::from_rgba(0, 0, 0, alpha).unwrap(); + edges.pixels_mut()[y * edges_size as usize + x] = color; + } + } + + RenderedShadow { side, edges } + } + + fn side_draw( + &self, + flipped: bool, + rotated: bool, + stack: usize, + dst_pixmap: &mut PixmapMut, + dst_left: usize, + dst_top: usize, + ) { + fn iter_copy<'a>( + src: impl Iterator<Item = &'a PremultipliedColorU8>, + dst: impl Iterator<Item = &'a mut PremultipliedColorU8>, + ) { + src.zip(dst).for_each(|(src, dst)| *dst = *src) + } + + let dst_width = dst_pixmap.width() as usize; + let dst_pixels = dst_pixmap.pixels_mut(); + match (flipped, rotated) { + (false, false) => (0..stack).for_each(|i| { + let dst = dst_pixels + .iter_mut() + .skip((dst_top + i) * dst_width + dst_left); + iter_copy(self.side.pixels().iter(), dst); + }), + (false, true) => (0..stack).for_each(|i| { + let dst = dst_pixels + .iter_mut() + .skip(dst_top * dst_width + dst_left + i) + .step_by(dst_width); + iter_copy(self.side.pixels().iter(), dst); + }), + (true, false) => (0..stack).for_each(|i| { + let dst = dst_pixels + .iter_mut() + .skip((dst_top + i) * dst_width + dst_left); + iter_copy(self.side.pixels().iter().rev(), dst); + }), + (true, true) => (0..stack).for_each(|i| { + let dst = dst_pixels + .iter_mut() + .skip(dst_top * dst_width + dst_left + i) + .step_by(dst_width); + iter_copy(self.side.pixels().iter().rev(), dst); + }), + } + } + + #[allow(clippy::too_many_arguments)] + fn edges_draw( + &self, + src_x_offset: isize, + src_y_offset: isize, + dst_pixmap: &mut PixmapMut, + dst_rect_left: usize, + dst_rect_top: usize, + dst_rect_width: usize, + dst_rect_height: usize, + ) { + let src_width = self.edges.width() as usize; + let src_pixels = self.edges.pixels(); + let dst_width = dst_pixmap.width() as usize; + let dst_pixels = dst_pixmap.pixels_mut(); + for y in 0..dst_rect_height { + let dst_y = dst_rect_top + y; + let src_y = y as isize + src_y_offset; + if src_y < 0 { + continue; + } + + let src_y = src_y as usize; + for x in 0..dst_rect_width { + let dst_x = dst_rect_left + x; + let src_x = x as isize + src_x_offset; + if src_x < 0 { + continue; + } + + let src = src_pixels.get(src_y * src_width + src_x as usize); + let dst = dst_pixels.get_mut(dst_y * dst_width + dst_x); + if let (Some(src), Some(dst)) = (src, dst) { + *dst = *src; + } + } + } + } + + fn draw(&self, dst_pixmap: &mut PixmapMut, scale: u32, part_idx: usize, corners: f32) { + let shadow_size = (SHADOW_SIZE * scale) as usize; + let visible_border_size = (theme::VISIBLE_BORDER_SIZE * scale) as usize; + let corner_radius = (theme::CORNER_RADIUS * scale) as usize; + assert!(corner_radius > visible_border_size); + + let dst_width = dst_pixmap.width() as usize; + let dst_height = dst_pixmap.height() as usize; + let edges_half = self.edges.width() as usize / 2; + match part_idx { + DecorationParts::TOP => { + let left_edge_width = edges_half; + let right_edge_width = edges_half; + let side_width = dst_width + .saturating_sub(left_edge_width) + .saturating_sub(right_edge_width); + + self.edges_draw( + 0, + -(visible_border_size as isize), + dst_pixmap, + 0, + 0, + left_edge_width, + dst_height, + ); + + self.side_draw( + true, + true, + side_width, + dst_pixmap, + left_edge_width, + visible_border_size, + ); + + self.edges_draw( + edges_half as isize, + -(visible_border_size as isize), + dst_pixmap, + left_edge_width + side_width, + 0, + right_edge_width, + dst_height, + ); + } + DecorationParts::LEFT => { + let top_edge_height = corner_radius; + let bottom_edge_height = corner_radius - visible_border_size; + let side_height = dst_height + .saturating_sub(top_edge_height) + .saturating_sub(bottom_edge_height); + + self.edges_draw( + 0, + shadow_size as isize, + dst_pixmap, + 0, + 0, + dst_width.saturating_sub(visible_border_size), + top_edge_height, + ); + + self.side_draw(true, false, side_height, dst_pixmap, 0, top_edge_height); + + // The bottom corner's piece reaches the border's own column: below the arc's + // tangent the side part draws no border there, and the shadow continues to the + // window's edge (`draw_side`). + self.edges_draw( + 0, + edges_half as isize, + dst_pixmap, + 0, + top_edge_height + side_height, + dst_width, + bottom_edge_height, + ); + } + DecorationParts::RIGHT => { + let top_edge_height = corner_radius; + let bottom_edge_height = corner_radius - visible_border_size; + let side_height = dst_height + .saturating_sub(top_edge_height) + .saturating_sub(bottom_edge_height); + + self.edges_draw( + edges_half as isize + corner_radius as isize, + shadow_size as isize, + dst_pixmap, + visible_border_size, + 0, + dst_width.saturating_sub(visible_border_size), + top_edge_height, + ); + + self.side_draw( + false, + false, + side_height, + dst_pixmap, + visible_border_size, + top_edge_height, + ); + + // The bottom corner's piece reaches the border's own column, where the side part + // draws no border below the arc's tangent: its source keeps the disc's centre where + // the top piece puts it (a corner radius outside this part, so `+ corner_radius`, + // less the column the piece now starts at). + self.edges_draw( + edges_half as isize + (corner_radius - visible_border_size) as isize, + edges_half as isize, + dst_pixmap, + 0, + top_edge_height + side_height, + dst_width, + bottom_edge_height, + ); + } + DecorationParts::BOTTOM => { + let left_edge_width = edges_half; + let right_edge_width = edges_half; + let side_width = dst_width + .saturating_sub(left_edge_width) + .saturating_sub(right_edge_width); + + // Below the window's bottom edge the shadow is a square frame's, whatever the + // corners, and the discs sit `visible_border_size` up from that edge: the source + // row puts them on the same pixel here and in the square part. + let corner_src_y = + edges_half as isize + (corner_radius - visible_border_size) as isize; + self.edges_draw( + 0, + corner_src_y, + dst_pixmap, + 0, + corner_radius, + left_edge_width, + dst_height, + ); + + self.side_draw( + false, + true, + side_width, + dst_pixmap, + left_edge_width, + corner_radius + visible_border_size, + ); + + self.edges_draw( + edges_half as isize, + corner_src_y, + dst_pixmap, + left_edge_width + side_width, + corner_radius, + right_edge_width, + dst_height, + ); + + if corners > 0. { + // The band above that edge carries the crescents the arcs cut out of the + // shadow, and only inside the content's own corner squares: outside them the + // side parts already draw the shadow down to the edge, and a second copy here + // would composite over theirs (the parts stack) and double it. + // + // The band's source keeps the disc's centre where the corner piece above puts + // it: `edges_half` in the image, `centre_x` in the part. + let band_src_y = edges_half as isize - visible_border_size as isize; + let margin = theme::BORDER_SIZE as usize * scale as usize; + let centres = [edges_half, dst_width.saturating_sub(edges_half)]; + let bands = [margin, dst_width.saturating_sub(margin + corner_radius)]; + for (centre_x, band_left) in centres.into_iter().zip(bands) { + let src_x = band_left as isize - centre_x as isize + edges_half as isize; + self.edges_draw(src_x, band_src_y, dst_pixmap, band_left, 0, corner_radius, corner_radius); + } + } + } + DecorationParts::HEADER => { + self.edges_draw( + shadow_size as isize, + shadow_size as isize, + dst_pixmap, + 0, + 0, + corner_radius, + corner_radius, + ); + + self.edges_draw( + edges_half as isize, + shadow_size as isize, + dst_pixmap, + dst_width.saturating_sub(corner_radius), + 0, + corner_radius, + corner_radius, + ); + } + _ => unreachable!(), + } + } +} + +#[derive(Debug)] +struct CachedPart { + pixmap: Pixmap, + scale: u32, + active: bool, + /// Whether it was drawn for round bottom corners, whose shadow reaches over the window. + corners: bool, +} + +impl CachedPart { + fn new( + dst_pixmap: &PixmapRef, + rendered: &RenderedShadow, + scale: u32, + active: bool, + part_idx: usize, + corners: f32, + ) -> CachedPart { + #[allow(clippy::unwrap_used)] + let mut pixmap = Pixmap::new(dst_pixmap.width(), dst_pixmap.height()).unwrap(); + rendered.draw(&mut pixmap.as_mut(), scale, part_idx, corners); + + CachedPart { + pixmap, + scale, + active, + corners: corners > 0., + } + } + + fn matches(&self, dst_pixmap: &PixmapRef, dst_scale: u32, dst_active: bool, corners: bool) -> bool { + self.pixmap.width() == dst_pixmap.width() + && self.pixmap.height() == dst_pixmap.height() + && self.scale == dst_scale + && self.active == dst_active + && self.corners == corners + } + + fn draw(&self, dst_pixmap: &mut PixmapMut) { + let src_data = self.pixmap.data(); + dst_pixmap.data_mut()[..src_data.len()].copy_from_slice(src_data); + } +} + +#[derive(Default, Debug)] +pub struct Shadow { + part_cache: [Option<CachedPart>; 5], + // (scale, active) -> RenderedShadow + rendered: BTreeMap<(u32, bool), RenderedShadow>, +} + +impl Shadow { + /// Draws part `part_idx`'s shadow. `corners` is the radius, in the part's pixels, of the round + /// bottom corners it is drawn for (zero for square ones): the bottom part reaches that far + /// above the window's bottom edge, so with round corners its shadow starts at the part's top. + pub fn draw(&mut self, pixmap: &mut PixmapMut, scale: u32, active: bool, part_idx: usize, corners: f32) { + let cache = &mut self.part_cache[part_idx]; + let round = corners > 0.; + + if let Some(cache_value) = cache { + if !cache_value.matches(&pixmap.as_ref(), scale, active, round) { + *cache = None; + } + } + + if cache.is_none() { + let rendered = self + .rendered + .entry((scale, active)) + .or_insert_with(|| RenderedShadow::new(scale, active)); + + *cache = Some(CachedPart::new( + &pixmap.as_ref(), + rendered, + scale, + active, + part_idx, + corners, + )); + } + + // We filled the cache above. + #[allow(clippy::unwrap_used)] + cache.as_ref().unwrap().draw(pixmap); + } +} diff --git a/app/vendor/rune/vendor/sctk-adwaita/src/tests.rs b/app/vendor/rune/vendor/sctk-adwaita/src/tests.rs new file mode 100644 index 0000000..15b61f0 --- /dev/null +++ b/app/vendor/rune/vendor/sctk-adwaita/src/tests.rs @@ -0,0 +1,308 @@ +//! The frame's rounded bottom corners: the radius each state gets, the border along the arcs, the +//! shadow the arcs cut out of the part that reaches over the window, and the bottom part's input +//! zone. Everything here draws into a `Pixmap` the way `redraw_inner` does, so it needs no +//! compositor. + +use crate::parts::{bottom_input_rect, DecorationParts}; +use crate::theme::{ColorTheme, BORDER_SIZE, CORNER_RADIUS, HEADER_SIZE, RESIZE_HANDLE_SIZE, VISIBLE_BORDER_SIZE}; +use crate::{ + border_radius, bottom_border_shape, content_radius, draw_bottom, draw_side, CONTENT_CORNER_RADIUS, +}; +use smithay_client_toolkit::reexports::csd_frame::WindowState; +use tiny_skia::{FillRule, Pixmap, PixmapPaint, Transform}; + +/// A pixel's alpha. +fn alpha(pixmap: &Pixmap, x: u32, y: u32) -> u8 { + pixmap + .pixel(x, y) + .unwrap_or_else(|| panic!("({x}, {y}) is outside {}x{}", pixmap.width(), pixmap.height())) + .alpha() +} + +/// Asserts the pixel is the light theme's border colour, within the antialiasing of the arcs, and +/// covered at least `min_alpha` of the way (the band is a point wide, so a pixel on the diagonal +/// is only part of it). +fn assert_border(pixmap: &Pixmap, x: u32, y: u32, min_alpha: u8, what: &str) { + let pixel = pixmap.pixel(x, y).expect("inside the pixmap").demultiply(); + let got = [pixel.red(), pixel.green(), pixel.blue()]; + let want = [220, 220, 220]; + assert!( + got.iter().zip(want).all(|(a, b)| a.abs_diff(b) <= 4), + "{what}: {got:?} at ({x}, {y}) is not the border colour {want:?}", + ); + assert!(pixel.alpha() >= min_alpha, "{what}: the band covers {}, not {min_alpha}", pixel.alpha()); +} + +/// The bottom part's pixmap as a window `width` points wide draws it: the shadow, the arcs cleared +/// out of it, and the border along them. +fn bottom_part(width: u32, state: WindowState) -> Pixmap { + let surface = (width + 2 * BORDER_SIZE, BORDER_SIZE + CORNER_RADIUS); + let mut pixmap = Pixmap::new(surface.0, surface.1).expect("a pixmap"); + draw_bottom( + &mut pixmap.as_mut(), + &mut Default::default(), + &ColorTheme::light().active, + &state, + 1, + surface.0, + ); + pixmap +} + +/// The frame's radius follows the window's state: round while it floats, square when the window +/// fills the screen or is tiled, and square in fullscreen, where the frame hides its borders. +#[test] +fn the_radius_follows_the_window_state() { + assert_eq!(content_radius(WindowState::empty()), CONTENT_CORNER_RADIUS as f32); + assert_eq!(border_radius(WindowState::empty()), CORNER_RADIUS as f32); + // An active window rounds the same as an inactive one. + assert_eq!(content_radius(WindowState::ACTIVATED), CONTENT_CORNER_RADIUS as f32); + for square in [ + WindowState::MAXIMIZED, + WindowState::TILED, + WindowState::FULLSCREEN, + WindowState::MAXIMIZED | WindowState::ACTIVATED, + WindowState::TILED | WindowState::FULLSCREEN, + ] { + assert_eq!(content_radius(square), 0., "{square:?} squares the content"); + assert_eq!(border_radius(square), 0., "{square:?} squares the border"); + } +} + +/// The border is a one-point band along the arc the content leaves: the content's side of it is +/// clear, the band is the border colour, and the shadow's side of it is the shadow's. +#[test] +fn the_border_follows_the_bottom_arcs() { + let (left, right, bottom, border, radius) = (43., 243., 10., 1., 10.); + let shape = bottom_border_shape(left, right, bottom, border, radius).expect("a border shape"); + let mut pixmap = Pixmap::new(288, 54).expect("a pixmap"); + pixmap + .as_mut() + .fill_path(&shape, &ColorTheme::light().active.border_paint(), FillRule::EvenOdd, Transform::identity(), None); + + // (46, 7) is 9.2 from the arc's centre (53, 1): inside the one-point band. + assert_border(&pixmap, 46, 7, 150, "the band on the arc"); + // (50, 5) is 5 from the centre: the content's own corner, which the band leaves clear. + assert_eq!(alpha(&pixmap, 50, 5), 0, "inside the arc is the content's"); + // The straight band runs the window's whole width, just under its bottom edge. + assert_border(&pixmap, 100, 10, 250, "the bottom band between the arcs"); + // Nothing is drawn below the band: that is the shadow's and the window's outside. + assert_eq!(alpha(&pixmap, 100, 12), 0, "below the band the shadow draws"); +} + +/// The shadow below the window's edge is the square frame's, pixel for pixel: round corners only +/// add the crescents above that edge, and nothing else about the shadow moves. +#[test] +fn a_round_frames_shadow_below_the_window_is_the_square_frames() { + let round = bottom_part(200, WindowState::empty()); + let square = bottom_part(200, WindowState::MAXIMIZED); + // The window's bottom edge is a corner radius into the part; the one-point band is just below + // it, and the shadow below the window starts under that. + let below = (CORNER_RADIUS + VISIBLE_BORDER_SIZE) as u32; + for y in below..round.height() { + for x in 0..round.width() { + let (rounded, squared) = (alpha(&round, x, y), alpha(&square, x, y)); + assert!( + rounded.abs_diff(squared) <= 1, + "({x}, {y}): round corners give {rounded}, the square frame {squared}", + ); + } + } + // And the content's corner is left alone: inside the arc nothing is drawn. + assert_eq!(alpha(&round, 50, 5), 0, "inside the arc is the content's"); +} + +/// The last corner column and the first plain one below the window's edge carry the same shadow: the +/// corner's crescent and the straight band meet without a step, at every depth. +#[test] +fn the_shadow_is_smooth_across_the_corner_and_plain_columns() { + let pixmap = bottom_part(200, WindowState::empty()); + // The corner's columns end where the straight band's begin: `left` plus the corner radius. + let plain = (BORDER_SIZE - VISIBLE_BORDER_SIZE + CORNER_RADIUS) as u32; + let corner = plain - 1; + for y in [11, 15, 20, 30, 40] { + let (corner_alpha, plain_alpha) = (alpha(&pixmap, corner, y), alpha(&pixmap, plain, y)); + if y <= 30 { + assert!(plain_alpha > 0, "({plain}, {y}) has the straight band's shadow"); + } + assert!( + corner_alpha.abs_diff(plain_alpha) <= 2, + "row {y}: the corner column has {corner_alpha}, the plain one {plain_alpha}", + ); + } + // The crescent above the edge, outside the arc, keeps its shadow too. + assert!(alpha(&pixmap, 45, 10) > 0, "the crescent outside the arc keeps its shadow"); + // And the mirror corner reads the same. + let width = pixmap.width() as u32; + for y in [11, 20, 40] { + let (corner_alpha, plain_alpha) = (alpha(&pixmap, width - 1 - corner, y), alpha(&pixmap, width - 1 - plain, y)); + assert!(corner_alpha.abs_diff(plain_alpha) <= 2, "row {y} on the right"); + } +} + +/// A square window (maximized, tiled or fullscreen) draws a straight band and no shadow over the +/// window at all: nothing is cut out of the content's corners. +#[test] +fn a_square_window_keeps_its_corners() { + let pixmap = bottom_part(200, WindowState::MAXIMIZED); + assert_border(&pixmap, 46, 10, 250, "the band straight across the corner"); + assert_eq!(alpha(&pixmap, 45, 9), 0, "no shadow over the window's corner"); + assert_eq!(alpha(&pixmap, 50, 5), 0, "nothing is cut out of the content"); + + assert!(alpha(&pixmap, 45, 12) > 0, "the shadow below the window is still drawn"); + + let tiled = bottom_part(200, WindowState::TILED); + assert_border(&tiled, 46, 10, 250, "a tiled window's straight border"); +} + +/// The bottom part reaches a corner radius above the window's bottom edge, so its input zone — its +/// resize handle — starts at that edge instead, and never takes input from the content. +#[test] +fn the_bottom_input_zone_starts_at_the_windows_edge() { + let surface = 200 + 2 * BORDER_SIZE; + let input = bottom_input_rect(surface); + assert_eq!(input.y, CORNER_RADIUS as i32, "the part's top is a corner radius above the edge"); + assert_eq!(input.height, RESIZE_HANDLE_SIZE); + assert_eq!(input.width, surface - BORDER_SIZE * 2 + RESIZE_HANDLE_SIZE * 2); + assert!(input.x >= BORDER_SIZE as i32 - RESIZE_HANDLE_SIZE as i32); +} + +/// A window narrower than two corner radii still gets a border: the arcs are rounded as far as +/// they fit and nothing runs outside the part. +#[test] +fn a_narrow_window_still_gets_a_border() { + let (left, right, bottom, border, radius) = (43., 53., 10., 1., 10.); + let shape = bottom_border_shape(left, right, bottom, border, radius).expect("a border shape"); + let mut pixmap = Pixmap::new((right + left) as u32, 54).expect("a pixmap"); + pixmap + .as_mut() + .fill_path(&shape, &ColorTheme::light().active.border_paint(), FillRule::EvenOdd, Transform::identity(), None); + assert_border(&pixmap, (left as u32 + right as u32) / 2, 10, 250, "the narrow window's band"); + // Degenerate shapes draw nothing rather than panicking. + assert!(bottom_border_shape(43., 43., 10., 1., 10.).is_none(), "no width, no shape"); + assert!(bottom_border_shape(43., 53., 10., 0., 10.).is_none(), "no border, no shape"); + assert!(bottom_border_shape(f32::NAN, 53., 10., 1., 10.).is_none(), "not a number, no shape"); +} + +/// The side and bottom parts composited as the compositor stacks them (left and right below the +/// bottom one), over a window `width` points wide and `height` tall, with `state`. The canvas is in +/// window coordinates: its top left is the window's `(-BORDER_SIZE, -HEADER_SIZE)`, and every part +/// sits at its `surface_rect`. +fn composite(width: u32, height: u32, state: WindowState) -> Pixmap { + let mut canvas = Pixmap::new(width + 2 * BORDER_SIZE, height + HEADER_SIZE + BORDER_SIZE).expect("a canvas"); + let colors = ColorTheme::light().active; + let mut shadow = Default::default(); + let parts: [(bool, (u32, u32), (i32, i32), usize); 3] = [ + (false, (BORDER_SIZE, height + HEADER_SIZE), (-(BORDER_SIZE as i32), -(HEADER_SIZE as i32)), DecorationParts::LEFT), + (true, (BORDER_SIZE, height + HEADER_SIZE), (width as i32, -(HEADER_SIZE as i32)), DecorationParts::RIGHT), + (false, (width + 2 * BORDER_SIZE, BORDER_SIZE + CORNER_RADIUS), (-(BORDER_SIZE as i32), height as i32 - CORNER_RADIUS as i32), DecorationParts::BOTTOM), + ]; + for (right, size, at, part) in parts { + let mut pixmap = Pixmap::new(size.0, size.1).expect("a part"); + match part { + DecorationParts::BOTTOM => draw_bottom(&mut pixmap.as_mut(), &mut shadow, &colors, &state, 1, size.0), + _ => draw_side(&mut pixmap.as_mut(), &mut shadow, &colors, &state, 1, right), + } + let (x, y) = (at.0 - (-(BORDER_SIZE as i32)), at.1 - (-(HEADER_SIZE as i32))); + canvas + .as_mut() + .draw_pixmap(x, y, pixmap.as_ref(), &PixmapPaint::default(), Transform::identity(), None); + } + canvas +} + +/// A pixel's alpha in window coordinates, from a canvas `composite` drew. +fn window_alpha(canvas: &Pixmap, (x, y): (i32, i32)) -> u8 { + let cx = (x + BORDER_SIZE as i32) as u32; + let cy = (y + HEADER_SIZE as i32) as u32; + alpha(canvas, cx, cy) +} + +/// Whether `(x, y)` in window coordinates is inside one of the two corner squares the bottom +/// corners round: `x` in `[-1, r]` or `[width - r, width + 1]`, `y` in `[height - r, height]`. +fn in_corner_square(width: u32, height: u32, (x, y): (i32, i32)) -> bool { + let r = CONTENT_CORNER_RADIUS as i32; + let (width, height) = (width as i32, height as i32); + y >= height - r && y <= height && (x >= -1 && x <= r || x >= width - r && x <= width + 1) +} + +/// Beside the bottom corners the composite is a square frame's: the side parts already draw the +/// shadow down to the window's edge, and the bottom part adds nothing over it. +#[test] +fn the_side_and_bottom_parts_composite_like_a_square_frame() { + let (width, height) = (200, 120); + let round = composite(width, height, WindowState::empty()); + let square = composite(width, height, WindowState::MAXIMIZED); + let mut compared = 0; + let mut worst = (0, (0, 0), 0, 0); + for cy in 0..round.height() { + for cx in 0..round.width() { + let at = (cx as i32 - BORDER_SIZE as i32, cy as i32 - HEADER_SIZE as i32); + let (x, y) = at; + // Outside the content rect, and not in a corner square, where the arcs' ring and the + // shadow's crescents are the intended difference. + let outside = x < 0 || x >= width as i32 || y < 0 || y >= height as i32; + if !outside || in_corner_square(width, height, at) { + continue; + } + let (rounded, squared) = (alpha(&round, cx, cy), alpha(&square, cx, cy)); + let off = rounded.abs_diff(squared); + if off > worst.0 { + worst = (off, at, rounded, squared); + } + compared += 1; + } + } + let (off, at, rounded, squared) = worst; + assert!( + off <= 2, + "the worst pixel is {at:?}: round corners composite {rounded}, the square frame {squared}", + ); + assert!(compared > 10_000, "the whole frame around the content was compared ({compared})"); +} + +/// The crescent the bottom part adds inside a corner square meets its neighbours without a step: +/// the shadow on the other side of the window's edge (the side part's own, which a square frame +/// draws) and the straight band just below the edge carry the same shadow at those distances. The +/// bound is the shadow's own gradient over a pixel — a hole (0 against ~29) or a doubled copy +/// (~58) is far past it. +#[test] +fn the_crescent_continues_the_shadow_around_it() { + let (width, height) = (200, 120); + let canvas = composite(width, height, WindowState::empty()); + for corner in [(0, height as i32 - 1), (width as i32 - 1, height as i32 - 1)] { + let crescent = window_alpha(&canvas, corner); + assert!(crescent > 0, "{corner:?}: the crescent keeps its shadow"); + // Outward, across the window's side edge, and down, across its bottom edge. + let outward = if corner.0 == 0 { (-1, corner.1) } else { (width as i32, corner.1) }; + let below = (corner.0, height as i32); + for neighbour in [outward, below] { + let other = window_alpha(&canvas, neighbour); + assert!( + crescent.abs_diff(other) <= 8, + "{corner:?} has {crescent}, its neighbour {neighbour:?} {other}", + ); + } + } +} + +/// The straight bands' shadow is the frame's own shadow model, which no patch touched: the +/// composite tests above compare their rounded frame against a square one drawn by the same code, +/// and this pins that reference to the model itself. +#[test] +fn the_straight_bands_shadow_is_the_shadow_model() { + let (width, height) = (200, 120); + let square = composite(width, height, WindowState::MAXIMIZED); + for dy in [1, 3, 8, 20] { + let y = height as i32 + dy; + let want = (crate::shadow::shadow(dy as f32 - 0.5, 1, false) * 255.).round() as u8; + let got = window_alpha(&square, (100, y)); + assert!(got.abs_diff(want) <= 2, "y {y}: the band draws {got}, the model says {want}"); + } + // The rounded frame's own band, at the same depths, is the same. + let round = composite(width, height, WindowState::empty()); + for dy in [1, 3, 8, 20] { + let y = height as i32 + dy; + assert_eq!(window_alpha(&round, (100, y)), window_alpha(&square, (100, y)), "y {y}"); + } +} diff --git a/app/vendor/rune/vendor/sctk-adwaita/src/theme.rs b/app/vendor/rune/vendor/sctk-adwaita/src/theme.rs new file mode 100644 index 0000000..8feeddf --- /dev/null +++ b/app/vendor/rune/vendor/sctk-adwaita/src/theme.rs @@ -0,0 +1,139 @@ +pub use tiny_skia::Color; +use tiny_skia::{Paint, Shader}; + +// https://gitlab.gnome.org/GNOME/gtk/-/blob/1bf88f1d81043fd99740e2f91e56ade7ede7303b/gtk/gtkwindow.c#L165 +pub(crate) const RESIZE_HANDLE_SIZE: u32 = 12; +// https://gitlab.gnome.org/GNOME/gtk/-/blob/1bf88f1d81043fd99740e2f91e56ade7ede7303b/gtk/gtkwindow.c#L166 +pub(crate) const RESIZE_HANDLE_CORNER_SIZE: u32 = 24; +pub(crate) const BORDER_SIZE: u32 = crate::shadow::SHADOW_SIZE + VISIBLE_BORDER_SIZE; +pub(crate) const HEADER_SIZE: u32 = 35; +pub(crate) const CORNER_RADIUS: u32 = 10; +pub(crate) const VISIBLE_BORDER_SIZE: u32 = 1; + +/// The color theme to use with the decorations frame. +#[derive(Debug, Clone)] +pub struct ColorTheme { + pub active: ColorMap, + pub inactive: ColorMap, +} + +impl ColorTheme { + /// Automatically choose between light & dark themes based on: + /// * dbus org.freedesktop.portal.Settings + /// <https://flatpak.github.io/xdg-desktop-portal/#gdbus-interface-org-freedesktop-portal-Settings> + pub fn auto() -> Self { + match crate::config::prefer_dark() { + true => Self::dark(), + false => Self::light(), + } + } + + /// Predefined light variant, which aims to replecate Adwaita theme. + pub fn light() -> Self { + Self { + active: ColorMap { + headerbar: Color::from_rgba8(235, 235, 235, 255), + button_idle: Color::from_rgba8(216, 216, 216, 255), + button_hover: Color::from_rgba8(207, 207, 207, 255), + button_icon: Color::from_rgba8(42, 42, 42, 255), + border_color: Color::from_rgba8(220, 220, 220, 255), + font_color: Color::from_rgba8(47, 47, 47, 255), + }, + inactive: ColorMap { + headerbar: Color::from_rgba8(250, 250, 250, 255), + button_idle: Color::from_rgba8(240, 240, 240, 255), + button_hover: Color::from_rgba8(216, 216, 216, 255), + button_icon: Color::from_rgba8(148, 148, 148, 255), + border_color: Color::from_rgba8(220, 220, 220, 255), + font_color: Color::from_rgba8(150, 150, 150, 255), + }, + } + } + + /// Predefined dark variant, which aims to replecate Adwaita-dark theme. + pub fn dark() -> Self { + Self { + active: ColorMap { + headerbar: Color::from_rgba8(48, 48, 48, 255), + button_idle: Color::from_rgba8(69, 69, 69, 255), + button_hover: Color::from_rgba8(79, 79, 79, 255), + button_icon: Color::from_rgba8(255, 255, 255, 255), + border_color: Color::from_rgba8(58, 58, 58, 255), + font_color: Color::from_rgba8(255, 255, 255, 255), + }, + inactive: ColorMap { + headerbar: Color::from_rgba8(36, 36, 36, 255), + button_idle: Color::from_rgba8(47, 47, 47, 255), + button_hover: Color::from_rgba8(57, 57, 57, 255), + button_icon: Color::from_rgba8(144, 144, 144, 255), + border_color: Color::from_rgba8(58, 58, 58, 255), + font_color: Color::from_rgba8(144, 144, 144, 255), + }, + } + } + + pub(crate) fn for_state(&self, active: bool) -> &ColorMap { + if active { + &self.active + } else { + &self.inactive + } + } +} + +impl Default for ColorTheme { + fn default() -> Self { + Self::auto() + } +} + +/// The color map for various decorcation parts. +#[derive(Debug, Clone)] +pub struct ColorMap { + pub headerbar: Color, + pub button_idle: Color, + pub button_hover: Color, + pub button_icon: Color, + pub border_color: Color, + pub font_color: Color, +} + +impl ColorMap { + pub(crate) fn headerbar_paint(&self) -> Paint { + Paint { + shader: Shader::SolidColor(self.headerbar), + anti_alias: true, + ..Default::default() + } + } + + pub(crate) fn button_idle_paint(&self) -> Paint { + Paint { + shader: Shader::SolidColor(self.button_idle), + anti_alias: true, + ..Default::default() + } + } + + pub(crate) fn button_hover_paint(&self) -> Paint { + Paint { + shader: Shader::SolidColor(self.button_hover), + anti_alias: true, + ..Default::default() + } + } + + pub(crate) fn button_icon_paint(&self) -> Paint { + Paint { + shader: Shader::SolidColor(self.button_icon), + ..Default::default() + } + } + + pub(crate) fn border_paint(&self) -> Paint { + Paint { + shader: Shader::SolidColor(self.border_color), + ..Default::default() + } + } +} diff --git a/app/vendor/rune/vendor/sctk-adwaita/src/title.rs b/app/vendor/rune/vendor/sctk-adwaita/src/title.rs new file mode 100644 index 0000000..1067f65 --- /dev/null +++ b/app/vendor/rune/vendor/sctk-adwaita/src/title.rs @@ -0,0 +1,61 @@ +use tiny_skia::{Color, Pixmap}; + +#[cfg(any(feature = "crossfont", feature = "ab_glyph"))] +mod config; +#[cfg(any(feature = "crossfont", feature = "ab_glyph"))] +mod font_preference; + +#[cfg(feature = "crossfont")] +mod crossfont_renderer; + +#[cfg(all(not(feature = "crossfont"), feature = "ab_glyph"))] +mod ab_glyph_renderer; + +#[cfg(all(not(feature = "crossfont"), not(feature = "ab_glyph")))] +mod dumb; + +#[derive(Debug)] +pub struct TitleText { + #[cfg(feature = "crossfont")] + imp: crossfont_renderer::CrossfontTitleText, + #[cfg(all(not(feature = "crossfont"), feature = "ab_glyph"))] + imp: ab_glyph_renderer::AbGlyphTitleText, + #[cfg(all(not(feature = "crossfont"), not(feature = "ab_glyph")))] + imp: dumb::DumbTitleText, +} + +impl TitleText { + pub fn new(color: Color) -> Option<Self> { + #[cfg(feature = "crossfont")] + return crossfont_renderer::CrossfontTitleText::new(color) + .ok() + .map(|imp| Self { imp }); + + #[cfg(all(not(feature = "crossfont"), feature = "ab_glyph"))] + return Some(Self { + imp: ab_glyph_renderer::AbGlyphTitleText::new(color), + }); + + #[cfg(all(not(feature = "crossfont"), not(feature = "ab_glyph")))] + { + let _ = color; + return None; + } + } + + pub fn update_scale(&mut self, scale: u32) { + self.imp.update_scale(scale) + } + + pub fn update_title(&mut self, title: impl Into<String>) { + self.imp.update_title(title) + } + + pub fn update_color(&mut self, color: Color) { + self.imp.update_color(color) + } + + pub fn pixmap(&self) -> Option<&Pixmap> { + self.imp.pixmap() + } +} diff --git a/app/vendor/rune/vendor/sctk-adwaita/src/title/Cantarell-Regular.ttf b/app/vendor/rune/vendor/sctk-adwaita/src/title/Cantarell-Regular.ttf new file mode 100644 index 0000000..0d4fd9a Binary files /dev/null and b/app/vendor/rune/vendor/sctk-adwaita/src/title/Cantarell-Regular.ttf differ diff --git a/app/vendor/rune/vendor/sctk-adwaita/src/title/ab_glyph_renderer.rs b/app/vendor/rune/vendor/sctk-adwaita/src/title/ab_glyph_renderer.rs new file mode 100644 index 0000000..d8f817f --- /dev/null +++ b/app/vendor/rune/vendor/sctk-adwaita/src/title/ab_glyph_renderer.rs @@ -0,0 +1,199 @@ +//! Title renderer using ab_glyph. +//! +//! Requires no dynamically linked dependencies. +//! +//! Can fallback to a embedded Cantarell-Regular.ttf font (SIL Open Font Licence v1.1) +//! if the system font doesn't work. +use crate::title::{config, font_preference::FontPreference}; +use ab_glyph::{point, Font, FontRef, Glyph, PxScale, PxScaleFont, ScaleFont, VariableFont}; +use std::{fs::File, process::Command}; +use tiny_skia::{Color, Pixmap, PremultipliedColorU8}; + +const CANTARELL: &[u8] = include_bytes!("Cantarell-Regular.ttf"); + +#[derive(Debug)] +pub struct AbGlyphTitleText { + title: String, + font: Option<(memmap2::Mmap, FontPreference)>, + original_px_size: f32, + size: PxScale, + color: Color, + pixmap: Option<Pixmap>, +} + +impl AbGlyphTitleText { + pub fn new(color: Color) -> Self { + let font_pref = config::titlebar_font().unwrap_or_default(); + let font_pref_pt_size = font_pref.pt_size; + let font = font_file_matching(&font_pref) + .and_then(|f| mmap(&f)) + .map(|mmap| (mmap, font_pref)); + + let size = parse_font(&font) + .pt_to_px_scale(font_pref_pt_size) + .unwrap_or_else(|| { + log::error!("invalid font units_per_em"); + PxScale { x: 17.6, y: 17.6 } + }); + + Self { + title: <_>::default(), + font, + original_px_size: size.x, + size, + color, + pixmap: None, + } + } + + pub fn update_scale(&mut self, scale: u32) { + let new_scale = PxScale::from(self.original_px_size * scale as f32); + if (self.size.x - new_scale.x).abs() > f32::EPSILON { + self.size = new_scale; + self.pixmap = self.render(); + } + } + + pub fn update_title(&mut self, title: impl Into<String>) { + let new_title = title.into(); + if new_title != self.title { + self.title = new_title; + self.pixmap = self.render(); + } + } + + pub fn update_color(&mut self, color: Color) { + if color != self.color { + self.color = color; + self.pixmap = self.render(); + } + } + + pub fn pixmap(&self) -> Option<&Pixmap> { + self.pixmap.as_ref() + } + + /// Render returning the new `Pixmap`. + fn render(&self) -> Option<Pixmap> { + let font = parse_font(&self.font); + let font = font.as_scaled(self.size); + + let glyphs = self.layout(&font); + let last_glyph = glyphs.last()?; + // + 2 because ab_glyph likes to draw outside of its area, + // so we add 1px border around the pixmap + let width = (last_glyph.position.x + font.h_advance(last_glyph.id)).ceil() as u32 + 2; + let height = font.height().ceil() as u32 + 2; + + let mut pixmap = Pixmap::new(width, height)?; + + let pixels = pixmap.pixels_mut(); + + for glyph in glyphs { + if let Some(outline) = font.outline_glyph(glyph) { + let bounds = outline.px_bounds(); + let left = bounds.min.x as u32; + let top = bounds.min.y as u32; + outline.draw(|x, y, c| { + // `ab_glyph` may return values greater than 1.0, but they are defined to be + // same as 1.0. For our purposes, we need to constrain this value. + let c = c.min(1.0); + + // offset the index by 1, so it is in the center of the pixmap + let p_idx = (top + y + 1) * width + (left + x + 1); + let Some(pixel) = pixels.get_mut(p_idx as usize) else { + log::warn!("Ignoring out of range pixel (pixel id: {p_idx}"); + return; + }; + + let old_alpha_u8 = pixel.alpha(); + + let new_alpha = c + (old_alpha_u8 as f32 / 255.0); + if let Some(px) = PremultipliedColorU8::from_rgba( + (self.color.red() * new_alpha * 255.0) as _, + (self.color.green() * new_alpha * 255.0) as _, + (self.color.blue() * new_alpha * 255.0) as _, + (new_alpha * 255.0) as _, + ) { + *pixel = px; + } + }) + } + } + + Some(pixmap) + } + + /// Simple single-line glyph layout. + fn layout(&self, font: &PxScaleFont<impl Font>) -> Vec<Glyph> { + let mut caret = point(0.0, font.ascent()); + let mut last_glyph: Option<Glyph> = None; + let mut target = Vec::new(); + for c in self.title.chars() { + if c.is_control() { + continue; + } + let mut glyph = font.scaled_glyph(c); + if let Some(previous) = last_glyph.take() { + caret.x += font.kern(previous.id, glyph.id); + } + glyph.position = caret; + + last_glyph = Some(glyph.clone()); + caret.x += font.h_advance(glyph.id); + + target.push(glyph); + } + target + } +} + +/// Parse the memmapped system font or fallback to built-in cantarell. +fn parse_font(sys_font: &Option<(memmap2::Mmap, FontPreference)>) -> FontRef<'_> { + match sys_font { + Some((mmap, font_pref)) => { + FontRef::try_from_slice(mmap) + .map(|mut f| { + // basic "bold" handling for variable fonts + if font_pref + .style + .as_deref() + .map_or(false, |s| s.eq_ignore_ascii_case("bold")) + { + f.set_variation(b"wght", 700.0); + } + f + }) + .unwrap_or_else(|_| { + // We control the default font, so I guess it's fine to unwrap it + #[allow(clippy::unwrap_used)] + FontRef::try_from_slice(CANTARELL).unwrap() + }) + } + // We control the default font, so I guess it's fine to unwrap it + #[allow(clippy::unwrap_used)] + _ => FontRef::try_from_slice(CANTARELL).unwrap(), + } +} + +/// Font-config without dynamically linked dependencies +fn font_file_matching(pref: &FontPreference) -> Option<File> { + let mut pattern = pref.name.clone(); + if let Some(style) = &pref.style { + pattern.push(':'); + pattern.push_str(style); + } + Command::new("fc-match") + .arg("-f") + .arg("%{file}") + .arg(&pattern) + .output() + .ok() + .and_then(|out| String::from_utf8(out.stdout).ok()) + .and_then(|path| File::open(path.trim()).ok()) +} + +fn mmap(file: &File) -> Option<memmap2::Mmap> { + // Safety: System font files are not expected to be mutated during use + unsafe { memmap2::Mmap::map(file).ok() } +} diff --git a/app/vendor/rune/vendor/sctk-adwaita/src/title/config.rs b/app/vendor/rune/vendor/sctk-adwaita/src/title/config.rs new file mode 100644 index 0000000..70541d3 --- /dev/null +++ b/app/vendor/rune/vendor/sctk-adwaita/src/title/config.rs @@ -0,0 +1,20 @@ +//! System font configuration. +use crate::title::font_preference::FontPreference; +use std::process::Command; + +/// Query system for which font to use for window titles. +pub(crate) fn titlebar_font() -> Option<FontPreference> { + // outputs something like: `'Cantarell Bold 12'` + let stdout = Command::new("gsettings") + .args(["get", "org.gnome.desktop.wm.preferences", "titlebar-font"]) + .output() + .ok() + .and_then(|out| String::from_utf8(out.stdout).ok())?; + + FontPreference::from_name_style_size( + stdout + .trim() + .trim_end_matches('\'') + .trim_start_matches('\''), + ) +} diff --git a/app/vendor/rune/vendor/sctk-adwaita/src/title/crossfont_renderer.rs b/app/vendor/rune/vendor/sctk-adwaita/src/title/crossfont_renderer.rs new file mode 100644 index 0000000..18ce6b5 --- /dev/null +++ b/app/vendor/rune/vendor/sctk-adwaita/src/title/crossfont_renderer.rs @@ -0,0 +1,227 @@ +use std::mem; + +use crossfont::{GlyphKey, Rasterize, RasterizedGlyph}; +use tiny_skia::{Color, Pixmap, PixmapPaint, PixmapRef, Transform}; + +use crate::title::config; + +pub struct CrossfontTitleText { + title: String, + + font_desc: crossfont::FontDesc, + font_key: crossfont::FontKey, + size: crossfont::Size, + scale: u32, + metrics: crossfont::Metrics, + rasterizer: crossfont::Rasterizer, + color: Color, + + pixmap: Option<Pixmap>, +} + +impl std::fmt::Debug for CrossfontTitleText { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("TitleText") + .field("title", &self.title) + .field("font_desc", &self.font_desc) + .field("font_key", &self.font_key) + .field("size", &self.size) + .field("scale", &self.scale) + .field("pixmap", &self.pixmap) + .finish() + } +} + +impl CrossfontTitleText { + pub fn new(color: Color) -> Result<Self, crossfont::Error> { + let title = "".into(); + + let font_pref = config::titlebar_font().unwrap_or_default(); + let font_style = font_pref + .style + .map(crossfont::Style::Specific) + .unwrap_or_else(|| crossfont::Style::Description { + slant: crossfont::Slant::Normal, + weight: crossfont::Weight::Normal, + }); + let font_desc = crossfont::FontDesc::new(&font_pref.name, font_style); + + let mut rasterizer = crossfont::Rasterizer::new()?; + let size = crossfont::Size::new(font_pref.pt_size); + let font_key = rasterizer.load_font(&font_desc, size)?; + + // Need to load at least one glyph for the face before calling metrics. + // The glyph requested here ('m' at the time of writing) has no special + // meaning. + rasterizer.get_glyph(GlyphKey { + font_key, + character: 'm', + size, + })?; + + let metrics = rasterizer.metrics(font_key, size)?; + + let mut this = Self { + pixmap: None, + rasterizer, + font_desc, + font_key, + scale: 1, + metrics, + title, + color, + size, + }; + + this.rerender(); + + Ok(this) + } + + fn update_metrics(&mut self) -> Result<(), crossfont::Error> { + self.rasterizer.get_glyph(GlyphKey { + font_key: self.font_key, + character: 'm', + size: self.size, + })?; + self.metrics = self.rasterizer.metrics(self.font_key, self.size)?; + Ok(()) + } + + pub fn update_scale(&mut self, scale: u32) { + let old_scale = mem::replace(&mut self.scale, scale); + if old_scale != self.scale { + self.size = self.size.scale(self.scale as f32 / old_scale as f32); + self.update_metrics().ok(); + self.rerender(); + } + } + + pub fn update_title<S: Into<String>>(&mut self, title: S) { + let title = title.into(); + if self.title != title { + self.title = title; + self.rerender(); + } + } + + pub fn update_color(&mut self, color: Color) { + if self.color != color { + self.color = color; + self.rerender(); + } + } + + fn rerender(&mut self) { + let glyphs: Vec<_> = self + .title + .chars() + .filter_map(|character| { + let key = GlyphKey { + character, + font_key: self.font_key, + size: self.size, + }; + + self.rasterizer + .get_glyph(key) + .map(|glyph| (key, glyph)) + .ok() + }) + .collect(); + + if glyphs.is_empty() { + self.pixmap = None; + return; + } + + let width = self.calc_width(&glyphs); + let height = self.metrics.line_height.round() as i32; + + let mut pixmap = if let Some(p) = Pixmap::new(width as u32, height as u32) { + p + } else { + self.pixmap = None; + return; + }; + // pixmap.fill(Color::from_rgba8(255, 0, 0, 55)); + + let mut caret = 0; + let mut last_glyph = None; + + for (key, glyph) in glyphs { + let mut buffer = Vec::with_capacity(glyph.width as usize * 4); + + let glyph_buffer = match &glyph.buffer { + crossfont::BitmapBuffer::Rgb(v) => v.chunks(3), + crossfont::BitmapBuffer::Rgba(v) => v.chunks(4), + }; + + for px in glyph_buffer { + let alpha = if let Some(alpha) = px.get(3) { + *alpha as f32 / 255.0 + } else { + let r = px[0] as f32 / 255.0; + let g = px[1] as f32 / 255.0; + let b = px[2] as f32 / 255.0; + (r + g + b) / 3.0 + }; + + let mut color = self.color; + color.set_alpha(alpha); + let color = color.premultiply().to_color_u8(); + + buffer.push(color.red()); + buffer.push(color.green()); + buffer.push(color.blue()); + buffer.push(color.alpha()); + } + + if let Some(last) = last_glyph { + let (x, _) = self.rasterizer.kerning(last, key); + caret += x as i32; + } + + if let Some(pixmap_glyph) = + PixmapRef::from_bytes(&buffer, glyph.width as _, glyph.height as _) + { + pixmap.draw_pixmap( + glyph.left + caret, + height - glyph.top + self.metrics.descent.round() as i32, + pixmap_glyph, + &PixmapPaint::default(), + Transform::identity(), + None, + ); + } + + caret += glyph.advance.0; + + last_glyph = Some(key); + } + + self.pixmap = Some(pixmap); + } + + pub fn pixmap(&self) -> Option<&Pixmap> { + self.pixmap.as_ref() + } + + fn calc_width(&mut self, glyphs: &[(GlyphKey, RasterizedGlyph)]) -> i32 { + let mut caret = 0; + let mut last_glyph: Option<&GlyphKey> = None; + + for (key, glyph) in glyphs.iter() { + if let Some(last) = last_glyph { + let (x, _) = self.rasterizer.kerning(*last, *key); + caret += x as i32; + } + + caret += glyph.advance.0; + + last_glyph = Some(key); + } + + caret + } +} diff --git a/app/vendor/rune/vendor/sctk-adwaita/src/title/dumb.rs b/app/vendor/rune/vendor/sctk-adwaita/src/title/dumb.rs new file mode 100644 index 0000000..b6c1d42 --- /dev/null +++ b/app/vendor/rune/vendor/sctk-adwaita/src/title/dumb.rs @@ -0,0 +1,16 @@ +use tiny_skia::{Color, Pixmap}; + +#[derive(Debug)] +pub struct DumbTitleText {} + +impl DumbTitleText { + pub fn update_scale(&mut self, _scale: u32) {} + + pub fn update_title<S: Into<String>>(&mut self, _title: S) {} + + pub fn update_color(&mut self, _color: Color) {} + + pub fn pixmap(&self) -> Option<&Pixmap> { + None + } +} diff --git a/app/vendor/rune/vendor/sctk-adwaita/src/title/font_preference.rs b/app/vendor/rune/vendor/sctk-adwaita/src/title/font_preference.rs new file mode 100644 index 0000000..beb6df7 --- /dev/null +++ b/app/vendor/rune/vendor/sctk-adwaita/src/title/font_preference.rs @@ -0,0 +1,91 @@ +#[derive(Debug)] +pub(crate) struct FontPreference { + pub name: String, + pub style: Option<String>, + pub pt_size: f32, +} + +impl Default for FontPreference { + fn default() -> Self { + Self { + name: "sans-serif".into(), + style: None, + pt_size: 10.0, + } + } +} + +impl FontPreference { + /// Parse config string like `Cantarell 12`, `Cantarell Bold 11`, `Noto Serif CJK HK Bold 12`. + pub fn from_name_style_size(conf: &str) -> Option<Self> { + // assume last is size, 2nd last is style and the rest is name. + match conf.rsplit_once(' ') { + Some((head, tail)) if tail.chars().all(|c| c.is_numeric()) => { + let pt_size: f32 = tail.parse().unwrap_or(10.0); + match head.rsplit_once(' ') { + Some((name, style)) if !name.is_empty() => Some(Self { + name: name.into(), + style: Some(style.into()), + pt_size, + }), + None if !head.is_empty() => Some(Self { + name: head.into(), + style: None, + pt_size, + }), + _ => None, + } + } + Some((head, tail)) if !head.is_empty() => Some(Self { + name: head.into(), + style: Some(tail.into()), + pt_size: 10.0, + }), + None if !conf.is_empty() => Some(Self { + name: conf.into(), + style: None, + pt_size: 10.0, + }), + _ => None, + } + } +} + +#[test] +fn pref_from_multi_name_variant_size() { + let pref = FontPreference::from_name_style_size("Noto Serif CJK HK Bold 12").unwrap(); + assert_eq!(pref.name, "Noto Serif CJK HK"); + assert_eq!(pref.style, Some("Bold".into())); + assert!((pref.pt_size - 12.0).abs() < f32::EPSILON); +} + +#[test] +fn pref_from_name_variant_size() { + let pref = FontPreference::from_name_style_size("Cantarell Bold 12").unwrap(); + assert_eq!(pref.name, "Cantarell"); + assert_eq!(pref.style, Some("Bold".into())); + assert!((pref.pt_size - 12.0).abs() < f32::EPSILON); +} + +#[test] +fn pref_from_name_size() { + let pref = FontPreference::from_name_style_size("Cantarell 12").unwrap(); + assert_eq!(pref.name, "Cantarell"); + assert_eq!(pref.style, None); + assert!((pref.pt_size - 12.0).abs() < f32::EPSILON); +} + +#[test] +fn pref_from_name() { + let pref = FontPreference::from_name_style_size("Cantarell").unwrap(); + assert_eq!(pref.name, "Cantarell"); + assert_eq!(pref.style, None); + assert!((pref.pt_size - 10.0).abs() < f32::EPSILON); +} +#[test] +fn pref_from_multi_name_style() { + let pref = FontPreference::from_name_style_size("Foo Bar Baz Bold").unwrap(); + assert_eq!(pref.name, "Foo Bar Baz"); + assert_eq!(pref.style, Some("Bold".into())); + assert!((pref.pt_size - 10.0).abs() < f32::EPSILON); +} diff --git a/app/vendor/rune/vendor/sctk-adwaita/src/wl_typed.rs b/app/vendor/rune/vendor/sctk-adwaita/src/wl_typed.rs new file mode 100644 index 0000000..26b6c11 --- /dev/null +++ b/app/vendor/rune/vendor/sctk-adwaita/src/wl_typed.rs @@ -0,0 +1,52 @@ +use std::{marker::PhantomData, ops::Deref}; + +use smithay_client_toolkit::reexports::client::{Dispatch, Proxy}; + +#[derive(Debug)] +pub struct WlTyped<I, DATA>(I, PhantomData<DATA>); + +impl<I, DATA> WlTyped<I, DATA> +where + I: Proxy, + DATA: Send + Sync + 'static, +{ + #[allow(clippy::extra_unused_type_parameters)] + pub fn wrap<STATE>(i: I) -> Self + where + STATE: Dispatch<I, DATA>, + { + Self(i, PhantomData) + } + + pub fn inner(&self) -> &I { + &self.0 + } + + #[allow(dead_code)] + pub fn data(&self) -> &DATA { + // Generic on Self::wrap makes sure that this will never panic + #[allow(clippy::unwrap_used)] + self.0.data().unwrap() + } +} + +impl<I: Clone, D> Clone for WlTyped<I, D> { + fn clone(&self) -> Self { + Self(self.0.clone(), PhantomData) + } +} + +impl<I, D> Deref for WlTyped<I, D> { + type Target = I; + + fn deref(&self) -> &Self::Target { + &self.0 + } +} + +impl<I: PartialEq, D> PartialEq for WlTyped<I, D> { + fn eq(&self, other: &Self) -> bool { + self.0 == other.0 + } +} +impl<I: Eq, D> Eq for WlTyped<I, D> {} diff --git a/app/vendor/rune/vendor/tiny-skia-path.patch b/app/vendor/rune/vendor/tiny-skia-path.patch new file mode 100644 index 0000000..216df4a --- /dev/null +++ b/app/vendor/rune/vendor/tiny-skia-path.patch @@ -0,0 +1,671 @@ +diff --git a/src/dash.rs b/src/dash.rs +index e648ad9..863db27 100644 +--- a/src/dash.rs ++++ b/src/dash.rs +@@ -296,7 +296,8 @@ impl Iterator for ContourMeasureIter<'_> { + + prev_p = p0; + } +- PathSegment::QuadTo(p0, p1) => { ++ // Dashing measures a conic as the quad through its control point. ++ PathSegment::QuadTo(p0, p1) | PathSegment::ConicTo(p0, p1, _) => { + let prev_d = distance; + distance = contour.compute_quad_segs( + prev_p, +diff --git a/src/lib.rs b/src/lib.rs +index e80a70c..41700ba 100644 +--- a/src/lib.rs ++++ b/src/lib.rs +@@ -248,8 +248,9 @@ fn set_point_length( + let yy = y as f64; + let dmag = (xx * xx + yy * yy).sqrt(); + let dscale = length as f64 / dmag; +- x *= dscale as f32; +- y *= dscale as f32; ++ // As Skia's `set_point_length`: the float times the double, rounded once. ++ x = (x as f64 * dscale) as f32; ++ y = (y as f64 * dscale) as f32; + + // check if we're not finite, or we're zero-length + if !x.is_finite() || !y.is_finite() || (x == 0.0 && y == 0.0) { +diff --git a/src/path.rs b/src/path.rs +index a72d06d..89695d9 100644 +--- a/src/path.rs ++++ b/src/path.rs +@@ -21,6 +21,8 @@ pub enum PathVerb { + Line, + Quad, + Cubic, ++ /// Only in a path built with `PathBuilder::set_keep_conics`. ++ Conic, + Close, + } + +@@ -49,6 +51,8 @@ pub enum PathVerb { + pub struct Path { + pub(crate) verbs: Vec<PathVerb>, + pub(crate) points: Vec<Point>, ++ /// Each conic's weight, in order. ++ pub(crate) weights: Vec<f32>, + pub(crate) bounds: Rect, + } + +@@ -92,7 +96,7 @@ impl Path { + extremas[0] = p; + count = 1; + } +- PathSegment::QuadTo(p0, p1) => { ++ PathSegment::QuadTo(p0, p1) | PathSegment::ConicTo(p0, p1, _) => { + count = compute_quad_extremas(last_point, p0, p1, &mut extremas); + } + PathSegment::CubicTo(p0, p1, p2) => { +@@ -123,6 +127,11 @@ impl Path { + &self.points + } + ++ /// Returns each conic's weight, in order. ++ pub fn weights(&self) -> &[f32] { ++ &self.weights ++ } ++ + /// Returns a transformed in-place path. + /// + /// Some points may become NaN/inf therefore this method can fail. +@@ -145,6 +154,7 @@ impl Path { + path: self, + verb_index: 0, + points_index: 0, ++ weight_index: 0, + is_auto_close: false, + last_move_to: Point::zero(), + last_point: Point::zero(), +@@ -159,8 +169,11 @@ impl Path { + PathBuilder { + verbs: self.verbs, + points: self.points, ++ weights: alloc::vec::Vec::new(), ++ keep_conics: false, + last_move_to_index: 0, + move_to_required: true, ++ conic_tolerance: 0.0, + } + } + } +@@ -181,6 +194,10 @@ impl core::fmt::Debug for Path { + "C {} {} {} {} {} {} ", + p0.x, p0.y, p1.x, p1.y, p2.x, p2.y + ))?, ++ PathSegment::ConicTo(p0, p1, w) => s.write_fmt(format_args!( ++ "K {} {} {} {} {} ", ++ p0.x, p0.y, p1.x, p1.y, w ++ ))?, + PathSegment::Close => s.write_fmt(format_args!("Z "))?, + } + } +@@ -249,6 +266,8 @@ pub enum PathSegment { + LineTo(Point), + QuadTo(Point, Point), + CubicTo(Point, Point, Point), ++ /// A conic's control point, end and weight. ++ ConicTo(Point, Point, f32), + Close, + } + +@@ -259,6 +278,7 @@ pub struct PathSegmentsIter<'a> { + path: &'a Path, + verb_index: usize, + points_index: usize, ++ weight_index: usize, + + is_auto_close: bool, + last_move_to: Point, +@@ -297,7 +317,7 @@ impl<'a> PathSegmentsIter<'a> { + + return true; + } +- PathSegment::QuadTo(p1, p2) => { ++ PathSegment::QuadTo(p1, p2) | PathSegment::ConicTo(p1, p2, _) => { + if iter.last_point == p1 && iter.last_point == p2 { + continue; + } +@@ -368,6 +388,16 @@ impl<'a> Iterator for PathSegmentsIter<'a> { + self.last_point, + )) + } ++ PathVerb::Conic => { ++ self.points_index += 2; ++ self.weight_index += 1; ++ self.last_point = self.path.points[self.points_index - 1]; ++ Some(PathSegment::ConicTo( ++ self.path.points[self.points_index - 2], ++ self.last_point, ++ self.path.weights[self.weight_index - 1], ++ )) ++ } + PathVerb::Close => { + let seg = self.auto_close(); + self.last_point = self.last_move_to; +diff --git a/src/path_builder.rs b/src/path_builder.rs +index 275f528..619962f 100644 +--- a/src/path_builder.rs ++++ b/src/path_builder.rs +@@ -30,6 +30,13 @@ pub struct PathBuilder { + pub(crate) points: Vec<Point>, + pub(crate) last_move_to_index: usize, + pub(crate) move_to_required: bool, ++ /// How far, in this path's units, the quads a conic becomes may stray from it: Skia's 0.25 of ++ /// a device pixel. 0 (the default) is 0.25; a stroker sets its own from its resolution scale. ++ pub(crate) conic_tolerance: f32, ++ /// Each conic's weight, where `keep_conics` keeps them as conics. ++ pub(crate) weights: Vec<f32>, ++ /// Whether `conic_to` keeps a conic, as Skia's paths do, rather than cutting it into quads. ++ pub(crate) keep_conics: bool, + } + + impl PathBuilder { +@@ -40,6 +47,9 @@ impl PathBuilder { + points: Vec::new(), + last_move_to_index: 0, + move_to_required: true, ++ conic_tolerance: 0.0, ++ weights: Vec::new(), ++ keep_conics: false, + } + } + +@@ -58,6 +68,9 @@ impl PathBuilder { + points: Vec::with_capacity(points_capacity), + last_move_to_index: 0, + move_to_required: true, ++ conic_tolerance: 0.0, ++ weights: Vec::new(), ++ keep_conics: false, + } + } + +@@ -88,6 +101,7 @@ impl PathBuilder { + bounds: rect, + verbs, + points, ++ weights: Vec::new(), + } + } + +@@ -114,6 +128,18 @@ impl PathBuilder { + self.points.reserve(additional_points); + } + ++ /// Keeps each conic `conic_to` adds as a conic, as Skia's own paths do (the stroker then strokes ++ /// it as one), rather than cutting it into quads. ++ pub fn set_keep_conics(&mut self, keep: bool) { ++ self.keep_conics = keep; ++ } ++ ++ /// Sets how far, in this path's units, the quads each conic is turned into may stray from it ++ /// (Skia: 0.25 of a device pixel, so 0.25 over the scale the path will be drawn at). ++ pub fn set_conic_tolerance(&mut self, tolerance: f32) { ++ self.conic_tolerance = tolerance; ++ } ++ + /// Returns the current number of segments in the builder. + pub fn len(&self) -> usize { + self.verbs.len() +@@ -179,7 +205,7 @@ impl PathBuilder { + + // We do not support conic segments, but Skia still relies on them from time to time. + // This method will simply convert the input data into quad segments. +- pub(crate) fn conic_to(&mut self, x1: f32, y1: f32, x: f32, y: f32, weight: f32) { ++ pub fn conic_to(&mut self, x1: f32, y1: f32, x: f32, y: f32, weight: f32) { + // check for <= 0 or NaN with this test + if !(weight > 0.0) { + self.line_to(x, y); +@@ -188,15 +214,23 @@ impl PathBuilder { + self.line_to(x, y); + } else if weight == 1.0 { + self.quad_to(x1, y1, x, y); ++ } else if self.keep_conics { ++ self.inject_move_to_if_needed(); ++ self.verbs.push(PathVerb::Conic); ++ self.points.push(Point::from_xy(x1, y1)); ++ self.points.push(Point::from_xy(x, y)); ++ self.weights.push(weight); + } else { + self.inject_move_to_if_needed(); + + let last = self.last_point().unwrap(); ++ let tolerance = if self.conic_tolerance > 0.0 { self.conic_tolerance } else { 0.25 }; + let quadder = path_geometry::AutoConicToQuads::compute( + last, + Point::from_xy(x1, y1), + Point::from_xy(x, y), + weight, ++ tolerance, + ); + if let Some(quadder) = quadder { + // Points are ordered as: 0 - 1 2 - 3 4 - 5 6 - .. +@@ -341,6 +375,7 @@ impl PathBuilder { + + self.verbs.extend_from_slice(&other.verbs); + self.points.extend_from_slice(&other.points); ++ self.weights.extend_from_slice(&other.weights); + } + + pub(crate) fn push_path_builder(&mut self, other: &PathBuilder) { +@@ -354,6 +389,7 @@ impl PathBuilder { + + self.verbs.extend_from_slice(&other.verbs); + self.points.extend_from_slice(&other.points); ++ self.weights.extend_from_slice(&other.weights); + } + + /// Appends, in a reverse order, the first contour of path ignoring path's last point. +@@ -390,6 +426,13 @@ impl PathBuilder { + points_offset -= 3; + self.cubic_to(pt1.x, pt1.y, pt2.x, pt2.y, pt3.x, pt3.y); + } ++ PathVerb::Conic => { ++ // A stroker's own builders never keep conics. ++ let pt1 = other.points[points_offset - 1]; ++ let pt2 = other.points[points_offset - 2]; ++ points_offset -= 2; ++ self.quad_to(pt1.x, pt1.y, pt2.x, pt2.y); ++ } + PathVerb::Close => {} + } + } +@@ -401,6 +444,7 @@ impl PathBuilder { + pub fn clear(&mut self) { + self.verbs.clear(); + self.points.clear(); ++ self.weights.clear(); + self.last_move_to_index = 0; + self.move_to_required = true; + } +@@ -424,6 +468,7 @@ impl PathBuilder { + bounds, + verbs: self.verbs, + points: self.points, ++ weights: self.weights, + }) + } + } +diff --git a/src/path_geometry.rs b/src/path_geometry.rs +index 1bb631c..3132f5c 100644 +--- a/src/path_geometry.rs ++++ b/src/path_geometry.rs +@@ -629,9 +629,8 @@ impl Conic { + pow2 += 1; + } + +- // Unlike Skia, we always expect `pow2` to be at least 1. +- // Otherwise it produces ugly results. +- Some(pow2.max(1)) ++ // As Skia: a conic within the tolerance of its hull's quad is that one quad. ++ Some(pow2) + } + + // Chop this conic into N quads, stored continuously in pts[], where +@@ -865,15 +864,15 @@ fn between(a: f32, b: f32, c: f32) -> bool { + (a - b) * (c - b) <= 0.0 + } + +-pub(crate) struct AutoConicToQuads { ++pub struct AutoConicToQuads { + pub points: [Point; 64], + pub len: u8, // the number of quads + } + + impl AutoConicToQuads { +- pub fn compute(pt0: Point, pt1: Point, pt2: Point, weight: f32) -> Option<Self> { ++ pub fn compute(pt0: Point, pt1: Point, pt2: Point, weight: f32, tolerance: f32) -> Option<Self> { + let conic = Conic::new(pt0, pt1, pt2, weight); +- let pow2 = conic.compute_quad_pow2(0.25)?; ++ let pow2 = conic.compute_quad_pow2(tolerance)?; + let mut points = [Point::zero(); 64]; + let len = conic.chop_into_quads_pow2(pow2, &mut points); + Some(AutoConicToQuads { points, len }) +diff --git a/src/stroker.rs b/src/stroker.rs +index 6a6aa55..9ee46d3 100644 +--- a/src/stroker.rs ++++ b/src/stroker.rs +@@ -127,6 +127,7 @@ impl Default for LineJoin { + } + + const QUAD_RECURSIVE_LIMIT: usize = 3; ++const CONIC_RECURSIVE_LIMIT: usize = 2; + + // quads with extreme widths (e.g. (0,1) (1,6) (0,3) width=5e7) recurse to point of failure + // largest seen for normal cubics: 5, 26 +@@ -347,6 +348,11 @@ impl PathStroker { + // The '4' below matches the fill scan converter's error term. + self.inv_res_scale = (res_scale * 4.0).invert(); + self.inv_res_scale_squared = self.inv_res_scale.sqr(); ++ // Skia turns a conic into quads in device space, a quarter pixel from it at most; the ++ // outline here is in the path's own units, res_scale device pixels each. ++ self.inner.conic_tolerance = 0.25 / res_scale; ++ self.outer.conic_tolerance = 0.25 / res_scale; ++ self.cusper.conic_tolerance = 0.25 / res_scale; + + self.radius = width.get().half(); + self.inv_miter_limit = inv_miter_limit; +@@ -408,6 +414,10 @@ impl PathStroker { + self.cubic_to(p1, p2, p3); + last_segment_is_line = false; + } ++ PathSegment::ConicTo(p1, p2, w) => { ++ self.conic_to(p1, p2, w); ++ last_segment_is_line = false; ++ } + PathSegment::Close => { + if line_cap != LineCap::Butt { + // If the stroke consists of a moveTo followed by a close, treat it +@@ -551,6 +561,127 @@ impl PathStroker { + self.post_join_to(p2, normal_bc, unit_bc); + } + ++ // As Skia's `SkPathStroker::conicTo`: a conic stroked as itself, its outline quads fitted ++ // to the conic's own offsets. ++ fn conic_to(&mut self, p1: Point, p2: Point, weight: f32) { ++ let conic = [self.prev_pt, p1, p2]; ++ let (reduction, reduction_type) = check_conic_linear(&conic, weight); ++ if reduction_type == ReductionType::Point || reduction_type == ReductionType::Line { ++ self.line_to(p2, None); ++ return; ++ } ++ ++ if reduction_type == ReductionType::Degenerate { ++ self.line_to(reduction, None); ++ let save_joiner = self.joiner; ++ self.joiner = round_joiner; ++ self.line_to(p2, None); ++ self.joiner = save_joiner; ++ return; ++ } ++ ++ let mut normal_ab = Point::zero(); ++ let mut unit_ab = Point::zero(); ++ let mut normal_bc = Point::zero(); ++ let mut unit_bc = Point::zero(); ++ if !self.pre_join_to(p1, false, &mut normal_ab, &mut unit_ab) { ++ self.line_to(p2, None); ++ return; ++ } ++ ++ let mut quad_points = QuadConstruct::default(); ++ self.init_quad(StrokeType::Outer, NormalizedF32::ZERO, NormalizedF32::ONE, &mut quad_points); ++ self.conic_stroke(&conic, weight, &mut quad_points); ++ self.init_quad(StrokeType::Inner, NormalizedF32::ZERO, NormalizedF32::ONE, &mut quad_points); ++ self.conic_stroke(&conic, weight, &mut quad_points); ++ ++ let ok = set_normal_unit_normal(conic[1], conic[2], self.res_scale, self.radius, &mut normal_bc, &mut unit_bc); ++ if !ok { ++ normal_bc = normal_ab; ++ unit_bc = unit_ab; ++ } ++ ++ self.post_join_to(p2, normal_bc, unit_bc); ++ } ++ ++ fn conic_stroke(&mut self, conic: &[Point; 3], weight: f32, quad_points: &mut QuadConstruct) -> bool { ++ let result_type = self.compare_quad_conic(conic, weight, quad_points); ++ if result_type == ResultType::Quad { ++ let path = if self.stroke_type == StrokeType::Outer { &mut self.outer } else { &mut self.inner }; ++ path.quad_to(quad_points.quad[1].x, quad_points.quad[1].y, quad_points.quad[2].x, quad_points.quad[2].y); ++ return true; ++ } ++ ++ if result_type == ResultType::Degenerate { ++ self.add_degenerate_line(quad_points); ++ return true; ++ } ++ ++ if !quad_points.quad[2].x.is_finite() || !quad_points.quad[2].y.is_finite() { ++ return false; ++ } ++ ++ self.recursion_depth += 1; ++ if self.recursion_depth > RECURSIVE_LIMITS[CONIC_RECURSIVE_LIMIT] { ++ self.add_degenerate_line(quad_points); ++ self.recursion_depth -= 1; ++ return true; ++ } ++ ++ let mut half = QuadConstruct::default(); ++ if !half.init_with_start(quad_points) { ++ self.add_degenerate_line(quad_points); ++ self.recursion_depth -= 1; ++ return true; ++ } ++ if !self.conic_stroke(conic, weight, &mut half) { ++ return false; ++ } ++ ++ if !half.init_with_end(quad_points) { ++ self.add_degenerate_line(quad_points); ++ self.recursion_depth -= 1; ++ return true; ++ } ++ if !self.conic_stroke(conic, weight, &mut half) { ++ return false; ++ } ++ ++ self.recursion_depth -= 1; ++ true ++ } ++ ++ fn compare_quad_conic(&mut self, conic: &[Point; 3], weight: f32, quad_points: &mut QuadConstruct) -> ResultType { ++ if !quad_points.start_set { ++ let mut start = Point::zero(); ++ self.conic_perp_ray(conic, weight, quad_points.start_t, &mut start, &mut quad_points.quad[0], Some(&mut quad_points.tangent_start)); ++ quad_points.start_set = true; ++ } ++ if !quad_points.end_set { ++ let mut end = Point::zero(); ++ self.conic_perp_ray(conic, weight, quad_points.end_t, &mut end, &mut quad_points.quad[2], Some(&mut quad_points.tangent_end)); ++ quad_points.end_set = true; ++ } ++ ++ let result_type = self.intersect_ray(IntersectRayType::CtrlPt, quad_points); ++ if result_type != ResultType::Quad { ++ return result_type; ++ } ++ ++ let mut ray0 = Point::zero(); ++ let mut ray1 = Point::zero(); ++ self.conic_perp_ray(conic, weight, quad_points.mid_t, &mut ray1, &mut ray0, None); ++ self.stroke_close_enough(&quad_points.quad.clone(), &[ray0, ray1], quad_points) ++ } ++ ++ fn conic_perp_ray(&self, conic: &[Point; 3], weight: f32, t: NormalizedF32, tp: &mut Point, on_p: &mut Point, tangent: Option<&mut Point>) { ++ *tp = conic_eval(conic, weight, t.get()); ++ let mut dxy = conic_eval_tangent(conic, weight, t.get()); ++ if dxy.is_zero() { ++ dxy = conic[2] - conic[0]; ++ } ++ self.set_ray_points(*tp, &mut dxy, on_p, tangent); ++ } + fn cubic_to(&mut self, pt1: Point, pt2: Point, pt3: Point) { + let cubic = [self.prev_pt, pt1, pt2, pt3]; + let mut reduction = [Point::zero(); 3]; +@@ -677,7 +808,10 @@ impl PathStroker { + + self.recursion_depth += 1; + if self.recursion_depth > RECURSIVE_LIMITS[self.found_tangents as usize] { +- return false; // just abort if projected quad isn't representable ++ // As Skia now does: when it stops making progress, a line, and on. ++ self.add_degenerate_line(quad_points); ++ self.recursion_depth -= 1; ++ return true; + } + + let mut half = QuadConstruct::default(); +@@ -1019,18 +1153,33 @@ impl PathStroker { + return true; + } + ++ if !quad_points.quad[2].x.is_finite() || !quad_points.quad[2].y.is_finite() { ++ return false; // just abort if projected quad isn't representable ++ } ++ + self.recursion_depth += 1; + if self.recursion_depth > RECURSIVE_LIMITS[QUAD_RECURSIVE_LIMIT] { +- return false; // just abort if projected quad isn't representable ++ // As Skia now does: when it stops making progress, a line, and on. ++ self.add_degenerate_line(quad_points); ++ self.recursion_depth -= 1; ++ return true; + } + + let mut half = QuadConstruct::default(); +- half.init_with_start(quad_points); ++ if !half.init_with_start(quad_points) { ++ self.add_degenerate_line(quad_points); ++ self.recursion_depth -= 1; ++ return true; ++ } + if !self.quad_stroke(quad, &mut half) { + return false; + } + +- half.init_with_end(quad_points); ++ if !half.init_with_end(quad_points) { ++ self.add_degenerate_line(quad_points); ++ self.recursion_depth -= 1; ++ return true; ++ } + if !self.quad_stroke(quad, &mut half) { + return false; + } +@@ -1098,9 +1247,9 @@ impl PathStroker { + on_p.x = tp.x + axis_flip * dxy.y; + on_p.y = tp.y - axis_flip * dxy.x; + ++ // As Skia now keeps it: the tangent as a vector, not a point a tangent's length on. + if let Some(ref mut tangent) = tangent { +- tangent.x = on_p.x + dxy.x; +- tangent.y = on_p.y + dxy.y; ++ **tangent = *dxy; + } + } + +@@ -1191,8 +1340,8 @@ impl PathStroker { + ) -> ResultType { + let start = quad_points.quad[0]; + let end = quad_points.quad[2]; +- let a_len = quad_points.tangent_start - start; +- let b_len = quad_points.tangent_end - end; ++ let a_len = quad_points.tangent_start; ++ let b_len = quad_points.tangent_end; + + // Slopes match when denom goes to zero: + // axLen / ayLen == bxLen / byLen +@@ -1214,8 +1363,8 @@ impl PathStroker { + + // if the perpendicular distances from the quad points to the opposite tangent line + // are small, a straight line is good enough +- let dist1 = pt_to_line(start, end, quad_points.tangent_end); +- let dist2 = pt_to_line(end, start, quad_points.tangent_start); ++ let dist1 = pt_to_tangent_line(start, end, quad_points.tangent_end); ++ let dist2 = pt_to_tangent_line(end, start, quad_points.tangent_start); + if dist1.max(dist2) <= self.inv_res_scale_squared { + return ResultType::Degenerate; + } +@@ -1231,10 +1380,8 @@ impl PathStroker { + if intersect_ray_type == IntersectRayType::CtrlPt { + // the intersection of the tangents need not be on the tangent segment + // so 0 <= numerA <= 1 is not necessarily true +- quad_points.quad[1].x = +- start.x * (1.0 - numer_a) + quad_points.tangent_start.x * numer_a; +- quad_points.quad[1].y = +- start.y * (1.0 - numer_a) + quad_points.tangent_start.y * numer_a; ++ quad_points.quad[1].x = start.x + quad_points.tangent_start.x * numer_a; ++ quad_points.quad[1].y = start.y + quad_points.tangent_start.y * numer_a; + } + + return ResultType::Quad; +@@ -1733,8 +1880,8 @@ fn fn_ptr_eq(f1: CapProc, f2: CapProc) -> bool { + struct QuadConstruct { + // The state of the quad stroke under construction. + quad: [Point; 3], // the stroked quad parallel to the original curve +- tangent_start: Point, // a point tangent to quad[0] +- tangent_end: Point, // a point tangent to quad[2] ++ tangent_start: Point, // the tangent at quad[0] ++ tangent_end: Point, // the tangent at quad[2] + start_t: NormalizedF32, // a segment of the original curve + mid_t: NormalizedF32, + end_t: NormalizedF32, +@@ -1819,6 +1966,53 @@ fn check_quad_linear(quad: &[Point; 3]) -> (Point, ReductionType) { + ) + } + ++/// `CheckConicLinear`. ++fn check_conic_linear(conic: &[Point; 3], weight: f32) -> (Point, ReductionType) { ++ let degenerate_ab = degenerate_vector(conic[1] - conic[0]); ++ let degenerate_bc = degenerate_vector(conic[2] - conic[1]); ++ if degenerate_ab & degenerate_bc { ++ return (Point::zero(), ReductionType::Point); ++ } ++ if degenerate_ab | degenerate_bc { ++ return (Point::zero(), ReductionType::Line); ++ } ++ if !quad_in_line(conic) { ++ return (Point::zero(), ReductionType::Quad); ++ } ++ let t = path_geometry::find_quad_max_curvature(conic).get(); ++ if t == 0.0 || t.is_nan() { ++ return (Point::zero(), ReductionType::Line); ++ } ++ (conic_eval(conic, weight, t), ReductionType::Degenerate) ++} ++ ++/// `SkConic::evalAt` (`SkConicCoeff`): the point at `t`. ++fn conic_eval(conic: &[Point; 3], weight: f32, t: f32) -> Point { ++ let (p0, p1, p2) = (conic[0], conic[1], conic[2]); ++ let p1w = Point::from_xy(p1.x * weight, p1.y * weight); ++ let a = Point::from_xy(p2.x - (p1w.x + p1w.x) + p0.x, p2.y - (p1w.y + p1w.y) + p0.y); ++ let b = Point::from_xy((p1w.x - p0.x) + (p1w.x - p0.x), (p1w.y - p0.y) + (p1w.y - p0.y)); ++ let db = (weight - 1.0) + (weight - 1.0); ++ let da = 0.0 - db; ++ let numer = Point::from_xy((a.x * t + b.x) * t + p0.x, (a.y * t + b.y) * t + p0.y); ++ let denom = (da * t + db) * t + 1.0; ++ Point::from_xy(numer.x / denom, numer.y / denom) ++} ++ ++/// `SkConic::evalTangentAt`. ++fn conic_eval_tangent(conic: &[Point; 3], weight: f32, t: f32) -> Point { ++ let (p0, p1, p2) = (conic[0], conic[1], conic[2]); ++ if (t == 0.0 && p0 == p1) || (t == 1.0 && p1 == p2) { ++ return p2 - p0; ++ } ++ let p20 = p2 - p0; ++ let p10 = p1 - p0; ++ let c = Point::from_xy(weight * p10.x, weight * p10.y); ++ let a = Point::from_xy(weight * p20.x - p20.x, weight * p20.y - p20.y); ++ let b = Point::from_xy(p20.x - c.x - c.x, p20.y - c.y - c.y); ++ Point::from_xy((a.x * t + b.x) * t + c.x, (a.y * t + b.y) * t + c.y) ++} ++ + fn degenerate_vector(v: Point) -> bool { + !v.can_normalize() + } +@@ -1855,6 +2049,20 @@ fn quad_in_line(quad: &[Point; 3]) -> bool { + pt_to_line(quad[mid], quad[outer1], quad[outer2]) <= line_slop + } + ++// The distance squared from `pt` to the segment from `line_start` along `tangent`. ++fn pt_to_tangent_line(pt: Point, line_start: Point, tangent: Point) -> f32 { ++ let ab0 = pt - line_start; ++ let numer = tangent.dot(ab0); ++ let denom = tangent.dot(tangent); ++ let t = numer / denom; ++ if t >= 0.0 && t <= 1.0 { ++ let hit = Point::from_xy(line_start.x + tangent.x * t, line_start.y + tangent.y * t); ++ hit.distance_to_sqd(pt) ++ } else { ++ pt.distance_to_sqd(line_start) ++ } ++} ++ + // returns the distance squared from the point to the line + fn pt_to_line(pt: Point, line_start: Point, line_end: Point) -> f32 { + let dxy = line_end - line_start; diff --git a/app/vendor/rune/vendor/tiny-skia-path/.cargo_vcs_info.json b/app/vendor/rune/vendor/tiny-skia-path/.cargo_vcs_info.json new file mode 100644 index 0000000..9dfd45e --- /dev/null +++ b/app/vendor/rune/vendor/tiny-skia-path/.cargo_vcs_info.json @@ -0,0 +1,6 @@ +{ + "git": { + "sha1": "ce3fe9bab0659fb928d6c22c03b74e009a8a2b77" + }, + "path_in_vcs": "path" +} \ No newline at end of file diff --git a/app/vendor/rune/vendor/tiny-skia-path/Cargo.toml b/app/vendor/rune/vendor/tiny-skia-path/Cargo.toml new file mode 100644 index 0000000..518b63f --- /dev/null +++ b/app/vendor/rune/vendor/tiny-skia-path/Cargo.toml @@ -0,0 +1,48 @@ +# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO +# +# When uploading crates to the registry Cargo will automatically +# "normalize" Cargo.toml files for maximal compatibility +# with all versions of Cargo and also rewrite `path` dependencies +# to registry (e.g., crates.io) dependencies. +# +# If you are reading this file be aware that the original Cargo.toml +# will likely look very different (and much more reasonable). +# See Cargo.toml.orig for the original contents. + +[package] +edition = "2018" +name = "tiny-skia-path" +version = "0.11.4" +authors = ["Yevhenii Reizner <razrfalcon@gmail.com>"] +description = "A tiny-skia Bezier path implementation" +documentation = "https://docs.rs/tiny-skia-path/" +readme = "README.md" +keywords = [ + "graphics", + "bezier", + "path", + "dash", + "stroke", +] +categories = ["graphics"] +license = "BSD-3-Clause" +repository = "https://github.com/RazrFalcon/tiny-skia/tree/master/path" + +[dependencies.arrayref] +version = "0.3.6" + +[dependencies.bytemuck] +version = "1.4" + +[dependencies.libm] +version = "0.2.1" +optional = true + +[dependencies.strict-num] +version = "0.1" +default-features = false + +[features] +default = ["std"] +no-std-float = ["libm"] +std = [] diff --git a/app/vendor/rune/vendor/tiny-skia-path/Cargo.toml.orig b/app/vendor/rune/vendor/tiny-skia-path/Cargo.toml.orig new file mode 100644 index 0000000..7451fb6 --- /dev/null +++ b/app/vendor/rune/vendor/tiny-skia-path/Cargo.toml.orig @@ -0,0 +1,27 @@ +[package] +name = "tiny-skia-path" +version = "0.11.4" +authors = ["Yevhenii Reizner <razrfalcon@gmail.com>"] +edition = "2018" +description = "A tiny-skia Bezier path implementation" +documentation = "https://docs.rs/tiny-skia-path/" +readme = "README.md" +repository = "https://github.com/RazrFalcon/tiny-skia/tree/master/path" +license = "BSD-3-Clause" +keywords = ["graphics", "bezier", "path", "dash", "stroke"] +categories = ["graphics"] +workspace = ".." + +[dependencies] +arrayref = "0.3.6" +bytemuck = "1.4" +libm = { version = "0.2.1", optional = true } # float support on no_std +strict-num = { version = "0.1", default-features = false } + +[features] +default = ["std"] + +# Enables the use of the standard library. Deactivate this and activate the no-std-float +# feature to compile for targets that don't have std. +std = [] +no-std-float = ["libm"] diff --git a/app/vendor/rune/vendor/tiny-skia-path/LICENSE b/app/vendor/rune/vendor/tiny-skia-path/LICENSE new file mode 100644 index 0000000..d7982d2 --- /dev/null +++ b/app/vendor/rune/vendor/tiny-skia-path/LICENSE @@ -0,0 +1,30 @@ +Copyright (c) 2011 Google Inc. All rights reserved. +Copyright (c) 2020 Yevhenii Reizner All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in + the documentation and/or other materials provided with the + distribution. + + * Neither the name of the copyright holder nor the names of its + contributors may be used to endorse or promote products derived + from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/app/vendor/rune/vendor/tiny-skia-path/README.md b/app/vendor/rune/vendor/tiny-skia-path/README.md new file mode 100644 index 0000000..8f5a8f7 --- /dev/null +++ b/app/vendor/rune/vendor/tiny-skia-path/README.md @@ -0,0 +1,18 @@ +# tiny-skia-path +![Build Status](https://github.com/RazrFalcon/tiny-skia/workflows/Rust/badge.svg) +[![Crates.io](https://img.shields.io/crates/v/tiny-skia-path.svg)](https://crates.io/crates/tiny-skia-path) +[![Documentation](https://docs.rs/tiny-skia-path/badge.svg)](https://docs.rs/tiny-skia-path) + +A [tiny-skia](https://github.com/RazrFalcon/tiny-skia) Bezier path implementation. + +Provides a memory-efficient Bezier path container, path builder, path stroker and path dasher. + +Also provides some basic geometry types, but they will be moved to an external crate eventually. + +Note that all types use single precision floats (`f32`), just like [Skia](https://skia.org/). + +MSRV: stable + +## License + +The same as used by [Skia](https://skia.org/): [New BSD License](./LICENSE) diff --git a/app/vendor/rune/vendor/tiny-skia-path/src/dash.rs b/app/vendor/rune/vendor/tiny-skia-path/src/dash.rs new file mode 100644 index 0000000..863db27 --- /dev/null +++ b/app/vendor/rune/vendor/tiny-skia-path/src/dash.rs @@ -0,0 +1,881 @@ +// Copyright 2014 Google Inc. +// Copyright 2020 Yevhenii Reizner +// +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +// This module is a mix of SkDashPath, SkDashPathEffect, SkContourMeasure and SkPathMeasure. + +use alloc::vec::Vec; + +use arrayref::array_ref; + +use crate::{Path, Point}; + +use crate::floating_point::{FiniteF32, NonZeroPositiveF32, NormalizedF32, NormalizedF32Exclusive}; +use crate::path::{PathSegment, PathSegmentsIter, PathVerb}; +use crate::path_builder::PathBuilder; +use crate::path_geometry; +use crate::scalar::Scalar; + +#[cfg(all(not(feature = "std"), feature = "no-std-float"))] +use crate::NoStdFloat; + +/// A stroke dashing properties. +/// +/// Contains an array of pairs, where the first number indicates an "on" interval +/// and the second one indicates an "off" interval; +/// a dash offset value and internal properties. +/// +/// # Guarantees +/// +/// - The dash array always have an even number of values. +/// - All dash array values are finite and >= 0. +/// - There is at least two dash array values. +/// - The sum of all dash array values is positive and finite. +/// - Dash offset is finite. +#[derive(Clone, PartialEq, Debug)] +pub struct StrokeDash { + array: Vec<f32>, + offset: f32, + interval_len: NonZeroPositiveF32, + first_len: f32, // TODO: PositiveF32 + first_index: usize, +} + +impl StrokeDash { + /// Creates a new stroke dashing object. + pub fn new(dash_array: Vec<f32>, dash_offset: f32) -> Option<Self> { + let dash_offset = FiniteF32::new(dash_offset)?; + + if dash_array.len() < 2 || dash_array.len() % 2 != 0 { + return None; + } + + if dash_array.iter().any(|n| *n < 0.0) { + return None; + } + + let interval_len: f32 = dash_array.iter().sum(); + let interval_len = NonZeroPositiveF32::new(interval_len)?; + + let dash_offset = adjust_dash_offset(dash_offset.get(), interval_len.get()); + debug_assert!(dash_offset >= 0.0); + debug_assert!(dash_offset < interval_len.get()); + + let (first_len, first_index) = find_first_interval(&dash_array, dash_offset); + debug_assert!(first_len >= 0.0); + debug_assert!(first_index < dash_array.len()); + + Some(StrokeDash { + array: dash_array, + offset: dash_offset, + interval_len, + first_len, + first_index, + }) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use alloc::vec; + + #[test] + fn test() { + assert_eq!(StrokeDash::new(vec![], 0.0), None); + assert_eq!(StrokeDash::new(vec![1.0], 0.0), None); + assert_eq!(StrokeDash::new(vec![1.0, 2.0, 3.0], 0.0), None); + assert_eq!(StrokeDash::new(vec![1.0, -2.0], 0.0), None); + assert_eq!(StrokeDash::new(vec![0.0, 0.0], 0.0), None); + assert_eq!(StrokeDash::new(vec![1.0, -1.0], 0.0), None); + assert_eq!(StrokeDash::new(vec![1.0, 1.0], f32::INFINITY), None); + assert_eq!(StrokeDash::new(vec![1.0, f32::INFINITY], 0.0), None); + } + + #[test] + fn bug_26() { + let mut pb = PathBuilder::new(); + pb.move_to(665.54, 287.3); + pb.line_to(675.67, 273.04); + pb.line_to(675.52, 271.32); + pb.line_to(674.79, 269.61); + pb.line_to(674.05, 268.04); + pb.line_to(672.88, 266.47); + pb.line_to(671.27, 264.9); + let path = pb.finish().unwrap(); + + let stroke_dash = StrokeDash::new(vec![6.0, 4.5], 0.0).unwrap(); + + assert!(path.dash(&stroke_dash, 1.0).is_some()); + } +} + +// Adjust phase to be between 0 and len, "flipping" phase if negative. +// e.g., if len is 100, then phase of -20 (or -120) is equivalent to 80. +fn adjust_dash_offset(mut offset: f32, len: f32) -> f32 { + if offset < 0.0 { + offset = -offset; + if offset > len { + offset %= len; + } + + offset = len - offset; + + // Due to finite precision, it's possible that phase == len, + // even after the subtract (if len >>> phase), so fix that here. + debug_assert!(offset <= len); + if offset == len { + offset = 0.0; + } + + offset + } else if offset >= len { + offset % len + } else { + offset + } +} + +fn find_first_interval(dash_array: &[f32], mut dash_offset: f32) -> (f32, usize) { + for (i, gap) in dash_array.iter().copied().enumerate() { + if dash_offset > gap || (dash_offset == gap && gap != 0.0) { + dash_offset -= gap; + } else { + return (gap - dash_offset, i); + } + } + + // If we get here, phase "appears" to be larger than our length. This + // shouldn't happen with perfect precision, but we can accumulate errors + // during the initial length computation (rounding can make our sum be too + // big or too small. In that event, we just have to eat the error here. + (dash_array[0], 0) +} + +impl Path { + /// Converts the current path into a dashed one. + /// + /// `resolution_scale` can be obtained via + /// [`compute_resolution_scale`](crate::PathStroker::compute_resolution_scale). + /// + /// Returns `None` when more than 1_000_000 dashes had to be produced + /// or when the final path has an invalid bounding box. + pub fn dash(&self, dash: &StrokeDash, resolution_scale: f32) -> Option<Path> { + dash_impl(self, dash, resolution_scale) + } +} + +fn dash_impl(src: &Path, dash: &StrokeDash, res_scale: f32) -> Option<Path> { + // We do not support the `cull_path` branch here. + // Skia has a lot of code for cases when a path contains only a single zero-length line + // or when a path is a rect. Not sure why. + // We simply ignoring it for the sake of simplicity. + + // We also doesn't support the `SpecialLineRec` case. + // I have no idea what the point in it. + + fn is_even(x: usize) -> bool { + x % 2 == 0 + } + + let mut pb = PathBuilder::new(); + let mut dash_count = 0.0; + for contour in ContourMeasureIter::new(src, res_scale) { + let mut skip_first_segment = contour.is_closed; + let mut added_segment = false; + let length = contour.length; + let mut index = dash.first_index; + + // Since the path length / dash length ratio may be arbitrarily large, we can exert + // significant memory pressure while attempting to build the filtered path. To avoid this, + // we simply give up dashing beyond a certain threshold. + // + // The original bug report (http://crbug.com/165432) is based on a path yielding more than + // 90 million dash segments and crashing the memory allocator. A limit of 1 million + // segments seems reasonable: at 2 verbs per segment * 9 bytes per verb, this caps the + // maximum dash memory overhead at roughly 17MB per path. + const MAX_DASH_COUNT: usize = 1000000; + dash_count += length * (dash.array.len() >> 1) as f32 / dash.interval_len.get(); + if dash_count > MAX_DASH_COUNT as f32 { + return None; + } + + // Using double precision to avoid looping indefinitely due to single precision rounding + // (for extreme path_length/dash_length ratios). See test_infinite_dash() unittest. + let mut distance = 0.0; + let mut d_len = dash.first_len; + + while distance < length { + debug_assert!(d_len >= 0.0); + added_segment = false; + if is_even(index) && !skip_first_segment { + added_segment = true; + contour.push_segment(distance, distance + d_len, true, &mut pb); + } + + distance += d_len; + + // clear this so we only respect it the first time around + skip_first_segment = false; + + // wrap around our intervals array if necessary + index += 1; + debug_assert!(index <= dash.array.len()); + if index == dash.array.len() { + index = 0; + } + + // fetch our next d_len + d_len = dash.array[index]; + } + + // extend if we ended on a segment and we need to join up with the (skipped) initial segment + if contour.is_closed && is_even(dash.first_index) && dash.first_len >= 0.0 { + contour.push_segment(0.0, dash.first_len, !added_segment, &mut pb); + } + } + + pb.finish() +} + +const MAX_T_VALUE: u32 = 0x3FFFFFFF; + +struct ContourMeasureIter<'a> { + iter: PathSegmentsIter<'a>, + tolerance: f32, +} + +impl<'a> ContourMeasureIter<'a> { + fn new(path: &'a Path, res_scale: f32) -> Self { + // can't use tangents, since we need [0..1..................2] to be seen + // as definitely not a line (it is when drawn, but not parametrically) + // so we compare midpoints + const CHEAP_DIST_LIMIT: f32 = 0.5; // just made this value up + + ContourMeasureIter { + iter: path.segments(), + tolerance: CHEAP_DIST_LIMIT * res_scale.invert(), + } + } +} + +impl Iterator for ContourMeasureIter<'_> { + type Item = ContourMeasure; + + // If it encounters a zero-length contour, it is skipped. + fn next(&mut self) -> Option<Self::Item> { + // Note: + // as we accumulate distance, we have to check that the result of += + // actually made it larger, since a very small delta might be > 0, but + // still have no effect on distance (if distance >>> delta). + // + // We do this check below, and in compute_quad_segs and compute_cubic_segs + + let mut contour = ContourMeasure::default(); + + let mut point_index = 0; + let mut distance = 0.0; + let mut have_seen_close = false; + let mut prev_p = Point::zero(); + while let Some(seg) = self.iter.next() { + match seg { + PathSegment::MoveTo(p0) => { + contour.points.push(p0); + prev_p = p0; + } + PathSegment::LineTo(p0) => { + let prev_d = distance; + distance = contour.compute_line_seg(prev_p, p0, distance, point_index); + + if distance > prev_d { + contour.points.push(p0); + point_index += 1; + } + + prev_p = p0; + } + // Dashing measures a conic as the quad through its control point. + PathSegment::QuadTo(p0, p1) | PathSegment::ConicTo(p0, p1, _) => { + let prev_d = distance; + distance = contour.compute_quad_segs( + prev_p, + p0, + p1, + distance, + 0, + MAX_T_VALUE, + point_index, + self.tolerance, + ); + + if distance > prev_d { + contour.points.push(p0); + contour.points.push(p1); + point_index += 2; + } + + prev_p = p1; + } + PathSegment::CubicTo(p0, p1, p2) => { + let prev_d = distance; + distance = contour.compute_cubic_segs( + prev_p, + p0, + p1, + p2, + distance, + 0, + MAX_T_VALUE, + point_index, + self.tolerance, + ); + + if distance > prev_d { + contour.points.push(p0); + contour.points.push(p1); + contour.points.push(p2); + point_index += 3; + } + + prev_p = p2; + } + PathSegment::Close => { + have_seen_close = true; + } + } + + // TODO: to contour iter? + if self.iter.next_verb() == Some(PathVerb::Move) { + break; + } + } + + if !distance.is_finite() { + return None; + } + + if have_seen_close { + let prev_d = distance; + let first_pt = contour.points[0]; + distance = contour.compute_line_seg( + contour.points[point_index], + first_pt, + distance, + point_index, + ); + + if distance > prev_d { + contour.points.push(first_pt); + } + } + + contour.length = distance; + contour.is_closed = have_seen_close; + + if contour.points.is_empty() { + None + } else { + Some(contour) + } + } +} + +#[derive(Copy, Clone, PartialEq, Debug)] +enum SegmentType { + Line, + Quad, + Cubic, +} + +#[derive(Copy, Clone, Debug)] +struct Segment { + distance: f32, // total distance up to this point + point_index: usize, // index into the ContourMeasure::points array + t_value: u32, + kind: SegmentType, +} + +impl Segment { + fn scalar_t(&self) -> f32 { + debug_assert!(self.t_value <= MAX_T_VALUE); + // 1/kMaxTValue can't be represented as a float, but it's close and the limits work fine. + const MAX_T_RECIPROCAL: f32 = 1.0 / MAX_T_VALUE as f32; + self.t_value as f32 * MAX_T_RECIPROCAL + } +} + +#[derive(Default, Debug)] +struct ContourMeasure { + segments: Vec<Segment>, + points: Vec<Point>, + length: f32, + is_closed: bool, +} + +impl ContourMeasure { + fn push_segment( + &self, + mut start_d: f32, + mut stop_d: f32, + start_with_move_to: bool, + pb: &mut PathBuilder, + ) { + if start_d < 0.0 { + start_d = 0.0; + } + + if stop_d > self.length { + stop_d = self.length; + } + + if !(start_d <= stop_d) { + // catch NaN values as well + return; + } + + if self.segments.is_empty() { + return; + } + + let (seg_index, mut start_t) = match self.distance_to_segment(start_d) { + Some(v) => v, + None => return, + }; + let mut seg = self.segments[seg_index]; + + let (stop_seg_index, stop_t) = match self.distance_to_segment(stop_d) { + Some(v) => v, + None => return, + }; + let stop_seg = self.segments[stop_seg_index]; + + debug_assert!(stop_seg_index <= stop_seg_index); + let mut p = Point::zero(); + if start_with_move_to { + compute_pos_tan( + &self.points[seg.point_index..], + seg.kind, + start_t, + Some(&mut p), + None, + ); + pb.move_to(p.x, p.y); + } + + if seg.point_index == stop_seg.point_index { + segment_to( + &self.points[seg.point_index..], + seg.kind, + start_t, + stop_t, + pb, + ); + } else { + let mut new_seg_index = seg_index; + loop { + segment_to( + &self.points[seg.point_index..], + seg.kind, + start_t, + NormalizedF32::ONE, + pb, + ); + + let old_point_index = seg.point_index; + loop { + new_seg_index += 1; + if self.segments[new_seg_index].point_index != old_point_index { + break; + } + } + seg = self.segments[new_seg_index]; + + start_t = NormalizedF32::ZERO; + + if seg.point_index >= stop_seg.point_index { + break; + } + } + + segment_to( + &self.points[seg.point_index..], + seg.kind, + NormalizedF32::ZERO, + stop_t, + pb, + ); + } + } + + fn distance_to_segment(&self, distance: f32) -> Option<(usize, NormalizedF32)> { + debug_assert!(distance >= 0.0 && distance <= self.length); + + let mut index = find_segment(&self.segments, distance); + // don't care if we hit an exact match or not, so we xor index if it is negative + index ^= index >> 31; + let index = index as usize; + let seg = self.segments[index]; + + // now interpolate t-values with the prev segment (if possible) + let mut start_t = 0.0; + let mut start_d = 0.0; + // check if the prev segment is legal, and references the same set of points + if index > 0 { + start_d = self.segments[index - 1].distance; + if self.segments[index - 1].point_index == seg.point_index { + debug_assert!(self.segments[index - 1].kind == seg.kind); + start_t = self.segments[index - 1].scalar_t(); + } + } + + debug_assert!(seg.scalar_t() > start_t); + debug_assert!(distance >= start_d); + debug_assert!(seg.distance > start_d); + + let t = + start_t + (seg.scalar_t() - start_t) * (distance - start_d) / (seg.distance - start_d); + let t = NormalizedF32::new(t)?; + Some((index, t)) + } + + fn compute_line_seg( + &mut self, + p0: Point, + p1: Point, + mut distance: f32, + point_index: usize, + ) -> f32 { + let d = p0.distance(p1); + debug_assert!(d >= 0.0); + let prev_d = distance; + distance += d; + if distance > prev_d { + debug_assert!(point_index < self.points.len()); + self.segments.push(Segment { + distance, + point_index, + t_value: MAX_T_VALUE, + kind: SegmentType::Line, + }); + } + + distance + } + + fn compute_quad_segs( + &mut self, + p0: Point, + p1: Point, + p2: Point, + mut distance: f32, + min_t: u32, + max_t: u32, + point_index: usize, + tolerance: f32, + ) -> f32 { + if t_span_big_enough(max_t - min_t) != 0 && quad_too_curvy(p0, p1, p2, tolerance) { + let mut tmp = [Point::zero(); 5]; + let half_t = (min_t + max_t) >> 1; + + path_geometry::chop_quad_at(&[p0, p1, p2], NormalizedF32Exclusive::HALF, &mut tmp); + distance = self.compute_quad_segs( + tmp[0], + tmp[1], + tmp[2], + distance, + min_t, + half_t, + point_index, + tolerance, + ); + distance = self.compute_quad_segs( + tmp[2], + tmp[3], + tmp[4], + distance, + half_t, + max_t, + point_index, + tolerance, + ); + } else { + let d = p0.distance(p2); + let prev_d = distance; + distance += d; + if distance > prev_d { + debug_assert!(point_index < self.points.len()); + self.segments.push(Segment { + distance, + point_index, + t_value: max_t, + kind: SegmentType::Quad, + }); + } + } + + distance + } + + fn compute_cubic_segs( + &mut self, + p0: Point, + p1: Point, + p2: Point, + p3: Point, + mut distance: f32, + min_t: u32, + max_t: u32, + point_index: usize, + tolerance: f32, + ) -> f32 { + if t_span_big_enough(max_t - min_t) != 0 && cubic_too_curvy(p0, p1, p2, p3, tolerance) { + let mut tmp = [Point::zero(); 7]; + let half_t = (min_t + max_t) >> 1; + + path_geometry::chop_cubic_at2( + &[p0, p1, p2, p3], + NormalizedF32Exclusive::HALF, + &mut tmp, + ); + distance = self.compute_cubic_segs( + tmp[0], + tmp[1], + tmp[2], + tmp[3], + distance, + min_t, + half_t, + point_index, + tolerance, + ); + distance = self.compute_cubic_segs( + tmp[3], + tmp[4], + tmp[5], + tmp[6], + distance, + half_t, + max_t, + point_index, + tolerance, + ); + } else { + let d = p0.distance(p3); + let prev_d = distance; + distance += d; + if distance > prev_d { + debug_assert!(point_index < self.points.len()); + self.segments.push(Segment { + distance, + point_index, + t_value: max_t, + kind: SegmentType::Cubic, + }); + } + } + + distance + } +} + +fn find_segment(base: &[Segment], key: f32) -> i32 { + let mut lo = 0u32; + let mut hi = (base.len() - 1) as u32; + + while lo < hi { + let mid = (hi + lo) >> 1; + if base[mid as usize].distance < key { + lo = mid + 1; + } else { + hi = mid; + } + } + + if base[hi as usize].distance < key { + hi += 1; + hi = !hi; + } else if key < base[hi as usize].distance { + hi = !hi; + } + + hi as i32 +} + +fn compute_pos_tan( + points: &[Point], + seg_kind: SegmentType, + t: NormalizedF32, + pos: Option<&mut Point>, + tangent: Option<&mut Point>, +) { + match seg_kind { + SegmentType::Line => { + if let Some(pos) = pos { + *pos = Point::from_xy( + interp(points[0].x, points[1].x, t), + interp(points[0].y, points[1].y, t), + ); + } + + if let Some(tangent) = tangent { + tangent.set_normalize(points[1].x - points[0].x, points[1].y - points[0].y); + } + } + SegmentType::Quad => { + let src = array_ref![points, 0, 3]; + if let Some(pos) = pos { + *pos = path_geometry::eval_quad_at(src, t); + } + + if let Some(tangent) = tangent { + *tangent = path_geometry::eval_quad_tangent_at(src, t); + tangent.normalize(); + } + } + SegmentType::Cubic => { + let src = array_ref![points, 0, 4]; + if let Some(pos) = pos { + *pos = path_geometry::eval_cubic_pos_at(src, t); + } + + if let Some(tangent) = tangent { + *tangent = path_geometry::eval_cubic_tangent_at(src, t); + tangent.normalize(); + } + } + } +} + +fn segment_to( + points: &[Point], + seg_kind: SegmentType, + start_t: NormalizedF32, + stop_t: NormalizedF32, + pb: &mut PathBuilder, +) { + debug_assert!(start_t <= stop_t); + + if start_t == stop_t { + if let Some(pt) = pb.last_point() { + // If the dash as a zero-length on segment, add a corresponding zero-length line. + // The stroke code will add end caps to zero length lines as appropriate. + pb.line_to(pt.x, pt.y); + } + + return; + } + + match seg_kind { + SegmentType::Line => { + if stop_t == NormalizedF32::ONE { + pb.line_to(points[1].x, points[1].y); + } else { + pb.line_to( + interp(points[0].x, points[1].x, stop_t), + interp(points[0].y, points[1].y, stop_t), + ); + } + } + SegmentType::Quad => { + let mut tmp0 = [Point::zero(); 5]; + let mut tmp1 = [Point::zero(); 5]; + if start_t == NormalizedF32::ZERO { + if stop_t == NormalizedF32::ONE { + pb.quad_to_pt(points[1], points[2]); + } else { + let stop_t = NormalizedF32Exclusive::new_bounded(stop_t.get()); + path_geometry::chop_quad_at(points, stop_t, &mut tmp0); + pb.quad_to_pt(tmp0[1], tmp0[2]); + } + } else { + let start_tt = NormalizedF32Exclusive::new_bounded(start_t.get()); + path_geometry::chop_quad_at(points, start_tt, &mut tmp0); + if stop_t == NormalizedF32::ONE { + pb.quad_to_pt(tmp0[3], tmp0[4]); + } else { + let new_t = (stop_t.get() - start_t.get()) / (1.0 - start_t.get()); + let new_t = NormalizedF32Exclusive::new_bounded(new_t); + path_geometry::chop_quad_at(&tmp0[2..], new_t, &mut tmp1); + pb.quad_to_pt(tmp1[1], tmp1[2]); + } + } + } + SegmentType::Cubic => { + let mut tmp0 = [Point::zero(); 7]; + let mut tmp1 = [Point::zero(); 7]; + if start_t == NormalizedF32::ZERO { + if stop_t == NormalizedF32::ONE { + pb.cubic_to_pt(points[1], points[2], points[3]); + } else { + let stop_t = NormalizedF32Exclusive::new_bounded(stop_t.get()); + path_geometry::chop_cubic_at2(array_ref![points, 0, 4], stop_t, &mut tmp0); + pb.cubic_to_pt(tmp0[1], tmp0[2], tmp0[3]); + } + } else { + let start_tt = NormalizedF32Exclusive::new_bounded(start_t.get()); + path_geometry::chop_cubic_at2(array_ref![points, 0, 4], start_tt, &mut tmp0); + if stop_t == NormalizedF32::ONE { + pb.cubic_to_pt(tmp0[4], tmp0[5], tmp0[6]); + } else { + let new_t = (stop_t.get() - start_t.get()) / (1.0 - start_t.get()); + let new_t = NormalizedF32Exclusive::new_bounded(new_t); + path_geometry::chop_cubic_at2(array_ref![tmp0, 3, 4], new_t, &mut tmp1); + pb.cubic_to_pt(tmp1[1], tmp1[2], tmp1[3]); + } + } + } + } +} + +fn t_span_big_enough(t_span: u32) -> u32 { + debug_assert!(t_span <= MAX_T_VALUE); + t_span >> 10 +} + +fn quad_too_curvy(p0: Point, p1: Point, p2: Point, tolerance: f32) -> bool { + // diff = (a/4 + b/2 + c/4) - (a/2 + c/2) + // diff = -a/4 + b/2 - c/4 + let dx = (p1.x).half() - (p0.x + p2.x).half().half(); + let dy = (p1.y).half() - (p0.y + p2.y).half().half(); + + let dist = dx.abs().max(dy.abs()); + dist > tolerance +} + +fn cubic_too_curvy(p0: Point, p1: Point, p2: Point, p3: Point, tolerance: f32) -> bool { + let n0 = cheap_dist_exceeds_limit( + p1, + interp_safe(p0.x, p3.x, 1.0 / 3.0), + interp_safe(p0.y, p3.y, 1.0 / 3.0), + tolerance, + ); + + let n1 = cheap_dist_exceeds_limit( + p2, + interp_safe(p0.x, p3.x, 2.0 / 3.0), + interp_safe(p0.y, p3.y, 2.0 / 3.0), + tolerance, + ); + + n0 || n1 +} + +fn cheap_dist_exceeds_limit(pt: Point, x: f32, y: f32, tolerance: f32) -> bool { + let dist = (x - pt.x).abs().max((y - pt.y).abs()); + // just made up the 1/2 + dist > tolerance +} + +/// Linearly interpolate between A and B, based on t. +/// +/// If t is 0, return A. If t is 1, return B else interpolate. +fn interp(a: f32, b: f32, t: NormalizedF32) -> f32 { + a + (b - a) * t.get() +} + +fn interp_safe(a: f32, b: f32, t: f32) -> f32 { + debug_assert!(t >= 0.0 && t <= 1.0); + a + (b - a) * t +} diff --git a/app/vendor/rune/vendor/tiny-skia-path/src/f32x2_t.rs b/app/vendor/rune/vendor/tiny-skia-path/src/f32x2_t.rs new file mode 100644 index 0000000..e471f42 --- /dev/null +++ b/app/vendor/rune/vendor/tiny-skia-path/src/f32x2_t.rs @@ -0,0 +1,109 @@ +// Copyright 2020 Yevhenii Reizner +// +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#[cfg(all(not(feature = "std"), feature = "no-std-float"))] +use crate::NoStdFloat; + +// Right now, there are no visible benefits of using SIMD for f32x2. So we don't. +/// A pair of f32 numbers. +/// +/// Mainly for internal use. Do not rely on it! +#[allow(non_camel_case_types)] +#[derive(Copy, Clone, Default, PartialEq, Debug)] +pub struct f32x2(pub [f32; 2]); + +impl f32x2 { + /// Creates a new pair. + pub fn new(a: f32, b: f32) -> f32x2 { + f32x2([a, b]) + } + + /// Creates a new pair from a single value. + pub fn splat(x: f32) -> f32x2 { + f32x2([x, x]) + } + + /// Returns an absolute value. + pub fn abs(self) -> f32x2 { + f32x2([self.x().abs(), self.y().abs()]) + } + + /// Returns a minimum value. + pub fn min(self, other: f32x2) -> f32x2 { + f32x2([pmin(self.x(), other.x()), pmin(self.y(), other.y())]) + } + + /// Returns a maximum value. + pub fn max(self, other: f32x2) -> f32x2 { + f32x2([pmax(self.x(), other.x()), pmax(self.y(), other.y())]) + } + + /// Returns a maximum of both values. + pub fn max_component(self) -> f32 { + pmax(self.x(), self.y()) + } + + /// Returns the first value. + pub fn x(&self) -> f32 { + self.0[0] + } + + /// Returns the second value. + pub fn y(&self) -> f32 { + self.0[1] + } +} + +impl core::ops::Add<f32x2> for f32x2 { + type Output = f32x2; + + fn add(self, other: f32x2) -> f32x2 { + f32x2([self.x() + other.x(), self.y() + other.y()]) + } +} + +impl core::ops::Sub<f32x2> for f32x2 { + type Output = f32x2; + + fn sub(self, other: f32x2) -> f32x2 { + f32x2([self.x() - other.x(), self.y() - other.y()]) + } +} + +impl core::ops::Mul<f32x2> for f32x2 { + type Output = f32x2; + + fn mul(self, other: f32x2) -> f32x2 { + f32x2([self.x() * other.x(), self.y() * other.y()]) + } +} + +impl core::ops::Div<f32x2> for f32x2 { + type Output = f32x2; + + fn div(self, other: f32x2) -> f32x2 { + f32x2([self.x() / other.x(), self.y() / other.y()]) + } +} + +// A faster and more forgiving f32 min/max implementation. +// +// Unlike std one, we do not care about NaN. + +fn pmax(a: f32, b: f32) -> f32 { + if a < b { + b + } else { + a + } +} + +fn pmin(a: f32, b: f32) -> f32 { + if b < a { + b + } else { + a + } +} diff --git a/app/vendor/rune/vendor/tiny-skia-path/src/f32x4_t.rs b/app/vendor/rune/vendor/tiny-skia-path/src/f32x4_t.rs new file mode 100644 index 0000000..e591b55 --- /dev/null +++ b/app/vendor/rune/vendor/tiny-skia-path/src/f32x4_t.rs @@ -0,0 +1,80 @@ +// Copyright 2020 Yevhenii Reizner +// +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +// Right now, there are no visible benefits of using SIMD for f32x4. So we don't. +#[derive(Default, Clone, Copy, PartialEq, Debug)] +#[repr(C, align(16))] +pub struct f32x4(pub [f32; 4]); + +impl f32x4 { + pub fn max(self, rhs: Self) -> Self { + Self([ + self.0[0].max(rhs.0[0]), + self.0[1].max(rhs.0[1]), + self.0[2].max(rhs.0[2]), + self.0[3].max(rhs.0[3]), + ]) + } + + pub fn min(self, rhs: Self) -> Self { + Self([ + self.0[0].min(rhs.0[0]), + self.0[1].min(rhs.0[1]), + self.0[2].min(rhs.0[2]), + self.0[3].min(rhs.0[3]), + ]) + } +} + +impl core::ops::Add for f32x4 { + type Output = Self; + + fn add(self, rhs: Self) -> Self::Output { + Self([ + self.0[0] + rhs.0[0], + self.0[1] + rhs.0[1], + self.0[2] + rhs.0[2], + self.0[3] + rhs.0[3], + ]) + } +} + +impl core::ops::AddAssign for f32x4 { + fn add_assign(&mut self, rhs: f32x4) { + *self = *self + rhs; + } +} + +impl core::ops::Sub for f32x4 { + type Output = Self; + + fn sub(self, rhs: Self) -> Self::Output { + Self([ + self.0[0] - rhs.0[0], + self.0[1] - rhs.0[1], + self.0[2] - rhs.0[2], + self.0[3] - rhs.0[3], + ]) + } +} + +impl core::ops::Mul for f32x4 { + type Output = Self; + + fn mul(self, rhs: Self) -> Self::Output { + Self([ + self.0[0] * rhs.0[0], + self.0[1] * rhs.0[1], + self.0[2] * rhs.0[2], + self.0[3] * rhs.0[3], + ]) + } +} + +impl core::ops::MulAssign for f32x4 { + fn mul_assign(&mut self, rhs: f32x4) { + *self = *self * rhs; + } +} diff --git a/app/vendor/rune/vendor/tiny-skia-path/src/floating_point.rs b/app/vendor/rune/vendor/tiny-skia-path/src/floating_point.rs new file mode 100644 index 0000000..31a97b9 --- /dev/null +++ b/app/vendor/rune/vendor/tiny-skia-path/src/floating_point.rs @@ -0,0 +1,148 @@ +// Copyright 2006 The Android Open Source Project +// Copyright 2020 Yevhenii Reizner +// +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +use crate::scalar::Scalar; + +pub use strict_num::{FiniteF32, NonZeroPositiveF32, NormalizedF32}; + +#[cfg(all(not(feature = "std"), feature = "no-std-float"))] +use crate::NoStdFloat; + +pub(crate) const FLOAT_PI: f32 = 3.14159265; + +const MAX_I32_FITS_IN_F32: f32 = 2147483520.0; +const MIN_I32_FITS_IN_F32: f32 = -MAX_I32_FITS_IN_F32; + +// TODO: is there an std alternative? +/// Custom float to integer conversion routines. +pub trait SaturateCast<T>: Sized { + /// Return the closest integer for the given float. + fn saturate_from(n: T) -> Self; +} + +impl SaturateCast<f32> for i32 { + /// Return the closest integer for the given float. + /// + /// Returns MAX_I32_FITS_IN_F32 for NaN. + fn saturate_from(mut x: f32) -> Self { + x = if x < MAX_I32_FITS_IN_F32 { + x + } else { + MAX_I32_FITS_IN_F32 + }; + x = if x > MIN_I32_FITS_IN_F32 { + x + } else { + MIN_I32_FITS_IN_F32 + }; + x as i32 + } +} + +impl SaturateCast<f64> for i32 { + /// Return the closest integer for the given double. + /// + /// Returns i32::MAX for NaN. + fn saturate_from(mut x: f64) -> Self { + x = if x < i32::MAX as f64 { + x + } else { + i32::MAX as f64 + }; + x = if x > i32::MIN as f64 { + x + } else { + i32::MIN as f64 + }; + x as i32 + } +} + +/// Custom float to integer rounding routines. +#[allow(missing_docs)] +pub trait SaturateRound<T>: SaturateCast<T> { + fn saturate_floor(n: T) -> Self; + fn saturate_ceil(n: T) -> Self; + fn saturate_round(n: T) -> Self; +} + +impl SaturateRound<f32> for i32 { + fn saturate_floor(x: f32) -> Self { + Self::saturate_from(x.floor()) + } + + fn saturate_ceil(x: f32) -> Self { + Self::saturate_from(x.ceil()) + } + + fn saturate_round(x: f32) -> Self { + Self::saturate_from(x.floor() + 0.5) + } +} + +/// Return the float as a 2s compliment int. Just to be used to compare floats +/// to each other or against positive float-bit-constants (like 0). This does +/// not return the int equivalent of the float, just something cheaper for +/// compares-only. +pub(crate) fn f32_as_2s_compliment(x: f32) -> i32 { + sign_bit_to_2s_compliment(bytemuck::cast(x)) +} + +/// Convert a sign-bit int (i.e. float interpreted as int) into a 2s compliement +/// int. This also converts -0 (0x80000000) to 0. Doing this to a float allows +/// it to be compared using normal C operators (<, <=, etc.) +fn sign_bit_to_2s_compliment(mut x: i32) -> i32 { + if x < 0 { + x &= 0x7FFFFFFF; + x = -x; + } + + x +} + +/// An immutable `f32` that is larger than 0 but less then 1. +#[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Default, Debug)] +#[repr(transparent)] +pub struct NormalizedF32Exclusive(FiniteF32); + +impl NormalizedF32Exclusive { + /// Just a random, valid number. + pub const ANY: Self = Self::HALF; + + /// A predefined 0.5 value. + pub const HALF: Self = NormalizedF32Exclusive(unsafe { FiniteF32::new_unchecked(0.5) }); + + /// Creates a `NormalizedF32Exclusive`. + pub fn new(n: f32) -> Option<Self> { + if n > 0.0 && n < 1.0 { + // `n` is guarantee to be finite after the bounds check. + FiniteF32::new(n).map(NormalizedF32Exclusive) + } else { + None + } + } + + /// Creates a `NormalizedF32Exclusive` clamping the given value. + /// + /// Returns zero in case of NaN or infinity. + pub fn new_bounded(n: f32) -> Self { + let n = n.bound(f32::EPSILON, 1.0 - f32::EPSILON); + // `n` is guarantee to be finite after clamping. + debug_assert!(n.is_finite()); + NormalizedF32Exclusive(unsafe { FiniteF32::new_unchecked(n) }) + } + + /// Returns the value as a primitive type. + pub fn get(self) -> f32 { + self.0.get() + } + + /// Returns the value as a `FiniteF32`. + pub fn to_normalized(self) -> NormalizedF32 { + // NormalizedF32 is (0,1), while NormalizedF32 is [0,1], so it will always fit. + unsafe { NormalizedF32::new_unchecked(self.0.get()) } + } +} diff --git a/app/vendor/rune/vendor/tiny-skia-path/src/lib.rs b/app/vendor/rune/vendor/tiny-skia-path/src/lib.rs new file mode 100644 index 0000000..41700ba --- /dev/null +++ b/app/vendor/rune/vendor/tiny-skia-path/src/lib.rs @@ -0,0 +1,329 @@ +// Copyright 2006 The Android Open Source Project +// Copyright 2020 Yevhenii Reizner +// +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +//! A [tiny-skia](https://github.com/RazrFalcon/tiny-skia) Bezier path implementation. +//! +//! Provides a memory-efficient Bezier path container, path builder, path stroker and path dasher. +//! +//! Also provides some basic geometry types, but they will be moved to an external crate eventually. +//! +//! Note that all types use single precision floats (`f32`), just like [Skia](https://skia.org/). + +#![no_std] +#![warn(missing_docs)] +#![warn(missing_copy_implementations)] +#![warn(missing_debug_implementations)] +#![allow(clippy::approx_constant)] +#![allow(clippy::collapsible_if)] +#![allow(clippy::eq_op)] +#![allow(clippy::excessive_precision)] +#![allow(clippy::identity_op)] +#![allow(clippy::manual_range_contains)] +#![allow(clippy::neg_cmp_op_on_partial_ord)] +#![allow(clippy::too_many_arguments)] +#![allow(clippy::upper_case_acronyms)] +#![allow(clippy::wrong_self_convention)] + +#[cfg(not(any(feature = "std", feature = "no-std-float")))] +compile_error!("You have to activate either the `std` or the `no-std-float` feature."); + +#[cfg(feature = "std")] +extern crate std; + +extern crate alloc; + +mod dash; +mod f32x2_t; +mod f32x4_t; +mod floating_point; +mod path; +mod path_builder; +pub mod path_geometry; +mod rect; +mod scalar; +mod size; +mod stroker; +mod transform; + +pub use dash::StrokeDash; +pub use f32x2_t::f32x2; +pub use floating_point::*; +pub use path::*; +pub use path_builder::*; +pub use rect::*; +pub use scalar::*; +pub use size::*; +pub use stroker::*; +pub use transform::*; + +/// An integer length that is guarantee to be > 0 +type LengthU32 = core::num::NonZeroU32; + +/// A point. +/// +/// Doesn't guarantee to be finite. +#[allow(missing_docs)] +#[repr(C)] +#[derive(Copy, Clone, PartialEq, Default, Debug)] +pub struct Point { + pub x: f32, + pub y: f32, +} + +impl From<(f32, f32)> for Point { + #[inline] + fn from(v: (f32, f32)) -> Self { + Point { x: v.0, y: v.1 } + } +} + +impl Point { + /// Creates a new `Point`. + pub fn from_xy(x: f32, y: f32) -> Self { + Point { x, y } + } + + /// Creates a new `Point` from `f32x2`. + pub fn from_f32x2(r: f32x2) -> Self { + Point::from_xy(r.x(), r.y()) + } + + /// Converts a `Point` into a `f32x2`. + pub fn to_f32x2(&self) -> f32x2 { + f32x2::new(self.x, self.y) + } + + /// Creates a point at 0x0 position. + pub fn zero() -> Self { + Point { x: 0.0, y: 0.0 } + } + + /// Returns true if x and y are both zero. + pub fn is_zero(&self) -> bool { + self.x == 0.0 && self.y == 0.0 + } + + /// Returns true if both x and y are measurable values. + /// + /// Both values are other than infinities and NaN. + pub fn is_finite(&self) -> bool { + (self.x * self.y).is_finite() + } + + /// Checks that two `Point`s are almost equal. + pub(crate) fn almost_equal(&self, other: Point) -> bool { + !(*self - other).can_normalize() + } + + /// Checks that two `Point`s are almost equal using the specified tolerance. + pub(crate) fn equals_within_tolerance(&self, other: Point, tolerance: f32) -> bool { + (self.x - other.x).is_nearly_zero_within_tolerance(tolerance) + && (self.y - other.y).is_nearly_zero_within_tolerance(tolerance) + } + + /// Scales (fX, fY) so that length() returns one, while preserving ratio of fX to fY, + /// if possible. + /// + /// If prior length is nearly zero, sets vector to (0, 0) and returns + /// false; otherwise returns true. + pub fn normalize(&mut self) -> bool { + self.set_length_from(self.x, self.y, 1.0) + } + + /// Sets vector to (x, y) scaled so length() returns one, and so that (x, y) + /// is proportional to (x, y). + /// + /// If (x, y) length is nearly zero, sets vector to (0, 0) and returns false; + /// otherwise returns true. + pub fn set_normalize(&mut self, x: f32, y: f32) -> bool { + self.set_length_from(x, y, 1.0) + } + + pub(crate) fn can_normalize(&self) -> bool { + self.x.is_finite() && self.y.is_finite() && (self.x != 0.0 || self.y != 0.0) + } + + /// Returns the Euclidean distance from origin. + pub fn length(&self) -> f32 { + let mag2 = self.x * self.x + self.y * self.y; + if mag2.is_finite() { + mag2.sqrt() + } else { + let xx = f64::from(self.x); + let yy = f64::from(self.y); + (xx * xx + yy * yy).sqrt() as f32 + } + } + + /// Scales vector so that distanceToOrigin() returns length, if possible. + /// + /// If former length is nearly zero, sets vector to (0, 0) and return false; + /// otherwise returns true. + pub fn set_length(&mut self, length: f32) -> bool { + self.set_length_from(self.x, self.y, length) + } + + /// Sets vector to (x, y) scaled to length, if possible. + /// + /// If former length is nearly zero, sets vector to (0, 0) and return false; + /// otherwise returns true. + pub fn set_length_from(&mut self, x: f32, y: f32, length: f32) -> bool { + set_point_length(self, x, y, length, &mut None) + } + + /// Returns the Euclidean distance from origin. + pub fn distance(&self, other: Point) -> f32 { + (*self - other).length() + } + + /// Returns the dot product of two points. + pub fn dot(&self, other: Point) -> f32 { + self.x * other.x + self.y * other.y + } + + /// Returns the cross product of vector and vec. + /// + /// Vector and vec form three-dimensional vectors with z-axis value equal to zero. + /// The cross product is a three-dimensional vector with x-axis and y-axis values + /// equal to zero. The cross product z-axis component is returned. + pub fn cross(&self, other: Point) -> f32 { + self.x * other.y - self.y * other.x + } + + pub(crate) fn distance_to_sqd(&self, pt: Point) -> f32 { + let dx = self.x - pt.x; + let dy = self.y - pt.y; + dx * dx + dy * dy + } + + pub(crate) fn length_sqd(&self) -> f32 { + self.dot(*self) + } + + /// Scales Point in-place by scale. + pub fn scale(&mut self, scale: f32) { + self.x *= scale; + self.y *= scale; + } + + pub(crate) fn scaled(&self, scale: f32) -> Self { + Point::from_xy(self.x * scale, self.y * scale) + } + + pub(crate) fn swap_coords(&mut self) { + core::mem::swap(&mut self.x, &mut self.y); + } + + pub(crate) fn rotate_cw(&mut self) { + self.swap_coords(); + self.x = -self.x; + } + + pub(crate) fn rotate_ccw(&mut self) { + self.swap_coords(); + self.y = -self.y; + } +} + +// We have to worry about 2 tricky conditions: +// 1. underflow of mag2 (compared against nearlyzero^2) +// 2. overflow of mag2 (compared w/ isfinite) +// +// If we underflow, we return false. If we overflow, we compute again using +// doubles, which is much slower (3x in a desktop test) but will not overflow. +fn set_point_length( + pt: &mut Point, + mut x: f32, + mut y: f32, + length: f32, + orig_length: &mut Option<f32>, +) -> bool { + // our mag2 step overflowed to infinity, so use doubles instead. + // much slower, but needed when x or y are very large, other wise we + // divide by inf. and return (0,0) vector. + let xx = x as f64; + let yy = y as f64; + let dmag = (xx * xx + yy * yy).sqrt(); + let dscale = length as f64 / dmag; + // As Skia's `set_point_length`: the float times the double, rounded once. + x = (x as f64 * dscale) as f32; + y = (y as f64 * dscale) as f32; + + // check if we're not finite, or we're zero-length + if !x.is_finite() || !y.is_finite() || (x == 0.0 && y == 0.0) { + *pt = Point::zero(); + return false; + } + + let mut mag = 0.0; + if orig_length.is_some() { + mag = dmag as f32; + } + + *pt = Point::from_xy(x, y); + + if orig_length.is_some() { + *orig_length = Some(mag); + } + + true +} + +impl core::ops::Neg for Point { + type Output = Point; + + fn neg(self) -> Self::Output { + Point { + x: -self.x, + y: -self.y, + } + } +} + +impl core::ops::Add for Point { + type Output = Point; + + fn add(self, other: Point) -> Self::Output { + Point::from_xy(self.x + other.x, self.y + other.y) + } +} + +impl core::ops::AddAssign for Point { + fn add_assign(&mut self, other: Point) { + self.x += other.x; + self.y += other.y; + } +} + +impl core::ops::Sub for Point { + type Output = Point; + + fn sub(self, other: Point) -> Self::Output { + Point::from_xy(self.x - other.x, self.y - other.y) + } +} + +impl core::ops::SubAssign for Point { + fn sub_assign(&mut self, other: Point) { + self.x -= other.x; + self.y -= other.y; + } +} + +impl core::ops::Mul for Point { + type Output = Point; + + fn mul(self, other: Point) -> Self::Output { + Point::from_xy(self.x * other.x, self.y * other.y) + } +} + +impl core::ops::MulAssign for Point { + fn mul_assign(&mut self, other: Point) { + self.x *= other.x; + self.y *= other.y; + } +} diff --git a/app/vendor/rune/vendor/tiny-skia-path/src/path.rs b/app/vendor/rune/vendor/tiny-skia-path/src/path.rs new file mode 100644 index 0000000..89695d9 --- /dev/null +++ b/app/vendor/rune/vendor/tiny-skia-path/src/path.rs @@ -0,0 +1,411 @@ +// Copyright 2006 The Android Open Source Project +// Copyright 2020 Yevhenii Reizner +// +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +use alloc::vec::Vec; + +use crate::path_builder::PathBuilder; +use crate::transform::Transform; +use crate::{Point, Rect}; + +#[cfg(all(not(feature = "std"), feature = "no-std-float"))] +use crate::NoStdFloat; + +/// A path verb. +#[allow(missing_docs)] +#[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Debug)] +pub enum PathVerb { + Move, + Line, + Quad, + Cubic, + /// Only in a path built with `PathBuilder::set_keep_conics`. + Conic, + Close, +} + +/// A Bezier path. +/// +/// Can be created via [`PathBuilder`]. +/// Where [`PathBuilder`] can be created from the [`Path`] using [`clear`] to reuse the allocation. +/// +/// Path is immutable and uses compact storage, where segment types and numbers are stored +/// separately. Use can access path segments via [`Path::verbs`] and [`Path::points`], +/// or via [`Path::segments`] +/// +/// # Guarantees +/// +/// - Has a valid, precomputed bounds. +/// - All points are finite. +/// - Has at least two segments. +/// - Each contour starts with a MoveTo. +/// - No duplicated Move. +/// - No duplicated Close. +/// - Zero-length contours are allowed. +/// +/// [`PathBuilder`]: struct.PathBuilder.html +/// [`clear`]: struct.Path.html#method.clear +#[derive(Clone, PartialEq)] +pub struct Path { + pub(crate) verbs: Vec<PathVerb>, + pub(crate) points: Vec<Point>, + /// Each conic's weight, in order. + pub(crate) weights: Vec<f32>, + pub(crate) bounds: Rect, +} + +impl Path { + /// Returns the number of segments in the path. + pub fn len(&self) -> usize { + self.verbs.len() + } + + /// Return if the path is empty. + pub fn is_empty(&self) -> bool { + self.verbs.is_empty() + } + + /// Returns the bounds of the path's points. + /// + /// The value is already calculated. + pub fn bounds(&self) -> Rect { + self.bounds + } + + /// Calculates path's tight bounds. + /// + /// This operation can be expensive. + pub fn compute_tight_bounds(&self) -> Option<Rect> { + // big enough to hold worst-case curve type (cubic) extremas + 1 + let mut extremas = [Point::zero(); 5]; + + let mut min = self.points[0]; + let mut max = self.points[0]; + let mut iter = self.segments(); + let mut last_point = Point::zero(); + while let Some(segment) = iter.next() { + let mut count = 0; + match segment { + PathSegment::MoveTo(p) => { + extremas[0] = p; + count = 1; + } + PathSegment::LineTo(p) => { + extremas[0] = p; + count = 1; + } + PathSegment::QuadTo(p0, p1) | PathSegment::ConicTo(p0, p1, _) => { + count = compute_quad_extremas(last_point, p0, p1, &mut extremas); + } + PathSegment::CubicTo(p0, p1, p2) => { + count = compute_cubic_extremas(last_point, p0, p1, p2, &mut extremas); + } + PathSegment::Close => {} + } + + last_point = iter.last_point; + for tmp in &extremas[0..count] { + min.x = min.x.min(tmp.x); + min.y = min.y.min(tmp.y); + max.x = max.x.max(tmp.x); + max.y = max.y.max(tmp.y); + } + } + + Rect::from_ltrb(min.x, min.y, max.x, max.y) + } + + /// Returns an internal vector of verbs. + pub fn verbs(&self) -> &[PathVerb] { + &self.verbs + } + + /// Returns an internal vector of points. + pub fn points(&self) -> &[Point] { + &self.points + } + + /// Returns each conic's weight, in order. + pub fn weights(&self) -> &[f32] { + &self.weights + } + + /// Returns a transformed in-place path. + /// + /// Some points may become NaN/inf therefore this method can fail. + pub fn transform(mut self, ts: Transform) -> Option<Self> { + if ts.is_identity() { + return Some(self); + } + + ts.map_points(&mut self.points); + + // Update bounds. + self.bounds = Rect::from_points(&self.points)?; + + Some(self) + } + + /// Returns an iterator over path's segments. + pub fn segments(&self) -> PathSegmentsIter { + PathSegmentsIter { + path: self, + verb_index: 0, + points_index: 0, + weight_index: 0, + is_auto_close: false, + last_move_to: Point::zero(), + last_point: Point::zero(), + } + } + + /// Clears the path and returns a `PathBuilder` that will reuse an allocated memory. + pub fn clear(mut self) -> PathBuilder { + self.verbs.clear(); + self.points.clear(); + + PathBuilder { + verbs: self.verbs, + points: self.points, + weights: alloc::vec::Vec::new(), + keep_conics: false, + last_move_to_index: 0, + move_to_required: true, + conic_tolerance: 0.0, + } + } +} + +impl core::fmt::Debug for Path { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + use core::fmt::Write; + + let mut s = alloc::string::String::new(); + for segment in self.segments() { + match segment { + PathSegment::MoveTo(p) => s.write_fmt(format_args!("M {} {} ", p.x, p.y))?, + PathSegment::LineTo(p) => s.write_fmt(format_args!("L {} {} ", p.x, p.y))?, + PathSegment::QuadTo(p0, p1) => { + s.write_fmt(format_args!("Q {} {} {} {} ", p0.x, p0.y, p1.x, p1.y))? + } + PathSegment::CubicTo(p0, p1, p2) => s.write_fmt(format_args!( + "C {} {} {} {} {} {} ", + p0.x, p0.y, p1.x, p1.y, p2.x, p2.y + ))?, + PathSegment::ConicTo(p0, p1, w) => s.write_fmt(format_args!( + "K {} {} {} {} {} ", + p0.x, p0.y, p1.x, p1.y, w + ))?, + PathSegment::Close => s.write_fmt(format_args!("Z "))?, + } + } + + s.pop(); // ' ' + + f.debug_struct("Path") + .field("segments", &s) + .field("bounds", &self.bounds) + .finish() + } +} + +fn compute_quad_extremas(p0: Point, p1: Point, p2: Point, extremas: &mut [Point; 5]) -> usize { + use crate::path_geometry; + + let src = [p0, p1, p2]; + let mut extrema_idx = 0; + if let Some(t) = path_geometry::find_quad_extrema(p0.x, p1.x, p2.x) { + extremas[extrema_idx] = path_geometry::eval_quad_at(&src, t.to_normalized()); + extrema_idx += 1; + } + if let Some(t) = path_geometry::find_quad_extrema(p0.y, p1.y, p2.y) { + extremas[extrema_idx] = path_geometry::eval_quad_at(&src, t.to_normalized()); + extrema_idx += 1; + } + extremas[extrema_idx] = p2; + extrema_idx + 1 +} + +fn compute_cubic_extremas( + p0: Point, + p1: Point, + p2: Point, + p3: Point, + extremas: &mut [Point; 5], +) -> usize { + use crate::path_geometry; + + let mut ts0 = path_geometry::new_t_values(); + let mut ts1 = path_geometry::new_t_values(); + let n0 = path_geometry::find_cubic_extrema(p0.x, p1.x, p2.x, p3.x, &mut ts0); + let n1 = path_geometry::find_cubic_extrema(p0.y, p1.y, p2.y, p3.y, &mut ts1); + let total_len = n0 + n1; + debug_assert!(total_len <= 4); + + let src = [p0, p1, p2, p3]; + let mut extrema_idx = 0; + for t in &ts0[0..n0] { + extremas[extrema_idx] = path_geometry::eval_cubic_pos_at(&src, t.to_normalized()); + extrema_idx += 1; + } + for t in &ts1[0..n1] { + extremas[extrema_idx] = path_geometry::eval_cubic_pos_at(&src, t.to_normalized()); + extrema_idx += 1; + } + extremas[total_len] = p3; + total_len + 1 +} + +/// A path segment. +#[allow(missing_docs)] +#[derive(Copy, Clone, PartialEq, Debug)] +pub enum PathSegment { + MoveTo(Point), + LineTo(Point), + QuadTo(Point, Point), + CubicTo(Point, Point, Point), + /// A conic's control point, end and weight. + ConicTo(Point, Point, f32), + Close, +} + +/// A path segments iterator. +#[allow(missing_debug_implementations)] +#[derive(Clone)] +pub struct PathSegmentsIter<'a> { + path: &'a Path, + verb_index: usize, + points_index: usize, + weight_index: usize, + + is_auto_close: bool, + last_move_to: Point, + last_point: Point, +} + +impl<'a> PathSegmentsIter<'a> { + /// Sets the auto closing mode. Off by default. + /// + /// When enabled, emits an additional `PathSegment::Line` from the current position + /// to the previous `PathSegment::Move`. And only then emits `PathSegment::Close`. + pub fn set_auto_close(&mut self, flag: bool) { + self.is_auto_close = flag; + } + + pub(crate) fn auto_close(&mut self) -> PathSegment { + if self.is_auto_close && self.last_point != self.last_move_to { + self.verb_index -= 1; + PathSegment::LineTo(self.last_move_to) + } else { + PathSegment::Close + } + } + + pub(crate) fn has_valid_tangent(&self) -> bool { + let mut iter = self.clone(); + while let Some(segment) = iter.next() { + match segment { + PathSegment::MoveTo(_) => { + return false; + } + PathSegment::LineTo(p) => { + if iter.last_point == p { + continue; + } + + return true; + } + PathSegment::QuadTo(p1, p2) | PathSegment::ConicTo(p1, p2, _) => { + if iter.last_point == p1 && iter.last_point == p2 { + continue; + } + + return true; + } + PathSegment::CubicTo(p1, p2, p3) => { + if iter.last_point == p1 && iter.last_point == p2 && iter.last_point == p3 { + continue; + } + + return true; + } + PathSegment::Close => { + return false; + } + } + } + + false + } + + /// Returns the current verb. + pub fn curr_verb(&self) -> PathVerb { + self.path.verbs[self.verb_index - 1] + } + + /// Returns the next verb. + pub fn next_verb(&self) -> Option<PathVerb> { + self.path.verbs.get(self.verb_index).cloned() + } +} + +impl<'a> Iterator for PathSegmentsIter<'a> { + type Item = PathSegment; + + fn next(&mut self) -> Option<Self::Item> { + if self.verb_index < self.path.verbs.len() { + let verb = self.path.verbs[self.verb_index]; + self.verb_index += 1; + + match verb { + PathVerb::Move => { + self.points_index += 1; + self.last_move_to = self.path.points[self.points_index - 1]; + self.last_point = self.last_move_to; + Some(PathSegment::MoveTo(self.last_move_to)) + } + PathVerb::Line => { + self.points_index += 1; + self.last_point = self.path.points[self.points_index - 1]; + Some(PathSegment::LineTo(self.last_point)) + } + PathVerb::Quad => { + self.points_index += 2; + self.last_point = self.path.points[self.points_index - 1]; + Some(PathSegment::QuadTo( + self.path.points[self.points_index - 2], + self.last_point, + )) + } + PathVerb::Cubic => { + self.points_index += 3; + self.last_point = self.path.points[self.points_index - 1]; + Some(PathSegment::CubicTo( + self.path.points[self.points_index - 3], + self.path.points[self.points_index - 2], + self.last_point, + )) + } + PathVerb::Conic => { + self.points_index += 2; + self.weight_index += 1; + self.last_point = self.path.points[self.points_index - 1]; + Some(PathSegment::ConicTo( + self.path.points[self.points_index - 2], + self.last_point, + self.path.weights[self.weight_index - 1], + )) + } + PathVerb::Close => { + let seg = self.auto_close(); + self.last_point = self.last_move_to; + Some(seg) + } + } + } else { + None + } + } +} diff --git a/app/vendor/rune/vendor/tiny-skia-path/src/path_builder.rs b/app/vendor/rune/vendor/tiny-skia-path/src/path_builder.rs new file mode 100644 index 0000000..619962f --- /dev/null +++ b/app/vendor/rune/vendor/tiny-skia-path/src/path_builder.rs @@ -0,0 +1,474 @@ +// Copyright 2006 The Android Open Source Project +// Copyright 2020 Yevhenii Reizner +// +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +// NOTE: this is not SkPathBuilder, but rather a reimplementation of SkPath. + +use alloc::vec; +use alloc::vec::Vec; + +use crate::{Path, Point, Rect}; + +use crate::path::PathVerb; +use crate::path_geometry; +use crate::scalar::{Scalar, SCALAR_ROOT_2_OVER_2}; + +#[derive(Copy, Clone, PartialEq, Debug)] +pub(crate) enum PathDirection { + /// Clockwise direction for adding closed contours. + CW, + /// Counter-clockwise direction for adding closed contours. + CCW, +} + +/// A path builder. +#[derive(Clone, Default, Debug)] +pub struct PathBuilder { + pub(crate) verbs: Vec<PathVerb>, + pub(crate) points: Vec<Point>, + pub(crate) last_move_to_index: usize, + pub(crate) move_to_required: bool, + /// How far, in this path's units, the quads a conic becomes may stray from it: Skia's 0.25 of + /// a device pixel. 0 (the default) is 0.25; a stroker sets its own from its resolution scale. + pub(crate) conic_tolerance: f32, + /// Each conic's weight, where `keep_conics` keeps them as conics. + pub(crate) weights: Vec<f32>, + /// Whether `conic_to` keeps a conic, as Skia's paths do, rather than cutting it into quads. + pub(crate) keep_conics: bool, +} + +impl PathBuilder { + /// Creates a new builder. + pub fn new() -> Self { + PathBuilder { + verbs: Vec::new(), + points: Vec::new(), + last_move_to_index: 0, + move_to_required: true, + conic_tolerance: 0.0, + weights: Vec::new(), + keep_conics: false, + } + } + + /// Creates a new builder with a specified capacity. + /// + /// Number of points depends on a verb type: + /// + /// - Move - 1 + /// - Line - 1 + /// - Quad - 2 + /// - Cubic - 3 + /// - Close - 0 + pub fn with_capacity(verbs_capacity: usize, points_capacity: usize) -> Self { + PathBuilder { + verbs: Vec::with_capacity(verbs_capacity), + points: Vec::with_capacity(points_capacity), + last_move_to_index: 0, + move_to_required: true, + conic_tolerance: 0.0, + weights: Vec::new(), + keep_conics: false, + } + } + + /// Creates a new `Path` from `Rect`. + /// + /// Never fails since `Rect` is always valid. + /// + /// Segments are created clockwise: TopLeft -> TopRight -> BottomRight -> BottomLeft + /// + /// The contour is closed. + pub fn from_rect(rect: Rect) -> Path { + let verbs = vec![ + PathVerb::Move, + PathVerb::Line, + PathVerb::Line, + PathVerb::Line, + PathVerb::Close, + ]; + + let points = vec![ + Point::from_xy(rect.left(), rect.top()), + Point::from_xy(rect.right(), rect.top()), + Point::from_xy(rect.right(), rect.bottom()), + Point::from_xy(rect.left(), rect.bottom()), + ]; + + Path { + bounds: rect, + verbs, + points, + weights: Vec::new(), + } + } + + /// Creates a new `Path` from a circle. + /// + /// See [`PathBuilder::push_circle`] for details. + pub fn from_circle(cx: f32, cy: f32, radius: f32) -> Option<Path> { + let mut b = PathBuilder::new(); + b.push_circle(cx, cy, radius); + b.finish() + } + + /// Creates a new `Path` from an oval. + /// + /// See [`PathBuilder::push_oval`] for details. + pub fn from_oval(oval: Rect) -> Option<Path> { + let mut b = PathBuilder::new(); + b.push_oval(oval); + b.finish() + } + + pub(crate) fn reserve(&mut self, additional_verbs: usize, additional_points: usize) { + self.verbs.reserve(additional_verbs); + self.points.reserve(additional_points); + } + + /// Keeps each conic `conic_to` adds as a conic, as Skia's own paths do (the stroker then strokes + /// it as one), rather than cutting it into quads. + pub fn set_keep_conics(&mut self, keep: bool) { + self.keep_conics = keep; + } + + /// Sets how far, in this path's units, the quads each conic is turned into may stray from it + /// (Skia: 0.25 of a device pixel, so 0.25 over the scale the path will be drawn at). + pub fn set_conic_tolerance(&mut self, tolerance: f32) { + self.conic_tolerance = tolerance; + } + + /// Returns the current number of segments in the builder. + pub fn len(&self) -> usize { + self.verbs.len() + } + + /// Checks if the builder has any segments added. + pub fn is_empty(&self) -> bool { + self.verbs.is_empty() + } + + /// Adds beginning of a contour. + /// + /// Multiple continuous MoveTo segments are not allowed. + /// If the previous segment was also MoveTo, it will be overwritten with the current one. + pub fn move_to(&mut self, x: f32, y: f32) { + if let Some(PathVerb::Move) = self.verbs.last() { + let last_idx = self.points.len() - 1; + self.points[last_idx] = Point::from_xy(x, y); + } else { + self.last_move_to_index = self.points.len(); + self.move_to_required = false; + + self.verbs.push(PathVerb::Move); + self.points.push(Point::from_xy(x, y)); + } + } + + fn inject_move_to_if_needed(&mut self) { + if self.move_to_required { + match self.points.get(self.last_move_to_index).cloned() { + Some(p) => self.move_to(p.x, p.y), + None => self.move_to(0.0, 0.0), + } + } + } + + /// Adds a line from the last point. + /// + /// - If `Path` is empty - adds Move(0, 0) first. + /// - If `Path` ends with Close - adds Move(last_x, last_y) first. + pub fn line_to(&mut self, x: f32, y: f32) { + self.inject_move_to_if_needed(); + + self.verbs.push(PathVerb::Line); + self.points.push(Point::from_xy(x, y)); + } + + /// Adds a quad curve from the last point to `x`, `y`. + /// + /// - If `Path` is empty - adds Move(0, 0) first. + /// - If `Path` ends with Close - adds Move(last_x, last_y) first. + pub fn quad_to(&mut self, x1: f32, y1: f32, x: f32, y: f32) { + self.inject_move_to_if_needed(); + + self.verbs.push(PathVerb::Quad); + self.points.push(Point::from_xy(x1, y1)); + self.points.push(Point::from_xy(x, y)); + } + + pub(crate) fn quad_to_pt(&mut self, p1: Point, p: Point) { + self.quad_to(p1.x, p1.y, p.x, p.y); + } + + // We do not support conic segments, but Skia still relies on them from time to time. + // This method will simply convert the input data into quad segments. + pub fn conic_to(&mut self, x1: f32, y1: f32, x: f32, y: f32, weight: f32) { + // check for <= 0 or NaN with this test + if !(weight > 0.0) { + self.line_to(x, y); + } else if !weight.is_finite() { + self.line_to(x1, y1); + self.line_to(x, y); + } else if weight == 1.0 { + self.quad_to(x1, y1, x, y); + } else if self.keep_conics { + self.inject_move_to_if_needed(); + self.verbs.push(PathVerb::Conic); + self.points.push(Point::from_xy(x1, y1)); + self.points.push(Point::from_xy(x, y)); + self.weights.push(weight); + } else { + self.inject_move_to_if_needed(); + + let last = self.last_point().unwrap(); + let tolerance = if self.conic_tolerance > 0.0 { self.conic_tolerance } else { 0.25 }; + let quadder = path_geometry::AutoConicToQuads::compute( + last, + Point::from_xy(x1, y1), + Point::from_xy(x, y), + weight, + tolerance, + ); + if let Some(quadder) = quadder { + // Points are ordered as: 0 - 1 2 - 3 4 - 5 6 - .. + // `count` is a number of pairs +1 + let mut offset = 1; + for _ in 0..quadder.len { + let pt1 = quadder.points[offset + 0]; + let pt2 = quadder.points[offset + 1]; + self.quad_to(pt1.x, pt1.y, pt2.x, pt2.y); + offset += 2; + } + } + } + } + + pub(crate) fn conic_points_to(&mut self, pt1: Point, pt2: Point, weight: f32) { + self.conic_to(pt1.x, pt1.y, pt2.x, pt2.y, weight); + } + + /// Adds a cubic curve from the last point to `x`, `y`. + /// + /// - If `Path` is empty - adds Move(0, 0) first. + /// - If `Path` ends with Close - adds Move(last_x, last_y) first. + pub fn cubic_to(&mut self, x1: f32, y1: f32, x2: f32, y2: f32, x: f32, y: f32) { + self.inject_move_to_if_needed(); + + self.verbs.push(PathVerb::Cubic); + self.points.push(Point::from_xy(x1, y1)); + self.points.push(Point::from_xy(x2, y2)); + self.points.push(Point::from_xy(x, y)); + } + + pub(crate) fn cubic_to_pt(&mut self, p1: Point, p2: Point, p: Point) { + self.cubic_to(p1.x, p1.y, p2.x, p2.y, p.x, p.y); + } + + /// Closes the current contour. + /// + /// A closed contour connects the first and the last Point + /// with a line, forming a continuous loop. + /// + /// Does nothing when `Path` is empty or already closed. + /// + /// Open and closed contour will be filled the same way. + /// Stroking an open contour will add LineCap at contour's start and end. + /// Stroking an closed contour will add LineJoin at contour's start and end. + pub fn close(&mut self) { + // don't add a close if it's the first verb or a repeat + if !self.verbs.is_empty() { + if self.verbs.last().cloned() != Some(PathVerb::Close) { + self.verbs.push(PathVerb::Close); + } + } + + self.move_to_required = true; + } + + /// Returns the last point if any. + pub fn last_point(&self) -> Option<Point> { + self.points.last().cloned() + } + + pub(crate) fn set_last_point(&mut self, pt: Point) { + match self.points.last_mut() { + Some(last) => *last = pt, + None => self.move_to(pt.x, pt.y), + } + } + + pub(crate) fn is_zero_length_since_point(&self, start_pt_index: usize) -> bool { + let count = self.points.len() - start_pt_index; + if count < 2 { + return true; + } + + let first = self.points[start_pt_index]; + for i in 1..count { + if first != self.points[start_pt_index + i] { + return false; + } + } + + true + } + + /// Adds a rectangle contour. + /// + /// The contour is closed and has a clock-wise direction. + pub fn push_rect(&mut self, rect: Rect) { + self.move_to(rect.left(), rect.top()); + self.line_to(rect.right(), rect.top()); + self.line_to(rect.right(), rect.bottom()); + self.line_to(rect.left(), rect.bottom()); + self.close(); + } + + /// Adds an oval contour bounded by the provided rectangle. + /// + /// The contour is closed and has a clock-wise direction. + pub fn push_oval(&mut self, oval: Rect) { + let cx = oval.left().half() + oval.right().half(); + let cy = oval.top().half() + oval.bottom().half(); + + let oval_points = [ + Point::from_xy(cx, oval.bottom()), + Point::from_xy(oval.left(), cy), + Point::from_xy(cx, oval.top()), + Point::from_xy(oval.right(), cy), + ]; + + let rect_points = [ + Point::from_xy(oval.right(), oval.bottom()), + Point::from_xy(oval.left(), oval.bottom()), + Point::from_xy(oval.left(), oval.top()), + Point::from_xy(oval.right(), oval.top()), + ]; + + let weight = SCALAR_ROOT_2_OVER_2; + self.move_to(oval_points[3].x, oval_points[3].y); + for (p1, p2) in rect_points.iter().zip(oval_points.iter()) { + self.conic_points_to(*p1, *p2, weight); + } + self.close(); + } + + /// Adds a circle contour. + /// + /// The contour is closed and has a clock-wise direction. + /// + /// Does nothing when: + /// - `radius` <= 0 + /// - any value is not finite or really large + pub fn push_circle(&mut self, x: f32, y: f32, r: f32) { + if let Some(r) = Rect::from_xywh(x - r, y - r, r + r, r + r) { + self.push_oval(r); + } + } + + /// Adds a path. + pub fn push_path(&mut self, other: &Path) { + self.last_move_to_index = self.points.len(); + + self.verbs.extend_from_slice(&other.verbs); + self.points.extend_from_slice(&other.points); + self.weights.extend_from_slice(&other.weights); + } + + pub(crate) fn push_path_builder(&mut self, other: &PathBuilder) { + if other.is_empty() { + return; + } + + if self.last_move_to_index != 0 { + self.last_move_to_index = self.points.len() + other.last_move_to_index; + } + + self.verbs.extend_from_slice(&other.verbs); + self.points.extend_from_slice(&other.points); + self.weights.extend_from_slice(&other.weights); + } + + /// Appends, in a reverse order, the first contour of path ignoring path's last point. + pub(crate) fn reverse_path_to(&mut self, other: &PathBuilder) { + if other.is_empty() { + return; + } + + debug_assert_eq!(other.verbs[0], PathVerb::Move); + + let mut points_offset = other.points.len() - 1; + for verb in other.verbs.iter().rev() { + match verb { + PathVerb::Move => { + // if the path has multiple contours, stop after reversing the last + break; + } + PathVerb::Line => { + // We're moving one point back manually, to prevent points_offset overflow. + let pt = other.points[points_offset - 1]; + points_offset -= 1; + self.line_to(pt.x, pt.y); + } + PathVerb::Quad => { + let pt1 = other.points[points_offset - 1]; + let pt2 = other.points[points_offset - 2]; + points_offset -= 2; + self.quad_to(pt1.x, pt1.y, pt2.x, pt2.y); + } + PathVerb::Cubic => { + let pt1 = other.points[points_offset - 1]; + let pt2 = other.points[points_offset - 2]; + let pt3 = other.points[points_offset - 3]; + points_offset -= 3; + self.cubic_to(pt1.x, pt1.y, pt2.x, pt2.y, pt3.x, pt3.y); + } + PathVerb::Conic => { + // A stroker's own builders never keep conics. + let pt1 = other.points[points_offset - 1]; + let pt2 = other.points[points_offset - 2]; + points_offset -= 2; + self.quad_to(pt1.x, pt1.y, pt2.x, pt2.y); + } + PathVerb::Close => {} + } + } + } + + /// Reset the builder. + /// + /// Memory is not deallocated. + pub fn clear(&mut self) { + self.verbs.clear(); + self.points.clear(); + self.weights.clear(); + self.last_move_to_index = 0; + self.move_to_required = true; + } + + /// Finishes the builder and returns a `Path`. + /// + /// Returns `None` when `Path` is empty or has invalid bounds. + pub fn finish(self) -> Option<Path> { + if self.is_empty() { + return None; + } + + // Just a move to? Bail. + if self.verbs.len() == 1 { + return None; + } + + let bounds = Rect::from_points(&self.points)?; + + Some(Path { + bounds, + verbs: self.verbs, + points: self.points, + weights: self.weights, + }) + } +} diff --git a/app/vendor/rune/vendor/tiny-skia-path/src/path_geometry.rs b/app/vendor/rune/vendor/tiny-skia-path/src/path_geometry.rs new file mode 100644 index 0000000..3132f5c --- /dev/null +++ b/app/vendor/rune/vendor/tiny-skia-path/src/path_geometry.rs @@ -0,0 +1,926 @@ +// Copyright 2006 The Android Open Source Project +// Copyright 2020 Yevhenii Reizner +// +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +//! A collection of functions to work with Bezier paths. +//! +//! Mainly for internal use. Do not rely on it! + +#![allow(missing_docs)] + +use crate::{Point, Transform}; + +use crate::f32x2_t::f32x2; +use crate::floating_point::FLOAT_PI; +use crate::scalar::{Scalar, SCALAR_NEARLY_ZERO, SCALAR_ROOT_2_OVER_2}; + +use crate::floating_point::{NormalizedF32, NormalizedF32Exclusive}; +use crate::path_builder::PathDirection; + +#[cfg(all(not(feature = "std"), feature = "no-std-float"))] +use crate::NoStdFloat; + +// use for : eval(t) == A * t^2 + B * t + C +#[derive(Clone, Copy, Default, Debug)] +pub struct QuadCoeff { + pub a: f32x2, + pub b: f32x2, + pub c: f32x2, +} + +impl QuadCoeff { + pub fn from_points(points: &[Point; 3]) -> Self { + let c = points[0].to_f32x2(); + let p1 = points[1].to_f32x2(); + let p2 = points[2].to_f32x2(); + let b = times_2(p1 - c); + let a = p2 - times_2(p1) + c; + + QuadCoeff { a, b, c } + } + + pub fn eval(&self, t: f32x2) -> f32x2 { + (self.a * t + self.b) * t + self.c + } +} + +#[derive(Clone, Copy, Default, Debug)] +pub struct CubicCoeff { + pub a: f32x2, + pub b: f32x2, + pub c: f32x2, + pub d: f32x2, +} + +impl CubicCoeff { + pub fn from_points(points: &[Point; 4]) -> Self { + let p0 = points[0].to_f32x2(); + let p1 = points[1].to_f32x2(); + let p2 = points[2].to_f32x2(); + let p3 = points[3].to_f32x2(); + let three = f32x2::splat(3.0); + + CubicCoeff { + a: p3 + three * (p1 - p2) - p0, + b: three * (p2 - times_2(p1) + p0), + c: three * (p1 - p0), + d: p0, + } + } + + pub fn eval(&self, t: f32x2) -> f32x2 { + ((self.a * t + self.b) * t + self.c) * t + self.d + } +} + +// TODO: to a custom type? +pub fn new_t_values() -> [NormalizedF32Exclusive; 3] { + [NormalizedF32Exclusive::ANY; 3] +} + +pub fn chop_quad_at(src: &[Point], t: NormalizedF32Exclusive, dst: &mut [Point; 5]) { + let p0 = src[0].to_f32x2(); + let p1 = src[1].to_f32x2(); + let p2 = src[2].to_f32x2(); + let tt = f32x2::splat(t.get()); + + let p01 = interp(p0, p1, tt); + let p12 = interp(p1, p2, tt); + + dst[0] = Point::from_f32x2(p0); + dst[1] = Point::from_f32x2(p01); + dst[2] = Point::from_f32x2(interp(p01, p12, tt)); + dst[3] = Point::from_f32x2(p12); + dst[4] = Point::from_f32x2(p2); +} + +// From Numerical Recipes in C. +// +// Q = -1/2 (B + sign(B) sqrt[B*B - 4*A*C]) +// x1 = Q / A +// x2 = C / Q +pub fn find_unit_quad_roots( + a: f32, + b: f32, + c: f32, + roots: &mut [NormalizedF32Exclusive; 3], +) -> usize { + if a == 0.0 { + if let Some(r) = valid_unit_divide(-c, b) { + roots[0] = r; + return 1; + } else { + return 0; + } + } + + // use doubles so we don't overflow temporarily trying to compute R + let mut dr = f64::from(b) * f64::from(b) - 4.0 * f64::from(a) * f64::from(c); + if dr < 0.0 { + return 0; + } + dr = dr.sqrt(); + let r = dr as f32; + if !r.is_finite() { + return 0; + } + + let q = if b < 0.0 { + -(b - r) / 2.0 + } else { + -(b + r) / 2.0 + }; + + let mut roots_offset = 0; + if let Some(r) = valid_unit_divide(q, a) { + roots[roots_offset] = r; + roots_offset += 1; + } + + if let Some(r) = valid_unit_divide(c, q) { + roots[roots_offset] = r; + roots_offset += 1; + } + + if roots_offset == 2 { + if roots[0].get() > roots[1].get() { + roots.swap(0, 1); + } else if roots[0] == roots[1] { + // nearly-equal? + roots_offset -= 1; // skip the double root + } + } + + roots_offset +} + +pub fn chop_cubic_at2(src: &[Point; 4], t: NormalizedF32Exclusive, dst: &mut [Point]) { + let p0 = src[0].to_f32x2(); + let p1 = src[1].to_f32x2(); + let p2 = src[2].to_f32x2(); + let p3 = src[3].to_f32x2(); + let tt = f32x2::splat(t.get()); + + let ab = interp(p0, p1, tt); + let bc = interp(p1, p2, tt); + let cd = interp(p2, p3, tt); + let abc = interp(ab, bc, tt); + let bcd = interp(bc, cd, tt); + let abcd = interp(abc, bcd, tt); + + dst[0] = Point::from_f32x2(p0); + dst[1] = Point::from_f32x2(ab); + dst[2] = Point::from_f32x2(abc); + dst[3] = Point::from_f32x2(abcd); + dst[4] = Point::from_f32x2(bcd); + dst[5] = Point::from_f32x2(cd); + dst[6] = Point::from_f32x2(p3); +} + +// Quad'(t) = At + B, where +// A = 2(a - 2b + c) +// B = 2(b - a) +// Solve for t, only if it fits between 0 < t < 1 +pub(crate) fn find_quad_extrema(a: f32, b: f32, c: f32) -> Option<NormalizedF32Exclusive> { + // At + B == 0 + // t = -B / A + valid_unit_divide(a - b, a - b - b + c) +} + +pub fn valid_unit_divide(mut numer: f32, mut denom: f32) -> Option<NormalizedF32Exclusive> { + if numer < 0.0 { + numer = -numer; + denom = -denom; + } + + if denom == 0.0 || numer == 0.0 || numer >= denom { + return None; + } + + let r = numer / denom; + NormalizedF32Exclusive::new(r) +} + +fn interp(v0: f32x2, v1: f32x2, t: f32x2) -> f32x2 { + v0 + (v1 - v0) * t +} + +fn times_2(value: f32x2) -> f32x2 { + value + value +} + +// F(t) = a (1 - t) ^ 2 + 2 b t (1 - t) + c t ^ 2 +// F'(t) = 2 (b - a) + 2 (a - 2b + c) t +// F''(t) = 2 (a - 2b + c) +// +// A = 2 (b - a) +// B = 2 (a - 2b + c) +// +// Maximum curvature for a quadratic means solving +// Fx' Fx'' + Fy' Fy'' = 0 +// +// t = - (Ax Bx + Ay By) / (Bx ^ 2 + By ^ 2) +pub(crate) fn find_quad_max_curvature(src: &[Point; 3]) -> NormalizedF32 { + let ax = src[1].x - src[0].x; + let ay = src[1].y - src[0].y; + let bx = src[0].x - src[1].x - src[1].x + src[2].x; + let by = src[0].y - src[1].y - src[1].y + src[2].y; + + let mut numer = -(ax * bx + ay * by); + let mut denom = bx * bx + by * by; + if denom < 0.0 { + numer = -numer; + denom = -denom; + } + + if numer <= 0.0 { + return NormalizedF32::ZERO; + } + + if numer >= denom { + // Also catches denom=0 + return NormalizedF32::ONE; + } + + let t = numer / denom; + NormalizedF32::new(t).unwrap() +} + +pub(crate) fn eval_quad_at(src: &[Point; 3], t: NormalizedF32) -> Point { + Point::from_f32x2(QuadCoeff::from_points(src).eval(f32x2::splat(t.get()))) +} + +pub(crate) fn eval_quad_tangent_at(src: &[Point; 3], tol: NormalizedF32) -> Point { + // The derivative equation is 2(b - a +(a - 2b +c)t). This returns a + // zero tangent vector when t is 0 or 1, and the control point is equal + // to the end point. In this case, use the quad end points to compute the tangent. + if (tol == NormalizedF32::ZERO && src[0] == src[1]) + || (tol == NormalizedF32::ONE && src[1] == src[2]) + { + return src[2] - src[0]; + } + + let p0 = src[0].to_f32x2(); + let p1 = src[1].to_f32x2(); + let p2 = src[2].to_f32x2(); + + let b = p1 - p0; + let a = p2 - p1 - b; + let t = a * f32x2::splat(tol.get()) + b; + + Point::from_f32x2(t + t) +} + +// Looking for F' dot F'' == 0 +// +// A = b - a +// B = c - 2b + a +// C = d - 3c + 3b - a +// +// F' = 3Ct^2 + 6Bt + 3A +// F'' = 6Ct + 6B +// +// F' dot F'' -> CCt^3 + 3BCt^2 + (2BB + CA)t + AB +pub fn find_cubic_max_curvature<'a>( + src: &[Point; 4], + t_values: &'a mut [NormalizedF32; 3], +) -> &'a [NormalizedF32] { + let mut coeff_x = formulate_f1_dot_f2(&[src[0].x, src[1].x, src[2].x, src[3].x]); + let coeff_y = formulate_f1_dot_f2(&[src[0].y, src[1].y, src[2].y, src[3].y]); + + for i in 0..4 { + coeff_x[i] += coeff_y[i]; + } + + let len = solve_cubic_poly(&coeff_x, t_values); + &t_values[0..len] +} + +// Looking for F' dot F'' == 0 +// +// A = b - a +// B = c - 2b + a +// C = d - 3c + 3b - a +// +// F' = 3Ct^2 + 6Bt + 3A +// F'' = 6Ct + 6B +// +// F' dot F'' -> CCt^3 + 3BCt^2 + (2BB + CA)t + AB +fn formulate_f1_dot_f2(src: &[f32; 4]) -> [f32; 4] { + let a = src[1] - src[0]; + let b = src[2] - 2.0 * src[1] + src[0]; + let c = src[3] + 3.0 * (src[1] - src[2]) - src[0]; + + [c * c, 3.0 * b * c, 2.0 * b * b + c * a, a * b] +} + +/// Solve coeff(t) == 0, returning the number of roots that lie withing 0 < t < 1. +/// coeff[0]t^3 + coeff[1]t^2 + coeff[2]t + coeff[3] +/// +/// Eliminates repeated roots (so that all t_values are distinct, and are always +/// in increasing order. +fn solve_cubic_poly(coeff: &[f32; 4], t_values: &mut [NormalizedF32; 3]) -> usize { + if coeff[0].is_nearly_zero() { + // we're just a quadratic + let mut tmp_t = new_t_values(); + let count = find_unit_quad_roots(coeff[1], coeff[2], coeff[3], &mut tmp_t); + for i in 0..count { + t_values[i] = tmp_t[i].to_normalized(); + } + + return count; + } + + debug_assert!(coeff[0] != 0.0); + + let inva = coeff[0].invert(); + let a = coeff[1] * inva; + let b = coeff[2] * inva; + let c = coeff[3] * inva; + + let q = (a * a - b * 3.0) / 9.0; + let r = (2.0 * a * a * a - 9.0 * a * b + 27.0 * c) / 54.0; + + let q3 = q * q * q; + let r2_minus_q3 = r * r - q3; + let adiv3 = a / 3.0; + + if r2_minus_q3 < 0.0 { + // we have 3 real roots + // the divide/root can, due to finite precisions, be slightly outside of -1...1 + let theta = (r / q3.sqrt()).bound(-1.0, 1.0).acos(); + let neg2_root_q = -2.0 * q.sqrt(); + + t_values[0] = NormalizedF32::new_clamped(neg2_root_q * (theta / 3.0).cos() - adiv3); + t_values[1] = NormalizedF32::new_clamped( + neg2_root_q * ((theta + 2.0 * FLOAT_PI) / 3.0).cos() - adiv3, + ); + t_values[2] = NormalizedF32::new_clamped( + neg2_root_q * ((theta - 2.0 * FLOAT_PI) / 3.0).cos() - adiv3, + ); + + // now sort the roots + sort_array3(t_values); + collapse_duplicates3(t_values) + } else { + // we have 1 real root + let mut a = r.abs() + r2_minus_q3.sqrt(); + a = scalar_cube_root(a); + if r > 0.0 { + a = -a; + } + + if a != 0.0 { + a += q / a; + } + + t_values[0] = NormalizedF32::new_clamped(a - adiv3); + 1 + } +} + +fn sort_array3(array: &mut [NormalizedF32; 3]) { + if array[0] > array[1] { + array.swap(0, 1); + } + + if array[1] > array[2] { + array.swap(1, 2); + } + + if array[0] > array[1] { + array.swap(0, 1); + } +} + +fn collapse_duplicates3(array: &mut [NormalizedF32; 3]) -> usize { + let mut len = 3; + + if array[1] == array[2] { + len = 2; + } + + if array[0] == array[1] { + len = 1; + } + + len +} + +fn scalar_cube_root(x: f32) -> f32 { + x.powf(0.3333333) +} + +// This is SkEvalCubicAt split into three functions. +pub(crate) fn eval_cubic_pos_at(src: &[Point; 4], t: NormalizedF32) -> Point { + Point::from_f32x2(CubicCoeff::from_points(src).eval(f32x2::splat(t.get()))) +} + +// This is SkEvalCubicAt split into three functions. +pub(crate) fn eval_cubic_tangent_at(src: &[Point; 4], t: NormalizedF32) -> Point { + // The derivative equation returns a zero tangent vector when t is 0 or 1, and the + // adjacent control point is equal to the end point. In this case, use the + // next control point or the end points to compute the tangent. + if (t.get() == 0.0 && src[0] == src[1]) || (t.get() == 1.0 && src[2] == src[3]) { + let mut tangent = if t.get() == 0.0 { + src[2] - src[0] + } else { + src[3] - src[1] + }; + + if tangent.x == 0.0 && tangent.y == 0.0 { + tangent = src[3] - src[0]; + } + + tangent + } else { + eval_cubic_derivative(src, t) + } +} + +fn eval_cubic_derivative(src: &[Point; 4], t: NormalizedF32) -> Point { + let p0 = src[0].to_f32x2(); + let p1 = src[1].to_f32x2(); + let p2 = src[2].to_f32x2(); + let p3 = src[3].to_f32x2(); + + let coeff = QuadCoeff { + a: p3 + f32x2::splat(3.0) * (p1 - p2) - p0, + b: times_2(p2 - times_2(p1) + p0), + c: p1 - p0, + }; + + Point::from_f32x2(coeff.eval(f32x2::splat(t.get()))) +} + +// Cubic'(t) = At^2 + Bt + C, where +// A = 3(-a + 3(b - c) + d) +// B = 6(a - 2b + c) +// C = 3(b - a) +// Solve for t, keeping only those that fit between 0 < t < 1 +pub(crate) fn find_cubic_extrema( + a: f32, + b: f32, + c: f32, + d: f32, + t_values: &mut [NormalizedF32Exclusive; 3], +) -> usize { + // we divide A,B,C by 3 to simplify + let aa = d - a + 3.0 * (b - c); + let bb = 2.0 * (a - b - b + c); + let cc = b - a; + + find_unit_quad_roots(aa, bb, cc, t_values) +} + +// http://www.faculty.idc.ac.il/arik/quality/appendixA.html +// +// Inflection means that curvature is zero. +// Curvature is [F' x F''] / [F'^3] +// So we solve F'x X F''y - F'y X F''y == 0 +// After some canceling of the cubic term, we get +// A = b - a +// B = c - 2b + a +// C = d - 3c + 3b - a +// (BxCy - ByCx)t^2 + (AxCy - AyCx)t + AxBy - AyBx == 0 +pub(crate) fn find_cubic_inflections<'a>( + src: &[Point; 4], + t_values: &'a mut [NormalizedF32Exclusive; 3], +) -> &'a [NormalizedF32Exclusive] { + let ax = src[1].x - src[0].x; + let ay = src[1].y - src[0].y; + let bx = src[2].x - 2.0 * src[1].x + src[0].x; + let by = src[2].y - 2.0 * src[1].y + src[0].y; + let cx = src[3].x + 3.0 * (src[1].x - src[2].x) - src[0].x; + let cy = src[3].y + 3.0 * (src[1].y - src[2].y) - src[0].y; + + let len = find_unit_quad_roots( + bx * cy - by * cx, + ax * cy - ay * cx, + ax * by - ay * bx, + t_values, + ); + + &t_values[0..len] +} + +// Return location (in t) of cubic cusp, if there is one. +// Note that classify cubic code does not reliably return all cusp'd cubics, so +// it is not called here. +pub(crate) fn find_cubic_cusp(src: &[Point; 4]) -> Option<NormalizedF32Exclusive> { + // When the adjacent control point matches the end point, it behaves as if + // the cubic has a cusp: there's a point of max curvature where the derivative + // goes to zero. Ideally, this would be where t is zero or one, but math + // error makes not so. It is not uncommon to create cubics this way; skip them. + if src[0] == src[1] { + return None; + } + + if src[2] == src[3] { + return None; + } + + // Cubics only have a cusp if the line segments formed by the control and end points cross. + // Detect crossing if line ends are on opposite sides of plane formed by the other line. + if on_same_side(src, 0, 2) || on_same_side(src, 2, 0) { + return None; + } + + // Cubics may have multiple points of maximum curvature, although at most only + // one is a cusp. + let mut t_values = [NormalizedF32::ZERO; 3]; + let max_curvature = find_cubic_max_curvature(src, &mut t_values); + for test_t in max_curvature { + if 0.0 >= test_t.get() || test_t.get() >= 1.0 { + // no need to consider max curvature on the end + continue; + } + + // A cusp is at the max curvature, and also has a derivative close to zero. + // Choose the 'close to zero' meaning by comparing the derivative length + // with the overall cubic size. + let d_pt = eval_cubic_derivative(src, *test_t); + let d_pt_magnitude = d_pt.length_sqd(); + let precision = calc_cubic_precision(src); + if d_pt_magnitude < precision { + // All three max curvature t values may be close to the cusp; + // return the first one. + return Some(NormalizedF32Exclusive::new_bounded(test_t.get())); + } + } + + None +} + +// Returns true if both points src[testIndex], src[testIndex+1] are in the same half plane defined +// by the line segment src[lineIndex], src[lineIndex+1]. +fn on_same_side(src: &[Point; 4], test_index: usize, line_index: usize) -> bool { + let origin = src[line_index]; + let line = src[line_index + 1] - origin; + let mut crosses = [0.0, 0.0]; + for index in 0..2 { + let test_line = src[test_index + index] - origin; + crosses[index] = line.cross(test_line); + } + + crosses[0] * crosses[1] >= 0.0 +} + +// Returns a constant proportional to the dimensions of the cubic. +// Constant found through experimentation -- maybe there's a better way.... +fn calc_cubic_precision(src: &[Point; 4]) -> f32 { + (src[1].distance_to_sqd(src[0]) + + src[2].distance_to_sqd(src[1]) + + src[3].distance_to_sqd(src[2])) + * 1e-8 +} + +#[derive(Copy, Clone, Default, Debug)] +pub(crate) struct Conic { + pub points: [Point; 3], + pub weight: f32, +} + +impl Conic { + pub fn new(pt0: Point, pt1: Point, pt2: Point, weight: f32) -> Self { + Conic { + points: [pt0, pt1, pt2], + weight, + } + } + + pub fn from_points(points: &[Point], weight: f32) -> Self { + Conic { + points: [points[0], points[1], points[2]], + weight, + } + } + + fn compute_quad_pow2(&self, tolerance: f32) -> Option<u8> { + if tolerance < 0.0 || !tolerance.is_finite() { + return None; + } + + if !self.points[0].is_finite() || !self.points[1].is_finite() || !self.points[2].is_finite() + { + return None; + } + + // Limit the number of suggested quads to approximate a conic + const MAX_CONIC_TO_QUAD_POW2: usize = 4; + + // "High order approximation of conic sections by quadratic splines" + // by Michael Floater, 1993 + let a = self.weight - 1.0; + let k = a / (4.0 * (2.0 + a)); + let x = k * (self.points[0].x - 2.0 * self.points[1].x + self.points[2].x); + let y = k * (self.points[0].y - 2.0 * self.points[1].y + self.points[2].y); + + let mut error = (x * x + y * y).sqrt(); + let mut pow2 = 0; + for _ in 0..MAX_CONIC_TO_QUAD_POW2 { + if error <= tolerance { + break; + } + + error *= 0.25; + pow2 += 1; + } + + // As Skia: a conic within the tolerance of its hull's quad is that one quad. + Some(pow2) + } + + // Chop this conic into N quads, stored continuously in pts[], where + // N = 1 << pow2. The amount of storage needed is (1 + 2 * N) + pub fn chop_into_quads_pow2(&self, pow2: u8, points: &mut [Point]) -> u8 { + debug_assert!(pow2 < 5); + + points[0] = self.points[0]; + subdivide(self, &mut points[1..], pow2); + + let quad_count = 1 << pow2; + let pt_count = 2 * quad_count + 1; + if points.iter().take(pt_count).any(|n| !n.is_finite()) { + // if we generated a non-finite, pin ourselves to the middle of the hull, + // as our first and last are already on the first/last pts of the hull. + for p in points.iter_mut().take(pt_count - 1).skip(1) { + *p = self.points[1]; + } + } + + 1 << pow2 + } + + fn chop(&self) -> (Conic, Conic) { + let scale = f32x2::splat((1.0 + self.weight).invert()); + let new_w = subdivide_weight_value(self.weight); + + let p0 = self.points[0].to_f32x2(); + let p1 = self.points[1].to_f32x2(); + let p2 = self.points[2].to_f32x2(); + let ww = f32x2::splat(self.weight); + + let wp1 = ww * p1; + let m = (p0 + times_2(wp1) + p2) * scale * f32x2::splat(0.5); + let mut m_pt = Point::from_f32x2(m); + if !m_pt.is_finite() { + let w_d = self.weight as f64; + let w_2 = w_d * 2.0; + let scale_half = 1.0 / (1.0 + w_d) * 0.5; + m_pt.x = ((self.points[0].x as f64 + + w_2 * self.points[1].x as f64 + + self.points[2].x as f64) + * scale_half) as f32; + + m_pt.y = ((self.points[0].y as f64 + + w_2 * self.points[1].y as f64 + + self.points[2].y as f64) + * scale_half) as f32; + } + + ( + Conic { + points: [self.points[0], Point::from_f32x2((p0 + wp1) * scale), m_pt], + weight: new_w, + }, + Conic { + points: [m_pt, Point::from_f32x2((wp1 + p2) * scale), self.points[2]], + weight: new_w, + }, + ) + } + + pub fn build_unit_arc( + u_start: Point, + u_stop: Point, + dir: PathDirection, + user_transform: Transform, + dst: &mut [Conic; 5], + ) -> Option<&[Conic]> { + // rotate by x,y so that u_start is (1.0) + let x = u_start.dot(u_stop); + let mut y = u_start.cross(u_stop); + + let abs_y = y.abs(); + + // check for (effectively) coincident vectors + // this can happen if our angle is nearly 0 or nearly 180 (y == 0) + // ... we use the dot-prod to distinguish between 0 and 180 (x > 0) + if abs_y <= SCALAR_NEARLY_ZERO + && x > 0.0 + && ((y >= 0.0 && dir == PathDirection::CW) || (y <= 0.0 && dir == PathDirection::CCW)) + { + return None; + } + + if dir == PathDirection::CCW { + y = -y; + } + + // We decide to use 1-conic per quadrant of a circle. What quadrant does [xy] lie in? + // 0 == [0 .. 90) + // 1 == [90 ..180) + // 2 == [180..270) + // 3 == [270..360) + // + let mut quadrant = 0; + if y == 0.0 { + quadrant = 2; // 180 + debug_assert!((x + 1.0) <= SCALAR_NEARLY_ZERO); + } else if x == 0.0 { + debug_assert!(abs_y - 1.0 <= SCALAR_NEARLY_ZERO); + quadrant = if y > 0.0 { 1 } else { 3 }; // 90 / 270 + } else { + if y < 0.0 { + quadrant += 2; + } + + if (x < 0.0) != (y < 0.0) { + quadrant += 1; + } + } + + let quadrant_points = [ + Point::from_xy(1.0, 0.0), + Point::from_xy(1.0, 1.0), + Point::from_xy(0.0, 1.0), + Point::from_xy(-1.0, 1.0), + Point::from_xy(-1.0, 0.0), + Point::from_xy(-1.0, -1.0), + Point::from_xy(0.0, -1.0), + Point::from_xy(1.0, -1.0), + ]; + + const QUADRANT_WEIGHT: f32 = SCALAR_ROOT_2_OVER_2; + + let mut conic_count = quadrant; + for i in 0..conic_count { + dst[i] = Conic::from_points(&quadrant_points[i * 2..], QUADRANT_WEIGHT); + } + + // Now compute any remaing (sub-90-degree) arc for the last conic + let final_pt = Point::from_xy(x, y); + let last_q = quadrant_points[quadrant * 2]; // will already be a unit-vector + let dot = last_q.dot(final_pt); + debug_assert!(0.0 <= dot && dot <= 1.0 + SCALAR_NEARLY_ZERO); + + if dot < 1.0 { + let mut off_curve = Point::from_xy(last_q.x + x, last_q.y + y); + // compute the bisector vector, and then rescale to be the off-curve point. + // we compute its length from cos(theta/2) = length / 1, using half-angle identity we get + // length = sqrt(2 / (1 + cos(theta)). We already have cos() when to computed the dot. + // This is nice, since our computed weight is cos(theta/2) as well! + let cos_theta_over_2 = ((1.0 + dot) / 2.0).sqrt(); + off_curve.set_length(cos_theta_over_2.invert()); + if !last_q.almost_equal(off_curve) { + dst[conic_count] = Conic::new(last_q, off_curve, final_pt, cos_theta_over_2); + conic_count += 1; + } + } + + // now handle counter-clockwise and the initial unitStart rotation + let mut transform = Transform::from_sin_cos(u_start.y, u_start.x); + if dir == PathDirection::CCW { + transform = transform.pre_scale(1.0, -1.0); + } + + transform = transform.post_concat(user_transform); + + for conic in dst.iter_mut().take(conic_count) { + transform.map_points(&mut conic.points); + } + + if conic_count == 0 { + None + } else { + Some(&dst[0..conic_count]) + } + } +} + +fn subdivide_weight_value(w: f32) -> f32 { + (0.5 + w * 0.5).sqrt() +} + +fn subdivide<'a>(src: &Conic, mut points: &'a mut [Point], mut level: u8) -> &'a mut [Point] { + if level == 0 { + points[0] = src.points[1]; + points[1] = src.points[2]; + &mut points[2..] + } else { + let mut dst = src.chop(); + + let start_y = src.points[0].y; + let end_y = src.points[2].y; + if between(start_y, src.points[1].y, end_y) { + // If the input is monotonic and the output is not, the scan converter hangs. + // Ensure that the chopped conics maintain their y-order. + let mid_y = dst.0.points[2].y; + if !between(start_y, mid_y, end_y) { + // If the computed midpoint is outside the ends, move it to the closer one. + let closer_y = if (mid_y - start_y).abs() < (mid_y - end_y).abs() { + start_y + } else { + end_y + }; + dst.0.points[2].y = closer_y; + dst.1.points[0].y = closer_y; + } + + if !between(start_y, dst.0.points[1].y, dst.0.points[2].y) { + // If the 1st control is not between the start and end, put it at the start. + // This also reduces the quad to a line. + dst.0.points[1].y = start_y; + } + + if !between(dst.1.points[0].y, dst.1.points[1].y, end_y) { + // If the 2nd control is not between the start and end, put it at the end. + // This also reduces the quad to a line. + dst.1.points[1].y = end_y; + } + + // Verify that all five points are in order. + debug_assert!(between(start_y, dst.0.points[1].y, dst.0.points[2].y)); + debug_assert!(between( + dst.0.points[1].y, + dst.0.points[2].y, + dst.1.points[1].y + )); + debug_assert!(between(dst.0.points[2].y, dst.1.points[1].y, end_y)); + } + + level -= 1; + points = subdivide(&dst.0, points, level); + subdivide(&dst.1, points, level) + } +} + +// This was originally developed and tested for pathops: see SkOpTypes.h +// returns true if (a <= b <= c) || (a >= b >= c) +fn between(a: f32, b: f32, c: f32) -> bool { + (a - b) * (c - b) <= 0.0 +} + +pub struct AutoConicToQuads { + pub points: [Point; 64], + pub len: u8, // the number of quads +} + +impl AutoConicToQuads { + pub fn compute(pt0: Point, pt1: Point, pt2: Point, weight: f32, tolerance: f32) -> Option<Self> { + let conic = Conic::new(pt0, pt1, pt2, weight); + let pow2 = conic.compute_quad_pow2(tolerance)?; + let mut points = [Point::zero(); 64]; + let len = conic.chop_into_quads_pow2(pow2, &mut points); + Some(AutoConicToQuads { points, len }) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn eval_cubic_at_1() { + let src = [ + Point::from_xy(30.0, 40.0), + Point::from_xy(30.0, 40.0), + Point::from_xy(171.0, 45.0), + Point::from_xy(180.0, 155.0), + ]; + + assert_eq!( + eval_cubic_pos_at(&src, NormalizedF32::ZERO), + Point::from_xy(30.0, 40.0) + ); + assert_eq!( + eval_cubic_tangent_at(&src, NormalizedF32::ZERO), + Point::from_xy(141.0, 5.0) + ); + } + + #[test] + fn find_cubic_max_curvature_1() { + let src = [ + Point::from_xy(20.0, 160.0), + Point::from_xy(20.0001, 160.0), + Point::from_xy(160.0, 20.0), + Point::from_xy(160.0001, 20.0), + ]; + + let mut t_values = [NormalizedF32::ZERO; 3]; + let t_values = find_cubic_max_curvature(&src, &mut t_values); + + assert_eq!( + &t_values, + &[ + NormalizedF32::ZERO, + NormalizedF32::new_clamped(0.5), + NormalizedF32::ONE, + ] + ); + } +} diff --git a/app/vendor/rune/vendor/tiny-skia-path/src/rect.rs b/app/vendor/rune/vendor/tiny-skia-path/src/rect.rs new file mode 100644 index 0000000..79b5bea --- /dev/null +++ b/app/vendor/rune/vendor/tiny-skia-path/src/rect.rs @@ -0,0 +1,640 @@ +// Copyright 2020 Yevhenii Reizner +// +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +use core::convert::TryFrom; + +use crate::{FiniteF32, IntSize, LengthU32, PathBuilder, Point, SaturateRound, Size, Transform}; + +#[cfg(all(not(feature = "std"), feature = "no-std-float"))] +use crate::NoStdFloat; + +/// An integer rectangle. +/// +/// # Guarantees +/// +/// - Width and height are in 1..=i32::MAX range. +/// - x+width and y+height does not overflow. +#[allow(missing_docs)] +#[derive(Copy, Clone, PartialEq, Debug)] +pub struct IntRect { + x: i32, + y: i32, + width: LengthU32, + height: LengthU32, +} + +impl IntRect { + /// Creates a new `IntRect`. + pub fn from_xywh(x: i32, y: i32, width: u32, height: u32) -> Option<Self> { + x.checked_add(i32::try_from(width).ok()?)?; + y.checked_add(i32::try_from(height).ok()?)?; + + Some(IntRect { + x, + y, + width: LengthU32::new(width)?, + height: LengthU32::new(height)?, + }) + } + + /// Creates a new `IntRect`. + pub fn from_ltrb(left: i32, top: i32, right: i32, bottom: i32) -> Option<Self> { + let width = u32::try_from(right.checked_sub(left)?).ok()?; + let height = u32::try_from(bottom.checked_sub(top)?).ok()?; + IntRect::from_xywh(left, top, width, height) + } + + /// Returns rect's X position. + pub fn x(&self) -> i32 { + self.x + } + + /// Returns rect's Y position. + pub fn y(&self) -> i32 { + self.y + } + + /// Returns rect's width. + pub fn width(&self) -> u32 { + self.width.get() + } + + /// Returns rect's height. + pub fn height(&self) -> u32 { + self.height.get() + } + + /// Returns rect's left edge. + pub fn left(&self) -> i32 { + self.x + } + + /// Returns rect's top edge. + pub fn top(&self) -> i32 { + self.y + } + + /// Returns rect's right edge. + pub fn right(&self) -> i32 { + // No overflow is guaranteed by constructors. + self.x + self.width.get() as i32 + } + + /// Returns rect's bottom edge. + pub fn bottom(&self) -> i32 { + // No overflow is guaranteed by constructors. + self.y + self.height.get() as i32 + } + + /// Returns rect's size. + pub fn size(&self) -> IntSize { + IntSize::from_wh_safe(self.width, self.height) + } + + /// Checks that the rect is completely includes `other` Rect. + pub fn contains(&self, other: &Self) -> bool { + self.x <= other.x + && self.y <= other.y + && self.right() >= other.right() + && self.bottom() >= other.bottom() + } + + /// Returns an intersection of two rectangles. + /// + /// Returns `None` otherwise. + pub fn intersect(&self, other: &Self) -> Option<Self> { + let left = self.x.max(other.x); + let top = self.y.max(other.y); + + let right = self.right().min(other.right()); + let bottom = self.bottom().min(other.bottom()); + + let w = u32::try_from(right.checked_sub(left)?).ok()?; + let h = u32::try_from(bottom.checked_sub(top)?).ok()?; + + IntRect::from_xywh(left, top, w, h) + } + + /// Insets the rectangle. + pub fn inset(&self, dx: i32, dy: i32) -> Option<Self> { + IntRect::from_ltrb( + self.left() + dx, + self.top() + dy, + self.right() - dx, + self.bottom() - dy, + ) + } + + /// Outsets the rectangle. + pub fn make_outset(&self, dx: i32, dy: i32) -> Option<Self> { + IntRect::from_ltrb( + self.left().saturating_sub(dx), + self.top().saturating_sub(dy), + self.right().saturating_add(dx), + self.bottom().saturating_add(dy), + ) + } + + /// Translates the rect by the specified offset. + pub fn translate(&self, tx: i32, ty: i32) -> Option<Self> { + IntRect::from_xywh(self.x() + tx, self.y() + ty, self.width(), self.height()) + } + + /// Translates the rect to the specified position. + pub fn translate_to(&self, x: i32, y: i32) -> Option<Self> { + IntRect::from_xywh(x, y, self.width(), self.height()) + } + + /// Converts into `Rect`. + pub fn to_rect(&self) -> Rect { + // Can't fail, because `IntRect` is always valid. + Rect::from_ltrb( + self.x as f32, + self.y as f32, + self.x as f32 + self.width.get() as f32, + self.y as f32 + self.height.get() as f32, + ) + .unwrap() + } +} + +#[cfg(test)] +mod int_rect_tests { + use super::*; + + #[test] + fn tests() { + assert_eq!(IntRect::from_xywh(0, 0, 0, 0), None); + assert_eq!(IntRect::from_xywh(0, 0, 1, 0), None); + assert_eq!(IntRect::from_xywh(0, 0, 0, 1), None); + + assert_eq!(IntRect::from_xywh(0, 0, u32::MAX, u32::MAX), None); + assert_eq!(IntRect::from_xywh(0, 0, 1, u32::MAX), None); + assert_eq!(IntRect::from_xywh(0, 0, u32::MAX, 1), None); + + assert_eq!(IntRect::from_xywh(i32::MAX, 0, 1, 1), None); + assert_eq!(IntRect::from_xywh(0, i32::MAX, 1, 1), None); + + { + // No intersection. + let r1 = IntRect::from_xywh(1, 2, 3, 4).unwrap(); + let r2 = IntRect::from_xywh(11, 12, 13, 14).unwrap(); + assert_eq!(r1.intersect(&r2), None); + } + + { + // Second inside the first one. + let r1 = IntRect::from_xywh(1, 2, 30, 40).unwrap(); + let r2 = IntRect::from_xywh(11, 12, 13, 14).unwrap(); + assert_eq!(r1.intersect(&r2), IntRect::from_xywh(11, 12, 13, 14)); + } + + { + // Partial overlap. + let r1 = IntRect::from_xywh(1, 2, 30, 40).unwrap(); + let r2 = IntRect::from_xywh(11, 12, 50, 60).unwrap(); + assert_eq!(r1.intersect(&r2), IntRect::from_xywh(11, 12, 20, 30)); + } + } +} + +/// A rectangle defined by left, top, right and bottom edges. +/// +/// Can have zero width and/or height. But not a negative one. +/// +/// # Guarantees +/// +/// - All values are finite. +/// - Left edge is <= right. +/// - Top edge is <= bottom. +/// - Width and height are <= f32::MAX. +#[allow(missing_docs)] +#[derive(Copy, Clone, PartialEq)] +pub struct Rect { + left: FiniteF32, + top: FiniteF32, + right: FiniteF32, + bottom: FiniteF32, +} + +impl core::fmt::Debug for Rect { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + f.debug_struct("Rect") + .field("left", &self.left.get()) + .field("top", &self.top.get()) + .field("right", &self.right.get()) + .field("bottom", &self.bottom.get()) + .finish() + } +} + +impl Rect { + /// Creates new `Rect`. + pub fn from_ltrb(left: f32, top: f32, right: f32, bottom: f32) -> Option<Self> { + let left = FiniteF32::new(left)?; + let top = FiniteF32::new(top)?; + let right = FiniteF32::new(right)?; + let bottom = FiniteF32::new(bottom)?; + + if left.get() <= right.get() && top.get() <= bottom.get() { + // Width and height must not overflow. + checked_f32_sub(right.get(), left.get())?; + checked_f32_sub(bottom.get(), top.get())?; + + Some(Rect { + left, + top, + right, + bottom, + }) + } else { + None + } + } + + /// Creates new `Rect`. + pub fn from_xywh(x: f32, y: f32, w: f32, h: f32) -> Option<Self> { + Rect::from_ltrb(x, y, w + x, h + y) + } + + /// Returns the left edge. + pub fn left(&self) -> f32 { + self.left.get() + } + + /// Returns the top edge. + pub fn top(&self) -> f32 { + self.top.get() + } + + /// Returns the right edge. + pub fn right(&self) -> f32 { + self.right.get() + } + + /// Returns the bottom edge. + pub fn bottom(&self) -> f32 { + self.bottom.get() + } + + /// Returns rect's X position. + pub fn x(&self) -> f32 { + self.left.get() + } + + /// Returns rect's Y position. + pub fn y(&self) -> f32 { + self.top.get() + } + + /// Returns rect's width. + #[inline] + pub fn width(&self) -> f32 { + self.right.get() - self.left.get() + } + + /// Returns rect's height. + #[inline] + pub fn height(&self) -> f32 { + self.bottom.get() - self.top.get() + } + + /// Converts into an `IntRect` by adding 0.5 and discarding the fractional portion. + /// + /// Width and height are guarantee to be >= 1. + pub fn round(&self) -> Option<IntRect> { + IntRect::from_xywh( + i32::saturate_round(self.x()), + i32::saturate_round(self.y()), + core::cmp::max(1, i32::saturate_round(self.width()) as u32), + core::cmp::max(1, i32::saturate_round(self.height()) as u32), + ) + } + + /// Converts into an `IntRect` rounding outwards. + /// + /// Width and height are guarantee to be >= 1. + pub fn round_out(&self) -> Option<IntRect> { + IntRect::from_xywh( + i32::saturate_floor(self.x()), + i32::saturate_floor(self.y()), + core::cmp::max(1, i32::saturate_ceil(self.width()) as u32), + core::cmp::max(1, i32::saturate_ceil(self.height()) as u32), + ) + } + + /// Returns an intersection of two rectangles. + /// + /// Returns `None` otherwise. + pub fn intersect(&self, other: &Self) -> Option<Self> { + let left = self.x().max(other.x()); + let top = self.y().max(other.y()); + + let right = self.right().min(other.right()); + let bottom = self.bottom().min(other.bottom()); + + Rect::from_ltrb(left, top, right, bottom) + } + + /// Creates a Rect from Point array. + /// + /// Returns None if count is zero or if Point array contains an infinity or NaN. + pub fn from_points(points: &[Point]) -> Option<Self> { + use crate::f32x4_t::f32x4; + + if points.is_empty() { + return None; + } + + let mut offset = 0; + let mut min; + let mut max; + if points.len() & 1 != 0 { + let pt = points[0]; + min = f32x4([pt.x, pt.y, pt.x, pt.y]); + max = min; + offset += 1; + } else { + let pt0 = points[0]; + let pt1 = points[1]; + min = f32x4([pt0.x, pt0.y, pt1.x, pt1.y]); + max = min; + offset += 2; + } + + let mut accum = f32x4::default(); + while offset != points.len() { + let pt0 = points[offset + 0]; + let pt1 = points[offset + 1]; + let xy = f32x4([pt0.x, pt0.y, pt1.x, pt1.y]); + + accum *= xy; + min = min.min(xy); + max = max.max(xy); + offset += 2; + } + + let all_finite = accum * f32x4::default() == f32x4::default(); + let min: [f32; 4] = min.0; + let max: [f32; 4] = max.0; + if all_finite { + Rect::from_ltrb( + min[0].min(min[2]), + min[1].min(min[3]), + max[0].max(max[2]), + max[1].max(max[3]), + ) + } else { + None + } + } + + /// Insets the rectangle by the specified offset. + pub fn inset(&self, dx: f32, dy: f32) -> Option<Self> { + Rect::from_ltrb( + self.left() + dx, + self.top() + dy, + self.right() - dx, + self.bottom() - dy, + ) + } + + /// Outsets the rectangle by the specified offset. + pub fn outset(&self, dx: f32, dy: f32) -> Option<Self> { + self.inset(-dx, -dy) + } + + /// Transforms the rect using the provided `Transform`. + /// + /// This method is expensive. + pub fn transform(&self, ts: Transform) -> Option<Self> { + if !ts.is_identity() { + // TODO: remove allocation + let mut path = PathBuilder::from_rect(*self); + path = path.transform(ts)?; + Some(path.bounds()) + } else { + Some(*self) + } + } + + /// Applies a bounding box transform. + pub fn bbox_transform(&self, bbox: NonZeroRect) -> Self { + let x = self.x() * bbox.width() + bbox.x(); + let y = self.y() * bbox.height() + bbox.y(); + let w = self.width() * bbox.width(); + let h = self.height() * bbox.height(); + Self::from_xywh(x, y, w, h).unwrap() + } + + /// Converts into [`NonZeroRect`]. + pub fn to_non_zero_rect(&self) -> Option<NonZeroRect> { + NonZeroRect::from_xywh(self.x(), self.y(), self.width(), self.height()) + } +} + +fn checked_f32_sub(a: f32, b: f32) -> Option<f32> { + debug_assert!(a.is_finite()); + debug_assert!(b.is_finite()); + + let n = a as f64 - b as f64; + // Not sure if this is perfectly correct. + if n > f32::MIN as f64 && n < f32::MAX as f64 { + Some(n as f32) + } else { + None + } +} + +#[cfg(test)] +mod rect_tests { + use super::*; + + #[test] + fn tests() { + assert_eq!(Rect::from_ltrb(10.0, 10.0, 5.0, 10.0), None); + assert_eq!(Rect::from_ltrb(10.0, 10.0, 10.0, 5.0), None); + assert_eq!(Rect::from_ltrb(f32::NAN, 10.0, 10.0, 10.0), None); + assert_eq!(Rect::from_ltrb(10.0, f32::NAN, 10.0, 10.0), None); + assert_eq!(Rect::from_ltrb(10.0, 10.0, f32::NAN, 10.0), None); + assert_eq!(Rect::from_ltrb(10.0, 10.0, 10.0, f32::NAN), None); + assert_eq!(Rect::from_ltrb(10.0, 10.0, 10.0, f32::INFINITY), None); + + let rect = Rect::from_ltrb(10.0, 20.0, 30.0, 40.0).unwrap(); + assert_eq!(rect.left(), 10.0); + assert_eq!(rect.top(), 20.0); + assert_eq!(rect.right(), 30.0); + assert_eq!(rect.bottom(), 40.0); + assert_eq!(rect.width(), 20.0); + assert_eq!(rect.height(), 20.0); + + let rect = Rect::from_ltrb(-30.0, 20.0, -10.0, 40.0).unwrap(); + assert_eq!(rect.width(), 20.0); + assert_eq!(rect.height(), 20.0); + } + + #[test] + fn round_overflow() { + // minimum value that cause overflow + // because i32::MAX has no exact conversion to f32 + let x = 128.0; + // maximum width + let width = i32::MAX as f32; + + let rect = Rect::from_xywh(x, 0.0, width, 1.0).unwrap(); + assert_eq!(rect.round(), None); + assert_eq!(rect.round_out(), None); + } +} + +/// A rectangle defined by left, top, right and bottom edges. +/// +/// Similar to [`Rect`], but width and height guarantee to be non-zero and positive. +/// +/// # Guarantees +/// +/// - All values are finite. +/// - Left edge is < right. +/// - Top edge is < bottom. +/// - Width and height are <= f32::MAX. +/// - Width and height are > 0.0 +#[allow(missing_docs)] +#[derive(Copy, Clone, PartialEq)] +pub struct NonZeroRect { + left: FiniteF32, + top: FiniteF32, + right: FiniteF32, + bottom: FiniteF32, +} + +impl core::fmt::Debug for NonZeroRect { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + f.debug_struct("NonZeroRect") + .field("left", &self.left.get()) + .field("top", &self.top.get()) + .field("right", &self.right.get()) + .field("bottom", &self.bottom.get()) + .finish() + } +} + +impl NonZeroRect { + /// Creates new `NonZeroRect`. + pub fn from_ltrb(left: f32, top: f32, right: f32, bottom: f32) -> Option<Self> { + let left = FiniteF32::new(left)?; + let top = FiniteF32::new(top)?; + let right = FiniteF32::new(right)?; + let bottom = FiniteF32::new(bottom)?; + + if left.get() < right.get() && top.get() < bottom.get() { + // Width and height must not overflow. + checked_f32_sub(right.get(), left.get())?; + checked_f32_sub(bottom.get(), top.get())?; + + Some(Self { + left, + top, + right, + bottom, + }) + } else { + None + } + } + + /// Creates new `NonZeroRect`. + pub fn from_xywh(x: f32, y: f32, w: f32, h: f32) -> Option<Self> { + Self::from_ltrb(x, y, w + x, h + y) + } + + /// Returns the left edge. + pub fn left(&self) -> f32 { + self.left.get() + } + + /// Returns the top edge. + pub fn top(&self) -> f32 { + self.top.get() + } + + /// Returns the right edge. + pub fn right(&self) -> f32 { + self.right.get() + } + + /// Returns the bottom edge. + pub fn bottom(&self) -> f32 { + self.bottom.get() + } + + /// Returns rect's X position. + pub fn x(&self) -> f32 { + self.left.get() + } + + /// Returns rect's Y position. + pub fn y(&self) -> f32 { + self.top.get() + } + + /// Returns rect's width. + pub fn width(&self) -> f32 { + self.right.get() - self.left.get() + } + + /// Returns rect's height. + pub fn height(&self) -> f32 { + self.bottom.get() - self.top.get() + } + + /// Returns rect's size. + pub fn size(&self) -> Size { + Size::from_wh(self.width(), self.height()).unwrap() + } + + /// Translates the rect to the specified position. + pub fn translate_to(&self, x: f32, y: f32) -> Option<Self> { + Self::from_xywh(x, y, self.width(), self.height()) + } + + /// Transforms the rect using the provided `Transform`. + /// + /// This method is expensive. + pub fn transform(&self, ts: Transform) -> Option<Self> { + if !ts.is_identity() { + // TODO: remove allocation + let mut path = PathBuilder::from_rect(self.to_rect()); + path = path.transform(ts)?; + path.bounds().to_non_zero_rect() + } else { + Some(*self) + } + } + + /// Applies a bounding box transform. + pub fn bbox_transform(&self, bbox: NonZeroRect) -> Self { + let x = self.x() * bbox.width() + bbox.x(); + let y = self.y() * bbox.height() + bbox.y(); + let w = self.width() * bbox.width(); + let h = self.height() * bbox.height(); + Self::from_xywh(x, y, w, h).unwrap() + } + + /// Converts into [`Rect`]. + pub fn to_rect(&self) -> Rect { + Rect::from_xywh(self.x(), self.y(), self.width(), self.height()).unwrap() + } + + /// Converts into [`IntRect`]. + pub fn to_int_rect(&self) -> IntRect { + IntRect::from_xywh( + self.x().floor() as i32, + self.y().floor() as i32, + core::cmp::max(1, self.width().ceil() as u32), + core::cmp::max(1, self.height().ceil() as u32), + ) + .unwrap() + } +} diff --git a/app/vendor/rune/vendor/tiny-skia-path/src/scalar.rs b/app/vendor/rune/vendor/tiny-skia-path/src/scalar.rs new file mode 100644 index 0000000..87a7309 --- /dev/null +++ b/app/vendor/rune/vendor/tiny-skia-path/src/scalar.rs @@ -0,0 +1,175 @@ +// Copyright 2006 The Android Open Source Project +// Copyright 2020 Yevhenii Reizner +// +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +use crate::floating_point::f32_as_2s_compliment; + +#[allow(missing_docs)] +pub const SCALAR_MAX: f32 = 3.402823466e+38; +#[allow(missing_docs)] +pub const SCALAR_NEARLY_ZERO: f32 = 1.0 / (1 << 12) as f32; +#[allow(missing_docs)] +pub const SCALAR_ROOT_2_OVER_2: f32 = 0.707106781; + +/// Float number extension methods. +/// +/// Mainly for internal use. Do not rely on it! +#[allow(missing_docs)] +pub trait Scalar { + fn half(self) -> Self; + fn ave(self, other: Self) -> Self; + fn sqr(self) -> Self; + fn invert(self) -> Self; + fn bound(self, min: Self, max: Self) -> Self; + fn is_nearly_equal(self, other: Self) -> bool; + fn is_nearly_zero(self) -> bool; + fn is_nearly_zero_within_tolerance(self, tolerance: Self) -> bool; + fn almost_dequal_ulps(self, other: Self) -> bool; +} + +impl Scalar for f32 { + fn half(self) -> f32 { + self * 0.5 + } + + fn ave(self, other: Self) -> f32 { + (self + other) * 0.5 + } + + fn sqr(self) -> f32 { + self * self + } + + fn invert(self) -> f32 { + 1.0 / self + } + + // Works just like SkTPin, returning `max` for NaN/inf + /// A non-panicking clamp. + fn bound(self, min: Self, max: Self) -> Self { + max.min(self).max(min) + } + + fn is_nearly_equal(self, other: Self) -> bool { + (self - other).abs() <= SCALAR_NEARLY_ZERO + } + + fn is_nearly_zero(self) -> bool { + self.is_nearly_zero_within_tolerance(SCALAR_NEARLY_ZERO) + } + + fn is_nearly_zero_within_tolerance(self, tolerance: Self) -> bool { + debug_assert!(tolerance >= 0.0); + self.abs() <= tolerance + } + + // From SkPathOpsTypes. + fn almost_dequal_ulps(self, other: Self) -> bool { + const ULPS_EPSILON: i32 = 16; + let a_bits = f32_as_2s_compliment(self); + let b_bits = f32_as_2s_compliment(other); + // Find the difference in ULPs. + a_bits < b_bits + ULPS_EPSILON && b_bits < a_bits + ULPS_EPSILON + } +} + +#[allow(missing_docs)] +#[cfg(all(not(feature = "std"), feature = "no-std-float"))] +pub trait NoStdFloat { + fn trunc(self) -> Self; + fn sqrt(self) -> Self; + fn abs(self) -> Self; + fn sin(self) -> Self; + fn cos(self) -> Self; + fn ceil(self) -> Self; + fn floor(self) -> Self; + fn round(self) -> Self; + fn powf(self, y: Self) -> Self; + fn acos(self) -> Self; +} + +#[cfg(all(not(feature = "std"), feature = "no-std-float"))] +impl NoStdFloat for f32 { + fn trunc(self) -> Self { + libm::truncf(self) + } + fn sqrt(self) -> Self { + libm::sqrtf(self) + } + fn abs(self) -> Self { + libm::fabsf(self) + } + fn sin(self) -> Self { + libm::sinf(self) + } + fn cos(self) -> Self { + libm::cosf(self) + } + fn ceil(self) -> Self { + libm::ceilf(self) + } + fn floor(self) -> Self { + libm::floorf(self) + } + fn round(self) -> Self { + libm::roundf(self) + } + fn powf(self, y: Self) -> Self { + libm::powf(self, y) + } + fn acos(self) -> Self { + libm::acosf(self) + } +} + +#[cfg(all(not(feature = "std"), feature = "no-std-float"))] +impl NoStdFloat for f64 { + fn trunc(self) -> Self { + libm::trunc(self) + } + fn sqrt(self) -> Self { + libm::sqrt(self) + } + fn abs(self) -> Self { + libm::fabs(self) + } + fn sin(self) -> Self { + libm::sin(self) + } + fn cos(self) -> Self { + libm::cos(self) + } + fn ceil(self) -> Self { + libm::ceil(self) + } + fn floor(self) -> Self { + libm::floor(self) + } + fn round(self) -> Self { + libm::round(self) + } + fn powf(self, y: Self) -> Self { + libm::pow(self, y) + } + fn acos(self) -> Self { + libm::acos(self) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn bound() { + assert_eq!(f32::NAN.bound(0.0, 1.0), 1.0); + assert_eq!(f32::INFINITY.bound(0.0, 1.0), 1.0); + assert_eq!(f32::NEG_INFINITY.bound(0.0, 1.0), 0.0); + assert_eq!(f32::EPSILON.bound(0.0, 1.0), f32::EPSILON); + assert_eq!(0.5.bound(0.0, 1.0), 0.5); + assert_eq!((-1.0).bound(0.0, 1.0), 0.0); + assert_eq!(2.0.bound(0.0, 1.0), 1.0); + } +} diff --git a/app/vendor/rune/vendor/tiny-skia-path/src/size.rs b/app/vendor/rune/vendor/tiny-skia-path/src/size.rs new file mode 100644 index 0000000..b32e3d5 --- /dev/null +++ b/app/vendor/rune/vendor/tiny-skia-path/src/size.rs @@ -0,0 +1,199 @@ +// Copyright 2020 Yevhenii Reizner +// +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +use strict_num::NonZeroPositiveF32; + +use crate::{IntRect, LengthU32, NonZeroRect, Rect}; + +#[cfg(all(not(feature = "std"), feature = "no-std-float"))] +use crate::NoStdFloat; + +/// An integer size. +/// +/// # Guarantees +/// +/// - Width and height are positive and non-zero. +#[derive(Copy, Clone, PartialEq, Debug)] +pub struct IntSize { + width: LengthU32, + height: LengthU32, +} + +impl IntSize { + /// Creates a new `IntSize` from width and height. + pub fn from_wh(width: u32, height: u32) -> Option<Self> { + Some(IntSize { + width: LengthU32::new(width)?, + height: LengthU32::new(height)?, + }) + } + + pub(crate) fn from_wh_safe(width: LengthU32, height: LengthU32) -> Self { + IntSize { width, height } + } + + /// Returns width. + pub fn width(&self) -> u32 { + self.width.get() + } + + /// Returns height. + pub fn height(&self) -> u32 { + self.height.get() + } + + /// Returns width and height as a tuple. + pub fn dimensions(&self) -> (u32, u32) { + (self.width(), self.height()) + } + + /// Scales current size by the specified factor. + #[inline] + pub fn scale_by(&self, factor: f32) -> Option<Self> { + Self::from_wh( + (self.width() as f32 * factor).round() as u32, + (self.height() as f32 * factor).round() as u32, + ) + } + + /// Scales current size to the specified size. + #[inline] + pub fn scale_to(&self, to: Self) -> Self { + size_scale(*self, to, false) + } + + /// Scales current size to the specified width. + #[inline] + pub fn scale_to_width(&self, new_width: u32) -> Option<Self> { + let new_height = (new_width as f32 * self.height() as f32 / self.width() as f32).ceil(); + Self::from_wh(new_width, new_height as u32) + } + + /// Scales current size to the specified height. + #[inline] + pub fn scale_to_height(&self, new_height: u32) -> Option<Self> { + let new_width = (new_height as f32 * self.width() as f32 / self.height() as f32).ceil(); + Self::from_wh(new_width as u32, new_height) + } + + /// Converts into [`Size`]. + pub fn to_size(&self) -> Size { + Size::from_wh(self.width() as f32, self.height() as f32).unwrap() + } + + /// Converts into [`IntRect`] at the provided position. + pub fn to_int_rect(&self, x: i32, y: i32) -> IntRect { + IntRect::from_xywh(x, y, self.width(), self.height()).unwrap() + } +} + +fn size_scale(s1: IntSize, s2: IntSize, expand: bool) -> IntSize { + let rw = (s2.height() as f32 * s1.width() as f32 / s1.height() as f32).ceil() as u32; + let with_h = if expand { + rw <= s2.width() + } else { + rw >= s2.width() + }; + + if !with_h { + IntSize::from_wh(rw, s2.height()).unwrap() + } else { + let h = (s2.width() as f32 * s1.height() as f32 / s1.width() as f32).ceil() as u32; + IntSize::from_wh(s2.width(), h).unwrap() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn int_size_tests() { + assert_eq!(IntSize::from_wh(0, 0), None); + assert_eq!(IntSize::from_wh(1, 0), None); + assert_eq!(IntSize::from_wh(0, 1), None); + + let size = IntSize::from_wh(3, 4).unwrap(); + assert_eq!( + size.to_int_rect(1, 2), + IntRect::from_xywh(1, 2, 3, 4).unwrap() + ); + } +} + +/// A size. +/// +/// # Guarantees +/// +/// - Width and height are positive, non-zero and finite. +#[derive(Copy, Clone, PartialEq, Debug)] +pub struct Size { + width: NonZeroPositiveF32, + height: NonZeroPositiveF32, +} + +impl Size { + /// Creates a new `Size` from width and height. + pub fn from_wh(width: f32, height: f32) -> Option<Self> { + Some(Size { + width: NonZeroPositiveF32::new(width)?, + height: NonZeroPositiveF32::new(height)?, + }) + } + + /// Returns width. + pub fn width(&self) -> f32 { + self.width.get() + } + + /// Returns height. + pub fn height(&self) -> f32 { + self.height.get() + } + + /// Scales current size to specified size. + pub fn scale_to(&self, to: Self) -> Self { + size_scale_f64(*self, to, false) + } + + /// Expands current size to specified size. + pub fn expand_to(&self, to: Self) -> Self { + size_scale_f64(*self, to, true) + } + + /// Converts into [`IntSize`]. + pub fn to_int_size(&self) -> IntSize { + IntSize::from_wh( + core::cmp::max(1, self.width().round() as u32), + core::cmp::max(1, self.height().round() as u32), + ) + .unwrap() + } + + /// Converts the current size to `Rect` at provided position. + pub fn to_rect(&self, x: f32, y: f32) -> Option<Rect> { + Rect::from_xywh(x, y, self.width.get(), self.height.get()) + } + + /// Converts the current size to `NonZeroRect` at provided position. + pub fn to_non_zero_rect(&self, x: f32, y: f32) -> NonZeroRect { + NonZeroRect::from_xywh(x, y, self.width.get(), self.height.get()).unwrap() + } +} + +fn size_scale_f64(s1: Size, s2: Size, expand: bool) -> Size { + let rw = s2.height.get() * s1.width.get() / s1.height.get(); + let with_h = if expand { + rw <= s2.width.get() + } else { + rw >= s2.width.get() + }; + if !with_h { + Size::from_wh(rw, s2.height.get()).unwrap() + } else { + let h = s2.width.get() * s1.height.get() / s1.width.get(); + Size::from_wh(s2.width.get(), h).unwrap() + } +} diff --git a/app/vendor/rune/vendor/tiny-skia-path/src/stroker.rs b/app/vendor/rune/vendor/tiny-skia-path/src/stroker.rs new file mode 100644 index 0000000..9ee46d3 --- /dev/null +++ b/app/vendor/rune/vendor/tiny-skia-path/src/stroker.rs @@ -0,0 +1,2413 @@ +// Copyright 2008 The Android Open Source Project +// Copyright 2020 Yevhenii Reizner +// +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +// Based on SkStroke.cpp + +use crate::{Path, Point, Transform}; + +use crate::dash::StrokeDash; +use crate::floating_point::{NonZeroPositiveF32, NormalizedF32, NormalizedF32Exclusive}; +use crate::path::{PathSegment, PathSegmentsIter}; +use crate::path_builder::{PathBuilder, PathDirection}; +use crate::path_geometry; +use crate::scalar::{Scalar, SCALAR_NEARLY_ZERO, SCALAR_ROOT_2_OVER_2}; + +#[cfg(all(not(feature = "std"), feature = "no-std-float"))] +use crate::NoStdFloat; + +struct SwappableBuilders<'a> { + inner: &'a mut PathBuilder, + outer: &'a mut PathBuilder, +} + +impl<'a> SwappableBuilders<'a> { + fn swap(&mut self) { + // Skia swaps pointers to inner and outer builders during joining, + // but not builders itself. So a simple `core::mem::swap` will produce invalid results. + // And if we try to use use `core::mem::swap` on references, like below, + // borrow checker will be unhappy. + // That's why we need this wrapper. Maybe there is a better solution. + core::mem::swap(&mut self.inner, &mut self.outer); + } +} + +/// Stroke properties. +#[derive(Clone, PartialEq, Debug)] +pub struct Stroke { + /// A stroke thickness. + /// + /// Must be >= 0. + /// + /// When set to 0, a hairline stroking will be used. + /// + /// Default: 1.0 + pub width: f32, + + /// The limit at which a sharp corner is drawn beveled. + /// + /// Default: 4.0 + pub miter_limit: f32, + + /// A stroke line cap. + /// + /// Default: Butt + pub line_cap: LineCap, + + /// A stroke line join. + /// + /// Default: Miter + pub line_join: LineJoin, + + /// A stroke dashing properties. + /// + /// Default: None + pub dash: Option<StrokeDash>, +} + +impl Default for Stroke { + fn default() -> Self { + Stroke { + width: 1.0, + miter_limit: 4.0, + line_cap: LineCap::default(), + line_join: LineJoin::default(), + dash: None, + } + } +} + +/// Draws at the beginning and end of an open path contour. +#[derive(Copy, Clone, PartialEq, Debug)] +pub enum LineCap { + /// No stroke extension. + Butt, + /// Adds circle. + Round, + /// Adds square. + Square, +} + +impl Default for LineCap { + fn default() -> Self { + LineCap::Butt + } +} + +/// Specifies how corners are drawn when a shape is stroked. +/// +/// Join affects the four corners of a stroked rectangle, and the connected segments in a +/// stroked path. +/// +/// Choose miter join to draw sharp corners. Choose round join to draw a circle with a +/// radius equal to the stroke width on top of the corner. Choose bevel join to minimally +/// connect the thick strokes. +/// +/// The fill path constructed to describe the stroked path respects the join setting but may +/// not contain the actual join. For instance, a fill path constructed with round joins does +/// not necessarily include circles at each connected segment. +#[derive(Copy, Clone, PartialEq, Debug)] +pub enum LineJoin { + /// Extends to miter limit, then switches to bevel. + Miter, + /// Extends to miter limit, then clips the corner. + MiterClip, + /// Adds circle. + Round, + /// Connects outside edges. + Bevel, +} + +impl Default for LineJoin { + fn default() -> Self { + LineJoin::Miter + } +} + +const QUAD_RECURSIVE_LIMIT: usize = 3; +const CONIC_RECURSIVE_LIMIT: usize = 2; + +// quads with extreme widths (e.g. (0,1) (1,6) (0,3) width=5e7) recurse to point of failure +// largest seen for normal cubics: 5, 26 +// largest seen for normal quads: 11 +const RECURSIVE_LIMITS: [i32; 4] = [5 * 3, 26 * 3, 11 * 3, 11 * 3]; // 3x limits seen in practice + +type CapProc = fn( + pivot: Point, + normal: Point, + stop: Point, + other_path: Option<&PathBuilder>, + path: &mut PathBuilder, +); + +type JoinProc = fn( + before_unit_normal: Point, + pivot: Point, + after_unit_normal: Point, + radius: f32, + inv_miter_limit: f32, + prev_is_line: bool, + curr_is_line: bool, + builders: SwappableBuilders, +); + +#[derive(Copy, Clone, PartialEq, PartialOrd, Debug)] +enum ReductionType { + Point, // all curve points are practically identical + Line, // the control point is on the line between the ends + Quad, // the control point is outside the line between the ends + Degenerate, // the control point is on the line but outside the ends + Degenerate2, // two control points are on the line but outside ends (cubic) + Degenerate3, // three areas of max curvature found (for cubic) +} + +#[derive(Copy, Clone, PartialEq, Debug)] +enum StrokeType { + Outer = 1, // use sign-opposite values later to flip perpendicular axis + Inner = -1, +} + +#[derive(Copy, Clone, PartialEq, Debug)] +enum ResultType { + Split, // the caller should split the quad stroke in two + Degenerate, // the caller should add a line + Quad, // the caller should (continue to try to) add a quad stroke +} + +#[derive(Copy, Clone, PartialEq, Debug)] +enum IntersectRayType { + CtrlPt, + ResultType, +} + +impl Path { + /// Returns a stoked path. + /// + /// `resolution_scale` can be obtained via + /// [`compute_resolution_scale`](PathStroker::compute_resolution_scale). + /// + /// If you plan stroking multiple paths, you can try using [`PathStroker`] + /// which will preserve temporary allocations required during stroking. + /// This might improve performance a bit. + pub fn stroke(&self, stroke: &Stroke, resolution_scale: f32) -> Option<Path> { + PathStroker::new().stroke(self, stroke, resolution_scale) + } +} + +/// A path stroker. +#[allow(missing_debug_implementations)] +#[derive(Clone)] +pub struct PathStroker { + radius: f32, + inv_miter_limit: f32, + res_scale: f32, + inv_res_scale: f32, + inv_res_scale_squared: f32, + + first_normal: Point, + prev_normal: Point, + first_unit_normal: Point, + prev_unit_normal: Point, + + // on original path + first_pt: Point, + prev_pt: Point, + + first_outer_pt: Point, + first_outer_pt_index_in_contour: usize, + segment_count: i32, + prev_is_line: bool, + + capper: CapProc, + joiner: JoinProc, + + // outer is our working answer, inner is temp + inner: PathBuilder, + outer: PathBuilder, + cusper: PathBuilder, + + stroke_type: StrokeType, + + recursion_depth: i32, // track stack depth to abort if numerics run amok + found_tangents: bool, // do less work until tangents meet (cubic) + join_completed: bool, // previous join was not degenerate +} + +impl Default for PathStroker { + fn default() -> Self { + PathStroker::new() + } +} + +impl PathStroker { + /// Creates a new PathStroker. + pub fn new() -> Self { + PathStroker { + radius: 0.0, + inv_miter_limit: 0.0, + res_scale: 1.0, + inv_res_scale: 1.0, + inv_res_scale_squared: 1.0, + + first_normal: Point::zero(), + prev_normal: Point::zero(), + first_unit_normal: Point::zero(), + prev_unit_normal: Point::zero(), + + first_pt: Point::zero(), + prev_pt: Point::zero(), + + first_outer_pt: Point::zero(), + first_outer_pt_index_in_contour: 0, + segment_count: -1, + prev_is_line: false, + + capper: butt_capper, + joiner: miter_joiner, + + inner: PathBuilder::new(), + outer: PathBuilder::new(), + cusper: PathBuilder::new(), + + stroke_type: StrokeType::Outer, + + recursion_depth: 0, + found_tangents: false, + join_completed: false, + } + } + + /// Computes a resolution scale. + /// + /// Resolution scale is the "intended" resolution for the output. Default is 1.0. + /// + /// Larger values (res > 1) indicate that the result should be more precise, since it will + /// be zoomed up, and small errors will be magnified. + /// + /// Smaller values (0 < res < 1) indicate that the result can be less precise, since it will + /// be zoomed down, and small errors may be invisible. + pub fn compute_resolution_scale(ts: &Transform) -> f32 { + let sx = Point::from_xy(ts.sx, ts.kx).length(); + let sy = Point::from_xy(ts.ky, ts.sy).length(); + if sx.is_finite() && sy.is_finite() { + let scale = sx.max(sy); + if scale > 0.0 { + return scale; + } + } + + 1.0 + } + + /// Stokes the path. + /// + /// Can be called multiple times to reuse allocated buffers. + /// + /// `resolution_scale` can be obtained via + /// [`compute_resolution_scale`](Self::compute_resolution_scale). + pub fn stroke(&mut self, path: &Path, stroke: &Stroke, resolution_scale: f32) -> Option<Path> { + let width = NonZeroPositiveF32::new(stroke.width)?; + self.stroke_inner( + path, + width, + stroke.miter_limit, + stroke.line_cap, + stroke.line_join, + resolution_scale, + ) + } + + fn stroke_inner( + &mut self, + path: &Path, + width: NonZeroPositiveF32, + miter_limit: f32, + line_cap: LineCap, + mut line_join: LineJoin, + res_scale: f32, + ) -> Option<Path> { + // TODO: stroke_rect optimization + + let mut inv_miter_limit = 0.0; + + if line_join == LineJoin::Miter { + if miter_limit <= 1.0 { + line_join = LineJoin::Bevel; + } else { + inv_miter_limit = miter_limit.invert(); + } + } + + if line_join == LineJoin::MiterClip { + inv_miter_limit = miter_limit.invert(); + } + + self.res_scale = res_scale; + // The '4' below matches the fill scan converter's error term. + self.inv_res_scale = (res_scale * 4.0).invert(); + self.inv_res_scale_squared = self.inv_res_scale.sqr(); + // Skia turns a conic into quads in device space, a quarter pixel from it at most; the + // outline here is in the path's own units, res_scale device pixels each. + self.inner.conic_tolerance = 0.25 / res_scale; + self.outer.conic_tolerance = 0.25 / res_scale; + self.cusper.conic_tolerance = 0.25 / res_scale; + + self.radius = width.get().half(); + self.inv_miter_limit = inv_miter_limit; + + self.first_normal = Point::zero(); + self.prev_normal = Point::zero(); + self.first_unit_normal = Point::zero(); + self.prev_unit_normal = Point::zero(); + + self.first_pt = Point::zero(); + self.prev_pt = Point::zero(); + + self.first_outer_pt = Point::zero(); + self.first_outer_pt_index_in_contour = 0; + self.segment_count = -1; + self.prev_is_line = false; + + self.capper = cap_factory(line_cap); + self.joiner = join_factory(line_join); + + // Need some estimate of how large our final result (fOuter) + // and our per-contour temp (fInner) will be, so we don't spend + // extra time repeatedly growing these arrays. + // + // 1x for inner == 'wag' (worst contour length would be better guess) + self.inner.clear(); + self.inner.reserve(path.verbs.len(), path.points.len()); + + // 3x for result == inner + outer + join (swag) + self.outer.clear(); + self.outer + .reserve(path.verbs.len() * 3, path.points.len() * 3); + + self.cusper.clear(); + + self.stroke_type = StrokeType::Outer; + + self.recursion_depth = 0; + self.found_tangents = false; + self.join_completed = false; + + let mut last_segment_is_line = false; + let mut iter = path.segments(); + iter.set_auto_close(true); + while let Some(segment) = iter.next() { + match segment { + PathSegment::MoveTo(p) => { + self.move_to(p); + } + PathSegment::LineTo(p) => { + self.line_to(p, Some(&iter)); + last_segment_is_line = true; + } + PathSegment::QuadTo(p1, p2) => { + self.quad_to(p1, p2); + last_segment_is_line = false; + } + PathSegment::CubicTo(p1, p2, p3) => { + self.cubic_to(p1, p2, p3); + last_segment_is_line = false; + } + PathSegment::ConicTo(p1, p2, w) => { + self.conic_to(p1, p2, w); + last_segment_is_line = false; + } + PathSegment::Close => { + if line_cap != LineCap::Butt { + // If the stroke consists of a moveTo followed by a close, treat it + // as if it were followed by a zero-length line. Lines without length + // can have square and round end caps. + if self.has_only_move_to() { + self.line_to(self.move_to_pt(), None); + last_segment_is_line = true; + continue; + } + + // If the stroke consists of a moveTo followed by one or more zero-length + // verbs, then followed by a close, treat is as if it were followed by a + // zero-length line. Lines without length can have square & round end caps. + if self.is_current_contour_empty() { + last_segment_is_line = true; + continue; + } + } + + self.close(last_segment_is_line); + } + } + } + + self.finish(last_segment_is_line) + } + + fn builders(&mut self) -> SwappableBuilders { + SwappableBuilders { + inner: &mut self.inner, + outer: &mut self.outer, + } + } + + fn move_to_pt(&self) -> Point { + self.first_pt + } + + fn move_to(&mut self, p: Point) { + if self.segment_count > 0 { + self.finish_contour(false, false); + } + + self.segment_count = 0; + self.first_pt = p; + self.prev_pt = p; + self.join_completed = false; + } + + fn line_to(&mut self, p: Point, iter: Option<&PathSegmentsIter>) { + let teeny_line = self + .prev_pt + .equals_within_tolerance(p, SCALAR_NEARLY_ZERO * self.inv_res_scale); + if fn_ptr_eq(self.capper, butt_capper) && teeny_line { + return; + } + + if teeny_line && (self.join_completed || iter.map(|i| i.has_valid_tangent()) == Some(true)) + { + return; + } + + let mut normal = Point::zero(); + let mut unit_normal = Point::zero(); + if !self.pre_join_to(p, true, &mut normal, &mut unit_normal) { + return; + } + + self.outer.line_to(p.x + normal.x, p.y + normal.y); + self.inner.line_to(p.x - normal.x, p.y - normal.y); + + self.post_join_to(p, normal, unit_normal); + } + + fn quad_to(&mut self, p1: Point, p2: Point) { + let quad = [self.prev_pt, p1, p2]; + let (reduction, reduction_type) = check_quad_linear(&quad); + if reduction_type == ReductionType::Point { + // If the stroke consists of a moveTo followed by a degenerate curve, treat it + // as if it were followed by a zero-length line. Lines without length + // can have square and round end caps. + self.line_to(p2, None); + return; + } + + if reduction_type == ReductionType::Line { + self.line_to(p2, None); + return; + } + + if reduction_type == ReductionType::Degenerate { + self.line_to(reduction, None); + let save_joiner = self.joiner; + self.joiner = round_joiner; + self.line_to(p2, None); + self.joiner = save_joiner; + return; + } + + debug_assert_eq!(reduction_type, ReductionType::Quad); + + let mut normal_ab = Point::zero(); + let mut unit_ab = Point::zero(); + let mut normal_bc = Point::zero(); + let mut unit_bc = Point::zero(); + if !self.pre_join_to(p1, false, &mut normal_ab, &mut unit_ab) { + self.line_to(p2, None); + return; + } + + let mut quad_points = QuadConstruct::default(); + self.init_quad( + StrokeType::Outer, + NormalizedF32::ZERO, + NormalizedF32::ONE, + &mut quad_points, + ); + self.quad_stroke(&quad, &mut quad_points); + self.init_quad( + StrokeType::Inner, + NormalizedF32::ZERO, + NormalizedF32::ONE, + &mut quad_points, + ); + self.quad_stroke(&quad, &mut quad_points); + + let ok = set_normal_unit_normal( + quad[1], + quad[2], + self.res_scale, + self.radius, + &mut normal_bc, + &mut unit_bc, + ); + if !ok { + normal_bc = normal_ab; + unit_bc = unit_ab; + } + + self.post_join_to(p2, normal_bc, unit_bc); + } + + // As Skia's `SkPathStroker::conicTo`: a conic stroked as itself, its outline quads fitted + // to the conic's own offsets. + fn conic_to(&mut self, p1: Point, p2: Point, weight: f32) { + let conic = [self.prev_pt, p1, p2]; + let (reduction, reduction_type) = check_conic_linear(&conic, weight); + if reduction_type == ReductionType::Point || reduction_type == ReductionType::Line { + self.line_to(p2, None); + return; + } + + if reduction_type == ReductionType::Degenerate { + self.line_to(reduction, None); + let save_joiner = self.joiner; + self.joiner = round_joiner; + self.line_to(p2, None); + self.joiner = save_joiner; + return; + } + + let mut normal_ab = Point::zero(); + let mut unit_ab = Point::zero(); + let mut normal_bc = Point::zero(); + let mut unit_bc = Point::zero(); + if !self.pre_join_to(p1, false, &mut normal_ab, &mut unit_ab) { + self.line_to(p2, None); + return; + } + + let mut quad_points = QuadConstruct::default(); + self.init_quad(StrokeType::Outer, NormalizedF32::ZERO, NormalizedF32::ONE, &mut quad_points); + self.conic_stroke(&conic, weight, &mut quad_points); + self.init_quad(StrokeType::Inner, NormalizedF32::ZERO, NormalizedF32::ONE, &mut quad_points); + self.conic_stroke(&conic, weight, &mut quad_points); + + let ok = set_normal_unit_normal(conic[1], conic[2], self.res_scale, self.radius, &mut normal_bc, &mut unit_bc); + if !ok { + normal_bc = normal_ab; + unit_bc = unit_ab; + } + + self.post_join_to(p2, normal_bc, unit_bc); + } + + fn conic_stroke(&mut self, conic: &[Point; 3], weight: f32, quad_points: &mut QuadConstruct) -> bool { + let result_type = self.compare_quad_conic(conic, weight, quad_points); + if result_type == ResultType::Quad { + let path = if self.stroke_type == StrokeType::Outer { &mut self.outer } else { &mut self.inner }; + path.quad_to(quad_points.quad[1].x, quad_points.quad[1].y, quad_points.quad[2].x, quad_points.quad[2].y); + return true; + } + + if result_type == ResultType::Degenerate { + self.add_degenerate_line(quad_points); + return true; + } + + if !quad_points.quad[2].x.is_finite() || !quad_points.quad[2].y.is_finite() { + return false; + } + + self.recursion_depth += 1; + if self.recursion_depth > RECURSIVE_LIMITS[CONIC_RECURSIVE_LIMIT] { + self.add_degenerate_line(quad_points); + self.recursion_depth -= 1; + return true; + } + + let mut half = QuadConstruct::default(); + if !half.init_with_start(quad_points) { + self.add_degenerate_line(quad_points); + self.recursion_depth -= 1; + return true; + } + if !self.conic_stroke(conic, weight, &mut half) { + return false; + } + + if !half.init_with_end(quad_points) { + self.add_degenerate_line(quad_points); + self.recursion_depth -= 1; + return true; + } + if !self.conic_stroke(conic, weight, &mut half) { + return false; + } + + self.recursion_depth -= 1; + true + } + + fn compare_quad_conic(&mut self, conic: &[Point; 3], weight: f32, quad_points: &mut QuadConstruct) -> ResultType { + if !quad_points.start_set { + let mut start = Point::zero(); + self.conic_perp_ray(conic, weight, quad_points.start_t, &mut start, &mut quad_points.quad[0], Some(&mut quad_points.tangent_start)); + quad_points.start_set = true; + } + if !quad_points.end_set { + let mut end = Point::zero(); + self.conic_perp_ray(conic, weight, quad_points.end_t, &mut end, &mut quad_points.quad[2], Some(&mut quad_points.tangent_end)); + quad_points.end_set = true; + } + + let result_type = self.intersect_ray(IntersectRayType::CtrlPt, quad_points); + if result_type != ResultType::Quad { + return result_type; + } + + let mut ray0 = Point::zero(); + let mut ray1 = Point::zero(); + self.conic_perp_ray(conic, weight, quad_points.mid_t, &mut ray1, &mut ray0, None); + self.stroke_close_enough(&quad_points.quad.clone(), &[ray0, ray1], quad_points) + } + + fn conic_perp_ray(&self, conic: &[Point; 3], weight: f32, t: NormalizedF32, tp: &mut Point, on_p: &mut Point, tangent: Option<&mut Point>) { + *tp = conic_eval(conic, weight, t.get()); + let mut dxy = conic_eval_tangent(conic, weight, t.get()); + if dxy.is_zero() { + dxy = conic[2] - conic[0]; + } + self.set_ray_points(*tp, &mut dxy, on_p, tangent); + } + fn cubic_to(&mut self, pt1: Point, pt2: Point, pt3: Point) { + let cubic = [self.prev_pt, pt1, pt2, pt3]; + let mut reduction = [Point::zero(); 3]; + let mut tangent_pt = Point::zero(); + let reduction_type = check_cubic_linear(&cubic, &mut reduction, Some(&mut tangent_pt)); + if reduction_type == ReductionType::Point { + // If the stroke consists of a moveTo followed by a degenerate curve, treat it + // as if it were followed by a zero-length line. Lines without length + // can have square and round end caps. + self.line_to(pt3, None); + return; + } + + if reduction_type == ReductionType::Line { + self.line_to(pt3, None); + return; + } + + if ReductionType::Degenerate <= reduction_type + && ReductionType::Degenerate3 >= reduction_type + { + self.line_to(reduction[0], None); + let save_joiner = self.joiner; + self.joiner = round_joiner; + if ReductionType::Degenerate2 <= reduction_type { + self.line_to(reduction[1], None); + } + + if ReductionType::Degenerate3 == reduction_type { + self.line_to(reduction[2], None); + } + + self.line_to(pt3, None); + self.joiner = save_joiner; + return; + } + + debug_assert_eq!(reduction_type, ReductionType::Quad); + let mut normal_ab = Point::zero(); + let mut unit_ab = Point::zero(); + let mut normal_cd = Point::zero(); + let mut unit_cd = Point::zero(); + if !self.pre_join_to(tangent_pt, false, &mut normal_ab, &mut unit_ab) { + self.line_to(pt3, None); + return; + } + + let mut t_values = path_geometry::new_t_values(); + let t_values = path_geometry::find_cubic_inflections(&cubic, &mut t_values); + let mut last_t = NormalizedF32::ZERO; + for index in 0..=t_values.len() { + let next_t = t_values + .get(index) + .cloned() + .map(|n| n.to_normalized()) + .unwrap_or(NormalizedF32::ONE); + + let mut quad_points = QuadConstruct::default(); + self.init_quad(StrokeType::Outer, last_t, next_t, &mut quad_points); + self.cubic_stroke(&cubic, &mut quad_points); + self.init_quad(StrokeType::Inner, last_t, next_t, &mut quad_points); + self.cubic_stroke(&cubic, &mut quad_points); + last_t = next_t; + } + + if let Some(cusp) = path_geometry::find_cubic_cusp(&cubic) { + let cusp_loc = path_geometry::eval_cubic_pos_at(&cubic, cusp.to_normalized()); + self.cusper.push_circle(cusp_loc.x, cusp_loc.y, self.radius); + } + + // emit the join even if one stroke succeeded but the last one failed + // this avoids reversing an inner stroke with a partial path followed by another moveto + self.set_cubic_end_normal(&cubic, normal_ab, unit_ab, &mut normal_cd, &mut unit_cd); + + self.post_join_to(pt3, normal_cd, unit_cd); + } + + fn cubic_stroke(&mut self, cubic: &[Point; 4], quad_points: &mut QuadConstruct) -> bool { + if !self.found_tangents { + let result_type = self.tangents_meet(cubic, quad_points); + if result_type != ResultType::Quad { + let ok = points_within_dist( + quad_points.quad[0], + quad_points.quad[2], + self.inv_res_scale, + ); + if (result_type == ResultType::Degenerate || ok) + && self.cubic_mid_on_line(cubic, quad_points) + { + self.add_degenerate_line(quad_points); + return true; + } + } else { + self.found_tangents = true; + } + } + + if self.found_tangents { + let result_type = self.compare_quad_cubic(cubic, quad_points); + if result_type == ResultType::Quad { + let stroke = &quad_points.quad; + if self.stroke_type == StrokeType::Outer { + self.outer + .quad_to(stroke[1].x, stroke[1].y, stroke[2].x, stroke[2].y); + } else { + self.inner + .quad_to(stroke[1].x, stroke[1].y, stroke[2].x, stroke[2].y); + } + + return true; + } + + if result_type == ResultType::Degenerate { + if !quad_points.opposite_tangents { + self.add_degenerate_line(quad_points); + return true; + } + } + } + + if !quad_points.quad[2].x.is_finite() || !quad_points.quad[2].x.is_finite() { + return false; // just abort if projected quad isn't representable + } + + self.recursion_depth += 1; + if self.recursion_depth > RECURSIVE_LIMITS[self.found_tangents as usize] { + // As Skia now does: when it stops making progress, a line, and on. + self.add_degenerate_line(quad_points); + self.recursion_depth -= 1; + return true; + } + + let mut half = QuadConstruct::default(); + if !half.init_with_start(quad_points) { + self.add_degenerate_line(quad_points); + self.recursion_depth -= 1; + return true; + } + + if !self.cubic_stroke(cubic, &mut half) { + return false; + } + + if !half.init_with_end(quad_points) { + self.add_degenerate_line(quad_points); + self.recursion_depth -= 1; + return true; + } + + if !self.cubic_stroke(cubic, &mut half) { + return false; + } + + self.recursion_depth -= 1; + true + } + + fn cubic_mid_on_line(&self, cubic: &[Point; 4], quad_points: &mut QuadConstruct) -> bool { + let mut stroke_mid = Point::zero(); + self.cubic_quad_mid(cubic, quad_points, &mut stroke_mid); + let dist = pt_to_line(stroke_mid, quad_points.quad[0], quad_points.quad[2]); + dist < self.inv_res_scale_squared + } + + fn cubic_quad_mid(&self, cubic: &[Point; 4], quad_points: &mut QuadConstruct, mid: &mut Point) { + let mut cubic_mid_pt = Point::zero(); + self.cubic_perp_ray(cubic, quad_points.mid_t, &mut cubic_mid_pt, mid, None); + } + + // Given a cubic and t, return the point on curve, + // its perpendicular, and the perpendicular tangent. + fn cubic_perp_ray( + &self, + cubic: &[Point; 4], + t: NormalizedF32, + t_pt: &mut Point, + on_pt: &mut Point, + tangent: Option<&mut Point>, + ) { + *t_pt = path_geometry::eval_cubic_pos_at(cubic, t); + let mut dxy = path_geometry::eval_cubic_tangent_at(cubic, t); + + let mut chopped = [Point::zero(); 7]; + if dxy.x == 0.0 && dxy.y == 0.0 { + let mut c_points: &[Point] = cubic; + if t.get().is_nearly_zero() { + dxy = cubic[2] - cubic[0]; + } else if (1.0 - t.get()).is_nearly_zero() { + dxy = cubic[3] - cubic[1]; + } else { + // If the cubic inflection falls on the cusp, subdivide the cubic + // to find the tangent at that point. + // + // Unwrap never fails, because we already checked that `t` is not 0/1, + let t = NormalizedF32Exclusive::new(t.get()).unwrap(); + path_geometry::chop_cubic_at2(cubic, t, &mut chopped); + dxy = chopped[3] - chopped[2]; + if dxy.x == 0.0 && dxy.y == 0.0 { + dxy = chopped[3] - chopped[1]; + c_points = &chopped; + } + } + + if dxy.x == 0.0 && dxy.y == 0.0 { + dxy = c_points[3] - c_points[0]; + } + } + + self.set_ray_points(*t_pt, &mut dxy, on_pt, tangent); + } + + fn set_cubic_end_normal( + &mut self, + cubic: &[Point; 4], + normal_ab: Point, + unit_normal_ab: Point, + normal_cd: &mut Point, + unit_normal_cd: &mut Point, + ) { + let mut ab = cubic[1] - cubic[0]; + let mut cd = cubic[3] - cubic[2]; + + let mut degenerate_ab = degenerate_vector(ab); + let mut degenerate_cb = degenerate_vector(cd); + + if degenerate_ab && degenerate_cb { + *normal_cd = normal_ab; + *unit_normal_cd = unit_normal_ab; + return; + } + + if degenerate_ab { + ab = cubic[2] - cubic[0]; + degenerate_ab = degenerate_vector(ab); + } + + if degenerate_cb { + cd = cubic[3] - cubic[1]; + degenerate_cb = degenerate_vector(cd); + } + + if degenerate_ab || degenerate_cb { + *normal_cd = normal_ab; + *unit_normal_cd = unit_normal_ab; + return; + } + + let res = set_normal_unit_normal2(cd, self.radius, normal_cd, unit_normal_cd); + debug_assert!(res); + } + + fn compare_quad_cubic( + &self, + cubic: &[Point; 4], + quad_points: &mut QuadConstruct, + ) -> ResultType { + // get the quadratic approximation of the stroke + self.cubic_quad_ends(cubic, quad_points); + let result_type = self.intersect_ray(IntersectRayType::CtrlPt, quad_points); + if result_type != ResultType::Quad { + return result_type; + } + + // project a ray from the curve to the stroke + // points near midpoint on quad, midpoint on cubic + let mut ray0 = Point::zero(); + let mut ray1 = Point::zero(); + self.cubic_perp_ray(cubic, quad_points.mid_t, &mut ray1, &mut ray0, None); + self.stroke_close_enough(&quad_points.quad.clone(), &[ray0, ray1], quad_points) + } + + // Given a cubic and a t range, find the start and end if they haven't been found already. + fn cubic_quad_ends(&self, cubic: &[Point; 4], quad_points: &mut QuadConstruct) { + if !quad_points.start_set { + let mut cubic_start_pt = Point::zero(); + self.cubic_perp_ray( + cubic, + quad_points.start_t, + &mut cubic_start_pt, + &mut quad_points.quad[0], + Some(&mut quad_points.tangent_start), + ); + quad_points.start_set = true; + } + + if !quad_points.end_set { + let mut cubic_end_pt = Point::zero(); + self.cubic_perp_ray( + cubic, + quad_points.end_t, + &mut cubic_end_pt, + &mut quad_points.quad[2], + Some(&mut quad_points.tangent_end), + ); + quad_points.end_set = true; + } + } + + fn close(&mut self, is_line: bool) { + self.finish_contour(true, is_line); + } + + fn finish_contour(&mut self, close: bool, curr_is_line: bool) { + if self.segment_count > 0 { + if close { + (self.joiner)( + self.prev_unit_normal, + self.prev_pt, + self.first_unit_normal, + self.radius, + self.inv_miter_limit, + self.prev_is_line, + curr_is_line, + self.builders(), + ); + self.outer.close(); + + // now add inner as its own contour + let pt = self.inner.last_point().unwrap_or_default(); + self.outer.move_to(pt.x, pt.y); + self.outer.reverse_path_to(&self.inner); + self.outer.close(); + } else { + // add caps to start and end + + // cap the end + let pt = self.inner.last_point().unwrap_or_default(); + let other_path = if curr_is_line { + Some(&self.inner) + } else { + None + }; + (self.capper)( + self.prev_pt, + self.prev_normal, + pt, + other_path, + &mut self.outer, + ); + self.outer.reverse_path_to(&self.inner); + + // cap the start + let other_path = if self.prev_is_line { + Some(&self.inner) + } else { + None + }; + (self.capper)( + self.first_pt, + -self.first_normal, + self.first_outer_pt, + other_path, + &mut self.outer, + ); + self.outer.close(); + } + + if !self.cusper.is_empty() { + self.outer.push_path_builder(&self.cusper); + self.cusper.clear(); + } + } + + // since we may re-use `inner`, we rewind instead of reset, to save on + // reallocating its internal storage. + self.inner.clear(); + self.segment_count = -1; + self.first_outer_pt_index_in_contour = self.outer.points.len(); + } + + fn pre_join_to( + &mut self, + p: Point, + curr_is_line: bool, + normal: &mut Point, + unit_normal: &mut Point, + ) -> bool { + debug_assert!(self.segment_count >= 0); + + let prev_x = self.prev_pt.x; + let prev_y = self.prev_pt.y; + + let normal_set = set_normal_unit_normal( + self.prev_pt, + p, + self.res_scale, + self.radius, + normal, + unit_normal, + ); + if !normal_set { + if fn_ptr_eq(self.capper, butt_capper) { + return false; + } + + // Square caps and round caps draw even if the segment length is zero. + // Since the zero length segment has no direction, set the orientation + // to upright as the default orientation. + *normal = Point::from_xy(self.radius, 0.0); + *unit_normal = Point::from_xy(1.0, 0.0); + } + + if self.segment_count == 0 { + self.first_normal = *normal; + self.first_unit_normal = *unit_normal; + self.first_outer_pt = Point::from_xy(prev_x + normal.x, prev_y + normal.y); + + self.outer + .move_to(self.first_outer_pt.x, self.first_outer_pt.y); + self.inner.move_to(prev_x - normal.x, prev_y - normal.y); + } else { + // we have a previous segment + (self.joiner)( + self.prev_unit_normal, + self.prev_pt, + *unit_normal, + self.radius, + self.inv_miter_limit, + self.prev_is_line, + curr_is_line, + self.builders(), + ); + } + self.prev_is_line = curr_is_line; + true + } + + fn post_join_to(&mut self, p: Point, normal: Point, unit_normal: Point) { + self.join_completed = true; + self.prev_pt = p; + self.prev_unit_normal = unit_normal; + self.prev_normal = normal; + self.segment_count += 1; + } + + fn init_quad( + &mut self, + stroke_type: StrokeType, + start: NormalizedF32, + end: NormalizedF32, + quad_points: &mut QuadConstruct, + ) { + self.stroke_type = stroke_type; + self.found_tangents = false; + quad_points.init(start, end); + } + + fn quad_stroke(&mut self, quad: &[Point; 3], quad_points: &mut QuadConstruct) -> bool { + let result_type = self.compare_quad_quad(quad, quad_points); + if result_type == ResultType::Quad { + let path = if self.stroke_type == StrokeType::Outer { + &mut self.outer + } else { + &mut self.inner + }; + + path.quad_to( + quad_points.quad[1].x, + quad_points.quad[1].y, + quad_points.quad[2].x, + quad_points.quad[2].y, + ); + + return true; + } + + if result_type == ResultType::Degenerate { + self.add_degenerate_line(quad_points); + return true; + } + + if !quad_points.quad[2].x.is_finite() || !quad_points.quad[2].y.is_finite() { + return false; // just abort if projected quad isn't representable + } + + self.recursion_depth += 1; + if self.recursion_depth > RECURSIVE_LIMITS[QUAD_RECURSIVE_LIMIT] { + // As Skia now does: when it stops making progress, a line, and on. + self.add_degenerate_line(quad_points); + self.recursion_depth -= 1; + return true; + } + + let mut half = QuadConstruct::default(); + if !half.init_with_start(quad_points) { + self.add_degenerate_line(quad_points); + self.recursion_depth -= 1; + return true; + } + if !self.quad_stroke(quad, &mut half) { + return false; + } + + if !half.init_with_end(quad_points) { + self.add_degenerate_line(quad_points); + self.recursion_depth -= 1; + return true; + } + if !self.quad_stroke(quad, &mut half) { + return false; + } + + self.recursion_depth -= 1; + true + } + + fn compare_quad_quad( + &mut self, + quad: &[Point; 3], + quad_points: &mut QuadConstruct, + ) -> ResultType { + // get the quadratic approximation of the stroke + if !quad_points.start_set { + let mut quad_start_pt = Point::zero(); + self.quad_perp_ray( + quad, + quad_points.start_t, + &mut quad_start_pt, + &mut quad_points.quad[0], + Some(&mut quad_points.tangent_start), + ); + quad_points.start_set = true; + } + + if !quad_points.end_set { + let mut quad_end_pt = Point::zero(); + self.quad_perp_ray( + quad, + quad_points.end_t, + &mut quad_end_pt, + &mut quad_points.quad[2], + Some(&mut quad_points.tangent_end), + ); + quad_points.end_set = true; + } + + let result_type = self.intersect_ray(IntersectRayType::CtrlPt, quad_points); + if result_type != ResultType::Quad { + return result_type; + } + + // project a ray from the curve to the stroke + let mut ray0 = Point::zero(); + let mut ray1 = Point::zero(); + self.quad_perp_ray(quad, quad_points.mid_t, &mut ray1, &mut ray0, None); + self.stroke_close_enough(&quad_points.quad.clone(), &[ray0, ray1], quad_points) + } + + // Given a point on the curve and its derivative, scale the derivative by the radius, and + // compute the perpendicular point and its tangent. + fn set_ray_points( + &self, + tp: Point, + dxy: &mut Point, + on_p: &mut Point, + mut tangent: Option<&mut Point>, + ) { + if !dxy.set_length(self.radius) { + *dxy = Point::from_xy(self.radius, 0.0); + } + + let axis_flip = self.stroke_type as i32 as f32; // go opposite ways for outer, inner + on_p.x = tp.x + axis_flip * dxy.y; + on_p.y = tp.y - axis_flip * dxy.x; + + // As Skia now keeps it: the tangent as a vector, not a point a tangent's length on. + if let Some(ref mut tangent) = tangent { + **tangent = *dxy; + } + } + + // Given a quad and t, return the point on curve, + // its perpendicular, and the perpendicular tangent. + fn quad_perp_ray( + &self, + quad: &[Point; 3], + t: NormalizedF32, + tp: &mut Point, + on_p: &mut Point, + tangent: Option<&mut Point>, + ) { + *tp = path_geometry::eval_quad_at(quad, t); + let mut dxy = path_geometry::eval_quad_tangent_at(quad, t); + + if dxy.is_zero() { + dxy = quad[2] - quad[0]; + } + + self.set_ray_points(*tp, &mut dxy, on_p, tangent); + } + + fn add_degenerate_line(&mut self, quad_points: &QuadConstruct) { + if self.stroke_type == StrokeType::Outer { + self.outer + .line_to(quad_points.quad[2].x, quad_points.quad[2].y); + } else { + self.inner + .line_to(quad_points.quad[2].x, quad_points.quad[2].y); + } + } + + fn stroke_close_enough( + &self, + stroke: &[Point; 3], + ray: &[Point; 2], + quad_points: &mut QuadConstruct, + ) -> ResultType { + let half = NormalizedF32::new_clamped(0.5); + let stroke_mid = path_geometry::eval_quad_at(stroke, half); + // measure the distance from the curve to the quad-stroke midpoint, compare to radius + if points_within_dist(ray[0], stroke_mid, self.inv_res_scale) { + // if the difference is small + if sharp_angle(&quad_points.quad) { + return ResultType::Split; + } + + return ResultType::Quad; + } + + // measure the distance to quad's bounds (quick reject) + // an alternative : look for point in triangle + if !pt_in_quad_bounds(stroke, ray[0], self.inv_res_scale) { + // if far, subdivide + return ResultType::Split; + } + + // measure the curve ray distance to the quad-stroke + let mut roots = path_geometry::new_t_values(); + let roots = intersect_quad_ray(ray, stroke, &mut roots); + if roots.len() != 1 { + return ResultType::Split; + } + + let quad_pt = path_geometry::eval_quad_at(stroke, roots[0].to_normalized()); + let error = self.inv_res_scale * (1.0 - (roots[0].get() - 0.5).abs() * 2.0); + if points_within_dist(ray[0], quad_pt, error) { + // if the difference is small, we're done + if sharp_angle(&quad_points.quad) { + return ResultType::Split; + } + + return ResultType::Quad; + } + + // otherwise, subdivide + ResultType::Split + } + + // Find the intersection of the stroke tangents to construct a stroke quad. + // Return whether the stroke is a degenerate (a line), a quad, or must be split. + // Optionally compute the quad's control point. + fn intersect_ray( + &self, + intersect_ray_type: IntersectRayType, + quad_points: &mut QuadConstruct, + ) -> ResultType { + let start = quad_points.quad[0]; + let end = quad_points.quad[2]; + let a_len = quad_points.tangent_start; + let b_len = quad_points.tangent_end; + + // Slopes match when denom goes to zero: + // axLen / ayLen == bxLen / byLen + // (ayLen * byLen) * axLen / ayLen == (ayLen * byLen) * bxLen / byLen + // byLen * axLen == ayLen * bxLen + // byLen * axLen - ayLen * bxLen ( == denom ) + let denom = a_len.cross(b_len); + if denom == 0.0 || !denom.is_finite() { + quad_points.opposite_tangents = a_len.dot(b_len) < 0.0; + return ResultType::Degenerate; + } + + quad_points.opposite_tangents = false; + let ab0 = start - end; + let mut numer_a = b_len.cross(ab0); + let numer_b = a_len.cross(ab0); + if (numer_a >= 0.0) == (numer_b >= 0.0) { + // if the control point is outside the quad ends + + // if the perpendicular distances from the quad points to the opposite tangent line + // are small, a straight line is good enough + let dist1 = pt_to_tangent_line(start, end, quad_points.tangent_end); + let dist2 = pt_to_tangent_line(end, start, quad_points.tangent_start); + if dist1.max(dist2) <= self.inv_res_scale_squared { + return ResultType::Degenerate; + } + + return ResultType::Split; + } + + // check to see if the denominator is teeny relative to the numerator + // if the offset by one will be lost, the ratio is too large + numer_a /= denom; + let valid_divide = numer_a > numer_a - 1.0; + if valid_divide { + if intersect_ray_type == IntersectRayType::CtrlPt { + // the intersection of the tangents need not be on the tangent segment + // so 0 <= numerA <= 1 is not necessarily true + quad_points.quad[1].x = start.x + quad_points.tangent_start.x * numer_a; + quad_points.quad[1].y = start.y + quad_points.tangent_start.y * numer_a; + } + + return ResultType::Quad; + } + + quad_points.opposite_tangents = a_len.dot(b_len) < 0.0; + + // if the lines are parallel, straight line is good enough + ResultType::Degenerate + } + + // Given a cubic and a t-range, determine if the stroke can be described by a quadratic. + fn tangents_meet(&self, cubic: &[Point; 4], quad_points: &mut QuadConstruct) -> ResultType { + self.cubic_quad_ends(cubic, quad_points); + self.intersect_ray(IntersectRayType::ResultType, quad_points) + } + + fn finish(&mut self, is_line: bool) -> Option<Path> { + self.finish_contour(false, is_line); + + // Swap out the outer builder. + let mut buf = PathBuilder::new(); + core::mem::swap(&mut self.outer, &mut buf); + + buf.finish() + } + + fn has_only_move_to(&self) -> bool { + self.segment_count == 0 + } + + fn is_current_contour_empty(&self) -> bool { + self.inner.is_zero_length_since_point(0) + && self + .outer + .is_zero_length_since_point(self.first_outer_pt_index_in_contour) + } +} + +fn cap_factory(cap: LineCap) -> CapProc { + match cap { + LineCap::Butt => butt_capper, + LineCap::Round => round_capper, + LineCap::Square => square_capper, + } +} + +fn butt_capper(_: Point, _: Point, stop: Point, _: Option<&PathBuilder>, path: &mut PathBuilder) { + path.line_to(stop.x, stop.y); +} + +fn round_capper( + pivot: Point, + normal: Point, + stop: Point, + _: Option<&PathBuilder>, + path: &mut PathBuilder, +) { + let mut parallel = normal; + parallel.rotate_cw(); + + let projected_center = pivot + parallel; + + path.conic_points_to( + projected_center + normal, + projected_center, + SCALAR_ROOT_2_OVER_2, + ); + path.conic_points_to(projected_center - normal, stop, SCALAR_ROOT_2_OVER_2); +} + +fn square_capper( + pivot: Point, + normal: Point, + stop: Point, + other_path: Option<&PathBuilder>, + path: &mut PathBuilder, +) { + let mut parallel = normal; + parallel.rotate_cw(); + + if other_path.is_some() { + path.set_last_point(Point::from_xy( + pivot.x + normal.x + parallel.x, + pivot.y + normal.y + parallel.y, + )); + path.line_to( + pivot.x - normal.x + parallel.x, + pivot.y - normal.y + parallel.y, + ); + } else { + path.line_to( + pivot.x + normal.x + parallel.x, + pivot.y + normal.y + parallel.y, + ); + path.line_to( + pivot.x - normal.x + parallel.x, + pivot.y - normal.y + parallel.y, + ); + path.line_to(stop.x, stop.y); + } +} + +fn join_factory(join: LineJoin) -> JoinProc { + match join { + LineJoin::Miter => miter_joiner, + LineJoin::MiterClip => miter_clip_joiner, + LineJoin::Round => round_joiner, + LineJoin::Bevel => bevel_joiner, + } +} + +fn is_clockwise(before: Point, after: Point) -> bool { + before.x * after.y > before.y * after.x +} + +#[derive(Copy, Clone, PartialEq, Debug)] +enum AngleType { + Nearly180, + Sharp, + Shallow, + NearlyLine, +} + +fn dot_to_angle_type(dot: f32) -> AngleType { + if dot >= 0.0 { + // shallow or line + if (1.0 - dot).is_nearly_zero() { + AngleType::NearlyLine + } else { + AngleType::Shallow + } + } else { + // sharp or 180 + if (1.0 + dot).is_nearly_zero() { + AngleType::Nearly180 + } else { + AngleType::Sharp + } + } +} + +fn handle_inner_join(pivot: Point, after: Point, inner: &mut PathBuilder) { + // In the degenerate case that the stroke radius is larger than our segments + // just connecting the two inner segments may "show through" as a funny + // diagonal. To pseudo-fix this, we go through the pivot point. This adds + // an extra point/edge, but I can't see a cheap way to know when this is + // not needed :( + inner.line_to(pivot.x, pivot.y); + + inner.line_to(pivot.x - after.x, pivot.y - after.y); +} + +fn bevel_joiner( + before_unit_normal: Point, + pivot: Point, + after_unit_normal: Point, + radius: f32, + _: f32, + _: bool, + _: bool, + mut builders: SwappableBuilders, +) { + let mut after = after_unit_normal.scaled(radius); + + if !is_clockwise(before_unit_normal, after_unit_normal) { + builders.swap(); + after = -after; + } + + builders.outer.line_to(pivot.x + after.x, pivot.y + after.y); + handle_inner_join(pivot, after, builders.inner); +} + +fn round_joiner( + before_unit_normal: Point, + pivot: Point, + after_unit_normal: Point, + radius: f32, + _: f32, + _: bool, + _: bool, + mut builders: SwappableBuilders, +) { + let dot_prod = before_unit_normal.dot(after_unit_normal); + let angle_type = dot_to_angle_type(dot_prod); + + if angle_type == AngleType::NearlyLine { + return; + } + + let mut before = before_unit_normal; + let mut after = after_unit_normal; + let mut dir = PathDirection::CW; + + if !is_clockwise(before, after) { + builders.swap(); + before = -before; + after = -after; + dir = PathDirection::CCW; + } + + let ts = Transform::from_row(radius, 0.0, 0.0, radius, pivot.x, pivot.y); + + let mut conics = [path_geometry::Conic::default(); 5]; + let conics = path_geometry::Conic::build_unit_arc(before, after, dir, ts, &mut conics); + if let Some(conics) = conics { + for conic in conics { + builders + .outer + .conic_points_to(conic.points[1], conic.points[2], conic.weight); + } + + after.scale(radius); + handle_inner_join(pivot, after, builders.inner); + } +} + +#[inline] +fn miter_joiner( + before_unit_normal: Point, + pivot: Point, + after_unit_normal: Point, + radius: f32, + inv_miter_limit: f32, + prev_is_line: bool, + curr_is_line: bool, + builders: SwappableBuilders, +) { + miter_joiner_inner( + before_unit_normal, + pivot, + after_unit_normal, + radius, + inv_miter_limit, + false, + prev_is_line, + curr_is_line, + builders, + ); +} + +#[inline] +fn miter_clip_joiner( + before_unit_normal: Point, + pivot: Point, + after_unit_normal: Point, + radius: f32, + inv_miter_limit: f32, + prev_is_line: bool, + curr_is_line: bool, + builders: SwappableBuilders, +) { + miter_joiner_inner( + before_unit_normal, + pivot, + after_unit_normal, + radius, + inv_miter_limit, + true, + prev_is_line, + curr_is_line, + builders, + ); +} + +fn miter_joiner_inner( + before_unit_normal: Point, + pivot: Point, + after_unit_normal: Point, + radius: f32, + inv_miter_limit: f32, + miter_clip: bool, + prev_is_line: bool, + mut curr_is_line: bool, + mut builders: SwappableBuilders, +) { + fn do_blunt_or_clipped( + builders: SwappableBuilders, + pivot: Point, + radius: f32, + prev_is_line: bool, + curr_is_line: bool, + mut before: Point, + mut mid: Point, + mut after: Point, + inv_miter_limit: f32, + miter_clip: bool, + ) { + after.scale(radius); + + if miter_clip { + mid.normalize(); + + let cos_beta = before.dot(mid); + let sin_beta = before.cross(mid); + + let x = if sin_beta.abs() <= SCALAR_NEARLY_ZERO { + 1.0 / inv_miter_limit + } else { + ((1.0 / inv_miter_limit) - cos_beta) / sin_beta + }; + + before.scale(radius); + + let mut before_tangent = before; + before_tangent.rotate_cw(); + + let mut after_tangent = after; + after_tangent.rotate_ccw(); + + let c1 = pivot + before + before_tangent.scaled(x); + let c2 = pivot + after + after_tangent.scaled(x); + + if prev_is_line { + builders.outer.set_last_point(c1); + } else { + builders.outer.line_to(c1.x, c1.y); + } + + builders.outer.line_to(c2.x, c2.y); + } + + if !curr_is_line { + builders.outer.line_to(pivot.x + after.x, pivot.y + after.y); + } + + handle_inner_join(pivot, after, builders.inner); + } + + fn do_miter( + builders: SwappableBuilders, + pivot: Point, + radius: f32, + prev_is_line: bool, + curr_is_line: bool, + mid: Point, + mut after: Point, + ) { + after.scale(radius); + + if prev_is_line { + builders + .outer + .set_last_point(Point::from_xy(pivot.x + mid.x, pivot.y + mid.y)); + } else { + builders.outer.line_to(pivot.x + mid.x, pivot.y + mid.y); + } + + if !curr_is_line { + builders.outer.line_to(pivot.x + after.x, pivot.y + after.y); + } + + handle_inner_join(pivot, after, builders.inner); + } + + // negate the dot since we're using normals instead of tangents + let dot_prod = before_unit_normal.dot(after_unit_normal); + let angle_type = dot_to_angle_type(dot_prod); + let mut before = before_unit_normal; + let mut after = after_unit_normal; + let mut mid; + + if angle_type == AngleType::NearlyLine { + return; + } + + if angle_type == AngleType::Nearly180 { + curr_is_line = false; + mid = (after - before).scaled(radius / 2.0); + do_blunt_or_clipped( + builders, + pivot, + radius, + prev_is_line, + curr_is_line, + before, + mid, + after, + inv_miter_limit, + miter_clip, + ); + return; + } + + let ccw = !is_clockwise(before, after); + if ccw { + builders.swap(); + before = -before; + after = -after; + } + + // Before we enter the world of square-roots and divides, + // check if we're trying to join an upright right angle + // (common case for stroking rectangles). If so, special case + // that (for speed an accuracy). + // Note: we only need to check one normal if dot==0 + if dot_prod == 0.0 && inv_miter_limit <= SCALAR_ROOT_2_OVER_2 { + mid = (before + after).scaled(radius); + do_miter( + builders, + pivot, + radius, + prev_is_line, + curr_is_line, + mid, + after, + ); + return; + } + + // choose the most accurate way to form the initial mid-vector + if angle_type == AngleType::Sharp { + mid = Point::from_xy(after.y - before.y, before.x - after.x); + if ccw { + mid = -mid; + } + } else { + mid = Point::from_xy(before.x + after.x, before.y + after.y); + } + + // midLength = radius / sinHalfAngle + // if (midLength > miterLimit * radius) abort + // if (radius / sinHalf > miterLimit * radius) abort + // if (1 / sinHalf > miterLimit) abort + // if (1 / miterLimit > sinHalf) abort + // My dotProd is opposite sign, since it is built from normals and not tangents + // hence 1 + dot instead of 1 - dot in the formula + let sin_half_angle = (1.0 + dot_prod).half().sqrt(); + if sin_half_angle < inv_miter_limit { + curr_is_line = false; + do_blunt_or_clipped( + builders, + pivot, + radius, + prev_is_line, + curr_is_line, + before, + mid, + after, + inv_miter_limit, + miter_clip, + ); + return; + } + + mid.set_length(radius / sin_half_angle); + do_miter( + builders, + pivot, + radius, + prev_is_line, + curr_is_line, + mid, + after, + ); +} + +fn set_normal_unit_normal( + before: Point, + after: Point, + scale: f32, + radius: f32, + normal: &mut Point, + unit_normal: &mut Point, +) -> bool { + if !unit_normal.set_normalize((after.x - before.x) * scale, (after.y - before.y) * scale) { + return false; + } + + unit_normal.rotate_ccw(); + *normal = unit_normal.scaled(radius); + true +} + +fn set_normal_unit_normal2( + vec: Point, + radius: f32, + normal: &mut Point, + unit_normal: &mut Point, +) -> bool { + if !unit_normal.set_normalize(vec.x, vec.y) { + return false; + } + + unit_normal.rotate_ccw(); + *normal = unit_normal.scaled(radius); + true +} + +fn fn_ptr_eq(f1: CapProc, f2: CapProc) -> bool { + core::ptr::eq(f1 as *const (), f2 as *const ()) +} + +#[derive(Debug)] +struct QuadConstruct { + // The state of the quad stroke under construction. + quad: [Point; 3], // the stroked quad parallel to the original curve + tangent_start: Point, // the tangent at quad[0] + tangent_end: Point, // the tangent at quad[2] + start_t: NormalizedF32, // a segment of the original curve + mid_t: NormalizedF32, + end_t: NormalizedF32, + start_set: bool, // state to share common points across structs + end_set: bool, + opposite_tangents: bool, // set if coincident tangents have opposite directions +} + +impl Default for QuadConstruct { + fn default() -> Self { + Self { + quad: Default::default(), + tangent_start: Point::default(), + tangent_end: Point::default(), + start_t: NormalizedF32::ZERO, + mid_t: NormalizedF32::ZERO, + end_t: NormalizedF32::ZERO, + start_set: false, + end_set: false, + opposite_tangents: false, + } + } +} + +impl QuadConstruct { + // return false if start and end are too close to have a unique middle + fn init(&mut self, start: NormalizedF32, end: NormalizedF32) -> bool { + self.start_t = start; + self.mid_t = NormalizedF32::new_clamped((start.get() + end.get()).half()); + self.end_t = end; + self.start_set = false; + self.end_set = false; + self.start_t < self.mid_t && self.mid_t < self.end_t + } + + fn init_with_start(&mut self, parent: &Self) -> bool { + if !self.init(parent.start_t, parent.mid_t) { + return false; + } + + self.quad[0] = parent.quad[0]; + self.tangent_start = parent.tangent_start; + self.start_set = true; + true + } + + fn init_with_end(&mut self, parent: &Self) -> bool { + if !self.init(parent.mid_t, parent.end_t) { + return false; + } + + self.quad[2] = parent.quad[2]; + self.tangent_end = parent.tangent_end; + self.end_set = true; + true + } +} + +fn check_quad_linear(quad: &[Point; 3]) -> (Point, ReductionType) { + let degenerate_ab = degenerate_vector(quad[1] - quad[0]); + let degenerate_bc = degenerate_vector(quad[2] - quad[1]); + if degenerate_ab & degenerate_bc { + return (Point::zero(), ReductionType::Point); + } + + if degenerate_ab | degenerate_bc { + return (Point::zero(), ReductionType::Line); + } + + if !quad_in_line(quad) { + return (Point::zero(), ReductionType::Quad); + } + + let t = path_geometry::find_quad_max_curvature(quad); + if t == NormalizedF32::ZERO || t == NormalizedF32::ONE { + return (Point::zero(), ReductionType::Line); + } + + ( + path_geometry::eval_quad_at(quad, t), + ReductionType::Degenerate, + ) +} + +/// `CheckConicLinear`. +fn check_conic_linear(conic: &[Point; 3], weight: f32) -> (Point, ReductionType) { + let degenerate_ab = degenerate_vector(conic[1] - conic[0]); + let degenerate_bc = degenerate_vector(conic[2] - conic[1]); + if degenerate_ab & degenerate_bc { + return (Point::zero(), ReductionType::Point); + } + if degenerate_ab | degenerate_bc { + return (Point::zero(), ReductionType::Line); + } + if !quad_in_line(conic) { + return (Point::zero(), ReductionType::Quad); + } + let t = path_geometry::find_quad_max_curvature(conic).get(); + if t == 0.0 || t.is_nan() { + return (Point::zero(), ReductionType::Line); + } + (conic_eval(conic, weight, t), ReductionType::Degenerate) +} + +/// `SkConic::evalAt` (`SkConicCoeff`): the point at `t`. +fn conic_eval(conic: &[Point; 3], weight: f32, t: f32) -> Point { + let (p0, p1, p2) = (conic[0], conic[1], conic[2]); + let p1w = Point::from_xy(p1.x * weight, p1.y * weight); + let a = Point::from_xy(p2.x - (p1w.x + p1w.x) + p0.x, p2.y - (p1w.y + p1w.y) + p0.y); + let b = Point::from_xy((p1w.x - p0.x) + (p1w.x - p0.x), (p1w.y - p0.y) + (p1w.y - p0.y)); + let db = (weight - 1.0) + (weight - 1.0); + let da = 0.0 - db; + let numer = Point::from_xy((a.x * t + b.x) * t + p0.x, (a.y * t + b.y) * t + p0.y); + let denom = (da * t + db) * t + 1.0; + Point::from_xy(numer.x / denom, numer.y / denom) +} + +/// `SkConic::evalTangentAt`. +fn conic_eval_tangent(conic: &[Point; 3], weight: f32, t: f32) -> Point { + let (p0, p1, p2) = (conic[0], conic[1], conic[2]); + if (t == 0.0 && p0 == p1) || (t == 1.0 && p1 == p2) { + return p2 - p0; + } + let p20 = p2 - p0; + let p10 = p1 - p0; + let c = Point::from_xy(weight * p10.x, weight * p10.y); + let a = Point::from_xy(weight * p20.x - p20.x, weight * p20.y - p20.y); + let b = Point::from_xy(p20.x - c.x - c.x, p20.y - c.y - c.y); + Point::from_xy((a.x * t + b.x) * t + c.x, (a.y * t + b.y) * t + c.y) +} + +fn degenerate_vector(v: Point) -> bool { + !v.can_normalize() +} + +/// Given quad, see if all there points are in a line. +/// Return true if the inside point is close to a line connecting the outermost points. +/// +/// Find the outermost point by looking for the largest difference in X or Y. +/// Since the XOR of the indices is 3 (0 ^ 1 ^ 2) +/// the missing index equals: outer_1 ^ outer_2 ^ 3. +fn quad_in_line(quad: &[Point; 3]) -> bool { + let mut pt_max = -1.0; + let mut outer1 = 0; + let mut outer2 = 0; + for index in 0..2 { + for inner in index + 1..3 { + let test_diff = quad[inner] - quad[index]; + let test_max = test_diff.x.abs().max(test_diff.y.abs()); + if pt_max < test_max { + outer1 = index; + outer2 = inner; + pt_max = test_max; + } + } + } + + debug_assert!(outer1 <= 1); + debug_assert!(outer2 >= 1 && outer2 <= 2); + debug_assert!(outer1 < outer2); + + let mid = outer1 ^ outer2 ^ 3; + const CURVATURE_SLOP: f32 = 0.000005; // this multiplier is pulled out of the air + let line_slop = pt_max * pt_max * CURVATURE_SLOP; + pt_to_line(quad[mid], quad[outer1], quad[outer2]) <= line_slop +} + +// The distance squared from `pt` to the segment from `line_start` along `tangent`. +fn pt_to_tangent_line(pt: Point, line_start: Point, tangent: Point) -> f32 { + let ab0 = pt - line_start; + let numer = tangent.dot(ab0); + let denom = tangent.dot(tangent); + let t = numer / denom; + if t >= 0.0 && t <= 1.0 { + let hit = Point::from_xy(line_start.x + tangent.x * t, line_start.y + tangent.y * t); + hit.distance_to_sqd(pt) + } else { + pt.distance_to_sqd(line_start) + } +} + +// returns the distance squared from the point to the line +fn pt_to_line(pt: Point, line_start: Point, line_end: Point) -> f32 { + let dxy = line_end - line_start; + let ab0 = pt - line_start; + let numer = dxy.dot(ab0); + let denom = dxy.dot(dxy); + let t = numer / denom; + if t >= 0.0 && t <= 1.0 { + let hit = Point::from_xy( + line_start.x * (1.0 - t) + line_end.x * t, + line_start.y * (1.0 - t) + line_end.y * t, + ); + hit.distance_to_sqd(pt) + } else { + pt.distance_to_sqd(line_start) + } +} + +// Intersect the line with the quad and return the t values on the quad where the line crosses. +fn intersect_quad_ray<'a>( + line: &[Point; 2], + quad: &[Point; 3], + roots: &'a mut [NormalizedF32Exclusive; 3], +) -> &'a [NormalizedF32Exclusive] { + let vec = line[1] - line[0]; + let mut r = [0.0; 3]; + for n in 0..3 { + r[n] = (quad[n].y - line[0].y) * vec.x - (quad[n].x - line[0].x) * vec.y; + } + let mut a = r[2]; + let mut b = r[1]; + let c = r[0]; + a += c - 2.0 * b; // A = a - 2*b + c + b -= c; // B = -(b - c) + + let len = path_geometry::find_unit_quad_roots(a, 2.0 * b, c, roots); + &roots[0..len] +} + +fn points_within_dist(near_pt: Point, far_pt: Point, limit: f32) -> bool { + near_pt.distance_to_sqd(far_pt) <= limit * limit +} + +fn sharp_angle(quad: &[Point; 3]) -> bool { + let mut smaller = quad[1] - quad[0]; + let mut larger = quad[1] - quad[2]; + let smaller_len = smaller.length_sqd(); + let mut larger_len = larger.length_sqd(); + if smaller_len > larger_len { + core::mem::swap(&mut smaller, &mut larger); + larger_len = smaller_len; + } + + if !smaller.set_length(larger_len) { + return false; + } + + let dot = smaller.dot(larger); + dot > 0.0 +} + +// Return true if the point is close to the bounds of the quad. This is used as a quick reject. +fn pt_in_quad_bounds(quad: &[Point; 3], pt: Point, inv_res_scale: f32) -> bool { + let x_min = quad[0].x.min(quad[1].x).min(quad[2].x); + if pt.x + inv_res_scale < x_min { + return false; + } + + let x_max = quad[0].x.max(quad[1].x).max(quad[2].x); + if pt.x - inv_res_scale > x_max { + return false; + } + + let y_min = quad[0].y.min(quad[1].y).min(quad[2].y); + if pt.y + inv_res_scale < y_min { + return false; + } + + let y_max = quad[0].y.max(quad[1].y).max(quad[2].y); + if pt.y - inv_res_scale > y_max { + return false; + } + + true +} + +fn check_cubic_linear( + cubic: &[Point; 4], + reduction: &mut [Point; 3], + tangent_pt: Option<&mut Point>, +) -> ReductionType { + let degenerate_ab = degenerate_vector(cubic[1] - cubic[0]); + let degenerate_bc = degenerate_vector(cubic[2] - cubic[1]); + let degenerate_cd = degenerate_vector(cubic[3] - cubic[2]); + if degenerate_ab & degenerate_bc & degenerate_cd { + return ReductionType::Point; + } + + if degenerate_ab as i32 + degenerate_bc as i32 + degenerate_cd as i32 == 2 { + return ReductionType::Line; + } + + if !cubic_in_line(cubic) { + if let Some(tangent_pt) = tangent_pt { + *tangent_pt = if degenerate_ab { cubic[2] } else { cubic[1] }; + } + + return ReductionType::Quad; + } + + let mut t_values = [NormalizedF32::ZERO; 3]; + let t_values = path_geometry::find_cubic_max_curvature(cubic, &mut t_values); + let mut r_count = 0; + // Now loop over the t-values, and reject any that evaluate to either end-point + for t in t_values { + if 0.0 >= t.get() || t.get() >= 1.0 { + continue; + } + + reduction[r_count] = path_geometry::eval_cubic_pos_at(cubic, *t); + if reduction[r_count] != cubic[0] && reduction[r_count] != cubic[3] { + r_count += 1; + } + } + + match r_count { + 0 => ReductionType::Line, + 1 => ReductionType::Degenerate, + 2 => ReductionType::Degenerate2, + 3 => ReductionType::Degenerate3, + _ => unreachable!(), + } +} + +/// Given a cubic, determine if all four points are in a line. +/// +/// Return true if the inner points is close to a line connecting the outermost points. +/// +/// Find the outermost point by looking for the largest difference in X or Y. +/// Given the indices of the outermost points, and that outer_1 is greater than outer_2, +/// this table shows the index of the smaller of the remaining points: +/// +/// ```text +/// outer_2 +/// 0 1 2 3 +/// outer_1 ---------------- +/// 0 | - 2 1 1 +/// 1 | - - 0 0 +/// 2 | - - - 0 +/// 3 | - - - - +/// ``` +/// +/// If outer_1 == 0 and outer_2 == 1, the smaller of the remaining indices (2 and 3) is 2. +/// +/// This table can be collapsed to: (1 + (2 >> outer_2)) >> outer_1 +/// +/// Given three indices (outer_1 outer_2 mid_1) from 0..3, the remaining index is: +/// +/// ```text +/// mid_2 == (outer_1 ^ outer_2 ^ mid_1) +/// ``` +fn cubic_in_line(cubic: &[Point; 4]) -> bool { + let mut pt_max = -1.0; + let mut outer1 = 0; + let mut outer2 = 0; + for index in 0..3 { + for inner in index + 1..4 { + let test_diff = cubic[inner] - cubic[index]; + let test_max = test_diff.x.abs().max(test_diff.y.abs()); + if pt_max < test_max { + outer1 = index; + outer2 = inner; + pt_max = test_max; + } + } + } + debug_assert!(outer1 <= 2); + debug_assert!(outer2 >= 1 && outer2 <= 3); + debug_assert!(outer1 < outer2); + let mid1 = (1 + (2 >> outer2)) >> outer1; + debug_assert!(mid1 <= 2); + debug_assert!(outer1 != mid1 && outer2 != mid1); + let mid2 = outer1 ^ outer2 ^ mid1; + debug_assert!(mid2 >= 1 && mid2 <= 3); + debug_assert!(mid2 != outer1 && mid2 != outer2 && mid2 != mid1); + debug_assert!(((1 << outer1) | (1 << outer2) | (1 << mid1) | (1 << mid2)) == 0x0f); + let line_slop = pt_max * pt_max * 0.00001; // this multiplier is pulled out of the air + + pt_to_line(cubic[mid1], cubic[outer1], cubic[outer2]) <= line_slop + && pt_to_line(cubic[mid2], cubic[outer1], cubic[outer2]) <= line_slop +} + +#[rustfmt::skip] +#[cfg(test)] +mod tests { + use super::*; + + impl PathSegment { + fn new_move_to(x: f32, y: f32) -> Self { + PathSegment::MoveTo(Point::from_xy(x, y)) + } + + fn new_line_to(x: f32, y: f32) -> Self { + PathSegment::LineTo(Point::from_xy(x, y)) + } + + // fn new_quad_to(x1: f32, y1: f32, x: f32, y: f32) -> Self { + // PathSegment::QuadTo(Point::from_xy(x1, y1), Point::from_xy(x, y)) + // } + + // fn new_cubic_to(x1: f32, y1: f32, x2: f32, y2: f32, x: f32, y: f32) -> Self { + // PathSegment::CubicTo(Point::from_xy(x1, y1), Point::from_xy(x2, y2), Point::from_xy(x, y)) + // } + + fn new_close() -> Self { + PathSegment::Close + } + } + + // Make sure that subpath auto-closing is enabled. + #[test] + fn auto_close() { + // A triangle. + let mut pb = PathBuilder::new(); + pb.move_to(10.0, 10.0); + pb.line_to(20.0, 50.0); + pb.line_to(30.0, 10.0); + pb.close(); + let path = pb.finish().unwrap(); + + let stroke = Stroke::default(); + let stroke_path = PathStroker::new().stroke(&path, &stroke, 1.0).unwrap(); + + let mut iter = stroke_path.segments(); + iter.set_auto_close(true); + + assert_eq!(iter.next().unwrap(), PathSegment::new_move_to(10.485071, 9.878732)); + assert_eq!(iter.next().unwrap(), PathSegment::new_line_to(20.485071, 49.878731)); + assert_eq!(iter.next().unwrap(), PathSegment::new_line_to(20.0, 50.0)); + assert_eq!(iter.next().unwrap(), PathSegment::new_line_to(19.514929, 49.878731)); + assert_eq!(iter.next().unwrap(), PathSegment::new_line_to(29.514929, 9.878732)); + assert_eq!(iter.next().unwrap(), PathSegment::new_line_to(30.0, 10.0)); + assert_eq!(iter.next().unwrap(), PathSegment::new_line_to(30.0, 10.5)); + assert_eq!(iter.next().unwrap(), PathSegment::new_line_to(10.0, 10.5)); + assert_eq!(iter.next().unwrap(), PathSegment::new_line_to(10.0, 10.0)); + assert_eq!(iter.next().unwrap(), PathSegment::new_line_to(10.485071, 9.878732)); + assert_eq!(iter.next().unwrap(), PathSegment::new_close()); + assert_eq!(iter.next().unwrap(), PathSegment::new_move_to(9.3596115, 9.5)); + assert_eq!(iter.next().unwrap(), PathSegment::new_line_to(30.640388, 9.5)); + assert_eq!(iter.next().unwrap(), PathSegment::new_line_to(20.485071, 50.121269)); + assert_eq!(iter.next().unwrap(), PathSegment::new_line_to(19.514929, 50.121269)); + assert_eq!(iter.next().unwrap(), PathSegment::new_line_to(9.514929, 10.121268)); + assert_eq!(iter.next().unwrap(), PathSegment::new_line_to(9.3596115, 9.5)); + assert_eq!(iter.next().unwrap(), PathSegment::new_close()); + } + + // From skia/tests/StrokeTest.cpp + #[test] + fn cubic_1() { + let mut pb = PathBuilder::new(); + pb.move_to(51.0161362, 1511.52478); + pb.cubic_to( + 51.0161362, 1511.52478, + 51.0161362, 1511.52478, + 51.0161362, 1511.52478, + ); + let path = pb.finish().unwrap(); + + let mut stroke = Stroke::default(); + stroke.width = 0.394537568; + + assert!(PathStroker::new().stroke(&path, &stroke, 1.0).is_none()); + } + + // From skia/tests/StrokeTest.cpp + #[test] + fn cubic_2() { + let mut pb = PathBuilder::new(); + pb.move_to(f32::from_bits(0x424c1086), f32::from_bits(0x44bcf0cb)); // 51.0161362, 1511.52478 + pb.cubic_to( + f32::from_bits(0x424c107c), f32::from_bits(0x44bcf0cb), // 51.0160980, 1511.52478 + f32::from_bits(0x424c10c2), f32::from_bits(0x44bcf0cb), // 51.0163651, 1511.52478 + f32::from_bits(0x424c1119), f32::from_bits(0x44bcf0ca), // 51.0166969, 1511.52466 + ); + let path = pb.finish().unwrap(); + + let mut stroke = Stroke::default(); + stroke.width = 0.394537568; + + assert!(PathStroker::new().stroke(&path, &stroke, 1.0).is_some()); + } + + // From skia/tests/StrokeTest.cpp + // From skbug.com/6491. The large stroke width can cause numerical instabilities. + #[test] + fn big() { + // Skia uses `kStrokeAndFill_Style` here, but we do not support it. + + let mut pb = PathBuilder::new(); + pb.move_to(f32::from_bits(0x46380000), f32::from_bits(0xc6380000)); // 11776, -11776 + pb.line_to(f32::from_bits(0x46a00000), f32::from_bits(0xc6a00000)); // 20480, -20480 + pb.line_to(f32::from_bits(0x468c0000), f32::from_bits(0xc68c0000)); // 17920, -17920 + pb.line_to(f32::from_bits(0x46100000), f32::from_bits(0xc6100000)); // 9216, -9216 + pb.line_to(f32::from_bits(0x46380000), f32::from_bits(0xc6380000)); // 11776, -11776 + pb.close(); + let path = pb.finish().unwrap(); + + let mut stroke = Stroke::default(); + stroke.width = 1.49679073e+10; + + assert!(PathStroker::new().stroke(&path, &stroke, 1.0).is_some()); + } + + // From skia/tests/StrokerTest.cpp + #[test] + fn quad_stroker_one_off() { + let mut pb = PathBuilder::new(); + pb.move_to(f32::from_bits(0x43c99223), f32::from_bits(0x42b7417e)); + pb.quad_to( + f32::from_bits(0x4285d839), f32::from_bits(0x43ed6645), + f32::from_bits(0x43c941c8), f32::from_bits(0x42b3ace3), + ); + let path = pb.finish().unwrap(); + + let mut stroke = Stroke::default(); + stroke.width = 164.683548; + + assert!(PathStroker::new().stroke(&path, &stroke, 1.0).is_some()); + } + + // From skia/tests/StrokerTest.cpp + #[test] + fn cubic_stroker_one_off() { + let mut pb = PathBuilder::new(); + pb.move_to(f32::from_bits(0x433f5370), f32::from_bits(0x43d1f4b3)); + pb.cubic_to( + f32::from_bits(0x4331cb76), f32::from_bits(0x43ea3340), + f32::from_bits(0x4388f498), f32::from_bits(0x42f7f08d), + f32::from_bits(0x43f1cd32), f32::from_bits(0x42802ec1), + ); + let path = pb.finish().unwrap(); + + let mut stroke = Stroke::default(); + stroke.width = 42.835968; + + assert!(PathStroker::new().stroke(&path, &stroke, 1.0).is_some()); + } +} diff --git a/app/vendor/rune/vendor/tiny-skia-path/src/transform.rs b/app/vendor/rune/vendor/tiny-skia-path/src/transform.rs new file mode 100644 index 0000000..2f441b6 --- /dev/null +++ b/app/vendor/rune/vendor/tiny-skia-path/src/transform.rs @@ -0,0 +1,497 @@ +// Copyright 2006 The Android Open Source Project +// Copyright 2020 Yevhenii Reizner +// +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +use crate::{NonZeroRect, Point}; + +use crate::scalar::{Scalar, SCALAR_NEARLY_ZERO}; + +#[cfg(all(not(feature = "std"), feature = "no-std-float"))] +use crate::NoStdFloat; + +/// An affine transformation matrix. +/// +/// Unlike other types, doesn't guarantee to be valid. This is Skia quirk. +/// Meaning Transform(0, 0, 0, 0, 0, 0) is ok, while it's technically not. +/// Non-finite values are also not an error. +#[allow(missing_docs)] +#[derive(Copy, Clone, PartialEq, Debug)] +pub struct Transform { + pub sx: f32, + pub kx: f32, + pub ky: f32, + pub sy: f32, + pub tx: f32, + pub ty: f32, +} + +impl Default for Transform { + fn default() -> Self { + Transform { + sx: 1.0, + kx: 0.0, + ky: 0.0, + sy: 1.0, + tx: 0.0, + ty: 0.0, + } + } +} + +impl Transform { + /// Creates an identity transform. + pub fn identity() -> Self { + Transform::default() + } + + /// Creates a new `Transform`. + /// + /// We are using column-major-column-vector matrix notation, therefore it's ky-kx, not kx-ky. + pub fn from_row(sx: f32, ky: f32, kx: f32, sy: f32, tx: f32, ty: f32) -> Self { + Transform { + sx, + ky, + kx, + sy, + tx, + ty, + } + } + + /// Creates a new translating `Transform`. + pub fn from_translate(tx: f32, ty: f32) -> Self { + Transform::from_row(1.0, 0.0, 0.0, 1.0, tx, ty) + } + + /// Creates a new scaling `Transform`. + pub fn from_scale(sx: f32, sy: f32) -> Self { + Transform::from_row(sx, 0.0, 0.0, sy, 0.0, 0.0) + } + + /// Creates a new skewing `Transform`. + pub fn from_skew(kx: f32, ky: f32) -> Self { + Transform::from_row(1.0, ky, kx, 1.0, 0.0, 0.0) + } + + /// Creates a new rotating `Transform`. + /// + /// `angle` in degrees. + pub fn from_rotate(angle: f32) -> Self { + let v = angle.to_radians(); + let a = v.cos(); + let b = v.sin(); + let c = -b; + let d = a; + Transform::from_row(a, b, c, d, 0.0, 0.0) + } + + /// Creates a new rotating `Transform` at the specified position. + /// + /// `angle` in degrees. + pub fn from_rotate_at(angle: f32, tx: f32, ty: f32) -> Self { + let mut ts = Self::default(); + ts = ts.pre_translate(tx, ty); + ts = ts.pre_concat(Transform::from_rotate(angle)); + ts = ts.pre_translate(-tx, -ty); + ts + } + + /// Converts `Rect` into a bounding box `Transform`. + #[inline] + pub fn from_bbox(bbox: NonZeroRect) -> Self { + Transform::from_row(bbox.width(), 0.0, 0.0, bbox.height(), bbox.x(), bbox.y()) + } + + /// Checks that transform is finite. + pub fn is_finite(&self) -> bool { + self.sx.is_finite() + && self.ky.is_finite() + && self.kx.is_finite() + && self.sy.is_finite() + && self.tx.is_finite() + && self.ty.is_finite() + } + + /// Checks that transform is finite and has non-zero scale. + pub fn is_valid(&self) -> bool { + if self.is_finite() { + let (sx, sy) = self.get_scale(); + !(sx.is_nearly_zero_within_tolerance(f32::EPSILON) + || sy.is_nearly_zero_within_tolerance(f32::EPSILON)) + } else { + false + } + } + + /// Checks that transform is identity. + pub fn is_identity(&self) -> bool { + *self == Transform::default() + } + + /// Checks that transform is scale-only. + pub fn is_scale(&self) -> bool { + self.has_scale() && !self.has_skew() && !self.has_translate() + } + + /// Checks that transform is skew-only. + pub fn is_skew(&self) -> bool { + !self.has_scale() && self.has_skew() && !self.has_translate() + } + + /// Checks that transform is translate-only. + pub fn is_translate(&self) -> bool { + !self.has_scale() && !self.has_skew() && self.has_translate() + } + + /// Checks that transform contains only scale and translate. + pub fn is_scale_translate(&self) -> bool { + (self.has_scale() || self.has_translate()) && !self.has_skew() + } + + /// Checks that transform contains a scale part. + pub fn has_scale(&self) -> bool { + self.sx != 1.0 || self.sy != 1.0 + } + + /// Checks that transform contains a skew part. + pub fn has_skew(&self) -> bool { + self.kx != 0.0 || self.ky != 0.0 + } + + /// Checks that transform contains a translate part. + pub fn has_translate(&self) -> bool { + self.tx != 0.0 || self.ty != 0.0 + } + + /// Returns transform's scale part. + pub fn get_scale(&self) -> (f32, f32) { + let x_scale = (self.sx * self.sx + self.kx * self.kx).sqrt(); + let y_scale = (self.ky * self.ky + self.sy * self.sy).sqrt(); + (x_scale, y_scale) + } + + /// Pre-scales the current transform. + #[must_use] + pub fn pre_scale(&self, sx: f32, sy: f32) -> Self { + self.pre_concat(Transform::from_scale(sx, sy)) + } + + /// Post-scales the current transform. + #[must_use] + pub fn post_scale(&self, sx: f32, sy: f32) -> Self { + self.post_concat(Transform::from_scale(sx, sy)) + } + + /// Pre-translates the current transform. + #[must_use] + pub fn pre_translate(&self, tx: f32, ty: f32) -> Self { + self.pre_concat(Transform::from_translate(tx, ty)) + } + + /// Post-translates the current transform. + #[must_use] + pub fn post_translate(&self, tx: f32, ty: f32) -> Self { + self.post_concat(Transform::from_translate(tx, ty)) + } + + /// Pre-rotates the current transform. + /// + /// `angle` in degrees. + #[must_use] + pub fn pre_rotate(&self, angle: f32) -> Self { + self.pre_concat(Transform::from_rotate(angle)) + } + + /// Post-rotates the current transform. + /// + /// `angle` in degrees. + #[must_use] + pub fn post_rotate(&self, angle: f32) -> Self { + self.post_concat(Transform::from_rotate(angle)) + } + + /// Pre-rotates the current transform by the specified position. + /// + /// `angle` in degrees. + #[must_use] + pub fn pre_rotate_at(&self, angle: f32, tx: f32, ty: f32) -> Self { + self.pre_concat(Transform::from_rotate_at(angle, tx, ty)) + } + + /// Post-rotates the current transform by the specified position. + /// + /// `angle` in degrees. + #[must_use] + pub fn post_rotate_at(&self, angle: f32, tx: f32, ty: f32) -> Self { + self.post_concat(Transform::from_rotate_at(angle, tx, ty)) + } + + /// Pre-concats the current transform. + #[must_use] + pub fn pre_concat(&self, other: Self) -> Self { + concat(*self, other) + } + + /// Post-concats the current transform. + #[must_use] + pub fn post_concat(&self, other: Self) -> Self { + concat(other, *self) + } + + pub(crate) fn from_sin_cos(sin: f32, cos: f32) -> Self { + Transform::from_row(cos, sin, -sin, cos, 0.0, 0.0) + } + + /// Transforms a points using the current transform. + pub fn map_point(&self, point: &mut Point) { + if self.is_identity() { + // Do nothing. + } else if self.is_translate() { + point.x += self.tx; + point.y += self.ty; + } else if self.is_scale_translate() { + point.x = point.x * self.sx + self.tx; + point.y = point.y * self.sy + self.ty; + } else { + let x = point.x * self.sx + point.y * self.kx + self.tx; + let y = point.x * self.ky + point.y * self.sy + self.ty; + point.x = x; + point.y = y; + } + } + + /// Transforms a slice of points using the current transform. + pub fn map_points(&self, points: &mut [Point]) { + if points.is_empty() { + return; + } + + // TODO: simd + + if self.is_identity() { + // Do nothing. + } else if self.is_translate() { + for p in points { + p.x += self.tx; + p.y += self.ty; + } + } else if self.is_scale_translate() { + for p in points { + p.x = p.x * self.sx + self.tx; + p.y = p.y * self.sy + self.ty; + } + } else { + for p in points { + let x = p.x * self.sx + p.y * self.kx + self.tx; + let y = p.x * self.ky + p.y * self.sy + self.ty; + p.x = x; + p.y = y; + } + } + } + + /// Returns an inverted transform. + pub fn invert(&self) -> Option<Self> { + // Allow the trivial case to be inlined. + if self.is_identity() { + return Some(*self); + } + + invert(self) + } +} + +fn invert(ts: &Transform) -> Option<Transform> { + debug_assert!(!ts.is_identity()); + + if ts.is_scale_translate() { + if ts.has_scale() { + let inv_x = ts.sx.invert(); + let inv_y = ts.sy.invert(); + Some(Transform::from_row( + inv_x, + 0.0, + 0.0, + inv_y, + -ts.tx * inv_x, + -ts.ty * inv_y, + )) + } else { + // translate only + Some(Transform::from_translate(-ts.tx, -ts.ty)) + } + } else { + let inv_det = inv_determinant(ts)?; + let inv_ts = compute_inv(ts, inv_det); + + if inv_ts.is_finite() { + Some(inv_ts) + } else { + None + } + } +} + +fn inv_determinant(ts: &Transform) -> Option<f64> { + let det = dcross(ts.sx as f64, ts.sy as f64, ts.kx as f64, ts.ky as f64); + + // Since the determinant is on the order of the cube of the matrix members, + // compare to the cube of the default nearly-zero constant (although an + // estimate of the condition number would be better if it wasn't so expensive). + let tolerance = SCALAR_NEARLY_ZERO * SCALAR_NEARLY_ZERO * SCALAR_NEARLY_ZERO; + if (det as f32).is_nearly_zero_within_tolerance(tolerance) { + None + } else { + Some(1.0 / det) + } +} + +fn compute_inv(ts: &Transform, inv_det: f64) -> Transform { + Transform::from_row( + (ts.sy as f64 * inv_det) as f32, + (-ts.ky as f64 * inv_det) as f32, + (-ts.kx as f64 * inv_det) as f32, + (ts.sx as f64 * inv_det) as f32, + dcross_dscale(ts.kx, ts.ty, ts.sy, ts.tx, inv_det), + dcross_dscale(ts.ky, ts.tx, ts.sx, ts.ty, inv_det), + ) +} + +fn dcross(a: f64, b: f64, c: f64, d: f64) -> f64 { + a * b - c * d +} + +fn dcross_dscale(a: f32, b: f32, c: f32, d: f32, scale: f64) -> f32 { + (dcross(a as f64, b as f64, c as f64, d as f64) * scale) as f32 +} + +fn concat(a: Transform, b: Transform) -> Transform { + if a.is_identity() { + b + } else if b.is_identity() { + a + } else if !a.has_skew() && !b.has_skew() { + // just scale and translate + Transform::from_row( + a.sx * b.sx, + 0.0, + 0.0, + a.sy * b.sy, + a.sx * b.tx + a.tx, + a.sy * b.ty + a.ty, + ) + } else { + Transform::from_row( + mul_add_mul(a.sx, b.sx, a.kx, b.ky), + mul_add_mul(a.ky, b.sx, a.sy, b.ky), + mul_add_mul(a.sx, b.kx, a.kx, b.sy), + mul_add_mul(a.ky, b.kx, a.sy, b.sy), + mul_add_mul(a.sx, b.tx, a.kx, b.ty) + a.tx, + mul_add_mul(a.ky, b.tx, a.sy, b.ty) + a.ty, + ) + } +} + +fn mul_add_mul(a: f32, b: f32, c: f32, d: f32) -> f32 { + (f64::from(a) * f64::from(b) + f64::from(c) * f64::from(d)) as f32 +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn transform() { + assert_eq!( + Transform::identity(), + Transform::from_row(1.0, 0.0, 0.0, 1.0, 0.0, 0.0) + ); + + assert_eq!( + Transform::from_scale(1.0, 2.0), + Transform::from_row(1.0, 0.0, 0.0, 2.0, 0.0, 0.0) + ); + + assert_eq!( + Transform::from_skew(2.0, 3.0), + Transform::from_row(1.0, 3.0, 2.0, 1.0, 0.0, 0.0) + ); + + assert_eq!( + Transform::from_translate(5.0, 6.0), + Transform::from_row(1.0, 0.0, 0.0, 1.0, 5.0, 6.0) + ); + + let ts = Transform::identity(); + assert_eq!(ts.is_identity(), true); + assert_eq!(ts.is_scale(), false); + assert_eq!(ts.is_skew(), false); + assert_eq!(ts.is_translate(), false); + assert_eq!(ts.is_scale_translate(), false); + assert_eq!(ts.has_scale(), false); + assert_eq!(ts.has_skew(), false); + assert_eq!(ts.has_translate(), false); + + let ts = Transform::from_scale(2.0, 3.0); + assert_eq!(ts.is_identity(), false); + assert_eq!(ts.is_scale(), true); + assert_eq!(ts.is_skew(), false); + assert_eq!(ts.is_translate(), false); + assert_eq!(ts.is_scale_translate(), true); + assert_eq!(ts.has_scale(), true); + assert_eq!(ts.has_skew(), false); + assert_eq!(ts.has_translate(), false); + + let ts = Transform::from_skew(2.0, 3.0); + assert_eq!(ts.is_identity(), false); + assert_eq!(ts.is_scale(), false); + assert_eq!(ts.is_skew(), true); + assert_eq!(ts.is_translate(), false); + assert_eq!(ts.is_scale_translate(), false); + assert_eq!(ts.has_scale(), false); + assert_eq!(ts.has_skew(), true); + assert_eq!(ts.has_translate(), false); + + let ts = Transform::from_translate(2.0, 3.0); + assert_eq!(ts.is_identity(), false); + assert_eq!(ts.is_scale(), false); + assert_eq!(ts.is_skew(), false); + assert_eq!(ts.is_translate(), true); + assert_eq!(ts.is_scale_translate(), true); + assert_eq!(ts.has_scale(), false); + assert_eq!(ts.has_skew(), false); + assert_eq!(ts.has_translate(), true); + + let ts = Transform::from_row(1.0, 2.0, 3.0, 4.0, 5.0, 6.0); + assert_eq!(ts.is_identity(), false); + assert_eq!(ts.is_scale(), false); + assert_eq!(ts.is_skew(), false); + assert_eq!(ts.is_translate(), false); + assert_eq!(ts.is_scale_translate(), false); + assert_eq!(ts.has_scale(), true); + assert_eq!(ts.has_skew(), true); + assert_eq!(ts.has_translate(), true); + + let ts = Transform::from_scale(1.0, 1.0); + assert_eq!(ts.has_scale(), false); + + let ts = Transform::from_skew(0.0, 0.0); + assert_eq!(ts.has_skew(), false); + + let ts = Transform::from_translate(0.0, 0.0); + assert_eq!(ts.has_translate(), false); + } + + #[test] + fn concat() { + let mut ts = Transform::from_row(1.2, 3.4, -5.6, -7.8, 1.2, 3.4); + ts = ts.pre_scale(2.0, -4.0); + assert_eq!(ts, Transform::from_row(2.4, 6.8, 22.4, 31.2, 1.2, 3.4)); + + let mut ts = Transform::from_row(1.2, 3.4, -5.6, -7.8, 1.2, 3.4); + ts = ts.post_scale(2.0, -4.0); + assert_eq!(ts, Transform::from_row(2.4, -13.6, -11.2, 31.2, 2.4, -13.6)); + } +} diff --git a/app/vendor/rune/vendor/wgpu-hal.patch b/app/vendor/rune/vendor/wgpu-hal.patch new file mode 100644 index 0000000..b8ab952 --- /dev/null +++ b/app/vendor/rune/vendor/wgpu-hal.patch @@ -0,0 +1,1074 @@ +diff --git a/src/auxil/dxgi/factory.rs b/src/auxil/dxgi/factory.rs +index ac050bc..6e3c74e 100644 +--- a/src/auxil/dxgi/factory.rs ++++ b/src/auxil/dxgi/factory.rs +@@ -9,7 +9,7 @@ use super::result::HResult as _; + + // We can rely on the presence of DXGI 1.4 since D3D12 requires WDDM 2.0, Windows 10 (1507), and so does DXGI 1.4. + +-fn should_keep_adapter(adapter: &Dxgi::IDXGIAdapter1) -> bool { ++pub(crate) fn should_keep_adapter(adapter: &Dxgi::IDXGIAdapter1) -> bool { + let desc = unsafe { adapter.GetDesc1() }.unwrap(); + + // The Intel Haswell family of iGPUs had support for the D3D12 API but it was later +diff --git a/src/dx12/adapter.rs b/src/dx12/adapter.rs +index 621eea4..fd5a64e 100644 +--- a/src/dx12/adapter.rs ++++ b/src/dx12/adapter.rs +@@ -1096,6 +1096,7 @@ impl crate::Adapter for super::Adapter { + .into_device_result("Queue idle fence creation")?; + let idle_event = super::Event::create(false, false)?; + ++ let drain = Arc::clone(&device.shared.drain); + Ok(crate::OpenDevice { + device, + queue: super::Queue { +@@ -1106,6 +1107,7 @@ impl crate::Adapter for super::Adapter { + idle_fence_value: AtomicU64::new(0), + pending_waits: Mutex::new(Vec::new()), + pending_signals: Mutex::new(Vec::new()), ++ drain, + }, + }) + } +diff --git a/src/dx12/command.rs b/src/dx12/command.rs +index 9e90e26..762d922 100644 +--- a/src/dx12/command.rs ++++ b/src/dx12/command.rs +@@ -389,22 +389,22 @@ impl crate::CommandEncoder for super::CommandEncoder { + type A = super::Api; + + unsafe fn begin_encoding(&mut self, label: crate::Label) -> Result<(), crate::DeviceError> { +- let list = loop { +- if let Some(list) = self.free_lists.pop() { ++ let reused = loop { ++ if let Some((list, list2)) = self.free_lists.pop() { + // TODO: Is an error expected here and should we print it? + let reset_result = unsafe { list.Reset(&self.allocator, None) }; + if reset_result.is_ok() { +- break Some(list); ++ break Some((list, list2)); + } + } else { + break None; + } + }; + +- let list = if let Some(list) = list { +- list ++ let (list, list2) = if let Some(pair) = reused { ++ pair + } else { +- unsafe { ++ let list: Direct3D12::ID3D12GraphicsCommandList = unsafe { + self.device.CreateCommandList( + 0, + Direct3D12::D3D12_COMMAND_LIST_TYPE_DIRECT, +@@ -412,7 +412,13 @@ impl crate::CommandEncoder for super::CommandEncoder { + None, + ) + } +- .into_device_result("Create command list")? ++ .into_device_result("Create command list")?; ++ let list2 = if self.shared.drain.has_marker() { ++ list.cast::<Direct3D12::ID3D12GraphicsCommandList2>().ok() ++ } else { ++ None ++ }; ++ (list, list2) + }; + + if let Some(label) = label { +@@ -425,24 +431,34 @@ impl crate::CommandEncoder for super::CommandEncoder { + self.end_of_pass_timer_query = None; + + self.list = Some(list); ++ self.list2 = list2; + Ok(()) + } + unsafe fn discard_encoding(&mut self) { ++ let list2 = self.list2.take(); + if let Some(list) = self.list.take() { + if unsafe { list.Close() }.is_ok() { +- self.free_lists.push(list); ++ self.free_lists.push((list, list2)); + } + } + } + unsafe fn end_encoding(&mut self) -> Result<super::CommandBuffer, crate::DeviceError> { + let raw = self.list.take().unwrap(); ++ let list2 = self.list2.take(); ++ let marker = self.shared.drain.record(list2.as_ref()); + unsafe { raw.Close() }.into_device_result("GraphicsCommandList::close")?; +- Ok(super::CommandBuffer { raw }) ++ Ok(super::CommandBuffer { raw, list2, marker }) + } + unsafe fn reset_all<I: Iterator<Item = super::CommandBuffer>>(&mut self, command_buffers: I) { + self.intermediate_copy_bufs.clear(); + for cmd_buf in command_buffers { +- self.free_lists.push(cmd_buf.raw); ++ self.free_lists.push((cmd_buf.raw, cmd_buf.list2)); ++ } ++ // Rune: never reset a command allocator on a removed device; no new commands will ever ++ // be recorded on it, and a timed-out drain on a removed device could still have the ++ // driver unwinding a list recorded in this allocator. ++ if self.shared.drain.is_removed() { ++ return; + } + if let Err(e) = unsafe { self.allocator.Reset() } { + log::error!("ID3D12CommandAllocator::Reset() failed with {e}"); +diff --git a/src/dx12/dcomp.rs b/src/dx12/dcomp.rs +index 46ef3da..035f9bd 100644 +--- a/src/dx12/dcomp.rs ++++ b/src/dx12/dcomp.rs +@@ -19,7 +19,7 @@ impl DCompLib { + pub(crate) fn new() -> Self { + Self { + lib: Lazy::new(|| unsafe { +- DynLib::new("dcomp.dll").map_err(|err| { ++ DynLib::new_system("dcomp.dll").map_err(|err| { + log::error!("Error loading dcomp.dll: {err}"); + crate::SurfaceError::Other("Error loading dcomp.dll") + }) +diff --git a/src/dx12/descriptor.rs b/src/dx12/descriptor.rs +index f57ba46..475a9e3 100644 +--- a/src/dx12/descriptor.rs ++++ b/src/dx12/descriptor.rs +@@ -37,6 +37,10 @@ pub(super) struct GeneralHeap { + total_handles: u64, + start: DualHandle, + ranges: Mutex<RangeAllocator<DescriptorIndex>>, ++ // Zero-sized without wgpu's counters. Updated under the range lock, so a free racing ++ // an allocation cannot inflate the high-water mark. ++ live: wgt::InternalCounter, ++ peak: wgt::InternalCounter, + } + + impl GeneralHeap { +@@ -70,6 +74,8 @@ impl GeneralHeap { + total_handles, + start, + ranges: Mutex::new(RangeAllocator::new(0..total_handles)), ++ live: Default::default(), ++ peak: Default::default(), + }) + } + +@@ -95,10 +101,17 @@ impl GeneralHeap { + } + + pub(super) fn allocate_slice(&self, count: u64) -> Result<DescriptorIndex, crate::DeviceError> { +- let range = self.ranges.lock().allocate_range(count).map_err(|err| { ++ let mut ranges = self.ranges.lock(); ++ let range = ranges.allocate_range(count).map_err(|err| { + log::error!("Unable to allocate descriptors: {err:?}"); + crate::DeviceError::OutOfMemory + })?; ++ self.live.add(count as isize); ++ let live = self.live.read(); ++ if live > self.peak.read() { ++ self.peak.set(live); ++ std::eprintln!("dx12: peak live view descriptors {live}/{} ({} B each)", self.total_handles, self.handle_size); ++ } + Ok(range.start) + } + +@@ -106,7 +119,9 @@ impl GeneralHeap { + /// Do not use this with handles not given out by this `DescriptorHeapSlice`. + pub(crate) fn free_slice(&self, handle: DualHandle) { + let start = (handle.gpu.ptr - self.start.gpu.ptr) / self.handle_size; +- self.ranges.lock().free_range(start..start + handle.count); ++ let mut ranges = self.ranges.lock(); ++ ranges.free_range(start..start + handle.count); ++ self.live.sub(handle.count as isize); + } + } + +diff --git a/src/dx12/device.rs b/src/dx12/device.rs +index 63fb313..aa74ea5 100644 +--- a/src/dx12/device.rs ++++ b/src/dx12/device.rs +@@ -136,6 +136,7 @@ impl super::Device { + None + }; + ++ let drain = Arc::new(super::DrainTracker::new(&adapter, &raw)); + let shared = super::DeviceShared { + adapter, + zero_buffer, +@@ -179,6 +180,7 @@ impl super::Device { + )?, + sampler_heap: super::sampler::SamplerHeap::new(&raw, &private_caps)?, + private_caps, ++ drain, + }; + + let mut rtv_pool = +@@ -256,23 +258,71 @@ impl super::Device { + signature.ok_or(crate::DeviceError::Unexpected) + } + ++ /// Rune: the highest value `fence` has reached, or None once the device is removed. A ++ /// removed device's fence reads `u64::MAX` (a GPU reset after a timeout, a driver update, a ++ /// GPU unplugged), which wgpu-core would take as every submission finished: each pending ++ /// work-done callback and buffer map would complete as if its work had run. Reporting the ++ /// value the fence last really reached leaves them pending, which they are: they will never ++ /// finish. An error here instead would make wgpu's `Device::poll` panic ("Parent device is ++ /// lost"). The removal itself is seen by the caller (Rune's `rune_gpu::health::removed`) and ++ /// by wgpu at the device's next submission, whose signal fails. ++ fn reached(&self, fence: &super::Fence) -> Option<crate::FenceValue> { ++ let value = unsafe { fence.raw.GetCompletedValue() }; ++ if value == u64::MAX { ++ // Never stored: read a moment before D3D12 reports the removal, it would stay ++ // "everything finished" for good. ++ if unsafe { self.raw.GetDeviceRemovedReason() }.is_err() { ++ self.shared.drain.mark_removed(); ++ return None; ++ } ++ return Some(fence.reached.load(core::sync::atomic::Ordering::Relaxed)); ++ } ++ Some(fence.reached.fetch_max(value, core::sync::atomic::Ordering::Relaxed).max(value)) ++ } ++ + // Blocks until the dedicated present queue is finished with all of its work. + // + // Once this method completes, the surface is able to be resized or deleted. + pub(super) unsafe fn wait_for_present_queue_idle(&self) -> Result<(), crate::DeviceError> { ++ let on_removed = || { ++ self.shared.drain.mark_removed(); ++ self.shared.drain.wait_after_removal(); ++ Err(crate::DeviceError::Lost) ++ }; + let cur_value = unsafe { self.idler.fence.GetCompletedValue() }; + if cur_value == !0 { +- return Err(crate::DeviceError::Lost); ++ return on_removed(); + } + + let event = Event::create(false, false)?; + + let value = cur_value + 1; +- unsafe { self.present_queue.Signal(&self.idler.fence, value) } +- .into_device_result("Signal")?; +- let hr = unsafe { self.idler.fence.SetEventOnCompletion(value, event.0) }; +- hr.into_device_result("Set event")?; +- unsafe { Threading::WaitForSingleObject(event.0, Threading::INFINITE) }; ++ if let Err(err) = unsafe { self.present_queue.Signal(&self.idler.fence, value) } ++ .into_device_result("Signal") ++ { ++ if matches!(err, crate::DeviceError::Lost) { ++ return on_removed(); ++ } ++ return Err(err); ++ } ++ if let Err(err) = unsafe { self.idler.fence.SetEventOnCompletion(value, event.0) } ++ .into_device_result("Set event") ++ { ++ if matches!(err, crate::DeviceError::Lost) { ++ return on_removed(); ++ } ++ return Err(err); ++ } ++ while unsafe { Threading::WaitForSingleObject(event.0, 100) } == Foundation::WAIT_TIMEOUT { ++ if unsafe { self.raw.GetDeviceRemovedReason() }.is_err() { ++ return on_removed(); ++ } ++ } ++ if unsafe { self.idler.fence.GetCompletedValue() } == !0 ++ && unsafe { self.raw.GetDeviceRemovedReason() }.is_err() ++ { ++ return on_removed(); ++ } + Ok(()) + } + +@@ -826,6 +876,7 @@ impl crate::Device for super::Device { + intermediate_copy_bufs: Vec::new(), + null_rtv_handle: self.null_rtv_handle, + list: None, ++ list2: None, + free_lists: Vec::new(), + pass: super::PassState::new(), + temp: super::Temp::default(), +@@ -2346,7 +2397,7 @@ impl crate::Device for super::Device { + + self.counters.fences.add(1); + +- Ok(super::Fence { raw }) ++ Ok(super::Fence { raw, reached: Default::default() }) + } + unsafe fn destroy_fence(&self, _fence: super::Fence) { + self.counters.fences.sub(1); +@@ -2356,7 +2407,7 @@ impl crate::Device for super::Device { + &self, + fence: &super::Fence, + ) -> Result<crate::FenceValue, crate::DeviceError> { +- Ok(unsafe { fence.raw.GetCompletedValue() }) ++ Ok(self.reached(fence).unwrap_or_else(|| fence.reached.load(core::sync::atomic::Ordering::Relaxed))) + } + unsafe fn wait( + &self, +@@ -2367,7 +2418,8 @@ impl crate::Device for super::Device { + let timeout = timeout.unwrap_or(Duration::MAX); + + // We first check if the fence has already reached the value we're waiting for. +- let mut fence_value = unsafe { fence.raw.GetCompletedValue() }; ++ // A removed device's fence never reaches `value`. ++ let Some(mut fence_value) = self.reached(fence) else { return Ok(false) }; + if fence_value >= value { + return Ok(true); + } +@@ -2408,17 +2460,23 @@ impl crate::Device for super::Device { + + log::trace!("Waiting for fence value {value} for {remaining_wait_duration:?}"); + ++ // Rune: in slices of at most 100 ms, reading the fence again after each. A fence can ++ // read `u64::MAX` a moment before D3D12 reports the removal; `reached` then gives the ++ // last real value, and the auto-reset event, already fired by that `u64::MAX`, never ++ // fires again: one wait for the whole timeout (`INFINITE` for `wait_indefinitely`) ++ // would never return. A slice that ends without the event costs a re-read ++ // (`GetCompletedValue`, and `GetDeviceRemovedReason` once the fence reads `u64::MAX`); ++ // a wait the GPU answers returns on the event, as before. ++ let slice = remaining_wait_duration.min(Duration::from_millis(100)); + match unsafe { +- Threading::WaitForSingleObject( +- event.0, +- remaining_wait_duration.as_millis().min(u32::MAX as u128) as u32, +- ) ++ Threading::WaitForSingleObject(event.0, slice.as_millis().min(u32::MAX as u128) as u32) + } { + Foundation::WAIT_OBJECT_0 => {} + Foundation::WAIT_ABANDONED | Foundation::WAIT_FAILED => { + log::error!("Wait failed!"); + break Err(crate::DeviceError::Lost); + } ++ Foundation::WAIT_TIMEOUT if slice < remaining_wait_duration => {} + Foundation::WAIT_TIMEOUT => { + log::trace!("Wait timed out!"); + break Ok(false); +@@ -2429,7 +2487,10 @@ impl crate::Device for super::Device { + } + }; + +- fence_value = unsafe { fence.raw.GetCompletedValue() }; ++ fence_value = match self.reached(fence) { ++ Some(value) => value, ++ None => break Ok(false), ++ }; + log::trace!("Wait complete! Fence actual value: {fence_value}"); + + if fence_value >= value { +diff --git a/src/dx12/instance.rs b/src/dx12/instance.rs +index fdb63bc..5f64a80 100644 +--- a/src/dx12/instance.rs ++++ b/src/dx12/instance.rs +@@ -187,3 +187,37 @@ impl crate::Instance for super::Instance { + .collect() + } + } ++ ++impl super::Instance { ++ /// Exposes one adapter the caller found through DXGI, as `enumerate_adapters` exposes each ++ /// one it lists, without creating a device on any other adapter or loading another adapter's ++ /// driver. `None` when the adapter is one `enumerate_adapters` skips or can't run D3D12. ++ /// ++ /// # Safety ++ /// ++ /// `adapter` must come from a DXGI factory in this process. ++ pub unsafe fn expose_adapter( ++ &self, ++ adapter: &Dxgi::IDXGIAdapter1, ++ ) -> Option<crate::ExposedAdapter<super::Api>> { ++ use windows::core::Interface as _; ++ if !auxil::dxgi::factory::should_keep_adapter(adapter) { ++ return None; ++ } ++ let raw = match adapter.cast::<Dxgi::IDXGIAdapter4>() { ++ Ok(adapter4) => auxil::dxgi::factory::DxgiAdapter::Adapter4(adapter4), ++ Err(_) => auxil::dxgi::factory::DxgiAdapter::Adapter3(adapter.cast().ok()?), ++ }; ++ super::Adapter::expose( ++ raw, ++ &self.library, ++ &self.device_factory, ++ &self.dcomp_lib, ++ self.flags, ++ self.memory_budget_thresholds, ++ self.compiler_container.clone(), ++ self.options.clone(), ++ self.telemetry, ++ ) ++ } ++} +diff --git a/src/dx12/mod.rs b/src/dx12/mod.rs +index 285d635..2fb4210 100644 +--- a/src/dx12/mod.rs ++++ b/src/dx12/mod.rs +@@ -92,7 +92,7 @@ mod suballocation; + mod types; + mod view; + +-use alloc::{borrow::ToOwned as _, string::String, sync::Arc, vec::Vec}; ++use alloc::{borrow::ToOwned as _, collections::VecDeque, string::String, sync::Arc, vec::Vec}; + use core::{ffi, fmt, mem, ops::Deref, sync::atomic::AtomicU64}; + + use arrayvec::ArrayVec; +@@ -134,6 +134,22 @@ impl DynLib { + unsafe { libloading::Library::new(filename) }.map(|inner| Self { inner }) + } + ++ // Rune: load Windows system DLLs from System32 only, not the app directory or CWD. ++ unsafe fn new_system<P>(filename: P) -> Result<Self, libloading::Error> ++ where ++ P: AsRef<std::ffi::OsStr>, ++ { ++ unsafe { ++ libloading::os::windows::Library::load_with_flags( ++ filename, ++ libloading::os::windows::LOAD_LIBRARY_SEARCH_SYSTEM32, ++ ) ++ } ++ .map(|inner| Self { ++ inner: inner.into(), ++ }) ++ } ++ + unsafe fn get<T>( + &self, + symbol: &[u8], +@@ -164,7 +180,7 @@ pub enum CreateDeviceError { + + impl D3D12Lib { + fn new() -> Result<Self, libloading::Error> { +- unsafe { DynLib::new("d3d12.dll").map(|lib| Self { lib }) } ++ unsafe { DynLib::new_system("d3d12.dll").map(|lib| Self { lib }) } + } + + fn create_device( +@@ -328,7 +344,7 @@ pub(super) struct DxgiLib { + + impl DxgiLib { + pub fn new() -> Result<Self, libloading::Error> { +- unsafe { DynLib::new("dxgi.dll").map(|lib| Self { lib }) } ++ unsafe { DynLib::new_system("dxgi.dll").map(|lib| Self { lib }) } + } + + /// Will error with crate::DeviceError::Unexpected if DXGI 1.3 is not available. +@@ -615,6 +631,8 @@ struct SwapChain { + present_mode: wgt::PresentMode, + format: wgt::TextureFormat, + size: wgt::Extent3d, ++ /// Rune: what the next present changed (Surface::set_present_rects); empty is all of it. ++ dirty: Vec<Foundation::RECT>, + } + + enum SurfaceTarget { +@@ -651,6 +669,15 @@ impl Surface { + Some(self.swap_chain.read().as_ref()?.raw.clone()) + } + ++ /// Rune: the only rectangles the next present changed, in the swap chain's pixels; the rest of ++ /// the buffer holds what the frame before showed. Cleared by the present. ++ pub fn set_present_rects(&self, rects: &[Foundation::RECT]) { ++ if let Some(sc) = self.swap_chain.write().as_mut() { ++ sc.dirty.clear(); ++ sc.dirty.extend_from_slice(rects); ++ } ++ } ++ + /// Returns the waitable handle associated with this swap chain, if any. + /// Handle is only valid while the swap chain is alive. + pub unsafe fn waitable_handle(&self) -> Option<Foundation::HANDLE> { +@@ -741,6 +768,279 @@ struct Idler { + fence: Direct3D12::ID3D12Fence, + } + ++/// Rune: GPU-written drain markers on software adapters (WARP) so releasing a removed device ++/// waits for any queued command lists its CPU worker threads are still executing. After ++/// `RemoveDevice`, D3D12 sets every fence to `u64::MAX` and rejects `Queue::Signal`, so fences ++/// can no longer tell when in-flight lists have finished; releasing allocators or resources ++/// before then crashes on WARP (0xC0000005). ++/// ++/// Hardware adapters (`!DXGI_ADAPTER_FLAG_SOFTWARE`) and drivers without `WriteBufferImmediate` ++/// (`DIRECT`) run with `marker: None` (zero steady-state marker cost: no buffer, no recording, no ++/// submit reads/locks); on hardware a real TDR/unplug aborts the queue so markers would never ++/// land anyway. Skipping `ExecuteCommandLists`, skipping `allocator.Reset()`, and sliced fence ++/// waits still run on every adapter. ++const DRAIN_MARKER_SLOTS: usize = 16_384; ++const DRAIN_STALL_TIMEOUT: core::time::Duration = core::time::Duration::from_millis(250); ++const DRAIN_TOTAL_TIMEOUT: core::time::Duration = core::time::Duration::from_millis(1_000); ++ ++struct DrainMarker { ++ resource: Direct3D12::ID3D12Resource, ++ mapped: core::ptr::NonNull<core::sync::atomic::AtomicU32>, ++ gpu_va: u64, ++ next_tag: core::sync::atomic::AtomicU32, ++} ++ ++// SAFETY: `mapped` points to `DRAIN_MARKER_SLOTS` aligned `AtomicU32`s inside `resource`'s ++// persistently mapped readback buffer and is never dereferenced after `Drop` unmaps it. ++unsafe impl Send for DrainMarker {} ++// SAFETY: all concurrent access to `mapped` is through atomic loads and GPU DMA writes. ++unsafe impl Sync for DrainMarker {} ++ ++impl Drop for DrainMarker { ++ fn drop(&mut self) { ++ let written = Direct3D12::D3D12_RANGE { Begin: 0, End: 0 }; ++ // SAFETY: subresource 0 was mapped in `DrainMarker::new`, and the CPU never writes it. ++ unsafe { self.resource.Unmap(0, Some(&written)) }; ++ } ++} ++ ++impl DrainMarker { ++ fn new(device: &Direct3D12::ID3D12Device) -> Option<Self> { ++ let mut options3 = Direct3D12::D3D12_FEATURE_DATA_D3D12_OPTIONS3::default(); ++ // SAFETY: `options3` matches `D3D12_FEATURE_D3D12_OPTIONS3` in type and byte size. ++ let supported = unsafe { ++ device.CheckFeatureSupport( ++ Direct3D12::D3D12_FEATURE_D3D12_OPTIONS3, ++ <*mut _>::cast(&mut options3), ++ size_of_val(&options3) as u32, ++ ) ++ } ++ .is_ok() ++ && (options3.WriteBufferImmediateSupportFlags.0 ++ & Direct3D12::D3D12_COMMAND_LIST_SUPPORT_FLAG_DIRECT.0) ++ != 0; ++ if !supported { ++ return None; ++ } ++ let heap = Direct3D12::D3D12_HEAP_PROPERTIES { ++ Type: Direct3D12::D3D12_HEAP_TYPE_READBACK, ++ ..Default::default() ++ }; ++ let desc = Direct3D12::D3D12_RESOURCE_DESC { ++ Dimension: Direct3D12::D3D12_RESOURCE_DIMENSION_BUFFER, ++ Alignment: 0, ++ Width: (DRAIN_MARKER_SLOTS * size_of::<u32>()) as u64, ++ Height: 1, ++ DepthOrArraySize: 1, ++ MipLevels: 1, ++ Format: Dxgi::Common::DXGI_FORMAT_UNKNOWN, ++ SampleDesc: Dxgi::Common::DXGI_SAMPLE_DESC { ++ Count: 1, ++ Quality: 0, ++ }, ++ Layout: Direct3D12::D3D12_TEXTURE_LAYOUT_ROW_MAJOR, ++ Flags: Direct3D12::D3D12_RESOURCE_FLAG_NONE, ++ }; ++ let mut resource = None::<Direct3D12::ID3D12Resource>; ++ // SAFETY: valid readback buffer descriptor permanently in `COPY_DEST`; without ++ // `D3D12_HEAP_FLAG_CREATE_NOT_ZEROED`, D3D12 zeroes the buffer on creation so 0 never ++ // matches a non-zero tag. ++ unsafe { ++ device.CreateCommittedResource( ++ &heap, ++ Direct3D12::D3D12_HEAP_FLAG_NONE, ++ &desc, ++ Direct3D12::D3D12_RESOURCE_STATE_COPY_DEST, ++ None, ++ &mut resource, ++ ) ++ } ++ .ok()?; ++ let resource = resource?; ++ let mut raw_ptr = core::ptr::null_mut(); ++ // SAFETY: readback buffer supports persistent CPU mapping on subresource 0. ++ unsafe { resource.Map(0, None, Some(&mut raw_ptr)) }.ok()?; ++ let mapped = core::ptr::NonNull::new(raw_ptr.cast::<core::sync::atomic::AtomicU32>())?; ++ // SAFETY: committed buffer has a valid GPU virtual address for its lifetime. ++ let gpu_va = unsafe { resource.GetGPUVirtualAddress() }; ++ Some(Self { ++ resource, ++ mapped, ++ gpu_va, ++ next_tag: core::sync::atomic::AtomicU32::new(1), ++ }) ++ } ++ ++ fn read(&self, slot: u32) -> u32 { ++ debug_assert!((slot as usize) < DRAIN_MARKER_SLOTS); ++ // SAFETY: `slot` is masked to `< DRAIN_MARKER_SLOTS` inside the mapped buffer. ++ unsafe { ++ (&*self.mapped.as_ptr().add(slot as usize)) ++ .load(core::sync::atomic::Ordering::Acquire) ++ } ++ } ++} ++ ++struct DrainInFlight { ++ /// Submitted `(slot, tag)` markers in FIFO submission order. ++ pending: VecDeque<(u32, u32)>, ++ /// Most recently submitted `tag` per slot (allocated only when `DrainMarker` is active). ++ /// Recording order can differ from submission order (for example `wgpu-core` records ++ /// `(wgpu internal) Transit` at submit time and pushes it ahead of earlier-recorded passes), ++ /// so a lower tag can overwrite a higher tag on the same wrapped slot. Tracking the last ++ /// submitted tag per slot lets earlier superseded entries retire immediately without ++ /// assuming monotonic execution order on a slot. ++ latest_tag: Vec<u32>, ++} ++ ++impl DrainInFlight { ++ fn is_done(&self, state: &DrainMarker, slot: u32, tag: u32) -> bool { ++ self.latest_tag[slot as usize] != tag || state.read(slot) == tag ++ } ++} ++ ++pub(super) struct DrainTracker { ++ marker: Option<DrainMarker>, ++ in_flight: Mutex<DrainInFlight>, ++ drain_gate: Mutex<()>, ++ removed: core::sync::atomic::AtomicBool, ++} ++ ++impl DrainTracker { ++ pub(super) fn new(adapter: &DxgiAdapter, device: &Direct3D12::ID3D12Device) -> Self { ++ // SAFETY: querying static adapter flags on a live DXGI adapter. ++ let software = unsafe { adapter.GetDesc1() }.is_ok_and(|desc| { ++ Dxgi::DXGI_ADAPTER_FLAG(desc.Flags as i32).contains(Dxgi::DXGI_ADAPTER_FLAG_SOFTWARE) ++ }); ++ let marker = if software { DrainMarker::new(device) } else { None }; ++ let latest_tag = if marker.is_some() { ++ alloc::vec![0u32; DRAIN_MARKER_SLOTS] ++ } else { ++ Vec::new() ++ }; ++ Self { ++ marker, ++ in_flight: Mutex::new(DrainInFlight { ++ pending: VecDeque::new(), ++ latest_tag, ++ }), ++ drain_gate: Mutex::new(()), ++ removed: core::sync::atomic::AtomicBool::new(false), ++ } ++ } ++ ++ pub(super) fn has_marker(&self) -> bool { ++ self.marker.is_some() ++ } ++ ++ pub(super) fn mark_removed(&self) { ++ let _in_flight = self.in_flight.lock(); ++ self.removed.store(true, core::sync::atomic::Ordering::Release); ++ } ++ ++ pub(super) fn is_removed(&self) -> bool { ++ self.removed.load(core::sync::atomic::Ordering::Acquire) ++ } ++ ++ pub(super) fn record( ++ &self, ++ list2: Option<&Direct3D12::ID3D12GraphicsCommandList2>, ++ ) -> Option<(u32, u32)> { ++ let state = self.marker.as_ref()?; ++ let list2 = list2?; ++ let tag = loop { ++ let v = state.next_tag.fetch_add(1, core::sync::atomic::Ordering::Relaxed); ++ if v != 0 { ++ break v; ++ } ++ }; ++ let slot = tag & (DRAIN_MARKER_SLOTS as u32 - 1); ++ let param = Direct3D12::D3D12_WRITEBUFFERIMMEDIATE_PARAMETER { ++ Dest: state.gpu_va + u64::from(slot) * 4, ++ Value: tag, ++ }; ++ let mode = Direct3D12::D3D12_WRITEBUFFERIMMEDIATE_MODE_MARKER_OUT; ++ // SAFETY: `Dest` is 4-byte aligned in `state.resource` (`COPY_DEST`); `list2` is open. ++ unsafe { list2.WriteBufferImmediate(1, &param, Some(&mode)) }; ++ Some((slot, tag)) ++ } ++ ++ pub(super) fn track_submitted(&self, command_buffers: &[&CommandBuffer]) -> bool { ++ let Some(state) = self.marker.as_ref() else { ++ return !self.is_removed(); ++ }; ++ let mut guard = self.in_flight.lock(); ++ let in_flight = &mut *guard; ++ if self.removed.load(core::sync::atomic::Ordering::Acquire) { ++ return false; ++ } ++ while let Some(&(slot, tag)) = in_flight.pending.front() { ++ if in_flight.is_done(state, slot, tag) { ++ in_flight.pending.pop_front(); ++ } else { ++ break; ++ } ++ } ++ if in_flight.pending.len() > 64 { ++ let latest_tag = &in_flight.latest_tag; ++ in_flight ++ .pending ++ .retain(|&(slot, tag)| latest_tag[slot as usize] == tag && state.read(slot) != tag); ++ } ++ for cmd_buf in command_buffers { ++ if let Some((slot, tag)) = cmd_buf.marker { ++ in_flight.latest_tag[slot as usize] = tag; ++ in_flight.pending.push_back((slot, tag)); ++ } ++ } ++ true ++ } ++ ++ pub(super) fn wait_after_removal(&self) { ++ let _gate = self.drain_gate.lock(); ++ let Some(state) = self.marker.as_ref() else { ++ self.mark_removed(); ++ return; ++ }; ++ // Set `removed` under `in_flight`'s lock before draining so no concurrent ++ // `track_submitted` can push un-executed markers after `Surface::unconfigure` drains. ++ // Drop any earlier superseded entries on the same slot now; every remaining entry owns ++ // its slot uniquely and waits for its exact tag to land. ++ let mut pending = { ++ let mut guard = self.in_flight.lock(); ++ let in_flight = &mut *guard; ++ self.removed.store(true, core::sync::atomic::Ordering::Release); ++ let latest_tag = &in_flight.latest_tag; ++ in_flight ++ .pending ++ .retain(|&(slot, tag)| latest_tag[slot as usize] == tag && state.read(slot) != tag); ++ if in_flight.pending.is_empty() { ++ return; ++ } ++ mem::take(&mut in_flight.pending) ++ }; ++ let started = std::time::Instant::now(); ++ let mut last_progress = started; ++ loop { ++ let before = pending.len(); ++ pending.retain(|&(slot, tag)| state.read(slot) != tag); ++ if pending.is_empty() { ++ return; ++ } ++ let now = std::time::Instant::now(); ++ if pending.len() < before { ++ last_progress = now; ++ } ++ if now.duration_since(last_progress) >= DRAIN_STALL_TIMEOUT ++ || now.duration_since(started) >= DRAIN_TOTAL_TIMEOUT ++ { ++ return; ++ } ++ std::thread::sleep(core::time::Duration::from_millis(1)); ++ } ++ } ++} ++ + #[derive(Debug, Clone)] + struct CommandSignatures { + draw: Direct3D12::ID3D12CommandSignature, +@@ -756,6 +1056,7 @@ struct DeviceShared { + heap_views: descriptor::GeneralHeap, + sampler_heap: sampler::SamplerHeap, + private_caps: PrivateCapabilities, ++ drain: Arc<DrainTracker>, + } + + unsafe impl Send for DeviceShared {} +@@ -810,6 +1111,7 @@ pub struct Queue { + idle_fence_value: AtomicU64, + pending_waits: Mutex<Vec<(Direct3D12::ID3D12Fence, u64)>>, + pending_signals: Mutex<Vec<(Direct3D12::ID3D12Fence, u64)>>, ++ drain: Arc<DrainTracker>, + } + + impl Queue { +@@ -992,7 +1294,11 @@ pub struct CommandEncoder { + + null_rtv_handle: descriptor::Handle, + list: Option<Direct3D12::ID3D12GraphicsCommandList>, +- free_lists: Vec<Direct3D12::ID3D12GraphicsCommandList>, ++ list2: Option<Direct3D12::ID3D12GraphicsCommandList2>, ++ free_lists: Vec<( ++ Direct3D12::ID3D12GraphicsCommandList, ++ Option<Direct3D12::ID3D12GraphicsCommandList2>, ++ )>, + pass: PassState, + temp: Temp, + +@@ -1018,6 +1324,8 @@ impl fmt::Debug for CommandEncoder { + #[derive(Debug)] + pub struct CommandBuffer { + raw: Direct3D12::ID3D12GraphicsCommandList, ++ list2: Option<Direct3D12::ID3D12GraphicsCommandList2>, ++ marker: Option<(u32, u32)>, + } + + impl crate::DynCommandBuffer for CommandBuffer {} +@@ -1209,6 +1517,8 @@ unsafe impl Sync for QuerySet {} + #[derive(Debug)] + pub struct Fence { + raw: Direct3D12::ID3D12Fence, ++ /// Rune: the highest value read from it (`Device::reached`). ++ reached: AtomicU64, + } + + impl crate::DynFence for Fence {} +@@ -1535,7 +1845,9 @@ impl crate::Surface for Surface { + BufferUsage: Dxgi::DXGI_USAGE_RENDER_TARGET_OUTPUT, + BufferCount: swap_chain_buffer, + Scaling: Dxgi::DXGI_SCALING_STRETCH, +- SwapEffect: Dxgi::DXGI_SWAP_EFFECT_FLIP_DISCARD, ++ // Rune: presenting part of a frame (Surface::set_present_rects, Present1's dirty ++ // rectangles) needs the sequential flip model; FLIP_DISCARD can't. ++ SwapEffect: Dxgi::DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL, + Flags: flags.0 as u32, + }; + let swap_chain1 = match self.target { +@@ -1702,6 +2014,7 @@ impl crate::Surface for Surface { + present_mode: config.present_mode, + format: config.format, + size: config.extent, ++ dirty: Vec::new(), + }); + + Ok(()) +@@ -1768,6 +2081,14 @@ impl crate::Surface for Surface { + } + } + ++impl Queue { ++ fn device_removed(&self) -> bool { ++ let mut device: Option<Direct3D12::ID3D12Device> = None; ++ unsafe { self.raw.GetDevice(&mut device) }.is_ok() ++ && device.is_some_and(|device| unsafe { device.GetDeviceRemovedReason() }.is_err()) ++ } ++} ++ + impl crate::Queue for Queue { + type A = Api; + +@@ -1777,6 +2098,18 @@ impl crate::Queue for Queue { + _surface_textures: &[&Texture], + (signal_fence, signal_value): (&Fence, crate::FenceValue), + ) -> Result<(), crate::DeviceError> { ++ // Rune: skip `ExecuteCommandLists` once removed. On software adapters with drain markers, ++ // also check `idle_fence` so a removal before the first poll does not queue untracked ++ // lists; hardware adapters pay only the atomic load (zero COM calls or marker reads). ++ if self.drain.is_removed() ++ || (self.drain.has_marker() ++ && unsafe { self.idle_fence.GetCompletedValue() } == u64::MAX ++ && self.device_removed()) ++ { ++ self.drain.mark_removed(); ++ return Err(crate::DeviceError::Lost); ++ } ++ + let mut temp_lists = self.temp_lists.lock(); + temp_lists.clear(); + for cmd_buf in command_buffers { +@@ -1790,25 +2123,48 @@ impl crate::Queue for Queue { + { + let mut waits = self.pending_waits.lock(); + for (fence, value) in waits.drain(..) { +- unsafe { self.raw.Wait(&fence, value) }.into_device_result("Wait pending fence")?; ++ if let Err(err) = ++ unsafe { self.raw.Wait(&fence, value) }.into_device_result("Wait pending fence") ++ { ++ if matches!(err, crate::DeviceError::Lost) { ++ self.drain.mark_removed(); ++ } ++ return Err(err); ++ } + } + } + ++ if !command_buffers.is_empty() && !self.drain.track_submitted(command_buffers) { ++ return Err(crate::DeviceError::Lost); ++ } ++ + { + profiling::scope!("ID3D12CommandQueue::ExecuteCommandLists"); + unsafe { self.raw.ExecuteCommandLists(&temp_lists) } + } + +- unsafe { self.raw.Signal(&signal_fence.raw, signal_value) } +- .into_device_result("Signal fence")?; ++ if let Err(err) = ++ unsafe { self.raw.Signal(&signal_fence.raw, signal_value) }.into_device_result("Signal fence") ++ { ++ if matches!(err, crate::DeviceError::Lost) { ++ self.drain.mark_removed(); ++ } ++ return Err(err); ++ } + + // Drain caller-staged signals after our own Signal so each + // additional fence value publishes once the submit completes. + { + let mut signals = self.pending_signals.lock(); + for (fence, value) in signals.drain(..) { +- unsafe { self.raw.Signal(&fence, value) } +- .into_device_result("Signal pending fence")?; ++ if let Err(err) = unsafe { self.raw.Signal(&fence, value) } ++ .into_device_result("Signal pending fence") ++ { ++ if matches!(err, crate::DeviceError::Lost) { ++ self.drain.mark_removed(); ++ } ++ return Err(err); ++ } + } + } + +@@ -1838,9 +2194,22 @@ impl crate::Queue for Queue { + }; + + profiling::scope!("IDXGISwapchain3::Present"); +- unsafe { sc.raw.Present(interval, flags) } +- .ok() +- .into_device_result("Present")?; ++ let dirty = core::mem::take(&mut sc.dirty); ++ if dirty.is_empty() { ++ unsafe { sc.raw.Present(interval, flags) } ++ .ok() ++ .into_device_result("Present")?; ++ } else { ++ let params = Dxgi::DXGI_PRESENT_PARAMETERS { ++ DirtyRectsCount: dirty.len() as u32, ++ pDirtyRects: dirty.as_ptr().cast_mut(), ++ pScrollRect: core::ptr::null_mut(), ++ pScrollOffset: core::ptr::null_mut(), ++ }; ++ unsafe { sc.raw.Present1(interval, flags, &params) } ++ .ok() ++ .into_device_result("Present1")?; ++ } + + Ok(()) + } +@@ -1851,18 +2220,51 @@ impl crate::Queue for Queue { + } + + unsafe fn wait_for_idle(&self) -> Result<(), crate::DeviceError> { ++ let on_removed = || { ++ self.drain.mark_removed(); ++ self.drain.wait_after_removal(); ++ Err(crate::DeviceError::Lost) ++ }; ++ if unsafe { self.idle_fence.GetCompletedValue() } == u64::MAX && self.device_removed() { ++ return on_removed(); ++ } + let value = self + .idle_fence_value + .fetch_add(1, core::sync::atomic::Ordering::Relaxed) + + 1; +- unsafe { self.raw.Signal(&self.idle_fence, value) } +- .into_device_result("Signal idle fence")?; +- unsafe { ++ if let Err(err) = unsafe { self.raw.Signal(&self.idle_fence, value) } ++ .into_device_result("Signal idle fence") ++ { ++ if matches!(err, crate::DeviceError::Lost) { ++ return on_removed(); ++ } ++ return Err(err); ++ } ++ if let Err(err) = unsafe { + self.idle_fence + .SetEventOnCompletion(value, self.idle_event.0) + } +- .into_device_result("SetEventOnCompletion")?; +- unsafe { Threading::WaitForSingleObject(self.idle_event.0, Threading::INFINITE) }; ++ .into_device_result("SetEventOnCompletion") ++ { ++ if matches!(err, crate::DeviceError::Lost) { ++ return on_removed(); ++ } ++ return Err(err); ++ } ++ // Rune: a removed device's work never finishes through fences, so the wait asks after ++ // the device every 100 ms instead of waiting forever (wgpu-core waits here when it drops ++ // the queue), and drains queued command lists through GPU-written markers before ++ // returning so wgpu-core doesn't free resources while the driver is still executing them. ++ while unsafe { Threading::WaitForSingleObject(self.idle_event.0, 100) } ++ == Foundation::WAIT_TIMEOUT ++ { ++ if self.device_removed() { ++ return on_removed(); ++ } ++ } ++ if unsafe { self.idle_fence.GetCompletedValue() } == u64::MAX && self.device_removed() { ++ return on_removed(); ++ } + Ok(()) + } + } +diff --git a/src/dx12/shader_compilation.rs b/src/dx12/shader_compilation.rs +index ff41e50..dcb167c 100644 +--- a/src/dx12/shader_compilation.rs ++++ b/src/dx12/shader_compilation.rs +@@ -17,7 +17,8 @@ pub(super) enum CompilerContainer { + } + + pub(super) struct CompilerFxc { +- fxc: FxcLib, ++ /// Loaded on the first compile: an app whose shaders all come precompiled never loads it. ++ fxc: std::sync::OnceLock<Result<FxcLib, String>>, + } + + pub(super) struct CompilerDynamicDxc { +@@ -43,7 +44,7 @@ pub(super) enum GetContainerError { + + impl CompilerContainer { + pub(super) fn new_fxc() -> Result<Self, GetContainerError> { +- FxcLib::new_dynamic().map(|fxc| Self::Fxc(CompilerFxc { fxc })) ++ Ok(Self::Fxc(CompilerFxc { fxc: std::sync::OnceLock::new() })) + } + + pub(super) fn new_dynamic_dxc(dxc_path: PathBuf) -> Result<Self, GetContainerError> { +@@ -121,7 +122,9 @@ impl CompilerContainer { + raw_ep, + stage_bit, + full_stage, +- fxc, ++ fxc.get_or_init(|| FxcLib::new_dynamic().map_err(|e| format!("{e}"))) ++ .as_ref() ++ .map_err(|e| crate::PipelineError::Linkage(stage_bit, e.clone()))?, + ), + CompilerContainer::DynamicDxc(CompilerDynamicDxc { compiler, .. }) + | CompilerContainer::StaticDxc(CompilerStaticDxc { compiler, .. }) => compile_dxc( +@@ -164,7 +167,7 @@ impl FxcLib { + + fn new_dynamic() -> Result<Self, GetContainerError> { + unsafe { +- let lib = crate::dx12::DynLib::new(Self::PATH) ++ let lib = crate::dx12::DynLib::new_system(Self::PATH) + .map_err(|e| GetContainerError::FailedToLoad(FxcLib::PATH, e))?; + let d3dcompile_fn: D3DCompileFn = *lib.get::<D3DCompileFn>(c"D3DCompile".to_bytes())?; + +diff --git a/src/gles/wgl.rs b/src/gles/wgl.rs +index 09ee3e9..4edbf3b 100644 +--- a/src/gles/wgl.rs ++++ b/src/gles/wgl.rs +@@ -455,14 +455,20 @@ impl crate::Instance for Instance { + + unsafe fn init(desc: &crate::InstanceDescriptor<'_>) -> Result<Self, crate::InstanceError> { + profiling::scope!("Init OpenGL (WGL) Backend"); +- let opengl_module = +- unsafe { LibraryLoader::LoadLibraryA(PCSTR(c"opengl32.dll".as_ptr().cast())) } +- .map_err(|e| { +- crate::InstanceError::with_source( +- String::from("unable to load the OpenGL library"), +- e, +- ) +- })?; ++ // Rune: load opengl32.dll from System32 only, not the app directory or CWD. ++ let opengl_module = unsafe { ++ LibraryLoader::LoadLibraryExA( ++ PCSTR(c"opengl32.dll".as_ptr().cast()), ++ None, ++ LibraryLoader::LOAD_LIBRARY_SEARCH_SYSTEM32, ++ ) ++ } ++ .map_err(|e| { ++ crate::InstanceError::with_source( ++ String::from("unable to load the OpenGL library"), ++ e, ++ ) ++ })?; + + let device = create_instance_device()?; + let dc = device.dc; diff --git a/app/vendor/rune/vendor/wgpu-hal/.cargo_vcs_info.json b/app/vendor/rune/vendor/wgpu-hal/.cargo_vcs_info.json new file mode 100644 index 0000000..9d36350 --- /dev/null +++ b/app/vendor/rune/vendor/wgpu-hal/.cargo_vcs_info.json @@ -0,0 +1,6 @@ +{ + "git": { + "sha1": "40f4a34ebaf56f9a046231f54125ad046239d3f3" + }, + "path_in_vcs": "wgpu-hal" +} \ No newline at end of file diff --git a/app/vendor/rune/vendor/wgpu-hal/Cargo.lock b/app/vendor/rune/vendor/wgpu-hal/Cargo.lock new file mode 100644 index 0000000..dfa162e --- /dev/null +++ b/app/vendor/rune/vendor/wgpu-hal/Cargo.lock @@ -0,0 +1,2564 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 3 + +[[package]] +name = "ab_glyph" +version = "0.2.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "01c0457472c38ea5bd1c3b5ada5e368271cb550be7a4ca4a0b4634e9913f6cc2" +dependencies = [ + "ab_glyph_rasterizer", + "owned_ttf_parser", +] + +[[package]] +name = "ab_glyph_rasterizer" +version = "0.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "366ffbaa4442f4684d91e2cd7c5ea7c4ed8add41959a31447066e279e432b618" + +[[package]] +name = "ahash" +version = "0.8.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a15f179cd60c4584b8a8c596927aadc462e27f2ca70c04e0071964a73ba7a75" +dependencies = [ + "cfg-if", + "getrandom", + "once_cell", + "version_check", + "zerocopy", +] + +[[package]] +name = "aho-corasick" +version = "1.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ddd31a130427c27518df266943a5308ed92d4b226cc639f5a8f1002816174301" +dependencies = [ + "memchr", +] + +[[package]] +name = "allocator-api2" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923" + +[[package]] +name = "android-activity" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0f2a1bb052857d5dd49572219344a7332b31b76405648eabac5bc68978251bcd" +dependencies = [ + "android-properties", + "bitflags 2.13.0", + "cc", + "jni", + "libc", + "log", + "ndk", + "ndk-context", + "ndk-sys", + "num_enum", + "thiserror 2.0.18", +] + +[[package]] +name = "android-properties" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc7eb209b1518d6bb87b283c20095f5228ecda460da70b44f0802523dea6da04" + +[[package]] +name = "android_system_properties" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "819e7219dbd41043ac279b19830f2efc897156490d7fd6ea916720117ee66311" +dependencies = [ + "libc", +] + +[[package]] +name = "arrayref" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "76a2e8124351fda1ef8aaaa3bbd7ebbcb486bbcd4225aca0aa0d84bb2db8fecb" + +[[package]] +name = "arrayvec" +version = "0.7.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7c02d123df017efcdfbd739ef81735b36c5ba83ec3c59c80a9d7ecc718f92e50" + +[[package]] +name = "as-raw-xcb-connection" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "175571dd1d178ced59193a6fc02dde1b972eb0bc56c892cde9beeceac5bf0f6b" + +[[package]] +name = "ash" +version = "0.38.0+1.3.281" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bb44936d800fea8f016d7f2311c6a4f97aebd5dc86f09906139ec848cf3a46f" +dependencies = [ + "libloading", +] + +[[package]] +name = "atomic-waker" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" + +[[package]] +name = "autocfg" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" + +[[package]] +name = "bit-set" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2f926cc3060f09db9ebc5b52823d85268d24bb917e472c0c4bea35780a7d" +dependencies = [ + "bit-vec", +] + +[[package]] +name = "bit-vec" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b71798fca2c1fe1086445a7258a4bc81e6e49dcd24c8d0dd9a1e57395b603f51" + +[[package]] +name = "bitflags" +version = "1.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" + +[[package]] +name = "bitflags" +version = "2.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b4388bee8683e3d04af747c73422af53102d2bd24d9eadb6cbc100baef4b43f8" + +[[package]] +name = "block2" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2c132eebf10f5cad5289222520a4a058514204aed6d791f1cf4fe8088b82d15f" +dependencies = [ + "objc2 0.5.2", +] + +[[package]] +name = "block2" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cdeb9d870516001442e364c5220d3574d2da8dc765554b4a617230d33fa58ef5" +dependencies = [ + "objc2 0.6.4", +] + +[[package]] +name = "bumpalo" +version = "3.20.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649" + +[[package]] +name = "bytemuck" +version = "1.25.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c8efb64bd706a16a1bdde310ae86b351e4d21550d98d056f22f8a7f7a2183fec" +dependencies = [ + "bytemuck_derive", +] + +[[package]] +name = "bytemuck_derive" +version = "1.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9abbd1bc6865053c427f7198e6af43bfdedc55ab791faed4fbd361d789575ff" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "bytes" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ae3f5d315924270530207e2a68396c3cc547f6dca3fbdca317cfb1a51edb593" + +[[package]] +name = "calloop" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b99da2f8558ca23c71f4fd15dc57c906239752dd27ff3c00a1d56b685b7cbfec" +dependencies = [ + "bitflags 2.13.0", + "log", + "polling", + "rustix 0.38.44", + "slab", + "thiserror 1.0.69", +] + +[[package]] +name = "calloop-wayland-source" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "95a66a987056935f7efce4ab5668920b5d0dac4a7c99991a67395f13702ddd20" +dependencies = [ + "calloop", + "rustix 0.38.44", + "wayland-backend", + "wayland-client", +] + +[[package]] +name = "cc" +version = "1.2.64" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dad887fd958be91b5098c0248def011f4523ab786cd411be668777e55063501f" +dependencies = [ + "find-msvc-tools", + "jobserver", + "libc", + "shlex", +] + +[[package]] +name = "cfg-if" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" + +[[package]] +name = "cfg_aliases" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527" + +[[package]] +name = "cgl" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ced0551234e87afee12411d535648dd89d2e7f34c78b753395567aff3d447ff" +dependencies = [ + "libc", +] + +[[package]] +name = "codespan-reporting" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af491d569909a7e4dee0ad7db7f5341fef5c614d5b8ec8cf765732aba3cff681" +dependencies = [ + "serde", + "termcolor", + "unicode-width", +] + +[[package]] +name = "combine" +version = "4.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba5a308b75df32fe02788e748662718f03fde005016435c444eea572398219fd" +dependencies = [ + "bytes", + "memchr", +] + +[[package]] +name = "concurrent-queue" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ca0197aee26d1ae37445ee532fefce43251d24cc7c166799f4d46817f1d3973" +dependencies = [ + "crossbeam-utils", +] + +[[package]] +name = "core-foundation" +version = "0.9.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "91e195e091a93c46f7102ec7818a2aa394e1e1771c3ab4825963fa03e45afb8f" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "core-foundation-sys" +version = "0.8.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" + +[[package]] +name = "core-graphics" +version = "0.23.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c07782be35f9e1140080c6b96f0d44b739e2278479f64e02fdab4e32dfd8b081" +dependencies = [ + "bitflags 1.3.2", + "core-foundation", + "core-graphics-types", + "foreign-types", + "libc", +] + +[[package]] +name = "core-graphics-types" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "45390e6114f68f718cc7a830514a96f903cccd70d02a8f6d9f643ac4ba45afaf" +dependencies = [ + "bitflags 1.3.2", + "core-foundation", + "libc", +] + +[[package]] +name = "crossbeam-utils" +version = "0.8.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d0a5c400df2834b80a4c3327b3aad3a4c4cd4de0629063962b03235697506a28" + +[[package]] +name = "crunchy" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5" + +[[package]] +name = "cursor-icon" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f27ae1dd37df86211c42e150270f82743308803d90a6f6e6651cd730d5e1732f" + +[[package]] +name = "dispatch" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bd0c93bb4b0c6d9b77f4435b0ae98c24d17f1c45b2ff844c6151a07256ca923b" + +[[package]] +name = "dispatch2" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e0e367e4e7da84520dedcac1901e4da967309406d1e51017ae1abfb97adbd38" +dependencies = [ + "bitflags 2.13.0", + "objc2 0.6.4", +] + +[[package]] +name = "dlib" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ab8ecd87370524b461f8557c119c405552c396ed91fc0a8eec68679eab26f94a" +dependencies = [ + "libloading", +] + +[[package]] +name = "downcast-rs" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "75b325c5dbd37f80359721ad39aca5a29fb04c89279657cffdda8736d0c0b9d2" + +[[package]] +name = "dpi" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d8b14ccef22fc6f5a8f4d7d768562a182c04ce9a3b3157b91390b52ddfdf1a76" + +[[package]] +name = "drm" +version = "0.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7a41816e58f47f49acfd956651055ddcf137c4882c2098c30c448817af21183a" +dependencies = [ + "bitflags 2.13.0", + "bytemuck", + "bytemuck_derive", + "drm-ffi", + "drm-fourcc", + "libc", + "rustix 1.1.4", +] + +[[package]] +name = "drm-ffi" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "51a91c9b32ac4e8105dec255e849e0d66e27d7c34d184364fb93e469db08f690" +dependencies = [ + "drm-sys", + "rustix 1.1.4", +] + +[[package]] +name = "drm-fourcc" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0aafbcdb8afc29c1a7ee5fbe53b5d62f4565b35a042a662ca9fecd0b54dae6f4" + +[[package]] +name = "drm-sys" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ecc8e1361066d91f5ffccff060a3c3be9c3ecde15be2959c1937595f7a82a9f8" +dependencies = [ + "libc", + "linux-raw-sys 0.9.4", +] + +[[package]] +name = "env_filter" +version = "2.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "900d271a03799a1ee8d1ca9b19893b48ca674a9284fefcfb85f05e74ed314217" +dependencies = [ + "log", + "regex", +] + +[[package]] +name = "env_logger" +version = "0.11.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "de671bd27a75a797dc9ae289ba1e77276e75e2026408aab65185384e2d5cd3f6" +dependencies = [ + "env_filter", + "log", +] + +[[package]] +name = "equivalent" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f" + +[[package]] +name = "errno" +version = "0.3.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "find-msvc-tools" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5baebc0774151f905a1a2cc41989300b1e6fbb29aff0ceffa1064fdd3088d582" + +[[package]] +name = "foldhash" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" + +[[package]] +name = "foreign-types" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d737d9aa519fb7b749cbc3b962edcf310a8dd1f4b67c91c4f83975dbdd17d965" +dependencies = [ + "foreign-types-macros", + "foreign-types-shared", +] + +[[package]] +name = "foreign-types-macros" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1a5c6c585bc94aaf2c7b51dd4c2ba22680844aba4c687be581871a6f518c5742" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "foreign-types-shared" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aa9a19cbb55df58761df49b23516a86d432839add4af60fc256da840f66ed35b" + +[[package]] +name = "futures-core" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e3450815272ef58cec6d564423f6e755e25379b217b0bc688e295ba24df6b1d" + +[[package]] +name = "futures-task" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "037711b3d59c33004d3856fbdc83b99d4ff37a24768fa1be9ce3538a1cde4393" + +[[package]] +name = "futures-util" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "389ca41296e6190b48053de0321d02a77f32f8a5d2461dd38762c0593805c6d6" +dependencies = [ + "futures-core", + "futures-task", + "pin-project-lite", + "slab", +] + +[[package]] +name = "gethostname" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1bd49230192a3797a9a4d6abe9b3eed6f7fa4c8a8a4947977c6f80025f92cbd8" +dependencies = [ + "rustix 1.1.4", + "windows-link", +] + +[[package]] +name = "getrandom" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd" +dependencies = [ + "cfg-if", + "libc", + "r-efi", + "wasip2", +] + +[[package]] +name = "gl_generator" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1a95dfc23a2b4a9a2f5ab41d194f8bfda3cabec42af4e39f08c339eb2a0c124d" +dependencies = [ + "khronos_api", + "log", + "xml-rs", +] + +[[package]] +name = "glam" +version = "0.33.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "898f5a568a84989b6c0f8caa50a93074b97dbdc58fc6d9543157bb4562758933" + +[[package]] +name = "glow" +version = "0.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29038e1c483364cc6bb3cf78feee1816002e127c331a1eec55a4d202b9e1adb5" +dependencies = [ + "js-sys", + "slotmap", + "wasm-bindgen", + "web-sys", +] + +[[package]] +name = "glutin" +version = "0.32.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "12124de845cacfebedff80e877bb37b5b75c34c5a4c89e47e1cdd67fb6041325" +dependencies = [ + "bitflags 2.13.0", + "cfg_aliases", + "cgl", + "dispatch2", + "glutin_egl_sys", + "glutin_wgl_sys", + "libloading", + "objc2 0.6.4", + "objc2-app-kit 0.3.2", + "objc2-core-foundation", + "objc2-foundation 0.3.2", + "once_cell", + "raw-window-handle", + "wayland-sys", + "windows-sys 0.52.0", + "x11-dl", +] + +[[package]] +name = "glutin-winit" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85edca7075f8fc728f28cb8fbb111a96c3b89e930574369e3e9c27eb75d3788f" +dependencies = [ + "cfg_aliases", + "glutin", + "raw-window-handle", + "winit", +] + +[[package]] +name = "glutin_egl_sys" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4c4680ba6195f424febdc3ba46e7a42a0e58743f2edb115297b86d7f8ecc02d2" +dependencies = [ + "gl_generator", + "windows-sys 0.52.0", +] + +[[package]] +name = "glutin_wgl_sys" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2c4ee00b289aba7a9e5306d57c2d05499b2e5dc427f84ac708bd2c090212cf3e" +dependencies = [ + "gl_generator", +] + +[[package]] +name = "gpu-allocator" +version = "0.28.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "51255ea7cfaadb6c5f1528d43e92a82acb2b96c43365989a28b2d44ee38f8795" +dependencies = [ + "ash", + "hashbrown 0.16.1", + "log", + "presser", + "thiserror 2.0.18", + "windows", +] + +[[package]] +name = "half" +version = "2.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ea2d84b969582b4b1864a92dc5d27cd2b77b622a8d79306834f1be5ba20d84b" +dependencies = [ + "cfg-if", + "crunchy", + "num-traits", + "zerocopy", +] + +[[package]] +name = "hashbrown" +version = "0.16.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100" +dependencies = [ + "allocator-api2", + "equivalent", + "foldhash", +] + +[[package]] +name = "hashbrown" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" +dependencies = [ + "foldhash", +] + +[[package]] +name = "hermit-abi" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc0fef456e4baa96da950455cd02c081ca953b141298e41db3fc7e36b1da849c" + +[[package]] +name = "indexmap" +version = "2.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d466e9454f08e4a911e14806c24e16fba1b4c121d1ea474396f396069cf949d9" +dependencies = [ + "equivalent", + "hashbrown 0.17.1", +] + +[[package]] +name = "jni" +version = "0.22.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5efd9a482cf3a427f00d6b35f14332adc7902ce91efb778580e180ff90fa3498" +dependencies = [ + "cfg-if", + "combine", + "jni-macros", + "jni-sys 0.4.1", + "log", + "simd_cesu8", + "thiserror 2.0.18", + "walkdir", + "windows-link", +] + +[[package]] +name = "jni-macros" +version = "0.22.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a00109accc170f0bdb141fed3e393c565b6f5e072365c3bd58f5b062591560a3" +dependencies = [ + "proc-macro2", + "quote", + "rustc_version", + "simd_cesu8", + "syn", +] + +[[package]] +name = "jni-sys" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41a652e1f9b6e0275df1f15b32661cf0d4b78d4d87ddec5e0c3c20f097433258" +dependencies = [ + "jni-sys 0.4.1", +] + +[[package]] +name = "jni-sys" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6377a88cb3910bee9b0fa88d4f42e1d2da8e79915598f65fb0c7ee14c878af2" +dependencies = [ + "jni-sys-macros", +] + +[[package]] +name = "jni-sys-macros" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38c0b942f458fe50cdac086d2f946512305e5631e720728f2a61aabcd47a6264" +dependencies = [ + "quote", + "syn", +] + +[[package]] +name = "jobserver" +version = "0.1.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9afb3de4395d6b3e67a780b6de64b51c978ecf11cb9a462c66be7d4ca9039d33" +dependencies = [ + "getrandom", + "libc", +] + +[[package]] +name = "js-sys" +version = "0.3.104" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e0c1080212aad755ea003d18543e8768dd432c48819efd73a7bf1e39b7a5a3a" +dependencies = [ + "cfg-if", + "futures-util", + "wasm-bindgen", +] + +[[package]] +name = "khronos-egl" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6aae1df220ece3c0ada96b8153459b67eebe9ae9212258bb0134ae60416fdf76" +dependencies = [ + "libc", + "libloading", + "pkg-config", +] + +[[package]] +name = "khronos_api" +version = "3.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e2db585e1d738fc771bf08a151420d3ed193d9d895a36df7f6f8a9456b911ddc" + +[[package]] +name = "libc" +version = "0.2.186" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "68ab91017fe16c622486840e4c83c9a37afeff978bd239b5293d61ece587de66" + +[[package]] +name = "libloading" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d7c4b02199fee7c5d21a5ae7d8cfa79a6ef5bb2fc834d6e9058e89c825efdc55" +dependencies = [ + "cfg-if", + "windows-link", +] + +[[package]] +name = "libm" +version = "0.2.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981" + +[[package]] +name = "libredox" +version = "0.1.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f02ab6bace2054fb888a3c16f990117b579d14a3088e472d63c6011fa185c9d3" +dependencies = [ + "bitflags 2.13.0", + "libc", + "plain", + "redox_syscall 0.8.1", +] + +[[package]] +name = "linux-raw-sys" +version = "0.4.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d26c52dbd32dccf2d10cac7725f8eae5296885fb5703b261f7d0a0739ec807ab" + +[[package]] +name = "linux-raw-sys" +version = "0.9.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd945864f07fe9f5371a27ad7b52a172b4b499999f1d97574c9fa68373937e12" + +[[package]] +name = "linux-raw-sys" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" + +[[package]] +name = "lock_api" +version = "0.4.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965" +dependencies = [ + "scopeguard", +] + +[[package]] +name = "log" +version = "0.4.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "953f07c43838f8e6f9758cab68bf5bed85465e7587ebe0b823f1bcd81978ad3a" + +[[package]] +name = "mach-dxcompiler-rs" +version = "0.1.4+2024.11.22-df583a3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e3cd67e8ea2ba061339150970542cf1c60ba44c6d17e31279cbc133a4b018f8" + +[[package]] +name = "memchr" +version = "2.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "88904434abc2901f197fe8cc55f0445e7ded921dba5911dad2e2b39b48e663c4" + +[[package]] +name = "memmap2" +version = "0.9.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "714098028fe011992e1c3962653c96b2d578c4b4bce9036e15ff220319b1e0e3" +dependencies = [ + "libc", +] + +[[package]] +name = "naga" +version = "30.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a616d2fb8c89516ac2723a581f69d6c18576046bed761bd6b305e5618e6ae130" +dependencies = [ + "arrayvec", + "bit-set", + "bitflags 2.13.0", + "cfg-if", + "cfg_aliases", + "codespan-reporting", + "half", + "hashbrown 0.17.1", + "indexmap", + "libm", + "log", + "naga-types", + "num-traits", + "once_cell", + "rustc-hash", + "spirv", + "thiserror 2.0.18", + "unicode-ident", +] + +[[package]] +name = "naga-types" +version = "30.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "590afbf58a6f4f62873cd5cff4468061844bafa1cdf399cc954537c22d768d49" +dependencies = [ + "hashbrown 0.17.1", + "indexmap", + "rustc-hash", + "thiserror 2.0.18", +] + +[[package]] +name = "ndk" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3f42e7bbe13d351b6bead8286a43aac9534b82bd3cc43e47037f012ebfd62d4" +dependencies = [ + "bitflags 2.13.0", + "jni-sys 0.3.1", + "log", + "ndk-sys", + "num_enum", + "raw-window-handle", + "thiserror 1.0.69", +] + +[[package]] +name = "ndk-context" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27b02d87554356db9e9a873add8782d4ea6e3e58ea071a9adb9a2e8ddb884a8b" + +[[package]] +name = "ndk-sys" +version = "0.6.0+11769913" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee6cda3051665f1fb8d9e08fc35c96d5a244fb1be711a03b71118828afc9a873" +dependencies = [ + "jni-sys 0.3.1", +] + +[[package]] +name = "num-traits" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" +dependencies = [ + "autocfg", + "libm", +] + +[[package]] +name = "num_enum" +version = "0.7.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d0bca838442ec211fa11de3a8b0e0e8f3a4522575b5c4c06ed722e005036f26" +dependencies = [ + "num_enum_derive", + "rustversion", +] + +[[package]] +name = "num_enum_derive" +version = "0.7.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "680998035259dcfcafe653688bf2aa6d3e2dc05e98be6ab46afb089dc84f1df8" +dependencies = [ + "proc-macro-crate", + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "objc-sys" +version = "0.3.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cdb91bdd390c7ce1a8607f35f3ca7151b65afc0ff5ff3b34fa350f7d7c7e4310" + +[[package]] +name = "objc2" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "46a785d4eeff09c14c487497c162e92766fbb3e4059a71840cecc03d9a50b804" +dependencies = [ + "objc-sys", + "objc2-encode", +] + +[[package]] +name = "objc2" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a12a8ed07aefc768292f076dc3ac8c48f3781c8f2d5851dd3d98950e8c5a89f" +dependencies = [ + "objc2-encode", +] + +[[package]] +name = "objc2-app-kit" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e4e89ad9e3d7d297152b17d39ed92cd50ca8063a89a9fa569046d41568891eff" +dependencies = [ + "bitflags 2.13.0", + "block2 0.5.1", + "libc", + "objc2 0.5.2", + "objc2-core-data", + "objc2-core-image", + "objc2-foundation 0.2.2", + "objc2-quartz-core 0.2.2", +] + +[[package]] +name = "objc2-app-kit" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d49e936b501e5c5bf01fda3a9452ff86dc3ea98ad5f283e1455153142d97518c" +dependencies = [ + "bitflags 2.13.0", + "objc2 0.6.4", + "objc2-core-foundation", + "objc2-foundation 0.3.2", +] + +[[package]] +name = "objc2-cloud-kit" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "74dd3b56391c7a0596a295029734d3c1c5e7e510a4cb30245f8221ccea96b009" +dependencies = [ + "bitflags 2.13.0", + "block2 0.5.1", + "objc2 0.5.2", + "objc2-core-location", + "objc2-foundation 0.2.2", +] + +[[package]] +name = "objc2-contacts" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a5ff520e9c33812fd374d8deecef01d4a840e7b41862d849513de77e44aa4889" +dependencies = [ + "block2 0.5.1", + "objc2 0.5.2", + "objc2-foundation 0.2.2", +] + +[[package]] +name = "objc2-core-data" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "617fbf49e071c178c0b24c080767db52958f716d9eabdf0890523aeae54773ef" +dependencies = [ + "bitflags 2.13.0", + "block2 0.5.1", + "objc2 0.5.2", + "objc2-foundation 0.2.2", +] + +[[package]] +name = "objc2-core-foundation" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2a180dd8642fa45cdb7dd721cd4c11b1cadd4929ce112ebd8b9f5803cc79d536" +dependencies = [ + "bitflags 2.13.0", + "dispatch2", + "objc2 0.6.4", +] + +[[package]] +name = "objc2-core-graphics" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e022c9d066895efa1345f8e33e584b9f958da2fd4cd116792e15e07e4720a807" +dependencies = [ + "dispatch2", + "objc2 0.6.4", + "objc2-core-foundation", + "objc2-io-surface", +] + +[[package]] +name = "objc2-core-image" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "55260963a527c99f1819c4f8e3b47fe04f9650694ef348ffd2227e8196d34c80" +dependencies = [ + "block2 0.5.1", + "objc2 0.5.2", + "objc2-foundation 0.2.2", + "objc2-metal 0.2.2", +] + +[[package]] +name = "objc2-core-location" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "000cfee34e683244f284252ee206a27953279d370e309649dc3ee317b37e5781" +dependencies = [ + "block2 0.5.1", + "objc2 0.5.2", + "objc2-contacts", + "objc2-foundation 0.2.2", +] + +[[package]] +name = "objc2-encode" +version = "4.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ef25abbcd74fb2609453eb695bd2f860d389e457f67dc17cafc8b8cbc89d0c33" + +[[package]] +name = "objc2-foundation" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ee638a5da3799329310ad4cfa62fbf045d5f56e3ef5ba4149e7452dcf89d5a8" +dependencies = [ + "bitflags 2.13.0", + "block2 0.5.1", + "dispatch", + "libc", + "objc2 0.5.2", +] + +[[package]] +name = "objc2-foundation" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3e0adef53c21f888deb4fa59fc59f7eb17404926ee8a6f59f5df0fd7f9f3272" +dependencies = [ + "bitflags 2.13.0", + "objc2 0.6.4", + "objc2-core-foundation", +] + +[[package]] +name = "objc2-io-surface" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "180788110936d59bab6bd83b6060ffdfffb3b922ba1396b312ae795e1de9d81d" +dependencies = [ + "bitflags 2.13.0", + "objc2 0.6.4", + "objc2-core-foundation", +] + +[[package]] +name = "objc2-link-presentation" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a1a1ae721c5e35be65f01a03b6d2ac13a54cb4fa70d8a5da293d7b0020261398" +dependencies = [ + "block2 0.5.1", + "objc2 0.5.2", + "objc2-app-kit 0.2.2", + "objc2-foundation 0.2.2", +] + +[[package]] +name = "objc2-metal" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dd0cba1276f6023976a406a14ffa85e1fdd19df6b0f737b063b95f6c8c7aadd6" +dependencies = [ + "bitflags 2.13.0", + "block2 0.5.1", + "objc2 0.5.2", + "objc2-foundation 0.2.2", +] + +[[package]] +name = "objc2-metal" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a0125f776a10d00af4152d74616409f0d4a2053a6f57fa5b7d6aa2854ac04794" +dependencies = [ + "bitflags 2.13.0", + "block2 0.6.2", + "objc2 0.6.4", + "objc2-foundation 0.3.2", +] + +[[package]] +name = "objc2-quartz-core" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e42bee7bff906b14b167da2bac5efe6b6a07e6f7c0a21a7308d40c960242dc7a" +dependencies = [ + "bitflags 2.13.0", + "block2 0.5.1", + "objc2 0.5.2", + "objc2-foundation 0.2.2", + "objc2-metal 0.2.2", +] + +[[package]] +name = "objc2-quartz-core" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "96c1358452b371bf9f104e21ec536d37a650eb10f7ee379fff67d2e08d537f1f" +dependencies = [ + "bitflags 2.13.0", + "objc2 0.6.4", + "objc2-core-foundation", + "objc2-core-graphics", + "objc2-foundation 0.3.2", + "objc2-metal 0.3.2", +] + +[[package]] +name = "objc2-symbols" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0a684efe3dec1b305badae1a28f6555f6ddd3bb2c2267896782858d5a78404dc" +dependencies = [ + "objc2 0.5.2", + "objc2-foundation 0.2.2", +] + +[[package]] +name = "objc2-ui-kit" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8bb46798b20cd6b91cbd113524c490f1686f4c4e8f49502431415f3512e2b6f" +dependencies = [ + "bitflags 2.13.0", + "block2 0.5.1", + "objc2 0.5.2", + "objc2-cloud-kit", + "objc2-core-data", + "objc2-core-image", + "objc2-core-location", + "objc2-foundation 0.2.2", + "objc2-link-presentation", + "objc2-quartz-core 0.2.2", + "objc2-symbols", + "objc2-uniform-type-identifiers", + "objc2-user-notifications", +] + +[[package]] +name = "objc2-uniform-type-identifiers" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "44fa5f9748dbfe1ca6c0b79ad20725a11eca7c2218bceb4b005cb1be26273bfe" +dependencies = [ + "block2 0.5.1", + "objc2 0.5.2", + "objc2-foundation 0.2.2", +] + +[[package]] +name = "objc2-user-notifications" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "76cfcbf642358e8689af64cee815d139339f3ed8ad05103ed5eaf73db8d84cb3" +dependencies = [ + "bitflags 2.13.0", + "block2 0.5.1", + "objc2 0.5.2", + "objc2-core-location", + "objc2-foundation 0.2.2", +] + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "orbclient" +version = "0.3.55" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5df339f526ea9a60e371768d50efc2f2508c7203290731565d1f7a6f71d21747" +dependencies = [ + "libc", + "libredox", +] + +[[package]] +name = "ordered-float" +version = "5.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b7d950ca161dc355eaf28f82b11345ed76c6e1f6eb1f4f4479e0323b9e2fbd0e" +dependencies = [ + "num-traits", +] + +[[package]] +name = "owned_ttf_parser" +version = "0.25.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "36820e9051aca1014ddc75770aab4d68bc1e9e632f0f5627c4086bc216fb583b" +dependencies = [ + "ttf-parser", +] + +[[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 0.5.18", + "smallvec", + "windows-link", +] + +[[package]] +name = "percent-encoding" +version = "2.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" + +[[package]] +name = "pin-project" +version = "1.1.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2466b2336ed02bcdca6b294417127b90ec92038d1d5c4fbeac971a922e0e0924" +dependencies = [ + "pin-project-internal", +] + +[[package]] +name = "pin-project-internal" +version = "1.1.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c96395f0a926bc13b1c17622aaddda1ecb55d49c8f1bf9777e4d877800a43f8b" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "pin-project-lite" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" + +[[package]] +name = "pkg-config" +version = "0.3.33" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "19f132c84eca552bf34cab8ec81f1c1dcc229b811638f9d283dceabe58c5569e" + +[[package]] +name = "plain" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b4596b6d070b27117e987119b4dac604f3c58cfb0b191112e24771b2faeac1a6" + +[[package]] +name = "polling" +version = "3.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d0e4f59085d47d8241c88ead0f274e8a0cb551f3625263c05eb8dd897c34218" +dependencies = [ + "cfg-if", + "concurrent-queue", + "hermit-abi", + "pin-project-lite", + "rustix 1.1.4", + "windows-sys 0.61.2", +] + +[[package]] +name = "portable-atomic" +version = "1.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c33a9471896f1c69cecef8d20cbe2f7accd12527ce60845ff44c153bb2a21b49" + +[[package]] +name = "portable-atomic-util" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2a106d1259c23fac8e543272398ae0e3c0b8d33c88ed73d0cc71b0f1d902618" +dependencies = [ + "portable-atomic", +] + +[[package]] +name = "presser" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e8cf8e6a8aa66ce33f63993ffc4ea4271eb5b0530a9002db8455ea6050c77bfa" + +[[package]] +name = "proc-macro-crate" +version = "3.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e67ba7e9b2b56446f1d419b1d807906278ffa1a658a8a5d8a39dcb1f5a78614f" +dependencies = [ + "toml_edit", +] + +[[package]] +name = "proc-macro2" +version = "1.0.106" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "profiling" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d595e54a326bc53c1c197b32d295e14b169e3cfeaa8dc82b529f947fba6bcf5" + +[[package]] +name = "quick-xml" +version = "0.39.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cdcc8dd4e2f670d309a5f0e83fe36dfdc05af317008fea29144da1a2ac858e5e" +dependencies = [ + "memchr", +] + +[[package]] +name = "quote" +version = "1.0.45" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41f2619966050689382d2b44f664f4bc593e129785a36d6ee376ddf37259b924" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "r-efi" +version = "5.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f" + +[[package]] +name = "range-alloc" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca45419789ae5a7899559e9512e58ca889e41f04f1f2445e9f4b290ceccd1d08" + +[[package]] +name = "raw-window-handle" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20675572f6f24e9e76ef639bc5552774ed45f1c30e2951e1e99c59888861c539" + +[[package]] +name = "raw-window-metal" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "40d213455a5f1dc59214213c7330e074ddf8114c9a42411eb890c767357ce135" +dependencies = [ + "objc2 0.6.4", + "objc2-core-foundation", + "objc2-foundation 0.3.2", + "objc2-quartz-core 0.3.2", +] + +[[package]] +name = "redox_syscall" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4722d768eff46b75989dd134e5c353f0d6296e5aaa3132e776cbdb56be7731aa" +dependencies = [ + "bitflags 1.3.2", +] + +[[package]] +name = "redox_syscall" +version = "0.5.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d" +dependencies = [ + "bitflags 2.13.0", +] + +[[package]] +name = "redox_syscall" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5b44b894f2a6e36457d665d1e08c3866add6ed5e70050c1b4ba8a8ddedb02ce7" +dependencies = [ + "bitflags 2.13.0", +] + +[[package]] +name = "regex" +version = "1.12.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1292b7759ae1cb9ec195452d1390a074f0cd8541ab7a5a8c31cd6db45d4a6ba" +dependencies = [ + "aho-corasick", + "memchr", + "regex-automata", + "regex-syntax", +] + +[[package]] +name = "regex-automata" +version = "0.4.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e1dd4122fc1595e8162618945476892eefca7b88c52820e74af6262213cae8f" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax", +] + +[[package]] +name = "regex-syntax" +version = "0.8.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" + +[[package]] +name = "renderdoc-sys" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "19b30a45b0cd0bcca8037f3d0dc3421eaf95327a17cad11964fb8179b4fc4832" + +[[package]] +name = "rustc-hash" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08d43f7aa6b08d49f382cde6a7982047c3426db949b1424bc4b7ec9ae12c6ce2" + +[[package]] +name = "rustc_version" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92" +dependencies = [ + "semver", +] + +[[package]] +name = "rustix" +version = "0.38.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fdb5bc1ae2baa591800df16c9ca78619bf65c0488b41b96ccec5d11220d8c154" +dependencies = [ + "bitflags 2.13.0", + "errno", + "libc", + "linux-raw-sys 0.4.15", + "windows-sys 0.59.0", +] + +[[package]] +name = "rustix" +version = "1.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6fe4565b9518b83ef4f91bb47ce29620ca828bd32cb7e408f0062e9930ba190" +dependencies = [ + "bitflags 2.13.0", + "errno", + "libc", + "linux-raw-sys 0.12.1", + "windows-sys 0.61.2", +] + +[[package]] +name = "rustversion" +version = "1.0.22" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b39cdef0fa800fc44525c84ccb54a029961a8215f9619753635a9c0d2538d46d" + +[[package]] +name = "same-file" +version = "1.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502" +dependencies = [ + "winapi-util", +] + +[[package]] +name = "scoped-tls" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e1cf6437eb19a8f4a6cc0f7dca544973b0b78843adbfeb3683d1a94a0024a294" + +[[package]] +name = "scopeguard" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" + +[[package]] +name = "sctk-adwaita" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6277f0217056f77f1d8f49f2950ac6c278c0d607c45f5ee99328d792ede24ec" +dependencies = [ + "ab_glyph", + "log", + "memmap2", + "smithay-client-toolkit", + "tiny-skia", +] + +[[package]] +name = "semver" +version = "1.0.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" + +[[package]] +name = "serde" +version = "1.0.228" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a8e94ea7f378bd32cbbd37198a4a91436180c5bb472411e48b5ec2e2124ae9e" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.228" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41d385c7d4ca58e59fc732af25c3983b67ac852c1a25000afe1175de458b67ad" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.228" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "shlex" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" + +[[package]] +name = "simd_cesu8" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94f90157bb87cddf702797c5dadfa0be7d266cdf49e22da2fcaa32eff75b2c33" +dependencies = [ + "rustc_version", + "simdutf8", +] + +[[package]] +name = "simdutf8" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e" + +[[package]] +name = "slab" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" + +[[package]] +name = "slotmap" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bdd58c3c93c3d278ca835519292445cb4b0d4dc59ccfdf7ceadaab3f8aeb4038" +dependencies = [ + "version_check", +] + +[[package]] +name = "smallvec" +version = "1.15.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ed6a63f02c8539c91a8685a86f4099661ba3da017932f6ebbea6de3f0fa7c90" + +[[package]] +name = "smithay-client-toolkit" +version = "0.19.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3457dea1f0eb631b4034d61d4d8c32074caa6cd1ab2d59f2327bd8461e2c0016" +dependencies = [ + "bitflags 2.13.0", + "calloop", + "calloop-wayland-source", + "cursor-icon", + "libc", + "log", + "memmap2", + "rustix 0.38.44", + "thiserror 1.0.69", + "wayland-backend", + "wayland-client", + "wayland-csd-frame", + "wayland-cursor", + "wayland-protocols", + "wayland-protocols-wlr", + "wayland-scanner", + "xkeysym", +] + +[[package]] +name = "smol_str" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dd538fb6910ac1099850255cf94a94df6551fbdd602454387d0adb2d1ca6dead" +dependencies = [ + "serde", +] + +[[package]] +name = "spirv" +version = "0.4.0+sdk-1.4.341.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d9571ea910ebd84c86af4b3ed27f9dbdc6ad06f17c5f96146b2b671e2976744f" +dependencies = [ + "bitflags 2.13.0", +] + +[[package]] +name = "static_assertions" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f" + +[[package]] +name = "strict-num" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6637bab7722d379c8b41ba849228d680cc12d0a45ba1fa2b48f2a30577a06731" + +[[package]] +name = "syn" +version = "2.0.118" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1b9ae57f904213ebb649ce6895b8a66c66f0203b9319718f69a5612a065b1422" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "termcolor" +version = "1.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06794f8f6c5c898b3275aebefa6b8a1cb24cd2c6c79397ab15774837a0bc5755" +dependencies = [ + "winapi-util", +] + +[[package]] +name = "thiserror" +version = "1.0.69" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52" +dependencies = [ + "thiserror-impl 1.0.69", +] + +[[package]] +name = "thiserror" +version = "2.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4288b5bcbc7920c07a1149a35cf9590a2aa808e0bc1eafaade0b80947865fbc4" +dependencies = [ + "thiserror-impl 2.0.18", +] + +[[package]] +name = "thiserror-impl" +version = "1.0.69" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebc4ee7f67670e9b64d05fa4253e753e016c6c95ff35b89b7941d6b856dec1d5" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "tiny-skia" +version = "0.11.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "83d13394d44dae3207b52a326c0c85a8bf87f1541f23b0d143811088497b09ab" +dependencies = [ + "arrayref", + "arrayvec", + "bytemuck", + "cfg-if", + "log", + "tiny-skia-path", +] + +[[package]] +name = "tiny-skia-path" +version = "0.11.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9c9e7fc0c2e86a30b117d0462aa261b72b7a99b7ebd7deb3a14ceda95c5bdc93" +dependencies = [ + "arrayref", + "bytemuck", + "strict-num", +] + +[[package]] +name = "toml_datetime" +version = "1.1.1+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3165f65f62e28e0115a00b2ebdd37eb6f3b641855f9d636d3cd4103767159ad7" +dependencies = [ + "serde_core", +] + +[[package]] +name = "toml_edit" +version = "0.25.12+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2153edc6955a6c354fad8f5efd38b6a8769bdccf9fe50f8e1329f81b0baa5d7" +dependencies = [ + "indexmap", + "toml_datetime", + "toml_parser", + "winnow", +] + +[[package]] +name = "toml_parser" +version = "1.1.2+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2abe9b86193656635d2411dc43050282ca48aa31c2451210f4202550afb7526" +dependencies = [ + "winnow", +] + +[[package]] +name = "tracing" +version = "0.1.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" +dependencies = [ + "pin-project-lite", + "tracing-core", +] + +[[package]] +name = "tracing-core" +version = "0.1.36" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" + +[[package]] +name = "ttf-parser" +version = "0.25.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2df906b07856748fa3f6e0ad0cbaa047052d4a7dd609e231c4f72cee8c36f31" + +[[package]] +name = "unicode-ident" +version = "1.0.24" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75" + +[[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.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b4ac048d71ede7ee76d585517add45da530660ef4390e49b098733c6e897f254" + +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + +[[package]] +name = "walkdir" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29790946404f91d9c5d06f9874efddea1dc06c5efe94541a7d6863108e3a5e4b" +dependencies = [ + "same-file", + "winapi-util", +] + +[[package]] +name = "wasip2" +version = "1.0.4+wasi-0.2.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b67efb37e106e55ce722a510d6b5f9c17f083e5fc79afc2badeb12cc313d9487" +dependencies = [ + "wit-bindgen", +] + +[[package]] +name = "wasm-bindgen" +version = "0.2.127" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1b70935747edd64d89de3efa29d73789b806c15798f8e7dca4d8ac356b50ce70" +dependencies = [ + "cfg-if", + "once_cell", + "rustversion", + "wasm-bindgen-macro", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-futures" +version = "0.4.77" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6b7777d5cc23d0e91404e53ce2d5e8ec7acae3026b16233dba62cd3246457950" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.127" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77775f8f3f7217702089053b94958f8f54061a3f663417df76e19cbdcca29bc1" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.127" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e11d33f857dc2fb11b8bc75aee111aa9cbeb12cd9f25efd3d4c2a3dd4e235284" +dependencies = [ + "bumpalo", + "proc-macro2", + "quote", + "syn", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.127" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7ef64dbcc55df09c7e5a46182d181c2cfa3e925f3da937ea764728b4bbb9dcbf" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "wayland-backend" +version = "0.3.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2857dd20b54e916ec7253b3d6b4d5c4d7d4ca2c33c2e11c6c76a99bd8744755d" +dependencies = [ + "cc", + "downcast-rs", + "rustix 1.1.4", + "scoped-tls", + "smallvec", + "wayland-sys", +] + +[[package]] +name = "wayland-client" +version = "0.31.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "645c7c96bb74690c3189b5c9cb4ca1627062bb23693a4fad9d8c3de958260144" +dependencies = [ + "bitflags 2.13.0", + "rustix 1.1.4", + "wayland-backend", + "wayland-scanner", +] + +[[package]] +name = "wayland-csd-frame" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "625c5029dbd43d25e6aa9615e88b829a5cad13b2819c4ae129fdbb7c31ab4c7e" +dependencies = [ + "bitflags 2.13.0", + "cursor-icon", + "wayland-backend", +] + +[[package]] +name = "wayland-cursor" +version = "0.31.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a52d18780be9b1314328a3de5f930b73d2200112e3849ca6cb11822793fb34d" +dependencies = [ + "rustix 1.1.4", + "wayland-client", + "xcursor", +] + +[[package]] +name = "wayland-protocols" +version = "0.32.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "563a85523cade2429938e790815fd7319062103b9f4a2dc806e9b53b95982d8f" +dependencies = [ + "bitflags 2.13.0", + "wayland-backend", + "wayland-client", + "wayland-scanner", +] + +[[package]] +name = "wayland-protocols-plasma" +version = "0.3.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b6d8cf1eb2c1c31ed1f5643c88a6e53538129d4af80030c8cabd1f9fa884d91" +dependencies = [ + "bitflags 2.13.0", + "wayland-backend", + "wayland-client", + "wayland-protocols", + "wayland-scanner", +] + +[[package]] +name = "wayland-protocols-wlr" +version = "0.3.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eb04e52f7836d7c7976c78ca0250d61e33873c34156a2a1fc9474828ec268234" +dependencies = [ + "bitflags 2.13.0", + "wayland-backend", + "wayland-client", + "wayland-protocols", + "wayland-scanner", +] + +[[package]] +name = "wayland-scanner" +version = "0.31.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9c324a910fd86ebdc364a3e61ec1f11737d3b1d6c273c0239ee8ff4bc0d24b4a" +dependencies = [ + "proc-macro2", + "quick-xml", + "quote", +] + +[[package]] +name = "wayland-sys" +version = "0.31.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d8eab23fefc9e41f8e841df4a9c707e8a8c4ed26e944ef69297184de2785e3be" +dependencies = [ + "dlib", + "log", + "once_cell", + "pkg-config", +] + +[[package]] +name = "web-sys" +version = "0.3.104" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c435338968042f4f59a557f690a253676d47ce13ceb55d70100e7facf6620a30" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "web-time" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a6580f308b1fad9207618087a65c04e7a10bc77e02c8e84e9b00dd4b12fa0bb" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "wgpu-hal" +version = "30.0.1" +dependencies = [ + "android_system_properties", + "arrayvec", + "ash", + "bit-set", + "bitflags 2.13.0", + "block2 0.6.2", + "bytemuck", + "cfg-if", + "cfg_aliases", + "drm", + "env_logger", + "glam", + "glow", + "glutin", + "glutin-winit", + "glutin_wgl_sys", + "gpu-allocator", + "hashbrown 0.17.1", + "js-sys", + "khronos-egl", + "libc", + "libloading", + "log", + "mach-dxcompiler-rs", + "naga", + "naga-types", + "ndk-sys", + "objc2 0.6.4", + "objc2-core-foundation", + "objc2-core-graphics", + "objc2-foundation 0.3.2", + "objc2-metal 0.3.2", + "objc2-quartz-core 0.3.2", + "once_cell", + "ordered-float", + "parking_lot", + "portable-atomic", + "portable-atomic-util", + "profiling", + "range-alloc", + "raw-window-handle", + "raw-window-metal", + "renderdoc-sys", + "smallvec", + "static_assertions", + "thiserror 2.0.18", + "wasm-bindgen", + "wayland-sys", + "web-sys", + "wgpu-naga-bridge", + "wgpu-types", + "windows", + "windows-core", + "windows-result", + "winit", +] + +[[package]] +name = "wgpu-naga-bridge" +version = "30.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2f62e73117bb7a62bfd9c5a5841438a823f6566c6442a808ee269d2d055c081" +dependencies = [ + "naga", + "wgpu-types", +] + +[[package]] +name = "wgpu-types" +version = "30.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "99dad6f1fbdbbdb4c278a6508b059d44688f5cebddf78d005a46a31340269286" +dependencies = [ + "bitflags 2.13.0", + "bytemuck", + "js-sys", + "log", + "naga-types", + "raw-window-handle", + "static_assertions", + "web-sys", +] + +[[package]] +name = "winapi-util" +version = "0.1.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "windows" +version = "0.62.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "527fadee13e0c05939a6a05d5bd6eec6cd2e3dbd648b9f8e447c6518133d8580" +dependencies = [ + "windows-collections", + "windows-core", + "windows-future", + "windows-numerics", +] + +[[package]] +name = "windows-collections" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23b2d95af1a8a14a3c7367e1ed4fc9c20e0a26e79551b1454d72583c97cc6610" +dependencies = [ + "windows-core", +] + +[[package]] +name = "windows-core" +version = "0.62.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb" +dependencies = [ + "windows-implement", + "windows-interface", + "windows-link", + "windows-result", + "windows-strings", +] + +[[package]] +name = "windows-future" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e1d6f90251fe18a279739e78025bd6ddc52a7e22f921070ccdc67dde84c605cb" +dependencies = [ + "windows-core", + "windows-link", + "windows-threading", +] + +[[package]] +name = "windows-implement" +version = "0.60.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "windows-interface" +version = "0.59.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-numerics" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e2e40844ac143cdb44aead537bbf727de9b044e107a0f1220392177d15b0f26" +dependencies = [ + "windows-core", + "windows-link", +] + +[[package]] +name = "windows-result" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-strings" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-sys" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" +dependencies = [ + "windows-targets", +] + +[[package]] +name = "windows-sys" +version = "0.59.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b" +dependencies = [ + "windows-targets", +] + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-targets" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" +dependencies = [ + "windows_aarch64_gnullvm", + "windows_aarch64_msvc", + "windows_i686_gnu", + "windows_i686_gnullvm", + "windows_i686_msvc", + "windows_x86_64_gnu", + "windows_x86_64_gnullvm", + "windows_x86_64_msvc", +] + +[[package]] +name = "windows-threading" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3949bd5b99cafdf1c7ca86b43ca564028dfe27d66958f2470940f73d86d75b37" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" + +[[package]] +name = "windows_i686_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" + +[[package]] +name = "windows_i686_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" + +[[package]] +name = "winit" +version = "0.30.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6755fa58a9f8350bd1e472d4c3fcc25f824ec358933bba33306d0b63df5978d" +dependencies = [ + "ahash", + "android-activity", + "atomic-waker", + "bitflags 2.13.0", + "block2 0.5.1", + "bytemuck", + "calloop", + "cfg_aliases", + "concurrent-queue", + "core-foundation", + "core-graphics", + "cursor-icon", + "dpi", + "js-sys", + "libc", + "memmap2", + "ndk", + "objc2 0.5.2", + "objc2-app-kit 0.2.2", + "objc2-foundation 0.2.2", + "objc2-ui-kit", + "orbclient", + "percent-encoding", + "pin-project", + "raw-window-handle", + "redox_syscall 0.4.1", + "rustix 0.38.44", + "sctk-adwaita", + "smithay-client-toolkit", + "smol_str", + "tracing", + "unicode-segmentation", + "wasm-bindgen", + "wasm-bindgen-futures", + "wayland-backend", + "wayland-client", + "wayland-protocols", + "wayland-protocols-plasma", + "web-sys", + "web-time", + "windows-sys 0.52.0", + "x11-dl", + "x11rb", + "xkbcommon-dl", +] + +[[package]] +name = "winnow" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0592e1c9d151f854e6fd382574c3a0855250e1d9b2f99d9281c6e6391af352f1" +dependencies = [ + "memchr", +] + +[[package]] +name = "wit-bindgen" +version = "0.57.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e" + +[[package]] +name = "x11-dl" +version = "2.21.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38735924fedd5314a6e548792904ed8c6de6636285cb9fec04d5b1db85c1516f" +dependencies = [ + "libc", + "once_cell", + "pkg-config", +] + +[[package]] +name = "x11rb" +version = "0.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9993aa5be5a26815fe2c3eacfc1fde061fc1a1f094bf1ad2a18bf9c495dd7414" +dependencies = [ + "as-raw-xcb-connection", + "gethostname", + "libc", + "libloading", + "once_cell", + "rustix 1.1.4", + "x11rb-protocol", +] + +[[package]] +name = "x11rb-protocol" +version = "0.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ea6fc2961e4ef194dcbfe56bb845534d0dc8098940c7e5c012a258bfec6701bd" + +[[package]] +name = "xcursor" +version = "0.3.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bec9e4a500ca8864c5b47b8b482a73d62e4237670e5b5f1d6b9e3cae50f28f2b" + +[[package]] +name = "xkbcommon-dl" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d039de8032a9a8856a6be89cea3e5d12fdd82306ab7c94d74e6deab2460651c5" +dependencies = [ + "bitflags 2.13.0", + "dlib", + "log", + "once_cell", + "xkeysym", +] + +[[package]] +name = "xkeysym" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9cc00251562a284751c9973bace760d86c0276c471b4be569fe6b068ee97a56" + +[[package]] +name = "xml-rs" +version = "0.8.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ae8337f8a065cfc972643663ea4279e04e7256de865aa66fe25cec5fb912d3f" + +[[package]] +name = "zerocopy" +version = "0.8.52" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce1022995ff5ff5d841ad7d994facc23098cd40152f2c1d11cd607c6f530653f" +dependencies = [ + "zerocopy-derive", +] + +[[package]] +name = "zerocopy-derive" +version = "0.8.52" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ae7f38b72ec2a254e2b87ef277cf2cd4fb97cbebf944faa6f33354da0867930" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] diff --git a/app/vendor/rune/vendor/wgpu-hal/Cargo.toml b/app/vendor/rune/vendor/wgpu-hal/Cargo.toml new file mode 100644 index 0000000..67f6541 --- /dev/null +++ b/app/vendor/rune/vendor/wgpu-hal/Cargo.toml @@ -0,0 +1,542 @@ +# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO +# +# When uploading crates to the registry Cargo will automatically +# "normalize" Cargo.toml files for maximal compatibility +# with all versions of Cargo and also rewrite `path` dependencies +# to registry (e.g., crates.io) dependencies. +# +# If you are reading this file be aware that the original Cargo.toml +# will likely look very different (and much more reasonable). +# See Cargo.toml.orig for the original contents. + +[package] +edition = "2021" +rust-version = "1.87" +name = "wgpu-hal" +version = "30.0.1" +authors = ["gfx-rs developers"] +build = "build.rs" +autolib = false +autobins = false +autoexamples = false +autotests = false +autobenches = false +description = "Hardware abstraction layer for wgpu, the cross-platform, safe, pure-rust graphics API" +homepage = "https://wgpu.rs/" +readme = "README.md" +keywords = ["graphics"] +license = "MIT OR Apache-2.0" +repository = "https://github.com/gfx-rs/wgpu" + +[package.metadata.docs.rs] +features = [ + "metal", + "vulkan", + "gles", + "renderdoc", +] +rustdoc-args = [ + "--cfg", + "docsrs", +] +targets = [ + "x86_64-unknown-linux-gnu", + "x86_64-apple-darwin", + "x86_64-pc-windows-msvc", + "wasm32-unknown-unknown", +] + +[package.metadata.cargo-machete] +ignored = ["cfg_aliases"] + +[features] +device_lost_panic = [] +dx12 = [ + "dep:arrayvec", + "dep:bit-set", + "dep:bytemuck", + "dep:gpu-allocator", + "dep:libloading", + "dep:once_cell", + "dep:ordered-float", + "dep:parking_lot", + "dep:profiling", + "dep:range-alloc", + "dep:windows-core", + "gpu-allocator/d3d12", + "naga/hlsl-out", + "once_cell/std", + "windows/Win32_Devices_DeviceAndDriverInstallation", + "windows/Win32_Devices_Display", + "windows/Win32_Graphics_Direct3D_Dxc", + "windows/Win32_Graphics_Direct3D_Fxc", + "windows/Win32_Graphics_Direct3D", + "windows/Win32_Graphics_Direct3D12", + "windows/Win32_Graphics_DirectComposition", + "windows/Win32_Graphics_Dxgi_Common", + "windows/Win32_Graphics_Gdi", + "windows/Win32_Security", + "windows/Win32_System_Diagnostics_Debug", + "windows/Win32_System_Kernel", + "windows/Win32_System_Performance", + "windows/Win32_System_Threading", + "windows/Win32_UI_WindowsAndMessaging", +] +fragile-send-sync-non-atomic-wasm = ["wgpu-types/fragile-send-sync-non-atomic-wasm"] +gles = [ + "dep:arrayvec", + "dep:bytemuck", + "dep:glow", + "dep:glutin_wgl_sys", + "dep:js-sys", + "dep:khronos-egl", + "dep:libloading", + "dep:ndk-sys", + "dep:objc2", + "dep:parking_lot", + "dep:profiling", + "dep:wasm-bindgen", + "dep:wayland-sys", + "dep:web-sys", + "dep:windows-result", + "naga/glsl-out", + "wgpu-types/web", + "windows-result/std", + "windows/Win32_Graphics_Gdi", + "windows/Win32_Graphics_OpenGL", + "windows/Win32_System_LibraryLoader", + "windows/Win32_UI_WindowsAndMessaging", +] +internal_error_panic = [] +metal = [ + "naga/msl-out", + "dep:arrayvec", + "dep:block2", + "dep:bytemuck", + "dep:libloading", + "dep:objc2", + "dep:objc2-core-foundation", + "dep:objc2-core-graphics", + "dep:objc2-foundation", + "dep:objc2-metal", + "dep:objc2-quartz-core", + "dep:parking_lot", + "dep:profiling", + "dep:smallvec", + "dep:raw-window-metal", +] +portable-atomic = [ + "dep:portable-atomic", + "dep:portable-atomic-util", +] +renderdoc = [ + "dep:libloading", + "dep:renderdoc-sys", +] +static-dxc = ["dep:mach-dxcompiler-rs"] +validation_canary = ["dep:parking_lot"] +vulkan = [ + "naga/spv-out", + "dep:android_system_properties", + "dep:arrayvec", + "dep:ash", + "dep:bytemuck", + "dep:libc", + "dep:libloading", + "dep:ordered-float", + "dep:parking_lot", + "dep:profiling", + "dep:raw-window-metal", + "dep:smallvec", + "dep:windows", + "gpu-allocator/vulkan", + "windows/Win32", + "windows/Win32_Devices_Display", + "windows/Win32_Foundation", + "windows/Win32_Graphics_Dxgi", + "windows/Win32_Graphics_Dxgi_Common", + "windows/Win32_Graphics_Gdi", +] + +[lib] +name = "wgpu_hal" +path = "src/lib.rs" + +[[example]] +name = "halmark" +path = "examples/halmark/main.rs" + +[[example]] +name = "raw-gles" +path = "examples/raw-gles.rs" +required-features = ["gles"] + +[[example]] +name = "ray-traced-triangle" +path = "examples/ray-traced-triangle/main.rs" + +[dependencies.arrayvec] +version = "0.7.1" +optional = true +default-features = false + +[dependencies.bitflags] +version = "2.9" + +[dependencies.bytemuck] +version = "1.22" +features = [ + "extern_crate_alloc", + "min_const_generics", + "derive", +] +optional = true + +[dependencies.cfg-if] +version = "1" + +[dependencies.glow] +version = "0.17" +optional = true + +[dependencies.hashbrown] +version = "0.17" +features = [ + "default-hasher", + "inline-more", +] +default-features = false + +[dependencies.log] +version = "0.4.29" + +[dependencies.naga] +version = "30.0.0" + +[dependencies.naga-types] +version = "30.0.0" + +[dependencies.ordered-float] +version = ">=3, <6.0" +optional = true +default-features = false + +[dependencies.parking_lot] +version = "0.12.3" +optional = true + +[dependencies.profiling] +version = "1.0.1" +optional = true +default-features = false + +[dependencies.raw-window-handle] +version = "0.6.2" +default-features = false + +[dependencies.static_assertions] +version = "1.1" + +[dependencies.thiserror] +version = "2.0.12" +default-features = false + +[dependencies.wgpu-naga-bridge] +version = "30.0.0" + +[dependencies.wgpu-types] +version = "30.0.0" +default-features = false + +[dev-dependencies.env_logger] +version = "0.11" +default-features = false + +[dev-dependencies.glam] +version = "0.33.0" + +[dev-dependencies.naga] +version = "30.0.0" +features = [ + "wgsl-in", + "termcolor", +] + +[dev-dependencies.winit] +version = "0.30.8" +features = ["android-native-activity"] + +[build-dependencies.cfg_aliases] +version = "0.2.2" + +[target.'cfg(all(target_arch = "wasm32", not(target_os = "emscripten")))'.dependencies.js-sys] +version = "0.3.104" +optional = true +default-features = true + +[target.'cfg(all(target_arch = "wasm32", not(target_os = "emscripten")))'.dependencies.wasm-bindgen] +version = "0.2.127" +optional = true +default-features = false + +[target.'cfg(all(target_arch = "wasm32", not(target_os = "emscripten")))'.dependencies.web-sys] +version = "0.3.104" +features = [ + "default", + "Window", + "HtmlCanvasElement", + "WebGl2RenderingContext", + "OffscreenCanvas", + "VideoFrame", +] +optional = true +default-features = false + +[target.'cfg(all(unix, not(target_vendor = "apple"), not(target_family = "wasm")))'.dependencies.drm] +version = "0.15" +optional = true + +[target.'cfg(all(windows, not(target_arch = "aarch64"), target_env = "msvc"))'.dependencies.mach-dxcompiler-rs] +version = "0.1.4" +optional = true +default-features = false + +[target.'cfg(any(not(target_has_atomic = "64"), not(target_has_atomic = "ptr")))'.dependencies.portable-atomic] +version = "1.10" +optional = true + +[target.'cfg(not(any(target_arch = "wasm32", target_os = "ios", target_os = "visionos", target_env = "ohos")))'.dev-dependencies.glutin] +version = "0.32" +features = [ + "egl", + "wgl", + "wayland", + "x11", +] +default-features = false + +[target.'cfg(not(any(target_arch = "wasm32", target_os = "ios", target_os = "visionos", target_env = "ohos")))'.dev-dependencies.glutin-winit] +version = "0.5" +features = [ + "egl", + "wgl", + "wayland", + "x11", +] +default-features = false + +[target.'cfg(not(target_arch = "wasm32"))'.dependencies.ash] +version = "0.38" +optional = true + +[target.'cfg(not(target_arch = "wasm32"))'.dependencies.gpu-allocator] +version = "0.28" +features = ["hashbrown"] +optional = true +default-features = false + +[target.'cfg(not(target_arch = "wasm32"))'.dependencies.khronos-egl] +version = "6" +features = ["dynamic"] +optional = true + +[target.'cfg(not(target_arch = "wasm32"))'.dependencies.libloading] +version = "0.8" +optional = true + +[target.'cfg(not(target_arch = "wasm32"))'.dependencies.renderdoc-sys] +version = "1" +optional = true + +[target.'cfg(not(target_arch = "wasm32"))'.dependencies.smallvec] +version = "1.14" +features = ["union"] +optional = true + +[target.'cfg(not(target_has_atomic = "ptr"))'.dependencies.portable-atomic-util] +version = "0.2.4" +features = ["alloc"] +optional = true + +[target.'cfg(target_os = "android")'.dependencies.android_system_properties] +version = "0.1.1" +optional = true + +[target.'cfg(target_os = "android")'.dependencies.ndk-sys] +version = "0.6" +optional = true + +[target.'cfg(target_os = "emscripten")'.dependencies.khronos-egl] +version = "6" +features = [ + "static", + "no-pkg-config", +] +optional = true + +[target.'cfg(target_os = "emscripten")'.dependencies.libloading] +version = "0.8" +optional = true + +[target.'cfg(target_vendor = "apple")'.dependencies.block2] +version = "0.6.2" +optional = true + +[target.'cfg(target_vendor = "apple")'.dependencies.bytemuck] +version = "1.22" +features = [ + "extern_crate_alloc", + "min_const_generics", +] +optional = true + +[target.'cfg(target_vendor = "apple")'.dependencies.objc2] +version = "0.6.3" +optional = true + +[target.'cfg(target_vendor = "apple")'.dependencies.objc2-core-foundation] +version = "0.3.2" +features = [ + "std", + "CFCGTypes", +] +optional = true +default-features = false + +[target.'cfg(target_vendor = "apple")'.dependencies.objc2-core-graphics] +version = "0.3.2" +features = [ + "std", + "CGColorSpace", +] +optional = true +default-features = false + +[target.'cfg(target_vendor = "apple")'.dependencies.objc2-foundation] +version = "0.3.2" +features = [ + "std", + "NSError", + "NSProcessInfo", + "NSRange", + "NSString", +] +optional = true +default-features = false + +[target.'cfg(target_vendor = "apple")'.dependencies.objc2-metal] +version = "0.3.2" +features = [ + "std", + "block2", + "MTLAllocation", + "MTLBlitCommandEncoder", + "MTLBlitPass", + "MTLBuffer", + "MTLCaptureManager", + "MTLCaptureScope", + "MTLCommandBuffer", + "MTLCommandEncoder", + "MTLCommandQueue", + "MTLComputeCommandEncoder", + "MTLComputePass", + "MTLComputePipeline", + "MTLCounters", + "MTLDepthStencil", + "MTLDevice", + "MTLDrawable", + "MTLEvent", + "MTLLibrary", + "MTLPipeline", + "MTLPixelFormat", + "MTLRenderCommandEncoder", + "MTLRenderPass", + "MTLRenderPipeline", + "MTLResource", + "MTLSampler", + "MTLStageInputOutputDescriptor", + "MTLTexture", + "MTLTypes", + "MTLVertexDescriptor", + "MTLAccelerationStructure", + "MTLAccelerationStructureTypes", + "MTLAccelerationStructureCommandEncoder", + "MTLResidencySet", +] +optional = true +default-features = false + +[target.'cfg(target_vendor = "apple")'.dependencies.objc2-quartz-core] +version = "0.3.2" +features = [ + "std", + "objc2-core-foundation", + "objc2-core-graphics", + "CALayer", + "CAMetalLayer", + "objc2-metal", +] +optional = true +default-features = false + +[target.'cfg(target_vendor = "apple")'.dependencies.raw-window-metal] +version = "1.0" +optional = true + +[target."cfg(unix)".dependencies.libc] +version = "0.2.183" +optional = true +default-features = false + +[target."cfg(unix)".dependencies.wayland-sys] +version = "0.31.3" +features = [ + "client", + "dlopen", + "egl", +] +optional = true + +[target."cfg(windows)".dependencies.bit-set] +version = "0.10" +optional = true +default-features = false + +[target."cfg(windows)".dependencies.glutin_wgl_sys] +version = "0.6" +optional = true + +[target."cfg(windows)".dependencies.once_cell] +version = "1.21" +optional = true +default-features = false + +[target."cfg(windows)".dependencies.range-alloc] +version = "0.1" +optional = true + +[target."cfg(windows)".dependencies.windows] +version = "0.62" +optional = true +default-features = false + +[target."cfg(windows)".dependencies.windows-core] +version = "0.62" +optional = true +default-features = false + +[target."cfg(windows)".dependencies.windows-result] +version = "0.4" +optional = true +default-features = false + +[lints.rust] +missing_debug_implementations = "warn" + +[lints.rust.unexpected_cfgs] +level = "warn" +priority = 0 +check-cfg = [ + 'cfg(feature, values("cargo-clippy"))', + "cfg(web_sys_unstable_apis)", +] diff --git a/app/vendor/rune/vendor/wgpu-hal/Cargo.toml.orig b/app/vendor/rune/vendor/wgpu-hal/Cargo.toml.orig new file mode 100644 index 0000000..da99cb1 --- /dev/null +++ b/app/vendor/rune/vendor/wgpu-hal/Cargo.toml.orig @@ -0,0 +1,365 @@ +[package] +name = "wgpu-hal" +version.workspace = true +authors.workspace = true +edition.workspace = true +description = "Hardware abstraction layer for wgpu, the cross-platform, safe, pure-rust graphics API" +homepage.workspace = true +repository.workspace = true +keywords.workspace = true +license.workspace = true + +# Override the workspace's `rust-version` key. `wgpu-core` and its dependencies +# have a less strict MSRV, to allow firefox more leeway in updating their Rust toolchain. +# +# See the repo README for more information on MSRV policy. +rust-version = "1.87" + +[package.metadata.docs.rs] +# Ideally we would enable all the features. +# +# However, the dx12 features fail to be documented because the docs.rs runner cross-compiling under +# x86_64-unknown-linux-gnu cannot compile in that environment at the moment. +features = ["metal", "vulkan", "gles", "renderdoc"] +rustdoc-args = ["--cfg", "docsrs"] +targets = [ + "x86_64-unknown-linux-gnu", + "x86_64-apple-darwin", + "x86_64-pc-windows-msvc", + "wasm32-unknown-unknown", +] + +[package.metadata.cargo-machete] +# Cargo machete can't check build.rs dependencies. See https://github.com/bnjbvr/cargo-machete/issues/100 +ignored = ["cfg_aliases"] + +[lints.rust] +missing_debug_implementations = "warn" +unexpected_cfgs = { level = "warn", check-cfg = [ + 'cfg(feature, values("cargo-clippy"))', # objc's `msg_send` macro injects this in our code https://github.com/SSheldon/rust-objc/issues/125 + 'cfg(web_sys_unstable_apis)', # web-sys uses this +] } + +[lib] + +[features] +######################## +### Backend Features ### +######################## + +# The interaction of features between wgpu-core and wgpu-hal is a bit nuanced to get +# the desired behavior on all platforms. +# +# At the wgpu-hal level the features are defined to enable the backends on all platforms +# that can compile the backend. Vulkan for example will have an effect on Windows, Mac, Linux, and Android. +# This is done with target conditional dependencies in wgpu-hal. This allows `--all-features` +# to compile on all platforms. +# +# wgpu-core's features are defined to enable the backends on their "default" platforms. For example we +# exclude the Vulkan backend on MacOS unless a separate feature `vulkan-portability` is enabled. In response +# to these features, it enables features of platform specific crates. For example, the `vulkan` feature in wgpu-core +# enables the `vulkan` feature in `wgpu-core-deps-windows-linux-android` which in turn enables the +# `vulkan` feature in `wgpu-hal` _only_ on those platforms. If you enable the `vulkan-portability` feature, it +# will enable the `vulkan` feature in `wgpu-core-deps-apple`. The only way to do this is unfortunately to have +# a separate crate for each platform category that participates in the feature unification. +# +# This trick doesn't work at the `wgpu` level, because the `wgpu` -> `wgpu-core` dependency is conditional, +# making the Cargo.toml signifigantly more complicated in all areas. +# +# See https://github.com/gfx-rs/wgpu/issues/3514, https://github.com/gfx-rs/wgpu/pull/7076, +# and https://github.com/rust-lang/cargo/issues/1197 for more information. + +## Enables the Metal backend when targeting Apple platforms. +metal = [ + # Metal is only available on Apple platforms, therefore request MSL output also only if we target an Apple platform. + "naga/msl-out", + "dep:arrayvec", + "dep:block2", + "dep:bytemuck", + "dep:libloading", + "dep:objc2", + "dep:objc2-core-foundation", + "dep:objc2-core-graphics", + "dep:objc2-foundation", + "dep:objc2-metal", + "dep:objc2-quartz-core", + "dep:parking_lot", + "dep:profiling", + "dep:smallvec", + "dep:raw-window-metal", +] +vulkan = [ + "naga/spv-out", + "dep:android_system_properties", + "dep:arrayvec", + "dep:ash", + "dep:bytemuck", + "dep:libc", + "dep:libloading", + "dep:ordered-float", + "dep:parking_lot", + "dep:profiling", + "dep:raw-window-metal", + "dep:smallvec", + "dep:windows", + "gpu-allocator/vulkan", + "windows/Win32", + "windows/Win32_Devices_Display", + "windows/Win32_Foundation", + "windows/Win32_Graphics_Dxgi", + "windows/Win32_Graphics_Dxgi_Common", + "windows/Win32_Graphics_Gdi", +] +gles = [ + "dep:arrayvec", + "dep:bytemuck", + "dep:glow", + "dep:glutin_wgl_sys", + "dep:js-sys", + "dep:khronos-egl", + "dep:libloading", + "dep:ndk-sys", + "dep:objc2", + "dep:parking_lot", + "dep:profiling", + "dep:wasm-bindgen", + "dep:wayland-sys", + "dep:web-sys", + "dep:windows-result", + "naga/glsl-out", + "wgpu-types/web", + "windows-result/std", # Need to enable this for the `Error` impl on `windows_result::Error` to work. + "windows/Win32_Graphics_Gdi", + "windows/Win32_Graphics_OpenGL", + "windows/Win32_System_LibraryLoader", + "windows/Win32_UI_WindowsAndMessaging", +] +## Enables the DX12 backend when targeting Windows. +dx12 = [ + "dep:arrayvec", + "dep:bit-set", + "dep:bytemuck", + "dep:gpu-allocator", + "dep:libloading", + "dep:once_cell", + "dep:ordered-float", + "dep:parking_lot", + "dep:profiling", + "dep:range-alloc", + "dep:windows-core", + "gpu-allocator/d3d12", + "naga/hlsl-out", + "once_cell/std", + "windows/Win32_Devices_DeviceAndDriverInstallation", + "windows/Win32_Devices_Display", + "windows/Win32_Graphics_Direct3D_Dxc", + "windows/Win32_Graphics_Direct3D_Fxc", + "windows/Win32_Graphics_Direct3D", + "windows/Win32_Graphics_Direct3D12", + "windows/Win32_Graphics_DirectComposition", + "windows/Win32_Graphics_Dxgi_Common", + "windows/Win32_Graphics_Gdi", + "windows/Win32_Security", + "windows/Win32_System_Diagnostics_Debug", + "windows/Win32_System_Kernel", + "windows/Win32_System_Performance", + "windows/Win32_System_Threading", + "windows/Win32_UI_WindowsAndMessaging", +] + +########################### +### Misc Other Features ### +########################### + +static-dxc = ["dep:mach-dxcompiler-rs"] +renderdoc = ["dep:libloading", "dep:renderdoc-sys"] +fragile-send-sync-non-atomic-wasm = [ + "wgpu-types/fragile-send-sync-non-atomic-wasm", +] +portable-atomic = ["dep:portable-atomic", "dep:portable-atomic-util"] + +################################### +### Internal Debugging Features ### +################################### + +# Panic when running into a device lost error (for debugging purposes). +# Only affects the d3d12 and vulkan backends. +device_lost_panic = [] +# Panic when running into an internal error other than out-of-memory and device lost +# (for debugging purposes). +# +# Only affects the d3d12 and vulkan backends. +internal_error_panic = [] +# Tracks validation errors in a `VALIDATION_CANARY` static. +validation_canary = ["dep:parking_lot"] + +[[example]] +name = "halmark" + +[[example]] +name = "raw-gles" +required-features = ["gles"] + +##################### +### Platform: All ### +##################### + +[dependencies] +naga.workspace = true +wgpu-naga-bridge.workspace = true +naga-types = { workspace = true } +wgpu-types = { workspace = true, default-features = false } + +# Dependencies in the lib and empty backend +bitflags.workspace = true +cfg-if.workspace = true +log = { workspace = true } +parking_lot = { workspace = true, optional = true } +raw-window-handle.workspace = true +thiserror.workspace = true + +# Target agnostic dependencies used only in backends. +arrayvec = { workspace = true, optional = true } +bytemuck = { workspace = true, optional = true, features = ["derive"] } +hashbrown = { workspace = true } +ordered-float = { workspace = true, optional = true } +profiling = { workspace = true, optional = true, default-features = false } +static_assertions = { workspace = true } + +# Backend: GLES +glow = { workspace = true, optional = true } + +######################## +### Platform: Native ### +######################## + +[target.'cfg(not(target_arch = "wasm32"))'.dependencies] +# Backend: Vulkan and Dx12 +gpu-allocator = { workspace = true, optional = true } +# Backend: Vulkan +ash = { workspace = true, optional = true } +smallvec = { workspace = true, optional = true, features = ["union"] } +# Backend: GLES +khronos-egl = { workspace = true, features = ["dynamic"], optional = true } +libloading = { workspace = true, optional = true } +renderdoc-sys = { workspace = true, optional = true } + +########################## +### Platform: All Unix ### +########################## + +[target.'cfg(unix)'.dependencies] +# Backend: Vulkan +libc = { workspace = true, optional = true } +# backend: GLES +wayland-sys = { version = "0.31.3", features = [ + "client", + "dlopen", + "egl", +], optional = true } + +## Support creating textures from DRM display/window handles. +[target.'cfg(all(unix, not(target_vendor = "apple"), not(target_family = "wasm")))'.dependencies] +drm = { version = "0.15", optional = true } + +######################### +### Platform: Windows ### +######################### + +[target.'cfg(windows)'.dependencies] +# Backend: Dx12 and GLES +windows = { workspace = true, optional = true } +windows-core = { workspace = true, optional = true } +windows-result = { workspace = true, optional = true } +# Backend: Dx12 +bit-set = { workspace = true, optional = true } +range-alloc = { workspace = true, optional = true } +once_cell = { workspace = true, optional = true } +# backend: GLES +glutin_wgl_sys = { workspace = true, optional = true } + +### Platform: x86/x86_64 Windows ### +# This doesn't support aarch64. See https://github.com/gfx-rs/wgpu/issues/6860. +# This doesn't support x86_64-pc-windows-gnu. See https://github.com/gfx-rs/wgpu/issues/8303 +# +# ⚠️ Keep in sync with static_dxc cfg in build.rs and cfg_alias in `wgpu` crate ⚠️ +[target.'cfg(all(windows, not(target_arch = "aarch64"), target_env = "msvc"))'.dependencies] +mach-dxcompiler-rs = { workspace = true, optional = true } + +####################### +### Platform: Apple ### +####################### + +[target.'cfg(target_vendor = "apple")'.dependencies] +# Backend: Metal +block2 = { workspace = true, optional = true } +bytemuck = { workspace = true, optional = true } +objc2 = { workspace = true, optional = true } +objc2-core-foundation = { workspace = true, optional = true } +objc2-core-graphics = { workspace = true, optional = true } +objc2-foundation = { workspace = true, optional = true } +objc2-metal = { workspace = true, optional = true } +objc2-quartz-core = { workspace = true, optional = true } + +# backend: Metal + Vulkan +raw-window-metal = { workspace = true, optional = true } + +######################### +### Platform: Android ### +######################### + +[target.'cfg(target_os = "android")'.dependencies] +android_system_properties = { workspace = true, optional = true } +ndk-sys = { workspace = true, optional = true } + +############################# +### Platform: Webassembly ### +############################# + +[target.'cfg(all(target_arch = "wasm32", not(target_os = "emscripten")))'.dependencies] +# Backend: GLES +wasm-bindgen = { workspace = true, optional = true } +web-sys = { workspace = true, optional = true, features = [ + "default", + "Window", + "HtmlCanvasElement", + "WebGl2RenderingContext", + "OffscreenCanvas", + "VideoFrame", +] } +js-sys = { workspace = true, optional = true, default-features = true } + +############################ +### Platform: Emscripten ### +############################ + +[target.'cfg(target_os = "emscripten")'.dependencies] +# Backend: GLES +khronos-egl = { workspace = true, optional = true, features = [ + "static", + "no-pkg-config", +] } +# Note: it's unused by emscripten, but we keep it to have single code base in egl.rs +libloading = { workspace = true, optional = true } + +[target.'cfg(any(not(target_has_atomic = "64"), not(target_has_atomic = "ptr")))'.dependencies] +portable-atomic = { workspace = true, optional = true } + +[target.'cfg(not(target_has_atomic = "ptr"))'.dependencies] +portable-atomic-util = { workspace = true, features = [ + "alloc", +], optional = true } + +[build-dependencies] +cfg_aliases.workspace = true + +[dev-dependencies] +env_logger.workspace = true +glam.workspace = true # for ray-traced-triangle example +naga = { workspace = true, features = ["wgsl-in", "termcolor"] } +winit.workspace = true # for "halmark" example + +### Platform: Windows + MacOS + Linux for "raw-gles" example ### +[target.'cfg(not(any(target_arch = "wasm32", target_os = "ios", target_os = "visionos", target_env = "ohos")))'.dev-dependencies] +glutin-winit = { workspace = true, features = ["egl", "wgl", "wayland", "x11"] } +glutin = { workspace = true, features = ["egl", "wgl", "wayland", "x11"] } diff --git a/app/vendor/rune/vendor/wgpu-hal/LICENSE.APACHE b/app/vendor/rune/vendor/wgpu-hal/LICENSE.APACHE new file mode 100644 index 0000000..d9a10c0 --- /dev/null +++ b/app/vendor/rune/vendor/wgpu-hal/LICENSE.APACHE @@ -0,0 +1,176 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS diff --git a/app/vendor/rune/vendor/wgpu-hal/LICENSE.MIT b/app/vendor/rune/vendor/wgpu-hal/LICENSE.MIT new file mode 100644 index 0000000..8d02e4d --- /dev/null +++ b/app/vendor/rune/vendor/wgpu-hal/LICENSE.MIT @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2025 The gfx-rs developers + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/app/vendor/rune/vendor/wgpu-hal/README.md b/app/vendor/rune/vendor/wgpu-hal/README.md new file mode 100644 index 0000000..1ea2f44 --- /dev/null +++ b/app/vendor/rune/vendor/wgpu-hal/README.md @@ -0,0 +1,119 @@ +# `wgpu_hal`: a cross-platform unsafe graphics abstraction + +This crate defines a set of traits abstracting over modern graphics APIs, +with implementations ("backends") for Vulkan, Metal, Direct3D, and GL. + +`wgpu_hal` is a spiritual successor to +[gfx-hal](https://github.com/gfx-rs/gfx), but with reduced scope, and +oriented towards WebGPU implementation goals. It has no overhead for +validation or tracking, and the API translation overhead is kept to the bare +minimum by the design of WebGPU. This API can be used for resource-demanding +applications and engines. + +The `wgpu_hal` crate's main design choices: + +- Our traits are meant to be _portable_: proper use + should get equivalent results regardless of the backend. + +- Our traits' contracts are _unsafe_: implementations perform minimal + validation, if any, and incorrect use will often cause undefined behavior. + This allows us to minimize the overhead we impose over the underlying + graphics system. If you need safety, the [`wgpu-core`] crate provides a + safe API for driving `wgpu_hal`, implementing all necessary validation, + resource state tracking, and so on. (Note that `wgpu-core` is designed for + use via FFI; the [`wgpu`] crate provides more idiomatic Rust bindings for + `wgpu-core`.) Or, you can do your own validation. + +- In the same vein, returned errors _only cover cases the user can't + anticipate_, like running out of memory or losing the device. Any errors + that the user could reasonably anticipate are their responsibility to + avoid. For example, `wgpu_hal` returns no error for mapping a buffer that's + not mappable: as the buffer creator, the user should already know if they + can map it. + +- We use _static dispatch_. The traits are not + generally object-safe. You must select a specific backend type + like [`vulkan::Api`] or [`metal::Api`], and then use that + according to the main traits, or call backend-specific methods. + +- We use _idiomatic Rust parameter passing_, + taking objects by reference, returning them by value, and so on, + unlike `wgpu-core`, which refers to objects by ID. + +- We map buffer contents _persistently_. This means that the buffer + can remain mapped on the CPU while the GPU reads or writes to it. + You must explicitly indicate when data might need to be + transferred between CPU and GPU, if `wgpu_hal` indicates that the + mapping is not coherent (that is, automatically synchronized + between the two devices). + +- You must record _explicit barriers_ between different usages of a + resource. For example, if a buffer is written to by a compute + shader, and then used as and index buffer to a draw call, you + must use [`CommandEncoder::transition_buffers`] between those two + operations. + +- Pipeline layouts are _explicitly specified_ when setting bind + group. Incompatible layouts disturb groups bound at higher indices. + +- The API _accepts collections as iterators_, to avoid forcing the user to + store data in particular containers. The implementation doesn't guarantee + that any of the iterators are drained, unless stated otherwise by the + function documentation. For this reason, we recommend that iterators don't + do any mutating work. + +Unfortunately, `wgpu_hal`'s safety requirements are not fully documented. +Ideally, all trait methods would have doc comments setting out the +requirements users must meet to ensure correct and portable behavior. If you +are aware of a specific requirement that a backend imposes that is not +ensured by the traits' documented rules, please file an issue. Or, if you are +a capable technical writer, please file a pull request! + +[`wgpu-core`]: https://crates.io/crates/wgpu-core +[`wgpu`]: https://crates.io/crates/wgpu +[`vulkan::Api`]: vulkan/struct.Api.html +[`metal::Api`]: metal/struct.Api.html + +## Primary backends + +The `wgpu_hal` crate has full-featured backends implemented on the following +platform graphics APIs: + +- Vulkan, available on Linux, Android, and Windows, using the [`ash`] crate's + Vulkan bindings. It's also available on macOS, if you install [MoltenVK]. + +- Metal on macOS, using the [`metal`] crate's bindings. + +- Direct3D 12 on Windows, using the [`windows`] crate's bindings. + +[`ash`]: https://crates.io/crates/ash +[MoltenVK]: https://github.com/KhronosGroup/MoltenVK +[`metal`]: https://crates.io/crates/metal +[`windows`]: https://crates.io/crates/windows + +## Secondary backends + +The `wgpu_hal` crate has a partial implementation based on the following +platform graphics API: + +- The GL backend is available anywhere OpenGL, OpenGL ES, or WebGL are + available. See the [`gles`] module documentation for details. + +[`gles`]: gles/index.html + +You can see what capabilities an adapter is missing by checking the +[`DownlevelCapabilities`][tdc] in [`ExposedAdapter::capabilities`], available +from [`Instance::enumerate_adapters`]. + +The API is generally designed to fit the primary backends better than the +secondary backends, so the latter may impose more overhead. + +[tdc]: wgt::DownlevelCapabilities + +## Debugging + +Most of the information on the wiki [Debugging wgpu Applications][wiki-debug] +page still applies to this API, with the exception of API tracing/replay +functionality, which is only available in `wgpu-core`. + +[wiki-debug]: https://github.com/gfx-rs/wgpu/wiki/Debugging-wgpu-Applications diff --git a/app/vendor/rune/vendor/wgpu-hal/build.rs b/app/vendor/rune/vendor/wgpu-hal/build.rs new file mode 100644 index 0000000..7430ccb --- /dev/null +++ b/app/vendor/rune/vendor/wgpu-hal/build.rs @@ -0,0 +1,36 @@ +fn main() { + cfg_aliases::cfg_aliases! { + native: { not(target_arch = "wasm32") }, + send_sync: { any( + not(target_arch = "wasm32"), + all(feature = "fragile-send-sync-non-atomic-wasm", not(target_feature = "atomics")) + ) }, + webgl: { all(target_arch = "wasm32", not(target_os = "emscripten"), gles) }, + Emscripten: { all(target_os = "emscripten", gles) }, + dx12: { all(target_os = "windows", feature = "dx12") }, + gles: { all(feature = "gles") }, + // Within the GL ES backend, use `std` and be Send + Sync only if we are using a target + // that, among the ones where the GL ES backend is supported, has `std`. + gles_with_std: { all( + feature = "gles", + any( + not(target_arch = "wasm32"), + // Accept wasm32-unknown-unknown, which uniquely has a stub `std` + all(target_vendor = "unknown", target_os = "unknown"), + // Accept wasm32-unknown-emscripten and similar, which has a real `std` + target_os = "emscripten" + ) + ) }, + metal: { all(target_vendor = "apple", feature = "metal") }, + vulkan: { all(not(target_arch = "wasm32"), feature = "vulkan") }, + drm: { all( + feature = "drm", + any(target_os = "linux", target_os = "freebsd", target_os = "netbsd", target_os = "openbsd") + ) }, + any_backend: { any(dx12, metal, vulkan, gles) }, + // ⚠️ Keep in sync with target.cfg() definition in Cargo.toml and cfg_alias in `wgpu` crate ⚠️ + static_dxc: { all(target_os = "windows", feature = "static-dxc", not(target_arch = "aarch64"), target_env = "msvc") }, + supports_64bit_atomics: { target_has_atomic = "64" }, + supports_ptr_atomics: { target_has_atomic = "ptr" } + } +} diff --git a/app/vendor/rune/vendor/wgpu-hal/examples/halmark/main.rs b/app/vendor/rune/vendor/wgpu-hal/examples/halmark/main.rs new file mode 100644 index 0000000..d49139e --- /dev/null +++ b/app/vendor/rune/vendor/wgpu-hal/examples/halmark/main.rs @@ -0,0 +1,919 @@ +//! This example shows basic usage of wgpu-hal by rendering +//! a ton of moving sprites, each with a separate texture and draw call. +extern crate wgpu_hal as hal; + +use hal::{ + Adapter as _, CommandEncoder as _, Device as _, Instance as _, Queue as _, Surface as _, +}; +use raw_window_handle::{HasDisplayHandle, HasWindowHandle}; +use winit::{ + application::ApplicationHandler, + event::{ElementState, KeyEvent, WindowEvent}, + event_loop::{ActiveEventLoop, ControlFlow}, + keyboard::{Key, NamedKey}, + window::Window, +}; + +use std::{ + borrow::{Borrow, Cow}, + iter, + num::NonZeroU64, + ptr, + time::Instant, +}; + +const MAX_BUNNIES: usize = 1 << 20; +const BUNNY_SIZE: f32 = 0.15 * 256.0; +const GRAVITY: f32 = -9.8 * 100.0; +const MAX_VELOCITY: f32 = 750.0; +const DESIRED_MAX_LATENCY: u32 = 2; + +#[repr(C)] +#[derive(Clone, Copy)] +struct Globals { + mvp: [[f32; 4]; 4], + size: [f32; 2], + pad: [f32; 2], +} + +#[repr(C, align(256))] +#[derive(Clone, Copy)] +struct Locals { + position: [f32; 2], + velocity: [f32; 2], + color: u32, + _pad: u32, +} + +struct ExecutionContext<A: hal::Api> { + encoder: A::CommandEncoder, + fence: A::Fence, + fence_value: hal::FenceValue, + used_views: Vec<A::TextureView>, + used_cmd_bufs: Vec<A::CommandBuffer>, + frames_recorded: usize, +} + +impl<A: hal::Api> ExecutionContext<A> { + unsafe fn wait_and_clear(&mut self, device: &A::Device) { + device.wait(&self.fence, self.fence_value, None).unwrap(); + self.encoder.reset_all(self.used_cmd_bufs.drain(..)); + for view in self.used_views.drain(..) { + device.destroy_texture_view(view); + } + self.frames_recorded = 0; + } +} + +#[allow(dead_code)] +struct Example<A: hal::Api> { + instance: A::Instance, + adapter: A::Adapter, + surface: A::Surface, + surface_format: wgpu_types::TextureFormat, + device: A::Device, + queue: A::Queue, + global_group: A::BindGroup, + local_group: A::BindGroup, + global_group_layout: A::BindGroupLayout, + local_group_layout: A::BindGroupLayout, + pipeline_layout: A::PipelineLayout, + shader: A::ShaderModule, + pipeline: A::RenderPipeline, + bunnies: Vec<Locals>, + local_buffer: A::Buffer, + local_alignment: u32, + global_buffer: A::Buffer, + sampler: A::Sampler, + texture: A::Texture, + texture_view: A::TextureView, + contexts: Vec<ExecutionContext<A>>, + context_index: usize, + extent: [u32; 2], + start: Instant, +} + +impl<A: hal::Api> Example<A> { + fn init(window: &winit::window::Window) -> Result<Self, Box<dyn std::error::Error>> { + // The Instance can be initialized with the DisplayHandle from the EventLoop as well + let raw_display_handle = window.display_handle()?; + + let instance_desc = hal::InstanceDescriptor { + name: "example", + flags: wgpu_types::InstanceFlags::from_build_config().with_env(), + memory_budget_thresholds: wgpu_types::MemoryBudgetThresholds::default(), + // Can't rely on having DXC available, so use FXC instead + backend_options: wgpu_types::BackendOptions::default(), + telemetry: None, + display: Some(raw_display_handle), + }; + let instance = unsafe { A::Instance::init(&instance_desc)? }; + let surface = { + let raw_window_handle = window.window_handle()?.as_raw(); + + unsafe { + instance + .create_surface(raw_display_handle.as_raw(), raw_window_handle) + .unwrap() + } + }; + + let (adapter, capabilities) = unsafe { + let mut adapters = instance.enumerate_adapters(Some(&surface)); + if adapters.is_empty() { + return Err("no adapters found".into()); + } + let exposed = adapters.swap_remove(0); + (exposed.adapter, exposed.capabilities) + }; + + let surface_caps = unsafe { adapter.surface_capabilities(&surface) } + .ok_or("failed to get surface capabilities")?; + log::info!("Surface caps: {surface_caps:#?}"); + + let hal::OpenDevice { device, queue } = unsafe { + adapter + .open( + wgpu_types::Features::empty(), + &wgpu_types::Limits::default(), + &wgpu_types::MemoryHints::default(), + ) + .unwrap() + }; + + let window_size: (u32, u32) = window.inner_size().into(); + let surface_config = hal::SurfaceConfiguration { + maximum_frame_latency: DESIRED_MAX_LATENCY.clamp( + *surface_caps.maximum_frame_latency.start(), + *surface_caps.maximum_frame_latency.end(), + ), + present_mode: wgpu_types::PresentMode::Fifo, + composite_alpha_mode: wgpu_types::CompositeAlphaMode::Opaque, + format: wgpu_types::TextureFormat::Bgra8UnormSrgb, + color_space: wgpu_types::SurfaceColorSpace::Srgb, + extent: wgpu_types::Extent3d { + width: window_size.0, + height: window_size.1, + depth_or_array_layers: 1, + }, + usage: wgpu_types::TextureUses::COLOR_TARGET, + view_formats: vec![], + }; + unsafe { + surface.configure(&device, &surface_config).unwrap(); + }; + + let naga_shader = { + let shader_file = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("examples") + .join("halmark") + .join("shader.wgsl"); + let source = std::fs::read_to_string(shader_file).unwrap(); + let module = naga::front::wgsl::Frontend::new().parse(&source).unwrap(); + let info = naga::valid::Validator::new( + naga::valid::ValidationFlags::all(), + naga::valid::Capabilities::empty(), + ) + .validate(&module) + .unwrap(); + hal::NagaShader { + module: Cow::Owned(module), + info, + debug_source: None, + } + }; + let shader_desc = hal::ShaderModuleDescriptor { + label: None, + runtime_checks: wgpu_types::ShaderRuntimeChecks::checked(), + }; + let shader = unsafe { + device + .create_shader_module(&shader_desc, hal::ShaderInput::Naga(naga_shader)) + .unwrap() + }; + + let global_bgl_desc = hal::BindGroupLayoutDescriptor { + label: None, + flags: hal::BindGroupLayoutFlags::empty(), + entries: &[ + wgpu_types::BindGroupLayoutEntry { + binding: 0, + visibility: wgpu_types::ShaderStages::VERTEX, + ty: wgpu_types::BindingType::Buffer { + ty: wgpu_types::BufferBindingType::Uniform, + has_dynamic_offset: false, + min_binding_size: wgpu_types::BufferSize::new(size_of::<Globals>() as _), + }, + count: None, + }, + wgpu_types::BindGroupLayoutEntry { + binding: 1, + visibility: wgpu_types::ShaderStages::FRAGMENT, + ty: wgpu_types::BindingType::Texture { + sample_type: wgpu_types::TextureSampleType::Float { filterable: true }, + view_dimension: wgpu_types::TextureViewDimension::D2, + multisampled: false, + }, + count: None, + }, + wgpu_types::BindGroupLayoutEntry { + binding: 2, + visibility: wgpu_types::ShaderStages::FRAGMENT, + ty: wgpu_types::BindingType::Sampler(wgpu_types::SamplerBindingType::Filtering), + count: None, + }, + ], + }; + + let global_group_layout = + unsafe { device.create_bind_group_layout(&global_bgl_desc).unwrap() }; + + let local_bgl_desc = hal::BindGroupLayoutDescriptor { + label: None, + flags: hal::BindGroupLayoutFlags::empty(), + entries: &[wgpu_types::BindGroupLayoutEntry { + binding: 0, + visibility: wgpu_types::ShaderStages::VERTEX, + ty: wgpu_types::BindingType::Buffer { + ty: wgpu_types::BufferBindingType::Uniform, + has_dynamic_offset: true, + min_binding_size: wgpu_types::BufferSize::new(size_of::<Locals>() as _), + }, + count: None, + }], + }; + let local_group_layout = + unsafe { device.create_bind_group_layout(&local_bgl_desc).unwrap() }; + + let pipeline_layout_desc = hal::PipelineLayoutDescriptor { + label: None, + flags: hal::PipelineLayoutFlags::empty(), + bind_group_layouts: &[Some(&global_group_layout), Some(&local_group_layout)], + immediate_size: 0, + }; + let pipeline_layout = unsafe { + device + .create_pipeline_layout(&pipeline_layout_desc) + .unwrap() + }; + + let constants = naga::back::PipelineConstants::default(); + let pipeline_desc = hal::RenderPipelineDescriptor { + label: None, + layout: &pipeline_layout, + vertex_processor: hal::VertexProcessor::Standard { + vertex_stage: hal::ProgrammableStage { + module: &shader, + entry_point: "vs_main", + constants: &constants, + zero_initialize_workgroup_memory: true, + }, + vertex_buffers: &[], + }, + fragment_stage: Some(hal::ProgrammableStage { + module: &shader, + entry_point: "fs_main", + constants: &constants, + zero_initialize_workgroup_memory: true, + }), + primitive: wgpu_types::PrimitiveState { + topology: wgpu_types::PrimitiveTopology::TriangleStrip, + ..wgpu_types::PrimitiveState::default() + }, + depth_stencil: None, + multisample: wgpu_types::MultisampleState::default(), + color_targets: &[Some(wgpu_types::ColorTargetState { + format: surface_config.format, + blend: Some(wgpu_types::BlendState::ALPHA_BLENDING), + write_mask: wgpu_types::ColorWrites::default(), + })], + multiview_mask: None, + cache: None, + }; + let pipeline = unsafe { device.create_render_pipeline(&pipeline_desc).unwrap() }; + + let texture_data = [0xFFu8; 4]; + + let staging_buffer_desc = hal::BufferDescriptor { + label: Some("stage"), + size: texture_data.len() as wgpu_types::BufferAddress, + usage: wgpu_types::BufferUses::MAP_WRITE | wgpu_types::BufferUses::COPY_SRC, + memory_flags: hal::MemoryFlags::TRANSIENT | hal::MemoryFlags::PREFER_COHERENT, + }; + let staging_buffer = unsafe { device.create_buffer(&staging_buffer_desc).unwrap() }; + unsafe { + let mapping = device + .map_buffer(&staging_buffer, 0..staging_buffer_desc.size) + .unwrap(); + ptr::copy_nonoverlapping( + texture_data.as_ptr(), + mapping.ptr.as_ptr(), + texture_data.len(), + ); + device.unmap_buffer(&staging_buffer); + assert!(mapping.is_coherent); + } + + let texture_desc = hal::TextureDescriptor { + label: None, + size: wgpu_types::Extent3d { + width: 1, + height: 1, + depth_or_array_layers: 1, + }, + mip_level_count: 1, + sample_count: 1, + dimension: wgpu_types::TextureDimension::D2, + format: wgpu_types::TextureFormat::Rgba8UnormSrgb, + usage: wgpu_types::TextureUses::COPY_DST | wgpu_types::TextureUses::RESOURCE, + memory_flags: hal::MemoryFlags::empty(), + view_formats: vec![], + }; + let texture = unsafe { device.create_texture(&texture_desc).unwrap() }; + + let cmd_encoder_desc = hal::CommandEncoderDescriptor { + label: None, + queue: &queue, + }; + let mut cmd_encoder = unsafe { device.create_command_encoder(&cmd_encoder_desc).unwrap() }; + unsafe { cmd_encoder.begin_encoding(Some("init")).unwrap() }; + { + let buffer_barrier = hal::BufferBarrier { + buffer: &staging_buffer, + usage: hal::StateTransition { + from: wgpu_types::BufferUses::empty(), + to: wgpu_types::BufferUses::COPY_SRC, + }, + }; + let texture_barrier1 = hal::TextureBarrier { + texture: &texture, + range: wgpu_types::ImageSubresourceRange::default(), + usage: hal::StateTransition { + from: wgpu_types::TextureUses::UNINITIALIZED, + to: wgpu_types::TextureUses::COPY_DST, + }, + }; + let texture_barrier2 = hal::TextureBarrier { + texture: &texture, + range: wgpu_types::ImageSubresourceRange::default(), + usage: hal::StateTransition { + from: wgpu_types::TextureUses::COPY_DST, + to: wgpu_types::TextureUses::RESOURCE, + }, + }; + let copy = hal::BufferTextureCopy { + buffer_layout: wgpu_types::TexelCopyBufferLayout { + offset: 0, + bytes_per_row: Some(4), + rows_per_image: None, + }, + texture_base: hal::TextureCopyBase { + origin: wgpu_types::Origin3d::ZERO, + mip_level: 0, + array_layer: 0, + aspect: hal::FormatAspects::COLOR, + }, + size: hal::CopyExtent { + width: 1, + height: 1, + depth: 1, + }, + }; + unsafe { + cmd_encoder.transition_buffers(iter::once(buffer_barrier)); + cmd_encoder.transition_textures(iter::once(texture_barrier1)); + cmd_encoder.copy_buffer_to_texture(&staging_buffer, &texture, iter::once(copy)); + cmd_encoder.transition_textures(iter::once(texture_barrier2)); + } + } + + let sampler_desc = hal::SamplerDescriptor { + label: None, + address_modes: [wgpu_types::AddressMode::ClampToEdge; 3], + mag_filter: wgpu_types::FilterMode::Linear, + min_filter: wgpu_types::FilterMode::Nearest, + mipmap_filter: wgpu_types::MipmapFilterMode::Nearest, + lod_clamp: 0.0..32.0, + compare: None, + anisotropy_clamp: 1, + border_color: None, + }; + let sampler = unsafe { device.create_sampler(&sampler_desc).unwrap() }; + + let globals = Globals { + // cgmath::ortho() projection + mvp: [ + [2.0 / window_size.0 as f32, 0.0, 0.0, 0.0], + [0.0, 2.0 / window_size.1 as f32, 0.0, 0.0], + [0.0, 0.0, 1.0, 0.0], + [-1.0, -1.0, 0.0, 1.0], + ], + size: [BUNNY_SIZE; 2], + pad: [0.0; 2], + }; + + let global_buffer_desc = hal::BufferDescriptor { + label: Some("global"), + size: size_of::<Globals>() as wgpu_types::BufferAddress, + usage: wgpu_types::BufferUses::MAP_WRITE | wgpu_types::BufferUses::UNIFORM, + memory_flags: hal::MemoryFlags::PREFER_COHERENT, + }; + let global_buffer = unsafe { + let buffer = device.create_buffer(&global_buffer_desc).unwrap(); + let mapping = device + .map_buffer(&buffer, 0..global_buffer_desc.size) + .unwrap(); + ptr::copy_nonoverlapping( + &globals as *const Globals as *const u8, + mapping.ptr.as_ptr(), + size_of::<Globals>(), + ); + device.unmap_buffer(&buffer); + assert!(mapping.is_coherent); + buffer + }; + + let local_alignment = wgpu_types::math::align_to( + size_of::<Locals>() as u32, + capabilities.limits.min_uniform_buffer_offset_alignment, + ); + let local_buffer_desc = hal::BufferDescriptor { + label: Some("local"), + size: (MAX_BUNNIES as wgpu_types::BufferAddress) + * (local_alignment as wgpu_types::BufferAddress), + usage: wgpu_types::BufferUses::MAP_WRITE | wgpu_types::BufferUses::UNIFORM, + memory_flags: hal::MemoryFlags::PREFER_COHERENT, + }; + let local_buffer = unsafe { device.create_buffer(&local_buffer_desc).unwrap() }; + + let view_desc = hal::TextureViewDescriptor { + label: None, + format: texture_desc.format, + dimension: wgpu_types::TextureViewDimension::D2, + usage: wgpu_types::TextureUses::RESOURCE, + range: wgpu_types::ImageSubresourceRange::default(), + }; + let texture_view = unsafe { device.create_texture_view(&texture, &view_desc).unwrap() }; + + let global_group = { + // SAFETY: This is the same size that was specified for buffer creation. + let global_buffer_binding = hal::BufferBinding::new_unchecked( + &global_buffer, + 0, + NonZeroU64::new(global_buffer_desc.size), + ); + let texture_binding = hal::TextureBinding { + view: &texture_view, + usage: wgpu_types::TextureUses::RESOURCE, + }; + let global_group_desc = hal::BindGroupDescriptor { + label: Some("global"), + layout: &global_group_layout, + buffers: &[global_buffer_binding], + samplers: &[&sampler], + textures: &[texture_binding], + acceleration_structures: &[], + external_textures: &[], + entries: &[ + hal::BindGroupEntry { + binding: 0, + resource_index: 0, + count: 1, + }, + hal::BindGroupEntry { + binding: 1, + resource_index: 0, + count: 1, + }, + hal::BindGroupEntry { + binding: 2, + resource_index: 0, + count: 1, + }, + ], + }; + unsafe { device.create_bind_group(&global_group_desc).unwrap() } + }; + + let local_group = { + // SAFETY: The size must fit within the buffer. + let local_buffer_binding = hal::BufferBinding::new_unchecked( + &local_buffer, + 0, + wgpu_types::BufferSize::new(size_of::<Locals>() as _), + ); + let local_group_desc = hal::BindGroupDescriptor { + label: Some("local"), + layout: &local_group_layout, + buffers: &[local_buffer_binding], + samplers: &[], + textures: &[], + acceleration_structures: &[], + external_textures: &[], + entries: &[hal::BindGroupEntry { + binding: 0, + resource_index: 0, + count: 1, + }], + }; + unsafe { device.create_bind_group(&local_group_desc).unwrap() } + }; + + let init_fence_value = 1; + let fence = unsafe { + let mut fence = device.create_fence().unwrap(); + let init_cmd = cmd_encoder.end_encoding().unwrap(); + queue + .submit(&[&init_cmd], &[], (&mut fence, init_fence_value)) + .unwrap(); + device.wait(&fence, init_fence_value, None).unwrap(); + device.destroy_buffer(staging_buffer); + cmd_encoder.reset_all(iter::once(init_cmd)); + fence + }; + + Ok(Example { + instance, + surface, + surface_format: surface_config.format, + adapter, + device, + queue, + pipeline_layout, + shader, + pipeline, + global_group, + local_group, + global_group_layout, + local_group_layout, + bunnies: Vec::new(), + local_buffer, + local_alignment, + global_buffer, + sampler, + texture, + texture_view, + contexts: vec![ExecutionContext { + encoder: cmd_encoder, + fence, + fence_value: init_fence_value + 1, + used_views: Vec::new(), + used_cmd_bufs: Vec::new(), + frames_recorded: 0, + }], + context_index: 0, + extent: [window_size.0, window_size.1], + start: Instant::now(), + }) + } + + fn is_empty(&self) -> bool { + self.bunnies.is_empty() + } + + fn exit(mut self) { + unsafe { + { + let ctx = &mut self.contexts[self.context_index]; + self.queue + .submit(&[], &[], (&mut ctx.fence, ctx.fence_value)) + .unwrap(); + } + + for mut ctx in self.contexts { + ctx.wait_and_clear(&self.device); + drop(ctx.encoder); + self.device.destroy_fence(ctx.fence); + } + + self.device.destroy_bind_group(self.local_group); + self.device.destroy_bind_group(self.global_group); + self.device.destroy_buffer(self.local_buffer); + self.device.destroy_buffer(self.global_buffer); + self.device.destroy_texture_view(self.texture_view); + self.device.destroy_texture(self.texture); + self.device.destroy_sampler(self.sampler); + self.device.destroy_shader_module(self.shader); + self.device.destroy_render_pipeline(self.pipeline); + self.device + .destroy_bind_group_layout(self.local_group_layout); + self.device + .destroy_bind_group_layout(self.global_group_layout); + self.device.destroy_pipeline_layout(self.pipeline_layout); + + self.surface.unconfigure(&self.device); + drop(self.queue); + drop(self.device); + drop(self.surface); + drop(self.adapter); + } + } + + fn update(&mut self, event: winit::event::WindowEvent) { + if let winit::event::WindowEvent::KeyboardInput { + event: + KeyEvent { + logical_key: Key::Named(NamedKey::Space), + state: ElementState::Pressed, + .. + }, + .. + } = event + { + let spawn_count = 64 + self.bunnies.len() / 2; + let elapsed = self.start.elapsed(); + let color = elapsed.as_nanos() as u32; + println!( + "Spawning {} bunnies, total at {}", + spawn_count, + self.bunnies.len() + spawn_count + ); + for i in 0..spawn_count { + let random = ((elapsed.as_nanos() * (i + 1) as u128) & 0xFF) as f32 / 255.0; + let speed = random * MAX_VELOCITY - (MAX_VELOCITY * 0.5); + self.bunnies.push(Locals { + position: [0.0, 0.5 * (self.extent[1] as f32)], + velocity: [speed, 0.0], + color, + _pad: 0, + }); + } + } + } + + fn render(&mut self) { + let delta = 0.01; + for bunny in self.bunnies.iter_mut() { + bunny.position[0] += bunny.velocity[0] * delta; + bunny.position[1] += bunny.velocity[1] * delta; + bunny.velocity[1] += GRAVITY * delta; + if (bunny.velocity[0] > 0.0 + && bunny.position[0] + 0.5 * BUNNY_SIZE > self.extent[0] as f32) + || (bunny.velocity[0] < 0.0 && bunny.position[0] - 0.5 * BUNNY_SIZE < 0.0) + { + bunny.velocity[0] *= -1.0; + } + if bunny.velocity[1] < 0.0 && bunny.position[1] < 0.5 * BUNNY_SIZE { + bunny.velocity[1] *= -1.0; + } + } + + if !self.bunnies.is_empty() { + let size = self.bunnies.len() * self.local_alignment as usize; + unsafe { + let mapping = self + .device + .map_buffer(&self.local_buffer, 0..size as wgpu_types::BufferAddress) + .unwrap(); + ptr::copy_nonoverlapping( + self.bunnies.as_ptr() as *const u8, + mapping.ptr.as_ptr(), + size, + ); + assert!(mapping.is_coherent); + self.device.unmap_buffer(&self.local_buffer); + } + } + + let ctx = &mut self.contexts[self.context_index]; + + let surface_tex = unsafe { + self.surface + .acquire_texture(None, &ctx.fence) + .unwrap() + .texture + }; + + let target_barrier0 = hal::TextureBarrier { + texture: surface_tex.borrow(), + range: wgpu_types::ImageSubresourceRange::default(), + usage: hal::StateTransition { + from: wgpu_types::TextureUses::UNINITIALIZED, + to: wgpu_types::TextureUses::COLOR_TARGET, + }, + }; + unsafe { + ctx.encoder.begin_encoding(Some("frame")).unwrap(); + ctx.encoder.transition_textures(iter::once(target_barrier0)); + } + + let surface_view_desc = hal::TextureViewDescriptor { + label: None, + format: self.surface_format, + dimension: wgpu_types::TextureViewDimension::D2, + usage: wgpu_types::TextureUses::COLOR_TARGET, + range: wgpu_types::ImageSubresourceRange::default(), + }; + let surface_tex_view = unsafe { + self.device + .create_texture_view(surface_tex.borrow(), &surface_view_desc) + .unwrap() + }; + let pass_desc = hal::RenderPassDescriptor { + label: None, + extent: wgpu_types::Extent3d { + width: self.extent[0], + height: self.extent[1], + depth_or_array_layers: 1, + }, + sample_count: 1, + color_attachments: &[Some(hal::ColorAttachment { + target: hal::Attachment { + view: &surface_tex_view, + usage: wgpu_types::TextureUses::COLOR_TARGET, + }, + depth_slice: None, + resolve_target: None, + ops: hal::AttachmentOps::STORE | hal::AttachmentOps::LOAD_CLEAR, + clear_value: wgpu_types::Color { + r: 0.1, + g: 0.2, + b: 0.3, + a: 1.0, + }, + })], + depth_stencil_attachment: None, + multiview_mask: None, + timestamp_writes: None, + occlusion_query_set: None, + }; + unsafe { + ctx.encoder.begin_render_pass(&pass_desc).unwrap(); + ctx.encoder.set_render_pipeline(&self.pipeline); + ctx.encoder + .set_bind_group(&self.pipeline_layout, 0, &self.global_group, &[]); + } + + for i in 0..self.bunnies.len() { + let offset = (i as wgpu_types::DynamicOffset) + * (self.local_alignment as wgpu_types::DynamicOffset); + unsafe { + ctx.encoder + .set_bind_group(&self.pipeline_layout, 1, &self.local_group, &[offset]); + ctx.encoder.draw(0, 4, 0, 1); + } + } + + ctx.frames_recorded += 1; + + let target_barrier1 = hal::TextureBarrier { + texture: surface_tex.borrow(), + range: wgpu_types::ImageSubresourceRange::default(), + usage: hal::StateTransition { + from: wgpu_types::TextureUses::COLOR_TARGET, + to: wgpu_types::TextureUses::PRESENT, + }, + }; + unsafe { + ctx.encoder.end_render_pass(); + ctx.encoder.transition_textures(iter::once(target_barrier1)); + } + + unsafe { + let cmd_buf = ctx.encoder.end_encoding().unwrap(); + self.queue + .submit( + &[&cmd_buf], + &[&surface_tex], + (&mut ctx.fence, ctx.fence_value), + ) + .unwrap(); + self.queue.present(&self.surface, surface_tex).unwrap(); + ctx.used_cmd_bufs.push(cmd_buf); + ctx.used_views.push(surface_tex_view); + }; + + log::debug!("Context switch from {}", self.context_index); + let old_fence_value = ctx.fence_value; + if self.contexts.len() == 1 { + let hal_desc = hal::CommandEncoderDescriptor { + label: None, + queue: &self.queue, + }; + self.contexts.push(unsafe { + ExecutionContext { + encoder: self.device.create_command_encoder(&hal_desc).unwrap(), + fence: self.device.create_fence().unwrap(), + fence_value: 0, + used_views: Vec::new(), + used_cmd_bufs: Vec::new(), + frames_recorded: 0, + } + }); + } + self.context_index = (self.context_index + 1) % self.contexts.len(); + let next = &mut self.contexts[self.context_index]; + unsafe { + next.wait_and_clear(&self.device); + } + next.fence_value = old_fence_value + 1; + } +} + +cfg_if::cfg_if! { + // Apple + Metal + if #[cfg(all(target_vendor = "apple", feature = "metal"))] { + type Api = hal::api::Metal; + } + // Wasm + Vulkan + else if #[cfg(all(not(target_arch = "wasm32"), feature = "vulkan"))] { + type Api = hal::api::Vulkan; + } + // Windows + DX12 + else if #[cfg(all(windows, feature = "dx12"))] { + type Api = hal::api::Dx12; + } + // Anything + GLES + else if #[cfg(feature = "gles")] { + type Api = hal::api::Gles; + } + // Fallback + else { + type Api = hal::api::Noop; + } +} + +struct App { + example: Option<Example<Api>>, + window: Option<Window>, + last_frame_inst: Instant, + frame_count: u32, + accum_time: f32, +} + +impl ApplicationHandler for App { + fn resumed(&mut self, event_loop: &ActiveEventLoop) { + if self.window.is_some() { + return; + } + let window = event_loop + .create_window(Window::default_attributes().with_title("hal-bunnymark")) + .unwrap(); + let example = Example::<Api>::init(&window).expect("Selected backend is not supported"); + self.window = Some(window); + self.example = Some(example); + println!("Press space to spawn bunnies."); + self.window.as_ref().unwrap().request_redraw(); + } + + fn exiting(&mut self, _event_loop: &ActiveEventLoop) { + self.example.take().unwrap().exit(); + } + + fn window_event( + &mut self, + event_loop: &ActiveEventLoop, + _window_id: winit::window::WindowId, + event: WindowEvent, + ) { + event_loop.set_control_flow(ControlFlow::Poll); + + match event { + WindowEvent::KeyboardInput { + event: + KeyEvent { + logical_key: Key::Named(NamedKey::Escape), + state: ElementState::Pressed, + .. + }, + .. + } + | WindowEvent::CloseRequested => event_loop.exit(), + WindowEvent::RedrawRequested => { + let ex = self.example.as_mut().unwrap(); + { + self.accum_time += self.last_frame_inst.elapsed().as_secs_f32(); + self.last_frame_inst = Instant::now(); + self.frame_count += 1; + if self.frame_count == 100 && !ex.is_empty() { + println!( + "Avg frame time {}ms", + self.accum_time * 1000.0 / self.frame_count as f32 + ); + self.accum_time = 0.0; + self.frame_count = 0; + } + } + ex.render(); + self.window.as_ref().unwrap().request_redraw(); + } + _ => { + self.example.as_mut().unwrap().update(event); + } + } + } +} + +fn main() { + env_logger::init(); + + let event_loop = winit::event_loop::EventLoop::new().unwrap(); + let mut app = App { + example: None, + window: None, + last_frame_inst: Instant::now(), + frame_count: 0, + accum_time: 0.0, + }; + event_loop.run_app(&mut app).unwrap(); +} diff --git a/app/vendor/rune/vendor/wgpu-hal/examples/halmark/shader.wgsl b/app/vendor/rune/vendor/wgpu-hal/examples/halmark/shader.wgsl new file mode 100644 index 0000000..ffa7264 --- /dev/null +++ b/app/vendor/rune/vendor/wgpu-hal/examples/halmark/shader.wgsl @@ -0,0 +1,50 @@ +struct Globals { + mvp: mat4x4<f32>, + size: vec2<f32>, + _pad0: u32, + _pad1: u32, +}; + +struct Locals { + position: vec2<f32>, + velocity: vec2<f32>, + color: u32, + _pad0: u32, + _pad1: u32, + _pad2: u32, +}; + +@group(0) +@binding(0) +var<uniform> globals: Globals; + +@group(1) +@binding(0) +var<uniform> locals: Locals; + +struct VertexOutput { + @builtin(position) position: vec4<f32>, + @location(0) tex_coords: vec2<f32>, + @location(1) color: vec4<f32>, +}; + +@vertex +fn vs_main(@builtin(vertex_index) vi: u32) -> VertexOutput { + let tc = vec2<f32>(f32(vi & 1u), 0.5 * f32(vi & 2u)); + let offset = vec2<f32>(tc.x * globals.size.x, tc.y * globals.size.y); + let pos = globals.mvp * vec4<f32>(locals.position + offset, 0.0, 1.0); + let color = vec4<f32>((vec4<u32>(locals.color) >> vec4<u32>(0u, 8u, 16u, 24u)) & vec4<u32>(255u)) / 255.0; + return VertexOutput(pos, tc, color); +} + +@group(0) +@binding(1) +var tex: texture_2d<f32>; +@group(0) +@binding(2) +var sam: sampler; + +@fragment +fn fs_main(vertex: VertexOutput) -> @location(0) vec4<f32> { + return vertex.color * textureSampleLevel(tex, sam, vertex.tex_coords, 0.0); +} diff --git a/app/vendor/rune/vendor/wgpu-hal/examples/raw-gles.em.html b/app/vendor/rune/vendor/wgpu-hal/examples/raw-gles.em.html new file mode 100644 index 0000000..d25ca31 --- /dev/null +++ b/app/vendor/rune/vendor/wgpu-hal/examples/raw-gles.em.html @@ -0,0 +1,20 @@ +<html> + <head> + <meta charset="UTF-8" /> + <meta name="viewport" content="width=device-width, initial-scale=1.0" /> + </head> + <body> + <canvas id="canvas" width="640" height="400"></canvas> + <script> + var Module = { + canvas: document.getElementById("canvas"), + preRun: [ + function () { + ENV.RUST_LOG = "debug"; + }, + ], + }; + </script> + <script src="raw-gles.js"></script> + </body> +</html> diff --git a/app/vendor/rune/vendor/wgpu-hal/examples/raw-gles.rs b/app/vendor/rune/vendor/wgpu-hal/examples/raw-gles.rs new file mode 100644 index 0000000..b32398c --- /dev/null +++ b/app/vendor/rune/vendor/wgpu-hal/examples/raw-gles.rs @@ -0,0 +1,396 @@ +//! This example shows interop with raw GLES contexts - +//! the ability to hook up wgpu-hal to an existing context and draw into it. +//! +//! Emscripten build: +//! 1. install emsdk +//! 2. build this example with cargo: +//! EMCC_CFLAGS="-g -s ERROR_ON_UNDEFINED_SYMBOLS=0 --no-entry -s FULL_ES3=1" cargo build --example raw-gles --target wasm32-unknown-emscripten +//! 3. copy raw-gles.em.html into target directory and open it in browser: +//! cp wgpu-hal/examples/raw-gles.em.html target/wasm32-unknown-emscripten/debug/examples + +extern crate wgpu_hal as hal; + +#[cfg(not(any( + target_arch = "wasm32", + target_os = "ios", + target_os = "visionos", + target_env = "ohos" +)))] +fn main() { + use std::ffi::CString; + + use glutin::{ + config::GlConfig as _, + context::{NotCurrentGlContext as _, PossiblyCurrentGlContext as _, Version}, + display::{GetGlDisplay as _, GlDisplay as _}, + surface::GlSurface as _, + }; + use glutin_winit::GlWindow as _; + use raw_window_handle::HasWindowHandle as _; + use winit::{ + application::ApplicationHandler, + event::{KeyEvent, WindowEvent}, + event_loop::{ActiveEventLoop, ControlFlow, EventLoop}, + keyboard::{Key, NamedKey}, + window::Window, + }; + + env_logger::init(); + println!("Initializing external GL context"); + + /// Find the config with the maximum number of samples, so our triangle will be + /// smooth. + fn gl_config_picker( + configs: Box<dyn Iterator<Item = glutin::config::Config> + '_>, + ) -> glutin::config::Config { + configs + .reduce(|accum, config| { + if config.num_samples() > accum.num_samples() { + config + } else { + accum + } + }) + .expect("Failed to find a matching config") + } + + struct App { + gl_config: Option<glutin::config::Config>, + not_current_gl_context: Option<glutin::context::NotCurrentContext>, + state: Option<( + glutin::context::PossiblyCurrentContext, + glutin::surface::Surface<glutin::surface::WindowSurface>, + Window, + )>, + exposed: Option<hal::ExposedAdapter<hal::api::Gles>>, + } + + impl App { + fn new() -> Self { + Self { + gl_config: None, + not_current_gl_context: None, + state: None, + exposed: None, + } + } + } + + impl ApplicationHandler for App { + fn resumed(&mut self, event_loop: &ActiveEventLoop) { + // First call: create display, pick config, create GL context. + if self.gl_config.is_none() { + // Only Windows requires the window to be present before creating the display. + // Other platforms don't really need one. + let window_attributes = cfg!(windows).then(|| { + Window::default_attributes() + .with_title("wgpu raw GLES example (press Escape to exit)") + }); + + let template = glutin::config::ConfigTemplateBuilder::new(); + + let display_builder = + glutin_winit::DisplayBuilder::new().with_window_attributes(window_attributes); + + let (window, gl_config) = display_builder + .build(event_loop, template, gl_config_picker) + .expect("Failed to build window and config from display"); + + println!("Picked a config with {} samples", gl_config.num_samples()); + + let raw_window_handle = window + .as_ref() + .and_then(|window| window.window_handle().ok()) + .map(|handle| handle.as_raw()); + + let gl_display = gl_config.display(); + + // Glutin tries to create an OpenGL context by default. + // Force it to use any version of GLES. + let context_attributes = glutin::context::ContextAttributesBuilder::new() + // wgpu expects GLES 3.0+. + .with_context_api(glutin::context::ContextApi::Gles(Some(Version::new(3, 0)))) + .build(raw_window_handle); + + let gl_context = unsafe { + gl_display + .create_context(&gl_config, &context_attributes) + .expect("failed to create context") + }; + + self.not_current_gl_context = Some(gl_context); + self.gl_config = Some(gl_config); + + // On Windows, the window was already created by DisplayBuilder. + if let Some(window) = window { + self.create_surface(event_loop, window); + return; + } + } + + // Create window + surface (non-Windows first call, or Android re-resume). + if self.state.is_none() { + let gl_config = self.gl_config.as_ref().unwrap(); + let window = glutin_winit::finalize_window( + event_loop, + Window::default_attributes() + .with_title("wgpu raw GLES example (press Escape to exit)"), + gl_config, + ) + .unwrap(); + self.create_surface(event_loop, window); + } + } + + fn suspended(&mut self, _event_loop: &ActiveEventLoop) { + // This event is only raised on Android, where the backing NativeWindow for a GL + // Surface can appear and disappear at any moment. + println!("Android window removed"); + + // Destroy the GL Surface and un-current the GL Context before ndk-glue releases + // the window back to the system. + if let Some((gl_context, ..)) = self.state.take() { + assert!(self + .not_current_gl_context + .replace(gl_context.make_not_current().unwrap()) + .is_none()); + } + } + + fn window_event( + &mut self, + event_loop: &ActiveEventLoop, + _window_id: winit::window::WindowId, + event: WindowEvent, + ) { + event_loop.set_control_flow(ControlFlow::Wait); + + match event { + WindowEvent::CloseRequested + | WindowEvent::KeyboardInput { + event: + KeyEvent { + logical_key: Key::Named(NamedKey::Escape), + .. + }, + .. + } => event_loop.exit(), + WindowEvent::Resized(size) => { + if size.width != 0 && size.height != 0 { + // Some platforms like EGL require resizing GL surface to update the size. + // Notable platforms here are Wayland and macOS, other don't require it + // and the function is no-op, but it's wise to resize it for portability + // reasons. + if let Some((gl_context, gl_surface, window)) = &self.state { + window.resize_surface(gl_surface, gl_context); + } + } + } + WindowEvent::RedrawRequested => { + if let (Some(exposed), Some((gl_context, gl_surface, window))) = + (&self.exposed, &self.state) + { + let inner_size = window.inner_size(); + + fill_screen(exposed, inner_size.width, inner_size.height); + + println!("Showing the window"); + gl_surface + .swap_buffers(gl_context) + .expect("Failed to swap buffers"); + } + } + _ => (), + } + } + } + + impl App { + fn create_surface(&mut self, _event_loop: &ActiveEventLoop, window: Window) { + let gl_config = self.gl_config.as_ref().unwrap(); + + let attrs = window + .build_surface_attributes(Default::default()) + .expect("Failed to build surface attributes"); + let gl_surface = unsafe { + gl_config + .display() + .create_window_surface(gl_config, &attrs) + .expect("Cannot create GL WindowSurface") + }; + + // Make it current. + let gl_context = self + .not_current_gl_context + .take() + .unwrap() + .make_current(&gl_surface) + .expect("GL context cannot be made current with WindowSurface"); + + // The context needs to be current for the Renderer to set up shaders and + // buffers. It also performs function loading, which needs a current context on + // WGL. + println!("Hooking up to wgpu-hal"); + self.exposed.get_or_insert_with(|| { + unsafe { + <hal::api::Gles as hal::Api>::Adapter::new_external( + |name| { + // XXX: On WGL this should only be called after the context was + // made current + gl_config + .display() + .get_proc_address(&CString::new(name).expect(name)) + }, + wgpu_types::GlBackendOptions::default(), + ) + } + .expect("GL adapter can't be initialized") + }); + + window.request_redraw(); + self.state = Some((gl_context, gl_surface, window)); + } + } + + let event_loop = EventLoop::new().unwrap(); + let mut app = App::new(); + event_loop + .run_app(&mut app) + .expect("Couldn't run event loop"); +} + +#[cfg(target_os = "emscripten")] +fn main() { + env_logger::init(); + + println!("Initializing external GL context"); + let egl = khronos_egl::Instance::new(khronos_egl::Static); + let display = unsafe { egl.get_display(khronos_egl::DEFAULT_DISPLAY) }.unwrap(); + egl.initialize(display) + .expect("unable to initialize display"); + + let attributes = [ + khronos_egl::RED_SIZE, + 8, + khronos_egl::GREEN_SIZE, + 8, + khronos_egl::BLUE_SIZE, + 8, + khronos_egl::NONE, + ]; + + let config = egl + .choose_first_config(display, &attributes) + .unwrap() + .expect("unable to choose config"); + let surface = unsafe { + let window = std::ptr::null_mut::<std::ffi::c_void>(); + egl.create_window_surface(display, config, window, None) + } + .expect("unable to create surface"); + + let context_attributes = [khronos_egl::CONTEXT_CLIENT_VERSION, 3, khronos_egl::NONE]; + + let gl_context = egl + .create_context(display, config, None, &context_attributes) + .expect("unable to create context"); + egl.make_current(display, Some(surface), Some(surface), Some(gl_context)) + .expect("can't make context current"); + + println!("Hooking up to wgpu-hal"); + let exposed = unsafe { + <hal::api::Gles as hal::Api>::Adapter::new_external(|name| { + egl.get_proc_address(name) + .map_or(std::ptr::null(), |p| p as *const _) + }) + } + .expect("GL adapter can't be initialized"); + + fill_screen(&exposed, 640, 400); +} + +#[cfg(any( + all(target_arch = "wasm32", not(target_os = "emscripten")), + target_os = "ios", + target_os = "visionos", + target_env = "ohos" +))] +fn main() { + eprintln!("This example is not supported on this platform") +} + +#[cfg(not(any( + all(target_arch = "wasm32", not(target_os = "emscripten")), + target_os = "ios", + target_os = "visionos" +)))] +fn fill_screen(exposed: &hal::ExposedAdapter<hal::api::Gles>, width: u32, height: u32) { + use hal::{Adapter as _, CommandEncoder as _, Device as _, Queue as _}; + + let od = unsafe { + exposed.adapter.open( + wgpu_types::Features::empty(), + &wgpu_types::Limits::downlevel_defaults(), + &wgpu_types::MemoryHints::default(), + ) + } + .unwrap(); + + let format = wgpu_types::TextureFormat::Rgba8UnormSrgb; + let texture = <hal::api::Gles as hal::Api>::Texture::default_framebuffer(format); + let view = unsafe { + od.device + .create_texture_view( + &texture, + &hal::TextureViewDescriptor { + label: None, + format, + dimension: wgpu_types::TextureViewDimension::D2, + usage: wgpu_types::TextureUses::COLOR_TARGET, + range: wgpu_types::ImageSubresourceRange::default(), + }, + ) + .unwrap() + }; + + println!("Filling the screen"); + let mut encoder = unsafe { + od.device + .create_command_encoder(&hal::CommandEncoderDescriptor { + label: None, + queue: &od.queue, + }) + .unwrap() + }; + let mut fence = unsafe { od.device.create_fence().unwrap() }; + let rp_desc = hal::RenderPassDescriptor { + label: None, + extent: wgpu_types::Extent3d { + width, + height, + depth_or_array_layers: 1, + }, + sample_count: 1, + color_attachments: &[Some(hal::ColorAttachment { + target: hal::Attachment { + view: &view, + usage: wgpu_types::TextureUses::COLOR_TARGET, + }, + depth_slice: None, + resolve_target: None, + ops: hal::AttachmentOps::STORE | hal::AttachmentOps::LOAD_CLEAR, + clear_value: wgpu_types::Color::BLUE, + })], + depth_stencil_attachment: None, + multiview_mask: None, + timestamp_writes: None, + occlusion_query_set: None, + }; + unsafe { + encoder.begin_encoding(None).unwrap(); + encoder.begin_render_pass(&rp_desc).unwrap(); + encoder.end_render_pass(); + let cmd_buf = encoder.end_encoding().unwrap(); + od.queue.submit(&[&cmd_buf], &[], (&mut fence, 0)).unwrap(); + } +} diff --git a/app/vendor/rune/vendor/wgpu-hal/examples/ray-traced-triangle/main.rs b/app/vendor/rune/vendor/wgpu-hal/examples/ray-traced-triangle/main.rs new file mode 100644 index 0000000..b0f940e --- /dev/null +++ b/app/vendor/rune/vendor/wgpu-hal/examples/ray-traced-triangle/main.rs @@ -0,0 +1,1225 @@ +extern crate wgpu_hal as hal; + +use hal::{ + Adapter as _, CommandEncoder as _, Device as _, Instance as _, Queue as _, Surface as _, +}; +use raw_window_handle::{HasDisplayHandle, HasWindowHandle}; + +use glam::{Affine3A, Mat4, Vec3}; +use std::{ + borrow::{Borrow, Cow}, + iter, ptr, + time::Instant, +}; +use wgpu_types::Dx12BackendOptions; +use winit::{ + application::ApplicationHandler, + event_loop::{ActiveEventLoop, ControlFlow}, + window::{Window, WindowButtons}, +}; + +const DESIRED_MAX_LATENCY: u32 = 2; + +/// [D3D12_RAYTRACING_INSTANCE_DESC](https://microsoft.github.io/DirectX-Specs/d3d/Raytracing.html#d3d12_raytracing_instance_desc) +/// [VkAccelerationStructureInstanceKHR](https://registry.khronos.org/vulkan/specs/1.3-extensions/man/html/VkAccelerationStructureInstanceKHR.html) +#[derive(Clone)] +#[repr(C)] +struct AccelerationStructureInstance { + transform: [f32; 12], + custom_index_and_mask: u32, + shader_binding_table_record_offset_and_flags: u32, + acceleration_structure_reference: u64, +} + +impl std::fmt::Debug for AccelerationStructureInstance { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("Instance") + .field("transform", &self.transform) + .field("custom_data()", &self.custom_index()) + .field("mask()", &self.mask()) + .field( + "shader_binding_table_record_offset()", + &self.shader_binding_table_record_offset(), + ) + .field("flags()", &self.flags()) + .field( + "acceleration_structure_reference", + &self.acceleration_structure_reference, + ) + .finish() + } +} + +#[allow(dead_code)] +impl AccelerationStructureInstance { + const LOW_24_MASK: u32 = 0x00ff_ffff; + const MAX_U24: u32 = (1u32 << 24u32) - 1u32; + + #[inline] + fn affine_to_rows(mat: &Affine3A) -> [f32; 12] { + let row_0 = mat.matrix3.row(0); + let row_1 = mat.matrix3.row(1); + let row_2 = mat.matrix3.row(2); + let translation = mat.translation; + [ + row_0.x, + row_0.y, + row_0.z, + translation.x, + row_1.x, + row_1.y, + row_1.z, + translation.y, + row_2.x, + row_2.y, + row_2.z, + translation.z, + ] + } + + #[inline] + fn rows_to_affine(rows: &[f32; 12]) -> Affine3A { + Affine3A::from_cols_array(&[ + rows[0], rows[3], rows[6], rows[9], rows[1], rows[4], rows[7], rows[10], rows[2], + rows[5], rows[8], rows[11], + ]) + } + + pub fn transform_as_affine(&self) -> Affine3A { + Self::rows_to_affine(&self.transform) + } + pub fn set_transform(&mut self, transform: &Affine3A) { + self.transform = Self::affine_to_rows(transform); + } + + pub fn custom_index(&self) -> u32 { + self.custom_index_and_mask & Self::LOW_24_MASK + } + + pub fn mask(&self) -> u8 { + (self.custom_index_and_mask >> 24) as u8 + } + + pub fn shader_binding_table_record_offset(&self) -> u32 { + self.shader_binding_table_record_offset_and_flags & Self::LOW_24_MASK + } + + pub fn flags(&self) -> u8 { + (self.shader_binding_table_record_offset_and_flags >> 24) as u8 + } + + pub fn set_custom_index(&mut self, custom_index: u32) { + debug_assert!( + custom_index <= Self::MAX_U24, + "custom_index uses more than 24 bits! {custom_index} > {}", + Self::MAX_U24 + ); + self.custom_index_and_mask = + (custom_index & Self::LOW_24_MASK) | (self.custom_index_and_mask & !Self::LOW_24_MASK) + } + + pub fn set_mask(&mut self, mask: u8) { + self.custom_index_and_mask = + (self.custom_index_and_mask & Self::LOW_24_MASK) | (u32::from(mask) << 24) + } + + pub fn set_shader_binding_table_record_offset( + &mut self, + shader_binding_table_record_offset: u32, + ) { + debug_assert!( + shader_binding_table_record_offset <= Self::MAX_U24, + "shader_binding_table_record_offset uses more than 24 bits! {} > {}", + shader_binding_table_record_offset, + Self::MAX_U24 + ); + self.shader_binding_table_record_offset_and_flags = (shader_binding_table_record_offset + & Self::LOW_24_MASK) + | (self.shader_binding_table_record_offset_and_flags & !Self::LOW_24_MASK) + } + + pub fn set_flags(&mut self, flags: u8) { + self.shader_binding_table_record_offset_and_flags = + (self.shader_binding_table_record_offset_and_flags & Self::LOW_24_MASK) + | (u32::from(flags) << 24) + } + + pub fn new( + transform: &Affine3A, + custom_index: u32, + mask: u8, + shader_binding_table_record_offset: u32, + flags: u8, + acceleration_structure_reference: u64, + ) -> Self { + debug_assert!( + custom_index <= Self::MAX_U24, + "custom_index uses more than 24 bits! {custom_index} > {}", + Self::MAX_U24 + ); + debug_assert!( + shader_binding_table_record_offset <= Self::MAX_U24, + "shader_binding_table_record_offset uses more than 24 bits! {} > {}", + shader_binding_table_record_offset, + Self::MAX_U24 + ); + AccelerationStructureInstance { + transform: Self::affine_to_rows(transform), + custom_index_and_mask: (custom_index & Self::MAX_U24) | (u32::from(mask) << 24), + shader_binding_table_record_offset_and_flags: (shader_binding_table_record_offset + & Self::MAX_U24) + | (u32::from(flags) << 24), + acceleration_structure_reference, + } + } +} + +struct ExecutionContext<A: hal::Api> { + encoder: A::CommandEncoder, + fence: A::Fence, + fence_value: hal::FenceValue, + used_views: Vec<A::TextureView>, + used_cmd_bufs: Vec<A::CommandBuffer>, + frames_recorded: usize, +} + +impl<A: hal::Api> ExecutionContext<A> { + unsafe fn wait_and_clear(&mut self, device: &A::Device) { + device.wait(&self.fence, self.fence_value, None).unwrap(); + self.encoder.reset_all(self.used_cmd_bufs.drain(..)); + for view in self.used_views.drain(..) { + device.destroy_texture_view(view); + } + self.frames_recorded = 0; + } +} + +#[allow(dead_code)] +struct Example<A: hal::Api> { + instance: A::Instance, + adapter: A::Adapter, + surface: A::Surface, + surface_format: wgpu_types::TextureFormat, + device: A::Device, + queue: A::Queue, + + contexts: Vec<ExecutionContext<A>>, + context_index: usize, + extent: [u32; 2], + start: Instant, + pipeline: A::ComputePipeline, + bind_group: A::BindGroup, + bgl: A::BindGroupLayout, + shader_module: A::ShaderModule, + texture_view: A::TextureView, + uniform_buffer: A::Buffer, + pipeline_layout: A::PipelineLayout, + vertices_buffer: A::Buffer, + indices_buffer: Option<A::Buffer>, + texture: A::Texture, + instances: [AccelerationStructureInstance; 3], + instances_buffer: A::Buffer, + blas: A::AccelerationStructure, + tlas: A::AccelerationStructure, + scratch_buffer: A::Buffer, + time: f32, +} + +impl<A: hal::Api> Example<A> { + fn init(window: &winit::window::Window) -> Result<Self, Box<dyn std::error::Error>> { + let mut index_buffer = false; + + for arg in std::env::args() { + if arg == "index_buffer" { + index_buffer = true; + } + } + + if index_buffer { + log::info!("using index buffer") + } + + // The Instance can be initialized with the DisplayHandle from the EventLoop as well + let raw_display_handle = window.display_handle()?; + + let instance_desc = hal::InstanceDescriptor { + name: "example", + flags: wgpu_types::InstanceFlags::default(), + memory_budget_thresholds: wgpu_types::MemoryBudgetThresholds::default(), + backend_options: wgpu_types::BackendOptions { + dx12: Dx12BackendOptions { + shader_compiler: wgpu_types::Dx12Compiler::default_dynamic_dxc(), + ..Default::default() + }, + ..Default::default() + }, + telemetry: None, + display: Some(raw_display_handle), + }; + let instance = unsafe { A::Instance::init(&instance_desc)? }; + let surface = { + let raw_window_handle = window.window_handle()?.as_raw(); + + unsafe { + instance + .create_surface(raw_display_handle.as_raw(), raw_window_handle) + .unwrap() + } + }; + + let (adapter, features) = unsafe { + let mut adapters = instance.enumerate_adapters(Some(&surface)); + if adapters.is_empty() { + panic!("No adapters found"); + } + let exposed = adapters.swap_remove(0); + dbg!(exposed.features); + (exposed.adapter, exposed.features) + }; + let surface_caps = unsafe { adapter.surface_capabilities(&surface) } + .expect("Surface doesn't support presentation"); + log::info!("Surface caps: {surface_caps:#?}"); + + let hal::OpenDevice { device, queue } = unsafe { + adapter + .open( + features, + &wgpu_types::Limits::default(), + &wgpu_types::MemoryHints::Performance, + ) + .unwrap() + }; + + let window_size: (u32, u32) = window.inner_size().into(); + dbg!(&surface_caps.formats); + let surface_format = if surface_caps + .formats + .iter() + .any(|fc| fc.format == wgpu_types::TextureFormat::Rgba8Unorm) + { + wgpu_types::TextureFormat::Rgba8Unorm + } else { + surface_caps.formats.first().unwrap().format + }; + let surface_config = hal::SurfaceConfiguration { + maximum_frame_latency: DESIRED_MAX_LATENCY + .max(*surface_caps.maximum_frame_latency.start()) + .min(*surface_caps.maximum_frame_latency.end()), + present_mode: wgpu_types::PresentMode::Fifo, + composite_alpha_mode: wgpu_types::CompositeAlphaMode::Opaque, + format: surface_format, + color_space: wgpu_types::SurfaceColorSpace::Srgb, + extent: wgpu_types::Extent3d { + width: window_size.0, + height: window_size.1, + depth_or_array_layers: 1, + }, + usage: wgpu_types::TextureUses::COLOR_TARGET | wgpu_types::TextureUses::COPY_DST, + view_formats: vec![surface_format], + }; + unsafe { + surface.configure(&device, &surface_config).unwrap(); + }; + + #[allow(dead_code)] + struct Uniforms { + view_inverse: glam::Mat4, + proj_inverse: glam::Mat4, + } + + let bgl_desc = hal::BindGroupLayoutDescriptor { + label: None, + flags: hal::BindGroupLayoutFlags::empty(), + entries: &[ + wgpu_types::BindGroupLayoutEntry { + binding: 0, + visibility: wgpu_types::ShaderStages::COMPUTE, + ty: wgpu_types::BindingType::Buffer { + ty: wgpu_types::BufferBindingType::Uniform, + has_dynamic_offset: false, + min_binding_size: wgpu_types::BufferSize::new(size_of::<Uniforms>() as _), + }, + count: None, + }, + wgpu_types::BindGroupLayoutEntry { + binding: 1, + visibility: wgpu_types::ShaderStages::COMPUTE, + ty: wgpu_types::BindingType::StorageTexture { + access: wgpu_types::StorageTextureAccess::WriteOnly, + format: wgpu_types::TextureFormat::Rgba8Unorm, + view_dimension: wgpu_types::TextureViewDimension::D2, + }, + count: None, + }, + wgpu_types::BindGroupLayoutEntry { + binding: 2, + visibility: wgpu_types::ShaderStages::COMPUTE, + ty: wgpu_types::BindingType::AccelerationStructure { + vertex_return: false, + }, + count: None, + }, + ], + }; + + let bgl = unsafe { device.create_bind_group_layout(&bgl_desc).unwrap() }; + + let naga_shader = { + let shader_file = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("examples") + .join("ray-traced-triangle") + .join("shader.wgsl"); + let source = std::fs::read_to_string(shader_file).unwrap(); + let module = naga::front::wgsl::Frontend::new().parse(&source).unwrap(); + let info = naga::valid::Validator::new( + naga::valid::ValidationFlags::all(), + naga::valid::Capabilities::RAY_QUERY, + ) + .validate(&module) + .unwrap(); + hal::NagaShader { + module: Cow::Owned(module), + info, + debug_source: None, + } + }; + let shader_desc = hal::ShaderModuleDescriptor { + label: None, + runtime_checks: wgpu_types::ShaderRuntimeChecks::checked(), + }; + let shader_module = unsafe { + device + .create_shader_module(&shader_desc, hal::ShaderInput::Naga(naga_shader)) + .unwrap() + }; + + let pipeline_layout_desc = hal::PipelineLayoutDescriptor { + label: None, + flags: hal::PipelineLayoutFlags::empty(), + bind_group_layouts: &[Some(&bgl)], + immediate_size: 0, + }; + let pipeline_layout = unsafe { + device + .create_pipeline_layout(&pipeline_layout_desc) + .unwrap() + }; + + let pipeline = unsafe { + device.create_compute_pipeline(&hal::ComputePipelineDescriptor { + label: Some("pipeline"), + layout: &pipeline_layout, + stage: hal::ProgrammableStage { + module: &shader_module, + entry_point: "main", + constants: &Default::default(), + zero_initialize_workgroup_memory: true, + }, + cache: None, + }) + } + .unwrap(); + + let vertices: [f32; 9] = [1.0, 1.0, 0.0, -1.0, 1.0, 0.0, 0.0, -1.0, 0.0]; + + let vertices_size_in_bytes = vertices.len() * 4; + + let indices: [u32; 3] = [0, 1, 2]; + + let indices_size_in_bytes = indices.len() * 4; + + let vertices_buffer = unsafe { + let vertices_buffer = device + .create_buffer(&hal::BufferDescriptor { + label: Some("vertices buffer"), + size: vertices_size_in_bytes as u64, + usage: wgpu_types::BufferUses::MAP_WRITE + | wgpu_types::BufferUses::BOTTOM_LEVEL_ACCELERATION_STRUCTURE_INPUT, + memory_flags: hal::MemoryFlags::TRANSIENT | hal::MemoryFlags::PREFER_COHERENT, + }) + .unwrap(); + + let mapping = device + .map_buffer(&vertices_buffer, 0..vertices_size_in_bytes as u64) + .unwrap(); + ptr::copy_nonoverlapping( + vertices.as_ptr() as *const u8, + mapping.ptr.as_ptr(), + vertices_size_in_bytes, + ); + device.unmap_buffer(&vertices_buffer); + assert!(mapping.is_coherent); + + vertices_buffer + }; + + let indices_buffer = if index_buffer { + unsafe { + let indices_buffer = device + .create_buffer(&hal::BufferDescriptor { + label: Some("indices buffer"), + size: indices_size_in_bytes as u64, + usage: wgpu_types::BufferUses::MAP_WRITE + | wgpu_types::BufferUses::BOTTOM_LEVEL_ACCELERATION_STRUCTURE_INPUT, + memory_flags: hal::MemoryFlags::TRANSIENT + | hal::MemoryFlags::PREFER_COHERENT, + }) + .unwrap(); + + let mapping = device + .map_buffer(&indices_buffer, 0..indices_size_in_bytes as u64) + .unwrap(); + ptr::copy_nonoverlapping( + indices.as_ptr() as *const u8, + mapping.ptr.as_ptr(), + indices_size_in_bytes, + ); + device.unmap_buffer(&indices_buffer); + assert!(mapping.is_coherent); + + Some((indices_buffer, indices.len())) + } + } else { + None + }; + + let blas_triangles = vec![hal::AccelerationStructureTriangles { + vertex_buffer: Some(&vertices_buffer), + first_vertex: 0, + vertex_format: wgpu_types::VertexFormat::Float32x3, + // each vertex is 3 floats, and floats are stored raw in the array + vertex_count: vertices.len() as u32 / 3, + vertex_stride: 3 * 4, + indices: indices_buffer.as_ref().map(|(buf, len)| { + hal::AccelerationStructureTriangleIndices { + buffer: Some(buf), + format: wgpu_types::IndexFormat::Uint32, + offset: 0, + count: *len as u32, + } + }), + + transform: None, + flags: hal::AccelerationStructureGeometryFlags::OPAQUE, + }]; + let blas_entries = hal::AccelerationStructureEntries::Triangles(blas_triangles); + + let blas_sizes = unsafe { + device.get_acceleration_structure_build_sizes( + &hal::GetAccelerationStructureBuildSizesDescriptor { + entries: &blas_entries, + flags: hal::AccelerationStructureBuildFlags::PREFER_FAST_TRACE, + }, + ) + }; + + let blas = unsafe { + device.create_acceleration_structure(&hal::AccelerationStructureDescriptor { + label: Some("blas"), + size: blas_sizes.acceleration_structure_size, + format: hal::AccelerationStructureFormat::BottomLevel, + allow_compaction: false, + }) + } + .unwrap(); + + let instances = [ + AccelerationStructureInstance::new( + &Affine3A::from_translation(Vec3 { + x: 0.0, + y: 0.0, + z: 0.0, + }), + 0, + 0xff, + 0, + 0, + unsafe { device.get_acceleration_structure_device_address(&blas) }, + ), + AccelerationStructureInstance::new( + &Affine3A::from_translation(Vec3 { + x: -1.0, + y: -1.0, + z: -2.0, + }), + 0, + 0xff, + 0, + 0, + unsafe { device.get_acceleration_structure_device_address(&blas) }, + ), + AccelerationStructureInstance::new( + &Affine3A::from_translation(Vec3 { + x: 1.0, + y: -1.0, + z: -2.0, + }), + 0, + 0xff, + 0, + 0, + unsafe { device.get_acceleration_structure_device_address(&blas) }, + ), + ]; + + let instances_buffer_size = instances.len() * size_of::<AccelerationStructureInstance>(); + + let instances_buffer = unsafe { + let instances_buffer = device + .create_buffer(&hal::BufferDescriptor { + label: Some("instances_buffer"), + size: instances_buffer_size as u64, + usage: wgpu_types::BufferUses::MAP_WRITE + | wgpu_types::BufferUses::TOP_LEVEL_ACCELERATION_STRUCTURE_INPUT, + memory_flags: hal::MemoryFlags::TRANSIENT | hal::MemoryFlags::PREFER_COHERENT, + }) + .unwrap(); + + let mapping = device + .map_buffer(&instances_buffer, 0..instances_buffer_size as u64) + .unwrap(); + ptr::copy_nonoverlapping( + instances.as_ptr() as *const u8, + mapping.ptr.as_ptr(), + instances_buffer_size, + ); + device.unmap_buffer(&instances_buffer); + assert!(mapping.is_coherent); + + instances_buffer + }; + + let mut tlas_entries = + hal::AccelerationStructureEntries::Instances(hal::AccelerationStructureInstances { + buffer: Some(&instances_buffer), + count: 3, + offset: 0, + }); + + let tlas_flags = hal::AccelerationStructureBuildFlags::PREFER_FAST_TRACE + | hal::AccelerationStructureBuildFlags::ALLOW_UPDATE; + + let tlas_sizes = unsafe { + device.get_acceleration_structure_build_sizes( + &hal::GetAccelerationStructureBuildSizesDescriptor { + entries: &tlas_entries, + flags: tlas_flags, + }, + ) + }; + + let tlas = unsafe { + device.create_acceleration_structure(&hal::AccelerationStructureDescriptor { + label: Some("tlas"), + size: tlas_sizes.acceleration_structure_size, + format: hal::AccelerationStructureFormat::TopLevel, + allow_compaction: false, + }) + } + .unwrap(); + + let uniforms = { + let view = Mat4::look_at_rh(Vec3::new(0.0, 0.0, 2.5), Vec3::ZERO, Vec3::Y); + let proj = Mat4::perspective_rh(59.0_f32.to_radians(), 1.0, 0.001, 1000.0); + + Uniforms { + view_inverse: view.inverse(), + proj_inverse: proj.inverse(), + } + }; + + let uniforms_size = size_of::<Uniforms>(); + + let uniform_buffer = unsafe { + let uniform_buffer = device + .create_buffer(&hal::BufferDescriptor { + label: Some("uniform buffer"), + size: uniforms_size as u64, + usage: wgpu_types::BufferUses::MAP_WRITE | wgpu_types::BufferUses::UNIFORM, + memory_flags: hal::MemoryFlags::PREFER_COHERENT, + }) + .unwrap(); + + let mapping = device + .map_buffer(&uniform_buffer, 0..uniforms_size as u64) + .unwrap(); + ptr::copy_nonoverlapping( + &uniforms as *const Uniforms as *const u8, + mapping.ptr.as_ptr(), + uniforms_size, + ); + device.unmap_buffer(&uniform_buffer); + assert!(mapping.is_coherent); + uniform_buffer + }; + + let texture_desc = hal::TextureDescriptor { + label: None, + size: wgpu_types::Extent3d { + width: 512, + height: 512, + depth_or_array_layers: 1, + }, + mip_level_count: 1, + sample_count: 1, + dimension: wgpu_types::TextureDimension::D2, + format: wgpu_types::TextureFormat::Rgba8Unorm, + usage: wgpu_types::TextureUses::STORAGE_READ_WRITE | wgpu_types::TextureUses::COPY_SRC, + memory_flags: hal::MemoryFlags::empty(), + view_formats: vec![wgpu_types::TextureFormat::Rgba8Unorm], + }; + let texture = unsafe { device.create_texture(&texture_desc).unwrap() }; + + let view_desc = hal::TextureViewDescriptor { + label: None, + format: texture_desc.format, + dimension: wgpu_types::TextureViewDimension::D2, + usage: wgpu_types::TextureUses::STORAGE_READ_WRITE | wgpu_types::TextureUses::COPY_SRC, + range: wgpu_types::ImageSubresourceRange::default(), + }; + let texture_view = unsafe { device.create_texture_view(&texture, &view_desc).unwrap() }; + + let bind_group = { + let buffer_binding = unsafe { + // SAFETY: The size matches the buffer allocation. + hal::BufferBinding::new_unchecked( + &uniform_buffer, + 0, + wgpu_types::BufferSize::new_unchecked(uniforms_size as u64), + ) + }; + let texture_binding = hal::TextureBinding { + view: &texture_view, + usage: wgpu_types::TextureUses::STORAGE_READ_WRITE, + }; + let group_desc = hal::BindGroupDescriptor { + label: Some("bind group"), + layout: &bgl, + buffers: &[buffer_binding], + samplers: &[], + textures: &[texture_binding], + acceleration_structures: &[&tlas], + external_textures: &[], + entries: &[ + hal::BindGroupEntry { + binding: 0, + resource_index: 0, + count: 1, + }, + hal::BindGroupEntry { + binding: 1, + resource_index: 0, + count: 1, + }, + hal::BindGroupEntry { + binding: 2, + resource_index: 0, + count: 1, + }, + ], + }; + unsafe { device.create_bind_group(&group_desc).unwrap() } + }; + + let scratch_buffer = unsafe { + device + .create_buffer(&hal::BufferDescriptor { + label: Some("scratch buffer"), + size: blas_sizes + .build_scratch_size + .max(tlas_sizes.build_scratch_size), + usage: wgpu_types::BufferUses::ACCELERATION_STRUCTURE_SCRATCH, + memory_flags: hal::MemoryFlags::empty(), + }) + .unwrap() + }; + + if let hal::AccelerationStructureEntries::Instances(ref mut i) = tlas_entries { + assert!( + instances.len() <= i.count as usize, + "Tlas allocation to small" + ); + } + + let cmd_encoder_desc = hal::CommandEncoderDescriptor { + label: None, + queue: &queue, + }; + let mut cmd_encoder = unsafe { device.create_command_encoder(&cmd_encoder_desc).unwrap() }; + + unsafe { cmd_encoder.begin_encoding(Some("init")).unwrap() }; + + unsafe { + cmd_encoder.place_acceleration_structure_barrier(hal::AccelerationStructureBarrier { + usage: hal::StateTransition { + from: hal::AccelerationStructureUses::empty(), + to: hal::AccelerationStructureUses::BUILD_OUTPUT, + }, + }); + + cmd_encoder.build_acceleration_structures( + 1, + [hal::BuildAccelerationStructureDescriptor { + mode: hal::AccelerationStructureBuildMode::Build, + flags: hal::AccelerationStructureBuildFlags::PREFER_FAST_TRACE, + destination_acceleration_structure: &blas, + scratch_buffer: &scratch_buffer, + entries: &blas_entries, + source_acceleration_structure: None, + scratch_buffer_offset: 0, + }], + ); + + let scratch_buffer_barrier = hal::BufferBarrier { + buffer: &scratch_buffer, + usage: hal::StateTransition { + from: wgpu_types::BufferUses::BOTTOM_LEVEL_ACCELERATION_STRUCTURE_INPUT, + to: wgpu_types::BufferUses::TOP_LEVEL_ACCELERATION_STRUCTURE_INPUT, + }, + }; + cmd_encoder.transition_buffers(iter::once(scratch_buffer_barrier)); + + cmd_encoder.place_acceleration_structure_barrier(hal::AccelerationStructureBarrier { + usage: hal::StateTransition { + from: hal::AccelerationStructureUses::BUILD_OUTPUT, + to: hal::AccelerationStructureUses::BUILD_INPUT, + }, + }); + + cmd_encoder.build_acceleration_structures( + 1, + [hal::BuildAccelerationStructureDescriptor { + mode: hal::AccelerationStructureBuildMode::Build, + flags: tlas_flags, + destination_acceleration_structure: &tlas, + scratch_buffer: &scratch_buffer, + entries: &tlas_entries, + source_acceleration_structure: None, + scratch_buffer_offset: 0, + }], + ); + + cmd_encoder.place_acceleration_structure_barrier(hal::AccelerationStructureBarrier { + usage: hal::StateTransition { + from: hal::AccelerationStructureUses::BUILD_OUTPUT, + to: hal::AccelerationStructureUses::SHADER_INPUT, + }, + }); + + let texture_barrier = hal::TextureBarrier { + texture: &texture, + range: wgpu_types::ImageSubresourceRange::default(), + usage: hal::StateTransition { + from: wgpu_types::TextureUses::UNINITIALIZED, + to: wgpu_types::TextureUses::STORAGE_READ_WRITE, + }, + }; + + cmd_encoder.transition_textures(iter::once(texture_barrier)); + } + + let init_fence_value = 1; + let fence = unsafe { + let mut fence = device.create_fence().unwrap(); + let init_cmd = cmd_encoder.end_encoding().unwrap(); + queue + .submit(&[&init_cmd], &[], (&mut fence, init_fence_value)) + .unwrap(); + device.wait(&fence, init_fence_value, None).unwrap(); + cmd_encoder.reset_all(iter::once(init_cmd)); + fence + }; + + Ok(Self { + instance, + adapter, + surface, + surface_format: surface_config.format, + device, + queue, + pipeline, + contexts: vec![ExecutionContext { + encoder: cmd_encoder, + fence, + fence_value: init_fence_value + 1, + used_views: Vec::new(), + used_cmd_bufs: Vec::new(), + frames_recorded: 0, + }], + context_index: 0, + extent: [window_size.0, window_size.1], + start: Instant::now(), + pipeline_layout, + bind_group, + texture, + instances, + instances_buffer, + blas, + tlas, + scratch_buffer, + time: 0.0, + indices_buffer: indices_buffer.map(|(buf, _)| buf), + vertices_buffer, + uniform_buffer, + texture_view, + bgl, + shader_module, + }) + } + + fn update(&mut self, _event: winit::event::WindowEvent) {} + + fn render(&mut self) { + let ctx = &mut self.contexts[self.context_index]; + + let surface_tex = unsafe { + self.surface + .acquire_texture(None, &ctx.fence) + .unwrap() + .texture + }; + + let target_barrier0 = hal::TextureBarrier { + texture: surface_tex.borrow(), + range: wgpu_types::ImageSubresourceRange::default(), + usage: hal::StateTransition { + from: wgpu_types::TextureUses::UNINITIALIZED, + to: wgpu_types::TextureUses::COPY_DST, + }, + }; + + let instances_buffer_size = + self.instances.len() * size_of::<AccelerationStructureInstance>(); + + let tlas_flags = hal::AccelerationStructureBuildFlags::PREFER_FAST_TRACE + | hal::AccelerationStructureBuildFlags::ALLOW_UPDATE; + + self.time += 1.0 / 60.0; + + self.instances[0].set_transform(&Affine3A::from_rotation_y(self.time)); + + unsafe { + let mapping = self + .device + .map_buffer(&self.instances_buffer, 0..instances_buffer_size as u64) + .unwrap(); + ptr::copy_nonoverlapping( + self.instances.as_ptr() as *const u8, + mapping.ptr.as_ptr(), + instances_buffer_size, + ); + self.device.unmap_buffer(&self.instances_buffer); + assert!(mapping.is_coherent); + } + + unsafe { + ctx.encoder.begin_encoding(Some("frame")).unwrap(); + + let instances = hal::AccelerationStructureInstances { + buffer: Some(&self.instances_buffer), + count: self.instances.len() as u32, + offset: 0, + }; + + ctx.encoder + .place_acceleration_structure_barrier(hal::AccelerationStructureBarrier { + usage: hal::StateTransition { + from: hal::AccelerationStructureUses::SHADER_INPUT, + to: hal::AccelerationStructureUses::BUILD_INPUT, + }, + }); + + ctx.encoder.build_acceleration_structures( + 1, + [hal::BuildAccelerationStructureDescriptor { + mode: hal::AccelerationStructureBuildMode::Update, + flags: tlas_flags, + destination_acceleration_structure: &self.tlas, + scratch_buffer: &self.scratch_buffer, + entries: &hal::AccelerationStructureEntries::Instances(instances), + source_acceleration_structure: Some(&self.tlas), + scratch_buffer_offset: 0, + }], + ); + + ctx.encoder + .place_acceleration_structure_barrier(hal::AccelerationStructureBarrier { + usage: hal::StateTransition { + from: hal::AccelerationStructureUses::BUILD_OUTPUT, + to: hal::AccelerationStructureUses::SHADER_INPUT, + }, + }); + + let scratch_buffer_barrier = hal::BufferBarrier { + buffer: &self.scratch_buffer, + usage: hal::StateTransition { + from: wgpu_types::BufferUses::BOTTOM_LEVEL_ACCELERATION_STRUCTURE_INPUT, + to: wgpu_types::BufferUses::TOP_LEVEL_ACCELERATION_STRUCTURE_INPUT, + }, + }; + ctx.encoder + .transition_buffers(iter::once(scratch_buffer_barrier)); + + ctx.encoder.transition_textures(iter::once(target_barrier0)); + } + + let surface_view_desc = hal::TextureViewDescriptor { + label: None, + format: self.surface_format, + dimension: wgpu_types::TextureViewDimension::D2, + usage: wgpu_types::TextureUses::COPY_DST, + range: wgpu_types::ImageSubresourceRange::default(), + }; + let surface_tex_view = unsafe { + self.device + .create_texture_view(surface_tex.borrow(), &surface_view_desc) + .unwrap() + }; + unsafe { + ctx.encoder.begin_compute_pass(&hal::ComputePassDescriptor { + label: None, + timestamp_writes: None, + }); + ctx.encoder.set_compute_pipeline(&self.pipeline); + ctx.encoder + .set_bind_group(&self.pipeline_layout, 0, &self.bind_group, &[]); + ctx.encoder.dispatch_workgroups([512 / 8, 512 / 8, 1]); + } + + ctx.frames_recorded += 1; + + let target_barrier1 = hal::TextureBarrier { + texture: surface_tex.borrow(), + range: wgpu_types::ImageSubresourceRange::default(), + usage: hal::StateTransition { + from: wgpu_types::TextureUses::COPY_DST, + to: wgpu_types::TextureUses::PRESENT, + }, + }; + let target_barrier2 = hal::TextureBarrier { + texture: &self.texture, + range: wgpu_types::ImageSubresourceRange::default(), + usage: hal::StateTransition { + from: wgpu_types::TextureUses::STORAGE_READ_WRITE, + to: wgpu_types::TextureUses::COPY_SRC, + }, + }; + let target_barrier3 = hal::TextureBarrier { + texture: &self.texture, + range: wgpu_types::ImageSubresourceRange::default(), + usage: hal::StateTransition { + from: wgpu_types::TextureUses::COPY_SRC, + to: wgpu_types::TextureUses::STORAGE_READ_WRITE, + }, + }; + unsafe { + ctx.encoder.end_compute_pass(); + ctx.encoder.transition_textures(iter::once(target_barrier2)); + ctx.encoder.copy_texture_to_texture( + &self.texture, + wgpu_types::TextureUses::COPY_SRC, + surface_tex.borrow(), + std::iter::once(hal::TextureCopy { + src_base: hal::TextureCopyBase { + mip_level: 0, + array_layer: 0, + origin: wgpu_types::Origin3d::ZERO, + aspect: hal::FormatAspects::COLOR, + }, + dst_base: hal::TextureCopyBase { + mip_level: 0, + array_layer: 0, + origin: wgpu_types::Origin3d::ZERO, + aspect: hal::FormatAspects::COLOR, + }, + size: hal::CopyExtent { + width: 512, + height: 512, + depth: 1, + }, + }), + ); + ctx.encoder.transition_textures(iter::once(target_barrier1)); + ctx.encoder.transition_textures(iter::once(target_barrier3)); + } + + unsafe { + let cmd_buf = ctx.encoder.end_encoding().unwrap(); + self.queue + .submit( + &[&cmd_buf], + &[&surface_tex], + (&mut ctx.fence, ctx.fence_value), + ) + .unwrap(); + self.queue.present(&self.surface, surface_tex).unwrap(); + ctx.used_cmd_bufs.push(cmd_buf); + ctx.used_views.push(surface_tex_view); + }; + + log::info!("Context switch from {}", self.context_index); + let old_fence_value = ctx.fence_value; + if self.contexts.len() == 1 { + let hal_desc = hal::CommandEncoderDescriptor { + label: None, + queue: &self.queue, + }; + self.contexts.push(unsafe { + ExecutionContext { + encoder: self.device.create_command_encoder(&hal_desc).unwrap(), + fence: self.device.create_fence().unwrap(), + fence_value: 0, + used_views: Vec::new(), + used_cmd_bufs: Vec::new(), + frames_recorded: 0, + } + }); + } + self.context_index = (self.context_index + 1) % self.contexts.len(); + let next = &mut self.contexts[self.context_index]; + unsafe { + next.wait_and_clear(&self.device); + } + next.fence_value = old_fence_value + 1; + } + + fn exit(mut self) { + unsafe { + { + let ctx = &mut self.contexts[self.context_index]; + self.queue + .submit(&[], &[], (&mut ctx.fence, ctx.fence_value)) + .unwrap(); + } + + for mut ctx in self.contexts { + ctx.wait_and_clear(&self.device); + drop(ctx.encoder); + self.device.destroy_fence(ctx.fence); + } + + self.device.destroy_bind_group(self.bind_group); + self.device.destroy_buffer(self.scratch_buffer); + self.device.destroy_buffer(self.instances_buffer); + if let Some(buffer) = self.indices_buffer { + self.device.destroy_buffer(buffer); + } + self.device.destroy_buffer(self.vertices_buffer); + self.device.destroy_buffer(self.uniform_buffer); + self.device.destroy_acceleration_structure(self.tlas); + self.device.destroy_acceleration_structure(self.blas); + self.device.destroy_texture_view(self.texture_view); + self.device.destroy_texture(self.texture); + self.device.destroy_compute_pipeline(self.pipeline); + self.device.destroy_pipeline_layout(self.pipeline_layout); + self.device.destroy_bind_group_layout(self.bgl); + self.device.destroy_shader_module(self.shader_module); + + self.surface.unconfigure(&self.device); + drop(self.queue); + drop(self.device); + drop(self.surface); + drop(self.adapter); + } + } +} + +cfg_if::cfg_if! { + // Apple + Metal + if #[cfg(all(target_vendor = "apple", feature = "metal"))] { + type Api = hal::api::Metal; + } + // Wasm + Vulkan + else if #[cfg(all(not(target_arch = "wasm32"), feature = "vulkan"))] { + type Api = hal::api::Vulkan; + } + // Windows + DX12 + else if #[cfg(all(windows, feature = "dx12"))] { + type Api = hal::api::Dx12; + } + // Anything + GLES + else if #[cfg(feature = "gles")] { + type Api = hal::api::Gles; + } + // Fallback + else { + type Api = hal::api::Noop; + } +} + +struct App { + example: Option<Example<Api>>, + window: Option<Window>, +} + +impl ApplicationHandler for App { + fn resumed(&mut self, event_loop: &ActiveEventLoop) { + if self.window.is_some() { + return; + } + let window = event_loop + .create_window( + Window::default_attributes() + .with_title("hal-ray-traced-triangle") + .with_inner_size(winit::dpi::PhysicalSize { + width: 512, + height: 512, + }) + .with_resizable(false) + .with_enabled_buttons(WindowButtons::CLOSE), + ) + .unwrap(); + let example = Example::<Api>::init(&window).expect("Selected backend is not supported"); + self.window = Some(window); + self.example = Some(example); + } + + fn exiting(&mut self, _event_loop: &ActiveEventLoop) { + self.example.take().unwrap().exit(); + } + + fn about_to_wait(&mut self, _event_loop: &ActiveEventLoop) { + if let Some(window) = &self.window { + window.request_redraw(); + } + } + + fn window_event( + &mut self, + event_loop: &ActiveEventLoop, + _window_id: winit::window::WindowId, + event: winit::event::WindowEvent, + ) { + event_loop.set_control_flow(ControlFlow::Poll); + + match event { + winit::event::WindowEvent::CloseRequested => { + event_loop.exit(); + } + winit::event::WindowEvent::KeyboardInput { event, .. } + if event.physical_key + == winit::keyboard::PhysicalKey::Code(winit::keyboard::KeyCode::Escape) => + { + event_loop.exit(); + } + winit::event::WindowEvent::RedrawRequested => { + let ex = self.example.as_mut().unwrap(); + ex.render(); + } + _ => { + self.example.as_mut().unwrap().update(event); + } + } + } +} + +fn main() { + env_logger::init(); + + let event_loop = winit::event_loop::EventLoop::new().unwrap(); + let mut app = App { + example: None, + window: None, + }; + event_loop.run_app(&mut app).unwrap(); +} diff --git a/app/vendor/rune/vendor/wgpu-hal/examples/ray-traced-triangle/shader.wgsl b/app/vendor/rune/vendor/wgpu-hal/examples/ray-traced-triangle/shader.wgsl new file mode 100644 index 0000000..9710ca6 --- /dev/null +++ b/app/vendor/rune/vendor/wgpu-hal/examples/ray-traced-triangle/shader.wgsl @@ -0,0 +1,39 @@ +enable wgpu_ray_query; + +struct Uniforms { + view_inv: mat4x4<f32>, + proj_inv: mat4x4<f32>, +}; +@group(0) @binding(0) +var<uniform> uniforms: Uniforms; + +@group(0) @binding(1) +var output: texture_storage_2d<rgba8unorm, write>; + +@group(0) @binding(2) +var acc_struct: acceleration_structure; + +@compute @workgroup_size(8, 8) +fn main(@builtin(global_invocation_id) global_id: vec3<u32>) { + let target_size = textureDimensions(output); + + let pixel_center = vec2<f32>(global_id.xy) + vec2<f32>(0.5); + let in_uv = pixel_center / vec2<f32>(target_size.xy); + let d = in_uv * 2.0 - 1.0; + + let origin = (uniforms.view_inv * vec4<f32>(0.0, 0.0, 0.0, 1.0)).xyz; + let temp = uniforms.proj_inv * vec4<f32>(d.x, d.y, 1.0, 1.0); + let direction = (uniforms.view_inv * vec4<f32>(normalize(temp.xyz), 0.0)).xyz; + + var rq: ray_query; + rayQueryInitialize(&rq, acc_struct, RayDesc(0u, 0xFFu, 0.1, 200.0, origin, direction)); + rayQueryProceed(&rq); + + var color = vec4<f32>(0.0, 0.0, 0.0, 1.0); + let intersection = rayQueryGetCommittedIntersection(&rq); + if intersection.kind != RAY_QUERY_INTERSECTION_NONE { + color = vec4<f32>(intersection.barycentrics, 1.0 - intersection.barycentrics.x - intersection.barycentrics.y, 1.0); + } + + textureStore(output, global_id.xy, color); +} \ No newline at end of file diff --git a/app/vendor/rune/vendor/wgpu-hal/src/auxil/dxgi/conv.rs b/app/vendor/rune/vendor/wgpu-hal/src/auxil/dxgi/conv.rs new file mode 100644 index 0000000..c9e4dbc --- /dev/null +++ b/app/vendor/rune/vendor/wgpu-hal/src/auxil/dxgi/conv.rs @@ -0,0 +1,301 @@ +use alloc::string::String; +use std::{ffi::OsString, os::windows::ffi::OsStringExt}; + +use windows::Win32::Graphics::Dxgi; + +// Helper to convert DXGI adapter name to a normal string +pub fn map_adapter_name(name: [u16; 128]) -> String { + let len = name.iter().take_while(|&&c| c != 0).count(); + let name = OsString::from_wide(&name[..len]); + name.to_string_lossy().into_owned() +} + +pub fn map_texture_format_failable( + format: wgt::TextureFormat, +) -> Option<Dxgi::Common::DXGI_FORMAT> { + use wgt::TextureFormat as Tf; + use Dxgi::Common::*; + + Some(match format { + Tf::R8Unorm => DXGI_FORMAT_R8_UNORM, + Tf::R8Snorm => DXGI_FORMAT_R8_SNORM, + Tf::R8Uint => DXGI_FORMAT_R8_UINT, + Tf::R8Sint => DXGI_FORMAT_R8_SINT, + Tf::R16Uint => DXGI_FORMAT_R16_UINT, + Tf::R16Sint => DXGI_FORMAT_R16_SINT, + Tf::R16Unorm => DXGI_FORMAT_R16_UNORM, + Tf::R16Snorm => DXGI_FORMAT_R16_SNORM, + Tf::R16Float => DXGI_FORMAT_R16_FLOAT, + Tf::Rg8Unorm => DXGI_FORMAT_R8G8_UNORM, + Tf::Rg8Snorm => DXGI_FORMAT_R8G8_SNORM, + Tf::Rg8Uint => DXGI_FORMAT_R8G8_UINT, + Tf::Rg8Sint => DXGI_FORMAT_R8G8_SINT, + Tf::Rg16Unorm => DXGI_FORMAT_R16G16_UNORM, + Tf::Rg16Snorm => DXGI_FORMAT_R16G16_SNORM, + Tf::R32Uint => DXGI_FORMAT_R32_UINT, + Tf::R32Sint => DXGI_FORMAT_R32_SINT, + Tf::R32Float => DXGI_FORMAT_R32_FLOAT, + Tf::Rg16Uint => DXGI_FORMAT_R16G16_UINT, + Tf::Rg16Sint => DXGI_FORMAT_R16G16_SINT, + Tf::Rg16Float => DXGI_FORMAT_R16G16_FLOAT, + Tf::Rgba8Unorm => DXGI_FORMAT_R8G8B8A8_UNORM, + Tf::Rgba8UnormSrgb => DXGI_FORMAT_R8G8B8A8_UNORM_SRGB, + Tf::Bgra8UnormSrgb => DXGI_FORMAT_B8G8R8A8_UNORM_SRGB, + Tf::Rgba8Snorm => DXGI_FORMAT_R8G8B8A8_SNORM, + Tf::Bgra8Unorm => DXGI_FORMAT_B8G8R8A8_UNORM, + Tf::Rgba8Uint => DXGI_FORMAT_R8G8B8A8_UINT, + Tf::Rgba8Sint => DXGI_FORMAT_R8G8B8A8_SINT, + Tf::Rgb9e5Ufloat => DXGI_FORMAT_R9G9B9E5_SHAREDEXP, + Tf::Rgb10a2Uint => DXGI_FORMAT_R10G10B10A2_UINT, + Tf::Rgb10a2Unorm => DXGI_FORMAT_R10G10B10A2_UNORM, + Tf::Rg11b10Ufloat => DXGI_FORMAT_R11G11B10_FLOAT, + Tf::R64Uint => DXGI_FORMAT_R32G32_UINT, // R64 emulated by R32G32 + Tf::Rg32Uint => DXGI_FORMAT_R32G32_UINT, + Tf::Rg32Sint => DXGI_FORMAT_R32G32_SINT, + Tf::Rg32Float => DXGI_FORMAT_R32G32_FLOAT, + Tf::Rgba16Uint => DXGI_FORMAT_R16G16B16A16_UINT, + Tf::Rgba16Sint => DXGI_FORMAT_R16G16B16A16_SINT, + Tf::Rgba16Unorm => DXGI_FORMAT_R16G16B16A16_UNORM, + Tf::Rgba16Snorm => DXGI_FORMAT_R16G16B16A16_SNORM, + Tf::Rgba16Float => DXGI_FORMAT_R16G16B16A16_FLOAT, + Tf::Rgba32Uint => DXGI_FORMAT_R32G32B32A32_UINT, + Tf::Rgba32Sint => DXGI_FORMAT_R32G32B32A32_SINT, + Tf::Rgba32Float => DXGI_FORMAT_R32G32B32A32_FLOAT, + Tf::Stencil8 => DXGI_FORMAT_D24_UNORM_S8_UINT, + Tf::Depth16Unorm => DXGI_FORMAT_D16_UNORM, + Tf::Depth24Plus => DXGI_FORMAT_D24_UNORM_S8_UINT, + Tf::Depth24PlusStencil8 => DXGI_FORMAT_D24_UNORM_S8_UINT, + Tf::Depth32Float => DXGI_FORMAT_D32_FLOAT, + Tf::Depth32FloatStencil8 => DXGI_FORMAT_D32_FLOAT_S8X24_UINT, + Tf::NV12 => DXGI_FORMAT_NV12, + Tf::P010 => DXGI_FORMAT_P010, + Tf::Bc1RgbaUnorm => DXGI_FORMAT_BC1_UNORM, + Tf::Bc1RgbaUnormSrgb => DXGI_FORMAT_BC1_UNORM_SRGB, + Tf::Bc2RgbaUnorm => DXGI_FORMAT_BC2_UNORM, + Tf::Bc2RgbaUnormSrgb => DXGI_FORMAT_BC2_UNORM_SRGB, + Tf::Bc3RgbaUnorm => DXGI_FORMAT_BC3_UNORM, + Tf::Bc3RgbaUnormSrgb => DXGI_FORMAT_BC3_UNORM_SRGB, + Tf::Bc4RUnorm => DXGI_FORMAT_BC4_UNORM, + Tf::Bc4RSnorm => DXGI_FORMAT_BC4_SNORM, + Tf::Bc5RgUnorm => DXGI_FORMAT_BC5_UNORM, + Tf::Bc5RgSnorm => DXGI_FORMAT_BC5_SNORM, + Tf::Bc6hRgbUfloat => DXGI_FORMAT_BC6H_UF16, + Tf::Bc6hRgbFloat => DXGI_FORMAT_BC6H_SF16, + Tf::Bc7RgbaUnorm => DXGI_FORMAT_BC7_UNORM, + Tf::Bc7RgbaUnormSrgb => DXGI_FORMAT_BC7_UNORM_SRGB, + Tf::Etc2Rgb8Unorm + | Tf::Etc2Rgb8UnormSrgb + | Tf::Etc2Rgb8A1Unorm + | Tf::Etc2Rgb8A1UnormSrgb + | Tf::Etc2Rgba8Unorm + | Tf::Etc2Rgba8UnormSrgb + | Tf::EacR11Unorm + | Tf::EacR11Snorm + | Tf::EacRg11Unorm + | Tf::EacRg11Snorm + | Tf::Astc { + block: _, + channel: _, + } => return None, + }) +} + +pub fn map_texture_format(format: wgt::TextureFormat) -> Dxgi::Common::DXGI_FORMAT { + match map_texture_format_failable(format) { + Some(f) => f, + None => unreachable!(), + } +} + +// Note: DXGI doesn't allow sRGB format on the swapchain, +// but creating RTV of swapchain buffers with sRGB works. +pub fn map_texture_format_nosrgb(format: wgt::TextureFormat) -> Dxgi::Common::DXGI_FORMAT { + match format { + wgt::TextureFormat::Bgra8UnormSrgb => Dxgi::Common::DXGI_FORMAT_B8G8R8A8_UNORM, + wgt::TextureFormat::Rgba8UnormSrgb => Dxgi::Common::DXGI_FORMAT_R8G8B8A8_UNORM, + _ => map_texture_format(format), + } +} + +// SRV and UAV can't use the depth or typeless formats +// see https://microsoft.github.io/DirectX-Specs/d3d/PlanarDepthStencilDDISpec.html#view-creation +pub fn map_texture_format_for_srv_uav( + format: wgt::TextureFormat, + aspect: crate::FormatAspects, +) -> Option<Dxgi::Common::DXGI_FORMAT> { + Some(match (format, aspect) { + (wgt::TextureFormat::Depth16Unorm, crate::FormatAspects::DEPTH) => { + Dxgi::Common::DXGI_FORMAT_R16_UNORM + } + (wgt::TextureFormat::Depth32Float, crate::FormatAspects::DEPTH) => { + Dxgi::Common::DXGI_FORMAT_R32_FLOAT + } + (wgt::TextureFormat::Depth32FloatStencil8, crate::FormatAspects::DEPTH) => { + Dxgi::Common::DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS + } + ( + wgt::TextureFormat::Depth24Plus | wgt::TextureFormat::Depth24PlusStencil8, + crate::FormatAspects::DEPTH, + ) => Dxgi::Common::DXGI_FORMAT_R24_UNORM_X8_TYPELESS, + + (wgt::TextureFormat::Depth32FloatStencil8, crate::FormatAspects::STENCIL) => { + Dxgi::Common::DXGI_FORMAT_X32_TYPELESS_G8X24_UINT + } + ( + wgt::TextureFormat::Stencil8 | wgt::TextureFormat::Depth24PlusStencil8, + crate::FormatAspects::STENCIL, + ) => Dxgi::Common::DXGI_FORMAT_X24_TYPELESS_G8_UINT, + + (_, crate::FormatAspects::DEPTH) + | (_, crate::FormatAspects::STENCIL) + | (_, crate::FormatAspects::DEPTH_STENCIL) => return None, + + _ => map_texture_format(format), + }) +} + +// see https://microsoft.github.io/DirectX-Specs/d3d/PlanarDepthStencilDDISpec.html#planar-layout-for-staging-from-buffer +pub fn map_texture_format_for_copy( + format: wgt::TextureFormat, + aspect: crate::FormatAspects, +) -> Option<Dxgi::Common::DXGI_FORMAT> { + Some(match (format, aspect) { + (wgt::TextureFormat::Depth16Unorm, crate::FormatAspects::DEPTH) => { + Dxgi::Common::DXGI_FORMAT_R16_UNORM + } + ( + wgt::TextureFormat::Depth32Float | wgt::TextureFormat::Depth32FloatStencil8, + crate::FormatAspects::DEPTH, + ) => Dxgi::Common::DXGI_FORMAT_R32_FLOAT, + + ( + wgt::TextureFormat::Stencil8 + | wgt::TextureFormat::Depth24PlusStencil8 + | wgt::TextureFormat::Depth32FloatStencil8, + crate::FormatAspects::STENCIL, + ) => Dxgi::Common::DXGI_FORMAT_R8_UINT, + + // `CopyTextureRegion` on a plane subresource wants the + // single-plane DXGI format, not the planar one. + (format, aspects) if format.is_multi_planar_format() && aspects.is_one() => { + map_texture_format(format.aspect_specific_format(aspects.map())?) + } + + (format, crate::FormatAspects::COLOR) => map_texture_format(format), + + _ => return None, + }) +} + +pub fn map_texture_format_for_resource( + format: wgt::TextureFormat, + usage: wgt::TextureUses, + has_view_formats: bool, + casting_fully_typed_format_supported: bool, +) -> Dxgi::Common::DXGI_FORMAT { + use wgt::TextureFormat as Tf; + use Dxgi::Common::*; + + if casting_fully_typed_format_supported { + map_texture_format(format) + + // We might view this resource as srgb or non-srgb + } else if has_view_formats { + match format { + Tf::Rgba8Unorm | Tf::Rgba8UnormSrgb => DXGI_FORMAT_R8G8B8A8_TYPELESS, + Tf::Bgra8Unorm | Tf::Bgra8UnormSrgb => DXGI_FORMAT_B8G8R8A8_TYPELESS, + Tf::Bc1RgbaUnorm | Tf::Bc1RgbaUnormSrgb => DXGI_FORMAT_BC1_TYPELESS, + Tf::Bc2RgbaUnorm | Tf::Bc2RgbaUnormSrgb => DXGI_FORMAT_BC2_TYPELESS, + Tf::Bc3RgbaUnorm | Tf::Bc3RgbaUnormSrgb => DXGI_FORMAT_BC3_TYPELESS, + Tf::Bc7RgbaUnorm | Tf::Bc7RgbaUnormSrgb => DXGI_FORMAT_BC7_TYPELESS, + format => map_texture_format(format), + } + + // We might view this resource as SRV/UAV but also as DSV + } else if format.is_depth_stencil_format() + && usage.intersects( + wgt::TextureUses::RESOURCE + | wgt::TextureUses::STORAGE_READ_ONLY + | wgt::TextureUses::STORAGE_WRITE_ONLY + | wgt::TextureUses::STORAGE_READ_WRITE, + ) + { + match format { + Tf::Depth16Unorm => DXGI_FORMAT_R16_TYPELESS, + Tf::Depth32Float => DXGI_FORMAT_R32_TYPELESS, + Tf::Depth32FloatStencil8 => DXGI_FORMAT_R32G8X24_TYPELESS, + Tf::Stencil8 | Tf::Depth24Plus | Tf::Depth24PlusStencil8 => DXGI_FORMAT_R24G8_TYPELESS, + _ => unreachable!(), + } + } else { + map_texture_format(format) + } +} + +pub fn map_index_format(format: wgt::IndexFormat) -> Dxgi::Common::DXGI_FORMAT { + match format { + wgt::IndexFormat::Uint16 => Dxgi::Common::DXGI_FORMAT_R16_UINT, + wgt::IndexFormat::Uint32 => Dxgi::Common::DXGI_FORMAT_R32_UINT, + } +} + +pub fn map_vertex_format(format: wgt::VertexFormat) -> Dxgi::Common::DXGI_FORMAT { + use wgt::VertexFormat as Vf; + use Dxgi::Common::*; + + match format { + Vf::Unorm8 => DXGI_FORMAT_R8_UNORM, + Vf::Snorm8 => DXGI_FORMAT_R8_SNORM, + Vf::Uint8 => DXGI_FORMAT_R8_UINT, + Vf::Sint8 => DXGI_FORMAT_R8_SINT, + Vf::Unorm8x2 => DXGI_FORMAT_R8G8_UNORM, + Vf::Snorm8x2 => DXGI_FORMAT_R8G8_SNORM, + Vf::Uint8x2 => DXGI_FORMAT_R8G8_UINT, + Vf::Sint8x2 => DXGI_FORMAT_R8G8_SINT, + Vf::Unorm8x4 => DXGI_FORMAT_R8G8B8A8_UNORM, + Vf::Snorm8x4 => DXGI_FORMAT_R8G8B8A8_SNORM, + Vf::Uint8x4 => DXGI_FORMAT_R8G8B8A8_UINT, + Vf::Sint8x4 => DXGI_FORMAT_R8G8B8A8_SINT, + Vf::Unorm16 => DXGI_FORMAT_R16_UNORM, + Vf::Snorm16 => DXGI_FORMAT_R16_SNORM, + Vf::Uint16 => DXGI_FORMAT_R16_UINT, + Vf::Sint16 => DXGI_FORMAT_R16_SINT, + Vf::Float16 => DXGI_FORMAT_R16_FLOAT, + Vf::Unorm16x2 => DXGI_FORMAT_R16G16_UNORM, + Vf::Snorm16x2 => DXGI_FORMAT_R16G16_SNORM, + Vf::Uint16x2 => DXGI_FORMAT_R16G16_UINT, + Vf::Sint16x2 => DXGI_FORMAT_R16G16_SINT, + Vf::Float16x2 => DXGI_FORMAT_R16G16_FLOAT, + Vf::Unorm16x4 => DXGI_FORMAT_R16G16B16A16_UNORM, + Vf::Snorm16x4 => DXGI_FORMAT_R16G16B16A16_SNORM, + Vf::Uint16x4 => DXGI_FORMAT_R16G16B16A16_UINT, + Vf::Sint16x4 => DXGI_FORMAT_R16G16B16A16_SINT, + Vf::Float16x4 => DXGI_FORMAT_R16G16B16A16_FLOAT, + Vf::Uint32 => DXGI_FORMAT_R32_UINT, + Vf::Sint32 => DXGI_FORMAT_R32_SINT, + Vf::Float32 => DXGI_FORMAT_R32_FLOAT, + Vf::Uint32x2 => DXGI_FORMAT_R32G32_UINT, + Vf::Sint32x2 => DXGI_FORMAT_R32G32_SINT, + Vf::Float32x2 => DXGI_FORMAT_R32G32_FLOAT, + Vf::Uint32x3 => DXGI_FORMAT_R32G32B32_UINT, + Vf::Sint32x3 => DXGI_FORMAT_R32G32B32_SINT, + Vf::Float32x3 => DXGI_FORMAT_R32G32B32_FLOAT, + Vf::Uint32x4 => DXGI_FORMAT_R32G32B32A32_UINT, + Vf::Sint32x4 => DXGI_FORMAT_R32G32B32A32_SINT, + Vf::Float32x4 => DXGI_FORMAT_R32G32B32A32_FLOAT, + Vf::Unorm10_10_10_2 => DXGI_FORMAT_R10G10B10A2_UNORM, + Vf::Unorm8x4Bgra => DXGI_FORMAT_B8G8R8A8_UNORM, + Vf::Float64 | Vf::Float64x2 | Vf::Float64x3 | Vf::Float64x4 => unimplemented!(), + } +} + +pub fn map_acomposite_alpha_mode(mode: wgt::CompositeAlphaMode) -> Dxgi::Common::DXGI_ALPHA_MODE { + match mode { + wgt::CompositeAlphaMode::PreMultiplied => Dxgi::Common::DXGI_ALPHA_MODE_PREMULTIPLIED, + wgt::CompositeAlphaMode::PostMultiplied => Dxgi::Common::DXGI_ALPHA_MODE_STRAIGHT, + wgt::CompositeAlphaMode::Opaque => Dxgi::Common::DXGI_ALPHA_MODE_IGNORE, + wgt::CompositeAlphaMode::Auto | wgt::CompositeAlphaMode::Inherit => { + Dxgi::Common::DXGI_ALPHA_MODE_UNSPECIFIED + } + } +} diff --git a/app/vendor/rune/vendor/wgpu-hal/src/auxil/dxgi/exception.rs b/app/vendor/rune/vendor/wgpu-hal/src/auxil/dxgi/exception.rs new file mode 100644 index 0000000..ac7d55d --- /dev/null +++ b/app/vendor/rune/vendor/wgpu-hal/src/auxil/dxgi/exception.rs @@ -0,0 +1,97 @@ +use alloc::{borrow::Cow, string::String}; + +use parking_lot::Mutex; +use windows::Win32::{Foundation, System::Diagnostics::Debug}; + +// This is a mutex as opposed to an atomic as we need to completely +// lock everyone out until we have registered or unregistered the +// exception handler, otherwise really nasty races could happen. +// +// By routing all the registration through these functions we can guarantee +// there is either 1 or 0 exception handlers registered, not multiple. +static EXCEPTION_HANDLER_COUNT: Mutex<usize> = Mutex::new(0); + +pub fn register_exception_handler() { + let mut count_guard = EXCEPTION_HANDLER_COUNT.lock(); + if *count_guard == 0 { + unsafe { Debug::AddVectoredExceptionHandler(0, Some(output_debug_string_handler)) }; + } + *count_guard += 1; +} + +pub fn unregister_exception_handler() { + let mut count_guard = EXCEPTION_HANDLER_COUNT.lock(); + if *count_guard == 1 { + unsafe { Debug::RemoveVectoredExceptionHandler(output_debug_string_handler as *mut _) }; + } + *count_guard -= 1; +} + +const MESSAGE_PREFIXES: &[(&str, log::Level)] = &[ + ("CORRUPTION", log::Level::Error), + ("ERROR", log::Level::Error), + ("WARNING", log::Level::Warn), + // We intentionally suppress "INFO" messages down to debug + // so that users are not innundated with info messages from the runtime. + ("INFO", log::Level::Debug), + ("MESSAGE", log::Level::Trace), +]; + +unsafe extern "system" fn output_debug_string_handler( + exception_info: *mut Debug::EXCEPTION_POINTERS, +) -> i32 { + // See https://stackoverflow.com/a/41480827 + let record = unsafe { &*(*exception_info).ExceptionRecord }; + if record.NumberParameters != 2 { + return Debug::EXCEPTION_CONTINUE_SEARCH; + } + let message = match record.ExceptionCode { + Foundation::DBG_PRINTEXCEPTION_C => { + String::from_utf8_lossy(bytemuck::cast_slice(&record.ExceptionInformation)) + } + Foundation::DBG_PRINTEXCEPTION_WIDE_C => Cow::Owned(String::from_utf16_lossy( + bytemuck::cast_slice(&record.ExceptionInformation), + )), + _ => return Debug::EXCEPTION_CONTINUE_SEARCH, + }; + + let message = match message.strip_prefix("D3D12 ") { + Some(msg) => msg + .trim_end_matches("\n\0") + .trim_end_matches("[ STATE_CREATION WARNING #0: UNKNOWN]"), + None => return Debug::EXCEPTION_CONTINUE_SEARCH, + }; + + let (message, level) = match MESSAGE_PREFIXES + .iter() + .find(|&&(prefix, _)| message.starts_with(prefix)) + { + Some(&(prefix, level)) => (&message[prefix.len() + 2..], level), + None => (message, log::Level::Debug), + }; + + if level == log::Level::Warn && message.contains("#82") { + // This is are useless spammy warnings (#820, #821): + // "The application did not pass any clear value to resource creation" + return Debug::EXCEPTION_CONTINUE_SEARCH; + } + + if level == log::Level::Warn && message.contains("DRAW_EMPTY_SCISSOR_RECTANGLE") { + // This is normal, WebGPU allows passing empty scissor rectangles. + return Debug::EXCEPTION_CONTINUE_SEARCH; + } + + let _ = std::panic::catch_unwind(|| { + log::log!(level, "{message}"); + }); + + #[cfg(feature = "validation_canary")] + if cfg!(debug_assertions) && level == log::Level::Error { + use alloc::string::ToString as _; + + // Set canary and continue + crate::VALIDATION_CANARY.add(message.to_string()); + } + + Debug::EXCEPTION_CONTINUE_EXECUTION +} diff --git a/app/vendor/rune/vendor/wgpu-hal/src/auxil/dxgi/factory.rs b/app/vendor/rune/vendor/wgpu-hal/src/auxil/dxgi/factory.rs new file mode 100644 index 0000000..6e3c74e --- /dev/null +++ b/app/vendor/rune/vendor/wgpu-hal/src/auxil/dxgi/factory.rs @@ -0,0 +1,181 @@ +use alloc::{string::String, vec::Vec}; +use core::ops::Deref; + +use windows::{core::Interface as _, Win32::Graphics::Dxgi}; + +use crate::dx12::DxgiLib; + +use super::result::HResult as _; + +// We can rely on the presence of DXGI 1.4 since D3D12 requires WDDM 2.0, Windows 10 (1507), and so does DXGI 1.4. + +pub(crate) fn should_keep_adapter(adapter: &Dxgi::IDXGIAdapter1) -> bool { + let desc = unsafe { adapter.GetDesc1() }.unwrap(); + + // The Intel Haswell family of iGPUs had support for the D3D12 API but it was later + // removed due to a security vulnerability. + // + // We are explicitly filtering out all the devices in the family because we are now + // getting reports of device loss at a later time than at device creation time (`D3D12CreateDevice`). + // + // See https://www.intel.com/content/www/us/en/support/articles/000057520/graphics.html + // This list of device IDs is from https://dgpu-docs.intel.com/devices/hardware-table.html + let haswell_device_ids = [ + 0x0422, 0x0426, 0x042A, 0x042B, 0x042E, 0x0C22, 0x0C26, 0x0C2A, 0x0C2B, 0x0C2E, 0x0A22, + 0x0A2A, 0x0A2B, 0x0D2A, 0x0D2B, 0x0D2E, 0x0A26, 0x0A2E, 0x0D22, 0x0D26, 0x0412, 0x0416, + 0x0D12, 0x041A, 0x041B, 0x0C12, 0x0C16, 0x0C1A, 0x0C1B, 0x0C1E, 0x0A12, 0x0A1A, 0x0A1B, + 0x0D16, 0x0D1A, 0x0D1B, 0x0D1E, 0x041E, 0x0A16, 0x0A1E, 0x0402, 0x0406, 0x040A, 0x040B, + 0x040E, 0x0C02, 0x0C06, 0x0C0A, 0x0C0B, 0x0C0E, 0x0A02, 0x0A06, 0x0A0A, 0x0A0B, 0x0A0E, + 0x0D02, 0x0D06, 0x0D0A, 0x0D0B, 0x0D0E, + ]; + if desc.VendorId == 0x8086 && haswell_device_ids.contains(&desc.DeviceId) { + return false; + } + + // If run completely headless, windows will show two different WARP adapters, one + // which is lying about being an integrated card. This is so that programs + // that ignore software adapters will actually run on headless/gpu-less machines. + // + // We don't want that and discourage that kind of filtering anyway, so we skip the integrated WARP. + if desc.VendorId == 5140 + && !Dxgi::DXGI_ADAPTER_FLAG(desc.Flags as i32).contains(Dxgi::DXGI_ADAPTER_FLAG_SOFTWARE) + { + let adapter_name = super::conv::map_adapter_name(desc.Description); + if adapter_name.contains("Microsoft Basic Render Driver") { + return false; + } + } + + true +} + +#[derive(Clone, Debug)] +pub enum DxgiAdapter { + /// Provided by DXGI 1.4 + Adapter3(Dxgi::IDXGIAdapter3), + /// Provided by DXGI 1.6 + Adapter4(Dxgi::IDXGIAdapter4), +} + +impl DxgiAdapter { + pub fn query_video_memory_info( + &self, + group: Dxgi::DXGI_MEMORY_SEGMENT_GROUP, + ) -> Result<Dxgi::DXGI_QUERY_VIDEO_MEMORY_INFO, crate::DeviceError> { + let mut info = Dxgi::DXGI_QUERY_VIDEO_MEMORY_INFO::default(); + unsafe { self.QueryVideoMemoryInfo(0, group, &mut info) } + .into_device_result("QueryVideoMemoryInfo")?; + Ok(info) + } +} + +impl Deref for DxgiAdapter { + type Target = Dxgi::IDXGIAdapter3; + + fn deref(&self) -> &Self::Target { + match self { + DxgiAdapter::Adapter3(a) => a, + DxgiAdapter::Adapter4(a) => a, + } + } +} + +pub fn enumerate_adapters(factory: DxgiFactory) -> Vec<DxgiAdapter> { + let mut adapters = Vec::with_capacity(8); + + for cur_index in 0.. { + profiling::scope!("IDXGIFactory1::EnumAdapters1"); + let adapter1: Dxgi::IDXGIAdapter1 = match unsafe { factory.EnumAdapters1(cur_index) } { + Ok(a) => a, + Err(e) if e.code() == Dxgi::DXGI_ERROR_NOT_FOUND => break, + Err(e) => { + log::error!("Failed enumerating adapters: {e}"); + break; + } + }; + + if !should_keep_adapter(&adapter1) { + continue; + } + + if let Ok(adapter4) = adapter1.cast::<Dxgi::IDXGIAdapter4>() { + adapters.push(DxgiAdapter::Adapter4(adapter4)); + } else { + let adapter3 = adapter1.cast::<Dxgi::IDXGIAdapter3>().unwrap(); + adapters.push(DxgiAdapter::Adapter3(adapter3)); + } + } + + adapters +} + +#[derive(Clone, Debug)] +pub enum DxgiFactory { + /// Provided by DXGI 1.4 + Factory4(Dxgi::IDXGIFactory4), + /// Provided by DXGI 1.5 + Factory5(Dxgi::IDXGIFactory5), + /// Provided by DXGI 1.6 + Factory6(Dxgi::IDXGIFactory6), +} + +impl Deref for DxgiFactory { + type Target = Dxgi::IDXGIFactory4; + + fn deref(&self) -> &Self::Target { + match self { + DxgiFactory::Factory4(f) => f, + DxgiFactory::Factory5(f) => f, + DxgiFactory::Factory6(f) => f, + } + } +} + +impl DxgiFactory { + pub fn as_factory5(&self) -> Option<&Dxgi::IDXGIFactory5> { + match self { + Self::Factory4(_) => None, + Self::Factory5(f) => Some(f), + Self::Factory6(f) => Some(f), + } + } +} + +pub fn create_factory( + instance_flags: wgt::InstanceFlags, +) -> Result<(DxgiLib, DxgiFactory), crate::InstanceError> { + let lib_dxgi = DxgiLib::new().map_err(|e| { + crate::InstanceError::with_source(String::from("failed to load dxgi.dll"), e) + })?; + + let mut factory_flags = Dxgi::DXGI_CREATE_FACTORY_FLAGS::default(); + + if instance_flags.contains(wgt::InstanceFlags::VALIDATION) { + // The `DXGI_CREATE_FACTORY_DEBUG` flag is only allowed to be passed to + // `CreateDXGIFactory2` if the debug interface is actually available. So + // we check for whether it exists first. + if let Ok(Some(_)) = lib_dxgi.debug_interface1() { + factory_flags |= Dxgi::DXGI_CREATE_FACTORY_DEBUG; + } + } + + let factory4 = match lib_dxgi.create_factory4(factory_flags) { + Ok(factory) => factory, + Err(err) => { + return Err(crate::InstanceError::with_source( + String::from("IDXGIFactory4 creation failed"), + err, + )); + } + }; + + if let Ok(factory6) = factory4.cast::<Dxgi::IDXGIFactory6>() { + return Ok((lib_dxgi, DxgiFactory::Factory6(factory6))); + } + + if let Ok(factory5) = factory4.cast::<Dxgi::IDXGIFactory5>() { + return Ok((lib_dxgi, DxgiFactory::Factory5(factory5))); + } + + Ok((lib_dxgi, DxgiFactory::Factory4(factory4))) +} diff --git a/app/vendor/rune/vendor/wgpu-hal/src/auxil/dxgi/hdr.rs b/app/vendor/rune/vendor/wgpu-hal/src/auxil/dxgi/hdr.rs new file mode 100644 index 0000000..3d810ee --- /dev/null +++ b/app/vendor/rune/vendor/wgpu-hal/src/auxil/dxgi/hdr.rs @@ -0,0 +1,352 @@ +//! Reading a window's [`wgt::DisplayHdrInfo`] through DXGI. +//! +//! Lives in `auxil/dxgi` so the DX12 and Vulkan-on-Windows backends share it: +//! both query through a [`DxgiHdrSource`], so the same monitor reports identical +//! numbers under either backend. + +use parking_lot::Mutex; +use windows::{ + core::Interface as _, + Win32::{ + Foundation::HWND, + Graphics::{Dxgi, Gdi}, + }, +}; + +/// The primary colors of a color space, in CIE 1931 xy: +/// `[[red_x, red_y], [green_x, green_y], [blue_x, blue_y]]`. +type Primaries = [[f32; 2]; 3]; + +/// Reference primaries (CIE 1931 xy: red, green, blue) for the three coarse +/// gamut buckets, used to classify a display's reported primaries. +const REC709: Primaries = [[0.640, 0.330], [0.300, 0.600], [0.150, 0.060]]; +const DISPLAY_P3: Primaries = [[0.680, 0.320], [0.265, 0.690], [0.150, 0.060]]; +const REC2020: Primaries = [[0.708, 0.292], [0.170, 0.797], [0.131, 0.046]]; + +/// Classifies reported primaries into the closest coarse [`wgt::DisplayGamut`] +/// bucket (least-squares over the R/G/B chromaticities). Advisory only. +/// +/// Returns `None` if every primary is zeroed (the EDID reported nothing usable), +/// so a bogus all-zero descriptor is not misclassified as sRGB. +fn classify_gamut(red: [f32; 2], green: [f32; 2], blue: [f32; 2]) -> Option<wgt::DisplayGamut> { + let measured = [red, green, blue]; + if measured.iter().all(|p| p[0] == 0.0 && p[1] == 0.0) { + return None; + } + let dist = |reference: &Primaries| -> f32 { + measured + .iter() + .zip(reference) + .map(|(m, r)| { + let dx = m[0] - r[0]; + let dy = m[1] - r[1]; + dx * dx + dy * dy + }) + .sum() + }; + [ + (wgt::DisplayGamut::Srgb, dist(&REC709)), + (wgt::DisplayGamut::DisplayP3, dist(&DISPLAY_P3)), + (wgt::DisplayGamut::Rec2020, dist(&REC2020)), + ] + .into_iter() + .min_by(|a, b| a.1.total_cmp(&b.1)) + .map(|(gamut, _)| gamut) +} + +/// Maps an [`IDXGIOutput6::GetDesc1`] result and the SDR white level (from +/// [`sdr_white_nits_for_monitor`]) into the backend-agnostic +/// [`wgt::DisplayHdrInfo`]. +/// +/// Pure: it interprets `desc1` without any system call. Numeric values are +/// advisory (EDID-sourced); see [`wgt::DisplayLuminance`]. +/// +/// [`IDXGIOutput6::GetDesc1`]: windows::Win32::Graphics::Dxgi::IDXGIOutput6::GetDesc1 +fn display_hdr_info_from_desc1( + desc1: &Dxgi::DXGI_OUTPUT_DESC1, + sdr_white_nits: Option<f32>, +) -> wgt::DisplayHdrInfo { + // The output is in an HDR color space if its `ColorSpace` is one of the two + // Windows uses for HDR swap-chains: HDR10 / PQ (`G2084_NONE_P2020`) or + // scRGB / linear-extended-sRGB (`G10_NONE_P709`). Checking both ensures scRGB + // HDR is not misreported as SDR. + let high_dynamic_range = desc1.ColorSpace + == Dxgi::Common::DXGI_COLOR_SPACE_RGB_FULL_G2084_NONE_P2020 + || desc1.ColorSpace == Dxgi::Common::DXGI_COLOR_SPACE_RGB_FULL_G10_NONE_P709; + + let luminance = wgt::DisplayLuminance { + max_nits: Some(desc1.MaxLuminance), + max_full_frame_nits: Some(desc1.MaxFullFrameLuminance), + min_nits: Some(desc1.MinLuminance), + sdr_white_nits, + }; + + let chromaticity = wgt::DisplayChromaticity { + red: Some(desc1.RedPrimary), + green: Some(desc1.GreenPrimary), + blue: Some(desc1.BluePrimary), + white: Some(desc1.WhitePoint), + }; + + let coarse = wgt::DisplayCoarseRange { + high_dynamic_range: Some(high_dynamic_range), + gamut: classify_gamut(desc1.RedPrimary, desc1.GreenPrimary, desc1.BluePrimary), + }; + + // `headroom` is `None`: DXGI exposes absolute luminance (captured in + // `luminance`) rather than a relative headroom ratio. `bits_per_color` drops + // values that don't fit `u8`. + wgt::DisplayHdrInfo { + luminance: Some(luminance), + headroom: None, + chromaticity: Some(chromaticity), + coarse: Some(coarse), + bits_per_color: u8::try_from(desc1.BitsPerColor).ok(), + } +} + +/// A window's display HDR info, read through DXGI. +/// +/// Bundles the window's `HWND` with the DXGI factory used to query it. The factory +/// is built once and reused, rebuilt only when DXGI reports it stale; the monitor +/// lookup and adapter/output walk still run every call, since the window can move +/// between displays and the SDR white level changes at runtime. +pub struct DxgiHdrSource { + hwnd: HWND, + factory: Mutex<Option<Dxgi::IDXGIFactory1>>, +} + +// SAFETY: `HWND` and `IDXGIFactory1` are `!Send`/`!Sync` in windows-rs. The `HWND` +// is only ever read to run a DXGI query (fine from any thread), and the factory is +// free-threaded for the enumeration done here with the `Mutex` serializing access. +// This mirrors the manual `Send`/`Sync` on `dx12::Surface`. +unsafe impl Send for DxgiHdrSource {} +unsafe impl Sync for DxgiHdrSource {} + +impl DxgiHdrSource { + /// Creates a source for the window identified by `hwnd`. The `HWND` is + /// borrowed; using the source after that window is destroyed is undefined + /// behavior. + pub fn new(hwnd: HWND) -> Self { + Self { + hwnd, + factory: Mutex::new(None), + } + } + + /// Reads the window's [`wgt::DisplayHdrInfo`], or `None` if its monitor can't + /// be identified or queried (a headless or composition window, a + /// pre-Win10-1703 system without `IDXGIOutput6`, or a COM failure). Never + /// panics. + pub fn display_hdr_info(&self) -> Option<wgt::DisplayHdrInfo> { + let desc1 = self.output_desc1()?; + let sdr_white_nits = sdr_white_nits_for_monitor(desc1.Monitor); + Some(display_hdr_info_from_desc1(&desc1, sdr_white_nits)) + } + + /// The [`DXGI_OUTPUT_DESC1`] for the window's monitor, reusing the cached + /// factory unless DXGI reports it stale. + /// + /// [`DXGI_OUTPUT_DESC1`]: Dxgi::DXGI_OUTPUT_DESC1 + fn output_desc1(&self) -> Option<Dxgi::DXGI_OUTPUT_DESC1> { + let mut factory = self.factory.lock(); + + // A factory only enumerates the adapter/output topology it saw at + // creation, so rebuild it once it reports `IsCurrent() == false` (a + // monitor or GPU was plugged or unplugged). + // SAFETY: a cached factory is live; `IsCurrent` takes no caller pointers. + let need_new = factory + .as_ref() + .is_none_or(|f| !unsafe { f.IsCurrent() }.as_bool()); + if need_new { + // SAFETY: `CreateDXGIFactory1` takes no caller pointers; the `windows` + // binding fills the interface out-pointer itself. + match unsafe { Dxgi::CreateDXGIFactory1() } { + Ok(new) => *factory = Some(new), + Err(e) => { + log::warn!("CreateDXGIFactory1 failed: {e}"); + return None; + } + } + } + output_desc1_from_factory(factory.as_ref()?, self.hwnd) + } +} + +/// The [`DXGI_OUTPUT_DESC1`] for the monitor backing `wnd_handle`, found by +/// walking every adapter's outputs on `factory` — not just the rendering +/// adapter's, so the monitor is found on hybrid-GPU systems where the window sits +/// on a display wired to a different adapter. `None` if none match. +/// +/// [`DXGI_OUTPUT_DESC1`]: Dxgi::DXGI_OUTPUT_DESC1 +fn output_desc1_from_factory( + factory: &Dxgi::IDXGIFactory1, + wnd_handle: HWND, +) -> Option<Dxgi::DXGI_OUTPUT_DESC1> { + // SAFETY: `MonitorFromWindow` is sound for any `HWND`; an invalid one yields + // a null `HMONITOR`, checked below. + let hmonitor = unsafe { Gdi::MonitorFromWindow(wnd_handle, Gdi::MONITOR_DEFAULTTONEAREST) }; + if hmonitor.is_invalid() { + log::warn!("MonitorFromWindow failed; cannot identify the window's output"); + return None; + } + for adapter_index in 0.. { + // SAFETY: `factory` is live; `EnumAdapters1` takes only an index. + let adapter = match unsafe { factory.EnumAdapters1(adapter_index) } { + Ok(adapter) => adapter, + // End of the adapter list: the monitor matched none of them. + Err(e) if e.code() == Dxgi::DXGI_ERROR_NOT_FOUND => break, + Err(e) => { + log::warn!("IDXGIFactory1::EnumAdapters1 failed: {e}"); + break; + } + }; + for output_index in 0.. { + // SAFETY: `adapter` is live (from above); `EnumOutputs` takes only + // an index. + let output = match unsafe { adapter.EnumOutputs(output_index) } { + Ok(output) => output, + // End of this adapter's outputs: move on to the next adapter. + Err(e) if e.code() == Dxgi::DXGI_ERROR_NOT_FOUND => break, + Err(e) => { + log::warn!("IDXGIAdapter1::EnumOutputs failed: {e}"); + break; + } + }; + // SAFETY: `output` is live (from above); `GetDesc` returns a + // binding-owned `DXGI_OUTPUT_DESC` by value. + let desc = match unsafe { output.GetDesc() } { + Ok(desc) => desc, + Err(e) => { + log::warn!("IDXGIOutput::GetDesc failed: {e}"); + continue; + } + }; + if desc.Monitor != hmonitor { + continue; + } + // The window's monitor matched, so a failure past this point is a + // real anomaly. `IDXGIOutput6` (DXGI 1.6 / Win10 1703+) is required + // for `GetDesc1`. + let output6 = match output.cast::<Dxgi::IDXGIOutput6>() { + Ok(output6) => output6, + Err(e) => { + log::warn!("Casting to IDXGIOutput6 failed: {e}"); + return None; + } + }; + // SAFETY: `output6` is live (from the cast above); `GetDesc1` + // returns a binding-owned `DXGI_OUTPUT_DESC1` by value. + return match unsafe { output6.GetDesc1() } { + Ok(desc1) => Some(desc1), + Err(e) => { + log::warn!("IDXGIOutput6::GetDesc1 failed: {e}"); + None + } + }; + } + } + log::warn!("No DXGI output matches the window's monitor"); + None +} + +/// Best-effort SDR white level in nits for `hmonitor`, via the Windows +/// DisplayConfig API. Tracks the brightness slider, so it changes at runtime. +/// +/// This is the only [`wgt::DisplayLuminance`] field `GetDesc1` doesn't carry; it +/// bridges absolute nits and relative headroom. It lives in +/// `DISPLAYCONFIG_SDR_WHITE_LEVEL`, outside DXGI, so it needs its own query. +/// +/// Returns `None` on any failure (no match, query error, or a `0` reading). Never +/// panics. Pass [`Dxgi::DXGI_OUTPUT_DESC1::Monitor`] so the value matches the rest +/// of the `DisplayHdrInfo`. +fn sdr_white_nits_for_monitor(hmonitor: Gdi::HMONITOR) -> Option<f32> { + use windows::Win32::{ + Devices::Display::{ + DisplayConfigGetDeviceInfo, GetDisplayConfigBufferSizes, QueryDisplayConfig, + DISPLAYCONFIG_DEVICE_INFO_GET_SDR_WHITE_LEVEL, + DISPLAYCONFIG_DEVICE_INFO_GET_SOURCE_NAME, DISPLAYCONFIG_MODE_INFO, + DISPLAYCONFIG_PATH_INFO, DISPLAYCONFIG_SDR_WHITE_LEVEL, + DISPLAYCONFIG_SOURCE_DEVICE_NAME, QDC_ONLY_ACTIVE_PATHS, + }, + Foundation::ERROR_SUCCESS, + Graphics::Gdi::{GetMonitorInfoW, MONITORINFO, MONITORINFOEXW}, + }; + + // 1. HMONITOR -> GDI device name (e.g. `\\.\DISPLAY1`). + let mut monitor_info = MONITORINFOEXW::default(); + monitor_info.monitorInfo.cbSize = size_of::<MONITORINFOEXW>() as u32; + // `GetMonitorInfoW` takes a `*mut MONITORINFO`; the `EXW` variant is + // layout-compatible (it starts with `MONITORINFO`) and reports `cbSize`. + let lpmi = core::ptr::from_mut(&mut monitor_info).cast::<MONITORINFO>(); + // SAFETY: `lpmi` points at a live `MONITORINFOEXW` with `cbSize` set, which + // bounds the write; an invalid `hmonitor` just fails (handled below). + let got_info = unsafe { GetMonitorInfoW(hmonitor, lpmi) }; + if !got_info.as_bool() { + return None; + } + let gdi_device_name = monitor_info.szDevice; + + // 2. Enumerate the active DisplayConfig paths. + let mut path_count = 0u32; + let mut mode_count = 0u32; + // SAFETY: both out-params are live `u32`s; the call only writes the required + // buffer sizes into them. + if unsafe { + GetDisplayConfigBufferSizes(QDC_ONLY_ACTIVE_PATHS, &mut path_count, &mut mode_count) + } != ERROR_SUCCESS + { + return None; + } + let mut paths = alloc::vec![DISPLAYCONFIG_PATH_INFO::default(); path_count as usize]; + let mut modes = alloc::vec![DISPLAYCONFIG_MODE_INFO::default(); mode_count as usize]; + // SAFETY: `paths`/`modes` are sized to the counts reported above and passed + // with those counts, bounding the writes. + if unsafe { + QueryDisplayConfig( + QDC_ONLY_ACTIVE_PATHS, + &mut path_count, + paths.as_mut_ptr(), + &mut mode_count, + modes.as_mut_ptr(), + None, + ) + } != ERROR_SUCCESS + { + return None; + } + + // 3. Match the path whose source is this monitor, then read its target's + // SDR white level. `DisplayConfigGetDeviceInfo` returns a WIN32 code as + // `i32` (`0` == `ERROR_SUCCESS`). + for path in paths.iter().take(path_count as usize) { + let mut source = DISPLAYCONFIG_SOURCE_DEVICE_NAME::default(); + source.header.r#type = DISPLAYCONFIG_DEVICE_INFO_GET_SOURCE_NAME; + source.header.size = size_of::<DISPLAYCONFIG_SOURCE_DEVICE_NAME>() as u32; + source.header.adapterId = path.sourceInfo.adapterId; + source.header.id = path.sourceInfo.id; + // SAFETY: `source` is live with `header.type`/`header.size` set, which + // bounds the call's access to that struct. + if unsafe { DisplayConfigGetDeviceInfo(&mut source.header) } != ERROR_SUCCESS.0 as i32 { + continue; + } + if source.viewGdiDeviceName != gdi_device_name { + continue; + } + + let mut white = DISPLAYCONFIG_SDR_WHITE_LEVEL::default(); + white.header.r#type = DISPLAYCONFIG_DEVICE_INFO_GET_SDR_WHITE_LEVEL; + white.header.size = size_of::<DISPLAYCONFIG_SDR_WHITE_LEVEL>() as u32; + white.header.adapterId = path.targetInfo.adapterId; + white.header.id = path.targetInfo.id; + // SAFETY: `white` is live with `header.type`/`header.size` set, which + // bounds the call's access to that struct. + if unsafe { DisplayConfigGetDeviceInfo(&mut white.header) } != ERROR_SUCCESS.0 as i32 { + return None; + } + // `SDRWhiteLevel` encodes nits as `(nits / 80) * 1000`; `0` means the OS + // reported nothing usable. + return (white.SDRWhiteLevel > 0).then(|| white.SDRWhiteLevel as f32 * 80.0 / 1000.0); + } + None +} diff --git a/app/vendor/rune/vendor/wgpu-hal/src/auxil/dxgi/mod.rs b/app/vendor/rune/vendor/wgpu-hal/src/auxil/dxgi/mod.rs new file mode 100644 index 0000000..7a4bcc7 --- /dev/null +++ b/app/vendor/rune/vendor/wgpu-hal/src/auxil/dxgi/mod.rs @@ -0,0 +1,16 @@ +// Every module here is gated behind `dx12` except `hdr` (the +// `DXGI_OUTPUT_DESC1` -> `DisplayHdrInfo` mapping), which the +// Vulkan-on-Windows backend also uses. +#[cfg(dx12)] +pub mod conv; +#[cfg(dx12)] +pub mod exception; +#[cfg(dx12)] +pub mod factory; +pub mod hdr; +#[cfg(dx12)] +pub mod name; +#[cfg(dx12)] +pub mod result; +#[cfg(dx12)] +pub mod time; diff --git a/app/vendor/rune/vendor/wgpu-hal/src/auxil/dxgi/name.rs b/app/vendor/rune/vendor/wgpu-hal/src/auxil/dxgi/name.rs new file mode 100644 index 0000000..d120e4e --- /dev/null +++ b/app/vendor/rune/vendor/wgpu-hal/src/auxil/dxgi/name.rs @@ -0,0 +1,24 @@ +use windows::Win32::Graphics::Direct3D12::ID3D12Object; + +use crate::auxil::dxgi::result::HResult; + +/// Helper trait for setting the name of a D3D12 object. +/// +/// This is implemented on all types that can be converted to an [`ID3D12Object`]. +pub trait ObjectExt { + fn set_name(&self, name: &str) -> Result<(), crate::DeviceError>; +} + +impl<T> ObjectExt for T +where + // Windows impls `From` for all parent interfaces, so we can use that to convert to ID3D12Object. + // + // This includes implementations for references. + for<'a> &'a ID3D12Object: From<&'a T>, +{ + fn set_name(&self, name: &str) -> Result<(), crate::DeviceError> { + let name = windows::core::HSTRING::from(name); + let object: &ID3D12Object = self.into(); + unsafe { object.SetName(&name).into_device_result("SetName") } + } +} diff --git a/app/vendor/rune/vendor/wgpu-hal/src/auxil/dxgi/result.rs b/app/vendor/rune/vendor/wgpu-hal/src/auxil/dxgi/result.rs new file mode 100644 index 0000000..f3d77e2 --- /dev/null +++ b/app/vendor/rune/vendor/wgpu-hal/src/auxil/dxgi/result.rs @@ -0,0 +1,28 @@ +use windows::Win32::{Foundation, Graphics::Dxgi}; + +pub(crate) trait HResult<O> { + fn into_device_result(self, description: &str) -> Result<O, crate::DeviceError>; +} +impl<T> HResult<T> for windows::core::Result<T> { + fn into_device_result(self, description: &str) -> Result<T, crate::DeviceError> { + #![allow(unreachable_code)] + + self.map_err(|err| { + log::error!("{description} failed: {err}"); + + match err.code() { + Foundation::E_OUTOFMEMORY => crate::DeviceError::OutOfMemory, + Dxgi::DXGI_ERROR_DEVICE_RESET | Dxgi::DXGI_ERROR_DEVICE_REMOVED => { + #[cfg(feature = "device_lost_panic")] + panic!("{description} failed: Device lost ({err})"); + crate::DeviceError::Lost + } + _ => { + #[cfg(feature = "internal_error_panic")] + panic!("{description} failed: {err}"); + crate::DeviceError::Unexpected + } + } + }) + } +} diff --git a/app/vendor/rune/vendor/wgpu-hal/src/auxil/dxgi/time.rs b/app/vendor/rune/vendor/wgpu-hal/src/auxil/dxgi/time.rs new file mode 100644 index 0000000..b740612 --- /dev/null +++ b/app/vendor/rune/vendor/wgpu-hal/src/auxil/dxgi/time.rs @@ -0,0 +1,97 @@ +#![allow(dead_code, reason = "IPresentationManager is unused currently")] + +use windows::Win32::System::Performance::{QueryPerformanceCounter, QueryPerformanceFrequency}; + +pub enum PresentationTimer { + /// DXGI uses [`QueryPerformanceCounter()`] + Dxgi { + /// How many ticks of QPC per second + frequency: u64, + }, + /// [`IPresentationManager`] uses [`QueryInterruptTimePrecise()`] + /// + /// [`IPresentationManager`]: https://microsoft.github.io/windows-docs-rs/doc/windows/Win32/Graphics/CompositionSwapchain/struct.IPresentationManager.html + /// [`QueryInterruptTimePrecise()`]: https://microsoft.github.io/windows-docs-rs/doc/windows/Win32/System/WindowsProgramming/fn.QueryInterruptTimePrecise.html + #[allow(non_snake_case)] + IPresentationManager { + fnQueryInterruptTimePrecise: unsafe extern "system" fn(*mut u64), + }, +} + +impl core::fmt::Debug for PresentationTimer { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + match *self { + Self::Dxgi { frequency } => f + .debug_struct("DXGI") + .field("frequency", &frequency) + .finish(), + Self::IPresentationManager { + fnQueryInterruptTimePrecise, + } => f + .debug_struct("IPresentationManager") + .field( + "QueryInterruptTimePrecise", + &(fnQueryInterruptTimePrecise as usize), + ) + .finish(), + } + } +} + +impl PresentationTimer { + /// Create a presentation timer using QueryPerformanceFrequency (what DXGI uses for presentation times) + pub fn new_dxgi() -> Self { + let mut frequency = 0; + unsafe { QueryPerformanceFrequency(&mut frequency) }.unwrap(); + + Self::Dxgi { + frequency: frequency + .try_into() + .expect("Frequency should not be negative"), + } + } + + /// Create a presentation timer using QueryInterruptTimePrecise (what IPresentationManager uses for presentation times) + /// + /// Panics if QueryInterruptTimePrecise isn't found (below Win10) + pub fn new_ipresentation_manager() -> Self { + // We need to load this explicitly, as QueryInterruptTimePrecise is only available on Windows 10+ + // + // Docs say it's in kernel32.dll, but it's actually in kernelbase.dll. + // api-ms-win-core-realtime-l1-1-1.dll + let kernelbase = + libloading::os::windows::Library::open_already_loaded("kernelbase.dll").unwrap(); + // No concerns about lifetimes here as kernelbase is always there. + let ptr = unsafe { + kernelbase + .get(c"QueryInterruptTimePrecise".to_bytes()) + .unwrap() + }; + Self::IPresentationManager { + fnQueryInterruptTimePrecise: *ptr, + } + } + + /// Gets the current time in nanoseconds. + pub fn get_timestamp_ns(&self) -> u128 { + // Always do u128 math _after_ hitting the timing function. + match *self { + PresentationTimer::Dxgi { frequency } => { + let mut counter = 0; + unsafe { QueryPerformanceCounter(&mut counter) }.unwrap(); + + // counter * (1_000_000_000 / freq) but re-ordered to make more precise + (counter as u128 * 1_000_000_000) / frequency as u128 + } + PresentationTimer::IPresentationManager { + fnQueryInterruptTimePrecise, + } => { + let mut counter = 0; + unsafe { fnQueryInterruptTimePrecise(&mut counter) }; + + // QueryInterruptTimePrecise uses units of 100ns for its tick. + counter as u128 * 100 + } + } + } +} diff --git a/app/vendor/rune/vendor/wgpu-hal/src/auxil/mod.rs b/app/vendor/rune/vendor/wgpu-hal/src/auxil/mod.rs new file mode 100644 index 0000000..599b7d0 --- /dev/null +++ b/app/vendor/rune/vendor/wgpu-hal/src/auxil/mod.rs @@ -0,0 +1,241 @@ +// Mostly DX12-only, but also compiled for Vulkan-on-Windows, which reuses +// `dxgi::hdr` to query display HDR info. The DX12-only submodules stay gated +// behind `dx12` in `dxgi/mod.rs`. +#[cfg(any(dx12, all(vulkan, windows)))] +pub(super) mod dxgi; + +#[cfg(all(native, feature = "renderdoc"))] +pub(super) mod renderdoc; + +pub mod db { + pub mod amd { + /// cbindgen:ignore + pub const VENDOR: u32 = 0x1002; + } + pub mod apple { + /// cbindgen:ignore + pub const VENDOR: u32 = 0x106B; + } + pub mod arm { + /// cbindgen:ignore + pub const VENDOR: u32 = 0x13B5; + } + pub mod broadcom { + /// cbindgen:ignore + pub const VENDOR: u32 = 0x14E4; + } + pub mod imgtec { + /// cbindgen:ignore + pub const VENDOR: u32 = 0x1010; + } + pub mod intel { + /// cbindgen:ignore + pub const VENDOR: u32 = 0x8086; + pub const DEVICE_KABY_LAKE_MASK: u32 = 0x5900; + pub const DEVICE_SKY_LAKE_MASK: u32 = 0x1900; + } + pub mod mesa { + // Mesa does not actually have a PCI vendor id. + // + // To match Vulkan, we use the VkVendorId for Mesa in the gles backend so that lavapipe (Vulkan) and + // llvmpipe (OpenGL) have the same vendor id. + /// cbindgen:ignore + pub const VENDOR: u32 = 0x10005; + } + pub mod nvidia { + /// cbindgen:ignore + pub const VENDOR: u32 = 0x10DE; + } + pub mod qualcomm { + /// cbindgen:ignore + pub const VENDOR: u32 = 0x5143; + } +} + +/// Maximum binding size for the shaders that only support `i32` indexing. +/// Interestingly, the index itself can't reach that high, because the minimum +/// element size is 4 bytes, but the compiler toolchain still computes the +/// offset at some intermediate point, internally, as i32. +pub const MAX_I32_BINDING_SIZE: u32 = (1 << 31) - 1; + +pub use wgpu_naga_bridge::map_naga_stage; + +impl crate::CopyExtent { + pub fn map_extent_to_copy_size(extent: &wgt::Extent3d, dim: wgt::TextureDimension) -> Self { + Self { + width: extent.width, + height: extent.height, + depth: match dim { + wgt::TextureDimension::D1 | wgt::TextureDimension::D2 => 1, + wgt::TextureDimension::D3 => extent.depth_or_array_layers, + }, + } + } + + pub fn min(&self, other: &Self) -> Self { + Self { + width: self.width.min(other.width), + height: self.height.min(other.height), + depth: self.depth.min(other.depth), + } + } + + // Get the copy size at a specific mipmap level. This doesn't make most sense, + // since the copy extents are provided *for* a mipmap level to start with. + // But backends use `CopyExtent` more sparingly, and this piece is shared. + pub fn at_mip_level(&self, level: u32) -> Self { + Self { + width: (self.width >> level).max(1), + height: (self.height >> level).max(1), + depth: (self.depth >> level).max(1), + } + } +} + +impl crate::TextureCopyBase { + pub fn max_copy_size(&self, full_size: &crate::CopyExtent) -> crate::CopyExtent { + let mip = full_size.at_mip_level(self.mip_level); + crate::CopyExtent { + width: mip.width - self.origin.x, + height: mip.height - self.origin.y, + depth: mip.depth - self.origin.z, + } + } +} + +impl crate::BufferTextureCopy { + pub fn clamp_size_to_virtual(&mut self, full_size: &crate::CopyExtent) { + let max_size = self.texture_base.max_copy_size(full_size); + self.size = self.size.min(&max_size); + } +} + +impl crate::TextureCopy { + pub fn clamp_size_to_virtual( + &mut self, + full_src_size: &crate::CopyExtent, + full_dst_size: &crate::CopyExtent, + ) { + let max_src_size = self.src_base.max_copy_size(full_src_size); + let max_dst_size = self.dst_base.max_copy_size(full_dst_size); + self.size = self.size.min(&max_src_size).min(&max_dst_size); + } +} + +/// Adjust `limits` to honor HAL-imposed maximums and comply with WebGPU's +/// adapter capability guarantees. +#[cfg_attr(not(any_backend), allow(dead_code))] +pub(crate) fn adjust_raw_limits(mut limits: wgt::Limits) -> wgt::Limits { + // Apply hal limits. + limits.max_bind_groups = limits.max_bind_groups.min(crate::MAX_BIND_GROUPS as u32); + limits.max_vertex_buffers = limits + .max_vertex_buffers + .min(crate::MAX_VERTEX_BUFFERS as u32); + // Once we allow the 2 limits above to be higher than 24 we should use + // `cap_limits_to_be_under_the_sum_limit` to cap them under + // `max_bind_groups_plus_vertex_buffers`. + const { assert!(crate::MAX_BIND_GROUPS + crate::MAX_VERTEX_BUFFERS == 24) }; + limits.max_bind_groups_plus_vertex_buffers = limits.max_bind_groups_plus_vertex_buffers.min(24); + limits.max_color_attachments = limits + .max_color_attachments + .min(crate::MAX_COLOR_ATTACHMENTS as u32); + + // Adjust limits according to WebGPU adapter capability guarantees. + // See <https://gpuweb.github.io/gpuweb/#adapter-capability-guarantees>. + + // WebGPU requires maxBindingsPerBindGroup to be at least the sum of all + // per-stage limits multiplied with the maximum shader stages per pipeline. + // + // Since backends already report their maximum maxBindingsPerBindGroup, + // we need to lower all per-stage limits to satisfy this guarantee. + const MAX_SHADER_STAGES_PER_PIPELINE: u32 = 2; + let max_per_stage_resources = + limits.max_bindings_per_bind_group / MAX_SHADER_STAGES_PER_PIPELINE; + + cap_limits_to_be_under_the_sum_limit( + [ + &mut limits.max_sampled_textures_per_shader_stage, + &mut limits.max_uniform_buffers_per_shader_stage, + &mut limits.max_storage_textures_per_shader_stage, + &mut limits.max_storage_buffers_per_shader_stage, + &mut limits.max_samplers_per_shader_stage, + &mut limits.max_acceleration_structures_per_shader_stage, + ], + max_per_stage_resources, + ); + + // Not required by the spec but dynamic buffers count + // towards non-dynamic buffer limits as well. + limits.max_dynamic_uniform_buffers_per_pipeline_layout = limits + .max_dynamic_uniform_buffers_per_pipeline_layout + .min(limits.max_uniform_buffers_per_shader_stage); + limits.max_dynamic_storage_buffers_per_pipeline_layout = limits + .max_dynamic_storage_buffers_per_pipeline_layout + .min(limits.max_storage_buffers_per_shader_stage); + + limits.min_uniform_buffer_offset_alignment = limits.min_uniform_buffer_offset_alignment.max(32); + limits.min_storage_buffer_offset_alignment = limits.min_storage_buffer_offset_alignment.max(32); + + limits.max_uniform_buffer_binding_size = limits + .max_uniform_buffer_binding_size + .min(limits.max_buffer_size); + limits.max_storage_buffer_binding_size = limits + .max_storage_buffer_binding_size + .min(limits.max_buffer_size); + + limits.max_storage_buffer_binding_size &= !(u64::from(wgt::STORAGE_BINDING_SIZE_ALIGNMENT) - 1); + limits.max_vertex_buffer_array_stride &= !(wgt::VERTEX_ALIGNMENT as u32 - 1); + + let x = limits.max_compute_workgroup_size_x; + let y = limits.max_compute_workgroup_size_y; + let z = limits.max_compute_workgroup_size_z; + let m = limits.max_compute_invocations_per_workgroup; + limits.max_compute_workgroup_size_x = x.min(m); + limits.max_compute_workgroup_size_y = y.min(m); + limits.max_compute_workgroup_size_z = z.min(m); + limits.max_compute_invocations_per_workgroup = m.min(x.saturating_mul(y).saturating_mul(z)); + + limits.max_immediate_size = limits.max_immediate_size.min(256); + + limits +} + +/// Evenly allocates space to each limit, +/// capping them only if strictly necessary. +pub fn cap_limits_to_be_under_the_sum_limit<const N: usize>( + mut limits: [&mut u32; N], + sum_limit: u32, +) { + limits.sort(); + + let mut rem_limit = sum_limit; + let mut divisor = limits.len() as u32; + for limit_to_adjust in limits { + let limit = rem_limit / divisor; + *limit_to_adjust = (*limit_to_adjust).min(limit); + rem_limit -= *limit_to_adjust; + divisor -= 1; + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_cap_limits_to_be_under_the_sum_limit() { + test([3, 3, 3], 3, [1, 1, 1]); + test([3, 2, 1], 3, [1, 1, 1]); + test([1, 2, 3], 6, [1, 2, 3]); + test([1, 2, 3], 3, [1, 1, 1]); + test([1, 8, 100], 6, [1, 2, 3]); + test([2, 80, 80], 6, [2, 2, 2]); + test([2, 80, 80], 12, [2, 5, 5]); + + #[track_caller] + fn test<const N: usize>(mut input: [u32; N], limit: u32, output: [u32; N]) { + cap_limits_to_be_under_the_sum_limit(input.each_mut(), limit); + assert_eq!(input, output); + } + } +} diff --git a/app/vendor/rune/vendor/wgpu-hal/src/auxil/renderdoc.rs b/app/vendor/rune/vendor/wgpu-hal/src/auxil/renderdoc.rs new file mode 100644 index 0000000..52fa2b0 --- /dev/null +++ b/app/vendor/rune/vendor/wgpu-hal/src/auxil/renderdoc.rs @@ -0,0 +1,141 @@ +//! RenderDoc integration - <https://renderdoc.org/> +#![cfg_attr(not(any(feature = "gles", feature = "vulkan")), allow(dead_code))] + +use alloc::format; +use alloc::string::String; +use core::{ffi, ptr}; + +/// The dynamically loaded RenderDoc API function table +#[repr(C)] +#[derive(Debug)] +pub struct RenderDocApi { + api: renderdoc_sys::RENDERDOC_API_1_4_1, + lib: libloading::Library, +} + +unsafe impl Send for RenderDocApi {} +unsafe impl Sync for RenderDocApi {} + +/// RenderDoc API type +#[derive(Debug)] +pub enum RenderDoc { + /// RenderDoc functionality is available + Available { + /// RenderDoc API with function pointers + api: RenderDocApi, + }, + /// RenderDoc functionality is _not_ available + NotAvailable { + /// A description why renderdoc functionality is not available + reason: String, + }, +} + +// TODO: replace with libloading API once supported +#[cfg(unix)] +const RTLD_NOLOAD: i32 = 0x4; + +impl RenderDoc { + pub unsafe fn new() -> Self { + type GetApiFn = unsafe extern "C" fn(version: u32, out: *mut *mut ffi::c_void) -> i32; + + #[cfg(windows)] + let renderdoc_filename = "renderdoc.dll"; + #[cfg(all(unix, not(target_os = "android")))] + let renderdoc_filename = "librenderdoc.so"; + #[cfg(target_os = "android")] + let renderdoc_filename = "libVkLayer_GLES_RenderDoc.so"; + + #[cfg(unix)] + let renderdoc_result: Result<libloading::Library, libloading::Error> = unsafe { + libloading::os::unix::Library::open( + Some(renderdoc_filename), + libloading::os::unix::RTLD_NOW | RTLD_NOLOAD, + ) + } + .map(|lib| lib.into()); + + #[cfg(windows)] + let renderdoc_result: Result<libloading::Library, libloading::Error> = + libloading::os::windows::Library::open_already_loaded(renderdoc_filename) + .map(|lib| lib.into()); + + let renderdoc_lib = match renderdoc_result { + Ok(lib) => lib, + Err(e) => { + return RenderDoc::NotAvailable { + reason: format!( + "Unable to load renderdoc library '{renderdoc_filename}': {e:?}" + ), + } + } + }; + + let get_api: libloading::Symbol<GetApiFn> = + match unsafe { renderdoc_lib.get(c"RENDERDOC_GetAPI".to_bytes()) } { + Ok(api) => api, + Err(e) => { + return RenderDoc::NotAvailable { + reason: format!( + "Unable to get RENDERDOC_GetAPI from renderdoc library '{renderdoc_filename}': {e:?}" + ), + } + } + }; + let mut obj = ptr::null_mut(); + match unsafe { get_api(10401, &mut obj) } { + 1 => RenderDoc::Available { + api: RenderDocApi { + api: unsafe { *obj.cast::<renderdoc_sys::RENDERDOC_API_1_4_1>() }, + lib: renderdoc_lib, + }, + }, + return_value => RenderDoc::NotAvailable { + reason: format!( + "Unable to get API from renderdoc library '{renderdoc_filename}': {return_value}" + ), + }, + } + } +} + +impl Default for RenderDoc { + fn default() -> Self { + if !cfg!(debug_assertions) { + return RenderDoc::NotAvailable { + reason: "RenderDoc support is only enabled with 'debug_assertions'".into(), + }; + } + unsafe { Self::new() } + } +} +/// An implementation specific handle +pub type Handle = *mut ffi::c_void; + +impl RenderDoc { + /// Start a RenderDoc frame capture + pub unsafe fn start_frame_capture(&self, device_handle: Handle, window_handle: Handle) -> bool { + match *self { + Self::Available { api: ref entry } => { + unsafe { entry.api.StartFrameCapture.unwrap()(device_handle, window_handle) }; + true + } + Self::NotAvailable { ref reason } => { + log::warn!("Could not start RenderDoc frame capture: {reason}"); + false + } + } + } + + /// End a RenderDoc frame capture + pub unsafe fn end_frame_capture(&self, device_handle: Handle, window_handle: Handle) { + match *self { + Self::Available { api: ref entry } => { + unsafe { entry.api.EndFrameCapture.unwrap()(device_handle, window_handle) }; + } + Self::NotAvailable { ref reason } => { + log::warn!("Could not end RenderDoc frame capture: {reason}") + } + }; + } +} diff --git a/app/vendor/rune/vendor/wgpu-hal/src/dx12/adapter.rs b/app/vendor/rune/vendor/wgpu-hal/src/dx12/adapter.rs new file mode 100644 index 0000000..fd5a64e --- /dev/null +++ b/app/vendor/rune/vendor/wgpu-hal/src/dx12/adapter.rs @@ -0,0 +1,1548 @@ +use alloc::{string::String, sync::Arc, vec::Vec}; +use core::{ptr, sync::atomic::AtomicU64}; +use std::thread; + +use parking_lot::Mutex; +use windows::{ + core::Interface as _, + Win32::{ + Devices::DeviceAndDriverInstallation::{ + SetupDiDestroyDeviceInfoList, SetupDiEnumDeviceInfo, SetupDiGetClassDevsW, + SetupDiGetDeviceRegistryPropertyW, DIGCF_PRESENT, GUID_DEVCLASS_DISPLAY, HDEVINFO, + SPDRP_ADDRESS, SPDRP_BUSNUMBER, SPDRP_HARDWAREID, SP_DEVINFO_DATA, + }, + Foundation::{GetLastError, ERROR_NO_MORE_ITEMS}, + Graphics::{Direct3D, Direct3D12, Dxgi}, + UI::WindowsAndMessaging, + }, +}; + +use super::D3D12Lib; +use crate::{ + auxil::{ + self, + dxgi::{factory::DxgiAdapter, result::HResult}, + }, + dx12::{ + dcomp::DCompLib, device_creation::DeviceFactory, shader_compilation, FeatureLevel, + ShaderModel, SurfaceTarget, + }, +}; + +impl Drop for super::Adapter { + fn drop(&mut self) { + // Debug tracking alive objects + if !thread::panicking() + && self + .private_caps + .instance_flags + .contains(wgt::InstanceFlags::VALIDATION) + { + unsafe { + self.report_live_objects(); + } + } + } +} + +impl super::Adapter { + pub unsafe fn report_live_objects(&self) { + if let Ok(debug_device) = self.raw.cast::<Direct3D12::ID3D12DebugDevice>() { + unsafe { + debug_device.ReportLiveDeviceObjects( + Direct3D12::D3D12_RLDO_SUMMARY | Direct3D12::D3D12_RLDO_IGNORE_INTERNAL, + ) + } + .unwrap() + } + } + + pub fn raw_adapter(&self) -> &DxgiAdapter { + &self.raw + } + + #[allow(clippy::too_many_arguments)] + pub(super) fn expose( + adapter: DxgiAdapter, + library: &Arc<D3D12Lib>, + device_factory: &Arc<DeviceFactory>, + dcomp_lib: &Arc<DCompLib>, + instance_flags: wgt::InstanceFlags, + memory_budget_thresholds: wgt::MemoryBudgetThresholds, + compiler_container: Arc<shader_compilation::CompilerContainer>, + backend_options: wgt::Dx12BackendOptions, + telemetry: Option<crate::Telemetry>, + ) -> Option<crate::ExposedAdapter<super::Api>> { + let desc = unsafe { adapter.GetDesc2() }.unwrap(); + let driver_version = unsafe { adapter.CheckInterfaceSupport(&Dxgi::IDXGIDevice::IID) }; + let driver_version = driver_version + .map(|driver_version| { + let driver_version = driver_version as u64; + [ + (driver_version >> 48) as u16, + (driver_version >> 32) as u16, + (driver_version >> 16) as u16, + driver_version as u16, + ] + }) + .map_err(|e| e.code()); + + // Create the device so that we can get the capabilities. + let res = { + profiling::scope!("ID3D12Device::create_device"); + device_factory.create_device(library, &adapter, Direct3D::D3D_FEATURE_LEVEL_11_0) + }; + if let Some(telemetry) = telemetry { + if let Err(err) = res { + (telemetry.d3d12_expose_adapter)( + &desc, + driver_version, + crate::D3D12ExposeAdapterResult::CreateDeviceError(err), + ); + } + } + let device = res.ok()?; + + profiling::scope!("feature queries"); + + // Detect the highest supported feature level. + let d3d_feature_level = [ + Direct3D::D3D_FEATURE_LEVEL_12_2, + Direct3D::D3D_FEATURE_LEVEL_12_1, + Direct3D::D3D_FEATURE_LEVEL_12_0, + Direct3D::D3D_FEATURE_LEVEL_11_1, + Direct3D::D3D_FEATURE_LEVEL_11_0, + ]; + let mut device_levels = Direct3D12::D3D12_FEATURE_DATA_FEATURE_LEVELS { + NumFeatureLevels: d3d_feature_level.len() as u32, + pFeatureLevelsRequested: d3d_feature_level.as_ptr().cast(), + MaxSupportedFeatureLevel: Default::default(), + }; + unsafe { + device.CheckFeatureSupport( + Direct3D12::D3D12_FEATURE_FEATURE_LEVELS, + <*mut _>::cast(&mut device_levels), + size_of_val(&device_levels) as u32, + ) + } + .unwrap(); + let max_feature_level = match device_levels.MaxSupportedFeatureLevel { + Direct3D::D3D_FEATURE_LEVEL_11_0 => FeatureLevel::V11_0, + Direct3D::D3D_FEATURE_LEVEL_11_1 => FeatureLevel::V11_1, + Direct3D::D3D_FEATURE_LEVEL_12_0 => FeatureLevel::V12_0, + Direct3D::D3D_FEATURE_LEVEL_12_1 => FeatureLevel::V12_1, + Direct3D::D3D_FEATURE_LEVEL_12_2 => FeatureLevel::V12_2, + fl => { + if let Some(telemetry) = telemetry { + (telemetry.d3d12_expose_adapter)( + &desc, + driver_version, + crate::D3D12ExposeAdapterResult::UnknownFeatureLevel(fl.0), + ); + } + return None; + } + }; + + let device_name = auxil::dxgi::conv::map_adapter_name(desc.Description); + + let mut features_architecture = Direct3D12::D3D12_FEATURE_DATA_ARCHITECTURE::default(); + + unsafe { + device.CheckFeatureSupport( + Direct3D12::D3D12_FEATURE_ARCHITECTURE, + <*mut _>::cast(&mut features_architecture), + size_of_val(&features_architecture) as u32, + ) + } + .unwrap(); + + let mut features1 = Direct3D12::D3D12_FEATURE_DATA_D3D12_OPTIONS1::default(); + let hr = unsafe { + device.CheckFeatureSupport( + Direct3D12::D3D12_FEATURE_D3D12_OPTIONS1, + <*mut _>::cast(&mut features1), + size_of_val(&features1) as u32, + ) + }; + + let mut workarounds = super::Workarounds::default(); + + let is_warp = device_name.contains("Microsoft Basic Render Driver"); + + // WARP uses two different versioning schemes. Versions that ship with windows + // use a version that starts with 10.x.x.x. Versions that ship from Nuget use 1.0.x.x. + // + // As far as we know, this is only an issue on the Nuget versions. + if let Ok(driver_version) = driver_version { + if is_warp && driver_version >= [1, 0, 13, 0] && driver_version[0] < 10 { + workarounds.avoid_shader_debug_info = true; + } + } + + let driver_version_string = { + let driver_version = driver_version.unwrap_or([0, 0, 0, 0]); + format!( + "{}.{}.{}.{}", + driver_version[0], driver_version[1], driver_version[2], driver_version[3] + ) + }; + + let info = wgt::AdapterInfo { + backend: wgt::Backend::Dx12, + name: device_name, + vendor: desc.VendorId, + device: desc.DeviceId, + device_type: if Dxgi::DXGI_ADAPTER_FLAG(desc.Flags as i32) + .contains(Dxgi::DXGI_ADAPTER_FLAG_SOFTWARE) + { + wgt::DeviceType::Cpu + } else if features_architecture.UMA.as_bool() { + wgt::DeviceType::IntegratedGpu + } else { + wgt::DeviceType::DiscreteGpu + }, + device_pci_bus_id: get_adapter_pci_info(desc.VendorId, desc.DeviceId), + driver: driver_version_string, + driver_info: String::new(), + subgroup_min_size: features1.WaveLaneCountMin, + subgroup_max_size: features1.WaveLaneCountMax, + transient_saves_memory: Some(false), + limit_bucket: None, + }; + + let mut options = Direct3D12::D3D12_FEATURE_DATA_D3D12_OPTIONS::default(); + unsafe { + device.CheckFeatureSupport( + Direct3D12::D3D12_FEATURE_D3D12_OPTIONS, + <*mut _>::cast(&mut options), + size_of_val(&options) as u32, + ) + } + .unwrap(); + + /// Resource Binding Tiers: https://learn.microsoft.com/en-us/windows/win32/direct3d12/hardware-support#limits-dependant-on-hardware + #[derive(PartialEq, Eq, PartialOrd, Ord)] + enum ResourceBindingTier { + T1, + T2, + T3, + } + let rbt = match options.ResourceBindingTier { + Direct3D12::D3D12_RESOURCE_BINDING_TIER_1 => ResourceBindingTier::T1, + Direct3D12::D3D12_RESOURCE_BINDING_TIER_2 => ResourceBindingTier::T2, + tier if tier.0 >= Direct3D12::D3D12_RESOURCE_BINDING_TIER_3.0 => { + ResourceBindingTier::T3 + } + other => { + log::debug!("Got zero or negative value for resource binding tier {other:?}"); + ResourceBindingTier::T1 + } + }; + + if rbt == ResourceBindingTier::T1 { + if let Some(telemetry) = telemetry { + (telemetry.d3d12_expose_adapter)( + &desc, + driver_version, + crate::D3D12ExposeAdapterResult::ResourceBindingTier2Requirement, + ); + } + // We require Tier 2 or higher for the ability to make samplers bindless in all cases. + return None; + } + + let _depth_bounds_test_supported = { + let mut features2 = Direct3D12::D3D12_FEATURE_DATA_D3D12_OPTIONS2::default(); + unsafe { + device.CheckFeatureSupport( + Direct3D12::D3D12_FEATURE_D3D12_OPTIONS2, + <*mut _>::cast(&mut features2), + size_of_val(&features2) as u32, + ) + } + .is_ok() + && features2.DepthBoundsTestSupported.as_bool() + }; + + let (casting_fully_typed_format_supported, view_instancing) = { + let mut features3 = Direct3D12::D3D12_FEATURE_DATA_D3D12_OPTIONS3::default(); + if unsafe { + device.CheckFeatureSupport( + Direct3D12::D3D12_FEATURE_D3D12_OPTIONS3, + <*mut _>::cast(&mut features3), + size_of_val(&features3) as u32, + ) + } + .is_ok() + { + ( + features3.CastingFullyTypedFormatSupported.as_bool(), + features3.ViewInstancingTier.0 >= Direct3D12::D3D12_VIEW_INSTANCING_TIER_1.0, + ) + } else { + (false, false) + } + }; + + let heap_create_not_zeroed = { + // For D3D12_HEAP_FLAG_CREATE_NOT_ZEROED we just need to + // make sure that options7 can be queried. See also: + // https://devblogs.microsoft.com/directx/coming-to-directx-12-more-control-over-memory-allocation/ + let mut features7 = Direct3D12::D3D12_FEATURE_DATA_D3D12_OPTIONS7::default(); + unsafe { + device.CheckFeatureSupport( + Direct3D12::D3D12_FEATURE_D3D12_OPTIONS7, + <*mut _>::cast(&mut features7), + size_of_val(&features7) as u32, + ) + } + .is_ok() + }; + + let unrestricted_buffer_texture_copy_pitch_supported = { + let mut features13 = Direct3D12::D3D12_FEATURE_DATA_D3D12_OPTIONS13::default(); + unsafe { + device.CheckFeatureSupport( + Direct3D12::D3D12_FEATURE_D3D12_OPTIONS13, + <*mut _>::cast(&mut features13), + size_of_val(&features13) as u32, + ) + } + .is_ok() + && features13 + .UnrestrictedBufferTextureCopyPitchSupported + .as_bool() + }; + + let mut max_sampler_descriptor_heap_size = + Direct3D12::D3D12_MAX_SHADER_VISIBLE_SAMPLER_HEAP_SIZE; + { + let mut features19 = Direct3D12::D3D12_FEATURE_DATA_D3D12_OPTIONS19::default(); + let res = unsafe { + device.CheckFeatureSupport( + Direct3D12::D3D12_FEATURE_D3D12_OPTIONS19, + <*mut _>::cast(&mut features19), + size_of_val(&features19) as u32, + ) + }; + + // Sometimes on Windows 11 23H2, the function returns success, even though the runtime + // does not know about `Options19`. This can cause this number to be 0 as the structure isn't written to. + // This value is nonsense and creating zero-sized sampler heaps can cause drivers to explode. + // As as we're guaranteed 2048 anyway, we make sure this value is not under 2048. + // + // https://github.com/gfx-rs/wgpu/issues/7053 + let is_ok = res.is_ok(); + let is_above_minimum = features19.MaxSamplerDescriptorHeapSize + > Direct3D12::D3D12_MAX_SHADER_VISIBLE_SAMPLER_HEAP_SIZE; + if is_ok && is_above_minimum { + max_sampler_descriptor_heap_size = features19.MaxSamplerDescriptorHeapSize; + } + }; + + let mut shader_models_after_5_1 = [ + Direct3D12::D3D_SHADER_MODEL_6_9, + Direct3D12::D3D_SHADER_MODEL_6_8, + Direct3D12::D3D_SHADER_MODEL_6_7, + Direct3D12::D3D_SHADER_MODEL_6_6, + Direct3D12::D3D_SHADER_MODEL_6_5, + Direct3D12::D3D_SHADER_MODEL_6_4, + Direct3D12::D3D_SHADER_MODEL_6_3, + Direct3D12::D3D_SHADER_MODEL_6_2, + Direct3D12::D3D_SHADER_MODEL_6_1, + Direct3D12::D3D_SHADER_MODEL_6_0, + ] + .iter(); + let max_device_shader_model = loop { + if let Some(&sm) = shader_models_after_5_1.next() { + let mut sm = Direct3D12::D3D12_FEATURE_DATA_SHADER_MODEL { + HighestShaderModel: sm, + }; + if unsafe { + device.CheckFeatureSupport( + Direct3D12::D3D12_FEATURE_SHADER_MODEL, + <*mut _>::cast(&mut sm), + size_of_val(&sm) as u32, + ) + } + .is_ok() + { + break match sm.HighestShaderModel { + Direct3D12::D3D_SHADER_MODEL_5_1 => ShaderModel::V5_1, + Direct3D12::D3D_SHADER_MODEL_6_0 => ShaderModel::V6_0, + Direct3D12::D3D_SHADER_MODEL_6_1 => ShaderModel::V6_1, + Direct3D12::D3D_SHADER_MODEL_6_2 => ShaderModel::V6_2, + Direct3D12::D3D_SHADER_MODEL_6_3 => ShaderModel::V6_3, + Direct3D12::D3D_SHADER_MODEL_6_4 => ShaderModel::V6_4, + Direct3D12::D3D_SHADER_MODEL_6_5 => ShaderModel::V6_5, + Direct3D12::D3D_SHADER_MODEL_6_6 => ShaderModel::V6_6, + Direct3D12::D3D_SHADER_MODEL_6_7 => ShaderModel::V6_7, + Direct3D12::D3D_SHADER_MODEL_6_8 => ShaderModel::V6_8, + Direct3D12::D3D_SHADER_MODEL_6_9 => ShaderModel::V6_9, + _ => unreachable!(), + }; + } + } else { + break ShaderModel::V5_1; + } + }; + + let wgt_shader_model = backend_options + .force_shader_model + .get() + .or(compiler_container.max_shader_model()); + + let shader_model = if let Some(max_shader_model) = wgt_shader_model { + let max_dxc_shader_model = match max_shader_model { + wgt::DxcShaderModel::V6_0 => ShaderModel::V6_0, + wgt::DxcShaderModel::V6_1 => ShaderModel::V6_1, + wgt::DxcShaderModel::V6_2 => ShaderModel::V6_2, + wgt::DxcShaderModel::V6_3 => ShaderModel::V6_3, + wgt::DxcShaderModel::V6_4 => ShaderModel::V6_4, + wgt::DxcShaderModel::V6_5 => ShaderModel::V6_5, + wgt::DxcShaderModel::V6_6 => ShaderModel::V6_6, + wgt::DxcShaderModel::V6_7 => ShaderModel::V6_7, + wgt::DxcShaderModel::V6_8 => ShaderModel::V6_8, + wgt::DxcShaderModel::V6_9 => ShaderModel::V6_9, + }; + + let shader_model = max_device_shader_model.min(max_dxc_shader_model); + + match shader_model { + ShaderModel::V5_1 => { + if let Some(telemetry) = telemetry { + (telemetry.d3d12_expose_adapter)( + &desc, + driver_version, + crate::D3D12ExposeAdapterResult::ShaderModel6Requirement, + ); + } + // don't expose this adapter if it doesn't support DXIL + return None; + } + ShaderModel::V6_0 => naga::back::hlsl::ShaderModel::V6_0, + ShaderModel::V6_1 => naga::back::hlsl::ShaderModel::V6_1, + ShaderModel::V6_2 => naga::back::hlsl::ShaderModel::V6_2, + ShaderModel::V6_3 => naga::back::hlsl::ShaderModel::V6_3, + ShaderModel::V6_4 => naga::back::hlsl::ShaderModel::V6_4, + ShaderModel::V6_5 => naga::back::hlsl::ShaderModel::V6_5, + ShaderModel::V6_6 => naga::back::hlsl::ShaderModel::V6_6, + ShaderModel::V6_7 => naga::back::hlsl::ShaderModel::V6_7, + ShaderModel::V6_8 => naga::back::hlsl::ShaderModel::V6_8, + ShaderModel::V6_9 => naga::back::hlsl::ShaderModel::V6_9, + } + } else { + naga::back::hlsl::ShaderModel::V5_1 + }; + let private_caps = super::PrivateCapabilities { + instance_flags, + workarounds, + heterogeneous_resource_heaps: options.ResourceHeapTier + != Direct3D12::D3D12_RESOURCE_HEAP_TIER_1, + memory_architecture: if features_architecture.UMA.as_bool() { + super::MemoryArchitecture::Unified { + cache_coherent: features_architecture.CacheCoherentUMA.as_bool(), + } + } else { + super::MemoryArchitecture::NonUnified + }, + heap_create_not_zeroed, + casting_fully_typed_format_supported, + // See https://github.com/gfx-rs/wgpu/issues/3552 + suballocation_supported: !info.name.contains("Iris(R) Xe"), + shader_model, + max_sampler_descriptor_heap_size, + unrestricted_buffer_texture_copy_pitch_supported, + }; + + // these should always be available on d3d12 + let mut features = wgt::Features::empty() + | wgt::Features::DEPTH_CLIP_CONTROL + | wgt::Features::DEPTH32FLOAT_STENCIL8 + | wgt::Features::INDIRECT_FIRST_INSTANCE + | wgt::Features::MAPPABLE_PRIMARY_BUFFERS + | wgt::Features::MULTI_DRAW_INDIRECT_COUNT + | wgt::Features::ADDRESS_MODE_CLAMP_TO_BORDER + | wgt::Features::ADDRESS_MODE_CLAMP_TO_ZERO + | wgt::Features::POLYGON_MODE_LINE + | wgt::Features::TEXTURE_ADAPTER_SPECIFIC_FORMAT_FEATURES + | wgt::Features::TIMESTAMP_QUERY + | wgt::Features::TIMESTAMP_QUERY_INSIDE_ENCODERS + | wgt::Features::TIMESTAMP_QUERY_INSIDE_PASSES + | wgt::Features::TEXTURE_COMPRESSION_BC + | wgt::Features::TEXTURE_COMPRESSION_BC_SLICED_3D + | wgt::Features::CLEAR_TEXTURE + | wgt::Features::TEXTURE_FORMAT_16BIT_NORM + | wgt::Features::IMMEDIATES + | wgt::Features::PRIMITIVE_INDEX + | wgt::Features::RG11B10UFLOAT_RENDERABLE + | wgt::Features::DUAL_SOURCE_BLENDING + | wgt::Features::TEXTURE_FORMAT_NV12 + | wgt::Features::FLOAT32_FILTERABLE + | wgt::Features::FLOAT32_BLENDABLE + | wgt::Features::TEXTURE_ATOMIC + | wgt::Features::PASSTHROUGH_SHADERS + | wgt::Features::EXTERNAL_TEXTURE + | wgt::Features::MEMORY_DECORATION_COHERENT; + + //TODO: in order to expose this, we need to run a compute shader + // that extract the necessary statistics out of the D3D12 result. + // Alternatively, we could allocate a buffer for the query set, + // write the results there, and issue a bunch of copy commands. + //| wgt::Features::PIPELINE_STATISTICS_QUERY + + if max_feature_level >= FeatureLevel::V11_1 { + features |= wgt::Features::VERTEX_WRITABLE_STORAGE; + } + + features.set( + wgt::Features::CONSERVATIVE_RASTERIZATION, + options.ConservativeRasterizationTier + != Direct3D12::D3D12_CONSERVATIVE_RASTERIZATION_TIER_NOT_SUPPORTED, + ); + + features.set( + wgt::Features::TEXTURE_BINDING_ARRAY + | wgt::Features::STORAGE_RESOURCE_BINDING_ARRAY + | wgt::Features::STORAGE_TEXTURE_ARRAY_NON_UNIFORM_INDEXING + | wgt::Features::SAMPLED_TEXTURE_AND_STORAGE_BUFFER_ARRAY_NON_UNIFORM_INDEXING + // See note below the table https://learn.microsoft.com/en-us/windows/win32/direct3d12/hardware-support + | wgt::Features::PARTIALLY_BOUND_BINDING_ARRAY, + shader_model >= naga::back::hlsl::ShaderModel::V5_1 && rbt >= ResourceBindingTier::T3, + ); + + let bgra8unorm_storage_supported = { + let mut bgra8unorm_info = Direct3D12::D3D12_FEATURE_DATA_FORMAT_SUPPORT { + Format: Dxgi::Common::DXGI_FORMAT_B8G8R8A8_UNORM, + ..Default::default() + }; + let hr = unsafe { + device.CheckFeatureSupport( + Direct3D12::D3D12_FEATURE_FORMAT_SUPPORT, + <*mut _>::cast(&mut bgra8unorm_info), + size_of_val(&bgra8unorm_info) as u32, + ) + }; + hr.is_ok() + && bgra8unorm_info + .Support2 + .contains(Direct3D12::D3D12_FORMAT_SUPPORT2_UAV_TYPED_STORE) + }; + features.set( + wgt::Features::BGRA8UNORM_STORAGE, + bgra8unorm_storage_supported, + ); + + let p010_format_supported = { + let mut p010_info = Direct3D12::D3D12_FEATURE_DATA_FORMAT_SUPPORT { + Format: Dxgi::Common::DXGI_FORMAT_P010, + ..Default::default() + }; + let hr = unsafe { + device.CheckFeatureSupport( + Direct3D12::D3D12_FEATURE_FORMAT_SUPPORT, + <*mut _>::cast(&mut p010_info), + size_of_val(&p010_info) as u32, + ) + }; + if hr.is_ok() { + let supports_texture2d = p010_info + .Support1 + .contains(Direct3D12::D3D12_FORMAT_SUPPORT1_TEXTURE2D); + let supports_shader_load = p010_info + .Support1 + .contains(Direct3D12::D3D12_FORMAT_SUPPORT1_SHADER_LOAD); + let supports_shader_sample = p010_info + .Support1 + .contains(Direct3D12::D3D12_FORMAT_SUPPORT1_SHADER_SAMPLE); + supports_texture2d && supports_shader_load && supports_shader_sample + } else { + false + } + }; + features.set(wgt::Features::TEXTURE_FORMAT_P010, p010_format_supported); + + features.set( + wgt::Features::SHADER_INT64, + shader_model >= naga::back::hlsl::ShaderModel::V6_0 + && hr.is_ok() + && features1.Int64ShaderOps.as_bool(), + ); + + let float16_supported = { + let mut features4 = Direct3D12::D3D12_FEATURE_DATA_D3D12_OPTIONS4::default(); + let hr = unsafe { + device.CheckFeatureSupport( + Direct3D12::D3D12_FEATURE_D3D12_OPTIONS4, // https://learn.microsoft.com/en-us/windows/win32/api/d3d12/ne-d3d12-d3d12_feature#syntax + ptr::from_mut(&mut features4).cast(), + size_of::<Direct3D12::D3D12_FEATURE_DATA_D3D12_OPTIONS4>() as _, + ) + }; + hr.is_ok() && features4.Native16BitShaderOpsSupported.as_bool() + }; + + features.set( + wgt::Features::SHADER_F16, + shader_model >= naga::back::hlsl::ShaderModel::V6_2 && float16_supported, + ); + features.set( + wgt::Features::SHADER_I16, + shader_model >= naga::back::hlsl::ShaderModel::V6_2 && float16_supported, + ); + + features.set( + wgt::Features::SUBGROUP, + shader_model >= naga::back::hlsl::ShaderModel::V6_0 + && hr.is_ok() + && features1.WaveOps.as_bool(), + ); + let mut features5 = Direct3D12::D3D12_FEATURE_DATA_D3D12_OPTIONS5::default(); + let has_features5 = unsafe { + device.CheckFeatureSupport( + Direct3D12::D3D12_FEATURE_D3D12_OPTIONS5, + <*mut _>::cast(&mut features5), + size_of_val(&features5) as u32, + ) + } + .is_ok(); + + // Once ray tracing pipelines are supported they also will go here + let supports_ray_tracing = features5.RaytracingTier.0 + >= Direct3D12::D3D12_RAYTRACING_TIER_1_1.0 + && shader_model >= naga::back::hlsl::ShaderModel::V6_5 + && has_features5; + + features.set( + wgt::Features::EXPERIMENTAL_RAY_QUERY + | wgt::Features::EXTENDED_ACCELERATION_STRUCTURE_VERTEX_FORMATS, + supports_ray_tracing, + ); + + // Binding arrays of TLAS are supported on D3D12 when ray tracing is supported. + // + // This flag is used for shader-side `binding_array<acceleration_structure>` as well as + // allowing `BindGroupLayoutEntry::count = Some(...)` for `BindingType::AccelerationStructure`. + features.set( + wgt::Features::ACCELERATION_STRUCTURE_BINDING_ARRAY, + supports_ray_tracing, + ); + + // Check for Int64 atomic support on buffers. This is very convoluted, but is based on a conservative reading + // of https://microsoft.github.io/DirectX-Specs/d3d/HLSL_SM_6_6_Int64_and_Float_Atomics.html#integer-64-bit-capabilities. + let atomic_int64_buffers; + let atomic_int64_textures; + { + let mut features9 = Direct3D12::D3D12_FEATURE_DATA_D3D12_OPTIONS9::default(); + let hr9 = unsafe { + device.CheckFeatureSupport( + Direct3D12::D3D12_FEATURE_D3D12_OPTIONS9, + <*mut _>::cast(&mut features9), + size_of_val(&features9) as u32, + ) + } + .is_ok(); + + let mut features11 = Direct3D12::D3D12_FEATURE_DATA_D3D12_OPTIONS11::default(); + let hr11 = unsafe { + device.CheckFeatureSupport( + Direct3D12::D3D12_FEATURE_D3D12_OPTIONS11, + <*mut _>::cast(&mut features11), + size_of_val(&features11) as u32, + ) + } + .is_ok(); + + atomic_int64_buffers = hr9 && hr11 && hr.is_ok() + // Int64 atomics show up in SM6.6. + && shader_model >= naga::back::hlsl::ShaderModel::V6_6 + // They require Int64 to be available in the shader at all. + && features1.Int64ShaderOps.as_bool() + // As our RWByteAddressBuffers can exist on both descriptor heaps and + // as root descriptors, we need to ensure that both cases are supported. + // base SM6.6 only guarantees Int64 atomics on resources in root descriptors. + && features11.AtomicInt64OnDescriptorHeapResourceSupported.as_bool() + // Our Int64 atomic caps currently require groupshared. This + // prevents Intel or Qcomm from using Int64 currently. + // https://github.com/gfx-rs/wgpu/issues/8666 + && features9.AtomicInt64OnGroupSharedSupported.as_bool(); + + atomic_int64_textures = hr9 && hr11 && hr.is_ok() + // Int64 atomics show up in SM6.6. + && shader_model >= naga::back::hlsl::ShaderModel::V6_6 + // They require Int64 to be available in the shader at all. + && features1.Int64ShaderOps.as_bool() + // Textures are typed resources, so we need this flag. + && features9.AtomicInt64OnTypedResourceSupported.as_bool() + // As textures can only exist in descriptor heaps, we require this. + // However, all architectures that support atomics on typed resources + // support this as well, so this is somewhat redundant. + && features11.AtomicInt64OnDescriptorHeapResourceSupported.as_bool(); + }; + features.set( + wgt::Features::SHADER_INT64_ATOMIC_ALL_OPS | wgt::Features::SHADER_INT64_ATOMIC_MIN_MAX, + atomic_int64_buffers, + ); + features.set(wgt::Features::TEXTURE_INT64_ATOMIC, atomic_int64_textures); + let mesh_shader_supported = { + let mut features7 = Direct3D12::D3D12_FEATURE_DATA_D3D12_OPTIONS7::default(); + unsafe { + device.CheckFeatureSupport( + Direct3D12::D3D12_FEATURE_D3D12_OPTIONS7, + <*mut _>::cast(&mut features7), + size_of_val(&features7) as u32, + ) + } + .is_ok() + && features7.MeshShaderTier != Direct3D12::D3D12_MESH_SHADER_TIER_NOT_SUPPORTED + && shader_model >= naga::back::hlsl::ShaderModel::V6_5 + }; + features.set( + wgt::Features::EXPERIMENTAL_MESH_SHADER, + mesh_shader_supported, + ); + let shader_barycentrics_supported = { + let mut features3 = Direct3D12::D3D12_FEATURE_DATA_D3D12_OPTIONS3::default(); + unsafe { + device.CheckFeatureSupport( + Direct3D12::D3D12_FEATURE_D3D12_OPTIONS3, + <*mut _>::cast(&mut features3), + size_of_val(&features3) as u32, + ) + } + .is_ok() + && features3.BarycentricsSupported.as_bool() + && shader_model >= naga::back::hlsl::ShaderModel::V6_1 + }; + features.set( + wgt::Features::SHADER_BARYCENTRICS | wgt::Features::SHADER_PER_VERTEX, + shader_barycentrics_supported, + ); + + features.set( + wgt::Features::MULTIVIEW, + view_instancing && shader_model >= naga::back::hlsl::ShaderModel::V6_1, + ); + features.set( + wgt::Features::SELECTIVE_MULTIVIEW, + view_instancing && shader_model >= naga::back::hlsl::ShaderModel::V6_1, + ); + + features.set( + wgt::Features::EXPERIMENTAL_MESH_SHADER_MULTIVIEW, + mesh_shader_supported + && view_instancing + && shader_model >= naga::back::hlsl::ShaderModel::V6_1, + ); + + // TODO: Determine if IPresentationManager is supported + let presentation_timer = auxil::dxgi::time::PresentationTimer::new_dxgi(); + + let downlevel = wgt::DownlevelCapabilities::default(); + + // Limits that must share D3D12's root signature size of + // D3D12_MAX_ROOT_COST 64 DWORDS (256 bytes). + // + // Root constants and root tables use 1 DWORD. + // Root descriptors use 2 DWORDs. + // Source: https://learn.microsoft.com/en-us/windows/win32/direct3d12/root-signature-limits#memory-limits-and-costs + // + // Per pipeline layout: + // - RootElement::Immediates, 32 root constants + // (bounded by maxImmediateSize) = 32 x 4 bytes = 128 bytes + // - RootElement::SamplerHeapDescriptorTable, a descriptor table = 4 bytes + // - RootElement::SpecialConstantBuffer, 3 root constants = 3 x 4 bytes = 12 bytes + // - RootElement::DynamicStorageBufferOffsets, a root constant per dynamic storage buffer + // (bounded by maxDynamicStorageBuffersPerPipelineLayout) = 4 x 4 bytes = 16 bytes + // - RootElement::DynamicUniformBuffer, a root descriptor per dynamic uniform buffer + // (bounded by maxDynamicUniformBuffersPerPipelineLayout) = 8 x 8 bytes = 64 bytes + // Per bind group: + // - RootElement::DescriptorTable, a descriptor table + // (bounded by maxBindGroups) = 8 x 4 bytes = 32 bytes + // + // Source: logic in `create_pipeline_layout` + // + // Total: 128 + 4 + 12 + 16 + 64 + 32 = 256 bytes + // + let max_immediate_size = super::MAX_IMMEDIATE_SIZE; + let max_bind_groups = 8; + let max_dynamic_uniform_buffers_per_pipeline_layout = 8; + let max_dynamic_storage_buffers_per_pipeline_layout = 4; + + // "Maximum number of descriptors in a Constant Buffer View (CBV), Shader Resource View (SRV), or Unordered Access View(UAV) heap used for rendering" + let full_heap_count = match rbt { + ResourceBindingTier::T1 | ResourceBindingTier::T2 => 1_000_000, + // 1_000_000+ + ResourceBindingTier::T3 => { + // Theoretically vram limited, but in practice 2^20 is the limit + 1 << 20 + } + }; + + // "Maximum number of Constant Buffer Views in all descriptor tables per shader stage" + let max_uniform_buffers_per_shader_stage = match rbt { + ResourceBindingTier::T1 | ResourceBindingTier::T2 => 14, + _ => full_heap_count, + }; + + // "Maximum number of Shader Resource Views in all descriptor tables per shader stage" + let mut max_srv_per_shader_stage = match rbt { + ResourceBindingTier::T1 => 128, + _ => full_heap_count, + }; + + // We use an extra SRV for all samplers in a bind group. + // See comment in `create_pipeline_layout`. + max_srv_per_shader_stage -= max_bind_groups; + + // If we also support acceleration structures these are shared so we must halve it. + // It's unlikely that this affects anything because most devices that support ray tracing + // probably have a higher binding tier than one. + let mut max_sampled_textures_per_shader_stage = if supports_ray_tracing { + max_srv_per_shader_stage / 2 + } else { + max_srv_per_shader_stage + }; + let mut max_acceleration_structures_per_shader_stage = if supports_ray_tracing { + max_srv_per_shader_stage / 2 + } else { + 0 + }; + + // "Maximum number of Unordered Access Views in all descriptor tables across all stages" + let max_uav_across_all_stages = match rbt { + ResourceBindingTier::T1 => match max_feature_level { + FeatureLevel::V11_0 => 8, + _ => 64, + }, + ResourceBindingTier::T2 => 64, + ResourceBindingTier::T3 => full_heap_count, + }; + const MAX_SHADER_STAGES_PER_PIPELINE: u32 = 2; + // We must share the UAV limit across both storage resource limits. + let max_uav_per_shader_stage = max_uav_across_all_stages / MAX_SHADER_STAGES_PER_PIPELINE; + let max_storage_textures_per_shader_stage = max_uav_per_shader_stage / 2; + let mut max_storage_buffers_per_shader_stage = max_uav_per_shader_stage / 2; + + // WebGPU storage buffers count as 1 SRV if they are read-only + // or as 1 UAV if they are read-write. See comment in + // `create_pipeline_layout`. Make sure we don't exceed + // the maximum number of SRVs for the relevant limits. + auxil::cap_limits_to_be_under_the_sum_limit( + [ + &mut max_sampled_textures_per_shader_stage, + &mut max_acceleration_structures_per_shader_stage, + &mut max_storage_buffers_per_shader_stage, + ], + max_srv_per_shader_stage, + ); + + // "Maximum number of Samplers in all descriptor tables per shader stage" + let max_samplers_per_shader_stage = match rbt { + ResourceBindingTier::T1 => 16, + _ => 2048, + }; + + // See https://microsoft.github.io/DirectX-Specs/d3d/ViewInstancing.html#maximum-viewinstancecount + let max_multiview_view_count = if view_instancing { 4 } else { 0 }; + + if let Some(telemetry) = telemetry { + (telemetry.d3d12_expose_adapter)( + &desc, + driver_version, + crate::D3D12ExposeAdapterResult::Success( + max_feature_level, + max_device_shader_model, + ), + ); + } + + // Source: https://microsoft.github.io/DirectX-Specs/d3d/MeshShader.html#dispatchmesh-api + let max_task_mesh_workgroup_total_count = if mesh_shader_supported { + 2u32.pow(22) + } else { + 0 + }; + // Technically it says "64k" but I highly doubt they want 65536 for compute and exactly 64,000 for task workgroups + let max_task_mesh_workgroups_per_dimension = if mesh_shader_supported { + Direct3D12::D3D12_CS_DISPATCH_MAX_THREAD_GROUPS_PER_DIMENSION + } else { + 0 + }; + + Some(crate::ExposedAdapter { + adapter: super::Adapter { + raw: adapter, + device, + library: Arc::clone(library), + dcomp_lib: Arc::clone(dcomp_lib), + private_caps, + presentation_timer, + memory_budget_thresholds, + compiler_container, + options: backend_options, + }, + info, + features, + capabilities: crate::Capabilities { + limits: auxil::adjust_raw_limits(wgt::Limits { + // + // WebGPU LIMITS: + // Based on https://gpuweb.github.io/gpuweb/correspondence/#limits + // + // 16384 + max_texture_dimension_1d: Direct3D12::D3D12_REQ_TEXTURE1D_U_DIMENSION, + // 16384 + max_texture_dimension_2d: Direct3D12::D3D12_REQ_TEXTURE2D_U_OR_V_DIMENSION + .min(Direct3D12::D3D12_REQ_TEXTURECUBE_DIMENSION), + // 2048 + max_texture_dimension_3d: Direct3D12::D3D12_REQ_TEXTURE3D_U_V_OR_W_DIMENSION, + // 2048 + max_texture_array_layers: Direct3D12::D3D12_REQ_TEXTURE2D_ARRAY_AXIS_DIMENSION, + // No limit. + max_bind_groups_plus_vertex_buffers: u32::MAX, + // No limit. + max_bindings_per_bind_group: u32::MAX, + max_sampled_textures_per_shader_stage, + max_samplers_per_shader_stage, + max_storage_textures_per_shader_stage, + max_storage_buffers_per_shader_stage, + max_uniform_buffers_per_shader_stage, + // See `InputSlot` param docs: https://learn.microsoft.com/en-ca/windows/win32/api/d3d12/ns-d3d12-d3d12_input_element_desc + max_vertex_buffers: 16, + // Dx12 does not expose a maximum buffer size in the API. + // This limit is chosen to avoid potential issues with drivers should they internally + // store buffer sizes using 32 bit ints (a situation we have already encountered with vulkan). + max_buffer_size: i32::MAX as u64, + max_storage_buffer_binding_size: auxil::MAX_I32_BINDING_SIZE as u64, + // 65536 + max_uniform_buffer_binding_size: + Direct3D12::D3D12_REQ_CONSTANT_BUFFER_ELEMENT_COUNT as u64 * 16, + // 256 + min_uniform_buffer_offset_alignment: + Direct3D12::D3D12_CONSTANT_BUFFER_DATA_PLACEMENT_ALIGNMENT, + // 16 + min_storage_buffer_offset_alignment: + Direct3D12::D3D12_RAW_UAV_SRV_BYTE_ALIGNMENT, + // 30 + max_vertex_attributes: Direct3D12::D3D12_IA_VERTEX_INPUT_RESOURCE_SLOT_COUNT + - 2, // -2 for `SV_VertexID` and `SV_InstanceID` + // 2048 + max_vertex_buffer_array_stride: Direct3D12::D3D12_SO_BUFFER_MAX_STRIDE_IN_BYTES, + // 31 + max_inter_stage_shader_variables: Direct3D12::D3D12_VS_OUTPUT_REGISTER_COUNT + .min(Direct3D12::D3D12_PS_INPUT_REGISTER_COUNT) + - 1, // - 1 for position + max_immediate_size, + max_bind_groups, + max_dynamic_uniform_buffers_per_pipeline_layout, + max_dynamic_storage_buffers_per_pipeline_layout, + // 8 + max_color_attachments: Direct3D12::D3D12_SIMULTANEOUS_RENDER_TARGET_COUNT, + // 128 (No documented limit) + max_color_attachment_bytes_per_sample: + Direct3D12::D3D12_SIMULTANEOUS_RENDER_TARGET_COUNT + * wgt::TextureFormat::MAX_TARGET_PIXEL_BYTE_COST, + // From: https://microsoft.github.io/DirectX-Specs/d3d/archive/D3D11_3_FunctionalSpec.htm#18.6.6%20Inter-Thread%20Data%20Sharing + max_compute_workgroup_storage_size: 32768, + // 1024 + max_compute_invocations_per_workgroup: + Direct3D12::D3D12_CS_THREAD_GROUP_MAX_THREADS_PER_GROUP, + // 1024 + max_compute_workgroup_size_x: Direct3D12::D3D12_CS_THREAD_GROUP_MAX_X, + // 1024 + max_compute_workgroup_size_y: Direct3D12::D3D12_CS_THREAD_GROUP_MAX_Y, + // 64 + max_compute_workgroup_size_z: Direct3D12::D3D12_CS_THREAD_GROUP_MAX_Z, + // 65535 + max_compute_workgroups_per_dimension: + Direct3D12::D3D12_CS_DISPATCH_MAX_THREAD_GROUPS_PER_DIMENSION, + // + // NATIVE (Non-WebGPU) LIMITS: + // + max_non_sampler_bindings: 1_000_000, + max_binding_array_elements_per_shader_stage: full_heap_count, + max_binding_array_sampler_elements_per_shader_stage: + Direct3D12::D3D12_MAX_SHADER_VISIBLE_SAMPLER_HEAP_SIZE, + + max_task_workgroup_total_count: max_task_mesh_workgroup_total_count, + max_task_workgroups_per_dimension: max_task_mesh_workgroups_per_dimension, + max_mesh_workgroup_total_count: max_task_mesh_workgroup_total_count, + max_mesh_workgroups_per_dimension: max_task_mesh_workgroups_per_dimension, + + // Source: https://microsoft.github.io/DirectX-Specs/d3d/MeshShader.html#dispatchmesh-api + // Assume this inherits from compute shaders + max_task_invocations_per_workgroup: if mesh_shader_supported { + Direct3D12::D3D12_CS_4_X_THREAD_GROUP_MAX_THREADS_PER_GROUP + } else { + 0 + }, + max_task_invocations_per_dimension: if mesh_shader_supported { + Direct3D12::D3D12_CS_THREAD_GROUP_MAX_Z + } else { + 0 + }, + // Source: https://microsoft.github.io/DirectX-Specs/d3d/MeshShader.html#amplification-shader-and-mesh-shader + max_mesh_invocations_per_workgroup: if mesh_shader_supported { 128 } else { 0 }, + max_mesh_invocations_per_dimension: if mesh_shader_supported { 128 } else { 0 }, + + max_task_payload_size: if mesh_shader_supported { 16384 } else { 0 }, + max_mesh_output_vertices: if mesh_shader_supported { 256 } else { 0 }, + max_mesh_output_primitives: if mesh_shader_supported { 256 } else { 0 }, + // Source: https://microsoft.github.io/DirectX-Specs/d3d/MeshShader.html#sv_rendertargetarrayindex-limitations-based-on-queryable-capability + max_mesh_output_layers: if mesh_shader_supported { 8 } else { 0 }, + max_mesh_multiview_view_count: if mesh_shader_supported { + max_multiview_view_count + } else { + 0 + }, + + max_blas_primitive_count: if supports_ray_tracing { + 1 << 29 // 2^29 + } else { + 0 + }, + max_blas_geometry_count: if supports_ray_tracing { + 1 << 24 // 2^24 + } else { + 0 + }, + max_tlas_instance_count: if supports_ray_tracing { + 1 << 24 // 2^24 + } else { + 0 + }, + max_acceleration_structures_per_shader_stage, + max_buffers_and_acceleration_structures_per_shader_stage: u32::MAX, + max_binding_array_acceleration_structure_elements_per_shader_stage: + max_acceleration_structures_per_shader_stage, + max_multiview_view_count, + + // not yet implemented + max_ray_dispatch_count: 0, + max_ray_recursion_depth: 0, + }), + alignments: crate::Alignments { + buffer_copy_offset: wgt::BufferSize::new( + Direct3D12::D3D12_TEXTURE_DATA_PLACEMENT_ALIGNMENT as u64, + ) + .unwrap(), + buffer_copy_pitch: wgt::BufferSize::new( + Direct3D12::D3D12_TEXTURE_DATA_PITCH_ALIGNMENT as u64, + ) + .unwrap(), + // Direct3D correctly bounds-checks all array accesses: + // https://microsoft.github.io/DirectX-Specs/d3d/archive/D3D11_3_FunctionalSpec.htm#18.6.8.2%20Device%20Memory%20Reads + uniform_bounds_check_alignment: wgt::BufferSize::new(1).unwrap(), + raw_tlas_instance_size: u32::try_from(size_of::< + Direct3D12::D3D12_RAYTRACING_INSTANCE_DESC, + >()) + .unwrap(), + ray_tracing_scratch_buffer_alignment: + Direct3D12::D3D12_RAYTRACING_ACCELERATION_STRUCTURE_BYTE_ALIGNMENT, + // Not yet implemented + ray_tracing_pipeline_group_data_size: 0, + ray_tracing_pipeline_group_data_alignment: 0, + ray_tracing_pipeline_data_offset_alignment: 0, + }, + downlevel, + cooperative_matrix_properties: Vec::new(), + }, + }) + } +} + +impl crate::Adapter for super::Adapter { + type A = super::Api; + + unsafe fn open( + &self, + features: wgt::Features, + limits: &wgt::Limits, + memory_hints: &wgt::MemoryHints, + ) -> Result<crate::OpenDevice<super::Api>, crate::DeviceError> { + let queue: Direct3D12::ID3D12CommandQueue = { + profiling::scope!("ID3D12Device::CreateCommandQueue"); + unsafe { + self.device + .CreateCommandQueue(&Direct3D12::D3D12_COMMAND_QUEUE_DESC { + Type: Direct3D12::D3D12_COMMAND_LIST_TYPE_DIRECT, + Priority: Direct3D12::D3D12_COMMAND_QUEUE_PRIORITY_NORMAL.0, + Flags: Direct3D12::D3D12_COMMAND_QUEUE_FLAG_NONE, + NodeMask: 0, + }) + } + .into_device_result("Queue creation")? + }; + + let device = super::Device::new( + self.raw.clone(), + self.device.clone(), + queue.clone(), + features, + limits, + memory_hints, + self.private_caps, + &self.library, + &self.dcomp_lib, + self.memory_budget_thresholds, + self.compiler_container.clone(), + self.options.clone(), + )?; + let idle_fence: Direct3D12::ID3D12Fence = unsafe { + self.device + .CreateFence(0, Direct3D12::D3D12_FENCE_FLAG_NONE) + } + .into_device_result("Queue idle fence creation")?; + let idle_event = super::Event::create(false, false)?; + + let drain = Arc::clone(&device.shared.drain); + Ok(crate::OpenDevice { + device, + queue: super::Queue { + raw: queue, + temp_lists: Mutex::new(Vec::new()), + idle_fence, + idle_event, + idle_fence_value: AtomicU64::new(0), + pending_waits: Mutex::new(Vec::new()), + pending_signals: Mutex::new(Vec::new()), + drain, + }, + }) + } + + unsafe fn texture_format_capabilities( + &self, + format: wgt::TextureFormat, + ) -> crate::TextureFormatCapabilities { + use crate::TextureFormatCapabilities as Tfc; + + let raw_format = match auxil::dxgi::conv::map_texture_format_failable(format) { + Some(f) => f, + None => return Tfc::empty(), + }; + let srv_uav_format = if format.is_combined_depth_stencil_format() { + auxil::dxgi::conv::map_texture_format_for_srv_uav( + format, + // use the depth aspect here as opposed to stencil since it has more capabilities + crate::FormatAspects::DEPTH, + ) + } else { + auxil::dxgi::conv::map_texture_format_for_srv_uav( + format, + crate::FormatAspects::from(format), + ) + } + .unwrap(); + + let mut data = Direct3D12::D3D12_FEATURE_DATA_FORMAT_SUPPORT { + Format: raw_format, + ..Default::default() + }; + unsafe { + self.device.CheckFeatureSupport( + Direct3D12::D3D12_FEATURE_FORMAT_SUPPORT, + <*mut _>::cast(&mut data), + size_of_val(&data) as u32, + ) + } + .unwrap(); + + // Because we use a different format for SRV and UAV views of depth textures, we need to check + // the features that use SRV/UAVs using the no-depth format. + let mut data_srv_uav = Direct3D12::D3D12_FEATURE_DATA_FORMAT_SUPPORT { + Format: srv_uav_format, + Support1: Direct3D12::D3D12_FORMAT_SUPPORT1_NONE, + Support2: Direct3D12::D3D12_FORMAT_SUPPORT2_NONE, + }; + if raw_format != srv_uav_format { + // Only-recheck if we're using a different format + unsafe { + self.device.CheckFeatureSupport( + Direct3D12::D3D12_FEATURE_FORMAT_SUPPORT, + ptr::addr_of_mut!(data_srv_uav).cast(), + size_of::<Direct3D12::D3D12_FEATURE_DATA_FORMAT_SUPPORT>() as u32, + ) + } + .unwrap(); + } else { + // Same format, just copy over. + data_srv_uav = data; + } + + let mut caps = Tfc::COPY_SRC | Tfc::COPY_DST; + // Cannot use the contains() helper, and windows-rs doesn't provide a .intersect() helper + let is_texture = (data.Support1 + & (Direct3D12::D3D12_FORMAT_SUPPORT1_TEXTURE1D + | Direct3D12::D3D12_FORMAT_SUPPORT1_TEXTURE2D + | Direct3D12::D3D12_FORMAT_SUPPORT1_TEXTURE3D + | Direct3D12::D3D12_FORMAT_SUPPORT1_TEXTURECUBE)) + .0 + != 0; + // SRVs use srv_uav_format + caps.set( + Tfc::SAMPLED, + is_texture + && data_srv_uav + .Support1 + .contains(Direct3D12::D3D12_FORMAT_SUPPORT1_SHADER_LOAD), + ); + caps.set( + Tfc::SAMPLED_LINEAR, + data_srv_uav + .Support1 + .contains(Direct3D12::D3D12_FORMAT_SUPPORT1_SHADER_SAMPLE), + ); + caps.set( + Tfc::COLOR_ATTACHMENT, + data.Support1 + .contains(Direct3D12::D3D12_FORMAT_SUPPORT1_RENDER_TARGET), + ); + caps.set( + Tfc::COLOR_ATTACHMENT_BLEND, + data.Support1 + .contains(Direct3D12::D3D12_FORMAT_SUPPORT1_BLENDABLE), + ); + caps.set( + Tfc::DEPTH_STENCIL_ATTACHMENT, + data.Support1 + .contains(Direct3D12::D3D12_FORMAT_SUPPORT1_DEPTH_STENCIL), + ); + // UAVs use srv_uav_format + caps.set( + Tfc::STORAGE_READ_ONLY, + data_srv_uav + .Support2 + .contains(Direct3D12::D3D12_FORMAT_SUPPORT2_UAV_TYPED_LOAD), + ); + caps.set( + Tfc::STORAGE_ATOMIC, + data_srv_uav + .Support2 + .contains(Direct3D12::D3D12_FORMAT_SUPPORT2_UAV_ATOMIC_UNSIGNED_MIN_OR_MAX), + ); + caps.set( + Tfc::STORAGE_WRITE_ONLY, + data_srv_uav + .Support2 + .contains(Direct3D12::D3D12_FORMAT_SUPPORT2_UAV_TYPED_STORE), + ); + caps.set( + Tfc::STORAGE_READ_WRITE, + caps.contains(Tfc::STORAGE_READ_ONLY | Tfc::STORAGE_WRITE_ONLY), + ); + + // We load via UAV/SRV so use srv_uav_format + let no_msaa_load = caps.contains(Tfc::SAMPLED) + && !data_srv_uav + .Support1 + .contains(Direct3D12::D3D12_FORMAT_SUPPORT1_MULTISAMPLE_LOAD); + + let no_msaa_target = (data.Support1 + & (Direct3D12::D3D12_FORMAT_SUPPORT1_RENDER_TARGET + | Direct3D12::D3D12_FORMAT_SUPPORT1_DEPTH_STENCIL)) + .0 + != 0 + && !data + .Support1 + .contains(Direct3D12::D3D12_FORMAT_SUPPORT1_MULTISAMPLE_RENDERTARGET); + + caps.set( + Tfc::MULTISAMPLE_RESOLVE, + data.Support1 + .contains(Direct3D12::D3D12_FORMAT_SUPPORT1_MULTISAMPLE_RESOLVE), + ); + + let mut ms_levels = Direct3D12::D3D12_FEATURE_DATA_MULTISAMPLE_QUALITY_LEVELS { + Format: raw_format, + SampleCount: 0, + Flags: Direct3D12::D3D12_MULTISAMPLE_QUALITY_LEVELS_FLAG_NONE, + NumQualityLevels: 0, + }; + + let mut set_sample_count = |sc: u32, tfc: Tfc| { + ms_levels.SampleCount = sc; + + if unsafe { + self.device.CheckFeatureSupport( + Direct3D12::D3D12_FEATURE_MULTISAMPLE_QUALITY_LEVELS, + <*mut _>::cast(&mut ms_levels), + size_of_val(&ms_levels) as u32, + ) + } + .is_ok() + && ms_levels.NumQualityLevels != 0 + { + caps.set(tfc, !no_msaa_load && !no_msaa_target); + } + }; + + set_sample_count(2, Tfc::MULTISAMPLE_X2); + set_sample_count(4, Tfc::MULTISAMPLE_X4); + set_sample_count(8, Tfc::MULTISAMPLE_X8); + set_sample_count(16, Tfc::MULTISAMPLE_X16); + + caps + } + + unsafe fn surface_capabilities( + &self, + surface: &super::Surface, + ) -> Option<crate::SurfaceCapabilities> { + let current_extent = { + match surface.target { + SurfaceTarget::WndHandle(wnd_handle) + | SurfaceTarget::VisualFromWndHandle { + handle: wnd_handle, .. + } => { + let mut rect = Default::default(); + if unsafe { WindowsAndMessaging::GetClientRect(wnd_handle, &mut rect) }.is_ok() + { + Some(wgt::Extent3d { + width: (rect.right - rect.left) as u32, + height: (rect.bottom - rect.top) as u32, + depth_or_array_layers: 1, + }) + } else { + log::warn!("Unable to get the window client rect"); + None + } + } + SurfaceTarget::Visual(_) + | SurfaceTarget::SurfaceHandle(_) + | SurfaceTarget::SwapChainPanel(_) => None, + } + }; + + let mut present_modes = vec![wgt::PresentMode::Mailbox, wgt::PresentMode::Fifo]; + if surface.supports_allow_tearing { + present_modes.push(wgt::PresentMode::Immediate); + } + + Some(crate::SurfaceCapabilities { + // `Surface::configure` applies the requested color space with + // `IDXGISwapChain3::SetColorSpace1`. fp16 buffers keep DXGI's + // scRGB interpretation (`DXGI_COLOR_SPACE_RGB_FULL_G10_NONE_P709`) + // and `Rgb10a2Unorm` additionally supports BT.2100 PQ (HDR10). + // + // These color spaces are advertised unconditionally, not gated on + // whether the output is currently in HDR mode: Windows always + // composites in scRGB and tone-maps PQ down to an SDR output, so the + // color space is configurable regardless, and `CheckColorSpaceSupport` + // returning false does not mean it won't present. Whether HDR is + // actually *visible* is a separate, live question (the upcoming + // display-HDR query, #9739), not a configuration gate. Display-P3 and + // HLG are never reported: DXGI has no RGB HLG swapchain color space, + // and P3 isn't a DXGI swapchain color space. + formats: [ + wgt::TextureFormat::Bgra8UnormSrgb, + wgt::TextureFormat::Bgra8Unorm, + wgt::TextureFormat::Rgba8UnormSrgb, + wgt::TextureFormat::Rgba8Unorm, + wgt::TextureFormat::Rgb10a2Unorm, + wgt::TextureFormat::Rgba16Float, + ] + .map(|format| wgt::SurfaceFormatCapabilities { + format, + color_spaces: match format { + wgt::TextureFormat::Rgba16Float => { + wgt::SurfaceColorSpaces::EXTENDED_SRGB_LINEAR + } + wgt::TextureFormat::Rgb10a2Unorm => { + wgt::SurfaceColorSpaces::SRGB | wgt::SurfaceColorSpaces::BT2100_PQ + } + _ => wgt::SurfaceColorSpaces::SRGB, + }, + }) + .to_vec(), + // See https://learn.microsoft.com/en-us/windows/win32/api/dxgi/nf-dxgi-idxgidevice1-setmaximumframelatency + maximum_frame_latency: 1..=16, + current_extent, + usage: wgt::TextureUses::COLOR_TARGET + | wgt::TextureUses::COPY_SRC + | wgt::TextureUses::COPY_DST, + present_modes, + composite_alpha_modes: match surface.target { + SurfaceTarget::WndHandle(_) => vec![wgt::CompositeAlphaMode::Opaque], + SurfaceTarget::Visual(_) + | SurfaceTarget::VisualFromWndHandle { .. } + | SurfaceTarget::SurfaceHandle(_) + | SurfaceTarget::SwapChainPanel(_) => vec![ + wgt::CompositeAlphaMode::Auto, + wgt::CompositeAlphaMode::Inherit, + wgt::CompositeAlphaMode::Opaque, + wgt::CompositeAlphaMode::PostMultiplied, + wgt::CompositeAlphaMode::PreMultiplied, + ], + }, + }) + } + + unsafe fn surface_display_hdr_info( + &self, + surface: &super::Surface, + ) -> Option<wgt::DisplayHdrInfo> { + surface.hdr_source.as_ref()?.display_hdr_info() + } + + unsafe fn get_presentation_timestamp(&self) -> wgt::PresentationTimestamp { + wgt::PresentationTimestamp(self.presentation_timer.get_timestamp_ns()) + } + + fn get_ordered_buffer_usages(&self) -> wgt::BufferUses { + wgt::BufferUses::INCLUSIVE | wgt::BufferUses::MAP_WRITE + } + + // Don't put barriers between inclusive uses + // DX12 implicitly orders renderpasses on the same resources. + fn get_ordered_texture_usages(&self) -> wgt::TextureUses { + wgt::TextureUses::INCLUSIVE + | wgt::TextureUses::COLOR_TARGET + | wgt::TextureUses::DEPTH_STENCIL_WRITE + } +} + +fn get_adapter_pci_info(vendor_id: u32, device_id: u32) -> String { + // SAFETY: SetupDiGetClassDevsW is called with valid parameters + let device_info_set = unsafe { + match SetupDiGetClassDevsW(Some(&GUID_DEVCLASS_DISPLAY), None, None, DIGCF_PRESENT) { + Ok(set) => set, + Err(_) => return String::new(), + } + }; + + struct DeviceInfoSetGuard(HDEVINFO); + impl Drop for DeviceInfoSetGuard { + fn drop(&mut self) { + // SAFETY: device_info_set is a valid HDEVINFO and is only dropped once via this guard + unsafe { + let _ = SetupDiDestroyDeviceInfoList(self.0); + } + } + } + let _guard = DeviceInfoSetGuard(device_info_set); + + let mut device_index = 0u32; + loop { + let mut device_info_data = SP_DEVINFO_DATA { + cbSize: size_of::<SP_DEVINFO_DATA>() as u32, + ..Default::default() + }; + + // SAFETY: device_info_set is a valid HDEVINFO, device_index starts at 0 and + // device_info_data is properly initialized above + unsafe { + if SetupDiEnumDeviceInfo(device_info_set, device_index, &mut device_info_data).is_err() + { + if GetLastError() == ERROR_NO_MORE_ITEMS { + break; + } + device_index += 1; + continue; + } + } + + let mut hardware_id_size = 0u32; + // SAFETY: device_info_set and device_info_data are valid + unsafe { + let _ = SetupDiGetDeviceRegistryPropertyW( + device_info_set, + &device_info_data, + SPDRP_HARDWAREID, + None, + None, + Some(&mut hardware_id_size), + ); + } + + if hardware_id_size == 0 { + device_index += 1; + continue; + } + + let mut hardware_id_buffer = vec![0u8; hardware_id_size as usize]; + // SAFETY: device_info_set and device_info_data are valid + unsafe { + if SetupDiGetDeviceRegistryPropertyW( + device_info_set, + &device_info_data, + SPDRP_HARDWAREID, + None, + Some(&mut hardware_id_buffer), + Some(&mut hardware_id_size), + ) + .is_err() + { + device_index += 1; + continue; + } + } + + let hardware_id_u16: Vec<u16> = hardware_id_buffer + .chunks_exact(2) + .map(|chunk| u16::from_le_bytes([chunk[0], chunk[1]])) + .collect(); + let hardware_ids: Vec<String> = hardware_id_u16 + .split(|&c| c == 0) + .filter(|s| !s.is_empty()) + .map(|s| String::from_utf16_lossy(s).to_uppercase()) + .collect(); + + // https://learn.microsoft.com/en-us/windows-hardware/drivers/install/identifiers-for-pci-devices + let expected_id = format!("PCI\\VEN_{vendor_id:04X}&DEV_{device_id:04X}"); + if !hardware_ids.iter().any(|id| id.contains(&expected_id)) { + device_index += 1; + continue; + } + + let mut bus_buffer = [0u8; 4]; + let mut data_size = bus_buffer.len() as u32; + // SAFETY: device_info_set and device_info_data are valid + let bus_number = unsafe { + if SetupDiGetDeviceRegistryPropertyW( + device_info_set, + &device_info_data, + SPDRP_BUSNUMBER, + None, + Some(&mut bus_buffer), + Some(&mut data_size), + ) + .is_err() + { + device_index += 1; + continue; + } + u32::from_le_bytes(bus_buffer) + }; + + let mut addr_buffer = [0u8; 4]; + let mut addr_size = addr_buffer.len() as u32; + // SAFETY: device_info_set and device_info_data are valid + unsafe { + if SetupDiGetDeviceRegistryPropertyW( + device_info_set, + &device_info_data, + SPDRP_ADDRESS, + None, + Some(&mut addr_buffer), + Some(&mut addr_size), + ) + .is_err() + { + device_index += 1; + continue; + } + } + let address = u32::from_le_bytes(addr_buffer); + + // https://learn.microsoft.com/en-us/windows-hardware/drivers/kernel/obtaining-device-configuration-information-at-irql---dispatch-level + let device = (address >> 16) & 0x0000FFFF; + let function = address & 0x0000FFFF; + + // domain:bus:device.function + return format!("{:04x}:{:02x}:{:02x}.{:x}", 0, bus_number, device, function); + } + + String::new() +} diff --git a/app/vendor/rune/vendor/wgpu-hal/src/dx12/command.rs b/app/vendor/rune/vendor/wgpu-hal/src/dx12/command.rs new file mode 100644 index 0000000..762d922 --- /dev/null +++ b/app/vendor/rune/vendor/wgpu-hal/src/dx12/command.rs @@ -0,0 +1,1884 @@ +use alloc::vec::Vec; +use core::{mem, ops::Range}; + +use windows::{ + core::Interface as _, + Win32::{ + Foundation, + Graphics::{Direct3D12, Dxgi}, + }, +}; + +use super::conv; +use crate::{ + auxil::{ + self, + dxgi::{name::ObjectExt as _, result::HResult as _}, + }, + dx12::borrow_interface_temporarily, + AccelerationStructureEntries, CommandEncoder as _, +}; + +fn make_box(origin: &wgt::Origin3d, size: &crate::CopyExtent) -> Direct3D12::D3D12_BOX { + Direct3D12::D3D12_BOX { + left: origin.x, + top: origin.y, + right: origin.x + size.width, + bottom: origin.y + size.height, + front: origin.z, + back: origin.z + size.depth, + } +} + +impl crate::BufferTextureCopy { + fn to_subresource_footprint( + &self, + format: wgt::TextureFormat, + ) -> Direct3D12::D3D12_PLACED_SUBRESOURCE_FOOTPRINT { + let (block_width, _) = format.block_dimensions(); + Direct3D12::D3D12_PLACED_SUBRESOURCE_FOOTPRINT { + Offset: self.buffer_layout.offset, + Footprint: Direct3D12::D3D12_SUBRESOURCE_FOOTPRINT { + Format: auxil::dxgi::conv::map_texture_format_for_copy( + format, + self.texture_base.aspect, + ) + .unwrap(), + Width: self.size.width, + Height: self.size.height, + Depth: self.size.depth, + RowPitch: { + let actual = self.buffer_layout.bytes_per_row.unwrap_or_else(|| { + // this may happen for single-line updates + let block_size = format + .block_copy_size(Some(self.texture_base.aspect.map())) + .unwrap(); + (self.size.width / block_width) * block_size + }); + wgt::math::align_to(actual, Direct3D12::D3D12_TEXTURE_DATA_PITCH_ALIGNMENT) + }, + }, + } + } +} + +impl super::Temp { + fn prepare_marker(&mut self, marker: &str) -> (&[u16], u32) { + self.marker.clear(); + self.marker.extend(marker.encode_utf16()); + self.marker.push(0); + (&self.marker, self.marker.len() as u32 * 2) + } +} + +impl Drop for super::CommandEncoder { + fn drop(&mut self) { + use crate::CommandEncoder; + unsafe { self.discard_encoding() } + + let mut rtv_pool = self.rtv_pool.lock(); + for handle in self.temp_rtv_handles.drain(..) { + rtv_pool.free_handle(handle); + } + drop(rtv_pool); + + self.counters.command_encoders.sub(1); + } +} + +impl super::CommandEncoder { + unsafe fn begin_pass(&mut self, kind: super::PassKind, label: crate::Label) { + let list = self.list.as_ref().unwrap(); + self.pass.kind = kind; + if let Some(label) = label { + let (wide_label, size) = self.temp.prepare_marker(label); + unsafe { list.BeginEvent(0, Some(wide_label.as_ptr().cast()), size) }; + self.pass.has_label = true; + } + self.pass.dirty_root_elements = 0; + self.pass.dirty_vertex_buffers = 0; + unsafe { + list.SetDescriptorHeaps(&[ + Some(self.shared.heap_views.raw.clone()), + Some(self.shared.sampler_heap.heap().clone()), + ]) + }; + } + + unsafe fn end_pass(&mut self) { + let list = self.list.as_ref().unwrap(); + unsafe { list.SetDescriptorHeaps(&[]) }; + if self.pass.has_label { + unsafe { list.EndEvent() }; + } + self.pass.clear(); + } + + unsafe fn prepare_vertex_buffers(&mut self) { + while self.pass.dirty_vertex_buffers != 0 { + let list = self.list.as_ref().unwrap(); + let index = self.pass.dirty_vertex_buffers.trailing_zeros(); + self.pass.dirty_vertex_buffers ^= 1 << index; + unsafe { + list.IASetVertexBuffers( + index, + Some(&self.pass.vertex_buffers[index as usize..][..1]), + ); + } + } + } + + unsafe fn prepare_draw(&mut self, first_vertex: i32, first_instance: u32) { + unsafe { + self.prepare_vertex_buffers(); + } + if let Some(root_index) = self + .pass + .layout + .special_constants + .as_ref() + .map(|sc| sc.root_index) + { + let special_constants = super::SpecialConstants::from_indirect_draw_call_params( + first_vertex, + first_instance, + ); + let needs_update = match self.pass.root_elements[root_index as usize] { + super::RootElement::SpecialConstants(old_special_constants) => { + old_special_constants != special_constants + } + _ => true, + }; + if needs_update { + self.pass.dirty_root_elements |= 1 << root_index; + self.pass.root_elements[root_index as usize] = + super::RootElement::SpecialConstants(special_constants); + } + } + self.update_root_elements(); + } + + fn prepare_dispatch(&mut self, workgroup_count: [u32; 3]) { + if let Some(root_index) = self + .pass + .layout + .special_constants + .as_ref() + .map(|sc| sc.root_index) + { + let special_constants = + super::SpecialConstants::from_compute_dispatch_params(workgroup_count); + let needs_update = match self.pass.root_elements[root_index as usize] { + super::RootElement::SpecialConstants(old_special_constants) => { + old_special_constants != special_constants + } + _ => true, + }; + if needs_update { + self.pass.dirty_root_elements |= 1 << root_index; + self.pass.root_elements[root_index as usize] = + super::RootElement::SpecialConstants(special_constants); + } + } + self.update_root_elements(); + } + + // Note: we have to call this lazily before draw calls. Otherwise, D3D complains + // about the root parameters being incompatible with root signature. + fn update_root_elements(&mut self) { + use super::PassKind as Pk; + + while self.pass.dirty_root_elements != 0 { + let list = self.list.as_ref().unwrap(); + let index = self.pass.dirty_root_elements.trailing_zeros(); + self.pass.dirty_root_elements ^= 1 << index; + + match self.pass.root_elements[index as usize] { + super::RootElement::Empty => unreachable!( + "Empty root element at index {index} should not have been marked as dirty" + ), + super::RootElement::Immediates => { + let info = self.pass.layout.immediates_info.as_ref().unwrap(); + + for offset in 0..info.size { + let val = self.pass.immediates[offset as usize]; + match self.pass.kind { + Pk::Render => unsafe { + list.SetGraphicsRoot32BitConstant(index, val, offset) + }, + Pk::Compute => unsafe { + list.SetComputeRoot32BitConstant(index, val, offset) + }, + Pk::Transfer => (), + } + } + } + super::RootElement::SpecialConstants(super::SpecialConstants { + first_vertex_or_x, + first_instance_or_y, + unused_or_z, + }) => match self.pass.kind { + Pk::Render => { + unsafe { + list.SetGraphicsRoot32BitConstant(index, first_vertex_or_x as u32, 0) + }; + unsafe { list.SetGraphicsRoot32BitConstant(index, first_instance_or_y, 1) }; + } + Pk::Compute => { + unsafe { + list.SetComputeRoot32BitConstant(index, first_vertex_or_x as u32, 0) + }; + unsafe { list.SetComputeRoot32BitConstant(index, first_instance_or_y, 1) }; + unsafe { list.SetComputeRoot32BitConstant(index, unused_or_z, 2) }; + } + Pk::Transfer => (), + }, + super::RootElement::DescriptorTable(descriptor) => match self.pass.kind { + Pk::Render => unsafe { list.SetGraphicsRootDescriptorTable(index, descriptor) }, + Pk::Compute => unsafe { list.SetComputeRootDescriptorTable(index, descriptor) }, + Pk::Transfer => (), + }, + super::RootElement::DynamicUniformBuffer { address } => { + let address = address.ptr; + match self.pass.kind { + Pk::Render => unsafe { + list.SetGraphicsRootConstantBufferView(index, address) + }, + Pk::Compute => unsafe { + list.SetComputeRootConstantBufferView(index, address) + }, + Pk::Transfer => (), + } + } + super::RootElement::DynamicStorageBufferOffsets { start, end } => { + let values = &self.pass.dynamic_storage_buffer_offsets[start..end]; + + for (offset, &value) in values.iter().enumerate() { + match self.pass.kind { + Pk::Render => unsafe { + list.SetGraphicsRoot32BitConstant(index, value, offset as u32) + }, + Pk::Compute => unsafe { + list.SetComputeRoot32BitConstant(index, value, offset as u32) + }, + Pk::Transfer => (), + } + } + } + super::RootElement::SamplerHeapDescriptorTable => match self.pass.kind { + Pk::Render => unsafe { + list.SetGraphicsRootDescriptorTable( + index, + self.shared.sampler_heap.gpu_descriptor_table(), + ) + }, + Pk::Compute => unsafe { + list.SetComputeRootDescriptorTable( + index, + self.shared.sampler_heap.gpu_descriptor_table(), + ) + }, + Pk::Transfer => (), + }, + } + } + } + + fn reset_signature(&mut self, layout: &super::PipelineLayoutShared) { + if let Some(root_index) = layout.special_constants.as_ref().map(|sc| sc.root_index) { + self.pass.root_elements[root_index as usize] = + super::RootElement::SpecialConstants(super::SpecialConstants::default()); + } + if let Some(root_index) = layout.sampler_heap_root_index { + self.pass.root_elements[root_index as usize] = + super::RootElement::SamplerHeapDescriptorTable; + } + self.pass.layout = layout.clone(); + self.pass.dirty_root_elements = (1 << layout.total_root_elements) - 1; + } + + fn write_pass_end_timestamp_if_requested(&mut self) { + if let Some((query_set_raw, index)) = self.end_of_pass_timer_query.take() { + use crate::CommandEncoder as _; + unsafe { + self.write_timestamp( + &crate::dx12::QuerySet { + raw: query_set_raw, + raw_ty: Direct3D12::D3D12_QUERY_TYPE_TIMESTAMP, + }, + index, + ); + } + } + } + + unsafe fn buf_tex_intermediate<T>( + &mut self, + region: crate::BufferTextureCopy, + tex_fmt: wgt::TextureFormat, + copy_op: impl FnOnce(&mut Self, &super::Buffer, wgt::BufferSize, crate::BufferTextureCopy) -> T, + ) -> (T, super::Buffer) { + let size = { + let copy_info = region.buffer_layout.get_buffer_texture_copy_info( + tex_fmt, + region.texture_base.aspect.map(), + &region.size.into(), + ); + copy_info.unwrap().bytes_in_copy + }; + + let size = wgt::BufferSize::new(size).unwrap(); + + let buffer = { + let (resource, allocation) = + super::suballocation::DeviceAllocationContext::from(&*self) + .create_buffer(&crate::BufferDescriptor { + label: None, + size: size.get(), + usage: wgt::BufferUses::COPY_SRC | wgt::BufferUses::COPY_DST, + memory_flags: crate::MemoryFlags::empty(), + }) + .expect(concat!( + "internal error: ", + "failed to allocate intermediate buffer ", + "for offset alignment" + )); + super::Buffer { + resource, + size: size.get(), + allocation, + } + }; + + let mut region = region; + region.buffer_layout.offset = 0; + + unsafe { + self.transition_buffers( + [crate::BufferBarrier { + buffer: &buffer, + usage: crate::StateTransition { + from: wgt::BufferUses::empty(), + to: wgt::BufferUses::COPY_DST, + }, + }] + .into_iter(), + ) + }; + + let t = copy_op(self, &buffer, size, region); + + unsafe { + self.transition_buffers( + [crate::BufferBarrier { + buffer: &buffer, + usage: crate::StateTransition { + from: wgt::BufferUses::COPY_DST, + to: wgt::BufferUses::COPY_SRC, + }, + }] + .into_iter(), + ) + }; + + (t, buffer) + } +} + +impl crate::CommandEncoder for super::CommandEncoder { + type A = super::Api; + + unsafe fn begin_encoding(&mut self, label: crate::Label) -> Result<(), crate::DeviceError> { + let reused = loop { + if let Some((list, list2)) = self.free_lists.pop() { + // TODO: Is an error expected here and should we print it? + let reset_result = unsafe { list.Reset(&self.allocator, None) }; + if reset_result.is_ok() { + break Some((list, list2)); + } + } else { + break None; + } + }; + + let (list, list2) = if let Some(pair) = reused { + pair + } else { + let list: Direct3D12::ID3D12GraphicsCommandList = unsafe { + self.device.CreateCommandList( + 0, + Direct3D12::D3D12_COMMAND_LIST_TYPE_DIRECT, + &self.allocator, + None, + ) + } + .into_device_result("Create command list")?; + let list2 = if self.shared.drain.has_marker() { + list.cast::<Direct3D12::ID3D12GraphicsCommandList2>().ok() + } else { + None + }; + (list, list2) + }; + + if let Some(label) = label { + list.set_name(label)?; + } + + // Ensure clean state even if the last encoding did not complete normally. + self.temp.clear(); + self.pass.clear(); + self.end_of_pass_timer_query = None; + + self.list = Some(list); + self.list2 = list2; + Ok(()) + } + unsafe fn discard_encoding(&mut self) { + let list2 = self.list2.take(); + if let Some(list) = self.list.take() { + if unsafe { list.Close() }.is_ok() { + self.free_lists.push((list, list2)); + } + } + } + unsafe fn end_encoding(&mut self) -> Result<super::CommandBuffer, crate::DeviceError> { + let raw = self.list.take().unwrap(); + let list2 = self.list2.take(); + let marker = self.shared.drain.record(list2.as_ref()); + unsafe { raw.Close() }.into_device_result("GraphicsCommandList::close")?; + Ok(super::CommandBuffer { raw, list2, marker }) + } + unsafe fn reset_all<I: Iterator<Item = super::CommandBuffer>>(&mut self, command_buffers: I) { + self.intermediate_copy_bufs.clear(); + for cmd_buf in command_buffers { + self.free_lists.push((cmd_buf.raw, cmd_buf.list2)); + } + // Rune: never reset a command allocator on a removed device; no new commands will ever + // be recorded on it, and a timed-out drain on a removed device could still have the + // driver unwinding a list recorded in this allocator. + if self.shared.drain.is_removed() { + return; + } + if let Err(e) = unsafe { self.allocator.Reset() } { + log::error!("ID3D12CommandAllocator::Reset() failed with {e}"); + } + } + + unsafe fn transition_buffers<'a, T>(&mut self, barriers: T) + where + T: Iterator<Item = crate::BufferBarrier<'a, super::Buffer>>, + { + self.temp.barriers.clear(); + + for barrier in barriers { + let s0 = conv::map_buffer_usage_to_state(barrier.usage.from); + let s1 = conv::map_buffer_usage_to_state(barrier.usage.to); + if s0 != s1 { + let raw = Direct3D12::D3D12_RESOURCE_BARRIER { + Type: Direct3D12::D3D12_RESOURCE_BARRIER_TYPE_TRANSITION, + Flags: Direct3D12::D3D12_RESOURCE_BARRIER_FLAG_NONE, + Anonymous: Direct3D12::D3D12_RESOURCE_BARRIER_0 { + Transition: mem::ManuallyDrop::new( + Direct3D12::D3D12_RESOURCE_TRANSITION_BARRIER { + pResource: unsafe { + borrow_interface_temporarily(&barrier.buffer.resource) + }, + Subresource: Direct3D12::D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, + StateBefore: s0, + StateAfter: s1, + }, + ), + }, + }; + self.temp.barriers.push(raw); + } else if barrier.usage.from == wgt::BufferUses::STORAGE_READ_WRITE + || barrier.usage.from == wgt::BufferUses::ACCELERATION_STRUCTURE_QUERY + { + let raw = Direct3D12::D3D12_RESOURCE_BARRIER { + Type: Direct3D12::D3D12_RESOURCE_BARRIER_TYPE_UAV, + Flags: Direct3D12::D3D12_RESOURCE_BARRIER_FLAG_NONE, + Anonymous: Direct3D12::D3D12_RESOURCE_BARRIER_0 { + UAV: mem::ManuallyDrop::new(Direct3D12::D3D12_RESOURCE_UAV_BARRIER { + pResource: unsafe { + borrow_interface_temporarily(&barrier.buffer.resource) + }, + }), + }, + }; + self.temp.barriers.push(raw); + } + } + + if !self.temp.barriers.is_empty() { + unsafe { + self.list + .as_ref() + .unwrap() + .ResourceBarrier(&self.temp.barriers) + }; + } + } + + unsafe fn transition_textures<'a, T>(&mut self, barriers: T) + where + T: Iterator<Item = crate::TextureBarrier<'a, super::Texture>>, + { + self.temp.barriers.clear(); + + for barrier in barriers { + let s0 = conv::map_texture_usage_to_state(barrier.usage.from); + let s1 = conv::map_texture_usage_to_state(barrier.usage.to); + if s0 != s1 { + let mut raw = Direct3D12::D3D12_RESOURCE_BARRIER { + Type: Direct3D12::D3D12_RESOURCE_BARRIER_TYPE_TRANSITION, + Flags: Direct3D12::D3D12_RESOURCE_BARRIER_FLAG_NONE, + Anonymous: Direct3D12::D3D12_RESOURCE_BARRIER_0 { + Transition: mem::ManuallyDrop::new( + Direct3D12::D3D12_RESOURCE_TRANSITION_BARRIER { + pResource: unsafe { + borrow_interface_temporarily(&barrier.texture.resource) + }, + Subresource: Direct3D12::D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, + StateBefore: s0, + StateAfter: s1, + }, + ), + }, + }; + + let tex_mip_level_count = barrier.texture.mip_level_count; + let tex_array_layer_count = barrier.texture.array_layer_count(); + + if barrier.range.is_full_resource( + barrier.texture.format, + tex_mip_level_count, + tex_array_layer_count, + ) { + // Only one barrier if it affects the whole image. + self.temp.barriers.push(raw); + } else { + // Selected texture aspect is relevant if the texture format has both depth _and_ stencil aspects. + let planes = if barrier.texture.format.is_combined_depth_stencil_format() { + match barrier.range.aspect { + wgt::TextureAspect::All => 0..2, + wgt::TextureAspect::DepthOnly => 0..1, + wgt::TextureAspect::StencilOnly => 1..2, + _ => unreachable!(), + } + } else if let Some(planes) = barrier.texture.format.planes() { + match barrier.range.aspect { + wgt::TextureAspect::All => 0..planes, + wgt::TextureAspect::Plane0 => 0..1, + wgt::TextureAspect::Plane1 => 1..2, + wgt::TextureAspect::Plane2 => 2..3, + _ => unreachable!(), + } + } else { + match barrier.texture.format { + wgt::TextureFormat::Stencil8 => 1..2, + wgt::TextureFormat::Depth24Plus => 0..2, // TODO: investigate why tests fail if we set this to 0..1 + _ => 0..1, + } + }; + + for mip_level in barrier.range.mip_range(tex_mip_level_count) { + for array_layer in barrier.range.layer_range(tex_array_layer_count) { + for plane in planes.clone() { + unsafe { &mut *raw.Anonymous.Transition }.Subresource = barrier + .texture + .calc_subresource(mip_level, array_layer, plane); + self.temp.barriers.push(raw.clone()); + } + } + } + } + } else if barrier.usage.from == wgt::TextureUses::STORAGE_READ_WRITE { + let raw = Direct3D12::D3D12_RESOURCE_BARRIER { + Type: Direct3D12::D3D12_RESOURCE_BARRIER_TYPE_UAV, + Flags: Direct3D12::D3D12_RESOURCE_BARRIER_FLAG_NONE, + Anonymous: Direct3D12::D3D12_RESOURCE_BARRIER_0 { + UAV: mem::ManuallyDrop::new(Direct3D12::D3D12_RESOURCE_UAV_BARRIER { + pResource: unsafe { + borrow_interface_temporarily(&barrier.texture.resource) + }, + }), + }, + }; + self.temp.barriers.push(raw); + } + } + + if !self.temp.barriers.is_empty() { + unsafe { + self.list + .as_ref() + .unwrap() + .ResourceBarrier(&self.temp.barriers) + }; + } + } + + unsafe fn clear_buffer(&mut self, buffer: &super::Buffer, range: crate::MemoryRange) { + let list = self.list.as_ref().unwrap(); + let mut offset = range.start; + while offset < range.end { + let size = super::ZERO_BUFFER_SIZE.min(range.end - offset); + unsafe { + list.CopyBufferRegion(&buffer.resource, offset, &self.shared.zero_buffer, 0, size) + }; + offset += size; + } + } + + unsafe fn copy_buffer_to_buffer<T>( + &mut self, + src: &super::Buffer, + dst: &super::Buffer, + regions: T, + ) where + T: Iterator<Item = crate::BufferCopy>, + { + let list = self.list.as_ref().unwrap(); + for r in regions { + unsafe { + list.CopyBufferRegion( + &dst.resource, + r.dst_offset, + &src.resource, + r.src_offset, + r.size.get(), + ) + }; + } + } + + unsafe fn copy_texture_to_texture<T>( + &mut self, + src: &super::Texture, + _src_usage: wgt::TextureUses, + dst: &super::Texture, + regions: T, + ) where + T: Iterator<Item = crate::TextureCopy>, + { + let list = self.list.as_ref().unwrap(); + + for r in regions { + let src_location = Direct3D12::D3D12_TEXTURE_COPY_LOCATION { + pResource: unsafe { borrow_interface_temporarily(&src.resource) }, + Type: Direct3D12::D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, + Anonymous: Direct3D12::D3D12_TEXTURE_COPY_LOCATION_0 { + SubresourceIndex: src.calc_subresource_for_copy(&r.src_base), + }, + }; + let dst_location = Direct3D12::D3D12_TEXTURE_COPY_LOCATION { + pResource: unsafe { borrow_interface_temporarily(&dst.resource) }, + Type: Direct3D12::D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, + Anonymous: Direct3D12::D3D12_TEXTURE_COPY_LOCATION_0 { + SubresourceIndex: dst.calc_subresource_for_copy(&r.dst_base), + }, + }; + + let src_box = make_box(&r.src_base.origin, &r.size); + + unsafe { + list.CopyTextureRegion( + &dst_location, + r.dst_base.origin.x, + r.dst_base.origin.y, + r.dst_base.origin.z, + &src_location, + Some(&src_box), + ) + }; + } + } + + unsafe fn copy_buffer_to_texture<T>( + &mut self, + src: &super::Buffer, + dst: &super::Texture, + regions: T, + ) where + T: Iterator<Item = crate::BufferTextureCopy>, + { + let offset_alignment = self.shared.private_caps.texture_data_placement_alignment(); + + for naive_copy_region in regions { + let is_offset_aligned = naive_copy_region.buffer_layout.offset % offset_alignment == 0; + let (final_copy_region, src) = if is_offset_aligned { + (naive_copy_region, src) + } else { + let (intermediate_to_dst_region, intermediate_buf) = unsafe { + let src_offset = naive_copy_region.buffer_layout.offset; + self.buf_tex_intermediate( + naive_copy_region, + dst.format, + |this, buf, size, intermediate_to_dst_region| { + let layout = crate::BufferCopy { + src_offset, + dst_offset: 0, + size, + }; + this.copy_buffer_to_buffer(src, buf, [layout].into_iter()); + intermediate_to_dst_region + }, + ) + }; + self.intermediate_copy_bufs.push(intermediate_buf); + let intermediate_buf = self.intermediate_copy_bufs.last().unwrap(); + (intermediate_to_dst_region, intermediate_buf) + }; + + let list = self.list.as_ref().unwrap(); + + let src_location = Direct3D12::D3D12_TEXTURE_COPY_LOCATION { + pResource: unsafe { borrow_interface_temporarily(&src.resource) }, + Type: Direct3D12::D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, + Anonymous: Direct3D12::D3D12_TEXTURE_COPY_LOCATION_0 { + PlacedFootprint: final_copy_region.to_subresource_footprint(dst.format), + }, + }; + let dst_location = Direct3D12::D3D12_TEXTURE_COPY_LOCATION { + pResource: unsafe { borrow_interface_temporarily(&dst.resource) }, + Type: Direct3D12::D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, + Anonymous: Direct3D12::D3D12_TEXTURE_COPY_LOCATION_0 { + SubresourceIndex: dst + .calc_subresource_for_copy(&final_copy_region.texture_base), + }, + }; + + let src_box = make_box(&wgt::Origin3d::ZERO, &final_copy_region.size); + unsafe { + list.CopyTextureRegion( + &dst_location, + final_copy_region.texture_base.origin.x, + final_copy_region.texture_base.origin.y, + final_copy_region.texture_base.origin.z, + &src_location, + Some(&src_box), + ) + }; + } + } + + unsafe fn copy_texture_to_buffer<T>( + &mut self, + src: &super::Texture, + _src_usage: wgt::TextureUses, + dst: &super::Buffer, + regions: T, + ) where + T: Iterator<Item = crate::BufferTextureCopy>, + { + let copy_aligned = |this: &mut Self, + src: &super::Texture, + dst: &super::Buffer, + r: crate::BufferTextureCopy| { + let list = this.list.as_ref().unwrap(); + + let src_location = Direct3D12::D3D12_TEXTURE_COPY_LOCATION { + pResource: unsafe { borrow_interface_temporarily(&src.resource) }, + Type: Direct3D12::D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, + Anonymous: Direct3D12::D3D12_TEXTURE_COPY_LOCATION_0 { + SubresourceIndex: src.calc_subresource_for_copy(&r.texture_base), + }, + }; + let dst_location = Direct3D12::D3D12_TEXTURE_COPY_LOCATION { + pResource: unsafe { borrow_interface_temporarily(&dst.resource) }, + Type: Direct3D12::D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, + Anonymous: Direct3D12::D3D12_TEXTURE_COPY_LOCATION_0 { + PlacedFootprint: r.to_subresource_footprint(src.format), + }, + }; + + let src_box = make_box(&r.texture_base.origin, &r.size); + unsafe { + list.CopyTextureRegion(&dst_location, 0, 0, 0, &src_location, Some(&src_box)) + }; + }; + + let offset_alignment = self.shared.private_caps.texture_data_placement_alignment(); + + for r in regions { + let is_offset_aligned = r.buffer_layout.offset % offset_alignment == 0; + if is_offset_aligned { + copy_aligned(self, src, dst, r) + } else { + let orig_offset = r.buffer_layout.offset; + let (intermediate_to_dst_region, src) = unsafe { + self.buf_tex_intermediate( + r, + src.format, + |this, buf, size, intermediate_region| { + copy_aligned(this, src, buf, intermediate_region); + crate::BufferCopy { + src_offset: 0, + dst_offset: orig_offset, + size, + } + }, + ) + }; + + unsafe { + self.copy_buffer_to_buffer(&src, dst, [intermediate_to_dst_region].into_iter()); + } + + self.intermediate_copy_bufs.push(src); + }; + } + } + + unsafe fn begin_query(&mut self, set: &super::QuerySet, index: u32) { + unsafe { + self.list + .as_ref() + .unwrap() + .BeginQuery(&set.raw, set.raw_ty, index) + }; + } + unsafe fn end_query(&mut self, set: &super::QuerySet, index: u32) { + unsafe { + self.list + .as_ref() + .unwrap() + .EndQuery(&set.raw, set.raw_ty, index) + }; + } + unsafe fn write_timestamp(&mut self, set: &super::QuerySet, index: u32) { + unsafe { + self.list.as_ref().unwrap().EndQuery( + &set.raw, + Direct3D12::D3D12_QUERY_TYPE_TIMESTAMP, + index, + ) + }; + } + unsafe fn read_acceleration_structure_compact_size( + &mut self, + acceleration_structure: &super::AccelerationStructure, + buf: &super::Buffer, + ) { + let list = self + .list + .as_ref() + .unwrap() + .cast::<Direct3D12::ID3D12GraphicsCommandList4>() + .unwrap(); + unsafe { + list.EmitRaytracingAccelerationStructurePostbuildInfo( + &Direct3D12::D3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_DESC { + DestBuffer: buf.resource.GetGPUVirtualAddress(), + InfoType: Direct3D12::D3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_COMPACTED_SIZE, + }, + &[ + acceleration_structure.resource.GetGPUVirtualAddress() + ], + ) + } + } + unsafe fn reset_queries(&mut self, _set: &super::QuerySet, _range: Range<u32>) { + // nothing to do here + } + unsafe fn copy_query_results( + &mut self, + set: &super::QuerySet, + range: Range<u32>, + buffer: &super::Buffer, + offset: wgt::BufferAddress, + _stride: wgt::BufferSize, + ) { + unsafe { + self.list.as_ref().unwrap().ResolveQueryData( + &set.raw, + set.raw_ty, + range.start, + range.end - range.start, + &buffer.resource, + offset, + ) + }; + } + + // render + + unsafe fn begin_render_pass( + &mut self, + desc: &crate::RenderPassDescriptor<super::QuerySet, super::TextureView>, + ) -> Result<(), crate::DeviceError> { + unsafe { self.begin_pass(super::PassKind::Render, desc.label) }; + + // Start timestamp if any (before all other commands but after debug marker) + if let Some(timestamp_writes) = desc.timestamp_writes.as_ref() { + if let Some(index) = timestamp_writes.beginning_of_pass_write_index { + unsafe { + self.write_timestamp(timestamp_writes.query_set, index); + } + } + self.end_of_pass_timer_query = timestamp_writes + .end_of_pass_write_index + .map(|index| (timestamp_writes.query_set.raw.clone(), index)); + } + + let mut color_views = + [Direct3D12::D3D12_CPU_DESCRIPTOR_HANDLE { ptr: 0 }; crate::MAX_COLOR_ATTACHMENTS]; + let mut rtv_pool = self.rtv_pool.lock(); + for (rtv, cat) in color_views.iter_mut().zip(desc.color_attachments.iter()) { + if let Some(cat) = cat.as_ref() { + if cat.target.view.dimension == wgt::TextureViewDimension::D3 { + let desc = Direct3D12::D3D12_RENDER_TARGET_VIEW_DESC { + Format: cat.target.view.raw_format, + ViewDimension: Direct3D12::D3D12_RTV_DIMENSION_TEXTURE3D, + Anonymous: Direct3D12::D3D12_RENDER_TARGET_VIEW_DESC_0 { + Texture3D: Direct3D12::D3D12_TEX3D_RTV { + MipSlice: cat.target.view.mip_slice, + FirstWSlice: cat.depth_slice.unwrap(), + WSize: 1, + }, + }, + }; + let handle = rtv_pool.alloc_handle()?; + unsafe { + self.device.CreateRenderTargetView( + &cat.target.view.texture, + Some(&desc), + handle.raw, + ) + }; + *rtv = handle.raw; + self.temp_rtv_handles.push(handle); + } else { + *rtv = cat.target.view.handle_rtv.unwrap().raw; + } + } else { + *rtv = self.null_rtv_handle.raw; + } + } + drop(rtv_pool); + + let ds_view = desc.depth_stencil_attachment.as_ref().map(|ds| { + if ds.target.usage == wgt::TextureUses::DEPTH_STENCIL_WRITE { + ds.target.view.handle_dsv_rw.as_ref().unwrap().raw + } else { + ds.target.view.handle_dsv_ro.as_ref().unwrap().raw + } + }); + + let list = self.list.as_ref().unwrap(); + unsafe { + list.OMSetRenderTargets( + desc.color_attachments.len() as u32, + Some(color_views.as_ptr()), + false, + ds_view.as_ref().map(core::ptr::from_ref), + ) + }; + + self.pass.resolves.clear(); + for (rtv, cat) in color_views.iter().zip(desc.color_attachments.iter()) { + if let Some(cat) = cat.as_ref() { + if cat.ops.contains(crate::AttachmentOps::LOAD_CLEAR) { + let value = [ + cat.clear_value.r as f32, + cat.clear_value.g as f32, + cat.clear_value.b as f32, + cat.clear_value.a as f32, + ]; + unsafe { list.ClearRenderTargetView(*rtv, &value, None) }; + } + if let Some(ref target) = cat.resolve_target { + self.pass.resolves.push(super::PassResolve { + src: ( + cat.target.view.texture.clone(), + cat.target.view.subresource_index, + ), + dst: (target.view.texture.clone(), target.view.subresource_index), + format: target.view.raw_format, + }); + } + } + } + + if let Some(ref ds) = desc.depth_stencil_attachment { + let mut flags = Direct3D12::D3D12_CLEAR_FLAGS::default(); + let aspects = ds.target.view.aspects; + if ds.depth_ops.contains(crate::AttachmentOps::LOAD_CLEAR) + && aspects.contains(crate::FormatAspects::DEPTH) + { + flags |= Direct3D12::D3D12_CLEAR_FLAG_DEPTH; + } + if ds.stencil_ops.contains(crate::AttachmentOps::LOAD_CLEAR) + && aspects.contains(crate::FormatAspects::STENCIL) + { + flags |= Direct3D12::D3D12_CLEAR_FLAG_STENCIL; + } + + if let Some(ds_view) = ds_view { + if flags != Direct3D12::D3D12_CLEAR_FLAGS::default() { + unsafe { + list.ClearDepthStencilView( + ds_view, + flags, + ds.clear_value.0, + ds.clear_value.1 as u8, + None, + ) + } + } + } + } + + if let Some(multiview_mask) = desc.multiview_mask { + unsafe { + list.cast::<Direct3D12::ID3D12GraphicsCommandList2>() + .unwrap() + .SetViewInstanceMask(multiview_mask.get()); + } + } + + let raw_vp = Direct3D12::D3D12_VIEWPORT { + TopLeftX: 0.0, + TopLeftY: 0.0, + Width: desc.extent.width as f32, + Height: desc.extent.height as f32, + MinDepth: 0.0, + MaxDepth: 1.0, + }; + let raw_rect = Foundation::RECT { + left: 0, + top: 0, + right: desc.extent.width as i32, + bottom: desc.extent.height as i32, + }; + unsafe { list.RSSetViewports(core::slice::from_ref(&raw_vp)) }; + unsafe { list.RSSetScissorRects(core::slice::from_ref(&raw_rect)) }; + + Ok(()) + } + + unsafe fn end_render_pass(&mut self) { + if !self.pass.resolves.is_empty() { + let list = self.list.as_ref().unwrap(); + self.temp.barriers.clear(); + + // All the targets are expected to be in `COLOR_TARGET` state, + // but D3D12 has special source/destination states for the resolves. + for resolve in self.pass.resolves.iter() { + let barrier = Direct3D12::D3D12_RESOURCE_BARRIER { + Type: Direct3D12::D3D12_RESOURCE_BARRIER_TYPE_TRANSITION, + Flags: Direct3D12::D3D12_RESOURCE_BARRIER_FLAG_NONE, + Anonymous: Direct3D12::D3D12_RESOURCE_BARRIER_0 { + // Note: this assumes `D3D12_RESOURCE_STATE_RENDER_TARGET`. + // If it's not the case, we can include the `TextureUses` in `PassResolve`. + Transition: mem::ManuallyDrop::new( + Direct3D12::D3D12_RESOURCE_TRANSITION_BARRIER { + pResource: unsafe { borrow_interface_temporarily(&resolve.src.0) }, + Subresource: resolve.src.1, + StateBefore: Direct3D12::D3D12_RESOURCE_STATE_RENDER_TARGET, + StateAfter: Direct3D12::D3D12_RESOURCE_STATE_RESOLVE_SOURCE, + }, + ), + }, + }; + self.temp.barriers.push(barrier); + let barrier = Direct3D12::D3D12_RESOURCE_BARRIER { + Type: Direct3D12::D3D12_RESOURCE_BARRIER_TYPE_TRANSITION, + Flags: Direct3D12::D3D12_RESOURCE_BARRIER_FLAG_NONE, + Anonymous: Direct3D12::D3D12_RESOURCE_BARRIER_0 { + // Note: this assumes `D3D12_RESOURCE_STATE_RENDER_TARGET`. + // If it's not the case, we can include the `TextureUses` in `PassResolve`. + Transition: mem::ManuallyDrop::new( + Direct3D12::D3D12_RESOURCE_TRANSITION_BARRIER { + pResource: unsafe { borrow_interface_temporarily(&resolve.dst.0) }, + Subresource: resolve.dst.1, + StateBefore: Direct3D12::D3D12_RESOURCE_STATE_RENDER_TARGET, + StateAfter: Direct3D12::D3D12_RESOURCE_STATE_RESOLVE_DEST, + }, + ), + }, + }; + self.temp.barriers.push(barrier); + } + + if !self.temp.barriers.is_empty() { + profiling::scope!("ID3D12GraphicsCommandList::ResourceBarrier"); + unsafe { list.ResourceBarrier(&self.temp.barriers) }; + } + + for resolve in self.pass.resolves.iter() { + profiling::scope!("ID3D12GraphicsCommandList::ResolveSubresource"); + unsafe { + list.ResolveSubresource( + &resolve.dst.0, + resolve.dst.1, + &resolve.src.0, + resolve.src.1, + resolve.format, + ) + }; + } + + // Flip all the barriers to reverse, back into `COLOR_TARGET`. + for barrier in self.temp.barriers.iter_mut() { + let transition = unsafe { &mut *barrier.Anonymous.Transition }; + mem::swap(&mut transition.StateBefore, &mut transition.StateAfter); + } + if !self.temp.barriers.is_empty() { + profiling::scope!("ID3D12GraphicsCommandList::ResourceBarrier"); + unsafe { list.ResourceBarrier(&self.temp.barriers) }; + } + } + + self.write_pass_end_timestamp_if_requested(); + + unsafe { self.end_pass() }; + } + + unsafe fn set_bind_group( + &mut self, + layout: &super::PipelineLayout, + index: u32, + group: &super::BindGroup, + dynamic_offsets: &[wgt::DynamicOffset], + ) { + let info = layout.bind_group_infos[index as usize].as_ref().unwrap(); + let mut root_index = info.base_root_index as usize; + + // Bind CBV/SRC/UAV descriptor tables + if info.tables.contains(super::TableTypes::SRV_CBV_UAV) { + self.pass.root_elements[root_index] = + super::RootElement::DescriptorTable(group.handle_views.unwrap().gpu); + root_index += 1; + } + + let mut offsets_index = 0; + if let Some(dynamic_storage_buffer_offsets) = info.dynamic_storage_buffer_offsets.as_ref() { + let root_index = dynamic_storage_buffer_offsets.root_index; + let range = &dynamic_storage_buffer_offsets.range; + + if range.end > self.pass.dynamic_storage_buffer_offsets.len() { + self.pass + .dynamic_storage_buffer_offsets + .resize(range.end, 0); + } + + offsets_index += range.start; + + self.pass.root_elements[root_index as usize] = + super::RootElement::DynamicStorageBufferOffsets { + start: range.start, + end: range.end, + }; + + if self.pass.layout.signature == layout.shared.signature { + self.pass.dirty_root_elements |= 1 << root_index; + } else { + // D3D12 requires full reset on signature change + // but we don't reset it here since it will be reset below + }; + } + + // Bind root descriptors for dynamic uniform buffers + // or set root constants for offsets of dynamic storage buffers + for (&dynamic_buffer, &offset) in group.dynamic_buffers.iter().zip(dynamic_offsets) { + match dynamic_buffer { + super::DynamicBuffer::Uniform(gpu_base) => { + self.pass.root_elements[root_index] = + super::RootElement::DynamicUniformBuffer { + address: Direct3D12::D3D12_GPU_DESCRIPTOR_HANDLE { + ptr: gpu_base.ptr + offset as u64, + }, + }; + root_index += 1; + } + super::DynamicBuffer::Storage => { + self.pass.dynamic_storage_buffer_offsets[offsets_index] = offset; + offsets_index += 1; + } + } + } + + if self.pass.layout.signature == layout.shared.signature { + self.pass.dirty_root_elements |= (1 << root_index) - (1 << info.base_root_index); + } else { + // D3D12 requires full reset on signature change + self.reset_signature(&layout.shared); + }; + } + unsafe fn set_immediates( + &mut self, + layout: &super::PipelineLayout, + offset_bytes: u32, + data: &[u32], + ) { + let offset_words = offset_bytes as usize / 4; + + let info = layout.shared.immediates_info.as_ref().unwrap(); + + self.pass.root_elements[info.root_index as usize] = super::RootElement::Immediates; + + self.pass.immediates[offset_words..(offset_words + data.len())].copy_from_slice(data); + + if self.pass.layout.signature == layout.shared.signature { + self.pass.dirty_root_elements |= 1 << info.root_index; + } else { + // D3D12 requires full reset on signature change + self.reset_signature(&layout.shared); + }; + } + + unsafe fn insert_debug_marker(&mut self, label: &str) { + let (wide_label, size) = self.temp.prepare_marker(label); + unsafe { + self.list + .as_ref() + .unwrap() + .SetMarker(0, Some(wide_label.as_ptr().cast()), size) + }; + } + unsafe fn begin_debug_marker(&mut self, group_label: &str) { + let (wide_label, size) = self.temp.prepare_marker(group_label); + unsafe { + self.list + .as_ref() + .unwrap() + .BeginEvent(0, Some(wide_label.as_ptr().cast()), size) + }; + } + unsafe fn end_debug_marker(&mut self) { + unsafe { self.list.as_ref().unwrap().EndEvent() } + } + + unsafe fn set_render_pipeline(&mut self, pipeline: &super::RenderPipeline) { + let list = self.list.clone().unwrap(); + + if self.pass.layout.signature != pipeline.layout.signature { + // D3D12 requires full reset on signature change + unsafe { list.SetGraphicsRootSignature(pipeline.layout.signature.as_ref()) }; + self.reset_signature(&pipeline.layout); + }; + + unsafe { list.SetPipelineState(&pipeline.raw) }; + unsafe { list.IASetPrimitiveTopology(pipeline.topology) }; + + for (index, (vb, &stride)) in self + .pass + .vertex_buffers + .iter_mut() + .zip(pipeline.vertex_strides.iter()) + .enumerate() + { + if let Some(stride) = stride { + if vb.StrideInBytes != stride { + vb.StrideInBytes = stride; + self.pass.dirty_vertex_buffers |= 1 << index; + } + } + } + } + + unsafe fn set_index_buffer<'a>( + &mut self, + binding: crate::BufferBinding<'a, super::Buffer>, + format: wgt::IndexFormat, + ) { + let ibv = Direct3D12::D3D12_INDEX_BUFFER_VIEW { + BufferLocation: binding.resolve_address(), + SizeInBytes: binding.resolve_size().try_into().unwrap(), + Format: auxil::dxgi::conv::map_index_format(format), + }; + + unsafe { self.list.as_ref().unwrap().IASetIndexBuffer(Some(&ibv)) } + } + unsafe fn set_vertex_buffer<'a>( + &mut self, + index: u32, + binding: crate::BufferBinding<'a, super::Buffer>, + ) { + let vb = &mut self.pass.vertex_buffers[index as usize]; + vb.BufferLocation = binding.resolve_address(); + vb.SizeInBytes = binding.resolve_size().try_into().unwrap(); + self.pass.dirty_vertex_buffers |= 1 << index; + } + + unsafe fn set_viewport(&mut self, rect: &crate::Rect<f32>, depth_range: Range<f32>) { + let raw_vp = Direct3D12::D3D12_VIEWPORT { + TopLeftX: rect.x, + TopLeftY: rect.y, + Width: rect.w, + Height: rect.h, + MinDepth: depth_range.start, + MaxDepth: depth_range.end, + }; + unsafe { + self.list + .as_ref() + .unwrap() + .RSSetViewports(core::slice::from_ref(&raw_vp)) + } + } + unsafe fn set_scissor_rect(&mut self, rect: &crate::Rect<u32>) { + let raw_rect = Foundation::RECT { + left: rect.x as i32, + top: rect.y as i32, + right: (rect.x + rect.w) as i32, + bottom: (rect.y + rect.h) as i32, + }; + unsafe { + self.list + .as_ref() + .unwrap() + .RSSetScissorRects(core::slice::from_ref(&raw_rect)) + } + } + unsafe fn set_stencil_reference(&mut self, value: u32) { + unsafe { self.list.as_ref().unwrap().OMSetStencilRef(value) } + } + unsafe fn set_blend_constants(&mut self, color: &[f32; 4]) { + unsafe { self.list.as_ref().unwrap().OMSetBlendFactor(Some(color)) } + } + + unsafe fn draw( + &mut self, + first_vertex: u32, + vertex_count: u32, + first_instance: u32, + instance_count: u32, + ) { + unsafe { self.prepare_draw(first_vertex as i32, first_instance) }; + unsafe { + self.list.as_ref().unwrap().DrawInstanced( + vertex_count, + instance_count, + first_vertex, + first_instance, + ) + } + } + unsafe fn draw_indexed( + &mut self, + first_index: u32, + index_count: u32, + base_vertex: i32, + first_instance: u32, + instance_count: u32, + ) { + unsafe { self.prepare_draw(base_vertex, first_instance) }; + unsafe { + self.list.as_ref().unwrap().DrawIndexedInstanced( + index_count, + instance_count, + first_index, + base_vertex, + first_instance, + ) + } + } + unsafe fn draw_mesh_tasks( + &mut self, + group_count_x: u32, + group_count_y: u32, + group_count_z: u32, + ) { + self.prepare_dispatch([group_count_x, group_count_y, group_count_z]); + let cmd_list6: Direct3D12::ID3D12GraphicsCommandList6 = + self.list.as_ref().unwrap().cast().unwrap(); + unsafe { + cmd_list6.DispatchMesh(group_count_x, group_count_y, group_count_z); + } + } + unsafe fn draw_indirect( + &mut self, + buffer: &super::Buffer, + offset: wgt::BufferAddress, + draw_count: u32, + ) { + if self + .pass + .layout + .special_constants + .as_ref() + .and_then(|sc| sc.indirect_cmd_signatures.as_ref()) + .is_some() + { + unsafe { self.prepare_vertex_buffers() }; + self.update_root_elements(); + } else { + unsafe { self.prepare_draw(0, 0) }; + } + + let cmd_signature = &self + .pass + .layout + .special_constants + .as_ref() + .and_then(|sc| sc.indirect_cmd_signatures.as_ref()) + .unwrap_or_else(|| &self.shared.cmd_signatures) + .draw; + unsafe { + self.list.as_ref().unwrap().ExecuteIndirect( + cmd_signature, + draw_count, + &buffer.resource, + offset, + None, + 0, + ) + } + } + unsafe fn draw_indexed_indirect( + &mut self, + buffer: &super::Buffer, + offset: wgt::BufferAddress, + draw_count: u32, + ) { + if self + .pass + .layout + .special_constants + .as_ref() + .and_then(|sc| sc.indirect_cmd_signatures.as_ref()) + .is_some() + { + unsafe { self.prepare_vertex_buffers() }; + self.update_root_elements(); + } else { + unsafe { self.prepare_draw(0, 0) }; + } + + let cmd_signature = &self + .pass + .layout + .special_constants + .as_ref() + .and_then(|sc| sc.indirect_cmd_signatures.as_ref()) + .unwrap_or_else(|| &self.shared.cmd_signatures) + .draw_indexed; + unsafe { + self.list.as_ref().unwrap().ExecuteIndirect( + cmd_signature, + draw_count, + &buffer.resource, + offset, + None, + 0, + ) + } + } + unsafe fn draw_mesh_tasks_indirect( + &mut self, + buffer: &<Self::A as crate::Api>::Buffer, + offset: wgt::BufferAddress, + draw_count: u32, + ) { + self.prepare_dispatch([0; 3]); + let cmd_list6: Direct3D12::ID3D12GraphicsCommandList6 = + self.list.as_ref().unwrap().cast().unwrap(); + let Some(cmd_signature) = &self.shared.cmd_signatures.draw_mesh else { + panic!("Feature `MESH_SHADING` not enabled"); + }; + unsafe { + cmd_list6.ExecuteIndirect(cmd_signature, draw_count, &buffer.resource, offset, None, 0); + } + } + unsafe fn draw_indirect_count( + &mut self, + buffer: &super::Buffer, + offset: wgt::BufferAddress, + count_buffer: &super::Buffer, + count_offset: wgt::BufferAddress, + max_count: u32, + ) { + unsafe { self.prepare_draw(0, 0) }; + unsafe { + self.list.as_ref().unwrap().ExecuteIndirect( + &self.shared.cmd_signatures.draw, + max_count, + &buffer.resource, + offset, + &count_buffer.resource, + count_offset, + ) + } + } + unsafe fn draw_indexed_indirect_count( + &mut self, + buffer: &super::Buffer, + offset: wgt::BufferAddress, + count_buffer: &super::Buffer, + count_offset: wgt::BufferAddress, + max_count: u32, + ) { + unsafe { self.prepare_draw(0, 0) }; + unsafe { + self.list.as_ref().unwrap().ExecuteIndirect( + &self.shared.cmd_signatures.draw_indexed, + max_count, + &buffer.resource, + offset, + &count_buffer.resource, + count_offset, + ) + } + } + unsafe fn draw_mesh_tasks_indirect_count( + &mut self, + buffer: &<Self::A as crate::Api>::Buffer, + offset: wgt::BufferAddress, + count_buffer: &<Self::A as crate::Api>::Buffer, + count_offset: wgt::BufferAddress, + max_count: u32, + ) { + self.prepare_dispatch([0; 3]); + let cmd_list6: Direct3D12::ID3D12GraphicsCommandList6 = + self.list.as_ref().unwrap().cast().unwrap(); + let Some(ref command_signature) = self.shared.cmd_signatures.draw_mesh else { + panic!("Feature `MESH_SHADING` not enabled"); + }; + unsafe { + cmd_list6.ExecuteIndirect( + command_signature, + max_count, + &buffer.resource, + offset, + &count_buffer.resource, + count_offset, + ); + } + } + + // compute + + unsafe fn begin_compute_pass<'a>( + &mut self, + desc: &crate::ComputePassDescriptor<'a, super::QuerySet>, + ) { + unsafe { self.begin_pass(super::PassKind::Compute, desc.label) }; + + if let Some(timestamp_writes) = desc.timestamp_writes.as_ref() { + if let Some(index) = timestamp_writes.beginning_of_pass_write_index { + unsafe { + self.write_timestamp(timestamp_writes.query_set, index); + } + } + self.end_of_pass_timer_query = timestamp_writes + .end_of_pass_write_index + .map(|index| (timestamp_writes.query_set.raw.clone(), index)); + } + } + unsafe fn end_compute_pass(&mut self) { + self.write_pass_end_timestamp_if_requested(); + unsafe { self.end_pass() }; + } + + unsafe fn set_compute_pipeline(&mut self, pipeline: &super::ComputePipeline) { + let list = self.list.clone().unwrap(); + + if self.pass.layout.signature != pipeline.layout.signature { + // D3D12 requires full reset on signature change + unsafe { list.SetComputeRootSignature(pipeline.layout.signature.as_ref()) }; + self.reset_signature(&pipeline.layout); + }; + + unsafe { list.SetPipelineState(&pipeline.raw) } + } + + unsafe fn dispatch_workgroups(&mut self, count @ [x, y, z]: [u32; 3]) { + self.prepare_dispatch(count); + unsafe { self.list.as_ref().unwrap().Dispatch(x, y, z) } + } + + unsafe fn dispatch_workgroups_indirect( + &mut self, + buffer: &super::Buffer, + offset: wgt::BufferAddress, + ) { + if self + .pass + .layout + .special_constants + .as_ref() + .and_then(|sc| sc.indirect_cmd_signatures.as_ref()) + .is_some() + { + self.update_root_elements(); + } else { + self.prepare_dispatch([0; 3]); + } + + let cmd_signature = &self + .pass + .layout + .special_constants + .as_ref() + .and_then(|sc| sc.indirect_cmd_signatures.as_ref()) + .unwrap_or_else(|| &self.shared.cmd_signatures) + .dispatch; + unsafe { + self.list.as_ref().unwrap().ExecuteIndirect( + cmd_signature, + 1, + &buffer.resource, + offset, + None, + 0, + ) + } + } + + unsafe fn build_acceleration_structures<'a, T>( + &mut self, + _descriptor_count: u32, + descriptors: T, + ) where + super::Api: 'a, + T: IntoIterator< + Item = crate::BuildAccelerationStructureDescriptor< + 'a, + super::Buffer, + super::AccelerationStructure, + >, + >, + { + // Implement using `BuildRaytracingAccelerationStructure`: + // https://microsoft.github.io/DirectX-Specs/d3d/Raytracing.html#buildraytracingaccelerationstructure + let list = self + .list + .as_ref() + .unwrap() + .cast::<Direct3D12::ID3D12GraphicsCommandList4>() + .unwrap(); + for descriptor in descriptors { + // TODO: This is the same as getting build sizes apart from requiring buffers, should this be de-duped? + let mut geometry_desc; + let ty; + let inputs0; + let num_desc; + match descriptor.entries { + AccelerationStructureEntries::Instances(instances) => { + let desc_address = unsafe { + instances + .buffer + .expect("needs buffer to build") + .resource + .GetGPUVirtualAddress() + } + instances.offset as u64; + ty = Direct3D12::D3D12_RAYTRACING_ACCELERATION_STRUCTURE_TYPE_TOP_LEVEL; + inputs0 = Direct3D12::D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_INPUTS_0 { + InstanceDescs: desc_address, + }; + num_desc = instances.count; + } + AccelerationStructureEntries::Triangles(triangles) => { + geometry_desc = Vec::with_capacity(triangles.len()); + for triangle in triangles { + let transform_address = + triangle.transform.as_ref().map_or(0, |transform| unsafe { + transform.buffer.resource.GetGPUVirtualAddress() + + transform.offset as u64 + }); + let index_format = triangle + .indices + .as_ref() + .map_or(Dxgi::Common::DXGI_FORMAT_UNKNOWN, |indices| { + auxil::dxgi::conv::map_index_format(indices.format) + }); + let vertex_format = + auxil::dxgi::conv::map_vertex_format(triangle.vertex_format); + let index_count = + triangle.indices.as_ref().map_or(0, |indices| indices.count); + let index_address = triangle.indices.as_ref().map_or(0, |indices| unsafe { + indices + .buffer + .expect("needs buffer to build") + .resource + .GetGPUVirtualAddress() + + indices.offset as u64 + }); + let vertex_address = unsafe { + triangle + .vertex_buffer + .expect("needs buffer to build") + .resource + .GetGPUVirtualAddress() + + (triangle.first_vertex as u64 * triangle.vertex_stride) + }; + + let triangle_desc = Direct3D12::D3D12_RAYTRACING_GEOMETRY_TRIANGLES_DESC { + Transform3x4: transform_address, + IndexFormat: index_format, + VertexFormat: vertex_format, + IndexCount: index_count, + VertexCount: triangle.vertex_count, + IndexBuffer: index_address, + VertexBuffer: Direct3D12::D3D12_GPU_VIRTUAL_ADDRESS_AND_STRIDE { + StartAddress: vertex_address, + StrideInBytes: triangle.vertex_stride, + }, + }; + + geometry_desc.push(Direct3D12::D3D12_RAYTRACING_GEOMETRY_DESC { + Type: Direct3D12::D3D12_RAYTRACING_GEOMETRY_TYPE_TRIANGLES, + Flags: conv::map_acceleration_structure_geometry_flags(triangle.flags), + Anonymous: Direct3D12::D3D12_RAYTRACING_GEOMETRY_DESC_0 { + Triangles: triangle_desc, + }, + }) + } + ty = Direct3D12::D3D12_RAYTRACING_ACCELERATION_STRUCTURE_TYPE_BOTTOM_LEVEL; + inputs0 = Direct3D12::D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_INPUTS_0 { + pGeometryDescs: geometry_desc.as_ptr(), + }; + num_desc = geometry_desc.len() as u32; + } + AccelerationStructureEntries::AABBs(aabbs) => { + geometry_desc = Vec::with_capacity(aabbs.len()); + for aabb in aabbs { + let aabb_address = unsafe { + aabb.buffer + .expect("needs buffer to build") + .resource + .GetGPUVirtualAddress() + + (aabb.offset as u64 * aabb.stride) + }; + + let aabb_desc = Direct3D12::D3D12_RAYTRACING_GEOMETRY_AABBS_DESC { + AABBCount: aabb.count as u64, + AABBs: Direct3D12::D3D12_GPU_VIRTUAL_ADDRESS_AND_STRIDE { + StartAddress: aabb_address, + StrideInBytes: aabb.stride, + }, + }; + + geometry_desc.push(Direct3D12::D3D12_RAYTRACING_GEOMETRY_DESC { + Type: Direct3D12::D3D12_RAYTRACING_GEOMETRY_TYPE_PROCEDURAL_PRIMITIVE_AABBS, + Flags: conv::map_acceleration_structure_geometry_flags(aabb.flags), + Anonymous: Direct3D12::D3D12_RAYTRACING_GEOMETRY_DESC_0 { + AABBs: aabb_desc, + }, + }) + } + ty = Direct3D12::D3D12_RAYTRACING_ACCELERATION_STRUCTURE_TYPE_BOTTOM_LEVEL; + inputs0 = Direct3D12::D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_INPUTS_0 { + pGeometryDescs: geometry_desc.as_ptr(), + }; + num_desc = geometry_desc.len() as u32; + } + }; + let acceleration_structure_inputs = + Direct3D12::D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_INPUTS { + Type: ty, + Flags: conv::map_acceleration_structure_build_flags( + descriptor.flags, + Some(descriptor.mode), + ), + NumDescs: num_desc, + DescsLayout: Direct3D12::D3D12_ELEMENTS_LAYOUT_ARRAY, + Anonymous: inputs0, + }; + + let dst_acceleration_structure_address = unsafe { + descriptor + .destination_acceleration_structure + .resource + .GetGPUVirtualAddress() + }; + let src_acceleration_structure_address = descriptor + .source_acceleration_structure + .as_ref() + .map_or(0, |source| unsafe { + source.resource.GetGPUVirtualAddress() + }); + let scratch_address = unsafe { + descriptor.scratch_buffer.resource.GetGPUVirtualAddress() + + descriptor.scratch_buffer_offset + }; + + let desc = Direct3D12::D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC { + DestAccelerationStructureData: dst_acceleration_structure_address, + Inputs: acceleration_structure_inputs, + SourceAccelerationStructureData: src_acceleration_structure_address, + ScratchAccelerationStructureData: scratch_address, + }; + unsafe { list.BuildRaytracingAccelerationStructure(&desc, None) }; + } + } + + unsafe fn place_acceleration_structure_barrier( + &mut self, + _barriers: crate::AccelerationStructureBarrier, + ) { + // TODO: This is not very optimal, we should be using [enhanced barriers](https://microsoft.github.io/DirectX-Specs/d3d/D3D12EnhancedBarriers.html) if possible + let list = self + .list + .as_ref() + .unwrap() + .cast::<Direct3D12::ID3D12GraphicsCommandList4>() + .unwrap(); + unsafe { + list.ResourceBarrier(&[Direct3D12::D3D12_RESOURCE_BARRIER { + Type: Direct3D12::D3D12_RESOURCE_BARRIER_TYPE_UAV, + Flags: Direct3D12::D3D12_RESOURCE_BARRIER_FLAG_NONE, + Anonymous: Direct3D12::D3D12_RESOURCE_BARRIER_0 { + UAV: mem::ManuallyDrop::new(Direct3D12::D3D12_RESOURCE_UAV_BARRIER { + pResource: Default::default(), + }), + }, + }]) + } + } + + unsafe fn copy_acceleration_structure_to_acceleration_structure( + &mut self, + src: &super::AccelerationStructure, + dst: &super::AccelerationStructure, + copy: wgt::AccelerationStructureCopy, + ) { + let list = self + .list + .as_ref() + .unwrap() + .cast::<Direct3D12::ID3D12GraphicsCommandList4>() + .unwrap(); + unsafe { + list.CopyRaytracingAccelerationStructure( + dst.resource.GetGPUVirtualAddress(), + src.resource.GetGPUVirtualAddress(), + conv::map_acceleration_structure_copy_mode(copy), + ) + } + } + + unsafe fn set_acceleration_structure_dependencies( + _command_buffers: &[&super::CommandBuffer], + _dependencies: &[&super::AccelerationStructure], + ) { + } + + unsafe fn begin_ray_tracing_pass(&mut self, _desc: &crate::RayTracingPassDescriptor) { + unreachable!("Ray tracing pipelines not supported") + } + + unsafe fn end_ray_tracing_pass(&mut self) { + unreachable!("Ray tracing pipelines not supported") + } + + unsafe fn set_ray_tracing_pipeline( + &mut self, + _pipeline: &<Self::A as crate::Api>::RayTracingPipeline, + ) { + unreachable!("Ray tracing pipelines not supported") + } + + unsafe fn trace_rays( + &mut self, + _count: [u32; 3], + _ray_generation_group_data: crate::PipelineGroupData<super::Buffer>, + _miss_group_data: crate::PipelineGroupData<super::Buffer>, + _intersection_group_data: crate::PipelineGroupData<super::Buffer>, + ) { + unreachable!("Ray tracing pipelines not supported") + } +} diff --git a/app/vendor/rune/vendor/wgpu-hal/src/dx12/conv.rs b/app/vendor/rune/vendor/wgpu-hal/src/dx12/conv.rs new file mode 100644 index 0000000..6cc2bec --- /dev/null +++ b/app/vendor/rune/vendor/wgpu-hal/src/dx12/conv.rs @@ -0,0 +1,467 @@ +use windows::Win32::Graphics::{Direct3D, Direct3D12, Dxgi}; + +pub fn map_buffer_usage_to_resource_flags( + usage: wgt::BufferUses, +) -> Direct3D12::D3D12_RESOURCE_FLAGS { + let mut flags = Direct3D12::D3D12_RESOURCE_FLAG_NONE; + if usage.contains(wgt::BufferUses::STORAGE_READ_WRITE) + || usage.contains(wgt::BufferUses::ACCELERATION_STRUCTURE_QUERY) + { + flags |= Direct3D12::D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; + } + flags +} + +pub fn map_buffer_descriptor( + desc: &crate::BufferDescriptor<'_>, +) -> Direct3D12::D3D12_RESOURCE_DESC { + Direct3D12::D3D12_RESOURCE_DESC { + Dimension: Direct3D12::D3D12_RESOURCE_DIMENSION_BUFFER, + Alignment: 0, + Width: desc.size, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + Format: Dxgi::Common::DXGI_FORMAT_UNKNOWN, + SampleDesc: Dxgi::Common::DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, + Layout: Direct3D12::D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + Flags: map_buffer_usage_to_resource_flags(desc.usage), + } +} + +pub fn map_texture_dimension(dim: wgt::TextureDimension) -> Direct3D12::D3D12_RESOURCE_DIMENSION { + match dim { + wgt::TextureDimension::D1 => Direct3D12::D3D12_RESOURCE_DIMENSION_TEXTURE1D, + wgt::TextureDimension::D2 => Direct3D12::D3D12_RESOURCE_DIMENSION_TEXTURE2D, + wgt::TextureDimension::D3 => Direct3D12::D3D12_RESOURCE_DIMENSION_TEXTURE3D, + } +} + +pub fn map_texture_usage_to_resource_flags( + usage: wgt::TextureUses, +) -> Direct3D12::D3D12_RESOURCE_FLAGS { + let mut flags = Direct3D12::D3D12_RESOURCE_FLAG_NONE; + + if usage.contains(wgt::TextureUses::COLOR_TARGET) { + flags |= Direct3D12::D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET; + } + if usage + .intersects(wgt::TextureUses::DEPTH_STENCIL_READ | wgt::TextureUses::DEPTH_STENCIL_WRITE) + { + flags |= Direct3D12::D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL; + if !usage.contains(wgt::TextureUses::RESOURCE) { + flags |= Direct3D12::D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE; + } + } + if usage.intersects( + wgt::TextureUses::STORAGE_READ_ONLY + | wgt::TextureUses::STORAGE_WRITE_ONLY + | wgt::TextureUses::STORAGE_READ_WRITE, + ) { + flags |= Direct3D12::D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; + } + + flags +} + +pub fn map_address_mode(mode: wgt::AddressMode) -> Direct3D12::D3D12_TEXTURE_ADDRESS_MODE { + use wgt::AddressMode as Am; + match mode { + Am::Repeat => Direct3D12::D3D12_TEXTURE_ADDRESS_MODE_WRAP, + Am::MirrorRepeat => Direct3D12::D3D12_TEXTURE_ADDRESS_MODE_MIRROR, + Am::ClampToEdge => Direct3D12::D3D12_TEXTURE_ADDRESS_MODE_CLAMP, + Am::ClampToBorder => Direct3D12::D3D12_TEXTURE_ADDRESS_MODE_BORDER, + //Am::MirrorClamp => Direct3D12::D3D12_TEXTURE_ADDRESS_MODE_MIRROR_ONCE, + } +} + +pub fn map_filter_mode(mode: wgt::FilterMode) -> Direct3D12::D3D12_FILTER_TYPE { + match mode { + wgt::FilterMode::Nearest => Direct3D12::D3D12_FILTER_TYPE_POINT, + wgt::FilterMode::Linear => Direct3D12::D3D12_FILTER_TYPE_LINEAR, + } +} + +pub fn map_mipmap_filter_mode(mode: wgt::MipmapFilterMode) -> Direct3D12::D3D12_FILTER_TYPE { + match mode { + wgt::MipmapFilterMode::Nearest => Direct3D12::D3D12_FILTER_TYPE_POINT, + wgt::MipmapFilterMode::Linear => Direct3D12::D3D12_FILTER_TYPE_LINEAR, + } +} + +pub fn map_comparison(func: wgt::CompareFunction) -> Direct3D12::D3D12_COMPARISON_FUNC { + use wgt::CompareFunction as Cf; + match func { + Cf::Never => Direct3D12::D3D12_COMPARISON_FUNC_NEVER, + Cf::Less => Direct3D12::D3D12_COMPARISON_FUNC_LESS, + Cf::LessEqual => Direct3D12::D3D12_COMPARISON_FUNC_LESS_EQUAL, + Cf::Equal => Direct3D12::D3D12_COMPARISON_FUNC_EQUAL, + Cf::GreaterEqual => Direct3D12::D3D12_COMPARISON_FUNC_GREATER_EQUAL, + Cf::Greater => Direct3D12::D3D12_COMPARISON_FUNC_GREATER, + Cf::NotEqual => Direct3D12::D3D12_COMPARISON_FUNC_NOT_EQUAL, + Cf::Always => Direct3D12::D3D12_COMPARISON_FUNC_ALWAYS, + } +} + +pub fn map_border_color(border_color: Option<wgt::SamplerBorderColor>) -> [f32; 4] { + use wgt::SamplerBorderColor as Sbc; + match border_color { + Some(Sbc::TransparentBlack) | Some(Sbc::Zero) | None => [0.0; 4], + Some(Sbc::OpaqueBlack) => [0.0, 0.0, 0.0, 1.0], + Some(Sbc::OpaqueWhite) => [1.0; 4], + } +} + +pub fn map_visibility(visibility: wgt::ShaderStages) -> Direct3D12::D3D12_SHADER_VISIBILITY { + match visibility { + wgt::ShaderStages::VERTEX => Direct3D12::D3D12_SHADER_VISIBILITY_VERTEX, + wgt::ShaderStages::FRAGMENT => Direct3D12::D3D12_SHADER_VISIBILITY_PIXEL, + _ => Direct3D12::D3D12_SHADER_VISIBILITY_ALL, + } +} + +pub fn map_binding_type(ty: &wgt::BindingType) -> Direct3D12::D3D12_DESCRIPTOR_RANGE_TYPE { + use wgt::BindingType as Bt; + match *ty { + Bt::Sampler { .. } => Direct3D12::D3D12_DESCRIPTOR_RANGE_TYPE_SAMPLER, + Bt::Buffer { + ty: wgt::BufferBindingType::Uniform, + .. + } => Direct3D12::D3D12_DESCRIPTOR_RANGE_TYPE_CBV, + Bt::Buffer { + ty: wgt::BufferBindingType::Storage { read_only: true }, + .. + } + | Bt::Texture { .. } => Direct3D12::D3D12_DESCRIPTOR_RANGE_TYPE_SRV, + Bt::Buffer { + ty: wgt::BufferBindingType::Storage { read_only: false }, + .. + } + | Bt::StorageTexture { .. } => Direct3D12::D3D12_DESCRIPTOR_RANGE_TYPE_UAV, + Bt::AccelerationStructure { .. } => Direct3D12::D3D12_DESCRIPTOR_RANGE_TYPE_SRV, + // External textures require multiple bindings and therefore cannot + // be mapped to a single descriptor range type. They must be handled + // separately by the caller. + Bt::ExternalTexture => unreachable!("External textures must be handled separately"), + } +} + +pub fn map_buffer_usage_to_state(usage: wgt::BufferUses) -> Direct3D12::D3D12_RESOURCE_STATES { + use wgt::BufferUses as Bu; + let mut state = Direct3D12::D3D12_RESOURCE_STATE_COMMON; + + if usage.intersects(Bu::COPY_SRC) { + state |= Direct3D12::D3D12_RESOURCE_STATE_COPY_SOURCE; + } + if usage.intersects(Bu::COPY_DST) { + state |= Direct3D12::D3D12_RESOURCE_STATE_COPY_DEST; + } + if usage.intersects(Bu::INDEX) { + state |= Direct3D12::D3D12_RESOURCE_STATE_INDEX_BUFFER; + } + if usage.intersects(Bu::VERTEX | Bu::UNIFORM) { + state |= Direct3D12::D3D12_RESOURCE_STATE_VERTEX_AND_CONSTANT_BUFFER; + } + if usage.intersects(Bu::STORAGE_READ_WRITE) { + state |= Direct3D12::D3D12_RESOURCE_STATE_UNORDERED_ACCESS; + } else if usage.intersects(Bu::STORAGE_READ_ONLY) { + state |= Direct3D12::D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE + | Direct3D12::D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE; + } + if usage.intersects(Bu::INDIRECT) { + state |= Direct3D12::D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT; + } + if usage.intersects(Bu::ACCELERATION_STRUCTURE_QUERY) { + state |= Direct3D12::D3D12_RESOURCE_STATE_UNORDERED_ACCESS; + } + state +} + +pub fn map_texture_usage_to_state(usage: wgt::TextureUses) -> Direct3D12::D3D12_RESOURCE_STATES { + use wgt::TextureUses as Tu; + let mut state = Direct3D12::D3D12_RESOURCE_STATE_COMMON; + //Note: `RESOLVE_SOURCE` and `RESOLVE_DEST` are not used here + //Note: `PRESENT` is the same as `COMMON` + if usage == wgt::TextureUses::UNINITIALIZED { + return state; + } + + if usage.intersects(Tu::COPY_SRC) { + state |= Direct3D12::D3D12_RESOURCE_STATE_COPY_SOURCE; + } + if usage.intersects(Tu::COPY_DST) { + state |= Direct3D12::D3D12_RESOURCE_STATE_COPY_DEST; + } + if usage.intersects(Tu::RESOURCE) { + state |= Direct3D12::D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE + | Direct3D12::D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE; + } + if usage.intersects(Tu::COLOR_TARGET) { + state |= Direct3D12::D3D12_RESOURCE_STATE_RENDER_TARGET; + } + if usage.intersects(Tu::DEPTH_STENCIL_READ) { + state |= Direct3D12::D3D12_RESOURCE_STATE_DEPTH_READ; + } + if usage.intersects(Tu::DEPTH_STENCIL_WRITE) { + state |= Direct3D12::D3D12_RESOURCE_STATE_DEPTH_WRITE; + } + if usage.intersects(Tu::STORAGE_READ_ONLY | Tu::STORAGE_WRITE_ONLY | Tu::STORAGE_READ_WRITE) { + state |= Direct3D12::D3D12_RESOURCE_STATE_UNORDERED_ACCESS; + } + state +} + +pub fn map_topology( + topology: wgt::PrimitiveTopology, +) -> ( + Direct3D12::D3D12_PRIMITIVE_TOPOLOGY_TYPE, + Direct3D::D3D_PRIMITIVE_TOPOLOGY, +) { + match topology { + wgt::PrimitiveTopology::PointList => ( + Direct3D12::D3D12_PRIMITIVE_TOPOLOGY_TYPE_POINT, + Direct3D::D3D_PRIMITIVE_TOPOLOGY_POINTLIST, + ), + wgt::PrimitiveTopology::LineList => ( + Direct3D12::D3D12_PRIMITIVE_TOPOLOGY_TYPE_LINE, + Direct3D::D3D_PRIMITIVE_TOPOLOGY_LINELIST, + ), + wgt::PrimitiveTopology::LineStrip => ( + Direct3D12::D3D12_PRIMITIVE_TOPOLOGY_TYPE_LINE, + Direct3D::D3D_PRIMITIVE_TOPOLOGY_LINESTRIP, + ), + wgt::PrimitiveTopology::TriangleList => ( + Direct3D12::D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE, + Direct3D::D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST, + ), + wgt::PrimitiveTopology::TriangleStrip => ( + Direct3D12::D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE, + Direct3D::D3D_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP, + ), + } +} + +pub fn map_polygon_mode(mode: wgt::PolygonMode) -> Direct3D12::D3D12_FILL_MODE { + match mode { + wgt::PolygonMode::Fill => Direct3D12::D3D12_FILL_MODE_SOLID, + wgt::PolygonMode::Line => Direct3D12::D3D12_FILL_MODE_WIREFRAME, + wgt::PolygonMode::Point => panic!( + "{:?} is not enabled for this backend", + wgt::Features::POLYGON_MODE_POINT + ), + } +} + +/// D3D12 doesn't support passing factors ending in `_COLOR` for alpha blending +/// (see <https://learn.microsoft.com/en-us/windows/win32/api/d3d12/ns-d3d12-d3d12_render_target_blend_desc>). +/// Therefore this function takes an additional `is_alpha` argument +/// which if set will return an equivalent `_ALPHA` factor. +fn map_blend_factor(factor: wgt::BlendFactor, is_alpha: bool) -> Direct3D12::D3D12_BLEND { + use wgt::BlendFactor as Bf; + match factor { + Bf::Zero => Direct3D12::D3D12_BLEND_ZERO, + Bf::One => Direct3D12::D3D12_BLEND_ONE, + Bf::Src if is_alpha => Direct3D12::D3D12_BLEND_SRC_ALPHA, + Bf::Src => Direct3D12::D3D12_BLEND_SRC_COLOR, + Bf::OneMinusSrc if is_alpha => Direct3D12::D3D12_BLEND_INV_SRC_ALPHA, + Bf::OneMinusSrc => Direct3D12::D3D12_BLEND_INV_SRC_COLOR, + Bf::Dst if is_alpha => Direct3D12::D3D12_BLEND_DEST_ALPHA, + Bf::Dst => Direct3D12::D3D12_BLEND_DEST_COLOR, + Bf::OneMinusDst if is_alpha => Direct3D12::D3D12_BLEND_INV_DEST_ALPHA, + Bf::OneMinusDst => Direct3D12::D3D12_BLEND_INV_DEST_COLOR, + Bf::SrcAlpha => Direct3D12::D3D12_BLEND_SRC_ALPHA, + Bf::OneMinusSrcAlpha => Direct3D12::D3D12_BLEND_INV_SRC_ALPHA, + Bf::DstAlpha => Direct3D12::D3D12_BLEND_DEST_ALPHA, + Bf::OneMinusDstAlpha => Direct3D12::D3D12_BLEND_INV_DEST_ALPHA, + Bf::Constant => Direct3D12::D3D12_BLEND_BLEND_FACTOR, + Bf::OneMinusConstant => Direct3D12::D3D12_BLEND_INV_BLEND_FACTOR, + Bf::SrcAlphaSaturated => Direct3D12::D3D12_BLEND_SRC_ALPHA_SAT, + Bf::Src1 if is_alpha => Direct3D12::D3D12_BLEND_SRC1_ALPHA, + Bf::Src1 => Direct3D12::D3D12_BLEND_SRC1_COLOR, + Bf::OneMinusSrc1 if is_alpha => Direct3D12::D3D12_BLEND_INV_SRC1_ALPHA, + Bf::OneMinusSrc1 => Direct3D12::D3D12_BLEND_INV_SRC1_COLOR, + Bf::Src1Alpha => Direct3D12::D3D12_BLEND_SRC1_ALPHA, + Bf::OneMinusSrc1Alpha => Direct3D12::D3D12_BLEND_INV_SRC1_ALPHA, + } +} + +fn map_blend_component( + component: &wgt::BlendComponent, + is_alpha: bool, +) -> ( + Direct3D12::D3D12_BLEND_OP, + Direct3D12::D3D12_BLEND, + Direct3D12::D3D12_BLEND, +) { + let raw_op = match component.operation { + wgt::BlendOperation::Add => Direct3D12::D3D12_BLEND_OP_ADD, + wgt::BlendOperation::Subtract => Direct3D12::D3D12_BLEND_OP_SUBTRACT, + wgt::BlendOperation::ReverseSubtract => Direct3D12::D3D12_BLEND_OP_REV_SUBTRACT, + wgt::BlendOperation::Min => Direct3D12::D3D12_BLEND_OP_MIN, + wgt::BlendOperation::Max => Direct3D12::D3D12_BLEND_OP_MAX, + }; + let raw_src = map_blend_factor(component.src_factor, is_alpha); + let raw_dst = map_blend_factor(component.dst_factor, is_alpha); + (raw_op, raw_src, raw_dst) +} + +pub fn map_render_targets( + color_targets: &[Option<wgt::ColorTargetState>], +) -> [Direct3D12::D3D12_RENDER_TARGET_BLEND_DESC; + Direct3D12::D3D12_SIMULTANEOUS_RENDER_TARGET_COUNT as usize] { + let dummy_target = Direct3D12::D3D12_RENDER_TARGET_BLEND_DESC { + BlendEnable: false.into(), + LogicOpEnable: false.into(), + SrcBlend: Direct3D12::D3D12_BLEND_ZERO, + DestBlend: Direct3D12::D3D12_BLEND_ZERO, + BlendOp: Direct3D12::D3D12_BLEND_OP_ADD, + SrcBlendAlpha: Direct3D12::D3D12_BLEND_ZERO, + DestBlendAlpha: Direct3D12::D3D12_BLEND_ZERO, + BlendOpAlpha: Direct3D12::D3D12_BLEND_OP_ADD, + LogicOp: Direct3D12::D3D12_LOGIC_OP_CLEAR, + RenderTargetWriteMask: 0, + }; + let mut raw_targets = + [dummy_target; Direct3D12::D3D12_SIMULTANEOUS_RENDER_TARGET_COUNT as usize]; + + for (raw, ct) in raw_targets.iter_mut().zip(color_targets.iter()) { + if let Some(ct) = ct.as_ref() { + raw.RenderTargetWriteMask = ct.write_mask.bits() as u8; + if let Some(ref blend) = ct.blend { + let (color_op, color_src, color_dst) = map_blend_component(&blend.color, false); + let (alpha_op, alpha_src, alpha_dst) = map_blend_component(&blend.alpha, true); + raw.BlendEnable = true.into(); + raw.BlendOp = color_op; + raw.SrcBlend = color_src; + raw.DestBlend = color_dst; + raw.BlendOpAlpha = alpha_op; + raw.SrcBlendAlpha = alpha_src; + raw.DestBlendAlpha = alpha_dst; + } + } + } + + raw_targets +} + +fn map_stencil_op(op: wgt::StencilOperation) -> Direct3D12::D3D12_STENCIL_OP { + use wgt::StencilOperation as So; + match op { + So::Keep => Direct3D12::D3D12_STENCIL_OP_KEEP, + So::Zero => Direct3D12::D3D12_STENCIL_OP_ZERO, + So::Replace => Direct3D12::D3D12_STENCIL_OP_REPLACE, + So::IncrementClamp => Direct3D12::D3D12_STENCIL_OP_INCR_SAT, + So::IncrementWrap => Direct3D12::D3D12_STENCIL_OP_INCR, + So::DecrementClamp => Direct3D12::D3D12_STENCIL_OP_DECR_SAT, + So::DecrementWrap => Direct3D12::D3D12_STENCIL_OP_DECR, + So::Invert => Direct3D12::D3D12_STENCIL_OP_INVERT, + } +} + +fn map_stencil_face(face: &wgt::StencilFaceState) -> Direct3D12::D3D12_DEPTH_STENCILOP_DESC { + Direct3D12::D3D12_DEPTH_STENCILOP_DESC { + StencilFailOp: map_stencil_op(face.fail_op), + StencilDepthFailOp: map_stencil_op(face.depth_fail_op), + StencilPassOp: map_stencil_op(face.pass_op), + StencilFunc: map_comparison(face.compare), + } +} + +pub fn map_depth_stencil(ds: &wgt::DepthStencilState) -> Direct3D12::D3D12_DEPTH_STENCIL_DESC { + Direct3D12::D3D12_DEPTH_STENCIL_DESC { + DepthEnable: ds.is_depth_enabled().into(), + DepthWriteMask: if ds.depth_write_enabled.unwrap_or_default() { + Direct3D12::D3D12_DEPTH_WRITE_MASK_ALL + } else { + Direct3D12::D3D12_DEPTH_WRITE_MASK_ZERO + }, + DepthFunc: map_comparison(ds.depth_compare.unwrap_or_default()), + StencilEnable: ds.stencil.is_enabled().into(), + StencilReadMask: ds.stencil.read_mask as u8, + StencilWriteMask: ds.stencil.write_mask as u8, + FrontFace: map_stencil_face(&ds.stencil.front), + BackFace: map_stencil_face(&ds.stencil.back), + } +} + +pub(crate) fn map_acceleration_structure_build_flags( + flags: wgt::AccelerationStructureFlags, + mode: Option<crate::AccelerationStructureBuildMode>, +) -> Direct3D12::D3D12_RAYTRACING_ACCELERATION_STRUCTURE_BUILD_FLAGS { + let mut d3d_flags = Default::default(); + if flags.contains(wgt::AccelerationStructureFlags::ALLOW_COMPACTION) { + d3d_flags |= + Direct3D12::D3D12_RAYTRACING_ACCELERATION_STRUCTURE_BUILD_FLAG_ALLOW_COMPACTION; + } + + if flags.contains(wgt::AccelerationStructureFlags::ALLOW_UPDATE) { + d3d_flags |= Direct3D12::D3D12_RAYTRACING_ACCELERATION_STRUCTURE_BUILD_FLAG_ALLOW_UPDATE; + } + + if flags.contains(wgt::AccelerationStructureFlags::LOW_MEMORY) { + d3d_flags |= Direct3D12::D3D12_RAYTRACING_ACCELERATION_STRUCTURE_BUILD_FLAG_MINIMIZE_MEMORY; + } + + if flags.contains(wgt::AccelerationStructureFlags::PREFER_FAST_BUILD) { + d3d_flags |= + Direct3D12::D3D12_RAYTRACING_ACCELERATION_STRUCTURE_BUILD_FLAG_PREFER_FAST_BUILD; + } + + if flags.contains(wgt::AccelerationStructureFlags::PREFER_FAST_TRACE) { + d3d_flags |= + Direct3D12::D3D12_RAYTRACING_ACCELERATION_STRUCTURE_BUILD_FLAG_PREFER_FAST_TRACE; + } + + if let Some(crate::AccelerationStructureBuildMode::Update) = mode { + d3d_flags |= Direct3D12::D3D12_RAYTRACING_ACCELERATION_STRUCTURE_BUILD_FLAG_PERFORM_UPDATE + } + + d3d_flags +} + +pub(crate) fn map_acceleration_structure_geometry_flags( + flags: wgt::AccelerationStructureGeometryFlags, +) -> Direct3D12::D3D12_RAYTRACING_GEOMETRY_FLAGS { + let mut d3d_flags = Default::default(); + if flags.contains(wgt::AccelerationStructureGeometryFlags::OPAQUE) { + d3d_flags |= Direct3D12::D3D12_RAYTRACING_GEOMETRY_FLAG_OPAQUE; + } + if flags.contains(wgt::AccelerationStructureGeometryFlags::NO_DUPLICATE_ANY_HIT_INVOCATION) { + d3d_flags |= Direct3D12::D3D12_RAYTRACING_GEOMETRY_FLAG_NO_DUPLICATE_ANYHIT_INVOCATION; + } + d3d_flags +} + +pub(crate) fn map_acceleration_structure_copy_mode( + mode: wgt::AccelerationStructureCopy, +) -> Direct3D12::D3D12_RAYTRACING_ACCELERATION_STRUCTURE_COPY_MODE { + match mode { + wgt::AccelerationStructureCopy::Clone => { + Direct3D12::D3D12_RAYTRACING_ACCELERATION_STRUCTURE_COPY_MODE_CLONE + } + wgt::AccelerationStructureCopy::Compact => { + Direct3D12::D3D12_RAYTRACING_ACCELERATION_STRUCTURE_COPY_MODE_COMPACT + } + } +} + +pub(crate) const fn make_shader_component_mapping( + src0: Direct3D12::D3D12_SHADER_COMPONENT_MAPPING, + src1: Direct3D12::D3D12_SHADER_COMPONENT_MAPPING, + src2: Direct3D12::D3D12_SHADER_COMPONENT_MAPPING, + src3: Direct3D12::D3D12_SHADER_COMPONENT_MAPPING, +) -> Direct3D12::D3D12_SHADER_COMPONENT_MAPPING { + const M: i32 = Direct3D12::D3D12_SHADER_COMPONENT_MAPPING_MASK as i32; + const S: i32 = Direct3D12::D3D12_SHADER_COMPONENT_MAPPING_SHIFT as i32; + Direct3D12::D3D12_SHADER_COMPONENT_MAPPING( + (src0.0 & M) + | (src1.0 & M) << S + | (src2.0 & M) << (S * 2) + | (src3.0 & M) << (S * 3) + | Direct3D12::D3D12_SHADER_COMPONENT_MAPPING_ALWAYS_SET_BIT_AVOIDING_ZEROMEM_MISTAKES + as i32, + ) +} diff --git a/app/vendor/rune/vendor/wgpu-hal/src/dx12/dcomp.rs b/app/vendor/rune/vendor/wgpu-hal/src/dx12/dcomp.rs new file mode 100644 index 0000000..035f9bd --- /dev/null +++ b/app/vendor/rune/vendor/wgpu-hal/src/dx12/dcomp.rs @@ -0,0 +1,120 @@ +use alloc::sync::Arc; +use core::{ffi, ptr}; + +use once_cell::sync::Lazy; +use windows::{ + core::Interface as _, + Win32::{Foundation::HWND, Graphics::DirectComposition}, +}; + +use super::DynLib; + +// Lazy-loaded DirectComposition library +#[derive(Debug)] +pub(crate) struct DCompLib { + lib: Lazy<Result<DynLib, crate::SurfaceError>>, +} + +impl DCompLib { + pub(crate) fn new() -> Self { + Self { + lib: Lazy::new(|| unsafe { + DynLib::new_system("dcomp.dll").map_err(|err| { + log::error!("Error loading dcomp.dll: {err}"); + crate::SurfaceError::Other("Error loading dcomp.dll") + }) + }), + } + } + + fn get_lib(&self) -> Result<&DynLib, crate::SurfaceError> { + match self.lib.as_ref() { + Ok(lib) => Ok(lib), + Err(err) => Err(err.clone()), + } + } + + pub(crate) fn create_device( + &self, + ) -> Result<DirectComposition::IDCompositionDevice, crate::SurfaceError> { + let lib = self.get_lib()?; + + // Calls windows::Win32::Graphics::DirectComposition::DCompositionCreateDevice2 on dcomp.dll + type Fun = extern "system" fn( + pdxdevice: *mut ffi::c_void, + riid: *const windows_core::GUID, + ppdcompdevice: *mut *mut ffi::c_void, + ) -> windows_core::HRESULT; + let func: libloading::Symbol<Fun> = + unsafe { lib.get(c"DCompositionCreateDevice2".to_bytes()) }?; + + let mut res: Option<DirectComposition::IDCompositionDevice> = None; + + (func)( + ptr::null_mut(), + &DirectComposition::IDCompositionDevice::IID, + <*mut _>::cast(&mut res), + ) + .map(|| res.unwrap()) + .map_err(|err| { + log::error!("DirectComposition::DCompositionCreateDevice2 failed: {err}"); + crate::SurfaceError::Other("DirectComposition::DCompositionCreateDevice2") + }) + } +} + +#[derive(Default)] +pub struct DCompState { + inner: Option<InnerState>, +} + +impl DCompState { + /// This will create a DirectComposition device and a target for the window handle if not already initialized. + /// If the device is already initialized, it will return the existing state. + pub unsafe fn get_or_init( + &mut self, + lib: &Arc<DCompLib>, + hwnd: &HWND, + ) -> Result<&mut InnerState, crate::SurfaceError> { + if self.inner.is_none() { + self.inner = Some(unsafe { InnerState::init(lib, hwnd) }?); + } + Ok(self.inner.as_mut().unwrap()) + } +} + +pub struct InnerState { + pub visual: DirectComposition::IDCompositionVisual, + pub device: DirectComposition::IDCompositionDevice, + // Must be kept alive but is otherwise unused after initialization. + pub _target: DirectComposition::IDCompositionTarget, +} + +impl InnerState { + /// Creates a DirectComposition device and a target for the given window handle. + pub unsafe fn init(lib: &Arc<DCompLib>, hwnd: &HWND) -> Result<Self, crate::SurfaceError> { + profiling::scope!("DCompState::init"); + let dcomp_device = lib.create_device()?; + + let target = unsafe { dcomp_device.CreateTargetForHwnd(*hwnd, false) }.map_err(|err| { + log::error!("IDCompositionDevice::CreateTargetForHwnd failed: {err}"); + crate::SurfaceError::Other("IDCompositionDevice::CreateTargetForHwnd") + })?; + + let visual = unsafe { dcomp_device.CreateVisual() }.map_err(|err| { + log::error!("IDCompositionDevice::CreateVisual failed: {err}"); + crate::SurfaceError::Other("IDCompositionDevice::CreateVisual") + })?; + + unsafe { target.SetRoot(&visual) }.map_err(|err| { + log::error!("IDCompositionTarget::SetRoot failed: {err}"); + crate::SurfaceError::Other("IDCompositionTarget::SetRoot") + })?; + + Ok(InnerState { + visual, + device: dcomp_device, + _target: target, + }) + } +} diff --git a/app/vendor/rune/vendor/wgpu-hal/src/dx12/descriptor.rs b/app/vendor/rune/vendor/wgpu-hal/src/dx12/descriptor.rs new file mode 100644 index 0000000..475a9e3 --- /dev/null +++ b/app/vendor/rune/vendor/wgpu-hal/src/dx12/descriptor.rs @@ -0,0 +1,344 @@ +use alloc::vec::Vec; +use core::fmt; + +use bit_set::BitSet; +use parking_lot::Mutex; +use range_alloc::RangeAllocator; +use windows::Win32::Graphics::Direct3D12; + +use crate::auxil::dxgi::result::HResult as _; + +const HEAP_SIZE_FIXED: usize = 64; + +#[derive(Copy, Clone)] +pub(super) struct DualHandle { + cpu: Direct3D12::D3D12_CPU_DESCRIPTOR_HANDLE, + pub gpu: Direct3D12::D3D12_GPU_DESCRIPTOR_HANDLE, + /// How large the block allocated to this handle is. + count: u64, +} + +impl fmt::Debug for DualHandle { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("DualHandle") + .field("cpu", &self.cpu.ptr) + .field("gpu", &self.gpu.ptr) + .field("count", &self.count) + .finish() + } +} + +type DescriptorIndex = u64; + +pub(super) struct GeneralHeap { + pub raw: Direct3D12::ID3D12DescriptorHeap, + ty: Direct3D12::D3D12_DESCRIPTOR_HEAP_TYPE, + handle_size: u64, + total_handles: u64, + start: DualHandle, + ranges: Mutex<RangeAllocator<DescriptorIndex>>, + // Zero-sized without wgpu's counters. Updated under the range lock, so a free racing + // an allocation cannot inflate the high-water mark. + live: wgt::InternalCounter, + peak: wgt::InternalCounter, +} + +impl GeneralHeap { + pub(super) fn new( + device: &Direct3D12::ID3D12Device, + ty: Direct3D12::D3D12_DESCRIPTOR_HEAP_TYPE, + total_handles: u64, + ) -> Result<Self, crate::DeviceError> { + let raw = { + profiling::scope!("ID3D12Device::CreateDescriptorHeap"); + let desc = Direct3D12::D3D12_DESCRIPTOR_HEAP_DESC { + Type: ty, + NumDescriptors: total_handles as u32, + Flags: Direct3D12::D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, + NodeMask: 0, + }; + unsafe { device.CreateDescriptorHeap::<Direct3D12::ID3D12DescriptorHeap>(&desc) } + .into_device_result("Descriptor heap creation")? + }; + + let start = DualHandle { + cpu: unsafe { raw.GetCPUDescriptorHandleForHeapStart() }, + gpu: unsafe { raw.GetGPUDescriptorHandleForHeapStart() }, + count: 0, + }; + + Ok(Self { + raw, + ty, + handle_size: unsafe { device.GetDescriptorHandleIncrementSize(ty) } as u64, + total_handles, + start, + ranges: Mutex::new(RangeAllocator::new(0..total_handles)), + live: Default::default(), + peak: Default::default(), + }) + } + + pub(super) fn at(&self, index: DescriptorIndex, count: u64) -> DualHandle { + assert!(index < self.total_handles); + DualHandle { + cpu: self.cpu_descriptor_at(index), + gpu: self.gpu_descriptor_at(index), + count, + } + } + + fn cpu_descriptor_at(&self, index: u64) -> Direct3D12::D3D12_CPU_DESCRIPTOR_HANDLE { + Direct3D12::D3D12_CPU_DESCRIPTOR_HANDLE { + ptr: self.start.cpu.ptr + (self.handle_size * index) as usize, + } + } + + fn gpu_descriptor_at(&self, index: u64) -> Direct3D12::D3D12_GPU_DESCRIPTOR_HANDLE { + Direct3D12::D3D12_GPU_DESCRIPTOR_HANDLE { + ptr: self.start.gpu.ptr + self.handle_size * index, + } + } + + pub(super) fn allocate_slice(&self, count: u64) -> Result<DescriptorIndex, crate::DeviceError> { + let mut ranges = self.ranges.lock(); + let range = ranges.allocate_range(count).map_err(|err| { + log::error!("Unable to allocate descriptors: {err:?}"); + crate::DeviceError::OutOfMemory + })?; + self.live.add(count as isize); + let live = self.live.read(); + if live > self.peak.read() { + self.peak.set(live); + std::eprintln!("dx12: peak live view descriptors {live}/{} ({} B each)", self.total_handles, self.handle_size); + } + Ok(range.start) + } + + /// Free handles previously given out by this `DescriptorHeapSlice`. + /// Do not use this with handles not given out by this `DescriptorHeapSlice`. + pub(crate) fn free_slice(&self, handle: DualHandle) { + let start = (handle.gpu.ptr - self.start.gpu.ptr) / self.handle_size; + let mut ranges = self.ranges.lock(); + ranges.free_range(start..start + handle.count); + self.live.sub(handle.count as isize); + } +} + +/// Fixed-size free-list allocator for CPU descriptors. +struct FixedSizeHeap { + _raw: Direct3D12::ID3D12DescriptorHeap, + /// Bit flag representation of available handles in the heap. + /// + /// 0 - Occupied + /// 1 - free + availability: u64, + handle_size: usize, + start: Direct3D12::D3D12_CPU_DESCRIPTOR_HANDLE, +} + +impl FixedSizeHeap { + fn new( + device: &Direct3D12::ID3D12Device, + ty: Direct3D12::D3D12_DESCRIPTOR_HEAP_TYPE, + ) -> Result<Self, crate::DeviceError> { + let desc = Direct3D12::D3D12_DESCRIPTOR_HEAP_DESC { + Type: ty, + NumDescriptors: HEAP_SIZE_FIXED as u32, + Flags: Direct3D12::D3D12_DESCRIPTOR_HEAP_FLAG_NONE, + NodeMask: 0, + }; + let heap = + unsafe { device.CreateDescriptorHeap::<Direct3D12::ID3D12DescriptorHeap>(&desc) } + .into_device_result("Descriptor heap creation")?; + + Ok(Self { + handle_size: unsafe { device.GetDescriptorHandleIncrementSize(ty) } as usize, + availability: !0, // all free! + start: unsafe { heap.GetCPUDescriptorHandleForHeapStart() }, + _raw: heap, + }) + } + + fn alloc_handle( + &mut self, + ) -> Result<Direct3D12::D3D12_CPU_DESCRIPTOR_HANDLE, crate::DeviceError> { + // Find first free slot. + let slot = self.availability.trailing_zeros() as usize; + if slot >= HEAP_SIZE_FIXED { + log::error!("Failed to allocate a handle form a fixed size heap"); + return Err(crate::DeviceError::OutOfMemory); + } + // Set the slot as occupied. + self.availability ^= 1 << slot; + + Ok(Direct3D12::D3D12_CPU_DESCRIPTOR_HANDLE { + ptr: self.start.ptr + self.handle_size * slot, + }) + } + + fn free_handle(&mut self, handle: Direct3D12::D3D12_CPU_DESCRIPTOR_HANDLE) { + let slot = (handle.ptr - self.start.ptr) / self.handle_size; + assert!(slot < HEAP_SIZE_FIXED); + assert_eq!(self.availability & (1 << slot), 0); + self.availability ^= 1 << slot; + } + + fn is_full(&self) -> bool { + self.availability == 0 + } +} + +#[derive(Clone, Copy)] +pub(super) struct Handle { + pub raw: Direct3D12::D3D12_CPU_DESCRIPTOR_HANDLE, + heap_index: usize, +} + +impl fmt::Debug for Handle { + fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + fmt.debug_struct("Handle") + .field("ptr", &self.raw.ptr) + .field("heap_index", &self.heap_index) + .finish() + } +} + +pub(super) struct CpuPool { + device: Direct3D12::ID3D12Device, + ty: Direct3D12::D3D12_DESCRIPTOR_HEAP_TYPE, + heaps: Vec<FixedSizeHeap>, + available_heap_indices: BitSet, +} + +impl CpuPool { + pub(super) fn new( + device: Direct3D12::ID3D12Device, + ty: Direct3D12::D3D12_DESCRIPTOR_HEAP_TYPE, + ) -> Self { + Self { + device, + ty, + heaps: Vec::new(), + available_heap_indices: BitSet::new(), + } + } + + pub(super) fn alloc_handle(&mut self) -> Result<Handle, crate::DeviceError> { + let heap_index = self + .available_heap_indices + .iter() + .next() + .unwrap_or(self.heaps.len()); + + // Allocate a new heap + if heap_index == self.heaps.len() { + self.heaps.push(FixedSizeHeap::new(&self.device, self.ty)?); + self.available_heap_indices.insert(heap_index); + } + + let heap = &mut self.heaps[heap_index]; + let handle = Handle { + raw: heap.alloc_handle()?, + heap_index, + }; + if heap.is_full() { + self.available_heap_indices.remove(heap_index); + } + + Ok(handle) + } + + pub(super) fn free_handle(&mut self, handle: Handle) { + self.heaps[handle.heap_index].free_handle(handle.raw); + self.available_heap_indices.insert(handle.heap_index); + } +} + +pub(super) struct CpuHeapInner { + pub _raw: Direct3D12::ID3D12DescriptorHeap, + pub stage: Vec<Direct3D12::D3D12_CPU_DESCRIPTOR_HANDLE>, +} + +pub(super) struct CpuHeap { + pub inner: Mutex<CpuHeapInner>, + start: Direct3D12::D3D12_CPU_DESCRIPTOR_HANDLE, + handle_size: u32, + total: u32, +} + +unsafe impl Send for CpuHeap {} +unsafe impl Sync for CpuHeap {} + +impl CpuHeap { + pub(super) fn new( + device: &Direct3D12::ID3D12Device, + ty: Direct3D12::D3D12_DESCRIPTOR_HEAP_TYPE, + total: u32, + ) -> Result<Self, crate::DeviceError> { + let handle_size = unsafe { device.GetDescriptorHandleIncrementSize(ty) }; + let desc = Direct3D12::D3D12_DESCRIPTOR_HEAP_DESC { + Type: ty, + NumDescriptors: total, + Flags: Direct3D12::D3D12_DESCRIPTOR_HEAP_FLAG_NONE, + NodeMask: 0, + }; + let raw = unsafe { device.CreateDescriptorHeap::<Direct3D12::ID3D12DescriptorHeap>(&desc) } + .into_device_result("CPU descriptor heap creation")?; + + let start = unsafe { raw.GetCPUDescriptorHandleForHeapStart() }; + + Ok(Self { + inner: Mutex::new(CpuHeapInner { + _raw: raw, + stage: Vec::new(), + }), + start, + handle_size, + total, + }) + } + + pub(super) fn at(&self, index: u32) -> Direct3D12::D3D12_CPU_DESCRIPTOR_HANDLE { + debug_assert!( + index < self.total, + "Index ({index}) out of bounds {total}", + total = self.total + ); + Direct3D12::D3D12_CPU_DESCRIPTOR_HANDLE { + ptr: self.start.ptr + (self.handle_size * index) as usize, + } + } +} + +impl fmt::Debug for CpuHeap { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("CpuHeap") + .field("start", &self.start.ptr) + .field("handle_size", &self.handle_size) + .field("total", &self.total) + .finish() + } +} + +pub(super) unsafe fn upload( + device: &Direct3D12::ID3D12Device, + src: &CpuHeapInner, + dst: &GeneralHeap, + dummy_copy_counts: &[u32], +) -> Result<DualHandle, crate::DeviceError> { + let count = src.stage.len() as u32; + let index = dst.allocate_slice(count as u64)?; + unsafe { + device.CopyDescriptors( + 1, + &dst.cpu_descriptor_at(index), + Some(&count), + count, + src.stage.as_ptr(), + Some(dummy_copy_counts.as_ptr()), + dst.ty, + ) + }; + Ok(dst.at(index, count as u64)) +} diff --git a/app/vendor/rune/vendor/wgpu-hal/src/dx12/device.rs b/app/vendor/rune/vendor/wgpu-hal/src/dx12/device.rs new file mode 100644 index 0000000..aa74ea5 --- /dev/null +++ b/app/vendor/rune/vendor/wgpu-hal/src/dx12/device.rs @@ -0,0 +1,2752 @@ +use alloc::borrow::ToOwned; +use alloc::{ + borrow::Cow, + string::{String, ToString as _}, + sync::Arc, + vec::Vec, +}; +use arrayvec::ArrayVec; +use core::{ffi, num::NonZeroU32, ptr, time::Duration}; +use std::time::Instant; + +use bytemuck::TransparentWrapper; +use parking_lot::Mutex; +use windows::{ + core::Interface as _, + Win32::{ + Foundation, + Graphics::{Direct3D12, Dxgi}, + System::Threading, + }, +}; + +use super::{conv, descriptor, D3D12Lib}; +use crate::{ + auxil::{ + self, + dxgi::{name::ObjectExt as _, result::HResult as _}, + }, + dx12::{ + borrow_optional_interface_temporarily, pipeline_desc::RenderPipelineStateStreamDesc, + shader_compilation, suballocation, DCompLib, DynamicStorageBufferOffsets, Event, + ShaderCacheKey, ShaderCacheValue, + }, + AccelerationStructureEntries, TlasInstance, +}; + +// this has to match Naga's HLSL backend, and also needs to be null-terminated +const NAGA_LOCATION_SEMANTIC: &[u8] = c"LOC".to_bytes(); + +impl super::Device { + #[allow(clippy::too_many_arguments)] + pub(super) fn new( + adapter: auxil::dxgi::factory::DxgiAdapter, + raw: Direct3D12::ID3D12Device, + present_queue: Direct3D12::ID3D12CommandQueue, + features: wgt::Features, + limits: &wgt::Limits, + memory_hints: &wgt::MemoryHints, + private_caps: super::PrivateCapabilities, + library: &Arc<D3D12Lib>, + dcomp_lib: &Arc<DCompLib>, + memory_budget_thresholds: wgt::MemoryBudgetThresholds, + compiler_container: Arc<shader_compilation::CompilerContainer>, + backend_options: wgt::Dx12BackendOptions, + ) -> Result<Self, crate::DeviceError> { + if private_caps + .instance_flags + .contains(wgt::InstanceFlags::VALIDATION) + { + auxil::dxgi::exception::register_exception_handler(); + } + + let mem_allocator = + suballocation::Allocator::new(&raw, memory_hints, memory_budget_thresholds)?; + + let idle_fence: Direct3D12::ID3D12Fence = unsafe { + profiling::scope!("ID3D12Device::CreateFence"); + raw.CreateFence(0, Direct3D12::D3D12_FENCE_FLAG_NONE) + } + .into_device_result("Idle fence creation")?; + + let raw_desc = Direct3D12::D3D12_RESOURCE_DESC { + Dimension: Direct3D12::D3D12_RESOURCE_DIMENSION_BUFFER, + Alignment: 0, + Width: super::ZERO_BUFFER_SIZE, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + Format: Dxgi::Common::DXGI_FORMAT_UNKNOWN, + SampleDesc: Dxgi::Common::DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, + Layout: Direct3D12::D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + Flags: Direct3D12::D3D12_RESOURCE_FLAG_NONE, + }; + + let heap_properties = Direct3D12::D3D12_HEAP_PROPERTIES { + Type: Direct3D12::D3D12_HEAP_TYPE_CUSTOM, + CPUPageProperty: Direct3D12::D3D12_CPU_PAGE_PROPERTY_NOT_AVAILABLE, + MemoryPoolPreference: match private_caps.memory_architecture { + super::MemoryArchitecture::Unified { .. } => Direct3D12::D3D12_MEMORY_POOL_L0, + super::MemoryArchitecture::NonUnified => Direct3D12::D3D12_MEMORY_POOL_L1, + }, + CreationNodeMask: 0, + VisibleNodeMask: 0, + }; + + profiling::scope!("Zero Buffer Allocation"); + let mut zero_buffer = None::<Direct3D12::ID3D12Resource>; + unsafe { + raw.CreateCommittedResource( + &heap_properties, + Direct3D12::D3D12_HEAP_FLAG_NONE, + &raw_desc, + Direct3D12::D3D12_RESOURCE_STATE_COMMON, + None, + &mut zero_buffer, + ) + } + .into_device_result("Zero buffer creation")?; + + let zero_buffer = zero_buffer.ok_or(crate::DeviceError::Unexpected)?; + + // Note: without `D3D12_HEAP_FLAG_CREATE_NOT_ZEROED` + // this resource is zeroed by default. + + // maximum number of CBV/SRV/UAV descriptors in heap for Tier 1 + let capacity_views = limits.max_non_sampler_bindings as u64; + + let draw_mesh = if features + .features_wgpu + .contains(wgt::FeaturesWGPU::EXPERIMENTAL_MESH_SHADER) + { + Some(Self::create_command_signature( + &raw, + None, + size_of::<wgt::DispatchIndirectArgs>(), + &[Direct3D12::D3D12_INDIRECT_ARGUMENT_DESC { + Type: Direct3D12::D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH_MESH, + ..Default::default() + }], + 0, + )?) + } else { + None + }; + + let drain = Arc::new(super::DrainTracker::new(&adapter, &raw)); + let shared = super::DeviceShared { + adapter, + zero_buffer, + cmd_signatures: super::CommandSignatures { + draw: Self::create_command_signature( + &raw, + None, + size_of::<wgt::DrawIndirectArgs>(), + &[Direct3D12::D3D12_INDIRECT_ARGUMENT_DESC { + Type: Direct3D12::D3D12_INDIRECT_ARGUMENT_TYPE_DRAW, + ..Default::default() + }], + 0, + )?, + draw_indexed: Self::create_command_signature( + &raw, + None, + size_of::<wgt::DrawIndexedIndirectArgs>(), + &[Direct3D12::D3D12_INDIRECT_ARGUMENT_DESC { + Type: Direct3D12::D3D12_INDIRECT_ARGUMENT_TYPE_DRAW_INDEXED, + ..Default::default() + }], + 0, + )?, + draw_mesh, + dispatch: Self::create_command_signature( + &raw, + None, + size_of::<wgt::DispatchIndirectArgs>(), + &[Direct3D12::D3D12_INDIRECT_ARGUMENT_DESC { + Type: Direct3D12::D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH, + ..Default::default() + }], + 0, + )?, + }, + heap_views: descriptor::GeneralHeap::new( + &raw, + Direct3D12::D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, + capacity_views, + )?, + sampler_heap: super::sampler::SamplerHeap::new(&raw, &private_caps)?, + private_caps, + drain, + }; + + let mut rtv_pool = + descriptor::CpuPool::new(raw.clone(), Direct3D12::D3D12_DESCRIPTOR_HEAP_TYPE_RTV); + let null_rtv_handle = rtv_pool.alloc_handle()?; + // A null pResource is used to initialize a null descriptor, + // which guarantees D3D11-like null binding behavior (reading 0s, writes are discarded) + unsafe { + raw.CreateRenderTargetView( + None, + Some(&Direct3D12::D3D12_RENDER_TARGET_VIEW_DESC { + Format: Dxgi::Common::DXGI_FORMAT_R8G8B8A8_UNORM, + ViewDimension: Direct3D12::D3D12_RTV_DIMENSION_TEXTURE2D, + Anonymous: Direct3D12::D3D12_RENDER_TARGET_VIEW_DESC_0 { + Texture2D: Direct3D12::D3D12_TEX2D_RTV { + MipSlice: 0, + PlaneSlice: 0, + }, + }, + }), + null_rtv_handle.raw, + ) + }; + + Ok(super::Device { + raw: raw.clone(), + present_queue, + idler: super::Idler { fence: idle_fence }, + features, + shared: Arc::new(shared), + rtv_pool: Arc::new(Mutex::new(rtv_pool)), + dsv_pool: Mutex::new(descriptor::CpuPool::new( + raw.clone(), + Direct3D12::D3D12_DESCRIPTOR_HEAP_TYPE_DSV, + )), + srv_uav_pool: Mutex::new(descriptor::CpuPool::new( + raw.clone(), + Direct3D12::D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, + )), + options: backend_options, + library: Arc::clone(library), + dcomp_lib: Arc::clone(dcomp_lib), + #[cfg(feature = "renderdoc")] + render_doc: Default::default(), + null_rtv_handle, + mem_allocator, + compiler_container, + shader_cache: Default::default(), + counters: Default::default(), + limits: limits.clone(), + }) + } + + fn create_command_signature( + raw: &Direct3D12::ID3D12Device, + root_signature: Option<&Direct3D12::ID3D12RootSignature>, + byte_stride: usize, + arguments: &[Direct3D12::D3D12_INDIRECT_ARGUMENT_DESC], + node_mask: u32, + ) -> Result<Direct3D12::ID3D12CommandSignature, crate::DeviceError> { + let mut signature = None; + unsafe { + raw.CreateCommandSignature( + &Direct3D12::D3D12_COMMAND_SIGNATURE_DESC { + ByteStride: byte_stride as u32, + NumArgumentDescs: arguments.len() as u32, + pArgumentDescs: arguments.as_ptr(), + NodeMask: node_mask, + }, + root_signature, + &mut signature, + ) + } + .into_device_result("Command signature creation")?; + signature.ok_or(crate::DeviceError::Unexpected) + } + + /// Rune: the highest value `fence` has reached, or None once the device is removed. A + /// removed device's fence reads `u64::MAX` (a GPU reset after a timeout, a driver update, a + /// GPU unplugged), which wgpu-core would take as every submission finished: each pending + /// work-done callback and buffer map would complete as if its work had run. Reporting the + /// value the fence last really reached leaves them pending, which they are: they will never + /// finish. An error here instead would make wgpu's `Device::poll` panic ("Parent device is + /// lost"). The removal itself is seen by the caller (Rune's `rune_gpu::health::removed`) and + /// by wgpu at the device's next submission, whose signal fails. + fn reached(&self, fence: &super::Fence) -> Option<crate::FenceValue> { + let value = unsafe { fence.raw.GetCompletedValue() }; + if value == u64::MAX { + // Never stored: read a moment before D3D12 reports the removal, it would stay + // "everything finished" for good. + if unsafe { self.raw.GetDeviceRemovedReason() }.is_err() { + self.shared.drain.mark_removed(); + return None; + } + return Some(fence.reached.load(core::sync::atomic::Ordering::Relaxed)); + } + Some(fence.reached.fetch_max(value, core::sync::atomic::Ordering::Relaxed).max(value)) + } + + // Blocks until the dedicated present queue is finished with all of its work. + // + // Once this method completes, the surface is able to be resized or deleted. + pub(super) unsafe fn wait_for_present_queue_idle(&self) -> Result<(), crate::DeviceError> { + let on_removed = || { + self.shared.drain.mark_removed(); + self.shared.drain.wait_after_removal(); + Err(crate::DeviceError::Lost) + }; + let cur_value = unsafe { self.idler.fence.GetCompletedValue() }; + if cur_value == !0 { + return on_removed(); + } + + let event = Event::create(false, false)?; + + let value = cur_value + 1; + if let Err(err) = unsafe { self.present_queue.Signal(&self.idler.fence, value) } + .into_device_result("Signal") + { + if matches!(err, crate::DeviceError::Lost) { + return on_removed(); + } + return Err(err); + } + if let Err(err) = unsafe { self.idler.fence.SetEventOnCompletion(value, event.0) } + .into_device_result("Set event") + { + if matches!(err, crate::DeviceError::Lost) { + return on_removed(); + } + return Err(err); + } + while unsafe { Threading::WaitForSingleObject(event.0, 100) } == Foundation::WAIT_TIMEOUT { + if unsafe { self.raw.GetDeviceRemovedReason() }.is_err() { + return on_removed(); + } + } + if unsafe { self.idler.fence.GetCompletedValue() } == !0 + && unsafe { self.raw.GetDeviceRemovedReason() }.is_err() + { + return on_removed(); + } + Ok(()) + } + + /// When generating the vertex shader, the fragment stage must be passed if it exists! + /// Otherwise, the generated HLSL may be incorrect since the fragment shader inputs are + /// allowed to be a subset of the vertex outputs. + fn load_shader( + &self, + stage: &crate::ProgrammableStage<super::ShaderModule>, + layout: &super::PipelineLayout, + naga_stage: naga::ShaderStage, + fragment_stage: Option<&crate::ProgrammableStage<super::ShaderModule>>, + ) -> Result<super::CompiledShader, crate::PipelineError> { + let stage_bit = auxil::map_naga_stage(naga_stage); + + let needs_temp_options = stage.zero_initialize_workgroup_memory + != layout.naga_options.zero_initialize_workgroup_memory + || stage.module.runtime_checks.bounds_checks != layout.naga_options.restrict_indexing + || !stage.module.runtime_checks.task_shader_dispatch_tracking + || !stage + .module + .runtime_checks + .mesh_shader_primitive_indices_clamp + || stage.module.runtime_checks.force_loop_bounding + != layout.naga_options.force_loop_bounding + || stage + .module + .runtime_checks + .ray_query_initialization_tracking + != layout.naga_options.ray_query_initialization_tracking; + let mut temp_options; + let naga_options = if needs_temp_options { + temp_options = layout.naga_options.clone(); + temp_options.zero_initialize_workgroup_memory = stage.zero_initialize_workgroup_memory; + temp_options.restrict_indexing = stage.module.runtime_checks.bounds_checks; + temp_options.force_loop_bounding = stage.module.runtime_checks.force_loop_bounding; + if !stage.module.runtime_checks.task_shader_dispatch_tracking { + temp_options.task_dispatch_limits = None; + } + temp_options.mesh_shader_primitive_indices_clamp = stage + .module + .runtime_checks + .mesh_shader_primitive_indices_clamp; + temp_options.ray_query_initialization_tracking = stage + .module + .runtime_checks + .ray_query_initialization_tracking; + &temp_options + } else { + &layout.naga_options + }; + + let key = match &stage.module.source { + super::ShaderModuleSource::Naga(naga_shader) => { + use naga::back::hlsl; + + let frag_ep = match fragment_stage { + Some(crate::ProgrammableStage { + module: + super::ShaderModule { + source: super::ShaderModuleSource::Naga(naga_shader), + .. + }, + entry_point, + .. + }) => Some( + hlsl::FragmentEntryPoint::new(&naga_shader.module, entry_point).ok_or( + crate::PipelineError::EntryPoint(naga::ShaderStage::Fragment), + ), + ), + _ => None, + } + .transpose()?; + let (module, info) = naga::back::pipeline_constants::process_overrides( + &naga_shader.module, + &naga_shader.info, + Some((naga_stage, stage.entry_point)), + stage.constants, + ) + .map_err(|e| { + crate::PipelineError::PipelineConstants(stage_bit, format!("HLSL: {e:?}")) + })?; + + let pipeline_options = hlsl::PipelineOptions { + entry_point: Some((naga_stage, stage.entry_point.to_string())), + }; + + //TODO: reuse the writer + let (source, entry_point) = { + let mut source = String::new(); + let mut writer = + hlsl::Writer::new(&mut source, naga_options, &pipeline_options); + + profiling::scope!("naga::back::hlsl::write"); + let mut reflection_info = writer + .write(&module, &info, frag_ep.as_ref()) + .map_err(|e| { + crate::PipelineError::Linkage(stage_bit, format!("HLSL: {e:?}")) + })?; + + assert_eq!(reflection_info.entry_point_names.len(), 1); + + let entry_point = reflection_info + .entry_point_names + .pop() + .unwrap() + .map_err(|e| crate::PipelineError::Linkage(stage_bit, format!("{e}")))?; + + (source, entry_point) + }; + log::debug!( + "Naga generated shader for {entry_point:?} at {naga_stage:?}:\n{source}" + ); + + ShaderCacheKey { + source, + entry_point, + stage: naga_stage, + shader_model: naga_options.shader_model, + } + } + super::ShaderModuleSource::HlslPassthrough(passthrough) => ShaderCacheKey { + source: passthrough.shader.clone(), + entry_point: stage.entry_point.to_string(), + stage: naga_stage, + shader_model: naga_options.shader_model, + }, + super::ShaderModuleSource::DxilPassthrough(passthrough) => { + return Ok(super::CompiledShader::Precompiled( + passthrough.shader.clone(), + )) + } + }; + + { + let mut shader_cache = self.shader_cache.lock(); + let nr_of_shaders_compiled = shader_cache.nr_of_shaders_compiled; + if let Some(value) = shader_cache.entries.get_mut(&key) { + value.last_used = nr_of_shaders_compiled; + return Ok(value.shader.clone()); + } + } + + let source_name = stage.module.raw_name.as_deref(); + + let full_stage = format!( + "{}_{}", + naga::back::hlsl::shader_stage_to_hlsl_str(naga_stage), + key.shader_model.to_str() + ); + + let compiled_shader = self.compiler_container.compile( + self, + &key.source, + source_name, + &key.entry_point, + stage_bit, + &full_stage, + )?; + + { + let mut shader_cache = self.shader_cache.lock(); + shader_cache.nr_of_shaders_compiled += 1; + let nr_of_shaders_compiled = shader_cache.nr_of_shaders_compiled; + let value = ShaderCacheValue { + last_used: nr_of_shaders_compiled, + shader: compiled_shader.clone(), + }; + shader_cache.entries.insert(key, value); + + // Retain all entries that have been used since we compiled the last 100 shaders. + if shader_cache.entries.len() > 200 { + shader_cache + .entries + .retain(|_, v| v.last_used >= nr_of_shaders_compiled - 100); + } + } + + Ok(compiled_shader) + } + + pub fn raw_device(&self) -> &Direct3D12::ID3D12Device { + &self.raw + } + + pub fn raw_queue(&self) -> &Direct3D12::ID3D12CommandQueue { + &self.present_queue + } + + pub unsafe fn texture_from_raw( + resource: Direct3D12::ID3D12Resource, + format: wgt::TextureFormat, + dimension: wgt::TextureDimension, + size: wgt::Extent3d, + mip_level_count: u32, + sample_count: u32, + ) -> super::Texture { + super::Texture { + resource, + format, + dimension, + size, + mip_level_count, + sample_count, + allocation: suballocation::Allocation::none( + suballocation::AllocationType::Texture, + format.theoretical_memory_footprint(size), + ), + plane_slice_override: None, + } + } + + pub unsafe fn buffer_from_raw( + resource: Direct3D12::ID3D12Resource, + size: wgt::BufferAddress, + ) -> super::Buffer { + super::Buffer { + resource, + size, + allocation: suballocation::Allocation::none( + suballocation::AllocationType::Buffer, + size, + ), + } + } +} + +impl crate::Device for super::Device { + type A = super::Api; + + unsafe fn create_buffer( + &self, + desc: &crate::BufferDescriptor, + ) -> Result<super::Buffer, crate::DeviceError> { + let mut desc = desc.clone(); + + if desc.usage.contains(wgt::BufferUses::UNIFORM) { + desc.size = desc + .size + .next_multiple_of(Direct3D12::D3D12_CONSTANT_BUFFER_DATA_PLACEMENT_ALIGNMENT.into()) + } + + let (resource, allocation) = + suballocation::DeviceAllocationContext::from(self).create_buffer(&desc)?; + + self.counters.buffers.add(1); + + Ok(super::Buffer { + resource, + size: desc.size, + allocation, + }) + } + + unsafe fn destroy_buffer(&self, buffer: super::Buffer) { + suballocation::DeviceAllocationContext::from(self) + .free_resource(buffer.resource, buffer.allocation); + + self.counters.buffers.sub(1); + } + + unsafe fn add_raw_buffer(&self, _buffer: &super::Buffer) { + self.counters.buffers.add(1); + } + + unsafe fn map_buffer( + &self, + buffer: &super::Buffer, + range: crate::MemoryRange, + ) -> Result<crate::BufferMapping, crate::DeviceError> { + let mut ptr = ptr::null_mut(); + // TODO: 0 for subresource should be fine here until map and unmap buffer is subresource aware? + unsafe { buffer.resource.Map(0, None, Some(&mut ptr)) }.into_device_result("Map buffer")?; + + Ok(crate::BufferMapping { + ptr: ptr::NonNull::new(unsafe { ptr.offset(range.start as isize).cast::<u8>() }) + .unwrap(), + //TODO: double-check this. Documentation is a bit misleading - + // it implies that Map/Unmap is needed to invalidate/flush memory. + is_coherent: true, + }) + } + + unsafe fn unmap_buffer(&self, buffer: &super::Buffer) { + unsafe { buffer.resource.Unmap(0, None) }; + } + + unsafe fn flush_mapped_ranges<I>(&self, _buffer: &super::Buffer, _ranges: I) {} + unsafe fn invalidate_mapped_ranges<I>(&self, _buffer: &super::Buffer, _ranges: I) {} + + unsafe fn create_texture( + &self, + desc: &crate::TextureDescriptor, + ) -> Result<super::Texture, crate::DeviceError> { + let raw_desc = Direct3D12::D3D12_RESOURCE_DESC { + Dimension: conv::map_texture_dimension(desc.dimension), + Alignment: 0, + Width: desc.size.width as u64, + Height: desc.size.height, + DepthOrArraySize: desc.size.depth_or_array_layers as u16, + MipLevels: desc.mip_level_count as u16, + Format: auxil::dxgi::conv::map_texture_format_for_resource( + desc.format, + desc.usage, + !desc.view_formats.is_empty(), + self.shared + .private_caps + .casting_fully_typed_format_supported, + ), + SampleDesc: Dxgi::Common::DXGI_SAMPLE_DESC { + Count: desc.sample_count, + Quality: 0, + }, + Layout: Direct3D12::D3D12_TEXTURE_LAYOUT_UNKNOWN, + Flags: conv::map_texture_usage_to_resource_flags(desc.usage), + }; + + let (resource, allocation) = + suballocation::DeviceAllocationContext::from(self).create_texture(desc, raw_desc)?; + + self.counters.textures.add(1); + + Ok(super::Texture { + resource, + format: desc.format, + dimension: desc.dimension, + size: desc.size, + mip_level_count: desc.mip_level_count, + sample_count: desc.sample_count, + allocation, + plane_slice_override: None, + }) + } + + unsafe fn destroy_texture(&self, texture: super::Texture) { + suballocation::DeviceAllocationContext::from(self) + .free_resource(texture.resource, texture.allocation); + + self.counters.textures.sub(1); + } + + unsafe fn add_raw_texture(&self, _texture: &super::Texture) { + self.counters.textures.add(1); + } + + unsafe fn create_texture_view( + &self, + texture: &super::Texture, + desc: &crate::TextureViewDescriptor, + ) -> Result<super::TextureView, crate::DeviceError> { + let view_desc = desc.to_internal(texture); + + self.counters.texture_views.add(1); + + Ok(super::TextureView { + raw_format: view_desc.rtv_dsv_format, + aspects: view_desc.aspects, + dimension: desc.dimension, + texture: texture.resource.clone(), + subresource_index: texture.calc_subresource( + desc.range.base_mip_level, + desc.range.base_array_layer, + view_desc.plane_slice(), + ), + mip_slice: desc.range.base_mip_level, + handle_srv: if desc.usage.intersects(wgt::TextureUses::RESOURCE) { + match unsafe { view_desc.to_srv() } { + Some(raw_desc) => { + let handle = self.srv_uav_pool.lock().alloc_handle()?; + unsafe { + self.raw.CreateShaderResourceView( + &texture.resource, + Some(&raw_desc), + handle.raw, + ) + }; + Some(handle) + } + None => None, + } + } else { + None + }, + handle_uav: if desc.usage.intersects( + wgt::TextureUses::STORAGE_READ_ONLY + | wgt::TextureUses::STORAGE_WRITE_ONLY + | wgt::TextureUses::STORAGE_READ_WRITE, + ) { + match unsafe { view_desc.to_uav() } { + Some(raw_desc) => { + let handle = self.srv_uav_pool.lock().alloc_handle()?; + unsafe { + self.raw.CreateUnorderedAccessView( + &texture.resource, + None, + Some(&raw_desc), + handle.raw, + ); + } + Some(handle) + } + None => None, + } + } else { + None + }, + handle_rtv: if desc.usage.intersects(wgt::TextureUses::COLOR_TARGET) + && desc.dimension != wgt::TextureViewDimension::D3 + // 3D RTVs must be created in the render pass + { + let raw_desc = unsafe { view_desc.to_rtv() }; + let handle = self.rtv_pool.lock().alloc_handle()?; + unsafe { + self.raw + .CreateRenderTargetView(&texture.resource, Some(&raw_desc), handle.raw) + }; + Some(handle) + } else { + None + }, + handle_dsv_ro: if desc.usage.intersects(wgt::TextureUses::DEPTH_STENCIL_READ) { + let raw_desc = unsafe { view_desc.to_dsv(true) }; + let handle = self.dsv_pool.lock().alloc_handle()?; + unsafe { + self.raw + .CreateDepthStencilView(&texture.resource, Some(&raw_desc), handle.raw) + }; + Some(handle) + } else { + None + }, + handle_dsv_rw: if desc.usage.intersects(wgt::TextureUses::DEPTH_STENCIL_WRITE) { + let raw_desc = unsafe { view_desc.to_dsv(false) }; + let handle = self.dsv_pool.lock().alloc_handle()?; + unsafe { + self.raw + .CreateDepthStencilView(&texture.resource, Some(&raw_desc), handle.raw) + }; + Some(handle) + } else { + None + }, + }) + } + + unsafe fn destroy_texture_view(&self, view: super::TextureView) { + if view.handle_srv.is_some() || view.handle_uav.is_some() { + let mut pool = self.srv_uav_pool.lock(); + if let Some(handle) = view.handle_srv { + pool.free_handle(handle); + } + if let Some(handle) = view.handle_uav { + pool.free_handle(handle); + } + } + if let Some(handle) = view.handle_rtv { + self.rtv_pool.lock().free_handle(handle); + } + if view.handle_dsv_ro.is_some() || view.handle_dsv_rw.is_some() { + let mut pool = self.dsv_pool.lock(); + if let Some(handle) = view.handle_dsv_ro { + pool.free_handle(handle); + } + if let Some(handle) = view.handle_dsv_rw { + pool.free_handle(handle); + } + } + + self.counters.texture_views.sub(1); + } + + unsafe fn create_sampler( + &self, + desc: &crate::SamplerDescriptor, + ) -> Result<super::Sampler, crate::DeviceError> { + let reduction = match desc.compare { + Some(_) => Direct3D12::D3D12_FILTER_REDUCTION_TYPE_COMPARISON, + None => Direct3D12::D3D12_FILTER_REDUCTION_TYPE_STANDARD, + }; + let mut filter = Direct3D12::D3D12_FILTER( + (conv::map_filter_mode(desc.min_filter).0 << Direct3D12::D3D12_MIN_FILTER_SHIFT) + | (conv::map_filter_mode(desc.mag_filter).0 << Direct3D12::D3D12_MAG_FILTER_SHIFT) + | (conv::map_mipmap_filter_mode(desc.mipmap_filter).0 + << Direct3D12::D3D12_MIP_FILTER_SHIFT) + | (reduction.0 << Direct3D12::D3D12_FILTER_REDUCTION_TYPE_SHIFT), + ); + + if desc.anisotropy_clamp != 1 { + filter.0 |= Direct3D12::D3D12_FILTER_ANISOTROPIC.0; + }; + + let border_color = conv::map_border_color(desc.border_color); + + let raw_desc = Direct3D12::D3D12_SAMPLER_DESC { + Filter: filter, + AddressU: conv::map_address_mode(desc.address_modes[0]), + AddressV: conv::map_address_mode(desc.address_modes[1]), + AddressW: conv::map_address_mode(desc.address_modes[2]), + MipLODBias: 0f32, + MaxAnisotropy: desc.anisotropy_clamp as u32, + + ComparisonFunc: conv::map_comparison(desc.compare.unwrap_or_default()), + BorderColor: border_color, + MinLOD: desc.lod_clamp.start, + MaxLOD: desc.lod_clamp.end, + }; + + let index = self + .shared + .sampler_heap + .create_sampler(&self.raw, raw_desc)?; + + self.counters.samplers.add(1); + + Ok(super::Sampler { + index, + desc: raw_desc, + }) + } + + unsafe fn destroy_sampler(&self, sampler: super::Sampler) { + self.shared + .sampler_heap + .destroy_sampler(sampler.desc, sampler.index); + self.counters.samplers.sub(1); + } + + unsafe fn create_command_encoder( + &self, + desc: &crate::CommandEncoderDescriptor<super::Queue>, + ) -> Result<super::CommandEncoder, crate::DeviceError> { + let allocator: Direct3D12::ID3D12CommandAllocator = unsafe { + self.raw + .CreateCommandAllocator(Direct3D12::D3D12_COMMAND_LIST_TYPE_DIRECT) + } + .into_device_result("Command allocator creation")?; + + if let Some(label) = desc.label { + allocator.set_name(label)?; + } + + self.counters.command_encoders.add(1); + + Ok(super::CommandEncoder { + allocator, + device: self.raw.clone(), + shared: Arc::clone(&self.shared), + mem_allocator: self.mem_allocator.clone(), + rtv_pool: Arc::clone(&self.rtv_pool), + temp_rtv_handles: Vec::new(), + intermediate_copy_bufs: Vec::new(), + null_rtv_handle: self.null_rtv_handle, + list: None, + list2: None, + free_lists: Vec::new(), + pass: super::PassState::new(), + temp: super::Temp::default(), + end_of_pass_timer_query: None, + counters: Arc::clone(&self.counters), + }) + } + + unsafe fn create_bind_group_layout( + &self, + desc: &crate::BindGroupLayoutDescriptor, + ) -> Result<super::BindGroupLayout, crate::DeviceError> { + let mut num_views = 0; + let mut has_sampler_in_group = false; + for entry in desc.entries.iter() { + let count = entry.count.map_or(1, NonZeroU32::get); + match entry.ty { + wgt::BindingType::Buffer { + ty: wgt::BufferBindingType::Uniform, + has_dynamic_offset: true, + .. + } => {} + wgt::BindingType::Buffer { .. } + | wgt::BindingType::Texture { .. } + | wgt::BindingType::StorageTexture { .. } + | wgt::BindingType::AccelerationStructure { .. } => num_views += count, + wgt::BindingType::Sampler { .. } => has_sampler_in_group = true, + // Three texture planes and one params buffer + wgt::BindingType::ExternalTexture => num_views += 4 * count, + } + } + + if has_sampler_in_group { + num_views += 1; + } + + self.counters.bind_group_layouts.add(1); + + Ok(super::BindGroupLayout { + entries: desc.entries.to_vec(), + cpu_heap_views: if num_views != 0 { + let heap = descriptor::CpuHeap::new( + &self.raw, + Direct3D12::D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, + num_views, + )?; + Some(heap) + } else { + None + }, + copy_counts: vec![1; num_views as usize], + }) + } + + unsafe fn destroy_bind_group_layout(&self, _bg_layout: super::BindGroupLayout) { + self.counters.bind_group_layouts.sub(1); + } + + unsafe fn create_pipeline_layout( + &self, + desc: &crate::PipelineLayoutDescriptor<super::BindGroupLayout>, + ) -> Result<super::PipelineLayout, crate::DeviceError> { + use naga::back::hlsl; + // Pipeline layouts are implemented as RootSignature for D3D12. + // + // Immediates are implemented as root constants. + // + // Each bind group layout might use one SRV/CBV/UAV descriptor table. + // With resources in the bind group layout using: + // - 1 CBV per non-dynamic uniform buffer + // - 1 SRV per acceleration structure + // - 1 SRV for all samplers in a bind group + // - 1 SRV per texture + // - 1 SRV per read-only storage buffer + // - 1 UAV per storage texture + // - 1 UAV per read-write storage buffer + // - 3 SRVs & 1 CBV per external texture + // + // Each dynamic uniform buffer takes up a CBV root descriptor. + // This is easier than trying to patch up the offset on the shader side. + // + // Each dynamic storage buffer is an SRV or UAV in the descriptor table + // and its dynamic offsets are passed via root constants. + // + // All samplers go into a single sampler descriptor table. + // + // 3 additional root constants are used to populate built-in (shader) inputs. + // + // Root signature layout: + // Root Constants: Parameter=0, Space=0 + // ... + // (bind group [0]) - Space=0 + // View descriptor table, if any + // Sampler buffer descriptor table, if any + // Root descriptors (for dynamic offset buffers) + // (bind group [1]) - Space=0 + // ... + // (bind group [2]) - Space=0 + // Special constant buffer: Space=0 + // Sampler descriptor tables: Space=0 + // SamplerState Array: Space=0, Register=0-2047 + // SamplerComparisonState Array: Space=0, Register=2048-4095 + + //TODO: put lower bind group indices further down the root signature. See: + // https://microsoft.github.io/DirectX-Specs/d3d/ResourceBinding.html#binding-model + // Currently impossible because wgpu-core only re-binds the descriptor sets based + // on Vulkan-like layout compatibility rules. + + let mut binding_map = hlsl::BindingMap::default(); + let mut sampler_buffer_binding_map = hlsl::SamplerIndexBufferBindingMap::default(); + let mut external_texture_binding_map = hlsl::ExternalTextureBindingMap::default(); + let mut bind_cbv = hlsl::BindTarget::default(); + let mut bind_srv = hlsl::BindTarget::default(); + let mut bind_uav = hlsl::BindTarget::default(); + let mut parameters = Vec::new(); + let mut immediates_target = None; + let mut immediates_info = None; + + if desc.immediate_size != 0 { + let parameter_index = parameters.len(); + let size = desc.immediate_size / 4; + parameters.push(Direct3D12::D3D12_ROOT_PARAMETER { + ParameterType: Direct3D12::D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS, + Anonymous: Direct3D12::D3D12_ROOT_PARAMETER_0 { + Constants: Direct3D12::D3D12_ROOT_CONSTANTS { + ShaderRegister: bind_cbv.register, + RegisterSpace: bind_cbv.space as u32, + Num32BitValues: size, + }, + }, + ShaderVisibility: Direct3D12::D3D12_SHADER_VISIBILITY_ALL, + }); + let binding = bind_cbv; + bind_cbv.register += 1; + immediates_info = Some(super::ImmediatesInfo { + root_index: parameter_index as u32, + size, + }); + immediates_target = Some(binding); + + bind_cbv.space += 1; + } + + let mut dynamic_storage_buffer_offsets_targets = alloc::collections::BTreeMap::new(); + let mut total_dynamic_storage_buffers = 0; + + // Collect the whole number of bindings we will create upfront. + // It allows us to preallocate enough storage to avoid reallocation, + // which could cause invalid pointers. + let mut total_non_dynamic_entries = 0_usize; + let mut sampler_in_any_bind_group = false; + for bgl in desc.bind_group_layouts { + let Some(bgl) = bgl else { + continue; + }; + + let mut sampler_in_bind_group = false; + + for entry in &bgl.entries { + match entry.ty { + wgt::BindingType::Buffer { + ty: wgt::BufferBindingType::Uniform, + has_dynamic_offset: true, + .. + } => {} + wgt::BindingType::Sampler(_) => sampler_in_bind_group = true, + // Three texture planes and one params buffer + wgt::BindingType::ExternalTexture => total_non_dynamic_entries += 4, + _ => total_non_dynamic_entries += 1, + } + } + + if sampler_in_bind_group { + // One for the sampler buffer + total_non_dynamic_entries += 1; + sampler_in_any_bind_group = true; + } + } + + if sampler_in_any_bind_group { + // Two for the sampler arrays themselves + total_non_dynamic_entries += 2; + } + + let mut ranges = Vec::with_capacity(total_non_dynamic_entries); + + let mut bind_group_infos = [const { None }; crate::MAX_BIND_GROUPS]; + for (index, bgl) in desc.bind_group_layouts.iter().enumerate() { + let Some(bgl) = bgl else { + continue; + }; + + let mut info = super::BindGroupInfo { + tables: super::TableTypes::empty(), + base_root_index: parameters.len() as u32, + dynamic_storage_buffer_offsets: None, + }; + + let mut visibility_view_static = wgt::ShaderStages::empty(); + let mut visibility_view_dynamic_uniform = wgt::ShaderStages::empty(); + let mut visibility_view_dynamic_storage = wgt::ShaderStages::empty(); + for entry in bgl.entries.iter() { + match entry.ty { + wgt::BindingType::Sampler { .. } => { + visibility_view_static |= wgt::ShaderStages::all() + } + wgt::BindingType::Buffer { + ty: wgt::BufferBindingType::Uniform, + has_dynamic_offset: true, + .. + } => visibility_view_dynamic_uniform |= entry.visibility, + wgt::BindingType::Buffer { + ty: wgt::BufferBindingType::Storage { .. }, + has_dynamic_offset: true, + .. + } => visibility_view_dynamic_storage |= entry.visibility, + _ => visibility_view_static |= entry.visibility, + } + } + + let mut dynamic_storage_buffers = 0; + + // SRV/CBV/UAV descriptor tables + let range_base = ranges.len(); + for entry in bgl.entries.iter() { + let count = entry.count.map_or(1, NonZeroU32::get); + if let wgt::BindingType::ExternalTexture = entry.ty { + // External textures need 3 SRVs (a texture for each plane) + // and 1 CBV for the parameters buffer. + let bind_target = hlsl::ExternalTextureBindTarget { + planes: core::array::from_fn(|_| hlsl::BindTarget { + register: { + let register = bind_srv.register; + bind_srv.register += count; + register + }, + ..bind_srv + }), + params: hlsl::BindTarget { + register: { + let register = bind_cbv.register; + bind_cbv.register += count; + register + }, + ..bind_cbv + }, + }; + external_texture_binding_map.insert( + naga::ResourceBinding { + group: index as u32, + binding: entry.binding, + }, + bind_target, + ); + for bt in bind_target.planes { + ranges.push(Direct3D12::D3D12_DESCRIPTOR_RANGE { + RangeType: Direct3D12::D3D12_DESCRIPTOR_RANGE_TYPE_SRV, + NumDescriptors: count, + BaseShaderRegister: bt.register, + RegisterSpace: bt.space as u32, + OffsetInDescriptorsFromTableStart: + Direct3D12::D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND, + }); + } + ranges.push(Direct3D12::D3D12_DESCRIPTOR_RANGE { + RangeType: Direct3D12::D3D12_DESCRIPTOR_RANGE_TYPE_CBV, + NumDescriptors: count, + BaseShaderRegister: bind_target.params.register, + RegisterSpace: bind_target.params.space as u32, + OffsetInDescriptorsFromTableStart: + Direct3D12::D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND, + }); + } else { + let (range_ty, has_dynamic_offset) = match entry.ty { + wgt::BindingType::Buffer { + ty, + has_dynamic_offset: true, + .. + } => match ty { + wgt::BufferBindingType::Uniform => continue, + wgt::BufferBindingType::Storage { .. } => { + (conv::map_binding_type(&entry.ty), true) + } + }, + ref other => (conv::map_binding_type(other), false), + }; + let bt = match range_ty { + Direct3D12::D3D12_DESCRIPTOR_RANGE_TYPE_CBV => &mut bind_cbv, + Direct3D12::D3D12_DESCRIPTOR_RANGE_TYPE_SRV => &mut bind_srv, + Direct3D12::D3D12_DESCRIPTOR_RANGE_TYPE_UAV => &mut bind_uav, + Direct3D12::D3D12_DESCRIPTOR_RANGE_TYPE_SAMPLER => continue, + _ => todo!(), + }; + + let binding_array_size = entry.count.map(NonZeroU32::get); + + let dynamic_storage_buffer_offsets_index = if has_dynamic_offset { + debug_assert!( + binding_array_size.is_none(), + "binding arrays and dynamic buffers are mutually exclusive" + ); + let ret = Some(dynamic_storage_buffers); + dynamic_storage_buffers += 1; + ret + } else { + None + }; + + binding_map.insert( + naga::ResourceBinding { + group: index as u32, + binding: entry.binding, + }, + hlsl::BindTarget { + binding_array_size, + dynamic_storage_buffer_offsets_index, + ..*bt + }, + ); + ranges.push(Direct3D12::D3D12_DESCRIPTOR_RANGE { + RangeType: range_ty, + NumDescriptors: count, + BaseShaderRegister: bt.register, + RegisterSpace: bt.space as u32, + OffsetInDescriptorsFromTableStart: + Direct3D12::D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND, + }); + bt.register += count; + } + } + + let mut sampler_index_within_bind_group = 0; + for entry in bgl.entries.iter() { + if let wgt::BindingType::Sampler(_) = entry.ty { + binding_map.insert( + naga::ResourceBinding { + group: index as u32, + binding: entry.binding, + }, + hlsl::BindTarget { + // Naga does not use the space field for samplers + space: 255, + register: sampler_index_within_bind_group, + binding_array_size: None, + dynamic_storage_buffer_offsets_index: None, + restrict_indexing: false, + }, + ); + sampler_index_within_bind_group += 1; + } + } + + if sampler_index_within_bind_group != 0 { + sampler_buffer_binding_map.insert( + hlsl::SamplerIndexBufferKey { + group: index as u32, + }, + bind_srv, + ); + ranges.push(Direct3D12::D3D12_DESCRIPTOR_RANGE { + RangeType: Direct3D12::D3D12_DESCRIPTOR_RANGE_TYPE_SRV, + NumDescriptors: 1, + BaseShaderRegister: bind_srv.register, + RegisterSpace: bind_srv.space as u32, + OffsetInDescriptorsFromTableStart: + Direct3D12::D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND, + }); + bind_srv.register += 1; + } + + if ranges.len() > range_base { + let range = &ranges[range_base..]; + parameters.push(Direct3D12::D3D12_ROOT_PARAMETER { + ParameterType: Direct3D12::D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE, + Anonymous: Direct3D12::D3D12_ROOT_PARAMETER_0 { + DescriptorTable: Direct3D12::D3D12_ROOT_DESCRIPTOR_TABLE { + NumDescriptorRanges: range.len() as u32, + pDescriptorRanges: range.as_ptr(), + }, + }, + ShaderVisibility: conv::map_visibility(visibility_view_static), + }); + info.tables |= super::TableTypes::SRV_CBV_UAV; + } + + // Root descriptors for dynamic uniform buffers + let dynamic_buffers_visibility = conv::map_visibility(visibility_view_dynamic_uniform); + for entry in bgl.entries.iter() { + match entry.ty { + wgt::BindingType::Buffer { + ty: wgt::BufferBindingType::Uniform, + has_dynamic_offset: true, + .. + } => {} + _ => continue, + }; + + binding_map.insert( + naga::ResourceBinding { + group: index as u32, + binding: entry.binding, + }, + hlsl::BindTarget { + binding_array_size: entry.count.map(NonZeroU32::get), + restrict_indexing: true, + ..bind_cbv + }, + ); + + parameters.push(Direct3D12::D3D12_ROOT_PARAMETER { + ParameterType: Direct3D12::D3D12_ROOT_PARAMETER_TYPE_CBV, + Anonymous: Direct3D12::D3D12_ROOT_PARAMETER_0 { + Descriptor: Direct3D12::D3D12_ROOT_DESCRIPTOR { + ShaderRegister: bind_cbv.register, + RegisterSpace: bind_cbv.space as u32, + }, + }, + ShaderVisibility: dynamic_buffers_visibility, + }); + + bind_cbv.register += entry.count.map_or(1, NonZeroU32::get); + } + + // Root constants for (offsets of) dynamic storage buffers + if dynamic_storage_buffers > 0 { + let parameter_index = parameters.len(); + + parameters.push(Direct3D12::D3D12_ROOT_PARAMETER { + ParameterType: Direct3D12::D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS, + Anonymous: Direct3D12::D3D12_ROOT_PARAMETER_0 { + Constants: Direct3D12::D3D12_ROOT_CONSTANTS { + ShaderRegister: bind_cbv.register, + RegisterSpace: bind_cbv.space as u32, + Num32BitValues: dynamic_storage_buffers, + }, + }, + ShaderVisibility: conv::map_visibility(visibility_view_dynamic_storage), + }); + + let binding = hlsl::OffsetsBindTarget { + space: bind_cbv.space, + register: bind_cbv.register, + size: dynamic_storage_buffers, + }; + + bind_cbv.register += 1; + + dynamic_storage_buffer_offsets_targets.insert(index as u32, binding); + info.dynamic_storage_buffer_offsets = Some(DynamicStorageBufferOffsets { + root_index: parameter_index as u32, + range: total_dynamic_storage_buffers as usize + ..total_dynamic_storage_buffers as usize + dynamic_storage_buffers as usize, + }); + total_dynamic_storage_buffers += dynamic_storage_buffers; + } + + bind_group_infos[index] = Some(info); + } + + let sampler_heap_target = hlsl::SamplerHeapBindTargets { + standard_samplers: hlsl::BindTarget { + space: 0, + register: 0, + binding_array_size: None, + dynamic_storage_buffer_offsets_index: None, + restrict_indexing: false, + }, + comparison_samplers: hlsl::BindTarget { + space: 0, + register: 2048, + binding_array_size: None, + dynamic_storage_buffer_offsets_index: None, + restrict_indexing: false, + }, + }; + + let mut sampler_heap_root_index = None; + if sampler_in_any_bind_group { + // Sampler descriptor tables + // + // We bind two sampler ranges pointing to the same descriptor heap, using two different register ranges. + // + // We bind them as normal samplers in registers 0-2047 and comparison samplers in registers 2048-4095. + // Tier 2 hardware guarantees that the type of sampler only needs to match if the sampler is actually + // accessed in the shader. As such, we can bind the same array of samplers to both registers. + // + // We do this because HLSL does not allow you to alias registers at all. + let range_base = ranges.len(); + // Standard samplers, registers 0-2047 + ranges.push(Direct3D12::D3D12_DESCRIPTOR_RANGE { + RangeType: Direct3D12::D3D12_DESCRIPTOR_RANGE_TYPE_SAMPLER, + NumDescriptors: 2048, + BaseShaderRegister: 0, + RegisterSpace: 0, + OffsetInDescriptorsFromTableStart: 0, + }); + // Comparison samplers, registers 2048-4095 + ranges.push(Direct3D12::D3D12_DESCRIPTOR_RANGE { + RangeType: Direct3D12::D3D12_DESCRIPTOR_RANGE_TYPE_SAMPLER, + NumDescriptors: 2048, + BaseShaderRegister: 2048, + RegisterSpace: 0, + OffsetInDescriptorsFromTableStart: 0, + }); + + let range = &ranges[range_base..]; + sampler_heap_root_index = Some(parameters.len() as super::RootIndex); + parameters.push(Direct3D12::D3D12_ROOT_PARAMETER { + ParameterType: Direct3D12::D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE, + Anonymous: Direct3D12::D3D12_ROOT_PARAMETER_0 { + DescriptorTable: Direct3D12::D3D12_ROOT_DESCRIPTOR_TABLE { + NumDescriptorRanges: range.len() as u32, + pDescriptorRanges: range.as_ptr(), + }, + }, + ShaderVisibility: Direct3D12::D3D12_SHADER_VISIBILITY_ALL, + }); + } + + // Ensure that we didn't reallocate! + debug_assert_eq!(ranges.len(), total_non_dynamic_entries); + + let (special_constants_root_index, special_constants_binding) = if desc.flags.intersects( + crate::PipelineLayoutFlags::FIRST_VERTEX_INSTANCE + | crate::PipelineLayoutFlags::NUM_WORK_GROUPS, + ) { + let parameter_index = parameters.len(); + parameters.push(Direct3D12::D3D12_ROOT_PARAMETER { + ParameterType: Direct3D12::D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS, + Anonymous: Direct3D12::D3D12_ROOT_PARAMETER_0 { + Constants: Direct3D12::D3D12_ROOT_CONSTANTS { + ShaderRegister: bind_cbv.register, + RegisterSpace: bind_cbv.space as u32, + Num32BitValues: 3, // 0 = first_vertex, 1 = first_instance, 2 = other + }, + }, + ShaderVisibility: Direct3D12::D3D12_SHADER_VISIBILITY_ALL, // really needed for VS and CS only, + }); + let binding = bind_cbv; + // This is the last time we use this, but lets increment + // it so if we add more later, the value behaves correctly. + + // This is an allow as it doesn't trigger on 1.90, hal's MSRV. + #[allow(unused_assignments)] + { + bind_cbv.register += 1; + } + (Some(parameter_index as u32), Some(binding)) + } else { + (None, None) + }; + + let blob = self.library.serialize_root_signature( + Direct3D12::D3D_ROOT_SIGNATURE_VERSION_1_0, + &parameters, + &[], + Direct3D12::D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT, + )?; + + let raw = unsafe { + self.raw + .CreateRootSignature::<Direct3D12::ID3D12RootSignature>(0, blob.as_slice()) + } + .into_device_result("Root signature creation")?; + + let special_constants = if let Some(root_index) = special_constants_root_index { + let cmd_signatures = if desc + .flags + .contains(crate::PipelineLayoutFlags::INDIRECT_BUILTIN_UPDATE) + { + let constant_indirect_argument_desc = Direct3D12::D3D12_INDIRECT_ARGUMENT_DESC { + Type: Direct3D12::D3D12_INDIRECT_ARGUMENT_TYPE_CONSTANT, + Anonymous: Direct3D12::D3D12_INDIRECT_ARGUMENT_DESC_0 { + Constant: Direct3D12::D3D12_INDIRECT_ARGUMENT_DESC_0_1 { + RootParameterIndex: root_index, + DestOffsetIn32BitValues: 0, + Num32BitValuesToSet: 3, + }, + }, + }; + let special_constant_buffer_args_len = size_of::<super::SpecialConstants>(); + + Some(super::CommandSignatures { + draw: Self::create_command_signature( + &self.raw, + Some(&raw), + special_constant_buffer_args_len + size_of::<wgt::DrawIndirectArgs>(), + &[ + constant_indirect_argument_desc, + Direct3D12::D3D12_INDIRECT_ARGUMENT_DESC { + Type: Direct3D12::D3D12_INDIRECT_ARGUMENT_TYPE_DRAW, + ..Default::default() + }, + ], + 0, + )?, + draw_indexed: Self::create_command_signature( + &self.raw, + Some(&raw), + special_constant_buffer_args_len + + size_of::<wgt::DrawIndexedIndirectArgs>(), + &[ + constant_indirect_argument_desc, + Direct3D12::D3D12_INDIRECT_ARGUMENT_DESC { + Type: Direct3D12::D3D12_INDIRECT_ARGUMENT_TYPE_DRAW_INDEXED, + ..Default::default() + }, + ], + 0, + )?, + // Mesh pipelines don't support updating special constants. + draw_mesh: None, + dispatch: Self::create_command_signature( + &self.raw, + Some(&raw), + special_constant_buffer_args_len + size_of::<wgt::DispatchIndirectArgs>(), + &[ + constant_indirect_argument_desc, + Direct3D12::D3D12_INDIRECT_ARGUMENT_DESC { + Type: Direct3D12::D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH, + ..Default::default() + }, + ], + 0, + )?, + }) + } else { + None + }; + Some(super::PipelineLayoutSpecialConstants { + root_index, + indirect_cmd_signatures: cmd_signatures, + }) + } else { + None + }; + + if let Some(label) = desc.label { + raw.set_name(label)?; + } + + self.counters.pipeline_layouts.add(1); + + Ok(super::PipelineLayout { + shared: super::PipelineLayoutShared { + signature: Some(raw), + total_root_elements: parameters.len() as super::RootIndex, + special_constants, + immediates_info, + sampler_heap_root_index, + }, + bind_group_infos, + naga_options: hlsl::Options { + shader_model: self.shared.private_caps.shader_model, + binding_map, + fake_missing_bindings: false, + special_constants_binding, + immediates_target, + dynamic_storage_buffer_offsets_targets, + zero_initialize_workgroup_memory: true, + restrict_indexing: true, + sampler_heap_target, + sampler_buffer_binding_map, + external_texture_binding_map, + force_loop_bounding: true, + task_dispatch_limits: Some(naga::back::TaskDispatchLimits { + max_mesh_workgroups_per_dim: self.limits.max_mesh_workgroups_per_dimension, + max_mesh_workgroups_total: self.limits.max_mesh_workgroup_total_count, + }), + mesh_shader_primitive_indices_clamp: true, + ray_query_initialization_tracking: true, + }, + }) + } + + unsafe fn destroy_pipeline_layout(&self, _pipeline_layout: super::PipelineLayout) { + self.counters.pipeline_layouts.sub(1); + } + + unsafe fn create_bind_group( + &self, + desc: &crate::BindGroupDescriptor< + super::BindGroupLayout, + super::Buffer, + super::Sampler, + super::TextureView, + super::AccelerationStructure, + >, + ) -> Result<super::BindGroup, crate::DeviceError> { + let mut cpu_views = desc + .layout + .cpu_heap_views + .as_ref() + .map(|cpu_heap| cpu_heap.inner.lock()); + if let Some(ref mut inner) = cpu_views { + inner.stage.clear(); + } + let mut dynamic_buffers = Vec::new(); + + let layout_and_entry_iter = desc.entries.iter().map(|entry| { + let layout = desc + .layout + .entries + .iter() + .find(|layout_entry| layout_entry.binding == entry.binding) + .expect("internal error: no layout entry found with binding slot"); + (layout, entry) + }); + let mut sampler_indexes: Vec<super::sampler::SamplerIndex> = Vec::new(); + + for (layout, entry) in layout_and_entry_iter { + match layout.ty { + wgt::BindingType::Buffer { + ty, + has_dynamic_offset, + .. + } => { + let start = entry.resource_index as usize; + let end = start + entry.count as usize; + for data in &desc.buffers[start..end] { + let gpu_address = data.resolve_address(); + let mut size = data.resolve_size().try_into().unwrap(); + + if has_dynamic_offset { + match ty { + wgt::BufferBindingType::Uniform => { + dynamic_buffers.push(super::DynamicBuffer::Uniform( + Direct3D12::D3D12_GPU_DESCRIPTOR_HANDLE { + ptr: data.resolve_address(), + }, + )); + continue; + } + wgt::BufferBindingType::Storage { .. } => { + size = (data.buffer.size - data.offset) as u32; + dynamic_buffers.push(super::DynamicBuffer::Storage); + } + } + } + + let inner = cpu_views.as_mut().unwrap(); + let cpu_index = inner.stage.len() as u32; + let handle = desc.layout.cpu_heap_views.as_ref().unwrap().at(cpu_index); + match ty { + wgt::BufferBindingType::Uniform => { + let size_mask = + Direct3D12::D3D12_CONSTANT_BUFFER_DATA_PLACEMENT_ALIGNMENT - 1; + let raw_desc = Direct3D12::D3D12_CONSTANT_BUFFER_VIEW_DESC { + BufferLocation: gpu_address, + SizeInBytes: ((size - 1) | size_mask) + 1, + }; + unsafe { + self.raw.CreateConstantBufferView(Some(&raw_desc), handle) + }; + } + wgt::BufferBindingType::Storage { read_only: true } => { + let raw_desc = Direct3D12::D3D12_SHADER_RESOURCE_VIEW_DESC { + Format: Dxgi::Common::DXGI_FORMAT_R32_TYPELESS, + Shader4ComponentMapping: + Direct3D12::D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, + ViewDimension: Direct3D12::D3D12_SRV_DIMENSION_BUFFER, + Anonymous: Direct3D12::D3D12_SHADER_RESOURCE_VIEW_DESC_0 { + Buffer: Direct3D12::D3D12_BUFFER_SRV { + FirstElement: data.offset / 4, + NumElements: size / 4, + StructureByteStride: 0, + Flags: Direct3D12::D3D12_BUFFER_SRV_FLAG_RAW, + }, + }, + }; + unsafe { + self.raw.CreateShaderResourceView( + &data.buffer.resource, + Some(&raw_desc), + handle, + ) + }; + } + wgt::BufferBindingType::Storage { read_only: false } => { + let raw_desc = Direct3D12::D3D12_UNORDERED_ACCESS_VIEW_DESC { + Format: Dxgi::Common::DXGI_FORMAT_R32_TYPELESS, + ViewDimension: Direct3D12::D3D12_UAV_DIMENSION_BUFFER, + Anonymous: Direct3D12::D3D12_UNORDERED_ACCESS_VIEW_DESC_0 { + Buffer: Direct3D12::D3D12_BUFFER_UAV { + FirstElement: data.offset / 4, + NumElements: size / 4, + StructureByteStride: 0, + CounterOffsetInBytes: 0, + Flags: Direct3D12::D3D12_BUFFER_UAV_FLAG_RAW, + }, + }, + }; + unsafe { + self.raw.CreateUnorderedAccessView( + &data.buffer.resource, + None, + Some(&raw_desc), + handle, + ) + }; + } + } + inner.stage.push(handle); + } + } + wgt::BindingType::Texture { .. } => { + let start = entry.resource_index as usize; + let end = start + entry.count as usize; + for data in &desc.textures[start..end] { + let handle = data.view.handle_srv.unwrap(); + cpu_views.as_mut().unwrap().stage.push(handle.raw); + } + // The table range reserves the full `layout.count`, so pad a + // partially-bound array with null SRVs to keep later bindings aligned. + let array_size = layout.count.map_or(1, NonZeroU32::get); + for _ in entry.count..array_size { + let inner = cpu_views.as_mut().unwrap(); + let cpu_index = inner.stage.len() as u32; + let handle = desc.layout.cpu_heap_views.as_ref().unwrap().at(cpu_index); + let raw_desc = Direct3D12::D3D12_SHADER_RESOURCE_VIEW_DESC { + Format: Dxgi::Common::DXGI_FORMAT_R8G8B8A8_UNORM, + ViewDimension: Direct3D12::D3D12_SRV_DIMENSION_TEXTURE2D, + Shader4ComponentMapping: + Direct3D12::D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, + Anonymous: Direct3D12::D3D12_SHADER_RESOURCE_VIEW_DESC_0 { + Texture2D: Direct3D12::D3D12_TEX2D_SRV { + MostDetailedMip: 0, + MipLevels: 1, + PlaneSlice: 0, + ResourceMinLODClamp: 0.0, + }, + }, + }; + unsafe { + self.raw + .CreateShaderResourceView(None, Some(&raw_desc), handle) + }; + inner.stage.push(handle); + } + } + wgt::BindingType::StorageTexture { .. } => { + let start = entry.resource_index as usize; + let end = start + entry.count as usize; + for data in &desc.textures[start..end] { + let handle = data.view.handle_uav.unwrap(); + cpu_views.as_mut().unwrap().stage.push(handle.raw); + } + // Same partial-binding-array padding as the `Texture` branch above, but + // with null UAVs so that bindings following the array keep their offsets. + let array_size = layout.count.map_or(1, NonZeroU32::get); + for _ in entry.count..array_size { + let inner = cpu_views.as_mut().unwrap(); + let cpu_index = inner.stage.len() as u32; + let handle = desc.layout.cpu_heap_views.as_ref().unwrap().at(cpu_index); + let raw_desc = Direct3D12::D3D12_UNORDERED_ACCESS_VIEW_DESC { + Format: Dxgi::Common::DXGI_FORMAT_R8G8B8A8_UNORM, + ViewDimension: Direct3D12::D3D12_UAV_DIMENSION_TEXTURE2D, + Anonymous: Direct3D12::D3D12_UNORDERED_ACCESS_VIEW_DESC_0 { + Texture2D: Direct3D12::D3D12_TEX2D_UAV { + MipSlice: 0, + PlaneSlice: 0, + }, + }, + }; + unsafe { + self.raw + .CreateUnorderedAccessView(None, None, Some(&raw_desc), handle) + }; + inner.stage.push(handle); + } + } + wgt::BindingType::Sampler { .. } => { + let start = entry.resource_index as usize; + let end = start + entry.count as usize; + for &data in &desc.samplers[start..end] { + sampler_indexes.push(data.index); + } + } + wgt::BindingType::AccelerationStructure { .. } => { + let start = entry.resource_index as usize; + let end = start + entry.count as usize; + for data in &desc.acceleration_structures[start..end] { + let inner = cpu_views.as_mut().unwrap(); + let cpu_index = inner.stage.len() as u32; + let handle = desc.layout.cpu_heap_views.as_ref().unwrap().at(cpu_index); + let raw_desc = Direct3D12::D3D12_SHADER_RESOURCE_VIEW_DESC { + Format: Dxgi::Common::DXGI_FORMAT_UNKNOWN, + Shader4ComponentMapping: + Direct3D12::D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, + ViewDimension: + Direct3D12::D3D12_SRV_DIMENSION_RAYTRACING_ACCELERATION_STRUCTURE, + Anonymous: Direct3D12::D3D12_SHADER_RESOURCE_VIEW_DESC_0 { + RaytracingAccelerationStructure: + Direct3D12::D3D12_RAYTRACING_ACCELERATION_STRUCTURE_SRV { + Location: unsafe { data.resource.GetGPUVirtualAddress() }, + }, + }, + }; + unsafe { + self.raw + .CreateShaderResourceView(None, Some(&raw_desc), handle) + }; + inner.stage.push(handle); + } + } + wgt::BindingType::ExternalTexture => { + // We don't yet support binding arrays of external textures. + // https://github.com/gfx-rs/wgpu/issues/8027 + assert_eq!(entry.count, 1); + let external_texture = &desc.external_textures[entry.resource_index as usize]; + for plane in &external_texture.planes { + let plane_handle = plane.view.handle_srv.unwrap(); + cpu_views.as_mut().unwrap().stage.push(plane_handle.raw); + } + let gpu_address = external_texture.params.resolve_address(); + let size = external_texture.params.resolve_size() as u32; + let inner = cpu_views.as_mut().unwrap(); + let cpu_index = inner.stage.len() as u32; + let params_handle = desc.layout.cpu_heap_views.as_ref().unwrap().at(cpu_index); + let size_mask = Direct3D12::D3D12_CONSTANT_BUFFER_DATA_PLACEMENT_ALIGNMENT - 1; + let raw_desc = Direct3D12::D3D12_CONSTANT_BUFFER_VIEW_DESC { + BufferLocation: gpu_address, + SizeInBytes: ((size - 1) | size_mask) + 1, + }; + unsafe { + self.raw + .CreateConstantBufferView(Some(&raw_desc), params_handle) + }; + inner.stage.push(params_handle); + } + } + } + + let sampler_index_buffer = if !sampler_indexes.is_empty() { + let buffer_size = (sampler_indexes.len() * size_of::<u32>()) as u64; + + let label = if let Some(label) = desc.label { + Cow::Owned(format!("{label} (Internal Sampler Index Buffer)")) + } else { + Cow::Borrowed("Internal Sampler Index Buffer") + }; + + let buffer_desc = crate::BufferDescriptor { + label: Some(&label), + size: buffer_size, + usage: wgt::BufferUses::STORAGE_READ_ONLY | wgt::BufferUses::MAP_WRITE, + // D3D12 backend doesn't care about the memory flags + memory_flags: crate::MemoryFlags::empty(), + }; + + let (buffer, allocation) = + suballocation::DeviceAllocationContext::from(self).create_buffer(&buffer_desc)?; + + let mut mapping = ptr::null_mut::<ffi::c_void>(); + unsafe { buffer.Map(0, None, Some(&mut mapping)) }.into_device_result("Map")?; + + assert!(!mapping.is_null()); + assert_eq!(mapping as usize % 4, 0); + + unsafe { + ptr::copy_nonoverlapping( + sampler_indexes.as_ptr(), + mapping.cast(), + sampler_indexes.len(), + ) + }; + + // The unmapping is not needed, as all memory is coherent in d3d12, but lets be nice to our address space. + unsafe { buffer.Unmap(0, None) }; + + let srv_desc = Direct3D12::D3D12_SHADER_RESOURCE_VIEW_DESC { + Format: Dxgi::Common::DXGI_FORMAT_UNKNOWN, + ViewDimension: Direct3D12::D3D12_SRV_DIMENSION_BUFFER, + Anonymous: Direct3D12::D3D12_SHADER_RESOURCE_VIEW_DESC_0 { + Buffer: Direct3D12::D3D12_BUFFER_SRV { + FirstElement: 0, + NumElements: sampler_indexes.len() as u32, + StructureByteStride: 4, + Flags: Direct3D12::D3D12_BUFFER_SRV_FLAG_NONE, + }, + }, + Shader4ComponentMapping: Direct3D12::D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, + }; + + let inner = cpu_views.as_mut().unwrap(); + let cpu_index = inner.stage.len() as u32; + let srv = desc.layout.cpu_heap_views.as_ref().unwrap().at(cpu_index); + + unsafe { + self.raw + .CreateShaderResourceView(&buffer, Some(&srv_desc), srv) + }; + + cpu_views.as_mut().unwrap().stage.push(srv); + + Some(super::SamplerIndexBuffer { buffer, allocation }) + } else { + None + }; + + let handle_views = match cpu_views { + Some(inner) => { + let dual = unsafe { + descriptor::upload( + &self.raw, + &inner, + &self.shared.heap_views, + &desc.layout.copy_counts, + ) + }?; + Some(dual) + } + None => None, + }; + + self.counters.bind_groups.add(1); + + Ok(super::BindGroup { + handle_views, + sampler_index_buffer, + dynamic_buffers, + }) + } + + unsafe fn destroy_bind_group(&self, group: super::BindGroup) { + if let Some(dual) = group.handle_views { + self.shared.heap_views.free_slice(dual); + } + + if let Some(sampler_buffer) = group.sampler_index_buffer { + suballocation::DeviceAllocationContext::from(self) + .free_resource(sampler_buffer.buffer, sampler_buffer.allocation); + } + + self.counters.bind_groups.sub(1); + } + + unsafe fn create_shader_module( + &self, + desc: &crate::ShaderModuleDescriptor, + shader: crate::ShaderInput, + ) -> Result<super::ShaderModule, crate::ShaderError> { + self.counters.shader_modules.add(1); + + let raw_name = desc + .label + .and_then(|label| alloc::ffi::CString::new(label).ok()); + match shader { + crate::ShaderInput::Naga(naga) => Ok(super::ShaderModule { + source: super::ShaderModuleSource::Naga(naga), + raw_name, + runtime_checks: desc.runtime_checks, + }), + crate::ShaderInput::Dxil { shader } => Ok(super::ShaderModule { + source: super::ShaderModuleSource::DxilPassthrough(super::DxilPassthroughShader { + shader: shader.to_vec(), + }), + raw_name, + runtime_checks: desc.runtime_checks, + }), + crate::ShaderInput::Hlsl { shader } => Ok(super::ShaderModule { + source: super::ShaderModuleSource::HlslPassthrough(super::HlslPassthroughShader { + shader: shader.to_owned(), + }), + raw_name, + runtime_checks: desc.runtime_checks, + }), + crate::ShaderInput::SpirV(_) + | crate::ShaderInput::MetalLib { .. } + | crate::ShaderInput::Msl { .. } + | crate::ShaderInput::Glsl { .. } => { + unreachable!() + } + } + } + unsafe fn destroy_shader_module(&self, _module: super::ShaderModule) { + self.counters.shader_modules.sub(1); + // just drop + } + + unsafe fn create_render_pipeline( + &self, + desc: &crate::RenderPipelineDescriptor< + super::PipelineLayout, + super::ShaderModule, + super::PipelineCache, + >, + ) -> Result<super::RenderPipeline, crate::PipelineError> { + let mut shader_stages = wgt::ShaderStages::empty(); + let (topology_class, topology) = conv::map_topology(desc.primitive.topology); + let mut rtv_formats = [Dxgi::Common::DXGI_FORMAT_UNKNOWN; + Direct3D12::D3D12_SIMULTANEOUS_RENDER_TARGET_COUNT as usize]; + for (rtv_format, ct) in rtv_formats.iter_mut().zip(desc.color_targets) { + if let Some(ct) = ct.as_ref() { + *rtv_format = auxil::dxgi::conv::map_texture_format(ct.format); + } + } + + let bias = desc + .depth_stencil + .as_ref() + .map(|ds| ds.bias) + .unwrap_or_default(); + + let rasterizer_state = Direct3D12::D3D12_RASTERIZER_DESC { + FillMode: conv::map_polygon_mode(desc.primitive.polygon_mode), + CullMode: match desc.primitive.cull_mode { + None => Direct3D12::D3D12_CULL_MODE_NONE, + Some(wgt::Face::Front) => Direct3D12::D3D12_CULL_MODE_FRONT, + Some(wgt::Face::Back) => Direct3D12::D3D12_CULL_MODE_BACK, + }, + FrontCounterClockwise: match desc.primitive.front_face { + wgt::FrontFace::Cw => Foundation::FALSE, + wgt::FrontFace::Ccw => Foundation::TRUE, + }, + DepthBias: bias.constant, + DepthBiasClamp: bias.clamp, + SlopeScaledDepthBias: bias.slope_scale, + DepthClipEnable: windows_core::BOOL::from(!desc.primitive.unclipped_depth), + MultisampleEnable: windows_core::BOOL::from(desc.multisample.count > 1), + ForcedSampleCount: 0, + AntialiasedLineEnable: false.into(), + ConservativeRaster: if desc.primitive.conservative { + Direct3D12::D3D12_CONSERVATIVE_RASTERIZATION_MODE_ON + } else { + Direct3D12::D3D12_CONSERVATIVE_RASTERIZATION_MODE_OFF + }, + }; + + let blob_fs = match desc.fragment_stage { + Some(ref stage) => { + shader_stages |= wgt::ShaderStages::FRAGMENT; + Some(self.load_shader(stage, desc.layout, naga::ShaderStage::Fragment, None)?) + } + None => None, + }; + let pixel_shader = match &blob_fs { + Some(shader) => shader.create_native_shader(), + None => Direct3D12::D3D12_SHADER_BYTECODE::default(), + }; + let stream_output = Direct3D12::D3D12_STREAM_OUTPUT_DESC { + pSODeclaration: ptr::null(), + NumEntries: 0, + pBufferStrides: ptr::null(), + NumStrides: 0, + RasterizedStream: 0, + }; + let blend_state = Direct3D12::D3D12_BLEND_DESC { + AlphaToCoverageEnable: windows_core::BOOL::from( + desc.multisample.alpha_to_coverage_enabled, + ), + IndependentBlendEnable: true.into(), + RenderTarget: conv::map_render_targets(desc.color_targets), + }; + let depth_stencil_state = match desc.depth_stencil { + Some(ref ds) => conv::map_depth_stencil(ds), + None => Default::default(), + }; + let dsv_format = desc + .depth_stencil + .as_ref() + .map_or(Dxgi::Common::DXGI_FORMAT_UNKNOWN, |ds| { + auxil::dxgi::conv::map_texture_format(ds.format) + }); + let sample_desc = Dxgi::Common::DXGI_SAMPLE_DESC { + Count: desc.multisample.count, + Quality: 0, + }; + let cached_pso = Direct3D12::D3D12_CACHED_PIPELINE_STATE { + pCachedBlob: ptr::null(), + CachedBlobSizeInBytes: 0, + }; + let flags = Direct3D12::D3D12_PIPELINE_STATE_FLAG_NONE; + + let mut view_instancing = ArrayVec::<Direct3D12::D3D12_VIEW_INSTANCE_LOCATION, 32>::new(); + if let Some(mask) = desc.multiview_mask { + let mask = mask.get(); + // This array is just what _could_ be rendered to. We actually apply the mask at + // renderpass creation time. The `view_index` passed to the shader depends on the + // view's index in this array, so if we include every view in this array, `view_index` + // actually the texture array layer, like in vulkan. + for i in 0..32 - mask.leading_zeros() { + view_instancing.push(Direct3D12::D3D12_VIEW_INSTANCE_LOCATION { + ViewportArrayIndex: 0, + RenderTargetArrayIndex: i, + }); + } + } + + // Borrow view instancing slice, so we can be sure that it won't be moved while we have pointers into this buffer. + let view_instancing_slice = view_instancing.as_slice(); + + let mut stream_desc = RenderPipelineStateStreamDesc { + // Shared by vertex and mesh pipelines + root_signature: desc.layout.shared.signature.as_ref(), + pixel_shader, + blend_state, + sample_mask: desc.multisample.mask as u32, + rasterizer_state, + depth_stencil_state, + primitive_topology_type: topology_class, + rtv_formats: Direct3D12::D3D12_RT_FORMAT_ARRAY { + RTFormats: rtv_formats, + NumRenderTargets: desc.color_targets.len() as u32, + }, + dsv_format, + sample_desc, + node_mask: 0, + cached_pso, + flags, + view_instancing: if !view_instancing_slice.is_empty() { + Some(Direct3D12::D3D12_VIEW_INSTANCING_DESC { + ViewInstanceCount: view_instancing_slice.len() as u32, + pViewInstanceLocations: view_instancing_slice.as_ptr(), + // This lets us hide/mask certain values later, at renderpass creation time. + Flags: Direct3D12::D3D12_VIEW_INSTANCING_FLAG_ENABLE_VIEW_INSTANCE_MASKING, + }) + } else { + None + }, + + // Optional data that depends on the pipeline type (vertex vs mesh). + vertex_shader: Default::default(), + input_layout: Default::default(), + index_buffer_strip_cut_value: Default::default(), + stream_output, + task_shader: Default::default(), + mesh_shader: Default::default(), + }; + let mut input_element_descs = Vec::new(); + let blob_vs; + let blob_ts; + let blob_ms; + let mut vertex_strides = [None; crate::MAX_VERTEX_BUFFERS]; + match &desc.vertex_processor { + &crate::VertexProcessor::Standard { + vertex_buffers, + ref vertex_stage, + } => { + shader_stages |= wgt::ShaderStages::VERTEX; + blob_vs = Some(self.load_shader( + vertex_stage, + desc.layout, + naga::ShaderStage::Vertex, + desc.fragment_stage.as_ref(), + )?); + + for (i, (stride, vbuf)) in vertex_strides.iter_mut().zip(vertex_buffers).enumerate() + { + let Some(vbuf) = vbuf else { + continue; + }; + *stride = Some(vbuf.array_stride as u32); + let (slot_class, step_rate) = match vbuf.step_mode { + wgt::VertexStepMode::Vertex => { + (Direct3D12::D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0) + } + wgt::VertexStepMode::Instance => { + (Direct3D12::D3D12_INPUT_CLASSIFICATION_PER_INSTANCE_DATA, 1) + } + }; + for attribute in vbuf.attributes { + input_element_descs.push(Direct3D12::D3D12_INPUT_ELEMENT_DESC { + SemanticName: windows::core::PCSTR(NAGA_LOCATION_SEMANTIC.as_ptr()), + SemanticIndex: attribute.shader_location, + Format: auxil::dxgi::conv::map_vertex_format(attribute.format), + InputSlot: i as u32, + AlignedByteOffset: attribute.offset as u32, + InputSlotClass: slot_class, + InstanceDataStepRate: step_rate, + }); + } + } + stream_desc.vertex_shader = blob_vs.as_ref().unwrap().create_native_shader(); + stream_desc.input_layout = Direct3D12::D3D12_INPUT_LAYOUT_DESC { + pInputElementDescs: if input_element_descs.is_empty() { + ptr::null() + } else { + input_element_descs.as_ptr() + }, + NumElements: input_element_descs.len() as u32, + }; + stream_desc.index_buffer_strip_cut_value = match desc.primitive.strip_index_format { + Some(wgt::IndexFormat::Uint16) => { + Direct3D12::D3D12_INDEX_BUFFER_STRIP_CUT_VALUE_0xFFFF + } + Some(wgt::IndexFormat::Uint32) => { + Direct3D12::D3D12_INDEX_BUFFER_STRIP_CUT_VALUE_0xFFFFFFFF + } + None => Direct3D12::D3D12_INDEX_BUFFER_STRIP_CUT_VALUE_DISABLED, + }; + stream_desc.stream_output = Direct3D12::D3D12_STREAM_OUTPUT_DESC { + pSODeclaration: ptr::null(), + NumEntries: 0, + pBufferStrides: ptr::null(), + NumStrides: 0, + RasterizedStream: 0, + }; + } + crate::VertexProcessor::Mesh { + task_stage, + mesh_stage, + } => { + blob_ts = if let Some(ts) = task_stage { + shader_stages |= wgt::ShaderStages::TASK; + Some(self.load_shader( + ts, + desc.layout, + naga::ShaderStage::Task, + desc.fragment_stage.as_ref(), + )?) + } else { + None + }; + let task_shader = if let Some(ts) = &blob_ts { + ts.create_native_shader() + } else { + Default::default() + }; + shader_stages |= wgt::ShaderStages::MESH; + blob_ms = Some(self.load_shader( + mesh_stage, + desc.layout, + naga::ShaderStage::Mesh, + desc.fragment_stage.as_ref(), + )?); + stream_desc.task_shader = task_shader; + stream_desc.mesh_shader = blob_ms.as_ref().unwrap().create_native_shader(); + } + }; + let raw: Direct3D12::ID3D12PipelineState = + // If stream descriptors are available, use them as they are more flexible. + if let Ok(device) = self.raw.cast::<Direct3D12::ID3D12Device2>() { + // Prefer stream descs where possible + let mut stream = stream_desc.to_stream(); + unsafe { + profiling::scope!("ID3D12Device2::CreatePipelineState"); + stream.create_pipeline_state(&device).map_err(|err| { + crate::PipelineError::Linkage(shader_stages, err.to_string()) + })? + } + } else { + unsafe { + // Safety: `stream_desc` entirely outlives the `desc`. + let desc = stream_desc.to_graphics_pipeline_descriptor(); + self.raw.CreateGraphicsPipelineState(&desc).map_err(|err| { + crate::PipelineError::Linkage(shader_stages, err.to_string()) + })? + } + }; + + if let Some(label) = desc.label { + raw.set_name(label)?; + } + + self.counters.render_pipelines.add(1); + + Ok(super::RenderPipeline { + raw, + layout: desc.layout.shared.clone(), + topology, + vertex_strides, + }) + } + + unsafe fn destroy_render_pipeline(&self, _pipeline: super::RenderPipeline) { + self.counters.render_pipelines.sub(1); + } + + unsafe fn create_compute_pipeline( + &self, + desc: &crate::ComputePipelineDescriptor< + super::PipelineLayout, + super::ShaderModule, + super::PipelineCache, + >, + ) -> Result<super::ComputePipeline, crate::PipelineError> { + let blob_cs = + self.load_shader(&desc.stage, desc.layout, naga::ShaderStage::Compute, None)?; + + let pair = { + profiling::scope!("ID3D12Device::CreateComputePipelineState"); + unsafe { + self.raw.CreateComputePipelineState( + &Direct3D12::D3D12_COMPUTE_PIPELINE_STATE_DESC { + pRootSignature: borrow_optional_interface_temporarily( + &desc.layout.shared.signature, + ), + CS: blob_cs.create_native_shader(), + NodeMask: 0, + CachedPSO: Direct3D12::D3D12_CACHED_PIPELINE_STATE::default(), + Flags: Direct3D12::D3D12_PIPELINE_STATE_FLAG_NONE, + }, + ) + } + }; + + let raw: Direct3D12::ID3D12PipelineState = pair.map_err(|err| { + crate::PipelineError::Linkage(wgt::ShaderStages::COMPUTE, err.to_string()) + })?; + + if let Some(label) = desc.label { + raw.set_name(label)?; + } + + self.counters.compute_pipelines.add(1); + + Ok(super::ComputePipeline { + raw, + layout: desc.layout.shared.clone(), + }) + } + + unsafe fn destroy_compute_pipeline(&self, _pipeline: super::ComputePipeline) { + self.counters.compute_pipelines.sub(1); + } + + unsafe fn create_ray_tracing_pipeline( + &self, + _desc: &crate::RayTracingPipelineDescriptor< + super::PipelineLayout, + super::ShaderModule, + super::PipelineCache, + >, + ) -> Result<<Self::A as crate::Api>::RayTracingPipeline, crate::PipelineError> { + unreachable!("ray tracing pipelines not yet implemented") + } + + unsafe fn destroy_ray_tracing_pipeline(&self, _pipeline: super::RayTracingPipeline) { + unreachable!("ray tracing pipelines not yet implemented") + } + + unsafe fn get_raytracing_pipeline_group_data( + &self, + _pipeline: &super::RayTracingPipeline, + _groups: core::ops::Range<u32>, + ) -> Result<Vec<u8>, crate::DeviceError> { + unimplemented!("ray tracing pipelines not yet implemented") + } + + unsafe fn create_pipeline_cache( + &self, + _desc: &crate::PipelineCacheDescriptor<'_>, + ) -> Result<super::PipelineCache, crate::PipelineCacheError> { + Ok(super::PipelineCache) + } + unsafe fn destroy_pipeline_cache(&self, _: super::PipelineCache) {} + + unsafe fn create_query_set( + &self, + desc: &wgt::QuerySetDescriptor<crate::Label>, + ) -> Result<super::QuerySet, crate::DeviceError> { + let (heap_ty, raw_ty) = match desc.ty { + wgt::QueryType::Occlusion => ( + Direct3D12::D3D12_QUERY_HEAP_TYPE_OCCLUSION, + Direct3D12::D3D12_QUERY_TYPE_BINARY_OCCLUSION, + ), + wgt::QueryType::PipelineStatistics(_) => ( + Direct3D12::D3D12_QUERY_HEAP_TYPE_PIPELINE_STATISTICS, + Direct3D12::D3D12_QUERY_TYPE_PIPELINE_STATISTICS, + ), + wgt::QueryType::Timestamp => ( + Direct3D12::D3D12_QUERY_HEAP_TYPE_TIMESTAMP, + Direct3D12::D3D12_QUERY_TYPE_TIMESTAMP, + ), + }; + + if let Some(threshold) = self + .mem_allocator + .memory_budget_thresholds + .for_resource_creation + { + let info = self + .shared + .adapter + .query_video_memory_info(Dxgi::DXGI_MEMORY_SEGMENT_GROUP_LOCAL)?; + + // Assume each query is 256 bytes. + // On an AMD W6800 with driver version 32.0.12030.9, occlusion and pipeline statistics are 256, timestamp is 8. + + if info.CurrentUsage + desc.count as u64 * 256 >= info.Budget / 100 * threshold as u64 { + return Err(crate::DeviceError::OutOfMemory); + } + } + + let mut raw = None::<Direct3D12::ID3D12QueryHeap>; + unsafe { + self.raw.CreateQueryHeap( + &Direct3D12::D3D12_QUERY_HEAP_DESC { + Type: heap_ty, + Count: desc.count, + NodeMask: 0, + }, + &mut raw, + ) + } + .into_device_result("Query heap creation")?; + + let raw = raw.ok_or(crate::DeviceError::Unexpected)?; + + if let Some(label) = desc.label { + raw.set_name(label)?; + } + + self.counters.query_sets.add(1); + + Ok(super::QuerySet { raw, raw_ty }) + } + + unsafe fn destroy_query_set(&self, _set: super::QuerySet) { + self.counters.query_sets.sub(1); + } + + unsafe fn create_fence(&self) -> Result<super::Fence, crate::DeviceError> { + let raw: Direct3D12::ID3D12Fence = + unsafe { self.raw.CreateFence(0, Direct3D12::D3D12_FENCE_FLAG_SHARED) } + .into_device_result("Fence creation")?; + + self.counters.fences.add(1); + + Ok(super::Fence { raw, reached: Default::default() }) + } + unsafe fn destroy_fence(&self, _fence: super::Fence) { + self.counters.fences.sub(1); + } + + unsafe fn get_fence_value( + &self, + fence: &super::Fence, + ) -> Result<crate::FenceValue, crate::DeviceError> { + Ok(self.reached(fence).unwrap_or_else(|| fence.reached.load(core::sync::atomic::Ordering::Relaxed))) + } + unsafe fn wait( + &self, + fence: &super::Fence, + value: crate::FenceValue, + timeout: Option<Duration>, + ) -> Result<bool, crate::DeviceError> { + let timeout = timeout.unwrap_or(Duration::MAX); + + // We first check if the fence has already reached the value we're waiting for. + // A removed device's fence never reaches `value`. + let Some(mut fence_value) = self.reached(fence) else { return Ok(false) }; + if fence_value >= value { + return Ok(true); + } + + let event = Event::create(false, false)?; + + unsafe { fence.raw.SetEventOnCompletion(value, event.0) } + .into_device_result("Set event")?; + + let start_time = Instant::now(); + + // We need to loop to get correct behavior when timeouts are involved. + // + // wait(0): + // - We set the event from the fence value 0. + // - WaitForSingleObject times out, we return false. + // + // wait(1): + // - We set the event from the fence value 1. + // - WaitForSingleObject returns. However we do not know if the fence value is 0 or 1, + // just that _something_ triggered the event. We check the fence value, and if it is + // 1, we return true. Otherwise, we loop and wait again. + loop { + let elapsed = start_time.elapsed(); + + // We need to explicitly use checked_sub. Overflow with duration panics, and if the + // timing works out just right, we can get a negative remaining wait duration. + // + // This happens when a previous iteration WaitForSingleObject succeeded with a previous fence value, + // right before the timeout would have been hit. + let remaining_wait_duration = match timeout.checked_sub(elapsed) { + Some(remaining) => remaining, + None => { + log::trace!("Timeout elapsed in between waits!"); + break Ok(false); + } + }; + + log::trace!("Waiting for fence value {value} for {remaining_wait_duration:?}"); + + // Rune: in slices of at most 100 ms, reading the fence again after each. A fence can + // read `u64::MAX` a moment before D3D12 reports the removal; `reached` then gives the + // last real value, and the auto-reset event, already fired by that `u64::MAX`, never + // fires again: one wait for the whole timeout (`INFINITE` for `wait_indefinitely`) + // would never return. A slice that ends without the event costs a re-read + // (`GetCompletedValue`, and `GetDeviceRemovedReason` once the fence reads `u64::MAX`); + // a wait the GPU answers returns on the event, as before. + let slice = remaining_wait_duration.min(Duration::from_millis(100)); + match unsafe { + Threading::WaitForSingleObject(event.0, slice.as_millis().min(u32::MAX as u128) as u32) + } { + Foundation::WAIT_OBJECT_0 => {} + Foundation::WAIT_ABANDONED | Foundation::WAIT_FAILED => { + log::error!("Wait failed!"); + break Err(crate::DeviceError::Lost); + } + Foundation::WAIT_TIMEOUT if slice < remaining_wait_duration => {} + Foundation::WAIT_TIMEOUT => { + log::trace!("Wait timed out!"); + break Ok(false); + } + other => { + log::error!("Unexpected wait status: 0x{other:?}"); + break Err(crate::DeviceError::Lost); + } + }; + + fence_value = match self.reached(fence) { + Some(value) => value, + None => break Ok(false), + }; + log::trace!("Wait complete! Fence actual value: {fence_value}"); + + if fence_value >= value { + break Ok(true); + } + } + } + + unsafe fn start_graphics_debugger_capture(&self) -> bool { + #[cfg(feature = "renderdoc")] + { + unsafe { + self.render_doc + .start_frame_capture(self.raw.as_raw(), ptr::null_mut()) + } + } + #[cfg(not(feature = "renderdoc"))] + false + } + + unsafe fn stop_graphics_debugger_capture(&self) { + #[cfg(feature = "renderdoc")] + unsafe { + self.render_doc + .end_frame_capture(self.raw.as_raw(), ptr::null_mut()) + } + } + + unsafe fn get_acceleration_structure_build_sizes<'a>( + &self, + desc: &crate::GetAccelerationStructureBuildSizesDescriptor<'a, super::Buffer>, + ) -> crate::AccelerationStructureBuildSizes { + let mut geometry_desc; + let device5 = self.raw.cast::<Direct3D12::ID3D12Device5>().unwrap(); + let ty; + let inputs0; + let num_desc; + match desc.entries { + AccelerationStructureEntries::Instances(instances) => { + ty = Direct3D12::D3D12_RAYTRACING_ACCELERATION_STRUCTURE_TYPE_TOP_LEVEL; + inputs0 = Direct3D12::D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_INPUTS_0 { + InstanceDescs: 0, + }; + num_desc = instances.count; + } + AccelerationStructureEntries::Triangles(triangles) => { + geometry_desc = Vec::with_capacity(triangles.len()); + for triangle in triangles { + let index_format = triangle + .indices + .as_ref() + .map_or(Dxgi::Common::DXGI_FORMAT_UNKNOWN, |indices| { + auxil::dxgi::conv::map_index_format(indices.format) + }); + let index_count = triangle.indices.as_ref().map_or(0, |indices| indices.count); + + let triangle_desc = Direct3D12::D3D12_RAYTRACING_GEOMETRY_TRIANGLES_DESC { + // https://learn.microsoft.com/en-us/windows/win32/api/d3d12/nf-d3d12-id3d12device5-getraytracingaccelerationstructureprebuildinfo + // It may not inspect/dereference any GPU virtual addresses, other than + // to check to see if a pointer is NULL or not, such as the optional + // transform in D3D12_RAYTRACING_GEOMETRY_TRIANGLES_DESC, without + // dereferencing it. + // + // This suggests we could pass a non-zero invalid address here if fetching the + // real address has significant overhead, but we pass the real one to be on the + // safe side for now. + Transform3x4: if desc + .flags + .contains(wgt::AccelerationStructureFlags::USE_TRANSFORM) + { + unsafe { + triangle + .transform + .as_ref() + .unwrap() + .buffer + .resource + .GetGPUVirtualAddress() + } + } else { + 0 + }, + IndexFormat: index_format, + VertexFormat: auxil::dxgi::conv::map_vertex_format(triangle.vertex_format), + IndexCount: index_count, + VertexCount: triangle.vertex_count, + IndexBuffer: 0, + VertexBuffer: Direct3D12::D3D12_GPU_VIRTUAL_ADDRESS_AND_STRIDE { + StartAddress: 0, + StrideInBytes: triangle.vertex_stride, + }, + }; + + geometry_desc.push(Direct3D12::D3D12_RAYTRACING_GEOMETRY_DESC { + Type: Direct3D12::D3D12_RAYTRACING_GEOMETRY_TYPE_TRIANGLES, + Flags: conv::map_acceleration_structure_geometry_flags(triangle.flags), + Anonymous: Direct3D12::D3D12_RAYTRACING_GEOMETRY_DESC_0 { + Triangles: triangle_desc, + }, + }) + } + ty = Direct3D12::D3D12_RAYTRACING_ACCELERATION_STRUCTURE_TYPE_BOTTOM_LEVEL; + inputs0 = Direct3D12::D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_INPUTS_0 { + pGeometryDescs: geometry_desc.as_ptr(), + }; + num_desc = geometry_desc.len() as u32; + } + AccelerationStructureEntries::AABBs(aabbs) => { + geometry_desc = Vec::with_capacity(aabbs.len()); + for aabb in aabbs { + let aabb_desc = Direct3D12::D3D12_RAYTRACING_GEOMETRY_AABBS_DESC { + AABBCount: aabb.count as u64, + AABBs: Direct3D12::D3D12_GPU_VIRTUAL_ADDRESS_AND_STRIDE { + StartAddress: 0, + StrideInBytes: aabb.stride, + }, + }; + geometry_desc.push(Direct3D12::D3D12_RAYTRACING_GEOMETRY_DESC { + Type: Direct3D12::D3D12_RAYTRACING_GEOMETRY_TYPE_PROCEDURAL_PRIMITIVE_AABBS, + Flags: conv::map_acceleration_structure_geometry_flags(aabb.flags), + Anonymous: Direct3D12::D3D12_RAYTRACING_GEOMETRY_DESC_0 { + AABBs: aabb_desc, + }, + }) + } + ty = Direct3D12::D3D12_RAYTRACING_ACCELERATION_STRUCTURE_TYPE_BOTTOM_LEVEL; + inputs0 = Direct3D12::D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_INPUTS_0 { + pGeometryDescs: geometry_desc.as_ptr(), + }; + num_desc = geometry_desc.len() as u32; + } + }; + let acceleration_structure_inputs = + Direct3D12::D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_INPUTS { + Type: ty, + Flags: conv::map_acceleration_structure_build_flags(desc.flags, None), + NumDescs: num_desc, + DescsLayout: Direct3D12::D3D12_ELEMENTS_LAYOUT_ARRAY, + Anonymous: inputs0, + }; + let mut info = Direct3D12::D3D12_RAYTRACING_ACCELERATION_STRUCTURE_PREBUILD_INFO::default(); + unsafe { + device5.GetRaytracingAccelerationStructurePrebuildInfo( + &acceleration_structure_inputs, + &mut info, + ) + }; + crate::AccelerationStructureBuildSizes { + acceleration_structure_size: info.ResultDataMaxSizeInBytes, + update_scratch_size: info.UpdateScratchDataSizeInBytes, + build_scratch_size: info.ScratchDataSizeInBytes, + } + } + + unsafe fn get_acceleration_structure_device_address( + &self, + acceleration_structure: &super::AccelerationStructure, + ) -> wgt::BufferAddress { + unsafe { acceleration_structure.resource.GetGPUVirtualAddress() } + } + + unsafe fn create_acceleration_structure( + &self, + desc: &crate::AccelerationStructureDescriptor, + ) -> Result<super::AccelerationStructure, crate::DeviceError> { + // Create a D3D12 resource as per-usual. + let size = desc.size; + + let raw_desc = Direct3D12::D3D12_RESOURCE_DESC { + Dimension: Direct3D12::D3D12_RESOURCE_DIMENSION_BUFFER, + Alignment: 0, + Width: size, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + Format: Dxgi::Common::DXGI_FORMAT_UNKNOWN, + SampleDesc: Dxgi::Common::DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, + Layout: Direct3D12::D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + // TODO: when moving to enhanced barriers use Direct3D12::D3D12_RESOURCE_FLAG_RAYTRACING_ACCELERATION_STRUCTURE + Flags: Direct3D12::D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, + }; + + let (resource, allocation) = suballocation::DeviceAllocationContext::from(self) + .create_acceleration_structure(desc, raw_desc)?; + + // for some reason there is no counter for acceleration structures + + Ok(super::AccelerationStructure { + resource, + allocation, + }) + } + + unsafe fn destroy_acceleration_structure( + &self, + acceleration_structure: super::AccelerationStructure, + ) { + suballocation::DeviceAllocationContext::from(self).free_resource( + acceleration_structure.resource, + acceleration_structure.allocation, + ); + } + + fn get_internal_counters(&self) -> wgt::HalCounters { + self.counters.as_ref().clone() + } + + fn generate_allocator_report(&self) -> Option<wgt::AllocatorReport> { + Some(self.mem_allocator.generate_report()) + } + + fn tlas_instance_to_bytes(&self, instance: TlasInstance) -> Vec<u8> { + const MAX_U24: u32 = (1u32 << 24u32) - 1u32; + let temp = Direct3D12::D3D12_RAYTRACING_INSTANCE_DESC { + Transform: instance.transform, + _bitfield1: (instance.custom_data & MAX_U24) | (u32::from(instance.mask) << 24), + _bitfield2: (instance.pipeline_intersection_data_offset & MAX_U24), + AccelerationStructure: instance.blas_address, + }; + + wgt::bytemuck_wrapper!(unsafe struct Desc(Direct3D12::D3D12_RAYTRACING_INSTANCE_DESC)); + + bytemuck::bytes_of(&Desc::wrap(temp)).to_vec() + } + + fn check_if_oom(&self) -> Result<(), crate::DeviceError> { + let Some(threshold) = self.mem_allocator.memory_budget_thresholds.for_device_loss else { + return Ok(()); + }; + + let info = self + .shared + .adapter + .query_video_memory_info(Dxgi::DXGI_MEMORY_SEGMENT_GROUP_LOCAL)?; + + if info.CurrentUsage >= info.Budget / 100 * threshold as u64 { + return Err(crate::DeviceError::OutOfMemory); + } + + if matches!( + self.shared.private_caps.memory_architecture, + super::MemoryArchitecture::NonUnified + ) { + let info = self + .shared + .adapter + .query_video_memory_info(Dxgi::DXGI_MEMORY_SEGMENT_GROUP_NON_LOCAL)?; + + if info.CurrentUsage >= info.Budget / 100 * threshold as u64 { + return Err(crate::DeviceError::OutOfMemory); + } + } + + Ok(()) + } +} diff --git a/app/vendor/rune/vendor/wgpu-hal/src/dx12/device_creation.rs b/app/vendor/rune/vendor/wgpu-hal/src/dx12/device_creation.rs new file mode 100644 index 0000000..dc5cdf9 --- /dev/null +++ b/app/vendor/rune/vendor/wgpu-hal/src/dx12/device_creation.rs @@ -0,0 +1,176 @@ +use alloc::sync::Arc; +use core::ops::Deref; + +use windows::core::Interface as _; +use windows::Win32::Graphics::{Direct3D, Direct3D12}; + +use super::D3D12Lib; +use crate::auxil::dxgi::factory::DxgiAdapter; + +/// Abstraction over D3D12 device creation. +/// +/// Supports two paths: +/// - **Independent**: Uses `ID3D12DeviceFactory` from the Agility SDK's Independent Devices API. +/// - **Legacy**: Uses the traditional `D3D12CreateDevice` export. +pub(super) enum DeviceFactory { + /// Uses `ID3D12DeviceFactory` from the Independent Devices API. + Independent(Direct3D12::ID3D12DeviceFactory), + /// Uses the traditional `D3D12CreateDevice` export. + Legacy, +} + +impl DeviceFactory { + /// Create a new `DeviceFactory`. + /// + /// If `agility_sdk` is `Some`, attempts to set up the Independent Devices API path. + /// On failure, the behavior depends on + /// [`on_load_failure`](wgt::Dx12AgilitySDKLoadFailure): + /// - [`Fallback`](wgt::Dx12AgilitySDKLoadFailure::Fallback): logs a warning and + /// returns `Ok(Legacy)`. + /// - [`Error`](wgt::Dx12AgilitySDKLoadFailure::Error): returns an `Err`. + pub(super) fn new( + lib: &D3D12Lib, + agility_sdk: Option<&wgt::Dx12AgilitySDK>, + ) -> Result<Self, crate::InstanceError> { + let Some(agility_sdk) = agility_sdk else { + log::debug!("No D3D12 Agility SDK configuration provided; using system D3D12 runtime"); + return Ok(Self::Legacy); + }; + + match Self::try_create_independent(lib, agility_sdk) { + Ok(factory) => { + log::debug!( + "Using D3D12 Agility SDK v{} from '{}'", + agility_sdk.sdk_version, + agility_sdk.sdk_path + ); + Ok(Self::Independent(factory)) + } + Err(err) => { + let message = format!( + "Failed to initialize D3D12 Agility SDK (v{} at '{}'): {err}", + agility_sdk.sdk_version, agility_sdk.sdk_path + ); + + match agility_sdk.on_load_failure { + wgt::Dx12AgilitySDKLoadFailure::Fallback => { + log::warn!("{message}; falling back to system D3D12 runtime"); + Ok(Self::Legacy) + } + wgt::Dx12AgilitySDKLoadFailure::Error => { + Err(crate::InstanceError::new(message)) + } + } + } + } + } + + fn try_create_independent( + lib: &D3D12Lib, + agility_sdk: &wgt::Dx12AgilitySDK, + ) -> Result<Direct3D12::ID3D12DeviceFactory, DeviceFactoryError> { + // Step 1: Get ID3D12SDKConfiguration1 via D3D12GetInterface + let sdk_config: Direct3D12::ID3D12SDKConfiguration1 = lib + .get_interface(&Direct3D12::CLSID_D3D12SDKConfiguration) + .map_err(DeviceFactoryError::GetInterface)?; + + // Step 2: Create device factory with the specified SDK version and path + let sdk_path = std::ffi::CString::new(agility_sdk.sdk_path.as_bytes()) + .map_err(|_| DeviceFactoryError::InvalidPath)?; + let factory: Direct3D12::ID3D12DeviceFactory = unsafe { + sdk_config.CreateDeviceFactory( + agility_sdk.sdk_version, + windows::core::PCSTR(sdk_path.as_ptr().cast::<u8>()), + ) + } + .map_err(DeviceFactoryError::CreateDeviceFactory)?; + + Ok(factory) + } + + /// Enable the D3D12 debug layer and optionally GPU-based validation. + /// + /// - **Legacy**: configures debug globally via `D3D12GetDebugInterface`. + /// - **Independent**: uses `GetConfigurationInterface` to get an + /// `ID3D12Debug` scoped to the factory. + pub(super) fn enable_debug_layer(&self, lib: &D3D12Lib, flags: wgt::InstanceFlags) { + if !flags + .intersects(wgt::InstanceFlags::VALIDATION | wgt::InstanceFlags::GPU_BASED_VALIDATION) + { + return; + } + + let debug_controller = match self { + Self::Independent(factory) => { + match unsafe { + factory.GetConfigurationInterface::<Direct3D12::ID3D12Debug>( + &Direct3D12::CLSID_D3D12Debug, + ) + } { + Ok(debug) => debug, + Err(err) => { + log::warn!("Failed to get debug interface from device factory: {err}"); + return; + } + } + } + Self::Legacy => match lib.debug_interface() { + Ok(Some(debug)) => debug, + Ok(None) => return, + Err(err) => { + log::warn!("Failed to get debug interface: {err}"); + return; + } + }, + }; + + if flags.intersects(wgt::InstanceFlags::VALIDATION) { + unsafe { debug_controller.EnableDebugLayer() } + } + if flags.intersects(wgt::InstanceFlags::GPU_BASED_VALIDATION) { + if let Ok(debug1) = debug_controller.cast::<Direct3D12::ID3D12Debug1>() { + unsafe { debug1.SetEnableGPUBasedValidation(true) } + } else { + log::warn!("Failed to enable GPU-based validation"); + } + } + } + + /// Create a D3D12 device using the appropriate method. + pub(super) fn create_device( + &self, + lib: &Arc<D3D12Lib>, + adapter: &DxgiAdapter, + feature_level: Direct3D::D3D_FEATURE_LEVEL, + ) -> Result<Direct3D12::ID3D12Device, super::CreateDeviceError> { + match self { + Self::Independent(factory) => { + let mut result__: Option<Direct3D12::ID3D12Device> = None; + unsafe { factory.CreateDevice(adapter.deref(), feature_level, &mut result__) } + .map_err(|e| super::CreateDeviceError::D3D12CreateDevice(e.into()))?; + + result__.ok_or(super::CreateDeviceError::RetDeviceIsNull) + } + Self::Legacy => lib.create_device(adapter, feature_level), + } + } +} + +impl core::fmt::Debug for DeviceFactory { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + match self { + Self::Independent(_) => write!(f, "DeviceFactory::Independent"), + Self::Legacy => write!(f, "DeviceFactory::Legacy"), + } + } +} + +#[derive(Debug, thiserror::Error)] +enum DeviceFactoryError { + #[error("failed to get ID3D12SDKConfiguration1: {0}")] + GetInterface(super::GetInterfaceError), + #[error("SDK path contains null bytes")] + InvalidPath, + #[error("CreateDeviceFactory failed: {0}")] + CreateDeviceFactory(windows::core::Error), +} diff --git a/app/vendor/rune/vendor/wgpu-hal/src/dx12/instance.rs b/app/vendor/rune/vendor/wgpu-hal/src/dx12/instance.rs new file mode 100644 index 0000000..5f64a80 --- /dev/null +++ b/app/vendor/rune/vendor/wgpu-hal/src/dx12/instance.rs @@ -0,0 +1,223 @@ +use alloc::{string::String, sync::Arc, vec::Vec}; + +use parking_lot::RwLock; +use windows::Win32::{Foundation, Graphics::Dxgi}; + +use super::SurfaceTarget; +use crate::{ + auxil, + dx12::{ + device_creation::DeviceFactory, shader_compilation::CompilerContainer, D3D12Lib, DCompLib, + }, +}; + +impl crate::Instance for super::Instance { + type A = super::Api; + + unsafe fn init(desc: &crate::InstanceDescriptor<'_>) -> Result<Self, crate::InstanceError> { + profiling::scope!("Init DX12 Backend"); + let lib_main = D3D12Lib::new().map_err(|e| { + crate::InstanceError::with_source(String::from("failed to load d3d12.dll"), e) + })?; + + // Create DeviceFactory first so we know which debug path to use + let device_factory = + DeviceFactory::new(&lib_main, desc.backend_options.dx12.agility_sdk.as_ref())?; + + device_factory.enable_debug_layer(&lib_main, desc.flags); + + let (lib_dxgi, factory) = auxil::dxgi::factory::create_factory(desc.flags)?; + + // Create IDXGIFactoryMedia + let factory_media = lib_dxgi.create_factory_media().ok(); + + let mut supports_allow_tearing = false; + if let Some(factory5) = factory.as_factory5() { + let mut allow_tearing = Foundation::FALSE; + let hr = unsafe { + factory5.CheckFeatureSupport( + Dxgi::DXGI_FEATURE_PRESENT_ALLOW_TEARING, + <*mut _>::cast(&mut allow_tearing), + size_of_val(&allow_tearing) as u32, + ) + }; + + match hr { + Err(err) => log::warn!("Unable to check for tearing support: {err}"), + Ok(()) => supports_allow_tearing = true, + } + } + + // Initialize the shader compiler + let compiler_container = match desc.backend_options.dx12.shader_compiler.clone() { + wgt::Dx12Compiler::DynamicDxc { dxc_path } => { + CompilerContainer::new_dynamic_dxc(dxc_path.into()).map_err(|e| { + crate::InstanceError::with_source(String::from("Failed to load dynamic DXC"), e) + })? + } + wgt::Dx12Compiler::StaticDxc => CompilerContainer::new_static_dxc().map_err(|e| { + crate::InstanceError::with_source(String::from("Failed to load static DXC"), e) + })?, + wgt::Dx12Compiler::Fxc => CompilerContainer::new_fxc().map_err(|e| { + crate::InstanceError::with_source(String::from("Failed to load FXC"), e) + })?, + wgt::Dx12Compiler::Auto => { + if cfg!(static_dxc) { + // Prefer static DXC if its compiled in + CompilerContainer::new_static_dxc().map_err(|e| { + crate::InstanceError::with_source( + String::from("Failed to load static DXC"), + e, + ) + })? + } else { + // Try to load dynamic DXC + let dynamic = CompilerContainer::new_dynamic_dxc("dxcompiler.dll".into()); + match dynamic { + Ok(v) => v, + Err(super::shader_compilation::GetContainerError::FailedToLoad(..)) => { + // If it can't be found load FXC + CompilerContainer::new_fxc().map_err(|e| { + crate::InstanceError::with_source( + String::from("Failed to load FXC"), + e, + ) + })? + } + Err(e) => { + // If another error occurs when loading static DXC return that error + return Err(crate::InstanceError::with_source( + String::from("Failed to load dynamic DXC"), + e, + )); + } + } + } + } + }; + + match compiler_container { + CompilerContainer::DynamicDxc(..) => { + log::debug!("Using dynamic DXC for shader compilation") + } + CompilerContainer::StaticDxc(..) => { + log::debug!("Using static DXC for shader compilation") + } + CompilerContainer::Fxc(..) => { + log::debug!("Using FXC for shader compilation") + } + } + + Ok(Self { + // The call to create_factory will only succeed if we get a factory4, so this is safe. + factory, + factory_media, + library: Arc::new(lib_main), + device_factory: Arc::new(device_factory), + dcomp_lib: Arc::new(DCompLib::new()), + presentation_system: desc.backend_options.dx12.presentation_system, + _lib_dxgi: lib_dxgi, + supports_allow_tearing, + flags: desc.flags, + memory_budget_thresholds: desc.memory_budget_thresholds, + compiler_container: Arc::new(compiler_container), + options: desc.backend_options.dx12.clone(), + telemetry: desc.telemetry, + }) + } + + unsafe fn create_surface( + &self, + display_handle: raw_window_handle::RawDisplayHandle, + window_handle: raw_window_handle::RawWindowHandle, + ) -> Result<super::Surface, crate::InstanceError> { + assert!(matches!( + display_handle, + raw_window_handle::RawDisplayHandle::Windows(_) + )); + match window_handle { + raw_window_handle::RawWindowHandle::Win32(handle) => { + // https://github.com/rust-windowing/raw-window-handle/issues/171 + let handle = Foundation::HWND(handle.hwnd.get() as *mut _); + let target = match self.presentation_system { + wgt::Dx12SwapchainKind::DxgiFromHwnd => SurfaceTarget::WndHandle(handle), + wgt::Dx12SwapchainKind::DxgiFromVisual => SurfaceTarget::VisualFromWndHandle { + handle, + dcomp_state: Default::default(), + }, + }; + + Ok(super::Surface { + factory: self.factory.clone(), + factory_media: self.factory_media.clone(), + target, + supports_allow_tearing: self.supports_allow_tearing, + swap_chain: RwLock::new(None), + options: self.options.clone(), + hdr_source: Some(auxil::dxgi::hdr::DxgiHdrSource::new(handle)), + }) + } + _ => Err(crate::InstanceError::new(format!( + "window handle {window_handle:?} is not a Win32 handle" + ))), + } + } + + unsafe fn enumerate_adapters( + &self, + _surface_hint: Option<&super::Surface>, + ) -> Vec<crate::ExposedAdapter<super::Api>> { + let adapters = auxil::dxgi::factory::enumerate_adapters(self.factory.clone()); + + adapters + .into_iter() + .filter_map(|raw| { + super::Adapter::expose( + raw, + &self.library, + &self.device_factory, + &self.dcomp_lib, + self.flags, + self.memory_budget_thresholds, + self.compiler_container.clone(), + self.options.clone(), + self.telemetry, + ) + }) + .collect() + } +} + +impl super::Instance { + /// Exposes one adapter the caller found through DXGI, as `enumerate_adapters` exposes each + /// one it lists, without creating a device on any other adapter or loading another adapter's + /// driver. `None` when the adapter is one `enumerate_adapters` skips or can't run D3D12. + /// + /// # Safety + /// + /// `adapter` must come from a DXGI factory in this process. + pub unsafe fn expose_adapter( + &self, + adapter: &Dxgi::IDXGIAdapter1, + ) -> Option<crate::ExposedAdapter<super::Api>> { + use windows::core::Interface as _; + if !auxil::dxgi::factory::should_keep_adapter(adapter) { + return None; + } + let raw = match adapter.cast::<Dxgi::IDXGIAdapter4>() { + Ok(adapter4) => auxil::dxgi::factory::DxgiAdapter::Adapter4(adapter4), + Err(_) => auxil::dxgi::factory::DxgiAdapter::Adapter3(adapter.cast().ok()?), + }; + super::Adapter::expose( + raw, + &self.library, + &self.device_factory, + &self.dcomp_lib, + self.flags, + self.memory_budget_thresholds, + self.compiler_container.clone(), + self.options.clone(), + self.telemetry, + ) + } +} diff --git a/app/vendor/rune/vendor/wgpu-hal/src/dx12/mod.rs b/app/vendor/rune/vendor/wgpu-hal/src/dx12/mod.rs new file mode 100644 index 0000000..2fb4210 --- /dev/null +++ b/app/vendor/rune/vendor/wgpu-hal/src/dx12/mod.rs @@ -0,0 +1,2310 @@ +/*! +# DirectX12 API internals. + +Generally the mapping is straightforward. + +## Resource transitions + +D3D12 API matches WebGPU internal states very well. The only +caveat here is issuing a special UAV barrier whenever both source +and destination states match, and they are for storage sync. + +## Memory + +For now, all resources are created with "committed" memory. + +## Sampler Descriptor Management + +At most one descriptor heap of each type can be bound at once. This +means that the descriptors from all bind groups need to be present +in the same heap, and they need to be contiguous within that heap. +This is not a problem for the SRV/CBV/UAV heap as it can be sized into +the millions of entries. However the sampler heap is limited to 2048 entries. + +In order to work around this limitation, we refer to samplers indirectly by index. +The entire sampler heap is bound at once and a buffer containing all sampler indexes +for that bind group is bound. The shader then uses the index to look up the sampler +in the heap. To help visualize this, the generated HLSL looks like this: + +```wgsl +@group(0) @binding(2) var myLinearSampler: sampler; +@group(1) @binding(1) var myAnisoSampler: sampler; +@group(1) @binding(4) var myCompSampler: sampler; +``` + +```cpp +// These bindings alias the same descriptors. Depending on the type, the shader will use the correct one. +SamplerState nagaSamplerHeap[2048]: register(s0, space0); +SamplerComparisonState nagaComparisonSamplerHeap[2048]: register(s2048, space1); + +StructuredBuffer<uint> nagaGroup0SamplerIndexArray : register(t0, space0); +StructuredBuffer<uint> nagaGroup1SamplerIndexArray : register(t1, space0); + +// Indexes into group 0 index array +static const SamplerState myLinearSampler = nagaSamplerHeap[nagaGroup0SamplerIndexArray[0]]; + +// Indexes into group 1 index array +static const SamplerState myAnisoSampler = nagaSamplerHeap[nagaGroup1SamplerIndexArray[0]]; +static const SamplerComparisonState myCompSampler = nagaComparisonSamplerHeap[nagaGroup1SamplerIndexArray[1]]; +``` + +Without this transform we would need separate set of sampler descriptors for each unique combination of samplers +in a bind group. This results in a lot of duplication and makes it easy to hit the 2048 limit. With the transform +the limit is merely 2048 unique samplers in existence, which is much more reasonable. + +## Resource binding + +See [`crate::Device::create_pipeline_layout`] documentation for the structure +of the root signature corresponding to WebGPU pipeline layout. + +Binding groups is mostly straightforward, with one big caveat: +all bindings have to be reset whenever the root signature changes. +This is the rule of D3D12, and we can do nothing to help it. + +We detect this change at both [`crate::CommandEncoder::set_bind_group`] +and [`crate::CommandEncoder::set_render_pipeline`] with +[`crate::CommandEncoder::set_compute_pipeline`]. + +For this reason, in order avoid repeating the binding code, +we are binding everything in `CommandEncoder::update_root_elements`. +When the pipeline layout is changed, we reset all bindings. +Otherwise, we pass a range corresponding only to the current bind group. + +!*/ + +#![expect( + missing_debug_implementations, + reason = "TODO: someone developing on Windows add Debug impls where possible" +)] + +mod adapter; +mod command; +mod conv; +mod dcomp; +mod descriptor; +mod device; +mod device_creation; +mod instance; +mod pipeline_desc; +mod sampler; +mod shader_compilation; +mod suballocation; +mod types; +mod view; + +use alloc::{borrow::ToOwned as _, collections::VecDeque, string::String, sync::Arc, vec::Vec}; +use core::{ffi, fmt, mem, ops::Deref, sync::atomic::AtomicU64}; + +use arrayvec::ArrayVec; +use hashbrown::HashMap; +use parking_lot::{Mutex, RwLock}; +use suballocation::Allocator; +use windows::{ + core::{Free as _, Interface}, + Win32::{ + Foundation, + Graphics::{ + Direct3D, + Direct3D12::{self, D3D12_TEXTURE_DATA_PLACEMENT_ALIGNMENT}, + DirectComposition, Dxgi, + }, + System::Threading, + }, +}; + +use self::dcomp::DCompLib; +use crate::auxil::{ + self, + dxgi::{ + factory::{DxgiAdapter, DxgiFactory}, + result::HResult, + }, +}; + +#[derive(Debug)] +struct DynLib { + inner: libloading::Library, +} + +impl DynLib { + unsafe fn new<P>(filename: P) -> Result<Self, libloading::Error> + where + P: AsRef<std::ffi::OsStr>, + { + unsafe { libloading::Library::new(filename) }.map(|inner| Self { inner }) + } + + // Rune: load Windows system DLLs from System32 only, not the app directory or CWD. + unsafe fn new_system<P>(filename: P) -> Result<Self, libloading::Error> + where + P: AsRef<std::ffi::OsStr>, + { + unsafe { + libloading::os::windows::Library::load_with_flags( + filename, + libloading::os::windows::LOAD_LIBRARY_SEARCH_SYSTEM32, + ) + } + .map(|inner| Self { + inner: inner.into(), + }) + } + + unsafe fn get<T>( + &self, + symbol: &[u8], + ) -> Result<libloading::Symbol<'_, T>, crate::DeviceError> { + unsafe { self.inner.get(symbol) }.map_err(|e| match e { + libloading::Error::GetProcAddress { .. } | libloading::Error::GetProcAddressUnknown => { + crate::DeviceError::Unexpected + } + libloading::Error::IncompatibleSize + | libloading::Error::CreateCString { .. } + | libloading::Error::CreateCStringWithTrailing { .. } => crate::hal_internal_error(e), + _ => crate::DeviceError::Unexpected, // could be unreachable!() but we prefer to be more robust + }) + } +} + +#[derive(Debug)] +struct D3D12Lib { + lib: DynLib, +} + +#[derive(Clone, Copy, Debug)] +pub enum CreateDeviceError { + GetProcAddress, + D3D12CreateDevice(windows_core::HRESULT), + RetDeviceIsNull, +} + +impl D3D12Lib { + fn new() -> Result<Self, libloading::Error> { + unsafe { DynLib::new_system("d3d12.dll").map(|lib| Self { lib }) } + } + + fn create_device( + &self, + adapter: &DxgiAdapter, + feature_level: Direct3D::D3D_FEATURE_LEVEL, + ) -> Result<Direct3D12::ID3D12Device, CreateDeviceError> { + // Calls windows::Win32::Graphics::Direct3D12::D3D12CreateDevice on d3d12.dll + type Fun = extern "system" fn( + padapter: *mut ffi::c_void, + minimumfeaturelevel: Direct3D::D3D_FEATURE_LEVEL, + riid: *const windows_core::GUID, + ppdevice: *mut *mut ffi::c_void, + ) -> windows_core::HRESULT; + let func: libloading::Symbol<Fun> = + unsafe { self.lib.get(c"D3D12CreateDevice".to_bytes()) } + .map_err(|_| CreateDeviceError::GetProcAddress)?; + + let mut result__: Option<Direct3D12::ID3D12Device> = None; + + let res = (func)( + adapter.as_raw(), + feature_level, + // TODO: Generic? + &Direct3D12::ID3D12Device::IID, + <*mut _>::cast(&mut result__), + ); + + if res.is_err() { + return Err(CreateDeviceError::D3D12CreateDevice(res)); + } + + result__.ok_or(CreateDeviceError::RetDeviceIsNull) + } + + fn serialize_root_signature( + &self, + version: Direct3D12::D3D_ROOT_SIGNATURE_VERSION, + parameters: &[Direct3D12::D3D12_ROOT_PARAMETER], + static_samplers: &[Direct3D12::D3D12_STATIC_SAMPLER_DESC], + flags: Direct3D12::D3D12_ROOT_SIGNATURE_FLAGS, + ) -> Result<D3DBlob, crate::DeviceError> { + // Calls windows::Win32::Graphics::Direct3D12::D3D12SerializeRootSignature on d3d12.dll + type Fun = extern "system" fn( + prootsignature: *const Direct3D12::D3D12_ROOT_SIGNATURE_DESC, + version: Direct3D12::D3D_ROOT_SIGNATURE_VERSION, + ppblob: *mut *mut ffi::c_void, + pperrorblob: *mut *mut ffi::c_void, + ) -> windows_core::HRESULT; + let func: libloading::Symbol<Fun> = + unsafe { self.lib.get(c"D3D12SerializeRootSignature".to_bytes()) }?; + + let desc = Direct3D12::D3D12_ROOT_SIGNATURE_DESC { + NumParameters: parameters.len() as _, + pParameters: parameters.as_ptr(), + NumStaticSamplers: static_samplers.len() as _, + pStaticSamplers: static_samplers.as_ptr(), + Flags: flags, + }; + + let mut blob = None; + let mut error = None::<Direct3D::ID3DBlob>; + (func)( + &desc, + version, + <*mut _>::cast(&mut blob), + <*mut _>::cast(&mut error), + ) + .ok() + .into_device_result("Root signature serialization")?; + + if let Some(error) = error { + let error = D3DBlob(error); + log::error!( + "Root signature serialization error: {:?}", + unsafe { error.as_c_str() }.unwrap().to_str().unwrap() + ); + return Err(crate::DeviceError::Unexpected); // could be hal_usage_error or hal_internal_error + } + + blob.ok_or(crate::DeviceError::Unexpected) + } + + fn debug_interface(&self) -> Result<Option<Direct3D12::ID3D12Debug>, crate::DeviceError> { + // Calls windows::Win32::Graphics::Direct3D12::D3D12GetDebugInterface on d3d12.dll + type Fun = extern "system" fn( + riid: *const windows_core::GUID, + ppvdebug: *mut *mut ffi::c_void, + ) -> windows_core::HRESULT; + let func: libloading::Symbol<Fun> = + unsafe { self.lib.get(c"D3D12GetDebugInterface".to_bytes()) }?; + + let mut result__ = None; + + let res = (func)(&Direct3D12::ID3D12Debug::IID, <*mut _>::cast(&mut result__)).ok(); + + if let Err(ref err) = res { + match err.code() { + Dxgi::DXGI_ERROR_SDK_COMPONENT_MISSING => return Ok(None), + _ => {} + } + } + + res.into_device_result("GetDebugInterface")?; + + result__.ok_or(crate::DeviceError::Unexpected).map(Some) + } + + /// Calls D3D12GetInterface to obtain a COM interface by CLSID and IID. + /// + /// This is used by the Independent Devices API to obtain `ID3D12SDKConfiguration1`. + fn get_interface<T: Interface>( + &self, + clsid: &windows_core::GUID, + ) -> Result<T, GetInterfaceError> { + // Calls windows::Win32::Graphics::Direct3D12::D3D12GetInterface on d3d12.dll + type Fun = extern "system" fn( + rclsid: *const windows_core::GUID, + riid: *const windows_core::GUID, + ppvdebug: *mut *mut ffi::c_void, + ) -> windows_core::HRESULT; + let func: libloading::Symbol<Fun> = + unsafe { self.lib.get(c"D3D12GetInterface".to_bytes()) } + .map_err(|_| GetInterfaceError::GetProcAddress)?; + + let mut result__: Option<T> = None; + + let res = (func)(clsid, &T::IID, <*mut _>::cast(&mut result__)); + + if res.is_err() { + return Err(GetInterfaceError::D3D12GetInterface(res)); + } + + result__.ok_or(GetInterfaceError::RetIsNull) + } +} + +#[derive(Clone, Copy, Debug)] +pub(super) enum GetInterfaceError { + GetProcAddress, + D3D12GetInterface(windows_core::HRESULT), + RetIsNull, +} + +impl fmt::Display for GetInterfaceError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::GetProcAddress => write!(f, "D3D12GetInterface not found in d3d12.dll"), + Self::D3D12GetInterface(hr) => write!(f, "D3D12GetInterface failed: {hr}"), + Self::RetIsNull => write!(f, "D3D12GetInterface returned null"), + } + } +} + +impl core::error::Error for GetInterfaceError {} + +#[derive(Debug)] +pub(super) struct DxgiLib { + lib: DynLib, +} + +impl DxgiLib { + pub fn new() -> Result<Self, libloading::Error> { + unsafe { DynLib::new_system("dxgi.dll").map(|lib| Self { lib }) } + } + + /// Will error with crate::DeviceError::Unexpected if DXGI 1.3 is not available. + pub fn debug_interface1(&self) -> Result<Option<Dxgi::IDXGIInfoQueue>, crate::DeviceError> { + // Calls windows::Win32::Graphics::Dxgi::DXGIGetDebugInterface1 on dxgi.dll + type Fun = extern "system" fn( + flags: u32, + riid: *const windows_core::GUID, + pdebug: *mut *mut ffi::c_void, + ) -> windows_core::HRESULT; + let func: libloading::Symbol<Fun> = + unsafe { self.lib.get(c"DXGIGetDebugInterface1".to_bytes()) }?; + + let mut result__ = None; + + let res = (func)(0, &Dxgi::IDXGIInfoQueue::IID, <*mut _>::cast(&mut result__)).ok(); + + if let Err(ref err) = res { + match err.code() { + Dxgi::DXGI_ERROR_SDK_COMPONENT_MISSING => return Ok(None), + _ => {} + } + } + + res.into_device_result("debug_interface1")?; + + result__.ok_or(crate::DeviceError::Unexpected).map(Some) + } + + /// Will error with crate::DeviceError::Unexpected if DXGI 1.4 is not available. + pub fn create_factory4( + &self, + factory_flags: Dxgi::DXGI_CREATE_FACTORY_FLAGS, + ) -> Result<Dxgi::IDXGIFactory4, crate::DeviceError> { + // Calls windows::Win32::Graphics::Dxgi::CreateDXGIFactory2 on dxgi.dll + type Fun = extern "system" fn( + flags: Dxgi::DXGI_CREATE_FACTORY_FLAGS, + riid: *const windows_core::GUID, + ppfactory: *mut *mut ffi::c_void, + ) -> windows_core::HRESULT; + let func: libloading::Symbol<Fun> = + unsafe { self.lib.get(c"CreateDXGIFactory2".to_bytes()) }?; + + let mut result__ = None; + + (func)( + factory_flags, + &Dxgi::IDXGIFactory4::IID, + <*mut _>::cast(&mut result__), + ) + .ok() + .into_device_result("create_factory4")?; + + result__.ok_or(crate::DeviceError::Unexpected) + } + + /// Will error with crate::DeviceError::Unexpected if DXGI 1.3 is not available. + pub fn create_factory_media(&self) -> Result<Dxgi::IDXGIFactoryMedia, crate::DeviceError> { + // Calls windows::Win32::Graphics::Dxgi::CreateDXGIFactory1 on dxgi.dll + type Fun = extern "system" fn( + riid: *const windows_core::GUID, + ppfactory: *mut *mut ffi::c_void, + ) -> windows_core::HRESULT; + let func: libloading::Symbol<Fun> = + unsafe { self.lib.get(c"CreateDXGIFactory1".to_bytes()) }?; + + let mut result__ = None; + + // https://learn.microsoft.com/en-us/windows/win32/api/dxgi1_3/nn-dxgi1_3-idxgifactorymedia + (func)(&Dxgi::IDXGIFactoryMedia::IID, <*mut _>::cast(&mut result__)) + .ok() + .into_device_result("create_factory_media")?; + + result__.ok_or(crate::DeviceError::Unexpected) + } +} + +/// Create a temporary "owned" copy inside a [`mem::ManuallyDrop`] without increasing the refcount or +/// moving away the source variable. +/// +/// This is a common pattern when needing to pass interface pointers ("borrows") into Windows +/// structs. Moving/cloning ownership is impossible/inconvenient because: +/// +/// - The caller does _not_ assume ownership (and decrement the refcount at a later time); +/// - Unnecessarily increasing and decrementing the refcount; +/// - [`Drop`] destructors cannot run inside `union` structures (when the created structure is +/// implicitly dropped after a call). +/// +/// See also <https://github.com/microsoft/windows-rs/pull/2361#discussion_r1150799401> and +/// <https://github.com/microsoft/windows-rs/issues/2386>. +/// +/// # Safety +/// Performs a [`mem::transmute_copy()`] on a refcounted [`Interface`] type. The returned +/// [`mem::ManuallyDrop`] should _not_ be dropped. +pub unsafe fn borrow_interface_temporarily<I: Interface>(src: &I) -> mem::ManuallyDrop<Option<I>> { + unsafe { mem::transmute_copy(src) } +} + +/// See [`borrow_interface_temporarily()`] +pub unsafe fn borrow_optional_interface_temporarily<I: Interface>( + src: &Option<I>, +) -> mem::ManuallyDrop<Option<I>> { + unsafe { mem::transmute_copy(src) } +} + +struct D3DBlob(Direct3D::ID3DBlob); + +impl Deref for D3DBlob { + type Target = Direct3D::ID3DBlob; + + fn deref(&self) -> &Self::Target { + &self.0 + } +} + +impl D3DBlob { + unsafe fn as_slice(&self) -> &[u8] { + unsafe { core::slice::from_raw_parts(self.GetBufferPointer().cast(), self.GetBufferSize()) } + } + + unsafe fn as_c_str(&self) -> Result<&ffi::CStr, ffi::FromBytesUntilNulError> { + ffi::CStr::from_bytes_until_nul(unsafe { self.as_slice() }) + } +} + +#[derive(Clone, Debug)] +pub struct Api; + +impl crate::Api for Api { + const VARIANT: wgt::Backend = wgt::Backend::Dx12; + + type Instance = Instance; + type Surface = Surface; + type Adapter = Adapter; + type Device = Device; + + type Queue = Queue; + type CommandEncoder = CommandEncoder; + type CommandBuffer = CommandBuffer; + + type Buffer = Buffer; + type Texture = Texture; + type SurfaceTexture = Texture; + type TextureView = TextureView; + type Sampler = Sampler; + type QuerySet = QuerySet; + type Fence = Fence; + + type BindGroupLayout = BindGroupLayout; + type BindGroup = BindGroup; + type PipelineLayout = PipelineLayout; + type ShaderModule = ShaderModule; + type RenderPipeline = RenderPipeline; + type ComputePipeline = ComputePipeline; + type RayTracingPipeline = RayTracingPipeline; + type PipelineCache = PipelineCache; + + type AccelerationStructure = AccelerationStructure; +} + +crate::impl_dyn_resource!( + Adapter, + AccelerationStructure, + BindGroup, + BindGroupLayout, + Buffer, + CommandBuffer, + CommandEncoder, + ComputePipeline, + Device, + Fence, + Instance, + PipelineCache, + PipelineLayout, + QuerySet, + Queue, + RayTracingPipeline, + RenderPipeline, + Sampler, + ShaderModule, + Surface, + Texture, + TextureView +); + +// Limited by D3D12's root signature size of 64. Each element takes 1 or 2 entries. +const MAX_ROOT_ELEMENTS: usize = 64; +/// See comment in [`Adapter::expose`]. +/// You must change the math in the comment before you update this value. +const MAX_IMMEDIATE_SIZE: u32 = 128; +const MAX_IMMEDIATES: usize = MAX_IMMEDIATE_SIZE as usize / 4; +const ZERO_BUFFER_SIZE: wgt::BufferAddress = 256 << 10; + +pub struct Instance { + factory: DxgiFactory, + factory_media: Option<Dxgi::IDXGIFactoryMedia>, + // `device_factory` must be dropped before `library` because the COM + // object's Release call goes through the d3d12.dll vtable. If + // `library` (which unloads d3d12.dll) is dropped first the Release + // segfaults. + device_factory: Arc<device_creation::DeviceFactory>, + library: Arc<D3D12Lib>, + dcomp_lib: Arc<DCompLib>, + supports_allow_tearing: bool, + presentation_system: wgt::Dx12SwapchainKind, + _lib_dxgi: DxgiLib, + flags: wgt::InstanceFlags, + memory_budget_thresholds: wgt::MemoryBudgetThresholds, + compiler_container: Arc<shader_compilation::CompilerContainer>, + options: wgt::Dx12BackendOptions, + telemetry: Option<crate::Telemetry>, +} + +impl Instance { + /// Get the raw DXGI factory associated with this instance. + pub unsafe fn raw_factory4(&self) -> &Dxgi::IDXGIFactory4 { + self.factory.deref() + } + + pub unsafe fn create_surface_from_visual(&self, visual: *mut ffi::c_void) -> Surface { + let visual = unsafe { DirectComposition::IDCompositionVisual::from_raw_borrowed(&visual) } + .expect("COM pointer should not be NULL"); + Surface { + factory: self.factory.clone(), + factory_media: self.factory_media.clone(), + target: SurfaceTarget::Visual(visual.to_owned()), + supports_allow_tearing: self.supports_allow_tearing, + swap_chain: RwLock::new(None), + options: self.options.clone(), + hdr_source: None, + } + } + + pub unsafe fn create_surface_from_surface_handle( + &self, + surface_handle: *mut ffi::c_void, + ) -> Surface { + // TODO: We're not given ownership, so we shouldn't call HANDLE::free(). This puts an extra burden on the caller to keep it alive. + // https://learn.microsoft.com/en-us/windows/win32/api/handleapi/nf-handleapi-duplicatehandle could help us, even though DirectComposition is not in the list? + // Or we make all these types owned, require an ownership transition, and replace SurfaceTargetUnsafe with SurfaceTarget. + let surface_handle = Foundation::HANDLE(surface_handle); + Surface { + factory: self.factory.clone(), + factory_media: self.factory_media.clone(), + target: SurfaceTarget::SurfaceHandle(surface_handle), + supports_allow_tearing: self.supports_allow_tearing, + swap_chain: RwLock::new(None), + options: self.options.clone(), + hdr_source: None, + } + } + + pub unsafe fn create_surface_from_swap_chain_panel( + &self, + swap_chain_panel: *mut ffi::c_void, + ) -> Surface { + let swap_chain_panel = + unsafe { types::ISwapChainPanelNative::from_raw_borrowed(&swap_chain_panel) } + .expect("COM pointer should not be NULL"); + Surface { + factory: self.factory.clone(), + factory_media: self.factory_media.clone(), + target: SurfaceTarget::SwapChainPanel(swap_chain_panel.to_owned()), + supports_allow_tearing: self.supports_allow_tearing, + swap_chain: RwLock::new(None), + options: self.options.clone(), + hdr_source: None, + } + } +} + +unsafe impl Send for Instance {} +unsafe impl Sync for Instance {} + +struct SwapChain { + // TODO: Drop order frees the SWC before the raw image pointers...? + raw: Dxgi::IDXGISwapChain3, + // need to associate raw image pointers with the swapchain so they can be properly released + // when the swapchain is destroyed + resources: Vec<Direct3D12::ID3D12Resource>, + /// Handle is freed in [`Self::release_resources()`] + waitable: Option<Foundation::HANDLE>, + acquired_count: usize, + present_mode: wgt::PresentMode, + format: wgt::TextureFormat, + size: wgt::Extent3d, + /// Rune: what the next present changed (Surface::set_present_rects); empty is all of it. + dirty: Vec<Foundation::RECT>, +} + +enum SurfaceTarget { + /// Borrowed, lifetime externally managed + WndHandle(Foundation::HWND), + /// `handle` is borrowed, lifetime externally managed + VisualFromWndHandle { + handle: Foundation::HWND, + dcomp_state: Mutex<dcomp::DCompState>, + }, + Visual(DirectComposition::IDCompositionVisual), + /// Borrowed, lifetime externally managed + SurfaceHandle(Foundation::HANDLE), + SwapChainPanel(types::ISwapChainPanelNative), +} + +pub struct Surface { + factory: DxgiFactory, + factory_media: Option<Dxgi::IDXGIFactoryMedia>, + target: SurfaceTarget, + supports_allow_tearing: bool, + swap_chain: RwLock<Option<SwapChain>>, + options: wgt::Dx12BackendOptions, + /// HDR-info source for HWND-backed targets; `None` for composition / + /// SwapChainPanel / surface-handle targets, which have no monitor identity. + hdr_source: Option<auxil::dxgi::hdr::DxgiHdrSource>, +} + +unsafe impl Send for Surface {} +unsafe impl Sync for Surface {} + +impl Surface { + pub fn swap_chain(&self) -> Option<Dxgi::IDXGISwapChain3> { + Some(self.swap_chain.read().as_ref()?.raw.clone()) + } + + /// Rune: the only rectangles the next present changed, in the swap chain's pixels; the rest of + /// the buffer holds what the frame before showed. Cleared by the present. + pub fn set_present_rects(&self, rects: &[Foundation::RECT]) { + if let Some(sc) = self.swap_chain.write().as_mut() { + sc.dirty.clear(); + sc.dirty.extend_from_slice(rects); + } + } + + /// Returns the waitable handle associated with this swap chain, if any. + /// Handle is only valid while the swap chain is alive. + pub unsafe fn waitable_handle(&self) -> Option<Foundation::HANDLE> { + self.swap_chain.read().as_ref()?.waitable + } +} + +#[derive(Debug, Clone, Copy)] +enum MemoryArchitecture { + Unified { + #[allow(unused)] + cache_coherent: bool, + }, + NonUnified, +} + +#[derive(Debug, Clone, Copy)] +struct PrivateCapabilities { + instance_flags: wgt::InstanceFlags, + workarounds: Workarounds, + #[allow(unused)] + heterogeneous_resource_heaps: bool, + memory_architecture: MemoryArchitecture, + heap_create_not_zeroed: bool, + casting_fully_typed_format_supported: bool, + suballocation_supported: bool, + shader_model: naga::back::hlsl::ShaderModel, + max_sampler_descriptor_heap_size: u32, + unrestricted_buffer_texture_copy_pitch_supported: bool, +} + +impl PrivateCapabilities { + fn texture_data_placement_alignment(&self) -> u64 { + if self.unrestricted_buffer_texture_copy_pitch_supported { + 4 + } else { + D3D12_TEXTURE_DATA_PLACEMENT_ALIGNMENT.into() + } + } +} + +#[derive(Default, Debug, Copy, Clone)] +struct Workarounds { + // On WARP 1.0.13+, debug information in shaders in certain situations causes the device + // to hang. https://github.com/gfx-rs/wgpu/issues/8368 + avoid_shader_debug_info: bool, +} + +pub struct Adapter { + raw: DxgiAdapter, + device: Direct3D12::ID3D12Device, + library: Arc<D3D12Lib>, + dcomp_lib: Arc<DCompLib>, + private_caps: PrivateCapabilities, + presentation_timer: auxil::dxgi::time::PresentationTimer, + memory_budget_thresholds: wgt::MemoryBudgetThresholds, + compiler_container: Arc<shader_compilation::CompilerContainer>, + options: wgt::Dx12BackendOptions, +} + +unsafe impl Send for Adapter {} +unsafe impl Sync for Adapter {} + +impl Adapter { + pub fn as_raw(&self) -> &Dxgi::IDXGIAdapter3 { + &self.raw + } +} + +struct Event(pub Foundation::HANDLE); +impl Event { + pub fn create(manual_reset: bool, initial_state: bool) -> Result<Self, crate::DeviceError> { + Ok(Self( + unsafe { Threading::CreateEventA(None, manual_reset, initial_state, None) } + .into_device_result("CreateEventA")?, + )) + } +} + +impl Drop for Event { + fn drop(&mut self) { + unsafe { Foundation::HANDLE::free(&mut self.0) } + } +} + +/// Helper structure for waiting for GPU. +struct Idler { + fence: Direct3D12::ID3D12Fence, +} + +/// Rune: GPU-written drain markers on software adapters (WARP) so releasing a removed device +/// waits for any queued command lists its CPU worker threads are still executing. After +/// `RemoveDevice`, D3D12 sets every fence to `u64::MAX` and rejects `Queue::Signal`, so fences +/// can no longer tell when in-flight lists have finished; releasing allocators or resources +/// before then crashes on WARP (0xC0000005). +/// +/// Hardware adapters (`!DXGI_ADAPTER_FLAG_SOFTWARE`) and drivers without `WriteBufferImmediate` +/// (`DIRECT`) run with `marker: None` (zero steady-state marker cost: no buffer, no recording, no +/// submit reads/locks); on hardware a real TDR/unplug aborts the queue so markers would never +/// land anyway. Skipping `ExecuteCommandLists`, skipping `allocator.Reset()`, and sliced fence +/// waits still run on every adapter. +const DRAIN_MARKER_SLOTS: usize = 16_384; +const DRAIN_STALL_TIMEOUT: core::time::Duration = core::time::Duration::from_millis(250); +const DRAIN_TOTAL_TIMEOUT: core::time::Duration = core::time::Duration::from_millis(1_000); + +struct DrainMarker { + resource: Direct3D12::ID3D12Resource, + mapped: core::ptr::NonNull<core::sync::atomic::AtomicU32>, + gpu_va: u64, + next_tag: core::sync::atomic::AtomicU32, +} + +// SAFETY: `mapped` points to `DRAIN_MARKER_SLOTS` aligned `AtomicU32`s inside `resource`'s +// persistently mapped readback buffer and is never dereferenced after `Drop` unmaps it. +unsafe impl Send for DrainMarker {} +// SAFETY: all concurrent access to `mapped` is through atomic loads and GPU DMA writes. +unsafe impl Sync for DrainMarker {} + +impl Drop for DrainMarker { + fn drop(&mut self) { + let written = Direct3D12::D3D12_RANGE { Begin: 0, End: 0 }; + // SAFETY: subresource 0 was mapped in `DrainMarker::new`, and the CPU never writes it. + unsafe { self.resource.Unmap(0, Some(&written)) }; + } +} + +impl DrainMarker { + fn new(device: &Direct3D12::ID3D12Device) -> Option<Self> { + let mut options3 = Direct3D12::D3D12_FEATURE_DATA_D3D12_OPTIONS3::default(); + // SAFETY: `options3` matches `D3D12_FEATURE_D3D12_OPTIONS3` in type and byte size. + let supported = unsafe { + device.CheckFeatureSupport( + Direct3D12::D3D12_FEATURE_D3D12_OPTIONS3, + <*mut _>::cast(&mut options3), + size_of_val(&options3) as u32, + ) + } + .is_ok() + && (options3.WriteBufferImmediateSupportFlags.0 + & Direct3D12::D3D12_COMMAND_LIST_SUPPORT_FLAG_DIRECT.0) + != 0; + if !supported { + return None; + } + let heap = Direct3D12::D3D12_HEAP_PROPERTIES { + Type: Direct3D12::D3D12_HEAP_TYPE_READBACK, + ..Default::default() + }; + let desc = Direct3D12::D3D12_RESOURCE_DESC { + Dimension: Direct3D12::D3D12_RESOURCE_DIMENSION_BUFFER, + Alignment: 0, + Width: (DRAIN_MARKER_SLOTS * size_of::<u32>()) as u64, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + Format: Dxgi::Common::DXGI_FORMAT_UNKNOWN, + SampleDesc: Dxgi::Common::DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, + Layout: Direct3D12::D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + Flags: Direct3D12::D3D12_RESOURCE_FLAG_NONE, + }; + let mut resource = None::<Direct3D12::ID3D12Resource>; + // SAFETY: valid readback buffer descriptor permanently in `COPY_DEST`; without + // `D3D12_HEAP_FLAG_CREATE_NOT_ZEROED`, D3D12 zeroes the buffer on creation so 0 never + // matches a non-zero tag. + unsafe { + device.CreateCommittedResource( + &heap, + Direct3D12::D3D12_HEAP_FLAG_NONE, + &desc, + Direct3D12::D3D12_RESOURCE_STATE_COPY_DEST, + None, + &mut resource, + ) + } + .ok()?; + let resource = resource?; + let mut raw_ptr = core::ptr::null_mut(); + // SAFETY: readback buffer supports persistent CPU mapping on subresource 0. + unsafe { resource.Map(0, None, Some(&mut raw_ptr)) }.ok()?; + let mapped = core::ptr::NonNull::new(raw_ptr.cast::<core::sync::atomic::AtomicU32>())?; + // SAFETY: committed buffer has a valid GPU virtual address for its lifetime. + let gpu_va = unsafe { resource.GetGPUVirtualAddress() }; + Some(Self { + resource, + mapped, + gpu_va, + next_tag: core::sync::atomic::AtomicU32::new(1), + }) + } + + fn read(&self, slot: u32) -> u32 { + debug_assert!((slot as usize) < DRAIN_MARKER_SLOTS); + // SAFETY: `slot` is masked to `< DRAIN_MARKER_SLOTS` inside the mapped buffer. + unsafe { + (&*self.mapped.as_ptr().add(slot as usize)) + .load(core::sync::atomic::Ordering::Acquire) + } + } +} + +struct DrainInFlight { + /// Submitted `(slot, tag)` markers in FIFO submission order. + pending: VecDeque<(u32, u32)>, + /// Most recently submitted `tag` per slot (allocated only when `DrainMarker` is active). + /// Recording order can differ from submission order (for example `wgpu-core` records + /// `(wgpu internal) Transit` at submit time and pushes it ahead of earlier-recorded passes), + /// so a lower tag can overwrite a higher tag on the same wrapped slot. Tracking the last + /// submitted tag per slot lets earlier superseded entries retire immediately without + /// assuming monotonic execution order on a slot. + latest_tag: Vec<u32>, +} + +impl DrainInFlight { + fn is_done(&self, state: &DrainMarker, slot: u32, tag: u32) -> bool { + self.latest_tag[slot as usize] != tag || state.read(slot) == tag + } +} + +pub(super) struct DrainTracker { + marker: Option<DrainMarker>, + in_flight: Mutex<DrainInFlight>, + drain_gate: Mutex<()>, + removed: core::sync::atomic::AtomicBool, +} + +impl DrainTracker { + pub(super) fn new(adapter: &DxgiAdapter, device: &Direct3D12::ID3D12Device) -> Self { + // SAFETY: querying static adapter flags on a live DXGI adapter. + let software = unsafe { adapter.GetDesc1() }.is_ok_and(|desc| { + Dxgi::DXGI_ADAPTER_FLAG(desc.Flags as i32).contains(Dxgi::DXGI_ADAPTER_FLAG_SOFTWARE) + }); + let marker = if software { DrainMarker::new(device) } else { None }; + let latest_tag = if marker.is_some() { + alloc::vec![0u32; DRAIN_MARKER_SLOTS] + } else { + Vec::new() + }; + Self { + marker, + in_flight: Mutex::new(DrainInFlight { + pending: VecDeque::new(), + latest_tag, + }), + drain_gate: Mutex::new(()), + removed: core::sync::atomic::AtomicBool::new(false), + } + } + + pub(super) fn has_marker(&self) -> bool { + self.marker.is_some() + } + + pub(super) fn mark_removed(&self) { + let _in_flight = self.in_flight.lock(); + self.removed.store(true, core::sync::atomic::Ordering::Release); + } + + pub(super) fn is_removed(&self) -> bool { + self.removed.load(core::sync::atomic::Ordering::Acquire) + } + + pub(super) fn record( + &self, + list2: Option<&Direct3D12::ID3D12GraphicsCommandList2>, + ) -> Option<(u32, u32)> { + let state = self.marker.as_ref()?; + let list2 = list2?; + let tag = loop { + let v = state.next_tag.fetch_add(1, core::sync::atomic::Ordering::Relaxed); + if v != 0 { + break v; + } + }; + let slot = tag & (DRAIN_MARKER_SLOTS as u32 - 1); + let param = Direct3D12::D3D12_WRITEBUFFERIMMEDIATE_PARAMETER { + Dest: state.gpu_va + u64::from(slot) * 4, + Value: tag, + }; + let mode = Direct3D12::D3D12_WRITEBUFFERIMMEDIATE_MODE_MARKER_OUT; + // SAFETY: `Dest` is 4-byte aligned in `state.resource` (`COPY_DEST`); `list2` is open. + unsafe { list2.WriteBufferImmediate(1, &param, Some(&mode)) }; + Some((slot, tag)) + } + + pub(super) fn track_submitted(&self, command_buffers: &[&CommandBuffer]) -> bool { + let Some(state) = self.marker.as_ref() else { + return !self.is_removed(); + }; + let mut guard = self.in_flight.lock(); + let in_flight = &mut *guard; + if self.removed.load(core::sync::atomic::Ordering::Acquire) { + return false; + } + while let Some(&(slot, tag)) = in_flight.pending.front() { + if in_flight.is_done(state, slot, tag) { + in_flight.pending.pop_front(); + } else { + break; + } + } + if in_flight.pending.len() > 64 { + let latest_tag = &in_flight.latest_tag; + in_flight + .pending + .retain(|&(slot, tag)| latest_tag[slot as usize] == tag && state.read(slot) != tag); + } + for cmd_buf in command_buffers { + if let Some((slot, tag)) = cmd_buf.marker { + in_flight.latest_tag[slot as usize] = tag; + in_flight.pending.push_back((slot, tag)); + } + } + true + } + + pub(super) fn wait_after_removal(&self) { + let _gate = self.drain_gate.lock(); + let Some(state) = self.marker.as_ref() else { + self.mark_removed(); + return; + }; + // Set `removed` under `in_flight`'s lock before draining so no concurrent + // `track_submitted` can push un-executed markers after `Surface::unconfigure` drains. + // Drop any earlier superseded entries on the same slot now; every remaining entry owns + // its slot uniquely and waits for its exact tag to land. + let mut pending = { + let mut guard = self.in_flight.lock(); + let in_flight = &mut *guard; + self.removed.store(true, core::sync::atomic::Ordering::Release); + let latest_tag = &in_flight.latest_tag; + in_flight + .pending + .retain(|&(slot, tag)| latest_tag[slot as usize] == tag && state.read(slot) != tag); + if in_flight.pending.is_empty() { + return; + } + mem::take(&mut in_flight.pending) + }; + let started = std::time::Instant::now(); + let mut last_progress = started; + loop { + let before = pending.len(); + pending.retain(|&(slot, tag)| state.read(slot) != tag); + if pending.is_empty() { + return; + } + let now = std::time::Instant::now(); + if pending.len() < before { + last_progress = now; + } + if now.duration_since(last_progress) >= DRAIN_STALL_TIMEOUT + || now.duration_since(started) >= DRAIN_TOTAL_TIMEOUT + { + return; + } + std::thread::sleep(core::time::Duration::from_millis(1)); + } + } +} + +#[derive(Debug, Clone)] +struct CommandSignatures { + draw: Direct3D12::ID3D12CommandSignature, + draw_indexed: Direct3D12::ID3D12CommandSignature, + draw_mesh: Option<Direct3D12::ID3D12CommandSignature>, + dispatch: Direct3D12::ID3D12CommandSignature, +} + +struct DeviceShared { + adapter: DxgiAdapter, + zero_buffer: Direct3D12::ID3D12Resource, + cmd_signatures: CommandSignatures, + heap_views: descriptor::GeneralHeap, + sampler_heap: sampler::SamplerHeap, + private_caps: PrivateCapabilities, + drain: Arc<DrainTracker>, +} + +unsafe impl Send for DeviceShared {} +unsafe impl Sync for DeviceShared {} + +pub struct Device { + raw: Direct3D12::ID3D12Device, + present_queue: Direct3D12::ID3D12CommandQueue, + idler: Idler, + features: wgt::Features, + shared: Arc<DeviceShared>, + options: wgt::Dx12BackendOptions, + // CPU only pools + rtv_pool: Arc<Mutex<descriptor::CpuPool>>, + dsv_pool: Mutex<descriptor::CpuPool>, + srv_uav_pool: Mutex<descriptor::CpuPool>, + // library + library: Arc<D3D12Lib>, + dcomp_lib: Arc<DCompLib>, + #[cfg(feature = "renderdoc")] + render_doc: auxil::renderdoc::RenderDoc, + null_rtv_handle: descriptor::Handle, + mem_allocator: Allocator, + compiler_container: Arc<shader_compilation::CompilerContainer>, + shader_cache: Mutex<ShaderCache>, + counters: Arc<wgt::HalCounters>, + limits: wgt::Limits, +} + +impl Drop for Device { + fn drop(&mut self) { + self.rtv_pool.lock().free_handle(self.null_rtv_handle); + if self + .shared + .private_caps + .instance_flags + .contains(wgt::InstanceFlags::VALIDATION) + { + auxil::dxgi::exception::unregister_exception_handler(); + } + } +} + +unsafe impl Send for Device {} +unsafe impl Sync for Device {} + +pub struct Queue { + raw: Direct3D12::ID3D12CommandQueue, + temp_lists: Mutex<Vec<Option<Direct3D12::ID3D12CommandList>>>, + idle_fence: Direct3D12::ID3D12Fence, + idle_event: Event, + idle_fence_value: AtomicU64, + pending_waits: Mutex<Vec<(Direct3D12::ID3D12Fence, u64)>>, + pending_signals: Mutex<Vec<(Direct3D12::ID3D12Fence, u64)>>, + drain: Arc<DrainTracker>, +} + +impl Queue { + pub fn as_raw(&self) -> &Direct3D12::ID3D12CommandQueue { + &self.raw + } + + /// Stage a `ID3D12CommandQueue::Wait(fence, value)` for the next + /// [`crate::Queue::submit`]. The wait is enqueued before the + /// submit's command lists, so subsequent GPU work observes the + /// foreign signal at `value`. + pub fn add_wait_fence(&self, fence: Direct3D12::ID3D12Fence, value: u64) { + self.pending_waits.lock().push((fence, value)); + } + + /// Remove `fence` from the pending wait list if it is still present. + /// Returns `true` if it was found and removed. + pub fn remove_wait_fence(&self, fence: &Direct3D12::ID3D12Fence) -> bool { + let target = fence.as_raw(); + let mut waits = self.pending_waits.lock(); + let before = waits.len(); + waits.retain(|(f, _)| f.as_raw() != target); + waits.len() != before + } + + /// Stage a `ID3D12CommandQueue::Signal(fence, value)` for the next + /// [`crate::Queue::submit`]. The signal is enqueued after the + /// submit's command lists complete, so a foreign API waiting on + /// `(fence, value)` observes the wgpu work as done. + pub fn add_signal_fence(&self, fence: Direct3D12::ID3D12Fence, value: u64) { + self.pending_signals.lock().push((fence, value)); + } + + /// Remove `fence` from the pending signal list if it is still present. + /// Returns `true` if it was found and removed. + pub fn remove_signal_fence(&self, fence: &Direct3D12::ID3D12Fence) -> bool { + let target = fence.as_raw(); + let mut signals = self.pending_signals.lock(); + let before = signals.len(); + signals.retain(|(f, _)| f.as_raw() != target); + signals.len() != before + } +} + +unsafe impl Send for Queue {} +unsafe impl Sync for Queue {} + +#[derive(Default)] +struct Temp { + marker: Vec<u16>, + barriers: Vec<Direct3D12::D3D12_RESOURCE_BARRIER>, +} + +impl Temp { + fn clear(&mut self) { + self.marker.clear(); + self.barriers.clear(); + } +} + +struct PassResolve { + src: (Direct3D12::ID3D12Resource, u32), + dst: (Direct3D12::ID3D12Resource, u32), + format: Dxgi::Common::DXGI_FORMAT, +} + +#[derive(Clone, Copy, Debug, Default, PartialEq)] +struct SpecialConstants { + /// The first vertex in an indirect draw call, _or_ the `x` of a compute dispatch. + first_vertex_or_x: i32, + /// The first instance in an indirect draw call, _or_ the `y` of a compute dispatch. + first_instance_or_y: u32, + /// Unused in an indirect draw call, _or_ the `z` of a compute dispatch. + unused_or_z: u32, +} + +impl SpecialConstants { + fn from_indirect_draw_call_params(first_vertex: i32, first_instance: u32) -> Self { + Self { + first_vertex_or_x: first_vertex, + first_instance_or_y: first_instance, + unused_or_z: 0, + } + } + + fn from_compute_dispatch_params(workgroup_count: [u32; 3]) -> Self { + Self { + first_vertex_or_x: workgroup_count[0] as i32, + first_instance_or_y: workgroup_count[1], + unused_or_z: workgroup_count[2], + } + } +} + +#[derive(Clone, Copy, Debug)] +enum RootElement { + Empty, + Immediates, + SpecialConstants(SpecialConstants), + DescriptorTable(Direct3D12::D3D12_GPU_DESCRIPTOR_HANDLE), + /// Descriptor table referring to the entire sampler heap. + SamplerHeapDescriptorTable, + /// Root descriptor for a uniform buffer binding that has a dynamic offset. + DynamicUniformBuffer { + address: Direct3D12::D3D12_GPU_DESCRIPTOR_HANDLE, + }, + /// Root constants for storage buffer bindings with dynamic offsets. + /// + /// start..end is the range of values in [`PassState::dynamic_storage_buffer_offsets`] + /// that will be used to update the root constants. + DynamicStorageBufferOffsets { + start: usize, + end: usize, + }, +} + +#[derive(Clone, Copy)] +enum PassKind { + Render, + Compute, + Transfer, +} + +struct PassState { + has_label: bool, + resolves: ArrayVec<PassResolve, { crate::MAX_COLOR_ATTACHMENTS }>, + layout: PipelineLayoutShared, + root_elements: [RootElement; MAX_ROOT_ELEMENTS], + immediates: [u32; MAX_IMMEDIATES], + dynamic_storage_buffer_offsets: Vec<u32>, + dirty_root_elements: u64, + vertex_buffers: [Direct3D12::D3D12_VERTEX_BUFFER_VIEW; crate::MAX_VERTEX_BUFFERS], + dirty_vertex_buffers: usize, + kind: PassKind, +} + +// `root_elements` size must match `dirty_root_elements` bit size +const _: () = assert!(MAX_ROOT_ELEMENTS == u64::BITS as usize); + +impl PassState { + fn new() -> Self { + PassState { + has_label: false, + resolves: ArrayVec::new(), + layout: PipelineLayoutShared { + signature: None, + total_root_elements: 0, + special_constants: None, + immediates_info: None, + sampler_heap_root_index: None, + }, + root_elements: [RootElement::Empty; MAX_ROOT_ELEMENTS], + immediates: [0; MAX_IMMEDIATES], + dynamic_storage_buffer_offsets: Vec::new(), + dirty_root_elements: 0, + vertex_buffers: [Default::default(); crate::MAX_VERTEX_BUFFERS], + dirty_vertex_buffers: 0, + kind: PassKind::Transfer, + } + } + + fn clear(&mut self) { + // careful about heap allocations! + *self = Self::new(); + } +} + +// Any state in this struct that may be dirty after an abandoned encoding must +// be reset for reused encoders in `begin_encoding`. +pub struct CommandEncoder { + allocator: Direct3D12::ID3D12CommandAllocator, + device: Direct3D12::ID3D12Device, + shared: Arc<DeviceShared>, + mem_allocator: Allocator, + + rtv_pool: Arc<Mutex<descriptor::CpuPool>>, + temp_rtv_handles: Vec<descriptor::Handle>, + + intermediate_copy_bufs: Vec<Buffer>, + + null_rtv_handle: descriptor::Handle, + list: Option<Direct3D12::ID3D12GraphicsCommandList>, + list2: Option<Direct3D12::ID3D12GraphicsCommandList2>, + free_lists: Vec<( + Direct3D12::ID3D12GraphicsCommandList, + Option<Direct3D12::ID3D12GraphicsCommandList2>, + )>, + pass: PassState, + temp: Temp, + + /// If set, the end of the next render/compute pass will write a timestamp at + /// the given pool & location. + end_of_pass_timer_query: Option<(Direct3D12::ID3D12QueryHeap, u32)>, + + counters: Arc<wgt::HalCounters>, +} + +unsafe impl Send for CommandEncoder {} +unsafe impl Sync for CommandEncoder {} + +impl fmt::Debug for CommandEncoder { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("CommandEncoder") + .field("allocator", &self.allocator) + .field("device", &self.allocator) + .finish() + } +} + +#[derive(Debug)] +pub struct CommandBuffer { + raw: Direct3D12::ID3D12GraphicsCommandList, + list2: Option<Direct3D12::ID3D12GraphicsCommandList2>, + marker: Option<(u32, u32)>, +} + +impl crate::DynCommandBuffer for CommandBuffer {} + +unsafe impl Send for CommandBuffer {} +unsafe impl Sync for CommandBuffer {} + +#[derive(Debug)] +pub struct Buffer { + resource: Direct3D12::ID3D12Resource, + // While the allocation also has _a_ size, it may not + // be the same as the original size of the buffer, + // as the allocation size varies for assorted reasons. + size: wgt::BufferAddress, + allocation: suballocation::Allocation, +} + +impl Buffer { + pub unsafe fn raw_resource(&self) -> &Direct3D12::ID3D12Resource { + &self.resource + } +} + +unsafe impl Send for Buffer {} +unsafe impl Sync for Buffer {} + +impl crate::DynBuffer for Buffer {} + +impl crate::BufferBinding<'_, Buffer> { + fn resolve_size(&self) -> wgt::BufferAddress { + match self.size { + Some(size) => size.get(), + None => self.buffer.size - self.offset, + } + } + + // TODO: Return GPU handle directly? + fn resolve_address(&self) -> wgt::BufferAddress { + (unsafe { self.buffer.resource.GetGPUVirtualAddress() }) + self.offset + } +} + +#[derive(Debug)] +pub struct Texture { + resource: Direct3D12::ID3D12Resource, + format: wgt::TextureFormat, + dimension: wgt::TextureDimension, + size: wgt::Extent3d, + mip_level_count: u32, + sample_count: u32, + allocation: suballocation::Allocation, + /// Pins `PlaneSlice` for every view and copy derived from this texture, + /// overriding the default aspect-based derivation. Used by cross-API + /// importers wrapping one plane of a multi-plane DXGI resource as a + /// single-plane wgpu texture. + plane_slice_override: Option<u32>, +} + +impl Texture { + pub unsafe fn raw_resource(&self) -> &Direct3D12::ID3D12Resource { + &self.resource + } + + /// Pin the D3D12 plane slice for every view and copy derived from + /// this texture. Pass `0` for the luma plane, `1` for chroma. The + /// declared `TextureFormat` must be single-plane (e.g. `R8Unorm`, + /// `Rg8Unorm`) and match the plane's texel layout. + /// + /// # Safety / aliasing + /// + /// The intended use is to wrap one plane of a multi-plane DXGI + /// resource (e.g. NV12) as a single-plane wgpu texture, typically + /// by calling [`Device::texture_from_raw`](Device::texture_from_raw) + /// twice with two clones of the same `ID3D12Resource` and a + /// different `plane_slice` on each. wgpu's state tracker treats + /// these wrappers as independent textures: per-subresource state, + /// hazard tracking, and resource-state barriers all assume + /// non-aliased ownership and have no way to know the two wrappers + /// alias the same underlying resource. + /// + /// The caller is responsible for ensuring that the underlying + /// resource is not concurrently used by another wgpu texture + /// wrapping a different plane in a way that would race or + /// invalidate state tracking — in particular, do not submit work + /// touching both wrappers in the same submission unless every + /// access goes through `COPY_SRC` / `COPY_DST` on the wrapper that + /// owns that plane's subresource, and do not destroy the wrappers + /// concurrently with in-flight work that uses either of them. + pub fn with_plane_slice(mut self, plane_slice: u32) -> Self { + debug_assert!( + !self.format.is_multi_planar_format(), + "`with_plane_slice` expects a single-plane format wrapping a \ + multi-plane DXGI resource; got planar format `{:?}`", + self.format, + ); + self.plane_slice_override = Some(plane_slice); + self + } + + pub(super) fn plane_slice_override(&self) -> Option<u32> { + self.plane_slice_override + } +} + +impl crate::DynTexture for Texture {} +impl crate::DynSurfaceTexture for Texture {} + +impl core::borrow::Borrow<dyn crate::DynTexture> for Texture { + fn borrow(&self) -> &dyn crate::DynTexture { + self + } +} + +unsafe impl Send for Texture {} +unsafe impl Sync for Texture {} + +impl Texture { + fn array_layer_count(&self) -> u32 { + match self.dimension { + wgt::TextureDimension::D1 | wgt::TextureDimension::D3 => 1, + wgt::TextureDimension::D2 => self.size.depth_or_array_layers, + } + } + + /// see <https://learn.microsoft.com/en-us/windows/win32/direct3d12/subresources#plane-slice> + fn calc_subresource(&self, mip_level: u32, array_layer: u32, plane: u32) -> u32 { + mip_level + (array_layer + plane * self.array_layer_count()) * self.mip_level_count + } + + fn calc_subresource_for_copy(&self, base: &crate::TextureCopyBase) -> u32 { + // Single-plane wrappers around a multi-plane resource report + // `COLOR` aspect, which would otherwise resolve to plane 0. + let plane = self + .plane_slice_override + .unwrap_or_else(|| match base.aspect { + crate::FormatAspects::COLOR + | crate::FormatAspects::DEPTH + | crate::FormatAspects::PLANE_0 => 0, + crate::FormatAspects::STENCIL | crate::FormatAspects::PLANE_1 => 1, + crate::FormatAspects::PLANE_2 => 2, + _ => unreachable!(), + }); + self.calc_subresource(base.mip_level, base.array_layer, plane) + } +} + +#[derive(Debug)] +pub struct TextureView { + raw_format: Dxgi::Common::DXGI_FORMAT, + aspects: crate::FormatAspects, + dimension: wgt::TextureViewDimension, + texture: Direct3D12::ID3D12Resource, + subresource_index: u32, + mip_slice: u32, + handle_srv: Option<descriptor::Handle>, + handle_uav: Option<descriptor::Handle>, + handle_rtv: Option<descriptor::Handle>, + handle_dsv_ro: Option<descriptor::Handle>, + handle_dsv_rw: Option<descriptor::Handle>, +} + +impl crate::DynTextureView for TextureView {} + +unsafe impl Send for TextureView {} +unsafe impl Sync for TextureView {} + +#[derive(Debug)] +pub struct Sampler { + index: sampler::SamplerIndex, + desc: Direct3D12::D3D12_SAMPLER_DESC, +} + +impl crate::DynSampler for Sampler {} + +#[cfg(send_sync)] +static_assertions::assert_impl_all!(Sampler: Send, Sync); + +#[derive(Debug)] +pub struct QuerySet { + raw: Direct3D12::ID3D12QueryHeap, + raw_ty: Direct3D12::D3D12_QUERY_TYPE, +} + +impl crate::DynQuerySet for QuerySet {} + +unsafe impl Send for QuerySet {} +unsafe impl Sync for QuerySet {} + +#[derive(Debug)] +pub struct Fence { + raw: Direct3D12::ID3D12Fence, + /// Rune: the highest value read from it (`Device::reached`). + reached: AtomicU64, +} + +impl crate::DynFence for Fence {} + +unsafe impl Send for Fence {} +unsafe impl Sync for Fence {} + +impl Fence { + pub fn raw_fence(&self) -> &Direct3D12::ID3D12Fence { + &self.raw + } +} + +#[derive(Debug)] +pub struct BindGroupLayout { + /// Sorted list of entries. + entries: Vec<wgt::BindGroupLayoutEntry>, + cpu_heap_views: Option<descriptor::CpuHeap>, + copy_counts: Vec<u32>, // all 1's +} + +impl crate::DynBindGroupLayout for BindGroupLayout {} + +#[derive(Debug, Clone, Copy)] +enum DynamicBuffer { + Uniform(Direct3D12::D3D12_GPU_DESCRIPTOR_HANDLE), + Storage, +} + +#[derive(Debug)] +struct SamplerIndexBuffer { + buffer: Direct3D12::ID3D12Resource, + allocation: suballocation::Allocation, +} + +#[derive(Debug)] +pub struct BindGroup { + handle_views: Option<descriptor::DualHandle>, + sampler_index_buffer: Option<SamplerIndexBuffer>, + dynamic_buffers: Vec<DynamicBuffer>, +} + +impl crate::DynBindGroup for BindGroup {} + +bitflags::bitflags! { + #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)] + struct TableTypes: u8 { + const SRV_CBV_UAV = 1 << 0; + const SAMPLERS = 1 << 1; + } +} + +// Element (also known as parameter) index into the root signature. +type RootIndex = u32; + +#[derive(Debug)] +struct BindGroupInfo { + base_root_index: RootIndex, + tables: TableTypes, + dynamic_storage_buffer_offsets: Option<DynamicStorageBufferOffsets>, +} + +#[derive(Debug, Clone)] +struct ImmediatesInfo { + root_index: RootIndex, + size: u32, +} + +#[derive(Debug, Clone)] +struct DynamicStorageBufferOffsets { + root_index: RootIndex, + range: core::ops::Range<usize>, +} + +#[derive(Debug, Clone)] +struct PipelineLayoutShared { + signature: Option<Direct3D12::ID3D12RootSignature>, + total_root_elements: RootIndex, + special_constants: Option<PipelineLayoutSpecialConstants>, + immediates_info: Option<ImmediatesInfo>, + sampler_heap_root_index: Option<RootIndex>, +} + +unsafe impl Send for PipelineLayoutShared {} +unsafe impl Sync for PipelineLayoutShared {} + +#[derive(Debug, Clone)] +struct PipelineLayoutSpecialConstants { + root_index: RootIndex, + indirect_cmd_signatures: Option<CommandSignatures>, +} + +unsafe impl Send for PipelineLayoutSpecialConstants {} +unsafe impl Sync for PipelineLayoutSpecialConstants {} + +#[derive(Debug)] +pub struct PipelineLayout { + shared: PipelineLayoutShared, + // Storing for each associated bind group, which tables we created + // in the root signature. This is required for binding descriptor sets. + bind_group_infos: [Option<BindGroupInfo>; crate::MAX_BIND_GROUPS], + naga_options: naga::back::hlsl::Options, +} + +impl crate::DynPipelineLayout for PipelineLayout {} + +#[derive(Debug)] +pub struct ShaderModule { + source: ShaderModuleSource, + raw_name: Option<alloc::ffi::CString>, + runtime_checks: wgt::ShaderRuntimeChecks, +} + +impl crate::DynShaderModule for ShaderModule {} + +#[derive(Default)] +pub struct ShaderCache { + nr_of_shaders_compiled: u32, + entries: HashMap<ShaderCacheKey, ShaderCacheValue>, +} + +#[derive(PartialEq, Eq, Hash)] +pub(super) struct ShaderCacheKey { + source: String, + entry_point: String, + stage: naga::ShaderStage, + shader_model: naga::back::hlsl::ShaderModel, +} + +pub(super) struct ShaderCacheValue { + /// This is the value of [`ShaderCache::nr_of_shaders_compiled`] + /// at the time the cache entry was last used. + last_used: u32, + shader: CompiledShader, +} + +#[derive(Clone)] +pub(super) enum CompiledShader { + Dxc(Direct3D::Dxc::IDxcBlob), + Fxc(Direct3D::ID3DBlob), + Precompiled(Vec<u8>), +} + +impl CompiledShader { + fn create_native_shader(&self) -> Direct3D12::D3D12_SHADER_BYTECODE { + match self { + CompiledShader::Dxc(shader) => Direct3D12::D3D12_SHADER_BYTECODE { + pShaderBytecode: unsafe { shader.GetBufferPointer() }, + BytecodeLength: unsafe { shader.GetBufferSize() }, + }, + CompiledShader::Fxc(shader) => Direct3D12::D3D12_SHADER_BYTECODE { + pShaderBytecode: unsafe { shader.GetBufferPointer() }, + BytecodeLength: unsafe { shader.GetBufferSize() }, + }, + CompiledShader::Precompiled(shader) => Direct3D12::D3D12_SHADER_BYTECODE { + pShaderBytecode: shader.as_ptr().cast(), + BytecodeLength: shader.len(), + }, + } + } +} + +#[derive(Debug)] +pub struct RenderPipeline { + raw: Direct3D12::ID3D12PipelineState, + layout: PipelineLayoutShared, + topology: Direct3D::D3D_PRIMITIVE_TOPOLOGY, + vertex_strides: [Option<u32>; crate::MAX_VERTEX_BUFFERS], +} + +impl crate::DynRenderPipeline for RenderPipeline {} + +unsafe impl Send for RenderPipeline {} +unsafe impl Sync for RenderPipeline {} + +#[derive(Debug)] +pub struct ComputePipeline { + raw: Direct3D12::ID3D12PipelineState, + layout: PipelineLayoutShared, +} + +impl crate::DynComputePipeline for ComputePipeline {} + +unsafe impl Send for ComputePipeline {} +unsafe impl Sync for ComputePipeline {} + +#[derive(Debug)] +pub struct RayTracingPipeline {} + +impl crate::DynRayTracingPipeline for RayTracingPipeline {} + +#[derive(Debug)] +pub struct PipelineCache; + +impl crate::DynPipelineCache for PipelineCache {} + +#[derive(Debug)] +pub struct AccelerationStructure { + resource: Direct3D12::ID3D12Resource, + allocation: suballocation::Allocation, +} + +impl crate::DynAccelerationStructure for AccelerationStructure {} + +impl SwapChain { + unsafe fn release_resources(mut self) -> Dxgi::IDXGISwapChain3 { + if let Some(mut waitable) = self.waitable.take() { + unsafe { Foundation::HANDLE::free(&mut waitable) }; + } + self.raw + } + + unsafe fn wait( + &mut self, + timeout: Option<core::time::Duration>, + ) -> Result<bool, crate::SurfaceError> { + let timeout_ms = match timeout { + Some(duration) => duration.as_millis() as u32, + None => Threading::INFINITE, + }; + + if let Some(waitable) = self.waitable { + match unsafe { Threading::WaitForSingleObject(waitable, timeout_ms) } { + Foundation::WAIT_ABANDONED | Foundation::WAIT_FAILED => { + Err(crate::SurfaceError::Lost) + } + Foundation::WAIT_OBJECT_0 => Ok(true), + Foundation::WAIT_TIMEOUT => Ok(false), + other => { + log::error!("Unexpected wait status: 0x{other:x?}"); + Err(crate::SurfaceError::Lost) + } + } + } else { + Ok(true) + } + } +} + +fn map_surface_color_space( + color_space: wgt::SurfaceColorSpace, +) -> Dxgi::Common::DXGI_COLOR_SPACE_TYPE { + use wgt::SurfaceColorSpace as Scs; + match color_space { + Scs::Srgb => Dxgi::Common::DXGI_COLOR_SPACE_RGB_FULL_G22_NONE_P709, + Scs::ExtendedSrgbLinear => Dxgi::Common::DXGI_COLOR_SPACE_RGB_FULL_G10_NONE_P709, + Scs::Bt2100Pq => Dxgi::Common::DXGI_COLOR_SPACE_RGB_FULL_G2084_NONE_P2020, + Scs::Auto + | Scs::DisplayP3 + | Scs::Bt2100Hlg + | Scs::ExtendedSrgb + | Scs::ExtendedDisplayP3 => { + unreachable!("`{color_space:?}` is never reported in the DX12 surface capabilities") + } + } +} + +impl crate::Surface for Surface { + type A = Api; + + unsafe fn configure( + &self, + device: &Device, + config: &crate::SurfaceConfiguration, + ) -> Result<(), crate::SurfaceError> { + let mut flags = Dxgi::DXGI_SWAP_CHAIN_FLAG_FRAME_LATENCY_WAITABLE_OBJECT; + // We always set ALLOW_TEARING on the swapchain no matter + // what kind of swapchain we want because ResizeBuffers + // cannot change the swapchain's ALLOW_TEARING flag. + // + // This does not change the behavior of the swapchain, just + // allow present calls to use tearing. + if self.supports_allow_tearing { + flags |= Dxgi::DXGI_SWAP_CHAIN_FLAG_ALLOW_TEARING; + } + + // While `configure`s contract ensures that no work on the GPU's main queues + // are in flight, we still need to wait for the present queue to be idle. + unsafe { device.wait_for_present_queue_idle() }?; + + let non_srgb_format = auxil::dxgi::conv::map_texture_format_nosrgb(config.format); + + // The range for `SetMaximumFrameLatency` is 1-16 so the maximum latency requested should be 15 because we add 1. + // https://learn.microsoft.com/en-us/windows/win32/api/dxgi/nf-dxgi-idxgidevice1-setmaximumframelatency + debug_assert!(config.maximum_frame_latency <= 15); + + // Nvidia recommends to use 1-2 more buffers than the maximum latency + // https://developer.nvidia.com/blog/advanced-api-performance-swap-chains/ + // For high latency extra buffers seems excessive, so go with a minimum of 3 and beyond that add 1. + let swap_chain_buffer = (config.maximum_frame_latency + 1).min(16); + + let swap_chain = match self.swap_chain.write().take() { + //Note: this path doesn't properly re-initialize all of the things + Some(sc) => { + let raw = unsafe { sc.release_resources() }; + let result = unsafe { + raw.ResizeBuffers( + swap_chain_buffer, + config.extent.width, + config.extent.height, + non_srgb_format, + flags, + ) + }; + if let Err(err) = result { + log::error!("ResizeBuffers failed: {err}"); + return Err(crate::SurfaceError::Other("window is in use")); + } + raw + } + None => { + let desc = Dxgi::DXGI_SWAP_CHAIN_DESC1 { + AlphaMode: auxil::dxgi::conv::map_acomposite_alpha_mode( + config.composite_alpha_mode, + ), + Width: config.extent.width, + Height: config.extent.height, + Format: non_srgb_format, + Stereo: false.into(), + SampleDesc: Dxgi::Common::DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, + BufferUsage: Dxgi::DXGI_USAGE_RENDER_TARGET_OUTPUT, + BufferCount: swap_chain_buffer, + Scaling: Dxgi::DXGI_SCALING_STRETCH, + // Rune: presenting part of a frame (Surface::set_present_rects, Present1's dirty + // rectangles) needs the sequential flip model; FLIP_DISCARD can't. + SwapEffect: Dxgi::DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL, + Flags: flags.0 as u32, + }; + let swap_chain1 = match self.target { + SurfaceTarget::Visual(_) + | SurfaceTarget::VisualFromWndHandle { .. } + | SurfaceTarget::SwapChainPanel(_) => { + profiling::scope!("IDXGIFactory2::CreateSwapChainForComposition"); + unsafe { + self.factory.CreateSwapChainForComposition( + &device.present_queue, + &desc, + None, + ) + } + } + SurfaceTarget::SurfaceHandle(handle) => { + profiling::scope!( + "IDXGIFactoryMedia::CreateSwapChainForCompositionSurfaceHandle" + ); + unsafe { + self.factory_media + .as_ref() + .ok_or(crate::SurfaceError::Other("IDXGIFactoryMedia not found"))? + .CreateSwapChainForCompositionSurfaceHandle( + &device.present_queue, + Some(handle), + &desc, + None, + ) + } + } + SurfaceTarget::WndHandle(hwnd) => { + profiling::scope!("IDXGIFactory2::CreateSwapChainForHwnd"); + unsafe { + self.factory.CreateSwapChainForHwnd( + &device.present_queue, + hwnd, + &desc, + None, + None, + ) + } + } + }; + + let swap_chain1 = swap_chain1.map_err(|err| { + log::error!("SwapChain creation error: {err}"); + crate::SurfaceError::Other("swapchain creation") + })?; + + match &self.target { + SurfaceTarget::WndHandle(_) | SurfaceTarget::SurfaceHandle(_) => {} + SurfaceTarget::VisualFromWndHandle { + handle, + dcomp_state, + } => { + let mut dcomp_state = dcomp_state.lock(); + let dcomp_state = + unsafe { dcomp_state.get_or_init(&device.dcomp_lib, handle) }?; + // Set the new swap chain as the content for the backing visual + // and commit the changes to the composition visual tree. + { + profiling::scope!("IDCompositionVisual::SetContent"); + unsafe { dcomp_state.visual.SetContent(&swap_chain1) }.map_err( + |err| { + log::error!("IDCompositionVisual::SetContent failed: {err}"); + crate::SurfaceError::Other("IDCompositionVisual::SetContent") + }, + )?; + } + + // Commit the changes to the composition device. + { + profiling::scope!("IDCompositionDevice::Commit"); + unsafe { dcomp_state.device.Commit() }.map_err(|err| { + log::error!("IDCompositionDevice::Commit failed: {err}"); + crate::SurfaceError::Other("IDCompositionDevice::Commit") + })?; + } + } + SurfaceTarget::Visual(visual) => { + if let Err(err) = unsafe { visual.SetContent(&swap_chain1) } { + log::error!("Unable to SetContent: {err}"); + return Err(crate::SurfaceError::Other( + "IDCompositionVisual::SetContent", + )); + } + } + SurfaceTarget::SwapChainPanel(swap_chain_panel) => { + if let Err(err) = unsafe { swap_chain_panel.SetSwapChain(&swap_chain1) } { + log::error!("Unable to SetSwapChain: {err}"); + return Err(crate::SurfaceError::Other( + "ISwapChainPanelNative::SetSwapChain", + )); + } + } + } + + swap_chain1.cast::<Dxgi::IDXGISwapChain3>().map_err(|err| { + log::error!("Unable to cast swapchain: {err}"); + crate::SurfaceError::Other("swapchain cast to version 3") + })? + } + }; + + // Apply the color space unconditionally (even for sRGB) so that + // reconfiguring away from HDR10 resets the swapchain's state. + // + // We deliberately skip `CheckColorSpaceSupport`: a color space reporting as + // unsupported is not a failure. Windows composites in scRGB and tone-maps + // the color space down to the output, so `SetColorSpace1` still presents + // correctly even when the check returns false (as the MS docs note). This + // lets an app configure e.g. BT.2100 PQ on an SDR output and let the + // compositor map it. + let color_space = map_surface_color_space(config.color_space); + // SAFETY: `swap_chain` is a live `IDXGISwapChain3`; `color_space` is a + // valid `DXGI_COLOR_SPACE_TYPE`. + unsafe { swap_chain.SetColorSpace1(color_space) }.map_err(|err| { + log::error!("SetColorSpace1 failed: {err}"); + crate::SurfaceError::Other("IDXGISwapChain3::SetColorSpace1") + })?; + + match self.target { + SurfaceTarget::WndHandle(wnd_handle) => { + // Disable automatic Alt+Enter handling by DXGI. + unsafe { + self.factory.MakeWindowAssociation( + wnd_handle, + Dxgi::DXGI_MWA_NO_WINDOW_CHANGES | Dxgi::DXGI_MWA_NO_ALT_ENTER, + ) + } + .into_device_result("MakeWindowAssociation")?; + } + SurfaceTarget::Visual(_) + | SurfaceTarget::VisualFromWndHandle { .. } + | SurfaceTarget::SurfaceHandle(_) + | SurfaceTarget::SwapChainPanel(_) => {} + } + + unsafe { swap_chain.SetMaximumFrameLatency(config.maximum_frame_latency) } + .into_device_result("SetMaximumFrameLatency")?; + + let waitable = match device.options.latency_waitable_object { + wgt::Dx12UseFrameLatencyWaitableObject::None => None, + wgt::Dx12UseFrameLatencyWaitableObject::Wait + | wgt::Dx12UseFrameLatencyWaitableObject::DontWait => { + Some(unsafe { swap_chain.GetFrameLatencyWaitableObject() }) + } + }; + + let mut resources = Vec::with_capacity(swap_chain_buffer as usize); + for i in 0..swap_chain_buffer { + let resource = unsafe { swap_chain.GetBuffer(i) } + .into_device_result("Failed to get swapchain buffer")?; + resources.push(resource); + } + + let mut swapchain = self.swap_chain.write(); + *swapchain = Some(SwapChain { + raw: swap_chain, + resources, + waitable, + acquired_count: 0, + present_mode: config.present_mode, + format: config.format, + size: config.extent, + dirty: Vec::new(), + }); + + Ok(()) + } + + unsafe fn unconfigure(&self, device: &Device) { + if let Some(sc) = self.swap_chain.write().take() { + unsafe { + // While `unconfigure`s contract ensures that no work on the GPU's main queues + // are in flight, we still need to wait for the present queue to be idle. + + // The major failure mode of this function is device loss, + // which if we have lost the device, we should just continue + // cleaning up, without error. + let _ = device.wait_for_present_queue_idle(); + + let _raw = sc.release_resources(); + } + } + } + + unsafe fn acquire_texture( + &self, + timeout: Option<core::time::Duration>, + _fence: &Fence, + ) -> Result<crate::AcquiredSurfaceTexture<Api>, crate::SurfaceError> { + let mut swapchain = self.swap_chain.write(); + let sc = swapchain.as_mut().unwrap(); + + match self.options.latency_waitable_object { + wgt::Dx12UseFrameLatencyWaitableObject::None + | wgt::Dx12UseFrameLatencyWaitableObject::DontWait => {} + wgt::Dx12UseFrameLatencyWaitableObject::Wait => { + unsafe { sc.wait(timeout) }?; + } + } + + let base_index = unsafe { sc.raw.GetCurrentBackBufferIndex() } as usize; + let index = (base_index + sc.acquired_count) % sc.resources.len(); + sc.acquired_count += 1; + + let texture = Texture { + resource: sc.resources[index].clone(), + format: sc.format, + dimension: wgt::TextureDimension::D2, + size: sc.size, + mip_level_count: 1, + sample_count: 1, + allocation: suballocation::Allocation::none( + suballocation::AllocationType::Texture, + sc.format.theoretical_memory_footprint(sc.size), + ), + plane_slice_override: None, + }; + Ok(crate::AcquiredSurfaceTexture { + texture, + suboptimal: false, + }) + } + unsafe fn discard_texture(&self, _texture: Texture) { + let mut swapchain = self.swap_chain.write(); + let sc = swapchain.as_mut().unwrap(); + sc.acquired_count -= 1; + } +} + +impl Queue { + fn device_removed(&self) -> bool { + let mut device: Option<Direct3D12::ID3D12Device> = None; + unsafe { self.raw.GetDevice(&mut device) }.is_ok() + && device.is_some_and(|device| unsafe { device.GetDeviceRemovedReason() }.is_err()) + } +} + +impl crate::Queue for Queue { + type A = Api; + + unsafe fn submit( + &self, + command_buffers: &[&CommandBuffer], + _surface_textures: &[&Texture], + (signal_fence, signal_value): (&Fence, crate::FenceValue), + ) -> Result<(), crate::DeviceError> { + // Rune: skip `ExecuteCommandLists` once removed. On software adapters with drain markers, + // also check `idle_fence` so a removal before the first poll does not queue untracked + // lists; hardware adapters pay only the atomic load (zero COM calls or marker reads). + if self.drain.is_removed() + || (self.drain.has_marker() + && unsafe { self.idle_fence.GetCompletedValue() } == u64::MAX + && self.device_removed()) + { + self.drain.mark_removed(); + return Err(crate::DeviceError::Lost); + } + + let mut temp_lists = self.temp_lists.lock(); + temp_lists.clear(); + for cmd_buf in command_buffers { + temp_lists.push(Some(cmd_buf.raw.clone().into())); + } + + // Drain caller-staged waits before ExecuteCommandLists so the + // GPU queue blocks on each foreign signal before running our + // command lists. D3D12 queue commands are FIFO - Wait calls + // here gate everything submitted after them. + { + let mut waits = self.pending_waits.lock(); + for (fence, value) in waits.drain(..) { + if let Err(err) = + unsafe { self.raw.Wait(&fence, value) }.into_device_result("Wait pending fence") + { + if matches!(err, crate::DeviceError::Lost) { + self.drain.mark_removed(); + } + return Err(err); + } + } + } + + if !command_buffers.is_empty() && !self.drain.track_submitted(command_buffers) { + return Err(crate::DeviceError::Lost); + } + + { + profiling::scope!("ID3D12CommandQueue::ExecuteCommandLists"); + unsafe { self.raw.ExecuteCommandLists(&temp_lists) } + } + + if let Err(err) = + unsafe { self.raw.Signal(&signal_fence.raw, signal_value) }.into_device_result("Signal fence") + { + if matches!(err, crate::DeviceError::Lost) { + self.drain.mark_removed(); + } + return Err(err); + } + + // Drain caller-staged signals after our own Signal so each + // additional fence value publishes once the submit completes. + { + let mut signals = self.pending_signals.lock(); + for (fence, value) in signals.drain(..) { + if let Err(err) = unsafe { self.raw.Signal(&fence, value) } + .into_device_result("Signal pending fence") + { + if matches!(err, crate::DeviceError::Lost) { + self.drain.mark_removed(); + } + return Err(err); + } + } + } + + // Note the lack of synchronization here between the main Direct queue + // and the dedicated presentation queue. This is automatically handled + // by the D3D runtime by detecting uses of resources derived from the + // swapchain. This automatic detection is why you cannot use a swapchain + // as an UAV in D3D12. + + Ok(()) + } + unsafe fn present( + &self, + surface: &Surface, + _texture: Texture, + ) -> Result<(), crate::SurfaceError> { + let mut swapchain = surface.swap_chain.write(); + let sc = swapchain.as_mut().unwrap(); + sc.acquired_count -= 1; + + let (interval, flags) = match sc.present_mode { + // We only allow immediate if ALLOW_TEARING is valid. + wgt::PresentMode::Immediate => (0, Dxgi::DXGI_PRESENT_ALLOW_TEARING), + wgt::PresentMode::Mailbox => (0, Dxgi::DXGI_PRESENT::default()), + wgt::PresentMode::Fifo => (1, Dxgi::DXGI_PRESENT::default()), + m => unreachable!("Cannot make surface with present mode {m:?}"), + }; + + profiling::scope!("IDXGISwapchain3::Present"); + let dirty = core::mem::take(&mut sc.dirty); + if dirty.is_empty() { + unsafe { sc.raw.Present(interval, flags) } + .ok() + .into_device_result("Present")?; + } else { + let params = Dxgi::DXGI_PRESENT_PARAMETERS { + DirtyRectsCount: dirty.len() as u32, + pDirtyRects: dirty.as_ptr().cast_mut(), + pScrollRect: core::ptr::null_mut(), + pScrollOffset: core::ptr::null_mut(), + }; + unsafe { sc.raw.Present1(interval, flags, &params) } + .ok() + .into_device_result("Present1")?; + } + + Ok(()) + } + + unsafe fn get_timestamp_period(&self) -> f32 { + let frequency = unsafe { self.raw.GetTimestampFrequency() }.expect("GetTimestampFrequency"); + (1_000_000_000.0 / frequency as f64) as f32 + } + + unsafe fn wait_for_idle(&self) -> Result<(), crate::DeviceError> { + let on_removed = || { + self.drain.mark_removed(); + self.drain.wait_after_removal(); + Err(crate::DeviceError::Lost) + }; + if unsafe { self.idle_fence.GetCompletedValue() } == u64::MAX && self.device_removed() { + return on_removed(); + } + let value = self + .idle_fence_value + .fetch_add(1, core::sync::atomic::Ordering::Relaxed) + + 1; + if let Err(err) = unsafe { self.raw.Signal(&self.idle_fence, value) } + .into_device_result("Signal idle fence") + { + if matches!(err, crate::DeviceError::Lost) { + return on_removed(); + } + return Err(err); + } + if let Err(err) = unsafe { + self.idle_fence + .SetEventOnCompletion(value, self.idle_event.0) + } + .into_device_result("SetEventOnCompletion") + { + if matches!(err, crate::DeviceError::Lost) { + return on_removed(); + } + return Err(err); + } + // Rune: a removed device's work never finishes through fences, so the wait asks after + // the device every 100 ms instead of waiting forever (wgpu-core waits here when it drops + // the queue), and drains queued command lists through GPU-written markers before + // returning so wgpu-core doesn't free resources while the driver is still executing them. + while unsafe { Threading::WaitForSingleObject(self.idle_event.0, 100) } + == Foundation::WAIT_TIMEOUT + { + if self.device_removed() { + return on_removed(); + } + } + if unsafe { self.idle_fence.GetCompletedValue() } == u64::MAX && self.device_removed() { + return on_removed(); + } + Ok(()) + } +} +#[derive(Debug)] +pub struct DxilPassthroughShader { + pub shader: Vec<u8>, +} + +#[derive(Debug)] +pub struct HlslPassthroughShader { + pub shader: String, +} + +#[derive(Debug)] +pub enum ShaderModuleSource { + Naga(crate::NagaShader), + DxilPassthrough(DxilPassthroughShader), + HlslPassthrough(HlslPassthroughShader), +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)] +pub enum FeatureLevel { + V11_0, + V11_1, + V12_0, + V12_1, + V12_2, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)] +pub enum ShaderModel { + V5_1, + V6_0, + V6_1, + V6_2, + V6_3, + V6_4, + V6_5, + V6_6, + V6_7, + V6_8, + V6_9, +} diff --git a/app/vendor/rune/vendor/wgpu-hal/src/dx12/pipeline_desc.rs b/app/vendor/rune/vendor/wgpu-hal/src/dx12/pipeline_desc.rs new file mode 100644 index 0000000..9fcf566 --- /dev/null +++ b/app/vendor/rune/vendor/wgpu-hal/src/dx12/pipeline_desc.rs @@ -0,0 +1,344 @@ +//! We try to use pipeline stream descriptors where possible, but this isn't allowed +//! on some older windows 10 versions. Therefore, we also must have some logic to +//! convert such descriptors to the "traditional" equivalent, +//! `D3D12_GRAPHICS_PIPELINE_STATE_DESC`. +//! +//! Stream descriptors allow extending the pipeline, enabling more advanced features, +//! including mesh shaders and multiview/view instancing. Using a stream descriptor +//! is like using a vulkan descriptor with a `pNext` chain. It doesn't have direct +//! benefits to all use cases, but allows new use cases. +//! +//! The code for pipeline stream descriptors is very complicated, and can have bad +//! consequences if it is written incorrectly. It has been isolated to this file for +//! that reason. + +use core::{ffi::c_void, mem::ManuallyDrop, ptr::NonNull}; + +use alloc::vec::Vec; +use windows::Win32::Graphics::Direct3D12::*; +use windows::Win32::Graphics::Dxgi::Common::*; +use windows_core::Interface; + +use crate::dx12::borrow_interface_temporarily; + +// Wrapper newtypes for various pipeline subobjects which +// use complicated or non-unique representations. + +#[repr(transparent)] +#[derive(Copy, Clone)] +// Option<NonNull<c_void>> is guaranteed to have the same representation as a raw pointer. +struct RootSignature(Option<NonNull<c_void>>); + +#[repr(transparent)] +#[derive(Copy, Clone)] +struct VertexShader(D3D12_SHADER_BYTECODE); +#[repr(transparent)] +#[derive(Copy, Clone)] +struct PixelShader(D3D12_SHADER_BYTECODE); + +#[repr(transparent)] +#[derive(Copy, Clone)] +struct MeshShader(D3D12_SHADER_BYTECODE); + +#[repr(transparent)] +#[derive(Copy, Clone)] +struct TaskShader(D3D12_SHADER_BYTECODE); + +#[repr(transparent)] +#[derive(Copy, Clone)] +struct SampleMask(u32); + +#[repr(transparent)] +#[derive(Copy, Clone)] +struct NodeMask(u32); + +/// Trait for types that can be used as subobjects in a pipeline state stream. +/// +/// Safety: +/// - The type must be the correct alignment and size for the subobject it represents. +/// - The type must map to exactly one `D3D12_PIPELINE_STATE_SUBOBJECT_TYPE` variant. +/// - The variant must correctly represent the type's role in the pipeline state stream. +/// - The type must be `Copy` to ensure safe duplication in the stream. +/// - The type must be valid to memcpy into the pipeline state stream. +unsafe trait RenderPipelineStreamObject: Copy { + const SUBOBJECT_TYPE: D3D12_PIPELINE_STATE_SUBOBJECT_TYPE; +} + +macro_rules! implement_stream_object { + (unsafe $ty:ty => $variant:expr) => { + unsafe impl RenderPipelineStreamObject for $ty { + const SUBOBJECT_TYPE: D3D12_PIPELINE_STATE_SUBOBJECT_TYPE = $variant; + } + }; +} + +implement_stream_object! { unsafe RootSignature => D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_ROOT_SIGNATURE } +implement_stream_object! { unsafe VertexShader => D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_VS } +implement_stream_object! { unsafe PixelShader => D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS } +implement_stream_object! { unsafe MeshShader => D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_MS } +implement_stream_object! { unsafe TaskShader => D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_AS } +implement_stream_object! { unsafe D3D12_BLEND_DESC => D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_BLEND } +implement_stream_object! { unsafe SampleMask => D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_MASK } +implement_stream_object! { unsafe D3D12_RASTERIZER_DESC => D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RASTERIZER } +implement_stream_object! { unsafe D3D12_DEPTH_STENCIL_DESC => D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL } +implement_stream_object! { unsafe D3D12_PRIMITIVE_TOPOLOGY_TYPE => D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PRIMITIVE_TOPOLOGY } +implement_stream_object! { unsafe D3D12_RT_FORMAT_ARRAY => D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RENDER_TARGET_FORMATS } +implement_stream_object! { unsafe DXGI_FORMAT => D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL_FORMAT } +implement_stream_object! { unsafe DXGI_SAMPLE_DESC => D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_DESC } +implement_stream_object! { unsafe NodeMask => D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_NODE_MASK } +implement_stream_object! { unsafe D3D12_CACHED_PIPELINE_STATE => D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_CACHED_PSO } +implement_stream_object! { unsafe D3D12_PIPELINE_STATE_FLAGS => D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_FLAGS } +implement_stream_object! { unsafe D3D12_INPUT_LAYOUT_DESC => D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_INPUT_LAYOUT } +implement_stream_object! { unsafe D3D12_INDEX_BUFFER_STRIP_CUT_VALUE => D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_IB_STRIP_CUT_VALUE } +implement_stream_object! { unsafe D3D12_STREAM_OUTPUT_DESC => D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_STREAM_OUTPUT } +implement_stream_object! { unsafe D3D12_VIEW_INSTANCING_DESC => D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_VIEW_INSTANCING } + +/// Implementaation of a pipeline state stream, which is a sequence of subobjects put into +/// a byte array according to some basic alignment rules. +/// +/// Each subobject must start on an 8 byte boundary. Each subobject contains a 32 bit +/// type identifier, followed by the actual subobject data, aligned as required by the +/// subobject's structure. +/// +/// See <https://learn.microsoft.com/en-us/windows/win32/api/d3d12/ns-d3d12-d3d12_pipeline_state_stream_desc> +/// for more information. +pub(super) struct RenderPipelineStateStream<'a> { + bytes: Vec<u8>, + _marker: core::marker::PhantomData<&'a ()>, +} + +impl<'a> RenderPipelineStateStream<'a> { + fn new() -> Self { + // Dynamic allocation is used here because the resulting stream can become very large. + // We pre-allocate the size based on an estimate of the size of the struct plus some extra space + // per member for tags and alignment padding. In practice this will always be too big, as not + // all members will be used. + let size_of_stream_desc = size_of::<RenderPipelineStateStreamDesc>(); + let members = 20; // Approximate number of members we might push + let capacity = size_of_stream_desc + members * 8; // Extra space for tags and alignment + Self { + bytes: Vec::with_capacity(capacity), + _marker: core::marker::PhantomData, + } + } + + /// Align the internal byte buffer to the given alignment, + /// padding with zeros as necessary. + fn align_to(&mut self, alignment: usize) { + let aligned_length = self.bytes.len().next_multiple_of(alignment); + self.bytes.resize(aligned_length, 0); + } + + /// Adds a subobject to the pipeline state stream. + fn add_object<T: RenderPipelineStreamObject>(&mut self, object: T) { + // Ensure 8-byte alignment for the subobject start. + self.align_to(8); + + // Append the type tag (u32) + let tag: u32 = T::SUBOBJECT_TYPE.0 as u32; + self.bytes.extend_from_slice(&tag.to_ne_bytes()); + + // Align the data to its natural alignment. + self.align_to(align_of_val::<T>(&object)); + + // Append the data itself, as raw bytes + let data_ptr: *const T = &object; + let data_u8_ptr: *const u8 = data_ptr.cast::<u8>(); + let data_size = size_of_val::<T>(&object); + let slice = unsafe { core::slice::from_raw_parts::<u8>(data_u8_ptr, data_size) }; + self.bytes.extend_from_slice(slice); + } + + /// Creates a pipeline state object from the stream. + /// + /// Safety: + /// - All unsafety invariants required by [`ID3D12Device2::CreatePipelineState`] must be upheld by the caller. + pub unsafe fn create_pipeline_state( + &mut self, + device: &ID3D12Device2, + ) -> windows::core::Result<ID3D12PipelineState> { + let stream_desc = D3D12_PIPELINE_STATE_STREAM_DESC { + SizeInBytes: self.bytes.len(), + pPipelineStateSubobjectStream: self.bytes.as_mut_ptr().cast(), + }; + + // Safety: lifetime on Self preserved the contents + // of the stream. Other unsafety invariants are upheld by the caller. + unsafe { device.CreatePipelineState(&stream_desc) } + } +} + +#[repr(C)] +#[derive(Debug)] +pub struct RenderPipelineStateStreamDesc<'a> { + pub root_signature: Option<&'a ID3D12RootSignature>, + pub pixel_shader: D3D12_SHADER_BYTECODE, + pub blend_state: D3D12_BLEND_DESC, + pub sample_mask: u32, + pub rasterizer_state: D3D12_RASTERIZER_DESC, + pub depth_stencil_state: D3D12_DEPTH_STENCIL_DESC, + pub primitive_topology_type: D3D12_PRIMITIVE_TOPOLOGY_TYPE, + pub rtv_formats: D3D12_RT_FORMAT_ARRAY, + pub dsv_format: DXGI_FORMAT, + pub sample_desc: DXGI_SAMPLE_DESC, + pub node_mask: u32, + pub cached_pso: D3D12_CACHED_PIPELINE_STATE, + pub flags: D3D12_PIPELINE_STATE_FLAGS, + pub view_instancing: Option<D3D12_VIEW_INSTANCING_DESC>, + + // Vertex pipeline specific + pub vertex_shader: D3D12_SHADER_BYTECODE, + pub input_layout: D3D12_INPUT_LAYOUT_DESC, + pub index_buffer_strip_cut_value: D3D12_INDEX_BUFFER_STRIP_CUT_VALUE, + pub stream_output: D3D12_STREAM_OUTPUT_DESC, + + // Mesh pipeline specific + pub task_shader: D3D12_SHADER_BYTECODE, + pub mesh_shader: D3D12_SHADER_BYTECODE, +} + +impl RenderPipelineStateStreamDesc<'_> { + pub fn to_stream(&self) -> RenderPipelineStateStream<'_> { + let mut stream = RenderPipelineStateStream::new(); + + // Importantly here, the ID3D12RootSignature _itself_ is the pointer we're + // trying to serialize into the stream, not a pointer to the pointer. + // + // This is correct because as_raw() returns turns that smart object into the raw + // pointer that _is_ the com object handle. + let root_sig_pointer = self + .root_signature + .map(|a| NonNull::new(a.as_raw()).unwrap()); + // Because the stream object borrows from self for its entire lifetime, + // it is safe to store the pointer into it. + stream.add_object(RootSignature(root_sig_pointer)); + + stream.add_object(self.blend_state); + stream.add_object(SampleMask(self.sample_mask)); + stream.add_object(self.rasterizer_state); + stream.add_object(self.depth_stencil_state); + stream.add_object(self.primitive_topology_type); + if self.rtv_formats.NumRenderTargets != 0 { + stream.add_object(self.rtv_formats); + } + if self.dsv_format != DXGI_FORMAT_UNKNOWN { + stream.add_object(self.dsv_format); + } + stream.add_object(self.sample_desc); + if self.node_mask != 0 { + stream.add_object(NodeMask(self.node_mask)); + } + if !self.cached_pso.pCachedBlob.is_null() { + stream.add_object(self.cached_pso); + } + stream.add_object(self.flags); + if let Some(view_instancing) = self.view_instancing { + stream.add_object(view_instancing); + } + if !self.pixel_shader.pShaderBytecode.is_null() { + stream.add_object(PixelShader(self.pixel_shader)); + } + if !self.vertex_shader.pShaderBytecode.is_null() { + stream.add_object(VertexShader(self.vertex_shader)); + stream.add_object(self.input_layout); + stream.add_object(self.index_buffer_strip_cut_value); + stream.add_object(self.stream_output); + } + if !self.task_shader.pShaderBytecode.is_null() { + stream.add_object(TaskShader(self.task_shader)); + } + if !self.mesh_shader.pShaderBytecode.is_null() { + stream.add_object(MeshShader(self.mesh_shader)); + } + + stream + } + + /// Returns a traditional D3D12_GRAPHICS_PIPELINE_STATE_DESC. + /// + /// Safety: + /// - This returned struct must not outlive self. + pub unsafe fn to_graphics_pipeline_descriptor(&self) -> D3D12_GRAPHICS_PIPELINE_STATE_DESC { + D3D12_GRAPHICS_PIPELINE_STATE_DESC { + pRootSignature: if let Some(rsig) = self.root_signature { + unsafe { borrow_interface_temporarily(rsig) } + } else { + ManuallyDrop::new(None) + }, + VS: self.vertex_shader, + PS: self.pixel_shader, + DS: D3D12_SHADER_BYTECODE::default(), + HS: D3D12_SHADER_BYTECODE::default(), + GS: D3D12_SHADER_BYTECODE::default(), + StreamOutput: self.stream_output, + BlendState: self.blend_state, + SampleMask: self.sample_mask, + RasterizerState: self.rasterizer_state, + DepthStencilState: self.depth_stencil_state, + InputLayout: self.input_layout, + IBStripCutValue: self.index_buffer_strip_cut_value, + PrimitiveTopologyType: self.primitive_topology_type, + NumRenderTargets: self.rtv_formats.NumRenderTargets, + RTVFormats: self.rtv_formats.RTFormats, + DSVFormat: self.dsv_format, + SampleDesc: self.sample_desc, + NodeMask: self.node_mask, + CachedPSO: self.cached_pso, + Flags: self.flags, + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn wrappers() { + assert_eq!(size_of::<RootSignature>(), size_of::<ID3D12RootSignature>()); + assert_eq!( + align_of::<RootSignature>(), + align_of::<ID3D12RootSignature>() + ) + } + + implement_stream_object!(unsafe u16 => D3D12_PIPELINE_STATE_SUBOBJECT_TYPE(1)); + implement_stream_object!(unsafe u32 => D3D12_PIPELINE_STATE_SUBOBJECT_TYPE(2)); + implement_stream_object!(unsafe u64 => D3D12_PIPELINE_STATE_SUBOBJECT_TYPE(3)); + + #[test] + fn stream() { + let mut stream = RenderPipelineStateStream::new(); + + stream.add_object(42u16); + stream.add_object(84u32); + stream.add_object(168u64); + + assert_eq!(stream.bytes.len(), 32); + + // Object 1: u16 + + // Tag at the beginning + assert_eq!(&stream.bytes[0..4], &1u32.to_ne_bytes()); + // Data tucked in, aligned to the natural alignment of u16 + assert_eq!(&stream.bytes[4..6], &42u16.to_ne_bytes()); + // Padding to align the next subobject to an 8 byte boundary. + assert_eq!(&stream.bytes[6..8], &[0, 0]); + + // Object 2: u32 + + // Tag at the beginning + assert_eq!(&stream.bytes[8..12], &2u32.to_ne_bytes()); + // Data tucked in, aligned to the natural alignment of u32 + assert_eq!(&stream.bytes[12..16], &84u32.to_ne_bytes()); + + // Object 3: u64 + + // Tag at the beginning + assert_eq!(&stream.bytes[16..20], &3u32.to_ne_bytes()); + // Padding to align the u64 to an 8 byte boundary. + assert_eq!(&stream.bytes[20..24], &[0, 0, 0, 0]); + // Data tucked in, aligned to the natural alignment of u64 + assert_eq!(&stream.bytes[24..32], &168u64.to_ne_bytes()); + } +} diff --git a/app/vendor/rune/vendor/wgpu-hal/src/dx12/sampler.rs b/app/vendor/rune/vendor/wgpu-hal/src/dx12/sampler.rs new file mode 100644 index 0000000..4b58a0b --- /dev/null +++ b/app/vendor/rune/vendor/wgpu-hal/src/dx12/sampler.rs @@ -0,0 +1,252 @@ +//! Sampler management for DX12. +//! +//! Nearly identical to the Vulkan sampler cache, with added descriptor heap management. + +use alloc::vec::Vec; + +use hashbrown::{hash_map::Entry, HashMap}; + +use ordered_float::OrderedFloat; +use parking_lot::Mutex; +use windows::Win32::Graphics::Direct3D12::*; + +use crate::dx12::HResult; + +/// The index of a sampler in the global sampler heap. +/// +/// This is a type-safe, transparent wrapper around a u32. +#[repr(transparent)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub(crate) struct SamplerIndex(u32); + +/// [`D3D12_SAMPLER_DESC`] is not hashable, so we wrap it in a newtype that is. +/// +/// We use [`OrderedFloat`] to allow for floating point values to be compared and +/// hashed in a defined way. +#[derive(Debug, Copy, Clone)] +struct HashableSamplerDesc(D3D12_SAMPLER_DESC); + +impl PartialEq for HashableSamplerDesc { + fn eq(&self, other: &Self) -> bool { + self.0.Filter == other.0.Filter + && self.0.AddressU == other.0.AddressU + && self.0.AddressV == other.0.AddressV + && self.0.AddressW == other.0.AddressW + && OrderedFloat(self.0.MipLODBias) == OrderedFloat(other.0.MipLODBias) + && self.0.MaxAnisotropy == other.0.MaxAnisotropy + && self.0.ComparisonFunc == other.0.ComparisonFunc + && self.0.BorderColor.map(OrderedFloat) == other.0.BorderColor.map(OrderedFloat) + && OrderedFloat(self.0.MinLOD) == OrderedFloat(other.0.MinLOD) + && OrderedFloat(self.0.MaxLOD) == OrderedFloat(other.0.MaxLOD) + } +} + +impl Eq for HashableSamplerDesc {} + +impl core::hash::Hash for HashableSamplerDesc { + fn hash<H: core::hash::Hasher>(&self, state: &mut H) { + self.0.Filter.0.hash(state); + self.0.AddressU.0.hash(state); + self.0.AddressV.0.hash(state); + self.0.AddressW.0.hash(state); + OrderedFloat(self.0.MipLODBias).hash(state); + self.0.MaxAnisotropy.hash(state); + self.0.ComparisonFunc.0.hash(state); + self.0.BorderColor.map(OrderedFloat).hash(state); + OrderedFloat(self.0.MinLOD).hash(state); + OrderedFloat(self.0.MaxLOD).hash(state); + } +} + +/// Entry in the sampler cache. +struct CacheEntry { + index: SamplerIndex, + ref_count: u32, +} + +/// Container for the mutable management state of the sampler heap. +/// +/// We have this separated, using interior mutability, to allow for the outside world +/// to access the heap directly without needing to take the lock. +pub(crate) struct SamplerHeapState { + /// Mapping from the sampler description to the index within the heap and the refcount. + mapping: HashMap<HashableSamplerDesc, CacheEntry>, + /// List of free sampler indices. + freelist: Vec<SamplerIndex>, +} + +/// Global sampler heap for the device. +/// +/// As D3D12 only allows 2048 samplers to be in a single heap, we need to cache +/// samplers aggressively and refer to them in shaders by index. +pub(crate) struct SamplerHeap { + /// Mutable management state of the sampler heap. + state: Mutex<SamplerHeapState>, + + /// The heap itself. + heap: ID3D12DescriptorHeap, + /// The CPU-side handle to the first descriptor in the heap. + /// + /// Both the CPU and GPU handles point to the same descriptor, just in + /// different contexts. + heap_cpu_start_handle: D3D12_CPU_DESCRIPTOR_HANDLE, + /// The GPU-side handle to the first descriptor in the heap. + /// + /// Both the CPU and GPU handles point to the same descriptor, just in + /// different contexts. + heap_gpu_start_handle: D3D12_GPU_DESCRIPTOR_HANDLE, + + /// This is the device-specific size of sampler descriptors. + descriptor_stride: u32, +} + +impl SamplerHeap { + pub fn new( + device: &ID3D12Device, + private_caps: &super::PrivateCapabilities, + ) -> Result<Self, crate::DeviceError> { + profiling::scope!("SamplerHeap::new"); + + // WARP can report this as 2M or more. We clamp it to 64k to be safe. + const SAMPLER_HEAP_SIZE_CLAMP: u32 = 64 * 1024; + + let max_unique_samplers = private_caps + .max_sampler_descriptor_heap_size + .min(SAMPLER_HEAP_SIZE_CLAMP); + + let desc = D3D12_DESCRIPTOR_HEAP_DESC { + Type: D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER, + NumDescriptors: max_unique_samplers, + Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, + NodeMask: 0, + }; + let heap = unsafe { device.CreateDescriptorHeap::<ID3D12DescriptorHeap>(&desc) } + .into_device_result("Failed to create global GPU-Visible Sampler Descriptor Heap")?; + + let heap_cpu_start_handle = unsafe { heap.GetCPUDescriptorHandleForHeapStart() }; + let heap_gpu_start_handle = unsafe { heap.GetGPUDescriptorHandleForHeapStart() }; + + let descriptor_stride = + unsafe { device.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER) }; + + Ok(Self { + state: Mutex::new(SamplerHeapState { + mapping: HashMap::new(), + // Reverse so that samplers get allocated starting from zero. + freelist: (0..max_unique_samplers).map(SamplerIndex).rev().collect(), + }), + heap, + heap_cpu_start_handle, + heap_gpu_start_handle, + descriptor_stride, + }) + } + + /// Returns a reference to the raw descriptor heap. + pub fn heap(&self) -> &ID3D12DescriptorHeap { + &self.heap + } + + /// Returns a reference the handle to be bound to the descriptor table. + pub fn gpu_descriptor_table(&self) -> D3D12_GPU_DESCRIPTOR_HANDLE { + self.heap_gpu_start_handle + } + + /// Add a sampler with the given description to the heap. + /// + /// If the sampler already exists, the refcount is incremented and the existing index is returned. + /// + /// If the sampler does not exist, a new sampler is created and the index is returned. + /// + /// If the heap is full, an error is returned. + pub fn create_sampler( + &self, + device: &ID3D12Device, + desc: D3D12_SAMPLER_DESC, + ) -> Result<SamplerIndex, crate::DeviceError> { + profiling::scope!("SamplerHeap::create_sampler"); + + let hashable_desc = HashableSamplerDesc(desc); + + // Eagarly dereference the lock to allow split borrows. + let state = &mut *self.state.lock(); + + // Lookup the sampler in the mapping. + match state.mapping.entry(hashable_desc) { + Entry::Occupied(occupied_entry) => { + // We have found a match, so increment the refcount and return the index. + let entry = occupied_entry.into_mut(); + entry.ref_count += 1; + Ok(entry.index) + } + Entry::Vacant(vacant_entry) => { + // We need to create a new sampler. + + // Try to get a new index from the freelist. + let Some(index) = state.freelist.pop() else { + // If the freelist is empty, we have hit the maximum number of samplers. + log::error!("There is no more room in the global sampler heap for more unique samplers. Your device supports a maximum of {} unique samplers.", state.mapping.len()); + return Err(crate::DeviceError::OutOfMemory); + }; + + // Compute the CPU side handle for the new sampler. + let handle = D3D12_CPU_DESCRIPTOR_HANDLE { + ptr: self.heap_cpu_start_handle.ptr + + self.descriptor_stride as usize * index.0 as usize, + }; + + unsafe { + device.CreateSampler(&desc, handle); + } + + // Insert the new sampler into the mapping. + vacant_entry.insert(CacheEntry { + index, + ref_count: 1, + }); + + Ok(index) + } + } + } + + /// Decrement the refcount of the sampler with the given description. + /// + /// If the refcount reaches zero, the sampler is destroyed and the index is returned to the freelist. + /// + /// The provided index is checked against the index of the sampler with the given description, ensuring + /// that there isn't a clerical error from the caller. + pub fn destroy_sampler(&self, desc: D3D12_SAMPLER_DESC, provided_index: SamplerIndex) { + profiling::scope!("SamplerHeap::destroy_sampler"); + + // Eagarly dereference the lock to allow split borrows. + let state = &mut *self.state.lock(); + + // Get the index of the sampler to destroy. + let Entry::Occupied(mut hash_map_entry) = state.mapping.entry(HashableSamplerDesc(desc)) + else { + log::error!( + "Tried to destroy a sampler that doesn't exist. Sampler description: {desc:#?}" + ); + return; + }; + let cache_entry = hash_map_entry.get_mut(); + + // Ensure that the provided index matches the index of the sampler to destroy. + assert_eq!( + cache_entry.index, provided_index, + "Mismatched sampler index, this is an implementation bug" + ); + + // Decrement the refcount of the sampler. + cache_entry.ref_count -= 1; + + // If we are the last reference, remove the sampler from the mapping and return the index to the freelist. + // + // As samplers only exist as descriptors in the heap, there is nothing needed to be done to destroy the sampler. + if cache_entry.ref_count == 0 { + state.freelist.push(cache_entry.index); + hash_map_entry.remove(); + } + } +} diff --git a/app/vendor/rune/vendor/wgpu-hal/src/dx12/shader_compilation.rs b/app/vendor/rune/vendor/wgpu-hal/src/dx12/shader_compilation.rs new file mode 100644 index 0000000..dcb167c --- /dev/null +++ b/app/vendor/rune/vendor/wgpu-hal/src/dx12/shader_compilation.rs @@ -0,0 +1,453 @@ +use alloc::{string::String, vec::Vec}; +use core::ffi::CStr; +use std::path::PathBuf; + +use crate::auxil::dxgi::result::HResult; +use thiserror::Error; +use windows::{ + core::{Interface, PCSTR, PCWSTR}, + Win32::Graphics::Direct3D::{Dxc, Fxc, ID3DBlob, D3D_SHADER_MACRO}, +}; + +pub(super) enum CompilerContainer { + Fxc(CompilerFxc), + DynamicDxc(CompilerDynamicDxc), + #[cfg_attr(not(static_dxc), allow(unused))] + StaticDxc(CompilerStaticDxc), +} + +pub(super) struct CompilerFxc { + /// Loaded on the first compile: an app whose shaders all come precompiled never loads it. + fxc: std::sync::OnceLock<Result<FxcLib, String>>, +} + +pub(super) struct CompilerDynamicDxc { + max_shader_model: wgt::DxcShaderModel, + compiler: Dxc::IDxcCompiler3, + // Has to be held onto for the lifetime of the device otherwise shaders will fail to compile. + // Only needed when using dynamic linking. + _dxc: DxcLib, +} + +pub(super) struct CompilerStaticDxc { + max_shader_model: wgt::DxcShaderModel, + compiler: Dxc::IDxcCompiler3, +} + +#[derive(Debug, Error)] +pub(super) enum GetContainerError { + #[error(transparent)] + Device(#[from] crate::DeviceError), + #[error("Failed to load {0}: {1}")] + FailedToLoad(&'static str, libloading::Error), +} + +impl CompilerContainer { + pub(super) fn new_fxc() -> Result<Self, GetContainerError> { + Ok(Self::Fxc(CompilerFxc { fxc: std::sync::OnceLock::new() })) + } + + pub(super) fn new_dynamic_dxc(dxc_path: PathBuf) -> Result<Self, GetContainerError> { + let dxc = DxcLib::new_dynamic(dxc_path) + .map_err(|e| GetContainerError::FailedToLoad("dxcompiler.dll", e))?; + + let compiler = dxc.create_instance::<Dxc::IDxcCompiler3>()?; + + let (mut major, mut minor) = (1, 0); + // DXC 1.0 didn't support this. If the cast fails assume it is DXC 1.0. + if let Ok(version_info) = compiler.cast::<Dxc::IDxcVersionInfo>() { + unsafe { + version_info.GetVersion(&mut major, &mut minor).unwrap(); + } + } + + Ok(Self::DynamicDxc(CompilerDynamicDxc { + max_shader_model: wgt::DxcShaderModel::from_dxc_version(major, minor), + compiler, + _dxc: dxc, + })) + } + + /// Creates a [`CompilerContainer`] that delegates to the statically-linked version of DXC. + pub(super) fn new_static_dxc() -> Result<CompilerContainer, crate::DeviceError> { + #[cfg(static_dxc)] + { + unsafe { + let compiler = dxc_create_instance::<Dxc::IDxcCompiler3>(|clsid, iid, ppv| { + windows_core::HRESULT(mach_dxcompiler_rs::DxcCreateInstance( + clsid.cast(), + iid.cast(), + ppv, + )) + })?; + + Ok(CompilerContainer::StaticDxc(CompilerStaticDxc { + max_shader_model: wgt::DxcShaderModel::V6_7, + compiler, + })) + } + } + #[cfg(not(static_dxc))] + { + panic!("Attempted to create a static DXC shader compiler, but the static-dxc feature was not enabled") + } + } + + pub(super) fn max_shader_model(&self) -> Option<wgt::DxcShaderModel> { + match self { + CompilerContainer::Fxc(..) => None, + CompilerContainer::DynamicDxc(CompilerDynamicDxc { + max_shader_model, .. + }) + | CompilerContainer::StaticDxc(CompilerStaticDxc { + max_shader_model, .. + }) => Some(max_shader_model.clone()), + } + } + + pub(super) fn compile( + &self, + device: &super::Device, + source: &str, + source_name: Option<&CStr>, + raw_ep: &str, + stage_bit: wgt::ShaderStages, + full_stage: &str, + ) -> Result<super::CompiledShader, crate::PipelineError> { + match self { + CompilerContainer::Fxc(CompilerFxc { fxc }) => compile_fxc( + device, + source, + source_name, + raw_ep, + stage_bit, + full_stage, + fxc.get_or_init(|| FxcLib::new_dynamic().map_err(|e| format!("{e}"))) + .as_ref() + .map_err(|e| crate::PipelineError::Linkage(stage_bit, e.clone()))?, + ), + CompilerContainer::DynamicDxc(CompilerDynamicDxc { compiler, .. }) + | CompilerContainer::StaticDxc(CompilerStaticDxc { compiler, .. }) => compile_dxc( + device, + source, + source_name, + raw_ep, + stage_bit, + full_stage, + compiler, + ), + } + } +} + +type D3DCompileFn = unsafe extern "system" fn( + psrcdata: *const core::ffi::c_void, + srcdatasize: usize, + psourcename: PCSTR, + pdefines: *const D3D_SHADER_MACRO, + pinclude: *mut core::ffi::c_void, + pentrypoint: PCSTR, + ptarget: PCSTR, + flags1: u32, + flags2: u32, + ppcode: *mut *mut core::ffi::c_void, + pperrormsgs: *mut *mut core::ffi::c_void, +) -> windows_core::HRESULT; + +#[derive(Debug)] +struct FxcLib { + // `d3dcompile_fn` points into `_lib`, so `_lib` must be held for as long + // as we want to keep compiling shaders with FXC. + _lib: crate::dx12::DynLib, + d3dcompile_fn: D3DCompileFn, +} + +impl FxcLib { + const PATH: &str = "d3dcompiler_47.dll"; + + fn new_dynamic() -> Result<Self, GetContainerError> { + unsafe { + let lib = crate::dx12::DynLib::new_system(Self::PATH) + .map_err(|e| GetContainerError::FailedToLoad(FxcLib::PATH, e))?; + let d3dcompile_fn: D3DCompileFn = *lib.get::<D3DCompileFn>(c"D3DCompile".to_bytes())?; + + Ok(Self { + _lib: lib, + d3dcompile_fn, + }) + } + } + + #[allow(clippy::too_many_arguments)] + fn compile( + &self, + source: &str, + source_name: Option<&CStr>, + raw_ep: &str, + full_stage: &str, + compile_flags: u32, + shader_data: &mut Option<ID3DBlob>, + error: &mut Option<ID3DBlob>, + ) -> Result<windows_core::Result<()>, crate::DeviceError> { + unsafe { + let raw_ep = alloc::ffi::CString::new(raw_ep).unwrap(); + let full_stage = alloc::ffi::CString::new(full_stage).unwrap(); + + // If no name has been set, D3DCompile wants the null pointer. + let source_name = source_name + .map(|cstr| cstr.as_ptr().cast()) + .unwrap_or(core::ptr::null()); + + let shader_data: *mut Option<ID3DBlob> = shader_data; + let error: *mut Option<ID3DBlob> = error; + + { + profiling::scope!("Fxc::D3DCompile"); + Ok((self.d3dcompile_fn)( + source.as_ptr().cast(), + source.len(), + PCSTR(source_name), + core::ptr::null(), + core::ptr::null_mut(), + PCSTR(raw_ep.as_ptr().cast()), + PCSTR(full_stage.as_ptr().cast()), + compile_flags, + 0, + shader_data.cast(), + error.cast(), + ) + .ok()) + } + } + } +} + +fn compile_fxc( + device: &super::Device, + source: &str, + source_name: Option<&CStr>, + raw_ep: &str, + stage_bit: wgt::ShaderStages, + full_stage: &str, + fxc: &FxcLib, +) -> Result<super::CompiledShader, crate::PipelineError> { + profiling::scope!("compile_fxc"); + let mut compile_flags = Fxc::D3DCOMPILE_ENABLE_STRICTNESS; + if device + .shared + .private_caps + .instance_flags + .contains(wgt::InstanceFlags::DEBUG) + { + compile_flags |= Fxc::D3DCOMPILE_DEBUG | Fxc::D3DCOMPILE_SKIP_OPTIMIZATION; + } + + let mut shader_data = None; + let mut error = None; + let hr = fxc.compile( + source, + source_name, + raw_ep, + full_stage, + compile_flags, + &mut shader_data, + &mut error, + )?; + + match hr { + Ok(()) => { + let shader_data = shader_data.unwrap(); + Ok(super::CompiledShader::Fxc(shader_data)) + } + Err(e) => { + let mut full_msg = format!("FXC D3DCompile error ({e})"); + if let Some(error) = error { + use core::fmt::Write as _; + let message = unsafe { + core::slice::from_raw_parts( + error.GetBufferPointer().cast(), + error.GetBufferSize(), + ) + }; + let _ = write!(full_msg, ": {}", String::from_utf8_lossy(message)); + } + Err(crate::PipelineError::Linkage(stage_bit, full_msg)) + } + } +} + +trait DxcObj: Interface { + const CLSID: windows::core::GUID; +} +impl DxcObj for Dxc::IDxcCompiler3 { + const CLSID: windows::core::GUID = Dxc::CLSID_DxcCompiler; +} +impl DxcObj for Dxc::IDxcUtils { + const CLSID: windows::core::GUID = Dxc::CLSID_DxcUtils; +} +impl DxcObj for Dxc::IDxcValidator { + const CLSID: windows::core::GUID = Dxc::CLSID_DxcValidator; +} + +#[derive(Debug)] +struct DxcLib { + lib: crate::dx12::DynLib, +} + +impl DxcLib { + fn new_dynamic(lib_path: PathBuf) -> Result<Self, libloading::Error> { + unsafe { crate::dx12::DynLib::new(lib_path).map(|lib| Self { lib }) } + } + + pub fn create_instance<T: DxcObj>(&self) -> Result<T, crate::DeviceError> { + unsafe { + type DxcCreateInstanceFn = unsafe extern "system" fn( + rclsid: *const windows_core::GUID, + riid: *const windows_core::GUID, + ppv: *mut *mut core::ffi::c_void, + ) + -> windows_core::HRESULT; + + let func: libloading::Symbol<DxcCreateInstanceFn> = + self.lib.get(c"DxcCreateInstance".to_bytes())?; + dxc_create_instance::<T>(|clsid, iid, ppv| func(clsid, iid, ppv)) + } + } +} + +/// Invokes the provided library function to create a DXC object. +unsafe fn dxc_create_instance<T: DxcObj>( + f: impl Fn( + *const windows_core::GUID, + *const windows_core::GUID, + *mut *mut core::ffi::c_void, + ) -> windows_core::HRESULT, +) -> Result<T, crate::DeviceError> { + let mut result__ = None; + f(&T::CLSID, &T::IID, <*mut _>::cast(&mut result__)) + .ok() + .into_device_result("DxcCreateInstance")?; + result__.ok_or(crate::DeviceError::Unexpected) +} + +/// Owned PCWSTR +#[allow(clippy::upper_case_acronyms)] +struct OPCWSTR { + inner: Vec<u16>, +} + +impl OPCWSTR { + fn new(s: &str) -> Self { + let mut inner: Vec<_> = s.encode_utf16().collect(); + inner.push(0); + Self { inner } + } + + fn ptr(&self) -> PCWSTR { + PCWSTR(self.inner.as_ptr()) + } +} + +fn get_output<T: Interface>( + res: &Dxc::IDxcResult, + kind: Dxc::DXC_OUT_KIND, +) -> Result<T, crate::DeviceError> { + let mut result__: Option<T> = None; + unsafe { res.GetOutput::<T>(kind, &mut None, <*mut _>::cast(&mut result__)) } + .into_device_result("GetOutput")?; + result__.ok_or(crate::DeviceError::Unexpected) +} + +fn as_err_str(blob: &Dxc::IDxcBlobUtf8) -> Result<&str, crate::DeviceError> { + let ptr = unsafe { blob.GetStringPointer() }; + let len = unsafe { blob.GetStringLength() }; + core::str::from_utf8(unsafe { core::slice::from_raw_parts(ptr.0, len) }) + .map_err(|_| crate::DeviceError::Unexpected) +} + +fn compile_dxc( + device: &crate::dx12::Device, + source: &str, + source_name: Option<&CStr>, + raw_ep: &str, + stage_bit: wgt::ShaderStages, + full_stage: &str, + compiler: &Dxc::IDxcCompiler3, +) -> Result<crate::dx12::CompiledShader, crate::PipelineError> { + profiling::scope!("compile_dxc"); + + let source_name = source_name.and_then(|cstr| cstr.to_str().ok()); + + let source_name = source_name.map(OPCWSTR::new); + let raw_ep = OPCWSTR::new(raw_ep); + let full_stage = OPCWSTR::new(full_stage); + + let mut compile_args = arrayvec::ArrayVec::<PCWSTR, 13>::new_const(); + + if let Some(source_name) = source_name.as_ref() { + compile_args.push(source_name.ptr()) + } + + compile_args.extend([ + windows::core::w!("-E"), + raw_ep.ptr(), + windows::core::w!("-T"), + full_stage.ptr(), + windows::core::w!("-HV"), + windows::core::w!("2018"), // Use HLSL 2018, Naga doesn't supported 2021 yet. + windows::core::w!("-no-warnings"), + Dxc::DXC_ARG_ENABLE_STRICTNESS, + ]); + + if device + .shared + .private_caps + .instance_flags + .contains(wgt::InstanceFlags::DEBUG) + && !device + .shared + .private_caps + .workarounds + .avoid_shader_debug_info + { + compile_args.push(Dxc::DXC_ARG_DEBUG); + compile_args.push(Dxc::DXC_ARG_SKIP_OPTIMIZATIONS); + } + + if device + .features + .intersects(wgt::Features::SHADER_F16 | wgt::Features::SHADER_I16) + { + compile_args.push(windows::core::w!("-enable-16bit-types")); + } + + let buffer = Dxc::DxcBuffer { + Ptr: source.as_ptr().cast(), + Size: source.len(), + Encoding: Dxc::DXC_CP_UTF8.0, + }; + + let compile_res: Dxc::IDxcResult = + unsafe { compiler.Compile(&buffer, Some(&compile_args), None) } + .into_device_result("Compile")?; + + drop(compile_args); + drop(source_name); + drop(raw_ep); + drop(full_stage); + + let err_blob = get_output::<Dxc::IDxcBlobUtf8>(&compile_res, Dxc::DXC_OUT_ERRORS)?; + + let len = unsafe { err_blob.GetStringLength() }; + if len != 0 { + let err = as_err_str(&err_blob)?; + return Err(crate::PipelineError::Linkage( + stage_bit, + format!("DXC compile error: {err}"), + )); + } + + let blob = get_output::<Dxc::IDxcBlob>(&compile_res, Dxc::DXC_OUT_OBJECT)?; + + Ok(crate::dx12::CompiledShader::Dxc(blob)) +} diff --git a/app/vendor/rune/vendor/wgpu-hal/src/dx12/suballocation.rs b/app/vendor/rune/vendor/wgpu-hal/src/dx12/suballocation.rs new file mode 100644 index 0000000..89c7dc4 --- /dev/null +++ b/app/vendor/rune/vendor/wgpu-hal/src/dx12/suballocation.rs @@ -0,0 +1,603 @@ +use alloc::sync::Arc; + +use gpu_allocator::{d3d12::AllocationCreateDesc, MemoryLocation}; +use parking_lot::Mutex; +use windows::Win32::Graphics::{Direct3D12, Dxgi}; + +use crate::{ + auxil::dxgi::{name::ObjectExt as _, result::HResult as _}, + dx12::conv, + AllocationSizes, +}; + +#[derive(Debug)] +pub(crate) enum AllocationType { + Buffer, + Texture, + AccelerationStructure, +} + +#[derive(Debug)] +enum AllocationInner { + /// This resource is suballocated from a heap. + Placed { + inner: gpu_allocator::d3d12::Allocation, + }, + /// This resource is a committed resource and does not belong to a + /// suballocated heap. We store an approximate size, so we can manage our counters + /// correctly. + /// + /// This is only used for Intel Xe drivers, which have a bug that + /// prevents suballocation from working correctly. + Committed { size: u64 }, +} + +#[derive(Debug)] +pub(crate) struct Allocation { + inner: AllocationInner, + ty: AllocationType, +} + +impl Allocation { + pub fn placed(inner: gpu_allocator::d3d12::Allocation, ty: AllocationType) -> Self { + Self { + inner: AllocationInner::Placed { inner }, + ty, + } + } + + pub fn none(ty: AllocationType, size: u64) -> Self { + Self { + inner: AllocationInner::Committed { size }, + ty, + } + } + + pub fn size(&self) -> u64 { + match self.inner { + AllocationInner::Placed { ref inner } => inner.size(), + AllocationInner::Committed { size } => size, + } + } +} + +#[derive(Clone)] +pub(crate) struct Allocator { + inner: Arc<Mutex<gpu_allocator::d3d12::Allocator>>, + device_memblock_size: u64, + host_memblock_size: u64, + pub memory_budget_thresholds: wgt::MemoryBudgetThresholds, +} + +impl Allocator { + pub(crate) fn new( + raw: &Direct3D12::ID3D12Device, + memory_hints: &wgt::MemoryHints, + memory_budget_thresholds: wgt::MemoryBudgetThresholds, + ) -> Result<Self, crate::DeviceError> { + let allocation_sizes = AllocationSizes::from_memory_hints(memory_hints); + let device_memblock_size = allocation_sizes.min_device_memblock_size; + let host_memblock_size = allocation_sizes.min_host_memblock_size; + + let allocator_desc = gpu_allocator::d3d12::AllocatorCreateDesc { + device: gpu_allocator::d3d12::ID3D12DeviceVersion::Device(raw.clone()), + debug_settings: Default::default(), + allocation_sizes: allocation_sizes.into(), + }; + + let allocator = gpu_allocator::d3d12::Allocator::new(&allocator_desc).inspect_err(|e| { + log::error!("Failed to create d3d12 allocator, error: {e}"); + })?; + + Ok(Self { + inner: Arc::new(Mutex::new(allocator)), + device_memblock_size, + host_memblock_size, + memory_budget_thresholds, + }) + } + + pub(crate) fn generate_report(&self) -> wgt::AllocatorReport { + let mut upstream = self.inner.lock().generate_report(); + + let allocations = upstream + .allocations + .iter_mut() + .map(|alloc| wgt::AllocationReport { + name: core::mem::take(&mut alloc.name), + offset: alloc.offset, + size: alloc.size, + }) + .collect(); + + let blocks = upstream + .blocks + .iter() + .map(|block| wgt::MemoryBlockReport { + size: block.size, + allocations: block.allocations.clone(), + }) + .collect(); + + wgt::AllocatorReport { + allocations, + blocks, + total_allocated_bytes: upstream.total_allocated_bytes, + total_reserved_bytes: upstream.total_capacity_bytes, + } + } +} + +/// To allow us to construct buffers from both a `Device` and `CommandEncoder` +/// without needing each function to take a million arguments, we create a +/// borrowed context struct that contains the relevant members. +pub(crate) struct DeviceAllocationContext<'a> { + pub(crate) raw: &'a Direct3D12::ID3D12Device, + pub(crate) shared: &'a super::DeviceShared, + pub(crate) mem_allocator: &'a Allocator, + pub(crate) counters: &'a wgt::HalCounters, +} + +impl<'a> From<&'a super::Device> for DeviceAllocationContext<'a> { + fn from(device: &'a super::Device) -> Self { + Self { + raw: &device.raw, + shared: &device.shared, + mem_allocator: &device.mem_allocator, + counters: &device.counters, + } + } +} + +impl<'a> From<&'a super::CommandEncoder> for DeviceAllocationContext<'a> { + fn from(encoder: &'a super::CommandEncoder) -> Self { + Self { + raw: &encoder.device, + shared: &encoder.shared, + mem_allocator: &encoder.mem_allocator, + counters: &encoder.counters, + } + } +} + +impl<'a> DeviceAllocationContext<'a> { + /////////////////////// + // Resource Creation // + /////////////////////// + + pub(crate) fn create_buffer( + &self, + desc: &crate::BufferDescriptor, + ) -> Result<(Direct3D12::ID3D12Resource, Allocation), crate::DeviceError> { + let is_cpu_read = desc.usage.contains(wgt::BufferUses::MAP_READ); + let is_cpu_write = desc.usage.contains(wgt::BufferUses::MAP_WRITE); + + let location = match (is_cpu_read, is_cpu_write) { + (true, true) => MemoryLocation::CpuToGpu, + (true, false) => MemoryLocation::GpuToCpu, + (false, true) => MemoryLocation::CpuToGpu, + (false, false) => MemoryLocation::GpuOnly, + }; + + let raw_desc = conv::map_buffer_descriptor(desc); + let allocation_info = + self.error_if_would_oom_on_resource_allocation(&raw_desc, location)?; + + let (resource, allocation) = if self.shared.private_caps.suballocation_supported { + self.create_placed_buffer(desc, raw_desc, allocation_info, location)? + } else { + self.create_committed_buffer(raw_desc, location)? + }; + + if let Some(label) = desc.label { + resource.set_name(label)?; + } + + self.counters.buffer_memory.add(allocation.size() as isize); + + Ok((resource, allocation)) + } + + pub(crate) fn create_texture( + &self, + desc: &crate::TextureDescriptor, + raw_desc: Direct3D12::D3D12_RESOURCE_DESC, + ) -> Result<(Direct3D12::ID3D12Resource, Allocation), crate::DeviceError> { + let location = MemoryLocation::GpuOnly; + let allocation_info = + self.error_if_would_oom_on_resource_allocation(&raw_desc, location)?; + + let (resource, allocation) = if self.shared.private_caps.suballocation_supported { + self.create_placed_texture(desc, raw_desc, allocation_info, location)? + } else { + self.create_committed_texture(desc, raw_desc)? + }; + + if let Some(label) = desc.label { + resource.set_name(label)?; + } + + self.counters.texture_memory.add(allocation.size() as isize); + + Ok((resource, allocation)) + } + + pub(crate) fn create_acceleration_structure( + &self, + desc: &crate::AccelerationStructureDescriptor, + raw_desc: Direct3D12::D3D12_RESOURCE_DESC, + ) -> Result<(Direct3D12::ID3D12Resource, Allocation), crate::DeviceError> { + let location = MemoryLocation::GpuOnly; + let allocation_info = + self.error_if_would_oom_on_resource_allocation(&raw_desc, location)?; + + let (resource, allocation) = if self.shared.private_caps.suballocation_supported { + self.create_placed_acceleration_structure(desc, raw_desc, allocation_info, location)? + } else { + self.create_committed_acceleration_structure(desc, raw_desc)? + }; + + if let Some(label) = desc.label { + resource.set_name(label)?; + } + + self.counters + .acceleration_structure_memory + .add(allocation.size() as isize); + + Ok((resource, allocation)) + } + + ////////////////////////// + // Resource Destruction // + ////////////////////////// + + pub(crate) fn free_resource( + &self, + resource: Direct3D12::ID3D12Resource, + allocation: Allocation, + ) { + // Make sure the resource is released before we free the allocation. + drop(resource); + + let counter = match allocation.ty { + AllocationType::Buffer => &self.counters.buffer_memory, + AllocationType::Texture => &self.counters.texture_memory, + AllocationType::AccelerationStructure => &self.counters.acceleration_structure_memory, + }; + counter.sub(allocation.size() as isize); + + if let AllocationInner::Placed { inner } = allocation.inner { + match self.mem_allocator.inner.lock().free(inner) { + Ok(_) => (), + // TODO: Don't panic here + Err(e) => panic!("Failed to destroy dx12 {:?}, {e}", allocation.ty), + }; + } + } + + /////////////////////////////// + // Placed Resource Creation /// + /////////////////////////////// + + fn create_placed_buffer( + &self, + desc: &crate::BufferDescriptor<'_>, + raw_desc: Direct3D12::D3D12_RESOURCE_DESC, + allocation_info: Direct3D12::D3D12_RESOURCE_ALLOCATION_INFO, + location: MemoryLocation, + ) -> Result<(Direct3D12::ID3D12Resource, Allocation), crate::DeviceError> { + let name = desc.label.unwrap_or("Unlabeled buffer"); + + let mut allocator = self.mem_allocator.inner.lock(); + + let allocation_desc = AllocationCreateDesc { + name, + location, + size: allocation_info.SizeInBytes, + alignment: allocation_info.Alignment, + resource_category: gpu_allocator::d3d12::ResourceCategory::from(&raw_desc), + }; + + let allocation = allocator.allocate(&allocation_desc)?; + let mut resource = None; + unsafe { + self.raw.CreatePlacedResource( + allocation.heap(), + allocation.offset(), + &raw_desc, + Direct3D12::D3D12_RESOURCE_STATE_COMMON, + None, + &mut resource, + ) + } + .into_device_result("Placed buffer creation")?; + + let resource = resource.ok_or(crate::DeviceError::Unexpected)?; + let wrapped_allocation = Allocation::placed(allocation, AllocationType::Buffer); + + Ok((resource, wrapped_allocation)) + } + + fn create_placed_texture( + &self, + desc: &crate::TextureDescriptor<'_>, + raw_desc: Direct3D12::D3D12_RESOURCE_DESC, + allocation_info: Direct3D12::D3D12_RESOURCE_ALLOCATION_INFO, + location: MemoryLocation, + ) -> Result<(Direct3D12::ID3D12Resource, Allocation), crate::DeviceError> { + let name = desc.label.unwrap_or("Unlabeled texture"); + + let mut allocator = self.mem_allocator.inner.lock(); + + let allocation_desc = AllocationCreateDesc { + name, + location, + size: allocation_info.SizeInBytes, + alignment: allocation_info.Alignment, + resource_category: gpu_allocator::d3d12::ResourceCategory::from(&raw_desc), + }; + + let allocation = allocator.allocate(&allocation_desc)?; + let mut resource = None; + unsafe { + self.raw.CreatePlacedResource( + allocation.heap(), + allocation.offset(), + &raw_desc, + Direct3D12::D3D12_RESOURCE_STATE_COMMON, + None, // clear value + &mut resource, + ) + } + .into_device_result("Placed texture creation")?; + + let resource = resource.ok_or(crate::DeviceError::Unexpected)?; + let wrapped_allocation = Allocation::placed(allocation, AllocationType::Texture); + + Ok((resource, wrapped_allocation)) + } + + fn create_placed_acceleration_structure( + &self, + desc: &crate::AccelerationStructureDescriptor<'_>, + raw_desc: Direct3D12::D3D12_RESOURCE_DESC, + allocation_info: Direct3D12::D3D12_RESOURCE_ALLOCATION_INFO, + location: MemoryLocation, + ) -> Result<(Direct3D12::ID3D12Resource, Allocation), crate::DeviceError> { + let name = desc.label.unwrap_or("Unlabeled acceleration structure"); + + let mut allocator = self.mem_allocator.inner.lock(); + + let allocation_desc = AllocationCreateDesc { + name, + location, + size: allocation_info.SizeInBytes, + alignment: allocation_info.Alignment, + resource_category: gpu_allocator::d3d12::ResourceCategory::from(&raw_desc), + }; + + let allocation = allocator.allocate(&allocation_desc)?; + let mut resource = None; + unsafe { + self.raw.CreatePlacedResource( + allocation.heap(), + allocation.offset(), + &raw_desc, + Direct3D12::D3D12_RESOURCE_STATE_RAYTRACING_ACCELERATION_STRUCTURE, + None, + &mut resource, + ) + } + .into_device_result("Placed acceleration structure creation")?; + + let resource = resource.ok_or(crate::DeviceError::Unexpected)?; + let wrapped_allocation = + Allocation::placed(allocation, AllocationType::AccelerationStructure); + + Ok((resource, wrapped_allocation)) + } + + ///////////////////////////////// + // Committed Resource Creation // + ///////////////////////////////// + + fn create_committed_buffer( + &self, + raw_desc: Direct3D12::D3D12_RESOURCE_DESC, + location: MemoryLocation, + ) -> Result<(Direct3D12::ID3D12Resource, Allocation), crate::DeviceError> { + let is_uma = matches!( + self.shared.private_caps.memory_architecture, + crate::dx12::MemoryArchitecture::Unified { .. } + ); + + let heap_properties = Direct3D12::D3D12_HEAP_PROPERTIES { + Type: Direct3D12::D3D12_HEAP_TYPE_CUSTOM, + CPUPageProperty: match location { + MemoryLocation::GpuOnly => Direct3D12::D3D12_CPU_PAGE_PROPERTY_NOT_AVAILABLE, + MemoryLocation::CpuToGpu => Direct3D12::D3D12_CPU_PAGE_PROPERTY_WRITE_COMBINE, + MemoryLocation::GpuToCpu => Direct3D12::D3D12_CPU_PAGE_PROPERTY_WRITE_BACK, + _ => unreachable!(), + }, + MemoryPoolPreference: match (is_uma, location) { + // On dedicated GPUs, we only use L1 for GPU-only allocations. + (false, MemoryLocation::GpuOnly) => Direct3D12::D3D12_MEMORY_POOL_L1, + (_, _) => Direct3D12::D3D12_MEMORY_POOL_L0, + }, + CreationNodeMask: 0, + VisibleNodeMask: 0, + }; + + let mut resource = None; + + unsafe { + self.raw.CreateCommittedResource( + &heap_properties, + if self.shared.private_caps.heap_create_not_zeroed { + Direct3D12::D3D12_HEAP_FLAG_CREATE_NOT_ZEROED + } else { + Direct3D12::D3D12_HEAP_FLAG_NONE + }, + &raw_desc, + Direct3D12::D3D12_RESOURCE_STATE_COMMON, + None, + &mut resource, + ) + } + .into_device_result("Committed buffer creation")?; + + let resource = resource.ok_or(crate::DeviceError::Unexpected)?; + let wrapped_allocation = Allocation::none(AllocationType::Buffer, raw_desc.Width); + + Ok((resource, wrapped_allocation)) + } + + fn create_committed_texture( + &self, + desc: &crate::TextureDescriptor, + raw_desc: Direct3D12::D3D12_RESOURCE_DESC, + ) -> Result<(Direct3D12::ID3D12Resource, Allocation), crate::DeviceError> { + let heap_properties = Direct3D12::D3D12_HEAP_PROPERTIES { + Type: Direct3D12::D3D12_HEAP_TYPE_CUSTOM, + CPUPageProperty: Direct3D12::D3D12_CPU_PAGE_PROPERTY_NOT_AVAILABLE, + MemoryPoolPreference: match self.shared.private_caps.memory_architecture { + crate::dx12::MemoryArchitecture::NonUnified => Direct3D12::D3D12_MEMORY_POOL_L1, + crate::dx12::MemoryArchitecture::Unified { .. } => Direct3D12::D3D12_MEMORY_POOL_L0, + }, + CreationNodeMask: 0, + VisibleNodeMask: 0, + }; + + let mut resource = None; + + unsafe { + self.raw.CreateCommittedResource( + &heap_properties, + if self.shared.private_caps.heap_create_not_zeroed { + Direct3D12::D3D12_HEAP_FLAG_CREATE_NOT_ZEROED + } else { + Direct3D12::D3D12_HEAP_FLAG_NONE + }, + &raw_desc, + Direct3D12::D3D12_RESOURCE_STATE_COMMON, + None, // clear value + &mut resource, + ) + } + .into_device_result("Committed texture creation")?; + + let resource = resource.ok_or(crate::DeviceError::Unexpected)?; + let wrapped_allocation = Allocation::none( + AllocationType::Texture, + desc.format.theoretical_memory_footprint(desc.size), + ); + + Ok((resource, wrapped_allocation)) + } + + fn create_committed_acceleration_structure( + &self, + desc: &crate::AccelerationStructureDescriptor, + raw_desc: Direct3D12::D3D12_RESOURCE_DESC, + ) -> Result<(Direct3D12::ID3D12Resource, Allocation), crate::DeviceError> { + let heap_properties = Direct3D12::D3D12_HEAP_PROPERTIES { + Type: Direct3D12::D3D12_HEAP_TYPE_CUSTOM, + CPUPageProperty: Direct3D12::D3D12_CPU_PAGE_PROPERTY_NOT_AVAILABLE, + MemoryPoolPreference: match self.shared.private_caps.memory_architecture { + crate::dx12::MemoryArchitecture::NonUnified => Direct3D12::D3D12_MEMORY_POOL_L1, + crate::dx12::MemoryArchitecture::Unified { .. } => Direct3D12::D3D12_MEMORY_POOL_L0, + }, + CreationNodeMask: 0, + VisibleNodeMask: 0, + }; + + let mut resource = None; + + unsafe { + self.raw.CreateCommittedResource( + &heap_properties, + if self.shared.private_caps.heap_create_not_zeroed { + Direct3D12::D3D12_HEAP_FLAG_CREATE_NOT_ZEROED + } else { + Direct3D12::D3D12_HEAP_FLAG_NONE + }, + &raw_desc, + Direct3D12::D3D12_RESOURCE_STATE_RAYTRACING_ACCELERATION_STRUCTURE, + None, + &mut resource, + ) + } + .into_device_result("Committed acceleration structure creation")?; + + let resource = resource.ok_or(crate::DeviceError::Unexpected)?; + let wrapped_allocation = Allocation::none(AllocationType::AccelerationStructure, desc.size); + + Ok((resource, wrapped_allocation)) + } + + fn error_if_would_oom_on_resource_allocation( + &self, + desc: &Direct3D12::D3D12_RESOURCE_DESC, + location: MemoryLocation, + ) -> Result<Direct3D12::D3D12_RESOURCE_ALLOCATION_INFO, crate::DeviceError> { + let allocation_info = unsafe { + self.raw + .GetResourceAllocationInfo(0, core::slice::from_ref(desc)) + }; + + // Some versions of WARP return SizeInBytes == 0 for very large + // allocations. Proceeding to attempt to allocate a zero-sized resource + // will result in a device lost error, so it seems preferable to return + // an out of memory error now. + if allocation_info.SizeInBytes == 0 { + return Err(crate::DeviceError::OutOfMemory); + } + + let Some(threshold) = self + .mem_allocator + .memory_budget_thresholds + .for_resource_creation + else { + return Ok(allocation_info); + }; + + let memory_segment_group = match location { + MemoryLocation::Unknown => unreachable!(), + MemoryLocation::GpuOnly => Dxgi::DXGI_MEMORY_SEGMENT_GROUP_LOCAL, + MemoryLocation::CpuToGpu | MemoryLocation::GpuToCpu => { + match self.shared.private_caps.memory_architecture { + super::MemoryArchitecture::Unified { .. } => { + Dxgi::DXGI_MEMORY_SEGMENT_GROUP_LOCAL + } + super::MemoryArchitecture::NonUnified => { + Dxgi::DXGI_MEMORY_SEGMENT_GROUP_NON_LOCAL + } + } + } + }; + + let info = self + .shared + .adapter + .query_video_memory_info(memory_segment_group)?; + + let memblock_size = match location { + MemoryLocation::Unknown => unreachable!(), + MemoryLocation::GpuOnly => self.mem_allocator.device_memblock_size, + MemoryLocation::CpuToGpu | MemoryLocation::GpuToCpu => { + self.mem_allocator.host_memblock_size + } + }; + + if info + .CurrentUsage + .checked_add(allocation_info.SizeInBytes.max(memblock_size)) + .is_none_or(|usage| usage >= info.Budget / 100 * threshold as u64) + { + return Err(crate::DeviceError::OutOfMemory); + } + + Ok(allocation_info) + } +} diff --git a/app/vendor/rune/vendor/wgpu-hal/src/dx12/types.rs b/app/vendor/rune/vendor/wgpu-hal/src/dx12/types.rs new file mode 100644 index 0000000..5270c6c --- /dev/null +++ b/app/vendor/rune/vendor/wgpu-hal/src/dx12/types.rs @@ -0,0 +1,39 @@ +#![allow(non_camel_case_types)] +#![allow(non_snake_case)] + +use windows::Win32::Graphics::Dxgi; + +windows_core::imp::define_interface!( + ISwapChainPanelNative, + ISwapChainPanelNative_Vtbl, + 0x63aad0b8_7c24_40ff_85a8_640d944cc325 +); +impl core::ops::Deref for ISwapChainPanelNative { + type Target = windows_core::IUnknown; + fn deref(&self) -> &Self::Target { + unsafe { core::mem::transmute(self) } + } +} +windows_core::imp::interface_hierarchy!(ISwapChainPanelNative, windows_core::IUnknown); +impl ISwapChainPanelNative { + pub unsafe fn SetSwapChain<P0>(&self, swap_chain: P0) -> windows_core::Result<()> + where + P0: windows_core::Param<Dxgi::IDXGISwapChain1>, + { + unsafe { + (windows_core::Interface::vtable(self).SetSwapChain)( + windows_core::Interface::as_raw(self), + swap_chain.param().abi(), + ) + } + .ok() + } +} +#[repr(C)] +pub struct ISwapChainPanelNative_Vtbl { + pub base__: windows_core::IUnknown_Vtbl, + pub SetSwapChain: unsafe extern "system" fn( + swap_chain_panel_native: *mut core::ffi::c_void, + swap_chain: *mut core::ffi::c_void, + ) -> windows_core::HRESULT, +} diff --git a/app/vendor/rune/vendor/wgpu-hal/src/dx12/view.rs b/app/vendor/rune/vendor/wgpu-hal/src/dx12/view.rs new file mode 100644 index 0000000..ba71583 --- /dev/null +++ b/app/vendor/rune/vendor/wgpu-hal/src/dx12/view.rs @@ -0,0 +1,370 @@ +use windows::Win32::Graphics::{Direct3D12, Dxgi}; + +use crate::auxil; + +pub(super) struct ViewDescriptor { + dimension: wgt::TextureViewDimension, + pub aspects: crate::FormatAspects, + pub rtv_dsv_format: Dxgi::Common::DXGI_FORMAT, + srv_uav_format: Option<Dxgi::Common::DXGI_FORMAT>, + multisampled: bool, + array_layer_base: u32, + array_layer_count: u32, + mip_level_base: u32, + mip_level_count: u32, + plane_slice_override: Option<u32>, +} + +impl crate::TextureViewDescriptor<'_> { + pub(super) fn to_internal(&self, texture: &super::Texture) -> ViewDescriptor { + let aspects = crate::FormatAspects::new(texture.format, self.range.aspect); + + ViewDescriptor { + dimension: self.dimension, + aspects, + rtv_dsv_format: auxil::dxgi::conv::map_texture_format(self.format), + srv_uav_format: auxil::dxgi::conv::map_texture_format_for_srv_uav(self.format, aspects), + multisampled: texture.sample_count > 1, + mip_level_base: self.range.base_mip_level, + mip_level_count: self.range.mip_level_count.unwrap_or(!0), + array_layer_base: self.range.base_array_layer, + array_layer_count: self.range.array_layer_count.unwrap_or(!0), + plane_slice_override: texture.plane_slice_override(), + } + } +} + +fn aspects_to_plane(aspects: crate::FormatAspects) -> u32 { + match aspects { + crate::FormatAspects::STENCIL => 1, + crate::FormatAspects::PLANE_1 => 1, + crate::FormatAspects::PLANE_2 => 2, + _ => 0, + } +} + +impl ViewDescriptor { + pub(super) fn plane_slice(&self) -> u32 { + self.plane_slice_override + .unwrap_or_else(|| aspects_to_plane(self.aspects)) + } +} + +/// Shader component mapping for stencil views +/// +/// Stencil views use `DXGI_FORMAT_X24_TYPELESS_G8_UINT` or +/// `DXGI_FORMAT_X32_TYPELESS_G8X24_UINT`, which have the stencil value in +/// the green component. WebGPU specifies that the stencil value be in the +/// red component. It also specifies that the remaining components _should_ +/// be (0, 0, 1), but may have an unspecified value. +const STENCIL_COMPONENT_MAPPING: Direct3D12::D3D12_SHADER_COMPONENT_MAPPING = + super::conv::make_shader_component_mapping( + Direct3D12::D3D12_SHADER_COMPONENT_MAPPING_FROM_MEMORY_COMPONENT_1, + Direct3D12::D3D12_SHADER_COMPONENT_MAPPING_FORCE_VALUE_0, + Direct3D12::D3D12_SHADER_COMPONENT_MAPPING_FORCE_VALUE_0, + Direct3D12::D3D12_SHADER_COMPONENT_MAPPING_FORCE_VALUE_1, + ); + +impl ViewDescriptor { + pub(crate) unsafe fn to_srv(&self) -> Option<Direct3D12::D3D12_SHADER_RESOURCE_VIEW_DESC> { + let swizzle = if self.aspects == crate::FormatAspects::STENCIL { + STENCIL_COMPONENT_MAPPING.0 as u32 + } else { + Direct3D12::D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING + }; + + let mut desc = Direct3D12::D3D12_SHADER_RESOURCE_VIEW_DESC { + Format: self.srv_uav_format?, + ViewDimension: Direct3D12::D3D12_SRV_DIMENSION_UNKNOWN, + Shader4ComponentMapping: swizzle, + Anonymous: Default::default(), + }; + + match self.dimension { + wgt::TextureViewDimension::D1 => { + desc.ViewDimension = Direct3D12::D3D12_SRV_DIMENSION_TEXTURE1D; + desc.Anonymous.Texture1D = Direct3D12::D3D12_TEX1D_SRV { + MostDetailedMip: self.mip_level_base, + MipLevels: self.mip_level_count, + ResourceMinLODClamp: 0.0, + } + } + /* + wgt::TextureViewDimension::D1Array => { + desc.ViewDimension = Direct3D12::D3D12_SRV_DIMENSION_TEXTURE1DARRAY; + desc.Anonymous.Texture1DArray = Direct3D12::D3D12_TEX1D_ARRAY_SRV { + MostDetailedMip: self.mip_level_base, + MipLevels: self.mip_level_count, + FirstArraySlice: self.array_layer_base, + ArraySize: self.array_layer_count, + ResourceMinLODClamp: 0.0, + } + } + */ + wgt::TextureViewDimension::D2 if self.multisampled && self.array_layer_base == 0 => { + desc.ViewDimension = Direct3D12::D3D12_SRV_DIMENSION_TEXTURE2DMS; + desc.Anonymous.Texture2DMS = Direct3D12::D3D12_TEX2DMS_SRV { + UnusedField_NothingToDefine: 0, + } + } + wgt::TextureViewDimension::D2 if self.array_layer_base == 0 => { + desc.ViewDimension = Direct3D12::D3D12_SRV_DIMENSION_TEXTURE2D; + desc.Anonymous.Texture2D = Direct3D12::D3D12_TEX2D_SRV { + MostDetailedMip: self.mip_level_base, + MipLevels: self.mip_level_count, + PlaneSlice: self.plane_slice(), + ResourceMinLODClamp: 0.0, + } + } + wgt::TextureViewDimension::D2 | wgt::TextureViewDimension::D2Array + if self.multisampled => + { + desc.ViewDimension = Direct3D12::D3D12_SRV_DIMENSION_TEXTURE2DMSARRAY; + desc.Anonymous.Texture2DMSArray = Direct3D12::D3D12_TEX2DMS_ARRAY_SRV { + FirstArraySlice: self.array_layer_base, + ArraySize: self.array_layer_count, + } + } + wgt::TextureViewDimension::D2 | wgt::TextureViewDimension::D2Array => { + desc.ViewDimension = Direct3D12::D3D12_SRV_DIMENSION_TEXTURE2DARRAY; + desc.Anonymous.Texture2DArray = Direct3D12::D3D12_TEX2D_ARRAY_SRV { + MostDetailedMip: self.mip_level_base, + MipLevels: self.mip_level_count, + FirstArraySlice: self.array_layer_base, + ArraySize: self.array_layer_count, + PlaneSlice: self.plane_slice(), + ResourceMinLODClamp: 0.0, + } + } + wgt::TextureViewDimension::D3 => { + desc.ViewDimension = Direct3D12::D3D12_SRV_DIMENSION_TEXTURE3D; + desc.Anonymous.Texture3D = Direct3D12::D3D12_TEX3D_SRV { + MostDetailedMip: self.mip_level_base, + MipLevels: self.mip_level_count, + ResourceMinLODClamp: 0.0, + } + } + wgt::TextureViewDimension::Cube if self.array_layer_base == 0 => { + desc.ViewDimension = Direct3D12::D3D12_SRV_DIMENSION_TEXTURECUBE; + desc.Anonymous.TextureCube = Direct3D12::D3D12_TEXCUBE_SRV { + MostDetailedMip: self.mip_level_base, + MipLevels: self.mip_level_count, + ResourceMinLODClamp: 0.0, + } + } + wgt::TextureViewDimension::Cube | wgt::TextureViewDimension::CubeArray => { + desc.ViewDimension = Direct3D12::D3D12_SRV_DIMENSION_TEXTURECUBEARRAY; + desc.Anonymous.TextureCubeArray = Direct3D12::D3D12_TEXCUBE_ARRAY_SRV { + MostDetailedMip: self.mip_level_base, + MipLevels: self.mip_level_count, + First2DArrayFace: self.array_layer_base, + NumCubes: if self.array_layer_count == !0 { + !0 + } else { + self.array_layer_count / 6 + }, + ResourceMinLODClamp: 0.0, + } + } + } + + Some(desc) + } + + pub(crate) unsafe fn to_uav(&self) -> Option<Direct3D12::D3D12_UNORDERED_ACCESS_VIEW_DESC> { + let mut desc = Direct3D12::D3D12_UNORDERED_ACCESS_VIEW_DESC { + Format: self.srv_uav_format?, + ViewDimension: Direct3D12::D3D12_UAV_DIMENSION_UNKNOWN, + Anonymous: Default::default(), + }; + + match self.dimension { + wgt::TextureViewDimension::D1 => { + desc.ViewDimension = Direct3D12::D3D12_UAV_DIMENSION_TEXTURE1D; + desc.Anonymous.Texture1D = Direct3D12::D3D12_TEX1D_UAV { + MipSlice: self.mip_level_base, + } + } + /* + wgt::TextureViewDimension::D1Array => { + desc.ViewDimension = Direct3D12::D3D12_UAV_DIMENSION_TEXTURE1DARRAY; + desc.Anonymous.Texture1DArray = Direct3D12::D3D12_TEX1D_ARRAY_UAV { + MipSlice: self.mip_level_base, + FirstArraySlice: self.array_layer_base, + ArraySize, + } + }*/ + wgt::TextureViewDimension::D2 if self.array_layer_base == 0 => { + desc.ViewDimension = Direct3D12::D3D12_UAV_DIMENSION_TEXTURE2D; + desc.Anonymous.Texture2D = Direct3D12::D3D12_TEX2D_UAV { + MipSlice: self.mip_level_base, + PlaneSlice: self.plane_slice(), + } + } + wgt::TextureViewDimension::D2 | wgt::TextureViewDimension::D2Array => { + desc.ViewDimension = Direct3D12::D3D12_UAV_DIMENSION_TEXTURE2DARRAY; + desc.Anonymous.Texture2DArray = Direct3D12::D3D12_TEX2D_ARRAY_UAV { + MipSlice: self.mip_level_base, + FirstArraySlice: self.array_layer_base, + ArraySize: self.array_layer_count, + PlaneSlice: self.plane_slice(), + } + } + wgt::TextureViewDimension::D3 => { + desc.ViewDimension = Direct3D12::D3D12_UAV_DIMENSION_TEXTURE3D; + desc.Anonymous.Texture3D = Direct3D12::D3D12_TEX3D_UAV { + MipSlice: self.mip_level_base, + FirstWSlice: 0, + WSize: u32::MAX, + } + } + wgt::TextureViewDimension::Cube | wgt::TextureViewDimension::CubeArray => { + panic!("Unable to view texture as cube UAV") + } + } + + Some(desc) + } + + pub(crate) unsafe fn to_rtv(&self) -> Direct3D12::D3D12_RENDER_TARGET_VIEW_DESC { + let mut desc = Direct3D12::D3D12_RENDER_TARGET_VIEW_DESC { + Format: self.rtv_dsv_format, + ViewDimension: Direct3D12::D3D12_RTV_DIMENSION_UNKNOWN, + Anonymous: Default::default(), + }; + + match self.dimension { + wgt::TextureViewDimension::D1 => { + desc.ViewDimension = Direct3D12::D3D12_RTV_DIMENSION_TEXTURE1D; + desc.Anonymous.Texture1D = Direct3D12::D3D12_TEX1D_RTV { + MipSlice: self.mip_level_base, + } + } + /* + wgt::TextureViewDimension::D1Array => { + desc.ViewDimension = Direct3D12::D3D12_RTV_DIMENSION_TEXTURE1DARRAY; + desc.Anonymous.Texture1DArray = Direct3D12::D3D12_TEX1D_ARRAY_RTV { + MipSlice: self.mip_level_base, + FirstArraySlice: self.array_layer_base, + ArraySize, + } + }*/ + wgt::TextureViewDimension::D2 if self.multisampled && self.array_layer_base == 0 => { + desc.ViewDimension = Direct3D12::D3D12_RTV_DIMENSION_TEXTURE2DMS; + desc.Anonymous.Texture2DMS = Direct3D12::D3D12_TEX2DMS_RTV { + UnusedField_NothingToDefine: 0, + } + } + wgt::TextureViewDimension::D2 if self.array_layer_base == 0 => { + desc.ViewDimension = Direct3D12::D3D12_RTV_DIMENSION_TEXTURE2D; + desc.Anonymous.Texture2D = Direct3D12::D3D12_TEX2D_RTV { + MipSlice: self.mip_level_base, + PlaneSlice: self.plane_slice(), + } + } + wgt::TextureViewDimension::D2 | wgt::TextureViewDimension::D2Array + if self.multisampled => + { + desc.ViewDimension = Direct3D12::D3D12_RTV_DIMENSION_TEXTURE2DMSARRAY; + desc.Anonymous.Texture2DMSArray = Direct3D12::D3D12_TEX2DMS_ARRAY_RTV { + FirstArraySlice: self.array_layer_base, + ArraySize: self.array_layer_count, + } + } + wgt::TextureViewDimension::D2 | wgt::TextureViewDimension::D2Array => { + desc.ViewDimension = Direct3D12::D3D12_RTV_DIMENSION_TEXTURE2DARRAY; + desc.Anonymous.Texture2DArray = Direct3D12::D3D12_TEX2D_ARRAY_RTV { + MipSlice: self.mip_level_base, + FirstArraySlice: self.array_layer_base, + ArraySize: self.array_layer_count, + PlaneSlice: self.plane_slice(), + } + } + wgt::TextureViewDimension::D3 + | wgt::TextureViewDimension::Cube + | wgt::TextureViewDimension::CubeArray => { + panic!("Unable to view texture as cube or 3D RTV") + } + } + + desc + } + + pub(crate) unsafe fn to_dsv( + &self, + read_only: bool, + ) -> Direct3D12::D3D12_DEPTH_STENCIL_VIEW_DESC { + let mut desc = Direct3D12::D3D12_DEPTH_STENCIL_VIEW_DESC { + Format: self.rtv_dsv_format, + ViewDimension: Direct3D12::D3D12_DSV_DIMENSION_UNKNOWN, + Flags: { + let mut flags = Direct3D12::D3D12_DSV_FLAG_NONE; + if read_only { + if self.aspects.contains(crate::FormatAspects::DEPTH) { + flags |= Direct3D12::D3D12_DSV_FLAG_READ_ONLY_DEPTH; + } + if self.aspects.contains(crate::FormatAspects::STENCIL) { + flags |= Direct3D12::D3D12_DSV_FLAG_READ_ONLY_STENCIL; + } + } + flags + }, + Anonymous: Default::default(), + }; + + match self.dimension { + wgt::TextureViewDimension::D1 => { + desc.ViewDimension = Direct3D12::D3D12_DSV_DIMENSION_TEXTURE1D; + desc.Anonymous.Texture1D = Direct3D12::D3D12_TEX1D_DSV { + MipSlice: self.mip_level_base, + } + } + /* + wgt::TextureViewDimension::D1Array => { + desc.ViewDimension = Direct3D12::D3D12_DSV_DIMENSION_TEXTURE1DARRAY; + desc.Anonymous.Texture1DArray = Direct3D12::D3D12_TEX1D_ARRAY_DSV { + MipSlice: self.mip_level_base, + FirstArraySlice: self.array_layer_base, + ArraySize, + } + }*/ + wgt::TextureViewDimension::D2 if self.multisampled && self.array_layer_base == 0 => { + desc.ViewDimension = Direct3D12::D3D12_DSV_DIMENSION_TEXTURE2DMS; + desc.Anonymous.Texture2DMS = Direct3D12::D3D12_TEX2DMS_DSV { + UnusedField_NothingToDefine: 0, + } + } + wgt::TextureViewDimension::D2 if self.array_layer_base == 0 => { + desc.ViewDimension = Direct3D12::D3D12_DSV_DIMENSION_TEXTURE2D; + + desc.Anonymous.Texture2D = Direct3D12::D3D12_TEX2D_DSV { + MipSlice: self.mip_level_base, + } + } + wgt::TextureViewDimension::D2 | wgt::TextureViewDimension::D2Array + if self.multisampled => + { + desc.ViewDimension = Direct3D12::D3D12_DSV_DIMENSION_TEXTURE2DMSARRAY; + desc.Anonymous.Texture2DMSArray = Direct3D12::D3D12_TEX2DMS_ARRAY_DSV { + FirstArraySlice: self.array_layer_base, + ArraySize: self.array_layer_count, + } + } + wgt::TextureViewDimension::D2 | wgt::TextureViewDimension::D2Array => { + desc.ViewDimension = Direct3D12::D3D12_DSV_DIMENSION_TEXTURE2DARRAY; + desc.Anonymous.Texture2DArray = Direct3D12::D3D12_TEX2D_ARRAY_DSV { + MipSlice: self.mip_level_base, + FirstArraySlice: self.array_layer_base, + ArraySize: self.array_layer_count, + } + } + wgt::TextureViewDimension::D3 + | wgt::TextureViewDimension::Cube + | wgt::TextureViewDimension::CubeArray => { + panic!("Unable to view texture as cube or 3D DSV") + } + } + + desc + } +} diff --git a/app/vendor/rune/vendor/wgpu-hal/src/dynamic/adapter.rs b/app/vendor/rune/vendor/wgpu-hal/src/dynamic/adapter.rs new file mode 100644 index 0000000..4921d71 --- /dev/null +++ b/app/vendor/rune/vendor/wgpu-hal/src/dynamic/adapter.rs @@ -0,0 +1,95 @@ +use alloc::boxed::Box; + +use crate::{ + Adapter, Api, DeviceError, OpenDevice, SurfaceCapabilities, TextureFormatCapabilities, +}; + +use super::{DynDevice, DynQueue, DynResource, DynResourceExt, DynSurface}; + +#[expect(missing_debug_implementations, reason = "dyn")] +pub struct DynOpenDevice { + pub device: Box<dyn DynDevice>, + pub queue: Box<dyn DynQueue>, +} + +impl<A: Api> From<OpenDevice<A>> for DynOpenDevice { + fn from(open_device: OpenDevice<A>) -> Self { + Self { + device: Box::new(open_device.device), + queue: Box::new(open_device.queue), + } + } +} + +pub trait DynAdapter: DynResource { + unsafe fn open( + &self, + features: wgt::Features, + limits: &wgt::Limits, + memory_hints: &wgt::MemoryHints, + ) -> Result<DynOpenDevice, DeviceError>; + + unsafe fn texture_format_capabilities( + &self, + format: wgt::TextureFormat, + ) -> TextureFormatCapabilities; + + unsafe fn surface_capabilities(&self, surface: &dyn DynSurface) -> Option<SurfaceCapabilities>; + + unsafe fn surface_display_hdr_info( + &self, + surface: &dyn DynSurface, + ) -> Option<wgt::DisplayHdrInfo>; + + unsafe fn get_presentation_timestamp(&self) -> wgt::PresentationTimestamp; + + fn get_ordered_buffer_usages(&self) -> wgt::BufferUses; + + fn get_ordered_texture_usages(&self) -> wgt::TextureUses; +} + +impl<A: Adapter + DynResource> DynAdapter for A { + unsafe fn open( + &self, + features: wgt::Features, + limits: &wgt::Limits, + memory_hints: &wgt::MemoryHints, + ) -> Result<DynOpenDevice, DeviceError> { + unsafe { A::open(self, features, limits, memory_hints) }.map(|open_device| DynOpenDevice { + device: Box::new(open_device.device), + queue: Box::new(open_device.queue), + }) + } + + unsafe fn texture_format_capabilities( + &self, + format: wgt::TextureFormat, + ) -> TextureFormatCapabilities { + unsafe { A::texture_format_capabilities(self, format) } + } + + unsafe fn surface_capabilities(&self, surface: &dyn DynSurface) -> Option<SurfaceCapabilities> { + let surface = surface.expect_downcast_ref(); + unsafe { A::surface_capabilities(self, surface) } + } + + unsafe fn surface_display_hdr_info( + &self, + surface: &dyn DynSurface, + ) -> Option<wgt::DisplayHdrInfo> { + let surface = surface.expect_downcast_ref(); + unsafe { A::surface_display_hdr_info(self, surface) } + } + + unsafe fn get_presentation_timestamp(&self) -> wgt::PresentationTimestamp { + unsafe { A::get_presentation_timestamp(self) } + } + + fn get_ordered_buffer_usages(&self) -> wgt::BufferUses { + A::get_ordered_buffer_usages(self) + } + + fn get_ordered_texture_usages(&self) -> wgt::TextureUses { + A::get_ordered_texture_usages(self) + } +} diff --git a/app/vendor/rune/vendor/wgpu-hal/src/dynamic/command.rs b/app/vendor/rune/vendor/wgpu-hal/src/dynamic/command.rs new file mode 100644 index 0000000..aca5bbc --- /dev/null +++ b/app/vendor/rune/vendor/wgpu-hal/src/dynamic/command.rs @@ -0,0 +1,823 @@ +use alloc::{boxed::Box, vec::Vec}; +use core::ops::Range; + +use crate::{ + AccelerationStructureBarrier, Api, Attachment, BufferBarrier, BufferBinding, BufferCopy, + BufferTextureCopy, BuildAccelerationStructureDescriptor, ColorAttachment, CommandEncoder, + ComputePassDescriptor, DepthStencilAttachment, DeviceError, DynRayTracingPipeline, Label, + MemoryRange, PassTimestampWrites, RayTracingPassDescriptor, Rect, RenderPassDescriptor, + TextureBarrier, TextureCopy, +}; + +use super::{ + DynAccelerationStructure, DynBindGroup, DynBuffer, DynCommandBuffer, DynComputePipeline, + DynPipelineLayout, DynQuerySet, DynRenderPipeline, DynResource, DynResourceExt as _, + DynTexture, DynTextureView, +}; + +pub trait DynCommandEncoder: DynResource + core::fmt::Debug { + unsafe fn begin_encoding(&mut self, label: Label) -> Result<(), DeviceError>; + + unsafe fn discard_encoding(&mut self); + + unsafe fn end_encoding(&mut self) -> Result<Box<dyn DynCommandBuffer>, DeviceError>; + + unsafe fn reset_all(&mut self, command_buffers: Vec<Box<dyn DynCommandBuffer>>); + + unsafe fn transition_buffers(&mut self, barriers: &[BufferBarrier<'_, dyn DynBuffer>]); + unsafe fn transition_textures(&mut self, barriers: &[TextureBarrier<'_, dyn DynTexture>]); + + unsafe fn clear_buffer(&mut self, buffer: &dyn DynBuffer, range: MemoryRange); + + unsafe fn copy_buffer_to_buffer( + &mut self, + src: &dyn DynBuffer, + dst: &dyn DynBuffer, + regions: &[BufferCopy], + ); + + unsafe fn copy_texture_to_texture( + &mut self, + src: &dyn DynTexture, + src_usage: wgt::TextureUses, + dst: &dyn DynTexture, + regions: &[TextureCopy], + ); + + unsafe fn copy_buffer_to_texture( + &mut self, + src: &dyn DynBuffer, + dst: &dyn DynTexture, + regions: &[BufferTextureCopy], + ); + + unsafe fn copy_texture_to_buffer( + &mut self, + src: &dyn DynTexture, + src_usage: wgt::TextureUses, + dst: &dyn DynBuffer, + regions: &[BufferTextureCopy], + ); + + unsafe fn set_bind_group( + &mut self, + layout: &dyn DynPipelineLayout, + index: u32, + group: &dyn DynBindGroup, + dynamic_offsets: &[wgt::DynamicOffset], + ); + + unsafe fn set_immediates( + &mut self, + layout: &dyn DynPipelineLayout, + offset_bytes: u32, + data: &[u32], + ); + + unsafe fn insert_debug_marker(&mut self, label: &str); + unsafe fn begin_debug_marker(&mut self, group_label: &str); + unsafe fn end_debug_marker(&mut self); + + unsafe fn begin_query(&mut self, set: &dyn DynQuerySet, index: u32); + unsafe fn end_query(&mut self, set: &dyn DynQuerySet, index: u32); + unsafe fn write_timestamp(&mut self, set: &dyn DynQuerySet, index: u32); + unsafe fn reset_queries(&mut self, set: &dyn DynQuerySet, range: Range<u32>); + unsafe fn copy_query_results( + &mut self, + set: &dyn DynQuerySet, + range: Range<u32>, + buffer: &dyn DynBuffer, + offset: wgt::BufferAddress, + stride: wgt::BufferSize, + ); + + unsafe fn begin_render_pass( + &mut self, + desc: &RenderPassDescriptor<dyn DynQuerySet, dyn DynTextureView>, + ) -> Result<(), DeviceError>; + unsafe fn end_render_pass(&mut self); + + unsafe fn set_render_pipeline(&mut self, pipeline: &dyn DynRenderPipeline); + + unsafe fn set_index_buffer<'a>( + &mut self, + binding: BufferBinding<'a, dyn DynBuffer>, + format: wgt::IndexFormat, + ); + + unsafe fn set_vertex_buffer<'a>( + &mut self, + index: u32, + binding: BufferBinding<'a, dyn DynBuffer>, + ); + unsafe fn set_viewport(&mut self, rect: &Rect<f32>, depth_range: Range<f32>); + unsafe fn set_scissor_rect(&mut self, rect: &Rect<u32>); + unsafe fn set_stencil_reference(&mut self, value: u32); + unsafe fn set_blend_constants(&mut self, color: &[f32; 4]); + + unsafe fn draw( + &mut self, + first_vertex: u32, + vertex_count: u32, + first_instance: u32, + instance_count: u32, + ); + unsafe fn draw_indexed( + &mut self, + first_index: u32, + index_count: u32, + base_vertex: i32, + first_instance: u32, + instance_count: u32, + ); + unsafe fn draw_mesh_tasks( + &mut self, + group_count_x: u32, + group_count_y: u32, + group_count_z: u32, + ); + unsafe fn draw_indirect( + &mut self, + buffer: &dyn DynBuffer, + offset: wgt::BufferAddress, + draw_count: u32, + ); + unsafe fn draw_indexed_indirect( + &mut self, + buffer: &dyn DynBuffer, + offset: wgt::BufferAddress, + draw_count: u32, + ); + unsafe fn draw_mesh_tasks_indirect( + &mut self, + buffer: &dyn DynBuffer, + offset: wgt::BufferAddress, + draw_count: u32, + ); + unsafe fn draw_indirect_count( + &mut self, + buffer: &dyn DynBuffer, + offset: wgt::BufferAddress, + count_buffer: &dyn DynBuffer, + count_offset: wgt::BufferAddress, + max_count: u32, + ); + unsafe fn draw_indexed_indirect_count( + &mut self, + buffer: &dyn DynBuffer, + offset: wgt::BufferAddress, + count_buffer: &dyn DynBuffer, + count_offset: wgt::BufferAddress, + max_count: u32, + ); + unsafe fn draw_mesh_tasks_indirect_count( + &mut self, + buffer: &dyn DynBuffer, + offset: wgt::BufferAddress, + count_buffer: &dyn DynBuffer, + count_offset: wgt::BufferAddress, + max_count: u32, + ); + + unsafe fn begin_compute_pass(&mut self, desc: &ComputePassDescriptor<dyn DynQuerySet>); + unsafe fn end_compute_pass(&mut self); + + unsafe fn set_compute_pipeline(&mut self, pipeline: &dyn DynComputePipeline); + + unsafe fn dispatch_workgroups(&mut self, count: [u32; 3]); + unsafe fn dispatch_workgroups_indirect( + &mut self, + buffer: &dyn DynBuffer, + offset: wgt::BufferAddress, + ); + + unsafe fn begin_ray_tracing_pass(&mut self, desc: &RayTracingPassDescriptor); + unsafe fn end_ray_tracing_pass(&mut self); + + unsafe fn trace_rays( + &mut self, + count: [u32; 3], + ray_generation_group_data: crate::PipelineGroupData<dyn DynBuffer>, + miss_group_data: crate::PipelineGroupData<dyn DynBuffer>, + intersection_group_data: crate::PipelineGroupData<dyn DynBuffer>, + ); + + unsafe fn set_ray_tracing_pipeline(&mut self, pipeline: &dyn DynRayTracingPipeline); + + unsafe fn build_acceleration_structures<'a>( + &mut self, + descriptors: &'a [BuildAccelerationStructureDescriptor< + 'a, + dyn DynBuffer, + dyn DynAccelerationStructure, + >], + ); + unsafe fn place_acceleration_structure_barrier( + &mut self, + barrier: AccelerationStructureBarrier, + ); + unsafe fn copy_acceleration_structure_to_acceleration_structure( + &mut self, + src: &dyn DynAccelerationStructure, + dst: &dyn DynAccelerationStructure, + copy: wgt::AccelerationStructureCopy, + ); + unsafe fn read_acceleration_structure_compact_size( + &mut self, + acceleration_structure: &dyn DynAccelerationStructure, + buf: &dyn DynBuffer, + ); + unsafe fn set_acceleration_structure_dependencies( + &self, + command_buffers: &[Box<dyn DynCommandBuffer>], + dependencies: &[&dyn DynAccelerationStructure], + ); +} + +impl<C: CommandEncoder + DynResource> DynCommandEncoder for C { + unsafe fn begin_encoding(&mut self, label: Label) -> Result<(), DeviceError> { + unsafe { C::begin_encoding(self, label) } + } + + unsafe fn discard_encoding(&mut self) { + unsafe { C::discard_encoding(self) } + } + + unsafe fn end_encoding(&mut self) -> Result<Box<dyn DynCommandBuffer>, DeviceError> { + unsafe { C::end_encoding(self) }.map(|cb| { + let boxed_command_buffer: Box<<C::A as Api>::CommandBuffer> = Box::new(cb); + let boxed_command_buffer: Box<dyn DynCommandBuffer> = boxed_command_buffer; + boxed_command_buffer + }) + } + + unsafe fn reset_all(&mut self, command_buffers: Vec<Box<dyn DynCommandBuffer>>) { + unsafe { C::reset_all(self, command_buffers.into_iter().map(|cb| cb.unbox())) } + } + + unsafe fn transition_buffers(&mut self, barriers: &[BufferBarrier<'_, dyn DynBuffer>]) { + let barriers = barriers.iter().map(|barrier| BufferBarrier { + buffer: barrier.buffer.expect_downcast_ref(), + usage: barrier.usage.clone(), + }); + unsafe { self.transition_buffers(barriers) }; + } + + unsafe fn transition_textures(&mut self, barriers: &[TextureBarrier<'_, dyn DynTexture>]) { + let barriers = barriers.iter().map(|barrier| TextureBarrier { + texture: barrier.texture.expect_downcast_ref(), + usage: barrier.usage.clone(), + range: barrier.range, + }); + unsafe { self.transition_textures(barriers) }; + } + + unsafe fn clear_buffer(&mut self, buffer: &dyn DynBuffer, range: MemoryRange) { + let buffer = buffer.expect_downcast_ref(); + unsafe { C::clear_buffer(self, buffer, range) }; + } + + unsafe fn copy_buffer_to_buffer( + &mut self, + src: &dyn DynBuffer, + dst: &dyn DynBuffer, + regions: &[BufferCopy], + ) { + let src = src.expect_downcast_ref(); + let dst = dst.expect_downcast_ref(); + unsafe { + C::copy_buffer_to_buffer(self, src, dst, regions.iter().copied()); + } + } + + unsafe fn copy_texture_to_texture( + &mut self, + src: &dyn DynTexture, + src_usage: wgt::TextureUses, + dst: &dyn DynTexture, + regions: &[TextureCopy], + ) { + let src = src.expect_downcast_ref(); + let dst = dst.expect_downcast_ref(); + unsafe { + C::copy_texture_to_texture(self, src, src_usage, dst, regions.iter().cloned()); + } + } + + unsafe fn copy_buffer_to_texture( + &mut self, + src: &dyn DynBuffer, + dst: &dyn DynTexture, + regions: &[BufferTextureCopy], + ) { + let src = src.expect_downcast_ref(); + let dst = dst.expect_downcast_ref(); + unsafe { + C::copy_buffer_to_texture(self, src, dst, regions.iter().cloned()); + } + } + + unsafe fn copy_texture_to_buffer( + &mut self, + src: &dyn DynTexture, + src_usage: wgt::TextureUses, + dst: &dyn DynBuffer, + regions: &[BufferTextureCopy], + ) { + let src = src.expect_downcast_ref(); + let dst = dst.expect_downcast_ref(); + unsafe { + C::copy_texture_to_buffer(self, src, src_usage, dst, regions.iter().cloned()); + } + } + + unsafe fn set_bind_group( + &mut self, + layout: &dyn DynPipelineLayout, + index: u32, + group: &dyn DynBindGroup, + dynamic_offsets: &[wgt::DynamicOffset], + ) { + let layout = layout.expect_downcast_ref(); + let group = group.expect_downcast_ref(); + unsafe { C::set_bind_group(self, layout, index, group, dynamic_offsets) }; + } + + unsafe fn set_immediates( + &mut self, + layout: &dyn DynPipelineLayout, + offset_bytes: u32, + data: &[u32], + ) { + let layout = layout.expect_downcast_ref(); + unsafe { C::set_immediates(self, layout, offset_bytes, data) }; + } + + unsafe fn insert_debug_marker(&mut self, label: &str) { + unsafe { + C::insert_debug_marker(self, label); + } + } + + unsafe fn begin_debug_marker(&mut self, group_label: &str) { + unsafe { + C::begin_debug_marker(self, group_label); + } + } + + unsafe fn end_debug_marker(&mut self) { + unsafe { + C::end_debug_marker(self); + } + } + + unsafe fn begin_query(&mut self, set: &dyn DynQuerySet, index: u32) { + let set = set.expect_downcast_ref(); + unsafe { C::begin_query(self, set, index) }; + } + + unsafe fn end_query(&mut self, set: &dyn DynQuerySet, index: u32) { + let set = set.expect_downcast_ref(); + unsafe { C::end_query(self, set, index) }; + } + + unsafe fn write_timestamp(&mut self, set: &dyn DynQuerySet, index: u32) { + let set = set.expect_downcast_ref(); + unsafe { C::write_timestamp(self, set, index) }; + } + + unsafe fn reset_queries(&mut self, set: &dyn DynQuerySet, range: Range<u32>) { + let set = set.expect_downcast_ref(); + unsafe { C::reset_queries(self, set, range) }; + } + + unsafe fn copy_query_results( + &mut self, + set: &dyn DynQuerySet, + range: Range<u32>, + buffer: &dyn DynBuffer, + offset: wgt::BufferAddress, + stride: wgt::BufferSize, + ) { + let set = set.expect_downcast_ref(); + let buffer = buffer.expect_downcast_ref(); + unsafe { C::copy_query_results(self, set, range, buffer, offset, stride) }; + } + + unsafe fn begin_render_pass( + &mut self, + desc: &RenderPassDescriptor<dyn DynQuerySet, dyn DynTextureView>, + ) -> Result<(), DeviceError> { + let color_attachments = desc + .color_attachments + .iter() + .map(|attachment| { + attachment + .as_ref() + .map(|attachment| attachment.expect_downcast()) + }) + .collect::<Vec<_>>(); + + let desc: RenderPassDescriptor<<C::A as Api>::QuerySet, <C::A as Api>::TextureView> = + RenderPassDescriptor { + label: desc.label, + extent: desc.extent, + sample_count: desc.sample_count, + color_attachments: &color_attachments, + depth_stencil_attachment: desc + .depth_stencil_attachment + .as_ref() + .map(|ds| ds.expect_downcast()), + multiview_mask: desc.multiview_mask, + timestamp_writes: desc + .timestamp_writes + .as_ref() + .map(|writes| writes.expect_downcast()), + occlusion_query_set: desc + .occlusion_query_set + .map(|set| set.expect_downcast_ref()), + }; + unsafe { C::begin_render_pass(self, &desc) } + } + + unsafe fn end_render_pass(&mut self) { + unsafe { + C::end_render_pass(self); + } + } + + unsafe fn set_viewport(&mut self, rect: &Rect<f32>, depth_range: Range<f32>) { + unsafe { + C::set_viewport(self, rect, depth_range); + } + } + + unsafe fn set_scissor_rect(&mut self, rect: &Rect<u32>) { + unsafe { + C::set_scissor_rect(self, rect); + } + } + + unsafe fn set_stencil_reference(&mut self, value: u32) { + unsafe { + C::set_stencil_reference(self, value); + } + } + + unsafe fn set_blend_constants(&mut self, color: &[f32; 4]) { + unsafe { C::set_blend_constants(self, color) }; + } + + unsafe fn draw( + &mut self, + first_vertex: u32, + vertex_count: u32, + first_instance: u32, + instance_count: u32, + ) { + unsafe { + C::draw( + self, + first_vertex, + vertex_count, + first_instance, + instance_count, + ) + }; + } + + unsafe fn draw_indexed( + &mut self, + first_index: u32, + index_count: u32, + base_vertex: i32, + first_instance: u32, + instance_count: u32, + ) { + unsafe { + C::draw_indexed( + self, + first_index, + index_count, + base_vertex, + first_instance, + instance_count, + ) + }; + } + + unsafe fn draw_mesh_tasks( + &mut self, + group_count_x: u32, + group_count_y: u32, + group_count_z: u32, + ) { + unsafe { C::draw_mesh_tasks(self, group_count_x, group_count_y, group_count_z) }; + } + + unsafe fn draw_indirect( + &mut self, + buffer: &dyn DynBuffer, + offset: wgt::BufferAddress, + draw_count: u32, + ) { + let buffer = buffer.expect_downcast_ref(); + unsafe { C::draw_indirect(self, buffer, offset, draw_count) }; + } + + unsafe fn draw_indexed_indirect( + &mut self, + buffer: &dyn DynBuffer, + offset: wgt::BufferAddress, + draw_count: u32, + ) { + let buffer = buffer.expect_downcast_ref(); + unsafe { C::draw_indexed_indirect(self, buffer, offset, draw_count) }; + } + + unsafe fn draw_mesh_tasks_indirect( + &mut self, + buffer: &dyn DynBuffer, + offset: wgt::BufferAddress, + draw_count: u32, + ) { + let buffer = buffer.expect_downcast_ref(); + unsafe { C::draw_mesh_tasks_indirect(self, buffer, offset, draw_count) }; + } + + unsafe fn draw_indirect_count( + &mut self, + buffer: &dyn DynBuffer, + offset: wgt::BufferAddress, + count_buffer: &dyn DynBuffer, + count_offset: wgt::BufferAddress, + max_count: u32, + ) { + let buffer = buffer.expect_downcast_ref(); + let count_buffer = count_buffer.expect_downcast_ref(); + unsafe { + C::draw_indirect_count(self, buffer, offset, count_buffer, count_offset, max_count) + }; + } + + unsafe fn draw_indexed_indirect_count( + &mut self, + buffer: &dyn DynBuffer, + offset: wgt::BufferAddress, + count_buffer: &dyn DynBuffer, + count_offset: wgt::BufferAddress, + max_count: u32, + ) { + let buffer = buffer.expect_downcast_ref(); + let count_buffer = count_buffer.expect_downcast_ref(); + unsafe { + C::draw_indexed_indirect_count( + self, + buffer, + offset, + count_buffer, + count_offset, + max_count, + ) + }; + } + + unsafe fn draw_mesh_tasks_indirect_count( + &mut self, + buffer: &dyn DynBuffer, + offset: wgt::BufferAddress, + count_buffer: &dyn DynBuffer, + count_offset: wgt::BufferAddress, + max_count: u32, + ) { + let buffer = buffer.expect_downcast_ref(); + let count_buffer = count_buffer.expect_downcast_ref(); + unsafe { + C::draw_mesh_tasks_indirect_count( + self, + buffer, + offset, + count_buffer, + count_offset, + max_count, + ) + }; + } + + unsafe fn begin_compute_pass(&mut self, desc: &ComputePassDescriptor<dyn DynQuerySet>) { + let desc = ComputePassDescriptor { + label: desc.label, + timestamp_writes: desc + .timestamp_writes + .as_ref() + .map(|writes| writes.expect_downcast()), + }; + unsafe { C::begin_compute_pass(self, &desc) }; + } + + unsafe fn end_compute_pass(&mut self) { + unsafe { C::end_compute_pass(self) }; + } + + unsafe fn set_compute_pipeline(&mut self, pipeline: &dyn DynComputePipeline) { + let pipeline = pipeline.expect_downcast_ref(); + unsafe { C::set_compute_pipeline(self, pipeline) }; + } + + unsafe fn dispatch_workgroups(&mut self, count: [u32; 3]) { + unsafe { C::dispatch_workgroups(self, count) }; + } + + unsafe fn dispatch_workgroups_indirect( + &mut self, + buffer: &dyn DynBuffer, + offset: wgt::BufferAddress, + ) { + let buffer = buffer.expect_downcast_ref(); + unsafe { C::dispatch_workgroups_indirect(self, buffer, offset) }; + } + + unsafe fn set_render_pipeline(&mut self, pipeline: &dyn DynRenderPipeline) { + let pipeline = pipeline.expect_downcast_ref(); + unsafe { C::set_render_pipeline(self, pipeline) }; + } + + unsafe fn set_index_buffer<'a>( + &mut self, + binding: BufferBinding<'a, dyn DynBuffer>, + format: wgt::IndexFormat, + ) { + let binding = binding.expect_downcast(); + unsafe { self.set_index_buffer(binding, format) }; + } + + unsafe fn set_vertex_buffer<'a>( + &mut self, + index: u32, + binding: BufferBinding<'a, dyn DynBuffer>, + ) { + let binding = binding.expect_downcast(); + unsafe { self.set_vertex_buffer(index, binding) }; + } + + unsafe fn begin_ray_tracing_pass(&mut self, desc: &RayTracingPassDescriptor) { + let desc = RayTracingPassDescriptor { label: desc.label }; + unsafe { C::begin_ray_tracing_pass(self, &desc) }; + } + + unsafe fn end_ray_tracing_pass(&mut self) { + unsafe { C::end_ray_tracing_pass(self) }; + } + + unsafe fn set_ray_tracing_pipeline(&mut self, pipeline: &dyn DynRayTracingPipeline) { + let pipeline = pipeline.expect_downcast_ref(); + unsafe { C::set_ray_tracing_pipeline(self, pipeline) }; + } + + unsafe fn trace_rays<'a>( + &mut self, + count: [u32; 3], + ray_generation_group_data: crate::PipelineGroupData<'a, dyn DynBuffer>, + miss_group_data: crate::PipelineGroupData<'a, dyn DynBuffer>, + intersection_group_data: crate::PipelineGroupData<'a, dyn DynBuffer>, + ) { + let downcast_group_data = + |data: crate::PipelineGroupData<'a, dyn DynBuffer>| crate::PipelineGroupData { + buffer: data.buffer.expect_downcast_ref(), + offset: data.offset, + stride: data.stride, + count: data.count, + }; + + unsafe { + C::trace_rays( + self, + count, + downcast_group_data(ray_generation_group_data), + downcast_group_data(miss_group_data), + downcast_group_data(intersection_group_data), + ); + } + } + + unsafe fn build_acceleration_structures<'a>( + &mut self, + descriptors: &'a [BuildAccelerationStructureDescriptor< + 'a, + dyn DynBuffer, + dyn DynAccelerationStructure, + >], + ) { + // Need to collect entries here so we can reference them in the descriptor. + // TODO: API should be redesigned to avoid this and other descriptor copies that happen due to the dyn api. + let descriptor_entries = descriptors + .iter() + .map(|d| d.entries.expect_downcast()) + .collect::<Vec<_>>(); + let descriptors = descriptors + .iter() + .zip(descriptor_entries.iter()) + .map(|(d, entries)| BuildAccelerationStructureDescriptor::< + <C::A as Api>::Buffer, + <C::A as Api>::AccelerationStructure, + > { + entries, + mode: d.mode, + flags: d.flags, + source_acceleration_structure: d + .source_acceleration_structure + .map(|a| a.expect_downcast_ref()), + destination_acceleration_structure: d + .destination_acceleration_structure + .expect_downcast_ref(), + scratch_buffer: d.scratch_buffer.expect_downcast_ref(), + scratch_buffer_offset: d.scratch_buffer_offset, + }); + unsafe { C::build_acceleration_structures(self, descriptors.len() as _, descriptors) }; + } + + unsafe fn place_acceleration_structure_barrier( + &mut self, + barrier: AccelerationStructureBarrier, + ) { + unsafe { C::place_acceleration_structure_barrier(self, barrier) }; + } + + unsafe fn copy_acceleration_structure_to_acceleration_structure( + &mut self, + src: &dyn DynAccelerationStructure, + dst: &dyn DynAccelerationStructure, + copy: wgt::AccelerationStructureCopy, + ) { + let src = src.expect_downcast_ref(); + let dst = dst.expect_downcast_ref(); + unsafe { C::copy_acceleration_structure_to_acceleration_structure(self, src, dst, copy) }; + } + unsafe fn read_acceleration_structure_compact_size( + &mut self, + acceleration_structure: &dyn DynAccelerationStructure, + buf: &dyn DynBuffer, + ) { + let acceleration_structure = acceleration_structure.expect_downcast_ref(); + let buf = buf.expect_downcast_ref(); + unsafe { C::read_acceleration_structure_compact_size(self, acceleration_structure, buf) } + } + + unsafe fn set_acceleration_structure_dependencies( + &self, + command_buffers: &[Box<dyn DynCommandBuffer>], + dependencies: &[&dyn DynAccelerationStructure], + ) { + let command_buffers: Vec<&<C::A as Api>::CommandBuffer> = command_buffers + .iter() + .map(|command_buffer| command_buffer.expect_downcast_ref()) + .collect(); + let dependencies: Vec<&<C::A as Api>::AccelerationStructure> = dependencies + .iter() + .map(|dependency| dependency.expect_downcast_ref()) + .collect(); + unsafe { C::set_acceleration_structure_dependencies(&command_buffers, &dependencies) } + } +} + +impl<'a> PassTimestampWrites<'a, dyn DynQuerySet> { + pub fn expect_downcast<B: DynQuerySet>(&self) -> PassTimestampWrites<'a, B> { + PassTimestampWrites { + query_set: self.query_set.expect_downcast_ref(), + beginning_of_pass_write_index: self.beginning_of_pass_write_index, + end_of_pass_write_index: self.end_of_pass_write_index, + } + } +} + +impl<'a> Attachment<'a, dyn DynTextureView> { + pub fn expect_downcast<B: DynTextureView>(&self) -> Attachment<'a, B> { + Attachment { + view: self.view.expect_downcast_ref(), + usage: self.usage, + } + } +} + +impl<'a> ColorAttachment<'a, dyn DynTextureView> { + pub fn expect_downcast<B: DynTextureView>(&self) -> ColorAttachment<'a, B> { + ColorAttachment { + target: self.target.expect_downcast(), + depth_slice: self.depth_slice, + resolve_target: self.resolve_target.as_ref().map(|rt| rt.expect_downcast()), + ops: self.ops, + clear_value: self.clear_value, + } + } +} + +impl<'a> DepthStencilAttachment<'a, dyn DynTextureView> { + pub fn expect_downcast<B: DynTextureView>(&self) -> DepthStencilAttachment<'a, B> { + DepthStencilAttachment { + target: self.target.expect_downcast(), + depth_ops: self.depth_ops, + stencil_ops: self.stencil_ops, + clear_value: self.clear_value, + } + } +} diff --git a/app/vendor/rune/vendor/wgpu-hal/src/dynamic/device.rs b/app/vendor/rune/vendor/wgpu-hal/src/dynamic/device.rs new file mode 100644 index 0000000..f9b9fe6 --- /dev/null +++ b/app/vendor/rune/vendor/wgpu-hal/src/dynamic/device.rs @@ -0,0 +1,622 @@ +use alloc::{borrow::ToOwned as _, boxed::Box, vec::Vec}; + +use crate::{ + AccelerationStructureBuildSizes, AccelerationStructureDescriptor, Api, BindGroupDescriptor, + BindGroupLayoutDescriptor, BufferDescriptor, BufferMapping, CommandEncoderDescriptor, + ComputePipelineDescriptor, Device, DeviceError, FenceValue, + GetAccelerationStructureBuildSizesDescriptor, Label, MemoryRange, PipelineCacheDescriptor, + PipelineCacheError, PipelineError, PipelineLayoutDescriptor, RayObjectIntersectionState, + RayTracingPipelineDescriptor, RenderPipelineDescriptor, SamplerDescriptor, ShaderError, + ShaderInput, ShaderModuleDescriptor, TextureDescriptor, TextureViewDescriptor, TlasInstance, +}; + +use super::{ + DynAccelerationStructure, DynBindGroup, DynBindGroupLayout, DynBuffer, DynCommandEncoder, + DynComputePipeline, DynFence, DynPipelineCache, DynPipelineLayout, DynQuerySet, DynQueue, + DynRayTracingPipeline, DynRenderPipeline, DynResource, DynResourceExt as _, DynSampler, + DynShaderModule, DynTexture, DynTextureView, +}; + +pub trait DynDevice: DynResource { + unsafe fn create_buffer( + &self, + desc: &BufferDescriptor, + ) -> Result<Box<dyn DynBuffer>, DeviceError>; + + unsafe fn destroy_buffer(&self, buffer: Box<dyn DynBuffer>); + unsafe fn add_raw_buffer(&self, buffer: &dyn DynBuffer); + + unsafe fn map_buffer( + &self, + buffer: &dyn DynBuffer, + range: MemoryRange, + ) -> Result<BufferMapping, DeviceError>; + + unsafe fn unmap_buffer(&self, buffer: &dyn DynBuffer); + + unsafe fn flush_mapped_ranges(&self, buffer: &dyn DynBuffer, ranges: &[MemoryRange]); + unsafe fn invalidate_mapped_ranges(&self, buffer: &dyn DynBuffer, ranges: &[MemoryRange]); + + unsafe fn create_texture( + &self, + desc: &TextureDescriptor, + ) -> Result<Box<dyn DynTexture>, DeviceError>; + unsafe fn destroy_texture(&self, texture: Box<dyn DynTexture>); + unsafe fn add_raw_texture(&self, texture: &dyn DynTexture); + + unsafe fn create_texture_view( + &self, + texture: &dyn DynTexture, + desc: &TextureViewDescriptor, + ) -> Result<Box<dyn DynTextureView>, DeviceError>; + unsafe fn destroy_texture_view(&self, view: Box<dyn DynTextureView>); + unsafe fn create_sampler( + &self, + desc: &SamplerDescriptor, + ) -> Result<Box<dyn DynSampler>, DeviceError>; + unsafe fn destroy_sampler(&self, sampler: Box<dyn DynSampler>); + + unsafe fn create_command_encoder( + &self, + desc: &CommandEncoderDescriptor<dyn DynQueue>, + ) -> Result<Box<dyn DynCommandEncoder>, DeviceError>; + + unsafe fn create_bind_group_layout( + &self, + desc: &BindGroupLayoutDescriptor, + ) -> Result<Box<dyn DynBindGroupLayout>, DeviceError>; + unsafe fn destroy_bind_group_layout(&self, bg_layout: Box<dyn DynBindGroupLayout>); + + unsafe fn create_pipeline_layout( + &self, + desc: &PipelineLayoutDescriptor<dyn DynBindGroupLayout>, + ) -> Result<Box<dyn DynPipelineLayout>, DeviceError>; + unsafe fn destroy_pipeline_layout(&self, pipeline_layout: Box<dyn DynPipelineLayout>); + + unsafe fn create_bind_group( + &self, + desc: &BindGroupDescriptor< + dyn DynBindGroupLayout, + dyn DynBuffer, + dyn DynSampler, + dyn DynTextureView, + dyn DynAccelerationStructure, + >, + ) -> Result<Box<dyn DynBindGroup>, DeviceError>; + unsafe fn destroy_bind_group(&self, group: Box<dyn DynBindGroup>); + + unsafe fn create_shader_module( + &self, + desc: &ShaderModuleDescriptor, + shader: ShaderInput, + ) -> Result<Box<dyn DynShaderModule>, ShaderError>; + unsafe fn destroy_shader_module(&self, module: Box<dyn DynShaderModule>); + + unsafe fn create_render_pipeline( + &self, + desc: &RenderPipelineDescriptor< + dyn DynPipelineLayout, + dyn DynShaderModule, + dyn DynPipelineCache, + >, + ) -> Result<Box<dyn DynRenderPipeline>, PipelineError>; + unsafe fn destroy_render_pipeline(&self, pipeline: Box<dyn DynRenderPipeline>); + + unsafe fn create_compute_pipeline( + &self, + desc: &ComputePipelineDescriptor< + dyn DynPipelineLayout, + dyn DynShaderModule, + dyn DynPipelineCache, + >, + ) -> Result<Box<dyn DynComputePipeline>, PipelineError>; + unsafe fn destroy_compute_pipeline(&self, pipeline: Box<dyn DynComputePipeline>); + + unsafe fn create_ray_tracing_pipeline( + &self, + desc: &RayTracingPipelineDescriptor< + dyn DynPipelineLayout, + dyn DynShaderModule, + dyn DynPipelineCache, + >, + ) -> Result<Box<dyn DynRayTracingPipeline>, PipelineError>; + unsafe fn destroy_ray_tracing_pipeline(&self, pipeline: Box<dyn DynRayTracingPipeline>); + unsafe fn get_raytracing_pipeline_group_data( + &self, + pipeline: &dyn DynRayTracingPipeline, + groups: core::ops::Range<u32>, + ) -> Result<Vec<u8>, DeviceError>; + + unsafe fn create_pipeline_cache( + &self, + desc: &PipelineCacheDescriptor<'_>, + ) -> Result<Box<dyn DynPipelineCache>, PipelineCacheError>; + fn pipeline_cache_validation_key(&self) -> Option<[u8; 16]> { + None + } + unsafe fn destroy_pipeline_cache(&self, cache: Box<dyn DynPipelineCache>); + + unsafe fn create_query_set( + &self, + desc: &wgt::QuerySetDescriptor<Label>, + ) -> Result<Box<dyn DynQuerySet>, DeviceError>; + unsafe fn destroy_query_set(&self, set: Box<dyn DynQuerySet>); + + unsafe fn create_fence(&self) -> Result<Box<dyn DynFence>, DeviceError>; + unsafe fn destroy_fence(&self, fence: Box<dyn DynFence>); + unsafe fn get_fence_value(&self, fence: &dyn DynFence) -> Result<FenceValue, DeviceError>; + + unsafe fn wait( + &self, + fence: &dyn DynFence, + value: FenceValue, + timeout: Option<core::time::Duration>, + ) -> Result<bool, DeviceError>; + + unsafe fn start_graphics_debugger_capture(&self) -> bool; + unsafe fn stop_graphics_debugger_capture(&self); + + unsafe fn pipeline_cache_get_data(&self, cache: &dyn DynPipelineCache) -> Option<Vec<u8>>; + + unsafe fn create_acceleration_structure( + &self, + desc: &AccelerationStructureDescriptor, + ) -> Result<Box<dyn DynAccelerationStructure>, DeviceError>; + unsafe fn get_acceleration_structure_build_sizes( + &self, + desc: &GetAccelerationStructureBuildSizesDescriptor<dyn DynBuffer>, + ) -> AccelerationStructureBuildSizes; + unsafe fn get_acceleration_structure_device_address( + &self, + acceleration_structure: &dyn DynAccelerationStructure, + ) -> wgt::BufferAddress; + unsafe fn destroy_acceleration_structure( + &self, + acceleration_structure: Box<dyn DynAccelerationStructure>, + ); + fn tlas_instance_to_bytes(&self, instance: TlasInstance) -> Vec<u8>; + + fn get_internal_counters(&self) -> wgt::HalCounters; + fn generate_allocator_report(&self) -> Option<wgt::AllocatorReport>; + + fn check_if_oom(&self) -> Result<(), DeviceError>; +} + +impl<D: Device + DynResource> DynDevice for D { + unsafe fn create_buffer( + &self, + desc: &BufferDescriptor, + ) -> Result<Box<dyn DynBuffer>, DeviceError> { + unsafe { D::create_buffer(self, desc) }.map(|b| -> Box<dyn DynBuffer> { Box::new(b) }) + } + + unsafe fn destroy_buffer(&self, buffer: Box<dyn DynBuffer>) { + unsafe { D::destroy_buffer(self, buffer.unbox()) }; + } + unsafe fn add_raw_buffer(&self, buffer: &dyn DynBuffer) { + let buffer = buffer.expect_downcast_ref(); + unsafe { D::add_raw_buffer(self, buffer) }; + } + + unsafe fn map_buffer( + &self, + buffer: &dyn DynBuffer, + range: MemoryRange, + ) -> Result<BufferMapping, DeviceError> { + let buffer = buffer.expect_downcast_ref(); + unsafe { D::map_buffer(self, buffer, range) } + } + + unsafe fn unmap_buffer(&self, buffer: &dyn DynBuffer) { + let buffer = buffer.expect_downcast_ref(); + unsafe { D::unmap_buffer(self, buffer) } + } + + unsafe fn flush_mapped_ranges(&self, buffer: &dyn DynBuffer, ranges: &[MemoryRange]) { + let buffer = buffer.expect_downcast_ref(); + unsafe { D::flush_mapped_ranges(self, buffer, ranges.iter().cloned()) } + } + + unsafe fn invalidate_mapped_ranges(&self, buffer: &dyn DynBuffer, ranges: &[MemoryRange]) { + let buffer = buffer.expect_downcast_ref(); + unsafe { D::invalidate_mapped_ranges(self, buffer, ranges.iter().cloned()) } + } + + unsafe fn create_texture( + &self, + desc: &TextureDescriptor, + ) -> Result<Box<dyn DynTexture>, DeviceError> { + unsafe { D::create_texture(self, desc) }.map(|b| { + let boxed_texture: Box<<D::A as Api>::Texture> = Box::new(b); + let boxed_texture: Box<dyn DynTexture> = boxed_texture; + boxed_texture + }) + } + + unsafe fn destroy_texture(&self, texture: Box<dyn DynTexture>) { + unsafe { D::destroy_texture(self, texture.unbox()) }; + } + + unsafe fn add_raw_texture(&self, texture: &dyn DynTexture) { + let texture = texture.expect_downcast_ref(); + unsafe { D::add_raw_texture(self, texture) }; + } + + unsafe fn create_texture_view( + &self, + texture: &dyn DynTexture, + desc: &TextureViewDescriptor, + ) -> Result<Box<dyn DynTextureView>, DeviceError> { + let texture = texture.expect_downcast_ref(); + unsafe { D::create_texture_view(self, texture, desc) }.map(|b| { + let boxed_texture_view: Box<<D::A as Api>::TextureView> = Box::new(b); + let boxed_texture_view: Box<dyn DynTextureView> = boxed_texture_view; + boxed_texture_view + }) + } + + unsafe fn destroy_texture_view(&self, view: Box<dyn DynTextureView>) { + unsafe { D::destroy_texture_view(self, view.unbox()) }; + } + + unsafe fn create_sampler( + &self, + desc: &SamplerDescriptor, + ) -> Result<Box<dyn DynSampler>, DeviceError> { + unsafe { D::create_sampler(self, desc) }.map(|b| { + let boxed_sampler: Box<<D::A as Api>::Sampler> = Box::new(b); + let boxed_sampler: Box<dyn DynSampler> = boxed_sampler; + boxed_sampler + }) + } + + unsafe fn destroy_sampler(&self, sampler: Box<dyn DynSampler>) { + unsafe { D::destroy_sampler(self, sampler.unbox()) }; + } + + unsafe fn create_command_encoder( + &self, + desc: &CommandEncoderDescriptor<'_, dyn DynQueue>, + ) -> Result<Box<dyn DynCommandEncoder>, DeviceError> { + let desc = CommandEncoderDescriptor { + label: desc.label, + queue: desc.queue.expect_downcast_ref(), + }; + unsafe { D::create_command_encoder(self, &desc) } + .map(|b| -> Box<dyn DynCommandEncoder> { Box::new(b) }) + } + + unsafe fn create_bind_group_layout( + &self, + desc: &BindGroupLayoutDescriptor, + ) -> Result<Box<dyn DynBindGroupLayout>, DeviceError> { + unsafe { D::create_bind_group_layout(self, desc) } + .map(|b| -> Box<dyn DynBindGroupLayout> { Box::new(b) }) + } + + unsafe fn destroy_bind_group_layout(&self, bg_layout: Box<dyn DynBindGroupLayout>) { + unsafe { D::destroy_bind_group_layout(self, bg_layout.unbox()) }; + } + + unsafe fn create_pipeline_layout( + &self, + desc: &PipelineLayoutDescriptor<dyn DynBindGroupLayout>, + ) -> Result<Box<dyn DynPipelineLayout>, DeviceError> { + let bind_group_layouts: Vec<_> = desc + .bind_group_layouts + .iter() + .map(|bgl| bgl.map(|bgl| bgl.expect_downcast_ref())) + .collect(); + let desc = PipelineLayoutDescriptor { + label: desc.label, + bind_group_layouts: &bind_group_layouts, + immediate_size: desc.immediate_size, + flags: desc.flags, + }; + + unsafe { D::create_pipeline_layout(self, &desc) } + .map(|b| -> Box<dyn DynPipelineLayout> { Box::new(b) }) + } + + unsafe fn destroy_pipeline_layout(&self, pipeline_layout: Box<dyn DynPipelineLayout>) { + unsafe { D::destroy_pipeline_layout(self, pipeline_layout.unbox()) }; + } + + unsafe fn create_bind_group( + &self, + desc: &BindGroupDescriptor< + dyn DynBindGroupLayout, + dyn DynBuffer, + dyn DynSampler, + dyn DynTextureView, + dyn DynAccelerationStructure, + >, + ) -> Result<Box<dyn DynBindGroup>, DeviceError> { + let buffers: Vec<_> = desc + .buffers + .iter() + .map(|b| b.clone().expect_downcast()) + .collect(); + let samplers: Vec<_> = desc + .samplers + .iter() + .map(|s| s.expect_downcast_ref()) + .collect(); + let textures: Vec<_> = desc + .textures + .iter() + .map(|t| t.clone().expect_downcast()) + .collect(); + let acceleration_structures: Vec<_> = desc + .acceleration_structures + .iter() + .map(|a| a.expect_downcast_ref()) + .collect(); + let external_textures: Vec<_> = desc + .external_textures + .iter() + .map(|et| et.clone().expect_downcast()) + .collect(); + + let desc = BindGroupDescriptor { + label: desc.label.to_owned(), + layout: desc.layout.expect_downcast_ref(), + buffers: &buffers, + samplers: &samplers, + textures: &textures, + entries: desc.entries, + acceleration_structures: &acceleration_structures, + external_textures: &external_textures, + }; + + unsafe { D::create_bind_group(self, &desc) } + .map(|b| -> Box<dyn DynBindGroup> { Box::new(b) }) + } + + unsafe fn destroy_bind_group(&self, group: Box<dyn DynBindGroup>) { + unsafe { D::destroy_bind_group(self, group.unbox()) }; + } + + unsafe fn create_shader_module( + &self, + desc: &ShaderModuleDescriptor, + shader: ShaderInput, + ) -> Result<Box<dyn DynShaderModule>, ShaderError> { + unsafe { D::create_shader_module(self, desc, shader) } + .map(|b| -> Box<dyn DynShaderModule> { Box::new(b) }) + } + + unsafe fn destroy_shader_module(&self, module: Box<dyn DynShaderModule>) { + unsafe { D::destroy_shader_module(self, module.unbox()) }; + } + + unsafe fn create_render_pipeline( + &self, + desc: &RenderPipelineDescriptor< + dyn DynPipelineLayout, + dyn DynShaderModule, + dyn DynPipelineCache, + >, + ) -> Result<Box<dyn DynRenderPipeline>, PipelineError> { + let desc = RenderPipelineDescriptor { + label: desc.label, + layout: desc.layout.expect_downcast_ref(), + vertex_processor: match &desc.vertex_processor { + crate::VertexProcessor::Standard { + vertex_buffers, + vertex_stage, + } => crate::VertexProcessor::Standard { + vertex_buffers, + vertex_stage: vertex_stage.clone().expect_downcast(), + }, + crate::VertexProcessor::Mesh { + task_stage: task, + mesh_stage: mesh, + } => crate::VertexProcessor::Mesh { + task_stage: task.as_ref().map(|a| a.clone().expect_downcast()), + mesh_stage: mesh.clone().expect_downcast(), + }, + }, + primitive: desc.primitive, + depth_stencil: desc.depth_stencil.clone(), + multisample: desc.multisample, + fragment_stage: desc.fragment_stage.clone().map(|f| f.expect_downcast()), + color_targets: desc.color_targets, + multiview_mask: desc.multiview_mask, + cache: desc.cache.map(|c| c.expect_downcast_ref()), + }; + + unsafe { D::create_render_pipeline(self, &desc) } + .map(|b| -> Box<dyn DynRenderPipeline> { Box::new(b) }) + } + + unsafe fn destroy_render_pipeline(&self, pipeline: Box<dyn DynRenderPipeline>) { + unsafe { D::destroy_render_pipeline(self, pipeline.unbox()) }; + } + + unsafe fn create_compute_pipeline( + &self, + desc: &ComputePipelineDescriptor< + dyn DynPipelineLayout, + dyn DynShaderModule, + dyn DynPipelineCache, + >, + ) -> Result<Box<dyn DynComputePipeline>, PipelineError> { + let desc = ComputePipelineDescriptor { + label: desc.label, + layout: desc.layout.expect_downcast_ref(), + stage: desc.stage.clone().expect_downcast(), + cache: desc.cache.as_ref().map(|c| c.expect_downcast_ref()), + }; + + unsafe { D::create_compute_pipeline(self, &desc) } + .map(|b| -> Box<dyn DynComputePipeline> { Box::new(b) }) + } + + unsafe fn destroy_compute_pipeline(&self, pipeline: Box<dyn DynComputePipeline>) { + unsafe { D::destroy_compute_pipeline(self, pipeline.unbox()) }; + } + + unsafe fn create_ray_tracing_pipeline( + &self, + desc: &RayTracingPipelineDescriptor< + dyn DynPipelineLayout, + dyn DynShaderModule, + dyn DynPipelineCache, + >, + ) -> Result<Box<dyn DynRayTracingPipeline>, PipelineError> { + let ray_intersection: Vec<_> = desc + .intersection + .iter() + .map(|stage| RayObjectIntersectionState { + closest_hit: stage.closest_hit.clone().expect_downcast(), + any_hit: stage + .any_hit + .as_ref() + .map(|stage| stage.clone().expect_downcast()), + }) + .collect(); + + let desc = RayTracingPipelineDescriptor { + label: desc.label, + layout: desc.layout.expect_downcast_ref(), + ray_generation: desc.ray_generation.clone().expect_downcast(), + miss: desc.miss.clone().expect_downcast(), + intersection: &ray_intersection, + max_recursion_depth: desc.max_recursion_depth, + cache: desc.cache.as_ref().map(|c| c.expect_downcast_ref()), + }; + + unsafe { D::create_ray_tracing_pipeline(self, &desc) } + .map(|b| -> Box<dyn DynRayTracingPipeline> { Box::new(b) }) + } + + unsafe fn destroy_ray_tracing_pipeline(&self, pipeline: Box<dyn DynRayTracingPipeline>) { + unsafe { + D::destroy_ray_tracing_pipeline(self, pipeline.unbox()); + }; + } + unsafe fn get_raytracing_pipeline_group_data( + &self, + pipeline: &dyn DynRayTracingPipeline, + groups: core::ops::Range<u32>, + ) -> Result<Vec<u8>, DeviceError> { + unsafe { + D::get_raytracing_pipeline_group_data(self, pipeline.expect_downcast_ref(), groups) + } + } + + unsafe fn create_pipeline_cache( + &self, + desc: &PipelineCacheDescriptor<'_>, + ) -> Result<Box<dyn DynPipelineCache>, PipelineCacheError> { + unsafe { D::create_pipeline_cache(self, desc) } + .map(|b| -> Box<dyn DynPipelineCache> { Box::new(b) }) + } + + fn pipeline_cache_validation_key(&self) -> Option<[u8; 16]> { + D::pipeline_cache_validation_key(self) + } + + unsafe fn destroy_pipeline_cache(&self, pipeline_cache: Box<dyn DynPipelineCache>) { + unsafe { D::destroy_pipeline_cache(self, pipeline_cache.unbox()) }; + } + + unsafe fn create_query_set( + &self, + desc: &wgt::QuerySetDescriptor<Label>, + ) -> Result<Box<dyn DynQuerySet>, DeviceError> { + unsafe { D::create_query_set(self, desc) }.map(|b| -> Box<dyn DynQuerySet> { Box::new(b) }) + } + + unsafe fn destroy_query_set(&self, query_set: Box<dyn DynQuerySet>) { + unsafe { D::destroy_query_set(self, query_set.unbox()) }; + } + + unsafe fn create_fence(&self) -> Result<Box<dyn DynFence>, DeviceError> { + unsafe { D::create_fence(self) }.map(|b| -> Box<dyn DynFence> { Box::new(b) }) + } + + unsafe fn destroy_fence(&self, fence: Box<dyn DynFence>) { + unsafe { D::destroy_fence(self, fence.unbox()) }; + } + + unsafe fn get_fence_value(&self, fence: &dyn DynFence) -> Result<FenceValue, DeviceError> { + let fence = fence.expect_downcast_ref(); + unsafe { D::get_fence_value(self, fence) } + } + + unsafe fn wait( + &self, + fence: &dyn DynFence, + value: FenceValue, + timeout: Option<core::time::Duration>, + ) -> Result<bool, DeviceError> { + let fence = fence.expect_downcast_ref(); + unsafe { D::wait(self, fence, value, timeout) } + } + + unsafe fn start_graphics_debugger_capture(&self) -> bool { + unsafe { D::start_graphics_debugger_capture(self) } + } + + unsafe fn stop_graphics_debugger_capture(&self) { + unsafe { D::stop_graphics_debugger_capture(self) } + } + + unsafe fn pipeline_cache_get_data(&self, cache: &dyn DynPipelineCache) -> Option<Vec<u8>> { + let cache = cache.expect_downcast_ref(); + unsafe { D::pipeline_cache_get_data(self, cache) } + } + + unsafe fn create_acceleration_structure( + &self, + desc: &AccelerationStructureDescriptor, + ) -> Result<Box<dyn DynAccelerationStructure>, DeviceError> { + unsafe { D::create_acceleration_structure(self, desc) } + .map(|b| -> Box<dyn DynAccelerationStructure> { Box::new(b) }) + } + + unsafe fn get_acceleration_structure_build_sizes( + &self, + desc: &GetAccelerationStructureBuildSizesDescriptor<dyn DynBuffer>, + ) -> AccelerationStructureBuildSizes { + let entries = desc.entries.expect_downcast(); + let desc = GetAccelerationStructureBuildSizesDescriptor { + entries: &entries, + flags: desc.flags, + }; + unsafe { D::get_acceleration_structure_build_sizes(self, &desc) } + } + + unsafe fn get_acceleration_structure_device_address( + &self, + acceleration_structure: &dyn DynAccelerationStructure, + ) -> wgt::BufferAddress { + let acceleration_structure = acceleration_structure.expect_downcast_ref(); + unsafe { D::get_acceleration_structure_device_address(self, acceleration_structure) } + } + + unsafe fn destroy_acceleration_structure( + &self, + acceleration_structure: Box<dyn DynAccelerationStructure>, + ) { + unsafe { D::destroy_acceleration_structure(self, acceleration_structure.unbox()) } + } + + fn tlas_instance_to_bytes(&self, instance: TlasInstance) -> Vec<u8> { + D::tlas_instance_to_bytes(self, instance) + } + + fn get_internal_counters(&self) -> wgt::HalCounters { + D::get_internal_counters(self) + } + + fn generate_allocator_report(&self) -> Option<wgt::AllocatorReport> { + D::generate_allocator_report(self) + } + + fn check_if_oom(&self) -> Result<(), DeviceError> { + D::check_if_oom(self) + } +} diff --git a/app/vendor/rune/vendor/wgpu-hal/src/dynamic/instance.rs b/app/vendor/rune/vendor/wgpu-hal/src/dynamic/instance.rs new file mode 100644 index 0000000..cab14cd --- /dev/null +++ b/app/vendor/rune/vendor/wgpu-hal/src/dynamic/instance.rs @@ -0,0 +1,71 @@ +use alloc::{boxed::Box, vec::Vec}; + +use crate::{Api, Capabilities, ExposedAdapter, Instance, InstanceError}; + +use super::{DynAdapter, DynResource, DynResourceExt as _, DynSurface}; + +#[expect(missing_debug_implementations, reason = "dyn")] +pub struct DynExposedAdapter { + pub adapter: Box<dyn DynAdapter>, + pub info: wgt::AdapterInfo, + pub features: wgt::Features, + pub capabilities: Capabilities, +} + +impl DynExposedAdapter { + /// Returns the backend this adapter is using. + pub fn backend(&self) -> wgt::Backend { + self.info.backend + } +} + +impl<A: Api> From<ExposedAdapter<A>> for DynExposedAdapter { + fn from(exposed_adapter: ExposedAdapter<A>) -> Self { + Self { + adapter: Box::new(exposed_adapter.adapter), + info: exposed_adapter.info, + features: exposed_adapter.features, + capabilities: exposed_adapter.capabilities, + } + } +} + +pub trait DynInstance: DynResource { + unsafe fn create_surface( + &self, + display_handle: raw_window_handle::RawDisplayHandle, + window_handle: raw_window_handle::RawWindowHandle, + ) -> Result<Box<dyn DynSurface>, InstanceError>; + + unsafe fn enumerate_adapters( + &self, + surface_hint: Option<&dyn DynSurface>, + ) -> Vec<DynExposedAdapter>; +} + +impl<I: Instance + DynResource> DynInstance for I { + unsafe fn create_surface( + &self, + display_handle: raw_window_handle::RawDisplayHandle, + window_handle: raw_window_handle::RawWindowHandle, + ) -> Result<Box<dyn DynSurface>, InstanceError> { + unsafe { I::create_surface(self, display_handle, window_handle) } + .map(|surface| -> Box<dyn DynSurface> { Box::new(surface) }) + } + + unsafe fn enumerate_adapters( + &self, + surface_hint: Option<&dyn DynSurface>, + ) -> Vec<DynExposedAdapter> { + let surface_hint = surface_hint.map(|s| s.expect_downcast_ref()); + unsafe { I::enumerate_adapters(self, surface_hint) } + .into_iter() + .map(|exposed| DynExposedAdapter { + adapter: Box::new(exposed.adapter), + info: exposed.info, + features: exposed.features, + capabilities: exposed.capabilities, + }) + .collect() + } +} diff --git a/app/vendor/rune/vendor/wgpu-hal/src/dynamic/mod.rs b/app/vendor/rune/vendor/wgpu-hal/src/dynamic/mod.rs new file mode 100644 index 0000000..cce4d3b --- /dev/null +++ b/app/vendor/rune/vendor/wgpu-hal/src/dynamic/mod.rs @@ -0,0 +1,212 @@ +mod adapter; +mod command; +mod device; +mod instance; +mod queue; +mod surface; + +pub use adapter::{DynAdapter, DynOpenDevice}; +pub use command::DynCommandEncoder; +pub use device::DynDevice; +pub use instance::{DynExposedAdapter, DynInstance}; +pub use queue::DynQueue; +pub use surface::{DynAcquiredSurfaceTexture, DynSurface}; + +use alloc::boxed::Box; +use core::{ + any::{Any, TypeId}, + fmt, +}; + +use wgt::WasmNotSendSync; + +use crate::{ + AccelerationStructureAABBs, AccelerationStructureEntries, AccelerationStructureInstances, + AccelerationStructureTriangleIndices, AccelerationStructureTriangleTransform, + AccelerationStructureTriangles, BufferBinding, ExternalTextureBinding, ProgrammableStage, + TextureBinding, +}; + +/// Base trait for all resources, allows downcasting via [`Any`]. +pub trait DynResource: Any + WasmNotSendSync + 'static { + fn as_any(&self) -> &dyn Any; + fn as_any_mut(&mut self) -> &mut dyn Any; +} + +/// Utility macro for implementing `DynResource` for a list of types. +macro_rules! impl_dyn_resource { + ($($type:ty),*) => { + $( + impl crate::DynResource for $type { + fn as_any(&self) -> &dyn ::core::any::Any { + self + } + + fn as_any_mut(&mut self) -> &mut dyn ::core::any::Any { + self + } + } + )* + }; +} +pub(crate) use impl_dyn_resource; + +/// Extension trait for `DynResource` used by implementations of various dynamic resource traits. +trait DynResourceExt { + /// # Panics + /// + /// - Panics if `self` is not downcastable to `T`. + fn expect_downcast_ref<T: DynResource>(&self) -> &T; + + /// Unboxes a `Box<dyn DynResource>` to a concrete type. + /// + /// # Safety + /// + /// - `self` must be the correct concrete type. + unsafe fn unbox<T: DynResource + 'static>(self: Box<Self>) -> T; +} + +impl<R: DynResource + ?Sized> DynResourceExt for R { + fn expect_downcast_ref<'a, T: DynResource>(&'a self) -> &'a T { + self.as_any() + .downcast_ref() + .expect("Resource doesn't have the expected backend type.") + } + + unsafe fn unbox<T: DynResource + 'static>(self: Box<Self>) -> T { + debug_assert!( + <Self as Any>::type_id(self.as_ref()) == TypeId::of::<T>(), + "Resource doesn't have the expected type, expected {:?}, got {:?}", + TypeId::of::<T>(), + <Self as Any>::type_id(self.as_ref()) + ); + + let casted_ptr = Box::into_raw(self).cast::<T>(); + // SAFETY: This is adheres to the safety contract of `Box::from_raw` because: + // + // - We are casting the value of a previously `Box`ed value, which guarantees: + // - `casted_ptr` is not null. + // - `casted_ptr` is valid for reads and writes, though by itself this does not mean + // valid reads and writes for `T` (read on for that). + // - We don't change the allocator. + // - The contract of `Box::from_raw` requires that an initialized and aligned `T` is stored + // within `casted_ptr`. + *unsafe { Box::from_raw(casted_ptr) } + } +} + +pub trait DynAccelerationStructure: DynResource + fmt::Debug {} +pub trait DynBindGroup: DynResource + fmt::Debug {} +pub trait DynBindGroupLayout: DynResource + fmt::Debug {} +pub trait DynBuffer: DynResource + fmt::Debug {} +pub trait DynCommandBuffer: DynResource + fmt::Debug {} +pub trait DynComputePipeline: DynResource + fmt::Debug {} +pub trait DynFence: DynResource + fmt::Debug {} +pub trait DynPipelineCache: DynResource + fmt::Debug {} +pub trait DynPipelineLayout: DynResource + fmt::Debug {} +pub trait DynQuerySet: DynResource + fmt::Debug {} +pub trait DynRenderPipeline: DynResource + fmt::Debug {} +pub trait DynRayTracingPipeline: DynResource + fmt::Debug {} +pub trait DynSampler: DynResource + fmt::Debug {} +pub trait DynShaderModule: DynResource + fmt::Debug {} +pub trait DynSurfaceTexture: + DynResource + core::borrow::Borrow<dyn DynTexture> + fmt::Debug +{ +} +pub trait DynTexture: DynResource + fmt::Debug {} +pub trait DynTextureView: DynResource + fmt::Debug {} + +impl<'a> BufferBinding<'a, dyn DynBuffer> { + pub fn expect_downcast<B: DynBuffer>(self) -> BufferBinding<'a, B> { + BufferBinding { + buffer: self.buffer.expect_downcast_ref(), + offset: self.offset, + size: self.size, + } + } +} + +impl<'a> TextureBinding<'a, dyn DynTextureView> { + pub fn expect_downcast<T: DynTextureView>(self) -> TextureBinding<'a, T> { + TextureBinding { + view: self.view.expect_downcast_ref(), + usage: self.usage, + } + } +} + +impl<'a> ExternalTextureBinding<'a, dyn DynBuffer, dyn DynTextureView> { + pub fn expect_downcast<B: DynBuffer, T: DynTextureView>( + self, + ) -> ExternalTextureBinding<'a, B, T> { + let planes = self.planes.map(|plane| plane.expect_downcast()); + let params = self.params.expect_downcast(); + ExternalTextureBinding { planes, params } + } +} + +impl<'a> ProgrammableStage<'a, dyn DynShaderModule> { + fn expect_downcast<T: DynShaderModule>(self) -> ProgrammableStage<'a, T> { + ProgrammableStage { + module: self.module.expect_downcast_ref(), + entry_point: self.entry_point, + constants: self.constants, + zero_initialize_workgroup_memory: self.zero_initialize_workgroup_memory, + } + } +} + +impl<'a> AccelerationStructureEntries<'a, dyn DynBuffer> { + fn expect_downcast<B: DynBuffer>(&self) -> AccelerationStructureEntries<'a, B> { + match self { + AccelerationStructureEntries::Instances(instances) => { + AccelerationStructureEntries::Instances(AccelerationStructureInstances { + buffer: instances.buffer.map(|b| b.expect_downcast_ref()), + offset: instances.offset, + count: instances.count, + }) + } + AccelerationStructureEntries::Triangles(triangles) => { + AccelerationStructureEntries::Triangles( + triangles + .iter() + .map(|t| AccelerationStructureTriangles { + vertex_buffer: t.vertex_buffer.map(|b| b.expect_downcast_ref()), + vertex_format: t.vertex_format, + first_vertex: t.first_vertex, + vertex_count: t.vertex_count, + vertex_stride: t.vertex_stride, + indices: t.indices.as_ref().map(|i| { + AccelerationStructureTriangleIndices { + buffer: i.buffer.map(|b| b.expect_downcast_ref()), + format: i.format, + offset: i.offset, + count: i.count, + } + }), + transform: t.transform.as_ref().map(|t| { + AccelerationStructureTriangleTransform { + buffer: t.buffer.expect_downcast_ref(), + offset: t.offset, + } + }), + flags: t.flags, + }) + .collect(), + ) + } + AccelerationStructureEntries::AABBs(entries) => AccelerationStructureEntries::AABBs( + entries + .iter() + .map(|e| AccelerationStructureAABBs { + buffer: e.buffer.map(|b| b.expect_downcast_ref()), + offset: e.offset, + count: e.count, + stride: e.stride, + flags: e.flags, + }) + .collect(), + ), + } + } +} diff --git a/app/vendor/rune/vendor/wgpu-hal/src/dynamic/queue.rs b/app/vendor/rune/vendor/wgpu-hal/src/dynamic/queue.rs new file mode 100644 index 0000000..5425b2d --- /dev/null +++ b/app/vendor/rune/vendor/wgpu-hal/src/dynamic/queue.rs @@ -0,0 +1,61 @@ +use alloc::{boxed::Box, vec::Vec}; + +use crate::{ + DeviceError, DynCommandBuffer, DynFence, DynResource, DynSurface, DynSurfaceTexture, + FenceValue, Queue, SurfaceError, +}; + +use super::DynResourceExt as _; + +pub trait DynQueue: DynResource { + unsafe fn submit( + &self, + command_buffers: &[&dyn DynCommandBuffer], + surface_textures: &[&dyn DynSurfaceTexture], + signal_fence: (&dyn DynFence, FenceValue), + ) -> Result<(), DeviceError>; + unsafe fn present( + &self, + surface: &dyn DynSurface, + texture: Box<dyn DynSurfaceTexture>, + ) -> Result<(), SurfaceError>; + unsafe fn get_timestamp_period(&self) -> f32; + unsafe fn wait_for_idle(&self) -> Result<(), DeviceError>; +} + +impl<Q: Queue + DynResource> DynQueue for Q { + unsafe fn submit( + &self, + command_buffers: &[&dyn DynCommandBuffer], + surface_textures: &[&dyn DynSurfaceTexture], + signal_fence: (&dyn DynFence, FenceValue), + ) -> Result<(), DeviceError> { + let command_buffers = command_buffers + .iter() + .map(|cb| (*cb).expect_downcast_ref()) + .collect::<Vec<_>>(); + let surface_textures = surface_textures + .iter() + .map(|surface| (*surface).expect_downcast_ref()) + .collect::<Vec<_>>(); + let signal_fence = (signal_fence.0.expect_downcast_ref(), signal_fence.1); + unsafe { Q::submit(self, &command_buffers, &surface_textures, signal_fence) } + } + + unsafe fn present( + &self, + surface: &dyn DynSurface, + texture: Box<dyn DynSurfaceTexture>, + ) -> Result<(), SurfaceError> { + let surface = surface.expect_downcast_ref(); + unsafe { Q::present(self, surface, texture.unbox()) } + } + + unsafe fn get_timestamp_period(&self) -> f32 { + unsafe { Q::get_timestamp_period(self) } + } + + unsafe fn wait_for_idle(&self) -> Result<(), DeviceError> { + unsafe { Q::wait_for_idle(self) } + } +} diff --git a/app/vendor/rune/vendor/wgpu-hal/src/dynamic/surface.rs b/app/vendor/rune/vendor/wgpu-hal/src/dynamic/surface.rs new file mode 100644 index 0000000..17fa8ee --- /dev/null +++ b/app/vendor/rune/vendor/wgpu-hal/src/dynamic/surface.rs @@ -0,0 +1,72 @@ +use alloc::boxed::Box; +use core::time::Duration; + +use crate::{ + DynDevice, DynFence, DynResource, DynSurfaceTexture, Surface, SurfaceConfiguration, + SurfaceError, +}; + +use super::DynResourceExt as _; + +#[derive(Debug)] +pub struct DynAcquiredSurfaceTexture { + pub texture: Box<dyn DynSurfaceTexture>, + /// The presentation configuration no longer matches + /// the surface properties exactly, but can still be used to present + /// to the surface successfully. + pub suboptimal: bool, +} + +pub trait DynSurface: DynResource { + unsafe fn configure( + &self, + device: &dyn DynDevice, + config: &SurfaceConfiguration, + ) -> Result<(), SurfaceError>; + + unsafe fn unconfigure(&self, device: &dyn DynDevice); + + unsafe fn acquire_texture( + &self, + timeout: Option<Duration>, + fence: &dyn DynFence, + ) -> Result<DynAcquiredSurfaceTexture, SurfaceError>; + + unsafe fn discard_texture(&self, texture: Box<dyn DynSurfaceTexture>); +} + +impl<S: Surface + DynResource> DynSurface for S { + unsafe fn configure( + &self, + device: &dyn DynDevice, + config: &SurfaceConfiguration, + ) -> Result<(), SurfaceError> { + let device = device.expect_downcast_ref(); + unsafe { S::configure(self, device, config) } + } + + unsafe fn unconfigure(&self, device: &dyn DynDevice) { + let device = device.expect_downcast_ref(); + unsafe { S::unconfigure(self, device) } + } + + unsafe fn acquire_texture( + &self, + timeout: Option<Duration>, + fence: &dyn DynFence, + ) -> Result<DynAcquiredSurfaceTexture, SurfaceError> { + let fence = fence.expect_downcast_ref(); + unsafe { S::acquire_texture(self, timeout, fence) }.map(|ast| { + let texture = Box::new(ast.texture); + let suboptimal = ast.suboptimal; + DynAcquiredSurfaceTexture { + texture, + suboptimal, + } + }) + } + + unsafe fn discard_texture(&self, texture: Box<dyn DynSurfaceTexture>) { + unsafe { S::discard_texture(self, texture.unbox()) } + } +} diff --git a/app/vendor/rune/vendor/wgpu-hal/src/gles/adapter.rs b/app/vendor/rune/vendor/wgpu-hal/src/gles/adapter.rs new file mode 100644 index 0000000..47b8115 --- /dev/null +++ b/app/vendor/rune/vendor/wgpu-hal/src/gles/adapter.rs @@ -0,0 +1,1470 @@ +use alloc::{borrow::ToOwned as _, format, string::String, sync::Arc, vec, vec::Vec}; +use core::sync::atomic::AtomicU8; + +use glow::HasContext; +use parking_lot::Mutex; +use wgt::AstcChannel; + +use crate::auxil::db; +use crate::gles::ShaderClearProgram; + +// https://webgl2fundamentals.org/webgl/lessons/webgl-data-textures.html + +const GL_UNMASKED_VENDOR_WEBGL: u32 = 0x9245; +const GL_UNMASKED_RENDERER_WEBGL: u32 = 0x9246; + +impl super::Adapter { + pub fn get_glsl_version(&self) -> naga::back::glsl::Version { + self.shared.shading_language_version + } + + /// Note that this function is intentionally lenient in regards to parsing, + /// and will try to recover at least the first two version numbers without + /// resulting in an `Err`. + /// # Notes + /// `WebGL 2` version returned as `OpenGL ES 3.0` + fn parse_version(mut src: &str) -> Result<(u8, u8), crate::InstanceError> { + let webgl_sig = "WebGL "; + // According to the WebGL specification + // VERSION WebGL<space>1.0<space><vendor-specific information> + // SHADING_LANGUAGE_VERSION WebGL<space>GLSL<space>ES<space>1.0<space><vendor-specific information> + let is_webgl = src.starts_with(webgl_sig); + if is_webgl { + let pos = src.rfind(webgl_sig).unwrap_or(0); + src = &src[pos + webgl_sig.len()..]; + } else { + let es_sig = " ES "; + match src.rfind(es_sig) { + Some(pos) => { + src = &src[pos + es_sig.len()..]; + } + None => { + return Err(crate::InstanceError::new(format!( + "OpenGL version {src:?} does not contain 'ES'" + ))); + } + } + }; + + let glsl_es_sig = "GLSL ES "; + let is_glsl = match src.find(glsl_es_sig) { + Some(pos) => { + src = &src[pos + glsl_es_sig.len()..]; + true + } + None => false, + }; + + Self::parse_full_version(src).map(|(major, minor)| { + ( + // Return WebGL 2.0 version as OpenGL ES 3.0 + if is_webgl && !is_glsl { + major + 1 + } else { + major + }, + minor, + ) + }) + } + + /// According to the OpenGL specification, the version information is + /// expected to follow the following syntax: + /// + /// ~~~bnf + /// <major> ::= <number> + /// <minor> ::= <number> + /// <revision> ::= <number> + /// <vendor-info> ::= <string> + /// <release> ::= <major> "." <minor> ["." <release>] + /// <version> ::= <release> [" " <vendor-info>] + /// ~~~ + /// + /// Note that this function is intentionally lenient in regards to parsing, + /// and will try to recover at least the first two version numbers without + /// resulting in an `Err`. + pub(super) fn parse_full_version(src: &str) -> Result<(u8, u8), crate::InstanceError> { + let (version, _vendor_info) = match src.find(' ') { + Some(i) => (&src[..i], src[i + 1..].to_owned()), + None => (src, String::new()), + }; + + // TODO: make this even more lenient so that we can also accept + // `<major> "." <minor> [<???>]` + let mut it = version.split('.'); + let major = it.next().and_then(|s| s.parse().ok()); + let minor = it.next().and_then(|s| { + let trimmed = if s.starts_with('0') { + "0" + } else { + s.trim_end_matches('0') + }; + trimmed.parse().ok() + }); + + match (major, minor) { + (Some(major), Some(minor)) => Ok((major, minor)), + _ => Err(crate::InstanceError::new(format!( + "unable to extract OpenGL version from {version:?}" + ))), + } + } + + fn make_info(vendor_orig: String, renderer_orig: String, version: String) -> wgt::AdapterInfo { + let vendor = vendor_orig.to_lowercase(); + let renderer = renderer_orig.to_lowercase(); + + // opengl has no way to discern device_type, so we can try to infer it from the renderer string + let strings_that_imply_integrated = [ + " xpress", // space here is on purpose so we don't match express + "amd renoir", + "radeon hd 4200", + "radeon hd 4250", + "radeon hd 4290", + "radeon hd 4270", + "radeon hd 4225", + "radeon hd 3100", + "radeon hd 3200", + "radeon hd 3000", + "radeon hd 3300", + "radeon(tm) r4 graphics", + "radeon(tm) r5 graphics", + "radeon(tm) r6 graphics", + "radeon(tm) r7 graphics", + "radeon r7 graphics", + "nforce", // all nvidia nforce are integrated + "tegra", // all nvidia tegra are integrated + "shield", // all nvidia shield are integrated + "igp", + "mali", + "intel", + "v3d", + "apple m", // all apple m are integrated + ]; + let strings_that_imply_cpu = ["mesa offscreen", "swiftshader", "llvmpipe"]; + + //TODO: handle Intel Iris XE as discreet + let inferred_device_type = if vendor.contains("qualcomm") + || vendor.contains("intel") + || strings_that_imply_integrated + .iter() + .any(|&s| renderer.contains(s)) + { + wgt::DeviceType::IntegratedGpu + } else if strings_that_imply_cpu.iter().any(|&s| renderer.contains(s)) { + wgt::DeviceType::Cpu + } else { + // At this point the Device type is Unknown. + // It's most likely DiscreteGpu, but we do not know for sure. + // Use "Other" to avoid possibly making incorrect assumptions. + // Note that if this same device is available under some other API (ex: Vulkan), + // It will mostly likely get a different device type (probably DiscreteGpu). + wgt::DeviceType::Other + }; + + // source: Sascha Willems at Vulkan + let vendor_id = if vendor.contains("amd") { + db::amd::VENDOR + } else if vendor.contains("imgtec") { + db::imgtec::VENDOR + } else if vendor.contains("nvidia") { + db::nvidia::VENDOR + } else if vendor.contains("arm") { + db::arm::VENDOR + } else if vendor.contains("qualcomm") { + db::qualcomm::VENDOR + } else if vendor.contains("intel") { + db::intel::VENDOR + } else if vendor.contains("broadcom") { + db::broadcom::VENDOR + } else if vendor.contains("mesa") { + db::mesa::VENDOR + } else if vendor.contains("apple") { + db::apple::VENDOR + } else { + 0 + }; + + wgt::AdapterInfo { + name: renderer_orig, + vendor: vendor_id, + driver_info: version, + ..wgt::AdapterInfo::new(inferred_device_type, wgt::Backend::Gl) + } + } + + pub(super) unsafe fn expose( + context: super::AdapterContext, + backend_options: wgt::GlBackendOptions, + ) -> Option<crate::ExposedAdapter<super::Api>> { + let gl = context.lock(); + let extensions = gl.supported_extensions(); + + let (vendor_const, renderer_const) = if extensions.contains("WEBGL_debug_renderer_info") { + // emscripten doesn't enable "WEBGL_debug_renderer_info" extension by default. so, we do it manually. + // See https://github.com/gfx-rs/wgpu/issues/3245 for context + #[cfg(Emscripten)] + if unsafe { + super::emscripten::enable_extension(c"WEBGL_debug_renderer_info".to_str().unwrap()) + } { + (GL_UNMASKED_VENDOR_WEBGL, GL_UNMASKED_RENDERER_WEBGL) + } else { + (glow::VENDOR, glow::RENDERER) + } + // glow already enables WEBGL_debug_renderer_info on wasm32-unknown-unknown target by default. + #[cfg(not(Emscripten))] + (GL_UNMASKED_VENDOR_WEBGL, GL_UNMASKED_RENDERER_WEBGL) + } else { + (glow::VENDOR, glow::RENDERER) + }; + + let vendor = unsafe { gl.get_parameter_string(vendor_const) }; + let renderer = unsafe { gl.get_parameter_string(renderer_const) }; + let version = unsafe { gl.get_parameter_string(glow::VERSION) }; + log::debug!("Vendor: {vendor}"); + log::debug!("Renderer: {renderer}"); + log::debug!("Version: {version}"); + + let full_ver = Self::parse_full_version(&version).ok(); + let es_ver = full_ver.map_or_else(|| Self::parse_version(&version).ok(), |_| None); + + if let Some(full_ver) = full_ver { + let core_profile = (full_ver >= (3, 2)).then(|| unsafe { + gl.get_parameter_i32(glow::CONTEXT_PROFILE_MASK) + & glow::CONTEXT_CORE_PROFILE_BIT as i32 + != 0 + }); + log::trace!( + "Profile: {}", + core_profile + .map(|core_profile| if core_profile { + "Core" + } else { + "Compatibility" + }) + .unwrap_or("Legacy") + ); + } + + if es_ver.is_none() && full_ver.is_none() { + log::warn!("Unable to parse OpenGL version"); + return None; + } + + if let Some(es_ver) = es_ver { + if es_ver < (3, 0) { + log::warn!( + "Returned GLES context is {}.{}, when 3.0+ was requested", + es_ver.0, + es_ver.1 + ); + return None; + } + } + + if let Some(full_ver) = full_ver { + if full_ver < (3, 3) { + log::warn!( + "Returned GL context is {}.{}, when 3.3+ is needed", + full_ver.0, + full_ver.1 + ); + return None; + } + } + + let shading_language_version = { + let sl_version = unsafe { gl.get_parameter_string(glow::SHADING_LANGUAGE_VERSION) }; + log::debug!("SL version: {}", &sl_version); + if full_ver.is_some() { + let (sl_major, sl_minor) = Self::parse_full_version(&sl_version).ok()?; + let mut value = sl_major as u16 * 100 + sl_minor as u16 * 10; + // Naga doesn't think it supports GL 460+, so we cap it at 450 + if value > 450 { + value = 450; + } + naga::back::glsl::Version::Desktop(value) + } else { + let (sl_major, sl_minor) = Self::parse_version(&sl_version).ok()?; + let value = sl_major as u16 * 100 + sl_minor as u16 * 10; + naga::back::glsl::Version::Embedded { + version: value, + is_webgl: cfg!(any(webgl, Emscripten)), + } + } + }; + + log::debug!("Supported GL Extensions: {extensions:#?}"); + + let supported = |(req_es_major, req_es_minor), (req_full_major, req_full_minor)| { + let es_supported = es_ver + .map(|es_ver| es_ver >= (req_es_major, req_es_minor)) + .unwrap_or_default(); + + let full_supported = full_ver + .map(|full_ver| full_ver >= (req_full_major, req_full_minor)) + .unwrap_or_default(); + + es_supported || full_supported + }; + + let supports_storage = + supported((3, 1), (4, 3)) || extensions.contains("GL_ARB_shader_storage_buffer_object"); + let supports_compute = + supported((3, 1), (4, 3)) || extensions.contains("GL_ARB_compute_shader"); + let supports_work_group_params = supports_compute; + + // ANGLE provides renderer strings like: "ANGLE (Apple, Apple M1 Pro, OpenGL 4.1)" + let is_angle = renderer.contains("ANGLE"); + + let vertex_shader_storage_blocks = if supports_storage { + let value = + (unsafe { gl.get_parameter_i32(glow::MAX_VERTEX_SHADER_STORAGE_BLOCKS) } as u32); + + if value == 0 && extensions.contains("GL_ARB_shader_storage_buffer_object") { + // The driver for AMD Radeon HD 5870 returns zero here, so assume the value matches the compute shader storage block count. + // Windows doesn't recognize `GL_MAX_VERTEX_ATTRIB_STRIDE`. + let new = (unsafe { gl.get_parameter_i32(glow::MAX_COMPUTE_SHADER_STORAGE_BLOCKS) } + as u32); + log::debug!("Max vertex shader storage blocks is zero, but GL_ARB_shader_storage_buffer_object is specified. Assuming the compute value {new}"); + new + } else { + value + } + } else { + 0 + }; + let fragment_shader_storage_blocks = if supports_storage { + (unsafe { gl.get_parameter_i32(glow::MAX_FRAGMENT_SHADER_STORAGE_BLOCKS) } as u32) + } else { + 0 + }; + let vertex_shader_storage_textures = if supports_storage { + (unsafe { gl.get_parameter_i32(glow::MAX_VERTEX_IMAGE_UNIFORMS) } as u32) + } else { + 0 + }; + let fragment_shader_storage_textures = if supports_storage { + (unsafe { gl.get_parameter_i32(glow::MAX_FRAGMENT_IMAGE_UNIFORMS) } as u32) + } else { + 0 + }; + let max_storage_block_size = if supports_storage { + (unsafe { gl.get_parameter_i32(glow::MAX_SHADER_STORAGE_BLOCK_SIZE) } as u32) + } else { + 0 + }; + let max_element_index = unsafe { gl.get_parameter_i32(glow::MAX_ELEMENT_INDEX) } as u32; + + // WORKAROUND: In order to work around an issue with GL on RPI4 and similar, we ignore a + // zero vertex ssbo count if there are vertex sstos. (more info: + // https://github.com/gfx-rs/wgpu/pull/1607#issuecomment-874938961) The hardware does not + // want us to write to these SSBOs, but GLES cannot express that. We detect this case and + // disable writing to SSBOs. + let vertex_ssbo_false_zero = + vertex_shader_storage_blocks == 0 && vertex_shader_storage_textures != 0; + if vertex_ssbo_false_zero { + // We only care about fragment here as the 0 is a lie. + log::debug!("Max vertex shader SSBO == 0 and SSTO != 0. Interpreting as false zero."); + } + + let max_storage_buffers_per_shader_stage = if vertex_shader_storage_blocks == 0 { + fragment_shader_storage_blocks + } else { + vertex_shader_storage_blocks.min(fragment_shader_storage_blocks) + }; + let max_storage_textures_per_shader_stage = if vertex_shader_storage_textures == 0 { + fragment_shader_storage_textures + } else { + vertex_shader_storage_textures.min(fragment_shader_storage_textures) + }; + // NOTE: GL_ARB_compute_shader adds support for indirect dispatch + let indirect_execution = supported((3, 1), (4, 3)) + || (extensions.contains("GL_ARB_draw_indirect") && supports_compute); + let supports_cube_array = supported((3, 2), (4, 0)) + || (supported((3, 1), (4, 0)) && extensions.contains("GL_EXT_texture_cube_map_array")); + + let mut downlevel_flags = wgt::DownlevelFlags::empty() + | wgt::DownlevelFlags::NON_POWER_OF_TWO_MIPMAPPED_TEXTURES + | wgt::DownlevelFlags::COMPARISON_SAMPLERS + | wgt::DownlevelFlags::SHADER_F16_IN_F32 + | wgt::DownlevelFlags::MSL2_1; + downlevel_flags.set( + wgt::DownlevelFlags::CUBE_ARRAY_TEXTURES, + supports_cube_array, + ); + downlevel_flags.set(wgt::DownlevelFlags::COMPUTE_SHADERS, supports_compute); + downlevel_flags.set( + wgt::DownlevelFlags::FRAGMENT_WRITABLE_STORAGE, + max_storage_block_size != 0, + ); + downlevel_flags.set(wgt::DownlevelFlags::INDIRECT_EXECUTION, indirect_execution); + downlevel_flags.set(wgt::DownlevelFlags::BASE_VERTEX, supported((3, 2), (3, 2))); + downlevel_flags.set( + wgt::DownlevelFlags::INDEPENDENT_BLEND, + supported((3, 2), (4, 0)) || extensions.contains("GL_EXT_draw_buffers_indexed"), + ); + downlevel_flags.set( + wgt::DownlevelFlags::VERTEX_STORAGE, + max_storage_block_size != 0 + && max_storage_buffers_per_shader_stage != 0 + && (vertex_shader_storage_blocks != 0 || vertex_ssbo_false_zero), + ); + downlevel_flags.set(wgt::DownlevelFlags::FRAGMENT_STORAGE, supports_storage); + if extensions.contains("EXT_texture_filter_anisotropic") + || extensions.contains("GL_EXT_texture_filter_anisotropic") + { + let max_aniso = + unsafe { gl.get_parameter_i32(glow::MAX_TEXTURE_MAX_ANISOTROPY_EXT) } as u32; + downlevel_flags.set(wgt::DownlevelFlags::ANISOTROPIC_FILTERING, max_aniso >= 16); + } + downlevel_flags.set( + wgt::DownlevelFlags::BUFFER_BINDINGS_NOT_16_BYTE_ALIGNED, + !(cfg!(any(webgl, Emscripten)) || is_angle), + ); + // see https://registry.khronos.org/webgl/specs/latest/2.0/#BUFFER_OBJECT_BINDING + downlevel_flags.set( + wgt::DownlevelFlags::UNRESTRICTED_INDEX_BUFFER, + !cfg!(any(webgl, Emscripten)), + ); + downlevel_flags.set( + wgt::DownlevelFlags::UNRESTRICTED_EXTERNAL_TEXTURE_COPIES, + !cfg!(any(webgl, Emscripten)), + ); + downlevel_flags.set( + wgt::DownlevelFlags::FULL_DRAW_INDEX_UINT32, + max_element_index == u32::MAX, + ); + downlevel_flags.set( + wgt::DownlevelFlags::MULTISAMPLED_SHADING, + supported((3, 2), (4, 0)) || extensions.contains("OES_sample_variables"), + ); + let query_buffers = extensions.contains("GL_ARB_query_buffer_object") + || extensions.contains("GL_AMD_query_buffer_object"); + if query_buffers { + downlevel_flags.set(wgt::DownlevelFlags::NONBLOCKING_QUERY_RESOLVE, true); + } + + // Desktop GL: norm16 is core since GL 3.0/3.1; we minimum-version + // to GL 3.3, so always on. GLES/WebGL2: needs `EXT_texture_norm16`. + let supports_16bit_norm = if es_ver.is_some() { + extensions.contains("GL_EXT_texture_norm16") + || extensions.contains("EXT_texture_norm16") + } else { + true + }; + // SNORM color-rendering is not spec-guaranteed on either path + // (GLES Table 8.13 marks it not-renderable; desktop GL exposes + // it as only "optionally renderable"), so gate it on + // `EXT_render_snorm` for both - matching how `COLOR_BUFFER_FLOAT` + // is probed above. + let supports_16bit_snorm_renderable = supports_16bit_norm + && (extensions.contains("GL_EXT_render_snorm") + || extensions.contains("EXT_render_snorm")); + // Storage on norm16. ARB_shader_image_load_store / GL 4.2 Table X.2 and + // NV_image_formats Table 8.27 both list `r16/rg16/rgba16` and the SNORM + // variants as image-unit formats, so one gate covers UNORM and SNORM. + // Paths: + // * Desktop: core in GL 4.2+; on 3.3..=4.1 via `GL_ARB_shader_image_load_store`. + // * GLES/WebGL2: only via `GL_NV_image_formats` - the ES 3.1/3.2 core + // Table 8.27 omits these formats, and `GL_EXT_texture_norm16` does not + // extend Table 8.27 (NV_image_formats itself depends on EXT_texture_norm16 + // for the norm16 entries, so an ES driver exposing NV_image_formats + // without EXT_texture_norm16 still wouldn't accept them - the + // `supports_16bit_norm` prerequisite below catches that). + let supports_16bit_norm_storage = supports_16bit_norm + && if es_ver.is_some() { + extensions.contains("GL_NV_image_formats") + } else { + full_ver.is_some_and(|v| v >= (4, 2)) + || extensions.contains("GL_ARB_shader_image_load_store") + }; + + let mut features = wgt::Features::empty() + | wgt::Features::TEXTURE_ADAPTER_SPECIFIC_FORMAT_FEATURES + | wgt::Features::CLEAR_TEXTURE + | wgt::Features::IMMEDIATES + | wgt::Features::DEPTH32FLOAT_STENCIL8 + | wgt::Features::PASSTHROUGH_SHADERS; + features.set( + wgt::Features::TEXTURE_FORMAT_16BIT_NORM, + supports_16bit_norm, + ); + features.set( + wgt::Features::ADDRESS_MODE_CLAMP_TO_BORDER | wgt::Features::ADDRESS_MODE_CLAMP_TO_ZERO, + extensions.contains("GL_EXT_texture_border_clamp") + || extensions.contains("GL_ARB_texture_border_clamp"), + ); + features.set( + wgt::Features::DEPTH_CLIP_CONTROL, + extensions.contains("GL_EXT_depth_clamp") || extensions.contains("GL_ARB_depth_clamp"), + ); + features.set( + wgt::Features::VERTEX_WRITABLE_STORAGE, + downlevel_flags.contains(wgt::DownlevelFlags::VERTEX_STORAGE) + && vertex_shader_storage_textures != 0, + ); + features.set( + wgt::Features::MULTIVIEW, + extensions.contains("OVR_multiview2") || extensions.contains("GL_OVR_multiview2"), + ); + features.set( + wgt::Features::DUAL_SOURCE_BLENDING, + extensions.contains("GL_EXT_blend_func_extended") + || extensions.contains("GL_ARB_blend_func_extended"), + ); + features.set( + wgt::Features::CLIP_DISTANCES, + full_ver.is_some() || extensions.contains("GL_EXT_clip_cull_distance"), + ); + features.set( + wgt::Features::PRIMITIVE_INDEX, + supported((3, 2), (3, 2)) + || extensions.contains("OES_geometry_shader") + || extensions.contains("GL_ARB_geometry_shader4"), + ); + features.set( + wgt::Features::SHADER_EARLY_DEPTH_TEST, + supported((3, 1), (4, 2)) || extensions.contains("GL_ARB_shader_image_load_store"), + ); + if extensions.contains("GL_ARB_timer_query") { + features.set(wgt::Features::TIMESTAMP_QUERY, true); + features.set(wgt::Features::TIMESTAMP_QUERY_INSIDE_ENCODERS, true); + features.set(wgt::Features::TIMESTAMP_QUERY_INSIDE_PASSES, true); + } + let gl_bcn_exts = [ + "GL_EXT_texture_compression_s3tc", + "GL_EXT_texture_compression_rgtc", + "GL_ARB_texture_compression_bptc", + ]; + let gles_bcn_exts = [ + "GL_EXT_texture_compression_s3tc_srgb", + "GL_EXT_texture_compression_rgtc", + "GL_EXT_texture_compression_bptc", + ]; + let webgl_bcn_exts = [ + "WEBGL_compressed_texture_s3tc", + "WEBGL_compressed_texture_s3tc_srgb", + "EXT_texture_compression_rgtc", + "EXT_texture_compression_bptc", + ]; + let bcn_exts = if cfg!(any(webgl, Emscripten)) { + &webgl_bcn_exts[..] + } else if es_ver.is_some() { + &gles_bcn_exts[..] + } else { + &gl_bcn_exts[..] + }; + features.set( + wgt::Features::TEXTURE_COMPRESSION_BC, + bcn_exts.iter().all(|&ext| extensions.contains(ext)), + ); + features.set( + wgt::Features::TEXTURE_COMPRESSION_BC_SLICED_3D, + bcn_exts.iter().all(|&ext| extensions.contains(ext)), // BC guaranteed Sliced 3D + ); + let has_etc = if cfg!(any(webgl, Emscripten)) { + extensions.contains("WEBGL_compressed_texture_etc") + } else { + es_ver.is_some() || extensions.contains("GL_ARB_ES3_compatibility") + }; + features.set(wgt::Features::TEXTURE_COMPRESSION_ETC2, has_etc); + + // `OES_texture_compression_astc` provides 2D + 3D, LDR + HDR support + if extensions.contains("WEBGL_compressed_texture_astc") + || extensions.contains("GL_OES_texture_compression_astc") + { + #[cfg(webgl)] + { + if context + .glow_context + .compressed_texture_astc_supports_ldr_profile() + { + features.insert(wgt::Features::TEXTURE_COMPRESSION_ASTC); + features.insert(wgt::Features::TEXTURE_COMPRESSION_ASTC_SLICED_3D); + } + if context + .glow_context + .compressed_texture_astc_supports_hdr_profile() + { + features.insert(wgt::Features::TEXTURE_COMPRESSION_ASTC_HDR); + } + } + + #[cfg(any(native, Emscripten))] + { + features.insert(wgt::Features::TEXTURE_COMPRESSION_ASTC); + features.insert(wgt::Features::TEXTURE_COMPRESSION_ASTC_SLICED_3D); + features.insert(wgt::Features::TEXTURE_COMPRESSION_ASTC_HDR); + } + } else { + features.set( + wgt::Features::TEXTURE_COMPRESSION_ASTC, + extensions.contains("GL_KHR_texture_compression_astc_ldr"), + ); + features.set( + wgt::Features::TEXTURE_COMPRESSION_ASTC_SLICED_3D, + extensions.contains("GL_KHR_texture_compression_astc_ldr") + && extensions.contains("GL_KHR_texture_compression_astc_sliced_3d"), + ); + features.set( + wgt::Features::TEXTURE_COMPRESSION_ASTC_HDR, + extensions.contains("GL_KHR_texture_compression_astc_hdr"), + ); + } + + downlevel_flags.set( + wgt::DownlevelFlags::TEXTURE_COMPRESSION, + features.contains(wgt::Features::TEXTURE_COMPRESSION_BC) + || features.contains( + wgt::Features::TEXTURE_COMPRESSION_ETC2 + | wgt::Features::TEXTURE_COMPRESSION_ASTC, + ), + ); + + features.set( + wgt::Features::FLOAT32_FILTERABLE, + extensions.contains("GL_ARB_color_buffer_float") + || extensions.contains("GL_EXT_color_buffer_float") + || extensions.contains("OES_texture_float_linear"), + ); + + if es_ver.is_none() { + features |= wgt::Features::POLYGON_MODE_LINE | wgt::Features::POLYGON_MODE_POINT; + } + + // We *might* be able to emulate bgra8unorm-storage but currently don't attempt to. + + let mut private_caps = super::PrivateCapabilities::empty(); + private_caps.set( + super::PrivateCapabilities::BUFFER_ALLOCATION, + extensions.contains("GL_EXT_buffer_storage") + || extensions.contains("GL_ARB_buffer_storage"), + ); + private_caps.set( + super::PrivateCapabilities::SHADER_BINDING_LAYOUT, + supports_compute, + ); + private_caps.set( + super::PrivateCapabilities::SHADER_TEXTURE_SHADOW_LOD, + extensions.contains("GL_EXT_texture_shadow_lod"), + ); + private_caps.set( + super::PrivateCapabilities::MEMORY_BARRIERS, + supported((3, 1), (4, 2)), + ); + private_caps.set( + super::PrivateCapabilities::VERTEX_BUFFER_LAYOUT, + supported((3, 1), (4, 3)) || extensions.contains("GL_ARB_vertex_attrib_binding"), + ); + private_caps.set( + super::PrivateCapabilities::INDEX_BUFFER_ROLE_CHANGE, + !cfg!(any(webgl, Emscripten)), + ); + private_caps.set( + super::PrivateCapabilities::GET_BUFFER_SUB_DATA, + cfg!(any(webgl, Emscripten)) || full_ver.is_some(), + ); + let color_buffer_float = extensions.contains("GL_EXT_color_buffer_float") + || extensions.contains("GL_ARB_color_buffer_float") + || extensions.contains("EXT_color_buffer_float"); + let color_buffer_half_float = extensions.contains("GL_EXT_color_buffer_half_float") + || extensions.contains("GL_ARB_half_float_pixel"); + private_caps.set( + super::PrivateCapabilities::COLOR_BUFFER_HALF_FLOAT, + color_buffer_half_float || color_buffer_float, + ); + private_caps.set( + super::PrivateCapabilities::COLOR_BUFFER_FLOAT, + color_buffer_float, + ); + private_caps.set(super::PrivateCapabilities::QUERY_BUFFERS, query_buffers); + private_caps.set(super::PrivateCapabilities::QUERY_64BIT, full_ver.is_some()); + private_caps.set( + super::PrivateCapabilities::TEXTURE_STORAGE, + supported((3, 0), (4, 2)), + ); + let is_mali = renderer.to_lowercase().contains("mali"); + let debug_fns_enabled = match backend_options.debug_fns { + wgt::GlDebugFns::Auto => gl.supports_debug() && !is_mali, + wgt::GlDebugFns::ForceEnabled => gl.supports_debug(), + wgt::GlDebugFns::Disabled => false, + }; + private_caps.set(super::PrivateCapabilities::DEBUG_FNS, debug_fns_enabled); + private_caps.set( + super::PrivateCapabilities::INVALIDATE_FRAMEBUFFER, + supported((3, 0), (4, 3)), + ); + if let Some(full_ver) = full_ver { + let supported = + full_ver >= (4, 2) && extensions.contains("GL_ARB_shader_draw_parameters"); + private_caps.set( + super::PrivateCapabilities::FULLY_FEATURED_INSTANCING, + supported, + ); + // Desktop 4.2 and greater specify the first instance parameter. + // + // For all other versions, the behavior is undefined. + // + // We only support indirect first instance when we also have ARB_shader_draw_parameters as + // that's the only way to get gl_InstanceID to work correctly. + features.set(wgt::Features::INDIRECT_FIRST_INSTANCE, supported); + } + private_caps.set( + super::PrivateCapabilities::MULTISAMPLED_RENDER_TO_TEXTURE, + extensions.contains("GL_EXT_multisampled_render_to_texture"), + ); + private_caps.set( + super::PrivateCapabilities::TEXTURE_FORMAT_NORM16, + supports_16bit_norm, + ); + private_caps.set( + super::PrivateCapabilities::TEXTURE_FORMAT_SNORM16_RENDERABLE, + supports_16bit_snorm_renderable, + ); + private_caps.set( + super::PrivateCapabilities::TEXTURE_FORMAT_NORM16_STORAGE, + supports_16bit_norm_storage, + ); + + // GLSL ES 3.10+ / GLSL 4.30+ natively support coherent/volatile qualifiers + // on storage buffers. These were introduced alongside storage buffer support. + if supports_storage { + features |= wgt::Features::MEMORY_DECORATION_COHERENT + | wgt::Features::MEMORY_DECORATION_VOLATILE; + } + + let max_texture_size = unsafe { gl.get_parameter_i32(glow::MAX_TEXTURE_SIZE) } as u32; + let max_texture_3d_size = unsafe { gl.get_parameter_i32(glow::MAX_3D_TEXTURE_SIZE) } as u32; + + let min_uniform_buffer_offset_alignment = + (unsafe { gl.get_parameter_i32(glow::UNIFORM_BUFFER_OFFSET_ALIGNMENT) } as u32); + let min_storage_buffer_offset_alignment = if supports_storage { + (unsafe { gl.get_parameter_i32(glow::SHADER_STORAGE_BUFFER_OFFSET_ALIGNMENT) } as u32) + } else { + 256 + }; + let max_uniform_buffers_per_shader_stage = + unsafe { gl.get_parameter_i32(glow::MAX_VERTEX_UNIFORM_BLOCKS) } + .min(unsafe { gl.get_parameter_i32(glow::MAX_FRAGMENT_UNIFORM_BLOCKS) }) + as u32; + + let max_compute_workgroups_per_dimension = if supports_work_group_params { + unsafe { gl.get_parameter_indexed_i32(glow::MAX_COMPUTE_WORK_GROUP_COUNT, 0) } + .min(unsafe { gl.get_parameter_indexed_i32(glow::MAX_COMPUTE_WORK_GROUP_COUNT, 1) }) + .min(unsafe { gl.get_parameter_indexed_i32(glow::MAX_COMPUTE_WORK_GROUP_COUNT, 2) }) + as u32 + } else { + 0 + }; + + let max_color_attachments = unsafe { + gl.get_parameter_i32(glow::MAX_COLOR_ATTACHMENTS) + .min(gl.get_parameter_i32(glow::MAX_DRAW_BUFFERS)) as u32 + }; + + // 16 bytes per sample is the maximum size of a color attachment. + let max_color_attachment_bytes_per_sample = + max_color_attachments * wgt::TextureFormat::MAX_TARGET_PIXEL_BYTE_COST; + + let limits = crate::auxil::adjust_raw_limits(wgt::Limits { + max_texture_dimension_1d: max_texture_size, + max_texture_dimension_2d: max_texture_size, + max_texture_dimension_3d: max_texture_3d_size, + max_texture_array_layers: unsafe { + gl.get_parameter_i32(glow::MAX_ARRAY_TEXTURE_LAYERS) + } as u32, + max_bind_groups: u32::MAX, + // No limit. + max_bind_groups_plus_vertex_buffers: u32::MAX, + // No limit. + max_bindings_per_bind_group: u32::MAX, + max_dynamic_uniform_buffers_per_pipeline_layout: max_uniform_buffers_per_shader_stage, + max_dynamic_storage_buffers_per_pipeline_layout: max_storage_buffers_per_shader_stage, + max_sampled_textures_per_shader_stage: super::MAX_TEXTURE_SLOTS as u32, + max_samplers_per_shader_stage: super::MAX_SAMPLERS as u32, + max_storage_buffers_per_shader_stage, + max_storage_textures_per_shader_stage, + max_uniform_buffers_per_shader_stage, + max_binding_array_elements_per_shader_stage: 0, + max_binding_array_sampler_elements_per_shader_stage: 0, + max_binding_array_acceleration_structure_elements_per_shader_stage: 0, + max_uniform_buffer_binding_size: unsafe { + gl.get_parameter_i32(glow::MAX_UNIFORM_BLOCK_SIZE) + } as u64, + max_storage_buffer_binding_size: if supports_storage { + unsafe { gl.get_parameter_i32(glow::MAX_SHADER_STORAGE_BLOCK_SIZE) } + } else { + 0 + } as u64, + max_vertex_buffers: if private_caps + .contains(super::PrivateCapabilities::VERTEX_BUFFER_LAYOUT) + { + (unsafe { gl.get_parameter_i32(glow::MAX_VERTEX_ATTRIB_BINDINGS) } as u32) + } else { + 16 // should this be different? + }, + max_vertex_attributes: (unsafe { gl.get_parameter_i32(glow::MAX_VERTEX_ATTRIBS) } + as u32) + .min(super::MAX_VERTEX_ATTRIBUTES as u32), + max_vertex_buffer_array_stride: if private_caps + .contains(super::PrivateCapabilities::VERTEX_BUFFER_LAYOUT) + { + if let Some(full_ver) = full_ver { + if full_ver >= (4, 4) { + // We can query `GL_MAX_VERTEX_ATTRIB_STRIDE` in OpenGL 4.4+ + let value = + (unsafe { gl.get_parameter_i32(glow::MAX_VERTEX_ATTRIB_STRIDE) }) + as u32; + + if value == 0 { + // This should be at least 2048, but the driver for AMD Radeon HD 5870 on + // Windows doesn't recognize `GL_MAX_VERTEX_ATTRIB_STRIDE`. + + log::debug!("Max vertex attribute stride is 0. Assuming it is the OpenGL minimum spec 2048"); + 2048 + } else { + value + } + } else { + log::debug!("Max vertex attribute stride unknown. Assuming it is the OpenGL minimum spec 2048"); + 2048 + } + } else { + (unsafe { gl.get_parameter_i32(glow::MAX_VERTEX_ATTRIB_STRIDE) }) as u32 + } + } else { + !0 + }, + max_immediate_size: super::MAX_IMMEDIATES as u32 * 4, + min_uniform_buffer_offset_alignment, + min_storage_buffer_offset_alignment, + max_inter_stage_shader_variables: { + // MAX_VARYING_COMPONENTS may return 0, because it is deprecated since OpenGL 3.2 core, + // and an OpenGL Context with the core profile and with forward-compatibility=true, + // will make deprecated constants unavailable. + let max_varying_components = + unsafe { gl.get_parameter_i32(glow::MAX_VARYING_COMPONENTS) } as u32; + if max_varying_components == 0 { + // default value for max_inter_stage_shader_variables + 15 + } else { + max_varying_components / 4 + } + }, + max_color_attachments, + max_color_attachment_bytes_per_sample, + max_compute_workgroup_storage_size: if supports_work_group_params { + (unsafe { gl.get_parameter_i32(glow::MAX_COMPUTE_SHARED_MEMORY_SIZE) } as u32) + } else { + 0 + }, + max_compute_invocations_per_workgroup: if supports_work_group_params { + (unsafe { gl.get_parameter_i32(glow::MAX_COMPUTE_WORK_GROUP_INVOCATIONS) } as u32) + } else { + 0 + }, + max_compute_workgroup_size_x: if supports_work_group_params { + (unsafe { gl.get_parameter_indexed_i32(glow::MAX_COMPUTE_WORK_GROUP_SIZE, 0) } + as u32) + } else { + 0 + }, + max_compute_workgroup_size_y: if supports_work_group_params { + (unsafe { gl.get_parameter_indexed_i32(glow::MAX_COMPUTE_WORK_GROUP_SIZE, 1) } + as u32) + } else { + 0 + }, + max_compute_workgroup_size_z: if supports_work_group_params { + (unsafe { gl.get_parameter_indexed_i32(glow::MAX_COMPUTE_WORK_GROUP_SIZE, 2) } + as u32) + } else { + 0 + }, + max_compute_workgroups_per_dimension, + max_buffer_size: i32::MAX as u64, + max_non_sampler_bindings: u32::MAX, + + max_task_workgroup_total_count: 0, + max_task_workgroups_per_dimension: 0, + max_mesh_workgroup_total_count: 0, + max_mesh_workgroups_per_dimension: 0, + max_task_invocations_per_workgroup: 0, + max_task_invocations_per_dimension: 0, + max_mesh_invocations_per_workgroup: 0, + max_mesh_invocations_per_dimension: 0, + max_task_payload_size: 0, + max_mesh_output_vertices: 0, + max_mesh_output_primitives: 0, + max_mesh_output_layers: 0, + max_mesh_multiview_view_count: 0, + + max_blas_primitive_count: 0, + max_blas_geometry_count: 0, + max_tlas_instance_count: 0, + max_acceleration_structures_per_shader_stage: 0, + max_buffers_and_acceleration_structures_per_shader_stage: u32::MAX, + + max_multiview_view_count: 0, + + max_ray_dispatch_count: 0, + max_ray_recursion_depth: 0, + }); + + let mut workarounds = super::Workarounds::empty(); + + workarounds.set( + super::Workarounds::EMULATE_BUFFER_MAP, + cfg!(any(webgl, Emscripten)), + ); + + let r = renderer.to_lowercase(); + // Check for Mesa sRGB clear bug. See + // [`super::PrivateCapabilities::MESA_I915_SRGB_SHADER_CLEAR`]. + if context.is_owned() + && r.contains("mesa") + && r.contains("intel") + && r.split(&[' ', '(', ')'][..]) + .any(|substr| substr.len() == 3 && substr.chars().nth(2) == Some('l')) + { + log::debug!( + "Detected skylake derivative running on mesa i915. Clears to srgb textures will \ + use manual shader clears." + ); + workarounds.set(super::Workarounds::MESA_I915_SRGB_SHADER_CLEAR, true); + } + + let downlevel_defaults = wgt::DownlevelLimits {}; + let max_samples = unsafe { gl.get_parameter_i32(glow::MAX_SAMPLES) }; + + // Drop the GL guard so we can move the context into AdapterShared + // ( on Wasm the gl handle is just a ref so we tell clippy to allow + // dropping the ref ) + #[cfg_attr(target_arch = "wasm32", allow(dropping_references))] + drop(gl); + + Some(crate::ExposedAdapter { + adapter: super::Adapter { + shared: Arc::new(super::AdapterShared { + context, + private_caps, + workarounds, + features, + limits: limits.clone(), + options: backend_options, + shading_language_version, + next_shader_id: Default::default(), + program_cache: Default::default(), + es: es_ver.is_some(), + max_msaa_samples: max_samples, + }), + }, + info: Self::make_info(vendor, renderer, version), + features, + capabilities: crate::Capabilities { + limits, + downlevel: wgt::DownlevelCapabilities { + flags: downlevel_flags, + limits: downlevel_defaults, + shader_model: wgt::ShaderModel::Sm5, + }, + alignments: crate::Alignments { + buffer_copy_offset: wgt::BufferSize::new(4).unwrap(), + buffer_copy_pitch: wgt::BufferSize::new(4).unwrap(), + // #6151: `wgpu_hal::gles` doesn't ask Naga to inject bounds + // checks in GLSL, and it doesn't request extensions like + // `KHR_robust_buffer_access_behavior` that would provide + // them, so we can't really implement the checks promised by + // [`crate::BufferBinding`]. + // + // Since this is a pre-existing condition, for the time + // being, provide 1 as the value here, to cause as little + // trouble as possible. + uniform_bounds_check_alignment: wgt::BufferSize::new(1).unwrap(), + raw_tlas_instance_size: 0, + ray_tracing_scratch_buffer_alignment: 0, + ray_tracing_pipeline_group_data_size: 0, + ray_tracing_pipeline_group_data_alignment: 0, + ray_tracing_pipeline_data_offset_alignment: 0, + }, + cooperative_matrix_properties: Vec::new(), + }, + }) + } + + unsafe fn compile_shader( + source: &str, + gl: &glow::Context, + shader_type: u32, + es: bool, + ) -> Option<glow::Shader> { + let source = if es { + format!("#version 300 es\nprecision lowp float;\n{source}") + } else { + let version = gl.version(); + if version.major == 3 && version.minor == 0 { + // OpenGL 3.0 only supports this format + format!("#version 130\n{source}") + } else { + // OpenGL 3.1+ support this format + format!("#version 140\n{source}") + } + }; + let shader = unsafe { gl.create_shader(shader_type) }.expect("Could not create shader"); + unsafe { gl.shader_source(shader, &source) }; + unsafe { gl.compile_shader(shader) }; + + if !unsafe { gl.get_shader_compile_status(shader) } { + let msg = unsafe { gl.get_shader_info_log(shader) }; + if !msg.is_empty() { + log::error!("\tShader compile error: {msg}"); + } + unsafe { gl.delete_shader(shader) }; + None + } else { + Some(shader) + } + } + + unsafe fn create_shader_clear_program( + gl: &glow::Context, + es: bool, + ) -> Option<ShaderClearProgram> { + let program = unsafe { gl.create_program() }.expect("Could not create shader program"); + let vertex = unsafe { + Self::compile_shader( + include_str!("./shaders/clear.vert"), + gl, + glow::VERTEX_SHADER, + es, + )? + }; + let fragment = unsafe { + Self::compile_shader( + include_str!("./shaders/clear.frag"), + gl, + glow::FRAGMENT_SHADER, + es, + )? + }; + unsafe { gl.attach_shader(program, vertex) }; + unsafe { gl.attach_shader(program, fragment) }; + unsafe { gl.link_program(program) }; + + let linked_ok = unsafe { gl.get_program_link_status(program) }; + let msg = unsafe { gl.get_program_info_log(program) }; + if !msg.is_empty() { + log::error!("Shader link error: {msg}"); + } + if !linked_ok { + return None; + } + + let color_uniform_location = unsafe { gl.get_uniform_location(program, "color") } + .expect("Could not find color uniform in shader clear shader"); + unsafe { gl.delete_shader(vertex) }; + unsafe { gl.delete_shader(fragment) }; + + Some(ShaderClearProgram { + program, + color_uniform_location, + }) + } +} + +impl crate::Adapter for super::Adapter { + type A = super::Api; + + unsafe fn open( + &self, + features: wgt::Features, + _limits: &wgt::Limits, + _memory_hints: &wgt::MemoryHints, + ) -> Result<crate::OpenDevice<super::Api>, crate::DeviceError> { + let gl = &self.shared.context.lock(); + unsafe { gl.pixel_store_i32(glow::UNPACK_ALIGNMENT, 1) }; + unsafe { gl.pixel_store_i32(glow::PACK_ALIGNMENT, 1) }; + let main_vao = + unsafe { gl.create_vertex_array() }.map_err(|_| crate::DeviceError::OutOfMemory)?; + unsafe { gl.bind_vertex_array(Some(main_vao)) }; + + let zero_buffer = + unsafe { gl.create_buffer() }.map_err(|_| crate::DeviceError::OutOfMemory)?; + unsafe { gl.bind_buffer(glow::COPY_READ_BUFFER, Some(zero_buffer)) }; + let zeroes = vec![0u8; super::ZERO_BUFFER_SIZE]; + unsafe { gl.buffer_data_u8_slice(glow::COPY_READ_BUFFER, &zeroes, glow::STATIC_DRAW) }; + + // Compile the shader program we use for doing manual clears to work around Mesa fastclear + // bug. + + let shader_clear_program = if self + .shared + .workarounds + .contains(super::Workarounds::MESA_I915_SRGB_SHADER_CLEAR) + { + Some(unsafe { + Self::create_shader_clear_program(gl, self.shared.es) + .ok_or(crate::DeviceError::Lost)? + }) + } else { + // If we don't need the workaround, don't waste time and resources compiling the clear program + None + }; + + Ok(crate::OpenDevice { + device: super::Device { + shared: Arc::clone(&self.shared), + main_vao, + #[cfg(all(native, feature = "renderdoc"))] + render_doc: Default::default(), + counters: Default::default(), + }, + queue: super::Queue { + shared: Arc::clone(&self.shared), + features, + draw_fbo: unsafe { gl.create_framebuffer() } + .map_err(|_| crate::DeviceError::OutOfMemory)?, + copy_fbo: unsafe { gl.create_framebuffer() } + .map_err(|_| crate::DeviceError::OutOfMemory)?, + shader_clear_program, + zero_buffer, + temp_query_results: Mutex::new(Vec::new()), + draw_buffer_count: AtomicU8::new(1), + current_index_buffer: Mutex::new(None), + }, + }) + } + + unsafe fn texture_format_capabilities( + &self, + format: wgt::TextureFormat, + ) -> crate::TextureFormatCapabilities { + use crate::TextureFormatCapabilities as Tfc; + use wgt::TextureFormat as Tf; + + let sample_count = { + let max_samples = self.shared.max_msaa_samples; + if max_samples >= 16 { + Tfc::MULTISAMPLE_X2 + | Tfc::MULTISAMPLE_X4 + | Tfc::MULTISAMPLE_X8 + | Tfc::MULTISAMPLE_X16 + } else if max_samples >= 8 { + Tfc::MULTISAMPLE_X2 | Tfc::MULTISAMPLE_X4 | Tfc::MULTISAMPLE_X8 + } else { + // The lowest supported level in GLE3.0/WebGL2 is 4X + // (see GL_MAX_SAMPLES in https://registry.khronos.org/OpenGL-Refpages/es3.0/html/glGet.xhtml). + // On some platforms, like iOS Safari, `get_parameter_i32(MAX_SAMPLES)` returns 0, + // so we always fall back to supporting 4x here. + Tfc::MULTISAMPLE_X2 | Tfc::MULTISAMPLE_X4 + } + }; + + // Base types are pulled from the table in the OpenGLES 3.0 spec in section 3.8. + // + // The storage types are based on table 8.26, in section + // "TEXTURE IMAGE LOADS AND STORES" of OpenGLES-3.2 spec. + let empty = Tfc::empty(); + let base = Tfc::COPY_SRC | Tfc::COPY_DST; + let unfilterable = base | Tfc::SAMPLED; + let depth = base | Tfc::SAMPLED | sample_count | Tfc::DEPTH_STENCIL_ATTACHMENT; + let filterable = unfilterable | Tfc::SAMPLED_LINEAR; + let renderable = + unfilterable | Tfc::COLOR_ATTACHMENT | sample_count | Tfc::MULTISAMPLE_RESOLVE; + let filterable_renderable = filterable | renderable | Tfc::COLOR_ATTACHMENT_BLEND; + let storage = + base | Tfc::STORAGE_READ_WRITE | Tfc::STORAGE_READ_ONLY | Tfc::STORAGE_WRITE_ONLY; + + let feature_fn = |f, caps| { + if self.shared.features.contains(f) { + caps + } else { + empty + } + }; + + let bcn_features = feature_fn(wgt::Features::TEXTURE_COMPRESSION_BC, filterable); + let etc2_features = feature_fn(wgt::Features::TEXTURE_COMPRESSION_ETC2, filterable); + let astc_features = feature_fn(wgt::Features::TEXTURE_COMPRESSION_ASTC, filterable); + let astc_hdr_features = feature_fn(wgt::Features::TEXTURE_COMPRESSION_ASTC_HDR, filterable); + + let private_caps_fn = |f, caps| { + if self.shared.private_caps.contains(f) { + caps + } else { + empty + } + }; + + let half_float_renderable = private_caps_fn( + super::PrivateCapabilities::COLOR_BUFFER_HALF_FLOAT, + Tfc::COLOR_ATTACHMENT + | Tfc::COLOR_ATTACHMENT_BLEND + | sample_count + | Tfc::MULTISAMPLE_RESOLVE, + ); + + let float_renderable = private_caps_fn( + super::PrivateCapabilities::COLOR_BUFFER_FLOAT, + Tfc::COLOR_ATTACHMENT + | Tfc::COLOR_ATTACHMENT_BLEND + | sample_count + | Tfc::MULTISAMPLE_RESOLVE, + ); + + let texture_float_linear = feature_fn(wgt::Features::FLOAT32_FILTERABLE, filterable); + + let image_atomic = feature_fn(wgt::Features::TEXTURE_ATOMIC, Tfc::STORAGE_ATOMIC); + let image_64_atomic = feature_fn(wgt::Features::TEXTURE_INT64_ATOMIC, Tfc::STORAGE_ATOMIC); + + // UNORM gets full filterable+renderable; SNORM splits because + // `EXT_texture_norm16` marks only UNORM as color-renderable. + // Storage rides on a separate cap (desktop GL >= 4.2 core / pre-4.2 + // `GL_ARB_shader_image_load_store`, GLES `GL_NV_image_formats`). + let norm16_unorm = private_caps_fn( + super::PrivateCapabilities::TEXTURE_FORMAT_NORM16, + filterable_renderable, + ); + let norm16_snorm = if self + .shared + .private_caps + .contains(super::PrivateCapabilities::TEXTURE_FORMAT_SNORM16_RENDERABLE) + { + norm16_unorm + } else { + private_caps_fn( + super::PrivateCapabilities::TEXTURE_FORMAT_NORM16, + filterable, + ) + }; + let norm16_storage = private_caps_fn( + super::PrivateCapabilities::TEXTURE_FORMAT_NORM16_STORAGE, + storage, + ); + + match format { + Tf::R8Unorm => filterable_renderable, + Tf::R8Snorm => filterable, + Tf::R8Uint => renderable, + Tf::R8Sint => renderable, + Tf::R16Uint => renderable, + Tf::R16Sint => renderable, + Tf::R16Unorm => norm16_unorm | norm16_storage, + Tf::R16Snorm => norm16_snorm | norm16_storage, + Tf::R16Float => filterable | half_float_renderable, + Tf::Rg8Unorm => filterable_renderable, + Tf::Rg8Snorm => filterable, + Tf::Rg8Uint => renderable, + Tf::Rg8Sint => renderable, + Tf::R32Uint => renderable | storage | image_atomic, + Tf::R32Sint => renderable | storage | image_atomic, + Tf::R32Float => unfilterable | storage | float_renderable | texture_float_linear, + Tf::Rg16Uint => renderable, + Tf::Rg16Sint => renderable, + Tf::Rg16Unorm => norm16_unorm | norm16_storage, + Tf::Rg16Snorm => norm16_snorm | norm16_storage, + Tf::Rg16Float => filterable | half_float_renderable, + Tf::Rgba8Unorm => filterable_renderable | storage, + Tf::Rgba8UnormSrgb => filterable_renderable, + Tf::Bgra8Unorm | Tf::Bgra8UnormSrgb => filterable_renderable, + Tf::Rgba8Snorm => filterable | storage, + Tf::Rgba8Uint => renderable | storage, + Tf::Rgba8Sint => renderable | storage, + Tf::Rgb10a2Uint => renderable, + Tf::Rgb10a2Unorm => filterable_renderable, + Tf::Rg11b10Ufloat => filterable | float_renderable, + Tf::R64Uint => image_64_atomic, + Tf::Rg32Uint => renderable, + Tf::Rg32Sint => renderable, + Tf::Rg32Float => unfilterable | float_renderable | texture_float_linear, + Tf::Rgba16Uint => renderable | storage, + Tf::Rgba16Sint => renderable | storage, + Tf::Rgba16Unorm => norm16_unorm | norm16_storage, + Tf::Rgba16Snorm => norm16_snorm | norm16_storage, + Tf::Rgba16Float => filterable | storage | half_float_renderable, + Tf::Rgba32Uint => renderable | storage, + Tf::Rgba32Sint => renderable | storage, + Tf::Rgba32Float => unfilterable | storage | float_renderable | texture_float_linear, + Tf::Stencil8 + | Tf::Depth16Unorm + | Tf::Depth32Float + | Tf::Depth32FloatStencil8 + | Tf::Depth24Plus + | Tf::Depth24PlusStencil8 => depth, + Tf::NV12 => empty, + Tf::P010 => empty, + Tf::Rgb9e5Ufloat => filterable, + Tf::Bc1RgbaUnorm + | Tf::Bc1RgbaUnormSrgb + | Tf::Bc2RgbaUnorm + | Tf::Bc2RgbaUnormSrgb + | Tf::Bc3RgbaUnorm + | Tf::Bc3RgbaUnormSrgb + | Tf::Bc4RUnorm + | Tf::Bc4RSnorm + | Tf::Bc5RgUnorm + | Tf::Bc5RgSnorm + | Tf::Bc6hRgbFloat + | Tf::Bc6hRgbUfloat + | Tf::Bc7RgbaUnorm + | Tf::Bc7RgbaUnormSrgb => bcn_features, + Tf::Etc2Rgb8Unorm + | Tf::Etc2Rgb8UnormSrgb + | Tf::Etc2Rgb8A1Unorm + | Tf::Etc2Rgb8A1UnormSrgb + | Tf::Etc2Rgba8Unorm + | Tf::Etc2Rgba8UnormSrgb + | Tf::EacR11Unorm + | Tf::EacR11Snorm + | Tf::EacRg11Unorm + | Tf::EacRg11Snorm => etc2_features, + Tf::Astc { + block: _, + channel: AstcChannel::Unorm | AstcChannel::UnormSrgb, + } => astc_features, + Tf::Astc { + block: _, + channel: AstcChannel::Hdr, + } => astc_hdr_features, + } + } + + unsafe fn surface_capabilities( + &self, + surface: &super::Surface, + ) -> Option<crate::SurfaceCapabilities> { + #[cfg(webgl)] + if self.shared.context.webgl2_context != surface.webgl2_context { + return None; + } + + if surface.presentable { + // There is no extended-range or wide-gamut path in the GLES + // backend; everything is presented as sRGB. + let format_caps = |format: wgt::TextureFormat| wgt::SurfaceFormatCapabilities { + format, + color_spaces: wgt::SurfaceColorSpaces::SRGB, + }; + let mut formats = vec![ + format_caps(wgt::TextureFormat::Rgba8Unorm), + #[cfg(native)] + format_caps(wgt::TextureFormat::Bgra8Unorm), + ]; + if surface.supports_srgb() { + formats.extend([ + format_caps(wgt::TextureFormat::Rgba8UnormSrgb), + #[cfg(native)] + format_caps(wgt::TextureFormat::Bgra8UnormSrgb), + ]) + } + if self + .shared + .private_caps + .contains(super::PrivateCapabilities::COLOR_BUFFER_HALF_FLOAT) + { + formats.push(format_caps(wgt::TextureFormat::Rgba16Float)) + } + + Some(crate::SurfaceCapabilities { + formats, + present_modes: if cfg!(windows) { + vec![wgt::PresentMode::Fifo, wgt::PresentMode::Immediate] + } else { + vec![wgt::PresentMode::Fifo] //TODO + }, + composite_alpha_modes: vec![wgt::CompositeAlphaMode::Opaque], //TODO + maximum_frame_latency: 2..=2, //TODO, unused currently + current_extent: None, + usage: wgt::TextureUses::COLOR_TARGET, + }) + } else { + None + } + } + + unsafe fn get_presentation_timestamp(&self) -> wgt::PresentationTimestamp { + wgt::PresentationTimestamp::INVALID_TIMESTAMP + } + + fn get_ordered_buffer_usages(&self) -> wgt::BufferUses { + wgt::BufferUses::INCLUSIVE | wgt::BufferUses::MAP_WRITE + } + + // Don't put barriers between inclusive uses + fn get_ordered_texture_usages(&self) -> wgt::TextureUses { + wgt::TextureUses::INCLUSIVE + | wgt::TextureUses::COLOR_TARGET + | wgt::TextureUses::DEPTH_STENCIL_WRITE + } +} + +impl super::AdapterShared { + pub(super) unsafe fn get_buffer_sub_data( + &self, + gl: &glow::Context, + target: u32, + offset: i32, + dst_data: &mut [u8], + ) { + if self + .private_caps + .contains(super::PrivateCapabilities::GET_BUFFER_SUB_DATA) + { + unsafe { gl.get_buffer_sub_data(target, offset, dst_data) }; + } else { + log::error!("Fake map"); + let length = dst_data.len(); + // glMapBufferRange throws an error if length is 0. + if length != 0 { + let buffer_mapping = + unsafe { gl.map_buffer_range(target, offset, length as _, glow::MAP_READ_BIT) }; + + unsafe { + core::ptr::copy_nonoverlapping(buffer_mapping, dst_data.as_mut_ptr(), length) + }; + + unsafe { gl.unmap_buffer(target) }; + } + } + } +} + +#[cfg(send_sync)] +unsafe impl Sync for super::Adapter {} +#[cfg(send_sync)] +unsafe impl Send for super::Adapter {} + +#[cfg(test)] +mod tests { + use super::super::Adapter; + + #[test] + fn test_version_parse() { + Adapter::parse_version("1").unwrap_err(); + Adapter::parse_version("1.").unwrap_err(); + Adapter::parse_version("1 h3l1o. W0rld").unwrap_err(); + Adapter::parse_version("1. h3l1o. W0rld").unwrap_err(); + Adapter::parse_version("1.2.3").unwrap_err(); + + assert_eq!(Adapter::parse_version("OpenGL ES 3.1").unwrap(), (3, 1)); + assert_eq!( + Adapter::parse_version("OpenGL ES 2.0 Google Nexus").unwrap(), + (2, 0) + ); + assert_eq!(Adapter::parse_version("GLSL ES 1.1").unwrap(), (1, 1)); + assert_eq!( + Adapter::parse_version("OpenGL ES GLSL ES 3.20").unwrap(), + (3, 2) + ); + assert_eq!( + // WebGL 2.0 should parse as OpenGL ES 3.0 + Adapter::parse_version("WebGL 2.0 (OpenGL ES 3.0 Chromium)").unwrap(), + (3, 0) + ); + assert_eq!( + Adapter::parse_version("WebGL GLSL ES 3.00 (OpenGL ES GLSL ES 3.0 Chromium)").unwrap(), + (3, 0) + ); + } +} diff --git a/app/vendor/rune/vendor/wgpu-hal/src/gles/command.rs b/app/vendor/rune/vendor/wgpu-hal/src/gles/command.rs new file mode 100644 index 0000000..427551c --- /dev/null +++ b/app/vendor/rune/vendor/wgpu-hal/src/gles/command.rs @@ -0,0 +1,1345 @@ +use alloc::string::String; +use core::{mem, ops::Range}; + +use arrayvec::ArrayVec; + +use super::{conv, Command as C}; + +#[derive(Clone, Copy, Debug, Default)] +struct TextureSlotDesc { + tex_target: super::BindTarget, + sampler_index: Option<u8>, +} + +pub(super) struct State { + topology: u32, + primitive: super::PrimitiveState, + index_format: wgt::IndexFormat, + index_offset: wgt::BufferAddress, + vertex_buffers: [( + Option<super::VertexBufferDesc>, + Option<super::BufferBinding>, + ); crate::MAX_VERTEX_BUFFERS], + vertex_attributes: ArrayVec<super::AttributeDesc, { super::MAX_VERTEX_ATTRIBUTES }>, + color_targets: ArrayVec<super::ColorTargetDesc, { crate::MAX_COLOR_ATTACHMENTS }>, + stencil: super::StencilState, + depth_bias: wgt::DepthBiasState, + alpha_to_coverage_enabled: bool, + samplers: [Option<glow::Sampler>; super::MAX_SAMPLERS], + texture_slots: [TextureSlotDesc; super::MAX_TEXTURE_SLOTS], + render_size: wgt::Extent3d, + resolve_attachments: ArrayVec<(u32, super::TextureView), { crate::MAX_COLOR_ATTACHMENTS }>, + invalidate_attachments: ArrayVec<u32, { crate::MAX_COLOR_ATTACHMENTS + 2 }>, + has_pass_label: bool, + instance_vbuf_mask: usize, + dirty_vbuf_mask: usize, + active_first_instance: u32, + first_instance_location: Option<glow::UniformLocation>, + immediates_descs: ArrayVec<super::ImmediateDesc, { super::MAX_IMMEDIATES_COMMANDS }>, + // The current state of the immediate data block. + current_immediates_data: [u32; super::MAX_IMMEDIATES], + end_of_pass_timestamp: Option<glow::Query>, + clip_distance_count: u32, +} + +impl Default for State { + fn default() -> Self { + Self { + topology: Default::default(), + primitive: Default::default(), + index_format: Default::default(), + index_offset: Default::default(), + vertex_buffers: Default::default(), + vertex_attributes: Default::default(), + color_targets: Default::default(), + stencil: Default::default(), + depth_bias: Default::default(), + alpha_to_coverage_enabled: Default::default(), + samplers: Default::default(), + texture_slots: Default::default(), + render_size: Default::default(), + resolve_attachments: Default::default(), + invalidate_attachments: Default::default(), + has_pass_label: Default::default(), + instance_vbuf_mask: Default::default(), + dirty_vbuf_mask: Default::default(), + active_first_instance: Default::default(), + first_instance_location: Default::default(), + immediates_descs: Default::default(), + current_immediates_data: [0; super::MAX_IMMEDIATES], + end_of_pass_timestamp: Default::default(), + clip_distance_count: Default::default(), + } + } +} + +impl super::CommandBuffer { + fn clear(&mut self) { + self.label = None; + self.commands.clear(); + self.data_bytes.clear(); + self.queries.clear(); + } + + fn add_marker(&mut self, marker: &str) -> Range<u32> { + let start = self.data_bytes.len() as u32; + self.data_bytes.extend(marker.as_bytes()); + start..self.data_bytes.len() as u32 + } + + fn add_immediates_data(&mut self, data: &[u32]) -> Range<u32> { + let data_raw = bytemuck::cast_slice(data); + let start = self.data_bytes.len(); + assert!(start < u32::MAX as usize); + self.data_bytes.extend_from_slice(data_raw); + let end = self.data_bytes.len(); + assert!(end < u32::MAX as usize); + (start as u32)..(end as u32) + } +} + +impl Drop for super::CommandEncoder { + fn drop(&mut self) { + use crate::CommandEncoder; + unsafe { self.discard_encoding() } + self.counters.command_encoders.sub(1); + } +} + +impl super::CommandEncoder { + fn rebind_stencil_func(&mut self) { + fn make(s: &super::StencilSide, face: u32) -> C { + C::SetStencilFunc { + face, + function: s.function, + reference: s.reference, + read_mask: s.mask_read, + } + } + + let s = &self.state.stencil; + if s.front.function == s.back.function + && s.front.mask_read == s.back.mask_read + && s.front.reference == s.back.reference + { + self.cmd_buffer + .commands + .push(make(&s.front, glow::FRONT_AND_BACK)); + } else { + self.cmd_buffer.commands.push(make(&s.front, glow::FRONT)); + self.cmd_buffer.commands.push(make(&s.back, glow::BACK)); + } + } + + fn rebind_vertex_data(&mut self, first_instance: u32) { + if self + .private_caps + .contains(super::PrivateCapabilities::VERTEX_BUFFER_LAYOUT) + { + for (index, pair) in self.state.vertex_buffers.iter().enumerate() { + if self.state.dirty_vbuf_mask & (1 << index) == 0 { + continue; + } + let (buffer_desc, vb) = match *pair { + (Some(ref vb_desc), Some(ref vb)) => (vb_desc.clone(), vb), + // Not all dirty bindings are necessarily filled. Some may be unused. + (_, _) => continue, + }; + let instance_offset = match buffer_desc.step { + wgt::VertexStepMode::Vertex => 0, + wgt::VertexStepMode::Instance => first_instance * buffer_desc.stride, + }; + + self.cmd_buffer.commands.push(C::SetVertexBuffer { + index: index as u32, + buffer: super::BufferBinding { + raw: vb.raw, + offset: vb.offset + instance_offset as wgt::BufferAddress, + }, + buffer_desc, + }); + self.state.dirty_vbuf_mask ^= 1 << index; + } + } else { + let mut vbuf_mask = 0; + for attribute in self.state.vertex_attributes.iter() { + if self.state.dirty_vbuf_mask & (1 << attribute.buffer_index) == 0 { + continue; + } + let (buffer_desc, vb) = + match self.state.vertex_buffers[attribute.buffer_index as usize] { + (Some(ref vb_desc), Some(ref vb)) => (vb_desc.clone(), vb), + // Not all dirty bindings are necessarily filled. Some may be unused. + (_, _) => continue, + }; + + let mut attribute_desc = attribute.clone(); + attribute_desc.offset += vb.offset as u32; + if buffer_desc.step == wgt::VertexStepMode::Instance { + attribute_desc.offset += buffer_desc.stride * first_instance; + } + + self.cmd_buffer.commands.push(C::SetVertexAttribute { + buffer: Some(vb.raw), + buffer_desc, + attribute_desc, + }); + vbuf_mask |= 1 << attribute.buffer_index; + } + self.state.dirty_vbuf_mask ^= vbuf_mask; + } + } + + fn rebind_sampler_states(&mut self, dirty_textures: u32, dirty_samplers: u32) { + for (texture_index, slot) in self.state.texture_slots.iter().enumerate() { + if dirty_textures & (1 << texture_index) != 0 + || slot + .sampler_index + .is_some_and(|si| dirty_samplers & (1 << si) != 0) + { + let sampler = slot + .sampler_index + .and_then(|si| self.state.samplers[si as usize]); + self.cmd_buffer + .commands + .push(C::BindSampler(texture_index as u32, sampler)); + } + } + } + + fn prepare_draw(&mut self, first_instance: u32) { + // If we support fully featured instancing, we want to bind everything as normal + // and let the draw call sort it out. + let emulated_first_instance_value = if self + .private_caps + .contains(super::PrivateCapabilities::FULLY_FEATURED_INSTANCING) + { + 0 + } else { + first_instance + }; + + if emulated_first_instance_value != self.state.active_first_instance { + // rebind all per-instance buffers on first-instance change + self.state.dirty_vbuf_mask |= self.state.instance_vbuf_mask; + self.state.active_first_instance = emulated_first_instance_value; + } + if self.state.dirty_vbuf_mask != 0 { + self.rebind_vertex_data(emulated_first_instance_value); + } + } + + fn set_pipeline_inner(&mut self, inner: &super::PipelineInner) { + self.cmd_buffer.commands.push(C::SetProgram(inner.program)); + + self.state + .first_instance_location + .clone_from(&inner.first_instance_location); + self.state + .immediates_descs + .clone_from(&inner.immediates_descs); + + // rebind textures, if needed + let mut dirty_textures = 0u32; + for (texture_index, (slot, &sampler_index)) in self + .state + .texture_slots + .iter_mut() + .zip(inner.sampler_map.iter()) + .enumerate() + { + if slot.sampler_index != sampler_index { + slot.sampler_index = sampler_index; + dirty_textures |= 1 << texture_index; + } + } + if dirty_textures != 0 { + self.rebind_sampler_states(dirty_textures, 0); + } + } +} + +impl crate::CommandEncoder for super::CommandEncoder { + type A = super::Api; + + unsafe fn begin_encoding(&mut self, label: crate::Label) -> Result<(), crate::DeviceError> { + self.state = State::default(); + self.cmd_buffer.label = label.map(String::from); + Ok(()) + } + unsafe fn discard_encoding(&mut self) { + self.cmd_buffer.clear(); + } + unsafe fn end_encoding(&mut self) -> Result<super::CommandBuffer, crate::DeviceError> { + Ok(mem::take(&mut self.cmd_buffer)) + } + unsafe fn reset_all<I>(&mut self, _command_buffers: I) { + //TODO: could re-use the allocations in all these command buffers + } + + unsafe fn transition_buffers<'a, T>(&mut self, barriers: T) + where + T: Iterator<Item = crate::BufferBarrier<'a, super::Buffer>>, + { + if !self + .private_caps + .contains(super::PrivateCapabilities::MEMORY_BARRIERS) + { + return; + } + for bar in barriers { + // GLES only synchronizes storage -> anything explicitly + if !bar.usage.from.contains(wgt::BufferUses::STORAGE_READ_WRITE) { + continue; + } + self.cmd_buffer + .commands + .push(C::BufferBarrier(bar.buffer.raw.unwrap(), bar.usage.to)); + } + } + + unsafe fn transition_textures<'a, T>(&mut self, barriers: T) + where + T: Iterator<Item = crate::TextureBarrier<'a, super::Texture>>, + { + if !self + .private_caps + .contains(super::PrivateCapabilities::MEMORY_BARRIERS) + { + return; + } + + let mut combined_usage = wgt::TextureUses::empty(); + for bar in barriers { + // GLES only synchronizes storage -> anything explicitly + // if shader writes to a texture then barriers should be placed + if !bar.usage.from.intersects( + wgt::TextureUses::STORAGE_READ_WRITE | wgt::TextureUses::STORAGE_WRITE_ONLY, + ) { + continue; + } + // unlike buffers, there is no need for a concrete texture + // object to be bound anywhere for a barrier + combined_usage |= bar.usage.to; + } + + if !combined_usage.is_empty() { + self.cmd_buffer + .commands + .push(C::TextureBarrier(combined_usage)); + } + } + + unsafe fn clear_buffer(&mut self, buffer: &super::Buffer, range: crate::MemoryRange) { + self.cmd_buffer.commands.push(C::ClearBuffer { + dst: buffer.clone(), + dst_target: buffer.target, + range, + }); + } + + unsafe fn copy_buffer_to_buffer<T>( + &mut self, + src: &super::Buffer, + dst: &super::Buffer, + regions: T, + ) where + T: Iterator<Item = crate::BufferCopy>, + { + let (src_target, dst_target) = if src.target == dst.target { + (glow::COPY_READ_BUFFER, glow::COPY_WRITE_BUFFER) + } else { + (src.target, dst.target) + }; + for copy in regions { + self.cmd_buffer.commands.push(C::CopyBufferToBuffer { + src: src.clone(), + src_target, + dst: dst.clone(), + dst_target, + copy, + }) + } + } + + #[cfg(webgl)] + unsafe fn copy_external_image_to_texture<T>( + &mut self, + src: &wgt::CopyExternalImageSourceInfo, + dst: &super::Texture, + dst_premultiplication: bool, + regions: T, + ) where + T: Iterator<Item = crate::TextureCopy>, + { + let (dst_raw, dst_target) = dst.inner.as_native(); + for copy in regions { + self.cmd_buffer + .commands + .push(C::CopyExternalImageToTexture { + src: src.clone(), + dst: dst_raw, + dst_target, + dst_format: dst.format, + dst_premultiplication, + copy, + }) + } + } + + unsafe fn copy_texture_to_texture<T>( + &mut self, + src: &super::Texture, + _src_usage: wgt::TextureUses, + dst: &super::Texture, + regions: T, + ) where + T: Iterator<Item = crate::TextureCopy>, + { + let (src_raw, src_target) = src.inner.as_native(); + let (dst_raw, dst_target) = dst.inner.as_native(); + for mut copy in regions { + copy.clamp_size_to_virtual(&src.copy_size, &dst.copy_size); + self.cmd_buffer.commands.push(C::CopyTextureToTexture { + src: src_raw, + src_target, + dst: dst_raw, + dst_target, + copy, + }) + } + } + + unsafe fn copy_buffer_to_texture<T>( + &mut self, + src: &super::Buffer, + dst: &super::Texture, + regions: T, + ) where + T: Iterator<Item = crate::BufferTextureCopy>, + { + let (dst_raw, dst_target) = dst.inner.as_native(); + + for mut copy in regions { + copy.clamp_size_to_virtual(&dst.copy_size); + self.cmd_buffer.commands.push(C::CopyBufferToTexture { + src: src.clone(), + src_target: src.target, + dst: dst_raw, + dst_target, + dst_format: dst.format, + copy, + }) + } + } + + unsafe fn copy_texture_to_buffer<T>( + &mut self, + src: &super::Texture, + _src_usage: wgt::TextureUses, + dst: &super::Buffer, + regions: T, + ) where + T: Iterator<Item = crate::BufferTextureCopy>, + { + let (src_raw, src_target) = src.inner.as_native(); + for mut copy in regions { + copy.clamp_size_to_virtual(&src.copy_size); + self.cmd_buffer.commands.push(C::CopyTextureToBuffer { + src: src_raw, + src_target, + src_format: src.format, + dst: dst.clone(), + dst_target: dst.target, + copy, + }) + } + } + + unsafe fn begin_query(&mut self, set: &super::QuerySet, index: u32) { + let query = set.queries[index as usize]; + self.cmd_buffer + .commands + .push(C::BeginQuery(query, set.target)); + } + unsafe fn end_query(&mut self, set: &super::QuerySet, _index: u32) { + self.cmd_buffer.commands.push(C::EndQuery(set.target)); + } + unsafe fn write_timestamp(&mut self, set: &super::QuerySet, index: u32) { + let query = set.queries[index as usize]; + self.cmd_buffer.commands.push(C::TimestampQuery(query)); + } + unsafe fn reset_queries(&mut self, _set: &super::QuerySet, _range: Range<u32>) { + //TODO: what do we do here? + } + unsafe fn copy_query_results( + &mut self, + set: &super::QuerySet, + range: Range<u32>, + buffer: &super::Buffer, + offset: wgt::BufferAddress, + _stride: wgt::BufferSize, + ) { + let start = self.cmd_buffer.queries.len(); + self.cmd_buffer + .queries + .extend_from_slice(&set.queries[range.start as usize..range.end as usize]); + let query_range = start as u32..self.cmd_buffer.queries.len() as u32; + self.cmd_buffer.commands.push(C::CopyQueryResults { + query_range, + dst: buffer.clone(), + dst_target: buffer.target, + dst_offset: offset, + }); + } + + // render + + unsafe fn begin_render_pass( + &mut self, + desc: &crate::RenderPassDescriptor<super::QuerySet, super::TextureView>, + ) -> Result<(), crate::DeviceError> { + debug_assert!(self.state.end_of_pass_timestamp.is_none()); + if let Some(ref t) = desc.timestamp_writes { + if let Some(index) = t.beginning_of_pass_write_index { + unsafe { self.write_timestamp(t.query_set, index) } + } + self.state.end_of_pass_timestamp = t + .end_of_pass_write_index + .map(|index| t.query_set.queries[index as usize]); + } + + self.state.render_size = desc.extent; + self.state.resolve_attachments.clear(); + self.state.invalidate_attachments.clear(); + if let Some(label) = desc.label { + let range = self.cmd_buffer.add_marker(label); + self.cmd_buffer.commands.push(C::PushDebugGroup(range)); + self.state.has_pass_label = true; + } + + let rendering_to_external_framebuffer = desc + .color_attachments + .iter() + .filter_map(|at| at.as_ref()) + .any(|at| match at.target.view.inner { + #[cfg(webgl)] + super::TextureInner::ExternalFramebuffer { .. } => true, + #[cfg(native)] + super::TextureInner::ExternalNativeFramebuffer { .. } => true, + _ => false, + }); + + if rendering_to_external_framebuffer && desc.color_attachments.len() != 1 { + panic!("Multiple render attachments with external framebuffers are not supported."); + } + + // `COLOR_ATTACHMENT0` to `COLOR_ATTACHMENT31` gives 32 possible color attachments. + assert!(desc.color_attachments.len() <= 32); + + match desc + .color_attachments + .first() + .filter(|at| at.is_some()) + .and_then(|at| at.as_ref().map(|at| &at.target.view.inner)) + { + // default framebuffer (provided externally) + Some(&super::TextureInner::DefaultRenderbuffer) => { + self.cmd_buffer + .commands + .push(C::ResetFramebuffer { is_default: true }); + } + _ => { + // set the framebuffer + self.cmd_buffer + .commands + .push(C::ResetFramebuffer { is_default: false }); + + for (i, cat) in desc.color_attachments.iter().enumerate() { + if let Some(cat) = cat.as_ref() { + let attachment = glow::COLOR_ATTACHMENT0 + i as u32; + // Try to use the multisampled render-to-texture extension to avoid resolving + if let Some(ref rat) = cat.resolve_target { + if matches!(rat.view.inner, super::TextureInner::Texture { .. }) + && self.private_caps.contains( + super::PrivateCapabilities::MULTISAMPLED_RENDER_TO_TEXTURE, + ) + && !cat.ops.contains(crate::AttachmentOps::STORE) + // Extension specifies that only COLOR_ATTACHMENT0 is valid + && i == 0 + { + self.cmd_buffer.commands.push(C::BindAttachment { + attachment, + view: rat.view.clone(), + depth_slice: None, + sample_count: desc.sample_count, + }); + continue; + } + } + self.cmd_buffer.commands.push(C::BindAttachment { + attachment, + view: cat.target.view.clone(), + depth_slice: cat.depth_slice, + sample_count: 1, + }); + if let Some(ref rat) = cat.resolve_target { + self.state + .resolve_attachments + .push((attachment, rat.view.clone())); + } + if cat.ops.contains(crate::AttachmentOps::STORE_DISCARD) { + self.state.invalidate_attachments.push(attachment); + } + } + } + if let Some(ref dsat) = desc.depth_stencil_attachment { + let aspects = dsat.target.view.aspects; + let attachment = match aspects { + crate::FormatAspects::DEPTH => glow::DEPTH_ATTACHMENT, + crate::FormatAspects::STENCIL => glow::STENCIL_ATTACHMENT, + _ => glow::DEPTH_STENCIL_ATTACHMENT, + }; + self.cmd_buffer.commands.push(C::BindAttachment { + attachment, + view: dsat.target.view.clone(), + depth_slice: None, + sample_count: 1, + }); + if aspects.contains(crate::FormatAspects::DEPTH) + && dsat.depth_ops.contains(crate::AttachmentOps::STORE_DISCARD) + { + self.state + .invalidate_attachments + .push(glow::DEPTH_ATTACHMENT); + } + if aspects.contains(crate::FormatAspects::STENCIL) + && dsat + .stencil_ops + .contains(crate::AttachmentOps::STORE_DISCARD) + { + self.state + .invalidate_attachments + .push(glow::STENCIL_ATTACHMENT); + } + } + } + } + + let rect = crate::Rect { + x: 0, + y: 0, + w: desc.extent.width as i32, + h: desc.extent.height as i32, + }; + self.cmd_buffer.commands.push(C::SetScissor(rect.clone())); + self.cmd_buffer.commands.push(C::SetViewport { + rect, + depth: 0.0..1.0, + }); + + if !rendering_to_external_framebuffer { + // set the draw buffers and states + self.cmd_buffer + .commands + .push(C::SetDrawColorBuffers(desc.color_attachments.len() as u8)); + } + + // issue the clears + for (i, cat) in desc + .color_attachments + .iter() + .filter_map(|at| at.as_ref()) + .enumerate() + { + if cat.ops.contains(crate::AttachmentOps::LOAD_CLEAR) { + let c = &cat.clear_value; + self.cmd_buffer.commands.push( + match cat.target.view.format.sample_type(None, None).unwrap() { + wgt::TextureSampleType::Float { .. } => C::ClearColorF { + draw_buffer: i as u32, + color: [c.r as f32, c.g as f32, c.b as f32, c.a as f32], + is_srgb: cat.target.view.format.is_srgb(), + }, + wgt::TextureSampleType::Uint => C::ClearColorU( + i as u32, + [c.r as u32, c.g as u32, c.b as u32, c.a as u32], + ), + wgt::TextureSampleType::Sint => C::ClearColorI( + i as u32, + [c.r as i32, c.g as i32, c.b as i32, c.a as i32], + ), + wgt::TextureSampleType::Depth => unreachable!(), + }, + ); + } + } + + if let Some(ref dsat) = desc.depth_stencil_attachment { + let clear_depth = dsat.depth_ops.contains(crate::AttachmentOps::LOAD_CLEAR); + let clear_stencil = dsat.stencil_ops.contains(crate::AttachmentOps::LOAD_CLEAR); + + if clear_depth && clear_stencil { + self.cmd_buffer.commands.push(C::ClearDepthAndStencil( + dsat.clear_value.0, + dsat.clear_value.1, + )); + } else if clear_depth { + self.cmd_buffer + .commands + .push(C::ClearDepth(dsat.clear_value.0)); + } else if clear_stencil { + self.cmd_buffer + .commands + .push(C::ClearStencil(dsat.clear_value.1)); + } + } + Ok(()) + } + unsafe fn end_render_pass(&mut self) { + for (attachment, dst) in self.state.resolve_attachments.drain(..) { + self.cmd_buffer.commands.push(C::ResolveAttachment { + attachment, + dst, + size: self.state.render_size, + }); + } + if !self.state.invalidate_attachments.is_empty() { + self.cmd_buffer.commands.push(C::InvalidateAttachments( + self.state.invalidate_attachments.clone(), + )); + self.state.invalidate_attachments.clear(); + } + if self.state.has_pass_label { + self.cmd_buffer.commands.push(C::PopDebugGroup); + self.state.has_pass_label = false; + } + self.state.instance_vbuf_mask = 0; + self.state.dirty_vbuf_mask = 0; + self.state.active_first_instance = 0; + self.state.color_targets.clear(); + for vat in &self.state.vertex_attributes { + self.cmd_buffer + .commands + .push(C::UnsetVertexAttribute(vat.location)); + } + self.state.vertex_attributes.clear(); + self.state.primitive = super::PrimitiveState::default(); + + if let Some(query) = self.state.end_of_pass_timestamp.take() { + self.cmd_buffer.commands.push(C::TimestampQuery(query)); + } + } + + unsafe fn set_bind_group( + &mut self, + layout: &super::PipelineLayout, + index: u32, + group: &super::BindGroup, + dynamic_offsets: &[wgt::DynamicOffset], + ) { + let mut do_index = 0; + let mut dirty_textures = 0u32; + let mut dirty_samplers = 0u32; + let group_info = layout.group_infos[index as usize].as_ref().unwrap(); + + for (binding_layout, raw_binding) in group_info.entries.iter().zip(group.contents.iter()) { + let slot = group_info.binding_to_slot[binding_layout.binding as usize] as u32; + match *raw_binding { + super::RawBinding::Buffer { + raw, + offset: base_offset, + size, + } => { + let mut offset = base_offset; + let target = match binding_layout.ty { + wgt::BindingType::Buffer { + ty, + has_dynamic_offset, + min_binding_size: _, + } => { + if has_dynamic_offset { + offset += dynamic_offsets[do_index] as i32; + do_index += 1; + } + match ty { + wgt::BufferBindingType::Uniform => glow::UNIFORM_BUFFER, + wgt::BufferBindingType::Storage { .. } => { + glow::SHADER_STORAGE_BUFFER + } + } + } + _ => unreachable!(), + }; + self.cmd_buffer.commands.push(C::BindBuffer { + target, + slot, + buffer: raw, + offset, + size, + }); + } + super::RawBinding::Sampler(sampler) => { + dirty_samplers |= 1 << slot; + self.state.samplers[slot as usize] = Some(sampler); + } + super::RawBinding::Texture { + raw, + target, + aspects, + ref mip_levels, + } => { + dirty_textures |= 1 << slot; + self.state.texture_slots[slot as usize].tex_target = target; + self.cmd_buffer.commands.push(C::BindTexture { + slot, + texture: raw, + target, + aspects, + mip_levels: mip_levels.clone(), + }); + } + super::RawBinding::Image(ref binding) => { + self.cmd_buffer.commands.push(C::BindImage { + slot, + binding: binding.clone(), + }); + } + } + } + + self.rebind_sampler_states(dirty_textures, dirty_samplers); + } + + unsafe fn set_immediates( + &mut self, + _layout: &super::PipelineLayout, + offset_bytes: u32, + data: &[u32], + ) { + // There is nothing preventing the user from trying to update a single value within + // a vector or matrix in the set_immediates call, as to the user, all of this is + // just memory. However OpenGL does not allow partial uniform updates. + // + // As such, we locally keep a copy of the current state of the immediate data memory + // block. If the user tries to update a single value, we have the data to update the entirety + // of the uniform. + let start_words = offset_bytes / 4; + let end_words = start_words + data.len() as u32; + self.state.current_immediates_data[start_words as usize..end_words as usize] + .copy_from_slice(data); + + // We iterate over the uniform list as there may be multiple uniforms that need + // updating from the same immediate data memory (one for each shader stage). + // + // Additionally, any statically unused uniform descs will have been removed from this list + // by OpenGL, so the uniform list is not contiguous. + for uniform in self.state.immediates_descs.iter().cloned() { + let uniform_size_words = uniform.size_bytes / 4; + let uniform_start_words = uniform.offset / 4; + let uniform_end_words = uniform_start_words + uniform_size_words; + + // Is true if any word within the uniform binding was updated + let needs_updating = + start_words < uniform_end_words || uniform_start_words <= end_words; + + if needs_updating { + let uniform_data = &self.state.current_immediates_data + [uniform_start_words as usize..uniform_end_words as usize]; + + let range = self.cmd_buffer.add_immediates_data(uniform_data); + + self.cmd_buffer.commands.push(C::SetImmediates { + uniform, + offset: range.start, + }); + } + } + } + + unsafe fn insert_debug_marker(&mut self, label: &str) { + let range = self.cmd_buffer.add_marker(label); + self.cmd_buffer.commands.push(C::InsertDebugMarker(range)); + } + unsafe fn begin_debug_marker(&mut self, group_label: &str) { + let range = self.cmd_buffer.add_marker(group_label); + self.cmd_buffer.commands.push(C::PushDebugGroup(range)); + } + unsafe fn end_debug_marker(&mut self) { + self.cmd_buffer.commands.push(C::PopDebugGroup); + } + + unsafe fn set_render_pipeline(&mut self, pipeline: &super::RenderPipeline) { + self.state.topology = conv::map_primitive_topology(pipeline.primitive.topology); + + if self + .private_caps + .contains(super::PrivateCapabilities::VERTEX_BUFFER_LAYOUT) + { + for vat in pipeline.vertex_attributes.iter() { + let vb = pipeline.vertex_buffers[vat.buffer_index as usize] + .as_ref() + .unwrap(); + // set the layout + self.cmd_buffer.commands.push(C::SetVertexAttribute { + buffer: None, + buffer_desc: vb.clone(), + attribute_desc: vat.clone(), + }); + } + } else { + for vat in &self.state.vertex_attributes { + self.cmd_buffer + .commands + .push(C::UnsetVertexAttribute(vat.location)); + } + self.state.vertex_attributes.clear(); + + self.state.dirty_vbuf_mask = 0; + // copy vertex attributes + for vat in pipeline.vertex_attributes.iter() { + //Note: we can invalidate more carefully here. + self.state.dirty_vbuf_mask |= 1 << vat.buffer_index; + self.state.vertex_attributes.push(vat.clone()); + } + } + + self.state.instance_vbuf_mask = 0; + // copy vertex state + for (index, (&mut (ref mut state_desc, _), pipe_desc)) in self + .state + .vertex_buffers + .iter_mut() + .zip(pipeline.vertex_buffers.iter()) + .enumerate() + { + let Some(pipe_desc) = pipe_desc else { + continue; + }; + if pipe_desc.step == wgt::VertexStepMode::Instance { + self.state.instance_vbuf_mask |= 1 << index; + } + if state_desc.as_ref() != Some(pipe_desc) { + self.state.dirty_vbuf_mask |= 1 << index; + *state_desc = Some(pipe_desc.clone()); + } + } + + self.set_pipeline_inner(&pipeline.inner); + + // set primitive state + let prim_state = conv::map_primitive_state(&pipeline.primitive); + if prim_state != self.state.primitive { + self.cmd_buffer + .commands + .push(C::SetPrimitive(prim_state.clone())); + self.state.primitive = prim_state; + } + + // set depth/stencil states + let mut aspects = crate::FormatAspects::empty(); + if pipeline.depth_bias != self.state.depth_bias { + self.state.depth_bias = pipeline.depth_bias; + self.cmd_buffer + .commands + .push(C::SetDepthBias(pipeline.depth_bias)); + } + if let Some(ref depth) = pipeline.depth { + aspects |= crate::FormatAspects::DEPTH; + self.cmd_buffer.commands.push(C::SetDepth(depth.clone())); + } + if let Some(ref stencil) = pipeline.stencil { + aspects |= crate::FormatAspects::STENCIL; + self.state.stencil = stencil.clone(); + self.rebind_stencil_func(); + if stencil.front.ops == stencil.back.ops + && stencil.front.mask_write == stencil.back.mask_write + { + self.cmd_buffer.commands.push(C::SetStencilOps { + face: glow::FRONT_AND_BACK, + write_mask: stencil.front.mask_write, + ops: stencil.front.ops.clone(), + }); + } else { + self.cmd_buffer.commands.push(C::SetStencilOps { + face: glow::FRONT, + write_mask: stencil.front.mask_write, + ops: stencil.front.ops.clone(), + }); + self.cmd_buffer.commands.push(C::SetStencilOps { + face: glow::BACK, + write_mask: stencil.back.mask_write, + ops: stencil.back.ops.clone(), + }); + } + } + self.cmd_buffer + .commands + .push(C::ConfigureDepthStencil(aspects)); + + // set multisampling state + if pipeline.alpha_to_coverage_enabled != self.state.alpha_to_coverage_enabled { + self.state.alpha_to_coverage_enabled = pipeline.alpha_to_coverage_enabled; + self.cmd_buffer + .commands + .push(C::SetAlphaToCoverage(pipeline.alpha_to_coverage_enabled)); + } + + // set blend states + if self.state.color_targets[..] != pipeline.color_targets[..] { + if pipeline + .color_targets + .iter() + .skip(1) + .any(|ct| *ct != pipeline.color_targets[0]) + { + for (index, ct) in pipeline.color_targets.iter().enumerate() { + self.cmd_buffer.commands.push(C::SetColorTarget { + draw_buffer_index: Some(index as u32), + desc: ct.clone(), + }); + } + } else { + self.cmd_buffer.commands.push(C::SetColorTarget { + draw_buffer_index: None, + desc: pipeline.color_targets.first().cloned().unwrap_or_default(), + }); + } + } + self.state.color_targets.clear(); + for ct in pipeline.color_targets.iter() { + self.state.color_targets.push(ct.clone()); + } + + // set clip plane count + if pipeline.inner.clip_distance_count != self.state.clip_distance_count { + self.cmd_buffer.commands.push(C::SetClipDistances { + old_count: self.state.clip_distance_count, + new_count: pipeline.inner.clip_distance_count, + }); + self.state.clip_distance_count = pipeline.inner.clip_distance_count; + } + } + + unsafe fn set_index_buffer<'a>( + &mut self, + binding: crate::BufferBinding<'a, super::Buffer>, + format: wgt::IndexFormat, + ) { + self.state.index_offset = binding.offset; + self.state.index_format = format; + self.cmd_buffer + .commands + .push(C::SetIndexBuffer(binding.buffer.raw.unwrap())); + } + unsafe fn set_vertex_buffer<'a>( + &mut self, + index: u32, + binding: crate::BufferBinding<'a, super::Buffer>, + ) { + self.state.dirty_vbuf_mask |= 1 << index; + let (_, ref mut vb) = self.state.vertex_buffers[index as usize]; + *vb = Some(super::BufferBinding { + raw: binding.buffer.raw.unwrap(), + offset: binding.offset, + }); + } + unsafe fn set_viewport(&mut self, rect: &crate::Rect<f32>, depth: Range<f32>) { + self.cmd_buffer.commands.push(C::SetViewport { + rect: crate::Rect { + x: rect.x as i32, + y: rect.y as i32, + w: rect.w as i32, + h: rect.h as i32, + }, + depth, + }); + } + unsafe fn set_scissor_rect(&mut self, rect: &crate::Rect<u32>) { + self.cmd_buffer.commands.push(C::SetScissor(crate::Rect { + x: rect.x as i32, + y: rect.y as i32, + w: rect.w as i32, + h: rect.h as i32, + })); + } + unsafe fn set_stencil_reference(&mut self, value: u32) { + self.state.stencil.front.reference = value; + self.state.stencil.back.reference = value; + self.rebind_stencil_func(); + } + unsafe fn set_blend_constants(&mut self, color: &[f32; 4]) { + self.cmd_buffer.commands.push(C::SetBlendConstant(*color)); + } + + unsafe fn draw( + &mut self, + first_vertex: u32, + vertex_count: u32, + first_instance: u32, + instance_count: u32, + ) { + self.prepare_draw(first_instance); + #[allow( + clippy::clone_on_copy, + reason = "False positive when cloning glow::UniformLocation" + )] + self.cmd_buffer.commands.push(C::Draw { + topology: self.state.topology, + first_vertex, + vertex_count, + first_instance, + instance_count, + first_instance_location: self.state.first_instance_location.clone(), + }); + } + unsafe fn draw_indexed( + &mut self, + first_index: u32, + index_count: u32, + base_vertex: i32, + first_instance: u32, + instance_count: u32, + ) { + self.prepare_draw(first_instance); + let (index_size, index_type) = match self.state.index_format { + wgt::IndexFormat::Uint16 => (2, glow::UNSIGNED_SHORT), + wgt::IndexFormat::Uint32 => (4, glow::UNSIGNED_INT), + }; + let index_offset = self.state.index_offset + index_size * first_index as wgt::BufferAddress; + #[allow( + clippy::clone_on_copy, + reason = "False positive when cloning glow::UniformLocation" + )] + self.cmd_buffer.commands.push(C::DrawIndexed { + topology: self.state.topology, + index_type, + index_offset, + index_count, + base_vertex, + first_instance, + instance_count, + first_instance_location: self.state.first_instance_location.clone(), + }); + } + unsafe fn draw_mesh_tasks( + &mut self, + _group_count_x: u32, + _group_count_y: u32, + _group_count_z: u32, + ) { + unreachable!() + } + unsafe fn draw_indirect( + &mut self, + buffer: &super::Buffer, + offset: wgt::BufferAddress, + draw_count: u32, + ) { + self.prepare_draw(0); + for draw in 0..draw_count as wgt::BufferAddress { + let indirect_offset = + offset + draw * size_of::<wgt::DrawIndirectArgs>() as wgt::BufferAddress; + #[allow( + clippy::clone_on_copy, + reason = "False positive when cloning glow::UniformLocation" + )] + self.cmd_buffer.commands.push(C::DrawIndirect { + topology: self.state.topology, + indirect_buf: buffer.raw.unwrap(), + indirect_offset, + first_instance_location: self.state.first_instance_location.clone(), + }); + } + } + unsafe fn draw_indexed_indirect( + &mut self, + buffer: &super::Buffer, + offset: wgt::BufferAddress, + draw_count: u32, + ) { + self.prepare_draw(0); + let index_type = match self.state.index_format { + wgt::IndexFormat::Uint16 => glow::UNSIGNED_SHORT, + wgt::IndexFormat::Uint32 => glow::UNSIGNED_INT, + }; + for draw in 0..draw_count as wgt::BufferAddress { + let indirect_offset = + offset + draw * size_of::<wgt::DrawIndexedIndirectArgs>() as wgt::BufferAddress; + #[allow( + clippy::clone_on_copy, + reason = "False positive when cloning glow::UniformLocation" + )] + self.cmd_buffer.commands.push(C::DrawIndexedIndirect { + topology: self.state.topology, + index_type, + indirect_buf: buffer.raw.unwrap(), + indirect_offset, + first_instance_location: self.state.first_instance_location.clone(), + }); + } + } + unsafe fn draw_mesh_tasks_indirect( + &mut self, + _buffer: &<Self::A as crate::Api>::Buffer, + _offset: wgt::BufferAddress, + _draw_count: u32, + ) { + unreachable!() + } + unsafe fn draw_indirect_count( + &mut self, + _buffer: &super::Buffer, + _offset: wgt::BufferAddress, + _count_buffer: &super::Buffer, + _count_offset: wgt::BufferAddress, + _max_count: u32, + ) { + unreachable!() + } + unsafe fn draw_indexed_indirect_count( + &mut self, + _buffer: &super::Buffer, + _offset: wgt::BufferAddress, + _count_buffer: &super::Buffer, + _count_offset: wgt::BufferAddress, + _max_count: u32, + ) { + unreachable!() + } + unsafe fn draw_mesh_tasks_indirect_count( + &mut self, + _buffer: &<Self::A as crate::Api>::Buffer, + _offset: wgt::BufferAddress, + _count_buffer: &<Self::A as crate::Api>::Buffer, + _count_offset: wgt::BufferAddress, + _max_count: u32, + ) { + unreachable!() + } + + // compute + + unsafe fn begin_compute_pass(&mut self, desc: &crate::ComputePassDescriptor<super::QuerySet>) { + debug_assert!(self.state.end_of_pass_timestamp.is_none()); + if let Some(ref t) = desc.timestamp_writes { + if let Some(index) = t.beginning_of_pass_write_index { + unsafe { self.write_timestamp(t.query_set, index) } + } + self.state.end_of_pass_timestamp = t + .end_of_pass_write_index + .map(|index| t.query_set.queries[index as usize]); + } + + if let Some(label) = desc.label { + let range = self.cmd_buffer.add_marker(label); + self.cmd_buffer.commands.push(C::PushDebugGroup(range)); + self.state.has_pass_label = true; + } + } + unsafe fn end_compute_pass(&mut self) { + if self.state.has_pass_label { + self.cmd_buffer.commands.push(C::PopDebugGroup); + self.state.has_pass_label = false; + } + + if let Some(query) = self.state.end_of_pass_timestamp.take() { + self.cmd_buffer.commands.push(C::TimestampQuery(query)); + } + } + + unsafe fn set_compute_pipeline(&mut self, pipeline: &super::ComputePipeline) { + self.set_pipeline_inner(&pipeline.inner); + } + + unsafe fn dispatch_workgroups(&mut self, count: [u32; 3]) { + // Empty dispatches are invalid in OpenGL, but valid in WebGPU. + if count.contains(&0) { + return; + } + self.cmd_buffer.commands.push(C::Dispatch(count)); + } + unsafe fn dispatch_workgroups_indirect( + &mut self, + buffer: &super::Buffer, + offset: wgt::BufferAddress, + ) { + self.cmd_buffer.commands.push(C::DispatchIndirect { + indirect_buf: buffer.raw.unwrap(), + indirect_offset: offset, + }); + } + + unsafe fn build_acceleration_structures<'a, T>( + &mut self, + _descriptor_count: u32, + _descriptors: T, + ) where + super::Api: 'a, + T: IntoIterator< + Item = crate::BuildAccelerationStructureDescriptor< + 'a, + super::Buffer, + super::AccelerationStructure, + >, + >, + { + unimplemented!() + } + + unsafe fn place_acceleration_structure_barrier( + &mut self, + _barriers: crate::AccelerationStructureBarrier, + ) { + unimplemented!() + } + + unsafe fn copy_acceleration_structure_to_acceleration_structure( + &mut self, + _src: &super::AccelerationStructure, + _dst: &super::AccelerationStructure, + _copy: wgt::AccelerationStructureCopy, + ) { + unimplemented!() + } + + unsafe fn read_acceleration_structure_compact_size( + &mut self, + _acceleration_structure: &super::AccelerationStructure, + _buf: &super::Buffer, + ) { + unimplemented!() + } + + unsafe fn set_acceleration_structure_dependencies( + _command_buffers: &[&super::CommandBuffer], + _dependencies: &[&super::AccelerationStructure], + ) { + unimplemented!() + } + + unsafe fn begin_ray_tracing_pass(&mut self, _desc: &crate::RayTracingPassDescriptor) { + unimplemented!() + } + + unsafe fn end_ray_tracing_pass(&mut self) { + unimplemented!() + } + + unsafe fn set_ray_tracing_pipeline( + &mut self, + _pipeline: &<Self::A as crate::Api>::RayTracingPipeline, + ) { + unimplemented!() + } + + unsafe fn trace_rays( + &mut self, + _count: [u32; 3], + _ray_generation_group_data: crate::PipelineGroupData<super::Buffer>, + _miss_group_data: crate::PipelineGroupData<super::Buffer>, + _intersection_group_data: crate::PipelineGroupData<super::Buffer>, + ) { + unimplemented!() + } +} diff --git a/app/vendor/rune/vendor/wgpu-hal/src/gles/conv.rs b/app/vendor/rune/vendor/wgpu-hal/src/gles/conv.rs new file mode 100644 index 0000000..5b54f8f --- /dev/null +++ b/app/vendor/rune/vendor/wgpu-hal/src/gles/conv.rs @@ -0,0 +1,430 @@ +impl super::AdapterShared { + pub(super) fn describe_texture_format( + &self, + texture_format: wgt::TextureFormat, + ) -> super::TextureFormatDesc { + use wgt::TextureFormat as Tf; + use wgt::{AstcBlock, AstcChannel}; + + let (internal, external, data_type) = match texture_format { + Tf::R8Unorm => (glow::R8, glow::RED, glow::UNSIGNED_BYTE), + Tf::R8Snorm => (glow::R8_SNORM, glow::RED, glow::BYTE), + Tf::R8Uint => (glow::R8UI, glow::RED_INTEGER, glow::UNSIGNED_BYTE), + Tf::R8Sint => (glow::R8I, glow::RED_INTEGER, glow::BYTE), + Tf::R16Uint => (glow::R16UI, glow::RED_INTEGER, glow::UNSIGNED_SHORT), + Tf::R16Sint => (glow::R16I, glow::RED_INTEGER, glow::SHORT), + Tf::R16Unorm => (glow::R16, glow::RED, glow::UNSIGNED_SHORT), + Tf::R16Snorm => (glow::R16_SNORM, glow::RED, glow::SHORT), + Tf::R16Float => (glow::R16F, glow::RED, glow::HALF_FLOAT), + Tf::Rg8Unorm => (glow::RG8, glow::RG, glow::UNSIGNED_BYTE), + Tf::Rg8Snorm => (glow::RG8_SNORM, glow::RG, glow::BYTE), + Tf::Rg8Uint => (glow::RG8UI, glow::RG_INTEGER, glow::UNSIGNED_BYTE), + Tf::Rg8Sint => (glow::RG8I, glow::RG_INTEGER, glow::BYTE), + Tf::R32Uint => (glow::R32UI, glow::RED_INTEGER, glow::UNSIGNED_INT), + Tf::R32Sint => (glow::R32I, glow::RED_INTEGER, glow::INT), + Tf::R32Float => (glow::R32F, glow::RED, glow::FLOAT), + Tf::Rg16Uint => (glow::RG16UI, glow::RG_INTEGER, glow::UNSIGNED_SHORT), + Tf::Rg16Sint => (glow::RG16I, glow::RG_INTEGER, glow::SHORT), + Tf::Rg16Unorm => (glow::RG16, glow::RG, glow::UNSIGNED_SHORT), + Tf::Rg16Snorm => (glow::RG16_SNORM, glow::RG, glow::SHORT), + Tf::Rg16Float => (glow::RG16F, glow::RG, glow::HALF_FLOAT), + Tf::Rgba8Unorm => (glow::RGBA8, glow::RGBA, glow::UNSIGNED_BYTE), + Tf::Rgba8UnormSrgb => (glow::SRGB8_ALPHA8, glow::RGBA, glow::UNSIGNED_BYTE), + Tf::Bgra8UnormSrgb => (glow::SRGB8_ALPHA8, glow::BGRA, glow::UNSIGNED_BYTE), //TODO? + Tf::Rgba8Snorm => (glow::RGBA8_SNORM, glow::RGBA, glow::BYTE), + Tf::Bgra8Unorm => (glow::RGBA8, glow::BGRA, glow::UNSIGNED_BYTE), //TODO? + Tf::Rgba8Uint => (glow::RGBA8UI, glow::RGBA_INTEGER, glow::UNSIGNED_BYTE), + Tf::Rgba8Sint => (glow::RGBA8I, glow::RGBA_INTEGER, glow::BYTE), + Tf::Rgb10a2Uint => ( + glow::RGB10_A2UI, + glow::RGBA_INTEGER, + glow::UNSIGNED_INT_2_10_10_10_REV, + ), + Tf::Rgb10a2Unorm => ( + glow::RGB10_A2, + glow::RGBA, + glow::UNSIGNED_INT_2_10_10_10_REV, + ), + Tf::Rg11b10Ufloat => ( + glow::R11F_G11F_B10F, + glow::RGB, + glow::UNSIGNED_INT_10F_11F_11F_REV, + ), + Tf::R64Uint => (glow::RG32UI, glow::RED_INTEGER, glow::UNSIGNED_INT), + Tf::Rg32Uint => (glow::RG32UI, glow::RG_INTEGER, glow::UNSIGNED_INT), + Tf::Rg32Sint => (glow::RG32I, glow::RG_INTEGER, glow::INT), + Tf::Rg32Float => (glow::RG32F, glow::RG, glow::FLOAT), + Tf::Rgba16Uint => (glow::RGBA16UI, glow::RGBA_INTEGER, glow::UNSIGNED_SHORT), + Tf::Rgba16Sint => (glow::RGBA16I, glow::RGBA_INTEGER, glow::SHORT), + Tf::Rgba16Unorm => (glow::RGBA16, glow::RGBA, glow::UNSIGNED_SHORT), + Tf::Rgba16Snorm => (glow::RGBA16_SNORM, glow::RGBA, glow::SHORT), + Tf::Rgba16Float => (glow::RGBA16F, glow::RGBA, glow::HALF_FLOAT), + Tf::Rgba32Uint => (glow::RGBA32UI, glow::RGBA_INTEGER, glow::UNSIGNED_INT), + Tf::Rgba32Sint => (glow::RGBA32I, glow::RGBA_INTEGER, glow::INT), + Tf::Rgba32Float => (glow::RGBA32F, glow::RGBA, glow::FLOAT), + Tf::Stencil8 => ( + glow::STENCIL_INDEX8, + glow::STENCIL_INDEX, + glow::UNSIGNED_BYTE, + ), + Tf::Depth16Unorm => ( + glow::DEPTH_COMPONENT16, + glow::DEPTH_COMPONENT, + glow::UNSIGNED_SHORT, + ), + Tf::Depth32Float => (glow::DEPTH_COMPONENT32F, glow::DEPTH_COMPONENT, glow::FLOAT), + Tf::Depth32FloatStencil8 => ( + glow::DEPTH32F_STENCIL8, + glow::DEPTH_STENCIL, + glow::FLOAT_32_UNSIGNED_INT_24_8_REV, + ), + Tf::Depth24Plus => ( + glow::DEPTH_COMPONENT24, + glow::DEPTH_COMPONENT, + glow::UNSIGNED_INT, + ), + Tf::Depth24PlusStencil8 => ( + glow::DEPTH24_STENCIL8, + glow::DEPTH_STENCIL, + glow::UNSIGNED_INT_24_8, + ), + Tf::NV12 => unreachable!(), + Tf::P010 => unreachable!(), + Tf::Rgb9e5Ufloat => (glow::RGB9_E5, glow::RGB, glow::UNSIGNED_INT_5_9_9_9_REV), + Tf::Bc1RgbaUnorm => (glow::COMPRESSED_RGBA_S3TC_DXT1_EXT, glow::RGBA, 0), + Tf::Bc1RgbaUnormSrgb => (glow::COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT, glow::RGBA, 0), + Tf::Bc2RgbaUnorm => (glow::COMPRESSED_RGBA_S3TC_DXT3_EXT, glow::RGBA, 0), + Tf::Bc2RgbaUnormSrgb => (glow::COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT, glow::RGBA, 0), + Tf::Bc3RgbaUnorm => (glow::COMPRESSED_RGBA_S3TC_DXT5_EXT, glow::RGBA, 0), + Tf::Bc3RgbaUnormSrgb => (glow::COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT, glow::RGBA, 0), + Tf::Bc4RUnorm => (glow::COMPRESSED_RED_RGTC1, glow::RED, 0), + Tf::Bc4RSnorm => (glow::COMPRESSED_SIGNED_RED_RGTC1, glow::RED, 0), + Tf::Bc5RgUnorm => (glow::COMPRESSED_RG_RGTC2, glow::RG, 0), + Tf::Bc5RgSnorm => (glow::COMPRESSED_SIGNED_RG_RGTC2, glow::RG, 0), + Tf::Bc6hRgbUfloat => (glow::COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT, glow::RGB, 0), + Tf::Bc6hRgbFloat => (glow::COMPRESSED_RGB_BPTC_SIGNED_FLOAT, glow::RGB, 0), + Tf::Bc7RgbaUnorm => (glow::COMPRESSED_RGBA_BPTC_UNORM, glow::RGBA, 0), + Tf::Bc7RgbaUnormSrgb => (glow::COMPRESSED_SRGB_ALPHA_BPTC_UNORM, glow::RGBA, 0), + Tf::Etc2Rgb8Unorm => (glow::COMPRESSED_RGB8_ETC2, glow::RGB, 0), + Tf::Etc2Rgb8UnormSrgb => (glow::COMPRESSED_SRGB8_ETC2, glow::RGB, 0), + Tf::Etc2Rgb8A1Unorm => ( + glow::COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2, + glow::RGBA, + 0, + ), + Tf::Etc2Rgb8A1UnormSrgb => ( + glow::COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2, + glow::RGBA, + 0, + ), + Tf::Etc2Rgba8Unorm => (glow::COMPRESSED_RGBA8_ETC2_EAC, glow::RGBA, 0), + Tf::Etc2Rgba8UnormSrgb => (glow::COMPRESSED_SRGB8_ALPHA8_ETC2_EAC, glow::RGBA, 0), + Tf::EacR11Unorm => (glow::COMPRESSED_R11_EAC, glow::RED, 0), + Tf::EacR11Snorm => (glow::COMPRESSED_SIGNED_R11_EAC, glow::RED, 0), + Tf::EacRg11Unorm => (glow::COMPRESSED_RG11_EAC, glow::RG, 0), + Tf::EacRg11Snorm => (glow::COMPRESSED_SIGNED_RG11_EAC, glow::RG, 0), + Tf::Astc { block, channel } => match channel { + AstcChannel::Unorm | AstcChannel::Hdr => match block { + AstcBlock::B4x4 => (glow::COMPRESSED_RGBA_ASTC_4x4_KHR, glow::RGBA, 0), + AstcBlock::B5x4 => (glow::COMPRESSED_RGBA_ASTC_5x4_KHR, glow::RGBA, 0), + AstcBlock::B5x5 => (glow::COMPRESSED_RGBA_ASTC_5x5_KHR, glow::RGBA, 0), + AstcBlock::B6x5 => (glow::COMPRESSED_RGBA_ASTC_6x5_KHR, glow::RGBA, 0), + AstcBlock::B6x6 => (glow::COMPRESSED_RGBA_ASTC_6x6_KHR, glow::RGBA, 0), + AstcBlock::B8x5 => (glow::COMPRESSED_RGBA_ASTC_8x5_KHR, glow::RGBA, 0), + AstcBlock::B8x6 => (glow::COMPRESSED_RGBA_ASTC_8x6_KHR, glow::RGBA, 0), + AstcBlock::B8x8 => (glow::COMPRESSED_RGBA_ASTC_8x8_KHR, glow::RGBA, 0), + AstcBlock::B10x5 => (glow::COMPRESSED_RGBA_ASTC_10x5_KHR, glow::RGBA, 0), + AstcBlock::B10x6 => (glow::COMPRESSED_RGBA_ASTC_10x6_KHR, glow::RGBA, 0), + AstcBlock::B10x8 => (glow::COMPRESSED_RGBA_ASTC_10x8_KHR, glow::RGBA, 0), + AstcBlock::B10x10 => (glow::COMPRESSED_RGBA_ASTC_10x10_KHR, glow::RGBA, 0), + AstcBlock::B12x10 => (glow::COMPRESSED_RGBA_ASTC_12x10_KHR, glow::RGBA, 0), + AstcBlock::B12x12 => (glow::COMPRESSED_RGBA_ASTC_12x12_KHR, glow::RGBA, 0), + }, + AstcChannel::UnormSrgb => match block { + AstcBlock::B4x4 => (glow::COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR, glow::RGBA, 0), + AstcBlock::B5x4 => (glow::COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR, glow::RGBA, 0), + AstcBlock::B5x5 => (glow::COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR, glow::RGBA, 0), + AstcBlock::B6x5 => (glow::COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR, glow::RGBA, 0), + AstcBlock::B6x6 => (glow::COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR, glow::RGBA, 0), + AstcBlock::B8x5 => (glow::COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR, glow::RGBA, 0), + AstcBlock::B8x6 => (glow::COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR, glow::RGBA, 0), + AstcBlock::B8x8 => (glow::COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR, glow::RGBA, 0), + AstcBlock::B10x5 => { + (glow::COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR, glow::RGBA, 0) + } + AstcBlock::B10x6 => { + (glow::COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR, glow::RGBA, 0) + } + AstcBlock::B10x8 => { + (glow::COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR, glow::RGBA, 0) + } + AstcBlock::B10x10 => { + (glow::COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR, glow::RGBA, 0) + } + AstcBlock::B12x10 => { + (glow::COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR, glow::RGBA, 0) + } + AstcBlock::B12x12 => { + (glow::COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR, glow::RGBA, 0) + } + }, + }, + }; + + super::TextureFormatDesc { + internal, + external, + data_type, + } + } +} + +pub(super) fn describe_vertex_format(vertex_format: wgt::VertexFormat) -> super::VertexFormatDesc { + use super::VertexAttribKind as Vak; + use wgt::VertexFormat as Vf; + + let (element_count, element_format, attrib_kind) = match vertex_format { + Vf::Unorm8 => (1, glow::UNSIGNED_BYTE, Vak::Float), + Vf::Snorm8 => (1, glow::BYTE, Vak::Float), + Vf::Uint8 => (1, glow::UNSIGNED_BYTE, Vak::Integer), + Vf::Sint8 => (1, glow::BYTE, Vak::Integer), + Vf::Unorm8x2 => (2, glow::UNSIGNED_BYTE, Vak::Float), + Vf::Snorm8x2 => (2, glow::BYTE, Vak::Float), + Vf::Uint8x2 => (2, glow::UNSIGNED_BYTE, Vak::Integer), + Vf::Sint8x2 => (2, glow::BYTE, Vak::Integer), + Vf::Unorm8x4 => (4, glow::UNSIGNED_BYTE, Vak::Float), + Vf::Snorm8x4 => (4, glow::BYTE, Vak::Float), + Vf::Uint8x4 => (4, glow::UNSIGNED_BYTE, Vak::Integer), + Vf::Sint8x4 => (4, glow::BYTE, Vak::Integer), + Vf::Unorm16 => (1, glow::UNSIGNED_SHORT, Vak::Float), + Vf::Snorm16 => (1, glow::SHORT, Vak::Float), + Vf::Uint16 => (1, glow::UNSIGNED_SHORT, Vak::Integer), + Vf::Sint16 => (1, glow::SHORT, Vak::Integer), + Vf::Float16 => (1, glow::HALF_FLOAT, Vak::Float), + Vf::Unorm16x2 => (2, glow::UNSIGNED_SHORT, Vak::Float), + Vf::Snorm16x2 => (2, glow::SHORT, Vak::Float), + Vf::Uint16x2 => (2, glow::UNSIGNED_SHORT, Vak::Integer), + Vf::Sint16x2 => (2, glow::SHORT, Vak::Integer), + Vf::Float16x2 => (2, glow::HALF_FLOAT, Vak::Float), + Vf::Unorm16x4 => (4, glow::UNSIGNED_SHORT, Vak::Float), + Vf::Snorm16x4 => (4, glow::SHORT, Vak::Float), + Vf::Uint16x4 => (4, glow::UNSIGNED_SHORT, Vak::Integer), + Vf::Sint16x4 => (4, glow::SHORT, Vak::Integer), + Vf::Float16x4 => (4, glow::HALF_FLOAT, Vak::Float), + Vf::Uint32 => (1, glow::UNSIGNED_INT, Vak::Integer), + Vf::Sint32 => (1, glow::INT, Vak::Integer), + Vf::Float32 => (1, glow::FLOAT, Vak::Float), + Vf::Uint32x2 => (2, glow::UNSIGNED_INT, Vak::Integer), + Vf::Sint32x2 => (2, glow::INT, Vak::Integer), + Vf::Float32x2 => (2, glow::FLOAT, Vak::Float), + Vf::Uint32x3 => (3, glow::UNSIGNED_INT, Vak::Integer), + Vf::Sint32x3 => (3, glow::INT, Vak::Integer), + Vf::Float32x3 => (3, glow::FLOAT, Vak::Float), + Vf::Uint32x4 => (4, glow::UNSIGNED_INT, Vak::Integer), + Vf::Sint32x4 => (4, glow::INT, Vak::Integer), + Vf::Float32x4 => (4, glow::FLOAT, Vak::Float), + Vf::Unorm10_10_10_2 => (4, glow::UNSIGNED_INT_2_10_10_10_REV, Vak::Float), + Vf::Unorm8x4Bgra => (glow::BGRA as i32, glow::UNSIGNED_BYTE, Vak::Float), + Vf::Float64 | Vf::Float64x2 | Vf::Float64x3 | Vf::Float64x4 => unimplemented!(), + }; + + super::VertexFormatDesc { + element_count, + element_format, + attrib_kind, + } +} + +pub fn map_filter_modes( + min: wgt::FilterMode, + mag: wgt::FilterMode, + mip: wgt::MipmapFilterMode, +) -> (u32, u32) { + use wgt::FilterMode as Fm; + use wgt::MipmapFilterMode as Mfm; + + let mag_filter = match mag { + Fm::Nearest => glow::NEAREST, + Fm::Linear => glow::LINEAR, + }; + + let min_filter = match (min, mip) { + (Fm::Nearest, Mfm::Nearest) => glow::NEAREST_MIPMAP_NEAREST, + (Fm::Nearest, Mfm::Linear) => glow::NEAREST_MIPMAP_LINEAR, + (Fm::Linear, Mfm::Nearest) => glow::LINEAR_MIPMAP_NEAREST, + (Fm::Linear, Mfm::Linear) => glow::LINEAR_MIPMAP_LINEAR, + }; + + (min_filter, mag_filter) +} + +pub fn map_address_mode(mode: wgt::AddressMode) -> u32 { + match mode { + wgt::AddressMode::Repeat => glow::REPEAT, + wgt::AddressMode::MirrorRepeat => glow::MIRRORED_REPEAT, + wgt::AddressMode::ClampToEdge => glow::CLAMP_TO_EDGE, + wgt::AddressMode::ClampToBorder => glow::CLAMP_TO_BORDER, + //wgt::AddressMode::MirrorClamp => glow::MIRROR_CLAMP_TO_EDGE, + } +} + +pub fn map_compare_func(fun: wgt::CompareFunction) -> u32 { + use wgt::CompareFunction as Cf; + match fun { + Cf::Never => glow::NEVER, + Cf::Less => glow::LESS, + Cf::LessEqual => glow::LEQUAL, + Cf::Equal => glow::EQUAL, + Cf::GreaterEqual => glow::GEQUAL, + Cf::Greater => glow::GREATER, + Cf::NotEqual => glow::NOTEQUAL, + Cf::Always => glow::ALWAYS, + } +} + +pub fn map_primitive_topology(topology: wgt::PrimitiveTopology) -> u32 { + use wgt::PrimitiveTopology as Pt; + match topology { + Pt::PointList => glow::POINTS, + Pt::LineList => glow::LINES, + Pt::LineStrip => glow::LINE_STRIP, + Pt::TriangleList => glow::TRIANGLES, + Pt::TriangleStrip => glow::TRIANGLE_STRIP, + } +} + +pub(super) fn map_primitive_state(state: &wgt::PrimitiveState) -> super::PrimitiveState { + super::PrimitiveState { + //Note: we are flipping the front face, so that + // the Y-flip in the generated GLSL keeps the same visibility. + // See `naga::back::glsl::WriterFlags::ADJUST_COORDINATE_SPACE`. + front_face: match state.front_face { + wgt::FrontFace::Cw => glow::CCW, + wgt::FrontFace::Ccw => glow::CW, + }, + cull_face: match state.cull_mode { + Some(wgt::Face::Front) => glow::FRONT, + Some(wgt::Face::Back) => glow::BACK, + None => 0, + }, + unclipped_depth: state.unclipped_depth, + polygon_mode: match state.polygon_mode { + wgt::PolygonMode::Fill => glow::FILL, + wgt::PolygonMode::Line => glow::LINE, + wgt::PolygonMode::Point => glow::POINT, + }, + } +} + +pub fn _map_view_dimension(dim: wgt::TextureViewDimension) -> u32 { + use wgt::TextureViewDimension as Tvd; + match dim { + Tvd::D1 | Tvd::D2 => glow::TEXTURE_2D, + Tvd::D2Array => glow::TEXTURE_2D_ARRAY, + Tvd::Cube => glow::TEXTURE_CUBE_MAP, + Tvd::CubeArray => glow::TEXTURE_CUBE_MAP_ARRAY, + Tvd::D3 => glow::TEXTURE_3D, + } +} + +fn map_stencil_op(operation: wgt::StencilOperation) -> u32 { + use wgt::StencilOperation as So; + match operation { + So::Keep => glow::KEEP, + So::Zero => glow::ZERO, + So::Replace => glow::REPLACE, + So::Invert => glow::INVERT, + So::IncrementClamp => glow::INCR, + So::DecrementClamp => glow::DECR, + So::IncrementWrap => glow::INCR_WRAP, + So::DecrementWrap => glow::DECR_WRAP, + } +} + +fn map_stencil_ops(face: &wgt::StencilFaceState) -> super::StencilOps { + super::StencilOps { + pass: map_stencil_op(face.pass_op), + fail: map_stencil_op(face.fail_op), + depth_fail: map_stencil_op(face.depth_fail_op), + } +} + +pub(super) fn map_stencil(state: &wgt::StencilState) -> super::StencilState { + super::StencilState { + front: super::StencilSide { + function: map_compare_func(state.front.compare), + mask_read: state.read_mask, + mask_write: state.write_mask, + reference: 0, + ops: map_stencil_ops(&state.front), + }, + back: super::StencilSide { + function: map_compare_func(state.back.compare), + mask_read: state.read_mask, + mask_write: state.write_mask, + reference: 0, + ops: map_stencil_ops(&state.back), + }, + } +} + +fn map_blend_factor(factor: wgt::BlendFactor) -> u32 { + use wgt::BlendFactor as Bf; + match factor { + Bf::Zero => glow::ZERO, + Bf::One => glow::ONE, + Bf::Src => glow::SRC_COLOR, + Bf::OneMinusSrc => glow::ONE_MINUS_SRC_COLOR, + Bf::Dst => glow::DST_COLOR, + Bf::OneMinusDst => glow::ONE_MINUS_DST_COLOR, + Bf::SrcAlpha => glow::SRC_ALPHA, + Bf::OneMinusSrcAlpha => glow::ONE_MINUS_SRC_ALPHA, + Bf::DstAlpha => glow::DST_ALPHA, + Bf::OneMinusDstAlpha => glow::ONE_MINUS_DST_ALPHA, + Bf::Constant => glow::CONSTANT_COLOR, + Bf::OneMinusConstant => glow::ONE_MINUS_CONSTANT_COLOR, + Bf::SrcAlphaSaturated => glow::SRC_ALPHA_SATURATE, + Bf::Src1 => glow::SRC1_COLOR, + Bf::OneMinusSrc1 => glow::ONE_MINUS_SRC1_COLOR, + Bf::Src1Alpha => glow::SRC1_ALPHA, + Bf::OneMinusSrc1Alpha => glow::ONE_MINUS_SRC1_ALPHA, + } +} + +fn map_blend_component(component: &wgt::BlendComponent) -> super::BlendComponent { + super::BlendComponent { + src: map_blend_factor(component.src_factor), + dst: map_blend_factor(component.dst_factor), + equation: match component.operation { + wgt::BlendOperation::Add => glow::FUNC_ADD, + wgt::BlendOperation::Subtract => glow::FUNC_SUBTRACT, + wgt::BlendOperation::ReverseSubtract => glow::FUNC_REVERSE_SUBTRACT, + wgt::BlendOperation::Min => glow::MIN, + wgt::BlendOperation::Max => glow::MAX, + }, + } +} + +pub(super) fn map_blend(blend: &wgt::BlendState) -> super::BlendDesc { + super::BlendDesc { + color: map_blend_component(&blend.color), + alpha: map_blend_component(&blend.alpha), + } +} + +pub(super) fn map_storage_access(access: wgt::StorageTextureAccess) -> u32 { + match access { + wgt::StorageTextureAccess::ReadOnly => glow::READ_ONLY, + wgt::StorageTextureAccess::WriteOnly => glow::WRITE_ONLY, + wgt::StorageTextureAccess::ReadWrite => glow::READ_WRITE, + wgt::StorageTextureAccess::Atomic => glow::READ_WRITE, + } +} + +pub(super) fn is_layered_target(target: u32) -> bool { + match target { + glow::TEXTURE_2D | glow::TEXTURE_CUBE_MAP => false, + glow::TEXTURE_2D_ARRAY | glow::TEXTURE_CUBE_MAP_ARRAY | glow::TEXTURE_3D => true, + _ => unreachable!(), + } +} diff --git a/app/vendor/rune/vendor/wgpu-hal/src/gles/device.rs b/app/vendor/rune/vendor/wgpu-hal/src/gles/device.rs new file mode 100644 index 0000000..1c61cf3 --- /dev/null +++ b/app/vendor/rune/vendor/wgpu-hal/src/gles/device.rs @@ -0,0 +1,1823 @@ +use alloc::{ + borrow::{Cow, ToOwned}, + format, + string::String, + string::ToString as _, + sync::Arc, + vec, + vec::Vec, +}; +use core::{cmp::max, convert::TryInto, num::NonZeroU32, ptr, sync::atomic::Ordering}; + +use arrayvec::ArrayVec; +use glow::HasContext; +use naga::FastHashMap; + +use super::{conv, lock, MaybeMutex, PrivateCapabilities}; +use crate::auxil::map_naga_stage; +use crate::TlasInstance; + +type ShaderStage<'a> = ( + naga::ShaderStage, + &'a crate::ProgrammableStage<'a, super::ShaderModule>, +); +type NameBindingMap = FastHashMap<String, (super::BindingRegister, u8)>; + +struct CompilationContext<'a> { + layout: &'a super::PipelineLayout, + sampler_map: &'a mut super::SamplerBindMap, + name_binding_map: &'a mut NameBindingMap, + immediates_items: &'a mut Vec<naga::back::glsl::ImmediateItem>, + multiview_mask: Option<NonZeroU32>, + clip_distance_count: &'a mut u32, +} + +impl CompilationContext<'_> { + fn consume_reflection( + self, + gl: &glow::Context, + module: &naga::Module, + ep_info: &naga::valid::FunctionInfo, + reflection_info: naga::back::glsl::ReflectionInfo, + naga_stage: naga::ShaderStage, + program: glow::Program, + ) { + for (handle, var) in module.global_variables.iter() { + if ep_info[handle].is_empty() { + continue; + } + let register = match var.space { + naga::AddressSpace::Uniform => super::BindingRegister::UniformBuffers, + naga::AddressSpace::Storage { .. } => super::BindingRegister::StorageBuffers, + _ => continue, + }; + + let br = var.binding.as_ref().unwrap(); + let slot = self.layout.get_slot(br); + + let name = match reflection_info.uniforms.get(&handle) { + Some(name) => name.clone(), + None => continue, + }; + log::trace!( + "Rebind buffer: {:?} -> {}, register={:?}, slot={}", + var.name.as_ref(), + &name, + register, + slot + ); + self.name_binding_map.insert(name, (register, slot)); + } + + for (name, mapping) in reflection_info.texture_mapping { + let var = &module.global_variables[mapping.texture]; + let register = match module.types[var.ty].inner { + naga::TypeInner::Image { + class: naga::ImageClass::Storage { .. }, + .. + } => super::BindingRegister::Images, + _ => super::BindingRegister::Textures, + }; + + let tex_br = var.binding.as_ref().unwrap(); + let texture_linear_index = self.layout.get_slot(tex_br); + + self.name_binding_map + .insert(name, (register, texture_linear_index)); + if let Some(sampler_handle) = mapping.sampler { + let sam_br = module.global_variables[sampler_handle] + .binding + .as_ref() + .unwrap(); + let sampler_linear_index = self.layout.get_slot(sam_br); + self.sampler_map[texture_linear_index as usize] = Some(sampler_linear_index); + } + } + + for (name, location) in reflection_info.varying { + match naga_stage { + naga::ShaderStage::Vertex => { + assert_eq!(location.index, 0); + unsafe { gl.bind_attrib_location(program, location.location, &name) } + } + naga::ShaderStage::Fragment => { + assert_eq!(location.index, 0); + unsafe { gl.bind_frag_data_location(program, location.location, &name) } + } + naga::ShaderStage::Compute => {} + naga::ShaderStage::Task + | naga::ShaderStage::Mesh + | naga::ShaderStage::RayGeneration + | naga::ShaderStage::AnyHit + | naga::ShaderStage::ClosestHit + | naga::ShaderStage::Miss => unreachable!(), + } + } + + *self.immediates_items = reflection_info.immediates_items; + + if naga_stage == naga::ShaderStage::Vertex { + *self.clip_distance_count = reflection_info.clip_distance_count; + } + } +} + +impl super::Device { + /// # Safety + /// + /// - `name` must be created respecting `desc` + /// - `name` must be a texture + /// - If `drop_callback` is [`None`], wgpu-hal will take ownership of the texture. If + /// `drop_callback` is [`Some`], the texture must be valid until the callback is called. + #[cfg(any(native, Emscripten))] + pub unsafe fn texture_from_raw( + &self, + name: NonZeroU32, + desc: &crate::TextureDescriptor, + drop_callback: Option<crate::DropCallback>, + ) -> super::Texture { + super::Texture { + inner: super::TextureInner::Texture { + raw: glow::NativeTexture(name), + target: super::Texture::get_info_from_desc(desc), + }, + drop_guard: crate::DropGuard::from_option(drop_callback), + mip_level_count: desc.mip_level_count, + array_layer_count: desc.array_layer_count(), + format: desc.format, + format_desc: self.shared.describe_texture_format(desc.format), + copy_size: desc.copy_extent(), + } + } + + /// # Safety + /// + /// - `name` must be created respecting `desc` + /// - `name` must be a renderbuffer + /// - If `drop_callback` is [`None`], wgpu-hal will take ownership of the renderbuffer. If + /// `drop_callback` is [`Some`], the renderbuffer must be valid until the callback is called. + #[cfg(any(native, Emscripten))] + pub unsafe fn texture_from_raw_renderbuffer( + &self, + name: NonZeroU32, + desc: &crate::TextureDescriptor, + drop_callback: Option<crate::DropCallback>, + ) -> super::Texture { + super::Texture { + inner: super::TextureInner::Renderbuffer { + raw: glow::NativeRenderbuffer(name), + }, + drop_guard: crate::DropGuard::from_option(drop_callback), + mip_level_count: desc.mip_level_count, + array_layer_count: desc.array_layer_count(), + format: desc.format, + format_desc: self.shared.describe_texture_format(desc.format), + copy_size: desc.copy_extent(), + } + } + + /// # Safety + /// + /// - `name` must be a non-zero GL buffer name created respecting `desc`. + /// - The buffer's storage size must be at least `desc.size`. + /// - If `desc.usage` includes [`BufferUses::MAP_READ`](wgt::BufferUses::MAP_READ) or + /// [`BufferUses::MAP_WRITE`](wgt::BufferUses::MAP_WRITE), the GL buffer must have + /// been allocated with `glBufferStorage` (or equivalent) using flags compatible + /// with persistent mapping (`GL_MAP_PERSISTENT_BIT` plus matching read/write/coherent + /// bits). Buffers created with the legacy `glBufferData` family cannot be mapped + /// through this path. + /// - If `drop_callback` is [`None`], wgpu-hal will take ownership of the buffer and + /// call `glDeleteBuffers` on it. If `drop_callback` is [`Some`], the buffer must + /// remain valid until the callback is invoked. + #[cfg(any(native, Emscripten))] + pub unsafe fn buffer_from_raw( + &self, + name: NonZeroU32, + desc: &crate::BufferDescriptor, + drop_callback: Option<crate::DropCallback>, + ) -> super::Buffer { + let target = if desc.usage.contains(wgt::BufferUses::INDEX) { + glow::ELEMENT_ARRAY_BUFFER + } else { + glow::ARRAY_BUFFER + }; + + let is_host_visible = desc + .usage + .intersects(wgt::BufferUses::MAP_READ | wgt::BufferUses::MAP_WRITE); + let is_coherent = desc + .memory_flags + .contains(crate::MemoryFlags::PREFER_COHERENT); + + let mut map_flags = 0; + if desc.usage.contains(wgt::BufferUses::MAP_READ) { + map_flags |= glow::MAP_READ_BIT; + } + if desc.usage.contains(wgt::BufferUses::MAP_WRITE) { + map_flags |= glow::MAP_WRITE_BIT; + } + if is_host_visible { + map_flags |= glow::MAP_PERSISTENT_BIT; + if is_coherent { + map_flags |= glow::MAP_COHERENT_BIT; + } + } + if !is_coherent && desc.usage.contains(wgt::BufferUses::MAP_WRITE) { + map_flags |= glow::MAP_FLUSH_EXPLICIT_BIT; + } + + self.counters.buffers.add(1); + + super::Buffer { + raw: Some(glow::NativeBuffer(name)), + target, + size: desc.size, + map_flags, + map_state: Arc::new(MaybeMutex::new(super::BufferMapState { + mapped: false, + data: None, + offset_of_current_mapping: 0, + })), + drop_guard: crate::DropGuard::from_option(drop_callback).map(Arc::new), + } + } + + unsafe fn compile_shader( + gl: &glow::Context, + shader: &str, + naga_stage: naga::ShaderStage, + #[cfg_attr(target_arch = "wasm32", allow(unused))] label: Option<&str>, + ) -> Result<glow::Shader, crate::PipelineError> { + let target = match naga_stage { + naga::ShaderStage::Vertex => glow::VERTEX_SHADER, + naga::ShaderStage::Fragment => glow::FRAGMENT_SHADER, + naga::ShaderStage::Compute => glow::COMPUTE_SHADER, + naga::ShaderStage::Task + | naga::ShaderStage::Mesh + | naga::ShaderStage::RayGeneration + | naga::ShaderStage::AnyHit + | naga::ShaderStage::ClosestHit + | naga::ShaderStage::Miss => unreachable!(), + }; + + let raw = unsafe { gl.create_shader(target) }.unwrap(); + #[cfg(native)] + if gl.supports_debug() { + let name = raw.0.get(); + unsafe { gl.object_label(glow::SHADER, name, label) }; + } + + unsafe { gl.shader_source(raw, shader) }; + unsafe { gl.compile_shader(raw) }; + + log::debug!("\tCompiled shader {raw:?}"); + + let compiled_ok = unsafe { gl.get_shader_compile_status(raw) }; + let msg = unsafe { gl.get_shader_info_log(raw) }; + if compiled_ok { + if !msg.is_empty() { + log::debug!("\tCompile message: {msg}"); + } + Ok(raw) + } else { + log::error!("\tShader compilation failed: {msg}"); + unsafe { gl.delete_shader(raw) }; + Err(crate::PipelineError::Linkage( + map_naga_stage(naga_stage), + msg, + )) + } + } + + fn create_shader( + gl: &glow::Context, + naga_stage: naga::ShaderStage, + stage: &crate::ProgrammableStage<super::ShaderModule>, + context: CompilationContext, + program: glow::Program, + ) -> Result<glow::Shader, crate::PipelineError> { + let source = 'outer: { + use naga::back::glsl; + let pipeline_options = glsl::PipelineOptions { + shader_stage: naga_stage, + entry_point: stage.entry_point.to_owned(), + multiview: context + .multiview_mask + .map(|a| NonZeroU32::new(a.get().count_ones()).unwrap()), + }; + + let naga = match stage.module.source { + super::ShaderModuleSource::Naga(ref naga) => naga, + super::ShaderModuleSource::Passthrough { ref source } => { + break 'outer Cow::Borrowed(source); + } + }; + + let (module, info) = naga::back::pipeline_constants::process_overrides( + &naga.module, + &naga.info, + Some((naga_stage, stage.entry_point)), + stage.constants, + ) + .map_err(|e| { + let msg = format!("{e}"); + crate::PipelineError::PipelineConstants(map_naga_stage(naga_stage), msg) + })?; + + let entry_point_index = module + .entry_points + .iter() + .position(|ep| ep.name.as_str() == stage.entry_point) + .ok_or(crate::PipelineError::EntryPoint(naga_stage))?; + + use naga::proc::BoundsCheckPolicy; + // The image bounds checks require the TEXTURE_LEVELS feature available in GL core 4.3+. + let version = gl.version(); + let image_check = if !version.is_embedded && (version.major, version.minor) >= (4, 3) { + BoundsCheckPolicy::ReadZeroSkipWrite + } else { + BoundsCheckPolicy::Unchecked + }; + + // Other bounds check are either provided by glsl or not implemented yet. + let policies = naga::proc::BoundsCheckPolicies { + index: BoundsCheckPolicy::Unchecked, + buffer: BoundsCheckPolicy::Unchecked, + image_load: image_check, + binding_array: BoundsCheckPolicy::Unchecked, + }; + + let mut output = String::new(); + let needs_temp_options = stage.zero_initialize_workgroup_memory + != context.layout.naga_options.zero_initialize_workgroup_memory; + let mut temp_options; + let naga_options = if needs_temp_options { + // We use a conditional here, as cloning the naga_options could be expensive + // That is, we want to avoid doing that unless we cannot avoid it + temp_options = context.layout.naga_options.clone(); + temp_options.zero_initialize_workgroup_memory = + stage.zero_initialize_workgroup_memory; + &temp_options + } else { + &context.layout.naga_options + }; + let mut writer = glsl::Writer::new( + &mut output, + &module, + &info, + naga_options, + &pipeline_options, + policies, + ) + .map_err(|e| { + let msg = format!("{e}"); + crate::PipelineError::Linkage(map_naga_stage(naga_stage), msg) + })?; + + let reflection_info = writer.write().map_err(|e| { + let msg = format!("{e}"); + crate::PipelineError::Linkage(map_naga_stage(naga_stage), msg) + })?; + + log::debug!("Naga generated shader:\n{output}"); + + context.consume_reflection( + gl, + &module, + info.get_entry_point(entry_point_index), + reflection_info, + naga_stage, + program, + ); + Cow::Owned(output) + }; + + unsafe { Self::compile_shader(gl, &source, naga_stage, stage.module.label.as_deref()) } + } + + unsafe fn create_pipeline<'a>( + &self, + gl: &glow::Context, + shaders: ArrayVec<ShaderStage<'a>, { crate::MAX_CONCURRENT_SHADER_STAGES }>, + layout: &super::PipelineLayout, + #[cfg_attr(target_arch = "wasm32", allow(unused))] label: Option<&str>, + multiview_mask: Option<NonZeroU32>, + ) -> Result<Arc<super::PipelineInner>, crate::PipelineError> { + let mut program_stages = ArrayVec::new(); + let group_to_binding_to_slot = layout + .group_infos + .iter() + .map(|group| group.as_ref().map(|group| group.binding_to_slot.clone())) + .collect::<Vec<_>>(); + for &(naga_stage, stage) in &shaders { + program_stages.push(super::ProgramStage { + naga_stage: naga_stage.to_owned(), + shader_id: stage.module.id, + entry_point: stage.entry_point.to_owned(), + zero_initialize_workgroup_memory: stage.zero_initialize_workgroup_memory, + constant_hash: Self::create_constant_hash(stage), + }); + } + let mut guard = self + .shared + .program_cache + .try_lock() + .expect("Couldn't acquire program_cache lock"); + // This guard ensures that we can't accidentally destroy a program whilst we're about to reuse it + // The only place that destroys a pipeline is also locking on `program_cache` + let program = guard + .entry(super::ProgramCacheKey { + stages: program_stages, + group_to_binding_to_slot: group_to_binding_to_slot.into_boxed_slice(), + }) + .or_insert_with(|| unsafe { + Self::create_program( + gl, + shaders, + layout, + label, + multiview_mask, + self.shared.shading_language_version, + self.shared.private_caps, + ) + }) + .to_owned()?; + drop(guard); + + Ok(program) + } + + fn create_constant_hash(stage: &crate::ProgrammableStage<super::ShaderModule>) -> Vec<u8> { + let mut buf: Vec<u8> = Vec::new(); + + for (key, value) in stage.constants.iter() { + buf.extend_from_slice(key.as_bytes()); + buf.extend_from_slice(&value.to_ne_bytes()); + } + + buf + } + + unsafe fn create_program<'a>( + gl: &glow::Context, + shaders: ArrayVec<ShaderStage<'a>, { crate::MAX_CONCURRENT_SHADER_STAGES }>, + layout: &super::PipelineLayout, + #[cfg_attr(target_arch = "wasm32", allow(unused))] label: Option<&str>, + multiview_mask: Option<NonZeroU32>, + glsl_version: naga::back::glsl::Version, + private_caps: PrivateCapabilities, + ) -> Result<Arc<super::PipelineInner>, crate::PipelineError> { + let glsl_version = match glsl_version { + naga::back::glsl::Version::Embedded { version, .. } => format!("{version} es"), + naga::back::glsl::Version::Desktop(version) => format!("{version}"), + }; + let program = unsafe { gl.create_program() }.unwrap(); + #[cfg(native)] + if let Some(label) = label { + if private_caps.contains(PrivateCapabilities::DEBUG_FNS) { + let name = program.0.get(); + unsafe { gl.object_label(glow::PROGRAM, name, Some(label)) }; + } + } + + let mut name_binding_map = NameBindingMap::default(); + let mut immediates_items = ArrayVec::<_, { crate::MAX_CONCURRENT_SHADER_STAGES }>::new(); + let mut sampler_map = [None; super::MAX_TEXTURE_SLOTS]; + let mut has_stages = wgt::ShaderStages::empty(); + let mut shaders_to_delete = ArrayVec::<_, { crate::MAX_CONCURRENT_SHADER_STAGES }>::new(); + let mut clip_distance_count = 0; + + for &(naga_stage, stage) in &shaders { + has_stages |= map_naga_stage(naga_stage); + let pc_item = { + immediates_items.push(Vec::new()); + immediates_items.last_mut().unwrap() + }; + let context = CompilationContext { + layout, + sampler_map: &mut sampler_map, + name_binding_map: &mut name_binding_map, + immediates_items: pc_item, + multiview_mask, + clip_distance_count: &mut clip_distance_count, + }; + + let shader = Self::create_shader(gl, naga_stage, stage, context, program)?; + shaders_to_delete.push(shader); + } + + // Create empty fragment shader if only vertex shader is present + if has_stages == wgt::ShaderStages::VERTEX { + let shader_src = format!("#version {glsl_version}\n void main(void) {{}}",); + log::debug!("Only vertex shader is present. Creating an empty fragment shader",); + let shader = unsafe { + Self::compile_shader( + gl, + &shader_src, + naga::ShaderStage::Fragment, + Some("(wgpu internal) dummy fragment shader"), + ) + }?; + shaders_to_delete.push(shader); + } + + for &shader in shaders_to_delete.iter() { + unsafe { gl.attach_shader(program, shader) }; + } + unsafe { gl.link_program(program) }; + + for shader in shaders_to_delete { + unsafe { gl.delete_shader(shader) }; + } + + log::debug!("\tLinked program {program:?}"); + + let linked_ok = unsafe { gl.get_program_link_status(program) }; + let msg = unsafe { gl.get_program_info_log(program) }; + if !linked_ok { + return Err(crate::PipelineError::Linkage(has_stages, msg)); + } + if !msg.is_empty() { + log::debug!("\tLink message: {msg}"); + } + + if !private_caps.contains(PrivateCapabilities::SHADER_BINDING_LAYOUT) { + // This remapping is only needed if we aren't able to put the binding layout + // in the shader. We can't remap storage buffers this way. + unsafe { gl.use_program(Some(program)) }; + for (ref name, (register, slot)) in name_binding_map { + log::trace!("Get binding {name:?} from program {program:?}"); + match register { + super::BindingRegister::UniformBuffers => { + let index = unsafe { gl.get_uniform_block_index(program, name) }.unwrap(); + log::trace!("\tBinding slot {slot} to block index {index}"); + unsafe { gl.uniform_block_binding(program, index, slot as _) }; + } + super::BindingRegister::StorageBuffers => { + let index = + unsafe { gl.get_shader_storage_block_index(program, name) }.unwrap(); + log::error!("Unable to re-map shader storage block {name} to {index}"); + return Err(crate::DeviceError::Lost.into()); + } + super::BindingRegister::Textures | super::BindingRegister::Images => { + let location = unsafe { gl.get_uniform_location(program, name) }; + unsafe { gl.uniform_1_i32(location.as_ref(), slot as _) }; + } + } + } + } + + let mut uniforms = ArrayVec::new(); + + for stage_items in immediates_items { + for item in stage_items { + let location = unsafe { gl.get_uniform_location(program, &item.access_path) }; + + log::trace!( + "immediate data item: name={}, ty={:?}, offset={}, location={:?}", + item.access_path, + item.ty, + item.offset, + location, + ); + + if let Some(location) = location { + uniforms.push(super::ImmediateDesc { + location, + offset: item.offset, + size_bytes: item.size_bytes, + ty: item.ty, + }); + } + } + } + + let first_instance_location = if has_stages.contains(wgt::ShaderStages::VERTEX) { + // If this returns none (the uniform isn't active), that's fine, we just won't set it. + unsafe { gl.get_uniform_location(program, naga::back::glsl::FIRST_INSTANCE_BINDING) } + } else { + None + }; + + Ok(Arc::new(super::PipelineInner { + program, + sampler_map, + first_instance_location, + immediates_descs: uniforms, + clip_distance_count, + })) + } +} + +impl crate::Device for super::Device { + type A = super::Api; + + unsafe fn create_buffer( + &self, + desc: &crate::BufferDescriptor, + ) -> Result<super::Buffer, crate::DeviceError> { + let target = if desc.usage.contains(wgt::BufferUses::INDEX) { + glow::ELEMENT_ARRAY_BUFFER + } else { + glow::ARRAY_BUFFER + }; + + let emulate_map = self + .shared + .workarounds + .contains(super::Workarounds::EMULATE_BUFFER_MAP) + || !self + .shared + .private_caps + .contains(PrivateCapabilities::BUFFER_ALLOCATION); + + if emulate_map && desc.usage.intersects(wgt::BufferUses::MAP_WRITE) { + return Ok(super::Buffer { + raw: None, + target, + size: desc.size, + map_flags: 0, + map_state: Arc::new(MaybeMutex::new(super::BufferMapState { + mapped: false, + data: Some(vec![0; desc.size as usize]), + offset_of_current_mapping: 0, + })), + drop_guard: None, + }); + } + + let gl = &self.shared.context.lock(); + + let target = if desc.usage.contains(wgt::BufferUses::INDEX) { + glow::ELEMENT_ARRAY_BUFFER + } else { + glow::ARRAY_BUFFER + }; + + let is_host_visible = desc + .usage + .intersects(wgt::BufferUses::MAP_READ | wgt::BufferUses::MAP_WRITE); + let is_coherent = desc + .memory_flags + .contains(crate::MemoryFlags::PREFER_COHERENT); + + let mut map_flags = 0; + if desc.usage.contains(wgt::BufferUses::MAP_READ) { + map_flags |= glow::MAP_READ_BIT; + } + if desc.usage.contains(wgt::BufferUses::MAP_WRITE) { + map_flags |= glow::MAP_WRITE_BIT; + } + + let raw = Some(unsafe { gl.create_buffer() }.map_err(|_| crate::DeviceError::OutOfMemory)?); + unsafe { gl.bind_buffer(target, raw) }; + let raw_size = desc + .size + .try_into() + .map_err(|_| crate::DeviceError::OutOfMemory)?; + + if self + .shared + .private_caps + .contains(PrivateCapabilities::BUFFER_ALLOCATION) + { + if is_host_visible { + map_flags |= glow::MAP_PERSISTENT_BIT; + if is_coherent { + map_flags |= glow::MAP_COHERENT_BIT; + } + } + // TODO: may also be required for other calls involving `buffer_sub_data_u8_slice` (e.g. copy buffer to buffer and clear buffer) + if desc.usage.intersects(wgt::BufferUses::QUERY_RESOLVE) { + map_flags |= glow::DYNAMIC_STORAGE_BIT; + } + unsafe { gl.buffer_storage(target, raw_size, None, map_flags) }; + } else { + assert!(!is_coherent); + let usage = if is_host_visible { + if desc.usage.contains(wgt::BufferUses::MAP_READ) { + glow::STREAM_READ + } else { + glow::DYNAMIC_DRAW + } + } else { + // Even if the usage doesn't contain SRC_READ, we update it internally at least once + // Some vendors take usage very literally and STATIC_DRAW will freeze us with an empty buffer + // https://github.com/gfx-rs/wgpu/issues/3371 + glow::DYNAMIC_DRAW + }; + unsafe { gl.buffer_data_size(target, raw_size, usage) }; + } + + unsafe { gl.bind_buffer(target, None) }; + + if !is_coherent && desc.usage.contains(wgt::BufferUses::MAP_WRITE) { + map_flags |= glow::MAP_FLUSH_EXPLICIT_BIT; + } + //TODO: do we need `glow::MAP_UNSYNCHRONIZED_BIT`? + + #[cfg(native)] + if let Some(label) = desc.label { + if self + .shared + .private_caps + .contains(PrivateCapabilities::DEBUG_FNS) + { + let name = raw.map_or(0, |buf| buf.0.get()); + unsafe { gl.object_label(glow::BUFFER, name, Some(label)) }; + } + } + + let data = if emulate_map && desc.usage.contains(wgt::BufferUses::MAP_READ) { + Some(vec![0; desc.size as usize]) + } else { + None + }; + + self.counters.buffers.add(1); + + Ok(super::Buffer { + raw, + target, + size: desc.size, + map_flags, + map_state: Arc::new(MaybeMutex::new(super::BufferMapState { + mapped: false, + data, + offset_of_current_mapping: 0, + })), + drop_guard: None, + }) + } + + unsafe fn destroy_buffer(&self, buffer: super::Buffer) { + if buffer.drop_guard.is_none() { + if let Some(raw) = buffer.raw { + let gl = &self.shared.context.lock(); + unsafe { gl.delete_buffer(raw) }; + } + } + + // For clarity, we explicitly drop the drop guard. Although this has no real semantic effect as the + // end of the scope will drop the drop guard since this function takes ownership of the buffer. + drop(buffer.drop_guard); + + self.counters.buffers.sub(1); + } + + unsafe fn add_raw_buffer(&self, _buffer: &super::Buffer) { + self.counters.buffers.add(1); + } + + unsafe fn map_buffer( + &self, + buffer: &super::Buffer, + range: crate::MemoryRange, + ) -> Result<crate::BufferMapping, crate::DeviceError> { + let is_coherent = buffer.map_flags & glow::MAP_COHERENT_BIT != 0; + let ptr = match buffer.raw { + None => { + let mut map_state = lock(&buffer.map_state); + let vec = map_state.data.as_mut().unwrap(); + let slice = &mut vec.as_mut_slice()[range.start as usize..range.end as usize]; + slice.as_mut_ptr() + } + Some(raw) => { + let gl = &self.shared.context.lock(); + unsafe { gl.bind_buffer(buffer.target, Some(raw)) }; + let mut map_state = lock(&buffer.map_state); + let ptr = if let Some(map_read_allocation) = map_state.data.as_mut() { + let slice = map_read_allocation.as_mut_slice(); + unsafe { self.shared.get_buffer_sub_data(gl, buffer.target, 0, slice) }; + slice.as_mut_ptr() + } else { + map_state.offset_of_current_mapping = range.start; + // glMapBufferRange throws an error if length is 0. + // We want to allow mapping 0-sized buffer slices, so perform a workaround + // if the range length is 0. The resulting pointer must never be dereferenced. + let range_start: i32 = range + .start + .try_into() + .expect("Buffer range invalid for GLES"); + let range_length: i32 = (range.end - range.start) + .try_into() + .expect("Buffer range invalid for GLES"); + if range_length != 0 { + map_state.mapped = true; + unsafe { + gl.map_buffer_range( + buffer.target, + range_start, + range_length, + buffer.map_flags, + ) + } + } else { + ptr::dangling_mut() + } + }; + unsafe { gl.bind_buffer(buffer.target, None) }; + ptr + } + }; + Ok(crate::BufferMapping { + ptr: ptr::NonNull::new(ptr).ok_or(crate::DeviceError::Lost)?, + is_coherent, + }) + } + unsafe fn unmap_buffer(&self, buffer: &super::Buffer) { + let gl = &self.shared.context.lock(); + let mut map_state = lock(&buffer.map_state); + if core::mem::replace(&mut map_state.mapped, false) { + if let Some(raw) = buffer.raw { + if map_state.data.is_none() { + unsafe { gl.bind_buffer(buffer.target, Some(raw)) }; + unsafe { gl.unmap_buffer(buffer.target) }; + unsafe { gl.bind_buffer(buffer.target, None) }; + map_state.offset_of_current_mapping = 0; + } + } + } + } + unsafe fn flush_mapped_ranges<I>(&self, buffer: &super::Buffer, ranges: I) + where + I: Iterator<Item = crate::MemoryRange>, + { + let gl = &self.shared.context.lock(); + let map_state = lock(&buffer.map_state); + if map_state.mapped { + if let Some(raw) = buffer.raw { + if map_state.data.is_none() { + unsafe { gl.bind_buffer(buffer.target, Some(raw)) }; + for range in ranges { + let offset_of_current_mapping = map_state.offset_of_current_mapping; + unsafe { + gl.flush_mapped_buffer_range( + buffer.target, + (range.start - offset_of_current_mapping) as i32, + (range.end - range.start) as i32, + ) + }; + } + } + } + } + } + unsafe fn invalidate_mapped_ranges<I>(&self, _buffer: &super::Buffer, _ranges: I) { + //TODO: do we need to do anything? + } + + unsafe fn create_texture( + &self, + desc: &crate::TextureDescriptor, + ) -> Result<super::Texture, crate::DeviceError> { + let gl = &self.shared.context.lock(); + + let render_usage = wgt::TextureUses::COLOR_TARGET + | wgt::TextureUses::DEPTH_STENCIL_WRITE + | wgt::TextureUses::DEPTH_STENCIL_READ + | wgt::TextureUses::TRANSIENT; + let format_desc = self.shared.describe_texture_format(desc.format); + + let inner = if render_usage.contains(desc.usage) + && desc.dimension == wgt::TextureDimension::D2 + && desc.size.depth_or_array_layers == 1 + { + let raw = unsafe { gl.create_renderbuffer().unwrap() }; + unsafe { gl.bind_renderbuffer(glow::RENDERBUFFER, Some(raw)) }; + if desc.sample_count > 1 { + unsafe { + gl.renderbuffer_storage_multisample( + glow::RENDERBUFFER, + desc.sample_count as i32, + format_desc.internal, + desc.size.width as i32, + desc.size.height as i32, + ) + }; + } else { + unsafe { + gl.renderbuffer_storage( + glow::RENDERBUFFER, + format_desc.internal, + desc.size.width as i32, + desc.size.height as i32, + ) + }; + } + + #[cfg(native)] + if let Some(label) = desc.label { + if self + .shared + .private_caps + .contains(PrivateCapabilities::DEBUG_FNS) + { + let name = raw.0.get(); + unsafe { gl.object_label(glow::RENDERBUFFER, name, Some(label)) }; + } + } + + unsafe { gl.bind_renderbuffer(glow::RENDERBUFFER, None) }; + super::TextureInner::Renderbuffer { raw } + } else { + let raw = unsafe { gl.create_texture().unwrap() }; + let target = super::Texture::get_info_from_desc(desc); + + unsafe { gl.bind_texture(target, Some(raw)) }; + //Note: this has to be done before defining the storage! + match desc.format.sample_type(None, Some(self.shared.features)) { + Some( + wgt::TextureSampleType::Float { filterable: false } + | wgt::TextureSampleType::Uint + | wgt::TextureSampleType::Sint, + ) => { + // reset default filtering mode + unsafe { + gl.tex_parameter_i32(target, glow::TEXTURE_MIN_FILTER, glow::NEAREST as i32) + }; + unsafe { + gl.tex_parameter_i32(target, glow::TEXTURE_MAG_FILTER, glow::NEAREST as i32) + }; + } + _ => {} + } + + if conv::is_layered_target(target) { + unsafe { + if self + .shared + .private_caps + .contains(PrivateCapabilities::TEXTURE_STORAGE) + { + gl.tex_storage_3d( + target, + desc.mip_level_count as i32, + format_desc.internal, + desc.size.width as i32, + desc.size.height as i32, + desc.size.depth_or_array_layers as i32, + ) + } else if target == glow::TEXTURE_3D { + let mut width = desc.size.width; + let mut height = desc.size.height; + let mut depth = desc.size.depth_or_array_layers; + for i in 0..desc.mip_level_count { + gl.tex_image_3d( + target, + i as i32, + format_desc.internal as i32, + width as i32, + height as i32, + depth as i32, + 0, + format_desc.external, + format_desc.data_type, + glow::PixelUnpackData::Slice(None), + ); + width = max(1, width / 2); + height = max(1, height / 2); + depth = max(1, depth / 2); + } + } else { + let mut width = desc.size.width; + let mut height = desc.size.height; + for i in 0..desc.mip_level_count { + gl.tex_image_3d( + target, + i as i32, + format_desc.internal as i32, + width as i32, + height as i32, + desc.size.depth_or_array_layers as i32, + 0, + format_desc.external, + format_desc.data_type, + glow::PixelUnpackData::Slice(None), + ); + width = max(1, width / 2); + height = max(1, height / 2); + } + } + }; + } else if desc.sample_count > 1 { + unsafe { + gl.tex_storage_2d_multisample( + target, + desc.sample_count as i32, + format_desc.internal, + desc.size.width as i32, + desc.size.height as i32, + true, + ) + }; + } else { + unsafe { + if self + .shared + .private_caps + .contains(PrivateCapabilities::TEXTURE_STORAGE) + { + gl.tex_storage_2d( + target, + desc.mip_level_count as i32, + format_desc.internal, + desc.size.width as i32, + desc.size.height as i32, + ) + } else if target == glow::TEXTURE_CUBE_MAP { + let mut width = desc.size.width; + let mut height = desc.size.height; + for i in 0..desc.mip_level_count { + for face in [ + glow::TEXTURE_CUBE_MAP_POSITIVE_X, + glow::TEXTURE_CUBE_MAP_NEGATIVE_X, + glow::TEXTURE_CUBE_MAP_POSITIVE_Y, + glow::TEXTURE_CUBE_MAP_NEGATIVE_Y, + glow::TEXTURE_CUBE_MAP_POSITIVE_Z, + glow::TEXTURE_CUBE_MAP_NEGATIVE_Z, + ] { + gl.tex_image_2d( + face, + i as i32, + format_desc.internal as i32, + width as i32, + height as i32, + 0, + format_desc.external, + format_desc.data_type, + glow::PixelUnpackData::Slice(None), + ); + } + width = max(1, width / 2); + height = max(1, height / 2); + } + } else { + let mut width = desc.size.width; + let mut height = desc.size.height; + for i in 0..desc.mip_level_count { + gl.tex_image_2d( + target, + i as i32, + format_desc.internal as i32, + width as i32, + height as i32, + 0, + format_desc.external, + format_desc.data_type, + glow::PixelUnpackData::Slice(None), + ); + width = max(1, width / 2); + height = max(1, height / 2); + } + } + }; + } + + #[cfg(native)] + if let Some(label) = desc.label { + if self + .shared + .private_caps + .contains(PrivateCapabilities::DEBUG_FNS) + { + let name = raw.0.get(); + unsafe { gl.object_label(glow::TEXTURE, name, Some(label)) }; + } + } + + unsafe { gl.bind_texture(target, None) }; + super::TextureInner::Texture { raw, target } + }; + + self.counters.textures.add(1); + + Ok(super::Texture { + inner, + drop_guard: None, + mip_level_count: desc.mip_level_count, + array_layer_count: desc.array_layer_count(), + format: desc.format, + format_desc, + copy_size: desc.copy_extent(), + }) + } + + unsafe fn destroy_texture(&self, texture: super::Texture) { + if texture.drop_guard.is_none() { + let gl = &self.shared.context.lock(); + match texture.inner { + super::TextureInner::Renderbuffer { raw, .. } => { + unsafe { gl.delete_renderbuffer(raw) }; + } + super::TextureInner::DefaultRenderbuffer => {} + super::TextureInner::Texture { raw, .. } => { + unsafe { gl.delete_texture(raw) }; + } + #[cfg(webgl)] + super::TextureInner::ExternalFramebuffer { .. } => {} + #[cfg(native)] + super::TextureInner::ExternalNativeFramebuffer { .. } => {} + } + } + + // For clarity, we explicitly drop the drop guard. Although this has no real semantic effect as the + // end of the scope will drop the drop guard since this function takes ownership of the texture. + drop(texture.drop_guard); + + self.counters.textures.sub(1); + } + + unsafe fn add_raw_texture(&self, _texture: &super::Texture) { + self.counters.textures.add(1); + } + + unsafe fn create_texture_view( + &self, + texture: &super::Texture, + desc: &crate::TextureViewDescriptor, + ) -> Result<super::TextureView, crate::DeviceError> { + self.counters.texture_views.add(1); + Ok(super::TextureView { + //TODO: use `conv::map_view_dimension(desc.dimension)`? + inner: texture.inner.clone(), + aspects: crate::FormatAspects::new(texture.format, desc.range.aspect), + mip_levels: desc.range.mip_range(texture.mip_level_count), + array_layers: desc.range.layer_range(texture.array_layer_count), + format: texture.format, + }) + } + + unsafe fn destroy_texture_view(&self, _view: super::TextureView) { + self.counters.texture_views.sub(1); + } + + unsafe fn create_sampler( + &self, + desc: &crate::SamplerDescriptor, + ) -> Result<super::Sampler, crate::DeviceError> { + let gl = &self.shared.context.lock(); + + let raw = unsafe { gl.create_sampler().unwrap() }; + + let (min, mag) = + conv::map_filter_modes(desc.min_filter, desc.mag_filter, desc.mipmap_filter); + + unsafe { gl.sampler_parameter_i32(raw, glow::TEXTURE_MIN_FILTER, min as i32) }; + unsafe { gl.sampler_parameter_i32(raw, glow::TEXTURE_MAG_FILTER, mag as i32) }; + + unsafe { + gl.sampler_parameter_i32( + raw, + glow::TEXTURE_WRAP_S, + conv::map_address_mode(desc.address_modes[0]) as i32, + ) + }; + unsafe { + gl.sampler_parameter_i32( + raw, + glow::TEXTURE_WRAP_T, + conv::map_address_mode(desc.address_modes[1]) as i32, + ) + }; + unsafe { + gl.sampler_parameter_i32( + raw, + glow::TEXTURE_WRAP_R, + conv::map_address_mode(desc.address_modes[2]) as i32, + ) + }; + + if let Some(border_color) = desc.border_color { + let border = match border_color { + wgt::SamplerBorderColor::TransparentBlack | wgt::SamplerBorderColor::Zero => { + [0.0; 4] + } + wgt::SamplerBorderColor::OpaqueBlack => [0.0, 0.0, 0.0, 1.0], + wgt::SamplerBorderColor::OpaqueWhite => [1.0; 4], + }; + unsafe { gl.sampler_parameter_f32_slice(raw, glow::TEXTURE_BORDER_COLOR, &border) }; + } + + unsafe { gl.sampler_parameter_f32(raw, glow::TEXTURE_MIN_LOD, desc.lod_clamp.start) }; + unsafe { gl.sampler_parameter_f32(raw, glow::TEXTURE_MAX_LOD, desc.lod_clamp.end) }; + + // If clamp is not 1, we know anisotropy is supported up to 16x + if desc.anisotropy_clamp != 1 { + unsafe { + gl.sampler_parameter_i32( + raw, + glow::TEXTURE_MAX_ANISOTROPY, + desc.anisotropy_clamp as i32, + ) + }; + } + + //set_param_float(glow::TEXTURE_LOD_BIAS, info.lod_bias.0); + + if let Some(compare) = desc.compare { + unsafe { + gl.sampler_parameter_i32( + raw, + glow::TEXTURE_COMPARE_MODE, + glow::COMPARE_REF_TO_TEXTURE as i32, + ) + }; + unsafe { + gl.sampler_parameter_i32( + raw, + glow::TEXTURE_COMPARE_FUNC, + conv::map_compare_func(compare) as i32, + ) + }; + } + + #[cfg(native)] + if let Some(label) = desc.label { + if self + .shared + .private_caps + .contains(PrivateCapabilities::DEBUG_FNS) + { + let name = raw.0.get(); + unsafe { gl.object_label(glow::SAMPLER, name, Some(label)) }; + } + } + + self.counters.samplers.add(1); + + Ok(super::Sampler { raw }) + } + + unsafe fn destroy_sampler(&self, sampler: super::Sampler) { + let gl = &self.shared.context.lock(); + unsafe { gl.delete_sampler(sampler.raw) }; + self.counters.samplers.sub(1); + } + + unsafe fn create_command_encoder( + &self, + _desc: &crate::CommandEncoderDescriptor<super::Queue>, + ) -> Result<super::CommandEncoder, crate::DeviceError> { + self.counters.command_encoders.add(1); + + Ok(super::CommandEncoder { + cmd_buffer: super::CommandBuffer::default(), + state: Default::default(), + private_caps: self.shared.private_caps, + counters: Arc::clone(&self.counters), + }) + } + + unsafe fn create_bind_group_layout( + &self, + desc: &crate::BindGroupLayoutDescriptor, + ) -> Result<super::BindGroupLayout, crate::DeviceError> { + self.counters.bind_group_layouts.add(1); + Ok(super::BindGroupLayout { + entries: Arc::from(desc.entries), + }) + } + + unsafe fn destroy_bind_group_layout(&self, _bg_layout: super::BindGroupLayout) { + self.counters.bind_group_layouts.sub(1); + } + + unsafe fn create_pipeline_layout( + &self, + desc: &crate::PipelineLayoutDescriptor<super::BindGroupLayout>, + ) -> Result<super::PipelineLayout, crate::DeviceError> { + use naga::back::glsl; + + let mut group_infos = Vec::with_capacity(desc.bind_group_layouts.len()); + let mut num_samplers = 0u8; + let mut num_textures = 0u8; + let mut num_images = 0u8; + let mut num_uniform_buffers = 0u8; + let mut num_storage_buffers = 0u8; + + let mut writer_flags = glsl::WriterFlags::ADJUST_COORDINATE_SPACE; + writer_flags.set( + glsl::WriterFlags::TEXTURE_SHADOW_LOD, + self.shared + .private_caps + .contains(PrivateCapabilities::SHADER_TEXTURE_SHADOW_LOD), + ); + writer_flags.set( + glsl::WriterFlags::DRAW_PARAMETERS, + self.shared + .private_caps + .contains(PrivateCapabilities::FULLY_FEATURED_INSTANCING), + ); + // We always force point size to be written and it will be ignored by the driver if it's not a point list primitive. + // https://github.com/gfx-rs/wgpu/pull/3440/files#r1095726950 + writer_flags.set(glsl::WriterFlags::FORCE_POINT_SIZE, true); + let mut binding_map = glsl::BindingMap::default(); + + for (group_index, bg_layout) in desc.bind_group_layouts.iter().enumerate() { + let Some(bg_layout) = bg_layout else { + group_infos.push(None); + continue; + }; + + // create a vector with the size enough to hold all the bindings, filled with `!0` + let mut binding_to_slot = vec![ + !0; + bg_layout + .entries + .iter() + .map(|b| b.binding) + .max() + .map_or(0, |idx| idx as usize + 1) + ] + .into_boxed_slice(); + + for entry in bg_layout.entries.iter() { + let counter = match entry.ty { + wgt::BindingType::Sampler { .. } => &mut num_samplers, + wgt::BindingType::Texture { .. } => &mut num_textures, + wgt::BindingType::StorageTexture { .. } => &mut num_images, + wgt::BindingType::Buffer { + ty: wgt::BufferBindingType::Uniform, + .. + } => &mut num_uniform_buffers, + wgt::BindingType::Buffer { + ty: wgt::BufferBindingType::Storage { .. }, + .. + } => &mut num_storage_buffers, + wgt::BindingType::AccelerationStructure { .. } => unimplemented!(), + wgt::BindingType::ExternalTexture => unimplemented!(), + }; + + binding_to_slot[entry.binding as usize] = *counter; + let br = naga::ResourceBinding { + group: group_index as u32, + binding: entry.binding, + }; + binding_map.insert(br, *counter); + *counter += entry.count.map_or(1, |c| c.get() as u8); + } + + group_infos.push(Some(super::BindGroupLayoutInfo { + entries: Arc::clone(&bg_layout.entries), + binding_to_slot, + })); + } + + self.counters.pipeline_layouts.add(1); + + Ok(super::PipelineLayout { + group_infos: group_infos.into_boxed_slice(), + naga_options: glsl::Options { + version: self.shared.shading_language_version, + writer_flags, + binding_map, + zero_initialize_workgroup_memory: true, + }, + }) + } + + unsafe fn destroy_pipeline_layout(&self, _pipeline_layout: super::PipelineLayout) { + self.counters.pipeline_layouts.sub(1); + } + + unsafe fn create_bind_group( + &self, + desc: &crate::BindGroupDescriptor< + super::BindGroupLayout, + super::Buffer, + super::Sampler, + super::TextureView, + super::AccelerationStructure, + >, + ) -> Result<super::BindGroup, crate::DeviceError> { + let mut contents = Vec::new(); + + let layout_and_entry_iter = desc.entries.iter().map(|entry| { + let layout = desc + .layout + .entries + .iter() + .find(|layout_entry| layout_entry.binding == entry.binding) + .expect("internal error: no layout entry found with binding slot"); + (entry, layout) + }); + for (entry, layout) in layout_and_entry_iter { + let binding = match layout.ty { + wgt::BindingType::Buffer { .. } => { + let bb = &desc.buffers[entry.resource_index as usize]; + super::RawBinding::Buffer { + raw: bb.buffer.raw.unwrap(), + offset: bb.offset as i32, + size: match bb.size { + Some(s) => s.get() as i32, + None => (bb.buffer.size - bb.offset) as i32, + }, + } + } + wgt::BindingType::Sampler { .. } => { + let sampler = desc.samplers[entry.resource_index as usize]; + super::RawBinding::Sampler(sampler.raw) + } + wgt::BindingType::Texture { view_dimension, .. } => { + let view = desc.textures[entry.resource_index as usize].view; + if view.array_layers.start != 0 { + log::error!("Unable to create a sampled texture binding for non-zero array layer.\n{}", + "This is an implementation problem of wgpu-hal/gles backend.") + } + let (raw, target) = view.inner.as_native(); + + super::Texture::log_failing_target_heuristics(view_dimension, target); + + super::RawBinding::Texture { + raw, + target, + aspects: view.aspects, + mip_levels: view.mip_levels.clone(), + } + } + wgt::BindingType::StorageTexture { + access, + format, + view_dimension, + } => { + let view = desc.textures[entry.resource_index as usize].view; + let format_desc = self.shared.describe_texture_format(format); + let (raw, _target) = view.inner.as_native(); + super::RawBinding::Image(super::ImageBinding { + raw, + mip_level: view.mip_levels.start, + array_layer: match view_dimension { + wgt::TextureViewDimension::D2Array + | wgt::TextureViewDimension::CubeArray => None, + _ => Some(view.array_layers.start), + }, + access: conv::map_storage_access(access), + format: format_desc.internal, + }) + } + wgt::BindingType::AccelerationStructure { .. } => unimplemented!(), + wgt::BindingType::ExternalTexture => unimplemented!(), + }; + contents.push(binding); + } + + self.counters.bind_groups.add(1); + + Ok(super::BindGroup { + contents: contents.into_boxed_slice(), + }) + } + + unsafe fn destroy_bind_group(&self, _group: super::BindGroup) { + self.counters.bind_groups.sub(1); + } + + unsafe fn create_shader_module( + &self, + desc: &crate::ShaderModuleDescriptor, + shader: crate::ShaderInput, + ) -> Result<super::ShaderModule, crate::ShaderError> { + self.counters.shader_modules.add(1); + + Ok(super::ShaderModule { + source: match shader { + crate::ShaderInput::Naga(naga) => super::ShaderModuleSource::Naga(naga), + // The backend doesn't yet expose this feature so it should be fine + crate::ShaderInput::Glsl { shader, .. } => super::ShaderModuleSource::Passthrough { + source: shader.to_owned(), + }, + crate::ShaderInput::SpirV(_) + | crate::ShaderInput::MetalLib { .. } + | crate::ShaderInput::Msl { .. } + | crate::ShaderInput::Dxil { .. } + | crate::ShaderInput::Hlsl { .. } => { + unreachable!() + } + }, + label: desc.label.map(|str| str.to_string()), + id: self.shared.next_shader_id.fetch_add(1, Ordering::Relaxed), + }) + } + + unsafe fn destroy_shader_module(&self, _module: super::ShaderModule) { + self.counters.shader_modules.sub(1); + } + + unsafe fn create_render_pipeline( + &self, + desc: &crate::RenderPipelineDescriptor< + super::PipelineLayout, + super::ShaderModule, + super::PipelineCache, + >, + ) -> Result<super::RenderPipeline, crate::PipelineError> { + let (vertex_stage, vertex_buffers) = match &desc.vertex_processor { + crate::VertexProcessor::Standard { + vertex_buffers, + ref vertex_stage, + } => (vertex_stage, vertex_buffers), + crate::VertexProcessor::Mesh { .. } => unreachable!(), + }; + let gl = &self.shared.context.lock(); + let mut shaders = ArrayVec::new(); + shaders.push((naga::ShaderStage::Vertex, vertex_stage)); + if let Some(ref fs) = desc.fragment_stage { + shaders.push((naga::ShaderStage::Fragment, fs)); + } + let inner = unsafe { + self.create_pipeline(gl, shaders, desc.layout, desc.label, desc.multiview_mask) + }?; + + let (vertex_buffers, vertex_attributes) = { + let mut buffers = Vec::new(); + let mut attributes = Vec::new(); + for (index, vb_layout) in vertex_buffers.iter().enumerate() { + let vb_desc = if let Some(vb_layout) = vb_layout { + for vat in vb_layout.attributes.iter() { + let format_desc = conv::describe_vertex_format(vat.format); + attributes.push(super::AttributeDesc { + location: vat.shader_location, + offset: vat.offset as u32, + buffer_index: index as u32, + format_desc, + }); + } + Some(super::VertexBufferDesc { + step: vb_layout.step_mode, + stride: vb_layout.array_stride as u32, + }) + } else { + None + }; + buffers.push(vb_desc); + } + (buffers.into_boxed_slice(), attributes.into_boxed_slice()) + }; + + let color_targets = { + let mut targets = Vec::new(); + for ct in desc.color_targets.iter().filter_map(|at| at.as_ref()) { + targets.push(super::ColorTargetDesc { + mask: ct.write_mask, + blend: ct.blend.as_ref().map(conv::map_blend), + }); + } + //Note: if any of the states are different, and `INDEPENDENT_BLEND` flag + // is not exposed, then this pipeline will not bind correctly. + targets.into_boxed_slice() + }; + + self.counters.render_pipelines.add(1); + + Ok(super::RenderPipeline { + inner, + primitive: desc.primitive, + vertex_buffers, + vertex_attributes, + color_targets, + depth: desc.depth_stencil.as_ref().map(|ds| super::DepthState { + function: conv::map_compare_func(ds.depth_compare.unwrap_or_default()), + mask: ds.depth_write_enabled.unwrap_or_default(), + }), + depth_bias: desc + .depth_stencil + .as_ref() + .map(|ds| ds.bias) + .unwrap_or_default(), + stencil: desc + .depth_stencil + .as_ref() + .map(|ds| conv::map_stencil(&ds.stencil)), + alpha_to_coverage_enabled: desc.multisample.alpha_to_coverage_enabled, + }) + } + + unsafe fn destroy_render_pipeline(&self, pipeline: super::RenderPipeline) { + // If the pipeline only has 2 strong references remaining, they're `pipeline` and `program_cache` + // This is safe to assume as long as: + // - `RenderPipeline` can't be cloned + // - The only place that we can get a new reference is during `program_cache.lock()` + if Arc::strong_count(&pipeline.inner) == 2 { + let gl = &self.shared.context.lock(); + let mut program_cache = self.shared.program_cache.lock(); + program_cache.retain(|_, v| match *v { + Ok(ref p) => p.program != pipeline.inner.program, + Err(_) => false, + }); + unsafe { gl.delete_program(pipeline.inner.program) }; + } + + self.counters.render_pipelines.sub(1); + } + + unsafe fn create_compute_pipeline( + &self, + desc: &crate::ComputePipelineDescriptor< + super::PipelineLayout, + super::ShaderModule, + super::PipelineCache, + >, + ) -> Result<super::ComputePipeline, crate::PipelineError> { + let gl = &self.shared.context.lock(); + let mut shaders = ArrayVec::new(); + shaders.push((naga::ShaderStage::Compute, &desc.stage)); + let inner = unsafe { self.create_pipeline(gl, shaders, desc.layout, desc.label, None) }?; + + self.counters.compute_pipelines.add(1); + + Ok(super::ComputePipeline { inner }) + } + + unsafe fn destroy_compute_pipeline(&self, pipeline: super::ComputePipeline) { + // If the pipeline only has 2 strong references remaining, they're `pipeline` and `program_cache`` + // This is safe to assume as long as: + // - `ComputePipeline` can't be cloned + // - The only place that we can get a new reference is during `program_cache.lock()` + if Arc::strong_count(&pipeline.inner) == 2 { + let gl = &self.shared.context.lock(); + let mut program_cache = self.shared.program_cache.lock(); + program_cache.retain(|_, v| match *v { + Ok(ref p) => p.program != pipeline.inner.program, + Err(_) => false, + }); + unsafe { gl.delete_program(pipeline.inner.program) }; + } + + self.counters.compute_pipelines.sub(1); + } + + unsafe fn create_ray_tracing_pipeline( + &self, + _desc: &crate::RayTracingPipelineDescriptor< + super::PipelineLayout, + super::ShaderModule, + super::PipelineCache, + >, + ) -> Result<super::RayTracingPipeline, crate::PipelineError> { + unimplemented!("Ray tracing is unsupported on GL") + } + + unsafe fn destroy_ray_tracing_pipeline(&self, _pipeline: super::RayTracingPipeline) { + unimplemented!("Ray tracing is unsupported on GL") + } + + unsafe fn get_raytracing_pipeline_group_data( + &self, + _pipeline: &super::RayTracingPipeline, + _groups: core::ops::Range<u32>, + ) -> Result<Vec<u8>, crate::DeviceError> { + unimplemented!("Ray tracing is unsupported on GL") + } + + unsafe fn create_pipeline_cache( + &self, + _: &crate::PipelineCacheDescriptor<'_>, + ) -> Result<super::PipelineCache, crate::PipelineCacheError> { + // Even though the cache doesn't do anything, we still return something here + // as the least bad option + Ok(super::PipelineCache) + } + unsafe fn destroy_pipeline_cache(&self, _: super::PipelineCache) {} + + #[cfg_attr(target_arch = "wasm32", allow(unused))] + unsafe fn create_query_set( + &self, + desc: &wgt::QuerySetDescriptor<crate::Label>, + ) -> Result<super::QuerySet, crate::DeviceError> { + let gl = &self.shared.context.lock(); + + let mut queries = Vec::with_capacity(desc.count as usize); + for _ in 0..desc.count { + let query = + unsafe { gl.create_query() }.map_err(|_| crate::DeviceError::OutOfMemory)?; + + // We aren't really able to, in general, label queries. + // + // We could take a timestamp here to "initialize" the query, + // but that's a bit of a hack, and we don't want to insert + // random timestamps into the command stream of we don't have to. + + queries.push(query); + } + + self.counters.query_sets.add(1); + + Ok(super::QuerySet { + queries: queries.into_boxed_slice(), + target: match desc.ty { + wgt::QueryType::Occlusion => glow::ANY_SAMPLES_PASSED_CONSERVATIVE, + wgt::QueryType::Timestamp => glow::TIMESTAMP, + _ => unimplemented!(), + }, + }) + } + + unsafe fn destroy_query_set(&self, set: super::QuerySet) { + let gl = &self.shared.context.lock(); + for &query in set.queries.iter() { + unsafe { gl.delete_query(query) }; + } + self.counters.query_sets.sub(1); + } + + unsafe fn create_fence(&self) -> Result<super::Fence, crate::DeviceError> { + self.counters.fences.add(1); + Ok(super::Fence::new(&self.shared.options)) + } + + unsafe fn destroy_fence(&self, fence: super::Fence) { + let gl = &self.shared.context.lock(); + fence.destroy(gl); + self.counters.fences.sub(1); + } + + unsafe fn get_fence_value( + &self, + fence: &super::Fence, + ) -> Result<crate::FenceValue, crate::DeviceError> { + #[cfg_attr(target_arch = "wasm32", allow(clippy::needless_borrow))] + Ok(fence.get_latest(&self.shared.context.lock())) + } + unsafe fn wait( + &self, + fence: &super::Fence, + wait_value: crate::FenceValue, + timeout: Option<core::time::Duration>, + ) -> Result<bool, crate::DeviceError> { + if fence.satisfied(wait_value) { + return Ok(true); + } + + let gl = &self.shared.context.lock(); + // MAX_CLIENT_WAIT_TIMEOUT_WEBGL is: + // - 1s in Gecko https://searchfox.org/mozilla-central/rev/754074e05178e017ef6c3d8e30428ffa8f1b794d/dom/canvas/WebGLTypes.h#1386 + // - 0 in WebKit https://github.com/WebKit/WebKit/blob/4ef90d4672ca50267c0971b85db403d9684508ea/Source/WebCore/html/canvas/WebGL2RenderingContext.cpp#L110 + // - 0 in Chromium https://source.chromium.org/chromium/chromium/src/+/main:third_party/blink/renderer/modules/webgl/webgl2_rendering_context_base.cc;l=112;drc=a3cb0ac4c71ec04abfeaed199e5d63230eca2551 + let timeout_ns = if cfg!(any(webgl, Emscripten)) { + 0 + } else { + timeout + .map(|t| t.as_nanos().min(u32::MAX as u128) as u32) + .unwrap_or(u32::MAX) + }; + fence.wait(gl, wait_value, timeout_ns) + } + + unsafe fn start_graphics_debugger_capture(&self) -> bool { + #[cfg(all(native, feature = "renderdoc"))] + return unsafe { + self.render_doc + .start_frame_capture(self.shared.context.raw_context(), ptr::null_mut()) + }; + #[allow(unreachable_code)] + false + } + unsafe fn stop_graphics_debugger_capture(&self) { + #[cfg(all(native, feature = "renderdoc"))] + unsafe { + self.render_doc + .end_frame_capture(ptr::null_mut(), ptr::null_mut()) + } + } + unsafe fn create_acceleration_structure( + &self, + _desc: &crate::AccelerationStructureDescriptor, + ) -> Result<super::AccelerationStructure, crate::DeviceError> { + unimplemented!() + } + unsafe fn get_acceleration_structure_build_sizes<'a>( + &self, + _desc: &crate::GetAccelerationStructureBuildSizesDescriptor<'a, super::Buffer>, + ) -> crate::AccelerationStructureBuildSizes { + unimplemented!() + } + unsafe fn get_acceleration_structure_device_address( + &self, + _acceleration_structure: &super::AccelerationStructure, + ) -> wgt::BufferAddress { + unimplemented!() + } + unsafe fn destroy_acceleration_structure( + &self, + _acceleration_structure: super::AccelerationStructure, + ) { + } + + fn tlas_instance_to_bytes(&self, _instance: TlasInstance) -> Vec<u8> { + unimplemented!() + } + + fn get_internal_counters(&self) -> wgt::HalCounters { + self.counters.as_ref().clone() + } + + fn check_if_oom(&self) -> Result<(), crate::DeviceError> { + Ok(()) + } +} + +#[cfg(send_sync)] +unsafe impl Sync for super::Device {} +#[cfg(send_sync)] +unsafe impl Send for super::Device {} diff --git a/app/vendor/rune/vendor/wgpu-hal/src/gles/egl.rs b/app/vendor/rune/vendor/wgpu-hal/src/gles/egl.rs new file mode 100644 index 0000000..eeb7369 --- /dev/null +++ b/app/vendor/rune/vendor/wgpu-hal/src/gles/egl.rs @@ -0,0 +1,1470 @@ +use alloc::{string::String, sync::Arc, vec::Vec}; +use core::{ffi, mem::ManuallyDrop, ptr, time::Duration}; +use std::sync::LazyLock; + +use glow::HasContext; +use hashbrown::HashMap; +use parking_lot::{MappedMutexGuard, Mutex, MutexGuard, RwLock}; + +/// The amount of time to wait while trying to obtain a lock to the adapter context +const CONTEXT_LOCK_TIMEOUT_SECS: u64 = 6; + +const EGL_CONTEXT_FLAGS_KHR: i32 = 0x30FC; +const EGL_CONTEXT_OPENGL_DEBUG_BIT_KHR: i32 = 0x0001; +const EGL_CONTEXT_OPENGL_ROBUST_ACCESS_EXT: i32 = 0x30BF; +const EGL_PLATFORM_WAYLAND_KHR: u32 = 0x31D8; +const EGL_PLATFORM_X11_KHR: u32 = 0x31D5; +const EGL_PLATFORM_XCB_EXT: u32 = 0x31DC; +const EGL_PLATFORM_XCB_SCREEN_EXT: u32 = 0x31DE; +const EGL_PLATFORM_ANGLE_ANGLE: u32 = 0x3202; +const EGL_PLATFORM_ANGLE_NATIVE_PLATFORM_TYPE_ANGLE: u32 = 0x348F; +const EGL_PLATFORM_ANGLE_DEBUG_LAYERS_ENABLED: u32 = 0x3451; +const EGL_PLATFORM_SURFACELESS_MESA: u32 = 0x31DD; +const EGL_GL_COLORSPACE_KHR: u32 = 0x309D; +const EGL_GL_COLORSPACE_SRGB_KHR: u32 = 0x3089; + +#[cfg(not(Emscripten))] +type EglInstance = khronos_egl::DynamicInstance<khronos_egl::EGL1_4>; + +#[cfg(Emscripten)] +type EglInstance = khronos_egl::Instance<khronos_egl::Static>; + +type EglLabel = *const ffi::c_void; + +#[allow(clippy::upper_case_acronyms)] +type EGLDEBUGPROCKHR = Option< + unsafe extern "system" fn( + error: khronos_egl::Enum, + command: *const ffi::c_char, + message_type: u32, + thread_label: EglLabel, + object_label: EglLabel, + message: *const ffi::c_char, + ), +>; + +const EGL_DEBUG_MSG_CRITICAL_KHR: u32 = 0x33B9; +const EGL_DEBUG_MSG_ERROR_KHR: u32 = 0x33BA; +const EGL_DEBUG_MSG_WARN_KHR: u32 = 0x33BB; +const EGL_DEBUG_MSG_INFO_KHR: u32 = 0x33BC; + +type EglDebugMessageControlFun = unsafe extern "system" fn( + proc: EGLDEBUGPROCKHR, + attrib_list: *const khronos_egl::Attrib, +) -> ffi::c_int; + +unsafe extern "system" fn egl_debug_proc( + error: khronos_egl::Enum, + command_raw: *const ffi::c_char, + message_type: u32, + _thread_label: EglLabel, + _object_label: EglLabel, + message_raw: *const ffi::c_char, +) { + let log_severity = match message_type { + EGL_DEBUG_MSG_CRITICAL_KHR | EGL_DEBUG_MSG_ERROR_KHR => log::Level::Error, + EGL_DEBUG_MSG_WARN_KHR => log::Level::Warn, + // We intentionally suppress info messages down to debug + // so that users are not inundated with info messages from + // the runtime. + EGL_DEBUG_MSG_INFO_KHR => log::Level::Debug, + _ => log::Level::Trace, + }; + let command = unsafe { ffi::CStr::from_ptr(command_raw) }.to_string_lossy(); + let message = if message_raw.is_null() { + "".into() + } else { + unsafe { ffi::CStr::from_ptr(message_raw) }.to_string_lossy() + }; + + log::log!(log_severity, "EGL '{command}' code 0x{error:x}: {message}",); +} + +#[derive(Clone, Copy, Debug)] +enum SrgbFrameBufferKind { + /// No support for SRGB surface + None, + /// Using EGL 1.5's support for colorspaces + Core, + /// Using EGL_KHR_gl_colorspace + Khr, +} + +/// Choose GLES framebuffer configuration. +fn choose_config( + egl: &EglInstance, + display: khronos_egl::Display, + srgb_kind: SrgbFrameBufferKind, +) -> Result<(khronos_egl::Config, bool), crate::InstanceError> { + //TODO: EGL_SLOW_CONFIG + let tiers = [ + ( + "off-screen", + &[ + khronos_egl::SURFACE_TYPE, + khronos_egl::PBUFFER_BIT, + khronos_egl::RENDERABLE_TYPE, + khronos_egl::OPENGL_ES2_BIT, + ][..], + ), + ( + "presentation", + &[khronos_egl::SURFACE_TYPE, khronos_egl::WINDOW_BIT][..], + ), + #[cfg(not(target_os = "android"))] + ( + "native-render", + &[khronos_egl::NATIVE_RENDERABLE, khronos_egl::TRUE as _][..], + ), + ]; + + let mut attributes = Vec::with_capacity(9); + for tier_max in (0..tiers.len()).rev() { + let name = tiers[tier_max].0; + log::debug!("\tTrying {name}"); + + attributes.clear(); + for &(_, tier_attr) in tiers[..=tier_max].iter() { + attributes.extend_from_slice(tier_attr); + } + // make sure the Alpha is enough to support sRGB + match srgb_kind { + SrgbFrameBufferKind::None => {} + _ => { + attributes.push(khronos_egl::ALPHA_SIZE); + attributes.push(8); + } + } + attributes.push(khronos_egl::NONE); + + match egl.choose_first_config(display, &attributes) { + Ok(Some(config)) => { + if tier_max == 1 { + //Note: this has been confirmed to malfunction on Intel+NV laptops, + // but also on Angle. + log::info!("EGL says it can present to the window but not natively",); + } + // Android emulator can't natively present either. + let tier_threshold = + if cfg!(target_os = "android") || cfg!(windows) || cfg!(target_env = "ohos") { + 1 + } else { + 2 + }; + return Ok((config, tier_max >= tier_threshold)); + } + Ok(None) => { + log::debug!("No config found!"); + } + Err(e) => { + log::error!("error in choose_first_config: {e:?}"); + } + } + } + + // TODO: include diagnostic details that are currently logged + Err(crate::InstanceError::new(String::from( + "unable to find an acceptable EGL framebuffer configuration", + ))) +} + +#[derive(Clone, Debug)] +struct EglContext { + instance: Arc<EglInstance>, + version: (i32, i32), + display: khronos_egl::Display, + raw: khronos_egl::Context, + pbuffer: Option<khronos_egl::Surface>, +} + +impl EglContext { + fn make_current(&self) { + self.instance + .make_current(self.display, self.pbuffer, self.pbuffer, Some(self.raw)) + .unwrap(); + } + + fn unmake_current(&self) { + self.instance + .make_current(self.display, None, None, None) + .unwrap(); + } +} + +/// A wrapper around a [`glow::Context`] and the required EGL context that uses locking to guarantee +/// exclusive access when shared with multiple threads. +#[derive(Debug)] +pub struct AdapterContext { + glow: Mutex<ManuallyDrop<glow::Context>>, + egl: Option<EglContext>, +} + +unsafe impl Sync for AdapterContext {} +unsafe impl Send for AdapterContext {} + +impl AdapterContext { + pub fn is_owned(&self) -> bool { + self.egl.is_some() + } + + /// Returns the EGL instance. + /// + /// This provides access to EGL functions and the ability to load GL and EGL extension functions. + pub fn egl_instance(&self) -> Option<&EglInstance> { + self.egl.as_ref().map(|egl| &*egl.instance) + } + + /// Returns the EGLDisplay corresponding to the adapter context. + /// + /// Returns [`None`] if the adapter was externally created. + pub fn raw_display(&self) -> Option<&khronos_egl::Display> { + self.egl.as_ref().map(|egl| &egl.display) + } + + /// Returns the EGL version the adapter context was created with. + /// + /// Returns [`None`] if the adapter was externally created. + pub fn egl_version(&self) -> Option<(i32, i32)> { + self.egl.as_ref().map(|egl| egl.version) + } + + pub fn raw_context(&self) -> *mut ffi::c_void { + match self.egl { + Some(ref egl) => egl.raw.as_ptr(), + None => ptr::null_mut(), + } + } +} + +impl Drop for AdapterContext { + fn drop(&mut self) { + struct CurrentGuard<'a>(&'a EglContext); + impl Drop for CurrentGuard<'_> { + fn drop(&mut self) { + self.0.unmake_current(); + } + } + + // Context must be current when dropped. See safety docs on + // `glow::HasContext`. + // + // NOTE: This is only set to `None` by `Adapter::new_external` which + // requires the context to be current when anything that may be holding + // the `Arc<AdapterShared>` is dropped. + let _guard = self.egl.as_ref().map(|egl| { + egl.make_current(); + CurrentGuard(egl) + }); + let glow = self.glow.get_mut(); + // SAFETY: Field not used after this. + unsafe { ManuallyDrop::drop(glow) }; + } +} + +struct EglContextLock<'a> { + instance: &'a Arc<EglInstance>, + display: khronos_egl::Display, +} + +/// A guard containing a lock to an [`AdapterContext`], while the GL context is kept current. +#[expect(missing_debug_implementations)] +pub struct AdapterContextLock<'a> { + glow: MutexGuard<'a, ManuallyDrop<glow::Context>>, + egl: Option<EglContextLock<'a>>, +} + +impl<'a> core::ops::Deref for AdapterContextLock<'a> { + type Target = glow::Context; + + fn deref(&self) -> &Self::Target { + &self.glow + } +} + +impl<'a> Drop for AdapterContextLock<'a> { + fn drop(&mut self) { + if let Some(egl) = self.egl.take() { + if let Err(err) = egl.instance.make_current(egl.display, None, None, None) { + log::error!("Failed to make EGL context current: {err:?}"); + } + } + } +} + +impl AdapterContext { + /// Get's the [`glow::Context`] without waiting for a lock + /// + /// # Safety + /// + /// This should only be called when you have manually made sure that the current thread has made + /// the EGL context current and that no other thread also has the EGL context current. + /// Additionally, you must manually make the EGL context **not** current after you are done with + /// it, so that future calls to `lock()` will not fail. + /// + /// > **Note:** Calling this function **will** still lock the [`glow::Context`] which adds an + /// > extra safe-guard against accidental concurrent access to the context. + pub unsafe fn get_without_egl_lock(&self) -> MappedMutexGuard<'_, glow::Context> { + let guard = self + .glow + .try_lock_for(Duration::from_secs(CONTEXT_LOCK_TIMEOUT_SECS)) + .expect("Could not lock adapter context. This is most-likely a deadlock."); + MutexGuard::map(guard, |glow| &mut **glow) + } + + /// Obtain a lock to the EGL context and get handle to the [`glow::Context`] that can be used to + /// do rendering. + #[track_caller] + pub fn lock<'a>(&'a self) -> AdapterContextLock<'a> { + let glow = self + .glow + // Don't lock forever. If it takes longer than 1 second to get the lock we've got a + // deadlock and should panic to show where we got stuck + .try_lock_for(Duration::from_secs(CONTEXT_LOCK_TIMEOUT_SECS)) + .expect("Could not lock adapter context. This is most-likely a deadlock."); + + let egl = self.egl.as_ref().map(|egl| { + egl.make_current(); + EglContextLock { + instance: &egl.instance, + display: egl.display, + } + }); + + AdapterContextLock { glow, egl } + } +} + +#[derive(Debug)] +struct Inner { + /// Note: the context contains a dummy pbuffer (1x1). + /// Required for `eglMakeCurrent` on platforms that doesn't supports `EGL_KHR_surfaceless_context`. + egl: EglContext, + version: (i32, i32), + supports_native_window: bool, + config: khronos_egl::Config, + /// Method by which the framebuffer should support srgb + srgb_kind: SrgbFrameBufferKind, +} + +#[cfg(send_sync)] +unsafe impl Send for Inner {} +#[cfg(send_sync)] +unsafe impl Sync for Inner {} + +// Different calls to `eglGetPlatformDisplay` may return the same `Display`, making it a global +// state of all our `EglContext`s. This forces us to track the number of such context to prevent +// terminating the display if it's currently used by another `EglContext`. +static DISPLAYS_REFERENCE_COUNT: LazyLock<Mutex<HashMap<usize, usize>>> = + LazyLock::new(Default::default); + +fn initialize_display( + egl: &EglInstance, + display: khronos_egl::Display, +) -> Result<(i32, i32), khronos_egl::Error> { + let mut guard = DISPLAYS_REFERENCE_COUNT.lock(); + *guard.entry(display.as_ptr() as usize).or_default() += 1; + + // We don't need to check the reference count here since according to the `eglInitialize` + // documentation, initializing an already initialized EGL display connection has no effect + // besides returning the version numbers. + egl.initialize(display) +} + +fn terminate_display( + egl: &EglInstance, + display: khronos_egl::Display, +) -> Result<(), khronos_egl::Error> { + let key = &(display.as_ptr() as usize); + let mut guard = DISPLAYS_REFERENCE_COUNT.lock(); + let count_ref = guard + .get_mut(key) + .expect("Attempted to decref a display before incref was called"); + + if *count_ref > 1 { + *count_ref -= 1; + + Ok(()) + } else { + guard.remove(key); + + egl.terminate(display) + } +} + +fn instance_err<E: core::error::Error + Send + Sync + 'static>( + message: impl Into<String>, +) -> impl FnOnce(E) -> crate::InstanceError { + move |e| crate::InstanceError::with_source(message.into(), e) +} + +impl Inner { + fn create( + flags: wgt::InstanceFlags, + egl: Arc<EglInstance>, + display: khronos_egl::Display, + force_gles_minor_version: wgt::Gles3MinorVersion, + ) -> Result<Self, crate::InstanceError> { + let version = initialize_display(&egl, display) + .map_err(instance_err("failed to initialize EGL display connection"))?; + let vendor = egl + .query_string(Some(display), khronos_egl::VENDOR) + .map_err(instance_err("failed to query EGL vendor"))?; + let display_extensions = egl + .query_string(Some(display), khronos_egl::EXTENSIONS) + .map_err(instance_err("failed to query EGL display extensions"))? + .to_string_lossy(); + log::debug!("Display vendor {vendor:?}, version {version:?}",); + log::debug!( + "Display extensions: {:#?}", + display_extensions.split_whitespace().collect::<Vec<_>>() + ); + + let srgb_kind = if version >= (1, 5) { + log::debug!("\tEGL surface: +srgb"); + SrgbFrameBufferKind::Core + } else if display_extensions.contains("EGL_KHR_gl_colorspace") { + log::debug!("\tEGL surface: +srgb khr"); + SrgbFrameBufferKind::Khr + } else { + log::debug!("\tEGL surface: -srgb"); + SrgbFrameBufferKind::None + }; + + if log::max_level() >= log::LevelFilter::Trace { + log::trace!("Configurations:"); + let config_count = egl + .get_config_count(display) + .map_err(instance_err("failed to get config count"))?; + let mut configurations = Vec::with_capacity(config_count); + egl.get_configs(display, &mut configurations) + .map_err(instance_err("failed to get configs"))?; + for &config in configurations.iter() { + log::trace!("\tCONFORMANT=0x{:X?}, RENDERABLE=0x{:X?}, NATIVE_RENDERABLE=0x{:X?}, SURFACE_TYPE=0x{:X?}, ALPHA_SIZE={:?}", + egl.get_config_attrib(display, config, khronos_egl::CONFORMANT), + egl.get_config_attrib(display, config, khronos_egl::RENDERABLE_TYPE), + egl.get_config_attrib(display, config, khronos_egl::NATIVE_RENDERABLE), + egl.get_config_attrib(display, config, khronos_egl::SURFACE_TYPE), + egl.get_config_attrib(display, config, khronos_egl::ALPHA_SIZE), + ); + } + } + + let (config, supports_native_window) = choose_config(&egl, display, srgb_kind)?; + + let supports_opengl = if version >= (1, 4) { + let client_apis = egl + .query_string(Some(display), khronos_egl::CLIENT_APIS) + .map_err(instance_err("failed to query EGL client APIs string"))? + .to_string_lossy(); + client_apis + .split(' ') + .any(|client_api| client_api == "OpenGL") + } else { + false + }; + + let mut khr_context_flags = 0; + let supports_khr_context = display_extensions.contains("EGL_KHR_create_context"); + + let mut context_attributes = vec![]; + let mut gl_context_attributes = vec![]; + let mut gles_context_attributes = vec![]; + gl_context_attributes.push(khronos_egl::CONTEXT_MAJOR_VERSION); + gl_context_attributes.push(3); + gl_context_attributes.push(khronos_egl::CONTEXT_MINOR_VERSION); + gl_context_attributes.push(3); + if supports_opengl && force_gles_minor_version != wgt::Gles3MinorVersion::Automatic { + log::warn!("Ignoring specified GLES minor version as OpenGL is used"); + } + gles_context_attributes.push(khronos_egl::CONTEXT_MAJOR_VERSION); + gles_context_attributes.push(3); // Request GLES 3.0 or higher + if force_gles_minor_version != wgt::Gles3MinorVersion::Automatic { + gles_context_attributes.push(khronos_egl::CONTEXT_MINOR_VERSION); + gles_context_attributes.push(match force_gles_minor_version { + wgt::Gles3MinorVersion::Automatic => unreachable!(), + wgt::Gles3MinorVersion::Version0 => 0, + wgt::Gles3MinorVersion::Version1 => 1, + wgt::Gles3MinorVersion::Version2 => 2, + }); + } + if flags.contains(wgt::InstanceFlags::DEBUG) { + if version >= (1, 5) { + log::debug!("\tEGL context: +debug"); + context_attributes.push(khronos_egl::CONTEXT_OPENGL_DEBUG); + context_attributes.push(khronos_egl::TRUE as _); + } else if supports_khr_context { + log::debug!("\tEGL context: +debug KHR"); + khr_context_flags |= EGL_CONTEXT_OPENGL_DEBUG_BIT_KHR; + } else { + log::debug!("\tEGL context: -debug"); + } + } + + if khr_context_flags != 0 { + context_attributes.push(EGL_CONTEXT_FLAGS_KHR); + context_attributes.push(khr_context_flags); + } + + gl_context_attributes.extend(&context_attributes); + gles_context_attributes.extend(&context_attributes); + + let context = { + #[derive(Copy, Clone)] + enum Robustness { + Core, + Ext, + } + + let robustness = if version >= (1, 5) { + Some(Robustness::Core) + } else if display_extensions.contains("EGL_EXT_create_context_robustness") { + Some(Robustness::Ext) + } else { + None + }; + + let create_context = |api, base_attributes: &[khronos_egl::Int]| { + egl.bind_api(api)?; + + let mut robustness = robustness; + loop { + let robustness_attributes = match robustness { + Some(Robustness::Core) => { + vec![ + khronos_egl::CONTEXT_OPENGL_ROBUST_ACCESS, + khronos_egl::TRUE as _, + khronos_egl::NONE, + ] + } + Some(Robustness::Ext) => { + vec![ + EGL_CONTEXT_OPENGL_ROBUST_ACCESS_EXT, + khronos_egl::TRUE as _, + khronos_egl::NONE, + ] + } + None => vec![khronos_egl::NONE], + }; + + let mut context_attributes = base_attributes.to_vec(); + context_attributes.extend(&robustness_attributes); + + match egl.create_context(display, config, None, &context_attributes) { + Ok(context) => { + match robustness { + Some(Robustness::Core) => { + log::debug!("\tEGL context: +robust access"); + } + Some(Robustness::Ext) => { + log::debug!("\tEGL context: +robust access EXT"); + } + None => { + log::debug!("\tEGL context: -robust access"); + } + } + return Ok(context); + } + + // Robust access context creation can fail with different error codes + // depending on the EGL path. Retry with a lower robustness level. + Err( + khronos_egl::Error::BadAttribute + | khronos_egl::Error::BadMatch + | khronos_egl::Error::BadConfig, + ) if robustness.is_some() => { + robustness = match robustness { + Some(Robustness::Core) + if display_extensions + .contains("EGL_EXT_create_context_robustness") => + { + Some(Robustness::Ext) + } + _ => None, + }; + continue; + } + + Err(e) => return Err(e), + } + } + }; + + let result = if supports_opengl { + create_context(khronos_egl::OPENGL_API, &gl_context_attributes).or_else( + |gl_error| { + log::debug!("Failed to create desktop OpenGL context: {gl_error}, falling back to OpenGL ES"); + create_context(khronos_egl::OPENGL_ES_API, &gles_context_attributes) + }, + ) + } else { + create_context(khronos_egl::OPENGL_ES_API, &gles_context_attributes) + }; + + result.map_err(|e| { + crate::InstanceError::with_source( + String::from("unable to create OpenGL or GLES 3.x context"), + e, + ) + }) + }?; + + // Testing if context can be binded without surface + // and creating dummy pbuffer surface if not. + let pbuffer = if version >= (1, 5) + || display_extensions.contains("EGL_KHR_surfaceless_context") + || cfg!(Emscripten) + { + log::debug!("\tEGL context: +surfaceless"); + None + } else { + let attributes = [ + khronos_egl::WIDTH, + 1, + khronos_egl::HEIGHT, + 1, + khronos_egl::NONE, + ]; + egl.create_pbuffer_surface(display, config, &attributes) + .map(Some) + .map_err(|e| { + crate::InstanceError::with_source( + String::from("error in create_pbuffer_surface"), + e, + ) + })? + }; + + Ok(Self { + egl: EglContext { + instance: egl, + display, + raw: context, + pbuffer, + version, + }, + version, + supports_native_window, + config, + srgb_kind, + }) + } +} + +impl Drop for Inner { + fn drop(&mut self) { + // ERROR: Since EglContext is erroneously Clone, these handles could be copied and + // accidentally used elsewhere outside of Inner, despite us assuming ownership and + // destroying the handles here. + if let Err(e) = self + .egl + .instance + .destroy_context(self.egl.display, self.egl.raw) + { + log::warn!("Error in destroy_context: {e:?}"); + } + + if let Err(e) = terminate_display(&self.egl.instance, self.egl.display) { + log::warn!("Error in terminate: {e:?}"); + } + } +} + +#[derive(Clone, Copy, Debug, PartialEq)] +enum WindowKind { + Wayland, + X11, + AngleX11, + Unknown, +} + +#[derive(Clone, Debug)] +struct WindowSystemInterface { + kind: WindowKind, +} + +#[derive(Debug)] +pub struct Instance { + wsi: WindowSystemInterface, + flags: wgt::InstanceFlags, + options: wgt::GlBackendOptions, + inner: Mutex<Inner>, +} + +impl Instance { + pub fn raw_display(&self) -> khronos_egl::Display { + self.inner + .try_lock() + .expect("Could not lock instance. This is most-likely a deadlock.") + .egl + .display + } + + /// Returns the version of the EGL display. + pub fn egl_version(&self) -> (i32, i32) { + self.inner + .try_lock() + .expect("Could not lock instance. This is most-likely a deadlock.") + .version + } + + pub fn egl_config(&self) -> khronos_egl::Config { + self.inner + .try_lock() + .expect("Could not lock instance. This is most-likely a deadlock.") + .config + } +} + +#[cfg(send_sync)] +static_assertions::assert_impl_all!(Instance: Send, Sync); + +impl crate::Instance for Instance { + type A = super::Api; + + unsafe fn init(desc: &crate::InstanceDescriptor<'_>) -> Result<Self, crate::InstanceError> { + use raw_window_handle::RawDisplayHandle as Rdh; + + profiling::scope!("Init OpenGL (EGL) Backend"); + #[cfg(Emscripten)] + let egl_result: Result<EglInstance, khronos_egl::Error> = + Ok(khronos_egl::Instance::new(khronos_egl::Static)); + + #[cfg(not(Emscripten))] + let egl_result = if cfg!(windows) { + unsafe { + khronos_egl::DynamicInstance::<khronos_egl::EGL1_4>::load_required_from_filename( + "libEGL.dll", + ) + } + } else if cfg!(target_vendor = "apple") { + unsafe { + khronos_egl::DynamicInstance::<khronos_egl::EGL1_4>::load_required_from_filename( + "libEGL.dylib", + ) + } + } else { + unsafe { khronos_egl::DynamicInstance::<khronos_egl::EGL1_4>::load_required() } + }; + let egl = egl_result + .map(Arc::new) + .map_err(instance_err("unable to open libEGL"))?; + + let client_extensions = egl.query_string(None, khronos_egl::EXTENSIONS); + + let client_ext_str = match client_extensions { + Ok(ext) => ext.to_string_lossy().into_owned(), + Err(_) => String::new(), + }; + log::debug!( + "Client extensions: {:#?}", + client_ext_str.split_whitespace().collect::<Vec<_>>() + ); + + #[cfg(not(Emscripten))] + let egl1_5 = egl.upcast::<khronos_egl::EGL1_5>(); + + #[cfg(Emscripten)] + let egl1_5: Option<&Arc<EglInstance>> = Some(&egl); + + let (display, wsi_kind) = match (desc.display.map(|d| d.as_raw()), egl1_5) { + (Some(Rdh::Wayland(wayland_display_handle)), Some(egl)) + if client_ext_str.contains("EGL_EXT_platform_wayland") => + { + log::debug!("Using Wayland platform"); + let display_attributes = [khronos_egl::ATTRIB_NONE]; + let display = unsafe { + egl.get_platform_display( + EGL_PLATFORM_WAYLAND_KHR, + wayland_display_handle.display.as_ptr(), + &display_attributes, + ) + } + .map_err(instance_err("failed to get Wayland display"))?; + (display, WindowKind::Wayland) + } + (Some(Rdh::Xlib(xlib_display_handle)), Some(egl)) + if client_ext_str.contains("EGL_EXT_platform_x11") => + { + log::debug!("Using X11 platform"); + let display_attributes = [khronos_egl::ATTRIB_NONE]; + let display = unsafe { + egl.get_platform_display( + EGL_PLATFORM_X11_KHR, + xlib_display_handle + .display + .map_or(khronos_egl::DEFAULT_DISPLAY, ptr::NonNull::as_ptr), + &display_attributes, + ) + } + .map_err(instance_err("failed to get X11 display"))?; + (display, WindowKind::X11) + } + (Some(Rdh::Xlib(xlib_display_handle)), Some(egl)) + if client_ext_str.contains("EGL_ANGLE_platform_angle") => + { + log::debug!("Using Angle platform with X11"); + let display_attributes = [ + EGL_PLATFORM_ANGLE_NATIVE_PLATFORM_TYPE_ANGLE as khronos_egl::Attrib, + EGL_PLATFORM_X11_KHR as khronos_egl::Attrib, + EGL_PLATFORM_ANGLE_DEBUG_LAYERS_ENABLED as khronos_egl::Attrib, + usize::from(desc.flags.contains(wgt::InstanceFlags::VALIDATION)), + khronos_egl::ATTRIB_NONE, + ]; + let display = unsafe { + egl.get_platform_display( + EGL_PLATFORM_ANGLE_ANGLE, + xlib_display_handle + .display + .map_or(khronos_egl::DEFAULT_DISPLAY, ptr::NonNull::as_ptr), + &display_attributes, + ) + } + .map_err(instance_err("failed to get Angle display"))?; + (display, WindowKind::AngleX11) + } + (Some(Rdh::Xcb(xcb_display_handle)), Some(egl)) + if client_ext_str.contains("EGL_EXT_platform_xcb") => + { + log::debug!("Using XCB platform"); + let display_attributes = [ + EGL_PLATFORM_XCB_SCREEN_EXT as khronos_egl::Attrib, + xcb_display_handle.screen as khronos_egl::Attrib, + khronos_egl::ATTRIB_NONE, + ]; + let display = unsafe { + egl.get_platform_display( + EGL_PLATFORM_XCB_EXT, + xcb_display_handle + .connection + .map_or(khronos_egl::DEFAULT_DISPLAY, ptr::NonNull::as_ptr), + &display_attributes, + ) + } + .map_err(instance_err("failed to get XCB display"))?; + (display, WindowKind::X11) + } + x if client_ext_str.contains("EGL_MESA_platform_surfaceless") => { + log::debug!( + "No (or unknown) windowing system ({x:?}) present. Using surfaceless platform" + ); + #[allow( + clippy::unnecessary_literal_unwrap, + reason = "this is only a literal on Emscripten" + )] + // TODO: This extension is also supported on EGL 1.4 with EGL_EXT_platform_base: https://registry.khronos.org/EGL/extensions/MESA/EGL_MESA_platform_surfaceless.txt + let egl = egl1_5.expect("Failed to get EGL 1.5 for surfaceless"); + let display = unsafe { + egl.get_platform_display( + EGL_PLATFORM_SURFACELESS_MESA, + khronos_egl::DEFAULT_DISPLAY, + &[khronos_egl::ATTRIB_NONE], + ) + } + .map_err(instance_err("failed to get MESA surfaceless display"))?; + (display, WindowKind::Unknown) + } + x => { + log::debug!( + "No (or unknown) windowing system {x:?} and EGL_MESA_platform_surfaceless not available. Using default platform" + ); + let display = + unsafe { egl.get_display(khronos_egl::DEFAULT_DISPLAY) }.ok_or_else(|| { + crate::InstanceError::new("Failed to get default display".into()) + })?; + (display, WindowKind::Unknown) + } + }; + + if desc.flags.contains(wgt::InstanceFlags::VALIDATION) + && client_ext_str.contains("EGL_KHR_debug") + { + log::debug!("Enabling EGL debug output"); + let function: EglDebugMessageControlFun = { + let addr = egl + .get_proc_address("eglDebugMessageControlKHR") + .ok_or_else(|| { + crate::InstanceError::new( + "failed to get `eglDebugMessageControlKHR` proc address".into(), + ) + })?; + unsafe { core::mem::transmute(addr) } + }; + let attributes = [ + EGL_DEBUG_MSG_CRITICAL_KHR as khronos_egl::Attrib, + 1, + EGL_DEBUG_MSG_ERROR_KHR as khronos_egl::Attrib, + 1, + EGL_DEBUG_MSG_WARN_KHR as khronos_egl::Attrib, + 1, + EGL_DEBUG_MSG_INFO_KHR as khronos_egl::Attrib, + 1, + khronos_egl::ATTRIB_NONE, + ]; + unsafe { (function)(Some(egl_debug_proc), attributes.as_ptr()) }; + } + + let inner = Inner::create( + desc.flags, + egl, + display, + desc.backend_options.gl.gles_minor_version, + )?; + + Ok(Instance { + wsi: WindowSystemInterface { kind: wsi_kind }, + flags: desc.flags, + options: desc.backend_options.gl.clone(), + inner: Mutex::new(inner), + }) + } + + unsafe fn create_surface( + &self, + display_handle: raw_window_handle::RawDisplayHandle, + window_handle: raw_window_handle::RawWindowHandle, + ) -> Result<Surface, crate::InstanceError> { + use raw_window_handle::RawWindowHandle as Rwh; + + let inner = self.inner.lock(); + + match (window_handle, display_handle) { + (Rwh::Xlib(_), _) => {} + (Rwh::Xcb(_), _) => {} + (Rwh::Win32(_), _) => {} + (Rwh::AppKit(_), _) => {} + (Rwh::OhosNdk(_), _) => {} + #[cfg(target_os = "android")] + (Rwh::AndroidNdk(handle), _) => { + let format = inner + .egl + .instance + .get_config_attrib( + inner.egl.display, + inner.config, + khronos_egl::NATIVE_VISUAL_ID, + ) + .map_err(instance_err("failed to get config NATIVE_VISUAL_ID"))?; + + let ret = unsafe { + ndk_sys::ANativeWindow_setBuffersGeometry( + handle + .a_native_window + .as_ptr() + .cast::<ndk_sys::ANativeWindow>(), + 0, + 0, + format, + ) + }; + + if ret != 0 { + return Err(crate::InstanceError::new(format!( + "error {ret} returned from ANativeWindow_setBuffersGeometry", + ))); + } + } + (Rwh::Wayland(_), _) => {} + #[cfg(Emscripten)] + (Rwh::Web(_), _) => {} + other => { + return Err(crate::InstanceError::new(format!( + "unsupported window: {other:?}" + ))); + } + }; + + inner.egl.unmake_current(); + + Ok(Surface { + egl: inner.egl.clone(), + wsi: self.wsi.clone(), + config: inner.config, + presentable: inner.supports_native_window, + raw_window_handle: window_handle, + swapchain: RwLock::new(None), + srgb_kind: inner.srgb_kind, + }) + } + + unsafe fn enumerate_adapters( + &self, + _surface_hint: Option<&Surface>, + ) -> Vec<crate::ExposedAdapter<super::Api>> { + let inner = self.inner.lock(); + inner.egl.make_current(); + + let mut gl = unsafe { + glow::Context::from_loader_function(|name| { + inner + .egl + .instance + .get_proc_address(name) + .map_or(ptr::null(), |p| p as *const _) + }) + }; + + // In contrast to OpenGL ES, OpenGL requires explicitly enabling sRGB conversions, + // as otherwise the user has to do the sRGB conversion. + if !matches!(inner.srgb_kind, SrgbFrameBufferKind::None) { + unsafe { gl.enable(glow::FRAMEBUFFER_SRGB) }; + } + + if self.flags.contains(wgt::InstanceFlags::DEBUG) && gl.supports_debug() { + log::debug!("Max label length: {}", unsafe { + gl.get_parameter_i32(glow::MAX_LABEL_LENGTH) + }); + } + + if self.flags.contains(wgt::InstanceFlags::VALIDATION) && gl.supports_debug() { + log::debug!("Enabling GLES debug output"); + unsafe { gl.enable(glow::DEBUG_OUTPUT) }; + unsafe { gl.debug_message_callback(super::gl_debug_message_callback) }; + } + + // Wrap in ManuallyDrop to make it easier to "current" the GL context before dropping this + // GLOW context, which could also happen if a panic occurs after we uncurrent the context + // below but before AdapterContext is constructed. + let gl = ManuallyDrop::new(gl); + inner.egl.unmake_current(); + + unsafe { + super::Adapter::expose( + AdapterContext { + glow: Mutex::new(gl), + // ERROR: Copying owned reference handles here, be careful to not drop them! + egl: Some(inner.egl.clone()), + }, + self.options.clone(), + ) + } + .into_iter() + .collect() + } +} + +impl super::Adapter { + /// Creates a new external adapter using the specified loader function. + /// + /// # Safety + /// + /// - The underlying OpenGL ES context must be current. + /// - The underlying OpenGL ES context must be current when interfacing with any objects returned by + /// wgpu-hal from this adapter. + /// - The underlying OpenGL ES context must be current when dropping this adapter and when + /// dropping any objects returned from this adapter. + pub unsafe fn new_external( + fun: impl FnMut(&str) -> *const ffi::c_void, + options: wgt::GlBackendOptions, + ) -> Option<crate::ExposedAdapter<super::Api>> { + let context = unsafe { glow::Context::from_loader_function(fun) }; + unsafe { + Self::expose( + AdapterContext { + glow: Mutex::new(ManuallyDrop::new(context)), + egl: None, + }, + options, + ) + } + } + + pub fn adapter_context(&self) -> &AdapterContext { + &self.shared.context + } +} + +impl super::Device { + /// Returns the underlying EGL context. + pub fn context(&self) -> &AdapterContext { + &self.shared.context + } +} + +#[derive(Debug)] +pub struct Swapchain { + surface: khronos_egl::Surface, + wl_window: Option<*mut wayland_sys::egl::wl_egl_window>, + framebuffer: glow::Framebuffer, + renderbuffer: glow::Renderbuffer, + /// Extent because the window lies + extent: wgt::Extent3d, + format: wgt::TextureFormat, + format_desc: super::TextureFormatDesc, + #[allow(unused)] + sample_type: wgt::TextureSampleType, +} + +#[derive(Debug)] +pub struct Surface { + egl: EglContext, + wsi: WindowSystemInterface, + config: khronos_egl::Config, + pub(super) presentable: bool, + raw_window_handle: raw_window_handle::RawWindowHandle, + swapchain: RwLock<Option<Swapchain>>, + srgb_kind: SrgbFrameBufferKind, +} + +unsafe impl Send for Surface {} +unsafe impl Sync for Surface {} + +impl Surface { + pub(super) unsafe fn present( + &self, + _suf_texture: super::Texture, + context: &AdapterContext, + ) -> Result<(), crate::SurfaceError> { + let gl = unsafe { context.get_without_egl_lock() }; + let swapchain = self.swapchain.read(); + let sc = swapchain.as_ref().ok_or(crate::SurfaceError::Other( + "Surface has no swap-chain configured", + ))?; + + self.egl + .instance + .make_current( + self.egl.display, + Some(sc.surface), + Some(sc.surface), + Some(self.egl.raw), + ) + .map_err(|e| { + log::error!("make_current(surface) failed: {e}"); + crate::SurfaceError::Lost + })?; + + unsafe { gl.disable(glow::SCISSOR_TEST) }; + unsafe { gl.color_mask(true, true, true, true) }; + + unsafe { gl.bind_framebuffer(glow::DRAW_FRAMEBUFFER, None) }; + unsafe { gl.bind_framebuffer(glow::READ_FRAMEBUFFER, Some(sc.framebuffer)) }; + + if !matches!(self.srgb_kind, SrgbFrameBufferKind::None) { + // Disable sRGB conversions for `glBlitFramebuffer` as behavior does diverge between + // drivers and formats otherwise and we want to ensure no sRGB conversions happen. + unsafe { gl.disable(glow::FRAMEBUFFER_SRGB) }; + } + + // Note the Y-flipping here. GL's presentation is not flipped, + // but main rendering is. Therefore, we Y-flip the output positions + // in the shader, and also this blit. + unsafe { + gl.blit_framebuffer( + 0, + sc.extent.height as i32, + sc.extent.width as i32, + 0, + 0, + 0, + sc.extent.width as i32, + sc.extent.height as i32, + glow::COLOR_BUFFER_BIT, + glow::NEAREST, + ) + }; + + if !matches!(self.srgb_kind, SrgbFrameBufferKind::None) { + unsafe { gl.enable(glow::FRAMEBUFFER_SRGB) }; + } + + unsafe { gl.bind_framebuffer(glow::READ_FRAMEBUFFER, None) }; + + self.egl + .instance + .swap_buffers(self.egl.display, sc.surface) + .map_err(|e| { + log::error!("swap_buffers failed: {e}"); + crate::SurfaceError::Lost + // TODO: should we unset the current context here? + })?; + self.egl + .instance + .make_current(self.egl.display, None, None, None) + .map_err(|e| { + log::error!("make_current(null) failed: {e}"); + crate::SurfaceError::Lost + })?; + + Ok(()) + } + + unsafe fn unconfigure_impl( + &self, + device: &super::Device, + ) -> Option<( + khronos_egl::Surface, + Option<*mut wayland_sys::egl::wl_egl_window>, + )> { + let gl = &device.shared.context.lock(); + match self.swapchain.write().take() { + Some(sc) => { + unsafe { gl.delete_renderbuffer(sc.renderbuffer) }; + unsafe { gl.delete_framebuffer(sc.framebuffer) }; + Some((sc.surface, sc.wl_window)) + } + None => None, + } + } + + pub fn supports_srgb(&self) -> bool { + match self.srgb_kind { + SrgbFrameBufferKind::None => false, + _ => true, + } + } +} + +impl crate::Surface for Surface { + type A = super::Api; + + unsafe fn configure( + &self, + device: &super::Device, + config: &crate::SurfaceConfiguration, + ) -> Result<(), crate::SurfaceError> { + use raw_window_handle::RawWindowHandle as Rwh; + + let (surface, wl_window) = match unsafe { self.unconfigure_impl(device) } { + Some((sc, wl_window)) => { + if let Some(window) = wl_window { + wayland_sys::ffi_dispatch!( + wayland_sys::egl::wayland_egl_handle(), + wl_egl_window_resize, + window, + config.extent.width as i32, + config.extent.height as i32, + 0, + 0, + ); + } + + (sc, wl_window) + } + None => { + let mut wl_window = None; + let (mut temp_xlib_handle, mut temp_xcb_handle); + let native_window_ptr = match (self.wsi.kind, self.raw_window_handle) { + (WindowKind::Unknown | WindowKind::X11, Rwh::Xlib(handle)) => { + temp_xlib_handle = handle.window; + ptr::from_mut(&mut temp_xlib_handle).cast::<ffi::c_void>() + } + (WindowKind::AngleX11, Rwh::Xlib(handle)) => handle.window as *mut ffi::c_void, + (WindowKind::Unknown | WindowKind::X11, Rwh::Xcb(handle)) => { + temp_xcb_handle = handle.window; + ptr::from_mut(&mut temp_xcb_handle).cast::<ffi::c_void>() + } + (WindowKind::AngleX11, Rwh::Xcb(handle)) => { + handle.window.get() as *mut ffi::c_void + } + (WindowKind::Unknown, Rwh::AndroidNdk(handle)) => { + handle.a_native_window.as_ptr() + } + (WindowKind::Unknown, Rwh::OhosNdk(handle)) => handle.native_window.as_ptr(), + #[cfg(unix)] + (WindowKind::Wayland, Rwh::Wayland(handle)) => { + let window = wayland_sys::ffi_dispatch!( + wayland_sys::egl::wayland_egl_handle(), + wl_egl_window_create, + handle.surface.as_ptr().cast(), + config.extent.width as i32, + config.extent.height as i32, + ); + wl_window = Some(window); + window.cast() + } + #[cfg(Emscripten)] + (WindowKind::Unknown, Rwh::Web(handle)) => handle.id as *mut ffi::c_void, + (WindowKind::Unknown, Rwh::Win32(handle)) => { + handle.hwnd.get() as *mut ffi::c_void + } + (WindowKind::Unknown, Rwh::AppKit(handle)) => { + #[cfg(not(target_os = "macos"))] + let window_ptr = handle.ns_view.as_ptr(); + #[cfg(target_os = "macos")] + let window_ptr = { + use objc2::msg_send; + use objc2::runtime::AnyObject; + // ns_view always have a layer and don't need to verify that it exists. + let layer: *mut AnyObject = + msg_send![handle.ns_view.as_ptr().cast::<AnyObject>(), layer]; + layer.cast::<ffi::c_void>() + }; + window_ptr + } + _ => { + log::warn!( + "Initialized platform {:?} doesn't work with window {:?}", + self.wsi.kind, + self.raw_window_handle + ); + return Err(crate::SurfaceError::Other("incompatible window kind")); + } + }; + + let mut attributes = vec![ + khronos_egl::RENDER_BUFFER, + // We don't want any of the buffering done by the driver, because we + // manage a swapchain on our side. + // Some drivers just fail on surface creation seeing `EGL_SINGLE_BUFFER`. + if cfg!(any( + target_os = "android", + target_os = "macos", + target_env = "ohos" + )) || cfg!(windows) + || self.wsi.kind == WindowKind::AngleX11 + { + khronos_egl::BACK_BUFFER + } else { + khronos_egl::SINGLE_BUFFER + }, + ]; + if config.format.is_srgb() { + match self.srgb_kind { + SrgbFrameBufferKind::None => {} + SrgbFrameBufferKind::Core => { + attributes.push(khronos_egl::GL_COLORSPACE); + attributes.push(khronos_egl::GL_COLORSPACE_SRGB); + } + SrgbFrameBufferKind::Khr => { + attributes.push(EGL_GL_COLORSPACE_KHR as i32); + attributes.push(EGL_GL_COLORSPACE_SRGB_KHR as i32); + } + } + } + attributes.push(khronos_egl::ATTRIB_NONE as i32); + + #[cfg(not(Emscripten))] + let egl1_5 = self.egl.instance.upcast::<khronos_egl::EGL1_5>(); + + #[cfg(Emscripten)] + let egl1_5: Option<&Arc<EglInstance>> = Some(&self.egl.instance); + + // Careful, we can still be in 1.4 version even if `upcast` succeeds + let raw_result = match egl1_5 { + Some(egl) if self.wsi.kind != WindowKind::Unknown => { + let attributes_usize = attributes + .into_iter() + .map(|v| v as usize) + .collect::<Vec<_>>(); + unsafe { + egl.create_platform_window_surface( + self.egl.display, + self.config, + native_window_ptr, + &attributes_usize, + ) + } + } + _ => unsafe { + self.egl.instance.create_window_surface( + self.egl.display, + self.config, + native_window_ptr, + Some(&attributes), + ) + }, + }; + + match raw_result { + Ok(raw) => (raw, wl_window), + Err(e) => { + log::warn!("Error in create_window_surface: {e:?}"); + return Err(crate::SurfaceError::Lost); + } + } + } + }; + + let format_desc = device.shared.describe_texture_format(config.format); + let gl = &device.shared.context.lock(); + let renderbuffer = unsafe { gl.create_renderbuffer() }.map_err(|error| { + log::error!("Internal swapchain renderbuffer creation failed: {error}"); + crate::DeviceError::OutOfMemory + })?; + unsafe { gl.bind_renderbuffer(glow::RENDERBUFFER, Some(renderbuffer)) }; + unsafe { + gl.renderbuffer_storage( + glow::RENDERBUFFER, + format_desc.internal, + config.extent.width as _, + config.extent.height as _, + ) + }; + let framebuffer = unsafe { gl.create_framebuffer() }.map_err(|error| { + log::error!("Internal swapchain framebuffer creation failed: {error}"); + crate::DeviceError::OutOfMemory + })?; + unsafe { gl.bind_framebuffer(glow::READ_FRAMEBUFFER, Some(framebuffer)) }; + unsafe { + gl.framebuffer_renderbuffer( + glow::READ_FRAMEBUFFER, + glow::COLOR_ATTACHMENT0, + glow::RENDERBUFFER, + Some(renderbuffer), + ) + }; + unsafe { gl.bind_renderbuffer(glow::RENDERBUFFER, None) }; + unsafe { gl.bind_framebuffer(glow::READ_FRAMEBUFFER, None) }; + + let mut swapchain = self.swapchain.write(); + *swapchain = Some(Swapchain { + surface, + wl_window, + renderbuffer, + framebuffer, + extent: config.extent, + format: config.format, + format_desc, + sample_type: wgt::TextureSampleType::Float { filterable: false }, + }); + + Ok(()) + } + + unsafe fn unconfigure(&self, device: &super::Device) { + if let Some((surface, wl_window)) = unsafe { self.unconfigure_impl(device) } { + self.egl + .instance + .destroy_surface(self.egl.display, surface) + .unwrap(); + if let Some(window) = wl_window { + wayland_sys::ffi_dispatch!( + wayland_sys::egl::wayland_egl_handle(), + wl_egl_window_destroy, + window, + ); + } + } + } + + unsafe fn acquire_texture( + &self, + _timeout_ms: Option<Duration>, //TODO + _fence: &super::Fence, + ) -> Result<crate::AcquiredSurfaceTexture<super::Api>, crate::SurfaceError> { + let swapchain = self.swapchain.read(); + let sc = swapchain.as_ref().ok_or(crate::SurfaceError::Other( + "Surface has no swap-chain configured", + ))?; + let texture = super::Texture { + inner: super::TextureInner::Renderbuffer { + raw: sc.renderbuffer, + }, + drop_guard: None, + array_layer_count: 1, + mip_level_count: 1, + format: sc.format, + format_desc: sc.format_desc.clone(), + copy_size: crate::CopyExtent { + width: sc.extent.width, + height: sc.extent.height, + depth: 1, + }, + }; + Ok(crate::AcquiredSurfaceTexture { + texture, + suboptimal: false, + }) + } + unsafe fn discard_texture(&self, _texture: super::Texture) {} +} diff --git a/app/vendor/rune/vendor/wgpu-hal/src/gles/emscripten.rs b/app/vendor/rune/vendor/wgpu-hal/src/gles/emscripten.rs new file mode 100644 index 0000000..88cc0be --- /dev/null +++ b/app/vendor/rune/vendor/wgpu-hal/src/gles/emscripten.rs @@ -0,0 +1,26 @@ +extern "C" { + /// returns 1 if success. 0 if failure. extension name must be null terminated + fn emscripten_webgl_enable_extension( + context: core::ffi::c_int, + extension: *const core::ffi::c_char, + ) -> core::ffi::c_int; + fn emscripten_webgl_get_current_context() -> core::ffi::c_int; +} +/// Webgl requires extensions to be enabled before using them. +/// This function can be used to enable webgl extension on emscripten target. +/// +/// returns true on success +/// +/// # Safety +/// +/// - opengl context MUST BE current +/// - extension_name_null_terminated argument must be a valid string with null terminator. +/// - extension must be present. check `glow_context.supported_extensions()` +pub unsafe fn enable_extension(extension_name_null_terminated: &str) -> bool { + unsafe { + emscripten_webgl_enable_extension( + emscripten_webgl_get_current_context(), + extension_name_null_terminated.as_ptr().cast(), + ) == 1 + } +} diff --git a/app/vendor/rune/vendor/wgpu-hal/src/gles/fence.rs b/app/vendor/rune/vendor/wgpu-hal/src/gles/fence.rs new file mode 100644 index 0000000..0470e5b --- /dev/null +++ b/app/vendor/rune/vendor/wgpu-hal/src/gles/fence.rs @@ -0,0 +1,198 @@ +use alloc::{sync::Arc, vec::Vec}; +use core::sync::atomic::Ordering; +use parking_lot::RwLock; + +use glow::HasContext; + +use crate::AtomicFenceValue; + +#[derive(Debug)] +struct GLFence { + // Since a fence can be `Copy`ed, there can exist some + // cases where a fence could be destroyed while something + // else is still using it. Therefore, while a function is + // using this fence (and doesn't keep pending read locked), + // it should clone the `Arc` to show it needs this to + // stay alive. + // + // The arc should not be kept after a function has finished + sync: Arc<glow::Fence>, + value: crate::FenceValue, +} + +#[derive(Debug)] +pub struct Fence { + last_completed: AtomicFenceValue, + pending: RwLock<Vec<GLFence>>, + fence_behavior: wgt::GlFenceBehavior, +} + +impl crate::DynFence for Fence {} + +#[cfg(send_sync)] +unsafe impl Send for Fence {} +#[cfg(send_sync)] +unsafe impl Sync for Fence {} + +impl Fence { + pub fn new(options: &wgt::GlBackendOptions) -> Self { + Self { + last_completed: AtomicFenceValue::new(0), + pending: RwLock::new(Vec::new()), + fence_behavior: options.fence_behavior, + } + } + + pub fn signal( + &self, + gl: &glow::Context, + value: crate::FenceValue, + ) -> Result<(), crate::DeviceError> { + if self.fence_behavior.is_auto_finish() { + self.last_completed.store(value, Ordering::Release); + return Ok(()); + } + + let sync = unsafe { gl.fence_sync(glow::SYNC_GPU_COMMANDS_COMPLETE, 0) } + .map_err(|_| crate::DeviceError::OutOfMemory)?; + self.pending.write().push(GLFence { + sync: Arc::new(sync), + value, + }); + + Ok(()) + } + + pub fn satisfied(&self, value: crate::FenceValue) -> bool { + self.last_completed.load(Ordering::Acquire) >= value + } + + pub fn get_latest(&self, gl: &glow::Context) -> crate::FenceValue { + let mut max_value = self.last_completed.load(Ordering::Acquire); + + if self.fence_behavior.is_auto_finish() { + return max_value; + } + + let pending = self.pending.read(); + + for gl_fence in pending.iter() { + if gl_fence.value <= max_value { + // We already know this was good, no need to check again + continue; + } + // We have pending `read` locked, so we shouldn't have to clone it. + let status = unsafe { gl.get_sync_status(*gl_fence.sync) }; + if status == glow::SIGNALED { + max_value = gl_fence.value; + } else { + // Anything after the first unsignalled is guaranteed to also be unsignalled + break; + } + } + + // Track the latest value, to save ourselves some querying later + self.last_completed.fetch_max(max_value, Ordering::AcqRel); + + max_value + } + + pub fn maintain(&self, gl: &glow::Context) { + if self.fence_behavior.is_auto_finish() { + return; + } + + let latest = self.get_latest(gl); + let mut pending = self.pending.write(); + pending.retain_mut(|gl_fence| { + if gl_fence.value > latest { + true + } else if let Some(fence) = Arc::get_mut(&mut gl_fence.sync) { + unsafe { + gl.delete_sync(*fence); + } + false + } else { + // Another function is currently using this value. In general, these should finish + // very quickly (for wait because the fence should already be signaled, an all + // others are just fast), but submit should be very fast, so we shouldn't block on + // this. + true + } + }); + } + + pub fn wait( + &self, + gl: &glow::Context, + wait_value: crate::FenceValue, + timeout_ns: u32, + ) -> Result<bool, crate::DeviceError> { + let last_completed = self.last_completed.load(Ordering::Acquire); + + if self.fence_behavior.is_auto_finish() { + return Ok(last_completed >= wait_value); + } + + // We already know this fence has been signalled to that value. Return signalled. + if last_completed >= wait_value { + return Ok(true); + } + + let pending = self.pending.read(); + + // Find a matching fence + let gl_fence = pending.iter().find(|gl_fence| gl_fence.value >= wait_value); + + let Some(gl_fence) = gl_fence else { + log::warn!("Tried to wait for {wait_value} but that value has not been signalled yet"); + return Ok(false); + }; + + // clone to show we're using the fence + let sync = gl_fence.sync.clone(); + let fence_value = gl_fence.value; + + drop(pending); + + let status = unsafe { + gl.client_wait_sync( + *sync, + glow::SYNC_FLUSH_COMMANDS_BIT, + timeout_ns.min(i32::MAX as u32) as i32, + ) + }; + + drop(sync); + + let signalled = match status { + glow::ALREADY_SIGNALED | glow::CONDITION_SATISFIED => true, + glow::TIMEOUT_EXPIRED | glow::WAIT_FAILED => false, + _ => { + log::warn!("Unexpected result from client_wait_sync: {status}"); + false + } + }; + + if signalled { + self.last_completed.fetch_max(fence_value, Ordering::AcqRel); + } + + Ok(signalled) + } + + pub fn destroy(self, gl: &glow::Context) { + if self.fence_behavior.is_auto_finish() { + return; + } + + for gl_fence in self.pending.into_inner() { + unsafe { + gl.delete_sync( + Arc::into_inner(gl_fence.sync) + .expect("A function has failed to drop all its references to this"), + ); + } + } + } +} diff --git a/app/vendor/rune/vendor/wgpu-hal/src/gles/mod.rs b/app/vendor/rune/vendor/wgpu-hal/src/gles/mod.rs new file mode 100644 index 0000000..24e26c6 --- /dev/null +++ b/app/vendor/rune/vendor/wgpu-hal/src/gles/mod.rs @@ -0,0 +1,1215 @@ +/*! +# OpenGL ES3 API (aka GLES3). + +Designed to work on Linux and Android, with context provided by EGL. + +## Texture views + +GLES3 doesn't really have separate texture view objects. We have to remember the +original texture and the sub-range into it. Problem is, however, that there is +no way to expose a subset of array layers or mip levels of a sampled texture. + +## Binding model + +Binding model is very different from WebGPU, especially with regards to samplers. +GLES3 has sampler objects, but they aren't separately bindable to the shaders. +Each sampled texture is exposed to the shader as a combined texture-sampler binding. + +When building the pipeline layout, we linearize binding entries based on the groups +(uniform/storage buffers, uniform/storage textures), and record the mapping into +`BindGroupLayoutInfo`. +When a pipeline gets created, and we track all the texture-sampler associations +from the static use in the shader. +We only support at most one sampler used with each texture so far. The linear index +of this sampler is stored per texture slot in `SamplerBindMap` array. + +The texture-sampler pairs get potentially invalidated in 2 places: + - when a new pipeline is set, we update the linear indices of associated samplers + - when a new bind group is set, we update both the textures and the samplers + +We expect that the changes to sampler states between any 2 pipelines of the same layout +will be minimal, if any. + +## Vertex data + +Generally, vertex buffers are marked as dirty and lazily bound on draw. + +GLES3 doesn't support `first_instance` semantics. However, it's easy to support, +since we are forced to do late binding anyway. We just adjust the offsets +into the vertex data. + +### Old path + +In GLES-3.0 and WebGL2, vertex buffer layout is provided +together with the actual buffer binding. +We invalidate the attributes on the vertex buffer change, and re-bind them. + +### New path + +In GLES-3.1 and higher, the vertex buffer layout can be declared separately +from the vertex data itself. This mostly matches WebGPU, however there is a catch: +`stride` needs to be specified with the data, not as a part of the layout. + +To address this, we invalidate the vertex buffers based on: + - whether or not `first_instance` is used + - stride has changed + +## Handling of `base_vertex`, `first_instance`, and `first_vertex` + +Between indirect, the lack of `first_instance` semantics, and the availability of `gl_BaseInstance` +in shaders, getting buffers and builtins to work correctly is a bit tricky. + +We never emulate `base_vertex` and gl_VertexID behaves as `@builtin(vertex_index)` does, so we +never need to do anything about that. + +### GL 4.2+ with ARB_shader_draw_parameters + +- `@builtin(instance_index)` translates to `gl_InstanceID + gl_BaseInstance` +- We bind instance buffers without any offset emulation. +- We advertise support for the `INDIRECT_FIRST_INSTANCE` feature. + +While we can theoretically have a card with 4.2+ support but without ARB_shader_draw_parameters, +we don't bother with that combination. + +### GLES & GL 4.1 + +- `@builtin(instance_index)` translates to `gl_InstanceID + naga_vs_first_instance` +- We bind instance buffers with offset emulation. +- We _do not_ advertise support for `INDIRECT_FIRST_INSTANCE` and cpu-side pretend the `first_instance` is 0 on indirect calls. + +*/ + +///cbindgen:ignore +#[cfg(not(any(windows, webgl)))] +mod egl; +#[cfg(Emscripten)] +mod emscripten; +#[cfg(webgl)] +mod web; +#[cfg(windows)] +mod wgl; + +mod adapter; +mod command; +mod conv; +mod device; +mod fence; +mod queue; + +pub use fence::Fence; + +#[cfg(not(any(windows, webgl)))] +pub use self::egl::{AdapterContext, AdapterContextLock}; +#[cfg(not(any(windows, webgl)))] +pub use self::egl::{Instance, Surface}; + +#[cfg(webgl)] +pub use self::web::AdapterContext; +#[cfg(webgl)] +pub use self::web::{Instance, Surface}; + +#[cfg(windows)] +use self::wgl::AdapterContext; +#[cfg(windows)] +pub use self::wgl::{Instance, Surface}; + +use alloc::{boxed::Box, string::String, string::ToString as _, sync::Arc, vec::Vec}; +use core::{ + fmt, + ops::Range, + sync::atomic::{AtomicU32, AtomicU8}, +}; +use parking_lot::Mutex; + +use arrayvec::ArrayVec; +use glow::HasContext; +use naga::FastHashMap; + +use crate::{CopyExtent, TextureDescriptor}; + +#[derive(Clone, Debug)] +pub struct Api; + +//Note: we can support more samplers if not every one of them is used at a time, +// but it probably doesn't worth it. +const MAX_TEXTURE_SLOTS: usize = 16; +const MAX_SAMPLERS: usize = 16; +const MAX_VERTEX_ATTRIBUTES: usize = 16; +const ZERO_BUFFER_SIZE: usize = 256 << 10; +const MAX_IMMEDIATES: usize = 64; +// We have to account for each immediate data may need to be set for every shader. +const MAX_IMMEDIATES_COMMANDS: usize = MAX_IMMEDIATES * crate::MAX_CONCURRENT_SHADER_STAGES; + +impl crate::Api for Api { + const VARIANT: wgt::Backend = wgt::Backend::Gl; + + type Instance = Instance; + type Surface = Surface; + type Adapter = Adapter; + type Device = Device; + + type Queue = Queue; + type CommandEncoder = CommandEncoder; + type CommandBuffer = CommandBuffer; + + type Buffer = Buffer; + type Texture = Texture; + type SurfaceTexture = Texture; + type TextureView = TextureView; + type Sampler = Sampler; + type QuerySet = QuerySet; + type Fence = Fence; + type AccelerationStructure = AccelerationStructure; + type PipelineCache = PipelineCache; + + type BindGroupLayout = BindGroupLayout; + type BindGroup = BindGroup; + type PipelineLayout = PipelineLayout; + type ShaderModule = ShaderModule; + type RenderPipeline = RenderPipeline; + type ComputePipeline = ComputePipeline; + type RayTracingPipeline = RayTracingPipeline; +} + +crate::impl_dyn_resource!( + Adapter, + AccelerationStructure, + BindGroup, + BindGroupLayout, + Buffer, + CommandBuffer, + CommandEncoder, + ComputePipeline, + Device, + Fence, + Instance, + PipelineCache, + PipelineLayout, + QuerySet, + Queue, + RenderPipeline, + RayTracingPipeline, + Sampler, + ShaderModule, + Surface, + Texture, + TextureView +); + +bitflags::bitflags! { + /// Flags that affect internal code paths but do not + /// change the exposed feature set. + #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)] + struct PrivateCapabilities: u32 { + /// Indicates support for `glBufferStorage` allocation. + const BUFFER_ALLOCATION = 1 << 0; + /// Support explicit layouts in shader. + const SHADER_BINDING_LAYOUT = 1 << 1; + /// Support extended shadow sampling instructions. + const SHADER_TEXTURE_SHADOW_LOD = 1 << 2; + /// Support memory barriers. + const MEMORY_BARRIERS = 1 << 3; + /// Vertex buffer layouts separate from the data. + const VERTEX_BUFFER_LAYOUT = 1 << 4; + /// Indicates that buffers used as `GL_ELEMENT_ARRAY_BUFFER` may be created / initialized / used + /// as other targets, if not present they must not be mixed with other targets. + const INDEX_BUFFER_ROLE_CHANGE = 1 << 5; + /// Supports `glGetBufferSubData` + const GET_BUFFER_SUB_DATA = 1 << 7; + /// Supports `f16` color buffers + const COLOR_BUFFER_HALF_FLOAT = 1 << 8; + /// Supports `f11/f10` and `f32` color buffers + const COLOR_BUFFER_FLOAT = 1 << 9; + /// Supports query buffer objects. + const QUERY_BUFFERS = 1 << 11; + /// Supports 64 bit queries via `glGetQueryObjectui64v` + const QUERY_64BIT = 1 << 12; + /// Supports `glTexStorage2D`, etc. + const TEXTURE_STORAGE = 1 << 13; + /// Supports `push_debug_group`, `pop_debug_group` and `debug_message_insert`. + const DEBUG_FNS = 1 << 14; + /// Supports framebuffer invalidation. + const INVALIDATE_FRAMEBUFFER = 1 << 15; + /// Indicates support for `glDrawElementsInstancedBaseVertexBaseInstance` and `ARB_shader_draw_parameters` + /// + /// When this is true, instance offset emulation via vertex buffer rebinding and a shader uniform will be disabled. + const FULLY_FEATURED_INSTANCING = 1 << 16; + /// Supports direct multisampled rendering to a texture without needing a resolve texture. + const MULTISAMPLED_RENDER_TO_TEXTURE = 1 << 17; + /// Supports norm16 sized internal formats as filterable sampled + /// textures, with UNORM variants also color-renderable. SNORM + /// renderability is gated on `TEXTURE_FORMAT_SNORM16_RENDERABLE`. + const TEXTURE_FORMAT_NORM16 = 1 << 18; + /// Supports SNORM 16-bit formats as color attachments. Requires + /// `GL_EXT_render_snorm` (in addition to `GL_EXT_texture_norm16` + /// on GLES) - desktop GL alone only "optionally" renders SNORM 16. + const TEXTURE_FORMAT_SNORM16_RENDERABLE = 1 << 19; + /// Supports norm16 sized internal formats as image-load/store targets. + /// Desktop GL >= 4.2 (core image-format list) or pre-4.2 with + /// `GL_ARB_shader_image_load_store`; GLES needs `GL_NV_image_formats` + /// (which itself depends on `GL_EXT_texture_norm16`). + const TEXTURE_FORMAT_NORM16_STORAGE = 1 << 20; + } +} + +bitflags::bitflags! { + /// Flags that indicate necessary workarounds for specific devices or driver bugs + #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)] + struct Workarounds: u32 { + // Needs workaround for Intel Mesa bug: + // https://gitlab.freedesktop.org/mesa/mesa/-/issues/2565. + // + // This comment + // (https://gitlab.freedesktop.org/mesa/mesa/-/merge_requests/4972/diffs?diff_id=75888#22f5d1004713c9bbf857988c7efb81631ab88f99_323_327) + // seems to indicate all skylake models are effected. + const MESA_I915_SRGB_SHADER_CLEAR = 1 << 0; + /// Buffer map must emulated because it is not supported natively + const EMULATE_BUFFER_MAP = 1 << 1; + } +} + +type BindTarget = u32; + +#[derive(Debug, Default, Clone, Copy)] +enum VertexAttribKind { + #[default] + Float, // glVertexAttribPointer + Integer, // glVertexAttribIPointer + //Double, // glVertexAttribLPointer +} + +#[derive(Clone, Debug)] +pub struct TextureFormatDesc { + pub internal: u32, + pub external: u32, + pub data_type: u32, +} + +struct AdapterShared { + context: AdapterContext, + private_caps: PrivateCapabilities, + features: wgt::Features, + limits: wgt::Limits, + workarounds: Workarounds, + options: wgt::GlBackendOptions, + shading_language_version: naga::back::glsl::Version, + next_shader_id: AtomicU32, + program_cache: Mutex<ProgramCache>, + es: bool, + + /// Result of `gl.get_parameter_i32(glow::MAX_SAMPLES)`. + /// Cached here so it doesn't need to be queried every time texture format capabilities are requested. + /// (this has been shown to be a significant enough overhead) + max_msaa_samples: i32, +} + +impl fmt::Debug for AdapterShared { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let Self { + context: _, // may or may not implement Debug depending on platform + private_caps, + features, + limits, + workarounds, + options, + shading_language_version, + next_shader_id, + program_cache: _, + es, + max_msaa_samples, + } = self; + f.debug_struct("AdapterShared") + .field("private_caps", private_caps) + .field("features", features) + .field("limits", limits) + .field("workarounds", workarounds) + .field("options", options) + .field("shading_language_version", shading_language_version) + .field("next_shader_id", next_shader_id) + .field("es", es) + .field("max_msaa_samples", max_msaa_samples) + .finish_non_exhaustive() + } +} + +#[derive(Debug)] +pub struct Adapter { + shared: Arc<AdapterShared>, +} + +#[derive(Debug)] +pub struct Device { + shared: Arc<AdapterShared>, + main_vao: glow::VertexArray, + #[cfg(all(native, feature = "renderdoc"))] + render_doc: crate::auxil::renderdoc::RenderDoc, + counters: Arc<wgt::HalCounters>, +} + +impl Drop for Device { + fn drop(&mut self) { + let gl = &self.shared.context.lock(); + unsafe { gl.delete_vertex_array(self.main_vao) }; + } +} + +#[derive(Debug)] +pub struct ShaderClearProgram { + pub program: glow::Program, + pub color_uniform_location: glow::UniformLocation, +} + +#[derive(Debug)] +pub struct Queue { + shared: Arc<AdapterShared>, + features: wgt::Features, + draw_fbo: glow::Framebuffer, + copy_fbo: glow::Framebuffer, + /// Shader program used to clear the screen for [`Workarounds::MESA_I915_SRGB_SHADER_CLEAR`] + /// devices. + shader_clear_program: Option<ShaderClearProgram>, + /// Keep a reasonably large buffer filled with zeroes, so that we can implement `ClearBuffer` of + /// zeroes by copying from it. + zero_buffer: glow::Buffer, + temp_query_results: Mutex<Vec<u64>>, + draw_buffer_count: AtomicU8, + current_index_buffer: Mutex<Option<glow::Buffer>>, +} + +impl Drop for Queue { + fn drop(&mut self) { + let gl = &self.shared.context.lock(); + unsafe { gl.delete_framebuffer(self.draw_fbo) }; + unsafe { gl.delete_framebuffer(self.copy_fbo) }; + unsafe { gl.delete_buffer(self.zero_buffer) }; + } +} + +#[derive(Clone, Debug)] +pub struct Buffer { + raw: Option<glow::Buffer>, + target: BindTarget, + size: wgt::BufferAddress, + /// Flags to use within calls to [`Device::map_buffer`](crate::Device::map_buffer). + map_flags: u32, + /// Buffer mapping state. + /// + /// If locked concurrently with the GL context, the GL context should be locked first. + map_state: Arc<MaybeMutex<BufferMapState>>, + /// Set when the buffer wraps an externally-owned GL name created via + /// [`Device::buffer_from_raw`](crate::gles::Device::buffer_from_raw). + /// + /// `Buffer` is `Clone`, so the guard is shared via `Arc` + /// and only fires its callback once every clone is dropped. + drop_guard: Option<Arc<crate::DropGuard>>, +} + +#[derive(Clone, Debug)] +struct BufferMapState { + /// True if the GL buffer is actually mapped, i.e. not "fake-mapped" with + /// an empty slice + mapped: bool, + data: Option<Vec<u8>>, + offset_of_current_mapping: wgt::BufferAddress, +} + +#[cfg(send_sync)] +static_assertions::assert_impl_all!(Buffer: Send, Sync); + +impl crate::DynBuffer for Buffer {} + +#[derive(Clone, Debug)] +pub enum TextureInner { + Renderbuffer { + raw: glow::Renderbuffer, + }, + DefaultRenderbuffer, + Texture { + raw: glow::Texture, + target: BindTarget, + }, + #[cfg(webgl)] + /// Render to a `WebGLFramebuffer` + /// + /// This is a web feature + ExternalFramebuffer { + inner: web_sys::WebGlFramebuffer, + }, + #[cfg(native)] + /// Render to a `glow::NativeFramebuffer` + /// Useful when the framebuffer to draw to + /// has a non-zero framebuffer ID + /// + /// This is a native feature + ExternalNativeFramebuffer { + inner: glow::NativeFramebuffer, + }, +} + +#[cfg(send_sync)] +unsafe impl Sync for TextureInner {} +#[cfg(send_sync)] +unsafe impl Send for TextureInner {} + +impl TextureInner { + fn as_native(&self) -> (glow::Texture, BindTarget) { + match *self { + Self::Renderbuffer { .. } | Self::DefaultRenderbuffer => { + panic!("Unexpected renderbuffer"); + } + Self::Texture { raw, target } => (raw, target), + #[cfg(webgl)] + Self::ExternalFramebuffer { .. } => panic!("Unexpected external framebuffer"), + #[cfg(native)] + Self::ExternalNativeFramebuffer { .. } => panic!("unexpected external framebuffer"), + } + } +} + +#[derive(Debug)] +pub struct Texture { + pub inner: TextureInner, + pub mip_level_count: u32, + pub array_layer_count: u32, + pub format: wgt::TextureFormat, + pub format_desc: TextureFormatDesc, + pub copy_size: CopyExtent, + + // The `drop_guard` field must be the last field of this struct so it is dropped last. + // Do not add new fields after it. + pub drop_guard: Option<crate::DropGuard>, +} + +impl crate::DynTexture for Texture {} +impl crate::DynSurfaceTexture for Texture {} + +impl core::borrow::Borrow<dyn crate::DynTexture> for Texture { + fn borrow(&self) -> &dyn crate::DynTexture { + self + } +} + +impl Texture { + pub fn default_framebuffer(format: wgt::TextureFormat) -> Self { + Self { + inner: TextureInner::DefaultRenderbuffer, + drop_guard: None, + mip_level_count: 1, + array_layer_count: 1, + format, + format_desc: TextureFormatDesc { + internal: 0, + external: 0, + data_type: 0, + }, + copy_size: CopyExtent { + width: 0, + height: 0, + depth: 0, + }, + } + } + + /// Returns the `target`, whether the image is 3d and whether the image is a cubemap. + fn get_info_from_desc(desc: &TextureDescriptor) -> u32 { + match desc.dimension { + // WebGL (1 and 2) as well as some GLES versions do not have 1D textures, so we are + // doing `TEXTURE_2D` instead + wgt::TextureDimension::D1 => glow::TEXTURE_2D, + wgt::TextureDimension::D2 => { + // HACK: detect a cube map; forces cube compatible textures to be cube textures + match (desc.is_cube_compatible(), desc.size.depth_or_array_layers) { + (false, 1) => glow::TEXTURE_2D, + (false, _) => glow::TEXTURE_2D_ARRAY, + (true, 6) => glow::TEXTURE_CUBE_MAP, + (true, _) => glow::TEXTURE_CUBE_MAP_ARRAY, + } + } + wgt::TextureDimension::D3 => glow::TEXTURE_3D, + } + } + + /// More information can be found in issues #1614 and #1574 + fn log_failing_target_heuristics(view_dimension: wgt::TextureViewDimension, target: u32) { + let expected_target = match view_dimension { + wgt::TextureViewDimension::D1 => glow::TEXTURE_2D, + wgt::TextureViewDimension::D2 => glow::TEXTURE_2D, + wgt::TextureViewDimension::D2Array => glow::TEXTURE_2D_ARRAY, + wgt::TextureViewDimension::Cube => glow::TEXTURE_CUBE_MAP, + wgt::TextureViewDimension::CubeArray => glow::TEXTURE_CUBE_MAP_ARRAY, + wgt::TextureViewDimension::D3 => glow::TEXTURE_3D, + }; + + if expected_target == target { + return; + } + + let buffer; + let got = match target { + glow::TEXTURE_2D => "D2", + glow::TEXTURE_2D_ARRAY => "D2Array", + glow::TEXTURE_CUBE_MAP => "Cube", + glow::TEXTURE_CUBE_MAP_ARRAY => "CubeArray", + glow::TEXTURE_3D => "D3", + target => { + buffer = target.to_string(); + &buffer + } + }; + + log::error!( + concat!( + "wgpu-hal heuristics assumed that ", + "the view dimension will be equal to `{}` rather than `{:?}`.\n", + "`D2` textures with ", + "`depth_or_array_layers == 1` ", + "are assumed to have view dimension `D2`\n", + "`D2` textures with ", + "`depth_or_array_layers > 1` ", + "are assumed to have view dimension `D2Array`\n", + "`D2` textures with ", + "`depth_or_array_layers == 6` ", + "are assumed to have view dimension `Cube`\n", + "`D2` textures with ", + "`depth_or_array_layers > 6 && depth_or_array_layers % 6 == 0` ", + "are assumed to have view dimension `CubeArray`\n", + ), + got, + view_dimension, + ); + } +} + +#[derive(Clone, Debug)] +pub struct TextureView { + inner: TextureInner, + aspects: crate::FormatAspects, + mip_levels: Range<u32>, + array_layers: Range<u32>, + format: wgt::TextureFormat, +} + +impl crate::DynTextureView for TextureView {} + +#[derive(Debug)] +pub struct Sampler { + raw: glow::Sampler, +} + +impl crate::DynSampler for Sampler {} + +#[derive(Debug)] +pub struct BindGroupLayout { + entries: Arc<[wgt::BindGroupLayoutEntry]>, +} + +impl crate::DynBindGroupLayout for BindGroupLayout {} + +#[derive(Debug)] +struct BindGroupLayoutInfo { + entries: Arc<[wgt::BindGroupLayoutEntry]>, + /// Mapping of resources, indexed by `binding`, into the whole layout space. + /// For texture resources, the value is the texture slot index. + /// For sampler resources, the value is the index of the sampler in the whole layout. + /// For buffers, the value is the uniform or storage slot index. + /// For unused bindings, the value is `!0` + binding_to_slot: Box<[u8]>, +} + +#[derive(Debug)] +pub struct PipelineLayout { + group_infos: Box<[Option<BindGroupLayoutInfo>]>, + naga_options: naga::back::glsl::Options, +} + +impl crate::DynPipelineLayout for PipelineLayout {} + +impl PipelineLayout { + /// # Panics + /// If the pipeline layout does not contain a bind group layout used by + /// the resource binding. + fn get_slot(&self, br: &naga::ResourceBinding) -> u8 { + let group_info = self.group_infos[br.group as usize].as_ref().unwrap(); + group_info.binding_to_slot[br.binding as usize] + } +} + +#[derive(Debug)] +enum BindingRegister { + UniformBuffers, + StorageBuffers, + Textures, + Images, +} + +#[derive(Debug)] +enum RawBinding { + Buffer { + raw: glow::Buffer, + offset: i32, + size: i32, + }, + Texture { + raw: glow::Texture, + target: BindTarget, + aspects: crate::FormatAspects, + mip_levels: Range<u32>, + //TODO: array layers + }, + Image(ImageBinding), + Sampler(glow::Sampler), +} + +#[derive(Debug)] +pub struct BindGroup { + contents: Box<[RawBinding]>, +} + +impl crate::DynBindGroup for BindGroup {} + +type ShaderId = u32; + +#[derive(Debug)] +pub enum ShaderModuleSource { + Naga(crate::NagaShader), + Passthrough { source: String }, +} + +#[derive(Debug)] +pub struct ShaderModule { + source: ShaderModuleSource, + label: Option<String>, + id: ShaderId, +} + +impl crate::DynShaderModule for ShaderModule {} + +#[derive(Clone, Debug, Default)] +struct VertexFormatDesc { + element_count: i32, + element_format: u32, + attrib_kind: VertexAttribKind, +} + +#[derive(Clone, Debug, Default)] +struct AttributeDesc { + location: u32, + offset: u32, + buffer_index: u32, + format_desc: VertexFormatDesc, +} + +#[derive(Clone, Debug)] +struct BufferBinding { + raw: glow::Buffer, + offset: wgt::BufferAddress, +} + +#[derive(Clone, Debug)] +struct ImageBinding { + raw: glow::Texture, + mip_level: u32, + array_layer: Option<u32>, + access: u32, + format: u32, +} + +#[derive(Clone, Debug, Default, PartialEq)] +struct VertexBufferDesc { + step: wgt::VertexStepMode, + stride: u32, +} + +#[derive(Clone, Debug)] +struct ImmediateDesc { + location: glow::UniformLocation, + ty: nt::glsl::GlslUniformType, + offset: u32, + size_bytes: u32, +} + +#[cfg(send_sync)] +unsafe impl Sync for ImmediateDesc {} +#[cfg(send_sync)] +unsafe impl Send for ImmediateDesc {} + +/// For each texture in the pipeline layout, store the index of the only +/// sampler (in this layout) that the texture is used with. +type SamplerBindMap = [Option<u8>; MAX_TEXTURE_SLOTS]; + +#[derive(Debug)] +struct PipelineInner { + program: glow::Program, + sampler_map: SamplerBindMap, + first_instance_location: Option<glow::UniformLocation>, + immediates_descs: ArrayVec<ImmediateDesc, MAX_IMMEDIATES_COMMANDS>, + clip_distance_count: u32, +} + +#[cfg(send_sync)] +unsafe impl Sync for PipelineInner {} +#[cfg(send_sync)] +unsafe impl Send for PipelineInner {} + +#[derive(Clone, Debug)] +struct DepthState { + function: u32, + mask: bool, +} + +#[derive(Clone, Debug, PartialEq)] +struct BlendComponent { + src: u32, + dst: u32, + equation: u32, +} + +#[derive(Clone, Debug, PartialEq)] +struct BlendDesc { + alpha: BlendComponent, + color: BlendComponent, +} + +#[derive(Clone, Debug, Default, PartialEq)] +struct ColorTargetDesc { + mask: wgt::ColorWrites, + blend: Option<BlendDesc>, +} + +#[derive(Debug, PartialEq, Eq, Hash)] +struct ProgramStage { + naga_stage: naga::ShaderStage, + shader_id: ShaderId, + entry_point: String, + zero_initialize_workgroup_memory: bool, + constant_hash: Vec<u8>, +} + +#[derive(Debug, PartialEq, Eq, Hash)] +struct ProgramCacheKey { + stages: ArrayVec<ProgramStage, 3>, + group_to_binding_to_slot: Box<[Option<Box<[u8]>>]>, +} + +type ProgramCache = FastHashMap<ProgramCacheKey, Result<Arc<PipelineInner>, crate::PipelineError>>; + +#[derive(Debug)] +pub struct RenderPipeline { + inner: Arc<PipelineInner>, + primitive: wgt::PrimitiveState, + vertex_buffers: Box<[Option<VertexBufferDesc>]>, + vertex_attributes: Box<[AttributeDesc]>, + color_targets: Box<[ColorTargetDesc]>, + depth: Option<DepthState>, + depth_bias: wgt::DepthBiasState, + stencil: Option<StencilState>, + alpha_to_coverage_enabled: bool, +} + +impl crate::DynRenderPipeline for RenderPipeline {} + +#[cfg(send_sync)] +static_assertions::assert_impl_all!(RenderPipeline: Send, Sync); + +#[derive(Debug)] +pub struct ComputePipeline { + inner: Arc<PipelineInner>, +} + +impl crate::DynComputePipeline for ComputePipeline {} + +#[derive(Debug)] +pub struct RayTracingPipeline {} + +impl crate::DynRayTracingPipeline for RayTracingPipeline {} + +#[cfg(send_sync)] +static_assertions::assert_impl_all!(ComputePipeline: Send, Sync); + +#[derive(Debug)] +pub struct QuerySet { + queries: Box<[glow::Query]>, + target: BindTarget, +} + +impl crate::DynQuerySet for QuerySet {} + +#[derive(Debug)] +pub struct AccelerationStructure; + +impl crate::DynAccelerationStructure for AccelerationStructure {} + +#[derive(Debug)] +pub struct PipelineCache; + +impl crate::DynPipelineCache for PipelineCache {} + +#[derive(Clone, Debug, PartialEq)] +struct StencilOps { + pass: u32, + fail: u32, + depth_fail: u32, +} + +impl Default for StencilOps { + fn default() -> Self { + Self { + pass: glow::KEEP, + fail: glow::KEEP, + depth_fail: glow::KEEP, + } + } +} + +#[derive(Clone, Debug, PartialEq)] +struct StencilSide { + function: u32, + mask_read: u32, + mask_write: u32, + reference: u32, + ops: StencilOps, +} + +impl Default for StencilSide { + fn default() -> Self { + Self { + function: glow::ALWAYS, + mask_read: 0xFF, + mask_write: 0xFF, + reference: 0, + ops: StencilOps::default(), + } + } +} + +#[derive(Debug, Clone, Default)] +struct StencilState { + front: StencilSide, + back: StencilSide, +} + +#[derive(Clone, Debug, Default, PartialEq)] +struct PrimitiveState { + front_face: u32, + cull_face: u32, + unclipped_depth: bool, + polygon_mode: u32, +} + +type InvalidatedAttachments = ArrayVec<u32, { crate::MAX_COLOR_ATTACHMENTS + 2 }>; + +#[derive(Debug)] +enum Command { + Draw { + topology: u32, + first_vertex: u32, + vertex_count: u32, + first_instance: u32, + instance_count: u32, + first_instance_location: Option<glow::UniformLocation>, + }, + DrawIndexed { + topology: u32, + index_type: u32, + index_count: u32, + index_offset: wgt::BufferAddress, + base_vertex: i32, + first_instance: u32, + instance_count: u32, + first_instance_location: Option<glow::UniformLocation>, + }, + DrawIndirect { + topology: u32, + indirect_buf: glow::Buffer, + indirect_offset: wgt::BufferAddress, + first_instance_location: Option<glow::UniformLocation>, + }, + DrawIndexedIndirect { + topology: u32, + index_type: u32, + indirect_buf: glow::Buffer, + indirect_offset: wgt::BufferAddress, + first_instance_location: Option<glow::UniformLocation>, + }, + Dispatch([u32; 3]), + DispatchIndirect { + indirect_buf: glow::Buffer, + indirect_offset: wgt::BufferAddress, + }, + ClearBuffer { + dst: Buffer, + dst_target: BindTarget, + range: crate::MemoryRange, + }, + CopyBufferToBuffer { + src: Buffer, + src_target: BindTarget, + dst: Buffer, + dst_target: BindTarget, + copy: crate::BufferCopy, + }, + #[cfg(webgl)] + CopyExternalImageToTexture { + src: wgt::CopyExternalImageSourceInfo, + dst: glow::Texture, + dst_target: BindTarget, + dst_format: wgt::TextureFormat, + dst_premultiplication: bool, + copy: crate::TextureCopy, + }, + CopyTextureToTexture { + src: glow::Texture, + src_target: BindTarget, + dst: glow::Texture, + dst_target: BindTarget, + copy: crate::TextureCopy, + }, + CopyBufferToTexture { + src: Buffer, + #[allow(unused)] + src_target: BindTarget, + dst: glow::Texture, + dst_target: BindTarget, + dst_format: wgt::TextureFormat, + copy: crate::BufferTextureCopy, + }, + CopyTextureToBuffer { + src: glow::Texture, + src_target: BindTarget, + src_format: wgt::TextureFormat, + dst: Buffer, + #[allow(unused)] + dst_target: BindTarget, + copy: crate::BufferTextureCopy, + }, + SetIndexBuffer(glow::Buffer), + BeginQuery(glow::Query, BindTarget), + EndQuery(BindTarget), + TimestampQuery(glow::Query), + CopyQueryResults { + query_range: Range<u32>, + dst: Buffer, + dst_target: BindTarget, + dst_offset: wgt::BufferAddress, + }, + ResetFramebuffer { + is_default: bool, + }, + BindAttachment { + attachment: u32, + view: TextureView, + depth_slice: Option<u32>, + sample_count: u32, + }, + ResolveAttachment { + attachment: u32, + dst: TextureView, + size: wgt::Extent3d, + }, + InvalidateAttachments(InvalidatedAttachments), + SetDrawColorBuffers(u8), + ClearColorF { + draw_buffer: u32, + color: [f32; 4], + is_srgb: bool, + }, + ClearColorU(u32, [u32; 4]), + ClearColorI(u32, [i32; 4]), + ClearDepth(f32), + ClearStencil(u32), + // Clearing both the depth and stencil buffer individually appears to + // result in the stencil buffer failing to clear, atleast in WebGL. + // It is also more efficient to emit a single command instead of two for + // this. + ClearDepthAndStencil(f32, u32), + BufferBarrier(glow::Buffer, wgt::BufferUses), + TextureBarrier(wgt::TextureUses), + SetViewport { + rect: crate::Rect<i32>, + depth: Range<f32>, + }, + SetScissor(crate::Rect<i32>), + SetStencilFunc { + face: u32, + function: u32, + reference: u32, + read_mask: u32, + }, + SetStencilOps { + face: u32, + write_mask: u32, + ops: StencilOps, + }, + SetDepth(DepthState), + SetDepthBias(wgt::DepthBiasState), + ConfigureDepthStencil(crate::FormatAspects), + SetAlphaToCoverage(bool), + SetVertexAttribute { + buffer: Option<glow::Buffer>, + buffer_desc: VertexBufferDesc, + attribute_desc: AttributeDesc, + }, + UnsetVertexAttribute(u32), + SetVertexBuffer { + index: u32, + buffer: BufferBinding, + buffer_desc: VertexBufferDesc, + }, + SetProgram(glow::Program), + SetPrimitive(PrimitiveState), + SetBlendConstant([f32; 4]), + SetColorTarget { + draw_buffer_index: Option<u32>, + desc: ColorTargetDesc, + }, + BindBuffer { + target: BindTarget, + slot: u32, + buffer: glow::Buffer, + offset: i32, + size: i32, + }, + BindSampler(u32, Option<glow::Sampler>), + BindTexture { + slot: u32, + texture: glow::Texture, + target: BindTarget, + aspects: crate::FormatAspects, + mip_levels: Range<u32>, + }, + BindImage { + slot: u32, + binding: ImageBinding, + }, + InsertDebugMarker(Range<u32>), + PushDebugGroup(Range<u32>), + PopDebugGroup, + SetImmediates { + uniform: ImmediateDesc, + /// Offset from the start of the `data_bytes` + offset: u32, + }, + SetClipDistances { + old_count: u32, + new_count: u32, + }, +} + +#[derive(Default)] +pub struct CommandBuffer { + label: Option<String>, + commands: Vec<Command>, + data_bytes: Vec<u8>, + queries: Vec<glow::Query>, +} + +impl crate::DynCommandBuffer for CommandBuffer {} + +impl fmt::Debug for CommandBuffer { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let mut builder = f.debug_struct("CommandBuffer"); + if let Some(ref label) = self.label { + builder.field("label", label); + } + builder.finish() + } +} + +#[cfg(send_sync)] +unsafe impl Sync for CommandBuffer {} +#[cfg(send_sync)] +unsafe impl Send for CommandBuffer {} + +//TODO: we would have something like `Arc<typed_arena::Arena>` +// here and in the command buffers. So that everything grows +// inside the encoder and stays there until `reset_all`. + +pub struct CommandEncoder { + cmd_buffer: CommandBuffer, + state: command::State, + private_caps: PrivateCapabilities, + counters: Arc<wgt::HalCounters>, +} + +impl fmt::Debug for CommandEncoder { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("CommandEncoder") + .field("cmd_buffer", &self.cmd_buffer) + .finish() + } +} + +#[cfg(send_sync)] +unsafe impl Sync for CommandEncoder {} +#[cfg(send_sync)] +unsafe impl Send for CommandEncoder {} + +#[cfg(not(webgl))] +fn gl_debug_message_callback(source: u32, gltype: u32, id: u32, severity: u32, message: &str) { + let source_str = match source { + glow::DEBUG_SOURCE_API => "API", + glow::DEBUG_SOURCE_WINDOW_SYSTEM => "Window System", + glow::DEBUG_SOURCE_SHADER_COMPILER => "ShaderCompiler", + glow::DEBUG_SOURCE_THIRD_PARTY => "Third Party", + glow::DEBUG_SOURCE_APPLICATION => "Application", + glow::DEBUG_SOURCE_OTHER => "Other", + _ => unreachable!(), + }; + + let log_severity = match severity { + glow::DEBUG_SEVERITY_HIGH => log::Level::Error, + glow::DEBUG_SEVERITY_MEDIUM => log::Level::Warn, + glow::DEBUG_SEVERITY_LOW => log::Level::Debug, + glow::DEBUG_SEVERITY_NOTIFICATION => log::Level::Trace, + _ => unreachable!(), + }; + + let type_str = match gltype { + glow::DEBUG_TYPE_DEPRECATED_BEHAVIOR => "Deprecated Behavior", + glow::DEBUG_TYPE_ERROR => "Error", + glow::DEBUG_TYPE_MARKER => "Marker", + glow::DEBUG_TYPE_OTHER => "Other", + glow::DEBUG_TYPE_PERFORMANCE => "Performance", + glow::DEBUG_TYPE_POP_GROUP => "Pop Group", + glow::DEBUG_TYPE_PORTABILITY => "Portability", + glow::DEBUG_TYPE_PUSH_GROUP => "Push Group", + glow::DEBUG_TYPE_UNDEFINED_BEHAVIOR => "Undefined Behavior", + _ => unreachable!(), + }; + + let _ = std::panic::catch_unwind(|| { + log::log!( + log_severity, + "GLES: [{source_str}/{type_str}] ID {id} : {message}" + ); + }); + + #[cfg(feature = "validation_canary")] + if cfg!(debug_assertions) && log_severity == log::Level::Error { + // Set canary and continue + crate::VALIDATION_CANARY.add(message.to_string()); + } +} + +// If we are using `std`, then use `Mutex` to provide `Send` and `Sync` +cfg_if::cfg_if! { + if #[cfg(gles_with_std)] { + type MaybeMutex<T> = std::sync::Mutex<T>; + + fn lock<T>(mutex: &MaybeMutex<T>) -> std::sync::MutexGuard<'_, T> { + mutex.lock().unwrap() + } + } else { + // It should be impossible for any build configuration to trigger this error + // It is intended only as a guard against changes elsewhere causing the use of + // `RefCell` here to become unsound. + #[cfg(all(send_sync, not(feature = "fragile-send-sync-non-atomic-wasm")))] + compile_error!("cannot provide non-fragile Send+Sync without std"); + + type MaybeMutex<T> = core::cell::RefCell<T>; + + fn lock<T>(mutex: &MaybeMutex<T>) -> core::cell::RefMut<'_, T> { + mutex.borrow_mut() + } + } +} diff --git a/app/vendor/rune/vendor/wgpu-hal/src/gles/queue.rs b/app/vendor/rune/vendor/wgpu-hal/src/gles/queue.rs new file mode 100644 index 0000000..9984cd5 --- /dev/null +++ b/app/vendor/rune/vendor/wgpu-hal/src/gles/queue.rs @@ -0,0 +1,1980 @@ +use alloc::sync::Arc; +use alloc::vec; +use core::sync::atomic::Ordering; + +use arrayvec::ArrayVec; +use glow::HasContext; + +use super::{conv::is_layered_target, lock, Command as C, PrivateCapabilities}; + +const DEBUG_ID: u32 = 0; + +fn extract_marker<'a>(data: &'a [u8], range: &core::ops::Range<u32>) -> &'a str { + core::str::from_utf8(&data[range.start as usize..range.end as usize]).unwrap() +} + +fn to_debug_str(s: &str) -> &str { + // The spec mentions that if the length given to debug functions is negative, + // the implementation will access the ptr and look for a null that terminates + // the string but some implementations will try to access the ptr even if the + // length is 0. + if s.is_empty() { + "<empty>" + } else { + s + } +} + +fn get_2d_target(target: u32, array_layer: u32) -> u32 { + const CUBEMAP_FACES: [u32; 6] = [ + glow::TEXTURE_CUBE_MAP_POSITIVE_X, + glow::TEXTURE_CUBE_MAP_NEGATIVE_X, + glow::TEXTURE_CUBE_MAP_POSITIVE_Y, + glow::TEXTURE_CUBE_MAP_NEGATIVE_Y, + glow::TEXTURE_CUBE_MAP_POSITIVE_Z, + glow::TEXTURE_CUBE_MAP_NEGATIVE_Z, + ]; + + match target { + glow::TEXTURE_2D => target, + glow::TEXTURE_CUBE_MAP => CUBEMAP_FACES[array_layer as usize], + _ => unreachable!(), + } +} + +fn get_z_offset(target: u32, base: &crate::TextureCopyBase) -> u32 { + match target { + glow::TEXTURE_2D_ARRAY | glow::TEXTURE_CUBE_MAP_ARRAY => base.array_layer, + glow::TEXTURE_3D => base.origin.z, + _ => unreachable!(), + } +} + +impl super::Queue { + /// Performs a manual shader clear, used as a workaround for a clearing bug on mesa + unsafe fn perform_shader_clear(&self, gl: &glow::Context, draw_buffer: u32, color: [f32; 4]) { + let shader_clear = self + .shader_clear_program + .as_ref() + .expect("shader_clear_program should always be set if the workaround is enabled"); + unsafe { gl.use_program(Some(shader_clear.program)) }; + unsafe { + gl.uniform_4_f32( + Some(&shader_clear.color_uniform_location), + color[0], + color[1], + color[2], + color[3], + ) + }; + unsafe { gl.disable(glow::DEPTH_TEST) }; + unsafe { gl.disable(glow::STENCIL_TEST) }; + unsafe { gl.disable(glow::SCISSOR_TEST) }; + unsafe { gl.disable(glow::BLEND) }; + unsafe { gl.disable(glow::CULL_FACE) }; + unsafe { gl.draw_buffers(&[glow::COLOR_ATTACHMENT0 + draw_buffer]) }; + unsafe { gl.draw_arrays(glow::TRIANGLES, 0, 3) }; + + let draw_buffer_count = self.draw_buffer_count.load(Ordering::Relaxed); + if draw_buffer_count != 0 { + // Reset the draw buffers to what they were before the clear + let indices = (0..draw_buffer_count as u32) + .map(|i| glow::COLOR_ATTACHMENT0 + i) + .collect::<ArrayVec<_, { crate::MAX_COLOR_ATTACHMENTS }>>(); + unsafe { gl.draw_buffers(&indices) }; + } + } + + unsafe fn reset_state(&self, gl: &glow::Context) { + unsafe { gl.use_program(None) }; + unsafe { gl.bind_framebuffer(glow::FRAMEBUFFER, None) }; + unsafe { gl.disable(glow::DEPTH_TEST) }; + unsafe { gl.disable(glow::STENCIL_TEST) }; + unsafe { gl.disable(glow::SCISSOR_TEST) }; + unsafe { gl.disable(glow::BLEND) }; + unsafe { gl.disable(glow::CULL_FACE) }; + unsafe { gl.disable(glow::POLYGON_OFFSET_FILL) }; + unsafe { gl.disable(glow::SAMPLE_ALPHA_TO_COVERAGE) }; + if self.features.contains(wgt::Features::DEPTH_CLIP_CONTROL) { + unsafe { gl.disable(glow::DEPTH_CLAMP) }; + } + + unsafe { gl.bind_buffer(glow::ELEMENT_ARRAY_BUFFER, None) }; + let mut current_index_buffer = self.current_index_buffer.lock(); + *current_index_buffer = None; + } + + unsafe fn set_attachment( + &self, + gl: &glow::Context, + fbo_target: u32, + attachment: u32, + view: &super::TextureView, + depth_slice: Option<u32>, + sample_count: u32, + ) { + match view.inner { + super::TextureInner::Renderbuffer { raw } => { + unsafe { + gl.framebuffer_renderbuffer( + fbo_target, + attachment, + glow::RENDERBUFFER, + Some(raw), + ) + }; + } + super::TextureInner::DefaultRenderbuffer => panic!("Unexpected default RBO"), + super::TextureInner::Texture { raw, target } => { + let num_layers = view.array_layers.end - view.array_layers.start; + if num_layers > 1 { + #[cfg(webgl)] + unsafe { + gl.framebuffer_texture_multiview_ovr( + fbo_target, + attachment, + Some(raw), + view.mip_levels.start as i32, + view.array_layers.start as i32, + num_layers as i32, + ) + }; + } else if is_layered_target(target) { + let layer = if target == glow::TEXTURE_3D { + depth_slice.unwrap() as i32 + } else { + view.array_layers.start as i32 + }; + unsafe { + gl.framebuffer_texture_layer( + fbo_target, + attachment, + Some(raw), + view.mip_levels.start as i32, + layer, + ) + }; + } else { + unsafe { + assert_eq!(view.mip_levels.len(), 1); + if sample_count != 1 { + gl.framebuffer_texture_2d_multisample( + fbo_target, + attachment, + get_2d_target(target, view.array_layers.start), + Some(raw), + view.mip_levels.start as i32, + sample_count as i32, + ) + } else { + gl.framebuffer_texture_2d( + fbo_target, + attachment, + get_2d_target(target, view.array_layers.start), + Some(raw), + view.mip_levels.start as i32, + ) + } + }; + } + } + #[cfg(webgl)] + super::TextureInner::ExternalFramebuffer { ref inner } => unsafe { + gl.bind_external_framebuffer(glow::FRAMEBUFFER, inner); + }, + #[cfg(native)] + super::TextureInner::ExternalNativeFramebuffer { ref inner } => unsafe { + gl.bind_framebuffer(glow::FRAMEBUFFER, Some(*inner)); + }, + } + } + + unsafe fn process( + &self, + gl: &glow::Context, + command: &C, + #[cfg_attr(target_arch = "wasm32", allow(unused))] data_bytes: &[u8], + queries: &[glow::Query], + ) { + match *command { + C::Draw { + topology, + first_vertex, + vertex_count, + instance_count, + first_instance, + ref first_instance_location, + } => { + let supports_full_instancing = self + .shared + .private_caps + .contains(PrivateCapabilities::FULLY_FEATURED_INSTANCING); + + if supports_full_instancing { + unsafe { + gl.draw_arrays_instanced_base_instance( + topology, + first_vertex as i32, + vertex_count as i32, + instance_count as i32, + first_instance, + ) + } + } else { + unsafe { + gl.uniform_1_u32(first_instance_location.as_ref(), first_instance); + } + + // Don't use `gl.draw_arrays` for `instance_count == 1`. + // Angle has a bug where it doesn't consider the instance divisor when `DYNAMIC_DRAW` is used in `draw_arrays`. + // See https://github.com/gfx-rs/wgpu/issues/3578 + unsafe { + gl.draw_arrays_instanced( + topology, + first_vertex as i32, + vertex_count as i32, + instance_count as i32, + ) + } + }; + } + C::DrawIndexed { + topology, + index_type, + index_count, + index_offset, + base_vertex, + first_instance, + instance_count, + ref first_instance_location, + } => { + let supports_full_instancing = self + .shared + .private_caps + .contains(PrivateCapabilities::FULLY_FEATURED_INSTANCING); + + if supports_full_instancing { + unsafe { + gl.draw_elements_instanced_base_vertex_base_instance( + topology, + index_count as i32, + index_type, + index_offset as i32, + instance_count as i32, + base_vertex, + first_instance, + ) + } + } else { + unsafe { gl.uniform_1_u32(first_instance_location.as_ref(), first_instance) }; + + if base_vertex == 0 { + unsafe { + // Don't use `gl.draw_elements`/`gl.draw_elements_base_vertex` for `instance_count == 1`. + // Angle has a bug where it doesn't consider the instance divisor when `DYNAMIC_DRAW` is used in `gl.draw_elements`/`gl.draw_elements_base_vertex`. + // See https://github.com/gfx-rs/wgpu/issues/3578 + gl.draw_elements_instanced( + topology, + index_count as i32, + index_type, + index_offset as i32, + instance_count as i32, + ) + } + } else { + // If we've gotten here, wgpu-core has already validated that this function exists via the DownlevelFlags::BASE_VERTEX feature. + unsafe { + gl.draw_elements_instanced_base_vertex( + topology, + index_count as _, + index_type, + index_offset as i32, + instance_count as i32, + base_vertex, + ) + } + } + } + } + C::DrawIndirect { + topology, + indirect_buf, + indirect_offset, + ref first_instance_location, + } => { + unsafe { gl.uniform_1_u32(first_instance_location.as_ref(), 0) }; + + unsafe { gl.bind_buffer(glow::DRAW_INDIRECT_BUFFER, Some(indirect_buf)) }; + unsafe { gl.draw_arrays_indirect_offset(topology, indirect_offset as i32) }; + } + C::DrawIndexedIndirect { + topology, + index_type, + indirect_buf, + indirect_offset, + ref first_instance_location, + } => { + unsafe { gl.uniform_1_u32(first_instance_location.as_ref(), 0) }; + + unsafe { gl.bind_buffer(glow::DRAW_INDIRECT_BUFFER, Some(indirect_buf)) }; + unsafe { + gl.draw_elements_indirect_offset(topology, index_type, indirect_offset as i32) + }; + } + C::Dispatch(group_counts) => { + unsafe { gl.dispatch_compute(group_counts[0], group_counts[1], group_counts[2]) }; + } + C::DispatchIndirect { + indirect_buf, + indirect_offset, + } => { + unsafe { gl.bind_buffer(glow::DISPATCH_INDIRECT_BUFFER, Some(indirect_buf)) }; + unsafe { gl.dispatch_compute_indirect(indirect_offset as i32) }; + } + C::ClearBuffer { + ref dst, + dst_target, + ref range, + } => match dst.raw { + Some(buffer) => { + // When `INDEX_BUFFER_ROLE_CHANGE` isn't available, we can't copy into the + // index buffer from the zero buffer. This would fail in Chrome with the + // following message: + // + // > Cannot copy into an element buffer destination from a non-element buffer + // > source + // + // Instead, we'll upload zeroes into the buffer. + let can_use_zero_buffer = self + .shared + .private_caps + .contains(PrivateCapabilities::INDEX_BUFFER_ROLE_CHANGE) + || dst_target != glow::ELEMENT_ARRAY_BUFFER; + + if can_use_zero_buffer { + unsafe { gl.bind_buffer(glow::COPY_READ_BUFFER, Some(self.zero_buffer)) }; + unsafe { gl.bind_buffer(dst_target, Some(buffer)) }; + let mut dst_offset = range.start; + while dst_offset < range.end { + let size = (range.end - dst_offset).min(super::ZERO_BUFFER_SIZE as u64); + unsafe { + gl.copy_buffer_sub_data( + glow::COPY_READ_BUFFER, + dst_target, + 0, + dst_offset as i32, + size as i32, + ) + }; + dst_offset += size; + } + } else { + unsafe { gl.bind_buffer(dst_target, Some(buffer)) }; + let zeroes = vec![0u8; (range.end - range.start) as usize]; + unsafe { + gl.buffer_sub_data_u8_slice(dst_target, range.start as i32, &zeroes) + }; + } + } + None => { + let mut map_state = lock(&dst.map_state); + map_state.data.as_mut().unwrap().as_mut_slice() + [range.start as usize..range.end as usize] + .fill(0); + } + }, + C::CopyBufferToBuffer { + ref src, + src_target, + ref dst, + dst_target, + copy, + } => { + let copy_src_target = glow::COPY_READ_BUFFER; + let is_index_buffer_only_element_dst = !self + .shared + .private_caps + .contains(PrivateCapabilities::INDEX_BUFFER_ROLE_CHANGE) + && dst_target == glow::ELEMENT_ARRAY_BUFFER + || src_target == glow::ELEMENT_ARRAY_BUFFER; + + // WebGL not allowed to copy data from other targets to element buffer and can't copy element data to other buffers + let copy_dst_target = if is_index_buffer_only_element_dst { + glow::ELEMENT_ARRAY_BUFFER + } else { + glow::COPY_WRITE_BUFFER + }; + let size = copy.size.get() as usize; + match (src.raw, dst.raw) { + (Some(ref src), Some(ref dst)) => { + unsafe { gl.bind_buffer(copy_src_target, Some(*src)) }; + unsafe { gl.bind_buffer(copy_dst_target, Some(*dst)) }; + unsafe { + gl.copy_buffer_sub_data( + copy_src_target, + copy_dst_target, + copy.src_offset as _, + copy.dst_offset as _, + copy.size.get() as _, + ) + }; + } + (Some(src), None) => { + let mut map_state = lock(&dst.map_state); + let dst_data = &mut map_state.data.as_mut().unwrap().as_mut_slice() + [copy.dst_offset as usize..copy.dst_offset as usize + size]; + + unsafe { gl.bind_buffer(copy_src_target, Some(src)) }; + unsafe { + self.shared.get_buffer_sub_data( + gl, + copy_src_target, + copy.src_offset as i32, + dst_data, + ) + }; + } + (None, Some(dst)) => { + let map_state = lock(&src.map_state); + let src_data = &map_state.data.as_ref().unwrap().as_slice() + [copy.src_offset as usize..copy.src_offset as usize + size]; + unsafe { gl.bind_buffer(copy_dst_target, Some(dst)) }; + unsafe { + gl.buffer_sub_data_u8_slice( + copy_dst_target, + copy.dst_offset as i32, + src_data, + ) + }; + } + (None, None) => { + todo!() + } + } + unsafe { gl.bind_buffer(copy_src_target, None) }; + if is_index_buffer_only_element_dst { + unsafe { + gl.bind_buffer( + glow::ELEMENT_ARRAY_BUFFER, + *self.current_index_buffer.lock(), + ) + }; + } else { + unsafe { gl.bind_buffer(copy_dst_target, None) }; + } + } + #[cfg(webgl)] + C::CopyExternalImageToTexture { + ref src, + dst, + dst_target, + dst_format, + dst_premultiplication, + ref copy, + } => { + const UNPACK_FLIP_Y_WEBGL: u32 = + web_sys::WebGl2RenderingContext::UNPACK_FLIP_Y_WEBGL; + const UNPACK_PREMULTIPLY_ALPHA_WEBGL: u32 = + web_sys::WebGl2RenderingContext::UNPACK_PREMULTIPLY_ALPHA_WEBGL; + + unsafe { + if src.flip_y { + gl.pixel_store_bool(UNPACK_FLIP_Y_WEBGL, true); + } + if dst_premultiplication { + gl.pixel_store_bool(UNPACK_PREMULTIPLY_ALPHA_WEBGL, true); + } + } + + unsafe { gl.bind_texture(dst_target, Some(dst)) }; + let format_desc = self.shared.describe_texture_format(dst_format); + if is_layered_target(dst_target) { + let z_offset = get_z_offset(dst_target, &copy.dst_base); + + match src.source { + wgt::ExternalImageSource::ImageBitmap(ref b) => unsafe { + gl.tex_sub_image_3d_with_image_bitmap( + dst_target, + copy.dst_base.mip_level as i32, + copy.dst_base.origin.x as i32, + copy.dst_base.origin.y as i32, + z_offset as i32, + copy.size.width as i32, + copy.size.height as i32, + copy.size.depth as i32, + format_desc.external, + format_desc.data_type, + b, + ); + }, + wgt::ExternalImageSource::HTMLImageElement(ref i) => unsafe { + gl.tex_sub_image_3d_with_html_image_element( + dst_target, + copy.dst_base.mip_level as i32, + copy.dst_base.origin.x as i32, + copy.dst_base.origin.y as i32, + z_offset as i32, + copy.size.width as i32, + copy.size.height as i32, + copy.size.depth as i32, + format_desc.external, + format_desc.data_type, + i, + ); + }, + wgt::ExternalImageSource::HTMLVideoElement(ref v) => unsafe { + gl.tex_sub_image_3d_with_html_video_element( + dst_target, + copy.dst_base.mip_level as i32, + copy.dst_base.origin.x as i32, + copy.dst_base.origin.y as i32, + z_offset as i32, + copy.size.width as i32, + copy.size.height as i32, + copy.size.depth as i32, + format_desc.external, + format_desc.data_type, + v, + ); + }, + #[cfg(not(web_sys_unstable_apis))] + wgt::ExternalImageSource::VideoFrame(_) => { + unimplemented!("web_sys_unstable_apis is needed for glow") + } + #[cfg(web_sys_unstable_apis)] + wgt::ExternalImageSource::VideoFrame(ref v) => unsafe { + gl.tex_sub_image_3d_with_video_frame( + dst_target, + copy.dst_base.mip_level as i32, + copy.dst_base.origin.x as i32, + copy.dst_base.origin.y as i32, + z_offset as i32, + copy.size.width as i32, + copy.size.height as i32, + copy.size.depth as i32, + format_desc.external, + format_desc.data_type, + v, + ) + }, + wgt::ExternalImageSource::ImageData(ref i) => unsafe { + gl.tex_sub_image_3d_with_image_data( + dst_target, + copy.dst_base.mip_level as i32, + copy.dst_base.origin.x as i32, + copy.dst_base.origin.y as i32, + z_offset as i32, + copy.size.width as i32, + copy.size.height as i32, + copy.size.depth as i32, + format_desc.external, + format_desc.data_type, + i, + ); + }, + wgt::ExternalImageSource::HTMLCanvasElement(ref c) => unsafe { + gl.tex_sub_image_3d_with_html_canvas_element( + dst_target, + copy.dst_base.mip_level as i32, + copy.dst_base.origin.x as i32, + copy.dst_base.origin.y as i32, + z_offset as i32, + copy.size.width as i32, + copy.size.height as i32, + copy.size.depth as i32, + format_desc.external, + format_desc.data_type, + c, + ); + }, + wgt::ExternalImageSource::OffscreenCanvas(_) => unreachable!(), + } + } else { + let dst_target = get_2d_target(dst_target, copy.dst_base.array_layer); + + match src.source { + wgt::ExternalImageSource::ImageBitmap(ref b) => unsafe { + gl.tex_sub_image_2d_with_image_bitmap_and_width_and_height( + dst_target, + copy.dst_base.mip_level as i32, + copy.dst_base.origin.x as i32, + copy.dst_base.origin.y as i32, + copy.size.width as i32, + copy.size.height as i32, + format_desc.external, + format_desc.data_type, + b, + ); + }, + wgt::ExternalImageSource::HTMLImageElement(ref i) => unsafe { + gl.tex_sub_image_2d_with_html_image_and_width_and_height( + dst_target, + copy.dst_base.mip_level as i32, + copy.dst_base.origin.x as i32, + copy.dst_base.origin.y as i32, + copy.size.width as i32, + copy.size.height as i32, + format_desc.external, + format_desc.data_type, + i, + ) + }, + wgt::ExternalImageSource::HTMLVideoElement(ref v) => unsafe { + gl.tex_sub_image_2d_with_html_video_and_width_and_height( + dst_target, + copy.dst_base.mip_level as i32, + copy.dst_base.origin.x as i32, + copy.dst_base.origin.y as i32, + copy.size.width as i32, + copy.size.height as i32, + format_desc.external, + format_desc.data_type, + v, + ) + }, + #[cfg(not(web_sys_unstable_apis))] + wgt::ExternalImageSource::VideoFrame(_) => { + unimplemented!("web_sys_unstable_apis is needed for glow") + } + #[cfg(web_sys_unstable_apis)] + wgt::ExternalImageSource::VideoFrame(ref v) => unsafe { + gl.tex_sub_image_2d_with_video_frame_and_width_and_height( + dst_target, + copy.dst_base.mip_level as i32, + copy.dst_base.origin.x as i32, + copy.dst_base.origin.y as i32, + copy.size.width as i32, + copy.size.height as i32, + format_desc.external, + format_desc.data_type, + v, + ) + }, + wgt::ExternalImageSource::ImageData(ref i) => unsafe { + gl.tex_sub_image_2d_with_image_data_and_width_and_height( + dst_target, + copy.dst_base.mip_level as i32, + copy.dst_base.origin.x as i32, + copy.dst_base.origin.y as i32, + copy.size.width as i32, + copy.size.height as i32, + format_desc.external, + format_desc.data_type, + i, + ); + }, + wgt::ExternalImageSource::HTMLCanvasElement(ref c) => unsafe { + gl.tex_sub_image_2d_with_html_canvas_and_width_and_height( + dst_target, + copy.dst_base.mip_level as i32, + copy.dst_base.origin.x as i32, + copy.dst_base.origin.y as i32, + copy.size.width as i32, + copy.size.height as i32, + format_desc.external, + format_desc.data_type, + c, + ) + }, + wgt::ExternalImageSource::OffscreenCanvas(_) => unreachable!(), + } + } + + unsafe { + if src.flip_y { + gl.pixel_store_bool(UNPACK_FLIP_Y_WEBGL, false); + } + if dst_premultiplication { + gl.pixel_store_bool(UNPACK_PREMULTIPLY_ALPHA_WEBGL, false); + } + } + } + C::CopyTextureToTexture { + src, + src_target, + dst, + dst_target, + ref copy, + } => { + //TODO: handle 3D copies + unsafe { gl.bind_framebuffer(glow::READ_FRAMEBUFFER, Some(self.copy_fbo)) }; + if is_layered_target(src_target) { + //TODO: handle GLES without framebuffer_texture_3d + unsafe { + gl.framebuffer_texture_layer( + glow::READ_FRAMEBUFFER, + glow::COLOR_ATTACHMENT0, + Some(src), + copy.src_base.mip_level as i32, + copy.src_base.array_layer as i32, + ) + }; + } else { + unsafe { + gl.framebuffer_texture_2d( + glow::READ_FRAMEBUFFER, + glow::COLOR_ATTACHMENT0, + src_target, + Some(src), + copy.src_base.mip_level as i32, + ) + }; + } + + unsafe { gl.bind_texture(dst_target, Some(dst)) }; + if is_layered_target(dst_target) { + unsafe { + gl.copy_tex_sub_image_3d( + dst_target, + copy.dst_base.mip_level as i32, + copy.dst_base.origin.x as i32, + copy.dst_base.origin.y as i32, + get_z_offset(dst_target, &copy.dst_base) as i32, + copy.src_base.origin.x as i32, + copy.src_base.origin.y as i32, + copy.size.width as i32, + copy.size.height as i32, + ) + }; + } else { + unsafe { + gl.copy_tex_sub_image_2d( + get_2d_target(dst_target, copy.dst_base.array_layer), + copy.dst_base.mip_level as i32, + copy.dst_base.origin.x as i32, + copy.dst_base.origin.y as i32, + copy.src_base.origin.x as i32, + copy.src_base.origin.y as i32, + copy.size.width as i32, + copy.size.height as i32, + ) + }; + } + } + C::CopyBufferToTexture { + ref src, + src_target: _, + dst, + dst_target, + dst_format, + ref copy, + } => { + let (block_width, block_height) = dst_format.block_dimensions(); + let block_size = dst_format.block_copy_size(None).unwrap(); + let format_desc = self.shared.describe_texture_format(dst_format); + let row_texels = copy + .buffer_layout + .bytes_per_row + .map_or(0, |bpr| block_width * bpr / block_size); + let column_texels = copy + .buffer_layout + .rows_per_image + .map_or(0, |rpi| block_height * rpi); + + unsafe { gl.bind_texture(dst_target, Some(dst)) }; + unsafe { gl.pixel_store_i32(glow::UNPACK_ROW_LENGTH, row_texels as i32) }; + unsafe { gl.pixel_store_i32(glow::UNPACK_IMAGE_HEIGHT, column_texels as i32) }; + let mut unbind_unpack_buffer = false; + if !dst_format.is_compressed() { + let map_state; + let unpack_data = match src.raw { + Some(buffer) => { + unsafe { gl.bind_buffer(glow::PIXEL_UNPACK_BUFFER, Some(buffer)) }; + unbind_unpack_buffer = true; + glow::PixelUnpackData::BufferOffset(copy.buffer_layout.offset as u32) + } + None => { + map_state = lock(&src.map_state); + let src_data = &map_state.data.as_ref().unwrap().as_slice() + [copy.buffer_layout.offset as usize..]; + glow::PixelUnpackData::Slice(Some(src_data)) + } + }; + if is_layered_target(dst_target) { + unsafe { + gl.tex_sub_image_3d( + dst_target, + copy.texture_base.mip_level as i32, + copy.texture_base.origin.x as i32, + copy.texture_base.origin.y as i32, + get_z_offset(dst_target, &copy.texture_base) as i32, + copy.size.width as i32, + copy.size.height as i32, + copy.size.depth as i32, + format_desc.external, + format_desc.data_type, + unpack_data, + ) + }; + } else { + unsafe { + gl.tex_sub_image_2d( + get_2d_target(dst_target, copy.texture_base.array_layer), + copy.texture_base.mip_level as i32, + copy.texture_base.origin.x as i32, + copy.texture_base.origin.y as i32, + copy.size.width as i32, + copy.size.height as i32, + format_desc.external, + format_desc.data_type, + unpack_data, + ) + }; + } + } else { + let bytes_per_row = copy + .buffer_layout + .bytes_per_row + .unwrap_or(copy.size.width * block_size); + let minimum_rows_per_image = copy.size.height.div_ceil(block_height); + let rows_per_image = copy + .buffer_layout + .rows_per_image + .unwrap_or(minimum_rows_per_image); + + let bytes_per_image = bytes_per_row * rows_per_image; + let minimum_bytes_per_image = bytes_per_row * minimum_rows_per_image; + let bytes_in_upload = + (bytes_per_image * (copy.size.depth - 1)) + minimum_bytes_per_image; + let offset = copy.buffer_layout.offset as u32; + + let map_state; + let unpack_data = match src.raw { + Some(buffer) => { + unsafe { gl.bind_buffer(glow::PIXEL_UNPACK_BUFFER, Some(buffer)) }; + unbind_unpack_buffer = true; + glow::CompressedPixelUnpackData::BufferRange( + offset..offset + bytes_in_upload, + ) + } + None => { + map_state = lock(&src.map_state); + let src_data = &map_state.data.as_ref().unwrap().as_slice() + [(offset as usize)..(offset + bytes_in_upload) as usize]; + glow::CompressedPixelUnpackData::Slice(src_data) + } + }; + + if is_layered_target(dst_target) { + unsafe { + gl.compressed_tex_sub_image_3d( + dst_target, + copy.texture_base.mip_level as i32, + copy.texture_base.origin.x as i32, + copy.texture_base.origin.y as i32, + get_z_offset(dst_target, &copy.texture_base) as i32, + copy.size.width as i32, + copy.size.height as i32, + copy.size.depth as i32, + format_desc.internal, + unpack_data, + ) + }; + } else { + unsafe { + gl.compressed_tex_sub_image_2d( + get_2d_target(dst_target, copy.texture_base.array_layer), + copy.texture_base.mip_level as i32, + copy.texture_base.origin.x as i32, + copy.texture_base.origin.y as i32, + copy.size.width as i32, + copy.size.height as i32, + format_desc.internal, + unpack_data, + ) + }; + } + } + if unbind_unpack_buffer { + unsafe { gl.bind_buffer(glow::PIXEL_UNPACK_BUFFER, None) }; + } + } + C::CopyTextureToBuffer { + src, + src_target, + src_format, + ref dst, + dst_target: _, + ref copy, + } => { + let block_size = src_format.block_copy_size(None).unwrap(); + if src_format.is_compressed() { + log::error!("Not implemented yet: compressed texture copy to buffer"); + return; + } + if src_target == glow::TEXTURE_CUBE_MAP + || src_target == glow::TEXTURE_CUBE_MAP_ARRAY + { + log::error!("Not implemented yet: cubemap texture copy to buffer"); + return; + } + let format_desc = self.shared.describe_texture_format(src_format); + let row_texels = copy + .buffer_layout + .bytes_per_row + .map_or(copy.size.width, |bpr| bpr / block_size); + let column_texels = copy + .buffer_layout + .rows_per_image + .unwrap_or(copy.size.height); + + unsafe { gl.bind_framebuffer(glow::READ_FRAMEBUFFER, Some(self.copy_fbo)) }; + + let read_pixels = |offset| { + let mut map_state; + let unpack_data = match dst.raw { + Some(buffer) => { + unsafe { gl.pixel_store_i32(glow::PACK_ROW_LENGTH, row_texels as i32) }; + unsafe { gl.bind_buffer(glow::PIXEL_PACK_BUFFER, Some(buffer)) }; + glow::PixelPackData::BufferOffset(offset as u32) + } + None => { + map_state = lock(&dst.map_state); + let dst_data = &mut map_state.data.as_mut().unwrap().as_mut_slice() + [offset as usize..]; + glow::PixelPackData::Slice(Some(dst_data)) + } + }; + unsafe { + gl.read_pixels( + copy.texture_base.origin.x as i32, + copy.texture_base.origin.y as i32, + copy.size.width as i32, + copy.size.height as i32, + format_desc.external, + format_desc.data_type, + unpack_data, + ) + }; + }; + + match src_target { + glow::TEXTURE_2D => { + unsafe { + gl.framebuffer_texture_2d( + glow::READ_FRAMEBUFFER, + glow::COLOR_ATTACHMENT0, + src_target, + Some(src), + copy.texture_base.mip_level as i32, + ) + }; + read_pixels(copy.buffer_layout.offset); + } + glow::TEXTURE_2D_ARRAY => { + unsafe { + gl.framebuffer_texture_layer( + glow::READ_FRAMEBUFFER, + glow::COLOR_ATTACHMENT0, + Some(src), + copy.texture_base.mip_level as i32, + copy.texture_base.array_layer as i32, + ) + }; + read_pixels(copy.buffer_layout.offset); + } + glow::TEXTURE_3D => { + for z in copy.texture_base.origin.z..copy.size.depth { + unsafe { + gl.framebuffer_texture_layer( + glow::READ_FRAMEBUFFER, + glow::COLOR_ATTACHMENT0, + Some(src), + copy.texture_base.mip_level as i32, + z as i32, + ) + }; + let offset = copy.buffer_layout.offset + + (z * block_size * row_texels * column_texels) as u64; + read_pixels(offset); + } + } + glow::TEXTURE_CUBE_MAP | glow::TEXTURE_CUBE_MAP_ARRAY => unimplemented!(), + _ => unreachable!(), + } + } + C::SetIndexBuffer(buffer) => { + unsafe { gl.bind_buffer(glow::ELEMENT_ARRAY_BUFFER, Some(buffer)) }; + let mut current_index_buffer = self.current_index_buffer.lock(); + *current_index_buffer = Some(buffer); + } + C::BeginQuery(query, target) => { + unsafe { gl.begin_query(target, query) }; + } + C::EndQuery(target) => { + unsafe { gl.end_query(target) }; + } + C::TimestampQuery(query) => { + unsafe { gl.query_counter(query, glow::TIMESTAMP) }; + } + C::CopyQueryResults { + ref query_range, + ref dst, + dst_target, + dst_offset, + } => { + if self + .shared + .private_caps + .contains(PrivateCapabilities::QUERY_BUFFERS) + && dst.raw.is_some() + { + unsafe { + // We're assuming that the only relevant queries are 8 byte timestamps or + // occlusion tests. + let query_size = 8; + + let query_range_size = query_size * query_range.len(); + + let buffer = gl.create_buffer().ok(); + gl.bind_buffer(glow::QUERY_BUFFER, buffer); + gl.buffer_data_size( + glow::QUERY_BUFFER, + query_range_size as _, + glow::STREAM_COPY, + ); + + for (i, &query) in queries + [query_range.start as usize..query_range.end as usize] + .iter() + .enumerate() + { + gl.get_query_parameter_u64_with_offset( + query, + glow::QUERY_RESULT, + query_size * i, + ) + } + gl.bind_buffer(dst_target, dst.raw); + gl.copy_buffer_sub_data( + glow::QUERY_BUFFER, + dst_target, + 0, + dst_offset as _, + query_range_size as _, + ); + if let Some(buffer) = buffer { + gl.delete_buffer(buffer) + } + } + } else { + let mut temp_query_results = self.temp_query_results.lock(); + temp_query_results.clear(); + for &query in + queries[query_range.start as usize..query_range.end as usize].iter() + { + let mut result: u64 = 0; + unsafe { + if self + .shared + .private_caps + .contains(PrivateCapabilities::QUERY_64BIT) + { + let result: *mut u64 = &mut result; + gl.get_query_parameter_u64_with_offset( + query, + glow::QUERY_RESULT, + result as usize, + ) + } else { + result = + gl.get_query_parameter_u32(query, glow::QUERY_RESULT) as u64; + } + }; + temp_query_results.push(result); + } + let query_data = bytemuck::cast_slice(&temp_query_results); + match dst.raw { + Some(buffer) => { + unsafe { gl.bind_buffer(dst_target, Some(buffer)) }; + unsafe { + gl.buffer_sub_data_u8_slice( + dst_target, + dst_offset as i32, + query_data, + ) + }; + } + None => { + let mut map_state = lock(&dst.map_state); + let data = map_state.data.as_mut().unwrap(); + let len = query_data.len().min(data.len()); + data[..len].copy_from_slice(&query_data[..len]); + } + } + } + } + C::ResetFramebuffer { is_default } => { + if is_default { + unsafe { gl.bind_framebuffer(glow::DRAW_FRAMEBUFFER, None) }; + } else { + unsafe { gl.bind_framebuffer(glow::DRAW_FRAMEBUFFER, Some(self.draw_fbo)) }; + unsafe { + gl.framebuffer_texture_2d( + glow::DRAW_FRAMEBUFFER, + glow::DEPTH_STENCIL_ATTACHMENT, + glow::TEXTURE_2D, + None, + 0, + ) + }; + for i in 0..self.shared.limits.max_color_attachments { + let target = glow::COLOR_ATTACHMENT0 + i; + unsafe { + gl.framebuffer_texture_2d( + glow::DRAW_FRAMEBUFFER, + target, + glow::TEXTURE_2D, + None, + 0, + ) + }; + } + } + unsafe { gl.color_mask(true, true, true, true) }; + unsafe { gl.depth_mask(true) }; + unsafe { gl.stencil_mask(!0) }; + unsafe { gl.disable(glow::DEPTH_TEST) }; + unsafe { gl.disable(glow::STENCIL_TEST) }; + unsafe { gl.disable(glow::SCISSOR_TEST) }; + } + C::BindAttachment { + attachment, + ref view, + depth_slice, + sample_count, + } => { + unsafe { + self.set_attachment( + gl, + glow::DRAW_FRAMEBUFFER, + attachment, + view, + depth_slice, + sample_count, + ) + }; + } + C::ResolveAttachment { + attachment, + ref dst, + ref size, + } => { + unsafe { gl.bind_framebuffer(glow::READ_FRAMEBUFFER, Some(self.draw_fbo)) }; + unsafe { gl.read_buffer(attachment) }; + unsafe { gl.bind_framebuffer(glow::DRAW_FRAMEBUFFER, Some(self.copy_fbo)) }; + unsafe { + self.set_attachment( + gl, + glow::DRAW_FRAMEBUFFER, + glow::COLOR_ATTACHMENT0, + dst, + None, + 1, + ) + }; + unsafe { + gl.blit_framebuffer( + 0, + 0, + size.width as i32, + size.height as i32, + 0, + 0, + size.width as i32, + size.height as i32, + glow::COLOR_BUFFER_BIT, + glow::NEAREST, + ) + }; + unsafe { gl.bind_framebuffer(glow::READ_FRAMEBUFFER, None) }; + unsafe { gl.bind_framebuffer(glow::DRAW_FRAMEBUFFER, Some(self.draw_fbo)) }; + } + C::InvalidateAttachments(ref list) => { + if self + .shared + .private_caps + .contains(PrivateCapabilities::INVALIDATE_FRAMEBUFFER) + { + unsafe { gl.invalidate_framebuffer(glow::DRAW_FRAMEBUFFER, list) }; + } + } + C::SetDrawColorBuffers(count) => { + self.draw_buffer_count.store(count, Ordering::Relaxed); + let indices = (0..count as u32) + .map(|i| glow::COLOR_ATTACHMENT0 + i) + .collect::<ArrayVec<_, { crate::MAX_COLOR_ATTACHMENTS }>>(); + unsafe { gl.draw_buffers(&indices) }; + } + C::ClearColorF { + draw_buffer, + ref color, + is_srgb, + } => { + if self + .shared + .workarounds + .contains(super::Workarounds::MESA_I915_SRGB_SHADER_CLEAR) + && is_srgb + { + unsafe { self.perform_shader_clear(gl, draw_buffer, *color) }; + } else { + unsafe { gl.clear_buffer_f32_slice(glow::COLOR, draw_buffer, color) }; + } + } + C::ClearColorU(draw_buffer, ref color) => { + unsafe { gl.clear_buffer_u32_slice(glow::COLOR, draw_buffer, color) }; + } + C::ClearColorI(draw_buffer, ref color) => { + unsafe { gl.clear_buffer_i32_slice(glow::COLOR, draw_buffer, color) }; + } + C::ClearDepth(depth) => { + // Prefer `clear` as `clear_buffer` functions have issues on Sandy Bridge + // on Windows. + unsafe { + gl.clear_depth_f32(depth); + gl.clear(glow::DEPTH_BUFFER_BIT); + } + } + C::ClearStencil(value) => { + // Prefer `clear` as `clear_buffer` functions have issues on Sandy Bridge + // on Windows. + unsafe { + gl.clear_stencil(value as i32); + gl.clear(glow::STENCIL_BUFFER_BIT); + } + } + C::ClearDepthAndStencil(depth, stencil_value) => { + // Prefer `clear` as `clear_buffer` functions have issues on Sandy Bridge + // on Windows. + unsafe { + gl.clear_depth_f32(depth); + gl.clear_stencil(stencil_value as i32); + gl.clear(glow::DEPTH_BUFFER_BIT | glow::STENCIL_BUFFER_BIT); + } + } + C::BufferBarrier(raw, usage) => { + let mut flags = 0; + if usage.contains(wgt::BufferUses::VERTEX) { + flags |= glow::VERTEX_ATTRIB_ARRAY_BARRIER_BIT; + unsafe { gl.bind_buffer(glow::ARRAY_BUFFER, Some(raw)) }; + unsafe { gl.vertex_attrib_pointer_f32(0, 1, glow::BYTE, true, 0, 0) }; + } + if usage.contains(wgt::BufferUses::INDEX) { + flags |= glow::ELEMENT_ARRAY_BARRIER_BIT; + unsafe { gl.bind_buffer(glow::ELEMENT_ARRAY_BUFFER, Some(raw)) }; + } + if usage.contains(wgt::BufferUses::UNIFORM) { + flags |= glow::UNIFORM_BARRIER_BIT; + } + if usage.contains(wgt::BufferUses::INDIRECT) { + flags |= glow::COMMAND_BARRIER_BIT; + unsafe { gl.bind_buffer(glow::DRAW_INDIRECT_BUFFER, Some(raw)) }; + } + if usage.contains(wgt::BufferUses::COPY_SRC) { + flags |= glow::PIXEL_BUFFER_BARRIER_BIT; + unsafe { gl.bind_buffer(glow::PIXEL_UNPACK_BUFFER, Some(raw)) }; + } + if usage.contains(wgt::BufferUses::COPY_DST) { + flags |= glow::PIXEL_BUFFER_BARRIER_BIT; + unsafe { gl.bind_buffer(glow::PIXEL_PACK_BUFFER, Some(raw)) }; + } + if usage.intersects(wgt::BufferUses::MAP_READ | wgt::BufferUses::MAP_WRITE) { + flags |= glow::BUFFER_UPDATE_BARRIER_BIT; + } + if usage.intersects( + wgt::BufferUses::STORAGE_READ_ONLY | wgt::BufferUses::STORAGE_READ_WRITE, + ) { + flags |= glow::SHADER_STORAGE_BARRIER_BIT; + } + unsafe { gl.memory_barrier(flags) }; + } + // because `STORAGE_WRITE_ONLY` and `STORAGE_READ_WRITE` are only states + // we can transit from due OpenGL memory barriers are used to make _subsequent_ + // operations see changes from the _shader_ side. We filter out usage changes that are + // does not comes from the shader side in `transition_textures` + C::TextureBarrier(usage) => { + let mut flags = 0; + if usage.contains(wgt::TextureUses::RESOURCE) { + flags |= glow::TEXTURE_FETCH_BARRIER_BIT; + } + if usage.intersects( + wgt::TextureUses::STORAGE_READ_ONLY + | wgt::TextureUses::STORAGE_WRITE_ONLY + | wgt::TextureUses::STORAGE_READ_WRITE, + ) { + flags |= glow::SHADER_IMAGE_ACCESS_BARRIER_BIT; + } + if usage.intersects(wgt::TextureUses::COPY_SRC) { + flags |= glow::PIXEL_BUFFER_BARRIER_BIT; + } + if usage.contains(wgt::TextureUses::COPY_DST) { + flags |= glow::TEXTURE_UPDATE_BARRIER_BIT; + } + if usage.intersects( + wgt::TextureUses::COLOR_TARGET + | wgt::TextureUses::DEPTH_STENCIL_READ + | wgt::TextureUses::DEPTH_STENCIL_WRITE, + ) { + flags |= glow::FRAMEBUFFER_BARRIER_BIT; + } + unsafe { gl.memory_barrier(flags) }; + } + C::SetViewport { + ref rect, + ref depth, + } => { + unsafe { gl.viewport(rect.x, rect.y, rect.w, rect.h) }; + unsafe { gl.depth_range_f32(depth.start, depth.end) }; + } + C::SetScissor(ref rect) => { + unsafe { gl.scissor(rect.x, rect.y, rect.w, rect.h) }; + unsafe { gl.enable(glow::SCISSOR_TEST) }; + } + C::SetStencilFunc { + face, + function, + reference, + read_mask, + } => { + unsafe { gl.stencil_func_separate(face, function, reference as i32, read_mask) }; + } + C::SetStencilOps { + face, + write_mask, + ref ops, + } => { + unsafe { gl.stencil_mask_separate(face, write_mask) }; + unsafe { gl.stencil_op_separate(face, ops.fail, ops.depth_fail, ops.pass) }; + } + C::SetVertexAttribute { + buffer, + ref buffer_desc, + attribute_desc: ref vat, + } => { + unsafe { gl.bind_buffer(glow::ARRAY_BUFFER, buffer) }; + unsafe { gl.enable_vertex_attrib_array(vat.location) }; + + if buffer.is_none() { + match vat.format_desc.attrib_kind { + super::VertexAttribKind::Float => unsafe { + gl.vertex_attrib_format_f32( + vat.location, + vat.format_desc.element_count, + vat.format_desc.element_format, + true, // always normalized + vat.offset, + ) + }, + super::VertexAttribKind::Integer => unsafe { + gl.vertex_attrib_format_i32( + vat.location, + vat.format_desc.element_count, + vat.format_desc.element_format, + vat.offset, + ) + }, + } + + //Note: there is apparently a bug on AMD 3500U: + // this call is ignored if the current array is disabled. + unsafe { gl.vertex_attrib_binding(vat.location, vat.buffer_index) }; + } else { + match vat.format_desc.attrib_kind { + super::VertexAttribKind::Float => unsafe { + gl.vertex_attrib_pointer_f32( + vat.location, + vat.format_desc.element_count, + vat.format_desc.element_format, + true, // always normalized + buffer_desc.stride as i32, + vat.offset as i32, + ) + }, + super::VertexAttribKind::Integer => unsafe { + gl.vertex_attrib_pointer_i32( + vat.location, + vat.format_desc.element_count, + vat.format_desc.element_format, + buffer_desc.stride as i32, + vat.offset as i32, + ) + }, + } + unsafe { gl.vertex_attrib_divisor(vat.location, buffer_desc.step as u32) }; + } + } + C::UnsetVertexAttribute(location) => { + unsafe { gl.disable_vertex_attrib_array(location) }; + } + C::SetVertexBuffer { + index, + ref buffer, + ref buffer_desc, + } => { + unsafe { gl.vertex_binding_divisor(index, buffer_desc.step as u32) }; + unsafe { + gl.bind_vertex_buffer( + index, + Some(buffer.raw), + buffer.offset as i32, + buffer_desc.stride as i32, + ) + }; + } + C::SetDepth(ref depth) => { + unsafe { gl.depth_func(depth.function) }; + unsafe { gl.depth_mask(depth.mask) }; + } + C::SetDepthBias(bias) => { + if bias.is_enabled() { + unsafe { gl.enable(glow::POLYGON_OFFSET_FILL) }; + unsafe { gl.polygon_offset(bias.slope_scale, bias.constant as f32) }; + } else { + unsafe { gl.disable(glow::POLYGON_OFFSET_FILL) }; + } + } + C::ConfigureDepthStencil(aspects) => { + if aspects.contains(crate::FormatAspects::DEPTH) { + unsafe { gl.enable(glow::DEPTH_TEST) }; + } else { + unsafe { gl.disable(glow::DEPTH_TEST) }; + } + if aspects.contains(crate::FormatAspects::STENCIL) { + unsafe { gl.enable(glow::STENCIL_TEST) }; + } else { + unsafe { gl.disable(glow::STENCIL_TEST) }; + } + } + C::SetAlphaToCoverage(enabled) => { + if enabled { + unsafe { gl.enable(glow::SAMPLE_ALPHA_TO_COVERAGE) }; + } else { + unsafe { gl.disable(glow::SAMPLE_ALPHA_TO_COVERAGE) }; + } + } + C::SetProgram(program) => { + unsafe { gl.use_program(Some(program)) }; + } + C::SetPrimitive(ref state) => { + unsafe { gl.front_face(state.front_face) }; + if state.cull_face != 0 { + unsafe { gl.enable(glow::CULL_FACE) }; + unsafe { gl.cull_face(state.cull_face) }; + } else { + unsafe { gl.disable(glow::CULL_FACE) }; + } + if self.features.contains(wgt::Features::DEPTH_CLIP_CONTROL) { + //Note: this is a bit tricky, since we are controlling the clip, not the clamp. + if state.unclipped_depth { + unsafe { gl.enable(glow::DEPTH_CLAMP) }; + } else { + unsafe { gl.disable(glow::DEPTH_CLAMP) }; + } + } + // POLYGON_MODE_LINE also implies POLYGON_MODE_POINT + if self.features.contains(wgt::Features::POLYGON_MODE_LINE) { + unsafe { gl.polygon_mode(glow::FRONT_AND_BACK, state.polygon_mode) }; + } + } + C::SetBlendConstant(c) => { + unsafe { gl.blend_color(c[0], c[1], c[2], c[3]) }; + } + C::SetColorTarget { + draw_buffer_index, + desc: super::ColorTargetDesc { mask, ref blend }, + } => { + use wgt::ColorWrites as Cw; + if let Some(index) = draw_buffer_index { + unsafe { + gl.color_mask_draw_buffer( + index, + mask.contains(Cw::RED), + mask.contains(Cw::GREEN), + mask.contains(Cw::BLUE), + mask.contains(Cw::ALPHA), + ) + }; + if let Some(ref blend) = *blend { + unsafe { gl.enable_draw_buffer(glow::BLEND, index) }; + if blend.color != blend.alpha { + unsafe { + gl.blend_equation_separate_draw_buffer( + index, + blend.color.equation, + blend.alpha.equation, + ) + }; + unsafe { + gl.blend_func_separate_draw_buffer( + index, + blend.color.src, + blend.color.dst, + blend.alpha.src, + blend.alpha.dst, + ) + }; + } else { + unsafe { gl.blend_equation_draw_buffer(index, blend.color.equation) }; + unsafe { + gl.blend_func_draw_buffer(index, blend.color.src, blend.color.dst) + }; + } + } else { + unsafe { gl.disable_draw_buffer(glow::BLEND, index) }; + } + } else { + unsafe { + gl.color_mask( + mask.contains(Cw::RED), + mask.contains(Cw::GREEN), + mask.contains(Cw::BLUE), + mask.contains(Cw::ALPHA), + ) + }; + if let Some(ref blend) = *blend { + unsafe { gl.enable(glow::BLEND) }; + if blend.color != blend.alpha { + unsafe { + gl.blend_equation_separate( + blend.color.equation, + blend.alpha.equation, + ) + }; + unsafe { + gl.blend_func_separate( + blend.color.src, + blend.color.dst, + blend.alpha.src, + blend.alpha.dst, + ) + }; + } else { + unsafe { gl.blend_equation(blend.color.equation) }; + unsafe { gl.blend_func(blend.color.src, blend.color.dst) }; + } + } else { + unsafe { gl.disable(glow::BLEND) }; + } + } + } + C::BindBuffer { + target, + slot, + buffer, + offset, + size, + } => { + unsafe { gl.bind_buffer_range(target, slot, Some(buffer), offset, size) }; + } + C::BindSampler(texture_index, sampler) => { + unsafe { gl.bind_sampler(texture_index, sampler) }; + } + C::BindTexture { + slot, + texture, + target, + aspects, + ref mip_levels, + } => { + unsafe { gl.active_texture(glow::TEXTURE0 + slot) }; + unsafe { gl.bind_texture(target, Some(texture)) }; + + unsafe { + gl.tex_parameter_i32(target, glow::TEXTURE_BASE_LEVEL, mip_levels.start as i32) + }; + unsafe { + gl.tex_parameter_i32( + target, + glow::TEXTURE_MAX_LEVEL, + (mip_levels.end - 1) as i32, + ) + }; + + let version = gl.version(); + let is_min_es_3_1 = version.is_embedded && (version.major, version.minor) >= (3, 1); + let is_min_4_3 = !version.is_embedded && (version.major, version.minor) >= (4, 3); + if is_min_es_3_1 || is_min_4_3 { + let mode = match aspects { + crate::FormatAspects::DEPTH => Some(glow::DEPTH_COMPONENT), + crate::FormatAspects::STENCIL => Some(glow::STENCIL_INDEX), + _ => None, + }; + if let Some(mode) = mode { + unsafe { + gl.tex_parameter_i32( + target, + glow::DEPTH_STENCIL_TEXTURE_MODE, + mode as _, + ) + }; + } + } + } + C::BindImage { slot, ref binding } => { + unsafe { + gl.bind_image_texture( + slot, + Some(binding.raw), + binding.mip_level as i32, + binding.array_layer.is_none(), + binding.array_layer.unwrap_or_default() as i32, + binding.access, + binding.format, + ) + }; + } + C::InsertDebugMarker(ref range) => { + let marker = extract_marker(data_bytes, range); + unsafe { + if self + .shared + .private_caps + .contains(PrivateCapabilities::DEBUG_FNS) + { + gl.debug_message_insert( + glow::DEBUG_SOURCE_APPLICATION, + glow::DEBUG_TYPE_MARKER, + DEBUG_ID, + glow::DEBUG_SEVERITY_NOTIFICATION, + to_debug_str(marker), + ) + } + }; + } + C::PushDebugGroup(ref range) => { + let marker = extract_marker(data_bytes, range); + unsafe { + if self + .shared + .private_caps + .contains(PrivateCapabilities::DEBUG_FNS) + { + gl.push_debug_group( + glow::DEBUG_SOURCE_APPLICATION, + DEBUG_ID, + to_debug_str(marker), + ) + } + }; + } + C::PopDebugGroup => { + unsafe { + if self + .shared + .private_caps + .contains(PrivateCapabilities::DEBUG_FNS) + { + gl.pop_debug_group() + } + }; + } + C::SetImmediates { + ref uniform, + offset, + } => { + fn get_data<T, const COUNT: usize>(data: &[u8], offset: u32) -> [T; COUNT] + where + [T; COUNT]: bytemuck::AnyBitPattern, + { + let data_required = size_of::<T>() * COUNT; + let raw = &data[(offset as usize)..][..data_required]; + bytemuck::pod_read_unaligned(raw) + } + + let location = Some(&uniform.location); + use nt::glsl::{GlslScalar, GlslUniformType, GlslVectorSize}; + match uniform.ty { + // + // --- Float 1-4 Component --- + // + GlslUniformType::Scalar(GlslScalar::F32) => { + let data = get_data::<f32, 1>(data_bytes, offset)[0]; + unsafe { gl.uniform_1_f32(location, data) }; + } + GlslUniformType::Vector { + size: GlslVectorSize::Bi, + scalar: GlslScalar::F32, + } => { + let data = &get_data::<f32, 2>(data_bytes, offset); + unsafe { gl.uniform_2_f32_slice(location, data) }; + } + GlslUniformType::Vector { + size: GlslVectorSize::Tri, + scalar: GlslScalar::F32, + } => { + let data = &get_data::<f32, 3>(data_bytes, offset); + unsafe { gl.uniform_3_f32_slice(location, data) }; + } + GlslUniformType::Vector { + size: GlslVectorSize::Quad, + scalar: GlslScalar::F32, + } => { + let data = &get_data::<f32, 4>(data_bytes, offset); + unsafe { gl.uniform_4_f32_slice(location, data) }; + } + + // + // --- Int 1-4 Component --- + // + GlslUniformType::Scalar(GlslScalar::I32) => { + let data = get_data::<i32, 1>(data_bytes, offset)[0]; + unsafe { gl.uniform_1_i32(location, data) }; + } + GlslUniformType::Vector { + size: GlslVectorSize::Bi, + scalar: GlslScalar::I32, + } => { + let data = &get_data::<i32, 2>(data_bytes, offset); + unsafe { gl.uniform_2_i32_slice(location, data) }; + } + GlslUniformType::Vector { + size: GlslVectorSize::Tri, + scalar: GlslScalar::I32, + } => { + let data = &get_data::<i32, 3>(data_bytes, offset); + unsafe { gl.uniform_3_i32_slice(location, data) }; + } + GlslUniformType::Vector { + size: GlslVectorSize::Quad, + scalar: GlslScalar::I32, + } => { + let data = &get_data::<i32, 4>(data_bytes, offset); + unsafe { gl.uniform_4_i32_slice(location, data) }; + } + + // + // --- Uint 1-4 Component --- + // + GlslUniformType::Scalar(GlslScalar::U32) => { + let data = get_data::<u32, 1>(data_bytes, offset)[0]; + unsafe { gl.uniform_1_u32(location, data) }; + } + GlslUniformType::Vector { + size: GlslVectorSize::Bi, + scalar: GlslScalar::U32, + } => { + let data = &get_data::<u32, 2>(data_bytes, offset); + unsafe { gl.uniform_2_u32_slice(location, data) }; + } + GlslUniformType::Vector { + size: GlslVectorSize::Tri, + scalar: GlslScalar::U32, + } => { + let data = &get_data::<u32, 3>(data_bytes, offset); + unsafe { gl.uniform_3_u32_slice(location, data) }; + } + GlslUniformType::Vector { + size: GlslVectorSize::Quad, + scalar: GlslScalar::U32, + } => { + let data = &get_data::<u32, 4>(data_bytes, offset); + unsafe { gl.uniform_4_u32_slice(location, data) }; + } + + // + // --- Matrix 2xR --- + // + GlslUniformType::Matrix { + columns: GlslVectorSize::Bi, + rows: GlslVectorSize::Bi, + scalar: GlslScalar::F32, + } => { + let data = &get_data::<f32, 4>(data_bytes, offset); + unsafe { gl.uniform_matrix_2_f32_slice(location, false, data) }; + } + GlslUniformType::Matrix { + columns: GlslVectorSize::Bi, + rows: GlslVectorSize::Tri, + scalar: GlslScalar::F32, + } => { + // repack 2 vec3s into 6 values. + let unpacked_data = &get_data::<f32, 8>(data_bytes, offset); + #[rustfmt::skip] + let packed_data = [ + unpacked_data[0], unpacked_data[1], unpacked_data[2], + unpacked_data[4], unpacked_data[5], unpacked_data[6], + ]; + unsafe { gl.uniform_matrix_2x3_f32_slice(location, false, &packed_data) }; + } + GlslUniformType::Matrix { + columns: GlslVectorSize::Bi, + rows: GlslVectorSize::Quad, + scalar: GlslScalar::F32, + } => { + let data = &get_data::<f32, 8>(data_bytes, offset); + unsafe { gl.uniform_matrix_2x4_f32_slice(location, false, data) }; + } + + // + // --- Matrix 3xR --- + // + GlslUniformType::Matrix { + columns: GlslVectorSize::Tri, + rows: GlslVectorSize::Bi, + scalar: GlslScalar::F32, + } => { + let data = &get_data::<f32, 6>(data_bytes, offset); + unsafe { gl.uniform_matrix_3x2_f32_slice(location, false, data) }; + } + GlslUniformType::Matrix { + columns: GlslVectorSize::Tri, + rows: GlslVectorSize::Tri, + scalar: GlslScalar::F32, + } => { + // repack 3 vec3s into 9 values. + let unpacked_data = &get_data::<f32, 12>(data_bytes, offset); + #[rustfmt::skip] + let packed_data = [ + unpacked_data[0], unpacked_data[1], unpacked_data[2], + unpacked_data[4], unpacked_data[5], unpacked_data[6], + unpacked_data[8], unpacked_data[9], unpacked_data[10], + ]; + unsafe { gl.uniform_matrix_3_f32_slice(location, false, &packed_data) }; + } + GlslUniformType::Matrix { + columns: GlslVectorSize::Tri, + rows: GlslVectorSize::Quad, + scalar: GlslScalar::F32, + } => { + let data = &get_data::<f32, 12>(data_bytes, offset); + unsafe { gl.uniform_matrix_3x4_f32_slice(location, false, data) }; + } + + // + // --- Matrix 4xR --- + // + GlslUniformType::Matrix { + columns: GlslVectorSize::Quad, + rows: GlslVectorSize::Bi, + scalar: GlslScalar::F32, + } => { + let data = &get_data::<f32, 8>(data_bytes, offset); + unsafe { gl.uniform_matrix_4x2_f32_slice(location, false, data) }; + } + GlslUniformType::Matrix { + columns: GlslVectorSize::Quad, + rows: GlslVectorSize::Tri, + scalar: GlslScalar::F32, + } => { + // repack 4 vec3s into 12 values. + let unpacked_data = &get_data::<f32, 16>(data_bytes, offset); + #[rustfmt::skip] + let packed_data = [ + unpacked_data[0], unpacked_data[1], unpacked_data[2], + unpacked_data[4], unpacked_data[5], unpacked_data[6], + unpacked_data[8], unpacked_data[9], unpacked_data[10], + unpacked_data[12], unpacked_data[13], unpacked_data[14], + ]; + unsafe { gl.uniform_matrix_4x3_f32_slice(location, false, &packed_data) }; + } + GlslUniformType::Matrix { + columns: GlslVectorSize::Quad, + rows: GlslVectorSize::Quad, + scalar: GlslScalar::F32, + } => { + let data = &get_data::<f32, 16>(data_bytes, offset); + unsafe { gl.uniform_matrix_4_f32_slice(location, false, data) }; + } + _ => panic!("Unsupported uniform datatype: {:?}!", uniform.ty), + } + } + C::SetClipDistances { + old_count, + new_count, + } => { + // Disable clip planes that are no longer active + for i in new_count..old_count { + unsafe { gl.disable(glow::CLIP_DISTANCE0 + i) }; + } + + // Enable clip planes that are now active + for i in old_count..new_count { + unsafe { gl.enable(glow::CLIP_DISTANCE0 + i) }; + } + } + } + } +} + +impl crate::Queue for super::Queue { + type A = super::Api; + + unsafe fn submit( + &self, + command_buffers: &[&super::CommandBuffer], + _surface_textures: &[&super::Texture], + (signal_fence, signal_value): (&super::Fence, crate::FenceValue), + ) -> Result<(), crate::DeviceError> { + let shared = Arc::clone(&self.shared); + let gl = &shared.context.lock(); + for cmd_buf in command_buffers.iter() { + // The command encoder assumes a default state when encoding the command buffer. + // Always reset the state between command_buffers to reflect this assumption. Do + // this at the beginning of the loop in case something outside of wgpu modified + // this state prior to commit. + unsafe { self.reset_state(gl) }; + if let Some(ref label) = cmd_buf.label { + if self + .shared + .private_caps + .contains(PrivateCapabilities::DEBUG_FNS) + { + unsafe { + gl.push_debug_group( + glow::DEBUG_SOURCE_APPLICATION, + DEBUG_ID, + to_debug_str(label), + ) + }; + } + } + + for command in cmd_buf.commands.iter() { + unsafe { self.process(gl, command, &cmd_buf.data_bytes, &cmd_buf.queries) }; + } + + if cmd_buf.label.is_some() + && self + .shared + .private_caps + .contains(PrivateCapabilities::DEBUG_FNS) + { + unsafe { gl.pop_debug_group() }; + } + } + + signal_fence.maintain(gl); + signal_fence.signal(gl, signal_value)?; + + // This is extremely important. If we don't flush, the above fences may never + // be signaled, particularly in headless contexts. Headed contexts will + // often flush every so often, but headless contexts may not. + unsafe { gl.flush() }; + + Ok(()) + } + + unsafe fn present( + &self, + surface: &super::Surface, + texture: super::Texture, + ) -> Result<(), crate::SurfaceError> { + unsafe { surface.present(texture, &self.shared.context) } + } + + unsafe fn get_timestamp_period(&self) -> f32 { + 1.0 + } + + unsafe fn wait_for_idle(&self) -> Result<(), crate::DeviceError> { + let gl = &self.shared.context.lock(); + unsafe { gl.finish() }; + Ok(()) + } +} + +#[cfg(send_sync)] +unsafe impl Sync for super::Queue {} +#[cfg(send_sync)] +unsafe impl Send for super::Queue {} diff --git a/app/vendor/rune/vendor/wgpu-hal/src/gles/shaders/clear.frag b/app/vendor/rune/vendor/wgpu-hal/src/gles/shaders/clear.frag new file mode 100644 index 0000000..1d0e414 --- /dev/null +++ b/app/vendor/rune/vendor/wgpu-hal/src/gles/shaders/clear.frag @@ -0,0 +1,7 @@ +uniform vec4 color; +//Hack: Some WebGL implementations don't find "color" otherwise. +uniform vec4 color_workaround; +out vec4 frag; +void main() { + frag = color + color_workaround; +} diff --git a/app/vendor/rune/vendor/wgpu-hal/src/gles/shaders/clear.vert b/app/vendor/rune/vendor/wgpu-hal/src/gles/shaders/clear.vert new file mode 100644 index 0000000..341b4e5 --- /dev/null +++ b/app/vendor/rune/vendor/wgpu-hal/src/gles/shaders/clear.vert @@ -0,0 +1,9 @@ +// A triangle that fills the whole screen +vec2[3] TRIANGLE_POS = vec2[]( + vec2( 0.0, -3.0), + vec2(-3.0, 1.0), + vec2( 3.0, 1.0) +); +void main() { + gl_Position = vec4(TRIANGLE_POS[gl_VertexID], 0.0, 1.0); +} \ No newline at end of file diff --git a/app/vendor/rune/vendor/wgpu-hal/src/gles/shaders/srgb_present.frag b/app/vendor/rune/vendor/wgpu-hal/src/gles/shaders/srgb_present.frag new file mode 100644 index 0000000..853f82a --- /dev/null +++ b/app/vendor/rune/vendor/wgpu-hal/src/gles/shaders/srgb_present.frag @@ -0,0 +1,16 @@ +#version 300 es +precision mediump float; +in vec2 uv; +uniform sampler2D present_texture; +out vec4 frag; +vec4 linear_to_srgb(vec4 linear) { + vec3 color_linear = linear.rgb; + vec3 selector = ceil(color_linear - 0.0031308); // 0 if under value, 1 if over + vec3 under = 12.92 * color_linear; + vec3 over = 1.055 * pow(color_linear, vec3(0.41666)) - 0.055; + vec3 result = mix(under, over, selector); + return vec4(result, linear.a); +} +void main() { + frag = linear_to_srgb(texture(present_texture, uv)); +} \ No newline at end of file diff --git a/app/vendor/rune/vendor/wgpu-hal/src/gles/shaders/srgb_present.vert b/app/vendor/rune/vendor/wgpu-hal/src/gles/shaders/srgb_present.vert new file mode 100644 index 0000000..922f2a1 --- /dev/null +++ b/app/vendor/rune/vendor/wgpu-hal/src/gles/shaders/srgb_present.vert @@ -0,0 +1,18 @@ +#version 300 es +precision mediump float; +// A triangle that fills the whole screen +const vec2[3] TRIANGLE_POS = vec2[]( + vec2( 0.0, -3.0), + vec2(-3.0, 1.0), + vec2( 3.0, 1.0) +); +const vec2[3] TRIANGLE_UV = vec2[]( + vec2( 0.5, 1.), + vec2( -1.0, -1.0), + vec2( 2.0, -1.0) +); +out vec2 uv; +void main() { + uv = TRIANGLE_UV[gl_VertexID]; + gl_Position = vec4(TRIANGLE_POS[gl_VertexID], 0.0, 1.0); +} \ No newline at end of file diff --git a/app/vendor/rune/vendor/wgpu-hal/src/gles/web.rs b/app/vendor/rune/vendor/wgpu-hal/src/gles/web.rs new file mode 100644 index 0000000..326b4f3 --- /dev/null +++ b/app/vendor/rune/vendor/wgpu-hal/src/gles/web.rs @@ -0,0 +1,490 @@ +use alloc::{format, string::String, vec::Vec}; + +use glow::HasContext; +use parking_lot::{Mutex, RwLock}; +use wasm_bindgen::{JsCast, JsValue}; + +use super::TextureFormatDesc; + +/// A wrapper around a [`glow::Context`] to provide a fake `lock()` api that makes it compatible +/// with the `AdapterContext` API from the EGL implementation. +#[derive(Debug)] +pub struct AdapterContext { + pub glow_context: glow::Context, + pub webgl2_context: web_sys::WebGl2RenderingContext, +} + +impl AdapterContext { + pub fn is_owned(&self) -> bool { + false + } + + /// Obtain a lock to the EGL context and get handle to the [`glow::Context`] that can be used to + /// do rendering. + #[track_caller] + pub fn lock(&self) -> &glow::Context { + &self.glow_context + } +} + +#[derive(Debug)] +pub struct Instance { + options: wgt::GlBackendOptions, +} + +impl Instance { + pub fn create_surface_from_canvas( + &self, + canvas: web_sys::HtmlCanvasElement, + ) -> Result<Surface, crate::InstanceError> { + let result = + canvas.get_context_with_context_options("webgl2", &Self::create_context_options()); + self.create_surface_from_context(Canvas::Canvas(canvas), result) + } + + pub fn create_surface_from_offscreen_canvas( + &self, + canvas: web_sys::OffscreenCanvas, + ) -> Result<Surface, crate::InstanceError> { + let result = + canvas.get_context_with_context_options("webgl2", &Self::create_context_options()); + self.create_surface_from_context(Canvas::Offscreen(canvas), result) + } + + /// Common portion of public `create_surface_from_*` functions. + /// + /// Note: Analogous code also exists in the WebGPU backend at + /// `wgpu::backend::web::Context`. + fn create_surface_from_context( + &self, + canvas: Canvas, + context_result: Result<Option<js_sys::Object>, JsValue>, + ) -> Result<Surface, crate::InstanceError> { + let context_object: js_sys::Object = match context_result { + Ok(Some(context)) => context, + Ok(None) => { + // <https://html.spec.whatwg.org/multipage/canvas.html#dom-canvas-getcontext-dev> + // A getContext() call “returns null if contextId is not supported, or if the + // canvas has already been initialized with another context type”. Additionally, + // “not supported” could include “insufficient GPU resources” or “the GPU process + // previously crashed”. So, we must return it as an `Err` since it could occur + // for circumstances outside the application author's control. + return Err(crate::InstanceError::new(String::from(concat!( + "canvas.getContext() returned null; ", + "webgl2 not available or canvas already in use" + )))); + } + Err(js_error) => { + // <https://html.spec.whatwg.org/multipage/canvas.html#dom-canvas-getcontext> + // A thrown exception indicates misuse of the canvas state. + return Err(crate::InstanceError::new(format!( + "canvas.getContext() threw exception {js_error:?}", + ))); + } + }; + + // Not returning this error because it is a type error that shouldn't happen unless + // the browser, JS builtin objects, or wasm bindings are misbehaving somehow. + let webgl2_context: web_sys::WebGl2RenderingContext = context_object + .dyn_into() + .expect("canvas context is not a WebGl2RenderingContext"); + + Ok(Surface { + canvas, + webgl2_context, + srgb_present_program: Mutex::new(None), + swapchain: RwLock::new(None), + texture: Mutex::new(None), + presentable: true, + }) + } + + fn create_context_options() -> js_sys::Object { + let context_options = js_sys::Object::new(); + js_sys::Reflect::set(&context_options, &"antialias".into(), &JsValue::FALSE) + .expect("Cannot create context options"); + context_options + } +} + +#[cfg(send_sync)] +static_assertions::assert_impl_all!(Instance: Send, Sync); + +impl crate::Instance for Instance { + type A = super::Api; + + unsafe fn init(desc: &crate::InstanceDescriptor<'_>) -> Result<Self, crate::InstanceError> { + profiling::scope!("Init OpenGL (WebGL) Backend"); + Ok(Instance { + options: desc.backend_options.gl.clone(), + }) + } + + unsafe fn enumerate_adapters( + &self, + surface_hint: Option<&Surface>, + ) -> Vec<crate::ExposedAdapter<super::Api>> { + if let Some(surface_hint) = surface_hint { + let gl = glow::Context::from_webgl2_context(surface_hint.webgl2_context.clone()); + + unsafe { + super::Adapter::expose( + AdapterContext { + glow_context: gl, + webgl2_context: surface_hint.webgl2_context.clone(), + }, + self.options.clone(), + ) + } + .into_iter() + .collect() + } else { + Vec::new() + } + } + + unsafe fn create_surface( + &self, + _display_handle: raw_window_handle::RawDisplayHandle, + window_handle: raw_window_handle::RawWindowHandle, + ) -> Result<Surface, crate::InstanceError> { + let canvas: web_sys::HtmlCanvasElement = match window_handle { + raw_window_handle::RawWindowHandle::Web(handle) => web_sys::window() + .and_then(|win| win.document()) + .expect("Cannot get document") + .query_selector(&format!("canvas[data-raw-handle=\"{}\"]", handle.id)) + .expect("Cannot query for canvas") + .expect("Canvas is not found") + .dyn_into() + .expect("Failed to downcast to canvas type"), + raw_window_handle::RawWindowHandle::WebCanvas(handle) => { + let value: &JsValue = unsafe { handle.obj.cast().as_ref() }; + value.clone().unchecked_into() + } + raw_window_handle::RawWindowHandle::WebOffscreenCanvas(handle) => { + let value: &JsValue = unsafe { handle.obj.cast().as_ref() }; + let canvas: web_sys::OffscreenCanvas = value.clone().unchecked_into(); + + return self.create_surface_from_offscreen_canvas(canvas); + } + _ => { + return Err(crate::InstanceError::new(format!( + "window handle {window_handle:?} is not a web handle" + ))) + } + }; + + self.create_surface_from_canvas(canvas) + } +} + +impl super::Adapter { + /// Creates a new external adapter from an existing WebGL2 rendering context. + /// + /// # Safety + /// + /// - The underlying WebGL2 context must be valid (not lost). + /// - The underlying WebGL2 context must be valid when interfacing with any objects returned by + /// wgpu-hal from this adapter. + /// - The underlying WebGL2 context must be valid when dropping this adapter and when + /// dropping any objects returned from this adapter. + pub unsafe fn new_external( + webgl2_context: web_sys::WebGl2RenderingContext, + options: wgt::GlBackendOptions, + ) -> Option<crate::ExposedAdapter<super::Api>> { + let glow_context = glow::Context::from_webgl2_context(webgl2_context.clone()); + unsafe { + Self::expose( + AdapterContext { + glow_context, + webgl2_context, + }, + options, + ) + } + } + + pub fn adapter_context(&self) -> &AdapterContext { + &self.shared.context + } +} + +impl super::Device { + /// Returns the underlying WebGL2 `AdapterContext`. + pub fn context(&self) -> &AdapterContext { + &self.shared.context + } +} + +#[derive(Debug)] +pub struct Surface { + canvas: Canvas, + pub(super) webgl2_context: web_sys::WebGl2RenderingContext, + pub(super) swapchain: RwLock<Option<Swapchain>>, + texture: Mutex<Option<glow::Texture>>, + pub(super) presentable: bool, + srgb_present_program: Mutex<Option<glow::Program>>, +} + +impl Clone for Surface { + fn clone(&self) -> Self { + Self { + canvas: self.canvas.clone(), + webgl2_context: self.webgl2_context.clone(), + swapchain: RwLock::new(self.swapchain.read().clone()), + texture: Mutex::new(*self.texture.lock()), + presentable: self.presentable, + srgb_present_program: Mutex::new(*self.srgb_present_program.lock()), + } + } +} + +#[cfg(send_sync)] +unsafe impl Sync for Surface {} +#[cfg(send_sync)] +unsafe impl Send for Surface {} + +#[derive(Clone, Debug)] +enum Canvas { + Canvas(web_sys::HtmlCanvasElement), + Offscreen(web_sys::OffscreenCanvas), +} + +#[derive(Clone, Debug)] +pub struct Swapchain { + pub(crate) extent: wgt::Extent3d, + // pub(crate) channel: f::ChannelType, + pub(super) format: wgt::TextureFormat, + pub(super) framebuffer: glow::Framebuffer, + pub(super) format_desc: TextureFormatDesc, +} + +impl Surface { + pub(super) unsafe fn present( + &self, + _suf_texture: super::Texture, + context: &AdapterContext, + ) -> Result<(), crate::SurfaceError> { + let gl = &context.glow_context; + let swapchain = self.swapchain.read(); + let swapchain = swapchain.as_ref().ok_or(crate::SurfaceError::Other( + "need to configure surface before presenting", + ))?; + + if swapchain.format.is_srgb() { + // Important to set the viewport since we don't know in what state the user left it. + unsafe { + gl.viewport( + 0, + 0, + swapchain.extent.width as _, + swapchain.extent.height as _, + ) + }; + unsafe { gl.bind_framebuffer(glow::DRAW_FRAMEBUFFER, None) }; + unsafe { gl.bind_sampler(0, None) }; + unsafe { gl.active_texture(glow::TEXTURE0) }; + unsafe { gl.bind_texture(glow::TEXTURE_2D, *self.texture.lock()) }; + unsafe { gl.use_program(*self.srgb_present_program.lock()) }; + unsafe { gl.disable(glow::DEPTH_TEST) }; + unsafe { gl.disable(glow::STENCIL_TEST) }; + unsafe { gl.disable(glow::SCISSOR_TEST) }; + unsafe { gl.disable(glow::BLEND) }; + unsafe { gl.disable(glow::CULL_FACE) }; + unsafe { gl.draw_buffers(&[glow::BACK]) }; + unsafe { gl.draw_arrays(glow::TRIANGLES, 0, 3) }; + } else { + unsafe { gl.bind_framebuffer(glow::READ_FRAMEBUFFER, Some(swapchain.framebuffer)) }; + unsafe { gl.bind_framebuffer(glow::DRAW_FRAMEBUFFER, None) }; + // Note the Y-flipping here. GL's presentation is not flipped, + // but main rendering is. Therefore, we Y-flip the output positions + // in the shader, and also this blit. + unsafe { + gl.blit_framebuffer( + 0, + swapchain.extent.height as i32, + swapchain.extent.width as i32, + 0, + 0, + 0, + swapchain.extent.width as i32, + swapchain.extent.height as i32, + glow::COLOR_BUFFER_BIT, + glow::NEAREST, + ) + }; + } + + Ok(()) + } + + unsafe fn create_srgb_present_program(gl: &glow::Context) -> glow::Program { + let program = unsafe { gl.create_program() }.expect("Could not create shader program"); + let vertex = + unsafe { gl.create_shader(glow::VERTEX_SHADER) }.expect("Could not create shader"); + unsafe { gl.shader_source(vertex, include_str!("./shaders/srgb_present.vert")) }; + unsafe { gl.compile_shader(vertex) }; + let fragment = + unsafe { gl.create_shader(glow::FRAGMENT_SHADER) }.expect("Could not create shader"); + unsafe { gl.shader_source(fragment, include_str!("./shaders/srgb_present.frag")) }; + unsafe { gl.compile_shader(fragment) }; + unsafe { gl.attach_shader(program, vertex) }; + unsafe { gl.attach_shader(program, fragment) }; + unsafe { gl.link_program(program) }; + unsafe { gl.delete_shader(vertex) }; + unsafe { gl.delete_shader(fragment) }; + unsafe { gl.bind_texture(glow::TEXTURE_2D, None) }; + + program + } + + pub fn supports_srgb(&self) -> bool { + // present.frag takes care of handling srgb conversion + true + } +} + +impl crate::Surface for Surface { + type A = super::Api; + + unsafe fn configure( + &self, + device: &super::Device, + config: &crate::SurfaceConfiguration, + ) -> Result<(), crate::SurfaceError> { + match self.canvas { + Canvas::Canvas(ref canvas) => { + canvas.set_width(config.extent.width); + canvas.set_height(config.extent.height); + } + Canvas::Offscreen(ref canvas) => { + canvas.set_width(config.extent.width); + canvas.set_height(config.extent.height); + } + } + + let gl = &device.shared.context.lock(); + + { + let mut swapchain = self.swapchain.write(); + if let Some(swapchain) = swapchain.take() { + // delete all frame buffers already allocated + unsafe { gl.delete_framebuffer(swapchain.framebuffer) }; + } + } + { + let mut srgb_present_program = self.srgb_present_program.lock(); + if srgb_present_program.is_none() && config.format.is_srgb() { + *srgb_present_program = Some(unsafe { Self::create_srgb_present_program(gl) }); + } + } + { + let mut texture = self.texture.lock(); + if let Some(texture) = texture.take() { + unsafe { gl.delete_texture(texture) }; + } + + *texture = Some(unsafe { gl.create_texture() }.map_err(|error| { + log::error!("Internal swapchain texture creation failed: {error}"); + crate::DeviceError::OutOfMemory + })?); + + let desc = device.shared.describe_texture_format(config.format); + unsafe { gl.bind_texture(glow::TEXTURE_2D, *texture) }; + unsafe { + gl.tex_parameter_i32( + glow::TEXTURE_2D, + glow::TEXTURE_MIN_FILTER, + glow::NEAREST as _, + ) + }; + unsafe { + gl.tex_parameter_i32( + glow::TEXTURE_2D, + glow::TEXTURE_MAG_FILTER, + glow::NEAREST as _, + ) + }; + unsafe { + gl.tex_storage_2d( + glow::TEXTURE_2D, + 1, + desc.internal, + config.extent.width as i32, + config.extent.height as i32, + ) + }; + + let framebuffer = unsafe { gl.create_framebuffer() }.map_err(|error| { + log::error!("Internal swapchain framebuffer creation failed: {error}"); + crate::DeviceError::OutOfMemory + })?; + unsafe { gl.bind_framebuffer(glow::READ_FRAMEBUFFER, Some(framebuffer)) }; + unsafe { + gl.framebuffer_texture_2d( + glow::READ_FRAMEBUFFER, + glow::COLOR_ATTACHMENT0, + glow::TEXTURE_2D, + *texture, + 0, + ) + }; + unsafe { gl.bind_texture(glow::TEXTURE_2D, None) }; + + let mut swapchain = self.swapchain.write(); + *swapchain = Some(Swapchain { + extent: config.extent, + // channel: config.format.base_format().1, + format: config.format, + format_desc: desc, + framebuffer, + }); + } + + Ok(()) + } + + unsafe fn unconfigure(&self, device: &super::Device) { + let gl = device.shared.context.lock(); + { + let mut swapchain = self.swapchain.write(); + if let Some(swapchain) = swapchain.take() { + unsafe { gl.delete_framebuffer(swapchain.framebuffer) }; + } + } + if let Some(renderbuffer) = self.texture.lock().take() { + unsafe { gl.delete_texture(renderbuffer) }; + } + } + + unsafe fn acquire_texture( + &self, + _timeout_ms: Option<core::time::Duration>, //TODO + _fence: &super::Fence, + ) -> Result<crate::AcquiredSurfaceTexture<super::Api>, crate::SurfaceError> { + let swapchain = self.swapchain.read(); + let sc = swapchain.as_ref().unwrap(); + let texture = super::Texture { + inner: super::TextureInner::Texture { + raw: self.texture.lock().unwrap(), + target: glow::TEXTURE_2D, + }, + drop_guard: None, + array_layer_count: 1, + mip_level_count: 1, + format: sc.format, + format_desc: sc.format_desc.clone(), + copy_size: crate::CopyExtent { + width: sc.extent.width, + height: sc.extent.height, + depth: 1, + }, + }; + Ok(crate::AcquiredSurfaceTexture { + texture, + suboptimal: false, + }) + } + + unsafe fn discard_texture(&self, _texture: super::Texture) {} +} diff --git a/app/vendor/rune/vendor/wgpu-hal/src/gles/wgl.rs b/app/vendor/rune/vendor/wgpu-hal/src/gles/wgl.rs new file mode 100644 index 0000000..4edbf3b --- /dev/null +++ b/app/vendor/rune/vendor/wgpu-hal/src/gles/wgl.rs @@ -0,0 +1,911 @@ +#![expect( + missing_debug_implementations, + reason = "TODO: someone developing on Windows add Debug impls where possible" +)] + +use alloc::{borrow::ToOwned as _, ffi::CString, string::String, sync::Arc, vec::Vec}; +use core::{ + ffi::{c_int, c_void, CStr}, + mem::{self, ManuallyDrop}, + ptr, + time::Duration, +}; +use std::{ + sync::{ + mpsc::{sync_channel, SyncSender}, + LazyLock, + }, + thread, +}; + +use glow::HasContext; +use glutin_wgl_sys::wgl_extra::{ + Wgl, CONTEXT_CORE_PROFILE_BIT_ARB, CONTEXT_DEBUG_BIT_ARB, CONTEXT_FLAGS_ARB, + CONTEXT_PROFILE_MASK_ARB, +}; +use hashbrown::HashSet; +use parking_lot::{Mutex, MutexGuard, RwLock}; +use raw_window_handle::{RawDisplayHandle, RawWindowHandle}; +use wgt::InstanceFlags; +use windows::{ + core::{Error, PCSTR}, + Win32::{ + Foundation, + Graphics::{Gdi, OpenGL}, + System::LibraryLoader, + UI::WindowsAndMessaging, + }, +}; + +/// The amount of time to wait while trying to obtain a lock to the adapter context +const CONTEXT_LOCK_TIMEOUT_SECS: u64 = 1; + +/// A wrapper around a `[`glow::Context`]` and the required WGL context that uses locking to +/// guarantee exclusive access when shared with multiple threads. +pub struct AdapterContext { + inner: Arc<Mutex<Inner>>, +} + +#[cfg(send_sync)] +static_assertions::assert_impl_all!(AdapterContext: Send, Sync); + +impl AdapterContext { + pub fn is_owned(&self) -> bool { + true + } + + pub fn raw_context(&self) -> *mut c_void { + match self.inner.lock().context { + Some(ref wgl) => wgl.context.0, + None => ptr::null_mut(), + } + } + + /// Obtain a lock to the WGL context and get handle to the [`glow::Context`] that can be used to + /// do rendering. + #[track_caller] + pub fn lock(&self) -> AdapterContextLock<'_> { + let inner = self + .inner + // Don't lock forever. If it takes longer than 1 second to get the lock we've got a + // deadlock and should panic to show where we got stuck + .try_lock_for(Duration::from_secs(CONTEXT_LOCK_TIMEOUT_SECS)) + .expect("Could not lock adapter context. This is most-likely a deadlock."); + + if let Some(wgl) = &inner.context { + wgl.make_current(inner.device.dc).unwrap() + }; + + AdapterContextLock { inner } + } + + /// Obtain a lock to the WGL context and get handle to the [`glow::Context`] that can be used to + /// do rendering. + /// + /// Unlike [`lock`](Self::lock), this accepts a device to pass to `make_current` and exposes the error + /// when `make_current` fails. + #[track_caller] + fn lock_with_dc(&self, device: Gdi::HDC) -> windows::core::Result<AdapterContextLock<'_>> { + let inner = self + .inner + .try_lock_for(Duration::from_secs(CONTEXT_LOCK_TIMEOUT_SECS)) + .expect("Could not lock adapter context. This is most-likely a deadlock."); + + if let Some(wgl) = &inner.context { + wgl.make_current(device)?; + } + + Ok(AdapterContextLock { inner }) + } +} + +/// A guard containing a lock to an [`AdapterContext`], while the GL context is kept current. +pub struct AdapterContextLock<'a> { + inner: MutexGuard<'a, Inner>, +} + +impl<'a> core::ops::Deref for AdapterContextLock<'a> { + type Target = glow::Context; + + fn deref(&self) -> &Self::Target { + &self.inner.gl + } +} + +impl<'a> Drop for AdapterContextLock<'a> { + fn drop(&mut self) { + if let Some(wgl) = &self.inner.context { + wgl.unmake_current().unwrap() + } + } +} + +struct WglContext { + context: OpenGL::HGLRC, +} + +impl WglContext { + fn make_current(&self, device: Gdi::HDC) -> windows::core::Result<()> { + unsafe { OpenGL::wglMakeCurrent(device, self.context) } + } + + fn unmake_current(&self) -> windows::core::Result<()> { + if unsafe { OpenGL::wglGetCurrentContext() }.is_invalid() { + return Ok(()); + } + unsafe { OpenGL::wglMakeCurrent(Default::default(), Default::default()) } + } +} + +impl Drop for WglContext { + fn drop(&mut self) { + if let Err(e) = unsafe { OpenGL::wglDeleteContext(self.context) } { + log::error!("failed to delete WGL context: {e}"); + } + } +} + +unsafe impl Send for WglContext {} +unsafe impl Sync for WglContext {} + +struct Inner { + gl: ManuallyDrop<glow::Context>, + device: InstanceDevice, + context: Option<WglContext>, +} + +impl Drop for Inner { + fn drop(&mut self) { + struct CurrentGuard<'a>(&'a WglContext); + impl Drop for CurrentGuard<'_> { + fn drop(&mut self) { + self.0.unmake_current().unwrap(); + } + } + + // Context must be current when dropped. See safety docs on + // `glow::HasContext`. + // + // NOTE: This is only set to `None` by `Adapter::new_external` which + // requires the context to be current when anything that may be holding + // the `Arc<AdapterShared>` is dropped. + let _guard = self.context.as_ref().map(|wgl| { + wgl.make_current(self.device.dc).unwrap(); + CurrentGuard(wgl) + }); + // SAFETY: Field not used after this. + unsafe { ManuallyDrop::drop(&mut self.gl) }; + } +} + +unsafe impl Send for Inner {} +unsafe impl Sync for Inner {} + +pub struct Instance { + srgb_capable: bool, + options: wgt::GlBackendOptions, + inner: Arc<Mutex<Inner>>, +} + +#[cfg(send_sync)] +static_assertions::assert_impl_all!(Instance: Send, Sync); + +fn load_gl_func(name: &str, module: Option<Foundation::HMODULE>) -> *const c_void { + let addr = CString::new(name.as_bytes()).unwrap(); + let mut ptr = unsafe { OpenGL::wglGetProcAddress(PCSTR(addr.as_ptr().cast())) }; + if ptr.is_none() { + if let Some(module) = module { + ptr = unsafe { LibraryLoader::GetProcAddress(module, PCSTR(addr.as_ptr().cast())) }; + } + } + ptr.map_or_else(ptr::null_mut, |p| p as *mut c_void) +} + +fn get_extensions(extra: &Wgl, dc: Gdi::HDC) -> HashSet<String> { + if extra.GetExtensionsStringARB.is_loaded() { + unsafe { CStr::from_ptr(extra.GetExtensionsStringARB(dc.0)) } + .to_str() + .unwrap_or("") + } else { + "" + } + .split(' ') + .map(|s| s.to_owned()) + .collect() +} + +unsafe fn setup_pixel_format(dc: Gdi::HDC) -> Result<(), crate::InstanceError> { + { + let format = OpenGL::PIXELFORMATDESCRIPTOR { + nVersion: 1, + nSize: size_of::<OpenGL::PIXELFORMATDESCRIPTOR>() as u16, + dwFlags: OpenGL::PFD_DRAW_TO_WINDOW + | OpenGL::PFD_SUPPORT_OPENGL + | OpenGL::PFD_DOUBLEBUFFER, + iPixelType: OpenGL::PFD_TYPE_RGBA, + cColorBits: 8, + ..unsafe { mem::zeroed() } + }; + + let index = unsafe { OpenGL::ChoosePixelFormat(dc, &format) }; + if index == 0 { + return Err(crate::InstanceError::with_source( + String::from("unable to choose pixel format"), + Error::from_thread(), + )); + } + + let current = unsafe { OpenGL::GetPixelFormat(dc) }; + + if index != current { + unsafe { OpenGL::SetPixelFormat(dc, index, &format) }.map_err(|e| { + crate::InstanceError::with_source(String::from("unable to set pixel format"), e) + })?; + } + } + + { + let index = unsafe { OpenGL::GetPixelFormat(dc) }; + if index == 0 { + return Err(crate::InstanceError::with_source( + String::from("unable to get pixel format index"), + Error::from_thread(), + )); + } + let mut format = Default::default(); + if unsafe { + OpenGL::DescribePixelFormat(dc, index, size_of_val(&format) as u32, Some(&mut format)) + } == 0 + { + return Err(crate::InstanceError::with_source( + String::from("unable to read pixel format"), + Error::from_thread(), + )); + } + + if !format.dwFlags.contains(OpenGL::PFD_SUPPORT_OPENGL) + || format.iPixelType != OpenGL::PFD_TYPE_RGBA + { + return Err(crate::InstanceError::new(String::from( + "unsuitable pixel format", + ))); + } + } + Ok(()) +} + +fn create_global_window_class() -> Result<CString, crate::InstanceError> { + let instance = unsafe { LibraryLoader::GetModuleHandleA(None) }.map_err(|e| { + crate::InstanceError::with_source(String::from("unable to get executable instance"), e) + })?; + + // Use the address of `UNIQUE` as part of the window class name to ensure different + // `wgpu` versions use different names. + static UNIQUE: Mutex<u8> = Mutex::new(0); + let class_addr: *const _ = &UNIQUE; + let name = format!("wgpu Device Class {:x}\0", class_addr as usize); + let name = CString::from_vec_with_nul(name.into_bytes()).unwrap(); + + // The window class may already be registered if we are a dynamic library that got + // unloaded & loaded back into the same process. If so, just skip creation. + let already_exists = unsafe { + let mut wc = mem::zeroed::<WindowsAndMessaging::WNDCLASSEXA>(); + WindowsAndMessaging::GetClassInfoExA( + Some(instance.into()), + PCSTR(name.as_ptr().cast()), + &mut wc, + ) + .is_ok() + }; + if already_exists { + return Ok(name); + } + + // Use a wrapper function for compatibility with `windows-rs`. + unsafe extern "system" fn wnd_proc( + window: Foundation::HWND, + msg: u32, + wparam: Foundation::WPARAM, + lparam: Foundation::LPARAM, + ) -> Foundation::LRESULT { + unsafe { WindowsAndMessaging::DefWindowProcA(window, msg, wparam, lparam) } + } + + let window_class = WindowsAndMessaging::WNDCLASSEXA { + cbSize: size_of::<WindowsAndMessaging::WNDCLASSEXA>() as u32, + style: WindowsAndMessaging::CS_OWNDC, + lpfnWndProc: Some(wnd_proc), + cbClsExtra: 0, + cbWndExtra: 0, + hInstance: instance.into(), + hIcon: WindowsAndMessaging::HICON::default(), + hCursor: WindowsAndMessaging::HCURSOR::default(), + hbrBackground: Gdi::HBRUSH::default(), + lpszMenuName: PCSTR::null(), + lpszClassName: PCSTR(name.as_ptr().cast()), + hIconSm: WindowsAndMessaging::HICON::default(), + }; + + let atom = unsafe { WindowsAndMessaging::RegisterClassExA(&window_class) }; + + if atom == 0 { + return Err(crate::InstanceError::with_source( + String::from("unable to register window class"), + Error::from_thread(), + )); + } + + // We intentionally leak the window class as we only need one per process. + + Ok(name) +} + +fn get_global_window_class() -> Result<CString, crate::InstanceError> { + static GLOBAL: LazyLock<Result<CString, crate::InstanceError>> = + LazyLock::new(create_global_window_class); + GLOBAL.clone() +} + +struct InstanceDevice { + dc: Gdi::HDC, + + /// This is used to keep the thread owning `dc` alive until this struct is dropped. + _tx: SyncSender<()>, +} + +fn create_instance_device() -> Result<InstanceDevice, crate::InstanceError> { + #[derive(Clone, Copy)] + // TODO: We can get these SendSync definitions in the upstream metadata if this is the case + struct SendDc(Gdi::HDC); + unsafe impl Sync for SendDc {} + unsafe impl Send for SendDc {} + + struct Window { + window: Foundation::HWND, + } + impl Drop for Window { + fn drop(&mut self) { + if let Err(e) = unsafe { WindowsAndMessaging::DestroyWindow(self.window) } { + log::error!("failed to destroy window: {e}"); + } + } + } + + let window_class = get_global_window_class()?; + + let (drop_tx, drop_rx) = sync_channel(0); + let (setup_tx, setup_rx) = sync_channel(0); + + // We spawn a thread which owns the hidden window for this instance. + thread::Builder::new() + .stack_size(256 * 1024) + .name("wgpu-hal WGL Instance Thread".to_owned()) + .spawn(move || { + let setup = (|| { + let instance = unsafe { LibraryLoader::GetModuleHandleA(None) }.map_err(|e| { + crate::InstanceError::with_source( + String::from("unable to get executable instance"), + e, + ) + })?; + + // Create a hidden window since we don't pass `WS_VISIBLE`. + let window = unsafe { + WindowsAndMessaging::CreateWindowExA( + WindowsAndMessaging::WINDOW_EX_STYLE::default(), + PCSTR(window_class.as_ptr().cast()), + PCSTR(window_class.as_ptr().cast()), + WindowsAndMessaging::WINDOW_STYLE::default(), + 0, + 0, + 1, + 1, + None, + None, + Some(instance.into()), + None, + ) + } + .map_err(|e| { + crate::InstanceError::with_source( + String::from("unable to create hidden instance window"), + e, + ) + })?; + let window = Window { window }; + + let dc = unsafe { Gdi::GetDC(Some(window.window)) }; + if dc.is_invalid() { + return Err(crate::InstanceError::with_source( + String::from("unable to create memory device"), + Error::from_thread(), + )); + } + let dc = DeviceContextHandle { + device: dc, + window: window.window, + }; + unsafe { setup_pixel_format(dc.device)? }; + + Ok((window, dc)) + })(); + + match setup { + Ok((_window, dc)) => { + setup_tx.send(Ok(SendDc(dc.device))).unwrap(); + // Wait for the shutdown event to free the window and device context handle. + drop_rx.recv().ok(); + } + Err(err) => { + setup_tx.send(Err(err)).unwrap(); + } + } + }) + .map_err(|e| { + crate::InstanceError::with_source(String::from("unable to create instance thread"), e) + })?; + + let dc = setup_rx.recv().unwrap()?.0; + + Ok(InstanceDevice { dc, _tx: drop_tx }) +} + +impl crate::Instance for Instance { + type A = super::Api; + + unsafe fn init(desc: &crate::InstanceDescriptor<'_>) -> Result<Self, crate::InstanceError> { + profiling::scope!("Init OpenGL (WGL) Backend"); + // Rune: load opengl32.dll from System32 only, not the app directory or CWD. + let opengl_module = unsafe { + LibraryLoader::LoadLibraryExA( + PCSTR(c"opengl32.dll".as_ptr().cast()), + None, + LibraryLoader::LOAD_LIBRARY_SEARCH_SYSTEM32, + ) + } + .map_err(|e| { + crate::InstanceError::with_source( + String::from("unable to load the OpenGL library"), + e, + ) + })?; + + let device = create_instance_device()?; + let dc = device.dc; + + let context = unsafe { OpenGL::wglCreateContext(dc) }.map_err(|e| { + crate::InstanceError::with_source( + String::from("unable to create initial OpenGL context"), + e, + ) + })?; + let context = WglContext { context }; + context.make_current(dc).map_err(|e| { + crate::InstanceError::with_source( + String::from("unable to set initial OpenGL context as current"), + e, + ) + })?; + + let extra = Wgl::load_with(|name| load_gl_func(name, None)); + let extensions = get_extensions(&extra, dc); + + let can_use_profile = extensions.contains("WGL_ARB_create_context_profile") + && extra.CreateContextAttribsARB.is_loaded(); + + let context = if can_use_profile { + let attributes = [ + CONTEXT_PROFILE_MASK_ARB as c_int, + CONTEXT_CORE_PROFILE_BIT_ARB as c_int, + CONTEXT_FLAGS_ARB as c_int, + if desc.flags.contains(InstanceFlags::DEBUG) { + CONTEXT_DEBUG_BIT_ARB as c_int + } else { + 0 + }, + 0, // End of list + ]; + let context = + unsafe { extra.CreateContextAttribsARB(dc.0, ptr::null(), attributes.as_ptr()) }; + if context.is_null() { + return Err(crate::InstanceError::with_source( + String::from("unable to create OpenGL context"), + Error::from_thread(), + )); + } + WglContext { + context: OpenGL::HGLRC(context.cast_mut()), + } + } else { + context + }; + + context.make_current(dc).map_err(|e| { + crate::InstanceError::with_source( + String::from("unable to set OpenGL context as current"), + e, + ) + })?; + + let mut gl = unsafe { + glow::Context::from_loader_function(|name| load_gl_func(name, Some(opengl_module))) + }; + + let extra = Wgl::load_with(|name| load_gl_func(name, None)); + let extensions = get_extensions(&extra, dc); + + let srgb_capable = extensions.contains("WGL_EXT_framebuffer_sRGB") + || extensions.contains("WGL_ARB_framebuffer_sRGB") + || gl + .supported_extensions() + .contains("GL_ARB_framebuffer_sRGB"); + + // In contrast to OpenGL ES, OpenGL requires explicitly enabling sRGB conversions, + // as otherwise the user has to do the sRGB conversion. + if srgb_capable { + unsafe { gl.enable(glow::FRAMEBUFFER_SRGB) }; + } + + if desc.flags.contains(InstanceFlags::VALIDATION) && gl.supports_debug() { + log::debug!("Enabling GL debug output"); + unsafe { gl.enable(glow::DEBUG_OUTPUT) }; + unsafe { gl.debug_message_callback(super::gl_debug_message_callback) }; + } + + // Wrap in ManuallyDrop to make it easier to "current" the GL context before dropping this + // GLOW context, which could also happen if a panic occurs after we uncurrent the context + // below but before Inner is constructed. + let gl = ManuallyDrop::new(gl); + context.unmake_current().map_err(|e| { + crate::InstanceError::with_source( + String::from("unable to unset the current WGL context"), + e, + ) + })?; + + Ok(Instance { + inner: Arc::new(Mutex::new(Inner { + device, + gl, + context: Some(context), + })), + options: desc.backend_options.gl.clone(), + srgb_capable, + }) + } + + unsafe fn create_surface( + &self, + display_handle: RawDisplayHandle, + window_handle: RawWindowHandle, + ) -> Result<Surface, crate::InstanceError> { + assert!(matches!(display_handle, RawDisplayHandle::Windows(_))); + let window = if let RawWindowHandle::Win32(handle) = window_handle { + handle + } else { + return Err(crate::InstanceError::new(format!( + "unsupported window: {window_handle:?}" + ))); + }; + Ok(Surface { + // This cast exists because of https://github.com/rust-windowing/raw-window-handle/issues/171 + window: Foundation::HWND(window.hwnd.get() as *mut _), + presentable: true, + swapchain: RwLock::new(None), + srgb_capable: self.srgb_capable, + }) + } + + unsafe fn enumerate_adapters( + &self, + _surface_hint: Option<&Surface>, + ) -> Vec<crate::ExposedAdapter<super::Api>> { + unsafe { + super::Adapter::expose( + AdapterContext { + inner: self.inner.clone(), + }, + self.options.clone(), + ) + } + .into_iter() + .collect() + } +} + +impl super::Adapter { + /// Creates a new external adapter using the specified loader function. + /// + /// # Safety + /// + /// - The underlying OpenGL ES context must be current. + /// - The underlying OpenGL ES context must be current when interfacing with any objects returned by + /// wgpu-hal from this adapter. + /// - The underlying OpenGL ES context must be current when dropping this adapter and when + /// dropping any objects returned from this adapter. + pub unsafe fn new_external( + fun: impl FnMut(&str) -> *const c_void, + options: wgt::GlBackendOptions, + ) -> Option<crate::ExposedAdapter<super::Api>> { + let context = unsafe { glow::Context::from_loader_function(fun) }; + unsafe { + Self::expose( + AdapterContext { + inner: Arc::new(Mutex::new(Inner { + gl: ManuallyDrop::new(context), + device: create_instance_device().ok()?, + context: None, + })), + }, + options, + ) + } + } + + pub fn adapter_context(&self) -> &AdapterContext { + &self.shared.context + } +} + +impl super::Device { + /// Returns the underlying WGL context. + pub fn context(&self) -> &AdapterContext { + &self.shared.context + } +} + +struct DeviceContextHandle { + device: Gdi::HDC, + window: Foundation::HWND, +} + +impl Drop for DeviceContextHandle { + fn drop(&mut self) { + unsafe { + Gdi::ReleaseDC(Some(self.window), self.device); + }; + } +} + +pub struct Swapchain { + framebuffer: glow::Framebuffer, + renderbuffer: glow::Renderbuffer, + + /// Extent because the window lies + extent: wgt::Extent3d, + + format: wgt::TextureFormat, + format_desc: super::TextureFormatDesc, + #[allow(unused)] + sample_type: wgt::TextureSampleType, +} + +pub struct Surface { + window: Foundation::HWND, + pub(super) presentable: bool, + swapchain: RwLock<Option<Swapchain>>, + srgb_capable: bool, +} + +unsafe impl Send for Surface {} +unsafe impl Sync for Surface {} + +impl Surface { + pub(super) unsafe fn present( + &self, + _suf_texture: super::Texture, + context: &AdapterContext, + ) -> Result<(), crate::SurfaceError> { + let swapchain = self.swapchain.read(); + let sc = swapchain.as_ref().unwrap(); + let dc = unsafe { Gdi::GetDC(Some(self.window)) }; + if dc.is_invalid() { + log::error!( + "unable to get the device context from window: {}", + Error::from_thread() + ); + return Err(crate::SurfaceError::Other( + "unable to get the device context from window", + )); + } + let dc = DeviceContextHandle { + device: dc, + window: self.window, + }; + + let gl = context.lock_with_dc(dc.device).map_err(|e| { + log::error!("unable to make the OpenGL context current for surface: {e}",); + crate::SurfaceError::Other("unable to make the OpenGL context current for surface") + })?; + + unsafe { gl.bind_framebuffer(glow::DRAW_FRAMEBUFFER, None) }; + unsafe { gl.bind_framebuffer(glow::READ_FRAMEBUFFER, Some(sc.framebuffer)) }; + + if self.srgb_capable { + // Disable sRGB conversions for `glBlitFramebuffer` as behavior does diverge between + // drivers and formats otherwise and we want to ensure no sRGB conversions happen. + unsafe { gl.disable(glow::FRAMEBUFFER_SRGB) }; + } + + // Note the Y-flipping here. GL's presentation is not flipped, + // but main rendering is. Therefore, we Y-flip the output positions + // in the shader, and also this blit. + unsafe { + gl.blit_framebuffer( + 0, + sc.extent.height as i32, + sc.extent.width as i32, + 0, + 0, + 0, + sc.extent.width as i32, + sc.extent.height as i32, + glow::COLOR_BUFFER_BIT, + glow::NEAREST, + ) + }; + + if self.srgb_capable { + unsafe { gl.enable(glow::FRAMEBUFFER_SRGB) }; + } + + unsafe { gl.bind_renderbuffer(glow::RENDERBUFFER, None) }; + unsafe { gl.bind_framebuffer(glow::READ_FRAMEBUFFER, None) }; + + if let Err(e) = unsafe { OpenGL::SwapBuffers(dc.device) } { + log::error!("unable to swap buffers: {e}"); + return Err(crate::SurfaceError::Other("unable to swap buffers")); + } + + Ok(()) + } + + pub fn supports_srgb(&self) -> bool { + self.srgb_capable + } +} + +impl crate::Surface for Surface { + type A = super::Api; + + unsafe fn configure( + &self, + device: &super::Device, + config: &crate::SurfaceConfiguration, + ) -> Result<(), crate::SurfaceError> { + // Remove the old configuration. + unsafe { self.unconfigure(device) }; + + let dc = unsafe { Gdi::GetDC(Some(self.window)) }; + if dc.is_invalid() { + log::error!( + "unable to get the device context from window: {}", + Error::from_thread() + ); + return Err(crate::SurfaceError::Other( + "unable to get the device context from window", + )); + } + let dc = DeviceContextHandle { + device: dc, + window: self.window, + }; + + if let Err(e) = unsafe { setup_pixel_format(dc.device) } { + log::error!("unable to setup surface pixel format: {e}",); + return Err(crate::SurfaceError::Other( + "unable to setup surface pixel format", + )); + } + + let format_desc = device.shared.describe_texture_format(config.format); + let gl = &device.shared.context.lock_with_dc(dc.device).map_err(|e| { + log::error!("unable to make the OpenGL context current for surface: {e}",); + crate::SurfaceError::Other("unable to make the OpenGL context current for surface") + })?; + + let renderbuffer = unsafe { gl.create_renderbuffer() }.map_err(|error| { + log::error!("Internal swapchain renderbuffer creation failed: {error}"); + crate::DeviceError::OutOfMemory + })?; + unsafe { gl.bind_renderbuffer(glow::RENDERBUFFER, Some(renderbuffer)) }; + unsafe { + gl.renderbuffer_storage( + glow::RENDERBUFFER, + format_desc.internal, + config.extent.width as _, + config.extent.height as _, + ) + }; + + let framebuffer = unsafe { gl.create_framebuffer() }.map_err(|error| { + log::error!("Internal swapchain framebuffer creation failed: {error}"); + crate::DeviceError::OutOfMemory + })?; + unsafe { gl.bind_framebuffer(glow::READ_FRAMEBUFFER, Some(framebuffer)) }; + unsafe { + gl.framebuffer_renderbuffer( + glow::READ_FRAMEBUFFER, + glow::COLOR_ATTACHMENT0, + glow::RENDERBUFFER, + Some(renderbuffer), + ) + }; + unsafe { gl.bind_renderbuffer(glow::RENDERBUFFER, None) }; + unsafe { gl.bind_framebuffer(glow::READ_FRAMEBUFFER, None) }; + + // Setup presentation mode + let extra = Wgl::load_with(|name| load_gl_func(name, None)); + let extensions = get_extensions(&extra, dc.device); + if !(extensions.contains("WGL_EXT_swap_control") && extra.SwapIntervalEXT.is_loaded()) { + log::error!("WGL_EXT_swap_control is unsupported"); + return Err(crate::SurfaceError::Other( + "WGL_EXT_swap_control is unsupported", + )); + } + + let vsync = match config.present_mode { + wgt::PresentMode::Immediate => false, + wgt::PresentMode::Fifo => true, + _ => { + log::error!("unsupported present mode: {:?}", config.present_mode); + return Err(crate::SurfaceError::Other("unsupported present mode")); + } + }; + + if unsafe { extra.SwapIntervalEXT(if vsync { 1 } else { 0 }) } == Foundation::FALSE.0 { + log::error!("unable to set swap interval: {}", Error::from_thread()); + return Err(crate::SurfaceError::Other("unable to set swap interval")); + } + + self.swapchain.write().replace(Swapchain { + renderbuffer, + framebuffer, + extent: config.extent, + format: config.format, + format_desc, + sample_type: wgt::TextureSampleType::Float { filterable: false }, + }); + + Ok(()) + } + + unsafe fn unconfigure(&self, device: &super::Device) { + let gl = &device.shared.context.lock(); + if let Some(sc) = self.swapchain.write().take() { + unsafe { + gl.delete_renderbuffer(sc.renderbuffer); + gl.delete_framebuffer(sc.framebuffer) + }; + } + } + + unsafe fn acquire_texture( + &self, + _timeout_ms: Option<Duration>, + _fence: &super::Fence, + ) -> Result<crate::AcquiredSurfaceTexture<super::Api>, crate::SurfaceError> { + let swapchain = self.swapchain.read(); + let sc = swapchain.as_ref().unwrap(); + let texture = super::Texture { + inner: super::TextureInner::Renderbuffer { + raw: sc.renderbuffer, + }, + drop_guard: None, + array_layer_count: 1, + mip_level_count: 1, + format: sc.format, + format_desc: sc.format_desc.clone(), + copy_size: crate::CopyExtent { + width: sc.extent.width, + height: sc.extent.height, + depth: 1, + }, + }; + Ok(crate::AcquiredSurfaceTexture { + texture, + suboptimal: false, + }) + } + unsafe fn discard_texture(&self, _texture: super::Texture) {} +} diff --git a/app/vendor/rune/vendor/wgpu-hal/src/lib.rs b/app/vendor/rune/vendor/wgpu-hal/src/lib.rs new file mode 100644 index 0000000..ca626f2 --- /dev/null +++ b/app/vendor/rune/vendor/wgpu-hal/src/lib.rs @@ -0,0 +1,3086 @@ +//! A cross-platform unsafe graphics abstraction. +//! +//! This crate defines a set of traits abstracting over modern graphics APIs, +//! with implementations ("backends") for Vulkan, Metal, Direct3D, and GL. +//! +//! `wgpu-hal` is a spiritual successor to +//! [gfx-hal](https://github.com/gfx-rs/gfx), but with reduced scope, and +//! oriented towards WebGPU implementation goals. It has no overhead for +//! validation or tracking, and the API translation overhead is kept to the bare +//! minimum by the design of WebGPU. This API can be used for resource-demanding +//! applications and engines. +//! +//! The `wgpu-hal` crate's main design choices: +//! +//! - Our traits are meant to be *portable*: proper use +//! should get equivalent results regardless of the backend. +//! +//! - Our traits' contracts are *unsafe*: implementations perform minimal +//! validation, if any, and incorrect use will often cause undefined behavior. +//! This allows us to minimize the overhead we impose over the underlying +//! graphics system. If you need safety, the [`wgpu-core`] crate provides a +//! safe API for driving `wgpu-hal`, implementing all necessary validation, +//! resource state tracking, and so on. (Note that `wgpu-core` is designed for +//! use via FFI; the [`wgpu`] crate provides more idiomatic Rust bindings for +//! `wgpu-core`.) Or, you can do your own validation. +//! +//! - In the same vein, returned errors *only cover cases the user can't +//! anticipate*, like running out of memory or losing the device. Any errors +//! that the user could reasonably anticipate are their responsibility to +//! avoid. For example, `wgpu-hal` returns no error for mapping a buffer that's +//! not mappable: as the buffer creator, the user should already know if they +//! can map it. +//! +//! - We use *static dispatch*. The traits are not +//! generally object-safe. You must select a specific backend type +//! like [`vulkan::Api`] or [`metal::Api`], and then use that +//! according to the main traits, or call backend-specific methods. +//! +//! - We use *idiomatic Rust parameter passing*, +//! taking objects by reference, returning them by value, and so on, +//! unlike `wgpu-core`, which refers to objects by ID. +//! +//! - We map buffer contents *persistently*. This means that the buffer can +//! remain mapped on the CPU while the GPU reads or writes to it. You must +//! explicitly indicate when data might need to be transferred between CPU and +//! GPU, if [`Device::map_buffer`] indicates that this is necessary. +//! +//! - You must record *explicit barriers* between different usages of a +//! resource. For example, if a buffer is written to by a compute +//! shader, and then used as and index buffer to a draw call, you +//! must use [`CommandEncoder::transition_buffers`] between those two +//! operations. +//! +//! - Pipeline layouts are *explicitly specified* when setting bind groups. +//! Incompatible layouts disturb groups bound at higher indices. +//! +//! - The API *accepts collections as iterators*, to avoid forcing the user to +//! store data in particular containers. The implementation doesn't guarantee +//! that any of the iterators are drained, unless stated otherwise by the +//! function documentation. For this reason, we recommend that iterators don't +//! do any mutating work. +//! +//! Unfortunately, `wgpu-hal`'s safety requirements are not fully documented. +//! Ideally, all trait methods would have doc comments setting out the +//! requirements users must meet to ensure correct and portable behavior. If you +//! are aware of a specific requirement that a backend imposes that is not +//! ensured by the traits' documented rules, please file an issue. Or, if you are +//! a capable technical writer, please file a pull request! +//! +//! [`wgpu-core`]: https://crates.io/crates/wgpu-core +//! [`wgpu`]: https://crates.io/crates/wgpu +//! [`vulkan::Api`]: vulkan/struct.Api.html +//! [`metal::Api`]: metal/struct.Api.html +//! +//! ## Primary backends +//! +//! The `wgpu-hal` crate has full-featured backends implemented on the following +//! platform graphics APIs: +//! +//! - Vulkan, available on Linux, Android, and Windows, using the [`ash`] crate's +//! Vulkan bindings. It's also available on macOS, if you install [MoltenVK]. +//! +//! - Metal on macOS, using the [`metal`] crate's bindings. +//! +//! - Direct3D 12 on Windows, using the [`windows`] crate's bindings. +//! +//! [`ash`]: https://crates.io/crates/ash +//! [MoltenVK]: https://github.com/KhronosGroup/MoltenVK +//! [`metal`]: https://crates.io/crates/metal +//! [`windows`]: https://crates.io/crates/windows +//! +//! ## Secondary backends +//! +//! The `wgpu-hal` crate has a partial implementation based on the following +//! platform graphics API: +//! +//! - The GL backend is available anywhere OpenGL, OpenGL ES, or WebGL are +//! available. See the [`gles`] module documentation for details. +//! +//! [`gles`]: gles/index.html +//! +//! You can see what capabilities an adapter is missing by checking the +//! [`DownlevelCapabilities`][tdc] in [`ExposedAdapter::capabilities`], available +//! from [`Instance::enumerate_adapters`]. +//! +//! The API is generally designed to fit the primary backends better than the +//! secondary backends, so the latter may impose more overhead. +//! +//! [tdc]: wgt::DownlevelCapabilities +//! +//! ## Traits +//! +//! The `wgpu-hal` crate defines a handful of traits that together +//! represent a cross-platform abstraction for modern GPU APIs. +//! +//! - The [`Api`] trait represents a `wgpu-hal` backend. It has no methods of its +//! own, only a collection of associated types. +//! +//! - [`Api::Instance`] implements the [`Instance`] trait. [`Instance::init`] +//! creates an instance value, which you can use to enumerate the adapters +//! available on the system. For example, [`vulkan::Api::Instance::init`][Ii] +//! returns an instance that can enumerate the Vulkan physical devices on your +//! system. +//! +//! - [`Api::Adapter`] implements the [`Adapter`] trait, representing a +//! particular device from a particular backend. For example, a Vulkan instance +//! might have a Lavapipe software adapter and a GPU-based adapter. +//! +//! - [`Api::Device`] implements the [`Device`] trait, representing an active +//! link to a device. You get a device value by calling [`Adapter::open`], and +//! then use it to create buffers, textures, shader modules, and so on. +//! +//! - [`Api::Queue`] implements the [`Queue`] trait, which you use to submit +//! command buffers to a given device. +//! +//! - [`Api::CommandEncoder`] implements the [`CommandEncoder`] trait, which you +//! use to build buffers of commands to submit to a queue. This has all the +//! methods for drawing and running compute shaders, which is presumably what +//! you're here for. +//! +//! - [`Api::Surface`] implements the [`Surface`] trait, which represents a +//! swapchain for presenting images on the screen, via interaction with the +//! system's window manager. +//! +//! The [`Api`] trait has various other associated types like [`Api::Buffer`] and +//! [`Api::Texture`] that represent resources the rest of the interface can +//! operate on, but these generally do not have their own traits. +//! +//! [Ii]: Instance::init +//! +//! ## Validation is the calling code's responsibility, not `wgpu-hal`'s +//! +//! As much as possible, `wgpu-hal` traits place the burden of validation, +//! resource tracking, and state tracking on the caller, not on the trait +//! implementations themselves. Anything which can reasonably be handled in +//! backend-independent code should be. A `wgpu_hal` backend's sole obligation is +//! to provide portable behavior, and report conditions that the calling code +//! can't reasonably anticipate, like device loss or running out of memory. +//! +//! The `wgpu` crate collection is intended for use in security-sensitive +//! applications, like web browsers, where the API is available to untrusted +//! code. This means that `wgpu-core`'s validation is not simply a service to +//! developers, to be provided opportunistically when the performance costs are +//! acceptable and the necessary data is ready at hand. Rather, `wgpu-core`'s +//! validation must be exhaustive, to ensure that even malicious content cannot +//! provoke and exploit undefined behavior in the platform's graphics API. +//! +//! Because graphics APIs' requirements are complex, the only practical way for +//! `wgpu` to provide exhaustive validation is to comprehensively track the +//! lifetime and state of all the resources in the system. Implementing this +//! separately for each backend is infeasible; effort would be better spent +//! making the cross-platform validation in `wgpu-core` legible and trustworthy. +//! Fortunately, the requirements are largely similar across the various +//! platforms, so cross-platform validation is practical. +//! +//! Some backends have specific requirements that aren't practical to foist off +//! on the `wgpu-hal` user. For example, properly managing macOS Objective-C or +//! Microsoft COM reference counts is best handled by using appropriate pointer +//! types within the backend. +//! +//! A desire for "defense in depth" may suggest performing additional validation +//! in `wgpu-hal` when the opportunity arises, but this must be done with +//! caution. Even experienced contributors infer the expectations their changes +//! must meet by considering not just requirements made explicit in types, tests, +//! assertions, and comments, but also those implicit in the surrounding code. +//! When one sees validation or state-tracking code in `wgpu-hal`, it is tempting +//! to conclude, "Oh, `wgpu-hal` checks for this, so `wgpu-core` needn't worry +//! about it - that would be redundant!" The responsibility for exhaustive +//! validation always rests with `wgpu-core`, regardless of what may or may not +//! be checked in `wgpu-hal`. +//! +//! To this end, any "defense in depth" validation that does appear in `wgpu-hal` +//! for requirements that `wgpu-core` should have enforced should report failure +//! via the `unreachable!` macro, because problems detected at this stage always +//! indicate a bug in `wgpu-core`. +//! +//! ## Debugging +//! +//! Most of the information on the wiki [Debugging wgpu Applications][wiki-debug] +//! page still applies to this API, with the exception of API tracing/replay +//! functionality, which is only available in `wgpu-core`. +//! +//! [wiki-debug]: https://github.com/gfx-rs/wgpu/wiki/Debugging-wgpu-Applications + +#![no_std] +#![cfg_attr(docsrs, feature(doc_cfg))] +#![allow( + // this happens on the GL backend, where it is both thread safe and non-thread safe in the same code. + clippy::arc_with_non_send_sync, + // We don't use syntax sugar where it's not necessary. + clippy::match_like_matches_macro, + // Redundant matching is more explicit. + clippy::redundant_pattern_matching, + // Explicit lifetimes are often easier to reason about. + clippy::needless_lifetimes, + // No need for defaults in the internal types. + clippy::new_without_default, + // Matches are good and extendable, no need to make an exception here. + clippy::single_match, + // Push commands are more regular than macros. + clippy::vec_init_then_push, + // TODO! + clippy::missing_safety_doc, + // It gets in the way a lot and does not prevent bugs in practice. + clippy::pattern_type_mismatch, + // We should investigate these. + clippy::large_enum_variant +)] +#![warn( + clippy::alloc_instead_of_core, + clippy::ptr_as_ptr, + clippy::std_instead_of_alloc, + clippy::std_instead_of_core, + trivial_casts, + trivial_numeric_casts, + unsafe_op_in_unsafe_fn, + unused_extern_crates, + unused_qualifications +)] + +extern crate alloc; +#[allow(unused_extern_crates)] +extern crate naga_types as nt; +extern crate wgpu_types as wgt; +// Each of these backends needs `std` in some fashion; usually `std::thread` functions. +#[cfg(any(dx12, gles_with_std, metal, vulkan))] +#[macro_use] +extern crate std; + +/// DirectX12 API internals. +#[cfg(dx12)] +pub mod dx12; +/// GLES API internals. +#[cfg(gles)] +pub mod gles; +/// Metal API internals. +#[cfg(metal)] +pub mod metal; +/// A dummy API implementation. +// TODO(https://github.com/gfx-rs/wgpu/issues/7120): this should have a cfg +pub mod noop; +/// Vulkan API internals. +#[cfg(vulkan)] +pub mod vulkan; + +pub mod auxil; +pub mod api { + #[cfg(dx12)] + pub use super::dx12::Api as Dx12; + #[cfg(gles)] + pub use super::gles::Api as Gles; + #[cfg(metal)] + pub use super::metal::Api as Metal; + pub use super::noop::Api as Noop; + #[cfg(vulkan)] + pub use super::vulkan::Api as Vulkan; +} + +mod dynamic; +#[cfg(feature = "validation_canary")] +mod validation_canary; + +#[cfg(feature = "validation_canary")] +pub use validation_canary::{ValidationCanary, VALIDATION_CANARY}; + +pub(crate) use dynamic::impl_dyn_resource; +pub use dynamic::{ + DynAccelerationStructure, DynAcquiredSurfaceTexture, DynAdapter, DynBindGroup, + DynBindGroupLayout, DynBuffer, DynCommandBuffer, DynCommandEncoder, DynComputePipeline, + DynDevice, DynExposedAdapter, DynFence, DynInstance, DynOpenDevice, DynPipelineCache, + DynPipelineLayout, DynQuerySet, DynQueue, DynRayTracingPipeline, DynRenderPipeline, + DynResource, DynSampler, DynShaderModule, DynSurface, DynSurfaceTexture, DynTexture, + DynTextureView, +}; + +#[allow(unused)] +use alloc::boxed::Box; +use alloc::{borrow::Cow, string::String, vec::Vec}; +use core::{ + borrow::Borrow, + error::Error, + fmt, + num::{NonZeroU32, NonZeroU64}, + ops::{Range, RangeInclusive}, + ptr::NonNull, +}; + +use bitflags::bitflags; +use raw_window_handle::DisplayHandle; +use thiserror::Error; +use wgt::WasmNotSendSync; + +cfg_if::cfg_if! { + if #[cfg(supports_ptr_atomics)] { + use alloc::sync::Arc; + } else if #[cfg(feature = "portable-atomic")] { + use portable_atomic_util::Arc; + } +} + +// - Vertex + Fragment +// - Compute +// Task + Mesh + Fragment +pub const MAX_CONCURRENT_SHADER_STAGES: usize = 3; +pub const MAX_ANISOTROPY: u8 = 16; +pub const MAX_BIND_GROUPS: usize = 8; +pub const MAX_VERTEX_BUFFERS: usize = 16; +pub const MAX_COLOR_ATTACHMENTS: usize = 8; +pub const MAX_MIP_LEVELS: u32 = 16; +/// Size of a single occlusion/timestamp query, when copied into a buffer, in bytes. +/// cbindgen:ignore +pub const QUERY_SIZE: wgt::BufferAddress = 8; + +pub type Label<'a> = Option<&'a str>; +pub type MemoryRange = Range<wgt::BufferAddress>; +pub type FenceValue = u64; +#[cfg(supports_64bit_atomics)] +pub type AtomicFenceValue = core::sync::atomic::AtomicU64; +#[cfg(not(supports_64bit_atomics))] +pub type AtomicFenceValue = portable_atomic::AtomicU64; + +/// A callback to signal that wgpu is no longer using a resource. +#[cfg(any(gles, vulkan, metal))] +pub type DropCallback = Box<dyn FnOnce() + Send + Sync + 'static>; + +#[cfg(any(gles, vulkan, metal))] +pub struct DropGuard { + callback: Option<DropCallback>, +} + +#[cfg(all(any(gles, vulkan, metal), any(native, Emscripten)))] +impl DropGuard { + fn from_option(callback: Option<DropCallback>) -> Option<Self> { + callback.map(Self::new) + } + + fn new(callback: DropCallback) -> Self { + Self { + callback: Some(callback), + } + } +} + +#[cfg(any(gles, vulkan, metal))] +impl Drop for DropGuard { + fn drop(&mut self) { + if let Some(cb) = self.callback.take() { + (cb)(); + } + } +} + +#[cfg(any(gles, vulkan, metal))] +impl fmt::Debug for DropGuard { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("DropGuard").finish() + } +} + +#[derive(Clone, Debug, PartialEq, Eq, Error)] +pub enum DeviceError { + #[error("Out of memory")] + OutOfMemory, + #[error("Device is lost")] + Lost, + #[error("Unexpected error variant (driver implementation is at fault)")] + Unexpected, +} + +#[cfg(any(dx12, vulkan))] +impl From<gpu_allocator::AllocationError> for DeviceError { + fn from(result: gpu_allocator::AllocationError) -> Self { + match result { + gpu_allocator::AllocationError::OutOfMemory => Self::OutOfMemory, + gpu_allocator::AllocationError::FailedToMap(e) => { + log::error!("gpu-allocator: Failed to map: {e}"); + Self::Lost + } + gpu_allocator::AllocationError::NoCompatibleMemoryTypeFound => { + log::error!("gpu-allocator: No Compatible Memory Type Found"); + Self::Lost + } + gpu_allocator::AllocationError::InvalidAllocationCreateDesc => { + log::error!("gpu-allocator: Invalid Allocation Creation Description"); + Self::Lost + } + gpu_allocator::AllocationError::InvalidAllocatorCreateDesc(e) => { + log::error!("gpu-allocator: Invalid Allocator Creation Description: {e}"); + Self::Lost + } + + gpu_allocator::AllocationError::Internal(e) => { + log::error!("gpu-allocator: Internal Error: {e}"); + Self::Lost + } + gpu_allocator::AllocationError::BarrierLayoutNeedsDevice10 + | gpu_allocator::AllocationError::CastableFormatsRequiresEnhancedBarriers + | gpu_allocator::AllocationError::CastableFormatsRequiresAtLeastDevice12 => { + unreachable!() + } + } + } +} + +// A copy of gpu_allocator::AllocationSizes, allowing to read the configured value for +// the dx12 backend, we should instead add getters to gpu_allocator::AllocationSizes +// and remove this type. +// https://github.com/Traverse-Research/gpu-allocator/issues/295 +#[cfg_attr(not(any(dx12, vulkan)), expect(dead_code))] +pub(crate) struct AllocationSizes { + pub(crate) min_device_memblock_size: u64, + pub(crate) max_device_memblock_size: u64, + pub(crate) min_host_memblock_size: u64, + pub(crate) max_host_memblock_size: u64, +} + +impl AllocationSizes { + #[allow(dead_code, reason = "may be unused on some platforms")] + pub(crate) fn from_memory_hints(memory_hints: &wgt::MemoryHints) -> Self { + // TODO: the allocator's configuration should take hardware capability into + // account. + const MB: u64 = 1024 * 1024; + + match memory_hints { + wgt::MemoryHints::Performance => Self { + min_device_memblock_size: 128 * MB, + max_device_memblock_size: 256 * MB, + min_host_memblock_size: 64 * MB, + max_host_memblock_size: 128 * MB, + }, + wgt::MemoryHints::MemoryUsage => Self { + min_device_memblock_size: 8 * MB, + max_device_memblock_size: 64 * MB, + min_host_memblock_size: 4 * MB, + max_host_memblock_size: 32 * MB, + }, + wgt::MemoryHints::Manual { + suballocated_device_memory_block_size, + } => { + // TODO: https://github.com/gfx-rs/wgpu/issues/8625 + // Would it be useful to expose the host size in memory hints + // instead of always using half of the device size? + let device_size = suballocated_device_memory_block_size; + let host_size = device_size.start / 2..device_size.end / 2; + + // gpu_allocator clamps the sizes between 4MiB and 256MiB, but we clamp them ourselves since we use + // the sizes when detecting high memory pressure and there is no way to query the values otherwise. + Self { + min_device_memblock_size: device_size.start.clamp(4 * MB, 256 * MB), + max_device_memblock_size: device_size.end.clamp(4 * MB, 256 * MB), + min_host_memblock_size: host_size.start.clamp(4 * MB, 256 * MB), + max_host_memblock_size: host_size.end.clamp(4 * MB, 256 * MB), + } + } + } + } +} + +#[cfg(any(dx12, vulkan))] +impl From<AllocationSizes> for gpu_allocator::AllocationSizes { + fn from(value: AllocationSizes) -> gpu_allocator::AllocationSizes { + gpu_allocator::AllocationSizes::new( + value.min_device_memblock_size, + value.min_host_memblock_size, + ) + .with_max_device_memblock_size(value.max_device_memblock_size) + .with_max_host_memblock_size(value.max_host_memblock_size) + } +} + +#[allow(dead_code, reason = "may be unused on some platforms")] +#[cold] +fn hal_usage_error<T: fmt::Display>(txt: T) -> ! { + panic!("wgpu-hal invariant was violated (usage error): {txt}") +} + +#[allow(dead_code, reason = "may be unused on some platforms")] +#[cold] +fn hal_internal_error<T: fmt::Display>(txt: T) -> ! { + panic!("wgpu-hal ran into a preventable internal error: {txt}") +} + +#[derive(Clone, Debug, Eq, PartialEq, Error)] +pub enum ShaderError { + #[error("Compilation failed: {0:?}")] + Compilation(String), + #[error(transparent)] + Device(#[from] DeviceError), +} + +#[derive(Clone, Debug, Eq, PartialEq, Error)] +pub enum PipelineError { + #[error("Linkage failed for stage {0:?}: {1}")] + Linkage(wgt::ShaderStages, String), + #[error("Entry point for stage {0:?} is invalid")] + EntryPoint(naga::ShaderStage), + #[error(transparent)] + Device(#[from] DeviceError), + #[error("Pipeline constant error for stage {0:?}: {1}")] + PipelineConstants(wgt::ShaderStages, String), +} + +#[derive(Clone, Debug, Eq, PartialEq, Error)] +pub enum PipelineCacheError { + #[error(transparent)] + Device(#[from] DeviceError), +} + +#[derive(Clone, Debug, Eq, PartialEq, Error)] +pub enum SurfaceError { + #[error("Surface is lost")] + Lost, + #[error("Surface is outdated, needs to be re-created")] + Outdated, + #[error("Timed out waiting for a surface texture")] + Timeout, + #[error("The window is occluded (e.g. minimized or behind another window). Try again once the window is no longer occluded.")] + Occluded, + #[error(transparent)] + Device(#[from] DeviceError), + #[error("Other reason: {0}")] + Other(&'static str), +} + +/// Error occurring while trying to create an instance, or create a surface from an instance; +/// typically relating to the state of the underlying graphics API or hardware. +#[derive(Clone, Debug, Error)] +#[error("{message}")] +pub struct InstanceError { + /// These errors are very platform specific, so do not attempt to encode them as an enum. + /// + /// This message should describe the problem in sufficient detail to be useful for a + /// user-to-developer “why won't this work on my machine” bug report, and otherwise follow + /// <https://rust-lang.github.io/api-guidelines/interoperability.html#error-types-are-meaningful-and-well-behaved-c-good-err>. + message: String, + + /// Underlying error value, if any is available. + #[source] + source: Option<Arc<dyn Error + Send + Sync + 'static>>, +} + +impl InstanceError { + #[allow(dead_code, reason = "may be unused on some platforms")] + pub(crate) fn new(message: String) -> Self { + Self { + message, + source: None, + } + } + #[allow(dead_code, reason = "may be unused on some platforms")] + pub(crate) fn with_source(message: String, source: impl Error + Send + Sync + 'static) -> Self { + cfg_if::cfg_if! { + if #[cfg(supports_ptr_atomics)] { + let source = Arc::new(source); + } else { + // TODO(https://github.com/rust-lang/rust/issues/18598): avoid indirection via Box once arbitrary types support unsized coercion + let source: Box<dyn Error + Send + Sync + 'static> = Box::new(source); + let source = Arc::from(source); + } + } + Self { + message, + source: Some(source), + } + } +} + +/// All the types and methods that make up a implementation on top of a backend. +/// +/// Only the types that have non-dyn trait bounds have methods on them. Most methods +/// are either on [`CommandEncoder`] or [`Device`]. +/// +/// The api can either be used through generics (through use of this trait and associated +/// types) or dynamically through using the `Dyn*` traits. +pub trait Api: Clone + fmt::Debug + Sized + WasmNotSendSync + 'static { + const VARIANT: wgt::Backend; + + type Instance: DynInstance + Instance<A = Self>; + type Surface: DynSurface + Surface<A = Self>; + type Adapter: DynAdapter + Adapter<A = Self>; + type Device: DynDevice + Device<A = Self>; + + type Queue: DynQueue + Queue<A = Self>; + type CommandEncoder: DynCommandEncoder + CommandEncoder<A = Self>; + + /// This API's command buffer type. + /// + /// The only thing you can do with `CommandBuffer`s is build them + /// with a [`CommandEncoder`] and then pass them to + /// [`Queue::submit`] for execution, or destroy them by passing + /// them to [`CommandEncoder::reset_all`]. + /// + /// [`CommandEncoder`]: Api::CommandEncoder + type CommandBuffer: DynCommandBuffer; + + type Buffer: DynBuffer; + type Texture: DynTexture; + type SurfaceTexture: DynSurfaceTexture + Borrow<Self::Texture>; + type TextureView: DynTextureView; + type Sampler: DynSampler; + type QuerySet: DynQuerySet; + + /// A value you can block on to wait for something to finish. + /// + /// A `Fence` holds a monotonically increasing [`FenceValue`]. You can call + /// [`Device::wait`] to block until a fence reaches or passes a value you + /// choose. [`Queue::submit`] can take a `Fence` and a [`FenceValue`] to + /// store in it when the submitted work is complete. + /// + /// Attempting to set a fence to a value less than its current value has no + /// effect. + /// + /// Waiting on a fence returns as soon as the fence reaches *or passes* the + /// requested value. This implies that, in order to reliably determine when + /// an operation has completed, operations must finish in order of + /// increasing fence values: if a higher-valued operation were to finish + /// before a lower-valued operation, then waiting for the fence to reach the + /// lower value could return before the lower-valued operation has actually + /// finished. + /// + /// Fences are internally synchronised by the hal, and so should not need to be + /// contained in external synchronisation primitives. + type Fence: DynFence; + + type BindGroupLayout: DynBindGroupLayout; + type BindGroup: DynBindGroup; + type PipelineLayout: DynPipelineLayout; + type ShaderModule: DynShaderModule; + type RenderPipeline: DynRenderPipeline; + type ComputePipeline: DynComputePipeline; + type RayTracingPipeline: DynRayTracingPipeline; + type PipelineCache: DynPipelineCache; + + type AccelerationStructure: DynAccelerationStructure + 'static; +} + +pub trait Instance: Sized + WasmNotSendSync { + type A: Api; + + unsafe fn init(desc: &InstanceDescriptor<'_>) -> Result<Self, InstanceError>; + unsafe fn create_surface( + &self, + display_handle: raw_window_handle::RawDisplayHandle, + window_handle: raw_window_handle::RawWindowHandle, + ) -> Result<<Self::A as Api>::Surface, InstanceError>; + /// `surface_hint` is only used by the GLES backend targeting WebGL2 + unsafe fn enumerate_adapters( + &self, + surface_hint: Option<&<Self::A as Api>::Surface>, + ) -> Vec<ExposedAdapter<Self::A>>; +} + +pub trait Surface: WasmNotSendSync { + type A: Api; + + /// Configure `self` to use `device`. + /// + /// # Safety + /// + /// - All GPU work using `self` must have been completed. + /// - All [`AcquiredSurfaceTexture`]s must have been destroyed. + /// - All [`Api::TextureView`]s derived from the [`AcquiredSurfaceTexture`]s must have been destroyed. + /// - The surface `self` must not currently be configured to use any other [`Device`]. + unsafe fn configure( + &self, + device: &<Self::A as Api>::Device, + config: &SurfaceConfiguration, + ) -> Result<(), SurfaceError>; + + /// Unconfigure `self` on `device`. + /// + /// # Safety + /// + /// - All GPU work that uses `surface` must have been completed. + /// - All [`AcquiredSurfaceTexture`]s must have been destroyed. + /// - All [`Api::TextureView`]s derived from the [`AcquiredSurfaceTexture`]s must have been destroyed. + /// - The surface `self` must have been configured on `device`. + unsafe fn unconfigure(&self, device: &<Self::A as Api>::Device); + + /// Return the next texture to be presented by `self`, for the caller to draw on. + /// + /// On success, return an [`AcquiredSurfaceTexture`] representing the + /// texture into which the caller should draw the image to be displayed on + /// `self`. + /// + /// If `timeout` elapses before `self` has a texture ready to be acquired, + /// return `Err(SurfaceError::Timeout)`. If `timeout` is `None`, wait + /// indefinitely, with no timeout. + /// + /// # Using an [`AcquiredSurfaceTexture`] + /// + /// On success, this function returns an [`AcquiredSurfaceTexture`] whose + /// [`texture`] field is a [`SurfaceTexture`] from which the caller can + /// [`borrow`] a [`Texture`] to draw on. The [`AcquiredSurfaceTexture`] also + /// carries some metadata about that [`SurfaceTexture`]. + /// + /// All calls to [`Queue::submit`] that draw on that [`Texture`] must also + /// include the [`SurfaceTexture`] in the `surface_textures` argument. + /// + /// When you are done drawing on the texture, you can display it on `self` + /// by passing the [`SurfaceTexture`] and `self` to [`Queue::present`]. + /// + /// If you do not wish to display the texture, you must pass the + /// [`SurfaceTexture`] to [`self.discard_texture`], so that it can be reused + /// by future acquisitions. + /// + /// The fence is internally synchronised by the hal. + /// + /// # Portability + /// + /// Some backends can't support a timeout when acquiring a texture. On these + /// backends, `timeout` is ignored. + /// + /// On macOS, this returns `Err(SurfaceError::Timeout)` when the window is + /// not visible (minimized, fully occluded, or on another virtual desktop) + /// to avoid blocking in `CAMetalLayer.nextDrawable()`. + /// + /// # Safety + /// + /// - The surface `self` must currently be configured on some [`Device`]. + /// + /// - The `fence` argument must be the same [`Fence`] passed to all calls to + /// [`Queue::submit`] that used [`Texture`]s acquired from this surface. + /// + /// - You may only have one texture acquired from `self` at a time. When + /// `acquire_texture` returns `Ok(ast)`, you must pass the returned + /// [`SurfaceTexture`] `ast.texture` to either [`Queue::present`] or + /// [`Surface::discard_texture`] before calling `acquire_texture` again. + /// + /// [`texture`]: AcquiredSurfaceTexture::texture + /// [`SurfaceTexture`]: Api::SurfaceTexture + /// [`borrow`]: alloc::borrow::Borrow::borrow + /// [`Texture`]: Api::Texture + /// [`Fence`]: Api::Fence + /// [`self.discard_texture`]: Surface::discard_texture + unsafe fn acquire_texture( + &self, + timeout: Option<core::time::Duration>, + fence: &<Self::A as Api>::Fence, + ) -> Result<AcquiredSurfaceTexture<Self::A>, SurfaceError>; + + /// Relinquish an acquired texture without presenting it. + /// + /// After this call, the texture underlying [`SurfaceTexture`] may be + /// returned by subsequent calls to [`self.acquire_texture`]. + /// + /// # Safety + /// + /// - The surface `self` must currently be configured on some [`Device`]. + /// + /// - `texture` must be a [`SurfaceTexture`] returned by a call to + /// [`self.acquire_texture`] that has not yet been passed to + /// [`Queue::present`]. + /// + /// [`SurfaceTexture`]: Api::SurfaceTexture + /// [`self.acquire_texture`]: Surface::acquire_texture + unsafe fn discard_texture(&self, texture: <Self::A as Api>::SurfaceTexture); +} + +pub trait Adapter: WasmNotSendSync { + type A: Api; + + unsafe fn open( + &self, + features: wgt::Features, + limits: &wgt::Limits, + memory_hints: &wgt::MemoryHints, + ) -> Result<OpenDevice<Self::A>, DeviceError>; + + /// Return the set of supported capabilities for a texture format. + unsafe fn texture_format_capabilities( + &self, + format: wgt::TextureFormat, + ) -> TextureFormatCapabilities; + + /// Returns the capabilities of working with a specified surface. + /// + /// `None` means presentation is not supported for it. + unsafe fn surface_capabilities( + &self, + surface: &<Self::A as Api>::Surface, + ) -> Option<SurfaceCapabilities>; + + /// Returns the HDR / luminance characteristics of the display backing + /// `surface`, queried from the OS on each call. + /// + /// `None` means no information is available; wgpu-core maps it to + /// [`wgt::DisplayHdrInfo::default`]. Implementors must not panic; degrade any + /// OS-query failure to `None`. The default implementation returns `None`. + /// + /// Implemented by Metal (macOS only, and only from the main thread), DX12, and + /// Vulkan (Win32 `HWND` surfaces only); GLES and noop keep the default `None`. + unsafe fn surface_display_hdr_info( + &self, + surface: &<Self::A as Api>::Surface, + ) -> Option<wgt::DisplayHdrInfo> { + let _ = surface; + None + } + + /// Creates a [`PresentationTimestamp`] using the adapter's WSI. + /// + /// [`PresentationTimestamp`]: wgt::PresentationTimestamp + unsafe fn get_presentation_timestamp(&self) -> wgt::PresentationTimestamp; + + /// The combination of all usages that the are guaranteed to be be ordered by the hardware. + /// If a usage is ordered, then if the buffer state doesn't change between draw calls, + /// there are no barriers needed for synchronization. + fn get_ordered_buffer_usages(&self) -> wgt::BufferUses; + + /// The combination of all usages that the are guaranteed to be be ordered by the hardware. + /// If a usage is ordered, then if the buffer state doesn't change between draw calls, + /// there are no barriers needed for synchronization. + fn get_ordered_texture_usages(&self) -> wgt::TextureUses; +} + +/// A connection to a GPU and a pool of resources to use with it. +/// +/// A `wgpu-hal` `Device` represents an open connection to a specific graphics +/// processor, controlled via the backend [`Device::A`]. A `Device` is mostly +/// used for creating resources. Each `Device` has an associated [`Queue`] used +/// for command submission. +/// +/// On Vulkan a `Device` corresponds to a logical device ([`VkDevice`]). Other +/// backends don't have an exact analog: for example, [`ID3D12Device`]s and +/// [`MTLDevice`]s are owned by the backends' [`wgpu_hal::Adapter`] +/// implementations, and shared by all [`wgpu_hal::Device`]s created from that +/// `Adapter`. +/// +/// A `Device`'s life cycle is generally: +/// +/// 1) Obtain a `Device` and its associated [`Queue`] by calling +/// [`Adapter::open`]. +/// +/// Alternatively, the backend-specific types that implement [`Adapter`] often +/// have methods for creating a `wgpu-hal` `Device` from a platform-specific +/// handle. For example, [`vulkan::Adapter::device_from_raw`] can create a +/// [`vulkan::Device`] from an [`ash::Device`]. +/// +/// 1) Create resources to use on the device by calling methods like +/// [`Device::create_texture`] or [`Device::create_shader_module`]. +/// +/// 1) Call [`Device::create_command_encoder`] to obtain a [`CommandEncoder`], +/// which you can use to build [`CommandBuffer`]s holding commands to be +/// executed on the GPU. +/// +/// 1) Call [`Queue::submit`] on the `Device`'s associated [`Queue`] to submit +/// [`CommandBuffer`]s for execution on the GPU. If needed, call +/// [`Device::wait`] to wait for them to finish execution. +/// +/// 1) Free resources with methods like [`Device::destroy_texture`] or +/// [`Device::destroy_shader_module`]. +/// +/// 1) Drop the device. +/// +/// [`vkDevice`]: https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html#VkDevice +/// [`ID3D12Device`]: https://learn.microsoft.com/en-us/windows/win32/api/d3d12/nn-d3d12-id3d12device +/// [`MTLDevice`]: https://developer.apple.com/documentation/metal/mtldevice +/// [`wgpu_hal::Adapter`]: Adapter +/// [`wgpu_hal::Device`]: Device +/// [`vulkan::Adapter::device_from_raw`]: vulkan/struct.Adapter.html#method.device_from_raw +/// [`vulkan::Device`]: vulkan/struct.Device.html +/// [`ash::Device`]: https://docs.rs/ash/latest/ash/struct.Device.html +/// [`CommandBuffer`]: Api::CommandBuffer +/// +/// # Safety +/// +/// As with other `wgpu-hal` APIs, [validation] is the caller's +/// responsibility. Here are the general requirements for all `Device` +/// methods: +/// +/// - Any resource passed to a `Device` method must have been created by that +/// `Device`. For example, a [`Texture`] passed to [`Device::destroy_texture`] must +/// have been created with the `Device` passed as `self`. +/// +/// - Resources may not be destroyed if they are used by any submitted command +/// buffers that have not yet finished execution. +/// +/// [validation]: index.html#validation-is-the-calling-codes-responsibility-not-wgpu-hals +/// [`Texture`]: Api::Texture +pub trait Device: WasmNotSendSync { + type A: Api; + + /// Creates a new buffer. + /// + /// The initial usage is `wgt::BufferUses::empty()`. + unsafe fn create_buffer( + &self, + desc: &BufferDescriptor, + ) -> Result<<Self::A as Api>::Buffer, DeviceError>; + + /// Free `buffer` and any GPU resources it owns. + /// + /// Note that backends are allowed to allocate GPU memory for buffers from + /// allocation pools, and this call is permitted to simply return `buffer`'s + /// storage to that pool, without making it available to other applications. + /// + /// # Safety + /// + /// - The given `buffer` must not currently be mapped. + unsafe fn destroy_buffer(&self, buffer: <Self::A as Api>::Buffer); + + /// A hook for when a wgpu-core buffer is created from a raw wgpu-hal buffer. + unsafe fn add_raw_buffer(&self, buffer: &<Self::A as Api>::Buffer); + + /// Return a pointer to CPU memory mapping the contents of `buffer`. + /// + /// Buffer mappings are persistent: the buffer may remain mapped on the CPU + /// while the GPU reads or writes to it. (Note that `wgpu_core` does not use + /// this feature: when a `wgpu_core::Buffer` is unmapped, the underlying + /// `wgpu_hal` buffer is also unmapped.) + /// + /// If this function returns `Ok(mapping)`, then: + /// + /// - `mapping.ptr` is the CPU address of the start of the mapped memory. + /// + /// - If `mapping.is_coherent` is `true`, then CPU writes to the mapped + /// memory are immediately visible on the GPU, and vice versa. + /// + /// # Safety + /// + /// - The given `buffer` must have been created with the [`MAP_READ`] or + /// [`MAP_WRITE`] flags set in [`BufferDescriptor::usage`]. + /// + /// - The given `range` must fall within the size of `buffer`. + /// + /// - The caller must avoid data races between the CPU and the GPU. A data + /// race is any pair of accesses to a particular byte, one of which is a + /// write, that are not ordered with respect to each other by some sort of + /// synchronization operation. + /// + /// - If this function returns `Ok(mapping)` and `mapping.is_coherent` is + /// `false`, then: + /// + /// - Every CPU write to a mapped byte followed by a GPU read of that byte + /// must have at least one call to [`Device::flush_mapped_ranges`] + /// covering that byte that occurs between those two accesses. + /// + /// - Every GPU write to a mapped byte followed by a CPU read of that byte + /// must have at least one call to [`Device::invalidate_mapped_ranges`] + /// covering that byte that occurs between those two accesses. + /// + /// Note that the data race rule above requires that all such access pairs + /// be ordered, so it is meaningful to talk about what must occur + /// "between" them. + /// + /// - Zero-sized mappings are not allowed. + /// + /// - The returned [`BufferMapping::ptr`] must not be used after a call to + /// [`Device::unmap_buffer`]. + /// + /// [`MAP_READ`]: wgt::BufferUses::MAP_READ + /// [`MAP_WRITE`]: wgt::BufferUses::MAP_WRITE + unsafe fn map_buffer( + &self, + buffer: &<Self::A as Api>::Buffer, + range: MemoryRange, + ) -> Result<BufferMapping, DeviceError>; + + /// Remove the mapping established by the last call to [`Device::map_buffer`]. + /// + /// # Safety + /// + /// - The given `buffer` must be currently mapped. + unsafe fn unmap_buffer(&self, buffer: &<Self::A as Api>::Buffer); + + /// Indicate that CPU writes to mapped buffer memory should be made visible to the GPU. + /// + /// # Safety + /// + /// - The given `buffer` must be currently mapped. + /// + /// - All ranges produced by `ranges` must fall within `buffer`'s size. + unsafe fn flush_mapped_ranges<I>(&self, buffer: &<Self::A as Api>::Buffer, ranges: I) + where + I: Iterator<Item = MemoryRange>; + + /// Indicate that GPU writes to mapped buffer memory should be made visible to the CPU. + /// + /// # Safety + /// + /// - The given `buffer` must be currently mapped. + /// + /// - All ranges produced by `ranges` must fall within `buffer`'s size. + unsafe fn invalidate_mapped_ranges<I>(&self, buffer: &<Self::A as Api>::Buffer, ranges: I) + where + I: Iterator<Item = MemoryRange>; + + /// Creates a new texture. + /// + /// The initial usage for all subresources is `wgt::TextureUses::UNINITIALIZED`. + unsafe fn create_texture( + &self, + desc: &TextureDescriptor, + ) -> Result<<Self::A as Api>::Texture, DeviceError>; + unsafe fn destroy_texture(&self, texture: <Self::A as Api>::Texture); + + /// A hook for when a wgpu-core texture is created from a raw wgpu-hal texture. + unsafe fn add_raw_texture(&self, texture: &<Self::A as Api>::Texture); + + unsafe fn create_texture_view( + &self, + texture: &<Self::A as Api>::Texture, + desc: &TextureViewDescriptor, + ) -> Result<<Self::A as Api>::TextureView, DeviceError>; + unsafe fn destroy_texture_view(&self, view: <Self::A as Api>::TextureView); + unsafe fn create_sampler( + &self, + desc: &SamplerDescriptor, + ) -> Result<<Self::A as Api>::Sampler, DeviceError>; + unsafe fn destroy_sampler(&self, sampler: <Self::A as Api>::Sampler); + + /// Create a fresh [`CommandEncoder`]. + /// + /// The new `CommandEncoder` is in the "closed" state. + unsafe fn create_command_encoder( + &self, + desc: &CommandEncoderDescriptor<<Self::A as Api>::Queue>, + ) -> Result<<Self::A as Api>::CommandEncoder, DeviceError>; + + /// Creates a bind group layout. + unsafe fn create_bind_group_layout( + &self, + desc: &BindGroupLayoutDescriptor, + ) -> Result<<Self::A as Api>::BindGroupLayout, DeviceError>; + unsafe fn destroy_bind_group_layout(&self, bg_layout: <Self::A as Api>::BindGroupLayout); + unsafe fn create_pipeline_layout( + &self, + desc: &PipelineLayoutDescriptor<<Self::A as Api>::BindGroupLayout>, + ) -> Result<<Self::A as Api>::PipelineLayout, DeviceError>; + unsafe fn destroy_pipeline_layout(&self, pipeline_layout: <Self::A as Api>::PipelineLayout); + + #[allow(clippy::type_complexity)] + unsafe fn create_bind_group( + &self, + desc: &BindGroupDescriptor< + <Self::A as Api>::BindGroupLayout, + <Self::A as Api>::Buffer, + <Self::A as Api>::Sampler, + <Self::A as Api>::TextureView, + <Self::A as Api>::AccelerationStructure, + >, + ) -> Result<<Self::A as Api>::BindGroup, DeviceError>; + unsafe fn destroy_bind_group(&self, group: <Self::A as Api>::BindGroup); + + unsafe fn create_shader_module( + &self, + desc: &ShaderModuleDescriptor, + shader: ShaderInput, + ) -> Result<<Self::A as Api>::ShaderModule, ShaderError>; + unsafe fn destroy_shader_module(&self, module: <Self::A as Api>::ShaderModule); + + #[allow(clippy::type_complexity)] + unsafe fn create_render_pipeline( + &self, + desc: &RenderPipelineDescriptor< + <Self::A as Api>::PipelineLayout, + <Self::A as Api>::ShaderModule, + <Self::A as Api>::PipelineCache, + >, + ) -> Result<<Self::A as Api>::RenderPipeline, PipelineError>; + unsafe fn destroy_render_pipeline(&self, pipeline: <Self::A as Api>::RenderPipeline); + + #[allow(clippy::type_complexity)] + unsafe fn create_compute_pipeline( + &self, + desc: &ComputePipelineDescriptor< + <Self::A as Api>::PipelineLayout, + <Self::A as Api>::ShaderModule, + <Self::A as Api>::PipelineCache, + >, + ) -> Result<<Self::A as Api>::ComputePipeline, PipelineError>; + unsafe fn destroy_compute_pipeline(&self, pipeline: <Self::A as Api>::ComputePipeline); + + #[allow(clippy::type_complexity)] + unsafe fn create_ray_tracing_pipeline( + &self, + desc: &RayTracingPipelineDescriptor< + <Self::A as Api>::PipelineLayout, + <Self::A as Api>::ShaderModule, + <Self::A as Api>::PipelineCache, + >, + ) -> Result<<Self::A as Api>::RayTracingPipeline, PipelineError>; + unsafe fn destroy_ray_tracing_pipeline(&self, pipeline: <Self::A as Api>::RayTracingPipeline); + /// Obtain the opaque data from each group, behaves as if group 0 is the ray generation, group 1 + /// is the miss shader, and group 2.. are the intersection groups. + unsafe fn get_raytracing_pipeline_group_data( + &self, + pipeline: &<Self::A as Api>::RayTracingPipeline, + groups: Range<u32>, + ) -> Result<Vec<u8>, DeviceError>; + + unsafe fn create_pipeline_cache( + &self, + desc: &PipelineCacheDescriptor<'_>, + ) -> Result<<Self::A as Api>::PipelineCache, PipelineCacheError>; + fn pipeline_cache_validation_key(&self) -> Option<[u8; 16]> { + None + } + unsafe fn destroy_pipeline_cache(&self, cache: <Self::A as Api>::PipelineCache); + + unsafe fn create_query_set( + &self, + desc: &wgt::QuerySetDescriptor<Label>, + ) -> Result<<Self::A as Api>::QuerySet, DeviceError>; + unsafe fn destroy_query_set(&self, set: <Self::A as Api>::QuerySet); + unsafe fn create_fence(&self) -> Result<<Self::A as Api>::Fence, DeviceError>; + unsafe fn destroy_fence(&self, fence: <Self::A as Api>::Fence); + unsafe fn get_fence_value( + &self, + fence: &<Self::A as Api>::Fence, + ) -> Result<FenceValue, DeviceError>; + + /// Wait for `fence` to reach `value`. + /// + /// Operations like [`Queue::submit`] can accept a [`Fence`] and a + /// [`FenceValue`] to store in it, so you can use this `wait` function + /// to wait for a given queue submission to finish execution. + /// + /// The `value` argument must not exceed the highest value that an actual + /// operation you have already presented to the device is going to store in + /// `fence`. You cannot wait for values yet to be submitted. (This + /// restriction accommodates implementations like the `vulkan` backend's + /// [`FencePool`] that must allocate a distinct synchronization object for + /// each fence value one is able to wait for.) + /// + /// Calling `wait` with a lower [`FenceValue`] than `fence`'s current value + /// returns immediately. + /// + /// If `timeout` is not provided, the function will block indefinitely or until + /// an error is encountered. + /// + /// Returns `Ok(true)` on success and `Ok(false)` on timeout. + /// + /// [`Fence`]: Api::Fence + /// [`FencePool`]: vulkan/enum.Fence.html#variant.FencePool + unsafe fn wait( + &self, + fence: &<Self::A as Api>::Fence, + value: FenceValue, + timeout: Option<core::time::Duration>, + ) -> Result<bool, DeviceError>; + + /// Start a graphics debugger capture. + /// + /// # Safety + /// + /// See [`wgpu::Device::start_graphics_debugger_capture`][api] for more details. + /// + /// [api]: ../wgpu/struct.Device.html#method.start_graphics_debugger_capture + unsafe fn start_graphics_debugger_capture(&self) -> bool; + + /// Stop a graphics debugger capture. + /// + /// # Safety + /// + /// See [`wgpu::Device::stop_graphics_debugger_capture`][api] for more details. + /// + /// [api]: ../wgpu/struct.Device.html#method.stop_graphics_debugger_capture + unsafe fn stop_graphics_debugger_capture(&self); + + #[allow(unused_variables)] + unsafe fn pipeline_cache_get_data( + &self, + cache: &<Self::A as Api>::PipelineCache, + ) -> Option<Vec<u8>> { + None + } + + unsafe fn create_acceleration_structure( + &self, + desc: &AccelerationStructureDescriptor, + ) -> Result<<Self::A as Api>::AccelerationStructure, DeviceError>; + unsafe fn get_acceleration_structure_build_sizes( + &self, + desc: &GetAccelerationStructureBuildSizesDescriptor<<Self::A as Api>::Buffer>, + ) -> AccelerationStructureBuildSizes; + unsafe fn get_acceleration_structure_device_address( + &self, + acceleration_structure: &<Self::A as Api>::AccelerationStructure, + ) -> wgt::BufferAddress; + unsafe fn destroy_acceleration_structure( + &self, + acceleration_structure: <Self::A as Api>::AccelerationStructure, + ); + fn tlas_instance_to_bytes(&self, instance: TlasInstance) -> Vec<u8>; + + fn get_internal_counters(&self) -> wgt::HalCounters; + + fn generate_allocator_report(&self) -> Option<wgt::AllocatorReport> { + None + } + + fn check_if_oom(&self) -> Result<(), DeviceError>; +} + +pub trait Queue: WasmNotSendSync { + type A: Api; + + /// Submit `command_buffers` for execution on GPU. + /// + /// Update `fence` to `value` when the operation is complete. See + /// [`Fence`] for details. + /// + /// All command buffers submitted to a `wgpu_hal` queue are executed in the + /// order they're submitted, with each buffer able to observe the effects of + /// previous buffers' execution. Specifically: + /// + /// - If two calls to `submit` on a single `Queue` occur in a particular + /// order (that is, they happen on the same thread, or on two threads that + /// have synchronized to establish an ordering), then the first + /// submission's commands all complete execution before any of the second + /// submission's commands begin. All results produced by one submission + /// are visible to the next. + /// + /// - Within a submission, command buffers execute in the order in which they + /// appear in `command_buffers`. All results produced by one buffer are + /// visible to the next. + /// + /// If two calls to `submit` on a single `Queue` from different threads are + /// not synchronized to occur in a particular order, they must pass distinct + /// [`Fence`]s. As explained in the [`Fence`] documentation, waiting for + /// operations to complete is only trustworthy when operations finish in + /// order of increasing fence value, but submissions from different threads + /// cannot determine how to order the fence values if the submissions + /// themselves are unordered. If each thread uses a separate [`Fence`], this + /// problem does not arise. + /// + /// # Safety + /// + /// - Each [`CommandBuffer`][cb] in `command_buffers` must have been created + /// from a [`CommandEncoder`][ce] that was constructed from the + /// [`Device`][d] associated with this [`Queue`]. + /// + /// - Each [`CommandBuffer`][cb] must remain alive until the submitted + /// commands have finished execution. Since command buffers must not + /// outlive their encoders, this implies that the encoders must remain + /// alive as well. + /// + /// - All resources used by a submitted [`CommandBuffer`][cb] + /// ([`Texture`][t]s, [`BindGroup`][bg]s, [`RenderPipeline`][rp]s, and so + /// on) must remain alive until the command buffer finishes execution. + /// + /// - Every [`SurfaceTexture`][st] that any command in `command_buffers` + /// writes to must appear in the `surface_textures` argument. + /// + /// - No [`SurfaceTexture`][st] may appear in the `surface_textures` + /// argument more than once. + /// + /// - Each [`SurfaceTexture`][st] in `surface_textures` must be configured + /// for use with the [`Device`][d] associated with this [`Queue`], + /// typically by calling [`Surface::configure`]. + /// + /// - All calls to this function that include a given [`SurfaceTexture`][st] + /// in `surface_textures` must use the same [`Fence`]. + /// + /// - The [`Fence`] passed as `signal_fence.0` must remain alive until + /// all submissions that will signal it have completed. + /// + /// [`Fence`]: Api::Fence + /// [cb]: Api::CommandBuffer + /// [ce]: Api::CommandEncoder + /// [d]: Api::Device + /// [t]: Api::Texture + /// [bg]: Api::BindGroup + /// [rp]: Api::RenderPipeline + /// [st]: Api::SurfaceTexture + unsafe fn submit( + &self, + command_buffers: &[&<Self::A as Api>::CommandBuffer], + surface_textures: &[&<Self::A as Api>::SurfaceTexture], + signal_fence: (&<Self::A as Api>::Fence, FenceValue), + ) -> Result<(), DeviceError>; + /// Present a surface texture to the screen. + /// + /// This consumes the surface texture, returning it to the swapchain. + /// + /// # Safety + /// + /// - `texture` must have been acquired from `surface` via + /// [`Surface::acquire_texture`] and not yet presented or discarded. + /// - `surface` must be configured for use with the [`Device`][d] associated + /// with this [`Queue`]. + /// - `texture` must be in the "present" state. Either: + /// - It was passed in [`submit`][s]'s `surface_textures` argument + /// (which transitions it to the present state), or + /// - The caller has otherwise transitioned it (e.g. via a clear + + /// barrier to `PRESENT` for textures that were never rendered to). + /// - Any command buffers that write to `texture` must have been submitted + /// via [`submit`][s] before this call. The submissions do not need to + /// have completed on the GPU; platform-level synchronization handles the + /// ordering between rendering and display. + /// - Must be externally synchronized with all other queue operations + /// ([`submit`][s], [`present`][Queue::present], + /// [`wait_for_idle`][Queue::wait_for_idle]) on the same queue. + /// + /// [d]: Api::Device + /// [s]: Queue::submit + unsafe fn present( + &self, + surface: &<Self::A as Api>::Surface, + texture: <Self::A as Api>::SurfaceTexture, + ) -> Result<(), SurfaceError>; + /// Block until all previously submitted work on this queue has completed, + /// including any pending presentations. + /// + /// # Safety + /// + /// - Must be externally synchronized with all other queue operations + /// ([`submit`][Queue::submit], [`present`][Queue::present], + /// [`wait_for_idle`][Queue::wait_for_idle]) on the same queue. + unsafe fn wait_for_idle(&self) -> Result<(), DeviceError>; + unsafe fn get_timestamp_period(&self) -> f32; +} + +/// Encoder and allocation pool for `CommandBuffer`s. +/// +/// A `CommandEncoder` not only constructs `CommandBuffer`s but also +/// acts as the allocation pool that owns the buffers' underlying +/// storage. Thus, `CommandBuffer`s must not outlive the +/// `CommandEncoder` that created them. +/// +/// The life cycle of a `CommandBuffer` is as follows: +/// +/// - Call [`Device::create_command_encoder`] to create a new +/// `CommandEncoder`, in the "closed" state. +/// +/// - Call `begin_encoding` on a closed `CommandEncoder` to begin +/// recording commands. This puts the `CommandEncoder` in the +/// "recording" state. +/// +/// - Call methods like `copy_buffer_to_buffer`, `begin_render_pass`, +/// etc. on a "recording" `CommandEncoder` to add commands to the +/// list. (If an error occurs, you must call `discard_encoding`; see +/// below.) +/// +/// - Call `end_encoding` on a recording `CommandEncoder` to close the +/// encoder and construct a fresh `CommandBuffer` consisting of the +/// list of commands recorded up to that point. +/// +/// - Call `discard_encoding` on a recording `CommandEncoder` to drop +/// the commands recorded thus far and close the encoder. This is +/// the only safe thing to do on a `CommandEncoder` if an error has +/// occurred while recording commands. +/// +/// - Call `reset_all` on a closed `CommandEncoder`, passing all the +/// live `CommandBuffers` built from it. All the `CommandBuffer`s +/// are destroyed, and their resources are freed. +/// +/// # Safety +/// +/// - The `CommandEncoder` must be in the states described above to +/// make the given calls. +/// +/// - A `CommandBuffer` that has been submitted for execution on the +/// GPU must live until its execution is complete. +/// +/// - A `CommandBuffer` must not outlive the `CommandEncoder` that +/// built it. +/// +/// It is the user's responsibility to meet this requirements. This +/// allows `CommandEncoder` implementations to keep their state +/// tracking to a minimum. +pub trait CommandEncoder: WasmNotSendSync + fmt::Debug { + type A: Api; + + /// Begin encoding a new command buffer. + /// + /// This puts this `CommandEncoder` in the "recording" state. + /// + /// # Safety + /// + /// This `CommandEncoder` must be in the "closed" state. + unsafe fn begin_encoding(&mut self, label: Label) -> Result<(), DeviceError>; + + /// Discard the command list under construction. + /// + /// If an error has occurred while recording commands, this + /// is the only safe thing to do with the encoder. + /// + /// This puts this `CommandEncoder` in the "closed" state. + /// + /// # Safety + /// + /// This `CommandEncoder` must be in the "recording" state. + /// + /// Callers must not assume that implementations of this + /// function are idempotent, and thus should not call it + /// multiple times in a row. + unsafe fn discard_encoding(&mut self); + + /// Return a fresh [`CommandBuffer`] holding the recorded commands. + /// + /// The returned [`CommandBuffer`] holds all the commands recorded + /// on this `CommandEncoder` since the last call to + /// [`begin_encoding`]. + /// + /// This puts this `CommandEncoder` in the "closed" state. + /// + /// # Safety + /// + /// This `CommandEncoder` must be in the "recording" state. + /// + /// The returned [`CommandBuffer`] must not outlive this + /// `CommandEncoder`. Implementations are allowed to build + /// `CommandBuffer`s that depend on storage owned by this + /// `CommandEncoder`. + /// + /// [`CommandBuffer`]: Api::CommandBuffer + /// [`begin_encoding`]: CommandEncoder::begin_encoding + unsafe fn end_encoding(&mut self) -> Result<<Self::A as Api>::CommandBuffer, DeviceError>; + + /// Reclaim all resources belonging to this `CommandEncoder`. + /// + /// # Safety + /// + /// This `CommandEncoder` must be in the "closed" state. + /// + /// The `command_buffers` iterator must produce all the live + /// [`CommandBuffer`]s built using this `CommandEncoder` --- that + /// is, every extant `CommandBuffer` returned from `end_encoding`. + /// + /// [`CommandBuffer`]: Api::CommandBuffer + unsafe fn reset_all<I>(&mut self, command_buffers: I) + where + I: Iterator<Item = <Self::A as Api>::CommandBuffer>; + + unsafe fn transition_buffers<'a, T>(&mut self, barriers: T) + where + T: Iterator<Item = BufferBarrier<'a, <Self::A as Api>::Buffer>>; + + unsafe fn transition_textures<'a, T>(&mut self, barriers: T) + where + T: Iterator<Item = TextureBarrier<'a, <Self::A as Api>::Texture>>; + + // copy operations + + unsafe fn clear_buffer(&mut self, buffer: &<Self::A as Api>::Buffer, range: MemoryRange); + + unsafe fn copy_buffer_to_buffer<T>( + &mut self, + src: &<Self::A as Api>::Buffer, + dst: &<Self::A as Api>::Buffer, + regions: T, + ) where + T: Iterator<Item = BufferCopy>; + + /// Copy from an external image to an internal texture. + /// Works with a single array layer. + /// Note: `dst` current usage has to be `wgt::TextureUses::COPY_DST`. + /// Note: the copy extent is in physical size (rounded to the block size) + #[cfg(webgl)] + unsafe fn copy_external_image_to_texture<T>( + &mut self, + src: &wgt::CopyExternalImageSourceInfo, + dst: &<Self::A as Api>::Texture, + dst_premultiplication: bool, + regions: T, + ) where + T: Iterator<Item = TextureCopy>; + + /// Copy from one texture to another. + /// Works with a single array layer. + /// Note: `dst` current usage has to be `wgt::TextureUses::COPY_DST`. + /// Note: the copy extent is in physical size (rounded to the block size) + unsafe fn copy_texture_to_texture<T>( + &mut self, + src: &<Self::A as Api>::Texture, + src_usage: wgt::TextureUses, + dst: &<Self::A as Api>::Texture, + regions: T, + ) where + T: Iterator<Item = TextureCopy>; + + /// Copy from buffer to texture. + /// Works with a single array layer. + /// Note: `dst` current usage has to be `wgt::TextureUses::COPY_DST`. + /// Note: the copy extent is in physical size (rounded to the block size) + unsafe fn copy_buffer_to_texture<T>( + &mut self, + src: &<Self::A as Api>::Buffer, + dst: &<Self::A as Api>::Texture, + regions: T, + ) where + T: Iterator<Item = BufferTextureCopy>; + + /// Copy from texture to buffer. + /// Works with a single array layer. + /// Note: the copy extent is in physical size (rounded to the block size) + unsafe fn copy_texture_to_buffer<T>( + &mut self, + src: &<Self::A as Api>::Texture, + src_usage: wgt::TextureUses, + dst: &<Self::A as Api>::Buffer, + regions: T, + ) where + T: Iterator<Item = BufferTextureCopy>; + + unsafe fn copy_acceleration_structure_to_acceleration_structure( + &mut self, + src: &<Self::A as Api>::AccelerationStructure, + dst: &<Self::A as Api>::AccelerationStructure, + copy: wgt::AccelerationStructureCopy, + ); + // pass common + + /// Sets the bind group at `index` to `group`. + /// + /// If this is not the first call to `set_bind_group` within the current + /// render or compute pass: + /// + /// - If `layout` contains `n` bind group layouts, then any previously set + /// bind groups at indices `n` or higher are cleared. + /// + /// - If the first `m` bind group layouts of `layout` are equal to those of + /// the previously passed layout, but no more, then any previously set + /// bind groups at indices `m` or higher are cleared. + /// + /// It follows from the above that passing the same layout as before doesn't + /// clear any bind groups. + /// + /// # Safety + /// + /// - This [`CommandEncoder`] must be within a render or compute pass. + /// + /// - `index` must be the valid index of some bind group layout in `layout`. + /// Call this the "relevant bind group layout". + /// + /// - The layout of `group` must be equal to the relevant bind group layout. + /// + /// - The length of `dynamic_offsets` must match the number of buffer + /// bindings [with dynamic offsets][hdo] in the relevant bind group + /// layout. + /// + /// - If those buffer bindings are ordered by increasing [`binding` number] + /// and paired with elements from `dynamic_offsets`, then each offset must + /// be a valid offset for the binding's corresponding buffer in `group`. + /// + /// [hdo]: wgt::BindingType::Buffer::has_dynamic_offset + /// [`binding` number]: wgt::BindGroupLayoutEntry::binding + unsafe fn set_bind_group( + &mut self, + layout: &<Self::A as Api>::PipelineLayout, + index: u32, + group: &<Self::A as Api>::BindGroup, + dynamic_offsets: &[wgt::DynamicOffset], + ); + + /// Sets a range in immediate data. + /// + /// IMPORTANT: while the data is passed as words, the offset is in bytes! + /// + /// # Safety + /// + /// - `offset_bytes` must be a multiple of 4. + /// - The range of immediates written must be valid for the pipeline layout at draw time. + unsafe fn set_immediates( + &mut self, + layout: &<Self::A as Api>::PipelineLayout, + offset_bytes: u32, + data: &[u32], + ); + + unsafe fn insert_debug_marker(&mut self, label: &str); + unsafe fn begin_debug_marker(&mut self, group_label: &str); + unsafe fn end_debug_marker(&mut self); + + // queries + + /// # Safety: + /// + /// - If `set` is an occlusion query set, it must be the same one as used in the [`RenderPassDescriptor::occlusion_query_set`] parameter. + unsafe fn begin_query(&mut self, set: &<Self::A as Api>::QuerySet, index: u32); + /// # Safety: + /// + /// - If `set` is an occlusion query set, it must be the same one as used in the [`RenderPassDescriptor::occlusion_query_set`] parameter. + unsafe fn end_query(&mut self, set: &<Self::A as Api>::QuerySet, index: u32); + unsafe fn write_timestamp(&mut self, set: &<Self::A as Api>::QuerySet, index: u32); + unsafe fn reset_queries(&mut self, set: &<Self::A as Api>::QuerySet, range: Range<u32>); + unsafe fn copy_query_results( + &mut self, + set: &<Self::A as Api>::QuerySet, + range: Range<u32>, + buffer: &<Self::A as Api>::Buffer, + offset: wgt::BufferAddress, + stride: wgt::BufferSize, + ); + + // render passes + + /// Begin a new render pass, clearing all active bindings. + /// + /// This clears any bindings established by the following calls: + /// + /// - [`set_bind_group`](CommandEncoder::set_bind_group) + /// - [`set_immediates`](CommandEncoder::set_immediates) + /// - [`begin_query`](CommandEncoder::begin_query) + /// - [`set_render_pipeline`](CommandEncoder::set_render_pipeline) + /// - [`set_index_buffer`](CommandEncoder::set_index_buffer) + /// - [`set_vertex_buffer`](CommandEncoder::set_vertex_buffer) + /// + /// # Safety + /// + /// - All prior calls to [`begin_render_pass`] on this [`CommandEncoder`] must have been followed + /// by a call to [`end_render_pass`]. + /// + /// - All prior calls to [`begin_compute_pass`] on this [`CommandEncoder`] must have been followed + /// by a call to [`end_compute_pass`]. + /// + /// - All prior calls to [`begin_ray_tracing_pass`] on this [`CommandEncoder`] must have been followed + /// by a call to [`end_ray_tracing_pass`]. + /// + /// [`begin_render_pass`]: CommandEncoder::begin_render_pass + /// [`begin_compute_pass`]: CommandEncoder::begin_compute_pass + /// [`begin_ray_tracing_pass`]: CommandEncoder::begin_ray_tracing_pass + /// [`end_render_pass`]: CommandEncoder::end_render_pass + /// [`end_compute_pass`]: CommandEncoder::end_compute_pass + /// [`end_ray_tracing_pass`]: CommandEncoder::end_ray_tracing_pass + unsafe fn begin_render_pass( + &mut self, + desc: &RenderPassDescriptor<<Self::A as Api>::QuerySet, <Self::A as Api>::TextureView>, + ) -> Result<(), DeviceError>; + + /// End the current render pass. + /// + /// # Safety + /// + /// - There must have been a prior call to [`begin_render_pass`] on this [`CommandEncoder`] + /// that has not been followed by a call to [`end_render_pass`]. + /// + /// [`begin_render_pass`]: CommandEncoder::begin_render_pass + /// [`end_render_pass`]: CommandEncoder::end_render_pass + unsafe fn end_render_pass(&mut self); + + unsafe fn set_render_pipeline(&mut self, pipeline: &<Self::A as Api>::RenderPipeline); + + unsafe fn set_index_buffer<'a>( + &mut self, + binding: BufferBinding<'a, <Self::A as Api>::Buffer>, + format: wgt::IndexFormat, + ); + unsafe fn set_vertex_buffer<'a>( + &mut self, + index: u32, + binding: BufferBinding<'a, <Self::A as Api>::Buffer>, + ); + unsafe fn set_viewport(&mut self, rect: &Rect<f32>, depth_range: Range<f32>); + unsafe fn set_scissor_rect(&mut self, rect: &Rect<u32>); + unsafe fn set_stencil_reference(&mut self, value: u32); + unsafe fn set_blend_constants(&mut self, color: &[f32; 4]); + + unsafe fn draw( + &mut self, + first_vertex: u32, + vertex_count: u32, + first_instance: u32, + instance_count: u32, + ); + unsafe fn draw_indexed( + &mut self, + first_index: u32, + index_count: u32, + base_vertex: i32, + first_instance: u32, + instance_count: u32, + ); + unsafe fn draw_indirect( + &mut self, + buffer: &<Self::A as Api>::Buffer, + offset: wgt::BufferAddress, + draw_count: u32, + ); + unsafe fn draw_indexed_indirect( + &mut self, + buffer: &<Self::A as Api>::Buffer, + offset: wgt::BufferAddress, + draw_count: u32, + ); + unsafe fn draw_indirect_count( + &mut self, + buffer: &<Self::A as Api>::Buffer, + offset: wgt::BufferAddress, + count_buffer: &<Self::A as Api>::Buffer, + count_offset: wgt::BufferAddress, + max_count: u32, + ); + unsafe fn draw_indexed_indirect_count( + &mut self, + buffer: &<Self::A as Api>::Buffer, + offset: wgt::BufferAddress, + count_buffer: &<Self::A as Api>::Buffer, + count_offset: wgt::BufferAddress, + max_count: u32, + ); + unsafe fn draw_mesh_tasks( + &mut self, + group_count_x: u32, + group_count_y: u32, + group_count_z: u32, + ); + unsafe fn draw_mesh_tasks_indirect( + &mut self, + buffer: &<Self::A as Api>::Buffer, + offset: wgt::BufferAddress, + draw_count: u32, + ); + unsafe fn draw_mesh_tasks_indirect_count( + &mut self, + buffer: &<Self::A as Api>::Buffer, + offset: wgt::BufferAddress, + count_buffer: &<Self::A as Api>::Buffer, + count_offset: wgt::BufferAddress, + max_count: u32, + ); + + // compute passes + + /// Begin a new compute pass, clearing all active bindings. + /// + /// This clears any bindings established by the following calls: + /// + /// - [`set_bind_group`](CommandEncoder::set_bind_group) + /// - [`set_immediates`](CommandEncoder::set_immediates) + /// - [`begin_query`](CommandEncoder::begin_query) + /// - [`set_compute_pipeline`](CommandEncoder::set_compute_pipeline) + /// + /// # Safety + /// + /// - All prior calls to [`begin_render_pass`] on this [`CommandEncoder`] must have been followed + /// by a call to [`end_render_pass`]. + /// + /// - All prior calls to [`begin_compute_pass`] on this [`CommandEncoder`] must have been followed + /// by a call to [`end_compute_pass`]. + /// + /// - All prior calls to [`begin_ray_tracing_pass`] on this [`CommandEncoder`] must have been followed + /// by a call to [`end_ray_tracing_pass`]. + /// + /// [`begin_render_pass`]: CommandEncoder::begin_render_pass + /// [`begin_compute_pass`]: CommandEncoder::begin_compute_pass + /// [`begin_ray_tracing_pass`]: CommandEncoder::begin_ray_tracing_pass + /// [`end_render_pass`]: CommandEncoder::end_render_pass + /// [`end_compute_pass`]: CommandEncoder::end_compute_pass + /// [`end_ray_tracing_pass`]: CommandEncoder::end_ray_tracing_pass + unsafe fn begin_compute_pass( + &mut self, + desc: &ComputePassDescriptor<<Self::A as Api>::QuerySet>, + ); + + /// End the current compute pass. + /// + /// # Safety + /// + /// - There must have been a prior call to [`begin_compute_pass`] on this [`CommandEncoder`] + /// that has not been followed by a call to [`end_compute_pass`]. + /// + /// [`begin_compute_pass`]: CommandEncoder::begin_compute_pass + /// [`end_compute_pass`]: CommandEncoder::end_compute_pass + unsafe fn end_compute_pass(&mut self); + + unsafe fn set_compute_pipeline(&mut self, pipeline: &<Self::A as Api>::ComputePipeline); + + unsafe fn dispatch_workgroups(&mut self, count: [u32; 3]); + unsafe fn dispatch_workgroups_indirect( + &mut self, + buffer: &<Self::A as Api>::Buffer, + offset: wgt::BufferAddress, + ); + + /// Begin a new ray tracing pass, clearing all active bindings. + /// + /// This clears any bindings established by the following calls: + /// + /// - [`set_bind_group`](CommandEncoder::set_bind_group) + /// - [`set_immediates`](CommandEncoder::set_immediates) + /// - [`begin_query`](CommandEncoder::begin_query) + /// - [`set_ray_tracing_pipeline`](CommandEncoder::set_compute_pipeline) + /// + /// # Safety + /// + /// - All prior calls to [`begin_render_pass`] on this [`CommandEncoder`] must have been followed + /// by a call to [`end_render_pass`]. + /// + /// - All prior calls to [`begin_compute_pass`] on this [`CommandEncoder`] must have been followed + /// by a call to [`end_compute_pass`]. + /// + /// - All prior calls to [`begin_ray_tracing_pass`] on this [`CommandEncoder`] must have been followed + /// by a call to [`end_ray_tracing_pass`]. + /// + /// [`begin_render_pass`]: CommandEncoder::begin_render_pass + /// [`begin_compute_pass`]: CommandEncoder::begin_compute_pass + /// [`begin_ray_tracing_pass`]: CommandEncoder::begin_ray_tracing_pass + /// [`end_render_pass`]: CommandEncoder::end_render_pass + /// [`end_compute_pass`]: CommandEncoder::end_compute_pass + /// [`end_ray_tracing_pass`]: CommandEncoder::end_ray_tracing_pass + unsafe fn begin_ray_tracing_pass(&mut self, desc: &RayTracingPassDescriptor); + + /// End the current compute pass. + /// + /// # Safety + /// + /// - There must have been a prior call to [`begin_ray_tracing_pass`] on this [`CommandEncoder`] + /// that has not been followed by a call to [`end_ray_tracing_pass`]. + /// + /// [`begin_ray_tracing_pass`]: CommandEncoder::begin_ray_tracing_pass + /// [`end_ray_tracing_pass`]: CommandEncoder::end_ray_tracing_pass + unsafe fn end_ray_tracing_pass(&mut self); + + /// # Safety + /// + /// - Pipeline must not be destroyed + unsafe fn set_ray_tracing_pipeline(&mut self, pipeline: &<Self::A as Api>::RayTracingPipeline); + + unsafe fn trace_rays<'a>( + &mut self, + count: [u32; 3], + ray_generation_group_data: PipelineGroupData<'a, <Self::A as Api>::Buffer>, + miss_group_data: PipelineGroupData<'a, <Self::A as Api>::Buffer>, + intersection_group_data: PipelineGroupData<'a, <Self::A as Api>::Buffer>, + ); + + /// To get the required sizes for the buffer allocations use `get_acceleration_structure_build_sizes` per descriptor + /// All buffers must be synchronized externally + /// All buffer regions, which are written to may only be passed once per function call, + /// with the exception of updates in the same descriptor. + /// Consequences of this limitation: + /// - scratch buffers need to be unique + /// - a tlas can't be build in the same call with a blas it contains + unsafe fn build_acceleration_structures<'a, T>( + &mut self, + descriptor_count: u32, + descriptors: T, + ) where + Self::A: 'a, + T: IntoIterator< + Item = BuildAccelerationStructureDescriptor< + 'a, + <Self::A as Api>::Buffer, + <Self::A as Api>::AccelerationStructure, + >, + >; + unsafe fn place_acceleration_structure_barrier( + &mut self, + barrier: AccelerationStructureBarrier, + ); + // modeled off dx12, because this is able to be polyfilled in vulkan as opposed to the other way round + unsafe fn read_acceleration_structure_compact_size( + &mut self, + acceleration_structure: &<Self::A as Api>::AccelerationStructure, + buf: &<Self::A as Api>::Buffer, + ); + unsafe fn set_acceleration_structure_dependencies( + command_buffers: &[&<Self::A as Api>::CommandBuffer], + dependencies: &[&<Self::A as Api>::AccelerationStructure], + ); +} + +bitflags!( + /// Pipeline layout creation flags. + #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)] + pub struct PipelineLayoutFlags: u32 { + /// D3D12: Add support for `first_vertex` and `first_instance` builtins + /// via immediates for direct execution. + const FIRST_VERTEX_INSTANCE = 1 << 0; + /// D3D12: Add support for `num_workgroups` builtins via immediates + /// for direct execution. + const NUM_WORK_GROUPS = 1 << 1; + /// D3D12: Add support for the builtins that the other flags enable for + /// indirect execution. + const INDIRECT_BUILTIN_UPDATE = 1 << 2; + } +); + +bitflags!( + /// Pipeline layout creation flags. + #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)] + pub struct BindGroupLayoutFlags: u32 { + /// Allows for bind group binding arrays to be shorter than the array in the BGL. + const PARTIALLY_BOUND = 1 << 0; + } +); + +bitflags!( + /// Texture format capability flags. + #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)] + pub struct TextureFormatCapabilities: u32 { + /// Format can be sampled. + const SAMPLED = 1 << 0; + /// Format can be sampled with a linear sampler. + const SAMPLED_LINEAR = 1 << 1; + /// Format can be sampled with a min/max reduction sampler. + const SAMPLED_MINMAX = 1 << 2; + + /// Format can be used as storage with read-only access. + const STORAGE_READ_ONLY = 1 << 3; + /// Format can be used as storage with write-only access. + const STORAGE_WRITE_ONLY = 1 << 4; + /// Format can be used as storage with both read and write access. + const STORAGE_READ_WRITE = 1 << 5; + /// Format can be used as storage with atomics. + const STORAGE_ATOMIC = 1 << 6; + + /// Format can be used as color and input attachment. + const COLOR_ATTACHMENT = 1 << 7; + /// Format can be used as color (with blending) and input attachment. + const COLOR_ATTACHMENT_BLEND = 1 << 8; + /// Format can be used as depth-stencil and input attachment. + const DEPTH_STENCIL_ATTACHMENT = 1 << 9; + + /// Format can be multisampled by x2. + const MULTISAMPLE_X2 = 1 << 10; + /// Format can be multisampled by x4. + const MULTISAMPLE_X4 = 1 << 11; + /// Format can be multisampled by x8. + const MULTISAMPLE_X8 = 1 << 12; + /// Format can be multisampled by x16. + const MULTISAMPLE_X16 = 1 << 13; + + /// Format can be used for render pass resolve targets. + const MULTISAMPLE_RESOLVE = 1 << 14; + + /// Format can be copied from. + const COPY_SRC = 1 << 15; + /// Format can be copied to. + const COPY_DST = 1 << 16; + } +); + +bitflags!( + /// Texture format capability flags. + #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)] + pub struct FormatAspects: u8 { + const COLOR = 1 << 0; + const DEPTH = 1 << 1; + const STENCIL = 1 << 2; + const PLANE_0 = 1 << 3; + const PLANE_1 = 1 << 4; + const PLANE_2 = 1 << 5; + + const DEPTH_STENCIL = Self::DEPTH.bits() | Self::STENCIL.bits(); + } +); + +impl FormatAspects { + pub fn new(format: wgt::TextureFormat, aspect: wgt::TextureAspect) -> Self { + let aspect_mask = match aspect { + wgt::TextureAspect::All => Self::all(), + wgt::TextureAspect::DepthOnly => Self::DEPTH, + wgt::TextureAspect::StencilOnly => Self::STENCIL, + wgt::TextureAspect::Plane0 => Self::PLANE_0, + wgt::TextureAspect::Plane1 => Self::PLANE_1, + wgt::TextureAspect::Plane2 => Self::PLANE_2, + }; + Self::from(format) & aspect_mask + } + + /// Returns `true` if only one flag is set + pub fn is_one(&self) -> bool { + self.bits().is_power_of_two() + } + + pub fn map(&self) -> wgt::TextureAspect { + match *self { + Self::COLOR => wgt::TextureAspect::All, + Self::DEPTH => wgt::TextureAspect::DepthOnly, + Self::STENCIL => wgt::TextureAspect::StencilOnly, + Self::PLANE_0 => wgt::TextureAspect::Plane0, + Self::PLANE_1 => wgt::TextureAspect::Plane1, + Self::PLANE_2 => wgt::TextureAspect::Plane2, + _ => unreachable!(), + } + } +} + +impl From<wgt::TextureFormat> for FormatAspects { + fn from(format: wgt::TextureFormat) -> Self { + match format { + wgt::TextureFormat::Stencil8 => Self::STENCIL, + wgt::TextureFormat::Depth16Unorm + | wgt::TextureFormat::Depth32Float + | wgt::TextureFormat::Depth24Plus => Self::DEPTH, + wgt::TextureFormat::Depth32FloatStencil8 | wgt::TextureFormat::Depth24PlusStencil8 => { + Self::DEPTH_STENCIL + } + wgt::TextureFormat::NV12 | wgt::TextureFormat::P010 => Self::PLANE_0 | Self::PLANE_1, + _ => Self::COLOR, + } + } +} + +bitflags!( + #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)] + pub struct MemoryFlags: u32 { + const TRANSIENT = 1 << 0; + const PREFER_COHERENT = 1 << 1; + } +); + +bitflags!( + /// Attachment load and store operations. + /// + /// There must be at least one flag from the LOAD group and one from the STORE group set. + #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)] + pub struct AttachmentOps: u8 { + /// Load the existing contents of the attachment. + const LOAD = 1 << 0; + /// Clear the attachment to a specified value. + const LOAD_CLEAR = 1 << 1; + /// The contents of the attachment are undefined. + const LOAD_DONT_CARE = 1 << 2; + /// Store the contents of the attachment. + const STORE = 1 << 3; + /// The contents of the attachment are undefined after the pass. + const STORE_DISCARD = 1 << 4; + } +); + +#[derive(Debug)] +pub struct InstanceDescriptor<'a> { + pub name: &'a str, + pub flags: wgt::InstanceFlags, + pub memory_budget_thresholds: wgt::MemoryBudgetThresholds, + pub backend_options: wgt::BackendOptions, + pub telemetry: Option<Telemetry>, + /// This is a borrow because the surrounding `core::Instance` keeps the owned display handle + /// alive already. + pub display: Option<DisplayHandle<'a>>, +} + +#[derive(Clone, Debug)] +pub struct Alignments { + /// The alignment of the start of the buffer used as a GPU copy source. + pub buffer_copy_offset: wgt::BufferSize, + + /// The alignment of the row pitch of the texture data stored in a buffer that is + /// used in a GPU copy operation. + pub buffer_copy_pitch: wgt::BufferSize, + + /// The finest alignment of bound range checking for uniform buffers. + /// + /// When `wgpu_hal` restricts shader references to the [accessible + /// region][ar] of a [`Uniform`] buffer, the size of the accessible region + /// is the bind group binding's stated [size], rounded up to the next + /// multiple of this value. + /// + /// We don't need an analogous field for storage buffer bindings, because + /// all our backends promise to enforce the size at least to a four-byte + /// alignment, and `wgpu_hal` requires bound range lengths to be a multiple + /// of four anyway. + /// + /// [ar]: struct.BufferBinding.html#accessible-region + /// [`Uniform`]: wgt::BufferBindingType::Uniform + /// [size]: BufferBinding::size + pub uniform_bounds_check_alignment: wgt::BufferSize, + + /// The size of the raw TLAS instance + pub raw_tlas_instance_size: u32, + + /// What the scratch buffer for building an acceleration structure must be aligned to + pub ray_tracing_scratch_buffer_alignment: u32, + + /// How large a single piece of group data is. That is, how large the vector returned + /// from `device.get_raytracing_pipeline_group_data(&pipeline, n..(n+1))` is. + /// + /// If ray tracing pipelines are implemented, this must be non zero. + pub ray_tracing_pipeline_group_data_size: u32, + + /// If ray tracing pipelines are implemented, this must be a power of two (and non zero). + pub ray_tracing_pipeline_group_data_alignment: u32, + + /// If ray tracing pipelines are implemented, this must be a power of two (and non zero). + /// + /// The offset within `PipelineGroupData` must be a multiple of this + pub ray_tracing_pipeline_data_offset_alignment: u32, +} + +#[derive(Clone, Debug)] +pub struct Capabilities { + pub limits: wgt::Limits, + pub alignments: Alignments, + pub downlevel: wgt::DownlevelCapabilities, + /// Supported cooperative matrix configurations. + /// + /// Empty if cooperative matrices are not supported. + pub cooperative_matrix_properties: Vec<wgt::CooperativeMatrixProperties>, +} + +/// An adapter with all the information needed to reason about its capabilities. +/// +/// These are either made by [`Instance::enumerate_adapters`] or by backend specific +/// methods on the backend [`Instance`] or [`Adapter`]. +#[derive(Debug)] +pub struct ExposedAdapter<A: Api> { + pub adapter: A::Adapter, + pub info: wgt::AdapterInfo, + pub features: wgt::Features, + pub capabilities: Capabilities, +} + +/// Describes information about what a `Surface`'s presentation capabilities are. +/// Fetch this with [Adapter::surface_capabilities]. +#[derive(Debug, Clone)] +pub struct SurfaceCapabilities { + /// List of supported texture formats together with the color spaces + /// supported for each format. + /// + /// Must be at least one. At most one entry per format, each with a + /// non-empty set of color spaces. + pub formats: Vec<wgt::SurfaceFormatCapabilities>, + + /// Range for the number of queued frames. + /// + /// This adjusts either the swapchain frame count to value + 1 - or sets SetMaximumFrameLatency to the value given, + /// or uses a wait-for-present in the acquire method to limit rendering such that it acts like it's a value + 1 swapchain frame set. + /// + /// - `maximum_frame_latency.start` must be at least 1. + /// - `maximum_frame_latency.end` must be larger or equal to `maximum_frame_latency.start`. + pub maximum_frame_latency: RangeInclusive<u32>, + + /// Current extent of the surface, if known. + pub current_extent: Option<wgt::Extent3d>, + + /// Supported texture usage flags. + /// + /// Must have at least `wgt::TextureUses::COLOR_TARGET` + pub usage: wgt::TextureUses, + + /// List of supported V-sync modes. + /// + /// Must be at least one. + pub present_modes: Vec<wgt::PresentMode>, + + /// List of supported alpha composition modes. + /// + /// Must be at least one. + pub composite_alpha_modes: Vec<wgt::CompositeAlphaMode>, +} + +impl SurfaceCapabilities { + /// Returns the supported texture formats, dropping the per-format color-space + /// information carried in [`Self::formats`]. + pub fn texture_formats(&self) -> impl Iterator<Item = wgt::TextureFormat> + '_ { + self.formats.iter().map(|fc| fc.format) + } +} + +#[derive(Debug)] +pub struct AcquiredSurfaceTexture<A: Api> { + pub texture: A::SurfaceTexture, + /// The presentation configuration no longer matches + /// the surface properties exactly, but can still be used to present + /// to the surface successfully. + pub suboptimal: bool, +} + +/// An open connection to a device and a queue. +/// +/// This can be created from [`Adapter::open`] or backend +/// specific methods on the backend's [`Instance`] or [`Adapter`]. +#[derive(Debug)] +pub struct OpenDevice<A: Api> { + pub device: A::Device, + pub queue: A::Queue, +} + +#[derive(Clone, Debug)] +pub struct BufferMapping { + pub ptr: NonNull<u8>, + pub is_coherent: bool, +} + +#[derive(Clone, Debug)] +pub struct BufferDescriptor<'a> { + pub label: Label<'a>, + pub size: wgt::BufferAddress, + pub usage: wgt::BufferUses, + pub memory_flags: MemoryFlags, +} + +#[derive(Clone, Debug)] +pub struct TextureDescriptor<'a> { + pub label: Label<'a>, + pub size: wgt::Extent3d, + pub mip_level_count: u32, + pub sample_count: u32, + pub dimension: wgt::TextureDimension, + pub format: wgt::TextureFormat, + pub usage: wgt::TextureUses, + pub memory_flags: MemoryFlags, + /// Allows views of this texture to have a different format + /// than the texture does. + pub view_formats: Vec<wgt::TextureFormat>, +} + +impl TextureDescriptor<'_> { + pub fn copy_extent(&self) -> CopyExtent { + CopyExtent::map_extent_to_copy_size(&self.size, self.dimension) + } + + pub fn is_cube_compatible(&self) -> bool { + self.dimension == wgt::TextureDimension::D2 + && self.size.depth_or_array_layers.is_multiple_of(6) + && self.sample_count == 1 + && self.size.width == self.size.height + } + + pub fn array_layer_count(&self) -> u32 { + match self.dimension { + wgt::TextureDimension::D1 | wgt::TextureDimension::D3 => 1, + wgt::TextureDimension::D2 => self.size.depth_or_array_layers, + } + } +} + +/// TextureView descriptor. +/// +/// Valid usage: +///. - `format` has to be the same as `TextureDescriptor::format` +///. - `dimension` has to be compatible with `TextureDescriptor::dimension` +///. - `usage` has to be a subset of `TextureDescriptor::usage` +///. - `range` has to be a subset of parent texture +#[derive(Clone, Debug)] +pub struct TextureViewDescriptor<'a> { + pub label: Label<'a>, + pub format: wgt::TextureFormat, + pub dimension: wgt::TextureViewDimension, + pub usage: wgt::TextureUses, + pub range: wgt::ImageSubresourceRange, +} + +#[derive(Clone, Debug)] +pub struct SamplerDescriptor<'a> { + pub label: Label<'a>, + pub address_modes: [wgt::AddressMode; 3], + pub mag_filter: wgt::FilterMode, + pub min_filter: wgt::FilterMode, + pub mipmap_filter: wgt::MipmapFilterMode, + pub lod_clamp: Range<f32>, + pub compare: Option<wgt::CompareFunction>, + // Must in the range [1, 16]. + // + // Anisotropic filtering must be supported if this is not 1. + pub anisotropy_clamp: u16, + pub border_color: Option<wgt::SamplerBorderColor>, +} + +/// BindGroupLayout descriptor. +/// +/// Valid usage: +/// - `entries` are sorted by ascending `wgt::BindGroupLayoutEntry::binding` +#[derive(Clone, Debug)] +pub struct BindGroupLayoutDescriptor<'a> { + pub label: Label<'a>, + pub flags: BindGroupLayoutFlags, + pub entries: &'a [wgt::BindGroupLayoutEntry], +} + +#[derive(Clone, Debug)] +pub struct PipelineLayoutDescriptor<'a, B: DynBindGroupLayout + ?Sized> { + pub label: Label<'a>, + pub flags: PipelineLayoutFlags, + pub bind_group_layouts: &'a [Option<&'a B>], + pub immediate_size: u32, +} + +/// A region of a buffer made visible to shaders via a [`BindGroup`]. +/// +/// [`BindGroup`]: Api::BindGroup +/// +/// ## Construction +/// +/// The recommended way to construct a `BufferBinding` is using the `binding` +/// method on a wgpu-core `Buffer`, which will validate the binding size +/// against the buffer size. A `new_unchecked` constructor is also provided for +/// cases where direct construction is necessary. +/// +/// ## Accessible region +/// +/// `wgpu_hal` guarantees that shaders compiled with +/// [`ShaderModuleDescriptor::runtime_checks`] set to `true` cannot read or +/// write data via this binding outside the *accessible region* of a buffer: +/// +/// - The accessible region starts at [`offset`]. +/// +/// - For [`Storage`] bindings, the size of the accessible region is [`size`], +/// which must be a multiple of 4. +/// +/// - For [`Uniform`] bindings, the size of the accessible region is [`size`] +/// rounded up to the next multiple of +/// [`Alignments::uniform_bounds_check_alignment`]. +/// +/// Note that this guarantee is stricter than WGSL's requirements for +/// [out-of-bounds accesses][woob], as WGSL allows them to return values from +/// elsewhere in the buffer. But this guarantee is necessary anyway, to permit +/// `wgpu-core` to avoid clearing uninitialized regions of buffers that will +/// never be read by the application before they are overwritten. This +/// optimization consults bind group buffer binding regions to determine which +/// parts of which buffers shaders might observe. This optimization is only +/// sound if shader access is bounds-checked. +/// +/// ## Zero-length bindings +/// +/// Some back ends cannot tolerate zero-length regions; for example, see +/// [VUID-VkDescriptorBufferInfo-offset-00340][340] and +/// [VUID-VkDescriptorBufferInfo-range-00341][341], or the +/// documentation for GLES's [glBindBufferRange][bbr]. This documentation +/// previously stated that a `BufferBinding` must have `offset` strictly less +/// than the size of the buffer, but this restriction was not honored elsewhere +/// in the code, so has been removed. However, it remains the case that +/// some backends do not support zero-length bindings, so additional +/// logic is needed somewhere to handle this properly. See +/// [#3170](https://github.com/gfx-rs/wgpu/issues/3170). +/// +/// [`offset`]: BufferBinding::offset +/// [`size`]: BufferBinding::size +/// [`Storage`]: wgt::BufferBindingType::Storage +/// [`Uniform`]: wgt::BufferBindingType::Uniform +/// [340]: https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html#VUID-VkDescriptorBufferInfo-offset-00340 +/// [341]: https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html#VUID-VkDescriptorBufferInfo-range-00341 +/// [bbr]: https://registry.khronos.org/OpenGL-Refpages/es3.0/html/glBindBufferRange.xhtml +/// [woob]: https://gpuweb.github.io/gpuweb/wgsl/#out-of-bounds-access-sec +#[derive(Debug)] +pub struct BufferBinding<'a, B: DynBuffer + ?Sized> { + /// The buffer being bound. + /// + /// This is not fully `pub` to prevent direct construction of + /// `BufferBinding`s, while still allowing public read access to the `offset` + /// and `size` properties. + pub(crate) buffer: &'a B, + + /// The offset at which the bound region starts. + /// + /// This must be less or equal to the size of the buffer. + pub offset: wgt::BufferAddress, + + /// The size of the region bound, in bytes. + /// + /// If `None`, the region extends from `offset` to the end of the + /// buffer. Given the restrictions on `offset`, this means that + /// the size is always greater than zero. + pub size: Option<wgt::BufferSize>, +} + +// We must implement this manually because `B` is not necessarily `Clone`. +impl<B: DynBuffer + ?Sized> Clone for BufferBinding<'_, B> { + fn clone(&self) -> Self { + BufferBinding { + buffer: self.buffer, + offset: self.offset, + size: self.size, + } + } +} + +/// Temporary convenience trait to let us call `.get()` on `u64`s in code that +/// really wants to be using `NonZeroU64`. +/// TODO(<https://github.com/gfx-rs/wgpu/issues/3170>): remove this +pub trait ShouldBeNonZeroExt { + fn get(&self) -> u64; +} + +impl ShouldBeNonZeroExt for NonZeroU64 { + fn get(&self) -> u64 { + NonZeroU64::get(*self) + } +} + +impl ShouldBeNonZeroExt for u64 { + fn get(&self) -> u64 { + *self + } +} + +impl ShouldBeNonZeroExt for Option<NonZeroU64> { + fn get(&self) -> u64 { + match *self { + Some(non_zero) => non_zero.get(), + None => 0, + } + } +} + +impl<'a, B: DynBuffer + ?Sized> BufferBinding<'a, B> { + /// Construct a `BufferBinding` with the given contents. + /// + /// When possible, use the `binding` method on a wgpu-core `Buffer` instead + /// of this method. `Buffer::binding` validates the size of the binding + /// against the size of the buffer. + /// + /// It is more difficult to provide a validating constructor here, due to + /// not having direct access to the size of a `DynBuffer`. + /// + /// SAFETY: The caller is responsible for ensuring that a binding of `size` + /// bytes starting at `offset` is contained within the buffer. + /// + /// The `S` type parameter is a temporary convenience to allow callers to + /// pass a zero size. When the zero-size binding issue is resolved, the + /// argument should just match the type of the member. + /// TODO(<https://github.com/gfx-rs/wgpu/issues/3170>): remove the parameter + pub fn new_unchecked<S: Into<Option<NonZeroU64>>>( + buffer: &'a B, + offset: wgt::BufferAddress, + size: S, + ) -> Self { + Self { + buffer, + offset, + size: size.into(), + } + } +} + +#[derive(Debug)] +pub struct TextureBinding<'a, T: DynTextureView + ?Sized> { + pub view: &'a T, + pub usage: wgt::TextureUses, +} + +impl<'a, T: DynTextureView + ?Sized> Clone for TextureBinding<'a, T> { + fn clone(&self) -> Self { + TextureBinding { + view: self.view, + usage: self.usage, + } + } +} + +#[derive(Debug)] +pub struct ExternalTextureBinding<'a, B: DynBuffer + ?Sized, T: DynTextureView + ?Sized> { + pub planes: [TextureBinding<'a, T>; 3], + pub params: BufferBinding<'a, B>, +} + +impl<'a, B: DynBuffer + ?Sized, T: DynTextureView + ?Sized> Clone + for ExternalTextureBinding<'a, B, T> +{ + fn clone(&self) -> Self { + ExternalTextureBinding { + planes: self.planes.clone(), + params: self.params.clone(), + } + } +} + +/// cbindgen:ignore +#[derive(Clone, Debug)] +pub struct BindGroupEntry { + pub binding: u32, + pub resource_index: u32, + pub count: u32, +} + +/// BindGroup descriptor. +/// +/// Valid usage: +///. - `entries` has to be sorted by ascending `BindGroupEntry::binding` +///. - `entries` has to have the same set of `BindGroupEntry::binding` as `layout` +///. - each entry has to be compatible with the `layout` +///. - each entry's `BindGroupEntry::resource_index` is within range +/// of the corresponding resource array, selected by the relevant +/// `BindGroupLayoutEntry`. +#[derive(Clone, Debug)] +pub struct BindGroupDescriptor< + 'a, + Bgl: DynBindGroupLayout + ?Sized, + B: DynBuffer + ?Sized, + S: DynSampler + ?Sized, + T: DynTextureView + ?Sized, + A: DynAccelerationStructure + ?Sized, +> { + pub label: Label<'a>, + pub layout: &'a Bgl, + pub buffers: &'a [BufferBinding<'a, B>], + pub samplers: &'a [&'a S], + pub textures: &'a [TextureBinding<'a, T>], + pub entries: &'a [BindGroupEntry], + pub acceleration_structures: &'a [&'a A], + pub external_textures: &'a [ExternalTextureBinding<'a, B, T>], +} + +#[derive(Clone, Debug)] +pub struct CommandEncoderDescriptor<'a, Q: DynQueue + ?Sized> { + pub label: Label<'a>, + pub queue: &'a Q, +} + +/// Naga shader module. +#[derive(Default)] +pub struct NagaShader { + /// Shader module IR. + pub module: Cow<'static, naga::Module>, + /// Analysis information of the module. + pub info: naga::valid::ModuleInfo, + /// Source codes for debug + pub debug_source: Option<DebugSource>, +} + +// Custom implementation avoids the need to generate Debug impl code +// for the whole Naga module and info. +impl fmt::Debug for NagaShader { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + write!(formatter, "Naga shader") + } +} + +/// Shader input. +pub enum ShaderInput<'a> { + Naga(NagaShader), + MetalLib { + file: &'a [u8], + num_workgroups: hashbrown::HashMap<String, (u32, u32, u32)>, + }, + Msl { + shader: &'a str, + num_workgroups: hashbrown::HashMap<String, (u32, u32, u32)>, + }, + SpirV(&'a [u32]), + Dxil { + shader: &'a [u8], + }, + Hlsl { + shader: &'a str, + }, + Glsl { + shader: &'a str, + }, +} + +impl fmt::Debug for ShaderInput<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + // Don't include the entire shader source, especially for binary formats, because it + // would be spammy. + Self::Naga { .. } => f.debug_tuple("Naga").finish_non_exhaustive(), + Self::MetalLib { .. } => f.debug_tuple("MetalLib").finish_non_exhaustive(), + Self::Msl { .. } => f.debug_tuple("Msl").finish_non_exhaustive(), + Self::SpirV { .. } => f.debug_tuple("SpirV").finish_non_exhaustive(), + Self::Dxil { .. } => f.debug_tuple("Dxil").finish_non_exhaustive(), + Self::Hlsl { .. } => f.debug_tuple("Hlsl").finish_non_exhaustive(), + Self::Glsl { .. } => f.debug_tuple("Glsl").finish_non_exhaustive(), + } + } +} + +#[derive(Debug)] +pub struct ShaderModuleDescriptor<'a> { + pub label: Label<'a>, + + /// # Safety + /// + /// See the documentation for each flag in [`ShaderRuntimeChecks`][src]. + /// + /// [src]: wgt::ShaderRuntimeChecks + pub runtime_checks: wgt::ShaderRuntimeChecks, +} + +#[derive(Debug, Clone)] +pub struct DebugSource { + pub file_name: Cow<'static, str>, + pub source_code: Cow<'static, str>, +} + +/// Describes a programmable pipeline stage. +#[derive(Debug)] +pub struct ProgrammableStage<'a, M: DynShaderModule + ?Sized> { + /// The compiled shader module for this stage. + pub module: &'a M, + /// The name of the entry point in the compiled shader. There must be a function with this name + /// in the shader. + pub entry_point: &'a str, + /// Pipeline constants + pub constants: &'a naga::back::PipelineConstants, + /// Whether workgroup scoped memory will be initialized with zero values for this stage. + /// + /// This is required by the WebGPU spec, but may have overhead which can be avoided + /// for cross-platform applications + pub zero_initialize_workgroup_memory: bool, +} + +impl<M: DynShaderModule + ?Sized> Clone for ProgrammableStage<'_, M> { + fn clone(&self) -> Self { + Self { + module: self.module, + entry_point: self.entry_point, + constants: self.constants, + zero_initialize_workgroup_memory: self.zero_initialize_workgroup_memory, + } + } +} + +/// Describes a compute pipeline. +#[derive(Clone, Debug)] +pub struct ComputePipelineDescriptor< + 'a, + Pl: DynPipelineLayout + ?Sized, + M: DynShaderModule + ?Sized, + Pc: DynPipelineCache + ?Sized, +> { + pub label: Label<'a>, + /// The layout of bind groups for this pipeline. + pub layout: &'a Pl, + /// The compiled compute stage and its entry point. + pub stage: ProgrammableStage<'a, M>, + /// The cache which will be used and filled when compiling this pipeline + pub cache: Option<&'a Pc>, +} + +#[derive(Debug)] +pub struct PipelineCacheDescriptor<'a> { + pub label: Label<'a>, + pub data: Option<&'a [u8]>, +} + +/// Describes how the vertex buffer is interpreted. +#[derive(Clone, Debug)] +pub struct VertexBufferLayout<'a> { + /// The stride, in bytes, between elements of this buffer. + pub array_stride: wgt::BufferAddress, + /// How often this vertex buffer is "stepped" forward. + pub step_mode: wgt::VertexStepMode, + /// The list of attributes which comprise a single vertex. + pub attributes: &'a [wgt::VertexAttribute], +} + +#[derive(Clone, Debug)] +pub enum VertexProcessor<'a, M: DynShaderModule + ?Sized> { + Standard { + /// The format of any vertex buffers used with this pipeline. + vertex_buffers: &'a [Option<VertexBufferLayout<'a>>], + /// The vertex stage for this pipeline. + vertex_stage: ProgrammableStage<'a, M>, + }, + Mesh { + task_stage: Option<ProgrammableStage<'a, M>>, + mesh_stage: ProgrammableStage<'a, M>, + }, +} + +/// Describes a render (graphics) pipeline. +#[derive(Clone, Debug)] +pub struct RenderPipelineDescriptor< + 'a, + Pl: DynPipelineLayout + ?Sized, + M: DynShaderModule + ?Sized, + Pc: DynPipelineCache + ?Sized, +> { + pub label: Label<'a>, + /// The layout of bind groups for this pipeline. + pub layout: &'a Pl, + /// The vertex processing state(vertex shader + buffers or task + mesh shaders) + pub vertex_processor: VertexProcessor<'a, M>, + /// The properties of the pipeline at the primitive assembly and rasterization level. + pub primitive: wgt::PrimitiveState, + /// The effect of draw calls on the depth and stencil aspects of the output target, if any. + pub depth_stencil: Option<wgt::DepthStencilState>, + /// The multi-sampling properties of the pipeline. + pub multisample: wgt::MultisampleState, + /// The fragment stage for this pipeline. + pub fragment_stage: Option<ProgrammableStage<'a, M>>, + /// The effect of draw calls on the color aspect of the output target. + pub color_targets: &'a [Option<wgt::ColorTargetState>], + /// If the pipeline will be used with a multiview render pass, this indicates how many array + /// layers the attachments will have. + pub multiview_mask: Option<NonZeroU32>, + /// The cache which will be used and filled when compiling this pipeline + pub cache: Option<&'a Pc>, +} + +#[derive(Clone, Debug)] +pub struct RayObjectIntersectionState<'a, M: DynShaderModule + ?Sized> { + pub closest_hit: ProgrammableStage<'a, M>, + pub any_hit: Option<ProgrammableStage<'a, M>>, +} + +/// Describes a ray tracing pipeline. +#[derive(Clone, Debug)] +pub struct RayTracingPipelineDescriptor< + 'a, + Pl: DynPipelineLayout + ?Sized, + M: DynShaderModule + ?Sized, + Pc: DynPipelineCache + ?Sized, +> { + pub label: Label<'a>, + /// The layout of bind groups for this pipeline. + pub layout: &'a Pl, + /// The ray generation stage. + pub ray_generation: ProgrammableStage<'a, M>, + /// The miss stage. + pub miss: ProgrammableStage<'a, M>, + /// All the object intersection stages. + pub intersection: &'a [RayObjectIntersectionState<'a, M>], + /// The maximum recursion depth allowed for the ray tracing (ray_generation shader counts as depth 0). + pub max_recursion_depth: u32, + /// The cache which will be used and filled when compiling this pipeline + pub cache: Option<&'a Pc>, +} + +#[derive(Debug, Clone)] +pub struct SurfaceConfiguration { + /// Maximum number of queued frames. Must be in + /// `SurfaceCapabilities::maximum_frame_latency` range. + pub maximum_frame_latency: u32, + /// Vertical synchronization mode. + pub present_mode: wgt::PresentMode, + /// Alpha composition mode. + pub composite_alpha_mode: wgt::CompositeAlphaMode, + /// Format of the surface textures. + pub format: wgt::TextureFormat, + /// Color space in which the presentation engine interprets the surface + /// textures. Never [`wgt::SurfaceColorSpace::Auto`]; `wgpu-core` resolves + /// `Auto` to a concrete color space before configuring the surface, and + /// the (format, color space) pair must be listed in + /// `SurfaceCapabilities::formats`. + pub color_space: wgt::SurfaceColorSpace, + /// Requested texture extent. Must be in + /// `SurfaceCapabilities::extents` range. + pub extent: wgt::Extent3d, + /// Allowed usage of surface textures, + pub usage: wgt::TextureUses, + /// Allows views of swapchain texture to have a different format + /// than the texture does. + pub view_formats: Vec<wgt::TextureFormat>, +} + +#[derive(Debug, Clone)] +pub struct Rect<T> { + pub x: T, + pub y: T, + pub w: T, + pub h: T, +} + +#[derive(Debug, Clone, PartialEq)] +pub struct StateTransition<T> { + pub from: T, + pub to: T, +} + +#[derive(Debug, Clone)] +pub struct BufferBarrier<'a, B: DynBuffer + ?Sized> { + pub buffer: &'a B, + pub usage: StateTransition<wgt::BufferUses>, +} + +#[derive(Debug, Clone)] +pub struct TextureBarrier<'a, T: DynTexture + ?Sized> { + pub texture: &'a T, + pub range: wgt::ImageSubresourceRange, + pub usage: StateTransition<wgt::TextureUses>, +} + +#[derive(Clone, Copy, Debug)] +pub struct BufferCopy { + pub src_offset: wgt::BufferAddress, + pub dst_offset: wgt::BufferAddress, + pub size: wgt::BufferSize, +} + +#[derive(Clone, Debug)] +pub struct TextureCopyBase { + pub mip_level: u32, + pub array_layer: u32, + /// Origin within a texture. + /// Note: for 1D and 2D textures, Z must be 0. + pub origin: wgt::Origin3d, + pub aspect: FormatAspects, +} + +#[derive(Clone, Copy, Debug)] +pub struct CopyExtent { + pub width: u32, + pub height: u32, + pub depth: u32, +} + +impl From<wgt::Extent3d> for CopyExtent { + fn from(value: wgt::Extent3d) -> Self { + let wgt::Extent3d { + width, + height, + depth_or_array_layers, + } = value; + Self { + width, + height, + depth: depth_or_array_layers, + } + } +} + +impl From<CopyExtent> for wgt::Extent3d { + fn from(value: CopyExtent) -> Self { + let CopyExtent { + width, + height, + depth, + } = value; + Self { + width, + height, + depth_or_array_layers: depth, + } + } +} + +#[derive(Clone, Debug)] +pub struct TextureCopy { + pub src_base: TextureCopyBase, + pub dst_base: TextureCopyBase, + pub size: CopyExtent, +} + +#[derive(Clone, Debug)] +pub struct BufferTextureCopy { + pub buffer_layout: wgt::TexelCopyBufferLayout, + pub texture_base: TextureCopyBase, + pub size: CopyExtent, +} + +#[derive(Clone, Debug)] +pub struct Attachment<'a, T: DynTextureView + ?Sized> { + pub view: &'a T, + /// Contains either a single mutating usage as a target, + /// or a valid combination of read-only usages. + pub usage: wgt::TextureUses, +} + +#[derive(Clone, Debug)] +pub struct ColorAttachment<'a, T: DynTextureView + ?Sized> { + pub target: Attachment<'a, T>, + pub depth_slice: Option<u32>, + pub resolve_target: Option<Attachment<'a, T>>, + pub ops: AttachmentOps, + pub clear_value: wgt::Color, +} + +#[derive(Clone, Debug)] +pub struct DepthStencilAttachment<'a, T: DynTextureView + ?Sized> { + pub target: Attachment<'a, T>, + pub depth_ops: AttachmentOps, + pub stencil_ops: AttachmentOps, + pub clear_value: (f32, u32), +} + +#[derive(Clone, Debug)] +pub struct PassTimestampWrites<'a, Q: DynQuerySet + ?Sized> { + pub query_set: &'a Q, + pub beginning_of_pass_write_index: Option<u32>, + pub end_of_pass_write_index: Option<u32>, +} + +#[derive(Clone, Debug)] +pub struct RenderPassDescriptor<'a, Q: DynQuerySet + ?Sized, T: DynTextureView + ?Sized> { + pub label: Label<'a>, + pub extent: wgt::Extent3d, + pub sample_count: u32, + pub color_attachments: &'a [Option<ColorAttachment<'a, T>>], + pub depth_stencil_attachment: Option<DepthStencilAttachment<'a, T>>, + pub multiview_mask: Option<NonZeroU32>, + pub timestamp_writes: Option<PassTimestampWrites<'a, Q>>, + pub occlusion_query_set: Option<&'a Q>, +} + +#[derive(Clone, Debug)] +pub struct ComputePassDescriptor<'a, Q: DynQuerySet + ?Sized> { + pub label: Label<'a>, + pub timestamp_writes: Option<PassTimestampWrites<'a, Q>>, +} + +#[derive(Clone, Debug)] +pub struct RayTracingPassDescriptor<'a> { + pub label: Label<'a>, +} + +#[test] +fn test_default_limits() { + let limits = wgt::Limits::default(); + assert!(limits.max_bind_groups <= MAX_BIND_GROUPS as u32); +} + +#[derive(Clone, Debug)] +pub struct AccelerationStructureDescriptor<'a> { + pub label: Label<'a>, + pub size: wgt::BufferAddress, + pub format: AccelerationStructureFormat, + pub allow_compaction: bool, +} + +#[derive(Debug, Clone, Copy, Eq, PartialEq)] +pub enum AccelerationStructureFormat { + TopLevel, + BottomLevel, +} + +#[derive(Debug, Clone, Copy, Eq, PartialEq)] +pub enum AccelerationStructureBuildMode { + Build, + Update, +} + +/// Information of the required size for a corresponding entries struct (+ flags) +#[derive(Copy, Clone, Debug, Default, Eq, PartialEq)] +pub struct AccelerationStructureBuildSizes { + pub acceleration_structure_size: wgt::BufferAddress, + pub update_scratch_size: wgt::BufferAddress, + pub build_scratch_size: wgt::BufferAddress, +} + +/// Updates use source_acceleration_structure if present, else the update will be performed in place. +/// For updates, only the data is allowed to change (not the meta data or sizes). +#[derive(Clone, Debug)] +pub struct BuildAccelerationStructureDescriptor< + 'a, + B: DynBuffer + ?Sized, + A: DynAccelerationStructure + ?Sized, +> { + pub entries: &'a AccelerationStructureEntries<'a, B>, + pub mode: AccelerationStructureBuildMode, + pub flags: AccelerationStructureBuildFlags, + pub source_acceleration_structure: Option<&'a A>, + pub destination_acceleration_structure: &'a A, + pub scratch_buffer: &'a B, + pub scratch_buffer_offset: wgt::BufferAddress, +} + +/// - All buffers, buffer addresses and offsets will be ignored. +/// - The build mode will be ignored. +/// - Reducing the amount of Instances, Triangle groups or AABB groups (or the number of Triangles/AABBs in corresponding groups), +/// may result in reduced size requirements. +/// - Any other change may result in a bigger or smaller size requirement. +#[derive(Clone, Debug)] +pub struct GetAccelerationStructureBuildSizesDescriptor<'a, B: DynBuffer + ?Sized> { + pub entries: &'a AccelerationStructureEntries<'a, B>, + pub flags: AccelerationStructureBuildFlags, +} + +/// Entries for a single descriptor +/// * `Instances` - Multiple instances for a top level acceleration structure +/// * `Triangles` - Multiple triangle meshes for a bottom level acceleration structure +/// * `AABBs` - List of list of axis aligned bounding boxes for a bottom level acceleration structure +#[derive(Debug)] +pub enum AccelerationStructureEntries<'a, B: DynBuffer + ?Sized> { + Instances(AccelerationStructureInstances<'a, B>), + Triangles(Vec<AccelerationStructureTriangles<'a, B>>), + AABBs(Vec<AccelerationStructureAABBs<'a, B>>), +} + +/// * `first_vertex` - offset in the vertex buffer (as number of vertices) +/// * `indices` - optional index buffer with attributes +/// * `transform` - optional transform +#[derive(Clone, Debug)] +pub struct AccelerationStructureTriangles<'a, B: DynBuffer + ?Sized> { + pub vertex_buffer: Option<&'a B>, + pub vertex_format: wgt::VertexFormat, + pub first_vertex: u32, + pub vertex_count: u32, + pub vertex_stride: wgt::BufferAddress, + pub indices: Option<AccelerationStructureTriangleIndices<'a, B>>, + pub transform: Option<AccelerationStructureTriangleTransform<'a, B>>, + pub flags: AccelerationStructureGeometryFlags, +} + +/// * `offset` - offset in bytes +#[derive(Clone, Debug)] +pub struct AccelerationStructureAABBs<'a, B: DynBuffer + ?Sized> { + pub buffer: Option<&'a B>, + pub offset: u32, + pub count: u32, + pub stride: wgt::BufferAddress, + pub flags: AccelerationStructureGeometryFlags, +} + +#[derive(Clone, Debug)] +pub struct AccelerationStructureCopy { + pub copy_flags: wgt::AccelerationStructureCopy, + pub type_flags: wgt::AccelerationStructureType, +} + +/// * `offset` - offset in bytes +#[derive(Clone, Debug)] +pub struct AccelerationStructureInstances<'a, B: DynBuffer + ?Sized> { + pub buffer: Option<&'a B>, + pub offset: u32, + pub count: u32, +} + +/// * `offset` - offset in bytes +#[derive(Clone, Debug)] +pub struct AccelerationStructureTriangleIndices<'a, B: DynBuffer + ?Sized> { + pub format: wgt::IndexFormat, + pub buffer: Option<&'a B>, + pub offset: u32, + pub count: u32, +} + +/// * `offset` - offset in bytes +#[derive(Clone, Debug)] +pub struct AccelerationStructureTriangleTransform<'a, B: DynBuffer + ?Sized> { + pub buffer: &'a B, + pub offset: u32, +} + +pub use wgt::AccelerationStructureFlags as AccelerationStructureBuildFlags; +pub use wgt::AccelerationStructureGeometryFlags; + +bitflags::bitflags! { + #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] + pub struct AccelerationStructureUses: u8 { + // For blas used as input for tlas + const BUILD_INPUT = 1 << 0; + // Target for acceleration structure build + const BUILD_OUTPUT = 1 << 1; + // Tlas used in a shader + const SHADER_INPUT = 1 << 2; + // Blas used to query compacted size + const QUERY_INPUT = 1 << 3; + // BLAS used as a src for a copy operation + const COPY_SRC = 1 << 4; + // BLAS used as a dst for a copy operation + const COPY_DST = 1 << 5; + } +} + +#[derive(Debug, Clone)] +pub struct AccelerationStructureBarrier { + pub usage: StateTransition<AccelerationStructureUses>, +} + +#[derive(Debug, Copy, Clone)] +pub struct TlasInstance { + pub transform: [f32; 12], + pub custom_data: u32, + pub mask: u8, + pub blas_address: u64, + /// The offset for the index into the intersection hit + /// group calculation. Number is in hit groups. + pub pipeline_intersection_data_offset: u32, +} + +#[cfg(dx12)] +#[derive(Debug)] +pub enum D3D12ExposeAdapterResult { + CreateDeviceError(dx12::CreateDeviceError), + UnknownFeatureLevel(i32), + ResourceBindingTier2Requirement, + ShaderModel6Requirement, + Success(dx12::FeatureLevel, dx12::ShaderModel), +} + +/// Pluggable telemetry, mainly to be used by Firefox. +#[derive(Debug, Clone, Copy)] +pub struct Telemetry { + #[cfg(dx12)] + pub d3d12_expose_adapter: fn( + desc: &windows::Win32::Graphics::Dxgi::DXGI_ADAPTER_DESC2, + driver_version: Result<[u16; 4], windows_core::HRESULT>, + result: D3D12ExposeAdapterResult, + ), +} + +#[derive(Debug)] +pub struct PipelineGroupData<'a, B: DynBuffer + ?Sized> { + pub buffer: &'a B, + pub offset: wgt::BufferAddress, + pub stride: u64, + pub count: u64, +} diff --git a/app/vendor/rune/vendor/wgpu-hal/src/metal/adapter.rs b/app/vendor/rune/vendor/wgpu-hal/src/metal/adapter.rs new file mode 100644 index 0000000..c9c48c3 --- /dev/null +++ b/app/vendor/rune/vendor/wgpu-hal/src/metal/adapter.rs @@ -0,0 +1,1808 @@ +use objc2::rc::autoreleasepool; +use objc2::runtime::{AnyObject, ProtocolObject, Sel}; +use objc2::{available, sel}; +use objc2_foundation::{NSOperatingSystemVersion, NSProcessInfo}; +use objc2_metal::{ + MTLArgumentBuffersTier, MTLCounterSamplingPoint, MTLDevice, MTLFeatureSet, MTLGPUFamily, + MTLIndirectAccelerationStructureInstanceDescriptor, MTLLanguageVersion, MTLPixelFormat, + MTLReadWriteTextureTier, +}; +use wgt::{AstcBlock, AstcChannel}; + +use alloc::{string::ToString as _, sync::Arc, vec::Vec}; +use core::sync::atomic; +use parking_lot::Mutex; +use std::sync::OnceLock; + +use crate::metal::QueueShared; + +use super::{OsFeatures, TimestampQuerySupport}; + +/// Check if a device's class has a given method in its method table. +/// +/// This mirrors the check that `objc2` performs internally (in debug builds) +/// before sending a message. We use it to skip method calls that would panic +/// on proxy objects like Apple's `CaptureMTLDevice`, which forwards messages +/// at runtime but doesn't declare the methods in its class. +fn device_class_responds_to(device: &ProtocolObject<dyn MTLDevice>, sel: Sel) -> bool { + AnyObject::class(device.as_ref()).responds_to(sel) +} + +/// Maximum number of command buffers for `MTLCommandQueue`s that we create. +/// +/// If a [new command buffer] is requested when Metal has run out of command +/// buffers, it waits indefinitely for one to become available. If the +/// outstanding command buffers are actively executing on the GPU, this will +/// happen relatively quickly. But if the outstanding command buffers will only +/// be recovered upon GC, and attempting to get a new command buffer prevents +/// forward progress towards that GC, there is a deadlock. +/// +/// This is mostly a problem for the CTS, which frequently creates command +/// buffers that it does not submit. It is unclear how likely command buffer +/// exhaustion is in real applications. +/// +/// This limit was increased from a previous value of 2048 for +/// <https://bugzilla.mozilla.org/show_bug.cgi?id=1971452>. +/// +/// [new command buffer]: https://developer.apple.com/documentation/metal/mtlcommandqueue/makecommandbuffer()?language=objc +pub(super) const MAX_COMMAND_BUFFERS: usize = 4096; + +/// "Maximum number of entries in the buffer argument table, per graphics or kernel function" +/// +/// Vertex buffers are placed at the end of the table (highest indices), +/// counting down from MAX_BUFFERS - 1. +pub const MAX_BUFFERS: u32 = 31; + +impl super::Adapter { + pub(super) fn new(shared: Arc<super::AdapterShared>) -> Self { + Self { shared } + } + pub fn raw_device(&self) -> &ProtocolObject<dyn MTLDevice> { + &self.shared.device + } +} + +impl crate::Adapter for super::Adapter { + type A = super::Api; + + unsafe fn open( + &self, + features: wgt::Features, + limits: &wgt::Limits, + _memory_hints: &wgt::MemoryHints, + ) -> Result<crate::OpenDevice<super::Api>, crate::DeviceError> { + autoreleasepool(|_| { + let queue = self + .shared + .device + .newCommandQueueWithMaxCommandBufferCount(MAX_COMMAND_BUFFERS) + .unwrap(); + + // Acquiring the meaning of timestamp ticks is hard with Metal! + // The only thing there is a method correlating cpu & gpu timestamps (`device.sample_timestamps`). + // Users are supposed to call this method twice and calculate the difference, + // see "Converting GPU Timestamps into CPU Time": + // https://developer.apple.com/documentation/metal/gpu_counters_and_counter_sample_buffers/converting_gpu_timestamps_into_cpu_time + // Not only does this mean we get an approximate value, this is as also *very slow*! + // Chromium opted to solve this using a linear regression that they stop at some point + // https://source.chromium.org/chromium/chromium/src/+/refs/heads/main:third_party/dawn/src/dawn/native/metal/DeviceMTL.mm;drc=76be2f9f117654f3fe4faa477b0445114fccedda;bpv=0;bpt=1;l=46 + // Generally, the assumption is that timestamp values aren't changing over time, after all all other APIs provide stable values. + // + // We should do as Chromium does for the general case, but this requires quite some state tracking + // and doesn't even provide perfectly accurate values, especially at the start of the application when + // we didn't have the chance to sample a lot of values just yet. + // + // So instead, we're doing the dangerous but easy thing and use our "knowledge" of timestamps + // conversions on different devices, after all Metal isn't supported on that many ;) + // Based on: + // * https://github.com/gfx-rs/wgpu/pull/2528 + // * https://github.com/gpuweb/gpuweb/issues/1325#issuecomment-761041326 + let timestamp_period = if self.shared.device.name().to_string().starts_with("Intel") { + 83.333 + } else { + // Known for Apple Silicon (at least M1 & M2, iPad Pro 2018) and AMD GPUs. + 1.0 + }; + + Ok(crate::OpenDevice { + device: super::Device { + shared: Arc::clone(&self.shared), + features, + counters: Default::default(), + limits: limits.clone(), + }, + queue: super::Queue { + shared: Arc::new(QueueShared { + raw: queue, + command_buffer_created_not_submitted: atomic::AtomicUsize::new(0), + pending_waits: Mutex::new(Vec::new()), + pending_signals: Mutex::new(Vec::new()), + relay: OnceLock::new(), + }), + timestamp_period, + }, + }) + }) + } + + unsafe fn texture_format_capabilities( + &self, + format: wgt::TextureFormat, + ) -> crate::TextureFormatCapabilities { + use crate::TextureFormatCapabilities as Tfc; + use wgt::TextureFormat as Tf; + + let msl_version = self.shared.private_caps.msl_version; + let pc = &self.shared.private_texture_format_caps; + // Affected formats documented at: + // https://developer.apple.com/documentation/metal/mtlreadwritetexturetier/mtlreadwritetexturetier1?language=objc + // https://developer.apple.com/documentation/metal/mtlreadwritetexturetier/mtlreadwritetexturetier2?language=objc + let (read_write_tier1_if, read_write_tier2_if) = match pc.read_write_texture_tier { + MTLReadWriteTextureTier::TierNone => (Tfc::empty(), Tfc::empty()), + MTLReadWriteTextureTier::Tier1 => (Tfc::STORAGE_READ_WRITE, Tfc::empty()), + MTLReadWriteTextureTier::Tier2 => (Tfc::STORAGE_READ_WRITE, Tfc::STORAGE_READ_WRITE), + // Unknown levels of support are likely higher than Tier 2. + _ => (Tfc::STORAGE_READ_WRITE, Tfc::STORAGE_READ_WRITE), + }; + let msaa_count = pc.sample_count_mask; + + let msaa_resolve_desktop_if = if pc.msaa_desktop { + Tfc::MULTISAMPLE_RESOLVE + } else { + Tfc::empty() + }; + let msaa_resolve_apple3x_if = if pc.msaa_desktop | pc.msaa_apple3 { + Tfc::MULTISAMPLE_RESOLVE + } else { + Tfc::empty() + }; + let is_not_apple1x = super::CapabilitiesQuery::supports_any( + self.shared.device.as_ref(), + &[ + MTLFeatureSet::iOS_GPUFamily2_v1, + MTLFeatureSet::macOS_GPUFamily1_v1, + MTLFeatureSet::tvOS_GPUFamily1_v1, + ], + ); + + let image_atomic_if = if msl_version >= MTLLanguageVersion::Version3_1 { + Tfc::STORAGE_ATOMIC + } else { + Tfc::empty() + }; + + let image_64_atomic_if = if pc.int64_atomics { + Tfc::STORAGE_ATOMIC + } else { + Tfc::empty() + }; + + // Metal defined pixel format capabilities + let all_caps = Tfc::SAMPLED_LINEAR + | Tfc::STORAGE_WRITE_ONLY + | Tfc::COLOR_ATTACHMENT + | Tfc::COLOR_ATTACHMENT_BLEND + | msaa_count + | Tfc::MULTISAMPLE_RESOLVE; + + let extra = match format { + Tf::R8Unorm | Tf::R16Float | Tf::Rgba8Unorm | Tf::Rgba16Float => { + read_write_tier2_if | all_caps + } + Tf::R8Snorm | Tf::Rg8Snorm | Tf::Rgba8Snorm => { + let mut flags = all_caps; + flags.set(Tfc::MULTISAMPLE_RESOLVE, is_not_apple1x); + flags + } + Tf::R8Uint + | Tf::R8Sint + | Tf::R16Uint + | Tf::R16Sint + | Tf::Rgba8Uint + | Tf::Rgba8Sint + | Tf::Rgba16Uint + | Tf::Rgba16Sint => { + read_write_tier2_if | Tfc::STORAGE_WRITE_ONLY | Tfc::COLOR_ATTACHMENT | msaa_count + } + Tf::R16Unorm + | Tf::R16Snorm + | Tf::Rg16Unorm + | Tf::Rg16Snorm + | Tf::Rgba16Unorm + | Tf::Rgba16Snorm => { + Tfc::SAMPLED_LINEAR + | Tfc::STORAGE_WRITE_ONLY + | Tfc::COLOR_ATTACHMENT + | Tfc::COLOR_ATTACHMENT_BLEND + | msaa_count + | msaa_resolve_desktop_if + } + Tf::Rg8Unorm | Tf::Rg16Float | Tf::Bgra8Unorm => all_caps, + Tf::Rg8Uint | Tf::Rg8Sint => { + Tfc::STORAGE_WRITE_ONLY | Tfc::COLOR_ATTACHMENT | msaa_count + } + Tf::R32Uint | Tf::R32Sint => { + read_write_tier1_if + | Tfc::STORAGE_WRITE_ONLY + | Tfc::COLOR_ATTACHMENT + | msaa_count + | image_atomic_if + } + Tf::R32Float => { + let flags = if pc.format_r32float_all { + all_caps + } else { + Tfc::STORAGE_WRITE_ONLY + | Tfc::COLOR_ATTACHMENT + | Tfc::COLOR_ATTACHMENT_BLEND + | msaa_count + }; + read_write_tier1_if | flags + } + Tf::Rg16Uint | Tf::Rg16Sint => { + Tfc::STORAGE_WRITE_ONLY | Tfc::COLOR_ATTACHMENT | msaa_count + } + Tf::Rgba8UnormSrgb | Tf::Bgra8UnormSrgb => { + let mut flags = all_caps; + flags.set(Tfc::STORAGE_WRITE_ONLY, pc.format_rgba8_srgb_all); + flags + } + Tf::Rgb10a2Uint => { + let mut flags = Tfc::COLOR_ATTACHMENT | msaa_count; + flags.set(Tfc::STORAGE_WRITE_ONLY, pc.format_rgb10a2_uint_write); + flags + } + Tf::Rgb10a2Unorm => { + let mut flags = all_caps; + flags.set(Tfc::STORAGE_WRITE_ONLY, pc.format_rgb10a2_unorm_all); + flags + } + Tf::Rg11b10Ufloat => { + let mut flags = all_caps; + flags.set(Tfc::STORAGE_WRITE_ONLY, pc.format_rg11b10_all); + flags + } + Tf::R64Uint => { + Tfc::COLOR_ATTACHMENT + | Tfc::STORAGE_WRITE_ONLY + | image_64_atomic_if + | read_write_tier1_if + } + Tf::Rg32Uint | Tf::Rg32Sint => { + Tfc::COLOR_ATTACHMENT | Tfc::STORAGE_WRITE_ONLY | msaa_count + } + Tf::Rg32Float => { + if pc.format_rg32float_all { + all_caps + } else { + Tfc::STORAGE_WRITE_ONLY + | Tfc::COLOR_ATTACHMENT + | Tfc::COLOR_ATTACHMENT_BLEND + | msaa_count + } + } + Tf::Rgba32Uint | Tf::Rgba32Sint => { + read_write_tier2_if | Tfc::STORAGE_WRITE_ONLY | Tfc::COLOR_ATTACHMENT | msaa_count + } + Tf::Rgba32Float => { + let mut flags = + read_write_tier2_if | Tfc::STORAGE_WRITE_ONLY | Tfc::COLOR_ATTACHMENT; + if pc.format_rgba32float_all { + flags |= all_caps + } else if pc.msaa_apple7 { + flags |= msaa_count + }; + flags + } + Tf::Stencil8 => { + all_caps | Tfc::DEPTH_STENCIL_ATTACHMENT | msaa_count | msaa_resolve_apple3x_if + } + Tf::Depth16Unorm => { + if pc.format_depth16unorm { + let mut flags = + Tfc::DEPTH_STENCIL_ATTACHMENT | msaa_count | msaa_resolve_apple3x_if; + if pc.format_depth16unorm_filter { + flags |= Tfc::SAMPLED_LINEAR; + } + flags + } else { + return Tfc::empty(); + } + } + Tf::Depth32Float | Tf::Depth32FloatStencil8 => { + let mut flags = + Tfc::DEPTH_STENCIL_ATTACHMENT | msaa_count | msaa_resolve_apple3x_if; + if pc.format_depth32float_filter { + flags |= Tfc::SAMPLED_LINEAR + } + flags + } + Tf::Depth24Plus | Tf::Depth24PlusStencil8 => { + let mut flags = Tfc::DEPTH_STENCIL_ATTACHMENT | msaa_count; + if pc.format_depth24_stencil8 { + flags |= Tfc::SAMPLED_LINEAR | Tfc::MULTISAMPLE_RESOLVE + } else { + flags |= msaa_resolve_apple3x_if; + if pc.format_depth32float_filter { + flags |= Tfc::SAMPLED_LINEAR + } + } + flags + } + Tf::NV12 => return Tfc::empty(), + Tf::P010 => return Tfc::empty(), + Tf::Rgb9e5Ufloat => { + if pc.msaa_apple3 { + all_caps + } else if pc.msaa_desktop { + Tfc::SAMPLED_LINEAR + } else { + Tfc::SAMPLED_LINEAR + | Tfc::COLOR_ATTACHMENT + | Tfc::COLOR_ATTACHMENT_BLEND + | msaa_count + | Tfc::MULTISAMPLE_RESOLVE + } + } + Tf::Bc1RgbaUnorm + | Tf::Bc1RgbaUnormSrgb + | Tf::Bc2RgbaUnorm + | Tf::Bc2RgbaUnormSrgb + | Tf::Bc3RgbaUnorm + | Tf::Bc3RgbaUnormSrgb + | Tf::Bc4RUnorm + | Tf::Bc4RSnorm + | Tf::Bc5RgUnorm + | Tf::Bc5RgSnorm + | Tf::Bc6hRgbUfloat + | Tf::Bc6hRgbFloat + | Tf::Bc7RgbaUnorm + | Tf::Bc7RgbaUnormSrgb => { + if pc.format_bc { + Tfc::SAMPLED_LINEAR + } else { + Tfc::empty() + } + } + Tf::Etc2Rgb8Unorm + | Tf::Etc2Rgb8UnormSrgb + | Tf::Etc2Rgb8A1Unorm + | Tf::Etc2Rgb8A1UnormSrgb + | Tf::Etc2Rgba8Unorm + | Tf::Etc2Rgba8UnormSrgb + | Tf::EacR11Unorm + | Tf::EacR11Snorm + | Tf::EacRg11Unorm + | Tf::EacRg11Snorm => { + if pc.format_eac_etc { + Tfc::SAMPLED_LINEAR + } else { + Tfc::empty() + } + } + Tf::Astc { + block: _, + channel: _, + } => { + if pc.format_astc || pc.format_astc_hdr { + Tfc::SAMPLED_LINEAR + } else { + Tfc::empty() + } + } + }; + + Tfc::COPY_SRC | Tfc::COPY_DST | Tfc::SAMPLED | Tfc::STORAGE_READ_ONLY | extra + } + + unsafe fn surface_capabilities( + &self, + surface: &super::Surface, + ) -> Option<crate::SurfaceCapabilities> { + // `CAMetalLayer` color-matches layer contents to whatever display the + // window is on, with the compositor tone-mapping where needed, so + // Display-P3 and HDR (PQ/HLG) color spaces work regardless of the + // physical display's gamut and are not gated on it here. + let format_caps = |format: wgt::TextureFormat| { + let mut color_spaces = + wgt::SurfaceColorSpaces::SRGB | wgt::SurfaceColorSpaces::DISPLAY_P3; + if format == wgt::TextureFormat::Rgba16Float { + // `Rgba16Float` enables Metal's extended dynamic range, in both + // linear (scRGB) and encoded (extended nonlinear sRGB) form, + // for the BT.709 and Display-P3 gamuts. + color_spaces |= wgt::SurfaceColorSpaces::EXTENDED_SRGB_LINEAR + | wgt::SurfaceColorSpaces::EXTENDED_SRGB + | wgt::SurfaceColorSpaces::EXTENDED_DISPLAY_P3; + } + // PQ/HLG only on the >=10-bit formats: 8-bit PQ would result in unusable + // banding. The ITUR_2100 color space constants require + // macOS 11.0/iOS 14.0. + if matches!( + format, + wgt::TextureFormat::Rgba16Float | wgt::TextureFormat::Rgb10a2Unorm + ) && available!(macos = 11.0, ios = 14.0, tvos = 14.0, visionos = 1.0) + { + color_spaces |= + wgt::SurfaceColorSpaces::BT2100_PQ | wgt::SurfaceColorSpaces::BT2100_HLG; + } + wgt::SurfaceFormatCapabilities { + format, + color_spaces, + } + }; + let mut formats = vec![ + format_caps(wgt::TextureFormat::Bgra8Unorm), + format_caps(wgt::TextureFormat::Bgra8UnormSrgb), + format_caps(wgt::TextureFormat::Rgba16Float), + ]; + if self + .shared + .private_texture_format_caps + .format_rgb10a2_unorm_all + { + formats.push(format_caps(wgt::TextureFormat::Rgb10a2Unorm)); + } + + Some(crate::SurfaceCapabilities { + formats, + // We use this here to govern the maximum number of drawables + 1. + // See https://developer.apple.com/documentation/quartzcore/cametallayer/maximumdrawablecount + maximum_frame_latency: if available!( + macos = 10.13.2, + ios = 11.2, + tvos = 11.2, + visionos = 1.0 + ) { + 1..=2 + } else { + // 3 is the default value for maximum drawables in `CAMetalLayer` documentation + // iOS 10.3 was tested to use 3 on iphone5s + 2..=2 + }, + // We enable Immediate mode using `-[CAMetalLayer setDisplaySyncEnabled: false]`. + present_modes: if OsFeatures::display_sync() { + vec![wgt::PresentMode::Fifo, wgt::PresentMode::Immediate] + } else { + vec![wgt::PresentMode::Fifo] + }, + composite_alpha_modes: vec![ + wgt::CompositeAlphaMode::Opaque, + wgt::CompositeAlphaMode::PostMultiplied, + ], + + current_extent: Some(surface.dimensions()), + usage: wgt::TextureUses::COLOR_TARGET + | wgt::TextureUses::COPY_SRC + | wgt::TextureUses::COPY_DST + | wgt::TextureUses::STORAGE_READ_ONLY + | wgt::TextureUses::STORAGE_WRITE_ONLY + | wgt::TextureUses::STORAGE_READ_WRITE, + }) + } + + unsafe fn surface_display_hdr_info( + &self, + surface: &super::Surface, + ) -> Option<wgt::DisplayHdrInfo> { + surface.display_hdr_info() + } + + unsafe fn get_presentation_timestamp(&self) -> wgt::PresentationTimestamp { + let timestamp = self.shared.presentation_timer.get_timestamp_ns(); + + wgt::PresentationTimestamp(timestamp) + } + + fn get_ordered_buffer_usages(&self) -> wgt::BufferUses { + wgt::BufferUses::INCLUSIVE | wgt::BufferUses::MAP_WRITE + } + + // Don't put barriers between inclusive uses + fn get_ordered_texture_usages(&self) -> wgt::TextureUses { + wgt::TextureUses::INCLUSIVE + | wgt::TextureUses::COLOR_TARGET + | wgt::TextureUses::DEPTH_STENCIL_WRITE + } +} + +const RESOURCE_HEAP_SUPPORT: &[MTLFeatureSet] = &[ + MTLFeatureSet::iOS_GPUFamily1_v3, + MTLFeatureSet::tvOS_GPUFamily1_v2, + MTLFeatureSet::macOS_GPUFamily1_v3, +]; + +const MUTABLE_COMPARISON_SAMPLER_SUPPORT: &[MTLFeatureSet] = &[ + MTLFeatureSet::iOS_GPUFamily3_v1, + MTLFeatureSet::macOS_GPUFamily1_v1, +]; + +const SAMPLER_CLAMP_TO_BORDER_SUPPORT: &[MTLFeatureSet] = &[MTLFeatureSet::macOS_GPUFamily1_v2]; + +const ASTC_PIXEL_FORMAT_FEATURES: &[MTLFeatureSet] = &[ + MTLFeatureSet::iOS_GPUFamily2_v1, + MTLFeatureSet::tvOS_GPUFamily1_v1, +]; + +const ANY8_UNORM_SRGB_ALL: &[MTLFeatureSet] = &[ + MTLFeatureSet::iOS_GPUFamily2_v3, + MTLFeatureSet::tvOS_GPUFamily1_v2, +]; + +const ANY8_SNORM_RESOLVE: &[MTLFeatureSet] = &[ + MTLFeatureSet::iOS_GPUFamily2_v1, + MTLFeatureSet::tvOS_GPUFamily1_v1, + MTLFeatureSet::macOS_GPUFamily1_v1, +]; + +const RGBA8_SRGB: &[MTLFeatureSet] = &[ + MTLFeatureSet::iOS_GPUFamily2_v3, + MTLFeatureSet::tvOS_GPUFamily1_v2, +]; + +const RGB10A2UNORM_ALL: &[MTLFeatureSet] = &[ + MTLFeatureSet::iOS_GPUFamily3_v1, + MTLFeatureSet::tvOS_GPUFamily2_v1, + MTLFeatureSet::macOS_GPUFamily1_v1, +]; + +const RGB10A2UINT_WRITE: &[MTLFeatureSet] = &[ + MTLFeatureSet::iOS_GPUFamily3_v1, + MTLFeatureSet::tvOS_GPUFamily2_v1, + MTLFeatureSet::macOS_GPUFamily1_v1, +]; + +const RG11B10FLOAT_ALL: &[MTLFeatureSet] = &[ + MTLFeatureSet::iOS_GPUFamily3_v1, + MTLFeatureSet::tvOS_GPUFamily2_v1, + MTLFeatureSet::macOS_GPUFamily1_v1, +]; + +const RGB9E5FLOAT_ALL: &[MTLFeatureSet] = &[ + MTLFeatureSet::iOS_GPUFamily3_v1, + MTLFeatureSet::tvOS_GPUFamily2_v1, +]; + +const BGR10A2_ALL: &[MTLFeatureSet] = &[ + MTLFeatureSet::iOS_GPUFamily1_v4, + MTLFeatureSet::tvOS_GPUFamily1_v3, + MTLFeatureSet::macOS_GPUFamily2_v1, +]; + +/// "Indirect draw & dispatch arguments" in the Metal feature set tables +const INDIRECT_DRAW_DISPATCH_SUPPORT: &[MTLFeatureSet] = &[ + MTLFeatureSet::iOS_GPUFamily3_v1, + MTLFeatureSet::tvOS_GPUFamily2_v1, + MTLFeatureSet::macOS_GPUFamily1_v1, +]; + +/// "Base vertex/instance drawing" in the Metal feature set tables +/// +/// in our terms, `base_vertex` and `first_instance` must be 0 +const BASE_VERTEX_FIRST_INSTANCE_SUPPORT: &[MTLFeatureSet] = INDIRECT_DRAW_DISPATCH_SUPPORT; + +const TEXTURE_CUBE_ARRAY_SUPPORT: &[MTLFeatureSet] = &[ + MTLFeatureSet::iOS_GPUFamily4_v1, + MTLFeatureSet::tvOS_GPUFamily1_v2, + MTLFeatureSet::macOS_GPUFamily1_v1, +]; + +const DUAL_SOURCE_BLEND_SUPPORT: &[MTLFeatureSet] = &[ + MTLFeatureSet::iOS_GPUFamily1_v4, + MTLFeatureSet::tvOS_GPUFamily1_v3, + MTLFeatureSet::macOS_GPUFamily1_v2, +]; + +const LAYERED_RENDERING_SUPPORT: &[MTLFeatureSet] = &[ + MTLFeatureSet::iOS_GPUFamily5_v1, + MTLFeatureSet::macOS_GPUFamily1_v1, + MTLFeatureSet::macOS_GPUFamily2_v1, +]; + +const FUNCTION_SPECIALIZATION_SUPPORT: &[MTLFeatureSet] = &[ + MTLFeatureSet::iOS_GPUFamily1_v3, + MTLFeatureSet::tvOS_GPUFamily1_v2, + MTLFeatureSet::macOS_GPUFamily1_v2, +]; + +const DEPTH_CLIP_MODE: &[MTLFeatureSet] = &[ + MTLFeatureSet::iOS_GPUFamily4_v1, + MTLFeatureSet::tvOS_GPUFamily1_v3, + MTLFeatureSet::macOS_GPUFamily1_v1, +]; + +impl super::CapabilitiesQuery { + fn supports_any(raw: &ProtocolObject<dyn MTLDevice>, features_sets: &[MTLFeatureSet]) -> bool { + features_sets + .iter() + .cloned() + .any(|x| raw.supportsFeatureSet(x)) + } + + /// Query the capabilities of the device. + pub fn new(device: &ProtocolObject<dyn MTLDevice>) -> Self { + // There are four different OSes we can target: macOS, iOS, tvOS and + // visionOS. This can be detected using `cfg!(target_os = "ios")`, or + // more conveniently using the `available!(...)` macro, which also + // checks that the OS version that the binary is currently running on + // is higher than or equal to the specified version. + // + // Along with the different OSes, there is also two other modes that + // applications can run in: the Simulator, and Mac Catalyst. This can + // be detected using `cfg!(target_env = "sim")` or + // `cfg!(target_env = "macabi")`. + // + // Finally, iOS applications can be run on macOS and visionOS directly + // using the "Designed for iPad" mode. This cannot be detected at + // compile-time. + // + // All of this means that it only makes sense to use `cfg!(...)` and + // `available!(...)` in here to check which Metal APIs are available; + // we cannot rely on it for knowing properties of the device. For + // that, we'll want to use `supportsFeatureSet` or `supportsFamily`. + // + // See the following link for further details: + // https://developer.apple.com/documentation/metal/developing-metal-apps-that-run-in-simulator + + let version = NSProcessInfo::processInfo().operatingSystemVersion(); + let os_type = super::OsType::new(version, device); + + let family_check = available!(macos = 10.15, ios = 13.0, tvos = 13.0, visionos = 1.0); + let metal3 = family_check && device.supportsFamily(MTLGPUFamily::Metal3); + let metal4 = family_check && device.supportsFamily(MTLGPUFamily::Metal4); + let mut sample_count_mask = crate::TextureFormatCapabilities::MULTISAMPLE_X4; // 1 and 4 samples are supported on all devices + if device.supportsTextureSampleCount(2) { + sample_count_mask |= crate::TextureFormatCapabilities::MULTISAMPLE_X2; + } + if device.supportsTextureSampleCount(8) { + sample_count_mask |= crate::TextureFormatCapabilities::MULTISAMPLE_X8; + } + if device.supportsTextureSampleCount(16) { + sample_count_mask |= crate::TextureFormatCapabilities::MULTISAMPLE_X16; + } + + let rw_texture_tier = if available!(macos = 10.13, ios = 11.0, tvos = 11.0, visionos = 1.0) + { + device.readWriteTextureSupport() + } else if available!(macos = 10.12) { + if Self::supports_any(device, &[MTLFeatureSet::macOS_ReadWriteTextureTier2]) { + MTLReadWriteTextureTier::Tier2 + } else { + MTLReadWriteTextureTier::Tier1 + } + } else { + MTLReadWriteTextureTier::TierNone + }; + + let mut timestamp_query_support = TimestampQuerySupport::empty(); + if available!(macos = 11.0, ios = 14.0, tvos = 14.0, visionos = 1.0) + && device.supportsCounterSampling(MTLCounterSamplingPoint::AtStageBoundary) + { + // If we don't support at stage boundary, don't support anything else. + timestamp_query_support.insert(TimestampQuerySupport::STAGE_BOUNDARIES); + + if device.supportsCounterSampling(MTLCounterSamplingPoint::AtDrawBoundary) { + timestamp_query_support.insert(TimestampQuerySupport::ON_RENDER_ENCODER); + } + if device.supportsCounterSampling(MTLCounterSamplingPoint::AtDispatchBoundary) { + timestamp_query_support.insert(TimestampQuerySupport::ON_COMPUTE_ENCODER); + } + if device.supportsCounterSampling(MTLCounterSamplingPoint::AtBlitBoundary) { + timestamp_query_support.insert(TimestampQuerySupport::ON_BLIT_ENCODER); + } + // `TimestampQuerySupport::INSIDE_WGPU_PASSES` emerges from the other flags. + } + + let argument_buffers = available!(macos = 10.13, ios = 11.0, tvos = 11.0, visionos = 1.0) + .then(|| device.argumentBuffersSupport()); + + let is_virtual = device.name().to_string().to_lowercase().contains("virtual"); + + let mesh_shaders = family_check + && (device.supportsFamily(MTLGPUFamily::Metal3) + || device.supportsFamily(MTLGPUFamily::Apple7) + || device.supportsFamily(MTLGPUFamily::Mac2)) + // Mesh shaders don't work on virtual devices even if they should be supported. CI thing + && !is_virtual; + + let msl_version = if available!(macos = 26.0, ios = 26.0, tvos = 26.0, visionos = 26.0) { + MTLLanguageVersion::Version4_0 + } else if available!(macos = 15.0, ios = 18.0, tvos = 18.0, visionos = 2.0) { + MTLLanguageVersion::Version3_2 + } else if available!(macos = 14.0, ios = 17.0, tvos = 17.0, visionos = 1.0) { + MTLLanguageVersion::Version3_1 + } else if available!(macos = 13.0, ios = 16.0, tvos = 16.0, visionos = 1.0) { + MTLLanguageVersion::Version3_0 + } else if available!(macos = 12.0, ios = 15.0, tvos = 15.0, visionos = 1.0) { + MTLLanguageVersion::Version2_4 + } else if available!(macos = 11.0, ios = 14.0, tvos = 14.0, visionos = 1.0) { + MTLLanguageVersion::Version2_3 + } else if available!(macos = 10.15, ios = 13.0, tvos = 13.0, visionos = 1.0) { + MTLLanguageVersion::Version2_2 + } else if available!(macos = 10.14, ios = 12.0, tvos = 12.0, visionos = 1.0) { + MTLLanguageVersion::Version2_1 + } else if available!(macos = 10.13, ios = 11.0, tvos = 11.0, visionos = 1.0) { + MTLLanguageVersion::Version2_0 + } else if available!(macos = 10.12, ios = 10.0, tvos = 10.0, visionos = 1.0) { + MTLLanguageVersion::Version1_2 + } else if available!(macos = 10.11, ios = 9.0, tvos = 9.0, visionos = 1.0) { + MTLLanguageVersion::Version1_1 + } else { + MTLLanguageVersion::Version1_0 + }; + + Self { + msl_version, + // macOS 10.11 doesn't support read-write resources + fragment_rw_storage: available!(macos = 10.12, ios = 8.0, tvos = 8.0, visionos = 1.0), + read_write_texture_tier: rw_texture_tier, + msaa_desktop: os_type == super::OsType::Macos, + msaa_apple3: (family_check && device.supportsFamily(MTLGPUFamily::Apple3)) + || device.supportsFeatureSet(MTLFeatureSet::iOS_GPUFamily3_v4), + msaa_apple7: family_check && device.supportsFamily(MTLGPUFamily::Apple7), + resource_heaps: Self::supports_any(device, RESOURCE_HEAP_SUPPORT), + argument_buffers, + mutable_comparison_samplers: Self::supports_any( + device, + MUTABLE_COMPARISON_SAMPLER_SUPPORT, + ), + sampler_clamp_to_border: Self::supports_any(device, SAMPLER_CLAMP_TO_BORDER_SUPPORT), + indirect_draw_dispatch: Self::supports_any(device, INDIRECT_DRAW_DISPATCH_SUPPORT), + base_vertex_first_instance_drawing: Self::supports_any( + device, + BASE_VERTEX_FIRST_INSTANCE_SUPPORT, + ), + dual_source_blending: Self::supports_any(device, DUAL_SOURCE_BLEND_SUPPORT), + low_power: os_type != super::OsType::Macos || device.isLowPower(), + headless: os_type == super::OsType::Macos && device.isHeadless(), + layered_rendering: Self::supports_any(device, LAYERED_RENDERING_SUPPORT), + function_specialization: Self::supports_any(device, FUNCTION_SPECIALIZATION_SUPPORT), + depth_clip_mode: Self::supports_any(device, DEPTH_CLIP_MODE), + texture_cube_array: Self::supports_any(device, TEXTURE_CUBE_ARRAY_SUPPORT), + supports_float_filtering: os_type == super::OsType::Macos + || (available!(macos = 11.0, ios = 14.0, tvos = 16.0, visionos = 1.0) + && device_class_responds_to(device, sel!(supports32BitFloatFiltering)) + && device.supports32BitFloatFiltering()), + format_depth24_stencil8: os_type == super::OsType::Macos + && device.isDepth24Stencil8PixelFormatSupported(), + format_depth32_stencil8_filter: os_type == super::OsType::Macos, + format_depth32_stencil8_none: os_type != super::OsType::Macos, + format_min_srgb_channels: if os_type == super::OsType::Macos { + 4 + } else { + 1 + }, + format_b5: os_type != super::OsType::Macos, + format_bc: os_type == super::OsType::Macos + || (available!(macos = 11.0, ios = 16.4, tvos = 16.4, visionos = 1.0) + && device_class_responds_to(device, sel!(supportsBCTextureCompression)) + && device.supportsBCTextureCompression()), + format_eac_etc: os_type != super::OsType::Macos + // M1 in macOS supports EAC/ETC2 + || (family_check && device.supportsFamily(MTLGPUFamily::Apple7)), + // A8(Apple2) and later always support ASTC pixel formats + format_astc: (family_check && device.supportsFamily(MTLGPUFamily::Apple2)) + || Self::supports_any(device, ASTC_PIXEL_FORMAT_FEATURES), + // A13(Apple6) M1(Apple7) and later always support HDR ASTC pixel formats + format_astc_hdr: family_check && device.supportsFamily(MTLGPUFamily::Apple6), + // Apple3 and later supports compressed volume texture formats including ASTC Sliced 3D + format_astc_3d: family_check && device.supportsFamily(MTLGPUFamily::Apple3), + format_any8_unorm_srgb_all: Self::supports_any(device, ANY8_UNORM_SRGB_ALL), + format_any8_unorm_srgb_no_write: !Self::supports_any(device, ANY8_UNORM_SRGB_ALL) + && os_type != super::OsType::Macos, + format_any8_snorm_all: Self::supports_any(device, ANY8_SNORM_RESOLVE), + format_r16_norm_all: os_type == super::OsType::Macos, + // No devices support r32's all capabilities + format_r32_all: false, + // All devices support r32's write capability + format_r32_no_write: false, + // iOS support r32float's write capability, macOS support r32float's all capabilities + format_r32float_no_write_no_filter: false, + // Only iOS doesn't support r32float's filter capability + format_r32float_no_filter: os_type != super::OsType::Macos, + format_r32float_all: os_type == super::OsType::Macos, + format_rgba8_srgb_all: Self::supports_any(device, RGBA8_SRGB), + format_rgba8_srgb_no_write: !Self::supports_any(device, RGBA8_SRGB), + format_rgb10a2_unorm_all: Self::supports_any(device, RGB10A2UNORM_ALL), + format_rgb10a2_unorm_no_write: !Self::supports_any(device, RGB10A2UNORM_ALL), + format_rgb10a2_uint_write: Self::supports_any(device, RGB10A2UINT_WRITE), + format_rg11b10_all: Self::supports_any(device, RG11B10FLOAT_ALL), + format_rg11b10_no_write: !Self::supports_any(device, RG11B10FLOAT_ALL), + format_rgb9e5_all: Self::supports_any(device, RGB9E5FLOAT_ALL), + format_rgb9e5_no_write: !Self::supports_any(device, RGB9E5FLOAT_ALL) + && os_type != super::OsType::Macos, + format_rgb9e5_filter_only: os_type == super::OsType::Macos, + format_rg32_color: true, + format_rg32_color_write: true, + // Only macOS support rg32float's all capabilities + format_rg32float_all: os_type == super::OsType::Macos, + // All devices support rg32float's color + blend capabilities + format_rg32float_color_blend: true, + // Only iOS doesn't support rg32float's filter + format_rg32float_no_filter: os_type != super::OsType::Macos, + format_rgba32int_color: true, + // All devices support rgba32uint and rgba32sint's color + write capabilities + format_rgba32int_color_write: true, + format_rgba32float_color: true, + // All devices support rgba32float's color + write capabilities + format_rgba32float_color_write: true, + // Only macOS support rgba32float's all capabilities + format_rgba32float_all: os_type == super::OsType::Macos, + // https://developer.apple.com/documentation/metal/mtlpixelformat/depth16unorm + format_depth16unorm: available!(macos = 10.12, ios = 13.0, tvos = 13.0, visionos = 1.0), + // https://developer.apple.com/metal/Metal-Feature-Set-Tables.pdf#page=12 + format_depth16unorm_filter: family_check + && (metal3 + || device.supportsFamily(MTLGPUFamily::Apple3) + || device.supportsFamily(MTLGPUFamily::Mac2)), + format_depth32float_filter: os_type == super::OsType::Macos, + format_depth32float_none: os_type != super::OsType::Macos, + format_bgr10a2_all: Self::supports_any(device, BGR10A2_ALL), + format_bgr10a2_no_write: !Self::supports_any(device, BGR10A2_ALL), + // "Maximum number of entries in the texture argument table, per graphics or kernel function" + // The tuple is (sampled, storage). + // The default limit split in WebGPU is 80%-20%. + // - The default maxSampledTexturesPerShaderStage in WebGPU is 16. + // - The default maxStorageTexturesPerShaderStage in WebGPU is 4. + // Use a split of 75%-25% which can exactly split 128 and 96. + max_textures_per_stage: if os_type == super::OsType::Macos + || (family_check && device.supportsFamily(MTLGPUFamily::Apple6)) + { + (96, 32) // 128 + } else if family_check && device.supportsFamily(MTLGPUFamily::Apple4) { + (72, 24) // 96 + } else { + (23, 8) // 31 + }, + max_binding_array_elements: if argument_buffers == Some(MTLArgumentBuffersTier::Tier2) { + 1_000_000 + } else if family_check && device.supportsFamily(MTLGPUFamily::Apple4) { + 96 + } else { + 31 + }, + // https://developer.apple.com/metal/Metal-Feature-Set-Tables.pdf#page=7 + max_sampler_binding_array_elements: if family_check + && device.supportsFamily(MTLGPUFamily::Apple9) + { + 500_000 + } else if family_check + && (device.supportsFamily(MTLGPUFamily::Apple7) + || device.supportsFamily(MTLGPUFamily::Mac2)) + { + 1024 + } else if family_check && device.supportsFamily(MTLGPUFamily::Apple6) { + 128 + } else { + 16 + }, + // "Buffer alignment for copying an existing texture to a buffer" + buffer_alignment: if matches!(os_type, super::OsType::Macos | super::OsType::VisionOs) { + 256 + } else if family_check && device.supportsFamily(MTLGPUFamily::Apple3) { + 16 + } else { + 64 + }, + // "Minimum constant buffer offset alignment" + constant_buffer_offset_alignment: if matches!( + os_type, + super::OsType::Macos | super::OsType::VisionOs + ) { + 256 + } else if device.supportsFeatureSet(MTLFeatureSet::macOS_GPUFamily2_v1) { + 32 + } else { + 4 + }, + max_buffer_size: if available!(macos = 10.14, ios = 12.0, tvos = 12.0, visionos = 1.0) { + device.maxBufferLength() as u64 + } else if os_type == super::OsType::Macos { + 1 << 30 // 1GB on macOS 10.11 and up + } else { + 1 << 28 // 256MB on iOS 8.0+ + }, + // "Maximum 1D texture width" & + // "Maximum 2D texture width and height" & + // "Maximum cube map texture width and height" + max_texture_size: if family_check && device.supportsFamily(MTLGPUFamily::Apple10) { + 32768 + } else if Self::supports_any( + device, + &[ + MTLFeatureSet::iOS_GPUFamily3_v1, + MTLFeatureSet::tvOS_GPUFamily2_v1, + MTLFeatureSet::macOS_GPUFamily1_v1, + ], + ) { + 16384 + } else { + 8192 + }, + // "Maximum 3D texture width, height, and depth" + max_texture_3d_size: 2048, + // "Maximum number of layers per 1D texture array, 2D texture array, or 3D texture" + max_texture_layers: 2048, + max_fragment_input_components: if os_type == super::OsType::Macos + || device.supportsFeatureSet(MTLFeatureSet::iOS_GPUFamily4_v1) + { + 124 + } else { + 60 + }, + // "Maximum number of color render targets per render pass descriptor" + // https://developer.apple.com/metal/Metal-Feature-Set-Tables.pdf#page=7 + max_color_render_targets: if Self::supports_any( + device, + &[ + MTLFeatureSet::iOS_GPUFamily2_v1, + MTLFeatureSet::tvOS_GPUFamily1_v1, + MTLFeatureSet::macOS_GPUFamily1_v1, + ], + ) { + 8 + } else { + 4 + }, + // "Maximum total render target size, per pixel, when using multiple color render targets" + // https://developer.apple.com/metal/Metal-Feature-Set-Tables.pdf#page=7 + max_color_attachment_bytes_per_sample: if family_check + && device.supportsFamily(MTLGPUFamily::Apple4) + { + 64 // 512 bits + } else if family_check && device.supportsFamily(MTLGPUFamily::Apple2) { + 32 // 256 bits + } else if device.supportsFeatureSet(MTLFeatureSet::macOS_GPUFamily1_v1) { + // No Limit, use max_color_render_targets * MAX_TARGET_PIXEL_BYTE_COST + 8 * wgt::TextureFormat::MAX_TARGET_PIXEL_BYTE_COST as u8 // 1024 bits + } else { + 16 // 128 bits + }, + // This limit is the minimum of: + // - "Maximum scalar or vector inputs to a fragment function" + // - "Maximum number of input components to a fragment function" / 4 + // + // On non-Apple GPUs only, the Metal validation layers will error with: + // + // "number of shader varying components (125) exceeds limit (124). + // Note that on macOS the following attributes count towards the + // limit: [[position]], [[clip_distance]], [[point_size]], + // [[point_coord]], and, when read in the fragment shader, + // [[viewport_array_index]] & [[render_target_array_index]]." + // + // if the limit in the feature tables is crossed while also using + // one of the built-ins mentioned above. + // + // Note that the error says "on macOS" but it actually only applies + // to non-Apple GPUs. + // + // We only need to account for the position built-in since the others + // are either not used or they already count towards the limit + // calculation as specified by WebGPU. + max_inter_stage_shader_variables: if family_check + && device.supportsFamily(MTLGPUFamily::Apple4) + { + 31 // min(124, 124 / 4) + } else if device.supportsFeatureSet(MTLFeatureSet::macOS_GPUFamily1_v1) { + 30 // min(32, 124 / 4) - 1 + } else { + 15 // min(60, 60 / 4) + }, + // "Maximum threads per threadgroup" + // https://developer.apple.com/metal/Metal-Feature-Set-Tables.pdf#page=6 + // These are older checks but still hold true; no entry in this table supports + // more than 1024 threads. + // **Note:** this is used to emit the `[[max_total_threads_per_threadgroup]]` + // attribute. This is how we guarantee that compute dispatches will always run + // and not silently fail due to hardware register pressure or occupancy limits. + max_threads_per_group: if Self::supports_any( + device, + &[ + MTLFeatureSet::iOS_GPUFamily4_v1, + MTLFeatureSet::macOS_GPUFamily1_v1, + ], + ) { + 1024 + } else { + 512 + }, + // "Maximum total threadgroup memory allocation" + // https://developer.apple.com/metal/Metal-Feature-Set-Tables.pdf#page=6 + // These are older checks but still hold true; no entry in this table supports + // more than 32kb. + max_total_threadgroup_memory: if Self::supports_any( + device, + &[ + MTLFeatureSet::iOS_GPUFamily4_v1, + MTLFeatureSet::macOS_GPUFamily1_v1, + ], + ) { + 32 << 10 + } else { + 16 << 10 + }, + sample_count_mask, + supports_debug_markers: Self::supports_any( + device, + &[ + MTLFeatureSet::macOS_GPUFamily1_v2, + MTLFeatureSet::iOS_GPUFamily1_v3, + MTLFeatureSet::tvOS_GPUFamily1_v2, + ], + ), + // https://developer.apple.com/metal/Metal-Feature-Set-Tables.pdf#page=4 + supports_binary_archives: family_check + && (metal3 + || device.supportsFamily(MTLGPUFamily::Apple3) + || device.supportsFamily(MTLGPUFamily::Mac2)), + // This is just trusted blindly since docs referencing supports_any have been removed + // but we don't want to remove feature support. + supports_arrays_of_textures: Self::supports_any( + device, + &[ + MTLFeatureSet::iOS_GPUFamily3_v2, + MTLFeatureSet::tvOS_GPUFamily2_v1, + MTLFeatureSet::macOS_GPUFamily1_v3, + ], + ), + // https://developer.apple.com/metal/Metal-Feature-Set-Tables.pdf#page=3 + supports_arrays_of_textures_write: family_check + && (metal3 + || device.supportsFamily(MTLGPUFamily::Apple6) + || device.supportsFamily(MTLGPUFamily::Mac2)), + // Depth clipping is supported on all macOS GPU families and iOS family 4 and later + supports_depth_clip_control: os_type == super::OsType::Macos + || device.supportsFeatureSet(MTLFeatureSet::iOS_GPUFamily4_v1), + // https://developer.apple.com/metal/Metal-Feature-Set-Tables.pdf#page=4 + supports_shader_primitive_index: family_check + && (metal3 + || device.supportsFamily(MTLGPUFamily::Apple7) + || device.supportsFamily(MTLGPUFamily::Mac2)), + // https://developer.apple.com/documentation/metal/mtldevice/hasunifiedmemory + has_unified_memory: if available!( + macos = 10.15, + ios = 13.0, + tvos = 13.0, + visionos = 1.0 + ) && device_class_responds_to(device, sel!(hasUnifiedMemory)) + { + Some(device.hasUnifiedMemory()) + } else { + None + }, + timestamp_query_support, + // https://developer.apple.com/metal/Metal-Feature-Set-Tables.pdf#page=4 + supports_simd_scoped_operations: family_check + && (metal3 + || device.supportsFamily(MTLGPUFamily::Mac2) + || device.supportsFamily(MTLGPUFamily::Apple7)), + // https://developer.apple.com/metal/Metal-Feature-Set-Tables.pdf#page=4 + int64: family_check && (metal3 || device.supportsFamily(MTLGPUFamily::Apple3)), + // https://developer.apple.com/metal/Metal-Feature-Set-Tables.pdf#page=4 + // There is also a footnote that says + // "Some GPU devices in the Apple8 family support 64-bit atomic minimum and maximum..." + int64_atomics_min_max: family_check + && (device.supportsFamily(MTLGPUFamily::Apple9) + || (device.supportsFamily(MTLGPUFamily::Apple8) + && device.supportsFamily(MTLGPUFamily::Mac2))), + int64_atomics: family_check && device.supportsFamily(MTLGPUFamily::Apple9), + // https://developer.apple.com/metal/Metal-Feature-Set-Tables.pdf#page=4 + float_atomics: family_check + && (metal3 + || device.supportsFamily(MTLGPUFamily::Apple7) + || device.supportsFamily(MTLGPUFamily::Mac2)), + // https://developer.apple.com/metal/Metal-Feature-Set-Tables.pdf#page=5 (footnote) + // Supported on some Metal4, Apple7, Mac2, and some other platforms can be queried with device.supportsShaderBarycentricCoordinates(). + shader_barycentrics: metal4 + || (family_check + && (device.supportsFamily(MTLGPUFamily::Apple7) + || device.supportsFamily(MTLGPUFamily::Mac2))) + || (available!(macos = 10.15, ios = 14.0, tvos = 16.0, visionos = 1.0) + && device_class_responds_to( + device, + sel!(supportsShaderBarycentricCoordinates), + ) + && device.supportsShaderBarycentricCoordinates()), + // https://developer.apple.com/metal/Metal-Feature-Set-Tables.pdf#page=3 + // See https://github.com/gfx-rs/wgpu/pull/8725 for more details + supports_memoryless_storage: metal4 + || if family_check { + // Apple A7 (MTLGPUFamily::Apple1) has been tested to have support. + device.supportsFamily(MTLGPUFamily::Apple1) + } else { + // macOS: Always rely on family check + // iOS/tvOS: API added in 10.0 + // visionOS: Always rely on family check + available!(ios = 10.0, tvos = 10.0) + }, + supported_vertex_amplification_factor: { + let mut factor = 1; + // https://developer.apple.com/documentation/metal/mtldevice/supportsvertexamplificationcount(_:) + if available!(macos = 10.15.4, ios = 13.0, tvos = 16.0, visionos = 1.0) { + // https://developer.apple.com/metal/Metal-Feature-Set-Tables.pdf#page=8 + // The table specifies either none, 2, 8, or unsupported, implying it is a relatively small power of 2 + // The bitmask only uses 32 bits, so it can't be higher even if the device for some reason claims to support that. + while factor < 32 && device.supportsVertexAmplificationCount(factor * 2) { + factor *= 2 + } + } + factor as u32 + }, + // https://developer.apple.com/metal/Metal-Feature-Set-Tables.pdf#page=4 + mesh_shaders, + max_task_workgroup_count: if mesh_shaders + && (metal4 || device.supportsFamily(MTLGPUFamily::Apple2)) + { + u32::MAX + } else if mesh_shaders { + 1024 + } else { + 0 + }, + max_mesh_workgroup_count: if mesh_shaders + && device.supportsFamily(MTLGPUFamily::Apple10) + { + 2u32.pow(22) + } else if mesh_shaders && device.supportsFamily(MTLGPUFamily::Apple9) { + 2u32.pow(20) + } else if mesh_shaders { + 1024 + } else { + 0 + }, + max_task_payload_size: if mesh_shaders { 16384 - 32 } else { 0 }, + supports_cooperative_matrix: family_check + && (device.supportsFamily(MTLGPUFamily::Apple7) + || device.supportsFamily(MTLGPUFamily::Mac2)), + // https://developer.apple.com/documentation/metal/mtlresidencyset + supports_raytracing: if available!( + macos = 15.0, + ios = 18.0, + tvos = 18.0, + visionos = 2.0, + ) { + device_class_responds_to(device, sel!(supportsRaytracing)) + && device.supportsRaytracing() + && device_class_responds_to(device, sel!(supportsRaytracingFromRender)) + && device.supportsRaytracingFromRender() + } else { + false + }, + shader_per_vertex: family_check && device.supportsFamily(MTLGPUFamily::Apple10), + + //https://developer.apple.com/documentation/metal/mtltexturetype/type2dmultisamplearray + supports_multisample_array: available!( + macos = 10.14, + ios = 14.0, + tvos = 16.0, + visionos = 1.0 + ), + } + } + + pub fn features(&self) -> wgt::Features { + use wgt::Features as F; + + let mut features = F::empty() + | F::MAPPABLE_PRIMARY_BUFFERS + | F::VERTEX_WRITABLE_STORAGE + | F::TEXTURE_ADAPTER_SPECIFIC_FORMAT_FEATURES + | F::IMMEDIATES + | F::POLYGON_MODE_LINE + | F::CLEAR_TEXTURE + | F::TEXTURE_FORMAT_16BIT_NORM + | F::SHADER_F16 + | F::SHADER_I16 + | F::DEPTH32FLOAT_STENCIL8 + | F::BGRA8UNORM_STORAGE + | F::PASSTHROUGH_SHADERS + | F::EXTERNAL_TEXTURE; + + features.set(F::FLOAT32_FILTERABLE, self.supports_float_filtering); + features.set(F::FLOAT32_BLENDABLE, true); + features.set(F::INDIRECT_FIRST_INSTANCE, self.indirect_draw_dispatch); + features.set( + F::TIMESTAMP_QUERY, + self.timestamp_query_support + .contains(TimestampQuerySupport::STAGE_BOUNDARIES), + ); + features.set( + F::TIMESTAMP_QUERY_INSIDE_ENCODERS, + self.timestamp_query_support + .contains(TimestampQuerySupport::ON_BLIT_ENCODER), + ); + features.set( + F::TIMESTAMP_QUERY_INSIDE_PASSES, + self.timestamp_query_support + .contains(TimestampQuerySupport::INSIDE_WGPU_PASSES), + ); + features.set(F::CLIP_DISTANCES, true); + features.set( + F::DUAL_SOURCE_BLENDING, + self.msl_version >= MTLLanguageVersion::Version1_2 && self.dual_source_blending, + ); + features.set(F::TEXTURE_COMPRESSION_ASTC, self.format_astc); + features.set(F::TEXTURE_COMPRESSION_ASTC_HDR, self.format_astc_hdr); + features.set(F::TEXTURE_COMPRESSION_ASTC_SLICED_3D, self.format_astc_3d); + features.set(F::TEXTURE_COMPRESSION_BC, self.format_bc); + features.set(F::TEXTURE_COMPRESSION_BC_SLICED_3D, self.format_bc); // BC guarantees Sliced 3D + features.set(F::TEXTURE_COMPRESSION_ETC2, self.format_eac_etc); + + features.set(F::DEPTH_CLIP_CONTROL, self.supports_depth_clip_control); + features.set(F::PRIMITIVE_INDEX, self.supports_shader_primitive_index); + + features.set( + F::TEXTURE_BINDING_ARRAY + | F::SAMPLED_TEXTURE_AND_STORAGE_BUFFER_ARRAY_NON_UNIFORM_INDEXING + | F::STORAGE_TEXTURE_ARRAY_NON_UNIFORM_INDEXING + | F::PARTIALLY_BOUND_BINDING_ARRAY, + self.msl_version >= MTLLanguageVersion::Version3_0 + && self.supports_arrays_of_textures + && self + .argument_buffers + .unwrap_or(MTLArgumentBuffersTier::Tier1) + >= MTLArgumentBuffersTier::Tier2, + ); + features.set( + F::BUFFER_BINDING_ARRAY, + self.msl_version >= MTLLanguageVersion::Version2_0 + && self + .argument_buffers + .unwrap_or(MTLArgumentBuffersTier::Tier1) + >= MTLArgumentBuffersTier::Tier2, + ); + features.set( + F::STORAGE_RESOURCE_BINDING_ARRAY, + self.msl_version >= MTLLanguageVersion::Version3_0 + && self.supports_arrays_of_textures + && self.supports_arrays_of_textures_write + && self + .argument_buffers + .unwrap_or(MTLArgumentBuffersTier::Tier1) + >= MTLArgumentBuffersTier::Tier2, + ); + features.set( + F::SHADER_INT64, + self.int64 && self.msl_version >= MTLLanguageVersion::Version2_3, + ); + features.set( + F::SHADER_INT64_ATOMIC_MIN_MAX, + self.int64_atomics_min_max && self.msl_version >= MTLLanguageVersion::Version2_4, + ); + features.set( + F::TEXTURE_INT64_ATOMIC, + self.int64_atomics && self.msl_version >= MTLLanguageVersion::Version3_1, + ); + features.set( + F::TEXTURE_ATOMIC, + self.msl_version >= MTLLanguageVersion::Version3_1, + ); + features.set( + F::SHADER_FLOAT32_ATOMIC, + self.float_atomics && self.msl_version >= MTLLanguageVersion::Version3_0, + ); + features.set( + F::MEMORY_DECORATION_COHERENT, + self.msl_version >= MTLLanguageVersion::Version3_2, + ); + + features.set( + F::ADDRESS_MODE_CLAMP_TO_BORDER, + self.sampler_clamp_to_border, + ); + features.set(F::ADDRESS_MODE_CLAMP_TO_ZERO, true); + + features.set(F::RG11B10UFLOAT_RENDERABLE, self.format_rg11b10_all); + + features.set( + F::SHADER_BARYCENTRICS, + self.shader_barycentrics && self.msl_version >= MTLLanguageVersion::Version2_2, + ); + + features.set(F::SHADER_PER_VERTEX, self.shader_per_vertex); + + if self.supports_simd_scoped_operations { + features.insert(F::SUBGROUP | F::SUBGROUP_BARRIER); + } + + features.set( + F::EXPERIMENTAL_MESH_SHADER | F::EXPERIMENTAL_MESH_SHADER_POINTS, + self.mesh_shaders, + ); + features.set( + F::EXPERIMENTAL_MESH_SHADER_MULTIVIEW, + self.supported_vertex_amplification_factor > 1 && self.mesh_shaders, + ); + + // Cooperative matrix (simdgroup matrix) requires MSL 2.3+ + features.set( + F::EXPERIMENTAL_COOPERATIVE_MATRIX, + self.supports_cooperative_matrix && self.msl_version >= MTLLanguageVersion::Version2_3, + ); + + if self.supported_vertex_amplification_factor > 1 { + features.insert(F::MULTIVIEW); + } + + features.set(F::EXPERIMENTAL_RAY_QUERY, self.supports_raytracing); + + features.set(F::MULTISAMPLE_ARRAY, self.supports_multisample_array); + + features + } + + pub fn capabilities(&self, instance_flags: wgt::InstanceFlags) -> crate::Capabilities { + let mut downlevel = wgt::DownlevelCapabilities::default(); + downlevel.flags.set( + wgt::DownlevelFlags::FRAGMENT_WRITABLE_STORAGE, + self.fragment_rw_storage, + ); + downlevel.flags.set( + wgt::DownlevelFlags::CUBE_ARRAY_TEXTURES, + self.texture_cube_array, + ); + // TODO: separate the mutable comparisons from immutable ones + downlevel.flags.set( + wgt::DownlevelFlags::COMPARISON_SAMPLERS, + self.mutable_comparison_samplers, + ); + downlevel.flags.set( + wgt::DownlevelFlags::INDIRECT_EXECUTION, + self.indirect_draw_dispatch, + ); + // TODO: add another flag for `first_instance` + downlevel.flags.set( + wgt::DownlevelFlags::BASE_VERTEX, + self.base_vertex_first_instance_drawing, + ); + downlevel + .flags + .set(wgt::DownlevelFlags::ANISOTROPIC_FILTERING, true); + + downlevel.flags.set( + wgt::DownlevelFlags::MSL2_1, + self.msl_version >= MTLLanguageVersion::Version2_1, + ); + downlevel.flags.set( + wgt::DownlevelFlags::TEXTURE_COMPRESSION, + self.format_bc || (self.format_eac_etc && self.format_astc), + ); + + let max_storage_buffers_per_shader_stage; + let max_uniform_buffers_per_shader_stage; + let max_vertex_buffers; + let max_acceleration_structures_per_shader_stage; + let max_buffers_and_acceleration_structures_per_shader_stage; + + // Metal has a single buffer limit that we must split across 3 WebGPU limits: + // - maxStorageBuffersPerShaderStage; must be at least 8 + // - maxUniformBuffersPerShaderStage; must be at least 12 + // - maxVertexBuffers; must be at least 8 + // We also have to reserve 2 additional internal buffers: + // - one for immediate data + // - one for sizes of other buffers + if instance_flags.contains(wgt::InstanceFlags::STRICT_WEBGPU_COMPLIANCE) { + max_storage_buffers_per_shader_stage = 9; + max_uniform_buffers_per_shader_stage = 12; + max_vertex_buffers = 8; + max_acceleration_structures_per_shader_stage = 0; + max_buffers_and_acceleration_structures_per_shader_stage = u32::MAX; + } else { + const MAX_USABLE_BUFFERS: u32 = MAX_BUFFERS - 2; + max_storage_buffers_per_shader_stage = MAX_USABLE_BUFFERS; + max_uniform_buffers_per_shader_stage = MAX_USABLE_BUFFERS; + max_vertex_buffers = MAX_USABLE_BUFFERS; + max_acceleration_structures_per_shader_stage = MAX_USABLE_BUFFERS; + max_buffers_and_acceleration_structures_per_shader_stage = MAX_USABLE_BUFFERS; + } + + let limits = crate::auxil::adjust_raw_limits(wgt::Limits { + // + // WebGPU LIMITS: + // Based on https://gpuweb.github.io/gpuweb/correspondence/#limits + // + max_texture_dimension_1d: self.max_texture_size as u32, + max_texture_dimension_2d: self.max_texture_size as u32, + max_texture_dimension_3d: self.max_texture_3d_size as u32, + max_texture_array_layers: self.max_texture_layers as u32, + // No limit. + max_bind_groups: u32::MAX, + // No limit. Once we start using argument buffers we should set this appropriately. + max_bind_groups_plus_vertex_buffers: u32::MAX, + // No limit. + max_bindings_per_bind_group: u32::MAX, + // No limit, use maxUniformBuffersPerShaderStage. + max_dynamic_uniform_buffers_per_pipeline_layout: max_uniform_buffers_per_shader_stage, + // No limit, use maxStorageBuffersPerShaderStage. + max_dynamic_storage_buffers_per_pipeline_layout: max_storage_buffers_per_shader_stage, + // "Maximum number of entries in the sampler state argument table, per graphics or kernel function" + max_samplers_per_shader_stage: 16, + max_sampled_textures_per_shader_stage: self.max_textures_per_stage.0, + max_storage_textures_per_shader_stage: self.max_textures_per_stage.1, + max_storage_buffers_per_shader_stage, + max_uniform_buffers_per_shader_stage, + max_vertex_buffers, + max_buffer_size: self.max_buffer_size, + // No limit, use maxBufferSize. + max_uniform_buffer_binding_size: self.max_buffer_size, + // No limit, use maxBufferSize. + max_storage_buffer_binding_size: self.max_buffer_size, + min_uniform_buffer_offset_alignment: self.constant_buffer_offset_alignment, + // No documented limit. Use 32, which is the lowest allowed value. + min_storage_buffer_offset_alignment: 32, + // "Maximum number of vertex attributes, per vertex descriptor" + max_vertex_attributes: 31, + // No documented limit, matches Vulkan's minimum limit and D3D12's static limit. + max_vertex_buffer_array_stride: 2048, + max_inter_stage_shader_variables: self.max_inter_stage_shader_variables, + max_color_attachments: self.max_color_render_targets as u32, + max_color_attachment_bytes_per_sample: self.max_color_attachment_bytes_per_sample + as u32, + max_compute_workgroup_storage_size: self.max_total_threadgroup_memory, + max_compute_invocations_per_workgroup: self.max_threads_per_group, + max_compute_workgroup_size_x: self.max_threads_per_group, + max_compute_workgroup_size_y: self.max_threads_per_group, + max_compute_workgroup_size_z: self.max_threads_per_group, + // No documented limit, matches Vulkan's minimum limit and D3D12's static limit. + max_compute_workgroups_per_dimension: 0xFFFF, + max_immediate_size: 0x1000, + // + // NATIVE (Non-WebGPU) LIMITS: + // + max_non_sampler_bindings: u32::MAX, + + max_binding_array_elements_per_shader_stage: self.max_binding_array_elements, + max_binding_array_sampler_elements_per_shader_stage: self + .max_sampler_binding_array_elements, + max_binding_array_acceleration_structure_elements_per_shader_stage: 0, + + // from https://developer.apple.com/documentation/metal/mtlaccelerationstructureusage/extendedlimits + max_blas_primitive_count: 1 << 28, + max_blas_geometry_count: 1 << 24, + max_tlas_instance_count: 1 << 24, + // From 2.17.7 in https://developer.apple.com/metal/Metal-Shading-Language-Specification.pdf + // > [Acceleration structures] are opaque objects that can be bound directly using + // buffer binding points or via argument buffers + max_acceleration_structures_per_shader_stage, + max_buffers_and_acceleration_structures_per_shader_stage, + + max_multiview_view_count: if self.supported_vertex_amplification_factor > 1 { + self.supported_vertex_amplification_factor + } else { + 0 + }, + + // Should be not too large + max_task_workgroup_total_count: self.max_task_workgroup_count, + max_task_workgroups_per_dimension: self.max_task_workgroup_count, + max_mesh_workgroup_total_count: self.max_mesh_workgroup_count, + max_mesh_workgroups_per_dimension: self.max_mesh_workgroup_count, + max_task_invocations_per_workgroup: if self.mesh_shaders { 1024 } else { 0 }, + max_task_invocations_per_dimension: if self.mesh_shaders { 1024 } else { 0 }, + max_mesh_invocations_per_workgroup: if self.mesh_shaders { 1024 } else { 0 }, + max_mesh_invocations_per_dimension: if self.mesh_shaders { 1024 } else { 0 }, + // Using certain variables or debuggers can reduce the size by 32 bytes + max_task_payload_size: self.max_task_payload_size, + max_mesh_output_vertices: 256, + max_mesh_output_primitives: 256, + max_mesh_output_layers: self.max_texture_layers as u32, + max_mesh_multiview_view_count: 0, + // unimplemented + max_ray_dispatch_count: 0, + max_ray_recursion_depth: 0, + }); + + crate::Capabilities { + limits, + alignments: crate::Alignments { + buffer_copy_offset: wgt::BufferSize::new(self.buffer_alignment).unwrap(), + buffer_copy_pitch: wgt::BufferSize::new(4).unwrap(), + // This backend has Naga incorporate bounds checks into the + // Metal Shading Language it generates, so from `wgpu_hal`'s + // users' point of view, references are tightly checked. + uniform_bounds_check_alignment: wgt::BufferSize::new(1).unwrap(), + raw_tlas_instance_size: u32::try_from(size_of::< + MTLIndirectAccelerationStructureInstanceDescriptor, + >()) + .unwrap(), + ray_tracing_scratch_buffer_alignment: 1, + // Not yet supported + ray_tracing_pipeline_group_data_size: 0, + ray_tracing_pipeline_group_data_alignment: 0, + ray_tracing_pipeline_data_offset_alignment: 0, + }, + downlevel, + cooperative_matrix_properties: self.cooperative_matrix_properties(), + } + } + + /// Returns the supported cooperative matrix configurations for Metal. + /// + /// Metal's simdgroup_matrix supports 8x8 tiles with f16 and f32 element types. + fn cooperative_matrix_properties(&self) -> Vec<wgt::CooperativeMatrixProperties> { + if !self.supports_cooperative_matrix || self.msl_version < MTLLanguageVersion::Version2_3 { + return Vec::new(); + } + + vec![ + // 8x8 f32 configuration + wgt::CooperativeMatrixProperties { + m_size: 8, + n_size: 8, + k_size: 8, + ab_type: wgt::CooperativeScalarType::F32, + cr_type: wgt::CooperativeScalarType::F32, + saturating_accumulation: false, + }, + // 8x8 f16 configuration + wgt::CooperativeMatrixProperties { + m_size: 8, + n_size: 8, + k_size: 8, + ab_type: wgt::CooperativeScalarType::F16, + cr_type: wgt::CooperativeScalarType::F16, + saturating_accumulation: false, + }, + // Mixed precision: f16 inputs, f32 accumulator + wgt::CooperativeMatrixProperties { + m_size: 8, + n_size: 8, + k_size: 8, + ab_type: wgt::CooperativeScalarType::F16, + cr_type: wgt::CooperativeScalarType::F32, + saturating_accumulation: false, + }, + ] + } + + pub fn private_capabilities(&self) -> super::PrivateCapabilities { + super::PrivateCapabilities { + msl_version: self.msl_version, + low_power: self.low_power, + headless: self.headless, + has_unified_memory: self.has_unified_memory, + timestamp_query_support: self.timestamp_query_support, + supports_memoryless_storage: self.supports_memoryless_storage, + mesh_shaders: self.mesh_shaders, + } + } + + pub fn private_texture_format_capabilities(&self) -> super::PrivateTextureFormatCapabilities { + super::PrivateTextureFormatCapabilities { + read_write_texture_tier: self.read_write_texture_tier, + sample_count_mask: self.sample_count_mask, + int64_atomics: self.int64_atomics, + msaa_desktop: self.msaa_desktop, + msaa_apple3: self.msaa_apple3, + msaa_apple7: self.msaa_apple7, + format_r32float_all: self.format_r32float_all, + format_rgba8_srgb_all: self.format_rgba8_srgb_all, + format_rgb10a2_uint_write: self.format_rgb10a2_uint_write, + format_rgb10a2_unorm_all: self.format_rgb10a2_unorm_all, + format_rg11b10_all: self.format_rg11b10_all, + format_rg32float_all: self.format_rg32float_all, + format_rgba32float_all: self.format_rgba32float_all, + format_depth16unorm: self.format_depth16unorm, + format_depth16unorm_filter: self.format_depth16unorm_filter, + format_depth32float_filter: self.format_depth32float_filter, + format_depth24_stencil8: self.format_depth24_stencil8, + format_bc: self.format_bc, + format_eac_etc: self.format_eac_etc, + format_astc: self.format_astc, + format_astc_hdr: self.format_astc_hdr, + } + } +} + +impl super::PrivateCapabilities { + pub fn device_type(&self) -> wgt::DeviceType { + if self.has_unified_memory.unwrap_or(self.low_power) { + wgt::DeviceType::IntegratedGpu + } else { + wgt::DeviceType::DiscreteGpu + } + } +} + +impl super::PrivateTextureFormatCapabilities { + pub fn map_format(&self, format: wgt::TextureFormat) -> MTLPixelFormat { + use wgt::TextureFormat as Tf; + use MTLPixelFormat as MTL; + match format { + Tf::R8Unorm => MTL::R8Unorm, + Tf::R8Snorm => MTL::R8Snorm, + Tf::R8Uint => MTL::R8Uint, + Tf::R8Sint => MTL::R8Sint, + Tf::R16Uint => MTL::R16Uint, + Tf::R16Sint => MTL::R16Sint, + Tf::R16Unorm => MTL::R16Unorm, + Tf::R16Snorm => MTL::R16Snorm, + Tf::R16Float => MTL::R16Float, + Tf::Rg8Unorm => MTL::RG8Unorm, + Tf::Rg8Snorm => MTL::RG8Snorm, + Tf::Rg8Uint => MTL::RG8Uint, + Tf::Rg8Sint => MTL::RG8Sint, + Tf::Rg16Unorm => MTL::RG16Unorm, + Tf::Rg16Snorm => MTL::RG16Snorm, + Tf::R32Uint => MTL::R32Uint, + Tf::R32Sint => MTL::R32Sint, + Tf::R32Float => MTL::R32Float, + Tf::Rg16Uint => MTL::RG16Uint, + Tf::Rg16Sint => MTL::RG16Sint, + Tf::Rg16Float => MTL::RG16Float, + Tf::Rgba8Unorm => MTL::RGBA8Unorm, + Tf::Rgba8UnormSrgb => MTL::RGBA8Unorm_sRGB, + Tf::Bgra8UnormSrgb => MTL::BGRA8Unorm_sRGB, + Tf::Rgba8Snorm => MTL::RGBA8Snorm, + Tf::Bgra8Unorm => MTL::BGRA8Unorm, + Tf::Rgba8Uint => MTL::RGBA8Uint, + Tf::Rgba8Sint => MTL::RGBA8Sint, + Tf::Rgb10a2Uint => MTL::RGB10A2Uint, + Tf::Rgb10a2Unorm => MTL::RGB10A2Unorm, + Tf::Rg11b10Ufloat => MTL::RG11B10Float, + // Ruint64 textures are emulated on metal + Tf::R64Uint => MTL::RG32Uint, + Tf::Rg32Uint => MTL::RG32Uint, + Tf::Rg32Sint => MTL::RG32Sint, + Tf::Rg32Float => MTL::RG32Float, + Tf::Rgba16Uint => MTL::RGBA16Uint, + Tf::Rgba16Sint => MTL::RGBA16Sint, + Tf::Rgba16Unorm => MTL::RGBA16Unorm, + Tf::Rgba16Snorm => MTL::RGBA16Snorm, + Tf::Rgba16Float => MTL::RGBA16Float, + Tf::Rgba32Uint => MTL::RGBA32Uint, + Tf::Rgba32Sint => MTL::RGBA32Sint, + Tf::Rgba32Float => MTL::RGBA32Float, + Tf::Stencil8 => MTL::Stencil8, + Tf::Depth16Unorm => MTL::Depth16Unorm, + Tf::Depth32Float => MTL::Depth32Float, + Tf::Depth32FloatStencil8 => MTL::Depth32Float_Stencil8, + Tf::Depth24Plus => { + if self.format_depth24_stencil8 { + MTL::Depth24Unorm_Stencil8 + } else { + MTL::Depth32Float + } + } + Tf::Depth24PlusStencil8 => { + if self.format_depth24_stencil8 { + MTL::Depth24Unorm_Stencil8 + } else { + MTL::Depth32Float_Stencil8 + } + } + Tf::NV12 => unreachable!(), + Tf::P010 => unreachable!(), + Tf::Rgb9e5Ufloat => MTL::RGB9E5Float, + Tf::Bc1RgbaUnorm => MTL::BC1_RGBA, + Tf::Bc1RgbaUnormSrgb => MTL::BC1_RGBA_sRGB, + Tf::Bc2RgbaUnorm => MTL::BC2_RGBA, + Tf::Bc2RgbaUnormSrgb => MTL::BC2_RGBA_sRGB, + Tf::Bc3RgbaUnorm => MTL::BC3_RGBA, + Tf::Bc3RgbaUnormSrgb => MTL::BC3_RGBA_sRGB, + Tf::Bc4RUnorm => MTL::BC4_RUnorm, + Tf::Bc4RSnorm => MTL::BC4_RSnorm, + Tf::Bc5RgUnorm => MTL::BC5_RGUnorm, + Tf::Bc5RgSnorm => MTL::BC5_RGSnorm, + Tf::Bc6hRgbFloat => MTL::BC6H_RGBFloat, + Tf::Bc6hRgbUfloat => MTL::BC6H_RGBUfloat, + Tf::Bc7RgbaUnorm => MTL::BC7_RGBAUnorm, + Tf::Bc7RgbaUnormSrgb => MTL::BC7_RGBAUnorm_sRGB, + Tf::Etc2Rgb8Unorm => MTL::ETC2_RGB8, + Tf::Etc2Rgb8UnormSrgb => MTL::ETC2_RGB8_sRGB, + Tf::Etc2Rgb8A1Unorm => MTL::ETC2_RGB8A1, + Tf::Etc2Rgb8A1UnormSrgb => MTL::ETC2_RGB8A1_sRGB, + Tf::Etc2Rgba8Unorm => MTL::EAC_RGBA8, + Tf::Etc2Rgba8UnormSrgb => MTL::EAC_RGBA8_sRGB, + Tf::EacR11Unorm => MTL::EAC_R11Unorm, + Tf::EacR11Snorm => MTL::EAC_R11Snorm, + Tf::EacRg11Unorm => MTL::EAC_RG11Unorm, + Tf::EacRg11Snorm => MTL::EAC_RG11Snorm, + Tf::Astc { block, channel } => match channel { + AstcChannel::Unorm => match block { + AstcBlock::B4x4 => MTL::ASTC_4x4_LDR, + AstcBlock::B5x4 => MTL::ASTC_5x4_LDR, + AstcBlock::B5x5 => MTL::ASTC_5x5_LDR, + AstcBlock::B6x5 => MTL::ASTC_6x5_LDR, + AstcBlock::B6x6 => MTL::ASTC_6x6_LDR, + AstcBlock::B8x5 => MTL::ASTC_8x5_LDR, + AstcBlock::B8x6 => MTL::ASTC_8x6_LDR, + AstcBlock::B8x8 => MTL::ASTC_8x8_LDR, + AstcBlock::B10x5 => MTL::ASTC_10x5_LDR, + AstcBlock::B10x6 => MTL::ASTC_10x6_LDR, + AstcBlock::B10x8 => MTL::ASTC_10x8_LDR, + AstcBlock::B10x10 => MTL::ASTC_10x10_LDR, + AstcBlock::B12x10 => MTL::ASTC_12x10_LDR, + AstcBlock::B12x12 => MTL::ASTC_12x12_LDR, + }, + AstcChannel::UnormSrgb => match block { + AstcBlock::B4x4 => MTL::ASTC_4x4_sRGB, + AstcBlock::B5x4 => MTL::ASTC_5x4_sRGB, + AstcBlock::B5x5 => MTL::ASTC_5x5_sRGB, + AstcBlock::B6x5 => MTL::ASTC_6x5_sRGB, + AstcBlock::B6x6 => MTL::ASTC_6x6_sRGB, + AstcBlock::B8x5 => MTL::ASTC_8x5_sRGB, + AstcBlock::B8x6 => MTL::ASTC_8x6_sRGB, + AstcBlock::B8x8 => MTL::ASTC_8x8_sRGB, + AstcBlock::B10x5 => MTL::ASTC_10x5_sRGB, + AstcBlock::B10x6 => MTL::ASTC_10x6_sRGB, + AstcBlock::B10x8 => MTL::ASTC_10x8_sRGB, + AstcBlock::B10x10 => MTL::ASTC_10x10_sRGB, + AstcBlock::B12x10 => MTL::ASTC_12x10_sRGB, + AstcBlock::B12x12 => MTL::ASTC_12x12_sRGB, + }, + AstcChannel::Hdr => match block { + AstcBlock::B4x4 => MTL::ASTC_4x4_HDR, + AstcBlock::B5x4 => MTL::ASTC_5x4_HDR, + AstcBlock::B5x5 => MTL::ASTC_5x5_HDR, + AstcBlock::B6x5 => MTL::ASTC_6x5_HDR, + AstcBlock::B6x6 => MTL::ASTC_6x6_HDR, + AstcBlock::B8x5 => MTL::ASTC_8x5_HDR, + AstcBlock::B8x6 => MTL::ASTC_8x6_HDR, + AstcBlock::B8x8 => MTL::ASTC_8x8_HDR, + AstcBlock::B10x5 => MTL::ASTC_10x5_HDR, + AstcBlock::B10x6 => MTL::ASTC_10x6_HDR, + AstcBlock::B10x8 => MTL::ASTC_10x8_HDR, + AstcBlock::B10x10 => MTL::ASTC_10x10_HDR, + AstcBlock::B12x10 => MTL::ASTC_12x10_HDR, + AstcBlock::B12x12 => MTL::ASTC_12x12_HDR, + }, + }, + } + } + + pub fn map_view_format( + &self, + format: wgt::TextureFormat, + aspects: crate::FormatAspects, + ) -> MTLPixelFormat { + use crate::FormatAspects as Fa; + use wgt::TextureFormat as Tf; + use MTLPixelFormat as MTL; + match (format, aspects) { + // map combined depth-stencil format to their stencil-only format + // see https://developer.apple.com/library/archive/documentation/Miscellaneous/Conceptual/MetalProgrammingGuide/WhatsNewiniOS10tvOS10andOSX1012/WhatsNewiniOS10tvOS10andOSX1012.html#//apple_ref/doc/uid/TP40014221-CH14-DontLinkElementID_77 + (Tf::Depth24PlusStencil8, Fa::STENCIL) => { + if self.format_depth24_stencil8 { + MTL::X24_Stencil8 + } else { + MTL::X32_Stencil8 + } + } + (Tf::Depth32FloatStencil8, Fa::STENCIL) => MTL::X32_Stencil8, + + _ => self.map_format(format), + } + } +} + +impl super::PrivateDisabilities { + pub fn new(device: &ProtocolObject<dyn MTLDevice>) -> Self { + let is_intel = device.name().to_string().starts_with("Intel"); + Self { + broken_viewport_near_depth: is_intel + && !device.supportsFeatureSet(MTLFeatureSet::macOS_GPUFamily1_v4), + broken_layered_clear_image: is_intel, + } + } +} + +impl super::OsType { + fn new(version: NSOperatingSystemVersion, device: &ProtocolObject<dyn MTLDevice>) -> Self { + // Metal was first introduced in OS X 10.11 and iOS 8. The current version number of visionOS is 1.0.0. Additionally, + // on the Simulator, Apple only provides the Apple2 GPU capability, and the Apple2+ GPU capability covers the capabilities of Apple2. + // Therefore, the following conditions can be used to determine if it is visionOS. + // https://developer.apple.com/documentation/metal/developing_metal_apps_that_run_in_simulator + let os_is_vision = version.majorVersion < 8 && device.supportsFamily(MTLGPUFamily::Apple2); + let os_is_mac = device.supportsFeatureSet(MTLFeatureSet::macOS_GPUFamily1_v1); + let os_is_tvos = device.supportsFeatureSet(MTLFeatureSet::tvOS_GPUFamily1_v1); + if os_is_vision { + Self::VisionOs + } else if os_is_mac { + Self::Macos + } else if os_is_tvos { + Self::Tvos + } else { + Self::Ios + } + } +} diff --git a/app/vendor/rune/vendor/wgpu-hal/src/metal/command.rs b/app/vendor/rune/vendor/wgpu-hal/src/metal/command.rs new file mode 100644 index 0000000..ba41a63 --- /dev/null +++ b/app/vendor/rune/vendor/wgpu-hal/src/metal/command.rs @@ -0,0 +1,1979 @@ +use objc2::{ + rc::{autoreleasepool, Retained}, + runtime::ProtocolObject, +}; +use objc2_foundation::{NSRange, NSString, NSUInteger}; +use objc2_metal::{ + MTLAccelerationStructure, MTLAccelerationStructureCommandEncoder, MTLBlitCommandEncoder, + MTLBlitPassDescriptor, MTLBuffer, MTLCommandBuffer, MTLCommandBufferStatus, MTLCommandEncoder, + MTLCommandQueue, MTLComputeCommandEncoder, MTLComputePassDescriptor, MTLCounterDontSample, + MTLDevice, MTLLoadAction, MTLPrimitiveType, MTLRenderCommandEncoder, MTLRenderPassDescriptor, + MTLResidencySet, MTLResidencySetDescriptor, MTLSamplerState, MTLScissorRect, MTLSize, + MTLStoreAction, MTLTexture, MTLVertexAmplificationViewMapping, MTLViewport, + MTLVisibilityResultMode, +}; + +use super::{ + adapter::{self, MAX_BUFFERS}, + conv, TimestampQuerySupport, +}; +use crate::CommandEncoder as _; +use alloc::{ + borrow::{Cow, ToOwned as _}, + sync::Arc, + vec::Vec, +}; +use core::{ops::Range, ptr::NonNull, sync::atomic}; +use smallvec::SmallVec; + +// has to match `Temp::binding_sizes` +const WORD_SIZE: usize = 4; + +impl Default for super::CommandState { + fn default() -> Self { + Self { + blit: None, + acceleration_structure_builder: None, + render: None, + compute: None, + raw_primitive_type: MTLPrimitiveType::Point, + index: None, + stage_infos: Default::default(), + storage_buffer_length_map: Default::default(), + vertex_buffer_size_map: Default::default(), + immediates: Vec::new(), + pending_timer_queries: Vec::new(), + } + } +} + +/// Helper for passing encoders to `update_bind_group_state`. +/// +/// Combines [`naga::ShaderStage`] and an encoder of the appropriate type for +/// that stage. +enum Encoder<'e> { + Vertex(&'e ProtocolObject<dyn MTLRenderCommandEncoder>), + Fragment(&'e ProtocolObject<dyn MTLRenderCommandEncoder>), + Task(&'e ProtocolObject<dyn MTLRenderCommandEncoder>), + Mesh(&'e ProtocolObject<dyn MTLRenderCommandEncoder>), + Compute(&'e ProtocolObject<dyn MTLComputeCommandEncoder>), +} + +impl Encoder<'_> { + fn stage(&self) -> naga::ShaderStage { + match self { + Self::Vertex(_) => naga::ShaderStage::Vertex, + Self::Fragment(_) => naga::ShaderStage::Fragment, + Self::Task(_) => naga::ShaderStage::Task, + Self::Mesh(_) => naga::ShaderStage::Mesh, + Self::Compute(_) => naga::ShaderStage::Compute, + } + } + + fn set_buffer( + &self, + buffer: Option<&ProtocolObject<dyn MTLBuffer>>, + offset: NSUInteger, + index: NSUInteger, + ) { + unsafe { + match *self { + Self::Vertex(enc) => enc.setVertexBuffer_offset_atIndex(buffer, offset, index), + Self::Fragment(enc) => enc.setFragmentBuffer_offset_atIndex(buffer, offset, index), + Self::Task(enc) => enc.setObjectBuffer_offset_atIndex(buffer, offset, index), + Self::Mesh(enc) => enc.setMeshBuffer_offset_atIndex(buffer, offset, index), + Self::Compute(enc) => enc.setBuffer_offset_atIndex(buffer, offset, index), + } + } + } + + fn set_acceleration_structure( + &self, + buffer: Option<&ProtocolObject<dyn MTLAccelerationStructure>>, + index: NSUInteger, + ) { + unsafe { + match *self { + Self::Vertex(enc) => { + enc.setVertexAccelerationStructure_atBufferIndex(buffer, index) + } + Self::Fragment(enc) => { + enc.setFragmentAccelerationStructure_atBufferIndex(buffer, index) + } + Self::Task(_) => { + unreachable!("Acceleration structures are not allowed in task shaders") + } + Self::Mesh(_) => { + unreachable!("Acceleration structures are not allowed in mesh shaders") + } + Self::Compute(enc) => enc.setAccelerationStructure_atBufferIndex(buffer, index), + } + } + } + + fn set_bytes(&self, bytes: NonNull<core::ffi::c_void>, length: NSUInteger, index: NSUInteger) { + unsafe { + match *self { + Self::Vertex(enc) => enc.setVertexBytes_length_atIndex(bytes, length, index), + Self::Fragment(enc) => enc.setFragmentBytes_length_atIndex(bytes, length, index), + Self::Task(enc) => enc.setObjectBytes_length_atIndex(bytes, length, index), + Self::Mesh(enc) => enc.setMeshBytes_length_atIndex(bytes, length, index), + Self::Compute(enc) => enc.setBytes_length_atIndex(bytes, length, index), + } + } + } + + fn set_sampler_state( + &self, + state: Option<&ProtocolObject<dyn MTLSamplerState>>, + index: NSUInteger, + ) { + unsafe { + match *self { + Self::Vertex(enc) => enc.setVertexSamplerState_atIndex(state, index), + Self::Fragment(enc) => enc.setFragmentSamplerState_atIndex(state, index), + Self::Task(enc) => enc.setObjectSamplerState_atIndex(state, index), + Self::Mesh(enc) => enc.setMeshSamplerState_atIndex(state, index), + Self::Compute(enc) => enc.setSamplerState_atIndex(state, index), + } + } + } + + fn set_texture(&self, texture: Option<&ProtocolObject<dyn MTLTexture>>, index: NSUInteger) { + unsafe { + match *self { + Self::Vertex(enc) => enc.setVertexTexture_atIndex(texture, index), + Self::Fragment(enc) => enc.setFragmentTexture_atIndex(texture, index), + Self::Task(enc) => enc.setObjectTexture_atIndex(texture, index), + Self::Mesh(enc) => enc.setMeshTexture_atIndex(texture, index), + Self::Compute(enc) => enc.setTexture_atIndex(texture, index), + } + } + } +} + +impl super::CommandEncoder { + pub fn raw_command_buffer(&self) -> Option<&ProtocolObject<dyn MTLCommandBuffer>> { + self.raw_cmd_buf.as_deref() + } + + fn enter_blit(&mut self) -> Retained<ProtocolObject<dyn MTLBlitCommandEncoder>> { + if self.state.blit.is_none() { + self.leave_acceleration_structure_builder(); + debug_assert!(self.state.render.is_none() && self.state.compute.is_none()); + let cmd_buf = self.raw_cmd_buf.as_ref().unwrap(); + + // This code path is currently unused since the written timestamp is always 0. + // We should see if we can get it working again, if not remove the code. + // + // Take care of pending timer queries. + // If we can't use `sample_counters_in_buffer` we have to create a dummy blit encoder! + // + // There is a known bug in Metal where blit encoders won't write timestamps if they don't have a blit operation. + // See https://github.com/gpuweb/gpuweb/issues/2046#issuecomment-1205793680 & https://source.chromium.org/chromium/chromium/src/+/006c4eb70c96229834bbaf271290f40418144cd3:third_party/dawn/src/dawn/native/metal/BackendMTL.mm;l=350 + // + // To make things worse: + // * what counts as a blit operation is a bit unclear, experimenting seemed to indicate that resolve_counters doesn't count. + // * in some cases (when?) using `set_start_of_encoder_sample_index` doesn't work, so we have to use `set_end_of_encoder_sample_index` instead + // + // All this means that pretty much the only *reliable* thing as of writing is to: + // * create a dummy blit encoder using set_end_of_encoder_sample_index + // * do a dummy write that is known to be not optimized out. + // * close the encoder since we used set_end_of_encoder_sample_index and don't want to get any extra stuff in there. + // * create another encoder for whatever we actually had in mind. + let supports_sample_counters_in_buffer = self + .shared + .private_caps + .timestamp_query_support + .contains(TimestampQuerySupport::ON_BLIT_ENCODER); + + if !self.state.pending_timer_queries.is_empty() && !supports_sample_counters_in_buffer { + autoreleasepool(|_| { + let descriptor = MTLBlitPassDescriptor::new(); + let mut last_query = None; + for (i, (set, index)) in self.state.pending_timer_queries.drain(..).enumerate() + { + let sba_descriptor = unsafe { + descriptor + .sampleBufferAttachments() + .objectAtIndexedSubscript(i) + }; + sba_descriptor + .setSampleBuffer(Some(set.counter_sample_buffer.as_ref().unwrap())); + + // Here be dragons: + // As mentioned above, for some reasons using the start of the encoder won't yield any results sometimes! + unsafe { + sba_descriptor.setStartOfEncoderSampleIndex(MTLCounterDontSample) + }; + unsafe { sba_descriptor.setEndOfEncoderSampleIndex(index as _) }; + + last_query = Some((set, index)); + } + let encoder = cmd_buf + .blitCommandEncoderWithDescriptor(&descriptor) + .unwrap(); + + // As explained above, we need to do some write: + // Conveniently, we have a buffer with every query set, that we can use for this for a dummy write, + // since we know that it is going to be overwritten again on timer resolve and HAL doesn't define its state before that. + let raw_range = NSRange { + location: last_query.as_ref().unwrap().1 as usize + * crate::QUERY_SIZE as usize, + length: 1, + }; + encoder.fillBuffer_range_value( + &last_query.as_ref().unwrap().0.raw_buffer, + raw_range, + 255, // Don't write 0, so it's easier to identify if something went wrong. + ); + + encoder.endEncoding(); + }); + } + + autoreleasepool(|_| { + self.state.blit = Some(cmd_buf.blitCommandEncoder().unwrap()); + }); + + #[allow(clippy::panicking_unwrap, reason = "false positive (fixed by 1.93.1)")] + let encoder = self.state.blit.as_ref().unwrap(); + + // UNTESTED: + // If the above described issue with empty blit encoder applies to `sample_counters_in_buffer` as well, we should use the same workaround instead! + for (set, index) in self.state.pending_timer_queries.drain(..) { + debug_assert!(supports_sample_counters_in_buffer); + unsafe { + encoder.sampleCountersInBuffer_atSampleIndex_withBarrier( + set.counter_sample_buffer.as_ref().unwrap(), + index as _, + true, + ) + }; + } + } + self.state.blit.as_ref().unwrap().clone() + } + + pub(super) fn leave_blit(&mut self) { + if let Some(encoder) = self.state.blit.take() { + encoder.endEncoding(); + } + } + + fn enter_acceleration_structure_builder( + &mut self, + ) -> Retained<ProtocolObject<dyn MTLAccelerationStructureCommandEncoder>> { + if self.state.acceleration_structure_builder.is_none() { + self.leave_blit(); + debug_assert!( + self.state.render.is_none() + && self.state.compute.is_none() + && self.state.blit.is_none() + ); + let cmd_buf = self.raw_cmd_buf.as_ref().unwrap(); + autoreleasepool(|_| { + self.state.acceleration_structure_builder = + cmd_buf.accelerationStructureCommandEncoder().to_owned(); + }); + } + self.state.acceleration_structure_builder.clone().unwrap() + } + + pub(super) fn leave_acceleration_structure_builder(&mut self) { + if let Some(encoder) = self.state.acceleration_structure_builder.take() { + encoder.endEncoding(); + } + } + + fn active_encoder(&mut self) -> Option<&ProtocolObject<dyn MTLCommandEncoder>> { + if let Some(ref encoder) = self.state.render { + Some(ProtocolObject::from_ref(&**encoder)) + } else if let Some(ref encoder) = self.state.acceleration_structure_builder { + Some(ProtocolObject::from_ref(&**encoder)) + } else if let Some(ref encoder) = self.state.compute { + Some(ProtocolObject::from_ref(&**encoder)) + } else if let Some(ref encoder) = self.state.blit { + Some(ProtocolObject::from_ref(&**encoder)) + } else { + None + } + } + + fn begin_pass(&mut self) { + self.state.reset(); + self.leave_blit(); + self.leave_acceleration_structure_builder(); + } + + /// Updates the bindings for a single shader stage, called in `set_bind_group`. + fn update_bind_group_state( + &mut self, + encoder: Encoder<'_>, + index_base: super::ResourceData<u32>, + bg_info: &super::BindGroupLayoutInfo, + dynamic_offsets: &[wgt::DynamicOffset], + group_index: u32, + group: &super::BindGroup, + ) { + use naga::ShaderStage as S; + let resource_indices = match encoder.stage() { + S::Vertex => &bg_info.base_resource_indices.vs, + S::Fragment => &bg_info.base_resource_indices.fs, + S::Task => &bg_info.base_resource_indices.ts, + S::Mesh => &bg_info.base_resource_indices.ms, + S::Compute => &bg_info.base_resource_indices.cs, + S::RayGeneration | S::AnyHit | S::ClosestHit | S::Miss => unimplemented!(), + }; + let buffers = match encoder.stage() { + S::Vertex => group.counters.vs.buffers, + S::Fragment => group.counters.fs.buffers, + S::Task => group.counters.ts.buffers, + S::Mesh => group.counters.ms.buffers, + S::Compute => group.counters.cs.buffers, + S::RayGeneration | S::AnyHit | S::ClosestHit | S::Miss => unimplemented!(), + }; + let mut changes_sizes_buffer = false; + for index in 0..buffers { + let res = &group.buffers[(index_base.buffers + index) as usize]; + match res { + super::BufferLikeResource::Buffer { + ptr, + mut offset, + dynamic_index, + binding_size, + binding_location, + } => { + let buffer = Some(unsafe { ptr.as_ref() }); + if let Some(dyn_index) = dynamic_index { + offset += dynamic_offsets[*dyn_index as usize] as wgt::BufferAddress; + } + let index = (resource_indices.buffers + index) as usize; + encoder.set_buffer(buffer, offset as usize, index); + let br = naga::ResourceBinding { + group: group_index, + binding: *binding_location, + }; + if let Some(size) = binding_size { + self.state.storage_buffer_length_map.insert((br, 0), *size); + changes_sizes_buffer = true; + } + } + super::BufferLikeResource::StorageBindingArray { + ptr, + array_element_sizes, + binding_location, + } => { + let buffer = Some(unsafe { ptr.as_ref() }); + let index = (resource_indices.buffers + index) as usize; + encoder.set_buffer(buffer, 0, index); + let br = naga::ResourceBinding { + group: group_index, + binding: *binding_location, + }; + for &(array_idx, size) in array_element_sizes { + self.state + .storage_buffer_length_map + .insert((br, array_idx), size); + changes_sizes_buffer = true; + } + } + super::BufferLikeResource::AccelerationStructure(ptr) => { + let buffer = Some(unsafe { ptr.as_ref() }); + let index = (resource_indices.buffers + index) as usize; + encoder.set_acceleration_structure(buffer, index); + } + } + } + if changes_sizes_buffer { + if let Some((index, sizes)) = self + .state + .make_sizes_buffer_update(encoder.stage(), &mut self.temp.binding_sizes) + { + let bytes_ptr = NonNull::new(sizes.as_ptr().cast_mut().cast()).unwrap(); + let length = sizes.len() * WORD_SIZE; + let index = index as _; + encoder.set_bytes(bytes_ptr, length, index); + } + } + let samplers = match encoder.stage() { + S::Vertex => group.counters.vs.samplers, + S::Fragment => group.counters.fs.samplers, + S::Task => group.counters.ts.samplers, + S::Mesh => group.counters.ms.samplers, + S::Compute => group.counters.cs.samplers, + S::RayGeneration | S::AnyHit | S::ClosestHit | S::Miss => unimplemented!(), + }; + for index in 0..samplers { + let res = group.samplers[(index_base.samplers + index) as usize]; + let index = (resource_indices.samplers + index) as usize; + let state = Some(unsafe { res.as_ref() }); + encoder.set_sampler_state(state, index); + } + + let textures = match encoder.stage() { + S::Vertex => group.counters.vs.textures, + S::Fragment => group.counters.fs.textures, + S::Task => group.counters.ts.textures, + S::Mesh => group.counters.ms.textures, + S::Compute => group.counters.cs.textures, + S::RayGeneration | S::AnyHit | S::ClosestHit | S::Miss => unimplemented!(), + }; + for index in 0..textures { + let res = group.textures[(index_base.textures + index) as usize]; + let index = (resource_indices.textures + index) as usize; + let texture = Some(unsafe { res.as_ref() }); + encoder.set_texture(texture, index); + } + } +} + +impl super::CommandState { + fn reset(&mut self) { + self.storage_buffer_length_map.clear(); + self.vertex_buffer_size_map.clear(); + self.stage_infos.vs.clear(); + self.stage_infos.fs.clear(); + self.stage_infos.cs.clear(); + self.stage_infos.ts.clear(); + self.stage_infos.ms.clear(); + self.immediates.clear(); + } + + fn make_sizes_buffer_update<'a>( + &self, + stage: naga::ShaderStage, + result_sizes: &'a mut Vec<u32>, + ) -> Option<(u32, &'a [u32])> { + let stage_info = &self.stage_infos[stage]; + let slot = stage_info.sizes_slot?; + + result_sizes.clear(); + result_sizes.extend(stage_info.sized_bindings.iter().map(|(br, array_idx)| { + self.storage_buffer_length_map + .get(&(*br, *array_idx)) + .map(|size| u32::try_from(size.get()).unwrap_or(u32::MAX)) + .unwrap_or_default() + })); + + // Extend with the sizes of the mapped vertex buffers, in the order + // they were added to the map. + result_sizes.extend(stage_info.vertex_buffer_mappings.iter().map(|vbm| { + self.vertex_buffer_size_map + .get(&vbm.id) + .map(|size| u32::try_from(size.get()).unwrap_or(u32::MAX)) + .unwrap_or_default() + })); + + if !result_sizes.is_empty() { + Some((slot as _, result_sizes)) + } else { + None + } + } +} + +impl crate::CommandEncoder for super::CommandEncoder { + type A = super::Api; + + unsafe fn begin_encoding(&mut self, label: crate::Label) -> Result<(), crate::DeviceError> { + let queue = &self.queue_shared.raw; + let retain_references = self.shared.settings.retain_command_buffer_references; + let relay = self.queue_shared.relay.get(); + + // Guard against exhausting Metal's command buffer budget. Use the hard + // limit (`MAX_COMMAND_BUFFERS`) so we fail before Metal can hang inside + // `new_command_buffer`. + let previous = self + .queue_shared + .command_buffer_created_not_submitted + .fetch_add(1, atomic::Ordering::AcqRel); + if previous >= adapter::MAX_COMMAND_BUFFERS { + let current = previous + 1; + log::warn!( + "metal: refusing to create new command buffer; {current} outstanding command \ + buffers exceeds the limit of {}. Treating this as device lost. \ + Ensure command encoders are submitted or dropped rather than kept alive \ + to avoid exhausting Metal's command buffer budget.", + adapter::MAX_COMMAND_BUFFERS + ); + return Err(crate::DeviceError::Lost); + } + + let raw = autoreleasepool(move |_| { + let cmd_buf_ref = if retain_references { + queue.commandBuffer() + } else { + queue.commandBufferWithUnretainedReferences() + } + .unwrap(); + if let Some(label) = label { + cmd_buf_ref.setLabel(Some(&NSString::from_str(label))); + } + // If strict event sync is enabled on this queue, gate the + // CB on the relay event at the value the next submit will + // signal. The CB pauses at the start until the relay fires. + if let Some(relay) = relay { + let expected = relay.next_release_value.load(atomic::Ordering::Acquire); + cmd_buf_ref.encodeWaitForEvent_value(relay.event.as_ref(), expected); + } + cmd_buf_ref.to_owned() + }); + + // Queries should either be closed out, or cleared in `discard_encoding`. + // This assertion is here mainly to facilitate comparison with the other + // backends, which clear in `begin_encoding` rather than `discard_encoding`. + debug_assert!(self.state.pending_timer_queries.is_empty()); + + self.raw_cmd_buf = Some(raw); + + Ok(()) + } + + unsafe fn discard_encoding(&mut self) { + self.leave_blit(); + self.leave_acceleration_structure_builder(); + // when discarding, we don't have a guarantee that + // everything is in a good state, so check carefully + if let Some(encoder) = self.state.render.take() { + encoder.endEncoding(); + } + if let Some(encoder) = self.state.compute.take() { + encoder.endEncoding(); + } + self.state.pending_timer_queries.clear(); + let had_command_buffer = self.raw_cmd_buf.is_some(); + // Clear the Option first so the underlying `metal::CommandBuffer` is + // dropped before we update the counter. + self.raw_cmd_buf = None; + if had_command_buffer { + self.queue_shared + .command_buffer_created_not_submitted + .fetch_sub(1, atomic::Ordering::AcqRel); + } + } + + unsafe fn end_encoding(&mut self) -> Result<super::CommandBuffer, crate::DeviceError> { + // Handle pending timer query if any. + if !self.state.pending_timer_queries.is_empty() { + self.leave_blit(); + self.enter_blit(); + } + + self.leave_blit(); + self.leave_acceleration_structure_builder(); + debug_assert!(self.state.render.is_none()); + debug_assert!(self.state.compute.is_none()); + debug_assert!(self.state.pending_timer_queries.is_empty()); + + Ok(super::CommandBuffer { + raw: self.raw_cmd_buf.take().unwrap(), + queue_shared: Arc::clone(&self.queue_shared), + }) + } + + unsafe fn reset_all<I>(&mut self, _cmd_bufs: I) + where + I: Iterator<Item = super::CommandBuffer>, + { + //do nothing + } + + unsafe fn transition_buffers<'a, T>(&mut self, _barriers: T) + where + T: Iterator<Item = crate::BufferBarrier<'a, super::Buffer>>, + { + } + + unsafe fn transition_textures<'a, T>(&mut self, _barriers: T) + where + T: Iterator<Item = crate::TextureBarrier<'a, super::Texture>>, + { + } + + unsafe fn clear_buffer(&mut self, buffer: &super::Buffer, range: crate::MemoryRange) { + let encoder = self.enter_blit(); + encoder.fillBuffer_range_value(&buffer.raw, conv::map_range(&range), 0); + } + + unsafe fn copy_buffer_to_buffer<T>( + &mut self, + src: &super::Buffer, + dst: &super::Buffer, + regions: T, + ) where + T: Iterator<Item = crate::BufferCopy>, + { + let encoder = self.enter_blit(); + for copy in regions { + unsafe { + encoder.copyFromBuffer_sourceOffset_toBuffer_destinationOffset_size( + &src.raw, + copy.src_offset as usize, + &dst.raw, + copy.dst_offset as usize, + copy.size.get() as usize, + ) + }; + } + } + + unsafe fn copy_texture_to_texture<T>( + &mut self, + src: &super::Texture, + _src_usage: wgt::TextureUses, + dst: &super::Texture, + regions: T, + ) where + T: Iterator<Item = crate::TextureCopy>, + { + let dst_texture = if src.format != dst.format { + let raw_format = self + .shared + .private_texture_format_caps + .map_format(src.format); + Cow::Owned(autoreleasepool(|_| { + dst.raw.newTextureViewWithPixelFormat(raw_format).unwrap() + })) + } else { + Cow::Borrowed(&dst.raw) + }; + let encoder = self.enter_blit(); + for copy in regions { + let src_origin = conv::map_origin(&copy.src_base.origin); + let dst_origin = conv::map_origin(&copy.dst_base.origin); + // no clamping is done: Metal expects physical sizes here + let extent = conv::map_copy_extent(&copy.size); + unsafe { + encoder.copyFromTexture_sourceSlice_sourceLevel_sourceOrigin_sourceSize_toTexture_destinationSlice_destinationLevel_destinationOrigin( + &src.raw, + copy.src_base.array_layer as usize, + copy.src_base.mip_level as usize, + src_origin, + extent, + &dst_texture, + copy.dst_base.array_layer as usize, + copy.dst_base.mip_level as usize, + dst_origin, + ) + }; + } + } + + unsafe fn copy_buffer_to_texture<T>( + &mut self, + src: &super::Buffer, + dst: &super::Texture, + regions: T, + ) where + T: Iterator<Item = crate::BufferTextureCopy>, + { + let encoder = self.enter_blit(); + for copy in regions { + let dst_origin = conv::map_origin(&copy.texture_base.origin); + // Metal expects buffer-texture copies in virtual sizes + let extent = copy + .texture_base + .max_copy_size(&dst.copy_size) + .min(&copy.size); + let bytes_per_row = copy.buffer_layout.bytes_per_row.unwrap_or(0) as u64; + let image_byte_stride = if extent.depth > 1 { + copy.buffer_layout + .rows_per_image + .map_or(0, |v| v as u64 * bytes_per_row) + } else { + // Don't pass a stride when updating a single layer, otherwise metal validation + // fails when updating a subset of the image due to the stride being larger than + // the amount of data to copy. + 0 + }; + unsafe { + encoder.copyFromBuffer_sourceOffset_sourceBytesPerRow_sourceBytesPerImage_sourceSize_toTexture_destinationSlice_destinationLevel_destinationOrigin_options( + &src.raw, + copy.buffer_layout.offset as usize, + bytes_per_row as usize, + image_byte_stride as usize, + conv::map_copy_extent(&extent), + &dst.raw, + copy.texture_base.array_layer as usize, + copy.texture_base.mip_level as usize, + dst_origin, + conv::get_blit_option(dst.format, copy.texture_base.aspect), + ) + }; + } + } + + unsafe fn copy_texture_to_buffer<T>( + &mut self, + src: &super::Texture, + _src_usage: wgt::TextureUses, + dst: &super::Buffer, + regions: T, + ) where + T: Iterator<Item = crate::BufferTextureCopy>, + { + let encoder = self.enter_blit(); + for copy in regions { + let src_origin = conv::map_origin(&copy.texture_base.origin); + // Metal expects texture-buffer copies in virtual sizes + let extent = copy + .texture_base + .max_copy_size(&src.copy_size) + .min(&copy.size); + let bytes_per_row = copy.buffer_layout.bytes_per_row.unwrap_or(0) as u64; + let bytes_per_image = copy + .buffer_layout + .rows_per_image + .map_or(0, |v| v as u64 * bytes_per_row); + unsafe { + encoder.copyFromTexture_sourceSlice_sourceLevel_sourceOrigin_sourceSize_toBuffer_destinationOffset_destinationBytesPerRow_destinationBytesPerImage_options( + &src.raw, + copy.texture_base.array_layer as usize, + copy.texture_base.mip_level as usize, + src_origin, + conv::map_copy_extent(&extent), + &dst.raw, + copy.buffer_layout.offset as usize, + bytes_per_row as usize, + bytes_per_image as usize, + conv::get_blit_option(src.format, copy.texture_base.aspect), + ) + }; + } + } + + unsafe fn copy_acceleration_structure_to_acceleration_structure( + &mut self, + src: &super::AccelerationStructure, + dst: &super::AccelerationStructure, + copy: wgt::AccelerationStructureCopy, + ) { + let command_encoder = self.enter_acceleration_structure_builder(); + match copy { + wgt::AccelerationStructureCopy::Clone => unsafe { + command_encoder + .copyAccelerationStructure_toAccelerationStructure(&src.raw, &dst.raw); + }, + wgt::AccelerationStructureCopy::Compact => { + command_encoder.copyAndCompactAccelerationStructure_toAccelerationStructure( + &src.raw, &dst.raw, + ); + } + }; + } + + unsafe fn begin_query(&mut self, set: &super::QuerySet, index: u32) { + match set.ty { + wgt::QueryType::Occlusion => { + self.state + .render + .as_ref() + .unwrap() + .setVisibilityResultMode_offset( + MTLVisibilityResultMode::Boolean, + index as usize * crate::QUERY_SIZE as usize, + ); + } + _ => {} + } + } + unsafe fn end_query(&mut self, set: &super::QuerySet, index: u32) { + match set.ty { + wgt::QueryType::Occlusion => { + self.state + .render + .as_ref() + .unwrap() + .setVisibilityResultMode_offset( + MTLVisibilityResultMode::Disabled, + index as usize * crate::QUERY_SIZE as usize, + ); + } + _ => {} + } + } + unsafe fn write_timestamp(&mut self, set: &super::QuerySet, index: u32) { + let support = self.shared.private_caps.timestamp_query_support; + debug_assert!( + support.contains(TimestampQuerySupport::STAGE_BOUNDARIES), + "Timestamp queries are not supported" + ); + let sample_buffer = set.counter_sample_buffer.as_ref().unwrap(); + let with_barrier = true; + + // Try to use an existing encoder for timestamp query if possible. + // This works only if it's supported for the active encoder. + if let (true, Some(encoder)) = ( + support.contains(TimestampQuerySupport::ON_BLIT_ENCODER), + self.state.blit.as_ref(), + ) { + unsafe { + encoder.sampleCountersInBuffer_atSampleIndex_withBarrier( + sample_buffer, + index as _, + with_barrier, + ) + }; + } else if let (true, Some(encoder)) = ( + support.contains(TimestampQuerySupport::ON_RENDER_ENCODER), + self.state.render.as_ref(), + ) { + unsafe { + encoder.sampleCountersInBuffer_atSampleIndex_withBarrier( + sample_buffer, + index as _, + with_barrier, + ) + }; + } else if let (true, Some(encoder)) = ( + support.contains(TimestampQuerySupport::ON_COMPUTE_ENCODER), + self.state.compute.as_ref(), + ) { + unsafe { + encoder.sampleCountersInBuffer_atSampleIndex_withBarrier( + sample_buffer, + index as _, + with_barrier, + ) + }; + } else { + // If we're here it means we either have no encoder open, or it's not supported to sample within them. + // If this happens with render/compute open, this is an invalid usage! + debug_assert!(self.state.render.is_none() && self.state.compute.is_none()); + + // But otherwise it means we'll put defer this to the next created encoder. + self.state.pending_timer_queries.push((set.clone(), index)); + + // Ensure we didn't already have a blit open. + self.leave_blit(); + }; + } + + unsafe fn reset_queries(&mut self, _set: &super::QuerySet, _range: Range<u32>) {} + + unsafe fn copy_query_results( + &mut self, + set: &super::QuerySet, + range: Range<u32>, + buffer: &super::Buffer, + offset: wgt::BufferAddress, + _: wgt::BufferSize, // Metal doesn't support queries that are bigger than a single element are not supported + ) { + let encoder = self.enter_blit(); + match set.ty { + wgt::QueryType::Occlusion => { + let size = (range.end - range.start) as u64 * crate::QUERY_SIZE; + unsafe { + encoder.copyFromBuffer_sourceOffset_toBuffer_destinationOffset_size( + &set.raw_buffer, + range.start as usize * crate::QUERY_SIZE as usize, + &buffer.raw, + offset as usize, + size as usize, + ) + }; + } + wgt::QueryType::Timestamp => { + unsafe { + encoder.resolveCounters_inRange_destinationBuffer_destinationOffset( + set.counter_sample_buffer.as_ref().unwrap(), + NSRange::new(range.start as usize, (range.end - range.start) as usize), + &buffer.raw, + offset as usize, + ) + }; + } + wgt::QueryType::PipelineStatistics(_) => todo!(), + } + } + + // render + + unsafe fn begin_render_pass( + &mut self, + desc: &crate::RenderPassDescriptor<super::QuerySet, super::TextureView>, + ) -> Result<(), crate::DeviceError> { + self.begin_pass(); + self.state.index = None; + + assert!(self.state.blit.is_none()); + assert!(self.state.compute.is_none()); + assert!(self.state.render.is_none()); + + autoreleasepool(|_| { + let descriptor = MTLRenderPassDescriptor::new(); + + for (i, at) in desc.color_attachments.iter().enumerate() { + if let Some(at) = at.as_ref() { + let at_descriptor = + unsafe { descriptor.colorAttachments().objectAtIndexedSubscript(i) }; + at_descriptor.setTexture(Some(&at.target.view.raw)); + if let Some(depth_slice) = at.depth_slice { + at_descriptor.setDepthPlane(depth_slice as usize); + } + if let Some(ref resolve) = at.resolve_target { + //Note: the selection of levels and slices is already handled by `TextureView` + at_descriptor.setResolveTexture(Some(&resolve.view.raw)); + } + let load_action = if at.ops.contains(crate::AttachmentOps::LOAD) { + MTLLoadAction::Load + } else if at.ops.contains(crate::AttachmentOps::LOAD_DONT_CARE) { + MTLLoadAction::DontCare + } else if at.ops.contains(crate::AttachmentOps::LOAD_CLEAR) { + at_descriptor.setClearColor(conv::map_clear_color(&at.clear_value)); + MTLLoadAction::Clear + } else { + unreachable!() + }; + let store_action = conv::map_store_action( + at.ops.contains(crate::AttachmentOps::STORE), + at.resolve_target.is_some(), + ); + at_descriptor.setLoadAction(load_action); + at_descriptor.setStoreAction(store_action); + } + } + + if let Some(ref at) = desc.depth_stencil_attachment { + if at.target.view.aspects.contains(crate::FormatAspects::DEPTH) { + let at_descriptor = descriptor.depthAttachment(); + at_descriptor.setTexture(Some(&at.target.view.raw)); + + let load_action = if at.depth_ops.contains(crate::AttachmentOps::LOAD) { + MTLLoadAction::Load + } else if at.depth_ops.contains(crate::AttachmentOps::LOAD_DONT_CARE) { + MTLLoadAction::DontCare + } else if at.depth_ops.contains(crate::AttachmentOps::LOAD_CLEAR) { + at_descriptor.setClearDepth(at.clear_value.0 as f64); + MTLLoadAction::Clear + } else { + unreachable!(); + }; + let store_action = if at.depth_ops.contains(crate::AttachmentOps::STORE) { + MTLStoreAction::Store + } else { + MTLStoreAction::DontCare + }; + at_descriptor.setLoadAction(load_action); + at_descriptor.setStoreAction(store_action); + } + if at + .target + .view + .aspects + .contains(crate::FormatAspects::STENCIL) + { + let at_descriptor = descriptor.stencilAttachment(); + at_descriptor.setTexture(Some(&at.target.view.raw)); + + let load_action = if at.stencil_ops.contains(crate::AttachmentOps::LOAD) { + MTLLoadAction::Load + } else if at + .stencil_ops + .contains(crate::AttachmentOps::LOAD_DONT_CARE) + { + MTLLoadAction::DontCare + } else if at.stencil_ops.contains(crate::AttachmentOps::LOAD_CLEAR) { + at_descriptor.setClearStencil(at.clear_value.1); + MTLLoadAction::Clear + } else { + unreachable!() + }; + let store_action = if at.stencil_ops.contains(crate::AttachmentOps::STORE) { + MTLStoreAction::Store + } else { + MTLStoreAction::DontCare + }; + at_descriptor.setLoadAction(load_action); + at_descriptor.setStoreAction(store_action); + } + } + + let mut sba_index = 0; + let mut next_sba_descriptor = || { + let sba_descriptor = unsafe { + descriptor + .sampleBufferAttachments() + .objectAtIndexedSubscript(sba_index) + }; + + unsafe { sba_descriptor.setEndOfVertexSampleIndex(MTLCounterDontSample) }; + unsafe { sba_descriptor.setStartOfFragmentSampleIndex(MTLCounterDontSample) }; + + sba_index += 1; + sba_descriptor + }; + + for (set, index) in self.state.pending_timer_queries.drain(..) { + let sba_descriptor = next_sba_descriptor(); + sba_descriptor.setSampleBuffer(Some(set.counter_sample_buffer.as_ref().unwrap())); + unsafe { sba_descriptor.setStartOfVertexSampleIndex(index as _) }; + unsafe { sba_descriptor.setEndOfFragmentSampleIndex(MTLCounterDontSample) }; + } + + if let Some(ref timestamp_writes) = desc.timestamp_writes { + let sba_descriptor = next_sba_descriptor(); + sba_descriptor.setSampleBuffer(Some( + timestamp_writes + .query_set + .counter_sample_buffer + .as_ref() + .unwrap(), + )); + + unsafe { + sba_descriptor.setStartOfVertexSampleIndex( + timestamp_writes + .beginning_of_pass_write_index + .map_or(MTLCounterDontSample, |i| i as _), + ) + }; + unsafe { + sba_descriptor.setEndOfFragmentSampleIndex( + timestamp_writes + .end_of_pass_write_index + .map_or(MTLCounterDontSample, |i| i as _), + ) + }; + } + + if let Some(occlusion_query_set) = desc.occlusion_query_set { + descriptor.setVisibilityResultBuffer(Some(occlusion_query_set.raw_buffer.as_ref())) + } + // This strangely isn't mentioned in https://developer.apple.com/documentation/metal/improving-rendering-performance-with-vertex-amplification. + // The docs for [`renderTargetArrayLength`](https://developer.apple.com/documentation/metal/mtlrenderpassdescriptor/rendertargetarraylength) + // also say "The number of active layers that all attachments must have for layered rendering," implying it is only for layered rendering. + // However, when I don't set this, I get undefined behavior in nonzero layers, and all non-apple examples of vertex amplification set it. + // So this is just one of those undocumented requirements. + if let Some(mv) = desc.multiview_mask { + descriptor.setRenderTargetArrayLength(32 - mv.leading_zeros() as usize); + } + let raw = self.raw_cmd_buf.as_ref().unwrap(); + let encoder = raw.renderCommandEncoderWithDescriptor(&descriptor).unwrap(); + if let Some(mv) = desc.multiview_mask { + // Most likely the API just wasn't thought about enough. It's not like they ever allow you + // to use enough views to overflow a 32-bit bitmask. + let mv = mv.get(); + let msb = 32 - mv.leading_zeros(); + let mut maps: SmallVec<[MTLVertexAmplificationViewMapping; 32]> = SmallVec::new(); + for i in 0..msb { + if (mv & (1 << i)) != 0 { + maps.push(MTLVertexAmplificationViewMapping { + renderTargetArrayIndexOffset: i, + viewportArrayIndexOffset: i, + }); + } + } + unsafe { + encoder.setVertexAmplificationCount_viewMappings( + mv.count_ones() as usize, + maps.as_ptr(), + ) + }; + } + if let Some(label) = desc.label { + encoder.setLabel(Some(&NSString::from_str(label))); + } + self.state.render = Some(encoder); + }); + + Ok(()) + } + + unsafe fn end_render_pass(&mut self) { + self.state.render.take().unwrap().endEncoding(); + } + + unsafe fn set_bind_group( + &mut self, + layout: &super::PipelineLayout, + group_index: u32, + group: &super::BindGroup, + dynamic_offsets: &[wgt::DynamicOffset], + ) { + let bg_info = layout.bind_group_infos[group_index as usize] + .as_ref() + .unwrap(); + let render_encoder = self.state.render.clone(); + let compute_encoder = self.state.compute.clone(); + if let Some(encoder) = render_encoder { + self.update_bind_group_state( + Encoder::Vertex(&encoder), + // All zeros, as vs comes first + super::ResourceData::default(), + bg_info, + dynamic_offsets, + group_index, + group, + ); + self.update_bind_group_state( + Encoder::Task(&encoder), + // All zeros, as ts comes first + super::ResourceData::default(), + bg_info, + dynamic_offsets, + group_index, + group, + ); + self.update_bind_group_state( + Encoder::Mesh(&encoder), + group.counters.ts.clone(), + bg_info, + dynamic_offsets, + group_index, + group, + ); + self.update_bind_group_state( + Encoder::Fragment(&encoder), + super::ResourceData { + buffers: group.counters.vs.buffers + + group.counters.ts.buffers + + group.counters.ms.buffers, + textures: group.counters.vs.textures + + group.counters.ts.textures + + group.counters.ms.textures, + samplers: group.counters.vs.samplers + + group.counters.ts.samplers + + group.counters.ms.samplers, + }, + bg_info, + dynamic_offsets, + group_index, + group, + ); + // Call useResource on all textures and buffers used indirectly so they are alive + for (resource, use_info) in group.resources_to_use.iter() { + encoder.useResource_usage_stages( + unsafe { resource.as_ref() }, + use_info.uses, + use_info.stages, + ); + } + } + if let Some(encoder) = compute_encoder { + self.update_bind_group_state( + Encoder::Compute(&encoder), + super::ResourceData { + buffers: group.counters.vs.buffers + + group.counters.ts.buffers + + group.counters.ms.buffers + + group.counters.fs.buffers, + textures: group.counters.vs.textures + + group.counters.ts.textures + + group.counters.ms.textures + + group.counters.fs.textures, + samplers: group.counters.vs.samplers + + group.counters.ts.samplers + + group.counters.ms.samplers + + group.counters.fs.samplers, + }, + bg_info, + dynamic_offsets, + group_index, + group, + ); + // Call useResource on all textures and buffers used indirectly so they are alive + for (resource, use_info) in group.resources_to_use.iter() { + if !use_info.visible_in_compute { + continue; + } + encoder.useResource_usage(unsafe { resource.as_ref() }, use_info.uses); + } + } + } + + unsafe fn set_immediates( + &mut self, + layout: &super::PipelineLayout, + offset_bytes: u32, + data: &[u32], + ) { + let state_pc = &mut self.state.immediates; + if state_pc.len() < layout.total_immediates as usize { + state_pc.resize(layout.total_immediates as usize, 0); + } + debug_assert_eq!(offset_bytes as usize % WORD_SIZE, 0); + + let offset_words = offset_bytes as usize / WORD_SIZE; + state_pc[offset_words..offset_words + data.len()].copy_from_slice(data); + + let bytes = NonNull::new(state_pc.as_ptr().cast_mut().cast()).unwrap(); + if let Some(ref compute) = self.state.compute { + unsafe { + compute.setBytes_length_atIndex( + bytes, + layout.total_immediates as usize * WORD_SIZE, + layout.immediates_infos.cs.unwrap().buffer_index as usize, + ) + }; + } + if let Some(ref render) = self.state.render { + if let Some(vs) = layout.immediates_infos.vs { + unsafe { + render.setVertexBytes_length_atIndex( + bytes, + layout.total_immediates as usize * WORD_SIZE, + vs.buffer_index as _, + ) + } + } + if let Some(fs) = layout.immediates_infos.fs { + unsafe { + render.setFragmentBytes_length_atIndex( + bytes, + layout.total_immediates as usize * WORD_SIZE, + fs.buffer_index as _, + ) + } + } + if let Some(ts) = layout.immediates_infos.ts { + if self.shared.private_caps.mesh_shaders { + unsafe { + render.setObjectBytes_length_atIndex( + bytes, + layout.total_immediates as usize * WORD_SIZE, + ts.buffer_index as _, + ) + } + } + } + if let Some(ms) = layout.immediates_infos.ms { + if self.shared.private_caps.mesh_shaders { + unsafe { + render.setMeshBytes_length_atIndex( + bytes, + layout.total_immediates as usize * WORD_SIZE, + ms.buffer_index as _, + ) + } + } + } + } + } + + unsafe fn insert_debug_marker(&mut self, label: &str) { + if let Some(encoder) = self.active_encoder() { + encoder.insertDebugSignpost(&NSString::from_str(label)); + } + } + unsafe fn begin_debug_marker(&mut self, group_label: &str) { + if let Some(encoder) = self.active_encoder() { + encoder.pushDebugGroup(&NSString::from_str(group_label)); + } else if let Some(ref buf) = self.raw_cmd_buf { + buf.pushDebugGroup(&NSString::from_str(group_label)); + } + } + unsafe fn end_debug_marker(&mut self) { + if let Some(encoder) = self.active_encoder() { + encoder.popDebugGroup(); + } else if let Some(ref buf) = self.raw_cmd_buf { + buf.popDebugGroup(); + } + } + + unsafe fn set_render_pipeline(&mut self, pipeline: &super::RenderPipeline) { + self.state.raw_primitive_type = pipeline.raw_primitive_type; + match pipeline.vs_info { + Some(ref info) => self.state.stage_infos.vs.assign_from(info), + None => self.state.stage_infos.vs.clear(), + } + match pipeline.fs_info { + Some(ref info) => self.state.stage_infos.fs.assign_from(info), + None => self.state.stage_infos.fs.clear(), + } + match pipeline.ts_info { + Some(ref info) => self.state.stage_infos.ts.assign_from(info), + None => self.state.stage_infos.ts.clear(), + } + match pipeline.ms_info { + Some(ref info) => self.state.stage_infos.ms.assign_from(info), + None => self.state.stage_infos.ms.clear(), + } + + let encoder = self.state.render.as_ref().unwrap(); + encoder.setRenderPipelineState(&pipeline.raw); + encoder.setFrontFacingWinding(pipeline.raw_front_winding); + encoder.setCullMode(pipeline.raw_cull_mode); + encoder.setTriangleFillMode(pipeline.raw_triangle_fill_mode); + if let Some(depth_clip) = pipeline.raw_depth_clip_mode { + encoder.setDepthClipMode(depth_clip); + } + if let Some((ref state, bias)) = pipeline.depth_stencil { + encoder.setDepthStencilState(Some(state)); + encoder.setDepthBias_slopeScale_clamp( + bias.constant as f32, + bias.slope_scale, + bias.clamp, + ); + } + + if pipeline.vs_info.is_some() { + if let Some((index, sizes)) = self + .state + .make_sizes_buffer_update(naga::ShaderStage::Vertex, &mut self.temp.binding_sizes) + { + unsafe { + encoder.setVertexBytes_length_atIndex( + NonNull::new(sizes.as_ptr().cast_mut().cast()).unwrap(), + sizes.len() * WORD_SIZE, + index as _, + ) + }; + } + } + if pipeline.fs_info.is_some() { + if let Some((index, sizes)) = self + .state + .make_sizes_buffer_update(naga::ShaderStage::Fragment, &mut self.temp.binding_sizes) + { + unsafe { + encoder.setFragmentBytes_length_atIndex( + NonNull::new(sizes.as_ptr().cast_mut().cast()).unwrap(), + sizes.len() * WORD_SIZE, + index as _, + ) + }; + } + } + if let Some(ts_info) = &pipeline.ts_info { + // update the threadgroup memory sizes + while self.state.stage_infos.ms.work_group_memory_sizes.len() + < ts_info.work_group_memory_sizes.len() + { + self.state.stage_infos.ms.work_group_memory_sizes.push(0); + } + for (index, (cur_size, pipeline_size)) in self + .state + .stage_infos + .ms + .work_group_memory_sizes + .iter_mut() + .zip(ts_info.work_group_memory_sizes.iter()) + .enumerate() + { + let size = pipeline_size.next_multiple_of(16); + if *cur_size != size { + *cur_size = size; + unsafe { encoder.setObjectThreadgroupMemoryLength_atIndex(size as _, index) }; + } + } + if let Some((index, sizes)) = self + .state + .make_sizes_buffer_update(naga::ShaderStage::Task, &mut self.temp.binding_sizes) + { + unsafe { + encoder.setObjectBytes_length_atIndex( + NonNull::new(sizes.as_ptr().cast_mut().cast()).unwrap(), + sizes.len() * WORD_SIZE, + index as _, + ) + }; + } + } + if let Some(_ms_info) = &pipeline.ms_info { + // So there isn't an equivalent to + // https://developer.apple.com/documentation/metal/mtlrendercommandencoder/setthreadgroupmemorylength(_:offset:index:) + // for mesh shaders. This is probably because the CPU has less control over the dispatch sizes and such. Interestingly + // it also affects mesh shaders without task/object shaders, even though none of compute, task or fragment shaders + // behave this way. + if let Some((index, sizes)) = self + .state + .make_sizes_buffer_update(naga::ShaderStage::Mesh, &mut self.temp.binding_sizes) + { + unsafe { + encoder.setMeshBytes_length_atIndex( + NonNull::new(sizes.as_ptr().cast_mut().cast()).unwrap(), + sizes.len() * WORD_SIZE, + index as _, + ) + }; + } + } + } + + unsafe fn set_index_buffer<'a>( + &mut self, + binding: crate::BufferBinding<'a, super::Buffer>, + format: wgt::IndexFormat, + ) { + let (stride, raw_type) = conv::map_index_format(format); + self.state.index = Some(super::IndexState { + buffer_ptr: NonNull::from(&*binding.buffer.raw), + offset: binding.offset, + stride, + raw_type, + }); + } + + unsafe fn set_vertex_buffer<'a>( + &mut self, + index: u32, + binding: crate::BufferBinding<'a, super::Buffer>, + ) { + let buffer_index = MAX_BUFFERS - 1 - index; + let encoder = self.state.render.as_ref().unwrap(); + unsafe { + encoder.setVertexBuffer_offset_atIndex( + Some(&binding.buffer.raw), + binding.offset as usize, + buffer_index as usize, + ) + }; + + let buffer_size = binding.resolve_size(); + if buffer_size > 0 { + self.state.vertex_buffer_size_map.insert( + buffer_index, + core::num::NonZeroU64::new(buffer_size).unwrap(), + ); + } else { + self.state.vertex_buffer_size_map.remove(&buffer_index); + } + + if let Some((index, sizes)) = self + .state + .make_sizes_buffer_update(naga::ShaderStage::Vertex, &mut self.temp.binding_sizes) + { + unsafe { + encoder.setVertexBytes_length_atIndex( + NonNull::new(sizes.as_ptr().cast_mut().cast()).unwrap(), + sizes.len() * WORD_SIZE, + index as _, + ) + }; + } + } + + unsafe fn set_viewport(&mut self, rect: &crate::Rect<f32>, depth_range: Range<f32>) { + let zfar = if self.shared.disabilities.broken_viewport_near_depth { + depth_range.end - depth_range.start + } else { + depth_range.end + }; + let encoder = self.state.render.as_ref().unwrap(); + encoder.setViewport(MTLViewport { + originX: rect.x as _, + originY: rect.y as _, + width: rect.w as _, + height: rect.h as _, + znear: depth_range.start as _, + zfar: zfar as _, + }); + } + unsafe fn set_scissor_rect(&mut self, rect: &crate::Rect<u32>) { + //TODO: support empty scissors by modifying the viewport + let scissor = MTLScissorRect { + x: rect.x as _, + y: rect.y as _, + width: rect.w as _, + height: rect.h as _, + }; + let encoder = self.state.render.as_ref().unwrap(); + encoder.setScissorRect(scissor); + } + unsafe fn set_stencil_reference(&mut self, value: u32) { + let encoder = self.state.render.as_ref().unwrap(); + encoder.setStencilFrontReferenceValue_backReferenceValue(value, value); + } + unsafe fn set_blend_constants(&mut self, color: &[f32; 4]) { + let encoder = self.state.render.as_ref().unwrap(); + encoder.setBlendColorRed_green_blue_alpha(color[0], color[1], color[2], color[3]); + } + + unsafe fn draw( + &mut self, + first_vertex: u32, + vertex_count: u32, + first_instance: u32, + instance_count: u32, + ) { + let encoder = self.state.render.as_ref().unwrap(); + if first_instance != 0 { + unsafe { + encoder.drawPrimitives_vertexStart_vertexCount_instanceCount_baseInstance( + self.state.raw_primitive_type, + first_vertex as _, + vertex_count as _, + instance_count as _, + first_instance as _, + ) + }; + } else if instance_count != 1 { + unsafe { + encoder.drawPrimitives_vertexStart_vertexCount_instanceCount( + self.state.raw_primitive_type, + first_vertex as _, + vertex_count as _, + instance_count as _, + ) + }; + } else { + unsafe { + encoder.drawPrimitives_vertexStart_vertexCount( + self.state.raw_primitive_type, + first_vertex as _, + vertex_count as _, + ) + }; + } + } + + unsafe fn draw_indexed( + &mut self, + first_index: u32, + index_count: u32, + base_vertex: i32, + first_instance: u32, + instance_count: u32, + ) { + let encoder = self.state.render.as_ref().unwrap(); + let index = self.state.index.as_ref().unwrap(); + let offset = (index.offset + index.stride * first_index as wgt::BufferAddress) as usize; + if base_vertex != 0 || first_instance != 0 { + unsafe { + encoder.drawIndexedPrimitives_indexCount_indexType_indexBuffer_indexBufferOffset_instanceCount_baseVertex_baseInstance( + self.state.raw_primitive_type, + index_count as _, + index.raw_type, + index.buffer_ptr.as_ref(), + offset, + instance_count as _, + base_vertex as _, + first_instance as _, + ) + }; + } else if instance_count != 1 { + unsafe { + encoder.drawIndexedPrimitives_indexCount_indexType_indexBuffer_indexBufferOffset_instanceCount( + self.state.raw_primitive_type, + index_count as _, + index.raw_type, + index.buffer_ptr.as_ref(), + offset, + instance_count as _, + ) + }; + } else { + unsafe { + encoder.drawIndexedPrimitives_indexCount_indexType_indexBuffer_indexBufferOffset( + self.state.raw_primitive_type, + index_count as _, + index.raw_type, + index.buffer_ptr.as_ref(), + offset, + ) + }; + } + } + + unsafe fn draw_mesh_tasks( + &mut self, + group_count_x: u32, + group_count_y: u32, + group_count_z: u32, + ) { + let encoder = self.state.render.as_ref().unwrap(); + let size = MTLSize { + width: group_count_x as usize, + height: group_count_y as usize, + depth: group_count_z as usize, + }; + encoder.drawMeshThreadgroups_threadsPerObjectThreadgroup_threadsPerMeshThreadgroup( + size, + self.state.stage_infos.ts.raw_wg_size, + self.state.stage_infos.ms.raw_wg_size, + ); + } + + unsafe fn draw_indirect( + &mut self, + buffer: &super::Buffer, + mut offset: wgt::BufferAddress, + draw_count: u32, + ) { + let encoder = self.state.render.as_ref().unwrap(); + for _ in 0..draw_count { + unsafe { + encoder.drawPrimitives_indirectBuffer_indirectBufferOffset( + self.state.raw_primitive_type, + &buffer.raw, + offset as usize, + ) + }; + offset += size_of::<wgt::DrawIndirectArgs>() as wgt::BufferAddress; + } + } + + unsafe fn draw_indexed_indirect( + &mut self, + buffer: &super::Buffer, + mut offset: wgt::BufferAddress, + draw_count: u32, + ) { + let encoder = self.state.render.as_ref().unwrap(); + let index = self.state.index.as_ref().unwrap(); + for _ in 0..draw_count { + unsafe { + encoder.drawIndexedPrimitives_indexType_indexBuffer_indexBufferOffset_indirectBuffer_indirectBufferOffset( + self.state.raw_primitive_type, + index.raw_type, + index.buffer_ptr.as_ref(), + index.offset as usize, + &buffer.raw, + offset as usize, + ) + }; + offset += size_of::<wgt::DrawIndexedIndirectArgs>() as wgt::BufferAddress; + } + } + + unsafe fn draw_mesh_tasks_indirect( + &mut self, + buffer: &<Self::A as crate::Api>::Buffer, + mut offset: wgt::BufferAddress, + draw_count: u32, + ) { + let encoder = self.state.render.as_ref().unwrap(); + for _ in 0..draw_count { + unsafe { + encoder.drawMeshThreadgroupsWithIndirectBuffer_indirectBufferOffset_threadsPerObjectThreadgroup_threadsPerMeshThreadgroup( + &buffer.raw, + offset as usize, + self.state.stage_infos.ts.raw_wg_size, + self.state.stage_infos.ms.raw_wg_size, + ) + }; + offset += size_of::<wgt::DispatchIndirectArgs>() as wgt::BufferAddress; + } + } + + unsafe fn draw_indirect_count( + &mut self, + _buffer: &super::Buffer, + _offset: wgt::BufferAddress, + _count_buffer: &super::Buffer, + _count_offset: wgt::BufferAddress, + _max_count: u32, + ) { + //TODO + } + unsafe fn draw_indexed_indirect_count( + &mut self, + _buffer: &super::Buffer, + _offset: wgt::BufferAddress, + _count_buffer: &super::Buffer, + _count_offset: wgt::BufferAddress, + _max_count: u32, + ) { + //TODO + } + + unsafe fn draw_mesh_tasks_indirect_count( + &mut self, + _buffer: &<Self::A as crate::Api>::Buffer, + _offset: wgt::BufferAddress, + _count_buffer: &<Self::A as crate::Api>::Buffer, + _count_offset: wgt::BufferAddress, + _max_count: u32, + ) { + unreachable!() + } + + // compute + + unsafe fn begin_compute_pass(&mut self, desc: &crate::ComputePassDescriptor<super::QuerySet>) { + self.begin_pass(); + + debug_assert!(self.state.blit.is_none()); + debug_assert!(self.state.compute.is_none()); + debug_assert!(self.state.render.is_none()); + + let raw = self.raw_cmd_buf.as_ref().unwrap(); + + autoreleasepool(|_| { + // TimeStamp Queries and ComputePassDescriptor were both introduced in Metal 2.3 (macOS 11, iOS 14) + // and we currently only need ComputePassDescriptor for timestamp queries + let encoder = if self.shared.private_caps.timestamp_query_support.is_empty() { + raw.computeCommandEncoder().unwrap() + } else { + let descriptor = MTLComputePassDescriptor::new(); + + let mut sba_index = 0; + let mut next_sba_descriptor = || { + let sba_descriptor = unsafe { + descriptor + .sampleBufferAttachments() + .objectAtIndexedSubscript(sba_index) + }; + sba_index += 1; + sba_descriptor + }; + + for (set, index) in self.state.pending_timer_queries.drain(..) { + let sba_descriptor = next_sba_descriptor(); + sba_descriptor + .setSampleBuffer(Some(set.counter_sample_buffer.as_ref().unwrap())); + unsafe { sba_descriptor.setStartOfEncoderSampleIndex(index as _) }; + unsafe { sba_descriptor.setEndOfEncoderSampleIndex(MTLCounterDontSample) }; + } + + if let Some(timestamp_writes) = desc.timestamp_writes.as_ref() { + let sba_descriptor = next_sba_descriptor(); + sba_descriptor.setSampleBuffer(Some( + timestamp_writes + .query_set + .counter_sample_buffer + .as_ref() + .unwrap(), + )); + + unsafe { + sba_descriptor.setStartOfEncoderSampleIndex( + timestamp_writes + .beginning_of_pass_write_index + .map_or(MTLCounterDontSample, |i| i as _), + ) + }; + unsafe { + sba_descriptor.setEndOfEncoderSampleIndex( + timestamp_writes + .end_of_pass_write_index + .map_or(MTLCounterDontSample, |i| i as _), + ) + }; + } + + raw.computeCommandEncoderWithDescriptor(&descriptor) + .unwrap() + }; + + if let Some(label) = desc.label { + encoder.setLabel(Some(&NSString::from_str(label))); + } + + self.state.compute = Some(encoder.to_owned()); + }); + } + unsafe fn end_compute_pass(&mut self) { + self.state.compute.take().unwrap().endEncoding(); + } + + unsafe fn set_compute_pipeline(&mut self, pipeline: &super::ComputePipeline) { + let previous_sizes = + core::mem::take(&mut self.state.stage_infos.cs.work_group_memory_sizes); + self.state.stage_infos.cs.assign_from(&pipeline.cs_info); + + let encoder = self.state.compute.as_ref().unwrap(); + encoder.setComputePipelineState(&pipeline.raw); + + if let Some((index, sizes)) = self + .state + .make_sizes_buffer_update(naga::ShaderStage::Compute, &mut self.temp.binding_sizes) + { + unsafe { + encoder.setBytes_length_atIndex( + NonNull::new(sizes.as_ptr().cast_mut().cast()).unwrap(), + sizes.len() * WORD_SIZE, + index as _, + ) + }; + } + + // update the threadgroup memory sizes + for (i, current_size) in self + .state + .stage_infos + .cs + .work_group_memory_sizes + .iter_mut() + .enumerate() + { + let prev_size = if i < previous_sizes.len() { + previous_sizes[i] + } else { + u32::MAX + }; + let size: u32 = current_size.next_multiple_of(16); + *current_size = size; + if size != prev_size { + unsafe { encoder.setThreadgroupMemoryLength_atIndex(size as _, i) }; + } + } + } + + unsafe fn dispatch_workgroups(&mut self, count: [u32; 3]) { + if count[0] > 0 && count[1] > 0 && count[2] > 0 { + let encoder = self.state.compute.as_ref().unwrap(); + let raw_count = MTLSize { + width: count[0] as usize, + height: count[1] as usize, + depth: count[2] as usize, + }; + encoder.dispatchThreadgroups_threadsPerThreadgroup( + raw_count, + self.state.stage_infos.cs.raw_wg_size, + ); + } + } + + unsafe fn dispatch_workgroups_indirect( + &mut self, + buffer: &super::Buffer, + offset: wgt::BufferAddress, + ) { + let encoder = self.state.compute.as_ref().unwrap(); + unsafe { + encoder + .dispatchThreadgroupsWithIndirectBuffer_indirectBufferOffset_threadsPerThreadgroup( + &buffer.raw, + offset as usize, + self.state.stage_infos.cs.raw_wg_size, + ) + }; + } + + unsafe fn build_acceleration_structures<'a, T>( + &mut self, + _descriptor_count: u32, + descriptors: T, + ) where + super::Api: 'a, + T: IntoIterator< + Item = crate::BuildAccelerationStructureDescriptor< + 'a, + super::Buffer, + super::AccelerationStructure, + >, + >, + { + let command_encoder = self.enter_acceleration_structure_builder(); + for descriptor in descriptors { + let acceleration_structure_descriptor = + conv::map_acceleration_structure_descriptor(descriptor.entries, descriptor.flags); + match descriptor.mode { + crate::AccelerationStructureBuildMode::Build => { + command_encoder + .buildAccelerationStructure_descriptor_scratchBuffer_scratchBufferOffset( + &descriptor.destination_acceleration_structure.raw, + &acceleration_structure_descriptor, + &descriptor.scratch_buffer.raw, + descriptor.scratch_buffer_offset as usize, + ); + } + crate::AccelerationStructureBuildMode::Update => unsafe { + command_encoder.refitAccelerationStructure_descriptor_destination_scratchBuffer_scratchBufferOffset( + &descriptor.source_acceleration_structure.unwrap().raw, + &acceleration_structure_descriptor, + Some(&descriptor.destination_acceleration_structure.raw), + Some(&descriptor.scratch_buffer.raw), + descriptor.scratch_buffer_offset as usize, + ); + }, + } + } + } + + unsafe fn place_acceleration_structure_barrier( + &mut self, + _barriers: crate::AccelerationStructureBarrier, + ) { + } + + unsafe fn read_acceleration_structure_compact_size( + &mut self, + acceleration_structure: &super::AccelerationStructure, + buffer: &super::Buffer, + ) { + let command_encoder = self.enter_acceleration_structure_builder(); + command_encoder.writeCompactedAccelerationStructureSize_toBuffer_offset( + &acceleration_structure.raw, + &buffer.raw, + 0, + ); + } + + unsafe fn set_acceleration_structure_dependencies( + command_buffers: &[&super::CommandBuffer], + dependencies: &[&super::AccelerationStructure], + ) { + let Some(first_command_buffer) = command_buffers.first() else { + return; + }; + let desc = MTLResidencySetDescriptor::new(); + desc.setLabel(first_command_buffer.raw.label().as_deref()); + let residency_set = first_command_buffer + .raw + .device() + .newResidencySetWithDescriptor_error(&desc) + .unwrap(); + for command_buffer in command_buffers { + command_buffer.raw.useResidencySet(&residency_set); + } + for dependency in dependencies { + residency_set.addAllocation(ProtocolObject::from_ref(&*dependency.raw)); + } + residency_set.commit(); + } + + unsafe fn begin_ray_tracing_pass(&mut self, _desc: &crate::RayTracingPassDescriptor) { + unreachable!("Ray tracing pipelines not supported") + } + + unsafe fn end_ray_tracing_pass(&mut self) { + unreachable!("Ray tracing pipelines not supported") + } + + unsafe fn set_ray_tracing_pipeline( + &mut self, + _pipeline: &<Self::A as crate::Api>::RayTracingPipeline, + ) { + unreachable!("Ray tracing pipelines not supported") + } + + unsafe fn trace_rays( + &mut self, + _count: [u32; 3], + _ray_generation_group_data: crate::PipelineGroupData<super::Buffer>, + _miss_group_data: crate::PipelineGroupData<super::Buffer>, + _intersection_group_data: crate::PipelineGroupData<super::Buffer>, + ) { + unreachable!("Ray tracing pipelines not supported") + } +} + +impl Drop for super::CommandEncoder { + fn drop(&mut self) { + // Metal raises an assert when a MTLCommandEncoder is deallocated without a call + // to endEncoding. This isn't documented in the general case at + // https://developer.apple.com/documentation/metal/mtlcommandencoder, but for the + // more-specific MTLComputeCommandEncoder it is stated as a requirement at + // https://developer.apple.com/documentation/metal/mtlcomputecommandencoder. It + // appears to be a requirement for all MTLCommandEncoder objects. Failing to call + // endEncoding causes a crash with the message 'Command encoder released without + // endEncoding'. To prevent this, we explicitiy call discard_encoding, which + // calls endEncoding on any still-held MTLCommandEncoders. + unsafe { + self.discard_encoding(); + } + self.counters.command_encoders.sub(1); + } +} + +impl Drop for super::CommandBuffer { + fn drop(&mut self) { + // `command_buffer_created_not_submitted` is usually decremented when the command + // buffer is submitted. But if we're dropping a command buffer that was never + // submitted, we need to decrement the count here. + let status = self.raw.status(); + if status == MTLCommandBufferStatus::NotEnqueued + || status == MTLCommandBufferStatus::Enqueued + { + let previous = self + .queue_shared + .command_buffer_created_not_submitted + .fetch_sub(1, atomic::Ordering::AcqRel); + debug_assert!(previous > 0); + } + } +} diff --git a/app/vendor/rune/vendor/wgpu-hal/src/metal/conv.rs b/app/vendor/rune/vendor/wgpu-hal/src/metal/conv.rs new file mode 100644 index 0000000..0b76164 --- /dev/null +++ b/app/vendor/rune/vendor/wgpu-hal/src/metal/conv.rs @@ -0,0 +1,494 @@ +use objc2::rc::Retained; +use objc2_foundation::{NSArray, NSRange}; +use objc2_metal::{ + MTLAccelerationStructureBoundingBoxGeometryDescriptor, MTLAccelerationStructureDescriptor, + MTLAccelerationStructureGeometryDescriptor, MTLAccelerationStructureInstanceDescriptorType, + MTLAccelerationStructureTriangleGeometryDescriptor, MTLAccelerationStructureUsage, + MTLAttributeFormat, MTLBlendFactor, MTLBlendOperation, MTLBlitOption, MTLClearColor, + MTLColorWriteMask, MTLCompareFunction, MTLCullMode, MTLIndexType, + MTLInstanceAccelerationStructureDescriptor, MTLOrigin, + MTLPrimitiveAccelerationStructureDescriptor, MTLPrimitiveTopologyClass, MTLPrimitiveType, + MTLRenderStages, MTLResourceUsage, MTLSamplerAddressMode, MTLSamplerBorderColor, + MTLSamplerMinMagFilter, MTLSize, MTLStencilOperation, MTLStoreAction, MTLTextureType, + MTLTextureUsage, MTLVertexFormat, MTLVertexStepFunction, MTLWinding, +}; + +pub fn map_texture_usage(format: wgt::TextureFormat, usage: wgt::TextureUses) -> MTLTextureUsage { + use wgt::TextureUses as Tu; + + let mut mtl_usage = MTLTextureUsage::Unknown; + + mtl_usage.set( + MTLTextureUsage::RenderTarget, + usage.intersects(Tu::COLOR_TARGET | Tu::DEPTH_STENCIL_READ | Tu::DEPTH_STENCIL_WRITE), + ); + mtl_usage.set( + MTLTextureUsage::ShaderRead, + usage.intersects( + Tu::RESOURCE | Tu::DEPTH_STENCIL_READ | Tu::STORAGE_READ_ONLY | Tu::STORAGE_READ_WRITE, + ), + ); + mtl_usage.set( + MTLTextureUsage::ShaderWrite, + usage.intersects(Tu::STORAGE_WRITE_ONLY | Tu::STORAGE_READ_WRITE), + ); + // needed for combined depth/stencil formats since we might + // create a stencil-only view from them + mtl_usage.set( + MTLTextureUsage::PixelFormatView, + format.is_combined_depth_stencil_format(), + ); + + mtl_usage.set( + MTLTextureUsage::ShaderAtomic, + usage.intersects(Tu::STORAGE_ATOMIC), + ); + + mtl_usage +} + +pub fn map_texture_view_dimension(dim: wgt::TextureViewDimension) -> MTLTextureType { + use wgt::TextureViewDimension as Tvd; + use MTLTextureType as MTL; + match dim { + Tvd::D1 => MTL::Type1D, + Tvd::D2 => MTL::Type2D, + Tvd::D2Array => MTL::Type2DArray, + Tvd::D3 => MTL::Type3D, + Tvd::Cube => MTL::TypeCube, + Tvd::CubeArray => MTL::TypeCubeArray, + } +} + +pub fn map_compare_function(fun: wgt::CompareFunction) -> MTLCompareFunction { + use wgt::CompareFunction as Cf; + use MTLCompareFunction as MTL; + match fun { + Cf::Never => MTL::Never, + Cf::Less => MTL::Less, + Cf::LessEqual => MTL::LessEqual, + Cf::Equal => MTL::Equal, + Cf::GreaterEqual => MTL::GreaterEqual, + Cf::Greater => MTL::Greater, + Cf::NotEqual => MTL::NotEqual, + Cf::Always => MTL::Always, + } +} + +pub fn map_filter_mode(filter: wgt::FilterMode) -> MTLSamplerMinMagFilter { + use MTLSamplerMinMagFilter as MTL; + match filter { + wgt::FilterMode::Nearest => MTL::Nearest, + wgt::FilterMode::Linear => MTL::Linear, + } +} + +pub fn map_address_mode(address: wgt::AddressMode) -> MTLSamplerAddressMode { + use wgt::AddressMode as Fm; + use MTLSamplerAddressMode as MTL; + match address { + Fm::Repeat => MTL::Repeat, + Fm::MirrorRepeat => MTL::MirrorRepeat, + Fm::ClampToEdge => MTL::ClampToEdge, + Fm::ClampToBorder => MTL::ClampToBorderColor, + //Fm::MirrorClamp => MTL::MirrorClampToEdge, + } +} + +pub fn map_border_color(border_color: wgt::SamplerBorderColor) -> MTLSamplerBorderColor { + use MTLSamplerBorderColor as MTL; + match border_color { + wgt::SamplerBorderColor::TransparentBlack => MTL::TransparentBlack, + wgt::SamplerBorderColor::OpaqueBlack => MTL::OpaqueBlack, + wgt::SamplerBorderColor::OpaqueWhite => MTL::OpaqueWhite, + wgt::SamplerBorderColor::Zero => unreachable!(), + } +} + +pub fn map_primitive_topology( + topology: wgt::PrimitiveTopology, +) -> (MTLPrimitiveTopologyClass, MTLPrimitiveType) { + use wgt::PrimitiveTopology as Pt; + match topology { + Pt::PointList => (MTLPrimitiveTopologyClass::Point, MTLPrimitiveType::Point), + Pt::LineList => (MTLPrimitiveTopologyClass::Line, MTLPrimitiveType::Line), + Pt::LineStrip => (MTLPrimitiveTopologyClass::Line, MTLPrimitiveType::LineStrip), + Pt::TriangleList => ( + MTLPrimitiveTopologyClass::Triangle, + MTLPrimitiveType::Triangle, + ), + Pt::TriangleStrip => ( + MTLPrimitiveTopologyClass::Triangle, + MTLPrimitiveType::TriangleStrip, + ), + } +} + +pub fn map_color_write(mask: wgt::ColorWrites) -> MTLColorWriteMask { + let mut raw_mask = MTLColorWriteMask::empty(); + + if mask.contains(wgt::ColorWrites::RED) { + raw_mask |= MTLColorWriteMask::Red; + } + if mask.contains(wgt::ColorWrites::GREEN) { + raw_mask |= MTLColorWriteMask::Green; + } + if mask.contains(wgt::ColorWrites::BLUE) { + raw_mask |= MTLColorWriteMask::Blue; + } + if mask.contains(wgt::ColorWrites::ALPHA) { + raw_mask |= MTLColorWriteMask::Alpha; + } + + raw_mask +} + +pub fn map_blend_factor(factor: wgt::BlendFactor) -> MTLBlendFactor { + use wgt::BlendFactor as Bf; + use MTLBlendFactor as MTL; + + match factor { + Bf::Zero => MTL::Zero, + Bf::One => MTL::One, + Bf::Src => MTL::SourceColor, + Bf::OneMinusSrc => MTL::OneMinusSourceColor, + Bf::Dst => MTL::DestinationColor, + Bf::OneMinusDst => MTL::OneMinusDestinationColor, + Bf::SrcAlpha => MTL::SourceAlpha, + Bf::OneMinusSrcAlpha => MTL::OneMinusSourceAlpha, + Bf::DstAlpha => MTL::DestinationAlpha, + Bf::OneMinusDstAlpha => MTL::OneMinusDestinationAlpha, + Bf::Constant => MTL::BlendColor, + Bf::OneMinusConstant => MTL::OneMinusBlendColor, + Bf::SrcAlphaSaturated => MTL::SourceAlphaSaturated, + Bf::Src1 => MTL::Source1Color, + Bf::OneMinusSrc1 => MTL::OneMinusSource1Color, + Bf::Src1Alpha => MTL::Source1Alpha, + Bf::OneMinusSrc1Alpha => MTL::OneMinusSource1Alpha, + } +} + +pub fn map_blend_op(operation: wgt::BlendOperation) -> MTLBlendOperation { + use wgt::BlendOperation as Bo; + use MTLBlendOperation as MTL; + + match operation { + Bo::Add => MTL::Add, + Bo::Subtract => MTL::Subtract, + Bo::ReverseSubtract => MTL::ReverseSubtract, + Bo::Min => MTL::Min, + Bo::Max => MTL::Max, + } +} + +pub fn map_blend_component( + component: &wgt::BlendComponent, +) -> (MTLBlendOperation, MTLBlendFactor, MTLBlendFactor) { + ( + map_blend_op(component.operation), + map_blend_factor(component.src_factor), + map_blend_factor(component.dst_factor), + ) +} + +pub fn map_vertex_format(format: wgt::VertexFormat) -> MTLVertexFormat { + use wgt::VertexFormat as Vf; + use MTLVertexFormat as MTL; + + match format { + Vf::Unorm8 => MTL::UCharNormalized, + Vf::Snorm8 => MTL::CharNormalized, + Vf::Uint8 => MTL::UChar, + Vf::Sint8 => MTL::Char, + Vf::Unorm8x2 => MTL::UChar2Normalized, + Vf::Snorm8x2 => MTL::Char2Normalized, + Vf::Uint8x2 => MTL::UChar2, + Vf::Sint8x2 => MTL::Char2, + Vf::Unorm8x4 => MTL::UChar4Normalized, + Vf::Snorm8x4 => MTL::Char4Normalized, + Vf::Uint8x4 => MTL::UChar4, + Vf::Sint8x4 => MTL::Char4, + Vf::Unorm16 => MTL::UShortNormalized, + Vf::Snorm16 => MTL::ShortNormalized, + Vf::Uint16 => MTL::UShort, + Vf::Sint16 => MTL::Short, + Vf::Float16 => MTL::Half, + Vf::Unorm16x2 => MTL::UShort2Normalized, + Vf::Snorm16x2 => MTL::Short2Normalized, + Vf::Uint16x2 => MTL::UShort2, + Vf::Sint16x2 => MTL::Short2, + Vf::Float16x2 => MTL::Half2, + Vf::Unorm16x4 => MTL::UShort4Normalized, + Vf::Snorm16x4 => MTL::Short4Normalized, + Vf::Uint16x4 => MTL::UShort4, + Vf::Sint16x4 => MTL::Short4, + Vf::Float16x4 => MTL::Half4, + Vf::Uint32 => MTL::UInt, + Vf::Sint32 => MTL::Int, + Vf::Float32 => MTL::Float, + Vf::Uint32x2 => MTL::UInt2, + Vf::Sint32x2 => MTL::Int2, + Vf::Float32x2 => MTL::Float2, + Vf::Uint32x3 => MTL::UInt3, + Vf::Sint32x3 => MTL::Int3, + Vf::Float32x3 => MTL::Float3, + Vf::Uint32x4 => MTL::UInt4, + Vf::Sint32x4 => MTL::Int4, + Vf::Float32x4 => MTL::Float4, + Vf::Unorm10_10_10_2 => MTL::UInt1010102Normalized, + Vf::Unorm8x4Bgra => MTL::UChar4Normalized_BGRA, + Vf::Float64 | Vf::Float64x2 | Vf::Float64x3 | Vf::Float64x4 => unimplemented!(), + } +} + +pub fn map_index_format(format: wgt::IndexFormat) -> (u64, MTLIndexType) { + match format { + wgt::IndexFormat::Uint16 => (2, MTLIndexType::UInt16), + wgt::IndexFormat::Uint32 => (4, MTLIndexType::UInt32), + } +} + +pub fn map_step_mode(mode: wgt::VertexStepMode) -> MTLVertexStepFunction { + match mode { + wgt::VertexStepMode::Vertex => MTLVertexStepFunction::PerVertex, + wgt::VertexStepMode::Instance => MTLVertexStepFunction::PerInstance, + } +} + +pub fn map_stencil_op(op: wgt::StencilOperation) -> MTLStencilOperation { + use wgt::StencilOperation as So; + use MTLStencilOperation as MTL; + + match op { + So::Keep => MTL::Keep, + So::Zero => MTL::Zero, + So::Replace => MTL::Replace, + So::IncrementClamp => MTL::IncrementClamp, + So::IncrementWrap => MTL::IncrementWrap, + So::DecrementClamp => MTL::DecrementClamp, + So::DecrementWrap => MTL::DecrementWrap, + So::Invert => MTL::Invert, + } +} + +pub fn map_winding(winding: wgt::FrontFace) -> MTLWinding { + match winding { + wgt::FrontFace::Cw => MTLWinding::Clockwise, + wgt::FrontFace::Ccw => MTLWinding::CounterClockwise, + } +} + +pub fn map_cull_mode(face: Option<wgt::Face>) -> MTLCullMode { + match face { + None => MTLCullMode::None, + Some(wgt::Face::Front) => MTLCullMode::Front, + Some(wgt::Face::Back) => MTLCullMode::Back, + } +} + +pub fn map_range(range: &crate::MemoryRange) -> NSRange { + NSRange { + location: range.start as usize, + length: (range.end - range.start) as usize, + } +} + +pub fn map_copy_extent(extent: &crate::CopyExtent) -> MTLSize { + MTLSize { + width: extent.width as usize, + height: extent.height as usize, + depth: extent.depth as usize, + } +} + +pub fn map_origin(origin: &wgt::Origin3d) -> MTLOrigin { + MTLOrigin { + x: origin.x as usize, + y: origin.y as usize, + z: origin.z as usize, + } +} + +pub fn map_store_action(store: bool, resolve: bool) -> MTLStoreAction { + use MTLStoreAction as MTL; + match (store, resolve) { + (true, true) => MTL::StoreAndMultisampleResolve, + (false, true) => MTL::MultisampleResolve, + (true, false) => MTL::Store, + (false, false) => MTL::DontCare, + } +} + +pub fn map_clear_color(color: &wgt::Color) -> MTLClearColor { + MTLClearColor { + red: color.r, + green: color.g, + blue: color.b, + alpha: color.a, + } +} + +pub fn get_blit_option(format: wgt::TextureFormat, aspect: crate::FormatAspects) -> MTLBlitOption { + if format.is_combined_depth_stencil_format() { + match aspect { + crate::FormatAspects::DEPTH => MTLBlitOption::DepthFromDepthStencil, + crate::FormatAspects::STENCIL => MTLBlitOption::StencilFromDepthStencil, + _ => unreachable!(), + } + } else { + MTLBlitOption::None + } +} + +pub fn map_render_stages(stage: wgt::ShaderStages) -> MTLRenderStages { + let mut raw_stages = MTLRenderStages::empty(); + + if stage.contains(wgt::ShaderStages::VERTEX) { + raw_stages |= MTLRenderStages::Vertex; + } + if stage.contains(wgt::ShaderStages::FRAGMENT) { + raw_stages |= MTLRenderStages::Fragment; + } + + raw_stages +} + +pub fn map_resource_usage(ty: &wgt::BindingType) -> MTLResourceUsage { + match ty { + #[allow(deprecated)] + wgt::BindingType::Texture { .. } => MTLResourceUsage::Sample, + wgt::BindingType::StorageTexture { access, .. } => match access { + wgt::StorageTextureAccess::WriteOnly => MTLResourceUsage::Write, + wgt::StorageTextureAccess::ReadOnly => MTLResourceUsage::Read, + wgt::StorageTextureAccess::Atomic | wgt::StorageTextureAccess::ReadWrite => { + MTLResourceUsage::Read | MTLResourceUsage::Write + } + }, + wgt::BindingType::Sampler(..) => MTLResourceUsage::empty(), + wgt::BindingType::Buffer { ty, .. } => match ty { + wgt::BufferBindingType::Uniform + | wgt::BufferBindingType::Storage { read_only: true } => MTLResourceUsage::Read, + wgt::BufferBindingType::Storage { read_only: false } => { + MTLResourceUsage::Read | MTLResourceUsage::Write + } + }, + _ => unreachable!(), + } +} + +pub fn map_acceleration_structure_descriptor<'a>( + entries: &'a crate::AccelerationStructureEntries<'a, super::Buffer>, + flags: crate::AccelerationStructureBuildFlags, +) -> Retained<MTLAccelerationStructureDescriptor> { + let descriptor = match entries { + crate::AccelerationStructureEntries::Instances(instances) => { + let descriptor = MTLInstanceAccelerationStructureDescriptor::new(); + descriptor.setInstanceDescriptorType( + MTLAccelerationStructureInstanceDescriptorType::Indirect, + ); + descriptor.setInstanceCount(instances.count as usize); + descriptor.setInstanceDescriptorBuffer(Some(&instances.buffer.unwrap().raw)); + unsafe { + descriptor.setInstanceDescriptorBufferOffset(instances.offset as usize); + } + descriptor.into_super() + } + crate::AccelerationStructureEntries::Triangles(entries) => { + let geometry_descriptors = entries + .iter() + .map(|triangles| { + let descriptor = MTLAccelerationStructureTriangleGeometryDescriptor::new(); + if let Some(indices) = triangles.indices.as_ref() { + descriptor.setIndexBuffer(Some(&indices.buffer.unwrap().raw)); + unsafe { + descriptor.setIndexBufferOffset(indices.offset as usize); + } + descriptor.setIndexType(map_index_format(indices.format).1); + descriptor.setTriangleCount(indices.count as usize / 3); + } else { + descriptor.setTriangleCount(triangles.vertex_count as usize / 3); + } + descriptor.setVertexBuffer(Some(&triangles.vertex_buffer.unwrap().raw)); + unsafe { + descriptor.setVertexBufferOffset( + triangles.first_vertex as usize * triangles.vertex_stride as usize, + ); + } + descriptor.setVertexStride(triangles.vertex_stride as usize); + // Safety: MTLVertexFormat and MTLAttributeFormat are identical. + // https://docs.rs/objc2-metal/latest/objc2_metal/struct.MTLAttributeFormat.html + // https://docs.rs/objc2-metal/latest/objc2_metal/struct.MTLVertexFormat.html + descriptor.setVertexFormat(unsafe { + core::mem::transmute::<MTLVertexFormat, MTLAttributeFormat>( + map_vertex_format(triangles.vertex_format), + ) + }); + if let Some(transform) = triangles.transform.as_ref() { + unsafe { + descriptor.setTransformationMatrixBuffer(Some(&transform.buffer.raw)); + descriptor + .setTransformationMatrixBufferOffset(transform.offset as usize); + } + } + descriptor.setOpaque( + triangles + .flags + .contains(wgt::AccelerationStructureGeometryFlags::OPAQUE), + ); + if !triangles.flags.contains( + wgt::AccelerationStructureGeometryFlags::NO_DUPLICATE_ANY_HIT_INVOCATION, + ) { + descriptor.allowDuplicateIntersectionFunctionInvocation(); + } + // descriptor.setIntersectionFunctionTableOffset(offset); + descriptor.into_super() + }) + .collect::<alloc::vec::Vec<Retained<MTLAccelerationStructureGeometryDescriptor>>>(); + let descriptor = MTLPrimitiveAccelerationStructureDescriptor::new(); + descriptor.setGeometryDescriptors(Some(&NSArray::from_retained_slice( + geometry_descriptors.as_slice(), + ))); + descriptor.into_super() + } + crate::AccelerationStructureEntries::AABBs(entries) => { + let geometry_descriptors = entries + .iter() + .map(|aabbs| { + let descriptor = MTLAccelerationStructureBoundingBoxGeometryDescriptor::new(); + descriptor.setBoundingBoxBuffer(Some(&aabbs.buffer.unwrap().raw)); + descriptor.setBoundingBoxCount(aabbs.count as usize); + unsafe { + descriptor.setBoundingBoxStride(aabbs.stride as usize); + descriptor.setBoundingBoxBufferOffset(aabbs.offset as usize); + } + descriptor.setOpaque( + aabbs + .flags + .contains(wgt::AccelerationStructureGeometryFlags::OPAQUE), + ); + if !aabbs.flags.contains( + wgt::AccelerationStructureGeometryFlags::NO_DUPLICATE_ANY_HIT_INVOCATION, + ) { + descriptor.allowDuplicateIntersectionFunctionInvocation(); + } + // descriptor.setIntersectionFunctionTableOffset(offset); + descriptor.into_super() + }) + .collect::<alloc::vec::Vec<Retained<MTLAccelerationStructureGeometryDescriptor>>>(); + let descriptor = MTLPrimitiveAccelerationStructureDescriptor::new(); + descriptor.setGeometryDescriptors(Some(&NSArray::from_retained_slice( + geometry_descriptors.as_slice(), + ))); + descriptor.into_super() + } + }; + let mut usage = MTLAccelerationStructureUsage::None; + if flags.contains(wgt::AccelerationStructureFlags::ALLOW_UPDATE) { + usage |= MTLAccelerationStructureUsage::Refit; + } + if flags.contains(wgt::AccelerationStructureFlags::PREFER_FAST_BUILD) { + usage |= MTLAccelerationStructureUsage::PreferFastBuild; + } + descriptor.setUsage(usage); + descriptor +} diff --git a/app/vendor/rune/vendor/wgpu-hal/src/metal/device.rs b/app/vendor/rune/vendor/wgpu-hal/src/metal/device.rs new file mode 100644 index 0000000..d7287b9 --- /dev/null +++ b/app/vendor/rune/vendor/wgpu-hal/src/metal/device.rs @@ -0,0 +1,2170 @@ +use alloc::{borrow::ToOwned as _, sync::Arc, vec::Vec}; +use core::{mem::align_of, ptr::NonNull}; + +use bytemuck::TransparentWrapper; +use objc2::{ + available, + rc::{autoreleasepool, Retained}, + runtime::ProtocolObject, +}; +use objc2_foundation::{ns_string, NSError, NSRange, NSString, NSUInteger}; +use objc2_metal::{ + MTLAccelerationStructure, MTLAccelerationStructureInstanceOptions, MTLBuffer, + MTLCaptureManager, MTLCaptureScope, MTLCompileOptions, MTLComputePipelineDescriptor, + MTLComputePipelineState, MTLCounterSampleBufferDescriptor, MTLCounterSet, MTLDepthClipMode, + MTLDepthStencilDescriptor, MTLDevice, MTLFunction, + MTLIndirectAccelerationStructureInstanceDescriptor, MTLLanguageVersion, MTLLibrary, + MTLMeshRenderPipelineDescriptor, MTLMutability, MTLPackedFloat3, MTLPackedFloat4x3, + MTLPipelineBufferDescriptorArray, MTLPipelineOption, MTLPixelFormat, MTLPrimitiveTopologyClass, + MTLRenderPipelineColorAttachmentDescriptorArray, MTLRenderPipelineDescriptor, MTLResource, + MTLResourceID, MTLResourceOptions, MTLSamplerAddressMode, MTLSamplerDescriptor, + MTLSamplerMipFilter, MTLSamplerState, MTLSize, MTLStencilDescriptor, MTLStorageMode, + MTLTexture, MTLTextureDescriptor, MTLTextureType, MTLTriangleFillMode, MTLVertexDescriptor, + MTLVertexStepFunction, +}; +use parking_lot::{Condvar, Mutex, RwLock}; + +use super::{adapter::MAX_BUFFERS, conv, PassthroughShader, ShaderModuleSource}; +use crate::{auxil::map_naga_stage, DropCallback, DropGuard, TlasInstance}; + +type DeviceResult<T> = Result<T, crate::DeviceError>; + +/// True on arm64_32 (watchOS ILP32) targets. +/// +/// There are no Apple OSes that support both 32-bit applications and Metal, +/// so `target_pointer_width = "32"` is a reliable proxy for ILP32 watchOS +/// devices (Apple Watch S4–S9, SE, Ultra). Several AGXMetalS4 driver bugs +/// require workarounds gated on this flag. +const IS_WATCHOS_ILP32: bool = cfg!(target_pointer_width = "32"); + +struct CompiledShader { + library: Retained<ProtocolObject<dyn MTLLibrary>>, + function: Retained<ProtocolObject<dyn MTLFunction>>, + wg_size: MTLSize, + wg_memory_sizes: Vec<u32>, + + /// Bindings of WGSL `storage` globals that contain variable-sized arrays, + /// paired with a binding-array element index when applicable. + /// + /// In order to implement bounds checks and the `arrayLength` function for + /// WGSL runtime-sized arrays, we pass the entry point a struct with a + /// `u32` member for each such binding. For ordinary storage buffers the + /// element index is zero; for storage binding arrays there is one entry per + /// layout element. Each member holds that element's total size in bytes--- + /// the size of the `Buffer` supplying its contents for the draw or dispatch. + sized_bindings: Vec<(naga::ResourceBinding, u32)>, + + immutable_buffer_mask: usize, +} + +fn create_stencil_desc( + face: &wgt::StencilFaceState, + read_mask: u32, + write_mask: u32, +) -> Retained<MTLStencilDescriptor> { + let desc = MTLStencilDescriptor::new(); + desc.setStencilCompareFunction(conv::map_compare_function(face.compare)); + desc.setReadMask(read_mask); + desc.setWriteMask(write_mask); + desc.setStencilFailureOperation(conv::map_stencil_op(face.fail_op)); + desc.setDepthFailureOperation(conv::map_stencil_op(face.depth_fail_op)); + desc.setDepthStencilPassOperation(conv::map_stencil_op(face.pass_op)); + desc +} + +fn create_depth_stencil_desc( + state: &wgt::DepthStencilState, +) -> Retained<MTLDepthStencilDescriptor> { + let desc = MTLDepthStencilDescriptor::new(); + desc.setDepthCompareFunction(conv::map_compare_function( + state.depth_compare.unwrap_or_default(), + )); + desc.setDepthWriteEnabled(state.depth_write_enabled.unwrap_or_default()); + let s = &state.stencil; + if s.is_enabled() { + let front_desc = create_stencil_desc(&s.front, s.read_mask, s.write_mask); + desc.setFrontFaceStencil(Some(&front_desc)); + let back_desc = create_stencil_desc(&s.back, s.read_mask, s.write_mask); + desc.setBackFaceStencil(Some(&back_desc)); + } + desc +} + +#[allow( + clippy::mut_from_ref, + reason = "MTLBuffer shared contents are writable through `&MTLBuffer`" +)] +fn bindless_id_table_mut( + buffer: &ProtocolObject<dyn MTLBuffer>, + count: u32, +) -> &mut [MTLResourceID] { + let ptr = buffer.contents().cast::<u8>().as_ptr(); + // SAFETY: The buffer is aligned to the size of `MTLResourceID`. + assert_eq!(ptr as usize % align_of::<MTLResourceID>(), 0); + let ptr = ptr.cast::<MTLResourceID>(); + unsafe { core::slice::from_raw_parts_mut(ptr, count as usize) } +} + +const fn convert_vertex_format_to_naga(format: wgt::VertexFormat) -> nt::VertexFormat { + match format { + wgt::VertexFormat::Uint8 => nt::VertexFormat::Uint8, + wgt::VertexFormat::Uint8x2 => nt::VertexFormat::Uint8x2, + wgt::VertexFormat::Uint8x4 => nt::VertexFormat::Uint8x4, + wgt::VertexFormat::Sint8 => nt::VertexFormat::Sint8, + wgt::VertexFormat::Sint8x2 => nt::VertexFormat::Sint8x2, + wgt::VertexFormat::Sint8x4 => nt::VertexFormat::Sint8x4, + wgt::VertexFormat::Unorm8 => nt::VertexFormat::Unorm8, + wgt::VertexFormat::Unorm8x2 => nt::VertexFormat::Unorm8x2, + wgt::VertexFormat::Unorm8x4 => nt::VertexFormat::Unorm8x4, + wgt::VertexFormat::Snorm8 => nt::VertexFormat::Snorm8, + wgt::VertexFormat::Snorm8x2 => nt::VertexFormat::Snorm8x2, + wgt::VertexFormat::Snorm8x4 => nt::VertexFormat::Snorm8x4, + wgt::VertexFormat::Uint16 => nt::VertexFormat::Uint16, + wgt::VertexFormat::Uint16x2 => nt::VertexFormat::Uint16x2, + wgt::VertexFormat::Uint16x4 => nt::VertexFormat::Uint16x4, + wgt::VertexFormat::Sint16 => nt::VertexFormat::Sint16, + wgt::VertexFormat::Sint16x2 => nt::VertexFormat::Sint16x2, + wgt::VertexFormat::Sint16x4 => nt::VertexFormat::Sint16x4, + wgt::VertexFormat::Unorm16 => nt::VertexFormat::Unorm16, + wgt::VertexFormat::Unorm16x2 => nt::VertexFormat::Unorm16x2, + wgt::VertexFormat::Unorm16x4 => nt::VertexFormat::Unorm16x4, + wgt::VertexFormat::Snorm16 => nt::VertexFormat::Snorm16, + wgt::VertexFormat::Snorm16x2 => nt::VertexFormat::Snorm16x2, + wgt::VertexFormat::Snorm16x4 => nt::VertexFormat::Snorm16x4, + wgt::VertexFormat::Float16 => nt::VertexFormat::Float16, + wgt::VertexFormat::Float16x2 => nt::VertexFormat::Float16x2, + wgt::VertexFormat::Float16x4 => nt::VertexFormat::Float16x4, + wgt::VertexFormat::Float32 => nt::VertexFormat::Float32, + wgt::VertexFormat::Float32x2 => nt::VertexFormat::Float32x2, + wgt::VertexFormat::Float32x3 => nt::VertexFormat::Float32x3, + wgt::VertexFormat::Float32x4 => nt::VertexFormat::Float32x4, + wgt::VertexFormat::Uint32 => nt::VertexFormat::Uint32, + wgt::VertexFormat::Uint32x2 => nt::VertexFormat::Uint32x2, + wgt::VertexFormat::Uint32x3 => nt::VertexFormat::Uint32x3, + wgt::VertexFormat::Uint32x4 => nt::VertexFormat::Uint32x4, + wgt::VertexFormat::Sint32 => nt::VertexFormat::Sint32, + wgt::VertexFormat::Sint32x2 => nt::VertexFormat::Sint32x2, + wgt::VertexFormat::Sint32x3 => nt::VertexFormat::Sint32x3, + wgt::VertexFormat::Sint32x4 => nt::VertexFormat::Sint32x4, + wgt::VertexFormat::Unorm10_10_10_2 => nt::VertexFormat::Unorm10_10_10_2, + wgt::VertexFormat::Unorm8x4Bgra => nt::VertexFormat::Unorm8x4Bgra, + + wgt::VertexFormat::Float64 + | wgt::VertexFormat::Float64x2 + | wgt::VertexFormat::Float64x3 + | wgt::VertexFormat::Float64x4 => { + unimplemented!() + } + } +} + +impl super::Device { + fn load_shader( + &self, + stage: &crate::ProgrammableStage<super::ShaderModule>, + vertex_buffer_mappings: &[naga::back::msl::VertexBufferMapping], + layout: &super::PipelineLayout, + primitive_class: MTLPrimitiveTopologyClass, + naga_stage: naga::ShaderStage, + ) -> Result<CompiledShader, crate::PipelineError> { + match stage.module.source { + ShaderModuleSource::Naga(ref naga_shader) => { + let stage_bit = map_naga_stage(naga_stage); + let (module, module_info) = naga::back::pipeline_constants::process_overrides( + &naga_shader.module, + &naga_shader.info, + Some((naga_stage, stage.entry_point)), + stage.constants, + ) + .map_err(|e| { + crate::PipelineError::PipelineConstants(stage_bit, format!("MSL: {e:?}")) + })?; + + let ep_resources = &layout.per_stage_map[naga_stage]; + + let bounds_check_policy = if stage.module.runtime_checks.bounds_checks { + naga::proc::BoundsCheckPolicy::Restrict + } else { + naga::proc::BoundsCheckPolicy::Unchecked + }; + + let options = naga::back::msl::Options { + lang_version: match self.shared.private_caps.msl_version { + #[allow(deprecated)] + MTLLanguageVersion::Version1_0 => (1, 0), + MTLLanguageVersion::Version1_1 => (1, 1), + MTLLanguageVersion::Version1_2 => (1, 2), + MTLLanguageVersion::Version2_0 => (2, 0), + MTLLanguageVersion::Version2_1 => (2, 1), + MTLLanguageVersion::Version2_2 => (2, 2), + MTLLanguageVersion::Version2_3 => (2, 3), + MTLLanguageVersion::Version2_4 => (2, 4), + MTLLanguageVersion::Version3_0 => (3, 0), + MTLLanguageVersion::Version3_1 => (3, 1), + MTLLanguageVersion::Version3_2 => (3, 2), + MTLLanguageVersion::Version4_0 => (4, 0), + // Newer version, fall back to 3.2 + _ => (4, 0), + }, + inline_samplers: Default::default(), + spirv_cross_compatibility: false, + fake_missing_bindings: false, + per_entry_point_map: naga::back::msl::EntryPointResourceMap::from([( + stage.entry_point.to_owned(), + ep_resources.clone(), + )]), + bounds_check_policies: naga::proc::BoundsCheckPolicies { + index: bounds_check_policy, + buffer: bounds_check_policy, + image_load: bounds_check_policy, + // TODO: support bounds checks on binding arrays + binding_array: naga::proc::BoundsCheckPolicy::Unchecked, + }, + zero_initialize_workgroup_memory: stage.zero_initialize_workgroup_memory, + force_loop_bounding: stage.module.runtime_checks.force_loop_bounding, + task_dispatch_limits: stage + .module + .runtime_checks + .task_shader_dispatch_tracking + .then_some(naga::back::TaskDispatchLimits { + max_mesh_workgroups_per_dim: self + .limits + .max_mesh_workgroups_per_dimension, + max_mesh_workgroups_total: self.limits.max_mesh_workgroup_total_count, + }), + mesh_shader_primitive_indices_clamp: stage + .module + .runtime_checks + .mesh_shader_primitive_indices_clamp, + emit_int_div_checks: stage.module.runtime_checks.int_div_checks, + ray_query_initialization_tracking: stage + .module + .runtime_checks + .ray_query_initialization_tracking, + }; + + let pipeline_options = naga::back::msl::PipelineOptions { + entry_point: Some((naga_stage, stage.entry_point.to_owned())), + allow_and_force_point_size: match primitive_class { + MTLPrimitiveTopologyClass::Point => true, + _ => false, + }, + vertex_pulling_transform: true, + vertex_buffer_mappings: vertex_buffer_mappings.to_vec(), + binding_array_length_map: layout.binding_array_length_map.clone(), + }; + + let (source, info) = naga::back::msl::write_string( + &module, + &module_info, + &options, + &pipeline_options, + ) + .map_err(|e| crate::PipelineError::Linkage(stage_bit, format!("MSL: {e:?}")))?; + + log::debug!( + "Naga generated shader for entry point '{}' and stage {:?}\n{}", + stage.entry_point, + naga_stage, + &source + ); + + let options = MTLCompileOptions::new(); + options.setLanguageVersion(self.shared.private_caps.msl_version); + + // https://developer.apple.com/documentation/metal/mtlcompileoptions/preserveinvariance + if available!(macos = 11.0, ios = 13.0, tvos = 14.0, visionos = 1.0) { + options.setPreserveInvariance(true); + } + + let library = self + .shared + .device + .newLibraryWithSource_options_error( + &NSString::from_str(&source), + Some(&options), + ) + .map_err(|err| { + log::debug!("Naga generated shader:\n{source}"); + crate::PipelineError::Linkage(stage_bit, format!("Metal: {err}")) + })?; + + let ep_index = module + .entry_points + .iter() + .position(|ep| ep.stage == naga_stage && ep.name == stage.entry_point) + .ok_or(crate::PipelineError::EntryPoint(naga_stage))?; + let ep = &module.entry_points[ep_index]; + let translated_ep_name = info.entry_point_names[0] + .as_ref() + .map_err(|e| crate::PipelineError::Linkage(stage_bit, format!("{e}")))?; + + let wg_size = MTLSize { + width: ep.workgroup_size[0] as _, + height: ep.workgroup_size[1] as _, + depth: ep.workgroup_size[2] as _, + }; + + let function = library + .newFunctionWithName(&NSString::from_str(translated_ep_name)) + .ok_or_else(|| { + log::error!("Function '{translated_ep_name}' does not exist"); + crate::PipelineError::EntryPoint(naga_stage) + })?; + + // collect sizes indices, immutable buffers, and work group memory sizes + let ep_info = &module_info.get_entry_point(ep_index); + let mut wg_memory_sizes = Vec::new(); + let mut sized_bindings = Vec::new(); + let mut immutable_buffer_mask = 0; + for (var_handle, var) in module.global_variables.iter() { + match var.space { + naga::AddressSpace::WorkGroup => { + if !ep_info[var_handle].is_empty() { + let size = module.types[var.ty].inner.size(module.to_ctx()); + wg_memory_sizes.push(size); + } + } + naga::AddressSpace::Uniform | naga::AddressSpace::Storage { .. } => { + let br = match var.binding { + Some(br) => br, + None => continue, + }; + let storage_access_store = match var.space { + naga::AddressSpace::Storage { access } => { + access.contains(naga::StorageAccess::STORE) + } + _ => false, + }; + + // check for an immutable buffer + if !ep_info[var_handle].is_empty() && !storage_access_store { + let slot = ep_resources.resources[&br].buffer.unwrap(); + immutable_buffer_mask |= 1 << slot; + } + + if module.types[var.ty] + .inner + .needs_host_buffer_byte_size(&module.types) + { + let n = match module.types[var.ty].inner { + naga::TypeInner::BindingArray { size, .. } => { + let from_shader = match size { + naga::ArraySize::Constant(n) => n.get(), + naga::ArraySize::Pending(_) + | naga::ArraySize::Dynamic => 0, + }; + let from_layout = layout + .binding_array_length_map + .get(&br) + .copied() + .unwrap_or(0); + from_shader.max(from_layout).max(1) + } + _ => 1, + }; + sized_bindings.extend((0..n).map(|i| (br, i))); + } + } + _ => {} + } + } + + Ok(CompiledShader { + library, + function, + wg_size, + wg_memory_sizes, + sized_bindings, + immutable_buffer_mask, + }) + } + ShaderModuleSource::Passthrough(ref shader) => { + let size = shader.num_workgroups[stage.entry_point]; + Ok(CompiledShader { + library: shader.library.clone(), + function: shader + .library + .newFunctionWithName(&NSString::from_str(stage.entry_point)) + .ok_or(crate::PipelineError::EntryPoint(naga_stage))?, + wg_size: MTLSize { + width: size.0 as usize, + height: size.1 as usize, + depth: size.2 as usize, + }, + wg_memory_sizes: vec![], + sized_bindings: vec![], + immutable_buffer_mask: 0, + }) + } + } + } + + fn set_buffers_mutability( + buffers: &MTLPipelineBufferDescriptorArray, + mut immutable_mask: usize, + ) { + while immutable_mask != 0 { + let slot = immutable_mask.trailing_zeros(); + immutable_mask ^= 1 << slot; + unsafe { buffers.objectAtIndexedSubscript(slot as usize) } + .setMutability(MTLMutability::Immutable); + } + } + + pub unsafe fn texture_from_raw( + raw: Retained<ProtocolObject<dyn MTLTexture>>, + format: wgt::TextureFormat, + raw_type: MTLTextureType, + array_layers: u32, + mip_levels: u32, + copy_size: crate::CopyExtent, + drop_callback: Option<DropCallback>, + ) -> super::Texture { + super::Texture { + raw, + format, + raw_type, + array_layers, + mip_levels, + copy_size, + _drop_guard: DropGuard::from_option(drop_callback), + } + } + + pub unsafe fn device_from_raw( + raw: Retained<ProtocolObject<dyn MTLDevice>>, + features: wgt::Features, + limits: &wgt::Limits, + ) -> super::Device { + let capabilities_query = super::CapabilitiesQuery::new(&raw); + let shared = super::AdapterShared::new(raw, &capabilities_query); + super::Device { + shared: Arc::new(shared), + features, + counters: Default::default(), + limits: limits.clone(), + } + } + + pub unsafe fn buffer_from_raw( + raw: Retained<ProtocolObject<dyn MTLBuffer>>, + size: wgt::BufferAddress, + ) -> super::Buffer { + super::Buffer { raw, size } + } + + pub fn raw_device(&self) -> &Retained<ProtocolObject<dyn MTLDevice>> { + &self.shared.device + } +} + +impl crate::Device for super::Device { + type A = super::Api; + + unsafe fn create_buffer(&self, desc: &crate::BufferDescriptor) -> DeviceResult<super::Buffer> { + let map_read = desc.usage.contains(wgt::BufferUses::MAP_READ); + let map_write = desc.usage.contains(wgt::BufferUses::MAP_WRITE); + + let mut options = MTLResourceOptions::empty(); + options |= if map_read || map_write { + // `crate::MemoryFlags::PREFER_COHERENT` is ignored here + MTLResourceOptions::StorageModeShared + } else { + MTLResourceOptions::StorageModePrivate + }; + options.set(MTLResourceOptions::CPUCacheModeWriteCombined, map_write); + + //TODO: HazardTrackingModeUntracked + + autoreleasepool(|_| { + let raw = self + .shared + .device + .newBufferWithLength_options(desc.size as usize, options) + .ok_or(crate::DeviceError::OutOfMemory)?; + if let Some(label) = desc.label { + raw.setLabel(Some(&NSString::from_str(label))); + } + self.counters.buffers.add(1); + Ok(super::Buffer { + raw, + size: desc.size, + }) + }) + } + unsafe fn destroy_buffer(&self, _buffer: super::Buffer) { + self.counters.buffers.sub(1); + } + + unsafe fn add_raw_buffer(&self, _buffer: &super::Buffer) { + self.counters.buffers.add(1); + } + + unsafe fn map_buffer( + &self, + buffer: &super::Buffer, + range: crate::MemoryRange, + ) -> DeviceResult<crate::BufferMapping> { + let ptr = buffer.raw.contents().cast::<u8>(); + Ok(crate::BufferMapping { + ptr: NonNull::new(unsafe { ptr.as_ptr().offset(range.start as isize) }).unwrap(), + is_coherent: true, + }) + } + + unsafe fn unmap_buffer(&self, _buffer: &super::Buffer) {} + unsafe fn flush_mapped_ranges<I>(&self, _buffer: &super::Buffer, _ranges: I) {} + unsafe fn invalidate_mapped_ranges<I>(&self, _buffer: &super::Buffer, _ranges: I) {} + + unsafe fn create_texture( + &self, + desc: &crate::TextureDescriptor, + ) -> DeviceResult<super::Texture> { + let mtl_format = self + .shared + .private_texture_format_caps + .map_format(desc.format); + + autoreleasepool(|_| { + let descriptor = MTLTextureDescriptor::new(); + + let mtl_type = match desc.dimension { + wgt::TextureDimension::D1 => MTLTextureType::Type1D, + wgt::TextureDimension::D2 => { + if desc.sample_count > 1 { + unsafe { descriptor.setSampleCount(desc.sample_count as usize) }; + + if desc.size.depth_or_array_layers > 1 { + unsafe { + descriptor.setArrayLength(desc.size.depth_or_array_layers as usize) + }; + MTLTextureType::Type2DMultisampleArray + } else { + MTLTextureType::Type2DMultisample + } + } else if desc.size.depth_or_array_layers > 1 { + unsafe { + descriptor.setArrayLength(desc.size.depth_or_array_layers as usize) + }; + MTLTextureType::Type2DArray + } else { + MTLTextureType::Type2D + } + } + wgt::TextureDimension::D3 => { + unsafe { descriptor.setDepth(desc.size.depth_or_array_layers as usize) }; + MTLTextureType::Type3D + } + }; + + let mtl_storage_mode = if desc.usage.contains(wgt::TextureUses::TRANSIENT) + && self.shared.private_caps.supports_memoryless_storage + { + MTLStorageMode::Memoryless + } else if IS_WATCHOS_ILP32 { + // The AGXMetalS4 driver (A13/S6 GPU) crashes in + // copyFromTexture:toBuffer: on Private textures — null deref at + // offset 0x50 in the driver's internal texture state. Use Shared + // storage which works correctly on Apple's unified memory + // architecture and matches what native Swift Metal code uses on + // these devices. + MTLStorageMode::Shared + } else { + MTLStorageMode::Private + }; + + descriptor.setTextureType(mtl_type); + unsafe { descriptor.setWidth(desc.size.width as usize) }; + unsafe { descriptor.setHeight(desc.size.height as usize) }; + unsafe { descriptor.setMipmapLevelCount(desc.mip_level_count as usize) }; + descriptor.setPixelFormat(mtl_format); + descriptor.setUsage(conv::map_texture_usage(desc.format, desc.usage)); + descriptor.setStorageMode(mtl_storage_mode); + + let raw = self + .shared + .device + .newTextureWithDescriptor(&descriptor) + .ok_or(crate::DeviceError::OutOfMemory)?; + if let Some(label) = desc.label { + raw.setLabel(Some(&NSString::from_str(label))); + } + + self.counters.textures.add(1); + + Ok(super::Texture { + raw, + format: desc.format, + raw_type: mtl_type, + mip_levels: desc.mip_level_count, + array_layers: desc.array_layer_count(), + copy_size: desc.copy_extent(), + _drop_guard: None, + }) + }) + } + + unsafe fn destroy_texture(&self, _texture: super::Texture) { + self.counters.textures.sub(1); + } + + unsafe fn add_raw_texture(&self, _texture: &super::Texture) { + self.counters.textures.add(1); + } + + unsafe fn create_texture_view( + &self, + texture: &super::Texture, + desc: &crate::TextureViewDescriptor, + ) -> DeviceResult<super::TextureView> { + let raw_type = if texture.raw_type == MTLTextureType::Type2DMultisample + || texture.raw_type == MTLTextureType::Type2DMultisampleArray + { + texture.raw_type + } else { + conv::map_texture_view_dimension(desc.dimension) + }; + + let aspects = crate::FormatAspects::new(texture.format, desc.range.aspect); + + let raw_format = self + .shared + .private_texture_format_caps + .map_view_format(desc.format, aspects); + + let format_equal = raw_format + == self + .shared + .private_texture_format_caps + .map_format(texture.format); + let type_equal = raw_type == texture.raw_type; + let range_full_resource = + desc.range + .is_full_resource(desc.format, texture.mip_levels, texture.array_layers); + + let raw = if format_equal && type_equal && range_full_resource { + // Some images are marked as framebuffer-only, and we can't create aliases of them. + // Also helps working around Metal bugs with aliased array textures. + texture.raw.to_owned() + } else { + let mip_level_count = desc + .range + .mip_level_count + .unwrap_or(texture.mip_levels - desc.range.base_mip_level); + let array_layer_count = desc + .range + .array_layer_count + .unwrap_or(texture.array_layers - desc.range.base_array_layer); + + autoreleasepool(|_| { + let level_range = NSRange { + location: desc.range.base_mip_level as _, + length: mip_level_count as _, + }; + let slice_range = NSRange { + location: desc.range.base_array_layer as _, + length: array_layer_count as _, + }; + let raw = unsafe { + texture + .raw + .newTextureViewWithPixelFormat_textureType_levels_slices( + raw_format, + raw_type, + level_range, + slice_range, + ) + .unwrap() + }; + if let Some(label) = desc.label { + raw.setLabel(Some(&NSString::from_str(label))); + } + raw + }) + }; + + self.counters.texture_views.add(1); + + Ok(super::TextureView { raw, aspects }) + } + + unsafe fn destroy_texture_view(&self, _view: super::TextureView) { + self.counters.texture_views.sub(1); + } + + unsafe fn create_sampler( + &self, + desc: &crate::SamplerDescriptor, + ) -> DeviceResult<super::Sampler> { + autoreleasepool(|_| { + let descriptor = MTLSamplerDescriptor::new(); + + descriptor.setMinFilter(conv::map_filter_mode(desc.min_filter)); + descriptor.setMagFilter(conv::map_filter_mode(desc.mag_filter)); + descriptor.setMipFilter(match desc.mipmap_filter { + wgt::MipmapFilterMode::Nearest if desc.lod_clamp == (0.0..0.0) => { + MTLSamplerMipFilter::NotMipmapped + } + wgt::MipmapFilterMode::Nearest => MTLSamplerMipFilter::Nearest, + wgt::MipmapFilterMode::Linear => MTLSamplerMipFilter::Linear, + }); + + let [s, t, r] = desc.address_modes; + descriptor.setSAddressMode(conv::map_address_mode(s)); + descriptor.setTAddressMode(conv::map_address_mode(t)); + descriptor.setRAddressMode(conv::map_address_mode(r)); + + // Anisotropy is always supported on mac up to 16x + descriptor.setMaxAnisotropy(desc.anisotropy_clamp as _); + + descriptor.setLodMinClamp(desc.lod_clamp.start); + descriptor.setLodMaxClamp(desc.lod_clamp.end); + + if let Some(fun) = desc.compare { + descriptor.setCompareFunction(conv::map_compare_function(fun)); + } + + if let Some(border_color) = desc.border_color { + if let wgt::SamplerBorderColor::Zero = border_color { + if s == wgt::AddressMode::ClampToBorder { + descriptor.setSAddressMode(MTLSamplerAddressMode::ClampToZero); + } + + if t == wgt::AddressMode::ClampToBorder { + descriptor.setTAddressMode(MTLSamplerAddressMode::ClampToZero); + } + + if r == wgt::AddressMode::ClampToBorder { + descriptor.setRAddressMode(MTLSamplerAddressMode::ClampToZero); + } + } else { + descriptor.setBorderColor(conv::map_border_color(border_color)); + } + } + + if let Some(label) = desc.label { + descriptor.setLabel(Some(&NSString::from_str(label))); + } + if self.features.contains(wgt::Features::TEXTURE_BINDING_ARRAY) { + descriptor.setSupportArgumentBuffers(true); + } + let raw = self + .shared + .device + .newSamplerStateWithDescriptor(&descriptor) + .unwrap(); + + self.counters.samplers.add(1); + + Ok(super::Sampler { raw }) + }) + } + unsafe fn destroy_sampler(&self, _sampler: super::Sampler) { + self.counters.samplers.sub(1); + } + + unsafe fn create_command_encoder( + &self, + desc: &crate::CommandEncoderDescriptor<super::Queue>, + ) -> Result<super::CommandEncoder, crate::DeviceError> { + self.counters.command_encoders.add(1); + Ok(super::CommandEncoder { + shared: Arc::clone(&self.shared), + queue_shared: Arc::clone(&desc.queue.shared), + raw_cmd_buf: None, + state: super::CommandState::default(), + temp: super::Temp::default(), + counters: Arc::clone(&self.counters), + }) + } + + unsafe fn create_bind_group_layout( + &self, + desc: &crate::BindGroupLayoutDescriptor, + ) -> DeviceResult<super::BindGroupLayout> { + self.counters.bind_group_layouts.add(1); + + Ok(super::BindGroupLayout { + entries: Arc::from(desc.entries), + }) + } + + unsafe fn destroy_bind_group_layout(&self, _bg_layout: super::BindGroupLayout) { + self.counters.bind_group_layouts.sub(1); + } + + unsafe fn create_pipeline_layout( + &self, + desc: &crate::PipelineLayoutDescriptor<super::BindGroupLayout>, + ) -> DeviceResult<super::PipelineLayout> { + #[derive(Debug)] + struct StageInfo { + stage: naga::ShaderStage, + counters: super::ResourceData<super::ResourceIndex>, + pc_buffer: Option<super::ResourceIndex>, + pc_limit: u32, + sizes_buffer: Option<super::ResourceIndex>, + need_sizes_buffer: bool, + resources: naga::back::msl::BindingMap, + } + + let mut stage_data = super::NAGA_STAGES.map(|stage| StageInfo { + stage, + counters: super::ResourceData::default(), + pc_buffer: None, + pc_limit: 0, + sizes_buffer: None, + need_sizes_buffer: false, + resources: Default::default(), + }); + let mut bind_group_infos = [const { None }; crate::MAX_BIND_GROUPS]; + let mut binding_array_length_map = naga::FastHashMap::default(); + + // First, place the immediates + for info in stage_data.iter_mut() { + info.pc_limit = desc.immediate_size; + + // handle the immediate data buffer assignment and shader overrides + if info.pc_limit != 0 { + info.pc_buffer = Some(info.counters.buffers); + info.counters.buffers += 1; + } + } + + // Second, place the described resources + for (group_index, bgl) in desc.bind_group_layouts.iter().enumerate() { + let Some(bgl) = bgl else { + continue; + }; + + // remember where the resources for this set start at each shader stage + let base_resource_indices = stage_data.map_ref(|info| info.counters.clone()); + + for entry in bgl.entries.iter() { + let br = naga::ResourceBinding { + group: group_index as u32, + binding: entry.binding, + }; + if let Some(count) = entry.count { + if matches!( + entry.ty, + wgt::BindingType::Buffer { + ty: wgt::BufferBindingType::Storage { .. }, + .. + } + ) { + binding_array_length_map.insert(br, count.get()); + } + } + + if let wgt::BindingType::Buffer { + ty: wgt::BufferBindingType::Storage { .. }, + .. + } = entry.ty + { + for info in stage_data.iter_mut() { + if entry.visibility.contains(map_naga_stage(info.stage)) { + info.need_sizes_buffer = true; + } + } + } + + for info in stage_data.iter_mut() { + if !entry.visibility.contains(map_naga_stage(info.stage)) { + continue; + } + + let mut target = naga::back::msl::BindTarget::default(); + // Bindless path + if let Some(_) = entry.count { + target.buffer = Some(info.counters.buffers as _); + info.counters.buffers += 1; + } else { + match entry.ty { + wgt::BindingType::Buffer { ty, .. } => { + target.buffer = Some(info.counters.buffers as _); + info.counters.buffers += 1; + if let wgt::BufferBindingType::Storage { read_only } = ty { + target.mutable = !read_only; + } + } + wgt::BindingType::Sampler { .. } => { + target.sampler = + Some(naga::back::msl::BindSamplerTarget::Resource( + info.counters.samplers as _, + )); + info.counters.samplers += 1; + } + wgt::BindingType::Texture { .. } => { + target.texture = Some(info.counters.textures as _); + info.counters.textures += 1; + } + wgt::BindingType::StorageTexture { access, .. } => { + target.texture = Some(info.counters.textures as _); + info.counters.textures += 1; + target.mutable = match access { + wgt::StorageTextureAccess::ReadOnly => false, + wgt::StorageTextureAccess::WriteOnly => true, + wgt::StorageTextureAccess::ReadWrite => true, + wgt::StorageTextureAccess::Atomic => true, + }; + } + wgt::BindingType::AccelerationStructure { .. } => { + target.buffer = Some(info.counters.buffers as _); + info.counters.buffers += 1; + } + wgt::BindingType::ExternalTexture => { + target.external_texture = + Some(naga::back::msl::BindExternalTextureTarget { + planes: [ + info.counters.textures as _, + (info.counters.textures + 1) as _, + (info.counters.textures + 2) as _, + ], + params: info.counters.buffers as _, + }); + info.counters.textures += 3; + info.counters.buffers += 1; + } + } + } + + info.resources.insert(br, target); + } + } + + bind_group_infos[group_index] = Some(super::BindGroupLayoutInfo { + base_resource_indices, + }); + } + + // Finally, make sure we fit the limits + for info in stage_data.iter_mut() { + if info.need_sizes_buffer || info.stage == naga::ShaderStage::Vertex { + // Set aside space for the sizes_buffer, which is required + // for variable-length buffers, or to support vertex pulling. + info.sizes_buffer = Some(info.counters.buffers); + info.counters.buffers += 1; + } + } + + let immediates_infos = stage_data.map_ref(|info| { + info.pc_buffer.map(|buffer_index| super::ImmediateDataInfo { + count: info.pc_limit, + buffer_index, + }) + }); + + let per_stage_map = stage_data.map(|info| naga::back::msl::EntryPointResources { + immediates_buffer: info + .pc_buffer + .map(|buffer_index| buffer_index as naga::back::msl::Slot), + sizes_buffer: info + .sizes_buffer + .map(|buffer_index| buffer_index as naga::back::msl::Slot), + resources: info.resources, + }); + + self.counters.pipeline_layouts.add(1); + + Ok(super::PipelineLayout { + bind_group_infos, + immediates_infos, + total_immediates: desc.immediate_size, + per_stage_map, + binding_array_length_map, + }) + } + + unsafe fn destroy_pipeline_layout(&self, _pipeline_layout: super::PipelineLayout) { + self.counters.pipeline_layouts.sub(1); + } + + unsafe fn create_bind_group( + &self, + desc: &crate::BindGroupDescriptor< + super::BindGroupLayout, + super::Buffer, + super::Sampler, + super::TextureView, + super::AccelerationStructure, + >, + ) -> DeviceResult<super::BindGroup> { + autoreleasepool(|_| { + let mut bg = super::BindGroup::default(); + for (&stage, counter) in super::NAGA_STAGES.iter().zip(bg.counters.iter_mut()) { + let stage_bit = map_naga_stage(stage); + let mut dynamic_offsets_count = 0u32; + let layout_and_entry_iter = desc.entries.iter().map(|entry| { + let layout = desc + .layout + .entries + .iter() + .find(|layout_entry| layout_entry.binding == entry.binding) + .expect("internal error: no layout entry found with binding slot"); + (entry, layout) + }); + for (entry, layout) in layout_and_entry_iter { + // Bindless path + if layout.count.is_some() { + if !layout.visibility.contains(stage_bit) { + continue; + } + + let count = entry.count; + + let stages = conv::map_render_stages(layout.visibility); + let uses = conv::map_resource_usage(&layout.ty); + + // Create argument buffer for this array + let argument_buffer = self + .shared + .device + .newBufferWithLength_options( + 8 * count as usize, + MTLResourceOptions::HazardTrackingModeUntracked + | MTLResourceOptions::StorageModeShared, + ) + .unwrap(); + + let mut array_element_sizes = Vec::new(); + match layout.ty { + wgt::BindingType::Texture { .. } + | wgt::BindingType::StorageTexture { .. } => { + let resource_ids = + bindless_id_table_mut(argument_buffer.as_ref(), count); + let start = entry.resource_index as usize; + let end = start + count as usize; + let textures = &desc.textures[start..end]; + + for (idx, tex) in textures.iter().enumerate() { + resource_ids[idx] = tex.view.raw.gpuResourceID(); + + let use_info = bg + .resources_to_use + .entry(tex.view.as_raw().cast()) + .or_default(); + use_info.stages |= stages; + use_info.uses |= uses; + use_info.visible_in_compute |= + layout.visibility.contains(wgt::ShaderStages::COMPUTE); + } + } + wgt::BindingType::Sampler { .. } => { + let resource_ids = + bindless_id_table_mut(argument_buffer.as_ref(), count); + let start = entry.resource_index as usize; + let end = start + count as usize; + let samplers = &desc.samplers[start..end]; + + for (idx, &sampler) in samplers.iter().enumerate() { + resource_ids[idx] = sampler.raw.gpuResourceID(); + // Samplers aren't resources like buffers and textures, so don't + // need to be passed to useResource + } + } + wgt::BindingType::Buffer { ty, .. } => { + let start = entry.resource_index as usize; + let end = start + count as usize; + let buffers = &desc.buffers[start..end]; + let pointers = argument_buffer.contents().cast::<u64>(); + for (idx, source) in buffers.iter().enumerate() { + let addr = source.buffer.raw.gpuAddress() + source.offset; + unsafe { + pointers.add(idx).write(addr); + } + + if let wgt::BufferBindingType::Storage { .. } = ty { + let remaining_size = wgt::BufferSize::new( + source.buffer.size - source.offset, + ); + if let Some(binding_size) = source.size.or(remaining_size) { + array_element_sizes.push((idx as u32, binding_size)); + } + } + + let use_info = bg + .resources_to_use + .entry(source.buffer.as_raw().cast()) + .or_default(); + use_info.stages |= stages; + use_info.uses |= uses; + use_info.visible_in_compute |= + layout.visibility.contains(wgt::ShaderStages::COMPUTE); + } + } + wgt::BindingType::AccelerationStructure { .. } => { + let resource_ids = + bindless_id_table_mut(argument_buffer.as_ref(), count); + let start = entry.resource_index as usize; + let end = start + count as usize; + let acceleration_structures = + &desc.acceleration_structures[start..end]; + + for (idx, &acceleration_structure) in + acceleration_structures.iter().enumerate() + { + resource_ids[idx] = acceleration_structure.raw.gpuResourceID(); + + let use_info = bg + .resources_to_use + .entry(acceleration_structure.as_raw().cast()) + .or_default(); + use_info.stages |= stages; + use_info.uses |= uses; + use_info.visible_in_compute |= + layout.visibility.contains(wgt::ShaderStages::COMPUTE); + } + } + _ => { + unimplemented!(); + } + } + + if matches!( + layout.ty, + wgt::BindingType::Buffer { + ty: wgt::BufferBindingType::Storage { .. }, + .. + } + ) { + bg.buffers + .push(super::BufferLikeResource::StorageBindingArray { + ptr: NonNull::from(&*argument_buffer), + array_element_sizes, + binding_location: layout.binding, + }); + } else { + bg.buffers.push(super::BufferLikeResource::Buffer { + ptr: NonNull::from(&*argument_buffer), + offset: 0, + dynamic_index: None, + binding_size: None, + binding_location: layout.binding, + }); + } + counter.buffers += 1; + + bg.argument_buffers.push(argument_buffer) + } + // Bindfull path + else { + if let wgt::BindingType::Buffer { + has_dynamic_offset: true, + .. + } = layout.ty + { + dynamic_offsets_count += 1; + } + if !layout.visibility.contains(stage_bit) { + continue; + } + match layout.ty { + wgt::BindingType::Buffer { + ty, + has_dynamic_offset, + .. + } => { + let start = entry.resource_index as usize; + let end = start + 1; + bg.buffers + .extend(desc.buffers[start..end].iter().map(|source| { + // Given the restrictions on `BufferBinding::offset`, + // this should never be `None`. + let remaining_size = wgt::BufferSize::new( + source.buffer.size - source.offset, + ); + let binding_size = match ty { + wgt::BufferBindingType::Storage { .. } => { + source.size.or(remaining_size) + } + _ => None, + }; + super::BufferLikeResource::Buffer { + ptr: source.buffer.as_raw(), + offset: source.offset, + dynamic_index: if has_dynamic_offset { + Some(dynamic_offsets_count - 1) + } else { + None + }, + binding_size, + binding_location: layout.binding, + } + })); + counter.buffers += 1; + } + wgt::BindingType::Sampler { .. } => { + let start = entry.resource_index as usize; + let end = start + 1; + bg.samplers.extend( + desc.samplers[start..end].iter().map(|samp| samp.as_raw()), + ); + counter.samplers += 1; + } + wgt::BindingType::Texture { .. } + | wgt::BindingType::StorageTexture { .. } => { + let start = entry.resource_index as usize; + let end = start + 1; + bg.textures.extend( + desc.textures[start..end] + .iter() + .map(|tex| tex.view.as_raw()), + ); + counter.textures += 1; + } + wgt::BindingType::AccelerationStructure { .. } => { + let start = entry.resource_index as usize; + let end = start + 1; + bg.buffers.extend( + desc.acceleration_structures[start..end].iter().map( + |acceleration_structure| { + super::BufferLikeResource::AccelerationStructure( + acceleration_structure.as_raw(), + ) + }, + ), + ); + counter.buffers += 1; + } + wgt::BindingType::ExternalTexture => { + // We don't yet support binding arrays of external textures. + // https://github.com/gfx-rs/wgpu/issues/8027 + assert_eq!(entry.count, 1); + let external_texture = + &desc.external_textures[entry.resource_index as usize]; + bg.textures.extend( + external_texture + .planes + .iter() + .map(|plane| plane.view.as_raw()), + ); + bg.buffers.push(super::BufferLikeResource::Buffer { + ptr: external_texture.params.buffer.as_raw(), + offset: external_texture.params.offset, + dynamic_index: None, + binding_size: None, + binding_location: layout.binding, + }); + counter.textures += 3; + counter.buffers += 1; + } + } + } + } + } + + self.counters.bind_groups.add(1); + + Ok(bg) + }) + } + + unsafe fn destroy_bind_group(&self, _group: super::BindGroup) { + self.counters.bind_groups.sub(1); + } + + unsafe fn create_shader_module( + &self, + desc: &crate::ShaderModuleDescriptor, + shader: crate::ShaderInput, + ) -> Result<super::ShaderModule, crate::ShaderError> { + self.counters.shader_modules.add(1); + + match shader { + crate::ShaderInput::Naga(naga) => Ok(super::ShaderModule { + source: ShaderModuleSource::Naga(naga), + runtime_checks: desc.runtime_checks, + }), + crate::ShaderInput::MetalLib { + file, + num_workgroups, + } => { + // SAFETY: this creates a reference to `file` that is dropped before `file` is dropped. + let library = super::library_from_metallib::new_library_from_metallib_bytes( + &self.shared.device, + file, + ) + .map_err(|e| crate::ShaderError::Compilation(format!("Metallib: {e:?}")))?; + Ok(super::ShaderModule { + source: ShaderModuleSource::Passthrough(PassthroughShader { + library, + num_workgroups, + }), + // This goes unused for passthrough shaders + runtime_checks: wgt::ShaderRuntimeChecks::unchecked(), + }) + } + crate::ShaderInput::Msl { + shader: source, + num_workgroups, + } => { + let options = MTLCompileOptions::new(); + // Obtain the device from shared + let device = &self.shared.device; + let library = device + .newLibraryWithSource_options_error(&NSString::from_str(source), Some(&options)) + .map_err(|e| crate::ShaderError::Compilation(format!("MSL: {e:?}")))?; + + Ok(super::ShaderModule { + source: ShaderModuleSource::Passthrough(PassthroughShader { + library, + num_workgroups, + }), + runtime_checks: desc.runtime_checks, + }) + } + crate::ShaderInput::SpirV(_) + | crate::ShaderInput::Dxil { .. } + | crate::ShaderInput::Hlsl { .. } + | crate::ShaderInput::Glsl { .. } => unreachable!(), + } + } + + unsafe fn destroy_shader_module(&self, _module: super::ShaderModule) { + self.counters.shader_modules.sub(1); + } + + unsafe fn create_render_pipeline( + &self, + desc: &crate::RenderPipelineDescriptor< + super::PipelineLayout, + super::ShaderModule, + super::PipelineCache, + >, + ) -> Result<super::RenderPipeline, crate::PipelineError> { + autoreleasepool(|_| { + enum MetalGenericRenderPipelineDescriptor { + Standard(Retained<MTLRenderPipelineDescriptor>), + Mesh(Retained<MTLMeshRenderPipelineDescriptor>), + } + macro_rules! descriptor_fn { + ($descriptor:ident . $method:ident $( ( $($args:expr),* ) )? ) => { + match $descriptor { + MetalGenericRenderPipelineDescriptor::Standard(ref inner) => inner.$method$(($($args),*))?, + MetalGenericRenderPipelineDescriptor::Mesh(ref inner) => inner.$method$(($($args),*))?, + } + }; + } + #[allow(non_snake_case)] + impl MetalGenericRenderPipelineDescriptor { + unsafe fn setFragmentFunction( + &self, + function: Option<&ProtocolObject<dyn MTLFunction>>, + ) { + unsafe { descriptor_fn!(self.setFragmentFunction(function)) }; + } + fn fragmentBuffers(&self) -> Retained<MTLPipelineBufferDescriptorArray> { + descriptor_fn!(self.fragmentBuffers()) + } + fn setDepthAttachmentPixelFormat(&self, pixel_format: MTLPixelFormat) { + descriptor_fn!(self.setDepthAttachmentPixelFormat(pixel_format)); + } + fn colorAttachments( + &self, + ) -> Retained<MTLRenderPipelineColorAttachmentDescriptorArray> { + descriptor_fn!(self.colorAttachments()) + } + fn setStencilAttachmentPixelFormat(&self, pixel_format: MTLPixelFormat) { + descriptor_fn!(self.setStencilAttachmentPixelFormat(pixel_format)); + } + fn setAlphaToCoverageEnabled(&self, enabled: bool) { + descriptor_fn!(self.setAlphaToCoverageEnabled(enabled)); + } + fn setLabel(&self, label: Option<&NSString>) { + descriptor_fn!(self.setLabel(label)); + } + unsafe fn setMaxVertexAmplificationCount(&self, count: NSUInteger) { + unsafe { descriptor_fn!(self.setMaxVertexAmplificationCount(count)) } + } + } + + // https://developer.apple.com/documentation/metal/mtlpipelinebufferdescriptor/mutability + // Disabled on watchOS ILP32: the AGXMetalS4 driver exhibits instability + // when mutability hints are combined with Shared storage mode textures. + // Conservative disable until broader device coverage. + let supports_mutability = !IS_WATCHOS_ILP32 + && available!(macos = 10.13, ios = 11.0, tvos = 11.0, visionos = 1.0); + + let (primitive_class, raw_primitive_type) = + conv::map_primitive_topology(desc.primitive.topology); + + let vs_info; + let ts_info; + let ms_info; + + // Create the pipeline descriptor and do vertex/mesh pipeline specific setup + let descriptor = match desc.vertex_processor { + crate::VertexProcessor::Standard { + vertex_buffers, + ref vertex_stage, + } => { + // Vertex pipeline specific setup + + let descriptor = MTLRenderPipelineDescriptor::new(); + ts_info = None; + ms_info = None; + + // Collect vertex buffer mappings + let mut vertex_buffer_mappings = + Vec::<naga::back::msl::VertexBufferMapping>::new(); + for (i, vbl) in vertex_buffers.iter().enumerate() { + let Some(vbl) = vbl else { + continue; + }; + let mut attributes = Vec::<naga::back::msl::AttributeMapping>::new(); + for attribute in vbl.attributes.iter() { + attributes.push(naga::back::msl::AttributeMapping { + shader_location: attribute.shader_location, + offset: attribute.offset as u32, + format: convert_vertex_format_to_naga(attribute.format), + }); + } + + let mapping = naga::back::msl::VertexBufferMapping { + id: MAX_BUFFERS - 1 - i as u32, + stride: if vbl.array_stride > 0 { + vbl.array_stride.try_into().unwrap() + } else { + vbl.attributes + .iter() + .map(|attribute| attribute.offset + attribute.format.size()) + .max() + .unwrap_or(0) + .try_into() + .unwrap() + }, + step_mode: match (vbl.array_stride == 0, vbl.step_mode) { + (true, _) => naga::back::msl::VertexBufferStepMode::Constant, + (false, wgt::VertexStepMode::Vertex) => { + naga::back::msl::VertexBufferStepMode::ByVertex + } + (false, wgt::VertexStepMode::Instance) => { + naga::back::msl::VertexBufferStepMode::ByInstance + } + }, + attributes, + }; + vertex_buffer_mappings.push(mapping); + } + + // Setup vertex shader + { + let vs = self.load_shader( + vertex_stage, + &vertex_buffer_mappings, + desc.layout, + primitive_class, + naga::ShaderStage::Vertex, + )?; + + descriptor.setVertexFunction(Some(&vs.function)); + + if supports_mutability { + Self::set_buffers_mutability( + &descriptor.vertexBuffers(), + vs.immutable_buffer_mask, + ); + } + + vs_info = Some(super::PipelineStageInfo { + immediates: desc.layout.immediates_infos.vs, + sizes_slot: desc.layout.per_stage_map.vs.sizes_buffer, + sized_bindings: vs.sized_bindings, + vertex_buffer_mappings, + library: Some(vs.library), + raw_wg_size: MTLSize { + width: 0, + height: 0, + depth: 0, + }, + work_group_memory_sizes: vec![], + }); + } + + // Set the pipeline vertex buffer info + if !vertex_buffers.is_empty() { + let vertex_descriptor = MTLVertexDescriptor::new(); + for (i, vb) in vertex_buffers.iter().enumerate() { + let Some(vb) = vb else { + continue; + }; + + let buffer_index = MAX_BUFFERS as usize - 1 - i; + let buffer_desc = unsafe { + vertex_descriptor + .layouts() + .objectAtIndexedSubscript(buffer_index) + }; + + // Metal expects the stride to be the actual size of the attributes. + // The semantics of array_stride == 0 can be achieved by setting + // the step function to constant and rate to 0. + if vb.array_stride == 0 { + let stride = vb + .attributes + .iter() + .map(|attribute| attribute.offset + attribute.format.size()) + .max() + .unwrap_or(0); + unsafe { + buffer_desc.setStride(wgt::math::align_to( + NSUInteger::try_from(stride).unwrap(), + 4, + )) + }; + buffer_desc.setStepFunction(MTLVertexStepFunction::Constant); + unsafe { buffer_desc.setStepRate(0) }; + } else { + unsafe { buffer_desc.setStride(vb.array_stride as _) }; + buffer_desc.setStepFunction(conv::map_step_mode(vb.step_mode)); + } + + for at in vb.attributes { + let attribute_desc = unsafe { + vertex_descriptor + .attributes() + .objectAtIndexedSubscript(at.shader_location as _) + }; + attribute_desc.setFormat(conv::map_vertex_format(at.format)); + unsafe { attribute_desc.setBufferIndex(buffer_index) }; + unsafe { attribute_desc.setOffset(at.offset as _) }; + } + } + descriptor.setVertexDescriptor(Some(&vertex_descriptor)); + } + + MetalGenericRenderPipelineDescriptor::Standard(descriptor) + } + crate::VertexProcessor::Mesh { + ref task_stage, + ref mesh_stage, + } => { + // Mesh pipeline specific setup + + vs_info = None; + let descriptor = MTLMeshRenderPipelineDescriptor::new(); + + // Setup task stage + if let Some(ref task_stage) = task_stage { + let ts = self.load_shader( + task_stage, + &[], + desc.layout, + primitive_class, + naga::ShaderStage::Task, + )?; + unsafe { descriptor.setObjectFunction(Some(&ts.function)) }; + if supports_mutability { + Self::set_buffers_mutability( + &descriptor.meshBuffers(), + ts.immutable_buffer_mask, + ); + } + ts_info = Some(super::PipelineStageInfo { + immediates: desc.layout.immediates_infos.ts, + sizes_slot: desc.layout.per_stage_map.ts.sizes_buffer, + sized_bindings: ts.sized_bindings, + vertex_buffer_mappings: vec![], + library: Some(ts.library), + raw_wg_size: ts.wg_size, + work_group_memory_sizes: ts.wg_memory_sizes, + }); + } else { + ts_info = None; + } + + // Setup mesh stage + { + let ms = self.load_shader( + mesh_stage, + &[], + desc.layout, + primitive_class, + naga::ShaderStage::Mesh, + )?; + unsafe { descriptor.setMeshFunction(Some(&ms.function)) }; + if supports_mutability { + Self::set_buffers_mutability( + &descriptor.meshBuffers(), + ms.immutable_buffer_mask, + ); + } + ms_info = Some(super::PipelineStageInfo { + immediates: desc.layout.immediates_infos.ms, + sizes_slot: desc.layout.per_stage_map.ms.sizes_buffer, + sized_bindings: ms.sized_bindings, + vertex_buffer_mappings: vec![], + library: Some(ms.library), + raw_wg_size: ms.wg_size, + work_group_memory_sizes: ms.wg_memory_sizes, + }); + } + + MetalGenericRenderPipelineDescriptor::Mesh(descriptor) + } + }; + + let raw_triangle_fill_mode = match desc.primitive.polygon_mode { + wgt::PolygonMode::Fill => MTLTriangleFillMode::Fill, + wgt::PolygonMode::Line => MTLTriangleFillMode::Lines, + wgt::PolygonMode::Point => panic!( + "{:?} is not enabled for this backend", + wgt::Features::POLYGON_MODE_POINT + ), + }; + + // Fragment shader + let fs_info = match desc.fragment_stage { + Some(ref stage) => { + let fs = self.load_shader( + stage, + &[], + desc.layout, + primitive_class, + naga::ShaderStage::Fragment, + )?; + + unsafe { descriptor.setFragmentFunction(Some(&fs.function)) }; + if supports_mutability { + Self::set_buffers_mutability( + &descriptor.fragmentBuffers(), + fs.immutable_buffer_mask, + ); + } + + Some(super::PipelineStageInfo { + immediates: desc.layout.immediates_infos.fs, + sizes_slot: desc.layout.per_stage_map.fs.sizes_buffer, + sized_bindings: fs.sized_bindings, + vertex_buffer_mappings: vec![], + library: Some(fs.library), + raw_wg_size: MTLSize { + width: 0, + height: 0, + depth: 0, + }, + work_group_memory_sizes: vec![], + }) + } + None => { + // TODO: This is a workaround for what appears to be a Metal validation bug + // A pixel format is required even though no attachments are provided + if desc.color_targets.is_empty() && desc.depth_stencil.is_none() { + descriptor.setDepthAttachmentPixelFormat(MTLPixelFormat::Depth32Float); + } + None + } + }; + + // Setup pipeline color attachments + for (i, ct) in desc.color_targets.iter().enumerate() { + let at_descriptor = + unsafe { descriptor.colorAttachments().objectAtIndexedSubscript(i) }; + let ct = if let Some(color_target) = ct.as_ref() { + color_target + } else { + at_descriptor.setPixelFormat(MTLPixelFormat::Invalid); + continue; + }; + + let raw_format = self + .shared + .private_texture_format_caps + .map_format(ct.format); + at_descriptor.setPixelFormat(raw_format); + at_descriptor.setWriteMask(conv::map_color_write(ct.write_mask)); + + if let Some(ref blend) = ct.blend { + at_descriptor.setBlendingEnabled(true); + let (color_op, color_src, color_dst) = conv::map_blend_component(&blend.color); + let (alpha_op, alpha_src, alpha_dst) = conv::map_blend_component(&blend.alpha); + + at_descriptor.setRgbBlendOperation(color_op); + at_descriptor.setSourceRGBBlendFactor(color_src); + at_descriptor.setDestinationRGBBlendFactor(color_dst); + + at_descriptor.setAlphaBlendOperation(alpha_op); + at_descriptor.setSourceAlphaBlendFactor(alpha_src); + at_descriptor.setDestinationAlphaBlendFactor(alpha_dst); + } + } + + // Setup depth stencil state + let depth_stencil = match desc.depth_stencil { + Some(ref ds) => { + let raw_format = self + .shared + .private_texture_format_caps + .map_format(ds.format); + let aspects = crate::FormatAspects::from(ds.format); + if aspects.contains(crate::FormatAspects::DEPTH) { + descriptor.setDepthAttachmentPixelFormat(raw_format); + } + if aspects.contains(crate::FormatAspects::STENCIL) { + descriptor.setStencilAttachmentPixelFormat(raw_format); + } + + let ds_descriptor = create_depth_stencil_desc(ds); + let raw = self + .shared + .device + .newDepthStencilStateWithDescriptor(&ds_descriptor) + .unwrap(); + Some((raw, ds.bias)) + } + None => None, + }; + + // Setup multisample state + if desc.multisample.count != 1 { + //TODO: handle sample mask + match descriptor { + MetalGenericRenderPipelineDescriptor::Standard(ref inner) => { + #[allow(deprecated)] + inner.setSampleCount(desc.multisample.count as _); + } + MetalGenericRenderPipelineDescriptor::Mesh(ref inner) => { + unsafe { inner.setRasterSampleCount(desc.multisample.count as _) }; + } + } + descriptor.setAlphaToCoverageEnabled(desc.multisample.alpha_to_coverage_enabled); + //descriptor.set_alpha_to_one_enabled(desc.multisample.alpha_to_one_enabled); + } + + // Set debug label + if let Some(name) = desc.label { + descriptor.setLabel(Some(&NSString::from_str(name))); + } + if let Some(mv) = desc.multiview_mask { + unsafe { + descriptor.setMaxVertexAmplificationCount(mv.get().count_ones() as usize) + }; + } + + // Create the pipeline from descriptor + let raw = match descriptor { + MetalGenericRenderPipelineDescriptor::Standard(d) => self + .shared + .device + .newRenderPipelineStateWithDescriptor_error(&d), + MetalGenericRenderPipelineDescriptor::Mesh(d) => self + .shared + .device + .newRenderPipelineStateWithMeshDescriptor_options_reflection_error( + &d, + MTLPipelineOption::empty(), + None, + ), + } + .map_err(|e| { + crate::PipelineError::Linkage( + wgt::ShaderStages::VERTEX | wgt::ShaderStages::FRAGMENT, + format!("new_render_pipeline_state: {e:?}"), + ) + })?; + + self.counters.render_pipelines.add(1); + + Ok(super::RenderPipeline { + raw, + vs_info, + fs_info, + ts_info, + ms_info, + raw_primitive_type, + raw_triangle_fill_mode, + raw_front_winding: conv::map_winding(desc.primitive.front_face), + raw_cull_mode: conv::map_cull_mode(desc.primitive.cull_mode), + raw_depth_clip_mode: if self.features.contains(wgt::Features::DEPTH_CLIP_CONTROL) { + Some(if desc.primitive.unclipped_depth { + MTLDepthClipMode::Clamp + } else { + MTLDepthClipMode::Clip + }) + } else { + None + }, + depth_stencil, + }) + }) + } + + unsafe fn destroy_render_pipeline(&self, _pipeline: super::RenderPipeline) { + self.counters.render_pipelines.sub(1); + } + + unsafe fn create_compute_pipeline( + &self, + desc: &crate::ComputePipelineDescriptor< + super::PipelineLayout, + super::ShaderModule, + super::PipelineCache, + >, + ) -> Result<super::ComputePipeline, crate::PipelineError> { + autoreleasepool(|_| { + let descriptor = MTLComputePipelineDescriptor::new(); + + let module = desc.stage.module; + let cs = if let ShaderModuleSource::Passthrough(passthrough_desc) = &module.source { + let size = passthrough_desc.num_workgroups[desc.stage.entry_point]; + CompiledShader { + library: passthrough_desc.library.clone(), + function: passthrough_desc + .library + .newFunctionWithName(&NSString::from_str(desc.stage.entry_point)) + .ok_or(crate::PipelineError::EntryPoint(naga::ShaderStage::Compute))?, + wg_size: MTLSize { + width: size.0 as usize, + height: size.1 as usize, + depth: size.2 as usize, + }, + wg_memory_sizes: vec![], + sized_bindings: vec![], + immutable_buffer_mask: 0, + } + } else { + self.load_shader( + &desc.stage, + &[], + desc.layout, + MTLPrimitiveTopologyClass::Unspecified, + naga::ShaderStage::Compute, + )? + }; + + descriptor.setComputeFunction(Some(&cs.function)); + + // https://developer.apple.com/documentation/metal/mtlpipelinebufferdescriptor/mutability + if available!(macos = 10.13, ios = 11.0, tvos = 11.0, visionos = 1.0) { + Self::set_buffers_mutability(&descriptor.buffers(), cs.immutable_buffer_mask); + } + + let cs_info = super::PipelineStageInfo { + library: Some(cs.library), + immediates: desc.layout.immediates_infos.cs, + sizes_slot: desc.layout.per_stage_map.cs.sizes_buffer, + sized_bindings: cs.sized_bindings, + vertex_buffer_mappings: vec![], + raw_wg_size: cs.wg_size, + work_group_memory_sizes: cs.wg_memory_sizes, + }; + + if let Some(name) = desc.label { + descriptor.setLabel(Some(&NSString::from_str(name))); + } + + let raw = self + .shared + .device + .newComputePipelineStateWithDescriptor_options_reflection_error( + &descriptor, + MTLPipelineOption::empty(), + None, + ); + + let raw: Retained<ProtocolObject<dyn MTLComputePipelineState>> = + raw.map_err(|e: Retained<NSError>| { + crate::PipelineError::Linkage( + wgt::ShaderStages::COMPUTE, + format!("new_compute_pipeline_state: {e:?}"), + ) + })?; + + self.counters.compute_pipelines.add(1); + + Ok(super::ComputePipeline { raw, cs_info }) + }) + } + + unsafe fn destroy_compute_pipeline(&self, _pipeline: super::ComputePipeline) { + self.counters.compute_pipelines.sub(1); + } + + unsafe fn create_ray_tracing_pipeline( + &self, + _desc: &crate::RayTracingPipelineDescriptor< + super::PipelineLayout, + super::ShaderModule, + super::PipelineCache, + >, + ) -> Result<super::RayTracingPipeline, crate::PipelineError> { + unimplemented!("Ray tracing pipelines are unsupported on Metal") + } + + unsafe fn destroy_ray_tracing_pipeline(&self, _pipeline: super::RayTracingPipeline) { + unimplemented!("Ray tracing pipelines are unsupported on Metal") + } + + unsafe fn get_raytracing_pipeline_group_data( + &self, + _pipeline: &super::RayTracingPipeline, + _groups: core::ops::Range<u32>, + ) -> Result<Vec<u8>, crate::DeviceError> { + unimplemented!("Ray tracing pipelines are unsupported on Metal") + } + + unsafe fn create_pipeline_cache( + &self, + _desc: &crate::PipelineCacheDescriptor<'_>, + ) -> Result<super::PipelineCache, crate::PipelineCacheError> { + Ok(super::PipelineCache) + } + unsafe fn destroy_pipeline_cache(&self, _: super::PipelineCache) {} + + unsafe fn create_query_set( + &self, + desc: &wgt::QuerySetDescriptor<crate::Label>, + ) -> DeviceResult<super::QuerySet> { + autoreleasepool(|_| { + match desc.ty { + wgt::QueryType::Occlusion => { + let size = desc.count as u64 * crate::QUERY_SIZE; + let options = MTLResourceOptions::empty(); + //TODO: HazardTrackingModeUntracked + let raw_buffer = self + .shared + .device + .newBufferWithLength_options(size as usize, options) + .unwrap(); + if let Some(label) = desc.label { + raw_buffer.setLabel(Some(&NSString::from_str(label))); + } + Ok(super::QuerySet { + raw_buffer, + counter_sample_buffer: None, + ty: desc.ty, + }) + } + wgt::QueryType::Timestamp => { + let size = desc.count as u64 * crate::QUERY_SIZE; + let device = &self.shared.device; + let destination_buffer = device + .newBufferWithLength_options(size as usize, MTLResourceOptions::empty()) + .unwrap(); + + let csb_desc = MTLCounterSampleBufferDescriptor::new(); + csb_desc.setStorageMode(MTLStorageMode::Shared); + unsafe { csb_desc.setSampleCount(desc.count as _) }; + if let Some(label) = desc.label { + csb_desc.setLabel(&NSString::from_str(label)); + } + + let counter_sets = device.counterSets().unwrap(); + let timestamp_counter = match counter_sets + .iter() + .find(|cs| &*cs.name() == ns_string!("timestamp")) + { + Some(counter) => counter, + None => { + log::error!("Failed to obtain timestamp counter set."); + return Err(crate::DeviceError::Unexpected); + } + }; + csb_desc.setCounterSet(Some(&timestamp_counter)); + + let counter_sample_buffer = + match device.newCounterSampleBufferWithDescriptor_error(&csb_desc) { + Ok(buffer) => buffer, + Err(err) => { + log::error!("Failed to create counter sample buffer: {err:?}"); + return Err(crate::DeviceError::Unexpected); + } + }; + + self.counters.query_sets.add(1); + + Ok(super::QuerySet { + raw_buffer: destination_buffer, + counter_sample_buffer: Some(counter_sample_buffer), + ty: desc.ty, + }) + } + _ => { + todo!() + } + } + }) + } + + unsafe fn destroy_query_set(&self, _set: super::QuerySet) { + self.counters.query_sets.sub(1); + } + + unsafe fn create_fence(&self) -> DeviceResult<super::Fence> { + self.counters.fences.add(1); + // https://developer.apple.com/documentation/metal/mtlsharedevent + let shared_event = if available!(macos = 10.14, ios = 12.0, tvos = 12.0, visionos = 1.0) { + self.shared.device.newSharedEvent() // This should be supported on said devices, but some sandbox environments may still restrict it, making it return `None`. + } else { + None + }; + Ok(super::Fence { + sync: Arc::new((Mutex::new(0), Condvar::new())), + pending_command_buffers: RwLock::new(Vec::new()), + shared_event, + }) + } + + unsafe fn destroy_fence(&self, _fence: super::Fence) { + self.counters.fences.sub(1); + } + + unsafe fn get_fence_value(&self, fence: &super::Fence) -> DeviceResult<crate::FenceValue> { + Ok(fence.get_latest()) + } + unsafe fn wait( + &self, + fence: &super::Fence, + wait_value: crate::FenceValue, + timeout: Option<core::time::Duration>, + ) -> DeviceResult<bool> { + let (ref mutex, ref condvar) = *fence.sync; + let mut lock = mutex.lock(); + + if wait_value <= *lock { + return Ok(true); + } + + { + let pending_command_buffers = fence.pending_command_buffers.read(); + if !pending_command_buffers + .iter() + .any(|&(value, _)| value >= wait_value) + { + log::error!("No active command buffers for fence value {wait_value}"); + return Err(crate::DeviceError::Lost); + } + } + + if let Some(timeout) = timeout { + let result = condvar.wait_while_for(&mut lock, |value| *value < wait_value, timeout); + if result.timed_out() { + return Ok(*lock >= wait_value); + } + } else { + condvar.wait_while(&mut lock, |value| *value < wait_value); + } + + Ok(true) + } + + unsafe fn start_graphics_debugger_capture(&self) -> bool { + // https://developer.apple.com/documentation/metal/mtlcapturemanager + if !available!(macos = 10.13, ios = 11.0, tvos = 11.0, visionos = 1.0) { + return false; + } + let device = &self.shared.device; + let shared_capture_manager = unsafe { MTLCaptureManager::sharedCaptureManager() }; + let default_capture_scope = shared_capture_manager.newCaptureScopeWithDevice(device); + shared_capture_manager.setDefaultCaptureScope(Some(&default_capture_scope)); + #[allow(deprecated)] + shared_capture_manager.startCaptureWithScope(&default_capture_scope); + default_capture_scope.beginScope(); + true + } + + unsafe fn stop_graphics_debugger_capture(&self) { + let shared_capture_manager = unsafe { MTLCaptureManager::sharedCaptureManager() }; + if let Some(default_capture_scope) = shared_capture_manager.defaultCaptureScope() { + default_capture_scope.endScope(); + } + shared_capture_manager.stopCapture(); + } + + unsafe fn get_acceleration_structure_build_sizes( + &self, + descriptor: &crate::GetAccelerationStructureBuildSizesDescriptor<super::Buffer>, + ) -> crate::AccelerationStructureBuildSizes { + let acceleration_structure_descriptor = + conv::map_acceleration_structure_descriptor(descriptor.entries, descriptor.flags); + let info = self + .shared + .device + .accelerationStructureSizesWithDescriptor(&acceleration_structure_descriptor); + crate::AccelerationStructureBuildSizes { + acceleration_structure_size: info.accelerationStructureSize as u64, + update_scratch_size: info.refitScratchBufferSize as u64, + build_scratch_size: info.buildScratchBufferSize as u64, + } + } + + unsafe fn get_acceleration_structure_device_address( + &self, + acceleration_structure: &super::AccelerationStructure, + ) -> wgt::BufferAddress { + acceleration_structure.raw.gpuResourceID().to_raw() + } + + unsafe fn create_acceleration_structure( + &self, + descriptor: &crate::AccelerationStructureDescriptor, + ) -> Result<super::AccelerationStructure, crate::DeviceError> { + // self.counters.acceleration_structures.add(1); + autoreleasepool(|_| { + Ok(super::AccelerationStructure { + raw: self + .shared + .device + .newAccelerationStructureWithSize(descriptor.size as usize) + .ok_or(crate::DeviceError::OutOfMemory)?, + }) + }) + } + + unsafe fn destroy_acceleration_structure( + &self, + _acceleration_structure: super::AccelerationStructure, + ) { + // self.counters.acceleration_structures.sub(1); + } + + fn tlas_instance_to_bytes(&self, instance: TlasInstance) -> Vec<u8> { + let temp = MTLIndirectAccelerationStructureInstanceDescriptor { + transformationMatrix: MTLPackedFloat4x3 { + columns: [ + MTLPackedFloat3 { + x: instance.transform[0], + y: instance.transform[4], + z: instance.transform[8], + }, + MTLPackedFloat3 { + x: instance.transform[1], + y: instance.transform[5], + z: instance.transform[9], + }, + MTLPackedFloat3 { + x: instance.transform[2], + y: instance.transform[6], + z: instance.transform[10], + }, + MTLPackedFloat3 { + x: instance.transform[3], + y: instance.transform[7], + z: instance.transform[11], + }, + ], + }, + options: MTLAccelerationStructureInstanceOptions::None, + mask: instance.mask as u32, + intersectionFunctionTableOffset: instance.pipeline_intersection_data_offset, + userID: instance.custom_data, + accelerationStructureID: unsafe { MTLResourceID::from_raw(instance.blas_address) }, + }; + + wgt::bytemuck_wrapper!(unsafe struct Desc(MTLIndirectAccelerationStructureInstanceDescriptor)); + + bytemuck::bytes_of(&Desc::wrap(temp)).to_vec() + } + + fn get_internal_counters(&self) -> wgt::HalCounters { + self.counters.as_ref().clone() + } + + fn check_if_oom(&self) -> Result<(), crate::DeviceError> { + // TODO: see https://github.com/gfx-rs/wgpu/issues/7460 + + Ok(()) + } +} diff --git a/app/vendor/rune/vendor/wgpu-hal/src/metal/library_from_metallib.rs b/app/vendor/rune/vendor/wgpu-hal/src/metal/library_from_metallib.rs new file mode 100644 index 0000000..2389847 --- /dev/null +++ b/app/vendor/rune/vendor/wgpu-hal/src/metal/library_from_metallib.rs @@ -0,0 +1,48 @@ +use core::{ffi::c_void, ptr::NonNull}; + +use objc2::{ + msg_send, + rc::Retained, + runtime::{AnyObject, ProtocolObject}, +}; +use objc2_foundation::NSError; +use objc2_metal::{MTLDevice, MTLLibrary}; + +#[link(name = "System")] // libdispatch lives inside libSystem +extern "C" { + fn dispatch_data_create( + buffer: NonNull<c_void>, + size: usize, + queue: Option<NonNull<c_void>>, // dispatch_queue_t _Nullable + destructor: *mut c_void, // dispatch_block_t _Nullable + ) -> *mut AnyObject; // dispatch_data_t + + fn dispatch_release(object: *mut AnyObject); // dispatch_data_t +} + +const DISPATCH_DATA_DESTRUCTOR_DEFAULT: *mut c_void = core::ptr::null_mut(); + +/// See <https://github.com/madsmtm/objc2/issues/819>. +/// +/// newLibraryWithData requires DispatchData, part of the Dispatch library. +/// Not only is this a big additional dependency for a glorified `Vec<u8>` +/// in this case, but the code in the dispatch2 rust crate is a WIP and +/// Mozilla has decided not to vendor it yet. +/// +/// This function allows us to deal with DispatchData without dealing +/// with these problems. +pub(crate) fn new_library_from_metallib_bytes( + device: &ProtocolObject<dyn MTLDevice>, + data: &[u8], +) -> Result<Retained<ProtocolObject<dyn MTLLibrary>>, Retained<NSError>> { + let buffer = NonNull::new(data.as_ptr().cast_mut()).unwrap().cast(); + let data = + unsafe { dispatch_data_create(buffer, data.len(), None, DISPATCH_DATA_DESTRUCTOR_DEFAULT) }; + assert!(!data.is_null()); + + let res: Result<Retained<ProtocolObject<dyn MTLLibrary>>, Retained<NSError>> = + unsafe { msg_send![device, newLibraryWithData: data, error: _] }; + + unsafe { dispatch_release(data) }; + res +} diff --git a/app/vendor/rune/vendor/wgpu-hal/src/metal/mod.rs b/app/vendor/rune/vendor/wgpu-hal/src/metal/mod.rs new file mode 100644 index 0000000..e227590 --- /dev/null +++ b/app/vendor/rune/vendor/wgpu-hal/src/metal/mod.rs @@ -0,0 +1,1410 @@ +/*! +# Metal API internals. + +## Pipeline Layout + +In Metal, immediates, vertex buffers, and resources in the bind groups +are all placed together in the native resource bindings, which work similarly to D3D11: +there are tables of textures, buffers, and samplers. + +We put immediates first (if any) in the table, followed by bind group 0 +resources, followed by other bind groups. The vertex buffers are bound at the very +end of the VS buffer table. + +!*/ + +#[allow( + deprecated, + reason = "MTLFeatureSet` is superseded by `MTLGpuFamily`. + However, `MTLGpuFamily` is only supported starting MacOS 10.15, whereas our minimum target is MacOS 10.13, + See https://github.com/gpuweb/gpuweb/issues/1069 for minimum spec. + TODO: Eventually all deprecated features should be abstracted and use new api when available." +)] +mod adapter; +mod command; +mod conv; +mod device; +mod library_from_metallib; +mod surface; +mod time; + +use alloc::{ + string::{String, ToString as _}, + sync::Arc, + vec::Vec, +}; +use core::{fmt, iter, ops, ptr::NonNull, sync::atomic}; +use std::sync::OnceLock; + +use bitflags::bitflags; +use hashbrown::HashMap; +use naga::FastHashMap; +use objc2::{ + available, + rc::{autoreleasepool, Retained}, + runtime::ProtocolObject, +}; +use objc2_foundation::ns_string; +use objc2_metal::{ + MTLAccelerationStructure, MTLAccelerationStructureCommandEncoder, MTLArgumentBuffersTier, + MTLBlitCommandEncoder, MTLBuffer, MTLCommandBuffer, MTLCommandBufferStatus, MTLCommandQueue, + MTLComputeCommandEncoder, MTLComputePipelineState, MTLCounterSampleBuffer, MTLCullMode, + MTLDepthClipMode, MTLDepthStencilState, MTLDevice, MTLDrawable, MTLIndexType, + MTLLanguageVersion, MTLLibrary, MTLPrimitiveType, MTLReadWriteTextureTier, + MTLRenderCommandEncoder, MTLRenderPipelineState, MTLRenderStages, MTLResource, + MTLResourceUsage, MTLSamplerState, MTLSharedEvent, MTLSize, MTLTexture, MTLTextureType, + MTLTriangleFillMode, MTLWinding, +}; +use objc2_quartz_core::CAMetalLayer; +use parking_lot::{Condvar, Mutex, RwLock}; + +#[derive(Clone, Debug)] +pub struct Api; + +type ResourceIndex = u32; + +impl crate::Api for Api { + const VARIANT: wgt::Backend = wgt::Backend::Metal; + + type Instance = Instance; + type Surface = Surface; + type Adapter = Adapter; + type Device = Device; + + type Queue = Queue; + type CommandEncoder = CommandEncoder; + type CommandBuffer = CommandBuffer; + + type Buffer = Buffer; + type Texture = Texture; + type SurfaceTexture = SurfaceTexture; + type TextureView = TextureView; + type Sampler = Sampler; + type QuerySet = QuerySet; + type Fence = Fence; + + type BindGroupLayout = BindGroupLayout; + type BindGroup = BindGroup; + type PipelineLayout = PipelineLayout; + type ShaderModule = ShaderModule; + type RenderPipeline = RenderPipeline; + type RayTracingPipeline = RayTracingPipeline; + type ComputePipeline = ComputePipeline; + type PipelineCache = PipelineCache; + + type AccelerationStructure = AccelerationStructure; +} + +crate::impl_dyn_resource!( + Adapter, + AccelerationStructure, + BindGroup, + BindGroupLayout, + Buffer, + CommandBuffer, + CommandEncoder, + ComputePipeline, + Device, + Fence, + Instance, + PipelineCache, + PipelineLayout, + QuerySet, + Queue, + RenderPipeline, + RayTracingPipeline, + Sampler, + ShaderModule, + Surface, + SurfaceTexture, + Texture, + TextureView +); + +/// Provides availability information about Mac APIs. +/// +/// This may include Metal features that depend only on software support. +/// Features with varying hardware support are in [`CapabilitiesQuery`] +/// +/// When feature detection is only needed once, it may also be done inline. +struct OsFeatures; + +impl OsFeatures { + fn display_sync() -> bool { + // https://developer.apple.com/documentation/quartzcore/cametallayer/displaysyncenabled + available!(macos = 10.13) || cfg!(target_abi = "macabi") + } +} + +#[derive(Debug)] +pub struct Instance { + flags: wgt::InstanceFlags, +} + +impl Instance { + pub fn create_surface_from_layer(&self, layer: &CAMetalLayer) -> Surface { + Surface::from_layer(layer) + } +} + +impl crate::Instance for Instance { + type A = Api; + + unsafe fn init(desc: &crate::InstanceDescriptor<'_>) -> Result<Self, crate::InstanceError> { + profiling::scope!("Init Metal Backend"); + // We do not enable metal validation based on the validation flags as it affects the entire + // process. Instead, we enable the validation inside the test harness itself in tests/src/native.rs. + Ok(Instance { flags: desc.flags }) + } + + unsafe fn create_surface( + &self, + display_handle: raw_window_handle::RawDisplayHandle, + window_handle: raw_window_handle::RawWindowHandle, + ) -> Result<Surface, crate::InstanceError> { + let layer = match (display_handle, window_handle) { + ( + raw_window_handle::RawDisplayHandle::AppKit(_), + raw_window_handle::RawWindowHandle::AppKit(handle), + ) => unsafe { raw_window_metal::Layer::from_ns_view(handle.ns_view) }, + ( + raw_window_handle::RawDisplayHandle::UiKit(_), + raw_window_handle::RawWindowHandle::UiKit(handle), + ) => unsafe { raw_window_metal::Layer::from_ui_view(handle.ui_view) }, + _ => { + return Err(crate::InstanceError::new(format!( + "window handle {window_handle:?} is not a Metal-compatible handle" + ))) + } + }; + + // SAFETY: The layer is an initialized instance of `CAMetalLayer`, and + // we transfer the retain count to `Retained` using `into_raw`. + let layer = unsafe { + Retained::from_raw(layer.into_raw().cast::<CAMetalLayer>().as_ptr()).unwrap() + }; + + Ok(Surface::new(layer)) + } + + unsafe fn enumerate_adapters( + &self, + _surface_hint: Option<&Surface>, + ) -> Vec<crate::ExposedAdapter<Api>> { + let devices = objc2_metal::MTLCopyAllDevices(); + let instance_flags = self.flags; + let mut adapters: Vec<crate::ExposedAdapter<Api>> = devices + .into_iter() + .map(|d| AdapterShared::expose(d, instance_flags)) + .collect(); + adapters.sort_by_key(|ad| { + ( + ad.adapter.shared.private_caps.low_power, + ad.adapter.shared.private_caps.headless, + ) + }); + adapters + } +} + +bitflags!( + /// Similar to `MTLCounterSamplingPoint`, but a bit higher abstracted for our purposes. + #[derive(Debug, Copy, Clone)] + pub struct TimestampQuerySupport: u32 { + /// On creating Metal encoders. + const STAGE_BOUNDARIES = 1 << 1; + /// Within existing draw encoders. + const ON_RENDER_ENCODER = Self::STAGE_BOUNDARIES.bits() | (1 << 2); + /// Within existing dispatch encoders. + const ON_COMPUTE_ENCODER = Self::STAGE_BOUNDARIES.bits() | (1 << 3); + /// Within existing blit encoders. + const ON_BLIT_ENCODER = Self::STAGE_BOUNDARIES.bits() | (1 << 4); + + /// Within any wgpu render/compute pass. + const INSIDE_WGPU_PASSES = Self::ON_RENDER_ENCODER.bits() | Self::ON_COMPUTE_ENCODER.bits(); + } +); + +#[allow(dead_code)] +struct CapabilitiesQuery { + msl_version: MTLLanguageVersion, + fragment_rw_storage: bool, + read_write_texture_tier: MTLReadWriteTextureTier, + msaa_desktop: bool, + msaa_apple3: bool, + msaa_apple7: bool, + resource_heaps: bool, + argument_buffers: Option<MTLArgumentBuffersTier>, + mutable_comparison_samplers: bool, + sampler_clamp_to_border: bool, + indirect_draw_dispatch: bool, + base_vertex_first_instance_drawing: bool, + dual_source_blending: bool, + low_power: bool, + headless: bool, + layered_rendering: bool, + function_specialization: bool, + depth_clip_mode: bool, + texture_cube_array: bool, + supports_float_filtering: bool, + format_depth24_stencil8: bool, + format_depth32_stencil8_filter: bool, + format_depth32_stencil8_none: bool, + format_min_srgb_channels: u8, + format_b5: bool, + format_bc: bool, + format_eac_etc: bool, + format_astc: bool, + format_astc_hdr: bool, + format_astc_3d: bool, + format_any8_unorm_srgb_all: bool, + format_any8_unorm_srgb_no_write: bool, + format_any8_snorm_all: bool, + format_r16_norm_all: bool, + format_r32_all: bool, + format_r32_no_write: bool, + format_r32float_no_write_no_filter: bool, + format_r32float_no_filter: bool, + format_r32float_all: bool, + format_rgba8_srgb_all: bool, + format_rgba8_srgb_no_write: bool, + format_rgb10a2_unorm_all: bool, + format_rgb10a2_unorm_no_write: bool, + format_rgb10a2_uint_write: bool, + format_rg11b10_all: bool, + format_rg11b10_no_write: bool, + format_rgb9e5_all: bool, + format_rgb9e5_no_write: bool, + format_rgb9e5_filter_only: bool, + format_rg32_color: bool, + format_rg32_color_write: bool, + format_rg32float_all: bool, + format_rg32float_color_blend: bool, + format_rg32float_no_filter: bool, + format_rgba32int_color: bool, + format_rgba32int_color_write: bool, + format_rgba32float_color: bool, + format_rgba32float_color_write: bool, + format_rgba32float_all: bool, + format_depth16unorm: bool, + format_depth16unorm_filter: bool, + format_depth32float_filter: bool, + format_depth32float_none: bool, + format_bgr10a2_all: bool, + format_bgr10a2_no_write: bool, + max_textures_per_stage: (ResourceIndex, ResourceIndex), + max_binding_array_elements: ResourceIndex, + max_sampler_binding_array_elements: ResourceIndex, + buffer_alignment: u64, + constant_buffer_offset_alignment: u32, + max_buffer_size: u64, + max_texture_size: u64, + max_texture_3d_size: u64, + max_texture_layers: u64, + max_fragment_input_components: u64, + max_color_render_targets: u8, + max_color_attachment_bytes_per_sample: u8, + max_inter_stage_shader_variables: u32, + max_threads_per_group: u32, + max_total_threadgroup_memory: u32, + sample_count_mask: crate::TextureFormatCapabilities, + supports_debug_markers: bool, + supports_binary_archives: bool, + supports_arrays_of_textures: bool, + supports_arrays_of_textures_write: bool, + supports_depth_clip_control: bool, + supports_shader_primitive_index: bool, + has_unified_memory: Option<bool>, + timestamp_query_support: TimestampQuerySupport, + supports_simd_scoped_operations: bool, + supports_cooperative_matrix: bool, + int64: bool, + int64_atomics_min_max: bool, + int64_atomics: bool, + float_atomics: bool, + mesh_shaders: bool, + max_task_workgroup_count: u32, + max_mesh_workgroup_count: u32, + max_task_payload_size: u32, + supported_vertex_amplification_factor: u32, + shader_barycentrics: bool, + supports_memoryless_storage: bool, + supports_raytracing: bool, + shader_per_vertex: bool, + supports_multisample_array: bool, +} + +#[derive(Debug)] +struct PrivateCapabilities { + msl_version: MTLLanguageVersion, + low_power: bool, + headless: bool, + has_unified_memory: Option<bool>, + timestamp_query_support: TimestampQuerySupport, + supports_memoryless_storage: bool, + mesh_shaders: bool, +} + +#[derive(Debug)] +struct PrivateTextureFormatCapabilities { + read_write_texture_tier: MTLReadWriteTextureTier, + sample_count_mask: crate::TextureFormatCapabilities, + int64_atomics: bool, + msaa_desktop: bool, + msaa_apple3: bool, + msaa_apple7: bool, + format_r32float_all: bool, + format_rgba8_srgb_all: bool, + format_rgb10a2_uint_write: bool, + format_rgb10a2_unorm_all: bool, + format_rg11b10_all: bool, + format_rg32float_all: bool, + format_rgba32float_all: bool, + format_depth16unorm: bool, + format_depth16unorm_filter: bool, + format_depth32float_filter: bool, + format_depth24_stencil8: bool, + format_bc: bool, + format_eac_etc: bool, + format_astc: bool, + format_astc_hdr: bool, +} + +#[derive(Clone, Debug)] +struct PrivateDisabilities { + /// Near depth is not respected properly on some Intel GPUs. + broken_viewport_near_depth: bool, + /// Multi-target clears don't appear to work properly on Intel GPUs. + #[allow(dead_code)] + broken_layered_clear_image: bool, +} + +#[derive(Debug)] +struct Settings { + retain_command_buffer_references: bool, +} + +impl Default for Settings { + fn default() -> Self { + Self { + retain_command_buffer_references: true, + } + } +} + +#[derive(Debug)] +struct AdapterShared { + device: Retained<ProtocolObject<dyn MTLDevice>>, + disabilities: PrivateDisabilities, + private_caps: PrivateCapabilities, + private_texture_format_caps: PrivateTextureFormatCapabilities, + settings: Settings, + presentation_timer: time::PresentationTimer, +} + +#[cfg(send_sync)] +static_assertions::assert_impl_all!(AdapterShared: Send, Sync); + +impl AdapterShared { + fn new( + device: Retained<ProtocolObject<dyn MTLDevice>>, + capabilities_query: &CapabilitiesQuery, + ) -> Self { + let private_caps = capabilities_query.private_capabilities(); + let private_texture_format_caps = capabilities_query.private_texture_format_capabilities(); + log::debug!("{private_caps:#?}"); + log::debug!("{private_texture_format_caps:#?}"); + + Self { + disabilities: PrivateDisabilities::new(&device), + private_caps, + private_texture_format_caps, + device, + settings: Settings::default(), + presentation_timer: time::PresentationTimer::new(), + } + } + + fn expose( + device: Retained<ProtocolObject<dyn MTLDevice>>, + instance_flags: wgt::InstanceFlags, + ) -> crate::ExposedAdapter<Api> { + autoreleasepool(|_| { + let name = device.name().to_string(); + let capabilities_query = CapabilitiesQuery::new(&device); + let shared = AdapterShared::new(device, &capabilities_query); + let features = capabilities_query.features(); + let capabilities = capabilities_query.capabilities(instance_flags); + crate::ExposedAdapter { + info: wgt::AdapterInfo { + name, + // These are hardcoded based on typical values for Metal devices + // + // See <https://github.com/gpuweb/gpuweb/blob/main/proposals/subgroups.md#adapter-info> + // for more information. + subgroup_min_size: 4, + subgroup_max_size: 64, + transient_saves_memory: Some(shared.private_caps.supports_memoryless_storage), + ..wgt::AdapterInfo::new(shared.private_caps.device_type(), wgt::Backend::Metal) + }, + features, + capabilities, + adapter: Adapter::new(Arc::new(shared)), + } + }) + } +} + +#[derive(Debug)] +pub struct Adapter { + shared: Arc<AdapterShared>, +} + +#[cfg(send_sync)] +static_assertions::assert_impl_all!(Adapter: Send, Sync); + +#[derive(Debug)] +pub struct Queue { + shared: Arc<QueueShared>, + timestamp_period: f32, +} + +#[cfg(send_sync)] +static_assertions::assert_impl_all!(Queue: Send, Sync); + +impl Queue { + pub unsafe fn queue_from_raw( + raw: Retained<ProtocolObject<dyn MTLCommandQueue>>, + timestamp_period: f32, + ) -> Self { + Self { + shared: Arc::new(QueueShared { + raw, + command_buffer_created_not_submitted: atomic::AtomicUsize::new(0), + pending_waits: Mutex::new(Vec::new()), + pending_signals: Mutex::new(Vec::new()), + relay: OnceLock::new(), + }), + timestamp_period, + } + } + + pub fn as_raw(&self) -> &ProtocolObject<dyn MTLCommandQueue> { + &self.shared.raw + } + + /// Enable strict GPU-side ordering for [`Self::add_wait_event`]. + /// + /// By default, `add_wait_event` encodes the wait on a separate + /// internal command buffer. Metal allows independent command + /// buffers in a queue to overlap on the GPU, so a wait CB does + /// not strictly gate subsequent user command buffers when those + /// CBs share no Metal-tracked resources with it. Single-stream + /// pipelines often serialize anyway because the GPU has no other + /// concurrent work to fill the slot, but mixed workloads (decode + /// + compute + render) can race. + /// + /// When enabled, every [`crate::CommandEncoder::begin_encoding`] + /// pre-encodes a wait on an internal `MTLSharedEvent` at the start + /// of the new command buffer; every [`crate::Queue::submit`] then + /// signals that event after draining the staged external waits. + /// All command buffers since the previous submit are released in + /// lockstep once the foreign signals arrive, regardless of GPU + /// concurrency. + /// + /// Costs one extra `encodeWaitForEvent` per command buffer plus + /// one extra internal command buffer per submit on this queue. + /// Other queues are unaffected. + /// + /// Idempotent. Cannot be disabled - once enabled, the queue stays + /// in strict mode for its lifetime, since command buffers already + /// encoded would be stranded if the relay stopped firing. + pub fn enable_strict_event_sync(&self) -> Result<(), crate::DeviceError> { + if self.shared.relay.get().is_some() { + return Ok(()); + } + let event = self + .shared + .raw + .device() + .newSharedEvent() + .ok_or(crate::DeviceError::OutOfMemory)?; + let _ = self.shared.relay.set(Relay { + event, + next_release_value: atomic::AtomicU64::new(1), + commit_lock: Mutex::new(()), + }); + Ok(()) + } + + /// Stage an `MTLCommandBuffer::encodeWaitForEvent(event, value)` for + /// the next [`crate::Queue::submit`]. Lets external producers be waited + /// on without a CPU block. + /// + /// By default the wait is encoded onto a dedicated internal command + /// buffer committed before the submit's user CBs - best-effort under + /// cross-CB GPU concurrency, see [`Self::enable_strict_event_sync`] + /// for strict gating. With strict mode enabled, the wait is chained + /// through an internal relay event that gates every user command + /// buffer encoded since the previous submit. + /// + /// Staging is queue-wide, not per-thread or per-submit: any + /// `add_wait_event` call is consumed by whichever + /// [`crate::Queue::submit`] runs next on this queue. If you stage + /// events from multiple threads, coordinate the staging and the + /// submit yourself, or another thread's submit may drain your + /// pending waits. + pub fn add_wait_event(&self, event: Retained<ProtocolObject<dyn MTLSharedEvent>>, value: u64) { + self.shared.pending_waits.lock().push((event, value)); + } + + /// Remove `event` from the pending wait list if it is still present. + /// Returns `true` if it was found and removed. + pub fn remove_wait_event(&self, event: &ProtocolObject<dyn MTLSharedEvent>) -> bool { + let target: *const ProtocolObject<dyn MTLSharedEvent> = event; + let mut waits = self.shared.pending_waits.lock(); + let before = waits.len(); + waits.retain(|(e, _)| Retained::as_ptr(e) != target); + waits.len() != before + } + + /// Stage an `MTLCommandBuffer::encodeSignalEvent(event, value)` for + /// the next [`crate::Queue::submit`]. The signal is encoded after + /// the submit's own completion signal, so a foreign API waiting on + /// `(event, value)` observes the wgpu work as done. + /// + /// Staging is queue-wide, not per-thread or per-submit: see + /// [`Self::add_wait_event`] for the threading caveat. + pub fn add_signal_event( + &self, + event: Retained<ProtocolObject<dyn MTLSharedEvent>>, + value: u64, + ) { + self.shared.pending_signals.lock().push((event, value)); + } + + /// Remove `event` from the pending signal list if it is still present. + /// Returns `true` if it was found and removed. + pub fn remove_signal_event(&self, event: &ProtocolObject<dyn MTLSharedEvent>) -> bool { + let target: *const ProtocolObject<dyn MTLSharedEvent> = event; + let mut signals = self.shared.pending_signals.lock(); + let before = signals.len(); + signals.retain(|(e, _)| Retained::as_ptr(e) != target); + signals.len() != before + } +} + +type PendingEvents = Mutex<Vec<(Retained<ProtocolObject<dyn MTLSharedEvent>>, u64)>>; + +/// Internal relay used by [`Queue::enable_strict_event_sync`] to chain +/// staged waits across all CBs in a submit. +/// +/// `begin_encoding` reads `next_release_value` and pre-encodes +/// `encodeWaitForEvent(event, expected)` at the start of each CB. +/// `submit` claims the value via `fetch_add`, encodes the foreign +/// waits + `encodeSignalEvent(event, claimed)` on a wait CB, and +/// commits it. `commit_lock` serializes the claim+commit pair so +/// concurrent submits land their signals in monotonic *commit* order +/// on the CPU. GPU-side execution of the resulting wait CBs may still +/// reorder under concurrency; see the comment in `submit` for why +/// that's harmless. +#[derive(Debug)] +struct Relay { + event: Retained<ProtocolObject<dyn MTLSharedEvent>>, + next_release_value: atomic::AtomicU64, + commit_lock: Mutex<()>, +} + +#[derive(Debug)] +pub struct QueueShared { + raw: Retained<ProtocolObject<dyn MTLCommandQueue>>, + // Tracks command buffers created via `CommandEncoder::begin_encoding` that + // have not yet been submitted or discarded. Used to proactively fail + // before hitting Metal's `maxCommandBufferCount`. + // + // (In a few places we call `.commandBuffer{,WithUnretainedReferences}` directly + // to create command buffers for internal purposes. In those cases we always + // commit the buffer immediately, so we don't adjust the counter for them.) + command_buffer_created_not_submitted: atomic::AtomicUsize, + pending_waits: PendingEvents, + pending_signals: PendingEvents, + relay: OnceLock<Relay>, +} + +#[derive(Debug)] +pub struct Device { + shared: Arc<AdapterShared>, + features: wgt::Features, + counters: Arc<wgt::HalCounters>, + limits: wgt::Limits, +} + +#[derive(Debug)] +pub struct Surface { + render_layer: Mutex<Retained<CAMetalLayer>>, + swapchain_format: RwLock<Option<wgt::TextureFormat>>, + extent: RwLock<wgt::Extent3d>, +} + +unsafe impl Send for Surface {} +unsafe impl Sync for Surface {} + +#[derive(Debug)] +pub struct SurfaceTexture { + texture: Texture, + // Useful for UI-intensive applications that are sensitive to + // window resizing. + drawable: Retained<ProtocolObject<dyn MTLDrawable>>, + present_with_transaction: bool, +} + +impl crate::DynSurfaceTexture for SurfaceTexture {} + +impl core::borrow::Borrow<Texture> for SurfaceTexture { + fn borrow(&self) -> &Texture { + &self.texture + } +} + +impl core::borrow::Borrow<dyn crate::DynTexture> for SurfaceTexture { + fn borrow(&self) -> &dyn crate::DynTexture { + &self.texture + } +} + +unsafe impl Send for SurfaceTexture {} +unsafe impl Sync for SurfaceTexture {} + +impl crate::Queue for Queue { + type A = Api; + + unsafe fn submit( + &self, + command_buffers: &[&CommandBuffer], + _surface_textures: &[&SurfaceTexture], + (signal_fence, signal_value): (&Fence, crate::FenceValue), + ) -> Result<(), crate::DeviceError> { + autoreleasepool(|_| { + // Drain caller-staged waits onto a dedicated command buffer + // committed before the user CBs. + // + // When strict event sync is enabled, this CB also signals + // the relay event to release every user CB encoded since + // the previous submit (see `Queue::enable_strict_event_sync`). + // The `commit_lock` is held across `fetch_add` + `commit` so + // concurrent submits land their relay signals in monotonic + // *commit* order on the CPU side; otherwise a later-claimed + // signal could commit first and the subsequent backward + // signal would temporarily regress the relay's signaledValue. + // + // GPU-side ordering across independent wait CBs remains + // best-effort: Metal may run them in parallel, so a wait CB + // with foreign waits can fire its signal after a later + // submit's wait-free signal. CBs already released stay + // released (`MTLSharedEvent` waits are `>=`), and future + // submits' signals catch the value back up, so the regression + // is harmless - but users wanting strict GPU-side ordering + // across concurrent submits must serialize submits themselves. + // + // Without strict mode, we only emit a wait CB when there are + // pending waits - keeps the common-case submit overhead-free. + { + let relay = self.shared.relay.get(); + let mut waits = self.shared.pending_waits.lock(); + if relay.is_some() || !waits.is_empty() { + let _commit_guard = relay.map(|r| r.commit_lock.lock()); + // We do not bother adjusting `command_buffer_created_not_submitted` + // because we immediately commit this buffer. + let wait_cb = self + .shared + .raw + .commandBufferWithUnretainedReferences() + .ok_or(crate::DeviceError::Lost)?; + wait_cb.setLabel(Some(ns_string!("(wgpu internal) Wait"))); + for (event, value) in waits.drain(..) { + wait_cb.encodeWaitForEvent_value(event.as_ref(), value); + } + if let Some(relay) = relay { + let release = relay + .next_release_value + .fetch_add(1, atomic::Ordering::AcqRel); + wait_cb.encodeSignalEvent_value(relay.event.as_ref(), release); + } + wait_cb.commit(); + } + } + + let extra_command_buffer = { + let fence_sync = Arc::clone(&signal_fence.sync); + let block = block2::RcBlock::new(move |_cmd_buf| { + *fence_sync.0.lock() = signal_value; + fence_sync.1.notify_all(); + }); + + let raw = match command_buffers.last() { + Some(&cmd_buf) => cmd_buf.raw.clone(), + None => { + // We do not bother adjusting `command_buffer_created_not_submitted` + // because we immediately commit this buffer. + self.shared + .raw + .commandBufferWithUnretainedReferences() + .ok_or(crate::DeviceError::Lost)? + } + }; + raw.setLabel(Some(ns_string!("(wgpu internal) Signal"))); + unsafe { raw.addCompletedHandler(block2::RcBlock::as_ptr(&block)) }; + + signal_fence.maintain(); + signal_fence + .pending_command_buffers + .write() + .push((signal_value, raw.clone())); + + if let Some(shared_event) = &signal_fence.shared_event { + raw.encodeSignalEvent_value(shared_event.as_ref(), signal_value); + } + + // Drain caller-staged signals after our own signal so each + // additional event value publishes once the submit completes. + { + let mut signals = self.shared.pending_signals.lock(); + for (event, value) in signals.drain(..) { + raw.encodeSignalEvent_value(event.as_ref(), value); + } + } + + // only return an extra one if it's extra + match command_buffers.last() { + Some(_) => None, + None => Some(raw), + } + }; + + for cmd_buffer in command_buffers { + cmd_buffer.raw.commit(); + // One command buffer per `end_encoding` call moves from the + // "created but not yet submitted" bucket into the submitted + // set, so update the counter. + let previous = self + .shared + .command_buffer_created_not_submitted + .fetch_sub(1, atomic::Ordering::AcqRel); + debug_assert!(previous > 0); + } + + if let Some(raw) = extra_command_buffer { + raw.commit(); + } + Ok(()) + }) + } + unsafe fn present( + &self, + _surface: &Surface, + texture: SurfaceTexture, + ) -> Result<(), crate::SurfaceError> { + autoreleasepool(|_| { + // We do not bother adjusting `command_buffer_created_not_submitted` + // because we immediately commit this buffer. + let command_buffer = self.shared.raw.commandBuffer().unwrap(); + command_buffer.setLabel(Some(ns_string!("(wgpu internal) Present"))); + + // https://developer.apple.com/documentation/quartzcore/cametallayer/1478157-presentswithtransaction?language=objc + if !texture.present_with_transaction { + command_buffer.presentDrawable(&texture.drawable); + } + + command_buffer.commit(); + + if texture.present_with_transaction { + command_buffer.waitUntilScheduled(); + texture.drawable.present(); + } + }); + Ok(()) + } + + unsafe fn get_timestamp_period(&self) -> f32 { + self.timestamp_period + } + + unsafe fn wait_for_idle(&self) -> Result<(), crate::DeviceError> { + autoreleasepool(|_| { + let command_buffer = self.shared.raw.commandBuffer().unwrap(); + command_buffer.setLabel(Some(ns_string!("(wgpu internal) wait_for_idle"))); + command_buffer.commit(); + command_buffer.waitUntilCompleted(); + }); + Ok(()) + } +} + +#[derive(Debug)] +pub struct Buffer { + raw: Retained<ProtocolObject<dyn MTLBuffer>>, + size: wgt::BufferAddress, +} + +unsafe impl Send for Buffer {} +unsafe impl Sync for Buffer {} + +impl crate::DynBuffer for Buffer {} + +impl Buffer { + fn as_raw(&self) -> NonNull<ProtocolObject<dyn MTLBuffer>> { + unsafe { NonNull::new_unchecked(Retained::as_ptr(&self.raw) as *mut _) } + } +} + +impl crate::BufferBinding<'_, Buffer> { + fn resolve_size(&self) -> wgt::BufferAddress { + match self.size { + Some(size) => size.get(), + None => self.buffer.size - self.offset, + } + } +} + +#[derive(Debug)] +pub struct Texture { + raw: Retained<ProtocolObject<dyn MTLTexture>>, + format: wgt::TextureFormat, + raw_type: MTLTextureType, + array_layers: u32, + mip_levels: u32, + copy_size: crate::CopyExtent, + + // The `drop_guard` field must be the last field of this struct so it is dropped last. + // Do not add new fields after it. + _drop_guard: Option<crate::DropGuard>, +} + +impl Texture { + pub fn raw_handle(&self) -> &ProtocolObject<dyn MTLTexture> { + &self.raw + } +} + +impl crate::DynTexture for Texture {} + +unsafe impl Send for Texture {} +unsafe impl Sync for Texture {} + +#[derive(Debug)] +pub struct TextureView { + raw: Retained<ProtocolObject<dyn MTLTexture>>, + aspects: crate::FormatAspects, +} + +impl crate::DynTextureView for TextureView {} + +unsafe impl Send for TextureView {} +unsafe impl Sync for TextureView {} + +impl TextureView { + fn as_raw(&self) -> NonNull<ProtocolObject<dyn MTLTexture>> { + unsafe { NonNull::new_unchecked(Retained::as_ptr(&self.raw) as *mut _) } + } +} + +#[derive(Debug)] +pub struct Sampler { + raw: Retained<ProtocolObject<dyn MTLSamplerState>>, +} + +impl crate::DynSampler for Sampler {} + +#[cfg(send_sync)] +static_assertions::assert_impl_all!(Sampler: Send, Sync); + +impl Sampler { + fn as_raw(&self) -> NonNull<ProtocolObject<dyn MTLSamplerState>> { + unsafe { NonNull::new_unchecked(Retained::as_ptr(&self.raw) as *mut _) } + } +} + +#[derive(Debug)] +pub struct BindGroupLayout { + /// Sorted list of BGL entries. + entries: Arc<[wgt::BindGroupLayoutEntry]>, +} + +impl crate::DynBindGroupLayout for BindGroupLayout {} + +#[derive(Clone, Debug, Default)] +struct ResourceData<T> { + buffers: T, + textures: T, + samplers: T, +} + +#[derive(Clone, Debug, Default)] +struct MultiStageData<T> { + vs: T, + fs: T, + cs: T, + ts: T, + ms: T, +} + +const NAGA_STAGES: MultiStageData<naga::ShaderStage> = MultiStageData { + vs: naga::ShaderStage::Vertex, + fs: naga::ShaderStage::Fragment, + cs: naga::ShaderStage::Compute, + ts: naga::ShaderStage::Task, + ms: naga::ShaderStage::Mesh, +}; + +impl<T> ops::Index<naga::ShaderStage> for MultiStageData<T> { + type Output = T; + fn index(&self, stage: naga::ShaderStage) -> &T { + match stage { + naga::ShaderStage::Vertex => &self.vs, + naga::ShaderStage::Fragment => &self.fs, + naga::ShaderStage::Compute => &self.cs, + naga::ShaderStage::Task => &self.ts, + naga::ShaderStage::Mesh => &self.ms, + naga::ShaderStage::RayGeneration + | naga::ShaderStage::AnyHit + | naga::ShaderStage::ClosestHit + | naga::ShaderStage::Miss => unimplemented!(), + } + } +} + +impl<T> MultiStageData<T> { + fn map_ref<Y>(&self, fun: impl Fn(&T) -> Y) -> MultiStageData<Y> { + MultiStageData { + vs: fun(&self.vs), + fs: fun(&self.fs), + cs: fun(&self.cs), + ts: fun(&self.ts), + ms: fun(&self.ms), + } + } + fn map<Y>(self, fun: impl Fn(T) -> Y) -> MultiStageData<Y> { + MultiStageData { + vs: fun(self.vs), + fs: fun(self.fs), + cs: fun(self.cs), + ts: fun(self.ts), + ms: fun(self.ms), + } + } + fn iter<'a>(&'a self) -> impl Iterator<Item = &'a T> { + iter::once(&self.vs) + .chain(iter::once(&self.fs)) + .chain(iter::once(&self.cs)) + .chain(iter::once(&self.ts)) + .chain(iter::once(&self.ms)) + } + fn iter_mut<'a>(&'a mut self) -> impl Iterator<Item = &'a mut T> { + iter::once(&mut self.vs) + .chain(iter::once(&mut self.fs)) + .chain(iter::once(&mut self.cs)) + .chain(iter::once(&mut self.ts)) + .chain(iter::once(&mut self.ms)) + } +} + +type MultiStageResourceCounters = MultiStageData<ResourceData<ResourceIndex>>; +type MultiStageResources = MultiStageData<naga::back::msl::EntryPointResources>; + +#[derive(Debug)] +struct BindGroupLayoutInfo { + base_resource_indices: MultiStageResourceCounters, +} + +#[derive(Copy, Clone, Debug, Eq, PartialEq)] +struct ImmediateDataInfo { + count: u32, + buffer_index: ResourceIndex, +} + +#[derive(Debug)] +pub struct PipelineLayout { + bind_group_infos: [Option<BindGroupLayoutInfo>; crate::MAX_BIND_GROUPS], + immediates_infos: MultiStageData<Option<ImmediateDataInfo>>, + total_immediates: u32, + per_stage_map: MultiStageResources, + binding_array_length_map: FastHashMap<naga::ResourceBinding, u32>, +} + +impl crate::DynPipelineLayout for PipelineLayout {} + +#[derive(Debug)] +enum BufferLikeResource { + Buffer { + ptr: NonNull<ProtocolObject<dyn MTLBuffer>>, + offset: wgt::BufferAddress, + dynamic_index: Option<u32>, + + /// The buffer's size, if it is a [`Storage`] binding. Otherwise `None`. + /// + /// Buffers with the [`wgt::BufferBindingType::Storage`] binding type can + /// hold WGSL runtime-sized arrays. When one does, we must pass its size to + /// shader entry points to implement bounds checks and WGSL's `arrayLength` + /// function. See `device::CompiledShader::sized_bindings` for details. + /// + /// [`Storage`]: wgt::BufferBindingType::Storage + binding_size: Option<wgt::BufferSize>, + + binding_location: u32, + }, + + /// Bindless storage `binding_array`: one argument [`MTLBuffer`] (pointer table) plus element + /// byte sizes `(array index, size)` for `_buffer_sizes` / runtime-sized arrays. + /// + /// [`MTLBuffer`]: objc2_metal::MTLBuffer + StorageBindingArray { + ptr: NonNull<ProtocolObject<dyn MTLBuffer>>, + array_element_sizes: Vec<(u32, wgt::BufferSize)>, + binding_location: u32, + }, + AccelerationStructure(NonNull<ProtocolObject<dyn MTLAccelerationStructure>>), +} + +#[derive(Debug)] +struct UseResourceInfo { + uses: MTLResourceUsage, + stages: MTLRenderStages, + visible_in_compute: bool, +} + +impl Default for UseResourceInfo { + fn default() -> Self { + Self { + uses: MTLResourceUsage::empty(), + stages: MTLRenderStages::empty(), + visible_in_compute: false, + } + } +} + +#[derive(Debug, Default)] +pub struct BindGroup { + counters: MultiStageResourceCounters, + buffers: Vec<BufferLikeResource>, + samplers: Vec<NonNull<ProtocolObject<dyn MTLSamplerState>>>, + textures: Vec<NonNull<ProtocolObject<dyn MTLTexture>>>, + + argument_buffers: Vec<Retained<ProtocolObject<dyn MTLBuffer>>>, + resources_to_use: HashMap<NonNull<ProtocolObject<dyn MTLResource>>, UseResourceInfo>, +} + +impl crate::DynBindGroup for BindGroup {} + +unsafe impl Send for BindGroup {} +unsafe impl Sync for BindGroup {} + +#[derive(Debug)] +pub enum ShaderModuleSource { + Naga(crate::NagaShader), + Passthrough(PassthroughShader), +} + +#[derive(Debug)] +pub struct PassthroughShader { + pub library: Retained<ProtocolObject<dyn MTLLibrary>>, + pub num_workgroups: HashMap<String, (u32, u32, u32)>, +} + +#[cfg(send_sync)] +static_assertions::assert_impl_all!(PassthroughShader: Send, Sync); + +#[derive(Debug)] +pub struct ShaderModule { + source: ShaderModuleSource, + runtime_checks: wgt::ShaderRuntimeChecks, +} + +impl crate::DynShaderModule for ShaderModule {} + +#[derive(Debug)] +struct PipelineStageInfo { + #[allow(dead_code)] + library: Option<Retained<ProtocolObject<dyn MTLLibrary>>>, + immediates: Option<ImmediateDataInfo>, + + /// The buffer argument table index at which we pass runtime-sized arrays' buffer sizes. + /// + /// See `device::CompiledShader::sized_bindings` for more details. + sizes_slot: Option<naga::back::msl::Slot>, + + /// Bindings of all WGSL `storage` globals that contain runtime-sized arrays. + /// + /// See `device::CompiledShader::sized_bindings` for more details. + sized_bindings: Vec<(naga::ResourceBinding, u32)>, + + /// Info on all bound vertex buffers. + vertex_buffer_mappings: Vec<naga::back::msl::VertexBufferMapping>, + + /// The workgroup size for compute, task or mesh stages + raw_wg_size: MTLSize, + + /// The workgroup memory sizes for compute task or mesh stages + work_group_memory_sizes: Vec<u32>, +} + +// TODO(madsmtm): Derive this when a release with +// https://github.com/madsmtm/objc2/issues/804 is available (likely 0.4). +impl Default for PipelineStageInfo { + fn default() -> Self { + Self { + library: Default::default(), + immediates: Default::default(), + sizes_slot: Default::default(), + sized_bindings: Default::default(), + vertex_buffer_mappings: Default::default(), + raw_wg_size: MTLSize { + width: 0, + height: 0, + depth: 0, + }, + work_group_memory_sizes: Default::default(), + } + } +} + +impl PipelineStageInfo { + fn clear(&mut self) { + self.immediates = None; + self.sizes_slot = None; + self.sized_bindings.clear(); + self.vertex_buffer_mappings.clear(); + self.library = None; + self.work_group_memory_sizes.clear(); + self.raw_wg_size = MTLSize { + width: 0, + height: 0, + depth: 0, + }; + } + + fn assign_from(&mut self, other: &Self) { + self.immediates = other.immediates; + self.sizes_slot = other.sizes_slot; + self.sized_bindings.clear(); + self.sized_bindings.extend_from_slice(&other.sized_bindings); + self.vertex_buffer_mappings.clear(); + self.vertex_buffer_mappings + .extend_from_slice(&other.vertex_buffer_mappings); + self.library = Some(other.library.as_ref().unwrap().clone()); + self.raw_wg_size = other.raw_wg_size; + self.work_group_memory_sizes.clear(); + self.work_group_memory_sizes + .extend_from_slice(&other.work_group_memory_sizes); + } +} + +#[derive(Debug)] +pub struct RenderPipeline { + raw: Retained<ProtocolObject<dyn MTLRenderPipelineState>>, + vs_info: Option<PipelineStageInfo>, + fs_info: Option<PipelineStageInfo>, + ts_info: Option<PipelineStageInfo>, + ms_info: Option<PipelineStageInfo>, + raw_primitive_type: MTLPrimitiveType, + raw_triangle_fill_mode: MTLTriangleFillMode, + raw_front_winding: MTLWinding, + raw_cull_mode: MTLCullMode, + raw_depth_clip_mode: Option<MTLDepthClipMode>, + depth_stencil: Option<( + Retained<ProtocolObject<dyn MTLDepthStencilState>>, + wgt::DepthBiasState, + )>, +} + +#[cfg(send_sync)] +static_assertions::assert_impl_all!(RenderPipeline: Send, Sync); + +impl crate::DynRenderPipeline for RenderPipeline {} + +#[derive(Debug)] +pub struct ComputePipeline { + raw: Retained<ProtocolObject<dyn MTLComputePipelineState>>, + cs_info: PipelineStageInfo, +} + +#[cfg(send_sync)] +static_assertions::assert_impl_all!(ComputePipeline: Send, Sync); + +impl crate::DynComputePipeline for ComputePipeline {} + +#[derive(Debug)] +pub struct RayTracingPipeline {} + +impl crate::DynRayTracingPipeline for RayTracingPipeline {} + +#[derive(Debug, Clone)] +pub struct QuerySet { + raw_buffer: Retained<ProtocolObject<dyn MTLBuffer>>, + //Metal has a custom buffer for counters. + counter_sample_buffer: Option<Retained<ProtocolObject<dyn MTLCounterSampleBuffer>>>, + ty: wgt::QueryType, +} + +impl crate::DynQuerySet for QuerySet {} + +unsafe impl Send for QuerySet {} +unsafe impl Sync for QuerySet {} + +#[derive(Debug)] +pub struct Fence { + sync: Arc<(Mutex<crate::FenceValue>, Condvar)>, + /// The pending fence values have to be ascending. + pending_command_buffers: RwLock<Vec<PendingCommandBuffer>>, + shared_event: Option<Retained<ProtocolObject<dyn MTLSharedEvent>>>, +} + +type PendingCommandBuffer = ( + crate::FenceValue, + Retained<ProtocolObject<dyn MTLCommandBuffer>>, +); + +impl crate::DynFence for Fence {} + +unsafe impl Send for Fence {} +unsafe impl Sync for Fence {} + +impl Fence { + fn get_latest(&self) -> crate::FenceValue { + let mut max_value = *self.sync.0.lock(); + let pending_command_buffers = self.pending_command_buffers.read(); + for &(value, ref cmd_buf) in pending_command_buffers.iter() { + match cmd_buf.status() { + MTLCommandBufferStatus::Completed | MTLCommandBufferStatus::Error => { + max_value = value; + } + _ => {} + } + } + max_value + } + + fn maintain(&self) { + let latest = self.get_latest(); + self.pending_command_buffers + .write() + .retain(|&(value, _)| value > latest); + } + + pub fn raw_shared_event(&self) -> Option<&ProtocolObject<dyn MTLSharedEvent>> { + self.shared_event.as_deref() + } +} + +struct IndexState { + buffer_ptr: NonNull<ProtocolObject<dyn MTLBuffer>>, + offset: wgt::BufferAddress, + stride: wgt::BufferAddress, + raw_type: MTLIndexType, +} + +#[derive(Default)] +struct Temp { + binding_sizes: Vec<u32>, +} + +// Any state in this struct that may be dirty after an abandoned encoding must +// be reset in `discard_encoding` for possible encoder reuse. +struct CommandState { + blit: Option<Retained<ProtocolObject<dyn MTLBlitCommandEncoder>>>, + acceleration_structure_builder: + Option<Retained<ProtocolObject<dyn MTLAccelerationStructureCommandEncoder>>>, + render: Option<Retained<ProtocolObject<dyn MTLRenderCommandEncoder>>>, + compute: Option<Retained<ProtocolObject<dyn MTLComputeCommandEncoder>>>, + raw_primitive_type: MTLPrimitiveType, + index: Option<IndexState>, + stage_infos: MultiStageData<PipelineStageInfo>, + + /// Sizes of currently bound [`wgt::BufferBindingType::Storage`] buffers. + /// + /// Specifically: + /// + /// - The keys are [`ResourceBinding`] values (that is, the WGSL `@group` + /// and `@binding` attributes) for `var<storage>` global variables in the + /// current module that contain runtime-sized arrays. + /// + /// - The values are the actual sizes of the buffers currently bound to + /// provide those globals' contents, which are needed to implement bounds + /// checks and the WGSL `arrayLength` function. + /// + /// For each stage `S` in `stage_infos`, we consult this to find the sizes + /// of the buffers listed in `stage_infos.S.sized_bindings`, which we must + /// pass to the entry point. + /// + /// See `device::CompiledShader::sized_bindings` for more details. + /// + /// [`ResourceBinding`]: naga::ResourceBinding + storage_buffer_length_map: FastHashMap<(naga::ResourceBinding, u32), wgt::BufferSize>, + + vertex_buffer_size_map: FastHashMap<u32, wgt::BufferSize>, + + immediates: Vec<u32>, + + /// Timer query that should be executed when the next pass starts. + pending_timer_queries: Vec<(QuerySet, u32)>, +} + +// Any state in this struct that may be dirty after an abandoned encoding must +// be reset in `discard_encoding` for possible encoder reuse. +pub struct CommandEncoder { + shared: Arc<AdapterShared>, + queue_shared: Arc<QueueShared>, + raw_cmd_buf: Option<Retained<ProtocolObject<dyn MTLCommandBuffer>>>, + state: CommandState, + temp: Temp, + counters: Arc<wgt::HalCounters>, +} + +impl fmt::Debug for CommandEncoder { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("CommandEncoder") + .field("raw_cmd_buf", &self.raw_cmd_buf) + .finish() + } +} + +unsafe impl Send for CommandEncoder {} +unsafe impl Sync for CommandEncoder {} + +#[derive(Debug)] +pub struct CommandBuffer { + raw: Retained<ProtocolObject<dyn MTLCommandBuffer>>, + queue_shared: Arc<QueueShared>, +} + +impl crate::DynCommandBuffer for CommandBuffer {} + +unsafe impl Send for CommandBuffer {} +unsafe impl Sync for CommandBuffer {} + +#[derive(Debug)] +pub struct PipelineCache; + +impl crate::DynPipelineCache for PipelineCache {} + +#[derive(Debug)] +pub struct AccelerationStructure { + raw: Retained<ProtocolObject<dyn MTLAccelerationStructure>>, +} + +impl AccelerationStructure { + fn as_raw(&self) -> NonNull<ProtocolObject<dyn MTLAccelerationStructure>> { + unsafe { NonNull::new_unchecked(Retained::as_ptr(&self.raw) as *mut _) } + } +} + +impl crate::DynAccelerationStructure for AccelerationStructure {} +unsafe impl Send for AccelerationStructure {} +unsafe impl Sync for AccelerationStructure {} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum OsType { + Macos, + Ios, + Tvos, + VisionOs, +} diff --git a/app/vendor/rune/vendor/wgpu-hal/src/metal/surface.rs b/app/vendor/rune/vendor/wgpu-hal/src/metal/surface.rs new file mode 100644 index 0000000..f8028a4 --- /dev/null +++ b/app/vendor/rune/vendor/wgpu-hal/src/metal/surface.rs @@ -0,0 +1,409 @@ +use std::sync::LazyLock; + +use alloc::borrow::ToOwned as _; + +use objc2::{ + available, + rc::{autoreleasepool, Retained}, + runtime::ProtocolObject, + ClassType, Message, +}; +use objc2_core_foundation::{CFString, CGSize}; +use objc2_core_graphics::CGColorSpace; +use objc2_foundation::NSObjectProtocol; +use objc2_metal::MTLTextureType; +use objc2_quartz_core::{CAMetalDrawable, CAMetalLayer}; +use parking_lot::{Mutex, RwLock}; + +use super::OsFeatures; + +/// Walks up from `start` to the `NSWindow` hosting this layer: the first ancestor +/// layer with a delegate is the backing `NSView`, and we return its `window`. +/// `None` if no ancestor has a delegate. +#[cfg(target_os = "macos")] +fn hosting_window( + start: Retained<objc2_quartz_core::CALayer>, +) -> Option<Retained<objc2::runtime::NSObject>> { + let mut current = Some(start); + while let Some(layer) = current { + if let Some(delegate) = layer.delegate() { + return unsafe { objc2::msg_send![&*delegate, window] }; + } + current = layer.superlayer(); + } + None +} + +impl super::Surface { + pub fn new(layer: Retained<CAMetalLayer>) -> Self { + Self { + render_layer: Mutex::new(layer), + swapchain_format: RwLock::new(None), + extent: RwLock::new(wgt::Extent3d::default()), + } + } + + pub fn from_layer(layer: &CAMetalLayer) -> Self { + assert!(layer.isKindOfClass(CAMetalLayer::class())); + Self::new(layer.retain()) + } + + pub fn render_layer(&self) -> &Mutex<Retained<CAMetalLayer>> { + &self.render_layer + } + + /// Returns the EDR headroom of the screen hosting this surface, as a + /// [`wgt::DisplayHdrInfo`]. + /// + /// macOS only. Returns `None` on other Apple platforms (iOS, tvOS, visionOS), + /// when the hosting screen can't be resolved (e.g. an off-screen window), or + /// when called off the main thread: `NSScreen` and `NSWindow` are + /// main-thread-only, and off-thread access is undefined behavior. + /// + /// Only `headroom` and the coarse `high_dynamic_range` bit are filled: Apple + /// exposes a relative EDR multiplier (`1.0` == SDR white), no absolute nits, + /// and no HDR-mode flag. `high_dynamic_range` tracks the live `current` + /// multiplier (`> 1.0`), so it reports HDR active, not merely capable. + pub(super) fn display_hdr_info(&self) -> Option<wgt::DisplayHdrInfo> { + #[cfg(target_os = "macos")] + { + use objc2::rc::Retained; + use objc2::runtime::NSObject; + + // Bail before any message send if we are not on the main thread. + // `MainThreadMarker::new()` is `None` off the main thread and does no + // Objective-C work, so it is a cheap, safe gate. + if objc2::MainThreadMarker::new().is_none() { + // Of the paths that yield `None`, this is the only one a caller + // can fix (the others — off-screen window, non-macOS — are + // environmental), so leave a breadcrumb instead of failing + // silently. Warn once per process so a caller that polls this + // per frame is not spammed. + static WARN_ONCE: std::sync::Once = std::sync::Once::new(); + WARN_ONCE.call_once(|| { + log::warn!( + "Surface::display_hdr_info() was called from thread {:?} \ + and will return None. On the Metal backend, it must be \ + called from the main thread to succeed.", + std::thread::current().id() + ); + }); + return None; + } + + // Take an owned reference to the layer and drop the lock before + // accessing the window and screen, so a main-thread AppKit callback + // can never deadlock against this lock. + let render_layer = { + let guard = self.render_layer.lock(); + guard.clone() + }; + + // Resolve the hosting `NSScreen` from the hosting window. `NSWindow.screen` + // is nil when the window is off-screen, so this can legitimately yield `None`. + let screen: Retained<NSObject> = autoreleasepool(|_| { + hosting_window(Retained::into_super(render_layer)) + .and_then(|window| unsafe { objc2::msg_send![&*window, screen] }) + })?; + + // AppKit documents these EDR properties as finite multipliers + // (`1.0` == SDR white), but guard against a non-finite read anyway so + // the advisory values stay finite and the coarse `high_dynamic_range` + // bit reports unknown (`None`) rather than a false `Some(false)`, + // mirroring the `is_finite` discipline in + // [`wgt::DisplayHdrInfo::tone_map_headroom`]. The EDR properties return + // `CGFloat` (`f64` on 64-bit macOS). + let finite = |v: f64| v.is_finite().then_some(v as f32); + + // `maximumExtendedDynamicRangeColorComponentValue` is macOS 10.11+, so + // it is safe at our 10.13 minimum. + let current: f64 = unsafe { + objc2::msg_send![&*screen, maximumExtendedDynamicRangeColorComponentValue] + }; + + // Apple exposes no discrete HDR-mode flag, so derive the coarse + // dynamic-range bit from the live `current` EDR multiplier (`> 1.0`), + // not `potential` (which is `> 1.0` on nearly every Apple display and + // would conflate "capable" with "active"). + let high_dynamic_range = current.is_finite().then_some(current > 1.0); + + // `maximumPotential...` and `maximumReference...` are macOS 10.15+, + // below which sending them would raise an unrecognized-selector + // exception, so only message them where available; otherwise leave + // them `None`. + let (potential, reference) = if available!(macos = 10.15) { + let potential: f64 = unsafe { + objc2::msg_send![ + &*screen, + maximumPotentialExtendedDynamicRangeColorComponentValue + ] + }; + let reference: f64 = unsafe { + objc2::msg_send![ + &*screen, + maximumReferenceExtendedDynamicRangeColorComponentValue + ] + }; + // AppKit reports `0.0` when there is no reference value; treat that + // (and any non-finite read) as "unknown" rather than a real `0.0`. + (finite(potential), finite(reference).filter(|&v| v > 0.0)) + } else { + (None, None) + }; + let headroom = wgt::DisplayHeadroom { + current: finite(current), + potential, + reference, + }; + + // `NSScreen.colorSpace` returns generic names on HDR panels + // post-Monterey, so deriving a gamut bucket from it would lie; leave + // `gamut` as `None` on macOS. + let coarse = wgt::DisplayCoarseRange { + high_dynamic_range, + gamut: None, + }; + + // Apple exposes no absolute nits, CIE-xy primaries, or panel bit + // depth, so `luminance` / `chromaticity` / `bits_per_color` stay `None`. + let info = wgt::DisplayHdrInfo { + luminance: None, + headroom: Some(headroom), + chromaticity: None, + coarse: Some(coarse), + bits_per_color: None, + }; + Some(info) + } + #[cfg(not(target_os = "macos"))] + { + // TODO: iOS/tvOS/visionOS could report EDR headroom via + // `UIScreen.currentEDRHeadroom`. + None + } + } + + /// Gets the current dimensions of the `Surface`. + /// + /// This function is safe to call off of the main thread. However, note that + /// `bounds` and `contentsScale` may be modified by the main thread while + /// this function is running, possibly resulting in the two values being out + /// of sync. This is sound, as these properties are accessed atomically. + /// See: <https://github.com/gfx-rs/wgpu/pull/7692> + pub(super) fn dimensions(&self) -> wgt::Extent3d { + let (size, scale) = { + let render_layer = self.render_layer.lock(); + let bounds = render_layer.bounds(); + let contents_scale = render_layer.contentsScale(); + (bounds.size, contents_scale) + }; + + wgt::Extent3d { + width: (size.width * scale) as u32, + height: (size.height * scale) as u32, + depth_or_array_layers: 1, + } + } +} + +// objc2 strings are not, in general, thread-safe, but these should be constants. +unsafe impl Send for ColorSpaces {} +unsafe impl Sync for ColorSpaces {} + +struct ColorSpaces { + extended_display_p3: &'static CFString, + itur_bt2100_pq: &'static CFString, + itur_bt2100_hlg: &'static CFString, +} + +static COLOR_SPACES: LazyLock<Result<ColorSpaces, crate::SurfaceError>> = LazyLock::new(|| { + // Stable Rust doesn't support weak linkage, so objc2 doesn't + // offer it. To avoid link errors on old OS versions, resolve + // these dynamically. + let lib = unsafe { + libloading::Library::new("/System/Library/Frameworks/CoreGraphics.framework/CoreGraphics") + .map_err(|_| crate::SurfaceError::Other("error loading CoreGraphics"))? + }; + fn lookup( + lib: &libloading::Library, + name: &[u8], + ) -> Result<&'static CFString, crate::SurfaceError> { + let sym = unsafe { lib.get(name) } + .map_err(|_| crate::SurfaceError::Other("error resolving symbol in CoreGraphics"))?; + Ok(*sym) + } + let extended_display_p3 = lookup(&lib, b"kCGColorSpaceExtendedDisplayP3\0")?; + let itur_bt2100_pq = lookup(&lib, b"kCGColorSpaceITUR_2100_PQ\0")?; + let itur_bt2100_hlg = lookup(&lib, b"kCGColorSpaceITUR_2100_HLG\0")?; + Ok(ColorSpaces { + extended_display_p3, + itur_bt2100_pq, + itur_bt2100_hlg, + }) +}); + +impl crate::Surface for super::Surface { + type A = super::Api; + + unsafe fn configure( + &self, + device: &super::Device, + config: &crate::SurfaceConfiguration, + ) -> Result<(), crate::SurfaceError> { + log::debug!("build swapchain {config:?}"); + + let caps = &device.shared.private_texture_format_caps; + *self.swapchain_format.write() = Some(config.format); + *self.extent.write() = config.extent; + + let render_layer = self.render_layer.lock(); + let framebuffer_only = config.usage == wgt::TextureUses::COLOR_TARGET; + let display_sync = match config.present_mode { + wgt::PresentMode::Fifo => true, + wgt::PresentMode::Immediate => false, + m => unreachable!("Unsupported present mode: {m:?}"), + }; + // CGFloat is f64 on 64-bit, f32 on 32-bit (arm64_32/ILP32) + let drawable_size = CGSize::new(config.extent.width as _, config.extent.height as _); + + match config.composite_alpha_mode { + wgt::CompositeAlphaMode::Opaque => render_layer.setOpaque(true), + wgt::CompositeAlphaMode::PostMultiplied => render_layer.setOpaque(false), + _ => (), + } + + let device_raw = &device.shared.device; + render_layer.setDevice(Some(device_raw)); + render_layer.setPixelFormat(caps.map_format(config.format)); + render_layer.setFramebufferOnly(framebuffer_only); + // Opt into Metal EDR for the HDR color spaces (more display power, memory, + // and bandwidth). The HDR spaces are exactly those `is_hdr()` classifies. + let wants_edr = config.color_space.is_hdr(); + if wants_edr != render_layer.wantsExtendedDynamicRangeContent() { + render_layer.setWantsExtendedDynamicRangeContent(wants_edr); + } + + let colorspace_name: Option<&'static CFString> = match config.color_space { + wgt::SurfaceColorSpace::Auto => { + unreachable!("wgpu-core resolves `Auto` before configuring the surface") + } + // Reset to the layer's default, which treats contents as sRGB. + wgt::SurfaceColorSpace::Srgb => None, + wgt::SurfaceColorSpace::ExtendedSrgbLinear => { + Some(unsafe { objc2_core_graphics::kCGColorSpaceExtendedLinearSRGB }) + } + wgt::SurfaceColorSpace::ExtendedSrgb => { + Some(unsafe { objc2_core_graphics::kCGColorSpaceExtendedSRGB }) + } + wgt::SurfaceColorSpace::ExtendedDisplayP3 => { + // TODO: This needs protection in `surface_capabilities` like the BT.2100 cases. + Some( + COLOR_SPACES + .as_ref() + .map_err(|e| e.clone())? + .extended_display_p3, + ) + } + wgt::SurfaceColorSpace::DisplayP3 => { + Some(unsafe { objc2_core_graphics::kCGColorSpaceDisplayP3 }) + } + wgt::SurfaceColorSpace::Bt2100Pq | wgt::SurfaceColorSpace::Bt2100Hlg => { + // The ITUR_2100 color space constants require macOS 11.0/iOS 14.0; + // `surface_capabilities` only reports BT.2100 PQ/HLG on those OS versions. + if !available!(macos = 11.0, ios = 14.0, tvos = 14.0, visionos = 1.0) { + unreachable!("BT.2100 PQ/HLG color spaces are only reported on macOS 11.0+/iOS 14.0+/tvOS 14.0+"); + } + Some(if config.color_space == wgt::SurfaceColorSpace::Bt2100Pq { + COLOR_SPACES.as_ref().map_err(|e| e.clone())?.itur_bt2100_pq + } else { + COLOR_SPACES + .as_ref() + .map_err(|e| e.clone())? + .itur_bt2100_hlg + }) + } + }; + let colorspace = colorspace_name.and_then(|name| CGColorSpace::with_name(Some(name))); + render_layer.setColorspace(colorspace.as_deref()); + + // this gets ignored on iOS for certain OS/device combinations (iphone5s iOS 10.3) + render_layer.setMaximumDrawableCount(config.maximum_frame_latency as usize + 1); + render_layer.setDrawableSize(drawable_size); + // https://developer.apple.com/documentation/quartzcore/cametallayer/allowsnextdrawabletimeout + if available!(macos = 10.13, ios = 11.0, tvos = 11.0, visionos = 1.0) { + render_layer.setAllowsNextDrawableTimeout(false); + } + if OsFeatures::display_sync() { + render_layer.setDisplaySyncEnabled(display_sync); + } + + Ok(()) + } + + unsafe fn unconfigure(&self, _device: &super::Device) { + *self.swapchain_format.write() = None; + } + + unsafe fn acquire_texture( + &self, + _timeout: Option<core::time::Duration>, // TODO + _fence: &super::Fence, + ) -> Result<crate::AcquiredSurfaceTexture<super::Api>, crate::SurfaceError> { + let render_layer = self.render_layer.lock(); + + #[cfg(target_os = "macos")] + { + // Workaround for https://github.com/gfx-rs/wgpu/issues/8309 + // When the window is occluded on macOS, presented drawables get stuck waiting + // for vsync. Check the window's occlusion state and skip acquisition if + // the window is not visible - this avoids a 1-second hang in nextDrawable(). + use objc2::rc::Retained; + + // The CAMetalLayer is typically a sublayer; find the hosting window + // and skip acquisition while it is occluded. + if let Some(window) = hosting_window(Retained::into_super(render_layer.clone())) { + const NS_WINDOW_OCCLUSION_STATE_VISIBLE: usize = 1 << 1; + let occlusion_state: usize = unsafe { objc2::msg_send![&*window, occlusionState] }; + if occlusion_state & NS_WINDOW_OCCLUSION_STATE_VISIBLE == 0 { + return Err(crate::SurfaceError::Occluded); + } + } + } + + let (drawable, texture) = match autoreleasepool(|_| { + render_layer + .nextDrawable() + .map(|drawable| (drawable.to_owned(), drawable.texture().to_owned())) + }) { + Some(pair) => pair, + None => return Err(crate::SurfaceError::Timeout), + }; + + let swapchain_format = self.swapchain_format.read().unwrap(); + let extent = self.extent.read(); + let suf_texture = super::SurfaceTexture { + texture: super::Texture { + raw: texture, + format: swapchain_format, + raw_type: MTLTextureType::Type2D, + array_layers: 1, + mip_levels: 1, + copy_size: crate::CopyExtent { + width: extent.width, + height: extent.height, + depth: 1, + }, + _drop_guard: None, + }, + drawable: ProtocolObject::from_retained(drawable), + present_with_transaction: render_layer.presentsWithTransaction(), + }; + + Ok(crate::AcquiredSurfaceTexture { + texture: suf_texture, + suboptimal: false, + }) + } + + unsafe fn discard_texture(&self, _texture: super::SurfaceTexture) {} +} diff --git a/app/vendor/rune/vendor/wgpu-hal/src/metal/time.rs b/app/vendor/rune/vendor/wgpu-hal/src/metal/time.rs new file mode 100644 index 0000000..5c6bec1 --- /dev/null +++ b/app/vendor/rune/vendor/wgpu-hal/src/metal/time.rs @@ -0,0 +1,38 @@ +//! Handling of global timestamps. + +#[repr(C)] +#[derive(Debug)] +struct MachTimebaseInfo { + numerator: u32, + denominator: u32, +} +extern "C" { + fn mach_timebase_info(out: *mut MachTimebaseInfo) -> u32; + fn mach_absolute_time() -> u64; +} + +/// A timer which uses mach_absolute_time to get its time. This is what the metal callbacks use. +#[derive(Debug)] +pub struct PresentationTimer { + scale: MachTimebaseInfo, +} +impl PresentationTimer { + /// Generates a new timer. + pub fn new() -> Self { + // Default to 1 / 1 in case the call to timebase_info fails. + let mut scale = MachTimebaseInfo { + numerator: 1, + denominator: 1, + }; + unsafe { mach_timebase_info(&mut scale) }; + + Self { scale } + } + + /// Gets the current time in nanoseconds. + pub fn get_timestamp_ns(&self) -> u128 { + let time = unsafe { mach_absolute_time() }; + + (time as u128 * self.scale.numerator as u128) / self.scale.denominator as u128 + } +} diff --git a/app/vendor/rune/vendor/wgpu-hal/src/noop/buffer.rs b/app/vendor/rune/vendor/wgpu-hal/src/noop/buffer.rs new file mode 100644 index 0000000..9b8ab17 --- /dev/null +++ b/app/vendor/rune/vendor/wgpu-hal/src/noop/buffer.rs @@ -0,0 +1,88 @@ +use alloc::vec::Vec; +use core::{cell::UnsafeCell, ops::Range, ptr}; + +cfg_if::cfg_if! { + if #[cfg(supports_ptr_atomics)] { + use alloc::sync::Arc; + } else if #[cfg(feature = "portable-atomic")] { + use portable_atomic_util::Arc; + } +} + +#[derive(Clone, Debug)] +pub struct Buffer { + /// This data is potentially accessed mutably in arbitrary non-overlapping slices, + /// so we must store it in `UnsafeCell` to avoid making any too-strong no-aliasing claims. + storage: Arc<UnsafeCell<[u8]>>, + + /// Size of the allocation. + /// + /// This is redundant with `storage.get().len()`, but that method is not + /// available until our MSRV is 1.79 or greater. + size: usize, +} + +/// SAFETY: +/// This shared mutable data will not be accessed in a way which causes data races; +/// the obligation to do so is on the caller of the HAL API. +/// For safe code, `wgpu-core` validation manages appropriate access. +unsafe impl Send for Buffer {} +unsafe impl Sync for Buffer {} + +impl Buffer { + pub(super) fn new(desc: &crate::BufferDescriptor) -> Result<Self, crate::DeviceError> { + let &crate::BufferDescriptor { + label: _, + size, + usage: _, + memory_flags: _, + } = desc; + + let size = usize::try_from(size).map_err(|_| crate::DeviceError::OutOfMemory)?; + + let mut vector: Vec<u8> = Vec::new(); + vector + .try_reserve_exact(size) + .map_err(|_| crate::DeviceError::OutOfMemory)?; + vector.resize(size, 0); + let storage: Arc<[u8]> = Arc::from(vector); + debug_assert_eq!(storage.len(), size); + + // SAFETY: `UnsafeCell<[u8]>` and `[u8]` have the same layout. + // This is just adding a wrapper type without changing any layout, + // because there is not currently a safe language/`std` way to accomplish this. + let storage: Arc<UnsafeCell<[u8]>> = + unsafe { Arc::from_raw(Arc::into_raw(storage) as *mut UnsafeCell<[u8]>) }; + + Ok(Buffer { storage, size }) + } + + /// Returns a pointer to the memory owned by this buffer within the given `range`. + /// + /// This may be used to create any number of simultaneous pointers; + /// aliasing is only a concern when actually reading, writing, or converting the pointer + /// to a reference. + pub(super) fn get_slice_ptr(&self, range: crate::MemoryRange) -> *mut [u8] { + let base_ptr = self.storage.get(); + let range = range_to_usize(range, self.size); + + // We must obtain a slice pointer without ever creating a slice reference + // that could alias with another slice. + ptr::slice_from_raw_parts_mut( + // SAFETY: `range_to_usize` bounds checks this addition. + unsafe { base_ptr.cast::<u8>().add(range.start) }, + range.len(), + ) + } +} + +/// Convert a [`crate::MemoryRange`] to `Range<usize>` and bounds check it. +fn range_to_usize(range: crate::MemoryRange, upper_bound: usize) -> Range<usize> { + // Note: these assertions should be impossible to trigger from safe code. + // We're doing them anyway since this entire backend is for testing + // (except for when it is an unused placeholder) + let start = usize::try_from(range.start).expect("range too large"); + let end = usize::try_from(range.end).expect("range too large"); + assert!(start <= end && end <= upper_bound, "range out of bounds"); + start..end +} diff --git a/app/vendor/rune/vendor/wgpu-hal/src/noop/command.rs b/app/vendor/rune/vendor/wgpu-hal/src/noop/command.rs new file mode 100644 index 0000000..16cca58 --- /dev/null +++ b/app/vendor/rune/vendor/wgpu-hal/src/noop/command.rs @@ -0,0 +1,356 @@ +use alloc::vec::Vec; +use core::mem; +use core::ops::Range; + +use super::{Api, Buffer, DeviceResult, Resource}; + +/// Command buffer type, which performs double duty as the command encoder type too. +#[derive(Debug)] +pub struct CommandBuffer { + commands: Vec<Command>, +} + +#[derive(Debug)] +enum Command { + ClearBuffer { + buffer: Buffer, + range: crate::MemoryRange, + }, + CopyBufferToBuffer { + src: Buffer, + dst: Buffer, + regions: Vec<crate::BufferCopy>, + }, +} + +impl CommandBuffer { + /// # Safety + /// + /// Must be called with appropriate synchronization for the resources affected by the command, + /// such as ensuring that buffers are not accessed by a command while aliasing references exist. + pub(crate) unsafe fn execute(&self) { + for command in &self.commands { + unsafe { command.execute() }; + } + } + + pub(crate) fn new() -> Self { + Self { + commands: Vec::new(), + } + } +} + +impl crate::CommandEncoder for CommandBuffer { + type A = Api; + + unsafe fn begin_encoding(&mut self, label: crate::Label) -> DeviceResult<()> { + assert!(self.commands.is_empty()); + Ok(()) + } + unsafe fn discard_encoding(&mut self) { + self.commands.clear(); + } + unsafe fn end_encoding(&mut self) -> DeviceResult<CommandBuffer> { + Ok(CommandBuffer { + commands: mem::take(&mut self.commands), + }) + } + unsafe fn reset_all<I>(&mut self, command_buffers: I) {} + + unsafe fn transition_buffers<'a, T>(&mut self, barriers: T) + where + T: Iterator<Item = crate::BufferBarrier<'a, Buffer>>, + { + } + + unsafe fn transition_textures<'a, T>(&mut self, barriers: T) + where + T: Iterator<Item = crate::TextureBarrier<'a, Resource>>, + { + } + + unsafe fn clear_buffer(&mut self, buffer: &Buffer, range: crate::MemoryRange) { + self.commands.push(Command::ClearBuffer { + buffer: buffer.clone(), + range, + }) + } + + unsafe fn copy_buffer_to_buffer<T>(&mut self, src: &Buffer, dst: &Buffer, regions: T) + where + T: Iterator<Item = crate::BufferCopy>, + { + self.commands.push(Command::CopyBufferToBuffer { + src: src.clone(), + dst: dst.clone(), + regions: regions.collect(), + }); + } + + #[cfg(webgl)] + unsafe fn copy_external_image_to_texture<T>( + &mut self, + src: &wgt::CopyExternalImageSourceInfo, + dst: &Resource, + dst_premultiplication: bool, + regions: T, + ) where + T: Iterator<Item = crate::TextureCopy>, + { + } + + unsafe fn copy_texture_to_texture<T>( + &mut self, + src: &Resource, + src_usage: wgt::TextureUses, + dst: &Resource, + regions: T, + ) { + // TODO: consider implementing this and other texture manipulation + } + + unsafe fn copy_buffer_to_texture<T>(&mut self, src: &Buffer, dst: &Resource, regions: T) { + // TODO: consider implementing this and other texture manipulation + } + + unsafe fn copy_texture_to_buffer<T>( + &mut self, + src: &Resource, + src_usage: wgt::TextureUses, + dst: &Buffer, + regions: T, + ) { + // TODO: consider implementing this and other texture manipulation + } + + unsafe fn begin_query(&mut self, set: &Resource, index: u32) {} + unsafe fn end_query(&mut self, set: &Resource, index: u32) {} + unsafe fn write_timestamp(&mut self, set: &Resource, index: u32) {} + unsafe fn read_acceleration_structure_compact_size( + &mut self, + acceleration_structure: &Resource, + buf: &Buffer, + ) { + } + unsafe fn reset_queries(&mut self, set: &Resource, range: Range<u32>) {} + unsafe fn copy_query_results( + &mut self, + set: &Resource, + range: Range<u32>, + buffer: &Buffer, + offset: wgt::BufferAddress, + stride: wgt::BufferSize, + ) { + } + + // render + + unsafe fn begin_render_pass( + &mut self, + desc: &crate::RenderPassDescriptor<Resource, Resource>, + ) -> DeviceResult<()> { + Ok(()) + } + unsafe fn end_render_pass(&mut self) {} + + unsafe fn set_bind_group( + &mut self, + layout: &Resource, + index: u32, + group: &Resource, + dynamic_offsets: &[wgt::DynamicOffset], + ) { + } + unsafe fn set_immediates(&mut self, layout: &Resource, offset_bytes: u32, data: &[u32]) {} + + unsafe fn insert_debug_marker(&mut self, label: &str) {} + unsafe fn begin_debug_marker(&mut self, group_label: &str) {} + unsafe fn end_debug_marker(&mut self) {} + + unsafe fn set_render_pipeline(&mut self, pipeline: &Resource) {} + + unsafe fn set_index_buffer<'a>( + &mut self, + binding: crate::BufferBinding<'a, Buffer>, + format: wgt::IndexFormat, + ) { + } + unsafe fn set_vertex_buffer<'a>( + &mut self, + index: u32, + binding: crate::BufferBinding<'a, Buffer>, + ) { + } + unsafe fn set_viewport(&mut self, rect: &crate::Rect<f32>, depth_range: Range<f32>) {} + unsafe fn set_scissor_rect(&mut self, rect: &crate::Rect<u32>) {} + unsafe fn set_stencil_reference(&mut self, value: u32) {} + unsafe fn set_blend_constants(&mut self, color: &[f32; 4]) {} + + unsafe fn draw( + &mut self, + first_vertex: u32, + vertex_count: u32, + first_instance: u32, + instance_count: u32, + ) { + } + unsafe fn draw_indexed( + &mut self, + first_index: u32, + index_count: u32, + base_vertex: i32, + first_instance: u32, + instance_count: u32, + ) { + } + unsafe fn draw_mesh_tasks( + &mut self, + group_count_x: u32, + group_count_y: u32, + group_count_z: u32, + ) { + } + unsafe fn draw_indirect( + &mut self, + buffer: &Buffer, + offset: wgt::BufferAddress, + draw_count: u32, + ) { + } + unsafe fn draw_indexed_indirect( + &mut self, + buffer: &Buffer, + offset: wgt::BufferAddress, + draw_count: u32, + ) { + } + unsafe fn draw_mesh_tasks_indirect( + &mut self, + buffer: &<Self::A as crate::Api>::Buffer, + offset: wgt::BufferAddress, + draw_count: u32, + ) { + } + unsafe fn draw_indirect_count( + &mut self, + buffer: &Buffer, + offset: wgt::BufferAddress, + count_buffer: &Buffer, + count_offset: wgt::BufferAddress, + max_count: u32, + ) { + } + unsafe fn draw_indexed_indirect_count( + &mut self, + buffer: &Buffer, + offset: wgt::BufferAddress, + count_buffer: &Buffer, + count_offset: wgt::BufferAddress, + max_count: u32, + ) { + } + unsafe fn draw_mesh_tasks_indirect_count( + &mut self, + buffer: &<Self::A as crate::Api>::Buffer, + offset: wgt::BufferAddress, + count_buffer: &<Self::A as crate::Api>::Buffer, + count_offset: wgt::BufferAddress, + max_count: u32, + ) { + } + + // compute + + unsafe fn begin_compute_pass(&mut self, desc: &crate::ComputePassDescriptor<Resource>) {} + unsafe fn end_compute_pass(&mut self) {} + + unsafe fn set_compute_pipeline(&mut self, pipeline: &Resource) {} + + unsafe fn dispatch_workgroups(&mut self, count: [u32; 3]) {} + unsafe fn dispatch_workgroups_indirect(&mut self, buffer: &Buffer, offset: wgt::BufferAddress) { + } + + unsafe fn build_acceleration_structures<'a, T>( + &mut self, + _descriptor_count: u32, + descriptors: T, + ) where + Api: 'a, + T: IntoIterator<Item = crate::BuildAccelerationStructureDescriptor<'a, Buffer, Resource>>, + { + } + + unsafe fn place_acceleration_structure_barrier( + &mut self, + _barriers: crate::AccelerationStructureBarrier, + ) { + } + + unsafe fn copy_acceleration_structure_to_acceleration_structure( + &mut self, + src: &Resource, + dst: &Resource, + copy: wgt::AccelerationStructureCopy, + ) { + } + + unsafe fn set_acceleration_structure_dependencies( + command_buffers: &[&CommandBuffer], + dependencies: &[&Resource], + ) { + } + + unsafe fn begin_ray_tracing_pass(&mut self, _desc: &crate::RayTracingPassDescriptor) {} + + unsafe fn end_ray_tracing_pass(&mut self) {} + + unsafe fn set_ray_tracing_pipeline( + &mut self, + _pipeline: &<Self::A as crate::Api>::RayTracingPipeline, + ) { + } + + unsafe fn trace_rays( + &mut self, + _count: [u32; 3], + _ray_generation_group_data: crate::PipelineGroupData<Buffer>, + _miss_group_data: crate::PipelineGroupData<Buffer>, + _intersection_group_data: crate::PipelineGroupData<Buffer>, + ) { + } +} + +impl Command { + /// # Safety + /// + /// Must be called with appropriate synchronization for the resources affected by the command, + /// such as ensuring that buffers are not accessed by a command while aliasing references exist. + unsafe fn execute(&self) { + match self { + Command::ClearBuffer { ref buffer, range } => { + // SAFETY: + // Caller is responsible for ensuring this does not alias. + let buffer_slice: &mut [u8] = unsafe { &mut *buffer.get_slice_ptr(range.clone()) }; + buffer_slice.fill(0); + } + + Command::CopyBufferToBuffer { src, dst, regions } => { + for &crate::BufferCopy { + src_offset, + dst_offset, + size, + } in regions + { + // SAFETY: + // Caller is responsible for ensuring this does not alias. + let src_region: &[u8] = + unsafe { &*src.get_slice_ptr(src_offset..src_offset + size.get()) }; + let dst_region: &mut [u8] = + unsafe { &mut *dst.get_slice_ptr(dst_offset..dst_offset + size.get()) }; + dst_region.copy_from_slice(src_region); + } + } + } + } +} diff --git a/app/vendor/rune/vendor/wgpu-hal/src/noop/mod.rs b/app/vendor/rune/vendor/wgpu-hal/src/noop/mod.rs new file mode 100644 index 0000000..b2e397d --- /dev/null +++ b/app/vendor/rune/vendor/wgpu-hal/src/noop/mod.rs @@ -0,0 +1,487 @@ +#![allow(unused_variables)] + +use alloc::{string::String, sync::Arc, vec, vec::Vec}; +use core::{ptr, sync::atomic::Ordering, time::Duration}; + +#[cfg(supports_64bit_atomics)] +use core::sync::atomic::AtomicU64; +#[cfg(not(supports_64bit_atomics))] +use portable_atomic::AtomicU64; + +use crate::TlasInstance; + +mod buffer; +pub use buffer::Buffer; +mod command; +pub use command::CommandBuffer; + +#[derive(Clone, Debug)] +pub struct Api; + +#[derive(Debug)] +pub struct Context { + options: Arc<wgt::NoopBackendOptions>, +} +#[derive(Debug)] +pub struct Encoder; +#[derive(Debug)] +pub struct Resource; + +#[derive(Debug)] +pub struct Fence { + value: AtomicU64, +} + +type DeviceResult<T> = Result<T, crate::DeviceError>; + +impl crate::Api for Api { + const VARIANT: wgt::Backend = wgt::Backend::Noop; + + type Instance = Context; + type Surface = Context; + type Adapter = Context; + type Device = Context; + + type Queue = Context; + type CommandEncoder = CommandBuffer; + type CommandBuffer = CommandBuffer; + + type Buffer = Buffer; + type Texture = Resource; + type SurfaceTexture = Resource; + type TextureView = Resource; + type Sampler = Resource; + type QuerySet = Resource; + type Fence = Fence; + type AccelerationStructure = Resource; + type PipelineCache = Resource; + + type BindGroupLayout = Resource; + type BindGroup = Resource; + type PipelineLayout = Resource; + type ShaderModule = Resource; + type RenderPipeline = Resource; + type RayTracingPipeline = Resource; + type ComputePipeline = Resource; +} + +crate::impl_dyn_resource!(Buffer, CommandBuffer, Context, Fence, Resource); + +impl crate::DynAccelerationStructure for Resource {} +impl crate::DynBindGroup for Resource {} +impl crate::DynBindGroupLayout for Resource {} +impl crate::DynBuffer for Buffer {} +impl crate::DynCommandBuffer for CommandBuffer {} +impl crate::DynComputePipeline for Resource {} +impl crate::DynFence for Fence {} +impl crate::DynPipelineCache for Resource {} +impl crate::DynPipelineLayout for Resource {} +impl crate::DynQuerySet for Resource {} +impl crate::DynRenderPipeline for Resource {} +impl crate::DynRayTracingPipeline for Resource {} +impl crate::DynSampler for Resource {} +impl crate::DynShaderModule for Resource {} +impl crate::DynSurfaceTexture for Resource {} +impl crate::DynTexture for Resource {} +impl crate::DynTextureView for Resource {} + +impl core::borrow::Borrow<dyn crate::DynTexture> for Resource { + fn borrow(&self) -> &dyn crate::DynTexture { + self + } +} + +impl crate::Instance for Context { + type A = Api; + + unsafe fn init(desc: &crate::InstanceDescriptor<'_>) -> Result<Self, crate::InstanceError> { + let options = Arc::new(desc.backend_options.noop.clone()); + if options.enable { + Ok(Context { options }) + } else { + Err(crate::InstanceError::new(String::from( + "noop backend disabled because NoopBackendOptions::enable is false", + ))) + } + } + unsafe fn create_surface( + &self, + _display_handle: raw_window_handle::RawDisplayHandle, + _window_handle: raw_window_handle::RawWindowHandle, + ) -> Result<Context, crate::InstanceError> { + Ok(Context { + options: Arc::clone(&self.options), + }) + } + unsafe fn enumerate_adapters( + &self, + _surface_hint: Option<&Context>, + ) -> Vec<crate::ExposedAdapter<Api>> { + let device_type = self.options.device_type.unwrap_or(wgt::DeviceType::Other); + let subgroup_min_size = self + .options + .subgroup_min_size + .unwrap_or(wgt::MINIMUM_SUBGROUP_MIN_SIZE); + let subgroup_max_size = self + .options + .subgroup_max_size + .unwrap_or(wgt::MAXIMUM_SUBGROUP_MAX_SIZE); + let features = self.options.features.unwrap_or(wgt::Features::all()); + let limits = self + .options + .limits + .clone() + .unwrap_or(CAPABILITIES.limits.clone()); + + let info = wgt::AdapterInfo { + subgroup_min_size, + subgroup_max_size, + ..adapter_info() + }; + + let capabilities = crate::Capabilities { + limits, + ..CAPABILITIES + }; + + vec![crate::ExposedAdapter { + adapter: Context { + options: Arc::clone(&self.options), + }, + info, + features, + capabilities, + }] + } +} + +/// Returns the adapter info for the noop backend. +/// +/// This is used in the test harness to construct info about +/// the noop backend adapter without actually initializing wgpu. +pub fn adapter_info() -> wgt::AdapterInfo { + wgt::AdapterInfo { + name: String::from("noop wgpu backend"), + driver: String::from("wgpu"), + ..wgt::AdapterInfo::new(wgt::DeviceType::Cpu, wgt::Backend::Noop) + } +} + +/// The capabilities of the noop backend. +/// +/// This is used in the test harness to construct capabilities +/// of the noop backend without actually initializing wgpu. +pub const CAPABILITIES: crate::Capabilities = { + crate::Capabilities { + limits: wgt::Limits::unlimited(), + alignments: crate::Alignments { + // All maximally permissive + buffer_copy_offset: wgt::BufferSize::MIN, + buffer_copy_pitch: wgt::BufferSize::MIN, + uniform_bounds_check_alignment: wgt::BufferSize::MIN, + raw_tlas_instance_size: 0, + ray_tracing_scratch_buffer_alignment: 1, + ray_tracing_pipeline_group_data_size: 1, + ray_tracing_pipeline_group_data_alignment: 1, + ray_tracing_pipeline_data_offset_alignment: 1, + }, + downlevel: wgt::DownlevelCapabilities { + flags: wgt::DownlevelFlags::all(), + limits: wgt::DownlevelLimits {}, + shader_model: wgt::ShaderModel::Sm5, + }, + cooperative_matrix_properties: Vec::new(), + } +}; + +impl crate::Surface for Context { + type A = Api; + + unsafe fn configure( + &self, + device: &Context, + config: &crate::SurfaceConfiguration, + ) -> Result<(), crate::SurfaceError> { + Ok(()) + } + + unsafe fn unconfigure(&self, device: &Context) {} + + unsafe fn acquire_texture( + &self, + _timeout: Option<Duration>, + _fence: &Fence, + ) -> Result<crate::AcquiredSurfaceTexture<Api>, crate::SurfaceError> { + Err(crate::SurfaceError::Timeout) + } + unsafe fn discard_texture(&self, texture: Resource) {} +} + +impl crate::Adapter for Context { + type A = Api; + + unsafe fn open( + &self, + features: wgt::Features, + _limits: &wgt::Limits, + _memory_hints: &wgt::MemoryHints, + ) -> DeviceResult<crate::OpenDevice<Api>> { + Ok(crate::OpenDevice { + device: Context { + options: Arc::clone(&self.options), + }, + queue: Context { + options: Arc::clone(&self.options), + }, + }) + } + unsafe fn texture_format_capabilities( + &self, + format: wgt::TextureFormat, + ) -> crate::TextureFormatCapabilities { + crate::TextureFormatCapabilities::empty() + } + + unsafe fn surface_capabilities(&self, surface: &Context) -> Option<crate::SurfaceCapabilities> { + None + } + + unsafe fn get_presentation_timestamp(&self) -> wgt::PresentationTimestamp { + wgt::PresentationTimestamp::INVALID_TIMESTAMP + } + + fn get_ordered_buffer_usages(&self) -> wgt::BufferUses { + wgt::BufferUses::INCLUSIVE | wgt::BufferUses::MAP_WRITE + } + + fn get_ordered_texture_usages(&self) -> wgt::TextureUses { + wgt::TextureUses::INCLUSIVE + | wgt::TextureUses::COLOR_TARGET + | wgt::TextureUses::DEPTH_STENCIL_WRITE + } +} + +impl crate::Queue for Context { + type A = Api; + + unsafe fn submit( + &self, + command_buffers: &[&CommandBuffer], + surface_textures: &[&Resource], + (fence, fence_value): (&Fence, crate::FenceValue), + ) -> DeviceResult<()> { + // All commands are executed synchronously. + for cb in command_buffers { + // SAFETY: Caller is responsible for ensuring synchronization between commands and + // other mutations. + unsafe { + cb.execute(); + } + } + fence.value.store(fence_value, Ordering::Release); + Ok(()) + } + unsafe fn present( + &self, + surface: &Context, + texture: Resource, + ) -> Result<(), crate::SurfaceError> { + Ok(()) + } + + unsafe fn get_timestamp_period(&self) -> f32 { + 1.0 + } + + unsafe fn wait_for_idle(&self) -> Result<(), crate::DeviceError> { + Ok(()) + } +} + +impl crate::Device for Context { + type A = Api; + + unsafe fn create_buffer(&self, desc: &crate::BufferDescriptor) -> DeviceResult<Buffer> { + Buffer::new(desc) + } + + unsafe fn destroy_buffer(&self, buffer: Buffer) {} + unsafe fn add_raw_buffer(&self, _buffer: &Buffer) {} + + unsafe fn map_buffer( + &self, + buffer: &Buffer, + range: crate::MemoryRange, + ) -> DeviceResult<crate::BufferMapping> { + // Safety: the `wgpu-core` validation layer will prevent any user-accessible aliasing + // mappings from being created, so we don’t need to perform any checks here, except for + // bounds checks on the range which are built into `get_slice_ptr()`. + Ok(crate::BufferMapping { + ptr: ptr::NonNull::new(buffer.get_slice_ptr(range).cast::<u8>()).unwrap(), + is_coherent: true, + }) + } + unsafe fn unmap_buffer(&self, buffer: &Buffer) {} + unsafe fn flush_mapped_ranges<I>(&self, buffer: &Buffer, ranges: I) {} + unsafe fn invalidate_mapped_ranges<I>(&self, buffer: &Buffer, ranges: I) {} + + unsafe fn create_texture(&self, desc: &crate::TextureDescriptor) -> DeviceResult<Resource> { + Ok(Resource) + } + unsafe fn destroy_texture(&self, texture: Resource) {} + unsafe fn add_raw_texture(&self, _texture: &Resource) {} + + unsafe fn create_texture_view( + &self, + texture: &Resource, + desc: &crate::TextureViewDescriptor, + ) -> DeviceResult<Resource> { + Ok(Resource) + } + unsafe fn destroy_texture_view(&self, view: Resource) {} + unsafe fn create_sampler(&self, desc: &crate::SamplerDescriptor) -> DeviceResult<Resource> { + Ok(Resource) + } + unsafe fn destroy_sampler(&self, sampler: Resource) {} + + unsafe fn create_command_encoder( + &self, + desc: &crate::CommandEncoderDescriptor<Context>, + ) -> DeviceResult<CommandBuffer> { + Ok(CommandBuffer::new()) + } + + unsafe fn create_bind_group_layout( + &self, + desc: &crate::BindGroupLayoutDescriptor, + ) -> DeviceResult<Resource> { + Ok(Resource) + } + unsafe fn destroy_bind_group_layout(&self, bg_layout: Resource) {} + unsafe fn create_pipeline_layout( + &self, + desc: &crate::PipelineLayoutDescriptor<Resource>, + ) -> DeviceResult<Resource> { + Ok(Resource) + } + unsafe fn destroy_pipeline_layout(&self, pipeline_layout: Resource) {} + unsafe fn create_bind_group( + &self, + desc: &crate::BindGroupDescriptor<Resource, Buffer, Resource, Resource, Resource>, + ) -> DeviceResult<Resource> { + Ok(Resource) + } + unsafe fn destroy_bind_group(&self, group: Resource) {} + + unsafe fn create_shader_module( + &self, + desc: &crate::ShaderModuleDescriptor, + shader: crate::ShaderInput, + ) -> Result<Resource, crate::ShaderError> { + Ok(Resource) + } + unsafe fn destroy_shader_module(&self, module: Resource) {} + unsafe fn create_render_pipeline( + &self, + desc: &crate::RenderPipelineDescriptor<Resource, Resource, Resource>, + ) -> Result<Resource, crate::PipelineError> { + Ok(Resource) + } + unsafe fn destroy_render_pipeline(&self, pipeline: Resource) {} + unsafe fn create_compute_pipeline( + &self, + desc: &crate::ComputePipelineDescriptor<Resource, Resource, Resource>, + ) -> Result<Resource, crate::PipelineError> { + Ok(Resource) + } + unsafe fn destroy_compute_pipeline(&self, pipeline: Resource) {} + unsafe fn create_ray_tracing_pipeline( + &self, + desc: &crate::RayTracingPipelineDescriptor<Resource, Resource, Resource>, + ) -> Result<Resource, crate::PipelineError> { + Ok(Resource) + } + unsafe fn destroy_ray_tracing_pipeline(&self, pipeline: Resource) {} + unsafe fn get_raytracing_pipeline_group_data( + &self, + pipeline: &Resource, + groups: core::ops::Range<u32>, + ) -> Result<Vec<u8>, crate::DeviceError> { + Ok(vec![0; groups.count()]) + } + unsafe fn create_pipeline_cache( + &self, + desc: &crate::PipelineCacheDescriptor<'_>, + ) -> Result<Resource, crate::PipelineCacheError> { + Ok(Resource) + } + unsafe fn destroy_pipeline_cache(&self, cache: Resource) {} + + unsafe fn create_query_set( + &self, + desc: &wgt::QuerySetDescriptor<crate::Label>, + ) -> DeviceResult<Resource> { + Ok(Resource) + } + unsafe fn destroy_query_set(&self, set: Resource) {} + unsafe fn create_fence(&self) -> DeviceResult<Fence> { + Ok(Fence { + value: AtomicU64::new(0), + }) + } + unsafe fn destroy_fence(&self, fence: Fence) {} + unsafe fn get_fence_value(&self, fence: &Fence) -> DeviceResult<crate::FenceValue> { + Ok(fence.value.load(Ordering::Acquire)) + } + unsafe fn wait( + &self, + fence: &Fence, + value: crate::FenceValue, + timeout: Option<Duration>, + ) -> DeviceResult<bool> { + // The relevant commands must have already been submitted, and noop-backend commands are + // executed synchronously, so there is no waiting — either it is already done, + // or this method was called incorrectly. + assert!( + fence.value.load(Ordering::Acquire) >= value, + "submission must have already been done" + ); + Ok(true) + } + + unsafe fn start_graphics_debugger_capture(&self) -> bool { + false + } + unsafe fn stop_graphics_debugger_capture(&self) {} + unsafe fn create_acceleration_structure( + &self, + desc: &crate::AccelerationStructureDescriptor, + ) -> DeviceResult<Resource> { + Ok(Resource) + } + unsafe fn get_acceleration_structure_build_sizes<'a>( + &self, + _desc: &crate::GetAccelerationStructureBuildSizesDescriptor<'a, Buffer>, + ) -> crate::AccelerationStructureBuildSizes { + Default::default() + } + unsafe fn get_acceleration_structure_device_address( + &self, + _acceleration_structure: &Resource, + ) -> wgt::BufferAddress { + Default::default() + } + unsafe fn destroy_acceleration_structure(&self, _acceleration_structure: Resource) {} + + fn tlas_instance_to_bytes(&self, instance: TlasInstance) -> Vec<u8> { + vec![] + } + + fn get_internal_counters(&self) -> wgt::HalCounters { + Default::default() + } + + fn check_if_oom(&self) -> DeviceResult<()> { + Ok(()) + } +} diff --git a/app/vendor/rune/vendor/wgpu-hal/src/validation_canary.rs b/app/vendor/rune/vendor/wgpu-hal/src/validation_canary.rs new file mode 100644 index 0000000..bd23db3 --- /dev/null +++ b/app/vendor/rune/vendor/wgpu-hal/src/validation_canary.rs @@ -0,0 +1,40 @@ +use alloc::{string::String, vec::Vec}; + +use parking_lot::Mutex; + +/// Stores the text of any validation errors that have occurred since +/// the last call to `get_and_reset`. +/// +/// Each value is a validation error and a message associated with it, +/// or `None` if the error has no message from the api. +/// +/// This is used for internal wgpu testing only and _must not_ be used +/// as a way to check for errors. +/// +/// This works as a static because `cargo nextest` runs all of our +/// tests in separate processes, so each test gets its own canary. +/// +/// This prevents the issue of one validation error terminating the +/// entire process. +pub static VALIDATION_CANARY: ValidationCanary = ValidationCanary { + inner: Mutex::new(Vec::new()), +}; + +/// Flag for internal testing. +#[derive(Debug)] +pub struct ValidationCanary { + inner: Mutex<Vec<String>>, +} + +impl ValidationCanary { + #[allow(dead_code, reason = "in some configurations this function is dead")] + pub(crate) fn add(&self, msg: String) { + self.inner.lock().push(msg); + } + + /// Returns any API validation errors that have occurred in this process + /// since the last call to this function. + pub fn get_and_reset(&self) -> Vec<String> { + self.inner.lock().drain(..).collect() + } +} diff --git a/app/vendor/rune/vendor/wgpu-hal/src/vulkan/adapter.rs b/app/vendor/rune/vendor/wgpu-hal/src/vulkan/adapter.rs new file mode 100644 index 0000000..196daf4 --- /dev/null +++ b/app/vendor/rune/vendor/wgpu-hal/src/vulkan/adapter.rs @@ -0,0 +1,3551 @@ +use alloc::{borrow::ToOwned as _, boxed::Box, collections::BTreeMap, sync::Arc, vec::Vec}; +use core::{ffi::CStr, marker::PhantomData}; + +use ash::{ext, google, khr, vk}; +use parking_lot::Mutex; + +use crate::{vulkan::semaphore_list::SemaphoreList, AllocationSizes}; + +use super::semaphore_list::SemaphoreListMode; + +fn depth_stencil_required_flags() -> vk::FormatFeatureFlags { + vk::FormatFeatureFlags::SAMPLED_IMAGE | vk::FormatFeatureFlags::DEPTH_STENCIL_ATTACHMENT +} + +const INDEXING_FEATURES: wgt::Features = wgt::Features::TEXTURE_BINDING_ARRAY + .union(wgt::Features::BUFFER_BINDING_ARRAY) + .union(wgt::Features::STORAGE_RESOURCE_BINDING_ARRAY) + .union(wgt::Features::SAMPLED_TEXTURE_AND_STORAGE_BUFFER_ARRAY_NON_UNIFORM_INDEXING) + .union(wgt::Features::STORAGE_TEXTURE_ARRAY_NON_UNIFORM_INDEXING) + .union(wgt::Features::UNIFORM_BUFFER_BINDING_ARRAYS) + .union(wgt::Features::PARTIALLY_BOUND_BINDING_ARRAY); +#[expect(rustdoc::private_intra_doc_links)] +/// Features supported by a [`vk::PhysicalDevice`] and its extensions. +/// +/// This is used in two phases: +/// +/// - When enumerating adapters, this represents the features offered by the +/// adapter. [`Instance::expose_adapter`] calls `vkGetPhysicalDeviceFeatures2` +/// (or `vkGetPhysicalDeviceFeatures` if that is not available) to collect +/// this information about the `VkPhysicalDevice` represented by the +/// `wgpu_hal::ExposedAdapter`. +/// +/// - When opening a device, this represents the features we would like to +/// enable. At `wgpu_hal::Device` construction time, +/// [`PhysicalDeviceFeatures::from_extensions_and_requested_features`] +/// constructs an value of this type indicating which Vulkan features to +/// enable, based on the `wgpu_types::Features` requested. +/// +/// [`Instance::expose_adapter`]: super::Instance::expose_adapter +#[derive(Debug, Default)] +pub struct PhysicalDeviceFeatures { + /// Basic Vulkan 1.0 features. + core: vk::PhysicalDeviceFeatures, + + /// Features provided by `VK_EXT_descriptor_indexing`, promoted to Vulkan 1.2. + pub(super) descriptor_indexing: + Option<vk::PhysicalDeviceDescriptorIndexingFeaturesEXT<'static>>, + + /// Features provided by `VK_KHR_timeline_semaphore`, promoted to Vulkan 1.2 + timeline_semaphore: Option<vk::PhysicalDeviceTimelineSemaphoreFeaturesKHR<'static>>, + + /// Features provided by `VK_EXT_image_robustness`, promoted to Vulkan 1.3 + image_robustness: Option<vk::PhysicalDeviceImageRobustnessFeaturesEXT<'static>>, + + /// Features provided by `VK_EXT_robustness2`. + robustness2: Option<vk::PhysicalDeviceRobustness2FeaturesEXT<'static>>, + + /// Features provided by `VK_KHR_multiview`, promoted to Vulkan 1.1. + multiview: Option<vk::PhysicalDeviceMultiviewFeaturesKHR<'static>>, + + /// Features provided by `VK_KHR_sampler_ycbcr_conversion`, promoted to Vulkan 1.1. + sampler_ycbcr_conversion: Option<vk::PhysicalDeviceSamplerYcbcrConversionFeatures<'static>>, + + /// Features provided by `VK_EXT_texture_compression_astc_hdr`, promoted to Vulkan 1.3. + astc_hdr: Option<vk::PhysicalDeviceTextureCompressionASTCHDRFeaturesEXT<'static>>, + + /// Features provided by `VK_KHR_shader_float16_int8`, promoted to Vulkan 1.2 + shader_float16_int8: Option<vk::PhysicalDeviceShaderFloat16Int8Features<'static>>, + + /// Features provided by `VK_KHR_16bit_storage`, promoted to Vulkan 1.1 + _16bit_storage: Option<vk::PhysicalDevice16BitStorageFeatures<'static>>, + + /// Features provided by `VK_KHR_acceleration_structure`. + acceleration_structure: Option<vk::PhysicalDeviceAccelerationStructureFeaturesKHR<'static>>, + + /// Features provided by `VK_KHR_buffer_device_address`, promoted to Vulkan 1.2. + /// + /// We only use this feature for + /// [`Features::EXPERIMENTAL_RAY_QUERY`], which requires + /// `VK_KHR_acceleration_structure`, which depends on + /// `VK_KHR_buffer_device_address`, so [`Instance::expose_adapter`] only + /// bothers to check if `VK_KHR_acceleration_structure` is available, + /// leaving this `None`. + /// + /// However, we do populate this when creating a device if + /// [`Features::EXPERIMENTAL_RAY_QUERY`] is requested. + /// + /// [`Instance::expose_adapter`]: super::Instance::expose_adapter + /// [`Features::EXPERIMENTAL_RAY_QUERY`]: wgt::Features::EXPERIMENTAL_RAY_QUERY + buffer_device_address: Option<vk::PhysicalDeviceBufferDeviceAddressFeaturesKHR<'static>>, + + /// Features provided by `VK_KHR_ray_query`, + /// + /// Vulkan requires that the feature be present if the `VK_KHR_ray_query` + /// extension is present, so [`Instance::expose_adapter`] doesn't bother retrieving + /// this from `vkGetPhysicalDeviceFeatures2`. + /// + /// However, we do populate this when creating a device if ray tracing is requested. + /// + /// [`Instance::expose_adapter`]: super::Instance::expose_adapter + ray_query: Option<vk::PhysicalDeviceRayQueryFeaturesKHR<'static>>, + + /// Features provided by `VK_KHR_ray_tracing_pipeline`. + ray_tracing_pipeline: Option<vk::PhysicalDeviceRayTracingPipelineFeaturesKHR<'static>>, + + /// Features provided by `VK_KHR_zero_initialize_workgroup_memory`, promoted + /// to Vulkan 1.3. + zero_initialize_workgroup_memory: + Option<vk::PhysicalDeviceZeroInitializeWorkgroupMemoryFeatures<'static>>, + position_fetch: Option<vk::PhysicalDeviceRayTracingPositionFetchFeaturesKHR<'static>>, + + /// Features provided by `VK_KHR_shader_atomic_int64`, promoted to Vulkan 1.2. + shader_atomic_int64: Option<vk::PhysicalDeviceShaderAtomicInt64Features<'static>>, + + /// Features provided by `VK_EXT_shader_image_atomic_int64` + shader_image_atomic_int64: Option<vk::PhysicalDeviceShaderImageAtomicInt64FeaturesEXT<'static>>, + + /// Features provided by `VK_EXT_shader_atomic_float`. + shader_atomic_float: Option<vk::PhysicalDeviceShaderAtomicFloatFeaturesEXT<'static>>, + + /// Features provided by `VK_EXT_subgroup_size_control`, promoted to Vulkan 1.3. + subgroup_size_control: Option<vk::PhysicalDeviceSubgroupSizeControlFeatures<'static>>, + + /// Features provided by `VK_KHR_maintenance4`, promoted to Vulkan 1.3. + maintenance4: Option<vk::PhysicalDeviceMaintenance4FeaturesKHR<'static>>, + + /// Features proved by `VK_EXT_mesh_shader` + mesh_shader: Option<vk::PhysicalDeviceMeshShaderFeaturesEXT<'static>>, + + /// Features provided by `VK_KHR_shader_integer_dot_product`, promoted to Vulkan 1.3. + shader_integer_dot_product: + Option<vk::PhysicalDeviceShaderIntegerDotProductFeaturesKHR<'static>>, + + /// Features provided by `VK_KHR_fragment_shader_barycentric` + shader_barycentrics: Option<vk::PhysicalDeviceFragmentShaderBarycentricFeaturesKHR<'static>>, + + /// Features provided by `VK_KHR_portability_subset`. + /// + /// Strictly speaking this tells us what features we *don't* have compared to core. + portability_subset: Option<vk::PhysicalDevicePortabilitySubsetFeaturesKHR<'static>>, + + /// Features provided by `VK_KHR_cooperative_matrix` + cooperative_matrix: Option<vk::PhysicalDeviceCooperativeMatrixFeaturesKHR<'static>>, + + /// Features provided by `VK_KHR_vulkan_memory_model`, promoted to Vulkan 1.2 + vulkan_memory_model: Option<vk::PhysicalDeviceVulkanMemoryModelFeaturesKHR<'static>>, + + shader_draw_parameters: Option<vk::PhysicalDeviceShaderDrawParametersFeatures<'static>>, +} + +impl PhysicalDeviceFeatures { + pub fn get_core(&self) -> vk::PhysicalDeviceFeatures { + self.core + } + + /// Add the members of `self` into `info.enabled_features` and its `p_next` chain. + pub fn add_to_device_create<'a>( + &'a mut self, + mut info: vk::DeviceCreateInfo<'a>, + ) -> vk::DeviceCreateInfo<'a> { + info = info.enabled_features(&self.core); + if let Some(ref mut feature) = self.descriptor_indexing { + info = info.push_next(feature); + } + if let Some(ref mut feature) = self.timeline_semaphore { + info = info.push_next(feature); + } + if let Some(ref mut feature) = self.image_robustness { + info = info.push_next(feature); + } + if let Some(ref mut feature) = self.robustness2 { + info = info.push_next(feature); + } + if let Some(ref mut feature) = self.multiview { + info = info.push_next(feature); + } + if let Some(ref mut feature) = self.astc_hdr { + info = info.push_next(feature); + } + if let Some(ref mut feature) = self.shader_float16_int8 { + info = info.push_next(feature); + } + if let Some(ref mut feature) = self._16bit_storage { + info = info.push_next(feature); + } + if let Some(ref mut feature) = self.zero_initialize_workgroup_memory { + info = info.push_next(feature); + } + if let Some(ref mut feature) = self.acceleration_structure { + info = info.push_next(feature); + } + if let Some(ref mut feature) = self.buffer_device_address { + info = info.push_next(feature); + } + if let Some(ref mut feature) = self.ray_query { + info = info.push_next(feature); + } + if let Some(ref mut feature) = self.ray_tracing_pipeline { + info = info.push_next(feature); + } + if let Some(ref mut feature) = self.shader_atomic_int64 { + info = info.push_next(feature); + } + if let Some(ref mut feature) = self.position_fetch { + info = info.push_next(feature); + } + if let Some(ref mut feature) = self.shader_image_atomic_int64 { + info = info.push_next(feature); + } + if let Some(ref mut feature) = self.shader_atomic_float { + info = info.push_next(feature); + } + if let Some(ref mut feature) = self.subgroup_size_control { + info = info.push_next(feature); + } + if let Some(ref mut feature) = self.maintenance4 { + info = info.push_next(feature); + } + if let Some(ref mut feature) = self.mesh_shader { + info = info.push_next(feature); + } + if let Some(ref mut feature) = self.shader_integer_dot_product { + info = info.push_next(feature); + } + if let Some(ref mut feature) = self.shader_barycentrics { + info = info.push_next(feature); + } + if let Some(ref mut feature) = self.portability_subset { + info = info.push_next(feature); + } + if let Some(ref mut feature) = self.cooperative_matrix { + info = info.push_next(feature); + } + if let Some(ref mut feature) = self.vulkan_memory_model { + info = info.push_next(feature); + } + if let Some(ref mut feature) = self.shader_draw_parameters { + info = info.push_next(feature); + } + info + } + + fn supports_storage_input_output_16(&self) -> bool { + self._16bit_storage + .as_ref() + .map(|features| features.storage_input_output16 != 0) + .unwrap_or(false) + } + + /// Create a `PhysicalDeviceFeatures` that can be used to create a logical + /// device. + /// + /// Return a `PhysicalDeviceFeatures` value capturing all the Vulkan + /// features needed for the given [`Features`], [`DownlevelFlags`], and + /// [`PrivateCapabilities`]. You can use the returned value's + /// [`add_to_device_create`] method to configure a + /// [`vk::DeviceCreateInfo`] to build a logical device providing those + /// features. + /// + /// To ensure that the returned value is able to select all the Vulkan + /// features needed to express `requested_features`, `downlevel_flags`, and + /// `private_caps`: + /// + /// - The given `enabled_extensions` set must include all the extensions + /// selected by [`Adapter::required_device_extensions`] when passed + /// `features`. + /// + /// - The given `device_api_version` must be the Vulkan API version of the + /// physical device we will use to create the logical device. + /// + /// [`Features`]: wgt::Features + /// [`DownlevelFlags`]: wgt::DownlevelFlags + /// [`PrivateCapabilities`]: super::PrivateCapabilities + /// [`add_to_device_create`]: PhysicalDeviceFeatures::add_to_device_create + /// [`Adapter::required_device_extensions`]: super::Adapter::required_device_extensions + fn from_extensions_and_requested_features( + phd_capabilities: &PhysicalDeviceProperties, + phd_features: &PhysicalDeviceFeatures, + enabled_extensions: &[&'static CStr], + requested_features: wgt::Features, + downlevel_flags: wgt::DownlevelFlags, + private_caps: &super::PrivateCapabilities, + ) -> Self { + let device_api_version = phd_capabilities.device_api_version; + let needs_bindless = requested_features.intersects( + wgt::Features::TEXTURE_BINDING_ARRAY + | wgt::Features::BUFFER_BINDING_ARRAY + | wgt::Features::STORAGE_RESOURCE_BINDING_ARRAY + | wgt::Features::STORAGE_TEXTURE_ARRAY_NON_UNIFORM_INDEXING + | wgt::Features::SAMPLED_TEXTURE_AND_STORAGE_BUFFER_ARRAY_NON_UNIFORM_INDEXING, + ); + let needs_partially_bound = + requested_features.intersects(wgt::Features::PARTIALLY_BOUND_BINDING_ARRAY); + + Self { + // vk::PhysicalDeviceFeatures is a struct composed of Bool32's while + // Features is a bitfield so we need to map everything manually + core: vk::PhysicalDeviceFeatures::default() + .robust_buffer_access(private_caps.robust_buffer_access) + .independent_blend(downlevel_flags.contains(wgt::DownlevelFlags::INDEPENDENT_BLEND)) + .sample_rate_shading( + downlevel_flags.contains(wgt::DownlevelFlags::MULTISAMPLED_SHADING), + ) + .image_cube_array( + downlevel_flags.contains(wgt::DownlevelFlags::CUBE_ARRAY_TEXTURES), + ) + .draw_indirect_first_instance( + requested_features.contains(wgt::Features::INDIRECT_FIRST_INSTANCE), + ) + //.dual_src_blend(requested_features.contains(wgt::Features::DUAL_SRC_BLENDING)) + .multi_draw_indirect(phd_features.core.multi_draw_indirect != 0) + .fill_mode_non_solid(requested_features.intersects( + wgt::Features::POLYGON_MODE_LINE | wgt::Features::POLYGON_MODE_POINT, + )) + //.depth_bounds(requested_features.contains(wgt::Features::DEPTH_BOUNDS)) + //.alpha_to_one(requested_features.contains(wgt::Features::ALPHA_TO_ONE)) + //.multi_viewport(requested_features.contains(wgt::Features::MULTI_VIEWPORTS)) + .sampler_anisotropy( + downlevel_flags.contains(wgt::DownlevelFlags::ANISOTROPIC_FILTERING), + ) + .texture_compression_etc2( + requested_features.contains(wgt::Features::TEXTURE_COMPRESSION_ETC2), + ) + .texture_compression_astc_ldr( + requested_features.contains(wgt::Features::TEXTURE_COMPRESSION_ASTC), + ) + .texture_compression_bc( + requested_features.contains(wgt::Features::TEXTURE_COMPRESSION_BC), + // BC provides formats for Sliced 3D + ) + //.occlusion_query_precise(requested_features.contains(wgt::Features::PRECISE_OCCLUSION_QUERY)) + .pipeline_statistics_query( + requested_features.contains(wgt::Features::PIPELINE_STATISTICS_QUERY), + ) + .vertex_pipeline_stores_and_atomics( + requested_features.contains(wgt::Features::VERTEX_WRITABLE_STORAGE), + ) + .fragment_stores_and_atomics( + downlevel_flags.contains(wgt::DownlevelFlags::FRAGMENT_WRITABLE_STORAGE), + ) + //.shader_image_gather_extended( + //.shader_storage_image_extended_formats( + .shader_uniform_buffer_array_dynamic_indexing( + requested_features.contains(wgt::Features::BUFFER_BINDING_ARRAY), + ) + .shader_storage_buffer_array_dynamic_indexing(requested_features.contains( + wgt::Features::BUFFER_BINDING_ARRAY + | wgt::Features::STORAGE_RESOURCE_BINDING_ARRAY, + )) + .shader_sampled_image_array_dynamic_indexing( + requested_features.contains(wgt::Features::TEXTURE_BINDING_ARRAY), + ) + .shader_storage_buffer_array_dynamic_indexing(requested_features.contains( + wgt::Features::TEXTURE_BINDING_ARRAY + | wgt::Features::STORAGE_RESOURCE_BINDING_ARRAY, + )) + //.shader_storage_image_array_dynamic_indexing( + .shader_clip_distance(requested_features.contains(wgt::Features::CLIP_DISTANCES)) + //.shader_cull_distance(requested_features.contains(wgt::Features::SHADER_CULL_DISTANCE)) + .shader_float64(requested_features.contains(wgt::Features::SHADER_F64)) + .shader_int64(requested_features.contains(wgt::Features::SHADER_INT64)) + .shader_int16(requested_features.contains(wgt::Features::SHADER_I16)) + //.shader_resource_residency(requested_features.contains(wgt::Features::SHADER_RESOURCE_RESIDENCY)) + .geometry_shader(requested_features.contains(wgt::Features::PRIMITIVE_INDEX)) + .depth_clamp(requested_features.contains(wgt::Features::DEPTH_CLIP_CONTROL)) + .dual_src_blend(requested_features.contains(wgt::Features::DUAL_SOURCE_BLENDING)), + descriptor_indexing: if requested_features.intersects(INDEXING_FEATURES) { + Some( + vk::PhysicalDeviceDescriptorIndexingFeaturesEXT::default() + .shader_sampled_image_array_non_uniform_indexing(needs_bindless) + .shader_storage_image_array_non_uniform_indexing(needs_bindless) + .shader_storage_buffer_array_non_uniform_indexing(needs_bindless) + .descriptor_binding_sampled_image_update_after_bind(needs_bindless) + .descriptor_binding_storage_image_update_after_bind(needs_bindless) + .descriptor_binding_storage_buffer_update_after_bind(needs_bindless) + .descriptor_binding_partially_bound(needs_partially_bound), + ) + } else { + None + }, + timeline_semaphore: if device_api_version >= vk::API_VERSION_1_2 + || enabled_extensions.contains(&khr::timeline_semaphore::NAME) + { + Some( + vk::PhysicalDeviceTimelineSemaphoreFeaturesKHR::default() + .timeline_semaphore(private_caps.timeline_semaphores), + ) + } else { + None + }, + image_robustness: if device_api_version >= vk::API_VERSION_1_3 + || enabled_extensions.contains(&ext::image_robustness::NAME) + { + Some( + vk::PhysicalDeviceImageRobustnessFeaturesEXT::default() + .robust_image_access(private_caps.robust_image_access), + ) + } else { + None + }, + robustness2: if enabled_extensions.contains(&ext::robustness2::NAME) { + Some( + vk::PhysicalDeviceRobustness2FeaturesEXT::default() + .robust_buffer_access2(private_caps.robust_buffer_access2) + .robust_image_access2(private_caps.robust_image_access2), + ) + } else { + None + }, + multiview: if device_api_version >= vk::API_VERSION_1_1 + || enabled_extensions.contains(&khr::multiview::NAME) + { + Some( + vk::PhysicalDeviceMultiviewFeatures::default() + .multiview(requested_features.contains(wgt::Features::MULTIVIEW)), + ) + } else { + None + }, + sampler_ycbcr_conversion: if device_api_version >= vk::API_VERSION_1_1 + || enabled_extensions.contains(&khr::sampler_ycbcr_conversion::NAME) + { + Some( + vk::PhysicalDeviceSamplerYcbcrConversionFeatures::default(), // .sampler_ycbcr_conversion(requested_features.contains(wgt::Features::TEXTURE_FORMAT_NV12)) + ) + } else { + None + }, + astc_hdr: if enabled_extensions.contains(&ext::texture_compression_astc_hdr::NAME) { + Some( + vk::PhysicalDeviceTextureCompressionASTCHDRFeaturesEXT::default() + .texture_compression_astc_hdr(true), + ) + } else { + None + }, + shader_float16_int8: match requested_features.contains(wgt::Features::SHADER_F16) { + shader_float16 if shader_float16 || private_caps.shader_int8 => Some( + vk::PhysicalDeviceShaderFloat16Int8Features::default() + .shader_float16(shader_float16) + .shader_int8(private_caps.shader_int8), + ), + _ => None, + }, + _16bit_storage: if requested_features + .intersects(wgt::Features::SHADER_F16 | wgt::Features::SHADER_I16) + { + Some( + vk::PhysicalDevice16BitStorageFeatures::default() + .storage_buffer16_bit_access(true) + .storage_input_output16(phd_features.supports_storage_input_output_16()) + .uniform_and_storage_buffer16_bit_access(true), + ) + } else { + None + }, + acceleration_structure: if enabled_extensions + .contains(&khr::acceleration_structure::NAME) + { + Some( + vk::PhysicalDeviceAccelerationStructureFeaturesKHR::default() + .acceleration_structure(true) + .descriptor_binding_acceleration_structure_update_after_bind( + requested_features + .contains(wgt::Features::ACCELERATION_STRUCTURE_BINDING_ARRAY), + ), + ) + } else { + None + }, + buffer_device_address: if enabled_extensions.contains(&khr::buffer_device_address::NAME) + { + Some( + vk::PhysicalDeviceBufferDeviceAddressFeaturesKHR::default() + .buffer_device_address(true), + ) + } else { + None + }, + ray_query: if enabled_extensions.contains(&khr::ray_query::NAME) { + Some(vk::PhysicalDeviceRayQueryFeaturesKHR::default().ray_query(true)) + } else { + None + }, + ray_tracing_pipeline: if enabled_extensions.contains(&khr::ray_tracing_pipeline::NAME) { + Some( + vk::PhysicalDeviceRayTracingPipelineFeaturesKHR::default() + .ray_tracing_pipeline(true), + ) + } else { + None + }, + zero_initialize_workgroup_memory: if device_api_version >= vk::API_VERSION_1_3 + || enabled_extensions.contains(&khr::zero_initialize_workgroup_memory::NAME) + { + Some( + vk::PhysicalDeviceZeroInitializeWorkgroupMemoryFeatures::default() + .shader_zero_initialize_workgroup_memory( + private_caps.zero_initialize_workgroup_memory, + ), + ) + } else { + None + }, + shader_atomic_int64: if device_api_version >= vk::API_VERSION_1_2 + || enabled_extensions.contains(&khr::shader_atomic_int64::NAME) + { + let needed = requested_features.intersects( + wgt::Features::SHADER_INT64_ATOMIC_ALL_OPS + | wgt::Features::SHADER_INT64_ATOMIC_MIN_MAX, + ); + Some( + vk::PhysicalDeviceShaderAtomicInt64Features::default() + .shader_buffer_int64_atomics(needed) + .shader_shared_int64_atomics(needed), + ) + } else { + None + }, + shader_image_atomic_int64: if enabled_extensions + .contains(&ext::shader_image_atomic_int64::NAME) + { + let needed = requested_features.intersects(wgt::Features::TEXTURE_INT64_ATOMIC); + Some( + vk::PhysicalDeviceShaderImageAtomicInt64FeaturesEXT::default() + .shader_image_int64_atomics(needed), + ) + } else { + None + }, + shader_atomic_float: if enabled_extensions.contains(&ext::shader_atomic_float::NAME) { + let needed = requested_features.contains(wgt::Features::SHADER_FLOAT32_ATOMIC); + Some( + vk::PhysicalDeviceShaderAtomicFloatFeaturesEXT::default() + .shader_buffer_float32_atomics(needed) + .shader_buffer_float32_atomic_add(needed), + ) + } else { + None + }, + subgroup_size_control: if device_api_version >= vk::API_VERSION_1_3 + || enabled_extensions.contains(&ext::subgroup_size_control::NAME) + { + Some( + vk::PhysicalDeviceSubgroupSizeControlFeatures::default() + .subgroup_size_control(true), + ) + } else { + None + }, + position_fetch: if enabled_extensions.contains(&khr::ray_tracing_position_fetch::NAME) { + Some( + vk::PhysicalDeviceRayTracingPositionFetchFeaturesKHR::default() + .ray_tracing_position_fetch(true), + ) + } else { + None + }, + mesh_shader: if enabled_extensions.contains(&ext::mesh_shader::NAME) { + let needed = requested_features.contains(wgt::Features::EXPERIMENTAL_MESH_SHADER); + let multiview_needed = + requested_features.contains(wgt::Features::EXPERIMENTAL_MESH_SHADER_MULTIVIEW); + Some( + vk::PhysicalDeviceMeshShaderFeaturesEXT::default() + .mesh_shader(needed) + .task_shader(needed) + .multiview_mesh_shader(multiview_needed), + ) + } else { + None + }, + maintenance4: if device_api_version >= vk::API_VERSION_1_3 + || enabled_extensions.contains(&khr::maintenance4::NAME) + { + let needed = requested_features.contains(wgt::Features::EXPERIMENTAL_MESH_SHADER); + Some(vk::PhysicalDeviceMaintenance4Features::default().maintenance4(needed)) + } else { + None + }, + shader_integer_dot_product: if device_api_version >= vk::API_VERSION_1_3 + || enabled_extensions.contains(&khr::shader_integer_dot_product::NAME) + { + Some( + vk::PhysicalDeviceShaderIntegerDotProductFeaturesKHR::default() + .shader_integer_dot_product(private_caps.shader_integer_dot_product), + ) + } else { + None + }, + shader_barycentrics: if enabled_extensions + .contains(&khr::fragment_shader_barycentric::NAME) + { + let needed = requested_features.intersects( + wgt::Features::SHADER_BARYCENTRICS | wgt::Features::SHADER_PER_VERTEX, + ); + Some( + vk::PhysicalDeviceFragmentShaderBarycentricFeaturesKHR::default() + .fragment_shader_barycentric(needed), + ) + } else { + None + }, + portability_subset: if enabled_extensions.contains(&khr::portability_subset::NAME) { + let multisample_array_needed = + requested_features.intersects(wgt::Features::MULTISAMPLE_ARRAY); + + Some( + vk::PhysicalDevicePortabilitySubsetFeaturesKHR::default() + .multisample_array_image(multisample_array_needed), + ) + } else { + None + }, + cooperative_matrix: if enabled_extensions.contains(&khr::cooperative_matrix::NAME) { + let needed = + requested_features.contains(wgt::Features::EXPERIMENTAL_COOPERATIVE_MATRIX); + Some( + vk::PhysicalDeviceCooperativeMatrixFeaturesKHR::default() + .cooperative_matrix(needed), + ) + } else { + None + }, + vulkan_memory_model: if device_api_version >= vk::API_VERSION_1_2 + || enabled_extensions.contains(&khr::vulkan_memory_model::NAME) + { + let needed = + requested_features.contains(wgt::Features::EXPERIMENTAL_COOPERATIVE_MATRIX); + Some( + vk::PhysicalDeviceVulkanMemoryModelFeaturesKHR::default() + .vulkan_memory_model(needed) + // The SPIR-V backend emits storage atomics with `Device` + // memory scope, so whenever the Vulkan memory model is + // enabled we must also enable device scope, otherwise the + // validation layers report + // `VUID-RuntimeSpirv-vulkanMemoryModel-06265`. + .vulkan_memory_model_device_scope(needed), + ) + } else { + None + }, + shader_draw_parameters: if device_api_version >= vk::API_VERSION_1_1 { + let needed = requested_features.contains(wgt::Features::SHADER_DRAW_INDEX); + Some( + vk::PhysicalDeviceShaderDrawParametersFeatures::default() + .shader_draw_parameters(needed), + ) + } else { + None + }, + } + } + + /// Compute the wgpu [`Features`] and [`DownlevelFlags`] supported by a physical device. + /// + /// Given `self`, together with the instance and physical device it was + /// built from, and a `caps` also built from those, determine which wgpu + /// features and downlevel flags the device can support. + /// + /// [`Features`]: wgt::Features + /// [`DownlevelFlags`]: wgt::DownlevelFlags + fn to_wgpu( + &self, + instance: &ash::Instance, + phd: vk::PhysicalDevice, + caps: &PhysicalDeviceProperties, + queue_props: &vk::QueueFamilyProperties, + ) -> (wgt::Features, wgt::DownlevelFlags) { + use wgt::{DownlevelFlags as Df, Features as F}; + let mut features = F::empty() + | F::MAPPABLE_PRIMARY_BUFFERS + | F::IMMEDIATES + | F::ADDRESS_MODE_CLAMP_TO_BORDER + | F::ADDRESS_MODE_CLAMP_TO_ZERO + | F::TEXTURE_ADAPTER_SPECIFIC_FORMAT_FEATURES + | F::CLEAR_TEXTURE + | F::PIPELINE_CACHE + | F::SHADER_EARLY_DEPTH_TEST + | F::TEXTURE_ATOMIC + | F::PASSTHROUGH_SHADERS + | F::MEMORY_DECORATION_COHERENT + | F::MEMORY_DECORATION_VOLATILE; + + let mut dl_flags = Df::COMPUTE_SHADERS + | Df::BASE_VERTEX + | Df::READ_ONLY_DEPTH_STENCIL + | Df::NON_POWER_OF_TWO_MIPMAPPED_TEXTURES + | Df::COMPARISON_SAMPLERS + | Df::VERTEX_STORAGE + | Df::FRAGMENT_STORAGE + | Df::DEPTH_TEXTURE_AND_BUFFER_COPIES + | Df::BUFFER_BINDINGS_NOT_16_BYTE_ALIGNED + | Df::UNRESTRICTED_INDEX_BUFFER + | Df::INDIRECT_EXECUTION + | Df::VIEW_FORMATS + | Df::UNRESTRICTED_EXTERNAL_TEXTURE_COPIES + | Df::NONBLOCKING_QUERY_RESOLVE + | Df::SHADER_F16_IN_F32 + | Df::MSL2_1; + + dl_flags.set( + Df::SURFACE_VIEW_FORMATS, + caps.supports_extension(khr::swapchain_mutable_format::NAME) + || !caps.supports_extension(khr::swapchain::NAME), + ); + dl_flags.set(Df::CUBE_ARRAY_TEXTURES, self.core.image_cube_array != 0); + dl_flags.set(Df::ANISOTROPIC_FILTERING, self.core.sampler_anisotropy != 0); + dl_flags.set( + Df::FRAGMENT_WRITABLE_STORAGE, + self.core.fragment_stores_and_atomics != 0, + ); + dl_flags.set(Df::MULTISAMPLED_SHADING, self.core.sample_rate_shading != 0); + dl_flags.set(Df::INDEPENDENT_BLEND, self.core.independent_blend != 0); + dl_flags.set( + Df::FULL_DRAW_INDEX_UINT32, + self.core.full_draw_index_uint32 != 0, + ); + dl_flags.set(Df::DEPTH_BIAS_CLAMP, self.core.depth_bias_clamp != 0); + + features.set( + F::TIMESTAMP_QUERY + | F::TIMESTAMP_QUERY_INSIDE_ENCODERS + | F::TIMESTAMP_QUERY_INSIDE_PASSES, + // Vulkan strictly defines this as either 36-64, or zero. + queue_props.timestamp_valid_bits >= 36, + ); + features.set( + F::INDIRECT_FIRST_INSTANCE, + self.core.draw_indirect_first_instance != 0, + ); + //if self.core.dual_src_blend != 0 + features.set(F::POLYGON_MODE_LINE, self.core.fill_mode_non_solid != 0); + features.set(F::POLYGON_MODE_POINT, self.core.fill_mode_non_solid != 0); + //if self.core.depth_bounds != 0 { + //if self.core.alpha_to_one != 0 { + //if self.core.multi_viewport != 0 { + features.set( + F::TEXTURE_COMPRESSION_ETC2, + self.core.texture_compression_etc2 != 0, + ); + features.set( + F::TEXTURE_COMPRESSION_ASTC, + self.core.texture_compression_astc_ldr != 0, + ); + features.set( + F::TEXTURE_COMPRESSION_BC, + self.core.texture_compression_bc != 0, + ); + features.set( + F::TEXTURE_COMPRESSION_BC_SLICED_3D, + self.core.texture_compression_bc != 0, // BC guarantees Sliced 3D + ); + features.set( + F::PIPELINE_STATISTICS_QUERY, + self.core.pipeline_statistics_query != 0, + ); + features.set( + F::VERTEX_WRITABLE_STORAGE, + self.core.vertex_pipeline_stores_and_atomics != 0, + ); + + features.set(F::SHADER_F64, self.core.shader_float64 != 0); + features.set(F::SHADER_INT64, self.core.shader_int64 != 0); + if let Some(ref bit16) = self._16bit_storage { + features.set( + F::SHADER_I16, + self.core.shader_int16 != 0 + && bit16.storage_buffer16_bit_access != 0 + && bit16.uniform_and_storage_buffer16_bit_access != 0, + ); + } + + features.set(F::PRIMITIVE_INDEX, self.core.geometry_shader != 0); + + if let Some(ref shader_atomic_int64) = self.shader_atomic_int64 { + features.set( + F::SHADER_INT64_ATOMIC_ALL_OPS | F::SHADER_INT64_ATOMIC_MIN_MAX, + shader_atomic_int64.shader_buffer_int64_atomics != 0 + && shader_atomic_int64.shader_shared_int64_atomics != 0, + ); + } + + if let Some(ref shader_image_atomic_int64) = self.shader_image_atomic_int64 { + features.set( + F::TEXTURE_INT64_ATOMIC, + shader_image_atomic_int64 + .shader_image_int64_atomics(true) + .shader_image_int64_atomics + != 0, + ); + } + + if let Some(ref shader_atomic_float) = self.shader_atomic_float { + features.set( + F::SHADER_FLOAT32_ATOMIC, + shader_atomic_float.shader_buffer_float32_atomics != 0 + && shader_atomic_float.shader_buffer_float32_atomic_add != 0, + ); + } + + if let Some(ref shader_barycentrics) = self.shader_barycentrics { + features.set( + F::SHADER_BARYCENTRICS | F::SHADER_PER_VERTEX, + shader_barycentrics.fragment_shader_barycentric != 0, + ); + } + + //if caps.supports_extension(khr::sampler_mirror_clamp_to_edge::NAME) { + //if caps.supports_extension(ext::sampler_filter_minmax::NAME) { + features.set( + F::MULTI_DRAW_INDIRECT_COUNT, + caps.supports_extension(khr::draw_indirect_count::NAME), + ); + features.set( + F::CONSERVATIVE_RASTERIZATION, + caps.supports_extension(ext::conservative_rasterization::NAME), + ); + features.set( + F::EXPERIMENTAL_RAY_HIT_VERTEX_RETURN, + caps.supports_extension(khr::ray_tracing_position_fetch::NAME), + ); + + if let Some(ref descriptor_indexing) = self.descriptor_indexing { + // We use update-after-bind descriptors for all bind groups containing binding arrays. + // + // In those bind groups, we allow all binding types except uniform buffers to be present. + // + // As we can only switch between update-after-bind and not on a per bind group basis, + // all supported binding types need to be able to be marked update after bind. + // + // As such, we enable all features as a whole, rather individually. + let supports_descriptor_indexing = + // Sampled Images + descriptor_indexing.shader_sampled_image_array_non_uniform_indexing != 0 + && descriptor_indexing.descriptor_binding_sampled_image_update_after_bind != 0 + // Storage Images + && descriptor_indexing.shader_storage_image_array_non_uniform_indexing != 0 + && descriptor_indexing.descriptor_binding_storage_image_update_after_bind != 0 + // Storage Buffers + && descriptor_indexing.shader_storage_buffer_array_non_uniform_indexing != 0 + && descriptor_indexing.descriptor_binding_storage_buffer_update_after_bind != 0; + + let descriptor_indexing_features = F::BUFFER_BINDING_ARRAY + | F::TEXTURE_BINDING_ARRAY + | F::STORAGE_RESOURCE_BINDING_ARRAY + | F::SAMPLED_TEXTURE_AND_STORAGE_BUFFER_ARRAY_NON_UNIFORM_INDEXING + | F::STORAGE_TEXTURE_ARRAY_NON_UNIFORM_INDEXING; + + features.set(descriptor_indexing_features, supports_descriptor_indexing); + + let supports_partially_bound = + descriptor_indexing.descriptor_binding_partially_bound != 0; + + features.set(F::PARTIALLY_BOUND_BINDING_ARRAY, supports_partially_bound); + } + + features.set(F::DEPTH_CLIP_CONTROL, self.core.depth_clamp != 0); + features.set(F::DUAL_SOURCE_BLENDING, self.core.dual_src_blend != 0); + features.set(F::CLIP_DISTANCES, self.core.shader_clip_distance != 0); + + if let Some(ref multiview) = self.multiview { + features.set(F::MULTIVIEW, multiview.multiview != 0); + features.set(F::SELECTIVE_MULTIVIEW, multiview.multiview != 0); + } + + features.set( + F::TEXTURE_FORMAT_16BIT_NORM, + is_format_16bit_norm_supported(instance, phd), + ); + + if let Some(ref astc_hdr) = self.astc_hdr { + features.set( + F::TEXTURE_COMPRESSION_ASTC_HDR, + astc_hdr.texture_compression_astc_hdr != 0, + ); + } + + if self.core.texture_compression_astc_ldr != 0 { + features.set( + F::TEXTURE_COMPRESSION_ASTC_SLICED_3D, + supports_astc_3d(instance, phd), + ); + } + + if let (Some(ref f16_i8), Some(ref bit16)) = (self.shader_float16_int8, self._16bit_storage) + { + // Note `storage_input_output16` is not required, we polyfill `f16` I/O using `f32` + // types when this capability is not available + features.set( + F::SHADER_F16, + f16_i8.shader_float16 != 0 + && bit16.storage_buffer16_bit_access != 0 + && bit16.uniform_and_storage_buffer16_bit_access != 0, + ); + } + + if let Some(ref subgroup) = caps.subgroup { + if (caps.device_api_version >= vk::API_VERSION_1_3 + || caps.supports_extension(ext::subgroup_size_control::NAME)) + && subgroup.supported_operations.contains( + vk::SubgroupFeatureFlags::BASIC + | vk::SubgroupFeatureFlags::VOTE + | vk::SubgroupFeatureFlags::ARITHMETIC + | vk::SubgroupFeatureFlags::BALLOT + | vk::SubgroupFeatureFlags::SHUFFLE + | vk::SubgroupFeatureFlags::SHUFFLE_RELATIVE + | vk::SubgroupFeatureFlags::QUAD, + ) + { + features.set( + F::SUBGROUP, + subgroup + .supported_stages + .contains(vk::ShaderStageFlags::COMPUTE | vk::ShaderStageFlags::FRAGMENT), + ); + features.set( + F::SUBGROUP_VERTEX, + subgroup + .supported_stages + .contains(vk::ShaderStageFlags::VERTEX), + ); + features.insert(F::SUBGROUP_BARRIER); + } + } + + let supports_depth_format = |format| { + supports_format( + instance, + phd, + format, + vk::ImageTiling::OPTIMAL, + depth_stencil_required_flags(), + ) + }; + + let texture_s8 = supports_depth_format(vk::Format::S8_UINT); + let texture_d32 = supports_depth_format(vk::Format::D32_SFLOAT); + let texture_d24_s8 = supports_depth_format(vk::Format::D24_UNORM_S8_UINT); + let texture_d32_s8 = supports_depth_format(vk::Format::D32_SFLOAT_S8_UINT); + + let stencil8 = texture_s8 || texture_d24_s8; + let depth24_plus_stencil8 = texture_d24_s8 || texture_d32_s8; + + dl_flags.set( + Df::WEBGPU_TEXTURE_FORMAT_SUPPORT, + stencil8 && depth24_plus_stencil8 && texture_d32, + ); + + features.set(F::DEPTH32FLOAT_STENCIL8, texture_d32_s8); + + let supports_acceleration_structures = caps + .supports_extension(khr::deferred_host_operations::NAME) + && caps.supports_extension(khr::acceleration_structure::NAME) + && caps.supports_extension(khr::buffer_device_address::NAME); + + let supports_ray_query = + supports_acceleration_structures && caps.supports_extension(khr::ray_query::NAME); + let supports_acceleration_structure_binding_array = supports_ray_query + && self + .acceleration_structure + .as_ref() + .is_some_and(|features| { + features.descriptor_binding_acceleration_structure_update_after_bind != 0 + }); + + features.set( + F::EXPERIMENTAL_RAY_QUERY + // Although this doesn't really require ray queries, it does not make sense to be enabled if acceleration structures + // aren't enabled. + | F::EXTENDED_ACCELERATION_STRUCTURE_VERTEX_FORMATS, + supports_ray_query, + ); + + // Binding arrays of TLAS are supported on Vulkan when ray queries are supported. + // + // Note: this flag is used for shader-side `binding_array<acceleration_structure>` as well as + // allowing `BindGroupLayoutEntry::count = Some(...)` for `BindingType::AccelerationStructure`. + features.set( + F::ACCELERATION_STRUCTURE_BINDING_ARRAY, + supports_acceleration_structure_binding_array, + ); + + if supports_acceleration_structures + && caps.supports_extension(khr::ray_tracing_pipeline::NAME) + { + features.insert( + F::EXPERIMENTAL_RAY_TRACING_PIPELINES + // Same reason as for ray queries. + | F::EXTENDED_ACCELERATION_STRUCTURE_VERTEX_FORMATS, + ); + } + + let rg11b10ufloat_renderable = supports_format( + instance, + phd, + vk::Format::B10G11R11_UFLOAT_PACK32, + vk::ImageTiling::OPTIMAL, + vk::FormatFeatureFlags::COLOR_ATTACHMENT + | vk::FormatFeatureFlags::COLOR_ATTACHMENT_BLEND, + ); + features.set(F::RG11B10UFLOAT_RENDERABLE, rg11b10ufloat_renderable); + + features.set( + F::BGRA8UNORM_STORAGE, + supports_bgra8unorm_storage(instance, phd, caps.device_api_version), + ); + + features.set( + F::FLOAT32_FILTERABLE, + is_float32_filterable_supported(instance, phd), + ); + + features.set( + F::FLOAT32_BLENDABLE, + is_float32_blendable_supported(instance, phd), + ); + + if let Some(ref _sampler_ycbcr_conversion) = self.sampler_ycbcr_conversion { + features.set( + F::TEXTURE_FORMAT_NV12, + supports_format( + instance, + phd, + vk::Format::G8_B8R8_2PLANE_420_UNORM, + vk::ImageTiling::OPTIMAL, + vk::FormatFeatureFlags::SAMPLED_IMAGE + | vk::FormatFeatureFlags::TRANSFER_SRC + | vk::FormatFeatureFlags::TRANSFER_DST, + ) && !caps.is_driver(vk::DriverId::MOLTENVK), + ); + } + + if let Some(ref _sampler_ycbcr_conversion) = self.sampler_ycbcr_conversion { + features.set( + F::TEXTURE_FORMAT_P010, + supports_format( + instance, + phd, + vk::Format::G10X6_B10X6R10X6_2PLANE_420_UNORM_3PACK16, + vk::ImageTiling::OPTIMAL, + vk::FormatFeatureFlags::SAMPLED_IMAGE + | vk::FormatFeatureFlags::TRANSFER_SRC + | vk::FormatFeatureFlags::TRANSFER_DST, + ) && !caps.is_driver(vk::DriverId::MOLTENVK), + ); + } + + features.set( + F::VULKAN_GOOGLE_DISPLAY_TIMING, + caps.supports_extension(google::display_timing::NAME), + ); + + features.set( + F::VULKAN_EXTERNAL_MEMORY_WIN32, + caps.supports_extension(khr::external_memory_win32::NAME), + ); + features.set( + F::VULKAN_EXTERNAL_MEMORY_FD, + caps.supports_extension(khr::external_memory_fd::NAME), + ); + features.set( + F::VULKAN_EXTERNAL_MEMORY_DMA_BUF, + caps.supports_extension(khr::external_memory_fd::NAME) + && caps.supports_extension(ext::external_memory_dma_buf::NAME) + && caps.supports_extension(ext::image_drm_format_modifier::NAME), + ); + features.set( + F::EXPERIMENTAL_MESH_SHADER, + caps.supports_extension(ext::mesh_shader::NAME), + ); + features.set( + F::EXPERIMENTAL_MESH_SHADER_POINTS, + caps.supports_extension(ext::mesh_shader::NAME), + ); + if let Some(ref mesh_shader) = self.mesh_shader { + features.set( + F::EXPERIMENTAL_MESH_SHADER_MULTIVIEW, + mesh_shader.multiview_mesh_shader != 0, + ); + } + + // Not supported by default by `VK_KHR_portability_subset`, which we use on apple platforms. + features.set( + F::MULTISAMPLE_ARRAY, + self.portability_subset + .map(|p| p.multisample_array_image == vk::TRUE) + .unwrap_or(true), + ); + // Enable cooperative matrix if any configuration is supported. The SPIR-V + // we emit for it uses `Device`-scope atomics under the Vulkan memory model, + // so the device must also support `vulkanMemoryModelDeviceScope`, otherwise + // those shaders trip `VUID-RuntimeSpirv-vulkanMemoryModel-06265`. + features.set( + F::EXPERIMENTAL_COOPERATIVE_MATRIX, + !caps.cooperative_matrix_properties.is_empty() + && self.vulkan_memory_model.is_some_and(|m| { + m.vulkan_memory_model == vk::TRUE + && m.vulkan_memory_model_device_scope == vk::TRUE + }), + ); + + features.set( + F::SHADER_DRAW_INDEX, + self.shader_draw_parameters + .is_some_and(|a| a.shader_draw_parameters != 0) + || caps.supports_extension(c"VK_KHR_shader_draw_parameters"), + ); + + (features, dl_flags) + } +} + +/// Vulkan "properties" structures gathered about a physical device. +/// +/// This structure holds the properties of a [`vk::PhysicalDevice`]: +/// - the standard Vulkan device properties +/// - the `VkExtensionProperties` structs for all available extensions, and +/// - the per-extension properties structures for the available extensions that +/// `wgpu` cares about. +/// +/// Generally, if you get it from any of these functions, it's stored +/// here: +/// - `vkEnumerateDeviceExtensionProperties` +/// - `vkGetPhysicalDeviceProperties` +/// - `vkGetPhysicalDeviceProperties2` +/// +/// This also includes a copy of the device API version, since we can +/// use that as a shortcut for searching for an extension, if the +/// extension has been promoted to core in the current version. +/// +/// This does not include device features; for those, see +/// [`PhysicalDeviceFeatures`]. +#[derive(Default, Debug)] +pub struct PhysicalDeviceProperties { + /// Extensions supported by the `vk::PhysicalDevice`, + /// as returned by `vkEnumerateDeviceExtensionProperties`. + supported_extensions: Vec<vk::ExtensionProperties>, + + /// Properties of the `vk::PhysicalDevice`, as returned by + /// `vkGetPhysicalDeviceProperties`. + properties: vk::PhysicalDeviceProperties, + + /// Additional `vk::PhysicalDevice` properties from the + /// `VK_KHR_maintenance3` extension, promoted to Vulkan 1.1. + maintenance_3: Option<vk::PhysicalDeviceMaintenance3Properties<'static>>, + + /// Additional `vk::PhysicalDevice` properties from the + /// `VK_KHR_maintenance4` extension, promoted to Vulkan 1.3. + maintenance_4: Option<vk::PhysicalDeviceMaintenance4Properties<'static>>, + + /// Additional `vk::PhysicalDevice` properties from the + /// `VK_EXT_descriptor_indexing` extension, promoted to Vulkan 1.2. + descriptor_indexing: Option<vk::PhysicalDeviceDescriptorIndexingPropertiesEXT<'static>>, + + /// Additional `vk::PhysicalDevice` properties from the + /// `VK_KHR_acceleration_structure` extension. + acceleration_structure: Option<vk::PhysicalDeviceAccelerationStructurePropertiesKHR<'static>>, + + /// Additional `vk::PhysicalDevice` properties from the + /// `VK_KHR_ray_tracing_pipeline` extension. + ray_tracing_pipeline: Option<vk::PhysicalDeviceRayTracingPipelinePropertiesKHR<'static>>, + + /// Additional `vk::PhysicalDevice` properties from the + /// `VK_KHR_driver_properties` extension, promoted to Vulkan 1.2. + driver: Option<vk::PhysicalDeviceDriverPropertiesKHR<'static>>, + + /// Additional `vk::PhysicalDevice` properties from Vulkan 1.1. + subgroup: Option<vk::PhysicalDeviceSubgroupProperties<'static>>, + + /// Additional `vk::PhysicalDevice` properties from the + /// `VK_EXT_subgroup_size_control` extension, promoted to Vulkan 1.3. + subgroup_size_control: Option<vk::PhysicalDeviceSubgroupSizeControlProperties<'static>>, + + /// Additional `vk::PhysicalDevice` properties from the + /// `VK_EXT_robustness2` extension. + robustness2: Option<vk::PhysicalDeviceRobustness2PropertiesEXT<'static>>, + + /// Additional `vk::PhysicalDevice` properties from the + /// `VK_EXT_mesh_shader` extension. + mesh_shader: Option<vk::PhysicalDeviceMeshShaderPropertiesEXT<'static>>, + + /// Additional `vk::PhysicalDevice` properties from the + /// `VK_KHR_multiview` extension. + multiview: Option<vk::PhysicalDeviceMultiviewPropertiesKHR<'static>>, + + /// `VK_EXT_pci_bus_info` extension. + pci_bus_info: Option<vk::PhysicalDevicePCIBusInfoPropertiesEXT<'static>>, + + /// The device API version. + /// + /// Which is the version of Vulkan supported for device-level functionality. + /// + /// It is associated with a `VkPhysicalDevice` and its children. + device_api_version: u32, + + /// Supported cooperative matrix configurations. + /// + /// This is determined by querying `vkGetPhysicalDeviceCooperativeMatrixPropertiesKHR`. + cooperative_matrix_properties: Vec<wgt::CooperativeMatrixProperties>, +} + +impl PhysicalDeviceProperties { + pub fn properties(&self) -> vk::PhysicalDeviceProperties { + self.properties + } + + pub fn supports_extension(&self, extension: &CStr) -> bool { + self.supported_extensions + .iter() + .any(|ep| ep.extension_name_as_c_str() == Ok(extension)) + } + + pub fn is_driver(&self, id: vk::DriverId) -> bool { + self.driver.is_some_and(|driver| driver.driver_id == id) + } + + /// Map `requested_features` to the list of Vulkan extension strings required to create the logical device. + fn get_required_extensions(&self, requested_features: wgt::Features) -> Vec<&'static CStr> { + let mut extensions = Vec::new(); + + // Note that quite a few extensions depend on the `VK_KHR_get_physical_device_properties2` instance extension. + // We enable `VK_KHR_get_physical_device_properties2` unconditionally (if available). + + // Require `VK_KHR_swapchain` + extensions.push(khr::swapchain::NAME); + + if self.device_api_version < vk::API_VERSION_1_1 { + // Require `VK_KHR_maintenance1` + extensions.push(khr::maintenance1::NAME); + + // Optional `VK_KHR_maintenance2` + if self.supports_extension(khr::maintenance2::NAME) { + extensions.push(khr::maintenance2::NAME); + } + + // Optional `VK_KHR_maintenance3` + if self.supports_extension(khr::maintenance3::NAME) { + extensions.push(khr::maintenance3::NAME); + } + + // Require `VK_KHR_storage_buffer_storage_class` + extensions.push(khr::storage_buffer_storage_class::NAME); + + // Require `VK_KHR_multiview` if the associated feature was requested + if requested_features.contains(wgt::Features::MULTIVIEW) { + extensions.push(khr::multiview::NAME); + } + + // Require `VK_KHR_sampler_ycbcr_conversion` if the associated feature was requested + if requested_features.contains(wgt::Features::TEXTURE_FORMAT_NV12) { + extensions.push(khr::sampler_ycbcr_conversion::NAME); + } + + // Require `VK_KHR_16bit_storage` if `SHADER_F16` or `SHADER_I16` was requested + if requested_features.intersects(wgt::Features::SHADER_F16 | wgt::Features::SHADER_I16) + { + // - Feature `SHADER_F16` also requires `VK_KHR_shader_float16_int8`, but we always + // require that anyway (if it is available) below. + // - `VK_KHR_16bit_storage` requires `VK_KHR_storage_buffer_storage_class`, however + // we require that one already. + extensions.push(khr::_16bit_storage::NAME); + } + + if requested_features.contains(wgt::Features::SHADER_DRAW_INDEX) { + extensions.push(khr::shader_draw_parameters::NAME); + } + } + + if self.device_api_version < vk::API_VERSION_1_2 { + // Optional `VK_KHR_image_format_list` + if self.supports_extension(khr::image_format_list::NAME) { + extensions.push(khr::image_format_list::NAME); + } + + // Optional `VK_KHR_driver_properties` + if self.supports_extension(khr::driver_properties::NAME) { + extensions.push(khr::driver_properties::NAME); + } + + // Optional `VK_KHR_timeline_semaphore` + if self.supports_extension(khr::timeline_semaphore::NAME) { + extensions.push(khr::timeline_semaphore::NAME); + } + + // Require `VK_EXT_descriptor_indexing` if one of the associated features was requested + if requested_features.intersects(INDEXING_FEATURES) { + extensions.push(ext::descriptor_indexing::NAME); + } + + // Always require `VK_KHR_shader_float16_int8` if available as it enables + // Int8 optimizations. Also require it even if it's not available but + // requested so that we get a corresponding error message. + if requested_features.contains(wgt::Features::SHADER_F16) + || self.supports_extension(khr::shader_float16_int8::NAME) + { + extensions.push(khr::shader_float16_int8::NAME); + } + + if requested_features.intersects(wgt::Features::EXPERIMENTAL_MESH_SHADER) { + extensions.push(khr::spirv_1_4::NAME); + } + + //extensions.push(khr::sampler_mirror_clamp_to_edge::NAME); + //extensions.push(ext::sampler_filter_minmax::NAME); + } + + if self.device_api_version < vk::API_VERSION_1_3 { + // Optional `VK_KHR_maintenance4` + if self.supports_extension(khr::maintenance4::NAME) { + extensions.push(khr::maintenance4::NAME); + } + + // Optional `VK_EXT_image_robustness` + if self.supports_extension(ext::image_robustness::NAME) { + extensions.push(ext::image_robustness::NAME); + } + + // Require `VK_EXT_subgroup_size_control` if the associated feature was requested + if requested_features.contains(wgt::Features::SUBGROUP) { + extensions.push(ext::subgroup_size_control::NAME); + } + + // Optional `VK_KHR_shader_integer_dot_product` + if self.supports_extension(khr::shader_integer_dot_product::NAME) { + extensions.push(khr::shader_integer_dot_product::NAME); + } + } + + // Optional `VK_KHR_swapchain_mutable_format` + if self.supports_extension(khr::swapchain_mutable_format::NAME) { + extensions.push(khr::swapchain_mutable_format::NAME); + } + + // Optional `VK_EXT_robustness2` + if self.supports_extension(ext::robustness2::NAME) { + extensions.push(ext::robustness2::NAME); + } + + // Optional `VK_KHR_external_memory_win32` + if self.supports_extension(khr::external_memory_win32::NAME) { + extensions.push(khr::external_memory_win32::NAME); + } + + // Optional `VK_KHR_external_memory_fd` + if self.supports_extension(khr::external_memory_fd::NAME) { + extensions.push(khr::external_memory_fd::NAME); + } + + // Optional `VK_EXT_external_memory_dma` + if self.supports_extension(ext::external_memory_dma_buf::NAME) { + extensions.push(ext::external_memory_dma_buf::NAME); + } + + // Optional `VK_EXT_image_drm_format_modifier` + if self.supports_extension(ext::image_drm_format_modifier::NAME) { + extensions.push(ext::image_drm_format_modifier::NAME); + } + + // Optional `VK_EXT_memory_budget` + if self.supports_extension(ext::memory_budget::NAME) { + extensions.push(ext::memory_budget::NAME); + } else { + log::debug!("VK_EXT_memory_budget is not available.") + } + + // Require `VK_KHR_draw_indirect_count` if the associated feature was requested + // Even though Vulkan 1.2 has promoted the extension to core, we must require the extension to avoid + // large amounts of spaghetti involved with using PhysicalDeviceVulkan12Features. + if requested_features.contains(wgt::Features::MULTI_DRAW_INDIRECT_COUNT) { + extensions.push(khr::draw_indirect_count::NAME); + } + + // Require `VK_KHR_deferred_host_operations`, `VK_KHR_acceleration_structure` `VK_KHR_buffer_device_address` (for acceleration structures) if either `EXPERIMENTAL_RAY_QUERY` or `EXPERIMENTAL_RAY_TRACING_PIPELINES` were requested. + if requested_features.intersects( + wgt::Features::EXPERIMENTAL_RAY_QUERY + | wgt::Features::EXPERIMENTAL_RAY_TRACING_PIPELINES, + ) { + extensions.push(khr::deferred_host_operations::NAME); + extensions.push(khr::acceleration_structure::NAME); + extensions.push(khr::buffer_device_address::NAME); + } + + // Require `VK_KHR_ray_query` if `EXPERIMENTAL_RAY_QUERY` was requested + if requested_features.contains(wgt::Features::EXPERIMENTAL_RAY_QUERY) { + extensions.push(khr::ray_query::NAME); + } + + // Require `VK_KHR_ray_tracing_pipeline` if `EXPERIMENTAL_RAY_TRACING_PIPELINES` was requested + if requested_features.contains(wgt::Features::EXPERIMENTAL_RAY_TRACING_PIPELINES) { + extensions.push(khr::ray_tracing_pipeline::NAME); + } + + if requested_features.contains(wgt::Features::EXPERIMENTAL_RAY_HIT_VERTEX_RETURN) { + extensions.push(khr::ray_tracing_position_fetch::NAME) + } + + // Require `VK_EXT_conservative_rasterization` if the associated feature was requested + if requested_features.contains(wgt::Features::CONSERVATIVE_RASTERIZATION) { + extensions.push(ext::conservative_rasterization::NAME); + } + + // Require `VK_KHR_portability_subset` on macOS/iOS + #[cfg(target_vendor = "apple")] + extensions.push(khr::portability_subset::NAME); + + // Require `VK_EXT_texture_compression_astc_hdr` if the associated feature was requested + if requested_features.contains(wgt::Features::TEXTURE_COMPRESSION_ASTC_HDR) { + extensions.push(ext::texture_compression_astc_hdr::NAME); + } + + // Require `VK_KHR_shader_atomic_int64` if the associated feature was requested + if requested_features.intersects( + wgt::Features::SHADER_INT64_ATOMIC_ALL_OPS | wgt::Features::SHADER_INT64_ATOMIC_MIN_MAX, + ) { + extensions.push(khr::shader_atomic_int64::NAME); + } + + // Require `VK_EXT_shader_image_atomic_int64` if the associated feature was requested + if requested_features.intersects(wgt::Features::TEXTURE_INT64_ATOMIC) { + extensions.push(ext::shader_image_atomic_int64::NAME); + } + + // Require `VK_EXT_shader_atomic_float` if the associated feature was requested + if requested_features.contains(wgt::Features::SHADER_FLOAT32_ATOMIC) { + extensions.push(ext::shader_atomic_float::NAME); + } + + // Require VK_GOOGLE_display_timing if the associated feature was requested + if requested_features.contains(wgt::Features::VULKAN_GOOGLE_DISPLAY_TIMING) { + extensions.push(google::display_timing::NAME); + } + + if requested_features.contains(wgt::Features::EXPERIMENTAL_MESH_SHADER) { + extensions.push(ext::mesh_shader::NAME); + } + + // Require `VK_KHR_fragment_shader_barycentric` if an associated feature was requested + // Vulkan bundles both barycentrics and per-vertex attributes under the same feature. + if requested_features + .intersects(wgt::Features::SHADER_BARYCENTRICS | wgt::Features::SHADER_PER_VERTEX) + { + extensions.push(khr::fragment_shader_barycentric::NAME); + } + + // Require `VK_KHR_cooperative_matrix` if the associated feature was requested + if requested_features.contains(wgt::Features::EXPERIMENTAL_COOPERATIVE_MATRIX) { + extensions.push(khr::cooperative_matrix::NAME); + } + + extensions + } + + fn to_wgpu_limits(&self) -> wgt::Limits { + let limits = &self.properties.limits; + + // Default is only implemented for tuples up to a certain size. + let ( + mut max_task_workgroup_total_count, + mut max_task_workgroups_per_dimension, + mut max_mesh_workgroup_total_count, + mut max_mesh_workgroups_per_dimension, + ) = Default::default(); + let ( + mut max_task_invocations_per_workgroup, + mut max_task_invocations_per_dimension, + mut max_mesh_invocations_per_workgroup, + mut max_mesh_invocations_per_dimension, + mut max_task_payload_size, + mut max_mesh_output_vertices, + mut max_mesh_output_primitives, + mut max_mesh_output_layers, + mut max_mesh_multiview_view_count, + ) = Default::default(); + if let Some(m) = self.mesh_shader { + max_task_workgroup_total_count = m.max_task_work_group_total_count; + max_task_workgroups_per_dimension = + m.max_task_work_group_count.into_iter().min().unwrap(); + max_mesh_workgroup_total_count = m.max_mesh_work_group_total_count; + max_mesh_workgroups_per_dimension = + m.max_mesh_work_group_count.into_iter().min().unwrap(); + max_task_invocations_per_workgroup = m.max_task_work_group_invocations; + max_task_invocations_per_dimension = + m.max_task_work_group_size.into_iter().min().unwrap(); + max_mesh_invocations_per_workgroup = m.max_mesh_work_group_invocations; + max_mesh_invocations_per_dimension = + m.max_mesh_work_group_size.into_iter().min().unwrap(); + max_task_payload_size = m.max_task_payload_size; + max_mesh_output_vertices = m.max_mesh_output_vertices; + max_mesh_output_primitives = m.max_mesh_output_primitives; + max_mesh_output_layers = m.max_mesh_output_layers; + max_mesh_multiview_view_count = m.max_mesh_multiview_view_count; + } + + let max_memory_allocation_size = self + .maintenance_3 + .map(|maintenance_3| maintenance_3.max_memory_allocation_size) + .unwrap_or(u64::MAX); + let max_buffer_size = self + .maintenance_4 + .map(|maintenance_4| maintenance_4.max_buffer_size) + .unwrap_or(u64::MAX); + let max_buffer_size = max_buffer_size.min(max_memory_allocation_size); + + // Prevent very large buffers on mesa and most android devices, and in all cases + // don't risk confusing JS by exceeding the range of a double. + let is_nvidia = self.properties.vendor_id == crate::auxil::db::nvidia::VENDOR; + let max_buffer_size_cap = + if (cfg!(target_os = "linux") || cfg!(target_os = "android")) && !is_nvidia { + i32::MAX as u64 + } else { + 1u64 << 52 + }; + + let max_buffer_size = max_buffer_size.min(max_buffer_size_cap); + + let mut max_binding_array_elements = 0; + let mut max_sampler_binding_array_elements = 0; + if let Some(ref descriptor_indexing) = self.descriptor_indexing { + max_binding_array_elements = descriptor_indexing + .max_descriptor_set_update_after_bind_sampled_images + .min(descriptor_indexing.max_descriptor_set_update_after_bind_storage_images) + .min(descriptor_indexing.max_descriptor_set_update_after_bind_storage_buffers) + .min(descriptor_indexing.max_per_stage_descriptor_update_after_bind_sampled_images) + .min(descriptor_indexing.max_per_stage_descriptor_update_after_bind_storage_images) + .min( + descriptor_indexing.max_per_stage_descriptor_update_after_bind_storage_buffers, + ); + + max_sampler_binding_array_elements = descriptor_indexing + .max_descriptor_set_update_after_bind_samplers + .min(descriptor_indexing.max_per_stage_descriptor_update_after_bind_samplers); + } + + const MAX_SHADER_STAGES_PER_PIPELINE: u32 = 2; + + // When summed, the 3 limits below must be under Vulkan's maxFragmentCombinedOutputResources. + // https://gpuweb.github.io/gpuweb/correspondence/#vulkan-maxFragmentCombinedOutputResources + // + // - maxStorageTexturesPerShaderStage, WebGPU default: 4 + // - maxStorageBuffersPerShaderStage, WebGPU default: 8 + // - maxColorAttachments, WebGPU default: 8 + // + // However, maxFragmentCombinedOutputResources should be ignored on + // intel/nvidia/amd/imgtec since it's not reported correctly. + // + // https://github.com/gpuweb/gpuweb/issues/3631#issuecomment-1498747606 + // https://github.com/gpuweb/gpuweb/issues/4018 + let mut max_storage_textures_per_shader_stage = limits + .max_per_stage_descriptor_storage_images + .min(limits.max_descriptor_set_storage_images / MAX_SHADER_STAGES_PER_PIPELINE); + let mut max_storage_buffers_per_shader_stage = limits + .max_per_stage_descriptor_storage_buffers + .min(limits.max_descriptor_set_storage_buffers / MAX_SHADER_STAGES_PER_PIPELINE); + let mut max_color_attachments = limits + .max_color_attachments + .min(limits.max_fragment_output_attachments); + + let ignore_max_fragment_combined_output_resources_by_device = [ + crate::auxil::db::intel::VENDOR, + crate::auxil::db::nvidia::VENDOR, + crate::auxil::db::amd::VENDOR, + crate::auxil::db::imgtec::VENDOR, + ] + .contains(&self.properties.vendor_id); + let ignore_max_fragment_combined_output_resources_by_driver = + self.is_driver(vk::DriverId::MESA_AGXV); + let ignore_max_fragment_combined_output_resources = + ignore_max_fragment_combined_output_resources_by_device + || ignore_max_fragment_combined_output_resources_by_driver; + + if !ignore_max_fragment_combined_output_resources { + crate::auxil::cap_limits_to_be_under_the_sum_limit( + [ + &mut max_storage_textures_per_shader_stage, + &mut max_storage_buffers_per_shader_stage, + &mut max_color_attachments, + ], + limits.max_fragment_combined_output_resources, + ); + } + + // When summed, the 5 limits below must be under Vulkan's maxPerStageResources. + // + // - maxUniformBuffersPerShaderStage, WebGPU default: 12 + // - maxSampledTexturesPerShaderStage, WebGPU default: 16 + // - maxStorageTexturesPerShaderStage, WebGPU default: 4 + // - maxStorageBuffersPerShaderStage, WebGPU default: 8 + // - maxColorAttachments, WebGPU default: 8 + // + // Note: Vulkan's texel buffers and input attachments also count towards + // maxPerStageResources but we don't make use of them. + let mut max_sampled_textures_per_shader_stage = limits + .max_per_stage_descriptor_sampled_images + .min(limits.max_descriptor_set_sampled_images / MAX_SHADER_STAGES_PER_PIPELINE); + let mut max_uniform_buffers_per_shader_stage = limits + .max_per_stage_descriptor_uniform_buffers + .min(limits.max_descriptor_set_uniform_buffers / MAX_SHADER_STAGES_PER_PIPELINE); + + crate::auxil::cap_limits_to_be_under_the_sum_limit( + [ + &mut max_sampled_textures_per_shader_stage, + &mut max_uniform_buffers_per_shader_stage, + &mut max_storage_textures_per_shader_stage, + &mut max_storage_buffers_per_shader_stage, + &mut max_color_attachments, + ], + limits.max_per_stage_resources, + ); + + // Acceleration structure limits + let mut max_blas_geometry_count = 0; + let mut max_blas_primitive_count = 0; + let mut max_tlas_instance_count = 0; + let mut max_acceleration_structures_per_shader_stage = 0; + if let Some(properties) = self.acceleration_structure { + max_blas_geometry_count = properties.max_geometry_count as u32; + max_blas_primitive_count = properties.max_primitive_count as u32; + max_tlas_instance_count = properties.max_instance_count as u32; + max_acceleration_structures_per_shader_stage = properties + .max_per_stage_descriptor_acceleration_structures + .min( + properties.max_descriptor_set_acceleration_structures + / MAX_SHADER_STAGES_PER_PIPELINE, + ); + } + + // When summed, the 6 limits below must be under Vulkan's + // maxPerSetDescriptors / MAX_SHADER_STAGES_PER_PIPELINE. + // + // - maxUniformBuffersPerShaderStage, WebGPU default: 12 + // - maxSampledTexturesPerShaderStage, WebGPU default: 16 + // - maxStorageTexturesPerShaderStage, WebGPU default: 4 + // - maxStorageBuffersPerShaderStage, WebGPU default: 8 + // - maxSamplersPerShaderStage, WebGPU default: 16 + // - maxAccelerationStructuresPerShaderStage, Native only + // + // Note: All Vulkan's descriptor types count towards maxPerSetDescriptors but + // we don't use all of them. + // See https://registry.khronos.org/vulkan/specs/latest/html/vkspec.html#interfaces-resources-limits + let max_per_set_descriptors = self + .maintenance_3 + .map(|maintenance_3| maintenance_3.max_per_set_descriptors) + // The lowest value seen in reports is 312, use 256 as a safe default. + // https://vulkan.gpuinfo.org/displayextensionproperty.php?extensionname=VK_KHR_maintenance3&extensionproperty=maxPerSetDescriptors&platform=all + // https://vulkan.gpuinfo.org/displaycoreproperty.php?core=1.1&name=maxPerSetDescriptors&platform=all + .unwrap_or(256); + + let mut max_samplers_per_shader_stage = limits + .max_per_stage_descriptor_samplers + .min(limits.max_descriptor_set_samplers / MAX_SHADER_STAGES_PER_PIPELINE); + + crate::auxil::cap_limits_to_be_under_the_sum_limit( + [ + &mut max_sampled_textures_per_shader_stage, + &mut max_uniform_buffers_per_shader_stage, + &mut max_storage_textures_per_shader_stage, + &mut max_storage_buffers_per_shader_stage, + &mut max_samplers_per_shader_stage, + &mut max_acceleration_structures_per_shader_stage, + ], + max_per_set_descriptors / MAX_SHADER_STAGES_PER_PIPELINE, + ); + + // Use max(default, maxPerSetDescriptors) since the spec requires this + // limit to be at least 1000. This is ok because we already lowered + // all the other relevant per stage limits so their sum is lower + // than maxPerSetDescriptors. + let max_bindings_per_bind_group = 1000.max(max_per_set_descriptors); + + // TODO: programmatically determine this, if possible. It's unclear whether we can + // as of https://github.com/gpuweb/gpuweb/issues/2965#issuecomment-1361315447. + // + // In theory some tilers may not support this much. We can't tell however, and + // the driver will throw a DEVICE_REMOVED if it goes too high in usage. This is fine. + let max_color_attachment_bytes_per_sample = + max_color_attachments * wgt::TextureFormat::MAX_TARGET_PIXEL_BYTE_COST; + + let mut max_ray_dispatch_count = 0; + let mut max_ray_recursion_depth = 0; + + if let Some(properties) = self.ray_tracing_pipeline { + max_ray_dispatch_count = properties.max_ray_dispatch_invocation_count; + max_ray_recursion_depth = properties.max_ray_recursion_depth; + } + + let max_multiview_view_count = self + .multiview + .map(|a| a.max_multiview_view_count.min(32)) + .unwrap_or(0); + + crate::auxil::adjust_raw_limits(wgt::Limits { + // + // WebGPU LIMITS: + // Based on https://gpuweb.github.io/gpuweb/correspondence/#limits + // + max_texture_dimension_1d: limits.max_image_dimension1_d, + max_texture_dimension_2d: limits + .max_image_dimension2_d + .min(limits.max_image_dimension_cube) + .min(limits.max_framebuffer_width) + .min(limits.max_framebuffer_height), + max_texture_dimension_3d: limits.max_image_dimension3_d, + max_texture_array_layers: limits.max_image_array_layers, + max_bind_groups: limits.max_bound_descriptor_sets, + // No limit. + max_bind_groups_plus_vertex_buffers: u32::MAX, + max_bindings_per_bind_group, + max_dynamic_uniform_buffers_per_pipeline_layout: limits + .max_descriptor_set_uniform_buffers_dynamic, + max_dynamic_storage_buffers_per_pipeline_layout: limits + .max_descriptor_set_storage_buffers_dynamic, + max_samplers_per_shader_stage, + max_sampled_textures_per_shader_stage, + max_storage_textures_per_shader_stage, + max_storage_buffers_per_shader_stage, + max_uniform_buffers_per_shader_stage, + max_vertex_buffers: limits.max_vertex_input_bindings, + max_buffer_size, + max_uniform_buffer_binding_size: limits + .max_uniform_buffer_range + .min(crate::auxil::MAX_I32_BINDING_SIZE) + .into(), + max_storage_buffer_binding_size: limits + .max_storage_buffer_range + .min(crate::auxil::MAX_I32_BINDING_SIZE) + .into(), + min_uniform_buffer_offset_alignment: limits.min_uniform_buffer_offset_alignment as u32, + min_storage_buffer_offset_alignment: limits.min_storage_buffer_offset_alignment as u32, + max_vertex_attributes: limits.max_vertex_input_attributes, + max_vertex_buffer_array_stride: limits.max_vertex_input_binding_stride, + max_inter_stage_shader_variables: limits + .max_vertex_output_components + .min(limits.max_fragment_input_components) + / 4 + - 1, // -1 for position + max_color_attachments, + max_color_attachment_bytes_per_sample, + max_compute_workgroup_storage_size: limits.max_compute_shared_memory_size, + max_compute_invocations_per_workgroup: limits.max_compute_work_group_invocations, + max_compute_workgroup_size_x: limits.max_compute_work_group_size[0], + max_compute_workgroup_size_y: limits.max_compute_work_group_size[1], + max_compute_workgroup_size_z: limits.max_compute_work_group_size[2], + max_compute_workgroups_per_dimension: limits.max_compute_work_group_count[0] + .min(limits.max_compute_work_group_count[1]) + .min(limits.max_compute_work_group_count[2]), + max_immediate_size: limits.max_push_constants_size, + // + // NATIVE (Non-WebGPU) LIMITS: + // + max_non_sampler_bindings: u32::MAX, + + max_binding_array_elements_per_shader_stage: max_binding_array_elements, + max_binding_array_sampler_elements_per_shader_stage: max_sampler_binding_array_elements, + max_binding_array_acceleration_structure_elements_per_shader_stage: if self + .descriptor_indexing + .is_some() + { + max_acceleration_structures_per_shader_stage + } else { + 0 + }, + + max_task_workgroup_total_count, + max_task_workgroups_per_dimension, + max_mesh_workgroup_total_count, + max_mesh_workgroups_per_dimension, + + max_task_invocations_per_workgroup, + max_task_invocations_per_dimension, + + max_mesh_invocations_per_workgroup, + max_mesh_invocations_per_dimension, + + max_task_payload_size, + max_mesh_output_vertices, + max_mesh_output_primitives, + max_mesh_output_layers, + max_mesh_multiview_view_count, + + max_blas_primitive_count, + max_blas_geometry_count, + max_tlas_instance_count, + max_acceleration_structures_per_shader_stage, + max_buffers_and_acceleration_structures_per_shader_stage: u32::MAX, + + max_multiview_view_count, + + max_ray_dispatch_count, + max_ray_recursion_depth, + }) + } + + /// Return a `wgpu_hal::Alignments` structure describing this adapter. + /// + /// The `using_robustness2` argument says how this adapter will implement + /// `wgpu_hal`'s guarantee that shaders can only read the [accessible + /// region][ar] of bindgroup's buffer bindings: + /// + /// - If this adapter will depend on `VK_EXT_robustness2`'s + /// `robustBufferAccess2` feature to apply bounds checks to shader buffer + /// access, `using_robustness2` must be `true`. + /// + /// - Otherwise, this adapter must use Naga to inject bounds checks on + /// buffer accesses, and `using_robustness2` must be `false`. + /// + /// [ar]: ../../struct.BufferBinding.html#accessible-region + fn to_hal_alignments(&self, using_robustness2: bool) -> crate::Alignments { + let limits = &self.properties.limits; + crate::Alignments { + buffer_copy_offset: wgt::BufferSize::new(limits.optimal_buffer_copy_offset_alignment) + .unwrap(), + buffer_copy_pitch: wgt::BufferSize::new(limits.optimal_buffer_copy_row_pitch_alignment) + .unwrap(), + uniform_bounds_check_alignment: { + let alignment = if using_robustness2 { + self.robustness2 + .unwrap() // if we're using it, we should have its properties + .robust_uniform_buffer_access_size_alignment + } else { + // If the `robustness2` properties are unavailable, then `robustness2` is not available either Naga-injected bounds checks are precise. + 1 + }; + wgt::BufferSize::new(alignment).unwrap() + }, + raw_tlas_instance_size: 64, + ray_tracing_scratch_buffer_alignment: self.acceleration_structure.map_or( + 0, + |acceleration_structure| { + acceleration_structure.min_acceleration_structure_scratch_offset_alignment + }, + ), + ray_tracing_pipeline_group_data_size: self + .ray_tracing_pipeline + .map_or(0, |ray_tracing_pipeline| { + ray_tracing_pipeline.shader_group_handle_size + }), + ray_tracing_pipeline_group_data_alignment: self + .ray_tracing_pipeline + .map_or(0, |ray_tracing_pipeline| { + ray_tracing_pipeline.shader_group_handle_alignment + }), + ray_tracing_pipeline_data_offset_alignment: self + .ray_tracing_pipeline + .map_or(0, |ray_tracing_pipeline| { + ray_tracing_pipeline.shader_group_base_alignment + }), + } + } +} + +impl super::InstanceShared { + fn inspect( + &self, + phd: vk::PhysicalDevice, + ) -> (PhysicalDeviceProperties, PhysicalDeviceFeatures) { + let capabilities = { + let mut capabilities = PhysicalDeviceProperties::default(); + capabilities.supported_extensions = + unsafe { self.raw.enumerate_device_extension_properties(phd).unwrap() }; + capabilities.properties = unsafe { self.raw.get_physical_device_properties(phd) }; + capabilities.device_api_version = capabilities.properties.api_version; + + let supports_multiview = capabilities.device_api_version >= vk::API_VERSION_1_1 + || capabilities.supports_extension(khr::multiview::NAME); + + if let Some(ref get_device_properties) = self.get_physical_device_properties { + // Get these now to avoid borrowing conflicts later + let supports_maintenance3 = capabilities.device_api_version >= vk::API_VERSION_1_1 + || capabilities.supports_extension(khr::maintenance3::NAME); + let supports_maintenance4 = capabilities.device_api_version >= vk::API_VERSION_1_3 + || capabilities.supports_extension(khr::maintenance4::NAME); + let supports_descriptor_indexing = capabilities.device_api_version + >= vk::API_VERSION_1_2 + || capabilities.supports_extension(ext::descriptor_indexing::NAME); + let supports_driver_properties = capabilities.device_api_version + >= vk::API_VERSION_1_2 + || capabilities.supports_extension(khr::driver_properties::NAME); + let supports_subgroup_size_control = capabilities.device_api_version + >= vk::API_VERSION_1_3 + || capabilities.supports_extension(ext::subgroup_size_control::NAME); + let supports_robustness2 = capabilities.supports_extension(ext::robustness2::NAME); + let supports_pci_bus_info = + capabilities.supports_extension(ext::pci_bus_info::NAME); + + let supports_acceleration_structure = + capabilities.supports_extension(khr::acceleration_structure::NAME); + + let supports_ray_tracing_pipeline = + capabilities.supports_extension(khr::ray_tracing_pipeline::NAME); + + let supports_mesh_shader = capabilities.supports_extension(ext::mesh_shader::NAME); + + let mut properties2 = vk::PhysicalDeviceProperties2KHR::default(); + if supports_maintenance3 { + let next = capabilities + .maintenance_3 + .insert(vk::PhysicalDeviceMaintenance3Properties::default()); + properties2 = properties2.push_next(next); + } + + if supports_maintenance4 { + let next = capabilities + .maintenance_4 + .insert(vk::PhysicalDeviceMaintenance4Properties::default()); + properties2 = properties2.push_next(next); + } + + if supports_descriptor_indexing { + let next = capabilities + .descriptor_indexing + .insert(vk::PhysicalDeviceDescriptorIndexingPropertiesEXT::default()); + properties2 = properties2.push_next(next); + } + + if supports_acceleration_structure { + let next = capabilities + .acceleration_structure + .insert(vk::PhysicalDeviceAccelerationStructurePropertiesKHR::default()); + properties2 = properties2.push_next(next); + } + + if supports_ray_tracing_pipeline { + let next = capabilities + .ray_tracing_pipeline + .insert(vk::PhysicalDeviceRayTracingPipelinePropertiesKHR::default()); + properties2 = properties2.push_next(next); + } + + if supports_driver_properties { + let next = capabilities + .driver + .insert(vk::PhysicalDeviceDriverPropertiesKHR::default()); + properties2 = properties2.push_next(next); + } + + if capabilities.device_api_version >= vk::API_VERSION_1_1 { + let next = capabilities + .subgroup + .insert(vk::PhysicalDeviceSubgroupProperties::default()); + properties2 = properties2.push_next(next); + } + + if supports_subgroup_size_control { + let next = capabilities + .subgroup_size_control + .insert(vk::PhysicalDeviceSubgroupSizeControlProperties::default()); + properties2 = properties2.push_next(next); + } + + if supports_robustness2 { + let next = capabilities + .robustness2 + .insert(vk::PhysicalDeviceRobustness2PropertiesEXT::default()); + properties2 = properties2.push_next(next); + } + + if supports_pci_bus_info { + let next = capabilities + .pci_bus_info + .insert(vk::PhysicalDevicePCIBusInfoPropertiesEXT::default()); + properties2 = properties2.push_next(next); + } + + if supports_mesh_shader { + let next = capabilities + .mesh_shader + .insert(vk::PhysicalDeviceMeshShaderPropertiesEXT::default()); + properties2 = properties2.push_next(next); + } + + if supports_multiview { + let next = capabilities + .multiview + .insert(vk::PhysicalDeviceMultiviewProperties::default()); + properties2 = properties2.push_next(next); + } + + unsafe { + get_device_properties.get_physical_device_properties2(phd, &mut properties2) + }; + + // Query cooperative matrix properties + if capabilities.supports_extension(khr::cooperative_matrix::NAME) { + let coop_matrix = + khr::cooperative_matrix::Instance::new(&self.entry, &self.raw); + capabilities.cooperative_matrix_properties = + query_cooperative_matrix_properties(&coop_matrix, phd); + } + + // Suppress some capabilities to avoid known problems + if is_intel_igpu_outdated_for_robustness2(&capabilities) { + capabilities + .supported_extensions + .retain(|&x| x.extension_name_as_c_str() != Ok(ext::robustness2::NAME)); + capabilities.robustness2 = None; + } + + // Due to https://gitlab.freedesktop.org/mesa/mesa/-/work_items/15725 + // TODO(https://github.com/gfx-rs/wgpu/issues/9742): enable on + // fixed driver versions, when available + if capabilities.is_driver(vk::DriverId::MESA_RADV) { + capabilities + .supported_extensions + .retain(|&x| x.extension_name_as_c_str() != Ok(ext::memory_budget::NAME)); + } + }; + capabilities + }; + + let mut features = PhysicalDeviceFeatures::default(); + features.core = if let Some(ref get_device_properties) = self.get_physical_device_properties + { + let core = vk::PhysicalDeviceFeatures::default(); + let mut features2 = vk::PhysicalDeviceFeatures2KHR::default().features(core); + + // `VK_KHR_multiview` is promoted to 1.1 + if capabilities.device_api_version >= vk::API_VERSION_1_1 + || capabilities.supports_extension(khr::multiview::NAME) + { + let next = features + .multiview + .insert(vk::PhysicalDeviceMultiviewFeatures::default()); + features2 = features2.push_next(next); + } + + // `VK_KHR_sampler_ycbcr_conversion` is promoted to 1.1 + if capabilities.device_api_version >= vk::API_VERSION_1_1 + || capabilities.supports_extension(khr::sampler_ycbcr_conversion::NAME) + { + let next = features + .sampler_ycbcr_conversion + .insert(vk::PhysicalDeviceSamplerYcbcrConversionFeatures::default()); + features2 = features2.push_next(next); + } + + if capabilities.supports_extension(ext::descriptor_indexing::NAME) { + let next = features + .descriptor_indexing + .insert(vk::PhysicalDeviceDescriptorIndexingFeaturesEXT::default()); + features2 = features2.push_next(next); + } + + // `VK_KHR_timeline_semaphore` is promoted to 1.2, but has no + // changes, so we can keep using the extension unconditionally. + if capabilities.supports_extension(khr::timeline_semaphore::NAME) { + let next = features + .timeline_semaphore + .insert(vk::PhysicalDeviceTimelineSemaphoreFeaturesKHR::default()); + features2 = features2.push_next(next); + } + + // `VK_KHR_shader_atomic_int64` is promoted to 1.2, but has no + // changes, so we can keep using the extension unconditionally. + if capabilities.device_api_version >= vk::API_VERSION_1_2 + || capabilities.supports_extension(khr::shader_atomic_int64::NAME) + { + let next = features + .shader_atomic_int64 + .insert(vk::PhysicalDeviceShaderAtomicInt64Features::default()); + features2 = features2.push_next(next); + } + + if capabilities.supports_extension(ext::shader_image_atomic_int64::NAME) { + let next = features + .shader_image_atomic_int64 + .insert(vk::PhysicalDeviceShaderImageAtomicInt64FeaturesEXT::default()); + features2 = features2.push_next(next); + } + if capabilities.supports_extension(ext::shader_atomic_float::NAME) { + let next = features + .shader_atomic_float + .insert(vk::PhysicalDeviceShaderAtomicFloatFeaturesEXT::default()); + features2 = features2.push_next(next); + } + if capabilities.supports_extension(ext::image_robustness::NAME) { + let next = features + .image_robustness + .insert(vk::PhysicalDeviceImageRobustnessFeaturesEXT::default()); + features2 = features2.push_next(next); + } + if capabilities.supports_extension(ext::robustness2::NAME) { + let next = features + .robustness2 + .insert(vk::PhysicalDeviceRobustness2FeaturesEXT::default()); + features2 = features2.push_next(next); + } + if capabilities.supports_extension(ext::texture_compression_astc_hdr::NAME) { + let next = features + .astc_hdr + .insert(vk::PhysicalDeviceTextureCompressionASTCHDRFeaturesEXT::default()); + features2 = features2.push_next(next); + } + + // `VK_KHR_shader_float16_int8` is promoted to 1.2 + if capabilities.device_api_version >= vk::API_VERSION_1_2 + || capabilities.supports_extension(khr::shader_float16_int8::NAME) + { + let next = features + .shader_float16_int8 + .insert(vk::PhysicalDeviceShaderFloat16Int8FeaturesKHR::default()); + features2 = features2.push_next(next); + } + + if capabilities.supports_extension(khr::_16bit_storage::NAME) { + let next = features + ._16bit_storage + .insert(vk::PhysicalDevice16BitStorageFeaturesKHR::default()); + features2 = features2.push_next(next); + } + if capabilities.supports_extension(khr::acceleration_structure::NAME) { + let next = features + .acceleration_structure + .insert(vk::PhysicalDeviceAccelerationStructureFeaturesKHR::default()); + features2 = features2.push_next(next); + } + + if capabilities.supports_extension(khr::ray_tracing_position_fetch::NAME) { + let next = features + .position_fetch + .insert(vk::PhysicalDeviceRayTracingPositionFetchFeaturesKHR::default()); + features2 = features2.push_next(next); + } + + // `VK_KHR_maintenance4` is promoted to 1.3 + if capabilities.device_api_version >= vk::API_VERSION_1_3 + || capabilities.supports_extension(khr::maintenance4::NAME) + { + let next = features + .maintenance4 + .insert(vk::PhysicalDeviceMaintenance4Features::default()); + features2 = features2.push_next(next); + } + + // `VK_KHR_zero_initialize_workgroup_memory` is promoted to 1.3 + if capabilities.device_api_version >= vk::API_VERSION_1_3 + || capabilities.supports_extension(khr::zero_initialize_workgroup_memory::NAME) + { + let next = features + .zero_initialize_workgroup_memory + .insert(vk::PhysicalDeviceZeroInitializeWorkgroupMemoryFeatures::default()); + features2 = features2.push_next(next); + } + + // `VK_EXT_subgroup_size_control` is promoted to 1.3 + if capabilities.device_api_version >= vk::API_VERSION_1_3 + || capabilities.supports_extension(ext::subgroup_size_control::NAME) + { + let next = features + .subgroup_size_control + .insert(vk::PhysicalDeviceSubgroupSizeControlFeatures::default()); + features2 = features2.push_next(next); + } + + if capabilities.supports_extension(ext::mesh_shader::NAME) { + let next = features + .mesh_shader + .insert(vk::PhysicalDeviceMeshShaderFeaturesEXT::default()); + features2 = features2.push_next(next); + } + + // `VK_KHR_shader_integer_dot_product` is promoted to 1.3 + if capabilities.device_api_version >= vk::API_VERSION_1_3 + || capabilities.supports_extension(khr::shader_integer_dot_product::NAME) + { + let next = features + .shader_integer_dot_product + .insert(vk::PhysicalDeviceShaderIntegerDotProductFeatures::default()); + features2 = features2.push_next(next); + } + + if capabilities.supports_extension(khr::fragment_shader_barycentric::NAME) { + let next = features + .shader_barycentrics + .insert(vk::PhysicalDeviceFragmentShaderBarycentricFeaturesKHR::default()); + features2 = features2.push_next(next); + } + + if capabilities.supports_extension(khr::portability_subset::NAME) { + let next = features + .portability_subset + .insert(vk::PhysicalDevicePortabilitySubsetFeaturesKHR::default()); + features2 = features2.push_next(next); + } + + if capabilities.supports_extension(khr::cooperative_matrix::NAME) { + let next = features + .cooperative_matrix + .insert(vk::PhysicalDeviceCooperativeMatrixFeaturesKHR::default()); + features2 = features2.push_next(next); + } + + if capabilities.device_api_version >= vk::API_VERSION_1_2 + || capabilities.supports_extension(khr::vulkan_memory_model::NAME) + { + let next = features + .vulkan_memory_model + .insert(vk::PhysicalDeviceVulkanMemoryModelFeaturesKHR::default()); + features2 = features2.push_next(next); + } + + if capabilities.device_api_version >= vk::API_VERSION_1_1 { + let next = features + .shader_draw_parameters + .insert(vk::PhysicalDeviceShaderDrawParametersFeatures::default()); + features2 = features2.push_next(next); + } + + unsafe { get_device_properties.get_physical_device_features2(phd, &mut features2) }; + features2.features + } else { + unsafe { self.raw.get_physical_device_features(phd) } + }; + + (capabilities, features) + } +} + +impl super::Instance { + pub fn expose_adapter( + &self, + phd: vk::PhysicalDevice, + ) -> Option<crate::ExposedAdapter<super::Api>> { + use crate::auxil::db; + + let (phd_capabilities, phd_features) = self.shared.inspect(phd); + + let mem_properties = { + profiling::scope!("vkGetPhysicalDeviceMemoryProperties"); + unsafe { self.shared.raw.get_physical_device_memory_properties(phd) } + }; + let memory_types = &mem_properties.memory_types_as_slice(); + let supports_lazily_allocated = memory_types.iter().any(|mem| { + mem.property_flags + .contains(vk::MemoryPropertyFlags::LAZILY_ALLOCATED) + }); + + let device_type = match phd_capabilities.properties.device_type { + vk::PhysicalDeviceType::OTHER => wgt::DeviceType::Other, + vk::PhysicalDeviceType::INTEGRATED_GPU => wgt::DeviceType::IntegratedGpu, + vk::PhysicalDeviceType::DISCRETE_GPU => wgt::DeviceType::DiscreteGpu, + vk::PhysicalDeviceType::VIRTUAL_GPU => wgt::DeviceType::VirtualGpu, + vk::PhysicalDeviceType::CPU => wgt::DeviceType::Cpu, + _ => wgt::DeviceType::Other, + }; + let info = wgt::AdapterInfo { + name: { + phd_capabilities + .properties + .device_name_as_c_str() + .ok() + .and_then(|name| name.to_str().ok()) + .unwrap_or("?") + .to_owned() + }, + vendor: phd_capabilities.properties.vendor_id, + device: phd_capabilities.properties.device_id, + device_pci_bus_id: phd_capabilities + .pci_bus_info + .filter(|info| info.pci_bus != 0 || info.pci_device != 0) + .map(|info| { + format!( + "{:04x}:{:02x}:{:02x}.{}", + info.pci_domain, info.pci_bus, info.pci_device, info.pci_function + ) + }) + .unwrap_or_default(), + driver: { + phd_capabilities + .driver + .as_ref() + .and_then(|driver| driver.driver_name_as_c_str().ok()) + .and_then(|name| name.to_str().ok()) + .unwrap_or("?") + .to_owned() + }, + driver_info: { + phd_capabilities + .driver + .as_ref() + .and_then(|driver| driver.driver_info_as_c_str().ok()) + .and_then(|name| name.to_str().ok()) + .unwrap_or("?") + .to_owned() + }, + subgroup_min_size: phd_capabilities + .subgroup_size_control + .map(|subgroup_size| subgroup_size.min_subgroup_size) + .unwrap_or(wgt::MINIMUM_SUBGROUP_MIN_SIZE), + subgroup_max_size: phd_capabilities + .subgroup_size_control + .map(|subgroup_size| subgroup_size.max_subgroup_size) + .unwrap_or(wgt::MAXIMUM_SUBGROUP_MAX_SIZE), + transient_saves_memory: Some(supports_lazily_allocated), + ..wgt::AdapterInfo::new(device_type, wgt::Backend::Vulkan) + }; + let mut workarounds = super::Workarounds::empty(); + { + // TODO: only enable for particular devices + workarounds |= super::Workarounds::SEPARATE_ENTRY_POINTS; + workarounds.set( + super::Workarounds::EMPTY_RESOLVE_ATTACHMENT_LISTS, + phd_capabilities.properties.vendor_id == db::qualcomm::VENDOR, + ); + workarounds.set( + super::Workarounds::FORCE_FILL_BUFFER_WITH_SIZE_GREATER_4096_ALIGNED_OFFSET_16, + phd_capabilities.properties.vendor_id == db::nvidia::VENDOR, + ); + }; + + if let Some(driver) = phd_capabilities.driver { + if driver.conformance_version.major == 0 { + if driver.driver_id == vk::DriverId::MOLTENVK { + log::debug!("Adapter is not Vulkan compliant, but is MoltenVK, continuing"); + } else if self + .shared + .flags + .contains(wgt::InstanceFlags::ALLOW_UNDERLYING_NONCOMPLIANT_ADAPTER) + { + log::debug!("Adapter is not Vulkan compliant: {}", info.name); + } else { + log::debug!( + "Adapter is not Vulkan compliant, hiding adapter: {}", + info.name + ); + return None; + } + } + } + if phd_capabilities.device_api_version == vk::API_VERSION_1_0 + && !phd_capabilities.supports_extension(khr::storage_buffer_storage_class::NAME) + { + log::debug!( + "SPIR-V storage buffer class is not supported, hiding adapter: {}", + info.name + ); + return None; + } + if !phd_capabilities.supports_extension(khr::maintenance1::NAME) + && phd_capabilities.device_api_version < vk::API_VERSION_1_1 + { + log::debug!( + "VK_KHR_maintenance1 is not supported, hiding adapter: {}", + info.name + ); + return None; + } + + let queue_families = unsafe { + self.shared + .raw + .get_physical_device_queue_family_properties(phd) + }; + let queue_family_properties = queue_families.first()?; + let queue_flags = queue_family_properties.queue_flags; + if !queue_flags.contains(vk::QueueFlags::GRAPHICS) { + log::debug!("The first queue only exposes {queue_flags:?}"); + return None; + } + + let (available_features, mut downlevel_flags) = phd_features.to_wgpu( + &self.shared.raw, + phd, + &phd_capabilities, + queue_family_properties, + ); + + if phd_capabilities.is_driver(vk::DriverId::MESA_LLVMPIPE) { + // The `F16_IN_F32` instructions do not normally require native `F16` support, but on + // llvmpipe, they do. + downlevel_flags.set( + wgt::DownlevelFlags::SHADER_F16_IN_F32, + available_features.contains(wgt::Features::SHADER_F16), + ); + } + + downlevel_flags.set( + wgt::DownlevelFlags::TEXTURE_COMPRESSION, + available_features.contains(wgt::Features::TEXTURE_COMPRESSION_BC) + || available_features.contains( + wgt::Features::TEXTURE_COMPRESSION_ETC2 + | wgt::Features::TEXTURE_COMPRESSION_ASTC, + ), + ); + + let has_robust_buffer_access2 = phd_features + .robustness2 + .as_ref() + .map(|r| r.robust_buffer_access2 == 1) + .unwrap_or_default(); + + let alignments = phd_capabilities.to_hal_alignments(has_robust_buffer_access2); + + let private_caps = super::PrivateCapabilities { + image_view_usage: phd_capabilities.device_api_version >= vk::API_VERSION_1_1 + || phd_capabilities.supports_extension(khr::maintenance2::NAME), + timeline_semaphores: match phd_features.timeline_semaphore { + Some(features) => features.timeline_semaphore == vk::TRUE, + None => phd_features + .timeline_semaphore + .is_some_and(|ext| ext.timeline_semaphore != 0), + }, + texture_d24: supports_format( + &self.shared.raw, + phd, + vk::Format::X8_D24_UNORM_PACK32, + vk::ImageTiling::OPTIMAL, + depth_stencil_required_flags(), + ), + texture_d24_s8: supports_format( + &self.shared.raw, + phd, + vk::Format::D24_UNORM_S8_UINT, + vk::ImageTiling::OPTIMAL, + depth_stencil_required_flags(), + ), + texture_s8: supports_format( + &self.shared.raw, + phd, + vk::Format::S8_UINT, + vk::ImageTiling::OPTIMAL, + depth_stencil_required_flags(), + ), + multi_draw_indirect: phd_features.core.multi_draw_indirect != 0, + max_draw_indirect_count: phd_capabilities.properties.limits.max_draw_indirect_count, + non_coherent_map_mask: phd_capabilities.properties.limits.non_coherent_atom_size - 1, + can_present: true, + //TODO: make configurable + robust_buffer_access: phd_features.core.robust_buffer_access != 0, + robust_image_access: match phd_features.robustness2 { + Some(ref f) => f.robust_image_access2 != 0, + None => phd_features + .image_robustness + .is_some_and(|ext| ext.robust_image_access != 0), + }, + robust_buffer_access2: has_robust_buffer_access2, + robust_image_access2: phd_features + .robustness2 + .as_ref() + .map(|r| r.robust_image_access2 == 1) + .unwrap_or_default(), + zero_initialize_workgroup_memory: phd_features + .zero_initialize_workgroup_memory + .is_some_and(|ext| ext.shader_zero_initialize_workgroup_memory == vk::TRUE), + image_format_list: phd_capabilities.device_api_version >= vk::API_VERSION_1_2 + || phd_capabilities.supports_extension(khr::image_format_list::NAME), + maximum_samplers: phd_capabilities + .properties + .limits + .max_sampler_allocation_count, + shader_integer_dot_product: phd_features + .shader_integer_dot_product + .is_some_and(|ext| ext.shader_integer_dot_product != 0), + shader_int8: phd_features + .shader_float16_int8 + .is_some_and(|features| features.shader_int8 != 0), + multiview_instance_index_limit: phd_capabilities + .multiview + .map(|a| a.max_multiview_instance_index) + .unwrap_or(0), + scratch_buffer_alignment: alignments.ray_tracing_scratch_buffer_alignment, + ray_tracing_pipeline_group_data_size: alignments.ray_tracing_pipeline_group_data_size, + }; + let capabilities = crate::Capabilities { + limits: phd_capabilities.to_wgpu_limits(), + alignments, + downlevel: wgt::DownlevelCapabilities { + flags: downlevel_flags, + limits: wgt::DownlevelLimits {}, + shader_model: wgt::ShaderModel::Sm5, //TODO? + }, + cooperative_matrix_properties: phd_capabilities.cooperative_matrix_properties.clone(), + }; + + let adapter = super::Adapter { + raw: phd, + instance: Arc::clone(&self.shared), + //queue_families, + known_memory_flags: vk::MemoryPropertyFlags::DEVICE_LOCAL + | vk::MemoryPropertyFlags::HOST_VISIBLE + | vk::MemoryPropertyFlags::HOST_COHERENT + | vk::MemoryPropertyFlags::HOST_CACHED + | vk::MemoryPropertyFlags::LAZILY_ALLOCATED, + phd_capabilities, + phd_features, + downlevel_flags, + private_caps, + workarounds, + }; + + Some(crate::ExposedAdapter { + adapter, + info, + features: available_features, + capabilities, + }) + } +} + +impl super::Adapter { + pub fn raw_physical_device(&self) -> vk::PhysicalDevice { + self.raw + } + + pub fn get_physical_device_features(&self) -> &PhysicalDeviceFeatures { + &self.phd_features + } + + pub fn physical_device_capabilities(&self) -> &PhysicalDeviceProperties { + &self.phd_capabilities + } + + pub fn shared_instance(&self) -> &super::InstanceShared { + &self.instance + } + + pub fn required_device_extensions(&self, features: wgt::Features) -> Vec<&'static CStr> { + let (supported_extensions, unsupported_extensions) = self + .phd_capabilities + .get_required_extensions(features) + .iter() + .partition::<Vec<&CStr>, _>(|&&extension| { + self.phd_capabilities.supports_extension(extension) + }); + + if !unsupported_extensions.is_empty() { + log::debug!("Missing extensions: {unsupported_extensions:?}"); + } + + log::debug!("Supported extensions: {supported_extensions:?}"); + supported_extensions + } + + /// Create a `PhysicalDeviceFeatures` for opening a logical device with + /// `features` from this adapter. + /// + /// The given `enabled_extensions` set must include all the extensions + /// selected by [`required_device_extensions`] when passed `features`. + /// Otherwise, the `PhysicalDeviceFeatures` value may not be able to select + /// all the Vulkan features needed to represent `features` and this + /// adapter's characteristics. + /// + /// Typically, you'd simply call `required_device_extensions`, and then pass + /// its return value and the feature set you gave it directly to this + /// function. But it's fine to add more extensions to the list. + /// + /// [`required_device_extensions`]: Self::required_device_extensions + pub fn physical_device_features( + &self, + enabled_extensions: &[&'static CStr], + features: wgt::Features, + ) -> PhysicalDeviceFeatures { + PhysicalDeviceFeatures::from_extensions_and_requested_features( + &self.phd_capabilities, + &self.phd_features, + enabled_extensions, + features, + self.downlevel_flags, + &self.private_caps, + ) + } + + /// # Safety + /// + /// - `raw_device` must be created from this adapter. + /// - `raw_device` must be created using `family_index`, `enabled_extensions` and `physical_device_features()` + /// - `enabled_extensions` must be a superset of `required_device_extensions()`. + /// - If `drop_callback` is [`None`], wgpu-hal will take ownership of `raw_device`. If + /// `drop_callback` is [`Some`], `raw_device` must be valid until the callback is called. + #[allow(clippy::too_many_arguments)] + pub unsafe fn device_from_raw( + &self, + raw_device: ash::Device, + drop_callback: Option<crate::DropCallback>, + enabled_extensions: &[&'static CStr], + features: wgt::Features, + limits: &wgt::Limits, + memory_hints: &wgt::MemoryHints, + family_index: u32, + queue_index: u32, + ) -> Result<crate::OpenDevice<super::Api>, crate::DeviceError> { + let mem_properties = { + profiling::scope!("vkGetPhysicalDeviceMemoryProperties"); + unsafe { + self.instance + .raw + .get_physical_device_memory_properties(self.raw) + } + }; + let memory_types = &mem_properties.memory_types_as_slice(); + let valid_ash_memory_types = memory_types.iter().enumerate().fold(0, |u, (i, mem)| { + if self.known_memory_flags.contains(mem.property_flags) { + u | (1 << i) + } else { + u + } + }); + + // Note that VK_EXT_debug_utils is an instance extension (enabled at the instance + // level) but contains a few functions that can be loaded directly on the Device for a + // dispatch-table-less pointer. + let debug_utils_fn = if self.instance.extensions.contains(&ext::debug_utils::NAME) { + Some(ext::debug_utils::Device::new( + &self.instance.raw, + &raw_device, + )) + } else { + None + }; + let indirect_count_fn = if enabled_extensions.contains(&khr::draw_indirect_count::NAME) { + Some(khr::draw_indirect_count::Device::new( + &self.instance.raw, + &raw_device, + )) + } else { + None + }; + let timeline_semaphore_fn = if enabled_extensions.contains(&khr::timeline_semaphore::NAME) { + Some(super::ExtensionFn::Extension( + khr::timeline_semaphore::Device::new(&self.instance.raw, &raw_device), + )) + } else if self.phd_capabilities.device_api_version >= vk::API_VERSION_1_2 { + Some(super::ExtensionFn::Promoted) + } else { + None + }; + let ray_tracing_fns = if enabled_extensions.contains(&khr::acceleration_structure::NAME) + && enabled_extensions.contains(&khr::buffer_device_address::NAME) + { + Some(super::RayTracingDeviceExtensionFunctions { + acceleration_structure: khr::acceleration_structure::Device::new( + &self.instance.raw, + &raw_device, + ), + buffer_device_address: khr::buffer_device_address::Device::new( + &self.instance.raw, + &raw_device, + ), + }) + } else { + None + }; + let ray_tracing_pipeline_fns = + if enabled_extensions.contains(&khr::ray_tracing_pipeline::NAME) { + Some(khr::ray_tracing_pipeline::Device::new( + &self.instance.raw, + &raw_device, + )) + } else { + None + }; + let mesh_shading_fns = if enabled_extensions.contains(&ext::mesh_shader::NAME) { + Some(ext::mesh_shader::Device::new( + &self.instance.raw, + &raw_device, + )) + } else { + None + }; + let external_memory_fd_fn = if enabled_extensions.contains(&khr::external_memory_fd::NAME) { + Some(khr::external_memory_fd::Device::new( + &self.instance.raw, + &raw_device, + )) + } else { + None + }; + + let naga_options = { + use naga::back::spv; + + // The following capabilities are always available + // see https://registry.khronos.org/vulkan/specs/1.3-extensions/html/chap52.html#spirvenv-capabilities + let mut capabilities = vec![ + spv::Capability::Shader, + spv::Capability::Matrix, + spv::Capability::Sampled1D, + spv::Capability::Image1D, + spv::Capability::ImageQuery, + spv::Capability::DerivativeControl, + spv::Capability::StorageImageExtendedFormats, + ]; + + if self + .downlevel_flags + .contains(wgt::DownlevelFlags::CUBE_ARRAY_TEXTURES) + { + capabilities.push(spv::Capability::SampledCubeArray); + } + + if self + .downlevel_flags + .contains(wgt::DownlevelFlags::MULTISAMPLED_SHADING) + { + capabilities.push(spv::Capability::SampleRateShading); + } + + if features.contains(wgt::Features::MULTIVIEW) { + capabilities.push(spv::Capability::MultiView); + } + + if features.contains(wgt::Features::PRIMITIVE_INDEX) { + capabilities.push(spv::Capability::Geometry); + } + + if features.intersects(wgt::Features::SUBGROUP | wgt::Features::SUBGROUP_VERTEX) { + capabilities.push(spv::Capability::GroupNonUniform); + capabilities.push(spv::Capability::GroupNonUniformVote); + capabilities.push(spv::Capability::GroupNonUniformArithmetic); + capabilities.push(spv::Capability::GroupNonUniformBallot); + capabilities.push(spv::Capability::GroupNonUniformShuffle); + capabilities.push(spv::Capability::GroupNonUniformShuffleRelative); + capabilities.push(spv::Capability::GroupNonUniformQuad); + } + + if features.intersects( + wgt::Features::SAMPLED_TEXTURE_AND_STORAGE_BUFFER_ARRAY_NON_UNIFORM_INDEXING + | wgt::Features::STORAGE_TEXTURE_ARRAY_NON_UNIFORM_INDEXING + | wgt::Features::UNIFORM_BUFFER_BINDING_ARRAYS, + ) { + capabilities.push(spv::Capability::ShaderNonUniform); + } + if features.contains(wgt::Features::BGRA8UNORM_STORAGE) { + capabilities.push(spv::Capability::StorageImageWriteWithoutFormat); + } + + if features.contains(wgt::Features::EXPERIMENTAL_RAY_QUERY) { + capabilities.push(spv::Capability::RayQueryKHR); + } + + if features.contains(wgt::Features::SHADER_INT64) { + capabilities.push(spv::Capability::Int64); + } + + if features.contains(wgt::Features::SHADER_F16) { + capabilities.push(spv::Capability::Float16); + } + + if features.contains(wgt::Features::SHADER_I16) { + capabilities.push(spv::Capability::Int16); + } + + if features.intersects( + wgt::Features::SHADER_INT64_ATOMIC_ALL_OPS + | wgt::Features::SHADER_INT64_ATOMIC_MIN_MAX + | wgt::Features::TEXTURE_INT64_ATOMIC, + ) { + capabilities.push(spv::Capability::Int64Atomics); + } + + if features.intersects(wgt::Features::TEXTURE_INT64_ATOMIC) { + capabilities.push(spv::Capability::Int64ImageEXT); + } + + if features.contains(wgt::Features::SHADER_FLOAT32_ATOMIC) { + capabilities.push(spv::Capability::AtomicFloat32AddEXT); + } + + if features.contains(wgt::Features::CLIP_DISTANCES) { + capabilities.push(spv::Capability::ClipDistance); + } + + // Vulkan bundles both barycentrics and per-vertex attributes under the same feature. + if features + .intersects(wgt::Features::SHADER_BARYCENTRICS | wgt::Features::SHADER_PER_VERTEX) + { + capabilities.push(spv::Capability::FragmentBarycentricKHR); + } + + if features.contains(wgt::Features::SHADER_DRAW_INDEX) { + capabilities.push(spv::Capability::DrawParameters); + } + + let mut flags = spv::WriterFlags::empty(); + flags.set( + spv::WriterFlags::DEBUG, + self.instance.flags.contains(wgt::InstanceFlags::DEBUG), + ); + flags.set( + spv::WriterFlags::LABEL_VARYINGS, + self.phd_capabilities.properties.vendor_id != crate::auxil::db::qualcomm::VENDOR, + ); + flags.set( + spv::WriterFlags::FORCE_POINT_SIZE, + //Note: we could technically disable this when we are compiling separate entry points, + // and we know exactly that the primitive topology is not `PointList`. + // But this requires cloning the `spv::Options` struct, which has heap allocations. + true, // could check `super::Workarounds::SEPARATE_ENTRY_POINTS` + ); + flags.set( + spv::WriterFlags::PRINT_ON_RAY_QUERY_INITIALIZATION_FAIL + | spv::WriterFlags::PRINT_ON_TRACE_RAYS_FAIL, + self.instance.flags.contains(wgt::InstanceFlags::DEBUG) + && (self.instance.instance_api_version >= vk::API_VERSION_1_3 + || enabled_extensions.contains(&khr::shader_non_semantic_info::NAME)), + ); + if features.contains(wgt::Features::EXPERIMENTAL_RAY_QUERY) { + capabilities.push(spv::Capability::RayQueryKHR); + } + if features.contains(wgt::Features::EXPERIMENTAL_RAY_TRACING_PIPELINES) { + capabilities.push(spv::Capability::RayTracingKHR); + } + if features.contains(wgt::Features::EXPERIMENTAL_RAY_HIT_VERTEX_RETURN) { + capabilities.push(spv::Capability::RayQueryPositionFetchKHR) + } + if features.contains(wgt::Features::EXPERIMENTAL_MESH_SHADER) { + capabilities.push(spv::Capability::MeshShadingEXT); + } + if features.contains(wgt::Features::EXPERIMENTAL_COOPERATIVE_MATRIX) { + capabilities.push(spv::Capability::CooperativeMatrixKHR); + // TODO: expose this more generally + capabilities.push(spv::Capability::VulkanMemoryModel); + } + if self.private_caps.shader_integer_dot_product { + // See <https://registry.khronos.org/vulkan/specs/1.3-extensions/man/html/VK_KHR_shader_integer_dot_product.html#_new_spir_v_capabilities>. + capabilities.extend(&[ + spv::Capability::DotProductInputAllKHR, + spv::Capability::DotProductInput4x8BitKHR, + spv::Capability::DotProductInput4x8BitPackedKHR, + spv::Capability::DotProductKHR, + ]); + } + if self.private_caps.shader_int8 { + // See <https://registry.khronos.org/vulkan/specs/latest/man/html/VkPhysicalDeviceShaderFloat16Int8Features.html#extension-features-shaderInt8>. + capabilities.extend(&[spv::Capability::Int8]); + } + spv::Options { + lang_version: match self.phd_capabilities.device_api_version { + // Use maximum supported SPIR-V version according to + // <https://github.com/KhronosGroup/Vulkan-Docs/blob/19b7651/appendices/spirvenv.adoc?plain=1#L21-L40>. + vk::API_VERSION_1_0..vk::API_VERSION_1_1 => (1, 0), + vk::API_VERSION_1_1..vk::API_VERSION_1_2 => (1, 3), + vk::API_VERSION_1_2..vk::API_VERSION_1_3 => (1, 5), + vk::API_VERSION_1_3.. => (1, 6), + _ => unreachable!(), + }, + flags, + capabilities: Some(capabilities.iter().cloned().collect()), + bounds_check_policies: naga::proc::BoundsCheckPolicies { + index: naga::proc::BoundsCheckPolicy::Restrict, + buffer: if self.private_caps.robust_buffer_access2 { + naga::proc::BoundsCheckPolicy::Unchecked + } else { + naga::proc::BoundsCheckPolicy::Restrict + }, + image_load: if self.private_caps.robust_image_access { + naga::proc::BoundsCheckPolicy::Unchecked + } else { + naga::proc::BoundsCheckPolicy::Restrict + }, + // TODO: support bounds checks on binding arrays + binding_array: naga::proc::BoundsCheckPolicy::Unchecked, + }, + zero_initialize_workgroup_memory: if self + .private_caps + .zero_initialize_workgroup_memory + { + spv::ZeroInitializeWorkgroupMemoryMode::Native + } else { + spv::ZeroInitializeWorkgroupMemoryMode::Polyfill + }, + force_loop_bounding: true, + ray_query_initialization_tracking: true, + use_storage_input_output_16: features.contains(wgt::Features::SHADER_F16) + && self.phd_features.supports_storage_input_output_16(), + fake_missing_bindings: false, + // We need to build this separately for each invocation, so just default it out here + binding_map: BTreeMap::default(), + debug_info: None, + task_dispatch_limits: Some(naga::back::TaskDispatchLimits { + max_mesh_workgroups_per_dim: limits.max_mesh_workgroups_per_dimension, + max_mesh_workgroups_total: limits.max_mesh_workgroup_total_count, + }), + mesh_shader_primitive_indices_clamp: true, + trace_ray_argument_validation: true, + emit_int_div_checks: true, + } + }; + + let raw_queue = { + profiling::scope!("vkGetDeviceQueue"); + unsafe { raw_device.get_device_queue(family_index, queue_index) } + }; + + let driver_version = self + .phd_capabilities + .properties + .driver_version + .to_be_bytes(); + #[rustfmt::skip] + let pipeline_cache_validation_key = [ + driver_version[0], driver_version[1], driver_version[2], driver_version[3], + 0, 0, 0, 0, + 0, 0, 0, 0, + 0, 0, 0, 0, + ]; + + let drop_guard = crate::DropGuard::from_option(drop_callback); + + let empty_descriptor_set_layout = unsafe { + raw_device + .create_descriptor_set_layout(&vk::DescriptorSetLayoutCreateInfo::default(), None) + .map_err(super::map_host_device_oom_err)? + }; + + let shared = Arc::new(super::DeviceShared { + raw: raw_device, + family_index, + queue_index, + raw_queue, + drop_guard, + instance: Arc::clone(&self.instance), + physical_device: self.raw, + enabled_extensions: enabled_extensions.into(), + extension_fns: super::DeviceExtensionFunctions { + debug_utils: debug_utils_fn, + draw_indirect_count: indirect_count_fn, + timeline_semaphore: timeline_semaphore_fn, + ray_tracing: ray_tracing_fns, + ray_tracing_pipelines: ray_tracing_pipeline_fns, + mesh_shading: mesh_shading_fns, + external_memory_fd: external_memory_fd_fn, + }, + pipeline_cache_validation_key, + vendor_id: self.phd_capabilities.properties.vendor_id, + timestamp_period: self.phd_capabilities.properties.limits.timestamp_period, + private_caps: self.private_caps.clone(), + features, + workarounds: self.workarounds, + render_passes: Mutex::new(Default::default()), + sampler_cache: Mutex::new(super::sampler::SamplerCache::new( + self.private_caps.maximum_samplers, + )), + memory_allocations_counter: Default::default(), + + texture_identity_factory: super::ResourceIdentityFactory::new(), + texture_view_identity_factory: super::ResourceIdentityFactory::new(), + empty_descriptor_set_layout, + }); + + let relay_semaphores = super::RelaySemaphores::new(&shared)?; + + let queue = super::Queue { + raw: raw_queue, + device: Arc::clone(&shared), + family_index, + relay_semaphores: Mutex::new(relay_semaphores), + signal_semaphores: Mutex::new(SemaphoreList::new(SemaphoreListMode::Signal)), + wait_semaphores: Mutex::new(SemaphoreList::new(SemaphoreListMode::Wait)), + }; + + let allocation_sizes = AllocationSizes::from_memory_hints(memory_hints).into(); + + let buffer_device_address = enabled_extensions.contains(&khr::buffer_device_address::NAME); + + let mem_allocator = + gpu_allocator::vulkan::Allocator::new(&gpu_allocator::vulkan::AllocatorCreateDesc { + instance: self.instance.raw.clone(), + device: shared.raw.clone(), + physical_device: self.raw, + debug_settings: Default::default(), + buffer_device_address, + allocation_sizes, + })?; + + let desc_allocator = super::descriptor::DescriptorAllocator::new( + if let Some(di) = self.phd_capabilities.descriptor_indexing { + di.max_update_after_bind_descriptors_in_all_pools + } else { + 0 + }, + ); + + let device = super::Device { + shared, + mem_allocator: Mutex::new(mem_allocator), + desc_allocator: Mutex::new(desc_allocator), + valid_ash_memory_types, + naga_options, + #[cfg(feature = "renderdoc")] + render_doc: Default::default(), + counters: Default::default(), + }; + + Ok(crate::OpenDevice { device, queue }) + } + + pub fn texture_format_as_raw(&self, texture_format: wgt::TextureFormat) -> vk::Format { + self.private_caps.map_texture_format(texture_format) + } + + /// # Safety: + /// - Same as `open` plus + /// - The callback may not change anything that the device does not support. + /// - The callback may not remove features. + pub unsafe fn open_with_callback<'a>( + &self, + features: wgt::Features, + limits: &wgt::Limits, + memory_hints: &wgt::MemoryHints, + callback: Option<Box<super::CreateDeviceCallback<'a>>>, + ) -> Result<crate::OpenDevice<super::Api>, crate::DeviceError> { + let mut enabled_extensions = self.required_device_extensions(features); + let mut enabled_phd_features = self.physical_device_features(&enabled_extensions, features); + + let family_index = 0; //TODO + let family_info = vk::DeviceQueueCreateInfo::default() + .queue_family_index(family_index) + .queue_priorities(&[1.0]); + let mut family_infos = Vec::from([family_info]); + + let mut pre_info = vk::DeviceCreateInfo::default(); + + if let Some(callback) = callback { + callback(super::CreateDeviceCallbackArgs { + extensions: &mut enabled_extensions, + device_features: &mut enabled_phd_features, + queue_create_infos: &mut family_infos, + create_info: &mut pre_info, + _phantom: PhantomData, + }) + } + + let str_pointers = enabled_extensions + .iter() + .map(|&s| { + // Safe because `enabled_extensions` entries have static lifetime. + s.as_ptr() + }) + .collect::<Vec<_>>(); + + let pre_info = pre_info + .queue_create_infos(&family_infos) + .enabled_extension_names(&str_pointers); + let info = enabled_phd_features.add_to_device_create(pre_info); + let raw_device = { + profiling::scope!("vkCreateDevice"); + unsafe { + self.instance + .raw + .create_device(self.raw, &info, None) + .map_err(map_err)? + } + }; + fn map_err(err: vk::Result) -> crate::DeviceError { + match err { + vk::Result::ERROR_TOO_MANY_OBJECTS => crate::DeviceError::OutOfMemory, + vk::Result::ERROR_INITIALIZATION_FAILED => crate::DeviceError::Lost, + vk::Result::ERROR_EXTENSION_NOT_PRESENT | vk::Result::ERROR_FEATURE_NOT_PRESENT => { + crate::hal_usage_error(err) + } + other => super::map_host_device_oom_and_lost_err(other), + } + } + + unsafe { + self.device_from_raw( + raw_device, + None, + &enabled_extensions, + features, + limits, + memory_hints, + family_info.queue_family_index, + 0, + ) + } + } +} + +impl crate::Adapter for super::Adapter { + type A = super::Api; + + unsafe fn open( + &self, + features: wgt::Features, + limits: &wgt::Limits, + memory_hints: &wgt::MemoryHints, + ) -> Result<crate::OpenDevice<super::Api>, crate::DeviceError> { + unsafe { self.open_with_callback(features, limits, memory_hints, None) } + } + + unsafe fn texture_format_capabilities( + &self, + format: wgt::TextureFormat, + ) -> crate::TextureFormatCapabilities { + use crate::TextureFormatCapabilities as Tfc; + + let vk_format = self.private_caps.map_texture_format(format); + let properties = unsafe { + self.instance + .raw + .get_physical_device_format_properties(self.raw, vk_format) + }; + let features = properties.optimal_tiling_features; + + let mut flags = Tfc::empty(); + flags.set( + Tfc::SAMPLED, + features.contains(vk::FormatFeatureFlags::SAMPLED_IMAGE), + ); + flags.set( + Tfc::SAMPLED_LINEAR, + features.contains(vk::FormatFeatureFlags::SAMPLED_IMAGE_FILTER_LINEAR), + ); + // flags.set( + // Tfc::SAMPLED_MINMAX, + // features.contains(vk::FormatFeatureFlags::SAMPLED_IMAGE_FILTER_MINMAX), + // ); + flags.set( + Tfc::STORAGE_READ_WRITE + | Tfc::STORAGE_WRITE_ONLY + | Tfc::STORAGE_READ_ONLY + | Tfc::STORAGE_ATOMIC, + features.contains(vk::FormatFeatureFlags::STORAGE_IMAGE), + ); + flags.set( + Tfc::STORAGE_ATOMIC, + features.contains(vk::FormatFeatureFlags::STORAGE_IMAGE_ATOMIC), + ); + flags.set( + Tfc::COLOR_ATTACHMENT, + features.contains(vk::FormatFeatureFlags::COLOR_ATTACHMENT), + ); + flags.set( + Tfc::COLOR_ATTACHMENT_BLEND, + features.contains(vk::FormatFeatureFlags::COLOR_ATTACHMENT_BLEND), + ); + flags.set( + Tfc::DEPTH_STENCIL_ATTACHMENT, + features.contains(vk::FormatFeatureFlags::DEPTH_STENCIL_ATTACHMENT), + ); + flags.set( + Tfc::COPY_SRC, + features.intersects(vk::FormatFeatureFlags::TRANSFER_SRC), + ); + flags.set( + Tfc::COPY_DST, + features.intersects(vk::FormatFeatureFlags::TRANSFER_DST), + ); + flags.set( + Tfc::STORAGE_ATOMIC, + features.intersects(vk::FormatFeatureFlags::STORAGE_IMAGE_ATOMIC), + ); + // Vulkan is very permissive about MSAA + flags.set(Tfc::MULTISAMPLE_RESOLVE, !format.is_compressed()); + + // get the supported sample counts + let format_aspect = crate::FormatAspects::from(format); + let limits = self.phd_capabilities.properties.limits; + + let sample_flags = if format_aspect.contains(crate::FormatAspects::DEPTH) { + limits + .framebuffer_depth_sample_counts + .min(limits.sampled_image_depth_sample_counts) + } else if format_aspect.contains(crate::FormatAspects::STENCIL) { + limits + .framebuffer_stencil_sample_counts + .min(limits.sampled_image_stencil_sample_counts) + } else { + let first_aspect = format_aspect + .iter() + .next() + .expect("All texture should at least one aspect") + .map(); + + // We should never get depth or stencil out of this, due to the above. + assert_ne!(first_aspect, wgt::TextureAspect::DepthOnly); + assert_ne!(first_aspect, wgt::TextureAspect::StencilOnly); + + match format.sample_type(Some(first_aspect), None).unwrap() { + wgt::TextureSampleType::Float { .. } => limits + .framebuffer_color_sample_counts + .min(limits.sampled_image_color_sample_counts), + wgt::TextureSampleType::Sint | wgt::TextureSampleType::Uint => { + limits.sampled_image_integer_sample_counts + } + _ => unreachable!(), + } + }; + + flags.set( + Tfc::MULTISAMPLE_X2, + sample_flags.contains(vk::SampleCountFlags::TYPE_2), + ); + flags.set( + Tfc::MULTISAMPLE_X4, + sample_flags.contains(vk::SampleCountFlags::TYPE_4), + ); + flags.set( + Tfc::MULTISAMPLE_X8, + sample_flags.contains(vk::SampleCountFlags::TYPE_8), + ); + flags.set( + Tfc::MULTISAMPLE_X16, + sample_flags.contains(vk::SampleCountFlags::TYPE_16), + ); + + flags + } + + unsafe fn surface_capabilities( + &self, + surface: &super::Surface, + ) -> Option<crate::SurfaceCapabilities> { + surface.inner.surface_capabilities(self) + } + + unsafe fn surface_display_hdr_info( + &self, + surface: &super::Surface, + ) -> Option<wgt::DisplayHdrInfo> { + // Vulkan has no portable luminance query; the Win32 surface reads it + // through DXGI (see `dxgi::hdr`). Every other surface reports `None`. + surface.inner.display_hdr_info() + } + + unsafe fn get_presentation_timestamp(&self) -> wgt::PresentationTimestamp { + // VK_GOOGLE_display_timing is the only way to get presentation + // timestamps on vulkan right now and it is only ever available + // on android and linux. This includes mac, but there's no alternative + // on mac, so this is fine. + #[cfg(unix)] + { + let mut timespec = libc::timespec::default(); + unsafe { + libc::clock_gettime(libc::CLOCK_MONOTONIC, &mut timespec); + } + + wgt::PresentationTimestamp( + timespec.tv_sec as u128 * 1_000_000_000 + timespec.tv_nsec as u128, + ) + } + #[cfg(not(unix))] + { + wgt::PresentationTimestamp::INVALID_TIMESTAMP + } + } + + fn get_ordered_buffer_usages(&self) -> wgt::BufferUses { + wgt::BufferUses::INCLUSIVE | wgt::BufferUses::MAP_WRITE + } + + // Vulkan makes very few execution ordering guarantees + // see https://registry.khronos.org/vulkan/specs/latest/html/vkspec.html#synchronization-implicit + // We just don't want to insert barriers between inclusive uses + // See https://github.com/gfx-rs/wgpu/issues/8853 + fn get_ordered_texture_usages(&self) -> wgt::TextureUses { + wgt::TextureUses::INCLUSIVE + } +} + +fn is_format_16bit_norm_supported(instance: &ash::Instance, phd: vk::PhysicalDevice) -> bool { + [ + vk::Format::R16_UNORM, + vk::Format::R16_SNORM, + vk::Format::R16G16_UNORM, + vk::Format::R16G16_SNORM, + vk::Format::R16G16B16A16_UNORM, + vk::Format::R16G16B16A16_SNORM, + ] + .into_iter() + .all(|format| { + supports_format( + instance, + phd, + format, + vk::ImageTiling::OPTIMAL, + vk::FormatFeatureFlags::SAMPLED_IMAGE + | vk::FormatFeatureFlags::STORAGE_IMAGE + | vk::FormatFeatureFlags::TRANSFER_SRC + | vk::FormatFeatureFlags::TRANSFER_DST, + ) + }) +} + +fn is_float32_filterable_supported(instance: &ash::Instance, phd: vk::PhysicalDevice) -> bool { + [ + vk::Format::R32_SFLOAT, + vk::Format::R32G32_SFLOAT, + vk::Format::R32G32B32A32_SFLOAT, + ] + .into_iter() + .all(|format| { + supports_format( + instance, + phd, + format, + vk::ImageTiling::OPTIMAL, + vk::FormatFeatureFlags::SAMPLED_IMAGE_FILTER_LINEAR, + ) + }) +} + +fn is_float32_blendable_supported(instance: &ash::Instance, phd: vk::PhysicalDevice) -> bool { + [ + vk::Format::R32_SFLOAT, + vk::Format::R32G32_SFLOAT, + vk::Format::R32G32B32A32_SFLOAT, + ] + .into_iter() + .all(|format| { + supports_format( + instance, + phd, + format, + vk::ImageTiling::OPTIMAL, + vk::FormatFeatureFlags::COLOR_ATTACHMENT_BLEND, + ) + }) +} + +fn supports_format( + instance: &ash::Instance, + phd: vk::PhysicalDevice, + format: vk::Format, + tiling: vk::ImageTiling, + features: vk::FormatFeatureFlags, +) -> bool { + let properties = unsafe { instance.get_physical_device_format_properties(phd, format) }; + match tiling { + vk::ImageTiling::LINEAR => properties.linear_tiling_features.contains(features), + vk::ImageTiling::OPTIMAL => properties.optimal_tiling_features.contains(features), + _ => false, + } +} + +fn supports_astc_3d(instance: &ash::Instance, phd: vk::PhysicalDevice) -> bool { + [ + vk::Format::ASTC_4X4_UNORM_BLOCK, + vk::Format::ASTC_4X4_SRGB_BLOCK, + vk::Format::ASTC_5X4_UNORM_BLOCK, + vk::Format::ASTC_5X4_SRGB_BLOCK, + vk::Format::ASTC_5X5_UNORM_BLOCK, + vk::Format::ASTC_5X5_SRGB_BLOCK, + vk::Format::ASTC_6X5_UNORM_BLOCK, + vk::Format::ASTC_6X5_SRGB_BLOCK, + vk::Format::ASTC_6X6_UNORM_BLOCK, + vk::Format::ASTC_6X6_SRGB_BLOCK, + vk::Format::ASTC_8X5_UNORM_BLOCK, + vk::Format::ASTC_8X5_SRGB_BLOCK, + vk::Format::ASTC_8X6_UNORM_BLOCK, + vk::Format::ASTC_8X6_SRGB_BLOCK, + vk::Format::ASTC_8X8_UNORM_BLOCK, + vk::Format::ASTC_8X8_SRGB_BLOCK, + vk::Format::ASTC_10X5_UNORM_BLOCK, + vk::Format::ASTC_10X5_SRGB_BLOCK, + vk::Format::ASTC_10X6_UNORM_BLOCK, + vk::Format::ASTC_10X6_SRGB_BLOCK, + vk::Format::ASTC_10X8_UNORM_BLOCK, + vk::Format::ASTC_10X8_SRGB_BLOCK, + vk::Format::ASTC_10X10_UNORM_BLOCK, + vk::Format::ASTC_10X10_SRGB_BLOCK, + vk::Format::ASTC_12X10_UNORM_BLOCK, + vk::Format::ASTC_12X10_SRGB_BLOCK, + vk::Format::ASTC_12X12_UNORM_BLOCK, + vk::Format::ASTC_12X12_SRGB_BLOCK, + ] + .into_iter() + .all(|format| { + unsafe { + instance.get_physical_device_image_format_properties( + phd, + format, + vk::ImageType::TYPE_3D, + vk::ImageTiling::OPTIMAL, + vk::ImageUsageFlags::SAMPLED, + vk::ImageCreateFlags::empty(), + ) + } + .is_ok() + }) +} + +fn supports_bgra8unorm_storage( + instance: &ash::Instance, + phd: vk::PhysicalDevice, + device_api_version: u32, +) -> bool { + // See https://github.com/KhronosGroup/Vulkan-Docs/issues/2027#issuecomment-1380608011 + + // This check gates the function call and structures used below. + // TODO: check for (`VK_KHR_get_physical_device_properties2` or VK1.1) and (`VK_KHR_format_feature_flags2` or VK1.3). + // Right now we only check for VK1.3. + if device_api_version < vk::API_VERSION_1_3 { + return false; + } + + unsafe { + let mut properties3 = vk::FormatProperties3::default(); + let mut properties2 = vk::FormatProperties2::default().push_next(&mut properties3); + + instance.get_physical_device_format_properties2( + phd, + vk::Format::B8G8R8A8_UNORM, + &mut properties2, + ); + + let features2 = properties2.format_properties.optimal_tiling_features; + let features3 = properties3.optimal_tiling_features; + + features2.contains(vk::FormatFeatureFlags::STORAGE_IMAGE) + && features3.contains(vk::FormatFeatureFlags2::STORAGE_WRITE_WITHOUT_FORMAT) + } +} + +// For https://github.com/gfx-rs/wgpu/issues/4599 +// Intel iGPUs with outdated drivers can break rendering if `VK_EXT_robustness2` is used. +// Driver version 31.0.101.2115 works, but there's probably an earlier functional version. +fn is_intel_igpu_outdated_for_robustness2(capabilities: &PhysicalDeviceProperties) -> bool { + const DRIVER_VERSION_WORKING: u32 = (101 << 14) | 2115; // X.X.101.2115 + + let props = &capabilities.properties; + + let is_outdated = props.vendor_id == crate::auxil::db::intel::VENDOR + && props.device_type == vk::PhysicalDeviceType::INTEGRATED_GPU + && props.driver_version < DRIVER_VERSION_WORKING + && capabilities.is_driver(vk::DriverId::INTEL_PROPRIETARY_WINDOWS); + + if is_outdated { + log::debug!( + "Disabling robustBufferAccess2 and robustImageAccess2: IntegratedGpu Intel Driver is outdated. Found with version 0x{:X}, less than the known good version 0x{:X} (31.0.101.2115)", + props.driver_version, + DRIVER_VERSION_WORKING + ); + } + is_outdated +} + +/// Convert Vulkan component type to wgt::CooperativeScalarType. +fn map_vk_component_type(ty: vk::ComponentTypeKHR) -> Option<wgt::CooperativeScalarType> { + match ty { + vk::ComponentTypeKHR::FLOAT16 => Some(wgt::CooperativeScalarType::F16), + vk::ComponentTypeKHR::FLOAT32 => Some(wgt::CooperativeScalarType::F32), + vk::ComponentTypeKHR::SINT32 => Some(wgt::CooperativeScalarType::I32), + vk::ComponentTypeKHR::UINT32 => Some(wgt::CooperativeScalarType::U32), + _ => None, + } +} + +/// Convert Vulkan matrix size. +fn map_vk_cooperative_size(size: u32) -> Option<u32> { + match size { + 8 | 16 => Some(size), + _ => None, + } +} + +/// Query all supported cooperative matrix configurations from Vulkan. +fn query_cooperative_matrix_properties( + coop_matrix: &khr::cooperative_matrix::Instance, + phd: vk::PhysicalDevice, +) -> Vec<wgt::CooperativeMatrixProperties> { + let vk_properties = + match unsafe { coop_matrix.get_physical_device_cooperative_matrix_properties(phd) } { + Ok(props) => props, + Err(e) => { + log::warn!("Failed to query cooperative matrix properties: {e:?}"); + return Vec::new(); + } + }; + + log::debug!( + "Vulkan reports {} cooperative matrix configurations", + vk_properties.len() + ); + + let mut result = Vec::new(); + for prop in &vk_properties { + log::debug!( + " Vulkan coop matrix: M={} N={} K={} A={:?} B={:?} C={:?} Result={:?} scope={:?} saturating={}", + prop.m_size, + prop.n_size, + prop.k_size, + prop.a_type, + prop.b_type, + prop.c_type, + prop.result_type, + prop.scope, + prop.saturating_accumulation + ); + + // Only include subgroup-scoped operations (the only scope we support) + if prop.scope != vk::ScopeKHR::SUBGROUP { + log::debug!(" Skipped: scope is not SUBGROUP"); + continue; + } + + // Map sizes - skip configurations with sizes we don't support + let m_size = match map_vk_cooperative_size(prop.m_size) { + Some(s) => s, + None => { + log::debug!(" Skipped: M size {} not supported", prop.m_size); + continue; + } + }; + let n_size = match map_vk_cooperative_size(prop.n_size) { + Some(s) => s, + None => { + log::debug!(" Skipped: N size {} not supported", prop.n_size); + continue; + } + }; + let k_size = match map_vk_cooperative_size(prop.k_size) { + Some(s) => s, + None => { + log::debug!(" Skipped: K size {} not supported", prop.k_size); + continue; + } + }; + + // Map the component types - A and B must match, C and Result must match + let ab_type = match map_vk_component_type(prop.a_type) { + Some(t) if Some(t) == map_vk_component_type(prop.b_type) => t, + _ => { + log::debug!( + " Skipped: A/B types {:?}/{:?} not supported or don't match", + prop.a_type, + prop.b_type + ); + continue; + } + }; + let cr_type = match map_vk_component_type(prop.c_type) { + Some(t) if Some(t) == map_vk_component_type(prop.result_type) => t, + _ => { + log::debug!( + " Skipped: C/Result types {:?}/{:?} not supported or don't match", + prop.c_type, + prop.result_type + ); + continue; + } + }; + + log::debug!(" Accepted!"); + result.push(wgt::CooperativeMatrixProperties { + m_size, + n_size, + k_size, + ab_type, + cr_type, + saturating_accumulation: prop.saturating_accumulation != 0, + }); + } + + log::info!( + "Found {} cooperative matrix configurations supported by wgpu", + result.len() + ); + result +} diff --git a/app/vendor/rune/vendor/wgpu-hal/src/vulkan/command.rs b/app/vendor/rune/vendor/wgpu-hal/src/vulkan/command.rs new file mode 100644 index 0000000..3ea853e --- /dev/null +++ b/app/vendor/rune/vendor/wgpu-hal/src/vulkan/command.rs @@ -0,0 +1,1495 @@ +use super::conv; +use arrayvec::ArrayVec; +use ash::vk; +use core::{mem, ops::Range}; +use hashbrown::hash_map::Entry; + +const ALLOCATION_GRANULARITY: u32 = 16; +const DST_IMAGE_LAYOUT: vk::ImageLayout = vk::ImageLayout::TRANSFER_DST_OPTIMAL; + +impl super::Texture { + fn map_buffer_copies<T>(&self, regions: T) -> impl Iterator<Item = vk::BufferImageCopy> + where + T: Iterator<Item = crate::BufferTextureCopy>, + { + let (block_width, block_height) = self.format.block_dimensions(); + let format = self.format; + let copy_size = self.copy_size; + regions.map(move |r| { + let extent = r.texture_base.max_copy_size(&copy_size).min(&r.size); + let (image_subresource, image_offset) = conv::map_subresource_layers(&r.texture_base); + vk::BufferImageCopy { + buffer_offset: r.buffer_layout.offset, + buffer_row_length: r.buffer_layout.bytes_per_row.map_or(0, |bpr| { + let block_size = format + .block_copy_size(Some(r.texture_base.aspect.map())) + .unwrap(); + block_width * (bpr / block_size) + }), + buffer_image_height: r + .buffer_layout + .rows_per_image + .map_or(0, |rpi| rpi * block_height), + image_subresource, + image_offset, + image_extent: conv::map_copy_extent(&extent), + } + }) + } +} + +impl super::CommandEncoder { + fn write_pass_end_timestamp_if_requested(&mut self) { + if let Some((query_set, index)) = self.end_of_pass_timer_query.take() { + unsafe { + self.device.raw.cmd_write_timestamp( + self.active, + vk::PipelineStageFlags::BOTTOM_OF_PIPE, + query_set, + index, + ); + } + } + } + + fn make_framebuffer( + &mut self, + key: super::FramebufferKey, + ) -> Result<vk::Framebuffer, crate::DeviceError> { + Ok(match self.framebuffers.entry(key) { + Entry::Occupied(e) => *e.get(), + Entry::Vacant(e) => { + let super::FramebufferKey { + raw_pass, + ref attachment_views, + attachment_identities: _, + extent, + } = *e.key(); + + let vk_info = vk::FramebufferCreateInfo::default() + .render_pass(raw_pass) + .width(extent.width) + .height(extent.height) + .layers(extent.depth_or_array_layers) + .attachments(attachment_views); + + let raw = unsafe { self.device.raw.create_framebuffer(&vk_info, None).unwrap() }; + *e.insert(raw) + } + }) + } + + fn make_temp_texture_view( + &mut self, + key: super::TempTextureViewKey, + ) -> Result<super::IdentifiedTextureView, crate::DeviceError> { + Ok(match self.temp_texture_views.entry(key) { + Entry::Occupied(e) => *e.get(), + Entry::Vacant(e) => { + let super::TempTextureViewKey { + texture, + texture_identity: _, + format, + mip_level, + depth_slice, + } = *e.key(); + + let vk_info = vk::ImageViewCreateInfo::default() + .image(texture) + .view_type(vk::ImageViewType::TYPE_2D) + .format(format) + .subresource_range(vk::ImageSubresourceRange { + aspect_mask: vk::ImageAspectFlags::COLOR, + base_mip_level: mip_level, + level_count: 1, + base_array_layer: depth_slice, + layer_count: 1, + }); + let raw = unsafe { self.device.raw.create_image_view(&vk_info, None) } + .map_err(super::map_host_device_oom_and_ioca_err)?; + + let identity = self.device.texture_view_identity_factory.next(); + + *e.insert(super::IdentifiedTextureView { raw, identity }) + } + }) + } +} + +impl crate::CommandEncoder for super::CommandEncoder { + type A = super::Api; + + unsafe fn begin_encoding(&mut self, label: crate::Label) -> Result<(), crate::DeviceError> { + if self.free.is_empty() { + let vk_info = vk::CommandBufferAllocateInfo::default() + .command_pool(self.raw) + .command_buffer_count(ALLOCATION_GRANULARITY); + let cmd_buf_vec = unsafe { + self.device + .raw + .allocate_command_buffers(&vk_info) + .map_err(super::map_host_device_oom_err)? + }; + self.free.extend(cmd_buf_vec); + } + let raw = self.free.pop().unwrap(); + + // Set the name unconditionally, since there might be a + // previous name assigned to this. + unsafe { self.device.set_object_name(raw, label.unwrap_or_default()) }; + + // Reset some state in case the last renderpass was never ended. + self.rpass_debug_marker_active = false; + self.end_of_pass_timer_query = None; + + let vk_info = vk::CommandBufferBeginInfo::default() + .flags(vk::CommandBufferUsageFlags::ONE_TIME_SUBMIT); + unsafe { self.device.raw.begin_command_buffer(raw, &vk_info) } + .map_err(super::map_host_device_oom_err)?; + self.active = raw; + + Ok(()) + } + + unsafe fn end_encoding(&mut self) -> Result<super::CommandBuffer, crate::DeviceError> { + let raw = self.active; + self.active = vk::CommandBuffer::null(); + unsafe { self.device.raw.end_command_buffer(raw) }.map_err(map_err)?; + fn map_err(err: vk::Result) -> crate::DeviceError { + // We don't use VK_KHR_video_encode_queue + // VK_ERROR_INVALID_VIDEO_STD_PARAMETERS_KHR + super::map_host_device_oom_err(err) + } + Ok(super::CommandBuffer { raw }) + } + + unsafe fn discard_encoding(&mut self) { + // Safe use requires this is not called in the "closed" state, so the buffer + // shouldn't be null. Assert this to make sure we're not pushing null + // buffers to the discard pile. + assert_ne!(self.active, vk::CommandBuffer::null()); + + self.discarded.push(self.active); + self.active = vk::CommandBuffer::null(); + } + + unsafe fn reset_all<I>(&mut self, cmd_bufs: I) + where + I: Iterator<Item = super::CommandBuffer>, + { + self.temp.clear(); + self.free + .extend(cmd_bufs.into_iter().map(|cmd_buf| cmd_buf.raw)); + self.free.append(&mut self.discarded); + // Delete framebuffers from the framebuffer cache + for (_, framebuffer) in self.framebuffers.drain() { + unsafe { self.device.raw.destroy_framebuffer(framebuffer, None) }; + } + let _ = unsafe { + self.device + .raw + .reset_command_pool(self.raw, vk::CommandPoolResetFlags::default()) + }; + } + + unsafe fn transition_buffers<'a, T>(&mut self, barriers: T) + where + T: Iterator<Item = crate::BufferBarrier<'a, super::Buffer>>, + { + //Note: this is done so that we never end up with empty stage flags + let mut src_stages = vk::PipelineStageFlags::TOP_OF_PIPE; + let mut dst_stages = vk::PipelineStageFlags::BOTTOM_OF_PIPE; + let vk_barriers = &mut self.temp.buffer_barriers; + vk_barriers.clear(); + + for bar in barriers { + let (src_stage, src_access) = conv::map_buffer_usage_to_barrier(bar.usage.from); + src_stages |= src_stage; + let (dst_stage, dst_access) = conv::map_buffer_usage_to_barrier(bar.usage.to); + dst_stages |= dst_stage; + + vk_barriers.push( + vk::BufferMemoryBarrier::default() + .buffer(bar.buffer.raw) + .size(vk::WHOLE_SIZE) + .src_access_mask(src_access) + .dst_access_mask(dst_access), + ) + } + + if !vk_barriers.is_empty() { + unsafe { + self.device.raw.cmd_pipeline_barrier( + self.active, + src_stages, + dst_stages, + vk::DependencyFlags::empty(), + &[], + vk_barriers, + &[], + ) + }; + } + } + + unsafe fn transition_textures<'a, T>(&mut self, barriers: T) + where + T: Iterator<Item = crate::TextureBarrier<'a, super::Texture>>, + { + let mut src_stages = vk::PipelineStageFlags::empty(); + let mut dst_stages = vk::PipelineStageFlags::empty(); + let vk_barriers = &mut self.temp.image_barriers; + vk_barriers.clear(); + + for bar in barriers { + let range = conv::map_subresource_range_combined_aspect( + &bar.range, + bar.texture.format, + &self.device.private_caps, + ); + let (src_stage, src_access) = conv::map_texture_usage_to_barrier(bar.usage.from); + let src_layout = conv::derive_image_layout(bar.usage.from, bar.texture.format); + src_stages |= src_stage; + let (dst_stage, dst_access) = conv::map_texture_usage_to_barrier(bar.usage.to); + let dst_layout = conv::derive_image_layout(bar.usage.to, bar.texture.format); + dst_stages |= dst_stage; + + vk_barriers.push( + vk::ImageMemoryBarrier::default() + .image(bar.texture.raw) + .subresource_range(range) + .src_access_mask(src_access) + .dst_access_mask(dst_access) + .old_layout(src_layout) + .new_layout(dst_layout), + ); + } + + if !vk_barriers.is_empty() { + unsafe { + self.device.raw.cmd_pipeline_barrier( + self.active, + src_stages, + dst_stages, + vk::DependencyFlags::empty(), + &[], + &[], + vk_barriers, + ) + }; + } + } + + unsafe fn clear_buffer(&mut self, buffer: &super::Buffer, range: crate::MemoryRange) { + let range_size = range.end - range.start; + if self.device.workarounds.contains( + super::Workarounds::FORCE_FILL_BUFFER_WITH_SIZE_GREATER_4096_ALIGNED_OFFSET_16, + ) && range_size >= 4096 + && !range.start.is_multiple_of(16) + { + let rounded_start = wgt::math::align_to(range.start, 16); + let prefix_size = rounded_start - range.start; + + unsafe { + self.device.raw.cmd_fill_buffer( + self.active, + buffer.raw, + range.start, + prefix_size, + 0, + ) + }; + + // This will never be zero, as rounding can only add up to 12 bytes, and the total size is 4096. + let suffix_size = range.end - rounded_start; + + unsafe { + self.device.raw.cmd_fill_buffer( + self.active, + buffer.raw, + rounded_start, + suffix_size, + 0, + ) + }; + } else { + unsafe { + self.device + .raw + .cmd_fill_buffer(self.active, buffer.raw, range.start, range_size, 0) + }; + } + } + + unsafe fn copy_buffer_to_buffer<T>( + &mut self, + src: &super::Buffer, + dst: &super::Buffer, + regions: T, + ) where + T: Iterator<Item = crate::BufferCopy>, + { + let vk_regions_iter = regions.map(|r| vk::BufferCopy { + src_offset: r.src_offset, + dst_offset: r.dst_offset, + size: r.size.get(), + }); + + unsafe { + self.device.raw.cmd_copy_buffer( + self.active, + src.raw, + dst.raw, + &smallvec::SmallVec::<[vk::BufferCopy; 32]>::from_iter(vk_regions_iter), + ) + }; + } + + unsafe fn copy_texture_to_texture<T>( + &mut self, + src: &super::Texture, + src_usage: wgt::TextureUses, + dst: &super::Texture, + regions: T, + ) where + T: Iterator<Item = crate::TextureCopy>, + { + let src_layout = conv::derive_image_layout(src_usage, src.format); + + let vk_regions_iter = regions.map(|r| { + let (src_subresource, src_offset) = conv::map_subresource_layers(&r.src_base); + let (dst_subresource, dst_offset) = conv::map_subresource_layers(&r.dst_base); + let extent = r + .size + .min(&r.src_base.max_copy_size(&src.copy_size)) + .min(&r.dst_base.max_copy_size(&dst.copy_size)); + vk::ImageCopy { + src_subresource, + src_offset, + dst_subresource, + dst_offset, + extent: conv::map_copy_extent(&extent), + } + }); + + unsafe { + self.device.raw.cmd_copy_image( + self.active, + src.raw, + src_layout, + dst.raw, + DST_IMAGE_LAYOUT, + &smallvec::SmallVec::<[vk::ImageCopy; 32]>::from_iter(vk_regions_iter), + ) + }; + } + + unsafe fn copy_buffer_to_texture<T>( + &mut self, + src: &super::Buffer, + dst: &super::Texture, + regions: T, + ) where + T: Iterator<Item = crate::BufferTextureCopy>, + { + let vk_regions_iter = dst.map_buffer_copies(regions); + + unsafe { + self.device.raw.cmd_copy_buffer_to_image( + self.active, + src.raw, + dst.raw, + DST_IMAGE_LAYOUT, + &smallvec::SmallVec::<[vk::BufferImageCopy; 32]>::from_iter(vk_regions_iter), + ) + }; + } + + unsafe fn copy_texture_to_buffer<T>( + &mut self, + src: &super::Texture, + src_usage: wgt::TextureUses, + dst: &super::Buffer, + regions: T, + ) where + T: Iterator<Item = crate::BufferTextureCopy>, + { + let src_layout = conv::derive_image_layout(src_usage, src.format); + let vk_regions_iter = src.map_buffer_copies(regions); + + unsafe { + self.device.raw.cmd_copy_image_to_buffer( + self.active, + src.raw, + src_layout, + dst.raw, + &smallvec::SmallVec::<[vk::BufferImageCopy; 32]>::from_iter(vk_regions_iter), + ) + }; + } + + unsafe fn begin_query(&mut self, set: &super::QuerySet, index: u32) { + unsafe { + self.device.raw.cmd_begin_query( + self.active, + set.raw, + index, + vk::QueryControlFlags::empty(), + ) + }; + } + unsafe fn end_query(&mut self, set: &super::QuerySet, index: u32) { + unsafe { self.device.raw.cmd_end_query(self.active, set.raw, index) }; + } + unsafe fn write_timestamp(&mut self, set: &super::QuerySet, index: u32) { + unsafe { + self.device.raw.cmd_write_timestamp( + self.active, + vk::PipelineStageFlags::BOTTOM_OF_PIPE, + set.raw, + index, + ) + }; + } + unsafe fn read_acceleration_structure_compact_size( + &mut self, + acceleration_structure: &super::AccelerationStructure, + buffer: &super::Buffer, + ) { + let ray_tracing_functions = self + .device + .extension_fns + .ray_tracing + .as_ref() + .expect("Feature `RAY_TRACING` not enabled"); + let query_pool = acceleration_structure + .compacted_size_query + .as_ref() + .unwrap(); + unsafe { + self.device + .raw + .cmd_reset_query_pool(self.active, *query_pool, 0, 1); + ray_tracing_functions + .acceleration_structure + .cmd_write_acceleration_structures_properties( + self.active, + &[acceleration_structure.raw], + vk::QueryType::ACCELERATION_STRUCTURE_COMPACTED_SIZE_KHR, + *query_pool, + 0, + ); + self.device.raw.cmd_copy_query_pool_results( + self.active, + *query_pool, + 0, + 1, + buffer.raw, + 0, + wgt::QUERY_SIZE as vk::DeviceSize, + vk::QueryResultFlags::TYPE_64 | vk::QueryResultFlags::WAIT, + ) + }; + } + unsafe fn reset_queries(&mut self, set: &super::QuerySet, range: Range<u32>) { + unsafe { + self.device.raw.cmd_reset_query_pool( + self.active, + set.raw, + range.start, + range.end - range.start, + ) + }; + } + unsafe fn copy_query_results( + &mut self, + set: &super::QuerySet, + range: Range<u32>, + buffer: &super::Buffer, + offset: wgt::BufferAddress, + stride: wgt::BufferSize, + ) { + unsafe { + self.device.raw.cmd_copy_query_pool_results( + self.active, + set.raw, + range.start, + range.end - range.start, + buffer.raw, + offset, + stride.get(), + vk::QueryResultFlags::TYPE_64 | vk::QueryResultFlags::WAIT, + ) + }; + } + + unsafe fn build_acceleration_structures<'a, T>(&mut self, descriptor_count: u32, descriptors: T) + where + super::Api: 'a, + T: IntoIterator< + Item = crate::BuildAccelerationStructureDescriptor< + 'a, + super::Buffer, + super::AccelerationStructure, + >, + >, + { + const CAPACITY_OUTER: usize = 8; + const CAPACITY_INNER: usize = 1; + let descriptor_count = descriptor_count as usize; + + let ray_tracing_functions = self + .device + .extension_fns + .ray_tracing + .as_ref() + .expect("Feature `RAY_TRACING` not enabled"); + + let get_device_address = |buffer: Option<&super::Buffer>| unsafe { + match buffer { + Some(buffer) => ray_tracing_functions + .buffer_device_address + .get_buffer_device_address( + &vk::BufferDeviceAddressInfo::default().buffer(buffer.raw), + ), + None => panic!("Buffers are required to build acceleration structures"), + } + }; + + // storage to all the data required for cmd_build_acceleration_structures + let mut ranges_storage = smallvec::SmallVec::< + [smallvec::SmallVec<[vk::AccelerationStructureBuildRangeInfoKHR; CAPACITY_INNER]>; + CAPACITY_OUTER], + >::with_capacity(descriptor_count); + let mut geometries_storage = smallvec::SmallVec::< + [smallvec::SmallVec<[vk::AccelerationStructureGeometryKHR; CAPACITY_INNER]>; + CAPACITY_OUTER], + >::with_capacity(descriptor_count); + + // pointers to all the data required for cmd_build_acceleration_structures + let mut geometry_infos = smallvec::SmallVec::< + [vk::AccelerationStructureBuildGeometryInfoKHR; CAPACITY_OUTER], + >::with_capacity(descriptor_count); + let mut ranges_ptrs = smallvec::SmallVec::< + [&[vk::AccelerationStructureBuildRangeInfoKHR]; CAPACITY_OUTER], + >::with_capacity(descriptor_count); + + for desc in descriptors { + let (geometries, ranges) = match *desc.entries { + crate::AccelerationStructureEntries::Instances(ref instances) => { + let instance_data = vk::AccelerationStructureGeometryInstancesDataKHR::default( + // TODO: Code is so large that rustfmt refuses to treat this... :( + ) + .data(vk::DeviceOrHostAddressConstKHR { + device_address: get_device_address(instances.buffer), + }); + + let geometry = vk::AccelerationStructureGeometryKHR::default() + .geometry_type(vk::GeometryTypeKHR::INSTANCES) + .geometry(vk::AccelerationStructureGeometryDataKHR { + instances: instance_data, + }); + + let range = vk::AccelerationStructureBuildRangeInfoKHR::default() + .primitive_count(instances.count) + .primitive_offset(instances.offset); + + (smallvec::smallvec![geometry], smallvec::smallvec![range]) + } + crate::AccelerationStructureEntries::Triangles(ref in_geometries) => { + let mut ranges = smallvec::SmallVec::< + [vk::AccelerationStructureBuildRangeInfoKHR; CAPACITY_INNER], + >::with_capacity(in_geometries.len()); + let mut geometries = smallvec::SmallVec::< + [vk::AccelerationStructureGeometryKHR; CAPACITY_INNER], + >::with_capacity(in_geometries.len()); + for triangles in in_geometries { + let mut triangle_data = + vk::AccelerationStructureGeometryTrianglesDataKHR::default() + // IndexType::NONE_KHR is not set by default (due to being provided by VK_KHR_acceleration_structure) but unless there is an + // index buffer we need to have IndexType::NONE_KHR as our index type. + .index_type(vk::IndexType::NONE_KHR) + .vertex_data(vk::DeviceOrHostAddressConstKHR { + device_address: get_device_address(triangles.vertex_buffer) + + (triangles.first_vertex as u64 * triangles.vertex_stride), + }) + .vertex_format(conv::map_vertex_format(triangles.vertex_format)) + .max_vertex(triangles.vertex_count) + .vertex_stride(triangles.vertex_stride); + + let mut range = vk::AccelerationStructureBuildRangeInfoKHR::default(); + + if let Some(ref indices) = triangles.indices { + triangle_data = triangle_data + .index_data(vk::DeviceOrHostAddressConstKHR { + device_address: get_device_address(indices.buffer), + }) + .index_type(conv::map_index_format(indices.format)); + + range = range + .primitive_count(indices.count / 3) + .primitive_offset(indices.offset); + } else { + range = range.primitive_count(triangles.vertex_count / 3); + } + + if let Some(ref transform) = triangles.transform { + let transform_device_address = unsafe { + ray_tracing_functions + .buffer_device_address + .get_buffer_device_address( + &vk::BufferDeviceAddressInfo::default() + .buffer(transform.buffer.raw), + ) + }; + triangle_data = + triangle_data.transform_data(vk::DeviceOrHostAddressConstKHR { + device_address: transform_device_address, + }); + + range = range.transform_offset(transform.offset); + } + + let geometry = vk::AccelerationStructureGeometryKHR::default() + .geometry_type(vk::GeometryTypeKHR::TRIANGLES) + .geometry(vk::AccelerationStructureGeometryDataKHR { + triangles: triangle_data, + }) + .flags(conv::map_acceleration_structure_geometry_flags( + triangles.flags, + )); + + geometries.push(geometry); + ranges.push(range); + } + (geometries, ranges) + } + crate::AccelerationStructureEntries::AABBs(ref in_geometries) => { + let mut ranges = smallvec::SmallVec::< + [vk::AccelerationStructureBuildRangeInfoKHR; CAPACITY_INNER], + >::with_capacity(in_geometries.len()); + let mut geometries = smallvec::SmallVec::< + [vk::AccelerationStructureGeometryKHR; CAPACITY_INNER], + >::with_capacity(in_geometries.len()); + for aabb in in_geometries { + let aabbs_data = vk::AccelerationStructureGeometryAabbsDataKHR::default() + .data(vk::DeviceOrHostAddressConstKHR { + device_address: get_device_address(aabb.buffer), + }) + .stride(aabb.stride); + + let range = vk::AccelerationStructureBuildRangeInfoKHR::default() + .primitive_count(aabb.count) + .primitive_offset(aabb.offset); + + let geometry = vk::AccelerationStructureGeometryKHR::default() + .geometry_type(vk::GeometryTypeKHR::AABBS) + .geometry(vk::AccelerationStructureGeometryDataKHR { + aabbs: aabbs_data, + }) + .flags(conv::map_acceleration_structure_geometry_flags(aabb.flags)); + + geometries.push(geometry); + ranges.push(range); + } + (geometries, ranges) + } + }; + + ranges_storage.push(ranges); + geometries_storage.push(geometries); + + let scratch_device_address = unsafe { + ray_tracing_functions + .buffer_device_address + .get_buffer_device_address( + &vk::BufferDeviceAddressInfo::default().buffer(desc.scratch_buffer.raw), + ) + }; + let ty = match *desc.entries { + crate::AccelerationStructureEntries::Instances(_) => { + vk::AccelerationStructureTypeKHR::TOP_LEVEL + } + _ => vk::AccelerationStructureTypeKHR::BOTTOM_LEVEL, + }; + let mut geometry_info = vk::AccelerationStructureBuildGeometryInfoKHR::default() + .ty(ty) + .mode(conv::map_acceleration_structure_build_mode(desc.mode)) + .flags(conv::map_acceleration_structure_flags(desc.flags)) + .dst_acceleration_structure(desc.destination_acceleration_structure.raw) + .scratch_data(vk::DeviceOrHostAddressKHR { + device_address: scratch_device_address + desc.scratch_buffer_offset, + }); + + if desc.mode == crate::AccelerationStructureBuildMode::Update { + geometry_info.src_acceleration_structure = desc + .source_acceleration_structure + .unwrap_or(desc.destination_acceleration_structure) + .raw; + } + + geometry_infos.push(geometry_info); + } + + for (i, geometry_info) in geometry_infos.iter_mut().enumerate() { + geometry_info.geometry_count = geometries_storage[i].len() as u32; + geometry_info.p_geometries = geometries_storage[i].as_ptr(); + ranges_ptrs.push(&ranges_storage[i]); + } + + unsafe { + ray_tracing_functions + .acceleration_structure + .cmd_build_acceleration_structures(self.active, &geometry_infos, &ranges_ptrs); + } + } + + unsafe fn place_acceleration_structure_barrier( + &mut self, + barrier: crate::AccelerationStructureBarrier, + ) { + let (src_stage, src_access) = conv::map_acceleration_structure_usage_to_barrier( + barrier.usage.from, + self.device.features, + ); + let (dst_stage, dst_access) = conv::map_acceleration_structure_usage_to_barrier( + barrier.usage.to, + self.device.features, + ); + + unsafe { + self.device.raw.cmd_pipeline_barrier( + self.active, + src_stage | vk::PipelineStageFlags::TOP_OF_PIPE, + dst_stage | vk::PipelineStageFlags::BOTTOM_OF_PIPE, + vk::DependencyFlags::empty(), + &[vk::MemoryBarrier::default() + .src_access_mask(src_access) + .dst_access_mask(dst_access)], + &[], + &[], + ) + }; + } + + unsafe fn set_acceleration_structure_dependencies( + _command_buffers: &[&super::CommandBuffer], + _dependencies: &[&super::AccelerationStructure], + ) { + } + // render + + unsafe fn begin_render_pass( + &mut self, + desc: &crate::RenderPassDescriptor<super::QuerySet, super::TextureView>, + ) -> Result<(), crate::DeviceError> { + let mut vk_clear_values = + ArrayVec::<vk::ClearValue, { super::MAX_TOTAL_ATTACHMENTS }>::new(); + let mut rp_key = super::RenderPassKey { + colors: ArrayVec::default(), + depth_stencil: None, + sample_count: desc.sample_count, + multiview_mask: desc.multiview_mask, + }; + let mut fb_key = super::FramebufferKey { + raw_pass: vk::RenderPass::null(), + attachment_views: ArrayVec::default(), + attachment_identities: ArrayVec::default(), + extent: desc.extent, + }; + + for cat in desc.color_attachments { + if let Some(cat) = cat.as_ref() { + let color_view = if cat.target.view.dimension == wgt::TextureViewDimension::D3 { + let key = super::TempTextureViewKey { + texture: cat.target.view.raw_texture, + texture_identity: cat.target.view.texture_identity, + format: cat.target.view.raw_format, + mip_level: cat.target.view.base_mip_level, + depth_slice: cat.depth_slice.unwrap(), + }; + self.make_temp_texture_view(key)? + } else { + cat.target.view.identified_raw_view() + }; + + vk_clear_values.push(vk::ClearValue { + color: unsafe { cat.make_vk_clear_color() }, + }); + let color = super::ColorAttachmentKey { + base: cat.target.make_attachment_key(cat.ops), + resolve: cat.resolve_target.as_ref().map(|target| { + target.make_attachment_key( + crate::AttachmentOps::LOAD_CLEAR | crate::AttachmentOps::STORE, + ) + }), + }; + + rp_key.colors.push(Some(color)); + fb_key.push_view(color_view); + if let Some(ref at) = cat.resolve_target { + vk_clear_values.push(unsafe { mem::zeroed() }); + fb_key.push_view(at.view.identified_raw_view()); + } + } else { + rp_key.colors.push(None); + } + } + if let Some(ref ds) = desc.depth_stencil_attachment { + vk_clear_values.push(vk::ClearValue { + depth_stencil: vk::ClearDepthStencilValue { + depth: ds.clear_value.0, + stencil: ds.clear_value.1, + }, + }); + rp_key.depth_stencil = Some(super::DepthStencilAttachmentKey { + base: ds.target.make_attachment_key(ds.depth_ops), + stencil_ops: ds.stencil_ops, + }); + fb_key.push_view(ds.target.view.identified_raw_view()); + } + + let render_area = vk::Rect2D { + offset: vk::Offset2D { x: 0, y: 0 }, + extent: vk::Extent2D { + width: desc.extent.width, + height: desc.extent.height, + }, + }; + let vk_viewports = [vk::Viewport { + x: 0.0, + y: desc.extent.height as f32, + width: desc.extent.width as f32, + height: -(desc.extent.height as f32), + min_depth: 0.0, + max_depth: 1.0, + }]; + + let raw_pass = self.device.make_render_pass(rp_key).unwrap(); + fb_key.raw_pass = raw_pass; + let raw_framebuffer = self.make_framebuffer(fb_key).unwrap(); + + let vk_info = vk::RenderPassBeginInfo::default() + .render_pass(raw_pass) + .render_area(render_area) + .clear_values(&vk_clear_values) + .framebuffer(raw_framebuffer); + + if let Some(label) = desc.label { + unsafe { self.begin_debug_marker(label) }; + self.rpass_debug_marker_active = true; + } + + // Start timestamp if any (before all other commands but after debug marker) + if let Some(timestamp_writes) = desc.timestamp_writes.as_ref() { + if let Some(index) = timestamp_writes.beginning_of_pass_write_index { + unsafe { + self.write_timestamp(timestamp_writes.query_set, index); + } + } + self.end_of_pass_timer_query = timestamp_writes + .end_of_pass_write_index + .map(|index| (timestamp_writes.query_set.raw, index)); + } + + unsafe { + self.device + .raw + .cmd_set_viewport(self.active, 0, &vk_viewports); + self.device + .raw + .cmd_set_scissor(self.active, 0, &[render_area]); + self.device.raw.cmd_begin_render_pass( + self.active, + &vk_info, + vk::SubpassContents::INLINE, + ); + }; + + self.bind_point = vk::PipelineBindPoint::GRAPHICS; + + Ok(()) + } + unsafe fn end_render_pass(&mut self) { + unsafe { + self.device.raw.cmd_end_render_pass(self.active); + } + + // After all other commands but before debug marker, so this is still seen as part of this pass. + self.write_pass_end_timestamp_if_requested(); + + if self.rpass_debug_marker_active { + unsafe { + self.end_debug_marker(); + } + self.rpass_debug_marker_active = false; + } + } + + unsafe fn set_bind_group( + &mut self, + layout: &super::PipelineLayout, + index: u32, + group: &super::BindGroup, + dynamic_offsets: &[wgt::DynamicOffset], + ) { + let sets = [group.set.raw()]; + unsafe { + self.device.raw.cmd_bind_descriptor_sets( + self.active, + self.bind_point, + layout.raw, + index, + &sets, + dynamic_offsets, + ) + }; + } + unsafe fn set_immediates( + &mut self, + layout: &super::PipelineLayout, + offset_bytes: u32, + data: &[u32], + ) { + unsafe { + self.device.raw.cmd_push_constants( + self.active, + layout.raw, + vk::ShaderStageFlags::ALL, + offset_bytes, + bytemuck::cast_slice(data), + ) + }; + } + + unsafe fn insert_debug_marker(&mut self, label: &str) { + if let Some(ext) = self.device.extension_fns.debug_utils.as_ref() { + let cstr = self.temp.make_c_str(label); + let vk_label = vk::DebugUtilsLabelEXT::default().label_name(cstr); + unsafe { ext.cmd_insert_debug_utils_label(self.active, &vk_label) }; + } + } + unsafe fn begin_debug_marker(&mut self, group_label: &str) { + if let Some(ext) = self.device.extension_fns.debug_utils.as_ref() { + let cstr = self.temp.make_c_str(group_label); + let vk_label = vk::DebugUtilsLabelEXT::default().label_name(cstr); + unsafe { ext.cmd_begin_debug_utils_label(self.active, &vk_label) }; + } + } + unsafe fn end_debug_marker(&mut self) { + if let Some(ext) = self.device.extension_fns.debug_utils.as_ref() { + unsafe { ext.cmd_end_debug_utils_label(self.active) }; + } + } + + unsafe fn set_render_pipeline(&mut self, pipeline: &super::RenderPipeline) { + unsafe { + self.current_pipeline_is_multiview = pipeline.is_multiview; + self.device.raw.cmd_bind_pipeline( + self.active, + vk::PipelineBindPoint::GRAPHICS, + pipeline.raw, + ) + }; + } + + unsafe fn set_index_buffer<'a>( + &mut self, + binding: crate::BufferBinding<'a, super::Buffer>, + format: wgt::IndexFormat, + ) { + unsafe { + self.device.raw.cmd_bind_index_buffer( + self.active, + binding.buffer.raw, + binding.offset, + conv::map_index_format(format), + ) + }; + } + unsafe fn set_vertex_buffer<'a>( + &mut self, + index: u32, + binding: crate::BufferBinding<'a, super::Buffer>, + ) { + let vk_buffers = [binding.buffer.raw]; + let vk_offsets = [binding.offset]; + unsafe { + self.device + .raw + .cmd_bind_vertex_buffers(self.active, index, &vk_buffers, &vk_offsets) + }; + } + unsafe fn set_viewport(&mut self, rect: &crate::Rect<f32>, depth_range: Range<f32>) { + let vk_viewports = [vk::Viewport { + x: rect.x, + y: rect.y + rect.h, + width: rect.w, + height: -rect.h, // flip Y + min_depth: depth_range.start, + max_depth: depth_range.end, + }]; + unsafe { + self.device + .raw + .cmd_set_viewport(self.active, 0, &vk_viewports) + }; + } + unsafe fn set_scissor_rect(&mut self, rect: &crate::Rect<u32>) { + let vk_scissors = [vk::Rect2D { + offset: vk::Offset2D { + x: rect.x as i32, + y: rect.y as i32, + }, + extent: vk::Extent2D { + width: rect.w, + height: rect.h, + }, + }]; + unsafe { + self.device + .raw + .cmd_set_scissor(self.active, 0, &vk_scissors) + }; + } + unsafe fn set_stencil_reference(&mut self, value: u32) { + unsafe { + self.device.raw.cmd_set_stencil_reference( + self.active, + vk::StencilFaceFlags::FRONT_AND_BACK, + value, + ) + }; + } + unsafe fn set_blend_constants(&mut self, color: &[f32; 4]) { + unsafe { self.device.raw.cmd_set_blend_constants(self.active, color) }; + } + + unsafe fn draw( + &mut self, + first_vertex: u32, + vertex_count: u32, + first_instance: u32, + instance_count: u32, + ) { + if self.current_pipeline_is_multiview + && (first_instance as u64 + instance_count as u64 - 1) + > self.device.private_caps.multiview_instance_index_limit as u64 + { + panic!("This vulkan device is affected by [#8333](https://github.com/gfx-rs/wgpu/issues/8333)"); + } + unsafe { + self.device.raw.cmd_draw( + self.active, + vertex_count, + instance_count, + first_vertex, + first_instance, + ) + }; + } + unsafe fn draw_indexed( + &mut self, + first_index: u32, + index_count: u32, + base_vertex: i32, + first_instance: u32, + instance_count: u32, + ) { + if self.current_pipeline_is_multiview + && (first_instance as u64 + instance_count as u64 - 1) + > self.device.private_caps.multiview_instance_index_limit as u64 + { + panic!("This vulkan device is affected by [#8333](https://github.com/gfx-rs/wgpu/issues/8333)"); + } + unsafe { + self.device.raw.cmd_draw_indexed( + self.active, + index_count, + instance_count, + first_index, + base_vertex, + first_instance, + ) + }; + } + unsafe fn draw_mesh_tasks( + &mut self, + group_count_x: u32, + group_count_y: u32, + group_count_z: u32, + ) { + if let Some(ref t) = self.device.extension_fns.mesh_shading { + unsafe { + t.cmd_draw_mesh_tasks(self.active, group_count_x, group_count_y, group_count_z); + }; + } else { + panic!("Feature `MESH_SHADING` not enabled"); + } + } + unsafe fn draw_indirect( + &mut self, + buffer: &super::Buffer, + offset: wgt::BufferAddress, + draw_count: u32, + ) { + if draw_count >= 1 + && self.device.private_caps.multi_draw_indirect + && draw_count <= self.device.private_caps.max_draw_indirect_count + { + unsafe { + self.device.raw.cmd_draw_indirect( + self.active, + buffer.raw, + offset, + draw_count, + size_of::<wgt::DrawIndirectArgs>() as u32, + ) + }; + } else { + for i in 0..draw_count { + let indirect_offset = offset + + i as wgt::BufferAddress + * size_of::<wgt::DrawIndirectArgs>() as wgt::BufferAddress; + unsafe { + self.device.raw.cmd_draw_indirect( + self.active, + buffer.raw, + indirect_offset, + 1, + size_of::<wgt::DrawIndirectArgs>() as u32, + ) + }; + } + } + } + unsafe fn draw_indexed_indirect( + &mut self, + buffer: &super::Buffer, + offset: wgt::BufferAddress, + draw_count: u32, + ) { + if draw_count >= 1 + && self.device.private_caps.multi_draw_indirect + && draw_count <= self.device.private_caps.max_draw_indirect_count + { + unsafe { + self.device.raw.cmd_draw_indexed_indirect( + self.active, + buffer.raw, + offset, + draw_count, + size_of::<wgt::DrawIndexedIndirectArgs>() as u32, + ) + }; + } else { + for i in 0..draw_count { + let indirect_offset = offset + + i as wgt::BufferAddress + * size_of::<wgt::DrawIndexedIndirectArgs>() as wgt::BufferAddress; + unsafe { + self.device.raw.cmd_draw_indexed_indirect( + self.active, + buffer.raw, + indirect_offset, + 1, + size_of::<wgt::DrawIndexedIndirectArgs>() as u32, + ) + }; + } + } + } + unsafe fn draw_mesh_tasks_indirect( + &mut self, + buffer: &<Self::A as crate::Api>::Buffer, + offset: wgt::BufferAddress, + draw_count: u32, + ) { + if let Some(ref t) = self.device.extension_fns.mesh_shading { + unsafe { + t.cmd_draw_mesh_tasks_indirect( + self.active, + buffer.raw, + offset, + draw_count, + size_of::<wgt::DispatchIndirectArgs>() as u32, + ); + }; + } else { + panic!("Feature `MESH_SHADING` not enabled"); + } + } + unsafe fn draw_indirect_count( + &mut self, + buffer: &super::Buffer, + offset: wgt::BufferAddress, + count_buffer: &super::Buffer, + count_offset: wgt::BufferAddress, + max_count: u32, + ) { + let stride = size_of::<wgt::DrawIndirectArgs>() as u32; + match self.device.extension_fns.draw_indirect_count { + Some(ref t) => { + unsafe { + t.cmd_draw_indirect_count( + self.active, + buffer.raw, + offset, + count_buffer.raw, + count_offset, + max_count, + stride, + ) + }; + } + None => panic!("Feature `DRAW_INDIRECT_COUNT` not enabled"), + } + } + unsafe fn draw_indexed_indirect_count( + &mut self, + buffer: &super::Buffer, + offset: wgt::BufferAddress, + count_buffer: &super::Buffer, + count_offset: wgt::BufferAddress, + max_count: u32, + ) { + let stride = size_of::<wgt::DrawIndexedIndirectArgs>() as u32; + match self.device.extension_fns.draw_indirect_count { + Some(ref t) => { + unsafe { + t.cmd_draw_indexed_indirect_count( + self.active, + buffer.raw, + offset, + count_buffer.raw, + count_offset, + max_count, + stride, + ) + }; + } + None => panic!("Feature `DRAW_INDIRECT_COUNT` not enabled"), + } + } + unsafe fn draw_mesh_tasks_indirect_count( + &mut self, + buffer: &<Self::A as crate::Api>::Buffer, + offset: wgt::BufferAddress, + count_buffer: &super::Buffer, + count_offset: wgt::BufferAddress, + max_count: u32, + ) { + if self.device.extension_fns.draw_indirect_count.is_none() { + panic!("Feature `DRAW_INDIRECT_COUNT` not enabled"); + } + if let Some(ref t) = self.device.extension_fns.mesh_shading { + unsafe { + t.cmd_draw_mesh_tasks_indirect_count( + self.active, + buffer.raw, + offset, + count_buffer.raw, + count_offset, + max_count, + size_of::<wgt::DispatchIndirectArgs>() as u32, + ); + }; + } else { + panic!("Feature `MESH_SHADING` not enabled"); + } + } + + // compute + + unsafe fn begin_compute_pass( + &mut self, + desc: &crate::ComputePassDescriptor<'_, super::QuerySet>, + ) { + self.bind_point = vk::PipelineBindPoint::COMPUTE; + if let Some(label) = desc.label { + unsafe { self.begin_debug_marker(label) }; + self.rpass_debug_marker_active = true; + } + + if let Some(timestamp_writes) = desc.timestamp_writes.as_ref() { + if let Some(index) = timestamp_writes.beginning_of_pass_write_index { + unsafe { + self.write_timestamp(timestamp_writes.query_set, index); + } + } + self.end_of_pass_timer_query = timestamp_writes + .end_of_pass_write_index + .map(|index| (timestamp_writes.query_set.raw, index)); + } + } + unsafe fn end_compute_pass(&mut self) { + self.write_pass_end_timestamp_if_requested(); + + if self.rpass_debug_marker_active { + unsafe { self.end_debug_marker() }; + self.rpass_debug_marker_active = false + } + } + + unsafe fn set_compute_pipeline(&mut self, pipeline: &super::ComputePipeline) { + unsafe { + self.device.raw.cmd_bind_pipeline( + self.active, + vk::PipelineBindPoint::COMPUTE, + pipeline.raw, + ) + }; + } + + unsafe fn dispatch_workgroups(&mut self, count: [u32; 3]) { + unsafe { + self.device + .raw + .cmd_dispatch(self.active, count[0], count[1], count[2]) + }; + } + unsafe fn dispatch_workgroups_indirect( + &mut self, + buffer: &super::Buffer, + offset: wgt::BufferAddress, + ) { + unsafe { + self.device + .raw + .cmd_dispatch_indirect(self.active, buffer.raw, offset) + } + } + + // ray tracing + + unsafe fn begin_ray_tracing_pass(&mut self, desc: &crate::RayTracingPassDescriptor<'_>) { + self.bind_point = vk::PipelineBindPoint::RAY_TRACING_KHR; + if let Some(label) = desc.label { + unsafe { self.begin_debug_marker(label) }; + self.rpass_debug_marker_active = true; + } + } + unsafe fn end_ray_tracing_pass(&mut self) { + if self.rpass_debug_marker_active { + unsafe { self.end_debug_marker() }; + self.rpass_debug_marker_active = false + } + } + + unsafe fn trace_rays( + &mut self, + count: [u32; 3], + ray_generation_group_data: crate::PipelineGroupData<super::Buffer>, + miss_group_data: crate::PipelineGroupData<super::Buffer>, + intersection_group_data: crate::PipelineGroupData<super::Buffer>, + ) { + let ray_tracing_functions = self + .device + .extension_fns + .ray_tracing + .as_ref() + .expect("Feature `EXPERIMENTAL_RAY_TRACING` not enabled"); + + let ray_tracing_pipeline_functions = self + .device + .extension_fns + .ray_tracing_pipelines + .as_ref() + .expect("Feature `EXPERIMENTAL_RAY_TRACING_PIPELINES` not enabled"); + + let get_device_address = |buffer: &super::Buffer| unsafe { + ray_tracing_functions + .buffer_device_address + .get_buffer_device_address( + &vk::BufferDeviceAddressInfo::default().buffer(buffer.raw), + ) + }; + + unsafe { + ray_tracing_pipeline_functions.cmd_trace_rays( + self.raw_handle(), + &vk::StridedDeviceAddressRegionKHR { + device_address: get_device_address(ray_generation_group_data.buffer) + + ray_generation_group_data.offset, + stride: ray_generation_group_data.stride, + size: ray_generation_group_data.stride /* no need for multiplying by count, vulkan requires the ray gen sbt to be just one group */, + }, + &vk::StridedDeviceAddressRegionKHR { + device_address: get_device_address(miss_group_data.buffer) + + miss_group_data.offset, + stride: miss_group_data.stride, + size: miss_group_data.stride * miss_group_data.count, + }, + &vk::StridedDeviceAddressRegionKHR { + device_address: get_device_address(intersection_group_data.buffer) + + intersection_group_data.offset, + stride: intersection_group_data.stride, + size: intersection_group_data.stride * intersection_group_data.count, + }, + &vk::StridedDeviceAddressRegionKHR { + device_address: 0, + stride: 0, + size: 0, + }, + count[0], + count[1], + count[2], + ) + }; + } + + unsafe fn set_ray_tracing_pipeline(&mut self, pipeline: &super::RayTracingPipeline) { + unsafe { + self.device.raw.cmd_bind_pipeline( + self.active, + vk::PipelineBindPoint::RAY_TRACING_KHR, + pipeline.raw, + ) + }; + } + + unsafe fn copy_acceleration_structure_to_acceleration_structure( + &mut self, + src: &super::AccelerationStructure, + dst: &super::AccelerationStructure, + copy: wgt::AccelerationStructureCopy, + ) { + let ray_tracing_functions = self + .device + .extension_fns + .ray_tracing + .as_ref() + .expect("Feature `RAY_TRACING` not enabled"); + + let mode = match copy { + wgt::AccelerationStructureCopy::Clone => vk::CopyAccelerationStructureModeKHR::CLONE, + wgt::AccelerationStructureCopy::Compact => { + vk::CopyAccelerationStructureModeKHR::COMPACT + } + }; + + unsafe { + ray_tracing_functions + .acceleration_structure + .cmd_copy_acceleration_structure( + self.active, + &vk::CopyAccelerationStructureInfoKHR { + s_type: vk::StructureType::COPY_ACCELERATION_STRUCTURE_INFO_KHR, + p_next: core::ptr::null(), + src: src.raw, + dst: dst.raw, + mode, + _marker: Default::default(), + }, + ); + } + } +} + +#[test] +fn check_dst_image_layout() { + assert_eq!( + conv::derive_image_layout(wgt::TextureUses::COPY_DST, wgt::TextureFormat::Rgba8Unorm), + DST_IMAGE_LAYOUT + ); +} diff --git a/app/vendor/rune/vendor/wgpu-hal/src/vulkan/conv.rs b/app/vendor/rune/vendor/wgpu-hal/src/vulkan/conv.rs new file mode 100644 index 0000000..47bdf49 --- /dev/null +++ b/app/vendor/rune/vendor/wgpu-hal/src/vulkan/conv.rs @@ -0,0 +1,1136 @@ +use alloc::vec::Vec; + +use ash::vk; + +impl super::PrivateCapabilities { + pub fn map_texture_format(&self, format: wgt::TextureFormat) -> vk::Format { + use ash::vk::Format as F; + use wgt::TextureFormat as Tf; + use wgt::{AstcBlock, AstcChannel}; + match format { + Tf::R8Unorm => F::R8_UNORM, + Tf::R8Snorm => F::R8_SNORM, + Tf::R8Uint => F::R8_UINT, + Tf::R8Sint => F::R8_SINT, + Tf::R16Uint => F::R16_UINT, + Tf::R16Sint => F::R16_SINT, + Tf::R16Unorm => F::R16_UNORM, + Tf::R16Snorm => F::R16_SNORM, + Tf::R16Float => F::R16_SFLOAT, + Tf::Rg8Unorm => F::R8G8_UNORM, + Tf::Rg8Snorm => F::R8G8_SNORM, + Tf::Rg8Uint => F::R8G8_UINT, + Tf::Rg8Sint => F::R8G8_SINT, + Tf::Rg16Unorm => F::R16G16_UNORM, + Tf::Rg16Snorm => F::R16G16_SNORM, + Tf::R32Uint => F::R32_UINT, + Tf::R32Sint => F::R32_SINT, + Tf::R32Float => F::R32_SFLOAT, + Tf::Rg16Uint => F::R16G16_UINT, + Tf::Rg16Sint => F::R16G16_SINT, + Tf::Rg16Float => F::R16G16_SFLOAT, + Tf::Rgba8Unorm => F::R8G8B8A8_UNORM, + Tf::Rgba8UnormSrgb => F::R8G8B8A8_SRGB, + Tf::Bgra8UnormSrgb => F::B8G8R8A8_SRGB, + Tf::Rgba8Snorm => F::R8G8B8A8_SNORM, + Tf::Bgra8Unorm => F::B8G8R8A8_UNORM, + Tf::Rgba8Uint => F::R8G8B8A8_UINT, + Tf::Rgba8Sint => F::R8G8B8A8_SINT, + Tf::Rgb10a2Uint => F::A2B10G10R10_UINT_PACK32, + Tf::Rgb10a2Unorm => F::A2B10G10R10_UNORM_PACK32, + Tf::Rg11b10Ufloat => F::B10G11R11_UFLOAT_PACK32, + Tf::R64Uint => F::R64_UINT, + Tf::Rg32Uint => F::R32G32_UINT, + Tf::Rg32Sint => F::R32G32_SINT, + Tf::Rg32Float => F::R32G32_SFLOAT, + Tf::Rgba16Uint => F::R16G16B16A16_UINT, + Tf::Rgba16Sint => F::R16G16B16A16_SINT, + Tf::Rgba16Unorm => F::R16G16B16A16_UNORM, + Tf::Rgba16Snorm => F::R16G16B16A16_SNORM, + Tf::Rgba16Float => F::R16G16B16A16_SFLOAT, + Tf::Rgba32Uint => F::R32G32B32A32_UINT, + Tf::Rgba32Sint => F::R32G32B32A32_SINT, + Tf::Rgba32Float => F::R32G32B32A32_SFLOAT, + Tf::Depth32Float => F::D32_SFLOAT, + Tf::Depth32FloatStencil8 => F::D32_SFLOAT_S8_UINT, + Tf::Depth24Plus => { + if self.texture_d24 { + F::X8_D24_UNORM_PACK32 + } else { + F::D32_SFLOAT + } + } + Tf::Depth24PlusStencil8 => { + if self.texture_d24_s8 { + F::D24_UNORM_S8_UINT + } else { + F::D32_SFLOAT_S8_UINT + } + } + Tf::Stencil8 => { + if self.texture_s8 { + F::S8_UINT + } else if self.texture_d24_s8 { + F::D24_UNORM_S8_UINT + } else { + F::D32_SFLOAT_S8_UINT + } + } + Tf::Depth16Unorm => F::D16_UNORM, + Tf::NV12 => F::G8_B8R8_2PLANE_420_UNORM, + Tf::P010 => F::G10X6_B10X6R10X6_2PLANE_420_UNORM_3PACK16, + Tf::Rgb9e5Ufloat => F::E5B9G9R9_UFLOAT_PACK32, + Tf::Bc1RgbaUnorm => F::BC1_RGBA_UNORM_BLOCK, + Tf::Bc1RgbaUnormSrgb => F::BC1_RGBA_SRGB_BLOCK, + Tf::Bc2RgbaUnorm => F::BC2_UNORM_BLOCK, + Tf::Bc2RgbaUnormSrgb => F::BC2_SRGB_BLOCK, + Tf::Bc3RgbaUnorm => F::BC3_UNORM_BLOCK, + Tf::Bc3RgbaUnormSrgb => F::BC3_SRGB_BLOCK, + Tf::Bc4RUnorm => F::BC4_UNORM_BLOCK, + Tf::Bc4RSnorm => F::BC4_SNORM_BLOCK, + Tf::Bc5RgUnorm => F::BC5_UNORM_BLOCK, + Tf::Bc5RgSnorm => F::BC5_SNORM_BLOCK, + Tf::Bc6hRgbUfloat => F::BC6H_UFLOAT_BLOCK, + Tf::Bc6hRgbFloat => F::BC6H_SFLOAT_BLOCK, + Tf::Bc7RgbaUnorm => F::BC7_UNORM_BLOCK, + Tf::Bc7RgbaUnormSrgb => F::BC7_SRGB_BLOCK, + Tf::Etc2Rgb8Unorm => F::ETC2_R8G8B8_UNORM_BLOCK, + Tf::Etc2Rgb8UnormSrgb => F::ETC2_R8G8B8_SRGB_BLOCK, + Tf::Etc2Rgb8A1Unorm => F::ETC2_R8G8B8A1_UNORM_BLOCK, + Tf::Etc2Rgb8A1UnormSrgb => F::ETC2_R8G8B8A1_SRGB_BLOCK, + Tf::Etc2Rgba8Unorm => F::ETC2_R8G8B8A8_UNORM_BLOCK, + Tf::Etc2Rgba8UnormSrgb => F::ETC2_R8G8B8A8_SRGB_BLOCK, + Tf::EacR11Unorm => F::EAC_R11_UNORM_BLOCK, + Tf::EacR11Snorm => F::EAC_R11_SNORM_BLOCK, + Tf::EacRg11Unorm => F::EAC_R11G11_UNORM_BLOCK, + Tf::EacRg11Snorm => F::EAC_R11G11_SNORM_BLOCK, + Tf::Astc { block, channel } => match channel { + AstcChannel::Unorm => match block { + AstcBlock::B4x4 => F::ASTC_4X4_UNORM_BLOCK, + AstcBlock::B5x4 => F::ASTC_5X4_UNORM_BLOCK, + AstcBlock::B5x5 => F::ASTC_5X5_UNORM_BLOCK, + AstcBlock::B6x5 => F::ASTC_6X5_UNORM_BLOCK, + AstcBlock::B6x6 => F::ASTC_6X6_UNORM_BLOCK, + AstcBlock::B8x5 => F::ASTC_8X5_UNORM_BLOCK, + AstcBlock::B8x6 => F::ASTC_8X6_UNORM_BLOCK, + AstcBlock::B8x8 => F::ASTC_8X8_UNORM_BLOCK, + AstcBlock::B10x5 => F::ASTC_10X5_UNORM_BLOCK, + AstcBlock::B10x6 => F::ASTC_10X6_UNORM_BLOCK, + AstcBlock::B10x8 => F::ASTC_10X8_UNORM_BLOCK, + AstcBlock::B10x10 => F::ASTC_10X10_UNORM_BLOCK, + AstcBlock::B12x10 => F::ASTC_12X10_UNORM_BLOCK, + AstcBlock::B12x12 => F::ASTC_12X12_UNORM_BLOCK, + }, + AstcChannel::UnormSrgb => match block { + AstcBlock::B4x4 => F::ASTC_4X4_SRGB_BLOCK, + AstcBlock::B5x4 => F::ASTC_5X4_SRGB_BLOCK, + AstcBlock::B5x5 => F::ASTC_5X5_SRGB_BLOCK, + AstcBlock::B6x5 => F::ASTC_6X5_SRGB_BLOCK, + AstcBlock::B6x6 => F::ASTC_6X6_SRGB_BLOCK, + AstcBlock::B8x5 => F::ASTC_8X5_SRGB_BLOCK, + AstcBlock::B8x6 => F::ASTC_8X6_SRGB_BLOCK, + AstcBlock::B8x8 => F::ASTC_8X8_SRGB_BLOCK, + AstcBlock::B10x5 => F::ASTC_10X5_SRGB_BLOCK, + AstcBlock::B10x6 => F::ASTC_10X6_SRGB_BLOCK, + AstcBlock::B10x8 => F::ASTC_10X8_SRGB_BLOCK, + AstcBlock::B10x10 => F::ASTC_10X10_SRGB_BLOCK, + AstcBlock::B12x10 => F::ASTC_12X10_SRGB_BLOCK, + AstcBlock::B12x12 => F::ASTC_12X12_SRGB_BLOCK, + }, + AstcChannel::Hdr => match block { + AstcBlock::B4x4 => F::ASTC_4X4_SFLOAT_BLOCK_EXT, + AstcBlock::B5x4 => F::ASTC_5X4_SFLOAT_BLOCK_EXT, + AstcBlock::B5x5 => F::ASTC_5X5_SFLOAT_BLOCK_EXT, + AstcBlock::B6x5 => F::ASTC_6X5_SFLOAT_BLOCK_EXT, + AstcBlock::B6x6 => F::ASTC_6X6_SFLOAT_BLOCK_EXT, + AstcBlock::B8x5 => F::ASTC_8X5_SFLOAT_BLOCK_EXT, + AstcBlock::B8x6 => F::ASTC_8X6_SFLOAT_BLOCK_EXT, + AstcBlock::B8x8 => F::ASTC_8X8_SFLOAT_BLOCK_EXT, + AstcBlock::B10x5 => F::ASTC_10X5_SFLOAT_BLOCK_EXT, + AstcBlock::B10x6 => F::ASTC_10X6_SFLOAT_BLOCK_EXT, + AstcBlock::B10x8 => F::ASTC_10X8_SFLOAT_BLOCK_EXT, + AstcBlock::B10x10 => F::ASTC_10X10_SFLOAT_BLOCK_EXT, + AstcBlock::B12x10 => F::ASTC_12X10_SFLOAT_BLOCK_EXT, + AstcBlock::B12x12 => F::ASTC_12X12_SFLOAT_BLOCK_EXT, + }, + }, + } + } +} + +pub fn map_vk_surface_formats( + sf: vk::SurfaceFormatKHR, +) -> Option<(wgt::TextureFormat, wgt::SurfaceColorSpace)> { + use ash::vk::Format as F; + use wgt::TextureFormat as Tf; + // Format list we care about pulled from https://vulkan.gpuinfo.org/listsurfaceformats.php. + let format = match sf.format { + F::B8G8R8A8_UNORM => Tf::Bgra8Unorm, + F::B8G8R8A8_SRGB => Tf::Bgra8UnormSrgb, + F::R8G8B8A8_SNORM => Tf::Rgba8Snorm, + F::R8G8B8A8_UNORM => Tf::Rgba8Unorm, + F::R8G8B8A8_SRGB => Tf::Rgba8UnormSrgb, + F::R16G16B16A16_SNORM => Tf::Rgba16Snorm, + F::R16G16B16A16_UNORM => Tf::Rgba16Unorm, + F::R16G16B16A16_SFLOAT => Tf::Rgba16Float, + F::A2B10G10R10_UNORM_PACK32 => Tf::Rgb10a2Unorm, + _ => return None, + }; + let color_space = map_vk_color_space(sf.color_space)?; + Some((format, color_space)) +} + +pub fn map_vk_color_space(color_space: vk::ColorSpaceKHR) -> Option<wgt::SurfaceColorSpace> { + use wgt::SurfaceColorSpace as Scs; + Some(match color_space { + vk::ColorSpaceKHR::SRGB_NONLINEAR => Scs::Srgb, + vk::ColorSpaceKHR::EXTENDED_SRGB_LINEAR_EXT => Scs::ExtendedSrgbLinear, + vk::ColorSpaceKHR::EXTENDED_SRGB_NONLINEAR_EXT => Scs::ExtendedSrgb, + vk::ColorSpaceKHR::DISPLAY_P3_NONLINEAR_EXT => Scs::DisplayP3, + vk::ColorSpaceKHR::HDR10_ST2084_EXT => Scs::Bt2100Pq, + vk::ColorSpaceKHR::HDR10_HLG_EXT => Scs::Bt2100Hlg, + _ => return None, + }) +} + +pub fn map_surface_color_space(color_space: wgt::SurfaceColorSpace) -> vk::ColorSpaceKHR { + use wgt::SurfaceColorSpace as Scs; + match color_space { + Scs::Auto => unreachable!("wgpu-core resolves `Auto` before configuring the surface"), + Scs::Srgb => vk::ColorSpaceKHR::SRGB_NONLINEAR, + Scs::ExtendedSrgbLinear => vk::ColorSpaceKHR::EXTENDED_SRGB_LINEAR_EXT, + Scs::ExtendedSrgb => vk::ColorSpaceKHR::EXTENDED_SRGB_NONLINEAR_EXT, + Scs::DisplayP3 => vk::ColorSpaceKHR::DISPLAY_P3_NONLINEAR_EXT, + Scs::Bt2100Pq => vk::ColorSpaceKHR::HDR10_ST2084_EXT, + Scs::Bt2100Hlg => vk::ColorSpaceKHR::HDR10_HLG_EXT, + Scs::ExtendedDisplayP3 => { + unreachable!("`ExtendedDisplayP3` is never reported in the Vulkan surface capabilities") + } + } +} + +impl crate::Attachment<'_, super::TextureView> { + pub(super) fn make_attachment_key(&self, ops: crate::AttachmentOps) -> super::AttachmentKey { + super::AttachmentKey { + format: self.view.raw_format, + layout: derive_image_layout(self.usage, self.view.format), + ops, + } + } +} + +impl crate::ColorAttachment<'_, super::TextureView> { + pub(super) unsafe fn make_vk_clear_color(&self) -> vk::ClearColorValue { + let cv = &self.clear_value; + match self.target.view.format.sample_type(None, None).unwrap() { + wgt::TextureSampleType::Float { .. } => vk::ClearColorValue { + float32: [cv.r as f32, cv.g as f32, cv.b as f32, cv.a as f32], + }, + wgt::TextureSampleType::Sint => vk::ClearColorValue { + int32: [cv.r as i32, cv.g as i32, cv.b as i32, cv.a as i32], + }, + wgt::TextureSampleType::Uint => vk::ClearColorValue { + uint32: [cv.r as u32, cv.g as u32, cv.b as u32, cv.a as u32], + }, + wgt::TextureSampleType::Depth => unreachable!(), + } + } +} + +pub fn derive_image_layout(usage: wgt::TextureUses, format: wgt::TextureFormat) -> vk::ImageLayout { + // Note: depth textures are always sampled with RODS layout + let is_color = !format.is_depth_stencil_format(); + match usage { + wgt::TextureUses::UNINITIALIZED => vk::ImageLayout::UNDEFINED, + wgt::TextureUses::COPY_SRC => vk::ImageLayout::TRANSFER_SRC_OPTIMAL, + wgt::TextureUses::COPY_DST => vk::ImageLayout::TRANSFER_DST_OPTIMAL, + wgt::TextureUses::RESOURCE if is_color => vk::ImageLayout::SHADER_READ_ONLY_OPTIMAL, + wgt::TextureUses::COLOR_TARGET => vk::ImageLayout::COLOR_ATTACHMENT_OPTIMAL, + wgt::TextureUses::DEPTH_STENCIL_WRITE => vk::ImageLayout::DEPTH_STENCIL_ATTACHMENT_OPTIMAL, + _ => { + if usage == wgt::TextureUses::PRESENT { + vk::ImageLayout::PRESENT_SRC_KHR + } else if is_color { + vk::ImageLayout::GENERAL + } else { + vk::ImageLayout::DEPTH_STENCIL_READ_ONLY_OPTIMAL + } + } + } +} + +pub fn map_texture_usage(usage: wgt::TextureUses) -> vk::ImageUsageFlags { + let mut flags = vk::ImageUsageFlags::empty(); + if usage.contains(wgt::TextureUses::COPY_SRC) { + flags |= vk::ImageUsageFlags::TRANSFER_SRC; + } + if usage.contains(wgt::TextureUses::COPY_DST) { + flags |= vk::ImageUsageFlags::TRANSFER_DST; + } + if usage.contains(wgt::TextureUses::RESOURCE) { + flags |= vk::ImageUsageFlags::SAMPLED; + } + if usage.contains(wgt::TextureUses::COLOR_TARGET) { + flags |= vk::ImageUsageFlags::COLOR_ATTACHMENT; + } + if usage + .intersects(wgt::TextureUses::DEPTH_STENCIL_READ | wgt::TextureUses::DEPTH_STENCIL_WRITE) + { + flags |= vk::ImageUsageFlags::DEPTH_STENCIL_ATTACHMENT; + } + if usage.intersects( + wgt::TextureUses::STORAGE_READ_ONLY + | wgt::TextureUses::STORAGE_WRITE_ONLY + | wgt::TextureUses::STORAGE_READ_WRITE + | wgt::TextureUses::STORAGE_ATOMIC, + ) { + flags |= vk::ImageUsageFlags::STORAGE; + } + if usage.contains(wgt::TextureUses::TRANSIENT) { + flags |= vk::ImageUsageFlags::TRANSIENT_ATTACHMENT; + } + flags +} + +pub fn map_texture_usage_to_barrier( + usage: wgt::TextureUses, +) -> (vk::PipelineStageFlags, vk::AccessFlags) { + let mut stages = vk::PipelineStageFlags::empty(); + let mut access = vk::AccessFlags::empty(); + let shader_stages = vk::PipelineStageFlags::VERTEX_SHADER + | vk::PipelineStageFlags::FRAGMENT_SHADER + | vk::PipelineStageFlags::COMPUTE_SHADER; + + if usage.contains(wgt::TextureUses::COPY_SRC) { + stages |= vk::PipelineStageFlags::TRANSFER; + access |= vk::AccessFlags::TRANSFER_READ; + } + if usage.contains(wgt::TextureUses::COPY_DST) { + stages |= vk::PipelineStageFlags::TRANSFER; + access |= vk::AccessFlags::TRANSFER_WRITE; + } + if usage.contains(wgt::TextureUses::RESOURCE) { + stages |= shader_stages; + access |= vk::AccessFlags::SHADER_READ; + } + if usage.contains(wgt::TextureUses::COLOR_TARGET) { + stages |= vk::PipelineStageFlags::COLOR_ATTACHMENT_OUTPUT; + access |= vk::AccessFlags::COLOR_ATTACHMENT_READ | vk::AccessFlags::COLOR_ATTACHMENT_WRITE; + } + if usage.intersects(wgt::TextureUses::DEPTH_STENCIL_READ) { + stages |= vk::PipelineStageFlags::EARLY_FRAGMENT_TESTS + | vk::PipelineStageFlags::LATE_FRAGMENT_TESTS; + access |= vk::AccessFlags::DEPTH_STENCIL_ATTACHMENT_READ; + } + if usage.intersects(wgt::TextureUses::DEPTH_STENCIL_WRITE) { + stages |= vk::PipelineStageFlags::EARLY_FRAGMENT_TESTS + | vk::PipelineStageFlags::LATE_FRAGMENT_TESTS; + access |= vk::AccessFlags::DEPTH_STENCIL_ATTACHMENT_READ + | vk::AccessFlags::DEPTH_STENCIL_ATTACHMENT_WRITE; + } + if usage.intersects( + wgt::TextureUses::STORAGE_READ_ONLY + | wgt::TextureUses::STORAGE_READ_WRITE + | wgt::TextureUses::STORAGE_ATOMIC, + ) { + stages |= shader_stages; + access |= vk::AccessFlags::SHADER_READ; + } + if usage.intersects( + wgt::TextureUses::STORAGE_WRITE_ONLY + | wgt::TextureUses::STORAGE_READ_WRITE + | wgt::TextureUses::STORAGE_ATOMIC, + ) { + stages |= shader_stages; + access |= vk::AccessFlags::SHADER_WRITE; + } + + if usage == wgt::TextureUses::UNINITIALIZED || usage == wgt::TextureUses::PRESENT { + ( + vk::PipelineStageFlags::TOP_OF_PIPE, + vk::AccessFlags::empty(), + ) + } else { + (stages, access) + } +} + +pub fn map_vk_image_usage(usage: vk::ImageUsageFlags) -> wgt::TextureUses { + let mut bits = wgt::TextureUses::empty(); + if usage.contains(vk::ImageUsageFlags::TRANSFER_SRC) { + bits |= wgt::TextureUses::COPY_SRC; + } + if usage.contains(vk::ImageUsageFlags::TRANSFER_DST) { + bits |= wgt::TextureUses::COPY_DST; + } + if usage.contains(vk::ImageUsageFlags::SAMPLED) { + bits |= wgt::TextureUses::RESOURCE; + } + if usage.contains(vk::ImageUsageFlags::COLOR_ATTACHMENT) { + bits |= wgt::TextureUses::COLOR_TARGET; + } + if usage.contains(vk::ImageUsageFlags::DEPTH_STENCIL_ATTACHMENT) { + bits |= wgt::TextureUses::DEPTH_STENCIL_READ | wgt::TextureUses::DEPTH_STENCIL_WRITE; + } + if usage.contains(vk::ImageUsageFlags::STORAGE) { + bits |= wgt::TextureUses::STORAGE_READ_ONLY + | wgt::TextureUses::STORAGE_WRITE_ONLY + | wgt::TextureUses::STORAGE_READ_WRITE + | wgt::TextureUses::STORAGE_ATOMIC; + } + if usage.contains(vk::ImageUsageFlags::TRANSIENT_ATTACHMENT) { + bits |= wgt::TextureUses::TRANSIENT; + } + bits +} + +pub fn map_texture_dimension(dim: wgt::TextureDimension) -> vk::ImageType { + match dim { + wgt::TextureDimension::D1 => vk::ImageType::TYPE_1D, + wgt::TextureDimension::D2 => vk::ImageType::TYPE_2D, + wgt::TextureDimension::D3 => vk::ImageType::TYPE_3D, + } +} + +pub fn map_index_format(index_format: wgt::IndexFormat) -> vk::IndexType { + match index_format { + wgt::IndexFormat::Uint16 => vk::IndexType::UINT16, + wgt::IndexFormat::Uint32 => vk::IndexType::UINT32, + } +} + +pub fn map_vertex_format(vertex_format: wgt::VertexFormat) -> vk::Format { + use wgt::VertexFormat as Vf; + match vertex_format { + Vf::Uint8 => vk::Format::R8_UINT, + Vf::Uint8x2 => vk::Format::R8G8_UINT, + Vf::Uint8x4 => vk::Format::R8G8B8A8_UINT, + Vf::Sint8 => vk::Format::R8_SINT, + Vf::Sint8x2 => vk::Format::R8G8_SINT, + Vf::Sint8x4 => vk::Format::R8G8B8A8_SINT, + Vf::Unorm8 => vk::Format::R8_UNORM, + Vf::Unorm8x2 => vk::Format::R8G8_UNORM, + Vf::Unorm8x4 => vk::Format::R8G8B8A8_UNORM, + Vf::Snorm8 => vk::Format::R8_SNORM, + Vf::Snorm8x2 => vk::Format::R8G8_SNORM, + Vf::Snorm8x4 => vk::Format::R8G8B8A8_SNORM, + Vf::Uint16 => vk::Format::R16_UINT, + Vf::Uint16x2 => vk::Format::R16G16_UINT, + Vf::Uint16x4 => vk::Format::R16G16B16A16_UINT, + Vf::Sint16 => vk::Format::R16_SINT, + Vf::Sint16x2 => vk::Format::R16G16_SINT, + Vf::Sint16x4 => vk::Format::R16G16B16A16_SINT, + Vf::Unorm16 => vk::Format::R16_UNORM, + Vf::Unorm16x2 => vk::Format::R16G16_UNORM, + Vf::Unorm16x4 => vk::Format::R16G16B16A16_UNORM, + Vf::Snorm16 => vk::Format::R16_SNORM, + Vf::Snorm16x2 => vk::Format::R16G16_SNORM, + Vf::Snorm16x4 => vk::Format::R16G16B16A16_SNORM, + Vf::Float16 => vk::Format::R16_SFLOAT, + Vf::Float16x2 => vk::Format::R16G16_SFLOAT, + Vf::Float16x4 => vk::Format::R16G16B16A16_SFLOAT, + Vf::Float32 => vk::Format::R32_SFLOAT, + Vf::Float32x2 => vk::Format::R32G32_SFLOAT, + Vf::Float32x3 => vk::Format::R32G32B32_SFLOAT, + Vf::Float32x4 => vk::Format::R32G32B32A32_SFLOAT, + Vf::Uint32 => vk::Format::R32_UINT, + Vf::Uint32x2 => vk::Format::R32G32_UINT, + Vf::Uint32x3 => vk::Format::R32G32B32_UINT, + Vf::Uint32x4 => vk::Format::R32G32B32A32_UINT, + Vf::Sint32 => vk::Format::R32_SINT, + Vf::Sint32x2 => vk::Format::R32G32_SINT, + Vf::Sint32x3 => vk::Format::R32G32B32_SINT, + Vf::Sint32x4 => vk::Format::R32G32B32A32_SINT, + Vf::Float64 => vk::Format::R64_SFLOAT, + Vf::Float64x2 => vk::Format::R64G64_SFLOAT, + Vf::Float64x3 => vk::Format::R64G64B64_SFLOAT, + Vf::Float64x4 => vk::Format::R64G64B64A64_SFLOAT, + Vf::Unorm10_10_10_2 => vk::Format::A2B10G10R10_UNORM_PACK32, + Vf::Unorm8x4Bgra => vk::Format::B8G8R8A8_UNORM, + } +} + +pub fn map_aspects(aspects: crate::FormatAspects) -> vk::ImageAspectFlags { + let mut flags = vk::ImageAspectFlags::empty(); + if aspects.contains(crate::FormatAspects::COLOR) { + flags |= vk::ImageAspectFlags::COLOR; + } + if aspects.contains(crate::FormatAspects::DEPTH) { + flags |= vk::ImageAspectFlags::DEPTH; + } + if aspects.contains(crate::FormatAspects::STENCIL) { + flags |= vk::ImageAspectFlags::STENCIL; + } + if aspects.contains(crate::FormatAspects::PLANE_0) { + flags |= vk::ImageAspectFlags::PLANE_0; + } + if aspects.contains(crate::FormatAspects::PLANE_1) { + flags |= vk::ImageAspectFlags::PLANE_1; + } + if aspects.contains(crate::FormatAspects::PLANE_2) { + flags |= vk::ImageAspectFlags::PLANE_2; + } + flags +} + +pub fn map_attachment_ops( + op: crate::AttachmentOps, +) -> (vk::AttachmentLoadOp, vk::AttachmentStoreOp) { + let load_op = if op.contains(crate::AttachmentOps::LOAD) { + vk::AttachmentLoadOp::LOAD + } else if op.contains(crate::AttachmentOps::LOAD_DONT_CARE) { + vk::AttachmentLoadOp::DONT_CARE + } else if op.contains(crate::AttachmentOps::LOAD_CLEAR) { + vk::AttachmentLoadOp::CLEAR + } else { + unreachable!() + }; + let store_op = if op.contains(crate::AttachmentOps::STORE) { + vk::AttachmentStoreOp::STORE + } else if op.contains(crate::AttachmentOps::STORE_DISCARD) { + vk::AttachmentStoreOp::DONT_CARE + } else { + unreachable!() + }; + (load_op, store_op) +} + +pub fn map_present_mode(mode: wgt::PresentMode) -> vk::PresentModeKHR { + match mode { + wgt::PresentMode::Immediate => vk::PresentModeKHR::IMMEDIATE, + wgt::PresentMode::Mailbox => vk::PresentModeKHR::MAILBOX, + wgt::PresentMode::Fifo => vk::PresentModeKHR::FIFO, + wgt::PresentMode::FifoRelaxed => vk::PresentModeKHR::FIFO_RELAXED, + wgt::PresentMode::AutoNoVsync | wgt::PresentMode::AutoVsync => { + unreachable!("Cannot create swapchain with Auto PresentationMode") + } + } +} + +pub fn map_vk_present_mode(mode: vk::PresentModeKHR) -> Option<wgt::PresentMode> { + // Not exposed in Ash yet. + const FIFO_LATEST_READY: vk::PresentModeKHR = vk::PresentModeKHR::from_raw(1_000_361_000); + + // See https://registry.khronos.org/vulkan/specs/latest/man/html/VkPresentModeKHR.html + match mode { + vk::PresentModeKHR::IMMEDIATE => Some(wgt::PresentMode::Immediate), + vk::PresentModeKHR::MAILBOX => Some(wgt::PresentMode::Mailbox), + vk::PresentModeKHR::FIFO => Some(wgt::PresentMode::Fifo), + vk::PresentModeKHR::FIFO_RELAXED => Some(wgt::PresentMode::FifoRelaxed), + + // Modes that aren't exposed yet. + vk::PresentModeKHR::SHARED_DEMAND_REFRESH => None, + vk::PresentModeKHR::SHARED_CONTINUOUS_REFRESH => None, + FIFO_LATEST_READY => None, + + _ => { + log::debug!("Unrecognized present mode {mode:?}"); + None + } + } +} + +pub fn map_composite_alpha_mode(mode: wgt::CompositeAlphaMode) -> vk::CompositeAlphaFlagsKHR { + match mode { + wgt::CompositeAlphaMode::Opaque => vk::CompositeAlphaFlagsKHR::OPAQUE, + wgt::CompositeAlphaMode::PreMultiplied => vk::CompositeAlphaFlagsKHR::PRE_MULTIPLIED, + wgt::CompositeAlphaMode::PostMultiplied => vk::CompositeAlphaFlagsKHR::POST_MULTIPLIED, + wgt::CompositeAlphaMode::Inherit => vk::CompositeAlphaFlagsKHR::INHERIT, + wgt::CompositeAlphaMode::Auto => unreachable!(), + } +} + +pub fn map_vk_composite_alpha(flags: vk::CompositeAlphaFlagsKHR) -> Vec<wgt::CompositeAlphaMode> { + let mut modes = Vec::new(); + if flags.contains(vk::CompositeAlphaFlagsKHR::OPAQUE) { + modes.push(wgt::CompositeAlphaMode::Opaque); + } + if flags.contains(vk::CompositeAlphaFlagsKHR::PRE_MULTIPLIED) { + modes.push(wgt::CompositeAlphaMode::PreMultiplied); + } + if flags.contains(vk::CompositeAlphaFlagsKHR::POST_MULTIPLIED) { + modes.push(wgt::CompositeAlphaMode::PostMultiplied); + } + if flags.contains(vk::CompositeAlphaFlagsKHR::INHERIT) { + modes.push(wgt::CompositeAlphaMode::Inherit); + } + modes +} + +pub fn map_buffer_usage(usage: wgt::BufferUses) -> vk::BufferUsageFlags { + let mut flags = vk::BufferUsageFlags::empty(); + if usage.contains(wgt::BufferUses::COPY_SRC) { + flags |= vk::BufferUsageFlags::TRANSFER_SRC; + } + if usage.contains(wgt::BufferUses::COPY_DST) { + flags |= vk::BufferUsageFlags::TRANSFER_DST; + } + if usage.contains(wgt::BufferUses::UNIFORM) { + flags |= vk::BufferUsageFlags::UNIFORM_BUFFER; + } + if usage.intersects(wgt::BufferUses::STORAGE_READ_ONLY | wgt::BufferUses::STORAGE_READ_WRITE) { + flags |= vk::BufferUsageFlags::STORAGE_BUFFER; + } + if usage.contains(wgt::BufferUses::INDEX) { + flags |= vk::BufferUsageFlags::INDEX_BUFFER; + } + if usage.contains(wgt::BufferUses::VERTEX) { + flags |= vk::BufferUsageFlags::VERTEX_BUFFER; + } + if usage.contains(wgt::BufferUses::INDIRECT) { + flags |= vk::BufferUsageFlags::INDIRECT_BUFFER; + } + if usage.contains(wgt::BufferUses::ACCELERATION_STRUCTURE_SCRATCH) { + flags |= vk::BufferUsageFlags::STORAGE_BUFFER | vk::BufferUsageFlags::SHADER_DEVICE_ADDRESS; + } + if usage.intersects( + wgt::BufferUses::BOTTOM_LEVEL_ACCELERATION_STRUCTURE_INPUT + | wgt::BufferUses::TOP_LEVEL_ACCELERATION_STRUCTURE_INPUT, + ) { + flags |= vk::BufferUsageFlags::ACCELERATION_STRUCTURE_BUILD_INPUT_READ_ONLY_KHR + | vk::BufferUsageFlags::SHADER_DEVICE_ADDRESS; + } + if usage.intersects(wgt::BufferUses::ACCELERATION_STRUCTURE_QUERY) { + flags |= vk::BufferUsageFlags::TRANSFER_DST; + } + if usage.intersects(wgt::BufferUses::RAY_TRACING_PIPELINE_SHADER_DATA) { + flags |= vk::BufferUsageFlags::SHADER_BINDING_TABLE_KHR + | vk::BufferUsageFlags::SHADER_DEVICE_ADDRESS; + } + flags +} + +pub fn map_buffer_usage_to_barrier( + usage: wgt::BufferUses, +) -> (vk::PipelineStageFlags, vk::AccessFlags) { + let mut stages = vk::PipelineStageFlags::empty(); + let mut access = vk::AccessFlags::empty(); + let shader_stages = vk::PipelineStageFlags::VERTEX_SHADER + | vk::PipelineStageFlags::FRAGMENT_SHADER + | vk::PipelineStageFlags::COMPUTE_SHADER; + + if usage.contains(wgt::BufferUses::MAP_READ) { + stages |= vk::PipelineStageFlags::HOST; + access |= vk::AccessFlags::HOST_READ; + } + if usage.contains(wgt::BufferUses::MAP_WRITE) { + stages |= vk::PipelineStageFlags::HOST; + access |= vk::AccessFlags::HOST_WRITE; + } + if usage.contains(wgt::BufferUses::COPY_SRC) { + stages |= vk::PipelineStageFlags::TRANSFER; + access |= vk::AccessFlags::TRANSFER_READ; + } + if usage.contains(wgt::BufferUses::COPY_DST) { + stages |= vk::PipelineStageFlags::TRANSFER; + access |= vk::AccessFlags::TRANSFER_WRITE; + } + if usage.contains(wgt::BufferUses::UNIFORM) { + stages |= shader_stages; + access |= vk::AccessFlags::UNIFORM_READ; + } + if usage.intersects(wgt::BufferUses::STORAGE_READ_ONLY) { + stages |= shader_stages; + access |= vk::AccessFlags::SHADER_READ; + } + if usage.intersects(wgt::BufferUses::STORAGE_READ_WRITE) { + stages |= shader_stages; + access |= vk::AccessFlags::SHADER_READ | vk::AccessFlags::SHADER_WRITE; + } + if usage.contains(wgt::BufferUses::INDEX) { + stages |= vk::PipelineStageFlags::VERTEX_INPUT; + access |= vk::AccessFlags::INDEX_READ; + } + if usage.contains(wgt::BufferUses::VERTEX) { + stages |= vk::PipelineStageFlags::VERTEX_INPUT; + access |= vk::AccessFlags::VERTEX_ATTRIBUTE_READ; + } + if usage.contains(wgt::BufferUses::INDIRECT) { + stages |= vk::PipelineStageFlags::DRAW_INDIRECT; + access |= vk::AccessFlags::INDIRECT_COMMAND_READ; + } + if usage.intersects( + wgt::BufferUses::BOTTOM_LEVEL_ACCELERATION_STRUCTURE_INPUT + | wgt::BufferUses::TOP_LEVEL_ACCELERATION_STRUCTURE_INPUT + | wgt::BufferUses::ACCELERATION_STRUCTURE_SCRATCH, + ) { + stages |= vk::PipelineStageFlags::ACCELERATION_STRUCTURE_BUILD_KHR; + access |= vk::AccessFlags::ACCELERATION_STRUCTURE_READ_KHR + | vk::AccessFlags::ACCELERATION_STRUCTURE_WRITE_KHR + | vk::AccessFlags::SHADER_READ; + } + if usage.contains(wgt::BufferUses::ACCELERATION_STRUCTURE_QUERY) { + stages |= vk::PipelineStageFlags::TRANSFER; + access |= vk::AccessFlags::TRANSFER_WRITE; + } + + (stages, access) +} + +pub fn map_view_dimension(dim: wgt::TextureViewDimension) -> vk::ImageViewType { + match dim { + wgt::TextureViewDimension::D1 => vk::ImageViewType::TYPE_1D, + wgt::TextureViewDimension::D2 => vk::ImageViewType::TYPE_2D, + wgt::TextureViewDimension::D2Array => vk::ImageViewType::TYPE_2D_ARRAY, + wgt::TextureViewDimension::Cube => vk::ImageViewType::CUBE, + wgt::TextureViewDimension::CubeArray => vk::ImageViewType::CUBE_ARRAY, + wgt::TextureViewDimension::D3 => vk::ImageViewType::TYPE_3D, + } +} + +pub fn map_copy_extent(extent: &crate::CopyExtent) -> vk::Extent3D { + vk::Extent3D { + width: extent.width, + height: extent.height, + depth: extent.depth, + } +} + +pub fn map_subresource_range( + range: &wgt::ImageSubresourceRange, + format: wgt::TextureFormat, +) -> vk::ImageSubresourceRange { + vk::ImageSubresourceRange { + aspect_mask: map_aspects(crate::FormatAspects::new(format, range.aspect)), + base_mip_level: range.base_mip_level, + level_count: range.mip_level_count.unwrap_or(vk::REMAINING_MIP_LEVELS), + base_array_layer: range.base_array_layer, + layer_count: range + .array_layer_count + .unwrap_or(vk::REMAINING_ARRAY_LAYERS), + } +} + +// Special subresource range mapping for dealing with barriers +// so that we account for the "hidden" depth aspect in emulated Stencil8. +pub(super) fn map_subresource_range_combined_aspect( + range: &wgt::ImageSubresourceRange, + format: wgt::TextureFormat, + private_caps: &super::PrivateCapabilities, +) -> vk::ImageSubresourceRange { + let mut range = map_subresource_range(range, format); + if !private_caps.texture_s8 && format == wgt::TextureFormat::Stencil8 { + range.aspect_mask |= vk::ImageAspectFlags::DEPTH; + } + range +} + +pub fn map_subresource_layers( + base: &crate::TextureCopyBase, +) -> (vk::ImageSubresourceLayers, vk::Offset3D) { + let offset = vk::Offset3D { + x: base.origin.x as i32, + y: base.origin.y as i32, + z: base.origin.z as i32, + }; + let subresource = vk::ImageSubresourceLayers { + aspect_mask: map_aspects(base.aspect), + mip_level: base.mip_level, + base_array_layer: base.array_layer, + layer_count: 1, + }; + (subresource, offset) +} + +pub fn map_filter_mode(mode: wgt::FilterMode) -> vk::Filter { + match mode { + wgt::FilterMode::Nearest => vk::Filter::NEAREST, + wgt::FilterMode::Linear => vk::Filter::LINEAR, + } +} + +pub fn map_mip_filter_mode(mode: wgt::MipmapFilterMode) -> vk::SamplerMipmapMode { + match mode { + wgt::MipmapFilterMode::Nearest => vk::SamplerMipmapMode::NEAREST, + wgt::MipmapFilterMode::Linear => vk::SamplerMipmapMode::LINEAR, + } +} + +pub fn map_address_mode(mode: wgt::AddressMode) -> vk::SamplerAddressMode { + match mode { + wgt::AddressMode::ClampToEdge => vk::SamplerAddressMode::CLAMP_TO_EDGE, + wgt::AddressMode::Repeat => vk::SamplerAddressMode::REPEAT, + wgt::AddressMode::MirrorRepeat => vk::SamplerAddressMode::MIRRORED_REPEAT, + wgt::AddressMode::ClampToBorder => vk::SamplerAddressMode::CLAMP_TO_BORDER, + // wgt::AddressMode::MirrorClamp => vk::SamplerAddressMode::MIRROR_CLAMP_TO_EDGE, + } +} + +pub fn map_border_color(border_color: wgt::SamplerBorderColor) -> vk::BorderColor { + match border_color { + wgt::SamplerBorderColor::TransparentBlack | wgt::SamplerBorderColor::Zero => { + vk::BorderColor::FLOAT_TRANSPARENT_BLACK + } + wgt::SamplerBorderColor::OpaqueBlack => vk::BorderColor::FLOAT_OPAQUE_BLACK, + wgt::SamplerBorderColor::OpaqueWhite => vk::BorderColor::FLOAT_OPAQUE_WHITE, + } +} + +pub fn map_comparison(fun: wgt::CompareFunction) -> vk::CompareOp { + use wgt::CompareFunction as Cf; + match fun { + Cf::Never => vk::CompareOp::NEVER, + Cf::Less => vk::CompareOp::LESS, + Cf::LessEqual => vk::CompareOp::LESS_OR_EQUAL, + Cf::Equal => vk::CompareOp::EQUAL, + Cf::GreaterEqual => vk::CompareOp::GREATER_OR_EQUAL, + Cf::Greater => vk::CompareOp::GREATER, + Cf::NotEqual => vk::CompareOp::NOT_EQUAL, + Cf::Always => vk::CompareOp::ALWAYS, + } +} + +pub fn map_shader_stage(stage: wgt::ShaderStages) -> vk::ShaderStageFlags { + let mut flags = vk::ShaderStageFlags::empty(); + if stage.contains(wgt::ShaderStages::VERTEX) { + flags |= vk::ShaderStageFlags::VERTEX; + } + if stage.contains(wgt::ShaderStages::FRAGMENT) { + flags |= vk::ShaderStageFlags::FRAGMENT; + } + if stage.contains(wgt::ShaderStages::COMPUTE) { + flags |= vk::ShaderStageFlags::COMPUTE; + } + if stage.contains(wgt::ShaderStages::TASK) { + flags |= vk::ShaderStageFlags::TASK_EXT; + } + if stage.contains(wgt::ShaderStages::MESH) { + flags |= vk::ShaderStageFlags::MESH_EXT; + } + if stage.contains(wgt::ShaderStages::RAY_GENERATION) { + flags |= vk::ShaderStageFlags::RAYGEN_KHR; + } + if stage.contains(wgt::ShaderStages::MISS) { + flags |= vk::ShaderStageFlags::MISS_KHR; + } + if stage.contains(wgt::ShaderStages::ANY_HIT) { + flags |= vk::ShaderStageFlags::ANY_HIT_KHR; + } + if stage.contains(wgt::ShaderStages::CLOSEST_HIT) { + flags |= vk::ShaderStageFlags::CLOSEST_HIT_KHR; + } + flags +} + +pub fn map_binding_type(ty: wgt::BindingType) -> vk::DescriptorType { + match ty { + wgt::BindingType::Buffer { + ty, + has_dynamic_offset, + .. + } => match ty { + wgt::BufferBindingType::Storage { .. } => match has_dynamic_offset { + true => vk::DescriptorType::STORAGE_BUFFER_DYNAMIC, + false => vk::DescriptorType::STORAGE_BUFFER, + }, + wgt::BufferBindingType::Uniform => match has_dynamic_offset { + true => vk::DescriptorType::UNIFORM_BUFFER_DYNAMIC, + false => vk::DescriptorType::UNIFORM_BUFFER, + }, + }, + wgt::BindingType::Sampler { .. } => vk::DescriptorType::SAMPLER, + wgt::BindingType::Texture { .. } => vk::DescriptorType::SAMPLED_IMAGE, + wgt::BindingType::StorageTexture { .. } => vk::DescriptorType::STORAGE_IMAGE, + wgt::BindingType::AccelerationStructure { .. } => { + vk::DescriptorType::ACCELERATION_STRUCTURE_KHR + } + wgt::BindingType::ExternalTexture => unimplemented!(), + } +} + +pub fn map_topology(topology: wgt::PrimitiveTopology) -> vk::PrimitiveTopology { + use wgt::PrimitiveTopology as Pt; + match topology { + Pt::PointList => vk::PrimitiveTopology::POINT_LIST, + Pt::LineList => vk::PrimitiveTopology::LINE_LIST, + Pt::LineStrip => vk::PrimitiveTopology::LINE_STRIP, + Pt::TriangleList => vk::PrimitiveTopology::TRIANGLE_LIST, + Pt::TriangleStrip => vk::PrimitiveTopology::TRIANGLE_STRIP, + } +} + +pub fn map_polygon_mode(mode: wgt::PolygonMode) -> vk::PolygonMode { + match mode { + wgt::PolygonMode::Fill => vk::PolygonMode::FILL, + wgt::PolygonMode::Line => vk::PolygonMode::LINE, + wgt::PolygonMode::Point => vk::PolygonMode::POINT, + } +} + +pub fn map_front_face(front_face: wgt::FrontFace) -> vk::FrontFace { + match front_face { + wgt::FrontFace::Cw => vk::FrontFace::CLOCKWISE, + wgt::FrontFace::Ccw => vk::FrontFace::COUNTER_CLOCKWISE, + } +} + +pub fn map_cull_face(face: wgt::Face) -> vk::CullModeFlags { + match face { + wgt::Face::Front => vk::CullModeFlags::FRONT, + wgt::Face::Back => vk::CullModeFlags::BACK, + } +} + +pub fn map_stencil_op(op: wgt::StencilOperation) -> vk::StencilOp { + use wgt::StencilOperation as So; + match op { + So::Keep => vk::StencilOp::KEEP, + So::Zero => vk::StencilOp::ZERO, + So::Replace => vk::StencilOp::REPLACE, + So::Invert => vk::StencilOp::INVERT, + So::IncrementClamp => vk::StencilOp::INCREMENT_AND_CLAMP, + So::IncrementWrap => vk::StencilOp::INCREMENT_AND_WRAP, + So::DecrementClamp => vk::StencilOp::DECREMENT_AND_CLAMP, + So::DecrementWrap => vk::StencilOp::DECREMENT_AND_WRAP, + } +} + +pub fn map_stencil_face( + face: &wgt::StencilFaceState, + compare_mask: u32, + write_mask: u32, +) -> vk::StencilOpState { + vk::StencilOpState { + fail_op: map_stencil_op(face.fail_op), + pass_op: map_stencil_op(face.pass_op), + depth_fail_op: map_stencil_op(face.depth_fail_op), + compare_op: map_comparison(face.compare), + compare_mask, + write_mask, + reference: 0, + } +} + +fn map_blend_factor(factor: wgt::BlendFactor) -> vk::BlendFactor { + use wgt::BlendFactor as Bf; + match factor { + Bf::Zero => vk::BlendFactor::ZERO, + Bf::One => vk::BlendFactor::ONE, + Bf::Src => vk::BlendFactor::SRC_COLOR, + Bf::OneMinusSrc => vk::BlendFactor::ONE_MINUS_SRC_COLOR, + Bf::SrcAlpha => vk::BlendFactor::SRC_ALPHA, + Bf::OneMinusSrcAlpha => vk::BlendFactor::ONE_MINUS_SRC_ALPHA, + Bf::Dst => vk::BlendFactor::DST_COLOR, + Bf::OneMinusDst => vk::BlendFactor::ONE_MINUS_DST_COLOR, + Bf::DstAlpha => vk::BlendFactor::DST_ALPHA, + Bf::OneMinusDstAlpha => vk::BlendFactor::ONE_MINUS_DST_ALPHA, + Bf::SrcAlphaSaturated => vk::BlendFactor::SRC_ALPHA_SATURATE, + Bf::Constant => vk::BlendFactor::CONSTANT_COLOR, + Bf::OneMinusConstant => vk::BlendFactor::ONE_MINUS_CONSTANT_COLOR, + Bf::Src1 => vk::BlendFactor::SRC1_COLOR, + Bf::OneMinusSrc1 => vk::BlendFactor::ONE_MINUS_SRC1_COLOR, + Bf::Src1Alpha => vk::BlendFactor::SRC1_ALPHA, + Bf::OneMinusSrc1Alpha => vk::BlendFactor::ONE_MINUS_SRC1_ALPHA, + } +} + +fn map_blend_op(operation: wgt::BlendOperation) -> vk::BlendOp { + use wgt::BlendOperation as Bo; + match operation { + Bo::Add => vk::BlendOp::ADD, + Bo::Subtract => vk::BlendOp::SUBTRACT, + Bo::ReverseSubtract => vk::BlendOp::REVERSE_SUBTRACT, + Bo::Min => vk::BlendOp::MIN, + Bo::Max => vk::BlendOp::MAX, + } +} + +pub fn map_blend_component( + component: &wgt::BlendComponent, +) -> (vk::BlendOp, vk::BlendFactor, vk::BlendFactor) { + let op = map_blend_op(component.operation); + let src = map_blend_factor(component.src_factor); + let dst = map_blend_factor(component.dst_factor); + (op, src, dst) +} + +pub fn map_pipeline_statistics( + types: wgt::PipelineStatisticsTypes, +) -> vk::QueryPipelineStatisticFlags { + use wgt::PipelineStatisticsTypes as Pst; + let mut flags = vk::QueryPipelineStatisticFlags::empty(); + if types.contains(Pst::VERTEX_SHADER_INVOCATIONS) { + flags |= vk::QueryPipelineStatisticFlags::VERTEX_SHADER_INVOCATIONS; + } + if types.contains(Pst::CLIPPER_INVOCATIONS) { + flags |= vk::QueryPipelineStatisticFlags::CLIPPING_INVOCATIONS; + } + if types.contains(Pst::CLIPPER_PRIMITIVES_OUT) { + flags |= vk::QueryPipelineStatisticFlags::CLIPPING_PRIMITIVES; + } + if types.contains(Pst::FRAGMENT_SHADER_INVOCATIONS) { + flags |= vk::QueryPipelineStatisticFlags::FRAGMENT_SHADER_INVOCATIONS; + } + if types.contains(Pst::COMPUTE_SHADER_INVOCATIONS) { + flags |= vk::QueryPipelineStatisticFlags::COMPUTE_SHADER_INVOCATIONS; + } + flags +} + +pub fn map_acceleration_structure_format( + format: crate::AccelerationStructureFormat, +) -> vk::AccelerationStructureTypeKHR { + match format { + crate::AccelerationStructureFormat::TopLevel => vk::AccelerationStructureTypeKHR::TOP_LEVEL, + crate::AccelerationStructureFormat::BottomLevel => { + vk::AccelerationStructureTypeKHR::BOTTOM_LEVEL + } + } +} + +pub fn map_acceleration_structure_build_mode( + format: crate::AccelerationStructureBuildMode, +) -> vk::BuildAccelerationStructureModeKHR { + match format { + crate::AccelerationStructureBuildMode::Build => { + vk::BuildAccelerationStructureModeKHR::BUILD + } + crate::AccelerationStructureBuildMode::Update => { + vk::BuildAccelerationStructureModeKHR::UPDATE + } + } +} + +pub fn map_acceleration_structure_flags( + flags: crate::AccelerationStructureBuildFlags, +) -> vk::BuildAccelerationStructureFlagsKHR { + let mut vk_flags = vk::BuildAccelerationStructureFlagsKHR::empty(); + + if flags.contains(crate::AccelerationStructureBuildFlags::PREFER_FAST_TRACE) { + vk_flags |= vk::BuildAccelerationStructureFlagsKHR::PREFER_FAST_TRACE; + } + + if flags.contains(crate::AccelerationStructureBuildFlags::PREFER_FAST_BUILD) { + vk_flags |= vk::BuildAccelerationStructureFlagsKHR::PREFER_FAST_BUILD; + } + + if flags.contains(crate::AccelerationStructureBuildFlags::ALLOW_UPDATE) { + vk_flags |= vk::BuildAccelerationStructureFlagsKHR::ALLOW_UPDATE; + } + + if flags.contains(crate::AccelerationStructureBuildFlags::LOW_MEMORY) { + vk_flags |= vk::BuildAccelerationStructureFlagsKHR::LOW_MEMORY; + } + + if flags.contains(crate::AccelerationStructureBuildFlags::ALLOW_COMPACTION) { + vk_flags |= vk::BuildAccelerationStructureFlagsKHR::ALLOW_COMPACTION + } + + if flags.contains(crate::AccelerationStructureBuildFlags::ALLOW_RAY_HIT_VERTEX_RETURN) { + vk_flags |= vk::BuildAccelerationStructureFlagsKHR::ALLOW_DATA_ACCESS + } + + vk_flags +} + +pub fn map_acceleration_structure_geometry_flags( + flags: crate::AccelerationStructureGeometryFlags, +) -> vk::GeometryFlagsKHR { + let mut vk_flags = vk::GeometryFlagsKHR::empty(); + + if flags.contains(crate::AccelerationStructureGeometryFlags::OPAQUE) { + vk_flags |= vk::GeometryFlagsKHR::OPAQUE; + } + + if flags.contains(crate::AccelerationStructureGeometryFlags::NO_DUPLICATE_ANY_HIT_INVOCATION) { + vk_flags |= vk::GeometryFlagsKHR::NO_DUPLICATE_ANY_HIT_INVOCATION; + } + + vk_flags +} + +pub fn map_acceleration_structure_usage_to_barrier( + usage: crate::AccelerationStructureUses, + features: wgt::Features, +) -> (vk::PipelineStageFlags, vk::AccessFlags) { + let mut stages = vk::PipelineStageFlags::empty(); + let mut access = vk::AccessFlags::empty(); + + if usage.contains(crate::AccelerationStructureUses::BUILD_INPUT) { + stages |= vk::PipelineStageFlags::ACCELERATION_STRUCTURE_BUILD_KHR; + access |= vk::AccessFlags::ACCELERATION_STRUCTURE_READ_KHR; + } + if usage.contains(crate::AccelerationStructureUses::QUERY_INPUT) { + stages |= vk::PipelineStageFlags::ACCELERATION_STRUCTURE_BUILD_KHR; + access |= vk::AccessFlags::ACCELERATION_STRUCTURE_READ_KHR; + } + if usage.contains(crate::AccelerationStructureUses::BUILD_OUTPUT) { + stages |= vk::PipelineStageFlags::ACCELERATION_STRUCTURE_BUILD_KHR; + access |= vk::AccessFlags::ACCELERATION_STRUCTURE_WRITE_KHR; + } + if usage.contains(crate::AccelerationStructureUses::SHADER_INPUT) + && features.contains(wgt::Features::EXPERIMENTAL_RAY_QUERY) + { + stages |= vk::PipelineStageFlags::VERTEX_SHADER + | vk::PipelineStageFlags::FRAGMENT_SHADER + | vk::PipelineStageFlags::COMPUTE_SHADER; + access |= vk::AccessFlags::ACCELERATION_STRUCTURE_READ_KHR; + } + if usage.contains(crate::AccelerationStructureUses::SHADER_INPUT) + && features.contains(wgt::Features::EXPERIMENTAL_RAY_TRACING_PIPELINES) + { + stages |= vk::PipelineStageFlags::RAY_TRACING_SHADER_KHR; + access |= vk::AccessFlags::ACCELERATION_STRUCTURE_READ_KHR; + } + if usage.contains(crate::AccelerationStructureUses::COPY_SRC) { + stages |= vk::PipelineStageFlags::ACCELERATION_STRUCTURE_BUILD_KHR; + access |= vk::AccessFlags::ACCELERATION_STRUCTURE_READ_KHR; + } + if usage.contains(crate::AccelerationStructureUses::COPY_DST) { + stages |= vk::PipelineStageFlags::ACCELERATION_STRUCTURE_BUILD_KHR; + access |= vk::AccessFlags::ACCELERATION_STRUCTURE_WRITE_KHR; + } + + (stages, access) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// `map_vk_color_space` and `map_surface_color_space` must stay mutually + /// inverse so that a color space reported in the surface capabilities is + /// exactly what the swapchain is created with. + #[test] + fn color_space_round_trip() { + for vk_color_space in [ + vk::ColorSpaceKHR::SRGB_NONLINEAR, + vk::ColorSpaceKHR::EXTENDED_SRGB_LINEAR_EXT, + vk::ColorSpaceKHR::EXTENDED_SRGB_NONLINEAR_EXT, + vk::ColorSpaceKHR::DISPLAY_P3_NONLINEAR_EXT, + vk::ColorSpaceKHR::HDR10_ST2084_EXT, + vk::ColorSpaceKHR::HDR10_HLG_EXT, + ] { + let mapped = map_vk_color_space(vk_color_space).unwrap(); + assert_eq!(map_surface_color_space(mapped), vk_color_space); + } + } + + #[test] + fn unknown_color_spaces_are_dropped() { + for vk_color_space in [ + vk::ColorSpaceKHR::BT2020_LINEAR_EXT, + vk::ColorSpaceKHR::DOLBYVISION_EXT, + vk::ColorSpaceKHR::PASS_THROUGH_EXT, + vk::ColorSpaceKHR::ADOBERGB_NONLINEAR_EXT, + ] { + assert!(map_vk_color_space(vk_color_space).is_none()); + assert!(map_vk_surface_formats(vk::SurfaceFormatKHR { + format: vk::Format::B8G8R8A8_UNORM, + color_space: vk_color_space, + }) + .is_none()); + } + } + + #[test] + fn hdr10_surface_format_maps() { + let (format, color_space) = map_vk_surface_formats(vk::SurfaceFormatKHR { + format: vk::Format::A2B10G10R10_UNORM_PACK32, + color_space: vk::ColorSpaceKHR::HDR10_ST2084_EXT, + }) + .unwrap(); + assert_eq!(format, wgt::TextureFormat::Rgb10a2Unorm); + assert_eq!(color_space, wgt::SurfaceColorSpace::Bt2100Pq); + } +} diff --git a/app/vendor/rune/vendor/wgpu-hal/src/vulkan/descriptor.rs b/app/vendor/rune/vendor/wgpu-hal/src/vulkan/descriptor.rs new file mode 100644 index 0000000..5961c3c --- /dev/null +++ b/app/vendor/rune/vendor/wgpu-hal/src/vulkan/descriptor.rs @@ -0,0 +1,339 @@ +use alloc::vec::Vec; +use arrayvec::ArrayVec; +use ash::vk; +use hashbrown::{HashMap, HashSet}; + +const POOL_MIN_SETS: u32 = 64; +const POOL_MAX_SETS: u32 = 512; + +/// The dynamic counts are tracked separately since dynamic textures/buffers +/// have distinct descriptor types compared to their non-dynamic counterparts. +#[derive(Debug, Default, Clone, PartialEq, Eq, Hash)] +pub struct DescriptorCounts { + pub sampler: u32, + pub sampled_image: u32, + pub storage_image: u32, + pub uniform_buffer: u32, + pub uniform_buffer_dynamic: u32, + pub storage_buffer: u32, + pub storage_buffer_dynamic: u32, + pub acceleration_structure: u32, +} + +impl DescriptorCounts { + fn total(&self) -> u32 { + self.sampler + + self.sampled_image + + self.storage_image + + self.uniform_buffer + + self.uniform_buffer_dynamic + + self.storage_buffer + + self.storage_buffer_dynamic + + self.acceleration_structure + } +} + +#[derive(Debug)] +pub struct DescriptorSet { + raw: vk::DescriptorSet, + bucket_key: BucketKey, + pool_index: usize, +} + +impl DescriptorSet { + pub fn raw(&self) -> vk::DescriptorSet { + self.raw + } +} + +#[derive(Debug, PartialEq, Eq, Hash)] +struct BucketKey { + counts: DescriptorCounts, + update_after_bind: bool, +} + +struct Pool { + raw: vk::DescriptorPool, + capacity: u32, + available: u32, +} + +/// Keeps track of all pools created with this bucket's [`BucketKey`]. +#[derive(Default)] +struct Bucket { + /// We keep track of all descriptor set layouts that might use this bucket. + /// If the set becomes empty, the bucket is destroyed. + layouts: HashSet<vk::DescriptorSetLayout>, + pools: Vec<Pool>, + available_sets: u32, + allocated_sets: u32, +} + +impl Bucket { + fn create_pool( + &mut self, + device: &ash::Device, + key: &BucketKey, + capacity_hint: u32, + ) -> Result<(usize, &mut Pool), crate::DeviceError> { + let index = self.pools.len(); + let pool = create_descriptor_pool(device, key, capacity_hint)?; + self.available_sets += pool.capacity; + self.pools.push(pool); + Ok((index, self.pools.last_mut().unwrap())) + } +} + +pub struct DescriptorAllocator { + buckets: HashMap<BucketKey, Bucket>, + max_update_after_bind_descriptors_in_all_pools: u32, + update_after_bind_descriptors_in_all_pools: u32, +} + +impl super::BindGroupLayout { + fn bucket_key(&self) -> BucketKey { + let update_after_bind = self.contains_binding_arrays; + let counts = self.desc_count.clone(); + BucketKey { + counts, + update_after_bind, + } + } +} + +impl DescriptorAllocator { + pub fn new(max_update_after_bind_descriptors_in_all_pools: u32) -> Self { + DescriptorAllocator { + buckets: HashMap::default(), + max_update_after_bind_descriptors_in_all_pools, + update_after_bind_descriptors_in_all_pools: 0, + } + } + + pub fn register_layout( + &mut self, + device: &ash::Device, + layout: &super::BindGroupLayout, + ) -> Result<(), crate::DeviceError> { + let key = layout.bucket_key(); + let bucket = match self.buckets.entry(key) { + hashbrown::hash_map::Entry::Occupied(occupied_entry) => occupied_entry.into_mut(), + hashbrown::hash_map::Entry::Vacant(vacant_entry) => { + let mut bucket = Bucket::default(); + // Create at least 1 pool upfront instead of doing this when + // creating the first bind group. + bucket.create_pool(device, vacant_entry.key(), POOL_MIN_SETS)?; + vacant_entry.insert(bucket) + } + }; + + assert!(bucket.layouts.insert(layout.raw)); + + Ok(()) + } + + pub fn unregister_layout(&mut self, device: &ash::Device, layout: &super::BindGroupLayout) { + let key = layout.bucket_key(); + let bucket = self.buckets.get_mut(&key).unwrap(); + + assert!(bucket.layouts.remove(&layout.raw)); + + if bucket.layouts.is_empty() { + // Remove the bucket and destroy any remaining pools. + let bucket = self.buckets.remove(&key).unwrap(); + for pool in bucket.pools { + assert_eq!( + pool.available, pool.capacity, + "pool is not empty, at least one DescriptorSet has not been freed" + ); + unsafe { device.destroy_descriptor_pool(pool.raw, None) }; + } + } + } + + pub unsafe fn alloc( + &mut self, + device: &ash::Device, + layout: &super::BindGroupLayout, + ) -> Result<DescriptorSet, crate::DeviceError> { + let update_after_bind = layout.contains_binding_arrays; + let total_descriptors = layout.desc_count.total(); + + if update_after_bind + && self.max_update_after_bind_descriptors_in_all_pools + - self.update_after_bind_descriptors_in_all_pools + < total_descriptors + { + return Err(crate::DeviceError::OutOfMemory); + } + + let key = layout.bucket_key(); + let bucket = self.buckets.get_mut(&key).unwrap(); + + // Prefer smaller/older/fuller pools for new allocations to prevent + // fragmentation and possibly fragmentation of hardware resources + // (VK_ERROR_FRAGMENTATION) + let pool = bucket + .pools + .iter_mut() + .enumerate() + .find(|(_, pool)| pool.available != 0); + + let (pool_index, pool) = if let Some(pool) = pool { + pool + } else { + let capacity_hint = bucket.allocated_sets; + bucket.create_pool(device, &key, capacity_hint)? + }; + + let vk_info = vk::DescriptorSetAllocateInfo::default() + .descriptor_pool(pool.raw) + .set_layouts(core::slice::from_ref(&layout.raw)); + + let raw = match unsafe { device.allocate_descriptor_sets(&vk_info) } { + Ok(sets) => Ok(sets[0]), + // We make sure not to exceed the size of the pool. + Err(vk::Result::ERROR_OUT_OF_POOL_MEMORY) => unreachable!(), + // We only allocate from a pool if the nr and type of descriptors + // used by a layout is the same as those specified at pool + // creation time. + // + // > Additionally, if all sets allocated from the pool since it was + // created or most recently reset use the same number of + // descriptors (of each type) and the requested allocation also + // uses that same number of descriptors (of each type), + // then fragmentation must not cause an allocation failure. + // + // from https://docs.vulkan.org/refpages/latest/refpages/source/VkDescriptorPoolCreateInfo.html#_description + Err(vk::Result::ERROR_FRAGMENTED_POOL) => unreachable!(), + Err(err) => Err(super::map_host_device_oom_err(err)), + }?; + + pool.available -= 1; + bucket.available_sets -= 1; + bucket.allocated_sets += 1; + if update_after_bind { + self.update_after_bind_descriptors_in_all_pools += total_descriptors; + } + + Ok(DescriptorSet { + raw, + bucket_key: key, + pool_index, + }) + } + + pub unsafe fn free(&mut self, device: &ash::Device, set: DescriptorSet) { + let bucket = self.buckets.get_mut(&set.bucket_key).unwrap(); + let pool = bucket.pools.get_mut(set.pool_index).unwrap(); + + let result = + unsafe { device.free_descriptor_sets(pool.raw, core::slice::from_ref(&set.raw())) }; + if let Err(err) = result { + // vkFreeDescriptorSets is documented to return: + // - VK_ERROR_UNKNOWN + // - VK_ERROR_VALIDATION_FAILED (we shouldn't encounter this one) + // wgpu-hal doesn't currently report errors in destroy functions. + // Panic here for now. It might be ok to ignore the error but the + // proper solution would probably be to lose the device. + panic!("vkFreeDescriptorSets error: {err}, please report this error"); + } + + pool.available += 1; + bucket.available_sets += 1; + bucket.allocated_sets -= 1; + if set.bucket_key.update_after_bind { + self.update_after_bind_descriptors_in_all_pools -= set.bucket_key.counts.total(); + } + + // Do not immediately destroy empty pools since they might have + // been recently created. + // Destroy a pool only if it's empty and we have 1/4th its capacity + // in other pools. + // Note that this logic will never destroy the last pool. + let pool = bucket.pools.last().unwrap(); + if pool.available == pool.capacity + && bucket.available_sets - pool.capacity > pool.capacity / 4 + { + let pool = bucket.pools.pop().unwrap(); + unsafe { device.destroy_descriptor_pool(pool.raw, None) }; + bucket.available_sets -= pool.capacity; + } + } +} + +impl Drop for DescriptorAllocator { + fn drop(&mut self) { + if !std::thread::panicking() { + assert!( + self.buckets.is_empty(), + "buckets are not empty, at least one BGL has not been unregistered" + ) + } + } +} + +fn create_descriptor_pool( + device: &ash::Device, + key: &BucketKey, + capacity_hint: u32, +) -> Result<Pool, crate::DeviceError> { + let counts = &key.counts; + + const NR_OF_DESCRIPTOR_TYPES: usize = 8; + + use vk::DescriptorType as Dt; + let counts: [_; NR_OF_DESCRIPTOR_TYPES] = [ + (Dt::SAMPLER, counts.sampler), + (Dt::SAMPLED_IMAGE, counts.sampled_image), + (Dt::STORAGE_IMAGE, counts.storage_image), + (Dt::UNIFORM_BUFFER, counts.uniform_buffer), + (Dt::UNIFORM_BUFFER_DYNAMIC, counts.uniform_buffer_dynamic), + (Dt::STORAGE_BUFFER, counts.storage_buffer), + (Dt::STORAGE_BUFFER_DYNAMIC, counts.storage_buffer_dynamic), + ( + Dt::ACCELERATION_STRUCTURE_KHR, + counts.acceleration_structure, + ), + ]; + + // bounded doubling growth strategy + let mut capacity = capacity_hint + .clamp(POOL_MIN_SETS, POOL_MAX_SETS) + .next_power_of_two(); + + // Lower capacity to avoid overflowing `count * capacity` calculations + // below. The resulting `capacity` might not be a power of 2 but that's + // ok. + for (_, count) in counts { + capacity = (u32::MAX / count.max(1)).min(capacity); + } + + let pool_sizes = counts + .into_iter() + .filter(|&(_, count)| count != 0) + .map(|(ty, count)| vk::DescriptorPoolSize { + ty, + descriptor_count: count * capacity, + }) + .collect::<ArrayVec<_, NR_OF_DESCRIPTOR_TYPES>>(); + + let mut flags = vk::DescriptorPoolCreateFlags::FREE_DESCRIPTOR_SET; + if key.update_after_bind { + flags |= vk::DescriptorPoolCreateFlags::UPDATE_AFTER_BIND; + }; + + let vk_info = vk::DescriptorPoolCreateInfo::default() + .flags(flags) + .max_sets(capacity) + .pool_sizes(&pool_sizes); + + let raw = unsafe { device.create_descriptor_pool(&vk_info, None) } + .map_err(super::map_host_device_oom_and_fragmentation_err)?; + + Ok(Pool { + raw, + capacity, + available: capacity, + }) +} diff --git a/app/vendor/rune/vendor/wgpu-hal/src/vulkan/device.rs b/app/vendor/rune/vendor/wgpu-hal/src/vulkan/device.rs new file mode 100644 index 0000000..948f77a --- /dev/null +++ b/app/vendor/rune/vendor/wgpu-hal/src/vulkan/device.rs @@ -0,0 +1,3116 @@ +use alloc::{borrow::ToOwned as _, collections::BTreeMap, ffi::CString, sync::Arc, vec::Vec}; +use core::{ + ffi::CStr, + mem::{self, MaybeUninit}, + num::NonZeroU32, + ptr, + time::Duration, +}; + +use arrayvec::ArrayVec; +use ash::{ext, vk}; +use hashbrown::hash_map::Entry; +use parking_lot::{Mutex, RwLock}; + +use super::{conv, descriptor::DescriptorCounts, RawTlasInstance}; +use crate::TlasInstance; + +impl super::DeviceShared { + /// Set the name of `object` to `name`. + /// + /// If `name` contains an interior null byte, then the name set will be truncated to that byte. + /// + /// # Safety + /// + /// This method inherits the safety contract from [`vkSetDebugUtilsObjectName`]. In particular: + /// + /// - `object` must be a valid handle for one of the following: + /// - An instance-level object from the same instance as this device. + /// - A physical-device-level object that descends from the same physical device as this + /// device. + /// - A device-level object that descends from this device. + /// - `object` must be externally synchronized—only the calling thread should access it during + /// this call. + /// + /// [`vkSetDebugUtilsObjectName`]: https://registry.khronos.org/vulkan/specs/latest/man/html/vkSetDebugUtilsObjectNameEXT.html + pub(super) unsafe fn set_object_name(&self, object: impl vk::Handle, name: &str) { + let Some(extension) = self.extension_fns.debug_utils.as_ref() else { + return; + }; + + // Keep variables outside the if-else block to ensure they do not + // go out of scope while we hold a pointer to them + let mut buffer: [u8; 64] = [0u8; 64]; + let buffer_vec: Vec<u8>; + + // Append a null terminator to the string + let name_bytes = if name.len() < buffer.len() { + // Common case, string is very small. Allocate a copy on the stack. + buffer[..name.len()].copy_from_slice(name.as_bytes()); + // Add null terminator + buffer[name.len()] = 0; + &buffer[..name.len() + 1] + } else { + // Less common case, the string is large. + // This requires a heap allocation. + buffer_vec = name + .as_bytes() + .iter() + .cloned() + .chain(core::iter::once(0)) + .collect(); + &buffer_vec + }; + + let name = CStr::from_bytes_until_nul(name_bytes).expect("We have added a null byte"); + + let _result = unsafe { + extension.set_debug_utils_object_name( + &vk::DebugUtilsObjectNameInfoEXT::default() + .object_handle(object) + .object_name(name), + ) + }; + } + + pub fn make_render_pass( + &self, + key: super::RenderPassKey, + ) -> Result<vk::RenderPass, crate::DeviceError> { + Ok(match self.render_passes.lock().entry(key) { + Entry::Occupied(e) => *e.get(), + Entry::Vacant(e) => { + let super::RenderPassKey { + ref colors, + ref depth_stencil, + sample_count, + multiview_mask, + } = *e.key(); + + let mut vk_attachments = Vec::new(); + let mut color_refs = Vec::with_capacity(colors.len()); + let mut resolve_refs = Vec::with_capacity(color_refs.capacity()); + let mut ds_ref = None; + let samples = vk::SampleCountFlags::from_raw(sample_count); + let unused = vk::AttachmentReference { + attachment: vk::ATTACHMENT_UNUSED, + layout: vk::ImageLayout::UNDEFINED, + }; + for cat in colors.iter() { + let (color_ref, resolve_ref) = + if let Some(super::ColorAttachmentKey { base, resolve }) = cat { + let super::AttachmentKey { + format, + layout, + ops, + } = *base; + + let color_ref = vk::AttachmentReference { + attachment: vk_attachments.len() as u32, + layout, + }; + vk_attachments.push({ + let (load_op, store_op) = conv::map_attachment_ops(ops); + vk::AttachmentDescription::default() + .format(format) + .samples(samples) + .load_op(load_op) + .store_op(store_op) + .initial_layout(layout) + .final_layout(layout) + }); + let resolve_ref = if let Some(rat) = resolve { + let super::AttachmentKey { + format, + layout, + ops, + } = *rat; + + let (load_op, store_op) = conv::map_attachment_ops(ops); + let vk_attachment = vk::AttachmentDescription::default() + .format(format) + .samples(vk::SampleCountFlags::TYPE_1) + .load_op(load_op) + .store_op(store_op) + .initial_layout(layout) + .final_layout(layout); + vk_attachments.push(vk_attachment); + + vk::AttachmentReference { + attachment: vk_attachments.len() as u32 - 1, + layout, + } + } else { + unused + }; + + (color_ref, resolve_ref) + } else { + (unused, unused) + }; + + color_refs.push(color_ref); + resolve_refs.push(resolve_ref); + } + + if let Some(ds) = depth_stencil { + let super::DepthStencilAttachmentKey { + ref base, + stencil_ops, + } = *ds; + + let super::AttachmentKey { + format, + layout, + ops, + } = *base; + + ds_ref = Some(vk::AttachmentReference { + attachment: vk_attachments.len() as u32, + layout, + }); + let (load_op, store_op) = conv::map_attachment_ops(ops); + let (stencil_load_op, stencil_store_op) = conv::map_attachment_ops(stencil_ops); + let vk_attachment = vk::AttachmentDescription::default() + .format(format) + .samples(samples) + .load_op(load_op) + .store_op(store_op) + .stencil_load_op(stencil_load_op) + .stencil_store_op(stencil_store_op) + .initial_layout(layout) + .final_layout(layout); + vk_attachments.push(vk_attachment); + } + + let vk_subpasses = [{ + let mut vk_subpass = vk::SubpassDescription::default() + .pipeline_bind_point(vk::PipelineBindPoint::GRAPHICS) + .color_attachments(&color_refs) + .resolve_attachments(&resolve_refs); + + if self + .workarounds + .contains(super::Workarounds::EMPTY_RESOLVE_ATTACHMENT_LISTS) + && resolve_refs.is_empty() + { + vk_subpass.p_resolve_attachments = ptr::null(); + } + + if let Some(ref reference) = ds_ref { + vk_subpass = vk_subpass.depth_stencil_attachment(reference) + } + vk_subpass + }]; + + let mut vk_info = vk::RenderPassCreateInfo::default() + .attachments(&vk_attachments) + .subpasses(&vk_subpasses); + + let mut multiview_info; + let mask; + if let Some(multiview_mask) = multiview_mask { + mask = [multiview_mask.get()]; + + // On Vulkan 1.1 or later, this is an alias for core functionality + multiview_info = vk::RenderPassMultiviewCreateInfoKHR::default() + .view_masks(&mask) + .correlation_masks(&mask); + vk_info = vk_info.push_next(&mut multiview_info); + } + + let raw = unsafe { + self.raw + .create_render_pass(&vk_info, None) + .map_err(super::map_host_device_oom_err)? + }; + + *e.insert(raw) + } + }) + } + + fn make_memory_ranges<'a, I: 'a + Iterator<Item = crate::MemoryRange>>( + &self, + buffer: &'a super::Buffer, + ranges: I, + ) -> Option<impl 'a + Iterator<Item = vk::MappedMemoryRange<'a>>> { + let super::BufferOwnership::Managed(ref allocation) = buffer.ownership else { + return None; + }; + let allocation = allocation.lock(); + let mask = self.private_caps.non_coherent_map_mask; + Some(ranges.map(move |range| { + vk::MappedMemoryRange::default() + .memory(allocation.memory()) + .offset((allocation.offset() + range.start) & !mask) + .size((range.end - range.start + mask) & !mask) + })) + } +} + +struct CompiledStage { + create_info: vk::PipelineShaderStageCreateInfo<'static>, + _entry_point: CString, + temp_raw_module: Option<vk::ShaderModule>, +} + +struct MemoryProperties { + base: vk::PhysicalDeviceMemoryProperties, + heap_budget: ArrayVec<vk::DeviceSize, { vk::MAX_MEMORY_HEAPS }>, + heap_usage: ArrayVec<vk::DeviceSize, { vk::MAX_MEMORY_HEAPS }>, +} + +impl MemoryProperties { + fn types(&self) -> &[vk::MemoryType] { + let count = self.base.memory_type_count as usize; + &self.base.memory_types[0..count] + } + + fn heaps(&self) -> &[vk::MemoryHeap] { + let count = self.base.memory_heap_count as usize; + &self.base.memory_heaps[0..count] + } + + fn heap_budget(&self) -> &[vk::DeviceSize] { + let count = self.base.memory_heap_count as usize; + &self.heap_budget[0..count] + } + + fn heap_usage(&self) -> &[vk::DeviceSize] { + let count = self.base.memory_heap_count as usize; + &self.heap_usage[0..count] + } +} + +impl super::Device { + /// # Safety + /// + /// - `vk_image` must be created respecting `desc` + /// - If `drop_callback` is [`None`], wgpu-hal will take ownership of `vk_image`. If + /// `drop_callback` is [`Some`], `vk_image` must be valid until the callback is called. + /// - If the `ImageCreateFlags` does not contain `MUTABLE_FORMAT`, the `view_formats` of `desc` must be empty. + /// - If `memory` is not [`super::TextureMemory::External`], wgpu-hal will take ownership of the + /// memory (which is presumed to back `vk_image`). Otherwise, the memory must remain valid until + /// `drop_callback` is called. + pub unsafe fn texture_from_raw( + &self, + vk_image: vk::Image, + desc: &crate::TextureDescriptor, + drop_callback: Option<crate::DropCallback>, + memory: super::TextureMemory, + ) -> super::Texture { + let identity = self.shared.texture_identity_factory.next(); + let drop_guard = crate::DropGuard::from_option(drop_callback); + + if let Some(label) = desc.label { + unsafe { self.shared.set_object_name(vk_image, label) }; + } + + super::Texture { + raw: vk_image, + drop_guard, + memory, + format: desc.format, + copy_size: desc.copy_extent(), + identity, + } + } + + fn find_memory_type_index( + &self, + type_bits_req: u32, + flags_req: vk::MemoryPropertyFlags, + ) -> Option<usize> { + let mem_properties = unsafe { + self.shared + .instance + .raw + .get_physical_device_memory_properties(self.shared.physical_device) + }; + + // https://registry.khronos.org/vulkan/specs/1.3-extensions/man/html/VkPhysicalDeviceMemoryProperties.html + for (i, mem_ty) in mem_properties.memory_types_as_slice().iter().enumerate() { + let types_bits = 1 << i; + let is_required_memory_type = type_bits_req & types_bits != 0; + let has_required_properties = mem_ty.property_flags & flags_req == flags_req; + if is_required_memory_type && has_required_properties { + return Some(i); + } + } + + None + } + + fn create_image_without_memory( + &self, + desc: &crate::TextureDescriptor, + external_memory_image_create_info: Option<&mut vk::ExternalMemoryImageCreateInfo>, + ) -> Result<ImageWithoutMemory, crate::DeviceError> { + self.create_image_without_memory_with_tiling( + desc, + vk::ImageTiling::OPTIMAL, + external_memory_image_create_info, + None, + ) + } + + fn create_image_without_memory_with_tiling( + &self, + desc: &crate::TextureDescriptor, + tiling: vk::ImageTiling, + external_memory_image_create_info: Option<&mut vk::ExternalMemoryImageCreateInfo>, + drm_modifier_info: Option<&mut vk::ImageDrmFormatModifierExplicitCreateInfoEXT>, + ) -> Result<ImageWithoutMemory, crate::DeviceError> { + let copy_size = desc.copy_extent(); + + let mut raw_flags = vk::ImageCreateFlags::empty(); + if desc.dimension == wgt::TextureDimension::D3 + && desc.usage.contains(wgt::TextureUses::COLOR_TARGET) + { + raw_flags |= vk::ImageCreateFlags::TYPE_2D_ARRAY_COMPATIBLE; + } + if desc.is_cube_compatible() { + raw_flags |= vk::ImageCreateFlags::CUBE_COMPATIBLE; + } + + let original_format = self.shared.private_caps.map_texture_format(desc.format); + let mut vk_view_formats = vec![]; + if !desc.view_formats.is_empty() { + raw_flags |= vk::ImageCreateFlags::MUTABLE_FORMAT; + + if self.shared.private_caps.image_format_list { + vk_view_formats = desc + .view_formats + .iter() + .map(|f| self.shared.private_caps.map_texture_format(*f)) + .collect(); + vk_view_formats.push(original_format) + } + } + if desc.format.is_multi_planar_format() { + raw_flags |= + vk::ImageCreateFlags::MUTABLE_FORMAT | vk::ImageCreateFlags::EXTENDED_USAGE; + } + + let mut vk_info = vk::ImageCreateInfo::default() + .flags(raw_flags) + .image_type(conv::map_texture_dimension(desc.dimension)) + .format(original_format) + .extent(conv::map_copy_extent(&copy_size)) + .mip_levels(desc.mip_level_count) + .array_layers(desc.array_layer_count()) + .samples(vk::SampleCountFlags::from_raw(desc.sample_count)) + .tiling(tiling) + .usage(conv::map_texture_usage(desc.usage)) + .sharing_mode(vk::SharingMode::EXCLUSIVE) + .initial_layout(vk::ImageLayout::UNDEFINED); + + let mut format_list_info = vk::ImageFormatListCreateInfo::default(); + if !vk_view_formats.is_empty() { + format_list_info = format_list_info.view_formats(&vk_view_formats); + vk_info = vk_info.push_next(&mut format_list_info); + } + + if let Some(ext_info) = external_memory_image_create_info { + vk_info = vk_info.push_next(ext_info); + } + + if let Some(drm_info) = drm_modifier_info { + vk_info = vk_info.push_next(drm_info); + } + + let raw = unsafe { self.shared.raw.create_image(&vk_info, None) }.map_err(map_err)?; + fn map_err(err: vk::Result) -> crate::DeviceError { + // We don't use VK_EXT_image_compression_control + // VK_ERROR_COMPRESSION_EXHAUSTED_EXT + super::map_host_device_oom_and_ioca_err(err) + } + let mut req = unsafe { self.shared.raw.get_image_memory_requirements(raw) }; + + if desc.usage.contains(wgt::TextureUses::TRANSIENT) { + let mem_type_index = self.find_memory_type_index( + req.memory_type_bits, + vk::MemoryPropertyFlags::LAZILY_ALLOCATED, + ); + if let Some(mem_type_index) = mem_type_index { + req.memory_type_bits = 1 << mem_type_index; + } + } + + Ok(ImageWithoutMemory { + raw, + requirements: req, + }) + } + + /// # Safety + /// + /// - Vulkan (with VK_KHR_external_memory_win32) + /// - The `d3d11_shared_handle` must be valid and respecting `desc` + /// - `VK_EXTERNAL_MEMORY_HANDLE_TYPE_D3D11_TEXTURE_BIT` flag is used because we need to hold a reference to the handle + #[cfg(windows)] + pub unsafe fn texture_from_d3d11_shared_handle( + &self, + d3d11_shared_handle: windows::Win32::Foundation::HANDLE, + desc: &crate::TextureDescriptor, + ) -> Result<super::Texture, crate::DeviceError> { + if !self + .shared + .features + .contains(wgt::Features::VULKAN_EXTERNAL_MEMORY_WIN32) + { + log::error!("Vulkan driver does not support VK_KHR_external_memory_win32"); + return Err(crate::DeviceError::Unexpected); + } + + let mut external_memory_image_info = vk::ExternalMemoryImageCreateInfo::default() + .handle_types(vk::ExternalMemoryHandleTypeFlags::D3D11_TEXTURE); + + let image = + self.create_image_without_memory(desc, Some(&mut external_memory_image_info))?; + + // Some external memory types require dedicated allocation + // https://docs.vulkan.org/guide/latest/extensions/external.html#_importing_memory + let mut dedicated_allocate_info = + vk::MemoryDedicatedAllocateInfo::default().image(image.raw); + + let mut import_memory_info = vk::ImportMemoryWin32HandleInfoKHR::default() + .handle_type(vk::ExternalMemoryHandleTypeFlags::D3D11_TEXTURE) + .handle(d3d11_shared_handle.0 as _); + // TODO: We should use `push_next` instead, but currently ash does not provide this method for the `ImportMemoryWin32HandleInfoKHR` type. + #[allow(clippy::unnecessary_mut_passed)] + { + import_memory_info.p_next = <*const _>::cast(&mut dedicated_allocate_info); + } + + let mem_type_index = self + .find_memory_type_index( + image.requirements.memory_type_bits, + vk::MemoryPropertyFlags::DEVICE_LOCAL, + ) + .ok_or(crate::DeviceError::Unexpected)?; + + let memory_allocate_info = vk::MemoryAllocateInfo::default() + .allocation_size(image.requirements.size) + .memory_type_index(mem_type_index as _) + .push_next(&mut import_memory_info); + let memory = unsafe { self.shared.raw.allocate_memory(&memory_allocate_info, None) } + .map_err(super::map_host_device_oom_err)?; + + unsafe { self.shared.raw.bind_image_memory(image.raw, memory, 0) } + .map_err(super::map_host_device_oom_err)?; + + Ok(unsafe { + self.texture_from_raw( + image.raw, + desc, + None, + super::TextureMemory::Dedicated(memory), + ) + }) + } + + /// Import a DMA-buf as a texture. Currently only supports single-plane DMA-bufs. + /// + /// # Safety + /// + /// - Requires `VULKAN_EXTERNAL_MEMORY_DMA_BUF` feature (implies VK_EXT_external_memory_dma_buf + /// and VK_EXT_image_drm_format_modifier) + /// - The `fd` must be a valid DMA-buf file descriptor matching `desc` + /// - On success, Vulkan takes ownership of the file descriptor. On failure, + /// the file descriptor is closed. + /// - The `drm_modifier`, `stride`, and `offset` must match the DMA-buf layout + #[cfg(unix)] + pub unsafe fn texture_from_dmabuf_fd( + &self, + fd: std::os::unix::io::OwnedFd, + desc: &crate::TextureDescriptor, + drm_modifier: u64, + stride: u64, + offset: u64, + ) -> Result<super::Texture, crate::DeviceError> { + use std::os::unix::io::IntoRawFd; + + if !self + .shared + .features + .contains(wgt::Features::VULKAN_EXTERNAL_MEMORY_DMA_BUF) + { + log::error!( + "Vulkan driver does not support VK_EXT_external_memory_dma_buf \ + or VK_EXT_image_drm_format_modifier" + ); + return Err(crate::DeviceError::Unexpected); + } + + let external_memory_fd_fn = self + .shared + .extension_fns + .external_memory_fd + .as_ref() + .ok_or_else(|| { + log::error!("VK_KHR_external_memory_fd extension not loaded"); + crate::DeviceError::Unexpected + })?; + + let mut external_memory_image_info = vk::ExternalMemoryImageCreateInfo::default() + .handle_types(vk::ExternalMemoryHandleTypeFlags::DMA_BUF_EXT); + + let plane_layout = vk::SubresourceLayout { + offset, + row_pitch: stride, + size: 0, + array_pitch: 0, + depth_pitch: 0, + }; + let mut drm_modifier_info = vk::ImageDrmFormatModifierExplicitCreateInfoEXT::default() + .drm_format_modifier(drm_modifier) + .plane_layouts(core::slice::from_ref(&plane_layout)); + + let image = self.create_image_without_memory_with_tiling( + desc, + vk::ImageTiling::DRM_FORMAT_MODIFIER_EXT, + Some(&mut external_memory_image_info), + Some(&mut drm_modifier_info), + )?; + + // Convert to raw fd. We must close it ourselves if any operation below + // fails, since Vulkan only takes ownership on successful vkAllocateMemory. + let fd_raw = fd.into_raw_fd(); + + let result = self.import_dmabuf_memory( + external_memory_fd_fn, + fd_raw, + image.raw, + &image.requirements, + ); + + match result { + Ok(memory) => Ok(unsafe { + self.texture_from_raw( + image.raw, + desc, + None, + super::TextureMemory::Dedicated(memory), + ) + }), + Err(e) => { + // Clean up the VkImage on failure. + unsafe { self.shared.raw.destroy_image(image.raw, None) }; + Err(e) + } + } + } + + /// Import DMA-buf memory and bind it to the image. + /// + /// On failure, the raw fd is closed (if not yet consumed by Vulkan) and the + /// caller is responsible for destroying the VkImage. + #[cfg(unix)] + fn import_dmabuf_memory( + &self, + external_memory_fd_fn: &ash::khr::external_memory_fd::Device, + fd_raw: i32, + image: vk::Image, + requirements: &vk::MemoryRequirements, + ) -> Result<vk::DeviceMemory, crate::DeviceError> { + let mut fd_props = vk::MemoryFdPropertiesKHR::default(); + unsafe { + external_memory_fd_fn.get_memory_fd_properties( + vk::ExternalMemoryHandleTypeFlags::DMA_BUF_EXT, + fd_raw, + &mut fd_props, + ) + } + .map_err(|e| { + unsafe { libc::close(fd_raw) }; + super::map_host_device_oom_err(e) + })?; + + let mem_type_index = self + .find_memory_type_index( + requirements.memory_type_bits & fd_props.memory_type_bits, + vk::MemoryPropertyFlags::empty(), + ) + .ok_or_else(|| { + unsafe { libc::close(fd_raw) }; + crate::DeviceError::Unexpected + })?; + + let mut dedicated_allocate_info = vk::MemoryDedicatedAllocateInfo::default().image(image); + + let mut import_memory_info = vk::ImportMemoryFdInfoKHR::default() + .handle_type(vk::ExternalMemoryHandleTypeFlags::DMA_BUF_EXT) + .fd(fd_raw); + + let memory_allocate_info = vk::MemoryAllocateInfo::default() + .allocation_size(requirements.size) + .memory_type_index(mem_type_index as _) + .push_next(&mut import_memory_info) + .push_next(&mut dedicated_allocate_info); + + // vkAllocateMemory takes ownership of the fd on success. + // On failure, the fd is NOT consumed and we must close it. + let memory = unsafe { self.shared.raw.allocate_memory(&memory_allocate_info, None) } + .map_err(|e| { + unsafe { libc::close(fd_raw) }; + super::map_host_device_oom_err(e) + })?; + + // From this point, the fd is consumed. Only VkDeviceMemory needs cleanup on error. + unsafe { self.shared.raw.bind_image_memory(image, memory, 0) }.map_err(|e| { + unsafe { self.shared.raw.free_memory(memory, None) }; + super::map_host_device_oom_err(e) + })?; + + Ok(memory) + } + + fn create_shader_module_impl( + &self, + spv: &[u32], + label: &crate::Label<'_>, + ) -> Result<vk::ShaderModule, crate::DeviceError> { + let vk_info = vk::ShaderModuleCreateInfo::default() + .flags(vk::ShaderModuleCreateFlags::empty()) + .code(spv); + + let raw = unsafe { + profiling::scope!("vkCreateShaderModule"); + self.shared + .raw + .create_shader_module(&vk_info, None) + .map_err(map_err)? + }; + fn map_err(err: vk::Result) -> crate::DeviceError { + // We don't use VK_NV_glsl_shader + // VK_ERROR_INVALID_SHADER_NV + super::map_host_device_oom_err(err) + } + + if let Some(label) = label { + unsafe { self.shared.set_object_name(raw, label) }; + } + + Ok(raw) + } + + fn compile_stage( + &self, + stage: &crate::ProgrammableStage<super::ShaderModule>, + naga_stage: naga::ShaderStage, + binding_map: &naga::back::spv::BindingMap, + ) -> Result<CompiledStage, crate::PipelineError> { + let stage_flags = crate::auxil::map_naga_stage(naga_stage); + let vk_module = match *stage.module { + super::ShaderModule::Raw(raw) => raw, + super::ShaderModule::Intermediate { + ref naga_shader, + runtime_checks, + } => { + let pipeline_options = naga::back::spv::PipelineOptions { + entry_point: stage.entry_point.to_owned(), + shader_stage: naga_stage, + }; + let needs_temp_options = !runtime_checks.bounds_checks + || !runtime_checks.force_loop_bounding + || !runtime_checks.ray_query_initialization_tracking + || !binding_map.is_empty() + || naga_shader.debug_source.is_some() + || !stage.zero_initialize_workgroup_memory + || !runtime_checks.task_shader_dispatch_tracking + || !runtime_checks.mesh_shader_primitive_indices_clamp + || !runtime_checks.int_div_checks; + + let mut temp_options; + let options = if needs_temp_options { + temp_options = self.naga_options.clone(); + if !runtime_checks.bounds_checks { + temp_options.bounds_check_policies = naga::proc::BoundsCheckPolicies { + index: naga::proc::BoundsCheckPolicy::Unchecked, + buffer: naga::proc::BoundsCheckPolicy::Unchecked, + image_load: naga::proc::BoundsCheckPolicy::Unchecked, + binding_array: naga::proc::BoundsCheckPolicy::Unchecked, + }; + } + if !runtime_checks.force_loop_bounding { + temp_options.force_loop_bounding = false; + } + if !runtime_checks.ray_query_initialization_tracking { + temp_options.ray_query_initialization_tracking = false; + } + if !binding_map.is_empty() { + temp_options.binding_map = binding_map.clone(); + } + + if let Some(ref debug) = naga_shader.debug_source { + temp_options.debug_info = Some(naga::back::spv::DebugInfo { + source_code: &debug.source_code, + file_name: debug.file_name.as_ref(), + language: naga::back::spv::SourceLanguage::WGSL, + }) + } + if !stage.zero_initialize_workgroup_memory { + temp_options.zero_initialize_workgroup_memory = + naga::back::spv::ZeroInitializeWorkgroupMemoryMode::None; + } + if !runtime_checks.task_shader_dispatch_tracking { + temp_options.task_dispatch_limits = None; + } + temp_options.mesh_shader_primitive_indices_clamp = + runtime_checks.mesh_shader_primitive_indices_clamp; + temp_options.emit_int_div_checks = runtime_checks.int_div_checks; + + &temp_options + } else { + &self.naga_options + }; + + let (module, info) = naga::back::pipeline_constants::process_overrides( + &naga_shader.module, + &naga_shader.info, + Some((naga_stage, stage.entry_point)), + stage.constants, + ) + .map_err(|e| { + crate::PipelineError::PipelineConstants(stage_flags, format!("{e}")) + })?; + + let spv = { + profiling::scope!("naga::spv::write_vec"); + naga::back::spv::write_vec(&module, &info, options, Some(&pipeline_options)) + } + .map_err(|e| crate::PipelineError::Linkage(stage_flags, format!("{e}")))?; + self.create_shader_module_impl(&spv, &None)? + } + }; + + let mut flags = vk::PipelineShaderStageCreateFlags::empty(); + if self.shared.features.contains(wgt::Features::SUBGROUP) { + flags |= vk::PipelineShaderStageCreateFlags::ALLOW_VARYING_SUBGROUP_SIZE + } + + let entry_point = CString::new(stage.entry_point).unwrap(); + let mut create_info = vk::PipelineShaderStageCreateInfo::default() + .flags(flags) + .stage(conv::map_shader_stage(stage_flags)) + .module(vk_module); + + // Circumvent struct lifetime check because of a self-reference inside CompiledStage + create_info.p_name = entry_point.as_ptr(); + + Ok(CompiledStage { + create_info, + _entry_point: entry_point, + temp_raw_module: match *stage.module { + super::ShaderModule::Raw(_) => None, + super::ShaderModule::Intermediate { .. } => Some(vk_module), + }, + }) + } + + /// Returns the queue family index of the device's internal queue. + /// + /// This is useful for constructing memory barriers needed for queue family ownership transfer when + /// external memory is involved (from/to `VK_QUEUE_FAMILY_EXTERNAL_KHR` and `VK_QUEUE_FAMILY_FOREIGN_EXT` + /// for example). + pub fn queue_family_index(&self) -> u32 { + self.shared.family_index + } + + pub fn queue_index(&self) -> u32 { + self.shared.queue_index + } + + pub fn raw_device(&self) -> &ash::Device { + &self.shared.raw + } + + pub fn raw_physical_device(&self) -> vk::PhysicalDevice { + self.shared.physical_device + } + + pub fn raw_queue(&self) -> vk::Queue { + self.shared.raw_queue + } + + pub fn enabled_device_extensions(&self) -> &[&'static CStr] { + &self.shared.enabled_extensions + } + + pub fn shared_instance(&self) -> &super::InstanceShared { + &self.shared.instance + } + + fn get_memory_properties(&self) -> Option<MemoryProperties> { + if !self + .shared + .enabled_extensions + .contains(&ext::memory_budget::NAME) + { + return None; + } + + let get_physical_device_properties = self + .shared + .instance + .get_physical_device_properties + .as_ref() + .unwrap(); + + let mut budget = vk::PhysicalDeviceMemoryBudgetPropertiesEXT::default(); + let mut props = vk::PhysicalDeviceMemoryProperties2::default().push_next(&mut budget); + + unsafe { + get_physical_device_properties + .get_physical_device_memory_properties2(self.shared.physical_device, &mut props); + } + + let vk::PhysicalDeviceMemoryProperties2 { + memory_properties, .. + } = props; + + let mut heap_budget = ArrayVec::from(budget.heap_budget); + let mut heap_usage = ArrayVec::from(budget.heap_usage); + heap_budget.truncate(memory_properties.memory_heap_count as usize); + heap_usage.truncate(memory_properties.memory_heap_count as usize); + + Some(MemoryProperties { + base: memory_properties, + heap_budget, + heap_usage, + }) + } + + /// Predict whether a proposed allocation will result in an OOM condition. + /// + /// If so, returns `Err(crate::DeviceError::OutOfMemory)`. If not, returns + /// `Ok(())`. + /// + /// The prediction quality depends on accurately selecting the heap that + /// [`gpu_allocator`] will use for the allocation, and is subject to + /// deteriorate if the logic in [`gpu_allocator`] changes. + fn error_if_would_oom_on_resource_allocation( + &self, + location: gpu_allocator::MemoryLocation, + requirements: &vk::MemoryRequirements, + ) -> Result<(), crate::DeviceError> { + use gpu_allocator::MemoryLocation; + + let Some(threshold) = self + .shared + .instance + .memory_budget_thresholds + .for_resource_creation + else { + return Ok(()); + }; + + let Some(memory_properties) = self.get_memory_properties() else { + return Ok(()); + }; + + // memory types not used by gpu-allocator + let invalid_flags = + vk::MemoryPropertyFlags::LAZILY_ALLOCATED | vk::MemoryPropertyFlags::PROTECTED; + + let preferred_flags = match location { + MemoryLocation::GpuOnly => vk::MemoryPropertyFlags::DEVICE_LOCAL, + MemoryLocation::CpuToGpu => { + vk::MemoryPropertyFlags::HOST_VISIBLE + | vk::MemoryPropertyFlags::HOST_COHERENT + | vk::MemoryPropertyFlags::DEVICE_LOCAL + } + MemoryLocation::GpuToCpu => { + vk::MemoryPropertyFlags::HOST_VISIBLE + | vk::MemoryPropertyFlags::HOST_COHERENT + | vk::MemoryPropertyFlags::HOST_CACHED + } + MemoryLocation::Unknown => vk::MemoryPropertyFlags::empty(), + }; + + let mut selected_heap = memory_properties + .types() + .iter() + .enumerate() + .find(|(i, ty)| { + (1 << i) & requirements.memory_type_bits != 0 + && ty.property_flags.contains(preferred_flags) + && !ty.property_flags.intersects(invalid_flags) + }); + + if selected_heap.is_none() { + let required_flags = match location { + MemoryLocation::GpuOnly => vk::MemoryPropertyFlags::DEVICE_LOCAL, + MemoryLocation::CpuToGpu | MemoryLocation::GpuToCpu => { + vk::MemoryPropertyFlags::HOST_VISIBLE | vk::MemoryPropertyFlags::HOST_COHERENT + } + MemoryLocation::Unknown => vk::MemoryPropertyFlags::empty(), + }; + selected_heap = memory_properties + .types() + .iter() + .enumerate() + .find(|(i, ty)| { + (1 << i) & requirements.memory_type_bits != 0 + && ty.property_flags.contains(required_flags) + && !ty.property_flags.intersects(invalid_flags) + }); + } + + if let Some((_, ty)) = selected_heap { + let i = ty.heap_index as usize; + let heap_usage = memory_properties.heap_usage()[i]; + let heap_budget = memory_properties.heap_budget()[i]; + if heap_usage + requirements.size < heap_budget / 100 * threshold as u64 { + Ok(()) + } else { + log::warn!( + "Allocation would result in an OOM condition\n\ + Request: {requirements:?}\n\ + Heap {index} had {heap_usage}B used of {heap_budget}B total before this request.", + index = ty.heap_index, + ); + Err(crate::DeviceError::OutOfMemory) + } + } else { + log::warn!("Failed to find a suitable heap for {requirements:?}"); + Err(crate::DeviceError::OutOfMemory) + } + } +} + +impl crate::Device for super::Device { + type A = super::Api; + + unsafe fn create_buffer( + &self, + desc: &crate::BufferDescriptor, + ) -> Result<super::Buffer, crate::DeviceError> { + let vk_info = vk::BufferCreateInfo::default() + .size(desc.size) + .usage(conv::map_buffer_usage(desc.usage)) + .sharing_mode(vk::SharingMode::EXCLUSIVE); + + let raw = unsafe { + self.shared + .raw + .create_buffer(&vk_info, None) + .map_err(super::map_host_device_oom_and_ioca_err)? + }; + + let mut requirements = unsafe { self.shared.raw.get_buffer_memory_requirements(raw) }; + + let is_cpu_read = desc.usage.contains(wgt::BufferUses::MAP_READ); + let is_cpu_write = desc.usage.contains(wgt::BufferUses::MAP_WRITE); + + let location = match (is_cpu_read, is_cpu_write) { + (true, true) => gpu_allocator::MemoryLocation::CpuToGpu, + (true, false) => gpu_allocator::MemoryLocation::GpuToCpu, + (false, true) => gpu_allocator::MemoryLocation::CpuToGpu, + (false, false) => gpu_allocator::MemoryLocation::GpuOnly, + }; + + self.error_if_would_oom_on_resource_allocation(location, &requirements) + .inspect_err(|_| { + unsafe { self.shared.raw.destroy_buffer(raw, None) }; + })?; + + let name = desc.label.unwrap_or("Unlabeled buffer"); + + if desc + .usage + .contains(wgt::BufferUses::ACCELERATION_STRUCTURE_SCRATCH) + { + // There is no way to specify this usage to Vulkan so we must make sure the alignment requirement is large enough. + requirements.alignment = requirements + .alignment + .max(self.shared.private_caps.scratch_buffer_alignment as u64); + } + + let allocation = self + .mem_allocator + .lock() + .allocate(&gpu_allocator::vulkan::AllocationCreateDesc { + name, + requirements: vk::MemoryRequirements { + memory_type_bits: requirements.memory_type_bits & self.valid_ash_memory_types, + ..requirements + }, + location, + linear: true, // Buffers are always linear + allocation_scheme: gpu_allocator::vulkan::AllocationScheme::GpuAllocatorManaged, + }) + .inspect_err(|_| { + unsafe { self.shared.raw.destroy_buffer(raw, None) }; + })?; + + unsafe { + self.shared + .raw + .bind_buffer_memory(raw, allocation.memory(), allocation.offset()) + } + .map_err(super::map_host_device_oom_and_ioca_err) + .inspect_err(|_| { + unsafe { self.shared.raw.destroy_buffer(raw, None) }; + })?; + + if let Some(label) = desc.label { + unsafe { self.shared.set_object_name(raw, label) }; + } + + self.counters.buffer_memory.add(allocation.size() as isize); + self.counters.buffers.add(1); + + Ok(super::Buffer { + raw, + ownership: super::BufferOwnership::Managed(Mutex::new( + super::BufferMemoryBacking::Managed(allocation), + )), + }) + } + unsafe fn destroy_buffer(&self, buffer: super::Buffer) { + match buffer.ownership { + super::BufferOwnership::Managed(allocation) => { + unsafe { self.shared.raw.destroy_buffer(buffer.raw, None) }; + let allocation = allocation.into_inner(); + self.counters.buffer_memory.sub(allocation.size() as isize); + match allocation { + super::BufferMemoryBacking::Managed(allocation) => { + let result = self.mem_allocator.lock().free(allocation); + if let Err(err) = result { + log::warn!("Failed to free buffer allocation: {err}"); + } + } + super::BufferMemoryBacking::VulkanMemory { memory, .. } => unsafe { + self.shared.raw.free_memory(memory, None); + }, + } + } + super::BufferOwnership::RawHandle => { + unsafe { self.shared.raw.destroy_buffer(buffer.raw, None) }; + } + super::BufferOwnership::External(_drop_guard) => { + // The caller owns the `vk::Buffer` and its memory. Dropping + // `_drop_guard` at the end of this arm runs the cleanup callback. + } + } + + self.counters.buffers.sub(1); + } + + unsafe fn add_raw_buffer(&self, _buffer: &super::Buffer) { + self.counters.buffers.add(1); + } + + unsafe fn map_buffer( + &self, + buffer: &super::Buffer, + range: crate::MemoryRange, + ) -> Result<crate::BufferMapping, crate::DeviceError> { + let super::BufferOwnership::Managed(ref allocation) = buffer.ownership else { + crate::hal_usage_error("tried to map external buffer") + }; + let mut allocation = allocation.lock(); + let super::BufferMemoryBacking::Managed(ref mut allocation) = *allocation else { + crate::hal_usage_error("tried to map externally created buffer") + }; + let is_coherent = allocation + .memory_properties() + .contains(vk::MemoryPropertyFlags::HOST_COHERENT); + Ok(crate::BufferMapping { + ptr: unsafe { + allocation + .mapped_ptr() + .unwrap() + .cast() + .offset(range.start as isize) + }, + is_coherent, + }) + } + + unsafe fn unmap_buffer(&self, buffer: &super::Buffer) { + match buffer.ownership { + super::BufferOwnership::Managed(_) => { + // gpu-allocator maps the buffer when allocated and unmaps it when free'd + } + super::BufferOwnership::RawHandle | super::BufferOwnership::External(_) => { + crate::hal_usage_error("tried to unmap external buffer") + } + } + } + + unsafe fn flush_mapped_ranges<I>(&self, buffer: &super::Buffer, ranges: I) + where + I: Iterator<Item = crate::MemoryRange>, + { + if let Some(vk_ranges) = self.shared.make_memory_ranges(buffer, ranges) { + unsafe { + self.shared + .raw + .flush_mapped_memory_ranges( + &smallvec::SmallVec::<[vk::MappedMemoryRange; 32]>::from_iter(vk_ranges), + ) + } + .unwrap(); + } + } + unsafe fn invalidate_mapped_ranges<I>(&self, buffer: &super::Buffer, ranges: I) + where + I: Iterator<Item = crate::MemoryRange>, + { + if let Some(vk_ranges) = self.shared.make_memory_ranges(buffer, ranges) { + unsafe { + self.shared + .raw + .invalidate_mapped_memory_ranges(&smallvec::SmallVec::< + [vk::MappedMemoryRange; 32], + >::from_iter(vk_ranges)) + } + .unwrap(); + } + } + + unsafe fn create_texture( + &self, + desc: &crate::TextureDescriptor, + ) -> Result<super::Texture, crate::DeviceError> { + let image = self.create_image_without_memory(desc, None)?; + + self.error_if_would_oom_on_resource_allocation( + gpu_allocator::MemoryLocation::GpuOnly, + &image.requirements, + ) + .inspect_err(|_| { + unsafe { self.shared.raw.destroy_image(image.raw, None) }; + })?; + + let name = desc.label.unwrap_or("Unlabeled texture"); + + let allocation = self + .mem_allocator + .lock() + .allocate(&gpu_allocator::vulkan::AllocationCreateDesc { + name, + requirements: vk::MemoryRequirements { + memory_type_bits: image.requirements.memory_type_bits + & self.valid_ash_memory_types, + ..image.requirements + }, + location: gpu_allocator::MemoryLocation::GpuOnly, + linear: false, + allocation_scheme: gpu_allocator::vulkan::AllocationScheme::GpuAllocatorManaged, + }) + .inspect_err(|_| { + unsafe { self.shared.raw.destroy_image(image.raw, None) }; + })?; + + self.counters.texture_memory.add(allocation.size() as isize); + + unsafe { + self.shared + .raw + .bind_image_memory(image.raw, allocation.memory(), allocation.offset()) + } + .map_err(super::map_host_device_oom_err) + .inspect_err(|_| { + unsafe { self.shared.raw.destroy_image(image.raw, None) }; + })?; + + Ok(unsafe { + self.texture_from_raw( + image.raw, + desc, + None, + super::TextureMemory::Allocation(allocation), + ) + }) + } + + unsafe fn destroy_texture(&self, texture: super::Texture) { + if texture.drop_guard.is_none() { + unsafe { self.shared.raw.destroy_image(texture.raw, None) }; + } + + match texture.memory { + super::TextureMemory::Allocation(allocation) => { + self.counters.texture_memory.sub(allocation.size() as isize); + let result = self.mem_allocator.lock().free(allocation); + if let Err(err) = result { + log::warn!("Failed to free texture allocation: {err}"); + } + } + super::TextureMemory::Dedicated(memory) => unsafe { + self.shared.raw.free_memory(memory, None); + }, + super::TextureMemory::External => {} + } + + self.counters.textures.sub(1); + } + + unsafe fn add_raw_texture(&self, _texture: &super::Texture) { + self.counters.textures.add(1); + } + + unsafe fn create_texture_view( + &self, + texture: &super::Texture, + desc: &crate::TextureViewDescriptor, + ) -> Result<super::TextureView, crate::DeviceError> { + let subresource_range = conv::map_subresource_range(&desc.range, texture.format); + let raw_format = self.shared.private_caps.map_texture_format(desc.format); + let mut vk_info = vk::ImageViewCreateInfo::default() + .flags(vk::ImageViewCreateFlags::empty()) + .image(texture.raw) + .view_type(conv::map_view_dimension(desc.dimension)) + .format(raw_format) + .subresource_range(subresource_range); + let layers = + NonZeroU32::new(subresource_range.layer_count).expect("Unexpected zero layer count"); + + let mut image_view_info; + if self.shared.private_caps.image_view_usage && !desc.usage.is_empty() { + image_view_info = + vk::ImageViewUsageCreateInfo::default().usage(conv::map_texture_usage(desc.usage)); + vk_info = vk_info.push_next(&mut image_view_info); + } + + let raw = unsafe { self.shared.raw.create_image_view(&vk_info, None) } + .map_err(super::map_host_device_oom_and_ioca_err)?; + + if let Some(label) = desc.label { + unsafe { self.shared.set_object_name(raw, label) }; + } + + let identity = self.shared.texture_view_identity_factory.next(); + + self.counters.texture_views.add(1); + + Ok(super::TextureView { + raw_texture: texture.raw, + raw, + _layers: layers, + format: desc.format, + raw_format, + base_mip_level: desc.range.base_mip_level, + dimension: desc.dimension, + texture_identity: texture.identity, + view_identity: identity, + }) + } + unsafe fn destroy_texture_view(&self, view: super::TextureView) { + unsafe { self.shared.raw.destroy_image_view(view.raw, None) }; + + self.counters.texture_views.sub(1); + } + + unsafe fn create_sampler( + &self, + desc: &crate::SamplerDescriptor, + ) -> Result<super::Sampler, crate::DeviceError> { + let mut create_info = vk::SamplerCreateInfo::default() + .flags(vk::SamplerCreateFlags::empty()) + .mag_filter(conv::map_filter_mode(desc.mag_filter)) + .min_filter(conv::map_filter_mode(desc.min_filter)) + .mipmap_mode(conv::map_mip_filter_mode(desc.mipmap_filter)) + .address_mode_u(conv::map_address_mode(desc.address_modes[0])) + .address_mode_v(conv::map_address_mode(desc.address_modes[1])) + .address_mode_w(conv::map_address_mode(desc.address_modes[2])) + .min_lod(desc.lod_clamp.start) + .max_lod(desc.lod_clamp.end); + + if let Some(fun) = desc.compare { + create_info = create_info + .compare_enable(true) + .compare_op(conv::map_comparison(fun)); + } + + if desc.anisotropy_clamp != 1 { + // We only enable anisotropy if it is supported, and wgpu-hal interface guarantees + // the clamp is in the range [1, 16] which is always supported if anisotropy is. + create_info = create_info + .anisotropy_enable(true) + .max_anisotropy(desc.anisotropy_clamp as f32); + } + + if let Some(color) = desc.border_color { + create_info = create_info.border_color(conv::map_border_color(color)); + } + + let mut sampler_cache_guard = self.shared.sampler_cache.lock(); + + let raw = sampler_cache_guard.create_sampler(&self.shared.raw, create_info)?; + + // Note: Cached samplers will just continually overwrite the label + // + // https://github.com/gfx-rs/wgpu/issues/6867 + if let Some(label) = desc.label { + // SAFETY: we are holding a lock on the sampler cache, + // so we can only be setting the name from one thread. + unsafe { self.shared.set_object_name(raw, label) }; + } + + drop(sampler_cache_guard); + + self.counters.samplers.add(1); + + Ok(super::Sampler { raw, create_info }) + } + unsafe fn destroy_sampler(&self, sampler: super::Sampler) { + self.shared.sampler_cache.lock().destroy_sampler( + &self.shared.raw, + sampler.create_info, + sampler.raw, + ); + + self.counters.samplers.sub(1); + } + + unsafe fn create_command_encoder( + &self, + desc: &crate::CommandEncoderDescriptor<super::Queue>, + ) -> Result<super::CommandEncoder, crate::DeviceError> { + let vk_info = vk::CommandPoolCreateInfo::default() + .queue_family_index(desc.queue.family_index) + .flags(vk::CommandPoolCreateFlags::TRANSIENT); + + let raw = unsafe { + self.shared + .raw + .create_command_pool(&vk_info, None) + .map_err(super::map_host_device_oom_err)? + }; + + self.counters.command_encoders.add(1); + + Ok(super::CommandEncoder { + raw, + device: Arc::clone(&self.shared), + active: vk::CommandBuffer::null(), + bind_point: vk::PipelineBindPoint::default(), + temp: super::Temp::default(), + free: Vec::new(), + discarded: Vec::new(), + rpass_debug_marker_active: false, + end_of_pass_timer_query: None, + framebuffers: Default::default(), + temp_texture_views: Default::default(), + counters: Arc::clone(&self.counters), + current_pipeline_is_multiview: false, + }) + } + + unsafe fn create_bind_group_layout( + &self, + desc: &crate::BindGroupLayoutDescriptor, + ) -> Result<super::BindGroupLayout, crate::DeviceError> { + // Iterate through the entries and accumulate our Vulkan + // DescriptorSetLayoutBindings and DescriptorBindingFlags, as well as + // our binding map and our descriptor counts. + // Note: not bothering with on stack arrays here as it's low frequency + let mut vk_bindings = Vec::new(); + let mut binding_flags = Vec::new(); + let mut binding_map = Vec::new(); + let mut next_binding = 0; + let mut contains_binding_arrays = false; + let mut desc_count = DescriptorCounts::default(); + for entry in desc.entries { + if entry.count.is_some() { + contains_binding_arrays = true; + } + + let partially_bound = desc + .flags + .contains(crate::BindGroupLayoutFlags::PARTIALLY_BOUND); + let mut flags = vk::DescriptorBindingFlags::empty(); + if partially_bound && entry.count.is_some() { + flags |= vk::DescriptorBindingFlags::PARTIALLY_BOUND; + } + if entry.count.is_some() { + flags |= vk::DescriptorBindingFlags::UPDATE_AFTER_BIND; + } + + let count = entry.count.map_or(1, |c| c.get()); + match entry.ty { + wgt::BindingType::ExternalTexture => unimplemented!(), + _ => { + vk_bindings.push(vk::DescriptorSetLayoutBinding { + binding: next_binding, + descriptor_type: conv::map_binding_type(entry.ty), + descriptor_count: count, + stage_flags: conv::map_shader_stage(entry.visibility), + p_immutable_samplers: ptr::null(), + _marker: Default::default(), + }); + binding_flags.push(flags); + binding_map.push(( + entry.binding, + super::BindingInfo { + binding: next_binding, + binding_array_size: entry.count, + }, + )); + next_binding += 1; + } + } + + match entry.ty { + wgt::BindingType::Buffer { + ty, + has_dynamic_offset, + .. + } => match ty { + wgt::BufferBindingType::Uniform => { + if has_dynamic_offset { + desc_count.uniform_buffer_dynamic += count; + } else { + desc_count.uniform_buffer += count; + } + } + wgt::BufferBindingType::Storage { .. } => { + if has_dynamic_offset { + desc_count.storage_buffer_dynamic += count; + } else { + desc_count.storage_buffer += count; + } + } + }, + wgt::BindingType::Sampler { .. } => { + desc_count.sampler += count; + } + wgt::BindingType::Texture { .. } => { + desc_count.sampled_image += count; + } + wgt::BindingType::StorageTexture { .. } => { + desc_count.storage_image += count; + } + wgt::BindingType::AccelerationStructure { .. } => { + desc_count.acceleration_structure += count; + } + wgt::BindingType::ExternalTexture => unimplemented!(), + } + } + + let vk_info = vk::DescriptorSetLayoutCreateInfo::default() + .bindings(&vk_bindings) + .flags(if contains_binding_arrays { + vk::DescriptorSetLayoutCreateFlags::UPDATE_AFTER_BIND_POOL + } else { + vk::DescriptorSetLayoutCreateFlags::empty() + }); + + let mut binding_flag_info = + vk::DescriptorSetLayoutBindingFlagsCreateInfo::default().binding_flags(&binding_flags); + + let vk_info = vk_info.push_next(&mut binding_flag_info); + + let raw = unsafe { + self.shared + .raw + .create_descriptor_set_layout(&vk_info, None) + .map_err(super::map_host_device_oom_err)? + }; + + if let Some(label) = desc.label { + unsafe { self.shared.set_object_name(raw, label) }; + } + + let layout = super::BindGroupLayout { + raw, + desc_count, + entries: desc.entries.into(), + binding_map, + contains_binding_arrays, + }; + + let result = self + .desc_allocator + .lock() + .register_layout(&self.shared.raw, &layout); + if let Err(err) = result { + unsafe { + self.shared + .raw + .destroy_descriptor_set_layout(layout.raw, None) + }; + return Err(err); + } + + self.counters.bind_group_layouts.add(1); + + Ok(layout) + } + unsafe fn destroy_bind_group_layout(&self, bg_layout: super::BindGroupLayout) { + self.desc_allocator + .lock() + .unregister_layout(&self.shared.raw, &bg_layout); + + unsafe { + self.shared + .raw + .destroy_descriptor_set_layout(bg_layout.raw, None) + }; + + self.counters.bind_group_layouts.sub(1); + } + + unsafe fn create_pipeline_layout( + &self, + desc: &crate::PipelineLayoutDescriptor<super::BindGroupLayout>, + ) -> Result<super::PipelineLayout, crate::DeviceError> { + //Note: not bothering with on stack array here as it's low frequency + let vk_set_layouts = desc + .bind_group_layouts + .iter() + .map(|bgl| match bgl { + Some(bgl) => bgl.raw, + None => { + // `VUID-VkPipelineLayoutCreateInfo-pSetLayouts-parameter` + // says `VK_NULL_HANDLE` is allowed but + // `VUID-VkPipelineLayoutCreateInfo-graphicsPipelineLibrary-06753` + // says it's not, unless the `graphicsPipelineLibrary` + // feature is enabled. + // + // We use an empty descriptor set layout to work around this. + self.shared.empty_descriptor_set_layout + } + }) + .collect::<Vec<_>>(); + let vk_immediates_ranges: Option<vk::PushConstantRange> = if desc.immediate_size != 0 { + Some(vk::PushConstantRange { + stage_flags: vk::ShaderStageFlags::ALL, + offset: 0, + size: desc.immediate_size, + }) + } else { + None + }; + + let vk_info = vk::PipelineLayoutCreateInfo::default() + .flags(vk::PipelineLayoutCreateFlags::empty()) + .set_layouts(&vk_set_layouts) + .push_constant_ranges(vk_immediates_ranges.as_slice()); + + let raw = { + profiling::scope!("vkCreatePipelineLayout"); + unsafe { + self.shared + .raw + .create_pipeline_layout(&vk_info, None) + .map_err(super::map_host_device_oom_err)? + } + }; + + if let Some(label) = desc.label { + unsafe { self.shared.set_object_name(raw, label) }; + } + + let mut binding_map = BTreeMap::new(); + for (group, layout) in desc.bind_group_layouts.iter().enumerate() { + let Some(layout) = layout else { + continue; + }; + + for &(binding, binding_info) in &layout.binding_map { + binding_map.insert( + naga::ResourceBinding { + group: group as u32, + binding, + }, + naga::back::spv::BindingInfo { + descriptor_set: group as u32, + binding: binding_info.binding, + binding_array_size: binding_info.binding_array_size.map(NonZeroU32::get), + }, + ); + } + } + + self.counters.pipeline_layouts.add(1); + Ok(super::PipelineLayout { raw, binding_map }) + } + unsafe fn destroy_pipeline_layout(&self, pipeline_layout: super::PipelineLayout) { + unsafe { + self.shared + .raw + .destroy_pipeline_layout(pipeline_layout.raw, None) + }; + + self.counters.pipeline_layouts.sub(1); + } + + unsafe fn create_bind_group( + &self, + desc: &crate::BindGroupDescriptor< + super::BindGroupLayout, + super::Buffer, + super::Sampler, + super::TextureView, + super::AccelerationStructure, + >, + ) -> Result<super::BindGroup, crate::DeviceError> { + let set = unsafe { + self.desc_allocator + .lock() + .alloc(&self.shared.raw, desc.layout)? + }; + + if let Some(label) = desc.label { + unsafe { self.shared.set_object_name(set.raw(), label) }; + } + + /// Helper for splitting off and initializing a given number of elements on a pre-allocated + /// stack, based on items returned from an [`ExactSizeIterator`]. Typically created from a + /// [`MaybeUninit`] slice (see [`Vec::spare_capacity_mut()`]). + /// The updated [`ExtensionStack`] of remaining uninitialized elements is returned, safely + /// representing that the initialized and remaining elements are two independent mutable + /// borrows. + struct ExtendStack<'a, T> { + remainder: &'a mut [MaybeUninit<T>], + } + + impl<'a, T> ExtendStack<'a, T> { + fn from_vec_capacity(vec: &'a mut Vec<T>) -> Self { + Self { + remainder: vec.spare_capacity_mut(), + } + } + + fn extend_one(self, value: T) -> (Self, &'a mut T) { + let (to_init, remainder) = self.remainder.split_first_mut().unwrap(); + let init = to_init.write(value); + (Self { remainder }, init) + } + + fn extend( + self, + iter: impl IntoIterator<Item = T> + ExactSizeIterator, + ) -> (Self, &'a mut [T]) { + let (to_init, remainder) = self.remainder.split_at_mut(iter.len()); + + for (value, to_init) in iter.into_iter().zip(to_init.iter_mut()) { + to_init.write(value); + } + + // we can't use the safe (yet unstable) MaybeUninit::write_slice() here because of having an iterator to write + + let init = { + // SAFETY: The loop above has initialized exactly as many items as to_init is + // long, so it is safe to cast away the MaybeUninit<T> wrapper into T. + + // Additional safety docs from unstable slice_assume_init_mut + // SAFETY: similar to safety notes for `slice_get_ref`, but we have a + // mutable reference which is also guaranteed to be valid for writes. + unsafe { mem::transmute::<&mut [MaybeUninit<T>], &mut [T]>(to_init) } + }; + (Self { remainder }, init) + } + } + + let mut writes = Vec::with_capacity(desc.entries.len()); + let mut buffer_infos = Vec::with_capacity(desc.buffers.len()); + let mut buffer_infos = ExtendStack::from_vec_capacity(&mut buffer_infos); + let mut image_infos = Vec::with_capacity(desc.samplers.len() + desc.textures.len()); + let mut image_infos = ExtendStack::from_vec_capacity(&mut image_infos); + // TODO: This length could be reduced to just the number of top-level acceleration + // structure bindings, where multiple consecutive TLAS bindings that are set via + // one `WriteDescriptorSet` count towards one "info" struct, not the total number of + // acceleration structure bindings to write: + let mut acceleration_structure_infos = + Vec::with_capacity(desc.acceleration_structures.len()); + let mut acceleration_structure_infos = + ExtendStack::from_vec_capacity(&mut acceleration_structure_infos); + let mut raw_acceleration_structures = + Vec::with_capacity(desc.acceleration_structures.len()); + let mut raw_acceleration_structures = + ExtendStack::from_vec_capacity(&mut raw_acceleration_structures); + + let layout_and_entry_iter = desc.entries.iter().map(|entry| { + let layout = desc + .layout + .entries + .iter() + .find(|layout_entry| layout_entry.binding == entry.binding) + .expect("internal error: no layout entry found with binding slot"); + (layout, entry) + }); + let mut next_binding = 0; + for (layout, entry) in layout_and_entry_iter { + let write = vk::WriteDescriptorSet::default().dst_set(set.raw()); + + match layout.ty { + wgt::BindingType::Sampler(_) => { + let start = entry.resource_index; + let end = start + entry.count; + let local_image_infos; + (image_infos, local_image_infos) = + image_infos.extend(desc.samplers[start as usize..end as usize].iter().map( + |sampler| vk::DescriptorImageInfo::default().sampler(sampler.raw), + )); + writes.push( + write + .dst_binding(next_binding) + .descriptor_type(conv::map_binding_type(layout.ty)) + .image_info(local_image_infos), + ); + next_binding += 1; + } + wgt::BindingType::Texture { .. } | wgt::BindingType::StorageTexture { .. } => { + let start = entry.resource_index; + let end = start + entry.count; + let local_image_infos; + (image_infos, local_image_infos) = + image_infos.extend(desc.textures[start as usize..end as usize].iter().map( + |binding| { + let layout = + conv::derive_image_layout(binding.usage, binding.view.format); + vk::DescriptorImageInfo::default() + .image_view(binding.view.raw) + .image_layout(layout) + }, + )); + writes.push( + write + .dst_binding(next_binding) + .descriptor_type(conv::map_binding_type(layout.ty)) + .image_info(local_image_infos), + ); + next_binding += 1; + } + wgt::BindingType::Buffer { .. } => { + let start = entry.resource_index; + let end = start + entry.count; + let local_buffer_infos; + (buffer_infos, local_buffer_infos) = + buffer_infos.extend(desc.buffers[start as usize..end as usize].iter().map( + |binding| { + vk::DescriptorBufferInfo::default() + .buffer(binding.buffer.raw) + .offset(binding.offset) + .range( + binding.size.map_or(vk::WHOLE_SIZE, wgt::BufferSize::get), + ) + }, + )); + writes.push( + write + .dst_binding(next_binding) + .descriptor_type(conv::map_binding_type(layout.ty)) + .buffer_info(local_buffer_infos), + ); + next_binding += 1; + } + wgt::BindingType::AccelerationStructure { .. } => { + let start = entry.resource_index; + let end = start + entry.count; + + let local_raw_acceleration_structures; + ( + raw_acceleration_structures, + local_raw_acceleration_structures, + ) = raw_acceleration_structures.extend( + desc.acceleration_structures[start as usize..end as usize] + .iter() + .map(|acceleration_structure| acceleration_structure.raw), + ); + + let local_acceleration_structure_infos; + ( + acceleration_structure_infos, + local_acceleration_structure_infos, + ) = acceleration_structure_infos.extend_one( + vk::WriteDescriptorSetAccelerationStructureKHR::default() + .acceleration_structures(local_raw_acceleration_structures), + ); + + writes.push( + write + .dst_binding(next_binding) + .descriptor_type(conv::map_binding_type(layout.ty)) + .descriptor_count(entry.count) + .push_next(local_acceleration_structure_infos), + ); + next_binding += 1; + } + wgt::BindingType::ExternalTexture => unimplemented!(), + } + } + + unsafe { self.shared.raw.update_descriptor_sets(&writes, &[]) }; + + self.counters.bind_groups.add(1); + + Ok(super::BindGroup { set }) + } + + unsafe fn destroy_bind_group(&self, group: super::BindGroup) { + unsafe { self.desc_allocator.lock().free(&self.shared.raw, group.set) }; + + self.counters.bind_groups.sub(1); + } + + unsafe fn create_shader_module( + &self, + desc: &crate::ShaderModuleDescriptor, + shader: crate::ShaderInput, + ) -> Result<super::ShaderModule, crate::ShaderError> { + let shader_module = match shader { + crate::ShaderInput::Naga(naga_shader) + if self + .shared + .workarounds + .contains(super::Workarounds::SEPARATE_ENTRY_POINTS) + || !naga_shader.module.overrides.is_empty() => + { + super::ShaderModule::Intermediate { + naga_shader, + runtime_checks: desc.runtime_checks, + } + } + crate::ShaderInput::Naga(naga_shader) => { + let mut naga_options = self.naga_options.clone(); + naga_options.debug_info = + naga_shader + .debug_source + .as_ref() + .map(|d| naga::back::spv::DebugInfo { + source_code: d.source_code.as_ref(), + file_name: d.file_name.as_ref(), + language: naga::back::spv::SourceLanguage::WGSL, + }); + if !desc.runtime_checks.bounds_checks { + naga_options.bounds_check_policies = naga::proc::BoundsCheckPolicies { + index: naga::proc::BoundsCheckPolicy::Unchecked, + buffer: naga::proc::BoundsCheckPolicy::Unchecked, + image_load: naga::proc::BoundsCheckPolicy::Unchecked, + binding_array: naga::proc::BoundsCheckPolicy::Unchecked, + }; + } + let spv = naga::back::spv::write_vec( + &naga_shader.module, + &naga_shader.info, + &naga_options, + None, + ) + .map_err(|e| crate::ShaderError::Compilation(format!("{e}")))?; + super::ShaderModule::Raw(self.create_shader_module_impl(&spv, &desc.label)?) + } + crate::ShaderInput::SpirV(data) => { + super::ShaderModule::Raw(self.create_shader_module_impl(data, &desc.label)?) + } + crate::ShaderInput::MetalLib { .. } + | crate::ShaderInput::Msl { .. } + | crate::ShaderInput::Dxil { .. } + | crate::ShaderInput::Hlsl { .. } + | crate::ShaderInput::Glsl { .. } => unreachable!(), + }; + + self.counters.shader_modules.add(1); + + Ok(shader_module) + } + + unsafe fn destroy_shader_module(&self, module: super::ShaderModule) { + match module { + super::ShaderModule::Raw(raw) => { + unsafe { self.shared.raw.destroy_shader_module(raw, None) }; + } + super::ShaderModule::Intermediate { .. } => {} + } + + self.counters.shader_modules.sub(1); + } + + unsafe fn create_render_pipeline( + &self, + desc: &crate::RenderPipelineDescriptor< + super::PipelineLayout, + super::ShaderModule, + super::PipelineCache, + >, + ) -> Result<super::RenderPipeline, crate::PipelineError> { + let dynamic_states = [ + vk::DynamicState::VIEWPORT, + vk::DynamicState::SCISSOR, + vk::DynamicState::BLEND_CONSTANTS, + vk::DynamicState::STENCIL_REFERENCE, + ]; + let mut compatible_rp_key = super::RenderPassKey { + sample_count: desc.multisample.count, + multiview_mask: desc.multiview_mask, + ..Default::default() + }; + let mut stages = ArrayVec::<_, { crate::MAX_CONCURRENT_SHADER_STAGES }>::new(); + let mut vertex_buffers = Vec::new(); + let mut vertex_attributes = Vec::new(); + + if let crate::VertexProcessor::Standard { + vertex_buffers: desc_vertex_buffers, + vertex_stage: _, + } = &desc.vertex_processor + { + vertex_buffers = Vec::with_capacity(desc_vertex_buffers.len()); + for (i, vb) in desc_vertex_buffers.iter().enumerate() { + let Some(vb) = vb else { + continue; + }; + vertex_buffers.push(vk::VertexInputBindingDescription { + binding: i as u32, + stride: vb.array_stride as u32, + input_rate: match vb.step_mode { + wgt::VertexStepMode::Vertex => vk::VertexInputRate::VERTEX, + wgt::VertexStepMode::Instance => vk::VertexInputRate::INSTANCE, + }, + }); + for at in vb.attributes { + vertex_attributes.push(vk::VertexInputAttributeDescription { + location: at.shader_location, + binding: i as u32, + format: conv::map_vertex_format(at.format), + offset: at.offset as u32, + }); + } + } + } + + let vk_vertex_input = vk::PipelineVertexInputStateCreateInfo::default() + .vertex_binding_descriptions(&vertex_buffers) + .vertex_attribute_descriptions(&vertex_attributes); + + let vk_input_assembly = vk::PipelineInputAssemblyStateCreateInfo::default() + .topology(conv::map_topology(desc.primitive.topology)) + .primitive_restart_enable(desc.primitive.strip_index_format.is_some()); + + let mut compiled_vs = None; + let mut compiled_ms = None; + let mut compiled_ts = None; + match &desc.vertex_processor { + crate::VertexProcessor::Standard { + vertex_buffers: _, + vertex_stage, + } => { + compiled_vs = Some(self.compile_stage( + vertex_stage, + naga::ShaderStage::Vertex, + &desc.layout.binding_map, + )?); + stages.push(compiled_vs.as_ref().unwrap().create_info); + } + crate::VertexProcessor::Mesh { + task_stage, + mesh_stage, + } => { + if let Some(t) = task_stage.as_ref() { + compiled_ts = Some(self.compile_stage( + t, + naga::ShaderStage::Task, + &desc.layout.binding_map, + )?); + stages.push(compiled_ts.as_ref().unwrap().create_info); + } + compiled_ms = Some(self.compile_stage( + mesh_stage, + naga::ShaderStage::Mesh, + &desc.layout.binding_map, + )?); + stages.push(compiled_ms.as_ref().unwrap().create_info); + } + } + let compiled_fs = match desc.fragment_stage { + Some(ref stage) => { + let compiled = self.compile_stage( + stage, + naga::ShaderStage::Fragment, + &desc.layout.binding_map, + )?; + stages.push(compiled.create_info); + Some(compiled) + } + None => None, + }; + + let mut vk_rasterization = vk::PipelineRasterizationStateCreateInfo::default() + .polygon_mode(conv::map_polygon_mode(desc.primitive.polygon_mode)) + .front_face(conv::map_front_face(desc.primitive.front_face)) + .line_width(1.0) + .depth_clamp_enable(desc.primitive.unclipped_depth); + if let Some(face) = desc.primitive.cull_mode { + vk_rasterization = vk_rasterization.cull_mode(conv::map_cull_face(face)) + } + let mut vk_rasterization_conservative_state = + vk::PipelineRasterizationConservativeStateCreateInfoEXT::default() + .conservative_rasterization_mode( + vk::ConservativeRasterizationModeEXT::OVERESTIMATE, + ); + if desc.primitive.conservative { + vk_rasterization = vk_rasterization.push_next(&mut vk_rasterization_conservative_state); + } + + let mut vk_depth_stencil = vk::PipelineDepthStencilStateCreateInfo::default(); + if let Some(ref ds) = desc.depth_stencil { + let vk_format = self.shared.private_caps.map_texture_format(ds.format); + let vk_layout = if ds.is_read_only(desc.primitive.cull_mode) { + vk::ImageLayout::DEPTH_STENCIL_READ_ONLY_OPTIMAL + } else { + vk::ImageLayout::DEPTH_STENCIL_ATTACHMENT_OPTIMAL + }; + compatible_rp_key.depth_stencil = Some(super::DepthStencilAttachmentKey { + base: super::AttachmentKey::compatible(vk_format, vk_layout), + stencil_ops: crate::AttachmentOps::all(), + }); + + if ds.is_depth_enabled() { + vk_depth_stencil = vk_depth_stencil + .depth_test_enable(true) + .depth_write_enable(ds.depth_write_enabled.unwrap_or_default()) + .depth_compare_op(conv::map_comparison(ds.depth_compare.unwrap_or_default())); + } + if ds.stencil.is_enabled() { + let s = &ds.stencil; + let front = conv::map_stencil_face(&s.front, s.read_mask, s.write_mask); + let back = conv::map_stencil_face(&s.back, s.read_mask, s.write_mask); + vk_depth_stencil = vk_depth_stencil + .stencil_test_enable(true) + .front(front) + .back(back); + } + + if ds.bias.is_enabled() { + vk_rasterization = vk_rasterization + .depth_bias_enable(true) + .depth_bias_constant_factor(ds.bias.constant as f32) + .depth_bias_clamp(ds.bias.clamp) + .depth_bias_slope_factor(ds.bias.slope_scale); + } + } + + let vk_viewport = vk::PipelineViewportStateCreateInfo::default() + .flags(vk::PipelineViewportStateCreateFlags::empty()) + .scissor_count(1) + .viewport_count(1); + + let vk_sample_mask = [ + desc.multisample.mask as u32, + (desc.multisample.mask >> 32) as u32, + ]; + let vk_multisample = vk::PipelineMultisampleStateCreateInfo::default() + .rasterization_samples(vk::SampleCountFlags::from_raw(desc.multisample.count)) + .alpha_to_coverage_enable(desc.multisample.alpha_to_coverage_enabled) + .sample_mask(&vk_sample_mask); + + let mut vk_attachments = Vec::with_capacity(desc.color_targets.len()); + for cat in desc.color_targets { + let (key, attarchment) = if let Some(cat) = cat.as_ref() { + let mut vk_attachment = vk::PipelineColorBlendAttachmentState::default() + .color_write_mask(vk::ColorComponentFlags::from_raw(cat.write_mask.bits())); + if let Some(ref blend) = cat.blend { + let (color_op, color_src, color_dst) = conv::map_blend_component(&blend.color); + let (alpha_op, alpha_src, alpha_dst) = conv::map_blend_component(&blend.alpha); + vk_attachment = vk_attachment + .blend_enable(true) + .color_blend_op(color_op) + .src_color_blend_factor(color_src) + .dst_color_blend_factor(color_dst) + .alpha_blend_op(alpha_op) + .src_alpha_blend_factor(alpha_src) + .dst_alpha_blend_factor(alpha_dst); + } + + let vk_format = self.shared.private_caps.map_texture_format(cat.format); + ( + Some(super::ColorAttachmentKey { + base: super::AttachmentKey::compatible( + vk_format, + vk::ImageLayout::COLOR_ATTACHMENT_OPTIMAL, + ), + resolve: None, + }), + vk_attachment, + ) + } else { + (None, vk::PipelineColorBlendAttachmentState::default()) + }; + + compatible_rp_key.colors.push(key); + vk_attachments.push(attarchment); + } + + let vk_color_blend = + vk::PipelineColorBlendStateCreateInfo::default().attachments(&vk_attachments); + + let vk_dynamic_state = + vk::PipelineDynamicStateCreateInfo::default().dynamic_states(&dynamic_states); + + let raw_pass = self.shared.make_render_pass(compatible_rp_key)?; + + let vk_infos = [{ + vk::GraphicsPipelineCreateInfo::default() + .layout(desc.layout.raw) + .stages(&stages) + .vertex_input_state(&vk_vertex_input) + .input_assembly_state(&vk_input_assembly) + .rasterization_state(&vk_rasterization) + .viewport_state(&vk_viewport) + .multisample_state(&vk_multisample) + .depth_stencil_state(&vk_depth_stencil) + .color_blend_state(&vk_color_blend) + .dynamic_state(&vk_dynamic_state) + .render_pass(raw_pass) + }]; + + let pipeline_cache = desc + .cache + .map(|it| it.raw) + .unwrap_or(vk::PipelineCache::null()); + + let mut raw_vec = { + profiling::scope!("vkCreateGraphicsPipelines"); + unsafe { + self.shared + .raw + .create_graphics_pipelines(pipeline_cache, &vk_infos, None) + .map_err(|(_, e)| super::map_pipeline_err(e)) + }? + }; + + let raw = raw_vec.pop().unwrap(); + if let Some(label) = desc.label { + unsafe { self.shared.set_object_name(raw, label) }; + } + + if let Some(CompiledStage { + temp_raw_module: Some(raw_module), + .. + }) = compiled_vs + { + unsafe { self.shared.raw.destroy_shader_module(raw_module, None) }; + } + if let Some(CompiledStage { + temp_raw_module: Some(raw_module), + .. + }) = compiled_ts + { + unsafe { self.shared.raw.destroy_shader_module(raw_module, None) }; + } + if let Some(CompiledStage { + temp_raw_module: Some(raw_module), + .. + }) = compiled_ms + { + unsafe { self.shared.raw.destroy_shader_module(raw_module, None) }; + } + if let Some(CompiledStage { + temp_raw_module: Some(raw_module), + .. + }) = compiled_fs + { + unsafe { self.shared.raw.destroy_shader_module(raw_module, None) }; + } + + self.counters.render_pipelines.add(1); + + Ok(super::RenderPipeline { + raw, + is_multiview: desc.multiview_mask.is_some(), + }) + } + + unsafe fn destroy_render_pipeline(&self, pipeline: super::RenderPipeline) { + unsafe { self.shared.raw.destroy_pipeline(pipeline.raw, None) }; + + self.counters.render_pipelines.sub(1); + } + + unsafe fn create_compute_pipeline( + &self, + desc: &crate::ComputePipelineDescriptor< + super::PipelineLayout, + super::ShaderModule, + super::PipelineCache, + >, + ) -> Result<super::ComputePipeline, crate::PipelineError> { + let compiled = self.compile_stage( + &desc.stage, + naga::ShaderStage::Compute, + &desc.layout.binding_map, + )?; + + let vk_infos = [{ + vk::ComputePipelineCreateInfo::default() + .layout(desc.layout.raw) + .stage(compiled.create_info) + }]; + + let pipeline_cache = desc + .cache + .map(|it| it.raw) + .unwrap_or(vk::PipelineCache::null()); + + let mut raw_vec = { + profiling::scope!("vkCreateComputePipelines"); + unsafe { + self.shared + .raw + .create_compute_pipelines(pipeline_cache, &vk_infos, None) + .map_err(|(_, e)| super::map_pipeline_err(e)) + }? + }; + + let raw = raw_vec.pop().unwrap(); + if let Some(label) = desc.label { + unsafe { self.shared.set_object_name(raw, label) }; + } + + if let Some(raw_module) = compiled.temp_raw_module { + unsafe { self.shared.raw.destroy_shader_module(raw_module, None) }; + } + + self.counters.compute_pipelines.add(1); + + Ok(super::ComputePipeline { raw }) + } + + unsafe fn destroy_compute_pipeline(&self, pipeline: super::ComputePipeline) { + unsafe { self.shared.raw.destroy_pipeline(pipeline.raw, None) }; + + self.counters.compute_pipelines.sub(1); + } + + unsafe fn create_ray_tracing_pipeline( + &self, + desc: &crate::RayTracingPipelineDescriptor< + super::PipelineLayout, + super::ShaderModule, + super::PipelineCache, + >, + ) -> Result<super::RayTracingPipeline, crate::PipelineError> { + let mut stages = Vec::new(); + let mut groups = Vec::new(); + + let compiled_ray_gen = self.compile_stage( + &desc.ray_generation, + naga::ShaderStage::RayGeneration, + &desc.layout.binding_map, + )?; + + groups.push( + vk::RayTracingShaderGroupCreateInfoKHR::default() + .closest_hit_shader(vk::SHADER_UNUSED_KHR) + .any_hit_shader(vk::SHADER_UNUSED_KHR) + .intersection_shader(vk::SHADER_UNUSED_KHR) + .general_shader(0) // stages is empty so next index is 0. + .ty(vk::RayTracingShaderGroupTypeKHR::GENERAL), + ); + + stages.push(compiled_ray_gen.create_info); + + let compiled_miss = self.compile_stage( + &desc.miss, + naga::ShaderStage::Miss, + &desc.layout.binding_map, + )?; + + groups.push( + vk::RayTracingShaderGroupCreateInfoKHR::default() + .closest_hit_shader(vk::SHADER_UNUSED_KHR) + .any_hit_shader(vk::SHADER_UNUSED_KHR) + .intersection_shader(vk::SHADER_UNUSED_KHR) + .general_shader(1) // stages always has one element so next index is 1. + .ty(vk::RayTracingShaderGroupTypeKHR::GENERAL), + ); + + stages.push(compiled_miss.create_info); + + // This is to keep alive the CStrings, as the ones in the loop would be deallocated + // causing UB otherwise. + let mut compiled_stages = Vec::new(); + + for group in desc.intersection { + let compiled_closest_hits = self.compile_stage( + &group.closest_hit, + naga::ShaderStage::ClosestHit, + &desc.layout.binding_map, + )?; + + let closest_idx = stages.len(); + + stages.push(compiled_closest_hits.create_info); + + compiled_stages.push(compiled_closest_hits); + + let mut raw_hit: vk::RayTracingShaderGroupCreateInfoKHR<'_> = + vk::RayTracingShaderGroupCreateInfoKHR::default() + .closest_hit_shader(closest_idx as _) + .any_hit_shader(vk::SHADER_UNUSED_KHR) + .intersection_shader(vk::SHADER_UNUSED_KHR) + .general_shader(vk::SHADER_UNUSED_KHR) + .ty(vk::RayTracingShaderGroupTypeKHR::TRIANGLES_HIT_GROUP); + + if let Some(any_hit) = &group.any_hit { + let compiled_any_hit = self.compile_stage( + any_hit, + naga::ShaderStage::AnyHit, + &desc.layout.binding_map, + )?; + + let any_idx = stages.len(); + + stages.push(compiled_any_hit.create_info); + + compiled_stages.push(compiled_any_hit); + + raw_hit = raw_hit.any_hit_shader(any_idx as _); + } + + groups.push(raw_hit); + } + + let create_infos = [{ + vk::RayTracingPipelineCreateInfoKHR::default() + .layout(desc.layout.raw) + .max_pipeline_ray_recursion_depth(desc.max_recursion_depth) + .stages(&stages) + .groups(&groups) + }]; + + let pipeline_cache = desc + .cache + .map(|it| it.raw) + .unwrap_or(vk::PipelineCache::null()); + + let fns = self + .shared + .extension_fns + .ray_tracing_pipelines + .as_ref() + .unwrap(); + let pipelines = unsafe { + fns.create_ray_tracing_pipelines( + vk::DeferredOperationKHR::null(), + pipeline_cache, + &create_infos, + None, + ) + .map_err(|(_, e)| super::map_pipeline_err(e)) + }?; + + if let Some(raw_module) = compiled_ray_gen.temp_raw_module { + unsafe { self.shared.raw.destroy_shader_module(raw_module, None) }; + } + + if let Some(raw_module) = compiled_miss.temp_raw_module { + unsafe { self.shared.raw.destroy_shader_module(raw_module, None) }; + } + + for raw_module in compiled_stages + .into_iter() + .flat_map(|stage| stage.temp_raw_module) + { + unsafe { self.shared.raw.destroy_shader_module(raw_module, None) }; + } + + self.counters.ray_tracing_pipelines.add(1); + + Ok(super::RayTracingPipeline { raw: pipelines[0] }) + } + + unsafe fn destroy_ray_tracing_pipeline(&self, pipeline: super::RayTracingPipeline) { + unsafe { self.shared.raw.destroy_pipeline(pipeline.raw, None) }; + + self.counters.ray_tracing_pipelines.sub(1); + } + + unsafe fn get_raytracing_pipeline_group_data( + &self, + pipeline: &super::RayTracingPipeline, + groups: core::ops::Range<u32>, + ) -> Result<Vec<u8>, crate::DeviceError> { + let fns = self + .shared + .extension_fns + .ray_tracing_pipelines + .as_ref() + .unwrap(); + + let num = groups.end - groups.start; + + unsafe { + fns.get_ray_tracing_shader_group_handles( + pipeline.raw, + groups.start, + num, + (num * self + .shared + .private_caps + .ray_tracing_pipeline_group_data_size) as usize, + ) + } + .map_err(super::map_host_device_oom_err) + } + + unsafe fn create_pipeline_cache( + &self, + desc: &crate::PipelineCacheDescriptor<'_>, + ) -> Result<super::PipelineCache, crate::PipelineCacheError> { + let mut info = vk::PipelineCacheCreateInfo::default(); + if let Some(data) = desc.data { + info = info.initial_data(data) + } + profiling::scope!("vkCreatePipelineCache"); + let raw = unsafe { self.shared.raw.create_pipeline_cache(&info, None) } + .map_err(super::map_host_device_oom_err)?; + + Ok(super::PipelineCache { raw }) + } + fn pipeline_cache_validation_key(&self) -> Option<[u8; 16]> { + Some(self.shared.pipeline_cache_validation_key) + } + unsafe fn destroy_pipeline_cache(&self, cache: super::PipelineCache) { + unsafe { self.shared.raw.destroy_pipeline_cache(cache.raw, None) } + } + unsafe fn create_query_set( + &self, + desc: &wgt::QuerySetDescriptor<crate::Label>, + ) -> Result<super::QuerySet, crate::DeviceError> { + // Assume each query is 256 bytes. This is the case for occlusion + // queries on an AMD W6800 with driver version 32.0.12030.9. The + // size and allocation policy may vary; this is an approximate + // check only. + self.error_if_would_oom_on_resource_allocation( + gpu_allocator::MemoryLocation::GpuToCpu, + &vk::MemoryRequirements { + size: desc.count as u64 * 256, + alignment: 256, + memory_type_bits: self.valid_ash_memory_types, + }, + )?; + + let (vk_type, pipeline_statistics) = match desc.ty { + wgt::QueryType::Occlusion => ( + vk::QueryType::OCCLUSION, + vk::QueryPipelineStatisticFlags::empty(), + ), + wgt::QueryType::PipelineStatistics(statistics) => ( + vk::QueryType::PIPELINE_STATISTICS, + conv::map_pipeline_statistics(statistics), + ), + wgt::QueryType::Timestamp => ( + vk::QueryType::TIMESTAMP, + vk::QueryPipelineStatisticFlags::empty(), + ), + }; + + let vk_info = vk::QueryPoolCreateInfo::default() + .query_type(vk_type) + .query_count(desc.count) + .pipeline_statistics(pipeline_statistics); + + let raw = unsafe { self.shared.raw.create_query_pool(&vk_info, None) } + .map_err(super::map_host_device_oom_err)?; + if let Some(label) = desc.label { + unsafe { self.shared.set_object_name(raw, label) }; + } + + self.counters.query_sets.add(1); + + Ok(super::QuerySet { raw }) + } + + unsafe fn destroy_query_set(&self, set: super::QuerySet) { + unsafe { self.shared.raw.destroy_query_pool(set.raw, None) }; + + self.counters.query_sets.sub(1); + } + + unsafe fn create_fence(&self) -> Result<super::Fence, crate::DeviceError> { + self.counters.fences.add(1); + + Ok(if self.shared.private_caps.timeline_semaphores { + let mut sem_type_info = + vk::SemaphoreTypeCreateInfo::default().semaphore_type(vk::SemaphoreType::TIMELINE); + let vk_info = vk::SemaphoreCreateInfo::default().push_next(&mut sem_type_info); + let raw = unsafe { self.shared.raw.create_semaphore(&vk_info, None) } + .map_err(super::map_host_device_oom_err)?; + + super::Fence::TimelineSemaphore(raw) + } else { + super::Fence::FencePool(RwLock::new(super::FencePool { + last_completed: 0, + active: Vec::new(), + free: Vec::new(), + })) + }) + } + unsafe fn destroy_fence(&self, fence: super::Fence) { + match fence { + super::Fence::TimelineSemaphore(raw) => { + unsafe { self.shared.raw.destroy_semaphore(raw, None) }; + } + super::Fence::FencePool(pool) => { + let super::FencePool { + active, + free, + last_completed: _, + } = pool.into_inner(); + + for (_, raw) in active { + unsafe { + self.shared.raw.destroy_fence(Arc::into_inner(raw).expect("Fence should have its reference count be one by the end of each function"), None) + }; + } + for raw in free { + unsafe { self.shared.raw.destroy_fence(raw, None) }; + } + } + } + + self.counters.fences.sub(1); + } + unsafe fn get_fence_value( + &self, + fence: &super::Fence, + ) -> Result<crate::FenceValue, crate::DeviceError> { + fence.get_latest( + &self.shared.raw, + self.shared.extension_fns.timeline_semaphore.as_ref(), + ) + } + unsafe fn wait( + &self, + fence: &super::Fence, + wait_value: crate::FenceValue, + timeout: Option<Duration>, + ) -> Result<bool, crate::DeviceError> { + let timeout_ns = timeout + .unwrap_or(Duration::MAX) + .as_nanos() + .min(u64::MAX as _) as u64; + self.shared.wait_for_fence(fence, wait_value, timeout_ns) + } + + unsafe fn start_graphics_debugger_capture(&self) -> bool { + #[cfg(feature = "renderdoc")] + { + // Renderdoc requires us to give us the pointer that vkInstance _points to_. + let raw_vk_instance = + vk::Handle::as_raw(self.shared.instance.raw.handle()) as *mut *mut _; + let raw_vk_instance_dispatch_table = unsafe { *raw_vk_instance }; + unsafe { + self.render_doc + .start_frame_capture(raw_vk_instance_dispatch_table, ptr::null_mut()) + } + } + #[cfg(not(feature = "renderdoc"))] + false + } + unsafe fn stop_graphics_debugger_capture(&self) { + #[cfg(feature = "renderdoc")] + { + // Renderdoc requires us to give us the pointer that vkInstance _points to_. + let raw_vk_instance = + vk::Handle::as_raw(self.shared.instance.raw.handle()) as *mut *mut _; + let raw_vk_instance_dispatch_table = unsafe { *raw_vk_instance }; + + unsafe { + self.render_doc + .end_frame_capture(raw_vk_instance_dispatch_table, ptr::null_mut()) + } + } + } + + unsafe fn pipeline_cache_get_data(&self, cache: &super::PipelineCache) -> Option<Vec<u8>> { + let data = unsafe { self.raw_device().get_pipeline_cache_data(cache.raw) }; + data.ok() + } + + unsafe fn get_acceleration_structure_build_sizes<'a>( + &self, + desc: &crate::GetAccelerationStructureBuildSizesDescriptor<'a, super::Buffer>, + ) -> crate::AccelerationStructureBuildSizes { + const CAPACITY: usize = 8; + + let ray_tracing_functions = self + .shared + .extension_fns + .ray_tracing + .as_ref() + .expect("Feature `RAY_TRACING` not enabled"); + + let (geometries, primitive_counts) = match *desc.entries { + crate::AccelerationStructureEntries::Instances(ref instances) => { + let instance_data = vk::AccelerationStructureGeometryInstancesDataKHR::default(); + + let geometry = vk::AccelerationStructureGeometryKHR::default() + .geometry_type(vk::GeometryTypeKHR::INSTANCES) + .geometry(vk::AccelerationStructureGeometryDataKHR { + instances: instance_data, + }); + + ( + smallvec::smallvec![geometry], + smallvec::smallvec![instances.count], + ) + } + crate::AccelerationStructureEntries::Triangles(ref in_geometries) => { + let mut primitive_counts = + smallvec::SmallVec::<[u32; CAPACITY]>::with_capacity(in_geometries.len()); + let mut geometries = smallvec::SmallVec::< + [vk::AccelerationStructureGeometryKHR; CAPACITY], + >::with_capacity(in_geometries.len()); + + for triangles in in_geometries { + let mut triangle_data = + vk::AccelerationStructureGeometryTrianglesDataKHR::default() + .index_type(vk::IndexType::NONE_KHR) + .vertex_format(conv::map_vertex_format(triangles.vertex_format)) + .max_vertex(triangles.vertex_count) + .vertex_stride(triangles.vertex_stride) + // The vulkan spec suggests we could pass a non-zero invalid address here if fetching + // the real address has significant overhead, but we pass the real one to be on the + // safe side for now. + // from https://registry.khronos.org/vulkan/specs/latest/man/html/vkGetAccelerationStructureBuildSizesKHR.html + // > The srcAccelerationStructure, dstAccelerationStructure, and mode members + // > of pBuildInfo are ignored. Any VkDeviceOrHostAddressKHR or VkDeviceOrHostAddressConstKHR + // > members of pBuildInfo are ignored by this command, except that the hostAddress + // > member of VkAccelerationStructureGeometryTrianglesDataKHR::transformData will + // > be examined to check if it is NULL. + .transform_data(vk::DeviceOrHostAddressConstKHR { + device_address: if desc + .flags + .contains(wgt::AccelerationStructureFlags::USE_TRANSFORM) + { + unsafe { + ray_tracing_functions + .buffer_device_address + .get_buffer_device_address( + &vk::BufferDeviceAddressInfo::default().buffer( + triangles + .transform + .as_ref() + .unwrap() + .buffer + .raw, + ), + ) + } + } else { + 0 + }, + }); + + let pritive_count = if let Some(ref indices) = triangles.indices { + triangle_data = + triangle_data.index_type(conv::map_index_format(indices.format)); + indices.count / 3 + } else { + triangles.vertex_count / 3 + }; + + let geometry = vk::AccelerationStructureGeometryKHR::default() + .geometry_type(vk::GeometryTypeKHR::TRIANGLES) + .geometry(vk::AccelerationStructureGeometryDataKHR { + triangles: triangle_data, + }) + .flags(conv::map_acceleration_structure_geometry_flags( + triangles.flags, + )); + + geometries.push(geometry); + primitive_counts.push(pritive_count); + } + (geometries, primitive_counts) + } + crate::AccelerationStructureEntries::AABBs(ref in_geometries) => { + let mut primitive_counts = + smallvec::SmallVec::<[u32; CAPACITY]>::with_capacity(in_geometries.len()); + let mut geometries = smallvec::SmallVec::< + [vk::AccelerationStructureGeometryKHR; CAPACITY], + >::with_capacity(in_geometries.len()); + for aabb in in_geometries { + let aabbs_data = vk::AccelerationStructureGeometryAabbsDataKHR::default() + .stride(aabb.stride); + + let geometry = vk::AccelerationStructureGeometryKHR::default() + .geometry_type(vk::GeometryTypeKHR::AABBS) + .geometry(vk::AccelerationStructureGeometryDataKHR { aabbs: aabbs_data }) + .flags(conv::map_acceleration_structure_geometry_flags(aabb.flags)); + + geometries.push(geometry); + primitive_counts.push(aabb.count); + } + (geometries, primitive_counts) + } + }; + + let ty = match *desc.entries { + crate::AccelerationStructureEntries::Instances(_) => { + vk::AccelerationStructureTypeKHR::TOP_LEVEL + } + _ => vk::AccelerationStructureTypeKHR::BOTTOM_LEVEL, + }; + + let geometry_info = vk::AccelerationStructureBuildGeometryInfoKHR::default() + .ty(ty) + .flags(conv::map_acceleration_structure_flags(desc.flags)) + .geometries(&geometries); + + let mut raw = Default::default(); + unsafe { + ray_tracing_functions + .acceleration_structure + .get_acceleration_structure_build_sizes( + vk::AccelerationStructureBuildTypeKHR::DEVICE, + &geometry_info, + &primitive_counts, + &mut raw, + ) + } + + crate::AccelerationStructureBuildSizes { + acceleration_structure_size: raw.acceleration_structure_size, + update_scratch_size: raw.update_scratch_size, + build_scratch_size: raw.build_scratch_size, + } + } + + unsafe fn get_acceleration_structure_device_address( + &self, + acceleration_structure: &super::AccelerationStructure, + ) -> wgt::BufferAddress { + let ray_tracing_functions = self + .shared + .extension_fns + .ray_tracing + .as_ref() + .expect("Feature `RAY_TRACING` not enabled"); + + unsafe { + ray_tracing_functions + .acceleration_structure + .get_acceleration_structure_device_address( + &vk::AccelerationStructureDeviceAddressInfoKHR::default() + .acceleration_structure(acceleration_structure.raw), + ) + } + } + + unsafe fn create_acceleration_structure( + &self, + desc: &crate::AccelerationStructureDescriptor, + ) -> Result<super::AccelerationStructure, crate::DeviceError> { + let ray_tracing_functions = self + .shared + .extension_fns + .ray_tracing + .as_ref() + .expect("Feature `RAY_TRACING` not enabled"); + + let vk_buffer_info = vk::BufferCreateInfo::default() + .size(desc.size) + .usage( + vk::BufferUsageFlags::ACCELERATION_STRUCTURE_STORAGE_KHR + | vk::BufferUsageFlags::SHADER_DEVICE_ADDRESS, + ) + .sharing_mode(vk::SharingMode::EXCLUSIVE); + + unsafe { + let raw_buffer = self + .shared + .raw + .create_buffer(&vk_buffer_info, None) + .map_err(super::map_host_device_oom_and_ioca_err)?; + + let requirements = self.shared.raw.get_buffer_memory_requirements(raw_buffer); + + self.error_if_would_oom_on_resource_allocation( + gpu_allocator::MemoryLocation::GpuOnly, + &requirements, + ) + .inspect_err(|_| { + self.shared.raw.destroy_buffer(raw_buffer, None); + })?; + + let name = desc + .label + .unwrap_or("Unlabeled acceleration structure buffer"); + + let allocation = self + .mem_allocator + .lock() + .allocate(&gpu_allocator::vulkan::AllocationCreateDesc { + name, + requirements, + location: gpu_allocator::MemoryLocation::GpuOnly, + linear: true, // Buffers are always linear + allocation_scheme: gpu_allocator::vulkan::AllocationScheme::GpuAllocatorManaged, + }) + .inspect_err(|_| { + self.shared.raw.destroy_buffer(raw_buffer, None); + })?; + + self.shared + .raw + .bind_buffer_memory(raw_buffer, allocation.memory(), allocation.offset()) + .map_err(super::map_host_device_oom_and_ioca_err) + .inspect_err(|_| { + self.shared.raw.destroy_buffer(raw_buffer, None); + })?; + + if let Some(label) = desc.label { + self.shared.set_object_name(raw_buffer, label); + } + + let vk_info = vk::AccelerationStructureCreateInfoKHR::default() + .buffer(raw_buffer) + .offset(0) + .size(desc.size) + .ty(conv::map_acceleration_structure_format(desc.format)); + + let raw_acceleration_structure = ray_tracing_functions + .acceleration_structure + .create_acceleration_structure(&vk_info, None) + .map_err(super::map_host_oom_and_ioca_err) + .inspect_err(|_| { + self.shared.raw.destroy_buffer(raw_buffer, None); + })?; + + if let Some(label) = desc.label { + self.shared + .set_object_name(raw_acceleration_structure, label); + } + + let pool = if desc.allow_compaction { + let vk_info = vk::QueryPoolCreateInfo::default() + .query_type(vk::QueryType::ACCELERATION_STRUCTURE_COMPACTED_SIZE_KHR) + .query_count(1); + + let raw = self + .shared + .raw + .create_query_pool(&vk_info, None) + .map_err(super::map_host_device_oom_err) + .inspect_err(|_| { + ray_tracing_functions + .acceleration_structure + .destroy_acceleration_structure(raw_acceleration_structure, None); + self.shared.raw.destroy_buffer(raw_buffer, None); + })?; + Some(raw) + } else { + None + }; + + Ok(super::AccelerationStructure { + raw: raw_acceleration_structure, + buffer: raw_buffer, + allocation, + compacted_size_query: pool, + }) + } + } + + unsafe fn destroy_acceleration_structure( + &self, + acceleration_structure: super::AccelerationStructure, + ) { + let ray_tracing_functions = self + .shared + .extension_fns + .ray_tracing + .as_ref() + .expect("Feature `RAY_TRACING` not enabled"); + + unsafe { + ray_tracing_functions + .acceleration_structure + .destroy_acceleration_structure(acceleration_structure.raw, None); + self.shared + .raw + .destroy_buffer(acceleration_structure.buffer, None); + let result = self + .mem_allocator + .lock() + .free(acceleration_structure.allocation); + if let Err(err) = result { + log::warn!("Failed to free buffer acceleration structure: {err}"); + } + if let Some(query) = acceleration_structure.compacted_size_query { + self.shared.raw.destroy_query_pool(query, None) + } + } + } + + fn get_internal_counters(&self) -> wgt::HalCounters { + self.counters + .memory_allocations + .set(self.shared.memory_allocations_counter.read()); + + self.counters.as_ref().clone() + } + + fn generate_allocator_report(&self) -> Option<wgt::AllocatorReport> { + let gpu_allocator::AllocatorReport { + allocations, + blocks, + total_allocated_bytes, + total_capacity_bytes, + } = self.mem_allocator.lock().generate_report(); + + let allocations = allocations + .into_iter() + .map(|alloc| wgt::AllocationReport { + name: alloc.name, + offset: alloc.offset, + size: alloc.size, + }) + .collect(); + + let blocks = blocks + .into_iter() + .map(|block| wgt::MemoryBlockReport { + size: block.size, + allocations: block.allocations.clone(), + }) + .collect(); + + Some(wgt::AllocatorReport { + allocations, + blocks, + total_allocated_bytes, + total_reserved_bytes: total_capacity_bytes, + }) + } + + fn tlas_instance_to_bytes(&self, instance: TlasInstance) -> Vec<u8> { + const MAX_U24: u32 = (1u32 << 24u32) - 1u32; + let temp = RawTlasInstance { + transform: instance.transform, + custom_data_and_mask: (instance.custom_data & MAX_U24) + | (u32::from(instance.mask) << 24), + shader_binding_table_record_offset_and_flags: (instance + .pipeline_intersection_data_offset + & MAX_U24), + acceleration_structure_reference: instance.blas_address, + }; + bytemuck::bytes_of(&temp).to_vec() + } + + fn check_if_oom(&self) -> Result<(), crate::DeviceError> { + let Some(threshold) = self + .shared + .instance + .memory_budget_thresholds + .for_device_loss + else { + return Ok(()); + }; + + let Some(memory_properties) = self.get_memory_properties() else { + return Ok(()); + }; + + for i in 0..memory_properties.heaps().len() { + let heap_usage = memory_properties.heap_usage()[i]; + let heap_budget = memory_properties.heap_budget()[i]; + + if heap_usage >= heap_budget / 100 * threshold as u64 { + return Err(crate::DeviceError::OutOfMemory); + } + } + + Ok(()) + } +} + +impl super::DeviceShared { + pub(super) fn new_binary_semaphore( + &self, + name: &str, + ) -> Result<vk::Semaphore, crate::DeviceError> { + unsafe { + let semaphore = self + .raw + .create_semaphore(&vk::SemaphoreCreateInfo::default(), None) + .map_err(super::map_host_device_oom_err)?; + + self.set_object_name(semaphore, name); + + Ok(semaphore) + } + } + + pub(super) fn wait_for_fence( + &self, + fence: &super::Fence, + wait_value: crate::FenceValue, + timeout_ns: u64, + ) -> Result<bool, crate::DeviceError> { + profiling::scope!("Device::wait"); + match *fence { + super::Fence::TimelineSemaphore(raw) => { + let semaphores = [raw]; + let values = [wait_value]; + let vk_info = vk::SemaphoreWaitInfo::default() + .semaphores(&semaphores) + .values(&values); + let result = match self.extension_fns.timeline_semaphore { + Some(super::ExtensionFn::Extension(ref ext)) => unsafe { + ext.wait_semaphores(&vk_info, timeout_ns) + }, + Some(super::ExtensionFn::Promoted) => unsafe { + self.raw.wait_semaphores(&vk_info, timeout_ns) + }, + None => unreachable!(), + }; + match result { + Ok(()) => Ok(true), + Err(vk::Result::TIMEOUT) => Ok(false), + Err(other) => Err(super::map_host_device_oom_and_lost_err(other)), + } + } + super::Fence::FencePool(ref pool) => { + let pool = pool.read(); + let super::FencePool { + last_completed, + ref active, + free: _, + } = *pool; + if wait_value <= last_completed { + Ok(true) + } else { + match active.iter().find(|&&(value, _)| value >= wait_value) { + Some((_, fence)) => { + // clone to show we are using this fence while the pool is unlocked. + let fence = fence.clone(); + drop(pool); + match unsafe { + self.raw.wait_for_fences( + core::slice::from_ref(&fence), + true, + timeout_ns, + ) + } { + Ok(()) => Ok(true), + Err(vk::Result::TIMEOUT) => Ok(false), + Err(other) => Err(super::map_host_device_oom_and_lost_err(other)), + } + } + None => { + crate::hal_usage_error(format!( + "no signals reached value {wait_value}" + )); + } + } + } + } + } + } +} + +struct ImageWithoutMemory { + raw: vk::Image, + requirements: vk::MemoryRequirements, +} diff --git a/app/vendor/rune/vendor/wgpu-hal/src/vulkan/drm.rs b/app/vendor/rune/vendor/wgpu-hal/src/vulkan/drm.rs new file mode 100644 index 0000000..9c03b04 --- /dev/null +++ b/app/vendor/rune/vendor/wgpu-hal/src/vulkan/drm.rs @@ -0,0 +1,252 @@ +#![cfg(drm)] + +use alloc::{string::ToString, vec::Vec}; +use core::{mem::MaybeUninit, num::NonZeroU32}; +use std::os::fd::{AsFd, BorrowedFd}; + +use ash::{ext, khr, vk}; + +use drm::{ + self, + control::{self, connector, Device as _}, +}; + +struct Card(i32); +impl AsFd for Card { + fn as_fd(&self) -> BorrowedFd<'_> { + unsafe { BorrowedFd::borrow_raw(self.0) } + } +} +impl control::Device for Card {} +impl drm::Device for Card {} + +macro_rules! to_u64 { + ($expr:expr) => {{ + #[allow(trivial_numeric_casts)] + let expr = $expr as u64; + assert!(size_of_val(&expr) <= size_of::<u64>()); + expr + }}; +} + +impl super::Instance { + /// Creates a new surface from the given drm fd and plane, deriving the connector and mode. + /// + /// # Safety + /// + /// - All parameters must point to valid DRM values. + pub fn create_surface_from_drm_plane( + &self, + fd: i32, + plane: u32, + ) -> Result<super::Surface, crate::InstanceError> { + let card = Card(fd); + let plane_info = card + .get_plane( + NonZeroU32::new(plane) + .ok_or(crate::InstanceError::new("Invalid drm plane".to_string()))? + .into(), + ) + .map_err(|e| crate::InstanceError::with_source("drm plane not found".to_string(), e))?; + let crtc_handle = plane_info.crtc().ok_or(crate::InstanceError::new( + "No CRTC for drm plane".to_string(), + ))?; + let crtc_info = card + .get_crtc(crtc_handle) + .map_err(|e| crate::InstanceError::with_source("drm CRTC not found".to_string(), e))?; + let mode = crtc_info.mode().ok_or(crate::InstanceError::new( + "No mode for drm CRTC".to_string(), + ))?; + + let mut connector_and_mode = None; + let resources = card.resource_handles().map_err(|e| { + crate::InstanceError::with_source("No drm resource handles found".to_string(), e) + })?; + for connector_handle in resources.connectors() { + let Ok(connector_info) = card.get_connector(*connector_handle, false) else { + continue; + }; + if connector_info.state() != connector::State::Connected { + continue; + } + + if let Some(encoder_handle) = connector_info.current_encoder() { + if let Ok(encoder_info) = card.get_encoder(encoder_handle) { + if encoder_info.crtc() == Some(crtc_handle) { + connector_and_mode = Some((*connector_handle, mode)); + break; + } + } + } + } + + let (connector_handle, mode) = connector_and_mode.ok_or(crate::InstanceError::new( + "Failed to derive drm connector and mode for plane".to_string(), + ))?; + let (width, height) = mode.size(); + // Rate in millihertz + let refresh_rate = (((mode.clock() as f64 * 1000.0) + / (mode.hsync().2 as f64 * mode.vsync().2 as f64)) + * 1000.0) + .round() as u32; + unsafe { + self.create_surface_from_drm( + fd, + plane, + connector_handle.into(), + width as u32, + height as u32, + refresh_rate, + ) + } + } + + /// Creates a new surface from the given drm configuration. + /// + /// # Safety + /// + /// - All parameters must point to valid DRM values. + pub unsafe fn create_surface_from_drm( + &self, + fd: i32, + plane: u32, + connector_id: u32, + width: u32, + height: u32, + refresh_rate: u32, + ) -> Result<super::Surface, crate::InstanceError> { + if !self + .shared + .extensions + .contains(&ext::acquire_drm_display::NAME) + { + return Err(crate::InstanceError::new( + "Vulkan driver does not support VK_EXT_acquire_drm_display".to_string(), + )); + } + + let drm_stat = { + let mut stat = MaybeUninit::<libc::stat>::uninit(); + + if unsafe { libc::fstat(fd, stat.as_mut_ptr()) } != 0 { + return Err(crate::InstanceError::new( + "Unable to fstat drm device".to_string(), + )); + } + + unsafe { stat.assume_init() } + }; + + let raw_devices = match unsafe { self.shared.raw.enumerate_physical_devices() } { + Ok(devices) => devices, + Err(err) => { + log::error!("enumerate_adapters: {err}"); + Vec::new() + } + }; + + let mut physical_device = None; + + for device in raw_devices { + let properties2 = vk::PhysicalDeviceProperties2KHR::default(); + + let mut drm_props = vk::PhysicalDeviceDrmPropertiesEXT::default(); + let mut properties2 = properties2.push_next(&mut drm_props); + + unsafe { + self.shared + .raw + .get_physical_device_properties2(device, &mut properties2) + }; + + /* + The makedev call is just bit manipulation to combine major and minor device numbers into a Unix device ID. + It doesn't perform any filesystem operations, only bitshifting. + See: https://github.com/rust-lang/libc/blob/268e1b3810ac07ed637d9005bc1a54e49218c958/src/unix/linux_like/linux/mod.rs#L6049 + We use the resulting device IDs to check if the Vulkan raw device from enumerate_physical_devices + matches the DRM device referred to by our file descriptor. + */ + + let primary_devid = + libc::makedev(drm_props.primary_major as _, drm_props.primary_minor as _); + let render_devid = + libc::makedev(drm_props.render_major as _, drm_props.render_minor as _); + + // On most platforms, both `*_devid`s and `st_rdev` are `dev_t`s (which is generally + // observed to be an unsigned integral type no greater than 64 bits). However, on some + // platforms, there divergences from this pattern: + // + // - `armv7-linux-androideabi`: `dev_t` is `c_ulong`, and `*_devid`s are `dev_t`, but + // `st_rdev` is `c_ulonglong`. So, we can't just do a `==` comparison. + // - OpenBSD has `dev_t` on both sides, but is `i32` (N.B., unsigned). Therefore, we + // can't just use `u64::from`. + #[allow(clippy::useless_conversion)] + if [primary_devid, render_devid] + .map(|devid| to_u64!(devid)) + .contains(&to_u64!(drm_stat.st_rdev)) + { + physical_device = Some(device) + } + } + + let physical_device = physical_device.ok_or(crate::InstanceError::new( + "Failed to find suitable drm device".to_string(), + ))?; + + let acquire_drm_display_instance = + ext::acquire_drm_display::Instance::new(&self.shared.entry, &self.shared.raw); + + let display = unsafe { + acquire_drm_display_instance + .get_drm_display(physical_device, fd, connector_id) + .expect("Failed to get drm display") + }; + + unsafe { + acquire_drm_display_instance + .acquire_drm_display(physical_device, fd, display) + .expect("Failed to acquire drm display") + } + + let display_instance = khr::display::Instance::new(&self.shared.entry, &self.shared.raw); + + let modes = unsafe { + display_instance + .get_display_mode_properties(physical_device, display) + .expect("Failed to get display modes") + }; + + let mut mode = None; + + for current_mode in modes { + log::trace!( + "Comparing mode {}x{}@{} with {width}x{height}@{refresh_rate}", + current_mode.parameters.visible_region.width, + current_mode.parameters.visible_region.height, + current_mode.parameters.refresh_rate + ); + if current_mode.parameters.refresh_rate == refresh_rate + && current_mode.parameters.visible_region.width == width + && current_mode.parameters.visible_region.height == height + { + mode = Some(current_mode) + } + } + + let mode = mode.ok_or(crate::InstanceError::new( + "Failed to find suitable display mode".to_string(), + ))?; + + let create_info = vk::DisplaySurfaceCreateInfoKHR::default() + .display_mode(mode.display_mode) + .image_extent(mode.parameters.visible_region) + .transform(vk::SurfaceTransformFlagsKHR::IDENTITY) + .alpha_mode(vk::DisplayPlaneAlphaFlagsKHR::OPAQUE) + .plane_index(plane); + + let surface = unsafe { display_instance.create_display_plane_surface(&create_info, None) } + .expect("Failed to create DRM surface"); + + Ok(self.create_surface_from_vk_surface_khr(surface, None)) + } +} diff --git a/app/vendor/rune/vendor/wgpu-hal/src/vulkan/instance.rs b/app/vendor/rune/vendor/wgpu-hal/src/vulkan/instance.rs new file mode 100644 index 0000000..1775875 --- /dev/null +++ b/app/vendor/rune/vendor/wgpu-hal/src/vulkan/instance.rs @@ -0,0 +1,1051 @@ +use alloc::{borrow::ToOwned as _, boxed::Box, ffi::CString, string::String, sync::Arc, vec::Vec}; +use core::{ + ffi::{c_void, CStr}, + marker::PhantomData, + slice, + str::FromStr, +}; +use std::thread; + +use arrayvec::ArrayVec; +use ash::{ext, khr, vk}; +use parking_lot::RwLock; + +unsafe extern "system" fn debug_utils_messenger_callback( + message_severity: vk::DebugUtilsMessageSeverityFlagsEXT, + message_type: vk::DebugUtilsMessageTypeFlagsEXT, + callback_data_ptr: *const vk::DebugUtilsMessengerCallbackDataEXT, + user_data: *mut c_void, +) -> vk::Bool32 { + use alloc::borrow::Cow; + + if thread::panicking() { + return vk::FALSE; + } + + let cd = unsafe { &*callback_data_ptr }; + let user_data = unsafe { &*user_data.cast::<super::DebugUtilsMessengerUserData>() }; + + const VUID_VKCMDENDDEBUGUTILSLABELEXT_COMMANDBUFFER_01912: i32 = 0x56146426; + if cd.message_id_number == VUID_VKCMDENDDEBUGUTILSLABELEXT_COMMANDBUFFER_01912 { + // https://github.com/KhronosGroup/Vulkan-ValidationLayers/issues/5671 + // Versions 1.3.240 through 1.3.250 return a spurious error here if + // the debug range start and end appear in different command buffers. + if let Some(layer_properties) = user_data.validation_layer_properties.as_ref() { + if layer_properties.layer_description.as_ref() == c"Khronos Validation Layer" + && layer_properties.layer_spec_version >= vk::make_api_version(0, 1, 3, 240) + && layer_properties.layer_spec_version <= vk::make_api_version(0, 1, 3, 250) + { + return vk::FALSE; + } + } + } + + // Silence Vulkan Validation error "VUID-VkSwapchainCreateInfoKHR-pNext-07781" + // This happens when a surface is configured with a size outside the allowed extent. + // It's a false positive due to the inherent racy-ness of surface resizing. + const VUID_VKSWAPCHAINCREATEINFOKHR_PNEXT_07781: i32 = 0x4c8929c1; + if cd.message_id_number == VUID_VKSWAPCHAINCREATEINFOKHR_PNEXT_07781 { + return vk::FALSE; + } + + // Silence Vulkan Validation error "VUID-VkRenderPassBeginInfo-framebuffer-04627" + // if the OBS layer is enabled. This is a bug in the OBS layer. As the OBS layer + // does not have a version number they increment, there is no way to qualify the + // suppression of the error to a specific version of the OBS layer. + // + // See https://github.com/obsproject/obs-studio/issues/9353 + const VUID_VKRENDERPASSBEGININFO_FRAMEBUFFER_04627: i32 = 0x45125641; + if cd.message_id_number == VUID_VKRENDERPASSBEGININFO_FRAMEBUFFER_04627 + && user_data.has_obs_layer + { + return vk::FALSE; + } + + // Silence Vulkan Validation error "VUID-vkCmdCopyImageToBuffer-pRegions-00184". + // While we aren't sure yet, we suspect this is probably a VVL issue. + // https://github.com/KhronosGroup/Vulkan-ValidationLayers/issues/9276 + const VUID_VKCMDCOPYIMAGETOBUFFER_PREGIONS_00184: i32 = 0x45ef177c; + if cd.message_id_number == VUID_VKCMDCOPYIMAGETOBUFFER_PREGIONS_00184 { + return vk::FALSE; + } + + // Silence Vulkan Validation error "VUID-StandaloneSpirv-None-10684". + // + // This is a bug. To prevent massive noise in the tests, lets suppress it for now. + // https://github.com/gfx-rs/wgpu/issues/7696 + const VUID_STANDALONESPIRV_NONE_10684: i32 = 0xb210f7c2_u32 as i32; + if cd.message_id_number == VUID_STANDALONESPIRV_NONE_10684 { + return vk::FALSE; + } + + let level = match message_severity { + // We intentionally suppress info messages down to debug + // so that users are not innundated with info messages from the runtime. + vk::DebugUtilsMessageSeverityFlagsEXT::VERBOSE => log::Level::Trace, + vk::DebugUtilsMessageSeverityFlagsEXT::INFO => log::Level::Debug, + vk::DebugUtilsMessageSeverityFlagsEXT::WARNING => log::Level::Warn, + vk::DebugUtilsMessageSeverityFlagsEXT::ERROR => log::Level::Error, + _ => log::Level::Warn, + }; + + let message_id_name = + unsafe { cd.message_id_name_as_c_str() }.map_or(Cow::Borrowed(""), CStr::to_string_lossy); + let message = unsafe { cd.message_as_c_str() }.map_or(Cow::Borrowed(""), CStr::to_string_lossy); + + let _ = std::panic::catch_unwind(|| { + log::log!( + level, + "{:?} [{} (0x{:x})]\n\t{}", + message_type, + message_id_name, + cd.message_id_number, + message, + ); + }); + + if cd.queue_label_count != 0 { + let labels = + unsafe { slice::from_raw_parts(cd.p_queue_labels, cd.queue_label_count as usize) }; + let names = labels + .iter() + .flat_map(|dul_obj| unsafe { dul_obj.label_name_as_c_str() }.map(CStr::to_string_lossy)) + .collect::<Vec<_>>(); + + let _ = std::panic::catch_unwind(|| { + log::log!(level, "\tqueues: {}", names.join(", ")); + }); + } + + if cd.cmd_buf_label_count != 0 { + let labels = + unsafe { slice::from_raw_parts(cd.p_cmd_buf_labels, cd.cmd_buf_label_count as usize) }; + let names = labels + .iter() + .flat_map(|dul_obj| unsafe { dul_obj.label_name_as_c_str() }.map(CStr::to_string_lossy)) + .collect::<Vec<_>>(); + + let _ = std::panic::catch_unwind(|| { + log::log!(level, "\tcommand buffers: {}", names.join(", ")); + }); + } + + if cd.object_count != 0 { + let labels = unsafe { slice::from_raw_parts(cd.p_objects, cd.object_count as usize) }; + //TODO: use color fields of `vk::DebugUtilsLabelExt`? + let names = labels + .iter() + .map(|obj_info| { + let name = unsafe { obj_info.object_name_as_c_str() } + .map_or(Cow::Borrowed("?"), CStr::to_string_lossy); + + format!( + "(type: {:?}, hndl: 0x{:x}, name: {})", + obj_info.object_type, obj_info.object_handle, name + ) + }) + .collect::<Vec<_>>(); + let _ = std::panic::catch_unwind(|| { + log::log!(level, "\tobjects: {}", names.join(", ")); + }); + } + + #[cfg(feature = "validation_canary")] + if cfg!(debug_assertions) && level == log::Level::Error { + use alloc::string::ToString as _; + + // Set canary and continue + crate::VALIDATION_CANARY.add(message.to_string()); + } + + vk::FALSE +} + +impl super::DebugUtilsCreateInfo { + fn to_vk_create_info(&self) -> vk::DebugUtilsMessengerCreateInfoEXT<'_> { + let user_data_ptr: *const super::DebugUtilsMessengerUserData = &*self.callback_data; + vk::DebugUtilsMessengerCreateInfoEXT::default() + .message_severity(self.severity) + .message_type(self.message_type) + .user_data(user_data_ptr as *mut _) + .pfn_user_callback(Some(debug_utils_messenger_callback)) + } +} + +impl super::InstanceShared { + pub fn entry(&self) -> &ash::Entry { + &self.entry + } + + pub fn raw_instance(&self) -> &ash::Instance { + &self.raw + } + + pub fn instance_api_version(&self) -> u32 { + self.instance_api_version + } + + pub fn extensions(&self) -> &[&'static CStr] { + &self.extensions[..] + } +} + +impl super::Instance { + pub fn shared_instance(&self) -> &super::InstanceShared { + &self.shared + } + + fn enumerate_instance_extension_properties( + entry: &ash::Entry, + layer_name: Option<&CStr>, + ) -> Result<Vec<vk::ExtensionProperties>, crate::InstanceError> { + let instance_extensions = { + profiling::scope!("vkEnumerateInstanceExtensionProperties"); + unsafe { entry.enumerate_instance_extension_properties(layer_name) } + }; + instance_extensions.map_err(|e| { + crate::InstanceError::with_source( + String::from("enumerate_instance_extension_properties() failed"), + e, + ) + }) + } + + /// Return the instance extension names wgpu would like to enable. + /// + /// Return a vector of the names of instance extensions actually available + /// on `entry` that wgpu would like to enable. + /// + /// The `instance_api_version` argument should be the instance's Vulkan API + /// version, as obtained from `vkEnumerateInstanceVersion`. This is the same + /// space of values as the `VK_API_VERSION` constants. + /// + /// Note that wgpu can function without many of these extensions (for + /// example, `VK_KHR_wayland_surface` is certainly not going to be available + /// everywhere), but if one of these extensions is available at all, wgpu + /// assumes that it has been enabled. + pub fn desired_extensions( + entry: &ash::Entry, + _instance_api_version: u32, + flags: wgt::InstanceFlags, + ) -> Result<Vec<&'static CStr>, crate::InstanceError> { + let instance_extensions = Self::enumerate_instance_extension_properties(entry, None)?; + + // Check our extensions against the available extensions + let mut extensions: Vec<&'static CStr> = Vec::new(); + + // VK_KHR_surface + extensions.push(khr::surface::NAME); + + // Platform-specific WSI extensions + if cfg!(all( + unix, + not(target_os = "android"), + not(target_os = "macos") + )) { + // VK_KHR_xlib_surface + extensions.push(khr::xlib_surface::NAME); + // VK_KHR_xcb_surface + extensions.push(khr::xcb_surface::NAME); + // VK_KHR_wayland_surface + extensions.push(khr::wayland_surface::NAME); + } + if cfg!(target_os = "android") { + // VK_KHR_android_surface + extensions.push(khr::android_surface::NAME); + } + if cfg!(target_os = "windows") { + // VK_KHR_win32_surface + extensions.push(khr::win32_surface::NAME); + } + if cfg!(target_os = "macos") { + // VK_EXT_metal_surface + extensions.push(ext::metal_surface::NAME); + extensions.push(khr::portability_enumeration::NAME); + } + if cfg!(drm) { + // VK_EXT_acquire_drm_display -> VK_EXT_direct_mode_display -> VK_KHR_display + extensions.push(ext::acquire_drm_display::NAME); + extensions.push(ext::direct_mode_display::NAME); + extensions.push(khr::display::NAME); + extensions.push(khr::get_physical_device_properties2::NAME); + extensions.push(khr::get_display_properties2::NAME); + } + + if flags.contains(wgt::InstanceFlags::DEBUG) { + // VK_EXT_debug_utils + extensions.push(ext::debug_utils::NAME); + } + + // VK_EXT_swapchain_colorspace + // Provides wide color gamut + extensions.push(ext::swapchain_colorspace::NAME); + + // VK_KHR_get_physical_device_properties2 + // Even though the extension was promoted to Vulkan 1.1, we still require the extension + // so that we don't have to conditionally use the functions provided by the 1.1 instance + extensions.push(khr::get_physical_device_properties2::NAME); + + // Only keep available extensions. + extensions.retain(|&ext| { + if instance_extensions + .iter() + .any(|inst_ext| inst_ext.extension_name_as_c_str() == Ok(ext)) + { + true + } else { + log::debug!("Unable to find extension: {}", ext.to_string_lossy()); + false + } + }); + Ok(extensions) + } + + /// # Safety + /// + /// - `raw_instance` must be created from `entry` + /// - `raw_instance` must be created respecting `instance_api_version`, `extensions` and `flags` + /// - `extensions` must be a superset of `desired_extensions()` and must be created from the + /// same entry, `instance_api_version`` and flags. + /// - `android_sdk_version` is ignored and can be `0` for all platforms besides Android + /// - If `drop_callback` is [`None`], wgpu-hal will take ownership of `raw_instance`. If + /// `drop_callback` is [`Some`], `raw_instance` must be valid until the callback is called. + /// + /// If `debug_utils_user_data` is `Some`, then the validation layer is + /// available, so create a [`vk::DebugUtilsMessengerEXT`]. + #[allow(clippy::too_many_arguments)] + pub unsafe fn from_raw( + entry: ash::Entry, + raw_instance: ash::Instance, + instance_api_version: u32, + android_sdk_version: u32, + debug_utils_create_info: Option<super::DebugUtilsCreateInfo>, + extensions: Vec<&'static CStr>, + flags: wgt::InstanceFlags, + memory_budget_thresholds: wgt::MemoryBudgetThresholds, + has_nv_optimus: bool, + drop_callback: Option<crate::DropCallback>, + ) -> Result<Self, crate::InstanceError> { + log::debug!("Instance version: 0x{instance_api_version:x}"); + + let debug_utils = if let Some(debug_utils_create_info) = debug_utils_create_info { + if extensions.contains(&ext::debug_utils::NAME) { + log::debug!("Enabling debug utils"); + + let extension = ext::debug_utils::Instance::new(&entry, &raw_instance); + let vk_info = debug_utils_create_info.to_vk_create_info(); + let messenger = + unsafe { extension.create_debug_utils_messenger(&vk_info, None) }.unwrap(); + + Some(super::DebugUtils { + extension, + messenger, + callback_data: debug_utils_create_info.callback_data, + }) + } else { + log::debug!("Debug utils not enabled: extension not listed"); + None + } + } else { + log::debug!( + "Debug utils not enabled: \ + debug_utils_user_data not passed to Instance::from_raw" + ); + None + }; + + let get_physical_device_properties = + if extensions.contains(&khr::get_physical_device_properties2::NAME) { + log::debug!("Enabling device properties2"); + Some(khr::get_physical_device_properties2::Instance::new( + &entry, + &raw_instance, + )) + } else { + None + }; + + let drop_guard = crate::DropGuard::from_option(drop_callback); + + Ok(Self { + shared: Arc::new(super::InstanceShared { + raw: raw_instance, + extensions, + drop_guard, + flags, + memory_budget_thresholds, + debug_utils, + get_physical_device_properties, + entry, + has_nv_optimus, + instance_api_version, + android_sdk_version, + }), + }) + } + + fn create_surface_from_xlib( + &self, + dpy: *mut vk::Display, + window: vk::Window, + ) -> Result<super::Surface, crate::InstanceError> { + if !self.shared.extensions.contains(&khr::xlib_surface::NAME) { + return Err(crate::InstanceError::new(String::from( + "Vulkan driver does not support VK_KHR_xlib_surface", + ))); + } + + let surface = { + let xlib_loader = + khr::xlib_surface::Instance::new(&self.shared.entry, &self.shared.raw); + let info = vk::XlibSurfaceCreateInfoKHR::default() + .flags(vk::XlibSurfaceCreateFlagsKHR::empty()) + .window(window) + .dpy(dpy); + + unsafe { xlib_loader.create_xlib_surface(&info, None) } + .expect("XlibSurface::create_xlib_surface() failed") + }; + + Ok(self.create_surface_from_vk_surface_khr(surface, None)) + } + + fn create_surface_from_xcb( + &self, + connection: *mut vk::xcb_connection_t, + window: vk::xcb_window_t, + ) -> Result<super::Surface, crate::InstanceError> { + if !self.shared.extensions.contains(&khr::xcb_surface::NAME) { + return Err(crate::InstanceError::new(String::from( + "Vulkan driver does not support VK_KHR_xcb_surface", + ))); + } + + let surface = { + let xcb_loader = khr::xcb_surface::Instance::new(&self.shared.entry, &self.shared.raw); + let info = vk::XcbSurfaceCreateInfoKHR::default() + .flags(vk::XcbSurfaceCreateFlagsKHR::empty()) + .window(window) + .connection(connection); + + unsafe { xcb_loader.create_xcb_surface(&info, None) } + .expect("XcbSurface::create_xcb_surface() failed") + }; + + Ok(self.create_surface_from_vk_surface_khr(surface, None)) + } + + fn create_surface_from_wayland( + &self, + display: *mut vk::wl_display, + surface: *mut vk::wl_surface, + ) -> Result<super::Surface, crate::InstanceError> { + if !self.shared.extensions.contains(&khr::wayland_surface::NAME) { + return Err(crate::InstanceError::new(String::from( + "Vulkan driver does not support VK_KHR_wayland_surface", + ))); + } + + let surface = { + let w_loader = + khr::wayland_surface::Instance::new(&self.shared.entry, &self.shared.raw); + let info = vk::WaylandSurfaceCreateInfoKHR::default() + .flags(vk::WaylandSurfaceCreateFlagsKHR::empty()) + .display(display) + .surface(surface); + + unsafe { w_loader.create_wayland_surface(&info, None) }.expect("WaylandSurface failed") + }; + + Ok(self.create_surface_from_vk_surface_khr(surface, None)) + } + + fn create_surface_android( + &self, + window: *mut vk::ANativeWindow, + ) -> Result<super::Surface, crate::InstanceError> { + if !self.shared.extensions.contains(&khr::android_surface::NAME) { + return Err(crate::InstanceError::new(String::from( + "Vulkan driver does not support VK_KHR_android_surface", + ))); + } + + let surface = { + let a_loader = + khr::android_surface::Instance::new(&self.shared.entry, &self.shared.raw); + let info = vk::AndroidSurfaceCreateInfoKHR::default() + .flags(vk::AndroidSurfaceCreateFlagsKHR::empty()) + .window(window); + + unsafe { a_loader.create_android_surface(&info, None) }.expect("AndroidSurface failed") + }; + + Ok(self.create_surface_from_vk_surface_khr(surface, None)) + } + + fn create_surface_from_hwnd( + &self, + hinstance: vk::HINSTANCE, + hwnd: vk::HWND, + ) -> Result<super::Surface, crate::InstanceError> { + if !self.shared.extensions.contains(&khr::win32_surface::NAME) { + return Err(crate::InstanceError::new(String::from( + "Vulkan driver does not support VK_KHR_win32_surface", + ))); + } + + let surface = { + let info = vk::Win32SurfaceCreateInfoKHR::default() + .flags(vk::Win32SurfaceCreateFlagsKHR::empty()) + .hinstance(hinstance) + .hwnd(hwnd); + let win32_loader = + khr::win32_surface::Instance::new(&self.shared.entry, &self.shared.raw); + unsafe { + win32_loader + .create_win32_surface(&info, None) + .expect("Unable to create Win32 surface") + } + }; + + // Wrap ash's `isize` `HWND` in `WindowHandle`; on Windows the + // `NativeSurface` builds its DXGI HDR source from it. + #[cfg(windows)] + let window_handle = Some(crate::vulkan::swapchain::WindowHandle( + windows::Win32::Foundation::HWND(hwnd as *mut c_void), + )); + #[cfg(not(windows))] + let window_handle: Option<crate::vulkan::swapchain::WindowHandle> = None; + Ok(self.create_surface_from_vk_surface_khr(surface, window_handle)) + } + + #[cfg(target_vendor = "apple")] + fn create_surface_from_layer( + &self, + layer: raw_window_metal::Layer, + ) -> Result<super::Surface, crate::InstanceError> { + if !self.shared.extensions.contains(&ext::metal_surface::NAME) { + return Err(crate::InstanceError::new(String::from( + "Vulkan driver does not support VK_EXT_metal_surface", + ))); + } + + // NOTE: The layer is retained by Vulkan's `vkCreateMetalSurfaceEXT`, + // so no need to retain it beyond the scope of this function. + let surface = { + let metal_loader = + ext::metal_surface::Instance::new(&self.shared.entry, &self.shared.raw); + let vk_info = vk::MetalSurfaceCreateInfoEXT::default() + .flags(vk::MetalSurfaceCreateFlagsEXT::empty()) + .layer(layer.as_ptr().as_ptr()); + + unsafe { metal_loader.create_metal_surface(&vk_info, None).unwrap() } + }; + + Ok(self.create_surface_from_vk_surface_khr(surface, None)) + } + + pub(super) fn create_surface_from_vk_surface_khr( + &self, + surface: vk::SurfaceKHR, + hwnd: Option<crate::vulkan::swapchain::WindowHandle>, + ) -> super::Surface { + let native_surface = + crate::vulkan::swapchain::NativeSurface::from_vk_surface_khr(self, surface, hwnd); + + super::Surface { + swapchain: RwLock::new(None), + inner: Box::new(native_surface), + } + } + + /// `Instance::init` but with a callback. + /// If you want to add extensions, add the to the `Vec<'static CStr>` not the create info, otherwise + /// it will be overwritten + /// + /// # Safety: + /// Same as `init` but additionally + /// - Callback must not remove features. + /// - Callback must not change anything to what the instance does not support. + pub unsafe fn init_with_callback( + desc: &crate::InstanceDescriptor<'_>, + callback: Option<Box<super::CreateInstanceCallback>>, + ) -> Result<Self, crate::InstanceError> { + profiling::scope!("Init Vulkan Backend"); + + let entry = unsafe { + profiling::scope!("Load vk library"); + // ohos support is already fixed on ash main, but it's unclear when + // a new release can happen. + #[cfg(target_env = "ohos")] + let loaded = ash::Entry::load_from("libvulkan.so"); + #[cfg(not(target_env = "ohos"))] + let loaded = ash::Entry::load(); + loaded + } + .map_err(|err| { + crate::InstanceError::with_source(String::from("missing Vulkan entry points"), err) + })?; + let version = { + profiling::scope!("vkEnumerateInstanceVersion"); + unsafe { entry.try_enumerate_instance_version() } + }; + let instance_api_version = match version { + // Vulkan 1.1+ + Ok(Some(version)) => version, + Ok(None) => vk::API_VERSION_1_0, + Err(err) => { + return Err(crate::InstanceError::with_source( + String::from("try_enumerate_instance_version() failed"), + err, + )); + } + }; + + let app_name = CString::new(desc.name).unwrap(); + let app_info = vk::ApplicationInfo::default() + .application_name(app_name.as_c_str()) + .application_version(1) + .engine_name(c"wgpu-hal") + .engine_version(2) + .api_version( + // Vulkan 1.0 doesn't like anything but 1.0 passed in here... + if instance_api_version < vk::API_VERSION_1_1 { + vk::API_VERSION_1_0 + } else { + // This is the max Vulkan API version supported by `wgpu-hal`. + // + // If we want to increment this, there are some things that must be done first: + // - Audit the behavioral differences between the previous and new API versions. + // - Audit all extensions used by this backend: + // - If any were promoted in the new API version and the behavior has changed, we must handle the new behavior in addition to the old behavior. + // - If any were obsoleted in the new API version, we must implement a fallback for the new API version + // - If any are non-KHR-vendored, we must ensure the new behavior is still correct (since backwards-compatibility is not guaranteed). + vk::API_VERSION_1_3 + }, + ); + + let mut extensions = Self::desired_extensions(&entry, instance_api_version, desc.flags)?; + let mut create_info = vk::InstanceCreateInfo::default(); + + if let Some(callback) = callback { + callback(super::CreateInstanceCallbackArgs { + extensions: &mut extensions, + create_info: &mut create_info, + entry: &entry, + _phantom: PhantomData, + }); + } + + let instance_layers = { + profiling::scope!("vkEnumerateInstanceLayerProperties"); + unsafe { entry.enumerate_instance_layer_properties() } + }; + let instance_layers = instance_layers.map_err(|e| { + log::debug!("enumerate_instance_layer_properties: {e:?}"); + crate::InstanceError::with_source( + String::from("enumerate_instance_layer_properties() failed"), + e, + ) + })?; + + fn find_layer<'layers>( + instance_layers: &'layers [vk::LayerProperties], + name: &CStr, + ) -> Option<&'layers vk::LayerProperties> { + instance_layers + .iter() + .find(|inst_layer| inst_layer.layer_name_as_c_str() == Ok(name)) + } + + let validation_layer_name = c"VK_LAYER_KHRONOS_validation"; + let validation_layer_properties = find_layer(&instance_layers, validation_layer_name); + + // Determine if VK_EXT_validation_features is available, so we can enable + // GPU assisted validation and synchronization validation. + let validation_features_are_enabled = if validation_layer_properties.is_some() { + // Get the all the instance extension properties. + let exts = + Self::enumerate_instance_extension_properties(&entry, Some(validation_layer_name))?; + // Convert all the names of the extensions into an iterator of CStrs. + let mut ext_names = exts + .iter() + .filter_map(|ext| ext.extension_name_as_c_str().ok()); + // Find the validation features extension. + ext_names.any(|ext_name| ext_name == ext::validation_features::NAME) + } else { + false + }; + + let should_enable_gpu_based_validation = desc + .flags + .intersects(wgt::InstanceFlags::GPU_BASED_VALIDATION) + && validation_features_are_enabled; + + let has_nv_optimus = find_layer(&instance_layers, c"VK_LAYER_NV_optimus").is_some(); + + let has_obs_layer = find_layer(&instance_layers, c"VK_LAYER_OBS_HOOK").is_some(); + + let mut layers: Vec<&'static CStr> = Vec::new(); + + let has_debug_extension = extensions.contains(&ext::debug_utils::NAME); + let mut debug_user_data = has_debug_extension.then(|| { + // Put the callback data on the heap, to ensure it will never be + // moved. + Box::new(super::DebugUtilsMessengerUserData { + validation_layer_properties: None, + has_obs_layer, + }) + }); + + // Request validation layer if asked. + if desc.flags.intersects(wgt::InstanceFlags::VALIDATION) + || should_enable_gpu_based_validation + { + if let Some(layer_properties) = validation_layer_properties { + layers.push(validation_layer_name); + + if let Some(debug_user_data) = debug_user_data.as_mut() { + debug_user_data.validation_layer_properties = + Some(super::ValidationLayerProperties { + layer_description: layer_properties + .description_as_c_str() + .unwrap() + .to_owned(), + layer_spec_version: layer_properties.spec_version, + }); + } + } else { + log::debug!( + "InstanceFlags::VALIDATION requested, but unable to find layer: {}", + validation_layer_name.to_string_lossy() + ); + } + } + let mut debug_utils = if let Some(callback_data) = debug_user_data { + // having ERROR unconditionally because Vk doesn't like empty flags + let mut severity = vk::DebugUtilsMessageSeverityFlagsEXT::ERROR; + if log::max_level() >= log::LevelFilter::Debug { + severity |= vk::DebugUtilsMessageSeverityFlagsEXT::VERBOSE; + } + if log::max_level() >= log::LevelFilter::Info { + severity |= vk::DebugUtilsMessageSeverityFlagsEXT::INFO; + } + if log::max_level() >= log::LevelFilter::Warn { + severity |= vk::DebugUtilsMessageSeverityFlagsEXT::WARNING; + } + + let message_type = vk::DebugUtilsMessageTypeFlagsEXT::GENERAL + | vk::DebugUtilsMessageTypeFlagsEXT::VALIDATION + | vk::DebugUtilsMessageTypeFlagsEXT::PERFORMANCE; + + let create_info = super::DebugUtilsCreateInfo { + severity, + message_type, + callback_data, + }; + + Some(create_info) + } else { + None + }; + + #[cfg(target_os = "android")] + let android_sdk_version = { + let properties = android_system_properties::AndroidSystemProperties::new(); + // See: https://developer.android.com/reference/android/os/Build.VERSION_CODES + if let Some(val) = properties.get("ro.build.version.sdk") { + match val.parse::<u32>() { + Ok(sdk_ver) => sdk_ver, + Err(err) => { + log::error!( + concat!( + "Couldn't parse Android's ", + "ro.build.version.sdk system property ({}): {}", + ), + val, + err, + ); + 0 + } + } + } else { + log::error!("Couldn't read Android's ro.build.version.sdk system property"); + 0 + } + }; + #[cfg(not(target_os = "android"))] + let android_sdk_version = 0; + + let mut flags = vk::InstanceCreateFlags::empty(); + + // Avoid VUID-VkInstanceCreateInfo-flags-06559: Only ask the instance to + // enumerate incomplete Vulkan implementations (which we need on Mac) if + // we managed to find the extension that provides the flag. + if extensions.contains(&khr::portability_enumeration::NAME) { + flags |= vk::InstanceCreateFlags::ENUMERATE_PORTABILITY_KHR; + } + let vk_instance = { + let str_pointers = layers + .iter() + .chain(extensions.iter()) + .map(|&s: &&'static _| { + // Safe because `layers` and `extensions` entries have static lifetime. + s.as_ptr() + }) + .collect::<Vec<_>>(); + + create_info = create_info + .flags(flags) + .application_info(&app_info) + .enabled_layer_names(&str_pointers[..layers.len()]) + .enabled_extension_names(&str_pointers[layers.len()..]); + + let mut debug_utils_create_info = debug_utils + .as_mut() + .map(|create_info| create_info.to_vk_create_info()); + if let Some(debug_utils_create_info) = debug_utils_create_info.as_mut() { + create_info = create_info.push_next(debug_utils_create_info); + } + + // Enable explicit validation features if available + let mut validation_features; + let mut validation_feature_list: ArrayVec<_, 3>; + if validation_features_are_enabled { + validation_feature_list = ArrayVec::new(); + + // Always enable synchronization validation + validation_feature_list + .push(vk::ValidationFeatureEnableEXT::SYNCHRONIZATION_VALIDATION); + + // Only enable GPU assisted validation if requested. + if should_enable_gpu_based_validation { + validation_feature_list.push(vk::ValidationFeatureEnableEXT::GPU_ASSISTED); + validation_feature_list + .push(vk::ValidationFeatureEnableEXT::GPU_ASSISTED_RESERVE_BINDING_SLOT); + } + + validation_features = vk::ValidationFeaturesEXT::default() + .enabled_validation_features(&validation_feature_list); + create_info = create_info.push_next(&mut validation_features); + } + + unsafe { + profiling::scope!("vkCreateInstance"); + entry.create_instance(&create_info, None) + } + .map_err(|e| { + crate::InstanceError::with_source( + String::from("Entry::create_instance() failed"), + e, + ) + })? + }; + + unsafe { + Self::from_raw( + entry, + vk_instance, + instance_api_version, + android_sdk_version, + debug_utils, + extensions, + desc.flags, + desc.memory_budget_thresholds, + has_nv_optimus, + None, + ) + } + } +} + +impl Drop for super::InstanceShared { + fn drop(&mut self) { + unsafe { + // Keep du alive since destroy_instance may also log + let _du = self.debug_utils.take().inspect(|du| { + du.extension + .destroy_debug_utils_messenger(du.messenger, None); + }); + if self.drop_guard.is_none() { + self.raw.destroy_instance(None); + } + } + } +} + +impl crate::Instance for super::Instance { + type A = super::Api; + + unsafe fn init(desc: &crate::InstanceDescriptor<'_>) -> Result<Self, crate::InstanceError> { + unsafe { Self::init_with_callback(desc, None) } + } + + unsafe fn create_surface( + &self, + display_handle: raw_window_handle::RawDisplayHandle, + window_handle: raw_window_handle::RawWindowHandle, + ) -> Result<super::Surface, crate::InstanceError> { + use raw_window_handle::{RawDisplayHandle as Rdh, RawWindowHandle as Rwh}; + + // TODO: Replace with ash-window, which also lazy-loads the extension based on handle type + + match (window_handle, display_handle) { + (Rwh::Wayland(handle), Rdh::Wayland(display)) => { + self.create_surface_from_wayland(display.display.as_ptr(), handle.surface.as_ptr()) + } + (Rwh::Xlib(handle), Rdh::Xlib(display)) => { + let display = display.display.expect("Display pointer is not set."); + self.create_surface_from_xlib(display.as_ptr(), handle.window) + } + (Rwh::Xcb(handle), Rdh::Xcb(display)) => { + let connection = display.connection.expect("Pointer to X-Server is not set."); + self.create_surface_from_xcb(connection.as_ptr(), handle.window.get()) + } + #[cfg(drm)] + (Rwh::Drm(handle), Rdh::Drm(display)) => { + self.create_surface_from_drm_plane(display.fd, handle.plane) + } + (Rwh::AndroidNdk(handle), _) => { + self.create_surface_android(handle.a_native_window.as_ptr()) + } + (Rwh::Win32(handle), _) => { + let hinstance = handle.hinstance.ok_or_else(|| { + crate::InstanceError::new(String::from( + "Vulkan requires raw-window-handle's Win32::hinstance to be set", + )) + })?; + self.create_surface_from_hwnd(hinstance.get(), handle.hwnd.get()) + } + #[cfg(target_vendor = "apple")] + (Rwh::AppKit(handle), _) + if self.shared.extensions.contains(&ext::metal_surface::NAME) => + { + let layer = unsafe { raw_window_metal::Layer::from_ns_view(handle.ns_view) }; + self.create_surface_from_layer(layer) + } + #[cfg(target_vendor = "apple")] + (Rwh::UiKit(handle), _) + if self.shared.extensions.contains(&ext::metal_surface::NAME) => + { + let layer = unsafe { raw_window_metal::Layer::from_ui_view(handle.ui_view) }; + self.create_surface_from_layer(layer) + } + (_, _) => Err(crate::InstanceError::new(format!( + "window handle {window_handle:?} is not a Vulkan-compatible handle" + ))), + } + } + + unsafe fn enumerate_adapters( + &self, + _surface_hint: Option<&super::Surface>, + ) -> Vec<crate::ExposedAdapter<super::Api>> { + use crate::auxil::db; + + let raw_devices = match unsafe { self.shared.raw.enumerate_physical_devices() } { + Ok(devices) => devices, + Err(err) => { + log::error!("enumerate_adapters: {err}"); + Vec::new() + } + }; + + let mut exposed_adapters = raw_devices + .into_iter() + .flat_map(|device| self.expose_adapter(device)) + .collect::<Vec<_>>(); + + // Detect if it's an Intel + NVidia configuration with Optimus + let has_nvidia_dgpu = exposed_adapters.iter().any(|exposed| { + exposed.info.device_type == wgt::DeviceType::DiscreteGpu + && exposed.info.vendor == db::nvidia::VENDOR + }); + if cfg!(target_os = "linux") && has_nvidia_dgpu && self.shared.has_nv_optimus { + for exposed in exposed_adapters.iter_mut() { + if exposed.info.device_type == wgt::DeviceType::IntegratedGpu + && exposed.info.vendor == db::intel::VENDOR + { + // Check if mesa driver and version less than 21.2 + if let Some(version) = exposed.info.driver_info.split_once("Mesa ").map(|s| { + let mut components = s.1.split('.'); + let major = components.next().and_then(|s| u8::from_str(s).ok()); + let minor = components.next().and_then(|s| u8::from_str(s).ok()); + if let (Some(major), Some(minor)) = (major, minor) { + (major, minor) + } else { + (0, 0) + } + }) { + if version < (21, 2) { + // See https://gitlab.freedesktop.org/mesa/mesa/-/issues/4688 + log::debug!( + concat!( + "Disabling presentation on '{}' (id {:?}) ", + "due to NV Optimus and Intel Mesa < v21.2" + ), + exposed.info.name, + exposed.adapter.raw + ); + exposed.adapter.private_caps.can_present = false; + } + } + } + } + } + + exposed_adapters + } +} + +impl crate::Surface for super::Surface { + type A = super::Api; + + unsafe fn configure( + &self, + device: &super::Device, + config: &crate::SurfaceConfiguration, + ) -> Result<(), crate::SurfaceError> { + // SAFETY: `configure`'s contract guarantees there are no resources derived from the swapchain in use. + let mut swap_chain = self.swapchain.write(); + + let mut old = swap_chain.take(); + if let Some(ref mut old) = old { + unsafe { old.release_resources(device) }; + } + + let swapchain = unsafe { self.inner.create_swapchain(device, config, old)? }; + *swap_chain = Some(swapchain); + + Ok(()) + } + + unsafe fn unconfigure(&self, device: &super::Device) { + if let Some(mut sc) = self.swapchain.write().take() { + // SAFETY: `unconfigure`'s contract guarantees there are no resources derived from the swapchain in use. + unsafe { sc.release_resources(device) }; + } + } + + unsafe fn acquire_texture( + &self, + timeout: Option<core::time::Duration>, + fence: &super::Fence, + ) -> Result<crate::AcquiredSurfaceTexture<super::Api>, crate::SurfaceError> { + let mut swapchain = self.swapchain.write(); + let swapchain = swapchain.as_mut().unwrap(); + + unsafe { swapchain.acquire(timeout, fence) } + } + + unsafe fn discard_texture(&self, texture: super::SurfaceTexture) { + unsafe { + self.swapchain + .write() + .as_mut() + .unwrap() + .discard_texture(texture) + .unwrap() + }; + } +} diff --git a/app/vendor/rune/vendor/wgpu-hal/src/vulkan/mod.rs b/app/vendor/rune/vendor/wgpu-hal/src/vulkan/mod.rs new file mode 100644 index 0000000..51e7414 --- /dev/null +++ b/app/vendor/rune/vendor/wgpu-hal/src/vulkan/mod.rs @@ -0,0 +1,1763 @@ +/*! +# Vulkan API internals. + +## Stack memory + +Ash expects slices, which we don't generally have available. +We cope with this requirement by the combination of the following ways: + - temporarily allocating `Vec` on heap, where overhead is permitted + - growing temporary local storage + +## Framebuffers and Render passes + +Render passes are cached on the device and kept forever. + +Framebuffers are also cached on the device, but they are removed when +any of the image views (they have) gets removed. +If Vulkan supports image-less framebuffers, +then the actual views are excluded from the framebuffer key. + +## Fences + +If timeline semaphores are available, they are used 1:1 with wgpu-hal fences. +Otherwise, we manage a pool of `VkFence` objects behind each `hal::Fence`. + +!*/ + +mod adapter; +mod command; +pub mod conv; +mod descriptor; +mod device; +mod drm; +mod instance; +mod sampler; +mod semaphore_list; +mod swapchain; + +pub use adapter::PhysicalDeviceFeatures; + +use alloc::{boxed::Box, ffi::CString, sync::Arc, vec::Vec}; +use core::{borrow::Borrow, ffi::CStr, fmt, marker::PhantomData, mem, num::NonZeroU32}; + +use arrayvec::ArrayVec; +use ash::{ext, khr, vk}; +use bytemuck::{Pod, Zeroable}; +use hashbrown::HashSet; +use parking_lot::{Mutex, RwLock}; + +use naga::FastHashMap; +use wgt::InternalCounter; + +use semaphore_list::SemaphoreList; + +use crate::vulkan::semaphore_list::{SemaphoreListMode, SemaphoreType}; + +const MAX_TOTAL_ATTACHMENTS: usize = crate::MAX_COLOR_ATTACHMENTS * 2 + 1; + +#[derive(Clone, Debug)] +pub struct Api; + +impl crate::Api for Api { + const VARIANT: wgt::Backend = wgt::Backend::Vulkan; + + type Instance = Instance; + type Surface = Surface; + type Adapter = Adapter; + type Device = Device; + + type Queue = Queue; + type CommandEncoder = CommandEncoder; + type CommandBuffer = CommandBuffer; + + type Buffer = Buffer; + type Texture = Texture; + type SurfaceTexture = SurfaceTexture; + type TextureView = TextureView; + type Sampler = Sampler; + type QuerySet = QuerySet; + type Fence = Fence; + type AccelerationStructure = AccelerationStructure; + type PipelineCache = PipelineCache; + + type BindGroupLayout = BindGroupLayout; + type BindGroup = BindGroup; + type PipelineLayout = PipelineLayout; + type ShaderModule = ShaderModule; + type RenderPipeline = RenderPipeline; + type ComputePipeline = ComputePipeline; + type RayTracingPipeline = RayTracingPipeline; +} + +crate::impl_dyn_resource!( + Adapter, + AccelerationStructure, + BindGroup, + BindGroupLayout, + Buffer, + CommandBuffer, + CommandEncoder, + ComputePipeline, + Device, + Fence, + Instance, + PipelineCache, + PipelineLayout, + QuerySet, + Queue, + RenderPipeline, + RayTracingPipeline, + Sampler, + ShaderModule, + Surface, + SurfaceTexture, + Texture, + TextureView +); + +struct DebugUtils { + extension: ext::debug_utils::Instance, + messenger: vk::DebugUtilsMessengerEXT, + + /// Owning pointer to the debug messenger callback user data. + /// + /// `InstanceShared::drop` destroys the debug messenger before + /// dropping this, so the callback should never receive a dangling + /// user data pointer. + #[allow(dead_code)] + callback_data: Box<DebugUtilsMessengerUserData>, +} + +#[derive(Debug)] +pub struct DebugUtilsCreateInfo { + severity: vk::DebugUtilsMessageSeverityFlagsEXT, + message_type: vk::DebugUtilsMessageTypeFlagsEXT, + callback_data: Box<DebugUtilsMessengerUserData>, +} + +#[derive(Debug)] +/// The properties related to the validation layer needed for the +/// DebugUtilsMessenger for their workarounds +struct ValidationLayerProperties { + /// Validation layer description, from `vk::LayerProperties`. + layer_description: CString, + + /// Validation layer specification version, from `vk::LayerProperties`. + layer_spec_version: u32, +} + +/// User data needed by `instance::debug_utils_messenger_callback`. +/// +/// When we create the [`vk::DebugUtilsMessengerEXT`], the `pUserData` +/// pointer refers to one of these values. +#[derive(Debug)] +pub struct DebugUtilsMessengerUserData { + /// The properties related to the validation layer, if present + validation_layer_properties: Option<ValidationLayerProperties>, + + /// If the OBS layer is present. OBS never increments the version of their layer, + /// so there's no reason to have the version. + has_obs_layer: bool, +} + +pub struct InstanceShared { + raw: ash::Instance, + extensions: Vec<&'static CStr>, + flags: wgt::InstanceFlags, + memory_budget_thresholds: wgt::MemoryBudgetThresholds, + debug_utils: Option<DebugUtils>, + get_physical_device_properties: Option<khr::get_physical_device_properties2::Instance>, + entry: ash::Entry, + has_nv_optimus: bool, + android_sdk_version: u32, + /// The instance API version. + /// + /// Which is the version of Vulkan supported for instance-level functionality. + /// + /// It is associated with a `VkInstance` and its children, + /// except for a `VkPhysicalDevice` and its children. + instance_api_version: u32, + + // The `drop_guard` field must be the last field of this struct so it is dropped last. + // Do not add new fields after it. + drop_guard: Option<crate::DropGuard>, +} + +impl fmt::Debug for InstanceShared { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let Self { + raw: _, + extensions, + flags, + memory_budget_thresholds, + debug_utils: _, + get_physical_device_properties: _, + entry: _, + has_nv_optimus, + android_sdk_version, + instance_api_version, + drop_guard: _, + } = self; + f.debug_struct("InstanceShared") + .field("extensions", extensions) + .field("flags", flags) + .field("memory_budget_thresholds", memory_budget_thresholds) + .field("has_nv_optimus", has_nv_optimus) + .field("android_sdk_version", android_sdk_version) + .field("instance_api_version", instance_api_version) + .finish_non_exhaustive() + } +} + +#[derive(Debug)] +pub struct Instance { + shared: Arc<InstanceShared>, +} + +#[expect(missing_debug_implementations, reason = "TODO?")] +pub struct Surface { + swapchain: RwLock<Option<Box<dyn swapchain::Swapchain>>>, + inner: Box<dyn swapchain::Surface>, +} + +impl Surface { + /// Returns the raw Vulkan surface handle. + /// + /// Returns `None` if the surface is a DXGI surface. + pub unsafe fn raw_native_handle(&self) -> Option<vk::SurfaceKHR> { + Some( + self.inner + .as_any() + .downcast_ref::<swapchain::NativeSurface>()? + .as_raw(), + ) + } + + /// Get the raw Vulkan swapchain associated with this surface. + /// + /// Returns [`None`] if the surface is not configured or if the swapchain + /// is a DXGI swapchain. + pub fn raw_native_swapchain(&self) -> Option<vk::SwapchainKHR> { + let read = self.swapchain.read(); + Some( + read.as_ref()? + .as_any() + .downcast_ref::<swapchain::NativeSwapchain>()? + .as_raw(), + ) + } + + /// Set the present timing information which will be used for the next [presentation](crate::Queue::present()) of this surface, + /// using [VK_GOOGLE_display_timing]. + /// + /// This can be used to give an id to presentations, for future use of [`vk::PastPresentationTimingGOOGLE`]. + /// Note that `wgpu-hal` does *not* provide a way to use that API - you should manually access this through [`ash`]. + /// + /// This can also be used to add a "not before" timestamp to the presentation. + /// + /// The exact semantics of the fields are also documented in the [specification](https://registry.khronos.org/vulkan/specs/1.3-extensions/man/html/VkPresentTimeGOOGLE.html) for the extension. + /// + /// # Panics + /// + /// - If the surface hasn't been configured. + /// - If the surface has been configured for a DXGI swapchain. + /// - If the device doesn't [support present timing](wgt::Features::VULKAN_GOOGLE_DISPLAY_TIMING). + /// + /// [VK_GOOGLE_display_timing]: https://registry.khronos.org/vulkan/specs/1.3-extensions/man/html/VK_GOOGLE_display_timing.html + #[track_caller] + pub fn set_next_present_time(&self, present_timing: vk::PresentTimeGOOGLE) { + let mut swapchain = self.swapchain.write(); + swapchain + .as_mut() + .expect("Surface should have been configured") + .as_any_mut() + .downcast_mut::<swapchain::NativeSwapchain>() + .expect("Surface should have a native Vulkan swapchain") + .set_next_present_time(present_timing); + } +} + +#[derive(Debug)] +pub struct SurfaceTexture { + index: u32, + texture: Texture, + metadata: Box<dyn swapchain::SurfaceTextureMetadata>, +} + +impl crate::DynSurfaceTexture for SurfaceTexture {} + +impl Borrow<Texture> for SurfaceTexture { + fn borrow(&self) -> &Texture { + &self.texture + } +} + +impl Borrow<dyn crate::DynTexture> for SurfaceTexture { + fn borrow(&self) -> &dyn crate::DynTexture { + &self.texture + } +} + +#[derive(Debug)] +pub struct Adapter { + raw: vk::PhysicalDevice, + instance: Arc<InstanceShared>, + //queue_families: Vec<vk::QueueFamilyProperties>, + known_memory_flags: vk::MemoryPropertyFlags, + phd_capabilities: adapter::PhysicalDeviceProperties, + phd_features: PhysicalDeviceFeatures, + downlevel_flags: wgt::DownlevelFlags, + private_caps: PrivateCapabilities, + workarounds: Workarounds, +} + +// TODO there's no reason why this can't be unified--the function pointers should all be the same--it's not clear how to do this with `ash`. +enum ExtensionFn<T> { + /// The loaded function pointer struct for an extension. + Extension(T), + /// The extension was promoted to a core version of Vulkan and the functions on `ash`'s `DeviceV1_x` traits should be used. + Promoted, +} + +struct DeviceExtensionFunctions { + debug_utils: Option<ext::debug_utils::Device>, + draw_indirect_count: Option<khr::draw_indirect_count::Device>, + timeline_semaphore: Option<ExtensionFn<khr::timeline_semaphore::Device>>, + ray_tracing: Option<RayTracingDeviceExtensionFunctions>, + ray_tracing_pipelines: Option<khr::ray_tracing_pipeline::Device>, + mesh_shading: Option<ext::mesh_shader::Device>, + #[cfg_attr(not(unix), allow(dead_code))] + external_memory_fd: Option<khr::external_memory_fd::Device>, +} + +struct RayTracingDeviceExtensionFunctions { + acceleration_structure: khr::acceleration_structure::Device, + buffer_device_address: khr::buffer_device_address::Device, +} + +/// Set of internal capabilities, which don't show up in the exposed +/// device geometry, but affect the code paths taken internally. +#[derive(Clone, Debug)] +struct PrivateCapabilities { + image_view_usage: bool, + timeline_semaphores: bool, + texture_d24: bool, + texture_d24_s8: bool, + texture_s8: bool, + /// Ability to present contents to any screen. Only needed to work around broken platform configurations. + can_present: bool, + non_coherent_map_mask: wgt::BufferAddress, + multi_draw_indirect: bool, + max_draw_indirect_count: u32, + + /// True if this adapter advertises the [`robustBufferAccess`][vrba] feature. + /// + /// Note that Vulkan's `robustBufferAccess` is not sufficient to implement + /// `wgpu_hal`'s guarantee that shaders will not access buffer contents via + /// a given bindgroup binding outside that binding's [accessible + /// region][ar]. Enabling `robustBufferAccess` does ensure that + /// out-of-bounds reads and writes are not undefined behavior (that's good), + /// but still permits out-of-bounds reads to return data from anywhere + /// within the buffer, not just the accessible region. + /// + /// [ar]: ../struct.BufferBinding.html#accessible-region + /// [vrba]: https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html#features-robustBufferAccess + robust_buffer_access: bool, + + robust_image_access: bool, + + /// True if this adapter supports the [`VK_EXT_robustness2`] extension's + /// [`robustBufferAccess2`] feature. + /// + /// This is sufficient to implement `wgpu_hal`'s [required bounds-checking][ar] of + /// shader accesses to buffer contents. If this feature is not available, + /// this backend must have Naga inject bounds checks in the generated + /// SPIR-V. + /// + /// [`VK_EXT_robustness2`]: https://registry.khronos.org/vulkan/specs/1.3-extensions/man/html/VK_EXT_robustness2.html + /// [`robustBufferAccess2`]: https://registry.khronos.org/vulkan/specs/1.3-extensions/man/html/VkPhysicalDeviceRobustness2FeaturesEXT.html#features-robustBufferAccess2 + /// [ar]: ../struct.BufferBinding.html#accessible-region + robust_buffer_access2: bool, + + robust_image_access2: bool, + zero_initialize_workgroup_memory: bool, + image_format_list: bool, + maximum_samplers: u32, + + /// True if this adapter supports the [`VK_KHR_shader_integer_dot_product`] extension + /// (promoted to Vulkan 1.3). + /// + /// This is used to generate optimized code for WGSL's `dot4{I, U}8Packed`. + /// + /// [`VK_KHR_shader_integer_dot_product`]: https://registry.khronos.org/vulkan/specs/1.3-extensions/man/html/VK_KHR_shader_integer_dot_product.html + shader_integer_dot_product: bool, + + /// True if this adapter supports 8-bit integers provided by the + /// [`VK_KHR_shader_float16_int8`] extension (promoted to Vulkan 1.2). + /// + /// Allows shaders to declare the "Int8" capability. Note, however, that this + /// feature alone allows the use of 8-bit integers "only in the `Private`, + /// `Workgroup` (for non-Block variables), and `Function` storage classes" + /// ([see spec]). To use 8-bit integers in the interface storage classes (e.g., + /// `StorageBuffer`), you also need to enable the corresponding feature in + /// `VkPhysicalDevice8BitStorageFeatures` and declare the corresponding SPIR-V + /// capability (e.g., `StorageBuffer8BitAccess`). + /// + /// [`VK_KHR_shader_float16_int8`]: https://registry.khronos.org/vulkan/specs/latest/man/html/VK_KHR_shader_float16_int8.html + /// [see spec]: https://registry.khronos.org/vulkan/specs/latest/man/html/VkPhysicalDeviceShaderFloat16Int8Features.html#extension-features-shaderInt8 + shader_int8: bool, + + /// This is done to panic before undefined behavior, and is imperfect. + /// Basically, to allow implementations to emulate mv using instancing, if you + /// want to draw `n` instances to VR, you must draw `2n` instances, but you + /// can never draw more than `u32::MAX` instances. Therefore, when drawing + /// multiview on some vulkan implementations, it might restrict the instance + /// count, which isn't usually a thing in webgpu. We don't expose this limit + /// because its strange, i.e. only occurs on certain vulkan implementations + /// if you are drawing more than 128 million instances. We still want to avoid + /// undefined behavior in this situation, so we panic if the limit is violated. + multiview_instance_index_limit: u32, + + /// BufferUsages::ACCELERATION_STRUCTURE_SCRATCH allows usage as a scratch buffer. + /// Vulkan has no way to specify this as a usage, and it maps to other usages, but + /// these usages do not have as high of an alignment requirement using the buffer as + /// a scratch buffer when building acceleration structures. + scratch_buffer_alignment: u32, + + /// `get_raytracing_pipeline_group_data` requires both a group count and a data size. + /// The data size parameter is just this * the group count, so we store this to not + /// require an unnecessary parameter. + ray_tracing_pipeline_group_data_size: u32, +} + +bitflags::bitflags!( + /// Workaround flags. + #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)] + pub struct Workarounds: u32 { + /// Only generate SPIR-V for one entry point at a time. + const SEPARATE_ENTRY_POINTS = 0x1; + /// Qualcomm OOMs when there are zero color attachments but a non-null pointer + /// to a subpass resolve attachment array. This nulls out that pointer in that case. + const EMPTY_RESOLVE_ATTACHMENT_LISTS = 0x2; + /// If the following code returns false, then nvidia will end up filling the wrong range. + /// + /// ```skip + /// fn nvidia_succeeds() -> bool { + /// # let (copy_length, start_offset) = (0, 0); + /// if copy_length >= 4096 { + /// if start_offset % 16 != 0 { + /// if copy_length == 4096 { + /// return true; + /// } + /// if copy_length % 16 == 0 { + /// return false; + /// } + /// } + /// } + /// true + /// } + /// ``` + /// + /// As such, we need to make sure all calls to vkCmdFillBuffer are aligned to 16 bytes + /// if they cover a range of 4096 bytes or more. + const FORCE_FILL_BUFFER_WITH_SIZE_GREATER_4096_ALIGNED_OFFSET_16 = 0x4; + } +); + +#[derive(Clone, Debug, Eq, Hash, PartialEq)] +struct AttachmentKey { + format: vk::Format, + layout: vk::ImageLayout, + ops: crate::AttachmentOps, +} + +impl AttachmentKey { + /// Returns an attachment key for a compatible attachment. + fn compatible(format: vk::Format, layout: vk::ImageLayout) -> Self { + Self { + format, + layout, + ops: crate::AttachmentOps::all(), + } + } +} + +#[derive(Clone, Eq, Hash, PartialEq)] +struct ColorAttachmentKey { + base: AttachmentKey, + resolve: Option<AttachmentKey>, +} + +#[derive(Clone, Eq, Hash, PartialEq)] +struct DepthStencilAttachmentKey { + base: AttachmentKey, + stencil_ops: crate::AttachmentOps, +} + +#[derive(Clone, Eq, Default, Hash, PartialEq)] +struct RenderPassKey { + colors: ArrayVec<Option<ColorAttachmentKey>, { crate::MAX_COLOR_ATTACHMENTS }>, + depth_stencil: Option<DepthStencilAttachmentKey>, + sample_count: u32, + multiview_mask: Option<NonZeroU32>, +} + +struct DeviceShared { + raw: ash::Device, + family_index: u32, + queue_index: u32, + raw_queue: vk::Queue, + instance: Arc<InstanceShared>, + physical_device: vk::PhysicalDevice, + enabled_extensions: Vec<&'static CStr>, + extension_fns: DeviceExtensionFunctions, + vendor_id: u32, + pipeline_cache_validation_key: [u8; 16], + timestamp_period: f32, + private_caps: PrivateCapabilities, + workarounds: Workarounds, + features: wgt::Features, + render_passes: Mutex<FastHashMap<RenderPassKey, vk::RenderPass>>, + sampler_cache: Mutex<sampler::SamplerCache>, + memory_allocations_counter: InternalCounter, + + /// Because we have cached framebuffers which are not deleted from until + /// the device is destroyed, if the implementation of vulkan re-uses handles + /// we need some way to differentiate between the old handle and the new handle. + /// This factory allows us to have a dedicated identity value for each texture. + texture_identity_factory: ResourceIdentityFactory<vk::Image>, + /// As above, for texture views. + texture_view_identity_factory: ResourceIdentityFactory<vk::ImageView>, + + empty_descriptor_set_layout: vk::DescriptorSetLayout, + + // The `drop_guard` field must be the last field of this struct so it is dropped last. + // Do not add new fields after it. + drop_guard: Option<crate::DropGuard>, +} + +impl Drop for DeviceShared { + fn drop(&mut self) { + for &raw in self.render_passes.lock().values() { + unsafe { self.raw.destroy_render_pass(raw, None) }; + } + unsafe { + self.raw + .destroy_descriptor_set_layout(self.empty_descriptor_set_layout, None) + }; + if self.drop_guard.is_none() { + unsafe { self.raw.destroy_device(None) }; + } + } +} + +#[expect( + missing_debug_implementations, + reason = "needs work to not be disastrously verbose" +)] +pub struct Device { + mem_allocator: Mutex<gpu_allocator::vulkan::Allocator>, + desc_allocator: Mutex<descriptor::DescriptorAllocator>, + valid_ash_memory_types: u32, + naga_options: naga::back::spv::Options<'static>, + #[cfg(feature = "renderdoc")] + render_doc: crate::auxil::renderdoc::RenderDoc, + counters: Arc<wgt::HalCounters>, + // Struct members are dropped from first to last, put the Device last to ensure that + // all resources that depends on it are destroyed before it like the mem_allocator + shared: Arc<DeviceShared>, +} + +impl Drop for Device { + fn drop(&mut self) {} +} + +/// Semaphores for forcing queue submissions to run in order. +/// +/// The [`wgpu_hal::Queue`] trait promises that if two calls to [`submit`] are +/// ordered, then the first submission will finish on the GPU before the second +/// submission begins. To get this behavior on Vulkan we need to pass semaphores +/// to [`vkQueueSubmit`] for the commands to wait on before beginning execution, +/// and to signal when their execution is done. +/// +/// Normally this can be done with a single semaphore, waited on and then +/// signalled for each submission. At any given time there's exactly one +/// submission that would signal the semaphore, and exactly one waiting on it, +/// as Vulkan requires. +/// +/// However, as of Oct 2021, bug [#5508] in the Mesa ANV drivers caused them to +/// hang if we use a single semaphore. The workaround is to alternate between +/// two semaphores. The bug has been fixed in Mesa, but we should probably keep +/// the workaround until, say, Oct 2026. +/// +/// [`wgpu_hal::Queue`]: crate::Queue +/// [`submit`]: crate::Queue::submit +/// [`vkQueueSubmit`]: https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html#vkQueueSubmit +/// [#5508]: https://gitlab.freedesktop.org/mesa/mesa/-/issues/5508 +#[derive(Clone)] +struct RelaySemaphores { + /// The semaphore the next submission should wait on before beginning + /// execution on the GPU. This is `None` for the first submission, which + /// should not wait on anything at all. + wait: Option<vk::Semaphore>, + + /// The semaphore the next submission should signal when it has finished + /// execution on the GPU. + signal: vk::Semaphore, +} + +impl RelaySemaphores { + fn new(device: &DeviceShared) -> Result<Self, crate::DeviceError> { + Ok(Self { + wait: None, + signal: device.new_binary_semaphore("RelaySemaphores: 1")?, + }) + } + + /// Advances the semaphores, returning the semaphores that should be used for a submission. + fn advance(&mut self, device: &DeviceShared) -> Result<Self, crate::DeviceError> { + let old = self.clone(); + + // Build the state for the next submission. + match self.wait { + None => { + // The `old` values describe the first submission to this queue. + // The second submission should wait on `old.signal`, and then + // signal a new semaphore which we'll create now. + self.wait = Some(old.signal); + self.signal = device.new_binary_semaphore("RelaySemaphores: 2")?; + } + Some(ref mut wait) => { + // What this submission signals, the next should wait. + mem::swap(wait, &mut self.signal); + } + }; + + Ok(old) + } + + /// Destroys the semaphores. + unsafe fn destroy(&self, device: &ash::Device) { + unsafe { + if let Some(wait) = self.wait { + device.destroy_semaphore(wait, None); + } + device.destroy_semaphore(self.signal, None); + } + } +} + +pub struct Queue { + raw: vk::Queue, + device: Arc<DeviceShared>, + family_index: u32, + relay_semaphores: Mutex<RelaySemaphores>, + signal_semaphores: Mutex<SemaphoreList>, + wait_semaphores: Mutex<SemaphoreList>, +} + +impl fmt::Debug for Queue { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let Self { + raw: _, + device: _, + family_index, + relay_semaphores: _, + signal_semaphores: _, + wait_semaphores: _, + } = self; + f.debug_struct("Queue") + .field("family_index", family_index) + .finish_non_exhaustive() + } +} + +impl Queue { + pub fn as_raw(&self) -> vk::Queue { + self.raw + } +} + +impl Drop for Queue { + fn drop(&mut self) { + unsafe { self.relay_semaphores.lock().destroy(&self.device.raw) }; + } +} +#[derive(Debug)] +enum BufferMemoryBacking { + Managed(gpu_allocator::vulkan::Allocation), + VulkanMemory { + memory: vk::DeviceMemory, + offset: u64, + size: u64, + }, +} +impl BufferMemoryBacking { + fn memory(&self) -> vk::DeviceMemory { + match self { + Self::Managed(m) => unsafe { m.memory() }, + Self::VulkanMemory { memory, .. } => *memory, + } + } + fn offset(&self) -> u64 { + match self { + Self::Managed(m) => m.offset(), + Self::VulkanMemory { offset, .. } => *offset, + } + } + fn size(&self) -> u64 { + match self { + Self::Managed(m) => m.size(), + Self::VulkanMemory { size, .. } => *size, + } + } +} +/// Describes who owns a [`Buffer`]'s `vk::Buffer` handle and its backing memory, +/// and therefore what cleanup is required when the buffer is destroyed. +#[derive(Debug)] +enum BufferOwnership { + /// wgpu-hal owns the `vk::Buffer` and its backing memory. On cleanup the buffer + /// handle is destroyed and the memory is released. + Managed(Mutex<BufferMemoryBacking>), + /// wgpu-hal owns the `vk::Buffer` handle but the backing memory is kept alive + /// by the caller. On cleanup only the buffer handle is destroyed. + RawHandle, + /// Caller owns the `vk::Buffer` and its backing memory. On cleanup the + /// [`crate::DropGuard`] runs the caller's cleanup callback and wgpu-hal touches + /// neither the handle nor the memory. + External(crate::DropGuard), +} + +#[derive(Debug)] +pub struct Buffer { + raw: vk::Buffer, + + // This field must be last, because it may contain a `DropGuard` which needs to be dropped after all other fields. + ownership: BufferOwnership, +} +impl Buffer { + /// # Safety + /// + /// - `vk_buffer`'s memory must be managed by the caller + /// - Externally imported buffers can't be mapped by `wgpu` + pub unsafe fn from_raw(vk_buffer: vk::Buffer) -> Self { + Self { + raw: vk_buffer, + ownership: BufferOwnership::RawHandle, + } + } + + /// # Safety + /// - `vk_buffer` must outlive the returned `Buffer`. + /// - wgpu-hal will NOT call `vkDestroyBuffer`; the caller remains responsible for the buffer handle's destruction. + /// The `drop_callback` runs when the `Buffer` drops and may be used to release caller-side bookkeeping. + /// - Externally imported buffers can't be mapped by `wgpu`. + pub unsafe fn from_raw_externally_owned( + vk_buffer: vk::Buffer, + drop_callback: crate::DropCallback, + ) -> Self { + Self { + raw: vk_buffer, + ownership: BufferOwnership::External(crate::DropGuard::new(drop_callback)), + } + } + + /// # Safety + /// - We will use this buffer and the buffer's backing memory range as if we have exclusive ownership over it, until the wgpu resource is dropped and the wgpu-hal object is cleaned up + /// - Externally imported buffers can't be mapped by `wgpu` + /// - `offset` and `size` must be valid with the allocation of `memory` + pub unsafe fn from_raw_managed( + vk_buffer: vk::Buffer, + memory: vk::DeviceMemory, + offset: u64, + size: u64, + ) -> Self { + Self { + raw: vk_buffer, + ownership: BufferOwnership::Managed(Mutex::new(BufferMemoryBacking::VulkanMemory { + memory, + offset, + size, + })), + } + } + + /// # Safety + /// - The buffer handle must not be manually destroyed + pub unsafe fn raw_handle(&self) -> vk::Buffer { + self.raw + } +} + +impl crate::DynBuffer for Buffer {} + +#[derive(Debug)] +pub struct AccelerationStructure { + raw: vk::AccelerationStructureKHR, + buffer: vk::Buffer, + allocation: gpu_allocator::vulkan::Allocation, + compacted_size_query: Option<vk::QueryPool>, +} + +impl crate::DynAccelerationStructure for AccelerationStructure {} + +#[derive(Debug)] +pub enum TextureMemory { + // shared memory in GPU allocator (owned by wgpu-hal) + Allocation(gpu_allocator::vulkan::Allocation), + + // dedicated memory (owned by wgpu-hal) + Dedicated(vk::DeviceMemory), + + // memory not owned by wgpu + External, +} + +#[derive(Debug)] +pub struct Texture { + raw: vk::Image, + memory: TextureMemory, + format: wgt::TextureFormat, + copy_size: crate::CopyExtent, + identity: ResourceIdentity<vk::Image>, + + // The `drop_guard` field must be the last field of this struct so it is dropped last. + // Do not add new fields after it. + drop_guard: Option<crate::DropGuard>, +} + +impl crate::DynTexture for Texture {} + +impl Texture { + /// # Safety + /// + /// - The image handle must not be manually destroyed + pub unsafe fn raw_handle(&self) -> vk::Image { + self.raw + } + + /// # Safety + /// + /// - The caller must not free the `vk::DeviceMemory` or + /// `gpu_alloc::MemoryBlock` in the returned `TextureMemory`. + pub unsafe fn memory(&self) -> &TextureMemory { + &self.memory + } +} + +#[derive(Debug)] +pub struct TextureView { + raw_texture: vk::Image, + raw: vk::ImageView, + _layers: NonZeroU32, + format: wgt::TextureFormat, + raw_format: vk::Format, + base_mip_level: u32, + dimension: wgt::TextureViewDimension, + texture_identity: ResourceIdentity<vk::Image>, + view_identity: ResourceIdentity<vk::ImageView>, +} + +impl crate::DynTextureView for TextureView {} + +impl TextureView { + /// # Safety + /// + /// - The image view handle must not be manually destroyed + pub unsafe fn raw_handle(&self) -> vk::ImageView { + self.raw + } + + /// Returns the raw texture view, along with its identity. + fn identified_raw_view(&self) -> IdentifiedTextureView { + IdentifiedTextureView { + raw: self.raw, + identity: self.view_identity, + } + } +} + +#[derive(Debug)] +pub struct Sampler { + raw: vk::Sampler, + create_info: vk::SamplerCreateInfo<'static>, +} + +impl crate::DynSampler for Sampler {} + +/// Information about a binding within a specific BindGroupLayout / BindGroup. +/// This will be used to construct a [`naga::back::spv::BindingInfo`], where +/// the descriptor set value will be taken from the index of the group. +#[derive(Copy, Clone, Debug)] +struct BindingInfo { + binding: u32, + binding_array_size: Option<NonZeroU32>, +} + +#[derive(Debug)] +pub struct BindGroupLayout { + raw: vk::DescriptorSetLayout, + desc_count: descriptor::DescriptorCounts, + /// Sorted list of entries. + entries: Box<[wgt::BindGroupLayoutEntry]>, + /// Map of original binding index to remapped binding index and optional + /// array size. + binding_map: Vec<(u32, BindingInfo)>, + contains_binding_arrays: bool, +} + +impl crate::DynBindGroupLayout for BindGroupLayout {} + +#[derive(Debug)] +pub struct PipelineLayout { + raw: vk::PipelineLayout, + binding_map: naga::back::spv::BindingMap, +} + +impl crate::DynPipelineLayout for PipelineLayout {} + +#[derive(Debug)] +pub struct BindGroup { + set: descriptor::DescriptorSet, +} + +impl crate::DynBindGroup for BindGroup {} + +/// Miscellaneous allocation recycling pool for `CommandAllocator`. +#[derive(Default)] +struct Temp { + marker: Vec<u8>, + buffer_barriers: Vec<vk::BufferMemoryBarrier<'static>>, + image_barriers: Vec<vk::ImageMemoryBarrier<'static>>, +} + +impl Temp { + fn clear(&mut self) { + self.marker.clear(); + self.buffer_barriers.clear(); + self.image_barriers.clear(); + } + + fn make_c_str(&mut self, name: &str) -> &CStr { + self.marker.clear(); + self.marker.extend_from_slice(name.as_bytes()); + self.marker.push(0); + unsafe { CStr::from_bytes_with_nul_unchecked(&self.marker) } + } +} + +/// Generates unique IDs for each resource of type `T`. +/// +/// Because vk handles are not permanently unique, this +/// provides a way to generate unique IDs for each resource. +struct ResourceIdentityFactory<T> { + #[cfg(not(target_has_atomic = "64"))] + next_id: Mutex<u64>, + #[cfg(target_has_atomic = "64")] + next_id: core::sync::atomic::AtomicU64, + _phantom: PhantomData<T>, +} + +impl<T> ResourceIdentityFactory<T> { + fn new() -> Self { + Self { + #[cfg(not(target_has_atomic = "64"))] + next_id: Mutex::new(0), + #[cfg(target_has_atomic = "64")] + next_id: core::sync::atomic::AtomicU64::new(0), + _phantom: PhantomData, + } + } + + /// Returns a new unique ID for a resource of type `T`. + fn next(&self) -> ResourceIdentity<T> { + #[cfg(not(target_has_atomic = "64"))] + { + let mut next_id = self.next_id.lock(); + let id = *next_id; + *next_id += 1; + ResourceIdentity { + id, + _phantom: PhantomData, + } + } + + #[cfg(target_has_atomic = "64")] + ResourceIdentity { + id: self + .next_id + .fetch_add(1, core::sync::atomic::Ordering::Relaxed), + _phantom: PhantomData, + } + } +} + +/// A unique identifier for a resource of type `T`. +/// +/// This is used as a hashable key for resources, which +/// is permanently unique through the lifetime of the program. +#[derive(Debug, Copy, Clone, Eq, Hash, PartialEq)] +struct ResourceIdentity<T> { + id: u64, + _phantom: PhantomData<T>, +} + +#[derive(Clone, Eq, Hash, PartialEq)] +struct FramebufferKey { + raw_pass: vk::RenderPass, + /// Because this is used as a key in a hash map, we need to include the identity + /// so that this hashes differently, even if the ImageView handles are the same + /// between different views. + attachment_identities: ArrayVec<ResourceIdentity<vk::ImageView>, { MAX_TOTAL_ATTACHMENTS }>, + /// While this is redundant for calculating the hash, we need access to an array + /// of all the raw ImageViews when we are creating the actual framebuffer, + /// so we store this here. + attachment_views: ArrayVec<vk::ImageView, { MAX_TOTAL_ATTACHMENTS }>, + extent: wgt::Extent3d, +} + +impl FramebufferKey { + fn push_view(&mut self, view: IdentifiedTextureView) { + self.attachment_identities.push(view.identity); + self.attachment_views.push(view.raw); + } +} + +/// A texture view paired with its identity. +#[derive(Copy, Clone)] +struct IdentifiedTextureView { + raw: vk::ImageView, + identity: ResourceIdentity<vk::ImageView>, +} + +#[derive(Clone, Eq, Hash, PartialEq)] +struct TempTextureViewKey { + texture: vk::Image, + /// As this is used in a hashmap, we need to + /// include the identity so that this hashes differently, + /// even if the Image handles are the same between different images. + texture_identity: ResourceIdentity<vk::Image>, + format: vk::Format, + mip_level: u32, + depth_slice: u32, +} + +// Any state in this struct that may be dirty after an abandoned encoding must +// be reset for reused encoders in `begin_encoding`. +pub struct CommandEncoder { + raw: vk::CommandPool, + device: Arc<DeviceShared>, + + /// The current command buffer, if `self` is in the ["recording"] + /// state. + /// + /// ["recording"]: crate::CommandEncoder + /// + /// If non-`null`, the buffer is in the Vulkan "recording" state. + active: vk::CommandBuffer, + + /// What kind of pass we are currently within: compute or render. + bind_point: vk::PipelineBindPoint, + + /// Allocation recycling pool for this encoder. + temp: Temp, + + /// A pool of available command buffers. + /// + /// These are all in the Vulkan "initial" state. + free: Vec<vk::CommandBuffer>, + + /// A pool of discarded command buffers. + /// + /// These could be in any Vulkan state except "pending". + discarded: Vec<vk::CommandBuffer>, + + /// If this is true, the active renderpass enabled a debug span, + /// and needs to be disabled on renderpass close. + rpass_debug_marker_active: bool, + + /// If set, the end of the next render/compute pass will write a timestamp at + /// the given pool & location. + end_of_pass_timer_query: Option<(vk::QueryPool, u32)>, + + framebuffers: FastHashMap<FramebufferKey, vk::Framebuffer>, + temp_texture_views: FastHashMap<TempTextureViewKey, IdentifiedTextureView>, + + counters: Arc<wgt::HalCounters>, + + current_pipeline_is_multiview: bool, +} + +impl Drop for CommandEncoder { + fn drop(&mut self) { + // SAFETY: + // + // VUID-vkDestroyCommandPool-commandPool-00041: wgpu_hal requires that a + // `CommandBuffer` must live until its execution is complete, and that a + // `CommandBuffer` must not outlive the `CommandEncoder` that built it. + // Thus, we know that none of our `CommandBuffers` are in the "pending" + // state. + // + // The other VUIDs are pretty obvious. + unsafe { + // `vkDestroyCommandPool` also frees any command buffers allocated + // from that pool, so there's no need to explicitly call + // `vkFreeCommandBuffers` on `cmd_encoder`'s `free` and `discarded` + // fields. + self.device.raw.destroy_command_pool(self.raw, None); + } + + for (_, fb) in self.framebuffers.drain() { + unsafe { self.device.raw.destroy_framebuffer(fb, None) }; + } + + for (_, view) in self.temp_texture_views.drain() { + unsafe { self.device.raw.destroy_image_view(view.raw, None) }; + } + + self.counters.command_encoders.sub(1); + } +} + +impl CommandEncoder { + /// # Safety + /// + /// - The command buffer handle must not be manually destroyed + pub unsafe fn raw_handle(&self) -> vk::CommandBuffer { + self.active + } +} + +impl fmt::Debug for CommandEncoder { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("CommandEncoder") + .field("raw", &self.raw) + .finish() + } +} + +#[derive(Debug)] +pub struct CommandBuffer { + raw: vk::CommandBuffer, +} + +impl crate::DynCommandBuffer for CommandBuffer {} + +#[derive(Debug)] +pub enum ShaderModule { + Raw(vk::ShaderModule), + Intermediate { + naga_shader: crate::NagaShader, + runtime_checks: wgt::ShaderRuntimeChecks, + }, +} + +impl crate::DynShaderModule for ShaderModule {} + +#[derive(Debug)] +pub struct RenderPipeline { + raw: vk::Pipeline, + is_multiview: bool, +} + +impl crate::DynRenderPipeline for RenderPipeline {} + +#[derive(Debug)] +pub struct ComputePipeline { + raw: vk::Pipeline, +} + +impl crate::DynComputePipeline for ComputePipeline {} + +#[derive(Debug)] +pub struct RayTracingPipeline { + raw: vk::Pipeline, +} + +impl crate::DynRayTracingPipeline for RayTracingPipeline {} + +#[derive(Debug)] +pub struct PipelineCache { + raw: vk::PipelineCache, +} + +impl crate::DynPipelineCache for PipelineCache {} + +#[derive(Debug)] +pub struct QuerySet { + raw: vk::QueryPool, +} + +impl crate::DynQuerySet for QuerySet {} + +/// The [`Api::Fence`] type for [`vulkan::Api`]. +/// +/// This is an `enum` because there are two possible implementations of +/// `wgpu-hal` fences on Vulkan: Vulkan fences, which work on any version of +/// Vulkan, and Vulkan timeline semaphores, which are easier and cheaper but +/// require non-1.0 features. +/// +/// [`Device::create_fence`] returns a [`TimelineSemaphore`] if +/// [`VK_KHR_timeline_semaphore`] is available and enabled, and a [`FencePool`] +/// otherwise. +/// +/// [`Api::Fence`]: crate::Api::Fence +/// [`vulkan::Api`]: Api +/// [`Device::create_fence`]: crate::Device::create_fence +/// [`TimelineSemaphore`]: Fence::TimelineSemaphore +/// [`VK_KHR_timeline_semaphore`]: https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html#VK_KHR_timeline_semaphore +/// [`FencePool`]: Fence::FencePool +#[derive(Debug)] +pub enum Fence { + /// A Vulkan [timeline semaphore]. + /// + /// These are simpler to use than Vulkan fences, since timeline semaphores + /// work exactly the way [`wpgu_hal::Api::Fence`] is specified to work. + /// + /// [timeline semaphore]: https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html#synchronization-semaphores + /// [`wpgu_hal::Api::Fence`]: crate::Api::Fence + TimelineSemaphore(vk::Semaphore), + + /// A collection of Vulkan [fence]s, each associated with a [`FenceValue`]. + /// + /// The effective [`FenceValue`] of this variant is the greater of + /// `last_completed` and the maximum value associated with a signalled fence + /// in `active`. + /// + /// Fences are available in all versions of Vulkan, but since they only have + /// two states, "signaled" and "unsignaled", we need to use a separate fence + /// for each queue submission we might want to wait for, and remember which + /// [`FenceValue`] each one represents. + /// + /// One should keep the fence pool read while there are any references to the + /// fences inside of them. This ensures there are no race conditions when + /// resetting the fences + /// + /// [fence]: https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html#synchronization-fences + /// [`FenceValue`]: crate::FenceValue + FencePool(RwLock<FencePool>), +} + +/// A shared fence type. The arc is expect to have a ref-count of one once a function has finished being called +/// +/// A fence should have access synchronised as fence resetting might happen at any point. Resetting checks the ref-count +/// of the fence, so instead of copying the fence, it should have its `Arc` container cloned which shows not to reset +/// this fence as it is being used. +pub(super) type SynchronizedFence = Arc<vk::Fence>; + +#[derive(Debug)] +pub struct FencePool { + last_completed: crate::FenceValue, + /// The pending fence values have to be ascending. + active: Vec<(crate::FenceValue, SynchronizedFence)>, + // Don't need extra synchronisation around the fences here, if they are used they should be put into active. + free: Vec<vk::Fence>, +} + +impl crate::DynFence for Fence {} + +impl Fence { + /// Return the highest [`FenceValue`] among the signalled fences in `active`. + /// + /// As an optimization, assume that we already know that the fence has + /// reached `last_completed`, and don't bother checking fences whose values + /// are less than that: those fences remain in the `active` array only + /// because we haven't called `maintain` yet to clean them up. + /// + /// [`FenceValue`]: crate::FenceValue + fn check_active( + device: &ash::Device, + mut last_completed: crate::FenceValue, + active: &[(crate::FenceValue, SynchronizedFence)], + ) -> Result<crate::FenceValue, crate::DeviceError> { + for &(value, ref raw) in active.iter() { + unsafe { + if value > last_completed + && device + // Don't need to clone as active should be from a read or + // write lock which means this is already synchronised. + .get_fence_status(**raw) + .map_err(map_host_device_oom_and_lost_err)? + { + last_completed = value; + } + } + } + Ok(last_completed) + } + + /// Return the highest signalled [`FenceValue`] for `self`. + /// + /// [`FenceValue`]: crate::FenceValue + fn get_latest( + &self, + device: &ash::Device, + extension: Option<&ExtensionFn<khr::timeline_semaphore::Device>>, + ) -> Result<crate::FenceValue, crate::DeviceError> { + match *self { + Self::TimelineSemaphore(raw) => unsafe { + Ok(match *extension.unwrap() { + ExtensionFn::Extension(ref ext) => ext + .get_semaphore_counter_value(raw) + .map_err(map_host_device_oom_and_lost_err)?, + ExtensionFn::Promoted => device + .get_semaphore_counter_value(raw) + .map_err(map_host_device_oom_and_lost_err)?, + }) + }, + Self::FencePool(ref pool) => { + let FencePool { + last_completed, + ref active, + free: _, + } = *pool.read(); + Self::check_active(device, last_completed, active) + } + } + } + + /// Trim the internal state of this [`Fence`]. + /// + /// This function has no externally visible effect, but you should call it + /// periodically to keep this fence's resource consumption under control. + /// + /// For fences using the [`FencePool`] implementation, this function + /// recycles fences that have been signaled. If you don't call this, + /// [`Queue::submit`] will just keep allocating a new Vulkan fence every + /// time it's called. + /// + /// [`FencePool`]: Fence::FencePool + /// [`Queue::submit`]: crate::Queue::submit + fn maintain(&self, device: &ash::Device) -> Result<(), crate::DeviceError> { + match *self { + Self::TimelineSemaphore(_) => {} + Self::FencePool(ref pool) => { + let FencePool { + ref mut last_completed, + ref mut active, + ref mut free, + } = *pool.write(); + + let base_free = free.len(); + let latest = Self::check_active(device, *last_completed, active)?; + + active.retain_mut(|&mut (value, ref mut fence)| { + if value > latest { + true + } else if let Some(fence) = Arc::get_mut(fence) { + // No other references to these, so we have exclusive access. Add them to free and reset them later, + // but drop them from active immediately + free.push(*fence); + false + } else { + // some other function is using it. Although this shouldn't be to long, + // maintain shouldn't block, and it should be cleared up by the next time it happens + true + } + }); + + if free.len() != base_free { + unsafe { device.reset_fences(&free[base_free..]) } + .map_err(map_device_oom_err)? + } + *last_completed = latest; + } + } + Ok(()) + } +} + +impl crate::Queue for Queue { + type A = Api; + + unsafe fn submit( + &self, + command_buffers: &[&CommandBuffer], + surface_textures: &[&SurfaceTexture], + (signal_fence, signal_value): (&Fence, crate::FenceValue), + ) -> Result<(), crate::DeviceError> { + let mut fence_raw = vk::Fence::null(); + + let mut wait_semaphores = SemaphoreList::new(SemaphoreListMode::Wait); + let mut signal_semaphores = SemaphoreList::new(SemaphoreListMode::Signal); + + // Double check that the same swapchain image isn't being given to us multiple times, + // as that will deadlock when we try to lock them all. + debug_assert!( + { + let mut check = HashSet::with_capacity(surface_textures.len()); + // We compare the Box by pointer, as Eq isn't well defined for SurfaceSemaphores. + for st in surface_textures { + let ptr: *const () = <*const _>::cast(&*st.metadata); + check.insert(ptr as usize); + } + check.len() == surface_textures.len() + }, + "More than one surface texture is being used from the same swapchain. This will cause a deadlock in release." + ); + + let locked_swapchain_semaphores = surface_textures + .iter() + .map(|st| st.metadata.get_semaphore_guard()) + .collect::<Vec<_>>(); + + for mut semaphores in locked_swapchain_semaphores { + semaphores.set_used_fence_value(signal_value); + + // If we're the first submission to operate on this image, wait on + // its acquire semaphore, to make sure the presentation engine is + // done with it. + if let Some(sem) = semaphores.get_acquire_wait_semaphore() { + wait_semaphores.push_wait(sem, vk::PipelineStageFlags::TOP_OF_PIPE); + } + + // Get a semaphore to signal when we're done writing to this surface + // image. Presentation of this image will wait for this. + let signal_semaphore = semaphores.get_submit_signal_semaphore(&self.device)?; + signal_semaphores.push_signal(signal_semaphore); + } + + let mut guard = self.signal_semaphores.lock(); + if !guard.is_empty() { + signal_semaphores.append(&mut guard); + } + + let mut wait_guard = self.wait_semaphores.lock(); + if !wait_guard.is_empty() { + wait_semaphores.append(&mut wait_guard); + } + + // In order for submissions to be strictly ordered, we encode a dependency between each submission + // using a pair of semaphores. This adds a wait if it is needed, and signals the next semaphore. + let semaphore_state = self.relay_semaphores.lock().advance(&self.device)?; + + if let Some(sem) = semaphore_state.wait { + wait_semaphores.push_wait( + SemaphoreType::Binary(sem), + vk::PipelineStageFlags::TOP_OF_PIPE, + ); + } + + signal_semaphores.push_signal(SemaphoreType::Binary(semaphore_state.signal)); + + // We need to signal our wgpu::Fence if we have one, this adds it to the signal list. + signal_fence.maintain(&self.device.raw)?; + // Keeping the Arc around is probably unneeded - the fence should never be signaled as it was reset, + // and newer submits should not happen until this submit is done. Therefore, it should be too high + // to be reset. + let shared_fence; + match *signal_fence { + Fence::TimelineSemaphore(raw) => { + signal_semaphores.push_signal(SemaphoreType::Timeline(raw, signal_value)); + } + Fence::FencePool(ref pool) => { + let FencePool { + ref mut active, + ref mut free, + .. + } = *pool.write(); + shared_fence = match free.pop() { + Some(raw) => Arc::new(raw), + None => unsafe { + let fence = self + .device + .raw + .create_fence(&vk::FenceCreateInfo::default(), None) + .map_err(map_host_device_oom_err)?; + Arc::new(fence) + }, + }; + fence_raw = *shared_fence; + active.push((signal_value, shared_fence.clone())); + } + } + + let vk_cmd_buffers = command_buffers + .iter() + .map(|cmd| cmd.raw) + .collect::<Vec<_>>(); + + let mut vk_info = vk::SubmitInfo::default().command_buffers(&vk_cmd_buffers); + let mut vk_timeline_info = mem::MaybeUninit::uninit(); + vk_info = SemaphoreList::add_to_submit( + &mut wait_semaphores, + &mut signal_semaphores, + vk_info, + &mut vk_timeline_info, + ); + + profiling::scope!("vkQueueSubmit"); + unsafe { + self.device + .raw + .queue_submit(self.raw, &[vk_info], fence_raw) + .map_err(map_host_device_oom_and_lost_err)? + }; + Ok(()) + } + + unsafe fn present( + &self, + surface: &Surface, + texture: SurfaceTexture, + ) -> Result<(), crate::SurfaceError> { + let mut swapchain = surface.swapchain.write(); + + unsafe { swapchain.as_mut().unwrap().present(self, texture) } + } + + unsafe fn get_timestamp_period(&self) -> f32 { + self.device.timestamp_period + } + + unsafe fn wait_for_idle(&self) -> Result<(), crate::DeviceError> { + unsafe { self.device.raw.queue_wait_idle(self.raw) } + .map_err(map_host_device_oom_and_lost_err) + } +} + +impl Queue { + pub fn raw_device(&self) -> &ash::Device { + &self.device.raw + } + + pub fn add_signal_semaphore(&self, semaphore: vk::Semaphore, semaphore_value: Option<u64>) { + let mut guard = self.signal_semaphores.lock(); + if let Some(value) = semaphore_value { + guard.push_signal(SemaphoreType::Timeline(semaphore, value)); + } else { + guard.push_signal(SemaphoreType::Binary(semaphore)); + } + } + + /// Remove `semaphore` from the pending signal list if it is still present. + /// + /// Returns `true` if the semaphore was found and removed. If the submit + /// already consumed it, this is a harmless no-op that returns `false`. + pub fn remove_signal_semaphore(&self, semaphore: vk::Semaphore) -> bool { + self.signal_semaphores.lock().remove(semaphore) + } + + /// Stage a semaphore wait on the next [`crate::Queue::submit`] call. + /// + /// `semaphore_value` selects the kind of payload the wait targets: + /// + /// - `Some(value)` - wait until `semaphore` (a timeline semaphore) has been signalled to at least `value`. + /// - `None` - wait on a binary semaphore signal. + /// + /// `stage` is the pipeline stage at which the wait blocks downstream + /// work (e.g. `vk::PipelineStageFlags::TOP_OF_PIPE` to gate the + /// entire submission, or a more specific stage when only that stage + /// reads the synchronised resource). + pub fn add_wait_semaphore( + &self, + semaphore: vk::Semaphore, + semaphore_value: Option<u64>, + stage: vk::PipelineStageFlags, + ) { + let mut guard = self.wait_semaphores.lock(); + if let Some(value) = semaphore_value { + guard.push_wait(SemaphoreType::Timeline(semaphore, value), stage); + } else { + guard.push_wait(SemaphoreType::Binary(semaphore), stage); + } + } + + /// Remove `semaphore` from the pending wait list if it is still present. + /// + /// Returns `true` if the semaphore was found and removed. If the submit + /// already consumed it, this is a no-op that returns `false`. + pub fn remove_wait_semaphore(&self, semaphore: vk::Semaphore) -> bool { + self.wait_semaphores.lock().remove(semaphore) + } +} + +/// Maps +/// +/// - VK_ERROR_OUT_OF_HOST_MEMORY +/// - VK_ERROR_OUT_OF_DEVICE_MEMORY +fn map_host_device_oom_err(err: vk::Result) -> crate::DeviceError { + match err { + vk::Result::ERROR_OUT_OF_HOST_MEMORY | vk::Result::ERROR_OUT_OF_DEVICE_MEMORY => { + get_oom_err(err) + } + e => get_unexpected_err(e), + } +} + +/// Maps +/// +/// - VK_ERROR_OUT_OF_HOST_MEMORY +/// - VK_ERROR_OUT_OF_DEVICE_MEMORY +/// - VK_ERROR_DEVICE_LOST +fn map_host_device_oom_and_lost_err(err: vk::Result) -> crate::DeviceError { + match err { + vk::Result::ERROR_DEVICE_LOST => get_lost_err(), + other => map_host_device_oom_err(other), + } +} + +/// Maps +/// +/// - VK_ERROR_OUT_OF_HOST_MEMORY +/// - VK_ERROR_OUT_OF_DEVICE_MEMORY +/// - VK_ERROR_FRAGMENTATION +fn map_host_device_oom_and_fragmentation_err(err: vk::Result) -> crate::DeviceError { + match err { + vk::Result::ERROR_FRAGMENTATION => get_oom_err(err), + other => map_host_device_oom_err(other), + } +} + +/// Maps +/// +/// - VK_ERROR_OUT_OF_HOST_MEMORY +/// - VK_ERROR_OUT_OF_DEVICE_MEMORY +/// - VK_ERROR_INVALID_OPAQUE_CAPTURE_ADDRESS_KHR +fn map_host_device_oom_and_ioca_err(err: vk::Result) -> crate::DeviceError { + // We don't use VK_KHR_buffer_device_address + // VK_ERROR_INVALID_OPAQUE_CAPTURE_ADDRESS_KHR + map_host_device_oom_err(err) +} + +/// Maps +/// +/// - VK_ERROR_OUT_OF_HOST_MEMORY +fn map_host_oom_err(err: vk::Result) -> crate::DeviceError { + match err { + vk::Result::ERROR_OUT_OF_HOST_MEMORY => get_oom_err(err), + e => get_unexpected_err(e), + } +} + +/// Maps +/// +/// - VK_ERROR_OUT_OF_DEVICE_MEMORY +fn map_device_oom_err(err: vk::Result) -> crate::DeviceError { + match err { + vk::Result::ERROR_OUT_OF_DEVICE_MEMORY => get_oom_err(err), + e => get_unexpected_err(e), + } +} + +/// Maps +/// +/// - VK_ERROR_OUT_OF_HOST_MEMORY +/// - VK_ERROR_INVALID_OPAQUE_CAPTURE_ADDRESS_KHR +fn map_host_oom_and_ioca_err(err: vk::Result) -> crate::DeviceError { + // We don't use VK_KHR_buffer_device_address + // VK_ERROR_INVALID_OPAQUE_CAPTURE_ADDRESS_KHR + map_host_oom_err(err) +} + +/// Maps +/// +/// - VK_ERROR_OUT_OF_HOST_MEMORY +/// - VK_ERROR_OUT_OF_DEVICE_MEMORY +/// - VK_PIPELINE_COMPILE_REQUIRED_EXT +/// - VK_ERROR_INVALID_SHADER_NV +fn map_pipeline_err(err: vk::Result) -> crate::DeviceError { + // We don't use VK_EXT_pipeline_creation_cache_control + // VK_PIPELINE_COMPILE_REQUIRED_EXT + // We don't use VK_NV_glsl_shader + // VK_ERROR_INVALID_SHADER_NV + map_host_device_oom_err(err) +} + +/// Returns [`crate::DeviceError::Unexpected`] or panics if the `internal_error_panic` +/// feature flag is enabled. +fn get_unexpected_err(_err: vk::Result) -> crate::DeviceError { + #[cfg(feature = "internal_error_panic")] + panic!("Unexpected Vulkan error: {_err:?}"); + + #[allow(unreachable_code)] + crate::DeviceError::Unexpected +} + +/// Returns [`crate::DeviceError::OutOfMemory`]. +fn get_oom_err(_err: vk::Result) -> crate::DeviceError { + crate::DeviceError::OutOfMemory +} + +/// Returns [`crate::DeviceError::Lost`] or panics if the `device_lost_panic` +/// feature flag is enabled. +fn get_lost_err() -> crate::DeviceError { + #[cfg(feature = "device_lost_panic")] + panic!("Device lost"); + + #[allow(unreachable_code)] + crate::DeviceError::Lost +} + +#[derive(Clone, Copy, Pod, Zeroable)] +#[repr(C)] +struct RawTlasInstance { + transform: [f32; 12], + custom_data_and_mask: u32, + shader_binding_table_record_offset_and_flags: u32, + acceleration_structure_reference: u64, +} + +/// Arguments to the [`CreateDeviceCallback`]. +#[derive(Debug)] +pub struct CreateDeviceCallbackArgs<'arg, 'pnext, 'this> +where + 'this: 'pnext, +{ + /// The extensions to enable for the device. You must not remove anything from this list, + /// but you may add to it. + pub extensions: &'arg mut Vec<&'static CStr>, + /// The physical device features to enable. You may enable features, but must not disable any. + pub device_features: &'arg mut PhysicalDeviceFeatures, + /// The queue create infos for the device. You may add or modify queue create infos as needed. + pub queue_create_infos: &'arg mut Vec<vk::DeviceQueueCreateInfo<'pnext>>, + /// The create info for the device. You may add or modify things in the pnext chain, but + /// do not turn features off. Additionally, do not add things to the list of extensions, + /// or to the feature set, as all changes to that member will be overwritten. + pub create_info: &'arg mut vk::DeviceCreateInfo<'pnext>, + /// We need to have `'this` in the struct, so we can declare that all lifetimes coming from + /// captures in the closure will live longer (and hence satisfy) `'pnext`. However, we + /// don't actually directly use `'this` + _phantom: PhantomData<&'this ()>, +} + +/// Callback to allow changing the vulkan device creation parameters. +/// +/// # Safety: +/// - If you want to add extensions, add the to the `Vec<'static CStr>` not the create info, +/// as the create info value will be overwritten. +/// - Callback must not remove features. +/// - Callback must not change anything to what the instance does not support. +pub type CreateDeviceCallback<'this> = + dyn for<'arg, 'pnext> FnOnce(CreateDeviceCallbackArgs<'arg, 'pnext, 'this>) + 'this; + +/// Arguments to the [`CreateInstanceCallback`]. +#[expect(missing_debug_implementations, reason = "TODO?")] +pub struct CreateInstanceCallbackArgs<'arg, 'pnext, 'this> +where + 'this: 'pnext, +{ + /// The extensions to enable for the instance. You must not remove anything from this list, + /// but you may add to it. + pub extensions: &'arg mut Vec<&'static CStr>, + /// The create info for the instance. You may add or modify things in the pnext chain, but + /// do not turn features off. Additionally, do not add things to the list of extensions, + /// all changes to that member will be overwritten. + pub create_info: &'arg mut vk::InstanceCreateInfo<'pnext>, + /// Vulkan entry point. + pub entry: &'arg ash::Entry, + /// We need to have `'this` in the struct, so we can declare that all lifetimes coming from + /// captures in the closure will live longer (and hence satisfy) `'pnext`. However, we + /// don't actually directly use `'this` + _phantom: PhantomData<&'this ()>, +} + +/// Callback to allow changing the vulkan instance creation parameters. +/// +/// # Safety: +/// - If you want to add extensions, add the to the `Vec<'static CStr>` not the create info, +/// as the create info value will be overwritten. +/// - Callback must not remove features. +/// - Callback must not change anything to what the instance does not support. +pub type CreateInstanceCallback<'this> = + dyn for<'arg, 'pnext> FnOnce(CreateInstanceCallbackArgs<'arg, 'pnext, 'this>) + 'this; diff --git a/app/vendor/rune/vendor/wgpu-hal/src/vulkan/sampler.rs b/app/vendor/rune/vendor/wgpu-hal/src/vulkan/sampler.rs new file mode 100644 index 0000000..b99341d --- /dev/null +++ b/app/vendor/rune/vendor/wgpu-hal/src/vulkan/sampler.rs @@ -0,0 +1,177 @@ +//! Sampler cache for Vulkan backend. +//! +//! Nearly identical to the DX12 sampler cache, without descriptor heap management. + +use ash::vk; +use hashbrown::{hash_map::Entry, HashMap}; +use ordered_float::OrderedFloat; + +/// If the allowed sampler count is above this value, the sampler cache is disabled. +const ENABLE_SAMPLER_CACHE_CUTOFF: u32 = 1 << 20; + +/// [`vk::SamplerCreateInfo`] is not hashable, so we wrap it in a newtype that is. +/// +/// We use [`OrderedFloat`] to allow for floating point values to be compared and +/// hashed in a defined way. +#[derive(Copy, Clone)] +struct HashableSamplerCreateInfo(vk::SamplerCreateInfo<'static>); + +impl PartialEq for HashableSamplerCreateInfo { + fn eq(&self, other: &Self) -> bool { + self.0.flags == other.0.flags + && self.0.mag_filter == other.0.mag_filter + && self.0.min_filter == other.0.min_filter + && self.0.mipmap_mode == other.0.mipmap_mode + && self.0.address_mode_u == other.0.address_mode_u + && self.0.address_mode_v == other.0.address_mode_v + && self.0.address_mode_w == other.0.address_mode_w + && OrderedFloat(self.0.mip_lod_bias) == OrderedFloat(other.0.mip_lod_bias) + && self.0.anisotropy_enable == other.0.anisotropy_enable + && OrderedFloat(self.0.max_anisotropy) == OrderedFloat(other.0.max_anisotropy) + && self.0.compare_enable == other.0.compare_enable + && self.0.compare_op == other.0.compare_op + && OrderedFloat(self.0.min_lod) == OrderedFloat(other.0.min_lod) + && OrderedFloat(self.0.max_lod) == OrderedFloat(other.0.max_lod) + && self.0.border_color == other.0.border_color + && self.0.unnormalized_coordinates == other.0.unnormalized_coordinates + } +} + +impl Eq for HashableSamplerCreateInfo {} + +impl core::hash::Hash for HashableSamplerCreateInfo { + fn hash<H: core::hash::Hasher>(&self, state: &mut H) { + self.0.flags.hash(state); + self.0.mag_filter.hash(state); + self.0.min_filter.hash(state); + self.0.mipmap_mode.hash(state); + self.0.address_mode_u.hash(state); + self.0.address_mode_v.hash(state); + self.0.address_mode_w.hash(state); + OrderedFloat(self.0.mip_lod_bias).hash(state); + self.0.anisotropy_enable.hash(state); + OrderedFloat(self.0.max_anisotropy).hash(state); + self.0.compare_enable.hash(state); + self.0.compare_op.hash(state); + OrderedFloat(self.0.min_lod).hash(state); + OrderedFloat(self.0.max_lod).hash(state); + self.0.border_color.hash(state); + self.0.unnormalized_coordinates.hash(state); + } +} + +/// Entry in the sampler cache. +struct CacheEntry { + sampler: vk::Sampler, + ref_count: u32, +} + +/// Global sampler cache. +/// +/// As some devices have a low limit (4000) on the number of unique samplers that can be created, +/// we need to cache samplers to avoid running out if people eagerly create duplicate samplers. +pub(crate) struct SamplerCache { + /// Mapping from the sampler description to sampler and reference count. + samplers: HashMap<HashableSamplerCreateInfo, CacheEntry>, + /// Maximum number of unique samplers that can be created. + total_capacity: u32, + /// If true, the sampler cache is disabled and all samplers are created on demand. + passthrough: bool, +} + +impl SamplerCache { + pub fn new(total_capacity: u32) -> Self { + let passthrough = total_capacity >= ENABLE_SAMPLER_CACHE_CUTOFF; + Self { + samplers: HashMap::new(), + total_capacity, + passthrough, + } + } + + /// Create a sampler, or return an existing one if it already exists. + /// + /// If the sampler already exists, the reference count is incremented. + /// + /// If the sampler does not exist, a new sampler is created and inserted into the cache. + /// + /// If the cache is full, an error is returned. + pub fn create_sampler( + &mut self, + device: &ash::Device, + create_info: vk::SamplerCreateInfo<'static>, + ) -> Result<vk::Sampler, crate::DeviceError> { + if self.passthrough { + return unsafe { device.create_sampler(&create_info, None) } + .map_err(super::map_host_device_oom_and_ioca_err); + }; + + // Get the number of used samplers. Needs to be done before to appease the borrow checker. + let used_samplers = self.samplers.len(); + + match self.samplers.entry(HashableSamplerCreateInfo(create_info)) { + Entry::Occupied(occupied_entry) => { + // We have found a match, so increment the refcount and return the index. + let value = occupied_entry.into_mut(); + value.ref_count += 1; + Ok(value.sampler) + } + Entry::Vacant(vacant_entry) => { + // We need to create a new sampler. + + // We need to check if we can create more samplers. + if used_samplers >= self.total_capacity as usize { + log::error!("There is no more room in the global sampler heap for more unique samplers. Your device supports a maximum of {} unique samplers.", self.samplers.len()); + return Err(crate::DeviceError::OutOfMemory); + } + + // Create the sampler. + let sampler = unsafe { device.create_sampler(&create_info, None) } + .map_err(super::map_host_device_oom_and_ioca_err)?; + + // Insert the new sampler into the mapping. + vacant_entry.insert(CacheEntry { + sampler, + ref_count: 1, + }); + + Ok(sampler) + } + } + } + + /// Decrease the reference count of a sampler and destroy it if the reference count reaches 0. + /// + /// The provided sampler is checked against the sampler in the cache to ensure there is no clerical error. + pub fn destroy_sampler( + &mut self, + device: &ash::Device, + create_info: vk::SamplerCreateInfo<'static>, + provided_sampler: vk::Sampler, + ) { + if self.passthrough { + unsafe { device.destroy_sampler(provided_sampler, None) }; + return; + }; + + let Entry::Occupied(mut hash_map_entry) = + self.samplers.entry(HashableSamplerCreateInfo(create_info)) + else { + log::error!("Trying to destroy a sampler that does not exist."); + return; + }; + let cache_entry = hash_map_entry.get_mut(); + + assert_eq!( + cache_entry.sampler, provided_sampler, + "Provided sampler does not match the sampler in the cache." + ); + + cache_entry.ref_count -= 1; + + if cache_entry.ref_count == 0 { + unsafe { device.destroy_sampler(cache_entry.sampler, None) }; + hash_map_entry.remove(); + } + } +} diff --git a/app/vendor/rune/vendor/wgpu-hal/src/vulkan/semaphore_list.rs b/app/vendor/rune/vendor/wgpu-hal/src/vulkan/semaphore_list.rs new file mode 100644 index 0000000..045bfe8 --- /dev/null +++ b/app/vendor/rune/vendor/wgpu-hal/src/vulkan/semaphore_list.rs @@ -0,0 +1,218 @@ +//! Definition of the [`SemaphoreList`] type. + +use alloc::vec::Vec; +use ash::vk; +use core::mem::MaybeUninit; + +#[derive(Debug, PartialEq)] +pub enum SemaphoreListMode { + Wait, + Signal, +} + +/// A list of Vulkan semaphores to wait for or signal. +/// +/// This represents a list of binary or timeline semaphores, together +/// with values for the timeline semaphores, and stage masks, if these +/// are used for waiting. +/// +/// This type ensures that the array of semaphores to be signaled +/// stays aligned with the array of values for timeline semaphores +/// appearing in that list. The [`add_to_submit`] method prepares the +/// `vkQueueSubmit` arguments appropriately for whatever semaphores we +/// actually have. +/// +/// [`add_to_submit`]: SemaphoreList::add_to_submit +#[derive(Debug)] +pub struct SemaphoreList { + /// Mode of the semaphore list. Used for validation. + mode: SemaphoreListMode, + + /// Semaphores to use. + /// + /// This can be a mix of binary and timeline semaphores. + semaphores: Vec<vk::Semaphore>, + + /// Values for the timeline semaphores. + /// + /// If no timeline semaphores are present in [`semaphores`], this + /// is empty. If any timeline semaphores are present, then this + /// has the same length as [`semaphores`], with dummy !0 values + /// in the elements corresponding to binary semaphores, since + /// Vulkan ignores these. + /// + /// [`semaphores`]: Self::semaphores + values: Vec<u64>, + + /// Stage masks for wait semaphores. + /// + /// This is only used if `mode` is `Wait`. + pub stage_masks: Vec<vk::PipelineStageFlags>, +} + +impl SemaphoreList { + pub fn new(mode: SemaphoreListMode) -> Self { + Self { + mode, + semaphores: Vec::new(), + values: Vec::new(), + stage_masks: Vec::new(), + } + } + + pub fn is_empty(&self) -> bool { + self.semaphores.is_empty() + } + + /// Add this list to the semaphores to be signalled by a `vkQueueSubmit` call. + /// + /// - Set `submit_info`'s `pSignalSemaphores` list to this list's + /// semaphores. + /// + /// - If this list contains any timeline semaphores, then initialize + /// `timeline_info`, set its `pSignalSemaphoreValues` to this + /// list's values, and add it to `submit_info`s extension chain. + /// + /// Return the revised `submit_info` value. + pub fn add_to_submit<'info, 'semaphores: 'info>( + wait_semaphores: &'semaphores mut Self, + signal_semaphores: &'semaphores mut Self, + submit_info: vk::SubmitInfo<'info>, + timeline_info: &'info mut MaybeUninit<vk::TimelineSemaphoreSubmitInfo<'info>>, + ) -> vk::SubmitInfo<'info> { + wait_semaphores.check(); + signal_semaphores.check(); + + assert!(matches!(wait_semaphores.mode, SemaphoreListMode::Wait)); + assert!(matches!(signal_semaphores.mode, SemaphoreListMode::Signal)); + + let timeline_info = timeline_info.write(vk::TimelineSemaphoreSubmitInfo::default()); + + let mut uses_timeline = false; + + if !wait_semaphores.values.is_empty() { + *timeline_info = timeline_info.wait_semaphore_values(&wait_semaphores.values); + uses_timeline = true; + } + + if !signal_semaphores.values.is_empty() { + *timeline_info = timeline_info.signal_semaphore_values(&signal_semaphores.values); + uses_timeline = true; + } + + let mut submit_info = submit_info + .wait_semaphores(&wait_semaphores.semaphores) + .wait_dst_stage_mask(&wait_semaphores.stage_masks) + .signal_semaphores(&signal_semaphores.semaphores); + + if uses_timeline { + submit_info = submit_info.push_next(timeline_info); + } + + submit_info + } + + /// Add a semaphore to be signaled. Panics if this is a list of semaphores to wait. + pub fn push_signal(&mut self, semaphore: SemaphoreType) { + assert!(matches!(self.mode, SemaphoreListMode::Signal)); + self.push_inner(semaphore); + } + + /// Add a semaphore to be waited for. Panics if this is a list of semaphores to signal. + pub fn push_wait(&mut self, semaphore: SemaphoreType, stage: vk::PipelineStageFlags) { + assert!(matches!(self.mode, SemaphoreListMode::Wait)); + + self.stage_masks.push(stage); + self.push_inner(semaphore); + } + + fn push_inner(&mut self, semaphore: SemaphoreType) { + match semaphore { + SemaphoreType::Binary(semaphore) => { + self.semaphores.push(semaphore); + // Push a dummy value if necessary. + if !self.values.is_empty() { + self.values.push(!0); + } + } + SemaphoreType::Timeline(semaphore, value) => { + // We may be the first timeline semaphore, ensure that the values + // array is filled with dummy values for existing binary semaphores. + self.pad_values(); + self.semaphores.push(semaphore); + self.values.push(value); + } + } + + self.check(); + } + + /// Remove all entries matching `semaphore` from the list. Returns `true` + /// if anything was removed. + pub fn remove(&mut self, semaphore: vk::Semaphore) -> bool { + let mut removed = false; + let mut i = 0; + while i < self.semaphores.len() { + if self.semaphores[i] == semaphore { + self.semaphores.swap_remove(i); + if !self.values.is_empty() { + self.values.swap_remove(i); + } + if !self.stage_masks.is_empty() { + self.stage_masks.swap_remove(i); + } + removed = true; + } else { + i += 1; + } + } + self.check(); + removed + } + + /// Append `other` to `self`, leaving `other` empty. + pub fn append(&mut self, other: &mut Self) { + assert_eq!(self.mode, other.mode); + + // If we're about to receive values, ensure we're aligned first. + if !other.values.is_empty() { + self.pad_values(); + } + self.semaphores.append(&mut other.semaphores); + self.values.append(&mut other.values); + // If we had values, but `other` did not, re-align. + if !self.values.is_empty() { + self.pad_values(); + } + self.stage_masks.append(&mut other.stage_masks); + self.check(); + } + + /// Pad `self.values` with dummy values for binary semaphores, + /// in preparation for adding a timeline semaphore value. + /// + /// This is a no-op if we already have values. + fn pad_values(&mut self) { + self.values.resize(self.semaphores.len(), !0); + } + + #[track_caller] + fn check(&self) { + debug_assert!(self.values.is_empty() || self.values.len() == self.semaphores.len()); + match self.mode { + SemaphoreListMode::Wait => { + debug_assert!( + self.stage_masks.is_empty() || self.stage_masks.len() == self.semaphores.len() + ); + } + SemaphoreListMode::Signal => { + debug_assert!(self.stage_masks.is_empty()); + } + } + } +} + +pub enum SemaphoreType { + Binary(vk::Semaphore), + Timeline(vk::Semaphore, u64), +} diff --git a/app/vendor/rune/vendor/wgpu-hal/src/vulkan/swapchain/mod.rs b/app/vendor/rune/vendor/wgpu-hal/src/vulkan/swapchain/mod.rs new file mode 100644 index 0000000..9be6002 --- /dev/null +++ b/app/vendor/rune/vendor/wgpu-hal/src/vulkan/swapchain/mod.rs @@ -0,0 +1,119 @@ +use alloc::boxed::Box; +use core::{any::Any, fmt::Debug, time::Duration}; + +use crate::vulkan::{semaphore_list::SemaphoreType, DeviceShared}; + +pub(super) use native::*; + +mod native; + +/// Win32 `HWND`, handed to a Win32 [`NativeSurface`] at construction so it can +/// build its [`DxgiHdrSource`](crate::auxil::dxgi::hdr::DxgiHdrSource) for the +/// display-HDR query. Borrowed from the app's window. +/// +/// A newtype rather than a bare `isize` so the cfg lives in one place: off Windows +/// it is an uninhabited enum, so the non-Windows surface paths can't construct one +/// and the constructor signatures stay cfg-free. +#[cfg(windows)] +#[derive(Clone, Copy)] +pub(crate) struct WindowHandle(pub(crate) windows::Win32::Foundation::HWND); + +#[cfg(not(windows))] +#[derive(Clone, Copy)] +pub(crate) enum WindowHandle {} + +pub(super) trait Surface: Send + Sync + 'static { + /// Returns the surface capabilities for the given adapter. + /// + /// Returns `None` if the surface is not compatible with the adapter. + fn surface_capabilities(&self, adapter: &super::Adapter) -> Option<crate::SurfaceCapabilities>; + + /// Creates a swapchain for the surface with the given configuration. + /// + /// If this is not the first swapchain created for the surface, the old swapchain + /// must be provided. [`Swapchain::release_resources`] must be called on the old swapchain + /// before calling this method. + unsafe fn create_swapchain( + &self, + device: &super::Device, + config: &crate::SurfaceConfiguration, + provided_old_swapchain: Option<Box<dyn Swapchain>>, + ) -> Result<Box<dyn Swapchain>, crate::SurfaceError>; + + /// This surface's current display HDR info, if it can report it. + /// + /// `Some` only for Win32 surfaces (read through DXGI); `None` otherwise + /// (Wayland / X11 / Android / Metal), which is the default. + fn display_hdr_info(&self) -> Option<wgt::DisplayHdrInfo> { + None + } + + /// Allows downcasting to the concrete type. + fn as_any(&self) -> &dyn Any; +} + +pub(super) trait Swapchain: Send + Sync + 'static { + /// Releases all resources associated with the swapchain, without + /// destroying the swapchain itself. Must be called before calling + /// either [`Surface::create_swapchain`] or dropping the swapchain. + /// + /// The swapchain must not be in use when this is called. + unsafe fn release_resources(&mut self, device: &super::Device); + + /// Acquires the next available surface texture for rendering. + /// + /// `timeout` specifies the maximum time to wait for an image to become available. + /// If `None` is specified, this function will wait indefinitely. + /// + /// Returns `Err(SurfaceError::Timeout)` if the timeout elapsed before an image became available. + unsafe fn acquire( + &mut self, + timeout: Option<Duration>, + fence: &super::Fence, + ) -> Result<crate::AcquiredSurfaceTexture<crate::api::Vulkan>, crate::SurfaceError>; + + /// Tries to discard the acquired texture without presenting it. + /// + /// In practice, this doesn't really work in the current implementations. + unsafe fn discard_texture( + &mut self, + texture: super::SurfaceTexture, + ) -> Result<(), crate::SurfaceError>; + + /// Presents the given surface texture using the queue. + unsafe fn present( + &mut self, + queue: &super::Queue, + texture: crate::vulkan::SurfaceTexture, + ) -> Result<(), crate::SurfaceError>; + + /// Allows downcasting to the concrete type. + fn as_any(&self) -> &dyn Any; + + /// Allows downcasting to the concrete type mutably. + fn as_any_mut(&mut self) -> &mut dyn Any; +} + +/// Swapchain specific metadata associated with a surface texture. +pub(super) trait SurfaceTextureMetadata: Debug + Send + Sync + 'static { + /// Returns a guard which can yield the semaphores needed for submission using this swapchain texture. + fn get_semaphore_guard(&self) -> Box<dyn SwapchainSubmissionSemaphoreGuard + '_>; + + /// Allows downcasting to the concrete type. + fn as_any(&self) -> &dyn Any; +} + +/// Guard type for managing swapchain submission semaphores. +pub(super) trait SwapchainSubmissionSemaphoreGuard { + /// Sets the Fence value for this submission. + fn set_used_fence_value(&mut self, value: u64); + + /// Gets semaphores to wait on before doing GPU work for this swapchain texture. + fn get_acquire_wait_semaphore(&mut self) -> Option<SemaphoreType>; + + /// Gets the semaphore to signal when GPU work for this swapchain texture is complete. + fn get_submit_signal_semaphore( + &mut self, + device: &DeviceShared, + ) -> Result<SemaphoreType, crate::DeviceError>; +} diff --git a/app/vendor/rune/vendor/wgpu-hal/src/vulkan/swapchain/native.rs b/app/vendor/rune/vendor/wgpu-hal/src/vulkan/swapchain/native.rs new file mode 100644 index 0000000..218b9ef --- /dev/null +++ b/app/vendor/rune/vendor/wgpu-hal/src/vulkan/swapchain/native.rs @@ -0,0 +1,937 @@ +//! Vulkan Surface and Swapchain implementation using native Vulkan surfaces. + +use alloc::{boxed::Box, sync::Arc, vec::Vec}; +use core::any::Any; + +use ash::{khr, vk}; +use parking_lot::{Mutex, MutexGuard}; + +use crate::vulkan::{ + conv, map_host_device_oom_and_lost_err, + semaphore_list::SemaphoreType, + swapchain::{ + Surface, SurfaceTextureMetadata, Swapchain, SwapchainSubmissionSemaphoreGuard, WindowHandle, + }, + DeviceShared, InstanceShared, +}; + +pub(crate) struct NativeSurface { + raw: vk::SurfaceKHR, + functor: khr::surface::Instance, + instance: Arc<InstanceShared>, + /// Built from the window's `HWND` (Windows only) to answer the display-HDR + /// query; `None` for non-Win32 surfaces. + #[cfg(windows)] + hdr_source: Option<crate::auxil::dxgi::hdr::DxgiHdrSource>, +} + +impl NativeSurface { + pub fn from_vk_surface_khr( + instance: &crate::vulkan::Instance, + raw: vk::SurfaceKHR, + hwnd: Option<WindowHandle>, + ) -> Self { + #[cfg(not(windows))] + let _ = hwnd; + let functor = khr::surface::Instance::new(&instance.shared.entry, &instance.shared.raw); + Self { + raw, + functor, + instance: Arc::clone(&instance.shared), + #[cfg(windows)] + hdr_source: hwnd.map(|wh| crate::auxil::dxgi::hdr::DxgiHdrSource::new(wh.0)), + } + } + + pub fn as_raw(&self) -> vk::SurfaceKHR { + self.raw + } +} + +impl Drop for NativeSurface { + fn drop(&mut self) { + unsafe { + self.functor.destroy_surface(self.raw, None); + } + } +} + +impl Surface for NativeSurface { + fn surface_capabilities( + &self, + adapter: &crate::vulkan::Adapter, + ) -> Option<crate::SurfaceCapabilities> { + if !adapter.private_caps.can_present { + return None; + } + let queue_family_index = 0; //TODO + { + profiling::scope!("vkGetPhysicalDeviceSurfaceSupportKHR"); + match unsafe { + self.functor.get_physical_device_surface_support( + adapter.raw, + queue_family_index, + self.raw, + ) + } { + Ok(true) => (), + Ok(false) => return None, + Err(e) => { + log::error!("get_physical_device_surface_support: {e}"); + return None; + } + } + } + + let caps = { + profiling::scope!("vkGetPhysicalDeviceSurfaceCapabilitiesKHR"); + match unsafe { + self.functor + .get_physical_device_surface_capabilities(adapter.raw, self.raw) + } { + Ok(caps) => caps, + Err(e) => { + log::error!("get_physical_device_surface_capabilities: {e}"); + return None; + } + } + }; + + // If image count is 0, the support number of images is unlimited. + let max_image_count = if caps.max_image_count == 0 { + !0 + } else { + caps.max_image_count + }; + + // `0xFFFFFFFF` indicates that the extent depends on the created swapchain. + let current_extent = if caps.current_extent.width != !0 && caps.current_extent.height != !0 + { + Some(wgt::Extent3d { + width: caps.current_extent.width, + height: caps.current_extent.height, + depth_or_array_layers: 1, + }) + } else { + None + }; + + let raw_present_modes = { + profiling::scope!("vkGetPhysicalDeviceSurfacePresentModesKHR"); + match unsafe { + self.functor + .get_physical_device_surface_present_modes(adapter.raw, self.raw) + } { + Ok(present_modes) => present_modes, + Err(e) => { + log::error!("get_physical_device_surface_present_modes: {e}"); + // Per definition of `SurfaceCapabilities`, there must be at least one present mode. + return None; + } + } + }; + + let raw_surface_formats = { + profiling::scope!("vkGetPhysicalDeviceSurfaceFormatsKHR"); + match unsafe { + self.functor + .get_physical_device_surface_formats(adapter.raw, self.raw) + } { + Ok(formats) => formats, + Err(e) => { + log::error!("get_physical_device_surface_formats: {e}"); + // Per definition of `SurfaceCapabilities`, there must be at least one present format. + return None; + } + } + }; + + // Group the driver's (format, color space) pairs into one entry per + // format, preserving the driver's format order. + let mut formats: Vec<wgt::SurfaceFormatCapabilities> = Vec::new(); + for (format, color_space) in raw_surface_formats + .into_iter() + .filter_map(conv::map_vk_surface_formats) + { + let color_spaces = color_space.to_color_spaces().unwrap(); + match formats.iter_mut().find(|fc| fc.format == format) { + Some(fc) => fc.color_spaces |= color_spaces, + None => formats.push(wgt::SurfaceFormatCapabilities { + format, + color_spaces, + }), + } + } + Some(crate::SurfaceCapabilities { + formats, + // TODO: Right now we're always truncating the swap chain + // (presumably - we're actually setting the min image count which isn't necessarily the swap chain size) + // Instead, we should use extensions when available to wait in present. + // See https://github.com/gfx-rs/wgpu/issues/2869 + maximum_frame_latency: (caps.min_image_count - 1)..=(max_image_count - 1), // Note this can't underflow since both `min_image_count` is at least one and we already patched `max_image_count`. + current_extent, + usage: conv::map_vk_image_usage(caps.supported_usage_flags), + present_modes: raw_present_modes + .into_iter() + .flat_map(conv::map_vk_present_mode) + .collect(), + composite_alpha_modes: conv::map_vk_composite_alpha(caps.supported_composite_alpha), + }) + } + + unsafe fn create_swapchain( + &self, + device: &crate::vulkan::Device, + config: &crate::SurfaceConfiguration, + provided_old_swapchain: Option<Box<dyn Swapchain>>, + ) -> Result<Box<dyn Swapchain>, crate::SurfaceError> { + profiling::scope!("Device::create_swapchain"); + let functor = khr::swapchain::Device::new(&self.instance.raw, &device.shared.raw); + + let old_swapchain = provided_old_swapchain + .as_ref() + .map(|osc| osc.as_any().downcast_ref::<NativeSwapchain>().unwrap().raw) + .unwrap_or(vk::SwapchainKHR::null()); + + let color_space = conv::map_surface_color_space(config.color_space); + + let original_format = device.shared.private_caps.map_texture_format(config.format); + let mut raw_flags = vk::SwapchainCreateFlagsKHR::empty(); + let mut raw_view_formats: Vec<vk::Format> = vec![]; + if !config.view_formats.is_empty() { + raw_flags |= vk::SwapchainCreateFlagsKHR::MUTABLE_FORMAT; + raw_view_formats = config + .view_formats + .iter() + .map(|f| device.shared.private_caps.map_texture_format(*f)) + .collect(); + raw_view_formats.push(original_format); + } + + let mut info = vk::SwapchainCreateInfoKHR::default() + .flags(raw_flags) + .surface(self.raw) + .min_image_count(config.maximum_frame_latency + 1) // TODO: https://github.com/gfx-rs/wgpu/issues/2869 + .image_format(original_format) + .image_color_space(color_space) + .image_extent(vk::Extent2D { + width: config.extent.width, + height: config.extent.height, + }) + .image_array_layers(config.extent.depth_or_array_layers) + .image_usage(conv::map_texture_usage(config.usage)) + .image_sharing_mode(vk::SharingMode::EXCLUSIVE) + .pre_transform(vk::SurfaceTransformFlagsKHR::IDENTITY) + .composite_alpha(conv::map_composite_alpha_mode(config.composite_alpha_mode)) + .present_mode(conv::map_present_mode(config.present_mode)) + .clipped(true) + .old_swapchain(old_swapchain); + + let mut format_list_info = vk::ImageFormatListCreateInfo::default(); + if !raw_view_formats.is_empty() { + format_list_info = format_list_info.view_formats(&raw_view_formats); + info = info.push_next(&mut format_list_info); + } + + let result = { + profiling::scope!("vkCreateSwapchainKHR"); + unsafe { functor.create_swapchain(&info, None) } + }; + + let raw = match result { + Ok(swapchain) => swapchain, + Err(error) => { + return Err(match error { + vk::Result::ERROR_SURFACE_LOST_KHR + | vk::Result::ERROR_INITIALIZATION_FAILED => crate::SurfaceError::Lost, + vk::Result::ERROR_NATIVE_WINDOW_IN_USE_KHR => { + crate::SurfaceError::Other("Native window is in use") + } + // We don't use VK_EXT_image_compression_control + // VK_ERROR_COMPRESSION_EXHAUSTED_EXT + other => map_host_device_oom_and_lost_err(other).into(), + }); + } + }; + + let images = unsafe { functor.get_swapchain_images(raw) } + .map_err(crate::vulkan::map_host_device_oom_err)?; + + // This fence is only used to throttle acquisition on Windows. It is very important to + // avoid bad frame pacing when the Vulkan driver is using a DXGI swapchain. See + // https://github.com/gfx-rs/wgpu/issues/8310 and + // https://github.com/gfx-rs/wgpu/issues/8354 for more details. + let fence = if cfg!(target_os = "windows") { + let raw = unsafe { + device + .shared + .raw + .create_fence(&vk::FenceCreateInfo::default(), None) + .map_err(crate::vulkan::map_host_device_oom_err)? + }; + Some(raw) + } else { + None + }; + + // NOTE: It's important that we define the same number of acquire/present semaphores + // as we will need to index into them with the image index. + let acquire_semaphores = (0..images.len()) + .map(|i| { + SwapchainAcquireSemaphore::new(&device.shared, i) + .map(Mutex::new) + .map(Arc::new) + }) + .collect::<Result<Vec<_>, _>>()?; + + let present_semaphores = (0..images.len()) + .map(|i| Arc::new(Mutex::new(SwapchainPresentSemaphores::new(i)))) + .collect::<Vec<_>>(); + + Ok(Box::new(NativeSwapchain { + raw, + functor, + device: Arc::clone(&device.shared), + images, + fence, + config: config.clone(), + acquire_semaphores, + next_acquire_index: 0, + present_semaphores, + next_present_time: None, + })) + } + + #[cfg(windows)] + fn display_hdr_info(&self) -> Option<wgt::DisplayHdrInfo> { + self.hdr_source.as_ref()?.display_hdr_info() + } + + fn as_any(&self) -> &dyn Any { + self + } +} + +pub(crate) struct NativeSwapchain { + raw: vk::SwapchainKHR, + functor: khr::swapchain::Device, + device: Arc<DeviceShared>, + images: Vec<vk::Image>, + /// Fence used to wait on the acquired image. + fence: Option<vk::Fence>, + config: crate::SurfaceConfiguration, + + /// Semaphores used between image acquisition and the first submission + /// that uses that image. This is indexed using [`next_acquire_index`]. + /// + /// Because we need to provide this to [`vkAcquireNextImageKHR`], we haven't + /// received the swapchain image index for the frame yet, so we cannot use + /// that to index it. + /// + /// Before we pass this to [`vkAcquireNextImageKHR`], we ensure that we wait on + /// the submission indicated by [`previously_used_submission_index`]. This ensures + /// the semaphore is no longer in use before we use it. + /// + /// [`next_acquire_index`]: NativeSwapchain::next_acquire_index + /// [`vkAcquireNextImageKHR`]: https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html#vkAcquireNextImageKHR + /// [`previously_used_submission_index`]: SwapchainAcquireSemaphore::previously_used_submission_index + acquire_semaphores: Vec<Arc<Mutex<SwapchainAcquireSemaphore>>>, + /// The index of the next acquire semaphore to use. + /// + /// This is incremented each time we acquire a new image, and wraps around + /// to 0 when it reaches the end of [`acquire_semaphores`]. + /// + /// [`acquire_semaphores`]: NativeSwapchain::acquire_semaphores + next_acquire_index: usize, + + /// Semaphore sets used between all submissions that write to an image and + /// the presentation of that image. + /// + /// This is indexed by the swapchain image index returned by + /// [`vkAcquireNextImageKHR`]. + /// + /// We know it is safe to use these semaphores because use them + /// _after_ the acquire semaphore. Because the acquire semaphore + /// has been signaled, the previous presentation using that image + /// is known-finished, so this semaphore is no longer in use. + /// + /// [`vkAcquireNextImageKHR`]: https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html#vkAcquireNextImageKHR + present_semaphores: Vec<Arc<Mutex<SwapchainPresentSemaphores>>>, + + /// The present timing information which will be set in the next call to [`present()`](crate::Queue::present()). + /// + /// # Safety + /// + /// This must only be set if [`wgt::Features::VULKAN_GOOGLE_DISPLAY_TIMING`] is enabled, and + /// so the VK_GOOGLE_display_timing extension is present. + next_present_time: Option<vk::PresentTimeGOOGLE>, +} + +impl Drop for NativeSwapchain { + fn drop(&mut self) { + unsafe { + self.functor.destroy_swapchain(self.raw, None); + } + } +} + +impl Swapchain for NativeSwapchain { + unsafe fn release_resources(&mut self, device: &crate::vulkan::Device) { + profiling::scope!("Swapchain::release_resources"); + { + profiling::scope!("vkDeviceWaitIdle"); + // We need to also wait until all presentation work is done. Because there is no way to portably wait until + // the presentation work is done, we are forced to wait until the device is idle. + let _ = unsafe { + device + .shared + .raw + .device_wait_idle() + .map_err(map_host_device_oom_and_lost_err) + }; + }; + + if let Some(fence) = self.fence { + unsafe { device.shared.raw.destroy_fence(fence, None) } + } + + // We cannot take this by value, as the function returns `self`. + for semaphore in self.acquire_semaphores.drain(..) { + let arc_removed = Arc::into_inner(semaphore).expect( + "Trying to destroy a SwapchainAcquireSemaphore that is still in use by a SurfaceTexture", + ); + let mutex_removed = arc_removed.into_inner(); + + unsafe { mutex_removed.destroy(&device.shared.raw) }; + } + + for semaphore in self.present_semaphores.drain(..) { + let arc_removed = Arc::into_inner(semaphore).expect( + "Trying to destroy a SwapchainPresentSemaphores that is still in use by a SurfaceTexture", + ); + let mutex_removed = arc_removed.into_inner(); + + unsafe { mutex_removed.destroy(&device.shared.raw) }; + } + } + + unsafe fn acquire( + &mut self, + timeout: Option<core::time::Duration>, + fence: &crate::vulkan::Fence, + ) -> Result<crate::AcquiredSurfaceTexture<crate::api::Vulkan>, crate::SurfaceError> { + let mut timeout_ns = match timeout { + Some(duration) => duration.as_nanos() as u64, + None => u64::MAX, + }; + + // AcquireNextImageKHR on Android (prior to Android 11) doesn't support timeouts + // and will also log verbose warnings if tying to use a timeout. + // + // Android 10 implementation for reference: + // https://android.googlesource.com/platform/frameworks/native/+/refs/tags/android-mainline-10.0.0_r13/vulkan/libvulkan/swapchain.cpp#1426 + // Android 11 implementation for reference: + // https://android.googlesource.com/platform/frameworks/native/+/refs/tags/android-mainline-11.0.0_r45/vulkan/libvulkan/swapchain.cpp#1438 + // + // Android 11 corresponds to an SDK_INT/ro.build.version.sdk of 30 + if cfg!(target_os = "android") && self.device.instance.android_sdk_version < 30 { + timeout_ns = u64::MAX; + } + + let acquire_semaphore_arc = self.get_acquire_semaphore(); + // Nothing should be using this, so we don't block, but panic if we fail to lock. + let acquire_semaphore_guard = acquire_semaphore_arc + .try_lock() + .expect("Failed to lock a SwapchainSemaphores."); + + // Wait for all commands writing to the previously acquired image to + // complete. + // + // Almost all the steps in the usual acquire-draw-present flow are + // asynchronous: they get something started on the presentation engine + // or the GPU, but on the CPU, control returns immediately. Without some + // sort of intervention, the CPU could crank out frames much faster than + // the presentation engine can display them. + // + // This is the intervention: if any submissions drew on this image, and + // thus waited for `locked_swapchain_semaphores.acquire`, wait for all + // of them to finish, thus ensuring that it's okay to pass `acquire` to + // `vkAcquireNextImageKHR` again. + let completed = self.device.wait_for_fence( + fence, + acquire_semaphore_guard.previously_used_submission_index, + timeout_ns, + )?; + if !completed { + return Err(crate::SurfaceError::Timeout); + } + + let acquire_fence = self.fence.unwrap_or_else(vk::Fence::null); + + // will block if no image is available + let (index, suboptimal) = match unsafe { + profiling::scope!("vkAcquireNextImageKHR"); + self.functor.acquire_next_image( + self.raw, + timeout_ns, + acquire_semaphore_guard.acquire, + acquire_fence, + ) + } { + // We treat `VK_SUBOPTIMAL_KHR` as `VK_SUCCESS` on Android. + // See the comment in `Queue::present`. + #[cfg(target_os = "android")] + Ok((index, _)) => (index, false), + #[cfg(not(target_os = "android"))] + Ok(pair) => pair, + Err(error) => { + return match error { + vk::Result::TIMEOUT => Err(crate::SurfaceError::Timeout), + vk::Result::NOT_READY | vk::Result::ERROR_OUT_OF_DATE_KHR => { + Err(crate::SurfaceError::Outdated) + } + vk::Result::ERROR_SURFACE_LOST_KHR => Err(crate::SurfaceError::Lost), + // We don't use VK_EXT_full_screen_exclusive + // VK_ERROR_FULL_SCREEN_EXCLUSIVE_MODE_LOST_EXT + other => Err(map_host_device_oom_and_lost_err(other).into()), + }; + } + }; + + if let Some(fence) = self.fence { + unsafe { + // The `wait_all` argument must be `true` to avoid crash on some Android devices. See https://github.com/gfx-rs/wgpu/pull/8769 + self.device + .raw + .wait_for_fences(&[fence], true, timeout_ns) + .map_err(map_host_device_oom_and_lost_err)?; + + self.device + .raw + .reset_fences(&[fence]) + .map_err(map_host_device_oom_and_lost_err)?; + } + } + + drop(acquire_semaphore_guard); + // We only advance the surface semaphores if we successfully acquired an image, otherwise + // we should try to re-acquire using the same semaphores. + self.advance_acquire_semaphore(); + + let present_semaphore_arc = self.get_present_semaphores(index); + + // special case for Intel Vulkan returning bizarre values (ugh) + if self.device.vendor_id == crate::auxil::db::intel::VENDOR && index > 0x100 { + return Err(crate::SurfaceError::Outdated); + } + + let identity = self.device.texture_identity_factory.next(); + + let texture = crate::vulkan::SurfaceTexture { + index, + texture: crate::vulkan::Texture { + raw: self.images[index as usize], + drop_guard: None, + memory: crate::vulkan::TextureMemory::External, + format: self.config.format, + copy_size: crate::CopyExtent { + width: self.config.extent.width, + height: self.config.extent.height, + depth: 1, + }, + identity, + }, + metadata: Box::new(NativeSurfaceTextureMetadata { + acquire_semaphores: acquire_semaphore_arc, + present_semaphores: present_semaphore_arc, + }), + }; + Ok(crate::AcquiredSurfaceTexture { + texture, + suboptimal, + }) + } + + unsafe fn discard_texture( + &mut self, + _texture: crate::vulkan::SurfaceTexture, + ) -> Result<(), crate::SurfaceError> { + // TODO: Current implementation no-ops + Ok(()) + } + + unsafe fn present( + &mut self, + queue: &crate::vulkan::Queue, + texture: crate::vulkan::SurfaceTexture, + ) -> Result<(), crate::SurfaceError> { + let metadata = texture + .metadata + .as_any() + .downcast_ref::<NativeSurfaceTextureMetadata>() + .unwrap(); + let mut acquire_semaphore = metadata.acquire_semaphores.lock(); + let mut present_semaphores = metadata.present_semaphores.lock(); + + let wait_semaphores = present_semaphores.get_present_wait_semaphores(); + + // Reset the acquire and present semaphores internal state + // to be ready for the next frame. + // + // We do this before the actual call to present to ensure that + // even if this method errors and early outs, we have reset + // the state for next frame. + acquire_semaphore.end_semaphore_usage(); + present_semaphores.end_semaphore_usage(); + + drop(acquire_semaphore); + + let swapchains = [self.raw]; + let image_indices = [texture.index]; + let vk_info = vk::PresentInfoKHR::default() + .swapchains(&swapchains) + .image_indices(&image_indices) + .wait_semaphores(&wait_semaphores); + + let mut display_timing; + let present_times; + let vk_info = if let Some(present_time) = self.next_present_time.take() { + debug_assert!( + self.device + .features + .contains(wgt::Features::VULKAN_GOOGLE_DISPLAY_TIMING), + "`next_present_time` should only be set if `VULKAN_GOOGLE_DISPLAY_TIMING` is enabled" + ); + present_times = [present_time]; + display_timing = vk::PresentTimesInfoGOOGLE::default().times(&present_times); + // SAFETY: We know that VK_GOOGLE_display_timing is present because of the safety contract on `next_present_time`. + vk_info.push_next(&mut display_timing) + } else { + vk_info + }; + + let suboptimal = { + profiling::scope!("vkQueuePresentKHR"); + unsafe { self.functor.queue_present(queue.raw, &vk_info) }.map_err(|error| { + match error { + vk::Result::ERROR_OUT_OF_DATE_KHR => crate::SurfaceError::Outdated, + vk::Result::ERROR_SURFACE_LOST_KHR => crate::SurfaceError::Lost, + // We don't use VK_EXT_full_screen_exclusive + // VK_ERROR_FULL_SCREEN_EXCLUSIVE_MODE_LOST_EXT + _ => map_host_device_oom_and_lost_err(error).into(), + } + })? + }; + if suboptimal { + // We treat `VK_SUBOPTIMAL_KHR` as `VK_SUCCESS` on Android. + // On Android 10+, libvulkan's `vkQueuePresentKHR` implementation returns `VK_SUBOPTIMAL_KHR` if not doing pre-rotation + // (i.e `VkSwapchainCreateInfoKHR::preTransform` not being equal to the current device orientation). + // This is always the case when the device orientation is anything other than the identity one, as we unconditionally use `VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR`. + #[cfg(not(target_os = "android"))] + log::debug!("Suboptimal present of frame {}", texture.index); + } + Ok(()) + } + + fn as_any(&self) -> &dyn Any { + self + } + + fn as_any_mut(&mut self) -> &mut dyn Any { + self + } +} + +impl NativeSwapchain { + pub(crate) fn as_raw(&self) -> vk::SwapchainKHR { + self.raw + } + + pub fn set_next_present_time(&mut self, present_timing: vk::PresentTimeGOOGLE) { + let features = wgt::Features::VULKAN_GOOGLE_DISPLAY_TIMING; + if self.device.features.contains(features) { + self.next_present_time = Some(present_timing); + } else { + // Ideally we'd use something like `device.required_features` here, but that's in `wgpu-core`, which we are a dependency of + panic!( + concat!( + "Tried to set display timing properties ", + "without the corresponding feature ({:?}) enabled." + ), + features + ); + } + } + + /// Mark the current frame finished, advancing to the next acquire semaphore. + fn advance_acquire_semaphore(&mut self) { + let semaphore_count = self.acquire_semaphores.len(); + self.next_acquire_index = (self.next_acquire_index + 1) % semaphore_count; + } + + /// Get the next acquire semaphore that should be used with this swapchain. + fn get_acquire_semaphore(&self) -> Arc<Mutex<SwapchainAcquireSemaphore>> { + self.acquire_semaphores[self.next_acquire_index].clone() + } + + /// Get the set of present semaphores that should be used with the given image index. + fn get_present_semaphores(&self, index: u32) -> Arc<Mutex<SwapchainPresentSemaphores>> { + self.present_semaphores[index as usize].clone() + } +} + +/// Semaphore used to acquire a swapchain image. +#[derive(Debug)] +struct SwapchainAcquireSemaphore { + /// A semaphore that is signaled when this image is safe for us to modify. + /// + /// When [`vkAcquireNextImageKHR`] returns the index of the next swapchain + /// image that we should use, that image may actually still be in use by the + /// presentation engine, and is not yet safe to modify. However, that + /// function does accept a semaphore that it will signal when the image is + /// indeed safe to begin messing with. + /// + /// This semaphore is: + /// + /// - waited for by the first queue submission to operate on this image + /// since it was acquired, and + /// + /// - signaled by [`vkAcquireNextImageKHR`] when the acquired image is ready + /// for us to use. + /// + /// [`vkAcquireNextImageKHR`]: https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html#vkAcquireNextImageKHR + acquire: vk::Semaphore, + + /// True if the next command submission operating on this image should wait + /// for [`acquire`]. + /// + /// We must wait for `acquire` before drawing to this swapchain image, but + /// because `wgpu-hal` queue submissions are always strongly ordered, only + /// the first submission that works with a swapchain image actually needs to + /// wait. We set this flag when this image is acquired, and clear it the + /// first time it's passed to [`Queue::submit`] as a surface texture. + /// + /// Additionally, semaphores can only be waited on once, so we need to ensure + /// that we only actually pass this semaphore to the first submission that + /// uses that image. + /// + /// [`acquire`]: SwapchainAcquireSemaphore::acquire + /// [`Queue::submit`]: crate::Queue::submit + should_wait_for_acquire: bool, + + /// The fence value of the last command submission that wrote to this image. + /// + /// The next time we try to acquire this image, we'll block until + /// this submission finishes, proving that [`acquire`] is ready to + /// pass to `vkAcquireNextImageKHR` again. + /// + /// [`acquire`]: SwapchainAcquireSemaphore::acquire + previously_used_submission_index: crate::FenceValue, +} + +impl SwapchainAcquireSemaphore { + fn new(device: &DeviceShared, index: usize) -> Result<Self, crate::DeviceError> { + Ok(Self { + acquire: device + .new_binary_semaphore(&format!("SwapchainImageSemaphore: Index {index} acquire"))?, + should_wait_for_acquire: true, + previously_used_submission_index: 0, + }) + } + + /// Sets the fence value which the next acquire will wait for. This prevents + /// the semaphore from being used while the previous submission is still in flight. + fn set_used_fence_value(&mut self, value: crate::FenceValue) { + self.previously_used_submission_index = value; + } + + /// Return the semaphore that commands drawing to this image should wait for, if any. + /// + /// This only returns `Some` once per acquisition; see + /// [`SwapchainAcquireSemaphore::should_wait_for_acquire`] for details. + fn get_acquire_wait_semaphore(&mut self) -> Option<vk::Semaphore> { + if self.should_wait_for_acquire { + self.should_wait_for_acquire = false; + Some(self.acquire) + } else { + None + } + } + + /// Indicates the cpu-side usage of this semaphore has finished for the frame, + /// so reset internal state to be ready for the next frame. + fn end_semaphore_usage(&mut self) { + // Reset the acquire semaphore, so that the next time we acquire this + // image, we can wait for it again. + self.should_wait_for_acquire = true; + } + + unsafe fn destroy(&self, device: &ash::Device) { + unsafe { + device.destroy_semaphore(self.acquire, None); + } + } +} + +#[derive(Debug)] +struct SwapchainPresentSemaphores { + /// A pool of semaphores for ordering presentation after drawing. + /// + /// The first [`present_index`] semaphores in this vector are: + /// + /// - all waited on by the call to [`vkQueuePresentKHR`] that presents this + /// image, and + /// + /// - each signaled by some [`vkQueueSubmit`] queue submission that draws to + /// this image, when the submission finishes execution. + /// + /// This vector accumulates one semaphore per submission that writes to this + /// image. This is awkward, but hard to avoid: [`vkQueuePresentKHR`] + /// requires a semaphore to order it with respect to drawing commands, and + /// we can't attach new completion semaphores to a command submission after + /// it's been submitted. This means that, at submission time, we must create + /// the semaphore we might need if the caller's next action is to enqueue a + /// presentation of this image. + /// + /// An alternative strategy would be for presentation to enqueue an empty + /// submit, ordered relative to other submits in the usual way, and + /// signaling a single presentation semaphore. But we suspect that submits + /// are usually expensive enough, and semaphores usually cheap enough, that + /// performance-sensitive users will avoid making many submits, so that the + /// cost of accumulated semaphores will usually be less than the cost of an + /// additional submit. + /// + /// Only the first [`present_index`] semaphores in the vector are actually + /// going to be signalled by submitted commands, and need to be waited for + /// by the next present call. Any semaphores beyond that index were created + /// for prior presents and are simply being retained for recycling. + /// + /// [`present_index`]: SwapchainPresentSemaphores::present_index + /// [`vkQueuePresentKHR`]: https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html#vkQueuePresentKHR + /// [`vkQueueSubmit`]: https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html#vkQueueSubmit + present: Vec<vk::Semaphore>, + + /// The number of semaphores in [`present`] to be signalled for this submission. + /// + /// [`present`]: SwapchainPresentSemaphores::present + present_index: usize, + + /// Which image this semaphore set is used for. + frame_index: usize, +} + +impl SwapchainPresentSemaphores { + pub fn new(frame_index: usize) -> Self { + Self { + present: Vec::new(), + present_index: 0, + frame_index, + } + } + + /// Return the semaphore that the next submission that writes to this image should + /// signal when it's done. + /// + /// See [`SwapchainPresentSemaphores::present`] for details. + fn get_submit_signal_semaphore( + &mut self, + device: &DeviceShared, + ) -> Result<vk::Semaphore, crate::DeviceError> { + // Try to recycle a semaphore we created for a previous presentation. + let sem = match self.present.get(self.present_index) { + Some(sem) => *sem, + None => { + let sem = device.new_binary_semaphore(&format!( + "SwapchainImageSemaphore: Image {} present semaphore {}", + self.frame_index, self.present_index + ))?; + self.present.push(sem); + sem + } + }; + + self.present_index += 1; + + Ok(sem) + } + + /// Indicates the cpu-side usage of this semaphore has finished for the frame, + /// so reset internal state to be ready for the next frame. + fn end_semaphore_usage(&mut self) { + // Reset the index to 0, so that the next time we get a semaphore, we + // start from the beginning of the list. + self.present_index = 0; + } + + /// Return the semaphores that a presentation of this image should wait on. + /// + /// Return a slice of semaphores that the call to [`vkQueueSubmit`] that + /// ends this image's acquisition should wait for. See + /// [`SwapchainPresentSemaphores::present`] for details. + /// + /// Reset `self` to be ready for the next acquisition cycle. + /// + /// [`vkQueueSubmit`]: https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html#vkQueueSubmit + fn get_present_wait_semaphores(&mut self) -> Vec<vk::Semaphore> { + self.present[0..self.present_index].to_vec() + } + + unsafe fn destroy(&self, device: &ash::Device) { + unsafe { + for sem in &self.present { + device.destroy_semaphore(*sem, None); + } + } + } +} + +#[derive(Debug)] +struct NativeSurfaceTextureMetadata { + acquire_semaphores: Arc<Mutex<SwapchainAcquireSemaphore>>, + present_semaphores: Arc<Mutex<SwapchainPresentSemaphores>>, +} + +impl SurfaceTextureMetadata for NativeSurfaceTextureMetadata { + fn get_semaphore_guard(&self) -> Box<dyn SwapchainSubmissionSemaphoreGuard + '_> { + Box::new(NativeSwapchainSubmissionSemaphoreGuard { + acquire_semaphore_guard: self + .acquire_semaphores + .try_lock() + .expect("Failed to lock surface acquire semaphore"), + present_semaphores_guard: self + .present_semaphores + .try_lock() + .expect("Failed to lock surface present semaphores"), + }) + } + + fn as_any(&self) -> &dyn Any { + self + } +} + +struct NativeSwapchainSubmissionSemaphoreGuard<'a> { + acquire_semaphore_guard: MutexGuard<'a, SwapchainAcquireSemaphore>, + present_semaphores_guard: MutexGuard<'a, SwapchainPresentSemaphores>, +} + +impl<'a> SwapchainSubmissionSemaphoreGuard for NativeSwapchainSubmissionSemaphoreGuard<'a> { + fn set_used_fence_value(&mut self, value: u64) { + self.acquire_semaphore_guard.set_used_fence_value(value); + } + + fn get_acquire_wait_semaphore(&mut self) -> Option<SemaphoreType> { + self.acquire_semaphore_guard + .get_acquire_wait_semaphore() + .map(SemaphoreType::Binary) + } + + fn get_submit_signal_semaphore( + &mut self, + device: &DeviceShared, + ) -> Result<SemaphoreType, crate::DeviceError> { + self.present_semaphores_guard + .get_submit_signal_semaphore(device) + .map(SemaphoreType::Binary) + } +} diff --git a/app/vendor/rune/vendor/winit.patch b/app/vendor/rune/vendor/winit.patch new file mode 100644 index 0000000..8390f72 --- /dev/null +++ b/app/vendor/rune/vendor/winit.patch @@ -0,0 +1,1401 @@ +diff --git a/src/platform_impl/linux/wayland/seat/pointer/mod.rs b/src/platform_impl/linux/wayland/seat/pointer/mod.rs +--- a/src/platform_impl/linux/wayland/seat/pointer/mod.rs ++++ b/src/platform_impl/linux/wayland/seat/pointer/mod.rs +@@ -171,3 +171,3 @@ + }, +- PointerEventKind::Axis { horizontal, vertical, .. } => { ++ PointerEventKind::Axis { horizontal, vertical, source, .. } => { + // Get the current phase. +@@ -204,5 +204,14 @@ + } else { + // NOTE: Wayland sign convention is the inverse of winit. ++ use sctk::reexports::client::protocol::wl_pointer::AxisSource; ++ // Chromium 152, wayland_pointer.cc: OnAxis converts surface units by ++ // kWheelDelta / kAxisValueScale. Only finger and continuous sources use ++ // this gain here: a wheel can send axis-only frames between detents. ++ const FINGER_POINTS_PER_AXIS_UNIT: f64 = 120.0 / 10.0; ++ let gain = match source { ++ Some(AxisSource::Finger | AxisSource::Continuous) => FINGER_POINTS_PER_AXIS_UNIT, ++ _ => 1.0, ++ }; + MouseScrollDelta::PixelDelta( +- LogicalPosition::new(-horizontal.absolute, -vertical.absolute) ++ LogicalPosition::new(-horizontal.absolute * gain, -vertical.absolute * gain) + .to_physical(scale_factor), +diff --git a/src/platform/macos.rs b/src/platform/macos.rs +index 30623b0..943e97b 100644 +--- a/src/platform/macos.rs ++++ b/src/platform/macos.rs +@@ -529,3 +529,25 @@ pub enum OptionAsAlt { + #[default] + None, + } ++ ++/// Rune: the focused field's text around its selection (the selection a byte range of it), which ++/// the input method reads through `selectedRange` and `attributedSubstringForProposedRange:` to ++/// convert committed text again; `None` when nothing takes text. ++pub fn set_ime_text(text: Option<(String, std::ops::Range<usize>)>) { ++ crate::platform_impl::ime_text::TEXT.with_borrow_mut(|t| *t = text); ++} ++ ++/// Rune: the clauses `setMarkedText:` gave marked text `preedit` (byte ranges, whether each is ++/// the one being converted), if it's the last marked text. ++pub fn take_ime_clauses(preedit: &str) -> Vec<(std::ops::Range<usize>, bool)> { ++ crate::platform_impl::ime_text::CLAUSES.with_borrow_mut(|c| match c.take() { ++ Some((text, clauses)) if text == preedit => clauses, ++ _ => Vec::new(), ++ }) ++} ++ ++/// Rune: the byte range of the text given to [`set_ime_text`] that a reconversion's marked text ++/// replaces, once. ++pub fn take_ime_replacement() -> Option<std::ops::Range<usize>> { ++ crate::platform_impl::ime_text::REPLACEMENT.with_borrow_mut(|r| r.take()) ++} +diff --git a/src/platform_impl/macos/ime_text.rs b/src/platform_impl/macos/ime_text.rs +new file mode 100644 +index 0000000..8725e96 +--- /dev/null ++++ b/src/platform_impl/macos/ime_text.rs +@@ -0,0 +1,30 @@ ++//! Rune: what `Ime::Preedit` can't carry, beside it. The app's text around its selection, for ++//! `selectedRange` and `attributedSubstringForProposedRange:` (reconversion), a composition's ++//! clauses from `setMarkedText:`'s attributes, and the range a reconversion replaces. ++ ++use std::cell::RefCell; ++use std::ops::Range; ++ ++thread_local! { ++ /// The focused field's paragraph and its selection, UTF-8 bytes. ++ pub(crate) static TEXT: RefCell<Option<(String, Range<usize>)>> = const { RefCell::new(None) }; ++ /// The last marked text and its clauses (byte ranges, whether each is being converted). ++ pub(crate) static CLAUSES: RefCell<Option<(String, Vec<(Range<usize>, bool)>)>> = const { RefCell::new(None) }; ++ /// The range of `TEXT` a reconversion's marked text replaces, UTF-8 bytes. ++ pub(crate) static REPLACEMENT: RefCell<Option<Range<usize>>> = const { RefCell::new(None) }; ++} ++ ++/// `utf16` UTF-16 units into `text` as a UTF-8 byte offset, clamped to its end. ++pub(crate) fn byte_of(text: &str, utf16: usize) -> usize { ++ let mut units = 0; ++ for (i, c) in text.char_indices() { ++ if units >= utf16 { return i; } ++ units += c.len_utf16(); ++ } ++ text.len() ++} ++ ++/// UTF-8 byte `byte` of `text` in UTF-16 units. ++pub(crate) fn utf16_of(text: &str, byte: usize) -> usize { ++ text[..byte.min(text.len())].encode_utf16().count() ++} +diff --git a/src/platform_impl/macos/mod.rs b/src/platform_impl/macos/mod.rs +index 1b427a8..fff68ab 100644 +--- a/src/platform_impl/macos/mod.rs ++++ b/src/platform_impl/macos/mod.rs +@@ -8,6 +8,7 @@ mod event; + mod event_handler; + mod event_loop; + mod ffi; ++pub(crate) mod ime_text; + mod menu; + mod monitor; + mod observer; +diff --git a/src/platform_impl/macos/view.rs b/src/platform_impl/macos/view.rs +index c7ca5bc..c83d635 100644 +--- a/src/platform_impl/macos/view.rs ++++ b/src/platform_impl/macos/view.rs +@@ -262,6 +262,16 @@ declare_class!( + #[method(selectedRange)] + fn selected_range(&self) -> NSRange { + trace_scope!("selectedRange"); ++ // Rune: the app's selection in the text it published, so the input method can ++ // reconvert it. ++ if self.ivars().marked_text.borrow().length() == 0 { ++ if let Some(range) = super::ime_text::TEXT.with_borrow(|t| t.as_ref().map(|(text, sel)| { ++ let a = super::ime_text::utf16_of(text, sel.start); ++ NSRange::new(a, super::ime_text::utf16_of(text, sel.end) - a) ++ })) { ++ return range; ++ } ++ } + // Documented to return `{NSNotFound, 0}` if there is no selection. + NSRange::new(NSNotFound as NSUInteger, 0) + } +@@ -271,16 +281,27 @@ declare_class!( + &self, + string: &NSObject, + selected_range: NSRange, +- _replacement_range: NSRange, ++ replacement_range: NSRange, + ) { +- // TODO: Use _replacement_range, requires changing the event to report surrounding text. + trace_scope!("setMarkedText:selectedRange:replacementRange:"); + ++ // Rune: a reconversion names the range of the published text the marked text replaces. ++ if replacement_range.location != NSNotFound as NSUInteger { ++ super::ime_text::TEXT.with_borrow(|t| if let Some((text, _)) = t { ++ let a = super::ime_text::byte_of(text, replacement_range.location); ++ let b = super::ime_text::byte_of(text, replacement_range.location + replacement_range.length); ++ super::ime_text::REPLACEMENT.with_borrow_mut(|r| *r = Some(a..b)); ++ }); ++ } ++ + // SAFETY: This method is guaranteed to get either a `NSString` or a `NSAttributedString`. + let (marked_text, string) = if string.is_kind_of::<NSAttributedString>() { + let string: *const NSObject = string; + let string: *const NSAttributedString = string.cast(); + let string = unsafe { &*string }; ++ // Rune: the clauses, by the input method's clause segments and underlines. ++ let clauses = marked_clauses(string); ++ super::ime_text::CLAUSES.with_borrow_mut(|c| *c = Some((string.string().to_string(), clauses))); + ( + NSMutableAttributedString::from_attributed_nsstring(string), + string.string(), +@@ -354,17 +375,30 @@ declare_class!( + #[method_id(validAttributesForMarkedText)] + fn valid_attributes_for_marked_text(&self) -> Retained<NSArray<NSAttributedStringKey>> { + trace_scope!("validAttributesForMarkedText"); +- NSArray::new() ++ // Rune: the underline and clause segments, which carry a composition's clauses. ++ NSArray::from_vec(vec![NSString::from_str("NSUnderline"), NSString::from_str("NSMarkedClauseSegment")]) + } + + #[method_id(attributedSubstringForProposedRange:actualRange:)] + fn attributed_substring_for_proposed_range( + &self, +- _range: NSRange, +- _actual_range: *mut NSRange, ++ range: NSRange, ++ actual_range: *mut NSRange, + ) -> Option<Retained<NSAttributedString>> { + trace_scope!("attributedSubstringForProposedRange:actualRange:"); +- None ++ // Rune: the published text, for reconversion and Look Up. ++ super::ime_text::TEXT.with_borrow(|t| { ++ let (text, _) = t.as_ref()?; ++ let a = super::ime_text::byte_of(text, range.location); ++ let b = super::ime_text::byte_of(text, range.location.saturating_add(range.length)); ++ if a >= b { return None; } ++ if !actual_range.is_null() { ++ let ua = super::ime_text::utf16_of(text, a); ++ // SAFETY: AppKit's out-parameter, checked non-null. ++ unsafe { *actual_range = NSRange::new(ua, super::ime_text::utf16_of(text, b) - ua) }; ++ } ++ Some(NSAttributedString::from_nsstring(&NSString::from_str(&text[a..b]))) ++ }) + } + + #[method(characterIndexForPoint:)] +@@ -1140,3 +1174,32 @@ fn replace_event(event: &NSEvent, option_as_alt: OptionAsAlt) -> Retained<NSEven + event.copy() + } + } ++ ++/// Rune: a marked text's clauses, byte ranges with whether each is the one being converted: one ++/// per run of `NSMarkedClauseSegment` (or of the underline when an input method sets no ++/// segments), the target the one with a thick underline. ++fn marked_clauses(string: &NSAttributedString) -> Vec<(std::ops::Range<usize>, bool)> { ++ let text = string.string(); ++ let utf8 = text.to_string(); ++ let len = text.length(); ++ let (segment, underline) = (NSString::from_str("NSMarkedClauseSegment"), NSString::from_str("NSUnderline")); ++ let attribute = |key: &NSString, at: NSUInteger, range: &mut NSRange| -> Option<Retained<AnyObject>> { ++ // SAFETY: `at` is inside the string; `range` is a valid out-parameter. ++ unsafe { msg_send_id![string, attribute: key, atIndex: at, effectiveRange: range as *mut NSRange] } ++ }; ++ let mut probe = NSRange::new(0, 0); ++ let by = if len > 0 && attribute(&segment, 0, &mut probe).is_some() { &segment } else { &underline }; ++ let mut out = Vec::new(); ++ let mut at = 0; ++ while at < len { ++ let mut run = NSRange::new(0, 0); ++ let _ = attribute(by, at, &mut run); ++ let end = (run.location + run.length).clamp(at + 1, len); ++ let mut ignored = NSRange::new(0, 0); ++ // NSUnderlineStyleThick is 2; an input method marks the clause being converted with it. ++ let style: isize = attribute(&underline, at, &mut ignored).map_or(0, |v| unsafe { objc2::msg_send![&*v, integerValue] }); ++ out.push((super::ime_text::byte_of(&utf8, at)..super::ime_text::byte_of(&utf8, end), style & 0xF >= 2)); ++ at = end; ++ } ++ out ++} +diff --git a/src/platform_impl/windows/window.rs b/src/platform_impl/windows/window.rs +index 228c6f0..1fcf1f2 100644 +--- a/src/platform_impl/windows/window.rs ++++ b/src/platform_impl/windows/window.rs +@@ -1246,7 +1246,12 @@ impl InitData<'_> { + unsafe { DeleteObject(region) }; + } + +- win.set_skip_taskbar(self.attributes.platform_specific.skip_taskbar); ++ // A new window is on the taskbar already: only taking it off needs the TaskbarList COM ++ // object (CoInitializeEx and CoCreateInstance on this thread, about 7,800 us and nine ++ // shell DLLs before the window's first frame). ++ if self.attributes.platform_specific.skip_taskbar { ++ win.set_skip_taskbar(true); ++ } + win.set_window_icon(self.attributes.window_icon.clone()); + win.set_taskbar_icon(self.attributes.platform_specific.taskbar_icon.clone()); + +@@ -1328,6 +1333,11 @@ unsafe fn init( + // Will be changed later using `window.set_enabled_buttons` but we need to set a default here + // so the diffing later can work. + window_flags.set(WindowFlags::CLOSABLE, true); ++ // The window is made with the boxes it asks for, so `set_enabled_buttons` in `on_create` ++ // changes nothing: adding them there rewrote its styles and changed its frame again ++ // (`SWP_FRAMECHANGED`, about 1,000 us before its first frame). ++ window_flags.set(WindowFlags::MINIMIZABLE, attributes.enabled_buttons.contains(WindowButtons::MINIMIZE)); ++ window_flags.set(WindowFlags::MAXIMIZABLE, attributes.enabled_buttons.contains(WindowButtons::MAXIMIZE)); + window_flags.set(WindowFlags::CLIP_CHILDREN, attributes.platform_specific.clip_children); + + let mut fallback_parent = || match attributes.platform_specific.owner { +@@ -1360,6 +1370,18 @@ unsafe fn init( + let menu = attributes.platform_specific.menu; + let fullscreen = attributes.fullscreen.clone(); + let maximized = attributes.maximized; ++ // A window with a physical position is made there, at its size, so it is born on its ++ // display at that display's scale. Made at the default place (the primary display) and moved ++ // there afterwards, it would cross to the other display's scale (WM_DPICHANGED) and be ++ // resized to keep its logical size: a window saved on a 150 % display beside a 100 % primary ++ // would reopen half as large again. ++ let (x, y, width, height) = match (attributes.position, attributes.inner_size) { ++ (Some(Position::Physical(p)), Some(Size::Physical(s))) => { ++ (p.x, p.y, s.width as i32, s.height as i32) ++ }, ++ (Some(Position::Physical(p)), _) => (p.x, p.y, CW_USEDEFAULT, CW_USEDEFAULT), ++ _ => (CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT), ++ }; + let mut initdata = InitData { event_loop, attributes, window_flags, window: None }; + + let (style, ex_style) = window_flags.to_window_styles(); +@@ -1369,10 +1391,10 @@ unsafe fn init( + class_name.as_ptr(), + title.as_ptr(), + style, +- CW_USEDEFAULT, +- CW_USEDEFAULT, +- CW_USEDEFAULT, +- CW_USEDEFAULT, ++ x, ++ y, ++ width, ++ height, + parent.unwrap_or(0), + menu.unwrap_or(0), + util::get_instance_handle(), +diff --git a/src/platform_impl/windows/window_state.rs b/src/platform_impl/windows/window_state.rs +index 8e24a4f..bfe251b 100644 +--- a/src/platform_impl/windows/window_state.rs ++++ b/src/platform_impl/windows/window_state.rs +@@ -380,7 +380,9 @@ impl WindowFlags { + diff.remove(WindowFlags::MINIMIZED); + } + +- if diff.contains(WindowFlags::CLOSABLE) || new.contains(WindowFlags::CLOSABLE) { ++ // A new window's system menu has Close enabled: the menu (`GetSystemMenu` makes the ++ // window its own copy, about 1,200 us before its first frame) is touched only to change it. ++ if diff.contains(WindowFlags::CLOSABLE) && !(self.is_empty() && new.contains(WindowFlags::CLOSABLE)) { + let flags = MF_BYCOMMAND + | if new.contains(WindowFlags::CLOSABLE) { MF_ENABLED } else { MF_DISABLED }; + +@@ -395,6 +397,12 @@ impl WindowFlags { + } + } + ++ // A show or a hide alone: ShowWindow set WS_VISIBLE itself. Writing the styles again and ++ // refreshing the frame (SWP_FRAMECHANGED) cost a window's first show about 2,200 us. ++ if diff == WindowFlags::VISIBLE { ++ return; ++ } ++ + if diff != WindowFlags::empty() { + let (style, style_ex) = new.to_window_styles(); + +diff --git a/src/platform/windows.rs b/src/platform/windows.rs +--- a/src/platform/windows.rs ++++ b/src/platform/windows.rs +@@ -13,6 +13,14 @@ use crate::monitor::MonitorHandle; + use crate::window::{BadIcon, Icon, Window, WindowAttributes}; + + /// Window Handle type used by Win32 API ++/// Builds winit's keyboard-layout table for thread `thread_id`'s keyboard layout on the calling ++/// thread, so the first key or mouse message that thread's windows handle doesn't build it (8-10 ++/// ms, every virtual key through `ToUnicodeEx`). Call it on a thread of its own at launch with ++/// the UI thread's id. ++pub fn warm_keyboard_layout(thread_id: u32) { ++ crate::platform_impl::warm_layout(thread_id); ++} ++ + pub type HWND = isize; + /// Menu Handle type used by Win32 API + pub type HMENU = isize; +diff --git a/src/platform_impl/windows/keyboard_layout.rs b/src/platform_impl/windows/keyboard_layout.rs +--- a/src/platform_impl/windows/keyboard_layout.rs ++++ b/src/platform_impl/windows/keyboard_layout.rs +@@ -48,6 +48,18 @@ use crate::platform_impl::{loword, primarylangid, scancode_to_physicalkey}; + pub(crate) static LAYOUT_CACHE: Lazy<Mutex<LayoutCache>> = + Lazy::new(|| Mutex::new(LayoutCache::default())); + ++/// Builds the layout cache's entry for the keyboard layout of thread `thread`, on the calling ++/// thread. The first key or mouse message a window's thread handles builds it otherwise (every ++/// virtual key through `ToUnicodeEx`, 8-10 ms), so a window's first input waited for it. ++pub(crate) fn warm_layout(thread: u32) { ++ let hkl = unsafe { GetKeyboardLayout(thread) } as u64; ++ if LAYOUT_CACHE.lock().unwrap().layouts.contains_key(&hkl) { ++ return; ++ } ++ let layout = LayoutCache::prepare_layout(hkl); ++ LAYOUT_CACHE.lock().unwrap().layouts.entry(hkl).or_insert(layout); ++} ++ + fn key_pressed(vkey: VIRTUAL_KEY) -> bool { + unsafe { (GetKeyState(vkey as i32) & (1 << 15)) == (1 << 15) } + } +diff --git a/src/platform_impl/windows/mod.rs b/src/platform_impl/windows/mod.rs +--- a/src/platform_impl/windows/mod.rs ++++ b/src/platform_impl/windows/mod.rs +@@ -8,6 +8,7 @@ pub(crate) use self::event_loop::{ + }; + pub(crate) use self::icon::{SelectedCursor, WinIcon}; + pub(crate) use self::keyboard::{physicalkey_to_scancode, scancode_to_physicalkey}; ++pub(crate) use self::keyboard_layout::warm_layout; + pub(crate) use self::monitor::{MonitorHandle, VideoModeHandle}; + pub(crate) use self::window::Window; + +diff --git a/src/platform_impl/windows/event_loop.rs b/src/platform_impl/windows/event_loop.rs +index 6d60c1c5..c386d644 100644 +--- a/src/platform_impl/windows/event_loop.rs ++++ b/src/platform_impl/windows/event_loop.rs +@@ -18,8 +18,9 @@ use crate::utils::Lazy; + + use windows_sys::Win32::Devices::HumanInterfaceDevice::MOUSE_MOVE_RELATIVE; + use windows_sys::Win32::Foundation::{ +- GetLastError, FALSE, HANDLE, HWND, LPARAM, LRESULT, POINT, RECT, WAIT_FAILED, WPARAM, ++ GetLastError, BOOL, FALSE, HANDLE, HWND, LPARAM, LRESULT, POINT, RECT, WAIT_FAILED, WPARAM, + }; ++use windows_sys::Win32::Graphics::Dwm::{DwmSetWindowAttribute, DWMWA_CLOAK}; + use windows_sys::Win32::Graphics::Gdi::{ + GetMonitorInfoW, MonitorFromRect, MonitorFromWindow, RedrawWindow, ScreenToClient, + ValidateRect, MONITORINFO, MONITOR_DEFAULTTONULL, RDW_INTERNALPAINT, SC_SCREENSAVE, +@@ -51,7 +52,7 @@ use windows_sys::Win32::UI::WindowsAndMessaging::{ + PT_TOUCH, QS_ALLINPUT, RI_MOUSE_HWHEEL, RI_MOUSE_WHEEL, SC_MINIMIZE, SC_RESTORE, + SIZE_MAXIMIZED, SWP_NOACTIVATE, SWP_NOMOVE, SWP_NOSIZE, SWP_NOZORDER, WHEEL_DELTA, WINDOWPOS, + WMSZ_BOTTOM, WMSZ_BOTTOMLEFT, WMSZ_BOTTOMRIGHT, WMSZ_LEFT, WMSZ_RIGHT, WMSZ_TOP, WMSZ_TOPLEFT, +- WMSZ_TOPRIGHT, WM_CAPTURECHANGED, WM_CLOSE, WM_CREATE, WM_DESTROY, WM_DPICHANGED, ++ WMSZ_TOPRIGHT, WM_CAPTURECHANGED, WM_CHAR, WM_CLOSE, WM_CREATE, WM_DESTROY, WM_DPICHANGED, + WM_ENTERSIZEMOVE, WM_EXITSIZEMOVE, WM_GETMINMAXINFO, WM_IME_COMPOSITION, WM_IME_ENDCOMPOSITION, + WM_IME_SETCONTEXT, WM_IME_STARTCOMPOSITION, WM_INPUT, WM_INPUT_DEVICE_CHANGE, WM_KEYDOWN, + WM_KEYUP, WM_KILLFOCUS, WM_LBUTTONDOWN, WM_LBUTTONUP, WM_MBUTTONDOWN, WM_MBUTTONUP, +@@ -950,6 +951,17 @@ fn create_event_target_window() -> HWND { + util::get_instance_handle(), + ptr::null(), + ); ++ // Rune: cloaked before it's made visible, so what walks the desktop's windows never meets ++ // it: UI Automation (screen readers) listed it as an unnamed 22x22 pane at 0,0, and window ++ // pickers that skip cloaked windows skip it. A cloaked window still gets WM_PAINT; a ++ // message-only or hidden one doesn't. ++ let cloak: BOOL = 1; ++ DwmSetWindowAttribute( ++ window, ++ DWMWA_CLOAK as u32, ++ &cloak as *const BOOL as *const c_void, ++ mem::size_of::<BOOL>() as u32, ++ ); + + super::set_window_long( + window, +@@ -1137,8 +1149,17 @@ unsafe fn public_window_callback_inner( + + let keyboard_callback = || { + use crate::event::WindowEvent::KeyboardInput; +- let events = +- userdata.key_event_builder.process_message(window, msg, wparam, lparam, &mut result); ++ // Rune: a bare WM_CHAR is dropped while an input method's composition is open. ++ let ime_composing = ++ msg == WM_CHAR && userdata.window_state_lock().ime_state != ImeState::Disabled; ++ let events = userdata.key_event_builder.process_message( ++ window, ++ msg, ++ wparam, ++ lparam, ++ ime_composing, ++ &mut result, ++ ); + for event in events { + userdata.send_event(Event::WindowEvent { + window_id: RootWindowId(WindowId(window)), +diff --git a/src/platform/wayland.rs b/src/platform/wayland.rs +index 9c1a8e4..63c0a92 100644 +--- a/src/platform/wayland.rs ++++ b/src/platform/wayland.rs +@@ -81,6 +81,23 @@ impl<T> EventLoopBuilderExtWayland for EventLoopBuilder<T> { + pub trait WindowExtWayland { + /// Returns `xdg_toplevel` of the window or [`None`] if the window is X11 window. + fn xdg_toplevel(&self) -> Option<NonNull<c_void>>; ++ ++ /// Rune: the radius, in logical points, of the arc the window's content takes at its bottom ++ /// corners. A client-side frame (`sctk-adwaita`) draws a one-point border around the window ++ /// and rounds its corners while it floats, so the content's own square corners would show ++ /// past it. ++ /// ++ /// Zero when the frame draws the window square (maximized or tiled), when no client-side ++ /// frame is drawn (server side decorations, or decorations off), and on X11. ++ fn content_corner_radius(&self) -> f32; ++ ++ /// Rune: whether a client-side frame draws the window's decorations, true whatever state the ++ /// frame is in: a maximized, tiled or fullscreen window keeps its frame, which hides parts of ++ /// itself rather than going away. ++ /// ++ /// False when the compositor draws the decorations, when decorations are off, when no frame ++ /// could be made, and on X11. ++ fn has_client_side_frame(&self) -> bool; + } + + impl WindowExtWayland for Window { +@@ -94,6 +111,28 @@ impl WindowExtWayland for Window { + crate::platform_impl::Window::Wayland(window) => window.xdg_toplevel(), + } + } ++ ++ #[inline] ++ fn content_corner_radius(&self) -> f32 { ++ #[allow(clippy::single_match)] ++ match &self.window { ++ #[cfg(x11_platform)] ++ crate::platform_impl::Window::X(_) => 0., ++ #[cfg(wayland_platform)] ++ crate::platform_impl::Window::Wayland(window) => window.content_corner_radius(), ++ } ++ } ++ ++ #[inline] ++ fn has_client_side_frame(&self) -> bool { ++ #[allow(clippy::single_match)] ++ match &self.window { ++ #[cfg(x11_platform)] ++ crate::platform_impl::Window::X(_) => false, ++ #[cfg(wayland_platform)] ++ crate::platform_impl::Window::Wayland(window) => window.has_client_side_frame(), ++ } ++ } + } + + /// Additional methods on [`WindowAttributes`] that are specific to Wayland. +diff --git a/src/platform_impl/linux/wayland/window/mod.rs b/src/platform_impl/linux/wayland/window/mod.rs +index 6d29a5a..2418b6f 100644 +--- a/src/platform_impl/linux/wayland/window/mod.rs ++++ b/src/platform_impl/linux/wayland/window/mod.rs +@@ -426,6 +426,18 @@ impl Window { + self.window_state.lock().unwrap().is_decorated() + } + ++ /// Rune: see `WindowExtWayland::content_corner_radius`. ++ #[inline] ++ pub fn content_corner_radius(&self) -> f32 { ++ self.window_state.lock().unwrap().content_corner_radius() ++ } ++ ++ /// Rune: see `WindowExtWayland::has_client_side_frame`. ++ #[inline] ++ pub fn has_client_side_frame(&self) -> bool { ++ self.window_state.lock().unwrap().has_client_side_frame() ++ } ++ + #[inline] + pub fn set_window_level(&self, _level: WindowLevel) {} + +diff --git a/src/platform_impl/linux/wayland/window/state.rs b/src/platform_impl/linux/wayland/window/state.rs +index 1ef7a06..9cd83c4 100644 +--- a/src/platform_impl/linux/wayland/window/state.rs ++++ b/src/platform_impl/linux/wayland/window/state.rs +@@ -398,6 +398,10 @@ impl WindowState { + self.resize(new_size); + true + } else { ++ // Rune: the frame may have appeared or gone, or turned square, and no resize follows to ++ // tell the compositor: the opaque region follows it now that it knows this configure's ++ // state. ++ self.reload_transparency_hint(); + false + } + } +@@ -599,6 +603,38 @@ impl WindowState { + } + } + ++ /// Rune: whether a client-side frame draws the window's decorations, whatever state it is in: ++ /// a maximized, tiled or fullscreen window keeps its frame (it draws square corners there), ++ /// which only hides parts of itself. False when the compositor draws the decorations, when ++ /// decorations are off, and when the frame could not be made (no subcompositor, or a frame that ++ /// failed to build). ++ #[inline] ++ pub fn has_client_side_frame(&self) -> bool { ++ self.decorate ++ && self ++ .last_configure ++ .as_ref() ++ .is_some_and(|configure| configure.decoration_mode == DecorationMode::Client) ++ && self.frame.is_some() ++ } ++ ++ /// Rune: the radius, in logical points, of the arc the window's content takes at its bottom ++ /// corners, which the client-side frame leaves it (the frame's visible border lies just ++ /// outside it). Zero when no client-side frame is drawn, and when the frame draws the window ++ /// square: maximized, tiled or fullscreen. ++ #[inline] ++ pub fn content_corner_radius(&self) -> f32 { ++ #[cfg(feature = "sctk-adwaita")] ++ if let Some(frame) = self ++ .frame ++ .as_ref() ++ .filter(|frame| self.decorate && !frame.is_hidden()) ++ { ++ return frame.content_corner_radius(); ++ } ++ 0. ++ } ++ + /// Get the outer size of the window. + #[inline] + pub fn outer_size(&self) -> LogicalSize<u32> { +@@ -655,17 +691,31 @@ impl WindowState { + } + + /// Reissue the transparency hint to the compositor. ++ /// ++ /// Rune: a client-side frame that rounds the content's bottom corners leaves the two corner ++ /// squares to the compositor, so an opaque window keeps the rest of itself opaque instead of ++ /// blending all of it. + pub fn reload_transparency_hint(&self) { + let surface = self.window.wl_surface(); + + if self.transparent { + surface.set_opaque_region(None); +- } else if let Ok(region) = Region::new(&*self.compositor) { ++ return; ++ } ++ let Ok(region) = Region::new(&*self.compositor) else { ++ warn!("Failed to mark window opaque."); ++ return; ++ }; ++ let radius = self.content_corner_radius() as i32; ++ let (width, height) = (self.size.width as i32, self.size.height as i32); ++ if radius <= 0 || width <= 2 * radius || height <= radius { + region.add(0, 0, i32::MAX, i32::MAX); +- surface.set_opaque_region(Some(region.wl_region())); + } else { +- warn!("Failed to mark window opaque."); ++ // Everything but the two squares the frame's arcs cross at the window's foot. ++ region.add(0, 0, width, height - radius); ++ region.add(radius, height - radius, width - 2 * radius, radius); + } ++ surface.set_opaque_region(Some(region.wl_region())); + } + + /// Try to resize the window when the user can do so. +diff --git a/src/platform_impl/windows/dark_mode.rs b/src/platform_impl/windows/dark_mode.rs +index 366e44c6..67c4fc53 100644 +--- a/src/platform_impl/windows/dark_mode.rs ++++ b/src/platform_impl/windows/dark_mode.rs +@@ -5,7 +5,9 @@ use std::{ffi::c_void, ptr}; + use crate::utils::Lazy; + use windows_sys::core::PCSTR; + use windows_sys::Win32::Foundation::{BOOL, HWND, NTSTATUS, S_OK}; +-use windows_sys::Win32::System::LibraryLoader::{GetProcAddress, LoadLibraryA}; ++use windows_sys::Win32::System::LibraryLoader::{ ++ GetProcAddress, LoadLibraryExA, LOAD_LIBRARY_SEARCH_SYSTEM32, ++}; + use windows_sys::Win32::System::SystemInformation::OSVERSIONINFOW; + use windows_sys::Win32::UI::Accessibility::{HCF_HIGHCONTRASTON, HIGHCONTRASTA}; + use windows_sys::Win32::UI::Controls::SetWindowTheme; +@@ -138,7 +140,9 @@ fn should_apps_use_dark_mode() -> bool { + return None; + } + +- let module = LoadLibraryA("uxtheme.dll\0".as_ptr().cast()); ++ // Rune: load uxtheme.dll from System32 only, not the app directory or CWD. ++ let module = ++ LoadLibraryExA("uxtheme.dll\0".as_ptr().cast(), 0, LOAD_LIBRARY_SEARCH_SYSTEM32); + + if module == 0 { + return None; +diff --git a/src/platform_impl/windows/util.rs b/src/platform_impl/windows/util.rs +index a3a7705d..c3980673 100644 +--- a/src/platform_impl/windows/util.rs ++++ b/src/platform_impl/windows/util.rs +@@ -9,7 +9,9 @@ use crate::utils::Lazy; + use windows_sys::core::{HRESULT, PCWSTR}; + use windows_sys::Win32::Foundation::{BOOL, HANDLE, HMODULE, HWND, POINT, RECT}; + use windows_sys::Win32::Graphics::Gdi::{ClientToScreen, HMONITOR}; +-use windows_sys::Win32::System::LibraryLoader::{GetProcAddress, LoadLibraryA}; ++use windows_sys::Win32::System::LibraryLoader::{ ++ GetProcAddress, LoadLibraryExA, LOAD_LIBRARY_SEARCH_SYSTEM32, ++}; + use windows_sys::Win32::System::SystemServices::IMAGE_DOS_HEADER; + use windows_sys::Win32::UI::HiDpi::{ + DPI_AWARENESS_CONTEXT, MONITOR_DPI_TYPE, PROCESS_DPI_AWARENESS, +@@ -195,7 +197,8 @@ pub(super) fn get_function_impl(library: &str, function: &str) -> Option<*const + assert_eq!(function.chars().last(), Some('\0')); + + // Library names we will use are ASCII so we can use the A version to avoid string conversion. +- let module = unsafe { LoadLibraryA(library.as_ptr()) }; ++ // Rune: load Windows system DLLs from System32 only, not the app directory or CWD. ++ let module = unsafe { LoadLibraryExA(library.as_ptr(), 0, LOAD_LIBRARY_SEARCH_SYSTEM32) }; + if module == 0 { + return None; + } +diff --git a/src/platform_impl/windows/keyboard.rs b/src/platform_impl/windows/keyboard.rs +index 9c109490..482bf051 100644 +--- a/src/platform_impl/windows/keyboard.rs ++++ b/src/platform_impl/windows/keyboard.rs +@@ -4,7 +4,9 @@ use std::mem::MaybeUninit; + use std::os::windows::ffi::OsStringExt; + use std::sync::atomic::AtomicU32; + use std::sync::atomic::Ordering::Relaxed; ++use std::collections::VecDeque; + use std::sync::{Mutex, MutexGuard}; ++use std::time::{Duration, Instant}; + + use windows_sys::Win32::Foundation::{HWND, LPARAM, WPARAM}; + use windows_sys::Win32::System::SystemServices::LANG_KOREAN; +@@ -14,8 +16,8 @@ use windows_sys::Win32::UI::Input::KeyboardAndMouse::{ + VK_CONTROL, VK_DECIMAL, VK_DELETE, VK_DIVIDE, VK_DOWN, VK_END, VK_F4, VK_HOME, VK_INSERT, + VK_LCONTROL, VK_LEFT, VK_LMENU, VK_LSHIFT, VK_LWIN, VK_MENU, VK_MULTIPLY, VK_NEXT, VK_NUMLOCK, + VK_NUMPAD0, VK_NUMPAD1, VK_NUMPAD2, VK_NUMPAD3, VK_NUMPAD4, VK_NUMPAD5, VK_NUMPAD6, VK_NUMPAD7, +- VK_NUMPAD8, VK_NUMPAD9, VK_PRIOR, VK_RCONTROL, VK_RETURN, VK_RIGHT, VK_RMENU, VK_RSHIFT, +- VK_RWIN, VK_SCROLL, VK_SHIFT, VK_SUBTRACT, VK_UP, ++ VK_NUMPAD8, VK_NUMPAD9, VK_PACKET, VK_PRIOR, VK_RCONTROL, VK_RETURN, VK_RIGHT, VK_RMENU, ++ VK_RSHIFT, VK_RWIN, VK_SCROLL, VK_SHIFT, VK_SUBTRACT, VK_UP, + }; + use windows_sys::Win32::UI::TextServices::HKL; + use windows_sys::Win32::UI::WindowsAndMessaging::{ +@@ -64,23 +66,39 @@ pub struct MessageAsKeyEvent { + /// text input. The "sequence" only consists of one WM_KEYUP / WM_SYSKEYUP event. + pub struct KeyEventBuilder { + event_info: Mutex<Option<PartialKeyEventInfo>>, ++ // Rune: high surrogate waiting for its matching low surrogate across consecutive VK_PACKET or ++ // bare WM_CHAR messages (Win+. emoji panel, Win+H voice typing, SendInput KEYEVENTF_UNICODE). ++ pending_high_surrogate: Mutex<Option<u16>>, ++ // Rune: recent key-downs whose `TranslateMessage` character may still arrive after their ++ // key-up (a program that posts keys), to tell that copy from other text. ++ translated: Mutex<VecDeque<Translated>>, ++ // Rune: the `lParam` of the key-down whose event takes the `WM_CHAR`s that follow it. ++ building: Mutex<Option<LPARAM>>, + pending: PendingEventQueue<MessageAsKeyEvent>, + } + impl Default for KeyEventBuilder { + fn default() -> Self { +- KeyEventBuilder { event_info: Mutex::new(None), pending: Default::default() } ++ KeyEventBuilder { ++ event_info: Mutex::new(None), ++ pending_high_surrogate: Mutex::new(None), ++ translated: Mutex::new(VecDeque::new()), ++ building: Mutex::new(None), ++ pending: Default::default(), ++ } + } + } + impl KeyEventBuilder { + /// Call this function for every window message. + /// Returns Some() if this window message completes a KeyEvent. + /// Returns None otherwise. ++ /// `ime_composing`: an input method's composition is open in the window (Rune). + pub(crate) fn process_message( + &self, + hwnd: HWND, + msg_kind: u32, + wparam: WPARAM, + lparam: LPARAM, ++ ime_composing: bool, + result: &mut ProcResult, + ) -> Vec<MessageAsKeyEvent> { + enum MatchResult { +@@ -98,6 +116,8 @@ impl KeyEventBuilder { + MatchResult::MessagesToDispatch(self.pending.complete_multi(key_events)) + }, + WM_KILLFOCUS => { ++ *self.pending_high_surrogate.lock().unwrap() = None; ++ self.translated.lock().unwrap().clear(); + // synthesize keyup events + let kbd_state = get_kbd_state(); + let key_events = Self::synthesize_kbd_state(ElementState::Released, &kbd_state); +@@ -109,6 +129,18 @@ impl KeyEventBuilder { + // This is handled in `event_loop.rs` + return MatchResult::Nothing; + } ++ // Rune: preserve an unpaired high surrogate across the two VK_PACKET presses ++ // that deliver a supplementary-plane Unicode character; drop it on any real key. ++ if wparam as VIRTUAL_KEY != VK_PACKET { ++ *self.pending_high_surrogate.lock().unwrap() = None; ++ } ++ // Rune: `TranslateMessage` has already posted this key's character, with this ++ // `lParam`; a program that posted the key-up too gets it after the key-up. ++ let noted = msg_kind == WM_KEYDOWN && wparam as VIRTUAL_KEY != VK_PACKET; ++ if noted { ++ note_key_down(&mut self.translated.lock().unwrap(), lparam, Instant::now()); ++ } ++ *self.building.lock().unwrap() = noted.then_some(lparam); + let pending_token = self.pending.add_pending(); + *result = ProcResult::Value(0); + +@@ -168,40 +200,40 @@ impl KeyEventBuilder { + WM_CHAR | WM_SYSCHAR => { + let mut event_info = self.event_info.lock().unwrap(); + if event_info.is_none() { +- trace!( +- "Received a CHAR message but no `event_info` was available. The \ +- message is probably IME, returning." +- ); +- return MatchResult::Nothing; ++ // Rune: a WM_CHAR with no preceding WM_KEYDOWN (text expanders, password ++ // managers, assistive tools, remote input) still carries text, as Chromium ++ // takes it. WM_SYSCHAR stays ignored so Alt+key mnemonics never type text. ++ drop(event_info); ++ if msg_kind == WM_SYSCHAR { ++ trace!("Received a SYSCHAR message with no `event_info`; ignoring."); ++ return MatchResult::Nothing; ++ } ++ let pending_token = self.pending.add_pending(); ++ *result = ProcResult::Value(0); ++ // Rune: a posted key's own character, after a key-up that came first, ++ // when that key already typed it: not text a second time. ++ if bare_char_is_copy(&mut self.translated.lock().unwrap(), wparam, lparam, Instant::now()) { ++ return MatchResult::TokenToRemove(pending_token); ++ } ++ let mut pending_high = self.pending_high_surrogate.lock().unwrap(); ++ let Some(text) = bare_char_text(&mut pending_high, wparam, ime_composing) ++ else { ++ return MatchResult::TokenToRemove(pending_token); ++ }; ++ let ev = standalone_char_event(text, (lparam & 0xffff) > 1); ++ return MatchResult::MessagesToDispatch(self.pending.complete_pending( ++ pending_token, ++ MessageAsKeyEvent { event: ev, is_synthetic: false }, ++ )); + } + let pending_token = self.pending.add_pending(); + *result = ProcResult::Value(0); +- let is_high_surrogate = (0xd800..=0xdbff).contains(&wparam); +- let is_low_surrogate = (0xdc00..=0xdfff).contains(&wparam); +- +- let is_utf16 = is_high_surrogate || is_low_surrogate; +- +- if is_utf16 { +- if let Some(ev_info) = event_info.as_mut() { +- ev_info.utf16parts.push(wparam as u16); +- } +- } else { +- // In this case, wparam holds a UTF-32 character. +- // Let's encode it as UTF-16 and append it to the end of `utf16parts` +- let utf16parts = match event_info.as_mut() { +- Some(ev_info) => &mut ev_info.utf16parts, +- None => { +- warn!("The event_info was None when it was expected to be some"); +- return MatchResult::TokenToRemove(pending_token); +- }, +- }; +- let start_offset = utf16parts.len(); +- let new_size = utf16parts.len() + 2; +- utf16parts.resize(new_size, 0); +- if let Some(ch) = char::from_u32(wparam as u32) { +- let encode_len = ch.encode_utf16(&mut utf16parts[start_offset..]).len(); +- let new_size = start_offset + encode_len; +- utf16parts.resize(new_size, 0); ++ if let Some(ev_info) = event_info.as_mut() { ++ if keyed_char_is_text(wparam, ev_info.vkey) { ++ append_wparam_utf16(wparam, &mut ev_info.utf16parts); ++ if let Some(down) = *self.building.lock().unwrap() { ++ note_keyed_text(&mut self.translated.lock().unwrap(), down, wparam); ++ } + } + } + // It's important that we unlock the mutex, and create the pending event token +@@ -224,6 +256,14 @@ impl KeyEventBuilder { + return MatchResult::TokenToRemove(pending_token); + }, + }; ++ let paired = resolve_surrogates( ++ &mut self.pending_high_surrogate.lock().unwrap(), ++ &mut event_info.utf16parts, ++ ); ++ if !paired && event_info.vkey == VK_PACKET { ++ // Rune: high half of a VK_PACKET surrogate pair; wait for the low half. ++ return MatchResult::TokenToRemove(pending_token); ++ } + let mut layouts = LAYOUT_CACHE.lock().unwrap(); + // It's okay to call `ToUnicode` here, because at this point the dead key + // is already consumed by the character. +@@ -238,10 +278,11 @@ impl KeyEventBuilder { + mod_state.contains(WindowsModifiers::CONTROL) + }; + +- // If Ctrl is not pressed, just use the text with all +- // modifiers because that already consumed the dead key. Otherwise, +- // we would interpret the character incorrectly, missing the dead key. +- if !ctrl_on { ++ // If Ctrl is not pressed (or this is VK_PACKET Unicode injection), just ++ // use the text with all modifiers because that already consumed the dead ++ // key. Otherwise, we would interpret the character incorrectly, missing ++ // the dead key. ++ if !ctrl_on || event_info.vkey == VK_PACKET { + event_info.text = PartialText::System(event_info.utf16parts.clone()); + } else { + let mod_no_ctrl = mod_state.remove_only_ctrl(); +@@ -510,7 +551,14 @@ impl PartialKeyEventInfo { + } else { + new_ex_scancode(lparam_struct.scancode, lparam_struct.extended) + }; +- let physical_key = scancode_to_physicalkey(scancode as u32); ++ // Rune: a VK_PACKET carries text, not a key: it is named as a bare WM_CHAR is ++ // (`standalone_char_event`), `Unidentified(NativeKeyCode::Unidentified)`, which Windows ++ // never reports for a real key (an unknown scan code is `NativeKeyCode::Windows(_)`). ++ let physical_key = if vkey == VK_PACKET { ++ PhysicalKey::Unidentified(NativeKeyCode::Unidentified) ++ } else { ++ scancode_to_physicalkey(scancode as u32) ++ }; + let location = get_location(scancode, layout.hkl as HKL); + + let kbd_state = get_kbd_state(); +@@ -541,9 +589,11 @@ impl PartialKeyEventInfo { + + let logical_key = if let Some(key) = code_as_key.clone() { + PartialLogicalKey::This(key) +- } else if is_pressed && key_is_char && !mods.contains(WindowsModifiers::CONTROL) { ++ } else if is_pressed ++ && (vkey == VK_PACKET || (key_is_char && !mods.contains(WindowsModifiers::CONTROL))) ++ { + // In some cases we want to use the UNICHAR text for logical_key in order to allow +- // dead keys to have an effect on the character reported by `logical_key`. ++ // dead keys (and Rune's VK_PACKET Unicode injection) to supply `logical_key`. + PartialLogicalKey::TextOr(preliminary_logical_key) + } else { + PartialLogicalKey::This(preliminary_logical_key) +@@ -612,7 +662,12 @@ impl PartialKeyEventInfo { + let logical_key = match self.logical_key { + PartialLogicalKey::TextOr(fallback) => match text.as_ref() { + Some(s) => { +- if s.grapheme_indices(true).count() > 1 { ++ // Rune: a VK_PACKET names its text as the key, unless the text is a control ++ // character: that keeps the `Unidentified` key it had before. ++ let packet = self.vkey == VK_PACKET; ++ if (packet && s.chars().any(char::is_control)) ++ || (!packet && s.grapheme_indices(true).count() > 1) ++ { + fallback + } else { + Key::Character(s.clone()) +@@ -638,6 +693,513 @@ impl PartialKeyEventInfo { + } + } + ++/// Rune: whether a `WM_CHAR` that follows a key-down is part of that key's text. `TranslateMessage` ++/// adds `WM_CHAR(0)` after a VK_PACKET key-down that carries no packet (one a program posted): it ++/// is not the packet's text. A real key's NUL (Ctrl+2, Ctrl+@) is that key's text, as before. ++fn keyed_char_is_text(wparam: WPARAM, vkey: VIRTUAL_KEY) -> bool { ++ !(wparam == 0 && vkey == VK_PACKET) ++} ++ ++/// Rune: a recent `WM_KEYDOWN` whose character `TranslateMessage` posted with the same `lParam`. ++/// A program that posts a key-down and its key-up together gets that character AFTER the key-up, ++/// with no key in progress. `typed` is the character the key's own event already took (from a ++/// `WM_CHAR` that program posted between the two), if any. ++#[derive(Clone, Copy, Debug, PartialEq)] ++struct Translated { ++ lparam: LPARAM, ++ typed: Option<WPARAM>, ++ at: Instant, ++} ++ ++/// How many key-downs are remembered, and for how long: a copy comes within a few messages. The ++/// count is far above any burst inside the second, so no typed key's entry is lost to it. ++const TRANSLATED_KEEP: usize = 256; ++const TRANSLATED_FOR: Duration = Duration::from_secs(1); ++ ++/// Rune: a `WM_KEYDOWN` with `lparam` happened at `now`. ++fn note_key_down(list: &mut VecDeque<Translated>, lparam: LPARAM, now: Instant) { ++ list.retain(|t| now.saturating_duration_since(t.at) < TRANSLATED_FOR); ++ list.push_back(Translated { lparam, typed: None, at: now }); ++ while list.len() > TRANSLATED_KEEP { ++ list.pop_front(); ++ } ++} ++ ++/// Rune: the event of the key-down with `down` took `wparam` as its text. A hardware key's own ++/// copy is that `WM_CHAR` (posted messages come before input), so nothing more follows it. ++fn note_keyed_text(list: &mut VecDeque<Translated>, down: LPARAM, wparam: WPARAM) { ++ if let Some(t) = list.iter_mut().rev().find(|t| t.lparam == down && t.typed.is_none()) { ++ t.typed = Some(wparam); ++ } ++} ++ ++/// Rune: whether a bare `WM_CHAR` is a remembered key-down's own copy of the character that key ++/// already typed (dropped), rather than text. A key-down that typed nothing yet claims a copy ++/// with its `lParam` first (oldest first): that copy is its character, and types once. Only then ++/// does a key-down that typed this same character claim it, and the copy is dropped. Any other ++/// `lParam` (programs that post text alone post 0 or 1), or an entry older than a second, matches ++/// nothing. Each entry is claimed once. ++fn bare_char_is_copy(list: &mut VecDeque<Translated>, wparam: WPARAM, lparam: LPARAM, now: Instant) -> bool { ++ list.retain(|t| now.saturating_duration_since(t.at) < TRANSLATED_FOR); ++ if let Some(i) = list.iter().position(|t| t.lparam == lparam && t.typed.is_none()) { ++ list.remove(i); ++ return false; ++ } ++ if let Some(i) = list.iter().position(|t| t.lparam == lparam && t.typed == Some(wparam)) { ++ list.remove(i); ++ return true; ++ } ++ false ++} ++ ++/// Rune: appends a `WM_CHAR` `wparam` (UTF-16 surrogate unit or Unicode scalar) onto ++/// `utf16parts`. ++fn append_wparam_utf16(wparam: WPARAM, utf16parts: &mut Vec<u16>) { ++ let is_high_surrogate = (0xd800..=0xdbff).contains(&wparam); ++ let is_low_surrogate = (0xdc00..=0xdfff).contains(&wparam); ++ if is_high_surrogate || is_low_surrogate { ++ utf16parts.push(wparam as u16); ++ } else if let Some(ch) = char::from_u32(wparam as u32) { ++ let mut buf = [0u16; 2]; ++ utf16parts.extend_from_slice(ch.encode_utf16(&mut buf)); ++ } ++} ++ ++/// Rune: pairs a pending high surrogate with an incoming leading low surrogate, and stashes a ++/// trailing lone high surrogate for the next `WM_CHAR`. Returns `false` when `units` held only ++/// that lone high surrogate so the caller waits for the low half instead of dropping it, and when ++/// `units` is empty (a VK_PACKET key-down whose only `WM_CHAR` was the NUL): nothing to type, and ++/// a waiting high half keeps waiting. ++fn resolve_surrogates(pending: &mut Option<u16>, units: &mut Vec<u16>) -> bool { ++ if units.is_empty() { ++ return false; ++ } ++ if units.first().copied().is_some_and(|u| (0xdc00..=0xdfff).contains(&u)) { ++ if let Some(hi) = pending.take() { ++ units.insert(0, hi); ++ } ++ } else { ++ *pending = None; ++ } ++ if units.last().copied().is_some_and(|u| (0xd800..=0xdbff).contains(&u)) { ++ *pending = units.pop(); ++ if units.is_empty() { ++ return false; ++ } ++ } ++ true ++} ++ ++/// Rune: the text a `WM_CHAR` with no preceding `WM_KEYDOWN` types, if any. A high surrogate ++/// waits in `pending` for its low half; a lone half is dropped, never inserted. Control ++/// characters (Backspace, Enter, Escape, DEL, …) are not text: they act only as keys. While an ++/// input method's composition is open its result arrives as `Ime::Commit`, so a stray `WM_CHAR` ++/// then would type the text twice: it is dropped. A NUL (the `WM_CHAR(0)` that `TranslateMessage` ++/// adds after a posted VK_PACKET key-down) changes nothing, not even a waiting high surrogate. ++fn bare_char_text(pending: &mut Option<u16>, wparam: WPARAM, ime_composing: bool) -> Option<String> { ++ if wparam == 0 { ++ return None; ++ } ++ if ime_composing { ++ *pending = None; ++ return None; ++ } ++ let mut units = Vec::with_capacity(2); ++ append_wparam_utf16(wparam, &mut units); ++ if !resolve_surrogates(pending, &mut units) { ++ return None; ++ } ++ let text = String::from_utf16(&units).ok()?; ++ (!text.is_empty() && !text.chars().any(char::is_control)).then_some(text) ++} ++ ++/// Rune: a pressed `KeyEvent` that types `text` and names no physical key. ++fn standalone_char_event(text: String, is_repeat: bool) -> KeyEvent { ++ let text = SmolStr::new(text); ++ KeyEvent { ++ physical_key: PhysicalKey::Unidentified(NativeKeyCode::Unidentified), ++ logical_key: Key::Character(text.clone()), ++ text: Some(text.clone()), ++ location: KeyLocation::Standard, ++ state: ElementState::Pressed, ++ repeat: is_repeat, ++ platform_specific: KeyEventExtra { ++ text_with_all_modifiers: Some(text), ++ key_without_modifiers: Key::Unidentified(NativeKey::Unidentified), ++ }, ++ } ++} ++ ++#[cfg(test)] ++mod rune_bare_char_tests { ++ use super::{bare_char_text, keyed_char_is_text, resolve_surrogates}; ++ use windows_sys::Win32::UI::Input::KeyboardAndMouse::{VK_2, VK_A, VK_PACKET}; ++ ++ const NONE: Option<String> = None; ++ ++ fn s(text: &str) -> Option<String> { ++ Some(text.to_owned()) ++ } ++ ++ /// Feeds `units` as consecutive bare `WM_CHAR`s and returns the text each one typed. ++ fn feed(units: &[usize], ime_composing: bool) -> Vec<Option<String>> { ++ let mut pending = None; ++ units.iter().map(|&u| bare_char_text(&mut pending, u, ime_composing)).collect() ++ } ++ ++ #[test] ++ fn bmp_characters_type_themselves() { ++ assert_eq!(feed(&[0x61, 0xe9, 0x65e5], false), [s("a"), s("é"), s("日")]); ++ } ++ ++ #[test] ++ fn a_surrogate_pair_split_over_two_messages_types_one_character() { ++ assert_eq!(feed(&[0xd83d, 0xde00], false), [NONE, s("😀")]); ++ } ++ ++ #[test] ++ fn a_lone_surrogate_half_is_dropped() { ++ // High half then a BMP character: the high half is dropped, the character types. ++ assert_eq!(feed(&[0xd83d, 0x61], false), [NONE, s("a")]); ++ // Low half with no high half before it. ++ assert_eq!(feed(&[0xde00], false), [NONE]); ++ // Two high halves: the first is dropped, the second pairs with the low half. ++ assert_eq!(feed(&[0xd83d, 0xd83d, 0xde00], false), [NONE, NONE, s("😀")]); ++ } ++ ++ #[test] ++ fn an_empty_packet_key_down_keeps_the_waiting_high_half() { ++ let mut pending = None; ++ // The high half's VK_PACKET key-down: it waits. ++ let mut high = vec![0xd83d]; ++ assert!(!resolve_surrogates(&mut pending, &mut high)); ++ assert_eq!(pending, Some(0xd83d)); ++ // The low half's VK_PACKET key-down completes with empty text (its only WM_CHAR was the ++ // NUL): nothing to type, and the high half keeps waiting. ++ let mut empty = Vec::new(); ++ assert!(!resolve_surrogates(&mut pending, &mut empty)); ++ assert_eq!(pending, Some(0xd83d)); ++ // The low half's character then arrives: one emoji. ++ assert_eq!(bare_char_text(&mut pending, 0xde00, false), s("😀")); ++ assert_eq!(pending, None); ++ } ++ ++ #[test] ++ fn only_a_packet_key_downs_nul_is_left_out_of_its_text() { ++ // The NUL `TranslateMessage` adds after a posted VK_PACKET key-down is not text. ++ assert!(!keyed_char_is_text(0, VK_PACKET)); ++ // The packet's real characters are. ++ assert!(keyed_char_is_text('a' as usize, VK_PACKET)); ++ assert!(keyed_char_is_text(0xd83d, VK_PACKET)); ++ // A real key's NUL (Ctrl+2) stays that key's text, as before. ++ assert!(keyed_char_is_text(0, VK_2)); ++ assert!(keyed_char_is_text(0, VK_A)); ++ } ++ ++ #[test] ++ fn a_nul_between_the_halves_neither_types_nor_breaks_the_pair() { ++ // `TranslateMessage` adds `WM_CHAR(0)` after a posted VK_PACKET key-down. ++ assert_eq!(feed(&[0xd83d, 0x00, 0xde00], false), [NONE, NONE, s("😀")]); ++ assert_eq!(feed(&[0x00, 0x61, 0x00], false), [NONE, s("a"), NONE]); ++ } ++ ++ #[test] ++ fn a_combining_mark_types_after_its_base() { ++ assert_eq!(feed(&[0x65, 0x301], false), [s("e"), s("\u{301}")]); ++ } ++ ++ #[test] ++ fn control_characters_are_not_text() { ++ for c in [0x08, 0x09, 0x0a, 0x0d, 0x1b, 0x7f, 0x00, 0x85] { ++ assert_eq!(feed(&[c], false), [NONE], "U+{c:04X}"); ++ } ++ } ++ ++ #[test] ++ fn nothing_types_while_an_ime_composition_is_open() { ++ assert_eq!(feed(&[0x61, 0xd83d, 0xde00], true), [NONE, NONE, NONE]); ++ // A high half that arrived before the composition opened does not pair after it. ++ let mut pending = None; ++ assert_eq!(bare_char_text(&mut pending, 0xd83d, false), None); ++ assert_eq!(bare_char_text(&mut pending, 0xde00, true), None); ++ assert_eq!(bare_char_text(&mut pending, 0xde00, false), None); ++ } ++} ++ ++#[cfg(test)] ++mod rune_posted_key_tests { ++ //! What a posted key's `TranslateMessage` copy does, for each order of key messages. Each test ++ //! replays the order through the same calls the key-down, keyed `WM_CHAR` and bare `WM_CHAR` ++ //! handlers make, and counts the characters that type. ++ use std::collections::VecDeque; ++ use std::time::{Duration, Instant}; ++ ++ use super::{bare_char_is_copy, note_key_down, note_keyed_text, Translated}; ++ ++ const H: usize = 'h' as usize; ++ const E: usize = 'e' as usize; ++ const L: usize = 'l' as usize; ++ // lParam: repeat count 1, scan code in bits 16-23 (as `TranslateMessage` copies it). ++ fn lp(scan: isize) -> isize { 1 | (scan << 16) } ++ ++ /// The text a sequence types: keyed chars type with their key; a bare char types unless it is ++ /// a copy of text its key already typed. ++ struct Replay { list: VecDeque<Translated>, now: Instant, typed: String } ++ impl Replay { ++ fn new() -> Self { Self { list: VecDeque::new(), now: Instant::now(), typed: String::new() } } ++ fn down(&mut self, lparam: isize) { note_key_down(&mut self.list, lparam, self.now); } ++ fn keyed(&mut self, down: isize, ch: usize) { note_keyed_text(&mut self.list, down, ch); self.typed.push(char::from_u32(ch as u32).unwrap()); } ++ fn bare(&mut self, ch: usize, lparam: isize) { ++ if !bare_char_is_copy(&mut self.list, ch, lparam, self.now) { self.typed.push(char::from_u32(ch as u32).unwrap()); } ++ } ++ fn wait(&mut self, d: Duration) { self.now += d; } ++ } ++ ++ #[test] ++ fn hardware_order_types_each_char_once() { ++ // down, its own char (posted before the key-up, which is input), up. ++ let mut r = Replay::new(); ++ for (ch, scan) in [(H, 0x23), (E, 0x12), (L, 0x26), (L, 0x26)] { r.down(lp(scan)); r.keyed(lp(scan), ch); } ++ assert_eq!(r.typed, "hell"); ++ } ++ ++ #[test] ++ fn down_and_up_back_to_back_type_the_late_copy_once() { ++ // The key's event takes no text (its key-up came first); its copy arrives bare. ++ let mut r = Replay::new(); ++ r.down(lp(0x23)); ++ r.bare(H, lp(0x23)); ++ assert_eq!(r.typed, "h"); ++ } ++ ++ #[test] ++ fn all_downs_then_all_ups_type_every_copy_once_in_order() { ++ let mut r = Replay::new(); ++ for scan in [0x23, 0x12, 0x26, 0x26] { r.down(lp(scan)); } ++ for (ch, scan) in [(H, 0x23), (E, 0x12), (L, 0x26), (L, 0x26)] { r.bare(ch, lp(scan)); } ++ assert_eq!(r.typed, "hell"); ++ } ++ ++ #[test] ++ fn down_char_up_does_not_type_the_copy_again() { ++ // A program posts key-down, WM_CHAR and key-up together: the explicit char types with the ++ // key; TranslateMessage's copy lands after the key-up (driver log, 02:58 run: `hhelloo`). ++ let mut r = Replay::new(); ++ for (ch, scan) in [(H, 0x23), (E, 0x12), (L, 0x26), (L, 0x26)] { r.down(lp(scan)); r.keyed(lp(scan), ch); } ++ for (ch, scan) in [(H, 0x23), (E, 0x12), (L, 0x26), (L, 0x26)] { r.bare(ch, lp(scan)); } ++ assert_eq!(r.typed, "hell"); ++ } ++ ++ #[test] ++ fn bare_text_from_a_program_types_as_before() { ++ // Programs that post text alone post lParam 0 or 1: never a remembered key-down's. ++ let mut r = Replay::new(); ++ r.down(lp(0x23)); ++ r.keyed(lp(0x23), H); ++ for ch in [E, L, L] { r.bare(ch, 1); } ++ r.bare(H, 0); ++ assert_eq!(r.typed, "hellh"); ++ } ++ ++ #[test] ++ fn with_nothing_remembered_every_bare_char_types() { ++ // VK_PACKET and bare paths: no key-down was remembered (VK_PACKET is never noted). ++ let mut r = Replay::new(); ++ r.bare(0xe9, 1); ++ r.bare(H, lp(0x23)); ++ assert_eq!(r.typed, "éh"); ++ } ++ ++ #[test] ++ fn a_held_key_s_repeats_type_one_char_each_and_nothing_is_dropped() { ++ // Auto-repeat: the same scan code, bit 30 (previous state) set, each repeat with its own char. ++ let rep = lp(0x26) | (1 << 30); ++ let mut r = Replay::new(); ++ r.down(lp(0x26)); ++ r.keyed(lp(0x26), L); ++ for _ in 0..5 { r.wait(Duration::from_millis(33)); r.down(rep); r.keyed(rep, L); } ++ assert_eq!(r.typed, "llllll"); ++ // A program's bare text afterwards still types. ++ r.bare(L, 1); ++ assert_eq!(r.typed, "lllllll"); ++ } ++ ++ #[test] ++ fn the_same_key_posted_twice_types_twice() { ++ // down, up, down, up, then the two copies: each copy belongs to one press. ++ let mut r = Replay::new(); ++ r.down(lp(0x26)); ++ r.down(lp(0x26)); ++ r.bare(L, lp(0x26)); ++ r.bare(L, lp(0x26)); ++ assert_eq!(r.typed, "ll"); ++ // And with explicit chars (down + char + up, twice): two l, no copies. ++ let mut r = Replay::new(); ++ r.down(lp(0x26)); r.keyed(lp(0x26), L); ++ r.down(lp(0x26)); r.keyed(lp(0x26), L); ++ r.bare(L, lp(0x26)); ++ r.bare(L, lp(0x26)); ++ assert_eq!(r.typed, "ll"); ++ } ++ ++ #[test] ++ fn a_stale_key_down_never_eats_later_text() { ++ // An entry older than a second matches nothing: later bare text with the same lParam types. ++ let mut r = Replay::new(); ++ r.down(lp(0x23)); ++ r.keyed(lp(0x23), H); ++ r.wait(Duration::from_millis(1001)); ++ r.bare(H, lp(0x23)); ++ assert_eq!(r.typed, "hh"); ++ // A different character with that lParam is not the copy either. ++ let mut r = Replay::new(); ++ r.down(lp(0x23)); ++ r.keyed(lp(0x23), H); ++ r.bare(E, lp(0x23)); ++ assert_eq!(r.typed, "he"); ++ } ++ ++ #[test] ++ fn a_real_key_s_entry_never_takes_a_later_posted_key_s_copy() { ++ // A real H (its char keyed), then a program's H down + up with the same lParam inside the ++ // second: the late copy belongs to the program's key, which typed nothing: it types. ++ let mut r = Replay::new(); ++ r.down(lp(0x23)); ++ r.keyed(lp(0x23), H); ++ r.wait(Duration::from_millis(200)); ++ r.down(lp(0x23)); ++ r.bare(H, lp(0x23)); ++ assert_eq!(r.typed, "hh"); ++ } ++ ++ #[test] ++ fn a_burst_of_forty_posted_letters_types_each_once() { ++ // down + char + up for forty letters, every copy after them: no typed entry is evicted. ++ let letters: Vec<(usize, isize)> = (0..40).map(|i| ('a' as usize + i % 26, 0x10 + (i % 26) as isize)).collect(); ++ let mut r = Replay::new(); ++ for &(ch, scan) in &letters { r.down(lp(scan)); r.keyed(lp(scan), ch); } ++ for &(ch, scan) in &letters { r.bare(ch, lp(scan)); } ++ let want: String = letters.iter().map(|&(ch, _)| char::from_u32(ch as u32).unwrap()).collect(); ++ assert_eq!(r.typed, want); ++ } ++ ++ #[test] ++ fn at_most_two_hundred_fifty_six_key_downs_are_remembered() { ++ let mut list = VecDeque::new(); ++ let now = Instant::now(); ++ for scan in 0..300 { note_key_down(&mut list, lp(scan), now); } ++ assert_eq!(list.len(), 256); ++ assert_eq!(list.front().map(|t| t.lparam), Some(lp(44)), "the oldest go first"); ++ } ++} ++ ++#[cfg(test)] ++mod rune_posted_key_handler_tests { ++ //! The same orders as real messages through `KeyEventBuilder::process_message`: posted to this ++ //! test thread's own queue, taken off it in order and handed to the handler with no window ++ //! (`hwnd` 0, so `next_kbd_msg` peeks this thread's queue as it peeks the window's). The test ++ //! posts `TranslateMessage`'s copy itself, where the driver log shows it: after the key-up, ++ //! with the key-down's `lParam`. ++ use std::mem::MaybeUninit; ++ ++ use windows_sys::Win32::System::Threading::GetCurrentThreadId; ++ use windows_sys::Win32::UI::Input::KeyboardAndMouse::VK_PACKET; ++ use windows_sys::Win32::UI::WindowsAndMessaging::{ ++ PeekMessageW, PostThreadMessageW, MSG, PM_NOREMOVE, PM_REMOVE, WM_CHAR, WM_KEYDOWN, ++ WM_KEYUP, WM_KILLFOCUS, ++ }; ++ ++ use super::KeyEventBuilder; ++ use crate::event::ElementState; ++ use crate::platform_impl::platform::event_loop::ProcResult; ++ ++ const VK_H: usize = 0x48; ++ const VK_E: usize = 0x45; ++ const H: usize = 'h' as usize; ++ const E: usize = 'e' as usize; ++ fn lp(scan: isize) -> isize { 1 | (scan << 16) } ++ fn up(scan: isize) -> isize { lp(scan) | (3 << 30) } ++ ++ /// Posts `messages` to this thread, then hands each to the handler in queue order; the text ++ /// of every pressed key event, in order. ++ fn feed(builder: &KeyEventBuilder, messages: &[(u32, usize, isize)]) -> String { ++ let mut msg = MaybeUninit::<MSG>::zeroed(); ++ // SAFETY: plain Win32 calls on this thread's own queue; `msg` is written before it is read. ++ unsafe { ++ PeekMessageW(msg.as_mut_ptr(), 0, 0, 0, PM_NOREMOVE); ++ let thread = GetCurrentThreadId(); ++ for &(kind, wparam, lparam) in messages { ++ assert_ne!(PostThreadMessageW(thread, kind, wparam, lparam), 0, "post {kind:#x}"); ++ } ++ let mut typed = String::new(); ++ while PeekMessageW(msg.as_mut_ptr(), 0, 0, 0, PM_REMOVE) != 0 { ++ let m = msg.assume_init_ref(); ++ let mut result = ProcResult::DefWindowProc(m.wParam); ++ for ev in builder.process_message(0, m.message, m.wParam, m.lParam, false, &mut result) { ++ if ev.event.state == ElementState::Pressed { ++ typed.push_str(ev.event.text.as_deref().unwrap_or("")); ++ } ++ } ++ } ++ typed ++ } ++ } ++ ++ #[test] ++ fn down_char_up_then_the_copy_types_once() { ++ let b = KeyEventBuilder::default(); ++ let typed = feed(&b, &[ ++ (WM_KEYDOWN, VK_H, lp(0x23)), (WM_CHAR, H, lp(0x23)), (WM_KEYUP, VK_H, up(0x23)), ++ (WM_KEYDOWN, VK_E, lp(0x12)), (WM_CHAR, E, lp(0x12)), (WM_KEYUP, VK_E, up(0x12)), ++ (WM_CHAR, H, lp(0x23)), (WM_CHAR, E, lp(0x12)), ++ ]); ++ assert_eq!(typed, "he", "the bare path consulted the list and dropped both copies"); ++ } ++ ++ #[test] ++ fn down_up_then_the_copy_types_once() { ++ let b = KeyEventBuilder::default(); ++ let typed = feed(&b, &[(WM_KEYDOWN, VK_H, lp(0x23)), (WM_KEYUP, VK_H, up(0x23)), (WM_CHAR, H, lp(0x23))]); ++ assert_eq!(typed, "h"); ++ } ++ ++ #[test] ++ fn a_real_key_then_a_posted_key_s_copy_types_twice() { ++ // Hardware order (the char comes before the key-up), then a program's down + up + copy. ++ let b = KeyEventBuilder::default(); ++ let typed = feed(&b, &[ ++ (WM_KEYDOWN, VK_H, lp(0x23)), (WM_CHAR, H, lp(0x23)), (WM_KEYUP, VK_H, up(0x23)), ++ (WM_KEYDOWN, VK_H, lp(0x23)), (WM_KEYUP, VK_H, up(0x23)), (WM_CHAR, H, lp(0x23)), ++ ]); ++ assert_eq!(typed, "hh"); ++ } ++ ++ #[test] ++ fn bare_text_from_a_program_types() { ++ let b = KeyEventBuilder::default(); ++ assert_eq!(feed(&b, &[(WM_CHAR, H, 1), (WM_CHAR, E, 0)]), "he"); ++ } ++ ++ #[test] ++ fn a_vk_packet_key_down_is_not_remembered() { ++ let b = KeyEventBuilder::default(); ++ let typed = feed(&b, &[(WM_KEYDOWN, VK_PACKET as usize, 1), (WM_CHAR, 0xe9, 1), (WM_KEYUP, VK_PACKET as usize, up(0))]); ++ assert_eq!(typed, "é"); ++ assert!(b.translated.lock().unwrap().is_empty()); ++ } ++ ++ #[test] ++ fn focus_loss_forgets_every_key_down() { ++ let b = KeyEventBuilder::default(); ++ feed(&b, &[(WM_KEYDOWN, VK_H, lp(0x23)), (WM_CHAR, H, lp(0x23)), (WM_KEYUP, VK_H, up(0x23))]); ++ assert_eq!(b.translated.lock().unwrap().len(), 1); ++ feed(&b, &[(WM_KILLFOCUS, 0, 0)]); ++ assert!(b.translated.lock().unwrap().is_empty()); ++ // So a copy arriving after focus came back types as text. ++ assert_eq!(feed(&b, &[(WM_CHAR, H, lp(0x23))]), "h"); ++ } ++} ++ + #[derive(Debug, Copy, Clone)] + struct KeyLParam { + pub scancode: u8, diff --git a/app/vendor/rune/vendor/winit/.cargo_vcs_info.json b/app/vendor/rune/vendor/winit/.cargo_vcs_info.json new file mode 100644 index 0000000..6a63283 --- /dev/null +++ b/app/vendor/rune/vendor/winit/.cargo_vcs_info.json @@ -0,0 +1,6 @@ +{ + "git": { + "sha1": "e9809ef54b18499bb4f2cac945719ecc2a61061b" + }, + "path_in_vcs": "" +} \ No newline at end of file diff --git a/app/vendor/rune/vendor/winit/Cargo.lock b/app/vendor/rune/vendor/winit/Cargo.lock new file mode 100644 index 0000000..fa62c18 --- /dev/null +++ b/app/vendor/rune/vendor/winit/Cargo.lock @@ -0,0 +1,2187 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "ab_glyph" +version = "0.2.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "79faae4620f45232f599d9bc7b290f88247a0834162c4495ab2f02d60004adfb" +dependencies = [ + "ab_glyph_rasterizer", + "owned_ttf_parser", +] + +[[package]] +name = "ab_glyph_rasterizer" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c71b1793ee61086797f5c80b6efa2b8ffa6d5dd703f118545808a7f2e27f7046" + +[[package]] +name = "adler" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f26201604c87b1e01bd3d98f8d5d9a8fcbb815e8cedb41ffccbeb4bf593a35fe" + +[[package]] +name = "ahash" +version = "0.8.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e89da841a80418a9b391ebaea17f5c112ffaaa96f621d2c285b5174da76b9011" +dependencies = [ + "cfg-if", + "getrandom", + "once_cell", + "version_check", + "zerocopy", +] + +[[package]] +name = "aho-corasick" +version = "1.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e60d3430d3a69478ad0993f19238d2df97c507009a52b3c10addcd7f6bcb916" +dependencies = [ + "memchr", +] + +[[package]] +name = "android-activity" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ef6978589202a00cd7e118380c448a08b6ed394c3a8df3a430d0898e3a42d046" +dependencies = [ + "android-properties", + "bitflags 2.6.0", + "cc", + "cesu8", + "jni", + "jni-sys", + "libc", + "log", + "ndk", + "ndk-context", + "ndk-sys", + "num_enum", + "thiserror", +] + +[[package]] +name = "android-properties" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc7eb209b1518d6bb87b283c20095f5228ecda460da70b44f0802523dea6da04" + +[[package]] +name = "arrayref" +version = "0.3.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9d151e35f61089500b617991b791fc8bfd237ae50cd5950803758a179b41e67a" + +[[package]] +name = "arrayvec" +version = "0.7.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "96d30a06541fbafbc7f82ed10c06164cfbd2c401138f6addd8404629c4b16711" + +[[package]] +name = "as-raw-xcb-connection" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "175571dd1d178ced59193a6fc02dde1b972eb0bc56c892cde9beeceac5bf0f6b" + +[[package]] +name = "atomic-waker" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" + +[[package]] +name = "autocfg" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c4b4d0bd25bd0b74681c0ad21497610ce1b7c91b1022cd21c80c6fbdd9476b0" + +[[package]] +name = "bitflags" +version = "1.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" + +[[package]] +name = "bitflags" +version = "2.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b048fb63fd8b5923fc5aa7b340d8e156aec7ec02f0c78fa8a6ddc2613f6f71de" + +[[package]] +name = "block2" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2c132eebf10f5cad5289222520a4a058514204aed6d791f1cf4fe8088b82d15f" +dependencies = [ + "objc2", +] + +[[package]] +name = "bumpalo" +version = "3.16.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "79296716171880943b8470b5f8d03aa55eb2e645a4874bdbb28adb49162e012c" + +[[package]] +name = "bytemuck" +version = "1.16.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b236fc92302c97ed75b38da1f4917b5cdda4984745740f153a5d3059e48d725e" + +[[package]] +name = "byteorder-lite" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f1fe948ff07f4bd06c30984e69f5b4899c516a3ef74f34df92a2df2ab535495" + +[[package]] +name = "bytes" +version = "1.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a12916984aab3fa6e39d655a33e09c0071eb36d6ab3aea5c2d78551f1df6d952" + +[[package]] +name = "calloop" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b99da2f8558ca23c71f4fd15dc57c906239752dd27ff3c00a1d56b685b7cbfec" +dependencies = [ + "bitflags 2.6.0", + "log", + "polling", + "rustix 0.38.44", + "slab", + "thiserror", +] + +[[package]] +name = "calloop-wayland-source" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "95a66a987056935f7efce4ab5668920b5d0dac4a7c99991a67395f13702ddd20" +dependencies = [ + "calloop", + "rustix 0.38.44", + "wayland-backend", + "wayland-client", +] + +[[package]] +name = "cc" +version = "1.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2aba8f4e9906c7ce3c73463f62a7f0c65183ada1a2d47e397cc8810827f9694f" +dependencies = [ + "jobserver", + "libc", +] + +[[package]] +name = "cesu8" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6d43a04d8753f35258c91f8ec639f792891f748a1edbd759cf1dcea3382ad83c" + +[[package]] +name = "cfg-if" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" + +[[package]] +name = "cfg_aliases" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "613afe47fcd5fac7ccf1db93babcb082c5994d996f20b8b159f2ad1658eb5724" + +[[package]] +name = "combine" +version = "4.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba5a308b75df32fe02788e748662718f03fde005016435c444eea572398219fd" +dependencies = [ + "bytes", + "memchr", +] + +[[package]] +name = "concurrent-queue" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ca0197aee26d1ae37445ee532fefce43251d24cc7c166799f4d46817f1d3973" +dependencies = [ + "crossbeam-utils", +] + +[[package]] +name = "console_error_panic_hook" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a06aeb73f470f66dcdbf7223caeebb85984942f22f1adb2a088cf9668146bbbc" +dependencies = [ + "cfg-if", + "wasm-bindgen", +] + +[[package]] +name = "core-foundation" +version = "0.9.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "91e195e091a93c46f7102ec7818a2aa394e1e1771c3ab4825963fa03e45afb8f" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "core-foundation" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b55271e5c8c478ad3f38ad24ef34923091e0548492a266d19b3c0b4d82574c63" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "core-foundation-sys" +version = "0.8.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" + +[[package]] +name = "core-graphics" +version = "0.23.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c07782be35f9e1140080c6b96f0d44b739e2278479f64e02fdab4e32dfd8b081" +dependencies = [ + "bitflags 1.3.2", + "core-foundation 0.9.4", + "core-graphics-types 0.1.3", + "foreign-types", + "libc", +] + +[[package]] +name = "core-graphics" +version = "0.24.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fa95a34622365fa5bbf40b20b75dba8dfa8c94c734aea8ac9a5ca38af14316f1" +dependencies = [ + "bitflags 2.6.0", + "core-foundation 0.10.0", + "core-graphics-types 0.2.0", + "foreign-types", + "libc", +] + +[[package]] +name = "core-graphics-types" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "45390e6114f68f718cc7a830514a96f903cccd70d02a8f6d9f643ac4ba45afaf" +dependencies = [ + "bitflags 1.3.2", + "core-foundation 0.9.4", + "libc", +] + +[[package]] +name = "core-graphics-types" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d44a101f213f6c4cdc1853d4b78aef6db6bdfa3468798cc1d9912f4735013eb" +dependencies = [ + "bitflags 2.6.0", + "core-foundation 0.10.0", + "libc", +] + +[[package]] +name = "core-text" +version = "20.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c9d2790b5c08465d49f8dc05c8bcae9fea467855947db39b0f8145c091aaced5" +dependencies = [ + "core-foundation 0.9.4", + "core-graphics 0.23.2", + "foreign-types", + "libc", +] + +[[package]] +name = "crc32fast" +version = "1.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a97769d94ddab943e4510d138150169a2758b5ef3eb191a9ee688de3e23ef7b3" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "crossbeam-utils" +version = "0.8.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "22ec99545bb0ed0ea7bb9b8e1e9122ea386ff8a48c0922e43f36d45ab09e0e80" + +[[package]] +name = "crossfont" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a650099c323679b4d6fb6858c2c512660ff5118f6b0ffb1bfc6cadcd54002b14" +dependencies = [ + "core-foundation 0.9.4", + "core-foundation-sys", + "core-graphics 0.23.2", + "core-text", + "dwrote", + "foreign-types", + "freetype-rs", + "libc", + "log", + "objc2", + "objc2-foundation", + "once_cell", + "pkg-config", + "winapi", + "yeslogic-fontconfig-sys", +] + +[[package]] +name = "cstr" +version = "0.2.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "68523903c8ae5aacfa32a0d9ae60cadeb764e1da14ee0d26b1f3089f13a54636" +dependencies = [ + "proc-macro2", + "quote", +] + +[[package]] +name = "ctor-lite" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1f791803201ab277ace03903de1594460708d2d54df6053f2d9e82f592b19e3b" + +[[package]] +name = "cty" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b365fabc795046672053e29c954733ec3b05e4be654ab130fe8f1f94d7051f35" + +[[package]] +name = "cursor-icon" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f27ae1dd37df86211c42e150270f82743308803d90a6f6e6651cd730d5e1732f" +dependencies = [ + "serde", +] + +[[package]] +name = "dispatch" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bd0c93bb4b0c6d9b77f4435b0ae98c24d17f1c45b2ff844c6151a07256ca923b" + +[[package]] +name = "dlib" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "330c60081dcc4c72131f8eb70510f1ac07223e5d4163db481a04a0befcffa412" +dependencies = [ + "libloading", +] + +[[package]] +name = "downcast-rs" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "75b325c5dbd37f80359721ad39aca5a29fb04c89279657cffdda8736d0c0b9d2" + +[[package]] +name = "dpi" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d8b14ccef22fc6f5a8f4d7d768562a182c04ce9a3b3157b91390b52ddfdf1a76" +dependencies = [ + "mint", + "serde", +] + +[[package]] +name = "dwrote" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "439a1c2ba5611ad3ed731280541d36d2e9c4ac5e7fb818a27b604bdc5a6aa65b" +dependencies = [ + "lazy_static", + "libc", + "serde", + "serde_derive", + "winapi", + "wio", +] + +[[package]] +name = "equivalent" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5443807d6dff69373d433ab9ef5378ad8df50ca6298caf15de6e52e24aaf54d5" + +[[package]] +name = "errno" +version = "0.3.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "976dd42dc7e85965fe702eb8164f21f450704bdde31faefd6471dba214cb594e" +dependencies = [ + "libc", + "windows-sys 0.59.0", +] + +[[package]] +name = "fastrand" +version = "2.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9fc0510504f03c51ada170672ac806f1f105a88aa97a5281117e1ddc3368e51a" + +[[package]] +name = "fdeflate" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4f9bfee30e4dedf0ab8b422f03af778d9612b63f502710fc500a334ebe2de645" +dependencies = [ + "simd-adler32", +] + +[[package]] +name = "flate2" +version = "1.0.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5f54427cfd1c7829e2a139fcefea601bf088ebca651d2bf53ebc600eac295dae" +dependencies = [ + "crc32fast", + "miniz_oxide", +] + +[[package]] +name = "foreign-types" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d737d9aa519fb7b749cbc3b962edcf310a8dd1f4b67c91c4f83975dbdd17d965" +dependencies = [ + "foreign-types-macros", + "foreign-types-shared", +] + +[[package]] +name = "foreign-types-macros" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1a5c6c585bc94aaf2c7b51dd4c2ba22680844aba4c687be581871a6f518c5742" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "foreign-types-shared" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aa9a19cbb55df58761df49b23516a86d432839add4af60fc256da840f66ed35b" + +[[package]] +name = "freetype-rs" +version = "0.36.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5442dee36ca09604133580dc0553780e867936bb3cbef3275859e889026d2b17" +dependencies = [ + "bitflags 2.6.0", + "freetype-sys", + "libc", +] + +[[package]] +name = "freetype-sys" +version = "0.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e7edc5b9669349acfda99533e9e0bcf26a51862ab43b08ee7745c55d28eb134" +dependencies = [ + "cc", + "libc", + "pkg-config", +] + +[[package]] +name = "gethostname" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0176e0459c2e4a1fe232f984bca6890e681076abb9934f6cea7c326f3fc47818" +dependencies = [ + "libc", + "windows-targets 0.48.5", +] + +[[package]] +name = "getrandom" +version = "0.2.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c4567c8db10ae91089c99af84c68c38da3ec2f087c3f82960bcdbf3656b6f4d7" +dependencies = [ + "cfg-if", + "libc", + "wasi", +] + +[[package]] +name = "hashbrown" +version = "0.14.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1" + +[[package]] +name = "hermit-abi" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fbf6a919d6cf397374f7dfeeea91d974c7c0a7221d0d0f4f20d859d329e53fcc" + +[[package]] +name = "image" +version = "0.25.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "99314c8a2152b8ddb211f924cdae532d8c5e4c8bb54728e12fff1b0cd5963a10" +dependencies = [ + "bytemuck", + "byteorder-lite", + "num-traits", + "png", +] + +[[package]] +name = "indexmap" +version = "2.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "168fb715dda47215e360912c096649d23d58bf392ac62f73919e831745e40f26" +dependencies = [ + "equivalent", + "hashbrown", +] + +[[package]] +name = "jni" +version = "0.21.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1a87aa2bb7d2af34197c04845522473242e1aa17c12f4935d5856491a7fb8c97" +dependencies = [ + "cesu8", + "cfg-if", + "combine", + "jni-sys", + "log", + "thiserror", + "walkdir", + "windows-sys 0.45.0", +] + +[[package]] +name = "jni-sys" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8eaf4bc02d17cbdd7ff4c7438cafcdf7fb9a4613313ad11b4f8fefe7d3fa0130" + +[[package]] +name = "jobserver" +version = "0.1.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "48d1dbcbbeb6a7fec7e059840aa538bd62aaccf972c7346c4d9d2059312853d0" +dependencies = [ + "libc", +] + +[[package]] +name = "js-sys" +version = "0.3.76" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6717b6b5b077764fb5966237269cb3c64edddde4b14ce42647430a78ced9e7b7" +dependencies = [ + "once_cell", + "wasm-bindgen", +] + +[[package]] +name = "lazy_static" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe" + +[[package]] +name = "libc" +version = "0.2.172" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d750af042f7ef4f724306de029d18836c26c1765a54a6a3f094cbd23a7267ffa" + +[[package]] +name = "libloading" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4979f22fdb869068da03c9f7528f8297c6fd2606bc3a4affe42e6a823fdb8da4" +dependencies = [ + "cfg-if", + "windows-targets 0.52.6", +] + +[[package]] +name = "libredox" +version = "0.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3af92c55d7d839293953fcd0fda5ecfe93297cfde6ffbdec13b41d99c0ba6607" +dependencies = [ + "bitflags 2.6.0", + "libc", + "redox_syscall 0.4.1", +] + +[[package]] +name = "linux-raw-sys" +version = "0.4.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78b3ae25bc7c8c38cec158d1f2757ee79e9b3740fbc7ccf0e59e4b08d793fa89" + +[[package]] +name = "linux-raw-sys" +version = "0.9.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd945864f07fe9f5371a27ad7b52a172b4b499999f1d97574c9fa68373937e12" + +[[package]] +name = "log" +version = "0.4.22" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7a70ba024b9dc04c27ea2f0c0548feb474ec5c54bba33a7f72f873a39d07b24" + +[[package]] +name = "matchers" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8263075bb86c5a1b1427b5ae862e8889656f126e9f77c484496e8b47cf5c5558" +dependencies = [ + "regex-automata 0.1.10", +] + +[[package]] +name = "memchr" +version = "2.7.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78ca9ab1a0babb1e7d5695e3530886289c18cf2f87ec19a575a0abdce112e3a3" + +[[package]] +name = "memmap2" +version = "0.9.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe751422e4a8caa417e13c3ea66452215d7d63e19e604f4980461212f3ae1322" +dependencies = [ + "libc", +] + +[[package]] +name = "miniz_oxide" +version = "0.7.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8a240ddb74feaf34a79a7add65a741f3167852fba007066dcac1ca548d89c08" +dependencies = [ + "adler", + "simd-adler32", +] + +[[package]] +name = "mint" +version = "0.5.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e53debba6bda7a793e5f99b8dacf19e626084f525f7829104ba9898f367d85ff" + +[[package]] +name = "ndk" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3f42e7bbe13d351b6bead8286a43aac9534b82bd3cc43e47037f012ebfd62d4" +dependencies = [ + "bitflags 2.6.0", + "jni-sys", + "log", + "ndk-sys", + "num_enum", + "raw-window-handle 0.4.3", + "raw-window-handle 0.5.2", + "raw-window-handle 0.6.2", + "thiserror", +] + +[[package]] +name = "ndk-context" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27b02d87554356db9e9a873add8782d4ea6e3e58ea071a9adb9a2e8ddb884a8b" + +[[package]] +name = "ndk-sys" +version = "0.6.0+11769913" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee6cda3051665f1fb8d9e08fc35c96d5a244fb1be711a03b71118828afc9a873" +dependencies = [ + "jni-sys", +] + +[[package]] +name = "nu-ansi-term" +version = "0.46.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77a8165726e8236064dbb45459242600304b42a5ea24ee2948e18e023bf7ba84" +dependencies = [ + "overload", + "winapi", +] + +[[package]] +name = "num-traits" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" +dependencies = [ + "autocfg", +] + +[[package]] +name = "num_enum" +version = "0.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "02339744ee7253741199f897151b38e72257d13802d4ee837285cc2990a90845" +dependencies = [ + "num_enum_derive", +] + +[[package]] +name = "num_enum_derive" +version = "0.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "681030a937600a36906c185595136d26abfebb4aa9c65701cefcaf8578bb982b" +dependencies = [ + "proc-macro-crate", + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "objc-sys" +version = "0.3.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cdb91bdd390c7ce1a8607f35f3ca7151b65afc0ff5ff3b34fa350f7d7c7e4310" + +[[package]] +name = "objc2" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "46a785d4eeff09c14c487497c162e92766fbb3e4059a71840cecc03d9a50b804" +dependencies = [ + "objc-sys", + "objc2-encode", +] + +[[package]] +name = "objc2-app-kit" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e4e89ad9e3d7d297152b17d39ed92cd50ca8063a89a9fa569046d41568891eff" +dependencies = [ + "bitflags 2.6.0", + "block2", + "libc", + "objc2", + "objc2-core-data", + "objc2-core-image", + "objc2-foundation", + "objc2-quartz-core", +] + +[[package]] +name = "objc2-cloud-kit" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "74dd3b56391c7a0596a295029734d3c1c5e7e510a4cb30245f8221ccea96b009" +dependencies = [ + "bitflags 2.6.0", + "block2", + "objc2", + "objc2-core-location", + "objc2-foundation", +] + +[[package]] +name = "objc2-contacts" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a5ff520e9c33812fd374d8deecef01d4a840e7b41862d849513de77e44aa4889" +dependencies = [ + "block2", + "objc2", + "objc2-foundation", +] + +[[package]] +name = "objc2-core-data" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "617fbf49e071c178c0b24c080767db52958f716d9eabdf0890523aeae54773ef" +dependencies = [ + "bitflags 2.6.0", + "block2", + "objc2", + "objc2-foundation", +] + +[[package]] +name = "objc2-core-image" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "55260963a527c99f1819c4f8e3b47fe04f9650694ef348ffd2227e8196d34c80" +dependencies = [ + "block2", + "objc2", + "objc2-foundation", + "objc2-metal", +] + +[[package]] +name = "objc2-core-location" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "000cfee34e683244f284252ee206a27953279d370e309649dc3ee317b37e5781" +dependencies = [ + "block2", + "objc2", + "objc2-contacts", + "objc2-foundation", +] + +[[package]] +name = "objc2-encode" +version = "4.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ef25abbcd74fb2609453eb695bd2f860d389e457f67dc17cafc8b8cbc89d0c33" + +[[package]] +name = "objc2-foundation" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ee638a5da3799329310ad4cfa62fbf045d5f56e3ef5ba4149e7452dcf89d5a8" +dependencies = [ + "bitflags 2.6.0", + "block2", + "dispatch", + "libc", + "objc2", +] + +[[package]] +name = "objc2-link-presentation" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a1a1ae721c5e35be65f01a03b6d2ac13a54cb4fa70d8a5da293d7b0020261398" +dependencies = [ + "block2", + "objc2", + "objc2-app-kit", + "objc2-foundation", +] + +[[package]] +name = "objc2-metal" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dd0cba1276f6023976a406a14ffa85e1fdd19df6b0f737b063b95f6c8c7aadd6" +dependencies = [ + "bitflags 2.6.0", + "block2", + "objc2", + "objc2-foundation", +] + +[[package]] +name = "objc2-quartz-core" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e42bee7bff906b14b167da2bac5efe6b6a07e6f7c0a21a7308d40c960242dc7a" +dependencies = [ + "bitflags 2.6.0", + "block2", + "objc2", + "objc2-foundation", + "objc2-metal", +] + +[[package]] +name = "objc2-symbols" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0a684efe3dec1b305badae1a28f6555f6ddd3bb2c2267896782858d5a78404dc" +dependencies = [ + "objc2", + "objc2-foundation", +] + +[[package]] +name = "objc2-ui-kit" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8bb46798b20cd6b91cbd113524c490f1686f4c4e8f49502431415f3512e2b6f" +dependencies = [ + "bitflags 2.6.0", + "block2", + "objc2", + "objc2-cloud-kit", + "objc2-core-data", + "objc2-core-image", + "objc2-core-location", + "objc2-foundation", + "objc2-link-presentation", + "objc2-quartz-core", + "objc2-symbols", + "objc2-uniform-type-identifiers", + "objc2-user-notifications", +] + +[[package]] +name = "objc2-uniform-type-identifiers" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "44fa5f9748dbfe1ca6c0b79ad20725a11eca7c2218bceb4b005cb1be26273bfe" +dependencies = [ + "block2", + "objc2", + "objc2-foundation", +] + +[[package]] +name = "objc2-user-notifications" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "76cfcbf642358e8689af64cee815d139339f3ed8ad05103ed5eaf73db8d84cb3" +dependencies = [ + "bitflags 2.6.0", + "block2", + "objc2", + "objc2-core-location", + "objc2-foundation", +] + +[[package]] +name = "once_cell" +version = "1.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3fdb12b2476b595f9358c5161aa467c2438859caa136dec86c26fdd2efe17b92" + +[[package]] +name = "orbclient" +version = "0.3.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52f0d54bde9774d3a51dcf281a5def240c71996bc6ca05d2c847ec8b2b216166" +dependencies = [ + "libredox", +] + +[[package]] +name = "overload" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b15813163c1d831bf4a13c3610c05c0d03b39feb07f7e09fa234dac9b15aaf39" + +[[package]] +name = "owned_ttf_parser" +version = "0.24.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "490d3a563d3122bf7c911a59b0add9389e5ec0f5f0c3ac6b91ff235a0e6a7f90" +dependencies = [ + "ttf-parser", +] + +[[package]] +name = "percent-encoding" +version = "2.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3148f5046208a5d56bcfc03053e3ca6334e51da8dfb19b6cdc8b306fae3283e" + +[[package]] +name = "pin-project" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6bf43b791c5b9e34c3d182969b4abb522f9343702850a2e57f460d00d09b4b3" +dependencies = [ + "pin-project-internal", +] + +[[package]] +name = "pin-project-internal" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f38a4412a78282e09a2cf38d195ea5420d15ba0602cb375210efbc877243965" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "pin-project-lite" +version = "0.2.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bda66fc9667c18cb2758a2ac84d1167245054bcf85d5d1aaa6923f45801bdd02" + +[[package]] +name = "pkg-config" +version = "0.3.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d231b230927b5e4ad203db57bbcbee2802f6bce620b1e4a9024a07d94e2907ec" + +[[package]] +name = "png" +version = "0.17.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06e4b0d3d1312775e782c86c91a111aa1f910cbb65e1337f9975b5f9a554b5e1" +dependencies = [ + "bitflags 1.3.2", + "crc32fast", + "fdeflate", + "flate2", + "miniz_oxide", +] + +[[package]] +name = "polling" +version = "3.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a3ed00ed3fbf728b5816498ecd316d1716eecaced9c0c8d2c5a6740ca214985b" +dependencies = [ + "cfg-if", + "concurrent-queue", + "hermit-abi", + "pin-project-lite", + "rustix 0.38.44", + "tracing", + "windows-sys 0.52.0", +] + +[[package]] +name = "proc-macro-crate" +version = "3.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6d37c51ca738a55da99dc0c4a34860fd675453b8b36209178c2249bb13651284" +dependencies = [ + "toml_edit", +] + +[[package]] +name = "proc-macro2" +version = "1.0.101" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "89ae43fd86e4158d6db51ad8e2b80f313af9cc74f5c0e03ccb87de09998732de" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quick-xml" +version = "0.37.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "331e97a1af0bf59823e6eadffe373d7b27f485be8748f71471c662c1f269b7fb" +dependencies = [ + "memchr", +] + +[[package]] +name = "quote" +version = "1.0.36" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0fa76aaf39101c457836aec0ce2316dbdc3ab723cdda1c6bd4e6ad4208acaca7" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "raw-window-handle" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b800beb9b6e7d2df1fe337c9e3d04e3af22a124460fb4c30fcc22c9117cefb41" +dependencies = [ + "cty", +] + +[[package]] +name = "raw-window-handle" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2ff9a1f06a88b01621b7ae906ef0211290d1c8a168a15542486a8f61c0833b9" + +[[package]] +name = "raw-window-handle" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20675572f6f24e9e76ef639bc5552774ed45f1c30e2951e1e99c59888861c539" + +[[package]] +name = "redox_syscall" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4722d768eff46b75989dd134e5c353f0d6296e5aaa3132e776cbdb56be7731aa" +dependencies = [ + "bitflags 1.3.2", +] + +[[package]] +name = "redox_syscall" +version = "0.5.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "03a862b389f93e68874fbf580b9de08dd02facb9a788ebadaf4a3fd33cf58834" +dependencies = [ + "bitflags 2.6.0", +] + +[[package]] +name = "regex" +version = "1.10.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b91213439dad192326a0d7c6ee3955910425f441d7038e0d6933b0aec5c4517f" +dependencies = [ + "aho-corasick", + "memchr", + "regex-automata 0.4.7", + "regex-syntax 0.8.4", +] + +[[package]] +name = "regex-automata" +version = "0.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c230d73fb8d8c1b9c0b3135c5142a8acee3a0558fb8db5cf1cb65f8d7862132" +dependencies = [ + "regex-syntax 0.6.29", +] + +[[package]] +name = "regex-automata" +version = "0.4.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38caf58cc5ef2fed281f89292ef23f6365465ed9a41b7a7754eb4e26496c92df" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax 0.8.4", +] + +[[package]] +name = "regex-syntax" +version = "0.6.29" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f162c6dd7b008981e4d40210aca20b4bd0f9b60ca9271061b07f78537722f2e1" + +[[package]] +name = "regex-syntax" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7a66a03ae7c801facd77a29370b4faec201768915ac14a721ba36f20bc9c209b" + +[[package]] +name = "rustix" +version = "0.38.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fdb5bc1ae2baa591800df16c9ca78619bf65c0488b41b96ccec5d11220d8c154" +dependencies = [ + "bitflags 2.6.0", + "errno", + "libc", + "linux-raw-sys 0.4.14", + "windows-sys 0.59.0", +] + +[[package]] +name = "rustix" +version = "1.0.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "11181fbabf243db407ef8df94a6ce0b2f9a733bd8be4ad02b4eda9602296cac8" +dependencies = [ + "bitflags 2.6.0", + "errno", + "libc", + "linux-raw-sys 0.9.4", + "windows-sys 0.59.0", +] + +[[package]] +name = "same-file" +version = "1.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502" +dependencies = [ + "winapi-util", +] + +[[package]] +name = "scoped-tls" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e1cf6437eb19a8f4a6cc0f7dca544973b0b78843adbfeb3683d1a94a0024a294" + +[[package]] +name = "sctk-adwaita" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6277f0217056f77f1d8f49f2950ac6c278c0d607c45f5ee99328d792ede24ec" +dependencies = [ + "ab_glyph", + "crossfont", + "log", + "memmap2", + "smithay-client-toolkit", + "tiny-skia", +] + +[[package]] +name = "serde" +version = "1.0.228" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a8e94ea7f378bd32cbbd37198a4a91436180c5bb472411e48b5ec2e2124ae9e" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.228" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41d385c7d4ca58e59fc732af25c3983b67ac852c1a25000afe1175de458b67ad" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.228" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "sharded-slab" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f40ca3c46823713e0d4209592e8d6e826aa57e928f09752619fc696c499637f6" +dependencies = [ + "lazy_static", +] + +[[package]] +name = "simd-adler32" +version = "0.3.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d66dc143e6b11c1eddc06d5c423cfc97062865baf299914ab64caa38182078fe" + +[[package]] +name = "slab" +version = "0.4.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f92a496fb766b417c996b9c5e57daf2f7ad3b0bebe1ccfca4856390e3d3bb67" +dependencies = [ + "autocfg", +] + +[[package]] +name = "smallvec" +version = "1.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c5e1a9a646d36c3599cd173a41282daf47c44583ad367b8e6837255952e5c67" + +[[package]] +name = "smithay-client-toolkit" +version = "0.19.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3457dea1f0eb631b4034d61d4d8c32074caa6cd1ab2d59f2327bd8461e2c0016" +dependencies = [ + "bitflags 2.6.0", + "calloop", + "calloop-wayland-source", + "cursor-icon", + "libc", + "log", + "memmap2", + "rustix 0.38.44", + "thiserror", + "wayland-backend", + "wayland-client", + "wayland-csd-frame", + "wayland-cursor", + "wayland-protocols", + "wayland-protocols-wlr", + "wayland-scanner", + "xkeysym", +] + +[[package]] +name = "smol_str" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dd538fb6910ac1099850255cf94a94df6551fbdd602454387d0adb2d1ca6dead" +dependencies = [ + "serde", +] + +[[package]] +name = "softbuffer" +version = "0.4.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "18051cdd562e792cad055119e0cdb2cfc137e44e3987532e0f9659a77931bb08" +dependencies = [ + "as-raw-xcb-connection", + "bytemuck", + "cfg_aliases", + "core-graphics 0.24.0", + "fastrand", + "foreign-types", + "js-sys", + "log", + "memmap2", + "objc2", + "objc2-foundation", + "objc2-quartz-core", + "raw-window-handle 0.6.2", + "redox_syscall 0.5.8", + "rustix 0.38.44", + "tiny-xlib", + "wasm-bindgen", + "wayland-backend", + "wayland-client", + "wayland-sys", + "web-sys", + "windows-sys 0.59.0", + "x11rb", +] + +[[package]] +name = "strict-num" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6637bab7722d379c8b41ba849228d680cc12d0a45ba1fa2b48f2a30577a06731" + +[[package]] +name = "syn" +version = "2.0.106" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ede7c438028d4436d71104916910f5bb611972c5cfd7f89b8300a8186e6fada6" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "thiserror" +version = "1.0.63" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c0342370b38b6a11b6cc11d6a805569958d54cfa061a29969c3b5ce2ea405724" +dependencies = [ + "thiserror-impl", +] + +[[package]] +name = "thiserror-impl" +version = "1.0.63" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4558b58466b9ad7ca0f102865eccc95938dca1a74a856f2b57b6629050da261" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "thread_local" +version = "1.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b9ef9bad013ada3808854ceac7b46812a6465ba368859a37e2100283d2d719c" +dependencies = [ + "cfg-if", + "once_cell", +] + +[[package]] +name = "tiny-skia" +version = "0.11.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "83d13394d44dae3207b52a326c0c85a8bf87f1541f23b0d143811088497b09ab" +dependencies = [ + "arrayref", + "arrayvec", + "bytemuck", + "cfg-if", + "log", + "tiny-skia-path", +] + +[[package]] +name = "tiny-skia-path" +version = "0.11.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9c9e7fc0c2e86a30b117d0462aa261b72b7a99b7ebd7deb3a14ceda95c5bdc93" +dependencies = [ + "arrayref", + "bytemuck", + "strict-num", +] + +[[package]] +name = "tiny-xlib" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d52f22673960ad13af14ff4025997312def1223bfa7c8e4949d099e6b3d5d1c" +dependencies = [ + "as-raw-xcb-connection", + "ctor-lite", + "libloading", + "pkg-config", + "tracing", +] + +[[package]] +name = "toml_datetime" +version = "0.6.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4badfd56924ae69bcc9039335b2e017639ce3f9b001c393c1b2d1ef846ce2cbf" + +[[package]] +name = "toml_edit" +version = "0.21.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6a8534fd7f78b5405e860340ad6575217ce99f38d4d5c8f2442cb5ecb50090e1" +dependencies = [ + "indexmap", + "toml_datetime", + "winnow", +] + +[[package]] +name = "tracing" +version = "0.1.40" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3523ab5a71916ccf420eebdf5521fcef02141234bbc0b8a49f2fdc4544364ef" +dependencies = [ + "log", + "pin-project-lite", + "tracing-core", +] + +[[package]] +name = "tracing-core" +version = "0.1.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c06d3da6113f116aaee68e4d601191614c9053067f9ab7f6edbcb161237daa54" +dependencies = [ + "once_cell", + "valuable", +] + +[[package]] +name = "tracing-log" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee855f1f400bd0e5c02d150ae5de3840039a3f54b025156404e34c23c03f47c3" +dependencies = [ + "log", + "once_cell", + "tracing-core", +] + +[[package]] +name = "tracing-subscriber" +version = "0.3.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ad0f048c97dbd9faa9b7df56362b8ebcaa52adb06b498c050d2f4e32f90a7a8b" +dependencies = [ + "matchers", + "nu-ansi-term", + "once_cell", + "regex", + "sharded-slab", + "smallvec", + "thread_local", + "tracing", + "tracing-core", + "tracing-log", +] + +[[package]] +name = "tracing-web" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9e6a141feebd51f8d91ebfd785af50fca223c570b86852166caa3b141defe7c" +dependencies = [ + "js-sys", + "tracing-core", + "tracing-subscriber", + "wasm-bindgen", + "web-sys", +] + +[[package]] +name = "ttf-parser" +version = "0.24.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8686b91785aff82828ed725225925b33b4fde44c4bb15876e5f7c832724c420a" + +[[package]] +name = "unicode-ident" +version = "1.0.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3354b9ac3fae1ff6755cb6db53683adb661634f67557942dea4facebec0fee4b" + +[[package]] +name = "unicode-segmentation" +version = "1.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d4c87d22b6e3f4a18d4d40ef354e97c90fcb14dd91d7dc0aa9d8a1172ebf7202" + +[[package]] +name = "valuable" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "830b7e5d4d90034032940e4ace0d9a9a057e7a45cd94e6c007832e39edb82f6d" + +[[package]] +name = "version_check" +version = "0.9.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "49874b5167b65d7193b8aba1567f5c7d93d001cafc34600cee003eda787e483f" + +[[package]] +name = "walkdir" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29790946404f91d9c5d06f9874efddea1dc06c5efe94541a7d6863108e3a5e4b" +dependencies = [ + "same-file", + "winapi-util", +] + +[[package]] +name = "wasi" +version = "0.11.0+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423" + +[[package]] +name = "wasm-bindgen" +version = "0.2.99" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a474f6281d1d70c17ae7aa6a613c87fce69a127e2624002df63dcb39d6cf6396" +dependencies = [ + "cfg-if", + "once_cell", + "wasm-bindgen-macro", +] + +[[package]] +name = "wasm-bindgen-backend" +version = "0.2.99" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5f89bb38646b4f81674e8f5c3fb81b562be1fd936d84320f3264486418519c79" +dependencies = [ + "bumpalo", + "log", + "proc-macro2", + "quote", + "syn", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-futures" +version = "0.4.49" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38176d9b44ea84e9184eff0bc34cc167ed044f816accfe5922e54d84cf48eca2" +dependencies = [ + "cfg-if", + "js-sys", + "once_cell", + "wasm-bindgen", + "web-sys", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.99" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2cc6181fd9a7492eef6fef1f33961e3695e4579b9872a6f7c83aee556666d4fe" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.99" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "30d7a95b763d3c45903ed6c81f156801839e5ee968bb07e534c44df0fcd330c2" +dependencies = [ + "proc-macro2", + "quote", + "syn", + "wasm-bindgen-backend", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.99" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "943aab3fdaaa029a6e0271b35ea10b72b943135afe9bffca82384098ad0e06a6" + +[[package]] +name = "wayland-backend" +version = "0.3.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "673a33c33048a5ade91a6b139580fa174e19fb0d23f396dca9fa15f2e1e49b35" +dependencies = [ + "cc", + "downcast-rs", + "rustix 1.0.8", + "scoped-tls", + "smallvec", + "wayland-sys", +] + +[[package]] +name = "wayland-client" +version = "0.31.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c66a47e840dc20793f2264eb4b3e4ecb4b75d91c0dd4af04b456128e0bdd449d" +dependencies = [ + "bitflags 2.6.0", + "rustix 1.0.8", + "wayland-backend", + "wayland-scanner", +] + +[[package]] +name = "wayland-csd-frame" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "625c5029dbd43d25e6aa9615e88b829a5cad13b2819c4ae129fdbb7c31ab4c7e" +dependencies = [ + "bitflags 2.6.0", + "cursor-icon", + "wayland-backend", +] + +[[package]] +name = "wayland-cursor" +version = "0.31.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ef9489a8df197ebf3a8ce8a7a7f0a2320035c3743f3c1bd0bdbccf07ce64f95" +dependencies = [ + "rustix 0.38.44", + "wayland-client", + "xcursor", +] + +[[package]] +name = "wayland-protocols" +version = "0.32.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "efa790ed75fbfd71283bd2521a1cfdc022aabcc28bdcff00851f9e4ae88d9901" +dependencies = [ + "bitflags 2.6.0", + "wayland-backend", + "wayland-client", + "wayland-scanner", +] + +[[package]] +name = "wayland-protocols-plasma" +version = "0.3.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4fd38cdad69b56ace413c6bcc1fbf5acc5e2ef4af9d5f8f1f9570c0c83eae175" +dependencies = [ + "bitflags 2.6.0", + "wayland-backend", + "wayland-client", + "wayland-protocols", + "wayland-scanner", +] + +[[package]] +name = "wayland-protocols-wlr" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd993de54a40a40fbe5601d9f1fbcaef0aebcc5fda447d7dc8f6dcbaae4f8953" +dependencies = [ + "bitflags 2.6.0", + "wayland-backend", + "wayland-client", + "wayland-protocols", + "wayland-scanner", +] + +[[package]] +name = "wayland-scanner" +version = "0.31.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "54cb1e9dc49da91950bdfd8b848c49330536d9d1fb03d4bfec8cae50caa50ae3" +dependencies = [ + "proc-macro2", + "quick-xml", + "quote", +] + +[[package]] +name = "wayland-sys" +version = "0.31.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "34949b42822155826b41db8e5d0c1be3a2bd296c747577a43a3e6daefc296142" +dependencies = [ + "dlib", + "log", + "once_cell", + "pkg-config", +] + +[[package]] +name = "web-sys" +version = "0.3.76" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "04dd7223427d52553d3702c004d3b2fe07c148165faa56313cb00211e31c12bc" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "web-time" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a6580f308b1fad9207618087a65c04e7a10bc77e02c8e84e9b00dd4b12fa0bb" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "winapi" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" +dependencies = [ + "winapi-i686-pc-windows-gnu", + "winapi-x86_64-pc-windows-gnu", +] + +[[package]] +name = "winapi-i686-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" + +[[package]] +name = "winapi-util" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4d4cc384e1e73b93bafa6fb4f1df8c41695c8a91cf9c4c64358067d15a7b6c6b" +dependencies = [ + "windows-sys 0.52.0", +] + +[[package]] +name = "winapi-x86_64-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" + +[[package]] +name = "windows-sys" +version = "0.45.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "75283be5efb2831d37ea142365f009c02ec203cd29a3ebecbc093d52315b66d0" +dependencies = [ + "windows-targets 0.42.2", +] + +[[package]] +name = "windows-sys" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" +dependencies = [ + "windows-targets 0.52.6", +] + +[[package]] +name = "windows-sys" +version = "0.59.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b" +dependencies = [ + "windows-targets 0.52.6", +] + +[[package]] +name = "windows-targets" +version = "0.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e5180c00cd44c9b1c88adb3693291f1cd93605ded80c250a75d472756b4d071" +dependencies = [ + "windows_aarch64_gnullvm 0.42.2", + "windows_aarch64_msvc 0.42.2", + "windows_i686_gnu 0.42.2", + "windows_i686_msvc 0.42.2", + "windows_x86_64_gnu 0.42.2", + "windows_x86_64_gnullvm 0.42.2", + "windows_x86_64_msvc 0.42.2", +] + +[[package]] +name = "windows-targets" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a2fa6e2155d7247be68c096456083145c183cbbbc2764150dda45a87197940c" +dependencies = [ + "windows_aarch64_gnullvm 0.48.5", + "windows_aarch64_msvc 0.48.5", + "windows_i686_gnu 0.48.5", + "windows_i686_msvc 0.48.5", + "windows_x86_64_gnu 0.48.5", + "windows_x86_64_gnullvm 0.48.5", + "windows_x86_64_msvc 0.48.5", +] + +[[package]] +name = "windows-targets" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" +dependencies = [ + "windows_aarch64_gnullvm 0.52.6", + "windows_aarch64_msvc 0.52.6", + "windows_i686_gnu 0.52.6", + "windows_i686_gnullvm", + "windows_i686_msvc 0.52.6", + "windows_x86_64_gnu 0.52.6", + "windows_x86_64_gnullvm 0.52.6", + "windows_x86_64_msvc 0.52.6", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "597a5118570b68bc08d8d59125332c54f1ba9d9adeedeef5b99b02ba2b0698f8" + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b38e32f0abccf9987a4e3079dfb67dcd799fb61361e53e2882c3cbaf0d905d8" + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e08e8864a60f06ef0d0ff4ba04124db8b0fb3be5776a5cd47641e942e58c4d43" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc35310971f3b2dbbf3f0690a219f40e2d9afcf64f9ab7cc1be722937c26b4bc" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" + +[[package]] +name = "windows_i686_gnu" +version = "0.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c61d927d8da41da96a81f029489353e68739737d3beca43145c8afec9a31a84f" + +[[package]] +name = "windows_i686_gnu" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a75915e7def60c94dcef72200b9a8e58e5091744960da64ec734a6c6e9b3743e" + +[[package]] +name = "windows_i686_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" + +[[package]] +name = "windows_i686_msvc" +version = "0.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "44d840b6ec649f480a41c8d80f9c65108b92d89345dd94027bfe06ac444d1060" + +[[package]] +name = "windows_i686_msvc" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f55c233f70c4b27f66c523580f78f1004e8b5a8b659e05a4eb49d4166cca406" + +[[package]] +name = "windows_i686_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8de912b8b8feb55c064867cf047dda097f92d51efad5b491dfb98f6bbb70cb36" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53d40abd2583d23e4718fddf1ebec84dbff8381c07cae67ff7768bbf19c6718e" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "26d41b46a36d453748aedef1486d5c7a85db22e56aff34643984ea85514e94a3" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b7b52767868a23d5bab768e390dc5f5c55825b6d30b86c844ff2dc7414044cc" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9aec5da331524158c6d1a4ac0ab1541149c0b9505fde06423b02f5ef0106b9f0" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed94fce61571a4006852b7389a063ab983c02eb1bb37b47f8272ce92d06d9538" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" + +[[package]] +name = "winit" +version = "0.30.13" +dependencies = [ + "ahash", + "android-activity", + "atomic-waker", + "bitflags 2.6.0", + "block2", + "bytemuck", + "calloop", + "cfg_aliases", + "concurrent-queue", + "console_error_panic_hook", + "core-foundation 0.9.4", + "core-graphics 0.23.2", + "cursor-icon", + "dpi", + "image", + "js-sys", + "libc", + "memmap2", + "ndk", + "objc2", + "objc2-app-kit", + "objc2-foundation", + "objc2-ui-kit", + "orbclient", + "percent-encoding", + "pin-project", + "raw-window-handle 0.4.3", + "raw-window-handle 0.5.2", + "raw-window-handle 0.6.2", + "redox_syscall 0.4.1", + "rustix 0.38.44", + "sctk-adwaita", + "serde", + "smithay-client-toolkit", + "smol_str", + "softbuffer", + "tracing", + "tracing-subscriber", + "tracing-web", + "unicode-segmentation", + "wasm-bindgen", + "wasm-bindgen-futures", + "wayland-backend", + "wayland-client", + "wayland-protocols", + "wayland-protocols-plasma", + "web-sys", + "web-time", + "windows-sys 0.52.0", + "x11-dl", + "x11rb", + "xkbcommon-dl", +] + +[[package]] +name = "winnow" +version = "0.5.40" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f593a95398737aeed53e489c785df13f3618e41dbcd6718c6addbf1395aa6876" +dependencies = [ + "memchr", +] + +[[package]] +name = "wio" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d129932f4644ac2396cb456385cbf9e63b5b30c6e8dc4820bdca4eb082037a5" +dependencies = [ + "winapi", +] + +[[package]] +name = "x11-dl" +version = "2.21.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38735924fedd5314a6e548792904ed8c6de6636285cb9fec04d5b1db85c1516f" +dependencies = [ + "libc", + "once_cell", + "pkg-config", +] + +[[package]] +name = "x11rb" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d91ffca73ee7f68ce055750bf9f6eca0780b8c85eff9bc046a3b0da41755e12" +dependencies = [ + "as-raw-xcb-connection", + "gethostname", + "libc", + "libloading", + "once_cell", + "rustix 0.38.44", + "x11rb-protocol", +] + +[[package]] +name = "x11rb-protocol" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec107c4503ea0b4a98ef47356329af139c0a4f7750e621cf2973cd3385ebcb3d" + +[[package]] +name = "xcursor" +version = "0.3.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d491ee231a51ae64a5b762114c3ac2104b967aadba1de45c86ca42cf051513b7" + +[[package]] +name = "xkbcommon-dl" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d039de8032a9a8856a6be89cea3e5d12fdd82306ab7c94d74e6deab2460651c5" +dependencies = [ + "bitflags 2.6.0", + "dlib", + "log", + "once_cell", + "xkeysym", +] + +[[package]] +name = "xkeysym" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9cc00251562a284751c9973bace760d86c0276c471b4be569fe6b068ee97a56" + +[[package]] +name = "yeslogic-fontconfig-sys" +version = "5.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ffb6b23999a8b1a997bf47c7bb4d19ad4029c3327bb3386ebe0a5ff584b33c7a" +dependencies = [ + "cstr", + "dlib", + "once_cell", + "pkg-config", +] + +[[package]] +name = "zerocopy" +version = "0.7.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1b9b4fd18abc82b8136838da5d50bae7bdea537c574d8dc1a34ed098d6c166f0" +dependencies = [ + "zerocopy-derive", +] + +[[package]] +name = "zerocopy-derive" +version = "0.7.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fa4f8080344d4671fb4e831a13ad1e68092748387dfc4f55e356242fae12ce3e" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] diff --git a/app/vendor/rune/vendor/winit/Cargo.toml b/app/vendor/rune/vendor/winit/Cargo.toml new file mode 100644 index 0000000..4bfded8 --- /dev/null +++ b/app/vendor/rune/vendor/winit/Cargo.toml @@ -0,0 +1,553 @@ +# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO +# +# When uploading crates to the registry Cargo will automatically +# "normalize" Cargo.toml files for maximal compatibility +# with all versions of Cargo and also rewrite `path` dependencies +# to registry (e.g., crates.io) dependencies. +# +# If you are reading this file be aware that the original Cargo.toml +# will likely look very different (and much more reasonable). +# See Cargo.toml.orig for the original contents. + +[package] +edition = "2021" +rust-version = "1.70.0" +name = "winit" +version = "0.30.13" +authors = [ + "The winit contributors", + "Pierre Krieger <pierre.krieger1708@gmail.com>", +] +build = "build.rs" +include = [ + "/build.rs", + "/docs", + "/examples", + "/FEATURES.md", + "/LICENSE", + "/src", + "!/src/platform_impl/web/script", + "/src/platform_impl/web/script/**/*.min.js", + "/tests", +] +autolib = false +autobins = false +autoexamples = false +autotests = false +autobenches = false +description = "Cross-platform window creation library." +documentation = "https://docs.rs/winit" +readme = "README.md" +keywords = ["windowing"] +categories = ["gui"] +license = "Apache-2.0" +repository = "https://github.com/rust-windowing/winit" + +[package.metadata.docs.rs] +features = [ + "rwh_04", + "rwh_05", + "rwh_06", + "serde", + "mint", + "android-native-activity", +] +targets = [ + "i686-pc-windows-msvc", + "x86_64-pc-windows-msvc", + "x86_64-apple-darwin", + "i686-unknown-linux-gnu", + "x86_64-unknown-linux-gnu", + "x86_64-apple-ios", + "aarch64-linux-android", + "wasm32-unknown-unknown", +] +rustdoc-args = [ + "--cfg", + "docsrs", +] + +[features] +android-game-activity = ["android-activity/game-activity"] +android-native-activity = ["android-activity/native-activity"] +default = [ + "rwh_06", + "x11", + "wayland", + "wayland-dlopen", + "wayland-csd-adwaita", +] +mint = ["dpi/mint"] +rwh_04 = [ + "dep:rwh_04", + "ndk/rwh_04", +] +rwh_05 = [ + "dep:rwh_05", + "ndk/rwh_05", +] +rwh_06 = [ + "dep:rwh_06", + "ndk/rwh_06", +] +serde = [ + "dep:serde", + "cursor-icon/serde", + "smol_str/serde", + "dpi/serde", +] +wayland = [ + "wayland-client", + "wayland-backend", + "wayland-protocols", + "wayland-protocols-plasma", + "sctk", + "ahash", + "memmap2", +] +wayland-csd-adwaita = [ + "sctk-adwaita", + "sctk-adwaita/ab_glyph", +] +wayland-csd-adwaita-crossfont = [ + "sctk-adwaita", + "sctk-adwaita/crossfont", +] +wayland-csd-adwaita-notitle = ["sctk-adwaita"] +wayland-dlopen = ["wayland-backend/dlopen"] +x11 = [ + "x11-dl", + "bytemuck", + "percent-encoding", + "xkbcommon-dl/x11", + "x11rb", +] + +[lib] +name = "winit" +path = "src/lib.rs" + +[[example]] +name = "child_window" +path = "examples/child_window.rs" + +[[example]] +name = "control_flow" +path = "examples/control_flow.rs" + +[[example]] +name = "pump_events" +path = "examples/pump_events.rs" + +[[example]] +name = "run_on_demand" +path = "examples/run_on_demand.rs" + +[[example]] +name = "window" +path = "examples/window.rs" +doc-scrape-examples = true + +[[example]] +name = "x11_embed" +path = "examples/x11_embed.rs" + +[[test]] +name = "send_objects" +path = "tests/send_objects.rs" + +[[test]] +name = "serde_objects" +path = "tests/serde_objects.rs" + +[[test]] +name = "sync_object" +path = "tests/sync_object.rs" + +[dependencies.bitflags] +version = "2" + +[dependencies.cursor-icon] +version = "1.1.0" + +[dependencies.dpi] +version = "0.1.1" + +[dependencies.rwh_04] +version = "0.4" +optional = true +package = "raw-window-handle" + +[dependencies.rwh_05] +version = "0.5.2" +features = ["std"] +optional = true +package = "raw-window-handle" + +[dependencies.rwh_06] +version = "0.6" +features = ["std"] +optional = true +package = "raw-window-handle" + +[dependencies.serde] +version = "1" +features = ["serde_derive"] +optional = true + +[dependencies.smol_str] +version = "0.2.0" + +[dependencies.tracing] +version = "0.1.40" +default-features = false + +[dev-dependencies.image] +version = "0.25.0" +features = ["png"] +default-features = false + +[dev-dependencies.tracing] +version = "0.1.40" +features = ["log"] +default-features = false + +[dev-dependencies.tracing-subscriber] +version = "0.3.18" +features = ["env-filter"] + +[build-dependencies.cfg_aliases] +version = "0.2.1" + +[target.'cfg(all(target_family = "wasm", target_feature = "atomics"))'.dependencies.atomic-waker] +version = "1" + +[target.'cfg(all(target_family = "wasm", target_feature = "atomics"))'.dependencies.concurrent-queue] +version = "2" +default-features = false + +[target.'cfg(all(unix, not(any(target_os = "redox", target_family = "wasm", target_os = "android", target_os = "ios", target_os = "macos"))))'.dependencies.ahash] +version = "0.8.7" +features = ["no-rng"] +optional = true + +[target.'cfg(all(unix, not(any(target_os = "redox", target_family = "wasm", target_os = "android", target_os = "ios", target_os = "macos"))))'.dependencies.bytemuck] +version = "1.13.1" +optional = true +default-features = false + +[target.'cfg(all(unix, not(any(target_os = "redox", target_family = "wasm", target_os = "android", target_os = "ios", target_os = "macos"))))'.dependencies.calloop] +version = "0.13.0" + +[target.'cfg(all(unix, not(any(target_os = "redox", target_family = "wasm", target_os = "android", target_os = "ios", target_os = "macos"))))'.dependencies.libc] +version = "0.2.64" + +[target.'cfg(all(unix, not(any(target_os = "redox", target_family = "wasm", target_os = "android", target_os = "ios", target_os = "macos"))))'.dependencies.memmap2] +version = "0.9.0" +optional = true + +[target.'cfg(all(unix, not(any(target_os = "redox", target_family = "wasm", target_os = "android", target_os = "ios", target_os = "macos"))))'.dependencies.percent-encoding] +version = "2.0" +optional = true + +[target.'cfg(all(unix, not(any(target_os = "redox", target_family = "wasm", target_os = "android", target_os = "ios", target_os = "macos"))))'.dependencies.rustix] +version = "0.38.4" +features = [ + "std", + "system", + "thread", + "process", +] +default-features = false + +[target.'cfg(all(unix, not(any(target_os = "redox", target_family = "wasm", target_os = "android", target_os = "ios", target_os = "macos"))))'.dependencies.sctk] +version = "0.19.2" +features = ["calloop"] +optional = true +default-features = false +package = "smithay-client-toolkit" + +[target.'cfg(all(unix, not(any(target_os = "redox", target_family = "wasm", target_os = "android", target_os = "ios", target_os = "macos"))))'.dependencies.sctk-adwaita] +version = "0.10.1" +optional = true +default-features = false + +[target.'cfg(all(unix, not(any(target_os = "redox", target_family = "wasm", target_os = "android", target_os = "ios", target_os = "macos"))))'.dependencies.wayland-backend] +version = "0.3.10" +features = ["client_system"] +optional = true +default-features = false + +[target.'cfg(all(unix, not(any(target_os = "redox", target_family = "wasm", target_os = "android", target_os = "ios", target_os = "macos"))))'.dependencies.wayland-client] +version = "0.31.10" +optional = true + +[target.'cfg(all(unix, not(any(target_os = "redox", target_family = "wasm", target_os = "android", target_os = "ios", target_os = "macos"))))'.dependencies.wayland-protocols] +version = "0.32.8" +features = ["staging"] +optional = true + +[target.'cfg(all(unix, not(any(target_os = "redox", target_family = "wasm", target_os = "android", target_os = "ios", target_os = "macos"))))'.dependencies.wayland-protocols-plasma] +version = "0.3.8" +features = ["client"] +optional = true + +[target.'cfg(all(unix, not(any(target_os = "redox", target_family = "wasm", target_os = "android", target_os = "ios", target_os = "macos"))))'.dependencies.x11-dl] +version = "2.19.1" +optional = true + +[target.'cfg(all(unix, not(any(target_os = "redox", target_family = "wasm", target_os = "android", target_os = "ios", target_os = "macos"))))'.dependencies.x11rb] +version = "0.13.0" +features = [ + "allow-unsafe-code", + "dl-libxcb", + "randr", + "resource_manager", + "xinput", + "xkb", +] +optional = true +default-features = false + +[target.'cfg(all(unix, not(any(target_os = "redox", target_family = "wasm", target_os = "android", target_os = "ios", target_os = "macos"))))'.dependencies.xkbcommon-dl] +version = "0.4.2" + +[target.'cfg(any(target_os = "ios", target_os = "macos"))'.dependencies.block2] +version = "0.5.1" + +[target.'cfg(any(target_os = "ios", target_os = "macos"))'.dependencies.core-foundation] +version = "0.9.3" + +[target.'cfg(any(target_os = "ios", target_os = "macos"))'.dependencies.objc2] +version = "0.5.2" +features = ["relax-sign-encoding"] + +[target.'cfg(not(any(target_os = "android", target_os = "ios")))'.dev-dependencies.softbuffer] +version = "0.4.0" +features = [ + "x11", + "x11-dlopen", + "wayland", + "wayland-dlopen", +] +default-features = false + +[target.'cfg(target_family = "wasm")'.dependencies.js-sys] +version = "0.3.70" + +[target.'cfg(target_family = "wasm")'.dependencies.pin-project] +version = "1" + +[target.'cfg(target_family = "wasm")'.dependencies.wasm-bindgen] +version = "0.2.93" + +[target.'cfg(target_family = "wasm")'.dependencies.wasm-bindgen-futures] +version = "0.4.43" + +[target.'cfg(target_family = "wasm")'.dependencies.web-time] +version = "1" + +[target.'cfg(target_family = "wasm")'.dependencies.web_sys] +version = "0.3.70" +features = [ + "AbortController", + "AbortSignal", + "Blob", + "BlobPropertyBag", + "console", + "CssStyleDeclaration", + "Document", + "DomException", + "DomRect", + "DomRectReadOnly", + "Element", + "Event", + "EventTarget", + "FocusEvent", + "HtmlCanvasElement", + "HtmlElement", + "HtmlImageElement", + "ImageBitmap", + "ImageBitmapOptions", + "ImageBitmapRenderingContext", + "ImageData", + "IntersectionObserver", + "IntersectionObserverEntry", + "KeyboardEvent", + "MediaQueryList", + "MessageChannel", + "MessagePort", + "Navigator", + "Node", + "OrientationLockType", + "OrientationType", + "PageTransitionEvent", + "Permissions", + "PermissionState", + "PermissionStatus", + "PointerEvent", + "PremultiplyAlpha", + "ResizeObserver", + "ResizeObserverBoxOptions", + "ResizeObserverEntry", + "ResizeObserverOptions", + "ResizeObserverSize", + "Screen", + "ScreenOrientation", + "Url", + "VisibilityState", + "WheelEvent", + "Window", + "Worker", +] +package = "web-sys" + +[target.'cfg(target_family = "wasm")'.dev-dependencies.console_error_panic_hook] +version = "0.1" + +[target.'cfg(target_family = "wasm")'.dev-dependencies.tracing-web] +version = "0.1" + +[target.'cfg(target_os = "android")'.dependencies.android-activity] +version = "0.6.0" + +[target.'cfg(target_os = "android")'.dependencies.ndk] +version = "0.9.0" +default-features = false + +[target.'cfg(target_os = "ios")'.dependencies.objc2-foundation] +version = "0.2.2" +features = [ + "block2", + "dispatch", + "NSArray", + "NSEnumerator", + "NSGeometry", + "NSObjCRuntime", + "NSOperation", + "NSString", + "NSProcessInfo", + "NSThread", + "NSSet", +] + +[target.'cfg(target_os = "ios")'.dependencies.objc2-ui-kit] +version = "0.2.2" +features = [ + "UIApplication", + "UIDevice", + "UIEvent", + "UIGeometry", + "UIGestureRecognizer", + "UITextInput", + "UITextInputTraits", + "UIOrientation", + "UIPanGestureRecognizer", + "UIPinchGestureRecognizer", + "UIResponder", + "UIRotationGestureRecognizer", + "UIScreen", + "UIScreenMode", + "UITapGestureRecognizer", + "UITouch", + "UITraitCollection", + "UIView", + "UIViewController", + "UIWindow", +] + +[target.'cfg(target_os = "macos")'.dependencies.core-graphics] +version = "0.23.1" + +[target.'cfg(target_os = "macos")'.dependencies.objc2-app-kit] +version = "0.2.2" +features = [ + "NSAppearance", + "NSApplication", + "NSBitmapImageRep", + "NSButton", + "NSColor", + "NSControl", + "NSCursor", + "NSDragging", + "NSEvent", + "NSGraphics", + "NSGraphicsContext", + "NSImage", + "NSImageRep", + "NSMenu", + "NSMenuItem", + "NSOpenGLView", + "NSPasteboard", + "NSResponder", + "NSRunningApplication", + "NSScreen", + "NSTextInputClient", + "NSTextInputContext", + "NSView", + "NSWindow", + "NSWindowScripting", + "NSWindowTabGroup", +] + +[target.'cfg(target_os = "macos")'.dependencies.objc2-foundation] +version = "0.2.2" +features = [ + "block2", + "dispatch", + "NSArray", + "NSAttributedString", + "NSData", + "NSDictionary", + "NSDistributedNotificationCenter", + "NSEnumerator", + "NSKeyValueObserving", + "NSNotification", + "NSObjCRuntime", + "NSPathUtilities", + "NSProcessInfo", + "NSRunLoop", + "NSString", + "NSThread", + "NSValue", +] + +[target.'cfg(target_os = "redox")'.dependencies.orbclient] +version = "0.3.47" +default-features = false + +[target.'cfg(target_os = "redox")'.dependencies.redox_syscall] +version = "0.4.1" + +[target.'cfg(target_os = "windows")'.dependencies.unicode-segmentation] +version = "1.7.1" + +[target.'cfg(target_os = "windows")'.dependencies.windows-sys] +version = "0.52.0" +features = [ + "Win32_Devices_HumanInterfaceDevice", + "Win32_Foundation", + "Win32_Globalization", + "Win32_Graphics_Dwm", + "Win32_Graphics_Gdi", + "Win32_Media", + "Win32_System_Com_StructuredStorage", + "Win32_System_Com", + "Win32_System_LibraryLoader", + "Win32_System_Ole", + "Win32_Security", + "Win32_System_SystemInformation", + "Win32_System_SystemServices", + "Win32_System_Threading", + "Win32_System_WindowsProgramming", + "Win32_UI_Accessibility", + "Win32_UI_Controls", + "Win32_UI_HiDpi", + "Win32_UI_Input_Ime", + "Win32_UI_Input_KeyboardAndMouse", + "Win32_UI_Input_Pointer", + "Win32_UI_Input_Touch", + "Win32_UI_Shell", + "Win32_UI_TextServices", + "Win32_UI_WindowsAndMessaging", +] diff --git a/app/vendor/rune/vendor/winit/Cargo.toml.orig b/app/vendor/rune/vendor/winit/Cargo.toml.orig new file mode 100644 index 0000000..71f7c58 --- /dev/null +++ b/app/vendor/rune/vendor/winit/Cargo.toml.orig @@ -0,0 +1,378 @@ +[package] +name = "winit" +version = "0.30.13" +authors = [ + "The winit contributors", + "Pierre Krieger <pierre.krieger1708@gmail.com>", +] +description = "Cross-platform window creation library." +keywords = ["windowing"] +readme = "README.md" +documentation = "https://docs.rs/winit" +categories = ["gui"] +rust-version.workspace = true +repository.workspace = true +license.workspace = true +edition.workspace = true +include = [ + "/build.rs", + "/docs", + "/examples", + "/FEATURES.md", + "/LICENSE", + "/src", + "!/src/platform_impl/web/script", + "/src/platform_impl/web/script/**/*.min.js", + "/tests", +] + +[package.metadata.docs.rs] +features = [ + "rwh_04", + "rwh_05", + "rwh_06", + "serde", + "mint", + # Enabled to get docs to compile + "android-native-activity", +] +# These are all tested in CI +targets = [ + # Windows + "i686-pc-windows-msvc", + "x86_64-pc-windows-msvc", + # macOS + "x86_64-apple-darwin", + # Unix (X11 & Wayland) + "i686-unknown-linux-gnu", + "x86_64-unknown-linux-gnu", + # iOS + "x86_64-apple-ios", + # Android + "aarch64-linux-android", + # Web + "wasm32-unknown-unknown", +] +rustdoc-args = ["--cfg", "docsrs"] + +# Features are documented in either `lib.rs` or under `winit::platform`. +[features] +default = ["rwh_06", "x11", "wayland", "wayland-dlopen", "wayland-csd-adwaita"] +x11 = ["x11-dl", "bytemuck", "percent-encoding", "xkbcommon-dl/x11", "x11rb"] +wayland = [ + "wayland-client", + "wayland-backend", + "wayland-protocols", + "wayland-protocols-plasma", + "sctk", + "ahash", + "memmap2", +] +wayland-dlopen = ["wayland-backend/dlopen"] +wayland-csd-adwaita = ["sctk-adwaita", "sctk-adwaita/ab_glyph"] +wayland-csd-adwaita-crossfont = ["sctk-adwaita", "sctk-adwaita/crossfont"] +wayland-csd-adwaita-notitle = ["sctk-adwaita"] +android-native-activity = ["android-activity/native-activity"] +android-game-activity = ["android-activity/game-activity"] +serde = ["dep:serde", "cursor-icon/serde", "smol_str/serde", "dpi/serde"] +mint = ["dpi/mint"] +rwh_04 = ["dep:rwh_04", "ndk/rwh_04"] +rwh_05 = ["dep:rwh_05", "ndk/rwh_05"] +rwh_06 = ["dep:rwh_06", "ndk/rwh_06"] + +[build-dependencies] +cfg_aliases = "0.2.1" + +[dependencies] +bitflags = "2" +cursor-icon = "1.1.0" +dpi = { version = "0.1.1", path = "dpi" } +rwh_04 = { package = "raw-window-handle", version = "0.4", optional = true } +rwh_05 = { package = "raw-window-handle", version = "0.5.2", features = [ + "std", +], optional = true } +rwh_06 = { package = "raw-window-handle", version = "0.6", features = [ + "std", +], optional = true } +serde = { workspace = true, optional = true } +smol_str = "0.2.0" +tracing = { version = "0.1.40", default-features = false } + +[dev-dependencies] +image = { version = "0.25.0", default-features = false, features = ["png"] } +tracing = { version = "0.1.40", default-features = false, features = ["log"] } +tracing-subscriber = { version = "0.3.18", features = ["env-filter"] } +winit = { path = ".", features = ["rwh_05"] } + +[target.'cfg(not(any(target_os = "android", target_os = "ios")))'.dev-dependencies] +softbuffer = { version = "0.4.0", default-features = false, features = [ + "x11", + "x11-dlopen", + "wayland", + "wayland-dlopen", +] } + +[target.'cfg(target_os = "android")'.dependencies] +android-activity = "0.6.0" +ndk = { version = "0.9.0", default-features = false } + +[target.'cfg(any(target_os = "ios", target_os = "macos"))'.dependencies] +block2 = "0.5.1" +core-foundation = "0.9.3" +objc2 = { version = "0.5.2", features = ["relax-sign-encoding"] } + +[target.'cfg(target_os = "macos")'.dependencies] +core-graphics = "0.23.1" + +[target.'cfg(target_os = "macos")'.dependencies.objc2-foundation] +version = "0.2.2" +features = [ + "block2", + "dispatch", + "NSArray", + "NSAttributedString", + "NSData", + "NSDictionary", + "NSDistributedNotificationCenter", + "NSEnumerator", + "NSKeyValueObserving", + "NSNotification", + "NSObjCRuntime", + "NSPathUtilities", + "NSProcessInfo", + "NSRunLoop", + "NSString", + "NSThread", + "NSValue", +] + +[target.'cfg(target_os = "macos")'.dependencies.objc2-app-kit] +version = "0.2.2" +features = [ + "NSAppearance", + "NSApplication", + "NSBitmapImageRep", + "NSButton", + "NSColor", + "NSControl", + "NSCursor", + "NSDragging", + "NSEvent", + "NSGraphics", + "NSGraphicsContext", + "NSImage", + "NSImageRep", + "NSMenu", + "NSMenuItem", + "NSOpenGLView", + "NSPasteboard", + "NSResponder", + "NSRunningApplication", + "NSScreen", + "NSTextInputClient", + "NSTextInputContext", + "NSView", + "NSWindow", + "NSWindowScripting", + "NSWindowTabGroup", +] + +[target.'cfg(target_os = "ios")'.dependencies.objc2-foundation] +version = "0.2.2" +features = [ + "block2", + "dispatch", + "NSArray", + "NSEnumerator", + "NSGeometry", + "NSObjCRuntime", + "NSOperation", + "NSString", + "NSProcessInfo", + "NSThread", + "NSSet", +] + +[target.'cfg(target_os = "ios")'.dependencies.objc2-ui-kit] +version = "0.2.2" +features = [ + "UIApplication", + "UIDevice", + "UIEvent", + "UIGeometry", + "UIGestureRecognizer", + "UITextInput", + "UITextInputTraits", + "UIOrientation", + "UIPanGestureRecognizer", + "UIPinchGestureRecognizer", + "UIResponder", + "UIRotationGestureRecognizer", + "UIScreen", + "UIScreenMode", + "UITapGestureRecognizer", + "UITouch", + "UITraitCollection", + "UIView", + "UIViewController", + "UIWindow", +] + +[target.'cfg(target_os = "windows")'.dependencies] +unicode-segmentation = "1.7.1" + +[target.'cfg(target_os = "windows")'.dependencies.windows-sys] +version = "0.52.0" +features = [ + "Win32_Devices_HumanInterfaceDevice", + "Win32_Foundation", + "Win32_Globalization", + "Win32_Graphics_Dwm", + "Win32_Graphics_Gdi", + "Win32_Media", + "Win32_System_Com_StructuredStorage", + "Win32_System_Com", + "Win32_System_LibraryLoader", + "Win32_System_Ole", + "Win32_Security", + "Win32_System_SystemInformation", + "Win32_System_SystemServices", + "Win32_System_Threading", + "Win32_System_WindowsProgramming", + "Win32_UI_Accessibility", + "Win32_UI_Controls", + "Win32_UI_HiDpi", + "Win32_UI_Input_Ime", + "Win32_UI_Input_KeyboardAndMouse", + "Win32_UI_Input_Pointer", + "Win32_UI_Input_Touch", + "Win32_UI_Shell", + "Win32_UI_TextServices", + "Win32_UI_WindowsAndMessaging", +] + +[target.'cfg(all(unix, not(any(target_os = "redox", target_family = "wasm", target_os = "android", target_os = "ios", target_os = "macos"))))'.dependencies] +ahash = { version = "0.8.7", features = ["no-rng"], optional = true } +bytemuck = { version = "1.13.1", default-features = false, optional = true } +calloop = "0.13.0" +libc = "0.2.64" +memmap2 = { version = "0.9.0", optional = true } +percent-encoding = { version = "2.0", optional = true } +rustix = { version = "0.38.4", default-features = false, features = [ + "std", + "system", + "thread", + "process", +] } +sctk = { package = "smithay-client-toolkit", version = "0.19.2", default-features = false, features = [ + "calloop", +], optional = true } +sctk-adwaita = { version = "0.10.1", default-features = false, optional = true } +wayland-backend = { version = "0.3.10", default-features = false, features = [ + "client_system", +], optional = true } +wayland-client = { version = "0.31.10", optional = true } +wayland-protocols = { version = "0.32.8", features = [ + "staging", +], optional = true } +wayland-protocols-plasma = { version = "0.3.8", features = [ + "client", +], optional = true } +x11-dl = { version = "2.19.1", optional = true } +x11rb = { version = "0.13.0", default-features = false, features = [ + "allow-unsafe-code", + "dl-libxcb", + "randr", + "resource_manager", + "xinput", + "xkb", +], optional = true } +xkbcommon-dl = "0.4.2" + +[target.'cfg(target_os = "redox")'.dependencies] +orbclient = { version = "0.3.47", default-features = false } +redox_syscall = "0.4.1" + +[target.'cfg(target_family = "wasm")'.dependencies] +js-sys = "0.3.70" +pin-project = "1" +wasm-bindgen = "0.2.93" +wasm-bindgen-futures = "0.4.43" +web-time = "1" +web_sys = { package = "web-sys", version = "0.3.70", features = [ + "AbortController", + "AbortSignal", + "Blob", + "BlobPropertyBag", + "console", + "CssStyleDeclaration", + "Document", + "DomException", + "DomRect", + "DomRectReadOnly", + "Element", + "Event", + "EventTarget", + "FocusEvent", + "HtmlCanvasElement", + "HtmlElement", + "HtmlImageElement", + "ImageBitmap", + "ImageBitmapOptions", + "ImageBitmapRenderingContext", + "ImageData", + "IntersectionObserver", + "IntersectionObserverEntry", + "KeyboardEvent", + "MediaQueryList", + "MessageChannel", + "MessagePort", + "Navigator", + "Node", + "OrientationLockType", + "OrientationType", + "PageTransitionEvent", + "Permissions", + "PermissionState", + "PermissionStatus", + "PointerEvent", + "PremultiplyAlpha", + "ResizeObserver", + "ResizeObserverBoxOptions", + "ResizeObserverEntry", + "ResizeObserverOptions", + "ResizeObserverSize", + "Screen", + "ScreenOrientation", + "Url", + "VisibilityState", + "WheelEvent", + "Window", + "Worker", +] } + +[target.'cfg(all(target_family = "wasm", target_feature = "atomics"))'.dependencies] +atomic-waker = "1" +concurrent-queue = { version = "2", default-features = false } + +[target.'cfg(target_family = "wasm")'.dev-dependencies] +console_error_panic_hook = "0.1" +tracing-web = "0.1" + +[[example]] +doc-scrape-examples = true +name = "window" + +[workspace] +resolver = "2" +members = ["dpi"] + +[workspace.package] +rust-version = "1.70.0" +repository = "https://github.com/rust-windowing/winit" +license = "Apache-2.0" +edition = "2021" + +[workspace.dependencies] +serde = { version = "1", features = ["serde_derive"] } +mint = "0.5.6" diff --git a/app/vendor/rune/vendor/winit/FEATURES.md b/app/vendor/rune/vendor/winit/FEATURES.md new file mode 100644 index 0000000..2ae9477 --- /dev/null +++ b/app/vendor/rune/vendor/winit/FEATURES.md @@ -0,0 +1,248 @@ +# Winit Scope + +Winit aims to expose an interface that abstracts over window creation and input handling and can +be used to create both games and applications. It supports the following main graphical platforms: +- Desktop + - Windows + - macOS + - Unix + - via X11 + - via Wayland + - Redox OS, via Orbital +- Mobile + - iOS + - Android +- Web + +Most platforms expose capabilities that cannot be meaningfully transposed onto others. Winit does not +aim to support every single feature of every platform, but rather to abstract over the common features +available everywhere. In this context, APIs exposed in winit can be split into different "support tiers": + +- **Core:** Features that are essential to providing a well-formed abstraction over each platform's + windowing and input APIs. +- **Platform:** Platform-specific features that can't be meaningfully exposed through a common API and + cannot be implemented outside of Winit without exposing a significant amount of Winit's internals + or interfering with Winit's abstractions. +- **Usability:** Features that are not strictly essential to Winit's functionality, but provide meaningful + usability improvements and cannot be reasonably implemented in an external crate. These are + generally optional and exposed through Cargo features. + +Core features are taken care of by the core Winit maintainers. Platform features are not. +When a platform feature is submitted, the submitter is considered the expert in the +feature and may be asked to support the feature should it break in the future. + +Winit ***does not*** directly expose functionality for drawing inside windows or creating native +menus, but ***does*** commit to providing APIs that higher-level crates can use to implement that +functionality. + +## `1.0` and stability + +When all core features are implemented to the satisfaction of the Winit maintainers, Winit 1.0 will +be released and the library will enter maintenance mode. For the most part, new core features will not +be added past this point. New platform features may be accepted and exposed through point releases. + +### Tier upgrades +Some platform features could, in theory, be exposed across multiple platforms, but have not gone +through the implementation work necessary to function on all platforms. When one of these features +gets implemented across all platforms, a PR can be opened to upgrade the feature to a core feature. +If that gets accepted, the platform-specific functions get deprecated and become permanently +exposed through the core, cross-platform API. + +# Features + +## Extending this section + +If your PR makes notable changes to Winit's features, please update this section as follows: + +- If your PR adds a new feature, add a brief description to the relevant section. If the feature is a core + feature, add a row to the feature matrix and describe what platforms the feature has been implemented on. + +- If your PR begins a new API rework, add a row to the `Pending API Reworks` table. If the PR implements the + API rework on all relevant platforms, please move it to the `Completed API Reworks` table. + +- If your PR implements an already-existing feature on a new platform, either mark the feature as *completed*, + or mark it as *mostly completed* and link to an issue describing the problems with the implementation. + +## Core + +### Windowing +- **Window initialization**: Winit allows the creation of a window +- **Providing pointer to init OpenGL**: Winit provides the necessary pointers to initialize a working opengl context +- **Providing pointer to init Vulkan**: Same as OpenGL but for Vulkan +- **Window decorations**: The windows created by winit are properly decorated, and the decorations can + be deactivated +- **Window decorations toggle**: Decorations can be turned on or off after window creation +- **Window resizing**: The windows created by winit can be resized and generate the appropriate events + when they are. The application can precisely control its window size if desired. +- **Window resize increments**: When the window gets resized, the application can choose to snap the window's + size to specific values. +- **Window transparency**: Winit allows the creation of windows with a transparent background. +- **Window maximization**: The windows created by winit can be maximized upon creation. +- **Window maximization toggle**: The windows created by winit can be maximized and unmaximized after + creation. +- **Window minimization**: The windows created by winit can be minimized after creation. +- **Fullscreen**: The windows created by winit can be put into fullscreen mode. +- **Fullscreen toggle**: The windows created by winit can be switched to and from fullscreen after + creation. +- **Exclusive fullscreen**: Winit allows changing the video mode of the monitor + for fullscreen windows and, if applicable, captures the monitor for exclusive + use by this application. +- **HiDPI support**: Winit assists developers in appropriately scaling HiDPI content. +- **Popup / modal windows**: Windows can be created relative to the client area of other windows, and parent + windows can be disabled in favor of popup windows. This feature also guarantees that popup windows + get drawn above their owner. + + +### System Information +- **Monitor list**: Retrieve the list of monitors and their metadata, including which one is primary. +- **Video mode query**: Monitors can be queried for their supported fullscreen video modes (consisting of resolution, refresh rate, and bit depth). + +### Input Handling +- **Mouse events**: Generating mouse events associated with pointer motion, click, and scrolling events. +- **Mouse set location**: Forcibly changing the location of the pointer. +- **Cursor locking**: Locking the cursor inside the window so it cannot move. +- **Cursor confining**: Confining the cursor to the window bounds so it cannot leave them. +- **Cursor icon**: Changing the cursor icon or hiding the cursor. +- **Cursor image**: Changing the cursor to your own image. +- **Cursor hittest**: Handle or ignore mouse events for a window. +- **Touch events**: Single-touch events. +- **Touch pressure**: Touch events contain information about the amount of force being applied. +- **Multitouch**: Multi-touch events, including cancellation of a gesture. +- **Keyboard events**: Properly processing keyboard events using the user-specified keymap and + translating keypresses into UTF-8 characters, handling dead keys and IMEs. +- **Drag & Drop**: Dragging content into winit, detecting when content enters, drops, or if the drop is cancelled. +- **Raw Device Events**: Capturing input from input devices without any OS filtering. +- **Gamepad/Joystick events**: Capturing input from gamepads and joysticks. +- **Device movement events**: Capturing input from the device gyroscope and accelerometer. + +## Platform +### Windows +* Setting the name of the internal window class +* Setting the taskbar icon +* Setting the parent window +* Setting a menu bar +* `WS_EX_NOREDIRECTIONBITMAP` support +* Theme the title bar according to Windows 10 Dark Mode setting or set a preferred theme +* Changing a system-drawn backdrop +* Setting the window border color +* Setting the title bar background color +* Setting the title color +* Setting the corner rounding preference + +### macOS +* Window activation policy +* Window movable by background +* Transparent titlebar +* Hidden titlebar +* Hidden titlebar buttons +* Full-size content view +* Accepts first mouse +* Set a preferred theme and get current theme. + +### Unix +* Window urgency +* X11 Window Class +* X11 Override Redirect Flag +* GTK Theme Variant +* Base window size +* Setting the X11 parent window + +### iOS +* Get the `UIScreen` object pointer +* Setting the `UIView` hidpi factor +* Valid orientations +* Home indicator visibility +* Status bar visibility and style +* Deferring system gestures +* Getting the device idiom +* Getting the preferred video mode + +### Web +* Get if the systems preferred color scheme is "dark" + +## Compatibility Matrix + +Legend: + +- ✔️: Works as intended +- ▢: Mostly works, but some bugs are known +- ❌: Missing feature or large bugs making it unusable +- **N/A**: Not applicable for this platform +- ❓: Unknown status + +### Windowing +|Feature |Windows|MacOS |Linux x11 |Linux Wayland |Android|iOS |Web |Redox OS| +|-------------------------------- | ----- | ---- | ------- | ----------- | ----- | ----- | -------- | ------ | +|Window initialization |✔️ |✔️ |▢[#5] |✔️ |▢[#33]|▢[#33] |✔️ |✔️ | +|Providing pointer to init OpenGL |✔️ |✔️ |✔️ |✔️ |✔️ |✔️ |**N/A**|✔️ | +|Providing pointer to init Vulkan |✔️ |✔️ |✔️ |✔️ |✔️ |❓ |**N/A**|**N/A** | +|Window decorations |✔️ |✔️ |✔️ |✔️ |**N/A**|**N/A**|**N/A**|✔️ | +|Window decorations toggle |✔️ |✔️ |✔️ |✔️ |**N/A**|**N/A**|**N/A**|**N/A** | +|Window resizing |✔️ |✔️ |✔️ |✔️ |**N/A**|**N/A**|✔️ |✔️ | +|Window resize increments |✔️ |✔️ |✔️ |❌ |**N/A**|**N/A**|**N/A**|**N/A** | +|Window transparency |✔️ |✔️ |✔️ |✔️ |**N/A**|**N/A**|N/A |✔️ | +|Window blur |❌ |❌ |❌ |✔️ |**N/A**|**N/A**|N/A |❌ | +|Window maximization |✔️ |✔️ |✔️ |✔️ |**N/A**|**N/A**|**N/A**|**N/A** | +|Window maximization toggle |✔️ |✔️ |✔️ |✔️ |**N/A**|**N/A**|**N/A**|**N/A** | +|Window minimization |✔️ |✔️ |✔️ |✔️ |**N/A**|**N/A**|**N/A**|**N/A** | +|Fullscreen |✔️ |✔️ |✔️ |✔️ |**N/A**|✔️ |✔️ |**N/A** | +|Fullscreen toggle |✔️ |✔️ |✔️ |✔️ |**N/A**|✔️ |✔️ |**N/A** | +|Exclusive fullscreen |✔️ |✔️ |✔️ |**N/A** |❌ |✔️ |**N/A**|**N/A** | +|HiDPI support |✔️ |✔️ |✔️ |✔️ |✔️ |✔️ |✔️ |❌ | +|Popup windows |❌ |❌ |❌ |❌ |❌ |❌ |**N/A**|**N/A** | + +### System information +|Feature |Windows|MacOS |Linux x11|Linux Wayland|Android|iOS |Web |Redox OS| +|---------------- | ----- | ---- | ------- | ----------- | ----- | ------- | -------- | ------ | +|Monitor list |✔️ |✔️ |✔️ |✔️ |✔️ |✔️ |**N/A**|❌ | +|Video mode query |✔️ |✔️ |✔️ |✔️ |✔️ |✔️ |**N/A**|❌ | + +### Input handling +|Feature |Windows |MacOS |Linux x11|Linux Wayland|Android|iOS |Web |Redox OS| +|----------------------- | ----- | ---- | ------- | ----------- | ----- | ----- | -------- | ------ | +|Mouse events |✔️ |▢[#63] |✔️ |✔️ |**N/A**|**N/A**|✔️ |✔️ | +|Mouse set location |✔️ |✔️ |✔️ |✔️(when locked) |**N/A**|**N/A**|**N/A**|**N/A** | +|Cursor locking |❌ |✔️ |❌ |✔️ |**N/A**|**N/A**|✔️ |❌ | +|Cursor confining |✔️ |❌ |✔️ |✔️ |**N/A**|**N/A**|❌ |❌ | +|Cursor icon |✔️ |✔️ |✔️ |✔️ |**N/A**|**N/A**|✔️ |**N/A** | +|Cursor image |✔️ |✔️ |✔️ |✔️ |**N/A**|**N/A**|✔️ |**N/A** | +|Cursor hittest |✔️ |✔️ |✔️ |✔️ |**N/A**|**N/A**|❌ |❌ | +|Touch events |✔️ |❌ |✔️ |✔️ |✔️ |✔️ |✔️ |**N/A** | +|Touch pressure |✔️ |❌ |❌ |❌ |❌ |✔️ |✔️ |**N/A** | +|Multitouch |✔️ |❌ |✔️ |✔️ |✔️ |✔️ |❌ |**N/A** | +|Keyboard events |✔️ |✔️ |✔️ |✔️ |✔️ |❌ |✔️ |✔️ | +|Drag & Drop |▢[#720] |▢[#720] |▢[#720] |▢[#720] |**N/A**|**N/A**|❓ |**N/A** | +|Raw Device Events |▢[#750] |▢[#750] |▢[#750] |❌ |❌ |❌ |❓ |**N/A** | +|Gamepad/Joystick events |❌[#804] |❌ |❌ |❌ |❌ |❌ |❓ |**N/A** | +|Device movement events |❓ |❓ |❓ |❓ |❌ |❌ |❓ |**N/A** | +|Drag window with cursor |✔️ |✔️ |✔️ |✔️ |**N/A**|**N/A**|**N/A** |**N/A** | +|Resize with cursor |✔️ |❌ |✔️ |✔️ |**N/A**|**N/A**|**N/A** |**N/A** | + +### Pending API Reworks +Changes in the API that have been agreed upon but aren't implemented across all platforms. + +|Feature |Windows|MacOS |Linux x11|Linux Wayland|Android|iOS |Web |Redox OS| +|------------------------------ | ----- | ---- | ------- | ----------- | ----- | ----- | -------- | ------ | +|New API for HiDPI ([#315] [#319]) |✔️ |✔️ |✔️ |✔️ |✔️ |✔️ |❓ |❓ | +|Event Loop 2.0 ([#459]) |✔️ |✔️ |✔️ |✔️ |✔️ |✔️ |❓ |✔️ | +|Keyboard Input 2.0 ([#753]) |✔️ |✔️ |✔️ |✔️ |✔️ |❌ |✔️ |✔️ | + +### Completed API Reworks +|Feature |Windows|MacOS |Linux x11|Linux Wayland|Android|iOS |Web |Redox OS| +|------------------------------ | ----- | ---- | ------- | ----------- | ----- | ----- | -------- | ------ | + +[#165]: https://github.com/rust-windowing/winit/issues/165 +[#219]: https://github.com/rust-windowing/winit/issues/219 +[#242]: https://github.com/rust-windowing/winit/issues/242 +[#306]: https://github.com/rust-windowing/winit/issues/306 +[#315]: https://github.com/rust-windowing/winit/issues/315 +[#319]: https://github.com/rust-windowing/winit/issues/319 +[#33]: https://github.com/rust-windowing/winit/issues/33 +[#459]: https://github.com/rust-windowing/winit/issues/459 +[#5]: https://github.com/rust-windowing/winit/issues/5 +[#63]: https://github.com/rust-windowing/winit/issues/63 +[#720]: https://github.com/rust-windowing/winit/issues/720 +[#721]: https://github.com/rust-windowing/winit/issues/721 +[#750]: https://github.com/rust-windowing/winit/issues/750 +[#753]: https://github.com/rust-windowing/winit/issues/753 +[#804]: https://github.com/rust-windowing/winit/issues/804 diff --git a/app/vendor/rune/vendor/winit/LICENSE b/app/vendor/rune/vendor/winit/LICENSE new file mode 100644 index 0000000..ad410e1 --- /dev/null +++ b/app/vendor/rune/vendor/winit/LICENSE @@ -0,0 +1,201 @@ +Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. \ No newline at end of file diff --git a/app/vendor/rune/vendor/winit/README.md b/app/vendor/rune/vendor/winit/README.md new file mode 100644 index 0000000..ab95887 --- /dev/null +++ b/app/vendor/rune/vendor/winit/README.md @@ -0,0 +1,70 @@ +# winit - Cross-platform window creation and management in Rust + +[![Crates.io](https://img.shields.io/crates/v/winit.svg)](https://crates.io/crates/winit) +[![Docs.rs](https://docs.rs/winit/badge.svg)](https://docs.rs/winit) +[![Master Docs](https://img.shields.io/github/actions/workflow/status/rust-windowing/winit/docs.yml?branch=master&label=master%20docs +)](https://rust-windowing.github.io/winit/winit/index.html) +[![CI Status](https://github.com/rust-windowing/winit/workflows/CI/badge.svg)](https://github.com/rust-windowing/winit/actions) + +```toml +[dependencies] +winit = "0.30.13" +``` + +## [Documentation](https://docs.rs/winit) + +For features _within_ the scope of winit, see [FEATURES.md](FEATURES.md). + +For features _outside_ the scope of winit, see [Are we GUI Yet?](https://areweguiyet.com/) and [Are we game yet?](https://arewegameyet.rs/), depending on what kind of project you're looking to do. + +## Contact Us + +Join us in our [![Matrix](https://img.shields.io/badge/Matrix-%23rust--windowing%3Amatrix.org-blueviolet.svg)](https://matrix.to/#/#rust-windowing:matrix.org) room. + +The maintainers have a meeting every friday at UTC 15. The meeting notes can be found [here](https://hackmd.io/@winit-meetings). + +## Usage + +Winit is a window creation and management library. It can create windows and lets you handle +events (for example: the window being resized, a key being pressed, a mouse movement, etc.) +produced by the window. + +Winit is designed to be a low-level brick in a hierarchy of libraries. Consequently, in order to +show something on the window you need to use the platform-specific getters provided by winit, or +another library. + +## CONTRIBUTING + +For contributing guidelines see [CONTRIBUTING.md](./CONTRIBUTING.md). + +## MSRV Policy + +This crate's Minimum Supported Rust Version (MSRV) is **1.70**. Changes to +the MSRV will be accompanied by a minor version bump. + +As a **tentative** policy, the upper bound of the MSRV is given by the following +formula: + +``` +min(sid, stable - 3) +``` + +Where `sid` is the current version of `rustc` provided by [Debian Sid], and +`stable` is the latest stable version of Rust. This bound may be broken in case of a major ecosystem shift or a security vulnerability. + +[Debian Sid]: https://packages.debian.org/sid/rustc + +The exception is for the Android platform, where a higher Rust version +must be used for certain Android features. In this case, the MSRV will be +capped at the latest stable version of Rust minus three. This inconsistency is +not reflected in Cargo metadata, as it is not powerful enough to expose this +restriction. + +All crates in the [`rust-windowing`] organizations have the +same MSRV policy. + +[`rust-windowing`]: https://github.com/rust-windowing + +### Platform-specific usage + +Check out the [`winit::platform`](https://rust-windowing.github.io/winit/winit/platform/index.html) module for platform-specific usage. diff --git a/app/vendor/rune/vendor/winit/build.rs b/app/vendor/rune/vendor/winit/build.rs new file mode 100644 index 0000000..6a4528b --- /dev/null +++ b/app/vendor/rune/vendor/winit/build.rs @@ -0,0 +1,27 @@ +use cfg_aliases::cfg_aliases; + +fn main() { + // The script doesn't depend on our code. + println!("cargo:rerun-if-changed=build.rs"); + + // Setup cfg aliases. + cfg_aliases! { + // Systems. + android_platform: { target_os = "android" }, + web_platform: { all(target_family = "wasm", target_os = "unknown") }, + macos_platform: { target_os = "macos" }, + ios_platform: { target_os = "ios" }, + windows_platform: { target_os = "windows" }, + apple: { any(target_os = "ios", target_os = "macos") }, + free_unix: { all(unix, not(apple), not(android_platform), not(target_os = "emscripten")) }, + redox: { target_os = "redox" }, + + // Native displays. + x11_platform: { all(feature = "x11", free_unix, not(redox)) }, + wayland_platform: { all(feature = "wayland", free_unix, not(redox)) }, + orbital_platform: { redox }, + } + + // Winit defined cfgs. + println!("cargo:rustc-check-cfg=cfg(unreleased_changelogs)"); +} diff --git a/app/vendor/rune/vendor/winit/docs/res/ATTRIBUTION.md b/app/vendor/rune/vendor/winit/docs/res/ATTRIBUTION.md new file mode 100644 index 0000000..268316f --- /dev/null +++ b/app/vendor/rune/vendor/winit/docs/res/ATTRIBUTION.md @@ -0,0 +1,11 @@ +# Image Attribution + +These images are used in the documentation of `winit`. + +## keyboard_*.svg + +These files are a modified version of "[ANSI US QWERTY (Windows)](https://commons.wikimedia.org/wiki/File:ANSI_US_QWERTY_(Windows).svg)" +by [Tomiĉo] (https://commons.wikimedia.org/wiki/User:Tomi%C4%89o). It was +originally released under the [CC-BY-SA 4.0](https://creativecommons.org/licenses/by-sa/4.0/deed.en) +License. Minor modifications have been made by [John Nunley](https://github.com/notgull), +which have been released under the same license as a derivative work. diff --git a/app/vendor/rune/vendor/winit/docs/res/keyboard_left_shift_key.svg b/app/vendor/rune/vendor/winit/docs/res/keyboard_left_shift_key.svg new file mode 100644 index 0000000..bae6f9a --- /dev/null +++ b/app/vendor/rune/vendor/winit/docs/res/keyboard_left_shift_key.svg @@ -0,0 +1 @@ +<svg xmlns="http://www.w3.org/2000/svg" xml:space="preserve" id="svg5048" x="0" y="0" style="enable-background:new 0 0 1226 349" version="1.1" viewBox="0 0 1226 349"><style id="style3852" type="text/css">.st1{fill:#ccc;stroke:#000;stroke-width:2}.st2{fill:#fcfcfc}</style><g id="Layer_1"><path id="path3854" d="M6.5.5h1213c3.3 0 6 2.7 6 6v336c0 3.3-2.7 6-6 6H6.5c-3.3 0-6-2.7-6-6V6.5c0-3.3 2.7-6 6-6z" style="fill:#eee;stroke:#ddd"/></g><g id="Layer_2"><path id="path3857" d="M13.5 9.8h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.3 1.8-4 4-4z" class="st1"/><path id="path3859" d="M121.5 9.8h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.3 1.8-4 4-4z" class="st1"/><path id="path3861" d="M175.5 9.8h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.3 1.8-4 4-4z" class="st1"/><path id="path3863" d="M229.5 9.8h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.3 1.8-4 4-4z" class="st1"/><path id="path3865" d="M283.5 9.8h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.3 1.8-4 4-4z" class="st1"/><path id="path3867" d="M364.5 9.8h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.3 1.8-4 4-4z" class="st1"/><path id="path3869" d="M418.5 9.8h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.3 1.8-4 4-4z" class="st1"/><path id="path3871" d="M472.5 9.8h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.3 1.8-4 4-4z" class="st1"/><path id="path3873" d="M526.5 9.8h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.3 1.8-4 4-4z" class="st1"/><path id="path3875" d="M607.5 9.8h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.3 1.8-4 4-4z" class="st1"/><path id="path3877" d="M661.5 9.8h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.3 1.8-4 4-4z" class="st1"/><path id="path3879" d="M715.5 9.8h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.3 1.8-4 4-4z" class="st1"/><path id="path3881" d="M769.5 9.8h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.3 1.8-4 4-4z" class="st1"/><path id="path3883" d="M837 9.8h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.3 1.8-4 4-4z" class="st1"/><path id="path3885" d="M891 9.8h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.3 1.8-4 4-4z" class="st1"/><path id="path3887" d="M945 9.8h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.3 1.8-4 4-4z" class="st1"/><path id="path3889" d="M13.5 77.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3891" d="M67.5 77.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3893" d="M121.5 77.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3895" d="M175.5 77.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3897" d="M229.5 77.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3899" d="M283.5 77.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3901" d="M337.5 77.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3903" d="M391.5 77.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3905" d="M445.5 77.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3907" d="M499.5 77.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3909" d="M553.5 77.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3911" d="M607.5 77.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3913" d="M661.5 77.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3915" d="M715.5 77.2h92c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-92c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3917" d="M837 77.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3919" d="M891 77.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3921" d="M945 77.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3923" d="M1012.5 77.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3925" d="M1066.5 77.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3927" d="M1120.5 77.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3929" d="M1174.5 77.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3931" d="M13.5 131.2h65c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-65c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3933" d="M94.5 131.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3935" d="M148.5 131.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3937" d="M202.5 131.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3939" d="M256.5 131.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3941" d="M310.5 131.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3943" d="M364.5 131.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3945" d="M418.5 131.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3947" d="M472.5 131.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3949" d="M526.5 131.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3951" d="M580.5 131.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3953" d="M634.5 131.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3955" d="M688.5 131.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3957" d="M742.5 131.2h65c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-65c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3959" d="M837 131.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3961" d="M891 131.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3963" d="M945 131.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3965" d="M1012.5 131.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3967" d="M1066.5 131.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3969" d="M1120.5 131.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3971" d="M1174.5 131.2h38c2.2 0 4 1.8 4 4v92c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-92c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3973" d="M13.5 185.2H92c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4H13.5c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3975" d="M108 185.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3977" d="M162 185.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3979" d="M216 185.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3981" d="M270 185.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3983" d="M324 185.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3985" d="M378 185.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3987" d="M432 185.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3989" d="M486 185.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3991" d="M540 185.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3993" d="M594 185.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3995" d="M648 185.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3997" d="M702 185.2h105.5c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4H702c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3999" d="M1012.5 185.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path4001" d="M1066.5 185.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path4003" d="M1120.5 185.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path4005" d="M13.5 239.2H119c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4H13.5c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path4007" d="M135 239.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path4009" d="M189 239.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path4011" d="M243 239.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path4013" d="M297 239.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path4015" d="M351 239.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path4017" d="M405 239.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path4019" d="M459 239.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path4021" d="M513 239.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path4023" d="M567 239.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path4025" d="M621 239.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path4027" d="M675 239.2h132.5c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4H675c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path4029" d="M891 239.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path4031" d="M1012.5 239.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path4033" d="M1066.5 239.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path4035" d="M1120.5 239.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path4037" d="M1174.5 239.2h38c2.2 0 4 1.8 4 4v92c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-92c0-2.2 1.8-4 4-4z" class="st1"/><path id="path4039" d="M13.5 293.2H65c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4H13.5c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path4041" d="M81 293.2h51.5c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4H81c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path4043" d="M148.5 293.2H200c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-51.5c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path4045" d="M216 293.2h321.5c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4H216c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path4047" d="M553.5 293.2H605c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-51.5c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path4049" d="M621 293.2h51.5c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4H621c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path4051" d="M688.5 293.2H740c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-51.5c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path4053" d="M756 293.2h51.5c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4H756c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path4055" d="M837 293.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path4057" d="M891 293.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path4059" d="M945 293.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path4061" d="M1012.5 293.2h92c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-92c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path4063" d="M1120.5 293.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/></g><g id="Layer_3"><path id="path4066" d="M14.5 10.8h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.3 1.8-4 4-4z" class="st2"/><path id="path4068" d="M122.5 10.8h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.3 1.8-4 4-4z" class="st2"/><path id="path4070" d="M176.5 10.8h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.3 1.8-4 4-4z" class="st2"/><path id="path4072" d="M230.5 10.8h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.3 1.8-4 4-4z" class="st2"/><path id="path4074" d="M284.5 10.8h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.3 1.8-4 4-4z" class="st2"/><path id="path4076" d="M365.5 10.8h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.3 1.8-4 4-4z" class="st2"/><path id="path4078" d="M419.5 10.8h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.3 1.8-4 4-4z" class="st2"/><path id="path4080" d="M473.5 10.8h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.3 1.8-4 4-4z" class="st2"/><path id="path4082" d="M527.5 10.8h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.3 1.8-4 4-4z" class="st2"/><path id="path4084" d="M608.5 10.8h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.3 1.8-4 4-4z" class="st2"/><path id="path4086" d="M662.5 10.8h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.3 1.8-4 4-4z" class="st2"/><path id="path4088" d="M716.5 10.8h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.3 1.8-4 4-4z" class="st2"/><path id="path4090" d="M770.5 10.8h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.3 1.8-4 4-4z" class="st2"/><path id="path4092" d="M838 10.8h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.3 1.8-4 4-4z" class="st2"/><path id="path4094" d="M892 10.8h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.3 1.8-4 4-4z" class="st2"/><path id="path4096" d="M946 10.8h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.3 1.8-4 4-4z" class="st2"/><path id="path4098" d="M14.5 78.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4100" d="M68.5 78.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4102" d="M122.5 78.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4104" d="M176.5 78.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4106" d="M230.5 78.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4108" d="M284.5 78.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4110" d="M338.5 78.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4112" d="M392.5 78.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4114" d="M446.5 78.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4116" d="M500.5 78.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4118" d="M554.5 78.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4120" d="M608.5 78.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4122" d="M662.5 78.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4124" d="M716.5 78.2h90c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-90c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4126" d="M838 78.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4128" d="M892 78.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4130" d="M946 78.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4132" d="M1013.5 78.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4134" d="M1067.5 78.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4136" d="M1121.5 78.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4138" d="M1175.5 78.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4140" d="M14.5 132.2h63c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-63c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4142" d="M95.5 132.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4144" d="M149.5 132.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4146" d="M203.5 132.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4148" d="M257.5 132.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4150" d="M311.5 132.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4152" d="M365.5 132.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4154" d="M419.5 132.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4156" d="M473.5 132.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4158" d="M527.5 132.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4160" d="M581.5 132.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4162" d="M635.5 132.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4164" d="M689.5 132.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4166" d="M743.5 132.2h63c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-63c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4168" d="M838 132.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4170" d="M892 132.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4172" d="M946 132.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4174" d="M1013.5 132.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4176" d="M1067.5 132.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4178" d="M1121.5 132.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4180" d="M1175.5 132.2h36c2.2 0 4 1.8 4 4v88c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-88c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4182" d="M14.5 186.2H91c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4H14.5c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4184" d="M109 186.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4186" d="M163 186.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4188" d="M217 186.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4190" d="M271 186.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4192" d="M325 186.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4194" d="M379 186.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4196" d="M433 186.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4198" d="M487 186.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4200" d="M541 186.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4202" d="M595 186.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4204" d="M649 186.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4206" d="M703 186.2h103.5c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4H703c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4208" d="M1013.5 186.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4210" d="M1067.5 186.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4212" d="M1121.5 186.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4214" d="M14.5 240.2H118c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4H14.5c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4216" d="M136 240.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4218" d="M190 240.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4220" d="M244 240.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4222" d="M298 240.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4224" d="M352 240.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4226" d="M406 240.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4228" d="M460 240.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4230" d="M514 240.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4232" d="M568 240.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4234" d="M622 240.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4236" d="M676 240.2h130.5c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4H676c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4238" d="M892 240.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4240" d="M1013.5 240.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4242" d="M1067.5 240.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4244" d="M1121.5 240.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4246" d="M1175.5 240.2h36c2.2 0 4 1.8 4 4v88c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-88c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4248" d="M14.5 294.2H64c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4H14.5c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4250" d="M82 294.2h49.5c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4H82c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4252" d="M149.5 294.2H199c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-49.5c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4254" d="M217 294.2h319.5c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4H217c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4256" d="M554.5 294.2H604c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-49.5c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4258" d="M622 294.2h49.5c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4H622c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4260" d="M689.5 294.2H739c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-49.5c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4262" d="M757 294.2h49.5c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4H757c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4264" d="M838 294.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4266" d="M892 294.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4268" d="M946 294.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4270" d="M1013.5 294.2h90c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-90c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4272" d="M1121.5 294.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/></g><g id="Layer_4"><g id="g4279"><path id="path4275" d="M141.4 29.3h-3.9v2.1h2.3v1.2h-2.3V36h-1.2v-7.9h5.1v1.2z"/><path id="path4277" d="M144.7 36h-1.2v-6.1h-1.4v-.8c.8-.1 1.5-.3 1.6-1h1V36z"/></g><g id="g4285"><path id="path4281" d="M193.8 29.3h-3.9v2.1h2.3v1.2h-2.3V36h-1.2v-7.9h5.1v1.2z"/><path id="path4283" d="M200.4 36h-5.7c.1-2.3 1.5-3.4 3-4.3 1.1-.6 1.3-1 1.3-1.5 0-.6-.4-1-1.5-1-.7 0-1.4.3-1.9.8l-.6-1c.7-.7 1.7-1.1 2.7-1.1 1.6 0 2.7.7 2.7 2.2 0 1.2-.6 1.7-2 2.6-1.5.9-1.9 1.4-2.1 2.2h4.2V36z"/></g><g id="g4291"><path id="path4287" d="M247.9 29.3H244v2.1h2.3v1.2H244V36h-1.2v-7.9h5.1v1.2z"/><path id="path4289" d="M254.5 33.7c0 1.6-1.1 2.5-3 2.5-1.1 0-2.3-.5-2.9-1.3l.9-.8c.5.6 1.2.9 2 .9 1.3 0 1.7-.5 1.7-1.3s-.6-1.2-1.4-1.2h-.7v-1.2h.7c.7 0 1.1-.5 1.1-1.1 0-.5-.3-1.1-1.5-1.1-.6 0-1.1.3-1.6.7l-.8-.8c.7-.7 1.5-1.1 2.5-1.1 1.5 0 2.7.8 2.7 2.2 0 1-.4 1.4-1 1.7.7.3 1.3.9 1.3 1.9z"/></g><g id="g4297"><path id="path4293" d="M301.6 29.3h-3.9v2.1h2.3v1.2h-2.3V36h-1.2v-7.9h5.1v1.2z"/><path id="path4295" d="M309 34.2h-1.1V36h-1.2v-1.7h-4.3v-1.1l4.1-5.1h1.4v5.1h1.1v1zm-2.2-4.8c-.1.2-.5.6-.7.9l-1.5 1.9c-.2.3-.6.7-.7.9h3v-2.3c-.1-.4-.1-1.1-.1-1.4z"/></g><g id="g4303"><path id="path4299" d="M382.7 29.3h-3.9v2.1h2.3v1.2h-2.3V36h-1.2v-7.9h5.1v1.2z"/><path id="path4301" d="M389.7 33.3c0 1.9-1.3 2.8-3.1 2.8-1 0-1.9-.2-2.8-.8l.6-1c.7.4 1.5.6 2.2.6 1.2 0 1.9-.6 1.9-1.6 0-.9-.6-1.4-1.6-1.4-.7 0-1.1.2-1.5.5l-1.3-.5.3-3.9h4.9v1.1h-3.8l-.2 2c.4-.2 1-.4 1.7-.4 1.8.1 2.7 1.2 2.7 2.6z"/></g><g id="g4309"><path id="path4305" d="M436.7 29.3h-3.9v2.1h2.3v1.2h-2.3V36h-1.2v-7.9h5.1v1.2z"/><path id="path4307" d="M443.9 33.5c0 1.7-1.4 2.6-3.1 2.6-1.7 0-3-.9-3-3.2 0-2.1 1.2-4.9 4.9-5V29c-1.8.1-3.1.9-3.6 2.6.6-.4 1.1-.6 2.1-.6 1.5 0 2.7.8 2.7 2.5zm-1.2 0c0-1-.7-1.4-1.8-1.4-1.2 0-1.9.5-1.9 1.4 0 .8.6 1.5 1.8 1.5 1.2 0 1.9-.6 1.9-1.5z"/></g><g id="g4315"><path id="path4311" d="M491 29.3h-3.9v2.1h2.3v1.2h-2.3V36h-1.2v-7.9h5.1v1.2z"/><path id="path4313" d="M497.2 29.3c-1.3 1.5-2.6 3.8-2.6 6.7h-1.2c0-2.7 1-4.9 2.5-6.8h-4.2V28h5.5v1.3z"/></g><g id="g4321"><path id="path4317" d="M544.5 29.3h-3.9v2.1h2.3v1.2h-2.3V36h-1.2v-7.9h5.1v1.2z"/><path id="path4319" d="M551.9 33.7c0 1.6-1.2 2.4-3.1 2.4s-3.1-.9-3.1-2.4c0-1 .5-1.6 1.4-2-.8-.3-1.1-1.1-1.1-1.5 0-1.5 1.2-2.2 2.8-2.2 1.4 0 2.8.7 2.8 2.2 0 .5-.2 1.2-1.1 1.6.9.3 1.4.9 1.4 1.9zm-1.2 0c0-.8-.6-1.4-1.9-1.4-1.3 0-1.9.5-1.9 1.3s.7 1.4 1.9 1.4c1.3.1 1.9-.5 1.9-1.3zm-.3-3.5c0-.6-.4-1.2-1.6-1.2s-1.6.5-1.6 1.1c0 .6.6 1.1 1.6 1.1 1 .1 1.6-.4 1.6-1z"/></g><g id="g4327"><path id="path4323" d="M625.7 29.3h-3.9v2.1h2.3v1.2h-2.3V36h-1.2v-7.9h5.1v1.2z"/><path id="path4325" d="M632.8 31.1c0 2.1-1.2 4.9-4.9 5V35c1.8-.1 3.1-.9 3.6-2.6-.6.4-1.1.6-2.1.6-1.4 0-2.7-.8-2.7-2.5s1.4-2.6 3.1-2.6c1.7.1 3 1 3 3.2zm-1.2-.5c0-.8-.6-1.5-1.8-1.5-1.2 0-1.9.6-1.9 1.5 0 1 .7 1.4 1.8 1.4 1.2 0 1.9-.5 1.9-1.4z"/></g><g id="g4335"><path id="path4329" d="M677.7 29.3h-3.9v2.1h2.3v1.2h-2.3V36h-1.2v-7.9h5.1v1.2z"/><path id="path4331" d="M680.9 36h-1.2v-6.1h-1.4v-.8c.8-.1 1.5-.3 1.6-1h1V36z"/><path id="path4333" d="M688.9 32c0 2.4-1.1 4.1-3.1 4.1s-3.1-1.7-3.1-4.1c0-2.4 1.1-4.1 3.1-4.1 2 .1 3.1 1.7 3.1 4.1zm-1.2.1c0-1.7-.5-2.9-1.9-2.9s-1.9 1.3-1.9 2.9.6 2.9 1.9 2.9c1.3 0 1.9-1.3 1.9-2.9z"/></g><g id="g4343"><path id="path4337" d="M733.5 29.3h-3.9v2.1h2.3v1.2h-2.3V36h-1.2v-7.9h5.1v1.2z"/><path id="path4339" d="M736.7 36h-1.2v-6.1h-1.4v-.8c.8-.1 1.5-.3 1.6-1h1V36z"/><path id="path4341" d="M740.6 36h-1.2v-6.1H738v-.8c.8-.1 1.5-.3 1.6-1h1V36z"/></g><g id="g4351"><path id="path4345" d="M785.8 29.3h-3.9v2.1h2.3v1.2h-2.3V36h-1.2v-7.9h5.1v1.2z"/><path id="path4347" d="M789.1 36h-1.2v-6.1h-1.4v-.8c.8-.1 1.5-.3 1.6-1h1V36z"/><path id="path4349" d="M796.4 36h-5.7c.1-2.3 1.5-3.4 3-4.3 1.1-.6 1.3-1 1.3-1.5 0-.6-.4-1-1.5-1-.7 0-1.4.3-1.9.8l-.8-.9c.7-.7 1.7-1.1 2.7-1.1 1.6 0 2.7.7 2.7 2.2 0 1.2-.6 1.7-2 2.6-1.5.9-2 1.4-2.1 2.2h4.2v1z"/></g><g id="g4357"><path id="path4353" d="M35.9 89.7c-.5 1.3-1.1 2-2.2 2-.6 0-.9-.2-1.4-.5-.6-.4-.9-.6-1.2-.6-.5 0-.7.3-1 1.1l-1-.5c.5-1.3 1.1-2 2.2-2 .6 0 .9.2 1.4.5.5.4.9.6 1.2.6.5 0 .7-.3 1.1-1.1l.9.5z"/><path id="path4355" d="M33.9 104.2h-1.2l-2.3-2.3h2l1.5 2.3z"/></g><g id="g4363"><path id="path4359" d="M87.6 94.8c0 .6-.5 1.1-1.1 1.1-.6 0-1.1-.5-1.1-1.1s.5-1.1 1.1-1.1c.6 0 1.1.5 1.1 1.1zm-.3-4.6-.3 2.6h-1l-.3-2.7v-4.4h1.5v4.5z"/><path id="path4361" d="M87.6 112.7h-1.5v-7.6h-1.8v-1c1-.1 1.9-.4 2-1.3h1.2v9.9z"/></g><g id="g4369"><path id="path4365" d="M145.6 89.1c0 2.1-.9 2.9-2.2 2.9-.7 0-1.3-.4-1.5-.9-.3.5-1.1.9-1.8.9-1.1 0-2.2-.6-2.2-1.9 0-1.2 1.1-1.8 2.3-1.8.6 0 1.1.2 1.4.4V88c0-.6-.5-.8-1.3-.8-.5 0-1 .1-1.4.3l-.4-.7c.5-.3 1.2-.5 1.8-.5 1.3 0 2.2.6 2.2 1.7v2.4c0 .5.3.9.9.9.9 0 1.2-.7 1.2-2.1 0-2.3-1.8-4.2-4.3-4.2s-4.3 1.8-4.3 4.3 1.8 4.3 4.3 4.3c.6 0 1.2-.1 1.8-.4l.3.8c-.8.4-1.4.5-2.2.5-3 0-5.1-2.2-5.1-5.1 0-3 2.2-5.1 5.1-5.1 3.3-.1 5.4 2.2 5.4 4.8zm-3.9 1.3v-.9c-.3-.2-.8-.4-1.5-.4-.8 0-1.3.3-1.3 1s.5 1.1 1.4 1.1c.5 0 1.1-.3 1.4-.8z"/><path id="path4367" d="M143.8 111.3h-7.1c.1-2.9 1.9-4.2 3.8-5.4 1.3-.8 1.7-1.2 1.7-1.9 0-.8-.5-1.3-1.9-1.3-.8 0-1.8.4-2.4 1l-.9-1.1c.9-.8 2.2-1.3 3.4-1.3 2.1 0 3.4.9 3.4 2.7 0 1.5-.8 2.2-2.5 3.2-1.9 1.1-2.4 1.8-2.7 2.7h5.3v1.4z"/></g><g id="g4375"><path id="path4371" d="M198.8 93.4h-1.7v2.3h-1.4v-2.3h-2.3v2.3H192v-2.3h-1.7v-1.3h1.7v-2.7h-1.7V88h1.7v-2.3h1.4V88h2.3v-2.3h1.4V88h1.7v1.3h-1.7V92h1.7v1.4zm-3.1-1.3v-2.7h-2.3v2.7h2.3z"/><path id="path4373" d="M197.8 109.7c0 2-1.4 3.1-3.7 3.1-1.4 0-2.9-.6-3.6-1.6l1.1-1c.6.8 1.5 1.1 2.4 1.1 1.6 0 2.2-.6 2.2-1.6s-.8-1.5-1.8-1.5h-.9v-1.4h.9c.9 0 1.4-.6 1.4-1.4 0-.6-.4-1.4-1.9-1.4-.8 0-1.4.3-2 .9l-1.1-1c.8-.9 1.8-1.3 3.1-1.3 1.9 0 3.4 1 3.4 2.7 0 1.2-.5 1.8-1.2 2.2 1.1.2 1.7 1 1.7 2.2z"/></g><g id="g4381"><path id="path4377" d="M252 92.7c0 1.6-.9 2.7-2.8 2.9V97h-1.5v-1.4c-1.2-.2-2.3-.7-2.9-1.6l1.1-1c.7.8 1.6 1.1 2.5 1.1 1.4 0 2-.5 2-1.3s-.6-1.1-2.2-1.6c-2.1-.6-3.1-1.1-3.1-2.9 0-1.5 1.1-2.4 2.5-2.6v-1.5h1.5v1.5c1 .2 1.8.6 2.5 1.3l-1 1c-.7-.6-1.3-1-2.3-1-1.1 0-1.6.5-1.6 1.1 0 .7.4 1 2.1 1.5 2 .8 3.2 1.3 3.2 3.1z"/><path id="path4379" d="M252.5 110.5h-1.3v2.2h-1.4v-2.2h-5.4v-1.4l5.1-6.3h1.7v6.4h1.3v1.3zm-2.7-6.1c-.2.3-.6.8-.9 1.2L247 108c-.3.4-.7.9-.9 1.1h3.7v-2.9c-.1-.5 0-1.4 0-1.8z"/></g><g id="g4387"><path id="path4383" d="M301.2 88.7c0 1.8-1 3.1-2.5 3.1s-2.4-1.3-2.4-3.1 1-3.1 2.5-3.1c1.4 0 2.4 1.3 2.4 3.1zm-1.3 0c0-1.1-.4-1.9-1.2-1.9s-1.2.7-1.2 1.8.4 1.9 1.2 1.9 1.2-.8 1.2-1.8zm6.4-3-6.1 9.9h-1.4l6.1-9.9h1.4zm2.4 7c0 1.8-1 3.1-2.5 3.1-1.4 0-2.4-1.3-2.4-3.1s1-3.1 2.5-3.1c1.5.1 2.4 1.3 2.4 3.1zm-1.2.1c0-1.1-.4-1.9-1.2-1.9-.8 0-1.2.7-1.2 1.8s.4 1.9 1.2 1.9c.7 0 1.2-.8 1.2-1.8z"/><path id="path4385" d="M306.1 109.3c0 2.4-1.6 3.5-3.9 3.5-1.3 0-2.4-.3-3.5-1l.7-1.2c.8.5 1.9.8 2.8.8 1.5 0 2.4-.8 2.4-2s-.8-1.8-2-1.8c-.8 0-1.4.2-1.9.6l-1.6-.6.3-4.8h6.1v1.4h-4.8l-.2 2.5c.6-.3 1.2-.5 2.1-.5 2.4 0 3.5 1.3 3.5 3.1z"/></g><g id="g4393"><path id="path4389" d="M359.9 90.3h-1.6l-1.8-3-1.8 3h-1.6l2.9-4.5h1.1l2.8 4.5z"/><path id="path4391" d="M360.4 109.5c0 2.2-1.7 3.3-3.9 3.3-2.1 0-3.7-1.1-3.7-4 0-2.6 1.4-6.1 6.2-6.3v1.4c-2.3.1-3.8 1.1-4.5 3.2.7-.6 1.4-.8 2.6-.8 1.8.1 3.3 1.1 3.3 3.2zm-1.5.1c0-1.2-.8-1.7-2.3-1.7-1.4 0-2.3.6-2.3 1.7 0 1 .8 1.8 2.3 1.8 1.5 0 2.3-.7 2.3-1.8z"/></g><g id="g4399"><path id="path4395" d="M414.9 95.7h-1.7l-.8-.9c-.7.7-1.7 1.1-2.8 1.1-2.1 0-3.1-1.1-3.1-2.7 0-1.3.7-2.2 2.1-2.9l-.2-.2c-.7-.8-.9-1.4-.9-2.1 0-1.4 1.1-2.3 2.8-2.3.9 0 1.8.3 2.7.9l-.7 1.2c-.8-.6-1.3-.8-2.1-.8s-1.1.3-1.1.9c0 .4.1.7.5 1.2l2.9 3.6c.3-.5.5-1.1.7-1.6l1.3.4c-.2.8-.6 1.7-1.1 2.4l1.5 1.8zm-3.4-2-2.1-2.5c-.9.5-1.4 1-1.4 1.9 0 .8.5 1.4 1.7 1.4.7 0 1.3-.3 1.8-.8z"/><path id="path4397" d="M413.6 104.3c-1.7 1.9-3.2 4.7-3.3 8.4h-1.5c.1-3.4 1.2-6.1 3.1-8.5h-5.2v-1.4h6.9v1.5z"/></g><g id="g4405"><path id="path4401" d="m467.3 89.5-.6 1.1-1.8-1.3.2 2.2h-1.2l.2-2.2-1.8 1.3-.6-1.1 2-.9-2-.9.6-1.1 1.8 1.3-.2-2.2h1.2l-.2 2.1 1.7-1.3.6 1.1-2 .9 2.1 1z"/><path id="path4403" d="M468.4 109.8c0 2-1.5 3-3.9 3s-3.9-1.1-3.9-3c0-1.2.6-2 1.8-2.5-1-.4-1.3-1.3-1.3-1.9 0-1.9 1.5-2.8 3.5-2.8 1.8 0 3.5.9 3.5 2.8 0 .6-.3 1.5-1.3 1.9.9.4 1.6 1.2 1.6 2.5zm-1.5 0c0-1-.8-1.7-2.4-1.7-1.6 0-2.4.6-2.4 1.6s.9 1.7 2.4 1.7c1.6.1 2.4-.6 2.4-1.6zm-.4-4.4c0-.8-.5-1.5-2-1.5-1.4 0-2 .7-2 1.4 0 .8.8 1.4 2 1.4 1.3 0 2-.6 2-1.3z"/></g><g id="g4411"><path id="path4407" d="m520.3 96.6-.7.6c-1.4-1.3-2.8-3.2-2.8-5.8 0-2.7 1.3-4.5 2.8-5.9l.7.6c-1.3 1.4-2 3-2 5.2.1 2.4.8 3.9 2 5.3z"/><path id="path4409" d="M522.2 106.6c0 2.6-1.4 6.1-6.2 6.3v-1.4c2.3-.1 3.8-1.1 4.5-3.2-.7.6-1.4.8-2.6.8-1.8 0-3.3-1-3.3-3.1 0-2.2 1.7-3.3 3.9-3.3 2.1-.1 3.7 1 3.7 3.9zm-1.5-.7c0-1-.8-1.8-2.3-1.8-1.5 0-2.3.7-2.3 1.8 0 1.2.8 1.7 2.3 1.7 1.4 0 2.3-.6 2.3-1.7z"/></g><g id="g4417"><path id="path4413" d="M574.2 91.3c0 2.7-1.3 4.5-2.8 5.9l-.7-.6c1.3-1.4 2-3 2-5.2 0-2.3-.8-3.9-2-5.2l.7-.6c1.4 1.3 2.8 3.2 2.8 5.7z"/><path id="path4415" d="M576.4 107.7c0 3-1.4 5.1-3.9 5.1-2.6 0-3.9-2.1-3.9-5.1s1.4-5.1 3.9-5.1c2.6 0 3.9 2.1 3.9 5.1zm-1.5 0c0-2.1-.7-3.7-2.4-3.7s-2.4 1.6-2.4 3.7.7 3.7 2.4 3.7c1.8 0 2.4-1.6 2.4-3.7z"/></g><g id="g4423"><path id="path4419" d="M630 98.2h-7v-1.3h7.1v1.3z"/><path id="path4421" d="M628.3 108.2h-3.5v-1.4h3.5v1.4z"/></g><g id="g4429"><path id="path4425" d="M683.9 91.5h-2.7v2.8h-1.5v-2.8H677v-1.4h2.7v-2.8h1.5v2.8h2.7v1.4z"/><path id="path4427" d="M683.6 106.9h-6.1v-1.4h6.1v1.4zm0 3.2h-6.1v-1.4h6.1v1.4z"/></g><g id="g4433"><path id="path4431" d="m1088.4 93-4.4 12.5h-1.5L1087 93h1.4z"/></g><g id="g4437"><path id="path4435" d="m1136.4 98.2.7-1.2 1.9 1.4-.2-2.4h1.4l-.2 2.4 1.9-1.4.7 1.2-2.2 1 2.2 1-.7 1.2-1.9-1.4.2 2.4h-1.4l.2-2.4-1.9 1.4-.7-1.2 2.2-1-2.2-1z"/></g><g id="g4441"><path id="path4439" d="M1189.9 98.4h7.2v1.6h-7.2v-1.6z"/></g><g id="g4445"><path id="path4443" d="M117.7 153.2c0 1.7-.6 3.2-1.5 4.1l.7 1-1.2.8-.7-1c-.4.2-.9.3-1.5.3-2.6 0-4.2-2.1-4.2-5.1s1.6-5.1 4.2-5.1c2.6-.1 4.2 2 4.2 5zm-1.5 0c0-2.2-.9-3.6-2.7-3.6-1.7 0-2.7 1.4-2.7 3.6s.9 3.7 2.7 3.7c.3 0 .5 0 .7-.1l-.7-1.1 1.2-.8.7 1.1c.5-.6.8-1.6.8-2.8z"/></g><g id="g4449"><path id="path4447" d="m172.9 148.2-2 9.9h-1.5l-1.5-6.4c-.1-.3-.2-1.1-.3-1.3 0 .2-.2 1-.3 1.3l-1.6 6.4h-1.5l-2-9.9h1.5l1.2 6.3c.1.3.2 1 .2 1.3.1-.3.2-1 .3-1.3l1.6-6.3h1.3l1.6 6.4c.1.3.2.8.2 1.1.1-.4.2-.9.2-1.2l1.2-6.4h1.4z"/></g><g id="g4453"><path id="path4451" d="M225 158.2h-6.6v-9.9h6.4v1.4h-4.9v2.5h2.8v1.4h-2.8v3.1h5.1v1.5z"/></g><g id="g4457"><path id="path4455" d="M279.4 151.2c0 1.6-.8 2.6-2.2 2.9l2 4.1h-1.7l-2-3.9h-2.2v3.9h-1.5v-9.9h4.4c1.8-.1 3.2.9 3.2 2.9zm-1.5.1c0-1-.7-1.6-1.7-1.6h-2.9v3.2h2.9c1-.1 1.7-.6 1.7-1.6z"/></g><g id="g4461"><path id="path4459" d="M333.1 149.7h-2.9v8.5h-1.5v-8.5h-2.9v-1.5h7.3v1.5z"/></g><g id="g4465"><path id="path4463" d="m387.8 148.2-3.6 6v3.9h-1.5v-3.9l-3.6-6h1.7l1.5 2.7c.3.6.9 1.6 1 2 .2-.4.7-1.3 1-2l1.6-2.8h1.9z"/></g><g id="g4469"><path id="path4467" d="M441.3 154c0 2.8-1.3 4.3-3.8 4.3s-3.7-1.6-3.7-4.3v-5.8h1.5v5.7c0 1.9.8 2.9 2.3 2.9 1.6 0 2.3-1 2.3-2.8v-5.8h1.5v5.8z"/></g><g id="g4473"><path id="path4471" d="M492.2 158.2h-1.5v-9.9h1.5v9.9z"/></g><g id="g4477"><path id="path4475" d="M549.7 153.2c0 3.1-1.7 5.1-4.3 5.1-2.5 0-4.2-2-4.2-5.1s1.7-5.1 4.2-5.1c2.6 0 4.3 2 4.3 5.1zm-1.5 0c0-2.3-1.2-3.7-2.8-3.7-1.6 0-2.7 1.4-2.7 3.6s1.1 3.7 2.7 3.7c1.7.1 2.8-1.3 2.8-3.6z"/></g><g id="g4481"><path id="path4479" d="M603.5 151.4c0 2-1.4 3.1-3.3 3.1h-2.6v3.7h-1.5v-9.9h4.2c1.8-.1 3.2 1 3.2 3.1zm-1.5 0c0-1.1-.7-1.7-1.7-1.7h-2.7v3.4h2.7c1.1 0 1.7-.7 1.7-1.7z"/></g><g id="g4487"><path id="path4483" d="M655.8 151.2c-2.3 0-3.3-1-3.3-3v-.9c0-1-.2-1.2-.8-1.2h-.3v-1.3h.3c.6 0 .8-.3.8-1.2v-.9c0-2 1-3 3.3-3v1.1c-1.4.1-1.8.7-1.8 1.8v.7c0 1.3-.3 1.9-1.1 2.2.8.3 1.1.9 1.1 2.2v.7c0 1.1.4 1.7 1.8 1.8v1z"/><path id="path4485" d="M655.3 168.2h-3.1v-11.5h3.1v1.2h-1.7v9.1h1.7v1.2z"/></g><g id="g4493"><path id="path4489" d="M709.6 146.1h-.3c-.6 0-.8.3-.8 1.2v.9c0 2-1 3-3.3 3v-1.1c1.4-.1 1.8-.7 1.8-1.8v-.7c0-1.3.3-1.9 1.1-2.2-.8-.3-1.1-.9-1.1-2.2v-.7c0-1.1-.4-1.7-1.8-1.8v-1.1c2.3 0 3.3 1 3.3 3v.9c0 1 .2 1.2.8 1.2h.3v1.4z"/><path id="path4491" d="M708.8 168.2h-3.1V167h1.7v-9h-1.7v-1.2h3.1v11.4z"/></g><g id="g4499"><path id="path4495" d="M775.7 152.3h-1.3v-14h1.3v14z"/><path id="path4497" d="M777.9 168h-1.5l-4.4-12.5h1.5l4.4 12.5z"/></g><g id="g4503"><path id="path4501" d="M1034.6 149.8c-1.7 1.9-3.2 4.7-3.3 8.4h-1.5c.1-3.4 1.2-6.1 3.1-8.5h-5.2v-1.4h6.9v1.5z"/></g><g id="g4507"><path id="path4505" d="M1089.4 155.3c0 2-1.5 3-3.9 3s-3.9-1.1-3.9-3c0-1.2.6-2 1.8-2.5-1-.4-1.3-1.3-1.3-1.9 0-1.9 1.5-2.8 3.5-2.8 1.8 0 3.5.9 3.5 2.8 0 .6-.3 1.5-1.3 1.9.9.4 1.6 1.2 1.6 2.5zm-1.5 0c0-1-.8-1.7-2.4-1.7-1.6 0-2.4.6-2.4 1.6s.9 1.7 2.4 1.7c1.6.1 2.4-.6 2.4-1.6zm-.4-4.4c0-.8-.5-1.5-2-1.5-1.4 0-2 .7-2 1.4 0 .8.8 1.4 2 1.4 1.3 0 2-.6 2-1.3z"/></g><g id="g4511"><path id="path4509" d="M1143.2 152c0 2.6-1.4 6.1-6.2 6.3v-1.4c2.3-.1 3.8-1.1 4.5-3.2-.7.6-1.4.8-2.6.8-1.8 0-3.3-1-3.3-3.1 0-2.2 1.7-3.3 3.9-3.3 2.1 0 3.7 1.1 3.7 3.9zm-1.5-.6c0-1-.8-1.8-2.3-1.8-1.5 0-2.3.7-2.3 1.8 0 1.2.8 1.7 2.3 1.7 1.4 0 2.3-.6 2.3-1.7z"/></g><g id="g4515"><path id="path4513" d="M1197.3 182h-3v3h-1.6v-3h-3v-1.6h3v-3h1.6v3h3v1.6z"/></g><g id="g4519"><path id="path4517" d="M131.4 212.2h-1.6l-.8-2.4h-4l-.8 2.4h-1.5l3.6-9.9h1.6l3.5 9.9zm-2.9-3.7-.8-2.3c-.2-.7-.6-1.9-.8-2.3-.1.4-.5 1.6-.7 2.3l-.8 2.3h3.1z"/></g><g id="g4523"><path id="path4521" d="M184.5 209.3c0 1.8-1.1 3-3.7 3-1.4 0-2.7-.6-3.5-1.6l1.1-1c.7.7 1.6 1.2 2.6 1.2 1.4 0 2.1-.5 2.1-1.4 0-.8-.6-1.1-2.2-1.6-2.1-.6-3.1-1.1-3.1-2.9 0-1.7 1.4-2.8 3.3-2.8 1.3 0 2.4.5 3.2 1.3l-1 1.1c-.6-.6-1.3-.9-2.3-.9-1.2 0-1.7.6-1.7 1.2 0 .7.5 1 2.2 1.5 1.8.5 3 1.2 3 2.9z"/></g><g id="g4527"><path id="path4525" d="M239 207.2c0 3.5-2.2 5-4.8 5h-2.7v-9.9h2.7c2.7-.1 4.8 1.4 4.8 4.9zm-1.5 0c0-2.1-1-3.5-3.3-3.5H233v7h1.2c2.3 0 3.3-1.4 3.3-3.5z"/></g><g id="g4531"><path id="path4529" d="M292.6 203.7h-4.9v2.6h2.8v1.5h-2.8v4.4h-1.5v-9.9h6.4v1.4z"/></g><g id="g4535"><path id="path4533" d="M347 208.3c0 2.6-1.6 4-3.8 4-2.6 0-4.2-2.1-4.2-5.1 0-3 1.6-5.1 4.2-5.1 1.6 0 2.7.7 3.4 1.9l-1.3.8c-.5-.8-1-1.2-2.1-1.2-1.7 0-2.7 1.4-2.7 3.6s.9 3.6 2.7 3.6c1.6 0 2.3-1.1 2.3-2.2h-1.6v-1.4h3.1v1.1z"/></g><g id="g4539"><path id="path4537" d="M400.8 212.2h-1.5v-4.4h-4.6v4.4h-1.5v-9.9h1.5v4h4.6v-4h1.5v9.9z"/></g><g id="g4543"><path id="path4541" d="M454.1 208.3c0 2.7-1.1 4.1-3.5 4.1-1.9 0-3-1-3.5-2.6l1.4-.4c.4 1 1 1.6 2.1 1.6 1.4 0 2-.8 2-2.7v-5.9h1.5v5.9z"/></g><g id="g4547"><path id="path4545" d="M509.3 212.2h-1.7l-2.8-5.1-1.8 2.2v2.9h-1.4v-9.9h1.4v5.2c.2-.3.8-1.1 1.1-1.5l2.9-3.7h1.7l-2.9 3.6 3.5 6.3z"/></g><g id="g4551"><path id="path4549" d="M562.5 212.2h-6.4v-9.9h1.5v8.5h4.9v1.4z"/></g><g id="g4557"><path id="path4553" d="M614.1 197.2c0 .6-.5 1.1-1.1 1.1-.6 0-1.1-.5-1.1-1.1s.5-1.1 1.1-1.1c.6 0 1.1.5 1.1 1.1zm0 5.5c0 .6-.5 1.1-1.1 1.1-.6 0-1.1-.5-1.1-1.1s.5-1.1 1.1-1.1c.6 0 1.1.5 1.1 1.1z"/><path id="path4555" d="M614.1 214.2c0 .6-.5 1.1-1.1 1.1-.6 0-1.1-.5-1.1-1.1s.5-1.1 1.1-1.1c.6 0 1.1.5 1.1 1.1zm-.1 4.5-1.1 3.8h-1l.2-3.8h1.9z"/></g><g id="g4563"><path id="path4559" d="m666.3 193.7-.2 3.6h-1.9l1.1-3.6h1zm3.3 0-.2 3.6h-1.9l1.1-3.6h1z"/><path id="path4561" d="m668 210.8-.2 3.6h-1.9l1.1-3.6h1z"/></g><g id="g4567"><path id="path4565" d="M1035.5 209.9h-1.3v2.2h-1.4V210h-5.4v-1.4l5.1-6.3h1.7v6.4h1.3v1.2zm-2.7-6c-.2.3-.6.8-.9 1.2l-1.9 2.4c-.3.4-.7.9-.9 1.1h3.7v-2.9c-.1-.5 0-1.4 0-1.8z"/></g><g id="g4571"><path id="path4569" d="M1089.1 208.8c0 2.4-1.6 3.5-3.9 3.5-1.3 0-2.4-.3-3.5-1l.7-1.2c.8.5 1.9.8 2.8.8 1.5 0 2.4-.8 2.4-2s-.8-1.8-2-1.8c-.8 0-1.4.2-1.9.6l-1.6-.6.3-4.8h6.1v1.4h-4.8l-.2 2.5c.6-.3 1.2-.5 2.1-.5 2.4 0 3.5 1.3 3.5 3.1z"/></g><g id="g4575"><path id="path4573" d="M1143.4 209c0 2.2-1.7 3.3-3.9 3.3-2.1 0-3.7-1.1-3.7-4 0-2.6 1.4-6.1 6.2-6.3v1.4c-2.3.1-3.8 1.1-4.5 3.2.7-.6 1.4-.8 2.6-.8 1.8.1 3.3 1.1 3.3 3.2zm-1.5.1c0-1.2-.8-1.7-2.3-1.7-1.4 0-2.3.6-2.3 1.7 0 1 .8 1.8 2.3 1.8 1.5 0 2.3-.7 2.3-1.8z"/></g><g id="g4579"><path id="path4577" d="M157.7 266.2h-7.5v-1.4l4.8-5.9c.3-.4.9-1 1.1-1.3h-5.7v-1.4h7.3v1.4l-4.8 5.9c-.3.4-.9 1-1.1 1.3h5.9v1.4z"/></g><g id="g4583"><path id="path4581" d="M212 266.2h-1.8l-1.1-1.9c-.4-.6-.9-1.6-1.1-2-.2.4-.7 1.4-1.1 2l-1.1 1.9h-1.7l3.1-5.1-2.9-4.8h1.8l.9 1.6c.3.6.9 1.7 1.1 2 .2-.4.7-1.4 1.1-2l.9-1.6h1.7L209 261l3 5.2z"/></g><g id="g4587"><path id="path4585" d="M265.8 264.4c-.7 1.2-1.9 1.9-3.4 1.9-2.6 0-4.2-2.1-4.2-5.1 0-3 1.6-5.1 4.2-5.1 1.6 0 2.7.7 3.4 1.9l-1.3.8c-.5-.8-1-1.2-2.1-1.2-1.7 0-2.7 1.4-2.7 3.6s.9 3.6 2.7 3.6c1 0 1.7-.4 2.2-1.2l1.2.8z"/></g><g id="g4591"><path id="path4589" d="m320.2 256.2-3.4 9.9h-1.6l-3.4-9.9h1.6l2.1 6.3.6 1.8c.1-.4.4-1.2.6-1.8l2-6.3h1.5z"/></g><g id="g4595"><path id="path4593" d="M373.8 263.1c0 2-1.2 3-3.4 3h-3.9v-9.9h4.1c1.7 0 2.8.9 2.8 2.6 0 1-.5 1.6-1.3 2 .9.2 1.7 1 1.7 2.3zm-1.8-4.2c0-.7-.4-1.3-1.4-1.3h-2.7v2.6h2.7c1 0 1.4-.6 1.4-1.3zm.4 4.3c0-1-.6-1.6-1.8-1.6h-2.7v3.3h2.7c1.3-.1 1.8-.8 1.8-1.7z"/></g><g id="g4599"><path id="path4597" d="M427.8 266.2h-1.4l-4-6.2c-.2-.4-.6-1-.7-1.2v7.4h-1.4v-9.9h1.5l3.8 6.1c.3.4.7 1.1.8 1.4v-7.4h1.4v9.8z"/></g><g id="g4603"><path id="path4601" d="M482.4 266.2H481v-6.9c-.1.3-.4 1-.6 1.6l-2.4 5.6-2.4-5.6c-.2-.6-.5-1.3-.6-1.6v6.9h-1.4v-9.9h1.5l2.2 5.3c.2.6.6 1.3.7 1.7.1-.4.4-1.1.7-1.7l2.2-5.3h1.6v9.9z"/></g><g id="g4609"><path id="path4605" d="m534 257-4.1-3.6v-1.2l4.1-3.6v1.8l-2.8 2.4 2.8 2.4v1.8z"/><path id="path4607" d="m533 272.7-1.1 3.8h-1l.2-3.8h1.9z"/></g><g id="g4615"><path id="path4611" d="M588.1 253.4 584 257v-1.8l2.8-2.4-2.8-2.4v-1.9l4.1 3.6v1.3z"/><path id="path4613" d="M587.1 273.7c0 .6-.5 1.1-1.1 1.1s-1.1-.5-1.1-1.1.5-1.1 1.1-1.1 1.1.5 1.1 1.1z"/></g><g id="g4621"><path id="path4617" d="M643.3 250.2c0 1.4-.6 2-1.8 2.7-.9.5-1.1.9-1.1 1.9h-1.5c0-1.7.3-2.2 1.9-3.1.7-.4 1-.7 1-1.4 0-.8-.7-1.2-1.9-1.2-1 0-1.8.4-2.5 1.1l-.9-1.1c.8-.8 2-1.5 3.5-1.5 1.9 0 3.3.9 3.3 2.6zm-2.6 6.6c0 .6-.5 1.1-1.1 1.1s-1.1-.5-1.1-1.1.5-1.1 1.1-1.1 1.1.5 1.1 1.1z"/><path id="path4619" d="m642.9 263.5-4.4 12.5H637l4.4-12.5h1.5z"/></g><g id="g4625"><path id="path4623" d="M912.4 259.8c-.1.2-.2.2-.4.2l-1.2-.4v8.6h-1.7v-8.6l-1.1.4c-.2.1-.3 0-.4-.2-.1-.1-.1-.2 0-.4l2.4-3.4 2.4 3.4c.1.2.1.3 0 .4z"/></g><g id="g4629"><path id="path4627" d="M1032.6 266.2h-1.5v-7.6h-1.8v-1c1-.1 1.9-.4 2-1.3h1.2v9.9z"/></g><g id="g4633"><path id="path4631" d="M1088.8 266.2h-7.1c.1-2.9 1.9-4.2 3.8-5.4 1.3-.8 1.7-1.2 1.7-1.9 0-.8-.5-1.3-1.9-1.3-.8 0-1.8.4-2.4 1l-1-1.1c.9-.8 2.2-1.3 3.4-1.3 2.1 0 3.4.9 3.4 2.7 0 1.5-.8 2.2-2.5 3.2-1.9 1.1-2.4 1.8-2.7 2.7h5.3v1.4z"/></g><g id="g4637"><path id="path4635" d="M1142.8 263.2c0 2-1.4 3.1-3.7 3.1-1.4 0-2.9-.6-3.6-1.6l1.1-1c.6.8 1.5 1.1 2.4 1.1 1.6 0 2.2-.6 2.2-1.6s-.8-1.5-1.8-1.5h-.9v-1.4h.9c.9 0 1.4-.6 1.4-1.4 0-.6-.4-1.4-1.9-1.4-.8 0-1.4.3-2 .9l-1.1-1c.8-.9 1.8-1.3 3.1-1.3 1.9 0 3.4 1 3.4 2.7 0 1.2-.5 1.8-1.2 2.2 1.1.2 1.7 1 1.7 2.2z"/></g><g id="g4641"><path id="path4639" d="M861.2 317.2h-7.1l.4 1.1c.1.2 0 .3-.2.4-.1.1-.2.1-.4 0l-3.7-2.4 3.7-2.4c.2-.1.3-.1.4-.1.2.1.2.2.2.4l-.4 1.2h7.1v1.8z"/></g><g id="g4645"><path id="path4643" d="M912.4 318.8c.1.1.1.2-.1.4l-2.4 3.4-2.4-3.4c-.1-.2-.1-.3 0-.4.1-.2.2-.2.4-.2l1.1.4v-8.6h1.7v8.6l1.2-.3c.3-.2.4-.1.5.1z"/></g><g id="g4649"><path id="path4647" d="m969.7 316.4-3.7 2.4c-.2.1-.3.1-.4 0-.2-.1-.2-.2-.2-.4l.4-1.1h-7.1v-1.7h7.1l-.4-1.2c-.1-.2 0-.3.2-.4.1-.1.2-.1.4.1l3.7 2.3z"/></g><g id="g4653"><path id="path4651" d="M1062.4 315.2c0 3-1.4 5.1-3.9 5.1s-3.9-2.1-3.9-5.1 1.4-5.1 3.9-5.1c2.6 0 3.9 2.1 3.9 5.1zm-1.5 0c0-2.1-.7-3.7-2.4-3.7s-2.4 1.6-2.4 3.7.7 3.7 2.4 3.7c1.8 0 2.4-1.6 2.4-3.7z"/></g><g id="g4657"><path id="path4655" d="M1140.6 319.2c0 .6-.5 1.1-1.1 1.1-.6 0-1.1-.5-1.1-1.1s.5-1.1 1.1-1.1c.6 0 1.1.5 1.1 1.1z"/></g><path id="path4659" d="M32.5 19.3c1.5 0 2.8.5 3.8 1.6 1 1 1.6 2.3 1.6 3.8s-.5 2.7-1.6 3.8c-1 1.1-2.3 1.6-3.8 1.6s-2.7-.5-3.8-1.6c-1.1-1.1-1.6-2.3-1.6-3.8h1c0 1.2.4 2.2 1.3 3.1s1.9 1.3 3.1 1.3c1.2 0 2.2-.4 3.1-1.3.9-.9 1.3-1.9 1.3-3.1 0-1.2-.4-2.2-1.3-3.1-.9-.9-1.9-1.3-3.1-1.3v-1zm.4 5-.7.7-3.7-3.7-1.3 1.3v-3.4h3.4l-1.3 1.3 3.6 3.8z"/><g id="g4667"><path id="path4661" d="M28.2 44h-5.3v-8H28v1.2h-3.9v2h2.3v1.2h-2.3v2.5h4.1V44z"/><path id="path4663" d="M35 41.7c0 1.4-.9 2.4-2.9 2.4-1.2 0-2.2-.5-2.8-1.3l.9-.8c.5.6 1.3.9 2.1.9 1.1 0 1.6-.4 1.6-1.2 0-.6-.5-.9-1.8-1.3-1.7-.5-2.5-.9-2.5-2.3s1.2-2.2 2.6-2.2c1.1 0 1.9.4 2.6 1.1l-.8.9c-.5-.5-1.1-.8-1.8-.8-.9 0-1.3.5-1.3 1 0 .6.4.8 1.7 1.2 1.4.5 2.4 1 2.4 2.4z"/><path id="path4665" d="M42.5 42.6c-.6 1-1.5 1.5-2.7 1.5-2.1 0-3.4-1.7-3.4-4.1 0-2.4 1.3-4.1 3.4-4.1 1.3 0 2.2.5 2.7 1.5l-1.1.7c-.4-.6-.8-1-1.6-1-1.4 0-2.1 1.1-2.1 2.9 0 1.8.7 2.9 2.1 2.9.8 0 1.3-.3 1.7-1l1 .7z"/></g><path id="path4669" d="M860.2 20.1c.1.3.1.6.2 1 0 .4.1.9.1 1.4v.7c0 .2 0 .5-.1.7s-.1.4-.1.6-.1.3-.1.4v.1c-.2.1-.5.2-.8.3-.3.1-.6.2-1 .3-.4.1-.7.1-1.1.2-.4 0-.8.1-1.2.1-.4 0-.8 0-1.2-.1s-.8-.1-1.1-.2-.7-.2-1-.3c-.3-.1-.5-.2-.7-.3h-.1v-.1c0-.1-.1-.3-.1-.5s-.1-.4-.1-.6c0-.2-.1-.4-.1-.7v-.7c0-.5 0-1 .1-1.4s.1-.8.2-1v-.1h.1c.3-.2.8-.3 1.3-.5s1.1-.3 1.8-.3l1.1-1.1h1.4v1.2c.5.1 1 .2 1.4.3.4.1.8.3 1 .5l.1.1zm-2 .1c-.1 0-.2 0-.3-.1-.1 0-.2-.1-.3-.1v2.7H854v-2.5l.3-.3c-.4.1-.7.1-1 .2s-.5.2-.7.3l-.1.7c0 .2-.1.4-.1.7v.7c0 .4 0 .8.1 1.2s.1.6.2.9l.6.3c.2.1.5.2.8.2.3.1.6.1 1 .1h2c.3 0 .7-.1.9-.1s.6-.1.8-.2l.6-.3c.1-.2.1-.5.2-.9s.1-.7.1-1.2 0-.8-.1-1.1c0-.4-.1-.6-.2-.9-.2-.1-.4-.1-.6-.2-.2 0-.4-.1-.6-.1zm-3.9.2v2.1h3.1v-4.1h-1v2h-2.1zm.2-.2h1.6v-1.6l-1.6 1.6zm3-.2c.1 0 .1 0 0 0 .1 0 .1 0 0 0z"/><g id="g4693"><path id="path4671" d="M848.6 31.9c0 1.2-.8 1.9-2 1.9H845V36h-.9v-6h2.5c1.2 0 2 .7 2 1.9zm-.9 0c0-.7-.4-1-1-1H845v2h1.6c.7 0 1.1-.4 1.1-1z"/><path id="path4673" d="M854.2 31.8c0 1-.5 1.5-1.3 1.7l1.2 2.4h-1l-1.2-2.4h-1.3V36h-.9v-6h2.6c1.1 0 1.9.6 1.9 1.8zm-.9 0c0-.6-.4-1-1-1h-1.7v1.9h1.7c.6.1 1-.2 1-.9z"/><path id="path4675" d="M856.6 36h-.9v-6h.9v6z"/><path id="path4677" d="M862.7 36h-.8l-2.4-3.7c-.1-.2-.3-.6-.4-.7V36h-.9v-6h.9l2.3 3.6c.2.2.4.7.5.8V30h.9v6z"/><path id="path4679" d="M868.2 30.9h-1.7V36h-.9v-5.1h-1.7V30h4.4v.9z"/><path id="path4681" d="M844.1 44.5c0 1.1-.7 1.8-2.2 1.8-.9 0-1.6-.4-2.1-1l.6-.6c.4.4 1 .7 1.5.7.8 0 1.2-.3 1.2-.9 0-.5-.3-.7-1.3-1-1.3-.4-1.9-.7-1.9-1.8 0-1 .9-1.7 2-1.7.8 0 1.4.3 1.9.8l-.6.6c-.4-.4-.8-.6-1.4-.6-.7 0-1 .3-1 .7 0 .4.3.6 1.3.9 1.3.6 2 1 2 2.1z"/><path id="path4683" d="M849.7 45.1c-.4.7-1.1 1.1-2 1.1-1.5 0-2.5-1.3-2.5-3.1s1-3.1 2.5-3.1c1 0 1.6.4 2 1.1l-.8.5c-.3-.5-.6-.7-1.2-.7-1 0-1.6.8-1.6 2.2s.6 2.2 1.6 2.2c.6 0 1-.3 1.3-.7l.7.5z"/><path id="path4685" d="M855.5 42c0 1-.5 1.5-1.3 1.7l1.2 2.4h-1l-1.2-2.4h-1.3v2.4h-.9v-5.9h2.6c1 0 1.9.6 1.9 1.8zm-.9 0c0-.6-.4-1-1-1h-1.7v2h1.7c.6 0 1-.3 1-1z"/><path id="path4687" d="M860.8 46.2h-4v-5.9h3.8v.9h-2.9v1.5h1.7v.9h-1.7v1.9h3.1v.7z"/><path id="path4689" d="M866.1 46.2h-4v-5.9h3.8v.9H863v1.5h1.7v.9H863v1.9h3.1v.7z"/><path id="path4691" d="M871.9 46.2h-.9l-2.4-3.7c-.1-.2-.3-.6-.4-.7v4.5h-.9v-5.9h.9l2.3 3.6c.2.2.4.7.5.8v-4.5h.9v5.9z"/></g><path id="path4695" d="M912.7 19.8h-.9l-.5-.4v5.3l.5-.4h.9l-2.7 2.2-2.7-2.1h.9l.5.4v-5.3l-.5.4h-.9l2.7-2.1 2.7 2zm-2.1-1-.5-.4-.5.4v6.4l.5.4.5-.4v-6.4z"/><g id="g4717"><path id="path4697" d="M898.4 34.3c0 1.1-.7 1.8-2.2 1.8-.9 0-1.6-.4-2.1-1l.6-.6c.4.4 1 .7 1.5.7.8 0 1.2-.3 1.2-.9 0-.5-.3-.7-1.3-1-1.3-.4-1.9-.7-1.9-1.8 0-1 .9-1.7 2-1.7.8 0 1.4.3 1.9.8l-.6.6c-.4-.4-.8-.6-1.4-.6-.7 0-1 .3-1 .7 0 .4.3.6 1.3.9 1.2.6 2 1 2 2.1z"/><path id="path4699" d="M904 34.9c-.4.7-1.1 1.1-2 1.1-1.5 0-2.5-1.3-2.5-3.1s1-3.1 2.5-3.1c1 0 1.6.4 2 1.1l-.8.5c-.3-.5-.6-.7-1.2-.7-1 0-1.6.8-1.6 2.2s.6 2.2 1.6 2.2c.6 0 1-.3 1.3-.7l.7.5z"/><path id="path4701" d="M909.8 31.8c0 1-.5 1.5-1.3 1.7l1.2 2.4h-1l-1.2-2.4h-1.3V36h-.9v-6h2.6c1 0 1.9.6 1.9 1.8zm-.9 0c0-.6-.4-1-1-1h-1.7v1.9h1.7c.5.1 1-.2 1-.9z"/><path id="path4703" d="M915.8 33c0 1.9-1 3.1-2.5 3.1s-2.5-1.2-2.5-3.1c0-1.9 1-3.1 2.5-3.1s2.5 1.2 2.5 3.1zm-.9 0c0-1.4-.7-2.2-1.6-2.2-.9 0-1.6.8-1.6 2.2 0 1.4.7 2.2 1.6 2.2.9 0 1.6-.8 1.6-2.2z"/><path id="path4705" d="M920.9 36H917v-6h.9v5.1h3v.9z"/><path id="path4707" d="M926 36h-3.9v-6h.9v5.1h3v.9z"/><path id="path4709" d="M903.5 46.2h-3.9v-5.9h.9v5.1h3v.8z"/><path id="path4711" d="M909.2 43.2c0 1.9-1 3.1-2.5 3.1s-2.5-1.2-2.5-3.1c0-1.9 1-3.1 2.5-3.1s2.5 1.2 2.5 3.1zm-.9 0c0-1.4-.7-2.2-1.6-2.2-.9 0-1.6.8-1.6 2.2 0 1.4.7 2.2 1.6 2.2 1 0 1.6-.8 1.6-2.2z"/><path id="path4713" d="M914.8 45.1c-.4.7-1.1 1.1-2 1.1-1.5 0-2.5-1.3-2.5-3.1s1-3.1 2.5-3.1c1 0 1.6.4 2 1.1l-.8.5c-.3-.5-.6-.7-1.2-.7-1 0-1.6.8-1.6 2.2s.6 2.2 1.6 2.2c.6 0 1-.3 1.3-.7l.7.5z"/><path id="path4715" d="M920.8 46.2h-1l-1.7-3.1-1.1 1.3v1.7h-.9v-5.9h.9v3.1c.1-.2.5-.6.7-.9l1.8-2.2h1l-1.7 2.2 2 3.8z"/></g><path id="path4719" d="M961.2 22c0 .3 0 .7-.1 1-.1.3-.2.6-.4.9-.2.3-.4.5-.6.8-.2.2-.5.4-.8.6-.3.2-.6.3-.9.4-.3.1-.7.1-1 .1-.3 0-.7 0-1-.1-.3-.1-.6-.2-.9-.4-.3-.2-.5-.4-.8-.6-.2-.2-.4-.5-.6-.8-.2-.3-.3-.6-.4-.9-.1-.3-.1-.7-.1-1 0-.4 0-.7.1-1 .1-.3.2-.6.4-.9.2-.3.4-.5.6-.8.2-.2.5-.4.8-.6.3-.2.6-.3.9-.4.3-.1.7-.1 1-.1.3 0 .7 0 1 .1.3.1.6.2.9.4s.5.4.8.6c.2.2.4.5.6.8.2.3.3.6.4.9s.1.7.1 1zm-1.6.4-2.2 2.4-2.2-2.4h-.8c0 .4.1.7.3 1.1.2.3.4.6.6.8l.9.6c.3.1.7.2 1.1.2.4 0 .8-.1 1.1-.2.4-.1.7-.3.9-.6s.5-.5.6-.8c.2-.3.3-.7.3-1.1h-.6zm.8-.9c0-.4-.1-.7-.3-1-.2-.3-.4-.6-.7-.8s-.6-.4-.9-.5c-.3-.1-.7-.2-1.1-.2-.4 0-.8.1-1.1.2-.3.1-.6.3-.9.5s-.5.5-.7.8c-.2.3-.3.6-.3 1h1l1.9 2.1 1.9-2.1h1.2z"/><path id="path4721" d="M974 22c0 .3 0 .7-.1 1s-.2.6-.4.9-.4.5-.6.8c-.2.2-.5.4-.8.6-.3.2-.6.3-.9.4-.3.1-.7.1-1 .1s-.7 0-1-.1-.6-.2-.9-.4c-.3-.2-.5-.4-.8-.6-.2-.2-.4-.5-.6-.8s-.3-.6-.4-.9-.1-.7-.1-1 0-.7.1-1 .2-.6.4-.9c.2-.3.4-.5.6-.8.2-.2.5-.4.8-.6.3-.2.6-.3.9-.4.3-.1.7-.1 1-.1s.7 0 1 .1c.3.1.6.2.9.4.3.2.5.4.8.6.2.2.4.5.6.8.2.3.3.6.4.9 0 .3.1.7.1 1zm-.8 0c0-.3 0-.5-.1-.8s-.2-.5-.3-.7-.3-.4-.5-.6-.4-.3-.6-.5c-.2-.1-.5-.2-.7-.3-.3-.1-.5-.1-.8-.1-.4 0-.8.1-1.2.2-.4.2-.7.4-1 .7s-.5.6-.7 1c-.2.4-.2.8-.2 1.2s.1.8.2 1.2c.2.4.4.7.7 1s.6.5 1 .7c.4.2.8.2 1.2.2.4 0 .8-.1 1.2-.2.4-.2.7-.4 1-.7s.5-.6.7-1 .1-.9.1-1.3zm-5.7-1.4h5.4l-2.7 4.5-2.7-4.5zm4.6.5h-3.8l1.9 3.2 1.9-3.2z"/><g id="g4733"><path id="path4723" d="M955.5 32.2c0 1.2-.8 1.9-2 1.9H952v2.2h-.9v-5.9h2.5c1.1-.1 1.9.5 1.9 1.8zm-.9 0c0-.7-.4-1-1-1H952v2h1.6c.7 0 1-.4 1-1z"/><path id="path4725" d="M960.9 36.2h-1l-.5-1.4H957l-.5 1.4h-.9l2.1-5.9h.9l2.3 5.9zm-1.7-2.2-.5-1.4c-.1-.4-.4-1.1-.5-1.4-.1.3-.3.9-.4 1.4l-.5 1.4h1.9z"/><path id="path4727" d="M966.4 33.8c0 1.7-.8 2.6-2.3 2.6-1.5 0-2.2-1-2.2-2.6v-3.5h.9v3.4c0 1.1.5 1.7 1.4 1.7.9 0 1.4-.6 1.4-1.7v-3.5h.9v3.6z"/><path id="path4729" d="M971.9 34.5c0 1.1-.7 1.8-2.2 1.8-.9 0-1.6-.4-2.1-1l.6-.6c.4.4 1 .7 1.5.7.8 0 1.2-.3 1.2-.9 0-.5-.3-.7-1.3-1-1.3-.4-1.9-.7-1.9-1.8 0-1 .9-1.7 2-1.7.8 0 1.4.3 1.9.8l-.6.6c-.4-.4-.8-.6-1.4-.6-.7 0-1 .3-1 .7 0 .4.3.6 1.3.9 1.2.7 2 1.1 2 2.1z"/><path id="path4731" d="M977.2 36.2h-4v-5.9h3.8v.9h-2.9v1.5h1.7v.9h-1.7v1.9h3.1v.7z"/></g><g id="g4745"><path id="path4735" d="M954.8 44.6c0 1.2-.7 1.8-2 1.8h-2.4v-5.9h2.4c1 0 1.7.5 1.7 1.5 0 .6-.3 1-.8 1.2.6.2 1.1.6 1.1 1.4zm-1.1-2.5c0-.4-.2-.8-.8-.8h-1.6v1.5h1.6c.5.1.8-.3.8-.7zm.2 2.6c0-.6-.4-1-1.1-1h-1.6v2h1.6c.8-.1 1.1-.5 1.1-1z"/><path id="path4737" d="M960.7 42.3c0 1-.5 1.5-1.3 1.7l1.2 2.4h-1l-1.2-2.4H957v2.4h-.9v-5.9h2.6c1.1 0 2 .6 2 1.8zm-.9 0c0-.6-.4-1-1-1H957v1.9h1.7c.6.1 1.1-.2 1.1-.9z"/><path id="path4739" d="M966 46.5h-4v-5.9h3.8v.9h-2.9V43h1.7v.9h-1.7v1.9h3.1v.7z"/><path id="path4741" d="M972.1 46.5h-1l-.5-1.4h-2.4l-.5 1.4h-.9l2.1-5.9h.9l2.3 5.9zm-1.7-2.3-.5-1.4c-.1-.4-.4-1.1-.5-1.4-.1.3-.3.9-.4 1.4l-.5 1.4h1.9z"/><path id="path4743" d="M978 46.5h-1l-1.7-3.1-1.1 1.3v1.7h-.9v-5.9h.9v3.1c.1-.2.5-.6.7-.9l1.8-2.2h1l-1.7 2.2 2 3.8z"/></g><path id="path4747" d="m759.2 97.2-5.1-5.1 5.1-5.1h9.5v10.2h-9.5zm-3.7-5.1 4.1 4.1h8.1V88h-8.1l-4.1 4.1zm7.2.7-2.3 2.3-.7-.7 2.3-2.3-2.3-2.3.7-.7 2.3 2.3 2.3-2.3.7.7-2.3 2.3 2.3 2.3-.7.7-2.3-2.3z"/><g id="g4767"><path id="path4749" d="M735.4 109c0 1.6-1 2.4-2.7 2.4h-3.2v-7.9h3.3c1.4 0 2.3.7 2.3 2.1 0 .8-.4 1.3-1 1.6.6.1 1.3.7 1.3 1.8zm-1.5-3.4c0-.6-.3-1-1.1-1h-2.1v2.1h2.1c.8-.1 1.1-.6 1.1-1.1zm.3 3.4c0-.8-.5-1.3-1.4-1.3h-2.2v2.6h2.1c1.2 0 1.5-.5 1.5-1.3z"/><path id="path4751" d="M743.5 111.4h-1.3l-.7-1.9h-3.2l-.7 1.9h-1.2l2.9-7.9h1.3l2.9 7.9zm-2.3-3-.6-1.8-.6-1.8-.6 1.8-.6 1.8h2.4z"/><path id="path4753" d="M750.5 110c-.6 1-1.5 1.5-2.7 1.5-2.1 0-3.4-1.7-3.4-4.1 0-2.4 1.3-4.1 3.4-4.1 1.3 0 2.2.5 2.7 1.5l-1.1.7c-.4-.6-.8-1-1.6-1-1.4 0-2.1 1.1-2.1 2.9 0 1.8.7 2.9 2.1 2.9.8 0 1.3-.3 1.7-1l1 .7z"/><path id="path4755" d="M758.5 111.4h-1.3l-2.3-4.1-1.5 1.8v2.3h-1.2v-7.9h1.2v4.1c.1-.2.7-.9.9-1.2l2.3-2.9h1.3l-2.3 2.9 2.9 5z"/><path id="path4757" d="M764.9 109.1c0 1.4-.9 2.4-2.9 2.4-1.2 0-2.2-.5-2.8-1.3l.8-.8c.5.6 1.3.9 2.1.9 1.1 0 1.6-.4 1.6-1.2 0-.6-.5-.9-1.8-1.3-1.7-.5-2.5-.9-2.5-2.3s1.2-2.2 2.6-2.2c1.1 0 1.9.4 2.6 1.1l-.8.9c-.5-.5-1.1-.8-1.8-.8-.9 0-1.3.5-1.3 1 0 .6.4.8 1.7 1.2 1.5.5 2.5 1 2.5 2.4z"/><path id="path4759" d="M772.5 105.9c0 1.6-1.1 2.5-2.6 2.5h-2.1v3h-1.2v-7.9h3.3c1.6 0 2.6.8 2.6 2.4zm-1.2 0c0-.9-.5-1.4-1.4-1.4h-2.1v2.7h2.1c1 .1 1.4-.4 1.4-1.3z"/><path id="path4761" d="M779.8 111.4h-1.3l-.7-1.9h-3.2l-.7 1.9h-1.2l2.9-7.9h1.3l2.9 7.9zm-2.3-3-.6-1.8-.6-1.8-.6 1.8-.6 1.8h2.4z"/><path id="path4763" d="M786.8 110c-.6 1-1.5 1.5-2.7 1.5-2.1 0-3.4-1.7-3.4-4.1 0-2.4 1.3-4.1 3.4-4.1 1.3 0 2.2.5 2.7 1.5l-1.1.7c-.4-.6-.8-1-1.6-1-1.4 0-2.1 1.1-2.1 2.9 0 1.8.7 2.9 2.1 2.9.8 0 1.3-.3 1.7-1l1 .7z"/><path id="path4765" d="M793.8 111.4h-5.3v-7.9h5.1v1.2h-3.9v2h2.3v1.2h-2.3v2.5h4.1v1z"/></g><path id="path4769" d="M848.5 87.9h1.5l5.9 6.3 5.9-6.3h1.6l-7.5 7.9-7.4-7.9zm8.3 3.2c-.1-.2-.1-.4-.1-.5-.3.3-.5.5-.7.5-.2.1-.4.1-.6.1-.3 0-.6-.1-.8-.3s-.3-.5-.3-.8c0-.4.2-.7.5-.9.3-.2.9-.4 1.6-.5l.4-.1v-.4c0-.2-.1-.4-.2-.5-.2-.1-.4-.1-.6-.1-.3 0-.5.1-.6.2-.2.1-.2.3-.2.4v.1h-.7v-.1c0-.2.1-.3.2-.5s.3-.3.6-.4.5-.1.8-.1c.3 0 .5 0 .8.1.2.1.4.2.5.4.1.2.2.4.2.8v2c0 .2.1.4.1.6h-.9zm-.1-1.9h-.2c-.7.2-1.1.3-1.3.5-.2.1-.3.3-.3.5 0 .1 0 .2.1.3.1.1.1.2.2.2.1.1.2.1.3.1.2 0 .4-.1.5-.2.2-.1.3-.2.4-.4.1-.2.1-.4.1-.6v-.4z"/><g id="g4783"><path id="path4771" d="M838.3 111.2h-1.2v-7.9h1.2v7.9z"/><path id="path4773" d="M846.4 111.2h-1.1l-3.2-5c-.2-.3-.5-.8-.6-1v5.9h-1.2v-7.9h1.2l3 4.8c.2.3.5.9.7 1.1v-6h1.2v8.1z"/><path id="path4775" d="M853.8 109c0 1.4-.9 2.4-2.9 2.4-1.2 0-2.2-.5-2.8-1.3l.8-.8c.5.6 1.3.9 2.1.9 1.1 0 1.6-.4 1.6-1.2 0-.6-.5-.9-1.8-1.3-1.7-.5-2.5-.9-2.5-2.3s1.2-2.2 2.6-2.2c1.1 0 1.9.4 2.6 1.1l-.8.9c-.5-.5-1.1-.8-1.8-.8-.9 0-1.3.5-1.3 1 0 .6.4.8 1.7 1.2 1.5.5 2.5 1 2.5 2.4z"/><path id="path4777" d="M860.9 111.2h-5.3v-7.9h5.1v1.2h-3.9v2h2.3v1.2h-2.3v2.5h4.1v1z"/><path id="path4779" d="M868.6 105.7c0 1.3-.7 2.1-1.7 2.3l1.6 3.2h-1.4l-1.6-3.1h-1.8v3.1h-1.2v-7.9h3.5c1.4 0 2.6.7 2.6 2.4zm-1.2 0c0-.8-.5-1.3-1.3-1.3h-2.3v2.6h2.3c.7 0 1.3-.4 1.3-1.3z"/><path id="path4781" d="M875.5 104.5h-2.3v6.8H872v-6.8h-2.3v-1.2h5.8v1.2z"/></g><path id="path4785" d="M913.8 87.9v.5h-7.1v7.1h-.5v-7.6h7.6zm-6 2 .4-.4h2.9v.9h-1.6l4.3 4.3-.8.8-4.3-4.3v1.6h-.9v-2.9z"/><g id="g4795"><path id="path4787" d="M900.9 110.4h-1.2v-3.5H896v3.5h-1.2v-7.9h1.2v3.2h3.7v-3.2h1.2v7.9z"/><path id="path4789" d="M909.4 106.5c0 2.5-1.4 4.1-3.4 4.1s-3.4-1.6-3.4-4.1c0-2.5 1.4-4.1 3.4-4.1s3.4 1.6 3.4 4.1zm-1.2 0c0-1.8-.9-2.9-2.2-2.9-1.3 0-2.1 1.1-2.1 2.9s.9 2.9 2.2 2.9c1.2 0 2.1-1.1 2.1-2.9z"/><path id="path4791" d="M918.1 110.4H917v-5.6c-.1.2-.3.8-.5 1.2l-1.9 4.5-1.9-4.5c-.2-.5-.4-1-.5-1.2v5.6H911v-7.9h1.2l1.8 4.2c.2.5.4 1 .5 1.4.1-.3.3-.9.5-1.4l1.7-4.2h1.3v7.9z"/><path id="path4793" d="M925.5 110.4h-5.3v-7.9h5.1v1.2h-3.9v2h2.3v1.2h-2.3v2.5h4.1v1z"/></g><path id="path4797" d="M964.5 92.3h1.8v1h-1.8v1.2h1.8v1h-1.8v2.7h-1v-2.7h-1.8v-1h1.8v-1.2h-1.8v-1h1.8v-2.1H961l3-3 3 3h-2.5v2.1z"/><g id="g4807"><path id="path4799" d="M954.4 105.9c0 1.6-1.1 2.4-2.6 2.4h-2v2.9h-1.1v-7.7h3.2c1.4-.1 2.5.8 2.5 2.4zm-1.2 0c0-.9-.5-1.3-1.3-1.3h-2.1v2.7h2.1c.9-.1 1.3-.6 1.3-1.4z"/><path id="path4801" d="M961.7 108.2c0 2-1.2 3.2-2.9 3.2-2 0-3.3-1.6-3.3-4s1.3-4 3.3-4c1.3 0 2.1.5 2.6 1.4l-1 .6c-.4-.6-.8-.9-1.6-.9-1.3 0-2.1 1.1-2.1 2.8s.7 2.8 2.1 2.8c1.3 0 1.8-.8 1.8-1.7h-1.3v-1.1h2.4v.9z"/><path id="path4803" d="M972.2 108c0 2.2-1.1 3.4-3 3.4s-2.9-1.2-2.9-3.4v-4.5h1.2v4.5c0 1.5.6 2.2 1.8 2.2 1.2 0 1.8-.8 1.8-2.2v-4.5h1.2v4.5z"/><path id="path4805" d="M979.9 105.9c0 1.6-1.1 2.4-2.6 2.4h-2v2.9h-1.1v-7.7h3.2c1.4-.1 2.5.8 2.5 2.4zm-1.2 0c0-.9-.5-1.3-1.3-1.3h-2.1v2.7h2.1c.8-.1 1.3-.6 1.3-1.4z"/></g><path id="path4809" d="M1030.1 91v-3.4h-1.2l2.6-2.6 2.6 2.6h-1.2V91h1.2v2h-5.2v-2h1.2zm1.2-5-1.1 1.1h.4v4.4h-1.2v1h1.9V86zm.4 0v6.5h1.9v-1h-1.2v-4.4h.4l-1.1-1.1z"/><path id="path4811" d="M1027.3 103.2h-.8l-2.4-3.7c-.1-.2-.3-.6-.4-.7v4.5h-.9v-5.9h.9l2.3 3.6c.2.2.4.7.5.8v-4.5h.9v5.9z"/><path id="path4813" d="M1033.4 100.7c0 1.7-.8 2.6-2.3 2.6-1.5 0-2.2-1-2.2-2.6v-3.5h.9v3.4c0 1.1.5 1.7 1.4 1.7.9 0 1.4-.6 1.4-1.7v-3.5h.9v3.6z"/><path id="path4815" d="M1040.2 103.2h-.9V99c-.1.2-.2.6-.4.9l-1.4 3.3-1.4-3.3c-.1-.3-.3-.8-.4-.9v4.1h-.8v-5.9h.9l1.3 3.2c.1.3.3.8.4 1 .1-.2.3-.7.4-1l1.3-3.2h1v6z"/><path id="path4817" d="M1025 113.4h-3.9v-5.9h.9v5.1h3v.8z"/><path id="path4819" d="M1030.7 110.4c0 1.9-1 3.1-2.5 3.1s-2.5-1.2-2.5-3.1c0-1.9 1-3.1 2.5-3.1s2.5 1.2 2.5 3.1zm-.9 0c0-1.4-.7-2.2-1.6-2.2-.9 0-1.6.8-1.6 2.2 0 1.4.7 2.2 1.6 2.2 1 0 1.6-.9 1.6-2.2z"/><path id="path4821" d="M1036.3 112.3c-.4.7-1.1 1.1-2 1.1-1.5 0-2.5-1.3-2.5-3.1s1-3.1 2.5-3.1c1 0 1.6.4 2 1.1l-.8.5c-.3-.5-.6-.7-1.2-.7-1 0-1.6.8-1.6 2.2s.6 2.2 1.6 2.2c.6 0 1-.3 1.3-.7l.7.5z"/><path id="path4823" d="M1042.3 113.4h-1l-1.7-3.1-1.1 1.3v1.7h-.9v-5.9h.9v3.1c.1-.2.5-.6.7-.9l1.8-2.2h1l-1.7 2.2 2 3.8z"/><path id="path4825" d="m44.2 141.3-1.9 2h10v.9h-10l1.9 2-.5.5-3.1-2.9v2.6h-.9V141h.9v2.6l3.1-2.9.5.6zm8.1 5.5v5.4h-.9v-2.6l-3.1 2.9-.5-.5 1.9-2h-10v-.9h10l-1.9-2 .5-.5 3.1 2.9v-2.6h.9z"/><g id="g4833"><path id="path4827" d="M41.6 158.9h-2.3v6.8h-1.2v-6.8h-2.3v-1.2h5.8v1.2z"/><path id="path4829" d="M48.6 165.6h-1.3l-.7-1.9h-3.2l-.7 1.9h-1.2l2.9-7.9h1.3l2.9 7.9zm-2.3-2.9-.6-1.8-.6-1.8-.6 1.8-.6 1.8h2.4z"/><path id="path4831" d="M56 163.2c0 1.6-1 2.4-2.7 2.4h-3.2v-7.9h3.3c1.4 0 2.3.7 2.3 2.1 0 .8-.4 1.3-1 1.6.6.1 1.3.7 1.3 1.8zm-1.5-3.4c0-.6-.3-1-1.1-1h-2.1v2.1h2.1c.8-.1 1.1-.6 1.1-1.1zm.4 3.4c0-.8-.5-1.3-1.4-1.3h-2.2v2.6h2.1c1.1 0 1.5-.5 1.5-1.3z"/></g><path id="path4835" d="M858.3 151.7h-9.5v-10.2h9.5l5.1 5.1-5.1 5.1zm3.7-5.1-4.1-4.1h-8.1v8.2h8.1l4.1-4.1zm-7.2.7-2.3 2.3-.7-.7 2.3-2.3-2.3-2.3.7-.7 2.3 2.3 2.3-2.3.7.7-2.3 2.3 2.3 2.3-.7.7-2.3-2.3z"/><g id="g4843"><path id="path4837" d="M852.4 161.3c0 2.8-1.8 4-3.9 4h-2.2v-7.9h2.2c2.1 0 3.9 1.1 3.9 3.9zm-1.3 0c0-1.7-.8-2.8-2.7-2.8h-1v5.6h1c2 .1 2.7-1.1 2.7-2.8z"/><path id="path4839" d="M859.3 165.3H854v-7.9h5.1v1.2h-3.9v2h2.3v1.2h-2.3v2.5h4.1v1z"/><path id="path4841" d="M866.1 165.3H861v-7.9h1.2v6.8h4v1.1z"/></g><path id="path4845" d="M911.8 148.6h-2.9v-.9h1.6l-4.3-4.3.8-.8 4.3 4.3v-1.6h.9v2.9l-.4.4zm2-5.9v7.6h-7.6v-.5h7.1v-7.1h.5z"/><g id="g4853"><path id="path4847" d="M904.9 165.3h-5.3v-7.9h5.1v1.2h-3.9v2h2.3v1.2h-2.3v2.5h4.1v1z"/><path id="path4849" d="M912.7 165.3h-1.1l-3.2-5c-.2-.3-.5-.8-.6-1v5.9h-1.2v-7.9h1.2l3 4.8c.2.3.5.9.7 1.1v-6h1.2v8.1z"/><path id="path4851" d="M920.7 161.3c0 2.8-1.8 4-3.9 4h-2.2v-7.9h2.2c2.2 0 3.9 1.1 3.9 3.9zm-1.2 0c0-1.7-.8-2.8-2.7-2.8h-1v5.6h1c2 .1 2.7-1.1 2.7-2.8z"/></g><path id="path4855" d="M963.5 147.4h-1.8v-1h1.8v-1.2h-1.8v-1h1.8v-2.7h1v2.7h1.8v1h-1.8v1.2h1.8v1h-1.8v2.1h2.5l-3 3-3-3h2.5v-2.1z"/><g id="g4865"><path id="path4857" d="M953.9 159.9c0 1.6-1.1 2.5-2.6 2.5h-2.1v3H948v-7.9h3.3c1.5-.1 2.6.7 2.6 2.4zm-1.2 0c0-.9-.5-1.4-1.4-1.4h-2.1v2.7h2.1c1 0 1.4-.5 1.4-1.3z"/><path id="path4859" d="M961.5 162.2c0 2-1.2 3.2-3 3.2-2.1 0-3.4-1.7-3.4-4.1 0-2.4 1.3-4.1 3.4-4.1 1.3 0 2.2.5 2.7 1.5l-1 .6c-.4-.6-.8-.9-1.7-.9-1.4 0-2.1 1.1-2.1 2.9 0 1.8.8 2.9 2.1 2.9s1.8-.9 1.8-1.8H959v-1.1h2.5v.9z"/><path id="path4861" d="M972.2 161.3c0 2.8-1.8 4-3.9 4h-2.2v-7.9h2.2c2.2 0 3.9 1.1 3.9 3.9zm-1.2 0c0-1.7-.8-2.8-2.7-2.8h-1v5.6h1c2 .1 2.7-1.1 2.7-2.8z"/><path id="path4863" d="M979.9 165.3h-1.1l-3.2-5c-.2-.3-.5-.8-.6-1v5.9h-1.2v-7.9h1.2l3 4.8c.2.3.5.9.7 1.1v-6h1.2v8.1z"/></g><path id="path4867" d="m47.2 200.4 5.6-5.6 5.6 5.6h-2.8v2.1H50v-2.1h-2.8zm5.6-4.4-3.7 3.7h1.7v2h4v-2h1.7l-3.7-3.7zm-2.8 8.1h5.6v2.8H50v-2.8zm.8.8v1.2h4v-1.2h-4z"/><g id="g4885"><path id="path4869" d="M28.3 218.2c-.6 1-1.5 1.5-2.7 1.5-2.1 0-3.4-1.7-3.4-4.1s1.3-4.1 3.4-4.1c1.3 0 2.2.5 2.7 1.5l-1.1.7c-.4-.6-.8-1-1.6-1-1.4 0-2.1 1.1-2.1 2.9 0 1.8.7 2.9 2.1 2.9.8 0 1.3-.3 1.7-1l1 .7z"/><path id="path4871" d="M36.3 219.5H35l-.7-1.9h-3.2l-.7 1.9h-1.2l2.9-7.9h1.3l2.9 7.9zm-2.3-2.9-.6-1.8-.6-1.8-.6 1.8-.6 1.8H34z"/><path id="path4873" d="M43.7 214.1c0 1.6-1.1 2.5-2.6 2.5H39v3h-1.2v-7.9h3.3c1.6-.1 2.6.8 2.6 2.4zm-1.2 0c0-.9-.5-1.4-1.4-1.4H39v2.7h2.1c1 .1 1.4-.5 1.4-1.3z"/><path id="path4875" d="M50.5 217.3c0 1.4-.9 2.4-2.9 2.4-1.2 0-2.2-.5-2.8-1.3l.9-.8c.5.6 1.3.9 2.1.9 1.1 0 1.6-.4 1.6-1.2 0-.6-.5-.9-1.8-1.3-1.7-.5-2.5-.9-2.5-2.3s1.2-2.2 2.6-2.2c1.1 0 1.9.4 2.6 1.1l-.8.8c-.5-.5-1.1-.8-1.8-.8-.9 0-1.3.5-1.3 1 0 .6.4.8 1.7 1.2 1.4.6 2.4 1.1 2.4 2.5z"/><path id="path4877" d="M60.5 219.5h-5.1v-7.9h1.2v6.8h4v1.1z"/><path id="path4879" d="M68.1 215.6c0 2.5-1.4 4.1-3.4 4.1s-3.4-1.6-3.4-4.1 1.4-4.1 3.4-4.1c2.1 0 3.4 1.6 3.4 4.1zm-1.2 0c0-1.8-.9-2.9-2.2-2.9-1.3 0-2.1 1.1-2.1 2.9s.9 2.9 2.2 2.9c1.2 0 2.1-1.1 2.1-2.9z"/><path id="path4881" d="M75.5 218.2c-.6 1-1.5 1.5-2.7 1.5-2.1 0-3.4-1.7-3.4-4.1s1.3-4.1 3.4-4.1c1.3 0 2.2.5 2.7 1.5l-1.1.7c-.4-.6-.8-1-1.6-1-1.4 0-2.1 1.1-2.1 2.9 0 1.8.7 2.9 2.1 2.9.8 0 1.3-.3 1.7-1l1 .7z"/><path id="path4883" d="M83.5 219.5h-1.3l-2.3-4.1-1.5 1.8v2.3h-1.2v-7.9h1.2v4.1c.1-.2.7-.9.9-1.2l2.3-2.9H83l-2.3 2.9 2.8 5z"/></g><path id="path4887" d="m748.9 200.5 3-3v2.5h7.1v-4.4h-3.5v-1h4.6v6.4H752v2.5l-3.1-3z"/><g id="g4901"><path id="path4889" d="M739 214.2c0 1.3-.7 2.1-1.7 2.3l1.6 3.2h-1.4l-1.6-3.1h-1.8v3.1h-1.2v-7.9h3.5c1.4 0 2.6.8 2.6 2.4zm-1.2.1c0-.8-.5-1.3-1.3-1.3h-2.3v2.6h2.3c.7-.1 1.3-.5 1.3-1.3z"/><path id="path4891" d="M746.1 219.8h-5.3v-7.9h5.1v1.2H742v2h2.3v1.2H742v2.5h4.1v1z"/><path id="path4893" d="M753.1 213h-2.3v6.8h-1.2V213h-2.3v-1.2h5.8v1.2z"/><path id="path4895" d="M760.6 216.5c0 2.2-1.1 3.4-3 3.4-2 0-3-1.3-3-3.5v-4.6h1.2v4.6c0 1.5.6 2.3 1.8 2.3 1.2 0 1.8-.8 1.8-2.2v-4.6h1.2v4.6z"/><path id="path4897" d="M768.7 214.2c0 1.3-.7 2.1-1.7 2.3l1.6 3.2h-1.4l-1.6-3.1h-1.8v3.1h-1.2v-7.9h3.5c1.4 0 2.6.8 2.6 2.4zm-1.2.1c0-.8-.5-1.3-1.3-1.3h-2.3v2.6h2.3c.7-.1 1.3-.5 1.3-1.3z"/><path id="path4899" d="M776.6 219.8h-1.1l-3.2-5c-.2-.3-.5-.8-.6-1v5.9h-1.2v-7.9h1.2l3 4.8c.2.3.5.9.7 1.1v-6h1.2v8.1z"/></g><path id="path4903" d="m60.4 254.4 5.9-5.9 5.9 5.9h-2.9v5.2h-5.9v-5.2h-3zm5.8-4.6-3.9 3.9h1.8v5.1h4.2v-5.1h1.8l-3.9-3.9z"/><g id="g4915"><path id="path4905" d="M56.6 271.5c0 1.4-.9 2.4-2.9 2.4-1.2 0-2.2-.5-2.8-1.3l.9-.8c.5.6 1.3.9 2.1.9 1.1 0 1.6-.4 1.6-1.2 0-.6-.5-.9-1.8-1.3-1.7-.5-2.5-.9-2.5-2.3s1.2-2.2 2.6-2.2c1.1 0 1.9.4 2.6 1.1l-.8.8c-.5-.5-1.1-.8-1.8-.8-.9 0-1.3.5-1.3 1 0 .6.4.8 1.7 1.2 1.4.6 2.4 1.1 2.4 2.5z"/><path id="path4907" d="M64.4 273.8h-1.2v-3.5h-3.7v3.5h-1.2v-7.9h1.2v3.2h3.7v-3.2h1.2v7.9z"/><path id="path4909" d="M67.7 273.8h-1.2v-7.9h1.2v7.9z"/><path id="path4911" d="M74.9 267.1H71v2.1h2.3v1.2H71v3.5h-1.2V266h5.1v1.1z"/><path id="path4913" d="M81.7 267.1h-2.3v6.8h-1.2v-6.8h-2.3v-1.2h5.8v1.2z"/></g><path id="path4917" d="m735.4 254.4 5.9-5.9 5.9 5.9h-2.9v5.2h-5.9v-5.2h-3zm5.8-4.6-3.9 3.9h1.8v5.1h4.2v-5.1h1.8l-3.9-3.9z"/><g id="g4929"><path id="path4919" d="M731.6 271.5c0 1.4-.9 2.4-2.9 2.4-1.2 0-2.2-.5-2.8-1.3l.8-.8c.5.6 1.3.9 2.1.9 1.1 0 1.6-.4 1.6-1.2 0-.6-.5-.9-1.8-1.3-1.7-.5-2.5-.9-2.5-2.3s1.2-2.2 2.6-2.2c1.1 0 1.9.4 2.6 1.1l-.8.8c-.5-.5-1.1-.8-1.8-.8-.9 0-1.3.5-1.3 1 0 .6.4.8 1.7 1.2 1.5.6 2.5 1.1 2.5 2.5z"/><path id="path4921" d="M739.4 273.8h-1.2v-3.5h-3.7v3.5h-1.2v-7.9h1.2v3.2h3.7v-3.2h1.2v7.9z"/><path id="path4923" d="M742.7 273.8h-1.2v-7.9h1.2v7.9z"/><path id="path4925" d="M749.9 267.1H746v2.1h2.3v1.2H746v3.5h-1.2V266h5.1v1.1z"/><path id="path4927" d="M756.7 267.1h-2.3v6.8h-1.2v-6.8h-2.3v-1.2h5.8v1.2z"/></g><path id="path4931" d="m1188.1 291.5 5.4-5.4 5.4 5.4-1 1-4.5-4.5-4.4 4.5-.9-1zm3.1-5.4v1.4h-3.2v-1.4h3.2zm7.7 0v1.4h-3.2v-1.4h3.2z"/><g id="g4943"><path id="path4933" d="M1181.4 326.4h-5.3v-7.9h5.1v1.2h-3.9v2h2.3v1.2h-2.3v2.5h4.1v1z"/><path id="path4935" d="M1189.1 326.4h-1.1l-3.2-5c-.2-.3-.5-.8-.6-1v5.9h-1.2v-7.9h1.2l3 4.8c.2.3.5.9.7 1.1v-6h1.2v8.1z"/><path id="path4937" d="M1196.5 319.7h-2.3v6.8h-1.2v-6.8h-2.3v-1.2h5.8v1.2z"/><path id="path4939" d="M1203.4 326.4h-5.3v-7.9h5.1v1.2h-3.9v2h2.3v1.2h-2.3v2.5h4.1v1z"/><path id="path4941" d="M1211.1 320.9c0 1.3-.7 2.1-1.7 2.3l1.6 3.2h-1.4l-1.6-3.1h-1.8v3.1h-1.2v-7.9h3.5c1.4 0 2.6.7 2.6 2.4zm-1.2 0c0-.8-.5-1.3-1.3-1.3h-2.3v2.6h2.3c.7 0 1.3-.4 1.3-1.3z"/></g><g id="g4959"><path id="path4945" d="M19.7 325c-.6 1-1.5 1.5-2.7 1.5-2.1 0-3.4-1.7-3.4-4.1s1.3-4.1 3.4-4.1c1.3 0 2.2.5 2.7 1.5l-1.1.7c-.4-.6-.8-1-1.6-1-1.4 0-2.1 1.1-2.1 2.9 0 1.8.7 2.9 2.1 2.9.8 0 1.3-.3 1.7-1l1 .7z"/><path id="path4947" d="M27.5 322.5c0 2.5-1.4 4.1-3.4 4.1s-3.4-1.6-3.4-4.1 1.4-4.1 3.4-4.1 3.4 1.6 3.4 4.1zm-1.2 0c0-1.8-.9-2.9-2.2-2.9-1.3 0-2.1 1.1-2.1 2.9s.9 2.9 2.2 2.9c1.2 0 2.1-1.1 2.1-2.9z"/><path id="path4949" d="M35.2 326.4h-1.1l-3.2-5c-.2-.3-.5-.8-.6-1v5.9h-1.2v-7.9h1.2l3 4.8c.2.3.5.9.7 1.1v-6h1.2v8.1z"/><path id="path4951" d="M42.6 319.7h-2.3v6.8h-1.2v-6.8h-2.3v-1.2h5.8v1.2z"/><path id="path4953" d="M50.2 320.9c0 1.3-.7 2.1-1.7 2.3l1.6 3.2h-1.4l-1.6-3.1h-1.8v3.1h-1.2v-7.9h3.5c1.4 0 2.6.7 2.6 2.4zm-1.2 0c0-.8-.5-1.3-1.3-1.3h-2.3v2.6h2.3c.7 0 1.3-.4 1.3-1.3z"/><path id="path4955" d="M58.2 322.5c0 2.5-1.4 4.1-3.4 4.1s-3.4-1.6-3.4-4.1 1.4-4.1 3.4-4.1 3.4 1.6 3.4 4.1zm-1.2 0c0-1.8-.9-2.9-2.2-2.9-1.3 0-2.1 1.1-2.1 2.9s.9 2.9 2.2 2.9c1.2 0 2.1-1.1 2.1-2.9z"/><path id="path4957" d="M65 326.4h-5.1v-7.9h1.2v6.8h4v1.1z"/></g><path id="path4961" d="M111 302.8v8.8h-8.7v-8.8h8.7zm-4.8 4v-3.2H103v3.2h3.2zm0 .8H103v3.2h3.2v-3.2zm.8-.8h3.3v-3.3H107v3.3zm0 .8v3.2h3.3v-3.2H107z"/><g id="g4969"><path id="path4963" d="m105.3 318.5-1.6 7.9h-1.2l-1.2-5.1c-.1-.3-.2-.9-.2-1.1 0 .2-.2.8-.2 1.1l-1.3 5.1h-1.2l-1.6-7.9H98l1 5c0 .2.1.8.2 1 0-.3.2-.8.2-1l1.3-5h1l1.3 5.1c.1.2.1.6.2.9.1-.3.1-.7.2-.9l1-5.1h.9z"/><path id="path4965" d="M108.2 326.4H107v-7.9h1.2v7.9z"/><path id="path4967" d="M116.3 326.4h-1.1l-3.2-5c-.2-.3-.5-.8-.6-1v5.9h-1.2v-7.9h1.2l3 4.8c.2.3.5.9.7 1.1v-6h1.2v8.1z"/></g><path id="path4971" d="M180.1 302v1H177l-4.6 9.2h-4v-1h3.2l4.6-9.2h3.9zm-4.7 10.3v-1h4.8v1h-4.8z"/><g id="g4979"><path id="path4973" d="M171.6 326.4h-1.3l-.7-1.9h-3.2l-.7 1.9h-1.2l2.9-7.9h1.3l2.9 7.9zm-2.3-2.9-.6-1.8-.6-1.8-.6 1.8-.6 1.8h2.4z"/><path id="path4975" d="M178.4 326.4h-5.1v-7.9h1.2v6.8h4v1.1z"/><path id="path4977" d="M183.9 319.7h-2.3v6.8h-1.2v-6.8H178v-1.2h5.8v1.2z"/></g><path id="path4981" d="M374.8 309.2v-2h.7v1.4h2.6v-1.4h.7v2h-4z"/><g id="g4993"><path id="path4983" d="M365.1 324.2c0 1.4-.9 2.4-2.9 2.4-1.2 0-2.2-.5-2.8-1.3l.9-.8c.5.6 1.3.9 2.1.9 1.1 0 1.6-.4 1.6-1.2 0-.6-.5-.9-1.8-1.3-1.7-.5-2.5-.9-2.5-2.3s1.2-2.2 2.6-2.2c1.1 0 1.9.4 2.6 1.1l-.8.8c-.5-.5-1.1-.8-1.8-.8-.9 0-1.3.5-1.3 1 0 .6.4.8 1.7 1.2 1.5.5 2.4 1 2.4 2.5z"/><path id="path4985" d="M372.8 321c0 1.6-1.1 2.5-2.6 2.5h-2.1v3h-1.2v-7.9h3.3c1.5-.1 2.6.7 2.6 2.4zm-1.2 0c0-.9-.5-1.4-1.4-1.4h-2.1v2.7h2.1c.9.1 1.4-.5 1.4-1.3z"/><path id="path4987" d="M380 326.4h-1.3l-.7-1.9h-3.2l-.7 1.9H373l2.9-7.9h1.3l2.8 7.9zm-2.3-2.9-.6-1.8-.6-1.8-.6 1.8-.6 1.8h2.4z"/><path id="path4989" d="M387.1 325c-.6 1-1.5 1.5-2.7 1.5-2.1 0-3.4-1.7-3.4-4.1s1.3-4.1 3.4-4.1c1.3 0 2.2.5 2.7 1.5l-1.1.7c-.4-.6-.8-1-1.6-1-1.4 0-2.1 1.1-2.1 2.9 0 1.8.7 2.9 2.1 2.9.8 0 1.3-.3 1.7-1l1 .7z"/><path id="path4991" d="M394.1 326.4h-5.3v-7.9h5.1v1.2H390v2h2.3v1.2H390v2.5h4.1v1z"/></g><path id="path4995" d="M573.4 311.2h3.2l4.6-9.2h4v1H582l-4.6 9.2h-4v-1zm7 0h4.8v1h-4.8v-1z"/><g id="g5003"><path id="path4997" d="M576.7 326.4h-1.3l-.7-1.9h-3.2l-.7 1.9h-1.2l2.9-7.9h1.3l2.9 7.9zm-2.3-2.9-.6-1.8-.6-1.8-.6 1.8-.6 1.8h2.4z"/><path id="path4999" d="M583.4 326.4h-5.1v-7.9h1.2v6.8h4v1.1z"/><path id="path5001" d="M588.9 319.7h-2.3v6.8h-1.2v-6.8H583v-1.2h5.8v1.2z"/></g><path id="path5005" d="M651.1 302.8v8.8h-8.7v-8.8h8.7zm-4.8 4v-3.2h-3.2v3.2h3.2zm0 .8h-3.2v3.2h3.2v-3.2zm.8-.8h3.3v-3.3h-3.3v3.3zm0 .8v3.2h3.3v-3.2h-3.3z"/><g id="g5013"><path id="path5007" d="m645.3 318.5-1.6 7.9h-1.2l-1.2-5.1c-.1-.3-.2-.9-.2-1.1 0 .2-.2.8-.2 1.1l-1.3 5.1h-1.2l-1.6-7.9h1.2l1 5c0 .2.1.8.2 1 0-.3.2-.8.2-1l1.3-5h1l1.3 5.1c.1.2.1.6.2.9.1-.3.1-.7.2-.9l1-5.1h.9z"/><path id="path5009" d="M648.2 326.4H647v-7.9h1.2v7.9z"/><path id="path5011" d="M656.3 326.4h-1.1l-3.2-5c-.2-.3-.5-.8-.6-1v5.9h-1.2v-7.9h1.2l3 4.8c.2.3.5.9.7 1.1v-6h1.2v8.1z"/></g><path id="path5015" d="M710.6 303.4h7.3v1.2h-7.3v-1.2zm0 2.5h7.3v1.2h-7.3v-1.2zm0 2.5h7.3v1.2h-7.3v-1.2zm0 2.5h7.3v1.2h-7.3v-1.2z"/><g id="g5025"><path id="path5017" d="M706.3 326.3h-1.2v-5.6c-.1.2-.3.8-.5 1.2l-1.9 4.5-1.9-4.5c-.2-.5-.4-1-.5-1.2v5.6h-1.1v-7.9h1.2l1.8 4.2c.2.5.4 1 .5 1.4.1-.3.3-.9.5-1.4l1.7-4.2h1.3v7.9z"/><path id="path5019" d="M713.6 326.3h-5.3v-7.9h5.1v1.2h-3.9v2h2.3v1.2h-2.3v2.5h4.1v1z"/><path id="path5021" d="M721.3 326.3h-1.1l-3.2-5c-.2-.3-.5-.8-.6-1v5.9h-1.2v-7.9h1.2l3 4.8c.2.3.5.9.7 1.1v-6h1.2v8.1z"/><path id="path5023" d="M729.4 323c0 2.2-1.1 3.4-3 3.4-2 0-3-1.3-3-3.5v-4.6h1.2v4.6c0 1.5.6 2.3 1.8 2.3 1.2 0 1.8-.8 1.8-2.2v-4.6h1.2v4.6z"/></g><path id="path5027" d="M781.2 313.6v-1.4c-1.5-.2-2.7-.9-3.6-2.1l-1.2.7-.5-.9 1.2-.7c-.3-.7-.4-1.4-.4-2.1 0-.7.1-1.4.4-2.1l-1.2-.7.5-.9 1.2.7c.9-1.2 2.1-1.9 3.6-2.1v-1.4h1v1.4c1.5.2 2.7.9 3.6 2.1l1.2-.7.5.9-1.2.7c.3.7.5 1.4.5 2.1 0 .7-.2 1.4-.5 2.1l1.2.7-.5.9-1.2-.7c-.9 1.2-2.1 1.9-3.6 2.1v1.4h-1zm-3.2-8c-.2.5-.3 1-.3 1.6 0 .5.1 1.1.3 1.6l2.8-1.6-2.8-1.6zm3.2-2.5c-1.1.1-2 .7-2.7 1.6l2.8 1.6v-3.2zm-2.7 6.5c.7.9 1.6 1.4 2.7 1.6V308l-2.7 1.6zm6.5-4.9c-.7-.9-1.6-1.4-2.7-1.6v3.2l2.7-1.6zm-2.7 6.5c1.1-.1 2-.7 2.7-1.6l-2.8-1.6v3.2zm3.2-2.5c.2-.5.3-1 .3-1.6 0-.5-.1-1.1-.3-1.6l-2.8 1.6 2.8 1.6z"/><path id="path5029" d="M38.7 313.6v-1.4c-1.5-.2-2.7-.9-3.6-2.1l-1.2.7-.5-.9 1.2-.7c-.3-.7-.4-1.4-.4-2.1 0-.7.1-1.4.4-2.1l-1.2-.7.5-.9 1.2.7c.9-1.2 2.1-1.9 3.6-2.1v-1.4h1v1.4c1.5.2 2.7.9 3.6 2.1l1.2-.7.5.9-1.2.7c.3.7.5 1.4.5 2.1 0 .7-.2 1.4-.5 2.1l1.2.7-.5.9-1.2-.7c-.9 1.2-2.1 1.9-3.6 2.1v1.4h-1zm-3.2-8c-.2.5-.3 1-.3 1.6 0 .5.1 1.1.3 1.6l2.8-1.6-2.8-1.6zm3.2-2.5c-1.1.1-2 .7-2.7 1.6l2.8 1.6v-3.2zm-2.7 6.5c.7.9 1.6 1.4 2.7 1.6V308l-2.7 1.6zm6.5-4.9c-.7-.9-1.6-1.4-2.7-1.6v3.2l2.7-1.6zm-2.7 6.5c1.1-.1 2-.7 2.7-1.6l-2.8-1.6v3.2zm3.2-2.5c.2-.5.3-1 .3-1.6 0-.5-.1-1.1-.3-1.6l-2.8 1.6 2.8 1.6z"/><g id="g5045"><path id="path5031" d="M762.2 325c-.6 1-1.5 1.5-2.7 1.5-2.1 0-3.4-1.7-3.4-4.1s1.3-4.1 3.4-4.1c1.3 0 2.2.5 2.7 1.5l-1.1.7c-.4-.6-.8-1-1.6-1-1.4 0-2.1 1.1-2.1 2.9 0 1.8.7 2.9 2.1 2.9.8 0 1.3-.3 1.7-1l1 .7z"/><path id="path5033" d="M770 322.5c0 2.5-1.4 4.1-3.4 4.1s-3.4-1.6-3.4-4.1 1.4-4.1 3.4-4.1 3.4 1.6 3.4 4.1zm-1.2 0c0-1.8-.9-2.9-2.2-2.9-1.3 0-2.1 1.1-2.1 2.9s.9 2.9 2.2 2.9c1.2 0 2.1-1.1 2.1-2.9z"/><path id="path5035" d="M777.7 326.4h-1.1l-3.2-5c-.2-.3-.5-.8-.6-1v5.9h-1.2v-7.9h1.2l3 4.8c.2.3.5.9.7 1.1v-6h1.2v8.1z"/><path id="path5037" d="M785.1 319.7h-2.3v6.8h-1.2v-6.8h-2.3v-1.2h5.8v1.2z"/><path id="path5039" d="M792.7 320.9c0 1.3-.7 2.1-1.7 2.3l1.6 3.2h-1.4l-1.6-3.1h-1.8v3.1h-1.2v-7.9h3.5c1.4 0 2.6.7 2.6 2.4zm-1.2 0c0-.8-.5-1.3-1.3-1.3h-2.3v2.6h2.3c.7 0 1.3-.4 1.3-1.3z"/><path id="path5041" d="M800.7 322.5c0 2.5-1.4 4.1-3.4 4.1s-3.4-1.6-3.4-4.1 1.4-4.1 3.4-4.1 3.4 1.6 3.4 4.1zm-1.2 0c0-1.8-.9-2.9-2.2-2.9-1.3 0-2.1 1.1-2.1 2.9s.9 2.9 2.2 2.9c1.2 0 2.1-1.1 2.1-2.9z"/><path id="path5043" d="M807.5 326.4h-5.1v-7.9h1.2v6.8h4v1.1z"/></g></g><ellipse id="path5133" cx="70.326" cy="265.073" rx="33.559" ry="32.483" style="fill:none;stroke:red;stroke-width:5.3111;stroke-linecap:round;stroke-linejoin:round"/><path id="path5285" d="m130.939 193.502-16.957 46.887L157.7 256.2l-8.545-18.228 57.256-26.842-10.956-23.372-55.44 25.991z" style="fill:#fe7777;fill-opacity:1;stroke:red;stroke-width:2.7008;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"/></svg> \ No newline at end of file diff --git a/app/vendor/rune/vendor/winit/docs/res/keyboard_numpad_1_key.svg b/app/vendor/rune/vendor/winit/docs/res/keyboard_numpad_1_key.svg new file mode 100644 index 0000000..d595758 --- /dev/null +++ b/app/vendor/rune/vendor/winit/docs/res/keyboard_numpad_1_key.svg @@ -0,0 +1 @@ +<svg xmlns="http://www.w3.org/2000/svg" xml:space="preserve" id="svg5048" x="0" y="0" style="enable-background:new 0 0 1226 349" version="1.1" viewBox="0 0 1226 349"><style id="style3852" type="text/css">.st1{fill:#ccc;stroke:#000;stroke-width:2}.st2{fill:#fcfcfc}</style><g id="Layer_1"><path id="path3854" d="M6.5.5h1213c3.3 0 6 2.7 6 6v336c0 3.3-2.7 6-6 6H6.5c-3.3 0-6-2.7-6-6V6.5c0-3.3 2.7-6 6-6z" style="fill:#eee;stroke:#ddd"/></g><g id="Layer_2"><path id="path3857" d="M13.5 9.8h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.3 1.8-4 4-4z" class="st1"/><path id="path3859" d="M121.5 9.8h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.3 1.8-4 4-4z" class="st1"/><path id="path3861" d="M175.5 9.8h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.3 1.8-4 4-4z" class="st1"/><path id="path3863" d="M229.5 9.8h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.3 1.8-4 4-4z" class="st1"/><path id="path3865" d="M283.5 9.8h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.3 1.8-4 4-4z" class="st1"/><path id="path3867" d="M364.5 9.8h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.3 1.8-4 4-4z" class="st1"/><path id="path3869" d="M418.5 9.8h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.3 1.8-4 4-4z" class="st1"/><path id="path3871" d="M472.5 9.8h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.3 1.8-4 4-4z" class="st1"/><path id="path3873" d="M526.5 9.8h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.3 1.8-4 4-4z" class="st1"/><path id="path3875" d="M607.5 9.8h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.3 1.8-4 4-4z" class="st1"/><path id="path3877" d="M661.5 9.8h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.3 1.8-4 4-4z" class="st1"/><path id="path3879" d="M715.5 9.8h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.3 1.8-4 4-4z" class="st1"/><path id="path3881" d="M769.5 9.8h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.3 1.8-4 4-4z" class="st1"/><path id="path3883" d="M837 9.8h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.3 1.8-4 4-4z" class="st1"/><path id="path3885" d="M891 9.8h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.3 1.8-4 4-4z" class="st1"/><path id="path3887" d="M945 9.8h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.3 1.8-4 4-4z" class="st1"/><path id="path3889" d="M13.5 77.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3891" d="M67.5 77.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3893" d="M121.5 77.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3895" d="M175.5 77.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3897" d="M229.5 77.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3899" d="M283.5 77.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3901" d="M337.5 77.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3903" d="M391.5 77.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3905" d="M445.5 77.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3907" d="M499.5 77.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3909" d="M553.5 77.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3911" d="M607.5 77.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3913" d="M661.5 77.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3915" d="M715.5 77.2h92c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-92c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3917" d="M837 77.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3919" d="M891 77.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3921" d="M945 77.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3923" d="M1012.5 77.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3925" d="M1066.5 77.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3927" d="M1120.5 77.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3929" d="M1174.5 77.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3931" d="M13.5 131.2h65c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-65c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3933" d="M94.5 131.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3935" d="M148.5 131.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3937" d="M202.5 131.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3939" d="M256.5 131.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3941" d="M310.5 131.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3943" d="M364.5 131.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3945" d="M418.5 131.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3947" d="M472.5 131.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3949" d="M526.5 131.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3951" d="M580.5 131.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3953" d="M634.5 131.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3955" d="M688.5 131.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3957" d="M742.5 131.2h65c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-65c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3959" d="M837 131.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3961" d="M891 131.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3963" d="M945 131.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3965" d="M1012.5 131.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3967" d="M1066.5 131.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3969" d="M1120.5 131.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3971" d="M1174.5 131.2h38c2.2 0 4 1.8 4 4v92c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-92c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3973" d="M13.5 185.2H92c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4H13.5c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3975" d="M108 185.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3977" d="M162 185.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3979" d="M216 185.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3981" d="M270 185.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3983" d="M324 185.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3985" d="M378 185.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3987" d="M432 185.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3989" d="M486 185.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3991" d="M540 185.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3993" d="M594 185.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3995" d="M648 185.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3997" d="M702 185.2h105.5c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4H702c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3999" d="M1012.5 185.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path4001" d="M1066.5 185.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path4003" d="M1120.5 185.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path4005" d="M13.5 239.2H119c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4H13.5c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path4007" d="M135 239.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path4009" d="M189 239.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path4011" d="M243 239.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path4013" d="M297 239.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path4015" d="M351 239.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path4017" d="M405 239.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path4019" d="M459 239.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path4021" d="M513 239.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path4023" d="M567 239.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path4025" d="M621 239.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path4027" d="M675 239.2h132.5c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4H675c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path4029" d="M891 239.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path4031" d="M1012.5 239.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path4033" d="M1066.5 239.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path4035" d="M1120.5 239.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path4037" d="M1174.5 239.2h38c2.2 0 4 1.8 4 4v92c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-92c0-2.2 1.8-4 4-4z" class="st1"/><path id="path4039" d="M13.5 293.2H65c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4H13.5c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path4041" d="M81 293.2h51.5c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4H81c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path4043" d="M148.5 293.2H200c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-51.5c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path4045" d="M216 293.2h321.5c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4H216c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path4047" d="M553.5 293.2H605c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-51.5c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path4049" d="M621 293.2h51.5c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4H621c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path4051" d="M688.5 293.2H740c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-51.5c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path4053" d="M756 293.2h51.5c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4H756c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path4055" d="M837 293.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path4057" d="M891 293.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path4059" d="M945 293.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path4061" d="M1012.5 293.2h92c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-92c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path4063" d="M1120.5 293.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/></g><g id="Layer_3"><path id="path4066" d="M14.5 10.8h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.3 1.8-4 4-4z" class="st2"/><path id="path4068" d="M122.5 10.8h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.3 1.8-4 4-4z" class="st2"/><path id="path4070" d="M176.5 10.8h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.3 1.8-4 4-4z" class="st2"/><path id="path4072" d="M230.5 10.8h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.3 1.8-4 4-4z" class="st2"/><path id="path4074" d="M284.5 10.8h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.3 1.8-4 4-4z" class="st2"/><path id="path4076" d="M365.5 10.8h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.3 1.8-4 4-4z" class="st2"/><path id="path4078" d="M419.5 10.8h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.3 1.8-4 4-4z" class="st2"/><path id="path4080" d="M473.5 10.8h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.3 1.8-4 4-4z" class="st2"/><path id="path4082" d="M527.5 10.8h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.3 1.8-4 4-4z" class="st2"/><path id="path4084" d="M608.5 10.8h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.3 1.8-4 4-4z" class="st2"/><path id="path4086" d="M662.5 10.8h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.3 1.8-4 4-4z" class="st2"/><path id="path4088" d="M716.5 10.8h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.3 1.8-4 4-4z" class="st2"/><path id="path4090" d="M770.5 10.8h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.3 1.8-4 4-4z" class="st2"/><path id="path4092" d="M838 10.8h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.3 1.8-4 4-4z" class="st2"/><path id="path4094" d="M892 10.8h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.3 1.8-4 4-4z" class="st2"/><path id="path4096" d="M946 10.8h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.3 1.8-4 4-4z" class="st2"/><path id="path4098" d="M14.5 78.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4100" d="M68.5 78.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4102" d="M122.5 78.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4104" d="M176.5 78.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4106" d="M230.5 78.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4108" d="M284.5 78.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4110" d="M338.5 78.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4112" d="M392.5 78.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4114" d="M446.5 78.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4116" d="M500.5 78.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4118" d="M554.5 78.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4120" d="M608.5 78.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4122" d="M662.5 78.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4124" d="M716.5 78.2h90c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-90c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4126" d="M838 78.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4128" d="M892 78.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4130" d="M946 78.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4132" d="M1013.5 78.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4134" d="M1067.5 78.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4136" d="M1121.5 78.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4138" d="M1175.5 78.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4140" d="M14.5 132.2h63c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-63c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4142" d="M95.5 132.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4144" d="M149.5 132.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4146" d="M203.5 132.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4148" d="M257.5 132.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4150" d="M311.5 132.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4152" d="M365.5 132.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4154" d="M419.5 132.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4156" d="M473.5 132.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4158" d="M527.5 132.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4160" d="M581.5 132.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4162" d="M635.5 132.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4164" d="M689.5 132.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4166" d="M743.5 132.2h63c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-63c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4168" d="M838 132.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4170" d="M892 132.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4172" d="M946 132.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4174" d="M1013.5 132.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4176" d="M1067.5 132.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4178" d="M1121.5 132.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4180" d="M1175.5 132.2h36c2.2 0 4 1.8 4 4v88c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-88c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4182" d="M14.5 186.2H91c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4H14.5c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4184" d="M109 186.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4186" d="M163 186.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4188" d="M217 186.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4190" d="M271 186.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4192" d="M325 186.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4194" d="M379 186.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4196" d="M433 186.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4198" d="M487 186.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4200" d="M541 186.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4202" d="M595 186.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4204" d="M649 186.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4206" d="M703 186.2h103.5c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4H703c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4208" d="M1013.5 186.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4210" d="M1067.5 186.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4212" d="M1121.5 186.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4214" d="M14.5 240.2H118c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4H14.5c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4216" d="M136 240.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4218" d="M190 240.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4220" d="M244 240.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4222" d="M298 240.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4224" d="M352 240.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4226" d="M406 240.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4228" d="M460 240.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4230" d="M514 240.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4232" d="M568 240.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4234" d="M622 240.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4236" d="M676 240.2h130.5c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4H676c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4238" d="M892 240.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4240" d="M1013.5 240.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4242" d="M1067.5 240.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4244" d="M1121.5 240.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4246" d="M1175.5 240.2h36c2.2 0 4 1.8 4 4v88c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-88c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4248" d="M14.5 294.2H64c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4H14.5c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4250" d="M82 294.2h49.5c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4H82c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4252" d="M149.5 294.2H199c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-49.5c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4254" d="M217 294.2h319.5c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4H217c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4256" d="M554.5 294.2H604c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-49.5c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4258" d="M622 294.2h49.5c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4H622c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4260" d="M689.5 294.2H739c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-49.5c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4262" d="M757 294.2h49.5c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4H757c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4264" d="M838 294.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4266" d="M892 294.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4268" d="M946 294.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4270" d="M1013.5 294.2h90c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-90c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4272" d="M1121.5 294.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/></g><g id="Layer_4"><g id="g4279"><path id="path4275" d="M141.4 29.3h-3.9v2.1h2.3v1.2h-2.3V36h-1.2v-7.9h5.1v1.2z"/><path id="path4277" d="M144.7 36h-1.2v-6.1h-1.4v-.8c.8-.1 1.5-.3 1.6-1h1V36z"/></g><g id="g4285"><path id="path4281" d="M193.8 29.3h-3.9v2.1h2.3v1.2h-2.3V36h-1.2v-7.9h5.1v1.2z"/><path id="path4283" d="M200.4 36h-5.7c.1-2.3 1.5-3.4 3-4.3 1.1-.6 1.3-1 1.3-1.5 0-.6-.4-1-1.5-1-.7 0-1.4.3-1.9.8l-.6-1c.7-.7 1.7-1.1 2.7-1.1 1.6 0 2.7.7 2.7 2.2 0 1.2-.6 1.7-2 2.6-1.5.9-1.9 1.4-2.1 2.2h4.2V36z"/></g><g id="g4291"><path id="path4287" d="M247.9 29.3H244v2.1h2.3v1.2H244V36h-1.2v-7.9h5.1v1.2z"/><path id="path4289" d="M254.5 33.7c0 1.6-1.1 2.5-3 2.5-1.1 0-2.3-.5-2.9-1.3l.9-.8c.5.6 1.2.9 2 .9 1.3 0 1.7-.5 1.7-1.3s-.6-1.2-1.4-1.2h-.7v-1.2h.7c.7 0 1.1-.5 1.1-1.1 0-.5-.3-1.1-1.5-1.1-.6 0-1.1.3-1.6.7l-.8-.8c.7-.7 1.5-1.1 2.5-1.1 1.5 0 2.7.8 2.7 2.2 0 1-.4 1.4-1 1.7.7.3 1.3.9 1.3 1.9z"/></g><g id="g4297"><path id="path4293" d="M301.6 29.3h-3.9v2.1h2.3v1.2h-2.3V36h-1.2v-7.9h5.1v1.2z"/><path id="path4295" d="M309 34.2h-1.1V36h-1.2v-1.7h-4.3v-1.1l4.1-5.1h1.4v5.1h1.1v1zm-2.2-4.8c-.1.2-.5.6-.7.9l-1.5 1.9c-.2.3-.6.7-.7.9h3v-2.3c-.1-.4-.1-1.1-.1-1.4z"/></g><g id="g4303"><path id="path4299" d="M382.7 29.3h-3.9v2.1h2.3v1.2h-2.3V36h-1.2v-7.9h5.1v1.2z"/><path id="path4301" d="M389.7 33.3c0 1.9-1.3 2.8-3.1 2.8-1 0-1.9-.2-2.8-.8l.6-1c.7.4 1.5.6 2.2.6 1.2 0 1.9-.6 1.9-1.6 0-.9-.6-1.4-1.6-1.4-.7 0-1.1.2-1.5.5l-1.3-.5.3-3.9h4.9v1.1h-3.8l-.2 2c.4-.2 1-.4 1.7-.4 1.8.1 2.7 1.2 2.7 2.6z"/></g><g id="g4309"><path id="path4305" d="M436.7 29.3h-3.9v2.1h2.3v1.2h-2.3V36h-1.2v-7.9h5.1v1.2z"/><path id="path4307" d="M443.9 33.5c0 1.7-1.4 2.6-3.1 2.6-1.7 0-3-.9-3-3.2 0-2.1 1.2-4.9 4.9-5V29c-1.8.1-3.1.9-3.6 2.6.6-.4 1.1-.6 2.1-.6 1.5 0 2.7.8 2.7 2.5zm-1.2 0c0-1-.7-1.4-1.8-1.4-1.2 0-1.9.5-1.9 1.4 0 .8.6 1.5 1.8 1.5 1.2 0 1.9-.6 1.9-1.5z"/></g><g id="g4315"><path id="path4311" d="M491 29.3h-3.9v2.1h2.3v1.2h-2.3V36h-1.2v-7.9h5.1v1.2z"/><path id="path4313" d="M497.2 29.3c-1.3 1.5-2.6 3.8-2.6 6.7h-1.2c0-2.7 1-4.9 2.5-6.8h-4.2V28h5.5v1.3z"/></g><g id="g4321"><path id="path4317" d="M544.5 29.3h-3.9v2.1h2.3v1.2h-2.3V36h-1.2v-7.9h5.1v1.2z"/><path id="path4319" d="M551.9 33.7c0 1.6-1.2 2.4-3.1 2.4s-3.1-.9-3.1-2.4c0-1 .5-1.6 1.4-2-.8-.3-1.1-1.1-1.1-1.5 0-1.5 1.2-2.2 2.8-2.2 1.4 0 2.8.7 2.8 2.2 0 .5-.2 1.2-1.1 1.6.9.3 1.4.9 1.4 1.9zm-1.2 0c0-.8-.6-1.4-1.9-1.4-1.3 0-1.9.5-1.9 1.3s.7 1.4 1.9 1.4c1.3.1 1.9-.5 1.9-1.3zm-.3-3.5c0-.6-.4-1.2-1.6-1.2s-1.6.5-1.6 1.1c0 .6.6 1.1 1.6 1.1 1 .1 1.6-.4 1.6-1z"/></g><g id="g4327"><path id="path4323" d="M625.7 29.3h-3.9v2.1h2.3v1.2h-2.3V36h-1.2v-7.9h5.1v1.2z"/><path id="path4325" d="M632.8 31.1c0 2.1-1.2 4.9-4.9 5V35c1.8-.1 3.1-.9 3.6-2.6-.6.4-1.1.6-2.1.6-1.4 0-2.7-.8-2.7-2.5s1.4-2.6 3.1-2.6c1.7.1 3 1 3 3.2zm-1.2-.5c0-.8-.6-1.5-1.8-1.5-1.2 0-1.9.6-1.9 1.5 0 1 .7 1.4 1.8 1.4 1.2 0 1.9-.5 1.9-1.4z"/></g><g id="g4335"><path id="path4329" d="M677.7 29.3h-3.9v2.1h2.3v1.2h-2.3V36h-1.2v-7.9h5.1v1.2z"/><path id="path4331" d="M680.9 36h-1.2v-6.1h-1.4v-.8c.8-.1 1.5-.3 1.6-1h1V36z"/><path id="path4333" d="M688.9 32c0 2.4-1.1 4.1-3.1 4.1s-3.1-1.7-3.1-4.1c0-2.4 1.1-4.1 3.1-4.1 2 .1 3.1 1.7 3.1 4.1zm-1.2.1c0-1.7-.5-2.9-1.9-2.9s-1.9 1.3-1.9 2.9.6 2.9 1.9 2.9c1.3 0 1.9-1.3 1.9-2.9z"/></g><g id="g4343"><path id="path4337" d="M733.5 29.3h-3.9v2.1h2.3v1.2h-2.3V36h-1.2v-7.9h5.1v1.2z"/><path id="path4339" d="M736.7 36h-1.2v-6.1h-1.4v-.8c.8-.1 1.5-.3 1.6-1h1V36z"/><path id="path4341" d="M740.6 36h-1.2v-6.1H738v-.8c.8-.1 1.5-.3 1.6-1h1V36z"/></g><g id="g4351"><path id="path4345" d="M785.8 29.3h-3.9v2.1h2.3v1.2h-2.3V36h-1.2v-7.9h5.1v1.2z"/><path id="path4347" d="M789.1 36h-1.2v-6.1h-1.4v-.8c.8-.1 1.5-.3 1.6-1h1V36z"/><path id="path4349" d="M796.4 36h-5.7c.1-2.3 1.5-3.4 3-4.3 1.1-.6 1.3-1 1.3-1.5 0-.6-.4-1-1.5-1-.7 0-1.4.3-1.9.8l-.8-.9c.7-.7 1.7-1.1 2.7-1.1 1.6 0 2.7.7 2.7 2.2 0 1.2-.6 1.7-2 2.6-1.5.9-2 1.4-2.1 2.2h4.2v1z"/></g><g id="g4357"><path id="path4353" d="M35.9 89.7c-.5 1.3-1.1 2-2.2 2-.6 0-.9-.2-1.4-.5-.6-.4-.9-.6-1.2-.6-.5 0-.7.3-1 1.1l-1-.5c.5-1.3 1.1-2 2.2-2 .6 0 .9.2 1.4.5.5.4.9.6 1.2.6.5 0 .7-.3 1.1-1.1l.9.5z"/><path id="path4355" d="M33.9 104.2h-1.2l-2.3-2.3h2l1.5 2.3z"/></g><g id="g4363"><path id="path4359" d="M87.6 94.8c0 .6-.5 1.1-1.1 1.1-.6 0-1.1-.5-1.1-1.1s.5-1.1 1.1-1.1c.6 0 1.1.5 1.1 1.1zm-.3-4.6-.3 2.6h-1l-.3-2.7v-4.4h1.5v4.5z"/><path id="path4361" d="M87.6 112.7h-1.5v-7.6h-1.8v-1c1-.1 1.9-.4 2-1.3h1.2v9.9z"/></g><g id="g4369"><path id="path4365" d="M145.6 89.1c0 2.1-.9 2.9-2.2 2.9-.7 0-1.3-.4-1.5-.9-.3.5-1.1.9-1.8.9-1.1 0-2.2-.6-2.2-1.9 0-1.2 1.1-1.8 2.3-1.8.6 0 1.1.2 1.4.4V88c0-.6-.5-.8-1.3-.8-.5 0-1 .1-1.4.3l-.4-.7c.5-.3 1.2-.5 1.8-.5 1.3 0 2.2.6 2.2 1.7v2.4c0 .5.3.9.9.9.9 0 1.2-.7 1.2-2.1 0-2.3-1.8-4.2-4.3-4.2s-4.3 1.8-4.3 4.3 1.8 4.3 4.3 4.3c.6 0 1.2-.1 1.8-.4l.3.8c-.8.4-1.4.5-2.2.5-3 0-5.1-2.2-5.1-5.1 0-3 2.2-5.1 5.1-5.1 3.3-.1 5.4 2.2 5.4 4.8zm-3.9 1.3v-.9c-.3-.2-.8-.4-1.5-.4-.8 0-1.3.3-1.3 1s.5 1.1 1.4 1.1c.5 0 1.1-.3 1.4-.8z"/><path id="path4367" d="M143.8 111.3h-7.1c.1-2.9 1.9-4.2 3.8-5.4 1.3-.8 1.7-1.2 1.7-1.9 0-.8-.5-1.3-1.9-1.3-.8 0-1.8.4-2.4 1l-.9-1.1c.9-.8 2.2-1.3 3.4-1.3 2.1 0 3.4.9 3.4 2.7 0 1.5-.8 2.2-2.5 3.2-1.9 1.1-2.4 1.8-2.7 2.7h5.3v1.4z"/></g><g id="g4375"><path id="path4371" d="M198.8 93.4h-1.7v2.3h-1.4v-2.3h-2.3v2.3H192v-2.3h-1.7v-1.3h1.7v-2.7h-1.7V88h1.7v-2.3h1.4V88h2.3v-2.3h1.4V88h1.7v1.3h-1.7V92h1.7v1.4zm-3.1-1.3v-2.7h-2.3v2.7h2.3z"/><path id="path4373" d="M197.8 109.7c0 2-1.4 3.1-3.7 3.1-1.4 0-2.9-.6-3.6-1.6l1.1-1c.6.8 1.5 1.1 2.4 1.1 1.6 0 2.2-.6 2.2-1.6s-.8-1.5-1.8-1.5h-.9v-1.4h.9c.9 0 1.4-.6 1.4-1.4 0-.6-.4-1.4-1.9-1.4-.8 0-1.4.3-2 .9l-1.1-1c.8-.9 1.8-1.3 3.1-1.3 1.9 0 3.4 1 3.4 2.7 0 1.2-.5 1.8-1.2 2.2 1.1.2 1.7 1 1.7 2.2z"/></g><g id="g4381"><path id="path4377" d="M252 92.7c0 1.6-.9 2.7-2.8 2.9V97h-1.5v-1.4c-1.2-.2-2.3-.7-2.9-1.6l1.1-1c.7.8 1.6 1.1 2.5 1.1 1.4 0 2-.5 2-1.3s-.6-1.1-2.2-1.6c-2.1-.6-3.1-1.1-3.1-2.9 0-1.5 1.1-2.4 2.5-2.6v-1.5h1.5v1.5c1 .2 1.8.6 2.5 1.3l-1 1c-.7-.6-1.3-1-2.3-1-1.1 0-1.6.5-1.6 1.1 0 .7.4 1 2.1 1.5 2 .8 3.2 1.3 3.2 3.1z"/><path id="path4379" d="M252.5 110.5h-1.3v2.2h-1.4v-2.2h-5.4v-1.4l5.1-6.3h1.7v6.4h1.3v1.3zm-2.7-6.1c-.2.3-.6.8-.9 1.2L247 108c-.3.4-.7.9-.9 1.1h3.7v-2.9c-.1-.5 0-1.4 0-1.8z"/></g><g id="g4387"><path id="path4383" d="M301.2 88.7c0 1.8-1 3.1-2.5 3.1s-2.4-1.3-2.4-3.1 1-3.1 2.5-3.1c1.4 0 2.4 1.3 2.4 3.1zm-1.3 0c0-1.1-.4-1.9-1.2-1.9s-1.2.7-1.2 1.8.4 1.9 1.2 1.9 1.2-.8 1.2-1.8zm6.4-3-6.1 9.9h-1.4l6.1-9.9h1.4zm2.4 7c0 1.8-1 3.1-2.5 3.1-1.4 0-2.4-1.3-2.4-3.1s1-3.1 2.5-3.1c1.5.1 2.4 1.3 2.4 3.1zm-1.2.1c0-1.1-.4-1.9-1.2-1.9-.8 0-1.2.7-1.2 1.8s.4 1.9 1.2 1.9c.7 0 1.2-.8 1.2-1.8z"/><path id="path4385" d="M306.1 109.3c0 2.4-1.6 3.5-3.9 3.5-1.3 0-2.4-.3-3.5-1l.7-1.2c.8.5 1.9.8 2.8.8 1.5 0 2.4-.8 2.4-2s-.8-1.8-2-1.8c-.8 0-1.4.2-1.9.6l-1.6-.6.3-4.8h6.1v1.4h-4.8l-.2 2.5c.6-.3 1.2-.5 2.1-.5 2.4 0 3.5 1.3 3.5 3.1z"/></g><g id="g4393"><path id="path4389" d="M359.9 90.3h-1.6l-1.8-3-1.8 3h-1.6l2.9-4.5h1.1l2.8 4.5z"/><path id="path4391" d="M360.4 109.5c0 2.2-1.7 3.3-3.9 3.3-2.1 0-3.7-1.1-3.7-4 0-2.6 1.4-6.1 6.2-6.3v1.4c-2.3.1-3.8 1.1-4.5 3.2.7-.6 1.4-.8 2.6-.8 1.8.1 3.3 1.1 3.3 3.2zm-1.5.1c0-1.2-.8-1.7-2.3-1.7-1.4 0-2.3.6-2.3 1.7 0 1 .8 1.8 2.3 1.8 1.5 0 2.3-.7 2.3-1.8z"/></g><g id="g4399"><path id="path4395" d="M414.9 95.7h-1.7l-.8-.9c-.7.7-1.7 1.1-2.8 1.1-2.1 0-3.1-1.1-3.1-2.7 0-1.3.7-2.2 2.1-2.9l-.2-.2c-.7-.8-.9-1.4-.9-2.1 0-1.4 1.1-2.3 2.8-2.3.9 0 1.8.3 2.7.9l-.7 1.2c-.8-.6-1.3-.8-2.1-.8s-1.1.3-1.1.9c0 .4.1.7.5 1.2l2.9 3.6c.3-.5.5-1.1.7-1.6l1.3.4c-.2.8-.6 1.7-1.1 2.4l1.5 1.8zm-3.4-2-2.1-2.5c-.9.5-1.4 1-1.4 1.9 0 .8.5 1.4 1.7 1.4.7 0 1.3-.3 1.8-.8z"/><path id="path4397" d="M413.6 104.3c-1.7 1.9-3.2 4.7-3.3 8.4h-1.5c.1-3.4 1.2-6.1 3.1-8.5h-5.2v-1.4h6.9v1.5z"/></g><g id="g4405"><path id="path4401" d="m467.3 89.5-.6 1.1-1.8-1.3.2 2.2h-1.2l.2-2.2-1.8 1.3-.6-1.1 2-.9-2-.9.6-1.1 1.8 1.3-.2-2.2h1.2l-.2 2.1 1.7-1.3.6 1.1-2 .9 2.1 1z"/><path id="path4403" d="M468.4 109.8c0 2-1.5 3-3.9 3s-3.9-1.1-3.9-3c0-1.2.6-2 1.8-2.5-1-.4-1.3-1.3-1.3-1.9 0-1.9 1.5-2.8 3.5-2.8 1.8 0 3.5.9 3.5 2.8 0 .6-.3 1.5-1.3 1.9.9.4 1.6 1.2 1.6 2.5zm-1.5 0c0-1-.8-1.7-2.4-1.7-1.6 0-2.4.6-2.4 1.6s.9 1.7 2.4 1.7c1.6.1 2.4-.6 2.4-1.6zm-.4-4.4c0-.8-.5-1.5-2-1.5-1.4 0-2 .7-2 1.4 0 .8.8 1.4 2 1.4 1.3 0 2-.6 2-1.3z"/></g><g id="g4411"><path id="path4407" d="m520.3 96.6-.7.6c-1.4-1.3-2.8-3.2-2.8-5.8 0-2.7 1.3-4.5 2.8-5.9l.7.6c-1.3 1.4-2 3-2 5.2.1 2.4.8 3.9 2 5.3z"/><path id="path4409" d="M522.2 106.6c0 2.6-1.4 6.1-6.2 6.3v-1.4c2.3-.1 3.8-1.1 4.5-3.2-.7.6-1.4.8-2.6.8-1.8 0-3.3-1-3.3-3.1 0-2.2 1.7-3.3 3.9-3.3 2.1-.1 3.7 1 3.7 3.9zm-1.5-.7c0-1-.8-1.8-2.3-1.8-1.5 0-2.3.7-2.3 1.8 0 1.2.8 1.7 2.3 1.7 1.4 0 2.3-.6 2.3-1.7z"/></g><g id="g4417"><path id="path4413" d="M574.2 91.3c0 2.7-1.3 4.5-2.8 5.9l-.7-.6c1.3-1.4 2-3 2-5.2 0-2.3-.8-3.9-2-5.2l.7-.6c1.4 1.3 2.8 3.2 2.8 5.7z"/><path id="path4415" d="M576.4 107.7c0 3-1.4 5.1-3.9 5.1-2.6 0-3.9-2.1-3.9-5.1s1.4-5.1 3.9-5.1c2.6 0 3.9 2.1 3.9 5.1zm-1.5 0c0-2.1-.7-3.7-2.4-3.7s-2.4 1.6-2.4 3.7.7 3.7 2.4 3.7c1.8 0 2.4-1.6 2.4-3.7z"/></g><g id="g4423"><path id="path4419" d="M630 98.2h-7v-1.3h7.1v1.3z"/><path id="path4421" d="M628.3 108.2h-3.5v-1.4h3.5v1.4z"/></g><g id="g4429"><path id="path4425" d="M683.9 91.5h-2.7v2.8h-1.5v-2.8H677v-1.4h2.7v-2.8h1.5v2.8h2.7v1.4z"/><path id="path4427" d="M683.6 106.9h-6.1v-1.4h6.1v1.4zm0 3.2h-6.1v-1.4h6.1v1.4z"/></g><g id="g4433"><path id="path4431" d="m1088.4 93-4.4 12.5h-1.5L1087 93h1.4z"/></g><g id="g4437"><path id="path4435" d="m1136.4 98.2.7-1.2 1.9 1.4-.2-2.4h1.4l-.2 2.4 1.9-1.4.7 1.2-2.2 1 2.2 1-.7 1.2-1.9-1.4.2 2.4h-1.4l.2-2.4-1.9 1.4-.7-1.2 2.2-1-2.2-1z"/></g><g id="g4441"><path id="path4439" d="M1189.9 98.4h7.2v1.6h-7.2v-1.6z"/></g><g id="g4445"><path id="path4443" d="M117.7 153.2c0 1.7-.6 3.2-1.5 4.1l.7 1-1.2.8-.7-1c-.4.2-.9.3-1.5.3-2.6 0-4.2-2.1-4.2-5.1s1.6-5.1 4.2-5.1c2.6-.1 4.2 2 4.2 5zm-1.5 0c0-2.2-.9-3.6-2.7-3.6-1.7 0-2.7 1.4-2.7 3.6s.9 3.7 2.7 3.7c.3 0 .5 0 .7-.1l-.7-1.1 1.2-.8.7 1.1c.5-.6.8-1.6.8-2.8z"/></g><g id="g4449"><path id="path4447" d="m172.9 148.2-2 9.9h-1.5l-1.5-6.4c-.1-.3-.2-1.1-.3-1.3 0 .2-.2 1-.3 1.3l-1.6 6.4h-1.5l-2-9.9h1.5l1.2 6.3c.1.3.2 1 .2 1.3.1-.3.2-1 .3-1.3l1.6-6.3h1.3l1.6 6.4c.1.3.2.8.2 1.1.1-.4.2-.9.2-1.2l1.2-6.4h1.4z"/></g><g id="g4453"><path id="path4451" d="M225 158.2h-6.6v-9.9h6.4v1.4h-4.9v2.5h2.8v1.4h-2.8v3.1h5.1v1.5z"/></g><g id="g4457"><path id="path4455" d="M279.4 151.2c0 1.6-.8 2.6-2.2 2.9l2 4.1h-1.7l-2-3.9h-2.2v3.9h-1.5v-9.9h4.4c1.8-.1 3.2.9 3.2 2.9zm-1.5.1c0-1-.7-1.6-1.7-1.6h-2.9v3.2h2.9c1-.1 1.7-.6 1.7-1.6z"/></g><g id="g4461"><path id="path4459" d="M333.1 149.7h-2.9v8.5h-1.5v-8.5h-2.9v-1.5h7.3v1.5z"/></g><g id="g4465"><path id="path4463" d="m387.8 148.2-3.6 6v3.9h-1.5v-3.9l-3.6-6h1.7l1.5 2.7c.3.6.9 1.6 1 2 .2-.4.7-1.3 1-2l1.6-2.8h1.9z"/></g><g id="g4469"><path id="path4467" d="M441.3 154c0 2.8-1.3 4.3-3.8 4.3s-3.7-1.6-3.7-4.3v-5.8h1.5v5.7c0 1.9.8 2.9 2.3 2.9 1.6 0 2.3-1 2.3-2.8v-5.8h1.5v5.8z"/></g><g id="g4473"><path id="path4471" d="M492.2 158.2h-1.5v-9.9h1.5v9.9z"/></g><g id="g4477"><path id="path4475" d="M549.7 153.2c0 3.1-1.7 5.1-4.3 5.1-2.5 0-4.2-2-4.2-5.1s1.7-5.1 4.2-5.1c2.6 0 4.3 2 4.3 5.1zm-1.5 0c0-2.3-1.2-3.7-2.8-3.7-1.6 0-2.7 1.4-2.7 3.6s1.1 3.7 2.7 3.7c1.7.1 2.8-1.3 2.8-3.6z"/></g><g id="g4481"><path id="path4479" d="M603.5 151.4c0 2-1.4 3.1-3.3 3.1h-2.6v3.7h-1.5v-9.9h4.2c1.8-.1 3.2 1 3.2 3.1zm-1.5 0c0-1.1-.7-1.7-1.7-1.7h-2.7v3.4h2.7c1.1 0 1.7-.7 1.7-1.7z"/></g><g id="g4487"><path id="path4483" d="M655.8 151.2c-2.3 0-3.3-1-3.3-3v-.9c0-1-.2-1.2-.8-1.2h-.3v-1.3h.3c.6 0 .8-.3.8-1.2v-.9c0-2 1-3 3.3-3v1.1c-1.4.1-1.8.7-1.8 1.8v.7c0 1.3-.3 1.9-1.1 2.2.8.3 1.1.9 1.1 2.2v.7c0 1.1.4 1.7 1.8 1.8v1z"/><path id="path4485" d="M655.3 168.2h-3.1v-11.5h3.1v1.2h-1.7v9.1h1.7v1.2z"/></g><g id="g4493"><path id="path4489" d="M709.6 146.1h-.3c-.6 0-.8.3-.8 1.2v.9c0 2-1 3-3.3 3v-1.1c1.4-.1 1.8-.7 1.8-1.8v-.7c0-1.3.3-1.9 1.1-2.2-.8-.3-1.1-.9-1.1-2.2v-.7c0-1.1-.4-1.7-1.8-1.8v-1.1c2.3 0 3.3 1 3.3 3v.9c0 1 .2 1.2.8 1.2h.3v1.4z"/><path id="path4491" d="M708.8 168.2h-3.1V167h1.7v-9h-1.7v-1.2h3.1v11.4z"/></g><g id="g4499"><path id="path4495" d="M775.7 152.3h-1.3v-14h1.3v14z"/><path id="path4497" d="M777.9 168h-1.5l-4.4-12.5h1.5l4.4 12.5z"/></g><g id="g4503"><path id="path4501" d="M1034.6 149.8c-1.7 1.9-3.2 4.7-3.3 8.4h-1.5c.1-3.4 1.2-6.1 3.1-8.5h-5.2v-1.4h6.9v1.5z"/></g><g id="g4507"><path id="path4505" d="M1089.4 155.3c0 2-1.5 3-3.9 3s-3.9-1.1-3.9-3c0-1.2.6-2 1.8-2.5-1-.4-1.3-1.3-1.3-1.9 0-1.9 1.5-2.8 3.5-2.8 1.8 0 3.5.9 3.5 2.8 0 .6-.3 1.5-1.3 1.9.9.4 1.6 1.2 1.6 2.5zm-1.5 0c0-1-.8-1.7-2.4-1.7-1.6 0-2.4.6-2.4 1.6s.9 1.7 2.4 1.7c1.6.1 2.4-.6 2.4-1.6zm-.4-4.4c0-.8-.5-1.5-2-1.5-1.4 0-2 .7-2 1.4 0 .8.8 1.4 2 1.4 1.3 0 2-.6 2-1.3z"/></g><g id="g4511"><path id="path4509" d="M1143.2 152c0 2.6-1.4 6.1-6.2 6.3v-1.4c2.3-.1 3.8-1.1 4.5-3.2-.7.6-1.4.8-2.6.8-1.8 0-3.3-1-3.3-3.1 0-2.2 1.7-3.3 3.9-3.3 2.1 0 3.7 1.1 3.7 3.9zm-1.5-.6c0-1-.8-1.8-2.3-1.8-1.5 0-2.3.7-2.3 1.8 0 1.2.8 1.7 2.3 1.7 1.4 0 2.3-.6 2.3-1.7z"/></g><g id="g4515"><path id="path4513" d="M1197.3 182h-3v3h-1.6v-3h-3v-1.6h3v-3h1.6v3h3v1.6z"/></g><g id="g4519"><path id="path4517" d="M131.4 212.2h-1.6l-.8-2.4h-4l-.8 2.4h-1.5l3.6-9.9h1.6l3.5 9.9zm-2.9-3.7-.8-2.3c-.2-.7-.6-1.9-.8-2.3-.1.4-.5 1.6-.7 2.3l-.8 2.3h3.1z"/></g><g id="g4523"><path id="path4521" d="M184.5 209.3c0 1.8-1.1 3-3.7 3-1.4 0-2.7-.6-3.5-1.6l1.1-1c.7.7 1.6 1.2 2.6 1.2 1.4 0 2.1-.5 2.1-1.4 0-.8-.6-1.1-2.2-1.6-2.1-.6-3.1-1.1-3.1-2.9 0-1.7 1.4-2.8 3.3-2.8 1.3 0 2.4.5 3.2 1.3l-1 1.1c-.6-.6-1.3-.9-2.3-.9-1.2 0-1.7.6-1.7 1.2 0 .7.5 1 2.2 1.5 1.8.5 3 1.2 3 2.9z"/></g><g id="g4527"><path id="path4525" d="M239 207.2c0 3.5-2.2 5-4.8 5h-2.7v-9.9h2.7c2.7-.1 4.8 1.4 4.8 4.9zm-1.5 0c0-2.1-1-3.5-3.3-3.5H233v7h1.2c2.3 0 3.3-1.4 3.3-3.5z"/></g><g id="g4531"><path id="path4529" d="M292.6 203.7h-4.9v2.6h2.8v1.5h-2.8v4.4h-1.5v-9.9h6.4v1.4z"/></g><g id="g4535"><path id="path4533" d="M347 208.3c0 2.6-1.6 4-3.8 4-2.6 0-4.2-2.1-4.2-5.1 0-3 1.6-5.1 4.2-5.1 1.6 0 2.7.7 3.4 1.9l-1.3.8c-.5-.8-1-1.2-2.1-1.2-1.7 0-2.7 1.4-2.7 3.6s.9 3.6 2.7 3.6c1.6 0 2.3-1.1 2.3-2.2h-1.6v-1.4h3.1v1.1z"/></g><g id="g4539"><path id="path4537" d="M400.8 212.2h-1.5v-4.4h-4.6v4.4h-1.5v-9.9h1.5v4h4.6v-4h1.5v9.9z"/></g><g id="g4543"><path id="path4541" d="M454.1 208.3c0 2.7-1.1 4.1-3.5 4.1-1.9 0-3-1-3.5-2.6l1.4-.4c.4 1 1 1.6 2.1 1.6 1.4 0 2-.8 2-2.7v-5.9h1.5v5.9z"/></g><g id="g4547"><path id="path4545" d="M509.3 212.2h-1.7l-2.8-5.1-1.8 2.2v2.9h-1.4v-9.9h1.4v5.2c.2-.3.8-1.1 1.1-1.5l2.9-3.7h1.7l-2.9 3.6 3.5 6.3z"/></g><g id="g4551"><path id="path4549" d="M562.5 212.2h-6.4v-9.9h1.5v8.5h4.9v1.4z"/></g><g id="g4557"><path id="path4553" d="M614.1 197.2c0 .6-.5 1.1-1.1 1.1-.6 0-1.1-.5-1.1-1.1s.5-1.1 1.1-1.1c.6 0 1.1.5 1.1 1.1zm0 5.5c0 .6-.5 1.1-1.1 1.1-.6 0-1.1-.5-1.1-1.1s.5-1.1 1.1-1.1c.6 0 1.1.5 1.1 1.1z"/><path id="path4555" d="M614.1 214.2c0 .6-.5 1.1-1.1 1.1-.6 0-1.1-.5-1.1-1.1s.5-1.1 1.1-1.1c.6 0 1.1.5 1.1 1.1zm-.1 4.5-1.1 3.8h-1l.2-3.8h1.9z"/></g><g id="g4563"><path id="path4559" d="m666.3 193.7-.2 3.6h-1.9l1.1-3.6h1zm3.3 0-.2 3.6h-1.9l1.1-3.6h1z"/><path id="path4561" d="m668 210.8-.2 3.6h-1.9l1.1-3.6h1z"/></g><g id="g4567"><path id="path4565" d="M1035.5 209.9h-1.3v2.2h-1.4V210h-5.4v-1.4l5.1-6.3h1.7v6.4h1.3v1.2zm-2.7-6c-.2.3-.6.8-.9 1.2l-1.9 2.4c-.3.4-.7.9-.9 1.1h3.7v-2.9c-.1-.5 0-1.4 0-1.8z"/></g><g id="g4571"><path id="path4569" d="M1089.1 208.8c0 2.4-1.6 3.5-3.9 3.5-1.3 0-2.4-.3-3.5-1l.7-1.2c.8.5 1.9.8 2.8.8 1.5 0 2.4-.8 2.4-2s-.8-1.8-2-1.8c-.8 0-1.4.2-1.9.6l-1.6-.6.3-4.8h6.1v1.4h-4.8l-.2 2.5c.6-.3 1.2-.5 2.1-.5 2.4 0 3.5 1.3 3.5 3.1z"/></g><g id="g4575"><path id="path4573" d="M1143.4 209c0 2.2-1.7 3.3-3.9 3.3-2.1 0-3.7-1.1-3.7-4 0-2.6 1.4-6.1 6.2-6.3v1.4c-2.3.1-3.8 1.1-4.5 3.2.7-.6 1.4-.8 2.6-.8 1.8.1 3.3 1.1 3.3 3.2zm-1.5.1c0-1.2-.8-1.7-2.3-1.7-1.4 0-2.3.6-2.3 1.7 0 1 .8 1.8 2.3 1.8 1.5 0 2.3-.7 2.3-1.8z"/></g><g id="g4579"><path id="path4577" d="M157.7 266.2h-7.5v-1.4l4.8-5.9c.3-.4.9-1 1.1-1.3h-5.7v-1.4h7.3v1.4l-4.8 5.9c-.3.4-.9 1-1.1 1.3h5.9v1.4z"/></g><g id="g4583"><path id="path4581" d="M212 266.2h-1.8l-1.1-1.9c-.4-.6-.9-1.6-1.1-2-.2.4-.7 1.4-1.1 2l-1.1 1.9h-1.7l3.1-5.1-2.9-4.8h1.8l.9 1.6c.3.6.9 1.7 1.1 2 .2-.4.7-1.4 1.1-2l.9-1.6h1.7L209 261l3 5.2z"/></g><g id="g4587"><path id="path4585" d="M265.8 264.4c-.7 1.2-1.9 1.9-3.4 1.9-2.6 0-4.2-2.1-4.2-5.1 0-3 1.6-5.1 4.2-5.1 1.6 0 2.7.7 3.4 1.9l-1.3.8c-.5-.8-1-1.2-2.1-1.2-1.7 0-2.7 1.4-2.7 3.6s.9 3.6 2.7 3.6c1 0 1.7-.4 2.2-1.2l1.2.8z"/></g><g id="g4591"><path id="path4589" d="m320.2 256.2-3.4 9.9h-1.6l-3.4-9.9h1.6l2.1 6.3.6 1.8c.1-.4.4-1.2.6-1.8l2-6.3h1.5z"/></g><g id="g4595"><path id="path4593" d="M373.8 263.1c0 2-1.2 3-3.4 3h-3.9v-9.9h4.1c1.7 0 2.8.9 2.8 2.6 0 1-.5 1.6-1.3 2 .9.2 1.7 1 1.7 2.3zm-1.8-4.2c0-.7-.4-1.3-1.4-1.3h-2.7v2.6h2.7c1 0 1.4-.6 1.4-1.3zm.4 4.3c0-1-.6-1.6-1.8-1.6h-2.7v3.3h2.7c1.3-.1 1.8-.8 1.8-1.7z"/></g><g id="g4599"><path id="path4597" d="M427.8 266.2h-1.4l-4-6.2c-.2-.4-.6-1-.7-1.2v7.4h-1.4v-9.9h1.5l3.8 6.1c.3.4.7 1.1.8 1.4v-7.4h1.4v9.8z"/></g><g id="g4603"><path id="path4601" d="M482.4 266.2H481v-6.9c-.1.3-.4 1-.6 1.6l-2.4 5.6-2.4-5.6c-.2-.6-.5-1.3-.6-1.6v6.9h-1.4v-9.9h1.5l2.2 5.3c.2.6.6 1.3.7 1.7.1-.4.4-1.1.7-1.7l2.2-5.3h1.6v9.9z"/></g><g id="g4609"><path id="path4605" d="m534 257-4.1-3.6v-1.2l4.1-3.6v1.8l-2.8 2.4 2.8 2.4v1.8z"/><path id="path4607" d="m533 272.7-1.1 3.8h-1l.2-3.8h1.9z"/></g><g id="g4615"><path id="path4611" d="M588.1 253.4 584 257v-1.8l2.8-2.4-2.8-2.4v-1.9l4.1 3.6v1.3z"/><path id="path4613" d="M587.1 273.7c0 .6-.5 1.1-1.1 1.1s-1.1-.5-1.1-1.1.5-1.1 1.1-1.1 1.1.5 1.1 1.1z"/></g><g id="g4621"><path id="path4617" d="M643.3 250.2c0 1.4-.6 2-1.8 2.7-.9.5-1.1.9-1.1 1.9h-1.5c0-1.7.3-2.2 1.9-3.1.7-.4 1-.7 1-1.4 0-.8-.7-1.2-1.9-1.2-1 0-1.8.4-2.5 1.1l-.9-1.1c.8-.8 2-1.5 3.5-1.5 1.9 0 3.3.9 3.3 2.6zm-2.6 6.6c0 .6-.5 1.1-1.1 1.1s-1.1-.5-1.1-1.1.5-1.1 1.1-1.1 1.1.5 1.1 1.1z"/><path id="path4619" d="m642.9 263.5-4.4 12.5H637l4.4-12.5h1.5z"/></g><g id="g4625"><path id="path4623" d="M912.4 259.8c-.1.2-.2.2-.4.2l-1.2-.4v8.6h-1.7v-8.6l-1.1.4c-.2.1-.3 0-.4-.2-.1-.1-.1-.2 0-.4l2.4-3.4 2.4 3.4c.1.2.1.3 0 .4z"/></g><g id="g4629"><path id="path4627" d="M1032.6 266.2h-1.5v-7.6h-1.8v-1c1-.1 1.9-.4 2-1.3h1.2v9.9z"/></g><g id="g4633"><path id="path4631" d="M1088.8 266.2h-7.1c.1-2.9 1.9-4.2 3.8-5.4 1.3-.8 1.7-1.2 1.7-1.9 0-.8-.5-1.3-1.9-1.3-.8 0-1.8.4-2.4 1l-1-1.1c.9-.8 2.2-1.3 3.4-1.3 2.1 0 3.4.9 3.4 2.7 0 1.5-.8 2.2-2.5 3.2-1.9 1.1-2.4 1.8-2.7 2.7h5.3v1.4z"/></g><g id="g4637"><path id="path4635" d="M1142.8 263.2c0 2-1.4 3.1-3.7 3.1-1.4 0-2.9-.6-3.6-1.6l1.1-1c.6.8 1.5 1.1 2.4 1.1 1.6 0 2.2-.6 2.2-1.6s-.8-1.5-1.8-1.5h-.9v-1.4h.9c.9 0 1.4-.6 1.4-1.4 0-.6-.4-1.4-1.9-1.4-.8 0-1.4.3-2 .9l-1.1-1c.8-.9 1.8-1.3 3.1-1.3 1.9 0 3.4 1 3.4 2.7 0 1.2-.5 1.8-1.2 2.2 1.1.2 1.7 1 1.7 2.2z"/></g><g id="g4641"><path id="path4639" d="M861.2 317.2h-7.1l.4 1.1c.1.2 0 .3-.2.4-.1.1-.2.1-.4 0l-3.7-2.4 3.7-2.4c.2-.1.3-.1.4-.1.2.1.2.2.2.4l-.4 1.2h7.1v1.8z"/></g><g id="g4645"><path id="path4643" d="M912.4 318.8c.1.1.1.2-.1.4l-2.4 3.4-2.4-3.4c-.1-.2-.1-.3 0-.4.1-.2.2-.2.4-.2l1.1.4v-8.6h1.7v8.6l1.2-.3c.3-.2.4-.1.5.1z"/></g><g id="g4649"><path id="path4647" d="m969.7 316.4-3.7 2.4c-.2.1-.3.1-.4 0-.2-.1-.2-.2-.2-.4l.4-1.1h-7.1v-1.7h7.1l-.4-1.2c-.1-.2 0-.3.2-.4.1-.1.2-.1.4.1l3.7 2.3z"/></g><g id="g4653"><path id="path4651" d="M1062.4 315.2c0 3-1.4 5.1-3.9 5.1s-3.9-2.1-3.9-5.1 1.4-5.1 3.9-5.1c2.6 0 3.9 2.1 3.9 5.1zm-1.5 0c0-2.1-.7-3.7-2.4-3.7s-2.4 1.6-2.4 3.7.7 3.7 2.4 3.7c1.8 0 2.4-1.6 2.4-3.7z"/></g><g id="g4657"><path id="path4655" d="M1140.6 319.2c0 .6-.5 1.1-1.1 1.1-.6 0-1.1-.5-1.1-1.1s.5-1.1 1.1-1.1c.6 0 1.1.5 1.1 1.1z"/></g><path id="path4659" d="M32.5 19.3c1.5 0 2.8.5 3.8 1.6 1 1 1.6 2.3 1.6 3.8s-.5 2.7-1.6 3.8c-1 1.1-2.3 1.6-3.8 1.6s-2.7-.5-3.8-1.6c-1.1-1.1-1.6-2.3-1.6-3.8h1c0 1.2.4 2.2 1.3 3.1s1.9 1.3 3.1 1.3c1.2 0 2.2-.4 3.1-1.3.9-.9 1.3-1.9 1.3-3.1 0-1.2-.4-2.2-1.3-3.1-.9-.9-1.9-1.3-3.1-1.3v-1zm.4 5-.7.7-3.7-3.7-1.3 1.3v-3.4h3.4l-1.3 1.3 3.6 3.8z"/><g id="g4667"><path id="path4661" d="M28.2 44h-5.3v-8H28v1.2h-3.9v2h2.3v1.2h-2.3v2.5h4.1V44z"/><path id="path4663" d="M35 41.7c0 1.4-.9 2.4-2.9 2.4-1.2 0-2.2-.5-2.8-1.3l.9-.8c.5.6 1.3.9 2.1.9 1.1 0 1.6-.4 1.6-1.2 0-.6-.5-.9-1.8-1.3-1.7-.5-2.5-.9-2.5-2.3s1.2-2.2 2.6-2.2c1.1 0 1.9.4 2.6 1.1l-.8.9c-.5-.5-1.1-.8-1.8-.8-.9 0-1.3.5-1.3 1 0 .6.4.8 1.7 1.2 1.4.5 2.4 1 2.4 2.4z"/><path id="path4665" d="M42.5 42.6c-.6 1-1.5 1.5-2.7 1.5-2.1 0-3.4-1.7-3.4-4.1 0-2.4 1.3-4.1 3.4-4.1 1.3 0 2.2.5 2.7 1.5l-1.1.7c-.4-.6-.8-1-1.6-1-1.4 0-2.1 1.1-2.1 2.9 0 1.8.7 2.9 2.1 2.9.8 0 1.3-.3 1.7-1l1 .7z"/></g><path id="path4669" d="M860.2 20.1c.1.3.1.6.2 1 0 .4.1.9.1 1.4v.7c0 .2 0 .5-.1.7s-.1.4-.1.6-.1.3-.1.4v.1c-.2.1-.5.2-.8.3-.3.1-.6.2-1 .3-.4.1-.7.1-1.1.2-.4 0-.8.1-1.2.1-.4 0-.8 0-1.2-.1s-.8-.1-1.1-.2-.7-.2-1-.3c-.3-.1-.5-.2-.7-.3h-.1v-.1c0-.1-.1-.3-.1-.5s-.1-.4-.1-.6c0-.2-.1-.4-.1-.7v-.7c0-.5 0-1 .1-1.4s.1-.8.2-1v-.1h.1c.3-.2.8-.3 1.3-.5s1.1-.3 1.8-.3l1.1-1.1h1.4v1.2c.5.1 1 .2 1.4.3.4.1.8.3 1 .5l.1.1zm-2 .1c-.1 0-.2 0-.3-.1-.1 0-.2-.1-.3-.1v2.7H854v-2.5l.3-.3c-.4.1-.7.1-1 .2s-.5.2-.7.3l-.1.7c0 .2-.1.4-.1.7v.7c0 .4 0 .8.1 1.2s.1.6.2.9l.6.3c.2.1.5.2.8.2.3.1.6.1 1 .1h2c.3 0 .7-.1.9-.1s.6-.1.8-.2l.6-.3c.1-.2.1-.5.2-.9s.1-.7.1-1.2 0-.8-.1-1.1c0-.4-.1-.6-.2-.9-.2-.1-.4-.1-.6-.2-.2 0-.4-.1-.6-.1zm-3.9.2v2.1h3.1v-4.1h-1v2h-2.1zm.2-.2h1.6v-1.6l-1.6 1.6zm3-.2c.1 0 .1 0 0 0 .1 0 .1 0 0 0z"/><g id="g4693"><path id="path4671" d="M848.6 31.9c0 1.2-.8 1.9-2 1.9H845V36h-.9v-6h2.5c1.2 0 2 .7 2 1.9zm-.9 0c0-.7-.4-1-1-1H845v2h1.6c.7 0 1.1-.4 1.1-1z"/><path id="path4673" d="M854.2 31.8c0 1-.5 1.5-1.3 1.7l1.2 2.4h-1l-1.2-2.4h-1.3V36h-.9v-6h2.6c1.1 0 1.9.6 1.9 1.8zm-.9 0c0-.6-.4-1-1-1h-1.7v1.9h1.7c.6.1 1-.2 1-.9z"/><path id="path4675" d="M856.6 36h-.9v-6h.9v6z"/><path id="path4677" d="M862.7 36h-.8l-2.4-3.7c-.1-.2-.3-.6-.4-.7V36h-.9v-6h.9l2.3 3.6c.2.2.4.7.5.8V30h.9v6z"/><path id="path4679" d="M868.2 30.9h-1.7V36h-.9v-5.1h-1.7V30h4.4v.9z"/><path id="path4681" d="M844.1 44.5c0 1.1-.7 1.8-2.2 1.8-.9 0-1.6-.4-2.1-1l.6-.6c.4.4 1 .7 1.5.7.8 0 1.2-.3 1.2-.9 0-.5-.3-.7-1.3-1-1.3-.4-1.9-.7-1.9-1.8 0-1 .9-1.7 2-1.7.8 0 1.4.3 1.9.8l-.6.6c-.4-.4-.8-.6-1.4-.6-.7 0-1 .3-1 .7 0 .4.3.6 1.3.9 1.3.6 2 1 2 2.1z"/><path id="path4683" d="M849.7 45.1c-.4.7-1.1 1.1-2 1.1-1.5 0-2.5-1.3-2.5-3.1s1-3.1 2.5-3.1c1 0 1.6.4 2 1.1l-.8.5c-.3-.5-.6-.7-1.2-.7-1 0-1.6.8-1.6 2.2s.6 2.2 1.6 2.2c.6 0 1-.3 1.3-.7l.7.5z"/><path id="path4685" d="M855.5 42c0 1-.5 1.5-1.3 1.7l1.2 2.4h-1l-1.2-2.4h-1.3v2.4h-.9v-5.9h2.6c1 0 1.9.6 1.9 1.8zm-.9 0c0-.6-.4-1-1-1h-1.7v2h1.7c.6 0 1-.3 1-1z"/><path id="path4687" d="M860.8 46.2h-4v-5.9h3.8v.9h-2.9v1.5h1.7v.9h-1.7v1.9h3.1v.7z"/><path id="path4689" d="M866.1 46.2h-4v-5.9h3.8v.9H863v1.5h1.7v.9H863v1.9h3.1v.7z"/><path id="path4691" d="M871.9 46.2h-.9l-2.4-3.7c-.1-.2-.3-.6-.4-.7v4.5h-.9v-5.9h.9l2.3 3.6c.2.2.4.7.5.8v-4.5h.9v5.9z"/></g><path id="path4695" d="M912.7 19.8h-.9l-.5-.4v5.3l.5-.4h.9l-2.7 2.2-2.7-2.1h.9l.5.4v-5.3l-.5.4h-.9l2.7-2.1 2.7 2zm-2.1-1-.5-.4-.5.4v6.4l.5.4.5-.4v-6.4z"/><g id="g4717"><path id="path4697" d="M898.4 34.3c0 1.1-.7 1.8-2.2 1.8-.9 0-1.6-.4-2.1-1l.6-.6c.4.4 1 .7 1.5.7.8 0 1.2-.3 1.2-.9 0-.5-.3-.7-1.3-1-1.3-.4-1.9-.7-1.9-1.8 0-1 .9-1.7 2-1.7.8 0 1.4.3 1.9.8l-.6.6c-.4-.4-.8-.6-1.4-.6-.7 0-1 .3-1 .7 0 .4.3.6 1.3.9 1.2.6 2 1 2 2.1z"/><path id="path4699" d="M904 34.9c-.4.7-1.1 1.1-2 1.1-1.5 0-2.5-1.3-2.5-3.1s1-3.1 2.5-3.1c1 0 1.6.4 2 1.1l-.8.5c-.3-.5-.6-.7-1.2-.7-1 0-1.6.8-1.6 2.2s.6 2.2 1.6 2.2c.6 0 1-.3 1.3-.7l.7.5z"/><path id="path4701" d="M909.8 31.8c0 1-.5 1.5-1.3 1.7l1.2 2.4h-1l-1.2-2.4h-1.3V36h-.9v-6h2.6c1 0 1.9.6 1.9 1.8zm-.9 0c0-.6-.4-1-1-1h-1.7v1.9h1.7c.5.1 1-.2 1-.9z"/><path id="path4703" d="M915.8 33c0 1.9-1 3.1-2.5 3.1s-2.5-1.2-2.5-3.1c0-1.9 1-3.1 2.5-3.1s2.5 1.2 2.5 3.1zm-.9 0c0-1.4-.7-2.2-1.6-2.2-.9 0-1.6.8-1.6 2.2 0 1.4.7 2.2 1.6 2.2.9 0 1.6-.8 1.6-2.2z"/><path id="path4705" d="M920.9 36H917v-6h.9v5.1h3v.9z"/><path id="path4707" d="M926 36h-3.9v-6h.9v5.1h3v.9z"/><path id="path4709" d="M903.5 46.2h-3.9v-5.9h.9v5.1h3v.8z"/><path id="path4711" d="M909.2 43.2c0 1.9-1 3.1-2.5 3.1s-2.5-1.2-2.5-3.1c0-1.9 1-3.1 2.5-3.1s2.5 1.2 2.5 3.1zm-.9 0c0-1.4-.7-2.2-1.6-2.2-.9 0-1.6.8-1.6 2.2 0 1.4.7 2.2 1.6 2.2 1 0 1.6-.8 1.6-2.2z"/><path id="path4713" d="M914.8 45.1c-.4.7-1.1 1.1-2 1.1-1.5 0-2.5-1.3-2.5-3.1s1-3.1 2.5-3.1c1 0 1.6.4 2 1.1l-.8.5c-.3-.5-.6-.7-1.2-.7-1 0-1.6.8-1.6 2.2s.6 2.2 1.6 2.2c.6 0 1-.3 1.3-.7l.7.5z"/><path id="path4715" d="M920.8 46.2h-1l-1.7-3.1-1.1 1.3v1.7h-.9v-5.9h.9v3.1c.1-.2.5-.6.7-.9l1.8-2.2h1l-1.7 2.2 2 3.8z"/></g><path id="path4719" d="M961.2 22c0 .3 0 .7-.1 1-.1.3-.2.6-.4.9-.2.3-.4.5-.6.8-.2.2-.5.4-.8.6-.3.2-.6.3-.9.4-.3.1-.7.1-1 .1-.3 0-.7 0-1-.1-.3-.1-.6-.2-.9-.4-.3-.2-.5-.4-.8-.6-.2-.2-.4-.5-.6-.8-.2-.3-.3-.6-.4-.9-.1-.3-.1-.7-.1-1 0-.4 0-.7.1-1 .1-.3.2-.6.4-.9.2-.3.4-.5.6-.8.2-.2.5-.4.8-.6.3-.2.6-.3.9-.4.3-.1.7-.1 1-.1.3 0 .7 0 1 .1.3.1.6.2.9.4s.5.4.8.6c.2.2.4.5.6.8.2.3.3.6.4.9s.1.7.1 1zm-1.6.4-2.2 2.4-2.2-2.4h-.8c0 .4.1.7.3 1.1.2.3.4.6.6.8l.9.6c.3.1.7.2 1.1.2.4 0 .8-.1 1.1-.2.4-.1.7-.3.9-.6s.5-.5.6-.8c.2-.3.3-.7.3-1.1h-.6zm.8-.9c0-.4-.1-.7-.3-1-.2-.3-.4-.6-.7-.8s-.6-.4-.9-.5c-.3-.1-.7-.2-1.1-.2-.4 0-.8.1-1.1.2-.3.1-.6.3-.9.5s-.5.5-.7.8c-.2.3-.3.6-.3 1h1l1.9 2.1 1.9-2.1h1.2z"/><path id="path4721" d="M974 22c0 .3 0 .7-.1 1s-.2.6-.4.9-.4.5-.6.8c-.2.2-.5.4-.8.6-.3.2-.6.3-.9.4-.3.1-.7.1-1 .1s-.7 0-1-.1-.6-.2-.9-.4c-.3-.2-.5-.4-.8-.6-.2-.2-.4-.5-.6-.8s-.3-.6-.4-.9-.1-.7-.1-1 0-.7.1-1 .2-.6.4-.9c.2-.3.4-.5.6-.8.2-.2.5-.4.8-.6.3-.2.6-.3.9-.4.3-.1.7-.1 1-.1s.7 0 1 .1c.3.1.6.2.9.4.3.2.5.4.8.6.2.2.4.5.6.8.2.3.3.6.4.9 0 .3.1.7.1 1zm-.8 0c0-.3 0-.5-.1-.8s-.2-.5-.3-.7-.3-.4-.5-.6-.4-.3-.6-.5c-.2-.1-.5-.2-.7-.3-.3-.1-.5-.1-.8-.1-.4 0-.8.1-1.2.2-.4.2-.7.4-1 .7s-.5.6-.7 1c-.2.4-.2.8-.2 1.2s.1.8.2 1.2c.2.4.4.7.7 1s.6.5 1 .7c.4.2.8.2 1.2.2.4 0 .8-.1 1.2-.2.4-.2.7-.4 1-.7s.5-.6.7-1 .1-.9.1-1.3zm-5.7-1.4h5.4l-2.7 4.5-2.7-4.5zm4.6.5h-3.8l1.9 3.2 1.9-3.2z"/><g id="g4733"><path id="path4723" d="M955.5 32.2c0 1.2-.8 1.9-2 1.9H952v2.2h-.9v-5.9h2.5c1.1-.1 1.9.5 1.9 1.8zm-.9 0c0-.7-.4-1-1-1H952v2h1.6c.7 0 1-.4 1-1z"/><path id="path4725" d="M960.9 36.2h-1l-.5-1.4H957l-.5 1.4h-.9l2.1-5.9h.9l2.3 5.9zm-1.7-2.2-.5-1.4c-.1-.4-.4-1.1-.5-1.4-.1.3-.3.9-.4 1.4l-.5 1.4h1.9z"/><path id="path4727" d="M966.4 33.8c0 1.7-.8 2.6-2.3 2.6-1.5 0-2.2-1-2.2-2.6v-3.5h.9v3.4c0 1.1.5 1.7 1.4 1.7.9 0 1.4-.6 1.4-1.7v-3.5h.9v3.6z"/><path id="path4729" d="M971.9 34.5c0 1.1-.7 1.8-2.2 1.8-.9 0-1.6-.4-2.1-1l.6-.6c.4.4 1 .7 1.5.7.8 0 1.2-.3 1.2-.9 0-.5-.3-.7-1.3-1-1.3-.4-1.9-.7-1.9-1.8 0-1 .9-1.7 2-1.7.8 0 1.4.3 1.9.8l-.6.6c-.4-.4-.8-.6-1.4-.6-.7 0-1 .3-1 .7 0 .4.3.6 1.3.9 1.2.7 2 1.1 2 2.1z"/><path id="path4731" d="M977.2 36.2h-4v-5.9h3.8v.9h-2.9v1.5h1.7v.9h-1.7v1.9h3.1v.7z"/></g><g id="g4745"><path id="path4735" d="M954.8 44.6c0 1.2-.7 1.8-2 1.8h-2.4v-5.9h2.4c1 0 1.7.5 1.7 1.5 0 .6-.3 1-.8 1.2.6.2 1.1.6 1.1 1.4zm-1.1-2.5c0-.4-.2-.8-.8-.8h-1.6v1.5h1.6c.5.1.8-.3.8-.7zm.2 2.6c0-.6-.4-1-1.1-1h-1.6v2h1.6c.8-.1 1.1-.5 1.1-1z"/><path id="path4737" d="M960.7 42.3c0 1-.5 1.5-1.3 1.7l1.2 2.4h-1l-1.2-2.4H957v2.4h-.9v-5.9h2.6c1.1 0 2 .6 2 1.8zm-.9 0c0-.6-.4-1-1-1H957v1.9h1.7c.6.1 1.1-.2 1.1-.9z"/><path id="path4739" d="M966 46.5h-4v-5.9h3.8v.9h-2.9V43h1.7v.9h-1.7v1.9h3.1v.7z"/><path id="path4741" d="M972.1 46.5h-1l-.5-1.4h-2.4l-.5 1.4h-.9l2.1-5.9h.9l2.3 5.9zm-1.7-2.3-.5-1.4c-.1-.4-.4-1.1-.5-1.4-.1.3-.3.9-.4 1.4l-.5 1.4h1.9z"/><path id="path4743" d="M978 46.5h-1l-1.7-3.1-1.1 1.3v1.7h-.9v-5.9h.9v3.1c.1-.2.5-.6.7-.9l1.8-2.2h1l-1.7 2.2 2 3.8z"/></g><path id="path4747" d="m759.2 97.2-5.1-5.1 5.1-5.1h9.5v10.2h-9.5zm-3.7-5.1 4.1 4.1h8.1V88h-8.1l-4.1 4.1zm7.2.7-2.3 2.3-.7-.7 2.3-2.3-2.3-2.3.7-.7 2.3 2.3 2.3-2.3.7.7-2.3 2.3 2.3 2.3-.7.7-2.3-2.3z"/><g id="g4767"><path id="path4749" d="M735.4 109c0 1.6-1 2.4-2.7 2.4h-3.2v-7.9h3.3c1.4 0 2.3.7 2.3 2.1 0 .8-.4 1.3-1 1.6.6.1 1.3.7 1.3 1.8zm-1.5-3.4c0-.6-.3-1-1.1-1h-2.1v2.1h2.1c.8-.1 1.1-.6 1.1-1.1zm.3 3.4c0-.8-.5-1.3-1.4-1.3h-2.2v2.6h2.1c1.2 0 1.5-.5 1.5-1.3z"/><path id="path4751" d="M743.5 111.4h-1.3l-.7-1.9h-3.2l-.7 1.9h-1.2l2.9-7.9h1.3l2.9 7.9zm-2.3-3-.6-1.8-.6-1.8-.6 1.8-.6 1.8h2.4z"/><path id="path4753" d="M750.5 110c-.6 1-1.5 1.5-2.7 1.5-2.1 0-3.4-1.7-3.4-4.1 0-2.4 1.3-4.1 3.4-4.1 1.3 0 2.2.5 2.7 1.5l-1.1.7c-.4-.6-.8-1-1.6-1-1.4 0-2.1 1.1-2.1 2.9 0 1.8.7 2.9 2.1 2.9.8 0 1.3-.3 1.7-1l1 .7z"/><path id="path4755" d="M758.5 111.4h-1.3l-2.3-4.1-1.5 1.8v2.3h-1.2v-7.9h1.2v4.1c.1-.2.7-.9.9-1.2l2.3-2.9h1.3l-2.3 2.9 2.9 5z"/><path id="path4757" d="M764.9 109.1c0 1.4-.9 2.4-2.9 2.4-1.2 0-2.2-.5-2.8-1.3l.8-.8c.5.6 1.3.9 2.1.9 1.1 0 1.6-.4 1.6-1.2 0-.6-.5-.9-1.8-1.3-1.7-.5-2.5-.9-2.5-2.3s1.2-2.2 2.6-2.2c1.1 0 1.9.4 2.6 1.1l-.8.9c-.5-.5-1.1-.8-1.8-.8-.9 0-1.3.5-1.3 1 0 .6.4.8 1.7 1.2 1.5.5 2.5 1 2.5 2.4z"/><path id="path4759" d="M772.5 105.9c0 1.6-1.1 2.5-2.6 2.5h-2.1v3h-1.2v-7.9h3.3c1.6 0 2.6.8 2.6 2.4zm-1.2 0c0-.9-.5-1.4-1.4-1.4h-2.1v2.7h2.1c1 .1 1.4-.4 1.4-1.3z"/><path id="path4761" d="M779.8 111.4h-1.3l-.7-1.9h-3.2l-.7 1.9h-1.2l2.9-7.9h1.3l2.9 7.9zm-2.3-3-.6-1.8-.6-1.8-.6 1.8-.6 1.8h2.4z"/><path id="path4763" d="M786.8 110c-.6 1-1.5 1.5-2.7 1.5-2.1 0-3.4-1.7-3.4-4.1 0-2.4 1.3-4.1 3.4-4.1 1.3 0 2.2.5 2.7 1.5l-1.1.7c-.4-.6-.8-1-1.6-1-1.4 0-2.1 1.1-2.1 2.9 0 1.8.7 2.9 2.1 2.9.8 0 1.3-.3 1.7-1l1 .7z"/><path id="path4765" d="M793.8 111.4h-5.3v-7.9h5.1v1.2h-3.9v2h2.3v1.2h-2.3v2.5h4.1v1z"/></g><path id="path4769" d="M848.5 87.9h1.5l5.9 6.3 5.9-6.3h1.6l-7.5 7.9-7.4-7.9zm8.3 3.2c-.1-.2-.1-.4-.1-.5-.3.3-.5.5-.7.5-.2.1-.4.1-.6.1-.3 0-.6-.1-.8-.3s-.3-.5-.3-.8c0-.4.2-.7.5-.9.3-.2.9-.4 1.6-.5l.4-.1v-.4c0-.2-.1-.4-.2-.5-.2-.1-.4-.1-.6-.1-.3 0-.5.1-.6.2-.2.1-.2.3-.2.4v.1h-.7v-.1c0-.2.1-.3.2-.5s.3-.3.6-.4.5-.1.8-.1c.3 0 .5 0 .8.1.2.1.4.2.5.4.1.2.2.4.2.8v2c0 .2.1.4.1.6h-.9zm-.1-1.9h-.2c-.7.2-1.1.3-1.3.5-.2.1-.3.3-.3.5 0 .1 0 .2.1.3.1.1.1.2.2.2.1.1.2.1.3.1.2 0 .4-.1.5-.2.2-.1.3-.2.4-.4.1-.2.1-.4.1-.6v-.4z"/><g id="g4783"><path id="path4771" d="M838.3 111.2h-1.2v-7.9h1.2v7.9z"/><path id="path4773" d="M846.4 111.2h-1.1l-3.2-5c-.2-.3-.5-.8-.6-1v5.9h-1.2v-7.9h1.2l3 4.8c.2.3.5.9.7 1.1v-6h1.2v8.1z"/><path id="path4775" d="M853.8 109c0 1.4-.9 2.4-2.9 2.4-1.2 0-2.2-.5-2.8-1.3l.8-.8c.5.6 1.3.9 2.1.9 1.1 0 1.6-.4 1.6-1.2 0-.6-.5-.9-1.8-1.3-1.7-.5-2.5-.9-2.5-2.3s1.2-2.2 2.6-2.2c1.1 0 1.9.4 2.6 1.1l-.8.9c-.5-.5-1.1-.8-1.8-.8-.9 0-1.3.5-1.3 1 0 .6.4.8 1.7 1.2 1.5.5 2.5 1 2.5 2.4z"/><path id="path4777" d="M860.9 111.2h-5.3v-7.9h5.1v1.2h-3.9v2h2.3v1.2h-2.3v2.5h4.1v1z"/><path id="path4779" d="M868.6 105.7c0 1.3-.7 2.1-1.7 2.3l1.6 3.2h-1.4l-1.6-3.1h-1.8v3.1h-1.2v-7.9h3.5c1.4 0 2.6.7 2.6 2.4zm-1.2 0c0-.8-.5-1.3-1.3-1.3h-2.3v2.6h2.3c.7 0 1.3-.4 1.3-1.3z"/><path id="path4781" d="M875.5 104.5h-2.3v6.8H872v-6.8h-2.3v-1.2h5.8v1.2z"/></g><path id="path4785" d="M913.8 87.9v.5h-7.1v7.1h-.5v-7.6h7.6zm-6 2 .4-.4h2.9v.9h-1.6l4.3 4.3-.8.8-4.3-4.3v1.6h-.9v-2.9z"/><g id="g4795"><path id="path4787" d="M900.9 110.4h-1.2v-3.5H896v3.5h-1.2v-7.9h1.2v3.2h3.7v-3.2h1.2v7.9z"/><path id="path4789" d="M909.4 106.5c0 2.5-1.4 4.1-3.4 4.1s-3.4-1.6-3.4-4.1c0-2.5 1.4-4.1 3.4-4.1s3.4 1.6 3.4 4.1zm-1.2 0c0-1.8-.9-2.9-2.2-2.9-1.3 0-2.1 1.1-2.1 2.9s.9 2.9 2.2 2.9c1.2 0 2.1-1.1 2.1-2.9z"/><path id="path4791" d="M918.1 110.4H917v-5.6c-.1.2-.3.8-.5 1.2l-1.9 4.5-1.9-4.5c-.2-.5-.4-1-.5-1.2v5.6H911v-7.9h1.2l1.8 4.2c.2.5.4 1 .5 1.4.1-.3.3-.9.5-1.4l1.7-4.2h1.3v7.9z"/><path id="path4793" d="M925.5 110.4h-5.3v-7.9h5.1v1.2h-3.9v2h2.3v1.2h-2.3v2.5h4.1v1z"/></g><path id="path4797" d="M964.5 92.3h1.8v1h-1.8v1.2h1.8v1h-1.8v2.7h-1v-2.7h-1.8v-1h1.8v-1.2h-1.8v-1h1.8v-2.1H961l3-3 3 3h-2.5v2.1z"/><g id="g4807"><path id="path4799" d="M954.4 105.9c0 1.6-1.1 2.4-2.6 2.4h-2v2.9h-1.1v-7.7h3.2c1.4-.1 2.5.8 2.5 2.4zm-1.2 0c0-.9-.5-1.3-1.3-1.3h-2.1v2.7h2.1c.9-.1 1.3-.6 1.3-1.4z"/><path id="path4801" d="M961.7 108.2c0 2-1.2 3.2-2.9 3.2-2 0-3.3-1.6-3.3-4s1.3-4 3.3-4c1.3 0 2.1.5 2.6 1.4l-1 .6c-.4-.6-.8-.9-1.6-.9-1.3 0-2.1 1.1-2.1 2.8s.7 2.8 2.1 2.8c1.3 0 1.8-.8 1.8-1.7h-1.3v-1.1h2.4v.9z"/><path id="path4803" d="M972.2 108c0 2.2-1.1 3.4-3 3.4s-2.9-1.2-2.9-3.4v-4.5h1.2v4.5c0 1.5.6 2.2 1.8 2.2 1.2 0 1.8-.8 1.8-2.2v-4.5h1.2v4.5z"/><path id="path4805" d="M979.9 105.9c0 1.6-1.1 2.4-2.6 2.4h-2v2.9h-1.1v-7.7h3.2c1.4-.1 2.5.8 2.5 2.4zm-1.2 0c0-.9-.5-1.3-1.3-1.3h-2.1v2.7h2.1c.8-.1 1.3-.6 1.3-1.4z"/></g><path id="path4809" d="M1030.1 91v-3.4h-1.2l2.6-2.6 2.6 2.6h-1.2V91h1.2v2h-5.2v-2h1.2zm1.2-5-1.1 1.1h.4v4.4h-1.2v1h1.9V86zm.4 0v6.5h1.9v-1h-1.2v-4.4h.4l-1.1-1.1z"/><path id="path4811" d="M1027.3 103.2h-.8l-2.4-3.7c-.1-.2-.3-.6-.4-.7v4.5h-.9v-5.9h.9l2.3 3.6c.2.2.4.7.5.8v-4.5h.9v5.9z"/><path id="path4813" d="M1033.4 100.7c0 1.7-.8 2.6-2.3 2.6-1.5 0-2.2-1-2.2-2.6v-3.5h.9v3.4c0 1.1.5 1.7 1.4 1.7.9 0 1.4-.6 1.4-1.7v-3.5h.9v3.6z"/><path id="path4815" d="M1040.2 103.2h-.9V99c-.1.2-.2.6-.4.9l-1.4 3.3-1.4-3.3c-.1-.3-.3-.8-.4-.9v4.1h-.8v-5.9h.9l1.3 3.2c.1.3.3.8.4 1 .1-.2.3-.7.4-1l1.3-3.2h1v6z"/><path id="path4817" d="M1025 113.4h-3.9v-5.9h.9v5.1h3v.8z"/><path id="path4819" d="M1030.7 110.4c0 1.9-1 3.1-2.5 3.1s-2.5-1.2-2.5-3.1c0-1.9 1-3.1 2.5-3.1s2.5 1.2 2.5 3.1zm-.9 0c0-1.4-.7-2.2-1.6-2.2-.9 0-1.6.8-1.6 2.2 0 1.4.7 2.2 1.6 2.2 1 0 1.6-.9 1.6-2.2z"/><path id="path4821" d="M1036.3 112.3c-.4.7-1.1 1.1-2 1.1-1.5 0-2.5-1.3-2.5-3.1s1-3.1 2.5-3.1c1 0 1.6.4 2 1.1l-.8.5c-.3-.5-.6-.7-1.2-.7-1 0-1.6.8-1.6 2.2s.6 2.2 1.6 2.2c.6 0 1-.3 1.3-.7l.7.5z"/><path id="path4823" d="M1042.3 113.4h-1l-1.7-3.1-1.1 1.3v1.7h-.9v-5.9h.9v3.1c.1-.2.5-.6.7-.9l1.8-2.2h1l-1.7 2.2 2 3.8z"/><path id="path4825" d="m44.2 141.3-1.9 2h10v.9h-10l1.9 2-.5.5-3.1-2.9v2.6h-.9V141h.9v2.6l3.1-2.9.5.6zm8.1 5.5v5.4h-.9v-2.6l-3.1 2.9-.5-.5 1.9-2h-10v-.9h10l-1.9-2 .5-.5 3.1 2.9v-2.6h.9z"/><g id="g4833"><path id="path4827" d="M41.6 158.9h-2.3v6.8h-1.2v-6.8h-2.3v-1.2h5.8v1.2z"/><path id="path4829" d="M48.6 165.6h-1.3l-.7-1.9h-3.2l-.7 1.9h-1.2l2.9-7.9h1.3l2.9 7.9zm-2.3-2.9-.6-1.8-.6-1.8-.6 1.8-.6 1.8h2.4z"/><path id="path4831" d="M56 163.2c0 1.6-1 2.4-2.7 2.4h-3.2v-7.9h3.3c1.4 0 2.3.7 2.3 2.1 0 .8-.4 1.3-1 1.6.6.1 1.3.7 1.3 1.8zm-1.5-3.4c0-.6-.3-1-1.1-1h-2.1v2.1h2.1c.8-.1 1.1-.6 1.1-1.1zm.4 3.4c0-.8-.5-1.3-1.4-1.3h-2.2v2.6h2.1c1.1 0 1.5-.5 1.5-1.3z"/></g><path id="path4835" d="M858.3 151.7h-9.5v-10.2h9.5l5.1 5.1-5.1 5.1zm3.7-5.1-4.1-4.1h-8.1v8.2h8.1l4.1-4.1zm-7.2.7-2.3 2.3-.7-.7 2.3-2.3-2.3-2.3.7-.7 2.3 2.3 2.3-2.3.7.7-2.3 2.3 2.3 2.3-.7.7-2.3-2.3z"/><g id="g4843"><path id="path4837" d="M852.4 161.3c0 2.8-1.8 4-3.9 4h-2.2v-7.9h2.2c2.1 0 3.9 1.1 3.9 3.9zm-1.3 0c0-1.7-.8-2.8-2.7-2.8h-1v5.6h1c2 .1 2.7-1.1 2.7-2.8z"/><path id="path4839" d="M859.3 165.3H854v-7.9h5.1v1.2h-3.9v2h2.3v1.2h-2.3v2.5h4.1v1z"/><path id="path4841" d="M866.1 165.3H861v-7.9h1.2v6.8h4v1.1z"/></g><path id="path4845" d="M911.8 148.6h-2.9v-.9h1.6l-4.3-4.3.8-.8 4.3 4.3v-1.6h.9v2.9l-.4.4zm2-5.9v7.6h-7.6v-.5h7.1v-7.1h.5z"/><g id="g4853"><path id="path4847" d="M904.9 165.3h-5.3v-7.9h5.1v1.2h-3.9v2h2.3v1.2h-2.3v2.5h4.1v1z"/><path id="path4849" d="M912.7 165.3h-1.1l-3.2-5c-.2-.3-.5-.8-.6-1v5.9h-1.2v-7.9h1.2l3 4.8c.2.3.5.9.7 1.1v-6h1.2v8.1z"/><path id="path4851" d="M920.7 161.3c0 2.8-1.8 4-3.9 4h-2.2v-7.9h2.2c2.2 0 3.9 1.1 3.9 3.9zm-1.2 0c0-1.7-.8-2.8-2.7-2.8h-1v5.6h1c2 .1 2.7-1.1 2.7-2.8z"/></g><path id="path4855" d="M963.5 147.4h-1.8v-1h1.8v-1.2h-1.8v-1h1.8v-2.7h1v2.7h1.8v1h-1.8v1.2h1.8v1h-1.8v2.1h2.5l-3 3-3-3h2.5v-2.1z"/><g id="g4865"><path id="path4857" d="M953.9 159.9c0 1.6-1.1 2.5-2.6 2.5h-2.1v3H948v-7.9h3.3c1.5-.1 2.6.7 2.6 2.4zm-1.2 0c0-.9-.5-1.4-1.4-1.4h-2.1v2.7h2.1c1 0 1.4-.5 1.4-1.3z"/><path id="path4859" d="M961.5 162.2c0 2-1.2 3.2-3 3.2-2.1 0-3.4-1.7-3.4-4.1 0-2.4 1.3-4.1 3.4-4.1 1.3 0 2.2.5 2.7 1.5l-1 .6c-.4-.6-.8-.9-1.7-.9-1.4 0-2.1 1.1-2.1 2.9 0 1.8.8 2.9 2.1 2.9s1.8-.9 1.8-1.8H959v-1.1h2.5v.9z"/><path id="path4861" d="M972.2 161.3c0 2.8-1.8 4-3.9 4h-2.2v-7.9h2.2c2.2 0 3.9 1.1 3.9 3.9zm-1.2 0c0-1.7-.8-2.8-2.7-2.8h-1v5.6h1c2 .1 2.7-1.1 2.7-2.8z"/><path id="path4863" d="M979.9 165.3h-1.1l-3.2-5c-.2-.3-.5-.8-.6-1v5.9h-1.2v-7.9h1.2l3 4.8c.2.3.5.9.7 1.1v-6h1.2v8.1z"/></g><path id="path4867" d="m47.2 200.4 5.6-5.6 5.6 5.6h-2.8v2.1H50v-2.1h-2.8zm5.6-4.4-3.7 3.7h1.7v2h4v-2h1.7l-3.7-3.7zm-2.8 8.1h5.6v2.8H50v-2.8zm.8.8v1.2h4v-1.2h-4z"/><g id="g4885"><path id="path4869" d="M28.3 218.2c-.6 1-1.5 1.5-2.7 1.5-2.1 0-3.4-1.7-3.4-4.1s1.3-4.1 3.4-4.1c1.3 0 2.2.5 2.7 1.5l-1.1.7c-.4-.6-.8-1-1.6-1-1.4 0-2.1 1.1-2.1 2.9 0 1.8.7 2.9 2.1 2.9.8 0 1.3-.3 1.7-1l1 .7z"/><path id="path4871" d="M36.3 219.5H35l-.7-1.9h-3.2l-.7 1.9h-1.2l2.9-7.9h1.3l2.9 7.9zm-2.3-2.9-.6-1.8-.6-1.8-.6 1.8-.6 1.8H34z"/><path id="path4873" d="M43.7 214.1c0 1.6-1.1 2.5-2.6 2.5H39v3h-1.2v-7.9h3.3c1.6-.1 2.6.8 2.6 2.4zm-1.2 0c0-.9-.5-1.4-1.4-1.4H39v2.7h2.1c1 .1 1.4-.5 1.4-1.3z"/><path id="path4875" d="M50.5 217.3c0 1.4-.9 2.4-2.9 2.4-1.2 0-2.2-.5-2.8-1.3l.9-.8c.5.6 1.3.9 2.1.9 1.1 0 1.6-.4 1.6-1.2 0-.6-.5-.9-1.8-1.3-1.7-.5-2.5-.9-2.5-2.3s1.2-2.2 2.6-2.2c1.1 0 1.9.4 2.6 1.1l-.8.8c-.5-.5-1.1-.8-1.8-.8-.9 0-1.3.5-1.3 1 0 .6.4.8 1.7 1.2 1.4.6 2.4 1.1 2.4 2.5z"/><path id="path4877" d="M60.5 219.5h-5.1v-7.9h1.2v6.8h4v1.1z"/><path id="path4879" d="M68.1 215.6c0 2.5-1.4 4.1-3.4 4.1s-3.4-1.6-3.4-4.1 1.4-4.1 3.4-4.1c2.1 0 3.4 1.6 3.4 4.1zm-1.2 0c0-1.8-.9-2.9-2.2-2.9-1.3 0-2.1 1.1-2.1 2.9s.9 2.9 2.2 2.9c1.2 0 2.1-1.1 2.1-2.9z"/><path id="path4881" d="M75.5 218.2c-.6 1-1.5 1.5-2.7 1.5-2.1 0-3.4-1.7-3.4-4.1s1.3-4.1 3.4-4.1c1.3 0 2.2.5 2.7 1.5l-1.1.7c-.4-.6-.8-1-1.6-1-1.4 0-2.1 1.1-2.1 2.9 0 1.8.7 2.9 2.1 2.9.8 0 1.3-.3 1.7-1l1 .7z"/><path id="path4883" d="M83.5 219.5h-1.3l-2.3-4.1-1.5 1.8v2.3h-1.2v-7.9h1.2v4.1c.1-.2.7-.9.9-1.2l2.3-2.9H83l-2.3 2.9 2.8 5z"/></g><path id="path4887" d="m748.9 200.5 3-3v2.5h7.1v-4.4h-3.5v-1h4.6v6.4H752v2.5l-3.1-3z"/><g id="g4901"><path id="path4889" d="M739 214.2c0 1.3-.7 2.1-1.7 2.3l1.6 3.2h-1.4l-1.6-3.1h-1.8v3.1h-1.2v-7.9h3.5c1.4 0 2.6.8 2.6 2.4zm-1.2.1c0-.8-.5-1.3-1.3-1.3h-2.3v2.6h2.3c.7-.1 1.3-.5 1.3-1.3z"/><path id="path4891" d="M746.1 219.8h-5.3v-7.9h5.1v1.2H742v2h2.3v1.2H742v2.5h4.1v1z"/><path id="path4893" d="M753.1 213h-2.3v6.8h-1.2V213h-2.3v-1.2h5.8v1.2z"/><path id="path4895" d="M760.6 216.5c0 2.2-1.1 3.4-3 3.4-2 0-3-1.3-3-3.5v-4.6h1.2v4.6c0 1.5.6 2.3 1.8 2.3 1.2 0 1.8-.8 1.8-2.2v-4.6h1.2v4.6z"/><path id="path4897" d="M768.7 214.2c0 1.3-.7 2.1-1.7 2.3l1.6 3.2h-1.4l-1.6-3.1h-1.8v3.1h-1.2v-7.9h3.5c1.4 0 2.6.8 2.6 2.4zm-1.2.1c0-.8-.5-1.3-1.3-1.3h-2.3v2.6h2.3c.7-.1 1.3-.5 1.3-1.3z"/><path id="path4899" d="M776.6 219.8h-1.1l-3.2-5c-.2-.3-.5-.8-.6-1v5.9h-1.2v-7.9h1.2l3 4.8c.2.3.5.9.7 1.1v-6h1.2v8.1z"/></g><path id="path4903" d="m60.4 254.4 5.9-5.9 5.9 5.9h-2.9v5.2h-5.9v-5.2h-3zm5.8-4.6-3.9 3.9h1.8v5.1h4.2v-5.1h1.8l-3.9-3.9z"/><g id="g4915"><path id="path4905" d="M56.6 271.5c0 1.4-.9 2.4-2.9 2.4-1.2 0-2.2-.5-2.8-1.3l.9-.8c.5.6 1.3.9 2.1.9 1.1 0 1.6-.4 1.6-1.2 0-.6-.5-.9-1.8-1.3-1.7-.5-2.5-.9-2.5-2.3s1.2-2.2 2.6-2.2c1.1 0 1.9.4 2.6 1.1l-.8.8c-.5-.5-1.1-.8-1.8-.8-.9 0-1.3.5-1.3 1 0 .6.4.8 1.7 1.2 1.4.6 2.4 1.1 2.4 2.5z"/><path id="path4907" d="M64.4 273.8h-1.2v-3.5h-3.7v3.5h-1.2v-7.9h1.2v3.2h3.7v-3.2h1.2v7.9z"/><path id="path4909" d="M67.7 273.8h-1.2v-7.9h1.2v7.9z"/><path id="path4911" d="M74.9 267.1H71v2.1h2.3v1.2H71v3.5h-1.2V266h5.1v1.1z"/><path id="path4913" d="M81.7 267.1h-2.3v6.8h-1.2v-6.8h-2.3v-1.2h5.8v1.2z"/></g><path id="path4917" d="m735.4 254.4 5.9-5.9 5.9 5.9h-2.9v5.2h-5.9v-5.2h-3zm5.8-4.6-3.9 3.9h1.8v5.1h4.2v-5.1h1.8l-3.9-3.9z"/><g id="g4929"><path id="path4919" d="M731.6 271.5c0 1.4-.9 2.4-2.9 2.4-1.2 0-2.2-.5-2.8-1.3l.8-.8c.5.6 1.3.9 2.1.9 1.1 0 1.6-.4 1.6-1.2 0-.6-.5-.9-1.8-1.3-1.7-.5-2.5-.9-2.5-2.3s1.2-2.2 2.6-2.2c1.1 0 1.9.4 2.6 1.1l-.8.8c-.5-.5-1.1-.8-1.8-.8-.9 0-1.3.5-1.3 1 0 .6.4.8 1.7 1.2 1.5.6 2.5 1.1 2.5 2.5z"/><path id="path4921" d="M739.4 273.8h-1.2v-3.5h-3.7v3.5h-1.2v-7.9h1.2v3.2h3.7v-3.2h1.2v7.9z"/><path id="path4923" d="M742.7 273.8h-1.2v-7.9h1.2v7.9z"/><path id="path4925" d="M749.9 267.1H746v2.1h2.3v1.2H746v3.5h-1.2V266h5.1v1.1z"/><path id="path4927" d="M756.7 267.1h-2.3v6.8h-1.2v-6.8h-2.3v-1.2h5.8v1.2z"/></g><path id="path4931" d="m1188.1 291.5 5.4-5.4 5.4 5.4-1 1-4.5-4.5-4.4 4.5-.9-1zm3.1-5.4v1.4h-3.2v-1.4h3.2zm7.7 0v1.4h-3.2v-1.4h3.2z"/><g id="g4943"><path id="path4933" d="M1181.4 326.4h-5.3v-7.9h5.1v1.2h-3.9v2h2.3v1.2h-2.3v2.5h4.1v1z"/><path id="path4935" d="M1189.1 326.4h-1.1l-3.2-5c-.2-.3-.5-.8-.6-1v5.9h-1.2v-7.9h1.2l3 4.8c.2.3.5.9.7 1.1v-6h1.2v8.1z"/><path id="path4937" d="M1196.5 319.7h-2.3v6.8h-1.2v-6.8h-2.3v-1.2h5.8v1.2z"/><path id="path4939" d="M1203.4 326.4h-5.3v-7.9h5.1v1.2h-3.9v2h2.3v1.2h-2.3v2.5h4.1v1z"/><path id="path4941" d="M1211.1 320.9c0 1.3-.7 2.1-1.7 2.3l1.6 3.2h-1.4l-1.6-3.1h-1.8v3.1h-1.2v-7.9h3.5c1.4 0 2.6.7 2.6 2.4zm-1.2 0c0-.8-.5-1.3-1.3-1.3h-2.3v2.6h2.3c.7 0 1.3-.4 1.3-1.3z"/></g><g id="g4959"><path id="path4945" d="M19.7 325c-.6 1-1.5 1.5-2.7 1.5-2.1 0-3.4-1.7-3.4-4.1s1.3-4.1 3.4-4.1c1.3 0 2.2.5 2.7 1.5l-1.1.7c-.4-.6-.8-1-1.6-1-1.4 0-2.1 1.1-2.1 2.9 0 1.8.7 2.9 2.1 2.9.8 0 1.3-.3 1.7-1l1 .7z"/><path id="path4947" d="M27.5 322.5c0 2.5-1.4 4.1-3.4 4.1s-3.4-1.6-3.4-4.1 1.4-4.1 3.4-4.1 3.4 1.6 3.4 4.1zm-1.2 0c0-1.8-.9-2.9-2.2-2.9-1.3 0-2.1 1.1-2.1 2.9s.9 2.9 2.2 2.9c1.2 0 2.1-1.1 2.1-2.9z"/><path id="path4949" d="M35.2 326.4h-1.1l-3.2-5c-.2-.3-.5-.8-.6-1v5.9h-1.2v-7.9h1.2l3 4.8c.2.3.5.9.7 1.1v-6h1.2v8.1z"/><path id="path4951" d="M42.6 319.7h-2.3v6.8h-1.2v-6.8h-2.3v-1.2h5.8v1.2z"/><path id="path4953" d="M50.2 320.9c0 1.3-.7 2.1-1.7 2.3l1.6 3.2h-1.4l-1.6-3.1h-1.8v3.1h-1.2v-7.9h3.5c1.4 0 2.6.7 2.6 2.4zm-1.2 0c0-.8-.5-1.3-1.3-1.3h-2.3v2.6h2.3c.7 0 1.3-.4 1.3-1.3z"/><path id="path4955" d="M58.2 322.5c0 2.5-1.4 4.1-3.4 4.1s-3.4-1.6-3.4-4.1 1.4-4.1 3.4-4.1 3.4 1.6 3.4 4.1zm-1.2 0c0-1.8-.9-2.9-2.2-2.9-1.3 0-2.1 1.1-2.1 2.9s.9 2.9 2.2 2.9c1.2 0 2.1-1.1 2.1-2.9z"/><path id="path4957" d="M65 326.4h-5.1v-7.9h1.2v6.8h4v1.1z"/></g><path id="path4961" d="M111 302.8v8.8h-8.7v-8.8h8.7zm-4.8 4v-3.2H103v3.2h3.2zm0 .8H103v3.2h3.2v-3.2zm.8-.8h3.3v-3.3H107v3.3zm0 .8v3.2h3.3v-3.2H107z"/><g id="g4969"><path id="path4963" d="m105.3 318.5-1.6 7.9h-1.2l-1.2-5.1c-.1-.3-.2-.9-.2-1.1 0 .2-.2.8-.2 1.1l-1.3 5.1h-1.2l-1.6-7.9H98l1 5c0 .2.1.8.2 1 0-.3.2-.8.2-1l1.3-5h1l1.3 5.1c.1.2.1.6.2.9.1-.3.1-.7.2-.9l1-5.1h.9z"/><path id="path4965" d="M108.2 326.4H107v-7.9h1.2v7.9z"/><path id="path4967" d="M116.3 326.4h-1.1l-3.2-5c-.2-.3-.5-.8-.6-1v5.9h-1.2v-7.9h1.2l3 4.8c.2.3.5.9.7 1.1v-6h1.2v8.1z"/></g><path id="path4971" d="M180.1 302v1H177l-4.6 9.2h-4v-1h3.2l4.6-9.2h3.9zm-4.7 10.3v-1h4.8v1h-4.8z"/><g id="g4979"><path id="path4973" d="M171.6 326.4h-1.3l-.7-1.9h-3.2l-.7 1.9h-1.2l2.9-7.9h1.3l2.9 7.9zm-2.3-2.9-.6-1.8-.6-1.8-.6 1.8-.6 1.8h2.4z"/><path id="path4975" d="M178.4 326.4h-5.1v-7.9h1.2v6.8h4v1.1z"/><path id="path4977" d="M183.9 319.7h-2.3v6.8h-1.2v-6.8H178v-1.2h5.8v1.2z"/></g><path id="path4981" d="M374.8 309.2v-2h.7v1.4h2.6v-1.4h.7v2h-4z"/><g id="g4993"><path id="path4983" d="M365.1 324.2c0 1.4-.9 2.4-2.9 2.4-1.2 0-2.2-.5-2.8-1.3l.9-.8c.5.6 1.3.9 2.1.9 1.1 0 1.6-.4 1.6-1.2 0-.6-.5-.9-1.8-1.3-1.7-.5-2.5-.9-2.5-2.3s1.2-2.2 2.6-2.2c1.1 0 1.9.4 2.6 1.1l-.8.8c-.5-.5-1.1-.8-1.8-.8-.9 0-1.3.5-1.3 1 0 .6.4.8 1.7 1.2 1.5.5 2.4 1 2.4 2.5z"/><path id="path4985" d="M372.8 321c0 1.6-1.1 2.5-2.6 2.5h-2.1v3h-1.2v-7.9h3.3c1.5-.1 2.6.7 2.6 2.4zm-1.2 0c0-.9-.5-1.4-1.4-1.4h-2.1v2.7h2.1c.9.1 1.4-.5 1.4-1.3z"/><path id="path4987" d="M380 326.4h-1.3l-.7-1.9h-3.2l-.7 1.9H373l2.9-7.9h1.3l2.8 7.9zm-2.3-2.9-.6-1.8-.6-1.8-.6 1.8-.6 1.8h2.4z"/><path id="path4989" d="M387.1 325c-.6 1-1.5 1.5-2.7 1.5-2.1 0-3.4-1.7-3.4-4.1s1.3-4.1 3.4-4.1c1.3 0 2.2.5 2.7 1.5l-1.1.7c-.4-.6-.8-1-1.6-1-1.4 0-2.1 1.1-2.1 2.9 0 1.8.7 2.9 2.1 2.9.8 0 1.3-.3 1.7-1l1 .7z"/><path id="path4991" d="M394.1 326.4h-5.3v-7.9h5.1v1.2H390v2h2.3v1.2H390v2.5h4.1v1z"/></g><path id="path4995" d="M573.4 311.2h3.2l4.6-9.2h4v1H582l-4.6 9.2h-4v-1zm7 0h4.8v1h-4.8v-1z"/><g id="g5003"><path id="path4997" d="M576.7 326.4h-1.3l-.7-1.9h-3.2l-.7 1.9h-1.2l2.9-7.9h1.3l2.9 7.9zm-2.3-2.9-.6-1.8-.6-1.8-.6 1.8-.6 1.8h2.4z"/><path id="path4999" d="M583.4 326.4h-5.1v-7.9h1.2v6.8h4v1.1z"/><path id="path5001" d="M588.9 319.7h-2.3v6.8h-1.2v-6.8H583v-1.2h5.8v1.2z"/></g><path id="path5005" d="M651.1 302.8v8.8h-8.7v-8.8h8.7zm-4.8 4v-3.2h-3.2v3.2h3.2zm0 .8h-3.2v3.2h3.2v-3.2zm.8-.8h3.3v-3.3h-3.3v3.3zm0 .8v3.2h3.3v-3.2h-3.3z"/><g id="g5013"><path id="path5007" d="m645.3 318.5-1.6 7.9h-1.2l-1.2-5.1c-.1-.3-.2-.9-.2-1.1 0 .2-.2.8-.2 1.1l-1.3 5.1h-1.2l-1.6-7.9h1.2l1 5c0 .2.1.8.2 1 0-.3.2-.8.2-1l1.3-5h1l1.3 5.1c.1.2.1.6.2.9.1-.3.1-.7.2-.9l1-5.1h.9z"/><path id="path5009" d="M648.2 326.4H647v-7.9h1.2v7.9z"/><path id="path5011" d="M656.3 326.4h-1.1l-3.2-5c-.2-.3-.5-.8-.6-1v5.9h-1.2v-7.9h1.2l3 4.8c.2.3.5.9.7 1.1v-6h1.2v8.1z"/></g><path id="path5015" d="M710.6 303.4h7.3v1.2h-7.3v-1.2zm0 2.5h7.3v1.2h-7.3v-1.2zm0 2.5h7.3v1.2h-7.3v-1.2zm0 2.5h7.3v1.2h-7.3v-1.2z"/><g id="g5025"><path id="path5017" d="M706.3 326.3h-1.2v-5.6c-.1.2-.3.8-.5 1.2l-1.9 4.5-1.9-4.5c-.2-.5-.4-1-.5-1.2v5.6h-1.1v-7.9h1.2l1.8 4.2c.2.5.4 1 .5 1.4.1-.3.3-.9.5-1.4l1.7-4.2h1.3v7.9z"/><path id="path5019" d="M713.6 326.3h-5.3v-7.9h5.1v1.2h-3.9v2h2.3v1.2h-2.3v2.5h4.1v1z"/><path id="path5021" d="M721.3 326.3h-1.1l-3.2-5c-.2-.3-.5-.8-.6-1v5.9h-1.2v-7.9h1.2l3 4.8c.2.3.5.9.7 1.1v-6h1.2v8.1z"/><path id="path5023" d="M729.4 323c0 2.2-1.1 3.4-3 3.4-2 0-3-1.3-3-3.5v-4.6h1.2v4.6c0 1.5.6 2.3 1.8 2.3 1.2 0 1.8-.8 1.8-2.2v-4.6h1.2v4.6z"/></g><path id="path5027" d="M781.2 313.6v-1.4c-1.5-.2-2.7-.9-3.6-2.1l-1.2.7-.5-.9 1.2-.7c-.3-.7-.4-1.4-.4-2.1 0-.7.1-1.4.4-2.1l-1.2-.7.5-.9 1.2.7c.9-1.2 2.1-1.9 3.6-2.1v-1.4h1v1.4c1.5.2 2.7.9 3.6 2.1l1.2-.7.5.9-1.2.7c.3.7.5 1.4.5 2.1 0 .7-.2 1.4-.5 2.1l1.2.7-.5.9-1.2-.7c-.9 1.2-2.1 1.9-3.6 2.1v1.4h-1zm-3.2-8c-.2.5-.3 1-.3 1.6 0 .5.1 1.1.3 1.6l2.8-1.6-2.8-1.6zm3.2-2.5c-1.1.1-2 .7-2.7 1.6l2.8 1.6v-3.2zm-2.7 6.5c.7.9 1.6 1.4 2.7 1.6V308l-2.7 1.6zm6.5-4.9c-.7-.9-1.6-1.4-2.7-1.6v3.2l2.7-1.6zm-2.7 6.5c1.1-.1 2-.7 2.7-1.6l-2.8-1.6v3.2zm3.2-2.5c.2-.5.3-1 .3-1.6 0-.5-.1-1.1-.3-1.6l-2.8 1.6 2.8 1.6z"/><path id="path5029" d="M38.7 313.6v-1.4c-1.5-.2-2.7-.9-3.6-2.1l-1.2.7-.5-.9 1.2-.7c-.3-.7-.4-1.4-.4-2.1 0-.7.1-1.4.4-2.1l-1.2-.7.5-.9 1.2.7c.9-1.2 2.1-1.9 3.6-2.1v-1.4h1v1.4c1.5.2 2.7.9 3.6 2.1l1.2-.7.5.9-1.2.7c.3.7.5 1.4.5 2.1 0 .7-.2 1.4-.5 2.1l1.2.7-.5.9-1.2-.7c-.9 1.2-2.1 1.9-3.6 2.1v1.4h-1zm-3.2-8c-.2.5-.3 1-.3 1.6 0 .5.1 1.1.3 1.6l2.8-1.6-2.8-1.6zm3.2-2.5c-1.1.1-2 .7-2.7 1.6l2.8 1.6v-3.2zm-2.7 6.5c.7.9 1.6 1.4 2.7 1.6V308l-2.7 1.6zm6.5-4.9c-.7-.9-1.6-1.4-2.7-1.6v3.2l2.7-1.6zm-2.7 6.5c1.1-.1 2-.7 2.7-1.6l-2.8-1.6v3.2zm3.2-2.5c.2-.5.3-1 .3-1.6 0-.5-.1-1.1-.3-1.6l-2.8 1.6 2.8 1.6z"/><g id="g5045"><path id="path5031" d="M762.2 325c-.6 1-1.5 1.5-2.7 1.5-2.1 0-3.4-1.7-3.4-4.1s1.3-4.1 3.4-4.1c1.3 0 2.2.5 2.7 1.5l-1.1.7c-.4-.6-.8-1-1.6-1-1.4 0-2.1 1.1-2.1 2.9 0 1.8.7 2.9 2.1 2.9.8 0 1.3-.3 1.7-1l1 .7z"/><path id="path5033" d="M770 322.5c0 2.5-1.4 4.1-3.4 4.1s-3.4-1.6-3.4-4.1 1.4-4.1 3.4-4.1 3.4 1.6 3.4 4.1zm-1.2 0c0-1.8-.9-2.9-2.2-2.9-1.3 0-2.1 1.1-2.1 2.9s.9 2.9 2.2 2.9c1.2 0 2.1-1.1 2.1-2.9z"/><path id="path5035" d="M777.7 326.4h-1.1l-3.2-5c-.2-.3-.5-.8-.6-1v5.9h-1.2v-7.9h1.2l3 4.8c.2.3.5.9.7 1.1v-6h1.2v8.1z"/><path id="path5037" d="M785.1 319.7h-2.3v6.8h-1.2v-6.8h-2.3v-1.2h5.8v1.2z"/><path id="path5039" d="M792.7 320.9c0 1.3-.7 2.1-1.7 2.3l1.6 3.2h-1.4l-1.6-3.1h-1.8v3.1h-1.2v-7.9h3.5c1.4 0 2.6.7 2.6 2.4zm-1.2 0c0-.8-.5-1.3-1.3-1.3h-2.3v2.6h2.3c.7 0 1.3-.4 1.3-1.3z"/><path id="path5041" d="M800.7 322.5c0 2.5-1.4 4.1-3.4 4.1s-3.4-1.6-3.4-4.1 1.4-4.1 3.4-4.1 3.4 1.6 3.4 4.1zm-1.2 0c0-1.8-.9-2.9-2.2-2.9-1.3 0-2.1 1.1-2.1 2.9s.9 2.9 2.2 2.9c1.2 0 2.1-1.1 2.1-2.9z"/><path id="path5043" d="M807.5 326.4h-5.1v-7.9h1.2v6.8h4v1.1z"/></g></g><ellipse id="path5133" cx="1034.097" cy="262.52" rx="33.559" ry="32.483" style="fill:none;stroke:red;stroke-width:5.3111;stroke-linecap:round;stroke-linejoin:round"/><path id="path5285" d="m948.116 249.477 46.388-18.281-17.045-43.252-8.025 18.463-57.995-25.206-10.29 23.673 56.156 24.407z" style="fill:#fe7777;fill-opacity:1;stroke:red;stroke-width:2.7008;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"/></svg> \ No newline at end of file diff --git a/app/vendor/rune/vendor/winit/docs/res/keyboard_right_shift_key.svg b/app/vendor/rune/vendor/winit/docs/res/keyboard_right_shift_key.svg new file mode 100644 index 0000000..dc016f0 --- /dev/null +++ b/app/vendor/rune/vendor/winit/docs/res/keyboard_right_shift_key.svg @@ -0,0 +1 @@ +<svg xmlns="http://www.w3.org/2000/svg" xml:space="preserve" id="svg5048" x="0" y="0" style="enable-background:new 0 0 1226 349" version="1.1" viewBox="0 0 1226 349"><style id="style3852" type="text/css">.st1{fill:#ccc;stroke:#000;stroke-width:2}.st2{fill:#fcfcfc}</style><g id="Layer_1"><path id="path3854" d="M6.5.5h1213c3.3 0 6 2.7 6 6v336c0 3.3-2.7 6-6 6H6.5c-3.3 0-6-2.7-6-6V6.5c0-3.3 2.7-6 6-6z" style="fill:#eee;stroke:#ddd"/></g><g id="Layer_2"><path id="path3857" d="M13.5 9.8h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.3 1.8-4 4-4z" class="st1"/><path id="path3859" d="M121.5 9.8h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.3 1.8-4 4-4z" class="st1"/><path id="path3861" d="M175.5 9.8h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.3 1.8-4 4-4z" class="st1"/><path id="path3863" d="M229.5 9.8h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.3 1.8-4 4-4z" class="st1"/><path id="path3865" d="M283.5 9.8h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.3 1.8-4 4-4z" class="st1"/><path id="path3867" d="M364.5 9.8h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.3 1.8-4 4-4z" class="st1"/><path id="path3869" d="M418.5 9.8h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.3 1.8-4 4-4z" class="st1"/><path id="path3871" d="M472.5 9.8h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.3 1.8-4 4-4z" class="st1"/><path id="path3873" d="M526.5 9.8h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.3 1.8-4 4-4z" class="st1"/><path id="path3875" d="M607.5 9.8h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.3 1.8-4 4-4z" class="st1"/><path id="path3877" d="M661.5 9.8h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.3 1.8-4 4-4z" class="st1"/><path id="path3879" d="M715.5 9.8h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.3 1.8-4 4-4z" class="st1"/><path id="path3881" d="M769.5 9.8h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.3 1.8-4 4-4z" class="st1"/><path id="path3883" d="M837 9.8h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.3 1.8-4 4-4z" class="st1"/><path id="path3885" d="M891 9.8h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.3 1.8-4 4-4z" class="st1"/><path id="path3887" d="M945 9.8h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.3 1.8-4 4-4z" class="st1"/><path id="path3889" d="M13.5 77.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3891" d="M67.5 77.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3893" d="M121.5 77.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3895" d="M175.5 77.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3897" d="M229.5 77.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3899" d="M283.5 77.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3901" d="M337.5 77.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3903" d="M391.5 77.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3905" d="M445.5 77.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3907" d="M499.5 77.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3909" d="M553.5 77.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3911" d="M607.5 77.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3913" d="M661.5 77.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3915" d="M715.5 77.2h92c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-92c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3917" d="M837 77.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3919" d="M891 77.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3921" d="M945 77.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3923" d="M1012.5 77.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3925" d="M1066.5 77.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3927" d="M1120.5 77.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3929" d="M1174.5 77.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3931" d="M13.5 131.2h65c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-65c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3933" d="M94.5 131.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3935" d="M148.5 131.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3937" d="M202.5 131.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3939" d="M256.5 131.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3941" d="M310.5 131.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3943" d="M364.5 131.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3945" d="M418.5 131.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3947" d="M472.5 131.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3949" d="M526.5 131.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3951" d="M580.5 131.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3953" d="M634.5 131.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3955" d="M688.5 131.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3957" d="M742.5 131.2h65c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-65c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3959" d="M837 131.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3961" d="M891 131.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3963" d="M945 131.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3965" d="M1012.5 131.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3967" d="M1066.5 131.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3969" d="M1120.5 131.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3971" d="M1174.5 131.2h38c2.2 0 4 1.8 4 4v92c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-92c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3973" d="M13.5 185.2H92c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4H13.5c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3975" d="M108 185.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3977" d="M162 185.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3979" d="M216 185.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3981" d="M270 185.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3983" d="M324 185.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3985" d="M378 185.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3987" d="M432 185.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3989" d="M486 185.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3991" d="M540 185.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3993" d="M594 185.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3995" d="M648 185.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3997" d="M702 185.2h105.5c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4H702c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3999" d="M1012.5 185.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path4001" d="M1066.5 185.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path4003" d="M1120.5 185.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path4005" d="M13.5 239.2H119c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4H13.5c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path4007" d="M135 239.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path4009" d="M189 239.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path4011" d="M243 239.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path4013" d="M297 239.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path4015" d="M351 239.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path4017" d="M405 239.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path4019" d="M459 239.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path4021" d="M513 239.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path4023" d="M567 239.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path4025" d="M621 239.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path4027" d="M675 239.2h132.5c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4H675c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path4029" d="M891 239.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path4031" d="M1012.5 239.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path4033" d="M1066.5 239.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path4035" d="M1120.5 239.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path4037" d="M1174.5 239.2h38c2.2 0 4 1.8 4 4v92c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-92c0-2.2 1.8-4 4-4z" class="st1"/><path id="path4039" d="M13.5 293.2H65c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4H13.5c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path4041" d="M81 293.2h51.5c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4H81c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path4043" d="M148.5 293.2H200c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-51.5c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path4045" d="M216 293.2h321.5c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4H216c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path4047" d="M553.5 293.2H605c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-51.5c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path4049" d="M621 293.2h51.5c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4H621c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path4051" d="M688.5 293.2H740c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-51.5c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path4053" d="M756 293.2h51.5c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4H756c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path4055" d="M837 293.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path4057" d="M891 293.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path4059" d="M945 293.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path4061" d="M1012.5 293.2h92c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-92c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path4063" d="M1120.5 293.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/></g><g id="Layer_3"><path id="path4066" d="M14.5 10.8h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.3 1.8-4 4-4z" class="st2"/><path id="path4068" d="M122.5 10.8h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.3 1.8-4 4-4z" class="st2"/><path id="path4070" d="M176.5 10.8h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.3 1.8-4 4-4z" class="st2"/><path id="path4072" d="M230.5 10.8h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.3 1.8-4 4-4z" class="st2"/><path id="path4074" d="M284.5 10.8h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.3 1.8-4 4-4z" class="st2"/><path id="path4076" d="M365.5 10.8h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.3 1.8-4 4-4z" class="st2"/><path id="path4078" d="M419.5 10.8h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.3 1.8-4 4-4z" class="st2"/><path id="path4080" d="M473.5 10.8h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.3 1.8-4 4-4z" class="st2"/><path id="path4082" d="M527.5 10.8h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.3 1.8-4 4-4z" class="st2"/><path id="path4084" d="M608.5 10.8h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.3 1.8-4 4-4z" class="st2"/><path id="path4086" d="M662.5 10.8h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.3 1.8-4 4-4z" class="st2"/><path id="path4088" d="M716.5 10.8h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.3 1.8-4 4-4z" class="st2"/><path id="path4090" d="M770.5 10.8h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.3 1.8-4 4-4z" class="st2"/><path id="path4092" d="M838 10.8h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.3 1.8-4 4-4z" class="st2"/><path id="path4094" d="M892 10.8h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.3 1.8-4 4-4z" class="st2"/><path id="path4096" d="M946 10.8h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.3 1.8-4 4-4z" class="st2"/><path id="path4098" d="M14.5 78.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4100" d="M68.5 78.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4102" d="M122.5 78.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4104" d="M176.5 78.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4106" d="M230.5 78.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4108" d="M284.5 78.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4110" d="M338.5 78.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4112" d="M392.5 78.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4114" d="M446.5 78.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4116" d="M500.5 78.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4118" d="M554.5 78.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4120" d="M608.5 78.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4122" d="M662.5 78.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4124" d="M716.5 78.2h90c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-90c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4126" d="M838 78.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4128" d="M892 78.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4130" d="M946 78.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4132" d="M1013.5 78.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4134" d="M1067.5 78.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4136" d="M1121.5 78.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4138" d="M1175.5 78.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4140" d="M14.5 132.2h63c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-63c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4142" d="M95.5 132.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4144" d="M149.5 132.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4146" d="M203.5 132.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4148" d="M257.5 132.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4150" d="M311.5 132.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4152" d="M365.5 132.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4154" d="M419.5 132.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4156" d="M473.5 132.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4158" d="M527.5 132.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4160" d="M581.5 132.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4162" d="M635.5 132.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4164" d="M689.5 132.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4166" d="M743.5 132.2h63c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-63c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4168" d="M838 132.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4170" d="M892 132.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4172" d="M946 132.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4174" d="M1013.5 132.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4176" d="M1067.5 132.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4178" d="M1121.5 132.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4180" d="M1175.5 132.2h36c2.2 0 4 1.8 4 4v88c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-88c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4182" d="M14.5 186.2H91c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4H14.5c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4184" d="M109 186.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4186" d="M163 186.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4188" d="M217 186.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4190" d="M271 186.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4192" d="M325 186.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4194" d="M379 186.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4196" d="M433 186.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4198" d="M487 186.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4200" d="M541 186.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4202" d="M595 186.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4204" d="M649 186.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4206" d="M703 186.2h103.5c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4H703c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4208" d="M1013.5 186.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4210" d="M1067.5 186.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4212" d="M1121.5 186.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4214" d="M14.5 240.2H118c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4H14.5c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4216" d="M136 240.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4218" d="M190 240.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4220" d="M244 240.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4222" d="M298 240.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4224" d="M352 240.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4226" d="M406 240.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4228" d="M460 240.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4230" d="M514 240.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4232" d="M568 240.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4234" d="M622 240.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4236" d="M676 240.2h130.5c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4H676c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4238" d="M892 240.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4240" d="M1013.5 240.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4242" d="M1067.5 240.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4244" d="M1121.5 240.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4246" d="M1175.5 240.2h36c2.2 0 4 1.8 4 4v88c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-88c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4248" d="M14.5 294.2H64c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4H14.5c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4250" d="M82 294.2h49.5c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4H82c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4252" d="M149.5 294.2H199c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-49.5c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4254" d="M217 294.2h319.5c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4H217c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4256" d="M554.5 294.2H604c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-49.5c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4258" d="M622 294.2h49.5c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4H622c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4260" d="M689.5 294.2H739c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-49.5c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4262" d="M757 294.2h49.5c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4H757c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4264" d="M838 294.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4266" d="M892 294.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4268" d="M946 294.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4270" d="M1013.5 294.2h90c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-90c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4272" d="M1121.5 294.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/></g><g id="Layer_4"><g id="g4279"><path id="path4275" d="M141.4 29.3h-3.9v2.1h2.3v1.2h-2.3V36h-1.2v-7.9h5.1v1.2z"/><path id="path4277" d="M144.7 36h-1.2v-6.1h-1.4v-.8c.8-.1 1.5-.3 1.6-1h1V36z"/></g><g id="g4285"><path id="path4281" d="M193.8 29.3h-3.9v2.1h2.3v1.2h-2.3V36h-1.2v-7.9h5.1v1.2z"/><path id="path4283" d="M200.4 36h-5.7c.1-2.3 1.5-3.4 3-4.3 1.1-.6 1.3-1 1.3-1.5 0-.6-.4-1-1.5-1-.7 0-1.4.3-1.9.8l-.6-1c.7-.7 1.7-1.1 2.7-1.1 1.6 0 2.7.7 2.7 2.2 0 1.2-.6 1.7-2 2.6-1.5.9-1.9 1.4-2.1 2.2h4.2V36z"/></g><g id="g4291"><path id="path4287" d="M247.9 29.3H244v2.1h2.3v1.2H244V36h-1.2v-7.9h5.1v1.2z"/><path id="path4289" d="M254.5 33.7c0 1.6-1.1 2.5-3 2.5-1.1 0-2.3-.5-2.9-1.3l.9-.8c.5.6 1.2.9 2 .9 1.3 0 1.7-.5 1.7-1.3s-.6-1.2-1.4-1.2h-.7v-1.2h.7c.7 0 1.1-.5 1.1-1.1 0-.5-.3-1.1-1.5-1.1-.6 0-1.1.3-1.6.7l-.8-.8c.7-.7 1.5-1.1 2.5-1.1 1.5 0 2.7.8 2.7 2.2 0 1-.4 1.4-1 1.7.7.3 1.3.9 1.3 1.9z"/></g><g id="g4297"><path id="path4293" d="M301.6 29.3h-3.9v2.1h2.3v1.2h-2.3V36h-1.2v-7.9h5.1v1.2z"/><path id="path4295" d="M309 34.2h-1.1V36h-1.2v-1.7h-4.3v-1.1l4.1-5.1h1.4v5.1h1.1v1zm-2.2-4.8c-.1.2-.5.6-.7.9l-1.5 1.9c-.2.3-.6.7-.7.9h3v-2.3c-.1-.4-.1-1.1-.1-1.4z"/></g><g id="g4303"><path id="path4299" d="M382.7 29.3h-3.9v2.1h2.3v1.2h-2.3V36h-1.2v-7.9h5.1v1.2z"/><path id="path4301" d="M389.7 33.3c0 1.9-1.3 2.8-3.1 2.8-1 0-1.9-.2-2.8-.8l.6-1c.7.4 1.5.6 2.2.6 1.2 0 1.9-.6 1.9-1.6 0-.9-.6-1.4-1.6-1.4-.7 0-1.1.2-1.5.5l-1.3-.5.3-3.9h4.9v1.1h-3.8l-.2 2c.4-.2 1-.4 1.7-.4 1.8.1 2.7 1.2 2.7 2.6z"/></g><g id="g4309"><path id="path4305" d="M436.7 29.3h-3.9v2.1h2.3v1.2h-2.3V36h-1.2v-7.9h5.1v1.2z"/><path id="path4307" d="M443.9 33.5c0 1.7-1.4 2.6-3.1 2.6-1.7 0-3-.9-3-3.2 0-2.1 1.2-4.9 4.9-5V29c-1.8.1-3.1.9-3.6 2.6.6-.4 1.1-.6 2.1-.6 1.5 0 2.7.8 2.7 2.5zm-1.2 0c0-1-.7-1.4-1.8-1.4-1.2 0-1.9.5-1.9 1.4 0 .8.6 1.5 1.8 1.5 1.2 0 1.9-.6 1.9-1.5z"/></g><g id="g4315"><path id="path4311" d="M491 29.3h-3.9v2.1h2.3v1.2h-2.3V36h-1.2v-7.9h5.1v1.2z"/><path id="path4313" d="M497.2 29.3c-1.3 1.5-2.6 3.8-2.6 6.7h-1.2c0-2.7 1-4.9 2.5-6.8h-4.2V28h5.5v1.3z"/></g><g id="g4321"><path id="path4317" d="M544.5 29.3h-3.9v2.1h2.3v1.2h-2.3V36h-1.2v-7.9h5.1v1.2z"/><path id="path4319" d="M551.9 33.7c0 1.6-1.2 2.4-3.1 2.4s-3.1-.9-3.1-2.4c0-1 .5-1.6 1.4-2-.8-.3-1.1-1.1-1.1-1.5 0-1.5 1.2-2.2 2.8-2.2 1.4 0 2.8.7 2.8 2.2 0 .5-.2 1.2-1.1 1.6.9.3 1.4.9 1.4 1.9zm-1.2 0c0-.8-.6-1.4-1.9-1.4-1.3 0-1.9.5-1.9 1.3s.7 1.4 1.9 1.4c1.3.1 1.9-.5 1.9-1.3zm-.3-3.5c0-.6-.4-1.2-1.6-1.2s-1.6.5-1.6 1.1c0 .6.6 1.1 1.6 1.1 1 .1 1.6-.4 1.6-1z"/></g><g id="g4327"><path id="path4323" d="M625.7 29.3h-3.9v2.1h2.3v1.2h-2.3V36h-1.2v-7.9h5.1v1.2z"/><path id="path4325" d="M632.8 31.1c0 2.1-1.2 4.9-4.9 5V35c1.8-.1 3.1-.9 3.6-2.6-.6.4-1.1.6-2.1.6-1.4 0-2.7-.8-2.7-2.5s1.4-2.6 3.1-2.6c1.7.1 3 1 3 3.2zm-1.2-.5c0-.8-.6-1.5-1.8-1.5-1.2 0-1.9.6-1.9 1.5 0 1 .7 1.4 1.8 1.4 1.2 0 1.9-.5 1.9-1.4z"/></g><g id="g4335"><path id="path4329" d="M677.7 29.3h-3.9v2.1h2.3v1.2h-2.3V36h-1.2v-7.9h5.1v1.2z"/><path id="path4331" d="M680.9 36h-1.2v-6.1h-1.4v-.8c.8-.1 1.5-.3 1.6-1h1V36z"/><path id="path4333" d="M688.9 32c0 2.4-1.1 4.1-3.1 4.1s-3.1-1.7-3.1-4.1c0-2.4 1.1-4.1 3.1-4.1 2 .1 3.1 1.7 3.1 4.1zm-1.2.1c0-1.7-.5-2.9-1.9-2.9s-1.9 1.3-1.9 2.9.6 2.9 1.9 2.9c1.3 0 1.9-1.3 1.9-2.9z"/></g><g id="g4343"><path id="path4337" d="M733.5 29.3h-3.9v2.1h2.3v1.2h-2.3V36h-1.2v-7.9h5.1v1.2z"/><path id="path4339" d="M736.7 36h-1.2v-6.1h-1.4v-.8c.8-.1 1.5-.3 1.6-1h1V36z"/><path id="path4341" d="M740.6 36h-1.2v-6.1H738v-.8c.8-.1 1.5-.3 1.6-1h1V36z"/></g><g id="g4351"><path id="path4345" d="M785.8 29.3h-3.9v2.1h2.3v1.2h-2.3V36h-1.2v-7.9h5.1v1.2z"/><path id="path4347" d="M789.1 36h-1.2v-6.1h-1.4v-.8c.8-.1 1.5-.3 1.6-1h1V36z"/><path id="path4349" d="M796.4 36h-5.7c.1-2.3 1.5-3.4 3-4.3 1.1-.6 1.3-1 1.3-1.5 0-.6-.4-1-1.5-1-.7 0-1.4.3-1.9.8l-.8-.9c.7-.7 1.7-1.1 2.7-1.1 1.6 0 2.7.7 2.7 2.2 0 1.2-.6 1.7-2 2.6-1.5.9-2 1.4-2.1 2.2h4.2v1z"/></g><g id="g4357"><path id="path4353" d="M35.9 89.7c-.5 1.3-1.1 2-2.2 2-.6 0-.9-.2-1.4-.5-.6-.4-.9-.6-1.2-.6-.5 0-.7.3-1 1.1l-1-.5c.5-1.3 1.1-2 2.2-2 .6 0 .9.2 1.4.5.5.4.9.6 1.2.6.5 0 .7-.3 1.1-1.1l.9.5z"/><path id="path4355" d="M33.9 104.2h-1.2l-2.3-2.3h2l1.5 2.3z"/></g><g id="g4363"><path id="path4359" d="M87.6 94.8c0 .6-.5 1.1-1.1 1.1-.6 0-1.1-.5-1.1-1.1s.5-1.1 1.1-1.1c.6 0 1.1.5 1.1 1.1zm-.3-4.6-.3 2.6h-1l-.3-2.7v-4.4h1.5v4.5z"/><path id="path4361" d="M87.6 112.7h-1.5v-7.6h-1.8v-1c1-.1 1.9-.4 2-1.3h1.2v9.9z"/></g><g id="g4369"><path id="path4365" d="M145.6 89.1c0 2.1-.9 2.9-2.2 2.9-.7 0-1.3-.4-1.5-.9-.3.5-1.1.9-1.8.9-1.1 0-2.2-.6-2.2-1.9 0-1.2 1.1-1.8 2.3-1.8.6 0 1.1.2 1.4.4V88c0-.6-.5-.8-1.3-.8-.5 0-1 .1-1.4.3l-.4-.7c.5-.3 1.2-.5 1.8-.5 1.3 0 2.2.6 2.2 1.7v2.4c0 .5.3.9.9.9.9 0 1.2-.7 1.2-2.1 0-2.3-1.8-4.2-4.3-4.2s-4.3 1.8-4.3 4.3 1.8 4.3 4.3 4.3c.6 0 1.2-.1 1.8-.4l.3.8c-.8.4-1.4.5-2.2.5-3 0-5.1-2.2-5.1-5.1 0-3 2.2-5.1 5.1-5.1 3.3-.1 5.4 2.2 5.4 4.8zm-3.9 1.3v-.9c-.3-.2-.8-.4-1.5-.4-.8 0-1.3.3-1.3 1s.5 1.1 1.4 1.1c.5 0 1.1-.3 1.4-.8z"/><path id="path4367" d="M143.8 111.3h-7.1c.1-2.9 1.9-4.2 3.8-5.4 1.3-.8 1.7-1.2 1.7-1.9 0-.8-.5-1.3-1.9-1.3-.8 0-1.8.4-2.4 1l-.9-1.1c.9-.8 2.2-1.3 3.4-1.3 2.1 0 3.4.9 3.4 2.7 0 1.5-.8 2.2-2.5 3.2-1.9 1.1-2.4 1.8-2.7 2.7h5.3v1.4z"/></g><g id="g4375"><path id="path4371" d="M198.8 93.4h-1.7v2.3h-1.4v-2.3h-2.3v2.3H192v-2.3h-1.7v-1.3h1.7v-2.7h-1.7V88h1.7v-2.3h1.4V88h2.3v-2.3h1.4V88h1.7v1.3h-1.7V92h1.7v1.4zm-3.1-1.3v-2.7h-2.3v2.7h2.3z"/><path id="path4373" d="M197.8 109.7c0 2-1.4 3.1-3.7 3.1-1.4 0-2.9-.6-3.6-1.6l1.1-1c.6.8 1.5 1.1 2.4 1.1 1.6 0 2.2-.6 2.2-1.6s-.8-1.5-1.8-1.5h-.9v-1.4h.9c.9 0 1.4-.6 1.4-1.4 0-.6-.4-1.4-1.9-1.4-.8 0-1.4.3-2 .9l-1.1-1c.8-.9 1.8-1.3 3.1-1.3 1.9 0 3.4 1 3.4 2.7 0 1.2-.5 1.8-1.2 2.2 1.1.2 1.7 1 1.7 2.2z"/></g><g id="g4381"><path id="path4377" d="M252 92.7c0 1.6-.9 2.7-2.8 2.9V97h-1.5v-1.4c-1.2-.2-2.3-.7-2.9-1.6l1.1-1c.7.8 1.6 1.1 2.5 1.1 1.4 0 2-.5 2-1.3s-.6-1.1-2.2-1.6c-2.1-.6-3.1-1.1-3.1-2.9 0-1.5 1.1-2.4 2.5-2.6v-1.5h1.5v1.5c1 .2 1.8.6 2.5 1.3l-1 1c-.7-.6-1.3-1-2.3-1-1.1 0-1.6.5-1.6 1.1 0 .7.4 1 2.1 1.5 2 .8 3.2 1.3 3.2 3.1z"/><path id="path4379" d="M252.5 110.5h-1.3v2.2h-1.4v-2.2h-5.4v-1.4l5.1-6.3h1.7v6.4h1.3v1.3zm-2.7-6.1c-.2.3-.6.8-.9 1.2L247 108c-.3.4-.7.9-.9 1.1h3.7v-2.9c-.1-.5 0-1.4 0-1.8z"/></g><g id="g4387"><path id="path4383" d="M301.2 88.7c0 1.8-1 3.1-2.5 3.1s-2.4-1.3-2.4-3.1 1-3.1 2.5-3.1c1.4 0 2.4 1.3 2.4 3.1zm-1.3 0c0-1.1-.4-1.9-1.2-1.9s-1.2.7-1.2 1.8.4 1.9 1.2 1.9 1.2-.8 1.2-1.8zm6.4-3-6.1 9.9h-1.4l6.1-9.9h1.4zm2.4 7c0 1.8-1 3.1-2.5 3.1-1.4 0-2.4-1.3-2.4-3.1s1-3.1 2.5-3.1c1.5.1 2.4 1.3 2.4 3.1zm-1.2.1c0-1.1-.4-1.9-1.2-1.9-.8 0-1.2.7-1.2 1.8s.4 1.9 1.2 1.9c.7 0 1.2-.8 1.2-1.8z"/><path id="path4385" d="M306.1 109.3c0 2.4-1.6 3.5-3.9 3.5-1.3 0-2.4-.3-3.5-1l.7-1.2c.8.5 1.9.8 2.8.8 1.5 0 2.4-.8 2.4-2s-.8-1.8-2-1.8c-.8 0-1.4.2-1.9.6l-1.6-.6.3-4.8h6.1v1.4h-4.8l-.2 2.5c.6-.3 1.2-.5 2.1-.5 2.4 0 3.5 1.3 3.5 3.1z"/></g><g id="g4393"><path id="path4389" d="M359.9 90.3h-1.6l-1.8-3-1.8 3h-1.6l2.9-4.5h1.1l2.8 4.5z"/><path id="path4391" d="M360.4 109.5c0 2.2-1.7 3.3-3.9 3.3-2.1 0-3.7-1.1-3.7-4 0-2.6 1.4-6.1 6.2-6.3v1.4c-2.3.1-3.8 1.1-4.5 3.2.7-.6 1.4-.8 2.6-.8 1.8.1 3.3 1.1 3.3 3.2zm-1.5.1c0-1.2-.8-1.7-2.3-1.7-1.4 0-2.3.6-2.3 1.7 0 1 .8 1.8 2.3 1.8 1.5 0 2.3-.7 2.3-1.8z"/></g><g id="g4399"><path id="path4395" d="M414.9 95.7h-1.7l-.8-.9c-.7.7-1.7 1.1-2.8 1.1-2.1 0-3.1-1.1-3.1-2.7 0-1.3.7-2.2 2.1-2.9l-.2-.2c-.7-.8-.9-1.4-.9-2.1 0-1.4 1.1-2.3 2.8-2.3.9 0 1.8.3 2.7.9l-.7 1.2c-.8-.6-1.3-.8-2.1-.8s-1.1.3-1.1.9c0 .4.1.7.5 1.2l2.9 3.6c.3-.5.5-1.1.7-1.6l1.3.4c-.2.8-.6 1.7-1.1 2.4l1.5 1.8zm-3.4-2-2.1-2.5c-.9.5-1.4 1-1.4 1.9 0 .8.5 1.4 1.7 1.4.7 0 1.3-.3 1.8-.8z"/><path id="path4397" d="M413.6 104.3c-1.7 1.9-3.2 4.7-3.3 8.4h-1.5c.1-3.4 1.2-6.1 3.1-8.5h-5.2v-1.4h6.9v1.5z"/></g><g id="g4405"><path id="path4401" d="m467.3 89.5-.6 1.1-1.8-1.3.2 2.2h-1.2l.2-2.2-1.8 1.3-.6-1.1 2-.9-2-.9.6-1.1 1.8 1.3-.2-2.2h1.2l-.2 2.1 1.7-1.3.6 1.1-2 .9 2.1 1z"/><path id="path4403" d="M468.4 109.8c0 2-1.5 3-3.9 3s-3.9-1.1-3.9-3c0-1.2.6-2 1.8-2.5-1-.4-1.3-1.3-1.3-1.9 0-1.9 1.5-2.8 3.5-2.8 1.8 0 3.5.9 3.5 2.8 0 .6-.3 1.5-1.3 1.9.9.4 1.6 1.2 1.6 2.5zm-1.5 0c0-1-.8-1.7-2.4-1.7-1.6 0-2.4.6-2.4 1.6s.9 1.7 2.4 1.7c1.6.1 2.4-.6 2.4-1.6zm-.4-4.4c0-.8-.5-1.5-2-1.5-1.4 0-2 .7-2 1.4 0 .8.8 1.4 2 1.4 1.3 0 2-.6 2-1.3z"/></g><g id="g4411"><path id="path4407" d="m520.3 96.6-.7.6c-1.4-1.3-2.8-3.2-2.8-5.8 0-2.7 1.3-4.5 2.8-5.9l.7.6c-1.3 1.4-2 3-2 5.2.1 2.4.8 3.9 2 5.3z"/><path id="path4409" d="M522.2 106.6c0 2.6-1.4 6.1-6.2 6.3v-1.4c2.3-.1 3.8-1.1 4.5-3.2-.7.6-1.4.8-2.6.8-1.8 0-3.3-1-3.3-3.1 0-2.2 1.7-3.3 3.9-3.3 2.1-.1 3.7 1 3.7 3.9zm-1.5-.7c0-1-.8-1.8-2.3-1.8-1.5 0-2.3.7-2.3 1.8 0 1.2.8 1.7 2.3 1.7 1.4 0 2.3-.6 2.3-1.7z"/></g><g id="g4417"><path id="path4413" d="M574.2 91.3c0 2.7-1.3 4.5-2.8 5.9l-.7-.6c1.3-1.4 2-3 2-5.2 0-2.3-.8-3.9-2-5.2l.7-.6c1.4 1.3 2.8 3.2 2.8 5.7z"/><path id="path4415" d="M576.4 107.7c0 3-1.4 5.1-3.9 5.1-2.6 0-3.9-2.1-3.9-5.1s1.4-5.1 3.9-5.1c2.6 0 3.9 2.1 3.9 5.1zm-1.5 0c0-2.1-.7-3.7-2.4-3.7s-2.4 1.6-2.4 3.7.7 3.7 2.4 3.7c1.8 0 2.4-1.6 2.4-3.7z"/></g><g id="g4423"><path id="path4419" d="M630 98.2h-7v-1.3h7.1v1.3z"/><path id="path4421" d="M628.3 108.2h-3.5v-1.4h3.5v1.4z"/></g><g id="g4429"><path id="path4425" d="M683.9 91.5h-2.7v2.8h-1.5v-2.8H677v-1.4h2.7v-2.8h1.5v2.8h2.7v1.4z"/><path id="path4427" d="M683.6 106.9h-6.1v-1.4h6.1v1.4zm0 3.2h-6.1v-1.4h6.1v1.4z"/></g><g id="g4433"><path id="path4431" d="m1088.4 93-4.4 12.5h-1.5L1087 93h1.4z"/></g><g id="g4437"><path id="path4435" d="m1136.4 98.2.7-1.2 1.9 1.4-.2-2.4h1.4l-.2 2.4 1.9-1.4.7 1.2-2.2 1 2.2 1-.7 1.2-1.9-1.4.2 2.4h-1.4l.2-2.4-1.9 1.4-.7-1.2 2.2-1-2.2-1z"/></g><g id="g4441"><path id="path4439" d="M1189.9 98.4h7.2v1.6h-7.2v-1.6z"/></g><g id="g4445"><path id="path4443" d="M117.7 153.2c0 1.7-.6 3.2-1.5 4.1l.7 1-1.2.8-.7-1c-.4.2-.9.3-1.5.3-2.6 0-4.2-2.1-4.2-5.1s1.6-5.1 4.2-5.1c2.6-.1 4.2 2 4.2 5zm-1.5 0c0-2.2-.9-3.6-2.7-3.6-1.7 0-2.7 1.4-2.7 3.6s.9 3.7 2.7 3.7c.3 0 .5 0 .7-.1l-.7-1.1 1.2-.8.7 1.1c.5-.6.8-1.6.8-2.8z"/></g><g id="g4449"><path id="path4447" d="m172.9 148.2-2 9.9h-1.5l-1.5-6.4c-.1-.3-.2-1.1-.3-1.3 0 .2-.2 1-.3 1.3l-1.6 6.4h-1.5l-2-9.9h1.5l1.2 6.3c.1.3.2 1 .2 1.3.1-.3.2-1 .3-1.3l1.6-6.3h1.3l1.6 6.4c.1.3.2.8.2 1.1.1-.4.2-.9.2-1.2l1.2-6.4h1.4z"/></g><g id="g4453"><path id="path4451" d="M225 158.2h-6.6v-9.9h6.4v1.4h-4.9v2.5h2.8v1.4h-2.8v3.1h5.1v1.5z"/></g><g id="g4457"><path id="path4455" d="M279.4 151.2c0 1.6-.8 2.6-2.2 2.9l2 4.1h-1.7l-2-3.9h-2.2v3.9h-1.5v-9.9h4.4c1.8-.1 3.2.9 3.2 2.9zm-1.5.1c0-1-.7-1.6-1.7-1.6h-2.9v3.2h2.9c1-.1 1.7-.6 1.7-1.6z"/></g><g id="g4461"><path id="path4459" d="M333.1 149.7h-2.9v8.5h-1.5v-8.5h-2.9v-1.5h7.3v1.5z"/></g><g id="g4465"><path id="path4463" d="m387.8 148.2-3.6 6v3.9h-1.5v-3.9l-3.6-6h1.7l1.5 2.7c.3.6.9 1.6 1 2 .2-.4.7-1.3 1-2l1.6-2.8h1.9z"/></g><g id="g4469"><path id="path4467" d="M441.3 154c0 2.8-1.3 4.3-3.8 4.3s-3.7-1.6-3.7-4.3v-5.8h1.5v5.7c0 1.9.8 2.9 2.3 2.9 1.6 0 2.3-1 2.3-2.8v-5.8h1.5v5.8z"/></g><g id="g4473"><path id="path4471" d="M492.2 158.2h-1.5v-9.9h1.5v9.9z"/></g><g id="g4477"><path id="path4475" d="M549.7 153.2c0 3.1-1.7 5.1-4.3 5.1-2.5 0-4.2-2-4.2-5.1s1.7-5.1 4.2-5.1c2.6 0 4.3 2 4.3 5.1zm-1.5 0c0-2.3-1.2-3.7-2.8-3.7-1.6 0-2.7 1.4-2.7 3.6s1.1 3.7 2.7 3.7c1.7.1 2.8-1.3 2.8-3.6z"/></g><g id="g4481"><path id="path4479" d="M603.5 151.4c0 2-1.4 3.1-3.3 3.1h-2.6v3.7h-1.5v-9.9h4.2c1.8-.1 3.2 1 3.2 3.1zm-1.5 0c0-1.1-.7-1.7-1.7-1.7h-2.7v3.4h2.7c1.1 0 1.7-.7 1.7-1.7z"/></g><g id="g4487"><path id="path4483" d="M655.8 151.2c-2.3 0-3.3-1-3.3-3v-.9c0-1-.2-1.2-.8-1.2h-.3v-1.3h.3c.6 0 .8-.3.8-1.2v-.9c0-2 1-3 3.3-3v1.1c-1.4.1-1.8.7-1.8 1.8v.7c0 1.3-.3 1.9-1.1 2.2.8.3 1.1.9 1.1 2.2v.7c0 1.1.4 1.7 1.8 1.8v1z"/><path id="path4485" d="M655.3 168.2h-3.1v-11.5h3.1v1.2h-1.7v9.1h1.7v1.2z"/></g><g id="g4493"><path id="path4489" d="M709.6 146.1h-.3c-.6 0-.8.3-.8 1.2v.9c0 2-1 3-3.3 3v-1.1c1.4-.1 1.8-.7 1.8-1.8v-.7c0-1.3.3-1.9 1.1-2.2-.8-.3-1.1-.9-1.1-2.2v-.7c0-1.1-.4-1.7-1.8-1.8v-1.1c2.3 0 3.3 1 3.3 3v.9c0 1 .2 1.2.8 1.2h.3v1.4z"/><path id="path4491" d="M708.8 168.2h-3.1V167h1.7v-9h-1.7v-1.2h3.1v11.4z"/></g><g id="g4499"><path id="path4495" d="M775.7 152.3h-1.3v-14h1.3v14z"/><path id="path4497" d="M777.9 168h-1.5l-4.4-12.5h1.5l4.4 12.5z"/></g><g id="g4503"><path id="path4501" d="M1034.6 149.8c-1.7 1.9-3.2 4.7-3.3 8.4h-1.5c.1-3.4 1.2-6.1 3.1-8.5h-5.2v-1.4h6.9v1.5z"/></g><g id="g4507"><path id="path4505" d="M1089.4 155.3c0 2-1.5 3-3.9 3s-3.9-1.1-3.9-3c0-1.2.6-2 1.8-2.5-1-.4-1.3-1.3-1.3-1.9 0-1.9 1.5-2.8 3.5-2.8 1.8 0 3.5.9 3.5 2.8 0 .6-.3 1.5-1.3 1.9.9.4 1.6 1.2 1.6 2.5zm-1.5 0c0-1-.8-1.7-2.4-1.7-1.6 0-2.4.6-2.4 1.6s.9 1.7 2.4 1.7c1.6.1 2.4-.6 2.4-1.6zm-.4-4.4c0-.8-.5-1.5-2-1.5-1.4 0-2 .7-2 1.4 0 .8.8 1.4 2 1.4 1.3 0 2-.6 2-1.3z"/></g><g id="g4511"><path id="path4509" d="M1143.2 152c0 2.6-1.4 6.1-6.2 6.3v-1.4c2.3-.1 3.8-1.1 4.5-3.2-.7.6-1.4.8-2.6.8-1.8 0-3.3-1-3.3-3.1 0-2.2 1.7-3.3 3.9-3.3 2.1 0 3.7 1.1 3.7 3.9zm-1.5-.6c0-1-.8-1.8-2.3-1.8-1.5 0-2.3.7-2.3 1.8 0 1.2.8 1.7 2.3 1.7 1.4 0 2.3-.6 2.3-1.7z"/></g><g id="g4515"><path id="path4513" d="M1197.3 182h-3v3h-1.6v-3h-3v-1.6h3v-3h1.6v3h3v1.6z"/></g><g id="g4519"><path id="path4517" d="M131.4 212.2h-1.6l-.8-2.4h-4l-.8 2.4h-1.5l3.6-9.9h1.6l3.5 9.9zm-2.9-3.7-.8-2.3c-.2-.7-.6-1.9-.8-2.3-.1.4-.5 1.6-.7 2.3l-.8 2.3h3.1z"/></g><g id="g4523"><path id="path4521" d="M184.5 209.3c0 1.8-1.1 3-3.7 3-1.4 0-2.7-.6-3.5-1.6l1.1-1c.7.7 1.6 1.2 2.6 1.2 1.4 0 2.1-.5 2.1-1.4 0-.8-.6-1.1-2.2-1.6-2.1-.6-3.1-1.1-3.1-2.9 0-1.7 1.4-2.8 3.3-2.8 1.3 0 2.4.5 3.2 1.3l-1 1.1c-.6-.6-1.3-.9-2.3-.9-1.2 0-1.7.6-1.7 1.2 0 .7.5 1 2.2 1.5 1.8.5 3 1.2 3 2.9z"/></g><g id="g4527"><path id="path4525" d="M239 207.2c0 3.5-2.2 5-4.8 5h-2.7v-9.9h2.7c2.7-.1 4.8 1.4 4.8 4.9zm-1.5 0c0-2.1-1-3.5-3.3-3.5H233v7h1.2c2.3 0 3.3-1.4 3.3-3.5z"/></g><g id="g4531"><path id="path4529" d="M292.6 203.7h-4.9v2.6h2.8v1.5h-2.8v4.4h-1.5v-9.9h6.4v1.4z"/></g><g id="g4535"><path id="path4533" d="M347 208.3c0 2.6-1.6 4-3.8 4-2.6 0-4.2-2.1-4.2-5.1 0-3 1.6-5.1 4.2-5.1 1.6 0 2.7.7 3.4 1.9l-1.3.8c-.5-.8-1-1.2-2.1-1.2-1.7 0-2.7 1.4-2.7 3.6s.9 3.6 2.7 3.6c1.6 0 2.3-1.1 2.3-2.2h-1.6v-1.4h3.1v1.1z"/></g><g id="g4539"><path id="path4537" d="M400.8 212.2h-1.5v-4.4h-4.6v4.4h-1.5v-9.9h1.5v4h4.6v-4h1.5v9.9z"/></g><g id="g4543"><path id="path4541" d="M454.1 208.3c0 2.7-1.1 4.1-3.5 4.1-1.9 0-3-1-3.5-2.6l1.4-.4c.4 1 1 1.6 2.1 1.6 1.4 0 2-.8 2-2.7v-5.9h1.5v5.9z"/></g><g id="g4547"><path id="path4545" d="M509.3 212.2h-1.7l-2.8-5.1-1.8 2.2v2.9h-1.4v-9.9h1.4v5.2c.2-.3.8-1.1 1.1-1.5l2.9-3.7h1.7l-2.9 3.6 3.5 6.3z"/></g><g id="g4551"><path id="path4549" d="M562.5 212.2h-6.4v-9.9h1.5v8.5h4.9v1.4z"/></g><g id="g4557"><path id="path4553" d="M614.1 197.2c0 .6-.5 1.1-1.1 1.1-.6 0-1.1-.5-1.1-1.1s.5-1.1 1.1-1.1c.6 0 1.1.5 1.1 1.1zm0 5.5c0 .6-.5 1.1-1.1 1.1-.6 0-1.1-.5-1.1-1.1s.5-1.1 1.1-1.1c.6 0 1.1.5 1.1 1.1z"/><path id="path4555" d="M614.1 214.2c0 .6-.5 1.1-1.1 1.1-.6 0-1.1-.5-1.1-1.1s.5-1.1 1.1-1.1c.6 0 1.1.5 1.1 1.1zm-.1 4.5-1.1 3.8h-1l.2-3.8h1.9z"/></g><g id="g4563"><path id="path4559" d="m666.3 193.7-.2 3.6h-1.9l1.1-3.6h1zm3.3 0-.2 3.6h-1.9l1.1-3.6h1z"/><path id="path4561" d="m668 210.8-.2 3.6h-1.9l1.1-3.6h1z"/></g><g id="g4567"><path id="path4565" d="M1035.5 209.9h-1.3v2.2h-1.4V210h-5.4v-1.4l5.1-6.3h1.7v6.4h1.3v1.2zm-2.7-6c-.2.3-.6.8-.9 1.2l-1.9 2.4c-.3.4-.7.9-.9 1.1h3.7v-2.9c-.1-.5 0-1.4 0-1.8z"/></g><g id="g4571"><path id="path4569" d="M1089.1 208.8c0 2.4-1.6 3.5-3.9 3.5-1.3 0-2.4-.3-3.5-1l.7-1.2c.8.5 1.9.8 2.8.8 1.5 0 2.4-.8 2.4-2s-.8-1.8-2-1.8c-.8 0-1.4.2-1.9.6l-1.6-.6.3-4.8h6.1v1.4h-4.8l-.2 2.5c.6-.3 1.2-.5 2.1-.5 2.4 0 3.5 1.3 3.5 3.1z"/></g><g id="g4575"><path id="path4573" d="M1143.4 209c0 2.2-1.7 3.3-3.9 3.3-2.1 0-3.7-1.1-3.7-4 0-2.6 1.4-6.1 6.2-6.3v1.4c-2.3.1-3.8 1.1-4.5 3.2.7-.6 1.4-.8 2.6-.8 1.8.1 3.3 1.1 3.3 3.2zm-1.5.1c0-1.2-.8-1.7-2.3-1.7-1.4 0-2.3.6-2.3 1.7 0 1 .8 1.8 2.3 1.8 1.5 0 2.3-.7 2.3-1.8z"/></g><g id="g4579"><path id="path4577" d="M157.7 266.2h-7.5v-1.4l4.8-5.9c.3-.4.9-1 1.1-1.3h-5.7v-1.4h7.3v1.4l-4.8 5.9c-.3.4-.9 1-1.1 1.3h5.9v1.4z"/></g><g id="g4583"><path id="path4581" d="M212 266.2h-1.8l-1.1-1.9c-.4-.6-.9-1.6-1.1-2-.2.4-.7 1.4-1.1 2l-1.1 1.9h-1.7l3.1-5.1-2.9-4.8h1.8l.9 1.6c.3.6.9 1.7 1.1 2 .2-.4.7-1.4 1.1-2l.9-1.6h1.7L209 261l3 5.2z"/></g><g id="g4587"><path id="path4585" d="M265.8 264.4c-.7 1.2-1.9 1.9-3.4 1.9-2.6 0-4.2-2.1-4.2-5.1 0-3 1.6-5.1 4.2-5.1 1.6 0 2.7.7 3.4 1.9l-1.3.8c-.5-.8-1-1.2-2.1-1.2-1.7 0-2.7 1.4-2.7 3.6s.9 3.6 2.7 3.6c1 0 1.7-.4 2.2-1.2l1.2.8z"/></g><g id="g4591"><path id="path4589" d="m320.2 256.2-3.4 9.9h-1.6l-3.4-9.9h1.6l2.1 6.3.6 1.8c.1-.4.4-1.2.6-1.8l2-6.3h1.5z"/></g><g id="g4595"><path id="path4593" d="M373.8 263.1c0 2-1.2 3-3.4 3h-3.9v-9.9h4.1c1.7 0 2.8.9 2.8 2.6 0 1-.5 1.6-1.3 2 .9.2 1.7 1 1.7 2.3zm-1.8-4.2c0-.7-.4-1.3-1.4-1.3h-2.7v2.6h2.7c1 0 1.4-.6 1.4-1.3zm.4 4.3c0-1-.6-1.6-1.8-1.6h-2.7v3.3h2.7c1.3-.1 1.8-.8 1.8-1.7z"/></g><g id="g4599"><path id="path4597" d="M427.8 266.2h-1.4l-4-6.2c-.2-.4-.6-1-.7-1.2v7.4h-1.4v-9.9h1.5l3.8 6.1c.3.4.7 1.1.8 1.4v-7.4h1.4v9.8z"/></g><g id="g4603"><path id="path4601" d="M482.4 266.2H481v-6.9c-.1.3-.4 1-.6 1.6l-2.4 5.6-2.4-5.6c-.2-.6-.5-1.3-.6-1.6v6.9h-1.4v-9.9h1.5l2.2 5.3c.2.6.6 1.3.7 1.7.1-.4.4-1.1.7-1.7l2.2-5.3h1.6v9.9z"/></g><g id="g4609"><path id="path4605" d="m534 257-4.1-3.6v-1.2l4.1-3.6v1.8l-2.8 2.4 2.8 2.4v1.8z"/><path id="path4607" d="m533 272.7-1.1 3.8h-1l.2-3.8h1.9z"/></g><g id="g4615"><path id="path4611" d="M588.1 253.4 584 257v-1.8l2.8-2.4-2.8-2.4v-1.9l4.1 3.6v1.3z"/><path id="path4613" d="M587.1 273.7c0 .6-.5 1.1-1.1 1.1s-1.1-.5-1.1-1.1.5-1.1 1.1-1.1 1.1.5 1.1 1.1z"/></g><g id="g4621"><path id="path4617" d="M643.3 250.2c0 1.4-.6 2-1.8 2.7-.9.5-1.1.9-1.1 1.9h-1.5c0-1.7.3-2.2 1.9-3.1.7-.4 1-.7 1-1.4 0-.8-.7-1.2-1.9-1.2-1 0-1.8.4-2.5 1.1l-.9-1.1c.8-.8 2-1.5 3.5-1.5 1.9 0 3.3.9 3.3 2.6zm-2.6 6.6c0 .6-.5 1.1-1.1 1.1s-1.1-.5-1.1-1.1.5-1.1 1.1-1.1 1.1.5 1.1 1.1z"/><path id="path4619" d="m642.9 263.5-4.4 12.5H637l4.4-12.5h1.5z"/></g><g id="g4625"><path id="path4623" d="M912.4 259.8c-.1.2-.2.2-.4.2l-1.2-.4v8.6h-1.7v-8.6l-1.1.4c-.2.1-.3 0-.4-.2-.1-.1-.1-.2 0-.4l2.4-3.4 2.4 3.4c.1.2.1.3 0 .4z"/></g><g id="g4629"><path id="path4627" d="M1032.6 266.2h-1.5v-7.6h-1.8v-1c1-.1 1.9-.4 2-1.3h1.2v9.9z"/></g><g id="g4633"><path id="path4631" d="M1088.8 266.2h-7.1c.1-2.9 1.9-4.2 3.8-5.4 1.3-.8 1.7-1.2 1.7-1.9 0-.8-.5-1.3-1.9-1.3-.8 0-1.8.4-2.4 1l-1-1.1c.9-.8 2.2-1.3 3.4-1.3 2.1 0 3.4.9 3.4 2.7 0 1.5-.8 2.2-2.5 3.2-1.9 1.1-2.4 1.8-2.7 2.7h5.3v1.4z"/></g><g id="g4637"><path id="path4635" d="M1142.8 263.2c0 2-1.4 3.1-3.7 3.1-1.4 0-2.9-.6-3.6-1.6l1.1-1c.6.8 1.5 1.1 2.4 1.1 1.6 0 2.2-.6 2.2-1.6s-.8-1.5-1.8-1.5h-.9v-1.4h.9c.9 0 1.4-.6 1.4-1.4 0-.6-.4-1.4-1.9-1.4-.8 0-1.4.3-2 .9l-1.1-1c.8-.9 1.8-1.3 3.1-1.3 1.9 0 3.4 1 3.4 2.7 0 1.2-.5 1.8-1.2 2.2 1.1.2 1.7 1 1.7 2.2z"/></g><g id="g4641"><path id="path4639" d="M861.2 317.2h-7.1l.4 1.1c.1.2 0 .3-.2.4-.1.1-.2.1-.4 0l-3.7-2.4 3.7-2.4c.2-.1.3-.1.4-.1.2.1.2.2.2.4l-.4 1.2h7.1v1.8z"/></g><g id="g4645"><path id="path4643" d="M912.4 318.8c.1.1.1.2-.1.4l-2.4 3.4-2.4-3.4c-.1-.2-.1-.3 0-.4.1-.2.2-.2.4-.2l1.1.4v-8.6h1.7v8.6l1.2-.3c.3-.2.4-.1.5.1z"/></g><g id="g4649"><path id="path4647" d="m969.7 316.4-3.7 2.4c-.2.1-.3.1-.4 0-.2-.1-.2-.2-.2-.4l.4-1.1h-7.1v-1.7h7.1l-.4-1.2c-.1-.2 0-.3.2-.4.1-.1.2-.1.4.1l3.7 2.3z"/></g><g id="g4653"><path id="path4651" d="M1062.4 315.2c0 3-1.4 5.1-3.9 5.1s-3.9-2.1-3.9-5.1 1.4-5.1 3.9-5.1c2.6 0 3.9 2.1 3.9 5.1zm-1.5 0c0-2.1-.7-3.7-2.4-3.7s-2.4 1.6-2.4 3.7.7 3.7 2.4 3.7c1.8 0 2.4-1.6 2.4-3.7z"/></g><g id="g4657"><path id="path4655" d="M1140.6 319.2c0 .6-.5 1.1-1.1 1.1-.6 0-1.1-.5-1.1-1.1s.5-1.1 1.1-1.1c.6 0 1.1.5 1.1 1.1z"/></g><path id="path4659" d="M32.5 19.3c1.5 0 2.8.5 3.8 1.6 1 1 1.6 2.3 1.6 3.8s-.5 2.7-1.6 3.8c-1 1.1-2.3 1.6-3.8 1.6s-2.7-.5-3.8-1.6c-1.1-1.1-1.6-2.3-1.6-3.8h1c0 1.2.4 2.2 1.3 3.1s1.9 1.3 3.1 1.3c1.2 0 2.2-.4 3.1-1.3.9-.9 1.3-1.9 1.3-3.1 0-1.2-.4-2.2-1.3-3.1-.9-.9-1.9-1.3-3.1-1.3v-1zm.4 5-.7.7-3.7-3.7-1.3 1.3v-3.4h3.4l-1.3 1.3 3.6 3.8z"/><g id="g4667"><path id="path4661" d="M28.2 44h-5.3v-8H28v1.2h-3.9v2h2.3v1.2h-2.3v2.5h4.1V44z"/><path id="path4663" d="M35 41.7c0 1.4-.9 2.4-2.9 2.4-1.2 0-2.2-.5-2.8-1.3l.9-.8c.5.6 1.3.9 2.1.9 1.1 0 1.6-.4 1.6-1.2 0-.6-.5-.9-1.8-1.3-1.7-.5-2.5-.9-2.5-2.3s1.2-2.2 2.6-2.2c1.1 0 1.9.4 2.6 1.1l-.8.9c-.5-.5-1.1-.8-1.8-.8-.9 0-1.3.5-1.3 1 0 .6.4.8 1.7 1.2 1.4.5 2.4 1 2.4 2.4z"/><path id="path4665" d="M42.5 42.6c-.6 1-1.5 1.5-2.7 1.5-2.1 0-3.4-1.7-3.4-4.1 0-2.4 1.3-4.1 3.4-4.1 1.3 0 2.2.5 2.7 1.5l-1.1.7c-.4-.6-.8-1-1.6-1-1.4 0-2.1 1.1-2.1 2.9 0 1.8.7 2.9 2.1 2.9.8 0 1.3-.3 1.7-1l1 .7z"/></g><path id="path4669" d="M860.2 20.1c.1.3.1.6.2 1 0 .4.1.9.1 1.4v.7c0 .2 0 .5-.1.7s-.1.4-.1.6-.1.3-.1.4v.1c-.2.1-.5.2-.8.3-.3.1-.6.2-1 .3-.4.1-.7.1-1.1.2-.4 0-.8.1-1.2.1-.4 0-.8 0-1.2-.1s-.8-.1-1.1-.2-.7-.2-1-.3c-.3-.1-.5-.2-.7-.3h-.1v-.1c0-.1-.1-.3-.1-.5s-.1-.4-.1-.6c0-.2-.1-.4-.1-.7v-.7c0-.5 0-1 .1-1.4s.1-.8.2-1v-.1h.1c.3-.2.8-.3 1.3-.5s1.1-.3 1.8-.3l1.1-1.1h1.4v1.2c.5.1 1 .2 1.4.3.4.1.8.3 1 .5l.1.1zm-2 .1c-.1 0-.2 0-.3-.1-.1 0-.2-.1-.3-.1v2.7H854v-2.5l.3-.3c-.4.1-.7.1-1 .2s-.5.2-.7.3l-.1.7c0 .2-.1.4-.1.7v.7c0 .4 0 .8.1 1.2s.1.6.2.9l.6.3c.2.1.5.2.8.2.3.1.6.1 1 .1h2c.3 0 .7-.1.9-.1s.6-.1.8-.2l.6-.3c.1-.2.1-.5.2-.9s.1-.7.1-1.2 0-.8-.1-1.1c0-.4-.1-.6-.2-.9-.2-.1-.4-.1-.6-.2-.2 0-.4-.1-.6-.1zm-3.9.2v2.1h3.1v-4.1h-1v2h-2.1zm.2-.2h1.6v-1.6l-1.6 1.6zm3-.2c.1 0 .1 0 0 0 .1 0 .1 0 0 0z"/><g id="g4693"><path id="path4671" d="M848.6 31.9c0 1.2-.8 1.9-2 1.9H845V36h-.9v-6h2.5c1.2 0 2 .7 2 1.9zm-.9 0c0-.7-.4-1-1-1H845v2h1.6c.7 0 1.1-.4 1.1-1z"/><path id="path4673" d="M854.2 31.8c0 1-.5 1.5-1.3 1.7l1.2 2.4h-1l-1.2-2.4h-1.3V36h-.9v-6h2.6c1.1 0 1.9.6 1.9 1.8zm-.9 0c0-.6-.4-1-1-1h-1.7v1.9h1.7c.6.1 1-.2 1-.9z"/><path id="path4675" d="M856.6 36h-.9v-6h.9v6z"/><path id="path4677" d="M862.7 36h-.8l-2.4-3.7c-.1-.2-.3-.6-.4-.7V36h-.9v-6h.9l2.3 3.6c.2.2.4.7.5.8V30h.9v6z"/><path id="path4679" d="M868.2 30.9h-1.7V36h-.9v-5.1h-1.7V30h4.4v.9z"/><path id="path4681" d="M844.1 44.5c0 1.1-.7 1.8-2.2 1.8-.9 0-1.6-.4-2.1-1l.6-.6c.4.4 1 .7 1.5.7.8 0 1.2-.3 1.2-.9 0-.5-.3-.7-1.3-1-1.3-.4-1.9-.7-1.9-1.8 0-1 .9-1.7 2-1.7.8 0 1.4.3 1.9.8l-.6.6c-.4-.4-.8-.6-1.4-.6-.7 0-1 .3-1 .7 0 .4.3.6 1.3.9 1.3.6 2 1 2 2.1z"/><path id="path4683" d="M849.7 45.1c-.4.7-1.1 1.1-2 1.1-1.5 0-2.5-1.3-2.5-3.1s1-3.1 2.5-3.1c1 0 1.6.4 2 1.1l-.8.5c-.3-.5-.6-.7-1.2-.7-1 0-1.6.8-1.6 2.2s.6 2.2 1.6 2.2c.6 0 1-.3 1.3-.7l.7.5z"/><path id="path4685" d="M855.5 42c0 1-.5 1.5-1.3 1.7l1.2 2.4h-1l-1.2-2.4h-1.3v2.4h-.9v-5.9h2.6c1 0 1.9.6 1.9 1.8zm-.9 0c0-.6-.4-1-1-1h-1.7v2h1.7c.6 0 1-.3 1-1z"/><path id="path4687" d="M860.8 46.2h-4v-5.9h3.8v.9h-2.9v1.5h1.7v.9h-1.7v1.9h3.1v.7z"/><path id="path4689" d="M866.1 46.2h-4v-5.9h3.8v.9H863v1.5h1.7v.9H863v1.9h3.1v.7z"/><path id="path4691" d="M871.9 46.2h-.9l-2.4-3.7c-.1-.2-.3-.6-.4-.7v4.5h-.9v-5.9h.9l2.3 3.6c.2.2.4.7.5.8v-4.5h.9v5.9z"/></g><path id="path4695" d="M912.7 19.8h-.9l-.5-.4v5.3l.5-.4h.9l-2.7 2.2-2.7-2.1h.9l.5.4v-5.3l-.5.4h-.9l2.7-2.1 2.7 2zm-2.1-1-.5-.4-.5.4v6.4l.5.4.5-.4v-6.4z"/><g id="g4717"><path id="path4697" d="M898.4 34.3c0 1.1-.7 1.8-2.2 1.8-.9 0-1.6-.4-2.1-1l.6-.6c.4.4 1 .7 1.5.7.8 0 1.2-.3 1.2-.9 0-.5-.3-.7-1.3-1-1.3-.4-1.9-.7-1.9-1.8 0-1 .9-1.7 2-1.7.8 0 1.4.3 1.9.8l-.6.6c-.4-.4-.8-.6-1.4-.6-.7 0-1 .3-1 .7 0 .4.3.6 1.3.9 1.2.6 2 1 2 2.1z"/><path id="path4699" d="M904 34.9c-.4.7-1.1 1.1-2 1.1-1.5 0-2.5-1.3-2.5-3.1s1-3.1 2.5-3.1c1 0 1.6.4 2 1.1l-.8.5c-.3-.5-.6-.7-1.2-.7-1 0-1.6.8-1.6 2.2s.6 2.2 1.6 2.2c.6 0 1-.3 1.3-.7l.7.5z"/><path id="path4701" d="M909.8 31.8c0 1-.5 1.5-1.3 1.7l1.2 2.4h-1l-1.2-2.4h-1.3V36h-.9v-6h2.6c1 0 1.9.6 1.9 1.8zm-.9 0c0-.6-.4-1-1-1h-1.7v1.9h1.7c.5.1 1-.2 1-.9z"/><path id="path4703" d="M915.8 33c0 1.9-1 3.1-2.5 3.1s-2.5-1.2-2.5-3.1c0-1.9 1-3.1 2.5-3.1s2.5 1.2 2.5 3.1zm-.9 0c0-1.4-.7-2.2-1.6-2.2-.9 0-1.6.8-1.6 2.2 0 1.4.7 2.2 1.6 2.2.9 0 1.6-.8 1.6-2.2z"/><path id="path4705" d="M920.9 36H917v-6h.9v5.1h3v.9z"/><path id="path4707" d="M926 36h-3.9v-6h.9v5.1h3v.9z"/><path id="path4709" d="M903.5 46.2h-3.9v-5.9h.9v5.1h3v.8z"/><path id="path4711" d="M909.2 43.2c0 1.9-1 3.1-2.5 3.1s-2.5-1.2-2.5-3.1c0-1.9 1-3.1 2.5-3.1s2.5 1.2 2.5 3.1zm-.9 0c0-1.4-.7-2.2-1.6-2.2-.9 0-1.6.8-1.6 2.2 0 1.4.7 2.2 1.6 2.2 1 0 1.6-.8 1.6-2.2z"/><path id="path4713" d="M914.8 45.1c-.4.7-1.1 1.1-2 1.1-1.5 0-2.5-1.3-2.5-3.1s1-3.1 2.5-3.1c1 0 1.6.4 2 1.1l-.8.5c-.3-.5-.6-.7-1.2-.7-1 0-1.6.8-1.6 2.2s.6 2.2 1.6 2.2c.6 0 1-.3 1.3-.7l.7.5z"/><path id="path4715" d="M920.8 46.2h-1l-1.7-3.1-1.1 1.3v1.7h-.9v-5.9h.9v3.1c.1-.2.5-.6.7-.9l1.8-2.2h1l-1.7 2.2 2 3.8z"/></g><path id="path4719" d="M961.2 22c0 .3 0 .7-.1 1-.1.3-.2.6-.4.9-.2.3-.4.5-.6.8-.2.2-.5.4-.8.6-.3.2-.6.3-.9.4-.3.1-.7.1-1 .1-.3 0-.7 0-1-.1-.3-.1-.6-.2-.9-.4-.3-.2-.5-.4-.8-.6-.2-.2-.4-.5-.6-.8-.2-.3-.3-.6-.4-.9-.1-.3-.1-.7-.1-1 0-.4 0-.7.1-1 .1-.3.2-.6.4-.9.2-.3.4-.5.6-.8.2-.2.5-.4.8-.6.3-.2.6-.3.9-.4.3-.1.7-.1 1-.1.3 0 .7 0 1 .1.3.1.6.2.9.4s.5.4.8.6c.2.2.4.5.6.8.2.3.3.6.4.9s.1.7.1 1zm-1.6.4-2.2 2.4-2.2-2.4h-.8c0 .4.1.7.3 1.1.2.3.4.6.6.8l.9.6c.3.1.7.2 1.1.2.4 0 .8-.1 1.1-.2.4-.1.7-.3.9-.6s.5-.5.6-.8c.2-.3.3-.7.3-1.1h-.6zm.8-.9c0-.4-.1-.7-.3-1-.2-.3-.4-.6-.7-.8s-.6-.4-.9-.5c-.3-.1-.7-.2-1.1-.2-.4 0-.8.1-1.1.2-.3.1-.6.3-.9.5s-.5.5-.7.8c-.2.3-.3.6-.3 1h1l1.9 2.1 1.9-2.1h1.2z"/><path id="path4721" d="M974 22c0 .3 0 .7-.1 1s-.2.6-.4.9-.4.5-.6.8c-.2.2-.5.4-.8.6-.3.2-.6.3-.9.4-.3.1-.7.1-1 .1s-.7 0-1-.1-.6-.2-.9-.4c-.3-.2-.5-.4-.8-.6-.2-.2-.4-.5-.6-.8s-.3-.6-.4-.9-.1-.7-.1-1 0-.7.1-1 .2-.6.4-.9c.2-.3.4-.5.6-.8.2-.2.5-.4.8-.6.3-.2.6-.3.9-.4.3-.1.7-.1 1-.1s.7 0 1 .1c.3.1.6.2.9.4.3.2.5.4.8.6.2.2.4.5.6.8.2.3.3.6.4.9 0 .3.1.7.1 1zm-.8 0c0-.3 0-.5-.1-.8s-.2-.5-.3-.7-.3-.4-.5-.6-.4-.3-.6-.5c-.2-.1-.5-.2-.7-.3-.3-.1-.5-.1-.8-.1-.4 0-.8.1-1.2.2-.4.2-.7.4-1 .7s-.5.6-.7 1c-.2.4-.2.8-.2 1.2s.1.8.2 1.2c.2.4.4.7.7 1s.6.5 1 .7c.4.2.8.2 1.2.2.4 0 .8-.1 1.2-.2.4-.2.7-.4 1-.7s.5-.6.7-1 .1-.9.1-1.3zm-5.7-1.4h5.4l-2.7 4.5-2.7-4.5zm4.6.5h-3.8l1.9 3.2 1.9-3.2z"/><g id="g4733"><path id="path4723" d="M955.5 32.2c0 1.2-.8 1.9-2 1.9H952v2.2h-.9v-5.9h2.5c1.1-.1 1.9.5 1.9 1.8zm-.9 0c0-.7-.4-1-1-1H952v2h1.6c.7 0 1-.4 1-1z"/><path id="path4725" d="M960.9 36.2h-1l-.5-1.4H957l-.5 1.4h-.9l2.1-5.9h.9l2.3 5.9zm-1.7-2.2-.5-1.4c-.1-.4-.4-1.1-.5-1.4-.1.3-.3.9-.4 1.4l-.5 1.4h1.9z"/><path id="path4727" d="M966.4 33.8c0 1.7-.8 2.6-2.3 2.6-1.5 0-2.2-1-2.2-2.6v-3.5h.9v3.4c0 1.1.5 1.7 1.4 1.7.9 0 1.4-.6 1.4-1.7v-3.5h.9v3.6z"/><path id="path4729" d="M971.9 34.5c0 1.1-.7 1.8-2.2 1.8-.9 0-1.6-.4-2.1-1l.6-.6c.4.4 1 .7 1.5.7.8 0 1.2-.3 1.2-.9 0-.5-.3-.7-1.3-1-1.3-.4-1.9-.7-1.9-1.8 0-1 .9-1.7 2-1.7.8 0 1.4.3 1.9.8l-.6.6c-.4-.4-.8-.6-1.4-.6-.7 0-1 .3-1 .7 0 .4.3.6 1.3.9 1.2.7 2 1.1 2 2.1z"/><path id="path4731" d="M977.2 36.2h-4v-5.9h3.8v.9h-2.9v1.5h1.7v.9h-1.7v1.9h3.1v.7z"/></g><g id="g4745"><path id="path4735" d="M954.8 44.6c0 1.2-.7 1.8-2 1.8h-2.4v-5.9h2.4c1 0 1.7.5 1.7 1.5 0 .6-.3 1-.8 1.2.6.2 1.1.6 1.1 1.4zm-1.1-2.5c0-.4-.2-.8-.8-.8h-1.6v1.5h1.6c.5.1.8-.3.8-.7zm.2 2.6c0-.6-.4-1-1.1-1h-1.6v2h1.6c.8-.1 1.1-.5 1.1-1z"/><path id="path4737" d="M960.7 42.3c0 1-.5 1.5-1.3 1.7l1.2 2.4h-1l-1.2-2.4H957v2.4h-.9v-5.9h2.6c1.1 0 2 .6 2 1.8zm-.9 0c0-.6-.4-1-1-1H957v1.9h1.7c.6.1 1.1-.2 1.1-.9z"/><path id="path4739" d="M966 46.5h-4v-5.9h3.8v.9h-2.9V43h1.7v.9h-1.7v1.9h3.1v.7z"/><path id="path4741" d="M972.1 46.5h-1l-.5-1.4h-2.4l-.5 1.4h-.9l2.1-5.9h.9l2.3 5.9zm-1.7-2.3-.5-1.4c-.1-.4-.4-1.1-.5-1.4-.1.3-.3.9-.4 1.4l-.5 1.4h1.9z"/><path id="path4743" d="M978 46.5h-1l-1.7-3.1-1.1 1.3v1.7h-.9v-5.9h.9v3.1c.1-.2.5-.6.7-.9l1.8-2.2h1l-1.7 2.2 2 3.8z"/></g><path id="path4747" d="m759.2 97.2-5.1-5.1 5.1-5.1h9.5v10.2h-9.5zm-3.7-5.1 4.1 4.1h8.1V88h-8.1l-4.1 4.1zm7.2.7-2.3 2.3-.7-.7 2.3-2.3-2.3-2.3.7-.7 2.3 2.3 2.3-2.3.7.7-2.3 2.3 2.3 2.3-.7.7-2.3-2.3z"/><g id="g4767"><path id="path4749" d="M735.4 109c0 1.6-1 2.4-2.7 2.4h-3.2v-7.9h3.3c1.4 0 2.3.7 2.3 2.1 0 .8-.4 1.3-1 1.6.6.1 1.3.7 1.3 1.8zm-1.5-3.4c0-.6-.3-1-1.1-1h-2.1v2.1h2.1c.8-.1 1.1-.6 1.1-1.1zm.3 3.4c0-.8-.5-1.3-1.4-1.3h-2.2v2.6h2.1c1.2 0 1.5-.5 1.5-1.3z"/><path id="path4751" d="M743.5 111.4h-1.3l-.7-1.9h-3.2l-.7 1.9h-1.2l2.9-7.9h1.3l2.9 7.9zm-2.3-3-.6-1.8-.6-1.8-.6 1.8-.6 1.8h2.4z"/><path id="path4753" d="M750.5 110c-.6 1-1.5 1.5-2.7 1.5-2.1 0-3.4-1.7-3.4-4.1 0-2.4 1.3-4.1 3.4-4.1 1.3 0 2.2.5 2.7 1.5l-1.1.7c-.4-.6-.8-1-1.6-1-1.4 0-2.1 1.1-2.1 2.9 0 1.8.7 2.9 2.1 2.9.8 0 1.3-.3 1.7-1l1 .7z"/><path id="path4755" d="M758.5 111.4h-1.3l-2.3-4.1-1.5 1.8v2.3h-1.2v-7.9h1.2v4.1c.1-.2.7-.9.9-1.2l2.3-2.9h1.3l-2.3 2.9 2.9 5z"/><path id="path4757" d="M764.9 109.1c0 1.4-.9 2.4-2.9 2.4-1.2 0-2.2-.5-2.8-1.3l.8-.8c.5.6 1.3.9 2.1.9 1.1 0 1.6-.4 1.6-1.2 0-.6-.5-.9-1.8-1.3-1.7-.5-2.5-.9-2.5-2.3s1.2-2.2 2.6-2.2c1.1 0 1.9.4 2.6 1.1l-.8.9c-.5-.5-1.1-.8-1.8-.8-.9 0-1.3.5-1.3 1 0 .6.4.8 1.7 1.2 1.5.5 2.5 1 2.5 2.4z"/><path id="path4759" d="M772.5 105.9c0 1.6-1.1 2.5-2.6 2.5h-2.1v3h-1.2v-7.9h3.3c1.6 0 2.6.8 2.6 2.4zm-1.2 0c0-.9-.5-1.4-1.4-1.4h-2.1v2.7h2.1c1 .1 1.4-.4 1.4-1.3z"/><path id="path4761" d="M779.8 111.4h-1.3l-.7-1.9h-3.2l-.7 1.9h-1.2l2.9-7.9h1.3l2.9 7.9zm-2.3-3-.6-1.8-.6-1.8-.6 1.8-.6 1.8h2.4z"/><path id="path4763" d="M786.8 110c-.6 1-1.5 1.5-2.7 1.5-2.1 0-3.4-1.7-3.4-4.1 0-2.4 1.3-4.1 3.4-4.1 1.3 0 2.2.5 2.7 1.5l-1.1.7c-.4-.6-.8-1-1.6-1-1.4 0-2.1 1.1-2.1 2.9 0 1.8.7 2.9 2.1 2.9.8 0 1.3-.3 1.7-1l1 .7z"/><path id="path4765" d="M793.8 111.4h-5.3v-7.9h5.1v1.2h-3.9v2h2.3v1.2h-2.3v2.5h4.1v1z"/></g><path id="path4769" d="M848.5 87.9h1.5l5.9 6.3 5.9-6.3h1.6l-7.5 7.9-7.4-7.9zm8.3 3.2c-.1-.2-.1-.4-.1-.5-.3.3-.5.5-.7.5-.2.1-.4.1-.6.1-.3 0-.6-.1-.8-.3s-.3-.5-.3-.8c0-.4.2-.7.5-.9.3-.2.9-.4 1.6-.5l.4-.1v-.4c0-.2-.1-.4-.2-.5-.2-.1-.4-.1-.6-.1-.3 0-.5.1-.6.2-.2.1-.2.3-.2.4v.1h-.7v-.1c0-.2.1-.3.2-.5s.3-.3.6-.4.5-.1.8-.1c.3 0 .5 0 .8.1.2.1.4.2.5.4.1.2.2.4.2.8v2c0 .2.1.4.1.6h-.9zm-.1-1.9h-.2c-.7.2-1.1.3-1.3.5-.2.1-.3.3-.3.5 0 .1 0 .2.1.3.1.1.1.2.2.2.1.1.2.1.3.1.2 0 .4-.1.5-.2.2-.1.3-.2.4-.4.1-.2.1-.4.1-.6v-.4z"/><g id="g4783"><path id="path4771" d="M838.3 111.2h-1.2v-7.9h1.2v7.9z"/><path id="path4773" d="M846.4 111.2h-1.1l-3.2-5c-.2-.3-.5-.8-.6-1v5.9h-1.2v-7.9h1.2l3 4.8c.2.3.5.9.7 1.1v-6h1.2v8.1z"/><path id="path4775" d="M853.8 109c0 1.4-.9 2.4-2.9 2.4-1.2 0-2.2-.5-2.8-1.3l.8-.8c.5.6 1.3.9 2.1.9 1.1 0 1.6-.4 1.6-1.2 0-.6-.5-.9-1.8-1.3-1.7-.5-2.5-.9-2.5-2.3s1.2-2.2 2.6-2.2c1.1 0 1.9.4 2.6 1.1l-.8.9c-.5-.5-1.1-.8-1.8-.8-.9 0-1.3.5-1.3 1 0 .6.4.8 1.7 1.2 1.5.5 2.5 1 2.5 2.4z"/><path id="path4777" d="M860.9 111.2h-5.3v-7.9h5.1v1.2h-3.9v2h2.3v1.2h-2.3v2.5h4.1v1z"/><path id="path4779" d="M868.6 105.7c0 1.3-.7 2.1-1.7 2.3l1.6 3.2h-1.4l-1.6-3.1h-1.8v3.1h-1.2v-7.9h3.5c1.4 0 2.6.7 2.6 2.4zm-1.2 0c0-.8-.5-1.3-1.3-1.3h-2.3v2.6h2.3c.7 0 1.3-.4 1.3-1.3z"/><path id="path4781" d="M875.5 104.5h-2.3v6.8H872v-6.8h-2.3v-1.2h5.8v1.2z"/></g><path id="path4785" d="M913.8 87.9v.5h-7.1v7.1h-.5v-7.6h7.6zm-6 2 .4-.4h2.9v.9h-1.6l4.3 4.3-.8.8-4.3-4.3v1.6h-.9v-2.9z"/><g id="g4795"><path id="path4787" d="M900.9 110.4h-1.2v-3.5H896v3.5h-1.2v-7.9h1.2v3.2h3.7v-3.2h1.2v7.9z"/><path id="path4789" d="M909.4 106.5c0 2.5-1.4 4.1-3.4 4.1s-3.4-1.6-3.4-4.1c0-2.5 1.4-4.1 3.4-4.1s3.4 1.6 3.4 4.1zm-1.2 0c0-1.8-.9-2.9-2.2-2.9-1.3 0-2.1 1.1-2.1 2.9s.9 2.9 2.2 2.9c1.2 0 2.1-1.1 2.1-2.9z"/><path id="path4791" d="M918.1 110.4H917v-5.6c-.1.2-.3.8-.5 1.2l-1.9 4.5-1.9-4.5c-.2-.5-.4-1-.5-1.2v5.6H911v-7.9h1.2l1.8 4.2c.2.5.4 1 .5 1.4.1-.3.3-.9.5-1.4l1.7-4.2h1.3v7.9z"/><path id="path4793" d="M925.5 110.4h-5.3v-7.9h5.1v1.2h-3.9v2h2.3v1.2h-2.3v2.5h4.1v1z"/></g><path id="path4797" d="M964.5 92.3h1.8v1h-1.8v1.2h1.8v1h-1.8v2.7h-1v-2.7h-1.8v-1h1.8v-1.2h-1.8v-1h1.8v-2.1H961l3-3 3 3h-2.5v2.1z"/><g id="g4807"><path id="path4799" d="M954.4 105.9c0 1.6-1.1 2.4-2.6 2.4h-2v2.9h-1.1v-7.7h3.2c1.4-.1 2.5.8 2.5 2.4zm-1.2 0c0-.9-.5-1.3-1.3-1.3h-2.1v2.7h2.1c.9-.1 1.3-.6 1.3-1.4z"/><path id="path4801" d="M961.7 108.2c0 2-1.2 3.2-2.9 3.2-2 0-3.3-1.6-3.3-4s1.3-4 3.3-4c1.3 0 2.1.5 2.6 1.4l-1 .6c-.4-.6-.8-.9-1.6-.9-1.3 0-2.1 1.1-2.1 2.8s.7 2.8 2.1 2.8c1.3 0 1.8-.8 1.8-1.7h-1.3v-1.1h2.4v.9z"/><path id="path4803" d="M972.2 108c0 2.2-1.1 3.4-3 3.4s-2.9-1.2-2.9-3.4v-4.5h1.2v4.5c0 1.5.6 2.2 1.8 2.2 1.2 0 1.8-.8 1.8-2.2v-4.5h1.2v4.5z"/><path id="path4805" d="M979.9 105.9c0 1.6-1.1 2.4-2.6 2.4h-2v2.9h-1.1v-7.7h3.2c1.4-.1 2.5.8 2.5 2.4zm-1.2 0c0-.9-.5-1.3-1.3-1.3h-2.1v2.7h2.1c.8-.1 1.3-.6 1.3-1.4z"/></g><path id="path4809" d="M1030.1 91v-3.4h-1.2l2.6-2.6 2.6 2.6h-1.2V91h1.2v2h-5.2v-2h1.2zm1.2-5-1.1 1.1h.4v4.4h-1.2v1h1.9V86zm.4 0v6.5h1.9v-1h-1.2v-4.4h.4l-1.1-1.1z"/><path id="path4811" d="M1027.3 103.2h-.8l-2.4-3.7c-.1-.2-.3-.6-.4-.7v4.5h-.9v-5.9h.9l2.3 3.6c.2.2.4.7.5.8v-4.5h.9v5.9z"/><path id="path4813" d="M1033.4 100.7c0 1.7-.8 2.6-2.3 2.6-1.5 0-2.2-1-2.2-2.6v-3.5h.9v3.4c0 1.1.5 1.7 1.4 1.7.9 0 1.4-.6 1.4-1.7v-3.5h.9v3.6z"/><path id="path4815" d="M1040.2 103.2h-.9V99c-.1.2-.2.6-.4.9l-1.4 3.3-1.4-3.3c-.1-.3-.3-.8-.4-.9v4.1h-.8v-5.9h.9l1.3 3.2c.1.3.3.8.4 1 .1-.2.3-.7.4-1l1.3-3.2h1v6z"/><path id="path4817" d="M1025 113.4h-3.9v-5.9h.9v5.1h3v.8z"/><path id="path4819" d="M1030.7 110.4c0 1.9-1 3.1-2.5 3.1s-2.5-1.2-2.5-3.1c0-1.9 1-3.1 2.5-3.1s2.5 1.2 2.5 3.1zm-.9 0c0-1.4-.7-2.2-1.6-2.2-.9 0-1.6.8-1.6 2.2 0 1.4.7 2.2 1.6 2.2 1 0 1.6-.9 1.6-2.2z"/><path id="path4821" d="M1036.3 112.3c-.4.7-1.1 1.1-2 1.1-1.5 0-2.5-1.3-2.5-3.1s1-3.1 2.5-3.1c1 0 1.6.4 2 1.1l-.8.5c-.3-.5-.6-.7-1.2-.7-1 0-1.6.8-1.6 2.2s.6 2.2 1.6 2.2c.6 0 1-.3 1.3-.7l.7.5z"/><path id="path4823" d="M1042.3 113.4h-1l-1.7-3.1-1.1 1.3v1.7h-.9v-5.9h.9v3.1c.1-.2.5-.6.7-.9l1.8-2.2h1l-1.7 2.2 2 3.8z"/><path id="path4825" d="m44.2 141.3-1.9 2h10v.9h-10l1.9 2-.5.5-3.1-2.9v2.6h-.9V141h.9v2.6l3.1-2.9.5.6zm8.1 5.5v5.4h-.9v-2.6l-3.1 2.9-.5-.5 1.9-2h-10v-.9h10l-1.9-2 .5-.5 3.1 2.9v-2.6h.9z"/><g id="g4833"><path id="path4827" d="M41.6 158.9h-2.3v6.8h-1.2v-6.8h-2.3v-1.2h5.8v1.2z"/><path id="path4829" d="M48.6 165.6h-1.3l-.7-1.9h-3.2l-.7 1.9h-1.2l2.9-7.9h1.3l2.9 7.9zm-2.3-2.9-.6-1.8-.6-1.8-.6 1.8-.6 1.8h2.4z"/><path id="path4831" d="M56 163.2c0 1.6-1 2.4-2.7 2.4h-3.2v-7.9h3.3c1.4 0 2.3.7 2.3 2.1 0 .8-.4 1.3-1 1.6.6.1 1.3.7 1.3 1.8zm-1.5-3.4c0-.6-.3-1-1.1-1h-2.1v2.1h2.1c.8-.1 1.1-.6 1.1-1.1zm.4 3.4c0-.8-.5-1.3-1.4-1.3h-2.2v2.6h2.1c1.1 0 1.5-.5 1.5-1.3z"/></g><path id="path4835" d="M858.3 151.7h-9.5v-10.2h9.5l5.1 5.1-5.1 5.1zm3.7-5.1-4.1-4.1h-8.1v8.2h8.1l4.1-4.1zm-7.2.7-2.3 2.3-.7-.7 2.3-2.3-2.3-2.3.7-.7 2.3 2.3 2.3-2.3.7.7-2.3 2.3 2.3 2.3-.7.7-2.3-2.3z"/><g id="g4843"><path id="path4837" d="M852.4 161.3c0 2.8-1.8 4-3.9 4h-2.2v-7.9h2.2c2.1 0 3.9 1.1 3.9 3.9zm-1.3 0c0-1.7-.8-2.8-2.7-2.8h-1v5.6h1c2 .1 2.7-1.1 2.7-2.8z"/><path id="path4839" d="M859.3 165.3H854v-7.9h5.1v1.2h-3.9v2h2.3v1.2h-2.3v2.5h4.1v1z"/><path id="path4841" d="M866.1 165.3H861v-7.9h1.2v6.8h4v1.1z"/></g><path id="path4845" d="M911.8 148.6h-2.9v-.9h1.6l-4.3-4.3.8-.8 4.3 4.3v-1.6h.9v2.9l-.4.4zm2-5.9v7.6h-7.6v-.5h7.1v-7.1h.5z"/><g id="g4853"><path id="path4847" d="M904.9 165.3h-5.3v-7.9h5.1v1.2h-3.9v2h2.3v1.2h-2.3v2.5h4.1v1z"/><path id="path4849" d="M912.7 165.3h-1.1l-3.2-5c-.2-.3-.5-.8-.6-1v5.9h-1.2v-7.9h1.2l3 4.8c.2.3.5.9.7 1.1v-6h1.2v8.1z"/><path id="path4851" d="M920.7 161.3c0 2.8-1.8 4-3.9 4h-2.2v-7.9h2.2c2.2 0 3.9 1.1 3.9 3.9zm-1.2 0c0-1.7-.8-2.8-2.7-2.8h-1v5.6h1c2 .1 2.7-1.1 2.7-2.8z"/></g><path id="path4855" d="M963.5 147.4h-1.8v-1h1.8v-1.2h-1.8v-1h1.8v-2.7h1v2.7h1.8v1h-1.8v1.2h1.8v1h-1.8v2.1h2.5l-3 3-3-3h2.5v-2.1z"/><g id="g4865"><path id="path4857" d="M953.9 159.9c0 1.6-1.1 2.5-2.6 2.5h-2.1v3H948v-7.9h3.3c1.5-.1 2.6.7 2.6 2.4zm-1.2 0c0-.9-.5-1.4-1.4-1.4h-2.1v2.7h2.1c1 0 1.4-.5 1.4-1.3z"/><path id="path4859" d="M961.5 162.2c0 2-1.2 3.2-3 3.2-2.1 0-3.4-1.7-3.4-4.1 0-2.4 1.3-4.1 3.4-4.1 1.3 0 2.2.5 2.7 1.5l-1 .6c-.4-.6-.8-.9-1.7-.9-1.4 0-2.1 1.1-2.1 2.9 0 1.8.8 2.9 2.1 2.9s1.8-.9 1.8-1.8H959v-1.1h2.5v.9z"/><path id="path4861" d="M972.2 161.3c0 2.8-1.8 4-3.9 4h-2.2v-7.9h2.2c2.2 0 3.9 1.1 3.9 3.9zm-1.2 0c0-1.7-.8-2.8-2.7-2.8h-1v5.6h1c2 .1 2.7-1.1 2.7-2.8z"/><path id="path4863" d="M979.9 165.3h-1.1l-3.2-5c-.2-.3-.5-.8-.6-1v5.9h-1.2v-7.9h1.2l3 4.8c.2.3.5.9.7 1.1v-6h1.2v8.1z"/></g><path id="path4867" d="m47.2 200.4 5.6-5.6 5.6 5.6h-2.8v2.1H50v-2.1h-2.8zm5.6-4.4-3.7 3.7h1.7v2h4v-2h1.7l-3.7-3.7zm-2.8 8.1h5.6v2.8H50v-2.8zm.8.8v1.2h4v-1.2h-4z"/><g id="g4885"><path id="path4869" d="M28.3 218.2c-.6 1-1.5 1.5-2.7 1.5-2.1 0-3.4-1.7-3.4-4.1s1.3-4.1 3.4-4.1c1.3 0 2.2.5 2.7 1.5l-1.1.7c-.4-.6-.8-1-1.6-1-1.4 0-2.1 1.1-2.1 2.9 0 1.8.7 2.9 2.1 2.9.8 0 1.3-.3 1.7-1l1 .7z"/><path id="path4871" d="M36.3 219.5H35l-.7-1.9h-3.2l-.7 1.9h-1.2l2.9-7.9h1.3l2.9 7.9zm-2.3-2.9-.6-1.8-.6-1.8-.6 1.8-.6 1.8H34z"/><path id="path4873" d="M43.7 214.1c0 1.6-1.1 2.5-2.6 2.5H39v3h-1.2v-7.9h3.3c1.6-.1 2.6.8 2.6 2.4zm-1.2 0c0-.9-.5-1.4-1.4-1.4H39v2.7h2.1c1 .1 1.4-.5 1.4-1.3z"/><path id="path4875" d="M50.5 217.3c0 1.4-.9 2.4-2.9 2.4-1.2 0-2.2-.5-2.8-1.3l.9-.8c.5.6 1.3.9 2.1.9 1.1 0 1.6-.4 1.6-1.2 0-.6-.5-.9-1.8-1.3-1.7-.5-2.5-.9-2.5-2.3s1.2-2.2 2.6-2.2c1.1 0 1.9.4 2.6 1.1l-.8.8c-.5-.5-1.1-.8-1.8-.8-.9 0-1.3.5-1.3 1 0 .6.4.8 1.7 1.2 1.4.6 2.4 1.1 2.4 2.5z"/><path id="path4877" d="M60.5 219.5h-5.1v-7.9h1.2v6.8h4v1.1z"/><path id="path4879" d="M68.1 215.6c0 2.5-1.4 4.1-3.4 4.1s-3.4-1.6-3.4-4.1 1.4-4.1 3.4-4.1c2.1 0 3.4 1.6 3.4 4.1zm-1.2 0c0-1.8-.9-2.9-2.2-2.9-1.3 0-2.1 1.1-2.1 2.9s.9 2.9 2.2 2.9c1.2 0 2.1-1.1 2.1-2.9z"/><path id="path4881" d="M75.5 218.2c-.6 1-1.5 1.5-2.7 1.5-2.1 0-3.4-1.7-3.4-4.1s1.3-4.1 3.4-4.1c1.3 0 2.2.5 2.7 1.5l-1.1.7c-.4-.6-.8-1-1.6-1-1.4 0-2.1 1.1-2.1 2.9 0 1.8.7 2.9 2.1 2.9.8 0 1.3-.3 1.7-1l1 .7z"/><path id="path4883" d="M83.5 219.5h-1.3l-2.3-4.1-1.5 1.8v2.3h-1.2v-7.9h1.2v4.1c.1-.2.7-.9.9-1.2l2.3-2.9H83l-2.3 2.9 2.8 5z"/></g><path id="path4887" d="m748.9 200.5 3-3v2.5h7.1v-4.4h-3.5v-1h4.6v6.4H752v2.5l-3.1-3z"/><g id="g4901"><path id="path4889" d="M739 214.2c0 1.3-.7 2.1-1.7 2.3l1.6 3.2h-1.4l-1.6-3.1h-1.8v3.1h-1.2v-7.9h3.5c1.4 0 2.6.8 2.6 2.4zm-1.2.1c0-.8-.5-1.3-1.3-1.3h-2.3v2.6h2.3c.7-.1 1.3-.5 1.3-1.3z"/><path id="path4891" d="M746.1 219.8h-5.3v-7.9h5.1v1.2H742v2h2.3v1.2H742v2.5h4.1v1z"/><path id="path4893" d="M753.1 213h-2.3v6.8h-1.2V213h-2.3v-1.2h5.8v1.2z"/><path id="path4895" d="M760.6 216.5c0 2.2-1.1 3.4-3 3.4-2 0-3-1.3-3-3.5v-4.6h1.2v4.6c0 1.5.6 2.3 1.8 2.3 1.2 0 1.8-.8 1.8-2.2v-4.6h1.2v4.6z"/><path id="path4897" d="M768.7 214.2c0 1.3-.7 2.1-1.7 2.3l1.6 3.2h-1.4l-1.6-3.1h-1.8v3.1h-1.2v-7.9h3.5c1.4 0 2.6.8 2.6 2.4zm-1.2.1c0-.8-.5-1.3-1.3-1.3h-2.3v2.6h2.3c.7-.1 1.3-.5 1.3-1.3z"/><path id="path4899" d="M776.6 219.8h-1.1l-3.2-5c-.2-.3-.5-.8-.6-1v5.9h-1.2v-7.9h1.2l3 4.8c.2.3.5.9.7 1.1v-6h1.2v8.1z"/></g><path id="path4903" d="m60.4 254.4 5.9-5.9 5.9 5.9h-2.9v5.2h-5.9v-5.2h-3zm5.8-4.6-3.9 3.9h1.8v5.1h4.2v-5.1h1.8l-3.9-3.9z"/><g id="g4915"><path id="path4905" d="M56.6 271.5c0 1.4-.9 2.4-2.9 2.4-1.2 0-2.2-.5-2.8-1.3l.9-.8c.5.6 1.3.9 2.1.9 1.1 0 1.6-.4 1.6-1.2 0-.6-.5-.9-1.8-1.3-1.7-.5-2.5-.9-2.5-2.3s1.2-2.2 2.6-2.2c1.1 0 1.9.4 2.6 1.1l-.8.8c-.5-.5-1.1-.8-1.8-.8-.9 0-1.3.5-1.3 1 0 .6.4.8 1.7 1.2 1.4.6 2.4 1.1 2.4 2.5z"/><path id="path4907" d="M64.4 273.8h-1.2v-3.5h-3.7v3.5h-1.2v-7.9h1.2v3.2h3.7v-3.2h1.2v7.9z"/><path id="path4909" d="M67.7 273.8h-1.2v-7.9h1.2v7.9z"/><path id="path4911" d="M74.9 267.1H71v2.1h2.3v1.2H71v3.5h-1.2V266h5.1v1.1z"/><path id="path4913" d="M81.7 267.1h-2.3v6.8h-1.2v-6.8h-2.3v-1.2h5.8v1.2z"/></g><path id="path4917" d="m735.4 254.4 5.9-5.9 5.9 5.9h-2.9v5.2h-5.9v-5.2h-3zm5.8-4.6-3.9 3.9h1.8v5.1h4.2v-5.1h1.8l-3.9-3.9z"/><g id="g4929"><path id="path4919" d="M731.6 271.5c0 1.4-.9 2.4-2.9 2.4-1.2 0-2.2-.5-2.8-1.3l.8-.8c.5.6 1.3.9 2.1.9 1.1 0 1.6-.4 1.6-1.2 0-.6-.5-.9-1.8-1.3-1.7-.5-2.5-.9-2.5-2.3s1.2-2.2 2.6-2.2c1.1 0 1.9.4 2.6 1.1l-.8.8c-.5-.5-1.1-.8-1.8-.8-.9 0-1.3.5-1.3 1 0 .6.4.8 1.7 1.2 1.5.6 2.5 1.1 2.5 2.5z"/><path id="path4921" d="M739.4 273.8h-1.2v-3.5h-3.7v3.5h-1.2v-7.9h1.2v3.2h3.7v-3.2h1.2v7.9z"/><path id="path4923" d="M742.7 273.8h-1.2v-7.9h1.2v7.9z"/><path id="path4925" d="M749.9 267.1H746v2.1h2.3v1.2H746v3.5h-1.2V266h5.1v1.1z"/><path id="path4927" d="M756.7 267.1h-2.3v6.8h-1.2v-6.8h-2.3v-1.2h5.8v1.2z"/></g><path id="path4931" d="m1188.1 291.5 5.4-5.4 5.4 5.4-1 1-4.5-4.5-4.4 4.5-.9-1zm3.1-5.4v1.4h-3.2v-1.4h3.2zm7.7 0v1.4h-3.2v-1.4h3.2z"/><g id="g4943"><path id="path4933" d="M1181.4 326.4h-5.3v-7.9h5.1v1.2h-3.9v2h2.3v1.2h-2.3v2.5h4.1v1z"/><path id="path4935" d="M1189.1 326.4h-1.1l-3.2-5c-.2-.3-.5-.8-.6-1v5.9h-1.2v-7.9h1.2l3 4.8c.2.3.5.9.7 1.1v-6h1.2v8.1z"/><path id="path4937" d="M1196.5 319.7h-2.3v6.8h-1.2v-6.8h-2.3v-1.2h5.8v1.2z"/><path id="path4939" d="M1203.4 326.4h-5.3v-7.9h5.1v1.2h-3.9v2h2.3v1.2h-2.3v2.5h4.1v1z"/><path id="path4941" d="M1211.1 320.9c0 1.3-.7 2.1-1.7 2.3l1.6 3.2h-1.4l-1.6-3.1h-1.8v3.1h-1.2v-7.9h3.5c1.4 0 2.6.7 2.6 2.4zm-1.2 0c0-.8-.5-1.3-1.3-1.3h-2.3v2.6h2.3c.7 0 1.3-.4 1.3-1.3z"/></g><g id="g4959"><path id="path4945" d="M19.7 325c-.6 1-1.5 1.5-2.7 1.5-2.1 0-3.4-1.7-3.4-4.1s1.3-4.1 3.4-4.1c1.3 0 2.2.5 2.7 1.5l-1.1.7c-.4-.6-.8-1-1.6-1-1.4 0-2.1 1.1-2.1 2.9 0 1.8.7 2.9 2.1 2.9.8 0 1.3-.3 1.7-1l1 .7z"/><path id="path4947" d="M27.5 322.5c0 2.5-1.4 4.1-3.4 4.1s-3.4-1.6-3.4-4.1 1.4-4.1 3.4-4.1 3.4 1.6 3.4 4.1zm-1.2 0c0-1.8-.9-2.9-2.2-2.9-1.3 0-2.1 1.1-2.1 2.9s.9 2.9 2.2 2.9c1.2 0 2.1-1.1 2.1-2.9z"/><path id="path4949" d="M35.2 326.4h-1.1l-3.2-5c-.2-.3-.5-.8-.6-1v5.9h-1.2v-7.9h1.2l3 4.8c.2.3.5.9.7 1.1v-6h1.2v8.1z"/><path id="path4951" d="M42.6 319.7h-2.3v6.8h-1.2v-6.8h-2.3v-1.2h5.8v1.2z"/><path id="path4953" d="M50.2 320.9c0 1.3-.7 2.1-1.7 2.3l1.6 3.2h-1.4l-1.6-3.1h-1.8v3.1h-1.2v-7.9h3.5c1.4 0 2.6.7 2.6 2.4zm-1.2 0c0-.8-.5-1.3-1.3-1.3h-2.3v2.6h2.3c.7 0 1.3-.4 1.3-1.3z"/><path id="path4955" d="M58.2 322.5c0 2.5-1.4 4.1-3.4 4.1s-3.4-1.6-3.4-4.1 1.4-4.1 3.4-4.1 3.4 1.6 3.4 4.1zm-1.2 0c0-1.8-.9-2.9-2.2-2.9-1.3 0-2.1 1.1-2.1 2.9s.9 2.9 2.2 2.9c1.2 0 2.1-1.1 2.1-2.9z"/><path id="path4957" d="M65 326.4h-5.1v-7.9h1.2v6.8h4v1.1z"/></g><path id="path4961" d="M111 302.8v8.8h-8.7v-8.8h8.7zm-4.8 4v-3.2H103v3.2h3.2zm0 .8H103v3.2h3.2v-3.2zm.8-.8h3.3v-3.3H107v3.3zm0 .8v3.2h3.3v-3.2H107z"/><g id="g4969"><path id="path4963" d="m105.3 318.5-1.6 7.9h-1.2l-1.2-5.1c-.1-.3-.2-.9-.2-1.1 0 .2-.2.8-.2 1.1l-1.3 5.1h-1.2l-1.6-7.9H98l1 5c0 .2.1.8.2 1 0-.3.2-.8.2-1l1.3-5h1l1.3 5.1c.1.2.1.6.2.9.1-.3.1-.7.2-.9l1-5.1h.9z"/><path id="path4965" d="M108.2 326.4H107v-7.9h1.2v7.9z"/><path id="path4967" d="M116.3 326.4h-1.1l-3.2-5c-.2-.3-.5-.8-.6-1v5.9h-1.2v-7.9h1.2l3 4.8c.2.3.5.9.7 1.1v-6h1.2v8.1z"/></g><path id="path4971" d="M180.1 302v1H177l-4.6 9.2h-4v-1h3.2l4.6-9.2h3.9zm-4.7 10.3v-1h4.8v1h-4.8z"/><g id="g4979"><path id="path4973" d="M171.6 326.4h-1.3l-.7-1.9h-3.2l-.7 1.9h-1.2l2.9-7.9h1.3l2.9 7.9zm-2.3-2.9-.6-1.8-.6-1.8-.6 1.8-.6 1.8h2.4z"/><path id="path4975" d="M178.4 326.4h-5.1v-7.9h1.2v6.8h4v1.1z"/><path id="path4977" d="M183.9 319.7h-2.3v6.8h-1.2v-6.8H178v-1.2h5.8v1.2z"/></g><path id="path4981" d="M374.8 309.2v-2h.7v1.4h2.6v-1.4h.7v2h-4z"/><g id="g4993"><path id="path4983" d="M365.1 324.2c0 1.4-.9 2.4-2.9 2.4-1.2 0-2.2-.5-2.8-1.3l.9-.8c.5.6 1.3.9 2.1.9 1.1 0 1.6-.4 1.6-1.2 0-.6-.5-.9-1.8-1.3-1.7-.5-2.5-.9-2.5-2.3s1.2-2.2 2.6-2.2c1.1 0 1.9.4 2.6 1.1l-.8.8c-.5-.5-1.1-.8-1.8-.8-.9 0-1.3.5-1.3 1 0 .6.4.8 1.7 1.2 1.5.5 2.4 1 2.4 2.5z"/><path id="path4985" d="M372.8 321c0 1.6-1.1 2.5-2.6 2.5h-2.1v3h-1.2v-7.9h3.3c1.5-.1 2.6.7 2.6 2.4zm-1.2 0c0-.9-.5-1.4-1.4-1.4h-2.1v2.7h2.1c.9.1 1.4-.5 1.4-1.3z"/><path id="path4987" d="M380 326.4h-1.3l-.7-1.9h-3.2l-.7 1.9H373l2.9-7.9h1.3l2.8 7.9zm-2.3-2.9-.6-1.8-.6-1.8-.6 1.8-.6 1.8h2.4z"/><path id="path4989" d="M387.1 325c-.6 1-1.5 1.5-2.7 1.5-2.1 0-3.4-1.7-3.4-4.1s1.3-4.1 3.4-4.1c1.3 0 2.2.5 2.7 1.5l-1.1.7c-.4-.6-.8-1-1.6-1-1.4 0-2.1 1.1-2.1 2.9 0 1.8.7 2.9 2.1 2.9.8 0 1.3-.3 1.7-1l1 .7z"/><path id="path4991" d="M394.1 326.4h-5.3v-7.9h5.1v1.2H390v2h2.3v1.2H390v2.5h4.1v1z"/></g><path id="path4995" d="M573.4 311.2h3.2l4.6-9.2h4v1H582l-4.6 9.2h-4v-1zm7 0h4.8v1h-4.8v-1z"/><g id="g5003"><path id="path4997" d="M576.7 326.4h-1.3l-.7-1.9h-3.2l-.7 1.9h-1.2l2.9-7.9h1.3l2.9 7.9zm-2.3-2.9-.6-1.8-.6-1.8-.6 1.8-.6 1.8h2.4z"/><path id="path4999" d="M583.4 326.4h-5.1v-7.9h1.2v6.8h4v1.1z"/><path id="path5001" d="M588.9 319.7h-2.3v6.8h-1.2v-6.8H583v-1.2h5.8v1.2z"/></g><path id="path5005" d="M651.1 302.8v8.8h-8.7v-8.8h8.7zm-4.8 4v-3.2h-3.2v3.2h3.2zm0 .8h-3.2v3.2h3.2v-3.2zm.8-.8h3.3v-3.3h-3.3v3.3zm0 .8v3.2h3.3v-3.2h-3.3z"/><g id="g5013"><path id="path5007" d="m645.3 318.5-1.6 7.9h-1.2l-1.2-5.1c-.1-.3-.2-.9-.2-1.1 0 .2-.2.8-.2 1.1l-1.3 5.1h-1.2l-1.6-7.9h1.2l1 5c0 .2.1.8.2 1 0-.3.2-.8.2-1l1.3-5h1l1.3 5.1c.1.2.1.6.2.9.1-.3.1-.7.2-.9l1-5.1h.9z"/><path id="path5009" d="M648.2 326.4H647v-7.9h1.2v7.9z"/><path id="path5011" d="M656.3 326.4h-1.1l-3.2-5c-.2-.3-.5-.8-.6-1v5.9h-1.2v-7.9h1.2l3 4.8c.2.3.5.9.7 1.1v-6h1.2v8.1z"/></g><path id="path5015" d="M710.6 303.4h7.3v1.2h-7.3v-1.2zm0 2.5h7.3v1.2h-7.3v-1.2zm0 2.5h7.3v1.2h-7.3v-1.2zm0 2.5h7.3v1.2h-7.3v-1.2z"/><g id="g5025"><path id="path5017" d="M706.3 326.3h-1.2v-5.6c-.1.2-.3.8-.5 1.2l-1.9 4.5-1.9-4.5c-.2-.5-.4-1-.5-1.2v5.6h-1.1v-7.9h1.2l1.8 4.2c.2.5.4 1 .5 1.4.1-.3.3-.9.5-1.4l1.7-4.2h1.3v7.9z"/><path id="path5019" d="M713.6 326.3h-5.3v-7.9h5.1v1.2h-3.9v2h2.3v1.2h-2.3v2.5h4.1v1z"/><path id="path5021" d="M721.3 326.3h-1.1l-3.2-5c-.2-.3-.5-.8-.6-1v5.9h-1.2v-7.9h1.2l3 4.8c.2.3.5.9.7 1.1v-6h1.2v8.1z"/><path id="path5023" d="M729.4 323c0 2.2-1.1 3.4-3 3.4-2 0-3-1.3-3-3.5v-4.6h1.2v4.6c0 1.5.6 2.3 1.8 2.3 1.2 0 1.8-.8 1.8-2.2v-4.6h1.2v4.6z"/></g><path id="path5027" d="M781.2 313.6v-1.4c-1.5-.2-2.7-.9-3.6-2.1l-1.2.7-.5-.9 1.2-.7c-.3-.7-.4-1.4-.4-2.1 0-.7.1-1.4.4-2.1l-1.2-.7.5-.9 1.2.7c.9-1.2 2.1-1.9 3.6-2.1v-1.4h1v1.4c1.5.2 2.7.9 3.6 2.1l1.2-.7.5.9-1.2.7c.3.7.5 1.4.5 2.1 0 .7-.2 1.4-.5 2.1l1.2.7-.5.9-1.2-.7c-.9 1.2-2.1 1.9-3.6 2.1v1.4h-1zm-3.2-8c-.2.5-.3 1-.3 1.6 0 .5.1 1.1.3 1.6l2.8-1.6-2.8-1.6zm3.2-2.5c-1.1.1-2 .7-2.7 1.6l2.8 1.6v-3.2zm-2.7 6.5c.7.9 1.6 1.4 2.7 1.6V308l-2.7 1.6zm6.5-4.9c-.7-.9-1.6-1.4-2.7-1.6v3.2l2.7-1.6zm-2.7 6.5c1.1-.1 2-.7 2.7-1.6l-2.8-1.6v3.2zm3.2-2.5c.2-.5.3-1 .3-1.6 0-.5-.1-1.1-.3-1.6l-2.8 1.6 2.8 1.6z"/><path id="path5029" d="M38.7 313.6v-1.4c-1.5-.2-2.7-.9-3.6-2.1l-1.2.7-.5-.9 1.2-.7c-.3-.7-.4-1.4-.4-2.1 0-.7.1-1.4.4-2.1l-1.2-.7.5-.9 1.2.7c.9-1.2 2.1-1.9 3.6-2.1v-1.4h1v1.4c1.5.2 2.7.9 3.6 2.1l1.2-.7.5.9-1.2.7c.3.7.5 1.4.5 2.1 0 .7-.2 1.4-.5 2.1l1.2.7-.5.9-1.2-.7c-.9 1.2-2.1 1.9-3.6 2.1v1.4h-1zm-3.2-8c-.2.5-.3 1-.3 1.6 0 .5.1 1.1.3 1.6l2.8-1.6-2.8-1.6zm3.2-2.5c-1.1.1-2 .7-2.7 1.6l2.8 1.6v-3.2zm-2.7 6.5c.7.9 1.6 1.4 2.7 1.6V308l-2.7 1.6zm6.5-4.9c-.7-.9-1.6-1.4-2.7-1.6v3.2l2.7-1.6zm-2.7 6.5c1.1-.1 2-.7 2.7-1.6l-2.8-1.6v3.2zm3.2-2.5c.2-.5.3-1 .3-1.6 0-.5-.1-1.1-.3-1.6l-2.8 1.6 2.8 1.6z"/><g id="g5045"><path id="path5031" d="M762.2 325c-.6 1-1.5 1.5-2.7 1.5-2.1 0-3.4-1.7-3.4-4.1s1.3-4.1 3.4-4.1c1.3 0 2.2.5 2.7 1.5l-1.1.7c-.4-.6-.8-1-1.6-1-1.4 0-2.1 1.1-2.1 2.9 0 1.8.7 2.9 2.1 2.9.8 0 1.3-.3 1.7-1l1 .7z"/><path id="path5033" d="M770 322.5c0 2.5-1.4 4.1-3.4 4.1s-3.4-1.6-3.4-4.1 1.4-4.1 3.4-4.1 3.4 1.6 3.4 4.1zm-1.2 0c0-1.8-.9-2.9-2.2-2.9-1.3 0-2.1 1.1-2.1 2.9s.9 2.9 2.2 2.9c1.2 0 2.1-1.1 2.1-2.9z"/><path id="path5035" d="M777.7 326.4h-1.1l-3.2-5c-.2-.3-.5-.8-.6-1v5.9h-1.2v-7.9h1.2l3 4.8c.2.3.5.9.7 1.1v-6h1.2v8.1z"/><path id="path5037" d="M785.1 319.7h-2.3v6.8h-1.2v-6.8h-2.3v-1.2h5.8v1.2z"/><path id="path5039" d="M792.7 320.9c0 1.3-.7 2.1-1.7 2.3l1.6 3.2h-1.4l-1.6-3.1h-1.8v3.1h-1.2v-7.9h3.5c1.4 0 2.6.7 2.6 2.4zm-1.2 0c0-.8-.5-1.3-1.3-1.3h-2.3v2.6h2.3c.7 0 1.3-.4 1.3-1.3z"/><path id="path5041" d="M800.7 322.5c0 2.5-1.4 4.1-3.4 4.1s-3.4-1.6-3.4-4.1 1.4-4.1 3.4-4.1 3.4 1.6 3.4 4.1zm-1.2 0c0-1.8-.9-2.9-2.2-2.9-1.3 0-2.1 1.1-2.1 2.9s.9 2.9 2.2 2.9c1.2 0 2.1-1.1 2.1-2.9z"/><path id="path5043" d="M807.5 326.4h-5.1v-7.9h1.2v6.8h4v1.1z"/></g></g><ellipse id="path5133" cx="738.14" cy="266.501" rx="33.559" ry="32.483" style="fill:none;stroke:red;stroke-width:5.3111;stroke-linecap:round;stroke-linejoin:round"/><path id="path5285" d="m646.682 253.87 46.388-18.281-17.045-43.252L668 210.8l-57.996-25.206-10.289 23.673 56.156 24.406z" style="fill:#fe7777;fill-opacity:1;stroke:red;stroke-width:2.7008;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"/></svg> \ No newline at end of file diff --git a/app/vendor/rune/vendor/winit/docs/res/keyboard_standard_1_key.svg b/app/vendor/rune/vendor/winit/docs/res/keyboard_standard_1_key.svg new file mode 100644 index 0000000..3520d55 --- /dev/null +++ b/app/vendor/rune/vendor/winit/docs/res/keyboard_standard_1_key.svg @@ -0,0 +1 @@ +<svg xmlns="http://www.w3.org/2000/svg" xml:space="preserve" id="svg5048" x="0" y="0" style="enable-background:new 0 0 1226 349" version="1.1" viewBox="0 0 1226 349"><style id="style3852" type="text/css">.st1{fill:#ccc;stroke:#000;stroke-width:2}.st2{fill:#fcfcfc}</style><g id="Layer_1"><path id="path3854" d="M6.5.5h1213c3.3 0 6 2.7 6 6v336c0 3.3-2.7 6-6 6H6.5c-3.3 0-6-2.7-6-6V6.5c0-3.3 2.7-6 6-6z" style="fill:#eee;stroke:#ddd"/></g><g id="Layer_2"><path id="path3857" d="M13.5 9.8h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.3 1.8-4 4-4z" class="st1"/><path id="path3859" d="M121.5 9.8h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.3 1.8-4 4-4z" class="st1"/><path id="path3861" d="M175.5 9.8h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.3 1.8-4 4-4z" class="st1"/><path id="path3863" d="M229.5 9.8h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.3 1.8-4 4-4z" class="st1"/><path id="path3865" d="M283.5 9.8h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.3 1.8-4 4-4z" class="st1"/><path id="path3867" d="M364.5 9.8h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.3 1.8-4 4-4z" class="st1"/><path id="path3869" d="M418.5 9.8h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.3 1.8-4 4-4z" class="st1"/><path id="path3871" d="M472.5 9.8h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.3 1.8-4 4-4z" class="st1"/><path id="path3873" d="M526.5 9.8h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.3 1.8-4 4-4z" class="st1"/><path id="path3875" d="M607.5 9.8h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.3 1.8-4 4-4z" class="st1"/><path id="path3877" d="M661.5 9.8h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.3 1.8-4 4-4z" class="st1"/><path id="path3879" d="M715.5 9.8h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.3 1.8-4 4-4z" class="st1"/><path id="path3881" d="M769.5 9.8h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.3 1.8-4 4-4z" class="st1"/><path id="path3883" d="M837 9.8h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.3 1.8-4 4-4z" class="st1"/><path id="path3885" d="M891 9.8h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.3 1.8-4 4-4z" class="st1"/><path id="path3887" d="M945 9.8h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.3 1.8-4 4-4z" class="st1"/><path id="path3889" d="M13.5 77.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3891" d="M67.5 77.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3893" d="M121.5 77.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3895" d="M175.5 77.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3897" d="M229.5 77.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3899" d="M283.5 77.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3901" d="M337.5 77.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3903" d="M391.5 77.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3905" d="M445.5 77.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3907" d="M499.5 77.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3909" d="M553.5 77.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3911" d="M607.5 77.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3913" d="M661.5 77.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3915" d="M715.5 77.2h92c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-92c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3917" d="M837 77.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3919" d="M891 77.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3921" d="M945 77.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3923" d="M1012.5 77.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3925" d="M1066.5 77.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3927" d="M1120.5 77.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3929" d="M1174.5 77.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3931" d="M13.5 131.2h65c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-65c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3933" d="M94.5 131.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3935" d="M148.5 131.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3937" d="M202.5 131.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3939" d="M256.5 131.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3941" d="M310.5 131.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3943" d="M364.5 131.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3945" d="M418.5 131.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3947" d="M472.5 131.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3949" d="M526.5 131.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3951" d="M580.5 131.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3953" d="M634.5 131.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3955" d="M688.5 131.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3957" d="M742.5 131.2h65c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-65c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3959" d="M837 131.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3961" d="M891 131.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3963" d="M945 131.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3965" d="M1012.5 131.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3967" d="M1066.5 131.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3969" d="M1120.5 131.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3971" d="M1174.5 131.2h38c2.2 0 4 1.8 4 4v92c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-92c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3973" d="M13.5 185.2H92c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4H13.5c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3975" d="M108 185.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3977" d="M162 185.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3979" d="M216 185.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3981" d="M270 185.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3983" d="M324 185.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3985" d="M378 185.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3987" d="M432 185.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3989" d="M486 185.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3991" d="M540 185.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3993" d="M594 185.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3995" d="M648 185.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3997" d="M702 185.2h105.5c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4H702c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path3999" d="M1012.5 185.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path4001" d="M1066.5 185.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path4003" d="M1120.5 185.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path4005" d="M13.5 239.2H119c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4H13.5c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path4007" d="M135 239.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path4009" d="M189 239.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path4011" d="M243 239.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path4013" d="M297 239.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path4015" d="M351 239.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path4017" d="M405 239.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path4019" d="M459 239.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path4021" d="M513 239.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path4023" d="M567 239.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path4025" d="M621 239.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path4027" d="M675 239.2h132.5c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4H675c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path4029" d="M891 239.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path4031" d="M1012.5 239.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path4033" d="M1066.5 239.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path4035" d="M1120.5 239.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path4037" d="M1174.5 239.2h38c2.2 0 4 1.8 4 4v92c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-92c0-2.2 1.8-4 4-4z" class="st1"/><path id="path4039" d="M13.5 293.2H65c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4H13.5c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path4041" d="M81 293.2h51.5c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4H81c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path4043" d="M148.5 293.2H200c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-51.5c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path4045" d="M216 293.2h321.5c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4H216c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path4047" d="M553.5 293.2H605c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-51.5c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path4049" d="M621 293.2h51.5c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4H621c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path4051" d="M688.5 293.2H740c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-51.5c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path4053" d="M756 293.2h51.5c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4H756c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path4055" d="M837 293.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path4057" d="M891 293.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path4059" d="M945 293.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path4061" d="M1012.5 293.2h92c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-92c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/><path id="path4063" d="M1120.5 293.2h38c2.2 0 4 1.8 4 4v38c0 2.2-1.8 4-4 4h-38c-2.2 0-4-1.8-4-4v-38c0-2.2 1.8-4 4-4z" class="st1"/></g><g id="Layer_3"><path id="path4066" d="M14.5 10.8h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.3 1.8-4 4-4z" class="st2"/><path id="path4068" d="M122.5 10.8h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.3 1.8-4 4-4z" class="st2"/><path id="path4070" d="M176.5 10.8h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.3 1.8-4 4-4z" class="st2"/><path id="path4072" d="M230.5 10.8h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.3 1.8-4 4-4z" class="st2"/><path id="path4074" d="M284.5 10.8h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.3 1.8-4 4-4z" class="st2"/><path id="path4076" d="M365.5 10.8h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.3 1.8-4 4-4z" class="st2"/><path id="path4078" d="M419.5 10.8h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.3 1.8-4 4-4z" class="st2"/><path id="path4080" d="M473.5 10.8h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.3 1.8-4 4-4z" class="st2"/><path id="path4082" d="M527.5 10.8h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.3 1.8-4 4-4z" class="st2"/><path id="path4084" d="M608.5 10.8h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.3 1.8-4 4-4z" class="st2"/><path id="path4086" d="M662.5 10.8h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.3 1.8-4 4-4z" class="st2"/><path id="path4088" d="M716.5 10.8h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.3 1.8-4 4-4z" class="st2"/><path id="path4090" d="M770.5 10.8h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.3 1.8-4 4-4z" class="st2"/><path id="path4092" d="M838 10.8h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.3 1.8-4 4-4z" class="st2"/><path id="path4094" d="M892 10.8h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.3 1.8-4 4-4z" class="st2"/><path id="path4096" d="M946 10.8h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.3 1.8-4 4-4z" class="st2"/><path id="path4098" d="M14.5 78.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4100" d="M68.5 78.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4102" d="M122.5 78.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4104" d="M176.5 78.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4106" d="M230.5 78.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4108" d="M284.5 78.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4110" d="M338.5 78.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4112" d="M392.5 78.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4114" d="M446.5 78.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4116" d="M500.5 78.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4118" d="M554.5 78.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4120" d="M608.5 78.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4122" d="M662.5 78.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4124" d="M716.5 78.2h90c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-90c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4126" d="M838 78.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4128" d="M892 78.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4130" d="M946 78.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4132" d="M1013.5 78.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4134" d="M1067.5 78.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4136" d="M1121.5 78.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4138" d="M1175.5 78.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4140" d="M14.5 132.2h63c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-63c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4142" d="M95.5 132.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4144" d="M149.5 132.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4146" d="M203.5 132.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4148" d="M257.5 132.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4150" d="M311.5 132.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4152" d="M365.5 132.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4154" d="M419.5 132.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4156" d="M473.5 132.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4158" d="M527.5 132.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4160" d="M581.5 132.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4162" d="M635.5 132.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4164" d="M689.5 132.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4166" d="M743.5 132.2h63c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-63c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4168" d="M838 132.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4170" d="M892 132.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4172" d="M946 132.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4174" d="M1013.5 132.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4176" d="M1067.5 132.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4178" d="M1121.5 132.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4180" d="M1175.5 132.2h36c2.2 0 4 1.8 4 4v88c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-88c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4182" d="M14.5 186.2H91c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4H14.5c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4184" d="M109 186.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4186" d="M163 186.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4188" d="M217 186.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4190" d="M271 186.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4192" d="M325 186.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4194" d="M379 186.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4196" d="M433 186.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4198" d="M487 186.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4200" d="M541 186.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4202" d="M595 186.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4204" d="M649 186.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4206" d="M703 186.2h103.5c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4H703c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4208" d="M1013.5 186.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4210" d="M1067.5 186.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4212" d="M1121.5 186.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4214" d="M14.5 240.2H118c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4H14.5c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4216" d="M136 240.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4218" d="M190 240.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4220" d="M244 240.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4222" d="M298 240.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4224" d="M352 240.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4226" d="M406 240.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4228" d="M460 240.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4230" d="M514 240.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4232" d="M568 240.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4234" d="M622 240.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4236" d="M676 240.2h130.5c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4H676c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4238" d="M892 240.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4240" d="M1013.5 240.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4242" d="M1067.5 240.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4244" d="M1121.5 240.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4246" d="M1175.5 240.2h36c2.2 0 4 1.8 4 4v88c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-88c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4248" d="M14.5 294.2H64c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4H14.5c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4250" d="M82 294.2h49.5c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4H82c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4252" d="M149.5 294.2H199c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-49.5c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4254" d="M217 294.2h319.5c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4H217c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4256" d="M554.5 294.2H604c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-49.5c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4258" d="M622 294.2h49.5c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4H622c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4260" d="M689.5 294.2H739c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-49.5c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4262" d="M757 294.2h49.5c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4H757c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4264" d="M838 294.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4266" d="M892 294.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4268" d="M946 294.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4270" d="M1013.5 294.2h90c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-90c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/><path id="path4272" d="M1121.5 294.2h36c2.2 0 4 1.8 4 4v34c0 2.2-1.8 4-4 4h-36c-2.2 0-4-1.8-4-4v-34c0-2.2 1.8-4 4-4z" class="st2"/></g><g id="Layer_4"><g id="g4279"><path id="path4275" d="M141.4 29.3h-3.9v2.1h2.3v1.2h-2.3V36h-1.2v-7.9h5.1v1.2z"/><path id="path4277" d="M144.7 36h-1.2v-6.1h-1.4v-.8c.8-.1 1.5-.3 1.6-1h1V36z"/></g><g id="g4285"><path id="path4281" d="M193.8 29.3h-3.9v2.1h2.3v1.2h-2.3V36h-1.2v-7.9h5.1v1.2z"/><path id="path4283" d="M200.4 36h-5.7c.1-2.3 1.5-3.4 3-4.3 1.1-.6 1.3-1 1.3-1.5 0-.6-.4-1-1.5-1-.7 0-1.4.3-1.9.8l-.6-1c.7-.7 1.7-1.1 2.7-1.1 1.6 0 2.7.7 2.7 2.2 0 1.2-.6 1.7-2 2.6-1.5.9-1.9 1.4-2.1 2.2h4.2V36z"/></g><g id="g4291"><path id="path4287" d="M247.9 29.3H244v2.1h2.3v1.2H244V36h-1.2v-7.9h5.1v1.2z"/><path id="path4289" d="M254.5 33.7c0 1.6-1.1 2.5-3 2.5-1.1 0-2.3-.5-2.9-1.3l.9-.8c.5.6 1.2.9 2 .9 1.3 0 1.7-.5 1.7-1.3s-.6-1.2-1.4-1.2h-.7v-1.2h.7c.7 0 1.1-.5 1.1-1.1 0-.5-.3-1.1-1.5-1.1-.6 0-1.1.3-1.6.7l-.8-.8c.7-.7 1.5-1.1 2.5-1.1 1.5 0 2.7.8 2.7 2.2 0 1-.4 1.4-1 1.7.7.3 1.3.9 1.3 1.9z"/></g><g id="g4297"><path id="path4293" d="M301.6 29.3h-3.9v2.1h2.3v1.2h-2.3V36h-1.2v-7.9h5.1v1.2z"/><path id="path4295" d="M309 34.2h-1.1V36h-1.2v-1.7h-4.3v-1.1l4.1-5.1h1.4v5.1h1.1v1zm-2.2-4.8c-.1.2-.5.6-.7.9l-1.5 1.9c-.2.3-.6.7-.7.9h3v-2.3c-.1-.4-.1-1.1-.1-1.4z"/></g><g id="g4303"><path id="path4299" d="M382.7 29.3h-3.9v2.1h2.3v1.2h-2.3V36h-1.2v-7.9h5.1v1.2z"/><path id="path4301" d="M389.7 33.3c0 1.9-1.3 2.8-3.1 2.8-1 0-1.9-.2-2.8-.8l.6-1c.7.4 1.5.6 2.2.6 1.2 0 1.9-.6 1.9-1.6 0-.9-.6-1.4-1.6-1.4-.7 0-1.1.2-1.5.5l-1.3-.5.3-3.9h4.9v1.1h-3.8l-.2 2c.4-.2 1-.4 1.7-.4 1.8.1 2.7 1.2 2.7 2.6z"/></g><g id="g4309"><path id="path4305" d="M436.7 29.3h-3.9v2.1h2.3v1.2h-2.3V36h-1.2v-7.9h5.1v1.2z"/><path id="path4307" d="M443.9 33.5c0 1.7-1.4 2.6-3.1 2.6-1.7 0-3-.9-3-3.2 0-2.1 1.2-4.9 4.9-5V29c-1.8.1-3.1.9-3.6 2.6.6-.4 1.1-.6 2.1-.6 1.5 0 2.7.8 2.7 2.5zm-1.2 0c0-1-.7-1.4-1.8-1.4-1.2 0-1.9.5-1.9 1.4 0 .8.6 1.5 1.8 1.5 1.2 0 1.9-.6 1.9-1.5z"/></g><g id="g4315"><path id="path4311" d="M491 29.3h-3.9v2.1h2.3v1.2h-2.3V36h-1.2v-7.9h5.1v1.2z"/><path id="path4313" d="M497.2 29.3c-1.3 1.5-2.6 3.8-2.6 6.7h-1.2c0-2.7 1-4.9 2.5-6.8h-4.2V28h5.5v1.3z"/></g><g id="g4321"><path id="path4317" d="M544.5 29.3h-3.9v2.1h2.3v1.2h-2.3V36h-1.2v-7.9h5.1v1.2z"/><path id="path4319" d="M551.9 33.7c0 1.6-1.2 2.4-3.1 2.4s-3.1-.9-3.1-2.4c0-1 .5-1.6 1.4-2-.8-.3-1.1-1.1-1.1-1.5 0-1.5 1.2-2.2 2.8-2.2 1.4 0 2.8.7 2.8 2.2 0 .5-.2 1.2-1.1 1.6.9.3 1.4.9 1.4 1.9zm-1.2 0c0-.8-.6-1.4-1.9-1.4-1.3 0-1.9.5-1.9 1.3s.7 1.4 1.9 1.4c1.3.1 1.9-.5 1.9-1.3zm-.3-3.5c0-.6-.4-1.2-1.6-1.2s-1.6.5-1.6 1.1c0 .6.6 1.1 1.6 1.1 1 .1 1.6-.4 1.6-1z"/></g><g id="g4327"><path id="path4323" d="M625.7 29.3h-3.9v2.1h2.3v1.2h-2.3V36h-1.2v-7.9h5.1v1.2z"/><path id="path4325" d="M632.8 31.1c0 2.1-1.2 4.9-4.9 5V35c1.8-.1 3.1-.9 3.6-2.6-.6.4-1.1.6-2.1.6-1.4 0-2.7-.8-2.7-2.5s1.4-2.6 3.1-2.6c1.7.1 3 1 3 3.2zm-1.2-.5c0-.8-.6-1.5-1.8-1.5-1.2 0-1.9.6-1.9 1.5 0 1 .7 1.4 1.8 1.4 1.2 0 1.9-.5 1.9-1.4z"/></g><g id="g4335"><path id="path4329" d="M677.7 29.3h-3.9v2.1h2.3v1.2h-2.3V36h-1.2v-7.9h5.1v1.2z"/><path id="path4331" d="M680.9 36h-1.2v-6.1h-1.4v-.8c.8-.1 1.5-.3 1.6-1h1V36z"/><path id="path4333" d="M688.9 32c0 2.4-1.1 4.1-3.1 4.1s-3.1-1.7-3.1-4.1c0-2.4 1.1-4.1 3.1-4.1 2 .1 3.1 1.7 3.1 4.1zm-1.2.1c0-1.7-.5-2.9-1.9-2.9s-1.9 1.3-1.9 2.9.6 2.9 1.9 2.9c1.3 0 1.9-1.3 1.9-2.9z"/></g><g id="g4343"><path id="path4337" d="M733.5 29.3h-3.9v2.1h2.3v1.2h-2.3V36h-1.2v-7.9h5.1v1.2z"/><path id="path4339" d="M736.7 36h-1.2v-6.1h-1.4v-.8c.8-.1 1.5-.3 1.6-1h1V36z"/><path id="path4341" d="M740.6 36h-1.2v-6.1H738v-.8c.8-.1 1.5-.3 1.6-1h1V36z"/></g><g id="g4351"><path id="path4345" d="M785.8 29.3h-3.9v2.1h2.3v1.2h-2.3V36h-1.2v-7.9h5.1v1.2z"/><path id="path4347" d="M789.1 36h-1.2v-6.1h-1.4v-.8c.8-.1 1.5-.3 1.6-1h1V36z"/><path id="path4349" d="M796.4 36h-5.7c.1-2.3 1.5-3.4 3-4.3 1.1-.6 1.3-1 1.3-1.5 0-.6-.4-1-1.5-1-.7 0-1.4.3-1.9.8l-.8-.9c.7-.7 1.7-1.1 2.7-1.1 1.6 0 2.7.7 2.7 2.2 0 1.2-.6 1.7-2 2.6-1.5.9-2 1.4-2.1 2.2h4.2v1z"/></g><g id="g4357"><path id="path4353" d="M35.9 89.7c-.5 1.3-1.1 2-2.2 2-.6 0-.9-.2-1.4-.5-.6-.4-.9-.6-1.2-.6-.5 0-.7.3-1 1.1l-1-.5c.5-1.3 1.1-2 2.2-2 .6 0 .9.2 1.4.5.5.4.9.6 1.2.6.5 0 .7-.3 1.1-1.1l.9.5z"/><path id="path4355" d="M33.9 104.2h-1.2l-2.3-2.3h2l1.5 2.3z"/></g><g id="g4363"><path id="path4359" d="M87.6 94.8c0 .6-.5 1.1-1.1 1.1-.6 0-1.1-.5-1.1-1.1s.5-1.1 1.1-1.1c.6 0 1.1.5 1.1 1.1zm-.3-4.6-.3 2.6h-1l-.3-2.7v-4.4h1.5v4.5z"/><path id="path4361" d="M87.6 112.7h-1.5v-7.6h-1.8v-1c1-.1 1.9-.4 2-1.3h1.2v9.9z"/></g><g id="g4369"><path id="path4365" d="M145.6 89.1c0 2.1-.9 2.9-2.2 2.9-.7 0-1.3-.4-1.5-.9-.3.5-1.1.9-1.8.9-1.1 0-2.2-.6-2.2-1.9 0-1.2 1.1-1.8 2.3-1.8.6 0 1.1.2 1.4.4V88c0-.6-.5-.8-1.3-.8-.5 0-1 .1-1.4.3l-.4-.7c.5-.3 1.2-.5 1.8-.5 1.3 0 2.2.6 2.2 1.7v2.4c0 .5.3.9.9.9.9 0 1.2-.7 1.2-2.1 0-2.3-1.8-4.2-4.3-4.2s-4.3 1.8-4.3 4.3 1.8 4.3 4.3 4.3c.6 0 1.2-.1 1.8-.4l.3.8c-.8.4-1.4.5-2.2.5-3 0-5.1-2.2-5.1-5.1 0-3 2.2-5.1 5.1-5.1 3.3-.1 5.4 2.2 5.4 4.8zm-3.9 1.3v-.9c-.3-.2-.8-.4-1.5-.4-.8 0-1.3.3-1.3 1s.5 1.1 1.4 1.1c.5 0 1.1-.3 1.4-.8z"/><path id="path4367" d="M143.8 111.3h-7.1c.1-2.9 1.9-4.2 3.8-5.4 1.3-.8 1.7-1.2 1.7-1.9 0-.8-.5-1.3-1.9-1.3-.8 0-1.8.4-2.4 1l-.9-1.1c.9-.8 2.2-1.3 3.4-1.3 2.1 0 3.4.9 3.4 2.7 0 1.5-.8 2.2-2.5 3.2-1.9 1.1-2.4 1.8-2.7 2.7h5.3v1.4z"/></g><g id="g4375"><path id="path4371" d="M198.8 93.4h-1.7v2.3h-1.4v-2.3h-2.3v2.3H192v-2.3h-1.7v-1.3h1.7v-2.7h-1.7V88h1.7v-2.3h1.4V88h2.3v-2.3h1.4V88h1.7v1.3h-1.7V92h1.7v1.4zm-3.1-1.3v-2.7h-2.3v2.7h2.3z"/><path id="path4373" d="M197.8 109.7c0 2-1.4 3.1-3.7 3.1-1.4 0-2.9-.6-3.6-1.6l1.1-1c.6.8 1.5 1.1 2.4 1.1 1.6 0 2.2-.6 2.2-1.6s-.8-1.5-1.8-1.5h-.9v-1.4h.9c.9 0 1.4-.6 1.4-1.4 0-.6-.4-1.4-1.9-1.4-.8 0-1.4.3-2 .9l-1.1-1c.8-.9 1.8-1.3 3.1-1.3 1.9 0 3.4 1 3.4 2.7 0 1.2-.5 1.8-1.2 2.2 1.1.2 1.7 1 1.7 2.2z"/></g><g id="g4381"><path id="path4377" d="M252 92.7c0 1.6-.9 2.7-2.8 2.9V97h-1.5v-1.4c-1.2-.2-2.3-.7-2.9-1.6l1.1-1c.7.8 1.6 1.1 2.5 1.1 1.4 0 2-.5 2-1.3s-.6-1.1-2.2-1.6c-2.1-.6-3.1-1.1-3.1-2.9 0-1.5 1.1-2.4 2.5-2.6v-1.5h1.5v1.5c1 .2 1.8.6 2.5 1.3l-1 1c-.7-.6-1.3-1-2.3-1-1.1 0-1.6.5-1.6 1.1 0 .7.4 1 2.1 1.5 2 .8 3.2 1.3 3.2 3.1z"/><path id="path4379" d="M252.5 110.5h-1.3v2.2h-1.4v-2.2h-5.4v-1.4l5.1-6.3h1.7v6.4h1.3v1.3zm-2.7-6.1c-.2.3-.6.8-.9 1.2L247 108c-.3.4-.7.9-.9 1.1h3.7v-2.9c-.1-.5 0-1.4 0-1.8z"/></g><g id="g4387"><path id="path4383" d="M301.2 88.7c0 1.8-1 3.1-2.5 3.1s-2.4-1.3-2.4-3.1 1-3.1 2.5-3.1c1.4 0 2.4 1.3 2.4 3.1zm-1.3 0c0-1.1-.4-1.9-1.2-1.9s-1.2.7-1.2 1.8.4 1.9 1.2 1.9 1.2-.8 1.2-1.8zm6.4-3-6.1 9.9h-1.4l6.1-9.9h1.4zm2.4 7c0 1.8-1 3.1-2.5 3.1-1.4 0-2.4-1.3-2.4-3.1s1-3.1 2.5-3.1c1.5.1 2.4 1.3 2.4 3.1zm-1.2.1c0-1.1-.4-1.9-1.2-1.9-.8 0-1.2.7-1.2 1.8s.4 1.9 1.2 1.9c.7 0 1.2-.8 1.2-1.8z"/><path id="path4385" d="M306.1 109.3c0 2.4-1.6 3.5-3.9 3.5-1.3 0-2.4-.3-3.5-1l.7-1.2c.8.5 1.9.8 2.8.8 1.5 0 2.4-.8 2.4-2s-.8-1.8-2-1.8c-.8 0-1.4.2-1.9.6l-1.6-.6.3-4.8h6.1v1.4h-4.8l-.2 2.5c.6-.3 1.2-.5 2.1-.5 2.4 0 3.5 1.3 3.5 3.1z"/></g><g id="g4393"><path id="path4389" d="M359.9 90.3h-1.6l-1.8-3-1.8 3h-1.6l2.9-4.5h1.1l2.8 4.5z"/><path id="path4391" d="M360.4 109.5c0 2.2-1.7 3.3-3.9 3.3-2.1 0-3.7-1.1-3.7-4 0-2.6 1.4-6.1 6.2-6.3v1.4c-2.3.1-3.8 1.1-4.5 3.2.7-.6 1.4-.8 2.6-.8 1.8.1 3.3 1.1 3.3 3.2zm-1.5.1c0-1.2-.8-1.7-2.3-1.7-1.4 0-2.3.6-2.3 1.7 0 1 .8 1.8 2.3 1.8 1.5 0 2.3-.7 2.3-1.8z"/></g><g id="g4399"><path id="path4395" d="M414.9 95.7h-1.7l-.8-.9c-.7.7-1.7 1.1-2.8 1.1-2.1 0-3.1-1.1-3.1-2.7 0-1.3.7-2.2 2.1-2.9l-.2-.2c-.7-.8-.9-1.4-.9-2.1 0-1.4 1.1-2.3 2.8-2.3.9 0 1.8.3 2.7.9l-.7 1.2c-.8-.6-1.3-.8-2.1-.8s-1.1.3-1.1.9c0 .4.1.7.5 1.2l2.9 3.6c.3-.5.5-1.1.7-1.6l1.3.4c-.2.8-.6 1.7-1.1 2.4l1.5 1.8zm-3.4-2-2.1-2.5c-.9.5-1.4 1-1.4 1.9 0 .8.5 1.4 1.7 1.4.7 0 1.3-.3 1.8-.8z"/><path id="path4397" d="M413.6 104.3c-1.7 1.9-3.2 4.7-3.3 8.4h-1.5c.1-3.4 1.2-6.1 3.1-8.5h-5.2v-1.4h6.9v1.5z"/></g><g id="g4405"><path id="path4401" d="m467.3 89.5-.6 1.1-1.8-1.3.2 2.2h-1.2l.2-2.2-1.8 1.3-.6-1.1 2-.9-2-.9.6-1.1 1.8 1.3-.2-2.2h1.2l-.2 2.1 1.7-1.3.6 1.1-2 .9 2.1 1z"/><path id="path4403" d="M468.4 109.8c0 2-1.5 3-3.9 3s-3.9-1.1-3.9-3c0-1.2.6-2 1.8-2.5-1-.4-1.3-1.3-1.3-1.9 0-1.9 1.5-2.8 3.5-2.8 1.8 0 3.5.9 3.5 2.8 0 .6-.3 1.5-1.3 1.9.9.4 1.6 1.2 1.6 2.5zm-1.5 0c0-1-.8-1.7-2.4-1.7-1.6 0-2.4.6-2.4 1.6s.9 1.7 2.4 1.7c1.6.1 2.4-.6 2.4-1.6zm-.4-4.4c0-.8-.5-1.5-2-1.5-1.4 0-2 .7-2 1.4 0 .8.8 1.4 2 1.4 1.3 0 2-.6 2-1.3z"/></g><g id="g4411"><path id="path4407" d="m520.3 96.6-.7.6c-1.4-1.3-2.8-3.2-2.8-5.8 0-2.7 1.3-4.5 2.8-5.9l.7.6c-1.3 1.4-2 3-2 5.2.1 2.4.8 3.9 2 5.3z"/><path id="path4409" d="M522.2 106.6c0 2.6-1.4 6.1-6.2 6.3v-1.4c2.3-.1 3.8-1.1 4.5-3.2-.7.6-1.4.8-2.6.8-1.8 0-3.3-1-3.3-3.1 0-2.2 1.7-3.3 3.9-3.3 2.1-.1 3.7 1 3.7 3.9zm-1.5-.7c0-1-.8-1.8-2.3-1.8-1.5 0-2.3.7-2.3 1.8 0 1.2.8 1.7 2.3 1.7 1.4 0 2.3-.6 2.3-1.7z"/></g><g id="g4417"><path id="path4413" d="M574.2 91.3c0 2.7-1.3 4.5-2.8 5.9l-.7-.6c1.3-1.4 2-3 2-5.2 0-2.3-.8-3.9-2-5.2l.7-.6c1.4 1.3 2.8 3.2 2.8 5.7z"/><path id="path4415" d="M576.4 107.7c0 3-1.4 5.1-3.9 5.1-2.6 0-3.9-2.1-3.9-5.1s1.4-5.1 3.9-5.1c2.6 0 3.9 2.1 3.9 5.1zm-1.5 0c0-2.1-.7-3.7-2.4-3.7s-2.4 1.6-2.4 3.7.7 3.7 2.4 3.7c1.8 0 2.4-1.6 2.4-3.7z"/></g><g id="g4423"><path id="path4419" d="M630 98.2h-7v-1.3h7.1v1.3z"/><path id="path4421" d="M628.3 108.2h-3.5v-1.4h3.5v1.4z"/></g><g id="g4429"><path id="path4425" d="M683.9 91.5h-2.7v2.8h-1.5v-2.8H677v-1.4h2.7v-2.8h1.5v2.8h2.7v1.4z"/><path id="path4427" d="M683.6 106.9h-6.1v-1.4h6.1v1.4zm0 3.2h-6.1v-1.4h6.1v1.4z"/></g><g id="g4433"><path id="path4431" d="m1088.4 93-4.4 12.5h-1.5L1087 93h1.4z"/></g><g id="g4437"><path id="path4435" d="m1136.4 98.2.7-1.2 1.9 1.4-.2-2.4h1.4l-.2 2.4 1.9-1.4.7 1.2-2.2 1 2.2 1-.7 1.2-1.9-1.4.2 2.4h-1.4l.2-2.4-1.9 1.4-.7-1.2 2.2-1-2.2-1z"/></g><g id="g4441"><path id="path4439" d="M1189.9 98.4h7.2v1.6h-7.2v-1.6z"/></g><g id="g4445"><path id="path4443" d="M117.7 153.2c0 1.7-.6 3.2-1.5 4.1l.7 1-1.2.8-.7-1c-.4.2-.9.3-1.5.3-2.6 0-4.2-2.1-4.2-5.1s1.6-5.1 4.2-5.1c2.6-.1 4.2 2 4.2 5zm-1.5 0c0-2.2-.9-3.6-2.7-3.6-1.7 0-2.7 1.4-2.7 3.6s.9 3.7 2.7 3.7c.3 0 .5 0 .7-.1l-.7-1.1 1.2-.8.7 1.1c.5-.6.8-1.6.8-2.8z"/></g><g id="g4449"><path id="path4447" d="m172.9 148.2-2 9.9h-1.5l-1.5-6.4c-.1-.3-.2-1.1-.3-1.3 0 .2-.2 1-.3 1.3l-1.6 6.4h-1.5l-2-9.9h1.5l1.2 6.3c.1.3.2 1 .2 1.3.1-.3.2-1 .3-1.3l1.6-6.3h1.3l1.6 6.4c.1.3.2.8.2 1.1.1-.4.2-.9.2-1.2l1.2-6.4h1.4z"/></g><g id="g4453"><path id="path4451" d="M225 158.2h-6.6v-9.9h6.4v1.4h-4.9v2.5h2.8v1.4h-2.8v3.1h5.1v1.5z"/></g><g id="g4457"><path id="path4455" d="M279.4 151.2c0 1.6-.8 2.6-2.2 2.9l2 4.1h-1.7l-2-3.9h-2.2v3.9h-1.5v-9.9h4.4c1.8-.1 3.2.9 3.2 2.9zm-1.5.1c0-1-.7-1.6-1.7-1.6h-2.9v3.2h2.9c1-.1 1.7-.6 1.7-1.6z"/></g><g id="g4461"><path id="path4459" d="M333.1 149.7h-2.9v8.5h-1.5v-8.5h-2.9v-1.5h7.3v1.5z"/></g><g id="g4465"><path id="path4463" d="m387.8 148.2-3.6 6v3.9h-1.5v-3.9l-3.6-6h1.7l1.5 2.7c.3.6.9 1.6 1 2 .2-.4.7-1.3 1-2l1.6-2.8h1.9z"/></g><g id="g4469"><path id="path4467" d="M441.3 154c0 2.8-1.3 4.3-3.8 4.3s-3.7-1.6-3.7-4.3v-5.8h1.5v5.7c0 1.9.8 2.9 2.3 2.9 1.6 0 2.3-1 2.3-2.8v-5.8h1.5v5.8z"/></g><g id="g4473"><path id="path4471" d="M492.2 158.2h-1.5v-9.9h1.5v9.9z"/></g><g id="g4477"><path id="path4475" d="M549.7 153.2c0 3.1-1.7 5.1-4.3 5.1-2.5 0-4.2-2-4.2-5.1s1.7-5.1 4.2-5.1c2.6 0 4.3 2 4.3 5.1zm-1.5 0c0-2.3-1.2-3.7-2.8-3.7-1.6 0-2.7 1.4-2.7 3.6s1.1 3.7 2.7 3.7c1.7.1 2.8-1.3 2.8-3.6z"/></g><g id="g4481"><path id="path4479" d="M603.5 151.4c0 2-1.4 3.1-3.3 3.1h-2.6v3.7h-1.5v-9.9h4.2c1.8-.1 3.2 1 3.2 3.1zm-1.5 0c0-1.1-.7-1.7-1.7-1.7h-2.7v3.4h2.7c1.1 0 1.7-.7 1.7-1.7z"/></g><g id="g4487"><path id="path4483" d="M655.8 151.2c-2.3 0-3.3-1-3.3-3v-.9c0-1-.2-1.2-.8-1.2h-.3v-1.3h.3c.6 0 .8-.3.8-1.2v-.9c0-2 1-3 3.3-3v1.1c-1.4.1-1.8.7-1.8 1.8v.7c0 1.3-.3 1.9-1.1 2.2.8.3 1.1.9 1.1 2.2v.7c0 1.1.4 1.7 1.8 1.8v1z"/><path id="path4485" d="M655.3 168.2h-3.1v-11.5h3.1v1.2h-1.7v9.1h1.7v1.2z"/></g><g id="g4493"><path id="path4489" d="M709.6 146.1h-.3c-.6 0-.8.3-.8 1.2v.9c0 2-1 3-3.3 3v-1.1c1.4-.1 1.8-.7 1.8-1.8v-.7c0-1.3.3-1.9 1.1-2.2-.8-.3-1.1-.9-1.1-2.2v-.7c0-1.1-.4-1.7-1.8-1.8v-1.1c2.3 0 3.3 1 3.3 3v.9c0 1 .2 1.2.8 1.2h.3v1.4z"/><path id="path4491" d="M708.8 168.2h-3.1V167h1.7v-9h-1.7v-1.2h3.1v11.4z"/></g><g id="g4499"><path id="path4495" d="M775.7 152.3h-1.3v-14h1.3v14z"/><path id="path4497" d="M777.9 168h-1.5l-4.4-12.5h1.5l4.4 12.5z"/></g><g id="g4503"><path id="path4501" d="M1034.6 149.8c-1.7 1.9-3.2 4.7-3.3 8.4h-1.5c.1-3.4 1.2-6.1 3.1-8.5h-5.2v-1.4h6.9v1.5z"/></g><g id="g4507"><path id="path4505" d="M1089.4 155.3c0 2-1.5 3-3.9 3s-3.9-1.1-3.9-3c0-1.2.6-2 1.8-2.5-1-.4-1.3-1.3-1.3-1.9 0-1.9 1.5-2.8 3.5-2.8 1.8 0 3.5.9 3.5 2.8 0 .6-.3 1.5-1.3 1.9.9.4 1.6 1.2 1.6 2.5zm-1.5 0c0-1-.8-1.7-2.4-1.7-1.6 0-2.4.6-2.4 1.6s.9 1.7 2.4 1.7c1.6.1 2.4-.6 2.4-1.6zm-.4-4.4c0-.8-.5-1.5-2-1.5-1.4 0-2 .7-2 1.4 0 .8.8 1.4 2 1.4 1.3 0 2-.6 2-1.3z"/></g><g id="g4511"><path id="path4509" d="M1143.2 152c0 2.6-1.4 6.1-6.2 6.3v-1.4c2.3-.1 3.8-1.1 4.5-3.2-.7.6-1.4.8-2.6.8-1.8 0-3.3-1-3.3-3.1 0-2.2 1.7-3.3 3.9-3.3 2.1 0 3.7 1.1 3.7 3.9zm-1.5-.6c0-1-.8-1.8-2.3-1.8-1.5 0-2.3.7-2.3 1.8 0 1.2.8 1.7 2.3 1.7 1.4 0 2.3-.6 2.3-1.7z"/></g><g id="g4515"><path id="path4513" d="M1197.3 182h-3v3h-1.6v-3h-3v-1.6h3v-3h1.6v3h3v1.6z"/></g><g id="g4519"><path id="path4517" d="M131.4 212.2h-1.6l-.8-2.4h-4l-.8 2.4h-1.5l3.6-9.9h1.6l3.5 9.9zm-2.9-3.7-.8-2.3c-.2-.7-.6-1.9-.8-2.3-.1.4-.5 1.6-.7 2.3l-.8 2.3h3.1z"/></g><g id="g4523"><path id="path4521" d="M184.5 209.3c0 1.8-1.1 3-3.7 3-1.4 0-2.7-.6-3.5-1.6l1.1-1c.7.7 1.6 1.2 2.6 1.2 1.4 0 2.1-.5 2.1-1.4 0-.8-.6-1.1-2.2-1.6-2.1-.6-3.1-1.1-3.1-2.9 0-1.7 1.4-2.8 3.3-2.8 1.3 0 2.4.5 3.2 1.3l-1 1.1c-.6-.6-1.3-.9-2.3-.9-1.2 0-1.7.6-1.7 1.2 0 .7.5 1 2.2 1.5 1.8.5 3 1.2 3 2.9z"/></g><g id="g4527"><path id="path4525" d="M239 207.2c0 3.5-2.2 5-4.8 5h-2.7v-9.9h2.7c2.7-.1 4.8 1.4 4.8 4.9zm-1.5 0c0-2.1-1-3.5-3.3-3.5H233v7h1.2c2.3 0 3.3-1.4 3.3-3.5z"/></g><g id="g4531"><path id="path4529" d="M292.6 203.7h-4.9v2.6h2.8v1.5h-2.8v4.4h-1.5v-9.9h6.4v1.4z"/></g><g id="g4535"><path id="path4533" d="M347 208.3c0 2.6-1.6 4-3.8 4-2.6 0-4.2-2.1-4.2-5.1 0-3 1.6-5.1 4.2-5.1 1.6 0 2.7.7 3.4 1.9l-1.3.8c-.5-.8-1-1.2-2.1-1.2-1.7 0-2.7 1.4-2.7 3.6s.9 3.6 2.7 3.6c1.6 0 2.3-1.1 2.3-2.2h-1.6v-1.4h3.1v1.1z"/></g><g id="g4539"><path id="path4537" d="M400.8 212.2h-1.5v-4.4h-4.6v4.4h-1.5v-9.9h1.5v4h4.6v-4h1.5v9.9z"/></g><g id="g4543"><path id="path4541" d="M454.1 208.3c0 2.7-1.1 4.1-3.5 4.1-1.9 0-3-1-3.5-2.6l1.4-.4c.4 1 1 1.6 2.1 1.6 1.4 0 2-.8 2-2.7v-5.9h1.5v5.9z"/></g><g id="g4547"><path id="path4545" d="M509.3 212.2h-1.7l-2.8-5.1-1.8 2.2v2.9h-1.4v-9.9h1.4v5.2c.2-.3.8-1.1 1.1-1.5l2.9-3.7h1.7l-2.9 3.6 3.5 6.3z"/></g><g id="g4551"><path id="path4549" d="M562.5 212.2h-6.4v-9.9h1.5v8.5h4.9v1.4z"/></g><g id="g4557"><path id="path4553" d="M614.1 197.2c0 .6-.5 1.1-1.1 1.1-.6 0-1.1-.5-1.1-1.1s.5-1.1 1.1-1.1c.6 0 1.1.5 1.1 1.1zm0 5.5c0 .6-.5 1.1-1.1 1.1-.6 0-1.1-.5-1.1-1.1s.5-1.1 1.1-1.1c.6 0 1.1.5 1.1 1.1z"/><path id="path4555" d="M614.1 214.2c0 .6-.5 1.1-1.1 1.1-.6 0-1.1-.5-1.1-1.1s.5-1.1 1.1-1.1c.6 0 1.1.5 1.1 1.1zm-.1 4.5-1.1 3.8h-1l.2-3.8h1.9z"/></g><g id="g4563"><path id="path4559" d="m666.3 193.7-.2 3.6h-1.9l1.1-3.6h1zm3.3 0-.2 3.6h-1.9l1.1-3.6h1z"/><path id="path4561" d="m668 210.8-.2 3.6h-1.9l1.1-3.6h1z"/></g><g id="g4567"><path id="path4565" d="M1035.5 209.9h-1.3v2.2h-1.4V210h-5.4v-1.4l5.1-6.3h1.7v6.4h1.3v1.2zm-2.7-6c-.2.3-.6.8-.9 1.2l-1.9 2.4c-.3.4-.7.9-.9 1.1h3.7v-2.9c-.1-.5 0-1.4 0-1.8z"/></g><g id="g4571"><path id="path4569" d="M1089.1 208.8c0 2.4-1.6 3.5-3.9 3.5-1.3 0-2.4-.3-3.5-1l.7-1.2c.8.5 1.9.8 2.8.8 1.5 0 2.4-.8 2.4-2s-.8-1.8-2-1.8c-.8 0-1.4.2-1.9.6l-1.6-.6.3-4.8h6.1v1.4h-4.8l-.2 2.5c.6-.3 1.2-.5 2.1-.5 2.4 0 3.5 1.3 3.5 3.1z"/></g><g id="g4575"><path id="path4573" d="M1143.4 209c0 2.2-1.7 3.3-3.9 3.3-2.1 0-3.7-1.1-3.7-4 0-2.6 1.4-6.1 6.2-6.3v1.4c-2.3.1-3.8 1.1-4.5 3.2.7-.6 1.4-.8 2.6-.8 1.8.1 3.3 1.1 3.3 3.2zm-1.5.1c0-1.2-.8-1.7-2.3-1.7-1.4 0-2.3.6-2.3 1.7 0 1 .8 1.8 2.3 1.8 1.5 0 2.3-.7 2.3-1.8z"/></g><g id="g4579"><path id="path4577" d="M157.7 266.2h-7.5v-1.4l4.8-5.9c.3-.4.9-1 1.1-1.3h-5.7v-1.4h7.3v1.4l-4.8 5.9c-.3.4-.9 1-1.1 1.3h5.9v1.4z"/></g><g id="g4583"><path id="path4581" d="M212 266.2h-1.8l-1.1-1.9c-.4-.6-.9-1.6-1.1-2-.2.4-.7 1.4-1.1 2l-1.1 1.9h-1.7l3.1-5.1-2.9-4.8h1.8l.9 1.6c.3.6.9 1.7 1.1 2 .2-.4.7-1.4 1.1-2l.9-1.6h1.7L209 261l3 5.2z"/></g><g id="g4587"><path id="path4585" d="M265.8 264.4c-.7 1.2-1.9 1.9-3.4 1.9-2.6 0-4.2-2.1-4.2-5.1 0-3 1.6-5.1 4.2-5.1 1.6 0 2.7.7 3.4 1.9l-1.3.8c-.5-.8-1-1.2-2.1-1.2-1.7 0-2.7 1.4-2.7 3.6s.9 3.6 2.7 3.6c1 0 1.7-.4 2.2-1.2l1.2.8z"/></g><g id="g4591"><path id="path4589" d="m320.2 256.2-3.4 9.9h-1.6l-3.4-9.9h1.6l2.1 6.3.6 1.8c.1-.4.4-1.2.6-1.8l2-6.3h1.5z"/></g><g id="g4595"><path id="path4593" d="M373.8 263.1c0 2-1.2 3-3.4 3h-3.9v-9.9h4.1c1.7 0 2.8.9 2.8 2.6 0 1-.5 1.6-1.3 2 .9.2 1.7 1 1.7 2.3zm-1.8-4.2c0-.7-.4-1.3-1.4-1.3h-2.7v2.6h2.7c1 0 1.4-.6 1.4-1.3zm.4 4.3c0-1-.6-1.6-1.8-1.6h-2.7v3.3h2.7c1.3-.1 1.8-.8 1.8-1.7z"/></g><g id="g4599"><path id="path4597" d="M427.8 266.2h-1.4l-4-6.2c-.2-.4-.6-1-.7-1.2v7.4h-1.4v-9.9h1.5l3.8 6.1c.3.4.7 1.1.8 1.4v-7.4h1.4v9.8z"/></g><g id="g4603"><path id="path4601" d="M482.4 266.2H481v-6.9c-.1.3-.4 1-.6 1.6l-2.4 5.6-2.4-5.6c-.2-.6-.5-1.3-.6-1.6v6.9h-1.4v-9.9h1.5l2.2 5.3c.2.6.6 1.3.7 1.7.1-.4.4-1.1.7-1.7l2.2-5.3h1.6v9.9z"/></g><g id="g4609"><path id="path4605" d="m534 257-4.1-3.6v-1.2l4.1-3.6v1.8l-2.8 2.4 2.8 2.4v1.8z"/><path id="path4607" d="m533 272.7-1.1 3.8h-1l.2-3.8h1.9z"/></g><g id="g4615"><path id="path4611" d="M588.1 253.4 584 257v-1.8l2.8-2.4-2.8-2.4v-1.9l4.1 3.6v1.3z"/><path id="path4613" d="M587.1 273.7c0 .6-.5 1.1-1.1 1.1s-1.1-.5-1.1-1.1.5-1.1 1.1-1.1 1.1.5 1.1 1.1z"/></g><g id="g4621"><path id="path4617" d="M643.3 250.2c0 1.4-.6 2-1.8 2.7-.9.5-1.1.9-1.1 1.9h-1.5c0-1.7.3-2.2 1.9-3.1.7-.4 1-.7 1-1.4 0-.8-.7-1.2-1.9-1.2-1 0-1.8.4-2.5 1.1l-.9-1.1c.8-.8 2-1.5 3.5-1.5 1.9 0 3.3.9 3.3 2.6zm-2.6 6.6c0 .6-.5 1.1-1.1 1.1s-1.1-.5-1.1-1.1.5-1.1 1.1-1.1 1.1.5 1.1 1.1z"/><path id="path4619" d="m642.9 263.5-4.4 12.5H637l4.4-12.5h1.5z"/></g><g id="g4625"><path id="path4623" d="M912.4 259.8c-.1.2-.2.2-.4.2l-1.2-.4v8.6h-1.7v-8.6l-1.1.4c-.2.1-.3 0-.4-.2-.1-.1-.1-.2 0-.4l2.4-3.4 2.4 3.4c.1.2.1.3 0 .4z"/></g><g id="g4629"><path id="path4627" d="M1032.6 266.2h-1.5v-7.6h-1.8v-1c1-.1 1.9-.4 2-1.3h1.2v9.9z"/></g><g id="g4633"><path id="path4631" d="M1088.8 266.2h-7.1c.1-2.9 1.9-4.2 3.8-5.4 1.3-.8 1.7-1.2 1.7-1.9 0-.8-.5-1.3-1.9-1.3-.8 0-1.8.4-2.4 1l-1-1.1c.9-.8 2.2-1.3 3.4-1.3 2.1 0 3.4.9 3.4 2.7 0 1.5-.8 2.2-2.5 3.2-1.9 1.1-2.4 1.8-2.7 2.7h5.3v1.4z"/></g><g id="g4637"><path id="path4635" d="M1142.8 263.2c0 2-1.4 3.1-3.7 3.1-1.4 0-2.9-.6-3.6-1.6l1.1-1c.6.8 1.5 1.1 2.4 1.1 1.6 0 2.2-.6 2.2-1.6s-.8-1.5-1.8-1.5h-.9v-1.4h.9c.9 0 1.4-.6 1.4-1.4 0-.6-.4-1.4-1.9-1.4-.8 0-1.4.3-2 .9l-1.1-1c.8-.9 1.8-1.3 3.1-1.3 1.9 0 3.4 1 3.4 2.7 0 1.2-.5 1.8-1.2 2.2 1.1.2 1.7 1 1.7 2.2z"/></g><g id="g4641"><path id="path4639" d="M861.2 317.2h-7.1l.4 1.1c.1.2 0 .3-.2.4-.1.1-.2.1-.4 0l-3.7-2.4 3.7-2.4c.2-.1.3-.1.4-.1.2.1.2.2.2.4l-.4 1.2h7.1v1.8z"/></g><g id="g4645"><path id="path4643" d="M912.4 318.8c.1.1.1.2-.1.4l-2.4 3.4-2.4-3.4c-.1-.2-.1-.3 0-.4.1-.2.2-.2.4-.2l1.1.4v-8.6h1.7v8.6l1.2-.3c.3-.2.4-.1.5.1z"/></g><g id="g4649"><path id="path4647" d="m969.7 316.4-3.7 2.4c-.2.1-.3.1-.4 0-.2-.1-.2-.2-.2-.4l.4-1.1h-7.1v-1.7h7.1l-.4-1.2c-.1-.2 0-.3.2-.4.1-.1.2-.1.4.1l3.7 2.3z"/></g><g id="g4653"><path id="path4651" d="M1062.4 315.2c0 3-1.4 5.1-3.9 5.1s-3.9-2.1-3.9-5.1 1.4-5.1 3.9-5.1c2.6 0 3.9 2.1 3.9 5.1zm-1.5 0c0-2.1-.7-3.7-2.4-3.7s-2.4 1.6-2.4 3.7.7 3.7 2.4 3.7c1.8 0 2.4-1.6 2.4-3.7z"/></g><g id="g4657"><path id="path4655" d="M1140.6 319.2c0 .6-.5 1.1-1.1 1.1-.6 0-1.1-.5-1.1-1.1s.5-1.1 1.1-1.1c.6 0 1.1.5 1.1 1.1z"/></g><path id="path4659" d="M32.5 19.3c1.5 0 2.8.5 3.8 1.6 1 1 1.6 2.3 1.6 3.8s-.5 2.7-1.6 3.8c-1 1.1-2.3 1.6-3.8 1.6s-2.7-.5-3.8-1.6c-1.1-1.1-1.6-2.3-1.6-3.8h1c0 1.2.4 2.2 1.3 3.1s1.9 1.3 3.1 1.3c1.2 0 2.2-.4 3.1-1.3.9-.9 1.3-1.9 1.3-3.1 0-1.2-.4-2.2-1.3-3.1-.9-.9-1.9-1.3-3.1-1.3v-1zm.4 5-.7.7-3.7-3.7-1.3 1.3v-3.4h3.4l-1.3 1.3 3.6 3.8z"/><g id="g4667"><path id="path4661" d="M28.2 44h-5.3v-8H28v1.2h-3.9v2h2.3v1.2h-2.3v2.5h4.1V44z"/><path id="path4663" d="M35 41.7c0 1.4-.9 2.4-2.9 2.4-1.2 0-2.2-.5-2.8-1.3l.9-.8c.5.6 1.3.9 2.1.9 1.1 0 1.6-.4 1.6-1.2 0-.6-.5-.9-1.8-1.3-1.7-.5-2.5-.9-2.5-2.3s1.2-2.2 2.6-2.2c1.1 0 1.9.4 2.6 1.1l-.8.9c-.5-.5-1.1-.8-1.8-.8-.9 0-1.3.5-1.3 1 0 .6.4.8 1.7 1.2 1.4.5 2.4 1 2.4 2.4z"/><path id="path4665" d="M42.5 42.6c-.6 1-1.5 1.5-2.7 1.5-2.1 0-3.4-1.7-3.4-4.1 0-2.4 1.3-4.1 3.4-4.1 1.3 0 2.2.5 2.7 1.5l-1.1.7c-.4-.6-.8-1-1.6-1-1.4 0-2.1 1.1-2.1 2.9 0 1.8.7 2.9 2.1 2.9.8 0 1.3-.3 1.7-1l1 .7z"/></g><path id="path4669" d="M860.2 20.1c.1.3.1.6.2 1 0 .4.1.9.1 1.4v.7c0 .2 0 .5-.1.7s-.1.4-.1.6-.1.3-.1.4v.1c-.2.1-.5.2-.8.3-.3.1-.6.2-1 .3-.4.1-.7.1-1.1.2-.4 0-.8.1-1.2.1-.4 0-.8 0-1.2-.1s-.8-.1-1.1-.2-.7-.2-1-.3c-.3-.1-.5-.2-.7-.3h-.1v-.1c0-.1-.1-.3-.1-.5s-.1-.4-.1-.6c0-.2-.1-.4-.1-.7v-.7c0-.5 0-1 .1-1.4s.1-.8.2-1v-.1h.1c.3-.2.8-.3 1.3-.5s1.1-.3 1.8-.3l1.1-1.1h1.4v1.2c.5.1 1 .2 1.4.3.4.1.8.3 1 .5l.1.1zm-2 .1c-.1 0-.2 0-.3-.1-.1 0-.2-.1-.3-.1v2.7H854v-2.5l.3-.3c-.4.1-.7.1-1 .2s-.5.2-.7.3l-.1.7c0 .2-.1.4-.1.7v.7c0 .4 0 .8.1 1.2s.1.6.2.9l.6.3c.2.1.5.2.8.2.3.1.6.1 1 .1h2c.3 0 .7-.1.9-.1s.6-.1.8-.2l.6-.3c.1-.2.1-.5.2-.9s.1-.7.1-1.2 0-.8-.1-1.1c0-.4-.1-.6-.2-.9-.2-.1-.4-.1-.6-.2-.2 0-.4-.1-.6-.1zm-3.9.2v2.1h3.1v-4.1h-1v2h-2.1zm.2-.2h1.6v-1.6l-1.6 1.6zm3-.2c.1 0 .1 0 0 0 .1 0 .1 0 0 0z"/><g id="g4693"><path id="path4671" d="M848.6 31.9c0 1.2-.8 1.9-2 1.9H845V36h-.9v-6h2.5c1.2 0 2 .7 2 1.9zm-.9 0c0-.7-.4-1-1-1H845v2h1.6c.7 0 1.1-.4 1.1-1z"/><path id="path4673" d="M854.2 31.8c0 1-.5 1.5-1.3 1.7l1.2 2.4h-1l-1.2-2.4h-1.3V36h-.9v-6h2.6c1.1 0 1.9.6 1.9 1.8zm-.9 0c0-.6-.4-1-1-1h-1.7v1.9h1.7c.6.1 1-.2 1-.9z"/><path id="path4675" d="M856.6 36h-.9v-6h.9v6z"/><path id="path4677" d="M862.7 36h-.8l-2.4-3.7c-.1-.2-.3-.6-.4-.7V36h-.9v-6h.9l2.3 3.6c.2.2.4.7.5.8V30h.9v6z"/><path id="path4679" d="M868.2 30.9h-1.7V36h-.9v-5.1h-1.7V30h4.4v.9z"/><path id="path4681" d="M844.1 44.5c0 1.1-.7 1.8-2.2 1.8-.9 0-1.6-.4-2.1-1l.6-.6c.4.4 1 .7 1.5.7.8 0 1.2-.3 1.2-.9 0-.5-.3-.7-1.3-1-1.3-.4-1.9-.7-1.9-1.8 0-1 .9-1.7 2-1.7.8 0 1.4.3 1.9.8l-.6.6c-.4-.4-.8-.6-1.4-.6-.7 0-1 .3-1 .7 0 .4.3.6 1.3.9 1.3.6 2 1 2 2.1z"/><path id="path4683" d="M849.7 45.1c-.4.7-1.1 1.1-2 1.1-1.5 0-2.5-1.3-2.5-3.1s1-3.1 2.5-3.1c1 0 1.6.4 2 1.1l-.8.5c-.3-.5-.6-.7-1.2-.7-1 0-1.6.8-1.6 2.2s.6 2.2 1.6 2.2c.6 0 1-.3 1.3-.7l.7.5z"/><path id="path4685" d="M855.5 42c0 1-.5 1.5-1.3 1.7l1.2 2.4h-1l-1.2-2.4h-1.3v2.4h-.9v-5.9h2.6c1 0 1.9.6 1.9 1.8zm-.9 0c0-.6-.4-1-1-1h-1.7v2h1.7c.6 0 1-.3 1-1z"/><path id="path4687" d="M860.8 46.2h-4v-5.9h3.8v.9h-2.9v1.5h1.7v.9h-1.7v1.9h3.1v.7z"/><path id="path4689" d="M866.1 46.2h-4v-5.9h3.8v.9H863v1.5h1.7v.9H863v1.9h3.1v.7z"/><path id="path4691" d="M871.9 46.2h-.9l-2.4-3.7c-.1-.2-.3-.6-.4-.7v4.5h-.9v-5.9h.9l2.3 3.6c.2.2.4.7.5.8v-4.5h.9v5.9z"/></g><path id="path4695" d="M912.7 19.8h-.9l-.5-.4v5.3l.5-.4h.9l-2.7 2.2-2.7-2.1h.9l.5.4v-5.3l-.5.4h-.9l2.7-2.1 2.7 2zm-2.1-1-.5-.4-.5.4v6.4l.5.4.5-.4v-6.4z"/><g id="g4717"><path id="path4697" d="M898.4 34.3c0 1.1-.7 1.8-2.2 1.8-.9 0-1.6-.4-2.1-1l.6-.6c.4.4 1 .7 1.5.7.8 0 1.2-.3 1.2-.9 0-.5-.3-.7-1.3-1-1.3-.4-1.9-.7-1.9-1.8 0-1 .9-1.7 2-1.7.8 0 1.4.3 1.9.8l-.6.6c-.4-.4-.8-.6-1.4-.6-.7 0-1 .3-1 .7 0 .4.3.6 1.3.9 1.2.6 2 1 2 2.1z"/><path id="path4699" d="M904 34.9c-.4.7-1.1 1.1-2 1.1-1.5 0-2.5-1.3-2.5-3.1s1-3.1 2.5-3.1c1 0 1.6.4 2 1.1l-.8.5c-.3-.5-.6-.7-1.2-.7-1 0-1.6.8-1.6 2.2s.6 2.2 1.6 2.2c.6 0 1-.3 1.3-.7l.7.5z"/><path id="path4701" d="M909.8 31.8c0 1-.5 1.5-1.3 1.7l1.2 2.4h-1l-1.2-2.4h-1.3V36h-.9v-6h2.6c1 0 1.9.6 1.9 1.8zm-.9 0c0-.6-.4-1-1-1h-1.7v1.9h1.7c.5.1 1-.2 1-.9z"/><path id="path4703" d="M915.8 33c0 1.9-1 3.1-2.5 3.1s-2.5-1.2-2.5-3.1c0-1.9 1-3.1 2.5-3.1s2.5 1.2 2.5 3.1zm-.9 0c0-1.4-.7-2.2-1.6-2.2-.9 0-1.6.8-1.6 2.2 0 1.4.7 2.2 1.6 2.2.9 0 1.6-.8 1.6-2.2z"/><path id="path4705" d="M920.9 36H917v-6h.9v5.1h3v.9z"/><path id="path4707" d="M926 36h-3.9v-6h.9v5.1h3v.9z"/><path id="path4709" d="M903.5 46.2h-3.9v-5.9h.9v5.1h3v.8z"/><path id="path4711" d="M909.2 43.2c0 1.9-1 3.1-2.5 3.1s-2.5-1.2-2.5-3.1c0-1.9 1-3.1 2.5-3.1s2.5 1.2 2.5 3.1zm-.9 0c0-1.4-.7-2.2-1.6-2.2-.9 0-1.6.8-1.6 2.2 0 1.4.7 2.2 1.6 2.2 1 0 1.6-.8 1.6-2.2z"/><path id="path4713" d="M914.8 45.1c-.4.7-1.1 1.1-2 1.1-1.5 0-2.5-1.3-2.5-3.1s1-3.1 2.5-3.1c1 0 1.6.4 2 1.1l-.8.5c-.3-.5-.6-.7-1.2-.7-1 0-1.6.8-1.6 2.2s.6 2.2 1.6 2.2c.6 0 1-.3 1.3-.7l.7.5z"/><path id="path4715" d="M920.8 46.2h-1l-1.7-3.1-1.1 1.3v1.7h-.9v-5.9h.9v3.1c.1-.2.5-.6.7-.9l1.8-2.2h1l-1.7 2.2 2 3.8z"/></g><path id="path4719" d="M961.2 22c0 .3 0 .7-.1 1-.1.3-.2.6-.4.9-.2.3-.4.5-.6.8-.2.2-.5.4-.8.6-.3.2-.6.3-.9.4-.3.1-.7.1-1 .1-.3 0-.7 0-1-.1-.3-.1-.6-.2-.9-.4-.3-.2-.5-.4-.8-.6-.2-.2-.4-.5-.6-.8-.2-.3-.3-.6-.4-.9-.1-.3-.1-.7-.1-1 0-.4 0-.7.1-1 .1-.3.2-.6.4-.9.2-.3.4-.5.6-.8.2-.2.5-.4.8-.6.3-.2.6-.3.9-.4.3-.1.7-.1 1-.1.3 0 .7 0 1 .1.3.1.6.2.9.4s.5.4.8.6c.2.2.4.5.6.8.2.3.3.6.4.9s.1.7.1 1zm-1.6.4-2.2 2.4-2.2-2.4h-.8c0 .4.1.7.3 1.1.2.3.4.6.6.8l.9.6c.3.1.7.2 1.1.2.4 0 .8-.1 1.1-.2.4-.1.7-.3.9-.6s.5-.5.6-.8c.2-.3.3-.7.3-1.1h-.6zm.8-.9c0-.4-.1-.7-.3-1-.2-.3-.4-.6-.7-.8s-.6-.4-.9-.5c-.3-.1-.7-.2-1.1-.2-.4 0-.8.1-1.1.2-.3.1-.6.3-.9.5s-.5.5-.7.8c-.2.3-.3.6-.3 1h1l1.9 2.1 1.9-2.1h1.2z"/><path id="path4721" d="M974 22c0 .3 0 .7-.1 1s-.2.6-.4.9-.4.5-.6.8c-.2.2-.5.4-.8.6-.3.2-.6.3-.9.4-.3.1-.7.1-1 .1s-.7 0-1-.1-.6-.2-.9-.4c-.3-.2-.5-.4-.8-.6-.2-.2-.4-.5-.6-.8s-.3-.6-.4-.9-.1-.7-.1-1 0-.7.1-1 .2-.6.4-.9c.2-.3.4-.5.6-.8.2-.2.5-.4.8-.6.3-.2.6-.3.9-.4.3-.1.7-.1 1-.1s.7 0 1 .1c.3.1.6.2.9.4.3.2.5.4.8.6.2.2.4.5.6.8.2.3.3.6.4.9 0 .3.1.7.1 1zm-.8 0c0-.3 0-.5-.1-.8s-.2-.5-.3-.7-.3-.4-.5-.6-.4-.3-.6-.5c-.2-.1-.5-.2-.7-.3-.3-.1-.5-.1-.8-.1-.4 0-.8.1-1.2.2-.4.2-.7.4-1 .7s-.5.6-.7 1c-.2.4-.2.8-.2 1.2s.1.8.2 1.2c.2.4.4.7.7 1s.6.5 1 .7c.4.2.8.2 1.2.2.4 0 .8-.1 1.2-.2.4-.2.7-.4 1-.7s.5-.6.7-1 .1-.9.1-1.3zm-5.7-1.4h5.4l-2.7 4.5-2.7-4.5zm4.6.5h-3.8l1.9 3.2 1.9-3.2z"/><g id="g4733"><path id="path4723" d="M955.5 32.2c0 1.2-.8 1.9-2 1.9H952v2.2h-.9v-5.9h2.5c1.1-.1 1.9.5 1.9 1.8zm-.9 0c0-.7-.4-1-1-1H952v2h1.6c.7 0 1-.4 1-1z"/><path id="path4725" d="M960.9 36.2h-1l-.5-1.4H957l-.5 1.4h-.9l2.1-5.9h.9l2.3 5.9zm-1.7-2.2-.5-1.4c-.1-.4-.4-1.1-.5-1.4-.1.3-.3.9-.4 1.4l-.5 1.4h1.9z"/><path id="path4727" d="M966.4 33.8c0 1.7-.8 2.6-2.3 2.6-1.5 0-2.2-1-2.2-2.6v-3.5h.9v3.4c0 1.1.5 1.7 1.4 1.7.9 0 1.4-.6 1.4-1.7v-3.5h.9v3.6z"/><path id="path4729" d="M971.9 34.5c0 1.1-.7 1.8-2.2 1.8-.9 0-1.6-.4-2.1-1l.6-.6c.4.4 1 .7 1.5.7.8 0 1.2-.3 1.2-.9 0-.5-.3-.7-1.3-1-1.3-.4-1.9-.7-1.9-1.8 0-1 .9-1.7 2-1.7.8 0 1.4.3 1.9.8l-.6.6c-.4-.4-.8-.6-1.4-.6-.7 0-1 .3-1 .7 0 .4.3.6 1.3.9 1.2.7 2 1.1 2 2.1z"/><path id="path4731" d="M977.2 36.2h-4v-5.9h3.8v.9h-2.9v1.5h1.7v.9h-1.7v1.9h3.1v.7z"/></g><g id="g4745"><path id="path4735" d="M954.8 44.6c0 1.2-.7 1.8-2 1.8h-2.4v-5.9h2.4c1 0 1.7.5 1.7 1.5 0 .6-.3 1-.8 1.2.6.2 1.1.6 1.1 1.4zm-1.1-2.5c0-.4-.2-.8-.8-.8h-1.6v1.5h1.6c.5.1.8-.3.8-.7zm.2 2.6c0-.6-.4-1-1.1-1h-1.6v2h1.6c.8-.1 1.1-.5 1.1-1z"/><path id="path4737" d="M960.7 42.3c0 1-.5 1.5-1.3 1.7l1.2 2.4h-1l-1.2-2.4H957v2.4h-.9v-5.9h2.6c1.1 0 2 .6 2 1.8zm-.9 0c0-.6-.4-1-1-1H957v1.9h1.7c.6.1 1.1-.2 1.1-.9z"/><path id="path4739" d="M966 46.5h-4v-5.9h3.8v.9h-2.9V43h1.7v.9h-1.7v1.9h3.1v.7z"/><path id="path4741" d="M972.1 46.5h-1l-.5-1.4h-2.4l-.5 1.4h-.9l2.1-5.9h.9l2.3 5.9zm-1.7-2.3-.5-1.4c-.1-.4-.4-1.1-.5-1.4-.1.3-.3.9-.4 1.4l-.5 1.4h1.9z"/><path id="path4743" d="M978 46.5h-1l-1.7-3.1-1.1 1.3v1.7h-.9v-5.9h.9v3.1c.1-.2.5-.6.7-.9l1.8-2.2h1l-1.7 2.2 2 3.8z"/></g><path id="path4747" d="m759.2 97.2-5.1-5.1 5.1-5.1h9.5v10.2h-9.5zm-3.7-5.1 4.1 4.1h8.1V88h-8.1l-4.1 4.1zm7.2.7-2.3 2.3-.7-.7 2.3-2.3-2.3-2.3.7-.7 2.3 2.3 2.3-2.3.7.7-2.3 2.3 2.3 2.3-.7.7-2.3-2.3z"/><g id="g4767"><path id="path4749" d="M735.4 109c0 1.6-1 2.4-2.7 2.4h-3.2v-7.9h3.3c1.4 0 2.3.7 2.3 2.1 0 .8-.4 1.3-1 1.6.6.1 1.3.7 1.3 1.8zm-1.5-3.4c0-.6-.3-1-1.1-1h-2.1v2.1h2.1c.8-.1 1.1-.6 1.1-1.1zm.3 3.4c0-.8-.5-1.3-1.4-1.3h-2.2v2.6h2.1c1.2 0 1.5-.5 1.5-1.3z"/><path id="path4751" d="M743.5 111.4h-1.3l-.7-1.9h-3.2l-.7 1.9h-1.2l2.9-7.9h1.3l2.9 7.9zm-2.3-3-.6-1.8-.6-1.8-.6 1.8-.6 1.8h2.4z"/><path id="path4753" d="M750.5 110c-.6 1-1.5 1.5-2.7 1.5-2.1 0-3.4-1.7-3.4-4.1 0-2.4 1.3-4.1 3.4-4.1 1.3 0 2.2.5 2.7 1.5l-1.1.7c-.4-.6-.8-1-1.6-1-1.4 0-2.1 1.1-2.1 2.9 0 1.8.7 2.9 2.1 2.9.8 0 1.3-.3 1.7-1l1 .7z"/><path id="path4755" d="M758.5 111.4h-1.3l-2.3-4.1-1.5 1.8v2.3h-1.2v-7.9h1.2v4.1c.1-.2.7-.9.9-1.2l2.3-2.9h1.3l-2.3 2.9 2.9 5z"/><path id="path4757" d="M764.9 109.1c0 1.4-.9 2.4-2.9 2.4-1.2 0-2.2-.5-2.8-1.3l.8-.8c.5.6 1.3.9 2.1.9 1.1 0 1.6-.4 1.6-1.2 0-.6-.5-.9-1.8-1.3-1.7-.5-2.5-.9-2.5-2.3s1.2-2.2 2.6-2.2c1.1 0 1.9.4 2.6 1.1l-.8.9c-.5-.5-1.1-.8-1.8-.8-.9 0-1.3.5-1.3 1 0 .6.4.8 1.7 1.2 1.5.5 2.5 1 2.5 2.4z"/><path id="path4759" d="M772.5 105.9c0 1.6-1.1 2.5-2.6 2.5h-2.1v3h-1.2v-7.9h3.3c1.6 0 2.6.8 2.6 2.4zm-1.2 0c0-.9-.5-1.4-1.4-1.4h-2.1v2.7h2.1c1 .1 1.4-.4 1.4-1.3z"/><path id="path4761" d="M779.8 111.4h-1.3l-.7-1.9h-3.2l-.7 1.9h-1.2l2.9-7.9h1.3l2.9 7.9zm-2.3-3-.6-1.8-.6-1.8-.6 1.8-.6 1.8h2.4z"/><path id="path4763" d="M786.8 110c-.6 1-1.5 1.5-2.7 1.5-2.1 0-3.4-1.7-3.4-4.1 0-2.4 1.3-4.1 3.4-4.1 1.3 0 2.2.5 2.7 1.5l-1.1.7c-.4-.6-.8-1-1.6-1-1.4 0-2.1 1.1-2.1 2.9 0 1.8.7 2.9 2.1 2.9.8 0 1.3-.3 1.7-1l1 .7z"/><path id="path4765" d="M793.8 111.4h-5.3v-7.9h5.1v1.2h-3.9v2h2.3v1.2h-2.3v2.5h4.1v1z"/></g><path id="path4769" d="M848.5 87.9h1.5l5.9 6.3 5.9-6.3h1.6l-7.5 7.9-7.4-7.9zm8.3 3.2c-.1-.2-.1-.4-.1-.5-.3.3-.5.5-.7.5-.2.1-.4.1-.6.1-.3 0-.6-.1-.8-.3s-.3-.5-.3-.8c0-.4.2-.7.5-.9.3-.2.9-.4 1.6-.5l.4-.1v-.4c0-.2-.1-.4-.2-.5-.2-.1-.4-.1-.6-.1-.3 0-.5.1-.6.2-.2.1-.2.3-.2.4v.1h-.7v-.1c0-.2.1-.3.2-.5s.3-.3.6-.4.5-.1.8-.1c.3 0 .5 0 .8.1.2.1.4.2.5.4.1.2.2.4.2.8v2c0 .2.1.4.1.6h-.9zm-.1-1.9h-.2c-.7.2-1.1.3-1.3.5-.2.1-.3.3-.3.5 0 .1 0 .2.1.3.1.1.1.2.2.2.1.1.2.1.3.1.2 0 .4-.1.5-.2.2-.1.3-.2.4-.4.1-.2.1-.4.1-.6v-.4z"/><g id="g4783"><path id="path4771" d="M838.3 111.2h-1.2v-7.9h1.2v7.9z"/><path id="path4773" d="M846.4 111.2h-1.1l-3.2-5c-.2-.3-.5-.8-.6-1v5.9h-1.2v-7.9h1.2l3 4.8c.2.3.5.9.7 1.1v-6h1.2v8.1z"/><path id="path4775" d="M853.8 109c0 1.4-.9 2.4-2.9 2.4-1.2 0-2.2-.5-2.8-1.3l.8-.8c.5.6 1.3.9 2.1.9 1.1 0 1.6-.4 1.6-1.2 0-.6-.5-.9-1.8-1.3-1.7-.5-2.5-.9-2.5-2.3s1.2-2.2 2.6-2.2c1.1 0 1.9.4 2.6 1.1l-.8.9c-.5-.5-1.1-.8-1.8-.8-.9 0-1.3.5-1.3 1 0 .6.4.8 1.7 1.2 1.5.5 2.5 1 2.5 2.4z"/><path id="path4777" d="M860.9 111.2h-5.3v-7.9h5.1v1.2h-3.9v2h2.3v1.2h-2.3v2.5h4.1v1z"/><path id="path4779" d="M868.6 105.7c0 1.3-.7 2.1-1.7 2.3l1.6 3.2h-1.4l-1.6-3.1h-1.8v3.1h-1.2v-7.9h3.5c1.4 0 2.6.7 2.6 2.4zm-1.2 0c0-.8-.5-1.3-1.3-1.3h-2.3v2.6h2.3c.7 0 1.3-.4 1.3-1.3z"/><path id="path4781" d="M875.5 104.5h-2.3v6.8H872v-6.8h-2.3v-1.2h5.8v1.2z"/></g><path id="path4785" d="M913.8 87.9v.5h-7.1v7.1h-.5v-7.6h7.6zm-6 2 .4-.4h2.9v.9h-1.6l4.3 4.3-.8.8-4.3-4.3v1.6h-.9v-2.9z"/><g id="g4795"><path id="path4787" d="M900.9 110.4h-1.2v-3.5H896v3.5h-1.2v-7.9h1.2v3.2h3.7v-3.2h1.2v7.9z"/><path id="path4789" d="M909.4 106.5c0 2.5-1.4 4.1-3.4 4.1s-3.4-1.6-3.4-4.1c0-2.5 1.4-4.1 3.4-4.1s3.4 1.6 3.4 4.1zm-1.2 0c0-1.8-.9-2.9-2.2-2.9-1.3 0-2.1 1.1-2.1 2.9s.9 2.9 2.2 2.9c1.2 0 2.1-1.1 2.1-2.9z"/><path id="path4791" d="M918.1 110.4H917v-5.6c-.1.2-.3.8-.5 1.2l-1.9 4.5-1.9-4.5c-.2-.5-.4-1-.5-1.2v5.6H911v-7.9h1.2l1.8 4.2c.2.5.4 1 .5 1.4.1-.3.3-.9.5-1.4l1.7-4.2h1.3v7.9z"/><path id="path4793" d="M925.5 110.4h-5.3v-7.9h5.1v1.2h-3.9v2h2.3v1.2h-2.3v2.5h4.1v1z"/></g><path id="path4797" d="M964.5 92.3h1.8v1h-1.8v1.2h1.8v1h-1.8v2.7h-1v-2.7h-1.8v-1h1.8v-1.2h-1.8v-1h1.8v-2.1H961l3-3 3 3h-2.5v2.1z"/><g id="g4807"><path id="path4799" d="M954.4 105.9c0 1.6-1.1 2.4-2.6 2.4h-2v2.9h-1.1v-7.7h3.2c1.4-.1 2.5.8 2.5 2.4zm-1.2 0c0-.9-.5-1.3-1.3-1.3h-2.1v2.7h2.1c.9-.1 1.3-.6 1.3-1.4z"/><path id="path4801" d="M961.7 108.2c0 2-1.2 3.2-2.9 3.2-2 0-3.3-1.6-3.3-4s1.3-4 3.3-4c1.3 0 2.1.5 2.6 1.4l-1 .6c-.4-.6-.8-.9-1.6-.9-1.3 0-2.1 1.1-2.1 2.8s.7 2.8 2.1 2.8c1.3 0 1.8-.8 1.8-1.7h-1.3v-1.1h2.4v.9z"/><path id="path4803" d="M972.2 108c0 2.2-1.1 3.4-3 3.4s-2.9-1.2-2.9-3.4v-4.5h1.2v4.5c0 1.5.6 2.2 1.8 2.2 1.2 0 1.8-.8 1.8-2.2v-4.5h1.2v4.5z"/><path id="path4805" d="M979.9 105.9c0 1.6-1.1 2.4-2.6 2.4h-2v2.9h-1.1v-7.7h3.2c1.4-.1 2.5.8 2.5 2.4zm-1.2 0c0-.9-.5-1.3-1.3-1.3h-2.1v2.7h2.1c.8-.1 1.3-.6 1.3-1.4z"/></g><path id="path4809" d="M1030.1 91v-3.4h-1.2l2.6-2.6 2.6 2.6h-1.2V91h1.2v2h-5.2v-2h1.2zm1.2-5-1.1 1.1h.4v4.4h-1.2v1h1.9V86zm.4 0v6.5h1.9v-1h-1.2v-4.4h.4l-1.1-1.1z"/><path id="path4811" d="M1027.3 103.2h-.8l-2.4-3.7c-.1-.2-.3-.6-.4-.7v4.5h-.9v-5.9h.9l2.3 3.6c.2.2.4.7.5.8v-4.5h.9v5.9z"/><path id="path4813" d="M1033.4 100.7c0 1.7-.8 2.6-2.3 2.6-1.5 0-2.2-1-2.2-2.6v-3.5h.9v3.4c0 1.1.5 1.7 1.4 1.7.9 0 1.4-.6 1.4-1.7v-3.5h.9v3.6z"/><path id="path4815" d="M1040.2 103.2h-.9V99c-.1.2-.2.6-.4.9l-1.4 3.3-1.4-3.3c-.1-.3-.3-.8-.4-.9v4.1h-.8v-5.9h.9l1.3 3.2c.1.3.3.8.4 1 .1-.2.3-.7.4-1l1.3-3.2h1v6z"/><path id="path4817" d="M1025 113.4h-3.9v-5.9h.9v5.1h3v.8z"/><path id="path4819" d="M1030.7 110.4c0 1.9-1 3.1-2.5 3.1s-2.5-1.2-2.5-3.1c0-1.9 1-3.1 2.5-3.1s2.5 1.2 2.5 3.1zm-.9 0c0-1.4-.7-2.2-1.6-2.2-.9 0-1.6.8-1.6 2.2 0 1.4.7 2.2 1.6 2.2 1 0 1.6-.9 1.6-2.2z"/><path id="path4821" d="M1036.3 112.3c-.4.7-1.1 1.1-2 1.1-1.5 0-2.5-1.3-2.5-3.1s1-3.1 2.5-3.1c1 0 1.6.4 2 1.1l-.8.5c-.3-.5-.6-.7-1.2-.7-1 0-1.6.8-1.6 2.2s.6 2.2 1.6 2.2c.6 0 1-.3 1.3-.7l.7.5z"/><path id="path4823" d="M1042.3 113.4h-1l-1.7-3.1-1.1 1.3v1.7h-.9v-5.9h.9v3.1c.1-.2.5-.6.7-.9l1.8-2.2h1l-1.7 2.2 2 3.8z"/><path id="path4825" d="m44.2 141.3-1.9 2h10v.9h-10l1.9 2-.5.5-3.1-2.9v2.6h-.9V141h.9v2.6l3.1-2.9.5.6zm8.1 5.5v5.4h-.9v-2.6l-3.1 2.9-.5-.5 1.9-2h-10v-.9h10l-1.9-2 .5-.5 3.1 2.9v-2.6h.9z"/><g id="g4833"><path id="path4827" d="M41.6 158.9h-2.3v6.8h-1.2v-6.8h-2.3v-1.2h5.8v1.2z"/><path id="path4829" d="M48.6 165.6h-1.3l-.7-1.9h-3.2l-.7 1.9h-1.2l2.9-7.9h1.3l2.9 7.9zm-2.3-2.9-.6-1.8-.6-1.8-.6 1.8-.6 1.8h2.4z"/><path id="path4831" d="M56 163.2c0 1.6-1 2.4-2.7 2.4h-3.2v-7.9h3.3c1.4 0 2.3.7 2.3 2.1 0 .8-.4 1.3-1 1.6.6.1 1.3.7 1.3 1.8zm-1.5-3.4c0-.6-.3-1-1.1-1h-2.1v2.1h2.1c.8-.1 1.1-.6 1.1-1.1zm.4 3.4c0-.8-.5-1.3-1.4-1.3h-2.2v2.6h2.1c1.1 0 1.5-.5 1.5-1.3z"/></g><path id="path4835" d="M858.3 151.7h-9.5v-10.2h9.5l5.1 5.1-5.1 5.1zm3.7-5.1-4.1-4.1h-8.1v8.2h8.1l4.1-4.1zm-7.2.7-2.3 2.3-.7-.7 2.3-2.3-2.3-2.3.7-.7 2.3 2.3 2.3-2.3.7.7-2.3 2.3 2.3 2.3-.7.7-2.3-2.3z"/><g id="g4843"><path id="path4837" d="M852.4 161.3c0 2.8-1.8 4-3.9 4h-2.2v-7.9h2.2c2.1 0 3.9 1.1 3.9 3.9zm-1.3 0c0-1.7-.8-2.8-2.7-2.8h-1v5.6h1c2 .1 2.7-1.1 2.7-2.8z"/><path id="path4839" d="M859.3 165.3H854v-7.9h5.1v1.2h-3.9v2h2.3v1.2h-2.3v2.5h4.1v1z"/><path id="path4841" d="M866.1 165.3H861v-7.9h1.2v6.8h4v1.1z"/></g><path id="path4845" d="M911.8 148.6h-2.9v-.9h1.6l-4.3-4.3.8-.8 4.3 4.3v-1.6h.9v2.9l-.4.4zm2-5.9v7.6h-7.6v-.5h7.1v-7.1h.5z"/><g id="g4853"><path id="path4847" d="M904.9 165.3h-5.3v-7.9h5.1v1.2h-3.9v2h2.3v1.2h-2.3v2.5h4.1v1z"/><path id="path4849" d="M912.7 165.3h-1.1l-3.2-5c-.2-.3-.5-.8-.6-1v5.9h-1.2v-7.9h1.2l3 4.8c.2.3.5.9.7 1.1v-6h1.2v8.1z"/><path id="path4851" d="M920.7 161.3c0 2.8-1.8 4-3.9 4h-2.2v-7.9h2.2c2.2 0 3.9 1.1 3.9 3.9zm-1.2 0c0-1.7-.8-2.8-2.7-2.8h-1v5.6h1c2 .1 2.7-1.1 2.7-2.8z"/></g><path id="path4855" d="M963.5 147.4h-1.8v-1h1.8v-1.2h-1.8v-1h1.8v-2.7h1v2.7h1.8v1h-1.8v1.2h1.8v1h-1.8v2.1h2.5l-3 3-3-3h2.5v-2.1z"/><g id="g4865"><path id="path4857" d="M953.9 159.9c0 1.6-1.1 2.5-2.6 2.5h-2.1v3H948v-7.9h3.3c1.5-.1 2.6.7 2.6 2.4zm-1.2 0c0-.9-.5-1.4-1.4-1.4h-2.1v2.7h2.1c1 0 1.4-.5 1.4-1.3z"/><path id="path4859" d="M961.5 162.2c0 2-1.2 3.2-3 3.2-2.1 0-3.4-1.7-3.4-4.1 0-2.4 1.3-4.1 3.4-4.1 1.3 0 2.2.5 2.7 1.5l-1 .6c-.4-.6-.8-.9-1.7-.9-1.4 0-2.1 1.1-2.1 2.9 0 1.8.8 2.9 2.1 2.9s1.8-.9 1.8-1.8H959v-1.1h2.5v.9z"/><path id="path4861" d="M972.2 161.3c0 2.8-1.8 4-3.9 4h-2.2v-7.9h2.2c2.2 0 3.9 1.1 3.9 3.9zm-1.2 0c0-1.7-.8-2.8-2.7-2.8h-1v5.6h1c2 .1 2.7-1.1 2.7-2.8z"/><path id="path4863" d="M979.9 165.3h-1.1l-3.2-5c-.2-.3-.5-.8-.6-1v5.9h-1.2v-7.9h1.2l3 4.8c.2.3.5.9.7 1.1v-6h1.2v8.1z"/></g><path id="path4867" d="m47.2 200.4 5.6-5.6 5.6 5.6h-2.8v2.1H50v-2.1h-2.8zm5.6-4.4-3.7 3.7h1.7v2h4v-2h1.7l-3.7-3.7zm-2.8 8.1h5.6v2.8H50v-2.8zm.8.8v1.2h4v-1.2h-4z"/><g id="g4885"><path id="path4869" d="M28.3 218.2c-.6 1-1.5 1.5-2.7 1.5-2.1 0-3.4-1.7-3.4-4.1s1.3-4.1 3.4-4.1c1.3 0 2.2.5 2.7 1.5l-1.1.7c-.4-.6-.8-1-1.6-1-1.4 0-2.1 1.1-2.1 2.9 0 1.8.7 2.9 2.1 2.9.8 0 1.3-.3 1.7-1l1 .7z"/><path id="path4871" d="M36.3 219.5H35l-.7-1.9h-3.2l-.7 1.9h-1.2l2.9-7.9h1.3l2.9 7.9zm-2.3-2.9-.6-1.8-.6-1.8-.6 1.8-.6 1.8H34z"/><path id="path4873" d="M43.7 214.1c0 1.6-1.1 2.5-2.6 2.5H39v3h-1.2v-7.9h3.3c1.6-.1 2.6.8 2.6 2.4zm-1.2 0c0-.9-.5-1.4-1.4-1.4H39v2.7h2.1c1 .1 1.4-.5 1.4-1.3z"/><path id="path4875" d="M50.5 217.3c0 1.4-.9 2.4-2.9 2.4-1.2 0-2.2-.5-2.8-1.3l.9-.8c.5.6 1.3.9 2.1.9 1.1 0 1.6-.4 1.6-1.2 0-.6-.5-.9-1.8-1.3-1.7-.5-2.5-.9-2.5-2.3s1.2-2.2 2.6-2.2c1.1 0 1.9.4 2.6 1.1l-.8.8c-.5-.5-1.1-.8-1.8-.8-.9 0-1.3.5-1.3 1 0 .6.4.8 1.7 1.2 1.4.6 2.4 1.1 2.4 2.5z"/><path id="path4877" d="M60.5 219.5h-5.1v-7.9h1.2v6.8h4v1.1z"/><path id="path4879" d="M68.1 215.6c0 2.5-1.4 4.1-3.4 4.1s-3.4-1.6-3.4-4.1 1.4-4.1 3.4-4.1c2.1 0 3.4 1.6 3.4 4.1zm-1.2 0c0-1.8-.9-2.9-2.2-2.9-1.3 0-2.1 1.1-2.1 2.9s.9 2.9 2.2 2.9c1.2 0 2.1-1.1 2.1-2.9z"/><path id="path4881" d="M75.5 218.2c-.6 1-1.5 1.5-2.7 1.5-2.1 0-3.4-1.7-3.4-4.1s1.3-4.1 3.4-4.1c1.3 0 2.2.5 2.7 1.5l-1.1.7c-.4-.6-.8-1-1.6-1-1.4 0-2.1 1.1-2.1 2.9 0 1.8.7 2.9 2.1 2.9.8 0 1.3-.3 1.7-1l1 .7z"/><path id="path4883" d="M83.5 219.5h-1.3l-2.3-4.1-1.5 1.8v2.3h-1.2v-7.9h1.2v4.1c.1-.2.7-.9.9-1.2l2.3-2.9H83l-2.3 2.9 2.8 5z"/></g><path id="path4887" d="m748.9 200.5 3-3v2.5h7.1v-4.4h-3.5v-1h4.6v6.4H752v2.5l-3.1-3z"/><g id="g4901"><path id="path4889" d="M739 214.2c0 1.3-.7 2.1-1.7 2.3l1.6 3.2h-1.4l-1.6-3.1h-1.8v3.1h-1.2v-7.9h3.5c1.4 0 2.6.8 2.6 2.4zm-1.2.1c0-.8-.5-1.3-1.3-1.3h-2.3v2.6h2.3c.7-.1 1.3-.5 1.3-1.3z"/><path id="path4891" d="M746.1 219.8h-5.3v-7.9h5.1v1.2H742v2h2.3v1.2H742v2.5h4.1v1z"/><path id="path4893" d="M753.1 213h-2.3v6.8h-1.2V213h-2.3v-1.2h5.8v1.2z"/><path id="path4895" d="M760.6 216.5c0 2.2-1.1 3.4-3 3.4-2 0-3-1.3-3-3.5v-4.6h1.2v4.6c0 1.5.6 2.3 1.8 2.3 1.2 0 1.8-.8 1.8-2.2v-4.6h1.2v4.6z"/><path id="path4897" d="M768.7 214.2c0 1.3-.7 2.1-1.7 2.3l1.6 3.2h-1.4l-1.6-3.1h-1.8v3.1h-1.2v-7.9h3.5c1.4 0 2.6.8 2.6 2.4zm-1.2.1c0-.8-.5-1.3-1.3-1.3h-2.3v2.6h2.3c.7-.1 1.3-.5 1.3-1.3z"/><path id="path4899" d="M776.6 219.8h-1.1l-3.2-5c-.2-.3-.5-.8-.6-1v5.9h-1.2v-7.9h1.2l3 4.8c.2.3.5.9.7 1.1v-6h1.2v8.1z"/></g><path id="path4903" d="m60.4 254.4 5.9-5.9 5.9 5.9h-2.9v5.2h-5.9v-5.2h-3zm5.8-4.6-3.9 3.9h1.8v5.1h4.2v-5.1h1.8l-3.9-3.9z"/><g id="g4915"><path id="path4905" d="M56.6 271.5c0 1.4-.9 2.4-2.9 2.4-1.2 0-2.2-.5-2.8-1.3l.9-.8c.5.6 1.3.9 2.1.9 1.1 0 1.6-.4 1.6-1.2 0-.6-.5-.9-1.8-1.3-1.7-.5-2.5-.9-2.5-2.3s1.2-2.2 2.6-2.2c1.1 0 1.9.4 2.6 1.1l-.8.8c-.5-.5-1.1-.8-1.8-.8-.9 0-1.3.5-1.3 1 0 .6.4.8 1.7 1.2 1.4.6 2.4 1.1 2.4 2.5z"/><path id="path4907" d="M64.4 273.8h-1.2v-3.5h-3.7v3.5h-1.2v-7.9h1.2v3.2h3.7v-3.2h1.2v7.9z"/><path id="path4909" d="M67.7 273.8h-1.2v-7.9h1.2v7.9z"/><path id="path4911" d="M74.9 267.1H71v2.1h2.3v1.2H71v3.5h-1.2V266h5.1v1.1z"/><path id="path4913" d="M81.7 267.1h-2.3v6.8h-1.2v-6.8h-2.3v-1.2h5.8v1.2z"/></g><path id="path4917" d="m735.4 254.4 5.9-5.9 5.9 5.9h-2.9v5.2h-5.9v-5.2h-3zm5.8-4.6-3.9 3.9h1.8v5.1h4.2v-5.1h1.8l-3.9-3.9z"/><g id="g4929"><path id="path4919" d="M731.6 271.5c0 1.4-.9 2.4-2.9 2.4-1.2 0-2.2-.5-2.8-1.3l.8-.8c.5.6 1.3.9 2.1.9 1.1 0 1.6-.4 1.6-1.2 0-.6-.5-.9-1.8-1.3-1.7-.5-2.5-.9-2.5-2.3s1.2-2.2 2.6-2.2c1.1 0 1.9.4 2.6 1.1l-.8.8c-.5-.5-1.1-.8-1.8-.8-.9 0-1.3.5-1.3 1 0 .6.4.8 1.7 1.2 1.5.6 2.5 1.1 2.5 2.5z"/><path id="path4921" d="M739.4 273.8h-1.2v-3.5h-3.7v3.5h-1.2v-7.9h1.2v3.2h3.7v-3.2h1.2v7.9z"/><path id="path4923" d="M742.7 273.8h-1.2v-7.9h1.2v7.9z"/><path id="path4925" d="M749.9 267.1H746v2.1h2.3v1.2H746v3.5h-1.2V266h5.1v1.1z"/><path id="path4927" d="M756.7 267.1h-2.3v6.8h-1.2v-6.8h-2.3v-1.2h5.8v1.2z"/></g><path id="path4931" d="m1188.1 291.5 5.4-5.4 5.4 5.4-1 1-4.5-4.5-4.4 4.5-.9-1zm3.1-5.4v1.4h-3.2v-1.4h3.2zm7.7 0v1.4h-3.2v-1.4h3.2z"/><g id="g4943"><path id="path4933" d="M1181.4 326.4h-5.3v-7.9h5.1v1.2h-3.9v2h2.3v1.2h-2.3v2.5h4.1v1z"/><path id="path4935" d="M1189.1 326.4h-1.1l-3.2-5c-.2-.3-.5-.8-.6-1v5.9h-1.2v-7.9h1.2l3 4.8c.2.3.5.9.7 1.1v-6h1.2v8.1z"/><path id="path4937" d="M1196.5 319.7h-2.3v6.8h-1.2v-6.8h-2.3v-1.2h5.8v1.2z"/><path id="path4939" d="M1203.4 326.4h-5.3v-7.9h5.1v1.2h-3.9v2h2.3v1.2h-2.3v2.5h4.1v1z"/><path id="path4941" d="M1211.1 320.9c0 1.3-.7 2.1-1.7 2.3l1.6 3.2h-1.4l-1.6-3.1h-1.8v3.1h-1.2v-7.9h3.5c1.4 0 2.6.7 2.6 2.4zm-1.2 0c0-.8-.5-1.3-1.3-1.3h-2.3v2.6h2.3c.7 0 1.3-.4 1.3-1.3z"/></g><g id="g4959"><path id="path4945" d="M19.7 325c-.6 1-1.5 1.5-2.7 1.5-2.1 0-3.4-1.7-3.4-4.1s1.3-4.1 3.4-4.1c1.3 0 2.2.5 2.7 1.5l-1.1.7c-.4-.6-.8-1-1.6-1-1.4 0-2.1 1.1-2.1 2.9 0 1.8.7 2.9 2.1 2.9.8 0 1.3-.3 1.7-1l1 .7z"/><path id="path4947" d="M27.5 322.5c0 2.5-1.4 4.1-3.4 4.1s-3.4-1.6-3.4-4.1 1.4-4.1 3.4-4.1 3.4 1.6 3.4 4.1zm-1.2 0c0-1.8-.9-2.9-2.2-2.9-1.3 0-2.1 1.1-2.1 2.9s.9 2.9 2.2 2.9c1.2 0 2.1-1.1 2.1-2.9z"/><path id="path4949" d="M35.2 326.4h-1.1l-3.2-5c-.2-.3-.5-.8-.6-1v5.9h-1.2v-7.9h1.2l3 4.8c.2.3.5.9.7 1.1v-6h1.2v8.1z"/><path id="path4951" d="M42.6 319.7h-2.3v6.8h-1.2v-6.8h-2.3v-1.2h5.8v1.2z"/><path id="path4953" d="M50.2 320.9c0 1.3-.7 2.1-1.7 2.3l1.6 3.2h-1.4l-1.6-3.1h-1.8v3.1h-1.2v-7.9h3.5c1.4 0 2.6.7 2.6 2.4zm-1.2 0c0-.8-.5-1.3-1.3-1.3h-2.3v2.6h2.3c.7 0 1.3-.4 1.3-1.3z"/><path id="path4955" d="M58.2 322.5c0 2.5-1.4 4.1-3.4 4.1s-3.4-1.6-3.4-4.1 1.4-4.1 3.4-4.1 3.4 1.6 3.4 4.1zm-1.2 0c0-1.8-.9-2.9-2.2-2.9-1.3 0-2.1 1.1-2.1 2.9s.9 2.9 2.2 2.9c1.2 0 2.1-1.1 2.1-2.9z"/><path id="path4957" d="M65 326.4h-5.1v-7.9h1.2v6.8h4v1.1z"/></g><path id="path4961" d="M111 302.8v8.8h-8.7v-8.8h8.7zm-4.8 4v-3.2H103v3.2h3.2zm0 .8H103v3.2h3.2v-3.2zm.8-.8h3.3v-3.3H107v3.3zm0 .8v3.2h3.3v-3.2H107z"/><g id="g4969"><path id="path4963" d="m105.3 318.5-1.6 7.9h-1.2l-1.2-5.1c-.1-.3-.2-.9-.2-1.1 0 .2-.2.8-.2 1.1l-1.3 5.1h-1.2l-1.6-7.9H98l1 5c0 .2.1.8.2 1 0-.3.2-.8.2-1l1.3-5h1l1.3 5.1c.1.2.1.6.2.9.1-.3.1-.7.2-.9l1-5.1h.9z"/><path id="path4965" d="M108.2 326.4H107v-7.9h1.2v7.9z"/><path id="path4967" d="M116.3 326.4h-1.1l-3.2-5c-.2-.3-.5-.8-.6-1v5.9h-1.2v-7.9h1.2l3 4.8c.2.3.5.9.7 1.1v-6h1.2v8.1z"/></g><path id="path4971" d="M180.1 302v1H177l-4.6 9.2h-4v-1h3.2l4.6-9.2h3.9zm-4.7 10.3v-1h4.8v1h-4.8z"/><g id="g4979"><path id="path4973" d="M171.6 326.4h-1.3l-.7-1.9h-3.2l-.7 1.9h-1.2l2.9-7.9h1.3l2.9 7.9zm-2.3-2.9-.6-1.8-.6-1.8-.6 1.8-.6 1.8h2.4z"/><path id="path4975" d="M178.4 326.4h-5.1v-7.9h1.2v6.8h4v1.1z"/><path id="path4977" d="M183.9 319.7h-2.3v6.8h-1.2v-6.8H178v-1.2h5.8v1.2z"/></g><path id="path4981" d="M374.8 309.2v-2h.7v1.4h2.6v-1.4h.7v2h-4z"/><g id="g4993"><path id="path4983" d="M365.1 324.2c0 1.4-.9 2.4-2.9 2.4-1.2 0-2.2-.5-2.8-1.3l.9-.8c.5.6 1.3.9 2.1.9 1.1 0 1.6-.4 1.6-1.2 0-.6-.5-.9-1.8-1.3-1.7-.5-2.5-.9-2.5-2.3s1.2-2.2 2.6-2.2c1.1 0 1.9.4 2.6 1.1l-.8.8c-.5-.5-1.1-.8-1.8-.8-.9 0-1.3.5-1.3 1 0 .6.4.8 1.7 1.2 1.5.5 2.4 1 2.4 2.5z"/><path id="path4985" d="M372.8 321c0 1.6-1.1 2.5-2.6 2.5h-2.1v3h-1.2v-7.9h3.3c1.5-.1 2.6.7 2.6 2.4zm-1.2 0c0-.9-.5-1.4-1.4-1.4h-2.1v2.7h2.1c.9.1 1.4-.5 1.4-1.3z"/><path id="path4987" d="M380 326.4h-1.3l-.7-1.9h-3.2l-.7 1.9H373l2.9-7.9h1.3l2.8 7.9zm-2.3-2.9-.6-1.8-.6-1.8-.6 1.8-.6 1.8h2.4z"/><path id="path4989" d="M387.1 325c-.6 1-1.5 1.5-2.7 1.5-2.1 0-3.4-1.7-3.4-4.1s1.3-4.1 3.4-4.1c1.3 0 2.2.5 2.7 1.5l-1.1.7c-.4-.6-.8-1-1.6-1-1.4 0-2.1 1.1-2.1 2.9 0 1.8.7 2.9 2.1 2.9.8 0 1.3-.3 1.7-1l1 .7z"/><path id="path4991" d="M394.1 326.4h-5.3v-7.9h5.1v1.2H390v2h2.3v1.2H390v2.5h4.1v1z"/></g><path id="path4995" d="M573.4 311.2h3.2l4.6-9.2h4v1H582l-4.6 9.2h-4v-1zm7 0h4.8v1h-4.8v-1z"/><g id="g5003"><path id="path4997" d="M576.7 326.4h-1.3l-.7-1.9h-3.2l-.7 1.9h-1.2l2.9-7.9h1.3l2.9 7.9zm-2.3-2.9-.6-1.8-.6-1.8-.6 1.8-.6 1.8h2.4z"/><path id="path4999" d="M583.4 326.4h-5.1v-7.9h1.2v6.8h4v1.1z"/><path id="path5001" d="M588.9 319.7h-2.3v6.8h-1.2v-6.8H583v-1.2h5.8v1.2z"/></g><path id="path5005" d="M651.1 302.8v8.8h-8.7v-8.8h8.7zm-4.8 4v-3.2h-3.2v3.2h3.2zm0 .8h-3.2v3.2h3.2v-3.2zm.8-.8h3.3v-3.3h-3.3v3.3zm0 .8v3.2h3.3v-3.2h-3.3z"/><g id="g5013"><path id="path5007" d="m645.3 318.5-1.6 7.9h-1.2l-1.2-5.1c-.1-.3-.2-.9-.2-1.1 0 .2-.2.8-.2 1.1l-1.3 5.1h-1.2l-1.6-7.9h1.2l1 5c0 .2.1.8.2 1 0-.3.2-.8.2-1l1.3-5h1l1.3 5.1c.1.2.1.6.2.9.1-.3.1-.7.2-.9l1-5.1h.9z"/><path id="path5009" d="M648.2 326.4H647v-7.9h1.2v7.9z"/><path id="path5011" d="M656.3 326.4h-1.1l-3.2-5c-.2-.3-.5-.8-.6-1v5.9h-1.2v-7.9h1.2l3 4.8c.2.3.5.9.7 1.1v-6h1.2v8.1z"/></g><path id="path5015" d="M710.6 303.4h7.3v1.2h-7.3v-1.2zm0 2.5h7.3v1.2h-7.3v-1.2zm0 2.5h7.3v1.2h-7.3v-1.2zm0 2.5h7.3v1.2h-7.3v-1.2z"/><g id="g5025"><path id="path5017" d="M706.3 326.3h-1.2v-5.6c-.1.2-.3.8-.5 1.2l-1.9 4.5-1.9-4.5c-.2-.5-.4-1-.5-1.2v5.6h-1.1v-7.9h1.2l1.8 4.2c.2.5.4 1 .5 1.4.1-.3.3-.9.5-1.4l1.7-4.2h1.3v7.9z"/><path id="path5019" d="M713.6 326.3h-5.3v-7.9h5.1v1.2h-3.9v2h2.3v1.2h-2.3v2.5h4.1v1z"/><path id="path5021" d="M721.3 326.3h-1.1l-3.2-5c-.2-.3-.5-.8-.6-1v5.9h-1.2v-7.9h1.2l3 4.8c.2.3.5.9.7 1.1v-6h1.2v8.1z"/><path id="path5023" d="M729.4 323c0 2.2-1.1 3.4-3 3.4-2 0-3-1.3-3-3.5v-4.6h1.2v4.6c0 1.5.6 2.3 1.8 2.3 1.2 0 1.8-.8 1.8-2.2v-4.6h1.2v4.6z"/></g><path id="path5027" d="M781.2 313.6v-1.4c-1.5-.2-2.7-.9-3.6-2.1l-1.2.7-.5-.9 1.2-.7c-.3-.7-.4-1.4-.4-2.1 0-.7.1-1.4.4-2.1l-1.2-.7.5-.9 1.2.7c.9-1.2 2.1-1.9 3.6-2.1v-1.4h1v1.4c1.5.2 2.7.9 3.6 2.1l1.2-.7.5.9-1.2.7c.3.7.5 1.4.5 2.1 0 .7-.2 1.4-.5 2.1l1.2.7-.5.9-1.2-.7c-.9 1.2-2.1 1.9-3.6 2.1v1.4h-1zm-3.2-8c-.2.5-.3 1-.3 1.6 0 .5.1 1.1.3 1.6l2.8-1.6-2.8-1.6zm3.2-2.5c-1.1.1-2 .7-2.7 1.6l2.8 1.6v-3.2zm-2.7 6.5c.7.9 1.6 1.4 2.7 1.6V308l-2.7 1.6zm6.5-4.9c-.7-.9-1.6-1.4-2.7-1.6v3.2l2.7-1.6zm-2.7 6.5c1.1-.1 2-.7 2.7-1.6l-2.8-1.6v3.2zm3.2-2.5c.2-.5.3-1 .3-1.6 0-.5-.1-1.1-.3-1.6l-2.8 1.6 2.8 1.6z"/><path id="path5029" d="M38.7 313.6v-1.4c-1.5-.2-2.7-.9-3.6-2.1l-1.2.7-.5-.9 1.2-.7c-.3-.7-.4-1.4-.4-2.1 0-.7.1-1.4.4-2.1l-1.2-.7.5-.9 1.2.7c.9-1.2 2.1-1.9 3.6-2.1v-1.4h1v1.4c1.5.2 2.7.9 3.6 2.1l1.2-.7.5.9-1.2.7c.3.7.5 1.4.5 2.1 0 .7-.2 1.4-.5 2.1l1.2.7-.5.9-1.2-.7c-.9 1.2-2.1 1.9-3.6 2.1v1.4h-1zm-3.2-8c-.2.5-.3 1-.3 1.6 0 .5.1 1.1.3 1.6l2.8-1.6-2.8-1.6zm3.2-2.5c-1.1.1-2 .7-2.7 1.6l2.8 1.6v-3.2zm-2.7 6.5c.7.9 1.6 1.4 2.7 1.6V308l-2.7 1.6zm6.5-4.9c-.7-.9-1.6-1.4-2.7-1.6v3.2l2.7-1.6zm-2.7 6.5c1.1-.1 2-.7 2.7-1.6l-2.8-1.6v3.2zm3.2-2.5c.2-.5.3-1 .3-1.6 0-.5-.1-1.1-.3-1.6l-2.8 1.6 2.8 1.6z"/><g id="g5045"><path id="path5031" d="M762.2 325c-.6 1-1.5 1.5-2.7 1.5-2.1 0-3.4-1.7-3.4-4.1s1.3-4.1 3.4-4.1c1.3 0 2.2.5 2.7 1.5l-1.1.7c-.4-.6-.8-1-1.6-1-1.4 0-2.1 1.1-2.1 2.9 0 1.8.7 2.9 2.1 2.9.8 0 1.3-.3 1.7-1l1 .7z"/><path id="path5033" d="M770 322.5c0 2.5-1.4 4.1-3.4 4.1s-3.4-1.6-3.4-4.1 1.4-4.1 3.4-4.1 3.4 1.6 3.4 4.1zm-1.2 0c0-1.8-.9-2.9-2.2-2.9-1.3 0-2.1 1.1-2.1 2.9s.9 2.9 2.2 2.9c1.2 0 2.1-1.1 2.1-2.9z"/><path id="path5035" d="M777.7 326.4h-1.1l-3.2-5c-.2-.3-.5-.8-.6-1v5.9h-1.2v-7.9h1.2l3 4.8c.2.3.5.9.7 1.1v-6h1.2v8.1z"/><path id="path5037" d="M785.1 319.7h-2.3v6.8h-1.2v-6.8h-2.3v-1.2h5.8v1.2z"/><path id="path5039" d="M792.7 320.9c0 1.3-.7 2.1-1.7 2.3l1.6 3.2h-1.4l-1.6-3.1h-1.8v3.1h-1.2v-7.9h3.5c1.4 0 2.6.7 2.6 2.4zm-1.2 0c0-.8-.5-1.3-1.3-1.3h-2.3v2.6h2.3c.7 0 1.3-.4 1.3-1.3z"/><path id="path5041" d="M800.7 322.5c0 2.5-1.4 4.1-3.4 4.1s-3.4-1.6-3.4-4.1 1.4-4.1 3.4-4.1 3.4 1.6 3.4 4.1zm-1.2 0c0-1.8-.9-2.9-2.2-2.9-1.3 0-2.1 1.1-2.1 2.9s.9 2.9 2.2 2.9c1.2 0 2.1-1.1 2.1-2.9z"/><path id="path5043" d="M807.5 326.4h-5.1v-7.9h1.2v6.8h4v1.1z"/></g></g><ellipse id="path5133" cx="86.103" cy="100.186" rx="33.559" ry="32.483" style="fill:none;stroke:red;stroke-width:5.3111;stroke-linecap:round;stroke-linejoin:round"/><path id="path5285" d="m190.095 117.617-48.107 13.104 12.219 44.855L164.2 158.1l54.895 31.391 12.813-22.407-53.153-30.396z" style="fill:#fe7777;fill-opacity:1;stroke:red;stroke-width:2.7008;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1"/></svg> \ No newline at end of file diff --git a/app/vendor/rune/vendor/winit/examples/child_window.rs b/app/vendor/rune/vendor/winit/examples/child_window.rs new file mode 100644 index 0000000..715996e --- /dev/null +++ b/app/vendor/rune/vendor/winit/examples/child_window.rs @@ -0,0 +1,88 @@ +#[cfg(all(feature = "rwh_06", any(x11_platform, macos_platform, windows_platform)))] +#[allow(deprecated)] +fn main() -> Result<(), impl std::error::Error> { + use std::collections::HashMap; + + use winit::dpi::{LogicalPosition, LogicalSize, Position}; + use winit::event::{ElementState, Event, KeyEvent, WindowEvent}; + use winit::event_loop::{ActiveEventLoop, EventLoop}; + use winit::raw_window_handle::HasRawWindowHandle; + use winit::window::Window; + + #[path = "util/fill.rs"] + mod fill; + + fn spawn_child_window(parent: &Window, event_loop: &ActiveEventLoop) -> Window { + let parent = parent.raw_window_handle().unwrap(); + let mut window_attributes = Window::default_attributes() + .with_title("child window") + .with_inner_size(LogicalSize::new(200.0f32, 200.0f32)) + .with_position(Position::Logical(LogicalPosition::new(0.0, 0.0))) + .with_visible(true); + // `with_parent_window` is unsafe. Parent window must be a valid window. + window_attributes = unsafe { window_attributes.with_parent_window(Some(parent)) }; + + event_loop.create_window(window_attributes).unwrap() + } + + let mut windows = HashMap::new(); + + let event_loop: EventLoop<()> = EventLoop::new().unwrap(); + let mut parent_window_id = None; + + event_loop.run(move |event: Event<()>, event_loop| { + match event { + Event::Resumed => { + let attributes = Window::default_attributes() + .with_title("parent window") + .with_position(Position::Logical(LogicalPosition::new(0.0, 0.0))) + .with_inner_size(LogicalSize::new(640.0f32, 480.0f32)); + let window = event_loop.create_window(attributes).unwrap(); + + parent_window_id = Some(window.id()); + + println!("Parent window id: {parent_window_id:?})"); + windows.insert(window.id(), window); + }, + Event::WindowEvent { window_id, event } => match event { + WindowEvent::CloseRequested => { + windows.clear(); + event_loop.exit(); + }, + WindowEvent::CursorEntered { device_id: _ } => { + // On x11, println when the cursor entered in a window even if the child window + // is created by some key inputs. + // the child windows are always placed at (0, 0) with size (200, 200) in the + // parent window, so we also can see this log when we move + // the cursor around (200, 200) in parent window. + println!("cursor entered in the window {window_id:?}"); + }, + WindowEvent::KeyboardInput { + event: KeyEvent { state: ElementState::Pressed, .. }, + .. + } => { + let parent_window = windows.get(&parent_window_id.unwrap()).unwrap(); + let child_window = spawn_child_window(parent_window, event_loop); + let child_id = child_window.id(); + println!("Child window created with id: {child_id:?}"); + windows.insert(child_id, child_window); + }, + WindowEvent::RedrawRequested => { + if let Some(window) = windows.get(&window_id) { + fill::fill_window(window); + } + }, + _ => (), + }, + _ => (), + } + }) +} + +#[cfg(all(feature = "rwh_06", not(any(x11_platform, macos_platform, windows_platform))))] +fn main() { + panic!( + "This example is supported only on x11, macOS, and Windows, with the `rwh_06` feature \ + enabled." + ); +} diff --git a/app/vendor/rune/vendor/winit/examples/control_flow.rs b/app/vendor/rune/vendor/winit/examples/control_flow.rs new file mode 100644 index 0000000..13cc947 --- /dev/null +++ b/app/vendor/rune/vendor/winit/examples/control_flow.rs @@ -0,0 +1,148 @@ +#![allow(clippy::single_match)] + +use std::thread; +#[cfg(not(web_platform))] +use std::time; + +use ::tracing::{info, warn}; +#[cfg(web_platform)] +use web_time as time; + +use winit::application::ApplicationHandler; +use winit::event::{ElementState, KeyEvent, StartCause, WindowEvent}; +use winit::event_loop::{ActiveEventLoop, ControlFlow, EventLoop}; +use winit::keyboard::{Key, NamedKey}; +use winit::window::{Window, WindowId}; + +#[path = "util/fill.rs"] +mod fill; +#[path = "util/tracing.rs"] +mod tracing; + +const WAIT_TIME: time::Duration = time::Duration::from_millis(100); +const POLL_SLEEP_TIME: time::Duration = time::Duration::from_millis(100); + +#[derive(Default, Debug, Clone, Copy, PartialEq, Eq)] +enum Mode { + #[default] + Wait, + WaitUntil, + Poll, +} + +fn main() -> Result<(), impl std::error::Error> { + #[cfg(web_platform)] + console_error_panic_hook::set_once(); + + tracing::init(); + + info!("Press '1' to switch to Wait mode."); + info!("Press '2' to switch to WaitUntil mode."); + info!("Press '3' to switch to Poll mode."); + info!("Press 'R' to toggle request_redraw() calls."); + info!("Press 'Esc' to close the window."); + + let event_loop = EventLoop::new().unwrap(); + + let mut app = ControlFlowDemo::default(); + event_loop.run_app(&mut app) +} + +#[derive(Default)] +struct ControlFlowDemo { + mode: Mode, + request_redraw: bool, + wait_cancelled: bool, + close_requested: bool, + window: Option<Window>, +} + +impl ApplicationHandler for ControlFlowDemo { + fn new_events(&mut self, _event_loop: &ActiveEventLoop, cause: StartCause) { + info!("new_events: {cause:?}"); + + self.wait_cancelled = match cause { + StartCause::WaitCancelled { .. } => self.mode == Mode::WaitUntil, + _ => false, + } + } + + fn resumed(&mut self, event_loop: &ActiveEventLoop) { + let window_attributes = Window::default_attributes().with_title( + "Press 1, 2, 3 to change control flow mode. Press R to toggle redraw requests.", + ); + self.window = Some(event_loop.create_window(window_attributes).unwrap()); + } + + fn window_event( + &mut self, + _event_loop: &ActiveEventLoop, + _window_id: WindowId, + event: WindowEvent, + ) { + info!("{event:?}"); + + match event { + WindowEvent::CloseRequested => { + self.close_requested = true; + }, + WindowEvent::KeyboardInput { + event: KeyEvent { logical_key: key, state: ElementState::Pressed, .. }, + .. + } => match key.as_ref() { + // WARNING: Consider using `key_without_modifiers()` if available on your platform. + // See the `key_binding` example + Key::Character("1") => { + self.mode = Mode::Wait; + warn!("mode: {:?}", self.mode); + }, + Key::Character("2") => { + self.mode = Mode::WaitUntil; + warn!("mode: {:?}", self.mode); + }, + Key::Character("3") => { + self.mode = Mode::Poll; + warn!("mode: {:?}", self.mode); + }, + Key::Character("r") => { + self.request_redraw = !self.request_redraw; + warn!("request_redraw: {}", self.request_redraw); + }, + Key::Named(NamedKey::Escape) => { + self.close_requested = true; + }, + _ => (), + }, + WindowEvent::RedrawRequested => { + let window = self.window.as_ref().unwrap(); + window.pre_present_notify(); + fill::fill_window(window); + }, + _ => (), + } + } + + fn about_to_wait(&mut self, event_loop: &ActiveEventLoop) { + if self.request_redraw && !self.wait_cancelled && !self.close_requested { + self.window.as_ref().unwrap().request_redraw(); + } + + match self.mode { + Mode::Wait => event_loop.set_control_flow(ControlFlow::Wait), + Mode::WaitUntil => { + if !self.wait_cancelled { + event_loop + .set_control_flow(ControlFlow::WaitUntil(time::Instant::now() + WAIT_TIME)); + } + }, + Mode::Poll => { + thread::sleep(POLL_SLEEP_TIME); + event_loop.set_control_flow(ControlFlow::Poll); + }, + }; + + if self.close_requested { + event_loop.exit(); + } + } +} diff --git a/app/vendor/rune/vendor/winit/examples/data/cross.png b/app/vendor/rune/vendor/winit/examples/data/cross.png new file mode 100644 index 0000000..9bfdf36 Binary files /dev/null and b/app/vendor/rune/vendor/winit/examples/data/cross.png differ diff --git a/app/vendor/rune/vendor/winit/examples/data/cross2.png b/app/vendor/rune/vendor/winit/examples/data/cross2.png new file mode 100644 index 0000000..b9f7a48 Binary files /dev/null and b/app/vendor/rune/vendor/winit/examples/data/cross2.png differ diff --git a/app/vendor/rune/vendor/winit/examples/data/gradient.png b/app/vendor/rune/vendor/winit/examples/data/gradient.png new file mode 100644 index 0000000..41ce610 Binary files /dev/null and b/app/vendor/rune/vendor/winit/examples/data/gradient.png differ diff --git a/app/vendor/rune/vendor/winit/examples/data/icon.png b/app/vendor/rune/vendor/winit/examples/data/icon.png new file mode 100644 index 0000000..aa3fbf3 Binary files /dev/null and b/app/vendor/rune/vendor/winit/examples/data/icon.png differ diff --git a/app/vendor/rune/vendor/winit/examples/pump_events.rs b/app/vendor/rune/vendor/winit/examples/pump_events.rs new file mode 100644 index 0000000..ad198cf --- /dev/null +++ b/app/vendor/rune/vendor/winit/examples/pump_events.rs @@ -0,0 +1,80 @@ +#![allow(clippy::single_match)] + +// Limit this example to only compatible platforms. +#[cfg(any(windows_platform, macos_platform, x11_platform, wayland_platform, android_platform,))] +fn main() -> std::process::ExitCode { + use std::process::ExitCode; + use std::thread::sleep; + use std::time::Duration; + + use winit::application::ApplicationHandler; + use winit::event::WindowEvent; + use winit::event_loop::{ActiveEventLoop, EventLoop}; + use winit::platform::pump_events::{EventLoopExtPumpEvents, PumpStatus}; + use winit::window::{Window, WindowId}; + + #[path = "util/fill.rs"] + mod fill; + + #[derive(Default)] + struct PumpDemo { + window: Option<Window>, + } + + impl ApplicationHandler for PumpDemo { + fn resumed(&mut self, event_loop: &ActiveEventLoop) { + let window_attributes = Window::default_attributes().with_title("A fantastic window!"); + self.window = Some(event_loop.create_window(window_attributes).unwrap()); + } + + fn window_event( + &mut self, + event_loop: &ActiveEventLoop, + _window_id: WindowId, + event: WindowEvent, + ) { + println!("{event:?}"); + + let window = match self.window.as_ref() { + Some(window) => window, + None => return, + }; + + match event { + WindowEvent::CloseRequested => event_loop.exit(), + WindowEvent::RedrawRequested => { + fill::fill_window(window); + window.request_redraw(); + }, + _ => (), + } + } + } + + let mut event_loop = EventLoop::new().unwrap(); + + tracing_subscriber::fmt::init(); + + let mut app = PumpDemo::default(); + + loop { + let timeout = Some(Duration::ZERO); + let status = event_loop.pump_app_events(timeout, &mut app); + + if let PumpStatus::Exit(exit_code) = status { + break ExitCode::from(exit_code as u8); + } + + // Sleep for 1/60 second to simulate application work + // + // Since `pump_events` doesn't block it will be important to + // throttle the loop in the app somehow. + println!("Update()"); + sleep(Duration::from_millis(16)); + } +} + +#[cfg(any(ios_platform, web_platform, orbital_platform))] +fn main() { + println!("This platform doesn't support pump_events."); +} diff --git a/app/vendor/rune/vendor/winit/examples/run_on_demand.rs b/app/vendor/rune/vendor/winit/examples/run_on_demand.rs new file mode 100644 index 0000000..5a277de --- /dev/null +++ b/app/vendor/rune/vendor/winit/examples/run_on_demand.rs @@ -0,0 +1,99 @@ +#![allow(clippy::single_match)] + +// Limit this example to only compatible platforms. +#[cfg(any(windows_platform, macos_platform, x11_platform, wayland_platform,))] +fn main() -> Result<(), Box<dyn std::error::Error>> { + use std::time::Duration; + + use winit::application::ApplicationHandler; + use winit::event::WindowEvent; + use winit::event_loop::{ActiveEventLoop, EventLoop}; + use winit::platform::run_on_demand::EventLoopExtRunOnDemand; + use winit::window::{Window, WindowId}; + + #[path = "util/fill.rs"] + mod fill; + + #[derive(Default)] + struct App { + idx: usize, + window_id: Option<WindowId>, + window: Option<Window>, + } + + impl ApplicationHandler for App { + fn about_to_wait(&mut self, _event_loop: &ActiveEventLoop) { + if let Some(window) = self.window.as_ref() { + window.request_redraw(); + } + } + + fn resumed(&mut self, event_loop: &ActiveEventLoop) { + let window_attributes = Window::default_attributes() + .with_title("Fantastic window number one!") + .with_inner_size(winit::dpi::LogicalSize::new(128.0, 128.0)); + let window = event_loop.create_window(window_attributes).unwrap(); + self.window_id = Some(window.id()); + self.window = Some(window); + } + + fn window_event( + &mut self, + event_loop: &ActiveEventLoop, + window_id: WindowId, + event: WindowEvent, + ) { + if event == WindowEvent::Destroyed && self.window_id == Some(window_id) { + println!( + "--------------------------------------------------------- Window {} Destroyed", + self.idx + ); + self.window_id = None; + event_loop.exit(); + return; + } + + let window = match self.window.as_mut() { + Some(window) => window, + None => return, + }; + + match event { + WindowEvent::CloseRequested => { + println!( + "--------------------------------------------------------- Window {} \ + CloseRequested", + self.idx + ); + fill::cleanup_window(window); + self.window = None; + }, + WindowEvent::RedrawRequested => { + fill::fill_window(window); + }, + _ => (), + } + } + } + + tracing_subscriber::fmt::init(); + + let mut event_loop = EventLoop::new().unwrap(); + + let mut app = App { idx: 1, ..Default::default() }; + event_loop.run_app_on_demand(&mut app)?; + + println!("--------------------------------------------------------- Finished first loop"); + println!("--------------------------------------------------------- Waiting 5 seconds"); + std::thread::sleep(Duration::from_secs(5)); + + app.idx += 1; + event_loop.run_app_on_demand(&mut app)?; + println!("--------------------------------------------------------- Finished second loop"); + Ok(()) +} + +#[cfg(not(any(windows_platform, macos_platform, x11_platform, wayland_platform,)))] +fn main() { + println!("This example is not supported on this platform"); +} diff --git a/app/vendor/rune/vendor/winit/examples/util/fill.rs b/app/vendor/rune/vendor/winit/examples/util/fill.rs new file mode 100644 index 0000000..31540c0 --- /dev/null +++ b/app/vendor/rune/vendor/winit/examples/util/fill.rs @@ -0,0 +1,117 @@ +//! Fill the window buffer with a solid color. +//! +//! Launching a window without drawing to it has unpredictable results varying from platform to +//! platform. In order to have well-defined examples, this module provides an easy way to +//! fill the window buffer with a solid color. +//! +//! The `softbuffer` crate is used, largely because of its ease of use. `glutin` or `wgpu` could +//! also be used to fill the window buffer, but they are more complicated to use. + +#[allow(unused_imports)] +pub use platform::cleanup_window; +pub use platform::fill_window; + +#[cfg(all(feature = "rwh_05", not(any(target_os = "android", target_os = "ios"))))] +mod platform { + use std::cell::RefCell; + use std::collections::HashMap; + use std::mem; + use std::mem::ManuallyDrop; + use std::num::NonZeroU32; + + use softbuffer::{Context, Surface}; + use winit::window::{Window, WindowId}; + + thread_local! { + // NOTE: You should never do things like that, create context and drop it before + // you drop the event loop. We do this for brevity to not blow up examples. We use + // ManuallyDrop to prevent destructors from running. + // + // A static, thread-local map of graphics contexts to open windows. + static GC: ManuallyDrop<RefCell<Option<GraphicsContext>>> = const { ManuallyDrop::new(RefCell::new(None)) }; + } + + /// The graphics context used to draw to a window. + struct GraphicsContext { + /// The global softbuffer context. + context: RefCell<Context<&'static Window>>, + + /// The hash map of window IDs to surfaces. + surfaces: HashMap<WindowId, Surface<&'static Window, &'static Window>>, + } + + impl GraphicsContext { + fn new(w: &Window) -> Self { + Self { + context: RefCell::new( + Context::new(unsafe { mem::transmute::<&'_ Window, &'static Window>(w) }) + .expect("Failed to create a softbuffer context"), + ), + surfaces: HashMap::new(), + } + } + + fn create_surface( + &mut self, + window: &Window, + ) -> &mut Surface<&'static Window, &'static Window> { + self.surfaces.entry(window.id()).or_insert_with(|| { + Surface::new(&self.context.borrow(), unsafe { + mem::transmute::<&'_ Window, &'static Window>(window) + }) + .expect("Failed to create a softbuffer surface") + }) + } + + fn destroy_surface(&mut self, window: &Window) { + self.surfaces.remove(&window.id()); + } + } + + pub fn fill_window(window: &Window) { + GC.with(|gc| { + let size = window.inner_size(); + let (Some(width), Some(height)) = + (NonZeroU32::new(size.width), NonZeroU32::new(size.height)) + else { + return; + }; + + // Either get the last context used or create a new one. + let mut gc = gc.borrow_mut(); + let surface = + gc.get_or_insert_with(|| GraphicsContext::new(window)).create_surface(window); + + // Fill a buffer with a solid color. + const DARK_GRAY: u32 = 0xff181818; + + surface.resize(width, height).expect("Failed to resize the softbuffer surface"); + + let mut buffer = surface.buffer_mut().expect("Failed to get the softbuffer buffer"); + buffer.fill(DARK_GRAY); + buffer.present().expect("Failed to present the softbuffer buffer"); + }) + } + + #[allow(dead_code)] + pub fn cleanup_window(window: &Window) { + GC.with(|gc| { + let mut gc = gc.borrow_mut(); + if let Some(context) = gc.as_mut() { + context.destroy_surface(window); + } + }); + } +} + +#[cfg(not(all(feature = "rwh_05", not(any(target_os = "android", target_os = "ios")))))] +mod platform { + pub fn fill_window(_window: &winit::window::Window) { + // No-op on mobile platforms. + } + + #[allow(dead_code)] + pub fn cleanup_window(_window: &winit::window::Window) { + // No-op on mobile platforms. + } +} diff --git a/app/vendor/rune/vendor/winit/examples/util/tracing.rs b/app/vendor/rune/vendor/winit/examples/util/tracing.rs new file mode 100644 index 0000000..bab7ced --- /dev/null +++ b/app/vendor/rune/vendor/winit/examples/util/tracing.rs @@ -0,0 +1,25 @@ +#[cfg(not(web_platform))] +pub fn init() { + use tracing_subscriber::filter::{EnvFilter, LevelFilter}; + + tracing_subscriber::fmt() + .with_env_filter( + EnvFilter::builder().with_default_directive(LevelFilter::INFO.into()).from_env_lossy(), + ) + .init(); +} + +#[cfg(web_platform)] +pub fn init() { + use tracing_subscriber::layer::SubscriberExt; + use tracing_subscriber::util::SubscriberInitExt; + + tracing_subscriber::registry() + .with( + tracing_subscriber::fmt::layer() + .with_ansi(false) + .without_time() + .with_writer(tracing_web::MakeWebConsoleWriter::new()), + ) + .init(); +} diff --git a/app/vendor/rune/vendor/winit/examples/window.rs b/app/vendor/rune/vendor/winit/examples/window.rs new file mode 100644 index 0000000..48afadf --- /dev/null +++ b/app/vendor/rune/vendor/winit/examples/window.rs @@ -0,0 +1,1110 @@ +//! Simple winit application. + +use std::collections::HashMap; +use std::error::Error; +use std::fmt::Debug; +#[cfg(not(any(android_platform, ios_platform)))] +use std::num::NonZeroU32; +use std::sync::Arc; +use std::{fmt, mem}; + +use ::tracing::{error, info}; +use cursor_icon::CursorIcon; +#[cfg(not(any(android_platform, ios_platform)))] +use rwh_06::{DisplayHandle, HasDisplayHandle}; +#[cfg(not(any(android_platform, ios_platform)))] +use softbuffer::{Context, Surface}; + +use winit::application::ApplicationHandler; +use winit::dpi::{LogicalSize, PhysicalPosition, PhysicalSize}; +use winit::event::{DeviceEvent, DeviceId, Ime, MouseButton, MouseScrollDelta, WindowEvent}; +use winit::event_loop::{ActiveEventLoop, EventLoop}; +use winit::keyboard::{Key, ModifiersState}; +use winit::window::{ + Cursor, CursorGrabMode, CustomCursor, CustomCursorSource, Fullscreen, Icon, ResizeDirection, + Theme, Window, WindowId, +}; + +#[cfg(macos_platform)] +use winit::platform::macos::{OptionAsAlt, WindowAttributesExtMacOS, WindowExtMacOS}; +#[cfg(any(x11_platform, wayland_platform))] +use winit::platform::startup_notify::{ + self, EventLoopExtStartupNotify, WindowAttributesExtStartupNotify, WindowExtStartupNotify, +}; +#[cfg(x11_platform)] +use winit::platform::x11::WindowAttributesExtX11; + +#[path = "util/tracing.rs"] +mod tracing; + +/// The amount of points to around the window for drag resize direction calculations. +const BORDER_SIZE: f64 = 20.; + +fn main() -> Result<(), Box<dyn Error>> { + #[cfg(web_platform)] + console_error_panic_hook::set_once(); + + tracing::init(); + + let event_loop = EventLoop::<UserEvent>::with_user_event().build()?; + let _event_loop_proxy = event_loop.create_proxy(); + + // Wire the user event from another thread. + #[cfg(not(web_platform))] + std::thread::spawn(move || { + // Wake up the `event_loop` once every second and dispatch a custom event + // from a different thread. + info!("Starting to send user event every second"); + loop { + let _ = _event_loop_proxy.send_event(UserEvent::WakeUp); + std::thread::sleep(std::time::Duration::from_secs(1)); + } + }); + + let mut state = Application::new(&event_loop); + + event_loop.run_app(&mut state).map_err(Into::into) +} + +#[allow(dead_code)] +#[derive(Debug, Clone, Copy)] +enum UserEvent { + WakeUp, +} + +/// Application state and event handling. +struct Application { + /// Custom cursors assets. + custom_cursors: Vec<CustomCursor>, + /// Application icon. + icon: Icon, + windows: HashMap<WindowId, WindowState>, + /// Drawing context. + /// + /// With OpenGL it could be EGLDisplay. + #[cfg(not(any(android_platform, ios_platform)))] + context: Option<Context<DisplayHandle<'static>>>, +} + +impl Application { + fn new<T>(event_loop: &EventLoop<T>) -> Self { + // SAFETY: we drop the context right before the event loop is stopped, thus making it safe. + #[cfg(not(any(android_platform, ios_platform)))] + let context = Some( + Context::new(unsafe { + std::mem::transmute::<DisplayHandle<'_>, DisplayHandle<'static>>( + event_loop.display_handle().unwrap(), + ) + }) + .unwrap(), + ); + + // You'll have to choose an icon size at your own discretion. On X11, the desired size + // varies by WM, and on Windows, you still have to account for screen scaling. Here + // we use 32px, since it seems to work well enough in most cases. Be careful about + // going too high, or you'll be bitten by the low-quality downscaling built into the + // WM. + let icon = load_icon(include_bytes!("data/icon.png")); + + info!("Loading cursor assets"); + let custom_cursors = vec![ + event_loop.create_custom_cursor(decode_cursor(include_bytes!("data/cross.png"))), + event_loop.create_custom_cursor(decode_cursor(include_bytes!("data/cross2.png"))), + event_loop.create_custom_cursor(decode_cursor(include_bytes!("data/gradient.png"))), + ]; + + Self { + #[cfg(not(any(android_platform, ios_platform)))] + context, + custom_cursors, + icon, + windows: Default::default(), + } + } + + fn create_window( + &mut self, + event_loop: &ActiveEventLoop, + _tab_id: Option<String>, + ) -> Result<WindowId, Box<dyn Error>> { + // TODO read-out activation token. + + #[allow(unused_mut)] + let mut window_attributes = Window::default_attributes() + .with_title("Winit window") + .with_transparent(true) + .with_window_icon(Some(self.icon.clone())); + + #[cfg(any(x11_platform, wayland_platform))] + if let Some(token) = event_loop.read_token_from_env() { + startup_notify::reset_activation_token_env(); + info!("Using token {:?} to activate a window", token); + window_attributes = window_attributes.with_activation_token(token); + } + + #[cfg(x11_platform)] + match std::env::var("X11_VISUAL_ID") { + Ok(visual_id_str) => { + info!("Using X11 visual id {visual_id_str}"); + let visual_id = visual_id_str.parse()?; + window_attributes = window_attributes.with_x11_visual(visual_id); + }, + Err(_) => info!("Set the X11_VISUAL_ID env variable to request specific X11 visual"), + } + + #[cfg(x11_platform)] + match std::env::var("X11_SCREEN_ID") { + Ok(screen_id_str) => { + info!("Placing the window on X11 screen {screen_id_str}"); + let screen_id = screen_id_str.parse()?; + window_attributes = window_attributes.with_x11_screen(screen_id); + }, + Err(_) => info!( + "Set the X11_SCREEN_ID env variable to place the window on non-default screen" + ), + } + + #[cfg(macos_platform)] + if let Some(tab_id) = _tab_id { + window_attributes = window_attributes.with_tabbing_identifier(&tab_id); + } + + #[cfg(web_platform)] + { + use winit::platform::web::WindowAttributesExtWebSys; + window_attributes = window_attributes.with_append(true); + } + + let window = event_loop.create_window(window_attributes)?; + + #[cfg(ios_platform)] + { + use winit::platform::ios::WindowExtIOS; + window.recognize_doubletap_gesture(true); + window.recognize_pinch_gesture(true); + window.recognize_rotation_gesture(true); + window.recognize_pan_gesture(true, 2, 2); + } + + let window_state = WindowState::new(self, window)?; + let window_id = window_state.window.id(); + info!("Created new window with id={window_id:?}"); + self.windows.insert(window_id, window_state); + Ok(window_id) + } + + fn handle_action(&mut self, event_loop: &ActiveEventLoop, window_id: WindowId, action: Action) { + // let cursor_position = self.cursor_position; + let window = self.windows.get_mut(&window_id).unwrap(); + info!("Executing action: {action:?}"); + match action { + Action::CloseWindow => { + let _ = self.windows.remove(&window_id); + }, + Action::CreateNewWindow => { + #[cfg(any(x11_platform, wayland_platform))] + if let Err(err) = window.window.request_activation_token() { + info!("Failed to get activation token: {err}"); + } else { + return; + } + + if let Err(err) = self.create_window(event_loop, None) { + error!("Error creating new window: {err}"); + } + }, + Action::ToggleResizeIncrements => window.toggle_resize_increments(), + Action::ToggleCursorVisibility => window.toggle_cursor_visibility(), + Action::ToggleResizable => window.toggle_resizable(), + Action::ToggleDecorations => window.toggle_decorations(), + Action::ToggleFullscreen => window.toggle_fullscreen(), + Action::ToggleMaximize => window.toggle_maximize(), + Action::ToggleImeInput => window.toggle_ime(), + Action::Minimize => window.minimize(), + Action::NextCursor => window.next_cursor(), + Action::NextCustomCursor => window.next_custom_cursor(&self.custom_cursors), + #[cfg(web_platform)] + Action::UrlCustomCursor => window.url_custom_cursor(event_loop), + #[cfg(web_platform)] + Action::AnimationCustomCursor => { + window.animation_custom_cursor(event_loop, &self.custom_cursors) + }, + Action::CycleCursorGrab => window.cycle_cursor_grab(), + Action::DragWindow => window.drag_window(), + Action::DragResizeWindow => window.drag_resize_window(), + Action::ShowWindowMenu => window.show_menu(), + Action::PrintHelp => self.print_help(), + #[cfg(macos_platform)] + Action::CycleOptionAsAlt => window.cycle_option_as_alt(), + Action::SetTheme(theme) => { + window.window.set_theme(theme); + // Get the resulting current theme to draw with + let actual_theme = theme.or_else(|| window.window.theme()).unwrap_or(Theme::Dark); + window.set_draw_theme(actual_theme); + }, + #[cfg(macos_platform)] + Action::CreateNewTab => { + let tab_id = window.window.tabbing_identifier(); + if let Err(err) = self.create_window(event_loop, Some(tab_id)) { + error!("Error creating new window: {err}"); + } + }, + Action::RequestResize => window.swap_dimensions(), + } + } + + fn dump_monitors(&self, event_loop: &ActiveEventLoop) { + info!("Monitors information"); + let primary_monitor = event_loop.primary_monitor(); + for monitor in event_loop.available_monitors() { + let intro = if primary_monitor.as_ref() == Some(&monitor) { + "Primary monitor" + } else { + "Monitor" + }; + + if let Some(name) = monitor.name() { + info!("{intro}: {name}"); + } else { + info!("{intro}: [no name]"); + } + + let PhysicalSize { width, height } = monitor.size(); + info!( + " Current mode: {width}x{height}{}", + if let Some(m_hz) = monitor.refresh_rate_millihertz() { + format!(" @ {}.{} Hz", m_hz / 1000, m_hz % 1000) + } else { + String::new() + } + ); + + let PhysicalPosition { x, y } = monitor.position(); + info!(" Position: {x},{y}"); + + info!(" Scale factor: {}", monitor.scale_factor()); + + info!(" Available modes (width x height x bit-depth):"); + for mode in monitor.video_modes() { + let PhysicalSize { width, height } = mode.size(); + let bits = mode.bit_depth(); + let m_hz = mode.refresh_rate_millihertz(); + info!(" {width}x{height}x{bits} @ {}.{} Hz", m_hz / 1000, m_hz % 1000); + } + } + } + + /// Process the key binding. + fn process_key_binding(key: &str, mods: &ModifiersState) -> Option<Action> { + KEY_BINDINGS + .iter() + .find_map(|binding| binding.is_triggered_by(&key, mods).then_some(binding.action)) + } + + /// Process mouse binding. + fn process_mouse_binding(button: MouseButton, mods: &ModifiersState) -> Option<Action> { + MOUSE_BINDINGS + .iter() + .find_map(|binding| binding.is_triggered_by(&button, mods).then_some(binding.action)) + } + + fn print_help(&self) { + info!("Keyboard bindings:"); + for binding in KEY_BINDINGS { + info!( + "{}{:<10} - {} ({})", + modifiers_to_string(binding.mods), + binding.trigger, + binding.action, + binding.action.help(), + ); + } + info!("Mouse bindings:"); + for binding in MOUSE_BINDINGS { + info!( + "{}{:<10} - {} ({})", + modifiers_to_string(binding.mods), + mouse_button_to_string(binding.trigger), + binding.action, + binding.action.help(), + ); + } + } +} + +impl ApplicationHandler<UserEvent> for Application { + fn user_event(&mut self, _event_loop: &ActiveEventLoop, event: UserEvent) { + info!("User event: {event:?}"); + } + + fn window_event( + &mut self, + event_loop: &ActiveEventLoop, + window_id: WindowId, + event: WindowEvent, + ) { + let window = match self.windows.get_mut(&window_id) { + Some(window) => window, + None => return, + }; + + match event { + WindowEvent::Resized(size) => { + window.resize(size); + }, + WindowEvent::Focused(focused) => { + if focused { + info!("Window={window_id:?} focused"); + } else { + info!("Window={window_id:?} unfocused"); + } + }, + WindowEvent::ScaleFactorChanged { scale_factor, .. } => { + info!("Window={window_id:?} changed scale to {scale_factor}"); + }, + WindowEvent::ThemeChanged(theme) => { + info!("Theme changed to {theme:?}"); + window.set_draw_theme(theme); + }, + WindowEvent::RedrawRequested => { + if let Err(err) = window.draw() { + error!("Error drawing window: {err}"); + } + }, + WindowEvent::Occluded(occluded) => { + window.set_occluded(occluded); + }, + WindowEvent::CloseRequested => { + info!("Closing Window={window_id:?}"); + self.windows.remove(&window_id); + }, + WindowEvent::ModifiersChanged(modifiers) => { + window.modifiers = modifiers.state(); + info!("Modifiers changed to {:?}", window.modifiers); + }, + WindowEvent::MouseWheel { delta, .. } => match delta { + MouseScrollDelta::LineDelta(x, y) => { + info!("Mouse wheel Line Delta: ({x},{y})"); + }, + MouseScrollDelta::PixelDelta(px) => { + info!("Mouse wheel Pixel Delta: ({},{})", px.x, px.y); + }, + }, + WindowEvent::KeyboardInput { event, is_synthetic: false, .. } => { + let mods = window.modifiers; + + // Dispatch actions only on press. + if event.state.is_pressed() { + let action = if let Key::Character(ch) = event.logical_key.as_ref() { + Self::process_key_binding(&ch.to_uppercase(), &mods) + } else { + None + }; + + if let Some(action) = action { + self.handle_action(event_loop, window_id, action); + } + } + }, + WindowEvent::MouseInput { button, state, .. } => { + let mods = window.modifiers; + if let Some(action) = + state.is_pressed().then(|| Self::process_mouse_binding(button, &mods)).flatten() + { + self.handle_action(event_loop, window_id, action); + } + }, + WindowEvent::CursorLeft { .. } => { + info!("Cursor left Window={window_id:?}"); + window.cursor_left(); + }, + WindowEvent::CursorMoved { position, .. } => { + info!("Moved cursor to {position:?}"); + window.cursor_moved(position); + }, + WindowEvent::ActivationTokenDone { token: _token, .. } => { + #[cfg(any(x11_platform, wayland_platform))] + { + startup_notify::set_activation_token_env(_token); + if let Err(err) = self.create_window(event_loop, None) { + error!("Error creating new window: {err}"); + } + } + }, + WindowEvent::Ime(event) => match event { + Ime::Enabled => info!("IME enabled for Window={window_id:?}"), + Ime::Preedit(text, caret_pos) => { + info!("Preedit: {}, with caret at {:?}", text, caret_pos); + }, + Ime::Commit(text) => { + info!("Committed: {}", text); + }, + Ime::Disabled => info!("IME disabled for Window={window_id:?}"), + }, + WindowEvent::PinchGesture { delta, .. } => { + window.zoom += delta; + let zoom = window.zoom; + if delta > 0.0 { + info!("Zoomed in {delta:.5} (now: {zoom:.5})"); + } else { + info!("Zoomed out {delta:.5} (now: {zoom:.5})"); + } + }, + WindowEvent::RotationGesture { delta, .. } => { + window.rotated += delta; + let rotated = window.rotated; + if delta > 0.0 { + info!("Rotated counterclockwise {delta:.5} (now: {rotated:.5})"); + } else { + info!("Rotated clockwise {delta:.5} (now: {rotated:.5})"); + } + }, + WindowEvent::PanGesture { delta, phase, .. } => { + window.panned.x += delta.x; + window.panned.y += delta.y; + info!("Panned ({delta:?})) (now: {:?}), {phase:?}", window.panned); + }, + WindowEvent::DoubleTapGesture { .. } => { + info!("Smart zoom"); + }, + WindowEvent::TouchpadPressure { .. } + | WindowEvent::HoveredFileCancelled + | WindowEvent::KeyboardInput { .. } + | WindowEvent::CursorEntered { .. } + | WindowEvent::AxisMotion { .. } + | WindowEvent::DroppedFile(_) + | WindowEvent::HoveredFile(_) + | WindowEvent::Destroyed + | WindowEvent::Touch(_) + | WindowEvent::Moved(_) => (), + } + } + + fn device_event( + &mut self, + _event_loop: &ActiveEventLoop, + device_id: DeviceId, + event: DeviceEvent, + ) { + info!("Device {device_id:?} event: {event:?}"); + } + + fn resumed(&mut self, event_loop: &ActiveEventLoop) { + info!("Resumed the event loop"); + self.dump_monitors(event_loop); + + // Create initial window. + self.create_window(event_loop, None).expect("failed to create initial window"); + + self.print_help(); + } + + fn about_to_wait(&mut self, event_loop: &ActiveEventLoop) { + if self.windows.is_empty() { + info!("No windows left, exiting..."); + event_loop.exit(); + } + } + + #[cfg(not(any(android_platform, ios_platform)))] + fn exiting(&mut self, _event_loop: &ActiveEventLoop) { + // We must drop the context here. + self.context = None; + } +} + +/// State of the window. +struct WindowState { + /// IME input. + ime: bool, + /// Render surface. + /// + /// NOTE: This surface must be dropped before the `Window`. + #[cfg(not(any(android_platform, ios_platform)))] + surface: Surface<DisplayHandle<'static>, Arc<Window>>, + /// The actual winit Window. + window: Arc<Window>, + /// The window theme we're drawing with. + theme: Theme, + /// Cursor position over the window. + cursor_position: Option<PhysicalPosition<f64>>, + /// Window modifiers state. + modifiers: ModifiersState, + /// Occlusion state of the window. + occluded: bool, + /// Current cursor grab mode. + cursor_grab: CursorGrabMode, + /// The amount of zoom into window. + zoom: f64, + /// The amount of rotation of the window. + rotated: f32, + /// The amount of pan of the window. + panned: PhysicalPosition<f32>, + + #[cfg(macos_platform)] + option_as_alt: OptionAsAlt, + + // Cursor states. + named_idx: usize, + custom_idx: usize, + cursor_hidden: bool, +} + +impl WindowState { + fn new(app: &Application, window: Window) -> Result<Self, Box<dyn Error>> { + let window = Arc::new(window); + + // SAFETY: the surface is dropped before the `window` which provided it with handle, thus + // it doesn't outlive it. + #[cfg(not(any(android_platform, ios_platform)))] + let surface = Surface::new(app.context.as_ref().unwrap(), Arc::clone(&window))?; + + let theme = window.theme().unwrap_or(Theme::Dark); + info!("Theme: {theme:?}"); + let named_idx = 0; + window.set_cursor(CURSORS[named_idx]); + + // Allow IME out of the box. + let ime = true; + window.set_ime_allowed(ime); + + let size = window.inner_size(); + let mut state = Self { + #[cfg(macos_platform)] + option_as_alt: window.option_as_alt(), + custom_idx: app.custom_cursors.len() - 1, + cursor_grab: CursorGrabMode::None, + named_idx, + #[cfg(not(any(android_platform, ios_platform)))] + surface, + window, + theme, + ime, + cursor_position: Default::default(), + cursor_hidden: Default::default(), + modifiers: Default::default(), + occluded: Default::default(), + rotated: Default::default(), + panned: Default::default(), + zoom: Default::default(), + }; + + state.resize(size); + Ok(state) + } + + pub fn toggle_ime(&mut self) { + self.ime = !self.ime; + self.window.set_ime_allowed(self.ime); + if let Some(position) = self.ime.then_some(self.cursor_position).flatten() { + self.window.set_ime_cursor_area(position, PhysicalSize::new(20, 20)); + } + } + + pub fn minimize(&mut self) { + self.window.set_minimized(true); + } + + pub fn cursor_moved(&mut self, position: PhysicalPosition<f64>) { + self.cursor_position = Some(position); + if self.ime { + self.window.set_ime_cursor_area(position, PhysicalSize::new(20, 20)); + } + } + + pub fn cursor_left(&mut self) { + self.cursor_position = None; + } + + /// Toggle maximized. + fn toggle_maximize(&self) { + let maximized = self.window.is_maximized(); + self.window.set_maximized(!maximized); + } + + /// Toggle window decorations. + fn toggle_decorations(&self) { + let decorated = self.window.is_decorated(); + self.window.set_decorations(!decorated); + } + + /// Toggle window resizable state. + fn toggle_resizable(&self) { + let resizable = self.window.is_resizable(); + self.window.set_resizable(!resizable); + } + + /// Toggle cursor visibility + fn toggle_cursor_visibility(&mut self) { + self.cursor_hidden = !self.cursor_hidden; + self.window.set_cursor_visible(!self.cursor_hidden); + } + + /// Toggle resize increments on a window. + fn toggle_resize_increments(&mut self) { + let new_increments = match self.window.resize_increments() { + Some(_) => None, + None => Some(LogicalSize::new(25.0, 25.0)), + }; + info!("Had increments: {}", new_increments.is_none()); + self.window.set_resize_increments(new_increments); + } + + /// Toggle fullscreen. + fn toggle_fullscreen(&self) { + let fullscreen = if self.window.fullscreen().is_some() { + None + } else { + Some(Fullscreen::Borderless(None)) + }; + + self.window.set_fullscreen(fullscreen); + } + + /// Cycle through the grab modes ignoring errors. + fn cycle_cursor_grab(&mut self) { + self.cursor_grab = match self.cursor_grab { + CursorGrabMode::None => CursorGrabMode::Confined, + CursorGrabMode::Confined => CursorGrabMode::Locked, + CursorGrabMode::Locked => CursorGrabMode::None, + }; + info!("Changing cursor grab mode to {:?}", self.cursor_grab); + if let Err(err) = self.window.set_cursor_grab(self.cursor_grab) { + error!("Error setting cursor grab: {err}"); + } + } + + #[cfg(macos_platform)] + fn cycle_option_as_alt(&mut self) { + self.option_as_alt = match self.option_as_alt { + OptionAsAlt::None => OptionAsAlt::OnlyLeft, + OptionAsAlt::OnlyLeft => OptionAsAlt::OnlyRight, + OptionAsAlt::OnlyRight => OptionAsAlt::Both, + OptionAsAlt::Both => OptionAsAlt::None, + }; + info!("Setting option as alt {:?}", self.option_as_alt); + self.window.set_option_as_alt(self.option_as_alt); + } + + /// Swap the window dimensions with `request_inner_size`. + fn swap_dimensions(&mut self) { + let old_inner_size = self.window.inner_size(); + let mut inner_size = old_inner_size; + + mem::swap(&mut inner_size.width, &mut inner_size.height); + info!("Requesting resize from {old_inner_size:?} to {inner_size:?}"); + + if let Some(new_inner_size) = self.window.request_inner_size(inner_size) { + if old_inner_size == new_inner_size { + info!("Inner size change got ignored"); + } else { + self.resize(new_inner_size); + } + } else { + info!("Request inner size is asynchronous"); + } + } + + /// Pick the next cursor. + fn next_cursor(&mut self) { + self.named_idx = (self.named_idx + 1) % CURSORS.len(); + info!("Setting cursor to \"{:?}\"", CURSORS[self.named_idx]); + self.window.set_cursor(Cursor::Icon(CURSORS[self.named_idx])); + } + + /// Pick the next custom cursor. + fn next_custom_cursor(&mut self, custom_cursors: &[CustomCursor]) { + self.custom_idx = (self.custom_idx + 1) % custom_cursors.len(); + let cursor = Cursor::Custom(custom_cursors[self.custom_idx].clone()); + self.window.set_cursor(cursor); + } + + /// Custom cursor from an URL. + #[cfg(web_platform)] + fn url_custom_cursor(&mut self, event_loop: &ActiveEventLoop) { + let cursor = event_loop.create_custom_cursor(url_custom_cursor()); + + self.window.set_cursor(cursor); + } + + /// Custom cursor from a URL. + #[cfg(web_platform)] + fn animation_custom_cursor( + &mut self, + event_loop: &ActiveEventLoop, + custom_cursors: &[CustomCursor], + ) { + use std::time::Duration; + use winit::platform::web::CustomCursorExtWebSys; + + let cursors = vec![ + custom_cursors[0].clone(), + custom_cursors[1].clone(), + event_loop.create_custom_cursor(url_custom_cursor()), + ]; + let cursor = CustomCursor::from_animation(Duration::from_secs(3), cursors).unwrap(); + let cursor = event_loop.create_custom_cursor(cursor); + + self.window.set_cursor(cursor); + } + + /// Resize the window to the new size. + fn resize(&mut self, size: PhysicalSize<u32>) { + info!("Resized to {size:?}"); + #[cfg(not(any(android_platform, ios_platform)))] + { + let (width, height) = match (NonZeroU32::new(size.width), NonZeroU32::new(size.height)) + { + (Some(width), Some(height)) => (width, height), + _ => return, + }; + self.surface.resize(width, height).expect("failed to resize inner buffer"); + } + self.window.request_redraw(); + } + + /// Change the theme that things are drawn in. + fn set_draw_theme(&mut self, theme: Theme) { + self.theme = theme; + self.window.request_redraw(); + } + + /// Show window menu. + fn show_menu(&self) { + if let Some(position) = self.cursor_position { + self.window.show_window_menu(position); + } + } + + /// Drag the window. + fn drag_window(&self) { + if let Err(err) = self.window.drag_window() { + info!("Error starting window drag: {err}"); + } else { + info!("Dragging window Window={:?}", self.window.id()); + } + } + + /// Drag-resize the window. + fn drag_resize_window(&self) { + let position = match self.cursor_position { + Some(position) => position, + None => { + info!("Drag-resize requires cursor to be inside the window"); + return; + }, + }; + + let win_size = self.window.inner_size(); + let border_size = BORDER_SIZE * self.window.scale_factor(); + + let x_direction = if position.x < border_size { + ResizeDirection::West + } else if position.x > (win_size.width as f64 - border_size) { + ResizeDirection::East + } else { + // Use arbitrary direction instead of None for simplicity. + ResizeDirection::SouthEast + }; + + let y_direction = if position.y < border_size { + ResizeDirection::North + } else if position.y > (win_size.height as f64 - border_size) { + ResizeDirection::South + } else { + // Use arbitrary direction instead of None for simplicity. + ResizeDirection::SouthEast + }; + + let direction = match (x_direction, y_direction) { + (ResizeDirection::West, ResizeDirection::North) => ResizeDirection::NorthWest, + (ResizeDirection::West, ResizeDirection::South) => ResizeDirection::SouthWest, + (ResizeDirection::West, _) => ResizeDirection::West, + (ResizeDirection::East, ResizeDirection::North) => ResizeDirection::NorthEast, + (ResizeDirection::East, ResizeDirection::South) => ResizeDirection::SouthEast, + (ResizeDirection::East, _) => ResizeDirection::East, + (_, ResizeDirection::South) => ResizeDirection::South, + (_, ResizeDirection::North) => ResizeDirection::North, + _ => return, + }; + + if let Err(err) = self.window.drag_resize_window(direction) { + info!("Error starting window drag-resize: {err}"); + } else { + info!("Drag-resizing window Window={:?}", self.window.id()); + } + } + + /// Change window occlusion state. + fn set_occluded(&mut self, occluded: bool) { + self.occluded = occluded; + if !occluded { + self.window.request_redraw(); + } + } + + /// Draw the window contents. + #[cfg(not(any(android_platform, ios_platform)))] + fn draw(&mut self) -> Result<(), Box<dyn Error>> { + if self.occluded { + info!("Skipping drawing occluded window={:?}", self.window.id()); + return Ok(()); + } + + const WHITE: u32 = 0xffffffff; + const DARK_GRAY: u32 = 0xff181818; + + let color = match self.theme { + Theme::Light => WHITE, + Theme::Dark => DARK_GRAY, + }; + + let mut buffer = self.surface.buffer_mut()?; + buffer.fill(color); + self.window.pre_present_notify(); + buffer.present()?; + Ok(()) + } + + #[cfg(any(android_platform, ios_platform))] + fn draw(&mut self) -> Result<(), Box<dyn Error>> { + info!("Drawing but without rendering..."); + Ok(()) + } +} + +struct Binding<T: Eq> { + trigger: T, + mods: ModifiersState, + action: Action, +} + +impl<T: Eq> Binding<T> { + const fn new(trigger: T, mods: ModifiersState, action: Action) -> Self { + Self { trigger, mods, action } + } + + fn is_triggered_by(&self, trigger: &T, mods: &ModifiersState) -> bool { + &self.trigger == trigger && &self.mods == mods + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Action { + CloseWindow, + ToggleCursorVisibility, + CreateNewWindow, + ToggleResizeIncrements, + ToggleImeInput, + ToggleDecorations, + ToggleResizable, + ToggleFullscreen, + ToggleMaximize, + Minimize, + NextCursor, + NextCustomCursor, + #[cfg(web_platform)] + UrlCustomCursor, + #[cfg(web_platform)] + AnimationCustomCursor, + CycleCursorGrab, + PrintHelp, + DragWindow, + DragResizeWindow, + ShowWindowMenu, + #[cfg(macos_platform)] + CycleOptionAsAlt, + SetTheme(Option<Theme>), + #[cfg(macos_platform)] + CreateNewTab, + RequestResize, +} + +impl Action { + fn help(&self) -> &'static str { + match self { + Action::CloseWindow => "Close window", + Action::ToggleCursorVisibility => "Hide cursor", + Action::CreateNewWindow => "Create new window", + Action::ToggleImeInput => "Toggle IME input", + Action::ToggleDecorations => "Toggle decorations", + Action::ToggleResizable => "Toggle window resizable state", + Action::ToggleFullscreen => "Toggle fullscreen", + Action::ToggleMaximize => "Maximize", + Action::Minimize => "Minimize", + Action::ToggleResizeIncrements => "Use resize increments when resizing window", + Action::NextCursor => "Advance the cursor to the next value", + Action::NextCustomCursor => "Advance custom cursor to the next value", + #[cfg(web_platform)] + Action::UrlCustomCursor => "Custom cursor from an URL", + #[cfg(web_platform)] + Action::AnimationCustomCursor => "Custom cursor from an animation", + Action::CycleCursorGrab => "Cycle through cursor grab mode", + Action::PrintHelp => "Print help", + Action::DragWindow => "Start window drag", + Action::DragResizeWindow => "Start window drag-resize", + Action::ShowWindowMenu => "Show window menu", + #[cfg(macos_platform)] + Action::CycleOptionAsAlt => "Cycle option as alt mode", + Action::SetTheme(None) => "Change to the system theme", + Action::SetTheme(Some(Theme::Light)) => "Change to a light theme", + Action::SetTheme(Some(Theme::Dark)) => "Change to a dark theme", + #[cfg(macos_platform)] + Action::CreateNewTab => "Create new tab", + Action::RequestResize => "Request a resize", + } + } +} + +impl fmt::Display for Action { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + Debug::fmt(&self, f) + } +} + +fn decode_cursor(bytes: &[u8]) -> CustomCursorSource { + let img = image::load_from_memory(bytes).unwrap().to_rgba8(); + let samples = img.into_flat_samples(); + let (_, w, h) = samples.extents(); + let (w, h) = (w as u16, h as u16); + CustomCursor::from_rgba(samples.samples, w, h, w / 2, h / 2).unwrap() +} + +#[cfg(web_platform)] +fn url_custom_cursor() -> CustomCursorSource { + use std::sync::atomic::{AtomicU64, Ordering}; + + use winit::platform::web::CustomCursorExtWebSys; + + static URL_COUNTER: AtomicU64 = AtomicU64::new(0); + + CustomCursor::from_url( + format!("https://picsum.photos/128?random={}", URL_COUNTER.fetch_add(1, Ordering::Relaxed)), + 64, + 64, + ) +} + +fn load_icon(bytes: &[u8]) -> Icon { + let (icon_rgba, icon_width, icon_height) = { + let image = image::load_from_memory(bytes).unwrap().into_rgba8(); + let (width, height) = image.dimensions(); + let rgba = image.into_raw(); + (rgba, width, height) + }; + Icon::from_rgba(icon_rgba, icon_width, icon_height).expect("Failed to open icon") +} + +fn modifiers_to_string(mods: ModifiersState) -> String { + let mut mods_line = String::new(); + // Always add + since it's printed as a part of the bindings. + for (modifier, desc) in [ + (ModifiersState::SUPER, "Super+"), + (ModifiersState::ALT, "Alt+"), + (ModifiersState::CONTROL, "Ctrl+"), + (ModifiersState::SHIFT, "Shift+"), + ] { + if !mods.contains(modifier) { + continue; + } + + mods_line.push_str(desc); + } + mods_line +} + +fn mouse_button_to_string(button: MouseButton) -> &'static str { + match button { + MouseButton::Left => "LMB", + MouseButton::Right => "RMB", + MouseButton::Middle => "MMB", + MouseButton::Back => "Back", + MouseButton::Forward => "Forward", + MouseButton::Other(_) => "", + } +} + +/// Cursor list to cycle through. +const CURSORS: &[CursorIcon] = &[ + CursorIcon::Default, + CursorIcon::Crosshair, + CursorIcon::Pointer, + CursorIcon::Move, + CursorIcon::Text, + CursorIcon::Wait, + CursorIcon::Help, + CursorIcon::Progress, + CursorIcon::NotAllowed, + CursorIcon::ContextMenu, + CursorIcon::Cell, + CursorIcon::VerticalText, + CursorIcon::Alias, + CursorIcon::Copy, + CursorIcon::NoDrop, + CursorIcon::Grab, + CursorIcon::Grabbing, + CursorIcon::AllScroll, + CursorIcon::ZoomIn, + CursorIcon::ZoomOut, + CursorIcon::EResize, + CursorIcon::NResize, + CursorIcon::NeResize, + CursorIcon::NwResize, + CursorIcon::SResize, + CursorIcon::SeResize, + CursorIcon::SwResize, + CursorIcon::WResize, + CursorIcon::EwResize, + CursorIcon::NsResize, + CursorIcon::NeswResize, + CursorIcon::NwseResize, + CursorIcon::ColResize, + CursorIcon::RowResize, +]; + +const KEY_BINDINGS: &[Binding<&'static str>] = &[ + Binding::new("Q", ModifiersState::CONTROL, Action::CloseWindow), + Binding::new("H", ModifiersState::CONTROL, Action::PrintHelp), + Binding::new("F", ModifiersState::CONTROL, Action::ToggleFullscreen), + Binding::new("D", ModifiersState::CONTROL, Action::ToggleDecorations), + Binding::new("I", ModifiersState::CONTROL, Action::ToggleImeInput), + Binding::new("L", ModifiersState::CONTROL, Action::CycleCursorGrab), + Binding::new("P", ModifiersState::CONTROL, Action::ToggleResizeIncrements), + Binding::new("R", ModifiersState::CONTROL, Action::ToggleResizable), + Binding::new("R", ModifiersState::ALT, Action::RequestResize), + // M. + Binding::new("M", ModifiersState::CONTROL, Action::ToggleMaximize), + Binding::new("M", ModifiersState::ALT, Action::Minimize), + // N. + Binding::new("N", ModifiersState::CONTROL, Action::CreateNewWindow), + // C. + Binding::new("C", ModifiersState::CONTROL, Action::NextCursor), + Binding::new("C", ModifiersState::ALT, Action::NextCustomCursor), + #[cfg(web_platform)] + Binding::new( + "C", + ModifiersState::CONTROL.union(ModifiersState::SHIFT), + Action::UrlCustomCursor, + ), + #[cfg(web_platform)] + Binding::new( + "C", + ModifiersState::ALT.union(ModifiersState::SHIFT), + Action::AnimationCustomCursor, + ), + Binding::new("Z", ModifiersState::CONTROL, Action::ToggleCursorVisibility), + // K. + Binding::new("K", ModifiersState::empty(), Action::SetTheme(None)), + Binding::new("K", ModifiersState::SUPER, Action::SetTheme(Some(Theme::Light))), + Binding::new("K", ModifiersState::CONTROL, Action::SetTheme(Some(Theme::Dark))), + #[cfg(macos_platform)] + Binding::new("T", ModifiersState::SUPER, Action::CreateNewTab), + #[cfg(macos_platform)] + Binding::new("O", ModifiersState::CONTROL, Action::CycleOptionAsAlt), +]; + +const MOUSE_BINDINGS: &[Binding<MouseButton>] = &[ + Binding::new(MouseButton::Left, ModifiersState::ALT, Action::DragResizeWindow), + Binding::new(MouseButton::Left, ModifiersState::CONTROL, Action::DragWindow), + Binding::new(MouseButton::Right, ModifiersState::CONTROL, Action::ShowWindowMenu), +]; diff --git a/app/vendor/rune/vendor/winit/examples/x11_embed.rs b/app/vendor/rune/vendor/winit/examples/x11_embed.rs new file mode 100644 index 0000000..9db55e5 --- /dev/null +++ b/app/vendor/rune/vendor/winit/examples/x11_embed.rs @@ -0,0 +1,69 @@ +//! A demonstration of embedding a winit window in an existing X11 application. +use std::error::Error; + +#[cfg(x11_platform)] +fn main() -> Result<(), Box<dyn Error>> { + use winit::application::ApplicationHandler; + use winit::event::WindowEvent; + use winit::event_loop::{ActiveEventLoop, EventLoop}; + use winit::platform::x11::WindowAttributesExtX11; + use winit::window::{Window, WindowId}; + + #[path = "util/fill.rs"] + mod fill; + + pub struct XEmbedDemo { + parent_window_id: u32, + window: Option<Window>, + } + + impl ApplicationHandler for XEmbedDemo { + fn resumed(&mut self, event_loop: &ActiveEventLoop) { + let window_attributes = Window::default_attributes() + .with_title("An embedded window!") + .with_inner_size(winit::dpi::LogicalSize::new(128.0, 128.0)) + .with_embed_parent_window(self.parent_window_id); + + self.window = Some(event_loop.create_window(window_attributes).unwrap()); + } + + fn window_event( + &mut self, + event_loop: &ActiveEventLoop, + _window_id: WindowId, + event: WindowEvent, + ) { + let window = self.window.as_ref().unwrap(); + match event { + WindowEvent::CloseRequested => event_loop.exit(), + WindowEvent::RedrawRequested => { + window.pre_present_notify(); + fill::fill_window(window); + }, + _ => (), + } + } + + fn about_to_wait(&mut self, _event_loop: &ActiveEventLoop) { + self.window.as_ref().unwrap().request_redraw(); + } + } + + // First argument should be a 32-bit X11 window ID. + let parent_window_id = std::env::args() + .nth(1) + .ok_or("Expected a 32-bit X11 window ID as the first argument.")? + .parse::<u32>()?; + + tracing_subscriber::fmt::init(); + let event_loop = EventLoop::new()?; + + let mut app = XEmbedDemo { parent_window_id, window: None }; + event_loop.run_app(&mut app).map_err(Into::into) +} + +#[cfg(not(x11_platform))] +fn main() -> Result<(), Box<dyn Error>> { + println!("This example is only supported on X11 platforms."); + Ok(()) +} diff --git a/app/vendor/rune/vendor/winit/src/application.rs b/app/vendor/rune/vendor/winit/src/application.rs new file mode 100644 index 0000000..977a7c7 --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/application.rs @@ -0,0 +1,339 @@ +//! End user application handling. + +use crate::event::{DeviceEvent, DeviceId, StartCause, WindowEvent}; +use crate::event_loop::ActiveEventLoop; +use crate::window::WindowId; + +/// The handler of the application events. +pub trait ApplicationHandler<T: 'static = ()> { + /// Emitted when new events arrive from the OS to be processed. + /// + /// This is a useful place to put code that should be done before you start processing + /// events, such as updating frame timing information for benchmarking or checking the + /// [`StartCause`] to see if a timer set by + /// [`ControlFlow::WaitUntil`][crate::event_loop::ControlFlow::WaitUntil] has elapsed. + fn new_events(&mut self, event_loop: &ActiveEventLoop, cause: StartCause) { + let _ = (event_loop, cause); + } + + /// Emitted when the application has been resumed. + /// + /// For consistency, all platforms emit a `Resumed` event even if they don't themselves have a + /// formal suspend/resume lifecycle. For systems without a formal suspend/resume lifecycle + /// the `Resumed` event is always emitted after the + /// [`NewEvents(StartCause::Init)`][StartCause::Init] event. + /// + /// # Portability + /// + /// It's recommended that applications should only initialize their graphics context and create + /// a window after they have received their first `Resumed` event. Some systems + /// (specifically Android) won't allow applications to create a render surface until they are + /// resumed. + /// + /// Considering that the implementation of [`Suspended`] and `Resumed` events may be internally + /// driven by multiple platform-specific events, and that there may be subtle differences across + /// platforms with how these internal events are delivered, it's recommended that applications + /// be able to gracefully handle redundant (i.e. back-to-back) [`Suspended`] or `Resumed` + /// events. + /// + /// Also see [`Suspended`] notes. + /// + /// ## Android + /// + /// On Android, the `Resumed` event is sent when a new [`SurfaceView`] has been created. This is + /// expected to closely correlate with the [`onResume`] lifecycle event but there may + /// technically be a discrepancy. + /// + /// [`onResume`]: https://developer.android.com/reference/android/app/Activity#onResume() + /// + /// Applications that need to run on Android must wait until they have been `Resumed` + /// before they will be able to create a render surface (such as an `EGLSurface`, + /// [`VkSurfaceKHR`] or [`wgpu::Surface`]) which depend on having a + /// [`SurfaceView`]. Applications must also assume that if they are [`Suspended`], then their + /// render surfaces are invalid and should be dropped. + /// + /// Also see [`Suspended`] notes. + /// + /// [`SurfaceView`]: https://developer.android.com/reference/android/view/SurfaceView + /// [Activity lifecycle]: https://developer.android.com/guide/components/activities/activity-lifecycle + /// [`VkSurfaceKHR`]: https://www.khronos.org/registry/vulkan/specs/1.3-extensions/man/html/VkSurfaceKHR.html + /// [`wgpu::Surface`]: https://docs.rs/wgpu/latest/wgpu/struct.Surface.html + /// + /// ## iOS + /// + /// On iOS, the `Resumed` event is emitted in response to an [`applicationDidBecomeActive`] + /// callback which means the application is "active" (according to the + /// [iOS application lifecycle]). + /// + /// [`applicationDidBecomeActive`]: https://developer.apple.com/documentation/uikit/uiapplicationdelegate/1622956-applicationdidbecomeactive + /// [iOS application lifecycle]: https://developer.apple.com/documentation/uikit/app_and_environment/managing_your_app_s_life_cycle + /// + /// ## Web + /// + /// On Web, the `Resumed` event is emitted in response to a [`pageshow`] event + /// with the property [`persisted`] being true, which means that the page is being + /// restored from the [`bfcache`] (back/forward cache) - an in-memory cache that + /// stores a complete snapshot of a page (including the JavaScript heap) as the + /// user is navigating away. + /// + /// [`pageshow`]: https://developer.mozilla.org/en-US/docs/Web/API/Window/pageshow_event + /// [`persisted`]: https://developer.mozilla.org/en-US/docs/Web/API/PageTransitionEvent/persisted + /// [`bfcache`]: https://web.dev/bfcache/ + /// [`Suspended`]: Self::suspended + fn resumed(&mut self, event_loop: &ActiveEventLoop); + + /// Emitted when an event is sent from [`EventLoopProxy::send_event`]. + /// + /// [`EventLoopProxy::send_event`]: crate::event_loop::EventLoopProxy::send_event + fn user_event(&mut self, event_loop: &ActiveEventLoop, event: T) { + let _ = (event_loop, event); + } + + /// Emitted when the OS sends an event to a winit window. + fn window_event( + &mut self, + event_loop: &ActiveEventLoop, + window_id: WindowId, + event: WindowEvent, + ); + + /// Emitted when the OS sends an event to a device. + fn device_event( + &mut self, + event_loop: &ActiveEventLoop, + device_id: DeviceId, + event: DeviceEvent, + ) { + let _ = (event_loop, device_id, event); + } + + /// Emitted when the event loop is about to block and wait for new events. + /// + /// Most applications shouldn't need to hook into this event since there is no real relationship + /// between how often the event loop needs to wake up and the dispatching of any specific + /// events. + /// + /// High frequency event sources, such as input devices could potentially lead to lots of wake + /// ups and also lots of corresponding `AboutToWait` events. + /// + /// This is not an ideal event to drive application rendering from and instead applications + /// should render in response to [`WindowEvent::RedrawRequested`] events. + fn about_to_wait(&mut self, event_loop: &ActiveEventLoop) { + let _ = event_loop; + } + + /// Emitted when the application has been suspended. + /// + /// # Portability + /// + /// Not all platforms support the notion of suspending applications, and there may be no + /// technical way to guarantee being able to emit a `Suspended` event if the OS has + /// no formal application lifecycle (currently only Android, iOS, and Web do). For this reason, + /// Winit does not currently try to emit pseudo `Suspended` events before the application + /// quits on platforms without an application lifecycle. + /// + /// Considering that the implementation of `Suspended` and [`Resumed`] events may be internally + /// driven by multiple platform-specific events, and that there may be subtle differences across + /// platforms with how these internal events are delivered, it's recommended that applications + /// be able to gracefully handle redundant (i.e. back-to-back) `Suspended` or [`Resumed`] + /// events. + /// + /// Also see [`Resumed`] notes. + /// + /// ## Android + /// + /// On Android, the `Suspended` event is only sent when the application's associated + /// [`SurfaceView`] is destroyed. This is expected to closely correlate with the [`onPause`] + /// lifecycle event but there may technically be a discrepancy. + /// + /// [`onPause`]: https://developer.android.com/reference/android/app/Activity#onPause() + /// + /// Applications that need to run on Android should assume their [`SurfaceView`] has been + /// destroyed, which indirectly invalidates any existing render surfaces that may have been + /// created outside of Winit (such as an `EGLSurface`, [`VkSurfaceKHR`] or [`wgpu::Surface`]). + /// + /// After being `Suspended` on Android applications must drop all render surfaces before + /// the event callback completes, which may be re-created when the application is next + /// [`Resumed`]. + /// + /// [`SurfaceView`]: https://developer.android.com/reference/android/view/SurfaceView + /// [Activity lifecycle]: https://developer.android.com/guide/components/activities/activity-lifecycle + /// [`VkSurfaceKHR`]: https://www.khronos.org/registry/vulkan/specs/1.3-extensions/man/html/VkSurfaceKHR.html + /// [`wgpu::Surface`]: https://docs.rs/wgpu/latest/wgpu/struct.Surface.html + /// + /// ## iOS + /// + /// On iOS, the `Suspended` event is currently emitted in response to an + /// [`applicationWillResignActive`] callback which means that the application is + /// about to transition from the active to inactive state (according to the + /// [iOS application lifecycle]). + /// + /// [`applicationWillResignActive`]: https://developer.apple.com/documentation/uikit/uiapplicationdelegate/1622950-applicationwillresignactive + /// [iOS application lifecycle]: https://developer.apple.com/documentation/uikit/app_and_environment/managing_your_app_s_life_cycle + /// + /// ## Web + /// + /// On Web, the `Suspended` event is emitted in response to a [`pagehide`] event + /// with the property [`persisted`] being true, which means that the page is being + /// put in the [`bfcache`] (back/forward cache) - an in-memory cache that stores a + /// complete snapshot of a page (including the JavaScript heap) as the user is + /// navigating away. + /// + /// [`pagehide`]: https://developer.mozilla.org/en-US/docs/Web/API/Window/pagehide_event + /// [`persisted`]: https://developer.mozilla.org/en-US/docs/Web/API/PageTransitionEvent/persisted + /// [`bfcache`]: https://web.dev/bfcache/ + /// [`Resumed`]: Self::resumed + fn suspended(&mut self, event_loop: &ActiveEventLoop) { + let _ = event_loop; + } + + /// Emitted when the event loop is being shut down. + /// + /// This is irreversible - if this method is called, it is guaranteed that the event loop + /// will exit right after. + fn exiting(&mut self, event_loop: &ActiveEventLoop) { + let _ = event_loop; + } + + /// Emitted when the application has received a memory warning. + /// + /// ## Platform-specific + /// + /// ### Android + /// + /// On Android, the `MemoryWarning` event is sent when [`onLowMemory`] was called. The + /// application must [release memory] or risk being killed. + /// + /// [`onLowMemory`]: https://developer.android.com/reference/android/app/Application.html#onLowMemory() + /// [release memory]: https://developer.android.com/topic/performance/memory#release + /// + /// ### iOS + /// + /// On iOS, the `MemoryWarning` event is emitted in response to an + /// [`applicationDidReceiveMemoryWarning`] callback. The application must free as much + /// memory as possible or risk being terminated, see [how to respond to memory warnings]. + /// + /// [`applicationDidReceiveMemoryWarning`]: https://developer.apple.com/documentation/uikit/uiapplicationdelegate/1623063-applicationdidreceivememorywarni + /// [how to respond to memory warnings]: https://developer.apple.com/documentation/uikit/app_and_environment/managing_your_app_s_life_cycle/responding_to_memory_warnings + /// + /// ### Others + /// + /// - **macOS / Orbital / Wayland / Web / Windows:** Unsupported. + fn memory_warning(&mut self, event_loop: &ActiveEventLoop) { + let _ = event_loop; + } +} + +impl<A: ?Sized + ApplicationHandler<T>, T: 'static> ApplicationHandler<T> for &mut A { + #[inline] + fn new_events(&mut self, event_loop: &ActiveEventLoop, cause: StartCause) { + (**self).new_events(event_loop, cause); + } + + #[inline] + fn resumed(&mut self, event_loop: &ActiveEventLoop) { + (**self).resumed(event_loop); + } + + #[inline] + fn user_event(&mut self, event_loop: &ActiveEventLoop, event: T) { + (**self).user_event(event_loop, event); + } + + #[inline] + fn window_event( + &mut self, + event_loop: &ActiveEventLoop, + window_id: WindowId, + event: WindowEvent, + ) { + (**self).window_event(event_loop, window_id, event); + } + + #[inline] + fn device_event( + &mut self, + event_loop: &ActiveEventLoop, + device_id: DeviceId, + event: DeviceEvent, + ) { + (**self).device_event(event_loop, device_id, event); + } + + #[inline] + fn about_to_wait(&mut self, event_loop: &ActiveEventLoop) { + (**self).about_to_wait(event_loop); + } + + #[inline] + fn suspended(&mut self, event_loop: &ActiveEventLoop) { + (**self).suspended(event_loop); + } + + #[inline] + fn exiting(&mut self, event_loop: &ActiveEventLoop) { + (**self).exiting(event_loop); + } + + #[inline] + fn memory_warning(&mut self, event_loop: &ActiveEventLoop) { + (**self).memory_warning(event_loop); + } +} + +impl<A: ?Sized + ApplicationHandler<T>, T: 'static> ApplicationHandler<T> for Box<A> { + #[inline] + fn new_events(&mut self, event_loop: &ActiveEventLoop, cause: StartCause) { + (**self).new_events(event_loop, cause); + } + + #[inline] + fn resumed(&mut self, event_loop: &ActiveEventLoop) { + (**self).resumed(event_loop); + } + + #[inline] + fn user_event(&mut self, event_loop: &ActiveEventLoop, event: T) { + (**self).user_event(event_loop, event); + } + + #[inline] + fn window_event( + &mut self, + event_loop: &ActiveEventLoop, + window_id: WindowId, + event: WindowEvent, + ) { + (**self).window_event(event_loop, window_id, event); + } + + #[inline] + fn device_event( + &mut self, + event_loop: &ActiveEventLoop, + device_id: DeviceId, + event: DeviceEvent, + ) { + (**self).device_event(event_loop, device_id, event); + } + + #[inline] + fn about_to_wait(&mut self, event_loop: &ActiveEventLoop) { + (**self).about_to_wait(event_loop); + } + + #[inline] + fn suspended(&mut self, event_loop: &ActiveEventLoop) { + (**self).suspended(event_loop); + } + + #[inline] + fn exiting(&mut self, event_loop: &ActiveEventLoop) { + (**self).exiting(event_loop); + } + + #[inline] + fn memory_warning(&mut self, event_loop: &ActiveEventLoop) { + (**self).memory_warning(event_loop); + } +} diff --git a/app/vendor/rune/vendor/winit/src/changelog/mod.rs b/app/vendor/rune/vendor/winit/src/changelog/mod.rs new file mode 100644 index 0000000..a05ea9c --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/changelog/mod.rs @@ -0,0 +1,77 @@ +//! # Changelog and migrations +//! +//! All notable changes to this project will be documented in this module, +//! along with migration instructions for larger changes. +// Put the current entry at the top of this page, for discoverability. +// See `.cargo/config.toml` for details about `unreleased_changelogs`. +#![cfg_attr(unreleased_changelogs, doc = include_str!("unreleased.md"))] +#![cfg_attr(not(unreleased_changelogs), doc = include_str!("v0.30.md"))] + +#[doc = include_str!("v0.30.md")] +pub mod v0_30 {} + +#[doc = include_str!("v0.29.md")] +pub mod v0_29 {} + +#[doc = include_str!("v0.28.md")] +pub mod v0_28 {} + +#[doc = include_str!("v0.27.md")] +pub mod v0_27 {} + +#[doc = include_str!("v0.26.md")] +pub mod v0_26 {} + +#[doc = include_str!("v0.25.md")] +pub mod v0_25 {} + +#[doc = include_str!("v0.24.md")] +pub mod v0_24 {} + +#[doc = include_str!("v0.23.md")] +pub mod v0_23 {} + +#[doc = include_str!("v0.22.md")] +pub mod v0_22 {} + +#[doc = include_str!("v0.21.md")] +pub mod v0_21 {} + +#[doc = include_str!("v0.20.md")] +pub mod v0_20 {} + +#[doc = include_str!("v0.19.md")] +pub mod v0_19 {} + +#[doc = include_str!("v0.18.md")] +pub mod v0_18 {} + +#[doc = include_str!("v0.17.md")] +pub mod v0_17 {} + +#[doc = include_str!("v0.16.md")] +pub mod v0_16 {} + +#[doc = include_str!("v0.15.md")] +pub mod v0_15 {} + +#[doc = include_str!("v0.14.md")] +pub mod v0_14 {} + +#[doc = include_str!("v0.13.md")] +pub mod v0_13 {} + +#[doc = include_str!("v0.12.md")] +pub mod v0_12 {} + +#[doc = include_str!("v0.11.md")] +pub mod v0_11 {} + +#[doc = include_str!("v0.10.md")] +pub mod v0_10 {} + +#[doc = include_str!("v0.9.md")] +pub mod v0_9 {} + +#[doc = include_str!("v0.8.md")] +pub mod v0_8 {} diff --git a/app/vendor/rune/vendor/winit/src/changelog/unreleased.md b/app/vendor/rune/vendor/winit/src/changelog/unreleased.md new file mode 100644 index 0000000..f3a0f6d --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/changelog/unreleased.md @@ -0,0 +1,41 @@ +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/). + +The sections should follow the order `Added`, `Changed`, `Deprecated`, +`Removed`, and `Fixed`. + +Platform specific changed should be added to the end of the section and grouped +by platform name. Common API additions should have `, implemented` at the end +for platforms where the API was initially implemented. See the following example +on how to add them: + +```md +### Added + +- Add `Window::turbo()`, implemented on X11, Wayland, and Web. +- On X11, add `Window::some_rare_api`. +- On X11, add `Window::even_more_rare_api`. +- On Wayland, add `Window::common_api`. +- On Windows, add `Window::some_rare_api`. +``` + +When the change requires non-trivial amount of work for users to comply +with it, the migration guide should be added below the entry, like: + +```md +- Deprecate `Window` creation outside of `EventLoop::run` + + This was done to simply migration in the future. Consider the + following code: + + // Code snippet. + + To migrate it we should do X, Y, and then Z, for example: + + // Code snippet. + +``` + +The migration guide could reference other migration examples in the current +changelog entry. + +## Unreleased diff --git a/app/vendor/rune/vendor/winit/src/changelog/v0.10.md b/app/vendor/rune/vendor/winit/src/changelog/v0.10.md new file mode 100644 index 0000000..9e47c0b --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/changelog/v0.10.md @@ -0,0 +1,13 @@ +## 0.10.1 + +_Yanked_ + +## 0.10.0 + +- Add support for `Touch` for emscripten backend. +- Added support for `DroppedFile`, `HoveredFile`, and `HoveredFileCancelled` to X11 backend. +- **Breaking:** `unix::WindowExt` no longer returns pointers for things that aren't actually pointers; `get_xlib_window` now returns `Option<std::os::raw::c_ulong>` and `get_xlib_screen_id` returns `Option<std::os::raw::c_int>`. Additionally, methods that previously returned `libc::c_void` have been changed to return `std::os::raw::c_void`, which are not interchangeable types, so users wanting the former will need to explicitly cast. +- Added `set_decorations` method to `Window` to allow decorations to be toggled after the window is built. Presently only implemented on X11. +- Raised the minimum supported version of Rust to 1.20 on MacOS due to usage of associated constants in new versions of cocoa and core-graphics. +- Added `modifiers` field to `MouseInput`, `MouseWheel`, and `CursorMoved` events to track the modifiers state (`ModifiersState`). +- Fixed the emscripten backend to return the size of the canvas instead of the size of the window. diff --git a/app/vendor/rune/vendor/winit/src/changelog/v0.11.md b/app/vendor/rune/vendor/winit/src/changelog/v0.11.md new file mode 100644 index 0000000..31fb1d3 --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/changelog/v0.11.md @@ -0,0 +1,27 @@ +## 0.11.3 + +- Added `set_min_dimensions` and `set_max_dimensions` methods to `Window`, and implemented on Windows, X11, Wayland, and OSX. +- On X11, dropping a `Window` actually closes it now, and clicking the window's × button (or otherwise having the WM signal to close it) will result in the window closing. +- Added `WindowBuilderExt` methods for macos: `with_titlebar_transparent`, + `with_title_hidden`, `with_titlebar_buttons_hidden`, + `with_fullsize_content_view`. +- Mapped X11 numpad keycodes (arrows, Home, End, PageUp, PageDown, Insert and Delete) to corresponding virtual keycodes + +## 0.11.2 + +- Impl `Hash`, `PartialEq`, and `Eq` for `events::ModifiersState`. +- Implement `MonitorId::get_hidpi_factor` for MacOS. +- Added method `os::macos::MonitorIdExt::get_nsscreen() -> *mut c_void` that gets a `NSScreen` object matching the monitor ID. +- Send `Awakened` event on Android when event loop is woken up. + +## 0.11.1 + +- Fixed windows not receiving mouse events when click-dragging the mouse outside the client area of a window, on Windows platforms. +- Added method `os::android::EventsLoopExt:set_suspend_callback(Option<Box<Fn(bool) -> ()>>)` that allows glutin to register a callback when a suspend event happens + +## 0.11.0 + +- Implement `MonitorId::get_dimensions` for Android. +- Added method `os::macos::WindowBuilderExt::with_movable_by_window_background(bool)` that allows to move a window without a titlebar - `with_decorations(false)` +- Implement `Window::set_fullscreen`, `Window::set_maximized` and `Window::set_decorations` for Wayland. +- Added `Caret` as VirtualKeyCode and support OSX ^-Key with german input. diff --git a/app/vendor/rune/vendor/winit/src/changelog/v0.12.md b/app/vendor/rune/vendor/winit/src/changelog/v0.12.md new file mode 100644 index 0000000..3f9c83d --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/changelog/v0.12.md @@ -0,0 +1,8 @@ +## 0.12.0 + +- Added subclass to macos windows so they can be made resizable even with no decorations. +- Dead keys now work properly on X11, no longer resulting in a panic. +- On X11, input method creation first tries to use the value from the user's `XMODIFIERS` environment variable, so application developers should no longer need to manually call `XSetLocaleModifiers`. If that fails, fallbacks are tried, which should prevent input method initialization from ever outright failing. +- Fixed thread safety issues with input methods on X11. +- Add support for `Touch` for win32 backend. +- Fixed `Window::get_inner_size` and friends to return the size in pixels instead of points when using HIDPI displays on OSX. diff --git a/app/vendor/rune/vendor/winit/src/changelog/v0.13.md b/app/vendor/rune/vendor/winit/src/changelog/v0.13.md new file mode 100644 index 0000000..fd45665 --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/changelog/v0.13.md @@ -0,0 +1,20 @@ +## 0.13.1 + +- Ensure necessary `x11-dl` version is used. + +## 0.13.0 + +- Implement `WindowBuilder::with_maximized`, `Window::set_fullscreen`, `Window::set_maximized` and `Window::set_decorations` for MacOS. +- Implement `WindowBuilder::with_maximized`, `Window::set_fullscreen`, `Window::set_maximized` and `Window::set_decorations` for Windows. +- On Windows, `WindowBuilder::with_fullscreen` no longer changing monitor display resolution. +- Overhauled X11 window geometry calculations. `get_position` and `set_position` are more universally accurate across different window managers, and `get_outer_size` actually works now. +- Fixed SIGSEGV/SIGILL crashes on macOS caused by stabilization of the `!` (never) type. +- Implement `WindowEvent::HiDPIFactorChanged` for macOS +- On X11, input methods now work completely out of the box, no longer requiring application developers to manually call `setlocale`. Additionally, when input methods are started, stopped, or restarted on the server end, it's correctly handled. +- Implemented `Refresh` event on Windows. +- Properly calculate the minimum and maximum window size on Windows, including window decorations. +- Map more `MouseCursor` variants to cursor icons on Windows. +- Corrected `get_position` on macOS to return outer frame position, not content area position. +- Corrected `set_position` on macOS to set outer frame position, not content area position. +- Added `get_inner_position` method to `Window`, which gets the position of the window's client area. This is implemented on all applicable platforms (all desktop platforms other than Wayland, where this isn't possible). +- **Breaking:** the `Closed` event has been replaced by `CloseRequested` and `Destroyed`. To migrate, you typically just need to replace all usages of `Closed` with `CloseRequested`; see example programs for more info. The exception is iOS, where `Closed` must be replaced by `Destroyed`. diff --git a/app/vendor/rune/vendor/winit/src/changelog/v0.14.md b/app/vendor/rune/vendor/winit/src/changelog/v0.14.md new file mode 100644 index 0000000..822ae20 --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/changelog/v0.14.md @@ -0,0 +1,21 @@ +## 0.14.0 + +- Created the `Copy`, `Paste` and `Cut` `VirtualKeyCode`s and added support for them on X11 and Wayland +- Fix `.with_decorations(false)` in macOS +- On Mac, `NSWindow` and supporting objects might be alive long after they were `closed` which resulted in apps consuming more heap then needed. Mainly it was affecting multi window applications. Not expecting any user visible change of behaviour after the fix. +- Fix regression of Window platform extensions for macOS where `NSFullSizeContentViewWindowMask` was not being correctly applied to `.fullsize_content_view`. +- Corrected `get_position` on Windows to be relative to the screen rather than to the taskbar. +- Corrected `Moved` event on Windows to use position values equivalent to those returned by `get_position`. It previously supplied client area positions instead of window positions, and would additionally interpret negative values as being very large (around `u16::MAX`). +- Implemented `Moved` event on macOS. +- On X11, the `Moved` event correctly use window positions rather than client area positions. Additionally, a stray `Moved` that unconditionally accompanied `Resized` with the client area position relative to the parent has been eliminated; `Moved` is still received alongside `Resized`, but now only once and always correctly. +- On Windows, implemented all variants of `DeviceEvent` other than `Text`. Mouse `DeviceEvent`s are now received even if the window isn't in the foreground. +- `DeviceId` on Windows is no longer a unit struct, and now contains a `u32`. For `WindowEvent`s, this will always be 0, but on `DeviceEvent`s it will be the handle to that device. `DeviceIdExt::get_persistent_identifier` can be used to acquire a unique identifier for that device that persists across replugs/reboots/etc. +- Corrected `run_forever` on X11 to stop discarding `Awakened` events. +- Various safety and correctness improvements to the X11 backend internals. +- Fixed memory leak on X11 every time the mouse entered the window. +- On X11, drag and drop now works reliably in release mode. +- Added `WindowBuilderExt::with_resize_increments` and `WindowBuilderExt::with_base_size` to X11, allowing for more optional hints to be set. +- Rework of the wayland backend, migrating it to use [Smithay's Client Toolkit](https://github.com/Smithay/client-toolkit). +- Added `WindowBuilder::with_window_icon` and `Window::set_window_icon`, finally making it possible to set the window icon on Windows and X11. The `icon_loading` feature can be enabled to allow for icons to be easily loaded; see example program `window_icon.rs` for usage. +- Windows additionally has `WindowBuilderExt::with_taskbar_icon` and `WindowExt::set_taskbar_icon`. +- On Windows, fix panic when trying to call `set_fullscreen(None)` on a window that has not been fullscreened prior. diff --git a/app/vendor/rune/vendor/winit/src/changelog/v0.15.md b/app/vendor/rune/vendor/winit/src/changelog/v0.15.md new file mode 100644 index 0000000..f5fc485 --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/changelog/v0.15.md @@ -0,0 +1,42 @@ +## 0.15.1 + +- On X11, the `Moved` event is no longer sent when the window is resized without changing position. +- `MouseCursor` and `CursorState` now implement `Default`. +- `WindowBuilder::with_resizable` implemented for Windows, X11, Wayland, and macOS. +- `Window::set_resizable` implemented for Windows, X11, Wayland, and macOS. +- On X11, if the monitor's width or height in millimeters is reported as 0, the DPI is now 1.0 instead of +inf. +- On X11, the environment variable `WINIT_HIDPI_FACTOR` has been added for overriding DPI factor. +- On X11, enabling transparency no longer causes the window contents to flicker when resizing. +- On X11, `with_override_redirect` now actually enables override redirect. +- macOS now generates `VirtualKeyCode::LAlt` and `VirtualKeyCode::RAlt` instead of `None` for both. +- On macOS, `VirtualKeyCode::RWin` and `VirtualKeyCode::LWin` are no longer switched. +- On macOS, windows without decorations can once again be resized. +- Fixed race conditions when creating an `EventsLoop` on X11, most commonly manifesting as `"[xcb] Unknown sequence number while processing queue"`. +- On macOS, `CursorMoved` and `MouseInput` events are only generated if they occurs within the window's client area. +- On macOS, resizing the window no longer generates a spurious `MouseInput` event. + +## 0.15.0 + +- `Icon::to_cardinals` is no longer public, since it was never supposed to be. +- Wayland: improve diagnostics if initialization fails +- Fix some system event key doesn't work when focused, do not block keyevent forward to system on macOS +- On X11, the scroll wheel position is now correctly reset on i3 and other WMs that have the same quirk. +- On X11, `Window::get_current_monitor` now reliably returns the correct monitor. +- On X11, `Window::hidpi_factor` returns values from XRandR rather than the inaccurate values previously queried from the core protocol. +- On X11, the primary monitor is detected correctly even when using versions of XRandR less than 1.5. +- `MonitorId` now implements `Debug`. +- Fixed bug on macOS where using `with_decorations(false)` would cause `set_decorations(true)` to produce a transparent titlebar with no title. +- Implemented `MonitorId::get_position` on macOS. +- On macOS, `Window::get_current_monitor` now returns accurate values. +- Added `WindowBuilderExt::with_resize_increments` to macOS. +- **Breaking:** On X11, `WindowBuilderExt::with_resize_increments` and `WindowBuilderExt::with_base_size` now take `u32` values rather than `i32`. +- macOS keyboard handling has been overhauled, allowing for the use of dead keys, IME, etc. Right modifier keys are also no longer reported as being left. +- Added the `Window::set_ime_spot(x: i32, y: i32)` method, which is implemented on X11 and macOS. +- **Breaking**: `os::unix::WindowExt::send_xim_spot(x: i16, y: i16)` no longer exists. Switch to the new `Window::set_ime_spot(x: i32, y: i32)`, which has equivalent functionality. +- Fixed detection of `Pause` and `Scroll` keys on Windows. +- On Windows, alt-tabbing while the cursor is grabbed no longer makes it impossible to re-grab the cursor. +- On Windows, using `CursorState::Hide` when the cursor is grabbed now ungrabs the cursor first. +- Implemented `MouseCursor::NoneCursor` on Windows. +- Added `WindowBuilder::with_always_on_top` and `Window::set_always_on_top`. Implemented on Windows, macOS, and X11. +- On X11, `WindowBuilderExt` now has `with_class`, `with_override_redirect`, and `with_x11_window_type` to allow for more control over window creation. `WindowExt` additionally has `set_urgent`. +- More hints are set by default on X11, including `_NET_WM_PID` and `WM_CLIENT_MACHINE`. Note that prior to this, the `WM_CLASS` hint was automatically set to whatever value was passed to `with_title`. It's now set to the executable name to better conform to expectations and the specification; if this is undesirable, you must explicitly use `WindowBuilderExt::with_class`. diff --git a/app/vendor/rune/vendor/winit/src/changelog/v0.16.md b/app/vendor/rune/vendor/winit/src/changelog/v0.16.md new file mode 100644 index 0000000..126ad9f --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/changelog/v0.16.md @@ -0,0 +1,32 @@ +## 0.16.2 + +- On Windows, non-resizable windows now have the maximization button disabled. This is consistent with behavior on macOS and popular X11 WMs. +- Corrected incorrect `unreachable!` usage when guessing the DPI factor with no detected monitors. + +## 0.16.1 + +- Added logging through `log`. Logging will become more extensive over time. +- On X11 and Windows, the window's DPI factor is guessed before creating the window. This _greatly_ cuts back on unsightly auto-resizing that would occur immediately after window creation. +- Fixed X11 backend compilation for environments where `c_char` is unsigned. + +## 0.16.0 + +- Windows additionally has `WindowBuilderExt::with_no_redirection_bitmap`. +- **Breaking:** Removed `VirtualKeyCode::LMenu` and `VirtualKeyCode::RMenu`; Windows now generates `VirtualKeyCode::LAlt` and `VirtualKeyCode::RAlt` instead. +- On X11, exiting fullscreen no longer leaves the window in the monitor's top left corner. +- **Breaking:** `Window::hidpi_factor` has been renamed to `Window::get_hidpi_factor` for better consistency. `WindowEvent::HiDPIFactorChanged` has been renamed to `WindowEvent::HiDpiFactorChanged`. DPI factors are always represented as `f64` instead of `f32` now. +- The Windows backend is now DPI aware. `WindowEvent::HiDpiFactorChanged` is implemented, and `MonitorId::get_hidpi_factor` and `Window::hidpi_factor` return accurate values. +- Implemented `WindowEvent::HiDpiFactorChanged` on X11. +- On macOS, `Window::set_cursor_position` is now relative to the client area. +- On macOS, setting the maximum and minimum dimensions now applies to the client area dimensions rather than to the window dimensions. +- On iOS, `MonitorId::get_dimensions` has been implemented and both `MonitorId::get_hidpi_factor` and `Window::get_hidpi_factor` return accurate values. +- On Emscripten, `MonitorId::get_hidpi_factor` now returns the same value as `Window::get_hidpi_factor` (it previously would always return 1.0). +- **Breaking:** The entire API for sizes, positions, etc. has changed. In the majority of cases, winit produces and consumes positions and sizes as `LogicalPosition` and `LogicalSize`, respectively. The notable exception is `MonitorId` methods, which deal in `PhysicalPosition` and `PhysicalSize`. See the documentation for specifics and explanations of the types. Additionally, winit automatically conserves logical size when the DPI factor changes. +- **Breaking:** All deprecated methods have been removed. For `Window::platform_display` and `Window::platform_window`, switch to the appropriate platform-specific `WindowExt` methods. For `Window::get_inner_size_points` and `Window::get_inner_size_pixels`, use the `LogicalSize` returned by `Window::get_inner_size` and convert as needed. +- HiDPI support for Wayland. +- `EventsLoop::get_available_monitors` and `EventsLoop::get_primary_monitor` now have identical counterparts on `Window`, so this information can be acquired without an `EventsLoop` borrow. +- `AvailableMonitorsIter` now implements `Debug`. +- Fixed quirk on macOS where certain keys would generate characters at twice the normal rate when held down. +- On X11, all event loops now share the same `XConnection`. +- **Breaking:** `Window::set_cursor_state` and `CursorState` enum removed in favor of the more composable `Window::grab_cursor` and `Window::hide_cursor`. As a result, grabbing the cursor no longer automatically hides it; you must call both methods to retain the old behavior on Windows and macOS. `Cursor::NoneCursor` has been removed, as it's no longer useful. +- **Breaking:** `Window::set_cursor_position` now returns `Result<(), String>`, thus allowing for `Box<Error>` conversion via `?`. diff --git a/app/vendor/rune/vendor/winit/src/changelog/v0.17.md b/app/vendor/rune/vendor/winit/src/changelog/v0.17.md new file mode 100644 index 0000000..0a1abc8 --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/changelog/v0.17.md @@ -0,0 +1,23 @@ +## 0.17.2 + +- On macOS, fix `<C-Tab>` so applications receive the event. +- On macOS, fix `<Cmd-{key}>` so applications receive the event. +- On Wayland, key press events will now be repeated. + +## 0.17.1 + +- On X11, prevent a compilation failure in release mode for versions of Rust greater than or equal to 1.30. +- Fixed deadlock that broke fullscreen mode on Windows. + +## 0.17.0 + +- Cocoa and core-graphics updates. +- Fixed thread-safety issues in several `Window` functions on Windows. +- On MacOS, the key state for modifiers key events is now properly set. +- On iOS, the view is now set correctly. This makes it possible to render things (instead of being stuck on a black screen), and touch events work again. +- Added NetBSD support. +- **Breaking:** On iOS, `UIView` is now the default root view. `WindowBuilderExt::with_root_view_class` can be used to set the root view objective-c class to `GLKView` (OpenGLES) or `MTKView` (Metal/MoltenVK). +- On iOS, the `UIApplication` is not started until `Window::new` is called. +- Fixed thread unsafety with cursor hiding on macOS. +- On iOS, fixed the size of the `JmpBuf` type used for `setjmp`/`longjmp` calls. Previously this was a buffer overflow on most architectures. +- On Windows, use cached window DPI instead of repeatedly querying the system. This fixes sporadic crashes on Windows 7. diff --git a/app/vendor/rune/vendor/winit/src/changelog/v0.18.md b/app/vendor/rune/vendor/winit/src/changelog/v0.18.md new file mode 100644 index 0000000..e98df5b --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/changelog/v0.18.md @@ -0,0 +1,52 @@ +## 0.18.1 + +- On macOS, fix `Yen` (JIS) so applications receive the event. +- On X11 with a tiling WM, fixed high CPU usage when moving windows across monitors. +- On X11, fixed panic caused by dropping the window before running the event loop. +- on macOS, added `WindowExt::set_simple_fullscreen` which does not require a separate space +- Introduce `WindowBuilderExt::with_app_id` to allow setting the application ID on Wayland. +- On Windows, catch panics in event loop child thread and forward them to the parent thread. This prevents an invocation of undefined behavior due to unwinding into foreign code. +- On Windows, fix issue where resizing or moving window combined with grabbing the cursor would freeze program. +- On Windows, fix issue where resizing or moving window would eat `Awakened` events. +- On Windows, exiting fullscreen after entering fullscreen with disabled decorations no longer shrinks window. +- On X11, fixed a segfault when using virtual monitors with XRandR. +- Derive `Ord` and `PartialOrd` for `VirtualKeyCode` enum. +- On Windows, fix issue where hovering or dropping a non file item would create a panic. +- On Wayland, fix resizing and DPI calculation when a `wl_output` is removed without sending a `leave` event to the `wl_surface`, such as disconnecting a monitor from a laptop. +- On Wayland, DPI calculation is handled by smithay-client-toolkit. +- On X11, `WindowBuilder::with_min_dimensions` and `WindowBuilder::with_max_dimensions` now correctly account for DPI. +- Added support for generating dummy `DeviceId`s and `WindowId`s to better support unit testing. +- On macOS, fixed unsoundness in drag-and-drop that could result in drops being rejected. +- On macOS, implemented `WindowEvent::Refresh`. +- On macOS, all `MouseCursor` variants are now implemented and the cursor will no longer reset after unfocusing. +- Removed minimum supported Rust version guarantee. + +## 0.18.0 + +- **Breaking:** `image` crate upgraded to 0.20. This is exposed as part of the `icon_loading` API. +- On Wayland, pointer events will now provide the current modifiers state. +- On Wayland, titles will now be displayed in the window header decoration. +- On Wayland, key repetition is now ended when keyboard loses focus. +- On Wayland, windows will now use more stylish and modern client side decorations. +- On Wayland, windows will use server-side decorations when available. +- **Breaking:** Added support for F16-F24 keys (variants were added to the `VirtualKeyCode` enum). +- Fixed graphical glitches when resizing on Wayland. +- On Windows, fix freezes when performing certain actions after a window resize has been triggered. Reintroduces some visual artifacts when resizing. +- Updated window manager hints under X11 to v1.5 of [Extended Window Manager Hints](https://specifications.freedesktop.org/wm-spec/wm-spec-1.5.html#idm140200472629520). +- Added `WindowBuilderExt::with_gtk_theme_variant` to X11-specific `WindowBuilder` functions. +- Fixed UTF8 handling bug in X11 `set_title` function. +- On Windows, `Window::set_cursor` now applies immediately instead of requiring specific events to occur first. +- On Windows, the `HoveredFile` and `HoveredFileCancelled` events are now implemented. +- On Windows, fix `Window::set_maximized`. +- On Windows 10, fix transparency (#260). +- On macOS, fix modifiers during key repeat. +- Implemented the `Debug` trait for `Window`, `EventsLoop`, `EventsLoopProxy` and `WindowBuilder`. +- On X11, now a `Resized` event will always be generated after a DPI change to ensure the window's logical size is consistent with the new DPI. +- Added further clarifications to the DPI docs. +- On Linux, if neither X11 nor Wayland manage to initialize, the corresponding panic now consists of a single line only. +- Add optional `serde` feature with implementations of `Serialize`/`Deserialize` for DPI types and various event types. +- Add `PartialEq`, `Eq`, and `Hash` implementations on public types that could have them but were missing them. +- On X11, drag-and-drop receiving an unsupported drop type can no longer cause the WM to freeze. +- Fix issue whereby the OpenGL context would not appear at startup on macOS Mojave (#1069). +- **Breaking:** Removed `From<NSApplicationActivationPolicy>` impl from `ActivationPolicy` on macOS. +- On macOS, the application can request the user's attention with `WindowExt::request_user_attention`. diff --git a/app/vendor/rune/vendor/winit/src/changelog/v0.19.md b/app/vendor/rune/vendor/winit/src/changelog/v0.19.md new file mode 100644 index 0000000..65aefef --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/changelog/v0.19.md @@ -0,0 +1,27 @@ +## 0.19.1 + +- On Wayland, added a `get_wayland_display` function to `EventsLoopExt`. +- On Windows, fix `CursorMoved(0, 0)` getting dispatched on window focus. +- On macOS, fix command key event left and right reverse. +- On FreeBSD, NetBSD, and OpenBSD, fix build of X11 backend. +- On Linux, the numpad's add, subtract and divide keys are now mapped to the `Add`, `Subtract` and `Divide` virtual key codes +- On macOS, the numpad's subtract key has been added to the `Subtract` mapping +- On Wayland, the numpad's home, end, page up and page down keys are now mapped to the `Home`, `End`, `PageUp` and `PageDown` virtual key codes +- On Windows, fix icon not showing up in corner of window. +- On X11, change DPI scaling factor behavior. First, winit tries to read it from "Xft.dpi" XResource, and uses DPI calculation from xrandr dimensions as fallback behavior. + +## 0.19.0 + +- On X11, we will use the faster `XRRGetScreenResourcesCurrent` function instead of `XRRGetScreenResources` when available. +- On macOS, fix keycodes being incorrect when using a non-US keyboard layout. +- On Wayland, fix `with_title()` not setting the windows title +- On Wayland, add `set_wayland_theme()` to control client decoration color theme +- Added serde serialization to `os::unix::XWindowType`. +- **Breaking:** Remove the `icon_loading` feature and the associated `image` dependency. +- On X11, make event loop thread safe by replacing XNextEvent with select(2) and XCheckIfEvent +- On Windows, fix malformed function pointer typecast that could invoke undefined behavior. +- Refactored Windows state/flag-setting code. +- On Windows, hiding the cursor no longer hides the cursor for all Winit windows - just the one `hide_cursor` was called on. +- On Windows, cursor grabs used to get perpetually canceled when the grabbing window lost focus. Now, cursor grabs automatically get re-initialized when the window regains focus and the mouse moves over the client area. +- On Windows, only vertical mouse wheel events were handled. Now, horizontal mouse wheel events are also handled. +- On Windows, ignore the AltGr key when populating the `ModifiersState` type. diff --git a/app/vendor/rune/vendor/winit/src/changelog/v0.20.md b/app/vendor/rune/vendor/winit/src/changelog/v0.20.md new file mode 100644 index 0000000..eb4ba6a --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/changelog/v0.20.md @@ -0,0 +1,200 @@ +## 0.20.0 + +- On X11, fix `ModifiersChanged` emitting incorrect modifier change events +- **Breaking**: Overhaul how Winit handles DPI: + - Window functions and events now return `PhysicalSize` instead of `LogicalSize`. + - Functions that take `Size` or `Position` types can now take either `Logical` or `Physical` types. + - `hidpi_factor` has been renamed to `scale_factor`. + - `HiDpiFactorChanged` has been renamed to `ScaleFactorChanged`, and lets you control how the OS + resizes the window in response to the change. + - On X11, deprecate `WINIT_HIDPI_FACTOR` environment variable in favor of `WINIT_X11_SCALE_FACTOR`. + - `Size` and `Position` types are now generic over their exact pixel type. + +## 0.20.0-alpha6 + +- On macOS, fix `set_cursor_visible` hides cursor outside of window. +- On macOS, fix `CursorEntered` and `CursorLeft` events fired at old window size. +- On macOS, fix error when `set_fullscreen` is called during fullscreen transition. +- On all platforms except mobile and WASM, implement `Window::set_minimized`. +- On X11, fix `CursorEntered` event being generated for non-winit windows. +- On macOS, fix crash when starting maximized without decorations. +- On macOS, fix application not terminating on `run_return`. +- On Wayland, fix cursor icon updates on window borders when using CSD. +- On Wayland, under mutter(GNOME Wayland), fix CSD being behind the status bar, when starting window in maximized mode. +- On Windows, theme the title bar according to whether the system theme is "Light" or "Dark". +- Added `WindowEvent::ThemeChanged` variant to handle changes to the system theme. Currently only implemented on Windows. +- **Breaking**: Changes to the `RedrawRequested` event (#1041): + - `RedrawRequested` has been moved from `WindowEvent` to `Event`. + - `EventsCleared` has been renamed to `MainEventsCleared`. + - `RedrawRequested` is now issued only after `MainEventsCleared`. + - `RedrawEventsCleared` is issued after each set of `RedrawRequested` events. +- Implement synthetic window focus key events on Windows. +- **Breaking**: Change `ModifiersState` to a `bitflags` struct. +- On Windows, implement `VirtualKeyCode` translation for `LWin` and `RWin`. +- On Windows, fix closing the last opened window causing `DeviceEvent`s to stop getting emitted. +- On Windows, fix `Window::set_visible` not setting internal flags correctly. This resulted in some weird behavior. +- Add `DeviceEvent::ModifiersChanged`. + - Deprecate `modifiers` fields in other events in favor of `ModifiersChanged`. +- On X11, `WINIT_HIDPI_FACTOR` now dominates `Xft.dpi` when picking DPI factor for output. +- On X11, add special value `randr` for `WINIT_HIDPI_FACTOR` to make winit use self computed DPI factor instead of the one from `Xft.dpi`. + +## 0.20.0-alpha5 + +- On macOS, fix application termination on `ControlFlow::Exit` +- On Windows, fix missing `ReceivedCharacter` events when Alt is held. +- On macOS, stop emitting private corporate characters in `ReceivedCharacter` events. +- On X11, fix misreporting DPI factor at startup. +- On X11, fix events not being reported when using `run_return`. +- On X11, fix key modifiers being incorrectly reported. +- On X11, fix window creation hanging when another window is fullscreen. +- On Windows, fix focusing unfocused windows when switching from fullscreen to windowed. +- On X11, fix reporting incorrect DPI factor when waking from suspend. +- Change `EventLoopClosed` to contain the original event. +- **Breaking**: Add `is_synthetic` field to `WindowEvent` variant `KeyboardInput`, + indicating that the event is generated by winit. +- On X11, generate synthetic key events for keys held when a window gains or loses focus. +- On X11, issue a `CursorMoved` event when a `Touch` event occurs, + as X11 implicitly moves the cursor for such events. + +## 0.20.0-alpha4 + +- Add web support via the 'stdweb' or 'web-sys' features +- On Windows, implemented function to get HINSTANCE +- On macOS, implement `run_return`. +- On iOS, fix inverted parameter in `set_prefers_home_indicator_hidden`. +- On X11, performance is improved when rapidly calling `Window::set_cursor_icon`. +- On iOS, fix improper `msg_send` usage that was UB and/or would break if `!` is stabilized. +- On Windows, unset `maximized` when manually changing the window's position or size. +- On Windows, add touch pressure information for touch events. +- On macOS, differentiate between `CursorIcon::Grab` and `CursorIcon::Grabbing`. +- On Wayland, fix event processing sometimes stalling when using OpenGL with vsync. +- Officially remove the Emscripten backend. +- On Windows, fix handling of surrogate pairs when dispatching `ReceivedCharacter`. +- On macOS 10.15, fix freeze upon exiting exclusive fullscreen mode. +- On iOS, fix panic upon closing the app. +- On X11, allow setting multiple `XWindowType`s. +- On iOS, fix null window on initial `HiDpiFactorChanged` event. +- On Windows, fix fullscreen window shrinking upon getting restored to a normal window. +- On macOS, fix events not being emitted during modal loops, such as when windows are being resized + by the user. +- On Windows, fix hovering the mouse over the active window creating an endless stream of CursorMoved events. +- Always dispatch a `RedrawRequested` event after creating a new window. +- On X11, return dummy monitor data to avoid panicking when no monitors exist. +- On X11, prevent stealing input focus when creating a new window. + Only steal input focus when entering fullscreen mode. +- On Wayland, fixed DeviceEvents for relative mouse movement is not always produced +- On Wayland, add support for set_cursor_visible and set_cursor_grab. +- On Wayland, fixed DeviceEvents for relative mouse movement is not always produced. +- Removed `derivative` crate dependency. +- On Wayland, add support for set_cursor_icon. +- Use `impl Iterator<Item = MonitorHandle>` instead of `AvailableMonitorsIter` consistently. +- On macOS, fix fullscreen state being updated after entering fullscreen instead of before, + resulting in `Window::fullscreen` returning the old state in `Resized` events instead of + reflecting the new fullscreen state +- On X11, fix use-after-free during window creation +- On Windows, disable monitor change keyboard shortcut while in exclusive fullscreen. +- On Windows, ensure that changing a borderless fullscreen window's monitor via keyboard shortcuts keeps the window fullscreen on the new monitor. +- Prevent `EventLoop::new` and `EventLoop::with_user_event` from getting called outside the main thread. + - This is because some platforms cannot run the event loop outside the main thread. Preventing this + reduces the potential for cross-platform compatibility gotchyas. +- On Windows and Linux X11/Wayland, add platform-specific functions for creating an `EventLoop` outside the main thread. +- On Wayland, drop resize events identical to the current window size. +- On Windows, fix window rectangle not getting set correctly on high-DPI systems. + +## 0.20.0-alpha3 + +- On macOS, drop the run closure on exit. +- On Windows, location of `WindowEvent::Touch` are window client coordinates instead of screen coordinates. +- On X11, fix delayed events after window redraw. +- On macOS, add `WindowBuilderExt::with_disallow_hidpi` to have the option to turn off best resolution openGL surface. +- On Windows, screen saver won't start if the window is in fullscreen mode. +- Change all occurrences of the `new_user_event` method to `with_user_event`. +- On macOS, the dock and the menu bar are now hidden in fullscreen mode. +- `Window::set_fullscreen` now takes `Option<Fullscreen>` where `Fullscreen` + consists of `Fullscreen::Exclusive(VideoMode)` and + `Fullscreen::Borderless(MonitorHandle)` variants. + - Adds support for exclusive fullscreen mode. +- On iOS, add support for hiding the home indicator. +- On iOS, add support for deferring system gestures. +- On iOS, fix a crash that occurred while acquiring a monitor's name. +- On iOS, fix armv7-apple-ios compile target. +- Removed the `T: Clone` requirement from the `Clone` impl of `EventLoopProxy<T>`. +- On iOS, disable overscan compensation for external displays (removes black + bars surrounding the image). +- On Linux, the functions `is_wayland`, `is_x11`, `xlib_xconnection` and `wayland_display` have been moved to a new `EventLoopWindowTargetExtUnix` trait. +- On iOS, add `set_prefers_status_bar_hidden` extension function instead of + hijacking `set_decorations` for this purpose. +- On macOS and iOS, corrected the auto trait impls of `EventLoopProxy`. +- On iOS, add touch pressure information for touch events. +- Implement `raw_window_handle::HasRawWindowHandle` for `Window` type on all supported platforms. +- On macOS, fix the signature of `-[NSView drawRect:]`. +- On iOS, fix the behavior of `ControlFlow::Poll`. It wasn't polling if that was the only mode ever used by the application. +- On iOS, fix DPI sent out by views on creation was `0.0` - now it gives a reasonable number. +- On iOS, RedrawRequested now works for gl/metal backed views. +- On iOS, RedrawRequested is generally ordered after EventsCleared. + +## 0.20.0-alpha2 + +- On X11, non-resizable windows now have maximize explicitly disabled. +- On Windows, support paths longer than MAX_PATH (260 characters) in `WindowEvent::DroppedFile` + and `WindowEvent::HoveredFile`. +- On Mac, implement `DeviceEvent::Button`. +- Change `Event::Suspended(true / false)` to `Event::Suspended` and `Event::Resumed`. +- On X11, fix sanity check which checks that a monitor's reported width and height (in millimeters) are non-zero when calculating the DPI factor. +- Revert the use of invisible surfaces in Wayland, which introduced graphical glitches with OpenGL (#835) +- On X11, implement `_NET_WM_PING` to allow desktop environment to kill unresponsive programs. +- On Windows, when a window is initially invisible, it won't take focus from the existing visible windows. +- On Windows, fix multiple calls to `request_redraw` during `EventsCleared` sending multiple `RedrawRequested events.` +- On Windows, fix edge case where `RedrawRequested` could be dispatched before input events in event loop iteration. +- On Windows, fix timing issue that could cause events to be improperly dispatched after `RedrawRequested` but before `EventsCleared`. +- On macOS, drop unused Metal dependency. +- On Windows, fix the trail effect happening on transparent decorated windows. Borderless (or un-decorated) windows were not affected. +- On Windows, fix `with_maximized` not properly setting window size to entire window. +- On macOS, change `WindowExtMacOS::request_user_attention()` to take an `enum` instead of a `bool`. + +## 0.20.0-alpha1 + +- Changes below are considered **breaking**. +- Change all occurrences of `EventsLoop` to `EventLoop`. +- Previously flat API is now exposed through `event`, `event_loop`, `monitor`, and `window` modules. +- `os` module changes: + - Renamed to `platform`. + - All traits now have platform-specific suffixes. + - Exposes new `desktop` module on Windows, Mac, and Linux. +- Changes to event loop types: + - `EventLoopProxy::wakeup` has been removed in favor of `send_event`. + - **Major:** New `run` method drives winit event loop. + - Returns `!` to ensure API behaves identically across all supported platforms. + - This allows `emscripten` implementation to work without lying about the API. + - `ControlFlow`'s variants have been replaced with `Wait`, `WaitUntil(Instant)`, `Poll`, and `Exit`. + - Is read after `EventsCleared` is processed. + - `Wait` waits until new events are available. + - `WaitUntil` waits until either new events are available or the provided time has been reached. + - `Poll` instantly resumes the event loop. + - `Exit` aborts the event loop. + - Takes a closure that implements `'static + FnMut(Event<T>, &EventLoop<T>, &mut ControlFlow)`. + - `&EventLoop<T>` is provided to allow new `Window`s to be created. + - **Major:** `platform::desktop` module exposes `EventLoopExtDesktop` trait with `run_return` method. + - Behaves identically to `run`, but returns control flow to the calling context and can take non-`'static` closures. + - `EventLoop`'s `poll_events` and `run_forever` methods have been removed in favor of `run` and `run_return`. +- Changes to events: + - Remove `Event::Awakened` in favor of `Event::UserEvent(T)`. + - Can be sent with `EventLoopProxy::send_event`. + - Rename `WindowEvent::Refresh` to `WindowEvent::RedrawRequested`. + - `RedrawRequested` can be sent by the user with the `Window::request_redraw` method. + - `EventLoop`, `EventLoopProxy`, and `Event` are now generic over `T`, for use in `UserEvent`. + - **Major:** Add `NewEvents(StartCause)`, `EventsCleared`, and `LoopDestroyed` variants to `Event`. + - `NewEvents` is emitted when new events are ready to be processed by event loop. + - `StartCause` describes why new events are available, with `ResumeTimeReached`, `Poll`, `WaitCancelled`, and `Init` (sent once at start of loop). + - `EventsCleared` is emitted when all available events have been processed. + - Can be used to perform logic that depends on all events being processed (e.g. an iteration of a game loop). + - `LoopDestroyed` is emitted when the `run` or `run_return` method is about to exit. +- Rename `MonitorId` to `MonitorHandle`. +- Removed `serde` implementations from `ControlFlow`. +- Rename several functions to improve both internal consistency and compliance with Rust API guidelines. +- Remove `WindowBuilder::multitouch` field, since it was only implemented on a few platforms. Multitouch is always enabled now. +- **Breaking:** On macOS, change `ns` identifiers to use snake_case for consistency with iOS's `ui` identifiers. +- Add `MonitorHandle::video_modes` method for retrieving supported video modes for the given monitor. +- On Wayland, the window now exists even if nothing has been drawn. +- On Windows, fix initial dimensions of a fullscreen window. +- On Windows, Fix transparent borderless windows rendering wrong. diff --git a/app/vendor/rune/vendor/winit/src/changelog/v0.21.md b/app/vendor/rune/vendor/winit/src/changelog/v0.21.md new file mode 100644 index 0000000..48f3d35 --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/changelog/v0.21.md @@ -0,0 +1,16 @@ +## 0.21.0 + +- On Windows, fixed "error: linking with `link.exe` failed: exit code: 1120" error on older versions of windows. +- On macOS, fix set_minimized(true) works only with decorations. +- On macOS, add `hide_application` to `EventLoopWindowTarget` via a new `EventLoopWindowTargetExtMacOS` trait. `hide_application` will hide the entire application by calling `-[NSApplication hide: nil]`. +- On macOS, fix not sending ReceivedCharacter event for specific keys combinations. +- On macOS, fix `CursorMoved` event reporting the cursor position using logical coordinates. +- On macOS, fix issue where unbundled applications would sometimes open without being focused. +- On macOS, fix `run_return` does not return unless it receives a message. +- On Windows, fix bug where `RedrawRequested` would only get emitted every other iteration of the event loop. +- On X11, fix deadlock on window state when handling certain window events. +- `WindowBuilder` now implements `Default`. +- **Breaking:** `WindowEvent::CursorMoved` changed to `f64` units, preserving high-precision data supplied by most backends +- On Wayland, fix coordinates in mouse events when scale factor isn't 1 +- On Web, add the ability to provide a custom canvas +- **Breaking:** On Wayland, the `WaylandTheme` struct has been replaced with a `Theme` trait, allowing for extra configuration diff --git a/app/vendor/rune/vendor/winit/src/changelog/v0.22.md b/app/vendor/rune/vendor/winit/src/changelog/v0.22.md new file mode 100644 index 0000000..07bc1ef --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/changelog/v0.22.md @@ -0,0 +1,37 @@ +## 0.22.2 + +- Added Clone implementation for 'static events. +- On Windows, fix window intermittently hanging when `ControlFlow` was set to `Poll`. +- On Windows, fix `WindowBuilder::with_maximized` being ignored. +- On Android, minimal platform support. +- On iOS, touch positions are now properly converted to physical pixels. +- On macOS, updated core-* dependencies and cocoa + +## 0.22.1 + +- On X11, fix `ResumeTimeReached` being fired too early. +- On Web, replaced zero timeout for `ControlFlow::Poll` with `requestAnimationFrame` +- On Web, fix a possible panic during event handling +- On macOS, fix `EventLoopProxy` leaking memory for every instance. + +## 0.22.0 + +- On Windows, fix minor timing issue in wait_until_time_or_msg +- On Windows, rework handling of request_redraw() to address panics. +- On macOS, fix `set_simple_screen` to remember frame excluding title bar. +- On Wayland, fix coordinates in touch events when scale factor isn't 1. +- On Wayland, fix color from `close_button_icon_color` not applying. +- Ignore locale if unsupported by X11 backend +- On Wayland, Add HiDPI cursor support +- On Web, add the ability to query "Light" or "Dark" system theme send `ThemeChanged` on change. +- Fix `Event::to_static` returning `None` for user events. +- On Wayland, Hide CSD for fullscreen windows. +- On Windows, ignore spurious mouse move messages. +- **Breaking:** Move `ModifiersChanged` variant from `DeviceEvent` to `WindowEvent`. +- On Windows, add `IconExtWindows` trait which exposes creating an `Icon` from an external file or embedded resource +- Add `BadIcon::OsError` variant for when OS icon functionality fails +- On Windows, fix crash at startup on systems that do not properly support Windows' Dark Mode +- Revert On macOS, fix not sending ReceivedCharacter event for specific keys combinations. +- on macOS, fix incorrect ReceivedCharacter events for some key combinations. +- **Breaking:** Use `i32` instead of `u32` for position type in `WindowEvent::Moved`. +- On macOS, a mouse motion event is now generated before every mouse click. diff --git a/app/vendor/rune/vendor/winit/src/changelog/v0.23.md b/app/vendor/rune/vendor/winit/src/changelog/v0.23.md new file mode 100644 index 0000000..33ea2ab --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/changelog/v0.23.md @@ -0,0 +1,65 @@ +## 0.23.0 + +- On iOS, fixed support for the "Debug View Hierarchy" feature in Xcode. +- On all platforms, `available_monitors` and `primary_monitor` are now on `EventLoopWindowTarget` rather than `EventLoop` to list monitors event in the event loop. +- On Unix, X11 and Wayland are now optional features (enabled by default) +- On X11, fix deadlock when calling `set_fullscreen_inner`. +- On Web, prevent the webpage from scrolling when the user is focused on a winit canvas +- On Web, calling `window.set_cursor_icon` no longer breaks HiDPI scaling +- On Windows, drag and drop is now optional (enabled by default) and can be disabled with `WindowBuilderExtWindows::with_drag_and_drop(false)`. +- On Wayland, fix deadlock when calling to `set_inner_size` from a callback. +- On macOS, add `hide__other_applications` to `EventLoopWindowTarget` via existing `EventLoopWindowTargetExtMacOS` trait. `hide_other_applications` will hide other applications by calling `-[NSApplication hideOtherApplications: nil]`. +- On android added support for `run_return`. +- On MacOS, Fixed fullscreen and dialog support for `run_return`. +- On Windows, fix bug where we'd try to emit `MainEventsCleared` events during nested win32 event loops. +- On Web, use mouse events if pointer events aren't supported. This affects Safari. +- On Windows, `set_ime_position` is now a no-op instead of a runtime crash. +- On Android, `set_fullscreen` is now a no-op instead of a runtime crash. +- On iOS and Android, `set_inner_size` is now a no-op instead of a runtime crash. +- On Android, fix `ControlFlow::Poll` not polling the Android event queue. +- On macOS, add `NSWindow.hasShadow` support. +- On Web, fix vertical mouse wheel scrolling being inverted. +- On Web, implement mouse capturing for click-dragging out of the canvas. +- On Web, fix `ControlFlow::Exit` not properly handled. +- On Web (web-sys only), send `WindowEvent::ScaleFactorChanged` event when `window.devicePixelRatio` is changed. +- **Breaking:** On Web, `set_cursor_position` and `set_cursor_grab` will now always return an error. +- **Breaking:** `PixelDelta` scroll events now return a `PhysicalPosition`. +- On NetBSD, fixed crash due to incorrect detection of the main thread. +- **Breaking:** On X11, `-` key is mapped to the `Minus` virtual key code, instead of `Subtract`. +- On macOS, fix inverted horizontal scroll. +- **Breaking:** `current_monitor` now returns `Option<MonitorHandle>`. +- **Breaking:** `primary_monitor` now returns `Option<MonitorHandle>`. +- On macOS, updated core-* dependencies and cocoa. +- Bump `parking_lot` to 0.11 +- On Android, bump `ndk`, `ndk-sys` and `ndk-glue` to 0.2. Checkout the new ndk-glue main proc attribute. +- On iOS, fixed starting the app in landscape where the view still had portrait dimensions. +- Deprecate the stdweb backend, to be removed in a future release +- **Breaking:** Prefixed virtual key codes `Add`, `Multiply`, `Divide`, `Decimal`, and `Subtract` with `Numpad`. +- Added `Asterisk` and `Plus` virtual key codes. +- On Web (web-sys only), the `Event::LoopDestroyed` event is correctly emitted when leaving the page. +- On Web, the `WindowEvent::Destroyed` event now gets emitted when a `Window` is dropped. +- On Web (web-sys only), the event listeners are now removed when a `Window` is dropped or when the event loop is destroyed. +- On Web, the event handler closure passed to `EventLoop::run` now gets dropped after the event loop is destroyed. +- **Breaking:** On Web, the canvas element associated to a `Window` is no longer removed from the DOM when the `Window` is dropped. +- On Web, `WindowEvent::Resized` is now emitted when `Window::set_inner_size` is called. +- **Breaking:** `Fullscreen` enum now uses `Borderless(Option<MonitorHandle>)` instead of `Borderless(MonitorHandle)` to allow picking the current monitor. +- On MacOS, fix `WindowEvent::Moved` ignoring the scale factor. +- On Wayland, add missing virtual keycodes. +- On Wayland, implement proper `set_cursor_grab`. +- On Wayland, the cursor will use similar icons if the requested one isn't available. +- On Wayland, right clicking on client side decorations will request application menu. +- On Wayland, fix tracking of window size after state changes. +- On Wayland, fix client side decorations not being hidden properly in fullscreen. +- On Wayland, fix incorrect size event when entering fullscreen with client side decorations. +- On Wayland, fix `resizable` attribute not being applied properly on startup. +- On Wayland, fix disabled repeat rate not being handled. +- On Wayland, fix decoration buttons not working after tty switch. +- On Wayland, fix scaling not being applied on output re-enable. +- On Wayland, fix crash when `XCURSOR_SIZE` is `0`. +- On Wayland, fix pointer getting created in some cases without pointer capability. +- On Wayland, on kwin, fix space between window and decorations on startup. +- **Breaking:** On Wayland, `Theme` trait was reworked. +- On Wayland, disable maximize button for non-resizable window. +- On Wayland, added support for `set_ime_position`. +- On Wayland, fix crash on startup since GNOME 3.37.90. +- On X11, fix incorrect modifiers state on startup. diff --git a/app/vendor/rune/vendor/winit/src/changelog/v0.24.md b/app/vendor/rune/vendor/winit/src/changelog/v0.24.md new file mode 100644 index 0000000..fa0a27b --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/changelog/v0.24.md @@ -0,0 +1,28 @@ +## 0.24.0 + +- On Windows, fix applications not exiting gracefully due to thread_event_target_callback accessing corrupted memory. +- On Windows, implement `Window::set_ime_position`. +- **Breaking:** On Windows, Renamed `WindowBuilderExtWindows`'s `is_dark_mode` to `theme`. +- **Breaking:** On Windows, renamed `WindowBuilderExtWindows::is_dark_mode` to `theme`. +- On Windows, add `WindowBuilderExtWindows::with_theme` to set a preferred theme. +- On Windows, fix bug causing message boxes to appear delayed. +- On Android, calling `WindowEvent::Focused` now works properly instead of always returning false. +- On Windows, fix Alt-Tab behaviour by removing borderless fullscreen "always on top" flag. +- On Windows, fix bug preventing windows with transparency enabled from having fully-opaque regions. +- **Breaking:** On Windows, include prefix byte in scancodes. +- On Wayland, fix window not being resizeable when using `WindowBuilder::with_min_inner_size`. +- On Unix, fix cross-compiling to wasm32 without enabling X11 or Wayland. +- On Windows, fix use-after-free crash during window destruction. +- On Web, fix `WindowEvent::ReceivedCharacter` never being sent on key input. +- On macOS, fix compilation when targeting aarch64. +- On X11, fix `Window::request_redraw` not waking the event loop. +- On Wayland, the keypad arrow keys are now recognized. +- **Breaking** Rename `desktop::EventLoopExtDesktop` to `run_return::EventLoopExtRunReturn`. +- Added `request_user_attention` method to `Window`. +- **Breaking:** On macOS, removed `WindowExt::request_user_attention`, use `Window::request_user_attention`. +- **Breaking:** On X11, removed `WindowExt::set_urgent`, use `Window::request_user_attention`. +- On Wayland, default font size in CSD increased from 11 to 17. +- On Windows, fix bug causing message boxes to appear delayed. +- On Android, support multi-touch. +- On Wayland, extra mouse buttons are not dropped anymore. +- **Breaking**: `MouseButton::Other` now uses `u16`. diff --git a/app/vendor/rune/vendor/winit/src/changelog/v0.25.md b/app/vendor/rune/vendor/winit/src/changelog/v0.25.md new file mode 100644 index 0000000..00451c0 --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/changelog/v0.25.md @@ -0,0 +1,31 @@ +## 0.25.0 + +- **Breaking:** On macOS, replace `WindowBuilderExtMacOS::with_activation_policy` with `EventLoopExtMacOS::set_activation_policy` +- On macOS, wait with activating the application until the application has initialized. +- On macOS, fix creating new windows when the application has a main menu. +- On Windows, fix fractional deltas for mouse wheel device events. +- On macOS, fix segmentation fault after dropping the main window. +- On Android, `InputEvent::KeyEvent` is partially implemented providing the key scancode. +- Added `is_maximized` method to `Window`. +- On Windows, fix bug where clicking the decoration bar would make the cursor blink. +- On Windows, fix bug causing newly created windows to erroneously display the "wait" (spinning) cursor. +- On macOS, wake up the event loop immediately when a redraw is requested. +- On Windows, change the default window size (1024x768) to match the default on other desktop platforms (800x600). +- On Windows, fix bug causing mouse capture to not be released. +- On Windows, fix fullscreen not preserving minimized/maximized state. +- On Android, unimplemented events are marked as unhandled on the native event loop. +- On Windows, added `WindowBuilderExtWindows::with_menu` to set a custom menu at window creation time. +- On Android, bump `ndk` and `ndk-glue` to 0.3: use predefined constants for event `ident`. +- On macOS, fix objects captured by the event loop closure not being dropped on panic. +- On Windows, fixed `WindowEvent::ThemeChanged` not properly firing and fixed `Window::theme` returning the wrong theme. +- On Web, added support for `DeviceEvent::MouseMotion` to listen for relative mouse movements. +- Added `WindowBuilder::with_position` to allow setting the position of a `Window` on creation. Supported on Windows, macOS and X11. +- Added `Window::drag_window`. Implemented on Windows, macOS, X11 and Wayland. +- On X11, bump `mio` to 0.7. +- On Windows, added `WindowBuilderExtWindows::with_owner_window` to allow creating popup windows. +- On Windows, added `WindowExtWindows::set_enable` to allow creating modal popup windows. +- On macOS, emit `RedrawRequested` events immediately while the window is being resized. +- Implement `Default`, `Hash`, and `Eq` for `LogicalPosition`, `PhysicalPosition`, `LogicalSize`, and `PhysicalSize`. +- On macOS, initialize the Menu Bar with minimal defaults. (Can be prevented using `enable_default_menu_creation`) +- On macOS, change the default behavior for first click when the window was unfocused. Now the window becomes focused and then emits a `MouseInput` event on a "first mouse click". +- Implement mint (math interoperability standard types) conversions (under feature flag `mint`). diff --git a/app/vendor/rune/vendor/winit/src/changelog/v0.26.md b/app/vendor/rune/vendor/winit/src/changelog/v0.26.md new file mode 100644 index 0000000..d33d4a3 --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/changelog/v0.26.md @@ -0,0 +1,36 @@ +## 0.26.1 + +- Fix linking to the `ColorSync` framework on macOS 10.7, and in newer Rust versions. +- On Web, implement cursor grabbing through the pointer lock API. +- On X11, add mappings for numpad comma, numpad enter, numlock and pause. +- On macOS, fix Pinyin IME input by reverting a change that intended to improve IME. +- On Windows, fix a crash with transparent windows on Windows 11. + +## 0.26.0 + +- Update `raw-window-handle` to `v0.4`. This is _not_ a breaking change, we still implement `HasRawWindowHandle` from `v0.3`, see [rust-windowing/raw-window-handle#74](https://github.com/rust-windowing/raw-window-handle/pull/74). Note that you might have to run `cargo update -p raw-window-handle` after upgrading. +- On X11, bump `mio` to 0.8. +- On Android, fixed `WindowExtAndroid::config` initially returning an empty `Configuration`. +- On Android, fixed `Window::scale_factor` and `MonitorHandle::scale_factor` initially always returning 1.0. +- On X11, select an appropriate visual for transparency if is requested +- On Wayland and X11, fix diagonal window resize cursor orientation. +- On macOS, drop the event callback before exiting. +- On Android, implement `Window::request_redraw` +- **Breaking:** On Web, remove the `stdweb` backend. +- Added `Window::focus_window`to bring the window to the front and set input focus. +- On Wayland and X11, implement `is_maximized` method on `Window`. +- On Windows, prevent ghost window from showing up in the taskbar after either several hours of use or restarting `explorer.exe`. +- On macOS, fix issue where `ReceivedCharacter` was not being emitted during some key repeat events. +- On Wayland, load cursor icons `hand2` and `hand1` for `CursorIcon::Hand`. +- **Breaking:** On Wayland, Theme trait and its support types are dropped. +- On Wayland, bump `smithay-client-toolkit` to 0.15.1. +- On Wayland, implement `request_user_attention` with `xdg_activation_v1`. +- On X11, emit missing `WindowEvent::ScaleFactorChanged` when the only monitor gets reconnected. +- On X11, if RANDR based scale factor is higher than 20 reset it to 1 +- On Wayland, add an enabled-by-default feature called `wayland-dlopen` so users can opt out of using `dlopen` to load system libraries. +- **Breaking:** On Android, bump `ndk` and `ndk-glue` to 0.5. +- On Windows, increase wait timer resolution for more accurate timing when using `WaitUntil`. +- On macOS, fix native file dialogs hanging the event loop. +- On Wayland, implement a workaround for wrong configure size when using `xdg_decoration` in `kwin_wayland` +- On macOS, fix an issue that prevented the menu bar from showing in borderless fullscreen mode. +- On X11, EINTR while polling for events no longer causes a panic. Instead it will be treated as a spurious wakeup. diff --git a/app/vendor/rune/vendor/winit/src/changelog/v0.27.md b/app/vendor/rune/vendor/winit/src/changelog/v0.27.md new file mode 100644 index 0000000..5f067f5 --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/changelog/v0.27.md @@ -0,0 +1,107 @@ +## 0.27.5 + +- On Wayland, fix byte offset in `Ime::Preedit` pointing to invalid bytes. + +## 0.27.4 + +- On Windows, emit `ReceivedCharacter` events on system keybindings. +- On Windows, fixed focus event emission on minimize. +- On X11, fixed IME crashing during reload. + +## 0.27.3 + +- On Windows, added `WindowExtWindows::set_undecorated_shadow` and `WindowBuilderExtWindows::with_undecorated_shadow` to draw the drop shadow behind a borderless window. +- On Windows, fixed default window features (ie snap, animations, shake, etc.) when decorations are disabled. +- On Windows, fixed ALT+Space shortcut to open window menu. +- On Wayland, fixed `Ime::Preedit` not being sent on IME reset. +- Fixed unbound version specified for `raw-window-handle` leading to compilation failures. +- Empty `Ime::Preedit` event will be sent before `Ime::Commit` to help clearing preedit. +- On X11, fixed IME context picking by querying for supported styles beforehand. + +## 0.27.2 + +- On macOS, fixed touch phase reporting when scrolling. +- On X11, fix min, max and resize increment hints not persisting for resizable windows (e.g. on DPI change). +- On Windows, respect min/max inner sizes when creating the window. +- For backwards compatibility, `Window` now (additionally) implements the old version (`0.4`) of the `HasRawWindowHandle` trait +- On Windows, added support for `EventLoopWindowTarget::set_device_event_filter`. +- On Wayland, fix user requested `WindowEvent::RedrawRequested` being delayed by a frame. + +## 0.27.1 + +- The minimum supported Rust version was lowered to `1.57.0` and now explicitly tested. +- On X11, fix crash on start due to inability to create an IME context without any preedit. + +## 0.27.0 + +- On Windows, fix hiding a maximized window. +- On Android, `ndk-glue`'s `NativeWindow` lock is now held between `Event::Resumed` and `Event::Suspended`. +- On Web, added `EventLoopExtWebSys` with a `spawn` method to start the event loop without throwing an exception. +- Added `WindowEvent::Occluded(bool)`, currently implemented on macOS and X11. +- On X11, fix events for caps lock key not being sent +- Build docs on `docs.rs` for iOS and Android as well. +- **Breaking:** Removed the `WindowAttributes` struct, since all its functionality is accessible from `WindowBuilder`. +- Added `WindowBuilder::transparent` getter to check if the user set `transparent` attribute. +- On macOS, Fix emitting `Event::LoopDestroyed` on CMD+Q. +- On macOS, fixed an issue where having multiple windows would prevent run_return from ever returning. +- On Wayland, fix bug where the cursor wouldn't hide in GNOME. +- On macOS, Windows, and Wayland, add `set_cursor_hittest` to let the window ignore mouse events. +- On Windows, added `WindowExtWindows::set_skip_taskbar` and `WindowBuilderExtWindows::with_skip_taskbar`. +- On Windows, added `EventLoopBuilderExtWindows::with_msg_hook`. +- On Windows, remove internally unique DC per window. +- On macOS, remove the need to call `set_ime_position` after moving the window. +- Added `Window::is_visible`. +- Added `Window::is_resizable`. +- Added `Window::is_decorated`. +- On X11, fix for repeated event loop iteration when `ControlFlow` was `Wait` +- On X11, fix scale factor calculation when the only monitor is reconnected +- On Wayland, report unaccelerated mouse deltas in `DeviceEvent::MouseMotion`. +- On Web, a focused event is manually generated when a click occurs to emulate behaviour of other backends. +- **Breaking:** Bump `ndk` version to 0.6, ndk-sys to `v0.3`, `ndk-glue` to `0.6`. +- Remove no longer needed `WINIT_LINK_COLORSYNC` environment variable. +- **Breaking:** Rename the `Exit` variant of `ControlFlow` to `ExitWithCode`, which holds a value to control the exit code after running. Add an `Exit` constant which aliases to `ExitWithCode(0)` instead to avoid major breakage. This shouldn't affect most existing programs. +- Add `EventLoopBuilder`, which allows you to create and tweak the settings of an event loop before creating it. +- Deprecated `EventLoop::with_user_event`; use `EventLoopBuilder::with_user_event` instead. +- **Breaking:** Replaced `EventLoopExtMacOS` with `EventLoopBuilderExtMacOS` (which also has renamed methods). +- **Breaking:** Replaced `EventLoopExtWindows` with `EventLoopBuilderExtWindows` (which also has renamed methods). +- **Breaking:** Replaced `EventLoopExtUnix` with `EventLoopBuilderExtUnix` (which also has renamed methods). +- **Breaking:** The platform specific extensions for Windows `winit::platform::windows` have changed. All `HANDLE`-like types e.g. `HWND` and `HMENU` were converted from winapi types or `*mut c_void` to `isize`. This was done to be consistent with the type definitions in windows-sys and to not expose internal dependencies. +- The internal bindings to the [Windows API](https://docs.microsoft.com/en-us/windows/) were changed from the unofficial [winapi](https://github.com/retep998/winapi-rs) bindings to the official Microsoft [windows-sys](https://github.com/microsoft/windows-rs) bindings. +- On Wayland, fix polling during consecutive `EventLoop::run_return` invocations. +- On Windows, fix race issue creating fullscreen windows with `WindowBuilder::with_fullscreen` +- On Android, `virtual_keycode` for `KeyboardInput` events is now filled in where a suitable match is found. +- Added helper methods on `ControlFlow` to set its value. +- On Wayland, fix `TouchPhase::Ended` always reporting the location of the first touch down, unless the compositor + sent a cancel or frame event. +- On iOS, send `RedrawEventsCleared` even if there are no redraw events, consistent with other platforms. +- **Breaking:** Replaced `Window::with_app_id` and `Window::with_class` with `Window::with_name` on `WindowBuilderExtUnix`. +- On Wayland, fallback CSD was replaced with proper one: + - `WindowBuilderExtUnix::with_wayland_csd_theme` to set color theme in builder. + - `WindowExtUnix::wayland_set_csd_theme` to set color theme when creating a window. + - `WINIT_WAYLAND_CSD_THEME` env variable was added, it can be used to set "dark"/"light" theme in apps that don't expose theme setting. + - `wayland-csd-adwaita` feature that enables proper CSD with title rendering using FreeType system library. + - `wayland-csd-adwaita-notitle` feature that enables CSD but without title rendering. +- On Wayland and X11, fix window not resizing with `Window::set_inner_size` after calling `Window:set_resizable(false)`. +- On Windows, fix wrong fullscreen monitors being recognized when handling WM_WINDOWPOSCHANGING messages +- **Breaking:** Added new `WindowEvent::Ime` supported on desktop platforms. +- Added `Window::set_ime_allowed` supported on desktop platforms. +- **Breaking:** IME input on desktop platforms won't be received unless it's explicitly allowed via `Window::set_ime_allowed` and new `WindowEvent::Ime` events are handled. +- On macOS, `WindowEvent::Resized` is now emitted in `frameDidChange` instead of `windowDidResize`. +- **Breaking:** On X11, device events are now ignored for unfocused windows by default, use `EventLoopWindowTarget::set_device_event_filter` to set the filter level. +- Implemented `Default` on `EventLoop<()>`. +- Implemented `Eq` for `Fullscreen`, `Theme`, and `UserAttentionType`. +- **Breaking:** `Window::set_cursor_grab` now accepts `CursorGrabMode` to control grabbing behavior. +- On Wayland, add support for `Window::set_cursor_position`. +- Fix on macOS `WindowBuilder::with_disallow_hidpi`, setting true or false by the user no matter the SO default value. +- `EventLoopBuilder::build` will now panic when the `EventLoop` is being created more than once. +- Added `From<u64>` for `WindowId` and `From<WindowId>` for `u64`. +- Added `MonitorHandle::refresh_rate_millihertz` to get monitor's refresh rate. +- **Breaking**, Replaced `VideoMode::refresh_rate` with `VideoMode::refresh_rate_millihertz` providing better precision. +- On Web, add `with_prevent_default` and `with_focusable` to `WindowBuilderExtWebSys` to control whether events should be propagated. +- On Windows, fix focus events being sent to inactive windows. +- **Breaking**, update `raw-window-handle` to `v0.5` and implement `HasRawDisplayHandle` for `Window` and `EventLoopWindowTarget`. +- On X11, add function `register_xlib_error_hook` into `winit::platform::unix` to subscribe for errors coming from Xlib. +- On Android, upgrade `ndk` and `ndk-glue` dependencies to the recently released `0.7.0`. +- All platforms can now be relied on to emit a `Resumed` event. Applications are recommended to lazily initialize graphics state and windows on first resume for portability. +- **Breaking:**: Reverse horizontal scrolling sign in `MouseScrollDelta` to match the direction of vertical scrolling. A positive X value now means moving the content to the right. The meaning of vertical scrolling stays the same: a positive Y value means moving the content down. +- On MacOS, fix deadlock when calling `set_maximized` from event loop. diff --git a/app/vendor/rune/vendor/winit/src/changelog/v0.28.md b/app/vendor/rune/vendor/winit/src/changelog/v0.28.md new file mode 100644 index 0000000..a8b3262 --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/changelog/v0.28.md @@ -0,0 +1,100 @@ +## 0.28.7 + +- Fix window size sometimes being invalid when resizing on macOS 14 Sonoma. + +## 0.28.6 + +- On macOS, fixed memory leak when getting monitor handle. +- On macOS, fix `Backspace` being emitted when clearing preedit with it. + +## 0.28.5 + +- On macOS, fix `key_up` being ignored when `Ime` is disabled. + +## 0.28.4 + +- On macOS, fix empty marked text blocking regular input. +- On macOS, fix potential panic when getting refresh rate. +- On macOS, fix crash when calling `Window::set_ime_position` from another thread. + +## 0.28.3 + +- Fix macOS memory leaks. + +## 0.28.2 + +- Implement `HasRawDisplayHandle` for `EventLoop`. +- On macOS, set resize increments only for live resizes. +- On Wayland, fix rare crash on DPI change +- Web: Added support for `Window::theme`. +- On Wayland, fix rounding issues when doing resize. +- On macOS, fix wrong focused state on startup. +- On Windows, fix crash on setting taskbar when using Visual Studio debugger. +- On macOS, resize simple fullscreen windows on windowDidChangeScreen events. + +## 0.28.1 + +- On Wayland, fix crash when dropping a window in multi-window setup. + +## 0.28.0 + +- On macOS, fixed `Ime::Commit` persisting for all input after interacting with `Ime`. +- On macOS, added `WindowExtMacOS::option_as_alt` and `WindowExtMacOS::set_option_as_alt`. +- On Windows, fix window size for maximized, undecorated windows. +- On Windows and macOS, add `WindowBuilder::with_active`. +- Add `Window::is_minimized`. +- On X11, fix errors handled during `register_xlib_error_hook` invocation bleeding into winit. +- Add `Window::has_focus`. +- On Windows, fix `Window::set_minimized(false)` not working for windows minimized by `Win + D` hotkey. +- **Breaking:** On Web, touch input no longer fires `WindowEvent::Cursor*`, `WindowEvent::MouseInput`, or `DeviceEvent::MouseMotion` like other platforms, but instead it fires `WindowEvent::Touch`. +- **Breaking:** Removed platform specific `WindowBuilder::with_parent` API in favor of `WindowBuilder::with_parent_window`. +- On Windows, retain `WS_MAXIMIZE` window style when un-minimizing a maximized window. +- On Windows, fix left mouse button release event not being sent after `Window::drag_window`. +- On macOS, run most actions on the main thread, which is strictly more correct, but might make multithreaded applications block slightly more. +- On macOS, fix panic when getting current monitor without any monitor attached. +- On Windows and MacOS, add API to enable/disable window buttons (close, minimize, ...etc). +- On Windows, macOS, X11 and Wayland, add `Window::set_theme`. +- **Breaking:** Remove `WindowExtWayland::wayland_set_csd_theme` and `WindowBuilderExtX11::with_gtk_theme_variant`. +- On Windows, revert window background to an empty brush to avoid white flashes when changing scaling. +- **Breaking:** Removed `Window::set_always_on_top` and related APIs in favor of `Window::set_window_level`. +- On Windows, MacOS and X11, add always on bottom APIs. +- On Windows, fix the value in `MouseButton::Other`. +- On macOS, add `WindowExtMacOS::is_document_edited` and `WindowExtMacOS::set_document_edited` APIs. +- **Breaking:** Removed `WindowBuilderExtIOS::with_root_view_class`; instead, you should use `[[view layer] addSublayer: ...]` to add an instance of the desired layer class (e.g. `CAEAGLLayer` or `CAMetalLayer`). See `vulkano-win` or `wgpu` for examples of this. +- On MacOS and Windows, add `Window::set_content_protected`. +- On MacOS, add `EventLoopBuilderExtMacOS::with_activate_ignoring_other_apps`. +- On Windows, fix icons specified on `WindowBuilder` not taking effect for windows created after the first one. +- On Windows and macOS, add `Window::title` to query the current window title. +- On Windows, fix focusing menubar when pressing `Alt`. +- On MacOS, made `accepts_first_mouse` configurable. +- Migrated `WindowBuilderExtUnix::with_resize_increments` to `WindowBuilder`. +- Added `Window::resize_increments`/`Window::set_resize_increments` to update resize increments at runtime for X11/macOS. +- macOS/iOS: Use `objc2` instead of `objc` internally. +- **Breaking:** Bump MSRV from `1.57` to `1.60`. +- **Breaking:** Split the `platform::unix` module into `platform::x11` and `platform::wayland`. The extension types are similarly renamed. +- **Breaking:**: Removed deprecated method `platform::unix::WindowExtUnix::is_ready`. +- Removed `parking_lot` dependency. +- **Breaking:** On macOS, add support for two-finger touchpad magnification and rotation gestures with new events `WindowEvent::TouchpadMagnify` and `WindowEvent::TouchpadRotate`. Also add support for touchpad smart-magnification gesture with a new event `WindowEvent::SmartMagnify`. +- **Breaking:** On web, the `WindowBuilderExtWebSys::with_prevent_default` setting (enabled by default), now additionally prevents scrolling of the webpage in mobile browsers, previously it only disabled scrolling on desktop. +- On Wayland, `wayland-csd-adwaita` now uses `ab_glyph` instead of `crossfont` to render the title for decorations. +- On Wayland, a new `wayland-csd-adwaita-crossfont` feature was added to use `crossfont` instead of `ab_glyph` for decorations. +- On Wayland, if not otherwise specified use upstream automatic CSD theme selection. +- On X11, added `WindowExtX11::with_parent` to create child windows. +- Added support for `WindowBuilder::with_theme` and `Window::theme` to support per-window dark/light/system theme configuration on macos, windows and wayland. +- On macOS, added support for `WindowEvent::ThemeChanged`. +- **Breaking:** Removed `WindowBuilderExtWindows::with_theme` and `WindowBuilderExtWayland::with_wayland_csd_theme` in favour of `WindowBuilder::with_theme`. +- **Breaking:** Removed `WindowExtWindows::theme` in favour of `Window::theme`. +- Enabled `doc_auto_cfg` when generating docs on docs.rs for feature labels. +- **Breaking:** On Android, switched to using [`android-activity`](https://github.com/rib/android-activity) crate as a glue layer instead of [`ndk-glue`](https://github.com/rust-windowing/android-ndk-rs/tree/master/ndk-glue). See [README.md#Android](https://github.com/rust-windowing/winit#Android) for more details. ([#2444](https://github.com/rust-windowing/winit/pull/2444)) +- **Breaking:** Removed support for `raw-window-handle` version `0.4` +- On Wayland, `RedrawRequested` not emitted during resize. +- Add a `set_wait_timeout` function to `ControlFlow` to allow waiting for a `Duration`. +- **Breaking:** Remove the unstable `xlib_xconnection()` function from the private interface. +- Added Orbital support for Redox OS +- On X11, added `drag_resize_window` method. +- Added `Window::set_transparent` to provide a hint about transparency of the window on Wayland and macOS. +- On macOS, fix the mouse buttons other than left/right/middle being reported as middle. +- On Wayland, support fractional scaling via the wp-fractional-scale protocol. +- On web, fix removal of mouse event listeners from the global object upon window destruction. +- Add WindowAttributes getter to WindowBuilder to allow introspection of default values. +- Added `Window::set_ime_purpose` for setting the IME purpose, currently implemented on Wayland only. diff --git a/app/vendor/rune/vendor/winit/src/changelog/v0.29.md b/app/vendor/rune/vendor/winit/src/changelog/v0.29.md new file mode 100644 index 0000000..fc17f17 --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/changelog/v0.29.md @@ -0,0 +1,289 @@ +## 0.29.15 + +- On X11, fix crash due to xsettings query on systems with incomplete xsettings. + +## 0.29.14 + +- On X11/Wayland, fix `text` and `text_with_all_modifiers` not being `None` during compose. +- On Wayland, don't reapply cursor grab when unchanged. +- On X11, fix a bug where some mouse events would be unexpectedly filtered out. + +## 0.29.13 + +- On Web, fix possible crash with `ControlFlow::Wait` and `ControlFlow::WaitUntil`. + +## 0.29.12 + +- On X11, fix use after free during xinput2 handling. +- On X11, filter close to zero values in mouse device events + +## 0.29.11 + +- Fix compatibility with 32-bit platforms without 64-bit atomics. +- On macOS, fix incorrect IME cursor rect origin. +- On Windows, fixed a race condition when sending an event through the loop proxy. +- On X11, fix swapped instance and general class names. +- On X11, don't require XIM to run. +- On X11, fix xkb state not being updated correctly sometimes leading to wrong input. +- On X11, reload dpi on `_XSETTINGS_SETTINGS` update. +- On X11, fix deadlock when adjusting DPI and resizing at the same time. +- On Wayland, disable `Occluded` event handling. +- On Wayland, fix DeviceEvent::Motion not being sent +- On Wayland, fix `Focused(false)` being send when other seats still have window focused. +- On Wayland, fix `Window::set_{min,max}_inner_size` not always applied. +- On Wayland, fix title in CSD not updated from `AboutToWait`. +- On Windows, fix inconsistent resizing behavior with multi-monitor setups when repositioning outside the event loop. +- On Wayland, fix `WAYLAND_SOCKET` not used when detecting platform. +- On Orbital, fix `logical_key` and `text` not reported in `KeyEvent`. +- On Orbital, implement `KeyEventExtModifierSupplement`. +- On Orbital, map keys to `NamedKey` when possible. +- On Orbital, implement `set_cursor_grab`. +- On Orbital, implement `set_cursor_visible`. +- On Orbital, implement `drag_window`. +- On Orbital, implement `drag_resize_window`. +- On Orbital, implement `set_transparent`. +- On Orbital, implement `set_visible`. +- On Orbital, implement `is_visible`. +- On Orbital, implement `set_resizable`. +- On Orbital, implement `is_resizable`. +- On Orbital, implement `set_maximized`. +- On Orbital, implement `is_maximized`. +- On Orbital, implement `set_decorations`. +- On Orbital, implement `is_decorated`. +- On Orbital, implement `set_window_level`. +- On Orbital, emit `DeviceEvent::MouseMotion`. + +## 0.29.10 + +- On Web, account for canvas being focused already before event loop starts. +- On Web, increase cursor position accuracy. + +## 0.29.9 + +- On X11, fix `NotSupported` error not propagated when creating event loop. +- On Wayland, fix resize not issued when scale changes +- On X11 and Wayland, fix arrow up on keypad reported as `ArrowLeft`. +- On macOS, report correct logical key when Ctrl or Cmd is pressed. + +## 0.29.8 + +- On X11, fix IME input lagging behind. +- On X11, fix `ModifiersChanged` not sent from xdotool-like input +- On X11, fix keymap not updated from xmodmap. +- On X11, reduce the amount of time spent fetching screen resources. +- On Wayland, fix `Window::request_inner_size` being overwritten by resize. +- On Wayland, fix `Window::inner_size` not using the correct rounding. + +## 0.29.7 + +- On X11, fix `Xft.dpi` reload during runtime. +- On X11, fix window minimize. + +## 0.29.6 + +- On Web, fix context menu not being disabled by `with_prevent_default(true)`. +- On Wayland, fix `WindowEvent::Destroyed` not being delivered after destroying window. +- Fix `EventLoopExtRunOnDemand::run_on_demand` not working for consequent invocation + +## 0.29.5 + +- On macOS, remove spurious error logging when handling `Fn`. +- On X11, fix an issue where floating point data from the server is + misinterpreted during a drag and drop operation. +- On X11, fix a bug where focusing the window would panic. +- On macOS, fix `refresh_rate_millihertz`. +- On Wayland, disable Client Side Decorations when `wl_subcompositor` is not supported. +- On X11, fix `Xft.dpi` detection from Xresources. +- On Windows, fix consecutive calls to `window.set_fullscreen(Some(Fullscreen::Borderless(None)))` resulting in losing previous window state when eventually exiting fullscreen using `window.set_fullscreen(None)`. +- On Wayland, fix resize being sent on focus change. +- On Windows, fix `set_ime_cursor_area`. + +## 0.29.4 + +- Fix crash when running iOS app on macOS. +- On X11, check common alternative cursor names when loading cursor. +- On X11, reload the DPI after a property change event. +- On Windows, fix so `drag_window` and `drag_resize_window` can be called from another thread. +- On Windows, fix `set_control_flow` in `AboutToWait` not being taken in account. +- On macOS, send a `Resized` event after each `ScaleFactorChanged` event. +- On Wayland, fix `wl_surface` being destroyed before associated objects. +- On macOS, fix assertion when pressing `Fn` key. +- On Windows, add `WindowBuilderExtWindows::with_clip_children` to control `WS_CLIPCHILDREN` style. + +## 0.29.3 + +- On Wayland, apply correct scale to `PhysicalSize` passed in `WindowBuilder::with_inner_size` when possible. +- On Wayland, fix `RedrawRequested` being always sent without decorations and `sctk-adwaita` feature. +- On Wayland, ignore resize requests when the window is fully tiled. +- On Wayland, use `configure_bounds` to constrain `with_inner_size` when compositor wants users to pick size. +- On Windows, fix deadlock when accessing the state during `Cursor{Enter,Leave}`. +- On Windows, add support for `Window::set_transparent`. +- On macOS, fix deadlock when entering a nested event loop from an event handler. +- On macOS, add support for `Window::set_blur`. + +## 0.29.2 + +- **Breaking:** Bump MSRV from `1.60` to `1.65`. +- **Breaking:** Add `Event::MemoryWarning`; implemented on iOS/Android. +- **Breaking:** Bump `ndk` version to `0.8.0`, ndk-sys to `0.5.0`, `android-activity` to `0.5.0`. +- **Breaking:** Change default `ControlFlow` from `Poll` to `Wait`. +- **Breaking:** Move `Event::RedrawRequested` to `WindowEvent::RedrawRequested`. +- **Breaking:** Moved `ControlFlow::Exit` to `EventLoopWindowTarget::exit()` and `EventLoopWindowTarget::exiting()` and removed `ControlFlow::ExitWithCode(_)` entirely. +- **Breaking:** Moved `ControlFlow` to `EventLoopWindowTarget::set_control_flow()` and `EventLoopWindowTarget::control_flow()`. +- **Breaking:** `EventLoop::new` and `EventLoopBuilder::build` now return `Result<Self, EventLoopError>` +- **Breaking:** `WINIT_UNIX_BACKEND` was removed in favor of standard `WAYLAND_DISPLAY` and `DISPLAY` variables. +- **Breaking:** on Wayland, dispatching user created Wayland queue won't wake up the loop unless winit has event to send back. +- **Breaking:** remove `DeviceEvent::Text`. +- **Breaking:** Remove lifetime parameter from `Event` and `WindowEvent`. +- **Breaking:** Rename `Window::set_inner_size` to `Window::request_inner_size` and indicate if the size was applied immediately. +- **Breaking:** `ActivationTokenDone` event which could be requested with the new `startup_notify` module, see its docs for more. +- **Breaking:** `ScaleFactorChanged` now contains a writer instead of a reference to update inner size. +- **Breaking** `run() -> !` has been replaced by `run() -> Result<(), EventLoopError>` for returning errors without calling `std::process::exit()` ([#2767](https://github.com/rust-windowing/winit/pull/2767)) +- **Breaking** Removed `EventLoopExtRunReturn` / `run_return` in favor of `EventLoopExtPumpEvents` / `pump_events` and `EventLoopExtRunOnDemand` / `run_on_demand` ([#2767](https://github.com/rust-windowing/winit/pull/2767)) +- `RedrawRequested` is no longer guaranteed to be emitted after `MainEventsCleared`, it is now platform-specific when the event is emitted after being requested via `redraw_request()`. + - On Windows, `RedrawRequested` is now driven by `WM_PAINT` messages which are requested via `redraw_request()` +- **Breaking** `LoopDestroyed` renamed to `LoopExiting` ([#2900](https://github.com/rust-windowing/winit/issues/2900)) +- **Breaking** `RedrawEventsCleared` removed ([#2900](https://github.com/rust-windowing/winit/issues/2900)) +- **Breaking** `MainEventsCleared` removed ([#2900](https://github.com/rust-windowing/winit/issues/2900)) +- **Breaking:** Remove all deprecated `modifiers` fields. +- **Breaking:** Rename `DeviceEventFilter` to `DeviceEvents` reversing the behavior of variants. +- **Breaking** Add `AboutToWait` event which is emitted when the event loop is about to block and wait for new events ([#2900](https://github.com/rust-windowing/winit/issues/2900)) +- **Breaking:** Rename `EventLoopWindowTarget::set_device_event_filter` to `listen_device_events`. +- **Breaking:** Rename `Window::set_ime_position` to `Window::set_ime_cursor_area` adding a way to set exclusive zone. +- **Breaking:** `with_x11_visual` now takes the visual ID instead of the bare pointer. +- **Breaking** `MouseButton` now supports `Back` and `Forward` variants, emitted from mouse events on Wayland, X11, Windows, macOS and Web. +- **Breaking:** On Web, `instant` is now replaced by `web_time`. +- **Breaking:** On Web, dropped support for Safari versions below 13.1. +- **Breaking:** On Web, the canvas output bitmap size is no longer adjusted. +- **Breaking:** On Web, the canvas size is not controlled by Winit anymore and external changes to the canvas size will be reported through `WindowEvent::Resized`. +- **Breaking:** Updated `bitflags` crate version to `2`, which changes the API on exposed types. +- **Breaking:** `CursorIcon::Arrow` was removed. +- **Breaking:** `CursorIcon::Hand` is now named `CursorIcon::Pointer`. +- **Breaking:** `CursorIcon` is now used from the `cursor-icon` crate. +- **Breaking:** `WindowExtWebSys::canvas()` now returns an `Option`. +- **Breaking:** Overhaul keyboard input handling. + - Replace `KeyboardInput` with `KeyEvent` and `RawKeyEvent`. + - Change `WindowEvent::KeyboardInput` to contain a `KeyEvent`. + - Change `Event::Key` to contain a `RawKeyEvent`. + - Remove `Event::ReceivedCharacter`. In its place, you should use + `KeyEvent.text` in combination with `WindowEvent::Ime`. + - Replace `VirtualKeyCode` with the `Key` enum. + - Replace `ScanCode` with the `KeyCode` enum. + - Rename `ModifiersState::LOGO` to `SUPER` and `ModifiersState::CTRL` to `CONTROL`. + - Add `PhysicalKey` wrapping `KeyCode` and `NativeKeyCode`. + - Add `KeyCode` to refer to keys (roughly) by their physical location. + - Add `NativeKeyCode` to represent raw `KeyCode`s which Winit doesn't + understand. + - Add `Key` to represent the keys after they've been interpreted by the + active (software) keyboard layout. + - Add `NamedKey` to represent the categorized keys. + - Add `NativeKey` to represent raw `Key`s which Winit doesn't understand. + - Add `KeyLocation` to tell apart `Key`s which usually "mean" the same thing, + but can appear simultaneously in different spots on the same keyboard + layout. + - Add `Window::reset_dead_keys` to enable application-controlled cancellation + of dead key sequences. + - Add `KeyEventExtModifierSupplement` to expose additional (and less + portable) interpretations of a given key-press. + - Add `PhysicalKeyExtScancode`, which lets you convert between scancodes and + `PhysicalKey`. + - `ModifiersChanged` now uses dedicated `Modifiers` struct. +- Removed platform-specific extensions that should be retrieved through `raw-window-handle` trait implementations instead: + - `platform::windows::HINSTANCE`. + - `WindowExtWindows::hinstance`. + - `WindowExtWindows::hwnd`. + - `WindowExtIOS::ui_window`. + - `WindowExtIOS::ui_view_controller`. + - `WindowExtIOS::ui_view`. + - `WindowExtMacOS::ns_window`. + - `WindowExtMacOS::ns_view`. + - `EventLoopWindowTargetExtWayland::wayland_display`. + - `WindowExtWayland::wayland_surface`. + - `WindowExtWayland::wayland_display`. + - `WindowExtX11::xlib_window`. + - `WindowExtX11::xlib_display`. + - `WindowExtX11::xlib_screen_id`. + - `WindowExtX11::xcb_connection`. +- Reexport `raw-window-handle` in `window` module. +- Add `ElementState::is_pressed`. +- Add `Window::pre_present_notify` to notify winit before presenting to the windowing system. +- Add `Window::set_blur` to request a blur behind the window; implemented on Wayland for now. +- Add `Window::show_window_menu` to request a titlebar/system menu; implemented on Wayland/Windows for now. +- Implement `AsFd`/`AsRawFd` for `EventLoop<T>` on X11 and Wayland. +- Implement `PartialOrd` and `Ord` for `MouseButton`. +- Implement `PartialOrd` and `Ord` on types in the `dpi` module. +- Make `WindowBuilder` `Send + Sync`. +- Make iOS `MonitorHandle` and `VideoMode` usable from other threads. +- Make iOS windows usable from other threads. +- On Android, add force data to touch events. +- On Android, added `EventLoopBuilderExtAndroid::handle_volume_keys` to indicate that the application will handle the volume keys manually. +- On Android, fix `DeviceId` to contain device id's. +- On Orbital, fix `ModifiersChanged` not being sent. +- On Wayland, `Window::outer_size` now accounts for **client side** decorations. +- On Wayland, add `Window::drag_resize_window` method. +- On Wayland, remove `WINIT_WAYLAND_CSD_THEME` variable. +- On Wayland, fix `TouchPhase::Canceled` being sent for moved events. +- On Wayland, fix forward compatibility issues. +- On Wayland, fix initial window size not restored for maximized/fullscreened on startup window. +- On Wayland, fix maximized startup not taking full size on GNOME. +- On Wayland, fix maximized window creation and window geometry handling. +- On Wayland, fix window not checking that it actually got initial configure event. +- On Wayland, make double clicking and moving the CSD frame more reliable. +- On Wayland, support `Occluded` event with xdg-shell v6 +- On Wayland, use frame callbacks to throttle `RedrawRequested` events so redraws will align with compositor. +- On Web, `ControlFlow::WaitUntil` now uses the Prioritized Task Scheduling API. `setTimeout()`, with a trick to circumvent throttling to 4ms, is used as a fallback. +- On Web, `EventLoopProxy` now implements `Send`. +- On Web, `Window` now implements `Send` and `Sync`. +- On Web, account for CSS `padding`, `border`, and `margin` when getting or setting the canvas position. +- On Web, add Fullscreen API compatibility for Safari. +- On Web, add `DeviceEvent::Motion`, `DeviceEvent::MouseWheel`, `DeviceEvent::Button` and `DeviceEvent::Key` support. +- On Web, add `EventLoopWindowTargetExtWebSys` and `PollStrategy`, which allows to set different strategies for `ControlFlow::Poll`. By default the Prioritized Task Scheduling API is used, but an option to use `Window.requestIdleCallback` is available as well. Both use `setTimeout()`, with a trick to circumvent throttling to 4ms, as a fallback. +- On Web, add `WindowBuilderExtWebSys::with_append()` to append the canvas element to the web page on creation. +- On Web, allow event loops to be recreated with `spawn`. +- On Web, enable event propagation. +- On Web, fix `ControlFlow::WaitUntil` to never wake up **before** the given time. +- On Web, fix `DeviceEvent::MouseMotion` only being emitted for each canvas instead of the whole window. +- On Web, fix `Window:::set_fullscreen` doing nothing when called outside the event loop but during transient activation. +- On Web, fix pen treated as mouse input. +- On Web, fix pointer button events not being processed when a buttons is already pressed. +- On Web, fix scale factor resize suggestion always overwriting the canvas size. +- On Web, fix some `WindowBuilder` methods doing nothing. +- On Web, fix some `Window` methods using incorrect HTML attributes instead of CSS properties. +- On Web, fix the bfcache by not using the `beforeunload` event and map bfcache loading/unloading to `Suspended`/`Resumed` events. +- On Web, fix touch input not gaining or losing focus. +- On Web, fix touch location to be as accurate as mouse position. +- On Web, handle coalesced pointer events, which increases the resolution of pointer inputs. +- On Web, implement `Window::focus_window()`. +- On Web, implement `Window::set_(min|max)_inner_size()`. +- On Web, implement `WindowEvent::Occluded`. +- On Web, never return a `MonitorHandle`. +- On Web, prevent clicks on the canvas to select text. +- On Web, remove any fullscreen requests from the queue when an external fullscreen activation was detected. +- On Web, remove unnecessary `Window::is_dark_mode()`, which was replaced with `Window::theme()`. +- On Web, respect `EventLoopWindowTarget::listen_device_events()` settings. +- On Web, scale factor and dark mode detection are now more robust. +- On Web, send mouse position on button release as well. +- On Web, take all transient activations on the canvas and window into account to queue a fullscreen request. +- On Web, use `Window.requestAnimationFrame()` to throttle `RedrawRequested` events. +- On Web, use the correct canvas size when calculating the new size during scale factor change, instead of using the output bitmap size. +- On Web: fix `Window::request_redraw` not waking the event loop when called from outside the loop. +- On Web: fix position of touch events to be relative to the canvas. +- On Windows, add `drag_resize_window` method support. +- On Windows, add horizontal MouseWheel `DeviceEvent`. +- On Windows, added `WindowBuilderExtWindows::with_class_name` to customize the internal class name. +- On Windows, fix IME APIs not working when from non event loop thread. +- On Windows, fix `CursorEnter/Left` not being sent when grabbing the mouse. +- On Windows, fix `RedrawRequested` not being delivered when calling `Window::request_redraw` from `RedrawRequested`. +- On Windows, port to `windows-sys` version 0.48.0. +- On X11, add a `with_embedded_parent_window` function to the window builder to allow embedding a window into another window. +- On X11, fix event loop not waking up on `ControlFlow::Poll` and `ControlFlow::WaitUntil`. +- On X11, fix false positive flagging of key repeats when pressing different keys with no release between presses. +- On X11, set `visual_id` in returned `raw-window-handle`. +- On iOS, add ability to change the status bar style. +- On iOS, add force data to touch events when using the Apple Pencil. +- On iOS, always wake the event loop when transitioning from `ControlFlow::Poll` to `ControlFlow::Poll`. +- On iOS, send events `WindowEvent::Occluded(false)`, `WindowEvent::Occluded(true)` when application enters/leaves foreground. +- On macOS, add tabbing APIs on `WindowExtMacOS` and `EventLoopWindowTargetExtMacOS`. +- On macOS, fix assertion when pressing `Globe` key. +- On macOS, fix crash in `window.set_minimized(false)`. +- On macOS, fix crash when dropping `Window`. diff --git a/app/vendor/rune/vendor/winit/src/changelog/v0.30.md b/app/vendor/rune/vendor/winit/src/changelog/v0.30.md new file mode 100644 index 0000000..6b0b47d --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/changelog/v0.30.md @@ -0,0 +1,413 @@ +## 0.30.13 + +### Added + +- On Wayland, add `Window::set_resize_increments`. + +### Fixed + +- On macOS, fixed crash when dragging non-file content onto window. +- On X11, fix `set_hittest` not working on some window managers. +- On X11, fix debug mode overflow panic in `set_timestamp`. +- On macOS, fix crash in `set_marked_text` when native Pinyin IME sends out-of-bounds `selected_range`. +- On Windows, fix `WM_IME_SETCONTEXT` IME UI flag masking on `lParam`. +- On Android, populate `KeyEvent::text` and `KeyEvent::text_with_all_modifiers` via `Key::to_text()`. + +## 0.30.12 + +### Fixed + +- On macOS, fix crash on macOS 26 by using objc2's `relax-sign-encoding` feature. + +## 0.30.11 + +### Fixed + +- On Windows, fixed crash in should_apps_use_dark_mode() for Windows versions < 17763. +- On Wayland, fixed `pump_events` driven loop deadlocking when loop was not drained before exit. + +## 0.30.10 + +### Added + +- On Windows, add `IconExtWindows::from_resource_name`. +- On Windows, add `CursorGrabMode::Locked`. +- On Wayland, add `WindowExtWayland::xdg_toplevel`. + +### Changed + +- On macOS, no longer need control of the main `NSApplication` class (which means you can now override it yourself). +- On iOS, remove custom application delegates. You are now allowed to override the + application delegate yourself. +- On iOS, no longer act as-if the application successfully open all URLs. Override + `application:didFinishLaunchingWithOptions:` and provide the desired behaviour yourself. + +### Fixed + +- On Windows, fixed ~500 ms pause when clicking the title bar during continuous redraw. +- On macOS, `WindowExtMacOS::set_simple_fullscreen` now honors `WindowExtMacOS::set_borderless_game` +- On X11 and Wayland, fixed pump_events with `Some(Duration::Zero)` blocking with `Wait` polling mode +- On Wayland, fixed a crash when consequently calling `set_cursor_grab` without pointer focus. +- On Wayland, ensure that external event loop is woken-up when using pump_events and integrating via `FD`. +- On Wayland, apply fractional scaling to custom cursors. +- On macOS, fixed `run_app_on_demand` returning without closing open windows. +- On macOS, fixed `VideoMode::refresh_rate_millihertz` for fractional refresh rates. +- On macOS, store monitor handle to avoid panics after going in/out of sleep. +- On macOS, allow certain invalid monitor handles and return `None` instead of panicking. +- On Windows, fixed `Ime::Preedit` cursor offset calculation. + +## 0.30.9 + +### Changed + +- On Wayland, no longer send an explicit clearing `Ime::Preedit` just prior to a new `Ime::Preedit`. + +### Fixed + +- On X11, fix crash with uim. +- On X11, fix modifiers for keys that were sent by the same X11 request. +- On iOS, fix high CPU usage even when using `ControlFlow::Wait`. + +## 0.30.8 + +### Added + +- `ActivationToken::from_raw` and `ActivationToken::into_raw`. +- On X11, add a workaround for disabling IME on GNOME. + +### Fixed + +- On Windows, fixed the event loop not waking on accessibility requests. +- On X11, fixed cursor grab mode state tracking on error. + +## 0.30.7 + +### Fixed + +- On X11, fixed KeyboardInput delivered twice when IME enabled. + +## 0.30.6 + +### Added + +- On macOS, add `WindowExtMacOS::set_borderless_game` and `WindowAttributesExtMacOS::with_borderless_game` + to fully disable the menu bar and dock in Borderless Fullscreen as commonly done in games. +- On X11, the `window` example now understands the `X11_VISUAL_ID` and `X11_SCREEN_ID` env + variables to test the respective modifiers of window creation. +- On Android, the soft keyboard can now be shown using `Window::set_ime_allowed`. +- Add basic iOS IME support. The soft keyboard can now be shown using `Window::set_ime_allowed`. + +### Fixed + +- On macOS, fix `WindowEvent::Moved` sometimes being triggered unnecessarily on resize. +- On macOS, package manifest definitions of `LSUIElement` will no longer be overridden with the + default activation policy, unless explicitly provided during initialization. +- On macOS, fix crash when calling `drag_window()` without a left click present. +- On X11, key events forward to IME anyway, even when it's disabled. +- On Windows, make `ControlFlow::WaitUntil` work more precisely using `CREATE_WAITABLE_TIMER_HIGH_RESOLUTION`. +- On X11, creating windows on screen that is not the first one (e.g. `DISPLAY=:0.1`) works again. +- On X11, creating windows while passing `with_x11_screen(non_default_screen)` works again. +- On X11, fix XInput handling that prevented a new window from getting the focus in some cases. +- On macOS, fix crash when pressing Caps Lock in certain configurations. +- On iOS, fixed `MonitorHandle`'s `PartialEq` and `Hash` implementations. +- On macOS, fixed undocumented cursors (e.g. zoom, resize, help) always appearing to be invalid and falling back to the default cursor. + +## 0.30.5 + +### Added + +- Add `ActiveEventLoop::system_theme()`, returning the current system theme. +- On Web, implement `Error` for `platform::web::CustomCursorError`. +- On Android, add `{Active,}EventLoopExtAndroid::android_app()` to access the app used to create the loop. + +### Fixed + +- On MacOS, fix building with `feature = "rwh_04"`. +- On Web, pen events are now routed through to `WindowEvent::Cursor*`. +- On macOS, fix panic when releasing not available monitor. +- On MacOS, return the system theme in `Window::theme()` if no theme override is set. + +## 0.30.4 + +### Changed + +- `DeviceId::dummy()` and `WindowId::dummy()` are no longer marked `unsafe`. + +### Fixed + +- On Wayland, avoid crashing when compositor is misbehaving. +- On Web, fix `WindowEvent::Resized` not using `requestAnimationFrame` when sending + `WindowEvent::RedrawRequested` and also potentially causing `WindowEvent::RedrawRequested` + to not be de-duplicated. +- Account for different browser engine implementations of pointer movement coordinate space. + +## 0.30.3 + +### Added + +- On Web, add `EventLoopExtWebSys::(set_)poll_strategy()` to allow setting + control flow strategies before starting the event loop. +- On Web, add `WaitUntilStrategy`, which allows to set different strategies for + `ControlFlow::WaitUntil`. By default the Prioritized Task Scheduling API is + used, with a fallback to `setTimeout()` with a trick to circumvent throttling + to 4ms. But an option to use a Web worker to schedule the timer is available + as well, which commonly prevents any throttling when the window is not focused. + +### Changed + +- On macOS, set the window theme on the `NSWindow` instead of application-wide. + +### Fixed + +- On X11, build on arm platforms. +- On macOS, fixed `WindowBuilder::with_theme` not having any effect on the window. + +## 0.30.2 + +### Fixed + +- On Web, fix `EventLoopProxy::send_event()` triggering event loop immediately + when not called from inside the event loop. Now queues a microtask instead. +- On Web, stop overwriting default cursor with `CursorIcon::Default`. +- On Web, prevent crash when using `InnerSizeWriter::request_inner_size()`. +- On macOS, fix not working opacity for entire window. + +## 0.30.1 + +### Added + +- Reexport `raw-window-handle` versions 0.4 and 0.5 as `raw_window_handle_04` and `raw_window_handle_05`. +- Implement `ApplicationHandler` for `&mut` references and heap allocations to something that implements `ApplicationHandler`. + +### Fixed + +- On macOS, fix panic on exit when dropping windows outside the event loop. +- On macOS, fix window dragging glitches when dragging across a monitor boundary with different scale factor. +- On macOS, fix the range in `Ime::Preedit`. +- On macOS, use the system's internal mechanisms for queuing events. +- On macOS, handle events directly instead of queuing when possible. + +## 0.30.0 + +### Added + +- Add `OwnedDisplayHandle` type for allowing safe display handle usage outside of + trivial cases. +- Add `ApplicationHandler<T>` trait which mimics `Event<T>`. +- Add `WindowBuilder::with_cursor` and `Window::set_cursor` which takes a + `CursorIcon` or `CustomCursor`. +- Add `Sync` implementation for `EventLoopProxy<T: Send>`. +- Add `Window::default_attributes` to get default `WindowAttributes`. +- Add `EventLoop::builder` to get `EventLoopBuilder` without export. +- Add `CustomCursor::from_rgba` to allow creating cursor images from RGBA data. +- Add `CustomCursorExtWebSys::from_url` to allow loading cursor images from URLs. +- Add `CustomCursorExtWebSys::from_animation` to allow creating animated + cursors from other `CustomCursor`s. +- Add `{Active,}EventLoop::create_custom_cursor` to load custom cursor image sources. +- Add `ActiveEventLoop::create_window` and `EventLoop::create_window`. +- Add `CustomCursor` which could be set via `Window::set_cursor`, implemented on + Windows, macOS, X11, Wayland, and Web. +- On Web, add to toggle calling `Event.preventDefault()` on `Window`. +- On iOS, add `PinchGesture`, `DoubleTapGesture`, `PanGesture` and `RotationGesture`. +- on iOS, use `UIGestureRecognizerDelegate` for fine grained control of gesture recognizers. +- On macOS, add services menu. +- On Windows, add `with_title_text_color`, and `with_corner_preference` on + `WindowAttributesExtWindows`. +- On Windows, implement resize increments. +- On Windows, add `AnyThread` API to access window handle off the main thread. + +### Changed + +- Bump MSRV from `1.65` to `1.70`. +- On Wayland, bump `sctk-adwaita` to `0.9.0`, which changed system library + crates. This change is a **cascading breaking change**, you must do breaking + change as well, even if you don't expose winit. +- Rename `TouchpadMagnify` to `PinchGesture`. +- Rename `SmartMagnify` to `DoubleTapGesture`. +- Rename `TouchpadRotate` to `RotationGesture`. +- Rename `EventLoopWindowTarget` to `ActiveEventLoop`. +- Rename `platform::x11::XWindowType` to `platform::x11::WindowType`. +- Rename `VideoMode` to `VideoModeHandle` to represent that it doesn't hold + static data. +- Make `Debug` formatting of `WindowId` more concise. +- Move `dpi` types to its own crate, and re-export it from the root crate. +- Replace `log` with `tracing`, use `log` feature on `tracing` to restore old + behavior. +- `EventLoop::with_user_event` now returns `EventLoopBuilder`. +- On Web, return `HandleError::Unavailable` when a window handle is not available. +- On Web, return `RawWindowHandle::WebCanvas` instead of `RawWindowHandle::Web`. +- On Web, remove queuing fullscreen request in absence of transient activation. +- On iOS, return `HandleError::Unavailable` when a window handle is not available. +- On macOS, return `HandleError::Unavailable` when a window handle is not available. +- On Windows, remove `WS_CAPTION`, `WS_BORDER`, and `WS_EX_WINDOWEDGE` styles + for child windows without decorations. +- On Android, bump `ndk` to `0.9.0` and `android-activity` to `0.6.0`, + and remove unused direct dependency on `ndk-sys`. + +### Deprecated + +- Deprecate `EventLoop::run`, use `EventLoop::run_app`. +- Deprecate `EventLoopExtRunOnDemand::run_on_demand`, use `EventLoop::run_app_on_demand`. +- Deprecate `EventLoopExtPumpEvents::pump_events`, use `EventLoopExtPumpEvents::pump_app_events`. + + The new `app` APIs accept a newly added `ApplicationHandler<T>` instead of + `Fn`. The semantics are mostly the same, given that the capture list of the + closure is your new `State`. Consider the following code: + + ```rust,no_run + use winit::event::Event; + use winit::event_loop::EventLoop; + use winit::window::Window; + + struct MyUserEvent; + + let event_loop = EventLoop::<MyUserEvent>::with_user_event().build().unwrap(); + let window = event_loop.create_window(Window::default_attributes()).unwrap(); + let mut counter = 0; + + let _ = event_loop.run(move |event, event_loop| { + match event { + Event::AboutToWait => { + window.request_redraw(); + counter += 1; + } + Event::WindowEvent { window_id, event } => { + // Handle window event. + } + Event::UserEvent(event) => { + // Handle user event. + } + Event::DeviceEvent { device_id, event } => { + // Handle device event. + } + _ => (), + } + }); + ``` + + To migrate this code, you should move all the captured values into some + newtype `State` and implement `ApplicationHandler` for this type. Finally, + we move particular `match event` arms into methods on `ApplicationHandler`, + for example: + + ```rust,no_run + use winit::application::ApplicationHandler; + use winit::event::{Event, WindowEvent, DeviceEvent, DeviceId}; + use winit::event_loop::{EventLoop, ActiveEventLoop}; + use winit::window::{Window, WindowId}; + + struct MyUserEvent; + + struct State { + window: Window, + counter: i32, + } + + impl ApplicationHandler<MyUserEvent> for State { + fn user_event(&mut self, event_loop: &ActiveEventLoop, user_event: MyUserEvent) { + // Handle user event. + } + + fn resumed(&mut self, event_loop: &ActiveEventLoop) { + // Your application got resumed. + } + + fn window_event(&mut self, event_loop: &ActiveEventLoop, window_id: WindowId, event: WindowEvent) { + // Handle window event. + } + + fn device_event(&mut self, event_loop: &ActiveEventLoop, device_id: DeviceId, event: DeviceEvent) { + // Handle device event. + } + + fn about_to_wait(&mut self, event_loop: &ActiveEventLoop) { + self.window.request_redraw(); + self.counter += 1; + } + } + + let event_loop = EventLoop::<MyUserEvent>::with_user_event().build().unwrap(); + #[allow(deprecated)] + let window = event_loop.create_window(Window::default_attributes()).unwrap(); + let mut state = State { window, counter: 0 }; + + let _ = event_loop.run_app(&mut state); + ``` + + Please submit your feedback after migrating in [this issue](https://github.com/rust-windowing/winit/issues/3626). + +- Deprecate `Window::set_cursor_icon`, use `Window::set_cursor`. + +### Removed + +- Remove `Window::new`, use `ActiveEventLoop::create_window` instead. + + You now have to create your windows inside the actively running event loop + (usually the `new_events(cause: StartCause::Init)` or `resumed()` events), + and can no longer do it before the application has properly launched. + This change is done to fix many long-standing issues on iOS and macOS, and + will improve things on Wayland once fully implemented. + + To ease migration, we provide the deprecated `EventLoop::create_window` that + will allow you to bypass this restriction in this release. + + Using the migration example from above, you can change your code as follows: + + ```rust,no_run + use winit::application::ApplicationHandler; + use winit::event::{Event, WindowEvent, DeviceEvent, DeviceId}; + use winit::event_loop::{EventLoop, ActiveEventLoop}; + use winit::window::{Window, WindowId}; + + #[derive(Default)] + struct State { + // Use an `Option` to allow the window to not be available until the + // application is properly running. + window: Option<Window>, + counter: i32, + } + + impl ApplicationHandler for State { + // This is a common indicator that you can create a window. + fn resumed(&mut self, event_loop: &ActiveEventLoop) { + self.window = Some(event_loop.create_window(Window::default_attributes()).unwrap()); + } + fn window_event(&mut self, event_loop: &ActiveEventLoop, window_id: WindowId, event: WindowEvent) { + // `unwrap` is fine, the window will always be available when + // receiving a window event. + let window = self.window.as_ref().unwrap(); + // Handle window event. + } + fn device_event(&mut self, event_loop: &ActiveEventLoop, device_id: DeviceId, event: DeviceEvent) { + // Handle window event. + } + fn about_to_wait(&mut self, event_loop: &ActiveEventLoop) { + if let Some(window) = self.window.as_ref() { + window.request_redraw(); + self.counter += 1; + } + } + } + + let event_loop = EventLoop::new().unwrap(); + let mut state = State::default(); + let _ = event_loop.run_app(&mut state); + ``` + +- Remove `Deref` implementation for `EventLoop` that gave `EventLoopWindowTarget`. +- Remove `WindowBuilder` in favor of `WindowAttributes`. +- Remove Generic parameter `T` from `ActiveEventLoop`. +- Remove `EventLoopBuilder::with_user_event`, use `EventLoop::with_user_event`. +- Remove Redundant `EventLoopError::AlreadyRunning`. +- Remove `WindowAttributes::fullscreen` and expose as field directly. +- On X11, remove `platform::x11::XNotSupported` export. + +### Fixed + +- On Web, fix setting cursor icon overriding cursor visibility. +- On Windows, fix cursor not confined to center of window when grabbed and hidden. +- On macOS, fix sequence of mouse events being out of order when dragging on the trackpad. +- On Wayland, fix decoration glitch on close with some compositors. +- On Android, fix a regression introduced in #2748 to allow volume key events to be received again. +- On Windows, don't return a valid window handle outside of the GUI thread. +- On macOS, don't set the background color when initializing a window with transparency. diff --git a/app/vendor/rune/vendor/winit/src/changelog/v0.8.md b/app/vendor/rune/vendor/winit/src/changelog/v0.8.md new file mode 100644 index 0000000..1963429 --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/changelog/v0.8.md @@ -0,0 +1,33 @@ +## 0.8.3 + +- Fixed issue of calls to `set_inner_size` blocking on Windows. +- Mapped `ISO_Left_Tab` to `VirtualKeyCode::Tab` to make the key work with modifiers +- Fixed the X11 backed on 32bit targets + +## 0.8.2 + +- Uniformize keyboard scancode values across Wayland and X11 (#297). +- Internal rework of the wayland event loop +- Added method `os::linux::WindowExt::is_ready` + +## 0.8.1 + +- Added various methods to `os::linux::EventsLoopExt`, plus some hidden items necessary to make + glutin work. + +## 0.8.0 + +- Added `Window::set_maximized`, `WindowAttributes::maximized` and `WindowBuilder::with_maximized`. +- Added `Window::set_fullscreen`. +- Changed `with_fullscreen` to take a `Option<MonitorId>` instead of a `MonitorId`. +- Removed `MonitorId::get_native_identifier()` in favor of platform-specific traits in the `os` + module. +- Changed `get_available_monitors()` and `get_primary_monitor()` to be methods of `EventsLoop` + instead of stand-alone methods. +- Changed `EventsLoop` to be tied to a specific X11 or Wayland connection. +- Added a `os::linux::EventsLoopExt` trait that makes it possible to configure the connection. +- Fixed the emscripten code, which now compiles. +- Changed the X11 fullscreen code to use `xrandr` instead of `xxf86vm`. +- Fixed the Wayland backend to produce `Refresh` event after window creation. +- Changed the `Suspended` event to be outside of `WindowEvent`. +- Fixed the X11 backend sometimes reporting the wrong virtual key (#273). diff --git a/app/vendor/rune/vendor/winit/src/changelog/v0.9.md b/app/vendor/rune/vendor/winit/src/changelog/v0.9.md new file mode 100644 index 0000000..2a9e8cc --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/changelog/v0.9.md @@ -0,0 +1,22 @@ +## 0.9.0 + +- Added event `WindowEvent::HiDPIFactorChanged`. +- Added method `MonitorId::get_hidpi_factor`. +- Deprecated `get_inner_size_pixels` and `get_inner_size_points` methods of `Window` in favor of + `get_inner_size`. +- **Breaking:** `EventsLoop` is `!Send` and `!Sync` because of platform-dependant constraints, + but `Window`, `WindowId`, `DeviceId` and `MonitorId` guaranteed to be `Send`. +- `MonitorId::get_position` now returns `(i32, i32)` instead of `(u32, u32)`. +- Rewrite of the wayland backend to use wayland-client-0.11 +- Support for dead keys on wayland for keyboard utf8 input +- Monitor enumeration on Windows is now implemented using `EnumDisplayMonitors` instead of + `EnumDisplayDevices`. This changes the value returned by `MonitorId::get_name()`. +- On Windows added `MonitorIdExt::hmonitor` method +- Impl `Clone` for `EventsLoopProxy` +- `EventsLoop::get_primary_monitor()` on X11 will fallback to any available monitor if no primary is found +- Support for touch event on wayland +- `WindowEvent`s `MouseMoved`, `MouseEntered`, and `MouseLeft` have been renamed to + `CursorMoved`, `CursorEntered`, and `CursorLeft`. +- New `DeviceEvent`s added, `MouseMotion` and `MouseWheel`. +- Send `CursorMoved` event after `CursorEntered` and `Focused` events. +- Add support for `ModifiersState`, `MouseMove`, `MouseInput`, `MouseMotion` for emscripten backend. diff --git a/app/vendor/rune/vendor/winit/src/cursor.rs b/app/vendor/rune/vendor/winit/src/cursor.rs new file mode 100644 index 0000000..7bcac54 --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/cursor.rs @@ -0,0 +1,263 @@ +use core::fmt; +use std::error::Error; +use std::hash::{Hash, Hasher}; +use std::sync::Arc; + +use cursor_icon::CursorIcon; + +use crate::platform_impl::{PlatformCustomCursor, PlatformCustomCursorSource}; + +/// The maximum width and height for a cursor when using [`CustomCursor::from_rgba`]. +pub const MAX_CURSOR_SIZE: u16 = 2048; + +const PIXEL_SIZE: usize = 4; + +/// See [`Window::set_cursor()`][crate::window::Window::set_cursor] for more details. +#[derive(Clone, Debug, Eq, Hash, PartialEq)] +pub enum Cursor { + Icon(CursorIcon), + Custom(CustomCursor), +} + +impl Default for Cursor { + fn default() -> Self { + Self::Icon(CursorIcon::default()) + } +} + +impl From<CursorIcon> for Cursor { + fn from(icon: CursorIcon) -> Self { + Self::Icon(icon) + } +} + +impl From<CustomCursor> for Cursor { + fn from(custom: CustomCursor) -> Self { + Self::Custom(custom) + } +} + +/// Use a custom image as a cursor (mouse pointer). +/// +/// Is guaranteed to be cheap to clone. +/// +/// ## Platform-specific +/// +/// **Web**: Some browsers have limits on cursor sizes usually at 128x128. +/// +/// # Example +/// +/// ```no_run +/// # use winit::event_loop::ActiveEventLoop; +/// # use winit::window::Window; +/// # fn scope(event_loop: &ActiveEventLoop, window: &Window) { +/// use winit::window::CustomCursor; +/// +/// let w = 10; +/// let h = 10; +/// let rgba = vec![255; (w * h * 4) as usize]; +/// +/// #[cfg(not(target_family = "wasm"))] +/// let source = CustomCursor::from_rgba(rgba, w, h, w / 2, h / 2).unwrap(); +/// +/// #[cfg(target_family = "wasm")] +/// let source = { +/// use winit::platform::web::CustomCursorExtWebSys; +/// CustomCursor::from_url(String::from("http://localhost:3000/cursor.png"), 0, 0) +/// }; +/// +/// let custom_cursor = event_loop.create_custom_cursor(source); +/// +/// window.set_cursor(custom_cursor.clone()); +/// # } +/// ``` +#[derive(Clone, Debug, Eq, Hash, PartialEq)] +pub struct CustomCursor { + /// Platforms should make sure this is cheap to clone. + pub(crate) inner: PlatformCustomCursor, +} + +impl CustomCursor { + /// Creates a new cursor from an rgba buffer. + /// + /// The alpha channel is assumed to be **not** premultiplied. + pub fn from_rgba( + rgba: impl Into<Vec<u8>>, + width: u16, + height: u16, + hotspot_x: u16, + hotspot_y: u16, + ) -> Result<CustomCursorSource, BadImage> { + let _span = + tracing::debug_span!("winit::Cursor::from_rgba", width, height, hotspot_x, hotspot_y) + .entered(); + + Ok(CustomCursorSource { + inner: PlatformCustomCursorSource::from_rgba( + rgba.into(), + width, + height, + hotspot_x, + hotspot_y, + )?, + }) + } +} + +/// Source for [`CustomCursor`]. +/// +/// See [`CustomCursor`] for more details. +#[derive(Debug)] +pub struct CustomCursorSource { + pub(crate) inner: PlatformCustomCursorSource, +} + +/// An error produced when using [`CustomCursor::from_rgba`] with invalid arguments. +#[derive(Debug, Clone)] +pub enum BadImage { + /// Produced when the image dimensions are larger than [`MAX_CURSOR_SIZE`]. This doesn't + /// guarantee that the cursor will work, but should avoid many platform and device specific + /// limits. + TooLarge { width: u16, height: u16 }, + /// Produced when the length of the `rgba` argument isn't divisible by 4, thus `rgba` can't be + /// safely interpreted as 32bpp RGBA pixels. + ByteCountNotDivisibleBy4 { byte_count: usize }, + /// Produced when the number of pixels (`rgba.len() / 4`) isn't equal to `width * height`. + /// At least one of your arguments is incorrect. + DimensionsVsPixelCount { width: u16, height: u16, width_x_height: u64, pixel_count: u64 }, + /// Produced when the hotspot is outside the image bounds + HotspotOutOfBounds { width: u16, height: u16, hotspot_x: u16, hotspot_y: u16 }, +} + +impl fmt::Display for BadImage { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + BadImage::TooLarge { width, height } => write!( + f, + "The specified dimensions ({width:?}x{height:?}) are too large. The maximum is \ + {MAX_CURSOR_SIZE:?}x{MAX_CURSOR_SIZE:?}.", + ), + BadImage::ByteCountNotDivisibleBy4 { byte_count } => write!( + f, + "The length of the `rgba` argument ({byte_count:?}) isn't divisible by 4, making \ + it impossible to interpret as 32bpp RGBA pixels.", + ), + BadImage::DimensionsVsPixelCount { width, height, width_x_height, pixel_count } => { + write!( + f, + "The specified dimensions ({width:?}x{height:?}) don't match the number of \ + pixels supplied by the `rgba` argument ({pixel_count:?}). For those \ + dimensions, the expected pixel count is {width_x_height:?}.", + ) + }, + BadImage::HotspotOutOfBounds { width, height, hotspot_x, hotspot_y } => write!( + f, + "The specified hotspot ({hotspot_x:?}, {hotspot_y:?}) is outside the image bounds \ + ({width:?}x{height:?}).", + ), + } + } +} + +impl Error for BadImage {} + +/// Platforms export this directly as `PlatformCustomCursorSource` if they need to only work with +/// images. +#[allow(dead_code)] +#[derive(Debug)] +pub(crate) struct OnlyCursorImageSource(pub(crate) CursorImage); + +#[allow(dead_code)] +impl OnlyCursorImageSource { + pub(crate) fn from_rgba( + rgba: Vec<u8>, + width: u16, + height: u16, + hotspot_x: u16, + hotspot_y: u16, + ) -> Result<Self, BadImage> { + CursorImage::from_rgba(rgba, width, height, hotspot_x, hotspot_y).map(Self) + } +} + +/// Platforms export this directly as `PlatformCustomCursor` if they don't implement caching. +#[allow(dead_code)] +#[derive(Debug, Clone)] +pub(crate) struct OnlyCursorImage(pub(crate) Arc<CursorImage>); + +impl Hash for OnlyCursorImage { + fn hash<H: Hasher>(&self, state: &mut H) { + Arc::as_ptr(&self.0).hash(state); + } +} + +impl PartialEq for OnlyCursorImage { + fn eq(&self, other: &Self) -> bool { + Arc::ptr_eq(&self.0, &other.0) + } +} + +impl Eq for OnlyCursorImage {} + +#[derive(Debug)] +#[allow(dead_code)] +pub(crate) struct CursorImage { + pub(crate) rgba: Vec<u8>, + pub(crate) width: u16, + pub(crate) height: u16, + pub(crate) hotspot_x: u16, + pub(crate) hotspot_y: u16, +} + +impl CursorImage { + pub(crate) fn from_rgba( + rgba: Vec<u8>, + width: u16, + height: u16, + hotspot_x: u16, + hotspot_y: u16, + ) -> Result<Self, BadImage> { + if width > MAX_CURSOR_SIZE || height > MAX_CURSOR_SIZE { + return Err(BadImage::TooLarge { width, height }); + } + + if rgba.len() % PIXEL_SIZE != 0 { + return Err(BadImage::ByteCountNotDivisibleBy4 { byte_count: rgba.len() }); + } + + let pixel_count = (rgba.len() / PIXEL_SIZE) as u64; + let width_x_height = width as u64 * height as u64; + if pixel_count != width_x_height { + return Err(BadImage::DimensionsVsPixelCount { + width, + height, + width_x_height, + pixel_count, + }); + } + + if hotspot_x >= width || hotspot_y >= height { + return Err(BadImage::HotspotOutOfBounds { width, height, hotspot_x, hotspot_y }); + } + + Ok(CursorImage { rgba, width, height, hotspot_x, hotspot_y }) + } +} + +// Platforms that don't support cursors will export this as `PlatformCustomCursor`. +#[derive(Debug, Clone, Hash, PartialEq, Eq)] +pub(crate) struct NoCustomCursor; + +#[allow(dead_code)] +impl NoCustomCursor { + pub(crate) fn from_rgba( + rgba: Vec<u8>, + width: u16, + height: u16, + hotspot_x: u16, + hotspot_y: u16, + ) -> Result<Self, BadImage> { + CursorImage::from_rgba(rgba, width, height, hotspot_x, hotspot_y)?; + Ok(Self) + } +} diff --git a/app/vendor/rune/vendor/winit/src/error.rs b/app/vendor/rune/vendor/winit/src/error.rs new file mode 100644 index 0000000..d15bb9e --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/error.rs @@ -0,0 +1,131 @@ +use std::{error, fmt}; + +use crate::platform_impl; + +// TODO: Rename +/// An error that may be generated when requesting Winit state +#[derive(Debug)] +pub enum ExternalError { + /// The operation is not supported by the backend. + NotSupported(NotSupportedError), + /// The operation was ignored. + Ignored, + /// The OS cannot perform the operation. + Os(OsError), +} + +/// The error type for when the requested operation is not supported by the backend. +#[derive(Clone)] +pub struct NotSupportedError { + _marker: (), +} + +/// The error type for when the OS cannot perform the requested operation. +#[derive(Debug)] +pub struct OsError { + line: u32, + file: &'static str, + error: platform_impl::OsError, +} + +/// A general error that may occur while running the Winit event loop +#[derive(Debug)] +pub enum EventLoopError { + /// The operation is not supported by the backend. + NotSupported(NotSupportedError), + /// The OS cannot perform the operation. + Os(OsError), + /// The event loop can't be re-created. + RecreationAttempt, + /// Application has exit with an error status. + ExitFailure(i32), +} + +impl From<OsError> for EventLoopError { + fn from(value: OsError) -> Self { + Self::Os(value) + } +} + +impl NotSupportedError { + #[inline] + #[allow(dead_code)] + pub(crate) fn new() -> NotSupportedError { + NotSupportedError { _marker: () } + } +} + +impl OsError { + #[allow(dead_code)] + pub(crate) fn new(line: u32, file: &'static str, error: platform_impl::OsError) -> OsError { + OsError { line, file, error } + } +} + +#[allow(unused_macros)] +macro_rules! os_error { + ($error:expr) => {{ + crate::error::OsError::new(line!(), file!(), $error) + }}; +} + +impl fmt::Display for OsError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> { + f.pad(&format!("os error at {}:{}: {}", self.file, self.line, self.error)) + } +} + +impl fmt::Display for ExternalError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> { + match self { + ExternalError::NotSupported(e) => e.fmt(f), + ExternalError::Ignored => write!(f, "Operation was ignored"), + ExternalError::Os(e) => e.fmt(f), + } + } +} + +impl fmt::Debug for NotSupportedError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> { + f.debug_struct("NotSupportedError").finish() + } +} + +impl fmt::Display for NotSupportedError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> { + f.pad("the requested operation is not supported by Winit") + } +} + +impl fmt::Display for EventLoopError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> { + match self { + EventLoopError::RecreationAttempt => write!(f, "EventLoop can't be recreated"), + EventLoopError::NotSupported(e) => e.fmt(f), + EventLoopError::Os(e) => e.fmt(f), + EventLoopError::ExitFailure(status) => write!(f, "Exit Failure: {status}"), + } + } +} + +impl error::Error for OsError {} +impl error::Error for ExternalError {} +impl error::Error for NotSupportedError {} +impl error::Error for EventLoopError {} + +#[cfg(test)] +#[allow(clippy::redundant_clone)] +mod tests { + use super::*; + + // Eat attributes for testing + #[test] + fn ensure_fmt_does_not_panic() { + let _ = format!("{:?}, {}", NotSupportedError::new(), NotSupportedError::new().clone()); + let _ = format!( + "{:?}, {}", + ExternalError::NotSupported(NotSupportedError::new()), + ExternalError::NotSupported(NotSupportedError::new()) + ); + } +} diff --git a/app/vendor/rune/vendor/winit/src/event.rs b/app/vendor/rune/vendor/winit/src/event.rs new file mode 100644 index 0000000..4e01420 --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/event.rs @@ -0,0 +1,1183 @@ +//! The [`Event`] enum and assorted supporting types. +//! +//! These are sent to the closure given to [`EventLoop::run_app(...)`], where they get +//! processed and used to modify the program state. For more details, see the root-level +//! documentation. +//! +//! Some of these events represent different "parts" of a traditional event-handling loop. You could +//! approximate the basic ordering loop of [`EventLoop::run_app(...)`] like this: +//! +//! ```rust,ignore +//! let mut start_cause = StartCause::Init; +//! +//! while !elwt.exiting() { +//! app.new_events(event_loop, start_cause); +//! +//! for event in (window events, user events, device events) { +//! // This will pick the right method on the application based on the event. +//! app.handle_event(event_loop, event); +//! } +//! +//! for window_id in (redraw windows) { +//! app.window_event(event_loop, window_id, RedrawRequested); +//! } +//! +//! app.about_to_wait(event_loop); +//! start_cause = wait_if_necessary(); +//! } +//! +//! app.exiting(event_loop); +//! ``` +//! +//! This leaves out timing details like [`ControlFlow::WaitUntil`] but hopefully +//! describes what happens in what order. +//! +//! [`EventLoop::run_app(...)`]: crate::event_loop::EventLoop::run_app +//! [`ControlFlow::WaitUntil`]: crate::event_loop::ControlFlow::WaitUntil +use std::path::PathBuf; +use std::sync::{Mutex, Weak}; +#[cfg(not(web_platform))] +use std::time::Instant; + +#[cfg(feature = "serde")] +use serde::{Deserialize, Serialize}; +use smol_str::SmolStr; +#[cfg(web_platform)] +use web_time::Instant; + +use crate::dpi::{PhysicalPosition, PhysicalSize}; +use crate::error::ExternalError; +use crate::event_loop::AsyncRequestSerial; +use crate::keyboard::{self, ModifiersKeyState, ModifiersKeys, ModifiersState}; +use crate::platform_impl; +#[cfg(doc)] +use crate::window::Window; +use crate::window::{ActivationToken, Theme, WindowId}; + +/// Describes a generic event. +/// +/// See the module-level docs for more information on the event loop manages each event. +#[derive(Debug, Clone, PartialEq)] +pub enum Event<T: 'static> { + /// See [`ApplicationHandler::new_events`] for details. + /// + /// [`ApplicationHandler::new_events`]: crate::application::ApplicationHandler::new_events + NewEvents(StartCause), + + /// See [`ApplicationHandler::window_event`] for details. + /// + /// [`ApplicationHandler::window_event`]: crate::application::ApplicationHandler::window_event + WindowEvent { window_id: WindowId, event: WindowEvent }, + + /// See [`ApplicationHandler::device_event`] for details. + /// + /// [`ApplicationHandler::device_event`]: crate::application::ApplicationHandler::device_event + DeviceEvent { device_id: DeviceId, event: DeviceEvent }, + + /// See [`ApplicationHandler::user_event`] for details. + /// + /// [`ApplicationHandler::user_event`]: crate::application::ApplicationHandler::user_event + UserEvent(T), + + /// See [`ApplicationHandler::suspended`] for details. + /// + /// [`ApplicationHandler::suspended`]: crate::application::ApplicationHandler::suspended + Suspended, + + /// See [`ApplicationHandler::resumed`] for details. + /// + /// [`ApplicationHandler::resumed`]: crate::application::ApplicationHandler::resumed + Resumed, + + /// See [`ApplicationHandler::about_to_wait`] for details. + /// + /// [`ApplicationHandler::about_to_wait`]: crate::application::ApplicationHandler::about_to_wait + AboutToWait, + + /// See [`ApplicationHandler::exiting`] for details. + /// + /// [`ApplicationHandler::exiting`]: crate::application::ApplicationHandler::exiting + LoopExiting, + + /// See [`ApplicationHandler::memory_warning`] for details. + /// + /// [`ApplicationHandler::memory_warning`]: crate::application::ApplicationHandler::memory_warning + MemoryWarning, +} + +impl<T> Event<T> { + #[allow(clippy::result_large_err)] + pub fn map_nonuser_event<U>(self) -> Result<Event<U>, Event<T>> { + use self::Event::*; + match self { + UserEvent(_) => Err(self), + WindowEvent { window_id, event } => Ok(WindowEvent { window_id, event }), + DeviceEvent { device_id, event } => Ok(DeviceEvent { device_id, event }), + NewEvents(cause) => Ok(NewEvents(cause)), + AboutToWait => Ok(AboutToWait), + LoopExiting => Ok(LoopExiting), + Suspended => Ok(Suspended), + Resumed => Ok(Resumed), + MemoryWarning => Ok(MemoryWarning), + } + } +} + +/// Describes the reason the event loop is resuming. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum StartCause { + /// Sent if the time specified by [`ControlFlow::WaitUntil`] has been reached. Contains the + /// moment the timeout was requested and the requested resume time. The actual resume time is + /// guaranteed to be equal to or after the requested resume time. + /// + /// [`ControlFlow::WaitUntil`]: crate::event_loop::ControlFlow::WaitUntil + ResumeTimeReached { start: Instant, requested_resume: Instant }, + + /// Sent if the OS has new events to send to the window, after a wait was requested. Contains + /// the moment the wait was requested and the resume time, if requested. + WaitCancelled { start: Instant, requested_resume: Option<Instant> }, + + /// Sent if the event loop is being resumed after the loop's control flow was set to + /// [`ControlFlow::Poll`]. + /// + /// [`ControlFlow::Poll`]: crate::event_loop::ControlFlow::Poll + Poll, + + /// Sent once, immediately after `run` is called. Indicates that the loop was just initialized. + Init, +} + +/// Describes an event from a [`Window`]. +#[derive(Debug, Clone, PartialEq)] +pub enum WindowEvent { + /// The activation token was delivered back and now could be used. + #[cfg_attr(not(any(x11_platform, wayland_platform)), allow(rustdoc::broken_intra_doc_links))] + /// Delivered in response to [`request_activation_token`]. + /// + /// [`request_activation_token`]: crate::platform::startup_notify::WindowExtStartupNotify::request_activation_token + ActivationTokenDone { serial: AsyncRequestSerial, token: ActivationToken }, + + /// The size of the window has changed. Contains the client area's new dimensions. + Resized(PhysicalSize<u32>), + + /// The position of the window has changed. Contains the window's new position. + /// + /// ## Platform-specific + /// + /// - **iOS / Android / Web / Wayland:** Unsupported. + Moved(PhysicalPosition<i32>), + + /// The window has been requested to close. + CloseRequested, + + /// The window has been destroyed. + Destroyed, + + /// A file has been dropped into the window. + /// + /// When the user drops multiple files at once, this event will be emitted for each file + /// separately. + DroppedFile(PathBuf), + + /// A file is being hovered over the window. + /// + /// When the user hovers multiple files at once, this event will be emitted for each file + /// separately. + HoveredFile(PathBuf), + + /// A file was hovered, but has exited the window. + /// + /// There will be a single `HoveredFileCancelled` event triggered even if multiple files were + /// hovered. + HoveredFileCancelled, + + /// The window gained or lost focus. + /// + /// The parameter is true if the window has gained focus, and false if it has lost focus. + Focused(bool), + + /// An event from the keyboard has been received. + /// + /// ## Platform-specific + /// - **Windows:** The shift key overrides NumLock. In other words, while shift is held down, + /// numpad keys act as if NumLock wasn't active. When this is used, the OS sends fake key + /// events which are not marked as `is_synthetic`. + KeyboardInput { + device_id: DeviceId, + event: KeyEvent, + + /// If `true`, the event was generated synthetically by winit + /// in one of the following circumstances: + /// + /// * Synthetic key press events are generated for all keys pressed when a window gains + /// focus. Likewise, synthetic key release events are generated for all keys pressed when + /// a window goes out of focus. ***Currently, this is only functional on X11 and + /// Windows*** + /// + /// Otherwise, this value is always `false`. + is_synthetic: bool, + }, + + /// The keyboard modifiers have changed. + ModifiersChanged(Modifiers), + + /// An event from an input method. + /// + /// **Note:** You have to explicitly enable this event using [`Window::set_ime_allowed`]. + /// + /// ## Platform-specific + /// + /// - **iOS / Android / Web / Orbital:** Unsupported. + Ime(Ime), + + /// The cursor has moved on the window. + /// + /// ## Platform-specific + /// + /// - **Web:** Doesn't take into account CSS [`border`], [`padding`], or [`transform`]. + /// + /// [`border`]: https://developer.mozilla.org/en-US/docs/Web/CSS/border + /// [`padding`]: https://developer.mozilla.org/en-US/docs/Web/CSS/padding + /// [`transform`]: https://developer.mozilla.org/en-US/docs/Web/CSS/transform + CursorMoved { + device_id: DeviceId, + + /// (x,y) coords in pixels relative to the top-left corner of the window. Because the range + /// of this data is limited by the display area and it may have been transformed by + /// the OS to implement effects such as cursor acceleration, it should not be used + /// to implement non-cursor-like interactions such as 3D camera control. + position: PhysicalPosition<f64>, + }, + + /// The cursor has entered the window. + /// + /// ## Platform-specific + /// + /// - **Web:** Doesn't take into account CSS [`border`], [`padding`], or [`transform`]. + /// + /// [`border`]: https://developer.mozilla.org/en-US/docs/Web/CSS/border + /// [`padding`]: https://developer.mozilla.org/en-US/docs/Web/CSS/padding + /// [`transform`]: https://developer.mozilla.org/en-US/docs/Web/CSS/transform + CursorEntered { device_id: DeviceId }, + + /// The cursor has left the window. + /// + /// ## Platform-specific + /// + /// - **Web:** Doesn't take into account CSS [`border`], [`padding`], or [`transform`]. + /// + /// [`border`]: https://developer.mozilla.org/en-US/docs/Web/CSS/border + /// [`padding`]: https://developer.mozilla.org/en-US/docs/Web/CSS/padding + /// [`transform`]: https://developer.mozilla.org/en-US/docs/Web/CSS/transform + CursorLeft { device_id: DeviceId }, + + /// A mouse wheel movement or touchpad scroll occurred. + MouseWheel { device_id: DeviceId, delta: MouseScrollDelta, phase: TouchPhase }, + + /// An mouse button press has been received. + MouseInput { device_id: DeviceId, state: ElementState, button: MouseButton }, + + /// Two-finger pinch gesture, often used for magnification. + /// + /// ## Platform-specific + /// + /// - Only available on **macOS** and **iOS**. + /// - On iOS, not recognized by default. It must be enabled when needed. + PinchGesture { + device_id: DeviceId, + /// Positive values indicate magnification (zooming in) and negative + /// values indicate shrinking (zooming out). + /// + /// This value may be NaN. + delta: f64, + phase: TouchPhase, + }, + + /// N-finger pan gesture + /// + /// ## Platform-specific + /// + /// - Only available on **iOS**. + /// - On iOS, not recognized by default. It must be enabled when needed. + PanGesture { + device_id: DeviceId, + /// Change in pixels of pan gesture from last update. + delta: PhysicalPosition<f32>, + phase: TouchPhase, + }, + + /// Double tap gesture. + /// + /// On a Mac, smart magnification is triggered by a double tap with two fingers + /// on the trackpad and is commonly used to zoom on a certain object + /// (e.g. a paragraph of a PDF) or (sort of like a toggle) to reset any zoom. + /// The gesture is also supported in Safari, Pages, etc. + /// + /// The event is general enough that its generating gesture is allowed to vary + /// across platforms. It could also be generated by another device. + /// + /// Unfortunately, neither [Windows](https://support.microsoft.com/en-us/windows/touch-gestures-for-windows-a9d28305-4818-a5df-4e2b-e5590f850741) + /// nor [Wayland](https://wayland.freedesktop.org/libinput/doc/latest/gestures.html) + /// support this gesture or any other gesture with the same effect. + /// + /// ## Platform-specific + /// + /// - Only available on **macOS 10.8** and later, and **iOS**. + /// - On iOS, not recognized by default. It must be enabled when needed. + DoubleTapGesture { device_id: DeviceId }, + + /// Two-finger rotation gesture. + /// + /// Positive delta values indicate rotation counterclockwise and + /// negative delta values indicate rotation clockwise. + /// + /// ## Platform-specific + /// + /// - Only available on **macOS** and **iOS**. + /// - On iOS, not recognized by default. It must be enabled when needed. + RotationGesture { + device_id: DeviceId, + /// change in rotation in degrees + delta: f32, + phase: TouchPhase, + }, + + /// Touchpad pressure event. + /// + /// At the moment, only supported on Apple forcetouch-capable macbooks. + /// The parameters are: pressure level (value between 0 and 1 representing how hard the + /// touchpad is being pressed) and stage (integer representing the click level). + TouchpadPressure { device_id: DeviceId, pressure: f32, stage: i64 }, + + /// Motion on some analog axis. May report data redundant to other, more specific events. + AxisMotion { device_id: DeviceId, axis: AxisId, value: f64 }, + + /// Touch event has been received + /// + /// ## Platform-specific + /// + /// - **Web:** Doesn't take into account CSS [`border`], [`padding`], or [`transform`]. + /// - **macOS:** Unsupported. + /// + /// [`border`]: https://developer.mozilla.org/en-US/docs/Web/CSS/border + /// [`padding`]: https://developer.mozilla.org/en-US/docs/Web/CSS/padding + /// [`transform`]: https://developer.mozilla.org/en-US/docs/Web/CSS/transform + Touch(Touch), + + /// The window's scale factor has changed. + /// + /// The following user actions can cause DPI changes: + /// + /// * Changing the display's resolution. + /// * Changing the display's scale factor (e.g. in Control Panel on Windows). + /// * Moving the window to a display with a different scale factor. + /// + /// To update the window size, use the provided [`InnerSizeWriter`] handle. By default, the + /// window is resized to the value suggested by the OS, but it can be changed to any value. + /// + /// For more information about DPI in general, see the [`dpi`] crate. + ScaleFactorChanged { + scale_factor: f64, + /// Handle to update inner size during scale changes. + /// + /// See [`InnerSizeWriter`] docs for more details. + inner_size_writer: InnerSizeWriter, + }, + + /// The system window theme has changed. + /// + /// Applications might wish to react to this to change the theme of the content of the window + /// when the system changes the window theme. + /// + /// This only reports a change if the window theme was not overridden by [`Window::set_theme`]. + /// + /// ## Platform-specific + /// + /// - **iOS / Android / X11 / Wayland / Orbital:** Unsupported. + ThemeChanged(Theme), + + /// The window has been occluded (completely hidden from view). + /// + /// This is different to window visibility as it depends on whether the window is closed, + /// minimised, set invisible, or fully occluded by another window. + /// + /// ## Platform-specific + /// + /// ### iOS + /// + /// On iOS, the `Occluded(false)` event is emitted in response to an + /// [`applicationWillEnterForeground`] callback which means the application should start + /// preparing its data. The `Occluded(true)` event is emitted in response to an + /// [`applicationDidEnterBackground`] callback which means the application should free + /// resources (according to the [iOS application lifecycle]). + /// + /// [`applicationWillEnterForeground`]: https://developer.apple.com/documentation/uikit/uiapplicationdelegate/1623076-applicationwillenterforeground + /// [`applicationDidEnterBackground`]: https://developer.apple.com/documentation/uikit/uiapplicationdelegate/1622997-applicationdidenterbackground + /// [iOS application lifecycle]: https://developer.apple.com/documentation/uikit/app_and_environment/managing_your_app_s_life_cycle + /// + /// ### Others + /// + /// - **Web:** Doesn't take into account CSS [`border`], [`padding`], or [`transform`]. + /// - **Android / Wayland / Windows / Orbital:** Unsupported. + /// + /// [`border`]: https://developer.mozilla.org/en-US/docs/Web/CSS/border + /// [`padding`]: https://developer.mozilla.org/en-US/docs/Web/CSS/padding + /// [`transform`]: https://developer.mozilla.org/en-US/docs/Web/CSS/transform + Occluded(bool), + + /// Emitted when a window should be redrawn. + /// + /// This gets triggered in two scenarios: + /// - The OS has performed an operation that's invalidated the window's contents (such as + /// resizing the window). + /// - The application has explicitly requested a redraw via [`Window::request_redraw`]. + /// + /// Winit will aggregate duplicate redraw requests into a single event, to + /// help avoid duplicating rendering work. + RedrawRequested, +} + +/// Identifier of an input device. +/// +/// Whenever you receive an event arising from a particular input device, this event contains a +/// `DeviceId` which identifies its origin. Note that devices may be virtual (representing an +/// on-screen cursor and keyboard focus) or physical. Virtual devices typically aggregate inputs +/// from multiple physical devices. +#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub struct DeviceId(pub(crate) platform_impl::DeviceId); + +impl DeviceId { + /// Returns a dummy id, useful for unit testing. + /// + /// # Notes + /// + /// The only guarantee made about the return value of this function is that + /// it will always be equal to itself and to future values returned by this function. + /// No other guarantees are made. This may be equal to a real `DeviceId`. + pub const fn dummy() -> Self { + DeviceId(platform_impl::DeviceId::dummy()) + } +} + +/// Represents raw hardware events that are not associated with any particular window. +/// +/// Useful for interactions that diverge significantly from a conventional 2D GUI, such as 3D camera +/// or first-person game controls. Many physical actions, such as mouse movement, can produce both +/// device and window events. Because window events typically arise from virtual devices +/// (corresponding to GUI cursors and keyboard focus) the device IDs may not match. +/// +/// Note that these events are delivered regardless of input focus. +#[derive(Clone, Debug, PartialEq)] +pub enum DeviceEvent { + Added, + Removed, + + /// Change in physical position of a pointing device. + /// + /// This represents raw, unfiltered physical motion. Not to be confused with + /// [`WindowEvent::CursorMoved`]. + MouseMotion { + /// (x, y) change in position in unspecified units. + /// + /// Different devices may use different units. + delta: (f64, f64), + }, + + /// Physical scroll event + MouseWheel { + delta: MouseScrollDelta, + }, + + /// Motion on some analog axis. This event will be reported for all arbitrary input devices + /// that winit supports on this platform, including mouse devices. If the device is a mouse + /// device then this will be reported alongside the MouseMotion event. + Motion { + axis: AxisId, + value: f64, + }, + + Button { + button: ButtonId, + state: ElementState, + }, + + Key(RawKeyEvent), +} + +/// Describes a keyboard input as a raw device event. +/// +/// Note that holding down a key may produce repeated `RawKeyEvent`s. The +/// operating system doesn't provide information whether such an event is a +/// repeat or the initial keypress. An application may emulate this by, for +/// example keeping a Map/Set of pressed keys and determining whether a keypress +/// corresponds to an already pressed key. +#[derive(Debug, Clone, Eq, PartialEq, Hash)] +#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] +pub struct RawKeyEvent { + pub physical_key: keyboard::PhysicalKey, + pub state: ElementState, +} + +/// Describes a keyboard input targeting a window. +#[derive(Debug, Clone, Eq, PartialEq, Hash)] +pub struct KeyEvent { + /// Represents the position of a key independent of the currently active layout. + /// + /// It also uniquely identifies the physical key (i.e. it's mostly synonymous with a scancode). + /// The most prevalent use case for this is games. For example the default keys for the player + /// to move around might be the W, A, S, and D keys on a US layout. The position of these keys + /// is more important than their label, so they should map to Z, Q, S, and D on an "AZERTY" + /// layout. (This value is `KeyCode::KeyW` for the Z key on an AZERTY layout.) + /// + /// ## Caveats + /// + /// - Certain niche hardware will shuffle around physical key positions, e.g. a keyboard that + /// implements DVORAK in hardware (or firmware) + /// - Your application will likely have to handle keyboards which are missing keys that your + /// own keyboard has. + /// - Certain `KeyCode`s will move between a couple of different positions depending on what + /// layout the keyboard was manufactured to support. + /// + /// **Because of these caveats, it is important that you provide users with a way to configure + /// most (if not all) keybinds in your application.** + /// + /// ## `Fn` and `FnLock` + /// + /// `Fn` and `FnLock` key events are *exceedingly unlikely* to be emitted by Winit. These keys + /// are usually handled at the hardware or OS level, and aren't surfaced to applications. If + /// you somehow see this in the wild, we'd like to know :) + pub physical_key: keyboard::PhysicalKey, + + // Allowing `broken_intra_doc_links` for `logical_key`, because + // `key_without_modifiers` is not available on all platforms + #[cfg_attr( + not(any(windows_platform, macos_platform, x11_platform, wayland_platform)), + allow(rustdoc::broken_intra_doc_links) + )] + /// This value is affected by all modifiers except <kbd>Ctrl</kbd>. + /// + /// This has two use cases: + /// - Allows querying whether the current input is a Dead key. + /// - Allows handling key-bindings on platforms which don't support [`key_without_modifiers`]. + /// + /// If you use this field (or [`key_without_modifiers`] for that matter) for keyboard + /// shortcuts, **it is important that you provide users with a way to configure your + /// application's shortcuts so you don't render your application unusable for users with an + /// incompatible keyboard layout.** + /// + /// ## Platform-specific + /// - **Web:** Dead keys might be reported as the real key instead of `Dead` depending on the + /// browser/OS. + /// + /// [`key_without_modifiers`]: crate::platform::modifier_supplement::KeyEventExtModifierSupplement::key_without_modifiers + pub logical_key: keyboard::Key, + + /// Contains the text produced by this keypress. + /// + /// In most cases this is identical to the content + /// of the `Character` variant of `logical_key`. + /// However, on Windows when a dead key was pressed earlier + /// but cannot be combined with the character from this + /// keypress, the produced text will consist of two characters: + /// the dead-key-character followed by the character resulting + /// from this keypress. + /// + /// An additional difference from `logical_key` is that + /// this field stores the text representation of any key + /// that has such a representation. For example when + /// `logical_key` is `Key::Named(NamedKey::Enter)`, this field is `Some("\r")`. + /// + /// This is `None` if the current keypress cannot + /// be interpreted as text. + /// + /// See also: `text_with_all_modifiers()` + pub text: Option<SmolStr>, + + /// Contains the location of this key on the keyboard. + /// + /// Certain keys on the keyboard may appear in more than once place. For example, the "Shift" + /// key appears on the left side of the QWERTY keyboard as well as the right side. However, + /// both keys have the same symbolic value. Another example of this phenomenon is the "1" + /// key, which appears both above the "Q" key and as the "Keypad 1" key. + /// + /// This field allows the user to differentiate between keys like this that have the same + /// symbolic value but different locations on the keyboard. + /// + /// See the [`KeyLocation`] type for more details. + /// + /// [`KeyLocation`]: crate::keyboard::KeyLocation + pub location: keyboard::KeyLocation, + + /// Whether the key is being pressed or released. + /// + /// See the [`ElementState`] type for more details. + pub state: ElementState, + + /// Whether or not this key is a key repeat event. + /// + /// On some systems, holding down a key for some period of time causes that key to be repeated + /// as though it were being pressed and released repeatedly. This field is `true` if and only + /// if this event is the result of one of those repeats. + /// + /// # Example + /// + /// In games, you often want to ignore repeated key events - this can be + /// done by ignoring events where this property is set. + /// + /// ``` + /// use winit::event::{ElementState, KeyEvent, WindowEvent}; + /// use winit::keyboard::{KeyCode, PhysicalKey}; + /// # let window_event = WindowEvent::RedrawRequested; // To make the example compile + /// match window_event { + /// WindowEvent::KeyboardInput { + /// event: + /// KeyEvent { + /// physical_key: PhysicalKey::Code(KeyCode::KeyW), + /// state: ElementState::Pressed, + /// repeat: false, + /// .. + /// }, + /// .. + /// } => { + /// // The physical key `W` was pressed, and it was not a repeat + /// }, + /// _ => {}, // Handle other events + /// } + /// ``` + pub repeat: bool, + + /// Platform-specific key event information. + /// + /// On Windows, Linux and macOS, this type contains the key without modifiers and the text with + /// all modifiers applied. + /// + /// On Android, iOS, Redox and Web, this type is a no-op. + pub(crate) platform_specific: platform_impl::KeyEventExtra, +} + +/// Describes keyboard modifiers event. +#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)] +pub struct Modifiers { + pub(crate) state: ModifiersState, + + // NOTE: Currently pressed modifiers keys. + // + // The field providing a metadata, it shouldn't be used as a source of truth. + pub(crate) pressed_mods: ModifiersKeys, +} + +impl Modifiers { + /// The state of the modifiers. + pub fn state(&self) -> ModifiersState { + self.state + } + + /// The state of the left shift key. + pub fn lshift_state(&self) -> ModifiersKeyState { + self.mod_state(ModifiersKeys::LSHIFT) + } + + /// The state of the right shift key. + pub fn rshift_state(&self) -> ModifiersKeyState { + self.mod_state(ModifiersKeys::RSHIFT) + } + + /// The state of the left alt key. + pub fn lalt_state(&self) -> ModifiersKeyState { + self.mod_state(ModifiersKeys::LALT) + } + + /// The state of the right alt key. + pub fn ralt_state(&self) -> ModifiersKeyState { + self.mod_state(ModifiersKeys::RALT) + } + + /// The state of the left control key. + pub fn lcontrol_state(&self) -> ModifiersKeyState { + self.mod_state(ModifiersKeys::LCONTROL) + } + + /// The state of the right control key. + pub fn rcontrol_state(&self) -> ModifiersKeyState { + self.mod_state(ModifiersKeys::RCONTROL) + } + + /// The state of the left super key. + pub fn lsuper_state(&self) -> ModifiersKeyState { + self.mod_state(ModifiersKeys::LSUPER) + } + + /// The state of the right super key. + pub fn rsuper_state(&self) -> ModifiersKeyState { + self.mod_state(ModifiersKeys::RSUPER) + } + + fn mod_state(&self, modifier: ModifiersKeys) -> ModifiersKeyState { + if self.pressed_mods.contains(modifier) { + ModifiersKeyState::Pressed + } else { + ModifiersKeyState::Unknown + } + } +} + +impl From<ModifiersState> for Modifiers { + fn from(value: ModifiersState) -> Self { + Self { state: value, pressed_mods: Default::default() } + } +} + +/// Describes [input method](https://en.wikipedia.org/wiki/Input_method) events. +/// +/// This is also called a "composition event". +/// +/// Most keypresses using a latin-like keyboard layout simply generate a +/// [`WindowEvent::KeyboardInput`]. However, one couldn't possibly have a key for every single +/// unicode character that the user might want to type +/// - so the solution operating systems employ is to allow the user to type these using _a sequence +/// of keypresses_ instead. +/// +/// A prominent example of this is accents - many keyboard layouts allow you to first click the +/// "accent key", and then the character you want to apply the accent to. In this case, some +/// platforms will generate the following event sequence: +/// +/// ```ignore +/// // Press "`" key +/// Ime::Preedit("`", Some((0, 0))) +/// // Press "E" key +/// Ime::Preedit("", None) // Synthetic event generated by winit to clear preedit. +/// Ime::Commit("é") +/// ``` +/// +/// Additionally, certain input devices are configured to display a candidate box that allow the +/// user to select the desired character interactively. (To properly position this box, you must use +/// [`Window::set_ime_cursor_area`].) +/// +/// An example of a keyboard layout which uses candidate boxes is pinyin. On a latin keyboard the +/// following event sequence could be obtained: +/// +/// ```ignore +/// // Press "A" key +/// Ime::Preedit("a", Some((1, 1))) +/// // Press "B" key +/// Ime::Preedit("a b", Some((3, 3))) +/// // Press left arrow key +/// Ime::Preedit("a b", Some((1, 1))) +/// // Press space key +/// Ime::Preedit("啊b", Some((3, 3))) +/// // Press space key +/// Ime::Preedit("", None) // Synthetic event generated by winit to clear preedit. +/// Ime::Commit("啊不") +/// ``` +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] +pub enum Ime { + /// Notifies when the IME was enabled. + /// + /// After getting this event you could receive [`Preedit`][Self::Preedit] and + /// [`Commit`][Self::Commit] events. You should also start performing IME related requests + /// like [`Window::set_ime_cursor_area`]. + Enabled, + + /// Notifies when a new composing text should be set at the cursor position. + /// + /// The value represents a pair of the preedit string and the cursor begin position and end + /// position. When it's `None`, the cursor should be hidden. When `String` is an empty string + /// this indicates that preedit was cleared. + /// + /// The cursor position is byte-wise indexed. + Preedit(String, Option<(usize, usize)>), + + /// Notifies when text should be inserted into the editor widget. + /// + /// Right before this event winit will send empty [`Self::Preedit`] event. + Commit(String), + + /// Notifies when the IME was disabled. + /// + /// After receiving this event you won't get any more [`Preedit`][Self::Preedit] or + /// [`Commit`][Self::Commit] events until the next [`Enabled`][Self::Enabled] event. You should + /// also stop issuing IME related requests like [`Window::set_ime_cursor_area`] and clear + /// pending preedit text. + Disabled, +} + +/// Describes touch-screen input state. +#[derive(Debug, Hash, PartialEq, Eq, Clone, Copy)] +#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] +pub enum TouchPhase { + Started, + Moved, + Ended, + Cancelled, +} + +/// Represents a touch event +/// +/// Every time the user touches the screen, a new [`TouchPhase::Started`] event with an unique +/// identifier for the finger is generated. When the finger is lifted, an [`TouchPhase::Ended`] +/// event is generated with the same finger id. +/// +/// After a `Started` event has been emitted, there may be zero or more `Move` +/// events when the finger is moved or the touch pressure changes. +/// +/// The finger id may be reused by the system after an `Ended` event. The user +/// should assume that a new `Started` event received with the same id has nothing +/// to do with the old finger and is a new finger. +/// +/// A [`TouchPhase::Cancelled`] event is emitted when the system has canceled tracking this +/// touch, such as when the window loses focus, or on iOS if the user moves the +/// device against their face. +/// +/// ## Platform-specific +/// +/// - **Web:** Doesn't take into account CSS [`border`], [`padding`], or [`transform`]. +/// - **macOS:** Unsupported. +/// +/// [`border`]: https://developer.mozilla.org/en-US/docs/Web/CSS/border +/// [`padding`]: https://developer.mozilla.org/en-US/docs/Web/CSS/padding +/// [`transform`]: https://developer.mozilla.org/en-US/docs/Web/CSS/transform +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct Touch { + pub device_id: DeviceId, + pub phase: TouchPhase, + pub location: PhysicalPosition<f64>, + /// Describes how hard the screen was pressed. May be `None` if the platform + /// does not support pressure sensitivity. + /// + /// ## Platform-specific + /// + /// - Only available on **iOS** 9.0+, **Windows** 8+, **Web**, and **Android**. + /// - **Android**: This will never be [None]. If the device doesn't support pressure + /// sensitivity, force will either be 0.0 or 1.0. Also see the + /// [android documentation](https://developer.android.com/reference/android/view/MotionEvent#AXIS_PRESSURE). + pub force: Option<Force>, + /// Unique identifier of a finger. + pub id: u64, +} + +/// Describes the force of a touch event +#[derive(Debug, Clone, Copy, PartialEq)] +pub enum Force { + /// On iOS, the force is calibrated so that the same number corresponds to + /// roughly the same amount of pressure on the screen regardless of the + /// device. + Calibrated { + /// The force of the touch, where a value of 1.0 represents the force of + /// an average touch (predetermined by the system, not user-specific). + /// + /// The force reported by Apple Pencil is measured along the axis of the + /// pencil. If you want a force perpendicular to the device, you need to + /// calculate this value using the `altitude_angle` value. + force: f64, + /// The maximum possible force for a touch. + /// + /// The value of this field is sufficiently high to provide a wide + /// dynamic range for values of the `force` field. + max_possible_force: f64, + /// The altitude (in radians) of the stylus. + /// + /// A value of 0 radians indicates that the stylus is parallel to the + /// surface. The value of this property is Pi/2 when the stylus is + /// perpendicular to the surface. + altitude_angle: Option<f64>, + }, + /// If the platform reports the force as normalized, we have no way of + /// knowing how much pressure 1.0 corresponds to – we know it's the maximum + /// amount of force, but as to how much force, you might either have to + /// press really really hard, or not hard at all, depending on the device. + Normalized(f64), +} + +impl Force { + /// Returns the force normalized to the range between 0.0 and 1.0 inclusive. + /// + /// Instead of normalizing the force, you should prefer to handle + /// [`Force::Calibrated`] so that the amount of force the user has to apply is + /// consistent across devices. + pub fn normalized(&self) -> f64 { + match self { + Force::Calibrated { force, max_possible_force, altitude_angle } => { + let force = match altitude_angle { + Some(altitude_angle) => force / altitude_angle.sin(), + None => *force, + }; + force / max_possible_force + }, + Force::Normalized(force) => *force, + } + } +} + +/// Identifier for a specific analog axis on some device. +pub type AxisId = u32; + +/// Identifier for a specific button on some device. +pub type ButtonId = u32; + +/// Describes the input state of a key. +#[derive(Debug, Hash, PartialEq, Eq, Clone, Copy)] +#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] +pub enum ElementState { + Pressed, + Released, +} + +impl ElementState { + /// True if `self == Pressed`. + pub fn is_pressed(self) -> bool { + self == ElementState::Pressed + } +} + +/// Describes a button of a mouse controller. +/// +/// ## Platform-specific +/// +/// **macOS:** `Back` and `Forward` might not work with all hardware. +/// **Orbital:** `Back` and `Forward` are unsupported due to orbital not supporting them. +#[derive(Debug, Hash, PartialEq, Eq, PartialOrd, Ord, Clone, Copy)] +#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] +pub enum MouseButton { + Left, + Right, + Middle, + Back, + Forward, + Other(u16), +} + +/// Describes a difference in the mouse scroll wheel state. +#[derive(Debug, Clone, Copy, PartialEq)] +#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] +pub enum MouseScrollDelta { + /// Amount in lines or rows to scroll in the horizontal + /// and vertical directions. + /// + /// Positive values indicate that the content that is being scrolled should move + /// right and down (revealing more content left and up). + LineDelta(f32, f32), + + /// Amount in pixels to scroll in the horizontal and + /// vertical direction. + /// + /// Scroll events are expressed as a `PixelDelta` if + /// supported by the device (eg. a touchpad) and + /// platform. + /// + /// Positive values indicate that the content being scrolled should + /// move right/down. + /// + /// For a 'natural scrolling' touch pad (that acts like a touch screen) + /// this means moving your fingers right and down should give positive values, + /// and move the content right and down (to reveal more things left and up). + PixelDelta(PhysicalPosition<f64>), +} + +/// Handle to synchronously change the size of the window from the +/// [`WindowEvent`]. +#[derive(Debug, Clone)] +pub struct InnerSizeWriter { + pub(crate) new_inner_size: Weak<Mutex<PhysicalSize<u32>>>, +} + +impl InnerSizeWriter { + #[cfg(not(orbital_platform))] + pub(crate) fn new(new_inner_size: Weak<Mutex<PhysicalSize<u32>>>) -> Self { + Self { new_inner_size } + } + + /// Try to request inner size which will be set synchronously on the window. + pub fn request_inner_size( + &mut self, + new_inner_size: PhysicalSize<u32>, + ) -> Result<(), ExternalError> { + if let Some(inner) = self.new_inner_size.upgrade() { + *inner.lock().unwrap() = new_inner_size; + Ok(()) + } else { + Err(ExternalError::Ignored) + } + } +} + +impl PartialEq for InnerSizeWriter { + fn eq(&self, other: &Self) -> bool { + self.new_inner_size.as_ptr() == other.new_inner_size.as_ptr() + } +} + +#[cfg(test)] +mod tests { + use crate::dpi::PhysicalPosition; + use crate::event; + use std::collections::{BTreeSet, HashSet}; + + macro_rules! foreach_event { + ($closure:expr) => {{ + #[allow(unused_mut)] + let mut x = $closure; + let did = event::DeviceId::dummy(); + + #[allow(deprecated)] + { + use crate::event::Event::*; + use crate::event::Ime::Enabled; + use crate::event::WindowEvent::*; + use crate::window::WindowId; + + // Mainline events. + let wid = WindowId::dummy(); + x(UserEvent(())); + x(NewEvents(event::StartCause::Init)); + x(AboutToWait); + x(LoopExiting); + x(Suspended); + x(Resumed); + + // Window events. + let with_window_event = |wev| x(WindowEvent { window_id: wid, event: wev }); + + with_window_event(CloseRequested); + with_window_event(Destroyed); + with_window_event(Focused(true)); + with_window_event(Moved((0, 0).into())); + with_window_event(Resized((0, 0).into())); + with_window_event(DroppedFile("x.txt".into())); + with_window_event(HoveredFile("x.txt".into())); + with_window_event(HoveredFileCancelled); + with_window_event(Ime(Enabled)); + with_window_event(CursorMoved { device_id: did, position: (0, 0).into() }); + with_window_event(ModifiersChanged(event::Modifiers::default())); + with_window_event(CursorEntered { device_id: did }); + with_window_event(CursorLeft { device_id: did }); + with_window_event(MouseWheel { + device_id: did, + delta: event::MouseScrollDelta::LineDelta(0.0, 0.0), + phase: event::TouchPhase::Started, + }); + with_window_event(MouseInput { + device_id: did, + state: event::ElementState::Pressed, + button: event::MouseButton::Other(0), + }); + with_window_event(PinchGesture { + device_id: did, + delta: 0.0, + phase: event::TouchPhase::Started, + }); + with_window_event(DoubleTapGesture { device_id: did }); + with_window_event(RotationGesture { + device_id: did, + delta: 0.0, + phase: event::TouchPhase::Started, + }); + with_window_event(PanGesture { + device_id: did, + delta: PhysicalPosition::<f32>::new(0.0, 0.0), + phase: event::TouchPhase::Started, + }); + with_window_event(TouchpadPressure { device_id: did, pressure: 0.0, stage: 0 }); + with_window_event(AxisMotion { device_id: did, axis: 0, value: 0.0 }); + with_window_event(Touch(event::Touch { + device_id: did, + phase: event::TouchPhase::Started, + location: (0.0, 0.0).into(), + id: 0, + force: Some(event::Force::Normalized(0.0)), + })); + with_window_event(ThemeChanged(crate::window::Theme::Light)); + with_window_event(Occluded(true)); + } + + #[allow(deprecated)] + { + use event::DeviceEvent::*; + + let with_device_event = + |dev_ev| x(event::Event::DeviceEvent { device_id: did, event: dev_ev }); + + with_device_event(Added); + with_device_event(Removed); + with_device_event(MouseMotion { delta: (0.0, 0.0).into() }); + with_device_event(MouseWheel { + delta: event::MouseScrollDelta::LineDelta(0.0, 0.0), + }); + with_device_event(Motion { axis: 0, value: 0.0 }); + with_device_event(Button { button: 0, state: event::ElementState::Pressed }); + } + }}; + } + + #[allow(clippy::redundant_clone)] + #[test] + fn test_event_clone() { + foreach_event!(|event: event::Event<()>| { + let event2 = event.clone(); + assert_eq!(event, event2); + }) + } + + #[test] + fn test_map_nonuser_event() { + foreach_event!(|event: event::Event<()>| { + let is_user = matches!(event, event::Event::UserEvent(())); + let event2 = event.map_nonuser_event::<()>(); + if is_user { + assert_eq!(event2, Err(event::Event::UserEvent(()))); + } else { + assert!(event2.is_ok()); + } + }) + } + + #[test] + fn test_force_normalize() { + let force = event::Force::Normalized(0.0); + assert_eq!(force.normalized(), 0.0); + + let force2 = + event::Force::Calibrated { force: 5.0, max_possible_force: 2.5, altitude_angle: None }; + assert_eq!(force2.normalized(), 2.0); + + let force3 = event::Force::Calibrated { + force: 5.0, + max_possible_force: 2.5, + altitude_angle: Some(std::f64::consts::PI / 2.0), + }; + assert_eq!(force3.normalized(), 2.0); + } + + #[allow(clippy::clone_on_copy)] + #[test] + fn ensure_attrs_do_not_panic() { + foreach_event!(|event: event::Event<()>| { + let _ = format!("{event:?}"); + }); + let _ = event::StartCause::Init.clone(); + + let did = crate::event::DeviceId::dummy().clone(); + HashSet::new().insert(did); + let mut set = [did, did, did]; + set.sort_unstable(); + let mut set2 = BTreeSet::new(); + set2.insert(did); + set2.insert(did); + + HashSet::new().insert(event::TouchPhase::Started.clone()); + HashSet::new().insert(event::MouseButton::Left.clone()); + HashSet::new().insert(event::Ime::Enabled); + + let _ = event::Touch { + device_id: did, + phase: event::TouchPhase::Started, + location: (0.0, 0.0).into(), + id: 0, + force: Some(event::Force::Normalized(0.0)), + } + .clone(); + let _ = + event::Force::Calibrated { force: 0.0, max_possible_force: 0.0, altitude_angle: None } + .clone(); + } +} diff --git a/app/vendor/rune/vendor/winit/src/event_loop.rs b/app/vendor/rune/vendor/winit/src/event_loop.rs new file mode 100644 index 0000000..233374b --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/event_loop.rs @@ -0,0 +1,651 @@ +//! The [`EventLoop`] struct and assorted supporting types, including +//! [`ControlFlow`]. +//! +//! If you want to send custom events to the event loop, use +//! [`EventLoop::create_proxy`] to acquire an [`EventLoopProxy`] and call its +//! [`send_event`][EventLoopProxy::send_event] method. +//! +//! See the root-level documentation for information on how to create and use an event loop to +//! handle events. +use std::marker::PhantomData; +#[cfg(any(x11_platform, wayland_platform))] +use std::os::unix::io::{AsFd, AsRawFd, BorrowedFd, RawFd}; +use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; +use std::{error, fmt}; + +#[cfg(not(web_platform))] +use std::time::{Duration, Instant}; +#[cfg(web_platform)] +use web_time::{Duration, Instant}; + +use crate::application::ApplicationHandler; +use crate::error::{EventLoopError, OsError}; +use crate::event::Event; +use crate::monitor::MonitorHandle; +use crate::platform_impl; +use crate::window::{CustomCursor, CustomCursorSource, Theme, Window, WindowAttributes}; + +/// Provides a way to retrieve events from the system and from the windows that were registered to +/// the events loop. +/// +/// An `EventLoop` can be seen more or less as a "context". Calling [`EventLoop::new`] +/// initializes everything that will be required to create windows. For example on Linux creating +/// an event loop opens a connection to the X or Wayland server. +/// +/// To wake up an `EventLoop` from a another thread, see the [`EventLoopProxy`] docs. +/// +/// Note that this cannot be shared across threads (due to platform-dependant logic +/// forbidding it), as such it is neither [`Send`] nor [`Sync`]. If you need cross-thread access, +/// the [`Window`] created from this _can_ be sent to an other thread, and the +/// [`EventLoopProxy`] allows you to wake up an `EventLoop` from another thread. +/// +/// [`Window`]: crate::window::Window +pub struct EventLoop<T: 'static> { + pub(crate) event_loop: platform_impl::EventLoop<T>, + pub(crate) _marker: PhantomData<*mut ()>, // Not Send nor Sync +} + +/// Target that associates windows with an [`EventLoop`]. +/// +/// This type exists to allow you to create new windows while Winit executes +/// your callback. +pub struct ActiveEventLoop { + pub(crate) p: platform_impl::ActiveEventLoop, + pub(crate) _marker: PhantomData<*mut ()>, // Not Send nor Sync +} + +/// Object that allows building the event loop. +/// +/// This is used to make specifying options that affect the whole application +/// easier. But note that constructing multiple event loops is not supported. +/// +/// This can be created using [`EventLoop::new`] or [`EventLoop::with_user_event`]. +#[derive(Default)] +pub struct EventLoopBuilder<T: 'static> { + pub(crate) platform_specific: platform_impl::PlatformSpecificEventLoopAttributes, + _p: PhantomData<T>, +} + +static EVENT_LOOP_CREATED: AtomicBool = AtomicBool::new(false); + +impl EventLoopBuilder<()> { + /// Start building a new event loop. + #[inline] + #[deprecated = "use `EventLoop::builder` instead"] + pub fn new() -> Self { + EventLoop::builder() + } +} + +impl<T> EventLoopBuilder<T> { + /// Builds a new event loop. + /// + /// ***For cross-platform compatibility, the [`EventLoop`] must be created on the main thread, + /// and only once per application.*** + /// + /// Calling this function will result in display backend initialisation. + /// + /// ## Panics + /// + /// Attempting to create the event loop off the main thread will panic. This + /// restriction isn't strictly necessary on all platforms, but is imposed to + /// eliminate any nasty surprises when porting to platforms that require it. + /// `EventLoopBuilderExt::any_thread` functions are exposed in the relevant + /// [`platform`] module if the target platform supports creating an event + /// loop on any thread. + /// + /// ## Platform-specific + /// + /// - **Wayland/X11:** to prevent running under `Wayland` or `X11` unset `WAYLAND_DISPLAY` or + /// `DISPLAY` respectively when building the event loop. + /// - **Android:** must be configured with an `AndroidApp` from `android_main()` by calling + /// [`.with_android_app(app)`] before calling `.build()`, otherwise it'll panic. + /// + /// [`platform`]: crate::platform + #[cfg_attr( + android_platform, + doc = "[`.with_android_app(app)`]: \ + crate::platform::android::EventLoopBuilderExtAndroid::with_android_app" + )] + #[cfg_attr( + not(android_platform), + doc = "[`.with_android_app(app)`]: #only-available-on-android" + )] + #[inline] + pub fn build(&mut self) -> Result<EventLoop<T>, EventLoopError> { + let _span = tracing::debug_span!("winit::EventLoopBuilder::build").entered(); + + if EVENT_LOOP_CREATED.swap(true, Ordering::Relaxed) { + return Err(EventLoopError::RecreationAttempt); + } + + // Certain platforms accept a mutable reference in their API. + #[allow(clippy::unnecessary_mut_passed)] + Ok(EventLoop { + event_loop: platform_impl::EventLoop::new(&mut self.platform_specific)?, + _marker: PhantomData, + }) + } + + #[cfg(web_platform)] + pub(crate) fn allow_event_loop_recreation() { + EVENT_LOOP_CREATED.store(false, Ordering::Relaxed); + } +} + +impl<T> fmt::Debug for EventLoop<T> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.pad("EventLoop { .. }") + } +} + +impl fmt::Debug for ActiveEventLoop { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.pad("ActiveEventLoop { .. }") + } +} + +/// Set through [`ActiveEventLoop::set_control_flow()`]. +/// +/// Indicates the desired behavior of the event loop after [`Event::AboutToWait`] is emitted. +/// +/// Defaults to [`Wait`]. +/// +/// [`Wait`]: Self::Wait +#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)] +pub enum ControlFlow { + /// When the current loop iteration finishes, immediately begin a new iteration regardless of + /// whether or not new events are available to process. + Poll, + + /// When the current loop iteration finishes, suspend the thread until another event arrives. + #[default] + Wait, + + /// When the current loop iteration finishes, suspend the thread until either another event + /// arrives or the given time is reached. + /// + /// Useful for implementing efficient timers. Applications which want to render at the + /// display's native refresh rate should instead use [`Poll`] and the VSync functionality + /// of a graphics API to reduce odds of missed frames. + /// + /// [`Poll`]: Self::Poll + WaitUntil(Instant), +} + +impl ControlFlow { + /// Creates a [`ControlFlow`] that waits until a timeout has expired. + /// + /// In most cases, this is set to [`WaitUntil`]. However, if the timeout overflows, it is + /// instead set to [`Wait`]. + /// + /// [`WaitUntil`]: Self::WaitUntil + /// [`Wait`]: Self::Wait + pub fn wait_duration(timeout: Duration) -> Self { + match Instant::now().checked_add(timeout) { + Some(instant) => Self::WaitUntil(instant), + None => Self::Wait, + } + } +} + +impl EventLoop<()> { + /// Create the event loop. + /// + /// This is an alias of `EventLoop::builder().build()`. + #[inline] + pub fn new() -> Result<EventLoop<()>, EventLoopError> { + Self::builder().build() + } + + /// Start building a new event loop. + /// + /// This returns an [`EventLoopBuilder`], to allow configuring the event loop before creation. + /// + /// To get the actual event loop, call [`build`][EventLoopBuilder::build] on that. + #[inline] + pub fn builder() -> EventLoopBuilder<()> { + Self::with_user_event() + } +} + +impl<T> EventLoop<T> { + /// Start building a new event loop, with the given type as the user event + /// type. + pub fn with_user_event() -> EventLoopBuilder<T> { + EventLoopBuilder { platform_specific: Default::default(), _p: PhantomData } + } + + /// See [`run_app`]. + /// + /// [`run_app`]: Self::run_app + #[inline] + #[deprecated = "use `EventLoop::run_app` instead"] + #[cfg(not(all(web_platform, target_feature = "exception-handling")))] + pub fn run<F>(self, event_handler: F) -> Result<(), EventLoopError> + where + F: FnMut(Event<T>, &ActiveEventLoop), + { + let _span = tracing::debug_span!("winit::EventLoop::run").entered(); + + self.event_loop.run(event_handler) + } + + /// Run the application with the event loop on the calling thread. + /// + /// See the [`set_control_flow()`] docs on how to change the event loop's behavior. + /// + /// ## Platform-specific + /// + /// - **iOS:** Will never return to the caller and so values not passed to this function will + /// *not* be dropped before the process exits. + /// - **Web:** Will _act_ as if it never returns to the caller by throwing a Javascript + /// exception (that Rust doesn't see) that will also mean that the rest of the function is + /// never executed and any values not passed to this function will *not* be dropped. + /// + /// Web applications are recommended to use + #[cfg_attr( + web_platform, + doc = "[`EventLoopExtWebSys::spawn_app()`][crate::platform::web::EventLoopExtWebSys::spawn_app()]" + )] + #[cfg_attr(not(web_platform), doc = "`EventLoopExtWebSys::spawn()`")] + /// [^1] instead of [`run_app()`] to avoid the need + /// for the Javascript exception trick, and to make it clearer that the event loop runs + /// asynchronously (via the browser's own, internal, event loop) and doesn't block the + /// current thread of execution like it does on other platforms. + /// + /// This function won't be available with `target_feature = "exception-handling"`. + /// + /// [`set_control_flow()`]: ActiveEventLoop::set_control_flow() + /// [`run_app()`]: Self::run_app() + /// [^1]: `EventLoopExtWebSys::spawn_app()` is only available on Web. + #[inline] + #[cfg(not(all(web_platform, target_feature = "exception-handling")))] + pub fn run_app<A: ApplicationHandler<T>>(self, app: &mut A) -> Result<(), EventLoopError> { + self.event_loop.run(|event, event_loop| dispatch_event_for_app(app, event_loop, event)) + } + + /// Creates an [`EventLoopProxy`] that can be used to dispatch user events + /// to the main event loop, possibly from another thread. + pub fn create_proxy(&self) -> EventLoopProxy<T> { + EventLoopProxy { event_loop_proxy: self.event_loop.create_proxy() } + } + + /// Gets a persistent reference to the underlying platform display. + /// + /// See the [`OwnedDisplayHandle`] type for more information. + pub fn owned_display_handle(&self) -> OwnedDisplayHandle { + OwnedDisplayHandle { platform: self.event_loop.window_target().p.owned_display_handle() } + } + + /// Change if or when [`DeviceEvent`]s are captured. + /// + /// See [`ActiveEventLoop::listen_device_events`] for details. + /// + /// [`DeviceEvent`]: crate::event::DeviceEvent + pub fn listen_device_events(&self, allowed: DeviceEvents) { + let _span = tracing::debug_span!( + "winit::EventLoop::listen_device_events", + allowed = ?allowed + ) + .entered(); + + self.event_loop.window_target().p.listen_device_events(allowed); + } + + /// Sets the [`ControlFlow`]. + pub fn set_control_flow(&self, control_flow: ControlFlow) { + self.event_loop.window_target().p.set_control_flow(control_flow) + } + + /// Create a window. + /// + /// Creating window without event loop running often leads to improper window creation; + /// use [`ActiveEventLoop::create_window`] instead. + #[deprecated = "use `ActiveEventLoop::create_window` instead"] + #[inline] + pub fn create_window(&self, window_attributes: WindowAttributes) -> Result<Window, OsError> { + let _span = tracing::debug_span!( + "winit::EventLoop::create_window", + window_attributes = ?window_attributes + ) + .entered(); + + let window = + platform_impl::Window::new(&self.event_loop.window_target().p, window_attributes)?; + Ok(Window { window }) + } + + /// Create custom cursor. + pub fn create_custom_cursor(&self, custom_cursor: CustomCursorSource) -> CustomCursor { + self.event_loop.window_target().p.create_custom_cursor(custom_cursor) + } +} + +#[cfg(feature = "rwh_06")] +impl<T> rwh_06::HasDisplayHandle for EventLoop<T> { + fn display_handle(&self) -> Result<rwh_06::DisplayHandle<'_>, rwh_06::HandleError> { + rwh_06::HasDisplayHandle::display_handle(self.event_loop.window_target()) + } +} + +#[cfg(feature = "rwh_05")] +unsafe impl<T> rwh_05::HasRawDisplayHandle for EventLoop<T> { + /// Returns a [`rwh_05::RawDisplayHandle`] for the event loop. + fn raw_display_handle(&self) -> rwh_05::RawDisplayHandle { + rwh_05::HasRawDisplayHandle::raw_display_handle(self.event_loop.window_target()) + } +} + +#[cfg(any(x11_platform, wayland_platform))] +impl<T> AsFd for EventLoop<T> { + /// Get the underlying [EventLoop]'s `fd` which you can register + /// into other event loop, like [`calloop`] or [`mio`]. When doing so, the + /// loop must be polled with the [`pump_app_events`] API. + /// + /// [`calloop`]: https://crates.io/crates/calloop + /// [`mio`]: https://crates.io/crates/mio + /// [`pump_app_events`]: crate::platform::pump_events::EventLoopExtPumpEvents::pump_app_events + fn as_fd(&self) -> BorrowedFd<'_> { + self.event_loop.as_fd() + } +} + +#[cfg(any(x11_platform, wayland_platform))] +impl<T> AsRawFd for EventLoop<T> { + /// Get the underlying [EventLoop]'s raw `fd` which you can register + /// into other event loop, like [`calloop`] or [`mio`]. When doing so, the + /// loop must be polled with the [`pump_app_events`] API. + /// + /// [`calloop`]: https://crates.io/crates/calloop + /// [`mio`]: https://crates.io/crates/mio + /// [`pump_app_events`]: crate::platform::pump_events::EventLoopExtPumpEvents::pump_app_events + fn as_raw_fd(&self) -> RawFd { + self.event_loop.as_raw_fd() + } +} + +impl ActiveEventLoop { + /// Create the window. + /// + /// Possible causes of error include denied permission, incompatible system, and lack of memory. + /// + /// ## Platform-specific + /// + /// - **Web:** The window is created but not inserted into the web page automatically. Please + /// see the web platform module for more information. + #[inline] + pub fn create_window(&self, window_attributes: WindowAttributes) -> Result<Window, OsError> { + let _span = tracing::debug_span!( + "winit::ActiveEventLoop::create_window", + window_attributes = ?window_attributes + ) + .entered(); + + let window = platform_impl::Window::new(&self.p, window_attributes)?; + Ok(Window { window }) + } + + /// Create custom cursor. + pub fn create_custom_cursor(&self, custom_cursor: CustomCursorSource) -> CustomCursor { + let _span = tracing::debug_span!("winit::ActiveEventLoop::create_custom_cursor",).entered(); + + self.p.create_custom_cursor(custom_cursor) + } + + /// Returns the list of all the monitors available on the system. + #[inline] + pub fn available_monitors(&self) -> impl Iterator<Item = MonitorHandle> { + let _span = tracing::debug_span!("winit::ActiveEventLoop::available_monitors",).entered(); + + #[allow(clippy::useless_conversion)] // false positive on some platforms + self.p.available_monitors().into_iter().map(|inner| MonitorHandle { inner }) + } + + /// Returns the primary monitor of the system. + /// + /// Returns `None` if it can't identify any monitor as a primary one. + /// + /// ## Platform-specific + /// + /// **Wayland / Web:** Always returns `None`. + #[inline] + pub fn primary_monitor(&self) -> Option<MonitorHandle> { + let _span = tracing::debug_span!("winit::ActiveEventLoop::primary_monitor",).entered(); + + self.p.primary_monitor().map(|inner| MonitorHandle { inner }) + } + + /// Change if or when [`DeviceEvent`]s are captured. + /// + /// Since the [`DeviceEvent`] capture can lead to high CPU usage for unfocused windows, winit + /// will ignore them by default for unfocused windows on Linux/BSD. This method allows changing + /// this at runtime to explicitly capture them again. + /// + /// ## Platform-specific + /// + /// - **Wayland / macOS / iOS / Android / Orbital:** Unsupported. + /// + /// [`DeviceEvent`]: crate::event::DeviceEvent + pub fn listen_device_events(&self, allowed: DeviceEvents) { + let _span = tracing::debug_span!( + "winit::ActiveEventLoop::listen_device_events", + allowed = ?allowed + ) + .entered(); + + self.p.listen_device_events(allowed); + } + + /// Returns the current system theme. + /// + /// Returns `None` if it cannot be determined on the current platform. + /// + /// ## Platform-specific + /// + /// - **iOS / Android / Wayland / x11 / Orbital:** Unsupported. + pub fn system_theme(&self) -> Option<Theme> { + self.p.system_theme() + } + + /// Sets the [`ControlFlow`]. + pub fn set_control_flow(&self, control_flow: ControlFlow) { + self.p.set_control_flow(control_flow) + } + + /// Gets the current [`ControlFlow`]. + pub fn control_flow(&self) -> ControlFlow { + self.p.control_flow() + } + + /// This exits the event loop. + /// + /// See [`LoopExiting`][Event::LoopExiting]. + pub fn exit(&self) { + let _span = tracing::debug_span!("winit::ActiveEventLoop::exit",).entered(); + + self.p.exit() + } + + /// Returns if the [`EventLoop`] is about to stop. + /// + /// See [`exit()`][Self::exit]. + pub fn exiting(&self) -> bool { + self.p.exiting() + } + + /// Gets a persistent reference to the underlying platform display. + /// + /// See the [`OwnedDisplayHandle`] type for more information. + pub fn owned_display_handle(&self) -> OwnedDisplayHandle { + OwnedDisplayHandle { platform: self.p.owned_display_handle() } + } +} + +#[cfg(feature = "rwh_06")] +impl rwh_06::HasDisplayHandle for ActiveEventLoop { + fn display_handle(&self) -> Result<rwh_06::DisplayHandle<'_>, rwh_06::HandleError> { + let raw = self.p.raw_display_handle_rwh_06()?; + // SAFETY: The display will never be deallocated while the event loop is alive. + Ok(unsafe { rwh_06::DisplayHandle::borrow_raw(raw) }) + } +} + +#[cfg(feature = "rwh_05")] +unsafe impl rwh_05::HasRawDisplayHandle for ActiveEventLoop { + /// Returns a [`rwh_05::RawDisplayHandle`] for the event loop. + fn raw_display_handle(&self) -> rwh_05::RawDisplayHandle { + self.p.raw_display_handle_rwh_05() + } +} + +/// A proxy for the underlying display handle. +/// +/// The purpose of this type is to provide a cheaply cloneable handle to the underlying +/// display handle. This is often used by graphics APIs to connect to the underlying APIs. +/// It is difficult to keep a handle to the [`EventLoop`] type or the [`ActiveEventLoop`] +/// type. In contrast, this type involves no lifetimes and can be persisted for as long as +/// needed. +/// +/// For all platforms, this is one of the following: +/// +/// - A zero-sized type that is likely optimized out. +/// - A reference-counted pointer to the underlying type. +#[derive(Clone)] +pub struct OwnedDisplayHandle { + #[cfg_attr(not(any(feature = "rwh_05", feature = "rwh_06")), allow(dead_code))] + platform: platform_impl::OwnedDisplayHandle, +} + +impl fmt::Debug for OwnedDisplayHandle { + #[inline] + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("OwnedDisplayHandle").finish_non_exhaustive() + } +} + +#[cfg(feature = "rwh_06")] +impl rwh_06::HasDisplayHandle for OwnedDisplayHandle { + #[inline] + fn display_handle(&self) -> Result<rwh_06::DisplayHandle<'_>, rwh_06::HandleError> { + let raw = self.platform.raw_display_handle_rwh_06()?; + + // SAFETY: The underlying display handle should be safe. + let handle = unsafe { rwh_06::DisplayHandle::borrow_raw(raw) }; + + Ok(handle) + } +} + +#[cfg(feature = "rwh_05")] +unsafe impl rwh_05::HasRawDisplayHandle for OwnedDisplayHandle { + #[inline] + fn raw_display_handle(&self) -> rwh_05::RawDisplayHandle { + self.platform.raw_display_handle_rwh_05() + } +} + +/// Used to send custom events to [`EventLoop`]. +pub struct EventLoopProxy<T: 'static> { + event_loop_proxy: platform_impl::EventLoopProxy<T>, +} + +impl<T: 'static> Clone for EventLoopProxy<T> { + fn clone(&self) -> Self { + Self { event_loop_proxy: self.event_loop_proxy.clone() } + } +} + +impl<T: 'static> EventLoopProxy<T> { + /// Send an event to the [`EventLoop`] from which this proxy was created. This emits a + /// `UserEvent(event)` event in the event loop, where `event` is the value passed to this + /// function. + /// + /// Returns an `Err` if the associated [`EventLoop`] no longer exists. + /// + /// [`UserEvent(event)`]: Event::UserEvent + pub fn send_event(&self, event: T) -> Result<(), EventLoopClosed<T>> { + let _span = tracing::debug_span!("winit::EventLoopProxy::send_event",).entered(); + + self.event_loop_proxy.send_event(event) + } +} + +impl<T: 'static> fmt::Debug for EventLoopProxy<T> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.pad("EventLoopProxy { .. }") + } +} + +/// The error that is returned when an [`EventLoopProxy`] attempts to wake up an [`EventLoop`] that +/// no longer exists. +/// +/// Contains the original event given to [`EventLoopProxy::send_event`]. +#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)] +pub struct EventLoopClosed<T>(pub T); + +impl<T> fmt::Display for EventLoopClosed<T> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("Tried to wake up a closed `EventLoop`") + } +} + +impl<T: fmt::Debug> error::Error for EventLoopClosed<T> {} + +/// Control when device events are captured. +#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, Default)] +pub enum DeviceEvents { + /// Report device events regardless of window focus. + Always, + /// Only capture device events while the window is focused. + #[default] + WhenFocused, + /// Never capture device events. + Never, +} + +/// A unique identifier of the winit's async request. +/// +/// This could be used to identify the async request once it's done +/// and a specific action must be taken. +/// +/// One of the handling scenarios could be to maintain a working list +/// containing [`AsyncRequestSerial`] and some closure associated with it. +/// Then once event is arriving the working list is being traversed and a job +/// executed and removed from the list. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct AsyncRequestSerial { + serial: usize, +} + +impl AsyncRequestSerial { + // TODO(kchibisov): Remove `cfg` when the clipboard will be added. + #[allow(dead_code)] + pub(crate) fn get() -> Self { + static CURRENT_SERIAL: AtomicUsize = AtomicUsize::new(0); + // NOTE: We rely on wrap around here, while the user may just request + // in the loop usize::MAX times that's issue is considered on them. + let serial = CURRENT_SERIAL.fetch_add(1, Ordering::Relaxed); + Self { serial } + } +} + +/// Shim for various run APIs. +#[inline(always)] +pub(crate) fn dispatch_event_for_app<T: 'static, A: ApplicationHandler<T>>( + app: &mut A, + event_loop: &ActiveEventLoop, + event: Event<T>, +) { + match event { + Event::NewEvents(cause) => app.new_events(event_loop, cause), + Event::WindowEvent { window_id, event } => app.window_event(event_loop, window_id, event), + Event::DeviceEvent { device_id, event } => app.device_event(event_loop, device_id, event), + Event::UserEvent(event) => app.user_event(event_loop, event), + Event::Suspended => app.suspended(event_loop), + Event::Resumed => app.resumed(event_loop), + Event::AboutToWait => app.about_to_wait(event_loop), + Event::LoopExiting => app.exiting(event_loop), + Event::MemoryWarning => app.memory_warning(event_loop), + } +} diff --git a/app/vendor/rune/vendor/winit/src/icon.rs b/app/vendor/rune/vendor/winit/src/icon.rs new file mode 100644 index 0000000..b013d2f --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/icon.rs @@ -0,0 +1,117 @@ +use crate::platform_impl::PlatformIcon; +use std::error::Error; +use std::{fmt, io, mem}; + +#[repr(C)] +#[derive(Debug)] +pub(crate) struct Pixel { + pub(crate) r: u8, + pub(crate) g: u8, + pub(crate) b: u8, + pub(crate) a: u8, +} + +pub(crate) const PIXEL_SIZE: usize = mem::size_of::<Pixel>(); + +#[derive(Debug)] +/// An error produced when using [`Icon::from_rgba`] with invalid arguments. +pub enum BadIcon { + /// Produced when the length of the `rgba` argument isn't divisible by 4, thus `rgba` can't be + /// safely interpreted as 32bpp RGBA pixels. + ByteCountNotDivisibleBy4 { byte_count: usize }, + /// Produced when the number of pixels (`rgba.len() / 4`) isn't equal to `width * height`. + /// At least one of your arguments is incorrect. + DimensionsVsPixelCount { width: u32, height: u32, width_x_height: usize, pixel_count: usize }, + /// Produced when underlying OS functionality failed to create the icon + OsError(io::Error), +} + +impl fmt::Display for BadIcon { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + BadIcon::ByteCountNotDivisibleBy4 { byte_count } => write!( + f, + "The length of the `rgba` argument ({byte_count:?}) isn't divisible by 4, making \ + it impossible to interpret as 32bpp RGBA pixels.", + ), + BadIcon::DimensionsVsPixelCount { width, height, width_x_height, pixel_count } => { + write!( + f, + "The specified dimensions ({width:?}x{height:?}) don't match the number of \ + pixels supplied by the `rgba` argument ({pixel_count:?}). For those \ + dimensions, the expected pixel count is {width_x_height:?}.", + ) + }, + BadIcon::OsError(e) => write!(f, "OS error when instantiating the icon: {e:?}"), + } + } +} + +impl Error for BadIcon {} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) struct RgbaIcon { + pub(crate) rgba: Vec<u8>, + pub(crate) width: u32, + pub(crate) height: u32, +} + +/// For platforms which don't have window icons (e.g. web) +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) struct NoIcon; + +#[allow(dead_code)] // These are not used on every platform +mod constructors { + use super::*; + + impl RgbaIcon { + pub fn from_rgba(rgba: Vec<u8>, width: u32, height: u32) -> Result<Self, BadIcon> { + if rgba.len() % PIXEL_SIZE != 0 { + return Err(BadIcon::ByteCountNotDivisibleBy4 { byte_count: rgba.len() }); + } + let pixel_count = rgba.len() / PIXEL_SIZE; + if pixel_count != (width * height) as usize { + Err(BadIcon::DimensionsVsPixelCount { + width, + height, + width_x_height: (width * height) as usize, + pixel_count, + }) + } else { + Ok(RgbaIcon { rgba, width, height }) + } + } + } + + impl NoIcon { + pub fn from_rgba(rgba: Vec<u8>, width: u32, height: u32) -> Result<Self, BadIcon> { + // Create the rgba icon anyway to validate the input + let _ = RgbaIcon::from_rgba(rgba, width, height)?; + Ok(NoIcon) + } + } +} + +/// An icon used for the window titlebar, taskbar, etc. +#[derive(Clone)] +pub struct Icon { + pub(crate) inner: PlatformIcon, +} + +impl fmt::Debug for Icon { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> { + fmt::Debug::fmt(&self.inner, formatter) + } +} + +impl Icon { + /// Creates an icon from 32bpp RGBA data. + /// + /// The length of `rgba` must be divisible by 4, and `width * height` must equal + /// `rgba.len() / 4`. Otherwise, this will return a `BadIcon` error. + pub fn from_rgba(rgba: Vec<u8>, width: u32, height: u32) -> Result<Self, BadIcon> { + let _span = tracing::debug_span!("winit::Icon::from_rgba", width, height).entered(); + + Ok(Icon { inner: PlatformIcon::from_rgba(rgba, width, height)? }) + } +} diff --git a/app/vendor/rune/vendor/winit/src/keyboard.rs b/app/vendor/rune/vendor/winit/src/keyboard.rs new file mode 100644 index 0000000..7b406f0 --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/keyboard.rs @@ -0,0 +1,1804 @@ +//! Types related to the keyboard. + +// This file contains a substantial portion of the UI Events Specification by the W3C. In +// particular, the variant names within `Key` and `KeyCode` and their documentation are modified +// versions of contents of the aforementioned specification. +// +// The original documents are: +// +// ### For `Key` +// UI Events KeyboardEvent key Values +// https://www.w3.org/TR/2017/CR-uievents-key-20170601/ +// Copyright © 2017 W3C® (MIT, ERCIM, Keio, Beihang). +// +// ### For `KeyCode` +// UI Events KeyboardEvent code Values +// https://www.w3.org/TR/2017/CR-uievents-code-20170601/ +// Copyright © 2017 W3C® (MIT, ERCIM, Keio, Beihang). +// +// These documents were used under the terms of the following license. This W3C license as well as +// the W3C short notice apply to the `Key` and `KeyCode` enums and their variants and the +// documentation attached to their variants. + +// --------- BEGINNING OF W3C LICENSE -------------------------------------------------------------- +// +// License +// +// By obtaining and/or copying this work, you (the licensee) agree that you have read, understood, +// and will comply with the following terms and conditions. +// +// Permission to copy, modify, and distribute this work, with or without modification, for any +// purpose and without fee or royalty is hereby granted, provided that you include the following on +// ALL copies of the work or portions thereof, including modifications: +// +// - The full text of this NOTICE in a location viewable to users of the redistributed or derivative +// work. +// - Any pre-existing intellectual property disclaimers, notices, or terms and conditions. If none +// exist, the W3C Software and Document Short Notice should be included. +// - Notice of any changes or modifications, through a copyright statement on the new code or +// document such as "This software or document includes material copied from or derived from +// [title and URI of the W3C document]. Copyright © [YEAR] W3C® (MIT, ERCIM, Keio, Beihang)." +// +// Disclaimers +// +// THIS WORK IS PROVIDED "AS IS," AND COPYRIGHT HOLDERS MAKE NO REPRESENTATIONS OR WARRANTIES, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY OR FITNESS FOR +// ANY PARTICULAR PURPOSE OR THAT THE USE OF THE SOFTWARE OR DOCUMENT WILL NOT INFRINGE ANY THIRD +// PARTY PATENTS, COPYRIGHTS, TRADEMARKS OR OTHER RIGHTS. +// +// COPYRIGHT HOLDERS WILL NOT BE LIABLE FOR ANY DIRECT, INDIRECT, SPECIAL OR CONSEQUENTIAL DAMAGES +// ARISING OUT OF ANY USE OF THE SOFTWARE OR DOCUMENT. +// +// The name and trademarks of copyright holders may NOT be used in advertising or publicity +// pertaining to the work without specific, written prior permission. Title to copyright in this +// work will at all times remain with copyright holders. +// +// --------- END OF W3C LICENSE -------------------------------------------------------------------- + +// --------- BEGINNING OF W3C SHORT NOTICE --------------------------------------------------------- +// +// winit: https://github.com/rust-windowing/winit +// +// Copyright © 2021 World Wide Web Consortium, (Massachusetts Institute of Technology, European +// Research Consortium for Informatics and Mathematics, Keio University, Beihang). All Rights +// Reserved. This work is distributed under the W3C® Software License [1] in the hope that it will +// be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +// FITNESS FOR A PARTICULAR PURPOSE. +// +// [1] http://www.w3.org/Consortium/Legal/copyright-software +// +// --------- END OF W3C SHORT NOTICE --------------------------------------------------------------- + +use bitflags::bitflags; +#[cfg(feature = "serde")] +use serde::{Deserialize, Serialize}; +pub use smol_str::SmolStr; + +/// Contains the platform-native physical key identifier +/// +/// The exact values vary from platform to platform (which is part of why this is a per-platform +/// enum), but the values are primarily tied to the key's physical location on the keyboard. +/// +/// This enum is primarily used to store raw keycodes when Winit doesn't map a given native +/// physical key identifier to a meaningful [`KeyCode`] variant. In the presence of identifiers we +/// haven't mapped for you yet, this lets you use use [`KeyCode`] to: +/// +/// - Correctly match key press and release events. +/// - On non-web platforms, support assigning keybinds to virtually any key through a UI. +#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] +#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] +pub enum NativeKeyCode { + Unidentified, + /// An Android "scancode". + Android(u32), + /// A macOS "scancode". + MacOS(u16), + /// A Windows "scancode". + Windows(u16), + /// An XKB "keycode". + Xkb(u32), +} + +impl std::fmt::Debug for NativeKeyCode { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + use NativeKeyCode::{Android, MacOS, Unidentified, Windows, Xkb}; + let mut debug_tuple; + match self { + Unidentified => { + debug_tuple = f.debug_tuple("Unidentified"); + }, + Android(code) => { + debug_tuple = f.debug_tuple("Android"); + debug_tuple.field(&format_args!("0x{code:04X}")); + }, + MacOS(code) => { + debug_tuple = f.debug_tuple("MacOS"); + debug_tuple.field(&format_args!("0x{code:04X}")); + }, + Windows(code) => { + debug_tuple = f.debug_tuple("Windows"); + debug_tuple.field(&format_args!("0x{code:04X}")); + }, + Xkb(code) => { + debug_tuple = f.debug_tuple("Xkb"); + debug_tuple.field(&format_args!("0x{code:04X}")); + }, + } + debug_tuple.finish() + } +} + +/// Contains the platform-native logical key identifier +/// +/// Exactly what that means differs from platform to platform, but the values are to some degree +/// tied to the currently active keyboard layout. The same key on the same keyboard may also report +/// different values on different platforms, which is one of the reasons this is a per-platform +/// enum. +/// +/// This enum is primarily used to store raw keysym when Winit doesn't map a given native logical +/// key identifier to a meaningful [`Key`] variant. This lets you use [`Key`], and let the user +/// define keybinds which work in the presence of identifiers we haven't mapped for you yet. +#[derive(Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] +#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] +pub enum NativeKey { + Unidentified, + /// An Android "keycode", which is similar to a "virtual-key code" on Windows. + Android(u32), + /// A macOS "scancode". There does not appear to be any direct analogue to either keysyms or + /// "virtual-key" codes in macOS, so we report the scancode instead. + MacOS(u16), + /// A Windows "virtual-key code". + Windows(u16), + /// An XKB "keysym". + Xkb(u32), + /// A "key value string". + Web(SmolStr), +} + +impl std::fmt::Debug for NativeKey { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + use NativeKey::{Android, MacOS, Unidentified, Web, Windows, Xkb}; + let mut debug_tuple; + match self { + Unidentified => { + debug_tuple = f.debug_tuple("Unidentified"); + }, + Android(code) => { + debug_tuple = f.debug_tuple("Android"); + debug_tuple.field(&format_args!("0x{code:04X}")); + }, + MacOS(code) => { + debug_tuple = f.debug_tuple("MacOS"); + debug_tuple.field(&format_args!("0x{code:04X}")); + }, + Windows(code) => { + debug_tuple = f.debug_tuple("Windows"); + debug_tuple.field(&format_args!("0x{code:04X}")); + }, + Xkb(code) => { + debug_tuple = f.debug_tuple("Xkb"); + debug_tuple.field(&format_args!("0x{code:04X}")); + }, + Web(code) => { + debug_tuple = f.debug_tuple("Web"); + debug_tuple.field(code); + }, + } + debug_tuple.finish() + } +} + +impl From<NativeKeyCode> for NativeKey { + #[inline] + fn from(code: NativeKeyCode) -> Self { + match code { + NativeKeyCode::Unidentified => NativeKey::Unidentified, + NativeKeyCode::Android(x) => NativeKey::Android(x), + NativeKeyCode::MacOS(x) => NativeKey::MacOS(x), + NativeKeyCode::Windows(x) => NativeKey::Windows(x), + NativeKeyCode::Xkb(x) => NativeKey::Xkb(x), + } + } +} + +impl PartialEq<NativeKey> for NativeKeyCode { + #[allow(clippy::cmp_owned)] // uses less code than direct match; target is stack allocated + #[inline] + fn eq(&self, rhs: &NativeKey) -> bool { + NativeKey::from(*self) == *rhs + } +} + +impl PartialEq<NativeKeyCode> for NativeKey { + #[inline] + fn eq(&self, rhs: &NativeKeyCode) -> bool { + rhs == self + } +} + +/// Represents the location of a physical key. +/// +/// This type is a superset of [`KeyCode`], including an [`Unidentified`][Self::Unidentified] +/// variant. +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] +#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] +pub enum PhysicalKey { + /// A known key code + Code(KeyCode), + /// This variant is used when the key cannot be translated to a [`KeyCode`] + /// + /// The native keycode is provided (if available) so you're able to more reliably match + /// key-press and key-release events by hashing the [`PhysicalKey`]. It is also possible to use + /// this for keybinds for non-standard keys, but such keybinds are tied to a given platform. + Unidentified(NativeKeyCode), +} + +impl From<KeyCode> for PhysicalKey { + #[inline] + fn from(code: KeyCode) -> Self { + PhysicalKey::Code(code) + } +} + +impl From<NativeKeyCode> for PhysicalKey { + #[inline] + fn from(code: NativeKeyCode) -> Self { + PhysicalKey::Unidentified(code) + } +} + +impl PartialEq<KeyCode> for PhysicalKey { + #[inline] + fn eq(&self, rhs: &KeyCode) -> bool { + match self { + PhysicalKey::Code(ref code) => code == rhs, + _ => false, + } + } +} + +impl PartialEq<PhysicalKey> for KeyCode { + #[inline] + fn eq(&self, rhs: &PhysicalKey) -> bool { + rhs == self + } +} + +impl PartialEq<NativeKeyCode> for PhysicalKey { + #[inline] + fn eq(&self, rhs: &NativeKeyCode) -> bool { + match self { + PhysicalKey::Unidentified(ref code) => code == rhs, + _ => false, + } + } +} + +impl PartialEq<PhysicalKey> for NativeKeyCode { + #[inline] + fn eq(&self, rhs: &PhysicalKey) -> bool { + rhs == self + } +} + +/// Code representing the location of a physical key +/// +/// This mostly conforms to the UI Events Specification's [`KeyboardEvent.code`] with a few +/// exceptions: +/// - The keys that the specification calls "MetaLeft" and "MetaRight" are named "SuperLeft" and +/// "SuperRight" here. +/// - The key that the specification calls "Super" is reported as `Unidentified` here. +/// +/// [`KeyboardEvent.code`]: https://w3c.github.io/uievents-code/#code-value-tables +#[non_exhaustive] +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] +#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] +pub enum KeyCode { + /// <kbd>`</kbd> on a US keyboard. This is also called a backtick or grave. + /// This is the <kbd>半角</kbd>/<kbd>全角</kbd>/<kbd>漢字</kbd> + /// (hankaku/zenkaku/kanji) key on Japanese keyboards + Backquote, + /// Used for both the US <kbd>\\</kbd> (on the 101-key layout) and also for the key + /// located between the <kbd>"</kbd> and <kbd>Enter</kbd> keys on row C of the 102-, + /// 104- and 106-key layouts. + /// Labeled <kbd>#</kbd> on a UK (102) keyboard. + Backslash, + /// <kbd>[</kbd> on a US keyboard. + BracketLeft, + /// <kbd>]</kbd> on a US keyboard. + BracketRight, + /// <kbd>,</kbd> on a US keyboard. + Comma, + /// <kbd>0</kbd> on a US keyboard. + Digit0, + /// <kbd>1</kbd> on a US keyboard. + Digit1, + /// <kbd>2</kbd> on a US keyboard. + Digit2, + /// <kbd>3</kbd> on a US keyboard. + Digit3, + /// <kbd>4</kbd> on a US keyboard. + Digit4, + /// <kbd>5</kbd> on a US keyboard. + Digit5, + /// <kbd>6</kbd> on a US keyboard. + Digit6, + /// <kbd>7</kbd> on a US keyboard. + Digit7, + /// <kbd>8</kbd> on a US keyboard. + Digit8, + /// <kbd>9</kbd> on a US keyboard. + Digit9, + /// <kbd>=</kbd> on a US keyboard. + Equal, + /// Located between the left <kbd>Shift</kbd> and <kbd>Z</kbd> keys. + /// Labeled <kbd>\\</kbd> on a UK keyboard. + IntlBackslash, + /// Located between the <kbd>/</kbd> and right <kbd>Shift</kbd> keys. + /// Labeled <kbd>\\</kbd> (ro) on a Japanese keyboard. + IntlRo, + /// Located between the <kbd>=</kbd> and <kbd>Backspace</kbd> keys. + /// Labeled <kbd>¥</kbd> (yen) on a Japanese keyboard. <kbd>\\</kbd> on a + /// Russian keyboard. + IntlYen, + /// <kbd>a</kbd> on a US keyboard. + /// Labeled <kbd>q</kbd> on an AZERTY (e.g., French) keyboard. + KeyA, + /// <kbd>b</kbd> on a US keyboard. + KeyB, + /// <kbd>c</kbd> on a US keyboard. + KeyC, + /// <kbd>d</kbd> on a US keyboard. + KeyD, + /// <kbd>e</kbd> on a US keyboard. + KeyE, + /// <kbd>f</kbd> on a US keyboard. + KeyF, + /// <kbd>g</kbd> on a US keyboard. + KeyG, + /// <kbd>h</kbd> on a US keyboard. + KeyH, + /// <kbd>i</kbd> on a US keyboard. + KeyI, + /// <kbd>j</kbd> on a US keyboard. + KeyJ, + /// <kbd>k</kbd> on a US keyboard. + KeyK, + /// <kbd>l</kbd> on a US keyboard. + KeyL, + /// <kbd>m</kbd> on a US keyboard. + KeyM, + /// <kbd>n</kbd> on a US keyboard. + KeyN, + /// <kbd>o</kbd> on a US keyboard. + KeyO, + /// <kbd>p</kbd> on a US keyboard. + KeyP, + /// <kbd>q</kbd> on a US keyboard. + /// Labeled <kbd>a</kbd> on an AZERTY (e.g., French) keyboard. + KeyQ, + /// <kbd>r</kbd> on a US keyboard. + KeyR, + /// <kbd>s</kbd> on a US keyboard. + KeyS, + /// <kbd>t</kbd> on a US keyboard. + KeyT, + /// <kbd>u</kbd> on a US keyboard. + KeyU, + /// <kbd>v</kbd> on a US keyboard. + KeyV, + /// <kbd>w</kbd> on a US keyboard. + /// Labeled <kbd>z</kbd> on an AZERTY (e.g., French) keyboard. + KeyW, + /// <kbd>x</kbd> on a US keyboard. + KeyX, + /// <kbd>y</kbd> on a US keyboard. + /// Labeled <kbd>z</kbd> on a QWERTZ (e.g., German) keyboard. + KeyY, + /// <kbd>z</kbd> on a US keyboard. + /// Labeled <kbd>w</kbd> on an AZERTY (e.g., French) keyboard, and <kbd>y</kbd> on a + /// QWERTZ (e.g., German) keyboard. + KeyZ, + /// <kbd>-</kbd> on a US keyboard. + Minus, + /// <kbd>.</kbd> on a US keyboard. + Period, + /// <kbd>'</kbd> on a US keyboard. + Quote, + /// <kbd>;</kbd> on a US keyboard. + Semicolon, + /// <kbd>/</kbd> on a US keyboard. + Slash, + /// <kbd>Alt</kbd>, <kbd>Option</kbd>, or <kbd>⌥</kbd>. + AltLeft, + /// <kbd>Alt</kbd>, <kbd>Option</kbd>, or <kbd>⌥</kbd>. + /// This is labeled <kbd>AltGr</kbd> on many keyboard layouts. + AltRight, + /// <kbd>Backspace</kbd> or <kbd>⌫</kbd>. + /// Labeled <kbd>Delete</kbd> on Apple keyboards. + Backspace, + /// <kbd>CapsLock</kbd> or <kbd>⇪</kbd> + CapsLock, + /// The application context menu key, which is typically found between the right + /// <kbd>Super</kbd> key and the right <kbd>Control</kbd> key. + ContextMenu, + /// <kbd>Control</kbd> or <kbd>⌃</kbd> + ControlLeft, + /// <kbd>Control</kbd> or <kbd>⌃</kbd> + ControlRight, + /// <kbd>Enter</kbd> or <kbd>↵</kbd>. Labeled <kbd>Return</kbd> on Apple keyboards. + Enter, + /// The Windows, <kbd>⌘</kbd>, <kbd>Command</kbd>, or other OS symbol key. + SuperLeft, + /// The Windows, <kbd>⌘</kbd>, <kbd>Command</kbd>, or other OS symbol key. + SuperRight, + /// <kbd>Shift</kbd> or <kbd>⇧</kbd> + ShiftLeft, + /// <kbd>Shift</kbd> or <kbd>⇧</kbd> + ShiftRight, + /// <kbd> </kbd> (space) + Space, + /// <kbd>Tab</kbd> or <kbd>⇥</kbd> + Tab, + /// Japanese: <kbd>変</kbd> (henkan) + Convert, + /// Japanese: <kbd>カタカナ</kbd>/<kbd>ひらがな</kbd>/<kbd>ローマ字</kbd> + /// (katakana/hiragana/romaji) + KanaMode, + /// Korean: HangulMode <kbd>한/영</kbd> (han/yeong) + /// + /// Japanese (Mac keyboard): <kbd>か</kbd> (kana) + Lang1, + /// Korean: Hanja <kbd>한</kbd> (hanja) + /// + /// Japanese (Mac keyboard): <kbd>英</kbd> (eisu) + Lang2, + /// Japanese (word-processing keyboard): Katakana + Lang3, + /// Japanese (word-processing keyboard): Hiragana + Lang4, + /// Japanese (word-processing keyboard): Zenkaku/Hankaku + Lang5, + /// Japanese: <kbd>無変換</kbd> (muhenkan) + NonConvert, + /// <kbd>⌦</kbd>. The forward delete key. + /// Note that on Apple keyboards, the key labelled <kbd>Delete</kbd> on the main part of + /// the keyboard is encoded as [`Backspace`]. + /// + /// [`Backspace`]: Self::Backspace + Delete, + /// <kbd>Page Down</kbd>, <kbd>End</kbd>, or <kbd>↘</kbd> + End, + /// <kbd>Help</kbd>. Not present on standard PC keyboards. + Help, + /// <kbd>Home</kbd> or <kbd>↖</kbd> + Home, + /// <kbd>Insert</kbd> or <kbd>Ins</kbd>. Not present on Apple keyboards. + Insert, + /// <kbd>Page Down</kbd>, <kbd>PgDn</kbd>, or <kbd>⇟</kbd> + PageDown, + /// <kbd>Page Up</kbd>, <kbd>PgUp</kbd>, or <kbd>⇞</kbd> + PageUp, + /// <kbd>↓</kbd> + ArrowDown, + /// <kbd>←</kbd> + ArrowLeft, + /// <kbd>→</kbd> + ArrowRight, + /// <kbd>↑</kbd> + ArrowUp, + /// On the Mac, this is used for the numpad <kbd>Clear</kbd> key. + NumLock, + /// <kbd>0 Ins</kbd> on a keyboard. <kbd>0</kbd> on a phone or remote control + Numpad0, + /// <kbd>1 End</kbd> on a keyboard. <kbd>1</kbd> or <kbd>1 QZ</kbd> on a phone or remote + /// control + Numpad1, + /// <kbd>2 ↓</kbd> on a keyboard. <kbd>2 ABC</kbd> on a phone or remote control + Numpad2, + /// <kbd>3 PgDn</kbd> on a keyboard. <kbd>3 DEF</kbd> on a phone or remote control + Numpad3, + /// <kbd>4 ←</kbd> on a keyboard. <kbd>4 GHI</kbd> on a phone or remote control + Numpad4, + /// <kbd>5</kbd> on a keyboard. <kbd>5 JKL</kbd> on a phone or remote control + Numpad5, + /// <kbd>6 →</kbd> on a keyboard. <kbd>6 MNO</kbd> on a phone or remote control + Numpad6, + /// <kbd>7 Home</kbd> on a keyboard. <kbd>7 PQRS</kbd> or <kbd>7 PRS</kbd> on a phone + /// or remote control + Numpad7, + /// <kbd>8 ↑</kbd> on a keyboard. <kbd>8 TUV</kbd> on a phone or remote control + Numpad8, + /// <kbd>9 PgUp</kbd> on a keyboard. <kbd>9 WXYZ</kbd> or <kbd>9 WXY</kbd> on a phone + /// or remote control + Numpad9, + /// <kbd>+</kbd> + NumpadAdd, + /// Found on the Microsoft Natural Keyboard. + NumpadBackspace, + /// <kbd>C</kbd> or <kbd>A</kbd> (All Clear). Also for use with numpads that have a + /// <kbd>Clear</kbd> key that is separate from the <kbd>NumLock</kbd> key. On the Mac, the + /// numpad <kbd>Clear</kbd> key is encoded as [`NumLock`]. + /// + /// [`NumLock`]: Self::NumLock + NumpadClear, + /// <kbd>C</kbd> (Clear Entry) + NumpadClearEntry, + /// <kbd>,</kbd> (thousands separator). For locales where the thousands separator + /// is a "." (e.g., Brazil), this key may generate a <kbd>.</kbd>. + NumpadComma, + /// <kbd>. Del</kbd>. For locales where the decimal separator is "," (e.g., + /// Brazil), this key may generate a <kbd>,</kbd>. + NumpadDecimal, + /// <kbd>/</kbd> + NumpadDivide, + NumpadEnter, + /// <kbd>=</kbd> + NumpadEqual, + /// <kbd>#</kbd> on a phone or remote control device. This key is typically found + /// below the <kbd>9</kbd> key and to the right of the <kbd>0</kbd> key. + NumpadHash, + /// <kbd>M</kbd> Add current entry to the value stored in memory. + NumpadMemoryAdd, + /// <kbd>M</kbd> Clear the value stored in memory. + NumpadMemoryClear, + /// <kbd>M</kbd> Replace the current entry with the value stored in memory. + NumpadMemoryRecall, + /// <kbd>M</kbd> Replace the value stored in memory with the current entry. + NumpadMemoryStore, + /// <kbd>M</kbd> Subtract current entry from the value stored in memory. + NumpadMemorySubtract, + /// <kbd>*</kbd> on a keyboard. For use with numpads that provide mathematical + /// operations (<kbd>+</kbd>, <kbd>-</kbd> <kbd>*</kbd> and <kbd>/</kbd>). + /// + /// Use `NumpadStar` for the <kbd>*</kbd> key on phones and remote controls. + NumpadMultiply, + /// <kbd>(</kbd> Found on the Microsoft Natural Keyboard. + NumpadParenLeft, + /// <kbd>)</kbd> Found on the Microsoft Natural Keyboard. + NumpadParenRight, + /// <kbd>*</kbd> on a phone or remote control device. + /// + /// This key is typically found below the <kbd>7</kbd> key and to the left of + /// the <kbd>0</kbd> key. + /// + /// Use <kbd>"NumpadMultiply"</kbd> for the <kbd>*</kbd> key on + /// numeric keypads. + NumpadStar, + /// <kbd>-</kbd> + NumpadSubtract, + /// <kbd>Esc</kbd> or <kbd>⎋</kbd> + Escape, + /// <kbd>Fn</kbd> This is typically a hardware key that does not generate a separate code. + Fn, + /// <kbd>FLock</kbd> or <kbd>FnLock</kbd>. Function Lock key. Found on the Microsoft + /// Natural Keyboard. + FnLock, + /// <kbd>PrtScr SysRq</kbd> or <kbd>Print Screen</kbd> + PrintScreen, + /// <kbd>Scroll Lock</kbd> + ScrollLock, + /// <kbd>Pause Break</kbd> + Pause, + /// Some laptops place this key to the left of the <kbd>↑</kbd> key. + /// + /// This also the "back" button (triangle) on Android. + BrowserBack, + BrowserFavorites, + /// Some laptops place this key to the right of the <kbd>↑</kbd> key. + BrowserForward, + /// The "home" button on Android. + BrowserHome, + BrowserRefresh, + BrowserSearch, + BrowserStop, + /// <kbd>Eject</kbd> or <kbd>⏏</kbd>. This key is placed in the function section on some Apple + /// keyboards. + Eject, + /// Sometimes labelled <kbd>My Computer</kbd> on the keyboard + LaunchApp1, + /// Sometimes labelled <kbd>Calculator</kbd> on the keyboard + LaunchApp2, + LaunchMail, + MediaPlayPause, + MediaSelect, + MediaStop, + MediaTrackNext, + MediaTrackPrevious, + /// This key is placed in the function section on some Apple keyboards, replacing the + /// <kbd>Eject</kbd> key. + Power, + Sleep, + AudioVolumeDown, + AudioVolumeMute, + AudioVolumeUp, + WakeUp, + // Legacy modifier key. Also called "Super" in certain places. + Meta, + // Legacy modifier key. + Hyper, + Turbo, + Abort, + Resume, + Suspend, + /// Found on Sun’s USB keyboard. + Again, + /// Found on Sun’s USB keyboard. + Copy, + /// Found on Sun’s USB keyboard. + Cut, + /// Found on Sun’s USB keyboard. + Find, + /// Found on Sun’s USB keyboard. + Open, + /// Found on Sun’s USB keyboard. + Paste, + /// Found on Sun’s USB keyboard. + Props, + /// Found on Sun’s USB keyboard. + Select, + /// Found on Sun’s USB keyboard. + Undo, + /// Use for dedicated <kbd>ひらがな</kbd> key found on some Japanese word processing keyboards. + Hiragana, + /// Use for dedicated <kbd>カタカナ</kbd> key found on some Japanese word processing keyboards. + Katakana, + /// General-purpose function key. + /// Usually found at the top of the keyboard. + F1, + /// General-purpose function key. + /// Usually found at the top of the keyboard. + F2, + /// General-purpose function key. + /// Usually found at the top of the keyboard. + F3, + /// General-purpose function key. + /// Usually found at the top of the keyboard. + F4, + /// General-purpose function key. + /// Usually found at the top of the keyboard. + F5, + /// General-purpose function key. + /// Usually found at the top of the keyboard. + F6, + /// General-purpose function key. + /// Usually found at the top of the keyboard. + F7, + /// General-purpose function key. + /// Usually found at the top of the keyboard. + F8, + /// General-purpose function key. + /// Usually found at the top of the keyboard. + F9, + /// General-purpose function key. + /// Usually found at the top of the keyboard. + F10, + /// General-purpose function key. + /// Usually found at the top of the keyboard. + F11, + /// General-purpose function key. + /// Usually found at the top of the keyboard. + F12, + /// General-purpose function key. + /// Usually found at the top of the keyboard. + F13, + /// General-purpose function key. + /// Usually found at the top of the keyboard. + F14, + /// General-purpose function key. + /// Usually found at the top of the keyboard. + F15, + /// General-purpose function key. + /// Usually found at the top of the keyboard. + F16, + /// General-purpose function key. + /// Usually found at the top of the keyboard. + F17, + /// General-purpose function key. + /// Usually found at the top of the keyboard. + F18, + /// General-purpose function key. + /// Usually found at the top of the keyboard. + F19, + /// General-purpose function key. + /// Usually found at the top of the keyboard. + F20, + /// General-purpose function key. + /// Usually found at the top of the keyboard. + F21, + /// General-purpose function key. + /// Usually found at the top of the keyboard. + F22, + /// General-purpose function key. + /// Usually found at the top of the keyboard. + F23, + /// General-purpose function key. + /// Usually found at the top of the keyboard. + F24, + /// General-purpose function key. + F25, + /// General-purpose function key. + F26, + /// General-purpose function key. + F27, + /// General-purpose function key. + F28, + /// General-purpose function key. + F29, + /// General-purpose function key. + F30, + /// General-purpose function key. + F31, + /// General-purpose function key. + F32, + /// General-purpose function key. + F33, + /// General-purpose function key. + F34, + /// General-purpose function key. + F35, +} + +/// A [`Key::Named`] value +/// +/// This mostly conforms to the UI Events Specification's [`KeyboardEvent.key`] with a few +/// exceptions: +/// - The `Super` variant here, is named `Meta` in the aforementioned specification. (There's +/// another key which the specification calls `Super`. That does not exist here.) +/// - The `Space` variant here, can be identified by the character it generates in the +/// specification. +/// +/// [`KeyboardEvent.key`]: https://w3c.github.io/uievents-key/ +#[non_exhaustive] +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)] +#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] +pub enum NamedKey { + /// The `Alt` (Alternative) key. + /// + /// This key enables the alternate modifier function for interpreting concurrent or subsequent + /// keyboard input. This key value is also used for the Apple <kbd>Option</kbd> key. + Alt, + /// The Alternate Graphics (<kbd>AltGr</kbd> or <kbd>AltGraph</kbd>) key. + /// + /// This key is used enable the ISO Level 3 shift modifier (the standard `Shift` key is the + /// level 2 modifier). + AltGraph, + /// The `Caps Lock` (Capital) key. + /// + /// Toggle capital character lock function for interpreting subsequent keyboard input event. + CapsLock, + /// The `Control` or `Ctrl` key. + /// + /// Used to enable control modifier function for interpreting concurrent or subsequent keyboard + /// input. + Control, + /// The Function switch `Fn` key. Activating this key simultaneously with another key changes + /// that key’s value to an alternate character or function. This key is often handled directly + /// in the keyboard hardware and does not usually generate key events. + Fn, + /// The Function-Lock (`FnLock` or `F-Lock`) key. Activating this key switches the mode of the + /// keyboard to changes some keys' values to an alternate character or function. This key is + /// often handled directly in the keyboard hardware and does not usually generate key events. + FnLock, + /// The `NumLock` or Number Lock key. Used to toggle numpad mode function for interpreting + /// subsequent keyboard input. + NumLock, + /// Toggle between scrolling and cursor movement modes. + ScrollLock, + /// Used to enable shift modifier function for interpreting concurrent or subsequent keyboard + /// input. + Shift, + /// The Symbol modifier key (used on some virtual keyboards). + Symbol, + SymbolLock, + // Legacy modifier key. Also called "Super" in certain places. + Meta, + // Legacy modifier key. + Hyper, + /// Used to enable "super" modifier function for interpreting concurrent or subsequent keyboard + /// input. This key value is used for the "Windows Logo" key and the Apple `Command` or `⌘` + /// key. + /// + /// Note: In some contexts (e.g. the Web) this is referred to as the "Meta" key. + Super, + /// The `Enter` or `↵` key. Used to activate current selection or accept current input. This + /// key value is also used for the `Return` (Macintosh numpad) key. This key value is also + /// used for the Android `KEYCODE_DPAD_CENTER`. + Enter, + /// The Horizontal Tabulation `Tab` key. + Tab, + /// Used in text to insert a space between words. Usually located below the character keys. + Space, + /// Navigate or traverse downward. (`KEYCODE_DPAD_DOWN`) + ArrowDown, + /// Navigate or traverse leftward. (`KEYCODE_DPAD_LEFT`) + ArrowLeft, + /// Navigate or traverse rightward. (`KEYCODE_DPAD_RIGHT`) + ArrowRight, + /// Navigate or traverse upward. (`KEYCODE_DPAD_UP`) + ArrowUp, + /// The End key, used with keyboard entry to go to the end of content (`KEYCODE_MOVE_END`). + End, + /// The Home key, used with keyboard entry, to go to start of content (`KEYCODE_MOVE_HOME`). + /// For the mobile phone `Home` key (which goes to the phone’s main screen), use [`GoHome`]. + /// + /// [`GoHome`]: Self::GoHome + Home, + /// Scroll down or display next page of content. + PageDown, + /// Scroll up or display previous page of content. + PageUp, + /// Used to remove the character to the left of the cursor. This key value is also used for + /// the key labeled `Delete` on MacOS keyboards. + Backspace, + /// Remove the currently selected input. + Clear, + /// Copy the current selection. (`APPCOMMAND_COPY`) + Copy, + /// The Cursor Select key. + CrSel, + /// Cut the current selection. (`APPCOMMAND_CUT`) + Cut, + /// Used to delete the character to the right of the cursor. This key value is also used for + /// the key labeled `Delete` on MacOS keyboards when `Fn` is active. + Delete, + /// The Erase to End of Field key. This key deletes all characters from the current cursor + /// position to the end of the current field. + EraseEof, + /// The Extend Selection (Exsel) key. + ExSel, + /// Toggle between text modes for insertion or overtyping. + /// (`KEYCODE_INSERT`) + Insert, + /// The Paste key. (`APPCOMMAND_PASTE`) + Paste, + /// Redo the last action. (`APPCOMMAND_REDO`) + Redo, + /// Undo the last action. (`APPCOMMAND_UNDO`) + Undo, + /// The Accept (Commit, OK) key. Accept current option or input method sequence conversion. + Accept, + /// Redo or repeat an action. + Again, + /// The Attention (Attn) key. + Attn, + Cancel, + /// Show the application’s context menu. + /// This key is commonly found between the right `Super` key and the right `Control` key. + ContextMenu, + /// The `Esc` key. This key was originally used to initiate an escape sequence, but is + /// now more generally used to exit or "escape" the current context, such as closing a dialog + /// or exiting full screen mode. + Escape, + Execute, + /// Open the Find dialog. (`APPCOMMAND_FIND`) + Find, + /// Open a help dialog or toggle display of help information. (`APPCOMMAND_HELP`, + /// `KEYCODE_HELP`) + Help, + /// Pause the current state or application (as appropriate). + /// + /// Note: Do not use this value for the `Pause` button on media controllers. Use `"MediaPause"` + /// instead. + Pause, + /// Play or resume the current state or application (as appropriate). + /// + /// Note: Do not use this value for the `Play` button on media controllers. Use `"MediaPlay"` + /// instead. + Play, + /// The properties (Props) key. + Props, + Select, + /// The ZoomIn key. (`KEYCODE_ZOOM_IN`) + ZoomIn, + /// The ZoomOut key. (`KEYCODE_ZOOM_OUT`) + ZoomOut, + /// The Brightness Down key. Typically controls the display brightness. + /// (`KEYCODE_BRIGHTNESS_DOWN`) + BrightnessDown, + /// The Brightness Up key. Typically controls the display brightness. (`KEYCODE_BRIGHTNESS_UP`) + BrightnessUp, + /// Toggle removable media to eject (open) and insert (close) state. (`KEYCODE_MEDIA_EJECT`) + Eject, + LogOff, + /// Toggle power state. (`KEYCODE_POWER`) + /// Note: Note: Some devices might not expose this key to the operating environment. + Power, + /// The `PowerOff` key. Sometime called `PowerDown`. + PowerOff, + /// Initiate print-screen function. + PrintScreen, + /// The Hibernate key. This key saves the current state of the computer to disk so that it can + /// be restored. The computer will then shutdown. + Hibernate, + /// The Standby key. This key turns off the display and places the computer into a low-power + /// mode without completely shutting down. It is sometimes labelled `Suspend` or `Sleep` key. + /// (`KEYCODE_SLEEP`) + Standby, + /// The WakeUp key. (`KEYCODE_WAKEUP`) + WakeUp, + /// Initiate the multi-candidate mode. + AllCandidates, + Alphanumeric, + /// Initiate the Code Input mode to allow characters to be entered by + /// their code points. + CodeInput, + /// The Compose key, also known as "Multi_key" on the X Window System. This key acts in a + /// manner similar to a dead key, triggering a mode where subsequent key presses are combined + /// to produce a different character. + Compose, + /// Convert the current input method sequence. + Convert, + /// The Final Mode `Final` key used on some Asian keyboards, to enable the final mode for IMEs. + FinalMode, + /// Switch to the first character group. (ISO/IEC 9995) + GroupFirst, + /// Switch to the last character group. (ISO/IEC 9995) + GroupLast, + /// Switch to the next character group. (ISO/IEC 9995) + GroupNext, + /// Switch to the previous character group. (ISO/IEC 9995) + GroupPrevious, + /// Toggle between or cycle through input modes of IMEs. + ModeChange, + NextCandidate, + /// Accept current input method sequence without + /// conversion in IMEs. + NonConvert, + PreviousCandidate, + Process, + SingleCandidate, + /// Toggle between Hangul and English modes. + HangulMode, + HanjaMode, + JunjaMode, + /// The Eisu key. This key may close the IME, but its purpose is defined by the current IME. + /// (`KEYCODE_EISU`) + Eisu, + /// The (Half-Width) Characters key. + Hankaku, + /// The Hiragana (Japanese Kana characters) key. + Hiragana, + /// The Hiragana/Katakana toggle key. (`KEYCODE_KATAKANA_HIRAGANA`) + HiraganaKatakana, + /// The Kana Mode (Kana Lock) key. This key is used to enter hiragana mode (typically from + /// romaji mode). + KanaMode, + /// The Kanji (Japanese name for ideographic characters of Chinese origin) Mode key. This key + /// is typically used to switch to a hiragana keyboard for the purpose of converting input + /// into kanji. (`KEYCODE_KANA`) + KanjiMode, + /// The Katakana (Japanese Kana characters) key. + Katakana, + /// The Roman characters function key. + Romaji, + /// The Zenkaku (Full-Width) Characters key. + Zenkaku, + /// The Zenkaku/Hankaku (full-width/half-width) toggle key. (`KEYCODE_ZENKAKU_HANKAKU`) + ZenkakuHankaku, + /// General purpose virtual function key, as index 1. + Soft1, + /// General purpose virtual function key, as index 2. + Soft2, + /// General purpose virtual function key, as index 3. + Soft3, + /// General purpose virtual function key, as index 4. + Soft4, + /// Select next (numerically or logically) lower channel. (`APPCOMMAND_MEDIA_CHANNEL_DOWN`, + /// `KEYCODE_CHANNEL_DOWN`) + ChannelDown, + /// Select next (numerically or logically) higher channel. (`APPCOMMAND_MEDIA_CHANNEL_UP`, + /// `KEYCODE_CHANNEL_UP`) + ChannelUp, + /// Close the current document or message (Note: This doesn’t close the application). + /// (`APPCOMMAND_CLOSE`) + Close, + /// Open an editor to forward the current message. (`APPCOMMAND_FORWARD_MAIL`) + MailForward, + /// Open an editor to reply to the current message. (`APPCOMMAND_REPLY_TO_MAIL`) + MailReply, + /// Send the current message. (`APPCOMMAND_SEND_MAIL`) + MailSend, + /// Close the current media, for example to close a CD or DVD tray. (`KEYCODE_MEDIA_CLOSE`) + MediaClose, + /// Initiate or continue forward playback at faster than normal speed, or increase speed if + /// already fast forwarding. (`APPCOMMAND_MEDIA_FAST_FORWARD`, `KEYCODE_MEDIA_FAST_FORWARD`) + MediaFastForward, + /// Pause the currently playing media. (`APPCOMMAND_MEDIA_PAUSE`, `KEYCODE_MEDIA_PAUSE`) + /// + /// Note: Media controller devices should use this value rather than `"Pause"` for their pause + /// keys. + MediaPause, + /// Initiate or continue media playback at normal speed, if not currently playing at normal + /// speed. (`APPCOMMAND_MEDIA_PLAY`, `KEYCODE_MEDIA_PLAY`) + MediaPlay, + /// Toggle media between play and pause states. (`APPCOMMAND_MEDIA_PLAY_PAUSE`, + /// `KEYCODE_MEDIA_PLAY_PAUSE`) + MediaPlayPause, + /// Initiate or resume recording of currently selected media. (`APPCOMMAND_MEDIA_RECORD`, + /// `KEYCODE_MEDIA_RECORD`) + MediaRecord, + /// Initiate or continue reverse playback at faster than normal speed, or increase speed if + /// already rewinding. (`APPCOMMAND_MEDIA_REWIND`, `KEYCODE_MEDIA_REWIND`) + MediaRewind, + /// Stop media playing, pausing, forwarding, rewinding, or recording, if not already stopped. + /// (`APPCOMMAND_MEDIA_STOP`, `KEYCODE_MEDIA_STOP`) + MediaStop, + /// Seek to next media or program track. (`APPCOMMAND_MEDIA_NEXTTRACK`, `KEYCODE_MEDIA_NEXT`) + MediaTrackNext, + /// Seek to previous media or program track. (`APPCOMMAND_MEDIA_PREVIOUSTRACK`, + /// `KEYCODE_MEDIA_PREVIOUS`) + MediaTrackPrevious, + /// Open a new document or message. (`APPCOMMAND_NEW`) + New, + /// Open an existing document or message. (`APPCOMMAND_OPEN`) + Open, + /// Print the current document or message. (`APPCOMMAND_PRINT`) + Print, + /// Save the current document or message. (`APPCOMMAND_SAVE`) + Save, + /// Spellcheck the current document or selection. (`APPCOMMAND_SPELL_CHECK`) + SpellCheck, + /// The `11` key found on media numpads that + /// have buttons from `1` ... `12`. + Key11, + /// The `12` key found on media numpads that + /// have buttons from `1` ... `12`. + Key12, + /// Adjust audio balance leftward. (`VK_AUDIO_BALANCE_LEFT`) + AudioBalanceLeft, + /// Adjust audio balance rightward. (`VK_AUDIO_BALANCE_RIGHT`) + AudioBalanceRight, + /// Decrease audio bass boost or cycle down through bass boost states. (`APPCOMMAND_BASS_DOWN`, + /// `VK_BASS_BOOST_DOWN`) + AudioBassBoostDown, + /// Toggle bass boost on/off. (`APPCOMMAND_BASS_BOOST`) + AudioBassBoostToggle, + /// Increase audio bass boost or cycle up through bass boost states. (`APPCOMMAND_BASS_UP`, + /// `VK_BASS_BOOST_UP`) + AudioBassBoostUp, + /// Adjust audio fader towards front. (`VK_FADER_FRONT`) + AudioFaderFront, + /// Adjust audio fader towards rear. (`VK_FADER_REAR`) + AudioFaderRear, + /// Advance surround audio mode to next available mode. (`VK_SURROUND_MODE_NEXT`) + AudioSurroundModeNext, + /// Decrease treble. (`APPCOMMAND_TREBLE_DOWN`) + AudioTrebleDown, + /// Increase treble. (`APPCOMMAND_TREBLE_UP`) + AudioTrebleUp, + /// Decrease audio volume. (`APPCOMMAND_VOLUME_DOWN`, `KEYCODE_VOLUME_DOWN`) + AudioVolumeDown, + /// Increase audio volume. (`APPCOMMAND_VOLUME_UP`, `KEYCODE_VOLUME_UP`) + AudioVolumeUp, + /// Toggle between muted state and prior volume level. (`APPCOMMAND_VOLUME_MUTE`, + /// `KEYCODE_VOLUME_MUTE`) + AudioVolumeMute, + /// Toggle the microphone on/off. (`APPCOMMAND_MIC_ON_OFF_TOGGLE`) + MicrophoneToggle, + /// Decrease microphone volume. (`APPCOMMAND_MICROPHONE_VOLUME_DOWN`) + MicrophoneVolumeDown, + /// Increase microphone volume. (`APPCOMMAND_MICROPHONE_VOLUME_UP`) + MicrophoneVolumeUp, + /// Mute the microphone. (`APPCOMMAND_MICROPHONE_VOLUME_MUTE`, `KEYCODE_MUTE`) + MicrophoneVolumeMute, + /// Show correction list when a word is incorrectly identified. (`APPCOMMAND_CORRECTION_LIST`) + SpeechCorrectionList, + /// Toggle between dictation mode and command/control mode. + /// (`APPCOMMAND_DICTATE_OR_COMMAND_CONTROL_TOGGLE`) + SpeechInputToggle, + /// The first generic "LaunchApplication" key. This is commonly associated with launching "My + /// Computer", and may have a computer symbol on the key. (`APPCOMMAND_LAUNCH_APP1`) + LaunchApplication1, + /// The second generic "LaunchApplication" key. This is commonly associated with launching + /// "Calculator", and may have a calculator symbol on the key. (`APPCOMMAND_LAUNCH_APP2`, + /// `KEYCODE_CALCULATOR`) + LaunchApplication2, + /// The "Calendar" key. (`KEYCODE_CALENDAR`) + LaunchCalendar, + /// The "Contacts" key. (`KEYCODE_CONTACTS`) + LaunchContacts, + /// The "Mail" key. (`APPCOMMAND_LAUNCH_MAIL`) + LaunchMail, + /// The "Media Player" key. (`APPCOMMAND_LAUNCH_MEDIA_SELECT`) + LaunchMediaPlayer, + LaunchMusicPlayer, + LaunchPhone, + LaunchScreenSaver, + LaunchSpreadsheet, + LaunchWebBrowser, + LaunchWebCam, + LaunchWordProcessor, + /// Navigate to previous content or page in current history. (`APPCOMMAND_BROWSER_BACKWARD`) + BrowserBack, + /// Open the list of browser favorites. (`APPCOMMAND_BROWSER_FAVORITES`) + BrowserFavorites, + /// Navigate to next content or page in current history. (`APPCOMMAND_BROWSER_FORWARD`) + BrowserForward, + /// Go to the user’s preferred home page. (`APPCOMMAND_BROWSER_HOME`) + BrowserHome, + /// Refresh the current page or content. (`APPCOMMAND_BROWSER_REFRESH`) + BrowserRefresh, + /// Call up the user’s preferred search page. (`APPCOMMAND_BROWSER_SEARCH`) + BrowserSearch, + /// Stop loading the current page or content. (`APPCOMMAND_BROWSER_STOP`) + BrowserStop, + /// The Application switch key, which provides a list of recent apps to switch between. + /// (`KEYCODE_APP_SWITCH`) + AppSwitch, + /// The Call key. (`KEYCODE_CALL`) + Call, + /// The Camera key. (`KEYCODE_CAMERA`) + Camera, + /// The Camera focus key. (`KEYCODE_FOCUS`) + CameraFocus, + /// The End Call key. (`KEYCODE_ENDCALL`) + EndCall, + /// The Back key. (`KEYCODE_BACK`) + GoBack, + /// The Home key, which goes to the phone’s main screen. (`KEYCODE_HOME`) + GoHome, + /// The Headset Hook key. (`KEYCODE_HEADSETHOOK`) + HeadsetHook, + LastNumberRedial, + /// The Notification key. (`KEYCODE_NOTIFICATION`) + Notification, + /// Toggle between manner mode state: silent, vibrate, ring, ... (`KEYCODE_MANNER_MODE`) + MannerMode, + VoiceDial, + /// Switch to viewing TV. (`KEYCODE_TV`) + TV, + /// TV 3D Mode. (`KEYCODE_3D_MODE`) + TV3DMode, + /// Toggle between antenna and cable input. (`KEYCODE_TV_ANTENNA_CABLE`) + TVAntennaCable, + /// Audio description. (`KEYCODE_TV_AUDIO_DESCRIPTION`) + TVAudioDescription, + /// Audio description mixing volume down. (`KEYCODE_TV_AUDIO_DESCRIPTION_MIX_DOWN`) + TVAudioDescriptionMixDown, + /// Audio description mixing volume up. (`KEYCODE_TV_AUDIO_DESCRIPTION_MIX_UP`) + TVAudioDescriptionMixUp, + /// Contents menu. (`KEYCODE_TV_CONTENTS_MENU`) + TVContentsMenu, + /// Contents menu. (`KEYCODE_TV_DATA_SERVICE`) + TVDataService, + /// Switch the input mode on an external TV. (`KEYCODE_TV_INPUT`) + TVInput, + /// Switch to component input #1. (`KEYCODE_TV_INPUT_COMPONENT_1`) + TVInputComponent1, + /// Switch to component input #2. (`KEYCODE_TV_INPUT_COMPONENT_2`) + TVInputComponent2, + /// Switch to composite input #1. (`KEYCODE_TV_INPUT_COMPOSITE_1`) + TVInputComposite1, + /// Switch to composite input #2. (`KEYCODE_TV_INPUT_COMPOSITE_2`) + TVInputComposite2, + /// Switch to HDMI input #1. (`KEYCODE_TV_INPUT_HDMI_1`) + TVInputHDMI1, + /// Switch to HDMI input #2. (`KEYCODE_TV_INPUT_HDMI_2`) + TVInputHDMI2, + /// Switch to HDMI input #3. (`KEYCODE_TV_INPUT_HDMI_3`) + TVInputHDMI3, + /// Switch to HDMI input #4. (`KEYCODE_TV_INPUT_HDMI_4`) + TVInputHDMI4, + /// Switch to VGA input #1. (`KEYCODE_TV_INPUT_VGA_1`) + TVInputVGA1, + /// Media context menu. (`KEYCODE_TV_MEDIA_CONTEXT_MENU`) + TVMediaContext, + /// Toggle network. (`KEYCODE_TV_NETWORK`) + TVNetwork, + /// Number entry. (`KEYCODE_TV_NUMBER_ENTRY`) + TVNumberEntry, + /// Toggle the power on an external TV. (`KEYCODE_TV_POWER`) + TVPower, + /// Radio. (`KEYCODE_TV_RADIO_SERVICE`) + TVRadioService, + /// Satellite. (`KEYCODE_TV_SATELLITE`) + TVSatellite, + /// Broadcast Satellite. (`KEYCODE_TV_SATELLITE_BS`) + TVSatelliteBS, + /// Communication Satellite. (`KEYCODE_TV_SATELLITE_CS`) + TVSatelliteCS, + /// Toggle between available satellites. (`KEYCODE_TV_SATELLITE_SERVICE`) + TVSatelliteToggle, + /// Analog Terrestrial. (`KEYCODE_TV_TERRESTRIAL_ANALOG`) + TVTerrestrialAnalog, + /// Digital Terrestrial. (`KEYCODE_TV_TERRESTRIAL_DIGITAL`) + TVTerrestrialDigital, + /// Timer programming. (`KEYCODE_TV_TIMER_PROGRAMMING`) + TVTimer, + /// Switch the input mode on an external AVR (audio/video receiver). (`KEYCODE_AVR_INPUT`) + AVRInput, + /// Toggle the power on an external AVR (audio/video receiver). (`KEYCODE_AVR_POWER`) + AVRPower, + /// General purpose color-coded media function key, as index 0 (red). (`VK_COLORED_KEY_0`, + /// `KEYCODE_PROG_RED`) + ColorF0Red, + /// General purpose color-coded media function key, as index 1 (green). (`VK_COLORED_KEY_1`, + /// `KEYCODE_PROG_GREEN`) + ColorF1Green, + /// General purpose color-coded media function key, as index 2 (yellow). (`VK_COLORED_KEY_2`, + /// `KEYCODE_PROG_YELLOW`) + ColorF2Yellow, + /// General purpose color-coded media function key, as index 3 (blue). (`VK_COLORED_KEY_3`, + /// `KEYCODE_PROG_BLUE`) + ColorF3Blue, + /// General purpose color-coded media function key, as index 4 (grey). (`VK_COLORED_KEY_4`) + ColorF4Grey, + /// General purpose color-coded media function key, as index 5 (brown). (`VK_COLORED_KEY_5`) + ColorF5Brown, + /// Toggle the display of Closed Captions. (`VK_CC`, `KEYCODE_CAPTIONS`) + ClosedCaptionToggle, + /// Adjust brightness of device, by toggling between or cycling through states. (`VK_DIMMER`) + Dimmer, + /// Swap video sources. (`VK_DISPLAY_SWAP`) + DisplaySwap, + /// Select Digital Video Recorder. (`KEYCODE_DVR`) + DVR, + /// Exit the current application. (`VK_EXIT`) + Exit, + /// Clear program or content stored as favorite 0. (`VK_CLEAR_FAVORITE_0`) + FavoriteClear0, + /// Clear program or content stored as favorite 1. (`VK_CLEAR_FAVORITE_1`) + FavoriteClear1, + /// Clear program or content stored as favorite 2. (`VK_CLEAR_FAVORITE_2`) + FavoriteClear2, + /// Clear program or content stored as favorite 3. (`VK_CLEAR_FAVORITE_3`) + FavoriteClear3, + /// Select (recall) program or content stored as favorite 0. (`VK_RECALL_FAVORITE_0`) + FavoriteRecall0, + /// Select (recall) program or content stored as favorite 1. (`VK_RECALL_FAVORITE_1`) + FavoriteRecall1, + /// Select (recall) program or content stored as favorite 2. (`VK_RECALL_FAVORITE_2`) + FavoriteRecall2, + /// Select (recall) program or content stored as favorite 3. (`VK_RECALL_FAVORITE_3`) + FavoriteRecall3, + /// Store current program or content as favorite 0. (`VK_STORE_FAVORITE_0`) + FavoriteStore0, + /// Store current program or content as favorite 1. (`VK_STORE_FAVORITE_1`) + FavoriteStore1, + /// Store current program or content as favorite 2. (`VK_STORE_FAVORITE_2`) + FavoriteStore2, + /// Store current program or content as favorite 3. (`VK_STORE_FAVORITE_3`) + FavoriteStore3, + /// Toggle display of program or content guide. (`VK_GUIDE`, `KEYCODE_GUIDE`) + Guide, + /// If guide is active and displayed, then display next day’s content. (`VK_NEXT_DAY`) + GuideNextDay, + /// If guide is active and displayed, then display previous day’s content. (`VK_PREV_DAY`) + GuidePreviousDay, + /// Toggle display of information about currently selected context or media. (`VK_INFO`, + /// `KEYCODE_INFO`) + Info, + /// Toggle instant replay. (`VK_INSTANT_REPLAY`) + InstantReplay, + /// Launch linked content, if available and appropriate. (`VK_LINK`) + Link, + /// List the current program. (`VK_LIST`) + ListProgram, + /// Toggle display listing of currently available live content or programs. (`VK_LIVE`) + LiveContent, + /// Lock or unlock current content or program. (`VK_LOCK`) + Lock, + /// Show a list of media applications: audio/video players and image viewers. (`VK_APPS`) + /// + /// Note: Do not confuse this key value with the Windows' `VK_APPS` / `VK_CONTEXT_MENU` key, + /// which is encoded as `"ContextMenu"`. + MediaApps, + /// Audio track key. (`KEYCODE_MEDIA_AUDIO_TRACK`) + MediaAudioTrack, + /// Select previously selected channel or media. (`VK_LAST`, `KEYCODE_LAST_CHANNEL`) + MediaLast, + /// Skip backward to next content or program. (`KEYCODE_MEDIA_SKIP_BACKWARD`) + MediaSkipBackward, + /// Skip forward to next content or program. (`VK_SKIP`, `KEYCODE_MEDIA_SKIP_FORWARD`) + MediaSkipForward, + /// Step backward to next content or program. (`KEYCODE_MEDIA_STEP_BACKWARD`) + MediaStepBackward, + /// Step forward to next content or program. (`KEYCODE_MEDIA_STEP_FORWARD`) + MediaStepForward, + /// Media top menu. (`KEYCODE_MEDIA_TOP_MENU`) + MediaTopMenu, + /// Navigate in. (`KEYCODE_NAVIGATE_IN`) + NavigateIn, + /// Navigate to next key. (`KEYCODE_NAVIGATE_NEXT`) + NavigateNext, + /// Navigate out. (`KEYCODE_NAVIGATE_OUT`) + NavigateOut, + /// Navigate to previous key. (`KEYCODE_NAVIGATE_PREVIOUS`) + NavigatePrevious, + /// Cycle to next favorite channel (in favorites list). (`VK_NEXT_FAVORITE_CHANNEL`) + NextFavoriteChannel, + /// Cycle to next user profile (if there are multiple user profiles). (`VK_USER`) + NextUserProfile, + /// Access on-demand content or programs. (`VK_ON_DEMAND`) + OnDemand, + /// Pairing key to pair devices. (`KEYCODE_PAIRING`) + Pairing, + /// Move picture-in-picture window down. (`VK_PINP_DOWN`) + PinPDown, + /// Move picture-in-picture window. (`VK_PINP_MOVE`) + PinPMove, + /// Toggle display of picture-in-picture window. (`VK_PINP_TOGGLE`) + PinPToggle, + /// Move picture-in-picture window up. (`VK_PINP_UP`) + PinPUp, + /// Decrease media playback speed. (`VK_PLAY_SPEED_DOWN`) + PlaySpeedDown, + /// Reset playback to normal speed. (`VK_PLAY_SPEED_RESET`) + PlaySpeedReset, + /// Increase media playback speed. (`VK_PLAY_SPEED_UP`) + PlaySpeedUp, + /// Toggle random media or content shuffle mode. (`VK_RANDOM_TOGGLE`) + RandomToggle, + /// Not a physical key, but this key code is sent when the remote control battery is low. + /// (`VK_RC_LOW_BATTERY`) + RcLowBattery, + /// Toggle or cycle between media recording speeds. (`VK_RECORD_SPEED_NEXT`) + RecordSpeedNext, + /// Toggle RF (radio frequency) input bypass mode (pass RF input directly to the RF output). + /// (`VK_RF_BYPASS`) + RfBypass, + /// Toggle scan channels mode. (`VK_SCAN_CHANNELS_TOGGLE`) + ScanChannelsToggle, + /// Advance display screen mode to next available mode. (`VK_SCREEN_MODE_NEXT`) + ScreenModeNext, + /// Toggle display of device settings screen. (`VK_SETTINGS`, `KEYCODE_SETTINGS`) + Settings, + /// Toggle split screen mode. (`VK_SPLIT_SCREEN_TOGGLE`) + SplitScreenToggle, + /// Switch the input mode on an external STB (set top box). (`KEYCODE_STB_INPUT`) + STBInput, + /// Toggle the power on an external STB (set top box). (`KEYCODE_STB_POWER`) + STBPower, + /// Toggle display of subtitles, if available. (`VK_SUBTITLE`) + Subtitle, + /// Toggle display of teletext, if available (`VK_TELETEXT`, `KEYCODE_TV_TELETEXT`). + Teletext, + /// Advance video mode to next available mode. (`VK_VIDEO_MODE_NEXT`) + VideoModeNext, + /// Cause device to identify itself in some manner, e.g., audibly or visibly. (`VK_WINK`) + Wink, + /// Toggle between full-screen and scaled content, or alter magnification level. (`VK_ZOOM`, + /// `KEYCODE_TV_ZOOM_MODE`) + ZoomToggle, + /// General-purpose function key. + /// Usually found at the top of the keyboard. + F1, + /// General-purpose function key. + /// Usually found at the top of the keyboard. + F2, + /// General-purpose function key. + /// Usually found at the top of the keyboard. + F3, + /// General-purpose function key. + /// Usually found at the top of the keyboard. + F4, + /// General-purpose function key. + /// Usually found at the top of the keyboard. + F5, + /// General-purpose function key. + /// Usually found at the top of the keyboard. + F6, + /// General-purpose function key. + /// Usually found at the top of the keyboard. + F7, + /// General-purpose function key. + /// Usually found at the top of the keyboard. + F8, + /// General-purpose function key. + /// Usually found at the top of the keyboard. + F9, + /// General-purpose function key. + /// Usually found at the top of the keyboard. + F10, + /// General-purpose function key. + /// Usually found at the top of the keyboard. + F11, + /// General-purpose function key. + /// Usually found at the top of the keyboard. + F12, + /// General-purpose function key. + /// Usually found at the top of the keyboard. + F13, + /// General-purpose function key. + /// Usually found at the top of the keyboard. + F14, + /// General-purpose function key. + /// Usually found at the top of the keyboard. + F15, + /// General-purpose function key. + /// Usually found at the top of the keyboard. + F16, + /// General-purpose function key. + /// Usually found at the top of the keyboard. + F17, + /// General-purpose function key. + /// Usually found at the top of the keyboard. + F18, + /// General-purpose function key. + /// Usually found at the top of the keyboard. + F19, + /// General-purpose function key. + /// Usually found at the top of the keyboard. + F20, + /// General-purpose function key. + /// Usually found at the top of the keyboard. + F21, + /// General-purpose function key. + /// Usually found at the top of the keyboard. + F22, + /// General-purpose function key. + /// Usually found at the top of the keyboard. + F23, + /// General-purpose function key. + /// Usually found at the top of the keyboard. + F24, + /// General-purpose function key. + F25, + /// General-purpose function key. + F26, + /// General-purpose function key. + F27, + /// General-purpose function key. + F28, + /// General-purpose function key. + F29, + /// General-purpose function key. + F30, + /// General-purpose function key. + F31, + /// General-purpose function key. + F32, + /// General-purpose function key. + F33, + /// General-purpose function key. + F34, + /// General-purpose function key. + F35, +} + +/// Key represents the meaning of a keypress. +/// +/// This is a superset of the UI Events Specification's [`KeyboardEvent.key`] with +/// additions: +/// - All simple variants are wrapped under the `Named` variant +/// - The `Unidentified` variant here, can still identify a key through it's `NativeKeyCode`. +/// - The `Dead` variant here, can specify the character which is inserted when pressing the +/// dead-key twice. +/// +/// [`KeyboardEvent.key`]: https://w3c.github.io/uievents-key/ +#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] +#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] +pub enum Key<Str = SmolStr> { + /// A simple (unparameterised) action + Named(NamedKey), + + /// A key string that corresponds to the character typed by the user, taking into account the + /// user’s current locale setting, and any system-level keyboard mapping overrides that are in + /// effect. + Character(Str), + + /// This variant is used when the key cannot be translated to any other variant. + /// + /// The native key is provided (if available) in order to allow the user to specify keybindings + /// for keys which are not defined by this API, mainly through some sort of UI. + Unidentified(NativeKey), + + /// Contains the text representation of the dead-key when available. + /// + /// ## Platform-specific + /// - **Web:** Always contains `None` + Dead(Option<char>), +} + +impl From<NamedKey> for Key { + #[inline] + fn from(action: NamedKey) -> Self { + Key::Named(action) + } +} + +impl From<NativeKey> for Key { + #[inline] + fn from(code: NativeKey) -> Self { + Key::Unidentified(code) + } +} + +impl<Str> PartialEq<NamedKey> for Key<Str> { + #[inline] + fn eq(&self, rhs: &NamedKey) -> bool { + match self { + Key::Named(ref a) => a == rhs, + _ => false, + } + } +} + +impl<Str: PartialEq<str>> PartialEq<str> for Key<Str> { + #[inline] + fn eq(&self, rhs: &str) -> bool { + match self { + Key::Character(ref s) => s == rhs, + _ => false, + } + } +} + +impl<Str: PartialEq<str>> PartialEq<&str> for Key<Str> { + #[inline] + fn eq(&self, rhs: &&str) -> bool { + self == *rhs + } +} + +impl<Str> PartialEq<NativeKey> for Key<Str> { + #[inline] + fn eq(&self, rhs: &NativeKey) -> bool { + match self { + Key::Unidentified(ref code) => code == rhs, + _ => false, + } + } +} + +impl<Str> PartialEq<Key<Str>> for NativeKey { + #[inline] + fn eq(&self, rhs: &Key<Str>) -> bool { + rhs == self + } +} + +impl Key<SmolStr> { + /// Convert `Key::Character(SmolStr)` to `Key::Character(&str)` so you can more easily match on + /// `Key`. All other variants remain unchanged. + pub fn as_ref(&self) -> Key<&str> { + match self { + Key::Named(a) => Key::Named(*a), + Key::Character(ch) => Key::Character(ch.as_str()), + Key::Dead(d) => Key::Dead(*d), + Key::Unidentified(u) => Key::Unidentified(u.clone()), + } + } +} + +impl NamedKey { + /// Convert an action to its approximate textual equivalent. + /// + /// # Examples + /// + /// ``` + /// use winit::keyboard::NamedKey; + /// + /// assert_eq!(NamedKey::Enter.to_text(), Some("\r")); + /// assert_eq!(NamedKey::F20.to_text(), None); + /// ``` + pub fn to_text(&self) -> Option<&str> { + match self { + NamedKey::Enter => Some("\r"), + NamedKey::Backspace => Some("\x08"), + NamedKey::Tab => Some("\t"), + NamedKey::Space => Some(" "), + NamedKey::Escape => Some("\x1b"), + _ => None, + } + } +} + +impl Key { + /// Convert a key to its approximate textual equivalent. + /// + /// # Examples + /// + /// ``` + /// use winit::keyboard::{Key, NamedKey}; + /// + /// assert_eq!(Key::Character("a".into()).to_text(), Some("a")); + /// assert_eq!(Key::Named(NamedKey::Enter).to_text(), Some("\r")); + /// assert_eq!(Key::Named(NamedKey::F20).to_text(), None); + /// ``` + pub fn to_text(&self) -> Option<&str> { + match self { + Key::Named(action) => action.to_text(), + Key::Character(ch) => Some(ch.as_str()), + _ => None, + } + } +} + +/// The location of the key on the keyboard. +/// +/// Certain physical keys on the keyboard can have the same value, but are in different locations. +/// For instance, the Shift key can be on the left or right side of the keyboard, or the number +/// keys can be above the letters or on the numpad. This enum allows the user to differentiate +/// them. +/// +/// See the documentation for the [`location`] field on the [`KeyEvent`] struct for more +/// information. +/// +/// [`location`]: ../event/struct.KeyEvent.html#structfield.location +/// [`KeyEvent`]: crate::event::KeyEvent +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] +pub enum KeyLocation { + /// The key is in its "normal" location on the keyboard. + /// + /// For instance, the "1" key above the "Q" key on a QWERTY keyboard will use this location. + /// This invariant is also returned when the location of the key cannot be identified. + /// + /// ![Standard 1 key](https://raw.githubusercontent.com/rust-windowing/winit/master/docs/res/keyboard_standard_1_key.svg) + /// + /// <sub> + /// For image attribution, see the + /// <a href="https://github.com/rust-windowing/winit/blob/master/docs/res/ATTRIBUTION.md"> + /// ATTRIBUTION.md + /// </a> + /// file. + /// </sub> + Standard, + + /// The key is on the left side of the keyboard. + /// + /// For instance, the left Shift key below the Caps Lock key on a QWERTY keyboard will use this + /// location. + /// + /// ![Left Shift key](https://raw.githubusercontent.com/rust-windowing/winit/master/docs/res/keyboard_left_shift_key.svg) + /// + /// <sub> + /// For image attribution, see the + /// <a href="https://github.com/rust-windowing/winit/blob/master/docs/res/ATTRIBUTION.md"> + /// ATTRIBUTION.md + /// </a> + /// file. + /// </sub> + Left, + + /// The key is on the right side of the keyboard. + /// + /// For instance, the right Shift key below the Enter key on a QWERTY keyboard will use this + /// location. + /// + /// ![Right Shift key](https://raw.githubusercontent.com/rust-windowing/winit/master/docs/res/keyboard_right_shift_key.svg) + /// + /// <sub> + /// For image attribution, see the + /// <a href="https://github.com/rust-windowing/winit/blob/master/docs/res/ATTRIBUTION.md"> + /// ATTRIBUTION.md + /// </a> + /// file. + /// </sub> + Right, + + /// The key is on the numpad. + /// + /// For instance, the "1" key on the numpad will use this location. + /// + /// ![Numpad 1 key](https://raw.githubusercontent.com/rust-windowing/winit/master/docs/res/keyboard_numpad_1_key.svg) + /// + /// <sub> + /// For image attribution, see the + /// <a href="https://github.com/rust-windowing/winit/blob/master/docs/res/ATTRIBUTION.md"> + /// ATTRIBUTION.md + /// </a> + /// file. + /// </sub> + Numpad, +} + +bitflags! { + /// Represents the current state of the keyboard modifiers + /// + /// Each flag represents a modifier and is set if this modifier is active. + #[derive(Default, Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] + pub struct ModifiersState: u32 { + /// The "shift" key. + const SHIFT = 0b100; + /// The "control" key. + const CONTROL = 0b100 << 3; + /// The "alt" key. + const ALT = 0b100 << 6; + /// This is the "windows" key on PC and "command" key on Mac. + const SUPER = 0b100 << 9; + } +} + +impl ModifiersState { + /// Returns `true` if the shift key is pressed. + pub fn shift_key(&self) -> bool { + self.intersects(Self::SHIFT) + } + + /// Returns `true` if the control key is pressed. + pub fn control_key(&self) -> bool { + self.intersects(Self::CONTROL) + } + + /// Returns `true` if the alt key is pressed. + pub fn alt_key(&self) -> bool { + self.intersects(Self::ALT) + } + + /// Returns `true` if the super key is pressed. + pub fn super_key(&self) -> bool { + self.intersects(Self::SUPER) + } +} + +/// The state of the particular modifiers key. +#[derive(Default, Debug, Clone, Copy, PartialEq, Eq)] +pub enum ModifiersKeyState { + /// The particular key is pressed. + Pressed, + /// The state of the key is unknown. + #[default] + Unknown, +} + +// NOTE: the exact modifier key is not used to represent modifiers state in the +// first place due to a fact that modifiers state could be changed without any +// key being pressed and on some platforms like Wayland/X11 which key resulted +// in modifiers change is hidden, also, not that it really matters. +// +// The reason this API is even exposed is mostly to provide a way for users +// to treat modifiers differently based on their position, which is required +// on macOS due to their AltGr/Option situation. +bitflags! { + #[derive(Default, Debug, Clone, Copy, PartialEq, Eq, Hash)] + pub(crate) struct ModifiersKeys: u8 { + const LSHIFT = 0b0000_0001; + const RSHIFT = 0b0000_0010; + const LCONTROL = 0b0000_0100; + const RCONTROL = 0b0000_1000; + const LALT = 0b0001_0000; + const RALT = 0b0010_0000; + const LSUPER = 0b0100_0000; + const RSUPER = 0b1000_0000; + } +} + +#[cfg(feature = "serde")] +mod modifiers_serde { + use super::ModifiersState; + use serde::{Deserialize, Deserializer, Serialize, Serializer}; + + #[derive(Default, Serialize, Deserialize)] + #[serde(default)] + #[serde(rename = "ModifiersState")] + pub struct ModifiersStateSerialize { + pub shift_key: bool, + pub control_key: bool, + pub alt_key: bool, + pub super_key: bool, + } + + impl Serialize for ModifiersState { + fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> + where + S: Serializer, + { + let s = ModifiersStateSerialize { + shift_key: self.shift_key(), + control_key: self.control_key(), + alt_key: self.alt_key(), + super_key: self.super_key(), + }; + s.serialize(serializer) + } + } + + impl<'de> Deserialize<'de> for ModifiersState { + fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> + where + D: Deserializer<'de>, + { + let ModifiersStateSerialize { shift_key, control_key, alt_key, super_key } = + ModifiersStateSerialize::deserialize(deserializer)?; + let mut m = ModifiersState::empty(); + m.set(ModifiersState::SHIFT, shift_key); + m.set(ModifiersState::CONTROL, control_key); + m.set(ModifiersState::ALT, alt_key); + m.set(ModifiersState::SUPER, super_key); + Ok(m) + } + } +} diff --git a/app/vendor/rune/vendor/winit/src/lib.rs b/app/vendor/rune/vendor/winit/src/lib.rs new file mode 100644 index 0000000..41a55b2 --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/lib.rs @@ -0,0 +1,217 @@ +//! Winit is a cross-platform window creation and event loop management library. +//! +//! # Building windows +//! +//! Before you can create a [`Window`], you first need to build an [`EventLoop`]. This is done with +//! the [`EventLoop::new()`] function. +//! +//! ```no_run +//! use winit::event_loop::EventLoop; +//! +//! # // Intentionally use `fn main` for clarity +//! fn main() { +//! let event_loop = EventLoop::new().unwrap(); +//! // ... +//! } +//! ``` +//! +//! Then you create a [`Window`] with [`create_window`]. +//! +//! # Event handling +//! +//! Once a [`Window`] has been created, it will generate different *events*. A [`Window`] object can +//! generate [`WindowEvent`]s when certain input events occur, such as a cursor moving over the +//! window or a key getting pressed while the window is focused. Devices can generate +//! [`DeviceEvent`]s, which contain unfiltered event data that isn't specific to a certain window. +//! Some user activity, like mouse movement, can generate both a [`WindowEvent`] *and* a +//! [`DeviceEvent`]. You can also create and handle your own custom [`Event::UserEvent`]s, if +//! desired. +//! +//! You can retrieve events by calling [`EventLoop::run_app()`]. This function will +//! dispatch events for every [`Window`] that was created with that particular [`EventLoop`], and +//! will run until [`exit()`] is used, at which point [`Event::LoopExiting`]. +//! +//! Winit no longer uses a `EventLoop::poll_events() -> impl Iterator<Event>`-based event loop +//! model, since that can't be implemented properly on some platforms (e.g web, iOS) and works +//! poorly on most other platforms. However, this model can be re-implemented to an extent with +#![cfg_attr( + any(windows_platform, macos_platform, android_platform, x11_platform, wayland_platform), + doc = "[`EventLoopExtPumpEvents::pump_app_events()`][platform::pump_events::EventLoopExtPumpEvents::pump_app_events()]" +)] +#![cfg_attr( + not(any(windows_platform, macos_platform, android_platform, x11_platform, wayland_platform)), + doc = "`EventLoopExtPumpEvents::pump_app_events()`" +)] +//! [^1]. See that method's documentation for more reasons about why +//! it's discouraged beyond compatibility reasons. +//! +//! +//! ```no_run +//! use winit::application::ApplicationHandler; +//! use winit::event::WindowEvent; +//! use winit::event_loop::{ActiveEventLoop, ControlFlow, EventLoop}; +//! use winit::window::{Window, WindowId}; +//! +//! #[derive(Default)] +//! struct App { +//! window: Option<Window>, +//! } +//! +//! impl ApplicationHandler for App { +//! fn resumed(&mut self, event_loop: &ActiveEventLoop) { +//! self.window = Some(event_loop.create_window(Window::default_attributes()).unwrap()); +//! } +//! +//! fn window_event(&mut self, event_loop: &ActiveEventLoop, id: WindowId, event: WindowEvent) { +//! match event { +//! WindowEvent::CloseRequested => { +//! println!("The close button was pressed; stopping"); +//! event_loop.exit(); +//! }, +//! WindowEvent::RedrawRequested => { +//! // Redraw the application. +//! // +//! // It's preferable for applications that do not render continuously to render in +//! // this event rather than in AboutToWait, since rendering in here allows +//! // the program to gracefully handle redraws requested by the OS. +//! +//! // Draw. +//! +//! // Queue a RedrawRequested event. +//! // +//! // You only need to call this if you've determined that you need to redraw in +//! // applications which do not always need to. Applications that redraw continuously +//! // can render here instead. +//! self.window.as_ref().unwrap().request_redraw(); +//! } +//! _ => (), +//! } +//! } +//! } +//! +//! # // Intentionally use `fn main` for clarity +//! fn main() { +//! let event_loop = EventLoop::new().unwrap(); +//! +//! // ControlFlow::Poll continuously runs the event loop, even if the OS hasn't +//! // dispatched any events. This is ideal for games and similar applications. +//! event_loop.set_control_flow(ControlFlow::Poll); +//! +//! // ControlFlow::Wait pauses the event loop if no events are available to process. +//! // This is ideal for non-game applications that only update in response to user +//! // input, and uses significantly less power/CPU time than ControlFlow::Poll. +//! event_loop.set_control_flow(ControlFlow::Wait); +//! +//! let mut app = App::default(); +//! event_loop.run_app(&mut app); +//! } +//! ``` +//! +//! [`WindowEvent`] has a [`WindowId`] member. In multi-window environments, it should be +//! compared to the value returned by [`Window::id()`] to determine which [`Window`] +//! dispatched the event. +//! +//! # Drawing on the window +//! +//! Winit doesn't directly provide any methods for drawing on a [`Window`]. However, it allows you +//! to retrieve the raw handle of the window and display (see the [`platform`] module and/or the +//! [`raw_window_handle`] and [`raw_display_handle`] methods), which in turn allows +//! you to create an OpenGL/Vulkan/DirectX/Metal/etc. context that can be used to render graphics. +//! +//! Note that many platforms will display garbage data in the window's client area if the +//! application doesn't render anything to the window by the time the desktop compositor is ready to +//! display the window to the user. If you notice this happening, you should create the window with +//! [`visible` set to `false`][crate::window::WindowAttributes::with_visible] and explicitly make +//! the window visible only once you're ready to render into it. +//! +//! # UI scaling +//! +//! UI scaling is important, go read the docs for the [`dpi`] crate for an +//! introduction. +//! +//! All of Winit's functions return physical types, but can take either logical or physical +//! coordinates as input, allowing you to use the most convenient coordinate system for your +//! particular application. +//! +//! Winit will dispatch a [`ScaleFactorChanged`] event whenever a window's scale factor has changed. +//! This can happen if the user drags their window from a standard-resolution monitor to a high-DPI +//! monitor or if the user changes their DPI settings. This allows you to rescale your application's +//! UI elements and adjust how the platform changes the window's size to reflect the new scale +//! factor. If a window hasn't received a [`ScaleFactorChanged`] event, its scale factor +//! can be found by calling [`window.scale_factor()`]. +//! +//! [`ScaleFactorChanged`]: event::WindowEvent::ScaleFactorChanged +//! [`window.scale_factor()`]: window::Window::scale_factor +//! +//! # Cargo Features +//! +//! Winit provides the following Cargo features: +//! +//! * `x11` (enabled by default): On Unix platforms, enables the X11 backend. +//! * `wayland` (enabled by default): On Unix platforms, enables the Wayland backend. +//! * `rwh_04`: Implement `raw-window-handle v0.4` traits. +//! * `rwh_05`: Implement `raw-window-handle v0.5` traits. +//! * `rwh_06`: Implement `raw-window-handle v0.6` traits. +//! * `serde`: Enables serialization/deserialization of certain types with [Serde](https://crates.io/crates/serde). +//! * `mint`: Enables mint (math interoperability standard types) conversions. +//! +//! See the [`platform`] module for documentation on platform-specific cargo +//! features. +//! +//! [`EventLoop`]: event_loop::EventLoop +//! [`EventLoop::new()`]: event_loop::EventLoop::new +//! [`EventLoop::run_app()`]: event_loop::EventLoop::run_app +//! [`exit()`]: event_loop::ActiveEventLoop::exit +//! [`Window`]: window::Window +//! [`WindowId`]: window::WindowId +//! [`WindowAttributes`]: window::WindowAttributes +//! [`create_window`]: event_loop::ActiveEventLoop::create_window +//! [`Window::id()`]: window::Window::id +//! [`WindowEvent`]: event::WindowEvent +//! [`DeviceEvent`]: event::DeviceEvent +//! [`Event::UserEvent`]: event::Event::UserEvent +//! [`Event::LoopExiting`]: event::Event::LoopExiting +//! [`raw_window_handle`]: ./window/struct.Window.html#method.raw_window_handle +//! [`raw_display_handle`]: ./window/struct.Window.html#method.raw_display_handle +//! [^1]: `EventLoopExtPumpEvents::pump_app_events()` is only available on Windows, macOS, Android, X11 and Wayland. + +#![deny(rust_2018_idioms)] +#![deny(rustdoc::broken_intra_doc_links)] +#![deny(clippy::all)] +#![deny(unsafe_op_in_unsafe_fn)] +#![cfg_attr(clippy, deny(warnings))] +// Doc feature labels can be tested locally by running RUSTDOCFLAGS="--cfg=docsrs" cargo +nightly +// doc +#![cfg_attr(docsrs, feature(doc_cfg), doc(auto_cfg(hide(doc, docsrs))))] +#![allow(clippy::missing_safety_doc)] +#![warn(clippy::uninlined_format_args)] +// TODO: wasm-binding needs to be updated for that to be resolved, for now just silence it. +#![cfg_attr(web_platform, allow(unknown_lints, renamed_and_removed_lints, wasm_c_abi))] + +#[cfg(feature = "rwh_04")] +pub use rwh_04 as raw_window_handle_04; +#[cfg(feature = "rwh_05")] +pub use rwh_05 as raw_window_handle_05; +#[cfg(feature = "rwh_06")] +pub use rwh_06 as raw_window_handle; + +// Re-export DPI types so that users don't have to put it in Cargo.toml. +#[doc(inline)] +pub use dpi; + +pub mod application; +#[cfg(any(doc, doctest, test))] +pub mod changelog; +#[macro_use] +pub mod error; +mod cursor; +pub mod event; +pub mod event_loop; +mod icon; +pub mod keyboard; +pub mod monitor; +mod platform_impl; +mod utils; +pub mod window; + +pub mod platform; diff --git a/app/vendor/rune/vendor/winit/src/monitor.rs b/app/vendor/rune/vendor/winit/src/monitor.rs new file mode 100644 index 0000000..ed987e2 --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/monitor.rs @@ -0,0 +1,167 @@ +//! Types useful for interacting with a user's monitors. +//! +//! If you want to get basic information about a monitor, you can use the +//! [`MonitorHandle`] type. This is retrieved from one of the following +//! methods, which return an iterator of [`MonitorHandle`]: +//! - [`ActiveEventLoop::available_monitors`][crate::event_loop::ActiveEventLoop::available_monitors]. +//! - [`Window::available_monitors`][crate::window::Window::available_monitors]. +use crate::dpi::{PhysicalPosition, PhysicalSize}; +use crate::platform_impl; + +/// Deprecated! Use `VideoModeHandle` instead. +#[deprecated = "Renamed to `VideoModeHandle`"] +pub type VideoMode = VideoModeHandle; + +/// Describes a fullscreen video mode of a monitor. +/// +/// Can be acquired with [`MonitorHandle::video_modes`]. +#[derive(Clone, PartialEq, Eq, Hash)] +pub struct VideoModeHandle { + pub(crate) video_mode: platform_impl::VideoModeHandle, +} + +impl std::fmt::Debug for VideoModeHandle { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + self.video_mode.fmt(f) + } +} + +impl PartialOrd for VideoModeHandle { + fn partial_cmp(&self, other: &VideoModeHandle) -> Option<std::cmp::Ordering> { + Some(self.cmp(other)) + } +} + +impl Ord for VideoModeHandle { + fn cmp(&self, other: &VideoModeHandle) -> std::cmp::Ordering { + self.monitor().cmp(&other.monitor()).then( + self.size() + .cmp(&other.size()) + .then( + self.refresh_rate_millihertz() + .cmp(&other.refresh_rate_millihertz()) + .then(self.bit_depth().cmp(&other.bit_depth())), + ) + .reverse(), + ) + } +} + +impl VideoModeHandle { + /// Returns the resolution of this video mode. + #[inline] + pub fn size(&self) -> PhysicalSize<u32> { + self.video_mode.size() + } + + /// Returns the bit depth of this video mode, as in how many bits you have + /// available per color. This is generally 24 bits or 32 bits on modern + /// systems, depending on whether the alpha channel is counted or not. + /// + /// ## Platform-specific + /// + /// - **Wayland / Orbital:** Always returns 32. + /// - **iOS:** Always returns 32. + #[inline] + pub fn bit_depth(&self) -> u16 { + self.video_mode.bit_depth() + } + + /// Returns the refresh rate of this video mode in mHz. + #[inline] + pub fn refresh_rate_millihertz(&self) -> u32 { + self.video_mode.refresh_rate_millihertz() + } + + /// Returns the monitor that this video mode is valid for. Each monitor has + /// a separate set of valid video modes. + #[inline] + pub fn monitor(&self) -> MonitorHandle { + MonitorHandle { inner: self.video_mode.monitor() } + } +} + +impl std::fmt::Display for VideoModeHandle { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!( + f, + "{}x{} @ {} mHz ({} bpp)", + self.size().width, + self.size().height, + self.refresh_rate_millihertz(), + self.bit_depth() + ) + } +} + +/// Handle to a monitor. +/// +/// Allows you to retrieve information about a given monitor and can be used in [`Window`] creation. +/// +/// [`Window`]: crate::window::Window +#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)] +pub struct MonitorHandle { + pub(crate) inner: platform_impl::MonitorHandle, +} + +impl MonitorHandle { + /// Returns a human-readable name of the monitor. + /// + /// Returns `None` if the monitor doesn't exist anymore. + #[inline] + pub fn name(&self) -> Option<String> { + self.inner.name() + } + + /// Returns the monitor's resolution. + #[inline] + pub fn size(&self) -> PhysicalSize<u32> { + self.inner.size() + } + + /// Returns the top-left corner position of the monitor relative to the larger full + /// screen area. + #[inline] + pub fn position(&self) -> PhysicalPosition<i32> { + self.inner.position() + } + + /// The monitor refresh rate used by the system. + /// + /// Return `Some` if succeed, or `None` if failed, which usually happens when the monitor + /// the window is on is removed. + /// + /// When using exclusive fullscreen, the refresh rate of the [`VideoModeHandle`] that was + /// used to enter fullscreen should be used instead. + #[inline] + pub fn refresh_rate_millihertz(&self) -> Option<u32> { + self.inner.refresh_rate_millihertz() + } + + /// Returns the scale factor of the underlying monitor. To map logical pixels to physical + /// pixels and vice versa, use [`Window::scale_factor`]. + /// + /// See the [`dpi`] module for more information. + /// + /// ## Platform-specific + /// + /// - **X11:** Can be overridden using the `WINIT_X11_SCALE_FACTOR` environment variable. + /// - **Wayland:** May differ from [`Window::scale_factor`]. + /// - **Android:** Always returns 1.0. + /// + /// [`Window::scale_factor`]: crate::window::Window::scale_factor + #[inline] + pub fn scale_factor(&self) -> f64 { + self.inner.scale_factor() + } + + /// Returns all fullscreen video modes supported by this monitor. + /// + /// ## Platform-specific + /// + /// - **Web:** Always returns an empty iterator + #[inline] + pub fn video_modes(&self) -> impl Iterator<Item = VideoModeHandle> { + self.inner.video_modes().map(|video_mode| VideoModeHandle { video_mode }) + } +} diff --git a/app/vendor/rune/vendor/winit/src/platform/android.rs b/app/vendor/rune/vendor/winit/src/platform/android.rs new file mode 100644 index 0000000..b76159c --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/platform/android.rs @@ -0,0 +1,188 @@ +//! # Android +//! +//! The Android backend builds on (and exposes types from) the [`ndk`](https://docs.rs/ndk/) crate. +//! +//! Native Android applications need some form of "glue" crate that is responsible +//! for defining the main entry point for your Rust application as well as tracking +//! various life-cycle events and synchronizing with the main JVM thread. +//! +//! Winit uses the [android-activity](https://docs.rs/android-activity/) as a +//! glue crate (prior to `0.28` it used +//! [ndk-glue](https://github.com/rust-windowing/android-ndk-rs/tree/master/ndk-glue)). +//! +//! The version of the glue crate that your application depends on _must_ match the +//! version that Winit depends on because the glue crate is responsible for your +//! application's main entry point. If Cargo resolves multiple versions, they will +//! clash. +//! +//! `winit` glue compatibility table: +//! +//! | winit | ndk-glue | +//! | :---: | :--------------------------: | +//! | 0.30 | `android-activity = "0.6"` | +//! | 0.29 | `android-activity = "0.5"` | +//! | 0.28 | `android-activity = "0.4"` | +//! | 0.27 | `ndk-glue = "0.7"` | +//! | 0.26 | `ndk-glue = "0.5"` | +//! | 0.25 | `ndk-glue = "0.3"` | +//! | 0.24 | `ndk-glue = "0.2"` | +//! +//! The recommended way to avoid a conflict with the glue version is to avoid explicitly +//! depending on the `android-activity` crate, and instead consume the API that +//! is re-exported by Winit under `winit::platform::android::activity::*` +//! +//! Running on an Android device needs a dynamic system library. Add this to Cargo.toml: +//! +//! ```toml +//! [lib] +//! name = "main" +//! crate-type = ["cdylib"] +//! ``` +//! +//! All Android applications are based on an `Activity` subclass, and the +//! `android-activity` crate is designed to support different choices for this base +//! class. Your application _must_ specify the base class it needs via a feature flag: +//! +//! | Base Class | Feature Flag | Notes | +//! | :--------------: | :---------------: | :-----: | +//! | `NativeActivity` | `android-native-activity` | Built-in to Android - it is possible to use without compiling any Java or Kotlin code. Java or Kotlin code may be needed to subclass `NativeActivity` to access some platform features. It does not derive from the [`AndroidAppCompat`] base class.| +//! | [`GameActivity`] | `android-game-activity` | Derives from [`AndroidAppCompat`], a defacto standard `Activity` base class that helps support a wider range of Android versions. Requires a build system that can compile Java or Kotlin and fetch Android dependencies from a [Maven repository][agdk_jetpack] (or link with an embedded [release][agdk_releases] of [`GameActivity`]) | +//! +//! [`GameActivity`]: https://developer.android.com/games/agdk/game-activity +//! [`GameTextInput`]: https://developer.android.com/games/agdk/add-support-for-text-input +//! [`AndroidAppCompat`]: https://developer.android.com/reference/androidx/appcompat/app/AppCompatActivity +//! [agdk_jetpack]: https://developer.android.com/jetpack/androidx/releases/games +//! [agdk_releases]: https://developer.android.com/games/agdk/download#agdk-libraries +//! [Gradle]: https://developer.android.com/studio/build +//! +//! For more details, refer to these `android-activity` [example applications](https://github.com/rust-mobile/android-activity/tree/main/examples). +//! +//! ## Converting from `ndk-glue` to `android-activity` +//! +//! If your application is currently based on `NativeActivity` via the `ndk-glue` crate and building +//! with `cargo apk`, then the minimal changes would be: +//! 1. Remove `ndk-glue` from your `Cargo.toml` +//! 2. Enable the `"android-native-activity"` feature for Winit: `winit = { version = "0.30.13", +//! features = [ "android-native-activity" ] }` +//! 3. Add an `android_main` entrypoint (as above), instead of using the '`[ndk_glue::main]` proc +//! macro from `ndk-macros` (optionally add a dependency on `android_logger` and initialize +//! logging as above). +//! 4. Pass a clone of the `AndroidApp` that your application receives to Winit when building your +//! event loop (as shown above). + +use crate::event_loop::{ActiveEventLoop, EventLoop, EventLoopBuilder}; +use crate::window::{Window, WindowAttributes}; + +use self::activity::{AndroidApp, ConfigurationRef, Rect}; + +/// Additional methods on [`EventLoop`] that are specific to Android. +pub trait EventLoopExtAndroid { + /// Get the [`AndroidApp`] which was used to create this event loop. + fn android_app(&self) -> &AndroidApp; +} + +impl<T> EventLoopExtAndroid for EventLoop<T> { + fn android_app(&self) -> &AndroidApp { + &self.event_loop.android_app + } +} + +/// Additional methods on [`ActiveEventLoop`] that are specific to Android. +pub trait ActiveEventLoopExtAndroid { + /// Get the [`AndroidApp`] which was used to create this event loop. + fn android_app(&self) -> &AndroidApp; +} + +/// Additional methods on [`Window`] that are specific to Android. +pub trait WindowExtAndroid { + fn content_rect(&self) -> Rect; + + fn config(&self) -> ConfigurationRef; +} + +impl WindowExtAndroid for Window { + fn content_rect(&self) -> Rect { + self.window.content_rect() + } + + fn config(&self) -> ConfigurationRef { + self.window.config() + } +} + +impl ActiveEventLoopExtAndroid for ActiveEventLoop { + fn android_app(&self) -> &AndroidApp { + &self.p.app + } +} + +/// Additional methods on [`WindowAttributes`] that are specific to Android. +pub trait WindowAttributesExtAndroid {} + +impl WindowAttributesExtAndroid for WindowAttributes {} + +pub trait EventLoopBuilderExtAndroid { + /// Associates the [`AndroidApp`] that was passed to `android_main()` with the event loop + /// + /// This must be called on Android since the [`AndroidApp`] is not global state. + fn with_android_app(&mut self, app: AndroidApp) -> &mut Self; + + /// Calling this will mark the volume keys to be manually handled by the application + /// + /// Default is to let the operating system handle the volume keys + fn handle_volume_keys(&mut self) -> &mut Self; +} + +impl<T> EventLoopBuilderExtAndroid for EventLoopBuilder<T> { + fn with_android_app(&mut self, app: AndroidApp) -> &mut Self { + self.platform_specific.android_app = Some(app); + self + } + + fn handle_volume_keys(&mut self) -> &mut Self { + self.platform_specific.ignore_volume_keys = false; + self + } +} + +/// Re-export of the `android_activity` API +/// +/// Winit re-exports the `android_activity` API for convenience so that most +/// applications can rely on the Winit crate to resolve the required version of +/// `android_activity` and avoid any chance of a conflict between Winit and the +/// application crate. +/// +/// Unlike most libraries there can only be a single implementation +/// of the `android_activity` glue crate linked with an application because +/// it is responsible for the application's `android_main()` entry point. +/// +/// Since Winit depends on a specific version of `android_activity` the simplest +/// way to avoid creating a conflict is for applications to avoid explicitly +/// depending on the `android_activity` crate, and instead consume the API that +/// is re-exported by Winit. +/// +/// For compatibility applications should then import the [`AndroidApp`] type for +/// their `android_main(app: AndroidApp)` function like: +/// ```rust +/// #[cfg(target_os = "android")] +/// use winit::platform::android::activity::AndroidApp; +/// ``` +pub mod activity { + // We enable the `"native-activity"` feature just so that we can build the + // docs, but it'll be very confusing for users to see the docs with that + // feature enabled, so we avoid inlining it so that they're forced to view + // it on the crate's own docs.rs page. + #[doc(no_inline)] + #[cfg(android_platform)] + pub use android_activity::*; + + #[cfg(not(android_platform))] + #[doc(hidden)] + pub struct Rect; + #[cfg(not(android_platform))] + #[doc(hidden)] + pub struct ConfigurationRef; + #[cfg(not(android_platform))] + #[doc(hidden)] + pub struct AndroidApp; +} diff --git a/app/vendor/rune/vendor/winit/src/platform/ios.rs b/app/vendor/rune/vendor/winit/src/platform/ios.rs new file mode 100644 index 0000000..6e62876 --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/platform/ios.rs @@ -0,0 +1,435 @@ +//! # iOS / UIKit +//! +//! Winit has an OS requirement of iOS 8 or higher, and is regularly tested on +//! iOS 9.3. +//! +//! ## Window initialization +//! +//! iOS's main `UIApplicationMain` does some init work that's required by all +//! UI-related code (see issue [#1705]). It is best to create your windows +//! inside [`ApplicationHandler::resumed`]. +//! +//! [#1705]: https://github.com/rust-windowing/winit/issues/1705 +//! [`ApplicationHandler::resumed`]: crate::application::ApplicationHandler::resumed +//! +//! ## Building app +//! +//! To build ios app you will need rustc built for this targets: +//! +//! - armv7-apple-ios +//! - armv7s-apple-ios +//! - i386-apple-ios +//! - aarch64-apple-ios +//! - x86_64-apple-ios +//! +//! Then +//! +//! ``` +//! cargo build --target=... +//! ``` +//! The simplest way to integrate your app into xcode environment is to build it +//! as a static library. Wrap your main function and export it. +//! +//! ```rust, ignore +//! #[no_mangle] +//! pub extern fn start_winit_app() { +//! start_inner() +//! } +//! +//! fn start_inner() { +//! ... +//! } +//! ``` +//! +//! Compile project and then drag resulting .a into Xcode project. Add winit.h to xcode. +//! +//! ```ignore +//! void start_winit_app(); +//! ``` +//! +//! Use start_winit_app inside your xcode's main function. +//! +//! +//! ## App lifecycle and events +//! +//! iOS environment is very different from other platforms and you must be very +//! careful with it's events. Familiarize yourself with +//! [app lifecycle](https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIApplicationDelegate_Protocol/). +//! +//! This is how those event are represented in winit: +//! +//! - applicationDidBecomeActive is Resumed +//! - applicationWillResignActive is Suspended +//! - applicationWillTerminate is LoopExiting +//! +//! Keep in mind that after LoopExiting event is received every attempt to draw with +//! opengl will result in segfault. +//! +//! Also note that app may not receive the LoopExiting event if suspended; it might be SIGKILL'ed. +//! +//! ## Custom `UIApplicationDelegate` +//! +//! Winit usually handles everything related to the lifecycle events of the application. Sometimes, +//! though, you might want to access some of the more niche stuff that [the application +//! delegate][app-delegate] provides. This functionality is not exposed directly in Winit, since it +//! would increase the API surface by quite a lot. Instead, Winit guarantees that it will not +//! register an application delegate, so you can set up a custom one in a nib file instead. +//! +//! [app-delegate]: https://developer.apple.com/documentation/uikit/uiapplicationdelegate?language=objc + +use std::os::raw::c_void; + +use crate::event_loop::EventLoop; +use crate::monitor::{MonitorHandle, VideoModeHandle}; +use crate::window::{Window, WindowAttributes}; + +/// Additional methods on [`EventLoop`] that are specific to iOS. +pub trait EventLoopExtIOS { + /// Returns the [`Idiom`] (phone/tablet/tv/etc) for the current device. + fn idiom(&self) -> Idiom; +} + +impl<T: 'static> EventLoopExtIOS for EventLoop<T> { + fn idiom(&self) -> Idiom { + self.event_loop.idiom() + } +} + +/// Additional methods on [`Window`] that are specific to iOS. +pub trait WindowExtIOS { + /// Sets the [`contentScaleFactor`] of the underlying [`UIWindow`] to `scale_factor`. + /// + /// The default value is device dependent, and it's recommended GLES or Metal applications set + /// this to [`MonitorHandle::scale_factor()`]. + /// + /// [`UIWindow`]: https://developer.apple.com/documentation/uikit/uiwindow?language=objc + /// [`contentScaleFactor`]: https://developer.apple.com/documentation/uikit/uiview/1622657-contentscalefactor?language=objc + fn set_scale_factor(&self, scale_factor: f64); + + /// Sets the valid orientations for the [`Window`]. + /// + /// The default value is [`ValidOrientations::LandscapeAndPortrait`]. + /// + /// This changes the value returned by + /// [`-[UIViewController supportedInterfaceOrientations]`](https://developer.apple.com/documentation/uikit/uiviewcontroller/1621435-supportedinterfaceorientations?language=objc), + /// and then calls + /// [`-[UIViewController attemptRotationToDeviceOrientation]`](https://developer.apple.com/documentation/uikit/uiviewcontroller/1621400-attemptrotationtodeviceorientati?language=objc). + fn set_valid_orientations(&self, valid_orientations: ValidOrientations); + + /// Sets whether the [`Window`] prefers the home indicator hidden. + /// + /// The default is to prefer showing the home indicator. + /// + /// This changes the value returned by + /// [`-[UIViewController prefersHomeIndicatorAutoHidden]`](https://developer.apple.com/documentation/uikit/uiviewcontroller/2887510-prefershomeindicatorautohidden?language=objc), + /// and then calls + /// [`-[UIViewController setNeedsUpdateOfHomeIndicatorAutoHidden]`](https://developer.apple.com/documentation/uikit/uiviewcontroller/2887509-setneedsupdateofhomeindicatoraut?language=objc). + /// + /// This only has an effect on iOS 11.0+. + fn set_prefers_home_indicator_hidden(&self, hidden: bool); + + /// Sets the screen edges for which the system gestures will take a lower priority than the + /// application's touch handling. + /// + /// This changes the value returned by + /// [`-[UIViewController preferredScreenEdgesDeferringSystemGestures]`](https://developer.apple.com/documentation/uikit/uiviewcontroller/2887512-preferredscreenedgesdeferringsys?language=objc), + /// and then calls + /// [`-[UIViewController setNeedsUpdateOfScreenEdgesDeferringSystemGestures]`](https://developer.apple.com/documentation/uikit/uiviewcontroller/2887507-setneedsupdateofscreenedgesdefer?language=objc). + /// + /// This only has an effect on iOS 11.0+. + fn set_preferred_screen_edges_deferring_system_gestures(&self, edges: ScreenEdge); + + /// Sets whether the [`Window`] prefers the status bar hidden. + /// + /// The default is to prefer showing the status bar. + /// + /// This sets the value of the + /// [`prefersStatusBarHidden`](https://developer.apple.com/documentation/uikit/uiviewcontroller/1621440-prefersstatusbarhidden?language=objc) + /// property. + /// + /// [`setNeedsStatusBarAppearanceUpdate()`](https://developer.apple.com/documentation/uikit/uiviewcontroller/1621354-setneedsstatusbarappearanceupdat?language=objc) + /// is also called for you. + fn set_prefers_status_bar_hidden(&self, hidden: bool); + + /// Sets the preferred status bar style for the [`Window`]. + /// + /// The default is system-defined. + /// + /// This sets the value of the + /// [`preferredStatusBarStyle`](https://developer.apple.com/documentation/uikit/uiviewcontroller/1621416-preferredstatusbarstyle?language=objc) + /// property. + /// + /// [`setNeedsStatusBarAppearanceUpdate()`](https://developer.apple.com/documentation/uikit/uiviewcontroller/1621354-setneedsstatusbarappearanceupdat?language=objc) + /// is also called for you. + fn set_preferred_status_bar_style(&self, status_bar_style: StatusBarStyle); + + /// Sets whether the [`Window`] should recognize pinch gestures. + /// + /// The default is to not recognize gestures. + fn recognize_pinch_gesture(&self, should_recognize: bool); + + /// Sets whether the [`Window`] should recognize pan gestures. + /// + /// The default is to not recognize gestures. + /// Installs [`UIPanGestureRecognizer`](https://developer.apple.com/documentation/uikit/uipangesturerecognizer) onto view + /// + /// Set the minimum number of touches required: [`minimumNumberOfTouches`](https://developer.apple.com/documentation/uikit/uipangesturerecognizer/1621208-minimumnumberoftouches) + /// + /// Set the maximum number of touches recognized: [`maximumNumberOfTouches`](https://developer.apple.com/documentation/uikit/uipangesturerecognizer/1621208-maximumnumberoftouches) + fn recognize_pan_gesture( + &self, + should_recognize: bool, + minimum_number_of_touches: u8, + maximum_number_of_touches: u8, + ); + + /// Sets whether the [`Window`] should recognize double tap gestures. + /// + /// The default is to not recognize gestures. + fn recognize_doubletap_gesture(&self, should_recognize: bool); + + /// Sets whether the [`Window`] should recognize rotation gestures. + /// + /// The default is to not recognize gestures. + fn recognize_rotation_gesture(&self, should_recognize: bool); +} + +impl WindowExtIOS for Window { + #[inline] + fn set_scale_factor(&self, scale_factor: f64) { + self.window.maybe_queue_on_main(move |w| w.set_scale_factor(scale_factor)) + } + + #[inline] + fn set_valid_orientations(&self, valid_orientations: ValidOrientations) { + self.window.maybe_queue_on_main(move |w| w.set_valid_orientations(valid_orientations)) + } + + #[inline] + fn set_prefers_home_indicator_hidden(&self, hidden: bool) { + self.window.maybe_queue_on_main(move |w| w.set_prefers_home_indicator_hidden(hidden)) + } + + #[inline] + fn set_preferred_screen_edges_deferring_system_gestures(&self, edges: ScreenEdge) { + self.window.maybe_queue_on_main(move |w| { + w.set_preferred_screen_edges_deferring_system_gestures(edges) + }) + } + + #[inline] + fn set_prefers_status_bar_hidden(&self, hidden: bool) { + self.window.maybe_queue_on_main(move |w| w.set_prefers_status_bar_hidden(hidden)) + } + + #[inline] + fn set_preferred_status_bar_style(&self, status_bar_style: StatusBarStyle) { + self.window.maybe_queue_on_main(move |w| w.set_preferred_status_bar_style(status_bar_style)) + } + + #[inline] + fn recognize_pinch_gesture(&self, should_recognize: bool) { + self.window.maybe_queue_on_main(move |w| w.recognize_pinch_gesture(should_recognize)); + } + + #[inline] + fn recognize_pan_gesture( + &self, + should_recognize: bool, + minimum_number_of_touches: u8, + maximum_number_of_touches: u8, + ) { + self.window.maybe_queue_on_main(move |w| { + w.recognize_pan_gesture( + should_recognize, + minimum_number_of_touches, + maximum_number_of_touches, + ) + }); + } + + #[inline] + fn recognize_doubletap_gesture(&self, should_recognize: bool) { + self.window.maybe_queue_on_main(move |w| w.recognize_doubletap_gesture(should_recognize)); + } + + #[inline] + fn recognize_rotation_gesture(&self, should_recognize: bool) { + self.window.maybe_queue_on_main(move |w| w.recognize_rotation_gesture(should_recognize)); + } +} + +/// Additional methods on [`WindowAttributes`] that are specific to iOS. +pub trait WindowAttributesExtIOS { + /// Sets the [`contentScaleFactor`] of the underlying [`UIWindow`] to `scale_factor`. + /// + /// The default value is device dependent, and it's recommended GLES or Metal applications set + /// this to [`MonitorHandle::scale_factor()`]. + /// + /// [`UIWindow`]: https://developer.apple.com/documentation/uikit/uiwindow?language=objc + /// [`contentScaleFactor`]: https://developer.apple.com/documentation/uikit/uiview/1622657-contentscalefactor?language=objc + fn with_scale_factor(self, scale_factor: f64) -> Self; + + /// Sets the valid orientations for the [`Window`]. + /// + /// The default value is [`ValidOrientations::LandscapeAndPortrait`]. + /// + /// This sets the initial value returned by + /// [`-[UIViewController supportedInterfaceOrientations]`](https://developer.apple.com/documentation/uikit/uiviewcontroller/1621435-supportedinterfaceorientations?language=objc). + fn with_valid_orientations(self, valid_orientations: ValidOrientations) -> Self; + + /// Sets whether the [`Window`] prefers the home indicator hidden. + /// + /// The default is to prefer showing the home indicator. + /// + /// This sets the initial value returned by + /// [`-[UIViewController prefersHomeIndicatorAutoHidden]`](https://developer.apple.com/documentation/uikit/uiviewcontroller/2887510-prefershomeindicatorautohidden?language=objc). + /// + /// This only has an effect on iOS 11.0+. + fn with_prefers_home_indicator_hidden(self, hidden: bool) -> Self; + + /// Sets the screen edges for which the system gestures will take a lower priority than the + /// application's touch handling. + /// + /// This sets the initial value returned by + /// [`-[UIViewController preferredScreenEdgesDeferringSystemGestures]`](https://developer.apple.com/documentation/uikit/uiviewcontroller/2887512-preferredscreenedgesdeferringsys?language=objc). + /// + /// This only has an effect on iOS 11.0+. + fn with_preferred_screen_edges_deferring_system_gestures(self, edges: ScreenEdge) -> Self; + + /// Sets whether the [`Window`] prefers the status bar hidden. + /// + /// The default is to prefer showing the status bar. + /// + /// This sets the initial value returned by + /// [`-[UIViewController prefersStatusBarHidden]`](https://developer.apple.com/documentation/uikit/uiviewcontroller/1621440-prefersstatusbarhidden?language=objc). + fn with_prefers_status_bar_hidden(self, hidden: bool) -> Self; + + /// Sets the style of the [`Window`]'s status bar. + /// + /// The default is system-defined. + /// + /// This sets the initial value returned by + /// [`-[UIViewController preferredStatusBarStyle]`](https://developer.apple.com/documentation/uikit/uiviewcontroller/1621416-preferredstatusbarstyle?language=objc), + fn with_preferred_status_bar_style(self, status_bar_style: StatusBarStyle) -> Self; +} + +impl WindowAttributesExtIOS for WindowAttributes { + #[inline] + fn with_scale_factor(mut self, scale_factor: f64) -> Self { + self.platform_specific.scale_factor = Some(scale_factor); + self + } + + #[inline] + fn with_valid_orientations(mut self, valid_orientations: ValidOrientations) -> Self { + self.platform_specific.valid_orientations = valid_orientations; + self + } + + #[inline] + fn with_prefers_home_indicator_hidden(mut self, hidden: bool) -> Self { + self.platform_specific.prefers_home_indicator_hidden = hidden; + self + } + + #[inline] + fn with_preferred_screen_edges_deferring_system_gestures(mut self, edges: ScreenEdge) -> Self { + self.platform_specific.preferred_screen_edges_deferring_system_gestures = edges; + self + } + + #[inline] + fn with_prefers_status_bar_hidden(mut self, hidden: bool) -> Self { + self.platform_specific.prefers_status_bar_hidden = hidden; + self + } + + #[inline] + fn with_preferred_status_bar_style(mut self, status_bar_style: StatusBarStyle) -> Self { + self.platform_specific.preferred_status_bar_style = status_bar_style; + self + } +} + +/// Additional methods on [`MonitorHandle`] that are specific to iOS. +pub trait MonitorHandleExtIOS { + /// Returns a pointer to the [`UIScreen`] that is used by this monitor. + /// + /// [`UIScreen`]: https://developer.apple.com/documentation/uikit/uiscreen?language=objc + fn ui_screen(&self) -> *mut c_void; + + /// Returns the preferred [`VideoModeHandle`] for this monitor. + /// + /// This translates to a call to [`-[UIScreen preferredMode]`](https://developer.apple.com/documentation/uikit/uiscreen/1617823-preferredmode?language=objc). + fn preferred_video_mode(&self) -> VideoModeHandle; +} + +impl MonitorHandleExtIOS for MonitorHandle { + #[inline] + fn ui_screen(&self) -> *mut c_void { + // SAFETY: The marker is only used to get the pointer of the screen + let mtm = unsafe { objc2_foundation::MainThreadMarker::new_unchecked() }; + objc2::rc::Retained::as_ptr(self.inner.ui_screen(mtm)) as *mut c_void + } + + #[inline] + fn preferred_video_mode(&self) -> VideoModeHandle { + VideoModeHandle { video_mode: self.inner.preferred_video_mode() } + } +} + +/// Valid orientations for a particular [`Window`]. +#[derive(Default, Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum ValidOrientations { + /// Excludes `PortraitUpsideDown` on iphone + #[default] + LandscapeAndPortrait, + + Landscape, + + /// Excludes `PortraitUpsideDown` on iphone + Portrait, +} + +/// The device [idiom]. +/// +/// [idiom]: https://developer.apple.com/documentation/uikit/uidevice/1620037-userinterfaceidiom?language=objc +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum Idiom { + Unspecified, + + /// iPhone and iPod touch. + Phone, + + /// iPad. + Pad, + + /// tvOS and Apple TV. + TV, + CarPlay, +} + +bitflags::bitflags! { + /// The [edges] of a screen. + /// + /// [edges]: https://developer.apple.com/documentation/uikit/uirectedge?language=objc + #[derive(Default, Debug, Clone, Copy, PartialEq, Eq, Hash)] + pub struct ScreenEdge: u8 { + const NONE = 0; + const TOP = 1 << 0; + const LEFT = 1 << 1; + const BOTTOM = 1 << 2; + const RIGHT = 1 << 3; + const ALL = ScreenEdge::TOP.bits() | ScreenEdge::LEFT.bits() + | ScreenEdge::BOTTOM.bits() | ScreenEdge::RIGHT.bits(); + } +} + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum StatusBarStyle { + #[default] + Default, + LightContent, + DarkContent, +} diff --git a/app/vendor/rune/vendor/winit/src/platform/macos.rs b/app/vendor/rune/vendor/winit/src/platform/macos.rs new file mode 100644 index 0000000..943e97b --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/platform/macos.rs @@ -0,0 +1,553 @@ +//! # macOS / AppKit +//! +//! Winit has an OS requirement of macOS 10.11 or higher (same as Rust +//! itself), and is regularly tested on macOS 10.14. +//! +//! ## Window initialization +//! +//! A lot of functionality expects the application to be ready before you +//! start doing anything; this includes creating windows, fetching monitors, +//! drawing, and so on, see issues [#2238], [#2051] and [#2087]. +//! +//! If you encounter problems, you should try doing your initialization inside +//! [`ApplicationHandler::resumed`]. +//! +//! [#2238]: https://github.com/rust-windowing/winit/issues/2238 +//! [#2051]: https://github.com/rust-windowing/winit/issues/2051 +//! [#2087]: https://github.com/rust-windowing/winit/issues/2087 +//! [`ApplicationHandler::resumed`]: crate::application::ApplicationHandler::resumed +//! +//! ## Custom `NSApplicationDelegate` +//! +//! Winit usually handles everything related to the lifecycle events of the application. Sometimes, +//! though, you might want to do more niche stuff, such as [handle when the user re-activates the +//! application][reopen]. Such functionality is not exposed directly in Winit, since it would +//! increase the API surface by quite a lot. +//! +//! [reopen]: https://developer.apple.com/documentation/appkit/nsapplicationdelegate/1428638-applicationshouldhandlereopen?language=objc +//! +//! Instead, Winit guarantees that it will not register an application delegate, so the solution is +//! to register your own application delegate, as outlined in the following example (see +//! `objc2-app-kit` for more detailed information). +#![cfg_attr(target_os = "macos", doc = "```")] +#![cfg_attr(not(target_os = "macos"), doc = "```ignore")] +//! use objc2::rc::Retained; +//! use objc2::runtime::ProtocolObject; +//! use objc2::{declare_class, msg_send_id, mutability, ClassType, DeclaredClass}; +//! use objc2_app_kit::{NSApplication, NSApplicationDelegate}; +//! use objc2_foundation::{NSArray, NSURL, MainThreadMarker, NSObject, NSObjectProtocol}; +//! use winit::event_loop::EventLoop; +//! +//! declare_class!( +//! struct AppDelegate; +//! +//! unsafe impl ClassType for AppDelegate { +//! type Super = NSObject; +//! type Mutability = mutability::MainThreadOnly; +//! const NAME: &'static str = "MyAppDelegate"; +//! } +//! +//! impl DeclaredClass for AppDelegate {} +//! +//! unsafe impl NSObjectProtocol for AppDelegate {} +//! +//! unsafe impl NSApplicationDelegate for AppDelegate { +//! #[method(application:openURLs:)] +//! fn application_openURLs(&self, application: &NSApplication, urls: &NSArray<NSURL>) { +//! // Note: To specifically get `application:openURLs:` to work, you _might_ +//! // have to bundle your application. This is not done in this example. +//! println!("open urls: {application:?}, {urls:?}"); +//! } +//! } +//! ); +//! +//! impl AppDelegate { +//! fn new(mtm: MainThreadMarker) -> Retained<Self> { +//! unsafe { msg_send_id![super(mtm.alloc().set_ivars(())), init] } +//! } +//! } +//! +//! fn main() -> Result<(), Box<dyn std::error::Error>> { +//! let event_loop = EventLoop::new()?; +//! +//! let mtm = MainThreadMarker::new().unwrap(); +//! let delegate = AppDelegate::new(mtm); +//! // Important: Call `sharedApplication` after `EventLoop::new`, +//! // doing it before is not yet supported. +//! let app = NSApplication::sharedApplication(mtm); +//! app.setDelegate(Some(ProtocolObject::from_ref(&*delegate))); +//! +//! // event_loop.run_app(&mut my_app); +//! Ok(()) +//! } +//! ``` + +use std::os::raw::c_void; + +#[cfg(feature = "serde")] +use serde::{Deserialize, Serialize}; + +use crate::event_loop::{ActiveEventLoop, EventLoopBuilder}; +use crate::monitor::MonitorHandle; +use crate::window::{Window, WindowAttributes}; + +/// Additional methods on [`Window`] that are specific to MacOS. +pub trait WindowExtMacOS { + /// Returns whether or not the window is in simple fullscreen mode. + fn simple_fullscreen(&self) -> bool; + + /// Toggles a fullscreen mode that doesn't require a new macOS space. + /// Returns a boolean indicating whether the transition was successful (this + /// won't work if the window was already in the native fullscreen). + /// + /// This is how fullscreen used to work on macOS in versions before Lion. + /// And allows the user to have a fullscreen window without using another + /// space or taking control over the entire monitor. + fn set_simple_fullscreen(&self, fullscreen: bool) -> bool; + + /// Returns whether or not the window has shadow. + fn has_shadow(&self) -> bool; + + /// Sets whether or not the window has shadow. + fn set_has_shadow(&self, has_shadow: bool); + + /// Group windows together by using the same tabbing identifier. + /// + /// <https://developer.apple.com/documentation/appkit/nswindow/1644704-tabbingidentifier> + fn set_tabbing_identifier(&self, identifier: &str); + + /// Returns the window's tabbing identifier. + fn tabbing_identifier(&self) -> String; + + /// Select next tab. + fn select_next_tab(&self); + + /// Select previous tab. + fn select_previous_tab(&self); + + /// Select the tab with the given index. + /// + /// Will no-op when the index is out of bounds. + fn select_tab_at_index(&self, index: usize); + + /// Get the number of tabs in the window tab group. + fn num_tabs(&self) -> usize; + + /// Get the window's edit state. + /// + /// # Examples + /// + /// ```ignore + /// WindowEvent::CloseRequested => { + /// if window.is_document_edited() { + /// // Show the user a save pop-up or similar + /// } else { + /// // Close the window + /// drop(window); + /// } + /// } + /// ``` + fn is_document_edited(&self) -> bool; + + /// Put the window in a state which indicates a file save is required. + fn set_document_edited(&self, edited: bool); + + /// Set option as alt behavior as described in [`OptionAsAlt`]. + /// + /// This will ignore diacritical marks and accent characters from + /// being processed as received characters. Instead, the input + /// device's raw character will be placed in event queues with the + /// Alt modifier set. + fn set_option_as_alt(&self, option_as_alt: OptionAsAlt); + + /// Getter for the [`WindowExtMacOS::set_option_as_alt`]. + fn option_as_alt(&self) -> OptionAsAlt; + + /// Disable the Menu Bar and Dock in Simple or Borderless Fullscreen mode. Useful for games. + /// The effect is applied when [`WindowExtMacOS::set_simple_fullscreen`] or + /// [`Window::set_fullscreen`] is called. + fn set_borderless_game(&self, borderless_game: bool); + + /// Getter for the [`WindowExtMacOS::set_borderless_game`]. + fn is_borderless_game(&self) -> bool; +} + +impl WindowExtMacOS for Window { + #[inline] + fn simple_fullscreen(&self) -> bool { + self.window.maybe_wait_on_main(|w| w.simple_fullscreen()) + } + + #[inline] + fn set_simple_fullscreen(&self, fullscreen: bool) -> bool { + self.window.maybe_wait_on_main(move |w| w.set_simple_fullscreen(fullscreen)) + } + + #[inline] + fn has_shadow(&self) -> bool { + self.window.maybe_wait_on_main(|w| w.has_shadow()) + } + + #[inline] + fn set_has_shadow(&self, has_shadow: bool) { + self.window.maybe_queue_on_main(move |w| w.set_has_shadow(has_shadow)) + } + + #[inline] + fn set_tabbing_identifier(&self, identifier: &str) { + self.window.maybe_wait_on_main(|w| w.set_tabbing_identifier(identifier)) + } + + #[inline] + fn tabbing_identifier(&self) -> String { + self.window.maybe_wait_on_main(|w| w.tabbing_identifier()) + } + + #[inline] + fn select_next_tab(&self) { + self.window.maybe_queue_on_main(|w| w.select_next_tab()) + } + + #[inline] + fn select_previous_tab(&self) { + self.window.maybe_queue_on_main(|w| w.select_previous_tab()) + } + + #[inline] + fn select_tab_at_index(&self, index: usize) { + self.window.maybe_queue_on_main(move |w| w.select_tab_at_index(index)) + } + + #[inline] + fn num_tabs(&self) -> usize { + self.window.maybe_wait_on_main(|w| w.num_tabs()) + } + + #[inline] + fn is_document_edited(&self) -> bool { + self.window.maybe_wait_on_main(|w| w.is_document_edited()) + } + + #[inline] + fn set_document_edited(&self, edited: bool) { + self.window.maybe_queue_on_main(move |w| w.set_document_edited(edited)) + } + + #[inline] + fn set_option_as_alt(&self, option_as_alt: OptionAsAlt) { + self.window.maybe_queue_on_main(move |w| w.set_option_as_alt(option_as_alt)) + } + + #[inline] + fn option_as_alt(&self) -> OptionAsAlt { + self.window.maybe_wait_on_main(|w| w.option_as_alt()) + } + + #[inline] + fn set_borderless_game(&self, borderless_game: bool) { + self.window.maybe_wait_on_main(|w| w.set_borderless_game(borderless_game)) + } + + #[inline] + fn is_borderless_game(&self) -> bool { + self.window.maybe_wait_on_main(|w| w.is_borderless_game()) + } +} + +/// Corresponds to `NSApplicationActivationPolicy`. +#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)] +pub enum ActivationPolicy { + /// Corresponds to `NSApplicationActivationPolicyRegular`. + #[default] + Regular, + + /// Corresponds to `NSApplicationActivationPolicyAccessory`. + Accessory, + + /// Corresponds to `NSApplicationActivationPolicyProhibited`. + Prohibited, +} + +/// Additional methods on [`WindowAttributes`] that are specific to MacOS. +/// +/// **Note:** Properties dealing with the titlebar will be overwritten by the +/// [`WindowAttributes::with_decorations`] method: +/// - `with_titlebar_transparent` +/// - `with_title_hidden` +/// - `with_titlebar_hidden` +/// - `with_titlebar_buttons_hidden` +/// - `with_fullsize_content_view` +pub trait WindowAttributesExtMacOS { + /// Enables click-and-drag behavior for the entire window, not just the titlebar. + fn with_movable_by_window_background(self, movable_by_window_background: bool) -> Self; + /// Makes the titlebar transparent and allows the content to appear behind it. + fn with_titlebar_transparent(self, titlebar_transparent: bool) -> Self; + /// Hides the window title. + fn with_title_hidden(self, title_hidden: bool) -> Self; + /// Hides the window titlebar. + fn with_titlebar_hidden(self, titlebar_hidden: bool) -> Self; + /// Hides the window titlebar buttons. + fn with_titlebar_buttons_hidden(self, titlebar_buttons_hidden: bool) -> Self; + /// Makes the window content appear behind the titlebar. + fn with_fullsize_content_view(self, fullsize_content_view: bool) -> Self; + fn with_disallow_hidpi(self, disallow_hidpi: bool) -> Self; + fn with_has_shadow(self, has_shadow: bool) -> Self; + /// Window accepts click-through mouse events. + fn with_accepts_first_mouse(self, accepts_first_mouse: bool) -> Self; + /// Defines the window tabbing identifier. + /// + /// <https://developer.apple.com/documentation/appkit/nswindow/1644704-tabbingidentifier> + fn with_tabbing_identifier(self, identifier: &str) -> Self; + /// Set how the <kbd>Option</kbd> keys are interpreted. + /// + /// See [`WindowExtMacOS::set_option_as_alt`] for details on what this means if set. + fn with_option_as_alt(self, option_as_alt: OptionAsAlt) -> Self; + /// See [`WindowExtMacOS::set_borderless_game`] for details on what this means if set. + fn with_borderless_game(self, borderless_game: bool) -> Self; +} + +impl WindowAttributesExtMacOS for WindowAttributes { + #[inline] + fn with_movable_by_window_background(mut self, movable_by_window_background: bool) -> Self { + self.platform_specific.movable_by_window_background = movable_by_window_background; + self + } + + #[inline] + fn with_titlebar_transparent(mut self, titlebar_transparent: bool) -> Self { + self.platform_specific.titlebar_transparent = titlebar_transparent; + self + } + + #[inline] + fn with_titlebar_hidden(mut self, titlebar_hidden: bool) -> Self { + self.platform_specific.titlebar_hidden = titlebar_hidden; + self + } + + #[inline] + fn with_titlebar_buttons_hidden(mut self, titlebar_buttons_hidden: bool) -> Self { + self.platform_specific.titlebar_buttons_hidden = titlebar_buttons_hidden; + self + } + + #[inline] + fn with_title_hidden(mut self, title_hidden: bool) -> Self { + self.platform_specific.title_hidden = title_hidden; + self + } + + #[inline] + fn with_fullsize_content_view(mut self, fullsize_content_view: bool) -> Self { + self.platform_specific.fullsize_content_view = fullsize_content_view; + self + } + + #[inline] + fn with_disallow_hidpi(mut self, disallow_hidpi: bool) -> Self { + self.platform_specific.disallow_hidpi = disallow_hidpi; + self + } + + #[inline] + fn with_has_shadow(mut self, has_shadow: bool) -> Self { + self.platform_specific.has_shadow = has_shadow; + self + } + + #[inline] + fn with_accepts_first_mouse(mut self, accepts_first_mouse: bool) -> Self { + self.platform_specific.accepts_first_mouse = accepts_first_mouse; + self + } + + #[inline] + fn with_tabbing_identifier(mut self, tabbing_identifier: &str) -> Self { + self.platform_specific.tabbing_identifier.replace(tabbing_identifier.to_string()); + self + } + + #[inline] + fn with_option_as_alt(mut self, option_as_alt: OptionAsAlt) -> Self { + self.platform_specific.option_as_alt = option_as_alt; + self + } + + #[inline] + fn with_borderless_game(mut self, borderless_game: bool) -> Self { + self.platform_specific.borderless_game = borderless_game; + self + } +} + +pub trait EventLoopBuilderExtMacOS { + /// Sets the activation policy for the application. If used, this will override + /// any relevant settings provided in the package manifest. + /// For instance, `with_activation_policy(ActivationPolicy::Regular)` will prevent + /// the application from running as an "agent", even if LSUIElement is set to true. + /// + /// If unused, the Winit will honor the package manifest. + /// + /// # Example + /// + /// Set the activation policy to "accessory". + /// + /// ``` + /// use winit::event_loop::EventLoopBuilder; + /// #[cfg(target_os = "macos")] + /// use winit::platform::macos::{ActivationPolicy, EventLoopBuilderExtMacOS}; + /// + /// let mut builder = EventLoopBuilder::new(); + /// #[cfg(target_os = "macos")] + /// builder.with_activation_policy(ActivationPolicy::Accessory); + /// # if false { // We can't test this part + /// let event_loop = builder.build(); + /// # } + /// ``` + fn with_activation_policy(&mut self, activation_policy: ActivationPolicy) -> &mut Self; + + /// Used to control whether a default menubar menu is created. + /// + /// Menu creation is enabled by default. + /// + /// # Example + /// + /// Disable creating a default menubar. + /// + /// ``` + /// use winit::event_loop::EventLoopBuilder; + /// #[cfg(target_os = "macos")] + /// use winit::platform::macos::EventLoopBuilderExtMacOS; + /// + /// let mut builder = EventLoopBuilder::new(); + /// #[cfg(target_os = "macos")] + /// builder.with_default_menu(false); + /// # if false { // We can't test this part + /// let event_loop = builder.build(); + /// # } + /// ``` + fn with_default_menu(&mut self, enable: bool) -> &mut Self; + + /// Used to prevent the application from automatically activating when launched if + /// another application is already active. + /// + /// The default behavior is to ignore other applications and activate when launched. + fn with_activate_ignoring_other_apps(&mut self, ignore: bool) -> &mut Self; +} + +impl<T> EventLoopBuilderExtMacOS for EventLoopBuilder<T> { + #[inline] + fn with_activation_policy(&mut self, activation_policy: ActivationPolicy) -> &mut Self { + self.platform_specific.activation_policy = Some(activation_policy); + self + } + + #[inline] + fn with_default_menu(&mut self, enable: bool) -> &mut Self { + self.platform_specific.default_menu = enable; + self + } + + #[inline] + fn with_activate_ignoring_other_apps(&mut self, ignore: bool) -> &mut Self { + self.platform_specific.activate_ignoring_other_apps = ignore; + self + } +} + +/// Additional methods on [`MonitorHandle`] that are specific to MacOS. +pub trait MonitorHandleExtMacOS { + /// Returns the identifier of the monitor for Cocoa. + fn native_id(&self) -> u32; + /// Returns a pointer to the NSScreen representing this monitor. + fn ns_screen(&self) -> Option<*mut c_void>; +} + +impl MonitorHandleExtMacOS for MonitorHandle { + #[inline] + fn native_id(&self) -> u32 { + self.inner.native_identifier() + } + + fn ns_screen(&self) -> Option<*mut c_void> { + // SAFETY: We only use the marker to get a pointer + let mtm = unsafe { objc2_foundation::MainThreadMarker::new_unchecked() }; + self.inner.ns_screen(mtm).map(|s| objc2::rc::Retained::as_ptr(&s) as _) + } +} + +/// Additional methods on [`ActiveEventLoop`] that are specific to macOS. +pub trait ActiveEventLoopExtMacOS { + /// Hide the entire application. In most applications this is typically triggered with + /// Command-H. + fn hide_application(&self); + /// Hide the other applications. In most applications this is typically triggered with + /// Command+Option-H. + fn hide_other_applications(&self); + /// Set whether the system can automatically organize windows into tabs. + /// + /// <https://developer.apple.com/documentation/appkit/nswindow/1646657-allowsautomaticwindowtabbing> + fn set_allows_automatic_window_tabbing(&self, enabled: bool); + /// Returns whether the system can automatically organize windows into tabs. + fn allows_automatic_window_tabbing(&self) -> bool; +} + +impl ActiveEventLoopExtMacOS for ActiveEventLoop { + fn hide_application(&self) { + self.p.hide_application() + } + + fn hide_other_applications(&self) { + self.p.hide_other_applications() + } + + fn set_allows_automatic_window_tabbing(&self, enabled: bool) { + self.p.set_allows_automatic_window_tabbing(enabled); + } + + fn allows_automatic_window_tabbing(&self) -> bool { + self.p.allows_automatic_window_tabbing() + } +} + +/// Option as alt behavior. +/// +/// The default is `None`. +#[derive(Default, Debug, Clone, Copy, PartialEq, Eq)] +#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] +pub enum OptionAsAlt { + /// The left `Option` key is treated as `Alt`. + OnlyLeft, + + /// The right `Option` key is treated as `Alt`. + OnlyRight, + + /// Both `Option` keys are treated as `Alt`. + Both, + + /// No special handling is applied for `Option` key. + #[default] + None, +} + +/// Rune: the focused field's text around its selection (the selection a byte range of it), which +/// the input method reads through `selectedRange` and `attributedSubstringForProposedRange:` to +/// convert committed text again; `None` when nothing takes text. +pub fn set_ime_text(text: Option<(String, std::ops::Range<usize>)>) { + crate::platform_impl::ime_text::TEXT.with_borrow_mut(|t| *t = text); +} + +/// Rune: the clauses `setMarkedText:` gave marked text `preedit` (byte ranges, whether each is +/// the one being converted), if it's the last marked text. +pub fn take_ime_clauses(preedit: &str) -> Vec<(std::ops::Range<usize>, bool)> { + crate::platform_impl::ime_text::CLAUSES.with_borrow_mut(|c| match c.take() { + Some((text, clauses)) if text == preedit => clauses, + _ => Vec::new(), + }) +} + +/// Rune: the byte range of the text given to [`set_ime_text`] that a reconversion's marked text +/// replaces, once. +pub fn take_ime_replacement() -> Option<std::ops::Range<usize>> { + crate::platform_impl::ime_text::REPLACEMENT.with_borrow_mut(|r| r.take()) +} diff --git a/app/vendor/rune/vendor/winit/src/platform/mod.rs b/app/vendor/rune/vendor/winit/src/platform/mod.rs new file mode 100644 index 0000000..4f59303 --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/platform/mod.rs @@ -0,0 +1,55 @@ +//! Contains traits with platform-specific methods in them. +//! +//! Only the modules corresponding to the platform you're compiling to will be available. + +#[cfg(any(android_platform, docsrs))] +pub mod android; +#[cfg(any(ios_platform, docsrs))] +pub mod ios; +#[cfg(any(macos_platform, docsrs))] +pub mod macos; +#[cfg(any(orbital_platform, docsrs))] +pub mod orbital; +#[cfg(any(x11_platform, wayland_platform, docsrs))] +pub mod startup_notify; +#[cfg(any(wayland_platform, docsrs))] +pub mod wayland; +#[cfg(any(web_platform, docsrs))] +pub mod web; +#[cfg(any(windows_platform, docsrs))] +pub mod windows; +#[cfg(any(x11_platform, docsrs))] +pub mod x11; + +#[cfg(any( + windows_platform, + macos_platform, + android_platform, + x11_platform, + wayland_platform, + docsrs, +))] +pub mod run_on_demand; + +#[cfg(any( + windows_platform, + macos_platform, + android_platform, + x11_platform, + wayland_platform, + docsrs, +))] +pub mod pump_events; + +#[cfg(any( + windows_platform, + macos_platform, + x11_platform, + wayland_platform, + orbital_platform, + docsrs +))] +pub mod modifier_supplement; + +#[cfg(any(windows_platform, macos_platform, x11_platform, wayland_platform, docsrs))] +pub mod scancode; diff --git a/app/vendor/rune/vendor/winit/src/platform/modifier_supplement.rs b/app/vendor/rune/vendor/winit/src/platform/modifier_supplement.rs new file mode 100644 index 0000000..b1db734 --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/platform/modifier_supplement.rs @@ -0,0 +1,35 @@ +use crate::event::KeyEvent; +use crate::keyboard::Key; + +/// Additional methods for the `KeyEvent` which cannot be implemented on all +/// platforms. +pub trait KeyEventExtModifierSupplement { + /// Identical to `KeyEvent::text` but this is affected by <kbd>Ctrl</kbd>. + /// + /// For example, pressing <kbd>Ctrl</kbd>+<kbd>a</kbd> produces `Some("\x01")`. + fn text_with_all_modifiers(&self) -> Option<&str>; + + /// This value ignores all modifiers including, + /// but not limited to <kbd>Shift</kbd>, <kbd>Caps Lock</kbd>, + /// and <kbd>Ctrl</kbd>. In most cases this means that the + /// unicode character in the resulting string is lowercase. + /// + /// This is useful for key-bindings / shortcut key combinations. + /// + /// In case `logical_key` reports `Dead`, this will still report the + /// key as `Character` according to the current keyboard layout. This value + /// cannot be `Dead`. + fn key_without_modifiers(&self) -> Key; +} + +impl KeyEventExtModifierSupplement for KeyEvent { + #[inline] + fn text_with_all_modifiers(&self) -> Option<&str> { + self.platform_specific.text_with_all_modifiers.as_ref().map(|s| s.as_str()) + } + + #[inline] + fn key_without_modifiers(&self) -> Key { + self.platform_specific.key_without_modifiers.clone() + } +} diff --git a/app/vendor/rune/vendor/winit/src/platform/orbital.rs b/app/vendor/rune/vendor/winit/src/platform/orbital.rs new file mode 100644 index 0000000..d809350 --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/platform/orbital.rs @@ -0,0 +1,6 @@ +//! # Orbital / Redox OS +//! +//! Redox OS has some functionality not yet present that will be implemented +//! when its orbital display server provides it. + +// There are no Orbital specific traits yet. diff --git a/app/vendor/rune/vendor/winit/src/platform/pump_events.rs b/app/vendor/rune/vendor/winit/src/platform/pump_events.rs new file mode 100644 index 0000000..4476635 --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/platform/pump_events.rs @@ -0,0 +1,143 @@ +use std::time::Duration; + +use crate::application::ApplicationHandler; +use crate::event::Event; +use crate::event_loop::{self, ActiveEventLoop, EventLoop}; + +/// Additional methods on [`EventLoop`] for pumping events within an external event loop +pub trait EventLoopExtPumpEvents { + /// A type provided by the user that can be passed through [`Event::UserEvent`]. + type UserEvent: 'static; + + /// Pump the `EventLoop` to check for and dispatch pending events. + /// + /// This API is designed to enable applications to integrate Winit into an + /// external event loop, for platforms that can support this. + /// + /// The given `timeout` limits how long it may block waiting for new events. + /// + /// Passing a `timeout` of `Some(Duration::ZERO)` would ensure your external + /// event loop is never blocked but you would likely need to consider how + /// to throttle your own external loop. + /// + /// Passing a `timeout` of `None` means that it may wait indefinitely for new + /// events before returning control back to the external loop. + /// + /// **Note:** This is not a portable API, and its usage involves a number of + /// caveats and trade offs that should be considered before using this API! + /// + /// You almost certainly shouldn't use this API, unless you absolutely know it's + /// the only practical option you have. + /// + /// ## Synchronous events + /// + /// Some events _must_ only be handled synchronously via the closure that + /// is passed to Winit so that the handler will also be synchronized with + /// the window system and operating system. + /// + /// This is because some events are driven by a window system callback + /// where the window systems expects the application to have handled the + /// event before returning. + /// + /// **These events can not be buffered and handled outside of the closure + /// passed to Winit.** + /// + /// As a general rule it is not recommended to ever buffer events to handle + /// them outside of the closure passed to Winit since it's difficult to + /// provide guarantees about which events are safe to buffer across all + /// operating systems. + /// + /// Notable events that will certainly create portability problems if + /// buffered and handled outside of Winit include: + /// - `RedrawRequested` events, used to schedule rendering. + /// + /// macOS for example uses a `drawRect` callback to drive rendering + /// within applications and expects rendering to be finished before + /// the `drawRect` callback returns. + /// + /// For portability it's strongly recommended that applications should + /// keep their rendering inside the closure provided to Winit. + /// - Any lifecycle events, such as `Suspended` / `Resumed`. + /// + /// The handling of these events needs to be synchronized with the + /// operating system and it would never be appropriate to buffer a + /// notification that your application has been suspended or resumed and + /// then handled that later since there would always be a chance that + /// other lifecycle events occur while the event is buffered. + /// + /// ## Supported Platforms + /// + /// - Windows + /// - Linux + /// - MacOS + /// - Android + /// + /// ## Unsupported Platforms + /// + /// - **Web:** This API is fundamentally incompatible with the event-based way in which Web + /// browsers work because it's not possible to have a long-running external loop that would + /// block the browser and there is nothing that can be polled to ask for new new events. + /// Events are delivered via callbacks based on an event loop that is internal to the browser + /// itself. + /// - **iOS:** It's not possible to stop and start an `NSApplication` repeatedly on iOS so + /// there's no way to support the same approach to polling as on MacOS. + /// + /// ## Platform-specific + /// + /// - **Windows**: The implementation will use `PeekMessage` when checking for window messages + /// to avoid blocking your external event loop. + /// + /// - **MacOS**: The implementation works in terms of stopping the global application whenever + /// the application `RunLoop` indicates that it is preparing to block and wait for new events. + /// + /// This is very different to the polling APIs that are available on other + /// platforms (the lower level polling primitives on MacOS are private + /// implementation details for `NSApplication` which aren't accessible to + /// application developers) + /// + /// It's likely this will be less efficient than polling on other OSs and + /// it also means the `NSApplication` is stopped while outside of the Winit + /// event loop - and that's observable (for example to crates like `rfd`) + /// because the `NSApplication` is global state. + /// + /// If you render outside of Winit you are likely to see window resizing artifacts + /// since MacOS expects applications to render synchronously during any `drawRect` + /// callback. + fn pump_app_events<A: ApplicationHandler<Self::UserEvent>>( + &mut self, + timeout: Option<Duration>, + app: &mut A, + ) -> PumpStatus { + #[allow(deprecated)] + self.pump_events(timeout, |event, event_loop| { + event_loop::dispatch_event_for_app(app, event_loop, event) + }) + } + + /// See [`pump_app_events`]. + /// + /// [`pump_app_events`]: Self::pump_app_events + #[deprecated = "use EventLoopExtPumpEvents::pump_app_events"] + fn pump_events<F>(&mut self, timeout: Option<Duration>, event_handler: F) -> PumpStatus + where + F: FnMut(Event<Self::UserEvent>, &ActiveEventLoop); +} + +impl<T> EventLoopExtPumpEvents for EventLoop<T> { + type UserEvent = T; + + fn pump_events<F>(&mut self, timeout: Option<Duration>, event_handler: F) -> PumpStatus + where + F: FnMut(Event<Self::UserEvent>, &ActiveEventLoop), + { + self.event_loop.pump_events(timeout, event_handler) + } +} + +/// The return status for `pump_events` +pub enum PumpStatus { + /// Continue running external loop. + Continue, + /// Exit external loop. + Exit(i32), +} diff --git a/app/vendor/rune/vendor/winit/src/platform/run_on_demand.rs b/app/vendor/rune/vendor/winit/src/platform/run_on_demand.rs new file mode 100644 index 0000000..0bb96e9 --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/platform/run_on_demand.rs @@ -0,0 +1,111 @@ +use crate::application::ApplicationHandler; +use crate::error::EventLoopError; +use crate::event::Event; +use crate::event_loop::{self, ActiveEventLoop, EventLoop}; + +#[cfg(doc)] +use crate::{platform::pump_events::EventLoopExtPumpEvents, window::Window}; + +/// Additional methods on [`EventLoop`] to return control flow to the caller. +pub trait EventLoopExtRunOnDemand { + /// A type provided by the user that can be passed through [`Event::UserEvent`]. + type UserEvent: 'static; + + /// See [`run_app_on_demand`]. + /// + /// [`run_app_on_demand`]: Self::run_app_on_demand + #[deprecated = "use EventLoopExtRunOnDemand::run_app_on_demand"] + fn run_on_demand<F>(&mut self, event_handler: F) -> Result<(), EventLoopError> + where + F: FnMut(Event<Self::UserEvent>, &ActiveEventLoop); + + /// Run the application with the event loop on the calling thread. + /// + /// Unlike [`EventLoop::run_app`], this function accepts non-`'static` (i.e. non-`move`) + /// closures and it is possible to return control back to the caller without + /// consuming the `EventLoop` (by using [`exit()`]) and + /// so the event loop can be re-run after it has exit. + /// + /// It's expected that each run of the loop will be for orthogonal instantiations of your + /// Winit application, but internally each instantiation may re-use some common window + /// system resources, such as a display server connection. + /// + /// This API is not designed to run an event loop in bursts that you can exit from and return + /// to while maintaining the full state of your application. (If you need something like this + /// you can look at the [`EventLoopExtPumpEvents::pump_app_events()`] API) + /// + /// Each time `run_app_on_demand` is called the startup sequence of `init`, followed by + /// `resume` is being preserved. + /// + /// See the [`set_control_flow()`] docs on how to change the event loop's behavior. + /// + /// # Caveats + /// - This extension isn't available on all platforms, since it's not always possible to return + /// to the caller (specifically this is impossible on iOS and Web - though with the Web + /// backend it is possible to use `EventLoopExtWebSys::spawn()` + #[cfg_attr(not(web_platform), doc = "[^1]")] + /// more than once instead). + /// - No [`Window`] state can be carried between separate runs of the event loop. + /// + /// You are strongly encouraged to use [`EventLoop::run_app()`] for portability, unless you + /// specifically need the ability to re-run a single event loop more than once + /// + /// # Supported Platforms + /// - Windows + /// - Linux + /// - macOS + /// - Android + /// + /// # Unsupported Platforms + /// - **Web:** This API is fundamentally incompatible with the event-based way in which Web + /// browsers work because it's not possible to have a long-running external loop that would + /// block the browser and there is nothing that can be polled to ask for new events. Events + /// are delivered via callbacks based on an event loop that is internal to the browser itself. + /// - **iOS:** It's not possible to stop and start an `UIApplication` repeatedly on iOS. + #[cfg_attr(not(web_platform), doc = "[^1]: `spawn()` is only available on `wasm` platforms.")] + /// + #[rustfmt::skip] + /// [`exit()`]: ActiveEventLoop::exit() + /// [`set_control_flow()`]: ActiveEventLoop::set_control_flow() + fn run_app_on_demand<A: ApplicationHandler<Self::UserEvent>>( + &mut self, + app: &mut A, + ) -> Result<(), EventLoopError> { + #[allow(deprecated)] + self.run_on_demand(|event, event_loop| { + event_loop::dispatch_event_for_app(app, event_loop, event) + }) + } +} + +impl<T> EventLoopExtRunOnDemand for EventLoop<T> { + type UserEvent = T; + + fn run_on_demand<F>(&mut self, event_handler: F) -> Result<(), EventLoopError> + where + F: FnMut(Event<Self::UserEvent>, &ActiveEventLoop), + { + self.event_loop.window_target().clear_exit(); + self.event_loop.run_on_demand(event_handler) + } +} + +impl ActiveEventLoop { + /// Clear exit status. + pub(crate) fn clear_exit(&self) { + self.p.clear_exit() + } +} + +/// ```compile_fail +/// use winit::event_loop::EventLoop; +/// use winit::platform::run_on_demand::EventLoopExtRunOnDemand; +/// +/// let mut event_loop = EventLoop::new().unwrap(); +/// event_loop.run_on_demand(|_, _| { +/// // Attempt to run the event loop re-entrantly; this must fail. +/// event_loop.run_on_demand(|_, _| {}); +/// }); +/// ``` +#[allow(dead_code)] +fn test_run_on_demand_cannot_access_event_loop() {} diff --git a/app/vendor/rune/vendor/winit/src/platform/scancode.rs b/app/vendor/rune/vendor/winit/src/platform/scancode.rs new file mode 100644 index 0000000..0d78313 --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/platform/scancode.rs @@ -0,0 +1,50 @@ +use crate::keyboard::{KeyCode, PhysicalKey}; + +// TODO: Describe what this value contains for each platform + +/// Additional methods for the [`PhysicalKey`] type that allow the user to access the +/// platform-specific scancode. +/// +/// [`PhysicalKey`]: crate::keyboard::PhysicalKey +pub trait PhysicalKeyExtScancode { + /// The raw value of the platform-specific physical key identifier. + /// + /// Returns `Some(key_id)` if the conversion was successful; returns `None` otherwise. + /// + /// ## Platform-specific + /// - **Windows:** A 16bit extended scancode + /// - **Wayland/X11**: A 32-bit linux scancode, which is X11/Wayland keycode subtracted by 8. + fn to_scancode(self) -> Option<u32>; + + /// Constructs a `PhysicalKey` from a platform-specific physical key identifier. + /// + /// Note that this conversion may be lossy, i.e. converting the returned `PhysicalKey` back + /// using `to_scancode` might not yield the original value. + /// + /// ## Platform-specific + /// - **Wayland/X11**: A 32-bit linux scancode. When building from X11/Wayland keycode subtract + /// `8` to get the value you wanted. + fn from_scancode(scancode: u32) -> PhysicalKey; +} + +impl PhysicalKeyExtScancode for PhysicalKey { + fn to_scancode(self) -> Option<u32> { + crate::platform_impl::physicalkey_to_scancode(self) + } + + fn from_scancode(scancode: u32) -> PhysicalKey { + crate::platform_impl::scancode_to_physicalkey(scancode) + } +} + +impl PhysicalKeyExtScancode for KeyCode { + #[inline] + fn to_scancode(self) -> Option<u32> { + <PhysicalKey as PhysicalKeyExtScancode>::to_scancode(PhysicalKey::Code(self)) + } + + #[inline] + fn from_scancode(scancode: u32) -> PhysicalKey { + <PhysicalKey as PhysicalKeyExtScancode>::from_scancode(scancode) + } +} diff --git a/app/vendor/rune/vendor/winit/src/platform/startup_notify.rs b/app/vendor/rune/vendor/winit/src/platform/startup_notify.rs new file mode 100644 index 0000000..6fab284 --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/platform/startup_notify.rs @@ -0,0 +1,99 @@ +//! Window startup notification to handle window raising. +//! +//! The [`ActivationToken`] is essential to ensure that your newly +//! created window will obtain the focus, otherwise the user could +//! be requered to click on the window. +//! +//! Such token is usually delivered via the environment variable and +//! could be read from it with the [`EventLoopExtStartupNotify::read_token_from_env`]. +//! +//! Such token must also be reset after reading it from your environment with +//! [`reset_activation_token_env`] otherwise child processes could inherit it. +//! +//! When starting a new child process with a newly obtained [`ActivationToken`] from +//! [`WindowExtStartupNotify::request_activation_token`] the [`set_activation_token_env`] +//! must be used to propagate it to the child +//! +//! To ensure the delivery of such token by other processes to you, the user should +//! set `StartupNotify=true` inside the `.desktop` file of their application. +//! +//! The specification could be found [`here`]. +//! +//! [`here`]: https://specifications.freedesktop.org/startup-notification-spec/startup-notification-latest.txt + +use std::env; + +use crate::error::NotSupportedError; +use crate::event_loop::{ActiveEventLoop, AsyncRequestSerial}; +use crate::window::{ActivationToken, Window, WindowAttributes}; + +/// The variable which is used mostly on X11. +const X11_VAR: &str = "DESKTOP_STARTUP_ID"; + +/// The variable which is used mostly on Wayland. +const WAYLAND_VAR: &str = "XDG_ACTIVATION_TOKEN"; + +pub trait EventLoopExtStartupNotify { + /// Read the token from the environment. + /// + /// It's recommended **to unset** this environment variable for child processes. + fn read_token_from_env(&self) -> Option<ActivationToken>; +} + +pub trait WindowExtStartupNotify { + /// Request a new activation token. + /// + /// The token will be delivered inside + fn request_activation_token(&self) -> Result<AsyncRequestSerial, NotSupportedError>; +} + +pub trait WindowAttributesExtStartupNotify { + /// Use this [`ActivationToken`] during window creation. + /// + /// Not using such a token upon a window could make your window not gaining + /// focus until the user clicks on the window. + fn with_activation_token(self, token: ActivationToken) -> Self; +} + +impl EventLoopExtStartupNotify for ActiveEventLoop { + fn read_token_from_env(&self) -> Option<ActivationToken> { + match self.p { + #[cfg(wayland_platform)] + crate::platform_impl::ActiveEventLoop::Wayland(_) => env::var(WAYLAND_VAR), + #[cfg(x11_platform)] + crate::platform_impl::ActiveEventLoop::X(_) => env::var(X11_VAR), + } + .ok() + .map(ActivationToken::from_raw) + } +} + +impl WindowExtStartupNotify for Window { + fn request_activation_token(&self) -> Result<AsyncRequestSerial, NotSupportedError> { + self.window.request_activation_token() + } +} + +impl WindowAttributesExtStartupNotify for WindowAttributes { + fn with_activation_token(mut self, token: ActivationToken) -> Self { + self.platform_specific.activation_token = Some(token); + self + } +} + +/// Remove the activation environment variables from the current process. +/// +/// This is wise to do before running child processes, +/// which may not to support the activation token. +pub fn reset_activation_token_env() { + env::remove_var(X11_VAR); + env::remove_var(WAYLAND_VAR); +} + +/// Set environment variables responsible for activation token. +/// +/// This could be used before running daemon processes. +pub fn set_activation_token_env(token: ActivationToken) { + env::set_var(X11_VAR, &token.token); + env::set_var(WAYLAND_VAR, token.token); +} diff --git a/app/vendor/rune/vendor/winit/src/platform/wayland.rs b/app/vendor/rune/vendor/winit/src/platform/wayland.rs new file mode 100644 index 0000000..63c0a92 --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/platform/wayland.rs @@ -0,0 +1,170 @@ +//! # Wayland +//! +//! **Note:** Windows don't appear on Wayland until you draw/present to them. +//! +//! By default, Winit loads system libraries using `dlopen`. This can be +//! disabled by disabling the `"wayland-dlopen"` cargo feature. +//! +//! ## Client-side decorations +//! +//! Winit provides client-side decorations by default, but the behaviour can +//! be controlled with the following feature flags: +//! +//! * `wayland-csd-adwaita` (default). +//! * `wayland-csd-adwaita-crossfont`. +//! * `wayland-csd-adwaita-notitle`. + +use std::ffi::c_void; +use std::ptr::NonNull; + +use crate::event_loop::{ActiveEventLoop, EventLoop, EventLoopBuilder}; +use crate::monitor::MonitorHandle; +use crate::window::{Window, WindowAttributes}; + +pub use crate::window::Theme; + +/// Additional methods on [`ActiveEventLoop`] that are specific to Wayland. +pub trait ActiveEventLoopExtWayland { + /// True if the [`ActiveEventLoop`] uses Wayland. + fn is_wayland(&self) -> bool; +} + +impl ActiveEventLoopExtWayland for ActiveEventLoop { + #[inline] + fn is_wayland(&self) -> bool { + self.p.is_wayland() + } +} + +/// Additional methods on [`EventLoop`] that are specific to Wayland. +pub trait EventLoopExtWayland { + /// True if the [`EventLoop`] uses Wayland. + fn is_wayland(&self) -> bool; +} + +impl<T: 'static> EventLoopExtWayland for EventLoop<T> { + #[inline] + fn is_wayland(&self) -> bool { + self.event_loop.is_wayland() + } +} + +/// Additional methods on [`EventLoopBuilder`] that are specific to Wayland. +pub trait EventLoopBuilderExtWayland { + /// Force using Wayland. + fn with_wayland(&mut self) -> &mut Self; + + /// Whether to allow the event loop to be created off of the main thread. + /// + /// By default, the window is only allowed to be created on the main + /// thread, to make platform compatibility easier. + fn with_any_thread(&mut self, any_thread: bool) -> &mut Self; +} + +impl<T> EventLoopBuilderExtWayland for EventLoopBuilder<T> { + #[inline] + fn with_wayland(&mut self) -> &mut Self { + self.platform_specific.forced_backend = Some(crate::platform_impl::Backend::Wayland); + self + } + + #[inline] + fn with_any_thread(&mut self, any_thread: bool) -> &mut Self { + self.platform_specific.any_thread = any_thread; + self + } +} + +/// Additional methods on [`Window`] that are specific to Wayland. +/// +/// [`Window`]: crate::window::Window +pub trait WindowExtWayland { + /// Returns `xdg_toplevel` of the window or [`None`] if the window is X11 window. + fn xdg_toplevel(&self) -> Option<NonNull<c_void>>; + + /// Rune: the radius, in logical points, of the arc the window's content takes at its bottom + /// corners. A client-side frame (`sctk-adwaita`) draws a one-point border around the window + /// and rounds its corners while it floats, so the content's own square corners would show + /// past it. + /// + /// Zero when the frame draws the window square (maximized or tiled), when no client-side + /// frame is drawn (server side decorations, or decorations off), and on X11. + fn content_corner_radius(&self) -> f32; + + /// Rune: whether a client-side frame draws the window's decorations, true whatever state the + /// frame is in: a maximized, tiled or fullscreen window keeps its frame, which hides parts of + /// itself rather than going away. + /// + /// False when the compositor draws the decorations, when decorations are off, when no frame + /// could be made, and on X11. + fn has_client_side_frame(&self) -> bool; +} + +impl WindowExtWayland for Window { + #[inline] + fn xdg_toplevel(&self) -> Option<NonNull<c_void>> { + #[allow(clippy::single_match)] + match &self.window { + #[cfg(x11_platform)] + crate::platform_impl::Window::X(_) => None, + #[cfg(wayland_platform)] + crate::platform_impl::Window::Wayland(window) => window.xdg_toplevel(), + } + } + + #[inline] + fn content_corner_radius(&self) -> f32 { + #[allow(clippy::single_match)] + match &self.window { + #[cfg(x11_platform)] + crate::platform_impl::Window::X(_) => 0., + #[cfg(wayland_platform)] + crate::platform_impl::Window::Wayland(window) => window.content_corner_radius(), + } + } + + #[inline] + fn has_client_side_frame(&self) -> bool { + #[allow(clippy::single_match)] + match &self.window { + #[cfg(x11_platform)] + crate::platform_impl::Window::X(_) => false, + #[cfg(wayland_platform)] + crate::platform_impl::Window::Wayland(window) => window.has_client_side_frame(), + } + } +} + +/// Additional methods on [`WindowAttributes`] that are specific to Wayland. +pub trait WindowAttributesExtWayland { + /// Build window with the given name. + /// + /// The `general` name sets an application ID, which should match the `.desktop` + /// file distributed with your program. The `instance` is a `no-op`. + /// + /// For details about application ID conventions, see the + /// [Desktop Entry Spec](https://specifications.freedesktop.org/desktop-entry-spec/desktop-entry-spec-latest.html#desktop-file-id) + fn with_name(self, general: impl Into<String>, instance: impl Into<String>) -> Self; +} + +impl WindowAttributesExtWayland for WindowAttributes { + #[inline] + fn with_name(mut self, general: impl Into<String>, instance: impl Into<String>) -> Self { + self.platform_specific.name = + Some(crate::platform_impl::ApplicationName::new(general.into(), instance.into())); + self + } +} + +/// Additional methods on `MonitorHandle` that are specific to Wayland. +pub trait MonitorHandleExtWayland { + /// Returns the inner identifier of the monitor. + fn native_id(&self) -> u32; +} + +impl MonitorHandleExtWayland for MonitorHandle { + #[inline] + fn native_id(&self) -> u32 { + self.inner.native_identifier() + } +} diff --git a/app/vendor/rune/vendor/winit/src/platform/web.rs b/app/vendor/rune/vendor/winit/src/platform/web.rs new file mode 100644 index 0000000..f257ca4 --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/platform/web.rs @@ -0,0 +1,465 @@ +//! # Web +//! +//! The officially supported browsers are Chrome, Firefox and Safari 13.1+, +//! though forks of these should work fine. +//! +//! Winit supports compiling to the `wasm32-unknown-unknown` target with +//! `web-sys`. +//! +//! On the web platform, a Winit window is backed by a `<canvas>` element. You +//! can either [provide Winit with a `<canvas>` element][with_canvas], or +//! [let Winit create a `<canvas>` element which you can then retrieve][get] +//! and insert it into the DOM yourself. +//! +//! Currently, there is no example code using Winit on Web, see [#3473]. For +//! information on using Rust on WebAssembly, check out the [Rust and +//! WebAssembly book]. +//! +//! [with_canvas]: WindowAttributesExtWebSys::with_canvas +//! [get]: WindowExtWebSys::canvas +//! [#3473]: https://github.com/rust-windowing/winit/issues/3473 +//! [Rust and WebAssembly book]: https://rustwasm.github.io/book/ +//! +//! ## CSS properties +//! +//! It is recommended **not** to apply certain CSS properties to the canvas: +//! - [`transform`](https://developer.mozilla.org/en-US/docs/Web/CSS/transform) +//! - [`border`](https://developer.mozilla.org/en-US/docs/Web/CSS/border) +//! - [`padding`](https://developer.mozilla.org/en-US/docs/Web/CSS/padding) +//! +//! The following APIs can't take them into account and will therefore provide inaccurate results: +//! - [`WindowEvent::Resized`] and [`Window::(set_)inner_size()`] +//! - [`WindowEvent::Occluded`] +//! - [`WindowEvent::CursorMoved`], [`WindowEvent::CursorEntered`], [`WindowEvent::CursorLeft`], and +//! [`WindowEvent::Touch`]. +//! - [`Window::set_outer_position()`] +//! +//! [`WindowEvent::Resized`]: crate::event::WindowEvent::Resized +//! [`Window::(set_)inner_size()`]: crate::window::Window::inner_size +//! [`WindowEvent::Occluded`]: crate::event::WindowEvent::Occluded +//! [`WindowEvent::CursorMoved`]: crate::event::WindowEvent::CursorMoved +//! [`WindowEvent::CursorEntered`]: crate::event::WindowEvent::CursorEntered +//! [`WindowEvent::CursorLeft`]: crate::event::WindowEvent::CursorLeft +//! [`WindowEvent::Touch`]: crate::event::WindowEvent::Touch +//! [`Window::set_outer_position()`]: crate::window::Window::set_outer_position + +use std::error::Error; +use std::fmt::{self, Display, Formatter}; +use std::future::Future; +use std::pin::Pin; +use std::task::{Context, Poll}; +use std::time::Duration; + +#[cfg(web_platform)] +use web_sys::HtmlCanvasElement; + +use crate::application::ApplicationHandler; +use crate::cursor::CustomCursorSource; +use crate::event::Event; +use crate::event_loop::{self, ActiveEventLoop, EventLoop}; +#[cfg(web_platform)] +use crate::platform_impl::CustomCursorFuture as PlatformCustomCursorFuture; +use crate::platform_impl::PlatformCustomCursorSource; +use crate::window::{CustomCursor, Window, WindowAttributes}; + +#[cfg(not(web_platform))] +#[doc(hidden)] +pub struct HtmlCanvasElement; + +pub trait WindowExtWebSys { + /// Only returns the canvas if called from inside the window context (the + /// main thread). + fn canvas(&self) -> Option<HtmlCanvasElement>; + + /// Returns [`true`] if calling `event.preventDefault()` is enabled. + /// + /// See [`Window::set_prevent_default()`] for more details. + fn prevent_default(&self) -> bool; + + /// Sets whether `event.preventDefault()` should be called on events on the + /// canvas that have side effects. + /// + /// For example, by default using the mouse wheel would cause the page to scroll, enabling this + /// would prevent that. + /// + /// Some events are impossible to prevent. E.g. Firefox allows to access the native browser + /// context menu with Shift+Rightclick. + fn set_prevent_default(&self, prevent_default: bool); +} + +impl WindowExtWebSys for Window { + #[inline] + fn canvas(&self) -> Option<HtmlCanvasElement> { + self.window.canvas() + } + + fn prevent_default(&self) -> bool { + self.window.prevent_default() + } + + fn set_prevent_default(&self, prevent_default: bool) { + self.window.set_prevent_default(prevent_default) + } +} + +pub trait WindowAttributesExtWebSys { + /// Pass an [`HtmlCanvasElement`] to be used for this [`Window`]. If [`None`], + /// [`WindowAttributes::default()`] will create one. + /// + /// In any case, the canvas won't be automatically inserted into the web page. + /// + /// [`None`] by default. + #[cfg_attr(not(web_platform), doc = "", doc = "[`HtmlCanvasElement`]: #only-available-on-wasm")] + fn with_canvas(self, canvas: Option<HtmlCanvasElement>) -> Self; + + /// Sets whether `event.preventDefault()` should be called on events on the + /// canvas that have side effects. + /// + /// See [`Window::set_prevent_default()`] for more details. + /// + /// Enabled by default. + fn with_prevent_default(self, prevent_default: bool) -> Self; + + /// Whether the canvas should be focusable using the tab key. This is necessary to capture + /// canvas keyboard events. + /// + /// Enabled by default. + fn with_focusable(self, focusable: bool) -> Self; + + /// On window creation, append the canvas element to the web page if it isn't already. + /// + /// Disabled by default. + fn with_append(self, append: bool) -> Self; +} + +impl WindowAttributesExtWebSys for WindowAttributes { + fn with_canvas(mut self, canvas: Option<HtmlCanvasElement>) -> Self { + self.platform_specific.set_canvas(canvas); + self + } + + fn with_prevent_default(mut self, prevent_default: bool) -> Self { + self.platform_specific.prevent_default = prevent_default; + self + } + + fn with_focusable(mut self, focusable: bool) -> Self { + self.platform_specific.focusable = focusable; + self + } + + fn with_append(mut self, append: bool) -> Self { + self.platform_specific.append = append; + self + } +} + +/// Additional methods on `EventLoop` that are specific to the web. +pub trait EventLoopExtWebSys { + /// A type provided by the user that can be passed through `Event::UserEvent`. + type UserEvent: 'static; + + /// Initializes the winit event loop. + /// + /// Unlike + #[cfg_attr(all(web_platform, target_feature = "exception-handling"), doc = "`run_app()`")] + #[cfg_attr( + not(all(web_platform, target_feature = "exception-handling")), + doc = "[`run_app()`]" + )] + /// [^1], this returns immediately, and doesn't throw an exception in order to + /// satisfy its [`!`] return type. + /// + /// Once the event loop has been destroyed, it's possible to reinitialize another event loop + /// by calling this function again. This can be useful if you want to recreate the event loop + /// while the WebAssembly module is still loaded. For example, this can be used to recreate the + /// event loop when switching between tabs on a single page application. + #[rustfmt::skip] + /// + #[cfg_attr( + not(all(web_platform, target_feature = "exception-handling")), + doc = "[`run_app()`]: EventLoop::run_app()" + )] + /// [^1]: `run_app()` is _not_ available on WASM when the target supports `exception-handling`. + fn spawn_app<A: ApplicationHandler<Self::UserEvent> + 'static>(self, app: A); + + /// See [`spawn_app`]. + /// + /// [`spawn_app`]: Self::spawn_app + #[deprecated = "use EventLoopExtWebSys::spawn_app"] + fn spawn<F>(self, event_handler: F) + where + F: 'static + FnMut(Event<Self::UserEvent>, &ActiveEventLoop); + + /// Sets the strategy for [`ControlFlow::Poll`]. + /// + /// See [`PollStrategy`]. + /// + /// [`ControlFlow::Poll`]: crate::event_loop::ControlFlow::Poll + fn set_poll_strategy(&self, strategy: PollStrategy); + + /// Gets the strategy for [`ControlFlow::Poll`]. + /// + /// See [`PollStrategy`]. + /// + /// [`ControlFlow::Poll`]: crate::event_loop::ControlFlow::Poll + fn poll_strategy(&self) -> PollStrategy; + + /// Sets the strategy for [`ControlFlow::WaitUntil`]. + /// + /// See [`WaitUntilStrategy`]. + /// + /// [`ControlFlow::WaitUntil`]: crate::event_loop::ControlFlow::WaitUntil + fn set_wait_until_strategy(&self, strategy: WaitUntilStrategy); + + /// Gets the strategy for [`ControlFlow::WaitUntil`]. + /// + /// See [`WaitUntilStrategy`]. + /// + /// [`ControlFlow::WaitUntil`]: crate::event_loop::ControlFlow::WaitUntil + fn wait_until_strategy(&self) -> WaitUntilStrategy; +} + +impl<T> EventLoopExtWebSys for EventLoop<T> { + type UserEvent = T; + + fn spawn_app<A: ApplicationHandler<Self::UserEvent> + 'static>(self, mut app: A) { + self.event_loop.spawn(move |event, event_loop| { + event_loop::dispatch_event_for_app(&mut app, event_loop, event) + }); + } + + fn spawn<F>(self, event_handler: F) + where + F: 'static + FnMut(Event<Self::UserEvent>, &ActiveEventLoop), + { + self.event_loop.spawn(event_handler) + } + + fn set_poll_strategy(&self, strategy: PollStrategy) { + self.event_loop.set_poll_strategy(strategy); + } + + fn poll_strategy(&self) -> PollStrategy { + self.event_loop.poll_strategy() + } + + fn set_wait_until_strategy(&self, strategy: WaitUntilStrategy) { + self.event_loop.set_wait_until_strategy(strategy); + } + + fn wait_until_strategy(&self) -> WaitUntilStrategy { + self.event_loop.wait_until_strategy() + } +} + +pub trait ActiveEventLoopExtWebSys { + /// Sets the strategy for [`ControlFlow::Poll`]. + /// + /// See [`PollStrategy`]. + /// + /// [`ControlFlow::Poll`]: crate::event_loop::ControlFlow::Poll + fn set_poll_strategy(&self, strategy: PollStrategy); + + /// Gets the strategy for [`ControlFlow::Poll`]. + /// + /// See [`PollStrategy`]. + /// + /// [`ControlFlow::Poll`]: crate::event_loop::ControlFlow::Poll + fn poll_strategy(&self) -> PollStrategy; + + /// Sets the strategy for [`ControlFlow::WaitUntil`]. + /// + /// See [`WaitUntilStrategy`]. + /// + /// [`ControlFlow::WaitUntil`]: crate::event_loop::ControlFlow::WaitUntil + fn set_wait_until_strategy(&self, strategy: WaitUntilStrategy); + + /// Gets the strategy for [`ControlFlow::WaitUntil`]. + /// + /// See [`WaitUntilStrategy`]. + /// + /// [`ControlFlow::WaitUntil`]: crate::event_loop::ControlFlow::WaitUntil + fn wait_until_strategy(&self) -> WaitUntilStrategy; + + /// Async version of [`ActiveEventLoop::create_custom_cursor()`] which waits until the + /// cursor has completely finished loading. + fn create_custom_cursor_async(&self, source: CustomCursorSource) -> CustomCursorFuture; +} + +impl ActiveEventLoopExtWebSys for ActiveEventLoop { + #[inline] + fn create_custom_cursor_async(&self, source: CustomCursorSource) -> CustomCursorFuture { + self.p.create_custom_cursor_async(source) + } + + #[inline] + fn set_poll_strategy(&self, strategy: PollStrategy) { + self.p.set_poll_strategy(strategy); + } + + #[inline] + fn poll_strategy(&self) -> PollStrategy { + self.p.poll_strategy() + } + + #[inline] + fn set_wait_until_strategy(&self, strategy: WaitUntilStrategy) { + self.p.set_wait_until_strategy(strategy); + } + + #[inline] + fn wait_until_strategy(&self) -> WaitUntilStrategy { + self.p.wait_until_strategy() + } +} + +/// Strategy used for [`ControlFlow::Poll`][crate::event_loop::ControlFlow::Poll]. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum PollStrategy { + /// Uses [`Window.requestIdleCallback()`] to queue the next event loop. If not available + /// this will fallback to [`setTimeout()`]. + /// + /// This strategy will wait for the browser to enter an idle period before running and might + /// be affected by browser throttling. + /// + /// [`Window.requestIdleCallback()`]: https://developer.mozilla.org/en-US/docs/Web/API/Window/requestIdleCallback + /// [`setTimeout()`]: https://developer.mozilla.org/en-US/docs/Web/API/setTimeout + IdleCallback, + /// Uses the [Prioritized Task Scheduling API] to queue the next event loop. If not available + /// this will fallback to [`setTimeout()`]. + /// + /// This strategy will run as fast as possible without disturbing users from interacting with + /// the page and is not affected by browser throttling. + /// + /// This is the default strategy. + /// + /// [Prioritized Task Scheduling API]: https://developer.mozilla.org/en-US/docs/Web/API/Prioritized_Task_Scheduling_API + /// [`setTimeout()`]: https://developer.mozilla.org/en-US/docs/Web/API/setTimeout + #[default] + Scheduler, +} + +/// Strategy used for [`ControlFlow::WaitUntil`][crate::event_loop::ControlFlow::WaitUntil]. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum WaitUntilStrategy { + /// Uses the [Prioritized Task Scheduling API] to queue the next event loop. If not available + /// this will fallback to [`setTimeout()`]. + /// + /// This strategy is commonly not affected by browser throttling unless the window is not + /// focused. + /// + /// This is the default strategy. + /// + /// [Prioritized Task Scheduling API]: https://developer.mozilla.org/en-US/docs/Web/API/Prioritized_Task_Scheduling_API + /// [`setTimeout()`]: https://developer.mozilla.org/en-US/docs/Web/API/setTimeout + #[default] + Scheduler, + /// Equal to [`Scheduler`][Self::Scheduler] but wakes up the event loop from a [worker]. + /// + /// This strategy is commonly not affected by browser throttling regardless of window focus. + /// + /// [worker]: https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API + Worker, +} + +pub trait CustomCursorExtWebSys { + /// Returns if this cursor is an animation. + fn is_animation(&self) -> bool; + + /// Creates a new cursor from a URL pointing to an image. + /// It uses the [url css function](https://developer.mozilla.org/en-US/docs/Web/CSS/url), + /// but browser support for image formats is inconsistent. Using [PNG] is recommended. + /// + /// [PNG]: https://en.wikipedia.org/wiki/PNG + fn from_url(url: String, hotspot_x: u16, hotspot_y: u16) -> CustomCursorSource; + + /// Crates a new animated cursor from multiple [`CustomCursor`]s. + /// Supplied `cursors` can't be empty or other animations. + fn from_animation( + duration: Duration, + cursors: Vec<CustomCursor>, + ) -> Result<CustomCursorSource, BadAnimation>; +} + +impl CustomCursorExtWebSys for CustomCursor { + fn is_animation(&self) -> bool { + self.inner.animation + } + + fn from_url(url: String, hotspot_x: u16, hotspot_y: u16) -> CustomCursorSource { + CustomCursorSource { inner: PlatformCustomCursorSource::Url { url, hotspot_x, hotspot_y } } + } + + fn from_animation( + duration: Duration, + cursors: Vec<CustomCursor>, + ) -> Result<CustomCursorSource, BadAnimation> { + if cursors.is_empty() { + return Err(BadAnimation::Empty); + } + + if cursors.iter().any(CustomCursor::is_animation) { + return Err(BadAnimation::Animation); + } + + Ok(CustomCursorSource { + inner: PlatformCustomCursorSource::Animation { duration, cursors }, + }) + } +} + +/// An error produced when using [`CustomCursor::from_animation`] with invalid arguments. +#[derive(Debug, Clone)] +pub enum BadAnimation { + /// Produced when no cursors were supplied. + Empty, + /// Produced when a supplied cursor is an animation. + Animation, +} + +impl fmt::Display for BadAnimation { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Empty => write!(f, "No cursors supplied"), + Self::Animation => write!(f, "A supplied cursor is an animation"), + } + } +} + +impl Error for BadAnimation {} + +#[cfg(not(web_platform))] +struct PlatformCustomCursorFuture; + +#[derive(Debug)] +pub struct CustomCursorFuture(pub(crate) PlatformCustomCursorFuture); + +impl Future for CustomCursorFuture { + type Output = Result<CustomCursor, CustomCursorError>; + + fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { + Pin::new(&mut self.0).poll(cx).map_ok(|cursor| CustomCursor { inner: cursor }) + } +} + +#[derive(Clone, Debug)] +pub enum CustomCursorError { + Blob, + Decode(String), + Animation, +} + +impl Display for CustomCursorError { + fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { + match self { + Self::Blob => write!(f, "failed to create `Blob`"), + Self::Decode(error) => write!(f, "failed to decode image: {error}"), + Self::Animation => { + write!(f, "found `CustomCursor` that is an animation when building an animation") + }, + } + } +} + +impl Error for CustomCursorError {} diff --git a/app/vendor/rune/vendor/winit/src/platform/windows.rs b/app/vendor/rune/vendor/winit/src/platform/windows.rs new file mode 100644 index 0000000..5f1b921 --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/platform/windows.rs @@ -0,0 +1,775 @@ +//! # Windows +//! +//! The supported OS version is Windows 7 or higher, though Windows 10 is +//! tested regularly. +use std::borrow::Borrow; +use std::ffi::c_void; +use std::path::Path; + +use crate::dpi::PhysicalSize; +use crate::event::DeviceId; +use crate::event_loop::EventLoopBuilder; +use crate::monitor::MonitorHandle; +use crate::window::{BadIcon, Icon, Window, WindowAttributes}; + +/// Window Handle type used by Win32 API +/// Builds winit's keyboard-layout table for thread `thread_id`'s keyboard layout on the calling +/// thread, so the first key or mouse message that thread's windows handle doesn't build it (8-10 +/// ms, every virtual key through `ToUnicodeEx`). Call it on a thread of its own at launch with +/// the UI thread's id. +pub fn warm_keyboard_layout(thread_id: u32) { + crate::platform_impl::warm_layout(thread_id); +} + +pub type HWND = isize; +/// Menu Handle type used by Win32 API +pub type HMENU = isize; +/// Monitor Handle type used by Win32 API +pub type HMONITOR = isize; + +/// Describes a system-drawn backdrop material of a window. +/// +/// For a detailed explanation, see [`DWM_SYSTEMBACKDROP_TYPE docs`]. +/// +/// [`DWM_SYSTEMBACKDROP_TYPE docs`]: https://learn.microsoft.com/en-us/windows/win32/api/dwmapi/ne-dwmapi-dwm_systembackdrop_type +#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)] +pub enum BackdropType { + /// Corresponds to `DWMSBT_AUTO`. + /// + /// Usually draws a default backdrop effect on the title bar. + #[default] + Auto = 0, + + /// Corresponds to `DWMSBT_NONE`. + None = 1, + + /// Corresponds to `DWMSBT_MAINWINDOW`. + /// + /// Draws the Mica backdrop material. + MainWindow = 2, + + /// Corresponds to `DWMSBT_TRANSIENTWINDOW`. + /// + /// Draws the Background Acrylic backdrop material. + TransientWindow = 3, + + /// Corresponds to `DWMSBT_TABBEDWINDOW`. + /// + /// Draws the Alt Mica backdrop material. + TabbedWindow = 4, +} + +/// Describes a color used by Windows +#[repr(transparent)] +#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)] +pub struct Color(u32); + +impl Color { + // Special constant only valid for the window border and therefore modeled using Option<Color> + // for user facing code + const NONE: Color = Color(0xfffffffe); + /// Use the system's default color + pub const SYSTEM_DEFAULT: Color = Color(0xffffffff); + + /// Create a new color from the given RGB values + pub const fn from_rgb(r: u8, g: u8, b: u8) -> Self { + Self((r as u32) | ((g as u32) << 8) | ((b as u32) << 16)) + } +} + +impl Default for Color { + fn default() -> Self { + Self::SYSTEM_DEFAULT + } +} + +/// Describes how the corners of a window should look like. +/// +/// For a detailed explanation, see [`DWM_WINDOW_CORNER_PREFERENCE docs`]. +/// +/// [`DWM_WINDOW_CORNER_PREFERENCE docs`]: https://learn.microsoft.com/en-us/windows/win32/api/dwmapi/ne-dwmapi-dwm_window_corner_preference +#[repr(i32)] +#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)] +pub enum CornerPreference { + /// Corresponds to `DWMWCP_DEFAULT`. + /// + /// Let the system decide when to round window corners. + #[default] + Default = 0, + + /// Corresponds to `DWMWCP_DONOTROUND`. + /// + /// Never round window corners. + DoNotRound = 1, + + /// Corresponds to `DWMWCP_ROUND`. + /// + /// Round the corners, if appropriate. + Round = 2, + + /// Corresponds to `DWMWCP_ROUNDSMALL`. + /// + /// Round the corners if appropriate, with a small radius. + RoundSmall = 3, +} + +/// A wrapper around a [`Window`] that ignores thread-specific window handle limitations. +/// +/// See [`WindowBorrowExtWindows::any_thread`] for more information. +#[derive(Debug)] +pub struct AnyThread<W>(W); + +impl<W: Borrow<Window>> AnyThread<W> { + /// Get a reference to the inner window. + #[inline] + pub fn get_ref(&self) -> &Window { + self.0.borrow() + } + + /// Get a reference to the inner object. + #[inline] + pub fn inner(&self) -> &W { + &self.0 + } + + /// Unwrap and get the inner window. + #[inline] + pub fn into_inner(self) -> W { + self.0 + } +} + +impl<W: Borrow<Window>> AsRef<Window> for AnyThread<W> { + fn as_ref(&self) -> &Window { + self.get_ref() + } +} + +impl<W: Borrow<Window>> Borrow<Window> for AnyThread<W> { + fn borrow(&self) -> &Window { + self.get_ref() + } +} + +impl<W: Borrow<Window>> std::ops::Deref for AnyThread<W> { + type Target = Window; + + fn deref(&self) -> &Self::Target { + self.get_ref() + } +} + +#[cfg(feature = "rwh_06")] +impl<W: Borrow<Window>> rwh_06::HasWindowHandle for AnyThread<W> { + fn window_handle(&self) -> Result<rwh_06::WindowHandle<'_>, rwh_06::HandleError> { + // SAFETY: The top level user has asserted this is only used safely. + unsafe { self.get_ref().window_handle_any_thread() } + } +} + +/// Additional methods on `EventLoop` that are specific to Windows. +pub trait EventLoopBuilderExtWindows { + /// Whether to allow the event loop to be created off of the main thread. + /// + /// By default, the window is only allowed to be created on the main + /// thread, to make platform compatibility easier. + /// + /// # `Window` caveats + /// + /// Note that any `Window` created on the new thread will be destroyed when the thread + /// terminates. Attempting to use a `Window` after its parent thread terminates has + /// unspecified, although explicitly not undefined, behavior. + fn with_any_thread(&mut self, any_thread: bool) -> &mut Self; + + /// Whether to enable process-wide DPI awareness. + /// + /// By default, `winit` will attempt to enable process-wide DPI awareness. If + /// that's undesirable, you can disable it with this function. + /// + /// # Example + /// + /// Disable process-wide DPI awareness. + /// + /// ``` + /// use winit::event_loop::EventLoopBuilder; + /// #[cfg(target_os = "windows")] + /// use winit::platform::windows::EventLoopBuilderExtWindows; + /// + /// let mut builder = EventLoopBuilder::new(); + /// #[cfg(target_os = "windows")] + /// builder.with_dpi_aware(false); + /// # if false { // We can't test this part + /// let event_loop = builder.build(); + /// # } + /// ``` + fn with_dpi_aware(&mut self, dpi_aware: bool) -> &mut Self; + + /// A callback to be executed before dispatching a win32 message to the window procedure. + /// Return true to disable winit's internal message dispatching. + /// + /// # Example + /// + /// ``` + /// # use windows_sys::Win32::UI::WindowsAndMessaging::{ACCEL, CreateAcceleratorTableW, TranslateAcceleratorW, DispatchMessageW, TranslateMessage, MSG}; + /// use winit::event_loop::EventLoopBuilder; + /// #[cfg(target_os = "windows")] + /// use winit::platform::windows::EventLoopBuilderExtWindows; + /// + /// let mut builder = EventLoopBuilder::new(); + /// #[cfg(target_os = "windows")] + /// builder.with_msg_hook(|msg|{ + /// let msg = msg as *const MSG; + /// # let accels: Vec<ACCEL> = Vec::new(); + /// let translated = unsafe { + /// TranslateAcceleratorW( + /// (*msg).hwnd, + /// CreateAcceleratorTableW(accels.as_ptr() as _, 1), + /// msg, + /// ) == 1 + /// }; + /// translated + /// }); + /// ``` + fn with_msg_hook<F>(&mut self, callback: F) -> &mut Self + where + F: FnMut(*const c_void) -> bool + 'static; +} + +impl<T> EventLoopBuilderExtWindows for EventLoopBuilder<T> { + #[inline] + fn with_any_thread(&mut self, any_thread: bool) -> &mut Self { + self.platform_specific.any_thread = any_thread; + self + } + + #[inline] + fn with_dpi_aware(&mut self, dpi_aware: bool) -> &mut Self { + self.platform_specific.dpi_aware = dpi_aware; + self + } + + #[inline] + fn with_msg_hook<F>(&mut self, callback: F) -> &mut Self + where + F: FnMut(*const c_void) -> bool + 'static, + { + self.platform_specific.msg_hook = Some(Box::new(callback)); + self + } +} + +/// Additional methods on `Window` that are specific to Windows. +pub trait WindowExtWindows { + /// Enables or disables mouse and keyboard input to the specified window. + /// + /// A window must be enabled before it can be activated. + /// If an application has create a modal dialog box by disabling its owner window + /// (as described in [`WindowAttributesExtWindows::with_owner_window`]), the application must + /// enable the owner window before destroying the dialog box. + /// Otherwise, another window will receive the keyboard focus and be activated. + /// + /// If a child window is disabled, it is ignored when the system tries to determine which + /// window should receive mouse messages. + /// + /// For more information, see <https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-enablewindow#remarks> + /// and <https://docs.microsoft.com/en-us/windows/win32/winmsg/window-features#disabled-windows> + fn set_enable(&self, enabled: bool); + + /// This sets `ICON_BIG`. A good ceiling here is 256x256. + fn set_taskbar_icon(&self, taskbar_icon: Option<Icon>); + + /// Whether to show or hide the window icon in the taskbar. + fn set_skip_taskbar(&self, skip: bool); + + /// Shows or hides the background drop shadow for undecorated windows. + /// + /// Enabling the shadow causes a thin 1px line to appear on the top of the window. + fn set_undecorated_shadow(&self, shadow: bool); + + /// Sets system-drawn backdrop type. + /// + /// Requires Windows 11 build 22523+. + fn set_system_backdrop(&self, backdrop_type: BackdropType); + + /// Sets the color of the window border. + /// + /// Supported starting with Windows 11 Build 22000. + fn set_border_color(&self, color: Option<Color>); + + /// Sets the background color of the title bar. + /// + /// Supported starting with Windows 11 Build 22000. + fn set_title_background_color(&self, color: Option<Color>); + + /// Sets the color of the window title. + /// + /// Supported starting with Windows 11 Build 22000. + fn set_title_text_color(&self, color: Color); + + /// Sets the preferred style of the window corners. + /// + /// Supported starting with Windows 11 Build 22000. + fn set_corner_preference(&self, preference: CornerPreference); + + /// Get the raw window handle for this [`Window`] without checking for thread affinity. + /// + /// Window handles in Win32 have a property called "thread affinity" that ties them to their + /// origin thread. Some operations can only happen on the window's origin thread, while others + /// can be called from any thread. For example, [`SetWindowSubclass`] is not thread safe while + /// [`GetDC`] is thread safe. + /// + /// In Rust terms, the window handle is `Send` sometimes but `!Send` other times. + /// + /// Therefore, in order to avoid confusing threading errors, [`Window`] only returns the + /// window handle when the [`window_handle`] function is called from the thread that created + /// the window. In other cases, it returns an [`Unavailable`] error. + /// + /// However in some cases you may already know that you are using the window handle for + /// operations that are guaranteed to be thread-safe. In which case this function aims + /// to provide an escape hatch so these functions are still accessible from other threads. + /// + /// # Safety + /// + /// It is the responsibility of the user to only pass the window handle into thread-safe + /// Win32 APIs. + /// + /// [`SetWindowSubclass`]: https://learn.microsoft.com/en-us/windows/win32/api/commctrl/nf-commctrl-setwindowsubclass + /// [`GetDC`]: https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-getdc + /// [`Window`]: crate::window::Window + /// [`window_handle`]: https://docs.rs/raw-window-handle/latest/raw_window_handle/trait.HasWindowHandle.html#tymethod.window_handle + /// [`Unavailable`]: https://docs.rs/raw-window-handle/latest/raw_window_handle/enum.HandleError.html#variant.Unavailable + /// + /// ## Example + /// + /// ```no_run + /// # use winit::window::Window; + /// # fn scope(window: Window) { + /// use std::thread; + /// use winit::platform::windows::WindowExtWindows; + /// use winit::raw_window_handle::HasWindowHandle; + /// + /// // We can get the window handle on the current thread. + /// let handle = window.window_handle().unwrap(); + /// + /// // However, on another thread, we can't! + /// thread::spawn(move || { + /// assert!(window.window_handle().is_err()); + /// + /// // We can use this function as an escape hatch. + /// let handle = unsafe { window.window_handle_any_thread().unwrap() }; + /// }); + /// # } + /// ``` + #[cfg(feature = "rwh_06")] + unsafe fn window_handle_any_thread( + &self, + ) -> Result<rwh_06::WindowHandle<'_>, rwh_06::HandleError>; +} + +impl WindowExtWindows for Window { + #[inline] + fn set_enable(&self, enabled: bool) { + self.window.set_enable(enabled) + } + + #[inline] + fn set_taskbar_icon(&self, taskbar_icon: Option<Icon>) { + self.window.set_taskbar_icon(taskbar_icon) + } + + #[inline] + fn set_skip_taskbar(&self, skip: bool) { + self.window.set_skip_taskbar(skip) + } + + #[inline] + fn set_undecorated_shadow(&self, shadow: bool) { + self.window.set_undecorated_shadow(shadow) + } + + #[inline] + fn set_system_backdrop(&self, backdrop_type: BackdropType) { + self.window.set_system_backdrop(backdrop_type) + } + + #[inline] + fn set_border_color(&self, color: Option<Color>) { + self.window.set_border_color(color.unwrap_or(Color::NONE)) + } + + #[inline] + fn set_title_background_color(&self, color: Option<Color>) { + // The windows docs don't mention NONE as a valid options but it works in practice and is + // useful to circumvent the Windows option "Show accent color on title bars and + // window borders" + self.window.set_title_background_color(color.unwrap_or(Color::NONE)) + } + + #[inline] + fn set_title_text_color(&self, color: Color) { + self.window.set_title_text_color(color) + } + + #[inline] + fn set_corner_preference(&self, preference: CornerPreference) { + self.window.set_corner_preference(preference) + } + + #[cfg(feature = "rwh_06")] + unsafe fn window_handle_any_thread( + &self, + ) -> Result<rwh_06::WindowHandle<'_>, rwh_06::HandleError> { + unsafe { + let handle = self.window.rwh_06_no_thread_check()?; + + // SAFETY: The handle is valid in this context. + Ok(rwh_06::WindowHandle::borrow_raw(handle)) + } + } +} + +/// Additional methods for anything that dereference to [`Window`]. +/// +/// [`Window`]: crate::window::Window +pub trait WindowBorrowExtWindows: Borrow<Window> + Sized { + /// Create an object that allows accessing the inner window handle in a thread-unsafe way. + /// + /// It is possible to call [`window_handle_any_thread`] to get around Windows's thread + /// affinity limitations. However, it may be desired to pass the [`Window`] into something + /// that requires the [`HasWindowHandle`] trait, while ignoring thread affinity limitations. + /// + /// This function wraps anything that implements `Borrow<Window>` into a structure that + /// uses the inner window handle as a mean of implementing [`HasWindowHandle`]. It wraps + /// `Window`, `&Window`, `Arc<Window>`, and other reference types. + /// + /// # Safety + /// + /// It is the responsibility of the user to only pass the window handle into thread-safe + /// Win32 APIs. + /// + /// [`window_handle_any_thread`]: WindowExtWindows::window_handle_any_thread + /// [`Window`]: crate::window::Window + /// [`HasWindowHandle`]: rwh_06::HasWindowHandle + unsafe fn any_thread(self) -> AnyThread<Self> { + AnyThread(self) + } +} + +impl<W: Borrow<Window> + Sized> WindowBorrowExtWindows for W {} + +/// Additional methods on `WindowAttributes` that are specific to Windows. +#[allow(rustdoc::broken_intra_doc_links)] +pub trait WindowAttributesExtWindows { + /// Set an owner to the window to be created. Can be used to create a dialog box, for example. + /// This only works when [`WindowAttributes::with_parent_window`] isn't called or set to `None`. + /// Can be used in combination with + /// [`WindowExtWindows::set_enable(false)`][WindowExtWindows::set_enable] on the owner + /// window to create a modal dialog box. + /// + /// From MSDN: + /// - An owned window is always above its owner in the z-order. + /// - The system automatically destroys an owned window when its owner is destroyed. + /// - An owned window is hidden when its owner is minimized. + /// + /// For more information, see <https://docs.microsoft.com/en-us/windows/win32/winmsg/window-features#owned-windows> + fn with_owner_window(self, parent: HWND) -> Self; + + /// Sets a menu on the window to be created. + /// + /// Parent and menu are mutually exclusive; a child window cannot have a menu! + /// + /// The menu must have been manually created beforehand with [`CreateMenu`] or similar. + /// + /// Note: Dark mode cannot be supported for win32 menus, it's simply not possible to change how + /// the menus look. If you use this, it is recommended that you combine it with + /// `with_theme(Some(Theme::Light))` to avoid a jarring effect. + #[cfg_attr( + windows_platform, + doc = "[`CreateMenu`]: windows_sys::Win32::UI::WindowsAndMessaging::CreateMenu" + )] + #[cfg_attr(not(windows_platform), doc = "[`CreateMenu`]: #only-available-on-windows")] + fn with_menu(self, menu: HMENU) -> Self; + + /// This sets `ICON_BIG`. A good ceiling here is 256x256. + fn with_taskbar_icon(self, taskbar_icon: Option<Icon>) -> Self; + + /// This sets `WS_EX_NOREDIRECTIONBITMAP`. + fn with_no_redirection_bitmap(self, flag: bool) -> Self; + + /// Enables or disables drag and drop support (enabled by default). Will interfere with other + /// crates that use multi-threaded COM API (`CoInitializeEx` with `COINIT_MULTITHREADED` + /// instead of `COINIT_APARTMENTTHREADED`) on the same thread. Note that winit may still + /// attempt to initialize COM API regardless of this option. Currently only fullscreen mode + /// does that, but there may be more in the future. If you need COM API with + /// `COINIT_MULTITHREADED` you must initialize it before calling any winit functions. See <https://docs.microsoft.com/en-us/windows/win32/api/objbase/nf-objbase-coinitialize#remarks> for more information. + fn with_drag_and_drop(self, flag: bool) -> Self; + + /// Whether show or hide the window icon in the taskbar. + fn with_skip_taskbar(self, skip: bool) -> Self; + + /// Customize the window class name. + fn with_class_name<S: Into<String>>(self, class_name: S) -> Self; + + /// Shows or hides the background drop shadow for undecorated windows. + /// + /// The shadow is hidden by default. + /// Enabling the shadow causes a thin 1px line to appear on the top of the window. + fn with_undecorated_shadow(self, shadow: bool) -> Self; + + /// Sets system-drawn backdrop type. + /// + /// Requires Windows 11 build 22523+. + fn with_system_backdrop(self, backdrop_type: BackdropType) -> Self; + + /// This sets or removes `WS_CLIPCHILDREN` style. + fn with_clip_children(self, flag: bool) -> Self; + + /// Sets the color of the window border. + /// + /// Supported starting with Windows 11 Build 22000. + fn with_border_color(self, color: Option<Color>) -> Self; + + /// Sets the background color of the title bar. + /// + /// Supported starting with Windows 11 Build 22000. + fn with_title_background_color(self, color: Option<Color>) -> Self; + + /// Sets the color of the window title. + /// + /// Supported starting with Windows 11 Build 22000. + fn with_title_text_color(self, color: Color) -> Self; + + /// Sets the preferred style of the window corners. + /// + /// Supported starting with Windows 11 Build 22000. + fn with_corner_preference(self, corners: CornerPreference) -> Self; +} + +impl WindowAttributesExtWindows for WindowAttributes { + #[inline] + fn with_owner_window(mut self, parent: HWND) -> Self { + self.platform_specific.owner = Some(parent); + self + } + + #[inline] + fn with_menu(mut self, menu: HMENU) -> Self { + self.platform_specific.menu = Some(menu); + self + } + + #[inline] + fn with_taskbar_icon(mut self, taskbar_icon: Option<Icon>) -> Self { + self.platform_specific.taskbar_icon = taskbar_icon; + self + } + + #[inline] + fn with_no_redirection_bitmap(mut self, flag: bool) -> Self { + self.platform_specific.no_redirection_bitmap = flag; + self + } + + #[inline] + fn with_drag_and_drop(mut self, flag: bool) -> Self { + self.platform_specific.drag_and_drop = flag; + self + } + + #[inline] + fn with_skip_taskbar(mut self, skip: bool) -> Self { + self.platform_specific.skip_taskbar = skip; + self + } + + #[inline] + fn with_class_name<S: Into<String>>(mut self, class_name: S) -> Self { + self.platform_specific.class_name = class_name.into(); + self + } + + #[inline] + fn with_undecorated_shadow(mut self, shadow: bool) -> Self { + self.platform_specific.decoration_shadow = shadow; + self + } + + #[inline] + fn with_system_backdrop(mut self, backdrop_type: BackdropType) -> Self { + self.platform_specific.backdrop_type = backdrop_type; + self + } + + #[inline] + fn with_clip_children(mut self, flag: bool) -> Self { + self.platform_specific.clip_children = flag; + self + } + + #[inline] + fn with_border_color(mut self, color: Option<Color>) -> Self { + self.platform_specific.border_color = Some(color.unwrap_or(Color::NONE)); + self + } + + #[inline] + fn with_title_background_color(mut self, color: Option<Color>) -> Self { + self.platform_specific.title_background_color = Some(color.unwrap_or(Color::NONE)); + self + } + + #[inline] + fn with_title_text_color(mut self, color: Color) -> Self { + self.platform_specific.title_text_color = Some(color); + self + } + + #[inline] + fn with_corner_preference(mut self, corners: CornerPreference) -> Self { + self.platform_specific.corner_preference = Some(corners); + self + } +} + +/// Additional methods on `MonitorHandle` that are specific to Windows. +pub trait MonitorHandleExtWindows { + /// Returns the name of the monitor adapter specific to the Win32 API. + fn native_id(&self) -> String; + + /// Returns the handle of the monitor - `HMONITOR`. + fn hmonitor(&self) -> HMONITOR; +} + +impl MonitorHandleExtWindows for MonitorHandle { + #[inline] + fn native_id(&self) -> String { + self.inner.native_identifier() + } + + #[inline] + fn hmonitor(&self) -> HMONITOR { + self.inner.hmonitor() + } +} + +/// Additional methods on `DeviceId` that are specific to Windows. +pub trait DeviceIdExtWindows { + /// Returns an identifier that persistently refers to this specific device. + /// + /// Will return `None` if the device is no longer available. + fn persistent_identifier(&self) -> Option<String>; +} + +impl DeviceIdExtWindows for DeviceId { + #[inline] + fn persistent_identifier(&self) -> Option<String> { + self.0.persistent_identifier() + } +} + +/// Additional methods on `Icon` that are specific to Windows. +/// +/// Windows icons can be created from files, or from the [`embedded resources`](https://learn.microsoft.com/en-us/windows/win32/menurc/about-resource-files). +/// +/// The `ICON` resource definition statement use the following syntax: +/// ```rc +/// nameID ICON filename +/// ``` +/// `nameID` is a unique name or a 16-bit unsigned integer value identifying the resource, +/// `filename` is the name of the file that contains the resource. +/// +/// More information about the `ICON` resource can be found at [`Microsoft Learn`](https://learn.microsoft.com/en-us/windows/win32/menurc/icon-resource) portal. +pub trait IconExtWindows: Sized { + /// Create an icon from a file path. + /// + /// Specify `size` to load a specific icon size from the file, or `None` to load the default + /// icon size from the file. + /// + /// In cases where the specified size does not exist in the file, Windows may perform scaling + /// to get an icon of the desired size. + fn from_path<P: AsRef<Path>>(path: P, size: Option<PhysicalSize<u32>>) + -> Result<Self, BadIcon>; + + /// Create an icon from a resource embedded in this executable or library by its ordinal id. + /// + /// The valid `ordinal` values range from 1 to [`u16::MAX`] (inclusive). The value `0` is an + /// invalid ordinal id, but it can be used with [`from_resource_name`] as `"0"`. + /// + /// [`from_resource_name`]: IconExtWindows::from_resource_name + /// + /// Specify `size` to load a specific icon size from the file, or `None` to load the default + /// icon size from the file. + /// + /// In cases where the specified size does not exist in the file, Windows may perform scaling + /// to get an icon of the desired size. + fn from_resource(ordinal: u16, size: Option<PhysicalSize<u32>>) -> Result<Self, BadIcon>; + + /// Create an icon from a resource embedded in this executable or library by its name. + /// + /// Specify `size` to load a specific icon size from the file, or `None` to load the default + /// icon size from the file. + /// + /// In cases where the specified size does not exist in the file, Windows may perform scaling + /// to get an icon of the desired size. + /// + /// # Notes + /// + /// Consider the following resource definition statements: + /// ```rc + /// app ICON "app.ico" + /// 1 ICON "a.ico" + /// 0027 ICON "custom.ico" + /// 0 ICON "alt.ico" + /// ``` + /// + /// Due to some internal implementation details of the resource embedding/loading process on + /// Windows platform, strings that can be interpreted as 16-bit unsigned integers (`"1"`, + /// `"002"`, etc.) cannot be used as valid resource names, and instead should be passed into + /// [`from_resource`]: + /// + /// [`from_resource`]: IconExtWindows::from_resource + /// + /// ```rust,no_run + /// use winit::platform::windows::IconExtWindows; + /// use winit::window::Icon; + /// + /// assert!(Icon::from_resource_name("app", None).is_ok()); + /// assert!(Icon::from_resource(1, None).is_ok()); + /// assert!(Icon::from_resource(27, None).is_ok()); + /// assert!(Icon::from_resource_name("27", None).is_err()); + /// assert!(Icon::from_resource_name("0027", None).is_err()); + /// ``` + /// + /// While `0` cannot be used as an ordinal id (see [`from_resource`]), it can be used as a + /// name: + /// + /// [`from_resource`]: IconExtWindows::from_resource + /// + /// ```rust,no_run + /// # use winit::platform::windows::IconExtWindows; + /// # use winit::window::Icon; + /// assert!(Icon::from_resource_name("0", None).is_ok()); + /// assert!(Icon::from_resource(0, None).is_err()); + /// ``` + fn from_resource_name(name: &str, size: Option<PhysicalSize<u32>>) -> Result<Self, BadIcon>; +} + +impl IconExtWindows for Icon { + fn from_path<P: AsRef<Path>>( + path: P, + size: Option<PhysicalSize<u32>>, + ) -> Result<Self, BadIcon> { + let win_icon = crate::platform_impl::WinIcon::from_path(path, size)?; + Ok(Icon { inner: win_icon }) + } + + fn from_resource(ordinal: u16, size: Option<PhysicalSize<u32>>) -> Result<Self, BadIcon> { + let win_icon = crate::platform_impl::WinIcon::from_resource(ordinal, size)?; + Ok(Icon { inner: win_icon }) + } + + fn from_resource_name(name: &str, size: Option<PhysicalSize<u32>>) -> Result<Self, BadIcon> { + let win_icon = crate::platform_impl::WinIcon::from_resource_name(name, size)?; + Ok(Icon { inner: win_icon }) + } +} diff --git a/app/vendor/rune/vendor/winit/src/platform/x11.rs b/app/vendor/rune/vendor/winit/src/platform/x11.rs new file mode 100644 index 0000000..4ab900c --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/platform/x11.rs @@ -0,0 +1,254 @@ +//! # X11 +#[cfg(feature = "serde")] +use serde::{Deserialize, Serialize}; + +use crate::event_loop::{ActiveEventLoop, EventLoop, EventLoopBuilder}; +use crate::monitor::MonitorHandle; +use crate::window::{Window, WindowAttributes}; + +use crate::dpi::Size; + +/// X window type. Maps directly to +/// [`_NET_WM_WINDOW_TYPE`](https://specifications.freedesktop.org/wm-spec/wm-spec-1.5.html). +#[derive(Debug, Default, Copy, Clone, PartialEq, Eq, Hash)] +#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] +pub enum WindowType { + /// A desktop feature. This can include a single window containing desktop icons with the same + /// dimensions as the screen, allowing the desktop environment to have full control of the + /// desktop, without the need for proxying root window clicks. + Desktop, + /// A dock or panel feature. Typically a Window Manager would keep such windows on top of all + /// other windows. + Dock, + /// Toolbar windows. "Torn off" from the main application. + Toolbar, + /// Pinnable menu windows. "Torn off" from the main application. + Menu, + /// A small persistent utility window, such as a palette or toolbox. + Utility, + /// The window is a splash screen displayed as an application is starting up. + Splash, + /// This is a dialog window. + Dialog, + /// A dropdown menu that usually appears when the user clicks on an item in a menu bar. + /// This property is typically used on override-redirect windows. + DropdownMenu, + /// A popup menu that usually appears when the user right clicks on an object. + /// This property is typically used on override-redirect windows. + PopupMenu, + /// A tooltip window. Usually used to show additional information when hovering over an object + /// with the cursor. This property is typically used on override-redirect windows. + Tooltip, + /// The window is a notification. + /// This property is typically used on override-redirect windows. + Notification, + /// This should be used on the windows that are popped up by combo boxes. + /// This property is typically used on override-redirect windows. + Combo, + /// This indicates the window is being dragged. + /// This property is typically used on override-redirect windows. + Dnd, + /// This is a normal, top-level window. + #[default] + Normal, +} + +/// The first argument in the provided hook will be the pointer to `XDisplay` +/// and the second one the pointer to [`XErrorEvent`]. The returned `bool` is an +/// indicator whether the error was handled by the callback. +/// +/// [`XErrorEvent`]: https://linux.die.net/man/3/xerrorevent +pub type XlibErrorHook = + Box<dyn Fn(*mut std::ffi::c_void, *mut std::ffi::c_void) -> bool + Send + Sync>; + +/// A unique identifier for an X11 visual. +pub type XVisualID = u32; + +/// A unique identifier for an X11 window. +pub type XWindow = u32; + +/// Hook to winit's xlib error handling callback. +/// +/// This method is provided as a safe way to handle the errors coming from X11 +/// when using xlib in external crates, like glutin for GLX access. Trying to +/// handle errors by speculating with `XSetErrorHandler` is [`unsafe`]. +/// +/// **Be aware that your hook is always invoked and returning `true` from it will +/// prevent `winit` from getting the error itself. It's wise to always return +/// `false` if you're not initiated the `Sync`.** +/// +/// [`unsafe`]: https://www.remlab.net/op/xlib.shtml +#[inline] +pub fn register_xlib_error_hook(hook: XlibErrorHook) { + // Append new hook. + crate::platform_impl::XLIB_ERROR_HOOKS.lock().unwrap().push(hook); +} + +/// Additional methods on [`ActiveEventLoop`] that are specific to X11. +pub trait ActiveEventLoopExtX11 { + /// True if the [`ActiveEventLoop`] uses X11. + fn is_x11(&self) -> bool; +} + +impl ActiveEventLoopExtX11 for ActiveEventLoop { + #[inline] + fn is_x11(&self) -> bool { + !self.p.is_wayland() + } +} + +/// Additional methods on [`EventLoop`] that are specific to X11. +pub trait EventLoopExtX11 { + /// True if the [`EventLoop`] uses X11. + fn is_x11(&self) -> bool; +} + +impl<T: 'static> EventLoopExtX11 for EventLoop<T> { + #[inline] + fn is_x11(&self) -> bool { + !self.event_loop.is_wayland() + } +} + +/// Additional methods on [`EventLoopBuilder`] that are specific to X11. +pub trait EventLoopBuilderExtX11 { + /// Force using X11. + fn with_x11(&mut self) -> &mut Self; + + /// Whether to allow the event loop to be created off of the main thread. + /// + /// By default, the window is only allowed to be created on the main + /// thread, to make platform compatibility easier. + fn with_any_thread(&mut self, any_thread: bool) -> &mut Self; +} + +impl<T> EventLoopBuilderExtX11 for EventLoopBuilder<T> { + #[inline] + fn with_x11(&mut self) -> &mut Self { + self.platform_specific.forced_backend = Some(crate::platform_impl::Backend::X); + self + } + + #[inline] + fn with_any_thread(&mut self, any_thread: bool) -> &mut Self { + self.platform_specific.any_thread = any_thread; + self + } +} + +/// Additional methods on [`Window`] that are specific to X11. +pub trait WindowExtX11 {} + +impl WindowExtX11 for Window {} + +/// Additional methods on [`WindowAttributes`] that are specific to X11. +pub trait WindowAttributesExtX11 { + /// Create this window with a specific X11 visual. + fn with_x11_visual(self, visual_id: XVisualID) -> Self; + + fn with_x11_screen(self, screen_id: i32) -> Self; + + /// Build window with the given `general` and `instance` names. + /// + /// The `general` sets general class of `WM_CLASS(STRING)`, while `instance` set the + /// instance part of it. The resulted property looks like `WM_CLASS(STRING) = "instance", + /// "general"`. + /// + /// For details about application ID conventions, see the + /// [Desktop Entry Spec](https://specifications.freedesktop.org/desktop-entry-spec/desktop-entry-spec-latest.html#desktop-file-id) + fn with_name(self, general: impl Into<String>, instance: impl Into<String>) -> Self; + + /// Build window with override-redirect flag; defaults to false. + fn with_override_redirect(self, override_redirect: bool) -> Self; + + /// Build window with `_NET_WM_WINDOW_TYPE` hints; defaults to `Normal`. + fn with_x11_window_type(self, x11_window_type: Vec<WindowType>) -> Self; + + /// Build window with base size hint. + /// + /// ``` + /// # use winit::dpi::{LogicalSize, PhysicalSize}; + /// # use winit::window::Window; + /// # use winit::platform::x11::WindowAttributesExtX11; + /// // Specify the size in logical dimensions like this: + /// Window::default_attributes().with_base_size(LogicalSize::new(400.0, 200.0)); + /// + /// // Or specify the size in physical dimensions like this: + /// Window::default_attributes().with_base_size(PhysicalSize::new(400, 200)); + /// ``` + fn with_base_size<S: Into<Size>>(self, base_size: S) -> Self; + + /// Embed this window into another parent window. + /// + /// # Example + /// + /// ```no_run + /// use winit::window::Window; + /// use winit::event_loop::ActiveEventLoop; + /// use winit::platform::x11::{XWindow, WindowAttributesExtX11}; + /// # fn create_window(event_loop: &ActiveEventLoop) -> Result<(), Box<dyn std::error::Error>> { + /// let parent_window_id = std::env::args().nth(1).unwrap().parse::<XWindow>()?; + /// let window_attributes = Window::default_attributes().with_embed_parent_window(parent_window_id); + /// let window = event_loop.create_window(window_attributes)?; + /// # Ok(()) } + /// ``` + fn with_embed_parent_window(self, parent_window_id: XWindow) -> Self; +} + +impl WindowAttributesExtX11 for WindowAttributes { + #[inline] + fn with_x11_visual(mut self, visual_id: XVisualID) -> Self { + self.platform_specific.x11.visual_id = Some(visual_id); + self + } + + #[inline] + fn with_x11_screen(mut self, screen_id: i32) -> Self { + self.platform_specific.x11.screen_id = Some(screen_id); + self + } + + #[inline] + fn with_name(mut self, general: impl Into<String>, instance: impl Into<String>) -> Self { + self.platform_specific.name = + Some(crate::platform_impl::ApplicationName::new(general.into(), instance.into())); + self + } + + #[inline] + fn with_override_redirect(mut self, override_redirect: bool) -> Self { + self.platform_specific.x11.override_redirect = override_redirect; + self + } + + #[inline] + fn with_x11_window_type(mut self, x11_window_types: Vec<WindowType>) -> Self { + self.platform_specific.x11.x11_window_types = x11_window_types; + self + } + + #[inline] + fn with_base_size<S: Into<Size>>(mut self, base_size: S) -> Self { + self.platform_specific.x11.base_size = Some(base_size.into()); + self + } + + #[inline] + fn with_embed_parent_window(mut self, parent_window_id: XWindow) -> Self { + self.platform_specific.x11.embed_window = Some(parent_window_id); + self + } +} + +/// Additional methods on `MonitorHandle` that are specific to X11. +pub trait MonitorHandleExtX11 { + /// Returns the inner identifier of the monitor. + fn native_id(&self) -> u32; +} + +impl MonitorHandleExtX11 for MonitorHandle { + #[inline] + fn native_id(&self) -> u32 { + self.inner.native_identifier() + } +} diff --git a/app/vendor/rune/vendor/winit/src/platform_impl/android/keycodes.rs b/app/vendor/rune/vendor/winit/src/platform_impl/android/keycodes.rs new file mode 100644 index 0000000..207d549 --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/platform_impl/android/keycodes.rs @@ -0,0 +1,608 @@ +use android_activity::input::{KeyAction, KeyEvent, KeyMapChar, Keycode}; +use android_activity::AndroidApp; + +use crate::keyboard::{Key, KeyCode, KeyLocation, NamedKey, NativeKey, NativeKeyCode, PhysicalKey}; + +pub fn to_physical_key(keycode: Keycode) -> PhysicalKey { + PhysicalKey::Code(match keycode { + Keycode::A => KeyCode::KeyA, + Keycode::B => KeyCode::KeyB, + Keycode::C => KeyCode::KeyC, + Keycode::D => KeyCode::KeyD, + Keycode::E => KeyCode::KeyE, + Keycode::F => KeyCode::KeyF, + Keycode::G => KeyCode::KeyG, + Keycode::H => KeyCode::KeyH, + Keycode::I => KeyCode::KeyI, + Keycode::J => KeyCode::KeyJ, + Keycode::K => KeyCode::KeyK, + Keycode::L => KeyCode::KeyL, + Keycode::M => KeyCode::KeyM, + Keycode::N => KeyCode::KeyN, + Keycode::O => KeyCode::KeyO, + Keycode::P => KeyCode::KeyP, + Keycode::Q => KeyCode::KeyQ, + Keycode::R => KeyCode::KeyR, + Keycode::S => KeyCode::KeyS, + Keycode::T => KeyCode::KeyT, + Keycode::U => KeyCode::KeyU, + Keycode::V => KeyCode::KeyV, + Keycode::W => KeyCode::KeyW, + Keycode::X => KeyCode::KeyX, + Keycode::Y => KeyCode::KeyY, + Keycode::Z => KeyCode::KeyZ, + + Keycode::Keycode0 => KeyCode::Digit0, + Keycode::Keycode1 => KeyCode::Digit1, + Keycode::Keycode2 => KeyCode::Digit2, + Keycode::Keycode3 => KeyCode::Digit3, + Keycode::Keycode4 => KeyCode::Digit4, + Keycode::Keycode5 => KeyCode::Digit5, + Keycode::Keycode6 => KeyCode::Digit6, + Keycode::Keycode7 => KeyCode::Digit7, + Keycode::Keycode8 => KeyCode::Digit8, + Keycode::Keycode9 => KeyCode::Digit9, + + Keycode::Numpad0 => KeyCode::Numpad0, + Keycode::Numpad1 => KeyCode::Numpad1, + Keycode::Numpad2 => KeyCode::Numpad2, + Keycode::Numpad3 => KeyCode::Numpad3, + Keycode::Numpad4 => KeyCode::Numpad4, + Keycode::Numpad5 => KeyCode::Numpad5, + Keycode::Numpad6 => KeyCode::Numpad6, + Keycode::Numpad7 => KeyCode::Numpad7, + Keycode::Numpad8 => KeyCode::Numpad8, + Keycode::Numpad9 => KeyCode::Numpad9, + + Keycode::NumpadAdd => KeyCode::NumpadAdd, + Keycode::NumpadSubtract => KeyCode::NumpadSubtract, + Keycode::NumpadMultiply => KeyCode::NumpadMultiply, + Keycode::NumpadDivide => KeyCode::NumpadDivide, + Keycode::NumpadEnter => KeyCode::NumpadEnter, + Keycode::NumpadEquals => KeyCode::NumpadEqual, + Keycode::NumpadComma => KeyCode::NumpadComma, + Keycode::NumpadDot => KeyCode::NumpadDecimal, + Keycode::NumLock => KeyCode::NumLock, + + Keycode::DpadLeft => KeyCode::ArrowLeft, + Keycode::DpadRight => KeyCode::ArrowRight, + Keycode::DpadUp => KeyCode::ArrowUp, + Keycode::DpadDown => KeyCode::ArrowDown, + + Keycode::F1 => KeyCode::F1, + Keycode::F2 => KeyCode::F2, + Keycode::F3 => KeyCode::F3, + Keycode::F4 => KeyCode::F4, + Keycode::F5 => KeyCode::F5, + Keycode::F6 => KeyCode::F6, + Keycode::F7 => KeyCode::F7, + Keycode::F8 => KeyCode::F8, + Keycode::F9 => KeyCode::F9, + Keycode::F10 => KeyCode::F10, + Keycode::F11 => KeyCode::F11, + Keycode::F12 => KeyCode::F12, + + Keycode::Space => KeyCode::Space, + Keycode::Escape => KeyCode::Escape, + Keycode::Enter => KeyCode::Enter, // not on the Numpad + Keycode::Tab => KeyCode::Tab, + + Keycode::PageUp => KeyCode::PageUp, + Keycode::PageDown => KeyCode::PageDown, + Keycode::MoveHome => KeyCode::Home, + Keycode::MoveEnd => KeyCode::End, + Keycode::Insert => KeyCode::Insert, + + Keycode::Del => KeyCode::Backspace, // Backspace (above Enter) + Keycode::ForwardDel => KeyCode::Delete, // Delete (below Insert) + + Keycode::Copy => KeyCode::Copy, + Keycode::Paste => KeyCode::Paste, + Keycode::Cut => KeyCode::Cut, + + Keycode::VolumeUp => KeyCode::AudioVolumeUp, + Keycode::VolumeDown => KeyCode::AudioVolumeDown, + Keycode::VolumeMute => KeyCode::AudioVolumeMute, + // Keycode::Mute => None, // Microphone mute + Keycode::MediaPlayPause => KeyCode::MediaPlayPause, + Keycode::MediaStop => KeyCode::MediaStop, + Keycode::MediaNext => KeyCode::MediaTrackNext, + Keycode::MediaPrevious => KeyCode::MediaTrackPrevious, + + Keycode::Plus => KeyCode::Equal, + Keycode::Minus => KeyCode::Minus, + // Winit doesn't differentiate both '+' and '=', considering they are usually + // on the same physical key + Keycode::Equals => KeyCode::Equal, + Keycode::Semicolon => KeyCode::Semicolon, + Keycode::Slash => KeyCode::Slash, + Keycode::Backslash => KeyCode::Backslash, + Keycode::Comma => KeyCode::Comma, + Keycode::Period => KeyCode::Period, + Keycode::Apostrophe => KeyCode::Quote, + Keycode::Grave => KeyCode::Backquote, + + // Winit doesn't expose a SysRq code, so map to PrintScreen since it's + // usually the same physical key + Keycode::Sysrq => KeyCode::PrintScreen, + // These are usually the same (Pause/Break) + Keycode::Break => KeyCode::Pause, + // These are exactly the same + Keycode::ScrollLock => KeyCode::ScrollLock, + + Keycode::Yen => KeyCode::IntlYen, + Keycode::Kana => KeyCode::Lang1, + Keycode::KatakanaHiragana => KeyCode::KanaMode, + + Keycode::CtrlLeft => KeyCode::ControlLeft, + Keycode::CtrlRight => KeyCode::ControlRight, + + Keycode::ShiftLeft => KeyCode::ShiftLeft, + Keycode::ShiftRight => KeyCode::ShiftRight, + + Keycode::AltLeft => KeyCode::AltLeft, + Keycode::AltRight => KeyCode::AltRight, + + Keycode::MetaLeft => KeyCode::SuperLeft, + Keycode::MetaRight => KeyCode::SuperRight, + + Keycode::LeftBracket => KeyCode::BracketLeft, + Keycode::RightBracket => KeyCode::BracketRight, + + Keycode::Power => KeyCode::Power, + Keycode::Sleep => KeyCode::Sleep, // what about SoftSleep? + Keycode::Wakeup => KeyCode::WakeUp, + + keycode => return PhysicalKey::Unidentified(NativeKeyCode::Android(keycode.into())), + }) +} + +/// Tries to map the `key_event` to a `KeyMapChar` containing a unicode character or dead key accent +/// +/// This takes a `KeyEvent` and looks up its corresponding `KeyCharacterMap` and +/// uses that to try and map the `key_code` + `meta_state` to a unicode +/// character or a dead key that can be combined with the next key press. +pub fn character_map_and_combine_key( + app: &AndroidApp, + key_event: &KeyEvent<'_>, + combining_accent: &mut Option<char>, +) -> Option<KeyMapChar> { + let device_id = key_event.device_id(); + + let key_map = match app.device_key_character_map(device_id) { + Ok(key_map) => key_map, + Err(err) => { + tracing::warn!("Failed to look up `KeyCharacterMap` for device {device_id}: {err:?}"); + return None; + }, + }; + + match key_map.get(key_event.key_code(), key_event.meta_state()) { + Ok(KeyMapChar::Unicode(unicode)) => { + // Only do dead key combining on key down + if key_event.action() == KeyAction::Down { + let combined_unicode = if let Some(accent) = combining_accent { + match key_map.get_dead_char(*accent, unicode) { + Ok(Some(key)) => Some(key), + Ok(None) => None, + Err(err) => { + tracing::warn!( + "KeyEvent: Failed to combine 'dead key' accent '{accent}' with \ + '{unicode}': {err:?}" + ); + None + }, + } + } else { + Some(unicode) + }; + *combining_accent = None; + combined_unicode.map(KeyMapChar::Unicode) + } else { + Some(KeyMapChar::Unicode(unicode)) + } + }, + Ok(KeyMapChar::CombiningAccent(accent)) => { + if key_event.action() == KeyAction::Down { + *combining_accent = Some(accent); + } + Some(KeyMapChar::CombiningAccent(accent)) + }, + Ok(KeyMapChar::None) => { + // Leave any combining_accent state in tact (seems to match how other + // Android apps work) + None + }, + Err(err) => { + tracing::warn!("KeyEvent: Failed to get key map character: {err:?}"); + *combining_accent = None; + None + }, + } +} + +pub fn to_logical(key_char: Option<KeyMapChar>, keycode: Keycode) -> Key { + use android_activity::input::Keycode::*; + + let native = NativeKey::Android(keycode.into()); + + match key_char { + Some(KeyMapChar::Unicode(c)) => Key::Character(smol_str::SmolStr::from_iter([c])), + Some(KeyMapChar::CombiningAccent(c)) => Key::Dead(Some(c)), + None | Some(KeyMapChar::None) => match keycode { + // Using `BrowserHome` instead of `GoHome` according to + // https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key/Key_Values + Home => Key::Named(NamedKey::BrowserHome), + Back => Key::Named(NamedKey::BrowserBack), + Call => Key::Named(NamedKey::Call), + Endcall => Key::Named(NamedKey::EndCall), + + //------------------------------------------------------------------------------- + // These should be redundant because they should have already been matched + // as `KeyMapChar::Unicode`, but also matched here as a fallback + Keycode0 => Key::Character("0".into()), + Keycode1 => Key::Character("1".into()), + Keycode2 => Key::Character("2".into()), + Keycode3 => Key::Character("3".into()), + Keycode4 => Key::Character("4".into()), + Keycode5 => Key::Character("5".into()), + Keycode6 => Key::Character("6".into()), + Keycode7 => Key::Character("7".into()), + Keycode8 => Key::Character("8".into()), + Keycode9 => Key::Character("9".into()), + Star => Key::Character("*".into()), + Pound => Key::Character("#".into()), + A => Key::Character("a".into()), + B => Key::Character("b".into()), + C => Key::Character("c".into()), + D => Key::Character("d".into()), + E => Key::Character("e".into()), + F => Key::Character("f".into()), + G => Key::Character("g".into()), + H => Key::Character("h".into()), + I => Key::Character("i".into()), + J => Key::Character("j".into()), + K => Key::Character("k".into()), + L => Key::Character("l".into()), + M => Key::Character("m".into()), + N => Key::Character("n".into()), + O => Key::Character("o".into()), + P => Key::Character("p".into()), + Q => Key::Character("q".into()), + R => Key::Character("r".into()), + S => Key::Character("s".into()), + T => Key::Character("t".into()), + U => Key::Character("u".into()), + V => Key::Character("v".into()), + W => Key::Character("w".into()), + X => Key::Character("x".into()), + Y => Key::Character("y".into()), + Z => Key::Character("z".into()), + Comma => Key::Character(",".into()), + Period => Key::Character(".".into()), + Grave => Key::Character("`".into()), + Minus => Key::Character("-".into()), + Equals => Key::Character("=".into()), + LeftBracket => Key::Character("[".into()), + RightBracket => Key::Character("]".into()), + Backslash => Key::Character("\\".into()), + Semicolon => Key::Character(";".into()), + Apostrophe => Key::Character("'".into()), + Slash => Key::Character("/".into()), + At => Key::Character("@".into()), + Plus => Key::Character("+".into()), + //------------------------------------------------------------------------------- + DpadUp => Key::Named(NamedKey::ArrowUp), + DpadDown => Key::Named(NamedKey::ArrowDown), + DpadLeft => Key::Named(NamedKey::ArrowLeft), + DpadRight => Key::Named(NamedKey::ArrowRight), + DpadCenter => Key::Named(NamedKey::Enter), + + VolumeUp => Key::Named(NamedKey::AudioVolumeUp), + VolumeDown => Key::Named(NamedKey::AudioVolumeDown), + Power => Key::Named(NamedKey::Power), + Camera => Key::Named(NamedKey::Camera), + Clear => Key::Named(NamedKey::Clear), + + AltLeft => Key::Named(NamedKey::Alt), + AltRight => Key::Named(NamedKey::Alt), + ShiftLeft => Key::Named(NamedKey::Shift), + ShiftRight => Key::Named(NamedKey::Shift), + Tab => Key::Named(NamedKey::Tab), + Space => Key::Named(NamedKey::Space), + Sym => Key::Named(NamedKey::Symbol), + Explorer => Key::Named(NamedKey::LaunchWebBrowser), + Envelope => Key::Named(NamedKey::LaunchMail), + Enter => Key::Named(NamedKey::Enter), + Del => Key::Named(NamedKey::Backspace), + + // According to https://developer.android.com/reference/android/view/KeyEvent#KEYCODE_NUM + Num => Key::Named(NamedKey::Alt), + + Headsethook => Key::Named(NamedKey::HeadsetHook), + Focus => Key::Named(NamedKey::CameraFocus), + + Notification => Key::Named(NamedKey::Notification), + Search => Key::Named(NamedKey::BrowserSearch), + MediaPlayPause => Key::Named(NamedKey::MediaPlayPause), + MediaStop => Key::Named(NamedKey::MediaStop), + MediaNext => Key::Named(NamedKey::MediaTrackNext), + MediaPrevious => Key::Named(NamedKey::MediaTrackPrevious), + MediaRewind => Key::Named(NamedKey::MediaRewind), + MediaFastForward => Key::Named(NamedKey::MediaFastForward), + Mute => Key::Named(NamedKey::MicrophoneVolumeMute), + PageUp => Key::Named(NamedKey::PageUp), + PageDown => Key::Named(NamedKey::PageDown), + + Escape => Key::Named(NamedKey::Escape), + ForwardDel => Key::Named(NamedKey::Delete), + CtrlLeft => Key::Named(NamedKey::Control), + CtrlRight => Key::Named(NamedKey::Control), + CapsLock => Key::Named(NamedKey::CapsLock), + ScrollLock => Key::Named(NamedKey::ScrollLock), + MetaLeft => Key::Named(NamedKey::Super), + MetaRight => Key::Named(NamedKey::Super), + Function => Key::Named(NamedKey::Fn), + Sysrq => Key::Named(NamedKey::PrintScreen), + Break => Key::Named(NamedKey::Pause), + MoveHome => Key::Named(NamedKey::Home), + MoveEnd => Key::Named(NamedKey::End), + Insert => Key::Named(NamedKey::Insert), + Forward => Key::Named(NamedKey::BrowserForward), + MediaPlay => Key::Named(NamedKey::MediaPlay), + MediaPause => Key::Named(NamedKey::MediaPause), + MediaClose => Key::Named(NamedKey::MediaClose), + MediaEject => Key::Named(NamedKey::Eject), + MediaRecord => Key::Named(NamedKey::MediaRecord), + F1 => Key::Named(NamedKey::F1), + F2 => Key::Named(NamedKey::F2), + F3 => Key::Named(NamedKey::F3), + F4 => Key::Named(NamedKey::F4), + F5 => Key::Named(NamedKey::F5), + F6 => Key::Named(NamedKey::F6), + F7 => Key::Named(NamedKey::F7), + F8 => Key::Named(NamedKey::F8), + F9 => Key::Named(NamedKey::F9), + F10 => Key::Named(NamedKey::F10), + F11 => Key::Named(NamedKey::F11), + F12 => Key::Named(NamedKey::F12), + NumLock => Key::Named(NamedKey::NumLock), + Numpad0 => Key::Character("0".into()), + Numpad1 => Key::Character("1".into()), + Numpad2 => Key::Character("2".into()), + Numpad3 => Key::Character("3".into()), + Numpad4 => Key::Character("4".into()), + Numpad5 => Key::Character("5".into()), + Numpad6 => Key::Character("6".into()), + Numpad7 => Key::Character("7".into()), + Numpad8 => Key::Character("8".into()), + Numpad9 => Key::Character("9".into()), + NumpadDivide => Key::Character("/".into()), + NumpadMultiply => Key::Character("*".into()), + NumpadSubtract => Key::Character("-".into()), + NumpadAdd => Key::Character("+".into()), + NumpadDot => Key::Character(".".into()), + NumpadComma => Key::Character(",".into()), + NumpadEnter => Key::Named(NamedKey::Enter), + NumpadEquals => Key::Character("=".into()), + NumpadLeftParen => Key::Character("(".into()), + NumpadRightParen => Key::Character(")".into()), + + VolumeMute => Key::Named(NamedKey::AudioVolumeMute), + Info => Key::Named(NamedKey::Info), + ChannelUp => Key::Named(NamedKey::ChannelUp), + ChannelDown => Key::Named(NamedKey::ChannelDown), + ZoomIn => Key::Named(NamedKey::ZoomIn), + ZoomOut => Key::Named(NamedKey::ZoomOut), + Tv => Key::Named(NamedKey::TV), + Guide => Key::Named(NamedKey::Guide), + Dvr => Key::Named(NamedKey::DVR), + Bookmark => Key::Named(NamedKey::BrowserFavorites), + Captions => Key::Named(NamedKey::ClosedCaptionToggle), + Settings => Key::Named(NamedKey::Settings), + TvPower => Key::Named(NamedKey::TVPower), + TvInput => Key::Named(NamedKey::TVInput), + StbPower => Key::Named(NamedKey::STBPower), + StbInput => Key::Named(NamedKey::STBInput), + AvrPower => Key::Named(NamedKey::AVRPower), + AvrInput => Key::Named(NamedKey::AVRInput), + ProgRed => Key::Named(NamedKey::ColorF0Red), + ProgGreen => Key::Named(NamedKey::ColorF1Green), + ProgYellow => Key::Named(NamedKey::ColorF2Yellow), + ProgBlue => Key::Named(NamedKey::ColorF3Blue), + AppSwitch => Key::Named(NamedKey::AppSwitch), + LanguageSwitch => Key::Named(NamedKey::GroupNext), + MannerMode => Key::Named(NamedKey::MannerMode), + Keycode3dMode => Key::Named(NamedKey::TV3DMode), + Contacts => Key::Named(NamedKey::LaunchContacts), + Calendar => Key::Named(NamedKey::LaunchCalendar), + Music => Key::Named(NamedKey::LaunchMusicPlayer), + Calculator => Key::Named(NamedKey::LaunchApplication2), + ZenkakuHankaku => Key::Named(NamedKey::ZenkakuHankaku), + Eisu => Key::Named(NamedKey::Eisu), + Muhenkan => Key::Named(NamedKey::NonConvert), + Henkan => Key::Named(NamedKey::Convert), + KatakanaHiragana => Key::Named(NamedKey::HiraganaKatakana), + Kana => Key::Named(NamedKey::KanjiMode), + BrightnessDown => Key::Named(NamedKey::BrightnessDown), + BrightnessUp => Key::Named(NamedKey::BrightnessUp), + MediaAudioTrack => Key::Named(NamedKey::MediaAudioTrack), + Sleep => Key::Named(NamedKey::Standby), + Wakeup => Key::Named(NamedKey::WakeUp), + Pairing => Key::Named(NamedKey::Pairing), + MediaTopMenu => Key::Named(NamedKey::MediaTopMenu), + LastChannel => Key::Named(NamedKey::MediaLast), + TvDataService => Key::Named(NamedKey::TVDataService), + VoiceAssist => Key::Named(NamedKey::VoiceDial), + TvRadioService => Key::Named(NamedKey::TVRadioService), + TvTeletext => Key::Named(NamedKey::Teletext), + TvNumberEntry => Key::Named(NamedKey::TVNumberEntry), + TvTerrestrialAnalog => Key::Named(NamedKey::TVTerrestrialAnalog), + TvTerrestrialDigital => Key::Named(NamedKey::TVTerrestrialDigital), + TvSatellite => Key::Named(NamedKey::TVSatellite), + TvSatelliteBs => Key::Named(NamedKey::TVSatelliteBS), + TvSatelliteCs => Key::Named(NamedKey::TVSatelliteCS), + TvSatelliteService => Key::Named(NamedKey::TVSatelliteToggle), + TvNetwork => Key::Named(NamedKey::TVNetwork), + TvAntennaCable => Key::Named(NamedKey::TVAntennaCable), + TvInputHdmi1 => Key::Named(NamedKey::TVInputHDMI1), + TvInputHdmi2 => Key::Named(NamedKey::TVInputHDMI2), + TvInputHdmi3 => Key::Named(NamedKey::TVInputHDMI3), + TvInputHdmi4 => Key::Named(NamedKey::TVInputHDMI4), + TvInputComposite1 => Key::Named(NamedKey::TVInputComposite1), + TvInputComposite2 => Key::Named(NamedKey::TVInputComposite2), + TvInputComponent1 => Key::Named(NamedKey::TVInputComponent1), + TvInputComponent2 => Key::Named(NamedKey::TVInputComponent2), + TvInputVga1 => Key::Named(NamedKey::TVInputVGA1), + TvAudioDescription => Key::Named(NamedKey::TVAudioDescription), + TvAudioDescriptionMixUp => Key::Named(NamedKey::TVAudioDescriptionMixUp), + TvAudioDescriptionMixDown => Key::Named(NamedKey::TVAudioDescriptionMixDown), + TvZoomMode => Key::Named(NamedKey::ZoomToggle), + TvContentsMenu => Key::Named(NamedKey::TVContentsMenu), + TvMediaContextMenu => Key::Named(NamedKey::TVMediaContext), + TvTimerProgramming => Key::Named(NamedKey::TVTimer), + Help => Key::Named(NamedKey::Help), + NavigatePrevious => Key::Named(NamedKey::NavigatePrevious), + NavigateNext => Key::Named(NamedKey::NavigateNext), + NavigateIn => Key::Named(NamedKey::NavigateIn), + NavigateOut => Key::Named(NamedKey::NavigateOut), + MediaSkipForward => Key::Named(NamedKey::MediaSkipForward), + MediaSkipBackward => Key::Named(NamedKey::MediaSkipBackward), + MediaStepForward => Key::Named(NamedKey::MediaStepForward), + MediaStepBackward => Key::Named(NamedKey::MediaStepBackward), + Cut => Key::Named(NamedKey::Cut), + Copy => Key::Named(NamedKey::Copy), + Paste => Key::Named(NamedKey::Paste), + Refresh => Key::Named(NamedKey::BrowserRefresh), + + // ----------------------------------------------------------------- + // Keycodes that don't have a logical Key mapping + // ----------------------------------------------------------------- + Unknown => Key::Unidentified(native), + + // Can be added on demand + SoftLeft => Key::Unidentified(native), + SoftRight => Key::Unidentified(native), + + Menu => Key::Unidentified(native), + + Pictsymbols => Key::Unidentified(native), + SwitchCharset => Key::Unidentified(native), + + // ----------------------------------------------------------------- + // Gamepad events should be exposed through a separate API, not + // keyboard events + ButtonA => Key::Unidentified(native), + ButtonB => Key::Unidentified(native), + ButtonC => Key::Unidentified(native), + ButtonX => Key::Unidentified(native), + ButtonY => Key::Unidentified(native), + ButtonZ => Key::Unidentified(native), + ButtonL1 => Key::Unidentified(native), + ButtonR1 => Key::Unidentified(native), + ButtonL2 => Key::Unidentified(native), + ButtonR2 => Key::Unidentified(native), + ButtonThumbl => Key::Unidentified(native), + ButtonThumbr => Key::Unidentified(native), + ButtonStart => Key::Unidentified(native), + ButtonSelect => Key::Unidentified(native), + ButtonMode => Key::Unidentified(native), + // ----------------------------------------------------------------- + Window => Key::Unidentified(native), + + Button1 => Key::Unidentified(native), + Button2 => Key::Unidentified(native), + Button3 => Key::Unidentified(native), + Button4 => Key::Unidentified(native), + Button5 => Key::Unidentified(native), + Button6 => Key::Unidentified(native), + Button7 => Key::Unidentified(native), + Button8 => Key::Unidentified(native), + Button9 => Key::Unidentified(native), + Button10 => Key::Unidentified(native), + Button11 => Key::Unidentified(native), + Button12 => Key::Unidentified(native), + Button13 => Key::Unidentified(native), + Button14 => Key::Unidentified(native), + Button15 => Key::Unidentified(native), + Button16 => Key::Unidentified(native), + + Yen => Key::Unidentified(native), + Ro => Key::Unidentified(native), + + Assist => Key::Unidentified(native), + + Keycode11 => Key::Unidentified(native), + Keycode12 => Key::Unidentified(native), + + StemPrimary => Key::Unidentified(native), + Stem1 => Key::Unidentified(native), + Stem2 => Key::Unidentified(native), + Stem3 => Key::Unidentified(native), + + DpadUpLeft => Key::Unidentified(native), + DpadDownLeft => Key::Unidentified(native), + DpadUpRight => Key::Unidentified(native), + DpadDownRight => Key::Unidentified(native), + + SoftSleep => Key::Unidentified(native), + + SystemNavigationUp => Key::Unidentified(native), + SystemNavigationDown => Key::Unidentified(native), + SystemNavigationLeft => Key::Unidentified(native), + SystemNavigationRight => Key::Unidentified(native), + + AllApps => Key::Unidentified(native), + ThumbsUp => Key::Unidentified(native), + ThumbsDown => Key::Unidentified(native), + ProfileSwitch => Key::Unidentified(native), + + // It's always possible that new versions of Android could introduce + // key codes we can't know about at compile time. + _ => Key::Unidentified(native), + }, + } +} + +pub fn to_location(keycode: Keycode) -> KeyLocation { + use android_activity::input::Keycode::*; + + match keycode { + AltLeft => KeyLocation::Left, + AltRight => KeyLocation::Right, + ShiftLeft => KeyLocation::Left, + ShiftRight => KeyLocation::Right, + + // According to https://developer.android.com/reference/android/view/KeyEvent#KEYCODE_NUM + Num => KeyLocation::Left, + + CtrlLeft => KeyLocation::Left, + CtrlRight => KeyLocation::Right, + MetaLeft => KeyLocation::Left, + MetaRight => KeyLocation::Right, + + NumLock => KeyLocation::Numpad, + Numpad0 => KeyLocation::Numpad, + Numpad1 => KeyLocation::Numpad, + Numpad2 => KeyLocation::Numpad, + Numpad3 => KeyLocation::Numpad, + Numpad4 => KeyLocation::Numpad, + Numpad5 => KeyLocation::Numpad, + Numpad6 => KeyLocation::Numpad, + Numpad7 => KeyLocation::Numpad, + Numpad8 => KeyLocation::Numpad, + Numpad9 => KeyLocation::Numpad, + NumpadDivide => KeyLocation::Numpad, + NumpadMultiply => KeyLocation::Numpad, + NumpadSubtract => KeyLocation::Numpad, + NumpadAdd => KeyLocation::Numpad, + NumpadDot => KeyLocation::Numpad, + NumpadComma => KeyLocation::Numpad, + NumpadEnter => KeyLocation::Numpad, + NumpadEquals => KeyLocation::Numpad, + NumpadLeftParen => KeyLocation::Numpad, + NumpadRightParen => KeyLocation::Numpad, + + _ => KeyLocation::Standard, + } +} diff --git a/app/vendor/rune/vendor/winit/src/platform_impl/android/mod.rs b/app/vendor/rune/vendor/winit/src/platform_impl/android/mod.rs new file mode 100644 index 0000000..c6a7416 --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/platform_impl/android/mod.rs @@ -0,0 +1,1141 @@ +use std::cell::Cell; +use std::collections::VecDeque; +use std::hash::Hash; +use std::marker::PhantomData; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::{mpsc, Arc, Mutex}; +use std::time::{Duration, Instant}; + +use android_activity::input::{InputEvent, KeyAction, Keycode, MotionAction}; +use android_activity::{ + AndroidApp, AndroidAppWaker, ConfigurationRef, InputStatus, MainEvent, Rect, +}; +use tracing::{debug, trace, warn}; + +use crate::cursor::Cursor; +use crate::dpi::{PhysicalPosition, PhysicalSize, Position, Size}; +use crate::error; +use crate::error::EventLoopError; +use crate::event::{self, Force, InnerSizeWriter, StartCause}; +use crate::event_loop::{self, ActiveEventLoop as RootAEL, ControlFlow, DeviceEvents}; +use crate::platform::pump_events::PumpStatus; +use crate::platform_impl::Fullscreen; +use crate::window::{ + self, CursorGrabMode, CustomCursor, CustomCursorSource, ImePurpose, ResizeDirection, Theme, + WindowButtons, WindowLevel, +}; + +mod keycodes; + +pub(crate) use crate::cursor::{ + NoCustomCursor as PlatformCustomCursor, NoCustomCursor as PlatformCustomCursorSource, +}; +pub(crate) use crate::icon::NoIcon as PlatformIcon; + +static HAS_FOCUS: AtomicBool = AtomicBool::new(true); + +/// Returns the minimum `Option<Duration>`, taking into account that `None` +/// equates to an infinite timeout, not a zero timeout (so can't just use +/// `Option::min`) +fn min_timeout(a: Option<Duration>, b: Option<Duration>) -> Option<Duration> { + a.map_or(b, |a_timeout| b.map_or(Some(a_timeout), |b_timeout| Some(a_timeout.min(b_timeout)))) +} + +struct PeekableReceiver<T> { + recv: mpsc::Receiver<T>, + first: Option<T>, +} + +impl<T> PeekableReceiver<T> { + pub fn from_recv(recv: mpsc::Receiver<T>) -> Self { + Self { recv, first: None } + } + + pub fn has_incoming(&mut self) -> bool { + if self.first.is_some() { + return true; + } + match self.recv.try_recv() { + Ok(v) => { + self.first = Some(v); + true + }, + Err(mpsc::TryRecvError::Empty) => false, + Err(mpsc::TryRecvError::Disconnected) => { + warn!("Channel was disconnected when checking incoming"); + false + }, + } + } + + pub fn try_recv(&mut self) -> Result<T, mpsc::TryRecvError> { + if let Some(first) = self.first.take() { + return Ok(first); + } + self.recv.try_recv() + } +} + +#[derive(Clone)] +struct SharedFlagSetter { + flag: Arc<AtomicBool>, +} +impl SharedFlagSetter { + pub fn set(&self) -> bool { + self.flag.compare_exchange(false, true, Ordering::AcqRel, Ordering::Relaxed).is_ok() + } +} + +struct SharedFlag { + flag: Arc<AtomicBool>, +} + +// Used for queuing redraws from arbitrary threads. We don't care how many +// times a redraw is requested (so don't actually need to queue any data, +// we just need to know at the start of a main loop iteration if a redraw +// was queued and be able to read and clear the state atomically) +impl SharedFlag { + pub fn new() -> Self { + Self { flag: Arc::new(AtomicBool::new(false)) } + } + + pub fn setter(&self) -> SharedFlagSetter { + SharedFlagSetter { flag: self.flag.clone() } + } + + pub fn get_and_reset(&self) -> bool { + self.flag.swap(false, std::sync::atomic::Ordering::AcqRel) + } +} + +#[derive(Clone)] +pub struct RedrawRequester { + flag: SharedFlagSetter, + waker: AndroidAppWaker, +} + +impl RedrawRequester { + fn new(flag: &SharedFlag, waker: AndroidAppWaker) -> Self { + RedrawRequester { flag: flag.setter(), waker } + } + + pub fn request_redraw(&self) { + if self.flag.set() { + // Only explicitly try to wake up the main loop when the flag + // value changes + self.waker.wake(); + } + } +} + +#[derive(Debug, Clone, Eq, PartialEq, Hash)] +pub struct KeyEventExtra {} + +pub struct EventLoop<T: 'static> { + pub(crate) android_app: AndroidApp, + window_target: event_loop::ActiveEventLoop, + redraw_flag: SharedFlag, + user_events_sender: mpsc::Sender<T>, + user_events_receiver: PeekableReceiver<T>, // must wake looper whenever something gets sent + loop_running: bool, // Dispatched `NewEvents<Init>` + running: bool, + pending_redraw: bool, + cause: StartCause, + ignore_volume_keys: bool, + combining_accent: Option<char>, +} + +#[derive(Debug, Clone, PartialEq)] +pub(crate) struct PlatformSpecificEventLoopAttributes { + pub(crate) android_app: Option<AndroidApp>, + pub(crate) ignore_volume_keys: bool, +} + +impl Default for PlatformSpecificEventLoopAttributes { + fn default() -> Self { + Self { android_app: Default::default(), ignore_volume_keys: true } + } +} + +impl<T: 'static> EventLoop<T> { + pub(crate) fn new( + attributes: &PlatformSpecificEventLoopAttributes, + ) -> Result<Self, EventLoopError> { + let (user_events_sender, user_events_receiver) = mpsc::channel(); + + let android_app = attributes.android_app.as_ref().expect( + "An `AndroidApp` as passed to android_main() is required to create an `EventLoop` on \ + Android", + ); + let redraw_flag = SharedFlag::new(); + + Ok(Self { + android_app: android_app.clone(), + window_target: event_loop::ActiveEventLoop { + p: ActiveEventLoop { + app: android_app.clone(), + control_flow: Cell::new(ControlFlow::default()), + exit: Cell::new(false), + redraw_requester: RedrawRequester::new( + &redraw_flag, + android_app.create_waker(), + ), + }, + _marker: PhantomData, + }, + redraw_flag, + user_events_sender, + user_events_receiver: PeekableReceiver::from_recv(user_events_receiver), + loop_running: false, + running: false, + pending_redraw: false, + cause: StartCause::Init, + ignore_volume_keys: attributes.ignore_volume_keys, + combining_accent: None, + }) + } + + fn single_iteration<F>(&mut self, main_event: Option<MainEvent<'_>>, callback: &mut F) + where + F: FnMut(event::Event<T>, &RootAEL), + { + trace!("Mainloop iteration"); + + let cause = self.cause; + let mut pending_redraw = self.pending_redraw; + let mut resized = false; + + callback(event::Event::NewEvents(cause), self.window_target()); + + if let Some(event) = main_event { + trace!("Handling main event {:?}", event); + + match event { + MainEvent::InitWindow { .. } => { + callback(event::Event::Resumed, self.window_target()); + }, + MainEvent::TerminateWindow { .. } => { + callback(event::Event::Suspended, self.window_target()); + }, + MainEvent::WindowResized { .. } => resized = true, + MainEvent::RedrawNeeded { .. } => pending_redraw = true, + MainEvent::ContentRectChanged { .. } => { + warn!("TODO: find a way to notify application of content rect change"); + }, + MainEvent::GainedFocus => { + HAS_FOCUS.store(true, Ordering::Relaxed); + callback( + event::Event::WindowEvent { + window_id: window::WindowId(WindowId), + event: event::WindowEvent::Focused(true), + }, + self.window_target(), + ); + }, + MainEvent::LostFocus => { + HAS_FOCUS.store(false, Ordering::Relaxed); + callback( + event::Event::WindowEvent { + window_id: window::WindowId(WindowId), + event: event::WindowEvent::Focused(false), + }, + self.window_target(), + ); + }, + MainEvent::ConfigChanged { .. } => { + let monitor = MonitorHandle::new(self.android_app.clone()); + let old_scale_factor = monitor.scale_factor(); + let scale_factor = monitor.scale_factor(); + if (scale_factor - old_scale_factor).abs() < f64::EPSILON { + let new_inner_size = Arc::new(Mutex::new( + MonitorHandle::new(self.android_app.clone()).size(), + )); + let event = event::Event::WindowEvent { + window_id: window::WindowId(WindowId), + event: event::WindowEvent::ScaleFactorChanged { + inner_size_writer: InnerSizeWriter::new(Arc::downgrade( + &new_inner_size, + )), + scale_factor, + }, + }; + callback(event, self.window_target()); + } + }, + MainEvent::LowMemory => { + callback(event::Event::MemoryWarning, self.window_target()); + }, + MainEvent::Start => { + // XXX: how to forward this state to applications? + warn!("TODO: forward onStart notification to application"); + }, + MainEvent::Resume { .. } => { + debug!("App Resumed - is running"); + self.running = true; + }, + MainEvent::SaveState { .. } => { + // XXX: how to forward this state to applications? + // XXX: also how do we expose state restoration to apps? + warn!("TODO: forward saveState notification to application"); + }, + MainEvent::Pause => { + debug!("App Paused - stopped running"); + self.running = false; + }, + MainEvent::Stop => { + // XXX: how to forward this state to applications? + warn!("TODO: forward onStop notification to application"); + }, + MainEvent::Destroy => { + // XXX: maybe exit mainloop to drop things before being + // killed by the OS? + warn!("TODO: forward onDestroy notification to application"); + }, + MainEvent::InsetsChanged { .. } => { + // XXX: how to forward this state to applications? + warn!("TODO: handle Android InsetsChanged notification"); + }, + unknown => { + trace!("Unknown MainEvent {unknown:?} (ignored)"); + }, + } + } else { + trace!("No main event to handle"); + } + + // temporarily decouple `android_app` from `self` so we aren't holding + // a borrow of `self` while iterating + let android_app = self.android_app.clone(); + + // Process input events + match android_app.input_events_iter() { + Ok(mut input_iter) => loop { + let read_event = + input_iter.next(|event| self.handle_input_event(&android_app, event, callback)); + + if !read_event { + break; + } + }, + Err(err) => { + tracing::warn!("Failed to get input events iterator: {err:?}"); + }, + } + + // Empty the user event buffer + { + while let Ok(event) = self.user_events_receiver.try_recv() { + callback(crate::event::Event::UserEvent(event), self.window_target()); + } + } + + if self.running { + if resized { + let size = if let Some(native_window) = self.android_app.native_window().as_ref() { + let width = native_window.width() as _; + let height = native_window.height() as _; + PhysicalSize::new(width, height) + } else { + PhysicalSize::new(0, 0) + }; + let event = event::Event::WindowEvent { + window_id: window::WindowId(WindowId), + event: event::WindowEvent::Resized(size), + }; + callback(event, self.window_target()); + } + + pending_redraw |= self.redraw_flag.get_and_reset(); + if pending_redraw { + pending_redraw = false; + let event = event::Event::WindowEvent { + window_id: window::WindowId(WindowId), + event: event::WindowEvent::RedrawRequested, + }; + callback(event, self.window_target()); + } + } + + // This is always the last event we dispatch before poll again + callback(event::Event::AboutToWait, self.window_target()); + + self.pending_redraw = pending_redraw; + } + + fn handle_input_event<F>( + &mut self, + android_app: &AndroidApp, + event: &InputEvent<'_>, + callback: &mut F, + ) -> InputStatus + where + F: FnMut(event::Event<T>, &RootAEL), + { + let mut input_status = InputStatus::Handled; + match event { + InputEvent::MotionEvent(motion_event) => { + let window_id = window::WindowId(WindowId); + let device_id = event::DeviceId(DeviceId(motion_event.device_id())); + + let phase = match motion_event.action() { + MotionAction::Down | MotionAction::PointerDown => { + Some(event::TouchPhase::Started) + }, + MotionAction::Up | MotionAction::PointerUp => Some(event::TouchPhase::Ended), + MotionAction::Move => Some(event::TouchPhase::Moved), + MotionAction::Cancel => Some(event::TouchPhase::Cancelled), + _ => { + None // TODO mouse events + }, + }; + if let Some(phase) = phase { + let pointers: Box<dyn Iterator<Item = android_activity::input::Pointer<'_>>> = + match phase { + event::TouchPhase::Started | event::TouchPhase::Ended => { + Box::new(std::iter::once( + motion_event.pointer_at_index(motion_event.pointer_index()), + )) + }, + event::TouchPhase::Moved | event::TouchPhase::Cancelled => { + Box::new(motion_event.pointers()) + }, + }; + + for pointer in pointers { + let location = + PhysicalPosition { x: pointer.x() as _, y: pointer.y() as _ }; + trace!( + "Input event {device_id:?}, {phase:?}, loc={location:?}, \ + pointer={pointer:?}" + ); + let event = event::Event::WindowEvent { + window_id, + event: event::WindowEvent::Touch(event::Touch { + device_id, + phase, + location, + id: pointer.pointer_id() as u64, + force: Some(Force::Normalized(pointer.pressure() as f64)), + }), + }; + callback(event, self.window_target()); + } + } + }, + InputEvent::KeyEvent(key) => { + match key.key_code() { + // Flag keys related to volume as unhandled. While winit does not have a way for + // applications to configure what keys to flag as handled, + // this appears to be a good default until winit + // can be configured. + Keycode::VolumeUp | Keycode::VolumeDown | Keycode::VolumeMute + if self.ignore_volume_keys => + { + input_status = InputStatus::Unhandled + }, + keycode => { + let state = match key.action() { + KeyAction::Down => event::ElementState::Pressed, + KeyAction::Up => event::ElementState::Released, + _ => event::ElementState::Released, + }; + + let key_char = keycodes::character_map_and_combine_key( + android_app, + key, + &mut self.combining_accent, + ); + + let logical_key = keycodes::to_logical(key_char, keycode); + let text = if state == event::ElementState::Pressed { + logical_key.to_text().map(smol_str::SmolStr::new) + } else { + None + }; + + let event = event::Event::WindowEvent { + window_id: window::WindowId(WindowId), + event: event::WindowEvent::KeyboardInput { + device_id: event::DeviceId(DeviceId(key.device_id())), + event: event::KeyEvent { + state, + physical_key: keycodes::to_physical_key(keycode), + logical_key, + location: keycodes::to_location(keycode), + repeat: key.repeat_count() > 0, + text, + platform_specific: KeyEventExtra {}, + }, + is_synthetic: false, + }, + }; + callback(event, self.window_target()); + }, + } + }, + _ => { + warn!("Unknown android_activity input event {event:?}") + }, + } + + input_status + } + + pub fn run<F>(mut self, event_handler: F) -> Result<(), EventLoopError> + where + F: FnMut(event::Event<T>, &event_loop::ActiveEventLoop), + { + self.run_on_demand(event_handler) + } + + pub fn run_on_demand<F>(&mut self, mut event_handler: F) -> Result<(), EventLoopError> + where + F: FnMut(event::Event<T>, &event_loop::ActiveEventLoop), + { + loop { + match self.pump_events(None, &mut event_handler) { + PumpStatus::Exit(0) => { + break Ok(()); + }, + PumpStatus::Exit(code) => { + break Err(EventLoopError::ExitFailure(code)); + }, + _ => { + continue; + }, + } + } + } + + pub fn pump_events<F>(&mut self, timeout: Option<Duration>, mut callback: F) -> PumpStatus + where + F: FnMut(event::Event<T>, &RootAEL), + { + if !self.loop_running { + self.loop_running = true; + + // Reset the internal state for the loop as we start running to + // ensure consistent behaviour in case the loop runs and exits more + // than once + self.pending_redraw = false; + self.cause = StartCause::Init; + + // run the initial loop iteration + self.single_iteration(None, &mut callback); + } + + // Consider the possibility that the `StartCause::Init` iteration could + // request to Exit + if !self.exiting() { + self.poll_events_with_timeout(timeout, &mut callback); + } + if self.exiting() { + self.loop_running = false; + + callback(event::Event::LoopExiting, self.window_target()); + + PumpStatus::Exit(0) + } else { + PumpStatus::Continue + } + } + + fn poll_events_with_timeout<F>(&mut self, mut timeout: Option<Duration>, mut callback: F) + where + F: FnMut(event::Event<T>, &RootAEL), + { + let start = Instant::now(); + + self.pending_redraw |= self.redraw_flag.get_and_reset(); + + timeout = + if self.running && (self.pending_redraw || self.user_events_receiver.has_incoming()) { + // If we already have work to do then we don't want to block on the next poll + Some(Duration::ZERO) + } else { + let control_flow_timeout = match self.control_flow() { + ControlFlow::Wait => None, + ControlFlow::Poll => Some(Duration::ZERO), + ControlFlow::WaitUntil(wait_deadline) => { + Some(wait_deadline.saturating_duration_since(start)) + }, + }; + + min_timeout(control_flow_timeout, timeout) + }; + + let app = self.android_app.clone(); // Don't borrow self as part of poll expression + app.poll_events(timeout, |poll_event| { + let mut main_event = None; + + match poll_event { + android_activity::PollEvent::Wake => { + // In the X11 backend it's noted that too many false-positive wake ups + // would cause the event loop to run continuously. They handle this by + // re-checking for pending events (assuming they cover all + // valid reasons for a wake up). + // + // For now, user_events and redraw_requests are the only reasons to expect + // a wake up here so we can ignore the wake up if there are no events/requests. + // We also ignore wake ups while suspended. + self.pending_redraw |= self.redraw_flag.get_and_reset(); + if !self.running + || (!self.pending_redraw && !self.user_events_receiver.has_incoming()) + { + return; + } + }, + android_activity::PollEvent::Timeout => {}, + android_activity::PollEvent::Main(event) => { + main_event = Some(event); + }, + unknown_event => { + warn!("Unknown poll event {unknown_event:?} (ignored)"); + }, + } + + self.cause = match self.control_flow() { + ControlFlow::Poll => StartCause::Poll, + ControlFlow::Wait => StartCause::WaitCancelled { start, requested_resume: None }, + ControlFlow::WaitUntil(deadline) => { + if Instant::now() < deadline { + StartCause::WaitCancelled { start, requested_resume: Some(deadline) } + } else { + StartCause::ResumeTimeReached { start, requested_resume: deadline } + } + }, + }; + + self.single_iteration(main_event, &mut callback); + }); + } + + pub fn window_target(&self) -> &event_loop::ActiveEventLoop { + &self.window_target + } + + pub fn create_proxy(&self) -> EventLoopProxy<T> { + EventLoopProxy { + user_events_sender: self.user_events_sender.clone(), + waker: self.android_app.create_waker(), + } + } + + fn control_flow(&self) -> ControlFlow { + self.window_target.p.control_flow() + } + + fn exiting(&self) -> bool { + self.window_target.p.exiting() + } +} + +pub struct EventLoopProxy<T: 'static> { + user_events_sender: mpsc::Sender<T>, + waker: AndroidAppWaker, +} + +impl<T: 'static> Clone for EventLoopProxy<T> { + fn clone(&self) -> Self { + EventLoopProxy { + user_events_sender: self.user_events_sender.clone(), + waker: self.waker.clone(), + } + } +} + +impl<T> EventLoopProxy<T> { + pub fn send_event(&self, event: T) -> Result<(), event_loop::EventLoopClosed<T>> { + self.user_events_sender.send(event).map_err(|err| event_loop::EventLoopClosed(err.0))?; + self.waker.wake(); + Ok(()) + } +} + +pub struct ActiveEventLoop { + pub(crate) app: AndroidApp, + control_flow: Cell<ControlFlow>, + exit: Cell<bool>, + redraw_requester: RedrawRequester, +} + +impl ActiveEventLoop { + pub fn primary_monitor(&self) -> Option<MonitorHandle> { + Some(MonitorHandle::new(self.app.clone())) + } + + pub fn create_custom_cursor(&self, source: CustomCursorSource) -> CustomCursor { + let _ = source.inner; + CustomCursor { inner: PlatformCustomCursor } + } + + pub fn available_monitors(&self) -> VecDeque<MonitorHandle> { + let mut v = VecDeque::with_capacity(1); + v.push_back(MonitorHandle::new(self.app.clone())); + v + } + + #[inline] + pub fn listen_device_events(&self, _allowed: DeviceEvents) {} + + #[cfg(feature = "rwh_05")] + #[inline] + pub fn raw_display_handle_rwh_05(&self) -> rwh_05::RawDisplayHandle { + rwh_05::RawDisplayHandle::Android(rwh_05::AndroidDisplayHandle::empty()) + } + + #[inline] + pub fn system_theme(&self) -> Option<Theme> { + None + } + + #[cfg(feature = "rwh_06")] + #[inline] + pub fn raw_display_handle_rwh_06( + &self, + ) -> Result<rwh_06::RawDisplayHandle, rwh_06::HandleError> { + Ok(rwh_06::RawDisplayHandle::Android(rwh_06::AndroidDisplayHandle::new())) + } + + pub(crate) fn set_control_flow(&self, control_flow: ControlFlow) { + self.control_flow.set(control_flow) + } + + pub(crate) fn control_flow(&self) -> ControlFlow { + self.control_flow.get() + } + + pub(crate) fn exit(&self) { + self.exit.set(true) + } + + pub(crate) fn clear_exit(&self) { + self.exit.set(false) + } + + pub(crate) fn exiting(&self) -> bool { + self.exit.get() + } + + pub(crate) fn owned_display_handle(&self) -> OwnedDisplayHandle { + OwnedDisplayHandle + } +} + +#[derive(Clone)] +pub(crate) struct OwnedDisplayHandle; + +impl OwnedDisplayHandle { + #[cfg(feature = "rwh_05")] + #[inline] + pub fn raw_display_handle_rwh_05(&self) -> rwh_05::RawDisplayHandle { + rwh_05::AndroidDisplayHandle::empty().into() + } + + #[cfg(feature = "rwh_06")] + #[inline] + pub fn raw_display_handle_rwh_06( + &self, + ) -> Result<rwh_06::RawDisplayHandle, rwh_06::HandleError> { + Ok(rwh_06::AndroidDisplayHandle::new().into()) + } +} + +#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] +pub(crate) struct WindowId; + +impl WindowId { + pub const fn dummy() -> Self { + WindowId + } +} + +impl From<WindowId> for u64 { + fn from(_: WindowId) -> Self { + 0 + } +} + +impl From<u64> for WindowId { + fn from(_: u64) -> Self { + Self + } +} + +#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] +pub struct DeviceId(i32); + +impl DeviceId { + pub const fn dummy() -> Self { + DeviceId(0) + } +} + +#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)] +pub struct PlatformSpecificWindowAttributes; + +pub(crate) struct Window { + app: AndroidApp, + redraw_requester: RedrawRequester, +} + +impl Window { + pub(crate) fn new( + el: &ActiveEventLoop, + _window_attrs: window::WindowAttributes, + ) -> Result<Self, error::OsError> { + // FIXME this ignores requested window attributes + + Ok(Self { app: el.app.clone(), redraw_requester: el.redraw_requester.clone() }) + } + + pub(crate) fn maybe_queue_on_main(&self, f: impl FnOnce(&Self) + Send + 'static) { + f(self) + } + + pub(crate) fn maybe_wait_on_main<R: Send>(&self, f: impl FnOnce(&Self) -> R + Send) -> R { + f(self) + } + + pub fn id(&self) -> WindowId { + WindowId + } + + pub fn primary_monitor(&self) -> Option<MonitorHandle> { + Some(MonitorHandle::new(self.app.clone())) + } + + pub fn available_monitors(&self) -> VecDeque<MonitorHandle> { + let mut v = VecDeque::with_capacity(1); + v.push_back(MonitorHandle::new(self.app.clone())); + v + } + + pub fn current_monitor(&self) -> Option<MonitorHandle> { + Some(MonitorHandle::new(self.app.clone())) + } + + pub fn scale_factor(&self) -> f64 { + MonitorHandle::new(self.app.clone()).scale_factor() + } + + pub fn request_redraw(&self) { + self.redraw_requester.request_redraw() + } + + pub fn pre_present_notify(&self) {} + + pub fn inner_position(&self) -> Result<PhysicalPosition<i32>, error::NotSupportedError> { + Err(error::NotSupportedError::new()) + } + + pub fn outer_position(&self) -> Result<PhysicalPosition<i32>, error::NotSupportedError> { + Err(error::NotSupportedError::new()) + } + + pub fn set_outer_position(&self, _position: Position) { + // no effect + } + + pub fn inner_size(&self) -> PhysicalSize<u32> { + self.outer_size() + } + + pub fn request_inner_size(&self, _size: Size) -> Option<PhysicalSize<u32>> { + Some(self.inner_size()) + } + + pub fn outer_size(&self) -> PhysicalSize<u32> { + MonitorHandle::new(self.app.clone()).size() + } + + pub fn set_min_inner_size(&self, _: Option<Size>) {} + + pub fn set_max_inner_size(&self, _: Option<Size>) {} + + pub fn resize_increments(&self) -> Option<PhysicalSize<u32>> { + None + } + + pub fn set_resize_increments(&self, _increments: Option<Size>) {} + + pub fn set_title(&self, _title: &str) {} + + pub fn set_transparent(&self, _transparent: bool) {} + + pub fn set_blur(&self, _blur: bool) {} + + pub fn set_visible(&self, _visibility: bool) {} + + pub fn is_visible(&self) -> Option<bool> { + None + } + + pub fn set_resizable(&self, _resizeable: bool) {} + + pub fn is_resizable(&self) -> bool { + false + } + + pub fn set_enabled_buttons(&self, _buttons: WindowButtons) {} + + pub fn enabled_buttons(&self) -> WindowButtons { + WindowButtons::all() + } + + pub fn set_minimized(&self, _minimized: bool) {} + + pub fn is_minimized(&self) -> Option<bool> { + None + } + + pub fn set_maximized(&self, _maximized: bool) {} + + pub fn is_maximized(&self) -> bool { + false + } + + pub fn set_fullscreen(&self, _monitor: Option<Fullscreen>) { + warn!("Cannot set fullscreen on Android"); + } + + pub fn fullscreen(&self) -> Option<Fullscreen> { + None + } + + pub fn set_decorations(&self, _decorations: bool) {} + + pub fn is_decorated(&self) -> bool { + true + } + + pub fn set_window_level(&self, _level: WindowLevel) {} + + pub fn set_window_icon(&self, _window_icon: Option<crate::icon::Icon>) {} + + pub fn set_ime_cursor_area(&self, _position: Position, _size: Size) {} + + pub fn set_ime_allowed(&self, allowed: bool) { + if allowed { + self.app.show_soft_input(true); + } else { + self.app.hide_soft_input(true); + } + } + + pub fn set_ime_purpose(&self, _purpose: ImePurpose) {} + + pub fn focus_window(&self) {} + + pub fn request_user_attention(&self, _request_type: Option<window::UserAttentionType>) {} + + pub fn set_cursor(&self, _: Cursor) {} + + pub fn set_cursor_position(&self, _: Position) -> Result<(), error::ExternalError> { + Err(error::ExternalError::NotSupported(error::NotSupportedError::new())) + } + + pub fn set_cursor_grab(&self, _: CursorGrabMode) -> Result<(), error::ExternalError> { + Err(error::ExternalError::NotSupported(error::NotSupportedError::new())) + } + + pub fn set_cursor_visible(&self, _: bool) {} + + pub fn drag_window(&self) -> Result<(), error::ExternalError> { + Err(error::ExternalError::NotSupported(error::NotSupportedError::new())) + } + + pub fn drag_resize_window( + &self, + _direction: ResizeDirection, + ) -> Result<(), error::ExternalError> { + Err(error::ExternalError::NotSupported(error::NotSupportedError::new())) + } + + #[inline] + pub fn show_window_menu(&self, _position: Position) {} + + pub fn set_cursor_hittest(&self, _hittest: bool) -> Result<(), error::ExternalError> { + Err(error::ExternalError::NotSupported(error::NotSupportedError::new())) + } + + #[cfg(feature = "rwh_04")] + pub fn raw_window_handle_rwh_04(&self) -> rwh_04::RawWindowHandle { + use rwh_04::HasRawWindowHandle; + + if let Some(native_window) = self.app.native_window().as_ref() { + native_window.raw_window_handle() + } else { + panic!( + "Cannot get the native window, it's null and will always be null before \ + Event::Resumed and after Event::Suspended. Make sure you only call this function \ + between those events." + ); + } + } + + #[cfg(feature = "rwh_05")] + pub fn raw_window_handle_rwh_05(&self) -> rwh_05::RawWindowHandle { + use rwh_05::HasRawWindowHandle; + + if let Some(native_window) = self.app.native_window().as_ref() { + native_window.raw_window_handle() + } else { + panic!( + "Cannot get the native window, it's null and will always be null before \ + Event::Resumed and after Event::Suspended. Make sure you only call this function \ + between those events." + ); + } + } + + #[cfg(feature = "rwh_05")] + pub fn raw_display_handle_rwh_05(&self) -> rwh_05::RawDisplayHandle { + rwh_05::RawDisplayHandle::Android(rwh_05::AndroidDisplayHandle::empty()) + } + + #[cfg(feature = "rwh_06")] + // Allow the usage of HasRawWindowHandle inside this function + #[allow(deprecated)] + pub fn raw_window_handle_rwh_06(&self) -> Result<rwh_06::RawWindowHandle, rwh_06::HandleError> { + use rwh_06::HasRawWindowHandle; + + if let Some(native_window) = self.app.native_window().as_ref() { + native_window.raw_window_handle() + } else { + tracing::error!( + "Cannot get the native window, it's null and will always be null before \ + Event::Resumed and after Event::Suspended. Make sure you only call this function \ + between those events." + ); + Err(rwh_06::HandleError::Unavailable) + } + } + + #[cfg(feature = "rwh_06")] + pub fn raw_display_handle_rwh_06( + &self, + ) -> Result<rwh_06::RawDisplayHandle, rwh_06::HandleError> { + Ok(rwh_06::RawDisplayHandle::Android(rwh_06::AndroidDisplayHandle::new())) + } + + pub fn config(&self) -> ConfigurationRef { + self.app.config() + } + + pub fn content_rect(&self) -> Rect { + self.app.content_rect() + } + + pub fn set_theme(&self, _theme: Option<Theme>) {} + + pub fn theme(&self) -> Option<Theme> { + None + } + + pub fn set_content_protected(&self, _protected: bool) {} + + pub fn has_focus(&self) -> bool { + HAS_FOCUS.load(Ordering::Relaxed) + } + + pub fn title(&self) -> String { + String::new() + } + + pub fn reset_dead_keys(&self) {} +} + +#[derive(Default, Clone, Debug)] +pub struct OsError; + +use std::fmt::{self, Display, Formatter}; +impl Display for OsError { + fn fmt(&self, fmt: &mut Formatter<'_>) -> Result<(), fmt::Error> { + write!(fmt, "Android OS Error") + } +} + +#[derive(Clone, Debug, PartialEq, Eq, Hash)] +pub struct MonitorHandle { + app: AndroidApp, +} +impl PartialOrd for MonitorHandle { + fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> { + Some(self.cmp(other)) + } +} +impl Ord for MonitorHandle { + fn cmp(&self, _other: &Self) -> std::cmp::Ordering { + std::cmp::Ordering::Equal + } +} + +impl MonitorHandle { + pub(crate) fn new(app: AndroidApp) -> Self { + Self { app } + } + + pub fn name(&self) -> Option<String> { + Some("Android Device".to_owned()) + } + + pub fn size(&self) -> PhysicalSize<u32> { + if let Some(native_window) = self.app.native_window() { + PhysicalSize::new(native_window.width() as _, native_window.height() as _) + } else { + PhysicalSize::new(0, 0) + } + } + + pub fn position(&self) -> PhysicalPosition<i32> { + (0, 0).into() + } + + pub fn scale_factor(&self) -> f64 { + self.app.config().density().map(|dpi| dpi as f64 / 160.0).unwrap_or(1.0) + } + + pub fn refresh_rate_millihertz(&self) -> Option<u32> { + // FIXME no way to get real refresh rate for now. + None + } + + pub fn video_modes(&self) -> impl Iterator<Item = VideoModeHandle> { + let size = self.size().into(); + // FIXME this is not the real refresh rate + // (it is guaranteed to support 32 bit color though) + std::iter::once(VideoModeHandle { + size, + bit_depth: 32, + refresh_rate_millihertz: 60000, + monitor: self.clone(), + }) + } +} + +#[derive(Clone, Debug, Eq, Hash, PartialEq)] +pub struct VideoModeHandle { + size: (u32, u32), + bit_depth: u16, + refresh_rate_millihertz: u32, + monitor: MonitorHandle, +} + +impl VideoModeHandle { + pub fn size(&self) -> PhysicalSize<u32> { + self.size.into() + } + + pub fn bit_depth(&self) -> u16 { + self.bit_depth + } + + pub fn refresh_rate_millihertz(&self) -> u32 { + self.refresh_rate_millihertz + } + + pub fn monitor(&self) -> MonitorHandle { + self.monitor.clone() + } +} diff --git a/app/vendor/rune/vendor/winit/src/platform_impl/ios/app_state.rs b/app/vendor/rune/vendor/winit/src/platform_impl/ios/app_state.rs new file mode 100644 index 0000000..e34bf43 --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/platform_impl/ios/app_state.rs @@ -0,0 +1,925 @@ +#![deny(unused_results)] + +use std::cell::{RefCell, RefMut}; +use std::collections::HashSet; +use std::os::raw::c_void; +use std::sync::{Arc, Mutex, OnceLock}; +use std::time::Instant; +use std::{fmt, mem, ptr}; + +use core_foundation::base::CFRelease; +use core_foundation::date::CFAbsoluteTimeGetCurrent; +use core_foundation::runloop::{ + kCFRunLoopCommonModes, CFRunLoopAddTimer, CFRunLoopGetMain, CFRunLoopRef, CFRunLoopTimerCreate, + CFRunLoopTimerInvalidate, CFRunLoopTimerRef, CFRunLoopTimerSetNextFireDate, +}; +use objc2::rc::Retained; +use objc2::runtime::AnyObject; +use objc2::{msg_send, sel}; +use objc2_foundation::{ + CGRect, CGSize, MainThreadMarker, NSInteger, NSObjectProtocol, NSOperatingSystemVersion, + NSProcessInfo, +}; +use objc2_ui_kit::{UIApplication, UICoordinateSpace, UIView, UIWindow}; + +use super::window::WinitUIWindow; +use crate::dpi::PhysicalSize; +use crate::event::{Event, InnerSizeWriter, StartCause, WindowEvent}; +use crate::event_loop::{ActiveEventLoop as RootActiveEventLoop, ControlFlow}; +use crate::window::WindowId as RootWindowId; + +macro_rules! bug { + ($($msg:tt)*) => { + panic!("winit iOS bug, file an issue: {}", format!($($msg)*)) + }; +} + +macro_rules! bug_assert { + ($test:expr, $($msg:tt)*) => { + assert!($test, "winit iOS bug, file an issue: {}", format!($($msg)*)) + }; +} + +#[derive(Debug)] +pub(crate) struct HandlePendingUserEvents; + +pub(crate) struct EventLoopHandler { + #[allow(clippy::type_complexity)] + pub(crate) handler: Box<dyn FnMut(Event<HandlePendingUserEvents>, &RootActiveEventLoop)>, + pub(crate) event_loop: RootActiveEventLoop, +} + +impl fmt::Debug for EventLoopHandler { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("EventLoopHandler") + .field("handler", &"...") + .field("event_loop", &self.event_loop) + .finish() + } +} + +impl EventLoopHandler { + fn handle_event(&mut self, event: Event<HandlePendingUserEvents>) { + (self.handler)(event, &self.event_loop) + } +} + +#[derive(Debug)] +pub(crate) enum EventWrapper { + StaticEvent(Event<HandlePendingUserEvents>), + ScaleFactorChanged(ScaleFactorChanged), +} + +#[derive(Debug)] +pub struct ScaleFactorChanged { + pub(super) window: Retained<WinitUIWindow>, + pub(super) suggested_size: PhysicalSize<u32>, + pub(super) scale_factor: f64, +} + +enum UserCallbackTransitionResult<'a> { + Success { + handler: EventLoopHandler, + active_control_flow: ControlFlow, + processing_redraws: bool, + }, + ReentrancyPrevented { + queued_events: &'a mut Vec<EventWrapper>, + }, +} + +impl Event<HandlePendingUserEvents> { + fn is_redraw(&self) -> bool { + matches!(self, Event::WindowEvent { event: WindowEvent::RedrawRequested, .. }) + } +} + +// this is the state machine for the app lifecycle +#[derive(Debug)] +#[must_use = "dropping `AppStateImpl` without inspecting it is probably a bug"] +enum AppStateImpl { + NotLaunched { + queued_windows: Vec<Retained<WinitUIWindow>>, + queued_events: Vec<EventWrapper>, + queued_gpu_redraws: HashSet<Retained<WinitUIWindow>>, + }, + Launching { + queued_windows: Vec<Retained<WinitUIWindow>>, + queued_events: Vec<EventWrapper>, + queued_handler: EventLoopHandler, + queued_gpu_redraws: HashSet<Retained<WinitUIWindow>>, + }, + ProcessingEvents { + handler: EventLoopHandler, + queued_gpu_redraws: HashSet<Retained<WinitUIWindow>>, + active_control_flow: ControlFlow, + }, + // special state to deal with reentrancy and prevent mutable aliasing. + InUserCallback { + queued_events: Vec<EventWrapper>, + queued_gpu_redraws: HashSet<Retained<WinitUIWindow>>, + }, + ProcessingRedraws { + handler: EventLoopHandler, + active_control_flow: ControlFlow, + }, + Waiting { + waiting_handler: EventLoopHandler, + start: Instant, + }, + PollFinished { + waiting_handler: EventLoopHandler, + }, + Terminated, +} + +pub(crate) struct AppState { + // This should never be `None`, except for briefly during a state transition. + app_state: Option<AppStateImpl>, + control_flow: ControlFlow, + waker: EventLoopWaker, +} + +impl AppState { + pub(crate) fn get_mut(_mtm: MainThreadMarker) -> RefMut<'static, AppState> { + // basically everything in UIKit requires the main thread, so it's pointless to use the + // std::sync APIs. + // must be mut because plain `static` requires `Sync` + static mut APP_STATE: RefCell<Option<AppState>> = RefCell::new(None); + + #[allow(unknown_lints)] // New lint below + #[allow(static_mut_refs)] // TODO: Use `MainThreadBound` instead. + let mut guard = unsafe { APP_STATE.borrow_mut() }; + if guard.is_none() { + #[inline(never)] + #[cold] + fn init_guard(guard: &mut RefMut<'static, Option<AppState>>) { + let waker = EventLoopWaker::new(unsafe { CFRunLoopGetMain() }); + **guard = Some(AppState { + app_state: Some(AppStateImpl::NotLaunched { + queued_windows: Vec::new(), + queued_events: Vec::new(), + queued_gpu_redraws: HashSet::new(), + }), + control_flow: ControlFlow::default(), + waker, + }); + } + init_guard(&mut guard); + } + RefMut::map(guard, |state| state.as_mut().unwrap()) + } + + fn state(&self) -> &AppStateImpl { + match &self.app_state { + Some(ref state) => state, + None => bug!("`AppState` previously failed a state transition"), + } + } + + fn state_mut(&mut self) -> &mut AppStateImpl { + match &mut self.app_state { + Some(ref mut state) => state, + None => bug!("`AppState` previously failed a state transition"), + } + } + + fn take_state(&mut self) -> AppStateImpl { + match self.app_state.take() { + Some(state) => state, + None => bug!("`AppState` previously failed a state transition"), + } + } + + fn set_state(&mut self, new_state: AppStateImpl) { + bug_assert!( + self.app_state.is_none(), + "attempted to set an `AppState` without calling `take_state` first {:?}", + self.app_state + ); + self.app_state = Some(new_state) + } + + fn replace_state(&mut self, new_state: AppStateImpl) -> AppStateImpl { + match &mut self.app_state { + Some(ref mut state) => mem::replace(state, new_state), + None => bug!("`AppState` previously failed a state transition"), + } + } + + fn has_launched(&self) -> bool { + !matches!(self.state(), AppStateImpl::NotLaunched { .. } | AppStateImpl::Launching { .. }) + } + + fn has_terminated(&self) -> bool { + matches!(self.state(), AppStateImpl::Terminated) + } + + fn will_launch_transition(&mut self, queued_handler: EventLoopHandler) { + let (queued_windows, queued_events, queued_gpu_redraws) = match self.take_state() { + AppStateImpl::NotLaunched { queued_windows, queued_events, queued_gpu_redraws } => { + (queued_windows, queued_events, queued_gpu_redraws) + }, + s => bug!("unexpected state {:?}", s), + }; + self.set_state(AppStateImpl::Launching { + queued_windows, + queued_events, + queued_handler, + queued_gpu_redraws, + }); + } + + fn did_finish_launching_transition( + &mut self, + ) -> (Vec<Retained<WinitUIWindow>>, Vec<EventWrapper>) { + let (windows, events, handler, queued_gpu_redraws) = match self.take_state() { + AppStateImpl::Launching { + queued_windows, + queued_events, + queued_handler, + queued_gpu_redraws, + } => (queued_windows, queued_events, queued_handler, queued_gpu_redraws), + s => bug!("unexpected state {:?}", s), + }; + self.set_state(AppStateImpl::ProcessingEvents { + handler, + active_control_flow: self.control_flow, + queued_gpu_redraws, + }); + (windows, events) + } + + fn wakeup_transition(&mut self) -> Option<EventWrapper> { + // before `AppState::did_finish_launching` is called, pretend there is no running + // event loop. + if !self.has_launched() || self.has_terminated() { + return None; + } + + let (handler, event) = match (self.control_flow, self.take_state()) { + (ControlFlow::Poll, AppStateImpl::PollFinished { waiting_handler }) => { + (waiting_handler, EventWrapper::StaticEvent(Event::NewEvents(StartCause::Poll))) + }, + (ControlFlow::Wait, AppStateImpl::Waiting { waiting_handler, start }) => ( + waiting_handler, + EventWrapper::StaticEvent(Event::NewEvents(StartCause::WaitCancelled { + start, + requested_resume: None, + })), + ), + ( + ControlFlow::WaitUntil(requested_resume), + AppStateImpl::Waiting { waiting_handler, start }, + ) => { + let event = if Instant::now() >= requested_resume { + EventWrapper::StaticEvent(Event::NewEvents(StartCause::ResumeTimeReached { + start, + requested_resume, + })) + } else { + EventWrapper::StaticEvent(Event::NewEvents(StartCause::WaitCancelled { + start, + requested_resume: Some(requested_resume), + })) + }; + (waiting_handler, event) + }, + s => bug!("`EventHandler` unexpectedly woke up {:?}", s), + }; + + self.set_state(AppStateImpl::ProcessingEvents { + handler, + queued_gpu_redraws: Default::default(), + active_control_flow: self.control_flow, + }); + Some(event) + } + + fn try_user_callback_transition(&mut self) -> UserCallbackTransitionResult<'_> { + // If we're not able to process an event due to recursion or `Init` not having been sent out + // yet, then queue the events up. + match self.state_mut() { + &mut AppStateImpl::Launching { ref mut queued_events, .. } + | &mut AppStateImpl::NotLaunched { ref mut queued_events, .. } + | &mut AppStateImpl::InUserCallback { ref mut queued_events, .. } => { + // A lifetime cast: early returns are not currently handled well with NLL, but + // polonius handles them well. This transmute is a safe workaround. + return unsafe { + mem::transmute::< + UserCallbackTransitionResult<'_>, + UserCallbackTransitionResult<'_>, + >(UserCallbackTransitionResult::ReentrancyPrevented { + queued_events, + }) + }; + }, + + &mut AppStateImpl::ProcessingEvents { .. } + | &mut AppStateImpl::ProcessingRedraws { .. } => {}, + + s @ &mut AppStateImpl::PollFinished { .. } + | s @ &mut AppStateImpl::Waiting { .. } + | s @ &mut AppStateImpl::Terminated => { + bug!("unexpected attempted to process an event {:?}", s) + }, + } + + let (handler, queued_gpu_redraws, active_control_flow, processing_redraws) = match self + .take_state() + { + AppStateImpl::Launching { .. } + | AppStateImpl::NotLaunched { .. } + | AppStateImpl::InUserCallback { .. } => unreachable!(), + AppStateImpl::ProcessingEvents { handler, queued_gpu_redraws, active_control_flow } => { + (handler, queued_gpu_redraws, active_control_flow, false) + }, + AppStateImpl::ProcessingRedraws { handler, active_control_flow } => { + (handler, Default::default(), active_control_flow, true) + }, + AppStateImpl::PollFinished { .. } + | AppStateImpl::Waiting { .. } + | AppStateImpl::Terminated => unreachable!(), + }; + self.set_state(AppStateImpl::InUserCallback { + queued_events: Vec::new(), + queued_gpu_redraws, + }); + UserCallbackTransitionResult::Success { handler, active_control_flow, processing_redraws } + } + + fn main_events_cleared_transition(&mut self) -> HashSet<Retained<WinitUIWindow>> { + let (handler, queued_gpu_redraws, active_control_flow) = match self.take_state() { + AppStateImpl::ProcessingEvents { handler, queued_gpu_redraws, active_control_flow } => { + (handler, queued_gpu_redraws, active_control_flow) + }, + s => bug!("unexpected state {:?}", s), + }; + self.set_state(AppStateImpl::ProcessingRedraws { handler, active_control_flow }); + queued_gpu_redraws + } + + fn events_cleared_transition(&mut self) { + if !self.has_launched() || self.has_terminated() { + return; + } + let (waiting_handler, old) = match self.take_state() { + AppStateImpl::ProcessingRedraws { handler, active_control_flow } => { + (handler, active_control_flow) + }, + s => bug!("unexpected state {:?}", s), + }; + + let new = self.control_flow; + match (old, new) { + (ControlFlow::Wait, ControlFlow::Wait) => { + let start = Instant::now(); + self.set_state(AppStateImpl::Waiting { waiting_handler, start }); + self.waker.stop() + }, + (ControlFlow::WaitUntil(old_instant), ControlFlow::WaitUntil(new_instant)) + if old_instant == new_instant => + { + let start = Instant::now(); + self.set_state(AppStateImpl::Waiting { waiting_handler, start }); + }, + (_, ControlFlow::Wait) => { + let start = Instant::now(); + self.set_state(AppStateImpl::Waiting { waiting_handler, start }); + self.waker.stop() + }, + (_, ControlFlow::WaitUntil(new_instant)) => { + let start = Instant::now(); + self.set_state(AppStateImpl::Waiting { waiting_handler, start }); + self.waker.start_at(new_instant) + }, + // Unlike on macOS, handle Poll to Poll transition here to call the waker + (_, ControlFlow::Poll) => { + self.set_state(AppStateImpl::PollFinished { waiting_handler }); + self.waker.start() + }, + } + } + + fn terminated_transition(&mut self) -> EventLoopHandler { + match self.replace_state(AppStateImpl::Terminated) { + AppStateImpl::ProcessingEvents { handler, .. } => handler, + s => bug!("`LoopExiting` happened while not processing events {:?}", s), + } + } + + pub(crate) fn set_control_flow(&mut self, control_flow: ControlFlow) { + self.control_flow = control_flow; + } + + pub(crate) fn control_flow(&self) -> ControlFlow { + self.control_flow + } +} + +pub(crate) fn set_key_window(mtm: MainThreadMarker, window: &Retained<WinitUIWindow>) { + let mut this = AppState::get_mut(mtm); + match this.state_mut() { + &mut AppStateImpl::NotLaunched { ref mut queued_windows, .. } => { + return queued_windows.push(window.clone()) + }, + &mut AppStateImpl::ProcessingEvents { .. } + | &mut AppStateImpl::InUserCallback { .. } + | &mut AppStateImpl::ProcessingRedraws { .. } => {}, + s @ &mut AppStateImpl::Launching { .. } + | s @ &mut AppStateImpl::Waiting { .. } + | s @ &mut AppStateImpl::PollFinished { .. } => bug!("unexpected state {:?}", s), + &mut AppStateImpl::Terminated => { + panic!("Attempt to create a `Window` after the app has terminated") + }, + } + drop(this); + window.makeKeyAndVisible(); +} + +pub(crate) fn queue_gl_or_metal_redraw(mtm: MainThreadMarker, window: Retained<WinitUIWindow>) { + let mut this = AppState::get_mut(mtm); + match this.state_mut() { + &mut AppStateImpl::NotLaunched { ref mut queued_gpu_redraws, .. } + | &mut AppStateImpl::Launching { ref mut queued_gpu_redraws, .. } + | &mut AppStateImpl::ProcessingEvents { ref mut queued_gpu_redraws, .. } + | &mut AppStateImpl::InUserCallback { ref mut queued_gpu_redraws, .. } => { + let _ = queued_gpu_redraws.insert(window); + }, + s @ &mut AppStateImpl::ProcessingRedraws { .. } + | s @ &mut AppStateImpl::Waiting { .. } + | s @ &mut AppStateImpl::PollFinished { .. } => bug!("unexpected state {:?}", s), + &mut AppStateImpl::Terminated => { + panic!("Attempt to create a `Window` after the app has terminated") + }, + } +} + +pub(crate) fn will_launch(mtm: MainThreadMarker, queued_handler: EventLoopHandler) { + AppState::get_mut(mtm).will_launch_transition(queued_handler) +} + +pub fn did_finish_launching(mtm: MainThreadMarker) { + let mut this = AppState::get_mut(mtm); + let windows = match this.state_mut() { + AppStateImpl::Launching { queued_windows, .. } => mem::take(queued_windows), + s => bug!("unexpected state {:?}", s), + }; + + this.waker.start(); + + // have to drop RefMut because the window setup code below can trigger new events + drop(this); + + for window in windows { + // Do a little screen dance here to account for windows being created before + // `UIApplicationMain` is called. This fixes visual issues such as being + // offcenter and sized incorrectly. Additionally, to fix orientation issues, we + // gotta reset the `rootViewController`. + // + // relevant iOS log: + // ``` + // [ApplicationLifecycle] Windows were created before application initialization + // completed. This may result in incorrect visual appearance. + // ``` + let screen = window.screen(); + let _: () = unsafe { msg_send![&window, setScreen: ptr::null::<AnyObject>()] }; + window.setScreen(&screen); + + let controller = window.rootViewController(); + window.setRootViewController(None); + window.setRootViewController(controller.as_deref()); + + window.makeKeyAndVisible(); + } + + let (windows, events) = AppState::get_mut(mtm).did_finish_launching_transition(); + + let events = std::iter::once(EventWrapper::StaticEvent(Event::NewEvents(StartCause::Init))) + .chain(events); + handle_nonuser_events(mtm, events); + + // the above window dance hack, could possibly trigger new windows to be created. + // we can just set those windows up normally, as they were created after didFinishLaunching + for window in windows { + window.makeKeyAndVisible(); + } +} + +// AppState::did_finish_launching handles the special transition `Init` +pub fn handle_wakeup_transition(mtm: MainThreadMarker) { + let mut this = AppState::get_mut(mtm); + let wakeup_event = match this.wakeup_transition() { + None => return, + Some(wakeup_event) => wakeup_event, + }; + drop(this); + + handle_nonuser_event(mtm, wakeup_event) +} + +pub(crate) fn handle_nonuser_event(mtm: MainThreadMarker, event: EventWrapper) { + handle_nonuser_events(mtm, std::iter::once(event)) +} + +pub(crate) fn handle_nonuser_events<I: IntoIterator<Item = EventWrapper>>( + mtm: MainThreadMarker, + events: I, +) { + let mut this = AppState::get_mut(mtm); + if this.has_terminated() { + return; + } + + let (mut handler, active_control_flow, processing_redraws) = + match this.try_user_callback_transition() { + UserCallbackTransitionResult::ReentrancyPrevented { queued_events } => { + queued_events.extend(events); + return; + }, + UserCallbackTransitionResult::Success { + handler, + active_control_flow, + processing_redraws, + } => (handler, active_control_flow, processing_redraws), + }; + drop(this); + + for wrapper in events { + match wrapper { + EventWrapper::StaticEvent(event) => { + if !processing_redraws && event.is_redraw() { + tracing::info!("processing `RedrawRequested` during the main event loop"); + } else if processing_redraws && !event.is_redraw() { + tracing::warn!( + "processing non `RedrawRequested` event after the main event loop: {:#?}", + event + ); + } + handler.handle_event(event) + }, + EventWrapper::ScaleFactorChanged(event) => handle_hidpi_proxy(&mut handler, event), + } + } + + loop { + let mut this = AppState::get_mut(mtm); + let queued_events = match this.state_mut() { + &mut AppStateImpl::InUserCallback { ref mut queued_events, queued_gpu_redraws: _ } => { + mem::take(queued_events) + }, + s => bug!("unexpected state {:?}", s), + }; + if queued_events.is_empty() { + let queued_gpu_redraws = match this.take_state() { + AppStateImpl::InUserCallback { queued_events: _, queued_gpu_redraws } => { + queued_gpu_redraws + }, + _ => unreachable!(), + }; + this.app_state = Some(if processing_redraws { + bug_assert!( + queued_gpu_redraws.is_empty(), + "redraw queued while processing redraws" + ); + AppStateImpl::ProcessingRedraws { handler, active_control_flow } + } else { + AppStateImpl::ProcessingEvents { handler, queued_gpu_redraws, active_control_flow } + }); + break; + } + drop(this); + + for wrapper in queued_events { + match wrapper { + EventWrapper::StaticEvent(event) => { + if !processing_redraws && event.is_redraw() { + tracing::info!("processing `RedrawRequested` during the main event loop"); + } else if processing_redraws && !event.is_redraw() { + tracing::warn!( + "processing non-`RedrawRequested` event after the main event loop: \ + {:#?}", + event + ); + } + handler.handle_event(event) + }, + EventWrapper::ScaleFactorChanged(event) => handle_hidpi_proxy(&mut handler, event), + } + } + } +} + +fn handle_user_events(mtm: MainThreadMarker) { + let mut this = AppState::get_mut(mtm); + let (mut handler, active_control_flow, processing_redraws) = + match this.try_user_callback_transition() { + UserCallbackTransitionResult::ReentrancyPrevented { .. } => { + bug!("unexpected attempted to process an event") + }, + UserCallbackTransitionResult::Success { + handler, + active_control_flow, + processing_redraws, + } => (handler, active_control_flow, processing_redraws), + }; + if processing_redraws { + bug!("user events attempted to be sent out while `ProcessingRedraws`"); + } + drop(this); + + handler.handle_event(Event::UserEvent(HandlePendingUserEvents)); + + loop { + let mut this = AppState::get_mut(mtm); + let queued_events = match this.state_mut() { + &mut AppStateImpl::InUserCallback { ref mut queued_events, queued_gpu_redraws: _ } => { + mem::take(queued_events) + }, + s => bug!("unexpected state {:?}", s), + }; + if queued_events.is_empty() { + let queued_gpu_redraws = match this.take_state() { + AppStateImpl::InUserCallback { queued_events: _, queued_gpu_redraws } => { + queued_gpu_redraws + }, + _ => unreachable!(), + }; + this.app_state = Some(AppStateImpl::ProcessingEvents { + handler, + queued_gpu_redraws, + active_control_flow, + }); + break; + } + drop(this); + + for wrapper in queued_events { + match wrapper { + EventWrapper::StaticEvent(event) => handler.handle_event(event), + EventWrapper::ScaleFactorChanged(event) => handle_hidpi_proxy(&mut handler, event), + } + } + + handler.handle_event(Event::UserEvent(HandlePendingUserEvents)); + } +} + +pub(crate) fn send_occluded_event_for_all_windows(application: &UIApplication, occluded: bool) { + let mtm = MainThreadMarker::from(application); + + let mut events = Vec::new(); + #[allow(deprecated)] + for window in application.windows().iter() { + if window.is_kind_of::<WinitUIWindow>() { + // SAFETY: We just checked that the window is a `winit` window + let window = unsafe { + let ptr: *const UIWindow = window; + let ptr: *const WinitUIWindow = ptr.cast(); + &*ptr + }; + events.push(EventWrapper::StaticEvent(Event::WindowEvent { + window_id: RootWindowId(window.id()), + event: WindowEvent::Occluded(occluded), + })); + } + } + handle_nonuser_events(mtm, events); +} + +pub fn handle_main_events_cleared(mtm: MainThreadMarker) { + let mut this = AppState::get_mut(mtm); + if !this.has_launched() || this.has_terminated() { + return; + } + match this.state_mut() { + AppStateImpl::ProcessingEvents { .. } => {}, + _ => bug!("`ProcessingRedraws` happened unexpectedly"), + }; + drop(this); + + handle_user_events(mtm); + + let mut this = AppState::get_mut(mtm); + let redraw_events: Vec<EventWrapper> = this + .main_events_cleared_transition() + .into_iter() + .map(|window| { + EventWrapper::StaticEvent(Event::WindowEvent { + window_id: RootWindowId(window.id()), + event: WindowEvent::RedrawRequested, + }) + }) + .collect(); + drop(this); + + handle_nonuser_events(mtm, redraw_events); + handle_nonuser_event(mtm, EventWrapper::StaticEvent(Event::AboutToWait)); +} + +pub fn handle_events_cleared(mtm: MainThreadMarker) { + AppState::get_mut(mtm).events_cleared_transition(); +} + +pub(crate) fn terminated(application: &UIApplication) { + let mtm = MainThreadMarker::from(application); + + let mut events = Vec::new(); + #[allow(deprecated)] + for window in application.windows().iter() { + if window.is_kind_of::<WinitUIWindow>() { + // SAFETY: We just checked that the window is a `winit` window + let window = unsafe { + let ptr: *const UIWindow = window; + let ptr: *const WinitUIWindow = ptr.cast(); + &*ptr + }; + events.push(EventWrapper::StaticEvent(Event::WindowEvent { + window_id: RootWindowId(window.id()), + event: WindowEvent::Destroyed, + })); + } + } + handle_nonuser_events(mtm, events); + + let mut this = AppState::get_mut(mtm); + let mut handler = this.terminated_transition(); + drop(this); + + handler.handle_event(Event::LoopExiting) +} + +fn handle_hidpi_proxy(handler: &mut EventLoopHandler, event: ScaleFactorChanged) { + let ScaleFactorChanged { suggested_size, scale_factor, window } = event; + let new_inner_size = Arc::new(Mutex::new(suggested_size)); + let event = Event::WindowEvent { + window_id: RootWindowId(window.id()), + event: WindowEvent::ScaleFactorChanged { + scale_factor, + inner_size_writer: InnerSizeWriter::new(Arc::downgrade(&new_inner_size)), + }, + }; + handler.handle_event(event); + let (view, screen_frame) = get_view_and_screen_frame(&window); + let physical_size = *new_inner_size.lock().unwrap(); + drop(new_inner_size); + let logical_size = physical_size.to_logical(scale_factor); + let size = CGSize::new(logical_size.width, logical_size.height); + let new_frame: CGRect = CGRect::new(screen_frame.origin, size); + view.setFrame(new_frame); +} + +fn get_view_and_screen_frame(window: &WinitUIWindow) -> (Retained<UIView>, CGRect) { + let view_controller = window.rootViewController().unwrap(); + let view = view_controller.view().unwrap(); + let bounds = window.bounds(); + let screen = window.screen(); + let screen_space = screen.coordinateSpace(); + let screen_frame = window.convertRect_toCoordinateSpace(bounds, &screen_space); + (view, screen_frame) +} + +struct EventLoopWaker { + timer: CFRunLoopTimerRef, +} + +impl Drop for EventLoopWaker { + fn drop(&mut self) { + unsafe { + CFRunLoopTimerInvalidate(self.timer); + CFRelease(self.timer as _); + } + } +} + +impl EventLoopWaker { + fn new(rl: CFRunLoopRef) -> EventLoopWaker { + extern "C" fn wakeup_main_loop(_timer: CFRunLoopTimerRef, _info: *mut c_void) {} + unsafe { + // Create a timer with a 0.1µs interval (1ns does not work) to mimic polling. + // It is initially setup with a first fire time really far into the + // future, but that gets changed to fire immediately in did_finish_launching + let timer = CFRunLoopTimerCreate( + ptr::null_mut(), + f64::MAX, + 0.000_000_1, + 0, + 0, + wakeup_main_loop, + ptr::null_mut(), + ); + CFRunLoopAddTimer(rl, timer, kCFRunLoopCommonModes); + + EventLoopWaker { timer } + } + } + + fn stop(&mut self) { + unsafe { CFRunLoopTimerSetNextFireDate(self.timer, f64::MAX) } + } + + fn start(&mut self) { + unsafe { CFRunLoopTimerSetNextFireDate(self.timer, f64::MIN) } + } + + fn start_at(&mut self, instant: Instant) { + let now = Instant::now(); + if now >= instant { + self.start(); + } else { + unsafe { + let current = CFAbsoluteTimeGetCurrent(); + let duration = instant - now; + let fsecs = + duration.subsec_nanos() as f64 / 1_000_000_000.0 + duration.as_secs() as f64; + CFRunLoopTimerSetNextFireDate(self.timer, current + fsecs) + } + } + } +} + +macro_rules! os_capabilities { + ( + $( + $(#[$attr:meta])* + $error_name:ident: $objc_call:literal, + $name:ident: $major:literal-$minor:literal + ),* + $(,)* + ) => { + #[derive(Clone, Debug)] + pub struct OSCapabilities { + $( + pub $name: bool, + )* + + os_version: NSOperatingSystemVersion, + } + + impl OSCapabilities { + fn from_os_version(os_version: NSOperatingSystemVersion) -> Self { + $(let $name = meets_requirements(os_version, $major, $minor);)* + Self { $($name,)* os_version, } + } + } + + impl OSCapabilities {$( + $(#[$attr])* + pub fn $error_name(&self, extra_msg: &str) { + tracing::warn!( + concat!("`", $objc_call, "` requires iOS {}.{}+. This device is running iOS {}.{}.{}. {}"), + $major, $minor, self.os_version.majorVersion, self.os_version.minorVersion, self.os_version.patchVersion, + extra_msg + ) + } + )*} + }; +} + +os_capabilities! { + /// <https://developer.apple.com/documentation/uikit/uiview/2891103-safeareainsets?language=objc> + #[allow(unused)] // error message unused + safe_area_err_msg: "-[UIView safeAreaInsets]", + safe_area: 11-0, + /// <https://developer.apple.com/documentation/uikit/uiviewcontroller/2887509-setneedsupdateofhomeindicatoraut?language=objc> + home_indicator_hidden_err_msg: "-[UIViewController setNeedsUpdateOfHomeIndicatorAutoHidden]", + home_indicator_hidden: 11-0, + /// <https://developer.apple.com/documentation/uikit/uiviewcontroller/2887507-setneedsupdateofscreenedgesdefer?language=objc> + defer_system_gestures_err_msg: "-[UIViewController setNeedsUpdateOfScreenEdgesDeferringSystem]", + defer_system_gestures: 11-0, + /// <https://developer.apple.com/documentation/uikit/uiscreen/2806814-maximumframespersecond?language=objc> + maximum_frames_per_second_err_msg: "-[UIScreen maximumFramesPerSecond]", + maximum_frames_per_second: 10-3, + /// <https://developer.apple.com/documentation/uikit/uitouch/1618110-force?language=objc> + #[allow(unused)] // error message unused + force_touch_err_msg: "-[UITouch force]", + force_touch: 9-0, +} + +fn meets_requirements( + version: NSOperatingSystemVersion, + required_major: NSInteger, + required_minor: NSInteger, +) -> bool { + (version.majorVersion, version.minorVersion) >= (required_major, required_minor) +} + +fn get_version() -> NSOperatingSystemVersion { + let process_info = NSProcessInfo::processInfo(); + let atleast_ios_8 = process_info.respondsToSelector(sel!(operatingSystemVersion)); + // Winit requires atleast iOS 8 because no one has put the time into supporting earlier os + // versions. Older iOS versions are increasingly difficult to test. For example, Xcode 11 does + // not support debugging on devices with an iOS version of less than 8. Another example, in + // order to use an iOS simulator older than iOS 8, you must download an older version of Xcode + // (<9), and at least Xcode 7 has been tested to not even run on macOS 10.15 - Xcode 8 might? + // + // The minimum required iOS version is likely to grow in the future. + assert!(atleast_ios_8, "`winit` requires iOS version 8 or greater"); + process_info.operatingSystemVersion() +} + +pub fn os_capabilities() -> OSCapabilities { + // Cache the version lookup for efficiency + static OS_CAPABILITIES: OnceLock<OSCapabilities> = OnceLock::new(); + OS_CAPABILITIES.get_or_init(|| OSCapabilities::from_os_version(get_version())).clone() +} diff --git a/app/vendor/rune/vendor/winit/src/platform_impl/ios/event_loop.rs b/app/vendor/rune/vendor/winit/src/platform_impl/ios/event_loop.rs new file mode 100644 index 0000000..a093b7b --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/platform_impl/ios/event_loop.rs @@ -0,0 +1,494 @@ +use std::collections::VecDeque; +use std::ffi::{c_char, c_int, c_void}; +use std::marker::PhantomData; +use std::ptr::{self, NonNull}; +use std::sync::mpsc::{self, Receiver, Sender}; + +use core_foundation::base::{CFIndex, CFRelease}; +use core_foundation::runloop::{ + kCFRunLoopAfterWaiting, kCFRunLoopBeforeWaiting, kCFRunLoopCommonModes, kCFRunLoopDefaultMode, + kCFRunLoopExit, CFRunLoopActivity, CFRunLoopAddObserver, CFRunLoopAddSource, CFRunLoopGetMain, + CFRunLoopObserverCreate, CFRunLoopObserverRef, CFRunLoopSourceContext, CFRunLoopSourceCreate, + CFRunLoopSourceInvalidate, CFRunLoopSourceRef, CFRunLoopSourceSignal, CFRunLoopWakeUp, +}; +use objc2::rc::Retained; +use objc2::{msg_send_id, ClassType}; +use objc2_foundation::{MainThreadMarker, NSNotificationCenter, NSObject}; +use objc2_ui_kit::{ + UIApplication, UIApplicationDidBecomeActiveNotification, + UIApplicationDidEnterBackgroundNotification, UIApplicationDidFinishLaunchingNotification, + UIApplicationDidReceiveMemoryWarningNotification, UIApplicationMain, + UIApplicationWillEnterForegroundNotification, UIApplicationWillResignActiveNotification, + UIApplicationWillTerminateNotification, UIDevice, UIScreen, UIUserInterfaceIdiom, +}; + +use crate::error::EventLoopError; +use crate::event::Event; +use crate::event_loop::{ + ActiveEventLoop as RootActiveEventLoop, ControlFlow, DeviceEvents, EventLoopClosed, +}; +use crate::platform::ios::Idiom; +use crate::platform_impl::ios::app_state::{EventLoopHandler, HandlePendingUserEvents}; +use crate::window::{CustomCursor, CustomCursorSource, Theme}; + +use super::app_state::{send_occluded_event_for_all_windows, AppState, EventWrapper}; +use super::notification_center::create_observer; +use super::{app_state, monitor, MonitorHandle}; + +#[derive(Debug)] +pub struct ActiveEventLoop { + pub(super) mtm: MainThreadMarker, +} + +impl ActiveEventLoop { + pub fn create_custom_cursor(&self, source: CustomCursorSource) -> CustomCursor { + let _ = source.inner; + CustomCursor { inner: super::PlatformCustomCursor } + } + + pub fn available_monitors(&self) -> VecDeque<MonitorHandle> { + monitor::uiscreens(self.mtm) + } + + pub fn primary_monitor(&self) -> Option<MonitorHandle> { + #[allow(deprecated)] + Some(MonitorHandle::new(UIScreen::mainScreen(self.mtm))) + } + + #[inline] + pub fn listen_device_events(&self, _allowed: DeviceEvents) {} + + #[cfg(feature = "rwh_05")] + #[inline] + pub fn raw_display_handle_rwh_05(&self) -> rwh_05::RawDisplayHandle { + rwh_05::RawDisplayHandle::UiKit(rwh_05::UiKitDisplayHandle::empty()) + } + + #[inline] + pub fn system_theme(&self) -> Option<Theme> { + None + } + + #[cfg(feature = "rwh_06")] + #[inline] + pub fn raw_display_handle_rwh_06( + &self, + ) -> Result<rwh_06::RawDisplayHandle, rwh_06::HandleError> { + Ok(rwh_06::RawDisplayHandle::UiKit(rwh_06::UiKitDisplayHandle::new())) + } + + pub(crate) fn set_control_flow(&self, control_flow: ControlFlow) { + AppState::get_mut(self.mtm).set_control_flow(control_flow) + } + + pub(crate) fn control_flow(&self) -> ControlFlow { + AppState::get_mut(self.mtm).control_flow() + } + + pub(crate) fn exit(&self) { + // https://developer.apple.com/library/archive/qa/qa1561/_index.html + // it is not possible to quit an iOS app gracefully and programmatically + tracing::warn!("`ControlFlow::Exit` ignored on iOS"); + } + + pub(crate) fn exiting(&self) -> bool { + false + } + + pub(crate) fn owned_display_handle(&self) -> OwnedDisplayHandle { + OwnedDisplayHandle + } +} + +#[derive(Clone)] +pub(crate) struct OwnedDisplayHandle; + +impl OwnedDisplayHandle { + #[cfg(feature = "rwh_05")] + #[inline] + pub fn raw_display_handle_rwh_05(&self) -> rwh_05::RawDisplayHandle { + rwh_05::UiKitDisplayHandle::empty().into() + } + + #[cfg(feature = "rwh_06")] + #[inline] + pub fn raw_display_handle_rwh_06( + &self, + ) -> Result<rwh_06::RawDisplayHandle, rwh_06::HandleError> { + Ok(rwh_06::UiKitDisplayHandle::new().into()) + } +} + +fn map_user_event<T: 'static>( + mut handler: impl FnMut(Event<T>, &RootActiveEventLoop), + receiver: mpsc::Receiver<T>, +) -> impl FnMut(Event<HandlePendingUserEvents>, &RootActiveEventLoop) { + move |event, window_target| match event.map_nonuser_event() { + Ok(event) => (handler)(event, window_target), + Err(_) => { + for event in receiver.try_iter() { + (handler)(Event::UserEvent(event), window_target); + } + }, + } +} + +pub struct EventLoop<T: 'static> { + mtm: MainThreadMarker, + sender: Sender<T>, + receiver: Receiver<T>, + window_target: RootActiveEventLoop, + + // Since iOS 9.0, we no longer need to remove the observers before they are deallocated; the + // system instead cleans it up next time it would have posted a notification to it. + // + // Though we do still need to keep the observers around to prevent them from being deallocated. + _did_finish_launching_observer: Retained<NSObject>, + _did_become_active_observer: Retained<NSObject>, + _will_resign_active_observer: Retained<NSObject>, + _will_enter_foreground_observer: Retained<NSObject>, + _did_enter_background_observer: Retained<NSObject>, + _will_terminate_observer: Retained<NSObject>, + _did_receive_memory_warning_observer: Retained<NSObject>, +} + +#[derive(Default, Debug, Copy, Clone, PartialEq, Eq, Hash)] +pub(crate) struct PlatformSpecificEventLoopAttributes {} + +impl<T: 'static> EventLoop<T> { + pub(crate) fn new( + _: &PlatformSpecificEventLoopAttributes, + ) -> Result<EventLoop<T>, EventLoopError> { + let mtm = MainThreadMarker::new() + .expect("On iOS, `EventLoop` must be created on the main thread"); + + static mut SINGLETON_INIT: bool = false; + unsafe { + assert!( + !SINGLETON_INIT, + "Only one `EventLoop` is supported on iOS. `EventLoopProxy` might be helpful" + ); + SINGLETON_INIT = true; + } + + let (sender, receiver) = mpsc::channel(); + + // this line sets up the main run loop before `UIApplicationMain` + setup_control_flow_observers(); + + let center = unsafe { NSNotificationCenter::defaultCenter() }; + + let _did_finish_launching_observer = create_observer( + &center, + // `application:didFinishLaunchingWithOptions:` + unsafe { UIApplicationDidFinishLaunchingNotification }, + move |_| { + app_state::did_finish_launching(mtm); + }, + ); + let _did_become_active_observer = create_observer( + &center, + // `applicationDidBecomeActive:` + unsafe { UIApplicationDidBecomeActiveNotification }, + move |_| { + app_state::handle_nonuser_event(mtm, EventWrapper::StaticEvent(Event::Resumed)); + }, + ); + let _will_resign_active_observer = create_observer( + &center, + // `applicationWillResignActive:` + unsafe { UIApplicationWillResignActiveNotification }, + move |_| { + app_state::handle_nonuser_event(mtm, EventWrapper::StaticEvent(Event::Suspended)); + }, + ); + let _will_enter_foreground_observer = create_observer( + &center, + // `applicationWillEnterForeground:` + unsafe { UIApplicationWillEnterForegroundNotification }, + move |notification| { + let app = unsafe { notification.object() }.expect( + "UIApplicationWillEnterForegroundNotification to have application object", + ); + // SAFETY: The `object` in `UIApplicationWillEnterForegroundNotification` is + // documented to be `UIApplication`. + let app: Retained<UIApplication> = unsafe { Retained::cast(app) }; + send_occluded_event_for_all_windows(&app, false); + }, + ); + let _did_enter_background_observer = create_observer( + &center, + // `applicationDidEnterBackground:` + unsafe { UIApplicationDidEnterBackgroundNotification }, + move |notification| { + let app = unsafe { notification.object() }.expect( + "UIApplicationDidEnterBackgroundNotification to have application object", + ); + // SAFETY: The `object` in `UIApplicationDidEnterBackgroundNotification` is + // documented to be `UIApplication`. + let app: Retained<UIApplication> = unsafe { Retained::cast(app) }; + send_occluded_event_for_all_windows(&app, true); + }, + ); + let _will_terminate_observer = create_observer( + &center, + // `applicationWillTerminate:` + unsafe { UIApplicationWillTerminateNotification }, + move |notification| { + let app = unsafe { notification.object() } + .expect("UIApplicationWillTerminateNotification to have application object"); + // SAFETY: The `object` in `UIApplicationWillTerminateNotification` is + // (somewhat) documented to be `UIApplication`. + let app: Retained<UIApplication> = unsafe { Retained::cast(app) }; + app_state::terminated(&app); + }, + ); + let _did_receive_memory_warning_observer = create_observer( + &center, + // `applicationDidReceiveMemoryWarning:` + unsafe { UIApplicationDidReceiveMemoryWarningNotification }, + move |_| { + app_state::handle_nonuser_event( + mtm, + EventWrapper::StaticEvent(Event::MemoryWarning), + ); + }, + ); + + Ok(EventLoop { + mtm, + sender, + receiver, + window_target: RootActiveEventLoop { p: ActiveEventLoop { mtm }, _marker: PhantomData }, + _did_finish_launching_observer, + _did_become_active_observer, + _will_resign_active_observer, + _will_enter_foreground_observer, + _did_enter_background_observer, + _will_terminate_observer, + _did_receive_memory_warning_observer, + }) + } + + pub fn run<F>(self, handler: F) -> ! + where + F: FnMut(Event<T>, &RootActiveEventLoop), + { + let application: Option<Retained<UIApplication>> = + unsafe { msg_send_id![UIApplication::class(), sharedApplication] }; + assert!( + application.is_none(), + "\ + `EventLoop` cannot be `run` after a call to `UIApplicationMain` on iOS\nNote: \ + `EventLoop::run_app` calls `UIApplicationMain` on iOS", + ); + + let handler = map_user_event(handler, self.receiver); + + let handler = unsafe { + std::mem::transmute::< + Box<dyn FnMut(Event<HandlePendingUserEvents>, &RootActiveEventLoop)>, + Box<dyn FnMut(Event<HandlePendingUserEvents>, &RootActiveEventLoop)>, + >(Box::new(handler)) + }; + + let handler = EventLoopHandler { handler, event_loop: self.window_target }; + + app_state::will_launch(self.mtm, handler); + + extern "C" { + // These functions are in crt_externs.h. + fn _NSGetArgc() -> *mut c_int; + fn _NSGetArgv() -> *mut *mut *mut c_char; + } + + unsafe { + UIApplicationMain( + *_NSGetArgc(), + NonNull::new(*_NSGetArgv()).unwrap(), + // We intentionally override neither the application nor the delegate, to allow the + // user to do so themselves! + None, + None, + ) + }; + unreachable!() + } + + pub fn create_proxy(&self) -> EventLoopProxy<T> { + EventLoopProxy::new(self.sender.clone()) + } + + pub fn window_target(&self) -> &RootActiveEventLoop { + &self.window_target + } +} + +// EventLoopExtIOS +impl<T: 'static> EventLoop<T> { + pub fn idiom(&self) -> Idiom { + match UIDevice::currentDevice(self.mtm).userInterfaceIdiom() { + UIUserInterfaceIdiom::Unspecified => Idiom::Unspecified, + UIUserInterfaceIdiom::Phone => Idiom::Phone, + UIUserInterfaceIdiom::Pad => Idiom::Pad, + UIUserInterfaceIdiom::TV => Idiom::TV, + UIUserInterfaceIdiom::CarPlay => Idiom::CarPlay, + _ => Idiom::Unspecified, + } + } +} + +pub struct EventLoopProxy<T> { + sender: Sender<T>, + source: CFRunLoopSourceRef, +} + +unsafe impl<T: Send> Send for EventLoopProxy<T> {} +unsafe impl<T: Send> Sync for EventLoopProxy<T> {} + +impl<T> Clone for EventLoopProxy<T> { + fn clone(&self) -> EventLoopProxy<T> { + EventLoopProxy::new(self.sender.clone()) + } +} + +impl<T> Drop for EventLoopProxy<T> { + fn drop(&mut self) { + unsafe { + CFRunLoopSourceInvalidate(self.source); + CFRelease(self.source as _); + } + } +} + +impl<T> EventLoopProxy<T> { + fn new(sender: Sender<T>) -> EventLoopProxy<T> { + unsafe { + // just wake up the eventloop + extern "C" fn event_loop_proxy_handler(_: *const c_void) {} + + // adding a Source to the main CFRunLoop lets us wake it up and + // process user events through the normal OS EventLoop mechanisms. + let rl = CFRunLoopGetMain(); + let mut context = CFRunLoopSourceContext { + version: 0, + info: ptr::null_mut(), + retain: None, + release: None, + copyDescription: None, + equal: None, + hash: None, + schedule: None, + cancel: None, + perform: event_loop_proxy_handler, + }; + let source = CFRunLoopSourceCreate(ptr::null_mut(), CFIndex::MAX - 1, &mut context); + CFRunLoopAddSource(rl, source, kCFRunLoopCommonModes); + CFRunLoopWakeUp(rl); + + EventLoopProxy { sender, source } + } + } + + pub fn send_event(&self, event: T) -> Result<(), EventLoopClosed<T>> { + self.sender.send(event).map_err(|::std::sync::mpsc::SendError(x)| EventLoopClosed(x))?; + unsafe { + // let the main thread know there's a new event + CFRunLoopSourceSignal(self.source); + let rl = CFRunLoopGetMain(); + CFRunLoopWakeUp(rl); + } + Ok(()) + } +} + +fn setup_control_flow_observers() { + unsafe { + // begin is queued with the highest priority to ensure it is processed before other + // observers + extern "C" fn control_flow_begin_handler( + _: CFRunLoopObserverRef, + activity: CFRunLoopActivity, + _: *mut c_void, + ) { + let mtm = MainThreadMarker::new().unwrap(); + #[allow(non_upper_case_globals)] + match activity { + kCFRunLoopAfterWaiting => app_state::handle_wakeup_transition(mtm), + _ => unreachable!(), + } + } + + // Core Animation registers its `CFRunLoopObserver` that performs drawing operations in + // `CA::Transaction::ensure_implicit` with a priority of `0x1e8480`. We set the main_end + // priority to be 0, in order to send AboutToWait before RedrawRequested. This value was + // chosen conservatively to guard against apple using different priorities for their redraw + // observers in different OS's or on different devices. If it so happens that it's too + // conservative, the main symptom would be non-redraw events coming in after `AboutToWait`. + // + // The value of `0x1e8480` was determined by inspecting stack traces and the associated + // registers for every `CFRunLoopAddObserver` call on an iPad Air 2 running iOS 11.4. + // + // Also tested to be `0x1e8480` on iPhone 8, iOS 13 beta 4. + extern "C" fn control_flow_main_end_handler( + _: CFRunLoopObserverRef, + activity: CFRunLoopActivity, + _: *mut c_void, + ) { + let mtm = MainThreadMarker::new().unwrap(); + #[allow(non_upper_case_globals)] + match activity { + kCFRunLoopBeforeWaiting => app_state::handle_main_events_cleared(mtm), + kCFRunLoopExit => {}, // may happen when running on macOS + _ => unreachable!(), + } + } + + // end is queued with the lowest priority to ensure it is processed after other observers + extern "C" fn control_flow_end_handler( + _: CFRunLoopObserverRef, + activity: CFRunLoopActivity, + _: *mut c_void, + ) { + let mtm = MainThreadMarker::new().unwrap(); + #[allow(non_upper_case_globals)] + match activity { + kCFRunLoopBeforeWaiting => app_state::handle_events_cleared(mtm), + kCFRunLoopExit => {}, // may happen when running on macOS + _ => unreachable!(), + } + } + + let main_loop = CFRunLoopGetMain(); + + let begin_observer = CFRunLoopObserverCreate( + ptr::null_mut(), + kCFRunLoopAfterWaiting, + 1, // repeat = true + CFIndex::MIN, + control_flow_begin_handler, + ptr::null_mut(), + ); + CFRunLoopAddObserver(main_loop, begin_observer, kCFRunLoopDefaultMode); + + let main_end_observer = CFRunLoopObserverCreate( + ptr::null_mut(), + kCFRunLoopExit | kCFRunLoopBeforeWaiting, + 1, // repeat = true + 0, // see comment on `control_flow_main_end_handler` + control_flow_main_end_handler, + ptr::null_mut(), + ); + CFRunLoopAddObserver(main_loop, main_end_observer, kCFRunLoopDefaultMode); + + let end_observer = CFRunLoopObserverCreate( + ptr::null_mut(), + kCFRunLoopExit | kCFRunLoopBeforeWaiting, + 1, // repeat = true + CFIndex::MAX, + control_flow_end_handler, + ptr::null_mut(), + ); + CFRunLoopAddObserver(main_loop, end_observer, kCFRunLoopDefaultMode); + } +} diff --git a/app/vendor/rune/vendor/winit/src/platform_impl/ios/mod.rs b/app/vendor/rune/vendor/winit/src/platform_impl/ios/mod.rs new file mode 100644 index 0000000..69e79c9 --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/platform_impl/ios/mod.rs @@ -0,0 +1,52 @@ +#![allow(clippy::let_unit_value)] + +mod app_state; +mod event_loop; +mod monitor; +mod notification_center; +mod view; +mod view_controller; +mod window; + +use std::fmt; + +use crate::event::DeviceId as RootDeviceId; + +pub(crate) use self::event_loop::{ + ActiveEventLoop, EventLoop, EventLoopProxy, OwnedDisplayHandle, + PlatformSpecificEventLoopAttributes, +}; +pub(crate) use self::monitor::{MonitorHandle, VideoModeHandle}; +pub(crate) use self::window::{PlatformSpecificWindowAttributes, Window, WindowId}; +pub(crate) use crate::cursor::{ + NoCustomCursor as PlatformCustomCursor, NoCustomCursor as PlatformCustomCursorSource, +}; +pub(crate) use crate::icon::NoIcon as PlatformIcon; +pub(crate) use crate::platform_impl::Fullscreen; + +/// There is no way to detect which device that performed a certain event in +/// UIKit (i.e. you can't differentiate between different external keyboards, +/// or whether it was the main touchscreen, assistive technologies, or some +/// other pointer device that caused a touch event). +#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub struct DeviceId; + +impl DeviceId { + pub const fn dummy() -> Self { + DeviceId + } +} + +pub(crate) const DEVICE_ID: RootDeviceId = RootDeviceId(DeviceId); + +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub struct KeyEventExtra {} + +#[derive(Debug)] +pub enum OsError {} + +impl fmt::Display for OsError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "os error") + } +} diff --git a/app/vendor/rune/vendor/winit/src/platform_impl/ios/monitor.rs b/app/vendor/rune/vendor/winit/src/platform_impl/ios/monitor.rs new file mode 100644 index 0000000..9f017a2 --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/platform_impl/ios/monitor.rs @@ -0,0 +1,277 @@ +#![allow(clippy::unnecessary_cast)] + +use std::collections::{BTreeSet, VecDeque}; +use std::{fmt, hash, ptr}; + +use objc2::mutability::IsRetainable; +use objc2::rc::Retained; +use objc2::Message; +use objc2_foundation::{run_on_main, MainThreadBound, MainThreadMarker, NSInteger}; +use objc2_ui_kit::{UIScreen, UIScreenMode}; + +use crate::dpi::{PhysicalPosition, PhysicalSize}; +use crate::monitor::VideoModeHandle as RootVideoModeHandle; +use crate::platform_impl::platform::app_state; + +// Workaround for `MainThreadBound` implementing almost no traits +#[derive(Debug)] +struct MainThreadBoundDelegateImpls<T>(MainThreadBound<Retained<T>>); + +impl<T: IsRetainable + Message> Clone for MainThreadBoundDelegateImpls<T> { + fn clone(&self) -> Self { + Self(run_on_main(|mtm| MainThreadBound::new(Retained::clone(self.0.get(mtm)), mtm))) + } +} + +impl<T: IsRetainable + Message> hash::Hash for MainThreadBoundDelegateImpls<T> { + fn hash<H: hash::Hasher>(&self, state: &mut H) { + // SAFETY: Marker only used to get the pointer + let mtm = unsafe { MainThreadMarker::new_unchecked() }; + Retained::as_ptr(self.0.get(mtm)).hash(state); + } +} + +impl<T: IsRetainable + Message> PartialEq for MainThreadBoundDelegateImpls<T> { + fn eq(&self, other: &Self) -> bool { + // SAFETY: Marker only used to get the pointer + let mtm = unsafe { MainThreadMarker::new_unchecked() }; + Retained::as_ptr(self.0.get(mtm)) == Retained::as_ptr(other.0.get(mtm)) + } +} + +impl<T: IsRetainable + Message> Eq for MainThreadBoundDelegateImpls<T> {} + +#[derive(Debug, PartialEq, Eq, Hash, Clone)] +pub struct VideoModeHandle { + pub(crate) size: (u32, u32), + pub(crate) bit_depth: u16, + pub(crate) refresh_rate_millihertz: u32, + screen_mode: MainThreadBoundDelegateImpls<UIScreenMode>, + pub(crate) monitor: MonitorHandle, +} + +impl VideoModeHandle { + fn new( + uiscreen: Retained<UIScreen>, + screen_mode: Retained<UIScreenMode>, + mtm: MainThreadMarker, + ) -> VideoModeHandle { + let refresh_rate_millihertz = refresh_rate_millihertz(&uiscreen); + let size = screen_mode.size(); + VideoModeHandle { + size: (size.width as u32, size.height as u32), + bit_depth: 32, + refresh_rate_millihertz, + screen_mode: MainThreadBoundDelegateImpls(MainThreadBound::new(screen_mode, mtm)), + monitor: MonitorHandle::new(uiscreen), + } + } + + pub fn size(&self) -> PhysicalSize<u32> { + self.size.into() + } + + pub fn bit_depth(&self) -> u16 { + self.bit_depth + } + + pub fn refresh_rate_millihertz(&self) -> u32 { + self.refresh_rate_millihertz + } + + pub fn monitor(&self) -> MonitorHandle { + self.monitor.clone() + } + + pub(super) fn screen_mode(&self, mtm: MainThreadMarker) -> &Retained<UIScreenMode> { + self.screen_mode.0.get(mtm) + } +} + +pub struct MonitorHandle { + ui_screen: MainThreadBound<Retained<UIScreen>>, +} + +impl Clone for MonitorHandle { + fn clone(&self) -> Self { + run_on_main(|mtm| Self { + ui_screen: MainThreadBound::new(self.ui_screen.get(mtm).clone(), mtm), + }) + } +} + +impl hash::Hash for MonitorHandle { + fn hash<H: hash::Hasher>(&self, state: &mut H) { + // SAFETY: Only getting the pointer. + let mtm = unsafe { MainThreadMarker::new_unchecked() }; + Retained::as_ptr(self.ui_screen.get(mtm)).hash(state); + } +} + +impl PartialEq for MonitorHandle { + fn eq(&self, other: &Self) -> bool { + // SAFETY: Only getting the pointer. + let mtm = unsafe { MainThreadMarker::new_unchecked() }; + ptr::eq( + Retained::as_ptr(self.ui_screen.get(mtm)), + Retained::as_ptr(other.ui_screen.get(mtm)), + ) + } +} + +impl Eq for MonitorHandle {} + +impl PartialOrd for MonitorHandle { + fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> { + Some(self.cmp(other)) + } +} + +impl Ord for MonitorHandle { + fn cmp(&self, other: &Self) -> std::cmp::Ordering { + // SAFETY: Only getting the pointer. + // TODO: Make a better ordering + let mtm = unsafe { MainThreadMarker::new_unchecked() }; + Retained::as_ptr(self.ui_screen.get(mtm)).cmp(&Retained::as_ptr(other.ui_screen.get(mtm))) + } +} + +impl fmt::Debug for MonitorHandle { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("MonitorHandle") + .field("name", &self.name()) + .field("size", &self.size()) + .field("position", &self.position()) + .field("scale_factor", &self.scale_factor()) + .field("refresh_rate_millihertz", &self.refresh_rate_millihertz()) + .finish_non_exhaustive() + } +} + +impl MonitorHandle { + pub(crate) fn new(ui_screen: Retained<UIScreen>) -> Self { + // Holding `Retained<UIScreen>` implies we're on the main thread. + let mtm = MainThreadMarker::new().unwrap(); + Self { ui_screen: MainThreadBound::new(ui_screen, mtm) } + } + + pub fn name(&self) -> Option<String> { + run_on_main(|mtm| { + #[allow(deprecated)] + let main = UIScreen::mainScreen(mtm); + if *self.ui_screen(mtm) == main { + Some("Primary".to_string()) + } else if Some(self.ui_screen(mtm)) == main.mirroredScreen().as_ref() { + Some("Mirrored".to_string()) + } else { + #[allow(deprecated)] + UIScreen::screens(mtm) + .iter() + .position(|rhs| rhs == &**self.ui_screen(mtm)) + .map(|idx| idx.to_string()) + } + }) + } + + pub fn size(&self) -> PhysicalSize<u32> { + let bounds = self.ui_screen.get_on_main(|ui_screen| ui_screen.nativeBounds()); + PhysicalSize::new(bounds.size.width as u32, bounds.size.height as u32) + } + + pub fn position(&self) -> PhysicalPosition<i32> { + let bounds = self.ui_screen.get_on_main(|ui_screen| ui_screen.nativeBounds()); + (bounds.origin.x as f64, bounds.origin.y as f64).into() + } + + pub fn scale_factor(&self) -> f64 { + self.ui_screen.get_on_main(|ui_screen| ui_screen.nativeScale()) as f64 + } + + pub fn refresh_rate_millihertz(&self) -> Option<u32> { + Some(self.ui_screen.get_on_main(|ui_screen| refresh_rate_millihertz(ui_screen))) + } + + pub fn video_modes(&self) -> impl Iterator<Item = VideoModeHandle> { + run_on_main(|mtm| { + let ui_screen = self.ui_screen(mtm); + // Use Ord impl of RootVideoModeHandle + + let modes: BTreeSet<_> = ui_screen + .availableModes() + .into_iter() + .map(|mode| RootVideoModeHandle { + video_mode: VideoModeHandle::new(ui_screen.clone(), mode, mtm), + }) + .collect(); + + modes.into_iter().map(|mode| mode.video_mode) + }) + } + + pub(crate) fn ui_screen(&self, mtm: MainThreadMarker) -> &Retained<UIScreen> { + self.ui_screen.get(mtm) + } + + pub fn preferred_video_mode(&self) -> VideoModeHandle { + run_on_main(|mtm| { + VideoModeHandle::new( + self.ui_screen(mtm).clone(), + self.ui_screen(mtm).preferredMode().unwrap(), + mtm, + ) + }) + } +} + +fn refresh_rate_millihertz(uiscreen: &UIScreen) -> u32 { + let refresh_rate_millihertz: NSInteger = { + let os_capabilities = app_state::os_capabilities(); + if os_capabilities.maximum_frames_per_second { + uiscreen.maximumFramesPerSecond() + } else { + // https://developer.apple.com/library/archive/technotes/tn2460/_index.html + // https://en.wikipedia.org/wiki/IPad_Pro#Model_comparison + // + // All iOS devices support 60 fps, and on devices where `maximumFramesPerSecond` is not + // supported, they are all guaranteed to have 60hz refresh rates. This does not + // correctly handle external displays. ProMotion displays support 120fps, but they were + // introduced at the same time as the `maximumFramesPerSecond` API. + // + // FIXME: earlier OSs could calculate the refresh rate using + // `-[CADisplayLink duration]`. + os_capabilities.maximum_frames_per_second_err_msg("defaulting to 60 fps"); + 60 + } + }; + + refresh_rate_millihertz as u32 * 1000 +} + +pub fn uiscreens(mtm: MainThreadMarker) -> VecDeque<MonitorHandle> { + #[allow(deprecated)] + UIScreen::screens(mtm).into_iter().map(MonitorHandle::new).collect() +} + +#[cfg(test)] +mod tests { + use objc2_foundation::NSSet; + + use super::*; + + // Test that UIScreen pointer comparisons are correct. + #[test] + #[allow(deprecated)] + fn screen_comparisons() { + // Test code, doesn't matter that it's not thread safe + let mtm = unsafe { MainThreadMarker::new_unchecked() }; + + assert!(ptr::eq(&*UIScreen::mainScreen(mtm), &*UIScreen::mainScreen(mtm))); + + let main = UIScreen::mainScreen(mtm); + assert!(UIScreen::screens(mtm).iter().any(|screen| ptr::eq(screen, &*main))); + + assert!(unsafe { + NSSet::setWithArray(&UIScreen::screens(mtm)).containsObject(&UIScreen::mainScreen(mtm)) + }); + } +} diff --git a/app/vendor/rune/vendor/winit/src/platform_impl/ios/notification_center.rs b/app/vendor/rune/vendor/winit/src/platform_impl/ios/notification_center.rs new file mode 100644 index 0000000..652bf1d --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/platform_impl/ios/notification_center.rs @@ -0,0 +1,27 @@ +use std::ptr::NonNull; + +use block2::RcBlock; +use objc2::rc::Retained; +use objc2_foundation::{NSNotification, NSNotificationCenter, NSNotificationName, NSObject}; + +/// Observe the given notification. +/// +/// This is used in Winit as an alternative to declaring an application delegate, as we want to +/// give the user full control over those. +pub fn create_observer( + center: &NSNotificationCenter, + name: &NSNotificationName, + handler: impl Fn(&NSNotification) + 'static, +) -> Retained<NSObject> { + let block = RcBlock::new(move |notification: NonNull<NSNotification>| { + handler(unsafe { notification.as_ref() }); + }); + unsafe { + center.addObserverForName_object_queue_usingBlock( + Some(name), + None, // No sender filter + None, // No queue, run on posting thread (i.e. main thread) + &block, + ) + } +} diff --git a/app/vendor/rune/vendor/winit/src/platform_impl/ios/view.rs b/app/vendor/rune/vendor/winit/src/platform_impl/ios/view.rs new file mode 100644 index 0000000..418968c --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/platform_impl/ios/view.rs @@ -0,0 +1,607 @@ +#![allow(clippy::unnecessary_cast)] +use std::cell::{Cell, RefCell}; + +use objc2::rc::Retained; +use objc2::runtime::{NSObjectProtocol, ProtocolObject}; +use objc2::{declare_class, msg_send, msg_send_id, mutability, sel, ClassType, DeclaredClass}; +use objc2_foundation::{CGFloat, CGPoint, CGRect, MainThreadMarker, NSObject, NSSet, NSString}; +use objc2_ui_kit::{ + UICoordinateSpace, UIEvent, UIForceTouchCapability, UIGestureRecognizer, + UIGestureRecognizerDelegate, UIGestureRecognizerState, UIKeyInput, UIPanGestureRecognizer, + UIPinchGestureRecognizer, UIResponder, UIRotationGestureRecognizer, UITapGestureRecognizer, + UITextInputTraits, UITouch, UITouchPhase, UITouchType, UITraitEnvironment, UIView, +}; + +use super::app_state::{self, EventWrapper}; +use super::window::WinitUIWindow; +use crate::dpi::PhysicalPosition; +use crate::event::{ElementState, Event, Force, KeyEvent, Touch, TouchPhase, WindowEvent}; +use crate::keyboard::{Key, KeyCode, KeyLocation, NamedKey, NativeKeyCode, PhysicalKey}; +use crate::platform_impl::platform::DEVICE_ID; +use crate::platform_impl::KeyEventExtra; +use crate::window::{WindowAttributes, WindowId as RootWindowId}; + +pub struct WinitViewState { + pinch_gesture_recognizer: RefCell<Option<Retained<UIPinchGestureRecognizer>>>, + doubletap_gesture_recognizer: RefCell<Option<Retained<UITapGestureRecognizer>>>, + rotation_gesture_recognizer: RefCell<Option<Retained<UIRotationGestureRecognizer>>>, + pan_gesture_recognizer: RefCell<Option<Retained<UIPanGestureRecognizer>>>, + + // for iOS delta references the start of the Gesture + rotation_last_delta: Cell<CGFloat>, + pinch_last_delta: Cell<CGFloat>, + pan_last_delta: Cell<CGPoint>, +} + +declare_class!( + pub(crate) struct WinitView; + + unsafe impl ClassType for WinitView { + #[inherits(UIResponder, NSObject)] + type Super = UIView; + type Mutability = mutability::MainThreadOnly; + const NAME: &'static str = "WinitUIView"; + } + + impl DeclaredClass for WinitView { + type Ivars = WinitViewState; + } + + unsafe impl WinitView { + #[method(drawRect:)] + fn draw_rect(&self, rect: CGRect) { + let mtm = MainThreadMarker::new().unwrap(); + let window = self.window().unwrap(); + app_state::handle_nonuser_event( + mtm, + EventWrapper::StaticEvent(Event::WindowEvent { + window_id: RootWindowId(window.id()), + event: WindowEvent::RedrawRequested, + }), + ); + let _: () = unsafe { msg_send![super(self), drawRect: rect] }; + } + + #[method(layoutSubviews)] + fn layout_subviews(&self) { + let mtm = MainThreadMarker::new().unwrap(); + let _: () = unsafe { msg_send![super(self), layoutSubviews] }; + + let window = self.window().unwrap(); + let window_bounds = window.bounds(); + let screen = window.screen(); + let screen_space = screen.coordinateSpace(); + let screen_frame = self.convertRect_toCoordinateSpace(window_bounds, &screen_space); + let scale_factor = screen.scale(); + let size = crate::dpi::LogicalSize { + width: screen_frame.size.width as f64, + height: screen_frame.size.height as f64, + } + .to_physical(scale_factor as f64); + + // If the app is started in landscape, the view frame and window bounds can be mismatched. + // The view frame will be in portrait and the window bounds in landscape. So apply the + // window bounds to the view frame to make it consistent. + let view_frame = self.frame(); + if view_frame != window_bounds { + self.setFrame(window_bounds); + } + + app_state::handle_nonuser_event( + mtm, + EventWrapper::StaticEvent(Event::WindowEvent { + window_id: RootWindowId(window.id()), + event: WindowEvent::Resized(size), + }), + ); + } + + #[method(setContentScaleFactor:)] + fn set_content_scale_factor(&self, untrusted_scale_factor: CGFloat) { + let mtm = MainThreadMarker::new().unwrap(); + let _: () = + unsafe { msg_send![super(self), setContentScaleFactor: untrusted_scale_factor] }; + + // `window` is null when `setContentScaleFactor` is invoked prior to `[UIWindow + // makeKeyAndVisible]` at window creation time (either manually or internally by + // UIKit when the `UIView` is first created), in which case we send no events here + let window = match self.window() { + Some(window) => window, + None => return, + }; + // `setContentScaleFactor` may be called with a value of 0, which means "reset the + // content scale factor to a device-specific default value", so we can't use the + // parameter here. We can query the actual factor using the getter + let scale_factor = self.contentScaleFactor(); + assert!( + !scale_factor.is_nan() + && scale_factor.is_finite() + && scale_factor.is_sign_positive() + && scale_factor > 0.0, + "invalid scale_factor set on UIView", + ); + let scale_factor = scale_factor as f64; + let bounds = self.bounds(); + let screen = window.screen(); + let screen_space = screen.coordinateSpace(); + let screen_frame = self.convertRect_toCoordinateSpace(bounds, &screen_space); + let size = crate::dpi::LogicalSize { + width: screen_frame.size.width as f64, + height: screen_frame.size.height as f64, + }; + let window_id = RootWindowId(window.id()); + app_state::handle_nonuser_events( + mtm, + std::iter::once(EventWrapper::ScaleFactorChanged( + app_state::ScaleFactorChanged { + window, + scale_factor, + suggested_size: size.to_physical(scale_factor), + }, + )) + .chain(std::iter::once(EventWrapper::StaticEvent( + Event::WindowEvent { + window_id, + event: WindowEvent::Resized(size.to_physical(scale_factor)), + }, + ))), + ); + } + + #[method(touchesBegan:withEvent:)] + fn touches_began(&self, touches: &NSSet<UITouch>, _event: Option<&UIEvent>) { + self.handle_touches(touches) + } + + #[method(touchesMoved:withEvent:)] + fn touches_moved(&self, touches: &NSSet<UITouch>, _event: Option<&UIEvent>) { + self.handle_touches(touches) + } + + #[method(touchesEnded:withEvent:)] + fn touches_ended(&self, touches: &NSSet<UITouch>, _event: Option<&UIEvent>) { + self.handle_touches(touches) + } + + #[method(touchesCancelled:withEvent:)] + fn touches_cancelled(&self, touches: &NSSet<UITouch>, _event: Option<&UIEvent>) { + self.handle_touches(touches) + } + + #[method(pinchGesture:)] + fn pinch_gesture(&self, recognizer: &UIPinchGestureRecognizer) { + let window = self.window().unwrap(); + + let (phase, delta) = match recognizer.state() { + UIGestureRecognizerState::Began => { + self.ivars().pinch_last_delta.set(recognizer.scale()); + (TouchPhase::Started, 0.0) + } + UIGestureRecognizerState::Changed => { + let last_scale: f64 = self.ivars().pinch_last_delta.replace(recognizer.scale()); + (TouchPhase::Moved, recognizer.scale() - last_scale) + } + UIGestureRecognizerState::Ended => { + let last_scale: f64 = self.ivars().pinch_last_delta.replace(0.0); + (TouchPhase::Moved, recognizer.scale() - last_scale) + } + UIGestureRecognizerState::Cancelled | UIGestureRecognizerState::Failed => { + self.ivars().rotation_last_delta.set(0.0); + // Pass -delta so that action is reversed + (TouchPhase::Cancelled, -recognizer.scale()) + } + state => panic!("unexpected recognizer state: {state:?}"), + }; + + let gesture_event = EventWrapper::StaticEvent(Event::WindowEvent { + window_id: RootWindowId(window.id()), + event: WindowEvent::PinchGesture { + device_id: DEVICE_ID, + delta: delta as f64, + phase, + }, + }); + + let mtm = MainThreadMarker::new().unwrap(); + app_state::handle_nonuser_event(mtm, gesture_event); + } + + #[method(doubleTapGesture:)] + fn double_tap_gesture(&self, recognizer: &UITapGestureRecognizer) { + let window = self.window().unwrap(); + + if recognizer.state() == UIGestureRecognizerState::Ended { + let gesture_event = EventWrapper::StaticEvent(Event::WindowEvent { + window_id: RootWindowId(window.id()), + event: WindowEvent::DoubleTapGesture { + device_id: DEVICE_ID, + }, + }); + + let mtm = MainThreadMarker::new().unwrap(); + app_state::handle_nonuser_event(mtm, gesture_event); + } + } + + #[method(rotationGesture:)] + fn rotation_gesture(&self, recognizer: &UIRotationGestureRecognizer) { + let window = self.window().unwrap(); + + let (phase, delta) = match recognizer.state() { + UIGestureRecognizerState::Began => { + self.ivars().rotation_last_delta.set(0.0); + + (TouchPhase::Started, 0.0) + } + UIGestureRecognizerState::Changed => { + let last_rotation = self.ivars().rotation_last_delta.replace(recognizer.rotation()); + + (TouchPhase::Moved, recognizer.rotation() - last_rotation) + } + UIGestureRecognizerState::Ended => { + let last_rotation = self.ivars().rotation_last_delta.replace(0.0); + + (TouchPhase::Ended, recognizer.rotation() - last_rotation) + } + UIGestureRecognizerState::Cancelled | UIGestureRecognizerState::Failed => { + self.ivars().rotation_last_delta.set(0.0); + + // Pass -delta so that action is reversed + (TouchPhase::Cancelled, -recognizer.rotation()) + } + state => panic!("unexpected recognizer state: {state:?}"), + }; + + // Make delta negative to match macos, convert to degrees + let gesture_event = EventWrapper::StaticEvent(Event::WindowEvent { + window_id: RootWindowId(window.id()), + event: WindowEvent::RotationGesture { + device_id: DEVICE_ID, + delta: -delta.to_degrees() as _, + phase, + }, + }); + + let mtm = MainThreadMarker::new().unwrap(); + app_state::handle_nonuser_event(mtm, gesture_event); + } + + #[method(panGesture:)] + fn pan_gesture(&self, recognizer: &UIPanGestureRecognizer) { + let window = self.window().unwrap(); + + let translation = recognizer.translationInView(Some(self)); + + let (phase, dx, dy) = match recognizer.state() { + UIGestureRecognizerState::Began => { + self.ivars().pan_last_delta.set(translation); + + (TouchPhase::Started, 0.0, 0.0) + } + UIGestureRecognizerState::Changed => { + let last_pan: CGPoint = self.ivars().pan_last_delta.replace(translation); + + let dx = translation.x - last_pan.x; + let dy = translation.y - last_pan.y; + + (TouchPhase::Moved, dx, dy) + } + UIGestureRecognizerState::Ended => { + let last_pan: CGPoint = self.ivars().pan_last_delta.replace(CGPoint{x:0.0, y:0.0}); + + let dx = translation.x - last_pan.x; + let dy = translation.y - last_pan.y; + + (TouchPhase::Ended, dx, dy) + } + UIGestureRecognizerState::Cancelled | UIGestureRecognizerState::Failed => { + let last_pan: CGPoint = self.ivars().pan_last_delta.replace(CGPoint{x:0.0, y:0.0}); + + // Pass -delta so that action is reversed + (TouchPhase::Cancelled, -last_pan.x, -last_pan.y) + } + state => panic!("unexpected recognizer state: {state:?}"), + }; + + + let gesture_event = EventWrapper::StaticEvent(Event::WindowEvent { + window_id: RootWindowId(window.id()), + event: WindowEvent::PanGesture { + device_id: DEVICE_ID, + delta: PhysicalPosition::new(dx as _, dy as _), + phase, + }, + }); + + let mtm = MainThreadMarker::new().unwrap(); + app_state::handle_nonuser_event(mtm, gesture_event); + } + + #[method(canBecomeFirstResponder)] + fn can_become_first_responder(&self) -> bool { + true + } + } + + unsafe impl NSObjectProtocol for WinitView {} + + unsafe impl UIGestureRecognizerDelegate for WinitView { + #[method(gestureRecognizer:shouldRecognizeSimultaneouslyWithGestureRecognizer:)] + fn should_recognize_simultaneously(&self, _gesture_recognizer: &UIGestureRecognizer, _other_gesture_recognizer: &UIGestureRecognizer) -> bool { + true + } + } + + unsafe impl UITextInputTraits for WinitView { + } + + unsafe impl UIKeyInput for WinitView { + #[method(hasText)] + fn has_text(&self) -> bool { + true + } + + #[method(insertText:)] + fn insert_text(&self, text: &NSString) { + self.handle_insert_text(text) + } + + #[method(deleteBackward)] + fn delete_backward(&self) { + self.handle_delete_backward() + } + } +); + +impl WinitView { + pub(crate) fn new( + mtm: MainThreadMarker, + window_attributes: &WindowAttributes, + frame: CGRect, + ) -> Retained<Self> { + let this = mtm.alloc().set_ivars(WinitViewState { + pinch_gesture_recognizer: RefCell::new(None), + doubletap_gesture_recognizer: RefCell::new(None), + rotation_gesture_recognizer: RefCell::new(None), + pan_gesture_recognizer: RefCell::new(None), + + rotation_last_delta: Cell::new(0.0), + pinch_last_delta: Cell::new(0.0), + pan_last_delta: Cell::new(CGPoint { x: 0.0, y: 0.0 }), + }); + let this: Retained<Self> = unsafe { msg_send_id![super(this), initWithFrame: frame] }; + + this.setMultipleTouchEnabled(true); + + if let Some(scale_factor) = window_attributes.platform_specific.scale_factor { + this.setContentScaleFactor(scale_factor as _); + } + + this + } + + fn window(&self) -> Option<Retained<WinitUIWindow>> { + // SAFETY: `WinitView`s are always installed in a `WinitUIWindow` + (**self).window().map(|window| unsafe { Retained::cast(window) }) + } + + pub(crate) fn recognize_pinch_gesture(&self, should_recognize: bool) { + let mtm = MainThreadMarker::from(self); + if should_recognize { + if self.ivars().pinch_gesture_recognizer.borrow().is_none() { + let pinch = unsafe { + UIPinchGestureRecognizer::initWithTarget_action( + mtm.alloc(), + Some(self), + Some(sel!(pinchGesture:)), + ) + }; + pinch.setDelegate(Some(ProtocolObject::from_ref(self))); + self.addGestureRecognizer(&pinch); + self.ivars().pinch_gesture_recognizer.replace(Some(pinch)); + } + } else if let Some(recognizer) = self.ivars().pinch_gesture_recognizer.take() { + self.removeGestureRecognizer(&recognizer); + } + } + + pub(crate) fn recognize_pan_gesture( + &self, + should_recognize: bool, + minimum_number_of_touches: u8, + maximum_number_of_touches: u8, + ) { + let mtm = MainThreadMarker::from(self); + if should_recognize { + if self.ivars().pan_gesture_recognizer.borrow().is_none() { + let pan = unsafe { + UIPanGestureRecognizer::initWithTarget_action( + mtm.alloc(), + Some(self), + Some(sel!(panGesture:)), + ) + }; + pan.setDelegate(Some(ProtocolObject::from_ref(self))); + pan.setMinimumNumberOfTouches(minimum_number_of_touches as _); + pan.setMaximumNumberOfTouches(maximum_number_of_touches as _); + self.addGestureRecognizer(&pan); + self.ivars().pan_gesture_recognizer.replace(Some(pan)); + } + } else if let Some(recognizer) = self.ivars().pan_gesture_recognizer.take() { + self.removeGestureRecognizer(&recognizer); + } + } + + pub(crate) fn recognize_doubletap_gesture(&self, should_recognize: bool) { + let mtm = MainThreadMarker::from(self); + if should_recognize { + if self.ivars().doubletap_gesture_recognizer.borrow().is_none() { + let tap = unsafe { + UITapGestureRecognizer::initWithTarget_action( + mtm.alloc(), + Some(self), + Some(sel!(doubleTapGesture:)), + ) + }; + tap.setDelegate(Some(ProtocolObject::from_ref(self))); + tap.setNumberOfTapsRequired(2); + tap.setNumberOfTouchesRequired(1); + self.addGestureRecognizer(&tap); + self.ivars().doubletap_gesture_recognizer.replace(Some(tap)); + } + } else if let Some(recognizer) = self.ivars().doubletap_gesture_recognizer.take() { + self.removeGestureRecognizer(&recognizer); + } + } + + pub(crate) fn recognize_rotation_gesture(&self, should_recognize: bool) { + let mtm = MainThreadMarker::from(self); + if should_recognize { + if self.ivars().rotation_gesture_recognizer.borrow().is_none() { + let rotation = unsafe { + UIRotationGestureRecognizer::initWithTarget_action( + mtm.alloc(), + Some(self), + Some(sel!(rotationGesture:)), + ) + }; + rotation.setDelegate(Some(ProtocolObject::from_ref(self))); + self.addGestureRecognizer(&rotation); + self.ivars().rotation_gesture_recognizer.replace(Some(rotation)); + } + } else if let Some(recognizer) = self.ivars().rotation_gesture_recognizer.take() { + self.removeGestureRecognizer(&recognizer); + } + } + + fn handle_touches(&self, touches: &NSSet<UITouch>) { + let window = self.window().unwrap(); + let mut touch_events = Vec::new(); + let os_supports_force = app_state::os_capabilities().force_touch; + for touch in touches { + let logical_location = touch.locationInView(None); + let touch_type = touch.r#type(); + let force = if os_supports_force { + let trait_collection = self.traitCollection(); + let touch_capability = trait_collection.forceTouchCapability(); + // Both the OS _and_ the device need to be checked for force touch support. + if touch_capability == UIForceTouchCapability::Available + || touch_type == UITouchType::Pencil + { + let force = touch.force(); + let max_possible_force = touch.maximumPossibleForce(); + let altitude_angle: Option<f64> = if touch_type == UITouchType::Pencil { + let angle = touch.altitudeAngle(); + Some(angle as _) + } else { + None + }; + Some(Force::Calibrated { + force: force as _, + max_possible_force: max_possible_force as _, + altitude_angle, + }) + } else { + None + } + } else { + None + }; + let touch_id = touch as *const UITouch as u64; + let phase = touch.phase(); + let phase = match phase { + UITouchPhase::Began => TouchPhase::Started, + UITouchPhase::Moved => TouchPhase::Moved, + // 2 is UITouchPhase::Stationary and is not expected here + UITouchPhase::Ended => TouchPhase::Ended, + UITouchPhase::Cancelled => TouchPhase::Cancelled, + _ => panic!("unexpected touch phase: {phase:?}"), + }; + + let physical_location = { + let scale_factor = self.contentScaleFactor(); + PhysicalPosition::from_logical::<(f64, f64), f64>( + (logical_location.x as _, logical_location.y as _), + scale_factor as f64, + ) + }; + touch_events.push(EventWrapper::StaticEvent(Event::WindowEvent { + window_id: RootWindowId(window.id()), + event: WindowEvent::Touch(Touch { + device_id: DEVICE_ID, + id: touch_id, + location: physical_location, + force, + phase, + }), + })); + } + let mtm = MainThreadMarker::new().unwrap(); + app_state::handle_nonuser_events(mtm, touch_events); + } + + fn handle_insert_text(&self, text: &NSString) { + let window = self.window().unwrap(); + let window_id = RootWindowId(window.id()); + let mtm = MainThreadMarker::new().unwrap(); + // send individual events for each character + app_state::handle_nonuser_events( + mtm, + text.to_string().chars().flat_map(|c| { + let text = smol_str::SmolStr::from_iter([c]); + // Emit both press and release events + [ElementState::Pressed, ElementState::Released].map(|state| { + EventWrapper::StaticEvent(Event::WindowEvent { + window_id, + event: WindowEvent::KeyboardInput { + event: KeyEvent { + text: if state == ElementState::Pressed { + Some(text.clone()) + } else { + None + }, + state, + location: KeyLocation::Standard, + repeat: false, + logical_key: Key::Character(text.clone()), + physical_key: PhysicalKey::Unidentified( + NativeKeyCode::Unidentified, + ), + platform_specific: KeyEventExtra {}, + }, + is_synthetic: false, + device_id: DEVICE_ID, + }, + }) + }) + }), + ); + } + + fn handle_delete_backward(&self) { + let window = self.window().unwrap(); + let window_id = RootWindowId(window.id()); + let mtm = MainThreadMarker::new().unwrap(); + app_state::handle_nonuser_events( + mtm, + [ElementState::Pressed, ElementState::Released].map(|state| { + EventWrapper::StaticEvent(Event::WindowEvent { + window_id, + event: WindowEvent::KeyboardInput { + device_id: DEVICE_ID, + event: KeyEvent { + state, + logical_key: Key::Named(NamedKey::Backspace), + physical_key: PhysicalKey::Code(KeyCode::Backspace), + platform_specific: KeyEventExtra {}, + repeat: false, + location: KeyLocation::Standard, + text: None, + }, + is_synthetic: false, + }, + }) + }), + ); + } +} diff --git a/app/vendor/rune/vendor/winit/src/platform_impl/ios/view_controller.rs b/app/vendor/rune/vendor/winit/src/platform_impl/ios/view_controller.rs new file mode 100644 index 0000000..dd65868 --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/platform_impl/ios/view_controller.rs @@ -0,0 +1,176 @@ +use std::cell::Cell; + +use objc2::rc::Retained; +use objc2::{declare_class, msg_send_id, mutability, ClassType, DeclaredClass}; +use objc2_foundation::{MainThreadMarker, NSObject}; +use objc2_ui_kit::{ + UIDevice, UIInterfaceOrientationMask, UIRectEdge, UIResponder, UIStatusBarStyle, + UIUserInterfaceIdiom, UIView, UIViewController, +}; + +use super::app_state::{self}; +use crate::platform::ios::{ScreenEdge, StatusBarStyle, ValidOrientations}; +use crate::window::WindowAttributes; + +pub struct ViewControllerState { + prefers_status_bar_hidden: Cell<bool>, + preferred_status_bar_style: Cell<UIStatusBarStyle>, + prefers_home_indicator_auto_hidden: Cell<bool>, + supported_orientations: Cell<UIInterfaceOrientationMask>, + preferred_screen_edges_deferring_system_gestures: Cell<UIRectEdge>, +} + +declare_class!( + pub(crate) struct WinitViewController; + + unsafe impl ClassType for WinitViewController { + #[inherits(UIResponder, NSObject)] + type Super = UIViewController; + type Mutability = mutability::MainThreadOnly; + const NAME: &'static str = "WinitUIViewController"; + } + + impl DeclaredClass for WinitViewController { + type Ivars = ViewControllerState; + } + + unsafe impl WinitViewController { + #[method(shouldAutorotate)] + fn should_autorotate(&self) -> bool { + true + } + + #[method(prefersStatusBarHidden)] + fn prefers_status_bar_hidden(&self) -> bool { + self.ivars().prefers_status_bar_hidden.get() + } + + #[method(preferredStatusBarStyle)] + fn preferred_status_bar_style(&self) -> UIStatusBarStyle { + self.ivars().preferred_status_bar_style.get() + } + + #[method(prefersHomeIndicatorAutoHidden)] + fn prefers_home_indicator_auto_hidden(&self) -> bool { + self.ivars().prefers_home_indicator_auto_hidden.get() + } + + #[method(supportedInterfaceOrientations)] + fn supported_orientations(&self) -> UIInterfaceOrientationMask { + self.ivars().supported_orientations.get() + } + + #[method(preferredScreenEdgesDeferringSystemGestures)] + fn preferred_screen_edges_deferring_system_gestures(&self) -> UIRectEdge { + self.ivars() + .preferred_screen_edges_deferring_system_gestures + .get() + } + } +); + +impl WinitViewController { + pub(crate) fn set_prefers_status_bar_hidden(&self, val: bool) { + self.ivars().prefers_status_bar_hidden.set(val); + self.setNeedsStatusBarAppearanceUpdate(); + } + + pub(crate) fn set_preferred_status_bar_style(&self, val: StatusBarStyle) { + let val = match val { + StatusBarStyle::Default => UIStatusBarStyle::Default, + StatusBarStyle::LightContent => UIStatusBarStyle::LightContent, + StatusBarStyle::DarkContent => UIStatusBarStyle::DarkContent, + }; + self.ivars().preferred_status_bar_style.set(val); + self.setNeedsStatusBarAppearanceUpdate(); + } + + pub(crate) fn set_prefers_home_indicator_auto_hidden(&self, val: bool) { + self.ivars().prefers_home_indicator_auto_hidden.set(val); + let os_capabilities = app_state::os_capabilities(); + if os_capabilities.home_indicator_hidden { + self.setNeedsUpdateOfHomeIndicatorAutoHidden(); + } else { + os_capabilities.home_indicator_hidden_err_msg("ignoring") + } + } + + pub(crate) fn set_preferred_screen_edges_deferring_system_gestures(&self, val: ScreenEdge) { + let val = { + assert_eq!(val.bits() & !ScreenEdge::ALL.bits(), 0, "invalid `ScreenEdge`"); + UIRectEdge(val.bits().into()) + }; + self.ivars().preferred_screen_edges_deferring_system_gestures.set(val); + let os_capabilities = app_state::os_capabilities(); + if os_capabilities.defer_system_gestures { + self.setNeedsUpdateOfScreenEdgesDeferringSystemGestures(); + } else { + os_capabilities.defer_system_gestures_err_msg("ignoring") + } + } + + pub(crate) fn set_supported_interface_orientations( + &self, + mtm: MainThreadMarker, + valid_orientations: ValidOrientations, + ) { + let mask = match (valid_orientations, UIDevice::currentDevice(mtm).userInterfaceIdiom()) { + (ValidOrientations::LandscapeAndPortrait, UIUserInterfaceIdiom::Phone) => { + UIInterfaceOrientationMask::AllButUpsideDown + }, + (ValidOrientations::LandscapeAndPortrait, _) => UIInterfaceOrientationMask::All, + (ValidOrientations::Landscape, _) => UIInterfaceOrientationMask::Landscape, + (ValidOrientations::Portrait, UIUserInterfaceIdiom::Phone) => { + UIInterfaceOrientationMask::Portrait + }, + (ValidOrientations::Portrait, _) => { + UIInterfaceOrientationMask::Portrait + | UIInterfaceOrientationMask::PortraitUpsideDown + }, + }; + self.ivars().supported_orientations.set(mask); + #[allow(deprecated)] + UIViewController::attemptRotationToDeviceOrientation(mtm); + } + + pub(crate) fn new( + mtm: MainThreadMarker, + window_attributes: &WindowAttributes, + view: &UIView, + ) -> Retained<Self> { + // These are set properly below, we just to set them to something in the meantime. + let this = mtm.alloc().set_ivars(ViewControllerState { + prefers_status_bar_hidden: Cell::new(false), + preferred_status_bar_style: Cell::new(UIStatusBarStyle::Default), + prefers_home_indicator_auto_hidden: Cell::new(false), + supported_orientations: Cell::new(UIInterfaceOrientationMask::All), + preferred_screen_edges_deferring_system_gestures: Cell::new(UIRectEdge::empty()), + }); + let this: Retained<Self> = unsafe { msg_send_id![super(this), init] }; + + this.set_prefers_status_bar_hidden( + window_attributes.platform_specific.prefers_status_bar_hidden, + ); + + this.set_preferred_status_bar_style( + window_attributes.platform_specific.preferred_status_bar_style, + ); + + this.set_supported_interface_orientations( + mtm, + window_attributes.platform_specific.valid_orientations, + ); + + this.set_prefers_home_indicator_auto_hidden( + window_attributes.platform_specific.prefers_home_indicator_hidden, + ); + + this.set_preferred_screen_edges_deferring_system_gestures( + window_attributes.platform_specific.preferred_screen_edges_deferring_system_gestures, + ); + + this.setView(Some(view)); + + this + } +} diff --git a/app/vendor/rune/vendor/winit/src/platform_impl/ios/window.rs b/app/vendor/rune/vendor/winit/src/platform_impl/ios/window.rs new file mode 100644 index 0000000..be02759 --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/platform_impl/ios/window.rs @@ -0,0 +1,750 @@ +#![allow(clippy::unnecessary_cast)] + +use std::collections::VecDeque; + +use objc2::rc::Retained; +use objc2::runtime::{AnyObject, NSObject}; +use objc2::{class, declare_class, msg_send, msg_send_id, mutability, ClassType, DeclaredClass}; +use objc2_foundation::{ + CGFloat, CGPoint, CGRect, CGSize, MainThreadBound, MainThreadMarker, NSObjectProtocol, +}; +use objc2_ui_kit::{ + UIApplication, UICoordinateSpace, UIResponder, UIScreen, UIScreenOverscanCompensation, + UIViewController, UIWindow, +}; +use tracing::{debug, warn}; + +use super::app_state::EventWrapper; +use super::view::WinitView; +use super::view_controller::WinitViewController; +use crate::cursor::Cursor; +use crate::dpi::{LogicalPosition, LogicalSize, PhysicalPosition, PhysicalSize, Position, Size}; +use crate::error::{ExternalError, NotSupportedError, OsError as RootOsError}; +use crate::event::{Event, WindowEvent}; +use crate::icon::Icon; +use crate::platform::ios::{ScreenEdge, StatusBarStyle, ValidOrientations}; +use crate::platform_impl::platform::{ + app_state, monitor, ActiveEventLoop, Fullscreen, MonitorHandle, +}; +use crate::window::{ + CursorGrabMode, ImePurpose, ResizeDirection, Theme, UserAttentionType, WindowAttributes, + WindowButtons, WindowId as RootWindowId, WindowLevel, +}; + +declare_class!( + #[derive(Debug, PartialEq, Eq, Hash)] + pub(crate) struct WinitUIWindow; + + unsafe impl ClassType for WinitUIWindow { + #[inherits(UIResponder, NSObject)] + type Super = UIWindow; + type Mutability = mutability::MainThreadOnly; + const NAME: &'static str = "WinitUIWindow"; + } + + impl DeclaredClass for WinitUIWindow {} + + unsafe impl WinitUIWindow { + #[method(becomeKeyWindow)] + fn become_key_window(&self) { + let mtm = MainThreadMarker::new().unwrap(); + app_state::handle_nonuser_event( + mtm, + EventWrapper::StaticEvent(Event::WindowEvent { + window_id: RootWindowId(self.id()), + event: WindowEvent::Focused(true), + }), + ); + let _: () = unsafe { msg_send![super(self), becomeKeyWindow] }; + } + + #[method(resignKeyWindow)] + fn resign_key_window(&self) { + let mtm = MainThreadMarker::new().unwrap(); + app_state::handle_nonuser_event( + mtm, + EventWrapper::StaticEvent(Event::WindowEvent { + window_id: RootWindowId(self.id()), + event: WindowEvent::Focused(false), + }), + ); + let _: () = unsafe { msg_send![super(self), resignKeyWindow] }; + } + } +); + +impl WinitUIWindow { + pub(crate) fn new( + mtm: MainThreadMarker, + window_attributes: &WindowAttributes, + frame: CGRect, + view_controller: &UIViewController, + ) -> Retained<Self> { + let this: Retained<Self> = unsafe { msg_send_id![mtm.alloc(), initWithFrame: frame] }; + + this.setRootViewController(Some(view_controller)); + + match window_attributes.fullscreen.clone().map(Into::into) { + Some(Fullscreen::Exclusive(ref video_mode)) => { + let monitor = video_mode.monitor(); + let screen = monitor.ui_screen(mtm); + screen.setCurrentMode(Some(video_mode.screen_mode(mtm))); + this.setScreen(screen); + }, + Some(Fullscreen::Borderless(Some(ref monitor))) => { + let screen = monitor.ui_screen(mtm); + this.setScreen(screen); + }, + _ => (), + } + + this + } + + pub(crate) fn id(&self) -> WindowId { + (self as *const Self as usize as u64).into() + } +} + +pub struct Inner { + window: Retained<WinitUIWindow>, + view_controller: Retained<WinitViewController>, + view: Retained<WinitView>, + gl_or_metal_backed: bool, +} + +impl Inner { + pub fn set_title(&self, _title: &str) { + debug!("`Window::set_title` is ignored on iOS") + } + + pub fn set_transparent(&self, _transparent: bool) { + debug!("`Window::set_transparent` is ignored on iOS") + } + + pub fn set_blur(&self, _blur: bool) { + debug!("`Window::set_blur` is ignored on iOS") + } + + pub fn set_visible(&self, visible: bool) { + self.window.setHidden(!visible) + } + + pub fn is_visible(&self) -> Option<bool> { + warn!("`Window::is_visible` is ignored on iOS"); + None + } + + pub fn request_redraw(&self) { + if self.gl_or_metal_backed { + let mtm = MainThreadMarker::new().unwrap(); + // `setNeedsDisplay` does nothing on UIViews which are directly backed by CAEAGLLayer or + // CAMetalLayer. Ordinarily the OS sets up a bunch of UIKit state before + // calling drawRect: on a UIView, but when using raw or gl/metal for drawing + // this work is completely avoided. + // + // The docs for `setNeedsDisplay` don't mention `CAMetalLayer`; however, this has been + // confirmed via testing. + // + // https://developer.apple.com/documentation/uikit/uiview/1622437-setneedsdisplay?language=objc + app_state::queue_gl_or_metal_redraw(mtm, self.window.clone()); + } else { + self.view.setNeedsDisplay(); + } + } + + pub fn pre_present_notify(&self) {} + + pub fn inner_position(&self) -> Result<PhysicalPosition<i32>, NotSupportedError> { + let safe_area = self.safe_area_screen_space(); + let position = + LogicalPosition { x: safe_area.origin.x as f64, y: safe_area.origin.y as f64 }; + let scale_factor = self.scale_factor(); + Ok(position.to_physical(scale_factor)) + } + + pub fn outer_position(&self) -> Result<PhysicalPosition<i32>, NotSupportedError> { + let screen_frame = self.screen_frame(); + let position = + LogicalPosition { x: screen_frame.origin.x as f64, y: screen_frame.origin.y as f64 }; + let scale_factor = self.scale_factor(); + Ok(position.to_physical(scale_factor)) + } + + pub fn set_outer_position(&self, physical_position: Position) { + let scale_factor = self.scale_factor(); + let position = physical_position.to_logical::<f64>(scale_factor); + let screen_frame = self.screen_frame(); + let new_screen_frame = CGRect { + origin: CGPoint { x: position.x as _, y: position.y as _ }, + size: screen_frame.size, + }; + let bounds = self.rect_from_screen_space(new_screen_frame); + self.window.setBounds(bounds); + } + + pub fn inner_size(&self) -> PhysicalSize<u32> { + let scale_factor = self.scale_factor(); + let safe_area = self.safe_area_screen_space(); + let size = LogicalSize { + width: safe_area.size.width as f64, + height: safe_area.size.height as f64, + }; + size.to_physical(scale_factor) + } + + pub fn outer_size(&self) -> PhysicalSize<u32> { + let scale_factor = self.scale_factor(); + let screen_frame = self.screen_frame(); + let size = LogicalSize { + width: screen_frame.size.width as f64, + height: screen_frame.size.height as f64, + }; + size.to_physical(scale_factor) + } + + pub fn request_inner_size(&self, _size: Size) -> Option<PhysicalSize<u32>> { + Some(self.inner_size()) + } + + pub fn set_min_inner_size(&self, _dimensions: Option<Size>) { + warn!("`Window::set_min_inner_size` is ignored on iOS") + } + + pub fn set_max_inner_size(&self, _dimensions: Option<Size>) { + warn!("`Window::set_max_inner_size` is ignored on iOS") + } + + pub fn resize_increments(&self) -> Option<PhysicalSize<u32>> { + None + } + + #[inline] + pub fn set_resize_increments(&self, _increments: Option<Size>) { + warn!("`Window::set_resize_increments` is ignored on iOS") + } + + pub fn set_resizable(&self, _resizable: bool) { + warn!("`Window::set_resizable` is ignored on iOS") + } + + pub fn is_resizable(&self) -> bool { + warn!("`Window::is_resizable` is ignored on iOS"); + false + } + + #[inline] + pub fn set_enabled_buttons(&self, _buttons: WindowButtons) { + warn!("`Window::set_enabled_buttons` is ignored on iOS"); + } + + #[inline] + pub fn enabled_buttons(&self) -> WindowButtons { + warn!("`Window::enabled_buttons` is ignored on iOS"); + WindowButtons::all() + } + + pub fn scale_factor(&self) -> f64 { + self.view.contentScaleFactor() as _ + } + + pub fn set_cursor(&self, _cursor: Cursor) { + debug!("`Window::set_cursor` ignored on iOS") + } + + pub fn set_cursor_position(&self, _position: Position) -> Result<(), ExternalError> { + Err(ExternalError::NotSupported(NotSupportedError::new())) + } + + pub fn set_cursor_grab(&self, _: CursorGrabMode) -> Result<(), ExternalError> { + Err(ExternalError::NotSupported(NotSupportedError::new())) + } + + pub fn set_cursor_visible(&self, _visible: bool) { + debug!("`Window::set_cursor_visible` is ignored on iOS") + } + + pub fn drag_window(&self) -> Result<(), ExternalError> { + Err(ExternalError::NotSupported(NotSupportedError::new())) + } + + pub fn drag_resize_window(&self, _direction: ResizeDirection) -> Result<(), ExternalError> { + Err(ExternalError::NotSupported(NotSupportedError::new())) + } + + #[inline] + pub fn show_window_menu(&self, _position: Position) {} + + pub fn set_cursor_hittest(&self, _hittest: bool) -> Result<(), ExternalError> { + Err(ExternalError::NotSupported(NotSupportedError::new())) + } + + pub fn set_minimized(&self, _minimized: bool) { + warn!("`Window::set_minimized` is ignored on iOS") + } + + pub fn is_minimized(&self) -> Option<bool> { + warn!("`Window::is_minimized` is ignored on iOS"); + None + } + + pub fn set_maximized(&self, _maximized: bool) { + warn!("`Window::set_maximized` is ignored on iOS") + } + + pub fn is_maximized(&self) -> bool { + warn!("`Window::is_maximized` is ignored on iOS"); + false + } + + pub(crate) fn set_fullscreen(&self, monitor: Option<Fullscreen>) { + let mtm = MainThreadMarker::new().unwrap(); + let uiscreen = match &monitor { + Some(Fullscreen::Exclusive(video_mode)) => { + let uiscreen = video_mode.monitor.ui_screen(mtm); + uiscreen.setCurrentMode(Some(video_mode.screen_mode(mtm))); + uiscreen.clone() + }, + Some(Fullscreen::Borderless(Some(monitor))) => monitor.ui_screen(mtm).clone(), + Some(Fullscreen::Borderless(None)) => { + self.current_monitor_inner().ui_screen(mtm).clone() + }, + None => { + warn!("`Window::set_fullscreen(None)` ignored on iOS"); + return; + }, + }; + + // this is pretty slow on iOS, so avoid doing it if we can + let current = self.window.screen(); + if uiscreen != current { + self.window.setScreen(&uiscreen); + } + + let bounds = uiscreen.bounds(); + self.window.setFrame(bounds); + + // For external displays, we must disable overscan compensation or + // the displayed image will have giant black bars surrounding it on + // each side + uiscreen.setOverscanCompensation(UIScreenOverscanCompensation::None); + } + + pub(crate) fn fullscreen(&self) -> Option<Fullscreen> { + let mtm = MainThreadMarker::new().unwrap(); + let monitor = self.current_monitor_inner(); + let uiscreen = monitor.ui_screen(mtm); + let screen_space_bounds = self.screen_frame(); + let screen_bounds = uiscreen.bounds(); + + // TODO: track fullscreen instead of relying on brittle float comparisons + if screen_space_bounds.origin.x == screen_bounds.origin.x + && screen_space_bounds.origin.y == screen_bounds.origin.y + && screen_space_bounds.size.width == screen_bounds.size.width + && screen_space_bounds.size.height == screen_bounds.size.height + { + Some(Fullscreen::Borderless(Some(monitor))) + } else { + None + } + } + + pub fn set_decorations(&self, _decorations: bool) {} + + pub fn is_decorated(&self) -> bool { + true + } + + pub fn set_window_level(&self, _level: WindowLevel) { + warn!("`Window::set_window_level` is ignored on iOS") + } + + pub fn set_window_icon(&self, _icon: Option<Icon>) { + warn!("`Window::set_window_icon` is ignored on iOS") + } + + pub fn set_ime_cursor_area(&self, _position: Position, _size: Size) { + warn!("`Window::set_ime_cursor_area` is ignored on iOS") + } + + /// Show / hide the keyboard. To show the keyboard, we call `becomeFirstResponder`, + /// requesting focus for the [WinitView]. Since [WinitView] implements + /// [objc2_ui_kit::UIKeyInput], the keyboard will be shown. + /// <https://developer.apple.com/documentation/uikit/uiresponder/1621113-becomefirstresponder> + pub fn set_ime_allowed(&self, allowed: bool) { + if allowed { + unsafe { + self.view.becomeFirstResponder(); + } + } else { + unsafe { + self.view.resignFirstResponder(); + } + } + } + + pub fn set_ime_purpose(&self, _purpose: ImePurpose) { + warn!("`Window::set_ime_purpose` is ignored on iOS") + } + + pub fn focus_window(&self) { + warn!("`Window::set_focus` is ignored on iOS") + } + + pub fn request_user_attention(&self, _request_type: Option<UserAttentionType>) { + warn!("`Window::request_user_attention` is ignored on iOS") + } + + // Allow directly accessing the current monitor internally without unwrapping. + fn current_monitor_inner(&self) -> MonitorHandle { + MonitorHandle::new(self.window.screen()) + } + + pub fn current_monitor(&self) -> Option<MonitorHandle> { + Some(self.current_monitor_inner()) + } + + pub fn available_monitors(&self) -> VecDeque<MonitorHandle> { + monitor::uiscreens(MainThreadMarker::new().unwrap()) + } + + pub fn primary_monitor(&self) -> Option<MonitorHandle> { + #[allow(deprecated)] + Some(MonitorHandle::new(UIScreen::mainScreen(MainThreadMarker::new().unwrap()))) + } + + pub fn id(&self) -> WindowId { + self.window.id() + } + + #[cfg(feature = "rwh_04")] + pub fn raw_window_handle_rwh_04(&self) -> rwh_04::RawWindowHandle { + let mut window_handle = rwh_04::UiKitHandle::empty(); + window_handle.ui_window = Retained::as_ptr(&self.window) as _; + window_handle.ui_view = Retained::as_ptr(&self.view) as _; + window_handle.ui_view_controller = Retained::as_ptr(&self.view_controller) as _; + rwh_04::RawWindowHandle::UiKit(window_handle) + } + + #[cfg(feature = "rwh_05")] + pub fn raw_window_handle_rwh_05(&self) -> rwh_05::RawWindowHandle { + let mut window_handle = rwh_05::UiKitWindowHandle::empty(); + window_handle.ui_window = Retained::as_ptr(&self.window) as _; + window_handle.ui_view = Retained::as_ptr(&self.view) as _; + window_handle.ui_view_controller = Retained::as_ptr(&self.view_controller) as _; + rwh_05::RawWindowHandle::UiKit(window_handle) + } + + #[cfg(feature = "rwh_05")] + pub fn raw_display_handle_rwh_05(&self) -> rwh_05::RawDisplayHandle { + rwh_05::RawDisplayHandle::UiKit(rwh_05::UiKitDisplayHandle::empty()) + } + + #[cfg(feature = "rwh_06")] + pub fn raw_window_handle_rwh_06(&self) -> rwh_06::RawWindowHandle { + let mut window_handle = rwh_06::UiKitWindowHandle::new({ + let ui_view = Retained::as_ptr(&self.view) as _; + std::ptr::NonNull::new(ui_view).expect("Retained<T> should never be null") + }); + window_handle.ui_view_controller = + std::ptr::NonNull::new(Retained::as_ptr(&self.view_controller) as _); + rwh_06::RawWindowHandle::UiKit(window_handle) + } + + pub fn theme(&self) -> Option<Theme> { + warn!("`Window::theme` is ignored on iOS"); + None + } + + pub fn set_content_protected(&self, _protected: bool) {} + + pub fn has_focus(&self) -> bool { + self.window.isKeyWindow() + } + + #[inline] + pub fn set_theme(&self, _theme: Option<Theme>) { + warn!("`Window::set_theme` is ignored on iOS"); + } + + pub fn title(&self) -> String { + warn!("`Window::title` is ignored on iOS"); + String::new() + } + + pub fn reset_dead_keys(&self) { + // Noop + } +} + +pub struct Window { + inner: MainThreadBound<Inner>, +} + +impl Window { + pub(crate) fn new( + event_loop: &ActiveEventLoop, + window_attributes: WindowAttributes, + ) -> Result<Window, RootOsError> { + let mtm = event_loop.mtm; + + if window_attributes.min_inner_size.is_some() { + warn!("`WindowAttributes::min_inner_size` is ignored on iOS"); + } + if window_attributes.max_inner_size.is_some() { + warn!("`WindowAttributes::max_inner_size` is ignored on iOS"); + } + + // TODO: transparency, visible + + #[allow(deprecated)] + let main_screen = UIScreen::mainScreen(mtm); + let fullscreen = window_attributes.fullscreen.clone().map(Into::into); + let screen = match fullscreen { + Some(Fullscreen::Exclusive(ref video_mode)) => video_mode.monitor.ui_screen(mtm), + Some(Fullscreen::Borderless(Some(ref monitor))) => monitor.ui_screen(mtm), + Some(Fullscreen::Borderless(None)) | None => &main_screen, + }; + + let screen_bounds = screen.bounds(); + + let frame = match window_attributes.inner_size { + Some(dim) => { + let scale_factor = screen.scale(); + let size = dim.to_logical::<f64>(scale_factor as f64); + CGRect { + origin: screen_bounds.origin, + size: CGSize { width: size.width as _, height: size.height as _ }, + } + }, + None => screen_bounds, + }; + + let view = WinitView::new(mtm, &window_attributes, frame); + + let gl_or_metal_backed = + view.isKindOfClass(class!(CAMetalLayer)) || view.isKindOfClass(class!(CAEAGLLayer)); + + let view_controller = WinitViewController::new(mtm, &window_attributes, &view); + let window = WinitUIWindow::new(mtm, &window_attributes, frame, &view_controller); + + app_state::set_key_window(mtm, &window); + + // Like the Windows and macOS backends, we send a `ScaleFactorChanged` and `Resized` + // event on window creation if the DPI factor != 1.0 + let scale_factor = view.contentScaleFactor(); + let scale_factor = scale_factor as f64; + if scale_factor != 1.0 { + let bounds = view.bounds(); + let screen = window.screen(); + let screen_space = screen.coordinateSpace(); + let screen_frame = view.convertRect_toCoordinateSpace(bounds, &screen_space); + let size = LogicalSize { + width: screen_frame.size.width as f64, + height: screen_frame.size.height as f64, + }; + let window_id = RootWindowId(window.id()); + app_state::handle_nonuser_events( + mtm, + std::iter::once(EventWrapper::ScaleFactorChanged(app_state::ScaleFactorChanged { + window: window.clone(), + scale_factor, + suggested_size: size.to_physical(scale_factor), + })) + .chain(std::iter::once(EventWrapper::StaticEvent( + Event::WindowEvent { + window_id, + event: WindowEvent::Resized(size.to_physical(scale_factor)), + }, + ))), + ); + } + + let inner = Inner { window, view_controller, view, gl_or_metal_backed }; + Ok(Window { inner: MainThreadBound::new(inner, mtm) }) + } + + pub(crate) fn maybe_queue_on_main(&self, f: impl FnOnce(&Inner) + Send + 'static) { + // For now, don't actually do queuing, since it may be less predictable + self.maybe_wait_on_main(f) + } + + pub(crate) fn maybe_wait_on_main<R: Send>(&self, f: impl FnOnce(&Inner) -> R + Send) -> R { + self.inner.get_on_main(|inner| f(inner)) + } + + #[cfg(feature = "rwh_06")] + #[inline] + pub(crate) fn raw_window_handle_rwh_06( + &self, + ) -> Result<rwh_06::RawWindowHandle, rwh_06::HandleError> { + if let Some(mtm) = MainThreadMarker::new() { + Ok(self.inner.get(mtm).raw_window_handle_rwh_06()) + } else { + Err(rwh_06::HandleError::Unavailable) + } + } + + #[cfg(feature = "rwh_06")] + #[inline] + pub(crate) fn raw_display_handle_rwh_06( + &self, + ) -> Result<rwh_06::RawDisplayHandle, rwh_06::HandleError> { + Ok(rwh_06::RawDisplayHandle::UiKit(rwh_06::UiKitDisplayHandle::new())) + } +} + +// WindowExtIOS +impl Inner { + pub fn set_scale_factor(&self, scale_factor: f64) { + assert!( + dpi::validate_scale_factor(scale_factor), + "`WindowExtIOS::set_scale_factor` received an invalid hidpi factor" + ); + let scale_factor = scale_factor as CGFloat; + self.view.setContentScaleFactor(scale_factor); + } + + pub fn set_valid_orientations(&self, valid_orientations: ValidOrientations) { + self.view_controller.set_supported_interface_orientations( + MainThreadMarker::new().unwrap(), + valid_orientations, + ); + } + + pub fn set_prefers_home_indicator_hidden(&self, hidden: bool) { + self.view_controller.set_prefers_home_indicator_auto_hidden(hidden); + } + + pub fn set_preferred_screen_edges_deferring_system_gestures(&self, edges: ScreenEdge) { + self.view_controller.set_preferred_screen_edges_deferring_system_gestures(edges); + } + + pub fn set_prefers_status_bar_hidden(&self, hidden: bool) { + self.view_controller.set_prefers_status_bar_hidden(hidden); + } + + pub fn set_preferred_status_bar_style(&self, status_bar_style: StatusBarStyle) { + self.view_controller.set_preferred_status_bar_style(status_bar_style); + } + + pub fn recognize_pinch_gesture(&self, should_recognize: bool) { + self.view.recognize_pinch_gesture(should_recognize); + } + + pub fn recognize_pan_gesture( + &self, + should_recognize: bool, + minimum_number_of_touches: u8, + maximum_number_of_touches: u8, + ) { + self.view.recognize_pan_gesture( + should_recognize, + minimum_number_of_touches, + maximum_number_of_touches, + ); + } + + pub fn recognize_doubletap_gesture(&self, should_recognize: bool) { + self.view.recognize_doubletap_gesture(should_recognize); + } + + pub fn recognize_rotation_gesture(&self, should_recognize: bool) { + self.view.recognize_rotation_gesture(should_recognize); + } +} + +impl Inner { + fn screen_frame(&self) -> CGRect { + self.rect_to_screen_space(self.window.bounds()) + } + + fn rect_to_screen_space(&self, rect: CGRect) -> CGRect { + let screen_space = self.window.screen().coordinateSpace(); + self.window.convertRect_toCoordinateSpace(rect, &screen_space) + } + + fn rect_from_screen_space(&self, rect: CGRect) -> CGRect { + let screen_space = self.window.screen().coordinateSpace(); + self.window.convertRect_fromCoordinateSpace(rect, &screen_space) + } + + fn safe_area_screen_space(&self) -> CGRect { + let bounds = self.window.bounds(); + if app_state::os_capabilities().safe_area { + let safe_area = self.window.safeAreaInsets(); + let safe_bounds = CGRect { + origin: CGPoint { + x: bounds.origin.x + safe_area.left, + y: bounds.origin.y + safe_area.top, + }, + size: CGSize { + width: bounds.size.width - safe_area.left - safe_area.right, + height: bounds.size.height - safe_area.top - safe_area.bottom, + }, + }; + self.rect_to_screen_space(safe_bounds) + } else { + let screen_frame = self.rect_to_screen_space(bounds); + let status_bar_frame = { + let app = UIApplication::sharedApplication(MainThreadMarker::new().unwrap()); + #[allow(deprecated)] + app.statusBarFrame() + }; + let (y, height) = if screen_frame.origin.y > status_bar_frame.size.height { + (screen_frame.origin.y, screen_frame.size.height) + } else { + let y = status_bar_frame.size.height; + let height = screen_frame.size.height + - (status_bar_frame.size.height - screen_frame.origin.y); + (y, height) + }; + CGRect { + origin: CGPoint { x: screen_frame.origin.x, y }, + size: CGSize { width: screen_frame.size.width, height }, + } + } + } +} + +#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub struct WindowId { + window: *mut WinitUIWindow, +} + +impl WindowId { + pub const fn dummy() -> Self { + WindowId { window: std::ptr::null_mut() } + } +} + +impl From<WindowId> for u64 { + fn from(window_id: WindowId) -> Self { + window_id.window as u64 + } +} + +impl From<u64> for WindowId { + fn from(raw_id: u64) -> Self { + Self { window: raw_id as _ } + } +} + +unsafe impl Send for WindowId {} +unsafe impl Sync for WindowId {} + +impl From<&AnyObject> for WindowId { + fn from(window: &AnyObject) -> WindowId { + WindowId { window: window as *const _ as _ } + } +} + +#[derive(Clone, Debug, Default)] +pub struct PlatformSpecificWindowAttributes { + pub scale_factor: Option<f64>, + pub valid_orientations: ValidOrientations, + pub prefers_home_indicator_hidden: bool, + pub prefers_status_bar_hidden: bool, + pub preferred_status_bar_style: StatusBarStyle, + pub preferred_screen_edges_deferring_system_gestures: ScreenEdge, +} diff --git a/app/vendor/rune/vendor/winit/src/platform_impl/linux/common/mod.rs b/app/vendor/rune/vendor/winit/src/platform_impl/linux/common/mod.rs new file mode 100644 index 0000000..ed7f82c --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/platform_impl/linux/common/mod.rs @@ -0,0 +1 @@ +pub mod xkb; diff --git a/app/vendor/rune/vendor/winit/src/platform_impl/linux/common/xkb/compose.rs b/app/vendor/rune/vendor/winit/src/platform_impl/linux/common/xkb/compose.rs new file mode 100644 index 0000000..9d4f590 --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/platform_impl/linux/common/xkb/compose.rs @@ -0,0 +1,123 @@ +//! XKB compose handling. + +use std::env; +use std::ffi::CString; +use std::ops::Deref; +use std::os::unix::ffi::OsStringExt; +use std::ptr::NonNull; + +use super::{XkbContext, XKBCH}; +use smol_str::SmolStr; +use xkbcommon_dl::{ + xkb_compose_compile_flags, xkb_compose_feed_result, xkb_compose_state, xkb_compose_state_flags, + xkb_compose_status, xkb_compose_table, xkb_keysym_t, +}; + +#[derive(Debug)] +pub struct XkbComposeTable { + table: NonNull<xkb_compose_table>, +} + +impl XkbComposeTable { + pub fn new(context: &XkbContext) -> Option<Self> { + let locale = env::var_os("LC_ALL") + .and_then(|v| if v.is_empty() { None } else { Some(v) }) + .or_else(|| env::var_os("LC_CTYPE")) + .and_then(|v| if v.is_empty() { None } else { Some(v) }) + .or_else(|| env::var_os("LANG")) + .and_then(|v| if v.is_empty() { None } else { Some(v) }) + .unwrap_or_else(|| "C".into()); + let locale = CString::new(locale.into_vec()).unwrap(); + + let table = unsafe { + (XKBCH.xkb_compose_table_new_from_locale)( + context.as_ptr(), + locale.as_ptr(), + xkb_compose_compile_flags::XKB_COMPOSE_COMPILE_NO_FLAGS, + ) + }; + + let table = NonNull::new(table)?; + Some(Self { table }) + } + + /// Create new state with the given compose table. + pub fn new_state(&self) -> Option<XkbComposeState> { + let state = unsafe { + (XKBCH.xkb_compose_state_new)( + self.table.as_ptr(), + xkb_compose_state_flags::XKB_COMPOSE_STATE_NO_FLAGS, + ) + }; + + let state = NonNull::new(state)?; + Some(XkbComposeState { state }) + } +} + +impl Deref for XkbComposeTable { + type Target = NonNull<xkb_compose_table>; + + fn deref(&self) -> &Self::Target { + &self.table + } +} + +impl Drop for XkbComposeTable { + fn drop(&mut self) { + unsafe { + (XKBCH.xkb_compose_table_unref)(self.table.as_ptr()); + } + } +} + +#[derive(Debug)] +pub struct XkbComposeState { + state: NonNull<xkb_compose_state>, +} + +impl XkbComposeState { + pub fn get_string(&mut self, scratch_buffer: &mut Vec<u8>) -> Option<SmolStr> { + super::make_string_with(scratch_buffer, |ptr, len| unsafe { + (XKBCH.xkb_compose_state_get_utf8)(self.state.as_ptr(), ptr, len) + }) + } + + #[inline] + pub fn feed(&mut self, keysym: xkb_keysym_t) -> ComposeStatus { + let feed_result = unsafe { (XKBCH.xkb_compose_state_feed)(self.state.as_ptr(), keysym) }; + match feed_result { + xkb_compose_feed_result::XKB_COMPOSE_FEED_IGNORED => ComposeStatus::Ignored, + xkb_compose_feed_result::XKB_COMPOSE_FEED_ACCEPTED => { + ComposeStatus::Accepted(self.status()) + }, + } + } + + #[inline] + pub fn reset(&mut self) { + unsafe { + (XKBCH.xkb_compose_state_reset)(self.state.as_ptr()); + } + } + + #[inline] + pub fn status(&mut self) -> xkb_compose_status { + unsafe { (XKBCH.xkb_compose_state_get_status)(self.state.as_ptr()) } + } +} + +impl Drop for XkbComposeState { + fn drop(&mut self) { + unsafe { + (XKBCH.xkb_compose_state_unref)(self.state.as_ptr()); + }; + } +} + +#[derive(Copy, Clone, Debug)] +pub enum ComposeStatus { + Accepted(xkb_compose_status), + Ignored, + None, +} diff --git a/app/vendor/rune/vendor/winit/src/platform_impl/linux/common/xkb/keymap.rs b/app/vendor/rune/vendor/winit/src/platform_impl/linux/common/xkb/keymap.rs new file mode 100644 index 0000000..67aac5c --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/platform_impl/linux/common/xkb/keymap.rs @@ -0,0 +1,1044 @@ +//! XKB keymap. + +use std::ffi::c_char; +use std::ops::Deref; +use std::ptr::{self, NonNull}; + +#[cfg(x11_platform)] +use x11_dl::xlib_xcb::xcb_connection_t; +#[cfg(wayland_platform)] +use {memmap2::MmapOptions, std::os::unix::io::OwnedFd}; + +use xkb::XKB_MOD_INVALID; +use xkbcommon_dl::{ + self as xkb, xkb_keycode_t, xkb_keymap, xkb_keymap_compile_flags, xkb_keysym_t, + xkb_layout_index_t, xkb_mod_index_t, +}; + +use crate::keyboard::{Key, KeyCode, KeyLocation, NamedKey, NativeKey, NativeKeyCode, PhysicalKey}; +#[cfg(x11_platform)] +use crate::platform_impl::common::xkb::XKBXH; +use crate::platform_impl::common::xkb::{XkbContext, XKBH}; + +/// Map the raw X11-style keycode to the `KeyCode` enum. +/// +/// X11-style keycodes are offset by 8 from the keycodes the Linux kernel uses. +pub fn raw_keycode_to_physicalkey(keycode: u32) -> PhysicalKey { + scancode_to_physicalkey(keycode.saturating_sub(8)) +} + +/// Map the linux scancode to Keycode. +/// +/// Both X11 and Wayland use keys with `+ 8` offset to linux scancode. +pub fn scancode_to_physicalkey(scancode: u32) -> PhysicalKey { + // The keycode values are taken from linux/include/uapi/linux/input-event-codes.h, as + // libxkbcommon's documentation seems to suggest that the keycode values we're interested in + // are defined by the Linux kernel. If Winit programs end up being run on other Unix-likes, + // I can only hope they agree on what the keycodes mean. + // + // Some of the keycodes are likely superfluous for our purposes, and some are ones which are + // difficult to test the correctness of, or discover the purpose of. Because of this, they've + // either been commented out here, or not included at all. + PhysicalKey::Code(match scancode { + 0 => return PhysicalKey::Unidentified(NativeKeyCode::Xkb(0)), + 1 => KeyCode::Escape, + 2 => KeyCode::Digit1, + 3 => KeyCode::Digit2, + 4 => KeyCode::Digit3, + 5 => KeyCode::Digit4, + 6 => KeyCode::Digit5, + 7 => KeyCode::Digit6, + 8 => KeyCode::Digit7, + 9 => KeyCode::Digit8, + 10 => KeyCode::Digit9, + 11 => KeyCode::Digit0, + 12 => KeyCode::Minus, + 13 => KeyCode::Equal, + 14 => KeyCode::Backspace, + 15 => KeyCode::Tab, + 16 => KeyCode::KeyQ, + 17 => KeyCode::KeyW, + 18 => KeyCode::KeyE, + 19 => KeyCode::KeyR, + 20 => KeyCode::KeyT, + 21 => KeyCode::KeyY, + 22 => KeyCode::KeyU, + 23 => KeyCode::KeyI, + 24 => KeyCode::KeyO, + 25 => KeyCode::KeyP, + 26 => KeyCode::BracketLeft, + 27 => KeyCode::BracketRight, + 28 => KeyCode::Enter, + 29 => KeyCode::ControlLeft, + 30 => KeyCode::KeyA, + 31 => KeyCode::KeyS, + 32 => KeyCode::KeyD, + 33 => KeyCode::KeyF, + 34 => KeyCode::KeyG, + 35 => KeyCode::KeyH, + 36 => KeyCode::KeyJ, + 37 => KeyCode::KeyK, + 38 => KeyCode::KeyL, + 39 => KeyCode::Semicolon, + 40 => KeyCode::Quote, + 41 => KeyCode::Backquote, + 42 => KeyCode::ShiftLeft, + 43 => KeyCode::Backslash, + 44 => KeyCode::KeyZ, + 45 => KeyCode::KeyX, + 46 => KeyCode::KeyC, + 47 => KeyCode::KeyV, + 48 => KeyCode::KeyB, + 49 => KeyCode::KeyN, + 50 => KeyCode::KeyM, + 51 => KeyCode::Comma, + 52 => KeyCode::Period, + 53 => KeyCode::Slash, + 54 => KeyCode::ShiftRight, + 55 => KeyCode::NumpadMultiply, + 56 => KeyCode::AltLeft, + 57 => KeyCode::Space, + 58 => KeyCode::CapsLock, + 59 => KeyCode::F1, + 60 => KeyCode::F2, + 61 => KeyCode::F3, + 62 => KeyCode::F4, + 63 => KeyCode::F5, + 64 => KeyCode::F6, + 65 => KeyCode::F7, + 66 => KeyCode::F8, + 67 => KeyCode::F9, + 68 => KeyCode::F10, + 69 => KeyCode::NumLock, + 70 => KeyCode::ScrollLock, + 71 => KeyCode::Numpad7, + 72 => KeyCode::Numpad8, + 73 => KeyCode::Numpad9, + 74 => KeyCode::NumpadSubtract, + 75 => KeyCode::Numpad4, + 76 => KeyCode::Numpad5, + 77 => KeyCode::Numpad6, + 78 => KeyCode::NumpadAdd, + 79 => KeyCode::Numpad1, + 80 => KeyCode::Numpad2, + 81 => KeyCode::Numpad3, + 82 => KeyCode::Numpad0, + 83 => KeyCode::NumpadDecimal, + 85 => KeyCode::Lang5, + 86 => KeyCode::IntlBackslash, + 87 => KeyCode::F11, + 88 => KeyCode::F12, + 89 => KeyCode::IntlRo, + 90 => KeyCode::Lang3, + 91 => KeyCode::Lang4, + 92 => KeyCode::Convert, + 93 => KeyCode::KanaMode, + 94 => KeyCode::NonConvert, + // 95 => KeyCode::KPJPCOMMA, + 96 => KeyCode::NumpadEnter, + 97 => KeyCode::ControlRight, + 98 => KeyCode::NumpadDivide, + 99 => KeyCode::PrintScreen, + 100 => KeyCode::AltRight, + // 101 => KeyCode::LINEFEED, + 102 => KeyCode::Home, + 103 => KeyCode::ArrowUp, + 104 => KeyCode::PageUp, + 105 => KeyCode::ArrowLeft, + 106 => KeyCode::ArrowRight, + 107 => KeyCode::End, + 108 => KeyCode::ArrowDown, + 109 => KeyCode::PageDown, + 110 => KeyCode::Insert, + 111 => KeyCode::Delete, + // 112 => KeyCode::MACRO, + 113 => KeyCode::AudioVolumeMute, + 114 => KeyCode::AudioVolumeDown, + 115 => KeyCode::AudioVolumeUp, + // 116 => KeyCode::POWER, + 117 => KeyCode::NumpadEqual, + // 118 => KeyCode::KPPLUSMINUS, + 119 => KeyCode::Pause, + // 120 => KeyCode::SCALE, + 121 => KeyCode::NumpadComma, + 122 => KeyCode::Lang1, + 123 => KeyCode::Lang2, + 124 => KeyCode::IntlYen, + 125 => KeyCode::SuperLeft, + 126 => KeyCode::SuperRight, + 127 => KeyCode::ContextMenu, + // 128 => KeyCode::STOP, + // 129 => KeyCode::AGAIN, + // 130 => KeyCode::PROPS, + // 131 => KeyCode::UNDO, + // 132 => KeyCode::FRONT, + // 133 => KeyCode::COPY, + // 134 => KeyCode::OPEN, + // 135 => KeyCode::PASTE, + // 136 => KeyCode::FIND, + // 137 => KeyCode::CUT, + // 138 => KeyCode::HELP, + // 139 => KeyCode::MENU, + // 140 => KeyCode::CALC, + // 141 => KeyCode::SETUP, + // 142 => KeyCode::SLEEP, + // 143 => KeyCode::WAKEUP, + // 144 => KeyCode::FILE, + // 145 => KeyCode::SENDFILE, + // 146 => KeyCode::DELETEFILE, + // 147 => KeyCode::XFER, + // 148 => KeyCode::PROG1, + // 149 => KeyCode::PROG2, + // 150 => KeyCode::WWW, + // 151 => KeyCode::MSDOS, + // 152 => KeyCode::COFFEE, + // 153 => KeyCode::ROTATE_DISPLAY, + // 154 => KeyCode::CYCLEWINDOWS, + // 155 => KeyCode::MAIL, + // 156 => KeyCode::BOOKMARKS, + // 157 => KeyCode::COMPUTER, + // 158 => KeyCode::BACK, + // 159 => KeyCode::FORWARD, + // 160 => KeyCode::CLOSECD, + // 161 => KeyCode::EJECTCD, + // 162 => KeyCode::EJECTCLOSECD, + 163 => KeyCode::MediaTrackNext, + 164 => KeyCode::MediaPlayPause, + 165 => KeyCode::MediaTrackPrevious, + 166 => KeyCode::MediaStop, + // 167 => KeyCode::RECORD, + // 168 => KeyCode::REWIND, + // 169 => KeyCode::PHONE, + // 170 => KeyCode::ISO, + // 171 => KeyCode::CONFIG, + // 172 => KeyCode::HOMEPAGE, + // 173 => KeyCode::REFRESH, + // 174 => KeyCode::EXIT, + // 175 => KeyCode::MOVE, + // 176 => KeyCode::EDIT, + // 177 => KeyCode::SCROLLUP, + // 178 => KeyCode::SCROLLDOWN, + // 179 => KeyCode::KPLEFTPAREN, + // 180 => KeyCode::KPRIGHTPAREN, + // 181 => KeyCode::NEW, + // 182 => KeyCode::REDO, + 183 => KeyCode::F13, + 184 => KeyCode::F14, + 185 => KeyCode::F15, + 186 => KeyCode::F16, + 187 => KeyCode::F17, + 188 => KeyCode::F18, + 189 => KeyCode::F19, + 190 => KeyCode::F20, + 191 => KeyCode::F21, + 192 => KeyCode::F22, + 193 => KeyCode::F23, + 194 => KeyCode::F24, + // 200 => KeyCode::PLAYCD, + // 201 => KeyCode::PAUSECD, + // 202 => KeyCode::PROG3, + // 203 => KeyCode::PROG4, + // 204 => KeyCode::DASHBOARD, + // 205 => KeyCode::SUSPEND, + // 206 => KeyCode::CLOSE, + // 207 => KeyCode::PLAY, + // 208 => KeyCode::FASTFORWARD, + // 209 => KeyCode::BASSBOOST, + // 210 => KeyCode::PRINT, + // 211 => KeyCode::HP, + // 212 => KeyCode::CAMERA, + // 213 => KeyCode::SOUND, + // 214 => KeyCode::QUESTION, + // 215 => KeyCode::EMAIL, + // 216 => KeyCode::CHAT, + // 217 => KeyCode::SEARCH, + // 218 => KeyCode::CONNECT, + // 219 => KeyCode::FINANCE, + // 220 => KeyCode::SPORT, + // 221 => KeyCode::SHOP, + // 222 => KeyCode::ALTERASE, + // 223 => KeyCode::CANCEL, + // 224 => KeyCode::BRIGHTNESSDOW, + // 225 => KeyCode::BRIGHTNESSU, + // 226 => KeyCode::MEDIA, + // 227 => KeyCode::SWITCHVIDEOMODE, + // 228 => KeyCode::KBDILLUMTOGGLE, + // 229 => KeyCode::KBDILLUMDOWN, + // 230 => KeyCode::KBDILLUMUP, + // 231 => KeyCode::SEND, + // 232 => KeyCode::REPLY, + // 233 => KeyCode::FORWARDMAIL, + // 234 => KeyCode::SAVE, + // 235 => KeyCode::DOCUMENTS, + // 236 => KeyCode::BATTERY, + // 237 => KeyCode::BLUETOOTH, + // 238 => KeyCode::WLAN, + // 239 => KeyCode::UWB, + 240 => return PhysicalKey::Unidentified(NativeKeyCode::Unidentified), + // 241 => KeyCode::VIDEO_NEXT, + // 242 => KeyCode::VIDEO_PREV, + // 243 => KeyCode::BRIGHTNESS_CYCLE, + // 244 => KeyCode::BRIGHTNESS_AUTO, + // 245 => KeyCode::DISPLAY_OFF, + // 246 => KeyCode::WWAN, + // 247 => KeyCode::RFKILL, + // 248 => KeyCode::KEY_MICMUTE, + _ => return PhysicalKey::Unidentified(NativeKeyCode::Xkb(scancode)), + }) +} + +pub fn physicalkey_to_scancode(key: PhysicalKey) -> Option<u32> { + let code = match key { + PhysicalKey::Code(code) => code, + PhysicalKey::Unidentified(code) => { + return match code { + NativeKeyCode::Unidentified => Some(240), + NativeKeyCode::Xkb(raw) => Some(raw), + _ => None, + }; + }, + }; + + match code { + KeyCode::Escape => Some(1), + KeyCode::Digit1 => Some(2), + KeyCode::Digit2 => Some(3), + KeyCode::Digit3 => Some(4), + KeyCode::Digit4 => Some(5), + KeyCode::Digit5 => Some(6), + KeyCode::Digit6 => Some(7), + KeyCode::Digit7 => Some(8), + KeyCode::Digit8 => Some(9), + KeyCode::Digit9 => Some(10), + KeyCode::Digit0 => Some(11), + KeyCode::Minus => Some(12), + KeyCode::Equal => Some(13), + KeyCode::Backspace => Some(14), + KeyCode::Tab => Some(15), + KeyCode::KeyQ => Some(16), + KeyCode::KeyW => Some(17), + KeyCode::KeyE => Some(18), + KeyCode::KeyR => Some(19), + KeyCode::KeyT => Some(20), + KeyCode::KeyY => Some(21), + KeyCode::KeyU => Some(22), + KeyCode::KeyI => Some(23), + KeyCode::KeyO => Some(24), + KeyCode::KeyP => Some(25), + KeyCode::BracketLeft => Some(26), + KeyCode::BracketRight => Some(27), + KeyCode::Enter => Some(28), + KeyCode::ControlLeft => Some(29), + KeyCode::KeyA => Some(30), + KeyCode::KeyS => Some(31), + KeyCode::KeyD => Some(32), + KeyCode::KeyF => Some(33), + KeyCode::KeyG => Some(34), + KeyCode::KeyH => Some(35), + KeyCode::KeyJ => Some(36), + KeyCode::KeyK => Some(37), + KeyCode::KeyL => Some(38), + KeyCode::Semicolon => Some(39), + KeyCode::Quote => Some(40), + KeyCode::Backquote => Some(41), + KeyCode::ShiftLeft => Some(42), + KeyCode::Backslash => Some(43), + KeyCode::KeyZ => Some(44), + KeyCode::KeyX => Some(45), + KeyCode::KeyC => Some(46), + KeyCode::KeyV => Some(47), + KeyCode::KeyB => Some(48), + KeyCode::KeyN => Some(49), + KeyCode::KeyM => Some(50), + KeyCode::Comma => Some(51), + KeyCode::Period => Some(52), + KeyCode::Slash => Some(53), + KeyCode::ShiftRight => Some(54), + KeyCode::NumpadMultiply => Some(55), + KeyCode::AltLeft => Some(56), + KeyCode::Space => Some(57), + KeyCode::CapsLock => Some(58), + KeyCode::F1 => Some(59), + KeyCode::F2 => Some(60), + KeyCode::F3 => Some(61), + KeyCode::F4 => Some(62), + KeyCode::F5 => Some(63), + KeyCode::F6 => Some(64), + KeyCode::F7 => Some(65), + KeyCode::F8 => Some(66), + KeyCode::F9 => Some(67), + KeyCode::F10 => Some(68), + KeyCode::NumLock => Some(69), + KeyCode::ScrollLock => Some(70), + KeyCode::Numpad7 => Some(71), + KeyCode::Numpad8 => Some(72), + KeyCode::Numpad9 => Some(73), + KeyCode::NumpadSubtract => Some(74), + KeyCode::Numpad4 => Some(75), + KeyCode::Numpad5 => Some(76), + KeyCode::Numpad6 => Some(77), + KeyCode::NumpadAdd => Some(78), + KeyCode::Numpad1 => Some(79), + KeyCode::Numpad2 => Some(80), + KeyCode::Numpad3 => Some(81), + KeyCode::Numpad0 => Some(82), + KeyCode::NumpadDecimal => Some(83), + KeyCode::Lang5 => Some(85), + KeyCode::IntlBackslash => Some(86), + KeyCode::F11 => Some(87), + KeyCode::F12 => Some(88), + KeyCode::IntlRo => Some(89), + KeyCode::Lang3 => Some(90), + KeyCode::Lang4 => Some(91), + KeyCode::Convert => Some(92), + KeyCode::KanaMode => Some(93), + KeyCode::NonConvert => Some(94), + KeyCode::NumpadEnter => Some(96), + KeyCode::ControlRight => Some(97), + KeyCode::NumpadDivide => Some(98), + KeyCode::PrintScreen => Some(99), + KeyCode::AltRight => Some(100), + KeyCode::Home => Some(102), + KeyCode::ArrowUp => Some(103), + KeyCode::PageUp => Some(104), + KeyCode::ArrowLeft => Some(105), + KeyCode::ArrowRight => Some(106), + KeyCode::End => Some(107), + KeyCode::ArrowDown => Some(108), + KeyCode::PageDown => Some(109), + KeyCode::Insert => Some(110), + KeyCode::Delete => Some(111), + KeyCode::AudioVolumeMute => Some(113), + KeyCode::AudioVolumeDown => Some(114), + KeyCode::AudioVolumeUp => Some(115), + KeyCode::NumpadEqual => Some(117), + KeyCode::Pause => Some(119), + KeyCode::NumpadComma => Some(121), + KeyCode::Lang1 => Some(122), + KeyCode::Lang2 => Some(123), + KeyCode::IntlYen => Some(124), + KeyCode::SuperLeft => Some(125), + KeyCode::SuperRight => Some(126), + KeyCode::ContextMenu => Some(127), + KeyCode::MediaTrackNext => Some(163), + KeyCode::MediaPlayPause => Some(164), + KeyCode::MediaTrackPrevious => Some(165), + KeyCode::MediaStop => Some(166), + KeyCode::F13 => Some(183), + KeyCode::F14 => Some(184), + KeyCode::F15 => Some(185), + KeyCode::F16 => Some(186), + KeyCode::F17 => Some(187), + KeyCode::F18 => Some(188), + KeyCode::F19 => Some(189), + KeyCode::F20 => Some(190), + KeyCode::F21 => Some(191), + KeyCode::F22 => Some(192), + KeyCode::F23 => Some(193), + KeyCode::F24 => Some(194), + _ => None, + } +} + +pub fn keysym_to_key(keysym: u32) -> Key { + use xkbcommon_dl::keysyms; + Key::Named(match keysym { + // TTY function keys + keysyms::BackSpace => NamedKey::Backspace, + keysyms::Tab => NamedKey::Tab, + // keysyms::Linefeed => NamedKey::Linefeed, + keysyms::Clear => NamedKey::Clear, + keysyms::Return => NamedKey::Enter, + keysyms::Pause => NamedKey::Pause, + keysyms::Scroll_Lock => NamedKey::ScrollLock, + keysyms::Sys_Req => NamedKey::PrintScreen, + keysyms::Escape => NamedKey::Escape, + keysyms::Delete => NamedKey::Delete, + + // IME keys + keysyms::Multi_key => NamedKey::Compose, + keysyms::Codeinput => NamedKey::CodeInput, + keysyms::SingleCandidate => NamedKey::SingleCandidate, + keysyms::MultipleCandidate => NamedKey::AllCandidates, + keysyms::PreviousCandidate => NamedKey::PreviousCandidate, + + // Japanese keys + keysyms::Kanji => NamedKey::KanjiMode, + keysyms::Muhenkan => NamedKey::NonConvert, + keysyms::Henkan_Mode => NamedKey::Convert, + keysyms::Romaji => NamedKey::Romaji, + keysyms::Hiragana => NamedKey::Hiragana, + keysyms::Hiragana_Katakana => NamedKey::HiraganaKatakana, + keysyms::Zenkaku => NamedKey::Zenkaku, + keysyms::Hankaku => NamedKey::Hankaku, + keysyms::Zenkaku_Hankaku => NamedKey::ZenkakuHankaku, + // keysyms::Touroku => NamedKey::Touroku, + // keysyms::Massyo => NamedKey::Massyo, + keysyms::Kana_Lock => NamedKey::KanaMode, + keysyms::Kana_Shift => NamedKey::KanaMode, + keysyms::Eisu_Shift => NamedKey::Alphanumeric, + keysyms::Eisu_toggle => NamedKey::Alphanumeric, + // NOTE: The next three items are aliases for values we've already mapped. + // keysyms::Kanji_Bangou => NamedKey::CodeInput, + // keysyms::Zen_Koho => NamedKey::AllCandidates, + // keysyms::Mae_Koho => NamedKey::PreviousCandidate, + + // Cursor control & motion + keysyms::Home => NamedKey::Home, + keysyms::Left => NamedKey::ArrowLeft, + keysyms::Up => NamedKey::ArrowUp, + keysyms::Right => NamedKey::ArrowRight, + keysyms::Down => NamedKey::ArrowDown, + // keysyms::Prior => NamedKey::PageUp, + keysyms::Page_Up => NamedKey::PageUp, + // keysyms::Next => NamedKey::PageDown, + keysyms::Page_Down => NamedKey::PageDown, + keysyms::End => NamedKey::End, + // keysyms::Begin => NamedKey::Begin, + + // Misc. functions + keysyms::Select => NamedKey::Select, + keysyms::Print => NamedKey::PrintScreen, + keysyms::Execute => NamedKey::Execute, + keysyms::Insert => NamedKey::Insert, + keysyms::Undo => NamedKey::Undo, + keysyms::Redo => NamedKey::Redo, + keysyms::Menu => NamedKey::ContextMenu, + keysyms::Find => NamedKey::Find, + keysyms::Cancel => NamedKey::Cancel, + keysyms::Help => NamedKey::Help, + keysyms::Break => NamedKey::Pause, + keysyms::Mode_switch => NamedKey::ModeChange, + // keysyms::script_switch => NamedKey::ModeChange, + keysyms::Num_Lock => NamedKey::NumLock, + + // Keypad keys + // keysyms::KP_Space => return Key::Character(" "), + keysyms::KP_Tab => NamedKey::Tab, + keysyms::KP_Enter => NamedKey::Enter, + keysyms::KP_F1 => NamedKey::F1, + keysyms::KP_F2 => NamedKey::F2, + keysyms::KP_F3 => NamedKey::F3, + keysyms::KP_F4 => NamedKey::F4, + keysyms::KP_Home => NamedKey::Home, + keysyms::KP_Left => NamedKey::ArrowLeft, + keysyms::KP_Up => NamedKey::ArrowUp, + keysyms::KP_Right => NamedKey::ArrowRight, + keysyms::KP_Down => NamedKey::ArrowDown, + // keysyms::KP_Prior => NamedKey::PageUp, + keysyms::KP_Page_Up => NamedKey::PageUp, + // keysyms::KP_Next => NamedKey::PageDown, + keysyms::KP_Page_Down => NamedKey::PageDown, + keysyms::KP_End => NamedKey::End, + // This is the key labeled "5" on the numpad when NumLock is off. + // keysyms::KP_Begin => NamedKey::Begin, + keysyms::KP_Insert => NamedKey::Insert, + keysyms::KP_Delete => NamedKey::Delete, + // keysyms::KP_Equal => NamedKey::Equal, + // keysyms::KP_Multiply => NamedKey::Multiply, + // keysyms::KP_Add => NamedKey::Add, + // keysyms::KP_Separator => NamedKey::Separator, + // keysyms::KP_Subtract => NamedKey::Subtract, + // keysyms::KP_Decimal => NamedKey::Decimal, + // keysyms::KP_Divide => NamedKey::Divide, + + // keysyms::KP_0 => return Key::Character("0"), + // keysyms::KP_1 => return Key::Character("1"), + // keysyms::KP_2 => return Key::Character("2"), + // keysyms::KP_3 => return Key::Character("3"), + // keysyms::KP_4 => return Key::Character("4"), + // keysyms::KP_5 => return Key::Character("5"), + // keysyms::KP_6 => return Key::Character("6"), + // keysyms::KP_7 => return Key::Character("7"), + // keysyms::KP_8 => return Key::Character("8"), + // keysyms::KP_9 => return Key::Character("9"), + + // Function keys + keysyms::F1 => NamedKey::F1, + keysyms::F2 => NamedKey::F2, + keysyms::F3 => NamedKey::F3, + keysyms::F4 => NamedKey::F4, + keysyms::F5 => NamedKey::F5, + keysyms::F6 => NamedKey::F6, + keysyms::F7 => NamedKey::F7, + keysyms::F8 => NamedKey::F8, + keysyms::F9 => NamedKey::F9, + keysyms::F10 => NamedKey::F10, + keysyms::F11 => NamedKey::F11, + keysyms::F12 => NamedKey::F12, + keysyms::F13 => NamedKey::F13, + keysyms::F14 => NamedKey::F14, + keysyms::F15 => NamedKey::F15, + keysyms::F16 => NamedKey::F16, + keysyms::F17 => NamedKey::F17, + keysyms::F18 => NamedKey::F18, + keysyms::F19 => NamedKey::F19, + keysyms::F20 => NamedKey::F20, + keysyms::F21 => NamedKey::F21, + keysyms::F22 => NamedKey::F22, + keysyms::F23 => NamedKey::F23, + keysyms::F24 => NamedKey::F24, + keysyms::F25 => NamedKey::F25, + keysyms::F26 => NamedKey::F26, + keysyms::F27 => NamedKey::F27, + keysyms::F28 => NamedKey::F28, + keysyms::F29 => NamedKey::F29, + keysyms::F30 => NamedKey::F30, + keysyms::F31 => NamedKey::F31, + keysyms::F32 => NamedKey::F32, + keysyms::F33 => NamedKey::F33, + keysyms::F34 => NamedKey::F34, + keysyms::F35 => NamedKey::F35, + + // Modifiers + keysyms::Shift_L => NamedKey::Shift, + keysyms::Shift_R => NamedKey::Shift, + keysyms::Control_L => NamedKey::Control, + keysyms::Control_R => NamedKey::Control, + keysyms::Caps_Lock => NamedKey::CapsLock, + // keysyms::Shift_Lock => NamedKey::ShiftLock, + + // keysyms::Meta_L => NamedKey::Meta, + // keysyms::Meta_R => NamedKey::Meta, + keysyms::Alt_L => NamedKey::Alt, + keysyms::Alt_R => NamedKey::Alt, + keysyms::Super_L => NamedKey::Super, + keysyms::Super_R => NamedKey::Super, + keysyms::Hyper_L => NamedKey::Hyper, + keysyms::Hyper_R => NamedKey::Hyper, + + // XKB function and modifier keys + // keysyms::ISO_Lock => NamedKey::IsoLock, + // keysyms::ISO_Level2_Latch => NamedKey::IsoLevel2Latch, + keysyms::ISO_Level3_Shift => NamedKey::AltGraph, + keysyms::ISO_Level3_Latch => NamedKey::AltGraph, + keysyms::ISO_Level3_Lock => NamedKey::AltGraph, + // keysyms::ISO_Level5_Shift => NamedKey::IsoLevel5Shift, + // keysyms::ISO_Level5_Latch => NamedKey::IsoLevel5Latch, + // keysyms::ISO_Level5_Lock => NamedKey::IsoLevel5Lock, + // keysyms::ISO_Group_Shift => NamedKey::IsoGroupShift, + // keysyms::ISO_Group_Latch => NamedKey::IsoGroupLatch, + // keysyms::ISO_Group_Lock => NamedKey::IsoGroupLock, + keysyms::ISO_Next_Group => NamedKey::GroupNext, + // keysyms::ISO_Next_Group_Lock => NamedKey::GroupNextLock, + keysyms::ISO_Prev_Group => NamedKey::GroupPrevious, + // keysyms::ISO_Prev_Group_Lock => NamedKey::GroupPreviousLock, + keysyms::ISO_First_Group => NamedKey::GroupFirst, + // keysyms::ISO_First_Group_Lock => NamedKey::GroupFirstLock, + keysyms::ISO_Last_Group => NamedKey::GroupLast, + // keysyms::ISO_Last_Group_Lock => NamedKey::GroupLastLock, + keysyms::ISO_Left_Tab => NamedKey::Tab, + // keysyms::ISO_Move_Line_Up => NamedKey::IsoMoveLineUp, + // keysyms::ISO_Move_Line_Down => NamedKey::IsoMoveLineDown, + // keysyms::ISO_Partial_Line_Up => NamedKey::IsoPartialLineUp, + // keysyms::ISO_Partial_Line_Down => NamedKey::IsoPartialLineDown, + // keysyms::ISO_Partial_Space_Left => NamedKey::IsoPartialSpaceLeft, + // keysyms::ISO_Partial_Space_Right => NamedKey::IsoPartialSpaceRight, + // keysyms::ISO_Set_Margin_Left => NamedKey::IsoSetMarginLeft, + // keysyms::ISO_Set_Margin_Right => NamedKey::IsoSetMarginRight, + // keysyms::ISO_Release_Margin_Left => NamedKey::IsoReleaseMarginLeft, + // keysyms::ISO_Release_Margin_Right => NamedKey::IsoReleaseMarginRight, + // keysyms::ISO_Release_Both_Margins => NamedKey::IsoReleaseBothMargins, + // keysyms::ISO_Fast_Cursor_Left => NamedKey::IsoFastCursorLeft, + // keysyms::ISO_Fast_Cursor_Right => NamedKey::IsoFastCursorRight, + // keysyms::ISO_Fast_Cursor_Up => NamedKey::IsoFastCursorUp, + // keysyms::ISO_Fast_Cursor_Down => NamedKey::IsoFastCursorDown, + // keysyms::ISO_Continuous_Underline => NamedKey::IsoContinuousUnderline, + // keysyms::ISO_Discontinuous_Underline => NamedKey::IsoDiscontinuousUnderline, + // keysyms::ISO_Emphasize => NamedKey::IsoEmphasize, + // keysyms::ISO_Center_Object => NamedKey::IsoCenterObject, + keysyms::ISO_Enter => NamedKey::Enter, + + // dead_grave..dead_currency + + // dead_lowline..dead_longsolidusoverlay + + // dead_a..dead_capital_schwa + + // dead_greek + + // First_Virtual_Screen..Terminate_Server + + // AccessX_Enable..AudibleBell_Enable + + // Pointer_Left..Pointer_Drag5 + + // Pointer_EnableKeys..Pointer_DfltBtnPrev + + // ch..C_H + + // 3270 terminal keys + // keysyms::3270_Duplicate => NamedKey::Duplicate, + // keysyms::3270_FieldMark => NamedKey::FieldMark, + // keysyms::3270_Right2 => NamedKey::Right2, + // keysyms::3270_Left2 => NamedKey::Left2, + // keysyms::3270_BackTab => NamedKey::BackTab, + keysyms::_3270_EraseEOF => NamedKey::EraseEof, + // keysyms::3270_EraseInput => NamedKey::EraseInput, + // keysyms::3270_Reset => NamedKey::Reset, + // keysyms::3270_Quit => NamedKey::Quit, + // keysyms::3270_PA1 => NamedKey::Pa1, + // keysyms::3270_PA2 => NamedKey::Pa2, + // keysyms::3270_PA3 => NamedKey::Pa3, + // keysyms::3270_Test => NamedKey::Test, + keysyms::_3270_Attn => NamedKey::Attn, + // keysyms::3270_CursorBlink => NamedKey::CursorBlink, + // keysyms::3270_AltCursor => NamedKey::AltCursor, + // keysyms::3270_KeyClick => NamedKey::KeyClick, + // keysyms::3270_Jump => NamedKey::Jump, + // keysyms::3270_Ident => NamedKey::Ident, + // keysyms::3270_Rule => NamedKey::Rule, + // keysyms::3270_Copy => NamedKey::Copy, + keysyms::_3270_Play => NamedKey::Play, + // keysyms::3270_Setup => NamedKey::Setup, + // keysyms::3270_Record => NamedKey::Record, + // keysyms::3270_ChangeScreen => NamedKey::ChangeScreen, + // keysyms::3270_DeleteWord => NamedKey::DeleteWord, + keysyms::_3270_ExSelect => NamedKey::ExSel, + keysyms::_3270_CursorSelect => NamedKey::CrSel, + keysyms::_3270_PrintScreen => NamedKey::PrintScreen, + keysyms::_3270_Enter => NamedKey::Enter, + + keysyms::space => NamedKey::Space, + // exclam..Sinh_kunddaliya + + // XFree86 + // keysyms::XF86_ModeLock => NamedKey::ModeLock, + + // XFree86 - Backlight controls + keysyms::XF86_MonBrightnessUp => NamedKey::BrightnessUp, + keysyms::XF86_MonBrightnessDown => NamedKey::BrightnessDown, + // keysyms::XF86_KbdLightOnOff => NamedKey::LightOnOff, + // keysyms::XF86_KbdBrightnessUp => NamedKey::KeyboardBrightnessUp, + // keysyms::XF86_KbdBrightnessDown => NamedKey::KeyboardBrightnessDown, + + // XFree86 - "Internet" + keysyms::XF86_Standby => NamedKey::Standby, + keysyms::XF86_AudioLowerVolume => NamedKey::AudioVolumeDown, + keysyms::XF86_AudioRaiseVolume => NamedKey::AudioVolumeUp, + keysyms::XF86_AudioPlay => NamedKey::MediaPlay, + keysyms::XF86_AudioStop => NamedKey::MediaStop, + keysyms::XF86_AudioPrev => NamedKey::MediaTrackPrevious, + keysyms::XF86_AudioNext => NamedKey::MediaTrackNext, + keysyms::XF86_HomePage => NamedKey::BrowserHome, + keysyms::XF86_Mail => NamedKey::LaunchMail, + // keysyms::XF86_Start => NamedKey::Start, + keysyms::XF86_Search => NamedKey::BrowserSearch, + keysyms::XF86_AudioRecord => NamedKey::MediaRecord, + + // XFree86 - PDA + keysyms::XF86_Calculator => NamedKey::LaunchApplication2, + // keysyms::XF86_Memo => NamedKey::Memo, + // keysyms::XF86_ToDoList => NamedKey::ToDoList, + keysyms::XF86_Calendar => NamedKey::LaunchCalendar, + keysyms::XF86_PowerDown => NamedKey::Power, + // keysyms::XF86_ContrastAdjust => NamedKey::AdjustContrast, + // keysyms::XF86_RockerUp => NamedKey::RockerUp, + // keysyms::XF86_RockerDown => NamedKey::RockerDown, + // keysyms::XF86_RockerEnter => NamedKey::RockerEnter, + + // XFree86 - More "Internet" + keysyms::XF86_Back => NamedKey::BrowserBack, + keysyms::XF86_Forward => NamedKey::BrowserForward, + // keysyms::XF86_Stop => NamedKey::Stop, + keysyms::XF86_Refresh => NamedKey::BrowserRefresh, + keysyms::XF86_PowerOff => NamedKey::Power, + keysyms::XF86_WakeUp => NamedKey::WakeUp, + keysyms::XF86_Eject => NamedKey::Eject, + keysyms::XF86_ScreenSaver => NamedKey::LaunchScreenSaver, + keysyms::XF86_WWW => NamedKey::LaunchWebBrowser, + keysyms::XF86_Sleep => NamedKey::Standby, + keysyms::XF86_Favorites => NamedKey::BrowserFavorites, + keysyms::XF86_AudioPause => NamedKey::MediaPause, + // keysyms::XF86_AudioMedia => NamedKey::AudioMedia, + keysyms::XF86_MyComputer => NamedKey::LaunchApplication1, + // keysyms::XF86_VendorHome => NamedKey::VendorHome, + // keysyms::XF86_LightBulb => NamedKey::LightBulb, + // keysyms::XF86_Shop => NamedKey::BrowserShop, + // keysyms::XF86_History => NamedKey::BrowserHistory, + // keysyms::XF86_OpenURL => NamedKey::OpenUrl, + // keysyms::XF86_AddFavorite => NamedKey::AddFavorite, + // keysyms::XF86_HotLinks => NamedKey::HotLinks, + // keysyms::XF86_BrightnessAdjust => NamedKey::BrightnessAdjust, + // keysyms::XF86_Finance => NamedKey::BrowserFinance, + // keysyms::XF86_Community => NamedKey::BrowserCommunity, + keysyms::XF86_AudioRewind => NamedKey::MediaRewind, + // keysyms::XF86_BackForward => Key::???, + // XF86_Launch0..XF86_LaunchF + + // XF86_ApplicationLeft..XF86_CD + keysyms::XF86_Calculater => NamedKey::LaunchApplication2, // Nice typo, libxkbcommon :) + // XF86_Clear + keysyms::XF86_Close => NamedKey::Close, + keysyms::XF86_Copy => NamedKey::Copy, + keysyms::XF86_Cut => NamedKey::Cut, + // XF86_Display..XF86_Documents + keysyms::XF86_Excel => NamedKey::LaunchSpreadsheet, + // XF86_Explorer..XF86iTouch + keysyms::XF86_LogOff => NamedKey::LogOff, + // XF86_Market..XF86_MenuPB + keysyms::XF86_MySites => NamedKey::BrowserFavorites, + keysyms::XF86_New => NamedKey::New, + // XF86_News..XF86_OfficeHome + keysyms::XF86_Open => NamedKey::Open, + // XF86_Option + keysyms::XF86_Paste => NamedKey::Paste, + keysyms::XF86_Phone => NamedKey::LaunchPhone, + // XF86_Q + keysyms::XF86_Reply => NamedKey::MailReply, + keysyms::XF86_Reload => NamedKey::BrowserRefresh, + // XF86_RotateWindows..XF86_RotationKB + keysyms::XF86_Save => NamedKey::Save, + // XF86_ScrollUp..XF86_ScrollClick + keysyms::XF86_Send => NamedKey::MailSend, + keysyms::XF86_Spell => NamedKey::SpellCheck, + keysyms::XF86_SplitScreen => NamedKey::SplitScreenToggle, + // XF86_Support..XF86_User2KB + keysyms::XF86_Video => NamedKey::LaunchMediaPlayer, + // XF86_WheelButton + keysyms::XF86_Word => NamedKey::LaunchWordProcessor, + // XF86_Xfer + keysyms::XF86_ZoomIn => NamedKey::ZoomIn, + keysyms::XF86_ZoomOut => NamedKey::ZoomOut, + + // XF86_Away..XF86_Messenger + keysyms::XF86_WebCam => NamedKey::LaunchWebCam, + keysyms::XF86_MailForward => NamedKey::MailForward, + // XF86_Pictures + keysyms::XF86_Music => NamedKey::LaunchMusicPlayer, + + // XF86_Battery..XF86_UWB + keysyms::XF86_AudioForward => NamedKey::MediaFastForward, + // XF86_AudioRepeat + keysyms::XF86_AudioRandomPlay => NamedKey::RandomToggle, + keysyms::XF86_Subtitle => NamedKey::Subtitle, + keysyms::XF86_AudioCycleTrack => NamedKey::MediaAudioTrack, + // XF86_CycleAngle..XF86_Blue + keysyms::XF86_Suspend => NamedKey::Standby, + keysyms::XF86_Hibernate => NamedKey::Hibernate, + // XF86_TouchpadToggle..XF86_TouchpadOff + keysyms::XF86_AudioMute => NamedKey::AudioVolumeMute, + + // XF86_Switch_VT_1..XF86_Switch_VT_12 + + // XF86_Ungrab..XF86_ClearGrab + keysyms::XF86_Next_VMode => NamedKey::VideoModeNext, + // keysyms::XF86_Prev_VMode => NamedKey::VideoModePrevious, + // XF86_LogWindowTree..XF86_LogGrabInfo + + // SunFA_Grave..SunFA_Cedilla + + // keysyms::SunF36 => NamedKey::F36 | NamedKey::F11, + // keysyms::SunF37 => NamedKey::F37 | NamedKey::F12, + + // keysyms::SunSys_Req => NamedKey::PrintScreen, + // The next couple of xkb (until SunStop) are already handled. + // SunPrint_Screen..SunPageDown + + // SunUndo..SunFront + keysyms::SUN_Copy => NamedKey::Copy, + keysyms::SUN_Open => NamedKey::Open, + keysyms::SUN_Paste => NamedKey::Paste, + keysyms::SUN_Cut => NamedKey::Cut, + + // SunPowerSwitch + keysyms::SUN_AudioLowerVolume => NamedKey::AudioVolumeDown, + keysyms::SUN_AudioMute => NamedKey::AudioVolumeMute, + keysyms::SUN_AudioRaiseVolume => NamedKey::AudioVolumeUp, + // SUN_VideoDegauss + keysyms::SUN_VideoLowerBrightness => NamedKey::BrightnessDown, + keysyms::SUN_VideoRaiseBrightness => NamedKey::BrightnessUp, + // SunPowerSwitchShift + 0 => return Key::Unidentified(NativeKey::Unidentified), + _ => return Key::Unidentified(NativeKey::Xkb(keysym)), + }) +} + +pub fn keysym_location(keysym: u32) -> KeyLocation { + use xkbcommon_dl::keysyms; + match keysym { + keysyms::Shift_L + | keysyms::Control_L + | keysyms::Meta_L + | keysyms::Alt_L + | keysyms::Super_L + | keysyms::Hyper_L => KeyLocation::Left, + keysyms::Shift_R + | keysyms::Control_R + | keysyms::Meta_R + | keysyms::Alt_R + | keysyms::Super_R + | keysyms::Hyper_R => KeyLocation::Right, + keysyms::KP_0 + | keysyms::KP_1 + | keysyms::KP_2 + | keysyms::KP_3 + | keysyms::KP_4 + | keysyms::KP_5 + | keysyms::KP_6 + | keysyms::KP_7 + | keysyms::KP_8 + | keysyms::KP_9 + | keysyms::KP_Space + | keysyms::KP_Tab + | keysyms::KP_Enter + | keysyms::KP_F1 + | keysyms::KP_F2 + | keysyms::KP_F3 + | keysyms::KP_F4 + | keysyms::KP_Home + | keysyms::KP_Left + | keysyms::KP_Up + | keysyms::KP_Right + | keysyms::KP_Down + | keysyms::KP_Page_Up + | keysyms::KP_Page_Down + | keysyms::KP_End + | keysyms::KP_Begin + | keysyms::KP_Insert + | keysyms::KP_Delete + | keysyms::KP_Equal + | keysyms::KP_Multiply + | keysyms::KP_Add + | keysyms::KP_Separator + | keysyms::KP_Subtract + | keysyms::KP_Decimal + | keysyms::KP_Divide => KeyLocation::Numpad, + _ => KeyLocation::Standard, + } +} + +#[derive(Debug)] +pub struct XkbKeymap { + keymap: NonNull<xkb_keymap>, + _mods_indices: ModsIndices, + pub _core_keyboard_id: i32, +} + +impl XkbKeymap { + #[cfg(wayland_platform)] + pub fn from_fd(context: &XkbContext, fd: OwnedFd, size: usize) -> Option<Self> { + let map = unsafe { MmapOptions::new().len(size).map_copy_read_only(&fd).ok()? }; + + let keymap = unsafe { + let keymap = (XKBH.xkb_keymap_new_from_string)( + (*context).as_ptr(), + map.as_ptr() as *const _, + xkb::xkb_keymap_format::XKB_KEYMAP_FORMAT_TEXT_V1, + xkb_keymap_compile_flags::XKB_KEYMAP_COMPILE_NO_FLAGS, + ); + NonNull::new(keymap)? + }; + + Some(Self::new_inner(keymap, 0)) + } + + #[cfg(x11_platform)] + pub fn from_x11_keymap( + context: &XkbContext, + xcb: *mut xcb_connection_t, + core_keyboard_id: i32, + ) -> Option<Self> { + let keymap = unsafe { + (XKBXH.xkb_x11_keymap_new_from_device)( + context.as_ptr(), + xcb, + core_keyboard_id, + xkb_keymap_compile_flags::XKB_KEYMAP_COMPILE_NO_FLAGS, + ) + }; + let keymap = NonNull::new(keymap)?; + Some(Self::new_inner(keymap, core_keyboard_id)) + } + + fn new_inner(keymap: NonNull<xkb_keymap>, _core_keyboard_id: i32) -> Self { + let mods_indices = ModsIndices { + shift: mod_index_for_name(keymap, xkb::XKB_MOD_NAME_SHIFT), + caps: mod_index_for_name(keymap, xkb::XKB_MOD_NAME_CAPS), + ctrl: mod_index_for_name(keymap, xkb::XKB_MOD_NAME_CTRL), + alt: mod_index_for_name(keymap, xkb::XKB_MOD_NAME_ALT), + num: mod_index_for_name(keymap, xkb::XKB_MOD_NAME_NUM), + mod3: mod_index_for_name(keymap, b"Mod3\0"), + logo: mod_index_for_name(keymap, xkb::XKB_MOD_NAME_LOGO), + mod5: mod_index_for_name(keymap, b"Mod5\0"), + }; + + Self { keymap, _mods_indices: mods_indices, _core_keyboard_id } + } + + #[cfg(x11_platform)] + pub fn mods_indices(&self) -> ModsIndices { + self._mods_indices + } + + pub fn first_keysym_by_level( + &mut self, + layout: xkb_layout_index_t, + keycode: xkb_keycode_t, + ) -> xkb_keysym_t { + unsafe { + let mut keysyms = ptr::null(); + let count = (XKBH.xkb_keymap_key_get_syms_by_level)( + self.keymap.as_ptr(), + keycode, + layout, + // NOTE: The level should be zero to ignore modifiers. + 0, + &mut keysyms, + ); + + if count == 1 { + *keysyms + } else { + 0 + } + } + } + + /// Check whether the given key repeats. + pub fn key_repeats(&mut self, keycode: xkb_keycode_t) -> bool { + unsafe { (XKBH.xkb_keymap_key_repeats)(self.keymap.as_ptr(), keycode) == 1 } + } +} + +impl Drop for XkbKeymap { + fn drop(&mut self) { + unsafe { + (XKBH.xkb_keymap_unref)(self.keymap.as_ptr()); + }; + } +} + +impl Deref for XkbKeymap { + type Target = NonNull<xkb_keymap>; + + fn deref(&self) -> &Self::Target { + &self.keymap + } +} + +/// Modifier index in the keymap. +#[cfg_attr(not(x11_platform), allow(dead_code))] +#[derive(Default, Debug, Clone, Copy)] +pub struct ModsIndices { + pub shift: Option<xkb_mod_index_t>, + pub caps: Option<xkb_mod_index_t>, + pub ctrl: Option<xkb_mod_index_t>, + pub alt: Option<xkb_mod_index_t>, + pub num: Option<xkb_mod_index_t>, + pub mod3: Option<xkb_mod_index_t>, + pub logo: Option<xkb_mod_index_t>, + pub mod5: Option<xkb_mod_index_t>, +} + +fn mod_index_for_name(keymap: NonNull<xkb_keymap>, name: &[u8]) -> Option<xkb_mod_index_t> { + unsafe { + let mod_index = + (XKBH.xkb_keymap_mod_get_index)(keymap.as_ptr(), name.as_ptr() as *const c_char); + if mod_index == XKB_MOD_INVALID { + None + } else { + Some(mod_index) + } + } +} diff --git a/app/vendor/rune/vendor/winit/src/platform_impl/linux/common/xkb/mod.rs b/app/vendor/rune/vendor/winit/src/platform_impl/linux/common/xkb/mod.rs new file mode 100644 index 0000000..706397f --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/platform_impl/linux/common/xkb/mod.rs @@ -0,0 +1,416 @@ +use std::ops::Deref; +use std::os::raw::c_char; +use std::ptr::{self, NonNull}; +use std::sync::atomic::{AtomicBool, Ordering}; + +use crate::utils::Lazy; +use smol_str::SmolStr; +#[cfg(wayland_platform)] +use std::os::unix::io::OwnedFd; +use tracing::warn; +use xkbcommon_dl::{ + self as xkb, xkb_compose_status, xkb_context, xkb_context_flags, xkbcommon_compose_handle, + xkbcommon_handle, XkbCommon, XkbCommonCompose, +}; +#[cfg(x11_platform)] +use {x11_dl::xlib_xcb::xcb_connection_t, xkbcommon_dl::x11::xkbcommon_x11_handle}; + +use crate::event::{ElementState, KeyEvent}; +use crate::keyboard::{Key, KeyLocation}; +use crate::platform_impl::KeyEventExtra; + +mod compose; +mod keymap; +mod state; + +use compose::{ComposeStatus, XkbComposeState, XkbComposeTable}; +use keymap::XkbKeymap; + +#[cfg(x11_platform)] +pub use keymap::raw_keycode_to_physicalkey; +pub use keymap::{physicalkey_to_scancode, scancode_to_physicalkey}; +pub use state::XkbState; + +// TODO: Wire this up without using a static `AtomicBool`. +static RESET_DEAD_KEYS: AtomicBool = AtomicBool::new(false); + +static XKBH: Lazy<&'static XkbCommon> = Lazy::new(xkbcommon_handle); +static XKBCH: Lazy<&'static XkbCommonCompose> = Lazy::new(xkbcommon_compose_handle); +#[cfg(feature = "x11")] +static XKBXH: Lazy<&'static xkb::x11::XkbCommonX11> = Lazy::new(xkbcommon_x11_handle); + +#[inline(always)] +pub fn reset_dead_keys() { + RESET_DEAD_KEYS.store(true, Ordering::SeqCst); +} + +#[derive(Debug)] +pub enum Error { + /// libxkbcommon is not available + XKBNotFound, +} + +#[derive(Debug)] +pub struct Context { + // NOTE: field order matters. + #[cfg(x11_platform)] + pub core_keyboard_id: i32, + state: Option<XkbState>, + keymap: Option<XkbKeymap>, + compose_state1: Option<XkbComposeState>, + compose_state2: Option<XkbComposeState>, + _compose_table: Option<XkbComposeTable>, + context: XkbContext, + scratch_buffer: Vec<u8>, +} + +impl Context { + pub fn new() -> Result<Self, Error> { + if xkb::xkbcommon_option().is_none() { + return Err(Error::XKBNotFound); + } + + let context = XkbContext::new()?; + let mut compose_table = XkbComposeTable::new(&context); + let mut compose_state1 = compose_table.as_ref().and_then(|table| table.new_state()); + let mut compose_state2 = compose_table.as_ref().and_then(|table| table.new_state()); + + // Disable compose if anything compose related failed to initialize. + if compose_table.is_none() || compose_state1.is_none() || compose_state2.is_none() { + compose_state2 = None; + compose_state1 = None; + compose_table = None; + } + + Ok(Self { + state: None, + keymap: None, + compose_state1, + compose_state2, + #[cfg(x11_platform)] + core_keyboard_id: 0, + _compose_table: compose_table, + context, + scratch_buffer: Vec::with_capacity(8), + }) + } + + #[cfg(feature = "x11")] + pub fn from_x11_xkb(xcb: *mut xcb_connection_t) -> Result<Self, Error> { + let result = unsafe { + (XKBXH.xkb_x11_setup_xkb_extension)( + xcb, + 1, + 2, + xkbcommon_dl::x11::xkb_x11_setup_xkb_extension_flags::XKB_X11_SETUP_XKB_EXTENSION_NO_FLAGS, + ptr::null_mut(), + ptr::null_mut(), + ptr::null_mut(), + ptr::null_mut(), + ) + }; + + if result != 1 { + return Err(Error::XKBNotFound); + } + + let mut this = Self::new()?; + this.core_keyboard_id = unsafe { (XKBXH.xkb_x11_get_core_keyboard_device_id)(xcb) }; + this.set_keymap_from_x11(xcb); + Ok(this) + } + + pub fn state_mut(&mut self) -> Option<&mut XkbState> { + self.state.as_mut() + } + + pub fn keymap_mut(&mut self) -> Option<&mut XkbKeymap> { + self.keymap.as_mut() + } + + #[cfg(wayland_platform)] + pub fn set_keymap_from_fd(&mut self, fd: OwnedFd, size: usize) { + let keymap = XkbKeymap::from_fd(&self.context, fd, size); + let state = keymap.as_ref().and_then(XkbState::new_wayland); + if keymap.is_none() || state.is_none() { + warn!("failed to update xkb keymap"); + } + self.state = state; + self.keymap = keymap; + } + + #[cfg(x11_platform)] + pub fn set_keymap_from_x11(&mut self, xcb: *mut xcb_connection_t) { + let keymap = XkbKeymap::from_x11_keymap(&self.context, xcb, self.core_keyboard_id); + let state = keymap.as_ref().and_then(|keymap| XkbState::new_x11(xcb, keymap)); + if keymap.is_none() || state.is_none() { + warn!("failed to update xkb keymap"); + } + self.state = state; + self.keymap = keymap; + } + + /// Key builder context with the user provided xkb state. + pub fn key_context(&mut self) -> Option<KeyContext<'_>> { + let state = self.state.as_mut()?; + let keymap = self.keymap.as_mut()?; + let compose_state1 = self.compose_state1.as_mut(); + let compose_state2 = self.compose_state2.as_mut(); + let scratch_buffer = &mut self.scratch_buffer; + Some(KeyContext { state, keymap, compose_state1, compose_state2, scratch_buffer }) + } + + /// Key builder context with the user provided xkb state. + /// + /// Should be used when the original context must not be altered. + #[cfg(x11_platform)] + pub fn key_context_with_state<'a>( + &'a mut self, + state: &'a mut XkbState, + ) -> Option<KeyContext<'a>> { + let keymap = self.keymap.as_mut()?; + let compose_state1 = self.compose_state1.as_mut(); + let compose_state2 = self.compose_state2.as_mut(); + let scratch_buffer = &mut self.scratch_buffer; + Some(KeyContext { state, keymap, compose_state1, compose_state2, scratch_buffer }) + } +} + +pub struct KeyContext<'a> { + pub state: &'a mut XkbState, + pub keymap: &'a mut XkbKeymap, + compose_state1: Option<&'a mut XkbComposeState>, + compose_state2: Option<&'a mut XkbComposeState>, + scratch_buffer: &'a mut Vec<u8>, +} + +impl KeyContext<'_> { + pub fn process_key_event( + &mut self, + keycode: u32, + state: ElementState, + repeat: bool, + ) -> KeyEvent { + let mut event = + KeyEventResults::new(self, keycode, !repeat && state == ElementState::Pressed); + let physical_key = keymap::raw_keycode_to_physicalkey(keycode); + let (logical_key, location) = event.key(); + let text = event.text(); + let (key_without_modifiers, _) = event.key_without_modifiers(); + let text_with_all_modifiers = event.text_with_all_modifiers(); + + let platform_specific = KeyEventExtra { text_with_all_modifiers, key_without_modifiers }; + + KeyEvent { physical_key, logical_key, text, location, state, repeat, platform_specific } + } + + fn keysym_to_utf8_raw(&mut self, keysym: u32) -> Option<SmolStr> { + self.scratch_buffer.clear(); + self.scratch_buffer.reserve(8); + loop { + let bytes_written = unsafe { + (XKBH.xkb_keysym_to_utf8)( + keysym, + self.scratch_buffer.as_mut_ptr().cast(), + self.scratch_buffer.capacity(), + ) + }; + if bytes_written == 0 { + return None; + } else if bytes_written == -1 { + self.scratch_buffer.reserve(8); + } else { + unsafe { self.scratch_buffer.set_len(bytes_written.try_into().unwrap()) }; + break; + } + } + + // Remove the null-terminator + self.scratch_buffer.pop(); + byte_slice_to_smol_str(self.scratch_buffer) + } +} + +struct KeyEventResults<'a, 'b> { + context: &'a mut KeyContext<'b>, + keycode: u32, + keysym: u32, + compose: ComposeStatus, +} + +impl<'a, 'b> KeyEventResults<'a, 'b> { + fn new(context: &'a mut KeyContext<'b>, keycode: u32, compose: bool) -> Self { + let keysym = context.state.get_one_sym_raw(keycode); + + let compose = if let Some(state) = context.compose_state1.as_mut().filter(|_| compose) { + if RESET_DEAD_KEYS.swap(false, Ordering::SeqCst) { + state.reset(); + context.compose_state2.as_mut().unwrap().reset(); + } + state.feed(keysym) + } else { + ComposeStatus::None + }; + + KeyEventResults { context, keycode, keysym, compose } + } + + pub fn key(&mut self) -> (Key, KeyLocation) { + let (key, location) = match self.keysym_to_key(self.keysym) { + Ok(known) => return known, + Err(undefined) => undefined, + }; + + if let ComposeStatus::Accepted(xkb_compose_status::XKB_COMPOSE_COMPOSING) = self.compose { + let compose_state = self.context.compose_state2.as_mut().unwrap(); + // When pressing a dead key twice, the non-combining variant of that character will + // be produced. Since this function only concerns itself with a single keypress, we + // simulate this double press here by feeding the keysym to the compose state + // twice. + + compose_state.feed(self.keysym); + if matches!(compose_state.feed(self.keysym), ComposeStatus::Accepted(_)) { + // Extracting only a single `char` here *should* be fine, assuming that no + // dead key's non-combining variant ever occupies more than one `char`. + let text = compose_state.get_string(self.context.scratch_buffer); + let key = Key::Dead(text.and_then(|s| s.chars().next())); + (key, location) + } else { + (key, location) + } + } else { + let key = self + .composed_text() + .unwrap_or_else(|_| self.context.keysym_to_utf8_raw(self.keysym)) + .map(Key::Character) + .unwrap_or(key); + (key, location) + } + } + + pub fn key_without_modifiers(&mut self) -> (Key, KeyLocation) { + // This will become a pointer to an array which libxkbcommon owns, so we don't need to + // deallocate it. + let layout = self.context.state.layout(self.keycode); + let keysym = self.context.keymap.first_keysym_by_level(layout, self.keycode); + + match self.keysym_to_key(keysym) { + Ok((key, location)) => (key, location), + Err((key, location)) => { + let key = + self.context.keysym_to_utf8_raw(keysym).map(Key::Character).unwrap_or(key); + (key, location) + }, + } + } + + fn keysym_to_key(&self, keysym: u32) -> Result<(Key, KeyLocation), (Key, KeyLocation)> { + let location = keymap::keysym_location(keysym); + let key = keymap::keysym_to_key(keysym); + if matches!(key, Key::Unidentified(_)) { + Err((key, location)) + } else { + Ok((key, location)) + } + } + + pub fn text(&mut self) -> Option<SmolStr> { + self.composed_text().unwrap_or_else(|_| self.context.keysym_to_utf8_raw(self.keysym)) + } + + // The current behaviour makes it so composing a character overrides attempts to input a + // control character with the `Ctrl` key. We can potentially add a configuration option + // if someone specifically wants the opposite behaviour. + pub fn text_with_all_modifiers(&mut self) -> Option<SmolStr> { + match self.composed_text() { + Ok(text) => text, + Err(_) => self.context.state.get_utf8_raw(self.keycode, self.context.scratch_buffer), + } + } + + fn composed_text(&mut self) -> Result<Option<SmolStr>, ()> { + match self.compose { + ComposeStatus::Accepted(status) => match status { + xkb_compose_status::XKB_COMPOSE_COMPOSED => { + let state = self.context.compose_state1.as_mut().unwrap(); + Ok(state.get_string(self.context.scratch_buffer)) + }, + xkb_compose_status::XKB_COMPOSE_COMPOSING + | xkb_compose_status::XKB_COMPOSE_CANCELLED => Ok(None), + xkb_compose_status::XKB_COMPOSE_NOTHING => Err(()), + }, + _ => Err(()), + } + } +} + +#[derive(Debug)] +pub struct XkbContext { + context: NonNull<xkb_context>, +} + +impl XkbContext { + pub fn new() -> Result<Self, Error> { + let context = unsafe { (XKBH.xkb_context_new)(xkb_context_flags::XKB_CONTEXT_NO_FLAGS) }; + + let context = match NonNull::new(context) { + Some(context) => context, + None => return Err(Error::XKBNotFound), + }; + + Ok(Self { context }) + } +} + +impl Drop for XkbContext { + fn drop(&mut self) { + unsafe { + (XKBH.xkb_context_unref)(self.context.as_ptr()); + } + } +} + +impl Deref for XkbContext { + type Target = NonNull<xkb_context>; + + fn deref(&self) -> &Self::Target { + &self.context + } +} + +/// Shared logic for constructing a string with `xkb_compose_state_get_utf8` and +/// `xkb_state_key_get_utf8`. +fn make_string_with<F>(scratch_buffer: &mut Vec<u8>, mut f: F) -> Option<SmolStr> +where + F: FnMut(*mut c_char, usize) -> i32, +{ + let size = f(ptr::null_mut(), 0); + if size == 0 { + return None; + } + let size = usize::try_from(size).unwrap(); + scratch_buffer.clear(); + // The allocated buffer must include space for the null-terminator. + scratch_buffer.reserve(size + 1); + unsafe { + let written = f(scratch_buffer.as_mut_ptr().cast(), scratch_buffer.capacity()); + if usize::try_from(written).unwrap() != size { + // This will likely never happen. + return None; + } + scratch_buffer.set_len(size); + }; + + byte_slice_to_smol_str(scratch_buffer) +} + +// NOTE: This is track_caller so we can have more informative line numbers when logging +#[track_caller] +fn byte_slice_to_smol_str(bytes: &[u8]) -> Option<SmolStr> { + std::str::from_utf8(bytes) + .map(SmolStr::new) + .map_err(|e| { + tracing::warn!("UTF-8 received from libxkbcommon ({:?}) was invalid: {e}", bytes) + }) + .ok() +} diff --git a/app/vendor/rune/vendor/winit/src/platform_impl/linux/common/xkb/state.rs b/app/vendor/rune/vendor/winit/src/platform_impl/linux/common/xkb/state.rs new file mode 100644 index 0000000..27c055a --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/platform_impl/linux/common/xkb/state.rs @@ -0,0 +1,189 @@ +//! XKB state. + +use std::os::raw::c_char; +use std::ptr::NonNull; + +use smol_str::SmolStr; +#[cfg(x11_platform)] +use x11_dl::xlib_xcb::xcb_connection_t; +use xkbcommon_dl::{ + self as xkb, xkb_keycode_t, xkb_keysym_t, xkb_layout_index_t, xkb_state, xkb_state_component, +}; + +use crate::platform_impl::common::xkb::keymap::XkbKeymap; +#[cfg(x11_platform)] +use crate::platform_impl::common::xkb::XKBXH; +use crate::platform_impl::common::xkb::{make_string_with, XKBH}; + +#[derive(Debug)] +pub struct XkbState { + state: NonNull<xkb_state>, + modifiers: ModifiersState, +} + +impl XkbState { + #[cfg(wayland_platform)] + pub fn new_wayland(keymap: &XkbKeymap) -> Option<Self> { + let state = NonNull::new(unsafe { (XKBH.xkb_state_new)(keymap.as_ptr()) })?; + Some(Self::new_inner(state)) + } + + #[cfg(x11_platform)] + pub fn new_x11(xcb: *mut xcb_connection_t, keymap: &XkbKeymap) -> Option<Self> { + let state = unsafe { + (XKBXH.xkb_x11_state_new_from_device)(keymap.as_ptr(), xcb, keymap._core_keyboard_id) + }; + let state = NonNull::new(state)?; + Some(Self::new_inner(state)) + } + + fn new_inner(state: NonNull<xkb_state>) -> Self { + let modifiers = ModifiersState::default(); + let mut this = Self { state, modifiers }; + this.reload_modifiers(); + this + } + + pub fn get_one_sym_raw(&mut self, keycode: xkb_keycode_t) -> xkb_keysym_t { + unsafe { (XKBH.xkb_state_key_get_one_sym)(self.state.as_ptr(), keycode) } + } + + pub fn layout(&mut self, key: xkb_keycode_t) -> xkb_layout_index_t { + unsafe { (XKBH.xkb_state_key_get_layout)(self.state.as_ptr(), key) } + } + + #[cfg(x11_platform)] + pub fn depressed_modifiers(&mut self) -> xkb::xkb_mod_mask_t { + unsafe { + (XKBH.xkb_state_serialize_mods)( + self.state.as_ptr(), + xkb_state_component::XKB_STATE_MODS_DEPRESSED, + ) + } + } + + #[cfg(x11_platform)] + pub fn latched_modifiers(&mut self) -> xkb::xkb_mod_mask_t { + unsafe { + (XKBH.xkb_state_serialize_mods)( + self.state.as_ptr(), + xkb_state_component::XKB_STATE_MODS_LATCHED, + ) + } + } + + #[cfg(x11_platform)] + pub fn locked_modifiers(&mut self) -> xkb::xkb_mod_mask_t { + unsafe { + (XKBH.xkb_state_serialize_mods)( + self.state.as_ptr(), + xkb_state_component::XKB_STATE_MODS_LOCKED, + ) + } + } + + pub fn get_utf8_raw( + &mut self, + keycode: xkb_keycode_t, + scratch_buffer: &mut Vec<u8>, + ) -> Option<SmolStr> { + make_string_with(scratch_buffer, |ptr, len| unsafe { + (XKBH.xkb_state_key_get_utf8)(self.state.as_ptr(), keycode, ptr, len) + }) + } + + pub fn modifiers(&self) -> ModifiersState { + self.modifiers + } + + pub fn update_modifiers( + &mut self, + mods_depressed: u32, + mods_latched: u32, + mods_locked: u32, + depressed_group: u32, + latched_group: u32, + locked_group: u32, + ) { + let mask = unsafe { + (XKBH.xkb_state_update_mask)( + self.state.as_ptr(), + mods_depressed, + mods_latched, + mods_locked, + depressed_group, + latched_group, + locked_group, + ) + }; + + if mask.contains(xkb_state_component::XKB_STATE_MODS_EFFECTIVE) { + // Effective value of mods have changed, we need to update our state. + self.reload_modifiers(); + } + } + + /// Reload the modifiers. + fn reload_modifiers(&mut self) { + self.modifiers.ctrl = self.mod_name_is_active(xkb::XKB_MOD_NAME_CTRL); + self.modifiers.alt = self.mod_name_is_active(xkb::XKB_MOD_NAME_ALT); + self.modifiers.shift = self.mod_name_is_active(xkb::XKB_MOD_NAME_SHIFT); + self.modifiers.caps_lock = self.mod_name_is_active(xkb::XKB_MOD_NAME_CAPS); + self.modifiers.logo = self.mod_name_is_active(xkb::XKB_MOD_NAME_LOGO); + self.modifiers.num_lock = self.mod_name_is_active(xkb::XKB_MOD_NAME_NUM); + } + + /// Check if the modifier is active within xkb. + fn mod_name_is_active(&mut self, name: &[u8]) -> bool { + unsafe { + (XKBH.xkb_state_mod_name_is_active)( + self.state.as_ptr(), + name.as_ptr() as *const c_char, + xkb_state_component::XKB_STATE_MODS_EFFECTIVE, + ) > 0 + } + } +} + +impl Drop for XkbState { + fn drop(&mut self) { + unsafe { + (XKBH.xkb_state_unref)(self.state.as_ptr()); + } + } +} + +/// Represents the current state of the keyboard modifiers +/// +/// Each field of this struct represents a modifier and is `true` if this modifier is active. +/// +/// For some modifiers, this means that the key is currently pressed, others are toggled +/// (like caps lock). +#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)] +pub struct ModifiersState { + /// The "control" key + pub ctrl: bool, + /// The "alt" key + pub alt: bool, + /// The "shift" key + pub shift: bool, + /// The "Caps lock" key + pub caps_lock: bool, + /// The "logo" key + /// + /// Also known as the "windows" key on most keyboards + pub logo: bool, + /// The "Num lock" key + pub num_lock: bool, +} + +impl From<ModifiersState> for crate::keyboard::ModifiersState { + fn from(mods: ModifiersState) -> crate::keyboard::ModifiersState { + let mut to_mods = crate::keyboard::ModifiersState::empty(); + to_mods.set(crate::keyboard::ModifiersState::SHIFT, mods.shift); + to_mods.set(crate::keyboard::ModifiersState::CONTROL, mods.ctrl); + to_mods.set(crate::keyboard::ModifiersState::ALT, mods.alt); + to_mods.set(crate::keyboard::ModifiersState::SUPER, mods.logo); + to_mods + } +} diff --git a/app/vendor/rune/vendor/winit/src/platform_impl/linux/mod.rs b/app/vendor/rune/vendor/winit/src/platform_impl/linux/mod.rs new file mode 100644 index 0000000..bc0e71c --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/platform_impl/linux/mod.rs @@ -0,0 +1,1044 @@ +#![cfg(free_unix)] + +#[cfg(all(not(x11_platform), not(wayland_platform)))] +compile_error!("Please select a feature to build for unix: `x11`, `wayland`"); + +use std::collections::VecDeque; +use std::os::unix::io::{AsFd, AsRawFd, BorrowedFd, RawFd}; +use std::sync::Arc; +use std::time::Duration; +use std::{env, fmt}; +#[cfg(x11_platform)] +use std::{ffi::CStr, mem::MaybeUninit, os::raw::*, sync::Mutex}; + +#[cfg(x11_platform)] +use crate::utils::Lazy; +use smol_str::SmolStr; + +#[cfg(x11_platform)] +use self::x11::{X11Error, XConnection, XError, XNotSupported}; +use crate::dpi::{PhysicalPosition, PhysicalSize, Position, Size}; +use crate::error::{EventLoopError, ExternalError, NotSupportedError, OsError as RootOsError}; +use crate::event_loop::{ + ActiveEventLoop as RootELW, AsyncRequestSerial, ControlFlow, DeviceEvents, EventLoopClosed, +}; +use crate::icon::Icon; +use crate::keyboard::Key; +use crate::platform::pump_events::PumpStatus; +#[cfg(x11_platform)] +use crate::platform::x11::{WindowType as XWindowType, XlibErrorHook}; +use crate::window::{ + ActivationToken, Cursor, CursorGrabMode, CustomCursor, CustomCursorSource, ImePurpose, + ResizeDirection, Theme, UserAttentionType, WindowAttributes, WindowButtons, WindowLevel, +}; + +pub(crate) use self::common::xkb::{physicalkey_to_scancode, scancode_to_physicalkey}; +pub(crate) use crate::cursor::OnlyCursorImageSource as PlatformCustomCursorSource; +pub(crate) use crate::icon::RgbaIcon as PlatformIcon; +pub(crate) use crate::platform_impl::Fullscreen; + +pub(crate) mod common; +#[cfg(wayland_platform)] +pub(crate) mod wayland; +#[cfg(x11_platform)] +pub(crate) mod x11; + +#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)] +pub(crate) enum Backend { + #[cfg(x11_platform)] + X, + #[cfg(wayland_platform)] + Wayland, +} + +#[derive(Debug, Default, Copy, Clone, PartialEq, Eq, Hash)] +pub(crate) struct PlatformSpecificEventLoopAttributes { + pub(crate) forced_backend: Option<Backend>, + pub(crate) any_thread: bool, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ApplicationName { + pub general: String, + pub instance: String, +} + +impl ApplicationName { + pub fn new(general: String, instance: String) -> Self { + Self { general, instance } + } +} + +#[derive(Clone, Debug)] +pub struct PlatformSpecificWindowAttributes { + pub name: Option<ApplicationName>, + pub activation_token: Option<ActivationToken>, + #[cfg(x11_platform)] + pub x11: X11WindowAttributes, +} + +#[derive(Clone, Debug)] +#[cfg(x11_platform)] +pub struct X11WindowAttributes { + pub visual_id: Option<x11rb::protocol::xproto::Visualid>, + pub screen_id: Option<i32>, + pub base_size: Option<Size>, + pub override_redirect: bool, + pub x11_window_types: Vec<XWindowType>, + + /// The parent window to embed this window into. + pub embed_window: Option<x11rb::protocol::xproto::Window>, +} + +#[cfg_attr(not(x11_platform), allow(clippy::derivable_impls))] +impl Default for PlatformSpecificWindowAttributes { + fn default() -> Self { + Self { + name: None, + activation_token: None, + #[cfg(x11_platform)] + x11: X11WindowAttributes { + visual_id: None, + screen_id: None, + base_size: None, + override_redirect: false, + x11_window_types: vec![XWindowType::Normal], + embed_window: None, + }, + } + } +} + +#[cfg(x11_platform)] +pub(crate) static X11_BACKEND: Lazy<Mutex<Result<Arc<XConnection>, XNotSupported>>> = + Lazy::new(|| Mutex::new(XConnection::new(Some(x_error_callback)).map(Arc::new))); + +#[derive(Debug, Clone)] +pub enum OsError { + Misc(&'static str), + #[cfg(x11_platform)] + XNotSupported(XNotSupported), + #[cfg(x11_platform)] + XError(Arc<X11Error>), + #[cfg(wayland_platform)] + WaylandError(Arc<wayland::WaylandError>), +} + +impl fmt::Display for OsError { + fn fmt(&self, _f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> { + match *self { + OsError::Misc(e) => _f.pad(e), + #[cfg(x11_platform)] + OsError::XNotSupported(ref e) => fmt::Display::fmt(e, _f), + #[cfg(x11_platform)] + OsError::XError(ref e) => fmt::Display::fmt(e, _f), + #[cfg(wayland_platform)] + OsError::WaylandError(ref e) => fmt::Display::fmt(e, _f), + } + } +} + +pub(crate) enum Window { + #[cfg(x11_platform)] + X(x11::Window), + #[cfg(wayland_platform)] + Wayland(wayland::Window), +} + +#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub struct WindowId(u64); + +impl From<WindowId> for u64 { + fn from(window_id: WindowId) -> Self { + window_id.0 + } +} + +impl From<u64> for WindowId { + fn from(raw_id: u64) -> Self { + Self(raw_id) + } +} + +impl WindowId { + pub const fn dummy() -> Self { + Self(0) + } +} + +#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub enum DeviceId { + #[cfg(x11_platform)] + X(x11::DeviceId), + #[cfg(wayland_platform)] + Wayland(wayland::DeviceId), +} + +impl DeviceId { + pub const fn dummy() -> Self { + #[cfg(wayland_platform)] + return DeviceId::Wayland(wayland::DeviceId::dummy()); + #[cfg(all(not(wayland_platform), x11_platform))] + return DeviceId::X(x11::DeviceId::dummy()); + } +} + +#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)] +pub enum MonitorHandle { + #[cfg(x11_platform)] + X(x11::MonitorHandle), + #[cfg(wayland_platform)] + Wayland(wayland::MonitorHandle), +} + +/// `x11_or_wayland!(match expr; Enum(foo) => foo.something())` +/// expands to the equivalent of +/// ```ignore +/// match self { +/// Enum::X(foo) => foo.something(), +/// Enum::Wayland(foo) => foo.something(), +/// } +/// ``` +/// The result can be converted to another enum by adding `; as AnotherEnum` +macro_rules! x11_or_wayland { + (match $what:expr; $enum:ident ( $($c1:tt)* ) => $x:expr; as $enum2:ident ) => { + match $what { + #[cfg(x11_platform)] + $enum::X($($c1)*) => $enum2::X($x), + #[cfg(wayland_platform)] + $enum::Wayland($($c1)*) => $enum2::Wayland($x), + } + }; + (match $what:expr; $enum:ident ( $($c1:tt)* ) => $x:expr) => { + match $what { + #[cfg(x11_platform)] + $enum::X($($c1)*) => $x, + #[cfg(wayland_platform)] + $enum::Wayland($($c1)*) => $x, + } + }; +} + +impl MonitorHandle { + #[inline] + pub fn name(&self) -> Option<String> { + x11_or_wayland!(match self; MonitorHandle(m) => m.name()) + } + + #[inline] + pub fn native_identifier(&self) -> u32 { + x11_or_wayland!(match self; MonitorHandle(m) => m.native_identifier()) + } + + #[inline] + pub fn size(&self) -> PhysicalSize<u32> { + x11_or_wayland!(match self; MonitorHandle(m) => m.size()) + } + + #[inline] + pub fn position(&self) -> PhysicalPosition<i32> { + x11_or_wayland!(match self; MonitorHandle(m) => m.position()) + } + + #[inline] + pub fn refresh_rate_millihertz(&self) -> Option<u32> { + x11_or_wayland!(match self; MonitorHandle(m) => m.refresh_rate_millihertz()) + } + + #[inline] + pub fn scale_factor(&self) -> f64 { + x11_or_wayland!(match self; MonitorHandle(m) => m.scale_factor() as _) + } + + #[inline] + pub fn video_modes(&self) -> Box<dyn Iterator<Item = VideoModeHandle>> { + x11_or_wayland!(match self; MonitorHandle(m) => Box::new(m.video_modes())) + } +} + +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub enum VideoModeHandle { + #[cfg(x11_platform)] + X(x11::VideoModeHandle), + #[cfg(wayland_platform)] + Wayland(wayland::VideoModeHandle), +} + +impl VideoModeHandle { + #[inline] + pub fn size(&self) -> PhysicalSize<u32> { + x11_or_wayland!(match self; VideoModeHandle(m) => m.size()) + } + + #[inline] + pub fn bit_depth(&self) -> u16 { + x11_or_wayland!(match self; VideoModeHandle(m) => m.bit_depth()) + } + + #[inline] + pub fn refresh_rate_millihertz(&self) -> u32 { + x11_or_wayland!(match self; VideoModeHandle(m) => m.refresh_rate_millihertz()) + } + + #[inline] + pub fn monitor(&self) -> MonitorHandle { + x11_or_wayland!(match self; VideoModeHandle(m) => m.monitor(); as MonitorHandle) + } +} + +impl Window { + #[inline] + pub(crate) fn new( + window_target: &ActiveEventLoop, + attribs: WindowAttributes, + ) -> Result<Self, RootOsError> { + match *window_target { + #[cfg(wayland_platform)] + ActiveEventLoop::Wayland(ref window_target) => { + wayland::Window::new(window_target, attribs).map(Window::Wayland) + }, + #[cfg(x11_platform)] + ActiveEventLoop::X(ref window_target) => { + x11::Window::new(window_target, attribs).map(Window::X) + }, + } + } + + pub(crate) fn maybe_queue_on_main(&self, f: impl FnOnce(&Self) + Send + 'static) { + f(self) + } + + pub(crate) fn maybe_wait_on_main<R: Send>(&self, f: impl FnOnce(&Self) -> R + Send) -> R { + f(self) + } + + #[inline] + pub fn id(&self) -> WindowId { + x11_or_wayland!(match self; Window(w) => w.id()) + } + + #[inline] + pub fn set_title(&self, title: &str) { + x11_or_wayland!(match self; Window(w) => w.set_title(title)); + } + + #[inline] + pub fn set_transparent(&self, transparent: bool) { + x11_or_wayland!(match self; Window(w) => w.set_transparent(transparent)); + } + + #[inline] + pub fn set_blur(&self, blur: bool) { + x11_or_wayland!(match self; Window(w) => w.set_blur(blur)); + } + + #[inline] + pub fn set_visible(&self, visible: bool) { + x11_or_wayland!(match self; Window(w) => w.set_visible(visible)) + } + + #[inline] + pub fn is_visible(&self) -> Option<bool> { + x11_or_wayland!(match self; Window(w) => w.is_visible()) + } + + #[inline] + pub fn outer_position(&self) -> Result<PhysicalPosition<i32>, NotSupportedError> { + x11_or_wayland!(match self; Window(w) => w.outer_position()) + } + + #[inline] + pub fn inner_position(&self) -> Result<PhysicalPosition<i32>, NotSupportedError> { + x11_or_wayland!(match self; Window(w) => w.inner_position()) + } + + #[inline] + pub fn set_outer_position(&self, position: Position) { + x11_or_wayland!(match self; Window(w) => w.set_outer_position(position)) + } + + #[inline] + pub fn inner_size(&self) -> PhysicalSize<u32> { + x11_or_wayland!(match self; Window(w) => w.inner_size()) + } + + #[inline] + pub fn outer_size(&self) -> PhysicalSize<u32> { + x11_or_wayland!(match self; Window(w) => w.outer_size()) + } + + #[inline] + pub fn request_inner_size(&self, size: Size) -> Option<PhysicalSize<u32>> { + x11_or_wayland!(match self; Window(w) => w.request_inner_size(size)) + } + + #[inline] + pub(crate) fn request_activation_token(&self) -> Result<AsyncRequestSerial, NotSupportedError> { + x11_or_wayland!(match self; Window(w) => w.request_activation_token()) + } + + #[inline] + pub fn set_min_inner_size(&self, dimensions: Option<Size>) { + x11_or_wayland!(match self; Window(w) => w.set_min_inner_size(dimensions)) + } + + #[inline] + pub fn set_max_inner_size(&self, dimensions: Option<Size>) { + x11_or_wayland!(match self; Window(w) => w.set_max_inner_size(dimensions)) + } + + #[inline] + pub fn resize_increments(&self) -> Option<PhysicalSize<u32>> { + x11_or_wayland!(match self; Window(w) => w.resize_increments()) + } + + #[inline] + pub fn set_resize_increments(&self, increments: Option<Size>) { + x11_or_wayland!(match self; Window(w) => w.set_resize_increments(increments)) + } + + #[inline] + pub fn set_resizable(&self, resizable: bool) { + x11_or_wayland!(match self; Window(w) => w.set_resizable(resizable)) + } + + #[inline] + pub fn is_resizable(&self) -> bool { + x11_or_wayland!(match self; Window(w) => w.is_resizable()) + } + + #[inline] + pub fn set_enabled_buttons(&self, buttons: WindowButtons) { + x11_or_wayland!(match self; Window(w) => w.set_enabled_buttons(buttons)) + } + + #[inline] + pub fn enabled_buttons(&self) -> WindowButtons { + x11_or_wayland!(match self; Window(w) => w.enabled_buttons()) + } + + #[inline] + pub fn set_cursor(&self, cursor: Cursor) { + x11_or_wayland!(match self; Window(w) => w.set_cursor(cursor)) + } + + #[inline] + pub fn set_cursor_grab(&self, mode: CursorGrabMode) -> Result<(), ExternalError> { + x11_or_wayland!(match self; Window(window) => window.set_cursor_grab(mode)) + } + + #[inline] + pub fn set_cursor_visible(&self, visible: bool) { + x11_or_wayland!(match self; Window(window) => window.set_cursor_visible(visible)) + } + + #[inline] + pub fn drag_window(&self) -> Result<(), ExternalError> { + x11_or_wayland!(match self; Window(window) => window.drag_window()) + } + + #[inline] + pub fn drag_resize_window(&self, direction: ResizeDirection) -> Result<(), ExternalError> { + x11_or_wayland!(match self; Window(window) => window.drag_resize_window(direction)) + } + + #[inline] + pub fn show_window_menu(&self, position: Position) { + x11_or_wayland!(match self; Window(w) => w.show_window_menu(position)) + } + + #[inline] + pub fn set_cursor_hittest(&self, hittest: bool) -> Result<(), ExternalError> { + x11_or_wayland!(match self; Window(w) => w.set_cursor_hittest(hittest)) + } + + #[inline] + pub fn scale_factor(&self) -> f64 { + x11_or_wayland!(match self; Window(w) => w.scale_factor()) + } + + #[inline] + pub fn set_cursor_position(&self, position: Position) -> Result<(), ExternalError> { + x11_or_wayland!(match self; Window(w) => w.set_cursor_position(position)) + } + + #[inline] + pub fn set_maximized(&self, maximized: bool) { + x11_or_wayland!(match self; Window(w) => w.set_maximized(maximized)) + } + + #[inline] + pub fn is_maximized(&self) -> bool { + x11_or_wayland!(match self; Window(w) => w.is_maximized()) + } + + #[inline] + pub fn set_minimized(&self, minimized: bool) { + x11_or_wayland!(match self; Window(w) => w.set_minimized(minimized)) + } + + #[inline] + pub fn is_minimized(&self) -> Option<bool> { + x11_or_wayland!(match self; Window(w) => w.is_minimized()) + } + + #[inline] + pub(crate) fn fullscreen(&self) -> Option<Fullscreen> { + x11_or_wayland!(match self; Window(w) => w.fullscreen()) + } + + #[inline] + pub(crate) fn set_fullscreen(&self, monitor: Option<Fullscreen>) { + x11_or_wayland!(match self; Window(w) => w.set_fullscreen(monitor)) + } + + #[inline] + pub fn set_decorations(&self, decorations: bool) { + x11_or_wayland!(match self; Window(w) => w.set_decorations(decorations)) + } + + #[inline] + pub fn is_decorated(&self) -> bool { + x11_or_wayland!(match self; Window(w) => w.is_decorated()) + } + + #[inline] + pub fn set_window_level(&self, level: WindowLevel) { + x11_or_wayland!(match self; Window(w) => w.set_window_level(level)) + } + + #[inline] + pub fn set_window_icon(&self, window_icon: Option<Icon>) { + x11_or_wayland!(match self; Window(w) => w.set_window_icon(window_icon.map(|icon| icon.inner))) + } + + #[inline] + pub fn set_ime_cursor_area(&self, position: Position, size: Size) { + x11_or_wayland!(match self; Window(w) => w.set_ime_cursor_area(position, size)) + } + + #[inline] + pub fn reset_dead_keys(&self) { + common::xkb::reset_dead_keys() + } + + #[inline] + pub fn set_ime_allowed(&self, allowed: bool) { + x11_or_wayland!(match self; Window(w) => w.set_ime_allowed(allowed)) + } + + #[inline] + pub fn set_ime_purpose(&self, purpose: ImePurpose) { + x11_or_wayland!(match self; Window(w) => w.set_ime_purpose(purpose)) + } + + #[inline] + pub fn focus_window(&self) { + x11_or_wayland!(match self; Window(w) => w.focus_window()) + } + + pub fn request_user_attention(&self, request_type: Option<UserAttentionType>) { + x11_or_wayland!(match self; Window(w) => w.request_user_attention(request_type)) + } + + #[inline] + pub fn request_redraw(&self) { + x11_or_wayland!(match self; Window(w) => w.request_redraw()) + } + + #[inline] + pub fn pre_present_notify(&self) { + x11_or_wayland!(match self; Window(w) => w.pre_present_notify()) + } + + #[inline] + pub fn current_monitor(&self) -> Option<MonitorHandle> { + Some(x11_or_wayland!(match self; Window(w) => w.current_monitor()?; as MonitorHandle)) + } + + #[inline] + pub fn available_monitors(&self) -> VecDeque<MonitorHandle> { + match self { + #[cfg(x11_platform)] + Window::X(ref window) => { + window.available_monitors().into_iter().map(MonitorHandle::X).collect() + }, + #[cfg(wayland_platform)] + Window::Wayland(ref window) => { + window.available_monitors().into_iter().map(MonitorHandle::Wayland).collect() + }, + } + } + + #[inline] + pub fn primary_monitor(&self) -> Option<MonitorHandle> { + Some(x11_or_wayland!(match self; Window(w) => w.primary_monitor()?; as MonitorHandle)) + } + + #[cfg(feature = "rwh_04")] + #[inline] + pub fn raw_window_handle_rwh_04(&self) -> rwh_04::RawWindowHandle { + x11_or_wayland!(match self; Window(window) => window.raw_window_handle_rwh_04()) + } + + #[cfg(feature = "rwh_05")] + #[inline] + pub fn raw_window_handle_rwh_05(&self) -> rwh_05::RawWindowHandle { + x11_or_wayland!(match self; Window(window) => window.raw_window_handle_rwh_05()) + } + + #[cfg(feature = "rwh_05")] + #[inline] + pub fn raw_display_handle_rwh_05(&self) -> rwh_05::RawDisplayHandle { + x11_or_wayland!(match self; Window(window) => window.raw_display_handle_rwh_05()) + } + + #[cfg(feature = "rwh_06")] + #[inline] + pub fn raw_window_handle_rwh_06(&self) -> Result<rwh_06::RawWindowHandle, rwh_06::HandleError> { + x11_or_wayland!(match self; Window(window) => window.raw_window_handle_rwh_06()) + } + + #[cfg(feature = "rwh_06")] + #[inline] + pub fn raw_display_handle_rwh_06( + &self, + ) -> Result<rwh_06::RawDisplayHandle, rwh_06::HandleError> { + x11_or_wayland!(match self; Window(window) => window.raw_display_handle_rwh_06()) + } + + #[inline] + pub fn set_theme(&self, theme: Option<Theme>) { + x11_or_wayland!(match self; Window(window) => window.set_theme(theme)) + } + + #[inline] + pub fn theme(&self) -> Option<Theme> { + x11_or_wayland!(match self; Window(window) => window.theme()) + } + + pub fn set_content_protected(&self, protected: bool) { + x11_or_wayland!(match self; Window(window) => window.set_content_protected(protected)) + } + + #[inline] + pub fn has_focus(&self) -> bool { + x11_or_wayland!(match self; Window(window) => window.has_focus()) + } + + pub fn title(&self) -> String { + x11_or_wayland!(match self; Window(window) => window.title()) + } +} + +#[derive(Debug, Clone, Eq, PartialEq, Hash)] +pub struct KeyEventExtra { + pub text_with_all_modifiers: Option<SmolStr>, + pub key_without_modifiers: Key, +} + +#[derive(Clone, Debug, Eq, Hash, PartialEq)] +pub(crate) enum PlatformCustomCursor { + #[cfg(wayland_platform)] + Wayland(wayland::CustomCursor), + #[cfg(x11_platform)] + X(x11::CustomCursor), +} + +/// Hooks for X11 errors. +#[cfg(x11_platform)] +pub(crate) static XLIB_ERROR_HOOKS: Mutex<Vec<XlibErrorHook>> = Mutex::new(Vec::new()); + +#[cfg(x11_platform)] +unsafe extern "C" fn x_error_callback( + display: *mut x11::ffi::Display, + event: *mut x11::ffi::XErrorEvent, +) -> c_int { + let xconn_lock = X11_BACKEND.lock().unwrap_or_else(|e| e.into_inner()); + if let Ok(ref xconn) = *xconn_lock { + // Call all the hooks. + let mut error_handled = false; + for hook in XLIB_ERROR_HOOKS.lock().unwrap().iter() { + error_handled |= hook(display as *mut _, event as *mut _); + } + + // `assume_init` is safe here because the array consists of `MaybeUninit` values, + // which do not require initialization. + let mut buf: [MaybeUninit<c_char>; 1024] = unsafe { MaybeUninit::uninit().assume_init() }; + unsafe { + (xconn.xlib.XGetErrorText)( + display, + (*event).error_code as c_int, + buf.as_mut_ptr() as *mut c_char, + buf.len() as c_int, + ) + }; + let description = + unsafe { CStr::from_ptr(buf.as_ptr() as *const c_char) }.to_string_lossy(); + + let error = unsafe { + XError { + description: description.into_owned(), + error_code: (*event).error_code, + request_code: (*event).request_code, + minor_code: (*event).minor_code, + } + }; + + // Don't log error. + if !error_handled { + tracing::error!("X11 error: {:#?}", error); + // XXX only update the error, if it wasn't handled by any of the hooks. + *xconn.latest_error.lock().unwrap() = Some(error); + } + } + // Fun fact: this return value is completely ignored. + 0 +} + +#[allow(clippy::large_enum_variant)] +pub enum EventLoop<T: 'static> { + #[cfg(wayland_platform)] + Wayland(Box<wayland::EventLoop<T>>), + #[cfg(x11_platform)] + X(x11::EventLoop<T>), +} + +pub enum EventLoopProxy<T: 'static> { + #[cfg(x11_platform)] + X(x11::EventLoopProxy<T>), + #[cfg(wayland_platform)] + Wayland(wayland::EventLoopProxy<T>), +} + +impl<T: 'static> Clone for EventLoopProxy<T> { + fn clone(&self) -> Self { + x11_or_wayland!(match self; EventLoopProxy(proxy) => proxy.clone(); as EventLoopProxy) + } +} + +impl<T: 'static> EventLoop<T> { + pub(crate) fn new( + attributes: &PlatformSpecificEventLoopAttributes, + ) -> Result<Self, EventLoopError> { + if !attributes.any_thread && !is_main_thread() { + panic!( + "Initializing the event loop outside of the main thread is a significant \ + cross-platform compatibility hazard. If you absolutely need to create an \ + EventLoop on a different thread, you can use the \ + `EventLoopBuilderExtX11::any_thread` or `EventLoopBuilderExtWayland::any_thread` \ + functions." + ); + } + + // NOTE: Wayland first because of X11 could be present under Wayland as well. Empty + // variables are also treated as not set. + let backend = match ( + attributes.forced_backend, + env::var("WAYLAND_DISPLAY") + .ok() + .filter(|var| !var.is_empty()) + .or_else(|| env::var("WAYLAND_SOCKET").ok()) + .filter(|var| !var.is_empty()) + .is_some(), + env::var("DISPLAY").map(|var| !var.is_empty()).unwrap_or(false), + ) { + // User is forcing a backend. + (Some(backend), ..) => backend, + // Wayland is present. + #[cfg(wayland_platform)] + (None, true, _) => Backend::Wayland, + // X11 is present. + #[cfg(x11_platform)] + (None, _, true) => Backend::X, + // No backend is present. + (_, wayland_display, x11_display) => { + let msg = if wayland_display && !cfg!(wayland_platform) { + "DISPLAY is not set; note: enable the `winit/wayland` feature to support \ + Wayland" + } else if x11_display && !cfg!(x11_platform) { + "neither WAYLAND_DISPLAY nor WAYLAND_SOCKET is set; note: enable the \ + `winit/x11` feature to support X11" + } else { + "neither WAYLAND_DISPLAY nor WAYLAND_SOCKET nor DISPLAY is set." + }; + return Err(EventLoopError::Os(os_error!(OsError::Misc(msg)))); + }, + }; + + // Create the display based on the backend. + match backend { + #[cfg(wayland_platform)] + Backend::Wayland => EventLoop::new_wayland_any_thread(), + #[cfg(x11_platform)] + Backend::X => EventLoop::new_x11_any_thread(), + } + } + + #[cfg(wayland_platform)] + fn new_wayland_any_thread() -> Result<EventLoop<T>, EventLoopError> { + wayland::EventLoop::new().map(|evlp| EventLoop::Wayland(Box::new(evlp))) + } + + #[cfg(x11_platform)] + fn new_x11_any_thread() -> Result<EventLoop<T>, EventLoopError> { + let xconn = match X11_BACKEND.lock().unwrap_or_else(|e| e.into_inner()).as_ref() { + Ok(xconn) => xconn.clone(), + Err(err) => { + return Err(EventLoopError::Os(os_error!(OsError::XNotSupported(err.clone())))) + }, + }; + + Ok(EventLoop::X(x11::EventLoop::new(xconn))) + } + + #[inline] + pub fn is_wayland(&self) -> bool { + match *self { + #[cfg(wayland_platform)] + EventLoop::Wayland(_) => true, + #[cfg(x11_platform)] + _ => false, + } + } + + pub fn create_proxy(&self) -> EventLoopProxy<T> { + x11_or_wayland!(match self; EventLoop(evlp) => evlp.create_proxy(); as EventLoopProxy) + } + + pub fn run<F>(mut self, callback: F) -> Result<(), EventLoopError> + where + F: FnMut(crate::event::Event<T>, &RootELW), + { + self.run_on_demand(callback) + } + + pub fn run_on_demand<F>(&mut self, callback: F) -> Result<(), EventLoopError> + where + F: FnMut(crate::event::Event<T>, &RootELW), + { + x11_or_wayland!(match self; EventLoop(evlp) => evlp.run_on_demand(callback)) + } + + pub fn pump_events<F>(&mut self, timeout: Option<Duration>, callback: F) -> PumpStatus + where + F: FnMut(crate::event::Event<T>, &RootELW), + { + x11_or_wayland!(match self; EventLoop(evlp) => evlp.pump_events(timeout, callback)) + } + + pub fn window_target(&self) -> &crate::event_loop::ActiveEventLoop { + x11_or_wayland!(match self; EventLoop(evlp) => evlp.window_target()) + } +} + +impl<T> AsFd for EventLoop<T> { + fn as_fd(&self) -> BorrowedFd<'_> { + x11_or_wayland!(match self; EventLoop(evlp) => evlp.as_fd()) + } +} + +impl<T> AsRawFd for EventLoop<T> { + fn as_raw_fd(&self) -> RawFd { + x11_or_wayland!(match self; EventLoop(evlp) => evlp.as_raw_fd()) + } +} + +impl<T: 'static> EventLoopProxy<T> { + pub fn send_event(&self, event: T) -> Result<(), EventLoopClosed<T>> { + x11_or_wayland!(match self; EventLoopProxy(proxy) => proxy.send_event(event)) + } +} + +#[allow(clippy::large_enum_variant)] +pub enum ActiveEventLoop { + #[cfg(wayland_platform)] + Wayland(wayland::ActiveEventLoop), + #[cfg(x11_platform)] + X(x11::ActiveEventLoop), +} + +impl ActiveEventLoop { + #[inline] + pub fn is_wayland(&self) -> bool { + match *self { + #[cfg(wayland_platform)] + ActiveEventLoop::Wayland(_) => true, + #[cfg(x11_platform)] + _ => false, + } + } + + pub fn create_custom_cursor(&self, cursor: CustomCursorSource) -> CustomCursor { + x11_or_wayland!(match self; ActiveEventLoop(evlp) => evlp.create_custom_cursor(cursor)) + } + + #[inline] + pub fn available_monitors(&self) -> VecDeque<MonitorHandle> { + match *self { + #[cfg(wayland_platform)] + ActiveEventLoop::Wayland(ref evlp) => { + evlp.available_monitors().map(MonitorHandle::Wayland).collect() + }, + #[cfg(x11_platform)] + ActiveEventLoop::X(ref evlp) => { + evlp.available_monitors().map(MonitorHandle::X).collect() + }, + } + } + + #[inline] + pub fn primary_monitor(&self) -> Option<MonitorHandle> { + Some( + x11_or_wayland!(match self; ActiveEventLoop(evlp) => evlp.primary_monitor()?; as MonitorHandle), + ) + } + + #[inline] + pub fn listen_device_events(&self, allowed: DeviceEvents) { + x11_or_wayland!(match self; Self(evlp) => evlp.listen_device_events(allowed)) + } + + #[cfg(feature = "rwh_05")] + #[inline] + pub fn raw_display_handle_rwh_05(&self) -> rwh_05::RawDisplayHandle { + x11_or_wayland!(match self; Self(evlp) => evlp.raw_display_handle_rwh_05()) + } + + #[inline] + pub fn system_theme(&self) -> Option<Theme> { + None + } + + #[cfg(feature = "rwh_06")] + #[inline] + pub fn raw_display_handle_rwh_06( + &self, + ) -> Result<rwh_06::RawDisplayHandle, rwh_06::HandleError> { + x11_or_wayland!(match self; Self(evlp) => evlp.raw_display_handle_rwh_06()) + } + + pub(crate) fn set_control_flow(&self, control_flow: ControlFlow) { + x11_or_wayland!(match self; Self(evlp) => evlp.set_control_flow(control_flow)) + } + + pub(crate) fn control_flow(&self) -> ControlFlow { + x11_or_wayland!(match self; Self(evlp) => evlp.control_flow()) + } + + pub(crate) fn clear_exit(&self) { + x11_or_wayland!(match self; Self(evlp) => evlp.clear_exit()) + } + + pub(crate) fn exit(&self) { + x11_or_wayland!(match self; Self(evlp) => evlp.exit()) + } + + pub(crate) fn exiting(&self) -> bool { + x11_or_wayland!(match self; Self(evlp) => evlp.exiting()) + } + + pub(crate) fn owned_display_handle(&self) -> OwnedDisplayHandle { + match self { + #[cfg(x11_platform)] + Self::X(conn) => OwnedDisplayHandle::X(conn.x_connection().clone()), + #[cfg(wayland_platform)] + Self::Wayland(conn) => OwnedDisplayHandle::Wayland(conn.connection.clone()), + } + } + + #[allow(dead_code)] + fn set_exit_code(&self, code: i32) { + x11_or_wayland!(match self; Self(evlp) => evlp.set_exit_code(code)) + } + + #[allow(dead_code)] + fn exit_code(&self) -> Option<i32> { + x11_or_wayland!(match self; Self(evlp) => evlp.exit_code()) + } +} + +#[derive(Clone)] +#[allow(dead_code)] +pub(crate) enum OwnedDisplayHandle { + #[cfg(x11_platform)] + X(Arc<XConnection>), + #[cfg(wayland_platform)] + Wayland(wayland_client::Connection), +} + +impl OwnedDisplayHandle { + #[cfg(feature = "rwh_05")] + #[inline] + pub fn raw_display_handle_rwh_05(&self) -> rwh_05::RawDisplayHandle { + match self { + #[cfg(x11_platform)] + Self::X(xconn) => { + let mut xlib_handle = rwh_05::XlibDisplayHandle::empty(); + xlib_handle.display = xconn.display.cast(); + xlib_handle.screen = xconn.default_screen_index() as _; + xlib_handle.into() + }, + + #[cfg(wayland_platform)] + Self::Wayland(conn) => { + use sctk::reexports::client::Proxy; + + let mut wayland_handle = rwh_05::WaylandDisplayHandle::empty(); + wayland_handle.display = conn.display().id().as_ptr() as *mut _; + wayland_handle.into() + }, + } + } + + #[cfg(feature = "rwh_06")] + #[inline] + pub fn raw_display_handle_rwh_06( + &self, + ) -> Result<rwh_06::RawDisplayHandle, rwh_06::HandleError> { + use std::ptr::NonNull; + + match self { + #[cfg(x11_platform)] + Self::X(xconn) => Ok(rwh_06::XlibDisplayHandle::new( + NonNull::new(xconn.display.cast()), + xconn.default_screen_index() as _, + ) + .into()), + + #[cfg(wayland_platform)] + Self::Wayland(conn) => { + use sctk::reexports::client::Proxy; + + Ok(rwh_06::WaylandDisplayHandle::new( + NonNull::new(conn.display().id().as_ptr().cast()).unwrap(), + ) + .into()) + }, + } + } +} + +/// Returns the minimum `Option<Duration>`, taking into account that `None` +/// equates to an infinite timeout, not a zero timeout (so can't just use +/// `Option::min`) +fn min_timeout(a: Option<Duration>, b: Option<Duration>) -> Option<Duration> { + a.map_or(b, |a_timeout| b.map_or(Some(a_timeout), |b_timeout| Some(a_timeout.min(b_timeout)))) +} + +#[cfg(target_os = "linux")] +fn is_main_thread() -> bool { + rustix::thread::gettid() == rustix::process::getpid() +} + +#[cfg(any(target_os = "dragonfly", target_os = "freebsd", target_os = "openbsd"))] +fn is_main_thread() -> bool { + use libc::pthread_main_np; + + unsafe { pthread_main_np() == 1 } +} + +#[cfg(target_os = "netbsd")] +fn is_main_thread() -> bool { + std::thread::current().name() == Some("main") +} diff --git a/app/vendor/rune/vendor/winit/src/platform_impl/linux/wayland/event_loop/mod.rs b/app/vendor/rune/vendor/winit/src/platform_impl/linux/wayland/event_loop/mod.rs new file mode 100644 index 0000000..fef13f4 --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/platform_impl/linux/wayland/event_loop/mod.rs @@ -0,0 +1,810 @@ +//! The event-loop routines. + +use std::cell::{Cell, RefCell}; +use std::io::Result as IOResult; +use std::marker::PhantomData; +use std::mem; +use std::os::fd::OwnedFd; +use std::os::unix::io::{AsFd, AsRawFd, BorrowedFd, RawFd}; +use std::rc::Rc; +use std::sync::atomic::Ordering; +use std::sync::{Arc, Condvar, Mutex}; +use std::thread::JoinHandle; +use std::time::{Duration, Instant}; + +use calloop::ping::Ping; +use rustix::event::{PollFd, PollFlags}; +use rustix::pipe::{self, PipeFlags}; +use sctk::reexports::calloop::Error as CalloopError; +use sctk::reexports::calloop_wayland_source::WaylandSource; +use sctk::reexports::client::{globals, Connection, QueueHandle}; +use tracing::warn; + +use crate::cursor::OnlyCursorImage; +use crate::dpi::LogicalSize; +use crate::error::{EventLoopError, OsError as RootOsError}; +use crate::event::{Event, InnerSizeWriter, StartCause, WindowEvent}; +use crate::event_loop::{ActiveEventLoop as RootActiveEventLoop, ControlFlow, DeviceEvents}; +use crate::platform::pump_events::PumpStatus; +use crate::platform_impl::platform::min_timeout; +use crate::platform_impl::{ + ActiveEventLoop as PlatformActiveEventLoop, OsError, PlatformCustomCursor, +}; +use crate::window::{CustomCursor as RootCustomCursor, CustomCursorSource}; + +mod proxy; +pub mod sink; + +pub use proxy::EventLoopProxy; +use sink::EventSink; + +use super::state::{WindowCompositorUpdate, WinitState}; +use super::window::state::FrameCallbackState; +use super::{logical_to_physical_rounded, DeviceId, WaylandError, WindowId}; + +type WaylandDispatcher = calloop::Dispatcher<'static, WaylandSource<WinitState>, WinitState>; + +/// The Wayland event loop. +pub struct EventLoop<T: 'static> { + /// Has `run` or `run_on_demand` been called or a call to `pump_events` that starts the loop + loop_running: bool, + + buffer_sink: EventSink, + compositor_updates: Vec<WindowCompositorUpdate>, + window_ids: Vec<WindowId>, + + /// Sender of user events. + user_events_sender: calloop::channel::Sender<T>, + + // XXX can't remove RefCell out of here, unless we can plumb generics into the `Window`, which + // we don't really want, since it'll break public API by a lot. + /// Pending events from the user. + pending_user_events: Rc<RefCell<Vec<T>>>, + + /// The Wayland dispatcher to has raw access to the queue when needed, such as + /// when creating a new window. + wayland_dispatcher: WaylandDispatcher, + + /// Connection to the wayland server. + connection: Connection, + + /// Event loop window target. + window_target: RootActiveEventLoop, + + // XXX drop after everything else, just to be safe. + /// Calloop's event loop. + event_loop: calloop::EventLoop<'static, WinitState>, + + pump_event_notifier: Option<PumpEventNotifier>, +} + +impl<T: 'static> EventLoop<T> { + pub fn new() -> Result<EventLoop<T>, EventLoopError> { + macro_rules! map_err { + ($e:expr, $err:expr) => { + $e.map_err(|error| os_error!($err(error).into())) + }; + } + + let connection = map_err!(Connection::connect_to_env(), WaylandError::Connection)?; + + let (globals, mut event_queue) = + map_err!(globals::registry_queue_init(&connection), WaylandError::Global)?; + let queue_handle = event_queue.handle(); + + let event_loop = + map_err!(calloop::EventLoop::<WinitState>::try_new(), WaylandError::Calloop)?; + + let mut winit_state = WinitState::new(&globals, &queue_handle, event_loop.handle()) + .map_err(|error| os_error!(error))?; + + // NOTE: do a roundtrip after binding the globals to prevent potential + // races with the server. + map_err!(event_queue.roundtrip(&mut winit_state), WaylandError::Dispatch)?; + + // Register Wayland source. + let wayland_source = WaylandSource::new(connection.clone(), event_queue); + let wayland_dispatcher = + calloop::Dispatcher::new(wayland_source, |_, queue, winit_state: &mut WinitState| { + let result = queue.dispatch_pending(winit_state); + if result.is_ok() + && (!winit_state.events_sink.is_empty() + || !winit_state.window_compositor_updates.is_empty()) + { + winit_state.dispatched_events = true; + } + result + }); + + map_err!( + event_loop.handle().register_dispatcher(wayland_dispatcher.clone()), + WaylandError::Calloop + )?; + + // Setup the user proxy. + let pending_user_events = Rc::new(RefCell::new(Vec::new())); + let pending_user_events_clone = pending_user_events.clone(); + let (user_events_sender, user_events_channel) = calloop::channel::channel(); + let result = event_loop + .handle() + .insert_source(user_events_channel, move |event, _, winit_state: &mut WinitState| { + if let calloop::channel::Event::Msg(msg) = event { + winit_state.dispatched_events = true; + pending_user_events_clone.borrow_mut().push(msg); + } + }) + .map_err(|error| error.error); + map_err!(result, WaylandError::Calloop)?; + + // An event's loop awakener to wake up for window events from winit's windows. + let (event_loop_awakener, event_loop_awakener_source) = map_err!( + calloop::ping::make_ping() + .map_err(|error| CalloopError::OtherError(Box::new(error).into())), + WaylandError::Calloop + )?; + + let result = event_loop + .handle() + .insert_source(event_loop_awakener_source, move |_, _, winit_state: &mut WinitState| { + // Mark that we have something to dispatch. + winit_state.dispatched_events = true; + }) + .map_err(|error| error.error); + map_err!(result, WaylandError::Calloop)?; + + let window_target = ActiveEventLoop { + connection: connection.clone(), + wayland_dispatcher: wayland_dispatcher.clone(), + event_loop_awakener, + queue_handle, + control_flow: Cell::new(ControlFlow::default()), + exit: Cell::new(None), + state: RefCell::new(winit_state), + }; + + let event_loop = Self { + loop_running: false, + compositor_updates: Vec::new(), + buffer_sink: EventSink::default(), + window_ids: Vec::new(), + connection, + wayland_dispatcher, + user_events_sender, + pending_user_events, + event_loop, + window_target: RootActiveEventLoop { + p: PlatformActiveEventLoop::Wayland(window_target), + _marker: PhantomData, + }, + pump_event_notifier: None, + }; + + Ok(event_loop) + } + + pub fn run_on_demand<F>(&mut self, mut event_handler: F) -> Result<(), EventLoopError> + where + F: FnMut(Event<T>, &RootActiveEventLoop), + { + let exit = loop { + match self.pump_events(None, &mut event_handler) { + PumpStatus::Exit(0) => { + break Ok(()); + }, + PumpStatus::Exit(code) => { + break Err(EventLoopError::ExitFailure(code)); + }, + _ => { + continue; + }, + } + }; + + // Applications aren't allowed to carry windows between separate + // `run_on_demand` calls but if they have only just dropped their + // windows we need to make sure those last requests are sent to the + // compositor. + let _ = self.roundtrip().map_err(EventLoopError::Os); + + exit + } + + pub fn pump_events<F>(&mut self, timeout: Option<Duration>, mut callback: F) -> PumpStatus + where + F: FnMut(Event<T>, &RootActiveEventLoop), + { + if !self.loop_running { + self.loop_running = true; + + // Run the initial loop iteration. + self.single_iteration(&mut callback, StartCause::Init); + } + + // Consider the possibility that the `StartCause::Init` iteration could + // request to Exit. + if !self.exiting() { + self.poll_events_with_timeout(timeout, &mut callback); + } + if let Some(code) = self.exit_code() { + self.loop_running = false; + + callback(Event::LoopExiting, self.window_target()); + + PumpStatus::Exit(code) + } else { + // NOTE: spawn a wake-up thread, thus if we have code reading the wayland connection + // in parallel to winit, we ensure that the loop itself is marked as having events. + if timeout.is_some() && self.pump_event_notifier.is_none() { + let awakener = match &self.window_target.p { + PlatformActiveEventLoop::Wayland(window_target) => { + window_target.event_loop_awakener.clone() + }, + #[cfg(x11_platform)] + PlatformActiveEventLoop::X(_) => unreachable!(), + }; + + self.pump_event_notifier = + Some(PumpEventNotifier::spawn(self.connection.clone(), awakener)); + } + + if let Some(pump_event_notifier) = self.pump_event_notifier.as_ref() { + // Notify that we don't have to wait, since we're out of winit. + *pump_event_notifier.control.0.lock().unwrap() = PumpEventNotifierAction::Monitor; + pump_event_notifier.control.1.notify_one(); + } + + PumpStatus::Continue + } + } + + pub fn poll_events_with_timeout<F>(&mut self, mut timeout: Option<Duration>, mut callback: F) + where + F: FnMut(Event<T>, &RootActiveEventLoop), + { + let cause = loop { + let start = Instant::now(); + + timeout = { + let control_flow_timeout = match self.control_flow() { + ControlFlow::Wait => None, + ControlFlow::Poll => Some(Duration::ZERO), + ControlFlow::WaitUntil(wait_deadline) => { + Some(wait_deadline.saturating_duration_since(start)) + }, + }; + min_timeout(control_flow_timeout, timeout) + }; + + // NOTE Ideally we should flush as the last thing we do before polling + // to wait for events, and this should be done by the calloop + // WaylandSource but we currently need to flush writes manually. + // + // Checking for flush error is essential to perform an exit with error, since + // once we have a protocol error, we could get stuck retrying... + if self.connection.flush().is_err() { + self.set_exit_code(1); + return; + } + + if let Err(error) = self.loop_dispatch(timeout) { + // NOTE We exit on errors from dispatches, since if we've got protocol error + // libwayland-client/wayland-rs will inform us anyway, but crashing downstream is + // not really an option. Instead we inform that the event loop got + // destroyed. We may communicate an error that something was + // terminated, but winit doesn't provide us with an API to do that + // via some event. Still, we set the exit code to the error's OS + // error code, or to 1 if not possible. + let exit_code = error.raw_os_error().unwrap_or(1); + self.set_exit_code(exit_code); + return; + } + + // NB: `StartCause::Init` is handled as a special case and doesn't need + // to be considered here + let cause = match self.control_flow() { + ControlFlow::Poll => StartCause::Poll, + ControlFlow::Wait => StartCause::WaitCancelled { start, requested_resume: None }, + ControlFlow::WaitUntil(deadline) => { + if Instant::now() < deadline { + StartCause::WaitCancelled { start, requested_resume: Some(deadline) } + } else { + StartCause::ResumeTimeReached { start, requested_resume: deadline } + } + }, + }; + + // Reduce spurious wake-ups. + let dispatched_events = self.with_state(|state| state.dispatched_events); + if matches!(cause, StartCause::WaitCancelled { .. }) + && !dispatched_events + && timeout.is_none() + { + continue; + } + + break cause; + }; + + self.single_iteration(&mut callback, cause); + } + + fn single_iteration<F>(&mut self, callback: &mut F, cause: StartCause) + where + F: FnMut(Event<T>, &RootActiveEventLoop), + { + // NOTE currently just indented to simplify the diff + + // We retain these grow-only scratch buffers as part of the EventLoop + // for the sake of avoiding lots of reallocs. We take them here to avoid + // trying to mutably borrow `self` more than once and we swap them back + // when finished. + let mut compositor_updates = std::mem::take(&mut self.compositor_updates); + let mut buffer_sink = std::mem::take(&mut self.buffer_sink); + let mut window_ids = std::mem::take(&mut self.window_ids); + + callback(Event::NewEvents(cause), &self.window_target); + + // NB: For consistency all platforms must emit a 'resumed' event even though Wayland + // applications don't themselves have a formal suspend/resume lifecycle. + if cause == StartCause::Init { + callback(Event::Resumed, &self.window_target); + } + + // Handle pending user events. We don't need back buffer, since we can't dispatch + // user events indirectly via callback to the user. + for user_event in self.pending_user_events.borrow_mut().drain(..) { + callback(Event::UserEvent(user_event), &self.window_target); + } + + // Drain the pending compositor updates. + self.with_state(|state| compositor_updates.append(&mut state.window_compositor_updates)); + + for mut compositor_update in compositor_updates.drain(..) { + let window_id = compositor_update.window_id; + if compositor_update.scale_changed { + let (physical_size, scale_factor) = self.with_state(|state| { + let windows = state.windows.get_mut(); + let window = windows.get(&window_id).unwrap().lock().unwrap(); + let scale_factor = window.scale_factor(); + let size = logical_to_physical_rounded(window.inner_size(), scale_factor); + (size, scale_factor) + }); + + // Stash the old window size. + let old_physical_size = physical_size; + + let new_inner_size = Arc::new(Mutex::new(physical_size)); + callback( + Event::WindowEvent { + window_id: crate::window::WindowId(window_id), + event: WindowEvent::ScaleFactorChanged { + scale_factor, + inner_size_writer: InnerSizeWriter::new(Arc::downgrade( + &new_inner_size, + )), + }, + }, + &self.window_target, + ); + + let physical_size = *new_inner_size.lock().unwrap(); + drop(new_inner_size); + + // Resize the window when user altered the size. + if old_physical_size != physical_size { + self.with_state(|state| { + let windows = state.windows.get_mut(); + let mut window = windows.get(&window_id).unwrap().lock().unwrap(); + + let new_logical_size: LogicalSize<f64> = + physical_size.to_logical(scale_factor); + window.request_inner_size(new_logical_size.into()); + }); + + // Make it queue resize. + compositor_update.resized = true; + } + } + + // NOTE: Rescale changed the physical size which winit operates in, thus we should + // resize. + if compositor_update.resized || compositor_update.scale_changed { + let physical_size = self.with_state(|state| { + let windows = state.windows.get_mut(); + let window = windows.get(&window_id).unwrap().lock().unwrap(); + + let scale_factor = window.scale_factor(); + let size = logical_to_physical_rounded(window.inner_size(), scale_factor); + + // Mark the window as needed a redraw. + state + .window_requests + .get_mut() + .get_mut(&window_id) + .unwrap() + .redraw_requested + .store(true, Ordering::Relaxed); + + size + }); + + callback( + Event::WindowEvent { + window_id: crate::window::WindowId(window_id), + event: WindowEvent::Resized(physical_size), + }, + &self.window_target, + ); + } + + if compositor_update.close_window { + callback( + Event::WindowEvent { + window_id: crate::window::WindowId(window_id), + event: WindowEvent::CloseRequested, + }, + &self.window_target, + ); + } + } + + // Push the events directly from the window. + self.with_state(|state| { + buffer_sink.append(&mut state.window_events_sink.lock().unwrap()); + }); + for event in buffer_sink.drain() { + let event = event.map_nonuser_event().unwrap(); + callback(event, &self.window_target); + } + + // Handle non-synthetic events. + self.with_state(|state| { + buffer_sink.append(&mut state.events_sink); + }); + for event in buffer_sink.drain() { + let event = event.map_nonuser_event().unwrap(); + callback(event, &self.window_target); + } + + // Collect the window ids + self.with_state(|state| { + window_ids.extend(state.window_requests.get_mut().keys()); + }); + + for window_id in window_ids.iter() { + let event = self.with_state(|state| { + let window_requests = state.window_requests.get_mut(); + if window_requests.get(window_id).unwrap().take_closed() { + mem::drop(window_requests.remove(window_id)); + mem::drop(state.windows.get_mut().remove(window_id)); + return Some(WindowEvent::Destroyed); + } + + let mut window = + state.windows.get_mut().get_mut(window_id).unwrap().lock().unwrap(); + + if window.frame_callback_state() == FrameCallbackState::Requested { + return None; + } + + // Reset the frame callbacks state. + window.frame_callback_reset(); + let mut redraw_requested = + window_requests.get(window_id).unwrap().take_redraw_requested(); + + // Redraw the frame while at it. + redraw_requested |= window.refresh_frame(); + + redraw_requested.then_some(WindowEvent::RedrawRequested) + }); + + if let Some(event) = event { + callback( + Event::WindowEvent { window_id: crate::window::WindowId(*window_id), event }, + &self.window_target, + ); + } + } + + // Reset the hint that we've dispatched events. + self.with_state(|state| { + state.dispatched_events = false; + }); + + // This is always the last event we dispatch before poll again + callback(Event::AboutToWait, &self.window_target); + + // Update the window frames and schedule redraws. + let mut wake_up = false; + for window_id in window_ids.drain(..) { + wake_up |= self.with_state(|state| match state.windows.get_mut().get_mut(&window_id) { + Some(window) => { + let refresh = window.lock().unwrap().refresh_frame(); + if refresh { + state + .window_requests + .get_mut() + .get_mut(&window_id) + .unwrap() + .redraw_requested + .store(true, Ordering::Relaxed); + } + + refresh + }, + None => false, + }); + } + + // Wakeup event loop if needed. + // + // If the user draws from the `AboutToWait` this is likely not required, however + // we can't do much about it. + if wake_up { + match &self.window_target.p { + PlatformActiveEventLoop::Wayland(window_target) => { + window_target.event_loop_awakener.ping(); + }, + #[cfg(x11_platform)] + PlatformActiveEventLoop::X(_) => unreachable!(), + } + } + + std::mem::swap(&mut self.compositor_updates, &mut compositor_updates); + std::mem::swap(&mut self.buffer_sink, &mut buffer_sink); + std::mem::swap(&mut self.window_ids, &mut window_ids); + } + + #[inline] + pub fn create_proxy(&self) -> EventLoopProxy<T> { + EventLoopProxy::new(self.user_events_sender.clone()) + } + + #[inline] + pub fn window_target(&self) -> &RootActiveEventLoop { + &self.window_target + } + + fn with_state<'a, U: 'a, F: FnOnce(&'a mut WinitState) -> U>(&'a mut self, callback: F) -> U { + let state = match &mut self.window_target.p { + PlatformActiveEventLoop::Wayland(window_target) => window_target.state.get_mut(), + #[cfg(x11_platform)] + _ => unreachable!(), + }; + + callback(state) + } + + fn loop_dispatch<D: Into<Option<std::time::Duration>>>(&mut self, timeout: D) -> IOResult<()> { + let state = match &mut self.window_target.p { + PlatformActiveEventLoop::Wayland(window_target) => window_target.state.get_mut(), + #[cfg(feature = "x11")] + _ => unreachable!(), + }; + + self.event_loop.dispatch(timeout, state).map_err(|error| { + tracing::error!("Error dispatching event loop: {}", error); + error.into() + }) + } + + fn roundtrip(&mut self) -> Result<usize, RootOsError> { + let state = match &mut self.window_target.p { + PlatformActiveEventLoop::Wayland(window_target) => window_target.state.get_mut(), + #[cfg(feature = "x11")] + _ => unreachable!(), + }; + + let mut wayland_source = self.wayland_dispatcher.as_source_mut(); + let event_queue = wayland_source.queue(); + event_queue.roundtrip(state).map_err(|error| { + os_error!(OsError::WaylandError(Arc::new(WaylandError::Dispatch(error)))) + }) + } + + fn control_flow(&self) -> ControlFlow { + self.window_target.p.control_flow() + } + + fn exiting(&self) -> bool { + self.window_target.p.exiting() + } + + fn set_exit_code(&self, code: i32) { + self.window_target.p.set_exit_code(code) + } + + fn exit_code(&self) -> Option<i32> { + self.window_target.p.exit_code() + } +} + +impl<T> AsFd for EventLoop<T> { + fn as_fd(&self) -> BorrowedFd<'_> { + self.event_loop.as_fd() + } +} + +impl<T> AsRawFd for EventLoop<T> { + fn as_raw_fd(&self) -> RawFd { + self.event_loop.as_raw_fd() + } +} + +pub struct ActiveEventLoop { + /// The event loop wakeup source. + pub event_loop_awakener: Ping, + + /// The main queue used by the event loop. + pub queue_handle: QueueHandle<WinitState>, + + /// The application's latest control_flow state + pub(crate) control_flow: Cell<ControlFlow>, + + /// The application's exit state. + pub(crate) exit: Cell<Option<i32>>, + + // TODO remove that RefCell once we can pass `&mut` in `Window::new`. + /// Winit state. + pub state: RefCell<WinitState>, + + /// Dispatcher of Wayland events. + pub wayland_dispatcher: WaylandDispatcher, + + /// Connection to the wayland server. + pub connection: Connection, +} + +impl ActiveEventLoop { + pub(crate) fn set_control_flow(&self, control_flow: ControlFlow) { + self.control_flow.set(control_flow) + } + + pub(crate) fn control_flow(&self) -> ControlFlow { + self.control_flow.get() + } + + pub(crate) fn exit(&self) { + self.exit.set(Some(0)) + } + + pub(crate) fn clear_exit(&self) { + self.exit.set(None) + } + + pub(crate) fn exiting(&self) -> bool { + self.exit.get().is_some() + } + + pub(crate) fn set_exit_code(&self, code: i32) { + self.exit.set(Some(code)) + } + + pub(crate) fn exit_code(&self) -> Option<i32> { + self.exit.get() + } + + #[inline] + pub fn listen_device_events(&self, _allowed: DeviceEvents) {} + + pub(crate) fn create_custom_cursor(&self, cursor: CustomCursorSource) -> RootCustomCursor { + RootCustomCursor { + inner: PlatformCustomCursor::Wayland(OnlyCursorImage(Arc::from(cursor.inner.0))), + } + } + + #[cfg(feature = "rwh_05")] + #[inline] + pub fn raw_display_handle_rwh_05(&self) -> rwh_05::RawDisplayHandle { + use sctk::reexports::client::Proxy; + + let mut display_handle = rwh_05::WaylandDisplayHandle::empty(); + display_handle.display = self.connection.display().id().as_ptr() as *mut _; + rwh_05::RawDisplayHandle::Wayland(display_handle) + } + + #[cfg(feature = "rwh_06")] + #[inline] + pub fn raw_display_handle_rwh_06( + &self, + ) -> Result<rwh_06::RawDisplayHandle, rwh_06::HandleError> { + use sctk::reexports::client::Proxy; + + Ok(rwh_06::WaylandDisplayHandle::new({ + let ptr = self.connection.display().id().as_ptr(); + std::ptr::NonNull::new(ptr as *mut _).expect("wl_display should never be null") + }) + .into()) + } +} + +#[derive(Debug)] +struct PumpEventNotifier { + /// Whether we're in winit or not. + control: Arc<(Mutex<PumpEventNotifierAction>, Condvar)>, + /// Waker handle for the working thread. + worker_waker: Option<OwnedFd>, + /// Thread handle. + handle: Option<JoinHandle<()>>, +} + +impl Drop for PumpEventNotifier { + fn drop(&mut self) { + // Wake-up the thread. + if let Some(worker_waker) = self.worker_waker.as_ref() { + let _ = rustix::io::write(worker_waker.as_fd(), &[0u8]); + } + *self.control.0.lock().unwrap() = PumpEventNotifierAction::Shutdown; + self.control.1.notify_one(); + + if let Some(handle) = self.handle.take() { + let _ = handle.join(); + } + } +} + +impl PumpEventNotifier { + fn spawn(connection: Connection, awakener: Ping) -> Self { + // Start from the waiting state. + let control = Arc::new((Mutex::new(PumpEventNotifierAction::Pause), Condvar::new())); + let control_thread = Arc::clone(&control); + + let (read, write) = match pipe::pipe_with(PipeFlags::CLOEXEC | PipeFlags::NONBLOCK) { + Ok((read, write)) => (read, write), + Err(_) => return Self { control, handle: None, worker_waker: None }, + }; + + let handle = + std::thread::Builder::new().name(String::from("pump_events mon")).spawn(move || { + let (lock, cvar) = &*control_thread; + 'outer: loop { + let mut wait = lock.lock().unwrap(); + while *wait == PumpEventNotifierAction::Pause { + wait = cvar.wait(wait).unwrap(); + } + + // Exit the loop when we're asked to. Given that we poll + // only once we can take the `prepare_read`, but in some cases + // it could be not possible, we may block on `join`. + if *wait == PumpEventNotifierAction::Shutdown { + break 'outer; + } + + // Wake-up the main loop and put this one back to sleep. + *wait = PumpEventNotifierAction::Pause; + drop(wait); + + while let Some(read_guard) = connection.prepare_read() { + let _ = connection.flush(); + let poll_fd = PollFd::from_borrowed_fd(connection.as_fd(), PollFlags::IN); + let pipe_poll_fd = PollFd::from_borrowed_fd(read.as_fd(), PollFlags::IN); + // Read from the `fd` before going back to poll. + if Ok(1) == rustix::io::read(read.as_fd(), &mut [0u8; 1]) { + break 'outer; + } + let _ = rustix::event::poll(&mut [poll_fd, pipe_poll_fd], -1); + // Non-blocking read the connection. + let _ = read_guard.read_without_dispatch(); + } + + awakener.ping(); + } + }); + + if let Some(err) = handle.as_ref().err() { + warn!("failed to spawn pump_events wake-up thread: {err}"); + } + + PumpEventNotifier { control, handle: handle.ok(), worker_waker: Some(write) } + } +} + +#[derive(Debug, PartialEq, Eq)] +enum PumpEventNotifierAction { + /// Monitor the wayland queue. + Monitor, + /// Pause monitoring. + Pause, + /// Shutdown the thread. + Shutdown, +} diff --git a/app/vendor/rune/vendor/winit/src/platform_impl/linux/wayland/event_loop/proxy.rs b/app/vendor/rune/vendor/winit/src/platform_impl/linux/wayland/event_loop/proxy.rs new file mode 100644 index 0000000..9dc7d99 --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/platform_impl/linux/wayland/event_loop/proxy.rs @@ -0,0 +1,28 @@ +//! An event loop proxy. + +use std::sync::mpsc::SendError; + +use sctk::reexports::calloop::channel::Sender; + +use crate::event_loop::EventLoopClosed; + +/// A handle that can be sent across the threads and used to wake up the `EventLoop`. +pub struct EventLoopProxy<T: 'static> { + user_events_sender: Sender<T>, +} + +impl<T: 'static> Clone for EventLoopProxy<T> { + fn clone(&self) -> Self { + EventLoopProxy { user_events_sender: self.user_events_sender.clone() } + } +} + +impl<T: 'static> EventLoopProxy<T> { + pub fn new(user_events_sender: Sender<T>) -> Self { + Self { user_events_sender } + } + + pub fn send_event(&self, event: T) -> Result<(), EventLoopClosed<T>> { + self.user_events_sender.send(event).map_err(|SendError(error)| EventLoopClosed(error)) + } +} diff --git a/app/vendor/rune/vendor/winit/src/platform_impl/linux/wayland/event_loop/sink.rs b/app/vendor/rune/vendor/winit/src/platform_impl/linux/wayland/event_loop/sink.rs new file mode 100644 index 0000000..e506b4a --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/platform_impl/linux/wayland/event_loop/sink.rs @@ -0,0 +1,53 @@ +//! An event loop's sink to deliver events from the Wayland event callbacks. + +use std::vec::Drain; + +use crate::event::{DeviceEvent, DeviceId as RootDeviceId, Event, WindowEvent}; +use crate::platform_impl::platform::DeviceId as PlatformDeviceId; +use crate::window::WindowId as RootWindowId; + +use super::{DeviceId, WindowId}; + +/// An event loop's sink to deliver events from the Wayland event callbacks +/// to the winit's user. +#[derive(Default)] +pub struct EventSink { + pub window_events: Vec<Event<()>>, +} + +impl EventSink { + pub fn new() -> Self { + Default::default() + } + + /// Return `true` if there're pending events. + #[inline] + pub fn is_empty(&self) -> bool { + self.window_events.is_empty() + } + + /// Add new device event to a queue. + #[inline] + pub fn push_device_event(&mut self, event: DeviceEvent, device_id: DeviceId) { + self.window_events.push(Event::DeviceEvent { + event, + device_id: RootDeviceId(PlatformDeviceId::Wayland(device_id)), + }); + } + + /// Add new window event to a queue. + #[inline] + pub fn push_window_event(&mut self, event: WindowEvent, window_id: WindowId) { + self.window_events.push(Event::WindowEvent { event, window_id: RootWindowId(window_id) }); + } + + #[inline] + pub fn append(&mut self, other: &mut Self) { + self.window_events.append(&mut other.window_events); + } + + #[inline] + pub fn drain(&mut self) -> Drain<'_, Event<()>> { + self.window_events.drain(..) + } +} diff --git a/app/vendor/rune/vendor/winit/src/platform_impl/linux/wayland/mod.rs b/app/vendor/rune/vendor/winit/src/platform_impl/linux/wayland/mod.rs new file mode 100644 index 0000000..63052b7 --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/platform_impl/linux/wayland/mod.rs @@ -0,0 +1,85 @@ +//! Winit's Wayland backend. + +use std::fmt::Display; +use std::sync::Arc; + +use sctk::reexports::client::globals::{BindError, GlobalError}; +use sctk::reexports::client::protocol::wl_surface::WlSurface; +use sctk::reexports::client::{self, ConnectError, DispatchError, Proxy}; + +pub(super) use crate::cursor::OnlyCursorImage as CustomCursor; +use crate::dpi::{LogicalSize, PhysicalSize}; +pub use crate::platform_impl::platform::{OsError, WindowId}; +pub use event_loop::{ActiveEventLoop, EventLoop, EventLoopProxy}; +pub use output::{MonitorHandle, VideoModeHandle}; +pub use window::Window; + +mod event_loop; +mod output; +mod seat; +mod state; +mod types; +mod window; + +#[derive(Debug)] +pub enum WaylandError { + /// Error connecting to the socket. + Connection(ConnectError), + + /// Error binding the global. + Global(GlobalError), + + // Bind error. + Bind(BindError), + + /// Error during the dispatching the event queue. + Dispatch(DispatchError), + + /// Calloop error. + Calloop(calloop::Error), + + /// Wayland + Wire(client::backend::WaylandError), +} + +impl Display for WaylandError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + WaylandError::Connection(error) => error.fmt(f), + WaylandError::Global(error) => error.fmt(f), + WaylandError::Bind(error) => error.fmt(f), + WaylandError::Dispatch(error) => error.fmt(f), + WaylandError::Calloop(error) => error.fmt(f), + WaylandError::Wire(error) => error.fmt(f), + } + } +} + +impl From<WaylandError> for OsError { + fn from(value: WaylandError) -> Self { + Self::WaylandError(Arc::new(value)) + } +} + +/// Dummy device id, since Wayland doesn't have device events. +#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub struct DeviceId; + +impl DeviceId { + pub const fn dummy() -> Self { + DeviceId + } +} + +/// Get the WindowId out of the surface. +#[inline] +fn make_wid(surface: &WlSurface) -> WindowId { + WindowId(surface.id().as_ptr() as u64) +} + +/// The default routine does floor, but we need round on Wayland. +fn logical_to_physical_rounded(size: LogicalSize<u32>, scale_factor: f64) -> PhysicalSize<u32> { + let width = size.width as f64 * scale_factor; + let height = size.height as f64 * scale_factor; + (width.round(), height.round()).into() +} diff --git a/app/vendor/rune/vendor/winit/src/platform_impl/linux/wayland/output.rs b/app/vendor/rune/vendor/winit/src/platform_impl/linux/wayland/output.rs new file mode 100644 index 0000000..ae6c1b0 --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/platform_impl/linux/wayland/output.rs @@ -0,0 +1,163 @@ +use sctk::reexports::client::protocol::wl_output::WlOutput; +use sctk::reexports::client::Proxy; + +use sctk::output::OutputData; + +use crate::dpi::{LogicalPosition, PhysicalPosition, PhysicalSize}; +use crate::platform_impl::platform::VideoModeHandle as PlatformVideoModeHandle; + +use super::event_loop::ActiveEventLoop; + +impl ActiveEventLoop { + #[inline] + pub fn available_monitors(&self) -> impl Iterator<Item = MonitorHandle> { + self.state.borrow().output_state.outputs().map(MonitorHandle::new) + } + + #[inline] + pub fn primary_monitor(&self) -> Option<MonitorHandle> { + // There's no primary monitor on Wayland. + None + } +} + +#[derive(Clone, Debug)] +pub struct MonitorHandle { + pub(crate) proxy: WlOutput, +} + +impl MonitorHandle { + #[inline] + pub(crate) fn new(proxy: WlOutput) -> Self { + Self { proxy } + } + + #[inline] + pub fn name(&self) -> Option<String> { + let output_data = self.proxy.data::<OutputData>().unwrap(); + output_data.with_output_info(|info| info.name.clone()) + } + + #[inline] + pub fn native_identifier(&self) -> u32 { + let output_data = self.proxy.data::<OutputData>().unwrap(); + output_data.with_output_info(|info| info.id) + } + + #[inline] + pub fn size(&self) -> PhysicalSize<u32> { + let output_data = self.proxy.data::<OutputData>().unwrap(); + let dimensions = output_data.with_output_info(|info| { + info.modes.iter().find_map(|mode| mode.current.then_some(mode.dimensions)) + }); + + match dimensions { + Some((width, height)) => (width as u32, height as u32), + _ => (0, 0), + } + .into() + } + + #[inline] + pub fn position(&self) -> PhysicalPosition<i32> { + let output_data = self.proxy.data::<OutputData>().unwrap(); + output_data.with_output_info(|info| { + info.logical_position.map_or_else( + || { + LogicalPosition::<i32>::from(info.location) + .to_physical(info.scale_factor as f64) + }, + |logical_position| { + LogicalPosition::<i32>::from(logical_position) + .to_physical(info.scale_factor as f64) + }, + ) + }) + } + + #[inline] + pub fn refresh_rate_millihertz(&self) -> Option<u32> { + let output_data = self.proxy.data::<OutputData>().unwrap(); + output_data.with_output_info(|info| { + info.modes.iter().find_map(|mode| mode.current.then_some(mode.refresh_rate as u32)) + }) + } + + #[inline] + pub fn scale_factor(&self) -> i32 { + let output_data = self.proxy.data::<OutputData>().unwrap(); + output_data.scale_factor() + } + + #[inline] + pub fn video_modes(&self) -> impl Iterator<Item = PlatformVideoModeHandle> { + let output_data = self.proxy.data::<OutputData>().unwrap(); + let modes = output_data.with_output_info(|info| info.modes.clone()); + + let monitor = self.clone(); + + modes.into_iter().map(move |mode| { + PlatformVideoModeHandle::Wayland(VideoModeHandle { + size: (mode.dimensions.0 as u32, mode.dimensions.1 as u32).into(), + refresh_rate_millihertz: mode.refresh_rate as u32, + bit_depth: 32, + monitor: monitor.clone(), + }) + }) + } +} + +impl PartialEq for MonitorHandle { + fn eq(&self, other: &Self) -> bool { + self.native_identifier() == other.native_identifier() + } +} + +impl Eq for MonitorHandle {} + +impl PartialOrd for MonitorHandle { + fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> { + Some(self.cmp(other)) + } +} + +impl Ord for MonitorHandle { + fn cmp(&self, other: &Self) -> std::cmp::Ordering { + self.native_identifier().cmp(&other.native_identifier()) + } +} + +impl std::hash::Hash for MonitorHandle { + fn hash<H: std::hash::Hasher>(&self, state: &mut H) { + self.native_identifier().hash(state); + } +} + +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub struct VideoModeHandle { + pub(crate) size: PhysicalSize<u32>, + pub(crate) bit_depth: u16, + pub(crate) refresh_rate_millihertz: u32, + pub(crate) monitor: MonitorHandle, +} + +impl VideoModeHandle { + #[inline] + pub fn size(&self) -> PhysicalSize<u32> { + self.size + } + + #[inline] + pub fn bit_depth(&self) -> u16 { + self.bit_depth + } + + #[inline] + pub fn refresh_rate_millihertz(&self) -> u32 { + self.refresh_rate_millihertz + } + + pub fn monitor(&self) -> MonitorHandle { + self.monitor.clone() + } +} diff --git a/app/vendor/rune/vendor/winit/src/platform_impl/linux/wayland/seat/keyboard/mod.rs b/app/vendor/rune/vendor/winit/src/platform_impl/linux/wayland/seat/keyboard/mod.rs new file mode 100644 index 0000000..f84c386 --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/platform_impl/linux/wayland/seat/keyboard/mod.rs @@ -0,0 +1,380 @@ +//! The keyboard input handling. + +use std::sync::Mutex; +use std::time::Duration; + +use calloop::timer::{TimeoutAction, Timer}; +use calloop::{LoopHandle, RegistrationToken}; +use tracing::warn; + +use sctk::reexports::client::protocol::wl_keyboard::{ + Event as WlKeyboardEvent, KeyState as WlKeyState, KeymapFormat as WlKeymapFormat, WlKeyboard, +}; +use sctk::reexports::client::protocol::wl_seat::WlSeat; +use sctk::reexports::client::{Connection, Dispatch, Proxy, QueueHandle, WEnum}; + +use crate::event::{ElementState, WindowEvent}; +use crate::keyboard::ModifiersState; + +use crate::platform_impl::common::xkb::Context; +use crate::platform_impl::wayland::event_loop::sink::EventSink; +use crate::platform_impl::wayland::state::WinitState; +use crate::platform_impl::wayland::{self, DeviceId, WindowId}; + +impl Dispatch<WlKeyboard, KeyboardData, WinitState> for WinitState { + fn event( + state: &mut WinitState, + wl_keyboard: &WlKeyboard, + event: <WlKeyboard as Proxy>::Event, + data: &KeyboardData, + _: &Connection, + _: &QueueHandle<WinitState>, + ) { + let seat_state = match state.seats.get_mut(&data.seat.id()) { + Some(seat_state) => seat_state, + None => { + warn!("Received keyboard event {event:?} without seat"); + return; + }, + }; + let keyboard_state = match seat_state.keyboard_state.as_mut() { + Some(keyboard_state) => keyboard_state, + None => { + warn!("Received keyboard event {event:?} without keyboard"); + return; + }, + }; + + match event { + WlKeyboardEvent::Keymap { format, fd, size } => match format { + WEnum::Value(format) => match format { + WlKeymapFormat::NoKeymap => { + warn!("non-xkb compatible keymap") + }, + WlKeymapFormat::XkbV1 => { + let context = &mut keyboard_state.xkb_context; + context.set_keymap_from_fd(fd, size as usize); + }, + _ => unreachable!(), + }, + WEnum::Unknown(value) => { + warn!("unknown keymap format 0x{:x}", value) + }, + }, + WlKeyboardEvent::Enter { surface, .. } => { + let window_id = wayland::make_wid(&surface); + + // Mark the window as focused. + let was_unfocused = match state.windows.get_mut().get(&window_id) { + Some(window) => { + let mut window = window.lock().unwrap(); + let was_unfocused = !window.has_focus(); + window.add_seat_focus(data.seat.id()); + was_unfocused + }, + None => return, + }; + + // Drop the repeat, if there were any. + keyboard_state.current_repeat = None; + if let Some(token) = keyboard_state.repeat_token.take() { + keyboard_state.loop_handle.remove(token); + } + + *data.window_id.lock().unwrap() = Some(window_id); + + // The keyboard focus is considered as general focus. + if was_unfocused { + state.events_sink.push_window_event(WindowEvent::Focused(true), window_id); + } + + // HACK: this is just for GNOME not fixing their ordering issue of modifiers. + if std::mem::take(&mut seat_state.modifiers_pending) { + state.events_sink.push_window_event( + WindowEvent::ModifiersChanged(seat_state.modifiers.into()), + window_id, + ); + } + }, + WlKeyboardEvent::Leave { surface, .. } => { + let window_id = wayland::make_wid(&surface); + + // NOTE: we should drop the repeat regardless whether it was for the present + // window of for the window which just went gone. + keyboard_state.current_repeat = None; + if let Some(token) = keyboard_state.repeat_token.take() { + keyboard_state.loop_handle.remove(token); + } + + // NOTE: The check whether the window exists is essential as we might get a + // nil surface, regardless of what protocol says. + let focused = match state.windows.get_mut().get(&window_id) { + Some(window) => { + let mut window = window.lock().unwrap(); + window.remove_seat_focus(&data.seat.id()); + window.has_focus() + }, + None => return, + }; + + // We don't need to update it above, because the next `Enter` will overwrite + // anyway. + *data.window_id.lock().unwrap() = None; + + if !focused { + // Notify that no modifiers are being pressed. + state.events_sink.push_window_event( + WindowEvent::ModifiersChanged(ModifiersState::empty().into()), + window_id, + ); + + state.events_sink.push_window_event(WindowEvent::Focused(false), window_id); + } + }, + WlKeyboardEvent::Key { key, state: WEnum::Value(WlKeyState::Pressed), .. } => { + let key = key + 8; + + key_input( + keyboard_state, + &mut state.events_sink, + data, + key, + ElementState::Pressed, + false, + ); + + let delay = match keyboard_state.repeat_info { + RepeatInfo::Repeat { delay, .. } => delay, + RepeatInfo::Disable => return, + }; + + if !keyboard_state.xkb_context.keymap_mut().unwrap().key_repeats(key) { + return; + } + + keyboard_state.current_repeat = Some(key); + + // NOTE terminate ongoing timer and start a new timer. + + if let Some(token) = keyboard_state.repeat_token.take() { + keyboard_state.loop_handle.remove(token); + } + + let timer = Timer::from_duration(delay); + let wl_keyboard = wl_keyboard.clone(); + keyboard_state.repeat_token = keyboard_state + .loop_handle + .insert_source(timer, move |_, _, state| { + // Required to handle the wakeups from the repeat sources. + state.dispatched_events = true; + + let data = wl_keyboard.data::<KeyboardData>().unwrap(); + let seat_state = match state.seats.get_mut(&data.seat.id()) { + Some(seat_state) => seat_state, + None => return TimeoutAction::Drop, + }; + + let keyboard_state = match seat_state.keyboard_state.as_mut() { + Some(keyboard_state) => keyboard_state, + None => return TimeoutAction::Drop, + }; + + // NOTE: The removed on event source is batched, but key change to `None` + // is instant. + let repeat_keycode = match keyboard_state.current_repeat { + Some(repeat_keycode) => repeat_keycode, + None => return TimeoutAction::Drop, + }; + + key_input( + keyboard_state, + &mut state.events_sink, + data, + repeat_keycode, + ElementState::Pressed, + true, + ); + + // NOTE: the gap could change dynamically while repeat is going. + match keyboard_state.repeat_info { + RepeatInfo::Repeat { gap, .. } => TimeoutAction::ToDuration(gap), + RepeatInfo::Disable => TimeoutAction::Drop, + } + }) + .ok(); + }, + WlKeyboardEvent::Key { key, state: WEnum::Value(WlKeyState::Released), .. } => { + let key = key + 8; + + key_input( + keyboard_state, + &mut state.events_sink, + data, + key, + ElementState::Released, + false, + ); + + if keyboard_state.repeat_info != RepeatInfo::Disable + && keyboard_state.xkb_context.keymap_mut().unwrap().key_repeats(key) + && Some(key) == keyboard_state.current_repeat + { + keyboard_state.current_repeat = None; + if let Some(token) = keyboard_state.repeat_token.take() { + keyboard_state.loop_handle.remove(token); + } + } + }, + WlKeyboardEvent::Modifiers { + mods_depressed, mods_latched, mods_locked, group, .. + } => { + let xkb_context = &mut keyboard_state.xkb_context; + let xkb_state = match xkb_context.state_mut() { + Some(state) => state, + None => return, + }; + + xkb_state.update_modifiers(mods_depressed, mods_latched, mods_locked, 0, 0, group); + seat_state.modifiers = xkb_state.modifiers().into(); + + // HACK: part of the workaround from `WlKeyboardEvent::Enter`. + let window_id = match *data.window_id.lock().unwrap() { + Some(window_id) => window_id, + None => { + seat_state.modifiers_pending = true; + return; + }, + }; + + state.events_sink.push_window_event( + WindowEvent::ModifiersChanged(seat_state.modifiers.into()), + window_id, + ); + }, + WlKeyboardEvent::RepeatInfo { rate, delay } => { + keyboard_state.repeat_info = if rate == 0 { + // Stop the repeat once we get a disable event. + keyboard_state.current_repeat = None; + if let Some(repeat_token) = keyboard_state.repeat_token.take() { + keyboard_state.loop_handle.remove(repeat_token); + } + RepeatInfo::Disable + } else { + let gap = Duration::from_micros(1_000_000 / rate as u64); + let delay = Duration::from_millis(delay as u64); + RepeatInfo::Repeat { gap, delay } + }; + }, + _ => unreachable!(), + } + } +} + +/// The state of the keyboard on the current seat. +#[derive(Debug)] +pub struct KeyboardState { + /// The underlying WlKeyboard. + pub keyboard: WlKeyboard, + + /// Loop handle to handle key repeat. + pub loop_handle: LoopHandle<'static, WinitState>, + + /// The state of the keyboard. + pub xkb_context: Context, + + /// The information about the repeat rate obtained from the compositor. + pub repeat_info: RepeatInfo, + + /// The token of the current handle inside the calloop's event loop. + pub repeat_token: Option<RegistrationToken>, + + /// The current repeat raw key. + pub current_repeat: Option<u32>, +} + +impl KeyboardState { + pub fn new(keyboard: WlKeyboard, loop_handle: LoopHandle<'static, WinitState>) -> Self { + Self { + keyboard, + loop_handle, + xkb_context: Context::new().unwrap(), + repeat_info: RepeatInfo::default(), + repeat_token: None, + current_repeat: None, + } + } +} + +impl Drop for KeyboardState { + fn drop(&mut self) { + if self.keyboard.version() >= 3 { + self.keyboard.release(); + } + + if let Some(token) = self.repeat_token.take() { + self.loop_handle.remove(token); + } + } +} + +/// The rate at which a pressed key is repeated. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum RepeatInfo { + /// Keys will be repeated at the specified rate and delay. + Repeat { + /// The time between the key repeats. + gap: Duration, + + /// Delay (in milliseconds) between a key press and the start of repetition. + delay: Duration, + }, + + /// Keys should not be repeated. + Disable, +} + +impl Default for RepeatInfo { + /// The default repeat rate is 25 keys per second with the delay of 200ms. + /// + /// The values are picked based on the default in various compositors and Xorg. + fn default() -> Self { + Self::Repeat { gap: Duration::from_millis(40), delay: Duration::from_millis(200) } + } +} + +/// Keyboard user data. +#[derive(Debug)] +pub struct KeyboardData { + /// The currently focused window surface. Could be `None` on bugged compositors, like mutter. + window_id: Mutex<Option<WindowId>>, + + /// The seat used to create this keyboard. + seat: WlSeat, +} + +impl KeyboardData { + pub fn new(seat: WlSeat) -> Self { + Self { window_id: Default::default(), seat } + } +} + +fn key_input( + keyboard_state: &mut KeyboardState, + event_sink: &mut EventSink, + data: &KeyboardData, + keycode: u32, + state: ElementState, + repeat: bool, +) { + let window_id = match *data.window_id.lock().unwrap() { + Some(window_id) => window_id, + None => return, + }; + + let device_id = crate::event::DeviceId(crate::platform_impl::DeviceId::Wayland(DeviceId)); + if let Some(mut key_context) = keyboard_state.xkb_context.key_context() { + let event = key_context.process_key_event(keycode, state, repeat); + let event = WindowEvent::KeyboardInput { device_id, event, is_synthetic: false }; + event_sink.push_window_event(event, window_id); + } +} diff --git a/app/vendor/rune/vendor/winit/src/platform_impl/linux/wayland/seat/mod.rs b/app/vendor/rune/vendor/winit/src/platform_impl/linux/wayland/seat/mod.rs new file mode 100644 index 0000000..eaecd93 --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/platform_impl/linux/wayland/seat/mod.rs @@ -0,0 +1,235 @@ +//! Seat handling. + +use std::sync::Arc; + +use ahash::AHashMap; +use tracing::warn; + +use sctk::reexports::client::backend::ObjectId; +use sctk::reexports::client::protocol::wl_seat::WlSeat; +use sctk::reexports::client::protocol::wl_touch::WlTouch; +use sctk::reexports::client::{Connection, Proxy, QueueHandle}; +use sctk::reexports::protocols::wp::relative_pointer::zv1::client::zwp_relative_pointer_v1::ZwpRelativePointerV1; +use sctk::reexports::protocols::wp::text_input::zv3::client::zwp_text_input_v3::ZwpTextInputV3; + +use sctk::seat::pointer::{ThemeSpec, ThemedPointer}; +use sctk::seat::{Capability as SeatCapability, SeatHandler, SeatState}; + +use crate::event::WindowEvent; +use crate::keyboard::ModifiersState; +use crate::platform_impl::wayland::state::WinitState; + +mod keyboard; +mod pointer; +mod text_input; +mod touch; + +pub use pointer::relative_pointer::RelativePointerState; +pub use pointer::{PointerConstraintsState, WinitPointerData, WinitPointerDataExt}; +pub use text_input::{TextInputState, ZwpTextInputV3Ext}; + +use keyboard::{KeyboardData, KeyboardState}; +use text_input::TextInputData; +use touch::TouchPoint; + +#[derive(Debug, Default)] +pub struct WinitSeatState { + /// The pointer bound on the seat. + pointer: Option<Arc<ThemedPointer<WinitPointerData>>>, + + /// The touch bound on the seat. + touch: Option<WlTouch>, + + /// The mapping from touched points to the surfaces they're present. + touch_map: AHashMap<i32, TouchPoint>, + + /// The text input bound on the seat. + text_input: Option<Arc<ZwpTextInputV3>>, + + /// The relative pointer bound on the seat. + relative_pointer: Option<ZwpRelativePointerV1>, + + /// The keyboard bound on the seat. + keyboard_state: Option<KeyboardState>, + + /// The current modifiers state on the seat. + modifiers: ModifiersState, + + /// Whether we have pending modifiers. + modifiers_pending: bool, +} + +impl WinitSeatState { + pub fn new() -> Self { + Default::default() + } +} + +impl SeatHandler for WinitState { + fn seat_state(&mut self) -> &mut SeatState { + &mut self.seat_state + } + + fn new_capability( + &mut self, + _: &Connection, + queue_handle: &QueueHandle<Self>, + seat: WlSeat, + capability: SeatCapability, + ) { + let seat_state = match self.seats.get_mut(&seat.id()) { + Some(seat_state) => seat_state, + None => { + warn!("Received wl_seat::new_capability for unknown seat"); + return; + }, + }; + + match capability { + SeatCapability::Touch if seat_state.touch.is_none() => { + seat_state.touch = self.seat_state.get_touch(queue_handle, &seat).ok(); + }, + SeatCapability::Keyboard if seat_state.keyboard_state.is_none() => { + let keyboard = seat.get_keyboard(queue_handle, KeyboardData::new(seat.clone())); + seat_state.keyboard_state = + Some(KeyboardState::new(keyboard, self.loop_handle.clone())); + }, + SeatCapability::Pointer if seat_state.pointer.is_none() => { + let surface = self.compositor_state.create_surface(queue_handle); + let viewport = self + .viewporter_state + .as_ref() + .map(|state| state.get_viewport(&surface, queue_handle)); + let surface_id = surface.id(); + let pointer_data = WinitPointerData::new(seat.clone(), viewport); + let themed_pointer = self + .seat_state + .get_pointer_with_theme_and_data( + queue_handle, + &seat, + self.shm.wl_shm(), + surface, + ThemeSpec::System, + pointer_data, + ) + .expect("failed to create pointer with present capability."); + + seat_state.relative_pointer = self.relative_pointer.as_ref().map(|manager| { + manager.get_relative_pointer( + themed_pointer.pointer(), + queue_handle, + sctk::globals::GlobalData, + ) + }); + + let themed_pointer = Arc::new(themed_pointer); + + // Register cursor surface. + self.pointer_surfaces.insert(surface_id, themed_pointer.clone()); + + seat_state.pointer = Some(themed_pointer); + }, + _ => (), + } + + if let Some(text_input_state) = + seat_state.text_input.is_none().then_some(self.text_input_state.as_ref()).flatten() + { + seat_state.text_input = Some(Arc::new(text_input_state.get_text_input( + &seat, + queue_handle, + TextInputData::default(), + ))); + } + } + + fn remove_capability( + &mut self, + _: &Connection, + _queue_handle: &QueueHandle<Self>, + seat: WlSeat, + capability: SeatCapability, + ) { + let seat_state = match self.seats.get_mut(&seat.id()) { + Some(seat_state) => seat_state, + None => { + warn!("Received wl_seat::remove_capability for unknown seat"); + return; + }, + }; + + if let Some(text_input) = seat_state.text_input.take() { + text_input.destroy(); + } + + match capability { + SeatCapability::Touch => { + if let Some(touch) = seat_state.touch.take() { + if touch.version() >= 3 { + touch.release(); + } + } + }, + SeatCapability::Pointer => { + if let Some(relative_pointer) = seat_state.relative_pointer.take() { + relative_pointer.destroy(); + } + + if let Some(pointer) = seat_state.pointer.take() { + let pointer_data = pointer.pointer().winit_data(); + + // Remove the cursor from the mapping. + let surface_id = pointer.surface().id(); + let _ = self.pointer_surfaces.remove(&surface_id); + + // Remove the inner locks/confines before dropping the pointer. + pointer_data.unlock_pointer(); + pointer_data.unconfine_pointer(); + + if pointer.pointer().version() >= 3 { + pointer.pointer().release(); + } + } + }, + SeatCapability::Keyboard => { + seat_state.keyboard_state = None; + self.on_keyboard_destroy(&seat.id()); + }, + _ => (), + } + } + + fn new_seat( + &mut self, + _connection: &Connection, + _queue_handle: &QueueHandle<Self>, + seat: WlSeat, + ) { + self.seats.insert(seat.id(), WinitSeatState::new()); + } + + fn remove_seat( + &mut self, + _connection: &Connection, + _queue_handle: &QueueHandle<Self>, + seat: WlSeat, + ) { + let _ = self.seats.remove(&seat.id()); + self.on_keyboard_destroy(&seat.id()); + } +} + +impl WinitState { + fn on_keyboard_destroy(&mut self, seat: &ObjectId) { + for (window_id, window) in self.windows.get_mut() { + let mut window = window.lock().unwrap(); + let had_focus = window.has_focus(); + window.remove_seat_focus(seat); + if had_focus != window.has_focus() { + self.events_sink.push_window_event(WindowEvent::Focused(false), *window_id); + } + } + } +} + +sctk::delegate_seat!(WinitState); diff --git a/app/vendor/rune/vendor/winit/src/platform_impl/linux/wayland/seat/pointer/mod.rs b/app/vendor/rune/vendor/winit/src/platform_impl/linux/wayland/seat/pointer/mod.rs new file mode 100644 index 0000000..88a3e5b --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/platform_impl/linux/wayland/seat/pointer/mod.rs @@ -0,0 +1,511 @@ +//! The pointer events. + +use std::ops::Deref; +use std::sync::{Arc, Mutex}; +use std::time::Duration; + +use tracing::warn; + +use sctk::reexports::client::delegate_dispatch; +use sctk::reexports::client::protocol::wl_pointer::WlPointer; +use sctk::reexports::client::protocol::wl_seat::WlSeat; +use sctk::reexports::client::protocol::wl_surface::WlSurface; +use sctk::reexports::client::{Connection, Proxy, QueueHandle, Dispatch}; +use sctk::reexports::protocols::wp::pointer_constraints::zv1::client::zwp_confined_pointer_v1::ZwpConfinedPointerV1; +use sctk::reexports::protocols::wp::pointer_constraints::zv1::client::zwp_locked_pointer_v1::ZwpLockedPointerV1; +use sctk::reexports::protocols::wp::cursor_shape::v1::client::wp_cursor_shape_device_v1::WpCursorShapeDeviceV1; +use sctk::reexports::protocols::wp::cursor_shape::v1::client::wp_cursor_shape_manager_v1::WpCursorShapeManagerV1; +use sctk::reexports::protocols::wp::pointer_constraints::zv1::client::zwp_pointer_constraints_v1::{Lifetime, ZwpPointerConstraintsV1}; +use sctk::reexports::client::globals::{BindError, GlobalList}; +use sctk::reexports::csd_frame::FrameClick; +use sctk::reexports::protocols::wp::viewporter::client::wp_viewport::WpViewport; + +use sctk::compositor::SurfaceData; +use sctk::globals::GlobalData; +use sctk::seat::pointer::{ + PointerData, PointerDataExt, PointerEvent, PointerEventKind, PointerHandler, +}; +use sctk::seat::SeatState; + +use crate::dpi::{LogicalPosition, PhysicalPosition}; +use crate::event::{ElementState, MouseButton, MouseScrollDelta, TouchPhase, WindowEvent}; + +use crate::platform_impl::wayland::state::WinitState; +use crate::platform_impl::wayland::{self, DeviceId, WindowId}; + +pub mod relative_pointer; + +impl PointerHandler for WinitState { + fn pointer_frame( + &mut self, + connection: &Connection, + _: &QueueHandle<Self>, + pointer: &WlPointer, + events: &[PointerEvent], + ) { + let seat = pointer.winit_data().seat(); + let seat_state = match self.seats.get(&seat.id()) { + Some(seat_state) => seat_state, + None => { + warn!("Received pointer event without seat"); + return; + }, + }; + + let themed_pointer = match seat_state.pointer.as_ref() { + Some(pointer) => pointer, + None => { + warn!("Received pointer event without pointer"); + return; + }, + }; + + let device_id = crate::event::DeviceId(crate::platform_impl::DeviceId::Wayland(DeviceId)); + + for event in events { + let surface = &event.surface; + + // The parent surface. + let parent_surface = match event.surface.data::<SurfaceData>() { + Some(data) => data.parent_surface().unwrap_or(surface), + None => continue, + }; + + let window_id = wayland::make_wid(parent_surface); + + // Ensure that window exists. + let mut window = match self.windows.get_mut().get_mut(&window_id) { + Some(window) => window.lock().unwrap(), + None => continue, + }; + + let scale_factor = window.scale_factor(); + let position: PhysicalPosition<f64> = + LogicalPosition::new(event.position.0, event.position.1).to_physical(scale_factor); + + match event.kind { + // Pointer movements on decorations. + PointerEventKind::Enter { .. } | PointerEventKind::Motion { .. } + if parent_surface != surface => + { + if let Some(icon) = window.frame_point_moved( + seat, + surface, + Duration::ZERO, + event.position.0, + event.position.1, + ) { + let _ = themed_pointer.set_cursor(connection, icon); + } + }, + PointerEventKind::Leave { .. } if parent_surface != surface => { + window.frame_point_left(); + }, + ref kind @ PointerEventKind::Press { button, serial, time } + | ref kind @ PointerEventKind::Release { button, serial, time } + if parent_surface != surface => + { + let click = match wayland_button_to_winit(button) { + MouseButton::Left => FrameClick::Normal, + MouseButton::Right => FrameClick::Alternate, + _ => continue, + }; + let pressed = matches!(kind, PointerEventKind::Press { .. }); + + // Emulate click on the frame. + window.frame_click( + click, + pressed, + seat, + serial, + Duration::from_millis(time as u64), + window_id, + &mut self.window_compositor_updates, + ); + }, + // Regular events on the main surface. + PointerEventKind::Enter { .. } => { + self.events_sink + .push_window_event(WindowEvent::CursorEntered { device_id }, window_id); + + window.pointer_entered(Arc::downgrade(themed_pointer)); + + // Set the currently focused surface. + pointer.winit_data().inner.lock().unwrap().surface = Some(window_id); + + self.events_sink.push_window_event( + WindowEvent::CursorMoved { device_id, position }, + window_id, + ); + }, + PointerEventKind::Leave { .. } => { + window.pointer_left(Arc::downgrade(themed_pointer)); + + // Remove the active surface. + pointer.winit_data().inner.lock().unwrap().surface = None; + + self.events_sink + .push_window_event(WindowEvent::CursorLeft { device_id }, window_id); + }, + PointerEventKind::Motion { .. } => { + self.events_sink.push_window_event( + WindowEvent::CursorMoved { device_id, position }, + window_id, + ); + }, + ref kind @ PointerEventKind::Press { button, serial, .. } + | ref kind @ PointerEventKind::Release { button, serial, .. } => { + // Update the last button serial. + pointer.winit_data().inner.lock().unwrap().latest_button_serial = serial; + + let button = wayland_button_to_winit(button); + let state = if matches!(kind, PointerEventKind::Press { .. }) { + ElementState::Pressed + } else { + ElementState::Released + }; + self.events_sink.push_window_event( + WindowEvent::MouseInput { device_id, state, button }, + window_id, + ); + }, + PointerEventKind::Axis { horizontal, vertical, source, .. } => { + // Get the current phase. + let mut pointer_data = pointer.winit_data().inner.lock().unwrap(); + + let has_discrete_scroll = horizontal.discrete != 0 || vertical.discrete != 0; + + // Figure out what to do about start/ended phases here. + // + // Figure out how to deal with `Started`. Also the `Ended` is not guaranteed + // to be sent for mouse wheels. + let phase = if horizontal.stop || vertical.stop { + TouchPhase::Ended + } else { + match pointer_data.phase { + // Discrete scroll only results in moved events. + _ if has_discrete_scroll => TouchPhase::Moved, + TouchPhase::Started | TouchPhase::Moved => TouchPhase::Moved, + _ => TouchPhase::Started, + } + }; + + // Update the phase. + pointer_data.phase = phase; + + // Mice events have both pixel and discrete delta's at the same time. So prefer + // the discrete values if they are present. + let delta = if has_discrete_scroll { + // NOTE: Wayland sign convention is the inverse of winit. + MouseScrollDelta::LineDelta( + (-horizontal.discrete) as f32, + (-vertical.discrete) as f32, + ) + } else { + // NOTE: Wayland sign convention is the inverse of winit. + use sctk::reexports::client::protocol::wl_pointer::AxisSource; + // Chromium 152, wayland_pointer.cc: OnAxis converts surface units by + // kWheelDelta / kAxisValueScale. Only finger and continuous sources use + // this gain here: a wheel can send axis-only frames between detents. + const FINGER_POINTS_PER_AXIS_UNIT: f64 = 120.0 / 10.0; + let gain = match source { + Some(AxisSource::Finger | AxisSource::Continuous) => FINGER_POINTS_PER_AXIS_UNIT, + _ => 1.0, + }; + MouseScrollDelta::PixelDelta( + LogicalPosition::new(-horizontal.absolute * gain, -vertical.absolute * gain) + .to_physical(scale_factor), + ) + }; + + self.events_sink.push_window_event( + WindowEvent::MouseWheel { device_id, delta, phase }, + window_id, + ) + }, + } + } + } +} + +#[derive(Debug)] +pub struct WinitPointerData { + /// The inner winit data associated with the pointer. + inner: Mutex<WinitPointerDataInner>, + + /// The data required by the sctk. + sctk_data: PointerData, + + /// Viewport for fractional cursor. + viewport: Option<WpViewport>, +} + +impl WinitPointerData { + pub fn new(seat: WlSeat, viewport: Option<WpViewport>) -> Self { + Self { + inner: Mutex::new(WinitPointerDataInner::default()), + sctk_data: PointerData::new(seat), + viewport, + } + } + + pub fn lock_pointer( + &self, + pointer_constraints: &PointerConstraintsState, + surface: &WlSurface, + pointer: &WlPointer, + queue_handle: &QueueHandle<WinitState>, + ) { + let mut inner = self.inner.lock().unwrap(); + if inner.locked_pointer.is_none() { + inner.locked_pointer = Some(pointer_constraints.lock_pointer( + surface, + pointer, + None, + Lifetime::Persistent, + queue_handle, + GlobalData, + )); + } + } + + pub fn unlock_pointer(&self) { + let mut inner = self.inner.lock().unwrap(); + if let Some(locked_pointer) = inner.locked_pointer.take() { + locked_pointer.destroy(); + } + } + + pub fn confine_pointer( + &self, + pointer_constraints: &PointerConstraintsState, + surface: &WlSurface, + pointer: &WlPointer, + queue_handle: &QueueHandle<WinitState>, + ) { + self.inner.lock().unwrap().confined_pointer = Some(pointer_constraints.confine_pointer( + surface, + pointer, + None, + Lifetime::Persistent, + queue_handle, + GlobalData, + )); + } + + pub fn unconfine_pointer(&self) { + let inner = self.inner.lock().unwrap(); + if let Some(confined_pointer) = inner.confined_pointer.as_ref() { + confined_pointer.destroy(); + } + } + + /// Seat associated with this pointer. + pub fn seat(&self) -> &WlSeat { + self.sctk_data.seat() + } + + /// Active window. + pub fn focused_window(&self) -> Option<WindowId> { + self.inner.lock().unwrap().surface + } + + /// Last button serial. + pub fn latest_button_serial(&self) -> u32 { + self.sctk_data.latest_button_serial().unwrap_or_default() + } + + /// Last enter serial. + pub fn latest_enter_serial(&self) -> u32 { + self.sctk_data.latest_enter_serial().unwrap_or_default() + } + + pub fn set_locked_cursor_position(&self, surface_x: f64, surface_y: f64) { + let inner = self.inner.lock().unwrap(); + if let Some(locked_pointer) = inner.locked_pointer.as_ref() { + locked_pointer.set_cursor_position_hint(surface_x, surface_y); + } + } + + pub fn viewport(&self) -> Option<&WpViewport> { + self.viewport.as_ref() + } +} + +impl Drop for WinitPointerData { + fn drop(&mut self) { + if let Some(viewport) = self.viewport.take() { + viewport.destroy(); + } + } +} + +impl PointerDataExt for WinitPointerData { + fn pointer_data(&self) -> &PointerData { + &self.sctk_data + } +} + +#[derive(Debug)] +pub struct WinitPointerDataInner { + /// The associated locked pointer. + locked_pointer: Option<ZwpLockedPointerV1>, + + /// The associated confined pointer. + confined_pointer: Option<ZwpConfinedPointerV1>, + + /// Serial of the last button event. + latest_button_serial: u32, + + /// Currently focused window. + surface: Option<WindowId>, + + /// Current axis phase. + phase: TouchPhase, +} + +impl Drop for WinitPointerDataInner { + fn drop(&mut self) { + if let Some(locked_pointer) = self.locked_pointer.take() { + locked_pointer.destroy(); + } + + if let Some(confined_pointer) = self.confined_pointer.take() { + confined_pointer.destroy(); + } + } +} + +impl Default for WinitPointerDataInner { + fn default() -> Self { + Self { + surface: None, + locked_pointer: None, + confined_pointer: None, + latest_button_serial: 0, + phase: TouchPhase::Ended, + } + } +} + +/// Convert the Wayland button into winit. +fn wayland_button_to_winit(button: u32) -> MouseButton { + // These values are coming from <linux/input-event-codes.h>. + const BTN_LEFT: u32 = 0x110; + const BTN_RIGHT: u32 = 0x111; + const BTN_MIDDLE: u32 = 0x112; + const BTN_SIDE: u32 = 0x113; + const BTN_EXTRA: u32 = 0x114; + const BTN_FORWARD: u32 = 0x115; + const BTN_BACK: u32 = 0x116; + + match button { + BTN_LEFT => MouseButton::Left, + BTN_RIGHT => MouseButton::Right, + BTN_MIDDLE => MouseButton::Middle, + BTN_BACK | BTN_SIDE => MouseButton::Back, + BTN_FORWARD | BTN_EXTRA => MouseButton::Forward, + button => MouseButton::Other(button as u16), + } +} + +pub trait WinitPointerDataExt { + fn winit_data(&self) -> &WinitPointerData; +} + +impl WinitPointerDataExt for WlPointer { + fn winit_data(&self) -> &WinitPointerData { + self.data::<WinitPointerData>().expect("failed to get pointer data.") + } +} + +pub struct PointerConstraintsState { + pointer_constraints: ZwpPointerConstraintsV1, +} + +impl PointerConstraintsState { + pub fn new( + globals: &GlobalList, + queue_handle: &QueueHandle<WinitState>, + ) -> Result<Self, BindError> { + let pointer_constraints = globals.bind(queue_handle, 1..=1, GlobalData)?; + Ok(Self { pointer_constraints }) + } +} + +impl Deref for PointerConstraintsState { + type Target = ZwpPointerConstraintsV1; + + fn deref(&self) -> &Self::Target { + &self.pointer_constraints + } +} + +impl Dispatch<ZwpPointerConstraintsV1, GlobalData, WinitState> for PointerConstraintsState { + fn event( + _state: &mut WinitState, + _proxy: &ZwpPointerConstraintsV1, + _event: <ZwpPointerConstraintsV1 as wayland_client::Proxy>::Event, + _data: &GlobalData, + _conn: &Connection, + _qhandle: &QueueHandle<WinitState>, + ) { + } +} + +impl Dispatch<ZwpLockedPointerV1, GlobalData, WinitState> for PointerConstraintsState { + fn event( + _state: &mut WinitState, + _proxy: &ZwpLockedPointerV1, + _event: <ZwpLockedPointerV1 as wayland_client::Proxy>::Event, + _data: &GlobalData, + _conn: &Connection, + _qhandle: &QueueHandle<WinitState>, + ) { + } +} + +impl Dispatch<ZwpConfinedPointerV1, GlobalData, WinitState> for PointerConstraintsState { + fn event( + _state: &mut WinitState, + _proxy: &ZwpConfinedPointerV1, + _event: <ZwpConfinedPointerV1 as wayland_client::Proxy>::Event, + _data: &GlobalData, + _conn: &Connection, + _qhandle: &QueueHandle<WinitState>, + ) { + } +} + +impl Dispatch<WpCursorShapeDeviceV1, GlobalData, WinitState> for SeatState { + fn event( + _: &mut WinitState, + _: &WpCursorShapeDeviceV1, + _: <WpCursorShapeDeviceV1 as Proxy>::Event, + _: &GlobalData, + _: &Connection, + _: &QueueHandle<WinitState>, + ) { + unreachable!("wp_cursor_shape_manager has no events") + } +} + +impl Dispatch<WpCursorShapeManagerV1, GlobalData, WinitState> for SeatState { + fn event( + _: &mut WinitState, + _: &WpCursorShapeManagerV1, + _: <WpCursorShapeManagerV1 as Proxy>::Event, + _: &GlobalData, + _: &Connection, + _: &QueueHandle<WinitState>, + ) { + unreachable!("wp_cursor_device_manager has no events") + } +} + +delegate_dispatch!(WinitState: [ WlPointer: WinitPointerData] => SeatState); +delegate_dispatch!(WinitState: [ WpCursorShapeManagerV1: GlobalData] => SeatState); +delegate_dispatch!(WinitState: [ WpCursorShapeDeviceV1: GlobalData] => SeatState); +delegate_dispatch!(WinitState: [ZwpPointerConstraintsV1: GlobalData] => PointerConstraintsState); +delegate_dispatch!(WinitState: [ZwpLockedPointerV1: GlobalData] => PointerConstraintsState); +delegate_dispatch!(WinitState: [ZwpConfinedPointerV1: GlobalData] => PointerConstraintsState); diff --git a/app/vendor/rune/vendor/winit/src/platform_impl/linux/wayland/seat/pointer/relative_pointer.rs b/app/vendor/rune/vendor/winit/src/platform_impl/linux/wayland/seat/pointer/relative_pointer.rs new file mode 100644 index 0000000..a9ce276 --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/platform_impl/linux/wayland/seat/pointer/relative_pointer.rs @@ -0,0 +1,83 @@ +//! Relative pointer. + +use std::ops::Deref; + +use sctk::reexports::client::globals::{BindError, GlobalList}; +use sctk::reexports::client::{delegate_dispatch, Dispatch}; +use sctk::reexports::client::{Connection, QueueHandle}; +use sctk::reexports::protocols::wp::relative_pointer::zv1::{ + client::zwp_relative_pointer_manager_v1::ZwpRelativePointerManagerV1, + client::zwp_relative_pointer_v1::{self, ZwpRelativePointerV1}, +}; + +use sctk::globals::GlobalData; + +use crate::event::DeviceEvent; +use crate::platform_impl::wayland::state::WinitState; + +/// Wrapper around the relative pointer. +pub struct RelativePointerState { + manager: ZwpRelativePointerManagerV1, +} + +impl RelativePointerState { + /// Create new relative pointer manager. + pub fn new( + globals: &GlobalList, + queue_handle: &QueueHandle<WinitState>, + ) -> Result<Self, BindError> { + let manager = globals.bind(queue_handle, 1..=1, GlobalData)?; + Ok(Self { manager }) + } +} + +impl Deref for RelativePointerState { + type Target = ZwpRelativePointerManagerV1; + + fn deref(&self) -> &Self::Target { + &self.manager + } +} + +impl Dispatch<ZwpRelativePointerManagerV1, GlobalData, WinitState> for RelativePointerState { + fn event( + _state: &mut WinitState, + _proxy: &ZwpRelativePointerManagerV1, + _event: <ZwpRelativePointerManagerV1 as wayland_client::Proxy>::Event, + _data: &GlobalData, + _conn: &Connection, + _qhandle: &QueueHandle<WinitState>, + ) { + } +} + +impl Dispatch<ZwpRelativePointerV1, GlobalData, WinitState> for RelativePointerState { + fn event( + state: &mut WinitState, + _proxy: &ZwpRelativePointerV1, + event: <ZwpRelativePointerV1 as wayland_client::Proxy>::Event, + _data: &GlobalData, + _conn: &Connection, + _qhandle: &QueueHandle<WinitState>, + ) { + let (dx_unaccel, dy_unaccel) = match event { + zwp_relative_pointer_v1::Event::RelativeMotion { dx_unaccel, dy_unaccel, .. } => { + (dx_unaccel, dy_unaccel) + }, + _ => return, + }; + state + .events_sink + .push_device_event(DeviceEvent::Motion { axis: 0, value: dx_unaccel }, super::DeviceId); + state + .events_sink + .push_device_event(DeviceEvent::Motion { axis: 1, value: dy_unaccel }, super::DeviceId); + state.events_sink.push_device_event( + DeviceEvent::MouseMotion { delta: (dx_unaccel, dy_unaccel) }, + super::DeviceId, + ); + } +} + +delegate_dispatch!(WinitState: [ZwpRelativePointerV1: GlobalData] => RelativePointerState); +delegate_dispatch!(WinitState: [ZwpRelativePointerManagerV1: GlobalData] => RelativePointerState); diff --git a/app/vendor/rune/vendor/winit/src/platform_impl/linux/wayland/seat/text_input/mod.rs b/app/vendor/rune/vendor/winit/src/platform_impl/linux/wayland/seat/text_input/mod.rs new file mode 100644 index 0000000..db72489 --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/platform_impl/linux/wayland/seat/text_input/mod.rs @@ -0,0 +1,201 @@ +use std::ops::Deref; + +use sctk::globals::GlobalData; +use sctk::reexports::client::{Connection, Proxy, QueueHandle}; + +use sctk::reexports::client::globals::{BindError, GlobalList}; +use sctk::reexports::client::protocol::wl_surface::WlSurface; +use sctk::reexports::client::{delegate_dispatch, Dispatch}; +use sctk::reexports::protocols::wp::text_input::zv3::client::zwp_text_input_manager_v3::ZwpTextInputManagerV3; +use sctk::reexports::protocols::wp::text_input::zv3::client::zwp_text_input_v3::{ + ContentHint, ContentPurpose, Event as TextInputEvent, ZwpTextInputV3, +}; + +use crate::event::{Ime, WindowEvent}; +use crate::platform_impl::wayland; +use crate::platform_impl::wayland::state::WinitState; +use crate::window::ImePurpose; + +pub struct TextInputState { + text_input_manager: ZwpTextInputManagerV3, +} + +impl TextInputState { + pub fn new( + globals: &GlobalList, + queue_handle: &QueueHandle<WinitState>, + ) -> Result<Self, BindError> { + let text_input_manager = globals.bind(queue_handle, 1..=1, GlobalData)?; + Ok(Self { text_input_manager }) + } +} + +impl Deref for TextInputState { + type Target = ZwpTextInputManagerV3; + + fn deref(&self) -> &Self::Target { + &self.text_input_manager + } +} + +impl Dispatch<ZwpTextInputManagerV3, GlobalData, WinitState> for TextInputState { + fn event( + _state: &mut WinitState, + _proxy: &ZwpTextInputManagerV3, + _event: <ZwpTextInputManagerV3 as Proxy>::Event, + _data: &GlobalData, + _conn: &Connection, + _qhandle: &QueueHandle<WinitState>, + ) { + } +} + +impl Dispatch<ZwpTextInputV3, TextInputData, WinitState> for TextInputState { + fn event( + state: &mut WinitState, + text_input: &ZwpTextInputV3, + event: <ZwpTextInputV3 as Proxy>::Event, + data: &TextInputData, + _conn: &Connection, + _qhandle: &QueueHandle<WinitState>, + ) { + let windows = state.windows.get_mut(); + let mut text_input_data = data.inner.lock().unwrap(); + match event { + TextInputEvent::Enter { surface } => { + let window_id = wayland::make_wid(&surface); + text_input_data.surface = Some(surface); + + let mut window = match windows.get(&window_id) { + Some(window) => window.lock().unwrap(), + None => return, + }; + + if window.ime_allowed() { + text_input.enable(); + text_input.set_content_type_by_purpose(window.ime_purpose()); + text_input.commit(); + state.events_sink.push_window_event(WindowEvent::Ime(Ime::Enabled), window_id); + } + + window.text_input_entered(text_input); + }, + TextInputEvent::Leave { surface } => { + text_input_data.surface = None; + + // Always issue a disable. + text_input.disable(); + text_input.commit(); + + let window_id = wayland::make_wid(&surface); + + // XXX this check is essential, because `leave` could have a + // reference to nil surface... + let mut window = match windows.get(&window_id) { + Some(window) => window.lock().unwrap(), + None => return, + }; + + window.text_input_left(text_input); + + state.events_sink.push_window_event(WindowEvent::Ime(Ime::Disabled), window_id); + }, + TextInputEvent::PreeditString { text, cursor_begin, cursor_end } => { + let text = text.unwrap_or_default(); + let cursor_begin = usize::try_from(cursor_begin) + .ok() + .and_then(|idx| text.is_char_boundary(idx).then_some(idx)); + let cursor_end = usize::try_from(cursor_end) + .ok() + .and_then(|idx| text.is_char_boundary(idx).then_some(idx)); + + text_input_data.pending_preedit = Some(Preedit { text, cursor_begin, cursor_end }) + }, + TextInputEvent::CommitString { text } => { + text_input_data.pending_preedit = None; + text_input_data.pending_commit = text; + }, + TextInputEvent::Done { .. } => { + let window_id = match text_input_data.surface.as_ref() { + Some(surface) => wayland::make_wid(surface), + None => return, + }; + + // Clear preedit, unless all we'll be doing next is sending a new preedit. + if text_input_data.pending_commit.is_some() + || text_input_data.pending_preedit.is_none() + { + state.events_sink.push_window_event( + WindowEvent::Ime(Ime::Preedit(String::new(), None)), + window_id, + ); + } + + // Send `Commit`. + if let Some(text) = text_input_data.pending_commit.take() { + state + .events_sink + .push_window_event(WindowEvent::Ime(Ime::Commit(text)), window_id); + } + + // Send preedit. + if let Some(preedit) = text_input_data.pending_preedit.take() { + let cursor_range = + preedit.cursor_begin.map(|b| (b, preedit.cursor_end.unwrap_or(b))); + + state.events_sink.push_window_event( + WindowEvent::Ime(Ime::Preedit(preedit.text, cursor_range)), + window_id, + ); + } + }, + TextInputEvent::DeleteSurroundingText { .. } => { + // Not handled. + }, + _ => {}, + } + } +} + +pub trait ZwpTextInputV3Ext { + fn set_content_type_by_purpose(&self, purpose: ImePurpose); +} + +impl ZwpTextInputV3Ext for ZwpTextInputV3 { + fn set_content_type_by_purpose(&self, purpose: ImePurpose) { + let (hint, purpose) = match purpose { + ImePurpose::Normal => (ContentHint::None, ContentPurpose::Normal), + ImePurpose::Password => (ContentHint::SensitiveData, ContentPurpose::Password), + ImePurpose::Terminal => (ContentHint::None, ContentPurpose::Terminal), + }; + self.set_content_type(hint, purpose); + } +} + +/// The Data associated with the text input. +#[derive(Default)] +pub struct TextInputData { + inner: std::sync::Mutex<TextInputDataInner>, +} + +#[derive(Default)] +pub struct TextInputDataInner { + /// The `WlSurface` we're performing input to. + surface: Option<WlSurface>, + + /// The commit to submit on `done`. + pending_commit: Option<String>, + + /// The preedit to submit on `done`. + pending_preedit: Option<Preedit>, +} + +/// The state of the preedit. +struct Preedit { + text: String, + cursor_begin: Option<usize>, + cursor_end: Option<usize>, +} + +delegate_dispatch!(WinitState: [ZwpTextInputManagerV3: GlobalData] => TextInputState); +delegate_dispatch!(WinitState: [ZwpTextInputV3: TextInputData] => TextInputState); diff --git a/app/vendor/rune/vendor/winit/src/platform_impl/linux/wayland/seat/touch/mod.rs b/app/vendor/rune/vendor/winit/src/platform_impl/linux/wayland/seat/touch/mod.rs new file mode 100644 index 0000000..124504f --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/platform_impl/linux/wayland/seat/touch/mod.rs @@ -0,0 +1,220 @@ +//! Touch handling. + +use tracing::warn; + +use sctk::reexports::client::protocol::wl_seat::WlSeat; +use sctk::reexports::client::protocol::wl_surface::WlSurface; +use sctk::reexports::client::protocol::wl_touch::WlTouch; +use sctk::reexports::client::{Connection, Proxy, QueueHandle}; + +use sctk::seat::touch::{TouchData, TouchHandler}; + +use crate::dpi::LogicalPosition; +use crate::event::{Touch, TouchPhase, WindowEvent}; + +use crate::platform_impl::wayland::state::WinitState; +use crate::platform_impl::wayland::{self, DeviceId}; + +impl TouchHandler for WinitState { + fn down( + &mut self, + _: &Connection, + _: &QueueHandle<Self>, + touch: &WlTouch, + _: u32, + _: u32, + surface: WlSurface, + id: i32, + position: (f64, f64), + ) { + let window_id = wayland::make_wid(&surface); + let scale_factor = match self.windows.get_mut().get(&window_id) { + Some(window) => window.lock().unwrap().scale_factor(), + None => return, + }; + + let seat_state = match self.seats.get_mut(&touch.seat().id()) { + Some(seat_state) => seat_state, + None => { + warn!("Received wl_touch::down without seat"); + return; + }, + }; + + // Update the state of the point. + let location = LogicalPosition::<f64>::from(position); + seat_state.touch_map.insert(id, TouchPoint { surface, location }); + + self.events_sink.push_window_event( + WindowEvent::Touch(Touch { + device_id: crate::event::DeviceId(crate::platform_impl::DeviceId::Wayland( + DeviceId, + )), + phase: TouchPhase::Started, + location: location.to_physical(scale_factor), + force: None, + id: id as u64, + }), + window_id, + ); + } + + fn up( + &mut self, + _: &Connection, + _: &QueueHandle<Self>, + touch: &WlTouch, + _: u32, + _: u32, + id: i32, + ) { + let seat_state = match self.seats.get_mut(&touch.seat().id()) { + Some(seat_state) => seat_state, + None => { + warn!("Received wl_touch::up without seat"); + return; + }, + }; + + // Remove the touch point. + let touch_point = match seat_state.touch_map.remove(&id) { + Some(touch_point) => touch_point, + None => return, + }; + + let window_id = wayland::make_wid(&touch_point.surface); + let scale_factor = match self.windows.get_mut().get(&window_id) { + Some(window) => window.lock().unwrap().scale_factor(), + None => return, + }; + + self.events_sink.push_window_event( + WindowEvent::Touch(Touch { + device_id: crate::event::DeviceId(crate::platform_impl::DeviceId::Wayland( + DeviceId, + )), + phase: TouchPhase::Ended, + location: touch_point.location.to_physical(scale_factor), + force: None, + id: id as u64, + }), + window_id, + ); + } + + fn motion( + &mut self, + _: &Connection, + _: &QueueHandle<Self>, + touch: &WlTouch, + _: u32, + id: i32, + position: (f64, f64), + ) { + let seat_state = match self.seats.get_mut(&touch.seat().id()) { + Some(seat_state) => seat_state, + None => { + warn!("Received wl_touch::motion without seat"); + return; + }, + }; + + // Remove the touch point. + let touch_point = match seat_state.touch_map.get_mut(&id) { + Some(touch_point) => touch_point, + None => return, + }; + + let window_id = wayland::make_wid(&touch_point.surface); + let scale_factor = match self.windows.get_mut().get(&window_id) { + Some(window) => window.lock().unwrap().scale_factor(), + None => return, + }; + + touch_point.location = LogicalPosition::<f64>::from(position); + + self.events_sink.push_window_event( + WindowEvent::Touch(Touch { + device_id: crate::event::DeviceId(crate::platform_impl::DeviceId::Wayland( + DeviceId, + )), + phase: TouchPhase::Moved, + location: touch_point.location.to_physical(scale_factor), + force: None, + id: id as u64, + }), + window_id, + ); + } + + fn cancel(&mut self, _: &Connection, _: &QueueHandle<Self>, touch: &WlTouch) { + let seat_state = match self.seats.get_mut(&touch.seat().id()) { + Some(seat_state) => seat_state, + None => { + warn!("Received wl_touch::cancel without seat"); + return; + }, + }; + + for (id, touch_point) in seat_state.touch_map.drain() { + let window_id = wayland::make_wid(&touch_point.surface); + let scale_factor = match self.windows.get_mut().get(&window_id) { + Some(window) => window.lock().unwrap().scale_factor(), + None => return, + }; + + let location = touch_point.location.to_physical(scale_factor); + + self.events_sink.push_window_event( + WindowEvent::Touch(Touch { + device_id: crate::event::DeviceId(crate::platform_impl::DeviceId::Wayland( + DeviceId, + )), + phase: TouchPhase::Cancelled, + location, + force: None, + id: id as u64, + }), + window_id, + ); + } + } + + fn shape( + &mut self, + _: &Connection, + _: &QueueHandle<Self>, + _: &WlTouch, + _: i32, + _: f64, + _: f64, + ) { + // Blank. + } + + fn orientation(&mut self, _: &Connection, _: &QueueHandle<Self>, _: &WlTouch, _: i32, _: f64) { + // Blank. + } +} + +/// The state of the touch point. +#[derive(Debug)] +pub struct TouchPoint { + /// The surface on which the point is present. + pub surface: WlSurface, + + /// The location of the point on the surface. + pub location: LogicalPosition<f64>, +} + +pub trait TouchDataExt { + fn seat(&self) -> &WlSeat; +} + +impl TouchDataExt for WlTouch { + fn seat(&self) -> &WlSeat { + self.data::<TouchData>().expect("failed to get touch data.").seat() + } +} + +sctk::delegate_touch!(WinitState); diff --git a/app/vendor/rune/vendor/winit/src/platform_impl/linux/wayland/state.rs b/app/vendor/rune/vendor/winit/src/platform_impl/linux/wayland/state.rs new file mode 100644 index 0000000..13ef99c --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/platform_impl/linux/wayland/state.rs @@ -0,0 +1,435 @@ +use std::cell::RefCell; +use std::sync::atomic::Ordering; +use std::sync::{Arc, Mutex}; + +use ahash::AHashMap; + +use sctk::reexports::calloop::LoopHandle; +use sctk::reexports::client::backend::ObjectId; +use sctk::reexports::client::globals::GlobalList; +use sctk::reexports::client::protocol::wl_output::WlOutput; +use sctk::reexports::client::protocol::wl_surface::WlSurface; +use sctk::reexports::client::{Connection, Proxy, QueueHandle}; + +use sctk::compositor::{CompositorHandler, CompositorState}; +use sctk::output::{OutputHandler, OutputState}; +use sctk::registry::{ProvidesRegistryState, RegistryState}; +use sctk::seat::pointer::ThemedPointer; +use sctk::seat::SeatState; +use sctk::shell::xdg::window::{Window, WindowConfigure, WindowHandler}; +use sctk::shell::xdg::XdgShell; +use sctk::shell::WaylandSurface; +use sctk::shm::slot::SlotPool; +use sctk::shm::{Shm, ShmHandler}; +use sctk::subcompositor::SubcompositorState; + +use crate::platform_impl::wayland::event_loop::sink::EventSink; +use crate::platform_impl::wayland::output::MonitorHandle; +use crate::platform_impl::wayland::seat::{ + PointerConstraintsState, RelativePointerState, TextInputState, WinitPointerData, + WinitPointerDataExt, WinitSeatState, +}; +use crate::platform_impl::wayland::types::kwin_blur::KWinBlurManager; +use crate::platform_impl::wayland::types::wp_fractional_scaling::FractionalScalingManager; +use crate::platform_impl::wayland::types::wp_viewporter::ViewporterState; +use crate::platform_impl::wayland::types::xdg_activation::XdgActivationState; +use crate::platform_impl::wayland::window::{WindowRequests, WindowState}; +use crate::platform_impl::wayland::{WaylandError, WindowId}; +use crate::platform_impl::OsError; + +/// Winit's Wayland state. +pub struct WinitState { + /// The WlRegistry. + pub registry_state: RegistryState, + + /// The state of the WlOutput handling. + pub output_state: OutputState, + + /// The compositor state which is used to create new windows and regions. + pub compositor_state: Arc<CompositorState>, + + /// The state of the subcompositor. + pub subcompositor_state: Option<Arc<SubcompositorState>>, + + /// The seat state responsible for all sorts of input. + pub seat_state: SeatState, + + /// The shm for software buffers, such as cursors. + pub shm: Shm, + + /// The pool where custom cursors are allocated. + pub custom_cursor_pool: Arc<Mutex<SlotPool>>, + + /// The XDG shell that is used for windows. + pub xdg_shell: XdgShell, + + /// The currently present windows. + pub windows: RefCell<AHashMap<WindowId, Arc<Mutex<WindowState>>>>, + + /// The requests from the `Window` to EventLoop, such as close operations and redraw requests. + pub window_requests: RefCell<AHashMap<WindowId, Arc<WindowRequests>>>, + + /// The events that were generated directly from the window. + pub window_events_sink: Arc<Mutex<EventSink>>, + + /// The update for the `windows` coming from the compositor. + pub window_compositor_updates: Vec<WindowCompositorUpdate>, + + /// Currently handled seats. + pub seats: AHashMap<ObjectId, WinitSeatState>, + + /// Currently present cursor surfaces. + pub pointer_surfaces: AHashMap<ObjectId, Arc<ThemedPointer<WinitPointerData>>>, + + /// The state of the text input on the client. + pub text_input_state: Option<TextInputState>, + + /// Observed monitors. + pub monitors: Arc<Mutex<Vec<MonitorHandle>>>, + + /// Sink to accumulate window events from the compositor, which is latter dispatched in + /// event loop run. + pub events_sink: EventSink, + + /// Xdg activation. + pub xdg_activation: Option<XdgActivationState>, + + /// Relative pointer. + pub relative_pointer: Option<RelativePointerState>, + + /// Pointer constraints to handle pointer locking and confining. + pub pointer_constraints: Option<Arc<PointerConstraintsState>>, + + /// Viewporter state on the given window. + pub viewporter_state: Option<ViewporterState>, + + /// Fractional scaling manager. + pub fractional_scaling_manager: Option<FractionalScalingManager>, + + /// KWin blur manager. + pub kwin_blur_manager: Option<KWinBlurManager>, + + /// Loop handle to re-register event sources, such as keyboard repeat. + pub loop_handle: LoopHandle<'static, Self>, + + /// Whether we have dispatched events to the user thus we want to + /// send `AboutToWait` and normally wakeup the user. + pub dispatched_events: bool, +} + +impl WinitState { + pub fn new( + globals: &GlobalList, + queue_handle: &QueueHandle<Self>, + loop_handle: LoopHandle<'static, WinitState>, + ) -> Result<Self, OsError> { + let registry_state = RegistryState::new(globals); + let compositor_state = + CompositorState::bind(globals, queue_handle).map_err(WaylandError::Bind)?; + let subcompositor_state = match SubcompositorState::bind( + compositor_state.wl_compositor().clone(), + globals, + queue_handle, + ) { + Ok(c) => Some(c), + Err(e) => { + tracing::warn!("Subcompositor protocol not available, ignoring CSD: {e:?}"); + None + }, + }; + + let output_state = OutputState::new(globals, queue_handle); + let monitors = output_state.outputs().map(MonitorHandle::new).collect(); + + let seat_state = SeatState::new(globals, queue_handle); + + let mut seats = AHashMap::default(); + for seat in seat_state.seats() { + seats.insert(seat.id(), WinitSeatState::new()); + } + + let (viewporter_state, fractional_scaling_manager) = + if let Ok(fsm) = FractionalScalingManager::new(globals, queue_handle) { + (ViewporterState::new(globals, queue_handle).ok(), Some(fsm)) + } else { + (None, None) + }; + + let shm = Shm::bind(globals, queue_handle).map_err(WaylandError::Bind)?; + let custom_cursor_pool = Arc::new(Mutex::new(SlotPool::new(2, &shm).unwrap())); + + Ok(Self { + registry_state, + compositor_state: Arc::new(compositor_state), + subcompositor_state: subcompositor_state.map(Arc::new), + output_state, + seat_state, + shm, + custom_cursor_pool, + + xdg_shell: XdgShell::bind(globals, queue_handle).map_err(WaylandError::Bind)?, + xdg_activation: XdgActivationState::bind(globals, queue_handle).ok(), + + windows: Default::default(), + window_requests: Default::default(), + window_compositor_updates: Vec::new(), + window_events_sink: Default::default(), + viewporter_state, + fractional_scaling_manager, + kwin_blur_manager: KWinBlurManager::new(globals, queue_handle).ok(), + + seats, + text_input_state: TextInputState::new(globals, queue_handle).ok(), + + relative_pointer: RelativePointerState::new(globals, queue_handle).ok(), + pointer_constraints: PointerConstraintsState::new(globals, queue_handle) + .map(Arc::new) + .ok(), + pointer_surfaces: Default::default(), + + monitors: Arc::new(Mutex::new(monitors)), + events_sink: EventSink::new(), + loop_handle, + // Make it true by default. + dispatched_events: true, + }) + } + + pub fn scale_factor_changed( + &mut self, + surface: &WlSurface, + scale_factor: f64, + is_legacy: bool, + ) { + // Check if the cursor surface. + let window_id = super::make_wid(surface); + + if let Some(window) = self.windows.get_mut().get(&window_id) { + // Don't update the scaling factor, when legacy method is used. + if is_legacy && self.fractional_scaling_manager.is_some() { + return; + } + + // The scale factor change is for the window. + let pos = if let Some(pos) = self + .window_compositor_updates + .iter() + .position(|update| update.window_id == window_id) + { + pos + } else { + self.window_compositor_updates.push(WindowCompositorUpdate::new(window_id)); + self.window_compositor_updates.len() - 1 + }; + + // Update the scale factor right away. + window.lock().unwrap().set_scale_factor(scale_factor); + self.window_compositor_updates[pos].scale_changed = true; + } else if let Some(pointer) = self.pointer_surfaces.get(&surface.id()) { + // Get the window, where the pointer resides right now. + let focused_window = match pointer.pointer().winit_data().focused_window() { + Some(focused_window) => focused_window, + None => return, + }; + + if let Some(window_state) = self.windows.get_mut().get(&focused_window) { + window_state.lock().unwrap().reload_cursor_style() + } + } + } + + pub fn queue_close(updates: &mut Vec<WindowCompositorUpdate>, window_id: WindowId) { + let pos = if let Some(pos) = updates.iter().position(|update| update.window_id == window_id) + { + pos + } else { + updates.push(WindowCompositorUpdate::new(window_id)); + updates.len() - 1 + }; + + updates[pos].close_window = true; + } +} + +impl ShmHandler for WinitState { + fn shm_state(&mut self) -> &mut Shm { + &mut self.shm + } +} + +impl WindowHandler for WinitState { + fn request_close(&mut self, _: &Connection, _: &QueueHandle<Self>, window: &Window) { + let window_id = super::make_wid(window.wl_surface()); + Self::queue_close(&mut self.window_compositor_updates, window_id); + } + + fn configure( + &mut self, + _: &Connection, + _: &QueueHandle<Self>, + window: &Window, + configure: WindowConfigure, + _serial: u32, + ) { + let window_id = super::make_wid(window.wl_surface()); + + let pos = if let Some(pos) = + self.window_compositor_updates.iter().position(|update| update.window_id == window_id) + { + pos + } else { + self.window_compositor_updates.push(WindowCompositorUpdate::new(window_id)); + self.window_compositor_updates.len() - 1 + }; + + // Populate the configure to the window. + self.window_compositor_updates[pos].resized |= self + .windows + .get_mut() + .get_mut(&window_id) + .expect("got configure for dead window.") + .lock() + .unwrap() + .configure(configure, &self.shm, &self.subcompositor_state); + + // NOTE: configure demands wl_surface::commit, however winit doesn't commit on behalf of the + // users, since it can break a lot of things, thus it'll ask users to redraw instead. + self.window_requests + .get_mut() + .get(&window_id) + .unwrap() + .redraw_requested + .store(true, Ordering::Relaxed); + + // Manually mark that we've got an event, since configure may not generate a resize. + self.dispatched_events = true; + } +} + +impl OutputHandler for WinitState { + fn output_state(&mut self) -> &mut OutputState { + &mut self.output_state + } + + fn new_output(&mut self, _: &Connection, _: &QueueHandle<Self>, output: WlOutput) { + self.monitors.lock().unwrap().push(MonitorHandle::new(output)); + } + + fn update_output(&mut self, _: &Connection, _: &QueueHandle<Self>, updated: WlOutput) { + let mut monitors = self.monitors.lock().unwrap(); + let updated = MonitorHandle::new(updated); + if let Some(pos) = monitors.iter().position(|output| output == &updated) { + monitors[pos] = updated + } else { + monitors.push(updated) + } + } + + fn output_destroyed(&mut self, _: &Connection, _: &QueueHandle<Self>, removed: WlOutput) { + let mut monitors = self.monitors.lock().unwrap(); + let removed = MonitorHandle::new(removed); + if let Some(pos) = monitors.iter().position(|output| output == &removed) { + monitors.remove(pos); + } + } +} + +impl CompositorHandler for WinitState { + fn transform_changed( + &mut self, + _: &Connection, + _: &QueueHandle<Self>, + _: &WlSurface, + _: wayland_client::protocol::wl_output::Transform, + ) { + // TODO(kchibisov) we need to expose it somehow in winit. + } + + fn surface_enter( + &mut self, + _: &Connection, + _: &QueueHandle<Self>, + _: &WlSurface, + _: &WlOutput, + ) { + } + + fn surface_leave( + &mut self, + _: &Connection, + _: &QueueHandle<Self>, + _: &WlSurface, + _: &WlOutput, + ) { + } + + fn scale_factor_changed( + &mut self, + _: &Connection, + _: &QueueHandle<Self>, + surface: &WlSurface, + scale_factor: i32, + ) { + self.scale_factor_changed(surface, scale_factor as f64, true) + } + + fn frame(&mut self, _: &Connection, _: &QueueHandle<Self>, surface: &WlSurface, _: u32) { + let window_id = super::make_wid(surface); + let window = match self.windows.get_mut().get(&window_id) { + Some(window) => window, + None => return, + }; + + // In case we have a redraw requested we must indicate the wake up. + if self + .window_requests + .get_mut() + .get(&window_id) + .unwrap() + .redraw_requested + .load(Ordering::Relaxed) + { + self.dispatched_events = true; + } + + window.lock().unwrap().frame_callback_received(); + } +} + +impl ProvidesRegistryState for WinitState { + sctk::registry_handlers![OutputState, SeatState]; + + fn registry(&mut self) -> &mut RegistryState { + &mut self.registry_state + } +} + +// The window update coming from the compositor. +#[derive(Debug, Clone, Copy)] +pub struct WindowCompositorUpdate { + /// The id of the window this updates belongs to. + pub window_id: WindowId, + + /// New window size. + pub resized: bool, + + /// New scale factor. + pub scale_changed: bool, + + /// Close the window. + pub close_window: bool, +} + +impl WindowCompositorUpdate { + fn new(window_id: WindowId) -> Self { + Self { window_id, resized: false, scale_changed: false, close_window: false } + } +} + +sctk::delegate_subcompositor!(WinitState); +sctk::delegate_compositor!(WinitState); +sctk::delegate_output!(WinitState); +sctk::delegate_registry!(WinitState); +sctk::delegate_shm!(WinitState); +sctk::delegate_xdg_shell!(WinitState); +sctk::delegate_xdg_window!(WinitState); diff --git a/app/vendor/rune/vendor/winit/src/platform_impl/linux/wayland/types/cursor.rs b/app/vendor/rune/vendor/winit/src/platform_impl/linux/wayland/types/cursor.rs new file mode 100644 index 0000000..c1a0c26 --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/platform_impl/linux/wayland/types/cursor.rs @@ -0,0 +1,59 @@ +use cursor_icon::CursorIcon; + +use sctk::reexports::client::protocol::wl_shm::Format; +use sctk::shm::slot::{Buffer, SlotPool}; + +use crate::cursor::CursorImage; + +#[derive(Debug)] +pub enum SelectedCursor { + Named(CursorIcon), + Custom(CustomCursor), +} + +impl Default for SelectedCursor { + fn default() -> Self { + Self::Named(Default::default()) + } +} + +#[derive(Debug)] +pub struct CustomCursor { + pub buffer: Buffer, + pub w: i32, + pub h: i32, + pub hotspot_x: i32, + pub hotspot_y: i32, +} + +impl CustomCursor { + pub(crate) fn new(pool: &mut SlotPool, image: &CursorImage) -> Self { + let (buffer, canvas) = pool + .create_buffer( + image.width as i32, + image.height as i32, + 4 * (image.width as i32), + Format::Argb8888, + ) + .unwrap(); + + for (canvas_chunk, rgba) in canvas.chunks_exact_mut(4).zip(image.rgba.chunks_exact(4)) { + // Alpha in buffer is premultiplied. + let alpha = rgba[3] as f32 / 255.; + let r = (rgba[0] as f32 * alpha) as u32; + let g = (rgba[1] as f32 * alpha) as u32; + let b = (rgba[2] as f32 * alpha) as u32; + let color = ((rgba[3] as u32) << 24) + (r << 16) + (g << 8) + b; + let array: &mut [u8; 4] = canvas_chunk.try_into().unwrap(); + *array = color.to_le_bytes(); + } + + CustomCursor { + buffer, + w: image.width as i32, + h: image.height as i32, + hotspot_x: image.hotspot_x as i32, + hotspot_y: image.hotspot_y as i32, + } + } +} diff --git a/app/vendor/rune/vendor/winit/src/platform_impl/linux/wayland/types/kwin_blur.rs b/app/vendor/rune/vendor/winit/src/platform_impl/linux/wayland/types/kwin_blur.rs new file mode 100644 index 0000000..83e82ad --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/platform_impl/linux/wayland/types/kwin_blur.rs @@ -0,0 +1,68 @@ +//! Handling of KDE-compatible blur. + +use sctk::reexports::client::globals::{BindError, GlobalList}; +use sctk::reexports::client::protocol::wl_surface::WlSurface; +use sctk::reexports::client::{delegate_dispatch, Connection, Dispatch, Proxy, QueueHandle}; +use wayland_protocols_plasma::blur::client::org_kde_kwin_blur::OrgKdeKwinBlur; +use wayland_protocols_plasma::blur::client::org_kde_kwin_blur_manager::OrgKdeKwinBlurManager; + +use sctk::globals::GlobalData; + +use crate::platform_impl::wayland::state::WinitState; + +/// KWin blur manager. +#[derive(Debug, Clone)] +pub struct KWinBlurManager { + manager: OrgKdeKwinBlurManager, +} + +impl KWinBlurManager { + pub fn new( + globals: &GlobalList, + queue_handle: &QueueHandle<WinitState>, + ) -> Result<Self, BindError> { + let manager = globals.bind(queue_handle, 1..=1, GlobalData)?; + Ok(Self { manager }) + } + + pub fn blur( + &self, + surface: &WlSurface, + queue_handle: &QueueHandle<WinitState>, + ) -> OrgKdeKwinBlur { + self.manager.create(surface, queue_handle, ()) + } + + pub fn unset(&self, surface: &WlSurface) { + self.manager.unset(surface) + } +} + +impl Dispatch<OrgKdeKwinBlurManager, GlobalData, WinitState> for KWinBlurManager { + fn event( + _: &mut WinitState, + _: &OrgKdeKwinBlurManager, + _: <OrgKdeKwinBlurManager as Proxy>::Event, + _: &GlobalData, + _: &Connection, + _: &QueueHandle<WinitState>, + ) { + unreachable!("no events defined for org_kde_kwin_blur_manager"); + } +} + +impl Dispatch<OrgKdeKwinBlur, (), WinitState> for KWinBlurManager { + fn event( + _: &mut WinitState, + _: &OrgKdeKwinBlur, + _: <OrgKdeKwinBlur as Proxy>::Event, + _: &(), + _: &Connection, + _: &QueueHandle<WinitState>, + ) { + unreachable!("no events defined for org_kde_kwin_blur"); + } +} + +delegate_dispatch!(WinitState: [OrgKdeKwinBlurManager: GlobalData] => KWinBlurManager); +delegate_dispatch!(WinitState: [OrgKdeKwinBlur: ()] => KWinBlurManager); diff --git a/app/vendor/rune/vendor/winit/src/platform_impl/linux/wayland/types/mod.rs b/app/vendor/rune/vendor/winit/src/platform_impl/linux/wayland/types/mod.rs new file mode 100644 index 0000000..77e67f4 --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/platform_impl/linux/wayland/types/mod.rs @@ -0,0 +1,7 @@ +//! Wayland protocol implementation boilerplate. + +pub mod cursor; +pub mod kwin_blur; +pub mod wp_fractional_scaling; +pub mod wp_viewporter; +pub mod xdg_activation; diff --git a/app/vendor/rune/vendor/winit/src/platform_impl/linux/wayland/types/wp_fractional_scaling.rs b/app/vendor/rune/vendor/winit/src/platform_impl/linux/wayland/types/wp_fractional_scaling.rs new file mode 100644 index 0000000..2dfc9db --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/platform_impl/linux/wayland/types/wp_fractional_scaling.rs @@ -0,0 +1,78 @@ +//! Handling of the fractional scaling. + +use sctk::reexports::client::globals::{BindError, GlobalList}; +use sctk::reexports::client::protocol::wl_surface::WlSurface; +use sctk::reexports::client::{delegate_dispatch, Connection, Dispatch, Proxy, QueueHandle}; +use sctk::reexports::protocols::wp::fractional_scale::v1::client::wp_fractional_scale_manager_v1::WpFractionalScaleManagerV1; +use sctk::reexports::protocols::wp::fractional_scale::v1::client::wp_fractional_scale_v1::{ + Event as FractionalScalingEvent, WpFractionalScaleV1, +}; + +use sctk::globals::GlobalData; + +use crate::platform_impl::wayland::state::WinitState; + +/// The scaling factor denominator. +const SCALE_DENOMINATOR: f64 = 120.; + +/// Fractional scaling manager. +#[derive(Debug)] +pub struct FractionalScalingManager { + manager: WpFractionalScaleManagerV1, +} + +pub struct FractionalScaling { + /// The surface used for scaling. + surface: WlSurface, +} + +impl FractionalScalingManager { + /// Create new viewporter. + pub fn new( + globals: &GlobalList, + queue_handle: &QueueHandle<WinitState>, + ) -> Result<Self, BindError> { + let manager = globals.bind(queue_handle, 1..=1, GlobalData)?; + Ok(Self { manager }) + } + + pub fn fractional_scaling( + &self, + surface: &WlSurface, + queue_handle: &QueueHandle<WinitState>, + ) -> WpFractionalScaleV1 { + let data = FractionalScaling { surface: surface.clone() }; + self.manager.get_fractional_scale(surface, queue_handle, data) + } +} + +impl Dispatch<WpFractionalScaleManagerV1, GlobalData, WinitState> for FractionalScalingManager { + fn event( + _: &mut WinitState, + _: &WpFractionalScaleManagerV1, + _: <WpFractionalScaleManagerV1 as Proxy>::Event, + _: &GlobalData, + _: &Connection, + _: &QueueHandle<WinitState>, + ) { + // No events. + } +} + +impl Dispatch<WpFractionalScaleV1, FractionalScaling, WinitState> for FractionalScalingManager { + fn event( + state: &mut WinitState, + _: &WpFractionalScaleV1, + event: <WpFractionalScaleV1 as Proxy>::Event, + data: &FractionalScaling, + _: &Connection, + _: &QueueHandle<WinitState>, + ) { + if let FractionalScalingEvent::PreferredScale { scale } = event { + state.scale_factor_changed(&data.surface, scale as f64 / SCALE_DENOMINATOR, false); + } + } +} + +delegate_dispatch!(WinitState: [WpFractionalScaleManagerV1: GlobalData] => FractionalScalingManager); +delegate_dispatch!(WinitState: [WpFractionalScaleV1: FractionalScaling] => FractionalScalingManager); diff --git a/app/vendor/rune/vendor/winit/src/platform_impl/linux/wayland/types/wp_viewporter.rs b/app/vendor/rune/vendor/winit/src/platform_impl/linux/wayland/types/wp_viewporter.rs new file mode 100644 index 0000000..9076482 --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/platform_impl/linux/wayland/types/wp_viewporter.rs @@ -0,0 +1,65 @@ +//! Handling of the wp-viewporter. + +use sctk::reexports::client::globals::{BindError, GlobalList}; +use sctk::reexports::client::protocol::wl_surface::WlSurface; +use sctk::reexports::client::{delegate_dispatch, Connection, Dispatch, Proxy, QueueHandle}; +use sctk::reexports::protocols::wp::viewporter::client::wp_viewport::WpViewport; +use sctk::reexports::protocols::wp::viewporter::client::wp_viewporter::WpViewporter; + +use sctk::globals::GlobalData; + +use crate::platform_impl::wayland::state::WinitState; + +/// Viewporter. +#[derive(Debug)] +pub struct ViewporterState { + viewporter: WpViewporter, +} + +impl ViewporterState { + /// Create new viewporter. + pub fn new( + globals: &GlobalList, + queue_handle: &QueueHandle<WinitState>, + ) -> Result<Self, BindError> { + let viewporter = globals.bind(queue_handle, 1..=1, GlobalData)?; + Ok(Self { viewporter }) + } + + /// Get the viewport for the given object. + pub fn get_viewport( + &self, + surface: &WlSurface, + queue_handle: &QueueHandle<WinitState>, + ) -> WpViewport { + self.viewporter.get_viewport(surface, queue_handle, GlobalData) + } +} + +impl Dispatch<WpViewporter, GlobalData, WinitState> for ViewporterState { + fn event( + _: &mut WinitState, + _: &WpViewporter, + _: <WpViewporter as Proxy>::Event, + _: &GlobalData, + _: &Connection, + _: &QueueHandle<WinitState>, + ) { + // No events. + } +} +impl Dispatch<WpViewport, GlobalData, WinitState> for ViewporterState { + fn event( + _: &mut WinitState, + _: &WpViewport, + _: <WpViewport as Proxy>::Event, + _: &GlobalData, + _: &Connection, + _: &QueueHandle<WinitState>, + ) { + // No events. + } +} + +delegate_dispatch!(WinitState: [WpViewporter: GlobalData] => ViewporterState); +delegate_dispatch!(WinitState: [WpViewport: GlobalData] => ViewporterState); diff --git a/app/vendor/rune/vendor/winit/src/platform_impl/linux/wayland/types/xdg_activation.rs b/app/vendor/rune/vendor/winit/src/platform_impl/linux/wayland/types/xdg_activation.rs new file mode 100644 index 0000000..9efc75d --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/platform_impl/linux/wayland/types/xdg_activation.rs @@ -0,0 +1,103 @@ +//! Handling of xdg activation, which is used for user attention requests. + +use std::sync::atomic::AtomicBool; +use std::sync::Weak; + +use sctk::reexports::client::globals::{BindError, GlobalList}; +use sctk::reexports::client::protocol::wl_surface::WlSurface; +use sctk::reexports::client::{delegate_dispatch, Connection, Dispatch, Proxy, QueueHandle}; +use sctk::reexports::protocols::xdg::activation::v1::client::xdg_activation_token_v1::{ + Event as ActivationTokenEvent, XdgActivationTokenV1, +}; +use sctk::reexports::protocols::xdg::activation::v1::client::xdg_activation_v1::XdgActivationV1; + +use sctk::globals::GlobalData; + +use crate::event_loop::AsyncRequestSerial; +use crate::platform_impl::wayland::state::WinitState; +use crate::platform_impl::WindowId; +use crate::window::ActivationToken; + +pub struct XdgActivationState { + xdg_activation: XdgActivationV1, +} + +impl XdgActivationState { + pub fn bind( + globals: &GlobalList, + queue_handle: &QueueHandle<WinitState>, + ) -> Result<Self, BindError> { + let xdg_activation = globals.bind(queue_handle, 1..=1, GlobalData)?; + Ok(Self { xdg_activation }) + } + + pub fn global(&self) -> &XdgActivationV1 { + &self.xdg_activation + } +} + +impl Dispatch<XdgActivationV1, GlobalData, WinitState> for XdgActivationState { + fn event( + _state: &mut WinitState, + _proxy: &XdgActivationV1, + _event: <XdgActivationV1 as Proxy>::Event, + _data: &GlobalData, + _conn: &Connection, + _qhandle: &QueueHandle<WinitState>, + ) { + } +} + +impl Dispatch<XdgActivationTokenV1, XdgActivationTokenData, WinitState> for XdgActivationState { + fn event( + state: &mut WinitState, + proxy: &XdgActivationTokenV1, + event: <XdgActivationTokenV1 as Proxy>::Event, + data: &XdgActivationTokenData, + _: &Connection, + _: &QueueHandle<WinitState>, + ) { + let token = match event { + ActivationTokenEvent::Done { token } => token, + _ => return, + }; + + let global = state + .xdg_activation + .as_ref() + .expect("got xdg_activation event without global.") + .global(); + + match data { + XdgActivationTokenData::Attention((surface, fence)) => { + global.activate(token, surface); + // Mark that no request attention is in process. + if let Some(attention_requested) = fence.upgrade() { + attention_requested.store(false, std::sync::atomic::Ordering::Relaxed); + } + }, + XdgActivationTokenData::Obtain((window_id, serial)) => { + state.events_sink.push_window_event( + crate::event::WindowEvent::ActivationTokenDone { + serial: *serial, + token: ActivationToken::from_raw(token), + }, + *window_id, + ); + }, + } + + proxy.destroy(); + } +} + +/// The data associated with the activation request. +pub enum XdgActivationTokenData { + /// Request user attention for the given surface. + Attention((WlSurface, Weak<AtomicBool>)), + /// Get a token to be passed outside of the winit. + Obtain((WindowId, AsyncRequestSerial)), +} + +delegate_dispatch!(WinitState: [ XdgActivationV1: GlobalData] => XdgActivationState); +delegate_dispatch!(WinitState: [ XdgActivationTokenV1: XdgActivationTokenData] => XdgActivationState); diff --git a/app/vendor/rune/vendor/winit/src/platform_impl/linux/wayland/window/mod.rs b/app/vendor/rune/vendor/winit/src/platform_impl/linux/wayland/window/mod.rs new file mode 100644 index 0000000..2418b6f --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/platform_impl/linux/wayland/window/mod.rs @@ -0,0 +1,775 @@ +//! The Wayland window. + +use std::ffi::c_void; +use std::ptr::NonNull; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::{Arc, Mutex}; + +use sctk::reexports::client::protocol::wl_display::WlDisplay; +use sctk::reexports::client::protocol::wl_surface::WlSurface; +use sctk::reexports::client::{Proxy, QueueHandle}; + +use sctk::compositor::{CompositorState, Region, SurfaceData}; +use sctk::reexports::protocols::xdg::activation::v1::client::xdg_activation_v1::XdgActivationV1; +use sctk::shell::xdg::window::{Window as SctkWindow, WindowDecorations}; +use sctk::shell::WaylandSurface; + +use tracing::warn; + +use crate::dpi::{LogicalSize, PhysicalPosition, PhysicalSize, Position, Size}; +use crate::error::{ExternalError, NotSupportedError, OsError as RootOsError}; +use crate::event::{Ime, WindowEvent}; +use crate::event_loop::AsyncRequestSerial; +use crate::platform_impl::{ + Fullscreen, MonitorHandle as PlatformMonitorHandle, OsError, PlatformIcon, +}; +use crate::window::{ + Cursor, CursorGrabMode, ImePurpose, ResizeDirection, Theme, UserAttentionType, + WindowAttributes, WindowButtons, WindowLevel, +}; + +use super::event_loop::sink::EventSink; +use super::output::MonitorHandle; +use super::state::WinitState; +use super::types::xdg_activation::XdgActivationTokenData; +use super::{ActiveEventLoop, WaylandError, WindowId}; + +pub(crate) mod state; + +pub use state::WindowState; + +/// The Wayland window. +pub struct Window { + /// Reference to the underlying SCTK window. + window: SctkWindow, + + /// Window id. + window_id: WindowId, + + /// The state of the window. + window_state: Arc<Mutex<WindowState>>, + + /// Compositor to handle WlRegion stuff. + compositor: Arc<CompositorState>, + + /// The wayland display used solely for raw window handle. + #[allow(dead_code)] + display: WlDisplay, + + /// Xdg activation to request user attention. + xdg_activation: Option<XdgActivationV1>, + + /// The state of the requested attention from the `xdg_activation`. + attention_requested: Arc<AtomicBool>, + + /// Handle to the main queue to perform requests. + queue_handle: QueueHandle<WinitState>, + + /// Window requests to the event loop. + window_requests: Arc<WindowRequests>, + + /// Observed monitors. + monitors: Arc<Mutex<Vec<MonitorHandle>>>, + + /// Source to wake-up the event-loop for window requests. + event_loop_awakener: calloop::ping::Ping, + + /// The event sink to deliver synthetic events. + window_events_sink: Arc<Mutex<EventSink>>, +} + +impl Window { + pub(crate) fn new( + event_loop_window_target: &ActiveEventLoop, + attributes: WindowAttributes, + ) -> Result<Self, RootOsError> { + let queue_handle = event_loop_window_target.queue_handle.clone(); + let mut state = event_loop_window_target.state.borrow_mut(); + + let monitors = state.monitors.clone(); + + let surface = state.compositor_state.create_surface(&queue_handle); + let compositor = state.compositor_state.clone(); + let xdg_activation = + state.xdg_activation.as_ref().map(|activation_state| activation_state.global().clone()); + let display = event_loop_window_target.connection.display(); + + let size: Size = attributes.inner_size.unwrap_or(LogicalSize::new(800., 600.).into()); + + // We prefer server side decorations, however to not have decorations we ask for client + // side decorations instead. + let default_decorations = if attributes.decorations { + WindowDecorations::RequestServer + } else { + WindowDecorations::RequestClient + }; + + let window = + state.xdg_shell.create_window(surface.clone(), default_decorations, &queue_handle); + + let mut window_state = WindowState::new( + event_loop_window_target.connection.clone(), + &event_loop_window_target.queue_handle, + &state, + size, + window.clone(), + attributes.preferred_theme, + ); + + // Set transparency hint. + window_state.set_transparent(attributes.transparent); + + window_state.set_blur(attributes.blur); + + // Set the decorations hint. + window_state.set_decorate(attributes.decorations); + + // Set the app_id. + if let Some(name) = attributes.platform_specific.name.map(|name| name.general) { + window.set_app_id(name); + } + + // Set the window title. + window_state.set_title(attributes.title); + + // Set the min and max sizes. We must set the hints upon creating a window, so + // we use the default `1.` scaling... + let min_size = attributes.min_inner_size.map(|size| size.to_logical(1.)); + let max_size = attributes.max_inner_size.map(|size| size.to_logical(1.)); + window_state.set_min_inner_size(min_size); + window_state.set_max_inner_size(max_size); + + // Non-resizable implies that the min and max sizes are set to the same value. + window_state.set_resizable(attributes.resizable); + + // Set startup mode. + match attributes.fullscreen.map(Into::into) { + Some(Fullscreen::Exclusive(_)) => { + warn!("`Fullscreen::Exclusive` is ignored on Wayland"); + }, + #[cfg_attr(not(x11_platform), allow(clippy::bind_instead_of_map))] + Some(Fullscreen::Borderless(monitor)) => { + let output = monitor.and_then(|monitor| match monitor { + PlatformMonitorHandle::Wayland(monitor) => Some(monitor.proxy), + #[cfg(x11_platform)] + PlatformMonitorHandle::X(_) => None, + }); + + window.set_fullscreen(output.as_ref()) + }, + _ if attributes.maximized => window.set_maximized(), + _ => (), + }; + + match attributes.cursor { + Cursor::Icon(icon) => window_state.set_cursor(icon), + Cursor::Custom(cursor) => window_state.set_custom_cursor(cursor), + } + + // Apply resize increments. + if let Some(increments) = attributes.resize_increments { + let increments = increments.to_logical(window_state.scale_factor()); + window_state.set_resize_increments(Some(increments)); + } + + // Activate the window when the token is passed. + if let (Some(xdg_activation), Some(token)) = + (xdg_activation.as_ref(), attributes.platform_specific.activation_token) + { + xdg_activation.activate(token.token, &surface); + } + + // XXX Do initial commit. + window.commit(); + + // Add the window and window requests into the state. + let window_state = Arc::new(Mutex::new(window_state)); + let window_id = super::make_wid(&surface); + state.windows.get_mut().insert(window_id, window_state.clone()); + + let window_requests = WindowRequests { + redraw_requested: AtomicBool::new(true), + closed: AtomicBool::new(false), + }; + let window_requests = Arc::new(window_requests); + state.window_requests.get_mut().insert(window_id, window_requests.clone()); + + // Setup the event sync to insert `WindowEvents` right from the window. + let window_events_sink = state.window_events_sink.clone(); + + let mut wayland_source = event_loop_window_target.wayland_dispatcher.as_source_mut(); + let event_queue = wayland_source.queue(); + + // Do a roundtrip. + event_queue.roundtrip(&mut state).map_err(|error| { + os_error!(OsError::WaylandError(Arc::new(WaylandError::Dispatch(error)))) + })?; + + // XXX Wait for the initial configure to arrive. + while !window_state.lock().unwrap().is_configured() { + event_queue.blocking_dispatch(&mut state).map_err(|error| { + os_error!(OsError::WaylandError(Arc::new(WaylandError::Dispatch(error)))) + })?; + } + + // Wake-up event loop, so it'll send initial redraw requested. + let event_loop_awakener = event_loop_window_target.event_loop_awakener.clone(); + event_loop_awakener.ping(); + + Ok(Self { + window, + display, + monitors, + window_id, + compositor, + window_state, + queue_handle, + xdg_activation, + attention_requested: Arc::new(AtomicBool::new(false)), + event_loop_awakener, + window_requests, + window_events_sink, + }) + } + + pub(crate) fn xdg_toplevel(&self) -> Option<NonNull<c_void>> { + NonNull::new(self.window.xdg_toplevel().id().as_ptr().cast()) + } +} + +impl Window { + #[inline] + pub fn id(&self) -> WindowId { + self.window_id + } + + #[inline] + pub fn set_title(&self, title: impl ToString) { + let new_title = title.to_string(); + self.window_state.lock().unwrap().set_title(new_title); + } + + #[inline] + pub fn set_visible(&self, _visible: bool) { + // Not possible on Wayland. + } + + #[inline] + pub fn is_visible(&self) -> Option<bool> { + None + } + + #[inline] + pub fn outer_position(&self) -> Result<PhysicalPosition<i32>, NotSupportedError> { + Err(NotSupportedError::new()) + } + + #[inline] + pub fn inner_position(&self) -> Result<PhysicalPosition<i32>, NotSupportedError> { + Err(NotSupportedError::new()) + } + + #[inline] + pub fn set_outer_position(&self, _: Position) { + // Not possible on Wayland. + } + + #[inline] + pub fn inner_size(&self) -> PhysicalSize<u32> { + let window_state = self.window_state.lock().unwrap(); + let scale_factor = window_state.scale_factor(); + super::logical_to_physical_rounded(window_state.inner_size(), scale_factor) + } + + #[inline] + pub fn request_redraw(&self) { + // NOTE: try to not wake up the loop when the event was already scheduled and not yet + // processed by the loop, because if at this point the value was `true` it could only + // mean that the loop still haven't dispatched the value to the client and will do + // eventually, resetting it to `false`. + if self + .window_requests + .redraw_requested + .compare_exchange(false, true, Ordering::Relaxed, Ordering::Relaxed) + .is_ok() + { + self.event_loop_awakener.ping(); + } + } + + #[inline] + pub fn pre_present_notify(&self) { + self.window_state.lock().unwrap().request_frame_callback(); + } + + #[inline] + pub fn outer_size(&self) -> PhysicalSize<u32> { + let window_state = self.window_state.lock().unwrap(); + let scale_factor = window_state.scale_factor(); + super::logical_to_physical_rounded(window_state.outer_size(), scale_factor) + } + + #[inline] + pub fn request_inner_size(&self, size: Size) -> Option<PhysicalSize<u32>> { + let mut window_state = self.window_state.lock().unwrap(); + let new_size = window_state.request_inner_size(size); + self.request_redraw(); + Some(new_size) + } + + /// Set the minimum inner size for the window. + #[inline] + pub fn set_min_inner_size(&self, min_size: Option<Size>) { + let scale_factor = self.scale_factor(); + let min_size = min_size.map(|size| size.to_logical(scale_factor)); + self.window_state.lock().unwrap().set_min_inner_size(min_size); + // NOTE: Requires commit to be applied. + self.request_redraw(); + } + + /// Set the maximum inner size for the window. + #[inline] + pub fn set_max_inner_size(&self, max_size: Option<Size>) { + let scale_factor = self.scale_factor(); + let max_size = max_size.map(|size| size.to_logical(scale_factor)); + self.window_state.lock().unwrap().set_max_inner_size(max_size); + // NOTE: Requires commit to be applied. + self.request_redraw(); + } + + #[inline] + pub fn resize_increments(&self) -> Option<PhysicalSize<u32>> { + let window_state = self.window_state.lock().unwrap(); + let scale_factor = window_state.scale_factor(); + window_state + .resize_increments() + .map(|size| super::logical_to_physical_rounded(size, scale_factor)) + } + + #[inline] + pub fn set_resize_increments(&self, increments: Option<Size>) { + let mut window_state = self.window_state.lock().unwrap(); + let scale_factor = window_state.scale_factor(); + let increments = increments.map(|size| size.to_logical(scale_factor)); + window_state.set_resize_increments(increments); + } + + #[inline] + pub fn set_transparent(&self, transparent: bool) { + self.window_state.lock().unwrap().set_transparent(transparent); + } + + #[inline] + pub fn has_focus(&self) -> bool { + self.window_state.lock().unwrap().has_focus() + } + + #[inline] + pub fn is_minimized(&self) -> Option<bool> { + // XXX clients don't know whether they are minimized or not. + None + } + + #[inline] + pub fn show_window_menu(&self, position: Position) { + let scale_factor = self.scale_factor(); + let position = position.to_logical(scale_factor); + self.window_state.lock().unwrap().show_window_menu(position); + } + + #[inline] + pub fn drag_resize_window(&self, direction: ResizeDirection) -> Result<(), ExternalError> { + self.window_state.lock().unwrap().drag_resize_window(direction) + } + + #[inline] + pub fn set_resizable(&self, resizable: bool) { + if self.window_state.lock().unwrap().set_resizable(resizable) { + // NOTE: Requires commit to be applied. + self.request_redraw(); + } + } + + #[inline] + pub fn is_resizable(&self) -> bool { + self.window_state.lock().unwrap().resizable() + } + + #[inline] + pub fn set_enabled_buttons(&self, _buttons: WindowButtons) { + // TODO(kchibisov) v5 of the xdg_shell allows that. + } + + #[inline] + pub fn enabled_buttons(&self) -> WindowButtons { + // TODO(kchibisov) v5 of the xdg_shell allows that. + WindowButtons::all() + } + + #[inline] + pub fn scale_factor(&self) -> f64 { + self.window_state.lock().unwrap().scale_factor() + } + + #[inline] + pub fn set_blur(&self, blur: bool) { + self.window_state.lock().unwrap().set_blur(blur); + } + + #[inline] + pub fn set_decorations(&self, decorate: bool) { + self.window_state.lock().unwrap().set_decorate(decorate) + } + + #[inline] + pub fn is_decorated(&self) -> bool { + self.window_state.lock().unwrap().is_decorated() + } + + /// Rune: see `WindowExtWayland::content_corner_radius`. + #[inline] + pub fn content_corner_radius(&self) -> f32 { + self.window_state.lock().unwrap().content_corner_radius() + } + + /// Rune: see `WindowExtWayland::has_client_side_frame`. + #[inline] + pub fn has_client_side_frame(&self) -> bool { + self.window_state.lock().unwrap().has_client_side_frame() + } + + #[inline] + pub fn set_window_level(&self, _level: WindowLevel) {} + + #[inline] + pub(crate) fn set_window_icon(&self, _window_icon: Option<PlatformIcon>) {} + + #[inline] + pub fn set_minimized(&self, minimized: bool) { + // You can't unminimize the window on Wayland. + if !minimized { + warn!("Unminimizing is ignored on Wayland."); + return; + } + + self.window.set_minimized(); + } + + #[inline] + pub fn is_maximized(&self) -> bool { + self.window_state + .lock() + .unwrap() + .last_configure + .as_ref() + .map(|last_configure| last_configure.is_maximized()) + .unwrap_or_default() + } + + #[inline] + pub fn set_maximized(&self, maximized: bool) { + if maximized { + self.window.set_maximized() + } else { + self.window.unset_maximized() + } + } + + #[inline] + pub(crate) fn fullscreen(&self) -> Option<Fullscreen> { + let is_fullscreen = self + .window_state + .lock() + .unwrap() + .last_configure + .as_ref() + .map(|last_configure| last_configure.is_fullscreen()) + .unwrap_or_default(); + + if is_fullscreen { + let current_monitor = self.current_monitor().map(PlatformMonitorHandle::Wayland); + Some(Fullscreen::Borderless(current_monitor)) + } else { + None + } + } + + #[inline] + pub(crate) fn set_fullscreen(&self, fullscreen: Option<Fullscreen>) { + match fullscreen { + Some(Fullscreen::Exclusive(_)) => { + warn!("`Fullscreen::Exclusive` is ignored on Wayland"); + }, + #[cfg_attr(not(x11_platform), allow(clippy::bind_instead_of_map))] + Some(Fullscreen::Borderless(monitor)) => { + let output = monitor.and_then(|monitor| match monitor { + PlatformMonitorHandle::Wayland(monitor) => Some(monitor.proxy), + #[cfg(x11_platform)] + PlatformMonitorHandle::X(_) => None, + }); + + self.window.set_fullscreen(output.as_ref()) + }, + None => self.window.unset_fullscreen(), + } + } + + #[inline] + pub fn set_cursor(&self, cursor: Cursor) { + let window_state = &mut self.window_state.lock().unwrap(); + + match cursor { + Cursor::Icon(icon) => window_state.set_cursor(icon), + Cursor::Custom(cursor) => window_state.set_custom_cursor(cursor), + } + } + + #[inline] + pub fn set_cursor_visible(&self, visible: bool) { + self.window_state.lock().unwrap().set_cursor_visible(visible); + } + + pub fn request_user_attention(&self, request_type: Option<UserAttentionType>) { + let xdg_activation = match self.xdg_activation.as_ref() { + Some(xdg_activation) => xdg_activation, + None => { + warn!("`request_user_attention` isn't supported"); + return; + }, + }; + + // Urgency is only removed by the compositor and there's no need to raise urgency when it + // was already raised. + if request_type.is_none() || self.attention_requested.load(Ordering::Relaxed) { + return; + } + + self.attention_requested.store(true, Ordering::Relaxed); + let surface = self.surface().clone(); + let data = XdgActivationTokenData::Attention(( + surface.clone(), + Arc::downgrade(&self.attention_requested), + )); + let xdg_activation_token = xdg_activation.get_activation_token(&self.queue_handle, data); + xdg_activation_token.set_surface(&surface); + xdg_activation_token.commit(); + } + + pub fn request_activation_token(&self) -> Result<AsyncRequestSerial, NotSupportedError> { + let xdg_activation = match self.xdg_activation.as_ref() { + Some(xdg_activation) => xdg_activation, + None => return Err(NotSupportedError::new()), + }; + + let serial = AsyncRequestSerial::get(); + + let data = XdgActivationTokenData::Obtain((self.window_id, serial)); + let xdg_activation_token = xdg_activation.get_activation_token(&self.queue_handle, data); + xdg_activation_token.set_surface(self.surface()); + xdg_activation_token.commit(); + + Ok(serial) + } + + #[inline] + pub fn set_cursor_grab(&self, mode: CursorGrabMode) -> Result<(), ExternalError> { + self.window_state.lock().unwrap().set_cursor_grab(mode) + } + + #[inline] + pub fn set_cursor_position(&self, position: Position) -> Result<(), ExternalError> { + let scale_factor = self.scale_factor(); + let position = position.to_logical(scale_factor); + self.window_state + .lock() + .unwrap() + .set_cursor_position(position) + // Request redraw on success, since the state is double buffered. + .map(|_| self.request_redraw()) + } + + #[inline] + pub fn drag_window(&self) -> Result<(), ExternalError> { + self.window_state.lock().unwrap().drag_window() + } + + #[inline] + pub fn set_cursor_hittest(&self, hittest: bool) -> Result<(), ExternalError> { + let surface = self.window.wl_surface(); + + if hittest { + surface.set_input_region(None); + Ok(()) + } else { + let region = Region::new(&*self.compositor).map_err(|_| { + ExternalError::Os(os_error!(OsError::Misc("failed to set input region."))) + })?; + region.add(0, 0, 0, 0); + surface.set_input_region(Some(region.wl_region())); + Ok(()) + } + } + + #[inline] + pub fn set_ime_cursor_area(&self, position: Position, size: Size) { + let window_state = self.window_state.lock().unwrap(); + if window_state.ime_allowed() { + let scale_factor = window_state.scale_factor(); + let position = position.to_logical(scale_factor); + let size = size.to_logical(scale_factor); + window_state.set_ime_cursor_area(position, size); + } + } + + #[inline] + pub fn set_ime_allowed(&self, allowed: bool) { + let mut window_state = self.window_state.lock().unwrap(); + + if window_state.ime_allowed() != allowed && window_state.set_ime_allowed(allowed) { + let event = WindowEvent::Ime(if allowed { Ime::Enabled } else { Ime::Disabled }); + self.window_events_sink.lock().unwrap().push_window_event(event, self.window_id); + self.event_loop_awakener.ping(); + } + } + + #[inline] + pub fn set_ime_purpose(&self, purpose: ImePurpose) { + self.window_state.lock().unwrap().set_ime_purpose(purpose); + } + + #[inline] + pub fn focus_window(&self) {} + + #[inline] + pub fn surface(&self) -> &WlSurface { + self.window.wl_surface() + } + + #[inline] + pub fn current_monitor(&self) -> Option<MonitorHandle> { + let data = self.window.wl_surface().data::<SurfaceData>()?; + data.outputs().next().map(MonitorHandle::new) + } + + #[inline] + pub fn available_monitors(&self) -> Vec<MonitorHandle> { + self.monitors.lock().unwrap().clone() + } + + #[inline] + pub fn primary_monitor(&self) -> Option<MonitorHandle> { + // XXX there's no such concept on Wayland. + None + } + + #[cfg(feature = "rwh_04")] + #[inline] + pub fn raw_window_handle_rwh_04(&self) -> rwh_04::RawWindowHandle { + let mut window_handle = rwh_04::WaylandHandle::empty(); + window_handle.surface = self.window.wl_surface().id().as_ptr() as *mut _; + window_handle.display = self.display.id().as_ptr() as *mut _; + rwh_04::RawWindowHandle::Wayland(window_handle) + } + + #[cfg(feature = "rwh_05")] + #[inline] + pub fn raw_window_handle_rwh_05(&self) -> rwh_05::RawWindowHandle { + let mut window_handle = rwh_05::WaylandWindowHandle::empty(); + window_handle.surface = self.window.wl_surface().id().as_ptr() as *mut _; + rwh_05::RawWindowHandle::Wayland(window_handle) + } + + #[cfg(feature = "rwh_05")] + #[inline] + pub fn raw_display_handle_rwh_05(&self) -> rwh_05::RawDisplayHandle { + let mut display_handle = rwh_05::WaylandDisplayHandle::empty(); + display_handle.display = self.display.id().as_ptr() as *mut _; + rwh_05::RawDisplayHandle::Wayland(display_handle) + } + + #[cfg(feature = "rwh_06")] + #[inline] + pub fn raw_window_handle_rwh_06(&self) -> Result<rwh_06::RawWindowHandle, rwh_06::HandleError> { + Ok(rwh_06::WaylandWindowHandle::new({ + let ptr = self.window.wl_surface().id().as_ptr(); + std::ptr::NonNull::new(ptr as *mut _).expect("wl_surface will never be null") + }) + .into()) + } + + #[cfg(feature = "rwh_06")] + #[inline] + pub fn raw_display_handle_rwh_06( + &self, + ) -> Result<rwh_06::RawDisplayHandle, rwh_06::HandleError> { + Ok(rwh_06::WaylandDisplayHandle::new({ + let ptr = self.display.id().as_ptr(); + std::ptr::NonNull::new(ptr as *mut _).expect("wl_proxy should never be null") + }) + .into()) + } + + #[inline] + pub fn set_theme(&self, theme: Option<Theme>) { + self.window_state.lock().unwrap().set_theme(theme) + } + + #[inline] + pub fn theme(&self) -> Option<Theme> { + self.window_state.lock().unwrap().theme() + } + + pub fn set_content_protected(&self, _protected: bool) {} + + #[inline] + pub fn title(&self) -> String { + self.window_state.lock().unwrap().title().to_owned() + } +} + +impl Drop for Window { + fn drop(&mut self) { + self.window_requests.closed.store(true, Ordering::Relaxed); + self.event_loop_awakener.ping(); + } +} + +/// The request from the window to the event loop. +#[derive(Debug)] +pub struct WindowRequests { + /// The window was closed. + pub closed: AtomicBool, + + /// Redraw Requested. + pub redraw_requested: AtomicBool, +} + +impl WindowRequests { + pub fn take_closed(&self) -> bool { + self.closed.swap(false, Ordering::Relaxed) + } + + pub fn take_redraw_requested(&self) -> bool { + self.redraw_requested.swap(false, Ordering::Relaxed) + } +} + +impl TryFrom<&str> for Theme { + type Error = (); + + /// ``` + /// use winit::window::Theme; + /// + /// assert_eq!("dark".try_into(), Ok(Theme::Dark)); + /// assert_eq!("lIghT".try_into(), Ok(Theme::Light)); + /// ``` + fn try_from(theme: &str) -> Result<Self, Self::Error> { + if theme.eq_ignore_ascii_case("dark") { + Ok(Self::Dark) + } else if theme.eq_ignore_ascii_case("light") { + Ok(Self::Light) + } else { + Err(()) + } + } +} diff --git a/app/vendor/rune/vendor/winit/src/platform_impl/linux/wayland/window/state.rs b/app/vendor/rune/vendor/winit/src/platform_impl/linux/wayland/window/state.rs new file mode 100644 index 0000000..9cd83c4 --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/platform_impl/linux/wayland/window/state.rs @@ -0,0 +1,1270 @@ +//! The state of the window, which is shared with the event-loop. + +use std::num::NonZeroU32; +use std::sync::{Arc, Mutex, Weak}; +use std::time::Duration; + +use ahash::HashSet; +use tracing::{info, warn}; + +use sctk::reexports::client::backend::ObjectId; +use sctk::reexports::client::protocol::wl_seat::WlSeat; +use sctk::reexports::client::protocol::wl_shm::WlShm; +use sctk::reexports::client::protocol::wl_surface::WlSurface; +use sctk::reexports::client::{Connection, Proxy, QueueHandle}; +use sctk::reexports::csd_frame::{ + DecorationsFrame, FrameAction, FrameClick, ResizeEdge, WindowState as XdgWindowState, +}; +use sctk::reexports::protocols::wp::fractional_scale::v1::client::wp_fractional_scale_v1::WpFractionalScaleV1; +use sctk::reexports::protocols::wp::text_input::zv3::client::zwp_text_input_v3::ZwpTextInputV3; +use sctk::reexports::protocols::wp::viewporter::client::wp_viewport::WpViewport; +use sctk::reexports::protocols::xdg::shell::client::xdg_toplevel::ResizeEdge as XdgResizeEdge; + +use sctk::compositor::{CompositorState, Region, SurfaceData, SurfaceDataExt}; +use sctk::seat::pointer::{PointerDataExt, ThemedPointer}; +use sctk::shell::xdg::window::{DecorationMode, Window, WindowConfigure}; +use sctk::shell::xdg::XdgSurface; +use sctk::shell::WaylandSurface; +use sctk::shm::slot::SlotPool; +use sctk::shm::Shm; +use sctk::subcompositor::SubcompositorState; +use wayland_protocols_plasma::blur::client::org_kde_kwin_blur::OrgKdeKwinBlur; + +use crate::cursor::CustomCursor as RootCustomCursor; +use crate::dpi::{LogicalPosition, LogicalSize, PhysicalPosition, PhysicalSize, Size}; +use crate::error::{ExternalError, NotSupportedError}; +use crate::platform_impl::wayland::logical_to_physical_rounded; +use crate::platform_impl::wayland::types::cursor::{CustomCursor, SelectedCursor}; +use crate::platform_impl::wayland::types::kwin_blur::KWinBlurManager; +use crate::platform_impl::{PlatformCustomCursor, WindowId}; +use crate::window::{CursorGrabMode, CursorIcon, ImePurpose, ResizeDirection, Theme}; + +use crate::platform_impl::wayland::seat::{ + PointerConstraintsState, WinitPointerData, WinitPointerDataExt, ZwpTextInputV3Ext, +}; +use crate::platform_impl::wayland::state::{WindowCompositorUpdate, WinitState}; + +#[cfg(feature = "sctk-adwaita")] +pub type WinitFrame = sctk_adwaita::AdwaitaFrame<WinitState>; +#[cfg(not(feature = "sctk-adwaita"))] +pub type WinitFrame = sctk::shell::xdg::fallback_frame::FallbackFrame<WinitState>; + +// Minimum window inner size. +const MIN_WINDOW_SIZE: LogicalSize<u32> = LogicalSize::new(2, 1); + +/// The state of the window which is being updated from the [`WinitState`]. +pub struct WindowState { + /// The connection to Wayland server. + pub connection: Connection, + + /// The `Shm` to set cursor. + pub shm: WlShm, + + // A shared pool where to allocate custom cursors. + custom_cursor_pool: Arc<Mutex<SlotPool>>, + + /// The last received configure. + pub last_configure: Option<WindowConfigure>, + + /// The pointers observed on the window. + pub pointers: Vec<Weak<ThemedPointer<WinitPointerData>>>, + + selected_cursor: SelectedCursor, + + /// Whether the cursor is visible. + pub cursor_visible: bool, + + /// Pointer constraints to lock/confine pointer. + pub pointer_constraints: Option<Arc<PointerConstraintsState>>, + + /// Queue handle. + pub queue_handle: QueueHandle<WinitState>, + + /// Theme variant. + theme: Option<Theme>, + + /// The current window title. + title: String, + + /// Whether the frame is resizable. + resizable: bool, + + // NOTE: we can't use simple counter, since it's racy when seat getting destroyed and new + // is created, since add/removed stuff could be delivered a bit out of order. + /// Seats that has keyboard focus on that window. + seat_focus: HashSet<ObjectId>, + + /// The scale factor of the window. + scale_factor: f64, + + /// Whether the window is transparent. + transparent: bool, + + /// The state of the compositor to create WlRegions. + compositor: Arc<CompositorState>, + + /// The current cursor grabbing mode. + cursor_grab_mode: GrabState, + + /// Whether the IME input is allowed for that window. + ime_allowed: bool, + + /// The current IME purpose. + ime_purpose: ImePurpose, + + /// The text inputs observed on the window. + text_inputs: Vec<ZwpTextInputV3>, + + /// The inner size of the window, as in without client side decorations. + size: LogicalSize<u32>, + + /// Whether the CSD fail to create, so we don't try to create them on each iteration. + csd_fails: bool, + + /// Whether we should decorate the frame. + decorate: bool, + + /// Min size. + min_inner_size: LogicalSize<u32>, + max_inner_size: Option<LogicalSize<u32>>, + resize_increments: Option<LogicalSize<u32>>, + + /// The size of the window when no states were applied to it. The primary use for it + /// is to fallback to original window size, before it was maximized, if the compositor + /// sends `None` for the new size in the configure. + stateless_size: LogicalSize<u32>, + + /// Initial window size provided by the user. Removed on the first + /// configure. + initial_size: Option<Size>, + + /// The state of the frame callback. + frame_callback_state: FrameCallbackState, + + viewport: Option<WpViewport>, + fractional_scale: Option<WpFractionalScaleV1>, + blur: Option<OrgKdeKwinBlur>, + blur_manager: Option<KWinBlurManager>, + + /// Whether the client side decorations have pending move operations. + /// + /// The value is the serial of the event triggered moved. + has_pending_move: Option<u32>, + + /// The underlying SCTK window. + pub window: Window, + + // NOTE: The spec says that destroying parent(`window` in our case), will unmap the + // subsurfaces. Thus to achieve atomic unmap of the client, drop the decorations + // frame after the `window` is dropped. To achieve that we rely on rust's struct + // field drop order guarantees. + /// The window frame, which is created from the configure request. + frame: Option<WinitFrame>, +} + +impl WindowState { + /// Create new window state. + pub fn new( + connection: Connection, + queue_handle: &QueueHandle<WinitState>, + winit_state: &WinitState, + initial_size: Size, + window: Window, + theme: Option<Theme>, + ) -> Self { + let compositor = winit_state.compositor_state.clone(); + let pointer_constraints = winit_state.pointer_constraints.clone(); + let viewport = winit_state + .viewporter_state + .as_ref() + .map(|state| state.get_viewport(window.wl_surface(), queue_handle)); + let fractional_scale = winit_state + .fractional_scaling_manager + .as_ref() + .map(|fsm| fsm.fractional_scaling(window.wl_surface(), queue_handle)); + + Self { + blur: None, + blur_manager: winit_state.kwin_blur_manager.clone(), + compositor, + connection, + csd_fails: false, + cursor_grab_mode: GrabState::new(), + selected_cursor: Default::default(), + cursor_visible: true, + decorate: true, + fractional_scale, + frame: None, + frame_callback_state: FrameCallbackState::None, + seat_focus: Default::default(), + has_pending_move: None, + ime_allowed: false, + ime_purpose: ImePurpose::Normal, + last_configure: None, + max_inner_size: None, + min_inner_size: MIN_WINDOW_SIZE, + resize_increments: None, + pointer_constraints, + pointers: Default::default(), + queue_handle: queue_handle.clone(), + resizable: true, + scale_factor: 1., + shm: winit_state.shm.wl_shm().clone(), + custom_cursor_pool: winit_state.custom_cursor_pool.clone(), + size: initial_size.to_logical(1.), + stateless_size: initial_size.to_logical(1.), + initial_size: Some(initial_size), + text_inputs: Vec::new(), + theme, + title: String::default(), + transparent: false, + viewport, + window, + } + } + + /// Apply closure on the given pointer. + fn apply_on_pointer<F: FnMut(&ThemedPointer<WinitPointerData>, &WinitPointerData)>( + &self, + mut callback: F, + ) { + self.pointers.iter().filter_map(Weak::upgrade).for_each(|pointer| { + let data = pointer.pointer().winit_data(); + callback(pointer.as_ref(), data); + }) + } + + /// Get the current state of the frame callback. + pub fn frame_callback_state(&self) -> FrameCallbackState { + self.frame_callback_state + } + + /// The frame callback was received, but not yet sent to the user. + pub fn frame_callback_received(&mut self) { + self.frame_callback_state = FrameCallbackState::Received; + } + + /// Reset the frame callbacks state. + pub fn frame_callback_reset(&mut self) { + self.frame_callback_state = FrameCallbackState::None; + } + + /// Request a frame callback if we don't have one for this window in flight. + pub fn request_frame_callback(&mut self) { + let surface = self.window.wl_surface(); + match self.frame_callback_state { + FrameCallbackState::None | FrameCallbackState::Received => { + self.frame_callback_state = FrameCallbackState::Requested; + surface.frame(&self.queue_handle, surface.clone()); + }, + FrameCallbackState::Requested => (), + } + } + + pub fn configure( + &mut self, + configure: WindowConfigure, + shm: &Shm, + subcompositor: &Option<Arc<SubcompositorState>>, + ) -> bool { + // NOTE: when using fractional scaling or wl_compositor@v6 the scaling + // should be delivered before the first configure, thus apply it to + // properly scale the physical sizes provided by the users. + if let Some(initial_size) = self.initial_size.take() { + self.size = initial_size.to_logical(self.scale_factor()); + self.stateless_size = self.size; + } + + if let Some(subcompositor) = subcompositor.as_ref().filter(|_| { + configure.decoration_mode == DecorationMode::Client + && self.frame.is_none() + && !self.csd_fails + }) { + match WinitFrame::new( + &self.window, + shm, + #[cfg(feature = "sctk-adwaita")] + self.compositor.clone(), + subcompositor.clone(), + self.queue_handle.clone(), + #[cfg(feature = "sctk-adwaita")] + into_sctk_adwaita_config(self.theme), + ) { + Ok(mut frame) => { + frame.set_title(&self.title); + frame.set_scaling_factor(self.scale_factor); + // Hide the frame if we were asked to not decorate. + frame.set_hidden(!self.decorate); + self.frame = Some(frame); + }, + Err(err) => { + warn!("Failed to create client side decorations frame: {err}"); + self.csd_fails = true; + }, + } + } else if configure.decoration_mode == DecorationMode::Server { + // Drop the frame for server side decorations to save resources. + self.frame = None; + } + + let stateless = Self::is_stateless(&configure); + + let (mut new_size, constrain) = if let Some(frame) = self.frame.as_mut() { + // Configure the window states. + frame.update_state(configure.state); + + match configure.new_size { + (Some(width), Some(height)) => { + let (width, height) = frame.subtract_borders(width, height); + let width = width.map(|w| w.get()).unwrap_or(1); + let height = height.map(|h| h.get()).unwrap_or(1); + ((width, height).into(), false) + }, + (..) if stateless => (self.stateless_size, true), + _ => (self.size, true), + } + } else { + match configure.new_size { + (Some(width), Some(height)) => ((width.get(), height.get()).into(), false), + _ if stateless => (self.stateless_size, true), + _ => (self.size, true), + } + }; + + // Apply configure bounds only when compositor let the user decide what size to pick. + if constrain { + let bounds = self.inner_size_bounds(&configure); + new_size.width = + bounds.0.map(|bound_w| new_size.width.min(bound_w.get())).unwrap_or(new_size.width); + new_size.height = bounds + .1 + .map(|bound_h| new_size.height.min(bound_h.get())) + .unwrap_or(new_size.height); + } + + // Apply size increments. + // + // We conditionally apply increments to avoid conflicts with the compositor's layout rules: + // 1. If the window is floating (constrain == true), we snap to increments to ensure the + // app's grid alignment. + // 2. If the user is interactively resizing (is_resizing), we snap the size to provide + // feedback. + // + // However, we MUST NOT snap if the compositor enforces a specific size (constrain == false, + // or states like Maximized/Tiled). Snapping in these cases (e.g. corner tiling) would + // shrink the window below the allocated area, creating visible gaps between valid + // windows or screen edges. + if (constrain || configure.is_resizing()) + && !configure.is_maximized() + && !configure.is_fullscreen() + && !configure.is_tiled() + { + if let Some(increments) = self.resize_increments { + // We use min size as a base size for the increments, similar to how X11 does it. + // + // This ensures that we can always reach the min size and the increments are + // calculated from it. + let (delta_width, delta_height) = ( + new_size.width.saturating_sub(self.min_inner_size.width), + new_size.height.saturating_sub(self.min_inner_size.height), + ); + + let width = + self.min_inner_size.width + (delta_width / increments.width) * increments.width; + let height = self.min_inner_size.height + + (delta_height / increments.height) * increments.height; + + new_size = (width, height).into(); + } + } + + let new_state = configure.state; + let old_state = self.last_configure.as_ref().map(|configure| configure.state); + + let state_change_requires_resize = old_state + .map(|old_state| { + !old_state + .symmetric_difference(new_state) + .difference(XdgWindowState::ACTIVATED | XdgWindowState::SUSPENDED) + .is_empty() + }) + // NOTE: `None` is present for the initial configure, thus we must always resize. + .unwrap_or(true); + + // NOTE: Set the configure before doing a resize, since we query it during it. + self.last_configure = Some(configure); + + if state_change_requires_resize || new_size != self.inner_size() { + self.resize(new_size); + true + } else { + // Rune: the frame may have appeared or gone, or turned square, and no resize follows to + // tell the compositor: the opaque region follows it now that it knows this configure's + // state. + self.reload_transparency_hint(); + false + } + } + + /// Compute the bounds for the inner size of the surface. + fn inner_size_bounds( + &self, + configure: &WindowConfigure, + ) -> (Option<NonZeroU32>, Option<NonZeroU32>) { + let configure_bounds = match configure.suggested_bounds { + Some((width, height)) => (NonZeroU32::new(width), NonZeroU32::new(height)), + None => (None, None), + }; + + if let Some(frame) = self.frame.as_ref() { + let (width, height) = frame.subtract_borders( + configure_bounds.0.unwrap_or(NonZeroU32::new(1).unwrap()), + configure_bounds.1.unwrap_or(NonZeroU32::new(1).unwrap()), + ); + (configure_bounds.0.and(width), configure_bounds.1.and(height)) + } else { + configure_bounds + } + } + + #[inline] + fn is_stateless(configure: &WindowConfigure) -> bool { + !(configure.is_maximized() || configure.is_fullscreen() || configure.is_tiled()) + } + + /// Start interacting drag resize. + pub fn drag_resize_window(&self, direction: ResizeDirection) -> Result<(), ExternalError> { + let xdg_toplevel = self.window.xdg_toplevel(); + + // TODO(kchibisov) handle touch serials. + self.apply_on_pointer(|_, data| { + let serial = data.latest_button_serial(); + let seat = data.seat(); + xdg_toplevel.resize(seat, serial, direction.into()); + }); + + Ok(()) + } + + /// Start the window drag. + pub fn drag_window(&self) -> Result<(), ExternalError> { + let xdg_toplevel = self.window.xdg_toplevel(); + // TODO(kchibisov) handle touch serials. + self.apply_on_pointer(|_, data| { + let serial = data.latest_button_serial(); + let seat = data.seat(); + xdg_toplevel._move(seat, serial); + }); + + Ok(()) + } + + /// Tells whether the window should be closed. + #[allow(clippy::too_many_arguments)] + pub fn frame_click( + &mut self, + click: FrameClick, + pressed: bool, + seat: &WlSeat, + serial: u32, + timestamp: Duration, + window_id: WindowId, + updates: &mut Vec<WindowCompositorUpdate>, + ) -> Option<bool> { + match self.frame.as_mut()?.on_click(timestamp, click, pressed)? { + FrameAction::Minimize => self.window.set_minimized(), + FrameAction::Maximize => self.window.set_maximized(), + FrameAction::UnMaximize => self.window.unset_maximized(), + FrameAction::Close => WinitState::queue_close(updates, window_id), + FrameAction::Move => self.has_pending_move = Some(serial), + FrameAction::Resize(edge) => { + let edge = match edge { + ResizeEdge::None => XdgResizeEdge::None, + ResizeEdge::Top => XdgResizeEdge::Top, + ResizeEdge::Bottom => XdgResizeEdge::Bottom, + ResizeEdge::Left => XdgResizeEdge::Left, + ResizeEdge::TopLeft => XdgResizeEdge::TopLeft, + ResizeEdge::BottomLeft => XdgResizeEdge::BottomLeft, + ResizeEdge::Right => XdgResizeEdge::Right, + ResizeEdge::TopRight => XdgResizeEdge::TopRight, + ResizeEdge::BottomRight => XdgResizeEdge::BottomRight, + _ => return None, + }; + self.window.resize(seat, serial, edge); + }, + FrameAction::ShowMenu(x, y) => self.window.show_window_menu(seat, serial, (x, y)), + _ => (), + }; + + Some(false) + } + + pub fn frame_point_left(&mut self) { + if let Some(frame) = self.frame.as_mut() { + frame.click_point_left(); + } + } + + // Move the point over decorations. + pub fn frame_point_moved( + &mut self, + seat: &WlSeat, + surface: &WlSurface, + timestamp: Duration, + x: f64, + y: f64, + ) -> Option<CursorIcon> { + // Take the serial if we had any, so it doesn't stick around. + let serial = self.has_pending_move.take(); + + if let Some(frame) = self.frame.as_mut() { + let cursor = frame.click_point_moved(timestamp, &surface.id(), x, y); + // If we have a cursor change, that means that cursor is over the decorations, + // so try to apply move. + if let Some(serial) = cursor.is_some().then_some(serial).flatten() { + self.window.move_(seat, serial); + None + } else { + cursor + } + } else { + None + } + } + + /// Get the stored resizable state. + #[inline] + pub fn resizable(&self) -> bool { + self.resizable + } + + /// Set the resizable state on the window. + /// + /// Returns `true` when the state was applied. + #[inline] + pub fn set_resizable(&mut self, resizable: bool) -> bool { + if self.resizable == resizable { + return false; + } + + self.resizable = resizable; + if resizable { + // Restore min/max sizes of the window. + self.reload_min_max_hints(); + } else { + self.set_min_inner_size(Some(self.size)); + self.set_max_inner_size(Some(self.size)); + } + + // Reload the state on the frame as well. + if let Some(frame) = self.frame.as_mut() { + frame.set_resizable(resizable); + } + + true + } + + /// Whether the window is focused by any seat. + #[inline] + pub fn has_focus(&self) -> bool { + !self.seat_focus.is_empty() + } + + /// Whether the IME is allowed. + #[inline] + pub fn ime_allowed(&self) -> bool { + self.ime_allowed + } + + /// Get the size of the window. + #[inline] + pub fn inner_size(&self) -> LogicalSize<u32> { + self.size + } + + /// Whether the window received initial configure event from the compositor. + #[inline] + pub fn is_configured(&self) -> bool { + self.last_configure.is_some() + } + + #[inline] + pub fn is_decorated(&mut self) -> bool { + let csd = self + .last_configure + .as_ref() + .map(|configure| configure.decoration_mode == DecorationMode::Client) + .unwrap_or(false); + if let Some(frame) = csd.then_some(self.frame.as_ref()).flatten() { + !frame.is_hidden() + } else { + // Server side decorations. + true + } + } + + /// Rune: whether a client-side frame draws the window's decorations, whatever state it is in: + /// a maximized, tiled or fullscreen window keeps its frame (it draws square corners there), + /// which only hides parts of itself. False when the compositor draws the decorations, when + /// decorations are off, and when the frame could not be made (no subcompositor, or a frame that + /// failed to build). + #[inline] + pub fn has_client_side_frame(&self) -> bool { + self.decorate + && self + .last_configure + .as_ref() + .is_some_and(|configure| configure.decoration_mode == DecorationMode::Client) + && self.frame.is_some() + } + + /// Rune: the radius, in logical points, of the arc the window's content takes at its bottom + /// corners, which the client-side frame leaves it (the frame's visible border lies just + /// outside it). Zero when no client-side frame is drawn, and when the frame draws the window + /// square: maximized, tiled or fullscreen. + #[inline] + pub fn content_corner_radius(&self) -> f32 { + #[cfg(feature = "sctk-adwaita")] + if let Some(frame) = self + .frame + .as_ref() + .filter(|frame| self.decorate && !frame.is_hidden()) + { + return frame.content_corner_radius(); + } + 0. + } + + /// Get the outer size of the window. + #[inline] + pub fn outer_size(&self) -> LogicalSize<u32> { + self.frame + .as_ref() + .map(|frame| frame.add_borders(self.size.width, self.size.height).into()) + .unwrap_or(self.size) + } + + /// Register pointer on the top-level. + pub fn pointer_entered(&mut self, added: Weak<ThemedPointer<WinitPointerData>>) { + self.pointers.push(added); + self.reload_cursor_style(); + + let mode = self.cursor_grab_mode.user_grab_mode; + let _ = self.set_cursor_grab_inner(mode); + } + + /// Pointer has left the top-level. + pub fn pointer_left(&mut self, removed: Weak<ThemedPointer<WinitPointerData>>) { + let mut new_pointers = Vec::new(); + for pointer in self.pointers.drain(..) { + if let Some(pointer) = pointer.upgrade() { + if pointer.pointer() != removed.upgrade().unwrap().pointer() { + new_pointers.push(Arc::downgrade(&pointer)); + } + } + } + + self.pointers = new_pointers; + } + + /// Refresh the decorations frame if it's present returning whether the client should redraw. + pub fn refresh_frame(&mut self) -> bool { + if let Some(frame) = self.frame.as_mut() { + if !frame.is_hidden() && frame.is_dirty() { + return frame.draw(); + } + } + + false + } + + /// Reload the cursor style on the given window. + pub fn reload_cursor_style(&mut self) { + if self.cursor_visible { + match &self.selected_cursor { + SelectedCursor::Named(icon) => self.set_cursor(*icon), + SelectedCursor::Custom(cursor) => self.apply_custom_cursor(cursor), + } + } else { + self.set_cursor_visible(self.cursor_visible); + } + } + + /// Reissue the transparency hint to the compositor. + /// + /// Rune: a client-side frame that rounds the content's bottom corners leaves the two corner + /// squares to the compositor, so an opaque window keeps the rest of itself opaque instead of + /// blending all of it. + pub fn reload_transparency_hint(&self) { + let surface = self.window.wl_surface(); + + if self.transparent { + surface.set_opaque_region(None); + return; + } + let Ok(region) = Region::new(&*self.compositor) else { + warn!("Failed to mark window opaque."); + return; + }; + let radius = self.content_corner_radius() as i32; + let (width, height) = (self.size.width as i32, self.size.height as i32); + if radius <= 0 || width <= 2 * radius || height <= radius { + region.add(0, 0, i32::MAX, i32::MAX); + } else { + // Everything but the two squares the frame's arcs cross at the window's foot. + region.add(0, 0, width, height - radius); + region.add(radius, height - radius, width - 2 * radius, radius); + } + surface.set_opaque_region(Some(region.wl_region())); + } + + /// Try to resize the window when the user can do so. + pub fn request_inner_size(&mut self, inner_size: Size) -> PhysicalSize<u32> { + if self.last_configure.as_ref().map(Self::is_stateless).unwrap_or(true) { + self.resize(inner_size.to_logical(self.scale_factor())) + } + + logical_to_physical_rounded(self.inner_size(), self.scale_factor()) + } + + /// Resize the window to the new inner size. + fn resize(&mut self, inner_size: LogicalSize<u32>) { + self.size = inner_size; + + // Update the stateless size. + if Some(true) == self.last_configure.as_ref().map(Self::is_stateless) { + self.stateless_size = inner_size; + } + + // Update the inner frame. + let ((x, y), outer_size) = if let Some(frame) = self.frame.as_mut() { + // Resize only visible frame. + if !frame.is_hidden() { + frame.resize( + NonZeroU32::new(self.size.width).unwrap(), + NonZeroU32::new(self.size.height).unwrap(), + ); + } + + (frame.location(), frame.add_borders(self.size.width, self.size.height).into()) + } else { + ((0, 0), self.size) + }; + + // Reload the hint. + self.reload_transparency_hint(); + + // Set the window geometry. + self.window.xdg_surface().set_window_geometry( + x, + y, + outer_size.width as i32, + outer_size.height as i32, + ); + + // Update the target viewport, this is used if and only if fractional scaling is in use. + if let Some(viewport) = self.viewport.as_ref() { + // Set inner size without the borders. + viewport.set_destination(self.size.width as _, self.size.height as _); + } + } + + /// Get the scale factor of the window. + #[inline] + pub fn scale_factor(&self) -> f64 { + self.scale_factor + } + + /// Set the cursor icon. + pub fn set_cursor(&mut self, cursor_icon: CursorIcon) { + self.selected_cursor = SelectedCursor::Named(cursor_icon); + + if !self.cursor_visible { + return; + } + + self.apply_on_pointer(|pointer, _| { + if pointer.set_cursor(&self.connection, cursor_icon).is_err() { + warn!("Failed to set cursor to {:?}", cursor_icon); + } + }) + } + + /// Set the custom cursor icon. + pub(crate) fn set_custom_cursor(&mut self, cursor: RootCustomCursor) { + let cursor = match cursor { + RootCustomCursor { inner: PlatformCustomCursor::Wayland(cursor) } => cursor.0, + #[cfg(x11_platform)] + RootCustomCursor { inner: PlatformCustomCursor::X(_) } => { + tracing::error!("passed a X11 cursor to Wayland backend"); + return; + }, + }; + + let cursor = { + let mut pool = self.custom_cursor_pool.lock().unwrap(); + CustomCursor::new(&mut pool, &cursor) + }; + + if self.cursor_visible { + self.apply_custom_cursor(&cursor); + } + + self.selected_cursor = SelectedCursor::Custom(cursor); + } + + /// Set the resize increments of the window. + pub fn set_resize_increments(&mut self, increments: Option<LogicalSize<u32>>) { + self.resize_increments = increments; + // NOTE: We don't update the window size here, because it will be done on the next resize + // or configure event. + } + + /// Get the resize increments of the window. + pub fn resize_increments(&self) -> Option<LogicalSize<u32>> { + self.resize_increments + } + + fn apply_custom_cursor(&self, cursor: &CustomCursor) { + self.apply_on_pointer(|pointer, data| { + let surface = pointer.surface(); + + let scale = if let Some(viewport) = data.viewport() { + let scale = self.scale_factor(); + let size = PhysicalSize::new(cursor.w, cursor.h).to_logical(scale); + viewport.set_destination(size.width, size.height); + scale + } else { + let scale = surface.data::<SurfaceData>().unwrap().surface_data().scale_factor(); + surface.set_buffer_scale(scale); + scale as f64 + }; + + surface.attach(Some(cursor.buffer.wl_buffer()), 0, 0); + if surface.version() >= 4 { + surface.damage_buffer(0, 0, cursor.w, cursor.h); + } else { + let size = PhysicalSize::new(cursor.w, cursor.h).to_logical(scale); + surface.damage(0, 0, size.width, size.height); + } + surface.commit(); + + let serial = pointer + .pointer() + .data::<WinitPointerData>() + .and_then(|data| data.pointer_data().latest_enter_serial()) + .unwrap(); + + let hotspot = + PhysicalPosition::new(cursor.hotspot_x, cursor.hotspot_y).to_logical(scale); + pointer.pointer().set_cursor(serial, Some(surface), hotspot.x, hotspot.y); + }); + } + + /// Set maximum inner window size. + pub fn set_min_inner_size(&mut self, size: Option<LogicalSize<u32>>) { + // Ensure that the window has the right minimum size. + let mut size = size.unwrap_or(MIN_WINDOW_SIZE); + size.width = size.width.max(MIN_WINDOW_SIZE.width); + size.height = size.height.max(MIN_WINDOW_SIZE.height); + + // Add the borders. + let size = self + .frame + .as_ref() + .map(|frame| frame.add_borders(size.width, size.height).into()) + .unwrap_or(size); + + self.min_inner_size = size; + self.window.set_min_size(Some(size.into())); + } + + /// Set maximum inner window size. + pub fn set_max_inner_size(&mut self, size: Option<LogicalSize<u32>>) { + let size = size.map(|size| { + self.frame + .as_ref() + .map(|frame| frame.add_borders(size.width, size.height).into()) + .unwrap_or(size) + }); + + self.max_inner_size = size; + self.window.set_max_size(size.map(Into::into)); + } + + /// Set the CSD theme. + pub fn set_theme(&mut self, theme: Option<Theme>) { + self.theme = theme; + #[cfg(feature = "sctk-adwaita")] + if let Some(frame) = self.frame.as_mut() { + frame.set_config(into_sctk_adwaita_config(theme)) + } + } + + /// The current theme for CSD decorations. + #[inline] + pub fn theme(&self) -> Option<Theme> { + self.theme + } + + /// Set the cursor grabbing state on the top-level. + pub fn set_cursor_grab(&mut self, mode: CursorGrabMode) -> Result<(), ExternalError> { + if self.cursor_grab_mode.user_grab_mode == mode { + return Ok(()); + } + + self.set_cursor_grab_inner(mode)?; + // Update user grab on success. + self.cursor_grab_mode.user_grab_mode = mode; + Ok(()) + } + + /// Reload the hints for minimum and maximum sizes. + pub fn reload_min_max_hints(&mut self) { + self.set_min_inner_size(Some(self.min_inner_size)); + self.set_max_inner_size(self.max_inner_size); + } + + /// Set the grabbing state on the surface. + fn set_cursor_grab_inner(&mut self, mode: CursorGrabMode) -> Result<(), ExternalError> { + let pointer_constraints = match self.pointer_constraints.as_ref() { + Some(pointer_constraints) => pointer_constraints, + None if mode == CursorGrabMode::None => return Ok(()), + None => return Err(ExternalError::NotSupported(NotSupportedError::new())), + }; + + let mut unset_old = false; + match self.cursor_grab_mode.current_grab_mode { + CursorGrabMode::None => unset_old = true, + CursorGrabMode::Confined => self.apply_on_pointer(|_, data| { + data.unconfine_pointer(); + unset_old = true; + }), + CursorGrabMode::Locked => { + self.apply_on_pointer(|_, data| { + data.unlock_pointer(); + unset_old = true; + }); + }, + } + + // In case we haven't unset the old mode, it means that we don't have a cursor above + // the window, thus just wait for it to re-appear. + if !unset_old { + return Ok(()); + } + + let mut set_mode = false; + let surface = self.window.wl_surface(); + match mode { + CursorGrabMode::Locked => self.apply_on_pointer(|pointer, data| { + let pointer = pointer.pointer(); + data.lock_pointer(pointer_constraints, surface, pointer, &self.queue_handle); + set_mode = true; + }), + CursorGrabMode::Confined => self.apply_on_pointer(|pointer, data| { + let pointer = pointer.pointer(); + data.confine_pointer(pointer_constraints, surface, pointer, &self.queue_handle); + set_mode = true; + }), + CursorGrabMode::None => { + // Current lock/confine was already removed. + set_mode = true; + }, + } + + // Replace the current grab mode after we've ensure that it got updated. + if set_mode { + self.cursor_grab_mode.current_grab_mode = mode; + } + + Ok(()) + } + + pub fn show_window_menu(&self, position: LogicalPosition<u32>) { + // TODO(kchibisov) handle touch serials. + self.apply_on_pointer(|_, data| { + let serial = data.latest_button_serial(); + let seat = data.seat(); + self.window.show_window_menu(seat, serial, position.into()); + }); + } + + /// Set the position of the cursor. + pub fn set_cursor_position(&self, position: LogicalPosition<f64>) -> Result<(), ExternalError> { + if self.pointer_constraints.is_none() { + return Err(ExternalError::NotSupported(NotSupportedError::new())); + } + + // Position can be set only for locked cursor. + if self.cursor_grab_mode.current_grab_mode != CursorGrabMode::Locked { + return Err(ExternalError::Os(os_error!(crate::platform_impl::OsError::Misc( + "cursor position can be set only for locked cursor." + )))); + } + + self.apply_on_pointer(|_, data| { + data.set_locked_cursor_position(position.x, position.y); + }); + + Ok(()) + } + + /// Set the visibility state of the cursor. + pub fn set_cursor_visible(&mut self, cursor_visible: bool) { + self.cursor_visible = cursor_visible; + + if self.cursor_visible { + match &self.selected_cursor { + SelectedCursor::Named(icon) => self.set_cursor(*icon), + SelectedCursor::Custom(cursor) => self.apply_custom_cursor(cursor), + } + } else { + for pointer in self.pointers.iter().filter_map(|pointer| pointer.upgrade()) { + let latest_enter_serial = pointer.pointer().winit_data().latest_enter_serial(); + + pointer.pointer().set_cursor(latest_enter_serial, None, 0, 0); + } + } + } + + /// Whether show or hide client side decorations. + #[inline] + pub fn set_decorate(&mut self, decorate: bool) { + if decorate == self.decorate { + return; + } + + self.decorate = decorate; + + match self.last_configure.as_ref().map(|configure| configure.decoration_mode) { + Some(DecorationMode::Server) if !self.decorate => { + // To disable decorations we should request client and hide the frame. + self.window.request_decoration_mode(Some(DecorationMode::Client)) + }, + _ if self.decorate => self.window.request_decoration_mode(Some(DecorationMode::Server)), + _ => (), + } + + if let Some(frame) = self.frame.as_mut() { + frame.set_hidden(!decorate); + // Force the resize. + self.resize(self.size); + } + } + + /// Add seat focus for the window. + #[inline] + pub fn add_seat_focus(&mut self, seat: ObjectId) { + self.seat_focus.insert(seat); + } + + /// Remove seat focus from the window. + #[inline] + pub fn remove_seat_focus(&mut self, seat: &ObjectId) { + self.seat_focus.remove(seat); + } + + /// Returns `true` if the requested state was applied. + pub fn set_ime_allowed(&mut self, allowed: bool) -> bool { + self.ime_allowed = allowed; + + let mut applied = false; + for text_input in &self.text_inputs { + applied = true; + if allowed { + text_input.enable(); + text_input.set_content_type_by_purpose(self.ime_purpose); + } else { + text_input.disable(); + } + text_input.commit(); + } + + applied + } + + /// Set the IME position. + pub fn set_ime_cursor_area(&self, position: LogicalPosition<u32>, size: LogicalSize<u32>) { + // FIXME: This won't fly unless user will have a way to request IME window per seat, since + // the ime windows will be overlapping, but winit doesn't expose API to specify for + // which seat we're setting IME position. + let (x, y) = (position.x as i32, position.y as i32); + let (width, height) = (size.width as i32, size.height as i32); + for text_input in self.text_inputs.iter() { + text_input.set_cursor_rectangle(x, y, width, height); + text_input.commit(); + } + } + + /// Set the IME purpose. + pub fn set_ime_purpose(&mut self, purpose: ImePurpose) { + self.ime_purpose = purpose; + + for text_input in &self.text_inputs { + text_input.set_content_type_by_purpose(purpose); + text_input.commit(); + } + } + + /// Get the IME purpose. + pub fn ime_purpose(&self) -> ImePurpose { + self.ime_purpose + } + + /// Set the scale factor for the given window. + #[inline] + pub fn set_scale_factor(&mut self, scale_factor: f64) { + self.scale_factor = scale_factor; + + // NOTE: When fractional scaling is not used update the buffer scale. + if self.fractional_scale.is_none() { + let _ = self.window.set_buffer_scale(self.scale_factor as _); + } + + if let Some(frame) = self.frame.as_mut() { + frame.set_scaling_factor(scale_factor); + } + } + + /// Make window background blurred + #[inline] + pub fn set_blur(&mut self, blurred: bool) { + if blurred && self.blur.is_none() { + if let Some(blur_manager) = self.blur_manager.as_ref() { + let blur = blur_manager.blur(self.window.wl_surface(), &self.queue_handle); + blur.commit(); + self.blur = Some(blur); + } else { + info!("Blur manager unavailable, unable to change blur") + } + } else if !blurred && self.blur.is_some() { + self.blur_manager.as_ref().unwrap().unset(self.window.wl_surface()); + self.blur.take().unwrap().release(); + } + } + + /// Set the window title to a new value. + /// + /// This will automatically truncate the title to something meaningful. + pub fn set_title(&mut self, mut title: String) { + // Truncate the title to at most 1024 bytes, so that it does not blow up the protocol + // messages + if title.len() > 1024 { + let mut new_len = 1024; + while !title.is_char_boundary(new_len) { + new_len -= 1; + } + title.truncate(new_len); + } + + // Update the CSD title. + if let Some(frame) = self.frame.as_mut() { + frame.set_title(&title); + } + + self.window.set_title(&title); + self.title = title; + } + + /// Mark the window as transparent. + #[inline] + pub fn set_transparent(&mut self, transparent: bool) { + self.transparent = transparent; + self.reload_transparency_hint(); + } + + /// Register text input on the top-level. + #[inline] + pub fn text_input_entered(&mut self, text_input: &ZwpTextInputV3) { + if !self.text_inputs.iter().any(|t| t == text_input) { + self.text_inputs.push(text_input.clone()); + } + } + + /// The text input left the top-level. + #[inline] + pub fn text_input_left(&mut self, text_input: &ZwpTextInputV3) { + if let Some(position) = self.text_inputs.iter().position(|t| t == text_input) { + self.text_inputs.remove(position); + } + } + + /// Get the cached title. + #[inline] + pub fn title(&self) -> &str { + &self.title + } +} + +impl Drop for WindowState { + fn drop(&mut self) { + if let Some(blur) = self.blur.take() { + blur.release(); + } + + if let Some(fs) = self.fractional_scale.take() { + fs.destroy(); + } + + if let Some(viewport) = self.viewport.take() { + viewport.destroy(); + } + + // NOTE: the wl_surface used by the window is being cleaned up when + // dropping SCTK `Window`. + } +} + +/// The state of the cursor grabs. +#[derive(Clone, Copy)] +struct GrabState { + /// The grab mode requested by the user. + user_grab_mode: CursorGrabMode, + + /// The current grab mode. + current_grab_mode: CursorGrabMode, +} + +impl GrabState { + fn new() -> Self { + Self { user_grab_mode: CursorGrabMode::None, current_grab_mode: CursorGrabMode::None } + } +} + +/// The state of the frame callback. +#[derive(Default, Debug, Clone, Copy, PartialEq, Eq)] +pub enum FrameCallbackState { + /// No frame callback was requested. + #[default] + None, + /// The frame callback was requested, but not yet arrived, the redraw events are throttled. + Requested, + /// The callback was marked as done, and user could receive redraw requested + Received, +} + +impl From<ResizeDirection> for XdgResizeEdge { + fn from(value: ResizeDirection) -> Self { + match value { + ResizeDirection::North => XdgResizeEdge::Top, + ResizeDirection::West => XdgResizeEdge::Left, + ResizeDirection::NorthWest => XdgResizeEdge::TopLeft, + ResizeDirection::NorthEast => XdgResizeEdge::TopRight, + ResizeDirection::East => XdgResizeEdge::Right, + ResizeDirection::SouthWest => XdgResizeEdge::BottomLeft, + ResizeDirection::SouthEast => XdgResizeEdge::BottomRight, + ResizeDirection::South => XdgResizeEdge::Bottom, + } + } +} + +// NOTE: Rust doesn't allow `From<Option<Theme>>`. +#[cfg(feature = "sctk-adwaita")] +fn into_sctk_adwaita_config(theme: Option<Theme>) -> sctk_adwaita::FrameConfig { + match theme { + Some(Theme::Light) => sctk_adwaita::FrameConfig::light(), + Some(Theme::Dark) => sctk_adwaita::FrameConfig::dark(), + None => sctk_adwaita::FrameConfig::auto(), + } +} diff --git a/app/vendor/rune/vendor/winit/src/platform_impl/linux/x11/activation.rs b/app/vendor/rune/vendor/winit/src/platform_impl/linux/x11/activation.rs new file mode 100644 index 0000000..8f4aa79 --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/platform_impl/linux/x11/activation.rs @@ -0,0 +1,194 @@ +// SPDX-License-Identifier: Apache-2.0 + +//! X11 activation handling. +//! +//! X11 has a "startup notification" specification similar to Wayland's, see this URL: +//! <https://specifications.freedesktop.org/startup-notification-spec/startup-notification-latest.txt> + +use super::atoms::*; +use super::{VoidCookie, X11Error, XConnection}; + +use std::ffi::CString; +use std::fmt::Write; + +use x11rb::protocol::xproto::{self, ConnectionExt as _}; + +impl XConnection { + /// "Request" a new activation token from the server. + pub(crate) fn request_activation_token(&self, window_title: &str) -> Result<String, X11Error> { + // The specification recommends the format "hostname+pid+"_TIME"+current time" + let uname = rustix::system::uname(); + let pid = rustix::process::getpid(); + let time = self.timestamp(); + + let activation_token = format!( + "{}{}_TIME{}", + uname.nodename().to_str().unwrap_or("winit"), + pid.as_raw_nonzero(), + time + ); + + // Set up the new startup notification. + let notification = { + let mut buffer = Vec::new(); + buffer.extend_from_slice(b"new: ID="); + quote_string(&activation_token, &mut buffer); + buffer.extend_from_slice(b" NAME="); + quote_string(window_title, &mut buffer); + buffer.extend_from_slice(b" SCREEN="); + push_display(&mut buffer, &self.default_screen_index()); + + CString::new(buffer) + .map_err(|err| X11Error::InvalidActivationToken(err.into_vec()))? + .into_bytes_with_nul() + }; + self.send_message(&notification)?; + + Ok(activation_token) + } + + /// Finish launching a window with the given startup ID. + pub(crate) fn remove_activation_token( + &self, + window: xproto::Window, + startup_id: &str, + ) -> Result<(), X11Error> { + let atoms = self.atoms(); + + // Set the _NET_STARTUP_ID property on the window. + self.xcb_connection() + .change_property( + xproto::PropMode::REPLACE, + window, + atoms[_NET_STARTUP_ID], + xproto::AtomEnum::STRING, + 8, + startup_id.len().try_into().unwrap(), + startup_id.as_bytes(), + )? + .check()?; + + // Send the message indicating that the startup is over. + let message = { + const MESSAGE_ROOT: &str = "remove: ID="; + + let mut buffer = Vec::with_capacity( + MESSAGE_ROOT + .len() + .checked_add(startup_id.len()) + .and_then(|x| x.checked_add(1)) + .unwrap(), + ); + buffer.extend_from_slice(MESSAGE_ROOT.as_bytes()); + quote_string(startup_id, &mut buffer); + CString::new(buffer) + .map_err(|err| X11Error::InvalidActivationToken(err.into_vec()))? + .into_bytes_with_nul() + }; + + self.send_message(&message) + } + + /// Send a startup notification message to the window manager. + fn send_message(&self, message: &[u8]) -> Result<(), X11Error> { + let atoms = self.atoms(); + + // Create a new window to send the message over. + let screen = self.default_root(); + let window = xproto::WindowWrapper::create_window( + self.xcb_connection(), + screen.root_depth, + screen.root, + -100, + -100, + 1, + 1, + 0, + xproto::WindowClass::INPUT_OUTPUT, + screen.root_visual, + &xproto::CreateWindowAux::new().override_redirect(1).event_mask( + xproto::EventMask::STRUCTURE_NOTIFY | xproto::EventMask::PROPERTY_CHANGE, + ), + )?; + + // Serialize the messages in 20-byte chunks. + let mut message_type = atoms[_NET_STARTUP_INFO_BEGIN]; + message + .chunks(20) + .map(|chunk| { + let mut buffer = [0u8; 20]; + buffer[..chunk.len()].copy_from_slice(chunk); + let event = + xproto::ClientMessageEvent::new(8, window.window(), message_type, buffer); + + // Set the message type to the continuation atom for the next chunk. + message_type = atoms[_NET_STARTUP_INFO]; + + event + }) + .try_for_each(|event| { + // Send each event in order. + self.xcb_connection() + .send_event(false, screen.root, xproto::EventMask::PROPERTY_CHANGE, event) + .map(VoidCookie::ignore_error) + })?; + + Ok(()) + } +} + +/// Quote a literal string as per the startup notification specification. +fn quote_string(s: &str, target: &mut Vec<u8>) { + let total_len = s.len().checked_add(3).expect("quote string overflow"); + target.reserve(total_len); + + // Add the opening quote. + target.push(b'"'); + + // Iterate over the string split by literal quotes. + s.as_bytes().split(|&b| b == b'"').for_each(|part| { + // Add the part. + target.extend_from_slice(part); + + // Escape the quote. + target.push(b'\\'); + target.push(b'"'); + }); + + // Un-escape the last quote. + target.remove(target.len() - 2); +} + +/// Push a `Display` implementation to the buffer. +fn push_display(buffer: &mut Vec<u8>, display: &impl std::fmt::Display) { + struct Writer<'a> { + buffer: &'a mut Vec<u8>, + } + + impl std::fmt::Write for Writer<'_> { + fn write_str(&mut self, s: &str) -> std::fmt::Result { + self.buffer.extend_from_slice(s.as_bytes()); + Ok(()) + } + } + + write!(Writer { buffer }, "{display}").unwrap(); +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn properly_escapes_x11_messages() { + let assert_eq = |input: &str, output: &[u8]| { + let mut buf = vec![]; + quote_string(input, &mut buf); + assert_eq!(buf, output); + }; + + assert_eq("", b"\"\""); + assert_eq("foo", b"\"foo\""); + assert_eq("foo\"bar", b"\"foo\\\"bar\""); + } +} diff --git a/app/vendor/rune/vendor/winit/src/platform_impl/linux/x11/atoms.rs b/app/vendor/rune/vendor/winit/src/platform_impl/linux/x11/atoms.rs new file mode 100644 index 0000000..c6d96c8 --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/platform_impl/linux/x11/atoms.rs @@ -0,0 +1,117 @@ +//! Collects every atom used by the platform implementation. + +use core::ops::Index; + +macro_rules! atom_manager { + ($($name:ident $(:$lit:literal)?),*) => { + x11rb::atom_manager! { + /// The atoms used by `winit` + pub Atoms: AtomsCookie { + $($name $(:$lit)?,)* + } + } + + /// Indices into the `Atoms` struct. + #[derive(Copy, Clone, Debug)] + #[allow(non_camel_case_types)] + pub enum AtomName { + $($name,)* + } + + impl AtomName { + pub(crate) fn atom_from( + self, + atoms: &Atoms + ) -> &x11rb::protocol::xproto::Atom { + match self { + $(AtomName::$name => &atoms.$name,)* + } + } + } + }; +} + +atom_manager! { + // General Use Atoms + CARD32, + UTF8_STRING, + WM_CHANGE_STATE, + WM_CLIENT_MACHINE, + WM_DELETE_WINDOW, + WM_PROTOCOLS, + WM_STATE, + XIM_SERVERS, + + // Assorted ICCCM Atoms + _NET_WM_ICON, + _NET_WM_MOVERESIZE, + _NET_WM_NAME, + _NET_WM_PID, + _NET_WM_PING, + _NET_WM_STATE, + _NET_WM_STATE_ABOVE, + _NET_WM_STATE_BELOW, + _NET_WM_STATE_FULLSCREEN, + _NET_WM_STATE_HIDDEN, + _NET_WM_STATE_MAXIMIZED_HORZ, + _NET_WM_STATE_MAXIMIZED_VERT, + _NET_WM_WINDOW_TYPE, + + // Activation atoms. + _NET_STARTUP_INFO_BEGIN, + _NET_STARTUP_INFO, + _NET_STARTUP_ID, + + // WM window types. + _NET_WM_WINDOW_TYPE_DESKTOP, + _NET_WM_WINDOW_TYPE_DOCK, + _NET_WM_WINDOW_TYPE_TOOLBAR, + _NET_WM_WINDOW_TYPE_MENU, + _NET_WM_WINDOW_TYPE_UTILITY, + _NET_WM_WINDOW_TYPE_SPLASH, + _NET_WM_WINDOW_TYPE_DIALOG, + _NET_WM_WINDOW_TYPE_DROPDOWN_MENU, + _NET_WM_WINDOW_TYPE_POPUP_MENU, + _NET_WM_WINDOW_TYPE_TOOLTIP, + _NET_WM_WINDOW_TYPE_NOTIFICATION, + _NET_WM_WINDOW_TYPE_COMBO, + _NET_WM_WINDOW_TYPE_DND, + _NET_WM_WINDOW_TYPE_NORMAL, + + // Drag-N-Drop Atoms + XdndAware, + XdndEnter, + XdndLeave, + XdndDrop, + XdndPosition, + XdndStatus, + XdndActionPrivate, + XdndSelection, + XdndFinished, + XdndTypeList, + TextUriList: b"text/uri-list", + None: b"None", + + // Miscellaneous Atoms + _GTK_THEME_VARIANT, + _MOTIF_WM_HINTS, + _NET_ACTIVE_WINDOW, + _NET_CLIENT_LIST, + _NET_FRAME_EXTENTS, + _NET_SUPPORTED, + _NET_SUPPORTING_WM_CHECK, + _XEMBED, + _XSETTINGS_SETTINGS +} + +impl Index<AtomName> for Atoms { + type Output = x11rb::protocol::xproto::Atom; + + fn index(&self, index: AtomName) -> &Self::Output { + index.atom_from(self) + } +} + +pub(crate) use AtomName::*; +// Make sure `None` is still defined. +pub(crate) use core::option::Option::None; diff --git a/app/vendor/rune/vendor/winit/src/platform_impl/linux/x11/dnd.rs b/app/vendor/rune/vendor/winit/src/platform_impl/linux/x11/dnd.rs new file mode 100644 index 0000000..691e40a --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/platform_impl/linux/x11/dnd.rs @@ -0,0 +1,174 @@ +use std::io; +use std::os::raw::*; +use std::path::{Path, PathBuf}; +use std::str::Utf8Error; +use std::sync::Arc; + +use percent_encoding::percent_decode; +use x11rb::protocol::xproto::{self, ConnectionExt}; + +use super::atoms::AtomName::None as DndNone; +use super::atoms::*; +use super::{util, CookieResultExt, X11Error, XConnection}; + +#[derive(Debug, Clone, Copy)] +pub enum DndState { + Accepted, + Rejected, +} + +#[derive(Debug)] +pub enum DndDataParseError { + EmptyData, + InvalidUtf8(#[allow(dead_code)] Utf8Error), + HostnameSpecified(#[allow(dead_code)] String), + UnexpectedProtocol(#[allow(dead_code)] String), + UnresolvablePath(#[allow(dead_code)] io::Error), +} + +impl From<Utf8Error> for DndDataParseError { + fn from(e: Utf8Error) -> Self { + DndDataParseError::InvalidUtf8(e) + } +} + +impl From<io::Error> for DndDataParseError { + fn from(e: io::Error) -> Self { + DndDataParseError::UnresolvablePath(e) + } +} + +pub struct Dnd { + xconn: Arc<XConnection>, + // Populated by XdndEnter event handler + pub version: Option<c_long>, + pub type_list: Option<Vec<xproto::Atom>>, + // Populated by XdndPosition event handler + pub source_window: Option<xproto::Window>, + // Populated by SelectionNotify event handler (triggered by XdndPosition event handler) + pub result: Option<Result<Vec<PathBuf>, DndDataParseError>>, +} + +impl Dnd { + pub fn new(xconn: Arc<XConnection>) -> Result<Self, X11Error> { + Ok(Dnd { xconn, version: None, type_list: None, source_window: None, result: None }) + } + + pub fn reset(&mut self) { + self.version = None; + self.type_list = None; + self.source_window = None; + self.result = None; + } + + pub unsafe fn send_status( + &self, + this_window: xproto::Window, + target_window: xproto::Window, + state: DndState, + ) -> Result<(), X11Error> { + let atoms = self.xconn.atoms(); + let (accepted, action) = match state { + DndState::Accepted => (1, atoms[XdndActionPrivate]), + DndState::Rejected => (0, atoms[DndNone]), + }; + self.xconn + .send_client_msg(target_window, target_window, atoms[XdndStatus] as _, None, [ + this_window, + accepted, + 0, + 0, + action as _, + ])? + .ignore_error(); + + Ok(()) + } + + pub unsafe fn send_finished( + &self, + this_window: xproto::Window, + target_window: xproto::Window, + state: DndState, + ) -> Result<(), X11Error> { + let atoms = self.xconn.atoms(); + let (accepted, action) = match state { + DndState::Accepted => (1, atoms[XdndActionPrivate]), + DndState::Rejected => (0, atoms[DndNone]), + }; + self.xconn + .send_client_msg(target_window, target_window, atoms[XdndFinished] as _, None, [ + this_window, + accepted, + action as _, + 0, + 0, + ])? + .ignore_error(); + + Ok(()) + } + + pub unsafe fn get_type_list( + &self, + source_window: xproto::Window, + ) -> Result<Vec<xproto::Atom>, util::GetPropertyError> { + let atoms = self.xconn.atoms(); + self.xconn.get_property( + source_window, + atoms[XdndTypeList], + xproto::Atom::from(xproto::AtomEnum::ATOM), + ) + } + + pub unsafe fn convert_selection(&self, window: xproto::Window, time: xproto::Timestamp) { + let atoms = self.xconn.atoms(); + self.xconn + .xcb_connection() + .convert_selection( + window, + atoms[XdndSelection], + atoms[TextUriList], + atoms[XdndSelection], + time, + ) + .expect_then_ignore_error("Failed to send XdndSelection event") + } + + pub unsafe fn read_data( + &self, + window: xproto::Window, + ) -> Result<Vec<c_uchar>, util::GetPropertyError> { + let atoms = self.xconn.atoms(); + self.xconn.get_property(window, atoms[XdndSelection], atoms[TextUriList]) + } + + pub fn parse_data(&self, data: &mut [c_uchar]) -> Result<Vec<PathBuf>, DndDataParseError> { + if !data.is_empty() { + let mut path_list = Vec::new(); + let decoded = percent_decode(data).decode_utf8()?.into_owned(); + for uri in decoded.split("\r\n").filter(|u| !u.is_empty()) { + // The format is specified as protocol://host/path + // However, it's typically simply protocol:///path + let path_str = if uri.starts_with("file://") { + let path_str = uri.replace("file://", ""); + if !path_str.starts_with('/') { + // A hostname is specified + // Supporting this case is beyond the scope of my mental health + return Err(DndDataParseError::HostnameSpecified(path_str)); + } + path_str + } else { + // Only the file protocol is supported + return Err(DndDataParseError::UnexpectedProtocol(uri.to_owned())); + }; + + let path = Path::new(&path_str).canonicalize()?; + path_list.push(path); + } + Ok(path_list) + } else { + Err(DndDataParseError::EmptyData) + } + } +} diff --git a/app/vendor/rune/vendor/winit/src/platform_impl/linux/x11/event_processor.rs b/app/vendor/rune/vendor/winit/src/platform_impl/linux/x11/event_processor.rs new file mode 100644 index 0000000..79f5c11 --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/platform_impl/linux/x11/event_processor.rs @@ -0,0 +1,1883 @@ +use std::cell::{Cell, RefCell}; +use std::collections::{HashMap, VecDeque}; +use std::os::raw::{c_char, c_int, c_long, c_ulong}; +use std::slice; +use std::sync::{Arc, Mutex}; + +use x11_dl::xinput2::{ + self, XIDeviceEvent, XIEnterEvent, XIFocusInEvent, XIFocusOutEvent, XIHierarchyEvent, + XILeaveEvent, XIModifierState, XIRawEvent, +}; +use x11_dl::xlib::{ + self, Display as XDisplay, Window as XWindow, XAnyEvent, XClientMessageEvent, XConfigureEvent, + XDestroyWindowEvent, XEvent, XExposeEvent, XKeyEvent, XMapEvent, XPropertyEvent, + XReparentEvent, XSelectionEvent, XVisibilityEvent, XkbAnyEvent, XkbStateRec, +}; +use x11rb::protocol::xinput; +use x11rb::protocol::xkb::ID as XkbId; +use x11rb::protocol::xproto::{self, ConnectionExt as _, ModMask}; +use x11rb::x11_utils::{ExtensionInformation, Serialize}; +use xkbcommon_dl::xkb_mod_mask_t; + +use crate::dpi::{PhysicalPosition, PhysicalSize}; +use crate::event::{ + DeviceEvent, ElementState, Event, Ime, InnerSizeWriter, MouseButton, MouseScrollDelta, + RawKeyEvent, Touch, TouchPhase, WindowEvent, +}; +use crate::event_loop::ActiveEventLoop as RootAEL; +use crate::keyboard::ModifiersState; +use crate::platform_impl::common::xkb::{self, XkbState}; +use crate::platform_impl::platform::common::xkb::Context; +use crate::platform_impl::platform::x11::ime::{ImeEvent, ImeEventReceiver, ImeRequest}; +use crate::platform_impl::platform::x11::ActiveEventLoop; +use crate::platform_impl::platform::ActiveEventLoop as PlatformActiveEventLoop; +use crate::platform_impl::x11::atoms::*; +use crate::platform_impl::x11::util::cookie::GenericEventCookie; +use crate::platform_impl::x11::{ + mkdid, mkwid, util, CookieResultExt, Device, DeviceId, DeviceInfo, Dnd, DndState, ImeReceiver, + ScrollOrientation, UnownedWindow, WindowId, +}; + +/// The maximum amount of X modifiers to replay. +pub const MAX_MOD_REPLAY_LEN: usize = 32; + +/// The X11 documentation states: "Keycodes lie in the inclusive range `[8, 255]`". +const KEYCODE_OFFSET: u8 = 8; + +pub struct EventProcessor { + pub dnd: Dnd, + pub ime_receiver: ImeReceiver, + pub ime_event_receiver: ImeEventReceiver, + pub randr_event_offset: u8, + pub devices: RefCell<HashMap<DeviceId, Device>>, + pub xi2ext: ExtensionInformation, + pub xkbext: ExtensionInformation, + pub target: RootAEL, + pub xkb_context: Context, + // Number of touch events currently in progress + pub num_touch: u32, + // This is the last pressed key that is repeatable (if it hasn't been + // released). + // + // Used to detect key repeats. + pub held_key_press: Option<u32>, + pub first_touch: Option<u64>, + // Currently focused window belonging to this process + pub active_window: Option<xproto::Window>, + /// Latest modifiers we've sent for the user to trigger change in event. + pub modifiers: Cell<ModifiersState>, + // Track modifiers based on keycodes. NOTE: that serials generally don't work for tracking + // since they are not unique and could be duplicated in case of sequence of key events is + // delivered at near the same time. + pub xfiltered_modifiers: VecDeque<u8>, + pub xmodmap: util::ModifierKeymap, + pub is_composing: bool, +} + +impl EventProcessor { + pub fn process_event<T: 'static, F>(&mut self, xev: &mut XEvent, mut callback: F) + where + F: FnMut(&RootAEL, Event<T>), + { + self.process_xevent(xev, &mut callback); + + let window_target = Self::window_target_mut(&mut self.target); + + // Handle IME requests. + while let Ok(request) = self.ime_receiver.try_recv() { + let ime = match window_target.ime.as_mut() { + Some(ime) => ime, + None => continue, + }; + let ime = ime.get_mut(); + match request { + ImeRequest::Position(window_id, x, y) => { + ime.send_xim_spot(window_id, x, y); + }, + ImeRequest::Allow(window_id, allowed) => { + ime.set_ime_allowed(window_id, allowed); + }, + } + } + + // Drain IME events. + while let Ok((window, event)) = self.ime_event_receiver.try_recv() { + let window_id = mkwid(window as xproto::Window); + let event = match event { + ImeEvent::Enabled => WindowEvent::Ime(Ime::Enabled), + ImeEvent::Start => { + self.is_composing = true; + WindowEvent::Ime(Ime::Preedit("".to_owned(), None)) + }, + ImeEvent::Update(text, position) if self.is_composing => { + WindowEvent::Ime(Ime::Preedit(text, Some((position, position)))) + }, + ImeEvent::End => { + self.is_composing = false; + // Issue empty preedit on `Done`. + WindowEvent::Ime(Ime::Preedit(String::new(), None)) + }, + ImeEvent::Disabled => { + self.is_composing = false; + WindowEvent::Ime(Ime::Disabled) + }, + _ => continue, + }; + + callback(&self.target, Event::WindowEvent { window_id, event }); + } + } + + /// XFilterEvent tells us when an event has been discarded by the input method. + /// Specifically, this involves all of the KeyPress events in compose/pre-edit sequences, + /// along with an extra copy of the KeyRelease events. This also prevents backspace and + /// arrow keys from being detected twice. + #[must_use] + fn filter_event(&mut self, xev: &mut XEvent) -> bool { + let wt = Self::window_target(&self.target); + unsafe { + (wt.xconn.xlib.XFilterEvent)(xev, { + let xev: &XAnyEvent = xev.as_ref(); + xev.window + }) == xlib::True + } + } + + fn process_xevent<T: 'static, F>(&mut self, xev: &mut XEvent, mut callback: F) + where + F: FnMut(&RootAEL, Event<T>), + { + let event_type = xev.get_type(); + + // If we have IME disabled, don't try to `filter_event`, since only IME can consume them + // and forward back. This is not desired for e.g. games since some IMEs may delay the input + // and game can toggle IME back when e.g. typing into some field where latency won't really + // matter. + let filtered = if event_type == xlib::KeyPress || event_type == xlib::KeyRelease { + let wt = Self::window_target(&self.target); + let ime = wt.ime.as_ref(); + let window = self.active_window.map(|window| window as XWindow); + let forward_to_ime = ime + .and_then(|ime| window.map(|window| ime.borrow().is_ime_allowed(window))) + .unwrap_or(false); + + let filtered = forward_to_ime && self.filter_event(xev); + if filtered { + let xev: &XKeyEvent = xev.as_ref(); + if self.xmodmap.is_modifier(xev.keycode as u8) { + // Don't grow the buffer past the `MAX_MOD_REPLAY_LEN`. This could happen + // when the modifiers are consumed entirely. + if self.xfiltered_modifiers.len() == MAX_MOD_REPLAY_LEN { + self.xfiltered_modifiers.pop_back(); + } + self.xfiltered_modifiers.push_front(xev.keycode as u8); + } + } + + filtered + } else { + self.filter_event(xev) + }; + + // Don't process event if it was filtered. + if filtered { + return; + } + + match event_type { + xlib::ClientMessage => self.client_message(xev.as_ref(), &mut callback), + xlib::SelectionNotify => self.selection_notify(xev.as_ref(), &mut callback), + xlib::ConfigureNotify => self.configure_notify(xev.as_ref(), &mut callback), + xlib::ReparentNotify => self.reparent_notify(xev.as_ref()), + xlib::MapNotify => self.map_notify(xev.as_ref(), &mut callback), + xlib::DestroyNotify => self.destroy_notify(xev.as_ref(), &mut callback), + xlib::PropertyNotify => self.property_notify(xev.as_ref(), &mut callback), + xlib::VisibilityNotify => self.visibility_notify(xev.as_ref(), &mut callback), + xlib::Expose => self.expose(xev.as_ref(), &mut callback), + // Note that in compose/pre-edit sequences, we'll always receive KeyRelease events. + ty @ xlib::KeyPress | ty @ xlib::KeyRelease => { + let state = if ty == xlib::KeyPress { + ElementState::Pressed + } else { + ElementState::Released + }; + + self.xinput_key_input(xev.as_mut(), state, &mut callback); + }, + xlib::GenericEvent => { + let wt = Self::window_target(&self.target); + let xev: GenericEventCookie = + match GenericEventCookie::from_event(wt.xconn.clone(), *xev) { + Some(xev) if xev.extension() == self.xi2ext.major_opcode => xev, + _ => return, + }; + + let evtype = xev.evtype(); + + match evtype { + ty @ xinput2::XI_ButtonPress | ty @ xinput2::XI_ButtonRelease => { + let state = if ty == xinput2::XI_ButtonPress { + ElementState::Pressed + } else { + ElementState::Released + }; + + let xev: &XIDeviceEvent = unsafe { xev.as_event() }; + self.update_mods_from_xinput2_event( + &xev.mods, + &xev.group, + false, + &mut callback, + ); + self.xinput2_button_input(xev, state, &mut callback); + }, + xinput2::XI_Motion => { + let xev: &XIDeviceEvent = unsafe { xev.as_event() }; + self.update_mods_from_xinput2_event( + &xev.mods, + &xev.group, + false, + &mut callback, + ); + self.xinput2_mouse_motion(xev, &mut callback); + }, + xinput2::XI_Enter => { + let xev: &XIEnterEvent = unsafe { xev.as_event() }; + self.xinput2_mouse_enter(xev, &mut callback); + }, + xinput2::XI_Leave => { + let xev: &XILeaveEvent = unsafe { xev.as_event() }; + self.update_mods_from_xinput2_event( + &xev.mods, + &xev.group, + false, + &mut callback, + ); + self.xinput2_mouse_left(xev, &mut callback); + }, + xinput2::XI_FocusIn => { + let xev: &XIFocusInEvent = unsafe { xev.as_event() }; + self.xinput2_focused(xev, &mut callback); + }, + xinput2::XI_FocusOut => { + let xev: &XIFocusOutEvent = unsafe { xev.as_event() }; + self.xinput2_unfocused(xev, &mut callback); + }, + xinput2::XI_TouchBegin | xinput2::XI_TouchUpdate | xinput2::XI_TouchEnd => { + let phase = match evtype { + xinput2::XI_TouchBegin => TouchPhase::Started, + xinput2::XI_TouchUpdate => TouchPhase::Moved, + xinput2::XI_TouchEnd => TouchPhase::Ended, + _ => unreachable!(), + }; + + let xev: &XIDeviceEvent = unsafe { xev.as_event() }; + self.xinput2_touch(xev, phase, &mut callback); + }, + xinput2::XI_RawButtonPress | xinput2::XI_RawButtonRelease => { + let state = match evtype { + xinput2::XI_RawButtonPress => ElementState::Pressed, + xinput2::XI_RawButtonRelease => ElementState::Released, + _ => unreachable!(), + }; + + let xev: &XIRawEvent = unsafe { xev.as_event() }; + self.xinput2_raw_button_input(xev, state, &mut callback); + }, + xinput2::XI_RawMotion => { + let xev: &XIRawEvent = unsafe { xev.as_event() }; + self.xinput2_raw_mouse_motion(xev, &mut callback); + }, + xinput2::XI_RawKeyPress | xinput2::XI_RawKeyRelease => { + let state = match evtype { + xinput2::XI_RawKeyPress => ElementState::Pressed, + xinput2::XI_RawKeyRelease => ElementState::Released, + _ => unreachable!(), + }; + + let xev: &xinput2::XIRawEvent = unsafe { xev.as_event() }; + self.xinput2_raw_key_input(xev, state, &mut callback); + }, + + xinput2::XI_HierarchyChanged => { + let xev: &XIHierarchyEvent = unsafe { xev.as_event() }; + self.xinput2_hierarchy_changed(xev, &mut callback); + }, + _ => {}, + } + }, + _ => { + if event_type == self.xkbext.first_event as _ { + let xev: &XkbAnyEvent = unsafe { &*(xev as *const _ as *const XkbAnyEvent) }; + self.xkb_event(xev, &mut callback); + } + if event_type == self.randr_event_offset as c_int { + self.process_dpi_change(&mut callback); + } + }, + } + } + + pub fn poll(&self) -> bool { + let window_target = Self::window_target(&self.target); + let result = unsafe { (window_target.xconn.xlib.XPending)(window_target.xconn.display) }; + + result != 0 + } + + pub unsafe fn poll_one_event(&mut self, event_ptr: *mut XEvent) -> bool { + let window_target = Self::window_target(&self.target); + // This function is used to poll and remove a single event + // from the Xlib event queue in a non-blocking, atomic way. + // XCheckIfEvent is non-blocking and removes events from queue. + // XNextEvent can't be used because it blocks while holding the + // global Xlib mutex. + // XPeekEvent does not remove events from the queue. + unsafe extern "C" fn predicate( + _display: *mut XDisplay, + _event: *mut XEvent, + _arg: *mut c_char, + ) -> c_int { + // This predicate always returns "true" (1) to accept all events + 1 + } + + let result = unsafe { + (window_target.xconn.xlib.XCheckIfEvent)( + window_target.xconn.display, + event_ptr, + Some(predicate), + std::ptr::null_mut(), + ) + }; + + result != 0 + } + + pub fn init_device(&self, device: xinput::DeviceId) { + let window_target = Self::window_target(&self.target); + let mut devices = self.devices.borrow_mut(); + if let Some(info) = DeviceInfo::get(&window_target.xconn, device as _) { + for info in info.iter() { + devices.insert(DeviceId(info.deviceid as _), Device::new(info)); + } + } + } + + pub fn with_window<F, Ret>(&self, window_id: xproto::Window, callback: F) -> Option<Ret> + where + F: Fn(&Arc<UnownedWindow>) -> Ret, + { + let mut deleted = false; + let window_id = WindowId(window_id as _); + let window_target = Self::window_target(&self.target); + let result = window_target + .windows + .borrow() + .get(&window_id) + .and_then(|window| { + let arc = window.upgrade(); + deleted = arc.is_none(); + arc + }) + .map(|window| callback(&window)); + + if deleted { + // Garbage collection + window_target.windows.borrow_mut().remove(&window_id); + } + + result + } + + // NOTE: we avoid `self` to not borrow the entire `self` as not mut. + /// Get the platform window target. + pub fn window_target(window_target: &RootAEL) -> &ActiveEventLoop { + match &window_target.p { + PlatformActiveEventLoop::X(target) => target, + #[cfg(wayland_platform)] + _ => unreachable!(), + } + } + + /// Get the platform window target. + pub fn window_target_mut(window_target: &mut RootAEL) -> &mut ActiveEventLoop { + match &mut window_target.p { + PlatformActiveEventLoop::X(target) => target, + #[cfg(wayland_platform)] + _ => unreachable!(), + } + } + + fn client_message<T: 'static, F>(&mut self, xev: &XClientMessageEvent, mut callback: F) + where + F: FnMut(&RootAEL, Event<T>), + { + let wt = Self::window_target(&self.target); + let atoms = wt.xconn.atoms(); + + let window = xev.window as xproto::Window; + let window_id = mkwid(window); + + if xev.data.get_long(0) as xproto::Atom == wt.wm_delete_window { + let event = Event::WindowEvent { window_id, event: WindowEvent::CloseRequested }; + callback(&self.target, event); + return; + } + + if xev.data.get_long(0) as xproto::Atom == wt.net_wm_ping { + let client_msg = xproto::ClientMessageEvent { + response_type: xproto::CLIENT_MESSAGE_EVENT, + format: xev.format as _, + sequence: xev.serial as _, + window: wt.root, + type_: xev.message_type as _, + data: xproto::ClientMessageData::from({ + let [a, b, c, d, e]: [c_long; 5] = xev.data.as_longs().try_into().unwrap(); + [a as u32, b as u32, c as u32, d as u32, e as u32] + }), + }; + + wt.xconn + .xcb_connection() + .send_event( + false, + wt.root, + xproto::EventMask::SUBSTRUCTURE_NOTIFY + | xproto::EventMask::SUBSTRUCTURE_REDIRECT, + client_msg.serialize(), + ) + .expect_then_ignore_error("Failed to send `ClientMessage` event."); + return; + } + + if xev.message_type == atoms[XdndEnter] as c_ulong { + let source_window = xev.data.get_long(0) as xproto::Window; + let flags = xev.data.get_long(1); + let version = flags >> 24; + self.dnd.version = Some(version); + let has_more_types = flags - (flags & (c_long::MAX - 1)) == 1; + if !has_more_types { + let type_list = vec![ + xev.data.get_long(2) as xproto::Atom, + xev.data.get_long(3) as xproto::Atom, + xev.data.get_long(4) as xproto::Atom, + ]; + self.dnd.type_list = Some(type_list); + } else if let Ok(more_types) = unsafe { self.dnd.get_type_list(source_window) } { + self.dnd.type_list = Some(more_types); + } + return; + } + + if xev.message_type == atoms[XdndPosition] as c_ulong { + // This event occurs every time the mouse moves while a file's being dragged + // over our window. We emit HoveredFile in response; while the macOS backend + // does that upon a drag entering, XDND doesn't have access to the actual drop + // data until this event. For parity with other platforms, we only emit + // `HoveredFile` the first time, though if winit's API is later extended to + // supply position updates with `HoveredFile` or another event, implementing + // that here would be trivial. + + let source_window = xev.data.get_long(0) as xproto::Window; + + // Equivalent to `(x << shift) | y` + // where `shift = mem::size_of::<c_short>() * 8` + // Note that coordinates are in "desktop space", not "window space" + // (in X11 parlance, they're root window coordinates) + // let packed_coordinates = xev.data.get_long(2); + // let shift = mem::size_of::<libc::c_short>() * 8; + // let x = packed_coordinates >> shift; + // let y = packed_coordinates & !(x << shift); + + // By our own state flow, `version` should never be `None` at this point. + let version = self.dnd.version.unwrap_or(5); + + // Action is specified in versions 2 and up, though we don't need it anyway. + // let action = xev.data.get_long(4); + + let accepted = if let Some(ref type_list) = self.dnd.type_list { + type_list.contains(&atoms[TextUriList]) + } else { + false + }; + + if !accepted { + unsafe { + self.dnd + .send_status(window, source_window, DndState::Rejected) + .expect("Failed to send `XdndStatus` message."); + } + self.dnd.reset(); + return; + } + + self.dnd.source_window = Some(source_window); + if self.dnd.result.is_none() { + let time = if version >= 1 { + xev.data.get_long(3) as xproto::Timestamp + } else { + // In version 0, time isn't specified + x11rb::CURRENT_TIME + }; + + // Log this timestamp. + wt.xconn.set_timestamp(time); + + // This results in the `SelectionNotify` event below + unsafe { + self.dnd.convert_selection(window, time); + } + } + + unsafe { + self.dnd + .send_status(window, source_window, DndState::Accepted) + .expect("Failed to send `XdndStatus` message."); + } + return; + } + + if xev.message_type == atoms[XdndDrop] as c_ulong { + let (source_window, state) = if let Some(source_window) = self.dnd.source_window { + if let Some(Ok(ref path_list)) = self.dnd.result { + for path in path_list { + let event = Event::WindowEvent { + window_id, + event: WindowEvent::DroppedFile(path.clone()), + }; + callback(&self.target, event); + } + } + (source_window, DndState::Accepted) + } else { + // `source_window` won't be part of our DND state if we already rejected the drop in + // our `XdndPosition` handler. + let source_window = xev.data.get_long(0) as xproto::Window; + (source_window, DndState::Rejected) + }; + + unsafe { + self.dnd + .send_finished(window, source_window, state) + .expect("Failed to send `XdndFinished` message."); + } + + self.dnd.reset(); + return; + } + + if xev.message_type == atoms[XdndLeave] as c_ulong { + self.dnd.reset(); + let event = Event::WindowEvent { window_id, event: WindowEvent::HoveredFileCancelled }; + callback(&self.target, event); + } + } + + fn selection_notify<T: 'static, F>(&mut self, xev: &XSelectionEvent, mut callback: F) + where + F: FnMut(&RootAEL, Event<T>), + { + let wt = Self::window_target(&self.target); + let atoms = wt.xconn.atoms(); + + let window = xev.requestor as xproto::Window; + let window_id = mkwid(window); + + // Set the timestamp. + wt.xconn.set_timestamp(xev.time as xproto::Timestamp); + + if xev.property != atoms[XdndSelection] as c_ulong { + return; + } + + // This is where we receive data from drag and drop + self.dnd.result = None; + if let Ok(mut data) = unsafe { self.dnd.read_data(window) } { + let parse_result = self.dnd.parse_data(&mut data); + if let Ok(ref path_list) = parse_result { + for path in path_list { + let event = Event::WindowEvent { + window_id, + event: WindowEvent::HoveredFile(path.clone()), + }; + callback(&self.target, event); + } + } + self.dnd.result = Some(parse_result); + } + } + + fn configure_notify<T: 'static, F>(&self, xev: &XConfigureEvent, mut callback: F) + where + F: FnMut(&RootAEL, Event<T>), + { + let wt = Self::window_target(&self.target); + + let xwindow = xev.window as xproto::Window; + let window_id = mkwid(xwindow); + + let window = match self.with_window(xwindow, Arc::clone) { + Some(window) => window, + None => return, + }; + + // So apparently... + // `XSendEvent` (synthetic `ConfigureNotify`) -> position relative to root + // `XConfigureNotify` (real `ConfigureNotify`) -> position relative to parent + // https://tronche.com/gui/x/icccm/sec-4.html#s-4.1.5 + // We don't want to send `Moved` when this is false, since then every `Resized` + // (whether the window moved or not) is accompanied by an extraneous `Moved` event + // that has a position relative to the parent window. + let is_synthetic = xev.send_event == xlib::True; + + // These are both in physical space. + let new_inner_size = (xev.width as u32, xev.height as u32); + let new_inner_position = (xev.x, xev.y); + + let (mut resized, moved) = { + let mut shared_state_lock = window.shared_state_lock(); + + let resized = util::maybe_change(&mut shared_state_lock.size, new_inner_size); + let moved = if is_synthetic { + util::maybe_change(&mut shared_state_lock.inner_position, new_inner_position) + } else { + // Detect when frame extents change. + // Since this isn't synthetic, as per the notes above, this position is relative to + // the parent window. + let rel_parent = new_inner_position; + if util::maybe_change(&mut shared_state_lock.inner_position_rel_parent, rel_parent) + { + // This ensures we process the next `Moved`. + shared_state_lock.inner_position = None; + // Extra insurance against stale frame extents. + shared_state_lock.frame_extents = None; + } + false + }; + (resized, moved) + }; + + let position = window.shared_state_lock().position; + + let new_outer_position = if let (Some(position), false) = (position, moved) { + position + } else { + let mut shared_state_lock = window.shared_state_lock(); + + // We need to convert client area position to window position. + let frame_extents = + shared_state_lock.frame_extents.as_ref().cloned().unwrap_or_else(|| { + let frame_extents = wt.xconn.get_frame_extents_heuristic(xwindow, wt.root); + shared_state_lock.frame_extents = Some(frame_extents.clone()); + frame_extents + }); + let outer = + frame_extents.inner_pos_to_outer(new_inner_position.0, new_inner_position.1); + shared_state_lock.position = Some(outer); + + // Unlock shared state to prevent deadlock in callback below + drop(shared_state_lock); + + if moved { + callback(&self.target, Event::WindowEvent { + window_id, + event: WindowEvent::Moved(outer.into()), + }); + } + outer + }; + + if is_synthetic { + let mut shared_state_lock = window.shared_state_lock(); + // If we don't use the existing adjusted value when available, then the user can screw + // up the resizing by dragging across monitors *without* dropping the + // window. + let (width, height) = + shared_state_lock.dpi_adjusted.unwrap_or((xev.width as u32, xev.height as u32)); + + let last_scale_factor = shared_state_lock.last_monitor.scale_factor; + let new_scale_factor = { + let window_rect = util::AaRect::new(new_outer_position, new_inner_size); + let monitor = wt + .xconn + .get_monitor_for_window(Some(window_rect)) + .expect("Failed to find monitor for window"); + + if monitor.is_dummy() { + // Avoid updating monitor using a dummy monitor handle + last_scale_factor + } else { + shared_state_lock.last_monitor = monitor.clone(); + monitor.scale_factor + } + }; + if last_scale_factor != new_scale_factor { + let (new_width, new_height) = window.adjust_for_dpi( + last_scale_factor, + new_scale_factor, + width, + height, + &shared_state_lock, + ); + + let old_inner_size = PhysicalSize::new(width, height); + let new_inner_size = PhysicalSize::new(new_width, new_height); + + // Unlock shared state to prevent deadlock in callback below + drop(shared_state_lock); + + let inner_size = Arc::new(Mutex::new(new_inner_size)); + callback(&self.target, Event::WindowEvent { + window_id, + event: WindowEvent::ScaleFactorChanged { + scale_factor: new_scale_factor, + inner_size_writer: InnerSizeWriter::new(Arc::downgrade(&inner_size)), + }, + }); + + let new_inner_size = *inner_size.lock().unwrap(); + drop(inner_size); + + if new_inner_size != old_inner_size { + window.request_inner_size_physical(new_inner_size.width, new_inner_size.height); + window.shared_state_lock().dpi_adjusted = Some(new_inner_size.into()); + // if the DPI factor changed, force a resize event to ensure the logical + // size is computed with the right DPI factor + resized = true; + } + } + } + + // NOTE: Ensure that the lock is dropped before handling the resized and + // sending the event back to user. + let hittest = { + let mut shared_state_lock = window.shared_state_lock(); + let hittest = shared_state_lock.cursor_hittest; + + // This is a hack to ensure that the DPI adjusted resize is actually + // applied on all WMs. KWin doesn't need this, but Xfwm does. The hack + // should not be run on other WMs, since tiling WMs constrain the window + // size, making the resize fail. This would cause an endless stream of + // XResizeWindow requests, making Xorg, the winit client, and the WM + // consume 100% of CPU. + if let Some(adjusted_size) = shared_state_lock.dpi_adjusted { + if new_inner_size == adjusted_size || !util::wm_name_is_one_of(&["Xfwm4"]) { + // When this finally happens, the event will not be synthetic. + shared_state_lock.dpi_adjusted = None; + } else { + // Unlock shared state to prevent deadlock in callback below + drop(shared_state_lock); + window.request_inner_size_physical(adjusted_size.0, adjusted_size.1); + } + } + + hittest + }; + + // Reload hittest. + if hittest.unwrap_or(false) { + let _ = window.set_cursor_hittest(true); + } + + if resized { + callback(&self.target, Event::WindowEvent { + window_id, + event: WindowEvent::Resized(new_inner_size.into()), + }); + } + } + + /// This is generally a reliable way to detect when the window manager's been + /// replaced, though this event is only fired by reparenting window managers + /// (which is almost all of them). Failing to correctly update WM info doesn't + /// really have much impact, since on the WMs affected (xmonad, dwm, etc.) the only + /// effect is that we waste some time trying to query unsupported properties. + fn reparent_notify(&self, xev: &XReparentEvent) { + let wt = Self::window_target(&self.target); + + wt.xconn.update_cached_wm_info(wt.root); + + self.with_window(xev.window as xproto::Window, |window| { + window.invalidate_cached_frame_extents(); + }); + } + + fn map_notify<T: 'static, F>(&self, xev: &XMapEvent, mut callback: F) + where + F: FnMut(&RootAEL, Event<T>), + { + let window = xev.window as xproto::Window; + let window_id = mkwid(window); + + // NOTE: Re-issue the focus state when mapping the window. + // + // The purpose of it is to deliver initial focused state of the newly created + // window, given that we can't rely on `CreateNotify`, due to it being not + // sent. + let focus = self.with_window(window, |window| window.has_focus()).unwrap_or_default(); + let event = Event::WindowEvent { window_id, event: WindowEvent::Focused(focus) }; + + callback(&self.target, event); + } + + fn destroy_notify<T: 'static, F>(&self, xev: &XDestroyWindowEvent, mut callback: F) + where + F: FnMut(&RootAEL, Event<T>), + { + let wt = Self::window_target(&self.target); + + let window = xev.window as xproto::Window; + let window_id = mkwid(window); + + // In the event that the window's been destroyed without being dropped first, we + // cleanup again here. + wt.windows.borrow_mut().remove(&WindowId(window as _)); + + // Since all XIM stuff needs to happen from the same thread, we destroy the input + // context here instead of when dropping the window. + if let Some(ime) = wt.ime.as_ref() { + ime.borrow_mut() + .remove_context(window as XWindow) + .expect("Failed to destroy input context"); + } + + callback(&self.target, Event::WindowEvent { window_id, event: WindowEvent::Destroyed }); + } + + fn property_notify<T: 'static, F>(&mut self, xev: &XPropertyEvent, mut callback: F) + where + F: FnMut(&RootAEL, Event<T>), + { + let wt = Self::window_target(&self.target); + let atoms = wt.x_connection().atoms(); + let atom = xev.atom as xproto::Atom; + + if atom == xproto::Atom::from(xproto::AtomEnum::RESOURCE_MANAGER) + || atom == atoms[_XSETTINGS_SETTINGS] + { + self.process_dpi_change(&mut callback); + } + } + + fn visibility_notify<T: 'static, F>(&self, xev: &XVisibilityEvent, mut callback: F) + where + F: FnMut(&RootAEL, Event<T>), + { + let xwindow = xev.window as xproto::Window; + + let event = Event::WindowEvent { + window_id: mkwid(xwindow), + event: WindowEvent::Occluded(xev.state == xlib::VisibilityFullyObscured), + }; + callback(&self.target, event); + + self.with_window(xwindow, |window| { + window.visibility_notify(); + }); + } + + fn expose<T: 'static, F>(&self, xev: &XExposeEvent, mut callback: F) + where + F: FnMut(&RootAEL, Event<T>), + { + // Multiple Expose events may be received for subareas of a window. + // We issue `RedrawRequested` only for the last event of such a series. + if xev.count == 0 { + let window = xev.window as xproto::Window; + let window_id = mkwid(window); + + let event = Event::WindowEvent { window_id, event: WindowEvent::RedrawRequested }; + + callback(&self.target, event); + } + } + + fn xinput_key_input<T: 'static, F>( + &mut self, + xev: &mut XKeyEvent, + state: ElementState, + mut callback: F, + ) where + F: FnMut(&RootAEL, Event<T>), + { + let wt = Self::window_target(&self.target); + + // Set the timestamp. + wt.xconn.set_timestamp(xev.time as xproto::Timestamp); + + let window = match self.active_window { + Some(window) => window, + None => return, + }; + + let window_id = mkwid(window); + let device_id = mkdid(util::VIRTUAL_CORE_KEYBOARD); + + let keycode = xev.keycode as _; + + // Update state to track key repeats and determine whether this key was a repeat. + // + // Note, when a key is held before focusing on this window the first + // (non-synthetic) event will not be flagged as a repeat (also note that the + // synthetic press event that is generated before this when the window gains focus + // will also not be flagged as a repeat). + // + // Only keys that can repeat should change the held_key_press state since a + // continuously held repeatable key may continue repeating after the press of a + // non-repeatable key. + let key_repeats = + self.xkb_context.keymap_mut().map(|k| k.key_repeats(keycode)).unwrap_or(false); + let repeat = if key_repeats { + let is_latest_held = self.held_key_press == Some(keycode); + + if state == ElementState::Pressed { + self.held_key_press = Some(keycode); + is_latest_held + } else { + // Check that the released key is the latest repeatable key that has been + // pressed, since repeats will continue for the latest key press if a + // different previously pressed key is released. + if is_latest_held { + self.held_key_press = None; + } + false + } + } else { + false + }; + + // NOTE: When the modifier was captured by the XFilterEvents the modifiers for the modifier + // itself are out of sync due to XkbState being delivered before XKeyEvent, since it's + // being replayed by the XIM, thus we should replay ourselves. + let replay = if let Some(position) = + self.xfiltered_modifiers.iter().rev().position(|&s| s == xev.keycode as u8) + { + // We don't have to replay modifiers pressed before the current event if some events + // were not forwarded to us, since their state is irrelevant. + self.xfiltered_modifiers.resize(self.xfiltered_modifiers.len() - 1 - position, 0); + true + } else { + false + }; + + // Always update the modifiers when we're not replaying. + if !replay { + self.update_mods_from_core_event(window_id, xev.state as u16, &mut callback); + } + + if keycode != 0 && !self.is_composing { + // Don't alter the modifiers state from replaying. + if replay { + self.send_synthic_modifier_from_core(window_id, xev.state as u16, &mut callback); + } + + if let Some(mut key_processor) = self.xkb_context.key_context() { + let event = key_processor.process_key_event(keycode, state, repeat); + let event = Event::WindowEvent { + window_id, + event: WindowEvent::KeyboardInput { device_id, event, is_synthetic: false }, + }; + callback(&self.target, event); + } + + // Restore the client's modifiers state after replay. + if replay { + self.send_modifiers(window_id, self.modifiers.get(), true, &mut callback); + } + + return; + } + + let wt = Self::window_target(&self.target); + + if let Some(ic) = + wt.ime.as_ref().and_then(|ime| ime.borrow().get_context(window as XWindow)) + { + let written = wt.xconn.lookup_utf8(ic, xev); + if !written.is_empty() { + let event = Event::WindowEvent { + window_id, + event: WindowEvent::Ime(Ime::Preedit(String::new(), None)), + }; + callback(&self.target, event); + + let event = + Event::WindowEvent { window_id, event: WindowEvent::Ime(Ime::Commit(written)) }; + + self.is_composing = false; + callback(&self.target, event); + } + } + } + + fn send_synthic_modifier_from_core<T: 'static, F>( + &mut self, + window_id: crate::window::WindowId, + state: u16, + mut callback: F, + ) where + F: FnMut(&RootAEL, Event<T>), + { + let keymap = match self.xkb_context.keymap_mut() { + Some(keymap) => keymap, + None => return, + }; + + let wt = Self::window_target(&self.target); + let xcb = wt.xconn.xcb_connection().get_raw_xcb_connection(); + + // Use synthetic state since we're replaying the modifier. The user modifier state + // will be restored later. + let mut xkb_state = match XkbState::new_x11(xcb, keymap) { + Some(xkb_state) => xkb_state, + None => return, + }; + + let mask = self.xkb_mod_mask_from_core(state); + xkb_state.update_modifiers(mask, 0, 0, 0, 0, Self::core_keyboard_group(state)); + let mods: ModifiersState = xkb_state.modifiers().into(); + + let event = + Event::WindowEvent { window_id, event: WindowEvent::ModifiersChanged(mods.into()) }; + + callback(&self.target, event); + } + + fn xinput2_button_input<T: 'static, F>( + &self, + event: &XIDeviceEvent, + state: ElementState, + mut callback: F, + ) where + F: FnMut(&RootAEL, Event<T>), + { + let wt = Self::window_target(&self.target); + let window_id = mkwid(event.event as xproto::Window); + let device_id = mkdid(event.deviceid as xinput::DeviceId); + + // Set the timestamp. + wt.xconn.set_timestamp(event.time as xproto::Timestamp); + + // Deliver multi-touch events instead of emulated mouse events. + if (event.flags & xinput2::XIPointerEmulated) != 0 { + return; + } + + let event = match event.detail as u32 { + xlib::Button1 => { + WindowEvent::MouseInput { device_id, state, button: MouseButton::Left } + }, + xlib::Button2 => { + WindowEvent::MouseInput { device_id, state, button: MouseButton::Middle } + }, + + xlib::Button3 => { + WindowEvent::MouseInput { device_id, state, button: MouseButton::Right } + }, + + // Suppress emulated scroll wheel clicks, since we handle the real motion events for + // those. In practice, even clicky scroll wheels appear to be reported by + // evdev (and XInput2 in turn) as axis motion, so we don't otherwise + // special-case these button presses. + 4..=7 => WindowEvent::MouseWheel { + device_id, + delta: match event.detail { + 4 => MouseScrollDelta::LineDelta(0.0, 1.0), + 5 => MouseScrollDelta::LineDelta(0.0, -1.0), + 6 => MouseScrollDelta::LineDelta(1.0, 0.0), + 7 => MouseScrollDelta::LineDelta(-1.0, 0.0), + _ => unreachable!(), + }, + phase: TouchPhase::Moved, + }, + 8 => WindowEvent::MouseInput { device_id, state, button: MouseButton::Back }, + + 9 => WindowEvent::MouseInput { device_id, state, button: MouseButton::Forward }, + x => WindowEvent::MouseInput { device_id, state, button: MouseButton::Other(x as u16) }, + }; + + let event = Event::WindowEvent { window_id, event }; + callback(&self.target, event); + } + + fn xinput2_mouse_motion<T: 'static, F>(&self, event: &XIDeviceEvent, mut callback: F) + where + F: FnMut(&RootAEL, Event<T>), + { + let wt = Self::window_target(&self.target); + + // Set the timestamp. + wt.xconn.set_timestamp(event.time as xproto::Timestamp); + + let device_id = mkdid(event.deviceid as xinput::DeviceId); + let window = event.event as xproto::Window; + let window_id = mkwid(window); + let new_cursor_pos = (event.event_x, event.event_y); + + let cursor_moved = self.with_window(window, |window| { + let mut shared_state_lock = window.shared_state_lock(); + util::maybe_change(&mut shared_state_lock.cursor_pos, new_cursor_pos) + }); + + if cursor_moved == Some(true) { + let position = PhysicalPosition::new(event.event_x, event.event_y); + + let event = Event::WindowEvent { + window_id, + event: WindowEvent::CursorMoved { device_id, position }, + }; + callback(&self.target, event); + } else if cursor_moved.is_none() { + return; + } + + // More gymnastics, for self.devices + let mask = unsafe { + slice::from_raw_parts(event.valuators.mask, event.valuators.mask_len as usize) + }; + let mut devices = self.devices.borrow_mut(); + let physical_device = match devices.get_mut(&DeviceId(event.sourceid as xinput::DeviceId)) { + Some(device) => device, + None => return, + }; + + let mut events = Vec::new(); + let mut value = event.valuators.values; + for i in 0..event.valuators.mask_len * 8 { + if !xinput2::XIMaskIsSet(mask, i) { + continue; + } + + let x = unsafe { *value }; + + let event = if let Some(&mut (_, ref mut info)) = + physical_device.scroll_axes.iter_mut().find(|&&mut (axis, _)| axis == i as _) + { + let delta = (x - info.position) / info.increment; + info.position = x; + // X11 vertical scroll coordinates are opposite to winit's + let delta = match info.orientation { + ScrollOrientation::Horizontal => { + MouseScrollDelta::LineDelta(-delta as f32, 0.0) + }, + ScrollOrientation::Vertical => MouseScrollDelta::LineDelta(0.0, -delta as f32), + }; + + WindowEvent::MouseWheel { device_id, delta, phase: TouchPhase::Moved } + } else { + WindowEvent::AxisMotion { device_id, axis: i as u32, value: unsafe { *value } } + }; + + events.push(Event::WindowEvent { window_id, event }); + + value = unsafe { value.offset(1) }; + } + + for event in events { + callback(&self.target, event); + } + } + + fn xinput2_mouse_enter<T: 'static, F>(&self, event: &XIEnterEvent, mut callback: F) + where + F: FnMut(&RootAEL, Event<T>), + { + let wt = Self::window_target(&self.target); + + // Set the timestamp. + wt.xconn.set_timestamp(event.time as xproto::Timestamp); + + let window = event.event as xproto::Window; + let window_id = mkwid(window); + let device_id = mkdid(event.deviceid as xinput::DeviceId); + + if let Some(all_info) = DeviceInfo::get(&wt.xconn, super::ALL_DEVICES.into()) { + let mut devices = self.devices.borrow_mut(); + for device_info in all_info.iter() { + // The second expression is need for resetting to work correctly on i3, and + // presumably some other WMs. On those, `XI_Enter` doesn't include the physical + // device ID, so both `sourceid` and `deviceid` are the virtual device. + if device_info.deviceid == event.sourceid + || device_info.attachment == event.sourceid + { + let device_id = DeviceId(device_info.deviceid as _); + if let Some(device) = devices.get_mut(&device_id) { + device.reset_scroll_position(device_info); + } + } + } + } + + if self.window_exists(window) { + let position = PhysicalPosition::new(event.event_x, event.event_y); + + let event = + Event::WindowEvent { window_id, event: WindowEvent::CursorEntered { device_id } }; + callback(&self.target, event); + + let event = Event::WindowEvent { + window_id, + event: WindowEvent::CursorMoved { device_id, position }, + }; + callback(&self.target, event); + } + } + + fn xinput2_mouse_left<T: 'static, F>(&self, event: &XILeaveEvent, mut callback: F) + where + F: FnMut(&RootAEL, Event<T>), + { + let wt = Self::window_target(&self.target); + let window = event.event as xproto::Window; + + // Set the timestamp. + wt.xconn.set_timestamp(event.time as xproto::Timestamp); + + // Leave, FocusIn, and FocusOut can be received by a window that's already + // been destroyed, which the user presumably doesn't want to deal with. + if self.window_exists(window) { + let event = Event::WindowEvent { + window_id: mkwid(window), + event: WindowEvent::CursorLeft { + device_id: mkdid(event.deviceid as xinput::DeviceId), + }, + }; + callback(&self.target, event); + } + } + + fn xinput2_focused<T: 'static, F>(&mut self, xev: &XIFocusInEvent, mut callback: F) + where + F: FnMut(&RootAEL, Event<T>), + { + let wt = Self::window_target(&self.target); + let window = xev.event as xproto::Window; + + // Set the timestamp. + wt.xconn.set_timestamp(xev.time as xproto::Timestamp); + + if let Some(ime) = wt.ime.as_ref() { + ime.borrow_mut().focus(xev.event).expect("Failed to focus input context"); + } + + if self.active_window == Some(window) { + return; + } + + self.active_window = Some(window); + + wt.update_listen_device_events(true); + + let window_id = mkwid(window); + let position = PhysicalPosition::new(xev.event_x, xev.event_y); + + if let Some(window) = self.with_window(window, Arc::clone) { + window.shared_state_lock().has_focus = true; + } + + let event = Event::WindowEvent { window_id, event: WindowEvent::Focused(true) }; + callback(&self.target, event); + + // Issue key press events for all pressed keys + Self::handle_pressed_keys( + &self.target, + window_id, + ElementState::Pressed, + &mut self.xkb_context, + &mut callback, + ); + + self.update_mods_from_query(window_id, &mut callback); + + // The deviceid for this event is for a keyboard instead of a pointer, + // so we have to do a little extra work. + let pointer_id = self + .devices + .borrow() + .get(&DeviceId(xev.deviceid as xinput::DeviceId)) + .map(|device| device.attachment) + .unwrap_or(2); + + let event = Event::WindowEvent { + window_id, + event: WindowEvent::CursorMoved { device_id: mkdid(pointer_id as _), position }, + }; + callback(&self.target, event); + } + + fn xinput2_unfocused<T: 'static, F>(&mut self, xev: &XIFocusOutEvent, mut callback: F) + where + F: FnMut(&RootAEL, Event<T>), + { + let wt = Self::window_target(&self.target); + let window = xev.event as xproto::Window; + + // Set the timestamp. + wt.xconn.set_timestamp(xev.time as xproto::Timestamp); + + if !self.window_exists(window) { + return; + } + + if let Some(ime) = wt.ime.as_ref() { + ime.borrow_mut().unfocus(xev.event).expect("Failed to unfocus input context"); + } + + if self.active_window.take() == Some(window) { + let window_id = mkwid(window); + + wt.update_listen_device_events(false); + + // Clear the modifiers when unfocusing the window. + if let Some(xkb_state) = self.xkb_context.state_mut() { + xkb_state.update_modifiers(0, 0, 0, 0, 0, 0); + let mods = xkb_state.modifiers(); + self.send_modifiers(window_id, mods.into(), true, &mut callback); + } + + // Issue key release events for all pressed keys + Self::handle_pressed_keys( + &self.target, + window_id, + ElementState::Released, + &mut self.xkb_context, + &mut callback, + ); + + // Clear this so detecting key repeats is consistently handled when the + // window regains focus. + self.held_key_press = None; + + if let Some(window) = self.with_window(window, Arc::clone) { + window.shared_state_lock().has_focus = false; + } + + let event = Event::WindowEvent { window_id, event: WindowEvent::Focused(false) }; + callback(&self.target, event) + } + } + + fn xinput2_touch<T: 'static, F>( + &mut self, + xev: &XIDeviceEvent, + phase: TouchPhase, + mut callback: F, + ) where + F: FnMut(&RootAEL, Event<T>), + { + let wt = Self::window_target(&self.target); + + // Set the timestamp. + wt.xconn.set_timestamp(xev.time as xproto::Timestamp); + + let window = xev.event as xproto::Window; + if self.window_exists(window) { + let window_id = mkwid(window); + let id = xev.detail as u64; + let location = PhysicalPosition::new(xev.event_x, xev.event_y); + + // Mouse cursor position changes when touch events are received. + // Only the first concurrently active touch ID moves the mouse cursor. + if is_first_touch(&mut self.first_touch, &mut self.num_touch, id, phase) { + let event = Event::WindowEvent { + window_id, + event: WindowEvent::CursorMoved { + device_id: mkdid(util::VIRTUAL_CORE_POINTER), + position: location.cast(), + }, + }; + callback(&self.target, event); + } + + let event = Event::WindowEvent { + window_id, + event: WindowEvent::Touch(Touch { + device_id: mkdid(xev.deviceid as xinput::DeviceId), + phase, + location, + force: None, // TODO + id, + }), + }; + callback(&self.target, event) + } + } + + fn xinput2_raw_button_input<T: 'static, F>( + &self, + xev: &XIRawEvent, + state: ElementState, + mut callback: F, + ) where + F: FnMut(&RootAEL, Event<T>), + { + let wt = Self::window_target(&self.target); + + // Set the timestamp. + wt.xconn.set_timestamp(xev.time as xproto::Timestamp); + + if xev.flags & xinput2::XIPointerEmulated == 0 { + let event = Event::DeviceEvent { + device_id: mkdid(xev.deviceid as xinput::DeviceId), + event: DeviceEvent::Button { state, button: xev.detail as u32 }, + }; + callback(&self.target, event); + } + } + + fn xinput2_raw_mouse_motion<T: 'static, F>(&self, xev: &XIRawEvent, mut callback: F) + where + F: FnMut(&RootAEL, Event<T>), + { + let wt = Self::window_target(&self.target); + + // Set the timestamp. + wt.xconn.set_timestamp(xev.time as xproto::Timestamp); + + let did = mkdid(xev.deviceid as xinput::DeviceId); + + let mask = + unsafe { slice::from_raw_parts(xev.valuators.mask, xev.valuators.mask_len as usize) }; + let mut value = xev.raw_values; + let mut mouse_delta = util::Delta::default(); + let mut scroll_delta = util::Delta::default(); + for i in 0..xev.valuators.mask_len * 8 { + if !xinput2::XIMaskIsSet(mask, i) { + continue; + } + let x = unsafe { value.read_unaligned() }; + + // We assume that every XInput2 device with analog axes is a pointing device emitting + // relative coordinates. + match i { + 0 => mouse_delta.set_x(x), + 1 => mouse_delta.set_y(x), + 2 => scroll_delta.set_x(x as f32), + 3 => scroll_delta.set_y(x as f32), + _ => {}, + } + + let event = Event::DeviceEvent { + device_id: did, + event: DeviceEvent::Motion { axis: i as u32, value: x }, + }; + callback(&self.target, event); + + value = unsafe { value.offset(1) }; + } + + if let Some(mouse_delta) = mouse_delta.consume() { + let event = Event::DeviceEvent { + device_id: did, + event: DeviceEvent::MouseMotion { delta: mouse_delta }, + }; + callback(&self.target, event); + } + + if let Some(scroll_delta) = scroll_delta.consume() { + let event = Event::DeviceEvent { + device_id: did, + event: DeviceEvent::MouseWheel { + delta: MouseScrollDelta::LineDelta(scroll_delta.0, scroll_delta.1), + }, + }; + callback(&self.target, event); + } + } + + fn xinput2_raw_key_input<T: 'static, F>( + &mut self, + xev: &XIRawEvent, + state: ElementState, + mut callback: F, + ) where + F: FnMut(&RootAEL, Event<T>), + { + let wt = Self::window_target(&self.target); + + // Set the timestamp. + wt.xconn.set_timestamp(xev.time as xproto::Timestamp); + + let device_id = mkdid(xev.sourceid as xinput::DeviceId); + let keycode = xev.detail as u32; + if keycode < KEYCODE_OFFSET as u32 { + return; + } + let physical_key = xkb::raw_keycode_to_physicalkey(keycode); + + callback(&self.target, Event::DeviceEvent { + device_id, + event: DeviceEvent::Key(RawKeyEvent { physical_key, state }), + }); + } + + fn xinput2_hierarchy_changed<T: 'static, F>(&mut self, xev: &XIHierarchyEvent, mut callback: F) + where + F: FnMut(&RootAEL, Event<T>), + { + let wt = Self::window_target(&self.target); + + // Set the timestamp. + wt.xconn.set_timestamp(xev.time as xproto::Timestamp); + let infos = unsafe { slice::from_raw_parts(xev.info, xev.num_info as usize) }; + for info in infos { + if 0 != info.flags & (xinput2::XISlaveAdded | xinput2::XIMasterAdded) { + self.init_device(info.deviceid as xinput::DeviceId); + callback(&self.target, Event::DeviceEvent { + device_id: mkdid(info.deviceid as xinput::DeviceId), + event: DeviceEvent::Added, + }); + } else if 0 != info.flags & (xinput2::XISlaveRemoved | xinput2::XIMasterRemoved) { + callback(&self.target, Event::DeviceEvent { + device_id: mkdid(info.deviceid as xinput::DeviceId), + event: DeviceEvent::Removed, + }); + let mut devices = self.devices.borrow_mut(); + devices.remove(&DeviceId(info.deviceid as xinput::DeviceId)); + } + } + } + + fn xkb_event<T: 'static, F>(&mut self, xev: &XkbAnyEvent, mut callback: F) + where + F: FnMut(&RootAEL, Event<T>), + { + let wt = Self::window_target(&self.target); + match xev.xkb_type { + xlib::XkbNewKeyboardNotify => { + let xev = unsafe { &*(xev as *const _ as *const xlib::XkbNewKeyboardNotifyEvent) }; + + // Set the timestamp. + wt.xconn.set_timestamp(xev.time as xproto::Timestamp); + + let keycodes_changed_flag = 0x1; + let geometry_changed_flag = 0x1 << 1; + + let keycodes_changed = util::has_flag(xev.changed, keycodes_changed_flag); + let geometry_changed = util::has_flag(xev.changed, geometry_changed_flag); + + if xev.device == self.xkb_context.core_keyboard_id + && (keycodes_changed || geometry_changed) + { + let xcb = wt.xconn.xcb_connection().get_raw_xcb_connection(); + self.xkb_context.set_keymap_from_x11(xcb); + self.xmodmap.reload_from_x_connection(&wt.xconn); + + let window_id = match self.active_window.map(super::mkwid) { + Some(window_id) => window_id, + None => return, + }; + + if let Some(state) = self.xkb_context.state_mut() { + let mods = state.modifiers().into(); + self.send_modifiers(window_id, mods, true, &mut callback); + } + } + }, + xlib::XkbMapNotify => { + let xcb = wt.xconn.xcb_connection().get_raw_xcb_connection(); + self.xkb_context.set_keymap_from_x11(xcb); + self.xmodmap.reload_from_x_connection(&wt.xconn); + let window_id = match self.active_window.map(super::mkwid) { + Some(window_id) => window_id, + None => return, + }; + + if let Some(state) = self.xkb_context.state_mut() { + let mods = state.modifiers().into(); + self.send_modifiers(window_id, mods, true, &mut callback); + } + }, + xlib::XkbStateNotify => { + let xev = unsafe { &*(xev as *const _ as *const xlib::XkbStateNotifyEvent) }; + + // Set the timestamp. + wt.xconn.set_timestamp(xev.time as xproto::Timestamp); + + if let Some(state) = self.xkb_context.state_mut() { + state.update_modifiers( + xev.base_mods, + xev.latched_mods, + xev.locked_mods, + xev.base_group as u32, + xev.latched_group as u32, + xev.locked_group as u32, + ); + + let window_id = match self.active_window.map(super::mkwid) { + Some(window_id) => window_id, + None => return, + }; + + let mods = state.modifiers().into(); + self.send_modifiers(window_id, mods, true, &mut callback); + } + }, + _ => {}, + } + } + + pub fn update_mods_from_xinput2_event<T: 'static, F>( + &mut self, + mods: &XIModifierState, + group: &XIModifierState, + force: bool, + mut callback: F, + ) where + F: FnMut(&RootAEL, Event<T>), + { + if let Some(state) = self.xkb_context.state_mut() { + state.update_modifiers( + mods.base as u32, + mods.latched as u32, + mods.locked as u32, + group.base as u32, + group.latched as u32, + group.locked as u32, + ); + + // NOTE: we use active window since generally sub windows don't have keyboard input, + // and winit assumes that unfocused window doesn't have modifiers. + let window_id = match self.active_window.map(super::mkwid) { + Some(window_id) => window_id, + None => return, + }; + + let mods = state.modifiers(); + self.send_modifiers(window_id, mods.into(), force, &mut callback); + } + } + + fn update_mods_from_query<T: 'static, F>( + &mut self, + window_id: crate::window::WindowId, + mut callback: F, + ) where + F: FnMut(&RootAEL, Event<T>), + { + let wt = Self::window_target(&self.target); + + let xkb_state = match self.xkb_context.state_mut() { + Some(xkb_state) => xkb_state, + None => return, + }; + + unsafe { + let mut state: XkbStateRec = std::mem::zeroed(); + if (wt.xconn.xlib.XkbGetState)(wt.xconn.display, XkbId::USE_CORE_KBD.into(), &mut state) + == xlib::True + { + xkb_state.update_modifiers( + state.base_mods as u32, + state.latched_mods as u32, + state.locked_mods as u32, + state.base_group as u32, + state.latched_group as u32, + state.locked_group as u32, + ); + } + } + + let mods = xkb_state.modifiers(); + self.send_modifiers(window_id, mods.into(), true, &mut callback) + } + + pub fn update_mods_from_core_event<T: 'static, F>( + &mut self, + window_id: crate::window::WindowId, + state: u16, + mut callback: F, + ) where + F: FnMut(&RootAEL, Event<T>), + { + let xkb_mask = self.xkb_mod_mask_from_core(state); + let xkb_state = match self.xkb_context.state_mut() { + Some(xkb_state) => xkb_state, + None => return, + }; + + // NOTE: this is inspired by Qt impl. + let mut depressed = xkb_state.depressed_modifiers() & xkb_mask; + let latched = xkb_state.latched_modifiers() & xkb_mask; + let locked = xkb_state.locked_modifiers() & xkb_mask; + // Set modifiers in depressed if they don't appear in any of the final masks. + depressed |= !(depressed | latched | locked) & xkb_mask; + + xkb_state.update_modifiers( + depressed, + latched, + locked, + 0, + 0, + Self::core_keyboard_group(state), + ); + + let mods = xkb_state.modifiers(); + self.send_modifiers(window_id, mods.into(), false, &mut callback); + } + + // Bits 13 and 14 report the state keyboard group. + pub fn core_keyboard_group(state: u16) -> u32 { + ((state >> 13) & 3) as u32 + } + + pub fn xkb_mod_mask_from_core(&mut self, state: u16) -> xkb_mod_mask_t { + let mods_indices = match self.xkb_context.keymap_mut() { + Some(keymap) => keymap.mods_indices(), + None => return 0, + }; + + // Build the XKB modifiers from the regular state. + let mut depressed = 0u32; + if let Some(shift) = mods_indices.shift.filter(|_| ModMask::SHIFT.intersects(state)) { + depressed |= 1 << shift; + } + if let Some(caps) = mods_indices.caps.filter(|_| ModMask::LOCK.intersects(state)) { + depressed |= 1 << caps; + } + if let Some(ctrl) = mods_indices.ctrl.filter(|_| ModMask::CONTROL.intersects(state)) { + depressed |= 1 << ctrl; + } + if let Some(alt) = mods_indices.alt.filter(|_| ModMask::M1.intersects(state)) { + depressed |= 1 << alt; + } + if let Some(num) = mods_indices.num.filter(|_| ModMask::M2.intersects(state)) { + depressed |= 1 << num; + } + if let Some(mod3) = mods_indices.mod3.filter(|_| ModMask::M3.intersects(state)) { + depressed |= 1 << mod3; + } + if let Some(logo) = mods_indices.logo.filter(|_| ModMask::M4.intersects(state)) { + depressed |= 1 << logo; + } + if let Some(mod5) = mods_indices.mod5.filter(|_| ModMask::M5.intersects(state)) { + depressed |= 1 << mod5; + } + + depressed + } + + /// Send modifiers for the active window. + /// + /// The event won't be sent when the `modifiers` match the previously `sent` modifiers value, + /// unless `force` is passed. The `force` should be passed when the active window changes. + fn send_modifiers<T: 'static, F: FnMut(&RootAEL, Event<T>)>( + &self, + window_id: crate::window::WindowId, + modifiers: ModifiersState, + force: bool, + callback: &mut F, + ) { + // NOTE: Always update the modifiers to account for case when they've changed + // and forced was `true`. + if self.modifiers.replace(modifiers) != modifiers || force { + let event = Event::WindowEvent { + window_id, + event: WindowEvent::ModifiersChanged(self.modifiers.get().into()), + }; + callback(&self.target, event); + } + } + + fn handle_pressed_keys<T: 'static, F>( + target: &RootAEL, + window_id: crate::window::WindowId, + state: ElementState, + xkb_context: &mut Context, + callback: &mut F, + ) where + F: FnMut(&RootAEL, Event<T>), + { + let device_id = mkdid(util::VIRTUAL_CORE_KEYBOARD); + + // Update modifiers state and emit key events based on which keys are currently pressed. + let window_target = Self::window_target(target); + let xcb = window_target.xconn.xcb_connection().get_raw_xcb_connection(); + + let keymap = match xkb_context.keymap_mut() { + Some(keymap) => keymap, + None => return, + }; + + // Send the keys using the synthetic state to not alter the main state. + let mut xkb_state = match XkbState::new_x11(xcb, keymap) { + Some(xkb_state) => xkb_state, + None => return, + }; + let mut key_processor = match xkb_context.key_context_with_state(&mut xkb_state) { + Some(key_processor) => key_processor, + None => return, + }; + + for keycode in + window_target.xconn.query_keymap().into_iter().filter(|k| *k >= KEYCODE_OFFSET) + { + let event = key_processor.process_key_event(keycode as u32, state, false); + let event = Event::WindowEvent { + window_id, + event: WindowEvent::KeyboardInput { device_id, event, is_synthetic: true }, + }; + callback(target, event); + } + } + + fn process_dpi_change<T: 'static, F>(&self, callback: &mut F) + where + F: FnMut(&RootAEL, Event<T>), + { + let wt = Self::window_target(&self.target); + wt.xconn.reload_database().expect("failed to reload Xft database"); + + // In the future, it would be quite easy to emit monitor hotplug events. + let prev_list = { + let prev_list = wt.xconn.invalidate_cached_monitor_list(); + match prev_list { + Some(prev_list) => prev_list, + None => return, + } + }; + + let new_list = wt.xconn.available_monitors().expect("Failed to get monitor list"); + for new_monitor in new_list { + // Previous list may be empty, in case of disconnecting and + // reconnecting the only one monitor. We still need to emit events in + // this case. + let maybe_prev_scale_factor = prev_list + .iter() + .find(|prev_monitor| prev_monitor.name == new_monitor.name) + .map(|prev_monitor| prev_monitor.scale_factor); + if Some(new_monitor.scale_factor) != maybe_prev_scale_factor { + for window in wt.windows.borrow().iter().filter_map(|(_, w)| w.upgrade()) { + window.refresh_dpi_for_monitor(&new_monitor, maybe_prev_scale_factor, |event| { + callback(&self.target, event); + }) + } + } + } + } + + fn window_exists(&self, window_id: xproto::Window) -> bool { + self.with_window(window_id, |_| ()).is_some() + } +} + +fn is_first_touch(first: &mut Option<u64>, num: &mut u32, id: u64, phase: TouchPhase) -> bool { + match phase { + TouchPhase::Started => { + if *num == 0 { + *first = Some(id); + } + *num += 1; + }, + TouchPhase::Cancelled | TouchPhase::Ended => { + if *first == Some(id) { + *first = None; + } + *num = num.saturating_sub(1); + }, + _ => (), + } + + *first == Some(id) +} diff --git a/app/vendor/rune/vendor/winit/src/platform_impl/linux/x11/ffi.rs b/app/vendor/rune/vendor/winit/src/platform_impl/linux/x11/ffi.rs new file mode 100644 index 0000000..57bd78e --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/platform_impl/linux/x11/ffi.rs @@ -0,0 +1,5 @@ +pub use x11_dl::error::OpenError; +pub use x11_dl::xcursor::*; +pub use x11_dl::xinput2::*; +pub use x11_dl::xlib::*; +pub use x11_dl::xlib_xcb::*; diff --git a/app/vendor/rune/vendor/winit/src/platform_impl/linux/x11/ime/callbacks.rs b/app/vendor/rune/vendor/winit/src/platform_impl/linux/x11/ime/callbacks.rs new file mode 100644 index 0000000..fa0fa5c --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/platform_impl/linux/x11/ime/callbacks.rs @@ -0,0 +1,206 @@ +use std::collections::HashMap; +use std::os::raw::c_char; +use std::ptr; +use std::sync::Arc; + +use super::{ffi, XConnection, XError}; + +use super::context::{ImeContext, ImeContextCreationError}; +use super::inner::{close_im, ImeInner}; +use super::input_method::PotentialInputMethods; + +pub(crate) unsafe fn xim_set_callback( + xconn: &Arc<XConnection>, + xim: ffi::XIM, + field: *const c_char, + callback: *mut ffi::XIMCallback, +) -> Result<(), XError> { + // It's advisable to wrap variadic FFI functions in our own functions, as we want to minimize + // access that isn't type-checked. + unsafe { (xconn.xlib.XSetIMValues)(xim, field, callback, ptr::null_mut::<()>()) }; + xconn.check_errors() +} + +// Set a callback for when an input method matching the current locale modifiers becomes +// available. Note that this has nothing to do with what input methods are open or able to be +// opened, and simply uses the modifiers that are set when the callback is set. +// * This is called per locale modifier, not per input method opened with that locale modifier. +// * Trying to set this for multiple locale modifiers causes problems, i.e. one of the rebuilt input +// contexts would always silently fail to use the input method. +pub(crate) unsafe fn set_instantiate_callback( + xconn: &Arc<XConnection>, + client_data: ffi::XPointer, +) -> Result<(), XError> { + unsafe { + (xconn.xlib.XRegisterIMInstantiateCallback)( + xconn.display, + ptr::null_mut(), + ptr::null_mut(), + ptr::null_mut(), + Some(xim_instantiate_callback), + client_data, + ) + }; + xconn.check_errors() +} + +pub(crate) unsafe fn unset_instantiate_callback( + xconn: &Arc<XConnection>, + client_data: ffi::XPointer, +) -> Result<(), XError> { + unsafe { + (xconn.xlib.XUnregisterIMInstantiateCallback)( + xconn.display, + ptr::null_mut(), + ptr::null_mut(), + ptr::null_mut(), + Some(xim_instantiate_callback), + client_data, + ) + }; + xconn.check_errors() +} + +pub(crate) unsafe fn set_destroy_callback( + xconn: &Arc<XConnection>, + im: ffi::XIM, + inner: &ImeInner, +) -> Result<(), XError> { + unsafe { + xim_set_callback( + xconn, + im, + ffi::XNDestroyCallback_0.as_ptr() as *const _, + &inner.destroy_callback as *const _ as *mut _, + ) + } +} + +#[derive(Debug)] +#[allow(clippy::enum_variant_names)] +enum ReplaceImError { + // Boxed to prevent large error type + MethodOpenFailed(#[allow(dead_code)] Box<PotentialInputMethods>), + ContextCreationFailed(#[allow(dead_code)] ImeContextCreationError), + SetDestroyCallbackFailed(#[allow(dead_code)] XError), +} + +// Attempt to replace current IM (which may or may not be presently valid) with a new one. This +// includes replacing all existing input contexts and free'ing resources as necessary. This only +// modifies existing state if all operations succeed. +unsafe fn replace_im(inner: *mut ImeInner) -> Result<(), ReplaceImError> { + let xconn = unsafe { &(*inner).xconn }; + + let (new_im, is_fallback) = { + let new_im = unsafe { (*inner).potential_input_methods.open_im(xconn, None) }; + let is_fallback = new_im.is_fallback(); + ( + new_im.ok().ok_or_else(|| { + ReplaceImError::MethodOpenFailed(Box::new(unsafe { + (*inner).potential_input_methods.clone() + })) + })?, + is_fallback, + ) + }; + + // It's important to always set a destroy callback, since there's otherwise potential for us + // to try to use or free a resource that's already been destroyed on the server. + { + let result = unsafe { set_destroy_callback(xconn, new_im.im, &*inner) }; + if result.is_err() { + let _ = unsafe { close_im(xconn, new_im.im) }; + } + result + } + .map_err(ReplaceImError::SetDestroyCallbackFailed)?; + + let mut new_contexts = HashMap::new(); + for (window, old_context) in unsafe { (*inner).contexts.iter() } { + let spot = old_context.as_ref().map(|old_context| old_context.ic_spot); + + // Check if the IME was allowed on that context. + let is_allowed = + old_context.as_ref().map(|old_context| old_context.is_allowed()).unwrap_or_default(); + + let new_context = { + let result = unsafe { + ImeContext::new( + xconn, + &new_im, + *window, + spot, + (*inner).event_sender.clone(), + is_allowed, + ) + }; + if result.is_err() { + let _ = unsafe { close_im(xconn, new_im.im) }; + } + result.map_err(ReplaceImError::ContextCreationFailed)? + }; + new_contexts.insert(*window, Some(new_context)); + } + + // If we've made it this far, everything succeeded. + unsafe { + let _ = (*inner).destroy_all_contexts_if_necessary(); + let _ = (*inner).close_im_if_necessary(); + (*inner).im = Some(new_im); + (*inner).contexts = new_contexts; + (*inner).is_destroyed = false; + (*inner).is_fallback = is_fallback; + } + Ok(()) +} + +pub unsafe extern "C" fn xim_instantiate_callback( + _display: *mut ffi::Display, + client_data: ffi::XPointer, + // This field is unsupplied. + _call_data: ffi::XPointer, +) { + let inner: *mut ImeInner = client_data as _; + if !inner.is_null() { + let xconn = unsafe { &(*inner).xconn }; + match unsafe { replace_im(inner) } { + Ok(()) => unsafe { + let _ = unset_instantiate_callback(xconn, client_data); + (*inner).is_fallback = false; + }, + Err(err) => unsafe { + if (*inner).is_destroyed { + // We have no usable input methods! + panic!("Failed to reopen input method: {err:?}"); + } + }, + } + } +} + +// This callback is triggered when the input method is closed on the server end. When this +// happens, XCloseIM/XDestroyIC doesn't need to be called, as the resources have already been +// free'd (attempting to do so causes our connection to freeze). +pub unsafe extern "C" fn xim_destroy_callback( + _xim: ffi::XIM, + client_data: ffi::XPointer, + // This field is unsupplied. + _call_data: ffi::XPointer, +) { + let inner: *mut ImeInner = client_data as _; + if !inner.is_null() { + unsafe { (*inner).is_destroyed = true }; + let xconn = unsafe { &(*inner).xconn }; + if unsafe { !(*inner).is_fallback } { + let _ = unsafe { set_instantiate_callback(xconn, client_data) }; + // Attempt to open fallback input method. + match unsafe { replace_im(inner) } { + Ok(()) => unsafe { (*inner).is_fallback = true }, + Err(err) => { + // We have no usable input methods! + panic!("Failed to open fallback input method: {err:?}"); + }, + } + } + } +} diff --git a/app/vendor/rune/vendor/winit/src/platform_impl/linux/x11/ime/context.rs b/app/vendor/rune/vendor/winit/src/platform_impl/linux/x11/ime/context.rs new file mode 100644 index 0000000..2c6c075 --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/platform_impl/linux/x11/ime/context.rs @@ -0,0 +1,376 @@ +use std::ffi::CStr; +use std::os::raw::c_short; +use std::sync::Arc; +use std::{mem, ptr}; + +use x11_dl::xlib::{XIMCallback, XIMPreeditCaretCallbackStruct, XIMPreeditDrawCallbackStruct}; + +use super::{ffi, util, XConnection, XError}; +use crate::platform_impl::platform::x11::ime::input_method::{InputMethod, Style, XIMStyle}; +use crate::platform_impl::platform::x11::ime::{ImeEvent, ImeEventSender}; + +/// IME creation error. +#[derive(Debug)] +pub enum ImeContextCreationError { + /// Got the error from Xlib. + XError(XError), + + /// Got null pointer from Xlib but without exact reason. + Null, +} + +/// The callback used by XIM preedit functions. +type XIMProcNonnull = unsafe extern "C" fn(ffi::XIM, ffi::XPointer, ffi::XPointer); + +/// Wrapper for creating XIM callbacks. +#[inline] +fn create_xim_callback(client_data: ffi::XPointer, callback: XIMProcNonnull) -> ffi::XIMCallback { + XIMCallback { client_data, callback: Some(callback) } +} + +/// The server started preedit. +extern "C" fn preedit_start_callback( + _xim: ffi::XIM, + client_data: ffi::XPointer, + _call_data: ffi::XPointer, +) -> i32 { + let client_data = unsafe { &mut *(client_data as *mut ImeContextClientData) }; + + client_data.text.clear(); + client_data.cursor_pos = 0; + client_data + .event_sender + .send((client_data.window, ImeEvent::Start)) + .expect("failed to send preedit start event"); + -1 +} + +/// Done callback is used when the preedit should be hidden. +extern "C" fn preedit_done_callback( + _xim: ffi::XIM, + client_data: ffi::XPointer, + _call_data: ffi::XPointer, +) { + let client_data = unsafe { &mut *(client_data as *mut ImeContextClientData) }; + + // Drop text buffer and reset cursor position on done. + client_data.text = Vec::new(); + client_data.cursor_pos = 0; + + client_data + .event_sender + .send((client_data.window, ImeEvent::End)) + .expect("failed to send preedit end event"); +} + +fn calc_byte_position(text: &[char], pos: usize) -> usize { + text.iter().take(pos).fold(0, |byte_pos, text| byte_pos + text.len_utf8()) +} + +/// Preedit text information to be drawn inline by the client. +extern "C" fn preedit_draw_callback( + _xim: ffi::XIM, + client_data: ffi::XPointer, + call_data: ffi::XPointer, +) { + let client_data = unsafe { &mut *(client_data as *mut ImeContextClientData) }; + let call_data = unsafe { &mut *(call_data as *mut XIMPreeditDrawCallbackStruct) }; + client_data.cursor_pos = call_data.caret as usize; + + let chg_range = + call_data.chg_first as usize..(call_data.chg_first + call_data.chg_length) as usize; + if chg_range.start > client_data.text.len() || chg_range.end > client_data.text.len() { + tracing::warn!( + "invalid chg range: buffer length={}, but chg_first={} chg_length={}", + client_data.text.len(), + call_data.chg_first, + call_data.chg_length + ); + return; + } + + // NULL indicate text deletion + let mut new_chars = if call_data.text.is_null() { + Vec::new() + } else { + let xim_text = unsafe { &mut *(call_data.text) }; + if xim_text.encoding_is_wchar > 0 { + return; + } + + let new_text = unsafe { xim_text.string.multi_byte }; + + if new_text.is_null() { + return; + } + + let new_text = unsafe { CStr::from_ptr(new_text) }; + + String::from(new_text.to_str().expect("Invalid UTF-8 String from IME")).chars().collect() + }; + let mut old_text_tail = client_data.text.split_off(chg_range.end); + client_data.text.truncate(chg_range.start); + client_data.text.append(&mut new_chars); + client_data.text.append(&mut old_text_tail); + let cursor_byte_pos = calc_byte_position(&client_data.text, client_data.cursor_pos); + + client_data + .event_sender + .send(( + client_data.window, + ImeEvent::Update(client_data.text.iter().collect(), cursor_byte_pos), + )) + .expect("failed to send preedit update event"); +} + +/// Handling of cursor movements in preedit text. +extern "C" fn preedit_caret_callback( + _xim: ffi::XIM, + client_data: ffi::XPointer, + call_data: ffi::XPointer, +) { + let client_data = unsafe { &mut *(client_data as *mut ImeContextClientData) }; + let call_data = unsafe { &mut *(call_data as *mut XIMPreeditCaretCallbackStruct) }; + + if call_data.direction == ffi::XIMCaretDirection::XIMAbsolutePosition { + client_data.cursor_pos = call_data.position as usize; + let cursor_byte_pos = calc_byte_position(&client_data.text, client_data.cursor_pos); + + client_data + .event_sender + .send(( + client_data.window, + ImeEvent::Update(client_data.text.iter().collect(), cursor_byte_pos), + )) + .expect("failed to send preedit update event"); + } +} + +/// Struct to simplify callback creation and latter passing into Xlib XIM. +struct PreeditCallbacks { + start_callback: ffi::XIMCallback, + done_callback: ffi::XIMCallback, + draw_callback: ffi::XIMCallback, + caret_callback: ffi::XIMCallback, +} + +impl PreeditCallbacks { + pub fn new(client_data: ffi::XPointer) -> PreeditCallbacks { + let start_callback = create_xim_callback(client_data, unsafe { + mem::transmute::<usize, unsafe extern "C" fn(ffi::XIM, ffi::XPointer, ffi::XPointer)>( + preedit_start_callback as *const () as usize, + ) + }); + let done_callback = create_xim_callback(client_data, preedit_done_callback); + let caret_callback = create_xim_callback(client_data, preedit_caret_callback); + let draw_callback = create_xim_callback(client_data, preedit_draw_callback); + + PreeditCallbacks { start_callback, done_callback, caret_callback, draw_callback } + } +} + +struct ImeContextClientData { + window: ffi::Window, + event_sender: ImeEventSender, + text: Vec<char>, + cursor_pos: usize, +} + +// XXX: this struct doesn't destroy its XIC resource when dropped. +// This is intentional, as it doesn't have enough information to know whether or not the context +// still exists on the server. Since `ImeInner` has that awareness, destruction must be handled +// through `ImeInner`. +pub struct ImeContext { + pub(crate) ic: ffi::XIC, + pub(crate) ic_spot: ffi::XPoint, + pub(crate) allowed: bool, + // Since the data is passed shared between X11 XIM callbacks, but couldn't be directly free + // from there we keep the pointer to automatically deallocate it. + _client_data: Box<ImeContextClientData>, +} + +impl ImeContext { + pub(crate) unsafe fn new( + xconn: &Arc<XConnection>, + im: &InputMethod, + window: ffi::Window, + ic_spot: Option<ffi::XPoint>, + event_sender: ImeEventSender, + allowed: bool, + ) -> Result<Self, ImeContextCreationError> { + let client_data = Box::into_raw(Box::new(ImeContextClientData { + window, + event_sender, + text: Vec::new(), + cursor_pos: 0, + })); + + let style = if allowed { im.preedit_style } else { im.none_style }; + + let ic = match style as _ { + Style::Preedit(style) => unsafe { + ImeContext::create_preedit_ic( + xconn, + im.im, + style, + window, + client_data as ffi::XPointer, + ) + }, + Style::Nothing(style) => unsafe { + ImeContext::create_nothing_ic(xconn, im.im, style, window) + }, + Style::None(style) => unsafe { + ImeContext::create_none_ic(xconn, im.im, style, window) + }, + } + .ok_or(ImeContextCreationError::Null)?; + + xconn.check_errors().map_err(ImeContextCreationError::XError)?; + + let mut context = ImeContext { + ic, + ic_spot: ffi::XPoint { x: 0, y: 0 }, + allowed, + _client_data: unsafe { Box::from_raw(client_data) }, + }; + + // Set the spot location, if it's present. + if let Some(ic_spot) = ic_spot { + context.set_spot(xconn, ic_spot.x, ic_spot.y) + } + + Ok(context) + } + + unsafe fn create_none_ic( + xconn: &Arc<XConnection>, + im: ffi::XIM, + style: XIMStyle, + window: ffi::Window, + ) -> Option<ffi::XIC> { + let ic = unsafe { + (xconn.xlib.XCreateIC)( + im, + ffi::XNInputStyle_0.as_ptr() as *const _, + style, + ffi::XNClientWindow_0.as_ptr() as *const _, + window, + ptr::null_mut::<()>(), + ) + }; + + (!ic.is_null()).then_some(ic) + } + + unsafe fn create_preedit_ic( + xconn: &Arc<XConnection>, + im: ffi::XIM, + style: XIMStyle, + window: ffi::Window, + client_data: ffi::XPointer, + ) -> Option<ffi::XIC> { + let preedit_callbacks = PreeditCallbacks::new(client_data); + let preedit_attr = util::memory::XSmartPointer::new(xconn, unsafe { + (xconn.xlib.XVaCreateNestedList)( + 0, + ffi::XNPreeditStartCallback_0.as_ptr() as *const _, + &(preedit_callbacks.start_callback) as *const _, + ffi::XNPreeditDoneCallback_0.as_ptr() as *const _, + &(preedit_callbacks.done_callback) as *const _, + ffi::XNPreeditCaretCallback_0.as_ptr() as *const _, + &(preedit_callbacks.caret_callback) as *const _, + ffi::XNPreeditDrawCallback_0.as_ptr() as *const _, + &(preedit_callbacks.draw_callback) as *const _, + ptr::null_mut::<()>(), + ) + }) + .expect("XVaCreateNestedList returned NULL"); + + let ic = unsafe { + (xconn.xlib.XCreateIC)( + im, + ffi::XNInputStyle_0.as_ptr() as *const _, + style, + ffi::XNClientWindow_0.as_ptr() as *const _, + window, + ffi::XNPreeditAttributes_0.as_ptr() as *const _, + preedit_attr.ptr, + ptr::null_mut::<()>(), + ) + }; + + (!ic.is_null()).then_some(ic) + } + + unsafe fn create_nothing_ic( + xconn: &Arc<XConnection>, + im: ffi::XIM, + style: XIMStyle, + window: ffi::Window, + ) -> Option<ffi::XIC> { + let ic = unsafe { + (xconn.xlib.XCreateIC)( + im, + ffi::XNInputStyle_0.as_ptr() as *const _, + style, + ffi::XNClientWindow_0.as_ptr() as *const _, + window, + ptr::null_mut::<()>(), + ) + }; + + (!ic.is_null()).then_some(ic) + } + + pub(crate) fn focus(&self, xconn: &Arc<XConnection>) -> Result<(), XError> { + unsafe { + (xconn.xlib.XSetICFocus)(self.ic); + } + xconn.check_errors() + } + + pub(crate) fn unfocus(&self, xconn: &Arc<XConnection>) -> Result<(), XError> { + unsafe { + (xconn.xlib.XUnsetICFocus)(self.ic); + } + xconn.check_errors() + } + + pub fn is_allowed(&self) -> bool { + self.allowed + } + + // Set the spot for preedit text. Setting spot isn't working with libX11 when preedit callbacks + // are being used. Certain IMEs do show selection window, but it's placed in bottom left of the + // window and couldn't be changed. + // + // For me see: https://bugs.freedesktop.org/show_bug.cgi?id=1580. + pub(crate) fn set_spot(&mut self, xconn: &Arc<XConnection>, x: c_short, y: c_short) { + if !self.is_allowed() || self.ic_spot.x == x && self.ic_spot.y == y { + return; + } + + self.ic_spot = ffi::XPoint { x, y }; + + unsafe { + let preedit_attr = util::memory::XSmartPointer::new( + xconn, + (xconn.xlib.XVaCreateNestedList)( + 0, + ffi::XNSpotLocation_0.as_ptr(), + &self.ic_spot, + ptr::null_mut::<()>(), + ), + ) + .expect("XVaCreateNestedList returned NULL"); + + (xconn.xlib.XSetICValues)( + self.ic, + ffi::XNPreeditAttributes_0.as_ptr() as *const _, + preedit_attr.ptr, + ptr::null_mut::<()>(), + ); + } + } +} diff --git a/app/vendor/rune/vendor/winit/src/platform_impl/linux/x11/ime/inner.rs b/app/vendor/rune/vendor/winit/src/platform_impl/linux/x11/ime/inner.rs new file mode 100644 index 0000000..da1ccf4 --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/platform_impl/linux/x11/ime/inner.rs @@ -0,0 +1,74 @@ +use std::collections::HashMap; +use std::mem; +use std::sync::Arc; + +use super::{ffi, XConnection, XError}; + +use super::context::ImeContext; +use super::input_method::{InputMethod, PotentialInputMethods}; +use crate::platform_impl::platform::x11::ime::ImeEventSender; + +pub(crate) unsafe fn close_im(xconn: &Arc<XConnection>, im: ffi::XIM) -> Result<(), XError> { + unsafe { (xconn.xlib.XCloseIM)(im) }; + xconn.check_errors() +} + +pub(crate) unsafe fn destroy_ic(xconn: &Arc<XConnection>, ic: ffi::XIC) -> Result<(), XError> { + unsafe { (xconn.xlib.XDestroyIC)(ic) }; + xconn.check_errors() +} + +pub(crate) struct ImeInner { + pub xconn: Arc<XConnection>, + pub im: Option<InputMethod>, + pub potential_input_methods: PotentialInputMethods, + pub contexts: HashMap<ffi::Window, Option<ImeContext>>, + // WARNING: this is initially zeroed! + pub destroy_callback: ffi::XIMCallback, + pub event_sender: ImeEventSender, + // Indicates whether or not the input method was destroyed on the server end + // (i.e. if ibus/fcitx/etc. was terminated/restarted) + pub is_destroyed: bool, + pub is_fallback: bool, +} + +impl ImeInner { + pub(crate) fn new( + xconn: Arc<XConnection>, + potential_input_methods: PotentialInputMethods, + event_sender: ImeEventSender, + ) -> Self { + ImeInner { + xconn, + im: None, + potential_input_methods, + contexts: HashMap::new(), + destroy_callback: unsafe { mem::zeroed() }, + event_sender, + is_destroyed: false, + is_fallback: false, + } + } + + pub unsafe fn close_im_if_necessary(&self) -> Result<bool, XError> { + match self.im.as_ref() { + Some(im) if !self.is_destroyed => unsafe { close_im(&self.xconn, im.im).map(|_| true) }, + _ => Ok(false), + } + } + + pub unsafe fn destroy_ic_if_necessary(&self, ic: ffi::XIC) -> Result<bool, XError> { + if !self.is_destroyed { + unsafe { destroy_ic(&self.xconn, ic) }.map(|_| true) + } else { + Ok(false) + } + } + + pub unsafe fn destroy_all_contexts_if_necessary(&self) -> Result<bool, XError> { + for context in self.contexts.values().flatten() { + unsafe { self.destroy_ic_if_necessary(context.ic)? }; + } + Ok(!self.is_destroyed) + } +} diff --git a/app/vendor/rune/vendor/winit/src/platform_impl/linux/x11/ime/input_method.rs b/app/vendor/rune/vendor/winit/src/platform_impl/linux/x11/ime/input_method.rs new file mode 100644 index 0000000..e1f2fbd --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/platform_impl/linux/x11/ime/input_method.rs @@ -0,0 +1,345 @@ +use std::ffi::{CStr, CString, IntoStringError}; +use std::os::raw::{c_char, c_ulong, c_ushort}; +use std::sync::{Arc, Mutex}; +use std::{env, fmt, ptr}; + +use super::super::atoms::*; +use super::{ffi, util, XConnection, XError}; +use x11rb::protocol::xproto; + +static GLOBAL_LOCK: Mutex<()> = Mutex::new(()); + +unsafe fn open_im(xconn: &Arc<XConnection>, locale_modifiers: &CStr) -> Option<ffi::XIM> { + let _lock = GLOBAL_LOCK.lock(); + + // XSetLocaleModifiers returns... + // * The current locale modifiers if it's given a NULL pointer. + // * The new locale modifiers if we succeeded in setting them. + // * NULL if the locale modifiers string is malformed or if the current locale is not supported + // by Xlib. + unsafe { (xconn.xlib.XSetLocaleModifiers)(locale_modifiers.as_ptr()) }; + + let im = unsafe { + (xconn.xlib.XOpenIM)(xconn.display, ptr::null_mut(), ptr::null_mut(), ptr::null_mut()) + }; + + if im.is_null() { + None + } else { + Some(im) + } +} + +#[derive(Debug)] +pub struct InputMethod { + pub im: ffi::XIM, + pub preedit_style: Style, + pub none_style: Style, + _name: String, +} + +impl InputMethod { + fn new(xconn: &Arc<XConnection>, im: ffi::XIM, name: String) -> Option<Self> { + let mut styles: *mut XIMStyles = std::ptr::null_mut(); + + // Query the styles supported by the XIM. + unsafe { + if !(xconn.xlib.XGetIMValues)( + im, + ffi::XNQueryInputStyle_0.as_ptr() as *const _, + (&mut styles) as *mut _, + std::ptr::null_mut::<()>(), + ) + .is_null() + { + return None; + } + } + + let mut preedit_style = None; + let mut none_style = None; + + unsafe { + std::slice::from_raw_parts((*styles).supported_styles, (*styles).count_styles as _) + .iter() + .for_each(|style| match *style { + XIM_PREEDIT_STYLE => { + preedit_style = Some(Style::Preedit(*style)); + }, + XIM_NOTHING_STYLE if preedit_style.is_none() => { + preedit_style = Some(Style::Nothing(*style)) + }, + XIM_NONE_STYLE => none_style = Some(Style::None(*style)), + _ => (), + }); + + (xconn.xlib.XFree)(styles.cast()); + }; + + if preedit_style.is_none() && none_style.is_none() { + return None; + } + + let preedit_style = preedit_style.unwrap_or_else(|| none_style.unwrap()); + let none_style = none_style.unwrap_or(preedit_style); + + Some(InputMethod { im, _name: name, preedit_style, none_style }) + } +} + +const XIM_PREEDIT_STYLE: XIMStyle = (ffi::XIMPreeditCallbacks | ffi::XIMStatusNothing) as XIMStyle; +const XIM_NOTHING_STYLE: XIMStyle = (ffi::XIMPreeditNothing | ffi::XIMStatusNothing) as XIMStyle; +const XIM_NONE_STYLE: XIMStyle = (ffi::XIMPreeditNone | ffi::XIMStatusNone) as XIMStyle; + +/// Style of the IME context. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Style { + /// Preedit callbacks. + Preedit(XIMStyle), + + /// Nothing. + Nothing(XIMStyle), + + /// No IME. + None(XIMStyle), +} + +impl Default for Style { + fn default() -> Self { + Style::None(XIM_NONE_STYLE) + } +} + +#[repr(C)] +#[derive(Debug)] +struct XIMStyles { + count_styles: c_ushort, + supported_styles: *const XIMStyle, +} + +pub(crate) type XIMStyle = c_ulong; + +#[derive(Debug)] +pub enum InputMethodResult { + /// Input method used locale modifier from `XMODIFIERS` environment variable. + XModifiers(InputMethod), + /// Input method used internal fallback locale modifier. + Fallback(InputMethod), + /// Input method could not be opened using any locale modifier tried. + Failure, +} + +impl InputMethodResult { + pub fn is_fallback(&self) -> bool { + matches!(self, InputMethodResult::Fallback(_)) + } + + pub fn ok(self) -> Option<InputMethod> { + use self::InputMethodResult::*; + match self { + XModifiers(im) | Fallback(im) => Some(im), + Failure => None, + } + } +} + +#[derive(Debug, Clone)] +enum GetXimServersError { + XError(#[allow(dead_code)] XError), + GetPropertyError(#[allow(dead_code)] util::GetPropertyError), + InvalidUtf8(#[allow(dead_code)] IntoStringError), +} + +impl From<util::GetPropertyError> for GetXimServersError { + fn from(error: util::GetPropertyError) -> Self { + GetXimServersError::GetPropertyError(error) + } +} + +// The root window has a property named XIM_SERVERS, which contains a list of atoms representing +// the available XIM servers. For instance, if you're using ibus, it would contain an atom named +// "@server=ibus". It's possible for this property to contain multiple atoms, though presumably +// rare. Note that we replace "@server=" with "@im=" in order to match the format of locale +// modifiers, since we don't want a user who's looking at logs to ask "am I supposed to set +// XMODIFIERS to `@server=ibus`?!?" +unsafe fn get_xim_servers(xconn: &Arc<XConnection>) -> Result<Vec<String>, GetXimServersError> { + let atoms = xconn.atoms(); + let servers_atom = atoms[XIM_SERVERS]; + + let root = unsafe { (xconn.xlib.XDefaultRootWindow)(xconn.display) }; + + let mut atoms: Vec<ffi::Atom> = xconn + .get_property::<xproto::Atom>( + root as xproto::Window, + servers_atom, + xproto::Atom::from(xproto::AtomEnum::ATOM), + ) + .map_err(GetXimServersError::GetPropertyError)? + .into_iter() + .map(|atom| atom as _) + .collect::<Vec<_>>(); + + let mut names: Vec<*const c_char> = Vec::with_capacity(atoms.len()); + unsafe { + (xconn.xlib.XGetAtomNames)( + xconn.display, + atoms.as_mut_ptr(), + atoms.len() as _, + names.as_mut_ptr() as _, + ) + }; + unsafe { names.set_len(atoms.len()) }; + + let mut formatted_names = Vec::with_capacity(names.len()); + for name in names { + let string = unsafe { CStr::from_ptr(name) } + .to_owned() + .into_string() + .map_err(GetXimServersError::InvalidUtf8)?; + unsafe { (xconn.xlib.XFree)(name as _) }; + formatted_names.push(string.replace("@server=", "@im=")); + } + xconn.check_errors().map_err(GetXimServersError::XError)?; + Ok(formatted_names) +} + +#[derive(Clone)] +struct InputMethodName { + c_string: CString, + string: String, +} + +impl InputMethodName { + pub fn from_string(string: String) -> Self { + let c_string = CString::new(string.clone()) + .expect("String used to construct CString contained null byte"); + InputMethodName { c_string, string } + } + + pub fn from_str(string: &str) -> Self { + let c_string = + CString::new(string).expect("String used to construct CString contained null byte"); + InputMethodName { c_string, string: string.to_owned() } + } +} + +impl fmt::Debug for InputMethodName { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + self.string.fmt(f) + } +} + +#[derive(Debug, Clone)] +struct PotentialInputMethod { + name: InputMethodName, + successful: Option<bool>, +} + +impl PotentialInputMethod { + pub fn from_string(string: String) -> Self { + PotentialInputMethod { name: InputMethodName::from_string(string), successful: None } + } + + pub fn from_str(string: &str) -> Self { + PotentialInputMethod { name: InputMethodName::from_str(string), successful: None } + } + + pub fn reset(&mut self) { + self.successful = None; + } + + pub fn open_im(&mut self, xconn: &Arc<XConnection>) -> Option<InputMethod> { + let im = unsafe { open_im(xconn, &self.name.c_string) }; + self.successful = Some(im.is_some()); + im.and_then(|im| InputMethod::new(xconn, im, self.name.string.clone())) + } +} + +// By logging this struct, you get a sequential listing of every locale modifier tried, where it +// came from, and if it succeeded. +#[derive(Debug, Clone)] +pub(crate) struct PotentialInputMethods { + // On correctly configured systems, the XMODIFIERS environment variable tells us everything we + // need to know. + xmodifiers: Option<PotentialInputMethod>, + // We have some standard options at our disposal that should ostensibly always work. For users + // who only need compose sequences, this ensures that the program launches without a hitch + // For users who need more sophisticated IME features, this is more or less a silent failure. + // Logging features should be added in the future to allow both audiences to be effectively + // served. + fallbacks: [PotentialInputMethod; 2], + // For diagnostic purposes, we include the list of XIM servers that the server reports as + // being available. + _xim_servers: Result<Vec<String>, GetXimServersError>, +} + +impl PotentialInputMethods { + pub fn new(xconn: &Arc<XConnection>) -> Self { + let xmodifiers = env::var("XMODIFIERS").ok().map(PotentialInputMethod::from_string); + PotentialInputMethods { + // Since passing "" to XSetLocaleModifiers results in it defaulting to the value of + // XMODIFIERS, it's worth noting what happens if XMODIFIERS is also "". If simply + // running the program with `XMODIFIERS="" cargo run`, then assuming XMODIFIERS is + // defined in the profile (or parent environment) then that parent XMODIFIERS is used. + // If that XMODIFIERS value is also "" (i.e. if you ran `export XMODIFIERS=""`), then + // XSetLocaleModifiers uses the default local input method. Note that defining + // XMODIFIERS as "" is different from XMODIFIERS not being defined at all, since in + // that case, we get `None` and end up skipping ahead to the next method. + xmodifiers, + fallbacks: [ + // This is a standard input method that supports compose sequences, which should + // always be available. `@im=none` appears to mean the same thing. + PotentialInputMethod::from_str("@im=local"), + // This explicitly specifies to use the implementation-dependent default, though + // that seems to be equivalent to just using the local input method. + PotentialInputMethod::from_str("@im="), + ], + // The XIM_SERVERS property can have surprising values. For instance, when I exited + // ibus to run fcitx, it retained the value denoting ibus. Even more surprising is + // that the fcitx input method could only be successfully opened using "@im=ibus". + // Presumably due to this quirk, it's actually possible to alternate between ibus and + // fcitx in a running application. + _xim_servers: unsafe { get_xim_servers(xconn) }, + } + } + + // This resets the `successful` field of every potential input method, ensuring we have + // accurate information when this struct is re-used by the destruction/instantiation callbacks. + fn reset(&mut self) { + if let Some(ref mut input_method) = self.xmodifiers { + input_method.reset(); + } + + for input_method in &mut self.fallbacks { + input_method.reset(); + } + } + + pub fn open_im( + &mut self, + xconn: &Arc<XConnection>, + callback: Option<&dyn Fn()>, + ) -> InputMethodResult { + use self::InputMethodResult::*; + + self.reset(); + + if let Some(ref mut input_method) = self.xmodifiers { + let im = input_method.open_im(xconn); + if let Some(im) = im { + return XModifiers(im); + } else if let Some(ref callback) = callback { + callback(); + } + } + + for input_method in &mut self.fallbacks { + let im = input_method.open_im(xconn); + if let Some(im) = im { + return Fallback(im); + } + } + + Failure + } +} diff --git a/app/vendor/rune/vendor/winit/src/platform_impl/linux/x11/ime/mod.rs b/app/vendor/rune/vendor/winit/src/platform_impl/linux/x11/ime/mod.rs new file mode 100644 index 0000000..0a419c8 --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/platform_impl/linux/x11/ime/mod.rs @@ -0,0 +1,233 @@ +// Important: all XIM calls need to happen from the same thread! + +mod callbacks; +mod context; +mod inner; +mod input_method; + +use std::sync::mpsc::{Receiver, Sender}; +use std::sync::Arc; + +#[cfg(feature = "serde")] +use serde::{Deserialize, Serialize}; + +use self::callbacks::*; +use self::context::ImeContext; +pub use self::context::ImeContextCreationError; +use self::inner::{close_im, ImeInner}; +use self::input_method::PotentialInputMethods; +use super::{ffi, util, XConnection, XError}; + +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] +pub enum ImeEvent { + Enabled, + Start, + Update(String, usize), + End, + Disabled, +} + +pub type ImeReceiver = Receiver<ImeRequest>; +pub type ImeSender = Sender<ImeRequest>; +pub type ImeEventReceiver = Receiver<(ffi::Window, ImeEvent)>; +pub type ImeEventSender = Sender<(ffi::Window, ImeEvent)>; + +/// Request to control XIM handler from the window. +pub enum ImeRequest { + /// Set IME spot position for given `window_id`. + Position(ffi::Window, i16, i16), + + /// Allow IME input for the given `window_id`. + Allow(ffi::Window, bool), +} + +#[derive(Debug)] +pub(crate) enum ImeCreationError { + // Boxed to prevent large error type + OpenFailure(Box<PotentialInputMethods>), + SetDestroyCallbackFailed(#[allow(dead_code)] XError), +} + +pub(crate) struct Ime { + xconn: Arc<XConnection>, + // The actual meat of this struct is boxed away, since it needs to have a fixed location in + // memory so we can pass a pointer to it around. + inner: Box<ImeInner>, +} + +impl Ime { + pub fn new( + xconn: Arc<XConnection>, + event_sender: ImeEventSender, + ) -> Result<Self, ImeCreationError> { + let potential_input_methods = PotentialInputMethods::new(&xconn); + + let (mut inner, client_data) = { + let mut inner = Box::new(ImeInner::new(xconn, potential_input_methods, event_sender)); + let inner_ptr = Box::into_raw(inner); + let client_data = inner_ptr as _; + let destroy_callback = + ffi::XIMCallback { client_data, callback: Some(xim_destroy_callback) }; + inner = unsafe { Box::from_raw(inner_ptr) }; + inner.destroy_callback = destroy_callback; + (inner, client_data) + }; + + let xconn = Arc::clone(&inner.xconn); + + let input_method = inner.potential_input_methods.open_im( + &xconn, + Some(&|| { + let _ = unsafe { set_instantiate_callback(&xconn, client_data) }; + }), + ); + + let is_fallback = input_method.is_fallback(); + if let Some(input_method) = input_method.ok() { + inner.is_fallback = is_fallback; + unsafe { + let result = set_destroy_callback(&xconn, input_method.im, &inner) + .map_err(ImeCreationError::SetDestroyCallbackFailed); + if result.is_err() { + let _ = close_im(&xconn, input_method.im); + } + result?; + } + inner.im = Some(input_method); + Ok(Ime { xconn, inner }) + } else { + Err(ImeCreationError::OpenFailure(Box::new(inner.potential_input_methods))) + } + } + + pub fn is_destroyed(&self) -> bool { + self.inner.is_destroyed + } + + // This pattern is used for various methods here: + // Ok(_) indicates that nothing went wrong internally + // Ok(true) indicates that the action was actually performed + // Ok(false) indicates that the action is not presently applicable + pub fn create_context( + &mut self, + window: ffi::Window, + with_ime: bool, + ) -> Result<bool, ImeContextCreationError> { + let context = if self.is_destroyed() { + // Create empty entry in map, so that when IME is rebuilt, this window has a context. + None + } else { + let im = self.inner.im.as_ref().unwrap(); + + let context = unsafe { + ImeContext::new( + &self.inner.xconn, + im, + window, + None, + self.inner.event_sender.clone(), + with_ime, + )? + }; + + let event = if context.is_allowed() { ImeEvent::Enabled } else { ImeEvent::Disabled }; + self.inner.event_sender.send((window, event)).expect("Failed to send enabled event"); + + Some(context) + }; + + self.inner.contexts.insert(window, context); + Ok(!self.is_destroyed()) + } + + pub fn get_context(&self, window: ffi::Window) -> Option<ffi::XIC> { + if self.is_destroyed() { + return None; + } + if let Some(Some(context)) = self.inner.contexts.get(&window) { + Some(context.ic) + } else { + None + } + } + + pub fn remove_context(&mut self, window: ffi::Window) -> Result<bool, XError> { + if let Some(Some(context)) = self.inner.contexts.remove(&window) { + unsafe { + self.inner.destroy_ic_if_necessary(context.ic)?; + } + Ok(true) + } else { + Ok(false) + } + } + + pub fn focus(&mut self, window: ffi::Window) -> Result<bool, XError> { + if self.is_destroyed() { + return Ok(false); + } + if let Some(&mut Some(ref mut context)) = self.inner.contexts.get_mut(&window) { + context.focus(&self.xconn).map(|_| true) + } else { + Ok(false) + } + } + + pub fn unfocus(&mut self, window: ffi::Window) -> Result<bool, XError> { + if self.is_destroyed() { + return Ok(false); + } + if let Some(&mut Some(ref mut context)) = self.inner.contexts.get_mut(&window) { + context.unfocus(&self.xconn).map(|_| true) + } else { + Ok(false) + } + } + + pub fn send_xim_spot(&mut self, window: ffi::Window, x: i16, y: i16) { + if self.is_destroyed() { + return; + } + if let Some(&mut Some(ref mut context)) = self.inner.contexts.get_mut(&window) { + context.set_spot(&self.xconn, x as _, y as _); + } + } + + pub fn set_ime_allowed(&mut self, window: ffi::Window, allowed: bool) { + if self.is_destroyed() { + return; + } + + if let Some(&mut Some(ref mut context)) = self.inner.contexts.get_mut(&window) { + if allowed == context.is_allowed() { + return; + } + } + + // Remove context for that window. + let _ = self.remove_context(window); + + // Create new context supporting IME input. + let _ = self.create_context(window, allowed); + } + + pub fn is_ime_allowed(&self, window: ffi::Window) -> bool { + if self.is_destroyed() { + false + } else if let Some(Some(context)) = self.inner.contexts.get(&window) { + context.is_allowed() + } else { + false + } + } +} + +impl Drop for Ime { + fn drop(&mut self) { + unsafe { + let _ = self.inner.destroy_all_contexts_if_necessary(); + let _ = self.inner.close_im_if_necessary(); + } + } +} diff --git a/app/vendor/rune/vendor/winit/src/platform_impl/linux/x11/mod.rs b/app/vendor/rune/vendor/winit/src/platform_impl/linux/x11/mod.rs new file mode 100644 index 0000000..f29b314 --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/platform_impl/linux/x11/mod.rs @@ -0,0 +1,1064 @@ +use std::cell::{Cell, RefCell}; +use std::collections::{HashMap, HashSet, VecDeque}; +use std::ffi::CStr; +use std::marker::PhantomData; +use std::mem::MaybeUninit; +use std::ops::Deref; +use std::os::raw::*; +use std::os::unix::io::{AsFd, AsRawFd, BorrowedFd, RawFd}; +use std::sync::mpsc::{self, Receiver, Sender, TryRecvError}; +use std::sync::{Arc, Weak}; +use std::time::{Duration, Instant}; +use std::{fmt, ptr, slice, str}; + +use calloop::generic::Generic; +use calloop::ping::Ping; +use calloop::{EventLoop as Loop, Readiness}; +use libc::{setlocale, LC_CTYPE}; +use tracing::warn; + +use x11rb::connection::RequestConnection; +use x11rb::errors::{ConnectError, ConnectionError, IdsExhausted, ReplyError}; +use x11rb::protocol::xinput::{self, ConnectionExt as _}; +use x11rb::protocol::xkb; +use x11rb::protocol::xproto::{self, ConnectionExt as _}; +use x11rb::x11_utils::X11Error as LogicalError; +use x11rb::xcb_ffi::ReplyOrIdError; + +use crate::error::{EventLoopError, OsError as RootOsError}; +use crate::event::{Event, StartCause, WindowEvent}; +use crate::event_loop::{ActiveEventLoop as RootAEL, ControlFlow, DeviceEvents, EventLoopClosed}; +use crate::platform::pump_events::PumpStatus; +use crate::platform_impl::common::xkb::Context; +use crate::platform_impl::platform::{min_timeout, WindowId}; +use crate::platform_impl::{ + ActiveEventLoop as PlatformActiveEventLoop, OsError, PlatformCustomCursor, +}; +use crate::window::{CustomCursor as RootCustomCursor, CustomCursorSource, WindowAttributes}; + +mod activation; +mod atoms; +mod dnd; +mod event_processor; +pub mod ffi; +mod ime; +mod monitor; +mod util; +mod window; +mod xdisplay; +mod xsettings; + +pub use util::CustomCursor; + +use atoms::*; +use dnd::{Dnd, DndState}; +use event_processor::{EventProcessor, MAX_MOD_REPLAY_LEN}; +use ime::{Ime, ImeCreationError, ImeReceiver, ImeRequest, ImeSender}; +pub(crate) use monitor::{MonitorHandle, VideoModeHandle}; +use window::UnownedWindow; +pub(crate) use xdisplay::{XConnection, XError, XNotSupported}; + +// Xinput constants not defined in x11rb +const ALL_DEVICES: u16 = 0; +const ALL_MASTER_DEVICES: u16 = 1; +const ICONIC_STATE: u32 = 3; + +/// The underlying x11rb connection that we are using. +type X11rbConnection = x11rb::xcb_ffi::XCBConnection; + +type X11Source = Generic<BorrowedFd<'static>>; + +struct WakeSender<T> { + sender: Sender<T>, + waker: Ping, +} + +impl<T> Clone for WakeSender<T> { + fn clone(&self) -> Self { + Self { sender: self.sender.clone(), waker: self.waker.clone() } + } +} + +impl<T> WakeSender<T> { + pub fn send(&self, t: T) -> Result<(), EventLoopClosed<T>> { + let res = self.sender.send(t).map_err(|e| EventLoopClosed(e.0)); + if res.is_ok() { + self.waker.ping(); + } + res + } +} + +struct PeekableReceiver<T> { + recv: Receiver<T>, + first: Option<T>, +} + +impl<T> PeekableReceiver<T> { + pub fn from_recv(recv: Receiver<T>) -> Self { + Self { recv, first: None } + } + + pub fn has_incoming(&mut self) -> bool { + if self.first.is_some() { + return true; + } + + match self.recv.try_recv() { + Ok(v) => { + self.first = Some(v); + true + }, + Err(TryRecvError::Empty) => false, + Err(TryRecvError::Disconnected) => { + warn!("Channel was disconnected when checking incoming"); + false + }, + } + } + + pub fn try_recv(&mut self) -> Result<T, TryRecvError> { + if let Some(first) = self.first.take() { + return Ok(first); + } + self.recv.try_recv() + } +} + +pub struct ActiveEventLoop { + xconn: Arc<XConnection>, + wm_delete_window: xproto::Atom, + net_wm_ping: xproto::Atom, + ime_sender: ImeSender, + control_flow: Cell<ControlFlow>, + exit: Cell<Option<i32>>, + root: xproto::Window, + ime: Option<RefCell<Ime>>, + windows: RefCell<HashMap<WindowId, Weak<UnownedWindow>>>, + redraw_sender: WakeSender<WindowId>, + activation_sender: WakeSender<ActivationToken>, + device_events: Cell<DeviceEvents>, +} + +pub struct EventLoop<T: 'static> { + loop_running: bool, + event_loop: Loop<'static, EventLoopState>, + waker: calloop::ping::Ping, + event_processor: EventProcessor, + redraw_receiver: PeekableReceiver<WindowId>, + user_receiver: PeekableReceiver<T>, + activation_receiver: PeekableReceiver<ActivationToken>, + user_sender: Sender<T>, + + /// The current state of the event loop. + state: EventLoopState, +} + +type ActivationToken = (WindowId, crate::event_loop::AsyncRequestSerial); + +struct EventLoopState { + /// The latest readiness state for the x11 file descriptor + x11_readiness: Readiness, +} + +pub struct EventLoopProxy<T: 'static> { + user_sender: WakeSender<T>, +} + +impl<T: 'static> Clone for EventLoopProxy<T> { + fn clone(&self) -> Self { + EventLoopProxy { user_sender: self.user_sender.clone() } + } +} + +impl<T: 'static> EventLoop<T> { + pub(crate) fn new(xconn: Arc<XConnection>) -> EventLoop<T> { + let root = xconn.default_root().root; + let atoms = xconn.atoms(); + + let wm_delete_window = atoms[WM_DELETE_WINDOW]; + let net_wm_ping = atoms[_NET_WM_PING]; + + let dnd = Dnd::new(Arc::clone(&xconn)) + .expect("Failed to call XInternAtoms when initializing drag and drop"); + + let (ime_sender, ime_receiver) = mpsc::channel(); + let (ime_event_sender, ime_event_receiver) = mpsc::channel(); + // Input methods will open successfully without setting the locale, but it won't be + // possible to actually commit pre-edit sequences. + unsafe { + // Remember default locale to restore it if target locale is unsupported + // by Xlib + let default_locale = setlocale(LC_CTYPE, ptr::null()); + setlocale(LC_CTYPE, b"\0".as_ptr() as *const _); + + // Check if set locale is supported by Xlib. + // If not, calls to some Xlib functions like `XSetLocaleModifiers` + // will fail. + let locale_supported = (xconn.xlib.XSupportsLocale)() == 1; + if !locale_supported { + let unsupported_locale = setlocale(LC_CTYPE, ptr::null()); + warn!( + "Unsupported locale \"{}\". Restoring default locale \"{}\".", + CStr::from_ptr(unsupported_locale).to_string_lossy(), + CStr::from_ptr(default_locale).to_string_lossy() + ); + // Restore default locale + setlocale(LC_CTYPE, default_locale); + } + } + + let ime = Ime::new(Arc::clone(&xconn), ime_event_sender); + if let Err(ImeCreationError::OpenFailure(state)) = ime.as_ref() { + warn!("Failed to open input method: {state:#?}"); + } else if let Err(err) = ime.as_ref() { + warn!("Failed to set input method destruction callback: {err:?}"); + } + + let ime = ime.ok().map(RefCell::new); + + let randr_event_offset = + xconn.select_xrandr_input(root).expect("Failed to query XRandR extension"); + + let xi2ext = xconn + .xcb_connection() + .extension_information(xinput::X11_EXTENSION_NAME) + .expect("Failed to query XInput extension") + .expect("X server missing XInput extension"); + let xkbext = xconn + .xcb_connection() + .extension_information(xkb::X11_EXTENSION_NAME) + .expect("Failed to query XKB extension") + .expect("X server missing XKB extension"); + + // Check for XInput2 support. + xconn + .xcb_connection() + .xinput_xi_query_version(2, 3) + .expect("Failed to send XInput2 query version request") + .reply() + .expect("Error while checking for XInput2 query version reply"); + + xconn.update_cached_wm_info(root); + + // Create an event loop. + let event_loop = + Loop::<EventLoopState>::try_new().expect("Failed to initialize the event loop"); + let handle = event_loop.handle(); + + // Create the X11 event dispatcher. + let source = X11Source::new( + // SAFETY: xcb owns the FD and outlives the source. + unsafe { BorrowedFd::borrow_raw(xconn.xcb_connection().as_raw_fd()) }, + calloop::Interest::READ, + calloop::Mode::Level, + ); + handle + .insert_source(source, |readiness, _, state| { + state.x11_readiness = readiness; + Ok(calloop::PostAction::Continue) + }) + .expect("Failed to register the X11 event dispatcher"); + + let (waker, waker_source) = + calloop::ping::make_ping().expect("Failed to create event loop waker"); + event_loop + .handle() + .insert_source(waker_source, move |_, _, _| { + // No extra handling is required, we just need to wake-up. + }) + .expect("Failed to register the event loop waker source"); + + // Create a channel for handling redraw requests. + let (redraw_sender, redraw_channel) = mpsc::channel(); + + // Create a channel for sending activation tokens. + let (activation_token_sender, activation_token_channel) = mpsc::channel(); + + // Create a channel for sending user events. + let (user_sender, user_channel) = mpsc::channel(); + + let xkb_context = + Context::from_x11_xkb(xconn.xcb_connection().get_raw_xcb_connection()).unwrap(); + + let mut xmodmap = util::ModifierKeymap::new(); + xmodmap.reload_from_x_connection(&xconn); + + let window_target = ActiveEventLoop { + ime, + root, + control_flow: Cell::new(ControlFlow::default()), + exit: Cell::new(None), + windows: Default::default(), + ime_sender, + xconn, + wm_delete_window, + net_wm_ping, + redraw_sender: WakeSender { + sender: redraw_sender, // not used again so no clone + waker: waker.clone(), + }, + activation_sender: WakeSender { + sender: activation_token_sender, // not used again so no clone + waker: waker.clone(), + }, + device_events: Default::default(), + }; + + // Set initial device event filter. + window_target.update_listen_device_events(true); + + let root_window_target = + RootAEL { p: PlatformActiveEventLoop::X(window_target), _marker: PhantomData }; + + let event_processor = EventProcessor { + target: root_window_target, + dnd, + devices: Default::default(), + randr_event_offset, + ime_receiver, + ime_event_receiver, + xi2ext, + xfiltered_modifiers: VecDeque::with_capacity(MAX_MOD_REPLAY_LEN), + xmodmap, + xkbext, + xkb_context, + num_touch: 0, + held_key_press: None, + first_touch: None, + active_window: None, + modifiers: Default::default(), + is_composing: false, + }; + + // Register for device hotplug events + // (The request buffer is flushed during `init_device`) + let xconn = &EventProcessor::window_target(&event_processor.target).xconn; + + xconn + .select_xinput_events( + root, + ALL_DEVICES, + x11rb::protocol::xinput::XIEventMask::HIERARCHY, + ) + .expect_then_ignore_error("Failed to register for XInput2 device hotplug events"); + + xconn + .select_xkb_events( + 0x100, // Use the "core keyboard device" + xkb::EventType::NEW_KEYBOARD_NOTIFY + | xkb::EventType::MAP_NOTIFY + | xkb::EventType::STATE_NOTIFY, + ) + .unwrap(); + + event_processor.init_device(ALL_DEVICES); + + EventLoop { + loop_running: false, + event_loop, + waker, + event_processor, + redraw_receiver: PeekableReceiver::from_recv(redraw_channel), + activation_receiver: PeekableReceiver::from_recv(activation_token_channel), + user_receiver: PeekableReceiver::from_recv(user_channel), + user_sender, + state: EventLoopState { x11_readiness: Readiness::EMPTY }, + } + } + + pub fn create_proxy(&self) -> EventLoopProxy<T> { + EventLoopProxy { + user_sender: WakeSender { sender: self.user_sender.clone(), waker: self.waker.clone() }, + } + } + + pub(crate) fn window_target(&self) -> &RootAEL { + &self.event_processor.target + } + + pub fn run_on_demand<F>(&mut self, mut event_handler: F) -> Result<(), EventLoopError> + where + F: FnMut(Event<T>, &RootAEL), + { + let exit = loop { + match self.pump_events(None, &mut event_handler) { + PumpStatus::Exit(0) => { + break Ok(()); + }, + PumpStatus::Exit(code) => { + break Err(EventLoopError::ExitFailure(code)); + }, + _ => { + continue; + }, + } + }; + + // Applications aren't allowed to carry windows between separate + // `run_on_demand` calls but if they have only just dropped their + // windows we need to make sure those last requests are sent to the + // X Server. + let wt = EventProcessor::window_target(&self.event_processor.target); + wt.x_connection().sync_with_server().map_err(|x_err| { + EventLoopError::Os(os_error!(OsError::XError(Arc::new(X11Error::Xlib(x_err))))) + })?; + + exit + } + + pub fn pump_events<F>(&mut self, timeout: Option<Duration>, mut callback: F) -> PumpStatus + where + F: FnMut(Event<T>, &RootAEL), + { + if !self.loop_running { + self.loop_running = true; + + // run the initial loop iteration + self.single_iteration(&mut callback, StartCause::Init); + } + + // Consider the possibility that the `StartCause::Init` iteration could + // request to Exit. + if !self.exiting() { + self.poll_events_with_timeout(timeout, &mut callback); + } + if let Some(code) = self.exit_code() { + self.loop_running = false; + + callback(Event::LoopExiting, self.window_target()); + + PumpStatus::Exit(code) + } else { + PumpStatus::Continue + } + } + + fn has_pending(&mut self) -> bool { + self.event_processor.poll() + || self.user_receiver.has_incoming() + || self.redraw_receiver.has_incoming() + } + + pub fn poll_events_with_timeout<F>(&mut self, mut timeout: Option<Duration>, mut callback: F) + where + F: FnMut(Event<T>, &RootAEL), + { + let start = Instant::now(); + + let has_pending = self.has_pending(); + + timeout = if has_pending { + // If we already have work to do then we don't want to block on the next poll. + Some(Duration::ZERO) + } else { + let control_flow_timeout = match self.control_flow() { + ControlFlow::Wait => None, + ControlFlow::Poll => Some(Duration::ZERO), + ControlFlow::WaitUntil(wait_deadline) => { + Some(wait_deadline.saturating_duration_since(start)) + }, + }; + + min_timeout(control_flow_timeout, timeout) + }; + + self.state.x11_readiness = Readiness::EMPTY; + if let Err(error) = + self.event_loop.dispatch(timeout, &mut self.state).map_err(std::io::Error::from) + { + tracing::error!("Failed to poll for events: {error:?}"); + let exit_code = error.raw_os_error().unwrap_or(1); + self.set_exit_code(exit_code); + return; + } + + // NB: `StartCause::Init` is handled as a special case and doesn't need + // to be considered here + let cause = match self.control_flow() { + ControlFlow::Poll => StartCause::Poll, + ControlFlow::Wait => StartCause::WaitCancelled { start, requested_resume: None }, + ControlFlow::WaitUntil(deadline) => { + if Instant::now() < deadline { + StartCause::WaitCancelled { start, requested_resume: Some(deadline) } + } else { + StartCause::ResumeTimeReached { start, requested_resume: deadline } + } + }, + }; + + // False positive / spurious wake ups could lead to us spamming + // redundant iterations of the event loop with no new events to + // dispatch. + // + // If there's no readable event source then we just double check if we + // have any pending `_receiver` events and if not we return without + // running a loop iteration. + // If we don't have any pending `_receiver` + if !self.has_pending() + && !matches!(&cause, StartCause::ResumeTimeReached { .. } | StartCause::Poll) + && timeout.is_none() + { + return; + } + + self.single_iteration(&mut callback, cause); + } + + fn single_iteration<F>(&mut self, callback: &mut F, cause: StartCause) + where + F: FnMut(Event<T>, &RootAEL), + { + callback(Event::NewEvents(cause), &self.event_processor.target); + + // NB: For consistency all platforms must emit a 'resumed' event even though X11 + // applications don't themselves have a formal suspend/resume lifecycle. + if cause == StartCause::Init { + callback(Event::Resumed, &self.event_processor.target); + } + + // Process all pending events + self.drain_events(callback); + + // Empty activation tokens. + while let Ok((window_id, serial)) = self.activation_receiver.try_recv() { + let token = self.event_processor.with_window(window_id.0 as xproto::Window, |window| { + window.generate_activation_token() + }); + + match token { + Some(Ok(token)) => { + let event = Event::WindowEvent { + window_id: crate::window::WindowId(window_id), + event: WindowEvent::ActivationTokenDone { + serial, + token: crate::window::ActivationToken::from_raw(token), + }, + }; + callback(event, &self.event_processor.target) + }, + Some(Err(e)) => { + tracing::error!("Failed to get activation token: {}", e); + }, + None => {}, + } + } + + // Empty the user event buffer + { + while let Ok(event) = self.user_receiver.try_recv() { + callback(Event::UserEvent(event), &self.event_processor.target); + } + } + + // Empty the redraw requests + { + let mut windows = HashSet::new(); + + while let Ok(window_id) = self.redraw_receiver.try_recv() { + windows.insert(window_id); + } + + for window_id in windows { + let window_id = crate::window::WindowId(window_id); + callback( + Event::WindowEvent { window_id, event: WindowEvent::RedrawRequested }, + &self.event_processor.target, + ); + } + } + + // This is always the last event we dispatch before poll again + { + callback(Event::AboutToWait, &self.event_processor.target); + } + } + + fn drain_events<F>(&mut self, callback: &mut F) + where + F: FnMut(Event<T>, &RootAEL), + { + let mut xev = MaybeUninit::uninit(); + + while unsafe { self.event_processor.poll_one_event(xev.as_mut_ptr()) } { + let mut xev = unsafe { xev.assume_init() }; + self.event_processor.process_event(&mut xev, |window_target, event| { + if let Event::WindowEvent { + window_id: crate::window::WindowId(wid), + event: WindowEvent::RedrawRequested, + } = event + { + let window_target = EventProcessor::window_target(window_target); + window_target.redraw_sender.send(wid).unwrap(); + } else { + callback(event, window_target); + } + }); + } + } + + fn control_flow(&self) -> ControlFlow { + let window_target = EventProcessor::window_target(&self.event_processor.target); + window_target.control_flow() + } + + fn exiting(&self) -> bool { + let window_target = EventProcessor::window_target(&self.event_processor.target); + window_target.exiting() + } + + fn set_exit_code(&self, code: i32) { + let window_target = EventProcessor::window_target(&self.event_processor.target); + window_target.set_exit_code(code); + } + + fn exit_code(&self) -> Option<i32> { + let window_target = EventProcessor::window_target(&self.event_processor.target); + window_target.exit_code() + } +} + +impl<T> AsFd for EventLoop<T> { + fn as_fd(&self) -> BorrowedFd<'_> { + self.event_loop.as_fd() + } +} + +impl<T> AsRawFd for EventLoop<T> { + fn as_raw_fd(&self) -> RawFd { + self.event_loop.as_raw_fd() + } +} + +impl ActiveEventLoop { + /// Returns the `XConnection` of this events loop. + #[inline] + pub(crate) fn x_connection(&self) -> &Arc<XConnection> { + &self.xconn + } + + pub fn available_monitors(&self) -> impl Iterator<Item = MonitorHandle> { + self.xconn.available_monitors().into_iter().flatten() + } + + pub fn primary_monitor(&self) -> Option<MonitorHandle> { + self.xconn.primary_monitor().ok() + } + + pub(crate) fn create_custom_cursor(&self, cursor: CustomCursorSource) -> RootCustomCursor { + RootCustomCursor { inner: PlatformCustomCursor::X(CustomCursor::new(self, cursor.inner)) } + } + + pub fn listen_device_events(&self, allowed: DeviceEvents) { + self.device_events.set(allowed); + } + + /// Update the device event based on window focus. + pub fn update_listen_device_events(&self, focus: bool) { + let device_events = self.device_events.get() == DeviceEvents::Always + || (focus && self.device_events.get() == DeviceEvents::WhenFocused); + + let mut mask = xinput::XIEventMask::from(0u32); + if device_events { + mask = xinput::XIEventMask::RAW_MOTION + | xinput::XIEventMask::RAW_BUTTON_PRESS + | xinput::XIEventMask::RAW_BUTTON_RELEASE + | xinput::XIEventMask::RAW_KEY_PRESS + | xinput::XIEventMask::RAW_KEY_RELEASE; + } + + self.xconn + .select_xinput_events(self.root, ALL_MASTER_DEVICES, mask) + .expect_then_ignore_error("Failed to update device event filter"); + } + + #[cfg(feature = "rwh_05")] + pub fn raw_display_handle_rwh_05(&self) -> rwh_05::RawDisplayHandle { + let mut display_handle = rwh_05::XlibDisplayHandle::empty(); + display_handle.display = self.xconn.display as *mut _; + display_handle.screen = self.xconn.default_screen_index() as c_int; + display_handle.into() + } + + #[cfg(feature = "rwh_06")] + pub fn raw_display_handle_rwh_06( + &self, + ) -> Result<rwh_06::RawDisplayHandle, rwh_06::HandleError> { + let display_handle = rwh_06::XlibDisplayHandle::new( + // SAFETY: display will never be null + Some( + std::ptr::NonNull::new(self.xconn.display as *mut _) + .expect("X11 display should never be null"), + ), + self.xconn.default_screen_index() as c_int, + ); + Ok(display_handle.into()) + } + + pub(crate) fn set_control_flow(&self, control_flow: ControlFlow) { + self.control_flow.set(control_flow) + } + + pub(crate) fn control_flow(&self) -> ControlFlow { + self.control_flow.get() + } + + pub(crate) fn exit(&self) { + self.exit.set(Some(0)) + } + + pub(crate) fn clear_exit(&self) { + self.exit.set(None) + } + + pub(crate) fn exiting(&self) -> bool { + self.exit.get().is_some() + } + + pub(crate) fn set_exit_code(&self, code: i32) { + self.exit.set(Some(code)) + } + + pub(crate) fn exit_code(&self) -> Option<i32> { + self.exit.get() + } +} + +impl<T: 'static> EventLoopProxy<T> { + pub fn send_event(&self, event: T) -> Result<(), EventLoopClosed<T>> { + self.user_sender.send(event).map_err(|e| EventLoopClosed(e.0)) + } +} + +struct DeviceInfo<'a> { + xconn: &'a XConnection, + info: *const ffi::XIDeviceInfo, + count: usize, +} + +impl<'a> DeviceInfo<'a> { + fn get(xconn: &'a XConnection, device: c_int) -> Option<Self> { + unsafe { + let mut count = 0; + let info = (xconn.xinput2.XIQueryDevice)(xconn.display, device, &mut count); + xconn.check_errors().ok()?; + + if info.is_null() || count == 0 { + None + } else { + Some(DeviceInfo { xconn, info, count: count as usize }) + } + } + } +} + +impl Drop for DeviceInfo<'_> { + fn drop(&mut self) { + assert!(!self.info.is_null()); + unsafe { (self.xconn.xinput2.XIFreeDeviceInfo)(self.info as *mut _) }; + } +} + +impl Deref for DeviceInfo<'_> { + type Target = [ffi::XIDeviceInfo]; + + fn deref(&self) -> &Self::Target { + unsafe { slice::from_raw_parts(self.info, self.count) } + } +} + +#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub struct DeviceId(xinput::DeviceId); + +impl DeviceId { + #[allow(unused)] + pub const fn dummy() -> Self { + DeviceId(0) + } +} + +pub(crate) struct Window(Arc<UnownedWindow>); + +impl Deref for Window { + type Target = UnownedWindow; + + #[inline] + fn deref(&self) -> &UnownedWindow { + &self.0 + } +} + +impl Window { + pub(crate) fn new( + event_loop: &ActiveEventLoop, + attribs: WindowAttributes, + ) -> Result<Self, RootOsError> { + let window = Arc::new(UnownedWindow::new(event_loop, attribs)?); + event_loop.windows.borrow_mut().insert(window.id(), Arc::downgrade(&window)); + Ok(Window(window)) + } +} + +impl Drop for Window { + fn drop(&mut self) { + let window = self.deref(); + let xconn = &window.xconn; + + if let Ok(c) = xconn.xcb_connection().destroy_window(window.id().0 as xproto::Window) { + c.ignore_error(); + } + } +} + +/// Generic sum error type for X11 errors. +#[derive(Debug)] +pub enum X11Error { + /// An error from the Xlib library. + Xlib(XError), + + /// An error that occurred while trying to connect to the X server. + Connect(ConnectError), + + /// An error that occurred over the connection medium. + Connection(ConnectionError), + + /// An error that occurred logically on the X11 end. + X11(LogicalError), + + /// The XID range has been exhausted. + XidsExhausted(IdsExhausted), + + /// Got `null` from an Xlib function without a reason. + UnexpectedNull(&'static str), + + /// Got an invalid activation token. + InvalidActivationToken(Vec<u8>), + + /// An extension that we rely on is not available. + MissingExtension(&'static str), + + /// Could not find a matching X11 visual for this visualid + NoSuchVisual(xproto::Visualid), + + /// Unable to parse xsettings. + XsettingsParse(xsettings::ParserError), + + /// Failed to get property. + GetProperty(util::GetPropertyError), +} + +impl fmt::Display for X11Error { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + X11Error::Xlib(e) => write!(f, "Xlib error: {e}"), + X11Error::Connect(e) => write!(f, "X11 connection error: {e}"), + X11Error::Connection(e) => write!(f, "X11 connection error: {e}"), + X11Error::XidsExhausted(e) => write!(f, "XID range exhausted: {e}"), + X11Error::GetProperty(e) => write!(f, "Failed to get X property {e}"), + X11Error::X11(e) => write!(f, "X11 error: {e:?}"), + X11Error::UnexpectedNull(s) => write!(f, "Xlib function returned null: {s}"), + X11Error::InvalidActivationToken(s) => write!( + f, + "Invalid activation token: {}", + std::str::from_utf8(s).unwrap_or("<invalid utf8>") + ), + X11Error::MissingExtension(s) => write!(f, "Missing X11 extension: {s}"), + X11Error::NoSuchVisual(visualid) => { + write!(f, "Could not find a matching X11 visual for ID `{visualid:x}`") + }, + X11Error::XsettingsParse(err) => { + write!(f, "Failed to parse xsettings: {err:?}") + }, + } + } +} + +impl std::error::Error for X11Error { + fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { + match self { + X11Error::Xlib(e) => Some(e), + X11Error::Connect(e) => Some(e), + X11Error::Connection(e) => Some(e), + X11Error::XidsExhausted(e) => Some(e), + _ => None, + } + } +} + +impl From<XError> for X11Error { + fn from(e: XError) -> Self { + X11Error::Xlib(e) + } +} + +impl From<ConnectError> for X11Error { + fn from(e: ConnectError) -> Self { + X11Error::Connect(e) + } +} + +impl From<ConnectionError> for X11Error { + fn from(e: ConnectionError) -> Self { + X11Error::Connection(e) + } +} + +impl From<LogicalError> for X11Error { + fn from(e: LogicalError) -> Self { + X11Error::X11(e) + } +} + +impl From<ReplyError> for X11Error { + fn from(value: ReplyError) -> Self { + match value { + ReplyError::ConnectionError(e) => e.into(), + ReplyError::X11Error(e) => e.into(), + } + } +} + +impl From<ime::ImeContextCreationError> for X11Error { + fn from(value: ime::ImeContextCreationError) -> Self { + match value { + ime::ImeContextCreationError::XError(e) => e.into(), + ime::ImeContextCreationError::Null => Self::UnexpectedNull("XOpenIM"), + } + } +} + +impl From<ReplyOrIdError> for X11Error { + fn from(value: ReplyOrIdError) -> Self { + match value { + ReplyOrIdError::ConnectionError(e) => e.into(), + ReplyOrIdError::X11Error(e) => e.into(), + ReplyOrIdError::IdsExhausted => Self::XidsExhausted(IdsExhausted), + } + } +} + +impl From<xsettings::ParserError> for X11Error { + fn from(value: xsettings::ParserError) -> Self { + Self::XsettingsParse(value) + } +} + +impl From<util::GetPropertyError> for X11Error { + fn from(value: util::GetPropertyError) -> Self { + Self::GetProperty(value) + } +} + +/// Type alias for a void cookie. +type VoidCookie<'a> = x11rb::cookie::VoidCookie<'a, X11rbConnection>; + +/// Extension trait for `Result<VoidCookie, E>`. +trait CookieResultExt { + /// Unwrap the send error and ignore the result. + fn expect_then_ignore_error(self, msg: &str); +} + +impl<E: fmt::Debug> CookieResultExt for Result<VoidCookie<'_>, E> { + fn expect_then_ignore_error(self, msg: &str) { + self.expect(msg).ignore_error() + } +} + +fn mkwid(w: xproto::Window) -> crate::window::WindowId { + crate::window::WindowId(crate::platform_impl::platform::WindowId(w as _)) +} +fn mkdid(w: xinput::DeviceId) -> crate::event::DeviceId { + crate::event::DeviceId(crate::platform_impl::DeviceId::X(DeviceId(w))) +} + +#[derive(Debug)] +pub struct Device { + _name: String, + scroll_axes: Vec<(i32, ScrollAxis)>, + // For master devices, this is the paired device (pointer <-> keyboard). + // For slave devices, this is the master. + attachment: c_int, +} + +#[derive(Debug, Copy, Clone)] +struct ScrollAxis { + increment: f64, + orientation: ScrollOrientation, + position: f64, +} + +#[derive(Debug, Copy, Clone)] +enum ScrollOrientation { + Vertical, + Horizontal, +} + +impl Device { + fn new(info: &ffi::XIDeviceInfo) -> Self { + let name = unsafe { CStr::from_ptr(info.name).to_string_lossy() }; + let mut scroll_axes = Vec::new(); + + if Device::physical_device(info) { + // Identify scroll axes + for &class_ptr in Device::classes(info) { + let ty = unsafe { (*class_ptr)._type }; + if ty == ffi::XIScrollClass { + let info = unsafe { &*(class_ptr as *const ffi::XIScrollClassInfo) }; + scroll_axes.push((info.number, ScrollAxis { + increment: info.increment, + orientation: match info.scroll_type { + ffi::XIScrollTypeHorizontal => ScrollOrientation::Horizontal, + ffi::XIScrollTypeVertical => ScrollOrientation::Vertical, + _ => unreachable!(), + }, + position: 0.0, + })); + } + } + } + + let mut device = + Device { _name: name.into_owned(), scroll_axes, attachment: info.attachment }; + device.reset_scroll_position(info); + device + } + + fn reset_scroll_position(&mut self, info: &ffi::XIDeviceInfo) { + if Device::physical_device(info) { + for &class_ptr in Device::classes(info) { + let ty = unsafe { (*class_ptr)._type }; + if ty == ffi::XIValuatorClass { + let info = unsafe { &*(class_ptr as *const ffi::XIValuatorClassInfo) }; + if let Some(&mut (_, ref mut axis)) = + self.scroll_axes.iter_mut().find(|&&mut (axis, _)| axis == info.number) + { + axis.position = info.value; + } + } + } + } + } + + #[inline] + fn physical_device(info: &ffi::XIDeviceInfo) -> bool { + info._use == ffi::XISlaveKeyboard + || info._use == ffi::XISlavePointer + || info._use == ffi::XIFloatingSlave + } + + #[inline] + fn classes(info: &ffi::XIDeviceInfo) -> &[*const ffi::XIAnyClassInfo] { + unsafe { + slice::from_raw_parts( + info.classes as *const *const ffi::XIAnyClassInfo, + info.num_classes as usize, + ) + } + } +} + +/// Convert the raw X11 representation for a 32-bit floating point to a double. +#[inline] +fn xinput_fp1616_to_float(fp: xinput::Fp1616) -> f64 { + (fp as f64) / ((1 << 16) as f64) +} diff --git a/app/vendor/rune/vendor/winit/src/platform_impl/linux/x11/monitor.rs b/app/vendor/rune/vendor/winit/src/platform_impl/linux/x11/monitor.rs new file mode 100644 index 0000000..1964bc9 --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/platform_impl/linux/x11/monitor.rs @@ -0,0 +1,355 @@ +use super::{util, X11Error, XConnection}; +use crate::dpi::{PhysicalPosition, PhysicalSize}; +use crate::platform_impl::VideoModeHandle as PlatformVideoModeHandle; +use x11rb::connection::RequestConnection; +use x11rb::protocol::randr::{self, ConnectionExt as _}; +use x11rb::protocol::xproto; + +// Used for testing. This should always be committed as false. +const DISABLE_MONITOR_LIST_CACHING: bool = false; + +impl XConnection { + pub fn invalidate_cached_monitor_list(&self) -> Option<Vec<MonitorHandle>> { + // We update this lazily. + self.monitor_handles.lock().unwrap().take() + } +} + +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub struct VideoModeHandle { + pub(crate) size: (u32, u32), + pub(crate) bit_depth: u16, + pub(crate) refresh_rate_millihertz: u32, + pub(crate) native_mode: randr::Mode, + pub(crate) monitor: Option<MonitorHandle>, +} + +impl VideoModeHandle { + #[inline] + pub fn size(&self) -> PhysicalSize<u32> { + self.size.into() + } + + #[inline] + pub fn bit_depth(&self) -> u16 { + self.bit_depth + } + + #[inline] + pub fn refresh_rate_millihertz(&self) -> u32 { + self.refresh_rate_millihertz + } + + #[inline] + pub fn monitor(&self) -> MonitorHandle { + self.monitor.clone().unwrap() + } +} + +#[derive(Debug, Clone)] +pub struct MonitorHandle { + /// The actual id + pub(crate) id: randr::Crtc, + /// The name of the monitor + pub(crate) name: String, + /// The size of the monitor + dimensions: (u32, u32), + /// The position of the monitor in the X screen + position: (i32, i32), + /// If the monitor is the primary one + primary: bool, + /// The refresh rate used by monitor. + refresh_rate_millihertz: Option<u32>, + /// The DPI scale factor + pub(crate) scale_factor: f64, + /// Used to determine which windows are on this monitor + pub(crate) rect: util::AaRect, + /// Supported video modes on this monitor + video_modes: Vec<VideoModeHandle>, +} + +impl PartialEq for MonitorHandle { + fn eq(&self, other: &Self) -> bool { + self.id == other.id + } +} + +impl Eq for MonitorHandle {} + +impl PartialOrd for MonitorHandle { + fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> { + Some(self.cmp(other)) + } +} + +impl Ord for MonitorHandle { + fn cmp(&self, other: &Self) -> std::cmp::Ordering { + self.id.cmp(&other.id) + } +} + +impl std::hash::Hash for MonitorHandle { + fn hash<H: std::hash::Hasher>(&self, state: &mut H) { + self.id.hash(state); + } +} + +#[inline] +pub fn mode_refresh_rate_millihertz(mode: &randr::ModeInfo) -> Option<u32> { + if mode.dot_clock > 0 && mode.htotal > 0 && mode.vtotal > 0 { + #[allow(clippy::unnecessary_cast)] + Some((mode.dot_clock as u64 * 1000 / (mode.htotal as u64 * mode.vtotal as u64)) as u32) + } else { + None + } +} + +impl MonitorHandle { + fn new( + xconn: &XConnection, + resources: &ScreenResources, + id: randr::Crtc, + crtc: &randr::GetCrtcInfoReply, + primary: bool, + ) -> Option<Self> { + let (name, scale_factor, video_modes) = xconn.get_output_info(resources, crtc)?; + let dimensions = (crtc.width as u32, crtc.height as u32); + let position = (crtc.x as i32, crtc.y as i32); + + // Get the refresh rate of the current video mode. + let current_mode = crtc.mode; + let screen_modes = resources.modes(); + let refresh_rate_millihertz = screen_modes + .iter() + .find(|mode| mode.id == current_mode) + .and_then(mode_refresh_rate_millihertz); + + let rect = util::AaRect::new(position, dimensions); + + Some(MonitorHandle { + id, + name, + refresh_rate_millihertz, + scale_factor, + dimensions, + position, + primary, + rect, + video_modes, + }) + } + + pub fn dummy() -> Self { + MonitorHandle { + id: 0, + name: "<dummy monitor>".into(), + scale_factor: 1.0, + dimensions: (1, 1), + position: (0, 0), + refresh_rate_millihertz: None, + primary: true, + rect: util::AaRect::new((0, 0), (1, 1)), + video_modes: Vec::new(), + } + } + + pub(crate) fn is_dummy(&self) -> bool { + // Zero is an invalid XID value; no real monitor will have it + self.id == 0 + } + + pub fn name(&self) -> Option<String> { + Some(self.name.clone()) + } + + #[inline] + pub fn native_identifier(&self) -> u32 { + self.id as _ + } + + pub fn size(&self) -> PhysicalSize<u32> { + self.dimensions.into() + } + + pub fn position(&self) -> PhysicalPosition<i32> { + self.position.into() + } + + pub fn refresh_rate_millihertz(&self) -> Option<u32> { + self.refresh_rate_millihertz + } + + #[inline] + pub fn scale_factor(&self) -> f64 { + self.scale_factor + } + + #[inline] + pub fn video_modes(&self) -> impl Iterator<Item = PlatformVideoModeHandle> { + let monitor = self.clone(); + self.video_modes.clone().into_iter().map(move |mut x| { + x.monitor = Some(monitor.clone()); + PlatformVideoModeHandle::X(x) + }) + } +} + +impl XConnection { + pub fn get_monitor_for_window( + &self, + window_rect: Option<util::AaRect>, + ) -> Result<MonitorHandle, X11Error> { + let monitors = self.available_monitors()?; + + if monitors.is_empty() { + // Return a dummy monitor to avoid panicking + return Ok(MonitorHandle::dummy()); + } + + let default = monitors.first().unwrap(); + + let window_rect = match window_rect { + Some(rect) => rect, + None => return Ok(default.to_owned()), + }; + + let mut largest_overlap = 0; + let mut matched_monitor = default; + for monitor in &monitors { + let overlapping_area = window_rect.get_overlapping_area(&monitor.rect); + if overlapping_area > largest_overlap { + largest_overlap = overlapping_area; + matched_monitor = monitor; + } + } + + Ok(matched_monitor.to_owned()) + } + + fn query_monitor_list(&self) -> Result<Vec<MonitorHandle>, X11Error> { + let root = self.default_root(); + let resources = + ScreenResources::from_connection(self.xcb_connection(), root, self.randr_version())?; + + // Pipeline all of the get-crtc requests. + let mut crtc_cookies = Vec::with_capacity(resources.crtcs().len()); + for &crtc in resources.crtcs() { + crtc_cookies + .push(self.xcb_connection().randr_get_crtc_info(crtc, x11rb::CURRENT_TIME)?); + } + + // Do this here so we do all of our requests in one shot. + let primary = self.xcb_connection().randr_get_output_primary(root.root)?.reply()?.output; + + let mut crtc_infos = Vec::with_capacity(crtc_cookies.len()); + for cookie in crtc_cookies { + let reply = cookie.reply()?; + crtc_infos.push(reply); + } + + let mut has_primary = false; + let mut available_monitors = Vec::with_capacity(resources.crtcs().len()); + for (crtc_id, crtc) in resources.crtcs().iter().zip(crtc_infos.iter()) { + if crtc.width == 0 || crtc.height == 0 || crtc.outputs.is_empty() { + continue; + } + + let is_primary = crtc.outputs[0] == primary; + has_primary |= is_primary; + let monitor = MonitorHandle::new(self, &resources, *crtc_id, crtc, is_primary); + available_monitors.extend(monitor); + } + + // If we don't have a primary monitor, just pick one ourselves! + if !has_primary { + if let Some(ref mut fallback) = available_monitors.first_mut() { + // Setting this here will come in handy if we ever add an `is_primary` method. + fallback.primary = true; + } + } + + Ok(available_monitors) + } + + pub fn available_monitors(&self) -> Result<Vec<MonitorHandle>, X11Error> { + let mut monitors_lock = self.monitor_handles.lock().unwrap(); + match *monitors_lock { + Some(ref monitors) => Ok(monitors.clone()), + None => { + let monitors = self.query_monitor_list()?; + if !DISABLE_MONITOR_LIST_CACHING { + *monitors_lock = Some(monitors.clone()); + } + Ok(monitors) + }, + } + } + + #[inline] + pub fn primary_monitor(&self) -> Result<MonitorHandle, X11Error> { + Ok(self + .available_monitors()? + .into_iter() + .find(|monitor| monitor.primary) + .unwrap_or_else(MonitorHandle::dummy)) + } + + pub fn select_xrandr_input(&self, root: xproto::Window) -> Result<u8, X11Error> { + use randr::NotifyMask; + + // Get extension info. + let info = self + .xcb_connection() + .extension_information(randr::X11_EXTENSION_NAME)? + .ok_or(X11Error::MissingExtension(randr::X11_EXTENSION_NAME))?; + + // Select input data. + let event_mask = + NotifyMask::CRTC_CHANGE | NotifyMask::OUTPUT_PROPERTY | NotifyMask::SCREEN_CHANGE; + self.xcb_connection().randr_select_input(root, event_mask)?; + + Ok(info.first_event) + } +} + +pub struct ScreenResources { + /// List of attached modes. + modes: Vec<randr::ModeInfo>, + + /// List of attached CRTCs. + crtcs: Vec<randr::Crtc>, +} + +impl ScreenResources { + pub(crate) fn modes(&self) -> &[randr::ModeInfo] { + &self.modes + } + + pub(crate) fn crtcs(&self) -> &[randr::Crtc] { + &self.crtcs + } + + pub(crate) fn from_connection( + conn: &impl x11rb::connection::Connection, + root: &x11rb::protocol::xproto::Screen, + (major_version, minor_version): (u32, u32), + ) -> Result<Self, X11Error> { + if (major_version == 1 && minor_version >= 3) || major_version > 1 { + let reply = conn.randr_get_screen_resources_current(root.root)?.reply()?; + Ok(Self::from_get_screen_resources_current_reply(reply)) + } else { + let reply = conn.randr_get_screen_resources(root.root)?.reply()?; + Ok(Self::from_get_screen_resources_reply(reply)) + } + } + + pub(crate) fn from_get_screen_resources_reply(reply: randr::GetScreenResourcesReply) -> Self { + Self { modes: reply.modes, crtcs: reply.crtcs } + } + + pub(crate) fn from_get_screen_resources_current_reply( + reply: randr::GetScreenResourcesCurrentReply, + ) -> Self { + Self { modes: reply.modes, crtcs: reply.crtcs } + } +} diff --git a/app/vendor/rune/vendor/winit/src/platform_impl/linux/x11/tests/xsettings.dat b/app/vendor/rune/vendor/winit/src/platform_impl/linux/x11/tests/xsettings.dat new file mode 100644 index 0000000..e04eeb1 --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/platform_impl/linux/x11/tests/xsettings.dat @@ -0,0 +1 @@ +0x6c,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x22,0x00,0x00,0x00,0x00,0x00,0x0b,0x00,0x58,0x66,0x74,0x2f,0x48,0x69,0x6e,0x74,0x69,0x6e,0x67,0x00,0x00,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x00,0x00,0x14,0x00,0x47,0x74,0x6b,0x2f,0x44,0x69,0x61,0x6c,0x6f,0x67,0x73,0x55,0x73,0x65,0x48,0x65,0x61,0x64,0x65,0x72,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x00,0x0c,0x00,0x47,0x74,0x6b,0x2f,0x46,0x6f,0x6e,0x74,0x4e,0x61,0x6d,0x65,0x00,0x00,0x00,0x00,0x0b,0x00,0x00,0x00,0x4e,0x6f,0x74,0x6f,0x20,0x53,0x61,0x6e,0x73,0x20,0x39,0x00,0x01,0x00,0x0d,0x00,0x58,0x66,0x74,0x2f,0x4c,0x63,0x64,0x66,0x69,0x6c,0x74,0x65,0x72,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x0a,0x00,0x00,0x00,0x6c,0x63,0x64,0x64,0x65,0x66,0x61,0x75,0x6c,0x74,0x00,0x00,0x01,0x00,0x10,0x00,0x47,0x74,0x6b,0x2f,0x4b,0x65,0x79,0x54,0x68,0x65,0x6d,0x65,0x4e,0x61,0x6d,0x65,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x00,0x0d,0x00,0x58,0x66,0x74,0x2f,0x48,0x69,0x6e,0x74,0x53,0x74,0x79,0x6c,0x65,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x0a,0x00,0x00,0x00,0x68,0x69,0x6e,0x74,0x73,0x6c,0x69,0x67,0x68,0x74,0x00,0x00,0x01,0x00,0x11,0x00,0x4e,0x65,0x74,0x2f,0x49,0x63,0x6f,0x6e,0x54,0x68,0x65,0x6d,0x65,0x4e,0x61,0x6d,0x65,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x14,0x00,0x00,0x00,0x65,0x6c,0x65,0x6d,0x65,0x6e,0x74,0x61,0x72,0x79,0x2d,0x78,0x66,0x63,0x65,0x2d,0x64,0x61,0x72,0x6b,0x00,0x00,0x0d,0x00,0x58,0x66,0x74,0x2f,0x41,0x6e,0x74,0x69,0x61,0x6c,0x69,0x61,0x73,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x01,0x00,0x08,0x00,0x58,0x66,0x74,0x2f,0x52,0x47,0x42,0x41,0x00,0x00,0x00,0x00,0x03,0x00,0x00,0x00,0x72,0x67,0x62,0x00,0x00,0x00,0x13,0x00,0x4e,0x65,0x74,0x2f,0x43,0x75,0x72,0x73,0x6f,0x72,0x42,0x6c,0x69,0x6e,0x6b,0x54,0x69,0x6d,0x65,0x00,0x00,0x00,0x00,0x00,0xb0,0x04,0x00,0x00,0x00,0x00,0x13,0x00,0x47,0x74,0x6b,0x2f,0x43,0x75,0x72,0x73,0x6f,0x72,0x54,0x68,0x65,0x6d,0x65,0x53,0x69,0x7a,0x65,0x00,0x00,0x00,0x00,0x00,0x18,0x00,0x00,0x00,0x01,0x00,0x15,0x00,0x4e,0x65,0x74,0x2f,0x46,0x61,0x6c,0x6c,0x62,0x61,0x63,0x6b,0x49,0x63,0x6f,0x6e,0x54,0x68,0x65,0x6d,0x65,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x05,0x00,0x00,0x00,0x67,0x6e,0x6f,0x6d,0x65,0x00,0x00,0x00,0x01,0x00,0x10,0x00,0x47,0x74,0x6b,0x2f,0x54,0x6f,0x6f,0x6c,0x62,0x61,0x72,0x53,0x74,0x79,0x6c,0x65,0x00,0x00,0x00,0x00,0x05,0x00,0x00,0x00,0x69,0x63,0x6f,0x6e,0x73,0x00,0x00,0x00,0x01,0x00,0x12,0x00,0x4e,0x65,0x74,0x2f,0x53,0x6f,0x75,0x6e,0x64,0x54,0x68,0x65,0x6d,0x65,0x4e,0x61,0x6d,0x65,0x00,0x00,0x00,0x00,0x00,0x00,0x07,0x00,0x00,0x00,0x64,0x65,0x66,0x61,0x75,0x6c,0x74,0x00,0x00,0x00,0x15,0x00,0x4e,0x65,0x74,0x2f,0x45,0x6e,0x61,0x62,0x6c,0x65,0x45,0x76,0x65,0x6e,0x74,0x53,0x6f,0x75,0x6e,0x64,0x73,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x0f,0x00,0x4e,0x65,0x74,0x2f,0x43,0x75,0x72,0x73,0x6f,0x72,0x42,0x6c,0x69,0x6e,0x6b,0x00,0x00,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x01,0x00,0x10,0x00,0x47,0x74,0x6b,0x2f,0x43,0x6f,0x6c,0x6f,0x72,0x50,0x61,0x6c,0x65,0x74,0x74,0x65,0x00,0x00,0x00,0x00,0x94,0x00,0x00,0x00,0x62,0x6c,0x61,0x63,0x6b,0x3a,0x77,0x68,0x69,0x74,0x65,0x3a,0x67,0x72,0x61,0x79,0x35,0x30,0x3a,0x72,0x65,0x64,0x3a,0x70,0x75,0x72,0x70,0x6c,0x65,0x3a,0x62,0x6c,0x75,0x65,0x3a,0x6c,0x69,0x67,0x68,0x74,0x20,0x62,0x6c,0x75,0x65,0x3a,0x67,0x72,0x65,0x65,0x6e,0x3a,0x79,0x65,0x6c,0x6c,0x6f,0x77,0x3a,0x6f,0x72,0x61,0x6e,0x67,0x65,0x3a,0x6c,0x61,0x76,0x65,0x6e,0x64,0x65,0x72,0x3a,0x62,0x72,0x6f,0x77,0x6e,0x3a,0x67,0x6f,0x6c,0x64,0x65,0x6e,0x72,0x6f,0x64,0x34,0x3a,0x64,0x6f,0x64,0x67,0x65,0x72,0x20,0x62,0x6c,0x75,0x65,0x3a,0x70,0x69,0x6e,0x6b,0x3a,0x6c,0x69,0x67,0x68,0x74,0x20,0x67,0x72,0x65,0x65,0x6e,0x3a,0x67,0x72,0x61,0x79,0x31,0x30,0x3a,0x67,0x72,0x61,0x79,0x33,0x30,0x3a,0x67,0x72,0x61,0x79,0x37,0x35,0x3a,0x67,0x72,0x61,0x79,0x39,0x30,0x00,0x00,0x13,0x00,0x4e,0x65,0x74,0x2f,0x44,0x6f,0x75,0x62,0x6c,0x65,0x43,0x6c,0x69,0x63,0x6b,0x54,0x69,0x6d,0x65,0x00,0x00,0x00,0x00,0x00,0x90,0x01,0x00,0x00,0x00,0x00,0x13,0x00,0x47,0x74,0x6b,0x2f,0x43,0x61,0x6e,0x43,0x68,0x61,0x6e,0x67,0x65,0x41,0x63,0x63,0x65,0x6c,0x73,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x00,0x10,0x00,0x47,0x74,0x6b,0x2f,0x4d,0x65,0x6e,0x75,0x42,0x61,0x72,0x41,0x63,0x63,0x65,0x6c,0x00,0x00,0x00,0x00,0x03,0x00,0x00,0x00,0x46,0x31,0x30,0x00,0x01,0x00,0x0d,0x00,0x4e,0x65,0x74,0x2f,0x54,0x68,0x65,0x6d,0x65,0x4e,0x61,0x6d,0x65,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x08,0x00,0x00,0x00,0x47,0x72,0x65,0x79,0x62,0x69,0x72,0x64,0x01,0x00,0x17,0x00,0x47,0x74,0x6b,0x2f,0x54,0x69,0x74,0x6c,0x65,0x62,0x61,0x72,0x4d,0x69,0x64,0x64,0x6c,0x65,0x43,0x6c,0x69,0x63,0x6b,0x00,0x00,0x00,0x00,0x00,0x05,0x00,0x00,0x00,0x6c,0x6f,0x77,0x65,0x72,0x00,0x00,0x00,0x00,0x00,0x10,0x00,0x47,0x74,0x6b,0x2f,0x42,0x75,0x74,0x74,0x6f,0x6e,0x49,0x6d,0x61,0x67,0x65,0x73,0x00,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x00,0x00,0x17,0x00,0x4e,0x65,0x74,0x2f,0x44,0x6f,0x75,0x62,0x6c,0x65,0x43,0x6c,0x69,0x63,0x6b,0x44,0x69,0x73,0x74,0x61,0x6e,0x63,0x65,0x00,0x00,0x00,0x00,0x00,0x05,0x00,0x00,0x00,0x01,0x00,0x15,0x00,0x47,0x74,0x6b,0x2f,0x4d,0x6f,0x6e,0x6f,0x73,0x70,0x61,0x63,0x65,0x46,0x6f,0x6e,0x74,0x4e,0x61,0x6d,0x65,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x0c,0x00,0x00,0x00,0x4d,0x6f,0x6e,0x6f,0x73,0x70,0x61,0x63,0x65,0x20,0x31,0x30,0x00,0x00,0x07,0x00,0x58,0x66,0x74,0x2f,0x44,0x50,0x49,0x00,0x02,0x00,0x00,0x00,0x00,0x80,0x01,0x00,0x01,0x00,0x13,0x00,0x47,0x74,0x6b,0x2f,0x43,0x75,0x72,0x73,0x6f,0x72,0x54,0x68,0x65,0x6d,0x65,0x4e,0x61,0x6d,0x65,0x00,0x00,0x00,0x00,0x00,0x09,0x00,0x00,0x00,0x44,0x4d,0x5a,0x2d,0x57,0x68,0x69,0x74,0x65,0x00,0x00,0x00,0x00,0x00,0x13,0x00,0x47,0x74,0x6b,0x2f,0x54,0x6f,0x6f,0x6c,0x62,0x61,0x72,0x49,0x63,0x6f,0x6e,0x53,0x69,0x7a,0x65,0x00,0x00,0x00,0x00,0x00,0x03,0x00,0x00,0x00,0x00,0x00,0x14,0x00,0x4e,0x65,0x74,0x2f,0x44,0x6e,0x64,0x44,0x72,0x61,0x67,0x54,0x68,0x72,0x65,0x73,0x68,0x6f,0x6c,0x64,0x00,0x00,0x00,0x00,0x08,0x00,0x00,0x00,0x01,0x00,0x14,0x00,0x47,0x74,0x6b,0x2f,0x44,0x65,0x63,0x6f,0x72,0x61,0x74,0x69,0x6f,0x6e,0x4c,0x61,0x79,0x6f,0x75,0x74,0x00,0x00,0x00,0x00,0x1c,0x00,0x00,0x00,0x6d,0x65,0x6e,0x75,0x3a,0x6d,0x69,0x6e,0x69,0x6d,0x69,0x7a,0x65,0x2c,0x6d,0x61,0x78,0x69,0x6d,0x69,0x7a,0x65,0x2c,0x63,0x6c,0x6f,0x73,0x65,0x00,0x00,0x1d,0x00,0x4e,0x65,0x74,0x2f,0x45,0x6e,0x61,0x62,0x6c,0x65,0x49,0x6e,0x70,0x75,0x74,0x46,0x65,0x65,0x64,0x62,0x61,0x63,0x6b,0x53,0x6f,0x75,0x6e,0x64,0x73,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x17,0x00,0x47,0x64,0x6b,0x2f,0x57,0x69,0x6e,0x64,0x6f,0x77,0x53,0x63,0x61,0x6c,0x69,0x6e,0x67,0x46,0x61,0x63,0x74,0x6f,0x72,0x00,0x00,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x01,0x00,0x0d,0x00,0x47,0x74,0x6b,0x2f,0x49,0x63,0x6f,0x6e,0x53,0x69,0x7a,0x65,0x73,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x10,0x00,0x00,0x00,0x67,0x74,0x6b,0x2d,0x62,0x75,0x74,0x74,0x6f,0x6e,0x3d,0x31,0x36,0x2c,0x31,0x36,0x00,0x00,0x0e,0x00,0x47,0x74,0x6b,0x2f,0x4d,0x65,0x6e,0x75,0x49,0x6d,0x61,0x67,0x65,0x73,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x00,0x00,0x00 diff --git a/app/vendor/rune/vendor/winit/src/platform_impl/linux/x11/util/client_msg.rs b/app/vendor/rune/vendor/winit/src/platform_impl/linux/x11/util/client_msg.rs new file mode 100644 index 0000000..cf55177 --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/platform_impl/linux/x11/util/client_msg.rs @@ -0,0 +1,31 @@ +use super::*; +use x11rb::x11_utils::Serialize; + +impl XConnection { + pub fn send_client_msg( + &self, + window: xproto::Window, // The window this is "about"; not necessarily this window + target_window: xproto::Window, // The window we're sending to + message_type: xproto::Atom, + event_mask: Option<xproto::EventMask>, + data: impl Into<xproto::ClientMessageData>, + ) -> Result<VoidCookie<'_>, X11Error> { + let event = xproto::ClientMessageEvent { + response_type: xproto::CLIENT_MESSAGE_EVENT, + window, + format: 32, + data: data.into(), + sequence: 0, + type_: message_type, + }; + + self.xcb_connection() + .send_event( + false, + target_window, + event_mask.unwrap_or(xproto::EventMask::NO_EVENT), + event.serialize(), + ) + .map_err(Into::into) + } +} diff --git a/app/vendor/rune/vendor/winit/src/platform_impl/linux/x11/util/cookie.rs b/app/vendor/rune/vendor/winit/src/platform_impl/linux/x11/util/cookie.rs new file mode 100644 index 0000000..ccdfa8c --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/platform_impl/linux/x11/util/cookie.rs @@ -0,0 +1,55 @@ +use std::ffi::c_int; +use std::sync::Arc; + +use x11_dl::xlib::{self, XEvent, XGenericEventCookie}; + +use crate::platform_impl::x11::XConnection; + +/// XEvents of type GenericEvent store their actual data in an XGenericEventCookie data structure. +/// This is a wrapper to extract the cookie from a GenericEvent XEvent and release the cookie data +/// once it has been processed +pub struct GenericEventCookie { + cookie: XGenericEventCookie, + xconn: Arc<XConnection>, +} + +impl GenericEventCookie { + pub fn from_event(xconn: Arc<XConnection>, event: XEvent) -> Option<GenericEventCookie> { + unsafe { + let mut cookie: XGenericEventCookie = From::from(event); + if (xconn.xlib.XGetEventData)(xconn.display, &mut cookie) == xlib::True { + Some(GenericEventCookie { cookie, xconn }) + } else { + None + } + } + } + + #[inline] + pub fn extension(&self) -> u8 { + self.cookie.extension as u8 + } + + #[inline] + pub fn evtype(&self) -> c_int { + self.cookie.evtype + } + + /// Borrow inner event data as `&T`. + /// + /// ## SAFETY + /// + /// The caller must ensure that the event has the `T` inside of it. + #[inline] + pub unsafe fn as_event<T>(&self) -> &T { + unsafe { &*(self.cookie.data as *const _) } + } +} + +impl Drop for GenericEventCookie { + fn drop(&mut self) { + unsafe { + (self.xconn.xlib.XFreeEventData)(self.xconn.display, &mut self.cookie); + } + } +} diff --git a/app/vendor/rune/vendor/winit/src/platform_impl/linux/x11/util/cursor.rs b/app/vendor/rune/vendor/winit/src/platform_impl/linux/x11/util/cursor.rs new file mode 100644 index 0000000..169748d --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/platform_impl/linux/x11/util/cursor.rs @@ -0,0 +1,174 @@ +use std::ffi::CString; +use std::hash::{Hash, Hasher}; +use std::sync::Arc; +use std::{iter, slice}; + +use x11rb::connection::Connection; + +use crate::platform_impl::PlatformCustomCursorSource; +use crate::window::CursorIcon; + +use super::super::ActiveEventLoop; +use super::*; + +impl XConnection { + pub fn set_cursor_icon(&self, window: xproto::Window, cursor: Option<CursorIcon>) { + let cursor = *self + .cursor_cache + .lock() + .unwrap() + .entry(cursor) + .or_insert_with(|| self.get_cursor(cursor)); + + self.update_cursor(window, cursor).expect("Failed to set cursor"); + } + + pub(crate) fn set_custom_cursor(&self, window: xproto::Window, cursor: &CustomCursor) { + self.update_cursor(window, cursor.inner.cursor).expect("Failed to set cursor"); + } + + fn create_empty_cursor(&self) -> ffi::Cursor { + let data = 0; + let pixmap = unsafe { + let screen = (self.xlib.XDefaultScreen)(self.display); + let window = (self.xlib.XRootWindow)(self.display, screen); + (self.xlib.XCreateBitmapFromData)(self.display, window, &data, 1, 1) + }; + + if pixmap == 0 { + panic!("failed to allocate pixmap for cursor"); + } + + unsafe { + // We don't care about this color, since it only fills bytes + // in the pixmap which are not 0 in the mask. + let mut dummy_color = MaybeUninit::uninit(); + let cursor = (self.xlib.XCreatePixmapCursor)( + self.display, + pixmap, + pixmap, + dummy_color.as_mut_ptr(), + dummy_color.as_mut_ptr(), + 0, + 0, + ); + (self.xlib.XFreePixmap)(self.display, pixmap); + + cursor + } + } + + fn get_cursor(&self, cursor: Option<CursorIcon>) -> ffi::Cursor { + let cursor = match cursor { + Some(cursor) => cursor, + None => return self.create_empty_cursor(), + }; + + let mut xcursor = 0; + for &name in iter::once(&cursor.name()).chain(cursor.alt_names().iter()) { + let name = CString::new(name).unwrap(); + xcursor = unsafe { + (self.xcursor.XcursorLibraryLoadCursor)( + self.display, + name.as_ptr() as *const c_char, + ) + }; + + if xcursor != 0 { + break; + } + } + + xcursor + } + + fn update_cursor(&self, window: xproto::Window, cursor: ffi::Cursor) -> Result<(), X11Error> { + self.xcb_connection() + .change_window_attributes( + window, + &xproto::ChangeWindowAttributesAux::new().cursor(cursor as xproto::Cursor), + )? + .ignore_error(); + + self.xcb_connection().flush()?; + Ok(()) + } +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum SelectedCursor { + Custom(CustomCursor), + Named(CursorIcon), +} + +#[derive(Debug, Clone)] +pub struct CustomCursor { + inner: Arc<CustomCursorInner>, +} + +impl Hash for CustomCursor { + fn hash<H: Hasher>(&self, state: &mut H) { + Arc::as_ptr(&self.inner).hash(state); + } +} + +impl PartialEq for CustomCursor { + fn eq(&self, other: &Self) -> bool { + Arc::ptr_eq(&self.inner, &other.inner) + } +} + +impl Eq for CustomCursor {} + +impl CustomCursor { + pub(crate) fn new( + event_loop: &ActiveEventLoop, + cursor: PlatformCustomCursorSource, + ) -> CustomCursor { + unsafe { + let ximage = (event_loop.xconn.xcursor.XcursorImageCreate)( + cursor.0.width as i32, + cursor.0.height as i32, + ); + if ximage.is_null() { + panic!("failed to allocate cursor image"); + } + (*ximage).xhot = cursor.0.hotspot_x as u32; + (*ximage).yhot = cursor.0.hotspot_y as u32; + (*ximage).delay = 0; + + let dst = slice::from_raw_parts_mut((*ximage).pixels, cursor.0.rgba.len() / 4); + for (dst, chunk) in dst.iter_mut().zip(cursor.0.rgba.chunks_exact(4)) { + *dst = (chunk[0] as u32) << 16 + | (chunk[1] as u32) << 8 + | (chunk[2] as u32) + | (chunk[3] as u32) << 24; + } + + let cursor = + (event_loop.xconn.xcursor.XcursorImageLoadCursor)(event_loop.xconn.display, ximage); + (event_loop.xconn.xcursor.XcursorImageDestroy)(ximage); + Self { inner: Arc::new(CustomCursorInner { xconn: event_loop.xconn.clone(), cursor }) } + } + } +} + +#[derive(Debug)] +struct CustomCursorInner { + xconn: Arc<XConnection>, + cursor: ffi::Cursor, +} + +impl Drop for CustomCursorInner { + fn drop(&mut self) { + unsafe { + (self.xconn.xlib.XFreeCursor)(self.xconn.display, self.cursor); + } + } +} + +impl Default for SelectedCursor { + fn default() -> Self { + SelectedCursor::Named(Default::default()) + } +} diff --git a/app/vendor/rune/vendor/winit/src/platform_impl/linux/x11/util/geometry.rs b/app/vendor/rune/vendor/winit/src/platform_impl/linux/x11/util/geometry.rs new file mode 100644 index 0000000..63ec564 --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/platform_impl/linux/x11/util/geometry.rs @@ -0,0 +1,265 @@ +use std::cmp; + +use super::*; + +// Friendly neighborhood axis-aligned rectangle +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct AaRect { + x: i64, + y: i64, + width: i64, + height: i64, +} + +impl AaRect { + pub fn new((x, y): (i32, i32), (width, height): (u32, u32)) -> Self { + let (x, y) = (x as i64, y as i64); + let (width, height) = (width as i64, height as i64); + AaRect { x, y, width, height } + } + + pub fn contains_point(&self, x: i64, y: i64) -> bool { + x >= self.x && x <= self.x + self.width && y >= self.y && y <= self.y + self.height + } + + pub fn get_overlapping_area(&self, other: &Self) -> i64 { + let x_overlap = cmp::max( + 0, + cmp::min(self.x + self.width, other.x + other.width) - cmp::max(self.x, other.x), + ); + let y_overlap = cmp::max( + 0, + cmp::min(self.y + self.height, other.y + other.height) - cmp::max(self.y, other.y), + ); + x_overlap * y_overlap + } +} + +#[derive(Debug, Clone)] +pub struct FrameExtents { + pub left: u32, + pub right: u32, + pub top: u32, + pub bottom: u32, +} + +impl FrameExtents { + pub fn new(left: u32, right: u32, top: u32, bottom: u32) -> Self { + FrameExtents { left, right, top, bottom } + } + + pub fn from_border(border: u32) -> Self { + Self::new(border, border, border, border) + } +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum FrameExtentsHeuristicPath { + Supported, + UnsupportedNested, + UnsupportedBordered, +} + +#[derive(Debug, Clone)] +pub struct FrameExtentsHeuristic { + pub frame_extents: FrameExtents, + pub heuristic_path: FrameExtentsHeuristicPath, +} + +impl FrameExtentsHeuristic { + pub fn inner_pos_to_outer(&self, x: i32, y: i32) -> (i32, i32) { + use self::FrameExtentsHeuristicPath::*; + if self.heuristic_path != UnsupportedBordered { + (x - self.frame_extents.left as i32, y - self.frame_extents.top as i32) + } else { + (x, y) + } + } + + pub fn inner_size_to_outer(&self, width: u32, height: u32) -> (u32, u32) { + ( + width.saturating_add( + self.frame_extents.left.saturating_add(self.frame_extents.right) as _ + ), + height.saturating_add( + self.frame_extents.top.saturating_add(self.frame_extents.bottom) as _ + ), + ) + } +} + +impl XConnection { + // This is adequate for inner_position + pub fn translate_coords( + &self, + window: xproto::Window, + root: xproto::Window, + ) -> Result<xproto::TranslateCoordinatesReply, X11Error> { + self.xcb_connection().translate_coordinates(window, root, 0, 0)?.reply().map_err(Into::into) + } + + // This is adequate for inner_size + pub fn get_geometry( + &self, + window: xproto::Window, + ) -> Result<xproto::GetGeometryReply, X11Error> { + self.xcb_connection().get_geometry(window)?.reply().map_err(Into::into) + } + + fn get_frame_extents(&self, window: xproto::Window) -> Option<FrameExtents> { + let atoms = self.atoms(); + let extents_atom = atoms[_NET_FRAME_EXTENTS]; + + if !hint_is_supported(extents_atom) { + return None; + } + + // Of the WMs tested, xmonad, i3, dwm, IceWM (1.3.x and earlier), and blackbox don't + // support this. As this is part of EWMH (Extended Window Manager Hints), it's likely to + // be unsupported by many smaller WMs. + let extents: Option<Vec<u32>> = self + .get_property(window, extents_atom, xproto::Atom::from(xproto::AtomEnum::CARDINAL)) + .ok(); + + extents.and_then(|extents| { + if extents.len() >= 4 { + Some(FrameExtents { + left: extents[0], + right: extents[1], + top: extents[2], + bottom: extents[3], + }) + } else { + None + } + }) + } + + pub fn is_top_level(&self, window: xproto::Window, root: xproto::Window) -> Option<bool> { + let atoms = self.atoms(); + let client_list_atom = atoms[_NET_CLIENT_LIST]; + + if !hint_is_supported(client_list_atom) { + return None; + } + + let client_list: Option<Vec<xproto::Window>> = self + .get_property(root, client_list_atom, xproto::Atom::from(xproto::AtomEnum::WINDOW)) + .ok(); + + client_list.map(|client_list| client_list.contains(&(window as xproto::Window))) + } + + fn get_parent_window(&self, window: xproto::Window) -> Result<xproto::Window, X11Error> { + let parent = self.xcb_connection().query_tree(window)?.reply()?.parent; + Ok(parent) + } + + fn climb_hierarchy( + &self, + window: xproto::Window, + root: xproto::Window, + ) -> Result<xproto::Window, X11Error> { + let mut outer_window = window; + loop { + let candidate = self.get_parent_window(outer_window)?; + if candidate == root { + break; + } + outer_window = candidate; + } + Ok(outer_window) + } + + pub fn get_frame_extents_heuristic( + &self, + window: xproto::Window, + root: xproto::Window, + ) -> FrameExtentsHeuristic { + use self::FrameExtentsHeuristicPath::*; + + // Position relative to root window. + // With rare exceptions, this is the position of a nested window. Cases where the window + // isn't nested are outlined in the comments throughout this function, but in addition to + // that, fullscreen windows often aren't nested. + let (inner_y_rel_root, child) = { + let coords = self + .translate_coords(window, root) + .expect("Failed to translate window coordinates"); + (coords.dst_y, coords.child) + }; + + let (width, height, border) = { + let inner_geometry = + self.get_geometry(window).expect("Failed to get inner window geometry"); + (inner_geometry.width, inner_geometry.height, inner_geometry.border_width) + }; + + // The first condition is only false for un-nested windows, but isn't always false for + // un-nested windows. Mutter/Muffin/Budgie and Marco present a mysterious discrepancy: + // when y is on the range [0, 2] and if the window has been unfocused since being + // undecorated (or was undecorated upon construction), the first condition is true, + // requiring us to rely on the second condition. + let nested = !(window == child || self.is_top_level(child, root) == Some(true)); + + // Hopefully the WM supports EWMH, allowing us to get exact info on the window frames. + if let Some(mut frame_extents) = self.get_frame_extents(window) { + // Mutter/Muffin/Budgie and Marco preserve their decorated frame extents when + // decorations are disabled, but since the window becomes un-nested, it's easy to + // catch. + if !nested { + frame_extents = FrameExtents::new(0, 0, 0, 0); + } + + // The difference between the nested window's position and the outermost window's + // position is equivalent to the frame size. In most scenarios, this is equivalent to + // manually climbing the hierarchy as is done in the case below. Here's a list of + // known discrepancies: + // * Mutter/Muffin/Budgie gives decorated windows a margin of 9px (only 7px on top) in + // addition to a 1px semi-transparent border. The margin can be easily observed by + // using a screenshot tool to get a screenshot of a selected window, and is presumably + // used for drawing drop shadows. Getting window geometry information via + // hierarchy-climbing results in this margin being included in both the position and + // outer size, so a window positioned at (0, 0) would be reported as having a position + // (-10, -8). + // * Compiz has a drop shadow margin just like Mutter/Muffin/Budgie, though it's 10px on + // all sides, and there's no additional border. + // * Enlightenment otherwise gets a y position equivalent to inner_y_rel_root. Without + // decorations, there's no difference. This is presumably related to Enlightenment's + // fairly unique concept of window position; it interprets positions given to + // XMoveWindow as a client area position rather than a position of the overall window. + + FrameExtentsHeuristic { frame_extents, heuristic_path: Supported } + } else if nested { + // If the position value we have is for a nested window used as the client area, we'll + // just climb up the hierarchy and get the geometry of the outermost window we're + // nested in. + let outer_window = + self.climb_hierarchy(window, root).expect("Failed to climb window hierarchy"); + let (outer_y, outer_width, outer_height) = { + let outer_geometry = + self.get_geometry(outer_window).expect("Failed to get outer window geometry"); + (outer_geometry.y, outer_geometry.width, outer_geometry.height) + }; + + // Since we have the geometry of the outermost window and the geometry of the client + // area, we can figure out what's in between. + let diff_x = outer_width.saturating_sub(width) as u32; + let diff_y = outer_height.saturating_sub(height) as u32; + let offset_y = inner_y_rel_root.saturating_sub(outer_y) as u32; + + let left = diff_x / 2; + let right = left; + let top = offset_y; + let bottom = diff_y.saturating_sub(offset_y); + + let frame_extents = FrameExtents::new(left, right, top, bottom); + FrameExtentsHeuristic { frame_extents, heuristic_path: UnsupportedNested } + } else { + // This is the case for xmonad and dwm, AKA the only WMs tested that supplied a + // border value. This is convenient, since we can use it to get an accurate frame. + let frame_extents = FrameExtents::from_border(border.into()); + FrameExtentsHeuristic { frame_extents, heuristic_path: UnsupportedBordered } + } + } +} diff --git a/app/vendor/rune/vendor/winit/src/platform_impl/linux/x11/util/hint.rs b/app/vendor/rune/vendor/winit/src/platform_impl/linux/x11/util/hint.rs new file mode 100644 index 0000000..a31872d --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/platform_impl/linux/x11/util/hint.rs @@ -0,0 +1,169 @@ +use crate::platform::x11::WindowType; +use std::sync::Arc; + +use super::*; + +#[derive(Debug)] +#[allow(dead_code)] +pub enum StateOperation { + Remove = 0, // _NET_WM_STATE_REMOVE + Add = 1, // _NET_WM_STATE_ADD + Toggle = 2, // _NET_WM_STATE_TOGGLE +} + +impl From<bool> for StateOperation { + fn from(op: bool) -> Self { + if op { + StateOperation::Add + } else { + StateOperation::Remove + } + } +} + +impl WindowType { + pub(crate) fn as_atom(&self, xconn: &Arc<XConnection>) -> xproto::Atom { + use self::WindowType::*; + let atom_name = match *self { + Desktop => _NET_WM_WINDOW_TYPE_DESKTOP, + Dock => _NET_WM_WINDOW_TYPE_DOCK, + Toolbar => _NET_WM_WINDOW_TYPE_TOOLBAR, + Menu => _NET_WM_WINDOW_TYPE_MENU, + Utility => _NET_WM_WINDOW_TYPE_UTILITY, + Splash => _NET_WM_WINDOW_TYPE_SPLASH, + Dialog => _NET_WM_WINDOW_TYPE_DIALOG, + DropdownMenu => _NET_WM_WINDOW_TYPE_DROPDOWN_MENU, + PopupMenu => _NET_WM_WINDOW_TYPE_POPUP_MENU, + Tooltip => _NET_WM_WINDOW_TYPE_TOOLTIP, + Notification => _NET_WM_WINDOW_TYPE_NOTIFICATION, + Combo => _NET_WM_WINDOW_TYPE_COMBO, + Dnd => _NET_WM_WINDOW_TYPE_DND, + Normal => _NET_WM_WINDOW_TYPE_NORMAL, + }; + + let atoms = xconn.atoms(); + atoms[atom_name] + } +} + +pub struct MotifHints { + hints: MwmHints, +} + +struct MwmHints { + flags: u32, + functions: u32, + decorations: u32, + input_mode: u32, + status: u32, +} + +#[allow(dead_code)] +mod mwm { + // Motif WM hints are obsolete, but still widely supported. + // https://stackoverflow.com/a/1909708 + pub const MWM_HINTS_FUNCTIONS: u32 = 1 << 0; + pub const MWM_HINTS_DECORATIONS: u32 = 1 << 1; + + pub const MWM_FUNC_ALL: u32 = 1 << 0; + pub const MWM_FUNC_RESIZE: u32 = 1 << 1; + pub const MWM_FUNC_MOVE: u32 = 1 << 2; + pub const MWM_FUNC_MINIMIZE: u32 = 1 << 3; + pub const MWM_FUNC_MAXIMIZE: u32 = 1 << 4; + pub const MWM_FUNC_CLOSE: u32 = 1 << 5; +} + +impl MotifHints { + pub fn new() -> MotifHints { + MotifHints { + hints: MwmHints { flags: 0, functions: 0, decorations: 0, input_mode: 0, status: 0 }, + } + } + + pub fn set_decorations(&mut self, decorations: bool) { + self.hints.flags |= mwm::MWM_HINTS_DECORATIONS; + self.hints.decorations = decorations as u32; + } + + pub fn set_maximizable(&mut self, maximizable: bool) { + if maximizable { + self.add_func(mwm::MWM_FUNC_MAXIMIZE); + } else { + self.remove_func(mwm::MWM_FUNC_MAXIMIZE); + } + } + + fn add_func(&mut self, func: u32) { + if self.hints.flags & mwm::MWM_HINTS_FUNCTIONS != 0 { + if self.hints.functions & mwm::MWM_FUNC_ALL != 0 { + self.hints.functions &= !func; + } else { + self.hints.functions |= func; + } + } + } + + fn remove_func(&mut self, func: u32) { + if self.hints.flags & mwm::MWM_HINTS_FUNCTIONS == 0 { + self.hints.flags |= mwm::MWM_HINTS_FUNCTIONS; + self.hints.functions = mwm::MWM_FUNC_ALL; + } + + if self.hints.functions & mwm::MWM_FUNC_ALL != 0 { + self.hints.functions |= func; + } else { + self.hints.functions &= !func; + } + } +} + +impl Default for MotifHints { + fn default() -> Self { + Self::new() + } +} + +impl XConnection { + pub fn get_motif_hints(&self, window: xproto::Window) -> MotifHints { + let atoms = self.atoms(); + let motif_hints = atoms[_MOTIF_WM_HINTS]; + + let mut hints = MotifHints::new(); + + if let Ok(props) = self.get_property::<u32>(window, motif_hints, motif_hints) { + hints.hints.flags = props.first().cloned().unwrap_or(0); + hints.hints.functions = props.get(1).cloned().unwrap_or(0); + hints.hints.decorations = props.get(2).cloned().unwrap_or(0); + hints.hints.input_mode = props.get(3).cloned().unwrap_or(0); + hints.hints.status = props.get(4).cloned().unwrap_or(0); + } + + hints + } + + #[allow(clippy::unnecessary_cast)] + pub fn set_motif_hints( + &self, + window: xproto::Window, + hints: &MotifHints, + ) -> Result<VoidCookie<'_>, X11Error> { + let atoms = self.atoms(); + let motif_hints = atoms[_MOTIF_WM_HINTS]; + + let hints_data: [u32; 5] = [ + hints.hints.flags as u32, + hints.hints.functions as u32, + hints.hints.decorations as u32, + hints.hints.input_mode as u32, + hints.hints.status as u32, + ]; + + self.change_property( + window, + motif_hints, + motif_hints, + xproto::PropMode::REPLACE, + &hints_data, + ) + } +} diff --git a/app/vendor/rune/vendor/winit/src/platform_impl/linux/x11/util/icon.rs b/app/vendor/rune/vendor/winit/src/platform_impl/linux/x11/util/icon.rs new file mode 100644 index 0000000..07b5fee --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/platform_impl/linux/x11/util/icon.rs @@ -0,0 +1,36 @@ +#![allow(clippy::assertions_on_constants)] + +use super::*; +use crate::icon::{Pixel, RgbaIcon, PIXEL_SIZE}; + +impl Pixel { + pub fn to_packed_argb(&self) -> Cardinal { + let mut cardinal = 0; + assert!(CARDINAL_SIZE >= PIXEL_SIZE); + let as_bytes = &mut cardinal as *mut _ as *mut u8; + unsafe { + *as_bytes.offset(0) = self.b; + *as_bytes.offset(1) = self.g; + *as_bytes.offset(2) = self.r; + *as_bytes.offset(3) = self.a; + } + cardinal + } +} + +impl RgbaIcon { + pub(crate) fn to_cardinals(&self) -> Vec<Cardinal> { + assert_eq!(self.rgba.len() % PIXEL_SIZE, 0); + let pixel_count = self.rgba.len() / PIXEL_SIZE; + assert_eq!(pixel_count, (self.width * self.height) as usize); + let mut data = Vec::with_capacity(pixel_count); + data.push(self.width as Cardinal); + data.push(self.height as Cardinal); + let pixels = self.rgba.as_ptr() as *const Pixel; + for pixel_index in 0..pixel_count { + let pixel = unsafe { &*pixels.add(pixel_index) }; + data.push(pixel.to_packed_argb()); + } + data + } +} diff --git a/app/vendor/rune/vendor/winit/src/platform_impl/linux/x11/util/input.rs b/app/vendor/rune/vendor/winit/src/platform_impl/linux/x11/util/input.rs new file mode 100644 index 0000000..37d21d1 --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/platform_impl/linux/x11/util/input.rs @@ -0,0 +1,106 @@ +use std::{slice, str}; +use x11rb::protocol::xinput::{self, ConnectionExt as _}; +use x11rb::protocol::xkb; + +use super::*; + +pub const VIRTUAL_CORE_POINTER: u16 = 2; +pub const VIRTUAL_CORE_KEYBOARD: u16 = 3; + +// A base buffer size of 1kB uses a negligible amount of RAM while preventing us from having to +// re-allocate (and make another round-trip) in the *vast* majority of cases. +// To test if `lookup_utf8` works correctly, set this to 1. +const TEXT_BUFFER_SIZE: usize = 1024; + +impl XConnection { + pub fn select_xinput_events( + &self, + window: xproto::Window, + device_id: u16, + mask: xinput::XIEventMask, + ) -> Result<VoidCookie<'_>, X11Error> { + self.xcb_connection() + .xinput_xi_select_events(window, &[xinput::EventMask { + deviceid: device_id, + mask: vec![mask], + }]) + .map_err(Into::into) + } + + pub fn select_xkb_events( + &self, + device_id: xkb::DeviceSpec, + mask: xkb::EventType, + ) -> Result<bool, X11Error> { + let mask = u16::from(mask) as _; + let status = + unsafe { (self.xlib.XkbSelectEvents)(self.display, device_id as _, mask, mask) }; + + if status == ffi::True { + self.flush_requests()?; + Ok(true) + } else { + tracing::error!("Could not select XKB events: The XKB extension is not initialized!"); + Ok(false) + } + } + + pub fn query_pointer( + &self, + window: xproto::Window, + device_id: u16, + ) -> Result<xinput::XIQueryPointerReply, X11Error> { + self.xcb_connection() + .xinput_xi_query_pointer(window, device_id)? + .reply() + .map_err(Into::into) + } + + fn lookup_utf8_inner( + &self, + ic: ffi::XIC, + key_event: &mut ffi::XKeyEvent, + buffer: *mut u8, + size: usize, + ) -> (ffi::KeySym, ffi::Status, c_int) { + let mut keysym: ffi::KeySym = 0; + let mut status: ffi::Status = 0; + let count = unsafe { + (self.xlib.Xutf8LookupString)( + ic, + key_event, + buffer as *mut c_char, + size as c_int, + &mut keysym, + &mut status, + ) + }; + (keysym, status, count) + } + + pub fn lookup_utf8(&self, ic: ffi::XIC, key_event: &mut ffi::XKeyEvent) -> String { + // `assume_init` is safe here because the array consists of `MaybeUninit` values, + // which do not require initialization. + let mut buffer: [MaybeUninit<u8>; TEXT_BUFFER_SIZE] = + unsafe { MaybeUninit::uninit().assume_init() }; + // If the buffer overflows, we'll make a new one on the heap. + let mut vec; + + let (_, status, count) = + self.lookup_utf8_inner(ic, key_event, buffer.as_mut_ptr() as *mut u8, buffer.len()); + + let bytes = if status == ffi::XBufferOverflow { + vec = Vec::with_capacity(count as usize); + let (_, _, new_count) = + self.lookup_utf8_inner(ic, key_event, vec.as_mut_ptr(), vec.capacity()); + debug_assert_eq!(count, new_count); + + unsafe { vec.set_len(count as usize) }; + &vec[..count as usize] + } else { + unsafe { slice::from_raw_parts(buffer.as_ptr() as *const u8, count as usize) } + }; + + str::from_utf8(bytes).unwrap_or("").to_string() + } +} diff --git a/app/vendor/rune/vendor/winit/src/platform_impl/linux/x11/util/keys.rs b/app/vendor/rune/vendor/winit/src/platform_impl/linux/x11/util/keys.rs new file mode 100644 index 0000000..a6ad291 --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/platform_impl/linux/x11/util/keys.rs @@ -0,0 +1,75 @@ +use std::iter::Enumerate; +use std::slice::Iter; + +use super::*; + +pub struct Keymap { + keys: [u8; 32], +} + +pub struct KeymapIter<'a> { + iter: Enumerate<Iter<'a, u8>>, + index: usize, + item: Option<u8>, +} + +impl Keymap { + pub fn iter(&self) -> KeymapIter<'_> { + KeymapIter { iter: self.keys.iter().enumerate(), index: 0, item: None } + } +} + +impl<'a> IntoIterator for &'a Keymap { + type IntoIter = KeymapIter<'a>; + type Item = ffi::KeyCode; + + fn into_iter(self) -> Self::IntoIter { + self.iter() + } +} + +impl Iterator for KeymapIter<'_> { + type Item = ffi::KeyCode; + + fn next(&mut self) -> Option<ffi::KeyCode> { + if self.item.is_none() { + for (index, &item) in self.iter.by_ref() { + if item != 0 { + self.index = index; + self.item = Some(item); + break; + } + } + } + + self.item.take().map(|item| { + debug_assert!(item != 0); + + let bit = first_bit(item); + + if item != bit { + // Remove the first bit; save the rest for further iterations + self.item = Some(item ^ bit); + } + + let shift = bit.trailing_zeros() + (self.index * 8) as u32; + shift as ffi::KeyCode + }) + } +} + +impl XConnection { + pub fn query_keymap(&self) -> Keymap { + let mut keys = [0; 32]; + + unsafe { + (self.xlib.XQueryKeymap)(self.display, keys.as_mut_ptr() as *mut c_char); + } + + Keymap { keys } + } +} + +fn first_bit(b: u8) -> u8 { + 1 << b.trailing_zeros() +} diff --git a/app/vendor/rune/vendor/winit/src/platform_impl/linux/x11/util/memory.rs b/app/vendor/rune/vendor/winit/src/platform_impl/linux/x11/util/memory.rs new file mode 100644 index 0000000..4e052a7 --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/platform_impl/linux/x11/util/memory.rs @@ -0,0 +1,42 @@ +use std::ops::{Deref, DerefMut}; + +use super::*; + +pub(crate) struct XSmartPointer<'a, T> { + xconn: &'a XConnection, + pub ptr: *mut T, +} + +impl<'a, T> XSmartPointer<'a, T> { + // You're responsible for only passing things to this that should be XFree'd. + // Returns None if ptr is null. + pub fn new(xconn: &'a XConnection, ptr: *mut T) -> Option<Self> { + if !ptr.is_null() { + Some(XSmartPointer { xconn, ptr }) + } else { + None + } + } +} + +impl<T> Deref for XSmartPointer<'_, T> { + type Target = T; + + fn deref(&self) -> &T { + unsafe { &*self.ptr } + } +} + +impl<T> DerefMut for XSmartPointer<'_, T> { + fn deref_mut(&mut self) -> &mut T { + unsafe { &mut *self.ptr } + } +} + +impl<T> Drop for XSmartPointer<'_, T> { + fn drop(&mut self) { + unsafe { + (self.xconn.xlib.XFree)(self.ptr as *mut _); + } + } +} diff --git a/app/vendor/rune/vendor/winit/src/platform_impl/linux/x11/util/mod.rs b/app/vendor/rune/vendor/winit/src/platform_impl/linux/x11/util/mod.rs new file mode 100644 index 0000000..55e6c2d --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/platform_impl/linux/x11/util/mod.rs @@ -0,0 +1,77 @@ +// Welcome to the util module, where we try to keep you from shooting yourself in the foot. +// *results may vary + +use std::mem::{self, MaybeUninit}; +use std::ops::BitAnd; +use std::os::raw::*; + +mod client_msg; +pub mod cookie; +mod cursor; +mod geometry; +mod hint; +mod icon; +mod input; +pub mod keys; +pub(crate) mod memory; +mod mouse; +mod randr; +mod window_property; +mod wm; +mod xmodmap; + +pub use self::cursor::*; +pub use self::geometry::*; +pub use self::hint::*; +pub use self::input::*; +pub use self::mouse::*; +pub use self::window_property::*; +pub use self::wm::*; +pub use self::xmodmap::ModifierKeymap; + +use super::atoms::*; +use super::{ffi, VoidCookie, X11Error, XConnection, XError}; +use x11rb::protocol::xproto::{self, ConnectionExt as _}; + +pub fn maybe_change<T: PartialEq>(field: &mut Option<T>, value: T) -> bool { + let wrapped = Some(value); + if *field != wrapped { + *field = wrapped; + true + } else { + false + } +} + +pub fn has_flag<T>(bitset: T, flag: T) -> bool +where + T: Copy + PartialEq + BitAnd<T, Output = T>, +{ + bitset & flag == flag +} + +impl XConnection { + // This is important, so pay attention! + // Xlib has an output buffer, and tries to hide the async nature of X from you. + // This buffer contains the requests you make, and is flushed under various circumstances: + // 1. `XPending`, `XNextEvent`, and `XWindowEvent` flush "as needed" + // 2. `XFlush` explicitly flushes + // 3. `XSync` flushes and blocks until all requests are responded to + // 4. Calls that have a return dependent on a response (i.e. `XGetWindowProperty`) sync + // internally. When in doubt, check the X11 source; if a function calls `_XReply`, it flushes + // and waits. + // All util functions that abstract an async function will return a `Flusher`. + pub fn flush_requests(&self) -> Result<(), XError> { + unsafe { (self.xlib.XFlush)(self.display) }; + // println!("XFlush"); + // This isn't necessarily a useful time to check for errors (since our request hasn't + // necessarily been processed yet) + self.check_errors() + } + + pub fn sync_with_server(&self) -> Result<(), XError> { + unsafe { (self.xlib.XSync)(self.display, ffi::False) }; + // println!("XSync"); + self.check_errors() + } +} diff --git a/app/vendor/rune/vendor/winit/src/platform_impl/linux/x11/util/modifiers.rs b/app/vendor/rune/vendor/winit/src/platform_impl/linux/x11/util/modifiers.rs new file mode 100644 index 0000000..bb157e4 --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/platform_impl/linux/x11/util/modifiers.rs @@ -0,0 +1,187 @@ +use std::{collections::HashMap, slice}; + +use super::*; + +use crate::event::{ElementState, ModifiersState}; + +// Offsets within XModifierKeymap to each set of keycodes. +// We are only interested in Shift, Control, Alt, and Logo. +// +// There are 8 sets total. The order of keycode sets is: +// Shift, Lock, Control, Mod1 (Alt), Mod2, Mod3, Mod4 (Logo), Mod5 +// +// https://tronche.com/gui/x/xlib/input/XSetModifierMapping.html +const SHIFT_OFFSET: usize = 0; +const CONTROL_OFFSET: usize = 2; +const ALT_OFFSET: usize = 3; +const LOGO_OFFSET: usize = 6; +const NUM_MODS: usize = 8; + +#[derive(Copy, Clone, Debug, Eq, PartialEq)] +pub enum Modifier { + Alt, + Ctrl, + Shift, + Logo, +} + +#[derive(Debug, Default)] +pub(crate) struct ModifierKeymap { + // Maps keycodes to modifiers + keys: HashMap<ffi::KeyCode, Modifier>, +} + +#[derive(Clone, Debug, Default)] +pub(crate) struct ModifierKeyState { + // Contains currently pressed modifier keys and their corresponding modifiers + keys: HashMap<ffi::KeyCode, Modifier>, + state: ModifiersState, +} + +impl ModifierKeymap { + pub fn new() -> ModifierKeymap { + ModifierKeymap::default() + } + + pub fn get_modifier(&self, keycode: ffi::KeyCode) -> Option<Modifier> { + self.keys.get(&keycode).cloned() + } + + pub fn reset_from_x_connection(&mut self, xconn: &XConnection) { + { + let keymap = xconn.xcb_connection().get_modifier_mapping().expect("get_modifier_mapping failed").reply().expect("get_modifier_mapping failed"); + + if keymap.is_null() { + panic!("failed to allocate XModifierKeymap"); + } + + self.reset_from_x_keymap(&*keymap); + + (xconn.xlib.XFreeModifiermap)(keymap); + } + } + + pub fn reset_from_x_keymap(&mut self, keymap: &ffi::XModifierKeymap) { + let keys_per_mod = keymap.max_keypermod as usize; + + let keys = unsafe { + slice::from_raw_parts(keymap.modifiermap as *const _, keys_per_mod * NUM_MODS) + }; + + self.keys.clear(); + + self.read_x_keys(keys, SHIFT_OFFSET, keys_per_mod, Modifier::Shift); + self.read_x_keys(keys, CONTROL_OFFSET, keys_per_mod, Modifier::Ctrl); + self.read_x_keys(keys, ALT_OFFSET, keys_per_mod, Modifier::Alt); + self.read_x_keys(keys, LOGO_OFFSET, keys_per_mod, Modifier::Logo); + } + + fn read_x_keys( + &mut self, + keys: &[ffi::KeyCode], + offset: usize, + keys_per_mod: usize, + modifier: Modifier, + ) { + let start = offset * keys_per_mod; + let end = start + keys_per_mod; + + for &keycode in &keys[start..end] { + if keycode != 0 { + self.keys.insert(keycode, modifier); + } + } + } +} + +impl ModifierKeyState { + pub fn update_keymap(&mut self, mods: &ModifierKeymap) { + self.keys.retain(|k, v| { + if let Some(m) = mods.get_modifier(*k) { + *v = m; + true + } else { + false + } + }); + + self.reset_state(); + } + + pub fn update_state( + &mut self, + state: &ModifiersState, + except: Option<Modifier>, + ) -> Option<ModifiersState> { + let mut new_state = *state; + + match except { + Some(Modifier::Alt) => new_state.set(ModifiersState::ALT, self.state.alt()), + Some(Modifier::Ctrl) => new_state.set(ModifiersState::CTRL, self.state.ctrl()), + Some(Modifier::Shift) => new_state.set(ModifiersState::SHIFT, self.state.shift()), + Some(Modifier::Logo) => new_state.set(ModifiersState::LOGO, self.state.logo()), + None => (), + } + + if self.state == new_state { + None + } else { + self.keys.retain(|_k, v| get_modifier(&new_state, *v)); + self.state = new_state; + Some(new_state) + } + } + + pub fn modifiers(&self) -> ModifiersState { + self.state + } + + pub fn key_event(&mut self, state: ElementState, keycode: ffi::KeyCode, modifier: Modifier) { + match state { + ElementState::Pressed => self.key_press(keycode, modifier), + ElementState::Released => self.key_release(keycode), + } + } + + pub fn key_press(&mut self, keycode: ffi::KeyCode, modifier: Modifier) { + self.keys.insert(keycode, modifier); + + set_modifier(&mut self.state, modifier, true); + } + + pub fn key_release(&mut self, keycode: ffi::KeyCode) { + if let Some(modifier) = self.keys.remove(&keycode) { + if !self.keys.values().any(|&m| m == modifier) { + set_modifier(&mut self.state, modifier, false); + } + } + } + + fn reset_state(&mut self) { + let mut new_state = ModifiersState::default(); + + for &m in self.keys.values() { + set_modifier(&mut new_state, m, true); + } + + self.state = new_state; + } +} + +fn get_modifier(state: &ModifiersState, modifier: Modifier) -> bool { + match modifier { + Modifier::Alt => state.alt(), + Modifier::Ctrl => state.ctrl(), + Modifier::Shift => state.shift(), + Modifier::Logo => state.logo(), + } +} + +fn set_modifier(state: &mut ModifiersState, modifier: Modifier, value: bool) { + match modifier { + Modifier::Alt => state.set(ModifiersState::ALT, value), + Modifier::Ctrl => state.set(ModifiersState::CTRL, value), + Modifier::Shift => state.set(ModifiersState::SHIFT, value), + Modifier::Logo => state.set(ModifiersState::LOGO, value), + } +} diff --git a/app/vendor/rune/vendor/winit/src/platform_impl/linux/x11/util/mouse.rs b/app/vendor/rune/vendor/winit/src/platform_impl/linux/x11/util/mouse.rs new file mode 100644 index 0000000..e66a76c --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/platform_impl/linux/x11/util/mouse.rs @@ -0,0 +1,49 @@ +//! Utilities for handling mouse events. + +/// Recorded mouse delta designed to filter out noise. +pub struct Delta<T> { + x: T, + y: T, +} + +impl<T: Default> Default for Delta<T> { + fn default() -> Self { + Self { x: Default::default(), y: Default::default() } + } +} + +impl<T: Default> Delta<T> { + pub(crate) fn set_x(&mut self, x: T) { + self.x = x; + } + + pub(crate) fn set_y(&mut self, y: T) { + self.y = y; + } +} + +macro_rules! consume { + ($this:expr, $ty:ty) => {{ + let this = $this; + let (x, y) = match (this.x.abs() < <$ty>::EPSILON, this.y.abs() < <$ty>::EPSILON) { + (true, true) => return None, + (false, true) => (this.x, 0.0), + (true, false) => (0.0, this.y), + (false, false) => (this.x, this.y), + }; + + Some((x, y)) + }}; +} + +impl Delta<f32> { + pub(crate) fn consume(self) -> Option<(f32, f32)> { + consume!(self, f32) + } +} + +impl Delta<f64> { + pub(crate) fn consume(self) -> Option<(f64, f64)> { + consume!(self, f64) + } +} diff --git a/app/vendor/rune/vendor/winit/src/platform_impl/linux/x11/util/randr.rs b/app/vendor/rune/vendor/winit/src/platform_impl/linux/x11/util/randr.rs new file mode 100644 index 0000000..d10c97e --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/platform_impl/linux/x11/util/randr.rs @@ -0,0 +1,186 @@ +use std::str::FromStr; +use std::{env, str}; + +use super::*; +use crate::dpi::validate_scale_factor; +use crate::platform_impl::platform::x11::{monitor, VideoModeHandle}; + +use tracing::warn; +use x11rb::protocol::randr::{self, ConnectionExt as _}; + +/// Represents values of `WINIT_HIDPI_FACTOR`. +pub enum EnvVarDPI { + Randr, + Scale(f64), + NotSet, +} + +pub fn calc_dpi_factor( + (width_px, height_px): (u32, u32), + (width_mm, height_mm): (u64, u64), +) -> f64 { + // See http://xpra.org/trac/ticket/728 for more information. + if width_mm == 0 || height_mm == 0 { + warn!("XRandR reported that the display's 0mm in size, which is certifiably insane"); + return 1.0; + } + + let ppmm = ((width_px as f64 * height_px as f64) / (width_mm as f64 * height_mm as f64)).sqrt(); + // Quantize 1/12 step size + let dpi_factor = ((ppmm * (12.0 * 25.4 / 96.0)).round() / 12.0).max(1.0); + assert!(validate_scale_factor(dpi_factor)); + if dpi_factor <= 20. { + dpi_factor + } else { + 1. + } +} + +impl XConnection { + // Retrieve DPI from Xft.dpi property + pub fn get_xft_dpi(&self) -> Option<f64> { + // Try to get it from XSETTINGS first. + if let Some(xsettings_screen) = self.xsettings_screen() { + match self.xsettings_dpi(xsettings_screen) { + Ok(Some(dpi)) => return Some(dpi), + Ok(None) => {}, + Err(err) => { + tracing::warn!("failed to fetch XSettings: {err}"); + }, + } + } + + self.database().get_string("Xft.dpi", "").and_then(|s| f64::from_str(s).ok()) + } + + pub fn get_output_info( + &self, + resources: &monitor::ScreenResources, + crtc: &randr::GetCrtcInfoReply, + ) -> Option<(String, f64, Vec<VideoModeHandle>)> { + let output_info = match self + .xcb_connection() + .randr_get_output_info(crtc.outputs[0], x11rb::CURRENT_TIME) + .map_err(X11Error::from) + .and_then(|r| r.reply().map_err(X11Error::from)) + { + Ok(output_info) => output_info, + Err(err) => { + warn!("Failed to get output info: {:?}", err); + return None; + }, + }; + + let bit_depth = self.default_root().root_depth; + let output_modes = &output_info.modes; + let resource_modes = resources.modes(); + + let modes = resource_modes + .iter() + // XRROutputInfo contains an array of mode ids that correspond to + // modes in the array in XRRScreenResources + .filter(|x| output_modes.contains(&x.id)) + .map(|mode| { + VideoModeHandle { + size: (mode.width.into(), mode.height.into()), + refresh_rate_millihertz: monitor::mode_refresh_rate_millihertz(mode) + .unwrap_or(0), + bit_depth: bit_depth as u16, + native_mode: mode.id, + // This is populated in `MonitorHandle::video_modes` as the + // video mode is returned to the user + monitor: None, + } + }) + .collect(); + + let name = match str::from_utf8(&output_info.name) { + Ok(name) => name.to_owned(), + Err(err) => { + warn!("Failed to get output name: {:?}", err); + return None; + }, + }; + // Override DPI if `WINIT_X11_SCALE_FACTOR` variable is set + let deprecated_dpi_override = env::var("WINIT_HIDPI_FACTOR").ok(); + if deprecated_dpi_override.is_some() { + warn!( + "The WINIT_HIDPI_FACTOR environment variable is deprecated; use \ + WINIT_X11_SCALE_FACTOR" + ) + } + let dpi_env = env::var("WINIT_X11_SCALE_FACTOR").ok().map_or_else( + || EnvVarDPI::NotSet, + |var| { + if var.to_lowercase() == "randr" { + EnvVarDPI::Randr + } else if let Ok(dpi) = f64::from_str(&var) { + EnvVarDPI::Scale(dpi) + } else if var.is_empty() { + EnvVarDPI::NotSet + } else { + panic!( + "`WINIT_X11_SCALE_FACTOR` invalid; DPI factors must be either normal \ + floats greater than 0, or `randr`. Got `{var}`" + ); + } + }, + ); + + let scale_factor = match dpi_env { + EnvVarDPI::Randr => calc_dpi_factor( + (crtc.width.into(), crtc.height.into()), + (output_info.mm_width as _, output_info.mm_height as _), + ), + EnvVarDPI::Scale(dpi_override) => { + if !validate_scale_factor(dpi_override) { + panic!( + "`WINIT_X11_SCALE_FACTOR` invalid; DPI factors must be either normal \ + floats greater than 0, or `randr`. Got `{dpi_override}`", + ); + } + dpi_override + }, + EnvVarDPI::NotSet => { + if let Some(dpi) = self.get_xft_dpi() { + dpi / 96. + } else { + calc_dpi_factor( + (crtc.width.into(), crtc.height.into()), + (output_info.mm_width as _, output_info.mm_height as _), + ) + } + }, + }; + + Some((name, scale_factor, modes)) + } + + pub fn set_crtc_config( + &self, + crtc_id: randr::Crtc, + mode_id: randr::Mode, + ) -> Result<(), X11Error> { + let crtc = + self.xcb_connection().randr_get_crtc_info(crtc_id, x11rb::CURRENT_TIME)?.reply()?; + + self.xcb_connection() + .randr_set_crtc_config( + crtc_id, + crtc.timestamp, + x11rb::CURRENT_TIME, + crtc.x, + crtc.y, + mode_id, + crtc.rotation, + &crtc.outputs, + )? + .reply() + .map(|_| ()) + .map_err(Into::into) + } + + pub fn get_crtc_mode(&self, crtc_id: randr::Crtc) -> Result<randr::Mode, X11Error> { + Ok(self.xcb_connection().randr_get_crtc_info(crtc_id, x11rb::CURRENT_TIME)?.reply()?.mode) + } +} diff --git a/app/vendor/rune/vendor/winit/src/platform_impl/linux/x11/util/window_property.rs b/app/vendor/rune/vendor/winit/src/platform_impl/linux/x11/util/window_property.rs new file mode 100644 index 0000000..0f4ca16 --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/platform_impl/linux/x11/util/window_property.rs @@ -0,0 +1,196 @@ +use std::error::Error; +use std::fmt; +use std::sync::Arc; + +use bytemuck::{NoUninit, Pod}; + +use x11rb::connection::Connection; +use x11rb::errors::ReplyError; + +use super::*; + +pub const CARDINAL_SIZE: usize = mem::size_of::<u32>(); + +pub type Cardinal = u32; + +#[derive(Debug, Clone)] +pub enum GetPropertyError { + X11rbError(Arc<ReplyError>), + TypeMismatch(xproto::Atom), + FormatMismatch(c_int), +} + +impl GetPropertyError { + pub fn is_actual_property_type(&self, t: xproto::Atom) -> bool { + if let GetPropertyError::TypeMismatch(actual_type) = *self { + actual_type == t + } else { + false + } + } +} + +impl<T: Into<ReplyError>> From<T> for GetPropertyError { + fn from(e: T) -> Self { + Self::X11rbError(Arc::new(e.into())) + } +} + +impl fmt::Display for GetPropertyError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + GetPropertyError::X11rbError(err) => err.fmt(f), + GetPropertyError::TypeMismatch(err) => write!(f, "type mismatch: {err}"), + GetPropertyError::FormatMismatch(err) => write!(f, "format mismatch: {err}"), + } + } +} + +impl Error for GetPropertyError {} + +// Number of 32-bit chunks to retrieve per iteration of get_property's inner loop. +// To test if `get_property` works correctly, set this to 1. +const PROPERTY_BUFFER_SIZE: u32 = 1024; // 4k of RAM ought to be enough for anyone! + +impl XConnection { + pub fn get_property<T: Pod>( + &self, + window: xproto::Window, + property: xproto::Atom, + property_type: xproto::Atom, + ) -> Result<Vec<T>, GetPropertyError> { + let mut iter = PropIterator::new(self.xcb_connection(), window, property, property_type); + let mut data = vec![]; + + loop { + if !iter.next_window(&mut data)? { + break; + } + } + + Ok(data) + } + + pub fn change_property<'a, T: NoUninit>( + &'a self, + window: xproto::Window, + property: xproto::Atom, + property_type: xproto::Atom, + mode: xproto::PropMode, + new_value: &[T], + ) -> Result<VoidCookie<'a>, X11Error> { + assert!([1usize, 2, 4].contains(&mem::size_of::<T>())); + self.xcb_connection() + .change_property( + mode, + window, + property, + property_type, + (mem::size_of::<T>() * 8) as u8, + new_value.len().try_into().expect("too many items for property"), + bytemuck::cast_slice::<T, u8>(new_value), + ) + .map_err(Into::into) + } +} + +/// An iterator over the "windows" of the property that we are fetching. +struct PropIterator<'a, C: ?Sized, T> { + /// Handle to the connection. + conn: &'a C, + + /// The window that we're fetching the property from. + window: xproto::Window, + + /// The property that we're fetching. + property: xproto::Atom, + + /// The type of the property that we're fetching. + property_type: xproto::Atom, + + /// The offset of the next window, in 32-bit chunks. + offset: u32, + + /// The format of the type. + format: u8, + + /// Keep a reference to `T`. + _phantom: std::marker::PhantomData<T>, +} + +impl<'a, C: Connection + ?Sized, T: Pod> PropIterator<'a, C, T> { + /// Create a new property iterator. + fn new( + conn: &'a C, + window: xproto::Window, + property: xproto::Atom, + property_type: xproto::Atom, + ) -> Self { + let format = match mem::size_of::<T>() { + 1 => 8, + 2 => 16, + 4 => 32, + _ => unreachable!(), + }; + + Self { + conn, + window, + property, + property_type, + offset: 0, + format, + _phantom: Default::default(), + } + } + + /// Get the next window and append it to `data`. + /// + /// Returns whether there are more windows to fetch. + fn next_window(&mut self, data: &mut Vec<T>) -> Result<bool, GetPropertyError> { + // Send the request and wait for the reply. + let reply = self + .conn + .get_property( + false, + self.window, + self.property, + self.property_type, + self.offset, + PROPERTY_BUFFER_SIZE, + )? + .reply()?; + + // Make sure that the reply is of the correct type. + if reply.type_ != self.property_type { + return Err(GetPropertyError::TypeMismatch(reply.type_)); + } + + // Make sure that the reply is of the correct format. + if reply.format != self.format { + return Err(GetPropertyError::FormatMismatch(reply.format.into())); + } + + // Append the data to the output. + if mem::size_of::<T>() == 1 && mem::align_of::<T>() == 1 { + // We can just do a bytewise append. + data.extend_from_slice(bytemuck::cast_slice(&reply.value)); + } else { + // Rust's borrowing and types system makes this a bit tricky. + // + // We need to make sure that the data is properly aligned. Unfortunately the best + // safe way to do this is to copy the data to another buffer and then append. + // + // TODO(notgull): It may be worth it to use `unsafe` to copy directly from + // `reply.value` to `data`; check if this is faster. Use benchmarks! + let old_len = data.len(); + let added_len = reply.value.len() / mem::size_of::<T>(); + data.resize(old_len + added_len, T::zeroed()); + bytemuck::cast_slice_mut::<T, u8>(&mut data[old_len..]).copy_from_slice(&reply.value); + } + + // Check `bytes_after` to see if there are more windows to fetch. + self.offset += PROPERTY_BUFFER_SIZE; + Ok(reply.bytes_after != 0) + } +} diff --git a/app/vendor/rune/vendor/winit/src/platform_impl/linux/x11/util/wm.rs b/app/vendor/rune/vendor/winit/src/platform_impl/linux/x11/util/wm.rs new file mode 100644 index 0000000..be70b83 --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/platform_impl/linux/x11/util/wm.rs @@ -0,0 +1,137 @@ +use std::sync::Mutex; + +use super::*; + +// https://specifications.freedesktop.org/wm-spec/latest/ar01s04.html#idm46075117309248 +pub const MOVERESIZE_TOPLEFT: isize = 0; +pub const MOVERESIZE_TOP: isize = 1; +pub const MOVERESIZE_TOPRIGHT: isize = 2; +pub const MOVERESIZE_RIGHT: isize = 3; +pub const MOVERESIZE_BOTTOMRIGHT: isize = 4; +pub const MOVERESIZE_BOTTOM: isize = 5; +pub const MOVERESIZE_BOTTOMLEFT: isize = 6; +pub const MOVERESIZE_LEFT: isize = 7; +pub const MOVERESIZE_MOVE: isize = 8; + +// This info is global to the window manager. +static SUPPORTED_HINTS: Mutex<Vec<xproto::Atom>> = Mutex::new(Vec::new()); +static WM_NAME: Mutex<Option<String>> = Mutex::new(None); + +pub fn hint_is_supported(hint: xproto::Atom) -> bool { + (*SUPPORTED_HINTS.lock().unwrap()).contains(&hint) +} + +pub fn wm_name_is_one_of(names: &[&str]) -> bool { + if let Some(ref name) = *WM_NAME.lock().unwrap() { + names.contains(&name.as_str()) + } else { + false + } +} + +impl XConnection { + pub fn update_cached_wm_info(&self, root: xproto::Window) { + *SUPPORTED_HINTS.lock().unwrap() = self.get_supported_hints(root); + *WM_NAME.lock().unwrap() = self.get_wm_name(root); + } + + fn get_supported_hints(&self, root: xproto::Window) -> Vec<xproto::Atom> { + let atoms = self.atoms(); + let supported_atom = atoms[_NET_SUPPORTED]; + self.get_property(root, supported_atom, xproto::Atom::from(xproto::AtomEnum::ATOM)) + .unwrap_or_else(|_| Vec::with_capacity(0)) + } + + #[allow(clippy::useless_conversion)] + fn get_wm_name(&self, root: xproto::Window) -> Option<String> { + let atoms = self.atoms(); + let check_atom = atoms[_NET_SUPPORTING_WM_CHECK]; + let wm_name_atom = atoms[_NET_WM_NAME]; + + // Mutter/Muffin/Budgie doesn't have _NET_SUPPORTING_WM_CHECK in its _NET_SUPPORTED, despite + // it working and being supported. This has been reported upstream, but due to the + // inavailability of time machines, we'll just try to get _NET_SUPPORTING_WM_CHECK + // regardless of whether or not the WM claims to support it. + // + // Blackbox 0.70 also incorrectly reports not supporting this, though that appears to be + // fixed in 0.72. + // if !supported_hints.contains(&check_atom) { + // return None; + // } + + // IceWM (1.3.x and earlier) doesn't report supporting _NET_WM_NAME, but will nonetheless + // provide us with a value for it. Note that the unofficial 1.4 fork of IceWM works fine. + // if !supported_hints.contains(&wm_name_atom) { + // return None; + // } + + // Of the WMs tested, only xmonad and dwm fail to provide a WM name. + + // Querying this property on the root window will give us the ID of a child window created + // by the WM. + let root_window_wm_check = { + let result = self.get_property::<xproto::Window>( + root, + check_atom, + xproto::Atom::from(xproto::AtomEnum::WINDOW), + ); + + let wm_check = result.ok().and_then(|wm_check| wm_check.first().cloned()); + + wm_check? + }; + + // Querying the same property on the child window we were given, we should get this child + // window's ID again. + let child_window_wm_check = { + let result = self.get_property::<xproto::Window>( + root_window_wm_check.into(), + check_atom, + xproto::Atom::from(xproto::AtomEnum::WINDOW), + ); + + let wm_check = result.ok().and_then(|wm_check| wm_check.first().cloned()); + + wm_check? + }; + + // These values should be the same. + if root_window_wm_check != child_window_wm_check { + return None; + } + + // All of that work gives us a window ID that we can get the WM name from. + let wm_name = { + let atoms = self.atoms(); + let utf8_string_atom = atoms[UTF8_STRING]; + + let result = + self.get_property(root_window_wm_check.into(), wm_name_atom, utf8_string_atom); + + // IceWM requires this. IceWM was also the only WM tested that returns a null-terminated + // string. For more fun trivia, IceWM is also unique in including version and uname + // information in this string (this means you'll have to be careful if you want to match + // against it, though). + // The unofficial 1.4 fork of IceWM still includes the extra details, but properly + // returns a UTF8 string that isn't null-terminated. + let no_utf8 = if let Err(ref err) = result { + err.is_actual_property_type(xproto::Atom::from(xproto::AtomEnum::STRING)) + } else { + false + }; + + if no_utf8 { + self.get_property( + root_window_wm_check.into(), + wm_name_atom, + xproto::Atom::from(xproto::AtomEnum::STRING), + ) + } else { + result + } + } + .ok(); + + wm_name.and_then(|wm_name| String::from_utf8(wm_name).ok()) + } +} diff --git a/app/vendor/rune/vendor/winit/src/platform_impl/linux/x11/util/xmodmap.rs b/app/vendor/rune/vendor/winit/src/platform_impl/linux/x11/util/xmodmap.rs new file mode 100644 index 0000000..565fd72 --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/platform_impl/linux/x11/util/xmodmap.rs @@ -0,0 +1,56 @@ +use std::collections::HashSet; +use std::slice; + +use x11_dl::xlib::{KeyCode as XKeyCode, XModifierKeymap}; + +// Offsets within XModifierKeymap to each set of keycodes. +// We are only interested in Shift, Control, Alt, and Logo. +// +// There are 8 sets total. The order of keycode sets is: +// Shift, Lock, Control, Mod1 (Alt), Mod2, Mod3, Mod4 (Logo), Mod5 +// +// https://tronche.com/gui/x/xlib/input/XSetModifierMapping.html +const NUM_MODS: usize = 8; + +/// Track which keys are modifiers, so we can properly replay them when they were filtered. +#[derive(Debug, Default)] +pub struct ModifierKeymap { + // Maps keycodes to modifiers + modifiers: HashSet<XKeyCode>, +} + +impl ModifierKeymap { + pub fn new() -> ModifierKeymap { + ModifierKeymap::default() + } + + pub fn is_modifier(&self, keycode: XKeyCode) -> bool { + self.modifiers.contains(&keycode) + } + + pub fn reload_from_x_connection(&mut self, xconn: &super::XConnection) { + unsafe { + let keymap = (xconn.xlib.XGetModifierMapping)(xconn.display); + + if keymap.is_null() { + return; + } + + self.reset_from_x_keymap(&*keymap); + + (xconn.xlib.XFreeModifiermap)(keymap); + } + } + + fn reset_from_x_keymap(&mut self, keymap: &XModifierKeymap) { + let keys_per_mod = keymap.max_keypermod as usize; + + let keys = unsafe { + slice::from_raw_parts(keymap.modifiermap as *const _, keys_per_mod * NUM_MODS) + }; + self.modifiers.clear(); + for key in keys { + self.modifiers.insert(*key); + } + } +} diff --git a/app/vendor/rune/vendor/winit/src/platform_impl/linux/x11/window.rs b/app/vendor/rune/vendor/winit/src/platform_impl/linux/x11/window.rs new file mode 100644 index 0000000..7e15d5f --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/platform_impl/linux/x11/window.rs @@ -0,0 +1,1938 @@ +use std::ffi::CString; +use std::mem::replace; +use std::os::raw::*; +use std::path::Path; +use std::sync::{Arc, Mutex, MutexGuard}; +use std::{cmp, env}; + +use tracing::{debug, info, warn}; +use x11rb::connection::Connection; +use x11rb::properties::{WmHints, WmSizeHints, WmSizeHintsSpecification}; +use x11rb::protocol::shape::{ConnectionExt as ShapeExt, SK, SO}; +use x11rb::protocol::xproto::{self, ClipOrdering, ConnectionExt as _, Rectangle}; +use x11rb::protocol::{randr, xinput}; + +use crate::cursor::{Cursor, CustomCursor as RootCustomCursor}; +use crate::dpi::{PhysicalPosition, PhysicalSize, Position, Size}; +use crate::error::{ExternalError, NotSupportedError, OsError as RootOsError}; +use crate::event::{Event, InnerSizeWriter, WindowEvent}; +use crate::event_loop::AsyncRequestSerial; +use crate::platform::x11::WindowType; +use crate::platform_impl::x11::atoms::*; +use crate::platform_impl::x11::{ + xinput_fp1616_to_float, MonitorHandle as X11MonitorHandle, WakeSender, X11Error, +}; +use crate::platform_impl::{ + Fullscreen, MonitorHandle as PlatformMonitorHandle, OsError, PlatformCustomCursor, + PlatformIcon, VideoModeHandle as PlatformVideoModeHandle, +}; +use crate::window::{ + CursorGrabMode, ImePurpose, ResizeDirection, Theme, UserAttentionType, WindowAttributes, + WindowButtons, WindowLevel, +}; + +use super::util::{self, SelectedCursor}; +use super::{ + ffi, ActiveEventLoop, CookieResultExt, ImeRequest, ImeSender, VoidCookie, WindowId, XConnection, +}; + +#[derive(Debug)] +pub struct SharedState { + pub cursor_pos: Option<(f64, f64)>, + pub size: Option<(u32, u32)>, + pub position: Option<(i32, i32)>, + pub inner_position: Option<(i32, i32)>, + pub inner_position_rel_parent: Option<(i32, i32)>, + pub is_resizable: bool, + pub is_decorated: bool, + pub last_monitor: X11MonitorHandle, + pub dpi_adjusted: Option<(u32, u32)>, + pub(crate) fullscreen: Option<Fullscreen>, + // Set when application calls `set_fullscreen` when window is not visible + pub(crate) desired_fullscreen: Option<Option<Fullscreen>>, + // Used to restore position after exiting fullscreen + pub restore_position: Option<(i32, i32)>, + // Used to restore video mode after exiting fullscreen + pub desktop_video_mode: Option<(randr::Crtc, randr::Mode)>, + pub frame_extents: Option<util::FrameExtentsHeuristic>, + pub min_inner_size: Option<Size>, + pub max_inner_size: Option<Size>, + pub resize_increments: Option<Size>, + pub base_size: Option<Size>, + pub visibility: Visibility, + pub has_focus: bool, + // Use `Option` to not apply hittest logic when it was never requested. + pub cursor_hittest: Option<bool>, +} + +#[derive(Copy, Clone, Debug, Eq, PartialEq)] +pub enum Visibility { + No, + Yes, + // Waiting for VisibilityNotify + YesWait, +} + +impl SharedState { + fn new(last_monitor: X11MonitorHandle, window_attributes: &WindowAttributes) -> Mutex<Self> { + let visibility = + if window_attributes.visible { Visibility::YesWait } else { Visibility::No }; + + Mutex::new(SharedState { + last_monitor, + visibility, + + is_resizable: window_attributes.resizable, + is_decorated: window_attributes.decorations, + cursor_pos: None, + size: None, + position: None, + inner_position: None, + inner_position_rel_parent: None, + dpi_adjusted: None, + fullscreen: None, + desired_fullscreen: None, + restore_position: None, + desktop_video_mode: None, + frame_extents: None, + min_inner_size: None, + max_inner_size: None, + resize_increments: None, + base_size: None, + has_focus: false, + cursor_hittest: None, + }) + } +} + +unsafe impl Send for UnownedWindow {} +unsafe impl Sync for UnownedWindow {} + +pub struct UnownedWindow { + pub(crate) xconn: Arc<XConnection>, // never changes + xwindow: xproto::Window, // never changes + #[allow(dead_code)] + visual: u32, // never changes + root: xproto::Window, // never changes + #[allow(dead_code)] + screen_id: i32, // never changes + selected_cursor: Mutex<SelectedCursor>, + cursor_grabbed_mode: Mutex<CursorGrabMode>, + #[allow(clippy::mutex_atomic)] + cursor_visible: Mutex<bool>, + ime_sender: Mutex<ImeSender>, + pub shared_state: Mutex<SharedState>, + redraw_sender: WakeSender<WindowId>, + activation_sender: WakeSender<super::ActivationToken>, +} + +macro_rules! leap { + ($e:expr) => { + match $e { + Ok(x) => x, + Err(err) => return Err(os_error!(OsError::XError(X11Error::from(err).into()))), + } + }; +} + +impl UnownedWindow { + #[allow(clippy::unnecessary_cast)] + pub(crate) fn new( + event_loop: &ActiveEventLoop, + window_attrs: WindowAttributes, + ) -> Result<UnownedWindow, RootOsError> { + let xconn = &event_loop.xconn; + let atoms = xconn.atoms(); + + let screen_id = match window_attrs.platform_specific.x11.screen_id { + Some(id) => id, + None => xconn.default_screen_index() as c_int, + }; + + let screen = { + let screen_id_usize = usize::try_from(screen_id) + .map_err(|_| os_error!(OsError::Misc("screen id must be non-negative")))?; + xconn.xcb_connection().setup().roots.get(screen_id_usize).ok_or(os_error!( + OsError::Misc("requested screen id not present in server's response") + ))? + }; + + #[cfg(feature = "rwh_06")] + let root = match window_attrs.parent_window.as_ref().map(|handle| handle.0) { + Some(rwh_06::RawWindowHandle::Xlib(handle)) => handle.window as xproto::Window, + Some(rwh_06::RawWindowHandle::Xcb(handle)) => handle.window.get(), + Some(raw) => unreachable!("Invalid raw window handle {raw:?} on X11"), + None => screen.root, + }; + #[cfg(not(feature = "rwh_06"))] + let root = event_loop.root; + + let mut monitors = leap!(xconn.available_monitors()); + let guessed_monitor = if monitors.is_empty() { + X11MonitorHandle::dummy() + } else { + xconn + .query_pointer(root, util::VIRTUAL_CORE_POINTER) + .ok() + .and_then(|pointer_state| { + let (x, y) = (pointer_state.root_x as i64, pointer_state.root_y as i64); + + for i in 0..monitors.len() { + if monitors[i].rect.contains_point(x, y) { + return Some(monitors.swap_remove(i)); + } + } + + None + }) + .unwrap_or_else(|| monitors.swap_remove(0)) + }; + let scale_factor = guessed_monitor.scale_factor(); + + info!("Guessed window scale factor: {}", scale_factor); + + let max_inner_size: Option<(u32, u32)> = + window_attrs.max_inner_size.map(|size| size.to_physical::<u32>(scale_factor).into()); + let min_inner_size: Option<(u32, u32)> = + window_attrs.min_inner_size.map(|size| size.to_physical::<u32>(scale_factor).into()); + + let position = + window_attrs.position.map(|position| position.to_physical::<i32>(scale_factor)); + + let dimensions = { + // x11 only applies constraints when the window is actively resized + // by the user, so we have to manually apply the initial constraints + let mut dimensions: (u32, u32) = window_attrs + .inner_size + .map(|size| size.to_physical::<u32>(scale_factor)) + .or_else(|| Some((800, 600).into())) + .map(Into::into) + .unwrap(); + if let Some(max) = max_inner_size { + dimensions.0 = cmp::min(dimensions.0, max.0); + dimensions.1 = cmp::min(dimensions.1, max.1); + } + if let Some(min) = min_inner_size { + dimensions.0 = cmp::max(dimensions.0, min.0); + dimensions.1 = cmp::max(dimensions.1, min.1); + } + debug!("Calculated physical dimensions: {}x{}", dimensions.0, dimensions.1); + dimensions + }; + + // An iterator over the visuals matching screen id combined with their depths. + let mut all_visuals = screen + .allowed_depths + .iter() + .flat_map(|depth| depth.visuals.iter().map(move |visual| (visual, depth.depth))); + + // creating + let (visualtype, depth, require_colormap) = + match window_attrs.platform_specific.x11.visual_id { + Some(vi) => { + // Find this specific visual. + let (visualtype, depth) = + all_visuals.find(|(visual, _)| visual.visual_id == vi).ok_or_else( + || os_error!(OsError::XError(X11Error::NoSuchVisual(vi).into())), + )?; + + (Some(visualtype), depth, true) + }, + None if window_attrs.transparent => { + // Find a suitable visual, true color with 32 bits of depth. + all_visuals + .find_map(|(visual, depth)| { + (depth == 32 && visual.class == xproto::VisualClass::TRUE_COLOR) + .then_some((Some(visual), depth, true)) + }) + .unwrap_or_else(|| { + debug!( + "Could not set transparency, because XMatchVisualInfo returned \ + zero for the required parameters" + ); + (None as _, x11rb::COPY_FROM_PARENT as _, false) + }) + }, + _ => (None, x11rb::COPY_FROM_PARENT as _, false), + }; + let mut visual = visualtype.map_or(x11rb::COPY_FROM_PARENT, |v| v.visual_id); + + let window_attributes = { + use xproto::EventMask; + + let mut aux = xproto::CreateWindowAux::new(); + let event_mask = EventMask::EXPOSURE + | EventMask::STRUCTURE_NOTIFY + | EventMask::VISIBILITY_CHANGE + | EventMask::KEY_PRESS + | EventMask::KEY_RELEASE + | EventMask::KEYMAP_STATE + | EventMask::BUTTON_PRESS + | EventMask::BUTTON_RELEASE + | EventMask::POINTER_MOTION + | EventMask::PROPERTY_CHANGE; + + aux = aux.event_mask(event_mask).border_pixel(0); + + if window_attrs.platform_specific.x11.override_redirect { + aux = aux.override_redirect(true as u32); + } + + // Add a colormap if needed. + let colormap_visual = match window_attrs.platform_specific.x11.visual_id { + Some(vi) => Some(vi), + None if require_colormap => Some(visual), + _ => None, + }; + + if let Some(visual) = colormap_visual { + let colormap = leap!(xconn.xcb_connection().generate_id()); + leap!(xconn.xcb_connection().create_colormap( + xproto::ColormapAlloc::NONE, + colormap, + root, + visual, + )); + aux = aux.colormap(colormap); + } else { + aux = aux.colormap(0); + } + + aux + }; + + // Figure out the window's parent. + let parent = window_attrs.platform_specific.x11.embed_window.unwrap_or(root); + + // finally creating the window + let xwindow = { + let (x, y) = position.map_or((0, 0), Into::into); + let wid = leap!(xconn.xcb_connection().generate_id()); + let result = xconn.xcb_connection().create_window( + depth, + wid, + parent, + x, + y, + dimensions.0.try_into().unwrap(), + dimensions.1.try_into().unwrap(), + 0, + xproto::WindowClass::INPUT_OUTPUT, + visual, + &window_attributes, + ); + leap!(leap!(result).check()); + + wid + }; + + // The COPY_FROM_PARENT is a special value for the visual used to copy + // the visual from the parent window, thus we have to query the visual + // we've got when we built the window above. + if visual == x11rb::COPY_FROM_PARENT { + visual = leap!(leap!(xconn + .xcb_connection() + .get_window_attributes(xwindow as xproto::Window)) + .reply()) + .visual; + } + + #[allow(clippy::mutex_atomic)] + let mut window = UnownedWindow { + xconn: Arc::clone(xconn), + xwindow: xwindow as xproto::Window, + visual, + root, + screen_id, + selected_cursor: Default::default(), + cursor_grabbed_mode: Mutex::new(CursorGrabMode::None), + cursor_visible: Mutex::new(true), + ime_sender: Mutex::new(event_loop.ime_sender.clone()), + shared_state: SharedState::new(guessed_monitor, &window_attrs), + redraw_sender: event_loop.redraw_sender.clone(), + activation_sender: event_loop.activation_sender.clone(), + }; + + // Title must be set before mapping. Some tiling window managers (i.e. i3) use the window + // title to determine placement/etc., so doing this after mapping would cause the WM to + // act on the wrong title state. + leap!(window.set_title_inner(&window_attrs.title)).ignore_error(); + leap!(window.set_decorations_inner(window_attrs.decorations)).ignore_error(); + + if let Some(theme) = window_attrs.preferred_theme { + leap!(window.set_theme_inner(Some(theme))).ignore_error(); + } + + // Embed the window if needed. + if window_attrs.platform_specific.x11.embed_window.is_some() { + window.embed_window()?; + } + + { + // Enable drag and drop (TODO: extend API to make this toggleable) + { + let dnd_aware_atom = atoms[XdndAware]; + let version = &[5u32]; // Latest version; hasn't changed since 2002 + leap!(xconn.change_property( + window.xwindow, + dnd_aware_atom, + u32::from(xproto::AtomEnum::ATOM), + xproto::PropMode::REPLACE, + version, + )) + .ignore_error(); + } + + // WM_CLASS must be set *before* mapping the window, as per ICCCM! + { + let (instance, class) = if let Some(name) = window_attrs.platform_specific.name { + (name.instance, name.general) + } else { + let class = env::args_os() + .next() + .as_ref() + // Default to the name of the binary (via argv[0]) + .and_then(|path| Path::new(path).file_name()) + .and_then(|bin_name| bin_name.to_str()) + .map(|bin_name| bin_name.to_owned()) + .unwrap_or_else(|| window_attrs.title.clone()); + // This environment variable is extraordinarily unlikely to actually be used... + let instance = env::var("RESOURCE_NAME").ok().unwrap_or_else(|| class.clone()); + (instance, class) + }; + + let class = format!("{instance}\0{class}\0"); + leap!(xconn.change_property( + window.xwindow, + xproto::Atom::from(xproto::AtomEnum::WM_CLASS), + xproto::Atom::from(xproto::AtomEnum::STRING), + xproto::PropMode::REPLACE, + class.as_bytes(), + )) + .ignore_error(); + } + + if let Some(flusher) = leap!(window.set_pid()) { + flusher.ignore_error() + } + + leap!(window.set_window_types(window_attrs.platform_specific.x11.x11_window_types)) + .ignore_error(); + + // Set size hints. + let mut min_inner_size = + window_attrs.min_inner_size.map(|size| size.to_physical::<u32>(scale_factor)); + let mut max_inner_size = + window_attrs.max_inner_size.map(|size| size.to_physical::<u32>(scale_factor)); + + if !window_attrs.resizable { + if util::wm_name_is_one_of(&["Xfwm4"]) { + warn!("To avoid a WM bug, disabling resizing has no effect on Xfwm4"); + } else { + max_inner_size = Some(dimensions.into()); + min_inner_size = Some(dimensions.into()); + } + } + + let shared_state = window.shared_state.get_mut().unwrap(); + shared_state.min_inner_size = min_inner_size.map(Into::into); + shared_state.max_inner_size = max_inner_size.map(Into::into); + shared_state.resize_increments = window_attrs.resize_increments; + shared_state.base_size = window_attrs.platform_specific.x11.base_size; + + let normal_hints = WmSizeHints { + position: position.map(|PhysicalPosition { x, y }| { + (WmSizeHintsSpecification::UserSpecified, x, y) + }), + size: Some(( + WmSizeHintsSpecification::UserSpecified, + cast_dimension_to_hint(dimensions.0), + cast_dimension_to_hint(dimensions.1), + )), + max_size: max_inner_size.map(cast_physical_size_to_hint), + min_size: min_inner_size.map(cast_physical_size_to_hint), + size_increment: window_attrs + .resize_increments + .map(|size| cast_size_to_hint(size, scale_factor)), + base_size: window_attrs + .platform_specific + .x11 + .base_size + .map(|size| cast_size_to_hint(size, scale_factor)), + aspect: None, + win_gravity: None, + }; + leap!(leap!(normal_hints.set( + xconn.xcb_connection(), + window.xwindow as xproto::Window, + xproto::AtomEnum::WM_NORMAL_HINTS, + )) + .check()); + + // Set window icons + if let Some(icon) = window_attrs.window_icon { + leap!(window.set_icon_inner(icon.inner)).ignore_error(); + } + + // Opt into handling window close + let result = xconn.xcb_connection().change_property( + xproto::PropMode::REPLACE, + window.xwindow, + atoms[WM_PROTOCOLS], + xproto::AtomEnum::ATOM, + 32, + 2, + bytemuck::cast_slice::<xproto::Atom, u8>(&[ + atoms[WM_DELETE_WINDOW], + atoms[_NET_WM_PING], + ]), + ); + leap!(result).ignore_error(); + + // Select XInput2 events + let mask = xinput::XIEventMask::MOTION + | xinput::XIEventMask::BUTTON_PRESS + | xinput::XIEventMask::BUTTON_RELEASE + | xinput::XIEventMask::ENTER + | xinput::XIEventMask::LEAVE + | xinput::XIEventMask::FOCUS_IN + | xinput::XIEventMask::FOCUS_OUT + | xinput::XIEventMask::TOUCH_BEGIN + | xinput::XIEventMask::TOUCH_UPDATE + | xinput::XIEventMask::TOUCH_END; + leap!(xconn.select_xinput_events(window.xwindow, super::ALL_MASTER_DEVICES, mask)) + .ignore_error(); + + // Set visibility (map window) + if window_attrs.visible { + leap!(xconn.xcb_connection().map_window(window.xwindow)).ignore_error(); + leap!(xconn.xcb_connection().configure_window( + xwindow, + &xproto::ConfigureWindowAux::new().stack_mode(xproto::StackMode::ABOVE) + )) + .ignore_error(); + } + + // Attempt to make keyboard input repeat detectable + unsafe { + let mut supported_ptr = ffi::False; + (xconn.xlib.XkbSetDetectableAutoRepeat)( + xconn.display, + ffi::True, + &mut supported_ptr, + ); + if supported_ptr == ffi::False { + return Err(os_error!(OsError::Misc("`XkbSetDetectableAutoRepeat` failed"))); + } + } + + // Try to create input context for the window. + if let Some(ime) = event_loop.ime.as_ref() { + let result = ime.borrow_mut().create_context(window.xwindow as ffi::Window, false); + leap!(result); + } + + // These properties must be set after mapping + if window_attrs.maximized { + leap!(window.set_maximized_inner(window_attrs.maximized)).ignore_error(); + } + if window_attrs.fullscreen.is_some() { + if let Some(flusher) = + leap!(window + .set_fullscreen_inner(window_attrs.fullscreen.clone().map(Into::into))) + { + flusher.ignore_error() + } + + if let Some(PhysicalPosition { x, y }) = position { + let shared_state = window.shared_state.get_mut().unwrap(); + + shared_state.restore_position = Some((x, y)); + } + } + + leap!(window.set_window_level_inner(window_attrs.window_level)).ignore_error(); + } + + window.set_cursor(window_attrs.cursor); + + // Remove the startup notification if we have one. + if let Some(startup) = window_attrs.platform_specific.activation_token.as_ref() { + leap!(xconn.remove_activation_token(xwindow, &startup.token)); + } + + // We never want to give the user a broken window, since by then, it's too late to handle. + let window = leap!(xconn.sync_with_server().map(|_| window)); + + Ok(window) + } + + /// Embed this window into a parent window. + pub(super) fn embed_window(&self) -> Result<(), RootOsError> { + let atoms = self.xconn.atoms(); + leap!(leap!(self.xconn.change_property( + self.xwindow, + atoms[_XEMBED], + atoms[_XEMBED], + xproto::PropMode::REPLACE, + &[0u32, 1u32], + )) + .check()); + + Ok(()) + } + + pub(super) fn shared_state_lock(&self) -> MutexGuard<'_, SharedState> { + self.shared_state.lock().unwrap() + } + + fn set_pid(&self) -> Result<Option<VoidCookie<'_>>, X11Error> { + let atoms = self.xconn.atoms(); + let pid_atom = atoms[_NET_WM_PID]; + let client_machine_atom = atoms[WM_CLIENT_MACHINE]; + + // Get the hostname and the PID. + let uname = rustix::system::uname(); + let pid = rustix::process::getpid(); + + self.xconn + .change_property( + self.xwindow, + pid_atom, + xproto::Atom::from(xproto::AtomEnum::CARDINAL), + xproto::PropMode::REPLACE, + &[pid.as_raw_nonzero().get() as util::Cardinal], + )? + .ignore_error(); + let flusher = self.xconn.change_property( + self.xwindow, + client_machine_atom, + xproto::Atom::from(xproto::AtomEnum::STRING), + xproto::PropMode::REPLACE, + uname.nodename().to_bytes(), + ); + flusher.map(Some) + } + + fn set_window_types(&self, window_types: Vec<WindowType>) -> Result<VoidCookie<'_>, X11Error> { + let atoms = self.xconn.atoms(); + let hint_atom = atoms[_NET_WM_WINDOW_TYPE]; + let atoms: Vec<_> = window_types.iter().map(|t| t.as_atom(&self.xconn)).collect(); + + self.xconn.change_property( + self.xwindow, + hint_atom, + xproto::Atom::from(xproto::AtomEnum::ATOM), + xproto::PropMode::REPLACE, + &atoms, + ) + } + + pub fn set_theme_inner(&self, theme: Option<Theme>) -> Result<VoidCookie<'_>, X11Error> { + let atoms = self.xconn.atoms(); + let hint_atom = atoms[_GTK_THEME_VARIANT]; + let utf8_atom = atoms[UTF8_STRING]; + let variant = match theme { + Some(Theme::Dark) => "dark", + Some(Theme::Light) => "light", + None => "dark", + }; + let variant = CString::new(variant).expect("`_GTK_THEME_VARIANT` contained null byte"); + self.xconn.change_property( + self.xwindow, + hint_atom, + utf8_atom, + xproto::PropMode::REPLACE, + variant.as_bytes(), + ) + } + + #[inline] + pub fn set_theme(&self, theme: Option<Theme>) { + self.set_theme_inner(theme).expect("Failed to change window theme").ignore_error(); + + self.xconn.flush_requests().expect("Failed to change window theme"); + } + + fn set_netwm( + &self, + operation: util::StateOperation, + properties: (u32, u32, u32, u32), + ) -> Result<VoidCookie<'_>, X11Error> { + let atoms = self.xconn.atoms(); + let state_atom = atoms[_NET_WM_STATE]; + self.xconn.send_client_msg( + self.xwindow, + self.root, + state_atom, + Some(xproto::EventMask::SUBSTRUCTURE_REDIRECT | xproto::EventMask::SUBSTRUCTURE_NOTIFY), + [operation as u32, properties.0, properties.1, properties.2, properties.3], + ) + } + + fn set_fullscreen_hint(&self, fullscreen: bool) -> Result<VoidCookie<'_>, X11Error> { + let atoms = self.xconn.atoms(); + let fullscreen_atom = atoms[_NET_WM_STATE_FULLSCREEN]; + let flusher = self.set_netwm(fullscreen.into(), (fullscreen_atom, 0, 0, 0)); + + if fullscreen { + // Ensure that the fullscreen window receives input focus to prevent + // locking up the user's display. + self.xconn + .xcb_connection() + .set_input_focus(xproto::InputFocus::PARENT, self.xwindow, x11rb::CURRENT_TIME)? + .ignore_error(); + } + + flusher + } + + fn set_fullscreen_inner( + &self, + fullscreen: Option<Fullscreen>, + ) -> Result<Option<VoidCookie<'_>>, X11Error> { + let mut shared_state_lock = self.shared_state_lock(); + + match shared_state_lock.visibility { + // Setting fullscreen on a window that is not visible will generate an error. + Visibility::No | Visibility::YesWait => { + shared_state_lock.desired_fullscreen = Some(fullscreen); + return Ok(None); + }, + Visibility::Yes => (), + } + + let old_fullscreen = shared_state_lock.fullscreen.clone(); + if old_fullscreen == fullscreen { + return Ok(None); + } + shared_state_lock.fullscreen.clone_from(&fullscreen); + + match (&old_fullscreen, &fullscreen) { + // Store the desktop video mode before entering exclusive + // fullscreen, so we can restore it upon exit, as XRandR does not + // provide a mechanism to set this per app-session or restore this + // to the desktop video mode as macOS and Windows do + (&None, &Some(Fullscreen::Exclusive(PlatformVideoModeHandle::X(ref video_mode)))) + | ( + &Some(Fullscreen::Borderless(_)), + &Some(Fullscreen::Exclusive(PlatformVideoModeHandle::X(ref video_mode))), + ) => { + let monitor = video_mode.monitor.as_ref().unwrap(); + shared_state_lock.desktop_video_mode = Some(( + monitor.id, + self.xconn.get_crtc_mode(monitor.id).expect("Failed to get desktop video mode"), + )); + }, + // Restore desktop video mode upon exiting exclusive fullscreen + (&Some(Fullscreen::Exclusive(_)), &None) + | (&Some(Fullscreen::Exclusive(_)), &Some(Fullscreen::Borderless(_))) => { + let (monitor_id, mode_id) = shared_state_lock.desktop_video_mode.take().unwrap(); + self.xconn + .set_crtc_config(monitor_id, mode_id) + .expect("failed to restore desktop video mode"); + }, + _ => (), + } + + drop(shared_state_lock); + + match fullscreen { + None => { + let flusher = self.set_fullscreen_hint(false); + let mut shared_state_lock = self.shared_state_lock(); + if let Some(position) = shared_state_lock.restore_position.take() { + drop(shared_state_lock); + self.set_position_inner(position.0, position.1) + .expect_then_ignore_error("Failed to restore window position"); + } + flusher.map(Some) + }, + Some(fullscreen) => { + let (video_mode, monitor) = match fullscreen { + Fullscreen::Exclusive(PlatformVideoModeHandle::X(ref video_mode)) => { + (Some(video_mode), video_mode.monitor.clone().unwrap()) + }, + Fullscreen::Borderless(Some(PlatformMonitorHandle::X(monitor))) => { + (None, monitor) + }, + Fullscreen::Borderless(None) => { + (None, self.shared_state_lock().last_monitor.clone()) + }, + #[cfg(wayland_platform)] + _ => unreachable!(), + }; + + // Don't set fullscreen on an invalid dummy monitor handle + if monitor.is_dummy() { + return Ok(None); + } + + if let Some(video_mode) = video_mode { + // FIXME: this is actually not correct if we're setting the + // video mode to a resolution higher than the current + // desktop resolution, because XRandR does not automatically + // reposition the monitors to the right and below this + // monitor. + // + // What ends up happening is we will get the fullscreen + // window showing up on those monitors as well, because + // their virtual position now overlaps with the monitor that + // we just made larger.. + // + // It'd be quite a bit of work to handle this correctly (and + // nobody else seems to bother doing this correctly either), + // so we're just leaving this broken. Fixing this would + // involve storing all CRTCs upon entering fullscreen, + // restoring them upon exit, and after entering fullscreen, + // repositioning displays to the right and below this + // display. I think there would still be edge cases that are + // difficult or impossible to handle correctly, e.g. what if + // a new monitor was plugged in while in fullscreen? + // + // I think we might just want to disallow setting the video + // mode higher than the current desktop video mode (I'm sure + // this will make someone unhappy, but it's very unusual for + // games to want to do this anyway). + self.xconn + .set_crtc_config(monitor.id, video_mode.native_mode) + .expect("failed to set video mode"); + } + + let window_position = self.outer_position_physical(); + self.shared_state_lock().restore_position = Some(window_position); + let monitor_origin: (i32, i32) = monitor.position().into(); + self.set_position_inner(monitor_origin.0, monitor_origin.1) + .expect_then_ignore_error("Failed to set window position"); + self.set_fullscreen_hint(true).map(Some) + }, + } + } + + #[inline] + pub(crate) fn fullscreen(&self) -> Option<Fullscreen> { + let shared_state = self.shared_state_lock(); + + shared_state.desired_fullscreen.clone().unwrap_or_else(|| shared_state.fullscreen.clone()) + } + + #[inline] + pub(crate) fn set_fullscreen(&self, fullscreen: Option<Fullscreen>) { + if let Some(flusher) = + self.set_fullscreen_inner(fullscreen).expect("Failed to change window fullscreen state") + { + flusher.check().expect("Failed to change window fullscreen state"); + self.invalidate_cached_frame_extents(); + } + } + + // Called by EventProcessor when a VisibilityNotify event is received + pub(crate) fn visibility_notify(&self) { + let mut shared_state = self.shared_state_lock(); + + match shared_state.visibility { + Visibility::No => self + .xconn + .xcb_connection() + .unmap_window(self.xwindow) + .expect_then_ignore_error("Failed to unmap window"), + Visibility::Yes => (), + Visibility::YesWait => { + shared_state.visibility = Visibility::Yes; + + if let Some(fullscreen) = shared_state.desired_fullscreen.take() { + drop(shared_state); + self.set_fullscreen(fullscreen); + } + }, + } + } + + pub fn current_monitor(&self) -> Option<X11MonitorHandle> { + Some(self.shared_state_lock().last_monitor.clone()) + } + + pub fn available_monitors(&self) -> Vec<X11MonitorHandle> { + self.xconn.available_monitors().expect("Failed to get available monitors") + } + + pub fn primary_monitor(&self) -> Option<X11MonitorHandle> { + Some(self.xconn.primary_monitor().expect("Failed to get primary monitor")) + } + + #[inline] + pub fn is_minimized(&self) -> Option<bool> { + let atoms = self.xconn.atoms(); + let state_atom = atoms[_NET_WM_STATE]; + let state = self.xconn.get_property( + self.xwindow, + state_atom, + xproto::Atom::from(xproto::AtomEnum::ATOM), + ); + let hidden_atom = atoms[_NET_WM_STATE_HIDDEN]; + + Some(match state { + Ok(atoms) => { + atoms.iter().any(|atom: &xproto::Atom| *atom as xproto::Atom == hidden_atom) + }, + _ => false, + }) + } + + /// Refresh the API for the given monitor. + #[inline] + pub(super) fn refresh_dpi_for_monitor<T: 'static>( + &self, + new_monitor: &X11MonitorHandle, + maybe_prev_scale_factor: Option<f64>, + mut callback: impl FnMut(Event<T>), + ) { + // Check if the self is on this monitor + let monitor = self.shared_state_lock().last_monitor.clone(); + if monitor.name == new_monitor.name { + let (width, height) = self.inner_size_physical(); + let (new_width, new_height) = self.adjust_for_dpi( + // If we couldn't determine the previous scale + // factor (e.g., because all monitors were closed + // before), just pick whatever the current monitor + // has set as a baseline. + maybe_prev_scale_factor.unwrap_or(monitor.scale_factor), + new_monitor.scale_factor, + width, + height, + &self.shared_state_lock(), + ); + + let window_id = crate::window::WindowId(self.id()); + let old_inner_size = PhysicalSize::new(width, height); + let inner_size = Arc::new(Mutex::new(PhysicalSize::new(new_width, new_height))); + callback(Event::WindowEvent { + window_id, + event: WindowEvent::ScaleFactorChanged { + scale_factor: new_monitor.scale_factor, + inner_size_writer: InnerSizeWriter::new(Arc::downgrade(&inner_size)), + }, + }); + + let new_inner_size = *inner_size.lock().unwrap(); + drop(inner_size); + + if new_inner_size != old_inner_size { + let (new_width, new_height) = new_inner_size.into(); + self.request_inner_size_physical(new_width, new_height); + } + } + } + + fn set_minimized_inner(&self, minimized: bool) -> Result<VoidCookie<'_>, X11Error> { + let atoms = self.xconn.atoms(); + + if minimized { + let root_window = self.xconn.default_root().root; + + self.xconn.send_client_msg( + self.xwindow, + root_window, + atoms[WM_CHANGE_STATE], + Some( + xproto::EventMask::SUBSTRUCTURE_REDIRECT + | xproto::EventMask::SUBSTRUCTURE_NOTIFY, + ), + [3u32, 0, 0, 0, 0], + ) + } else { + self.xconn.send_client_msg( + self.xwindow, + self.root, + atoms[_NET_ACTIVE_WINDOW], + Some( + xproto::EventMask::SUBSTRUCTURE_REDIRECT + | xproto::EventMask::SUBSTRUCTURE_NOTIFY, + ), + [1, x11rb::CURRENT_TIME, 0, 0, 0], + ) + } + } + + #[inline] + pub fn set_minimized(&self, minimized: bool) { + self.set_minimized_inner(minimized) + .expect_then_ignore_error("Failed to change window minimization"); + + self.xconn.flush_requests().expect("Failed to change window minimization"); + } + + #[inline] + pub fn is_maximized(&self) -> bool { + let atoms = self.xconn.atoms(); + let state_atom = atoms[_NET_WM_STATE]; + let state = self.xconn.get_property( + self.xwindow, + state_atom, + xproto::Atom::from(xproto::AtomEnum::ATOM), + ); + let horz_atom = atoms[_NET_WM_STATE_MAXIMIZED_HORZ]; + let vert_atom = atoms[_NET_WM_STATE_MAXIMIZED_VERT]; + match state { + Ok(atoms) => { + let horz_maximized = atoms.contains(&horz_atom); + let vert_maximized = atoms.contains(&vert_atom); + horz_maximized && vert_maximized + }, + _ => false, + } + } + + fn set_maximized_inner(&self, maximized: bool) -> Result<VoidCookie<'_>, X11Error> { + let atoms = self.xconn.atoms(); + let horz_atom = atoms[_NET_WM_STATE_MAXIMIZED_HORZ]; + let vert_atom = atoms[_NET_WM_STATE_MAXIMIZED_VERT]; + + self.set_netwm(maximized.into(), (horz_atom, vert_atom, 0, 0)) + } + + #[inline] + pub fn set_maximized(&self, maximized: bool) { + self.set_maximized_inner(maximized) + .expect_then_ignore_error("Failed to change window maximization"); + self.xconn.flush_requests().expect("Failed to change window maximization"); + self.invalidate_cached_frame_extents(); + } + + fn set_title_inner(&self, title: &str) -> Result<VoidCookie<'_>, X11Error> { + let atoms = self.xconn.atoms(); + + let title = CString::new(title).expect("Window title contained null byte"); + self.xconn + .change_property( + self.xwindow, + xproto::Atom::from(xproto::AtomEnum::WM_NAME), + xproto::Atom::from(xproto::AtomEnum::STRING), + xproto::PropMode::REPLACE, + title.as_bytes(), + )? + .ignore_error(); + self.xconn.change_property( + self.xwindow, + atoms[_NET_WM_NAME], + atoms[UTF8_STRING], + xproto::PropMode::REPLACE, + title.as_bytes(), + ) + } + + #[inline] + pub fn set_title(&self, title: &str) { + self.set_title_inner(title).expect_then_ignore_error("Failed to set window title"); + + self.xconn.flush_requests().expect("Failed to set window title"); + } + + #[inline] + pub fn set_transparent(&self, _transparent: bool) {} + + #[inline] + pub fn set_blur(&self, _blur: bool) {} + + fn set_decorations_inner(&self, decorations: bool) -> Result<VoidCookie<'_>, X11Error> { + self.shared_state_lock().is_decorated = decorations; + let mut hints = self.xconn.get_motif_hints(self.xwindow); + + hints.set_decorations(decorations); + + self.xconn.set_motif_hints(self.xwindow, &hints) + } + + #[inline] + pub fn set_decorations(&self, decorations: bool) { + self.set_decorations_inner(decorations) + .expect_then_ignore_error("Failed to set decoration state"); + self.xconn.flush_requests().expect("Failed to set decoration state"); + self.invalidate_cached_frame_extents(); + } + + #[inline] + pub fn is_decorated(&self) -> bool { + self.shared_state_lock().is_decorated + } + + fn set_maximizable_inner(&self, maximizable: bool) -> Result<VoidCookie<'_>, X11Error> { + let mut hints = self.xconn.get_motif_hints(self.xwindow); + + hints.set_maximizable(maximizable); + + self.xconn.set_motif_hints(self.xwindow, &hints) + } + + fn toggle_atom(&self, atom_name: AtomName, enable: bool) -> Result<VoidCookie<'_>, X11Error> { + let atoms = self.xconn.atoms(); + let atom = atoms[atom_name]; + self.set_netwm(enable.into(), (atom, 0, 0, 0)) + } + + fn set_window_level_inner(&self, level: WindowLevel) -> Result<VoidCookie<'_>, X11Error> { + self.toggle_atom(_NET_WM_STATE_ABOVE, level == WindowLevel::AlwaysOnTop)?.ignore_error(); + self.toggle_atom(_NET_WM_STATE_BELOW, level == WindowLevel::AlwaysOnBottom) + } + + #[inline] + pub fn set_window_level(&self, level: WindowLevel) { + self.set_window_level_inner(level) + .expect_then_ignore_error("Failed to set window-level state"); + self.xconn.flush_requests().expect("Failed to set window-level state"); + } + + fn set_icon_inner(&self, icon: PlatformIcon) -> Result<VoidCookie<'_>, X11Error> { + let atoms = self.xconn.atoms(); + let icon_atom = atoms[_NET_WM_ICON]; + let data = icon.to_cardinals(); + self.xconn.change_property( + self.xwindow, + icon_atom, + xproto::Atom::from(xproto::AtomEnum::CARDINAL), + xproto::PropMode::REPLACE, + data.as_slice(), + ) + } + + fn unset_icon_inner(&self) -> Result<VoidCookie<'_>, X11Error> { + let atoms = self.xconn.atoms(); + let icon_atom = atoms[_NET_WM_ICON]; + let empty_data: [util::Cardinal; 0] = []; + self.xconn.change_property( + self.xwindow, + icon_atom, + xproto::Atom::from(xproto::AtomEnum::CARDINAL), + xproto::PropMode::REPLACE, + &empty_data, + ) + } + + #[inline] + pub(crate) fn set_window_icon(&self, icon: Option<PlatformIcon>) { + match icon { + Some(icon) => self.set_icon_inner(icon), + None => self.unset_icon_inner(), + } + .expect_then_ignore_error("Failed to set icons"); + + self.xconn.flush_requests().expect("Failed to set icons"); + } + + #[inline] + pub fn set_visible(&self, visible: bool) { + let mut shared_state = self.shared_state_lock(); + + match (visible, shared_state.visibility) { + (true, Visibility::Yes) | (true, Visibility::YesWait) | (false, Visibility::No) => { + return + }, + _ => (), + } + + if visible { + self.xconn + .xcb_connection() + .map_window(self.xwindow) + .expect_then_ignore_error("Failed to call `xcb_map_window`"); + self.xconn + .xcb_connection() + .configure_window( + self.xwindow, + &xproto::ConfigureWindowAux::new().stack_mode(xproto::StackMode::ABOVE), + ) + .expect_then_ignore_error("Failed to call `xcb_configure_window`"); + self.xconn.flush_requests().expect("Failed to call XMapRaised"); + shared_state.visibility = Visibility::YesWait; + } else { + self.xconn + .xcb_connection() + .unmap_window(self.xwindow) + .expect_then_ignore_error("Failed to call `xcb_unmap_window`"); + self.xconn.flush_requests().expect("Failed to call XUnmapWindow"); + shared_state.visibility = Visibility::No; + } + } + + #[inline] + pub fn is_visible(&self) -> Option<bool> { + Some(self.shared_state_lock().visibility == Visibility::Yes) + } + + fn update_cached_frame_extents(&self) { + let extents = self.xconn.get_frame_extents_heuristic(self.xwindow, self.root); + self.shared_state_lock().frame_extents = Some(extents); + } + + pub(crate) fn invalidate_cached_frame_extents(&self) { + self.shared_state_lock().frame_extents.take(); + } + + pub(crate) fn outer_position_physical(&self) -> (i32, i32) { + let extents = self.shared_state_lock().frame_extents.clone(); + if let Some(extents) = extents { + let (x, y) = self.inner_position_physical(); + extents.inner_pos_to_outer(x, y) + } else { + self.update_cached_frame_extents(); + self.outer_position_physical() + } + } + + #[inline] + pub fn outer_position(&self) -> Result<PhysicalPosition<i32>, NotSupportedError> { + let extents = self.shared_state_lock().frame_extents.clone(); + if let Some(extents) = extents { + let (x, y) = self.inner_position_physical(); + Ok(extents.inner_pos_to_outer(x, y).into()) + } else { + self.update_cached_frame_extents(); + self.outer_position() + } + } + + pub(crate) fn inner_position_physical(&self) -> (i32, i32) { + // This should be okay to unwrap since the only error XTranslateCoordinates can return + // is BadWindow, and if the window handle is bad we have bigger problems. + self.xconn + .translate_coords(self.xwindow, self.root) + .map(|coords| (coords.dst_x.into(), coords.dst_y.into())) + .unwrap() + } + + #[inline] + pub fn inner_position(&self) -> Result<PhysicalPosition<i32>, NotSupportedError> { + Ok(self.inner_position_physical().into()) + } + + pub(crate) fn set_position_inner( + &self, + mut x: i32, + mut y: i32, + ) -> Result<VoidCookie<'_>, X11Error> { + // There are a few WMs that set client area position rather than window position, so + // we'll translate for consistency. + if util::wm_name_is_one_of(&["Enlightenment", "FVWM"]) { + let extents = self.shared_state_lock().frame_extents.clone(); + if let Some(extents) = extents { + x += cast_dimension_to_hint(extents.frame_extents.left); + y += cast_dimension_to_hint(extents.frame_extents.top); + } else { + self.update_cached_frame_extents(); + return self.set_position_inner(x, y); + } + } + + self.xconn + .xcb_connection() + .configure_window(self.xwindow, &xproto::ConfigureWindowAux::new().x(x).y(y)) + .map_err(Into::into) + } + + pub(crate) fn set_position_physical(&self, x: i32, y: i32) { + self.set_position_inner(x, y).expect_then_ignore_error("Failed to call `XMoveWindow`"); + } + + #[inline] + pub fn set_outer_position(&self, position: Position) { + let (x, y) = position.to_physical::<i32>(self.scale_factor()).into(); + self.set_position_physical(x, y); + } + + pub(crate) fn inner_size_physical(&self) -> (u32, u32) { + // This should be okay to unwrap since the only error XGetGeometry can return + // is BadWindow, and if the window handle is bad we have bigger problems. + self.xconn + .get_geometry(self.xwindow) + .map(|geo| (geo.width.into(), geo.height.into())) + .unwrap() + } + + #[inline] + pub fn inner_size(&self) -> PhysicalSize<u32> { + self.inner_size_physical().into() + } + + #[inline] + pub fn outer_size(&self) -> PhysicalSize<u32> { + let extents = self.shared_state_lock().frame_extents.clone(); + if let Some(extents) = extents { + let (width, height) = self.inner_size_physical(); + extents.inner_size_to_outer(width, height).into() + } else { + self.update_cached_frame_extents(); + self.outer_size() + } + } + + pub(crate) fn request_inner_size_physical(&self, width: u32, height: u32) { + self.xconn + .xcb_connection() + .configure_window( + self.xwindow, + &xproto::ConfigureWindowAux::new().width(width).height(height), + ) + .expect_then_ignore_error("Failed to call `xcb_configure_window`"); + self.xconn.flush_requests().expect("Failed to call XResizeWindow"); + // cursor_hittest needs to be reapplied after each window resize. + if self.shared_state_lock().cursor_hittest.unwrap_or(false) { + let _ = self.set_cursor_hittest(true); + } + } + + #[inline] + pub fn request_inner_size(&self, size: Size) -> Option<PhysicalSize<u32>> { + let scale_factor = self.scale_factor(); + let size = size.to_physical::<u32>(scale_factor).into(); + if !self.shared_state_lock().is_resizable { + self.update_normal_hints(|normal_hints| { + normal_hints.min_size = Some(size); + normal_hints.max_size = Some(size); + }) + .expect("Failed to call `XSetWMNormalHints`"); + } + self.request_inner_size_physical(size.0 as u32, size.1 as u32); + + None + } + + fn update_normal_hints<F>(&self, callback: F) -> Result<(), X11Error> + where + F: FnOnce(&mut WmSizeHints), + { + let mut normal_hints = WmSizeHints::get( + self.xconn.xcb_connection(), + self.xwindow as xproto::Window, + xproto::AtomEnum::WM_NORMAL_HINTS, + )? + .reply()? + .unwrap_or_default(); + callback(&mut normal_hints); + normal_hints + .set( + self.xconn.xcb_connection(), + self.xwindow as xproto::Window, + xproto::AtomEnum::WM_NORMAL_HINTS, + )? + .ignore_error(); + Ok(()) + } + + pub(crate) fn set_min_inner_size_physical(&self, dimensions: Option<(u32, u32)>) { + self.update_normal_hints(|normal_hints| { + normal_hints.min_size = + dimensions.map(|(w, h)| (cast_dimension_to_hint(w), cast_dimension_to_hint(h))) + }) + .expect("Failed to call `XSetWMNormalHints`"); + } + + #[inline] + pub fn set_min_inner_size(&self, dimensions: Option<Size>) { + self.shared_state_lock().min_inner_size = dimensions; + let physical_dimensions = + dimensions.map(|dimensions| dimensions.to_physical::<u32>(self.scale_factor()).into()); + self.set_min_inner_size_physical(physical_dimensions); + } + + pub(crate) fn set_max_inner_size_physical(&self, dimensions: Option<(u32, u32)>) { + self.update_normal_hints(|normal_hints| { + normal_hints.max_size = + dimensions.map(|(w, h)| (cast_dimension_to_hint(w), cast_dimension_to_hint(h))) + }) + .expect("Failed to call `XSetWMNormalHints`"); + } + + #[inline] + pub fn set_max_inner_size(&self, dimensions: Option<Size>) { + self.shared_state_lock().max_inner_size = dimensions; + let physical_dimensions = + dimensions.map(|dimensions| dimensions.to_physical::<u32>(self.scale_factor()).into()); + self.set_max_inner_size_physical(physical_dimensions); + } + + #[inline] + pub fn resize_increments(&self) -> Option<PhysicalSize<u32>> { + WmSizeHints::get( + self.xconn.xcb_connection(), + self.xwindow as xproto::Window, + xproto::AtomEnum::WM_NORMAL_HINTS, + ) + .ok() + .and_then(|cookie| cookie.reply().ok()) + .flatten() + .and_then(|hints| hints.size_increment) + .map(|(width, height)| (width as u32, height as u32).into()) + } + + #[inline] + pub fn set_resize_increments(&self, increments: Option<Size>) { + self.shared_state_lock().resize_increments = increments; + let physical_increments = + increments.map(|increments| cast_size_to_hint(increments, self.scale_factor())); + self.update_normal_hints(|hints| hints.size_increment = physical_increments) + .expect("Failed to call `XSetWMNormalHints`"); + } + + pub(crate) fn adjust_for_dpi( + &self, + old_scale_factor: f64, + new_scale_factor: f64, + width: u32, + height: u32, + shared_state: &SharedState, + ) -> (u32, u32) { + let scale_factor = new_scale_factor / old_scale_factor; + self.update_normal_hints(|normal_hints| { + let dpi_adjuster = |size: Size| -> (i32, i32) { cast_size_to_hint(size, scale_factor) }; + let max_size = shared_state.max_inner_size.map(dpi_adjuster); + let min_size = shared_state.min_inner_size.map(dpi_adjuster); + let resize_increments = shared_state.resize_increments.map(dpi_adjuster); + let base_size = shared_state.base_size.map(dpi_adjuster); + + normal_hints.max_size = max_size; + normal_hints.min_size = min_size; + normal_hints.size_increment = resize_increments; + normal_hints.base_size = base_size; + }) + .expect("Failed to update normal hints"); + + let new_width = (width as f64 * scale_factor).round() as u32; + let new_height = (height as f64 * scale_factor).round() as u32; + + (new_width, new_height) + } + + pub fn set_resizable(&self, resizable: bool) { + if util::wm_name_is_one_of(&["Xfwm4"]) { + // Making the window unresizable on Xfwm prevents further changes to `WM_NORMAL_HINTS` + // from being detected. This makes it impossible for resizing to be + // re-enabled, and also breaks DPI scaling. As such, we choose the lesser of + // two evils and do nothing. + warn!("To avoid a WM bug, disabling resizing has no effect on Xfwm4"); + return; + } + + let (min_size, max_size) = if resizable { + let shared_state_lock = self.shared_state_lock(); + (shared_state_lock.min_inner_size, shared_state_lock.max_inner_size) + } else { + let window_size = Some(Size::from(self.inner_size())); + (window_size, window_size) + }; + self.shared_state_lock().is_resizable = resizable; + + self.set_maximizable_inner(resizable) + .expect_then_ignore_error("Failed to call `XSetWMNormalHints`"); + + let scale_factor = self.scale_factor(); + let min_inner_size = min_size.map(|size| cast_size_to_hint(size, scale_factor)); + let max_inner_size = max_size.map(|size| cast_size_to_hint(size, scale_factor)); + self.update_normal_hints(|normal_hints| { + normal_hints.min_size = min_inner_size; + normal_hints.max_size = max_inner_size; + }) + .expect("Failed to call `XSetWMNormalHints`"); + } + + #[inline] + pub fn is_resizable(&self) -> bool { + self.shared_state_lock().is_resizable + } + + #[inline] + pub fn set_enabled_buttons(&self, _buttons: WindowButtons) {} + + #[inline] + pub fn enabled_buttons(&self) -> WindowButtons { + WindowButtons::all() + } + + #[allow(dead_code)] + #[inline] + pub fn xlib_display(&self) -> *mut c_void { + self.xconn.display as _ + } + + #[allow(dead_code)] + #[inline] + pub fn xlib_window(&self) -> c_ulong { + self.xwindow as ffi::Window + } + + #[inline] + pub fn set_cursor(&self, cursor: Cursor) { + match cursor { + Cursor::Icon(icon) => { + let old_cursor = replace( + &mut *self.selected_cursor.lock().unwrap(), + SelectedCursor::Named(icon), + ); + + #[allow(clippy::mutex_atomic)] + if SelectedCursor::Named(icon) != old_cursor && *self.cursor_visible.lock().unwrap() + { + self.xconn.set_cursor_icon(self.xwindow, Some(icon)); + } + }, + Cursor::Custom(RootCustomCursor { inner: PlatformCustomCursor::X(cursor) }) => { + #[allow(clippy::mutex_atomic)] + if *self.cursor_visible.lock().unwrap() { + self.xconn.set_custom_cursor(self.xwindow, &cursor); + } + + *self.selected_cursor.lock().unwrap() = SelectedCursor::Custom(cursor); + }, + #[cfg(wayland_platform)] + Cursor::Custom(RootCustomCursor { inner: PlatformCustomCursor::Wayland(_) }) => { + tracing::error!("passed a Wayland cursor to X11 backend") + }, + } + } + + #[inline] + pub fn set_cursor_grab(&self, mode: CursorGrabMode) -> Result<(), ExternalError> { + // We don't support the locked cursor yet, so ignore it early on. + if mode == CursorGrabMode::Locked { + return Err(ExternalError::NotSupported(NotSupportedError::new())); + } + + let mut grabbed_lock = self.cursor_grabbed_mode.lock().unwrap(); + if mode == *grabbed_lock { + return Ok(()); + } + + // We ungrab before grabbing to prevent passive grabs from causing `AlreadyGrabbed`. + // Therefore, this is common to both codepaths. + self.xconn + .xcb_connection() + .ungrab_pointer(x11rb::CURRENT_TIME) + .expect_then_ignore_error("Failed to call `xcb_ungrab_pointer`"); + *grabbed_lock = CursorGrabMode::None; + + let result = match mode { + CursorGrabMode::None => self.xconn.flush_requests().map_err(|err| { + ExternalError::Os(os_error!(OsError::XError(X11Error::Xlib(err).into()))) + }), + CursorGrabMode::Confined => { + let result = self + .xconn + .xcb_connection() + .grab_pointer( + true as _, + self.xwindow, + xproto::EventMask::BUTTON_PRESS + | xproto::EventMask::BUTTON_RELEASE + | xproto::EventMask::ENTER_WINDOW + | xproto::EventMask::LEAVE_WINDOW + | xproto::EventMask::POINTER_MOTION + | xproto::EventMask::POINTER_MOTION_HINT + | xproto::EventMask::BUTTON1_MOTION + | xproto::EventMask::BUTTON2_MOTION + | xproto::EventMask::BUTTON3_MOTION + | xproto::EventMask::BUTTON4_MOTION + | xproto::EventMask::BUTTON5_MOTION + | xproto::EventMask::KEYMAP_STATE, + xproto::GrabMode::ASYNC, + xproto::GrabMode::ASYNC, + self.xwindow, + 0u32, + x11rb::CURRENT_TIME, + ) + .expect("Failed to call `grab_pointer`") + .reply() + .expect("Failed to receive reply from `grab_pointer`"); + + match result.status { + xproto::GrabStatus::SUCCESS => Ok(()), + xproto::GrabStatus::ALREADY_GRABBED => { + Err("Cursor could not be confined: already confined by another client") + }, + xproto::GrabStatus::INVALID_TIME => { + Err("Cursor could not be confined: invalid time") + }, + xproto::GrabStatus::NOT_VIEWABLE => { + Err("Cursor could not be confined: confine location not viewable") + }, + xproto::GrabStatus::FROZEN => { + Err("Cursor could not be confined: frozen by another client") + }, + _ => unreachable!(), + } + .map_err(|err| ExternalError::Os(os_error!(OsError::Misc(err)))) + }, + CursorGrabMode::Locked => return Ok(()), + }; + + if result.is_ok() { + *grabbed_lock = mode; + } + + result + } + + #[inline] + pub fn set_cursor_visible(&self, visible: bool) { + #[allow(clippy::mutex_atomic)] + let mut visible_lock = self.cursor_visible.lock().unwrap(); + if visible == *visible_lock { + return; + } + let cursor = + if visible { Some((*self.selected_cursor.lock().unwrap()).clone()) } else { None }; + *visible_lock = visible; + drop(visible_lock); + match cursor { + Some(SelectedCursor::Custom(cursor)) => { + self.xconn.set_custom_cursor(self.xwindow, &cursor); + }, + Some(SelectedCursor::Named(cursor)) => { + self.xconn.set_cursor_icon(self.xwindow, Some(cursor)); + }, + None => { + self.xconn.set_cursor_icon(self.xwindow, None); + }, + } + } + + #[inline] + pub fn scale_factor(&self) -> f64 { + self.shared_state_lock().last_monitor.scale_factor + } + + pub fn set_cursor_position_physical(&self, x: i32, y: i32) -> Result<(), ExternalError> { + { + self.xconn + .xcb_connection() + .warp_pointer(x11rb::NONE, self.xwindow, 0, 0, 0, 0, x as _, y as _) + .map_err(|e| { + ExternalError::Os(os_error!(OsError::XError(X11Error::from(e).into()))) + })?; + self.xconn.flush_requests().map_err(|e| { + ExternalError::Os(os_error!(OsError::XError(X11Error::Xlib(e).into()))) + }) + } + } + + #[inline] + pub fn set_cursor_position(&self, position: Position) -> Result<(), ExternalError> { + let (x, y) = position.to_physical::<i32>(self.scale_factor()).into(); + self.set_cursor_position_physical(x, y) + } + + #[inline] + pub fn set_cursor_hittest(&self, hittest: bool) -> Result<(), ExternalError> { + // Implement cursor hittest for X11 by either setting an empty or full window input shape. + + // In X11, every window has two "shapes": + // * Bounding shape: defines the visible outline of the window. + // * Input shape: defines the region of the window that receives pointer/keyboard events. + // If the input shape is the full window rectangle, the window behaves normally. + // If the input shape is empty, the window is completely click‑through. + // Here, we implement hit test by mapping `hittest = true` to "restore a full input shape" + // and `hittest = false` to "clear the input shape" (empty list of rectangles). + let mut rectangles: Vec<Rectangle> = Vec::new(); + if hittest { + let size = self.inner_size(); + rectangles.push(Rectangle { + x: 0, + y: 0, + width: size.width as u16, + height: size.height as u16, + }) + } + + self.xconn + .xcb_connection() + .shape_rectangles( + SO::SET, + SK::INPUT, + ClipOrdering::UNSORTED, + self.xwindow, + 0, + 0, + &rectangles, + ) + .map_err(|_e| ExternalError::Ignored)?; + self.shared_state_lock().cursor_hittest = Some(hittest); + Ok(()) + } + + /// Moves the window while it is being dragged. + pub fn drag_window(&self) -> Result<(), ExternalError> { + self.drag_initiate(util::MOVERESIZE_MOVE) + } + + #[inline] + pub fn show_window_menu(&self, _position: Position) {} + + /// Resizes the window while it is being dragged. + pub fn drag_resize_window(&self, direction: ResizeDirection) -> Result<(), ExternalError> { + self.drag_initiate(match direction { + ResizeDirection::East => util::MOVERESIZE_RIGHT, + ResizeDirection::North => util::MOVERESIZE_TOP, + ResizeDirection::NorthEast => util::MOVERESIZE_TOPRIGHT, + ResizeDirection::NorthWest => util::MOVERESIZE_TOPLEFT, + ResizeDirection::South => util::MOVERESIZE_BOTTOM, + ResizeDirection::SouthEast => util::MOVERESIZE_BOTTOMRIGHT, + ResizeDirection::SouthWest => util::MOVERESIZE_BOTTOMLEFT, + ResizeDirection::West => util::MOVERESIZE_LEFT, + }) + } + + /// Initiates a drag operation while the left mouse button is pressed. + fn drag_initiate(&self, action: isize) -> Result<(), ExternalError> { + let pointer = self + .xconn + .query_pointer(self.xwindow, util::VIRTUAL_CORE_POINTER) + .map_err(|err| ExternalError::Os(os_error!(OsError::XError(err.into()))))?; + + let window = self.inner_position().map_err(ExternalError::NotSupported)?; + + let atoms = self.xconn.atoms(); + let message = atoms[_NET_WM_MOVERESIZE]; + + // we can't use `set_cursor_grab(false)` here because it doesn't run `XUngrabPointer` + // if the cursor isn't currently grabbed + let mut grabbed_lock = self.cursor_grabbed_mode.lock().unwrap(); + self.xconn + .xcb_connection() + .ungrab_pointer(x11rb::CURRENT_TIME) + .map_err(|err| { + ExternalError::Os(os_error!(OsError::XError(X11Error::from(err).into()))) + })? + .ignore_error(); + self.xconn.flush_requests().map_err(|err| { + ExternalError::Os(os_error!(OsError::XError(X11Error::Xlib(err).into()))) + })?; + *grabbed_lock = CursorGrabMode::None; + + // we keep the lock until we are done + self.xconn + .send_client_msg( + self.xwindow, + self.root, + message, + Some( + xproto::EventMask::SUBSTRUCTURE_REDIRECT + | xproto::EventMask::SUBSTRUCTURE_NOTIFY, + ), + [ + (window.x + xinput_fp1616_to_float(pointer.win_x) as i32) as u32, + (window.y + xinput_fp1616_to_float(pointer.win_y) as i32) as u32, + action.try_into().unwrap(), + 1, // Button 1 + 1, + ], + ) + .map_err(|err| ExternalError::Os(os_error!(OsError::XError(err.into()))))?; + + self.xconn.flush_requests().map_err(|err| { + ExternalError::Os(os_error!(OsError::XError(X11Error::Xlib(err).into()))) + }) + } + + #[inline] + pub fn set_ime_cursor_area(&self, spot: Position, _size: Size) { + let (x, y) = spot.to_physical::<i32>(self.scale_factor()).into(); + let _ = self.ime_sender.lock().unwrap().send(ImeRequest::Position( + self.xwindow as ffi::Window, + x, + y, + )); + } + + #[inline] + pub fn set_ime_allowed(&self, allowed: bool) { + let _ = self + .ime_sender + .lock() + .unwrap() + .send(ImeRequest::Allow(self.xwindow as ffi::Window, allowed)); + } + + #[inline] + pub fn set_ime_purpose(&self, _purpose: ImePurpose) {} + + #[inline] + pub fn focus_window(&self) { + let atoms = self.xconn.atoms(); + let state_atom = atoms[WM_STATE]; + let state_type_atom = atoms[CARD32]; + let is_minimized = if let Ok(state) = + self.xconn.get_property::<u32>(self.xwindow, state_atom, state_type_atom) + { + state.contains(&super::ICONIC_STATE) + } else { + false + }; + let is_visible = match self.shared_state_lock().visibility { + Visibility::Yes => true, + Visibility::YesWait | Visibility::No => false, + }; + + if is_visible && !is_minimized { + self.xconn + .send_client_msg( + self.xwindow, + self.root, + atoms[_NET_ACTIVE_WINDOW], + Some( + xproto::EventMask::SUBSTRUCTURE_REDIRECT + | xproto::EventMask::SUBSTRUCTURE_NOTIFY, + ), + [1, x11rb::CURRENT_TIME, 0, 0, 0], + ) + .expect_then_ignore_error("Failed to send client message"); + if let Err(e) = self.xconn.flush_requests() { + tracing::error!( + "`flush` returned an error when focusing the window. Error was: {}", + e + ); + } + } + } + + #[inline] + pub fn request_user_attention(&self, request_type: Option<UserAttentionType>) { + let mut wm_hints = + WmHints::get(self.xconn.xcb_connection(), self.xwindow as xproto::Window) + .ok() + .and_then(|cookie| cookie.reply().ok()) + .flatten() + .unwrap_or_default(); + + wm_hints.urgent = request_type.is_some(); + wm_hints + .set(self.xconn.xcb_connection(), self.xwindow as xproto::Window) + .expect_then_ignore_error("Failed to set WM hints"); + } + + #[inline] + pub(crate) fn generate_activation_token(&self) -> Result<String, X11Error> { + // Get the title from the WM_NAME property. + let atoms = self.xconn.atoms(); + let title = { + let title_bytes = self + .xconn + .get_property(self.xwindow, atoms[_NET_WM_NAME], atoms[UTF8_STRING]) + .expect("Failed to get title"); + + String::from_utf8(title_bytes).expect("Bad title") + }; + + // Get the activation token and then put it in the event queue. + let token = self.xconn.request_activation_token(&title)?; + + Ok(token) + } + + #[inline] + pub fn request_activation_token(&self) -> Result<AsyncRequestSerial, NotSupportedError> { + let serial = AsyncRequestSerial::get(); + self.activation_sender + .send((self.id(), serial)) + .expect("activation token channel should never be closed"); + Ok(serial) + } + + #[inline] + pub fn id(&self) -> WindowId { + WindowId(self.xwindow as _) + } + + #[inline] + pub fn request_redraw(&self) { + self.redraw_sender.send(WindowId(self.xwindow as _)).unwrap(); + } + + #[inline] + pub fn pre_present_notify(&self) { + // TODO timer + } + + #[cfg(feature = "rwh_04")] + #[inline] + pub fn raw_window_handle_rwh_04(&self) -> rwh_04::RawWindowHandle { + let mut window_handle = rwh_04::XlibHandle::empty(); + window_handle.display = self.xlib_display(); + window_handle.window = self.xlib_window(); + window_handle.visual_id = self.visual as c_ulong; + rwh_04::RawWindowHandle::Xlib(window_handle) + } + + #[cfg(feature = "rwh_05")] + #[inline] + pub fn raw_window_handle_rwh_05(&self) -> rwh_05::RawWindowHandle { + let mut window_handle = rwh_05::XlibWindowHandle::empty(); + window_handle.window = self.xlib_window(); + window_handle.visual_id = self.visual as c_ulong; + window_handle.into() + } + + #[cfg(feature = "rwh_05")] + #[inline] + pub fn raw_display_handle_rwh_05(&self) -> rwh_05::RawDisplayHandle { + let mut display_handle = rwh_05::XlibDisplayHandle::empty(); + display_handle.display = self.xlib_display(); + display_handle.screen = self.screen_id; + display_handle.into() + } + + #[cfg(feature = "rwh_06")] + #[inline] + pub fn raw_window_handle_rwh_06(&self) -> Result<rwh_06::RawWindowHandle, rwh_06::HandleError> { + let mut window_handle = rwh_06::XlibWindowHandle::new(self.xlib_window()); + window_handle.visual_id = self.visual as c_ulong; + Ok(window_handle.into()) + } + + #[cfg(feature = "rwh_06")] + #[inline] + pub fn raw_display_handle_rwh_06( + &self, + ) -> Result<rwh_06::RawDisplayHandle, rwh_06::HandleError> { + Ok(rwh_06::XlibDisplayHandle::new( + Some( + std::ptr::NonNull::new(self.xlib_display()) + .expect("display pointer should never be null"), + ), + self.screen_id, + ) + .into()) + } + + #[inline] + pub fn theme(&self) -> Option<Theme> { + None + } + + pub fn set_content_protected(&self, _protected: bool) {} + + #[inline] + pub fn has_focus(&self) -> bool { + self.shared_state_lock().has_focus + } + + pub fn title(&self) -> String { + String::new() + } +} + +/// Cast a dimension value into a hinted dimension for `WmSizeHints`, clamping if too large. +fn cast_dimension_to_hint(val: u32) -> i32 { + val.try_into().unwrap_or(i32::MAX) +} + +/// Use the above strategy to cast a physical size into a hinted size. +fn cast_physical_size_to_hint(size: PhysicalSize<u32>) -> (i32, i32) { + let PhysicalSize { width, height } = size; + (cast_dimension_to_hint(width), cast_dimension_to_hint(height)) +} + +/// Use the above strategy to cast a size into a hinted size. +fn cast_size_to_hint(size: Size, scale_factor: f64) -> (i32, i32) { + match size { + Size::Physical(size) => cast_physical_size_to_hint(size), + Size::Logical(size) => size.to_physical::<i32>(scale_factor).into(), + } +} diff --git a/app/vendor/rune/vendor/winit/src/platform_impl/linux/x11/xdisplay.rs b/app/vendor/rune/vendor/winit/src/platform_impl/linux/x11/xdisplay.rs new file mode 100644 index 0000000..79da0d1 --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/platform_impl/linux/x11/xdisplay.rs @@ -0,0 +1,356 @@ +use std::collections::HashMap; +use std::error::Error; +use std::sync::atomic::{AtomicU32, Ordering}; +use std::sync::{Arc, Mutex, RwLock, RwLockReadGuard}; +use std::{fmt, ptr}; + +use crate::window::CursorIcon; + +use super::atoms::Atoms; +use super::ffi; +use super::monitor::MonitorHandle; +use x11rb::connection::Connection; +use x11rb::protocol::randr::ConnectionExt as _; +use x11rb::protocol::xproto::{self, ConnectionExt}; +use x11rb::resource_manager; +use x11rb::xcb_ffi::XCBConnection; + +/// A connection to an X server. +pub struct XConnection { + pub xlib: ffi::Xlib, + pub xcursor: ffi::Xcursor, + + // TODO(notgull): I'd like to remove this, but apparently Xlib and Xinput2 are tied together + // for some reason. + pub xinput2: ffi::XInput2, + + pub display: *mut ffi::Display, + + /// The manager for the XCB connection. + /// + /// The `Option` ensures that we can drop it before we close the `Display`. + xcb: Option<XCBConnection>, + + /// The atoms used by `winit`. + /// + /// This is a large structure, so I've elected to Box it to make accessing the fields of + /// this struct easier. Feel free to unbox it if you like kicking puppies. + atoms: Box<Atoms>, + + /// The index of the default screen. + default_screen: usize, + + /// The last timestamp received by this connection. + timestamp: AtomicU32, + + /// List of monitor handles. + pub monitor_handles: Mutex<Option<Vec<MonitorHandle>>>, + + /// The resource database. + database: RwLock<resource_manager::Database>, + + /// RandR version. + randr_version: (u32, u32), + + /// Atom for the XSettings screen. + xsettings_screen: Option<xproto::Atom>, + + pub latest_error: Mutex<Option<XError>>, + pub cursor_cache: Mutex<HashMap<Option<CursorIcon>, ffi::Cursor>>, +} + +unsafe impl Send for XConnection {} +unsafe impl Sync for XConnection {} + +pub type XErrorHandler = + Option<unsafe extern "C" fn(*mut ffi::Display, *mut ffi::XErrorEvent) -> std::os::raw::c_int>; + +impl XConnection { + pub fn new(error_handler: XErrorHandler) -> Result<XConnection, XNotSupported> { + // opening the libraries + let xlib = ffi::Xlib::open()?; + let xcursor = ffi::Xcursor::open()?; + let xlib_xcb = ffi::Xlib_xcb::open()?; + let xinput2 = ffi::XInput2::open()?; + + unsafe { (xlib.XInitThreads)() }; + unsafe { (xlib.XSetErrorHandler)(error_handler) }; + + // calling XOpenDisplay + let display = unsafe { + let display = (xlib.XOpenDisplay)(ptr::null()); + if display.is_null() { + return Err(XNotSupported::XOpenDisplayFailed); + } + display + }; + + // Open the x11rb XCB connection. + let xcb = { + // Get a pointer to the underlying XCB connection + let xcb_connection = + unsafe { (xlib_xcb.XGetXCBConnection)(display as *mut ffi::Display) }; + assert!(!xcb_connection.is_null()); + + // Wrap the XCB connection in an x11rb XCB connection + let conn = + unsafe { XCBConnection::from_raw_xcb_connection(xcb_connection.cast(), false) }; + + conn.map_err(|e| XNotSupported::XcbConversionError(Arc::new(WrapConnectError(e))))? + }; + + // Get the default screen. + let default_screen = unsafe { (xlib.XDefaultScreen)(display) } as usize; + + // Load the database. + let database = resource_manager::new_from_default(&xcb) + .map_err(|e| XNotSupported::XcbConversionError(Arc::new(e)))?; + + // Load the RandR version. + let randr_version = xcb + .randr_query_version(1, 3) + .expect("failed to request XRandR version") + .reply() + .expect("failed to query XRandR version"); + + let xsettings_screen = Self::new_xsettings_screen(&xcb, default_screen); + if xsettings_screen.is_none() { + tracing::warn!("error setting XSETTINGS; Xft options won't reload automatically") + } + + // Fetch atoms. + let atoms = Atoms::new(&xcb) + .map_err(|e| XNotSupported::XcbConversionError(Arc::new(e)))? + .reply() + .map_err(|e| XNotSupported::XcbConversionError(Arc::new(e)))?; + + Ok(XConnection { + xlib, + xcursor, + xinput2, + display, + xcb: Some(xcb), + atoms: Box::new(atoms), + default_screen, + timestamp: AtomicU32::new(0), + latest_error: Mutex::new(None), + monitor_handles: Mutex::new(None), + database: RwLock::new(database), + cursor_cache: Default::default(), + randr_version: (randr_version.major_version, randr_version.minor_version), + xsettings_screen, + }) + } + + fn new_xsettings_screen(xcb: &XCBConnection, default_screen: usize) -> Option<xproto::Atom> { + // Fetch the _XSETTINGS_S[screen number] atom. + let xsettings_screen = xcb + .intern_atom(false, format!("_XSETTINGS_S{default_screen}").as_bytes()) + .ok()? + .reply() + .ok()? + .atom; + + // Get PropertyNotify events from the XSETTINGS window. + // TODO: The XSETTINGS window here can change. In the future, listen for DestroyNotify on + // this window in order to accommodate for a changed window here. + let selector_window = xcb.get_selection_owner(xsettings_screen).ok()?.reply().ok()?.owner; + + xcb.change_window_attributes( + selector_window, + &xproto::ChangeWindowAttributesAux::new() + .event_mask(xproto::EventMask::PROPERTY_CHANGE), + ) + .ok()? + .check() + .ok()?; + + Some(xsettings_screen) + } + + /// Checks whether an error has been triggered by the previous function calls. + #[inline] + pub fn check_errors(&self) -> Result<(), XError> { + let error = self.latest_error.lock().unwrap().take(); + if let Some(error) = error { + Err(error) + } else { + Ok(()) + } + } + + #[inline] + pub fn randr_version(&self) -> (u32, u32) { + self.randr_version + } + + /// Get the underlying XCB connection. + #[inline] + pub fn xcb_connection(&self) -> &XCBConnection { + self.xcb.as_ref().expect("xcb_connection somehow called after drop?") + } + + /// Get the list of atoms. + #[inline] + pub fn atoms(&self) -> &Atoms { + &self.atoms + } + + /// Get the index of the default screen. + #[inline] + pub fn default_screen_index(&self) -> usize { + self.default_screen + } + + /// Get the default screen. + #[inline] + pub fn default_root(&self) -> &xproto::Screen { + &self.xcb_connection().setup().roots[self.default_screen] + } + + /// Get the resource database. + #[inline] + pub fn database(&self) -> RwLockReadGuard<'_, resource_manager::Database> { + self.database.read().unwrap_or_else(|e| e.into_inner()) + } + + /// Reload the resource database. + #[inline] + pub fn reload_database(&self) -> Result<(), super::X11Error> { + let database = resource_manager::new_from_default(self.xcb_connection())?; + *self.database.write().unwrap_or_else(|e| e.into_inner()) = database; + Ok(()) + } + + /// Get the latest timestamp. + #[inline] + pub fn timestamp(&self) -> u32 { + self.timestamp.load(Ordering::Relaxed) + } + + /// Set the last witnessed timestamp. + #[inline] + pub fn set_timestamp(&self, timestamp: u32) { + // Store the timestamp in the slot if it's greater than the last one. + let mut last_timestamp = self.timestamp.load(Ordering::Relaxed); + loop { + if (timestamp as i32).wrapping_sub(last_timestamp as i32) <= 0 { + break; + } + + match self.timestamp.compare_exchange( + last_timestamp, + timestamp, + Ordering::Relaxed, + Ordering::Relaxed, + ) { + Ok(_) => break, + Err(x) => last_timestamp = x, + } + } + } + + /// Get the atom for Xsettings. + #[inline] + pub fn xsettings_screen(&self) -> Option<xproto::Atom> { + self.xsettings_screen + } +} + +impl fmt::Debug for XConnection { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + self.display.fmt(f) + } +} + +impl Drop for XConnection { + #[inline] + fn drop(&mut self) { + self.xcb = None; + unsafe { (self.xlib.XCloseDisplay)(self.display) }; + } +} + +/// Error triggered by xlib. +#[derive(Debug, Clone)] +pub struct XError { + pub description: String, + pub error_code: u8, + pub request_code: u8, + pub minor_code: u8, +} + +impl Error for XError {} + +impl fmt::Display for XError { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> { + write!( + formatter, + "X error: {} (code: {}, request code: {}, minor code: {})", + self.description, self.error_code, self.request_code, self.minor_code + ) + } +} + +/// Error returned if this system doesn't have XLib or can't create an X connection. +#[derive(Clone, Debug)] +pub enum XNotSupported { + /// Failed to load one or several shared libraries. + LibraryOpenError(ffi::OpenError), + + /// Connecting to the X server with `XOpenDisplay` failed. + XOpenDisplayFailed, // TODO: add better message. + + /// We encountered an error while converting the connection to XCB. + XcbConversionError(Arc<dyn Error + Send + Sync + 'static>), +} + +impl From<ffi::OpenError> for XNotSupported { + #[inline] + fn from(err: ffi::OpenError) -> XNotSupported { + XNotSupported::LibraryOpenError(err) + } +} + +impl XNotSupported { + fn description(&self) -> &'static str { + match self { + XNotSupported::LibraryOpenError(_) => "Failed to load one of xlib's shared libraries", + XNotSupported::XOpenDisplayFailed => "Failed to open connection to X server", + XNotSupported::XcbConversionError(_) => "Failed to convert Xlib connection to XCB", + } + } +} + +impl Error for XNotSupported { + #[inline] + fn source(&self) -> Option<&(dyn Error + 'static)> { + match *self { + XNotSupported::LibraryOpenError(ref err) => Some(err), + XNotSupported::XcbConversionError(ref err) => Some(&**err), + _ => None, + } + } +} + +impl fmt::Display for XNotSupported { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> { + formatter.write_str(self.description()) + } +} + +/// A newtype wrapper around a `ConnectError` that can't be accessed by downstream libraries. +/// +/// Without this, `x11rb` would become a public dependency. +#[derive(Debug)] +struct WrapConnectError(x11rb::rust_connection::ConnectError); + +impl fmt::Display for WrapConnectError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + fmt::Display::fmt(&self.0, f) + } +} + +impl Error for WrapConnectError { + // We can't implement `source()` here or otherwise risk exposing `x11rb`. +} diff --git a/app/vendor/rune/vendor/winit/src/platform_impl/linux/x11/xsettings.rs b/app/vendor/rune/vendor/winit/src/platform_impl/linux/x11/xsettings.rs new file mode 100644 index 0000000..dd5b074 --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/platform_impl/linux/x11/xsettings.rs @@ -0,0 +1,325 @@ +//! Parser for the xsettings data format. +//! +//! Some of this code is referenced from [here]. +//! +//! [here]: https://github.com/derat/xsettingsd + +use std::iter; +use std::num::NonZeroUsize; + +use x11rb::protocol::xproto::{self, ConnectionExt}; + +use super::atoms::*; +use super::XConnection; + +type Result<T> = core::result::Result<T, ParserError>; + +const DPI_NAME: &[u8] = b"Xft/DPI"; +const DPI_MULTIPLIER: f64 = 1024.0; +const LITTLE_ENDIAN: u8 = b'l'; +const BIG_ENDIAN: u8 = b'B'; + +impl XConnection { + /// Get the DPI from XSettings. + pub(crate) fn xsettings_dpi( + &self, + xsettings_screen: xproto::Atom, + ) -> core::result::Result<Option<f64>, super::X11Error> { + let atoms = self.atoms(); + + // Get the current owner of the screen's settings. + let owner = self.xcb_connection().get_selection_owner(xsettings_screen)?.reply()?; + + // Read the _XSETTINGS_SETTINGS property. + let data: Vec<u8> = + self.get_property(owner.owner, atoms[_XSETTINGS_SETTINGS], atoms[_XSETTINGS_SETTINGS])?; + + // Parse the property. + let dpi_setting = read_settings(&data)? + .find(|res| res.as_ref().map_or(true, |s| s.name == DPI_NAME)) + .transpose()?; + if let Some(dpi_setting) = dpi_setting { + let base_dpi = match dpi_setting.data { + SettingData::Integer(dpi) => dpi as f64, + SettingData::String(_) => { + return Err(ParserError::BadType(SettingType::String).into()) + }, + SettingData::Color(_) => { + return Err(ParserError::BadType(SettingType::Color).into()) + }, + }; + + Ok(Some(base_dpi / DPI_MULTIPLIER)) + } else { + Ok(None) + } + } +} + +/// Read over the settings in the block of data. +fn read_settings(data: &[u8]) -> Result<impl Iterator<Item = Result<Setting<'_>>> + '_> { + // Create a parser. This automatically parses the first 8 bytes for metadata. + let mut parser = Parser::new(data)?; + + // Read the total number of settings. + let total_settings = parser.i32()?; + + // Iterate over the settings. + let iter = iter::repeat_with(move || Setting::parse(&mut parser)).take(total_settings as usize); + Ok(iter) +} + +/// A setting in the settings list. +struct Setting<'a> { + /// The name of the setting. + name: &'a [u8], + + /// The data contained in the setting. + data: SettingData<'a>, +} + +/// The data contained in a setting. +enum SettingData<'a> { + Integer(i32), + String(#[allow(dead_code)] &'a [u8]), + Color(#[allow(dead_code)] [i16; 4]), +} + +impl<'a> Setting<'a> { + /// Parse a new `SettingData`. + fn parse(parser: &mut Parser<'a>) -> Result<Self> { + // Read the type. + let ty: SettingType = parser.i8()?.try_into()?; + + // Read another byte of padding. + parser.advance(1)?; + + // Read the name of the setting. + let name_len = parser.i16()?; + let name = parser.advance(name_len as usize)?; + parser.pad(name.len(), 4)?; + + // Ignore the serial number. + parser.advance(4)?; + + let data = match ty { + SettingType::Integer => { + // Read a 32-bit integer. + SettingData::Integer(parser.i32()?) + }, + + SettingType::String => { + // Read the data. + let data_len = parser.i32()?; + let data = parser.advance(data_len as usize)?; + parser.pad(data.len(), 4)?; + + SettingData::String(data) + }, + + SettingType::Color => { + // Read i16's of color. + let (red, blue, green, alpha) = + (parser.i16()?, parser.i16()?, parser.i16()?, parser.i16()?); + + SettingData::Color([red, blue, green, alpha]) + }, + }; + + Ok(Setting { name, data }) + } +} + +#[derive(Debug)] +pub enum SettingType { + Integer = 0, + String = 1, + Color = 2, +} + +impl TryFrom<i8> for SettingType { + type Error = ParserError; + + fn try_from(value: i8) -> Result<Self> { + Ok(match value { + 0 => Self::Integer, + 1 => Self::String, + 2 => Self::Color, + x => return Err(ParserError::InvalidType(x)), + }) + } +} + +/// Parser for the incoming byte stream. +struct Parser<'a> { + bytes: &'a [u8], + endianness: Endianness, +} + +impl<'a> Parser<'a> { + /// Create a new parser. + fn new(bytes: &'a [u8]) -> Result<Self> { + let (endianness, bytes) = bytes.split_first().ok_or_else(|| ParserError::ran_out(1, 0))?; + let endianness = match *endianness { + BIG_ENDIAN => Endianness::Big, + LITTLE_ENDIAN => Endianness::Little, + _ => Endianness::native(), + }; + + Ok(Self { + // Ignore three bytes of padding and the four-byte serial. + bytes: bytes.get(7..).ok_or_else(|| ParserError::ran_out(7, bytes.len()))?, + endianness, + }) + } + + /// Get a slice of bytes. + fn advance(&mut self, n: usize) -> Result<&'a [u8]> { + if n == 0 { + return Ok(&[]); + } + + if n > self.bytes.len() { + Err(ParserError::ran_out(n, self.bytes.len())) + } else { + let (part, rem) = self.bytes.split_at(n); + self.bytes = rem; + Ok(part) + } + } + + /// Skip some padding. + fn pad(&mut self, size: usize, pad: usize) -> Result<()> { + let advance = (pad - (size % pad)) % pad; + self.advance(advance)?; + Ok(()) + } + + /// Get a single byte. + fn i8(&mut self) -> Result<i8> { + self.advance(1).map(|s| s[0] as i8) + } + + /// Get two bytes. + fn i16(&mut self) -> Result<i16> { + self.advance(2).map(|s| { + let bytes: &[u8; 2] = s.try_into().unwrap(); + match self.endianness { + Endianness::Big => i16::from_be_bytes(*bytes), + Endianness::Little => i16::from_le_bytes(*bytes), + } + }) + } + + /// Get four bytes. + fn i32(&mut self) -> Result<i32> { + self.advance(4).map(|s| { + let bytes: &[u8; 4] = s.try_into().unwrap(); + match self.endianness { + Endianness::Big => i32::from_be_bytes(*bytes), + Endianness::Little => i32::from_le_bytes(*bytes), + } + }) + } +} + +/// Endianness of the incoming data. +enum Endianness { + Little, + Big, +} + +impl Endianness { + #[cfg(target_endian = "little")] + fn native() -> Self { + Endianness::Little + } + + #[cfg(target_endian = "big")] + fn native() -> Self { + Endianness::Big + } +} + +/// Parser errors. +#[allow(dead_code)] +#[derive(Debug)] +pub enum ParserError { + /// Ran out of bytes. + NoMoreBytes { expected: NonZeroUsize, found: usize }, + + /// Invalid type. + InvalidType(i8), + + /// Bad setting type. + BadType(SettingType), +} + +impl ParserError { + fn ran_out(expected: usize, found: usize) -> ParserError { + let expected = NonZeroUsize::new(expected).unwrap(); + Self::NoMoreBytes { expected, found } + } +} + +#[cfg(test)] +/// Tests for the XSETTINGS parser. +mod tests { + use super::*; + + const XSETTINGS: &str = include_str!("tests/xsettings.dat"); + + #[test] + fn empty() { + let err = match read_settings(&[]) { + Ok(_) => panic!(), + Err(err) => err, + }; + match err { + ParserError::NoMoreBytes { expected, found } => { + assert_eq!(expected.get(), 1); + assert_eq!(found, 0); + }, + + _ => panic!(), + } + } + + #[test] + fn parse_xsettings() { + let data = XSETTINGS + .trim() + .split(',') + .map(|tok| { + let val = tok.strip_prefix("0x").unwrap(); + u8::from_str_radix(val, 16).unwrap() + }) + .collect::<Vec<_>>(); + + let settings = read_settings(&data).unwrap().collect::<Result<Vec<_>>>().unwrap(); + + let dpi = settings.iter().find(|s| s.name == b"Xft/DPI").unwrap(); + assert_int(&dpi.data, 96 * 1024); + let hinting = settings.iter().find(|s| s.name == b"Xft/Hinting").unwrap(); + assert_int(&hinting.data, 1); + + let rgba = settings.iter().find(|s| s.name == b"Xft/RGBA").unwrap(); + assert_string(&rgba.data, "rgb"); + let lcd = settings.iter().find(|s| s.name == b"Xft/Lcdfilter").unwrap(); + assert_string(&lcd.data, "lcddefault"); + } + + fn assert_string(dat: &SettingData<'_>, s: &str) { + match dat { + SettingData::String(left) => assert_eq!(*left, s.as_bytes()), + _ => panic!("invalid data type"), + } + } + + fn assert_int(dat: &SettingData<'_>, i: i32) { + match dat { + SettingData::Integer(left) => assert_eq!(*left, i), + _ => panic!("invalid data type"), + } + } +} diff --git a/app/vendor/rune/vendor/winit/src/platform_impl/macos/app.rs b/app/vendor/rune/vendor/winit/src/platform_impl/macos/app.rs new file mode 100644 index 0000000..4fb95db --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/platform_impl/macos/app.rs @@ -0,0 +1,195 @@ +#![allow(clippy::unnecessary_cast)] +#![allow(unknown_lints)] // New lint below +#![allow(static_mut_refs)] // Uses `MainThreadBound` in new version. + +use std::cell::Cell; +use std::mem; + +use objc2::runtime::{Imp, Sel}; +use objc2::sel; +use objc2_app_kit::{NSApplication, NSEvent, NSEventModifierFlags, NSEventType}; +use objc2_foundation::MainThreadMarker; + +use super::app_state::ApplicationDelegate; +use crate::event::{DeviceEvent, ElementState}; + +type SendEvent = extern "C" fn(&NSApplication, Sel, &NSEvent); + +// NOTE: Only used on the main thread. Ideally, we'd use `MainThreadBound`, but that isn't +// constructible from `const` with this `objc2` version. +static mut ORIGINAL: Cell<Option<SendEvent>> = Cell::new(None); + +extern "C" fn send_event(app: &NSApplication, sel: Sel, event: &NSEvent) { + let mtm = MainThreadMarker::from(app); + + // Normally, holding Cmd + any key never sends us a `keyUp` event for that key. + // Overriding `sendEvent:` fixes that. (https://stackoverflow.com/a/15294196) + // Fun fact: Firefox still has this bug! (https://bugzilla.mozilla.org/show_bug.cgi?id=1299553) + // + // For posterity, there are some undocumented event types + // (https://github.com/servo/cocoa-rs/issues/155) + // but that doesn't really matter here. + let event_type = unsafe { event.r#type() }; + let modifier_flags = unsafe { event.modifierFlags() }; + if event_type == NSEventType::KeyUp + && modifier_flags.contains(NSEventModifierFlags::NSEventModifierFlagCommand) + { + if let Some(key_window) = app.keyWindow() { + key_window.sendEvent(event); + } + return; + } + + // Events are generally scoped to the window level, so the best way + // to get device events is to listen for them on NSApplication. + let delegate = ApplicationDelegate::get(mtm); + maybe_dispatch_device_event(&delegate, event); + + let _ = mtm; + let original = unsafe { ORIGINAL.get().expect("no existing sendEvent: handler set") }; + original(app, sel, event) +} + +/// Override the [`sendEvent:`][NSApplication::sendEvent] method on the given application class. +/// +/// The previous implementation created a subclass of [`NSApplication`], however we would like to +/// give the user full control over their `NSApplication`, so we override the method here using +/// method swizzling instead. +/// +/// This _should_ also allow two versions of Winit to exist in the same application. +/// +/// See the following links for more info on method swizzling: +/// - <https://nshipster.com/method-swizzling/> +/// - <https://spin.atomicobject.com/method-swizzling-objective-c/> +/// - <https://web.archive.org/web/20130308110627/http://cocoadev.com/wiki/MethodSwizzling> +/// +/// NOTE: This function assumes that the passed in application object is the one returned from +/// [`NSApplication::sharedApplication`], i.e. the one and only global shared application object. +/// For testing though, we allow it to be a different object. +pub(crate) fn override_send_event(global_app: &NSApplication) { + let mtm = MainThreadMarker::from(global_app); + let class = global_app.class(); + + let method = + class.instance_method(sel!(sendEvent:)).expect("NSApplication must have sendEvent: method"); + + // SAFETY: Converting our `sendEvent:` implementation to an IMP. + let overridden = unsafe { mem::transmute::<SendEvent, Imp>(send_event) }; + + // If we've already overridden the method, don't do anything. + // FIXME(madsmtm): Use `std::ptr::fn_addr_eq` (Rust 1.85) once available in MSRV. + #[allow(unknown_lints, unpredictable_function_pointer_comparisons)] + if overridden == method.implementation() { + return; + } + + // SAFETY: Our implementation has: + // 1. The same signature as `sendEvent:`. + // 2. Does not impose extra safety requirements on callers. + let original = unsafe { method.set_implementation(overridden) }; + + // SAFETY: This is the actual signature of `sendEvent:`. + let original = unsafe { mem::transmute::<Imp, SendEvent>(original) }; + + // NOTE: If NSApplication was safe to use from multiple threads, then this would potentially be + // a (checked) race-condition, since one could call `sendEvent:` before the original had been + // stored here. + // + // It is only usable from the main thread, however, so we're good! + let _ = mtm; + unsafe { ORIGINAL.set(Some(original)) }; +} + +fn maybe_dispatch_device_event(delegate: &ApplicationDelegate, event: &NSEvent) { + let event_type = unsafe { event.r#type() }; + #[allow(non_upper_case_globals)] + match event_type { + NSEventType::MouseMoved + | NSEventType::LeftMouseDragged + | NSEventType::OtherMouseDragged + | NSEventType::RightMouseDragged => { + let delta_x = unsafe { event.deltaX() } as f64; + let delta_y = unsafe { event.deltaY() } as f64; + + if delta_x != 0.0 { + delegate.maybe_queue_device_event(DeviceEvent::Motion { axis: 0, value: delta_x }); + } + + if delta_y != 0.0 { + delegate.maybe_queue_device_event(DeviceEvent::Motion { axis: 1, value: delta_y }) + } + + if delta_x != 0.0 || delta_y != 0.0 { + delegate.maybe_queue_device_event(DeviceEvent::MouseMotion { + delta: (delta_x, delta_y), + }); + } + }, + NSEventType::LeftMouseDown | NSEventType::RightMouseDown | NSEventType::OtherMouseDown => { + delegate.maybe_queue_device_event(DeviceEvent::Button { + button: unsafe { event.buttonNumber() } as u32, + state: ElementState::Pressed, + }); + }, + NSEventType::LeftMouseUp | NSEventType::RightMouseUp | NSEventType::OtherMouseUp => { + delegate.maybe_queue_device_event(DeviceEvent::Button { + button: unsafe { event.buttonNumber() } as u32, + state: ElementState::Released, + }); + }, + _ => (), + } +} + +#[cfg(test)] +mod tests { + use objc2::rc::Retained; + use objc2::{declare_class, msg_send_id, mutability, ClassType, DeclaredClass}; + + use super::*; + + #[test] + fn test_override() { + // FIXME(madsmtm): Ensure this always runs (maybe use cargo-nextest or `--test-threads=1`?) + let Some(mtm) = MainThreadMarker::new() else { return }; + + // Create a new application, without making it the shared application. + let app = unsafe { NSApplication::new(mtm) }; + override_send_event(&app); + // Test calling twice works. + override_send_event(&app); + + // FIXME(madsmtm): Can't test this yet, need some way to mock AppState. + // unsafe { + // let event = super::super::event::dummy_event().unwrap(); + // app.sendEvent(&event) + // } + } + + #[test] + fn test_custom_class() { + let Some(_mtm) = MainThreadMarker::new() else { return }; + + declare_class!( + struct TestApplication; + + unsafe impl ClassType for TestApplication { + type Super = NSApplication; + type Mutability = mutability::MainThreadOnly; + const NAME: &'static str = "TestApplication"; + } + + impl DeclaredClass for TestApplication {} + + unsafe impl TestApplication { + #[method(sendEvent:)] + fn send_event(&self, _event: &NSEvent) { + todo!() + } + } + ); + + let app: Retained<TestApplication> = unsafe { msg_send_id![TestApplication::class(), new] }; + override_send_event(&app); + } +} diff --git a/app/vendor/rune/vendor/winit/src/platform_impl/macos/app_state.rs b/app/vendor/rune/vendor/winit/src/platform_impl/macos/app_state.rs new file mode 100644 index 0000000..dd2ccd1 --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/platform_impl/macos/app_state.rs @@ -0,0 +1,446 @@ +use std::cell::{Cell, RefCell}; +use std::mem; +use std::rc::Weak; +use std::time::Instant; + +use objc2::rc::Retained; +use objc2::{declare_class, msg_send_id, mutability, ClassType, DeclaredClass}; +use objc2_app_kit::{ + NSApplication, NSApplicationActivationPolicy, NSApplicationDelegate, NSRunningApplication, +}; +use objc2_foundation::{MainThreadMarker, NSNotification, NSObject, NSObjectProtocol}; + +use super::event_handler::EventHandler; +use super::event_loop::{notify_windows_of_exit, stop_app_immediately, ActiveEventLoop, PanicInfo}; +use super::observer::{EventLoopWaker, RunLoop}; +use super::{menu, WindowId, DEVICE_ID}; +use crate::event::{DeviceEvent, Event, StartCause, WindowEvent}; +use crate::event_loop::{ActiveEventLoop as RootActiveEventLoop, ControlFlow}; +use crate::window::WindowId as RootWindowId; + +#[derive(Debug)] +pub(super) struct AppState { + activation_policy: Option<NSApplicationActivationPolicy>, + default_menu: bool, + activate_ignoring_other_apps: bool, + run_loop: RunLoop, + event_handler: EventHandler, + stop_on_launch: Cell<bool>, + stop_before_wait: Cell<bool>, + stop_after_wait: Cell<bool>, + stop_on_redraw: Cell<bool>, + /// Whether `applicationDidFinishLaunching:` has been run or not. + is_launched: Cell<bool>, + /// Whether an `EventLoop` is currently running. + is_running: Cell<bool>, + /// Whether the user has requested the event loop to exit. + exit: Cell<bool>, + control_flow: Cell<ControlFlow>, + waker: RefCell<EventLoopWaker>, + start_time: Cell<Option<Instant>>, + wait_timeout: Cell<Option<Instant>>, + pending_redraw: RefCell<Vec<WindowId>>, + // NOTE: This is strongly referenced by our `NSWindowDelegate` and our `NSView` subclass, and + // as such should be careful to not add fields that, in turn, strongly reference those. +} + +declare_class!( + #[derive(Debug)] + pub(super) struct ApplicationDelegate; + + unsafe impl ClassType for ApplicationDelegate { + type Super = NSObject; + type Mutability = mutability::MainThreadOnly; + const NAME: &'static str = "WinitApplicationDelegate"; + } + + impl DeclaredClass for ApplicationDelegate { + type Ivars = AppState; + } + + unsafe impl NSObjectProtocol for ApplicationDelegate {} + + unsafe impl NSApplicationDelegate for ApplicationDelegate { + #[method(applicationDidFinishLaunching:)] + fn app_did_finish_launching(&self, notification: &NSNotification) { + self.did_finish_launching(notification) + } + + #[method(applicationWillTerminate:)] + fn app_will_terminate(&self, notification: &NSNotification) { + self.will_terminate(notification) + } + } +); + +impl ApplicationDelegate { + pub(super) fn new( + mtm: MainThreadMarker, + activation_policy: Option<NSApplicationActivationPolicy>, + default_menu: bool, + activate_ignoring_other_apps: bool, + ) -> Retained<Self> { + let this = mtm.alloc().set_ivars(AppState { + activation_policy, + default_menu, + activate_ignoring_other_apps, + run_loop: RunLoop::main(mtm), + event_handler: EventHandler::new(), + stop_on_launch: Cell::new(false), + stop_before_wait: Cell::new(false), + stop_after_wait: Cell::new(false), + stop_on_redraw: Cell::new(false), + is_launched: Cell::new(false), + is_running: Cell::new(false), + exit: Cell::new(false), + control_flow: Cell::new(ControlFlow::default()), + waker: RefCell::new(EventLoopWaker::new()), + start_time: Cell::new(None), + wait_timeout: Cell::new(None), + pending_redraw: RefCell::new(vec![]), + }); + unsafe { msg_send_id![super(this), init] } + } + + // NOTE: This will, globally, only be run once, no matter how many + // `EventLoop`s the user creates. + fn did_finish_launching(&self, _notification: &NSNotification) { + trace_scope!("applicationDidFinishLaunching:"); + self.ivars().is_launched.set(true); + + let mtm = MainThreadMarker::from(self); + let app = NSApplication::sharedApplication(mtm); + // We need to delay setting the activation policy and activating the app + // until `applicationDidFinishLaunching` has been called. Otherwise the + // menu bar is initially unresponsive on macOS 10.15. + // If no activation policy is explicitly provided, do not set it at all + // to allow the package manifest to define behavior via LSUIElement. + if let Some(activation_policy) = self.ivars().activation_policy { + app.setActivationPolicy(activation_policy); + } else { + // If no activation policy is explicitly provided, and the application + // is bundled, do not set the activation policy at all, to allow the + // package manifest to define the behavior via LSUIElement. + // + // See: + // - https://github.com/rust-windowing/winit/issues/261 + // - https://github.com/rust-windowing/winit/issues/3958 + let is_bundled = + unsafe { NSRunningApplication::currentApplication().bundleIdentifier().is_some() }; + if !is_bundled { + app.setActivationPolicy(NSApplicationActivationPolicy::Regular); + } + } + + window_activation_hack(&app); + #[allow(deprecated)] + app.activateIgnoringOtherApps(self.ivars().activate_ignoring_other_apps); + + if self.ivars().default_menu { + // The menubar initialization should be before the `NewEvents` event, to allow + // overriding of the default menu even if it's created + menu::initialize(&app); + } + + self.ivars().waker.borrow_mut().start(); + + self.set_is_running(true); + self.dispatch_init_events(); + + // If the application is being launched via `EventLoop::pump_app_events()` then we'll + // want to stop the app once it is launched (and return to the external loop) + // + // In this case we still want to consider Winit's `EventLoop` to be "running", + // so we call `start_running()` above. + if self.ivars().stop_on_launch.get() { + // NOTE: the original idea had been to only stop the underlying `RunLoop` + // for the app but that didn't work as expected (`-[NSApplication run]` + // effectively ignored the attempt to stop the RunLoop and re-started it). + // + // So we return from `pump_events` by stopping the application. + let app = NSApplication::sharedApplication(mtm); + stop_app_immediately(&app); + } + } + + fn will_terminate(&self, _notification: &NSNotification) { + trace_scope!("applicationWillTerminate:"); + let mtm = MainThreadMarker::from(self); + let app = NSApplication::sharedApplication(mtm); + notify_windows_of_exit(&app); + self.internal_exit(); + } + + pub fn get(mtm: MainThreadMarker) -> Retained<Self> { + let app = NSApplication::sharedApplication(mtm); + let delegate = + unsafe { app.delegate() }.expect("a delegate was not configured on the application"); + if delegate.is_kind_of::<Self>() { + // SAFETY: Just checked that the delegate is an instance of `ApplicationDelegate` + unsafe { Retained::cast(delegate) } + } else { + panic!("tried to get a delegate that was not the one Winit has registered") + } + } + + /// Place the event handler in the application delegate for the duration + /// of the given closure. + pub fn set_event_handler<R>( + &self, + handler: impl FnMut(Event<HandlePendingUserEvents>, &RootActiveEventLoop), + closure: impl FnOnce() -> R, + ) -> R { + self.ivars().event_handler.set(handler, closure) + } + + /// If `pump_events` is called to progress the event loop then we + /// bootstrap the event loop via `-[NSApplication run]` but will use + /// `CFRunLoopRunInMode` for subsequent calls to `pump_events`. + pub fn set_stop_on_launch(&self) { + self.ivars().stop_on_launch.set(true); + } + + pub fn set_stop_before_wait(&self, value: bool) { + self.ivars().stop_before_wait.set(value) + } + + pub fn set_stop_after_wait(&self, value: bool) { + self.ivars().stop_after_wait.set(value) + } + + pub fn set_stop_on_redraw(&self, value: bool) { + self.ivars().stop_on_redraw.set(value) + } + + pub fn set_wait_timeout(&self, value: Option<Instant>) { + self.ivars().wait_timeout.set(value) + } + + /// Clears the `running` state and resets the `control_flow` state when an `EventLoop` exits. + /// + /// NOTE: that if the `NSApplication` has been launched then that state is preserved, + /// and we won't need to re-launch the app if subsequent EventLoops are run. + pub fn internal_exit(&self) { + self.handle_event(Event::LoopExiting); + + self.set_is_running(false); + self.set_stop_on_redraw(false); + self.set_stop_before_wait(false); + self.set_stop_after_wait(false); + self.set_wait_timeout(None); + } + + pub fn is_launched(&self) -> bool { + self.ivars().is_launched.get() + } + + pub fn set_is_running(&self, value: bool) { + self.ivars().is_running.set(value) + } + + pub fn is_running(&self) -> bool { + self.ivars().is_running.get() + } + + pub fn exit(&self) { + self.ivars().exit.set(true) + } + + pub fn clear_exit(&self) { + self.ivars().exit.set(false) + } + + pub fn exiting(&self) -> bool { + self.ivars().exit.get() + } + + pub fn set_control_flow(&self, value: ControlFlow) { + self.ivars().control_flow.set(value) + } + + pub fn control_flow(&self) -> ControlFlow { + self.ivars().control_flow.get() + } + + pub fn maybe_queue_window_event(&self, window_id: WindowId, event: WindowEvent) { + self.maybe_queue_event(Event::WindowEvent { window_id: RootWindowId(window_id), event }); + } + + pub fn handle_window_event(&self, window_id: WindowId, event: WindowEvent) { + self.handle_event(Event::WindowEvent { window_id: RootWindowId(window_id), event }); + } + + pub fn maybe_queue_device_event(&self, event: DeviceEvent) { + self.maybe_queue_event(Event::DeviceEvent { device_id: DEVICE_ID, event }); + } + + pub fn handle_redraw(&self, window_id: WindowId) { + let mtm = MainThreadMarker::from(self); + // Redraw request might come out of order from the OS. + // -> Don't go back into the event handler when our callstack originates from there + if !self.ivars().event_handler.in_use() { + self.handle_event(Event::WindowEvent { + window_id: RootWindowId(window_id), + event: WindowEvent::RedrawRequested, + }); + + // `pump_events` will request to stop immediately _after_ dispatching RedrawRequested + // events as a way to ensure that `pump_events` can't block an external loop + // indefinitely + if self.ivars().stop_on_redraw.get() { + let app = NSApplication::sharedApplication(mtm); + stop_app_immediately(&app); + } + } + } + + pub fn queue_redraw(&self, window_id: WindowId) { + let mut pending_redraw = self.ivars().pending_redraw.borrow_mut(); + if !pending_redraw.contains(&window_id) { + pending_redraw.push(window_id); + } + self.ivars().run_loop.wakeup(); + } + + #[track_caller] + fn maybe_queue_event(&self, event: Event<HandlePendingUserEvents>) { + // Most programmer actions in AppKit (e.g. change window fullscreen, set focused, etc.) + // result in an event being queued, and applied at a later point. + // + // However, it is not documented which actions do this, and which ones are done immediately, + // so to make sure that we don't encounter re-entrancy issues, we first check if we're + // currently handling another event, and if we are, we queue the event instead. + if !self.ivars().event_handler.in_use() { + self.handle_event(event); + } else { + tracing::debug!(?event, "had to queue event since another is currently being handled"); + let this = self.retain(); + self.ivars().run_loop.queue_closure(move || this.handle_event(event)); + } + } + + #[track_caller] + fn handle_event(&self, event: Event<HandlePendingUserEvents>) { + self.ivars().event_handler.handle_event(event, &ActiveEventLoop::new_root(self.retain())) + } + + /// dispatch `NewEvents(Init)` + `Resumed` + pub fn dispatch_init_events(&self) { + self.handle_event(Event::NewEvents(StartCause::Init)); + // NB: For consistency all platforms must emit a 'resumed' event even though macOS + // applications don't themselves have a formal suspend/resume lifecycle. + self.handle_event(Event::Resumed); + } + + // Called by RunLoopObserver after finishing waiting for new events + pub fn wakeup(&self, panic_info: Weak<PanicInfo>) { + let mtm = MainThreadMarker::from(self); + let panic_info = panic_info + .upgrade() + .expect("The panic info must exist here. This failure indicates a developer error."); + + // Return when in event handler due to https://github.com/rust-windowing/winit/issues/1779 + if panic_info.is_panicking() || !self.ivars().event_handler.ready() || !self.is_running() { + return; + } + + if self.ivars().stop_after_wait.get() { + let app = NSApplication::sharedApplication(mtm); + stop_app_immediately(&app); + } + + let start = self.ivars().start_time.get().unwrap(); + let cause = match self.control_flow() { + ControlFlow::Poll => StartCause::Poll, + ControlFlow::Wait => StartCause::WaitCancelled { start, requested_resume: None }, + ControlFlow::WaitUntil(requested_resume) => { + if Instant::now() >= requested_resume { + StartCause::ResumeTimeReached { start, requested_resume } + } else { + StartCause::WaitCancelled { start, requested_resume: Some(requested_resume) } + } + }, + }; + + self.handle_event(Event::NewEvents(cause)); + } + + // Called by RunLoopObserver before waiting for new events + pub fn cleared(&self, panic_info: Weak<PanicInfo>) { + let mtm = MainThreadMarker::from(self); + let panic_info = panic_info + .upgrade() + .expect("The panic info must exist here. This failure indicates a developer error."); + + // Return when in event handler due to https://github.com/rust-windowing/winit/issues/1779 + // XXX: how does it make sense that `event_handler.ready()` can ever return `false` here if + // we're about to return to the `CFRunLoop` to poll for new events? + if panic_info.is_panicking() || !self.ivars().event_handler.ready() || !self.is_running() { + return; + } + + self.handle_event(Event::UserEvent(HandlePendingUserEvents)); + + let redraw = mem::take(&mut *self.ivars().pending_redraw.borrow_mut()); + for window_id in redraw { + self.handle_event(Event::WindowEvent { + window_id: RootWindowId(window_id), + event: WindowEvent::RedrawRequested, + }); + } + + self.handle_event(Event::AboutToWait); + + if self.exiting() { + let app = NSApplication::sharedApplication(mtm); + stop_app_immediately(&app); + notify_windows_of_exit(&app); + } + + if self.ivars().stop_before_wait.get() { + let app = NSApplication::sharedApplication(mtm); + stop_app_immediately(&app); + } + self.ivars().start_time.set(Some(Instant::now())); + let wait_timeout = self.ivars().wait_timeout.get(); // configured by pump_events + let app_timeout = match self.control_flow() { + ControlFlow::Wait => None, + ControlFlow::Poll => Some(Instant::now()), + ControlFlow::WaitUntil(instant) => Some(instant), + }; + self.ivars().waker.borrow_mut().start_at(min_timeout(wait_timeout, app_timeout)); + } +} + +#[derive(Debug)] +pub(crate) struct HandlePendingUserEvents; + +/// Returns the minimum `Option<Instant>`, taking into account that `None` +/// equates to an infinite timeout, not a zero timeout (so can't just use +/// `Option::min`) +fn min_timeout(a: Option<Instant>, b: Option<Instant>) -> Option<Instant> { + a.map_or(b, |a_timeout| b.map_or(Some(a_timeout), |b_timeout| Some(a_timeout.min(b_timeout)))) +} + +/// A hack to make activation of multiple windows work when creating them before +/// `applicationDidFinishLaunching:` / `Event::Event::NewEvents(StartCause::Init)`. +/// +/// Alternative to this would be the user calling `window.set_visible(true)` in +/// `StartCause::Init`. +/// +/// If this becomes too bothersome to maintain, it can probably be removed +/// without too much damage. +fn window_activation_hack(app: &NSApplication) { + // TODO: Proper ordering of the windows + app.windows().into_iter().for_each(|window| { + // Call `makeKeyAndOrderFront` if it was called on the window in `WinitWindow::new` + // This way we preserve the user's desired initial visibility status + // TODO: Also filter on the type/"level" of the window, and maybe other things? + if window.isVisible() { + tracing::trace!("Activating visible window"); + window.makeKeyAndOrderFront(None); + } else { + tracing::trace!("Skipping activating invisible window"); + } + }) +} diff --git a/app/vendor/rune/vendor/winit/src/platform_impl/macos/cursor.rs b/app/vendor/rune/vendor/winit/src/platform_impl/macos/cursor.rs new file mode 100644 index 0000000..9e14e8b --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/platform_impl/macos/cursor.rs @@ -0,0 +1,225 @@ +use std::ffi::c_uchar; +use std::slice; +use std::sync::OnceLock; + +use objc2::rc::Retained; +use objc2::runtime::Sel; +use objc2::{msg_send, msg_send_id, sel, ClassType}; +use objc2_app_kit::{NSBitmapImageRep, NSCursor, NSDeviceRGBColorSpace, NSImage}; +use objc2_foundation::{ + ns_string, NSData, NSDictionary, NSNumber, NSObject, NSObjectProtocol, NSPoint, NSSize, + NSString, +}; + +use crate::cursor::{CursorImage, OnlyCursorImageSource}; +use crate::window::CursorIcon; + +#[derive(Clone, Debug, PartialEq, Eq, Hash)] +pub struct CustomCursor(pub(crate) Retained<NSCursor>); + +// SAFETY: NSCursor is immutable and thread-safe +// TODO(madsmtm): Put this logic in objc2-app-kit itself +unsafe impl Send for CustomCursor {} +unsafe impl Sync for CustomCursor {} + +impl CustomCursor { + pub(crate) fn new(cursor: OnlyCursorImageSource) -> CustomCursor { + Self(cursor_from_image(&cursor.0)) + } +} + +pub(crate) fn cursor_from_image(cursor: &CursorImage) -> Retained<NSCursor> { + let width = cursor.width; + let height = cursor.height; + + let bitmap = unsafe { + NSBitmapImageRep::initWithBitmapDataPlanes_pixelsWide_pixelsHigh_bitsPerSample_samplesPerPixel_hasAlpha_isPlanar_colorSpaceName_bytesPerRow_bitsPerPixel( + NSBitmapImageRep::alloc(), + std::ptr::null_mut::<*mut c_uchar>(), + width as isize, + height as isize, + 8, + 4, + true, + false, + NSDeviceRGBColorSpace, + width as isize * 4, + 32, + ).unwrap() + }; + let bitmap_data = unsafe { slice::from_raw_parts_mut(bitmap.bitmapData(), cursor.rgba.len()) }; + bitmap_data.copy_from_slice(&cursor.rgba); + + let image = unsafe { + NSImage::initWithSize(NSImage::alloc(), NSSize::new(width.into(), height.into())) + }; + unsafe { image.addRepresentation(&bitmap) }; + + let hotspot = NSPoint::new(cursor.hotspot_x as f64, cursor.hotspot_y as f64); + + NSCursor::initWithImage_hotSpot(NSCursor::alloc(), &image, hotspot) +} + +pub(crate) fn default_cursor() -> Retained<NSCursor> { + NSCursor::arrowCursor() +} + +unsafe fn try_cursor_from_selector(sel: Sel) -> Option<Retained<NSCursor>> { + let cls = NSCursor::class(); + if msg_send![cls, respondsToSelector: sel] { + let cursor: Retained<NSCursor> = unsafe { msg_send_id![cls, performSelector: sel] }; + Some(cursor) + } else { + tracing::warn!("cursor `{sel}` appears to be invalid"); + None + } +} + +macro_rules! def_undocumented_cursor { + {$( + $(#[$($m:meta)*])* + fn $name:ident(); + )*} => {$( + $(#[$($m)*])* + #[allow(non_snake_case)] + fn $name() -> Retained<NSCursor> { + unsafe { try_cursor_from_selector(sel!($name)).unwrap_or_else(|| default_cursor()) } + } + )*}; +} + +def_undocumented_cursor!( + // Undocumented cursors: https://stackoverflow.com/a/46635398/5435443 + fn _helpCursor(); + fn _zoomInCursor(); + fn _zoomOutCursor(); + fn _windowResizeNorthEastCursor(); + fn _windowResizeNorthWestCursor(); + fn _windowResizeSouthEastCursor(); + fn _windowResizeSouthWestCursor(); + fn _windowResizeNorthEastSouthWestCursor(); + fn _windowResizeNorthWestSouthEastCursor(); + + // While these two are available, the former just loads a white arrow, + // and the latter loads an ugly deflated beachball! + // pub fn _moveCursor(); + // pub fn _waitCursor(); + + // An even more undocumented cursor... + // https://bugs.eclipse.org/bugs/show_bug.cgi?id=522349 + fn busyButClickableCursor(); +); + +// Note that loading `busybutclickable` with this code won't animate +// the frames; instead you'll just get them all in a column. +unsafe fn load_webkit_cursor(name: &NSString) -> Retained<NSCursor> { + // Snatch a cursor from WebKit; They fit the style of the native + // cursors, and will seem completely standard to macOS users. + // + // https://stackoverflow.com/a/21786835/5435443 + let root = ns_string!( + "/System/Library/Frameworks/ApplicationServices.framework/Versions/A/Frameworks/\ + HIServices.framework/Versions/A/Resources/cursors" + ); + let cursor_path = root.stringByAppendingPathComponent(name); + + let pdf_path = cursor_path.stringByAppendingPathComponent(ns_string!("cursor.pdf")); + let image = NSImage::initByReferencingFile(NSImage::alloc(), &pdf_path).unwrap(); + + // TODO: Handle PLists better + let info_path = cursor_path.stringByAppendingPathComponent(ns_string!("info.plist")); + let info: Retained<NSDictionary<NSObject, NSObject>> = unsafe { + msg_send_id![ + <NSDictionary<NSObject, NSObject>>::class(), + dictionaryWithContentsOfFile: &*info_path, + ] + }; + let mut x = 0.0; + if let Some(n) = info.get(&*ns_string!("hotx")) { + if n.is_kind_of::<NSNumber>() { + let ptr: *const NSObject = n; + let ptr: *const NSNumber = ptr.cast(); + x = unsafe { &*ptr }.as_cgfloat() + } + } + let mut y = 0.0; + if let Some(n) = info.get(&*ns_string!("hotx")) { + if n.is_kind_of::<NSNumber>() { + let ptr: *const NSObject = n; + let ptr: *const NSNumber = ptr.cast(); + y = unsafe { &*ptr }.as_cgfloat() + } + } + + let hotspot = NSPoint::new(x, y); + NSCursor::initWithImage_hotSpot(NSCursor::alloc(), &image, hotspot) +} + +fn webkit_move() -> Retained<NSCursor> { + unsafe { load_webkit_cursor(ns_string!("move")) } +} + +fn webkit_cell() -> Retained<NSCursor> { + unsafe { load_webkit_cursor(ns_string!("cell")) } +} + +pub(crate) fn invisible_cursor() -> Retained<NSCursor> { + // 16x16 GIF data for invisible cursor + // You can reproduce this via ImageMagick. + // $ convert -size 16x16 xc:none cursor.gif + static CURSOR_BYTES: &[u8] = &[ + 0x47, 0x49, 0x46, 0x38, 0x39, 0x61, 0x10, 0x00, 0x10, 0x00, 0xf0, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x21, 0xf9, 0x04, 0x01, 0x00, 0x00, 0x00, 0x00, 0x2c, 0x00, 0x00, + 0x00, 0x00, 0x10, 0x00, 0x10, 0x00, 0x00, 0x02, 0x0e, 0x84, 0x8f, 0xa9, 0xcb, 0xed, 0x0f, + 0xa3, 0x9c, 0xb4, 0xda, 0x8b, 0xb3, 0x3e, 0x05, 0x00, 0x3b, + ]; + + fn new_invisible() -> Retained<NSCursor> { + // TODO: Consider using `dataWithBytesNoCopy:` + let data = NSData::with_bytes(CURSOR_BYTES); + let image = NSImage::initWithData(NSImage::alloc(), &data).unwrap(); + let hotspot = NSPoint::new(0.0, 0.0); + NSCursor::initWithImage_hotSpot(NSCursor::alloc(), &image, hotspot) + } + + // Cache this for efficiency + static CURSOR: OnceLock<CustomCursor> = OnceLock::new(); + CURSOR.get_or_init(|| CustomCursor(new_invisible())).0.clone() +} + +pub(crate) fn cursor_from_icon(icon: CursorIcon) -> Retained<NSCursor> { + match icon { + CursorIcon::Default => default_cursor(), + CursorIcon::Pointer => NSCursor::pointingHandCursor(), + CursorIcon::Grab => NSCursor::openHandCursor(), + CursorIcon::Grabbing => NSCursor::closedHandCursor(), + CursorIcon::Text => NSCursor::IBeamCursor(), + CursorIcon::VerticalText => NSCursor::IBeamCursorForVerticalLayout(), + CursorIcon::Copy => NSCursor::dragCopyCursor(), + CursorIcon::Alias => NSCursor::dragLinkCursor(), + CursorIcon::NotAllowed | CursorIcon::NoDrop => NSCursor::operationNotAllowedCursor(), + CursorIcon::ContextMenu => NSCursor::contextualMenuCursor(), + CursorIcon::Crosshair => NSCursor::crosshairCursor(), + CursorIcon::EResize => NSCursor::resizeRightCursor(), + CursorIcon::NResize => NSCursor::resizeUpCursor(), + CursorIcon::WResize => NSCursor::resizeLeftCursor(), + CursorIcon::SResize => NSCursor::resizeDownCursor(), + CursorIcon::EwResize | CursorIcon::ColResize => NSCursor::resizeLeftRightCursor(), + CursorIcon::NsResize | CursorIcon::RowResize => NSCursor::resizeUpDownCursor(), + CursorIcon::Help => _helpCursor(), + CursorIcon::ZoomIn => _zoomInCursor(), + CursorIcon::ZoomOut => _zoomOutCursor(), + CursorIcon::NeResize => _windowResizeNorthEastCursor(), + CursorIcon::NwResize => _windowResizeNorthWestCursor(), + CursorIcon::SeResize => _windowResizeSouthEastCursor(), + CursorIcon::SwResize => _windowResizeSouthWestCursor(), + CursorIcon::NeswResize => _windowResizeNorthEastSouthWestCursor(), + CursorIcon::NwseResize => _windowResizeNorthWestSouthEastCursor(), + // This is the wrong semantics for `Wait`, but it's the same as + // what's used in Safari and Chrome. + CursorIcon::Wait | CursorIcon::Progress => busyButClickableCursor(), + CursorIcon::Move | CursorIcon::AllScroll => webkit_move(), + CursorIcon::Cell => webkit_cell(), + _ => default_cursor(), + } +} diff --git a/app/vendor/rune/vendor/winit/src/platform_impl/macos/event.rs b/app/vendor/rune/vendor/winit/src/platform_impl/macos/event.rs new file mode 100644 index 0000000..9b7f35b --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/platform_impl/macos/event.rs @@ -0,0 +1,616 @@ +use std::ffi::c_void; + +use core_foundation::base::CFRelease; +use core_foundation::data::{CFDataGetBytePtr, CFDataRef}; +use objc2::rc::Retained; +use objc2_app_kit::{NSEvent, NSEventModifierFlags, NSEventSubtype, NSEventType}; +use objc2_foundation::{run_on_main, NSPoint}; +use smol_str::SmolStr; + +use crate::event::{ElementState, KeyEvent, Modifiers}; +use crate::keyboard::{ + Key, KeyCode, KeyLocation, ModifiersKeys, ModifiersState, NamedKey, NativeKey, NativeKeyCode, + PhysicalKey, +}; +use crate::platform_impl::platform::ffi; + +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub struct KeyEventExtra { + pub text_with_all_modifiers: Option<SmolStr>, + pub key_without_modifiers: Key, +} + +/// Ignores ALL modifiers. +pub fn get_modifierless_char(scancode: u16) -> Key { + let mut string = [0; 16]; + let input_source; + let layout; + unsafe { + input_source = ffi::TISCopyCurrentKeyboardLayoutInputSource(); + if input_source.is_null() { + tracing::error!("`TISCopyCurrentKeyboardLayoutInputSource` returned null ptr"); + return Key::Unidentified(NativeKey::MacOS(scancode)); + } + let layout_data = + ffi::TISGetInputSourceProperty(input_source, ffi::kTISPropertyUnicodeKeyLayoutData); + if layout_data.is_null() { + CFRelease(input_source as *mut c_void); + tracing::error!("`TISGetInputSourceProperty` returned null ptr"); + return Key::Unidentified(NativeKey::MacOS(scancode)); + } + layout = CFDataGetBytePtr(layout_data as CFDataRef) as *const ffi::UCKeyboardLayout; + } + let keyboard_type = run_on_main(|_mtm| unsafe { ffi::LMGetKbdType() }); + + let mut result_len = 0; + let mut dead_keys = 0; + let modifiers = 0; + let translate_result = unsafe { + ffi::UCKeyTranslate( + layout, + scancode, + ffi::kUCKeyActionDisplay, + modifiers, + keyboard_type as u32, + ffi::kUCKeyTranslateNoDeadKeysMask, + &mut dead_keys, + string.len() as ffi::UniCharCount, + &mut result_len, + string.as_mut_ptr(), + ) + }; + unsafe { + CFRelease(input_source as *mut c_void); + } + if translate_result != 0 { + tracing::error!("`UCKeyTranslate` returned with the non-zero value: {}", translate_result); + return Key::Unidentified(NativeKey::MacOS(scancode)); + } + if result_len == 0 { + // This is fine - not all keys have text representation. + // For instance, users that have mapped the `Fn` key to toggle + // keyboard layouts will hit this code path. + return Key::Unidentified(NativeKey::MacOS(scancode)); + } + let chars = String::from_utf16_lossy(&string[0..result_len as usize]); + Key::Character(SmolStr::new(chars)) +} + +// Ignores all modifiers except for SHIFT (yes, even ALT is ignored). +fn get_logical_key_char(ns_event: &NSEvent, modifierless_chars: &str) -> Key { + let string = unsafe { ns_event.charactersIgnoringModifiers() } + .map(|s| s.to_string()) + .unwrap_or_default(); + if string.is_empty() { + // Probably a dead key + let first_char = modifierless_chars.chars().next(); + return Key::Dead(first_char); + } + Key::Character(SmolStr::new(string)) +} + +/// Create `KeyEvent` for the given `NSEvent`. +/// +/// This function shouldn't be called when the IME input is in process. +pub(crate) fn create_key_event(ns_event: &NSEvent, is_press: bool, is_repeat: bool) -> KeyEvent { + use ElementState::{Pressed, Released}; + let state = if is_press { Pressed } else { Released }; + + let scancode = unsafe { ns_event.keyCode() }; + let mut physical_key = scancode_to_physicalkey(scancode as u32); + + // NOTE: The logical key should heed both SHIFT and ALT if possible. + // For instance: + // * Pressing the A key: logical key should be "a" + // * Pressing SHIFT A: logical key should be "A" + // * Pressing CTRL SHIFT A: logical key should also be "A" + // This is not easy to tease out of `NSEvent`, but we do our best. + + let characters = unsafe { ns_event.characters() }.map(|s| s.to_string()).unwrap_or_default(); + let text_with_all_modifiers = if characters.is_empty() { + None + } else { + if matches!(physical_key, PhysicalKey::Unidentified(_)) { + // The key may be one of the funky function keys + physical_key = extra_function_key_to_code(scancode, &characters); + } + Some(SmolStr::new(characters)) + }; + + let key_from_code = code_to_key(physical_key, scancode); + let (logical_key, key_without_modifiers) = if matches!(key_from_code, Key::Unidentified(_)) { + // `get_modifierless_char/key_without_modifiers` ignores ALL modifiers. + let key_without_modifiers = get_modifierless_char(scancode); + + let modifiers = unsafe { ns_event.modifierFlags() }; + let has_ctrl = modifiers.contains(NSEventModifierFlags::NSEventModifierFlagControl); + let has_cmd = modifiers.contains(NSEventModifierFlags::NSEventModifierFlagCommand); + + let logical_key = match text_with_all_modifiers.as_ref() { + // Only checking for ctrl and cmd here, not checking for alt because we DO want to + // include its effect in the key. For example if -on the German layout- one + // presses alt+8, the logical key should be "{" + // Also not checking if this is a release event because then this issue would + // still affect the key release. + Some(text) if !has_ctrl && !has_cmd => { + // Character heeding both SHIFT and ALT. + Key::Character(text.clone()) + }, + + _ => match key_without_modifiers.as_ref() { + // Character heeding just SHIFT, ignoring ALT. + Key::Character(ch) => get_logical_key_char(ns_event, ch), + + // Character ignoring ALL modifiers. + _ => key_without_modifiers.clone(), + }, + }; + + (logical_key, key_without_modifiers) + } else { + (key_from_code.clone(), key_from_code) + }; + + let text = if is_press { logical_key.to_text().map(SmolStr::new) } else { None }; + + let location = code_to_location(physical_key); + + KeyEvent { + location, + logical_key, + physical_key, + repeat: is_repeat, + state, + text, + platform_specific: KeyEventExtra { text_with_all_modifiers, key_without_modifiers }, + } +} + +pub fn code_to_key(key: PhysicalKey, scancode: u16) -> Key { + let code = match key { + PhysicalKey::Code(code) => code, + PhysicalKey::Unidentified(code) => return Key::Unidentified(code.into()), + }; + + Key::Named(match code { + KeyCode::Enter => NamedKey::Enter, + KeyCode::Tab => NamedKey::Tab, + KeyCode::Space => NamedKey::Space, + KeyCode::Backspace => NamedKey::Backspace, + KeyCode::Escape => NamedKey::Escape, + KeyCode::SuperRight => NamedKey::Super, + KeyCode::SuperLeft => NamedKey::Super, + KeyCode::ShiftLeft => NamedKey::Shift, + KeyCode::AltLeft => NamedKey::Alt, + KeyCode::ControlLeft => NamedKey::Control, + KeyCode::ShiftRight => NamedKey::Shift, + KeyCode::AltRight => NamedKey::Alt, + KeyCode::ControlRight => NamedKey::Control, + + KeyCode::NumLock => NamedKey::NumLock, + KeyCode::AudioVolumeUp => NamedKey::AudioVolumeUp, + KeyCode::AudioVolumeDown => NamedKey::AudioVolumeDown, + + // Other numpad keys all generate text on macOS (if I understand correctly) + KeyCode::NumpadEnter => NamedKey::Enter, + + KeyCode::F1 => NamedKey::F1, + KeyCode::F2 => NamedKey::F2, + KeyCode::F3 => NamedKey::F3, + KeyCode::F4 => NamedKey::F4, + KeyCode::F5 => NamedKey::F5, + KeyCode::F6 => NamedKey::F6, + KeyCode::F7 => NamedKey::F7, + KeyCode::F8 => NamedKey::F8, + KeyCode::F9 => NamedKey::F9, + KeyCode::F10 => NamedKey::F10, + KeyCode::F11 => NamedKey::F11, + KeyCode::F12 => NamedKey::F12, + KeyCode::F13 => NamedKey::F13, + KeyCode::F14 => NamedKey::F14, + KeyCode::F15 => NamedKey::F15, + KeyCode::F16 => NamedKey::F16, + KeyCode::F17 => NamedKey::F17, + KeyCode::F18 => NamedKey::F18, + KeyCode::F19 => NamedKey::F19, + KeyCode::F20 => NamedKey::F20, + + KeyCode::Insert => NamedKey::Insert, + KeyCode::Home => NamedKey::Home, + KeyCode::PageUp => NamedKey::PageUp, + KeyCode::Delete => NamedKey::Delete, + KeyCode::End => NamedKey::End, + KeyCode::PageDown => NamedKey::PageDown, + KeyCode::ArrowLeft => NamedKey::ArrowLeft, + KeyCode::ArrowRight => NamedKey::ArrowRight, + KeyCode::ArrowDown => NamedKey::ArrowDown, + KeyCode::ArrowUp => NamedKey::ArrowUp, + _ => return Key::Unidentified(NativeKey::MacOS(scancode)), + }) +} + +pub fn code_to_location(key: PhysicalKey) -> KeyLocation { + let code = match key { + PhysicalKey::Code(code) => code, + PhysicalKey::Unidentified(_) => return KeyLocation::Standard, + }; + + match code { + KeyCode::SuperRight => KeyLocation::Right, + KeyCode::SuperLeft => KeyLocation::Left, + KeyCode::ShiftLeft => KeyLocation::Left, + KeyCode::AltLeft => KeyLocation::Left, + KeyCode::ControlLeft => KeyLocation::Left, + KeyCode::ShiftRight => KeyLocation::Right, + KeyCode::AltRight => KeyLocation::Right, + KeyCode::ControlRight => KeyLocation::Right, + + KeyCode::NumLock => KeyLocation::Numpad, + KeyCode::NumpadDecimal => KeyLocation::Numpad, + KeyCode::NumpadMultiply => KeyLocation::Numpad, + KeyCode::NumpadAdd => KeyLocation::Numpad, + KeyCode::NumpadDivide => KeyLocation::Numpad, + KeyCode::NumpadEnter => KeyLocation::Numpad, + KeyCode::NumpadSubtract => KeyLocation::Numpad, + KeyCode::NumpadEqual => KeyLocation::Numpad, + KeyCode::Numpad0 => KeyLocation::Numpad, + KeyCode::Numpad1 => KeyLocation::Numpad, + KeyCode::Numpad2 => KeyLocation::Numpad, + KeyCode::Numpad3 => KeyLocation::Numpad, + KeyCode::Numpad4 => KeyLocation::Numpad, + KeyCode::Numpad5 => KeyLocation::Numpad, + KeyCode::Numpad6 => KeyLocation::Numpad, + KeyCode::Numpad7 => KeyLocation::Numpad, + KeyCode::Numpad8 => KeyLocation::Numpad, + KeyCode::Numpad9 => KeyLocation::Numpad, + + _ => KeyLocation::Standard, + } +} + +// While F1-F20 have scancodes we can match on, we have to check against UTF-16 +// constants for the rest. +// https://developer.apple.com/documentation/appkit/1535851-function-key_unicodes?preferredLanguage=occ +pub fn extra_function_key_to_code(scancode: u16, string: &str) -> PhysicalKey { + if let Some(ch) = string.encode_utf16().next() { + match ch { + 0xf718 => PhysicalKey::Code(KeyCode::F21), + 0xf719 => PhysicalKey::Code(KeyCode::F22), + 0xf71a => PhysicalKey::Code(KeyCode::F23), + 0xf71b => PhysicalKey::Code(KeyCode::F24), + _ => PhysicalKey::Unidentified(NativeKeyCode::MacOS(scancode)), + } + } else { + PhysicalKey::Unidentified(NativeKeyCode::MacOS(scancode)) + } +} + +// The values are from the https://github.com/apple-oss-distributions/IOHIDFamily/blob/19666c840a6d896468416ff0007040a10b7b46b8/IOHIDSystem/IOKit/hidsystem/IOLLEvent.h#L258-L259 +const NX_DEVICELCTLKEYMASK: NSEventModifierFlags = NSEventModifierFlags(0x00000001); +const NX_DEVICELSHIFTKEYMASK: NSEventModifierFlags = NSEventModifierFlags(0x00000002); +const NX_DEVICERSHIFTKEYMASK: NSEventModifierFlags = NSEventModifierFlags(0x00000004); +const NX_DEVICELCMDKEYMASK: NSEventModifierFlags = NSEventModifierFlags(0x00000008); +const NX_DEVICERCMDKEYMASK: NSEventModifierFlags = NSEventModifierFlags(0x00000010); +const NX_DEVICELALTKEYMASK: NSEventModifierFlags = NSEventModifierFlags(0x00000020); +const NX_DEVICERALTKEYMASK: NSEventModifierFlags = NSEventModifierFlags(0x00000040); +const NX_DEVICERCTLKEYMASK: NSEventModifierFlags = NSEventModifierFlags(0x00002000); + +pub(super) fn lalt_pressed(event: &NSEvent) -> bool { + unsafe { event.modifierFlags() }.contains(NX_DEVICELALTKEYMASK) +} + +pub(super) fn ralt_pressed(event: &NSEvent) -> bool { + unsafe { event.modifierFlags() }.contains(NX_DEVICERALTKEYMASK) +} + +pub(super) fn event_mods(event: &NSEvent) -> Modifiers { + let flags = unsafe { event.modifierFlags() }; + let mut state = ModifiersState::empty(); + let mut pressed_mods = ModifiersKeys::empty(); + + state + .set(ModifiersState::SHIFT, flags.contains(NSEventModifierFlags::NSEventModifierFlagShift)); + pressed_mods.set(ModifiersKeys::LSHIFT, flags.contains(NX_DEVICELSHIFTKEYMASK)); + pressed_mods.set(ModifiersKeys::RSHIFT, flags.contains(NX_DEVICERSHIFTKEYMASK)); + + state.set( + ModifiersState::CONTROL, + flags.contains(NSEventModifierFlags::NSEventModifierFlagControl), + ); + pressed_mods.set(ModifiersKeys::LCONTROL, flags.contains(NX_DEVICELCTLKEYMASK)); + pressed_mods.set(ModifiersKeys::RCONTROL, flags.contains(NX_DEVICERCTLKEYMASK)); + + state.set(ModifiersState::ALT, flags.contains(NSEventModifierFlags::NSEventModifierFlagOption)); + pressed_mods.set(ModifiersKeys::LALT, flags.contains(NX_DEVICELALTKEYMASK)); + pressed_mods.set(ModifiersKeys::RALT, flags.contains(NX_DEVICERALTKEYMASK)); + + state.set( + ModifiersState::SUPER, + flags.contains(NSEventModifierFlags::NSEventModifierFlagCommand), + ); + pressed_mods.set(ModifiersKeys::LSUPER, flags.contains(NX_DEVICELCMDKEYMASK)); + pressed_mods.set(ModifiersKeys::RSUPER, flags.contains(NX_DEVICERCMDKEYMASK)); + + Modifiers { state, pressed_mods } +} + +pub(super) fn dummy_event() -> Option<Retained<NSEvent>> { + unsafe { + NSEvent::otherEventWithType_location_modifierFlags_timestamp_windowNumber_context_subtype_data1_data2( + NSEventType::ApplicationDefined, + NSPoint::new(0.0, 0.0), + NSEventModifierFlags(0), + 0.0, + 0, + None, + NSEventSubtype::WindowExposed.0, + 0, + 0, + ) + } +} + +pub(crate) fn physicalkey_to_scancode(physical_key: PhysicalKey) -> Option<u32> { + let code = match physical_key { + PhysicalKey::Code(code) => code, + PhysicalKey::Unidentified(_) => return None, + }; + + match code { + KeyCode::KeyA => Some(0x00), + KeyCode::KeyS => Some(0x01), + KeyCode::KeyD => Some(0x02), + KeyCode::KeyF => Some(0x03), + KeyCode::KeyH => Some(0x04), + KeyCode::KeyG => Some(0x05), + KeyCode::KeyZ => Some(0x06), + KeyCode::KeyX => Some(0x07), + KeyCode::KeyC => Some(0x08), + KeyCode::KeyV => Some(0x09), + KeyCode::KeyB => Some(0x0b), + KeyCode::KeyQ => Some(0x0c), + KeyCode::KeyW => Some(0x0d), + KeyCode::KeyE => Some(0x0e), + KeyCode::KeyR => Some(0x0f), + KeyCode::KeyY => Some(0x10), + KeyCode::KeyT => Some(0x11), + KeyCode::Digit1 => Some(0x12), + KeyCode::Digit2 => Some(0x13), + KeyCode::Digit3 => Some(0x14), + KeyCode::Digit4 => Some(0x15), + KeyCode::Digit6 => Some(0x16), + KeyCode::Digit5 => Some(0x17), + KeyCode::Equal => Some(0x18), + KeyCode::Digit9 => Some(0x19), + KeyCode::Digit7 => Some(0x1a), + KeyCode::Minus => Some(0x1b), + KeyCode::Digit8 => Some(0x1c), + KeyCode::Digit0 => Some(0x1d), + KeyCode::BracketRight => Some(0x1e), + KeyCode::KeyO => Some(0x1f), + KeyCode::KeyU => Some(0x20), + KeyCode::BracketLeft => Some(0x21), + KeyCode::KeyI => Some(0x22), + KeyCode::KeyP => Some(0x23), + KeyCode::Enter => Some(0x24), + KeyCode::KeyL => Some(0x25), + KeyCode::KeyJ => Some(0x26), + KeyCode::Quote => Some(0x27), + KeyCode::KeyK => Some(0x28), + KeyCode::Semicolon => Some(0x29), + KeyCode::Backslash => Some(0x2a), + KeyCode::Comma => Some(0x2b), + KeyCode::Slash => Some(0x2c), + KeyCode::KeyN => Some(0x2d), + KeyCode::KeyM => Some(0x2e), + KeyCode::Period => Some(0x2f), + KeyCode::Tab => Some(0x30), + KeyCode::Space => Some(0x31), + KeyCode::Backquote => Some(0x32), + KeyCode::Backspace => Some(0x33), + KeyCode::Escape => Some(0x35), + KeyCode::SuperRight => Some(0x36), + KeyCode::SuperLeft => Some(0x37), + KeyCode::ShiftLeft => Some(0x38), + KeyCode::AltLeft => Some(0x3a), + KeyCode::ControlLeft => Some(0x3b), + KeyCode::ShiftRight => Some(0x3c), + KeyCode::AltRight => Some(0x3d), + KeyCode::ControlRight => Some(0x3e), + KeyCode::F17 => Some(0x40), + KeyCode::NumpadDecimal => Some(0x41), + KeyCode::NumpadMultiply => Some(0x43), + KeyCode::NumpadAdd => Some(0x45), + KeyCode::NumLock => Some(0x47), + KeyCode::AudioVolumeUp => Some(0x49), + KeyCode::AudioVolumeDown => Some(0x4a), + KeyCode::NumpadDivide => Some(0x4b), + KeyCode::NumpadEnter => Some(0x4c), + KeyCode::NumpadSubtract => Some(0x4e), + KeyCode::F18 => Some(0x4f), + KeyCode::F19 => Some(0x50), + KeyCode::NumpadEqual => Some(0x51), + KeyCode::Numpad0 => Some(0x52), + KeyCode::Numpad1 => Some(0x53), + KeyCode::Numpad2 => Some(0x54), + KeyCode::Numpad3 => Some(0x55), + KeyCode::Numpad4 => Some(0x56), + KeyCode::Numpad5 => Some(0x57), + KeyCode::Numpad6 => Some(0x58), + KeyCode::Numpad7 => Some(0x59), + KeyCode::F20 => Some(0x5a), + KeyCode::Numpad8 => Some(0x5b), + KeyCode::Numpad9 => Some(0x5c), + KeyCode::IntlYen => Some(0x5d), + KeyCode::F5 => Some(0x60), + KeyCode::F6 => Some(0x61), + KeyCode::F7 => Some(0x62), + KeyCode::F3 => Some(0x63), + KeyCode::F8 => Some(0x64), + KeyCode::F9 => Some(0x65), + KeyCode::F11 => Some(0x67), + KeyCode::F13 => Some(0x69), + KeyCode::F16 => Some(0x6a), + KeyCode::F14 => Some(0x6b), + KeyCode::F10 => Some(0x6d), + KeyCode::F12 => Some(0x6f), + KeyCode::F15 => Some(0x71), + KeyCode::Insert => Some(0x72), + KeyCode::Home => Some(0x73), + KeyCode::PageUp => Some(0x74), + KeyCode::Delete => Some(0x75), + KeyCode::F4 => Some(0x76), + KeyCode::End => Some(0x77), + KeyCode::F2 => Some(0x78), + KeyCode::PageDown => Some(0x79), + KeyCode::F1 => Some(0x7a), + KeyCode::ArrowLeft => Some(0x7b), + KeyCode::ArrowRight => Some(0x7c), + KeyCode::ArrowDown => Some(0x7d), + KeyCode::ArrowUp => Some(0x7e), + _ => None, + } +} + +pub(crate) fn scancode_to_physicalkey(scancode: u32) -> PhysicalKey { + PhysicalKey::Code(match scancode { + 0x00 => KeyCode::KeyA, + 0x01 => KeyCode::KeyS, + 0x02 => KeyCode::KeyD, + 0x03 => KeyCode::KeyF, + 0x04 => KeyCode::KeyH, + 0x05 => KeyCode::KeyG, + 0x06 => KeyCode::KeyZ, + 0x07 => KeyCode::KeyX, + 0x08 => KeyCode::KeyC, + 0x09 => KeyCode::KeyV, + // 0x0a => World 1, + 0x0b => KeyCode::KeyB, + 0x0c => KeyCode::KeyQ, + 0x0d => KeyCode::KeyW, + 0x0e => KeyCode::KeyE, + 0x0f => KeyCode::KeyR, + 0x10 => KeyCode::KeyY, + 0x11 => KeyCode::KeyT, + 0x12 => KeyCode::Digit1, + 0x13 => KeyCode::Digit2, + 0x14 => KeyCode::Digit3, + 0x15 => KeyCode::Digit4, + 0x16 => KeyCode::Digit6, + 0x17 => KeyCode::Digit5, + 0x18 => KeyCode::Equal, + 0x19 => KeyCode::Digit9, + 0x1a => KeyCode::Digit7, + 0x1b => KeyCode::Minus, + 0x1c => KeyCode::Digit8, + 0x1d => KeyCode::Digit0, + 0x1e => KeyCode::BracketRight, + 0x1f => KeyCode::KeyO, + 0x20 => KeyCode::KeyU, + 0x21 => KeyCode::BracketLeft, + 0x22 => KeyCode::KeyI, + 0x23 => KeyCode::KeyP, + 0x24 => KeyCode::Enter, + 0x25 => KeyCode::KeyL, + 0x26 => KeyCode::KeyJ, + 0x27 => KeyCode::Quote, + 0x28 => KeyCode::KeyK, + 0x29 => KeyCode::Semicolon, + 0x2a => KeyCode::Backslash, + 0x2b => KeyCode::Comma, + 0x2c => KeyCode::Slash, + 0x2d => KeyCode::KeyN, + 0x2e => KeyCode::KeyM, + 0x2f => KeyCode::Period, + 0x30 => KeyCode::Tab, + 0x31 => KeyCode::Space, + 0x32 => KeyCode::Backquote, + 0x33 => KeyCode::Backspace, + // 0x34 => unknown, + 0x35 => KeyCode::Escape, + 0x36 => KeyCode::SuperRight, + 0x37 => KeyCode::SuperLeft, + 0x38 => KeyCode::ShiftLeft, + 0x39 => KeyCode::CapsLock, + 0x3a => KeyCode::AltLeft, + 0x3b => KeyCode::ControlLeft, + 0x3c => KeyCode::ShiftRight, + 0x3d => KeyCode::AltRight, + 0x3e => KeyCode::ControlRight, + 0x3f => KeyCode::Fn, + 0x40 => KeyCode::F17, + 0x41 => KeyCode::NumpadDecimal, + // 0x42 -> unknown, + 0x43 => KeyCode::NumpadMultiply, + // 0x44 => unknown, + 0x45 => KeyCode::NumpadAdd, + // 0x46 => unknown, + 0x47 => KeyCode::NumLock, + // 0x48 => KeyCode::NumpadClear, + + // TODO: (Artur) for me, kVK_VolumeUp is 0x48 + // macOS 10.11 + // /System/Library/Frameworks/Carbon.framework/Versions/A/Frameworks/HIToolbox.framework/ + // Versions/A/Headers/Events.h + 0x49 => KeyCode::AudioVolumeUp, + 0x4a => KeyCode::AudioVolumeDown, + 0x4b => KeyCode::NumpadDivide, + 0x4c => KeyCode::NumpadEnter, + // 0x4d => unknown, + 0x4e => KeyCode::NumpadSubtract, + 0x4f => KeyCode::F18, + 0x50 => KeyCode::F19, + 0x51 => KeyCode::NumpadEqual, + 0x52 => KeyCode::Numpad0, + 0x53 => KeyCode::Numpad1, + 0x54 => KeyCode::Numpad2, + 0x55 => KeyCode::Numpad3, + 0x56 => KeyCode::Numpad4, + 0x57 => KeyCode::Numpad5, + 0x58 => KeyCode::Numpad6, + 0x59 => KeyCode::Numpad7, + 0x5a => KeyCode::F20, + 0x5b => KeyCode::Numpad8, + 0x5c => KeyCode::Numpad9, + 0x5d => KeyCode::IntlYen, + // 0x5e => JIS Ro, + // 0x5f => unknown, + 0x60 => KeyCode::F5, + 0x61 => KeyCode::F6, + 0x62 => KeyCode::F7, + 0x63 => KeyCode::F3, + 0x64 => KeyCode::F8, + 0x65 => KeyCode::F9, + // 0x66 => JIS Eisuu (macOS), + 0x67 => KeyCode::F11, + // 0x68 => JIS Kanna (macOS), + 0x69 => KeyCode::F13, + 0x6a => KeyCode::F16, + 0x6b => KeyCode::F14, + // 0x6c => unknown, + 0x6d => KeyCode::F10, + // 0x6e => unknown, + 0x6f => KeyCode::F12, + // 0x70 => unknown, + 0x71 => KeyCode::F15, + 0x72 => KeyCode::Insert, + 0x73 => KeyCode::Home, + 0x74 => KeyCode::PageUp, + 0x75 => KeyCode::Delete, + 0x76 => KeyCode::F4, + 0x77 => KeyCode::End, + 0x78 => KeyCode::F2, + 0x79 => KeyCode::PageDown, + 0x7a => KeyCode::F1, + 0x7b => KeyCode::ArrowLeft, + 0x7c => KeyCode::ArrowRight, + 0x7d => KeyCode::ArrowDown, + 0x7e => KeyCode::ArrowUp, + // 0x7f => unknown, + + // 0xA is the caret (^) an macOS's German QERTZ layout. This key is at the same location as + // backquote (`) on Windows' US layout. + 0xa => KeyCode::Backquote, + _ => return PhysicalKey::Unidentified(NativeKeyCode::MacOS(scancode as u16)), + }) +} diff --git a/app/vendor/rune/vendor/winit/src/platform_impl/macos/event_handler.rs b/app/vendor/rune/vendor/winit/src/platform_impl/macos/event_handler.rs new file mode 100644 index 0000000..5c353c1 --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/platform_impl/macos/event_handler.rs @@ -0,0 +1,139 @@ +use std::cell::RefCell; +use std::{fmt, mem}; + +use super::app_state::HandlePendingUserEvents; +use crate::event::Event; +use crate::event_loop::ActiveEventLoop as RootActiveEventLoop; + +struct EventHandlerData { + #[allow(clippy::type_complexity)] + handler: Box<dyn FnMut(Event<HandlePendingUserEvents>, &RootActiveEventLoop) + 'static>, +} + +impl fmt::Debug for EventHandlerData { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("EventHandlerData").finish_non_exhaustive() + } +} + +#[derive(Debug)] +pub(crate) struct EventHandler { + /// This can be in the following states: + /// - Not registered by the event loop (None). + /// - Present (Some(handler)). + /// - Currently executing the handler / in use (RefCell borrowed). + inner: RefCell<Option<EventHandlerData>>, +} + +impl EventHandler { + pub(crate) const fn new() -> Self { + Self { inner: RefCell::new(None) } + } + + /// Set the event loop handler for the duration of the given closure. + /// + /// This is similar to using the `scoped-tls` or `scoped-tls-hkt` crates + /// to store the handler in a thread local, such that it can be accessed + /// from within the closure. + pub(crate) fn set<'handler, R>( + &self, + handler: impl FnMut(Event<HandlePendingUserEvents>, &RootActiveEventLoop) + 'handler, + closure: impl FnOnce() -> R, + ) -> R { + // SAFETY: We extend the lifetime of the handler here so that we can + // store it in `EventHandler`'s `RefCell`. + // + // This is sound, since we make sure to unset the handler again at the + // end of this function, and as such the lifetime isn't actually + // extended beyond `'handler`. + let handler = unsafe { + mem::transmute::< + Box<dyn FnMut(Event<HandlePendingUserEvents>, &RootActiveEventLoop) + 'handler>, + Box<dyn FnMut(Event<HandlePendingUserEvents>, &RootActiveEventLoop) + 'static>, + >(Box::new(handler)) + }; + + match self.inner.try_borrow_mut().as_deref_mut() { + Ok(Some(_)) => { + unreachable!("tried to set handler while another was already set"); + }, + Ok(data @ None) => { + *data = Some(EventHandlerData { handler }); + }, + Err(_) => { + unreachable!("tried to set handler that is currently in use"); + }, + } + + struct ClearOnDrop<'a>(&'a EventHandler); + + impl Drop for ClearOnDrop<'_> { + fn drop(&mut self) { + match self.0.inner.try_borrow_mut().as_deref_mut() { + Ok(data @ Some(_)) => { + *data = None; + }, + Ok(None) => { + tracing::error!("tried to clear handler, but no handler was set"); + }, + Err(_) => { + // Note: This is not expected to ever happen, this + // module generally controls the `RefCell`, and + // prevents it from ever being borrowed outside of it. + // + // But if it _does_ happen, it is a serious error, and + // we must abort the process, it'd be unsound if we + // weren't able to unset the handler. + eprintln!("tried to clear handler that is currently in use"); + std::process::abort(); + }, + } + } + } + + let _clear_on_drop = ClearOnDrop(self); + + // Note: The RefCell should not be borrowed while executing the + // closure, that'd defeat the whole point. + closure() + + // `_clear_on_drop` will be dropped here, or when unwinding, ensuring + // soundness. + } + + pub(crate) fn in_use(&self) -> bool { + self.inner.try_borrow().is_err() + } + + pub(crate) fn ready(&self) -> bool { + matches!(self.inner.try_borrow().as_deref(), Ok(Some(_))) + } + + pub(crate) fn handle_event( + &self, + event: Event<HandlePendingUserEvents>, + event_loop: &RootActiveEventLoop, + ) { + match self.inner.try_borrow_mut().as_deref_mut() { + Ok(Some(EventHandlerData { handler })) => { + // It is important that we keep the reference borrowed here, + // so that `in_use` can properly detect that the handler is + // still in use. + // + // If the handler unwinds, the `RefMut` will ensure that the + // handler is no longer borrowed. + (handler)(event, event_loop); + }, + Ok(None) => { + // `NSApplication`, our app delegate and this handler are all + // global state and so it's not impossible that we could get + // an event after the application has exited the `EventLoop`. + tracing::error!("tried to run event handler, but no handler was set"); + }, + Err(_) => { + // Prevent re-entrancy. + panic!("tried to handle event while another event is currently being handled"); + }, + } + } +} diff --git a/app/vendor/rune/vendor/winit/src/platform_impl/macos/event_loop.rs b/app/vendor/rune/vendor/winit/src/platform_impl/macos/event_loop.rs new file mode 100644 index 0000000..5c093d5 --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/platform_impl/macos/event_loop.rs @@ -0,0 +1,523 @@ +use std::any::Any; +use std::cell::Cell; +use std::collections::VecDeque; +use std::marker::PhantomData; +use std::os::raw::c_void; +use std::panic::{catch_unwind, resume_unwind, RefUnwindSafe, UnwindSafe}; +use std::ptr; +use std::rc::{Rc, Weak}; +use std::sync::mpsc; +use std::time::{Duration, Instant}; + +use core_foundation::base::{CFIndex, CFRelease}; +use core_foundation::runloop::{ + kCFRunLoopCommonModes, CFRunLoopAddSource, CFRunLoopGetMain, CFRunLoopSourceContext, + CFRunLoopSourceCreate, CFRunLoopSourceRef, CFRunLoopSourceSignal, CFRunLoopWakeUp, +}; +use objc2::rc::{autoreleasepool, Retained}; +use objc2::runtime::ProtocolObject; +use objc2::sel; +use objc2_app_kit::{NSApplication, NSApplicationActivationPolicy, NSWindow}; +use objc2_foundation::{MainThreadMarker, NSObjectProtocol}; + +use super::app::override_send_event; +use super::app_state::{ApplicationDelegate, HandlePendingUserEvents}; +use super::event::dummy_event; +use super::monitor::{self, MonitorHandle}; +use super::observer::setup_control_flow_observers; +use crate::error::EventLoopError; +use crate::event::Event; +use crate::event_loop::{ + ActiveEventLoop as RootWindowTarget, ControlFlow, DeviceEvents, EventLoopClosed, +}; +use crate::platform::macos::ActivationPolicy; +use crate::platform::pump_events::PumpStatus; +use crate::platform_impl::platform::cursor::CustomCursor; +use crate::window::{CustomCursor as RootCustomCursor, CustomCursorSource, Theme}; + +#[derive(Default)] +pub struct PanicInfo { + inner: Cell<Option<Box<dyn Any + Send + 'static>>>, +} + +// WARNING: +// As long as this struct is used through its `impl`, it is UnwindSafe. +// (If `get_mut` is called on `inner`, unwind safety may get broken.) +impl UnwindSafe for PanicInfo {} +impl RefUnwindSafe for PanicInfo {} +impl PanicInfo { + pub fn is_panicking(&self) -> bool { + let inner = self.inner.take(); + let result = inner.is_some(); + self.inner.set(inner); + result + } + + /// Overwrites the current state if the current state is not panicking + pub fn set_panic(&self, p: Box<dyn Any + Send + 'static>) { + if !self.is_panicking() { + self.inner.set(Some(p)); + } + } + + pub fn take(&self) -> Option<Box<dyn Any + Send + 'static>> { + self.inner.take() + } +} + +#[derive(Debug)] +pub struct ActiveEventLoop { + delegate: Retained<ApplicationDelegate>, + pub(super) mtm: MainThreadMarker, +} + +impl ActiveEventLoop { + pub(super) fn new_root(delegate: Retained<ApplicationDelegate>) -> RootWindowTarget { + let mtm = MainThreadMarker::from(&*delegate); + let p = Self { delegate, mtm }; + RootWindowTarget { p, _marker: PhantomData } + } + + pub(super) fn app_delegate(&self) -> &ApplicationDelegate { + &self.delegate + } + + pub fn create_custom_cursor(&self, source: CustomCursorSource) -> RootCustomCursor { + RootCustomCursor { inner: CustomCursor::new(source.inner) } + } + + #[inline] + pub fn available_monitors(&self) -> VecDeque<MonitorHandle> { + monitor::available_monitors() + } + + #[inline] + pub fn primary_monitor(&self) -> Option<MonitorHandle> { + let monitor = monitor::primary_monitor(); + Some(monitor) + } + + #[inline] + pub fn listen_device_events(&self, _allowed: DeviceEvents) {} + + #[cfg(feature = "rwh_05")] + #[inline] + pub fn raw_display_handle_rwh_05(&self) -> rwh_05::RawDisplayHandle { + rwh_05::RawDisplayHandle::AppKit(rwh_05::AppKitDisplayHandle::empty()) + } + + #[inline] + pub fn system_theme(&self) -> Option<Theme> { + let app = NSApplication::sharedApplication(self.mtm); + + if app.respondsToSelector(sel!(effectiveAppearance)) { + Some(super::window_delegate::appearance_to_theme(&app.effectiveAppearance())) + } else { + Some(Theme::Light) + } + } + + #[cfg(feature = "rwh_06")] + #[inline] + pub fn raw_display_handle_rwh_06( + &self, + ) -> Result<rwh_06::RawDisplayHandle, rwh_06::HandleError> { + Ok(rwh_06::RawDisplayHandle::AppKit(rwh_06::AppKitDisplayHandle::new())) + } + + pub(crate) fn set_control_flow(&self, control_flow: ControlFlow) { + self.delegate.set_control_flow(control_flow) + } + + pub(crate) fn control_flow(&self) -> ControlFlow { + self.delegate.control_flow() + } + + pub(crate) fn exit(&self) { + self.delegate.exit() + } + + pub(crate) fn clear_exit(&self) { + self.delegate.clear_exit() + } + + pub(crate) fn exiting(&self) -> bool { + self.delegate.exiting() + } + + pub(crate) fn owned_display_handle(&self) -> OwnedDisplayHandle { + OwnedDisplayHandle + } + + pub(crate) fn hide_application(&self) { + NSApplication::sharedApplication(self.mtm).hide(None) + } + + pub(crate) fn hide_other_applications(&self) { + NSApplication::sharedApplication(self.mtm).hideOtherApplications(None) + } + + pub(crate) fn set_allows_automatic_window_tabbing(&self, enabled: bool) { + NSWindow::setAllowsAutomaticWindowTabbing(enabled, self.mtm) + } + + pub(crate) fn allows_automatic_window_tabbing(&self) -> bool { + NSWindow::allowsAutomaticWindowTabbing(self.mtm) + } +} + +fn map_user_event<T: 'static>( + mut handler: impl FnMut(Event<T>, &RootWindowTarget), + receiver: Rc<mpsc::Receiver<T>>, +) -> impl FnMut(Event<HandlePendingUserEvents>, &RootWindowTarget) { + move |event, window_target| match event.map_nonuser_event() { + Ok(event) => (handler)(event, window_target), + Err(_) => { + for event in receiver.try_iter() { + (handler)(Event::UserEvent(event), window_target); + } + }, + } +} + +pub struct EventLoop<T: 'static> { + /// Store a reference to the application for convenience. + /// + /// We intentionally don't store `WinitApplication` since we want to have + /// the possibility of swapping that out at some point. + app: Retained<NSApplication>, + /// The application delegate that we've registered. + /// + /// The delegate is only weakly referenced by NSApplication, so we must + /// keep it around here as well. + delegate: Retained<ApplicationDelegate>, + + // Event sender and receiver, used for EventLoopProxy. + sender: mpsc::Sender<T>, + receiver: Rc<mpsc::Receiver<T>>, + + window_target: RootWindowTarget, + panic_info: Rc<PanicInfo>, +} + +#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)] +pub(crate) struct PlatformSpecificEventLoopAttributes { + pub(crate) activation_policy: Option<ActivationPolicy>, + pub(crate) default_menu: bool, + pub(crate) activate_ignoring_other_apps: bool, +} + +impl Default for PlatformSpecificEventLoopAttributes { + fn default() -> Self { + Self { activation_policy: None, default_menu: true, activate_ignoring_other_apps: true } + } +} + +impl<T> EventLoop<T> { + pub(crate) fn new( + attributes: &PlatformSpecificEventLoopAttributes, + ) -> Result<Self, EventLoopError> { + let mtm = MainThreadMarker::new() + .expect("on macOS, `EventLoop` must be created on the main thread!"); + + // Initialize the application (if it has not already been). + let app = NSApplication::sharedApplication(mtm); + + let activation_policy = match attributes.activation_policy { + None => None, + Some(ActivationPolicy::Regular) => Some(NSApplicationActivationPolicy::Regular), + Some(ActivationPolicy::Accessory) => Some(NSApplicationActivationPolicy::Accessory), + Some(ActivationPolicy::Prohibited) => Some(NSApplicationActivationPolicy::Prohibited), + }; + let delegate = ApplicationDelegate::new( + mtm, + activation_policy, + attributes.default_menu, + attributes.activate_ignoring_other_apps, + ); + + autoreleasepool(|_| { + app.setDelegate(Some(ProtocolObject::from_ref(&*delegate))); + }); + + // Override `sendEvent:` on the application to forward to our application state. + override_send_event(&app); + + let panic_info: Rc<PanicInfo> = Default::default(); + setup_control_flow_observers(mtm, Rc::downgrade(&panic_info)); + + let (sender, receiver) = mpsc::channel(); + Ok(EventLoop { + app, + delegate: delegate.clone(), + sender, + receiver: Rc::new(receiver), + window_target: RootWindowTarget { + p: ActiveEventLoop { delegate, mtm }, + _marker: PhantomData, + }, + panic_info, + }) + } + + pub fn window_target(&self) -> &RootWindowTarget { + &self.window_target + } + + pub fn run<F>(mut self, handler: F) -> Result<(), EventLoopError> + where + F: FnMut(Event<T>, &RootWindowTarget), + { + self.run_on_demand(handler) + } + + // NB: we don't base this on `pump_events` because for `MacOs` we can't support + // `pump_events` elegantly (we just ask to run the loop for a "short" amount of + // time and so a layered implementation would end up using a lot of CPU due to + // redundant wake ups. + pub fn run_on_demand<F>(&mut self, handler: F) -> Result<(), EventLoopError> + where + F: FnMut(Event<T>, &RootWindowTarget), + { + let handler = map_user_event(handler, self.receiver.clone()); + + self.delegate.set_event_handler(handler, || { + autoreleasepool(|_| { + // clear / normalize pump_events state + self.delegate.set_wait_timeout(None); + self.delegate.set_stop_before_wait(false); + self.delegate.set_stop_after_wait(false); + self.delegate.set_stop_on_redraw(false); + + if self.delegate.is_launched() { + debug_assert!(!self.delegate.is_running()); + self.delegate.set_is_running(true); + self.delegate.dispatch_init_events(); + } + + // SAFETY: We do not run the application re-entrantly + unsafe { self.app.run() }; + + // While the app is running it's possible that we catch a panic + // to avoid unwinding across an objective-c ffi boundary, which + // will lead to us stopping the `NSApplication` and saving the + // `PanicInfo` so that we can resume the unwind at a controlled, + // safe point in time. + if let Some(panic) = self.panic_info.take() { + resume_unwind(panic); + } + + self.delegate.internal_exit() + }) + }); + + Ok(()) + } + + pub fn pump_events<F>(&mut self, timeout: Option<Duration>, handler: F) -> PumpStatus + where + F: FnMut(Event<T>, &RootWindowTarget), + { + let handler = map_user_event(handler, self.receiver.clone()); + + self.delegate.set_event_handler(handler, || { + autoreleasepool(|_| { + // As a special case, if the application hasn't been launched yet then we at least + // run the loop until it has fully launched. + if !self.delegate.is_launched() { + debug_assert!(!self.delegate.is_running()); + + self.delegate.set_stop_on_launch(); + // SAFETY: We do not run the application re-entrantly + unsafe { self.app.run() }; + + // Note: we dispatch `NewEvents(Init)` + `Resumed` events after the application + // has launched + } else if !self.delegate.is_running() { + // Even though the application may have been launched, it's possible we aren't + // running if the `EventLoop` was run before and has since + // exited. This indicates that we just starting to re-run + // the same `EventLoop` again. + self.delegate.set_is_running(true); + self.delegate.dispatch_init_events(); + } else { + // Only run for as long as the given `Duration` allows so we don't block the + // external loop. + match timeout { + Some(Duration::ZERO) => { + self.delegate.set_wait_timeout(None); + self.delegate.set_stop_before_wait(true); + }, + Some(duration) => { + self.delegate.set_stop_before_wait(false); + let timeout = Instant::now() + duration; + self.delegate.set_wait_timeout(Some(timeout)); + self.delegate.set_stop_after_wait(true); + }, + None => { + self.delegate.set_wait_timeout(None); + self.delegate.set_stop_before_wait(false); + self.delegate.set_stop_after_wait(true); + }, + } + self.delegate.set_stop_on_redraw(true); + // SAFETY: We do not run the application re-entrantly + unsafe { self.app.run() }; + } + + // While the app is running it's possible that we catch a panic + // to avoid unwinding across an objective-c ffi boundary, which + // will lead to us stopping the application and saving the + // `PanicInfo` so that we can resume the unwind at a controlled, + // safe point in time. + if let Some(panic) = self.panic_info.take() { + resume_unwind(panic); + } + + if self.delegate.exiting() { + self.delegate.internal_exit(); + PumpStatus::Exit(0) + } else { + PumpStatus::Continue + } + }) + }) + } + + pub fn create_proxy(&self) -> EventLoopProxy<T> { + EventLoopProxy::new(self.sender.clone()) + } +} + +#[derive(Clone)] +pub(crate) struct OwnedDisplayHandle; + +impl OwnedDisplayHandle { + #[cfg(feature = "rwh_05")] + #[inline] + pub fn raw_display_handle_rwh_05(&self) -> rwh_05::RawDisplayHandle { + rwh_05::AppKitDisplayHandle::empty().into() + } + + #[cfg(feature = "rwh_06")] + #[inline] + pub fn raw_display_handle_rwh_06( + &self, + ) -> Result<rwh_06::RawDisplayHandle, rwh_06::HandleError> { + Ok(rwh_06::AppKitDisplayHandle::new().into()) + } +} + +pub(super) fn stop_app_immediately(app: &NSApplication) { + autoreleasepool(|_| { + app.stop(None); + // To stop event loop immediately, we need to post some event here. + // See: https://stackoverflow.com/questions/48041279/stopping-the-nsapplication-main-event-loop/48064752#48064752 + app.postEvent_atStart(&dummy_event().unwrap(), true); + }); +} + +/// Tell all windows to close. +/// +/// This will synchronously trigger `WindowEvent::Destroyed` within +/// `windowWillClose:`, giving the application one last chance to handle +/// those events. It doesn't matter if the user also ends up closing the +/// windows in `Window`'s `Drop` impl, once a window has been closed once, it +/// stays closed. +/// +/// This ensures that no windows linger on after the event loop has exited, +/// see <https://github.com/rust-windowing/winit/issues/4135>. +pub(super) fn notify_windows_of_exit(app: &NSApplication) { + for window in app.windows() { + window.close(); + } +} + +/// Catches panics that happen inside `f` and when a panic +/// happens, stops the `sharedApplication` +#[inline] +pub fn stop_app_on_panic<F: FnOnce() -> R + UnwindSafe, R>( + mtm: MainThreadMarker, + panic_info: Weak<PanicInfo>, + f: F, +) -> Option<R> { + match catch_unwind(f) { + Ok(r) => Some(r), + Err(e) => { + // It's important that we set the panic before requesting a `stop` + // because some callback are still called during the `stop` message + // and we need to know in those callbacks if the application is currently + // panicking + { + let panic_info = panic_info.upgrade().unwrap(); + panic_info.set_panic(e); + } + let app = NSApplication::sharedApplication(mtm); + stop_app_immediately(&app); + None + }, + } +} + +pub struct EventLoopProxy<T> { + sender: mpsc::Sender<T>, + source: CFRunLoopSourceRef, +} + +unsafe impl<T: Send> Send for EventLoopProxy<T> {} +unsafe impl<T: Send> Sync for EventLoopProxy<T> {} + +impl<T> Drop for EventLoopProxy<T> { + fn drop(&mut self) { + unsafe { + CFRelease(self.source as _); + } + } +} + +impl<T> Clone for EventLoopProxy<T> { + fn clone(&self) -> Self { + EventLoopProxy::new(self.sender.clone()) + } +} + +impl<T> EventLoopProxy<T> { + fn new(sender: mpsc::Sender<T>) -> Self { + unsafe { + // just wake up the eventloop + extern "C" fn event_loop_proxy_handler(_: *const c_void) {} + + // adding a Source to the main CFRunLoop lets us wake it up and + // process user events through the normal OS EventLoop mechanisms. + let rl = CFRunLoopGetMain(); + let mut context = CFRunLoopSourceContext { + version: 0, + info: ptr::null_mut(), + retain: None, + release: None, + copyDescription: None, + equal: None, + hash: None, + schedule: None, + cancel: None, + perform: event_loop_proxy_handler, + }; + let source = CFRunLoopSourceCreate(ptr::null_mut(), CFIndex::MAX - 1, &mut context); + CFRunLoopAddSource(rl, source, kCFRunLoopCommonModes); + CFRunLoopWakeUp(rl); + + EventLoopProxy { sender, source } + } + } + + pub fn send_event(&self, event: T) -> Result<(), EventLoopClosed<T>> { + self.sender.send(event).map_err(|mpsc::SendError(x)| EventLoopClosed(x))?; + unsafe { + // let the main thread know there's a new event + CFRunLoopSourceSignal(self.source); + let rl = CFRunLoopGetMain(); + CFRunLoopWakeUp(rl); + } + Ok(()) + } +} diff --git a/app/vendor/rune/vendor/winit/src/platform_impl/macos/ffi.rs b/app/vendor/rune/vendor/winit/src/platform_impl/macos/ffi.rs new file mode 100644 index 0000000..1daee07 --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/platform_impl/macos/ffi.rs @@ -0,0 +1,256 @@ +// TODO: Upstream these + +#![allow(dead_code, non_snake_case, non_upper_case_globals)] + +use std::ffi::c_void; + +use core_foundation::array::CFArrayRef; +use core_foundation::dictionary::CFDictionaryRef; +use core_foundation::string::CFStringRef; +use core_foundation::uuid::CFUUIDRef; +use core_graphics::base::CGError; +use core_graphics::display::{CGDirectDisplayID, CGDisplayConfigRef}; +use objc2::ffi::NSInteger; +use objc2::runtime::AnyObject; + +pub type CGDisplayFadeInterval = f32; +pub type CGDisplayReservationInterval = f32; +pub type CGDisplayBlendFraction = f32; + +pub const kCGDisplayBlendNormal: f32 = 0.0; +pub const kCGDisplayBlendSolidColor: f32 = 1.0; + +pub type CGDisplayFadeReservationToken = u32; +pub const kCGDisplayFadeReservationInvalidToken: CGDisplayFadeReservationToken = 0; + +pub type Boolean = u8; +pub const FALSE: Boolean = 0; +pub const TRUE: Boolean = 1; + +pub const kCGErrorSuccess: i32 = 0; +pub const kCGErrorFailure: i32 = 1000; +pub const kCGErrorIllegalArgument: i32 = 1001; +pub const kCGErrorInvalidConnection: i32 = 1002; +pub const kCGErrorInvalidContext: i32 = 1003; +pub const kCGErrorCannotComplete: i32 = 1004; +pub const kCGErrorNotImplemented: i32 = 1006; +pub const kCGErrorRangeCheck: i32 = 1007; +pub const kCGErrorTypeCheck: i32 = 1008; +pub const kCGErrorInvalidOperation: i32 = 1010; +pub const kCGErrorNoneAvailable: i32 = 1011; + +pub const IO1BitIndexedPixels: &str = "P"; +pub const IO2BitIndexedPixels: &str = "PP"; +pub const IO4BitIndexedPixels: &str = "PPPP"; +pub const IO8BitIndexedPixels: &str = "PPPPPPPP"; +pub const IO16BitDirectPixels: &str = "-RRRRRGGGGGBBBBB"; +pub const IO32BitDirectPixels: &str = "--------RRRRRRRRGGGGGGGGBBBBBBBB"; + +pub const kIO30BitDirectPixels: &str = "--RRRRRRRRRRGGGGGGGGGGBBBBBBBBBB"; +pub const kIO64BitDirectPixels: &str = "-16R16G16B16"; + +pub const kIO16BitFloatPixels: &str = "-16FR16FG16FB16"; +pub const kIO32BitFloatPixels: &str = "-32FR32FG32FB32"; + +pub const IOYUV422Pixels: &str = "Y4U2V2"; +pub const IO8BitOverlayPixels: &str = "O8"; + +pub type CGWindowLevel = i32; +pub type CGDisplayModeRef = *mut c_void; + +// `CGDisplayCreateUUIDFromDisplayID` comes from the `ColorSync` framework. +// However, that framework was only introduced "publicly" in macOS 10.13. +// +// Since we want to support older versions, we can't link to `ColorSync` +// directly. Fortunately, it has always been available as a subframework of +// `ApplicationServices`, see: +// https://developer.apple.com/library/archive/documentation/MacOSX/Conceptual/OSX_Technology_Overview/SystemFrameworks/SystemFrameworks.html#//apple_ref/doc/uid/TP40001067-CH210-BBCFFIEG +#[link(name = "ApplicationServices", kind = "framework")] +extern "C" { + pub fn CGDisplayCreateUUIDFromDisplayID(display: CGDirectDisplayID) -> CFUUIDRef; + + pub fn CGDisplayGetDisplayIDFromUUID(uuid: CFUUIDRef) -> CGDirectDisplayID; +} + +#[link(name = "CoreGraphics", kind = "framework")] +extern "C" { + pub fn CGRestorePermanentDisplayConfiguration(); + pub fn CGDisplayCapture(display: CGDirectDisplayID) -> CGError; + pub fn CGDisplayRelease(display: CGDirectDisplayID) -> CGError; + pub fn CGConfigureDisplayFadeEffect( + config: CGDisplayConfigRef, + fadeOutSeconds: CGDisplayFadeInterval, + fadeInSeconds: CGDisplayFadeInterval, + fadeRed: f32, + fadeGreen: f32, + fadeBlue: f32, + ) -> CGError; + pub fn CGAcquireDisplayFadeReservation( + seconds: CGDisplayReservationInterval, + token: *mut CGDisplayFadeReservationToken, + ) -> CGError; + pub fn CGDisplayFade( + token: CGDisplayFadeReservationToken, + duration: CGDisplayFadeInterval, + startBlend: CGDisplayBlendFraction, + endBlend: CGDisplayBlendFraction, + redBlend: f32, + greenBlend: f32, + blueBlend: f32, + synchronous: Boolean, + ) -> CGError; + pub fn CGReleaseDisplayFadeReservation(token: CGDisplayFadeReservationToken) -> CGError; + pub fn CGShieldingWindowLevel() -> CGWindowLevel; + pub fn CGDisplaySetDisplayMode( + display: CGDirectDisplayID, + mode: CGDisplayModeRef, + options: CFDictionaryRef, + ) -> CGError; + pub fn CGDisplayCopyAllDisplayModes( + display: CGDirectDisplayID, + options: CFDictionaryRef, + ) -> CFArrayRef; + pub fn CGDisplayModeGetPixelWidth(mode: CGDisplayModeRef) -> usize; + pub fn CGDisplayModeGetPixelHeight(mode: CGDisplayModeRef) -> usize; + pub fn CGDisplayModeGetRefreshRate(mode: CGDisplayModeRef) -> f64; + pub fn CGDisplayModeCopyPixelEncoding(mode: CGDisplayModeRef) -> CFStringRef; + pub fn CGDisplayModeRetain(mode: CGDisplayModeRef); + pub fn CGDisplayModeRelease(mode: CGDisplayModeRef); + + // Wildly used private APIs; Apple uses them for their Terminal.app. + pub fn CGSMainConnectionID() -> *mut AnyObject; + pub fn CGSSetWindowBackgroundBlurRadius( + connection_id: *mut AnyObject, + window_id: NSInteger, + radius: i64, + ) -> i32; +} + +mod core_video { + use super::*; + + #[link(name = "CoreVideo", kind = "framework")] + extern "C" {} + + // CVBase.h + + pub type CVTimeFlags = i32; // int32_t + pub const kCVTimeIsIndefinite: CVTimeFlags = 1 << 0; + + #[repr(C)] + #[derive(Debug, Clone)] + pub struct CVTime { + pub time_value: i64, // int64_t + pub time_scale: i32, // int32_t + pub flags: i32, // int32_t + } + + // CVReturn.h + + pub type CVReturn = i32; // int32_t + pub const kCVReturnSuccess: CVReturn = 0; + + // CVDisplayLink.h + + pub type CVDisplayLinkRef = *mut c_void; + + extern "C" { + pub fn CVDisplayLinkCreateWithCGDisplay( + displayID: CGDirectDisplayID, + displayLinkOut: *mut CVDisplayLinkRef, + ) -> CVReturn; + pub fn CVDisplayLinkGetNominalOutputVideoRefreshPeriod( + displayLink: CVDisplayLinkRef, + ) -> CVTime; + pub fn CVDisplayLinkRelease(displayLink: CVDisplayLinkRef); + } +} + +pub use core_video::*; +#[repr(transparent)] +pub struct TISInputSource(std::ffi::c_void); +pub type TISInputSourceRef = *mut TISInputSource; + +#[repr(transparent)] +pub struct UCKeyboardLayout(std::ffi::c_void); + +pub type OptionBits = u32; +pub type UniCharCount = std::os::raw::c_ulong; +pub type UniChar = std::os::raw::c_ushort; +pub type OSStatus = i32; + +#[allow(non_upper_case_globals)] +pub const kUCKeyActionDisplay: u16 = 3; +#[allow(non_upper_case_globals)] +pub const kUCKeyTranslateNoDeadKeysMask: OptionBits = 1; + +#[link(name = "Carbon", kind = "framework")] +extern "C" { + pub static kTISPropertyUnicodeKeyLayoutData: CFStringRef; + + #[allow(non_snake_case)] + pub fn TISGetInputSourceProperty( + inputSource: TISInputSourceRef, + propertyKey: CFStringRef, + ) -> *mut c_void; + + pub fn TISCopyCurrentKeyboardLayoutInputSource() -> TISInputSourceRef; + + pub fn LMGetKbdType() -> u8; + + #[allow(non_snake_case)] + pub fn UCKeyTranslate( + keyLayoutPtr: *const UCKeyboardLayout, + virtualKeyCode: u16, + keyAction: u16, + modifierKeyState: u32, + keyboardType: u32, + keyTranslateOptions: OptionBits, + deadKeyState: *mut u32, + maxStringLength: UniCharCount, + actualStringLength: *mut UniCharCount, + unicodeString: *mut UniChar, + ) -> OSStatus; +} + +// CGWindowLevel.h +// +// Note: There are two different things at play in this header: +// `CGWindowLevel` and `CGWindowLevelKey`. +// +// It seems like there was a push towards using "key" values instead of the +// raw window level values, and then you were supposed to use +// `CGWindowLevelForKey` to get the actual level. +// +// But the values that `NSWindowLevel` has are compiled in, and as such has +// to remain ABI compatible, so they're safe for us to hardcode as well. +#[allow(dead_code, non_upper_case_globals)] +mod window_level { + const kCGNumReservedWindowLevels: i32 = 16; + const kCGNumReservedBaseWindowLevels: i32 = 5; + + pub const kCGBaseWindowLevel: i32 = i32::MIN; + pub const kCGMinimumWindowLevel: i32 = kCGBaseWindowLevel + kCGNumReservedBaseWindowLevels; + pub const kCGMaximumWindowLevel: i32 = i32::MAX - kCGNumReservedWindowLevels; + + pub const kCGDesktopWindowLevel: i32 = kCGMinimumWindowLevel + 20; + pub const kCGDesktopIconWindowLevel: i32 = kCGDesktopWindowLevel + 20; + pub const kCGBackstopMenuLevel: i32 = -20; + pub const kCGNormalWindowLevel: i32 = 0; + pub const kCGFloatingWindowLevel: i32 = 3; + pub const kCGTornOffMenuWindowLevel: i32 = 3; + pub const kCGModalPanelWindowLevel: i32 = 8; + pub const kCGUtilityWindowLevel: i32 = 19; + pub const kCGDockWindowLevel: i32 = 20; + pub const kCGMainMenuWindowLevel: i32 = 24; + pub const kCGStatusWindowLevel: i32 = 25; + pub const kCGPopUpMenuWindowLevel: i32 = 101; + pub const kCGOverlayWindowLevel: i32 = 102; + pub const kCGHelpWindowLevel: i32 = 200; + pub const kCGDraggingWindowLevel: i32 = 500; + pub const kCGScreenSaverWindowLevel: i32 = 1000; + pub const kCGAssistiveTechHighWindowLevel: i32 = 1500; + pub const kCGCursorWindowLevel: i32 = kCGMaximumWindowLevel - 1; +} + +pub use window_level::*; diff --git a/app/vendor/rune/vendor/winit/src/platform_impl/macos/ime_text.rs b/app/vendor/rune/vendor/winit/src/platform_impl/macos/ime_text.rs new file mode 100644 index 0000000..8725e96 --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/platform_impl/macos/ime_text.rs @@ -0,0 +1,30 @@ +//! Rune: what `Ime::Preedit` can't carry, beside it. The app's text around its selection, for +//! `selectedRange` and `attributedSubstringForProposedRange:` (reconversion), a composition's +//! clauses from `setMarkedText:`'s attributes, and the range a reconversion replaces. + +use std::cell::RefCell; +use std::ops::Range; + +thread_local! { + /// The focused field's paragraph and its selection, UTF-8 bytes. + pub(crate) static TEXT: RefCell<Option<(String, Range<usize>)>> = const { RefCell::new(None) }; + /// The last marked text and its clauses (byte ranges, whether each is being converted). + pub(crate) static CLAUSES: RefCell<Option<(String, Vec<(Range<usize>, bool)>)>> = const { RefCell::new(None) }; + /// The range of `TEXT` a reconversion's marked text replaces, UTF-8 bytes. + pub(crate) static REPLACEMENT: RefCell<Option<Range<usize>>> = const { RefCell::new(None) }; +} + +/// `utf16` UTF-16 units into `text` as a UTF-8 byte offset, clamped to its end. +pub(crate) fn byte_of(text: &str, utf16: usize) -> usize { + let mut units = 0; + for (i, c) in text.char_indices() { + if units >= utf16 { return i; } + units += c.len_utf16(); + } + text.len() +} + +/// UTF-8 byte `byte` of `text` in UTF-16 units. +pub(crate) fn utf16_of(text: &str, byte: usize) -> usize { + text[..byte.min(text.len())].encode_utf16().count() +} diff --git a/app/vendor/rune/vendor/winit/src/platform_impl/macos/menu.rs b/app/vendor/rune/vendor/winit/src/platform_impl/macos/menu.rs new file mode 100644 index 0000000..cdebea0 --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/platform_impl/macos/menu.rs @@ -0,0 +1,107 @@ +use objc2::rc::Retained; +use objc2::runtime::Sel; +use objc2::sel; +use objc2_app_kit::{NSApplication, NSEventModifierFlags, NSMenu, NSMenuItem}; +use objc2_foundation::{ns_string, MainThreadMarker, NSProcessInfo, NSString}; + +struct KeyEquivalent<'a> { + key: &'a NSString, + masks: Option<NSEventModifierFlags>, +} + +pub fn initialize(app: &NSApplication) { + let mtm = MainThreadMarker::from(app); + let menubar = NSMenu::new(mtm); + let app_menu_item = NSMenuItem::new(mtm); + menubar.addItem(&app_menu_item); + + let app_menu = NSMenu::new(mtm); + let process_name = NSProcessInfo::processInfo().processName(); + + // About menu item + let about_item_title = ns_string!("About ").stringByAppendingString(&process_name); + let about_item = + menu_item(mtm, &about_item_title, Some(sel!(orderFrontStandardAboutPanel:)), None); + + // Services menu item + let services_menu = NSMenu::new(mtm); + let services_item = menu_item(mtm, ns_string!("Services"), None, None); + services_item.setSubmenu(Some(&services_menu)); + + // Separator menu item + let sep_first = NSMenuItem::separatorItem(mtm); + + // Hide application menu item + let hide_item_title = ns_string!("Hide ").stringByAppendingString(&process_name); + let hide_item = menu_item( + mtm, + &hide_item_title, + Some(sel!(hide:)), + Some(KeyEquivalent { key: ns_string!("h"), masks: None }), + ); + + // Hide other applications menu item + let hide_others_item_title = ns_string!("Hide Others"); + let hide_others_item = menu_item( + mtm, + hide_others_item_title, + Some(sel!(hideOtherApplications:)), + Some(KeyEquivalent { + key: ns_string!("h"), + masks: Some( + NSEventModifierFlags::NSEventModifierFlagOption + | NSEventModifierFlags::NSEventModifierFlagCommand, + ), + }), + ); + + // Show applications menu item + let show_all_item_title = ns_string!("Show All"); + let show_all_item = + menu_item(mtm, show_all_item_title, Some(sel!(unhideAllApplications:)), None); + + // Separator menu item + let sep = NSMenuItem::separatorItem(mtm); + + // Quit application menu item + let quit_item_title = ns_string!("Quit ").stringByAppendingString(&process_name); + let quit_item = menu_item( + mtm, + &quit_item_title, + Some(sel!(terminate:)), + Some(KeyEquivalent { key: ns_string!("q"), masks: None }), + ); + + app_menu.addItem(&about_item); + app_menu.addItem(&sep_first); + app_menu.addItem(&services_item); + app_menu.addItem(&hide_item); + app_menu.addItem(&hide_others_item); + app_menu.addItem(&show_all_item); + app_menu.addItem(&sep); + app_menu.addItem(&quit_item); + app_menu_item.setSubmenu(Some(&app_menu)); + + unsafe { app.setServicesMenu(Some(&services_menu)) }; + app.setMainMenu(Some(&menubar)); +} + +fn menu_item( + mtm: MainThreadMarker, + title: &NSString, + selector: Option<Sel>, + key_equivalent: Option<KeyEquivalent<'_>>, +) -> Retained<NSMenuItem> { + let (key, masks) = match key_equivalent { + Some(ke) => (ke.key, ke.masks), + None => (ns_string!(""), None), + }; + let item = unsafe { + NSMenuItem::initWithTitle_action_keyEquivalent(mtm.alloc(), title, selector, key) + }; + if let Some(masks) = masks { + item.setKeyEquivalentModifierMask(masks) + } + + item +} diff --git a/app/vendor/rune/vendor/winit/src/platform_impl/macos/mod.rs b/app/vendor/rune/vendor/winit/src/platform_impl/macos/mod.rs new file mode 100644 index 0000000..fff68ab --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/platform_impl/macos/mod.rs @@ -0,0 +1,62 @@ +#[macro_use] +mod util; + +mod app; +mod app_state; +mod cursor; +mod event; +mod event_handler; +mod event_loop; +mod ffi; +pub(crate) mod ime_text; +mod menu; +mod monitor; +mod observer; +mod view; +mod window; +mod window_delegate; + +use std::fmt; + +pub(crate) use self::event::{physicalkey_to_scancode, scancode_to_physicalkey, KeyEventExtra}; +pub(crate) use self::event_loop::{ + ActiveEventLoop, EventLoop, EventLoopProxy, OwnedDisplayHandle, + PlatformSpecificEventLoopAttributes, +}; +pub(crate) use self::monitor::{MonitorHandle, VideoModeHandle}; +pub(crate) use self::window::WindowId; +pub(crate) use self::window_delegate::PlatformSpecificWindowAttributes; +use crate::event::DeviceId as RootDeviceId; + +pub(crate) use self::cursor::CustomCursor as PlatformCustomCursor; +pub(crate) use self::window::Window; +pub(crate) use crate::cursor::OnlyCursorImageSource as PlatformCustomCursorSource; +pub(crate) use crate::icon::NoIcon as PlatformIcon; +pub(crate) use crate::platform_impl::Fullscreen; + +#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub struct DeviceId; + +impl DeviceId { + pub const fn dummy() -> Self { + DeviceId + } +} + +// Constant device ID; to be removed when if backend is updated to report real device IDs. +pub(crate) const DEVICE_ID: RootDeviceId = RootDeviceId(DeviceId); + +#[derive(Debug)] +pub enum OsError { + CGError(core_graphics::base::CGError), + CreationError(&'static str), +} + +impl fmt::Display for OsError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + OsError::CGError(e) => f.pad(&format!("CGError {e}")), + OsError::CreationError(e) => f.pad(e), + } + } +} diff --git a/app/vendor/rune/vendor/winit/src/platform_impl/macos/monitor.rs b/app/vendor/rune/vendor/winit/src/platform_impl/macos/monitor.rs new file mode 100644 index 0000000..44e6316 --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/platform_impl/macos/monitor.rs @@ -0,0 +1,409 @@ +#![allow(clippy::unnecessary_cast)] + +use std::collections::VecDeque; +use std::fmt; + +use core_foundation::array::{CFArrayGetCount, CFArrayGetValueAtIndex}; +use core_foundation::base::{CFRelease, TCFType}; +use core_foundation::string::CFString; +use core_foundation::uuid::{CFUUIDGetUUIDBytes, CFUUID}; +use core_graphics::display::{ + CGDirectDisplayID, CGDisplay, CGDisplayBounds, CGDisplayCopyDisplayMode, +}; +use objc2::rc::Retained; +use objc2::runtime::AnyObject; +use objc2_app_kit::NSScreen; +use objc2_foundation::{ns_string, run_on_main, MainThreadMarker, NSNumber, NSPoint, NSRect}; +use tracing::warn; + +use super::ffi; +use crate::dpi::{LogicalPosition, PhysicalPosition, PhysicalSize}; + +#[derive(Clone)] +pub struct VideoModeHandle { + size: PhysicalSize<u32>, + bit_depth: u16, + refresh_rate_millihertz: u32, + pub(crate) monitor: MonitorHandle, + pub(crate) native_mode: NativeDisplayMode, +} + +impl PartialEq for VideoModeHandle { + fn eq(&self, other: &Self) -> bool { + self.size == other.size + && self.bit_depth == other.bit_depth + && self.refresh_rate_millihertz == other.refresh_rate_millihertz + && self.monitor == other.monitor + } +} + +impl Eq for VideoModeHandle {} + +impl std::hash::Hash for VideoModeHandle { + fn hash<H: std::hash::Hasher>(&self, state: &mut H) { + self.size.hash(state); + self.bit_depth.hash(state); + self.refresh_rate_millihertz.hash(state); + self.monitor.hash(state); + } +} + +impl std::fmt::Debug for VideoModeHandle { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("VideoModeHandle") + .field("size", &self.size) + .field("bit_depth", &self.bit_depth) + .field("refresh_rate_millihertz", &self.refresh_rate_millihertz) + .field("monitor", &self.monitor) + .finish() + } +} + +pub struct NativeDisplayMode(pub ffi::CGDisplayModeRef); + +unsafe impl Send for NativeDisplayMode {} +unsafe impl Sync for NativeDisplayMode {} + +impl Drop for NativeDisplayMode { + fn drop(&mut self) { + unsafe { + ffi::CGDisplayModeRelease(self.0); + } + } +} + +impl Clone for NativeDisplayMode { + fn clone(&self) -> Self { + unsafe { + ffi::CGDisplayModeRetain(self.0); + } + NativeDisplayMode(self.0) + } +} + +impl VideoModeHandle { + pub fn size(&self) -> PhysicalSize<u32> { + self.size + } + + pub fn bit_depth(&self) -> u16 { + self.bit_depth + } + + pub fn refresh_rate_millihertz(&self) -> u32 { + self.refresh_rate_millihertz + } + + pub fn monitor(&self) -> MonitorHandle { + self.monitor.clone() + } +} + +/// `CGDirectDisplayID` is documented as: +/// > a framebuffer, a color correction (gamma) table, and possibly an attached monitor. +/// +/// That is, it doesn't actually represent the monitor itself. Instead, we use the UUID of the +/// monitor, as retrieved from `CGDisplayCreateUUIDFromDisplayID` (this makes the monitor ID stable, +/// even across reboots and video mode changes). +/// +/// NOTE: I'd be perfectly valid to store `[u8; 16]` in here instead, we only store `CFUUID` to +/// avoid having to re-create it when we want to fetch the display ID. +#[derive(Clone)] +pub struct MonitorHandle(CFUUID); + +// SAFETY: CFUUID is immutable. +// FIXME(madsmtm): Upstream this into `objc2-core-foundation`. +unsafe impl Send for MonitorHandle {} +unsafe impl Sync for MonitorHandle {} + +type MonitorUuid = [u8; 16]; + +impl MonitorHandle { + /// Internal comparisons of [`MonitorHandle`]s are done first requesting a UUID for the handle. + fn uuid(&self) -> MonitorUuid { + let uuid = unsafe { CFUUIDGetUUIDBytes(self.0.as_concrete_TypeRef()) }; + MonitorUuid::from([ + uuid.byte0, + uuid.byte1, + uuid.byte2, + uuid.byte3, + uuid.byte4, + uuid.byte5, + uuid.byte6, + uuid.byte7, + uuid.byte8, + uuid.byte9, + uuid.byte10, + uuid.byte11, + uuid.byte12, + uuid.byte13, + uuid.byte14, + uuid.byte15, + ]) + } + + fn display_id(&self) -> CGDirectDisplayID { + unsafe { ffi::CGDisplayGetDisplayIDFromUUID(self.0.as_concrete_TypeRef()) } + } + + #[track_caller] + pub(crate) fn new(display_id: CGDirectDisplayID) -> Option<Self> { + // kCGNullDirectDisplay + if display_id == 0 { + // `CGDisplayCreateUUIDFromDisplayID` checks kCGNullDirectDisplay internally. + warn!("constructing monitor from invalid display ID 0; falling back to main monitor"); + } + let ptr = unsafe { ffi::CGDisplayCreateUUIDFromDisplayID(display_id) }; + if ptr.is_null() { + return None; + } + Some(Self(unsafe { CFUUID::wrap_under_create_rule(ptr) })) + } +} + +impl PartialEq for MonitorHandle { + fn eq(&self, other: &Self) -> bool { + self.uuid() == other.uuid() + } +} + +impl Eq for MonitorHandle {} + +impl PartialOrd for MonitorHandle { + fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> { + Some(self.cmp(other)) + } +} + +impl Ord for MonitorHandle { + fn cmp(&self, other: &Self) -> std::cmp::Ordering { + self.uuid().cmp(&other.uuid()) + } +} + +impl std::hash::Hash for MonitorHandle { + fn hash<H: std::hash::Hasher>(&self, state: &mut H) { + self.uuid().hash(state); + } +} + +pub fn available_monitors() -> VecDeque<MonitorHandle> { + if let Ok(displays) = CGDisplay::active_displays() { + let mut monitors = VecDeque::with_capacity(displays.len()); + for display in displays { + // Display ID just fetched from `CGGetActiveDisplayList`, should be fine to unwrap. + monitors.push_back(MonitorHandle::new(display).expect("invalid display ID")); + } + monitors + } else { + VecDeque::with_capacity(0) + } +} + +pub fn primary_monitor() -> MonitorHandle { + // Display ID just fetched from `CGMainDisplayID`, should be fine to unwrap. + MonitorHandle::new(CGDisplay::main().id).expect("invalid display ID") +} + +impl fmt::Debug for MonitorHandle { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("MonitorHandle") + .field("name", &self.name()) + .field("native_identifier", &self.native_identifier()) + .field("size", &self.size()) + .field("position", &self.position()) + .field("scale_factor", &self.scale_factor()) + .field("refresh_rate_millihertz", &self.refresh_rate_millihertz()) + .finish_non_exhaustive() + } +} + +impl MonitorHandle { + // TODO: Be smarter about this: + // <https://github.com/glfw/glfw/blob/57cbded0760a50b9039ee0cb3f3c14f60145567c/src/cocoa_monitor.m#L44-L126> + pub fn name(&self) -> Option<String> { + let screen_num = CGDisplay::new(self.display_id()).model_number(); + Some(format!("Monitor #{screen_num}")) + } + + #[inline] + pub fn native_identifier(&self) -> u32 { + self.display_id() + } + + pub fn size(&self) -> PhysicalSize<u32> { + let display = CGDisplay::new(self.display_id()); + let height = display.pixels_high(); + let width = display.pixels_wide(); + PhysicalSize::from_logical::<_, f64>((width as f64, height as f64), self.scale_factor()) + } + + #[inline] + pub fn position(&self) -> PhysicalPosition<i32> { + // This is already in screen coordinates. If we were using `NSScreen`, + // then a conversion would've been needed: + // flip_window_screen_coordinates(self.ns_screen(mtm)?.frame()) + let bounds = unsafe { CGDisplayBounds(self.native_identifier()) }; + let position = LogicalPosition::new(bounds.origin.x, bounds.origin.y); + position.to_physical(self.scale_factor()) + } + + pub fn scale_factor(&self) -> f64 { + run_on_main(|mtm| { + match self.ns_screen(mtm) { + Some(screen) => screen.backingScaleFactor() as f64, + None => 1.0, // default to 1.0 when we can't find the screen + } + }) + } + + pub fn refresh_rate_millihertz(&self) -> Option<u32> { + unsafe { + let current_display_mode = + NativeDisplayMode(CGDisplayCopyDisplayMode(self.display_id()) as _); + let refresh_rate = ffi::CGDisplayModeGetRefreshRate(current_display_mode.0); + if refresh_rate > 0.0 { + return Some((refresh_rate * 1000.0).round() as u32); + } + + let mut display_link = std::ptr::null_mut(); + if ffi::CVDisplayLinkCreateWithCGDisplay(self.display_id(), &mut display_link) + != ffi::kCVReturnSuccess + { + return None; + } + let time = ffi::CVDisplayLinkGetNominalOutputVideoRefreshPeriod(display_link); + ffi::CVDisplayLinkRelease(display_link); + + // This value is indefinite if an invalid display link was specified + if time.flags & ffi::kCVTimeIsIndefinite != 0 { + return None; + } + + (time.time_scale as i64).checked_div(time.time_value).map(|v| (v * 1000) as u32) + } + } + + pub fn video_modes(&self) -> impl Iterator<Item = VideoModeHandle> { + let refresh_rate_millihertz = self.refresh_rate_millihertz().unwrap_or(0); + let monitor = self.clone(); + + unsafe { + let modes = { + let array = ffi::CGDisplayCopyAllDisplayModes(self.display_id(), std::ptr::null()); + if array.is_null() { + // Occasionally, certain CalDigit Thunderbolt Hubs report a spurious monitor + // during sleep/wake/cycling monitors. It tends to have null + // or 1 video mode only. See <https://github.com/bevyengine/bevy/issues/17827>. + warn!(monitor = ?self, "failed to get a list of display modes"); + Vec::new() + } else { + let array_count = CFArrayGetCount(array); + let modes: Vec<_> = (0..array_count) + .map(move |i| { + let mode = CFArrayGetValueAtIndex(array, i) as *mut _; + ffi::CGDisplayModeRetain(mode); + mode + }) + .collect(); + CFRelease(array as *const _); + modes + } + }; + + modes.into_iter().map(move |mode| { + let cg_refresh_rate_hertz = ffi::CGDisplayModeGetRefreshRate(mode); + + // CGDisplayModeGetRefreshRate returns 0.0 for any display that + // isn't a CRT + let refresh_rate_millihertz = if cg_refresh_rate_hertz > 0.0 { + (cg_refresh_rate_hertz * 1000.0).round() as u32 + } else { + refresh_rate_millihertz + }; + + let pixel_encoding = + CFString::wrap_under_create_rule(ffi::CGDisplayModeCopyPixelEncoding(mode)) + .to_string(); + let bit_depth = if pixel_encoding.eq_ignore_ascii_case(ffi::IO32BitDirectPixels) { + 32 + } else if pixel_encoding.eq_ignore_ascii_case(ffi::IO16BitDirectPixels) { + 16 + } else if pixel_encoding.eq_ignore_ascii_case(ffi::kIO30BitDirectPixels) { + 30 + } else { + unimplemented!() + }; + + VideoModeHandle { + size: PhysicalSize::new( + ffi::CGDisplayModeGetPixelWidth(mode) as u32, + ffi::CGDisplayModeGetPixelHeight(mode) as u32, + ), + refresh_rate_millihertz, + bit_depth, + monitor: monitor.clone(), + native_mode: NativeDisplayMode(mode), + } + }) + } + } + + pub(crate) fn ns_screen(&self, mtm: MainThreadMarker) -> Option<Retained<NSScreen>> { + let uuid = self.uuid(); + NSScreen::screens(mtm).into_iter().find(|screen| { + let other_native_id = get_display_id(screen); + if let Some(other) = MonitorHandle::new(other_native_id) { + uuid == other.uuid() + } else { + // Display ID was just fetched from live NSScreen, but can still result in `None` + // with certain Thunderbolt docked monitors. + warn!(other_native_id, "comparing against screen with invalid display ID"); + false + } + }) + } +} + +pub(crate) fn get_display_id(screen: &NSScreen) -> u32 { + let key = ns_string!("NSScreenNumber"); + + objc2::rc::autoreleasepool(|_| { + let device_description = screen.deviceDescription(); + + // Retrieve the CGDirectDisplayID associated with this screen + // + // SAFETY: The value from @"NSScreenNumber" in deviceDescription is guaranteed + // to be an NSNumber. See documentation for `deviceDescription` for details: + // <https://developer.apple.com/documentation/appkit/nsscreen/1388360-devicedescription?language=objc> + let obj = device_description + .get(key) + .expect("failed getting screen display id from device description"); + let obj: *const AnyObject = obj; + let obj: *const NSNumber = obj.cast(); + let obj: &NSNumber = unsafe { &*obj }; + + obj.as_u32() + }) +} + +/// Core graphics screen coordinates are relative to the top-left corner of +/// the so-called "main" display, with y increasing downwards - which is +/// exactly what we want in Winit. +/// +/// However, `NSWindow` and `NSScreen` changes these coordinates to: +/// 1. Be relative to the bottom-left corner of the "main" screen. +/// 2. Be relative to the bottom-left corner of the window/screen itself. +/// 3. Have y increasing upwards. +/// +/// This conversion happens to be symmetric, so we only need this one function +/// to convert between the two coordinate systems. +pub(crate) fn flip_window_screen_coordinates(frame: NSRect) -> NSPoint { + // It is intentional that we use `CGMainDisplayID` (as opposed to + // `NSScreen::mainScreen`), because that's what the screen coordinates + // are relative to, no matter which display the window is currently on. + let main_screen_height = CGDisplay::main().bounds().size.height; + + let y = main_screen_height - frame.size.height - frame.origin.y; + NSPoint::new(frame.origin.x, y) +} diff --git a/app/vendor/rune/vendor/winit/src/platform_impl/macos/observer.rs b/app/vendor/rune/vendor/winit/src/platform_impl/macos/observer.rs new file mode 100644 index 0000000..8339803 --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/platform_impl/macos/observer.rs @@ -0,0 +1,312 @@ +//! Utilities for working with `CFRunLoop`. +//! +//! See Apple's documentation on Run Loops for details: +//! <https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/Multithreading/RunLoopManagement/RunLoopManagement.html> +use std::cell::Cell; +use std::ffi::c_void; +use std::panic::{AssertUnwindSafe, UnwindSafe}; +use std::ptr; +use std::rc::Weak; +use std::time::Instant; + +use block2::Block; +use core_foundation::base::{CFIndex, CFOptionFlags, CFRelease, CFTypeRef}; +use core_foundation::date::CFAbsoluteTimeGetCurrent; +use core_foundation::runloop::{ + kCFRunLoopAfterWaiting, kCFRunLoopBeforeWaiting, kCFRunLoopCommonModes, kCFRunLoopDefaultMode, + kCFRunLoopExit, CFRunLoopActivity, CFRunLoopAddObserver, CFRunLoopAddTimer, CFRunLoopGetMain, + CFRunLoopObserverCallBack, CFRunLoopObserverContext, CFRunLoopObserverCreate, + CFRunLoopObserverRef, CFRunLoopRef, CFRunLoopTimerCreate, CFRunLoopTimerInvalidate, + CFRunLoopTimerRef, CFRunLoopTimerSetNextFireDate, CFRunLoopWakeUp, +}; +use objc2_foundation::MainThreadMarker; +use tracing::error; + +use super::app_state::ApplicationDelegate; +use super::event_loop::{stop_app_on_panic, PanicInfo}; +use super::ffi; + +unsafe fn control_flow_handler<F>(panic_info: *mut c_void, f: F) +where + F: FnOnce(Weak<PanicInfo>) + UnwindSafe, +{ + let info_from_raw = unsafe { Weak::from_raw(panic_info as *mut PanicInfo) }; + // Asserting unwind safety on this type should be fine because `PanicInfo` is + // `RefUnwindSafe` and `Rc<T>` is `UnwindSafe` if `T` is `RefUnwindSafe`. + let panic_info = AssertUnwindSafe(Weak::clone(&info_from_raw)); + // `from_raw` takes ownership of the data behind the pointer. + // But if this scope takes ownership of the weak pointer, then + // the weak pointer will get free'd at the end of the scope. + // However we want to keep that weak reference around after the function. + std::mem::forget(info_from_raw); + + let mtm = MainThreadMarker::new().unwrap(); + stop_app_on_panic(mtm, Weak::clone(&panic_info), move || { + let _ = &panic_info; + f(panic_info.0) + }); +} + +// begin is queued with the highest priority to ensure it is processed before other observers +extern "C" fn control_flow_begin_handler( + _: CFRunLoopObserverRef, + activity: CFRunLoopActivity, + panic_info: *mut c_void, +) { + unsafe { + control_flow_handler(panic_info, |panic_info| { + #[allow(non_upper_case_globals)] + match activity { + kCFRunLoopAfterWaiting => { + // trace!("Triggered `CFRunLoopAfterWaiting`"); + ApplicationDelegate::get(MainThreadMarker::new().unwrap()).wakeup(panic_info); + // trace!("Completed `CFRunLoopAfterWaiting`"); + }, + _ => unreachable!(), + } + }); + } +} + +// end is queued with the lowest priority to ensure it is processed after other observers +// without that, LoopExiting would get sent after AboutToWait +extern "C" fn control_flow_end_handler( + _: CFRunLoopObserverRef, + activity: CFRunLoopActivity, + panic_info: *mut c_void, +) { + unsafe { + control_flow_handler(panic_info, |panic_info| { + #[allow(non_upper_case_globals)] + match activity { + kCFRunLoopBeforeWaiting => { + // trace!("Triggered `CFRunLoopBeforeWaiting`"); + ApplicationDelegate::get(MainThreadMarker::new().unwrap()).cleared(panic_info); + // trace!("Completed `CFRunLoopBeforeWaiting`"); + }, + kCFRunLoopExit => (), // unimplemented!(), // not expected to ever happen + _ => unreachable!(), + } + }); + } +} + +#[derive(Debug)] +pub struct RunLoop(CFRunLoopRef); + +impl Default for RunLoop { + fn default() -> Self { + Self(ptr::null_mut()) + } +} + +impl RunLoop { + pub fn main(mtm: MainThreadMarker) -> Self { + // SAFETY: We have a MainThreadMarker here, which means we know we're on the main thread, so + // scheduling (and scheduling a non-`Send` block) to that thread is allowed. + let _ = mtm; + RunLoop(unsafe { CFRunLoopGetMain() }) + } + + pub fn wakeup(&self) { + unsafe { CFRunLoopWakeUp(self.0) } + } + + unsafe fn add_observer( + &self, + flags: CFOptionFlags, + priority: CFIndex, + handler: CFRunLoopObserverCallBack, + context: *mut CFRunLoopObserverContext, + ) { + let observer = unsafe { + CFRunLoopObserverCreate( + ptr::null_mut(), + flags, + ffi::TRUE, // Indicates we want this to run repeatedly + priority, // The lower the value, the sooner this will run + handler, + context, + ) + }; + unsafe { CFRunLoopAddObserver(self.0, observer, kCFRunLoopCommonModes) }; + } + + /// Submit a closure to run on the main thread as the next step in the run loop, before other + /// event sources are processed. + /// + /// This is used for running event handlers, as those are not allowed to run re-entrantly. + /// + /// # Implementation + /// + /// This queuing could be implemented in the following several ways with subtle differences in + /// timing. This list is sorted in rough order in which they are run: + /// + /// 1. Using `CFRunLoopPerformBlock` or `-[NSRunLoop performBlock:]`. + /// + /// 2. Using `-[NSObject performSelectorOnMainThread:withObject:waitUntilDone:]` or wrapping the + /// event in `NSEvent` and posting that to `-[NSApplication postEvent:atStart:]` (both + /// creates a custom `CFRunLoopSource`, and signals that to wake up the main event loop). + /// + /// a. `atStart = true`. + /// + /// b. `atStart = false`. + /// + /// 3. `dispatch_async` or `dispatch_async_f`. Note that this may appear before 2b, it does not + /// respect the ordering that runloop events have. + /// + /// We choose the first one, both for ease-of-implementation, but mostly for consistency, as we + /// want the event to be queued in a way that preserves the order the events originally arrived + /// in. + /// + /// As an example, let's assume that we receive two events from the user, a mouse click which we + /// handled by queuing it, and a window resize which we handled immediately. If we allowed + /// AppKit to choose the ordering when queuing the mouse event, it might get put in the back of + /// the queue, and the events would appear out of order to the user of Winit. So we must instead + /// put the event at the very front of the queue, to be handled as soon as possible after + /// handling whatever event it's currently handling. + pub fn queue_closure(&self, closure: impl FnOnce() + 'static) { + extern "C" { + fn CFRunLoopPerformBlock(rl: CFRunLoopRef, mode: CFTypeRef, block: &Block<dyn Fn()>); + } + + // Convert `FnOnce()` to `Block<dyn Fn()>`. + let closure = Cell::new(Some(closure)); + let block = block2::RcBlock::new(move || { + if let Some(closure) = closure.take() { + closure() + } else { + error!("tried to execute queued closure on main thread twice"); + } + }); + + // There are a few common modes (`kCFRunLoopCommonModes`) defined by Cocoa: + // - `NSDefaultRunLoopMode`, alias of `kCFRunLoopDefaultMode`. + // - `NSEventTrackingRunLoopMode`, used when mouse-dragging and live-resizing a window. + // - `NSModalPanelRunLoopMode`, used when running a modal inside the Winit event loop. + // - `NSConnectionReplyMode`: TODO. + // + // We only want to run event handlers in the default mode, as we support running a blocking + // modal inside a Winit event handler (see [#1779]) which outrules the modal panel mode, and + // resizing such panel window enters the event tracking run loop mode, so we can't directly + // trigger events inside that mode either. + // + // Any events that are queued while running a modal or when live-resizing will instead wait, + // and be delivered to the application afterwards. + // + // [#1779]: https://github.com/rust-windowing/winit/issues/1779 + let mode = unsafe { kCFRunLoopDefaultMode as CFTypeRef }; + + // SAFETY: The runloop is valid, the mode is a `CFStringRef`, and the block is `'static`. + unsafe { CFRunLoopPerformBlock(self.0, mode, &block) } + } +} + +pub fn setup_control_flow_observers(mtm: MainThreadMarker, panic_info: Weak<PanicInfo>) { + let run_loop = RunLoop::main(mtm); + unsafe { + let mut context = CFRunLoopObserverContext { + info: Weak::into_raw(panic_info) as *mut _, + version: 0, + retain: None, + release: None, + copyDescription: None, + }; + run_loop.add_observer( + kCFRunLoopAfterWaiting, + CFIndex::MIN, + control_flow_begin_handler, + &mut context as *mut _, + ); + run_loop.add_observer( + kCFRunLoopExit | kCFRunLoopBeforeWaiting, + CFIndex::MAX, + control_flow_end_handler, + &mut context as *mut _, + ); + } +} + +#[derive(Debug)] +pub struct EventLoopWaker { + timer: CFRunLoopTimerRef, + + /// An arbitrary instant in the past, that will trigger an immediate wake + /// We save this as the `next_fire_date` for consistency so we can + /// easily check if the next_fire_date needs updating. + start_instant: Instant, + + /// This is what the `NextFireDate` has been set to. + /// `None` corresponds to `waker.stop()` and `start_instant` is used + /// for `waker.start()` + next_fire_date: Option<Instant>, +} + +impl Drop for EventLoopWaker { + fn drop(&mut self) { + unsafe { + CFRunLoopTimerInvalidate(self.timer); + CFRelease(self.timer as _); + } + } +} + +impl EventLoopWaker { + pub(crate) fn new() -> Self { + extern "C" fn wakeup_main_loop(_timer: CFRunLoopTimerRef, _info: *mut c_void) {} + unsafe { + // Create a timer with a 0.1µs interval (1ns does not work) to mimic polling. + // It is initially setup with a first fire time really far into the + // future, but that gets changed to fire immediately in did_finish_launching + let timer = CFRunLoopTimerCreate( + ptr::null_mut(), + f64::MAX, + 0.000_000_1, + 0, + 0, + wakeup_main_loop, + ptr::null_mut(), + ); + CFRunLoopAddTimer(CFRunLoopGetMain(), timer, kCFRunLoopCommonModes); + Self { timer, start_instant: Instant::now(), next_fire_date: None } + } + } + + pub fn stop(&mut self) { + if self.next_fire_date.is_some() { + self.next_fire_date = None; + unsafe { CFRunLoopTimerSetNextFireDate(self.timer, f64::MAX) } + } + } + + pub fn start(&mut self) { + if self.next_fire_date != Some(self.start_instant) { + self.next_fire_date = Some(self.start_instant); + unsafe { CFRunLoopTimerSetNextFireDate(self.timer, f64::MIN) } + } + } + + pub fn start_at(&mut self, instant: Option<Instant>) { + let now = Instant::now(); + match instant { + Some(instant) if now >= instant => { + self.start(); + }, + Some(instant) => { + if self.next_fire_date != Some(instant) { + self.next_fire_date = Some(instant); + unsafe { + let current = CFAbsoluteTimeGetCurrent(); + let duration = instant - now; + let fsecs = duration.subsec_nanos() as f64 / 1_000_000_000.0 + + duration.as_secs() as f64; + CFRunLoopTimerSetNextFireDate(self.timer, current + fsecs) + } + } + }, + None => { + self.stop(); + }, + } + } +} diff --git a/app/vendor/rune/vendor/winit/src/platform_impl/macos/util.rs b/app/vendor/rune/vendor/winit/src/platform_impl/macos/util.rs new file mode 100644 index 0000000..8110573 --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/platform_impl/macos/util.rs @@ -0,0 +1,27 @@ +use tracing::trace; + +macro_rules! trace_scope { + ($s:literal) => { + let _crate = $crate::platform_impl::platform::util::TraceGuard::new(module_path!(), $s); + }; +} + +pub(crate) struct TraceGuard { + module_path: &'static str, + called_from_fn: &'static str, +} + +impl TraceGuard { + #[inline] + pub(crate) fn new(module_path: &'static str, called_from_fn: &'static str) -> Self { + trace!(target = module_path, "Triggered `{}`", called_from_fn); + Self { module_path, called_from_fn } + } +} + +impl Drop for TraceGuard { + #[inline] + fn drop(&mut self) { + trace!(target = self.module_path, "Completed `{}`", self.called_from_fn); + } +} diff --git a/app/vendor/rune/vendor/winit/src/platform_impl/macos/view.rs b/app/vendor/rune/vendor/winit/src/platform_impl/macos/view.rs new file mode 100644 index 0000000..c83d635 --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/platform_impl/macos/view.rs @@ -0,0 +1,1205 @@ +#![allow(clippy::unnecessary_cast)] +use std::cell::{Cell, RefCell}; +use std::collections::{HashMap, VecDeque}; +use std::ptr; + +use objc2::rc::{Retained, WeakId}; +use objc2::runtime::{AnyObject, Sel}; +use objc2::{declare_class, msg_send_id, mutability, sel, ClassType, DeclaredClass}; +use objc2_app_kit::{ + NSApplication, NSCursor, NSEvent, NSEventPhase, NSResponder, NSTextInputClient, + NSTrackingRectTag, NSView, NSViewFrameDidChangeNotification, +}; +use objc2_foundation::{ + MainThreadMarker, NSArray, NSAttributedString, NSAttributedStringKey, NSCopying, + NSMutableAttributedString, NSNotFound, NSNotificationCenter, NSObject, NSObjectProtocol, + NSPoint, NSRange, NSRect, NSSize, NSString, NSUInteger, +}; + +use super::app_state::ApplicationDelegate; +use super::cursor::{default_cursor, invisible_cursor}; +use super::event::{ + code_to_key, code_to_location, create_key_event, event_mods, lalt_pressed, ralt_pressed, + scancode_to_physicalkey, KeyEventExtra, +}; +use super::window::WinitWindow; +use super::DEVICE_ID; +use crate::dpi::{LogicalPosition, LogicalSize}; +use crate::event::{ + DeviceEvent, ElementState, Ime, KeyEvent, Modifiers, MouseButton, MouseScrollDelta, TouchPhase, + WindowEvent, +}; +use crate::keyboard::{Key, KeyCode, KeyLocation, ModifiersState, NamedKey}; +use crate::platform::macos::OptionAsAlt; + +#[derive(Debug)] +struct CursorState { + visible: bool, + cursor: Retained<NSCursor>, +} + +impl Default for CursorState { + fn default() -> Self { + Self { visible: true, cursor: default_cursor() } + } +} + +#[derive(Debug, Eq, PartialEq, Clone, Copy, Default)] +enum ImeState { + #[default] + /// The IME events are disabled, so only `ReceivedCharacter` is being sent to the user. + Disabled, + + /// The ground state of enabled IME input. It means that both Preedit and regular keyboard + /// input could be start from it. + Ground, + + /// The IME is in preedit. + Preedit, + + /// The text was just committed, so the next input from the keyboard must be ignored. + Committed, +} + +bitflags::bitflags! { + #[derive(Debug, Clone, Copy, PartialEq)] + struct ModLocationMask: u8 { + const LEFT = 0b0001; + const RIGHT = 0b0010; + } +} +impl ModLocationMask { + fn from_location(loc: KeyLocation) -> ModLocationMask { + match loc { + KeyLocation::Left => ModLocationMask::LEFT, + KeyLocation::Right => ModLocationMask::RIGHT, + _ => unreachable!(), + } + } +} + +fn key_to_modifier(key: &Key) -> Option<ModifiersState> { + match key { + Key::Named(NamedKey::Alt) => Some(ModifiersState::ALT), + Key::Named(NamedKey::Control) => Some(ModifiersState::CONTROL), + Key::Named(NamedKey::Super) => Some(ModifiersState::SUPER), + Key::Named(NamedKey::Shift) => Some(ModifiersState::SHIFT), + _ => None, + } +} + +fn get_right_modifier_code(key: &Key) -> KeyCode { + match key { + Key::Named(NamedKey::Alt) => KeyCode::AltRight, + Key::Named(NamedKey::Control) => KeyCode::ControlRight, + Key::Named(NamedKey::Shift) => KeyCode::ShiftRight, + Key::Named(NamedKey::Super) => KeyCode::SuperRight, + _ => unreachable!(), + } +} + +fn get_left_modifier_code(key: &Key) -> KeyCode { + match key { + Key::Named(NamedKey::Alt) => KeyCode::AltLeft, + Key::Named(NamedKey::Control) => KeyCode::ControlLeft, + Key::Named(NamedKey::Shift) => KeyCode::ShiftLeft, + Key::Named(NamedKey::Super) => KeyCode::SuperLeft, + _ => unreachable!(), + } +} + +#[derive(Debug)] +pub struct ViewState { + /// Strong reference to the global application state. + app_delegate: Retained<ApplicationDelegate>, + + cursor_state: RefCell<CursorState>, + ime_position: Cell<NSPoint>, + ime_size: Cell<NSSize>, + modifiers: Cell<Modifiers>, + phys_modifiers: RefCell<HashMap<Key, ModLocationMask>>, + tracking_rect: Cell<Option<NSTrackingRectTag>>, + ime_state: Cell<ImeState>, + input_source: RefCell<String>, + + /// True iff the application wants IME events. + /// + /// Can be set using `set_ime_allowed` + ime_allowed: Cell<bool>, + + /// True if the current key event should be forwarded + /// to the application, even during IME + forward_key_to_app: Cell<bool>, + + marked_text: RefCell<Retained<NSMutableAttributedString>>, + accepts_first_mouse: bool, + + // Weak reference because the window keeps a strong reference to the view + _ns_window: WeakId<WinitWindow>, + + /// The state of the `Option` as `Alt`. + option_as_alt: Cell<OptionAsAlt>, +} + +declare_class!( + pub(super) struct WinitView; + + unsafe impl ClassType for WinitView { + #[inherits(NSResponder, NSObject)] + type Super = NSView; + type Mutability = mutability::MainThreadOnly; + const NAME: &'static str = "WinitView"; + } + + impl DeclaredClass for WinitView { + type Ivars = ViewState; + } + + unsafe impl WinitView { + #[method(isFlipped)] + fn is_flipped(&self) -> bool { + // `winit` uses the upper-left corner as the origin. + true + } + + #[method(viewDidMoveToWindow)] + fn view_did_move_to_window(&self) { + trace_scope!("viewDidMoveToWindow"); + if let Some(tracking_rect) = self.ivars().tracking_rect.take() { + self.removeTrackingRect(tracking_rect); + } + + let rect = self.frame(); + let tracking_rect = unsafe { + self.addTrackingRect_owner_userData_assumeInside(rect, self, ptr::null_mut(), false) + }; + assert_ne!(tracking_rect, 0, "failed adding tracking rect"); + self.ivars().tracking_rect.set(Some(tracking_rect)); + } + + #[method(frameDidChange:)] + fn frame_did_change(&self, _event: &NSEvent) { + trace_scope!("frameDidChange:"); + if let Some(tracking_rect) = self.ivars().tracking_rect.take() { + self.removeTrackingRect(tracking_rect); + } + + let rect = self.frame(); + let tracking_rect = unsafe { + self.addTrackingRect_owner_userData_assumeInside(rect, self, ptr::null_mut(), false) + }; + assert_ne!(tracking_rect, 0, "failed adding tracking rect"); + self.ivars().tracking_rect.set(Some(tracking_rect)); + + // Emit resize event here rather than from windowDidResize because: + // 1. When a new window is created as a tab, the frame size may change without a window resize occurring. + // 2. Even when a window resize does occur on a new tabbed window, it contains the wrong size (includes tab height). + let logical_size = LogicalSize::new(rect.size.width as f64, rect.size.height as f64); + let size = logical_size.to_physical::<u32>(self.scale_factor()); + self.queue_event(WindowEvent::Resized(size)); + } + + #[method(drawRect:)] + fn draw_rect(&self, _rect: NSRect) { + trace_scope!("drawRect:"); + + // It's a workaround for https://github.com/rust-windowing/winit/issues/2640, don't replace with `self.window_id()`. + if let Some(window) = self.ivars()._ns_window.load() { + self.ivars().app_delegate.handle_redraw(window.id()); + } + + // This is a direct subclass of NSView, no need to call superclass' drawRect: + } + + #[method(acceptsFirstResponder)] + fn accepts_first_responder(&self) -> bool { + trace_scope!("acceptsFirstResponder"); + true + } + + // This is necessary to prevent a beefy terminal error on MacBook Pros: + // IMKInputSession [0x7fc573576ff0 presentFunctionRowItemTextInputViewWithEndpoint:completionHandler:] : [self textInputContext]=0x7fc573558e10 *NO* NSRemoteViewController to client, NSError=Error Domain=NSCocoaErrorDomain Code=4099 "The connection from pid 0 was invalidated from this process." UserInfo={NSDebugDescription=The connection from pid 0 was invalidated from this process.}, com.apple.inputmethod.EmojiFunctionRowItem + // TODO: Add an API extension for using `NSTouchBar` + #[method_id(touchBar)] + fn touch_bar(&self) -> Option<Retained<NSObject>> { + trace_scope!("touchBar"); + None + } + + #[method(resetCursorRects)] + fn reset_cursor_rects(&self) { + trace_scope!("resetCursorRects"); + let bounds = self.bounds(); + let cursor_state = self.ivars().cursor_state.borrow(); + // We correctly invoke `addCursorRect` only from inside `resetCursorRects` + if cursor_state.visible { + self.addCursorRect_cursor(bounds, &cursor_state.cursor); + } else { + self.addCursorRect_cursor(bounds, &invisible_cursor()); + } + } + } + + unsafe impl NSTextInputClient for WinitView { + #[method(hasMarkedText)] + fn has_marked_text(&self) -> bool { + trace_scope!("hasMarkedText"); + self.ivars().marked_text.borrow().length() > 0 + } + + #[method(markedRange)] + fn marked_range(&self) -> NSRange { + trace_scope!("markedRange"); + let length = self.ivars().marked_text.borrow().length(); + if length > 0 { + NSRange::new(0, length) + } else { + // Documented to return `{NSNotFound, 0}` if there is no marked range. + NSRange::new(NSNotFound as NSUInteger, 0) + } + } + + #[method(selectedRange)] + fn selected_range(&self) -> NSRange { + trace_scope!("selectedRange"); + // Rune: the app's selection in the text it published, so the input method can + // reconvert it. + if self.ivars().marked_text.borrow().length() == 0 { + if let Some(range) = super::ime_text::TEXT.with_borrow(|t| t.as_ref().map(|(text, sel)| { + let a = super::ime_text::utf16_of(text, sel.start); + NSRange::new(a, super::ime_text::utf16_of(text, sel.end) - a) + })) { + return range; + } + } + // Documented to return `{NSNotFound, 0}` if there is no selection. + NSRange::new(NSNotFound as NSUInteger, 0) + } + + #[method(setMarkedText:selectedRange:replacementRange:)] + fn set_marked_text( + &self, + string: &NSObject, + selected_range: NSRange, + replacement_range: NSRange, + ) { + trace_scope!("setMarkedText:selectedRange:replacementRange:"); + + // Rune: a reconversion names the range of the published text the marked text replaces. + if replacement_range.location != NSNotFound as NSUInteger { + super::ime_text::TEXT.with_borrow(|t| if let Some((text, _)) = t { + let a = super::ime_text::byte_of(text, replacement_range.location); + let b = super::ime_text::byte_of(text, replacement_range.location + replacement_range.length); + super::ime_text::REPLACEMENT.with_borrow_mut(|r| *r = Some(a..b)); + }); + } + + // SAFETY: This method is guaranteed to get either a `NSString` or a `NSAttributedString`. + let (marked_text, string) = if string.is_kind_of::<NSAttributedString>() { + let string: *const NSObject = string; + let string: *const NSAttributedString = string.cast(); + let string = unsafe { &*string }; + // Rune: the clauses, by the input method's clause segments and underlines. + let clauses = marked_clauses(string); + super::ime_text::CLAUSES.with_borrow_mut(|c| *c = Some((string.string().to_string(), clauses))); + ( + NSMutableAttributedString::from_attributed_nsstring(string), + string.string(), + ) + } else { + let string: *const NSObject = string; + let string: *const NSString = string.cast(); + let string = unsafe { &*string }; + ( + NSMutableAttributedString::from_nsstring(string), + string.copy(), + ) + }; + + // Update marked text. + *self.ivars().marked_text.borrow_mut() = marked_text; + + // Notify IME is active if application still doesn't know it. + if self.ivars().ime_state.get() == ImeState::Disabled { + *self.ivars().input_source.borrow_mut() = self.current_input_source(); + self.queue_event(WindowEvent::Ime(Ime::Enabled)); + } + + if unsafe { self.hasMarkedText() } { + self.ivars().ime_state.set(ImeState::Preedit); + } else { + // In case the preedit was cleared, set IME into the Ground state. + self.ivars().ime_state.set(ImeState::Ground); + } + + let cursor_range = if string.is_empty() { + // An empty string basically means that there's no preedit, so indicate that by + // sending a `None` cursor range. + None + } else { + // Clamp to string length to avoid NSRangeException from out-of-bounds + // indices sent by macOS IME (e.g. native Pinyin, see + // https://github.com/alacritty/alacritty/issues/8791). + let len = string.length(); + let location = selected_range.location.min(len); + let end = selected_range.end().min(len); + // Convert the selected range from UTF-16 indices to UTF-8 indices. + let sub_string_a = unsafe { string.substringToIndex(location) }; + let sub_string_b = unsafe { string.substringToIndex(end) }; + let lowerbound_utf8 = sub_string_a.len(); + let upperbound_utf8 = sub_string_b.len(); + Some((lowerbound_utf8, upperbound_utf8)) + }; + + // Send WindowEvent for updating marked text + self.queue_event(WindowEvent::Ime(Ime::Preedit(string.to_string(), cursor_range))); + } + + #[method(unmarkText)] + fn unmark_text(&self) { + trace_scope!("unmarkText"); + *self.ivars().marked_text.borrow_mut() = NSMutableAttributedString::new(); + + let input_context = self.inputContext().expect("input context"); + input_context.discardMarkedText(); + + self.queue_event(WindowEvent::Ime(Ime::Preedit(String::new(), None))); + if self.is_ime_enabled() { + // Leave the Preedit self.ivars() + self.ivars().ime_state.set(ImeState::Ground); + } else { + tracing::warn!("Expected to have IME enabled when receiving unmarkText"); + } + } + + #[method_id(validAttributesForMarkedText)] + fn valid_attributes_for_marked_text(&self) -> Retained<NSArray<NSAttributedStringKey>> { + trace_scope!("validAttributesForMarkedText"); + // Rune: the underline and clause segments, which carry a composition's clauses. + NSArray::from_vec(vec![NSString::from_str("NSUnderline"), NSString::from_str("NSMarkedClauseSegment")]) + } + + #[method_id(attributedSubstringForProposedRange:actualRange:)] + fn attributed_substring_for_proposed_range( + &self, + range: NSRange, + actual_range: *mut NSRange, + ) -> Option<Retained<NSAttributedString>> { + trace_scope!("attributedSubstringForProposedRange:actualRange:"); + // Rune: the published text, for reconversion and Look Up. + super::ime_text::TEXT.with_borrow(|t| { + let (text, _) = t.as_ref()?; + let a = super::ime_text::byte_of(text, range.location); + let b = super::ime_text::byte_of(text, range.location.saturating_add(range.length)); + if a >= b { return None; } + if !actual_range.is_null() { + let ua = super::ime_text::utf16_of(text, a); + // SAFETY: AppKit's out-parameter, checked non-null. + unsafe { *actual_range = NSRange::new(ua, super::ime_text::utf16_of(text, b) - ua) }; + } + Some(NSAttributedString::from_nsstring(&NSString::from_str(&text[a..b]))) + }) + } + + #[method(characterIndexForPoint:)] + fn character_index_for_point(&self, _point: NSPoint) -> NSUInteger { + trace_scope!("characterIndexForPoint:"); + 0 + } + + #[method(firstRectForCharacterRange:actualRange:)] + fn first_rect_for_character_range( + &self, + _range: NSRange, + _actual_range: *mut NSRange, + ) -> NSRect { + trace_scope!("firstRectForCharacterRange:actualRange:"); + let rect = NSRect::new( + self.ivars().ime_position.get(), + self.ivars().ime_size.get() + ); + // Return value is expected to be in screen coordinates, so we need a conversion here + self.window() + .convertRectToScreen(self.convertRect_toView(rect, None)) + } + + #[method(insertText:replacementRange:)] + fn insert_text(&self, string: &NSObject, _replacement_range: NSRange) { + // TODO: Use _replacement_range, requires changing the event to report surrounding text. + trace_scope!("insertText:replacementRange:"); + + // SAFETY: This method is guaranteed to get either a `NSString` or a `NSAttributedString`. + let string = if string.is_kind_of::<NSAttributedString>() { + let string: *const NSObject = string; + let string: *const NSAttributedString = string.cast(); + unsafe { &*string }.string().to_string() + } else { + let string: *const NSObject = string; + let string: *const NSString = string.cast(); + unsafe { &*string }.to_string() + }; + + let is_control = string.chars().next().is_some_and(|c| c.is_control()); + + // Commit only if we have marked text. + if unsafe { self.hasMarkedText() } && self.is_ime_enabled() && !is_control { + self.queue_event(WindowEvent::Ime(Ime::Preedit(String::new(), None))); + self.queue_event(WindowEvent::Ime(Ime::Commit(string))); + self.ivars().ime_state.set(ImeState::Committed); + } + } + + // Basically, we're sent this message whenever a keyboard event that doesn't generate a "human + // readable" character happens, i.e. newlines, tabs, and Ctrl+C. + #[method(doCommandBySelector:)] + fn do_command_by_selector(&self, _command: Sel) { + trace_scope!("doCommandBySelector:"); + // We shouldn't forward any character from just committed text, since we'll end up sending + // it twice with some IMEs like Korean one. We'll also always send `Enter` in that case, + // which is not desired given it was used to confirm IME input. + if self.ivars().ime_state.get() == ImeState::Committed { + return; + } + + self.ivars().forward_key_to_app.set(true); + + if unsafe { self.hasMarkedText() } && self.ivars().ime_state.get() == ImeState::Preedit + { + // Leave preedit so that we also report the key-up for this key. + self.ivars().ime_state.set(ImeState::Ground); + } + } + } + + unsafe impl WinitView { + #[method(keyDown:)] + fn key_down(&self, event: &NSEvent) { + trace_scope!("keyDown:"); + { + let mut prev_input_source = self.ivars().input_source.borrow_mut(); + let current_input_source = self.current_input_source(); + if *prev_input_source != current_input_source && self.is_ime_enabled() { + *prev_input_source = current_input_source; + drop(prev_input_source); + self.ivars().ime_state.set(ImeState::Disabled); + self.queue_event(WindowEvent::Ime(Ime::Disabled)); + } + } + + // Get the characters from the event. + let old_ime_state = self.ivars().ime_state.get(); + self.ivars().forward_key_to_app.set(false); + let event = replace_event(event, self.option_as_alt()); + + // The `interpretKeyEvents` function might call + // `setMarkedText`, `insertText`, and `doCommandBySelector`. + // It's important that we call this before queuing the KeyboardInput, because + // we must send the `KeyboardInput` event during IME if it triggered + // `doCommandBySelector`. (doCommandBySelector means that the keyboard input + // is not handled by IME and should be handled by the application) + if self.ivars().ime_allowed.get() { + let events_for_nsview = NSArray::from_slice(&[&*event]); + unsafe { self.interpretKeyEvents(&events_for_nsview) }; + + // If the text was committed we must treat the next keyboard event as IME related. + if self.ivars().ime_state.get() == ImeState::Committed { + // Remove any marked text, so normal input can continue. + *self.ivars().marked_text.borrow_mut() = NSMutableAttributedString::new(); + } + } + + self.update_modifiers(&event, false); + + let had_ime_input = match self.ivars().ime_state.get() { + ImeState::Committed => { + // Allow normal input after the commit. + self.ivars().ime_state.set(ImeState::Ground); + true + } + ImeState::Preedit => true, + // `key_down` could result in preedit clear, so compare old and current state. + _ => old_ime_state != self.ivars().ime_state.get(), + }; + + if !had_ime_input || self.ivars().forward_key_to_app.get() { + let key_event = create_key_event(&event, true, unsafe { event.isARepeat() }); + self.queue_event(WindowEvent::KeyboardInput { + device_id: DEVICE_ID, + event: key_event, + is_synthetic: false, + }); + } + } + + #[method(keyUp:)] + fn key_up(&self, event: &NSEvent) { + trace_scope!("keyUp:"); + + let event = replace_event(event, self.option_as_alt()); + self.update_modifiers(&event, false); + + // We want to send keyboard input when we are currently in the ground state. + if matches!( + self.ivars().ime_state.get(), + ImeState::Ground | ImeState::Disabled + ) { + self.queue_event(WindowEvent::KeyboardInput { + device_id: DEVICE_ID, + event: create_key_event(&event, false, false), + is_synthetic: false, + }); + } + } + + #[method(flagsChanged:)] + fn flags_changed(&self, event: &NSEvent) { + trace_scope!("flagsChanged:"); + + self.update_modifiers(event, true); + } + + #[method(insertTab:)] + fn insert_tab(&self, _sender: Option<&AnyObject>) { + trace_scope!("insertTab:"); + let window = self.window(); + if let Some(first_responder) = window.firstResponder() { + if *first_responder == ***self { + window.selectNextKeyView(Some(self)) + } + } + } + + #[method(insertBackTab:)] + fn insert_back_tab(&self, _sender: Option<&AnyObject>) { + trace_scope!("insertBackTab:"); + let window = self.window(); + if let Some(first_responder) = window.firstResponder() { + if *first_responder == ***self { + window.selectPreviousKeyView(Some(self)) + } + } + } + + // Allows us to receive Cmd-. (the shortcut for closing a dialog) + // https://bugs.eclipse.org/bugs/show_bug.cgi?id=300620#c6 + #[method(cancelOperation:)] + fn cancel_operation(&self, _sender: Option<&AnyObject>) { + let mtm = MainThreadMarker::from(self); + trace_scope!("cancelOperation:"); + + let event = NSApplication::sharedApplication(mtm) + .currentEvent() + .expect("could not find current event"); + + self.update_modifiers(&event, false); + let event = create_key_event(&event, true, unsafe { event.isARepeat() }); + + self.queue_event(WindowEvent::KeyboardInput { + device_id: DEVICE_ID, + event, + is_synthetic: false, + }); + } + + // In the past (?), `mouseMoved:` events were not generated when the + // user hovered over a window from a separate window, and as such the + // application might not know the location of the mouse in the event. + // + // To fix this, we emit `mouse_motion` inside of mouse click, mouse + // scroll, magnify and other gesture event handlers, to ensure that + // the application's state of where the mouse click was located is up + // to date. + // + // See https://github.com/rust-windowing/winit/pull/1490 for history. + + #[method(mouseDown:)] + fn mouse_down(&self, event: &NSEvent) { + trace_scope!("mouseDown:"); + self.mouse_motion(event); + self.mouse_click(event, ElementState::Pressed); + } + + #[method(mouseUp:)] + fn mouse_up(&self, event: &NSEvent) { + trace_scope!("mouseUp:"); + self.mouse_motion(event); + self.mouse_click(event, ElementState::Released); + } + + #[method(rightMouseDown:)] + fn right_mouse_down(&self, event: &NSEvent) { + trace_scope!("rightMouseDown:"); + self.mouse_motion(event); + self.mouse_click(event, ElementState::Pressed); + } + + #[method(rightMouseUp:)] + fn right_mouse_up(&self, event: &NSEvent) { + trace_scope!("rightMouseUp:"); + self.mouse_motion(event); + self.mouse_click(event, ElementState::Released); + } + + #[method(otherMouseDown:)] + fn other_mouse_down(&self, event: &NSEvent) { + trace_scope!("otherMouseDown:"); + self.mouse_motion(event); + self.mouse_click(event, ElementState::Pressed); + } + + #[method(otherMouseUp:)] + fn other_mouse_up(&self, event: &NSEvent) { + trace_scope!("otherMouseUp:"); + self.mouse_motion(event); + self.mouse_click(event, ElementState::Released); + } + + // No tracing on these because that would be overly verbose + + #[method(mouseMoved:)] + fn mouse_moved(&self, event: &NSEvent) { + self.mouse_motion(event); + } + + #[method(mouseDragged:)] + fn mouse_dragged(&self, event: &NSEvent) { + self.mouse_motion(event); + } + + #[method(rightMouseDragged:)] + fn right_mouse_dragged(&self, event: &NSEvent) { + self.mouse_motion(event); + } + + #[method(otherMouseDragged:)] + fn other_mouse_dragged(&self, event: &NSEvent) { + self.mouse_motion(event); + } + + #[method(mouseEntered:)] + fn mouse_entered(&self, _event: &NSEvent) { + trace_scope!("mouseEntered:"); + self.queue_event(WindowEvent::CursorEntered { + device_id: DEVICE_ID, + }); + } + + #[method(mouseExited:)] + fn mouse_exited(&self, _event: &NSEvent) { + trace_scope!("mouseExited:"); + + self.queue_event(WindowEvent::CursorLeft { + device_id: DEVICE_ID, + }); + } + + #[method(scrollWheel:)] + fn scroll_wheel(&self, event: &NSEvent) { + trace_scope!("scrollWheel:"); + + self.mouse_motion(event); + + let delta = { + let (x, y) = unsafe { (event.scrollingDeltaX(), event.scrollingDeltaY()) }; + if unsafe { event.hasPreciseScrollingDeltas() } { + let delta = LogicalPosition::new(x, y).to_physical(self.scale_factor()); + MouseScrollDelta::PixelDelta(delta) + } else { + MouseScrollDelta::LineDelta(x as f32, y as f32) + } + }; + + // The "momentum phase," if any, has higher priority than touch phase (the two should + // be mutually exclusive anyhow, which is why the API is rather incoherent). If no momentum + // phase is recorded (or rather, the started/ended cases of the momentum phase) then we + // report the touch phase. + #[allow(non_upper_case_globals)] + let phase = match unsafe { event.momentumPhase() } { + NSEventPhase::MayBegin | NSEventPhase::Began => TouchPhase::Started, + NSEventPhase::Ended | NSEventPhase::Cancelled => TouchPhase::Ended, + _ => match unsafe { event.phase() } { + NSEventPhase::MayBegin | NSEventPhase::Began => TouchPhase::Started, + NSEventPhase::Ended | NSEventPhase::Cancelled => TouchPhase::Ended, + _ => TouchPhase::Moved, + }, + }; + + self.update_modifiers(event, false); + + self.ivars().app_delegate.maybe_queue_device_event(DeviceEvent::MouseWheel { delta }); + self.queue_event(WindowEvent::MouseWheel { + device_id: DEVICE_ID, + delta, + phase, + }); + } + + #[method(magnifyWithEvent:)] + fn magnify_with_event(&self, event: &NSEvent) { + trace_scope!("magnifyWithEvent:"); + + self.mouse_motion(event); + + #[allow(non_upper_case_globals)] + let phase = match unsafe { event.phase() } { + NSEventPhase::Began => TouchPhase::Started, + NSEventPhase::Changed => TouchPhase::Moved, + NSEventPhase::Cancelled => TouchPhase::Cancelled, + NSEventPhase::Ended => TouchPhase::Ended, + _ => return, + }; + + self.queue_event(WindowEvent::PinchGesture { + device_id: DEVICE_ID, + delta: unsafe { event.magnification() }, + phase, + }); + } + + #[method(smartMagnifyWithEvent:)] + fn smart_magnify_with_event(&self, event: &NSEvent) { + trace_scope!("smartMagnifyWithEvent:"); + + self.mouse_motion(event); + + self.queue_event(WindowEvent::DoubleTapGesture { + device_id: DEVICE_ID, + }); + } + + #[method(rotateWithEvent:)] + fn rotate_with_event(&self, event: &NSEvent) { + trace_scope!("rotateWithEvent:"); + + self.mouse_motion(event); + + #[allow(non_upper_case_globals)] + let phase = match unsafe { event.phase() } { + NSEventPhase::Began => TouchPhase::Started, + NSEventPhase::Changed => TouchPhase::Moved, + NSEventPhase::Cancelled => TouchPhase::Cancelled, + NSEventPhase::Ended => TouchPhase::Ended, + _ => return, + }; + + self.queue_event(WindowEvent::RotationGesture { + device_id: DEVICE_ID, + delta: unsafe { event.rotation() }, + phase, + }); + } + + #[method(pressureChangeWithEvent:)] + fn pressure_change_with_event(&self, event: &NSEvent) { + trace_scope!("pressureChangeWithEvent:"); + + self.queue_event(WindowEvent::TouchpadPressure { + device_id: DEVICE_ID, + pressure: unsafe { event.pressure() }, + stage: unsafe { event.stage() } as i64, + }); + } + + // Allows us to receive Ctrl-Tab and Ctrl-Esc. + // Note that this *doesn't* help with any missing Cmd inputs. + // https://github.com/chromium/chromium/blob/a86a8a6bcfa438fa3ac2eba6f02b3ad1f8e0756f/ui/views/cocoa/bridged_content_view.mm#L816 + #[method(_wantsKeyDownForEvent:)] + fn wants_key_down_for_event(&self, _event: &NSEvent) -> bool { + trace_scope!("_wantsKeyDownForEvent:"); + true + } + + #[method(acceptsFirstMouse:)] + fn accepts_first_mouse(&self, _event: &NSEvent) -> bool { + trace_scope!("acceptsFirstMouse:"); + self.ivars().accepts_first_mouse + } + } +); + +impl WinitView { + pub(super) fn new( + app_delegate: &ApplicationDelegate, + window: &WinitWindow, + accepts_first_mouse: bool, + option_as_alt: OptionAsAlt, + ) -> Retained<Self> { + let mtm = MainThreadMarker::from(window); + let this = mtm.alloc().set_ivars(ViewState { + app_delegate: app_delegate.retain(), + cursor_state: Default::default(), + ime_position: Default::default(), + ime_size: Default::default(), + modifiers: Default::default(), + phys_modifiers: Default::default(), + tracking_rect: Default::default(), + ime_state: Default::default(), + input_source: Default::default(), + ime_allowed: Default::default(), + forward_key_to_app: Default::default(), + marked_text: Default::default(), + accepts_first_mouse, + _ns_window: WeakId::new(&window.retain()), + option_as_alt: Cell::new(option_as_alt), + }); + let this: Retained<Self> = unsafe { msg_send_id![super(this), init] }; + + this.setPostsFrameChangedNotifications(true); + let notification_center = unsafe { NSNotificationCenter::defaultCenter() }; + unsafe { + notification_center.addObserver_selector_name_object( + &this, + sel!(frameDidChange:), + Some(NSViewFrameDidChangeNotification), + Some(&this), + ) + } + + *this.ivars().input_source.borrow_mut() = this.current_input_source(); + + this + } + + fn window(&self) -> Retained<WinitWindow> { + // TODO: Simply use `window` property on `NSView`. + // That only returns a window _after_ the view has been attached though! + // (which is incompatible with `frameDidChange:`) + // + // unsafe { msg_send_id![self, window] } + self.ivars()._ns_window.load().expect("view to have a window") + } + + fn queue_event(&self, event: WindowEvent) { + self.ivars().app_delegate.maybe_queue_window_event(self.window().id(), event); + } + + fn scale_factor(&self) -> f64 { + self.window().backingScaleFactor() as f64 + } + + fn is_ime_enabled(&self) -> bool { + !matches!(self.ivars().ime_state.get(), ImeState::Disabled) + } + + fn current_input_source(&self) -> String { + self.inputContext() + .expect("input context") + .selectedKeyboardInputSource() + .map(|input_source| input_source.to_string()) + .unwrap_or_default() + } + + pub(super) fn cursor_icon(&self) -> Retained<NSCursor> { + self.ivars().cursor_state.borrow().cursor.clone() + } + + pub(super) fn set_cursor_icon(&self, icon: Retained<NSCursor>) { + let mut cursor_state = self.ivars().cursor_state.borrow_mut(); + cursor_state.cursor = icon; + } + + /// Set whether the cursor should be visible or not. + /// + /// Returns whether the state changed. + pub(super) fn set_cursor_visible(&self, visible: bool) -> bool { + let mut cursor_state = self.ivars().cursor_state.borrow_mut(); + if visible != cursor_state.visible { + cursor_state.visible = visible; + true + } else { + false + } + } + + pub(super) fn set_ime_allowed(&self, ime_allowed: bool) { + if self.ivars().ime_allowed.get() == ime_allowed { + return; + } + self.ivars().ime_allowed.set(ime_allowed); + if self.ivars().ime_allowed.get() { + return; + } + + // Clear markedText + *self.ivars().marked_text.borrow_mut() = NSMutableAttributedString::new(); + + if self.ivars().ime_state.get() != ImeState::Disabled { + self.ivars().ime_state.set(ImeState::Disabled); + self.queue_event(WindowEvent::Ime(Ime::Disabled)); + } + } + + pub(super) fn set_ime_cursor_area(&self, position: NSPoint, size: NSSize) { + self.ivars().ime_position.set(position); + self.ivars().ime_size.set(size); + let input_context = self.inputContext().expect("input context"); + input_context.invalidateCharacterCoordinates(); + } + + /// Reset modifiers and emit a synthetic ModifiersChanged event if deemed necessary. + pub(super) fn reset_modifiers(&self) { + if !self.ivars().modifiers.get().state().is_empty() { + self.ivars().modifiers.set(Modifiers::default()); + self.queue_event(WindowEvent::ModifiersChanged(self.ivars().modifiers.get())); + } + } + + pub(super) fn set_option_as_alt(&self, value: OptionAsAlt) { + self.ivars().option_as_alt.set(value) + } + + pub(super) fn option_as_alt(&self) -> OptionAsAlt { + self.ivars().option_as_alt.get() + } + + /// Update modifiers if `event` has something different + fn update_modifiers(&self, ns_event: &NSEvent, is_flags_changed_event: bool) { + use ElementState::{Pressed, Released}; + + let current_modifiers = event_mods(ns_event); + let prev_modifiers = self.ivars().modifiers.get(); + self.ivars().modifiers.set(current_modifiers); + + // This function was called form the flagsChanged event, which is triggered + // when the user presses/releases a modifier even if the same kind of modifier + // has already been pressed. + // + // When flags changed event has key code of zero it means that event doesn't carry any key + // event, thus we can't generate regular presses based on that. The `ModifiersChanged` + // later will work though, since the flags are attached to the event and contain valid + // information. + 'send_event: { + if is_flags_changed_event && unsafe { ns_event.keyCode() } != 0 { + let scancode = unsafe { ns_event.keyCode() }; + let physical_key = scancode_to_physicalkey(scancode as u32); + + let logical_key = code_to_key(physical_key, scancode); + // Ignore processing of unknown modifiers because we can't determine whether + // it was pressed or release reliably. + // + // Furthermore, sometimes normal keys are reported inside flagsChanged:, such as + // when holding Caps Lock while pressing another key, see: + // https://github.com/alacritty/alacritty/issues/8268 + let Some(event_modifier) = key_to_modifier(&logical_key) else { + break 'send_event; + }; + + let mut event = KeyEvent { + location: code_to_location(physical_key), + logical_key: logical_key.clone(), + physical_key, + repeat: false, + // We'll correct this later. + state: Pressed, + text: None, + platform_specific: KeyEventExtra { + text_with_all_modifiers: None, + key_without_modifiers: logical_key.clone(), + }, + }; + + let location_mask = ModLocationMask::from_location(event.location); + + let mut phys_mod_state = self.ivars().phys_modifiers.borrow_mut(); + let phys_mod = + phys_mod_state.entry(logical_key).or_insert(ModLocationMask::empty()); + + let is_active = current_modifiers.state().contains(event_modifier); + let mut events = VecDeque::with_capacity(2); + + // There is no API for getting whether the button was pressed or released + // during this event. For this reason we have to do a bit of magic below + // to come up with a good guess whether this key was pressed or released. + // (This is not trivial because there are multiple buttons that may affect + // the same modifier) + if !is_active { + event.state = Released; + if phys_mod.contains(ModLocationMask::LEFT) { + let mut event = event.clone(); + event.location = KeyLocation::Left; + event.physical_key = get_left_modifier_code(&event.logical_key).into(); + events.push_back(WindowEvent::KeyboardInput { + device_id: DEVICE_ID, + event, + is_synthetic: false, + }); + } + if phys_mod.contains(ModLocationMask::RIGHT) { + event.location = KeyLocation::Right; + event.physical_key = get_right_modifier_code(&event.logical_key).into(); + events.push_back(WindowEvent::KeyboardInput { + device_id: DEVICE_ID, + event, + is_synthetic: false, + }); + } + *phys_mod = ModLocationMask::empty(); + } else { + if *phys_mod == location_mask { + // Here we hit a contradiction: + // The modifier state was "changed" to active, + // yet the only pressed modifier key was the one that we + // just got a change event for. + // This seemingly means that the only pressed modifier is now released, + // but at the same time the modifier became active. + // + // But this scenario is possible if we released modifiers + // while the application was not in focus. (Because we don't + // get informed of modifier key events while the application + // is not focused) + + // In this case we prioritize the information + // about the current modifier state which means + // that the button was pressed. + event.state = Pressed; + } else { + phys_mod.toggle(location_mask); + let is_pressed = phys_mod.contains(location_mask); + event.state = if is_pressed { Pressed } else { Released }; + } + + events.push_back(WindowEvent::KeyboardInput { + device_id: DEVICE_ID, + event, + is_synthetic: false, + }); + } + + drop(phys_mod_state); + + for event in events { + self.queue_event(event); + } + } + } + + if prev_modifiers == current_modifiers { + return; + } + + self.queue_event(WindowEvent::ModifiersChanged(self.ivars().modifiers.get())); + } + + fn mouse_click(&self, event: &NSEvent, button_state: ElementState) { + let button = mouse_button(event); + + self.update_modifiers(event, false); + + self.queue_event(WindowEvent::MouseInput { + device_id: DEVICE_ID, + state: button_state, + button, + }); + } + + fn mouse_motion(&self, event: &NSEvent) { + let window_point = unsafe { event.locationInWindow() }; + let view_point = self.convertPoint_fromView(window_point, None); + let frame = self.frame(); + + if view_point.x.is_sign_negative() + || view_point.y.is_sign_negative() + || view_point.x > frame.size.width + || view_point.y > frame.size.height + { + let mouse_buttons_down = unsafe { NSEvent::pressedMouseButtons() }; + if mouse_buttons_down == 0 { + // Point is outside of the client area (view) and no buttons are pressed + return; + } + } + + let view_point = LogicalPosition::new(view_point.x, view_point.y); + + self.update_modifiers(event, false); + + self.queue_event(WindowEvent::CursorMoved { + device_id: DEVICE_ID, + position: view_point.to_physical(self.scale_factor()), + }); + } +} + +/// Get the mouse button from the NSEvent. +fn mouse_button(event: &NSEvent) -> MouseButton { + // The buttonNumber property only makes sense for the mouse events: + // NSLeftMouse.../NSRightMouse.../NSOtherMouse... + // For the other events, it's always set to 0. + // MacOS only defines the left, right and middle buttons, 3..=31 are left as generic buttons, + // but 3 and 4 are very commonly used as Back and Forward by hardware vendors and applications. + match unsafe { event.buttonNumber() } { + 0 => MouseButton::Left, + 1 => MouseButton::Right, + 2 => MouseButton::Middle, + 3 => MouseButton::Back, + 4 => MouseButton::Forward, + n => MouseButton::Other(n as u16), + } +} + +// NOTE: to get option as alt working we need to rewrite events +// we're getting from the operating system, which makes it +// impossible to provide such events as extra in `KeyEvent`. +fn replace_event(event: &NSEvent, option_as_alt: OptionAsAlt) -> Retained<NSEvent> { + let ev_mods = event_mods(event).state; + let ignore_alt_characters = match option_as_alt { + OptionAsAlt::OnlyLeft if lalt_pressed(event) => true, + OptionAsAlt::OnlyRight if ralt_pressed(event) => true, + OptionAsAlt::Both if ev_mods.alt_key() => true, + _ => false, + } && !ev_mods.control_key() + && !ev_mods.super_key(); + + if ignore_alt_characters { + let ns_chars = unsafe { + event.charactersIgnoringModifiers().expect("expected characters to be non-null") + }; + + unsafe { + NSEvent::keyEventWithType_location_modifierFlags_timestamp_windowNumber_context_characters_charactersIgnoringModifiers_isARepeat_keyCode( + event.r#type(), + event.locationInWindow(), + event.modifierFlags(), + event.timestamp(), + event.windowNumber(), + None, + &ns_chars, + &ns_chars, + event.isARepeat(), + event.keyCode(), + ) + .unwrap() + } + } else { + event.copy() + } +} + +/// Rune: a marked text's clauses, byte ranges with whether each is the one being converted: one +/// per run of `NSMarkedClauseSegment` (or of the underline when an input method sets no +/// segments), the target the one with a thick underline. +fn marked_clauses(string: &NSAttributedString) -> Vec<(std::ops::Range<usize>, bool)> { + let text = string.string(); + let utf8 = text.to_string(); + let len = text.length(); + let (segment, underline) = (NSString::from_str("NSMarkedClauseSegment"), NSString::from_str("NSUnderline")); + let attribute = |key: &NSString, at: NSUInteger, range: &mut NSRange| -> Option<Retained<AnyObject>> { + // SAFETY: `at` is inside the string; `range` is a valid out-parameter. + unsafe { msg_send_id![string, attribute: key, atIndex: at, effectiveRange: range as *mut NSRange] } + }; + let mut probe = NSRange::new(0, 0); + let by = if len > 0 && attribute(&segment, 0, &mut probe).is_some() { &segment } else { &underline }; + let mut out = Vec::new(); + let mut at = 0; + while at < len { + let mut run = NSRange::new(0, 0); + let _ = attribute(by, at, &mut run); + let end = (run.location + run.length).clamp(at + 1, len); + let mut ignored = NSRange::new(0, 0); + // NSUnderlineStyleThick is 2; an input method marks the clause being converted with it. + let style: isize = attribute(&underline, at, &mut ignored).map_or(0, |v| unsafe { objc2::msg_send![&*v, integerValue] }); + out.push((super::ime_text::byte_of(&utf8, at)..super::ime_text::byte_of(&utf8, end), style & 0xF >= 2)); + at = end; + } + out +} diff --git a/app/vendor/rune/vendor/winit/src/platform_impl/macos/window.rs b/app/vendor/rune/vendor/winit/src/platform_impl/macos/window.rs new file mode 100644 index 0000000..04da8b2 --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/platform_impl/macos/window.rs @@ -0,0 +1,126 @@ +#![allow(clippy::unnecessary_cast)] + +use objc2::rc::{autoreleasepool, Retained}; +use objc2::{declare_class, mutability, ClassType, DeclaredClass}; +use objc2_app_kit::{NSResponder, NSWindow}; +use objc2_foundation::{MainThreadBound, MainThreadMarker, NSObject}; + +use super::event_loop::ActiveEventLoop; +use super::window_delegate::WindowDelegate; +use crate::error::OsError as RootOsError; +use crate::window::WindowAttributes; + +pub(crate) struct Window { + window: MainThreadBound<Retained<WinitWindow>>, + /// The window only keeps a weak reference to this, so we must keep it around here. + delegate: MainThreadBound<Retained<WindowDelegate>>, +} + +impl Drop for Window { + fn drop(&mut self) { + self.window.get_on_main(|window| autoreleasepool(|_| window.close())) + } +} + +impl Window { + pub(crate) fn new( + window_target: &ActiveEventLoop, + attributes: WindowAttributes, + ) -> Result<Self, RootOsError> { + let mtm = window_target.mtm; + let delegate = autoreleasepool(|_| { + WindowDelegate::new(window_target.app_delegate(), attributes, mtm) + })?; + Ok(Window { + window: MainThreadBound::new(delegate.window().retain(), mtm), + delegate: MainThreadBound::new(delegate, mtm), + }) + } + + pub(crate) fn maybe_queue_on_main(&self, f: impl FnOnce(&WindowDelegate) + Send + 'static) { + // For now, don't actually do queuing, since it may be less predictable + self.maybe_wait_on_main(f) + } + + pub(crate) fn maybe_wait_on_main<R: Send>( + &self, + f: impl FnOnce(&WindowDelegate) -> R + Send, + ) -> R { + self.delegate.get_on_main(|delegate| f(delegate)) + } + + #[cfg(feature = "rwh_06")] + #[inline] + pub(crate) fn raw_window_handle_rwh_06( + &self, + ) -> Result<rwh_06::RawWindowHandle, rwh_06::HandleError> { + if let Some(mtm) = MainThreadMarker::new() { + Ok(self.delegate.get(mtm).raw_window_handle_rwh_06()) + } else { + Err(rwh_06::HandleError::Unavailable) + } + } + + #[cfg(feature = "rwh_06")] + #[inline] + pub(crate) fn raw_display_handle_rwh_06( + &self, + ) -> Result<rwh_06::RawDisplayHandle, rwh_06::HandleError> { + Ok(rwh_06::RawDisplayHandle::AppKit(rwh_06::AppKitDisplayHandle::new())) + } +} + +#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub struct WindowId(pub usize); + +impl WindowId { + pub const fn dummy() -> Self { + Self(0) + } +} + +impl From<WindowId> for u64 { + fn from(window_id: WindowId) -> Self { + window_id.0 as u64 + } +} + +impl From<u64> for WindowId { + fn from(raw_id: u64) -> Self { + Self(raw_id as usize) + } +} + +declare_class!( + #[derive(Debug)] + pub struct WinitWindow; + + unsafe impl ClassType for WinitWindow { + #[inherits(NSResponder, NSObject)] + type Super = NSWindow; + type Mutability = mutability::MainThreadOnly; + const NAME: &'static str = "WinitWindow"; + } + + impl DeclaredClass for WinitWindow {} + + unsafe impl WinitWindow { + #[method(canBecomeMainWindow)] + fn can_become_main_window(&self) -> bool { + trace_scope!("canBecomeMainWindow"); + true + } + + #[method(canBecomeKeyWindow)] + fn can_become_key_window(&self) -> bool { + trace_scope!("canBecomeKeyWindow"); + true + } + } +); + +impl WinitWindow { + pub(super) fn id(&self) -> WindowId { + WindowId(self as *const Self as usize) + } +} diff --git a/app/vendor/rune/vendor/winit/src/platform_impl/macos/window_delegate.rs b/app/vendor/rune/vendor/winit/src/platform_impl/macos/window_delegate.rs new file mode 100644 index 0000000..e293505 --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/platform_impl/macos/window_delegate.rs @@ -0,0 +1,1910 @@ +#![allow(clippy::unnecessary_cast)] +use std::cell::{Cell, RefCell}; +use std::collections::VecDeque; +use std::ffi::c_void; +use std::ptr; +use std::sync::{Arc, Mutex}; + +use core_graphics::display::{CGDisplay, CGPoint}; +use monitor::VideoModeHandle; +use objc2::rc::{autoreleasepool, Retained}; +use objc2::runtime::{AnyObject, ProtocolObject}; +use objc2::{declare_class, msg_send_id, mutability, sel, ClassType, DeclaredClass}; +use objc2_app_kit::{ + NSAppKitVersionNumber, NSAppKitVersionNumber10_12, NSAppearance, NSAppearanceCustomization, + NSAppearanceNameAqua, NSApplication, NSApplicationPresentationOptions, NSBackingStoreType, + NSColor, NSDraggingDestination, NSFilenamesPboardType, NSPasteboard, + NSRequestUserAttentionType, NSScreen, NSView, NSWindowButton, NSWindowDelegate, + NSWindowFullScreenButton, NSWindowLevel, NSWindowOcclusionState, NSWindowOrderingMode, + NSWindowSharingType, NSWindowStyleMask, NSWindowTabbingMode, NSWindowTitleVisibility, +}; +use objc2_foundation::{ + ns_string, CGFloat, MainThreadMarker, NSArray, NSCopying, NSDictionary, NSKeyValueChangeKey, + NSKeyValueChangeNewKey, NSKeyValueChangeOldKey, NSKeyValueObservingOptions, NSObject, + NSObjectNSDelayedPerforming, NSObjectNSKeyValueObserverRegistration, NSObjectProtocol, NSPoint, + NSRect, NSSize, NSString, +}; +use tracing::{trace, warn}; + +use super::app_state::ApplicationDelegate; +use super::cursor::cursor_from_icon; +use super::monitor::{self, flip_window_screen_coordinates, get_display_id}; +use super::observer::RunLoop; +use super::view::WinitView; +use super::window::WinitWindow; +use super::{ffi, Fullscreen, MonitorHandle, OsError, WindowId}; +use crate::dpi::{LogicalPosition, LogicalSize, PhysicalPosition, PhysicalSize, Position, Size}; +use crate::error::{ExternalError, NotSupportedError, OsError as RootOsError}; +use crate::event::{InnerSizeWriter, WindowEvent}; +use crate::platform::macos::{OptionAsAlt, WindowExtMacOS}; +use crate::window::{ + Cursor, CursorGrabMode, Icon, ImePurpose, ResizeDirection, Theme, UserAttentionType, + WindowAttributes, WindowButtons, WindowLevel, +}; + +#[derive(Clone, Debug)] +pub struct PlatformSpecificWindowAttributes { + pub movable_by_window_background: bool, + pub titlebar_transparent: bool, + pub title_hidden: bool, + pub titlebar_hidden: bool, + pub titlebar_buttons_hidden: bool, + pub fullsize_content_view: bool, + pub disallow_hidpi: bool, + pub has_shadow: bool, + pub accepts_first_mouse: bool, + pub tabbing_identifier: Option<String>, + pub option_as_alt: OptionAsAlt, + pub borderless_game: bool, +} + +impl Default for PlatformSpecificWindowAttributes { + #[inline] + fn default() -> Self { + Self { + movable_by_window_background: false, + titlebar_transparent: false, + title_hidden: false, + titlebar_hidden: false, + titlebar_buttons_hidden: false, + fullsize_content_view: false, + disallow_hidpi: false, + has_shadow: true, + accepts_first_mouse: true, + tabbing_identifier: None, + option_as_alt: Default::default(), + borderless_game: false, + } + } +} + +#[derive(Debug)] +pub(crate) struct State { + /// Strong reference to the global application state. + app_delegate: Retained<ApplicationDelegate>, + + window: Retained<WinitWindow>, + + // During `windowDidResize`, we use this to only send Moved if the position changed. + // + // This is expressed in desktop coordinates, and flipped to match Winit's coordinate system. + previous_position: Cell<NSPoint>, + + // Used to prevent redundant events. + previous_scale_factor: Cell<f64>, + + /// The current resize increments for the window content. + resize_increments: Cell<NSSize>, + /// Whether the window is showing decorations. + decorations: Cell<bool>, + resizable: Cell<bool>, + maximized: Cell<bool>, + + /// Presentation options saved before entering `set_simple_fullscreen`, and + /// restored upon exiting it. Also used when transitioning from Borderless to + /// Exclusive fullscreen in `set_fullscreen` because we need to disable the menu + /// bar in exclusive fullscreen but want to restore the original options when + /// transitioning back to borderless fullscreen. + save_presentation_opts: Cell<Option<NSApplicationPresentationOptions>>, + // This is set when WindowAttributes::with_fullscreen was set, + // see comments of `window_did_fail_to_enter_fullscreen` + initial_fullscreen: Cell<bool>, + /// This field tracks the current fullscreen state of the window + /// (as seen by `WindowDelegate`). + fullscreen: RefCell<Option<Fullscreen>>, + // If it is attempted to toggle fullscreen when in_fullscreen_transition is true, + // Set target_fullscreen and do after fullscreen transition is end. + target_fullscreen: RefCell<Option<Option<Fullscreen>>>, + // This is true between windowWillEnterFullScreen and windowDidEnterFullScreen + // or windowWillExitFullScreen and windowDidExitFullScreen. + // We must not toggle fullscreen when this is true. + in_fullscreen_transition: Cell<bool>, + standard_frame: Cell<Option<NSRect>>, + is_simple_fullscreen: Cell<bool>, + saved_style: Cell<Option<NSWindowStyleMask>>, + is_borderless_game: Cell<bool>, +} + +declare_class!( + pub(crate) struct WindowDelegate; + + unsafe impl ClassType for WindowDelegate { + type Super = NSObject; + type Mutability = mutability::MainThreadOnly; + const NAME: &'static str = "WinitWindowDelegate"; + } + + impl DeclaredClass for WindowDelegate { + type Ivars = State; + } + + unsafe impl NSObjectProtocol for WindowDelegate {} + + unsafe impl NSWindowDelegate for WindowDelegate { + #[method(windowShouldClose:)] + fn window_should_close(&self, _: Option<&AnyObject>) -> bool { + trace_scope!("windowShouldClose:"); + self.queue_event(WindowEvent::CloseRequested); + false + } + + #[method(windowWillClose:)] + fn window_will_close(&self, _: Option<&AnyObject>) { + trace_scope!("windowWillClose:"); + // `setDelegate:` retains the previous value and then autoreleases it + autoreleasepool(|_| { + // Since El Capitan, we need to be careful that delegate methods can't + // be called after the window closes. + self.window().setDelegate(None); + }); + self.queue_event(WindowEvent::Destroyed); + } + + #[method(windowDidResize:)] + fn window_did_resize(&self, _: Option<&AnyObject>) { + trace_scope!("windowDidResize:"); + // NOTE: WindowEvent::Resized is reported in frameDidChange. + self.emit_move_event(); + } + + #[method(windowWillStartLiveResize:)] + fn window_will_start_live_resize(&self, _: Option<&AnyObject>) { + trace_scope!("windowWillStartLiveResize:"); + + let increments = self.ivars().resize_increments.get(); + self.set_resize_increments_inner(increments); + } + + #[method(windowDidEndLiveResize:)] + fn window_did_end_live_resize(&self, _: Option<&AnyObject>) { + trace_scope!("windowDidEndLiveResize:"); + self.set_resize_increments_inner(NSSize::new(1., 1.)); + } + + // This won't be triggered if the move was part of a resize. + #[method(windowDidMove:)] + fn window_did_move(&self, _: Option<&AnyObject>) { + trace_scope!("windowDidMove:"); + self.emit_move_event(); + } + + #[method(windowDidChangeBackingProperties:)] + fn window_did_change_backing_properties(&self, _: Option<&AnyObject>) { + trace_scope!("windowDidChangeBackingProperties:"); + let scale_factor = self.scale_factor(); + if scale_factor == self.ivars().previous_scale_factor.get() { + return; + }; + self.ivars().previous_scale_factor.set(scale_factor); + + let mtm = MainThreadMarker::from(self); + let this = self.retain(); + RunLoop::main(mtm).queue_closure(move || { + this.handle_scale_factor_changed(scale_factor); + }); + } + + #[method(windowDidBecomeKey:)] + fn window_did_become_key(&self, _: Option<&AnyObject>) { + trace_scope!("windowDidBecomeKey:"); + // TODO: center the cursor if the window had mouse grab when it + // lost focus + self.queue_event(WindowEvent::Focused(true)); + } + + #[method(windowDidResignKey:)] + fn window_did_resign_key(&self, _: Option<&AnyObject>) { + trace_scope!("windowDidResignKey:"); + // It happens rather often, e.g. when the user is Cmd+Tabbing, that the + // NSWindowDelegate will receive a didResignKey event despite no event + // being received when the modifiers are released. This is because + // flagsChanged events are received by the NSView instead of the + // NSWindowDelegate, and as a result a tracked modifiers state can quite + // easily fall out of synchrony with reality. This requires us to emit + // a synthetic ModifiersChanged event when we lose focus. + self.view().reset_modifiers(); + + self.queue_event(WindowEvent::Focused(false)); + } + + /// Invoked when before enter fullscreen + #[method(windowWillEnterFullScreen:)] + fn window_will_enter_fullscreen(&self, _: Option<&AnyObject>) { + trace_scope!("windowWillEnterFullScreen:"); + + self.ivars().maximized.set(self.is_zoomed()); + let mut fullscreen = self.ivars().fullscreen.borrow_mut(); + match &*fullscreen { + // Exclusive mode sets the state in `set_fullscreen` as the user + // can't enter exclusive mode by other means (like the + // fullscreen button on the window decorations) + Some(Fullscreen::Exclusive(_)) => (), + // `window_will_enter_fullscreen` was triggered and we're already + // in fullscreen, so we must've reached here by `set_fullscreen` + // as it updates the state + Some(Fullscreen::Borderless(_)) => (), + // Otherwise, we must've reached fullscreen by the user clicking + // on the green fullscreen button. Update state! + None => { + let current_monitor = self.current_monitor_inner(); + *fullscreen = Some(Fullscreen::Borderless(current_monitor)); + }, + } + self.ivars().in_fullscreen_transition.set(true); + } + + /// Invoked when before exit fullscreen + #[method(windowWillExitFullScreen:)] + fn window_will_exit_fullscreen(&self, _: Option<&AnyObject>) { + trace_scope!("windowWillExitFullScreen:"); + + self.ivars().in_fullscreen_transition.set(true); + } + + #[method(window:willUseFullScreenPresentationOptions:)] + fn window_will_use_fullscreen_presentation_options( + &self, + _: Option<&AnyObject>, + proposed_options: NSApplicationPresentationOptions, + ) -> NSApplicationPresentationOptions { + trace_scope!("window:willUseFullScreenPresentationOptions:"); + // Generally, games will want to disable the menu bar and the dock. Ideally, + // this would be configurable by the user. Unfortunately because of our + // `CGShieldingWindowLevel() + 1` hack (see `set_fullscreen`), our window is + // placed on top of the menu bar in exclusive fullscreen mode. This looks + // broken so we always disable the menu bar in exclusive fullscreen. We may + // still want to make this configurable for borderless fullscreen. Right now + // we don't, for consistency. If we do, it should be documented that the + // user-provided options are ignored in exclusive fullscreen. + let mut options = proposed_options; + let fullscreen = self.ivars().fullscreen.borrow(); + if let Some(Fullscreen::Exclusive(_)) = &*fullscreen { + options = NSApplicationPresentationOptions::NSApplicationPresentationFullScreen + | NSApplicationPresentationOptions::NSApplicationPresentationHideDock + | NSApplicationPresentationOptions::NSApplicationPresentationHideMenuBar; + } + + options + } + + /// Invoked when entered fullscreen + #[method(windowDidEnterFullScreen:)] + fn window_did_enter_fullscreen(&self, _: Option<&AnyObject>) { + trace_scope!("windowDidEnterFullScreen:"); + self.ivars().initial_fullscreen.set(false); + self.ivars().in_fullscreen_transition.set(false); + if let Some(target_fullscreen) = self.ivars().target_fullscreen.take() { + self.set_fullscreen(target_fullscreen); + } + } + + /// Invoked when exited fullscreen + #[method(windowDidExitFullScreen:)] + fn window_did_exit_fullscreen(&self, _: Option<&AnyObject>) { + trace_scope!("windowDidExitFullScreen:"); + + self.restore_state_from_fullscreen(); + self.ivars().in_fullscreen_transition.set(false); + if let Some(target_fullscreen) = self.ivars().target_fullscreen.take() { + self.set_fullscreen(target_fullscreen); + } + } + + /// Invoked when fail to enter fullscreen + /// + /// When this window launch from a fullscreen app (e.g. launch from VS Code + /// terminal), it creates a new virtual desktop and a transition animation. + /// This animation takes one second and cannot be disable without + /// elevated privileges. In this animation time, all toggleFullscreen events + /// will be failed. In this implementation, we will try again by using + /// performSelector:withObject:afterDelay: until window_did_enter_fullscreen. + /// It should be fine as we only do this at initialization (i.e with_fullscreen + /// was set). + /// + /// From Apple doc: + /// In some cases, the transition to enter full-screen mode can fail, + /// due to being in the midst of handling some other animation or user gesture. + /// This method indicates that there was an error, and you should clean up any + /// work you may have done to prepare to enter full-screen mode. + #[method(windowDidFailToEnterFullScreen:)] + fn window_did_fail_to_enter_fullscreen(&self, _: Option<&AnyObject>) { + trace_scope!("windowDidFailToEnterFullScreen:"); + self.ivars().in_fullscreen_transition.set(false); + self.ivars().target_fullscreen.replace(None); + if self.ivars().initial_fullscreen.get() { + unsafe { + self.window().performSelector_withObject_afterDelay( + sel!(toggleFullScreen:), + None, + 0.5, + ) + }; + } else { + self.restore_state_from_fullscreen(); + } + } + + // Invoked when the occlusion state of the window changes + #[method(windowDidChangeOcclusionState:)] + fn window_did_change_occlusion_state(&self, _: Option<&AnyObject>) { + trace_scope!("windowDidChangeOcclusionState:"); + let visible = self.window().occlusionState().contains(NSWindowOcclusionState::Visible); + self.queue_event(WindowEvent::Occluded(!visible)); + } + + #[method(windowDidChangeScreen:)] + fn window_did_change_screen(&self, _: Option<&AnyObject>) { + trace_scope!("windowDidChangeScreen:"); + let is_simple_fullscreen = self.ivars().is_simple_fullscreen.get(); + if is_simple_fullscreen { + if let Some(screen) = self.window().screen() { + self.window().setFrame_display(screen.frame(), true); + } + } + } + } + + unsafe impl NSDraggingDestination for WindowDelegate { + /// Invoked when the dragged image enters destination bounds or frame + #[method(draggingEntered:)] + fn dragging_entered(&self, sender: &NSObject) -> bool { + trace_scope!("draggingEntered:"); + + use std::path::PathBuf; + + let pb: Retained<NSPasteboard> = unsafe { msg_send_id![sender, draggingPasteboard] }; + let filenames = match pb.propertyListForType(unsafe { NSFilenamesPboardType }) { + Some(filenames) => filenames, + None => return false.into(), + }; + let filenames: Retained<NSArray<NSString>> = unsafe { Retained::cast(filenames) }; + + filenames.into_iter().for_each(|file| { + let path = PathBuf::from(file.to_string()); + self.queue_event(WindowEvent::HoveredFile(path)); + }); + + true + } + + /// Invoked when the image is released + #[method(prepareForDragOperation:)] + fn prepare_for_drag_operation(&self, _sender: &NSObject) -> bool { + trace_scope!("prepareForDragOperation:"); + true + } + + /// Invoked after the released image has been removed from the screen + #[method(performDragOperation:)] + fn perform_drag_operation(&self, sender: &NSObject) -> bool { + trace_scope!("performDragOperation:"); + + use std::path::PathBuf; + + let pb: Retained<NSPasteboard> = unsafe { msg_send_id![sender, draggingPasteboard] }; + let filenames = match pb.propertyListForType(unsafe { NSFilenamesPboardType }) { + Some(filenames) => filenames, + None => return false.into(), + }; + let filenames: Retained<NSArray<NSString>> = unsafe { Retained::cast(filenames) }; + + filenames.into_iter().for_each(|file| { + let path = PathBuf::from(file.to_string()); + self.queue_event(WindowEvent::DroppedFile(path)); + }); + + true + } + + /// Invoked when the dragging operation is complete + #[method(concludeDragOperation:)] + fn conclude_drag_operation(&self, _sender: Option<&NSObject>) { + trace_scope!("concludeDragOperation:"); + } + + /// Invoked when the dragging operation is cancelled + #[method(draggingExited:)] + fn dragging_exited(&self, _sender: Option<&NSObject>) { + trace_scope!("draggingExited:"); + self.queue_event(WindowEvent::HoveredFileCancelled); + } + } + + // Key-Value Observing + unsafe impl WindowDelegate { + #[method(observeValueForKeyPath:ofObject:change:context:)] + fn observe_value( + &self, + key_path: Option<&NSString>, + _object: Option<&AnyObject>, + change: Option<&NSDictionary<NSKeyValueChangeKey, AnyObject>>, + _context: *mut c_void, + ) { + trace_scope!("observeValueForKeyPath:ofObject:change:context:"); + // NOTE: We don't _really_ need to check the key path, as there should only be one, but + // in the future we might want to observe other key paths. + if key_path == Some(ns_string!("effectiveAppearance")) { + let change = change.expect("requested a change dictionary in `addObserver`, but none was provided"); + let old = change.get(unsafe { NSKeyValueChangeOldKey }).expect("requested change dictionary did not contain `NSKeyValueChangeOldKey`"); + let new = change.get(unsafe { NSKeyValueChangeNewKey }).expect("requested change dictionary did not contain `NSKeyValueChangeNewKey`"); + + // SAFETY: The value of `effectiveAppearance` is `NSAppearance` + let old: *const AnyObject = old; + let old: *const NSAppearance = old.cast(); + let old: &NSAppearance = unsafe { &*old }; + let new: *const AnyObject = new; + let new: *const NSAppearance = new.cast(); + let new: &NSAppearance = unsafe { &*new }; + + trace!(old = %unsafe { old.name() }, new = %unsafe { new.name() }, "effectiveAppearance changed"); + + // Ignore the change if the window's theme is customized by the user (since in that + // case the `effectiveAppearance` is only emitted upon said customization, and then + // it's triggered directly by a user action, and we don't want to emit the event). + if unsafe { self.window().appearance() }.is_some() { + return; + } + + let old = appearance_to_theme(old); + let new = appearance_to_theme(new); + // Check that the theme changed in Winit's terms (the theme might have changed on + // other parameters, such as level of contrast, but the event should not be emitted + // in those cases). + if old == new { + return; + } + + self.queue_event(WindowEvent::ThemeChanged(new)); + } else { + panic!("unknown observed keypath {key_path:?}"); + } + } + } +); + +impl Drop for WindowDelegate { + fn drop(&mut self) { + unsafe { + self.window().removeObserver_forKeyPath(self, ns_string!("effectiveAppearance")); + } + } +} + +fn new_window( + app_delegate: &ApplicationDelegate, + attrs: &WindowAttributes, + mtm: MainThreadMarker, +) -> Option<Retained<WinitWindow>> { + autoreleasepool(|_| { + let screen = match attrs.fullscreen.clone().map(Into::into) { + Some(Fullscreen::Borderless(Some(monitor))) + | Some(Fullscreen::Exclusive(VideoModeHandle { monitor, .. })) => { + monitor.ns_screen(mtm).or_else(|| NSScreen::mainScreen(mtm)) + }, + Some(Fullscreen::Borderless(None)) => NSScreen::mainScreen(mtm), + None => None, + }; + let frame = match &screen { + Some(screen) => screen.frame(), + None => { + let scale_factor = NSScreen::mainScreen(mtm) + .map(|screen| screen.backingScaleFactor() as f64) + .unwrap_or(1.0); + let size = match attrs.inner_size { + Some(size) => { + let size = size.to_logical(scale_factor); + NSSize::new(size.width, size.height) + }, + None => NSSize::new(800.0, 600.0), + }; + let position = match attrs.position { + Some(position) => { + let position = position.to_logical(scale_factor); + flip_window_screen_coordinates(NSRect::new( + NSPoint::new(position.x, position.y), + size, + )) + }, + // This value is ignored by calling win.center() below + None => NSPoint::new(0.0, 0.0), + }; + NSRect::new(position, size) + }, + }; + + let mut masks = if (!attrs.decorations && screen.is_none()) + || attrs.platform_specific.titlebar_hidden + { + // Resizable without a titlebar or borders + // if decorations is set to false, ignore pl_attrs + // + // if the titlebar is hidden, ignore other pl_attrs + NSWindowStyleMask::Borderless + | NSWindowStyleMask::Resizable + | NSWindowStyleMask::Miniaturizable + } else { + // default case, resizable window with titlebar and titlebar buttons + NSWindowStyleMask::Closable + | NSWindowStyleMask::Miniaturizable + | NSWindowStyleMask::Resizable + | NSWindowStyleMask::Titled + }; + + if !attrs.resizable { + masks &= !NSWindowStyleMask::Resizable; + } + + if !attrs.enabled_buttons.contains(WindowButtons::MINIMIZE) { + masks &= !NSWindowStyleMask::Miniaturizable; + } + + if !attrs.enabled_buttons.contains(WindowButtons::CLOSE) { + masks &= !NSWindowStyleMask::Closable; + } + + if attrs.platform_specific.fullsize_content_view { + masks |= NSWindowStyleMask::FullSizeContentView; + } + + let window: Option<Retained<WinitWindow>> = unsafe { + msg_send_id![ + super(mtm.alloc().set_ivars(())), + initWithContentRect: frame, + styleMask: masks, + backing: NSBackingStoreType::NSBackingStoreBuffered, + defer: false, + ] + }; + let window = window?; + + // It is very important for correct memory management that we + // disable the extra release that would otherwise happen when + // calling `close` on the window. + unsafe { window.setReleasedWhenClosed(false) }; + + window.setTitle(&NSString::from_str(&attrs.title)); + window.setAcceptsMouseMovedEvents(true); + + if let Some(identifier) = &attrs.platform_specific.tabbing_identifier { + window.setTabbingIdentifier(&NSString::from_str(identifier)); + window.setTabbingMode(NSWindowTabbingMode::Preferred); + } + + if attrs.content_protected { + window.setSharingType(NSWindowSharingType::NSWindowSharingNone); + } + + if attrs.platform_specific.titlebar_transparent { + window.setTitlebarAppearsTransparent(true); + } + if attrs.platform_specific.title_hidden { + window.setTitleVisibility(NSWindowTitleVisibility::NSWindowTitleHidden); + } + if attrs.platform_specific.titlebar_buttons_hidden { + for titlebar_button in &[ + #[allow(deprecated)] + NSWindowFullScreenButton, + NSWindowButton::NSWindowMiniaturizeButton, + NSWindowButton::NSWindowCloseButton, + NSWindowButton::NSWindowZoomButton, + ] { + if let Some(button) = window.standardWindowButton(*titlebar_button) { + button.setHidden(true); + } + } + } + if attrs.platform_specific.movable_by_window_background { + window.setMovableByWindowBackground(true); + } + + if !attrs.enabled_buttons.contains(WindowButtons::MAXIMIZE) { + if let Some(button) = window.standardWindowButton(NSWindowButton::NSWindowZoomButton) { + button.setEnabled(false); + } + } + + if !attrs.platform_specific.has_shadow { + window.setHasShadow(false); + } + if attrs.position.is_none() { + window.center(); + } + + let view = WinitView::new( + app_delegate, + &window, + attrs.platform_specific.accepts_first_mouse, + attrs.platform_specific.option_as_alt, + ); + + // The default value of `setWantsBestResolutionOpenGLSurface:` was `false` until + // macos 10.14 and `true` after 10.15, we should set it to `YES` or `NO` to avoid + // always the default system value in favour of the user's code + #[allow(deprecated)] + view.setWantsBestResolutionOpenGLSurface(!attrs.platform_specific.disallow_hidpi); + + // On Mojave, views automatically become layer-backed shortly after being added to + // a window. Changing the layer-backedness of a view breaks the association between + // the view and its associated OpenGL context. To work around this, on Mojave we + // explicitly make the view layer-backed up front so that AppKit doesn't do it + // itself and break the association with its context. + if unsafe { NSAppKitVersionNumber }.floor() > NSAppKitVersionNumber10_12 { + view.setWantsLayer(true); + } + + // Configure the new view as the "key view" for the window + window.setContentView(Some(&view)); + window.setInitialFirstResponder(Some(&view)); + + if attrs.transparent { + window.setOpaque(false); + // See `set_transparent` for details on why we do this. + window.setBackgroundColor(unsafe { Some(&NSColor::clearColor()) }); + } + + // register for drag and drop operations. + window + .registerForDraggedTypes(&NSArray::from_id_slice(&[ + unsafe { NSFilenamesPboardType }.copy() + ])); + + Some(window) + }) +} + +impl WindowDelegate { + pub(super) fn new( + app_delegate: &ApplicationDelegate, + attrs: WindowAttributes, + mtm: MainThreadMarker, + ) -> Result<Retained<Self>, RootOsError> { + let window = new_window(app_delegate, &attrs, mtm) + .ok_or_else(|| os_error!(OsError::CreationError("couldn't create `NSWindow`")))?; + + #[cfg(feature = "rwh_06")] + match attrs.parent_window.map(|handle| handle.0) { + Some(rwh_06::RawWindowHandle::AppKit(handle)) => { + // SAFETY: Caller ensures the pointer is valid or NULL + // Unwrap is fine, since the pointer comes from `NonNull`. + let parent_view: Retained<NSView> = + unsafe { Retained::retain(handle.ns_view.as_ptr().cast()) }.unwrap(); + let parent = parent_view.window().ok_or_else(|| { + os_error!(OsError::CreationError("parent view should be installed in a window")) + })?; + + // SAFETY: We know that there are no parent -> child -> parent cycles since the only + // place in `winit` where we allow making a window a child window is + // right here, just after it's been created. + unsafe { + parent.addChildWindow_ordered(&window, NSWindowOrderingMode::NSWindowAbove) + }; + }, + Some(raw) => panic!("invalid raw window handle {raw:?} on macOS"), + None => (), + } + + let resize_increments = + match attrs.resize_increments.map(|i| i.to_logical(window.backingScaleFactor() as _)) { + Some(LogicalSize { width, height }) if width >= 1. && height >= 1. => { + NSSize::new(width, height) + }, + _ => NSSize::new(1., 1.), + }; + + let scale_factor = window.backingScaleFactor() as _; + + if let Some(appearance) = theme_to_appearance(attrs.preferred_theme) { + unsafe { window.setAppearance(Some(&appearance)) }; + } + + let delegate = mtm.alloc().set_ivars(State { + app_delegate: app_delegate.retain(), + window: window.retain(), + previous_position: Cell::new(flip_window_screen_coordinates(window.frame())), + previous_scale_factor: Cell::new(scale_factor), + resize_increments: Cell::new(resize_increments), + decorations: Cell::new(attrs.decorations), + resizable: Cell::new(attrs.resizable), + maximized: Cell::new(attrs.maximized), + save_presentation_opts: Cell::new(None), + initial_fullscreen: Cell::new(attrs.fullscreen.is_some()), + fullscreen: RefCell::new(None), + target_fullscreen: RefCell::new(None), + in_fullscreen_transition: Cell::new(false), + standard_frame: Cell::new(None), + is_simple_fullscreen: Cell::new(false), + saved_style: Cell::new(None), + is_borderless_game: Cell::new(attrs.platform_specific.borderless_game), + }); + let delegate: Retained<WindowDelegate> = unsafe { msg_send_id![super(delegate), init] }; + + if scale_factor != 1.0 { + let delegate = delegate.clone(); + RunLoop::main(mtm).queue_closure(move || { + delegate.handle_scale_factor_changed(scale_factor); + }); + } + window.setDelegate(Some(ProtocolObject::from_ref(&*delegate))); + + // Listen for theme change event. + // + // SAFETY: The observer is un-registered in the `Drop` of the delegate. + unsafe { + window.addObserver_forKeyPath_options_context( + &delegate, + ns_string!("effectiveAppearance"), + NSKeyValueObservingOptions::NSKeyValueObservingOptionNew + | NSKeyValueObservingOptions::NSKeyValueObservingOptionOld, + ptr::null_mut(), + ) + }; + + if attrs.blur { + delegate.set_blur(attrs.blur); + } + + if let Some(dim) = attrs.min_inner_size { + delegate.set_min_inner_size(Some(dim)); + } + if let Some(dim) = attrs.max_inner_size { + delegate.set_max_inner_size(Some(dim)); + } + + delegate.set_window_level(attrs.window_level); + + delegate.set_cursor(attrs.cursor); + + // XXX Send `Focused(false)` right after creating the window delegate, so we won't + // obscure the real focused events on the startup. + delegate.queue_event(WindowEvent::Focused(false)); + + // Set fullscreen mode after we setup everything + delegate.set_fullscreen(attrs.fullscreen.map(Into::into)); + + // Setting the window as key has to happen *after* we set the fullscreen + // state, since otherwise we'll briefly see the window at normal size + // before it transitions. + if attrs.visible { + if attrs.active { + // Tightly linked with `app_state::window_activation_hack` + window.makeKeyAndOrderFront(None); + } else { + window.orderFront(None); + } + } + + if attrs.maximized { + delegate.set_maximized(attrs.maximized); + } + + Ok(delegate) + } + + #[track_caller] + pub(super) fn view(&self) -> Retained<WinitView> { + // SAFETY: The view inside WinitWindow is always `WinitView` + unsafe { Retained::cast(self.window().contentView().unwrap()) } + } + + #[track_caller] + pub(super) fn window(&self) -> &WinitWindow { + &self.ivars().window + } + + #[track_caller] + pub(crate) fn id(&self) -> WindowId { + self.window().id() + } + + pub(crate) fn queue_event(&self, event: WindowEvent) { + self.ivars().app_delegate.maybe_queue_window_event(self.window().id(), event); + } + + fn handle_scale_factor_changed(&self, scale_factor: CGFloat) { + let app_delegate = &self.ivars().app_delegate; + let window = self.window(); + + let content_size = window.contentRectForFrameRect(window.frame()).size; + let content_size = LogicalSize::new(content_size.width, content_size.height); + + let suggested_size = content_size.to_physical(scale_factor); + let new_inner_size = Arc::new(Mutex::new(suggested_size)); + app_delegate.handle_window_event(window.id(), WindowEvent::ScaleFactorChanged { + scale_factor, + inner_size_writer: InnerSizeWriter::new(Arc::downgrade(&new_inner_size)), + }); + let physical_size = *new_inner_size.lock().unwrap(); + drop(new_inner_size); + + if physical_size != suggested_size { + let logical_size = physical_size.to_logical(scale_factor); + let size = NSSize::new(logical_size.width, logical_size.height); + window.setContentSize(size); + } + app_delegate.handle_window_event(window.id(), WindowEvent::Resized(physical_size)); + } + + fn emit_move_event(&self) { + let position = flip_window_screen_coordinates(self.window().frame()); + if self.ivars().previous_position.get() == position { + return; + } + self.ivars().previous_position.set(position); + + let position = + LogicalPosition::new(position.x, position.y).to_physical(self.scale_factor()); + self.queue_event(WindowEvent::Moved(position)); + } + + fn set_style_mask(&self, mask: NSWindowStyleMask) { + self.window().setStyleMask(mask); + // If we don't do this, key handling will break + // (at least until the window is clicked again/etc.) + let _ = self.window().makeFirstResponder(Some(&self.view())); + } + + pub fn set_title(&self, title: &str) { + self.window().setTitle(&NSString::from_str(title)) + } + + pub fn set_transparent(&self, transparent: bool) { + // This is just a hint for Quartz, it doesn't actually speculate with window alpha. + // Providing a wrong value here could result in visual artifacts, when the window is + // transparent. + self.window().setOpaque(!transparent); + + // AppKit draws the window with a background color by default, which is usually really + // nice, but gets in the way when we want to allow the contents of the window to be + // transparent, as in that case, the transparent contents will just be drawn on top of + // the background color. As such, to allow the window to be transparent, we must also set + // the background color to one with an empty alpha channel. + let color = if transparent { + unsafe { NSColor::clearColor() } + } else { + unsafe { NSColor::windowBackgroundColor() } + }; + + self.window().setBackgroundColor(Some(&color)); + } + + pub fn set_blur(&self, blur: bool) { + // NOTE: in general we want to specify the blur radius, but the choice of 80 + // should be a reasonable default. + let radius = if blur { 80 } else { 0 }; + let window_number = unsafe { self.window().windowNumber() }; + unsafe { + ffi::CGSSetWindowBackgroundBlurRadius( + ffi::CGSMainConnectionID(), + window_number, + radius, + ); + } + } + + pub fn set_visible(&self, visible: bool) { + match visible { + true => self.window().makeKeyAndOrderFront(None), + false => self.window().orderOut(None), + } + } + + #[inline] + pub fn is_visible(&self) -> Option<bool> { + Some(self.window().isVisible()) + } + + pub fn request_redraw(&self) { + self.ivars().app_delegate.queue_redraw(self.window().id()); + } + + #[inline] + pub fn pre_present_notify(&self) {} + + pub fn outer_position(&self) -> Result<PhysicalPosition<i32>, NotSupportedError> { + let position = flip_window_screen_coordinates(self.window().frame()); + Ok(LogicalPosition::new(position.x, position.y).to_physical(self.scale_factor())) + } + + pub fn inner_position(&self) -> Result<PhysicalPosition<i32>, NotSupportedError> { + let content_rect = self.window().contentRectForFrameRect(self.window().frame()); + let position = flip_window_screen_coordinates(content_rect); + Ok(LogicalPosition::new(position.x, position.y).to_physical(self.scale_factor())) + } + + pub fn set_outer_position(&self, position: Position) { + let position = position.to_logical(self.scale_factor()); + let point = flip_window_screen_coordinates(NSRect::new( + NSPoint::new(position.x, position.y), + self.window().frame().size, + )); + unsafe { self.window().setFrameOrigin(point) }; + } + + #[inline] + pub fn inner_size(&self) -> PhysicalSize<u32> { + let content_rect = self.window().contentRectForFrameRect(self.window().frame()); + let logical = LogicalSize::new(content_rect.size.width, content_rect.size.height); + logical.to_physical(self.scale_factor()) + } + + #[inline] + pub fn outer_size(&self) -> PhysicalSize<u32> { + let frame = self.window().frame(); + let logical = LogicalSize::new(frame.size.width, frame.size.height); + logical.to_physical(self.scale_factor()) + } + + #[inline] + pub fn request_inner_size(&self, size: Size) -> Option<PhysicalSize<u32>> { + let scale_factor = self.scale_factor(); + let size = size.to_logical(scale_factor); + self.window().setContentSize(NSSize::new(size.width, size.height)); + None + } + + pub fn set_min_inner_size(&self, dimensions: Option<Size>) { + let dimensions = + dimensions.unwrap_or(Size::Logical(LogicalSize { width: 0.0, height: 0.0 })); + let min_size = dimensions.to_logical::<CGFloat>(self.scale_factor()); + + let min_size = NSSize::new(min_size.width, min_size.height); + unsafe { self.window().setContentMinSize(min_size) }; + + // If necessary, resize the window to match constraint + let mut current_size = self.window().contentRectForFrameRect(self.window().frame()).size; + if current_size.width < min_size.width { + current_size.width = min_size.width; + } + if current_size.height < min_size.height { + current_size.height = min_size.height; + } + self.window().setContentSize(current_size); + } + + pub fn set_max_inner_size(&self, dimensions: Option<Size>) { + let dimensions = dimensions.unwrap_or(Size::Logical(LogicalSize { + width: f32::MAX as f64, + height: f32::MAX as f64, + })); + let scale_factor = self.scale_factor(); + let max_size = dimensions.to_logical::<CGFloat>(scale_factor); + + let max_size = NSSize::new(max_size.width, max_size.height); + unsafe { self.window().setContentMaxSize(max_size) }; + + // If necessary, resize the window to match constraint + let mut current_size = self.window().contentRectForFrameRect(self.window().frame()).size; + if max_size.width < current_size.width { + current_size.width = max_size.width; + } + if max_size.height < current_size.height { + current_size.height = max_size.height; + } + self.window().setContentSize(current_size); + } + + pub fn resize_increments(&self) -> Option<PhysicalSize<u32>> { + let increments = self.ivars().resize_increments.get(); + let (w, h) = (increments.width, increments.height); + if w > 1.0 || h > 1.0 { + Some(LogicalSize::new(w, h).to_physical(self.scale_factor())) + } else { + None + } + } + + pub fn set_resize_increments(&self, increments: Option<Size>) { + // XXX the resize increments are only used during live resizes. + self.ivars().resize_increments.set( + increments + .map(|increments| { + let logical = increments.to_logical::<f64>(self.scale_factor()); + NSSize::new(logical.width.max(1.0), logical.height.max(1.0)) + }) + .unwrap_or_else(|| NSSize::new(1.0, 1.0)), + ); + } + + pub(crate) fn set_resize_increments_inner(&self, size: NSSize) { + // It was concluded (#2411) that there is never a use-case for + // "outer" resize increments, hence we set "inner" ones here. + // ("outer" in macOS being just resizeIncrements, and "inner" - contentResizeIncrements) + // This is consistent with X11 size hints behavior + self.window().setContentResizeIncrements(size); + } + + #[inline] + pub fn set_resizable(&self, resizable: bool) { + self.ivars().resizable.set(resizable); + let fullscreen = self.ivars().fullscreen.borrow().is_some(); + if !fullscreen { + let mut mask = self.window().styleMask(); + if resizable { + mask |= NSWindowStyleMask::Resizable; + } else { + mask &= !NSWindowStyleMask::Resizable; + } + self.set_style_mask(mask); + } + // Otherwise, we don't change the mask until we exit fullscreen. + } + + #[inline] + pub fn is_resizable(&self) -> bool { + self.window().isResizable() + } + + #[inline] + pub fn set_enabled_buttons(&self, buttons: WindowButtons) { + let mut mask = self.window().styleMask(); + + if buttons.contains(WindowButtons::CLOSE) { + mask |= NSWindowStyleMask::Closable; + } else { + mask &= !NSWindowStyleMask::Closable; + } + + if buttons.contains(WindowButtons::MINIMIZE) { + mask |= NSWindowStyleMask::Miniaturizable; + } else { + mask &= !NSWindowStyleMask::Miniaturizable; + } + + // This must happen before the button's "enabled" status has been set, + // hence we do it synchronously. + self.set_style_mask(mask); + + // We edit the button directly instead of using `NSResizableWindowMask`, + // since that mask also affect the resizability of the window (which is + // controllable by other means in `winit`). + if let Some(button) = self.window().standardWindowButton(NSWindowButton::NSWindowZoomButton) + { + button.setEnabled(buttons.contains(WindowButtons::MAXIMIZE)); + } + } + + #[inline] + pub fn enabled_buttons(&self) -> WindowButtons { + let mut buttons = WindowButtons::empty(); + if self.window().isMiniaturizable() { + buttons |= WindowButtons::MINIMIZE; + } + if self + .window() + .standardWindowButton(NSWindowButton::NSWindowZoomButton) + .map(|b| b.isEnabled()) + .unwrap_or(true) + { + buttons |= WindowButtons::MAXIMIZE; + } + if self.window().hasCloseBox() { + buttons |= WindowButtons::CLOSE; + } + buttons + } + + pub fn set_cursor(&self, cursor: Cursor) { + let view = self.view(); + + let cursor = match cursor { + Cursor::Icon(icon) => cursor_from_icon(icon), + Cursor::Custom(cursor) => cursor.inner.0, + }; + + if view.cursor_icon() == cursor { + return; + } + + view.set_cursor_icon(cursor); + self.window().invalidateCursorRectsForView(&view); + } + + #[inline] + pub fn set_cursor_grab(&self, mode: CursorGrabMode) -> Result<(), ExternalError> { + let associate_mouse_cursor = match mode { + CursorGrabMode::Locked => false, + CursorGrabMode::None => true, + CursorGrabMode::Confined => { + return Err(ExternalError::NotSupported(NotSupportedError::new())) + }, + }; + + // TODO: Do this for real https://stackoverflow.com/a/40922095/5435443 + CGDisplay::associate_mouse_and_mouse_cursor_position(associate_mouse_cursor) + .map_err(|status| ExternalError::Os(os_error!(OsError::CGError(status)))) + } + + #[inline] + pub fn set_cursor_visible(&self, visible: bool) { + let view = self.view(); + let state_changed = view.set_cursor_visible(visible); + if state_changed { + self.window().invalidateCursorRectsForView(&view); + } + } + + #[inline] + pub fn scale_factor(&self) -> f64 { + self.window().backingScaleFactor() as _ + } + + #[inline] + pub fn set_cursor_position(&self, cursor_position: Position) -> Result<(), ExternalError> { + let physical_window_position = self.inner_position().unwrap(); + let scale_factor = self.scale_factor(); + let window_position = physical_window_position.to_logical::<CGFloat>(scale_factor); + let logical_cursor_position = cursor_position.to_logical::<CGFloat>(scale_factor); + let point = CGPoint { + x: logical_cursor_position.x + window_position.x, + y: logical_cursor_position.y + window_position.y, + }; + CGDisplay::warp_mouse_cursor_position(point) + .map_err(|e| ExternalError::Os(os_error!(OsError::CGError(e))))?; + CGDisplay::associate_mouse_and_mouse_cursor_position(true) + .map_err(|e| ExternalError::Os(os_error!(OsError::CGError(e))))?; + + Ok(()) + } + + #[inline] + pub fn drag_window(&self) -> Result<(), ExternalError> { + let mtm = MainThreadMarker::from(self); + let event = + NSApplication::sharedApplication(mtm).currentEvent().ok_or(ExternalError::Ignored)?; + self.window().performWindowDragWithEvent(&event); + Ok(()) + } + + #[inline] + pub fn drag_resize_window(&self, _direction: ResizeDirection) -> Result<(), ExternalError> { + Err(ExternalError::NotSupported(NotSupportedError::new())) + } + + #[inline] + pub fn show_window_menu(&self, _position: Position) {} + + #[inline] + pub fn set_cursor_hittest(&self, hittest: bool) -> Result<(), ExternalError> { + self.window().setIgnoresMouseEvents(!hittest); + Ok(()) + } + + pub(crate) fn is_zoomed(&self) -> bool { + // because `isZoomed` doesn't work if the window's borderless, + // we make it resizable temporarily. + let curr_mask = self.window().styleMask(); + + let required = NSWindowStyleMask::Titled | NSWindowStyleMask::Resizable; + let needs_temp_mask = !curr_mask.contains(required); + if needs_temp_mask { + self.set_style_mask(required); + } + + let is_zoomed = self.window().isZoomed(); + + // Roll back temp styles + if needs_temp_mask { + self.set_style_mask(curr_mask); + } + + is_zoomed + } + + fn saved_style(&self) -> NSWindowStyleMask { + let base_mask = + self.ivars().saved_style.take().unwrap_or_else(|| self.window().styleMask()); + if self.ivars().resizable.get() { + base_mask | NSWindowStyleMask::Resizable + } else { + base_mask & !NSWindowStyleMask::Resizable + } + } + + /// This is called when the window is exiting fullscreen, whether by the + /// user clicking on the green fullscreen button or programmatically by + /// `toggleFullScreen:` + pub(crate) fn restore_state_from_fullscreen(&self) { + self.ivars().fullscreen.replace(None); + + let maximized = self.ivars().maximized.get(); + let mask = self.saved_style(); + + self.set_style_mask(mask); + self.set_maximized(maximized); + } + + #[inline] + pub fn set_minimized(&self, minimized: bool) { + let is_minimized = self.window().isMiniaturized(); + if is_minimized == minimized { + return; + } + + if minimized { + self.window().miniaturize(Some(self)); + } else { + unsafe { self.window().deminiaturize(Some(self)) }; + } + } + + #[inline] + pub fn is_minimized(&self) -> Option<bool> { + Some(self.window().isMiniaturized()) + } + + #[inline] + pub fn set_maximized(&self, maximized: bool) { + let mtm = MainThreadMarker::from(self); + let is_zoomed = self.is_zoomed(); + if is_zoomed == maximized { + return; + }; + + // Save the standard frame sized if it is not zoomed + if !is_zoomed { + self.ivars().standard_frame.set(Some(self.window().frame())); + } + + self.ivars().maximized.set(maximized); + + if self.ivars().fullscreen.borrow().is_some() { + // Handle it in window_did_exit_fullscreen + return; + } + + if self.window().styleMask().contains(NSWindowStyleMask::Resizable) { + // Just use the native zoom if resizable + self.window().zoom(None); + } else { + // if it's not resizable, we set the frame directly + let new_rect = if maximized { + let screen = NSScreen::mainScreen(mtm).expect("no screen found"); + screen.visibleFrame() + } else { + self.ivars().standard_frame.get().unwrap_or(DEFAULT_STANDARD_FRAME) + }; + self.window().setFrame_display(new_rect, false); + } + } + + #[inline] + pub(crate) fn fullscreen(&self) -> Option<Fullscreen> { + self.ivars().fullscreen.borrow().clone() + } + + #[inline] + pub fn is_maximized(&self) -> bool { + self.is_zoomed() + } + + #[inline] + pub(crate) fn set_fullscreen(&self, fullscreen: Option<Fullscreen>) { + let mtm = MainThreadMarker::from(self); + let app = NSApplication::sharedApplication(mtm); + + if self.ivars().is_simple_fullscreen.get() { + return; + } + if self.ivars().in_fullscreen_transition.get() { + // We can't set fullscreen here. + // Set fullscreen after transition. + self.ivars().target_fullscreen.replace(Some(fullscreen)); + return; + } + let old_fullscreen = self.ivars().fullscreen.borrow().clone(); + if fullscreen == old_fullscreen { + return; + } + + // If the fullscreen is on a different monitor, we must move the window + // to that monitor before we toggle fullscreen (as `toggleFullScreen` + // does not take a screen parameter, but uses the current screen) + if let Some(ref fullscreen) = fullscreen { + let new_screen = match fullscreen { + Fullscreen::Borderless(Some(monitor)) => monitor.clone(), + Fullscreen::Borderless(None) => { + if let Some(monitor) = self.current_monitor_inner() { + monitor + } else { + return; + } + }, + Fullscreen::Exclusive(video_mode) => video_mode.monitor(), + } + .ns_screen(mtm) + .unwrap(); + + let old_screen = self.window().screen().unwrap(); + if old_screen != new_screen { + unsafe { self.window().setFrameOrigin(new_screen.frame().origin) }; + } + } + + if let Some(Fullscreen::Exclusive(ref video_mode)) = fullscreen { + // Note: `enterFullScreenMode:withOptions:` seems to do the exact + // same thing as we're doing here (captures the display, sets the + // video mode, and hides the menu bar and dock), with the exception + // of that I couldn't figure out how to set the display mode with + // it. I think `enterFullScreenMode:withOptions:` is still using the + // older display mode API where display modes were of the type + // `CFDictionary`, but this has changed, so we can't obtain the + // correct parameter for this any longer. Apple's code samples for + // this function seem to just pass in "YES" for the display mode + // parameter, which is not consistent with the docs saying that it + // takes a `NSDictionary`.. + + let display_id = video_mode.monitor().native_identifier(); + + let mut fade_token = ffi::kCGDisplayFadeReservationInvalidToken; + + if matches!(old_fullscreen, Some(Fullscreen::Borderless(_))) { + self.ivars().save_presentation_opts.replace(Some(app.presentationOptions())); + } + + unsafe { + // Fade to black (and wait for the fade to complete) to hide the + // flicker from capturing the display and switching display mode + if ffi::CGAcquireDisplayFadeReservation(5.0, &mut fade_token) + == ffi::kCGErrorSuccess + { + ffi::CGDisplayFade( + fade_token, + 0.3, + ffi::kCGDisplayBlendNormal, + ffi::kCGDisplayBlendSolidColor, + 0.0, + 0.0, + 0.0, + ffi::TRUE, + ); + } + + assert_eq!(ffi::CGDisplayCapture(display_id), ffi::kCGErrorSuccess); + } + + unsafe { + let result = ffi::CGDisplaySetDisplayMode( + display_id, + video_mode.native_mode.0, + std::ptr::null(), + ); + assert!(result == ffi::kCGErrorSuccess, "failed to set video mode"); + + // After the display has been configured, fade back in + // asynchronously + if fade_token != ffi::kCGDisplayFadeReservationInvalidToken { + ffi::CGDisplayFade( + fade_token, + 0.6, + ffi::kCGDisplayBlendSolidColor, + ffi::kCGDisplayBlendNormal, + 0.0, + 0.0, + 0.0, + ffi::FALSE, + ); + ffi::CGReleaseDisplayFadeReservation(fade_token); + } + } + } + + self.ivars().fullscreen.replace(fullscreen.clone()); + + fn toggle_fullscreen(window: &WinitWindow) { + // Window level must be restored from `CGShieldingWindowLevel() + // + 1` back to normal in order for `toggleFullScreen` to do + // anything + window.setLevel(ffi::kCGNormalWindowLevel as NSWindowLevel); + window.toggleFullScreen(None); + } + + match (old_fullscreen, fullscreen) { + (None, Some(fullscreen)) => { + // `toggleFullScreen` doesn't work if the `StyleMask` is none, so we + // set a normal style temporarily. The previous state will be + // restored in `WindowDelegate::window_did_exit_fullscreen`. + let curr_mask = self.window().styleMask(); + let required = NSWindowStyleMask::Titled | NSWindowStyleMask::Resizable; + if !curr_mask.contains(required) { + self.set_style_mask(required); + self.ivars().saved_style.set(Some(curr_mask)); + } + + // In borderless games, we want to disable the dock and menu bar + // by setting the presentation options. We do this here rather than in + // `window:willUseFullScreenPresentationOptions` because for some reason + // the menu bar remains interactable despite being hidden. + if self.is_borderless_game() && matches!(fullscreen, Fullscreen::Borderless(_)) { + let presentation_options = NSApplicationPresentationOptions::NSApplicationPresentationHideDock + | NSApplicationPresentationOptions::NSApplicationPresentationHideMenuBar; + app.setPresentationOptions(presentation_options); + } + + toggle_fullscreen(self.window()); + }, + (Some(Fullscreen::Borderless(_)), None) => { + // State is restored by `window_did_exit_fullscreen` + toggle_fullscreen(self.window()); + }, + (Some(Fullscreen::Exclusive(ref video_mode)), None) => { + restore_and_release_display(&video_mode.monitor()); + toggle_fullscreen(self.window()); + }, + (Some(Fullscreen::Borderless(_)), Some(Fullscreen::Exclusive(_))) => { + // If we're already in fullscreen mode, calling + // `CGDisplayCapture` will place the shielding window on top of + // our window, which results in a black display and is not what + // we want. So, we must place our window on top of the shielding + // window. Unfortunately, this also makes our window be on top + // of the menu bar, and this looks broken, so we must make sure + // that the menu bar is disabled. This is done in the window + // delegate in `window:willUseFullScreenPresentationOptions:`. + self.ivars().save_presentation_opts.set(Some(app.presentationOptions())); + + let presentation_options = + NSApplicationPresentationOptions::NSApplicationPresentationFullScreen + | NSApplicationPresentationOptions::NSApplicationPresentationHideDock + | NSApplicationPresentationOptions::NSApplicationPresentationHideMenuBar; + app.setPresentationOptions(presentation_options); + + let window_level = unsafe { ffi::CGShieldingWindowLevel() } as NSWindowLevel + 1; + self.window().setLevel(window_level); + }, + (Some(Fullscreen::Exclusive(ref video_mode)), Some(Fullscreen::Borderless(_))) => { + let presentation_options = self.ivars().save_presentation_opts.get().unwrap_or( + NSApplicationPresentationOptions::NSApplicationPresentationFullScreen + | NSApplicationPresentationOptions::NSApplicationPresentationAutoHideDock + | NSApplicationPresentationOptions::NSApplicationPresentationAutoHideMenuBar + ); + app.setPresentationOptions(presentation_options); + + restore_and_release_display(&video_mode.monitor()); + + // Restore the normal window level following the Borderless fullscreen + // `CGShieldingWindowLevel() + 1` hack. + self.window().setLevel(ffi::kCGNormalWindowLevel as NSWindowLevel); + }, + _ => {}, + }; + } + + #[inline] + pub fn set_decorations(&self, decorations: bool) { + if decorations == self.ivars().decorations.get() { + return; + } + + self.ivars().decorations.set(decorations); + + let fullscreen = self.ivars().fullscreen.borrow().is_some(); + let resizable = self.ivars().resizable.get(); + + // If we're in fullscreen mode, we wait to apply decoration changes + // until we're in `window_did_exit_fullscreen`. + if fullscreen { + return; + } + + let new_mask = { + let mut new_mask = if decorations { + NSWindowStyleMask::Closable + | NSWindowStyleMask::Miniaturizable + | NSWindowStyleMask::Resizable + | NSWindowStyleMask::Titled + } else { + NSWindowStyleMask::Borderless | NSWindowStyleMask::Resizable + }; + if !resizable { + new_mask &= !NSWindowStyleMask::Resizable; + } + new_mask + }; + self.set_style_mask(new_mask); + } + + #[inline] + pub fn is_decorated(&self) -> bool { + self.ivars().decorations.get() + } + + #[inline] + pub fn set_window_level(&self, level: WindowLevel) { + let level = match level { + WindowLevel::AlwaysOnTop => ffi::kCGFloatingWindowLevel as NSWindowLevel, + WindowLevel::AlwaysOnBottom => (ffi::kCGNormalWindowLevel - 1) as NSWindowLevel, + WindowLevel::Normal => ffi::kCGNormalWindowLevel as NSWindowLevel, + }; + self.window().setLevel(level); + } + + #[inline] + pub fn set_window_icon(&self, _icon: Option<Icon>) { + // macOS doesn't have window icons. Though, there is + // `setRepresentedFilename`, but that's semantically distinct and should + // only be used when the window is in some way representing a specific + // file/directory. For instance, Terminal.app uses this for the CWD. + // Anyway, that should eventually be implemented as + // `WindowAttributesExt::with_represented_file` or something, and doesn't + // have anything to do with `set_window_icon`. + // https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/WinPanel/Tasks/SettingWindowTitle.html + } + + #[inline] + pub fn set_ime_cursor_area(&self, spot: Position, size: Size) { + let scale_factor = self.scale_factor(); + let logical_spot = spot.to_logical(scale_factor); + let logical_spot = NSPoint::new(logical_spot.x, logical_spot.y); + + let size = size.to_logical(scale_factor); + let size = NSSize::new(size.width, size.height); + + self.view().set_ime_cursor_area(logical_spot, size); + } + + #[inline] + pub fn set_ime_allowed(&self, allowed: bool) { + self.view().set_ime_allowed(allowed); + } + + #[inline] + pub fn set_ime_purpose(&self, _purpose: ImePurpose) {} + + #[inline] + pub fn focus_window(&self) { + let mtm = MainThreadMarker::from(self); + let is_minimized = self.window().isMiniaturized(); + let is_visible = self.window().isVisible(); + + if !is_minimized && is_visible { + #[allow(deprecated)] + NSApplication::sharedApplication(mtm).activateIgnoringOtherApps(true); + self.window().makeKeyAndOrderFront(None); + } + } + + #[inline] + pub fn request_user_attention(&self, request_type: Option<UserAttentionType>) { + let mtm = MainThreadMarker::from(self); + let ns_request_type = request_type.map(|ty| match ty { + UserAttentionType::Critical => NSRequestUserAttentionType::NSCriticalRequest, + UserAttentionType::Informational => NSRequestUserAttentionType::NSInformationalRequest, + }); + if let Some(ty) = ns_request_type { + NSApplication::sharedApplication(mtm).requestUserAttention(ty); + } + } + + #[inline] + // Allow directly accessing the current monitor internally without unwrapping. + pub(crate) fn current_monitor_inner(&self) -> Option<MonitorHandle> { + let display_id = get_display_id(&*self.window().screen()?); + if let Some(monitor) = MonitorHandle::new(display_id) { + Some(monitor) + } else { + // NOTE: Display ID was just fetched from live NSScreen, but can still result in `None` + // with certain Thunderbolt docked monitors. + warn!(display_id, "got screen with invalid display ID"); + None + } + } + + #[inline] + pub fn current_monitor(&self) -> Option<MonitorHandle> { + self.current_monitor_inner() + } + + #[inline] + pub fn available_monitors(&self) -> VecDeque<MonitorHandle> { + monitor::available_monitors() + } + + #[inline] + pub fn primary_monitor(&self) -> Option<MonitorHandle> { + let monitor = monitor::primary_monitor(); + Some(monitor) + } + + #[cfg(feature = "rwh_04")] + #[inline] + pub fn raw_window_handle_rwh_04(&self) -> rwh_04::RawWindowHandle { + let mut window_handle = rwh_04::AppKitHandle::empty(); + window_handle.ns_window = self.window() as *const WinitWindow as *mut _; + window_handle.ns_view = Retained::as_ptr(&self.view()) as *mut _; + rwh_04::RawWindowHandle::AppKit(window_handle) + } + + #[cfg(feature = "rwh_05")] + #[inline] + pub fn raw_window_handle_rwh_05(&self) -> rwh_05::RawWindowHandle { + let mut window_handle = rwh_05::AppKitWindowHandle::empty(); + window_handle.ns_window = self.window() as *const WinitWindow as *mut _; + window_handle.ns_view = Retained::as_ptr(&self.view()) as *mut _; + rwh_05::RawWindowHandle::AppKit(window_handle) + } + + #[cfg(feature = "rwh_05")] + #[inline] + pub fn raw_display_handle_rwh_05(&self) -> rwh_05::RawDisplayHandle { + rwh_05::RawDisplayHandle::AppKit(rwh_05::AppKitDisplayHandle::empty()) + } + + #[cfg(feature = "rwh_06")] + #[inline] + pub fn raw_window_handle_rwh_06(&self) -> rwh_06::RawWindowHandle { + let window_handle = rwh_06::AppKitWindowHandle::new({ + let ptr = Retained::as_ptr(&self.view()) as *mut _; + std::ptr::NonNull::new(ptr).expect("Retained<T> should never be null") + }); + rwh_06::RawWindowHandle::AppKit(window_handle) + } + + fn toggle_style_mask(&self, mask: NSWindowStyleMask, on: bool) { + let current_style_mask = self.window().styleMask(); + if on { + self.set_style_mask(current_style_mask | mask); + } else { + self.set_style_mask(current_style_mask & !mask); + } + } + + #[inline] + pub fn has_focus(&self) -> bool { + self.window().isKeyWindow() + } + + pub fn theme(&self) -> Option<Theme> { + unsafe { self.window().appearance() } + .map(|appearance| appearance_to_theme(&appearance)) + .or_else(|| { + let mtm = MainThreadMarker::from(self); + let app = NSApplication::sharedApplication(mtm); + + if app.respondsToSelector(sel!(effectiveAppearance)) { + Some(super::window_delegate::appearance_to_theme(&app.effectiveAppearance())) + } else { + Some(Theme::Light) + } + }) + } + + pub fn set_theme(&self, theme: Option<Theme>) { + unsafe { self.window().setAppearance(theme_to_appearance(theme).as_deref()) }; + } + + #[inline] + pub fn set_content_protected(&self, protected: bool) { + self.window().setSharingType(if protected { + NSWindowSharingType::NSWindowSharingNone + } else { + NSWindowSharingType::NSWindowSharingReadOnly + }) + } + + pub fn title(&self) -> String { + self.window().title().to_string() + } + + pub fn reset_dead_keys(&self) { + // (Artur) I couldn't find a way to implement this. + } +} + +fn restore_and_release_display(monitor: &MonitorHandle) { + let available_monitors = monitor::available_monitors(); + if available_monitors.contains(monitor) { + unsafe { + ffi::CGRestorePermanentDisplayConfiguration(); + assert_eq!(ffi::CGDisplayRelease(monitor.native_identifier()), ffi::kCGErrorSuccess); + }; + } else { + warn!( + monitor = monitor.name(), + "Tried to restore exclusive fullscreen on a monitor that is no longer available" + ); + } +} + +impl WindowExtMacOS for WindowDelegate { + #[inline] + fn simple_fullscreen(&self) -> bool { + self.ivars().is_simple_fullscreen.get() + } + + #[inline] + fn set_simple_fullscreen(&self, fullscreen: bool) -> bool { + let mtm = MainThreadMarker::from(self); + + let app = NSApplication::sharedApplication(mtm); + let is_native_fullscreen = self.ivars().fullscreen.borrow().is_some(); + let is_simple_fullscreen = self.ivars().is_simple_fullscreen.get(); + + // Do nothing if native fullscreen is active. + if is_native_fullscreen + || (fullscreen && is_simple_fullscreen) + || (!fullscreen && !is_simple_fullscreen) + { + return false; + } + + if fullscreen { + // Remember the original window's settings + // Exclude title bar + self.ivars() + .standard_frame + .set(Some(self.window().contentRectForFrameRect(self.window().frame()))); + self.ivars().saved_style.set(Some(self.window().styleMask())); + self.ivars().save_presentation_opts.set(Some(app.presentationOptions())); + + // Tell our window's state that we're in fullscreen + self.ivars().is_simple_fullscreen.set(true); + + // Simulate pre-Lion fullscreen by hiding the dock and menu bar + let presentation_options = if self.is_borderless_game() { + NSApplicationPresentationOptions::NSApplicationPresentationHideDock + | NSApplicationPresentationOptions::NSApplicationPresentationHideMenuBar + } else { + NSApplicationPresentationOptions::NSApplicationPresentationAutoHideDock + | NSApplicationPresentationOptions::NSApplicationPresentationAutoHideMenuBar + }; + app.setPresentationOptions(presentation_options); + + // Hide the titlebar + self.toggle_style_mask(NSWindowStyleMask::Titled, false); + + // Set the window frame to the screen frame size + let screen = self.window().screen().expect("expected screen to be available"); + self.window().setFrame_display(screen.frame(), true); + + // Fullscreen windows can't be resized, minimized, or moved + self.toggle_style_mask(NSWindowStyleMask::Miniaturizable, false); + self.toggle_style_mask(NSWindowStyleMask::Resizable, false); + self.window().setMovable(false); + } else { + let new_mask = self.saved_style(); + self.ivars().is_simple_fullscreen.set(false); + + let save_presentation_opts = self.ivars().save_presentation_opts.get(); + let frame = self.ivars().standard_frame.get().unwrap_or(DEFAULT_STANDARD_FRAME); + + if let Some(presentation_opts) = save_presentation_opts { + app.setPresentationOptions(presentation_opts); + } + + self.window().setFrame_display(frame, true); + self.window().setMovable(true); + self.set_style_mask(new_mask); + } + + true + } + + #[inline] + fn has_shadow(&self) -> bool { + self.window().hasShadow() + } + + #[inline] + fn set_has_shadow(&self, has_shadow: bool) { + self.window().setHasShadow(has_shadow) + } + + #[inline] + fn set_tabbing_identifier(&self, identifier: &str) { + self.window().setTabbingIdentifier(&NSString::from_str(identifier)) + } + + #[inline] + fn tabbing_identifier(&self) -> String { + self.window().tabbingIdentifier().to_string() + } + + #[inline] + fn select_next_tab(&self) { + self.window().selectNextTab(None) + } + + #[inline] + fn select_previous_tab(&self) { + unsafe { self.window().selectPreviousTab(None) } + } + + #[inline] + fn select_tab_at_index(&self, index: usize) { + if let Some(group) = self.window().tabGroup() { + if let Some(windows) = unsafe { self.window().tabbedWindows() } { + if index < windows.len() { + group.setSelectedWindow(Some(&windows[index])); + } + } + } + } + + #[inline] + fn num_tabs(&self) -> usize { + unsafe { self.window().tabbedWindows() }.map(|windows| windows.len()).unwrap_or(1) + } + + fn is_document_edited(&self) -> bool { + self.window().isDocumentEdited() + } + + fn set_document_edited(&self, edited: bool) { + self.window().setDocumentEdited(edited) + } + + fn set_option_as_alt(&self, option_as_alt: OptionAsAlt) { + self.view().set_option_as_alt(option_as_alt); + } + + fn option_as_alt(&self) -> OptionAsAlt { + self.view().option_as_alt() + } + + fn set_borderless_game(&self, borderless_game: bool) { + self.ivars().is_borderless_game.set(borderless_game); + } + + fn is_borderless_game(&self) -> bool { + self.ivars().is_borderless_game.get() + } +} + +const DEFAULT_STANDARD_FRAME: NSRect = + NSRect::new(NSPoint::new(50.0, 50.0), NSSize::new(800.0, 600.0)); + +fn dark_appearance_name() -> &'static NSString { + // Don't use the static `NSAppearanceNameDarkAqua` to allow linking on macOS < 10.14 + ns_string!("NSAppearanceNameDarkAqua") +} + +pub fn appearance_to_theme(appearance: &NSAppearance) -> Theme { + let best_match = appearance.bestMatchFromAppearancesWithNames(&NSArray::from_id_slice(&[ + unsafe { NSAppearanceNameAqua.copy() }, + dark_appearance_name().copy(), + ])); + if let Some(best_match) = best_match { + if *best_match == *dark_appearance_name() { + Theme::Dark + } else { + Theme::Light + } + } else { + warn!(?appearance, "failed to determine the theme of the appearance"); + // Default to light in this case + Theme::Light + } +} + +fn theme_to_appearance(theme: Option<Theme>) -> Option<Retained<NSAppearance>> { + let appearance = match theme? { + Theme::Light => unsafe { NSAppearance::appearanceNamed(NSAppearanceNameAqua) }, + Theme::Dark => NSAppearance::appearanceNamed(dark_appearance_name()), + }; + if let Some(appearance) = appearance { + Some(appearance) + } else { + warn!(?theme, "could not find appearance for theme"); + // Assume system appearance in this case + None + } +} diff --git a/app/vendor/rune/vendor/winit/src/platform_impl/mod.rs b/app/vendor/rune/vendor/winit/src/platform_impl/mod.rs new file mode 100644 index 0000000..3bfce68 --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/platform_impl/mod.rs @@ -0,0 +1,78 @@ +use crate::monitor::{MonitorHandle as RootMonitorHandle, VideoModeHandle as RootVideoModeHandle}; +use crate::window::Fullscreen as RootFullscreen; + +#[cfg(android_platform)] +mod android; +#[cfg(ios_platform)] +mod ios; +#[cfg(any(x11_platform, wayland_platform))] +mod linux; +#[cfg(macos_platform)] +mod macos; +#[cfg(orbital_platform)] +mod orbital; +#[cfg(web_platform)] +mod web; +#[cfg(windows_platform)] +mod windows; + +#[cfg(android_platform)] +use android as platform; +#[cfg(ios_platform)] +use ios as platform; +#[cfg(any(x11_platform, wayland_platform))] +use linux as platform; +#[cfg(macos_platform)] +use macos as platform; +#[cfg(orbital_platform)] +use orbital as platform; +#[cfg(web_platform)] +use web as platform; +#[cfg(windows_platform)] +use windows as platform; + +pub use self::platform::*; + +/// Helper for converting between platform-specific and generic +/// [`VideoModeHandle`]/[`MonitorHandle`] +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) enum Fullscreen { + Exclusive(VideoModeHandle), + Borderless(Option<MonitorHandle>), +} + +impl From<RootFullscreen> for Fullscreen { + fn from(f: RootFullscreen) -> Self { + match f { + RootFullscreen::Exclusive(mode) => Self::Exclusive(mode.video_mode), + RootFullscreen::Borderless(Some(handle)) => Self::Borderless(Some(handle.inner)), + RootFullscreen::Borderless(None) => Self::Borderless(None), + } + } +} + +impl From<Fullscreen> for RootFullscreen { + fn from(f: Fullscreen) -> Self { + match f { + Fullscreen::Exclusive(video_mode) => { + Self::Exclusive(RootVideoModeHandle { video_mode }) + }, + Fullscreen::Borderless(Some(inner)) => { + Self::Borderless(Some(RootMonitorHandle { inner })) + }, + Fullscreen::Borderless(None) => Self::Borderless(None), + } + } +} + +#[cfg(all( + not(ios_platform), + not(windows_platform), + not(macos_platform), + not(android_platform), + not(x11_platform), + not(wayland_platform), + not(web_platform), + not(orbital_platform), +))] +compile_error!("The platform you're compiling for is not supported by winit"); diff --git a/app/vendor/rune/vendor/winit/src/platform_impl/orbital/event_loop.rs b/app/vendor/rune/vendor/winit/src/platform_impl/orbital/event_loop.rs new file mode 100644 index 0000000..91f76e7 --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/platform_impl/orbital/event_loop.rs @@ -0,0 +1,829 @@ +use std::cell::Cell; +use std::collections::VecDeque; +use std::marker::PhantomData; +use std::sync::{mpsc, Arc, Mutex}; +use std::time::Instant; +use std::{mem, slice}; + +use bitflags::bitflags; +use orbclient::{ + ButtonEvent, EventOption, FocusEvent, HoverEvent, KeyEvent, MouseEvent, MouseRelativeEvent, + MoveEvent, QuitEvent, ResizeEvent, ScrollEvent, TextInputEvent, +}; +use smol_str::SmolStr; + +use crate::error::EventLoopError; +use crate::event::{self, Ime, Modifiers, StartCause}; +use crate::event_loop::{self, ControlFlow, DeviceEvents}; +use crate::keyboard::{ + Key, KeyCode, KeyLocation, ModifiersKeys, ModifiersState, NamedKey, NativeKey, NativeKeyCode, + PhysicalKey, +}; +use crate::window::{ + CustomCursor as RootCustomCursor, CustomCursorSource, Theme, WindowId as RootWindowId, +}; + +use super::{ + DeviceId, KeyEventExtra, MonitorHandle, OsError, PlatformSpecificEventLoopAttributes, + RedoxSocket, TimeSocket, WindowId, WindowProperties, +}; + +fn convert_scancode(scancode: u8) -> (PhysicalKey, Option<NamedKey>) { + // Key constants from https://docs.rs/orbclient/latest/orbclient/event/index.html + let (key_code, named_key_opt) = match scancode { + orbclient::K_A => (KeyCode::KeyA, None), + orbclient::K_B => (KeyCode::KeyB, None), + orbclient::K_C => (KeyCode::KeyC, None), + orbclient::K_D => (KeyCode::KeyD, None), + orbclient::K_E => (KeyCode::KeyE, None), + orbclient::K_F => (KeyCode::KeyF, None), + orbclient::K_G => (KeyCode::KeyG, None), + orbclient::K_H => (KeyCode::KeyH, None), + orbclient::K_I => (KeyCode::KeyI, None), + orbclient::K_J => (KeyCode::KeyJ, None), + orbclient::K_K => (KeyCode::KeyK, None), + orbclient::K_L => (KeyCode::KeyL, None), + orbclient::K_M => (KeyCode::KeyM, None), + orbclient::K_N => (KeyCode::KeyN, None), + orbclient::K_O => (KeyCode::KeyO, None), + orbclient::K_P => (KeyCode::KeyP, None), + orbclient::K_Q => (KeyCode::KeyQ, None), + orbclient::K_R => (KeyCode::KeyR, None), + orbclient::K_S => (KeyCode::KeyS, None), + orbclient::K_T => (KeyCode::KeyT, None), + orbclient::K_U => (KeyCode::KeyU, None), + orbclient::K_V => (KeyCode::KeyV, None), + orbclient::K_W => (KeyCode::KeyW, None), + orbclient::K_X => (KeyCode::KeyX, None), + orbclient::K_Y => (KeyCode::KeyY, None), + orbclient::K_Z => (KeyCode::KeyZ, None), + orbclient::K_0 => (KeyCode::Digit0, None), + orbclient::K_1 => (KeyCode::Digit1, None), + orbclient::K_2 => (KeyCode::Digit2, None), + orbclient::K_3 => (KeyCode::Digit3, None), + orbclient::K_4 => (KeyCode::Digit4, None), + orbclient::K_5 => (KeyCode::Digit5, None), + orbclient::K_6 => (KeyCode::Digit6, None), + orbclient::K_7 => (KeyCode::Digit7, None), + orbclient::K_8 => (KeyCode::Digit8, None), + orbclient::K_9 => (KeyCode::Digit9, None), + + orbclient::K_ALT => (KeyCode::AltLeft, Some(NamedKey::Alt)), + orbclient::K_ALT_GR => (KeyCode::AltRight, Some(NamedKey::AltGraph)), + orbclient::K_BACKSLASH => (KeyCode::Backslash, None), + orbclient::K_BKSP => (KeyCode::Backspace, Some(NamedKey::Backspace)), + orbclient::K_BRACE_CLOSE => (KeyCode::BracketRight, None), + orbclient::K_BRACE_OPEN => (KeyCode::BracketLeft, None), + orbclient::K_CAPS => (KeyCode::CapsLock, Some(NamedKey::CapsLock)), + orbclient::K_COMMA => (KeyCode::Comma, None), + orbclient::K_CTRL => (KeyCode::ControlLeft, Some(NamedKey::Control)), + orbclient::K_DEL => (KeyCode::Delete, Some(NamedKey::Delete)), + orbclient::K_DOWN => (KeyCode::ArrowDown, Some(NamedKey::ArrowDown)), + orbclient::K_END => (KeyCode::End, Some(NamedKey::End)), + orbclient::K_ENTER => (KeyCode::Enter, Some(NamedKey::Enter)), + orbclient::K_EQUALS => (KeyCode::Equal, None), + orbclient::K_ESC => (KeyCode::Escape, Some(NamedKey::Escape)), + orbclient::K_F1 => (KeyCode::F1, Some(NamedKey::F1)), + orbclient::K_F2 => (KeyCode::F2, Some(NamedKey::F2)), + orbclient::K_F3 => (KeyCode::F3, Some(NamedKey::F3)), + orbclient::K_F4 => (KeyCode::F4, Some(NamedKey::F4)), + orbclient::K_F5 => (KeyCode::F5, Some(NamedKey::F5)), + orbclient::K_F6 => (KeyCode::F6, Some(NamedKey::F6)), + orbclient::K_F7 => (KeyCode::F7, Some(NamedKey::F7)), + orbclient::K_F8 => (KeyCode::F8, Some(NamedKey::F8)), + orbclient::K_F9 => (KeyCode::F9, Some(NamedKey::F9)), + orbclient::K_F10 => (KeyCode::F10, Some(NamedKey::F10)), + orbclient::K_F11 => (KeyCode::F11, Some(NamedKey::F11)), + orbclient::K_F12 => (KeyCode::F12, Some(NamedKey::F12)), + orbclient::K_HOME => (KeyCode::Home, Some(NamedKey::Home)), + orbclient::K_LEFT => (KeyCode::ArrowLeft, Some(NamedKey::ArrowLeft)), + orbclient::K_LEFT_SHIFT => (KeyCode::ShiftLeft, Some(NamedKey::Shift)), + orbclient::K_MINUS => (KeyCode::Minus, None), + orbclient::K_NUM_0 => (KeyCode::Numpad0, None), + orbclient::K_NUM_1 => (KeyCode::Numpad1, None), + orbclient::K_NUM_2 => (KeyCode::Numpad2, None), + orbclient::K_NUM_3 => (KeyCode::Numpad3, None), + orbclient::K_NUM_4 => (KeyCode::Numpad4, None), + orbclient::K_NUM_5 => (KeyCode::Numpad5, None), + orbclient::K_NUM_6 => (KeyCode::Numpad6, None), + orbclient::K_NUM_7 => (KeyCode::Numpad7, None), + orbclient::K_NUM_8 => (KeyCode::Numpad8, None), + orbclient::K_NUM_9 => (KeyCode::Numpad9, None), + orbclient::K_PERIOD => (KeyCode::Period, None), + orbclient::K_PGDN => (KeyCode::PageDown, Some(NamedKey::PageDown)), + orbclient::K_PGUP => (KeyCode::PageUp, Some(NamedKey::PageUp)), + orbclient::K_QUOTE => (KeyCode::Quote, None), + orbclient::K_RIGHT => (KeyCode::ArrowRight, Some(NamedKey::ArrowRight)), + orbclient::K_RIGHT_SHIFT => (KeyCode::ShiftRight, Some(NamedKey::Shift)), + orbclient::K_SEMICOLON => (KeyCode::Semicolon, None), + orbclient::K_SLASH => (KeyCode::Slash, None), + orbclient::K_SPACE => (KeyCode::Space, Some(NamedKey::Space)), + orbclient::K_SUPER => (KeyCode::SuperLeft, Some(NamedKey::Super)), + orbclient::K_TAB => (KeyCode::Tab, Some(NamedKey::Tab)), + orbclient::K_TICK => (KeyCode::Backquote, None), + orbclient::K_UP => (KeyCode::ArrowUp, Some(NamedKey::ArrowUp)), + orbclient::K_VOLUME_DOWN => (KeyCode::AudioVolumeDown, Some(NamedKey::AudioVolumeDown)), + orbclient::K_VOLUME_TOGGLE => (KeyCode::AudioVolumeMute, Some(NamedKey::AudioVolumeMute)), + orbclient::K_VOLUME_UP => (KeyCode::AudioVolumeUp, Some(NamedKey::AudioVolumeUp)), + + _ => return (PhysicalKey::Unidentified(NativeKeyCode::Unidentified), None), + }; + (PhysicalKey::Code(key_code), named_key_opt) +} + +fn element_state(pressed: bool) -> event::ElementState { + if pressed { + event::ElementState::Pressed + } else { + event::ElementState::Released + } +} + +bitflags! { + #[derive(Default, Debug, Clone, Copy, PartialEq, Eq, Hash)] + struct KeyboardModifierState: u8 { + const LSHIFT = 1 << 0; + const RSHIFT = 1 << 1; + const LCTRL = 1 << 2; + const RCTRL = 1 << 3; + const LALT = 1 << 4; + const RALT = 1 << 5; + const LSUPER = 1 << 6; + const RSUPER = 1 << 7; + } +} + +bitflags! { + #[derive(Default, Debug, Clone, Copy, PartialEq, Eq, Hash)] + struct MouseButtonState: u8 { + const LEFT = 1 << 0; + const MIDDLE = 1 << 1; + const RIGHT = 1 << 2; + } +} + +#[derive(Default)] +struct EventState { + keyboard: KeyboardModifierState, + mouse: MouseButtonState, + resize_opt: Option<(u32, u32)>, +} + +impl EventState { + fn character_all_modifiers(&self, character: char) -> char { + // Modify character if Ctrl is pressed + #[allow(clippy::collapsible_if)] + if self.keyboard.contains(KeyboardModifierState::LCTRL) + || self.keyboard.contains(KeyboardModifierState::RCTRL) + { + if character.is_ascii_lowercase() { + return ((character as u8 - b'a') + 1) as char; + } + // TODO: more control key variants? + } + + // Return character as-is if no special handling required + character + } + + fn key(&mut self, key: PhysicalKey, pressed: bool) { + let code = match key { + PhysicalKey::Code(code) => code, + _ => return, + }; + + match code { + KeyCode::ShiftLeft => self.keyboard.set(KeyboardModifierState::LSHIFT, pressed), + KeyCode::ShiftRight => self.keyboard.set(KeyboardModifierState::RSHIFT, pressed), + KeyCode::ControlLeft => self.keyboard.set(KeyboardModifierState::LCTRL, pressed), + KeyCode::ControlRight => self.keyboard.set(KeyboardModifierState::RCTRL, pressed), + KeyCode::AltLeft => self.keyboard.set(KeyboardModifierState::LALT, pressed), + KeyCode::AltRight => self.keyboard.set(KeyboardModifierState::RALT, pressed), + KeyCode::SuperLeft => self.keyboard.set(KeyboardModifierState::LSUPER, pressed), + KeyCode::SuperRight => self.keyboard.set(KeyboardModifierState::RSUPER, pressed), + _ => (), + } + } + + fn mouse( + &mut self, + left: bool, + middle: bool, + right: bool, + ) -> Option<(event::MouseButton, event::ElementState)> { + if self.mouse.contains(MouseButtonState::LEFT) != left { + self.mouse.set(MouseButtonState::LEFT, left); + return Some((event::MouseButton::Left, element_state(left))); + } + + if self.mouse.contains(MouseButtonState::MIDDLE) != middle { + self.mouse.set(MouseButtonState::MIDDLE, middle); + return Some((event::MouseButton::Middle, element_state(middle))); + } + + if self.mouse.contains(MouseButtonState::RIGHT) != right { + self.mouse.set(MouseButtonState::RIGHT, right); + return Some((event::MouseButton::Right, element_state(right))); + } + + None + } + + fn modifiers(&self) -> Modifiers { + let mut state = ModifiersState::empty(); + let mut pressed_mods = ModifiersKeys::empty(); + + if self.keyboard.intersects(KeyboardModifierState::LSHIFT | KeyboardModifierState::RSHIFT) { + state |= ModifiersState::SHIFT; + } + + pressed_mods + .set(ModifiersKeys::LSHIFT, self.keyboard.contains(KeyboardModifierState::LSHIFT)); + pressed_mods + .set(ModifiersKeys::RSHIFT, self.keyboard.contains(KeyboardModifierState::RSHIFT)); + + if self.keyboard.intersects(KeyboardModifierState::LCTRL | KeyboardModifierState::RCTRL) { + state |= ModifiersState::CONTROL; + } + + pressed_mods + .set(ModifiersKeys::LCONTROL, self.keyboard.contains(KeyboardModifierState::LCTRL)); + pressed_mods + .set(ModifiersKeys::RCONTROL, self.keyboard.contains(KeyboardModifierState::RCTRL)); + + if self.keyboard.intersects(KeyboardModifierState::LALT | KeyboardModifierState::RALT) { + state |= ModifiersState::ALT; + } + + pressed_mods.set(ModifiersKeys::LALT, self.keyboard.contains(KeyboardModifierState::LALT)); + pressed_mods.set(ModifiersKeys::RALT, self.keyboard.contains(KeyboardModifierState::RALT)); + + if self.keyboard.intersects(KeyboardModifierState::LSUPER | KeyboardModifierState::RSUPER) { + state |= ModifiersState::SUPER + } + + pressed_mods + .set(ModifiersKeys::LSUPER, self.keyboard.contains(KeyboardModifierState::LSUPER)); + pressed_mods + .set(ModifiersKeys::RSUPER, self.keyboard.contains(KeyboardModifierState::RSUPER)); + + Modifiers { state, pressed_mods } + } +} + +pub struct EventLoop<T> { + windows: Vec<(Arc<RedoxSocket>, EventState)>, + window_target: event_loop::ActiveEventLoop, + user_events_sender: mpsc::Sender<T>, + user_events_receiver: mpsc::Receiver<T>, +} + +impl<T: 'static> EventLoop<T> { + pub(crate) fn new(_: &PlatformSpecificEventLoopAttributes) -> Result<Self, EventLoopError> { + let (user_events_sender, user_events_receiver) = mpsc::channel(); + + let event_socket = Arc::new( + RedoxSocket::event() + .map_err(OsError::new) + .map_err(|error| EventLoopError::Os(os_error!(error)))?, + ); + + let wake_socket = Arc::new( + TimeSocket::open() + .map_err(OsError::new) + .map_err(|error| EventLoopError::Os(os_error!(error)))?, + ); + + event_socket + .write(&syscall::Event { + id: wake_socket.0.fd, + flags: syscall::EventFlags::EVENT_READ, + data: wake_socket.0.fd, + }) + .map_err(OsError::new) + .map_err(|error| EventLoopError::Os(os_error!(error)))?; + + Ok(Self { + windows: Vec::new(), + window_target: event_loop::ActiveEventLoop { + p: ActiveEventLoop { + control_flow: Cell::new(ControlFlow::default()), + exit: Cell::new(false), + creates: Mutex::new(VecDeque::new()), + redraws: Arc::new(Mutex::new(VecDeque::new())), + destroys: Arc::new(Mutex::new(VecDeque::new())), + event_socket, + wake_socket, + }, + _marker: PhantomData, + }, + user_events_sender, + user_events_receiver, + }) + } + + fn process_event<F>( + window_id: WindowId, + event_option: EventOption, + event_state: &mut EventState, + mut event_handler: F, + ) where + F: FnMut(event::Event<T>), + { + match event_option { + EventOption::Key(KeyEvent { character, scancode, pressed }) => { + // Convert scancode + let (physical_key, named_key_opt) = convert_scancode(scancode); + + // Get previous modifiers and update modifiers based on physical key + let modifiers_before = event_state.keyboard; + event_state.key(physical_key, pressed); + + // Default to unidentified key with no text + let mut logical_key = Key::Unidentified(NativeKey::Unidentified); + let mut key_without_modifiers = logical_key.clone(); + let mut text = None; + let mut text_with_all_modifiers = None; + + // Set key and text based on character + if character != '\0' { + let mut tmp = [0u8; 4]; + let character_str = character.encode_utf8(&mut tmp); + // The key with Shift and Caps Lock applied (but not Ctrl) + logical_key = Key::Character(character_str.into()); + // The key without Shift or Caps Lock applied + key_without_modifiers = + Key::Character(SmolStr::from_iter(character.to_lowercase())); + if pressed { + // The key with Shift and Caps Lock applied (but not Ctrl) + text = Some(character_str.into()); + // The key with Shift, Caps Lock, and Ctrl applied + let character_all_modifiers = + event_state.character_all_modifiers(character); + text_with_all_modifiers = + Some(character_all_modifiers.encode_utf8(&mut tmp).into()) + } + }; + + // Override key if a named key was found (this is to allow Enter to replace '\n') + if let Some(named_key) = named_key_opt { + logical_key = Key::Named(named_key); + key_without_modifiers = logical_key.clone(); + } + + event_handler(event::Event::WindowEvent { + window_id: RootWindowId(window_id), + event: event::WindowEvent::KeyboardInput { + device_id: event::DeviceId(DeviceId), + event: event::KeyEvent { + logical_key, + physical_key, + location: KeyLocation::Standard, + state: element_state(pressed), + repeat: false, + text, + platform_specific: KeyEventExtra { + key_without_modifiers, + text_with_all_modifiers, + }, + }, + is_synthetic: false, + }, + }); + + // If the state of the modifiers has changed, send the event. + if modifiers_before != event_state.keyboard { + event_handler(event::Event::WindowEvent { + window_id: RootWindowId(window_id), + event: event::WindowEvent::ModifiersChanged(event_state.modifiers()), + }) + } + }, + EventOption::TextInput(TextInputEvent { character }) => { + event_handler(event::Event::WindowEvent { + window_id: RootWindowId(window_id), + event: event::WindowEvent::Ime(Ime::Preedit("".into(), None)), + }); + event_handler(event::Event::WindowEvent { + window_id: RootWindowId(window_id), + event: event::WindowEvent::Ime(Ime::Commit(character.into())), + }); + }, + EventOption::Mouse(MouseEvent { x, y }) => { + event_handler(event::Event::WindowEvent { + window_id: RootWindowId(window_id), + event: event::WindowEvent::CursorMoved { + device_id: event::DeviceId(DeviceId), + position: (x, y).into(), + }, + }); + }, + EventOption::MouseRelative(MouseRelativeEvent { dx, dy }) => { + event_handler(event::Event::DeviceEvent { + device_id: event::DeviceId(DeviceId), + event: event::DeviceEvent::MouseMotion { delta: (dx as f64, dy as f64) }, + }); + }, + EventOption::Button(ButtonEvent { left, middle, right }) => { + while let Some((button, state)) = event_state.mouse(left, middle, right) { + event_handler(event::Event::WindowEvent { + window_id: RootWindowId(window_id), + event: event::WindowEvent::MouseInput { + device_id: event::DeviceId(DeviceId), + state, + button, + }, + }); + } + }, + EventOption::Scroll(ScrollEvent { x, y }) => { + event_handler(event::Event::WindowEvent { + window_id: RootWindowId(window_id), + event: event::WindowEvent::MouseWheel { + device_id: event::DeviceId(DeviceId), + delta: event::MouseScrollDelta::LineDelta(x as f32, y as f32), + phase: event::TouchPhase::Moved, + }, + }); + }, + EventOption::Quit(QuitEvent {}) => { + event_handler(event::Event::WindowEvent { + window_id: RootWindowId(window_id), + event: event::WindowEvent::CloseRequested, + }); + }, + EventOption::Focus(FocusEvent { focused }) => { + event_handler(event::Event::WindowEvent { + window_id: RootWindowId(window_id), + event: event::WindowEvent::Focused(focused), + }); + }, + EventOption::Move(MoveEvent { x, y }) => { + event_handler(event::Event::WindowEvent { + window_id: RootWindowId(window_id), + event: event::WindowEvent::Moved((x, y).into()), + }); + }, + EventOption::Resize(ResizeEvent { width, height }) => { + event_handler(event::Event::WindowEvent { + window_id: RootWindowId(window_id), + event: event::WindowEvent::Resized((width, height).into()), + }); + + // Acknowledge resize after event loop. + event_state.resize_opt = Some((width, height)); + }, + // TODO: Screen, Clipboard, Drop + EventOption::Hover(HoverEvent { entered }) => { + if entered { + event_handler(event::Event::WindowEvent { + window_id: RootWindowId(window_id), + event: event::WindowEvent::CursorEntered { + device_id: event::DeviceId(DeviceId), + }, + }); + } else { + event_handler(event::Event::WindowEvent { + window_id: RootWindowId(window_id), + event: event::WindowEvent::CursorLeft { + device_id: event::DeviceId(DeviceId), + }, + }); + } + }, + other => { + tracing::warn!("unhandled event: {:?}", other); + }, + } + } + + pub fn run<F>(mut self, mut event_handler_inner: F) -> Result<(), EventLoopError> + where + F: FnMut(event::Event<T>, &event_loop::ActiveEventLoop), + { + let mut event_handler = + move |event: event::Event<T>, window_target: &event_loop::ActiveEventLoop| { + event_handler_inner(event, window_target); + }; + + let mut start_cause = StartCause::Init; + + loop { + event_handler(event::Event::NewEvents(start_cause), &self.window_target); + + if start_cause == StartCause::Init { + event_handler(event::Event::Resumed, &self.window_target); + } + + // Handle window creates. + while let Some(window) = { + let mut creates = self.window_target.p.creates.lock().unwrap(); + creates.pop_front() + } { + let window_id = WindowId { fd: window.fd as u64 }; + + let mut buf: [u8; 4096] = [0; 4096]; + let path = window.fpath(&mut buf).expect("failed to read properties"); + let properties = WindowProperties::new(path); + + self.windows.push((window, EventState::default())); + + // Send resize event on create to indicate first size. + event_handler( + event::Event::WindowEvent { + window_id: RootWindowId(window_id), + event: event::WindowEvent::Resized((properties.w, properties.h).into()), + }, + &self.window_target, + ); + + // Send resize event on create to indicate first position. + event_handler( + event::Event::WindowEvent { + window_id: RootWindowId(window_id), + event: event::WindowEvent::Moved((properties.x, properties.y).into()), + }, + &self.window_target, + ); + } + + // Handle window destroys. + while let Some(destroy_id) = { + let mut destroys = self.window_target.p.destroys.lock().unwrap(); + destroys.pop_front() + } { + event_handler( + event::Event::WindowEvent { + window_id: RootWindowId(destroy_id), + event: event::WindowEvent::Destroyed, + }, + &self.window_target, + ); + + self.windows.retain(|(window, _event_state)| window.fd as u64 != destroy_id.fd); + } + + // Handle window events. + let mut i = 0; + // While loop is used here because the same window may be processed more than once. + while let Some((window, event_state)) = self.windows.get_mut(i) { + let window_id = WindowId { fd: window.fd as u64 }; + + let mut event_buf = [0u8; 16 * mem::size_of::<orbclient::Event>()]; + let count = + syscall::read(window.fd, &mut event_buf).expect("failed to read window events"); + // Safety: orbclient::Event is a packed struct designed to be transferred over a + // socket. + let events = unsafe { + slice::from_raw_parts( + event_buf.as_ptr() as *const orbclient::Event, + count / mem::size_of::<orbclient::Event>(), + ) + }; + + for orbital_event in events { + Self::process_event( + window_id, + orbital_event.to_option(), + event_state, + |event| event_handler(event, &self.window_target), + ); + } + + if count == event_buf.len() { + // If event buf was full, process same window again to ensure all events are + // drained. + continue; + } + + // Acknowledge the latest resize event. + if let Some((w, h)) = event_state.resize_opt.take() { + window + .write(format!("S,{w},{h}").as_bytes()) + .expect("failed to acknowledge resize"); + + // Require redraw after resize. + let mut redraws = self.window_target.p.redraws.lock().unwrap(); + if !redraws.contains(&window_id) { + redraws.push_back(window_id); + } + } + + // Move to next window. + i += 1; + } + + while let Ok(event) = self.user_events_receiver.try_recv() { + event_handler(event::Event::UserEvent(event), &self.window_target); + } + + // To avoid deadlocks the redraws lock is not held during event processing. + while let Some(window_id) = { + let mut redraws = self.window_target.p.redraws.lock().unwrap(); + redraws.pop_front() + } { + event_handler( + event::Event::WindowEvent { + window_id: RootWindowId(window_id), + event: event::WindowEvent::RedrawRequested, + }, + &self.window_target, + ); + } + + event_handler(event::Event::AboutToWait, &self.window_target); + + if self.window_target.p.exiting() { + break; + } + + let requested_resume = match self.window_target.p.control_flow() { + ControlFlow::Poll => { + start_cause = StartCause::Poll; + continue; + }, + ControlFlow::Wait => None, + ControlFlow::WaitUntil(instant) => Some(instant), + }; + + // Re-using wake socket caused extra wake events before because there were leftover + // timeouts, and then new timeouts were added each time a spurious timeout expired. + let timeout_socket = TimeSocket::open().unwrap(); + + self.window_target + .p + .event_socket + .write(&syscall::Event { + id: timeout_socket.0.fd, + flags: syscall::EventFlags::EVENT_READ, + data: 0, + }) + .unwrap(); + + let start = Instant::now(); + if let Some(instant) = requested_resume { + let mut time = timeout_socket.current_time().unwrap(); + + if let Some(duration) = instant.checked_duration_since(start) { + time.tv_sec += duration.as_secs() as i64; + time.tv_nsec += duration.subsec_nanos() as i32; + // Normalize timespec so tv_nsec is not greater than one second. + while time.tv_nsec >= 1_000_000_000 { + time.tv_sec += 1; + time.tv_nsec -= 1_000_000_000; + } + } + + timeout_socket.timeout(&time).unwrap(); + } + + // Wait for event if needed. + let mut event = syscall::Event::default(); + self.window_target.p.event_socket.read(&mut event).unwrap(); + + // TODO: handle spurious wakeups (redraw caused wakeup but redraw already handled) + match requested_resume { + Some(requested_resume) if event.id == timeout_socket.0.fd => { + // If the event is from the special timeout socket, report that resume + // time was reached. + start_cause = StartCause::ResumeTimeReached { start, requested_resume }; + }, + _ => { + // Normal window event or spurious timeout. + start_cause = StartCause::WaitCancelled { start, requested_resume }; + }, + } + } + + event_handler(event::Event::LoopExiting, &self.window_target); + + Ok(()) + } + + pub fn window_target(&self) -> &event_loop::ActiveEventLoop { + &self.window_target + } + + pub fn create_proxy(&self) -> EventLoopProxy<T> { + EventLoopProxy { + user_events_sender: self.user_events_sender.clone(), + wake_socket: self.window_target.p.wake_socket.clone(), + } + } +} + +pub struct EventLoopProxy<T: 'static> { + user_events_sender: mpsc::Sender<T>, + wake_socket: Arc<TimeSocket>, +} + +impl<T> EventLoopProxy<T> { + pub fn send_event(&self, event: T) -> Result<(), event_loop::EventLoopClosed<T>> { + self.user_events_sender + .send(event) + .map_err(|mpsc::SendError(x)| event_loop::EventLoopClosed(x))?; + + self.wake_socket.wake().unwrap(); + + Ok(()) + } +} + +impl<T> Clone for EventLoopProxy<T> { + fn clone(&self) -> Self { + Self { + user_events_sender: self.user_events_sender.clone(), + wake_socket: self.wake_socket.clone(), + } + } +} + +impl<T> Unpin for EventLoopProxy<T> {} + +pub struct ActiveEventLoop { + control_flow: Cell<ControlFlow>, + exit: Cell<bool>, + pub(super) creates: Mutex<VecDeque<Arc<RedoxSocket>>>, + pub(super) redraws: Arc<Mutex<VecDeque<WindowId>>>, + pub(super) destroys: Arc<Mutex<VecDeque<WindowId>>>, + pub(super) event_socket: Arc<RedoxSocket>, + pub(super) wake_socket: Arc<TimeSocket>, +} + +impl ActiveEventLoop { + pub fn create_custom_cursor(&self, source: CustomCursorSource) -> RootCustomCursor { + let _ = source.inner; + RootCustomCursor { inner: super::PlatformCustomCursor } + } + + pub fn primary_monitor(&self) -> Option<MonitorHandle> { + Some(MonitorHandle) + } + + pub fn available_monitors(&self) -> VecDeque<MonitorHandle> { + let mut v = VecDeque::with_capacity(1); + v.push_back(MonitorHandle); + v + } + + #[inline] + pub fn listen_device_events(&self, _allowed: DeviceEvents) {} + + #[cfg(feature = "rwh_05")] + #[inline] + pub fn raw_display_handle_rwh_05(&self) -> rwh_05::RawDisplayHandle { + rwh_05::RawDisplayHandle::Orbital(rwh_05::OrbitalDisplayHandle::empty()) + } + + #[inline] + pub fn system_theme(&self) -> Option<Theme> { + None + } + + #[cfg(feature = "rwh_06")] + #[inline] + pub fn raw_display_handle_rwh_06( + &self, + ) -> Result<rwh_06::RawDisplayHandle, rwh_06::HandleError> { + Ok(rwh_06::RawDisplayHandle::Orbital(rwh_06::OrbitalDisplayHandle::new())) + } + + pub fn set_control_flow(&self, control_flow: ControlFlow) { + self.control_flow.set(control_flow) + } + + pub fn control_flow(&self) -> ControlFlow { + self.control_flow.get() + } + + pub(crate) fn exit(&self) { + self.exit.set(true); + } + + pub(crate) fn exiting(&self) -> bool { + self.exit.get() + } + + pub(crate) fn owned_display_handle(&self) -> OwnedDisplayHandle { + OwnedDisplayHandle + } +} + +#[derive(Clone)] +pub(crate) struct OwnedDisplayHandle; + +impl OwnedDisplayHandle { + #[cfg(feature = "rwh_05")] + #[inline] + pub fn raw_display_handle_rwh_05(&self) -> rwh_05::RawDisplayHandle { + rwh_05::OrbitalDisplayHandle::empty().into() + } + + #[cfg(feature = "rwh_06")] + #[inline] + pub fn raw_display_handle_rwh_06( + &self, + ) -> Result<rwh_06::RawDisplayHandle, rwh_06::HandleError> { + Ok(rwh_06::OrbitalDisplayHandle::new().into()) + } +} diff --git a/app/vendor/rune/vendor/winit/src/platform_impl/orbital/mod.rs b/app/vendor/rune/vendor/winit/src/platform_impl/orbital/mod.rs new file mode 100644 index 0000000..2d15251 --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/platform_impl/orbital/mod.rs @@ -0,0 +1,255 @@ +#![cfg(target_os = "redox")] + +use std::fmt::{self, Display, Formatter}; +use std::str; +use std::sync::Arc; + +use smol_str::SmolStr; + +use crate::dpi::{PhysicalPosition, PhysicalSize}; +use crate::keyboard::Key; + +pub(crate) use self::event_loop::{ActiveEventLoop, EventLoop, EventLoopProxy, OwnedDisplayHandle}; +mod event_loop; + +pub use self::window::Window; +mod window; + +struct RedoxSocket { + fd: usize, +} + +impl RedoxSocket { + fn event() -> syscall::Result<Self> { + Self::open_raw("event:") + } + + fn orbital(properties: &WindowProperties<'_>) -> syscall::Result<Self> { + Self::open_raw(&format!("{properties}")) + } + + // Paths should be checked to ensure they are actually sockets and not normal files. If a + // non-socket path is used, it could cause read and write to not function as expected. For + // example, the seek would change in a potentially unpredictable way if either read or write + // were called at the same time by multiple threads. + fn open_raw(path: &str) -> syscall::Result<Self> { + let fd = syscall::open(path, syscall::O_RDWR | syscall::O_CLOEXEC)?; + Ok(Self { fd }) + } + + fn read(&self, buf: &mut [u8]) -> syscall::Result<()> { + let count = syscall::read(self.fd, buf)?; + if count == buf.len() { + Ok(()) + } else { + Err(syscall::Error::new(syscall::EINVAL)) + } + } + + fn write(&self, buf: &[u8]) -> syscall::Result<()> { + let count = syscall::write(self.fd, buf)?; + if count == buf.len() { + Ok(()) + } else { + Err(syscall::Error::new(syscall::EINVAL)) + } + } + + fn fpath<'a>(&self, buf: &'a mut [u8]) -> syscall::Result<&'a str> { + let count = syscall::fpath(self.fd, buf)?; + str::from_utf8(&buf[..count]).map_err(|_err| syscall::Error::new(syscall::EINVAL)) + } +} + +impl Drop for RedoxSocket { + fn drop(&mut self) { + let _ = syscall::close(self.fd); + } +} + +pub struct TimeSocket(RedoxSocket); + +impl TimeSocket { + fn open() -> syscall::Result<Self> { + RedoxSocket::open_raw("time:4").map(Self) + } + + // Read current time. + fn current_time(&self) -> syscall::Result<syscall::TimeSpec> { + let mut timespec = syscall::TimeSpec::default(); + self.0.read(&mut timespec)?; + Ok(timespec) + } + + // Write a timeout. + fn timeout(&self, timespec: &syscall::TimeSpec) -> syscall::Result<()> { + self.0.write(timespec) + } + + // Wake immediately. + fn wake(&self) -> syscall::Result<()> { + // Writing a default TimeSpec will always trigger a time event. + self.timeout(&syscall::TimeSpec::default()) + } +} + +#[derive(Default, Debug, Copy, Clone, PartialEq, Eq, Hash)] +pub(crate) struct PlatformSpecificEventLoopAttributes {} + +#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] +pub struct WindowId { + fd: u64, +} + +impl WindowId { + pub const fn dummy() -> Self { + WindowId { fd: u64::MAX } + } +} + +impl From<WindowId> for u64 { + fn from(id: WindowId) -> Self { + id.fd + } +} + +impl From<u64> for WindowId { + fn from(fd: u64) -> Self { + Self { fd } + } +} + +#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] +pub struct DeviceId; + +impl DeviceId { + pub const fn dummy() -> Self { + DeviceId + } +} + +#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)] +pub struct PlatformSpecificWindowAttributes; + +struct WindowProperties<'a> { + flags: &'a str, + x: i32, + y: i32, + w: u32, + h: u32, + title: &'a str, +} + +impl<'a> WindowProperties<'a> { + fn new(path: &'a str) -> Self { + // orbital:flags/x/y/w/h/t + let mut parts = path.splitn(6, '/'); + let flags = parts.next().unwrap_or(""); + let x = parts.next().map_or(0, |part| part.parse::<i32>().unwrap_or(0)); + let y = parts.next().map_or(0, |part| part.parse::<i32>().unwrap_or(0)); + let w = parts.next().map_or(0, |part| part.parse::<u32>().unwrap_or(0)); + let h = parts.next().map_or(0, |part| part.parse::<u32>().unwrap_or(0)); + let title = parts.next().unwrap_or(""); + Self { flags, x, y, w, h, title } + } +} + +impl fmt::Display for WindowProperties<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!( + f, + "orbital:{}/{}/{}/{}/{}/{}", + self.flags, self.x, self.y, self.w, self.h, self.title + ) + } +} + +#[derive(Clone, Debug)] +pub struct OsError(Arc<syscall::Error>); + +impl OsError { + fn new(error: syscall::Error) -> Self { + Self(Arc::new(error)) + } +} + +impl Display for OsError { + fn fmt(&self, fmt: &mut Formatter<'_>) -> Result<(), fmt::Error> { + self.0.fmt(fmt) + } +} + +pub(crate) use crate::cursor::{ + NoCustomCursor as PlatformCustomCursor, NoCustomCursor as PlatformCustomCursorSource, +}; +pub(crate) use crate::icon::NoIcon as PlatformIcon; + +#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] +pub struct MonitorHandle; + +impl MonitorHandle { + pub fn name(&self) -> Option<String> { + Some("Redox Device".to_owned()) + } + + pub fn size(&self) -> PhysicalSize<u32> { + PhysicalSize::new(0, 0) // TODO + } + + pub fn position(&self) -> PhysicalPosition<i32> { + (0, 0).into() + } + + pub fn scale_factor(&self) -> f64 { + 1.0 // TODO + } + + pub fn refresh_rate_millihertz(&self) -> Option<u32> { + // FIXME no way to get real refresh rate for now. + None + } + + pub fn video_modes(&self) -> impl Iterator<Item = VideoModeHandle> { + let size = self.size().into(); + // FIXME this is not the real refresh rate + // (it is guaranteed to support 32 bit color though) + std::iter::once(VideoModeHandle { + size, + bit_depth: 32, + refresh_rate_millihertz: 60000, + monitor: self.clone(), + }) + } +} + +#[derive(Clone, Debug, Eq, Hash, PartialEq)] +pub struct VideoModeHandle { + size: (u32, u32), + bit_depth: u16, + refresh_rate_millihertz: u32, + monitor: MonitorHandle, +} + +impl VideoModeHandle { + pub fn size(&self) -> PhysicalSize<u32> { + self.size.into() + } + + pub fn bit_depth(&self) -> u16 { + self.bit_depth + } + + pub fn refresh_rate_millihertz(&self) -> u32 { + self.refresh_rate_millihertz + } + + pub fn monitor(&self) -> MonitorHandle { + self.monitor.clone() + } +} + +#[derive(Debug, Clone, Eq, PartialEq, Hash)] +pub struct KeyEventExtra { + pub key_without_modifiers: Key, + pub text_with_all_modifiers: Option<SmolStr>, +} diff --git a/app/vendor/rune/vendor/winit/src/platform_impl/orbital/window.rs b/app/vendor/rune/vendor/winit/src/platform_impl/orbital/window.rs new file mode 100644 index 0000000..3e676c3 --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/platform_impl/orbital/window.rs @@ -0,0 +1,509 @@ +use std::collections::VecDeque; +use std::sync::{Arc, Mutex}; + +use crate::cursor::Cursor; +use crate::dpi::{PhysicalPosition, PhysicalSize, Position, Size}; +use crate::platform_impl::Fullscreen; +use crate::window::ImePurpose; +use crate::{error, window}; + +use super::{ + ActiveEventLoop, MonitorHandle, OsError, RedoxSocket, TimeSocket, WindowId, WindowProperties, +}; + +// These values match the values uses in the `window_new` function in orbital: +// https://gitlab.redox-os.org/redox-os/orbital/-/blob/master/src/scheme.rs +const ORBITAL_FLAG_ASYNC: char = 'a'; +const ORBITAL_FLAG_BACK: char = 'b'; +const ORBITAL_FLAG_FRONT: char = 'f'; +const ORBITAL_FLAG_HIDDEN: char = 'h'; +const ORBITAL_FLAG_BORDERLESS: char = 'l'; +const ORBITAL_FLAG_MAXIMIZED: char = 'm'; +const ORBITAL_FLAG_RESIZABLE: char = 'r'; +const ORBITAL_FLAG_TRANSPARENT: char = 't'; + +pub struct Window { + window_socket: Arc<RedoxSocket>, + redraws: Arc<Mutex<VecDeque<WindowId>>>, + destroys: Arc<Mutex<VecDeque<WindowId>>>, + wake_socket: Arc<TimeSocket>, +} + +impl Window { + pub(crate) fn new( + el: &ActiveEventLoop, + attrs: window::WindowAttributes, + ) -> Result<Self, error::OsError> { + let scale = MonitorHandle.scale_factor(); + + let (x, y) = if let Some(pos) = attrs.position { + pos.to_physical::<i32>(scale).into() + } else { + // These coordinates are a special value to center the window. + (-1, -1) + }; + + let (w, h): (u32, u32) = if let Some(size) = attrs.inner_size { + size.to_physical::<u32>(scale).into() + } else { + (1024, 768) + }; + + // TODO: min/max inner_size + + // Async by default. + let mut flag_str = ORBITAL_FLAG_ASYNC.to_string(); + + if attrs.maximized { + flag_str.push(ORBITAL_FLAG_MAXIMIZED); + } + + if attrs.resizable { + flag_str.push(ORBITAL_FLAG_RESIZABLE); + } + + // TODO: fullscreen + + if attrs.transparent { + flag_str.push(ORBITAL_FLAG_TRANSPARENT); + } + + if !attrs.decorations { + flag_str.push(ORBITAL_FLAG_BORDERLESS); + } + + if !attrs.visible { + flag_str.push(ORBITAL_FLAG_HIDDEN); + } + + match attrs.window_level { + window::WindowLevel::AlwaysOnBottom => { + flag_str.push(ORBITAL_FLAG_BACK); + }, + window::WindowLevel::Normal => {}, + window::WindowLevel::AlwaysOnTop => { + flag_str.push(ORBITAL_FLAG_FRONT); + }, + } + + // TODO: window_icon + + // Open window. + let window = RedoxSocket::orbital(&WindowProperties { + flags: &flag_str, + x, + y, + w, + h, + title: &attrs.title, + }) + .expect("failed to open window"); + + // Add to event socket. + el.event_socket + .write(&syscall::Event { + id: window.fd, + flags: syscall::EventFlags::EVENT_READ, + data: window.fd, + }) + .unwrap(); + + let window_socket = Arc::new(window); + + // Notify event thread that this window was created, it will send some default events. + { + let mut creates = el.creates.lock().unwrap(); + creates.push_back(window_socket.clone()); + } + + el.wake_socket.wake().unwrap(); + + Ok(Self { + window_socket, + redraws: el.redraws.clone(), + destroys: el.destroys.clone(), + wake_socket: el.wake_socket.clone(), + }) + } + + pub(crate) fn maybe_queue_on_main(&self, f: impl FnOnce(&Self) + Send + 'static) { + f(self) + } + + pub(crate) fn maybe_wait_on_main<R: Send>(&self, f: impl FnOnce(&Self) -> R + Send) -> R { + f(self) + } + + fn get_flag(&self, flag: char) -> Result<bool, error::ExternalError> { + let mut buf: [u8; 4096] = [0; 4096]; + let path = self + .window_socket + .fpath(&mut buf) + .map_err(|err| error::ExternalError::Os(os_error!(OsError::new(err))))?; + let properties = WindowProperties::new(path); + Ok(properties.flags.contains(flag)) + } + + fn set_flag(&self, flag: char, value: bool) -> Result<(), error::ExternalError> { + self.window_socket + .write(format!("F,{flag},{}", if value { 1 } else { 0 }).as_bytes()) + .map_err(|err| error::ExternalError::Os(os_error!(OsError::new(err))))?; + Ok(()) + } + + #[inline] + pub fn id(&self) -> WindowId { + WindowId { fd: self.window_socket.fd as u64 } + } + + #[inline] + pub fn primary_monitor(&self) -> Option<MonitorHandle> { + Some(MonitorHandle) + } + + #[inline] + pub fn available_monitors(&self) -> VecDeque<MonitorHandle> { + let mut v = VecDeque::with_capacity(1); + v.push_back(MonitorHandle); + v + } + + #[inline] + pub fn current_monitor(&self) -> Option<MonitorHandle> { + Some(MonitorHandle) + } + + #[inline] + pub fn scale_factor(&self) -> f64 { + MonitorHandle.scale_factor() + } + + #[inline] + pub fn request_redraw(&self) { + let window_id = self.id(); + let mut redraws = self.redraws.lock().unwrap(); + if !redraws.contains(&window_id) { + redraws.push_back(window_id); + + self.wake_socket.wake().unwrap(); + } + } + + #[inline] + pub fn pre_present_notify(&self) {} + + #[inline] + pub fn reset_dead_keys(&self) { + // TODO? + } + + #[inline] + pub fn inner_position(&self) -> Result<PhysicalPosition<i32>, error::NotSupportedError> { + let mut buf: [u8; 4096] = [0; 4096]; + let path = self.window_socket.fpath(&mut buf).expect("failed to read properties"); + let properties = WindowProperties::new(path); + Ok((properties.x, properties.y).into()) + } + + #[inline] + pub fn outer_position(&self) -> Result<PhysicalPosition<i32>, error::NotSupportedError> { + // TODO: adjust for window decorations + self.inner_position() + } + + #[inline] + pub fn set_outer_position(&self, position: Position) { + // TODO: adjust for window decorations + let (x, y): (i32, i32) = position.to_physical::<i32>(self.scale_factor()).into(); + self.window_socket.write(format!("P,{x},{y}").as_bytes()).expect("failed to set position"); + } + + #[inline] + pub fn inner_size(&self) -> PhysicalSize<u32> { + let mut buf: [u8; 4096] = [0; 4096]; + let path = self.window_socket.fpath(&mut buf).expect("failed to read properties"); + let properties = WindowProperties::new(path); + (properties.w, properties.h).into() + } + + #[inline] + pub fn request_inner_size(&self, size: Size) -> Option<PhysicalSize<u32>> { + let (w, h): (u32, u32) = size.to_physical::<u32>(self.scale_factor()).into(); + self.window_socket.write(format!("S,{w},{h}").as_bytes()).expect("failed to set size"); + None + } + + #[inline] + pub fn outer_size(&self) -> PhysicalSize<u32> { + // TODO: adjust for window decorations + self.inner_size() + } + + #[inline] + pub fn set_min_inner_size(&self, _: Option<Size>) {} + + #[inline] + pub fn set_max_inner_size(&self, _: Option<Size>) {} + + #[inline] + pub fn title(&self) -> String { + let mut buf: [u8; 4096] = [0; 4096]; + let path = self.window_socket.fpath(&mut buf).expect("failed to read properties"); + let properties = WindowProperties::new(path); + properties.title.to_string() + } + + #[inline] + pub fn set_title(&self, title: &str) { + self.window_socket.write(format!("T,{title}").as_bytes()).expect("failed to set title"); + } + + #[inline] + pub fn set_transparent(&self, transparent: bool) { + let _ = self.set_flag(ORBITAL_FLAG_TRANSPARENT, transparent); + } + + #[inline] + pub fn set_blur(&self, _blur: bool) {} + + #[inline] + pub fn set_visible(&self, visible: bool) { + let _ = self.set_flag(ORBITAL_FLAG_HIDDEN, !visible); + } + + #[inline] + pub fn is_visible(&self) -> Option<bool> { + Some(!self.get_flag(ORBITAL_FLAG_HIDDEN).unwrap_or(false)) + } + + #[inline] + pub fn resize_increments(&self) -> Option<PhysicalSize<u32>> { + None + } + + #[inline] + pub fn set_resize_increments(&self, _increments: Option<Size>) {} + + #[inline] + pub fn set_resizable(&self, resizeable: bool) { + let _ = self.set_flag(ORBITAL_FLAG_RESIZABLE, resizeable); + } + + #[inline] + pub fn is_resizable(&self) -> bool { + self.get_flag(ORBITAL_FLAG_RESIZABLE).unwrap_or(false) + } + + #[inline] + pub fn set_minimized(&self, _minimized: bool) {} + + #[inline] + pub fn is_minimized(&self) -> Option<bool> { + None + } + + #[inline] + pub fn set_maximized(&self, maximized: bool) { + let _ = self.set_flag(ORBITAL_FLAG_MAXIMIZED, maximized); + } + + #[inline] + pub fn is_maximized(&self) -> bool { + self.get_flag(ORBITAL_FLAG_MAXIMIZED).unwrap_or(false) + } + + #[inline] + pub(crate) fn set_fullscreen(&self, _monitor: Option<Fullscreen>) {} + + #[inline] + pub(crate) fn fullscreen(&self) -> Option<Fullscreen> { + None + } + + #[inline] + pub fn set_decorations(&self, decorations: bool) { + let _ = self.set_flag(ORBITAL_FLAG_BORDERLESS, !decorations); + } + + #[inline] + pub fn is_decorated(&self) -> bool { + !self.get_flag(ORBITAL_FLAG_BORDERLESS).unwrap_or(false) + } + + #[inline] + pub fn set_window_level(&self, level: window::WindowLevel) { + match level { + window::WindowLevel::AlwaysOnBottom => { + let _ = self.set_flag(ORBITAL_FLAG_BACK, true); + }, + window::WindowLevel::Normal => { + let _ = self.set_flag(ORBITAL_FLAG_BACK, false); + let _ = self.set_flag(ORBITAL_FLAG_FRONT, false); + }, + window::WindowLevel::AlwaysOnTop => { + let _ = self.set_flag(ORBITAL_FLAG_FRONT, true); + }, + } + } + + #[inline] + pub fn set_window_icon(&self, _window_icon: Option<crate::icon::Icon>) {} + + #[inline] + pub fn set_ime_cursor_area(&self, _position: Position, _size: Size) {} + + #[inline] + pub fn set_ime_allowed(&self, _allowed: bool) {} + + #[inline] + pub fn set_ime_purpose(&self, _purpose: ImePurpose) {} + + #[inline] + pub fn focus_window(&self) {} + + #[inline] + pub fn request_user_attention(&self, _request_type: Option<window::UserAttentionType>) {} + + #[inline] + pub fn set_cursor(&self, _: Cursor) {} + + #[inline] + pub fn set_cursor_position(&self, _: Position) -> Result<(), error::ExternalError> { + Err(error::ExternalError::NotSupported(error::NotSupportedError::new())) + } + + #[inline] + pub fn set_cursor_grab( + &self, + mode: window::CursorGrabMode, + ) -> Result<(), error::ExternalError> { + let (grab, relative) = match mode { + window::CursorGrabMode::None => (false, false), + window::CursorGrabMode::Confined => (true, false), + window::CursorGrabMode::Locked => (true, true), + }; + self.window_socket + .write(format!("M,G,{}", if grab { 1 } else { 0 }).as_bytes()) + .map_err(|err| error::ExternalError::Os(os_error!(OsError::new(err))))?; + self.window_socket + .write(format!("M,R,{}", if relative { 1 } else { 0 }).as_bytes()) + .map_err(|err| error::ExternalError::Os(os_error!(OsError::new(err))))?; + Ok(()) + } + + #[inline] + pub fn set_cursor_visible(&self, visible: bool) { + let _ = self.window_socket.write(format!("M,C,{}", if visible { 1 } else { 0 }).as_bytes()); + } + + #[inline] + pub fn drag_window(&self) -> Result<(), error::ExternalError> { + self.window_socket + .write(b"D") + .map_err(|err| error::ExternalError::Os(os_error!(OsError::new(err))))?; + Ok(()) + } + + #[inline] + pub fn drag_resize_window( + &self, + direction: window::ResizeDirection, + ) -> Result<(), error::ExternalError> { + let arg = match direction { + window::ResizeDirection::East => "R", + window::ResizeDirection::North => "T", + window::ResizeDirection::NorthEast => "T,R", + window::ResizeDirection::NorthWest => "T,L", + window::ResizeDirection::South => "B", + window::ResizeDirection::SouthEast => "B,R", + window::ResizeDirection::SouthWest => "B,L", + window::ResizeDirection::West => "L", + }; + self.window_socket + .write(format!("D,{arg}").as_bytes()) + .map_err(|err| error::ExternalError::Os(os_error!(OsError::new(err))))?; + Ok(()) + } + + #[inline] + pub fn show_window_menu(&self, _position: Position) {} + + #[inline] + pub fn set_cursor_hittest(&self, _hittest: bool) -> Result<(), error::ExternalError> { + Err(error::ExternalError::NotSupported(error::NotSupportedError::new())) + } + + #[cfg(feature = "rwh_04")] + #[inline] + pub fn raw_window_handle_rwh_04(&self) -> rwh_04::RawWindowHandle { + let mut handle = rwh_04::OrbitalHandle::empty(); + handle.window = self.window_socket.fd as *mut _; + rwh_04::RawWindowHandle::Orbital(handle) + } + + #[cfg(feature = "rwh_05")] + #[inline] + pub fn raw_window_handle_rwh_05(&self) -> rwh_05::RawWindowHandle { + let mut handle = rwh_05::OrbitalWindowHandle::empty(); + handle.window = self.window_socket.fd as *mut _; + rwh_05::RawWindowHandle::Orbital(handle) + } + + #[cfg(feature = "rwh_05")] + #[inline] + pub fn raw_display_handle_rwh_05(&self) -> rwh_05::RawDisplayHandle { + rwh_05::RawDisplayHandle::Orbital(rwh_05::OrbitalDisplayHandle::empty()) + } + + #[cfg(feature = "rwh_06")] + #[inline] + pub fn raw_window_handle_rwh_06(&self) -> Result<rwh_06::RawWindowHandle, rwh_06::HandleError> { + let handle = rwh_06::OrbitalWindowHandle::new({ + let window = self.window_socket.fd as *mut _; + std::ptr::NonNull::new(window).expect("orbital fd should never be null") + }); + Ok(rwh_06::RawWindowHandle::Orbital(handle)) + } + + #[cfg(feature = "rwh_06")] + #[inline] + pub fn raw_display_handle_rwh_06( + &self, + ) -> Result<rwh_06::RawDisplayHandle, rwh_06::HandleError> { + Ok(rwh_06::RawDisplayHandle::Orbital(rwh_06::OrbitalDisplayHandle::new())) + } + + #[inline] + pub fn set_enabled_buttons(&self, _buttons: window::WindowButtons) {} + + #[inline] + pub fn enabled_buttons(&self) -> window::WindowButtons { + window::WindowButtons::all() + } + + #[inline] + pub fn theme(&self) -> Option<window::Theme> { + None + } + + #[inline] + pub fn has_focus(&self) -> bool { + false + } + + #[inline] + pub fn set_theme(&self, _theme: Option<window::Theme>) {} + + pub fn set_content_protected(&self, _protected: bool) {} +} + +impl Drop for Window { + fn drop(&mut self) { + { + let mut destroys = self.destroys.lock().unwrap(); + destroys.push_back(self.id()); + } + + self.wake_socket.wake().unwrap(); + } +} diff --git a/app/vendor/rune/vendor/winit/src/platform_impl/web/async/abortable.rs b/app/vendor/rune/vendor/winit/src/platform_impl/web/async/abortable.rs new file mode 100644 index 0000000..671ae87 --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/platform_impl/web/async/abortable.rs @@ -0,0 +1,96 @@ +use std::error::Error; +use std::fmt::{self, Display, Formatter}; +use std::future::Future; +use std::pin::Pin; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::Arc; +use std::task::{Context, Poll}; + +use pin_project::pin_project; + +use super::AtomicWaker; + +#[pin_project] +pub struct Abortable<F: Future> { + #[pin] + future: F, + shared: Arc<Shared>, +} + +impl<F: Future> Abortable<F> { + pub fn new(handle: AbortHandle, future: F) -> Self { + Self { future, shared: handle.0 } + } +} + +impl<F: Future> Future for Abortable<F> { + type Output = Result<F::Output, Aborted>; + + fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { + if self.shared.aborted.load(Ordering::Relaxed) { + return Poll::Ready(Err(Aborted)); + } + + if let Poll::Ready(value) = self.as_mut().project().future.poll(cx) { + return Poll::Ready(Ok(value)); + } + + self.shared.waker.register(cx.waker()); + + if self.shared.aborted.load(Ordering::Relaxed) { + return Poll::Ready(Err(Aborted)); + } + + Poll::Pending + } +} + +#[derive(Debug)] +struct Shared { + waker: AtomicWaker, + aborted: AtomicBool, +} + +#[derive(Clone, Debug)] +pub struct AbortHandle(Arc<Shared>); + +impl AbortHandle { + pub fn new() -> Self { + Self(Arc::new(Shared { waker: AtomicWaker::new(), aborted: AtomicBool::new(false) })) + } + + pub fn abort(&self) { + self.0.aborted.store(true, Ordering::Relaxed); + self.0.waker.wake() + } +} + +#[derive(Debug)] +pub struct DropAbortHandle(AbortHandle); + +impl DropAbortHandle { + pub fn new(handle: AbortHandle) -> Self { + Self(handle) + } + + pub fn handle(&self) -> AbortHandle { + self.0.clone() + } +} + +impl Drop for DropAbortHandle { + fn drop(&mut self) { + self.0.abort() + } +} + +#[derive(Copy, Clone, Debug, Eq, Hash, PartialEq)] +pub struct Aborted; + +impl Display for Aborted { + fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { + write!(f, "`Abortable` future has been aborted") + } +} + +impl Error for Aborted {} diff --git a/app/vendor/rune/vendor/winit/src/platform_impl/web/async/atomic_waker.rs b/app/vendor/rune/vendor/winit/src/platform_impl/web/async/atomic_waker.rs new file mode 100644 index 0000000..87b8361 --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/platform_impl/web/async/atomic_waker.rs @@ -0,0 +1,35 @@ +use std::cell::RefCell; +use std::ops::Deref; +use std::task::Waker; + +#[derive(Debug)] +pub struct AtomicWaker(RefCell<Option<Waker>>); + +impl AtomicWaker { + pub const fn new() -> Self { + Self(RefCell::new(None)) + } + + pub fn register(&self, waker: &Waker) { + let mut this = self.0.borrow_mut(); + + if let Some(old_waker) = this.deref() { + if old_waker.will_wake(waker) { + return; + } + } + + *this = Some(waker.clone()); + } + + pub fn wake(&self) { + if let Some(waker) = self.0.borrow_mut().take() { + waker.wake(); + } + } +} + +// SAFETY: Wasm without the `atomics` target feature is single-threaded. +unsafe impl Send for AtomicWaker {} +// SAFETY: Wasm without the `atomics` target feature is single-threaded. +unsafe impl Sync for AtomicWaker {} diff --git a/app/vendor/rune/vendor/winit/src/platform_impl/web/async/channel.rs b/app/vendor/rune/vendor/winit/src/platform_impl/web/async/channel.rs new file mode 100644 index 0000000..11a7a47 --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/platform_impl/web/async/channel.rs @@ -0,0 +1,113 @@ +use std::future; +use std::rc::Rc; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::mpsc::{self, RecvError, SendError, TryRecvError}; +use std::sync::{Arc, Mutex}; +use std::task::Poll; + +use super::AtomicWaker; + +pub fn channel<T>() -> (Sender<T>, Receiver<T>) { + let (sender, receiver) = mpsc::channel(); + let shared = Arc::new(Shared { closed: AtomicBool::new(false), waker: AtomicWaker::new() }); + + let sender = + Sender(Arc::new(SenderInner { sender: Mutex::new(sender), shared: Arc::clone(&shared) })); + let receiver = Receiver { receiver: Rc::new(receiver), shared }; + + (sender, receiver) +} + +pub struct Sender<T>(Arc<SenderInner<T>>); + +struct SenderInner<T> { + // We need to wrap it into a `Mutex` to make it `Sync`. So the sender can't + // be accessed on the main thread, as it could block. Additionally we need + // to wrap `Sender` in an `Arc` to make it cloneable on the main thread without + // having to block. + sender: Mutex<mpsc::Sender<T>>, + shared: Arc<Shared>, +} + +impl<T> Sender<T> { + pub fn send(&self, event: T) -> Result<(), SendError<T>> { + self.0.sender.lock().unwrap().send(event)?; + self.0.shared.waker.wake(); + + Ok(()) + } +} + +impl<T> SenderInner<T> { + fn close(&self) { + self.shared.closed.store(true, Ordering::Relaxed); + self.shared.waker.wake(); + } +} + +impl<T> Clone for Sender<T> { + fn clone(&self) -> Self { + Self(Arc::clone(&self.0)) + } +} + +impl<T> Drop for SenderInner<T> { + fn drop(&mut self) { + self.close(); + } +} + +pub struct Receiver<T> { + receiver: Rc<mpsc::Receiver<T>>, + shared: Arc<Shared>, +} + +impl<T> Receiver<T> { + pub async fn next(&self) -> Result<T, RecvError> { + future::poll_fn(|cx| match self.receiver.try_recv() { + Ok(event) => Poll::Ready(Ok(event)), + Err(TryRecvError::Empty) => { + self.shared.waker.register(cx.waker()); + + match self.receiver.try_recv() { + Ok(event) => Poll::Ready(Ok(event)), + Err(TryRecvError::Empty) => { + if self.shared.closed.load(Ordering::Relaxed) { + Poll::Ready(Err(RecvError)) + } else { + Poll::Pending + } + }, + Err(TryRecvError::Disconnected) => Poll::Ready(Err(RecvError)), + } + }, + Err(TryRecvError::Disconnected) => Poll::Ready(Err(RecvError)), + }) + .await + } + + pub fn try_recv(&self) -> Result<Option<T>, RecvError> { + match self.receiver.try_recv() { + Ok(value) => Ok(Some(value)), + Err(TryRecvError::Empty) => Ok(None), + Err(TryRecvError::Disconnected) => Err(RecvError), + } + } +} + +impl<T> Clone for Receiver<T> { + fn clone(&self) -> Self { + Self { receiver: Rc::clone(&self.receiver), shared: Arc::clone(&self.shared) } + } +} + +impl<T> Drop for Receiver<T> { + fn drop(&mut self) { + self.shared.closed.store(true, Ordering::Relaxed); + } +} + +struct Shared { + closed: AtomicBool, + waker: AtomicWaker, +} diff --git a/app/vendor/rune/vendor/winit/src/platform_impl/web/async/concurrent_queue.rs b/app/vendor/rune/vendor/winit/src/platform_impl/web/async/concurrent_queue.rs new file mode 100644 index 0000000..70afb3d --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/platform_impl/web/async/concurrent_queue.rs @@ -0,0 +1,52 @@ +use std::cell::{Cell, RefCell}; + +#[derive(Debug)] +pub struct ConcurrentQueue<T> { + queue: RefCell<Vec<T>>, + closed: Cell<bool>, +} + +pub enum PushError<T> { + #[allow(dead_code)] + Full(T), + Closed(T), +} + +pub enum PopError { + Empty, + Closed, +} + +impl<T> ConcurrentQueue<T> { + pub fn unbounded() -> Self { + Self { queue: RefCell::new(Vec::new()), closed: Cell::new(false) } + } + + pub fn push(&self, value: T) -> Result<(), PushError<T>> { + if self.closed.get() { + return Err(PushError::Closed(value)); + } + + self.queue.borrow_mut().push(value); + Ok(()) + } + + pub fn pop(&self) -> Result<T, PopError> { + self.queue.borrow_mut().pop().ok_or_else(|| { + if self.closed.get() { + PopError::Closed + } else { + PopError::Empty + } + }) + } + + pub fn close(&self) -> bool { + !self.closed.replace(true) + } +} + +// SAFETY: Wasm without the `atomics` target feature is single-threaded. +unsafe impl<T> Send for ConcurrentQueue<T> {} +// SAFETY: Wasm without the `atomics` target feature is single-threaded. +unsafe impl<T> Sync for ConcurrentQueue<T> {} diff --git a/app/vendor/rune/vendor/winit/src/platform_impl/web/async/dispatcher.rs b/app/vendor/rune/vendor/winit/src/platform_impl/web/async/dispatcher.rs new file mode 100644 index 0000000..10ab345 --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/platform_impl/web/async/dispatcher.rs @@ -0,0 +1,106 @@ +use super::super::main_thread::MainThreadMarker; +use super::{channel, Receiver, Sender, Wrapper}; +use std::cell::Ref; +use std::sync::{Arc, Condvar, Mutex}; + +pub struct Dispatcher<T: 'static>(Wrapper<T, Sender<Closure<T>>, Closure<T>>); + +struct Closure<T>(Box<dyn FnOnce(&T) + Send>); + +impl<T> Dispatcher<T> { + #[track_caller] + pub fn new(main_thread: MainThreadMarker, value: T) -> Option<(Self, DispatchRunner<T>)> { + let (sender, receiver) = channel::<Closure<T>>(); + + Wrapper::new( + main_thread, + value, + |value, Closure(closure)| { + // SAFETY: The given `Closure` here isn't really `'static`, so we shouldn't do + // anything funny with it here. See `Self::queue()`. + closure(value.borrow().as_ref().unwrap()) + }, + { + let receiver = receiver.clone(); + move |value| async move { + while let Ok(Closure(closure)) = receiver.next().await { + // SAFETY: The given `Closure` here isn't really `'static`, so we shouldn't + // do anything funny with it here. See + // `Self::queue()`. + closure(value.borrow().as_ref().unwrap()) + } + } + }, + sender, + |sender, closure| { + // SAFETY: The given `Closure` here isn't really `'static`, so we shouldn't do + // anything funny with it here. See `Self::queue()`. + sender.send(closure).unwrap() + }, + ) + .map(|wrapper| (Self(wrapper.clone()), DispatchRunner { wrapper, receiver })) + } + + pub fn value(&self) -> Option<Ref<'_, T>> { + self.0.value() + } + + pub fn dispatch(&self, f: impl 'static + FnOnce(&T) + Send) { + if let Some(value) = self.0.value() { + f(&value) + } else { + self.0.send(Closure(Box::new(f))) + } + } + + pub fn queue<R: Send>(&self, f: impl FnOnce(&T) -> R + Send) -> R { + if let Some(value) = self.0.value() { + f(&value) + } else { + let pair = Arc::new((Mutex::new(None), Condvar::new())); + let closure = Box::new({ + let pair = pair.clone(); + move |value: &T| { + *pair.0.lock().unwrap() = Some(f(value)); + pair.1.notify_one(); + } + }) as Box<dyn FnOnce(&T) + Send>; + // SAFETY: The `transmute` is necessary because `Closure` requires `'static`. This is + // safe because this function won't return until `f` has finished executing. See + // `Self::new()`. + let closure = Closure(unsafe { + std::mem::transmute::< + Box<dyn FnOnce(&T) + Send>, + Box<dyn FnOnce(&T) + Send + 'static>, + >(closure) + }); + + self.0.send(closure); + + let mut started = pair.0.lock().unwrap(); + + while started.is_none() { + started = pair.1.wait(started).unwrap(); + } + + started.take().unwrap() + } + } +} + +pub struct DispatchRunner<T: 'static> { + wrapper: Wrapper<T, Sender<Closure<T>>, Closure<T>>, + receiver: Receiver<Closure<T>>, +} + +impl<T> DispatchRunner<T> { + pub fn run(&self) { + while let Some(Closure(closure)) = + self.receiver.try_recv().expect("should only be closed when `Dispatcher` is dropped") + { + // SAFETY: The given `Closure` here isn't really `'static`, so we shouldn't do anything + // funny with it here. See `Self::queue()`. + closure(&self.wrapper.value().expect("don't call this outside the main thread")) + } + } +} diff --git a/app/vendor/rune/vendor/winit/src/platform_impl/web/async/mod.rs b/app/vendor/rune/vendor/winit/src/platform_impl/web/async/mod.rs new file mode 100644 index 0000000..4681cf9 --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/platform_impl/web/async/mod.rs @@ -0,0 +1,19 @@ +mod abortable; +#[cfg(not(target_feature = "atomics"))] +mod atomic_waker; +mod channel; +#[cfg(not(target_feature = "atomics"))] +mod concurrent_queue; +mod dispatcher; +mod notifier; +mod waker; +mod wrapper; + +pub use self::abortable::{AbortHandle, Abortable, DropAbortHandle}; +pub use self::channel::{channel, Receiver, Sender}; +pub use self::dispatcher::{DispatchRunner, Dispatcher}; +pub use self::notifier::{Notified, Notifier}; +pub use self::waker::{Waker, WakerSpawner}; +use self::wrapper::Wrapper; +use atomic_waker::AtomicWaker; +use concurrent_queue::{ConcurrentQueue, PushError}; diff --git a/app/vendor/rune/vendor/winit/src/platform_impl/web/async/notifier.rs b/app/vendor/rune/vendor/winit/src/platform_impl/web/async/notifier.rs new file mode 100644 index 0000000..81655d1 --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/platform_impl/web/async/notifier.rs @@ -0,0 +1,72 @@ +use std::future::Future; +use std::pin::Pin; +use std::sync::{Arc, OnceLock}; +use std::task::{Context, Poll, Waker}; + +use super::{ConcurrentQueue, PushError}; + +#[derive(Debug)] +pub struct Notifier<T: Clone>(Arc<Inner<T>>); + +impl<T: Clone> Notifier<T> { + pub fn new() -> Self { + Self(Arc::new(Inner { queue: ConcurrentQueue::unbounded(), value: OnceLock::new() })) + } + + pub fn notify(self, value: T) { + if self.0.value.set(value).is_err() { + unreachable!("value set before") + } + + self.0.queue.close(); + + while let Ok(waker) = self.0.queue.pop() { + waker.wake() + } + } + + pub fn notified(&self) -> Notified<T> { + Notified(Some(Arc::clone(&self.0))) + } +} + +#[derive(Clone, Debug)] +pub struct Notified<T: Clone>(Option<Arc<Inner<T>>>); + +impl<T: Clone> Future for Notified<T> { + type Output = T; + + fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { + let this = self.0.take().expect("`Receiver` polled after completion"); + + if this.value.get().is_none() { + match this.queue.push(cx.waker().clone()) { + Ok(()) => { + if this.value.get().is_none() { + self.0 = Some(this); + return Poll::Pending; + } + }, + Err(PushError::Closed(_)) => (), + Err(PushError::Full(_)) => { + unreachable!("found full queue despite using unbounded queue") + }, + } + } + + let (Ok(Some(value)) | Err(Some(value))) = Arc::try_unwrap(this) + .map(|mut inner| inner.value.take()) + .map_err(|this| this.value.get().cloned()) + else { + unreachable!("found no value despite being ready") + }; + + Poll::Ready(value) + } +} + +#[derive(Debug)] +struct Inner<T> { + queue: ConcurrentQueue<Waker>, + value: OnceLock<T>, +} diff --git a/app/vendor/rune/vendor/winit/src/platform_impl/web/async/waker.rs b/app/vendor/rune/vendor/winit/src/platform_impl/web/async/waker.rs new file mode 100644 index 0000000..40b316d --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/platform_impl/web/async/waker.rs @@ -0,0 +1,131 @@ +use std::future; +use std::num::NonZeroUsize; +use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; +use std::sync::Arc; +use std::task::Poll; + +use super::super::main_thread::MainThreadMarker; +use super::{AtomicWaker, Wrapper}; + +pub struct WakerSpawner<T: 'static>(Wrapper<Handler<T>, Sender, NonZeroUsize>); + +pub struct Waker<T: 'static>(Wrapper<Handler<T>, Sender, NonZeroUsize>); + +struct Handler<T> { + value: T, + handler: fn(&T, NonZeroUsize, bool), +} + +#[derive(Clone)] +struct Sender(Arc<Inner>); + +impl<T> WakerSpawner<T> { + #[track_caller] + pub fn new( + main_thread: MainThreadMarker, + value: T, + handler: fn(&T, NonZeroUsize, bool), + ) -> Option<Self> { + let inner = Arc::new(Inner { + counter: AtomicUsize::new(0), + waker: AtomicWaker::new(), + closed: AtomicBool::new(false), + }); + + let handler = Handler { value, handler }; + + let sender = Sender(Arc::clone(&inner)); + + let wrapper = Wrapper::new( + main_thread, + handler, + |handler, count| { + let handler = handler.borrow(); + let handler = handler.as_ref().unwrap(); + (handler.handler)(&handler.value, count, true); + }, + { + let inner = Arc::clone(&inner); + + move |handler| async move { + while let Some(count) = future::poll_fn(|cx| { + let count = inner.counter.swap(0, Ordering::Relaxed); + + match NonZeroUsize::new(count) { + Some(count) => Poll::Ready(Some(count)), + None => { + inner.waker.register(cx.waker()); + + let count = inner.counter.swap(0, Ordering::Relaxed); + + match NonZeroUsize::new(count) { + Some(count) => Poll::Ready(Some(count)), + None => { + if inner.closed.load(Ordering::Relaxed) { + return Poll::Ready(None); + } + + Poll::Pending + }, + } + }, + } + }) + .await + { + let handler = handler.borrow(); + let handler = handler.as_ref().unwrap(); + (handler.handler)(&handler.value, count, false); + } + } + }, + sender, + |inner, _| { + inner.0.counter.fetch_add(1, Ordering::Relaxed); + inner.0.waker.wake(); + }, + )?; + + Some(Self(wrapper)) + } + + pub fn waker(&self) -> Waker<T> { + Waker(self.0.clone()) + } + + pub fn fetch(&self) -> usize { + debug_assert!( + MainThreadMarker::new().is_some(), + "this should only be called from the main thread" + ); + + self.0.with_sender_data(|inner| inner.0.counter.swap(0, Ordering::Relaxed)) + } +} + +impl<T> Drop for WakerSpawner<T> { + fn drop(&mut self) { + self.0.with_sender_data(|inner| { + inner.0.closed.store(true, Ordering::Relaxed); + inner.0.waker.wake(); + }); + } +} + +impl<T> Waker<T> { + pub fn wake(&self) { + self.0.send(NonZeroUsize::MIN) + } +} + +impl<T> Clone for Waker<T> { + fn clone(&self) -> Self { + Self(self.0.clone()) + } +} + +struct Inner { + counter: AtomicUsize, + waker: AtomicWaker, + closed: AtomicBool, +} diff --git a/app/vendor/rune/vendor/winit/src/platform_impl/web/async/wrapper.rs b/app/vendor/rune/vendor/winit/src/platform_impl/web/async/wrapper.rs new file mode 100644 index 0000000..2c7f694 --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/platform_impl/web/async/wrapper.rs @@ -0,0 +1,89 @@ +use super::super::main_thread::MainThreadMarker; +use std::cell::{Ref, RefCell}; +use std::future::Future; +use std::marker::PhantomData; +use std::sync::Arc; + +// Unsafe wrapper type that allows us to use `T` when it's not `Send` from other threads. +// `value` **must** only be accessed on the main thread. +pub struct Wrapper<V: 'static, S: Clone + Send, E> { + value: Value<V>, + handler: fn(&RefCell<Option<V>>, E), + sender_data: S, + sender_handler: fn(&S, E), +} + +struct Value<V> { + // SAFETY: + // This value must not be accessed if not on the main thread. + // + // - We wrap this in an `Arc` to allow it to be safely cloned without accessing the value. + // - The `RefCell` lets us mutably access in the main thread but is safe to drop in any thread + // because it has no `Drop` behavior. + // - The `Option` lets us safely drop `T` only in the main thread. + value: Arc<RefCell<Option<V>>>, + // Prevent's `Send` or `Sync` to be automatically implemented. + local: PhantomData<*const ()>, +} + +// SAFETY: See `Self::value`. +unsafe impl<V> Send for Value<V> {} +// SAFETY: See `Self::value`. +unsafe impl<V> Sync for Value<V> {} + +impl<V, S: Clone + Send, E> Wrapper<V, S, E> { + #[track_caller] + pub fn new<R: Future<Output = ()>>( + _: MainThreadMarker, + value: V, + handler: fn(&RefCell<Option<V>>, E), + receiver: impl 'static + FnOnce(Arc<RefCell<Option<V>>>) -> R, + sender_data: S, + sender_handler: fn(&S, E), + ) -> Option<Self> { + let value = Arc::new(RefCell::new(Some(value))); + + wasm_bindgen_futures::spawn_local({ + let value = Arc::clone(&value); + async move { + receiver(Arc::clone(&value)).await; + drop(value.borrow_mut().take().unwrap()); + } + }); + + Some(Self { + value: Value { value, local: PhantomData }, + handler, + sender_data, + sender_handler, + }) + } + + pub fn send(&self, event: E) { + if MainThreadMarker::new().is_some() { + (self.handler)(&self.value.value, event) + } else { + (self.sender_handler)(&self.sender_data, event) + } + } + + pub fn value(&self) -> Option<Ref<'_, V>> { + MainThreadMarker::new() + .map(|_| Ref::map(self.value.value.borrow(), |value| value.as_ref().unwrap())) + } + + pub fn with_sender_data<T>(&self, f: impl FnOnce(&S) -> T) -> T { + f(&self.sender_data) + } +} + +impl<V, S: Clone + Send, E> Clone for Wrapper<V, S, E> { + fn clone(&self) -> Self { + Self { + value: Value { value: self.value.value.clone(), local: PhantomData }, + handler: self.handler, + sender_data: self.sender_data.clone(), + sender_handler: self.sender_handler, + } + } +} diff --git a/app/vendor/rune/vendor/winit/src/platform_impl/web/cursor.rs b/app/vendor/rune/vendor/winit/src/platform_impl/web/cursor.rs new file mode 100644 index 0000000..214ff45 --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/platform_impl/web/cursor.rs @@ -0,0 +1,730 @@ +use std::cell::RefCell; +use std::future::{self, Future}; +use std::hash::{Hash, Hasher}; +use std::mem; +use std::ops::{Deref, DerefMut}; +use std::pin::Pin; +use std::rc::Rc; +use std::sync::Arc; +use std::task::{ready, Context, Poll, Waker}; +use std::time::Duration; + +use cursor_icon::CursorIcon; +use js_sys::{Array, Object}; +use wasm_bindgen::closure::Closure; +use wasm_bindgen::prelude::wasm_bindgen; +use wasm_bindgen::JsCast; +use wasm_bindgen_futures::JsFuture; +use web_sys::{ + Blob, Document, DomException, HtmlCanvasElement, HtmlImageElement, ImageBitmap, + ImageBitmapOptions, ImageBitmapRenderingContext, ImageData, PremultiplyAlpha, Url, Window, +}; + +use super::backend::Style; +use super::main_thread::{MainThreadMarker, MainThreadSafe}; +use super::r#async::{AbortHandle, Abortable, DropAbortHandle, Notified, Notifier}; +use super::ActiveEventLoop; +use crate::cursor::{BadImage, Cursor, CursorImage, CustomCursor as RootCustomCursor}; +use crate::platform::web::CustomCursorError; + +#[derive(Debug)] +pub(crate) enum CustomCursorSource { + Image(CursorImage), + Url { url: String, hotspot_x: u16, hotspot_y: u16 }, + Animation { duration: Duration, cursors: Vec<RootCustomCursor> }, +} + +impl CustomCursorSource { + pub fn from_rgba( + rgba: Vec<u8>, + width: u16, + height: u16, + hotspot_x: u16, + hotspot_y: u16, + ) -> Result<CustomCursorSource, BadImage> { + Ok(CustomCursorSource::Image(CursorImage::from_rgba( + rgba, width, height, hotspot_x, hotspot_y, + )?)) + } +} + +#[derive(Clone, Debug)] +pub struct CustomCursor { + pub(crate) animation: bool, + state: Arc<MainThreadSafe<RefCell<ImageState>>>, +} + +impl Hash for CustomCursor { + fn hash<H: Hasher>(&self, state: &mut H) { + Arc::as_ptr(&self.state).hash(state); + } +} + +impl PartialEq for CustomCursor { + fn eq(&self, other: &Self) -> bool { + Arc::ptr_eq(&self.state, &other.state) + } +} + +impl Eq for CustomCursor {} + +impl CustomCursor { + pub(crate) fn new(event_loop: &ActiveEventLoop, source: CustomCursorSource) -> Self { + match source { + CustomCursorSource::Image(image) => Self::build_spawn( + event_loop, + from_rgba(event_loop.runner.window(), event_loop.runner.document().clone(), &image), + false, + ), + CustomCursorSource::Url { url, hotspot_x, hotspot_y } => Self::build_spawn( + event_loop, + from_url(UrlType::Plain(url), hotspot_x, hotspot_y), + false, + ), + CustomCursorSource::Animation { duration, cursors } => Self::build_spawn( + event_loop, + from_animation( + event_loop.runner.main_thread(), + duration, + cursors.into_iter().map(|cursor| cursor.inner), + ), + true, + ), + } + } + + fn build_spawn<F, S>(window_target: &ActiveEventLoop, task: F, animation: bool) -> CustomCursor + where + F: 'static + Future<Output = Result<S, CustomCursorError>>, + S: Into<ImageState>, + { + let handle = AbortHandle::new(); + let this = CustomCursor { + animation, + state: Arc::new(MainThreadSafe::new( + window_target.runner.main_thread(), + RefCell::new(ImageState::Loading { + notifier: Notifier::new(), + _handle: DropAbortHandle::new(handle.clone()), + }), + )), + }; + let weak = Arc::downgrade(&this.state); + let main_thread = window_target.runner.main_thread(); + + let task = Abortable::new(handle, { + async move { + let result = task.await; + + let this = weak.upgrade().expect("`CursorHandler` invalidated without aborting"); + let mut this = this.get(main_thread).borrow_mut(); + + match result { + Ok(new_state) => { + let ImageState::Loading { notifier, .. } = + mem::replace(this.deref_mut(), new_state.into()) + else { + unreachable!("found invalid state"); + }; + notifier.notify(Ok(())); + }, + Err(error) => { + let ImageState::Loading { notifier, .. } = + mem::replace(this.deref_mut(), ImageState::Failed(error.clone())) + else { + unreachable!("found invalid state"); + }; + notifier.notify(Err(error)); + }, + } + } + }); + + wasm_bindgen_futures::spawn_local(async move { + let _ = task.await; + }); + + this + } + + pub(crate) fn new_async( + event_loop: &ActiveEventLoop, + source: CustomCursorSource, + ) -> CustomCursorFuture { + let CustomCursor { animation, state } = Self::new(event_loop, source); + let binding = state.get(event_loop.runner.main_thread()).borrow(); + let ImageState::Loading { notifier, .. } = binding.deref() else { + unreachable!("found invalid state") + }; + let notified = notifier.notified(); + drop(binding); + + CustomCursorFuture { notified, animation, state: Some(state) } + } +} + +#[derive(Debug)] +pub struct CustomCursorFuture { + notified: Notified<Result<(), CustomCursorError>>, + animation: bool, + state: Option<Arc<MainThreadSafe<RefCell<ImageState>>>>, +} + +impl Future for CustomCursorFuture { + type Output = Result<CustomCursor, CustomCursorError>; + + fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { + if self.state.is_none() { + panic!("`CustomCursorFuture` polled after completion") + } + + let result = ready!(Pin::new(&mut self.notified).poll(cx)); + let state = self.state.take().expect("`CustomCursorFuture` polled after completion"); + + Poll::Ready(result.map(|_| CustomCursor { animation: self.animation, state })) + } +} + +#[derive(Debug)] +pub struct CursorHandler(Rc<RefCell<Inner>>); + +#[derive(Debug)] +struct Inner { + main_thread: MainThreadMarker, + canvas: HtmlCanvasElement, + style: Style, + visible: bool, + cursor: SelectedCursor, +} + +impl CursorHandler { + pub(crate) fn new( + main_thread: MainThreadMarker, + canvas: HtmlCanvasElement, + style: Style, + ) -> Self { + Self(Rc::new(RefCell::new(Inner { + main_thread, + canvas, + style, + visible: true, + cursor: SelectedCursor::default(), + }))) + } + + pub fn set_cursor(&self, cursor: Cursor) { + let mut this = self.0.borrow_mut(); + + match cursor { + Cursor::Icon(icon) => { + if let SelectedCursor::Icon(old_icon) + | SelectedCursor::Loading { previous: Previous::Icon(old_icon), .. } = + &this.cursor + { + if *old_icon == icon { + return; + } + } + + this.cursor = SelectedCursor::Icon(icon); + this.set_style(); + }, + Cursor::Custom(cursor) => { + let cursor = cursor.inner; + + if let SelectedCursor::Loading { cursor: old_cursor, .. } + | SelectedCursor::Image(old_cursor) + | SelectedCursor::Animation { cursor: old_cursor, .. } = &this.cursor + { + if *old_cursor == cursor { + return; + } + } + + let state = cursor.state.get(this.main_thread).borrow(); + + match state.deref() { + ImageState::Loading { notifier, .. } => { + let notified = notifier.notified(); + let handle = DropAbortHandle::new(AbortHandle::new()); + let task = Abortable::new(handle.handle(), { + let weak = Rc::downgrade(&self.0); + async move { + let _ = notified.await; + let handler = weak + .upgrade() + .expect("`CursorHandler` invalidated without aborting"); + handler.borrow_mut().notify(); + } + }); + wasm_bindgen_futures::spawn_local(async move { + let _ = task.await; + }); + + drop(state); + this.cursor = SelectedCursor::Loading { + cursor, + previous: mem::take(&mut this.cursor).into(), + _handle: handle, + }; + }, + ImageState::Failed(error) => { + tracing::error!( + "trying to load custom cursor that has failed to load: {error}" + ) + }, + ImageState::Image(_) => { + drop(state); + this.cursor = SelectedCursor::Image(cursor); + this.set_style(); + }, + ImageState::Animation(animation) => { + let canvas: &CanvasAnimateExt = this.canvas.unchecked_ref(); + let animation = canvas.animate_with_keyframe_animation_options( + Some(&animation.keyframes), + &animation.options, + ); + drop(state); + + if !this.visible { + animation.cancel(); + } + + this.cursor = SelectedCursor::Animation { + animation: AnimationDropper(animation), + cursor, + }; + this.set_style(); + }, + }; + }, + } + } + + pub fn set_cursor_visible(&self, visible: bool) { + let mut this = self.0.borrow_mut(); + + if !visible && this.visible { + this.visible = false; + this.style.set("cursor", "none"); + + if let SelectedCursor::Animation { animation, .. } = &this.cursor { + animation.0.cancel(); + } + } else if visible && !this.visible { + this.visible = true; + this.set_style(); + } + } +} + +impl Inner { + fn set_style(&self) { + if self.visible { + match &self.cursor { + SelectedCursor::Icon(icon) + | SelectedCursor::Loading { previous: Previous::Icon(icon), .. } => { + if let CursorIcon::Default = icon { + self.style.remove("cursor") + } else { + self.style.set("cursor", icon.name()) + } + }, + SelectedCursor::Loading { previous: Previous::Image(cursor), .. } + | SelectedCursor::Image(cursor) => { + match cursor.state.get(self.main_thread).borrow().deref() { + ImageState::Image(Image { style, .. }) => self.style.set("cursor", style), + _ => unreachable!("found invalid saved state"), + } + }, + SelectedCursor::Loading { + previous: Previous::Animation { animation, .. }, .. + } + | SelectedCursor::Animation { animation, .. } => { + self.style.remove("cursor"); + animation.0.play() + }, + } + } + } + + fn notify(&mut self) { + let SelectedCursor::Loading { cursor, previous, .. } = mem::take(&mut self.cursor) else { + unreachable!("found wrong state") + }; + + let state = cursor.state.get(self.main_thread).borrow(); + match state.deref() { + ImageState::Image(_) => { + drop(state); + self.cursor = SelectedCursor::Image(cursor); + self.set_style(); + }, + ImageState::Animation(animation) => { + let canvas: &CanvasAnimateExt = self.canvas.unchecked_ref(); + let animation = canvas.animate_with_keyframe_animation_options( + Some(&animation.keyframes), + &animation.options, + ); + drop(state); + + if !self.visible { + animation.cancel(); + } + + self.cursor = + SelectedCursor::Animation { animation: AnimationDropper(animation), cursor }; + self.set_style(); + }, + ImageState::Failed(error) => { + tracing::error!("custom cursor failed to load: {error}"); + self.cursor = previous.into() + }, + ImageState::Loading { .. } => unreachable!("notified without being ready"), + } + } +} + +#[derive(Debug)] +enum SelectedCursor { + Icon(CursorIcon), + Loading { cursor: CustomCursor, previous: Previous, _handle: DropAbortHandle }, + Image(CustomCursor), + Animation { cursor: CustomCursor, animation: AnimationDropper }, +} + +impl Default for SelectedCursor { + fn default() -> Self { + Self::Icon(Default::default()) + } +} + +impl From<Previous> for SelectedCursor { + fn from(previous: Previous) -> Self { + match previous { + Previous::Icon(icon) => Self::Icon(icon), + Previous::Image(cursor) => Self::Image(cursor), + Previous::Animation { cursor, animation } => Self::Animation { cursor, animation }, + } + } +} + +#[derive(Debug)] +enum Previous { + Icon(CursorIcon), + Image(CustomCursor), + Animation { cursor: CustomCursor, animation: AnimationDropper }, +} + +impl From<SelectedCursor> for Previous { + fn from(value: SelectedCursor) -> Self { + match value { + SelectedCursor::Icon(icon) => Self::Icon(icon), + SelectedCursor::Loading { previous, .. } => previous, + SelectedCursor::Image(image) => Self::Image(image), + SelectedCursor::Animation { cursor, animation } => { + Self::Animation { cursor, animation } + }, + } + } +} + +#[derive(Debug)] +enum ImageState { + Loading { notifier: Notifier<Result<(), CustomCursorError>>, _handle: DropAbortHandle }, + Failed(CustomCursorError), + Image(Image), + Animation(Animation), +} + +#[derive(Debug)] +struct Image { + style: String, + _object_url: Option<ObjectUrl>, + _image: HtmlImageElement, +} + +impl From<Image> for ImageState { + fn from(image: Image) -> Self { + Self::Image(image) + } +} + +#[derive(Debug)] +struct Animation { + keyframes: Array, + options: KeyframeAnimationOptions, + _images: Vec<CustomCursor>, +} + +impl From<Animation> for ImageState { + fn from(animation: Animation) -> Self { + Self::Animation(animation) + } +} + +#[derive(Debug)] +enum UrlType { + Plain(String), + Object(ObjectUrl), +} + +impl UrlType { + fn url(&self) -> &str { + match &self { + UrlType::Plain(url) => url, + UrlType::Object(object_url) => &object_url.0, + } + } +} + +#[derive(Debug)] +struct ObjectUrl(String); + +impl Drop for ObjectUrl { + fn drop(&mut self) { + Url::revoke_object_url(&self.0).expect("unexpected exception in `URL.revokeObjectURL()`"); + } +} + +#[derive(Debug)] +struct AnimationDropper(WebAnimation); + +impl Drop for AnimationDropper { + fn drop(&mut self) { + self.0.cancel() + } +} + +fn from_rgba( + window: &Window, + document: Document, + image: &CursorImage, +) -> impl Future<Output = Result<Image, CustomCursorError>> { + // 1. Create an `ImageData` from the RGBA data. + // 2. Create an `ImageBitmap` from the `ImageData`. + // 3. Draw `ImageBitmap` on an `HTMLCanvasElement`. + // 4. Create a `Blob` from the `HTMLCanvasElement`. + // 5. Create an object URL from the `Blob`. + // 6. Decode the image on an `HTMLImageElement` from the URL. + + // 1. Create an `ImageData` from the RGBA data. + // Adapted from https://github.com/rust-windowing/softbuffer/blob/ab7688e2ed2e2eca51b3c4e1863a5bd7fe85800e/src/web.rs#L196-L223 + #[cfg(target_feature = "atomics")] + // Can't share `SharedArrayBuffer` with `ImageData`. + let result = { + use js_sys::{Uint8Array, Uint8ClampedArray}; + use wasm_bindgen::JsValue; + + #[wasm_bindgen] + extern "C" { + #[wasm_bindgen(js_namespace = ImageData)] + type ImageDataExt; + #[wasm_bindgen(catch, constructor, js_class = ImageData)] + fn new(array: Uint8ClampedArray, sw: u32) -> Result<ImageDataExt, JsValue>; + } + + let array = Uint8Array::new_with_length(image.rgba.len() as u32); + array.copy_from(&image.rgba); + let array = Uint8ClampedArray::new(&array); + ImageDataExt::new(array, image.width as u32) + .map(JsValue::from) + .map(ImageData::unchecked_from_js) + }; + #[cfg(not(target_feature = "atomics"))] + let result = ImageData::new_with_u8_clamped_array( + wasm_bindgen::Clamped(&image.rgba), + image.width as u32, + ); + let image_data = result.expect("found wrong image size"); + + // 2. Create an `ImageBitmap` from the `ImageData`. + // + // We call `createImageBitmap()` before spawning the future, + // to not have to clone the image buffer. + let options = ImageBitmapOptions::new(); + options.set_premultiply_alpha(PremultiplyAlpha::None); + let bitmap = JsFuture::from( + window + .create_image_bitmap_with_image_data_and_image_bitmap_options(&image_data, &options) + .expect("unexpected exception in `createImageBitmap()`"), + ); + + let CursorImage { width, height, hotspot_x, hotspot_y, .. } = *image; + async move { + let bitmap: ImageBitmap = + bitmap.await.expect("found invalid state in `ImageData`").unchecked_into(); + + let canvas: HtmlCanvasElement = + document.create_element("canvas").expect("invalid tag name").unchecked_into(); + #[allow(clippy::disallowed_methods)] + canvas.set_width(width as u32); + #[allow(clippy::disallowed_methods)] + canvas.set_height(height as u32); + + // 3. Draw `ImageBitmap` on an `HTMLCanvasElement`. + let context: ImageBitmapRenderingContext = canvas + .get_context("bitmaprenderer") + .expect("unexpected exception in `HTMLCanvasElement.getContext()`") + .expect("`bitmaprenderer` context unsupported") + .unchecked_into(); + context.transfer_from_image_bitmap(&bitmap); + drop(bitmap); + drop(context); + + // 4. Create a `Blob` from the `HTMLCanvasElement`. + // + // To keep the `Closure` alive until `HTMLCanvasElement.toBlob()` is done, + // we do the whole `Waker` strategy. Commonly on `Drop` the callback is aborted, + // but it would increase complexity and isn't possible in this case. + // Keep in mind that `HTMLCanvasElement.toBlob()` can call the callback immediately. + let value = Rc::new(RefCell::new(None)); + let waker = Rc::new(RefCell::<Option<Waker>>::new(None)); + let callback = Closure::once({ + let value = value.clone(); + let waker = waker.clone(); + move |blob: Option<Blob>| { + *value.borrow_mut() = Some(blob); + if let Some(waker) = waker.borrow_mut().take() { + waker.wake(); + } + } + }); + canvas + .to_blob(callback.as_ref().unchecked_ref()) + .expect("failed with `SecurityError` despite only source coming from memory"); + let blob = future::poll_fn(|cx| { + if let Some(blob) = value.borrow_mut().take() { + Poll::Ready(blob) + } else { + *waker.borrow_mut() = Some(cx.waker().clone()); + Poll::Pending + } + }) + .await; + drop(canvas); + + let Some(blob) = blob else { + return Err(CustomCursorError::Blob); + }; + + // 5. Create an object URL from the `Blob`. + let url = Url::create_object_url_with_blob(&blob) + .expect("unexpected exception in `URL.createObjectURL()`"); + let url = UrlType::Object(ObjectUrl(url)); + + from_url(url, hotspot_x, hotspot_y).await + } +} + +async fn from_url( + url: UrlType, + hotspot_x: u16, + hotspot_y: u16, +) -> Result<Image, CustomCursorError> { + // 6. Decode the image on an `HTMLImageElement` from the URL. + let image = HtmlImageElement::new().expect("unexpected exception in `new HtmlImageElement`"); + image.set_src(url.url()); + let result = JsFuture::from(image.decode()).await; + + if let Err(error) = result { + debug_assert!(error.has_type::<DomException>()); + let error: DomException = error.unchecked_into(); + debug_assert_eq!(error.name(), "EncodingError"); + let error = error.message(); + + return Err(CustomCursorError::Decode(error)); + } + + Ok(Image { + style: format!("url({}) {hotspot_x} {hotspot_y}, auto", url.url()), + _object_url: match url { + UrlType::Plain(_) => None, + UrlType::Object(object_url) => Some(object_url), + }, + _image: image, + }) +} + +#[allow(clippy::await_holding_refcell_ref)] // false-positive +async fn from_animation( + main_thread: MainThreadMarker, + duration: Duration, + cursors: impl ExactSizeIterator<Item = CustomCursor>, +) -> Result<Animation, CustomCursorError> { + let keyframes = Array::new(); + let mut images = Vec::with_capacity(cursors.len()); + + for cursor in cursors { + let state = cursor.state.get(main_thread).borrow(); + + match state.deref() { + ImageState::Loading { notifier, .. } => { + let notified = notifier.notified(); + drop(state); + notified.await?; + }, + ImageState::Failed(error) => return Err(error.clone()), + ImageState::Image(_) => drop(state), + ImageState::Animation(_) => unreachable!("check in `CustomCursorSource` failed"), + } + + let state = cursor.state.get(main_thread).borrow(); + let style = match state.deref() { + ImageState::Image(Image { style, .. }) => style, + _ => unreachable!("found invalid state"), + }; + + let keyframe: Keyframe = Object::new().unchecked_into(); + keyframe.set_cursor(style); + keyframes.push(&keyframe); + drop(state); + + images.push(cursor); + } + + keyframes.push(&keyframes.get(0)); + + let options: KeyframeAnimationOptions = Object::new().unchecked_into(); + options.set_duration(duration.as_millis() as f64); + options.set_iterations(f64::INFINITY); + + Ok(Animation { keyframes, options, _images: images }) +} + +#[wasm_bindgen] +extern "C" { + type CanvasAnimateExt; + + #[wasm_bindgen(method, js_name = animate)] + fn animate_with_keyframe_animation_options( + this: &CanvasAnimateExt, + keyframes: Option<&Object>, + options: &KeyframeAnimationOptions, + ) -> WebAnimation; + + #[derive(Debug)] + type WebAnimation; + + #[wasm_bindgen(method)] + fn cancel(this: &WebAnimation); + + #[wasm_bindgen(method)] + fn play(this: &WebAnimation); + + #[wasm_bindgen(extends = Object)] + type Keyframe; + + #[wasm_bindgen(method, setter, js_name = cursor)] + fn set_cursor(this: &Keyframe, value: &str); + + #[derive(Debug)] + #[wasm_bindgen(extends = Object)] + type KeyframeAnimationOptions; + + #[wasm_bindgen(method, setter, js_name = duration)] + fn set_duration(this: &KeyframeAnimationOptions, value: f64); + + #[wasm_bindgen(method, setter, js_name = iterations)] + fn set_iterations(this: &KeyframeAnimationOptions, value: f64); +} diff --git a/app/vendor/rune/vendor/winit/src/platform_impl/web/device.rs b/app/vendor/rune/vendor/winit/src/platform_impl/web/device.rs new file mode 100644 index 0000000..91d0858 --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/platform_impl/web/device.rs @@ -0,0 +1,8 @@ +#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub struct DeviceId(pub i32); + +impl DeviceId { + pub const fn dummy() -> Self { + Self(0) + } +} diff --git a/app/vendor/rune/vendor/winit/src/platform_impl/web/error.rs b/app/vendor/rune/vendor/winit/src/platform_impl/web/error.rs new file mode 100644 index 0000000..6995f2b --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/platform_impl/web/error.rs @@ -0,0 +1,10 @@ +use std::fmt; + +#[derive(Debug)] +pub struct OsError(pub String); + +impl fmt::Display for OsError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "{}", self.0) + } +} diff --git a/app/vendor/rune/vendor/winit/src/platform_impl/web/event_loop/mod.rs b/app/vendor/rune/vendor/winit/src/platform_impl/web/event_loop/mod.rs new file mode 100644 index 0000000..23fe2e0 --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/platform_impl/web/event_loop/mod.rs @@ -0,0 +1,119 @@ +use std::marker::PhantomData; +use std::sync::mpsc::{self, Receiver, Sender}; + +use crate::error::EventLoopError; +use crate::event::Event; +use crate::event_loop::ActiveEventLoop as RootActiveEventLoop; +use crate::platform::web::{ActiveEventLoopExtWebSys, PollStrategy, WaitUntilStrategy}; + +use super::{backend, device, window}; + +mod proxy; +pub(crate) mod runner; +mod state; +mod window_target; + +pub(crate) use proxy::EventLoopProxy; +pub(crate) use window_target::{ActiveEventLoop, OwnedDisplayHandle}; + +pub struct EventLoop<T: 'static> { + elw: RootActiveEventLoop, + user_event_sender: Sender<T>, + user_event_receiver: Receiver<T>, +} + +#[derive(Default, Debug, Copy, Clone, PartialEq, Eq, Hash)] +pub(crate) struct PlatformSpecificEventLoopAttributes {} + +impl<T> EventLoop<T> { + pub(crate) fn new(_: &PlatformSpecificEventLoopAttributes) -> Result<Self, EventLoopError> { + let (user_event_sender, user_event_receiver) = mpsc::channel(); + let elw = RootActiveEventLoop { p: ActiveEventLoop::new(), _marker: PhantomData }; + Ok(EventLoop { elw, user_event_sender, user_event_receiver }) + } + + pub fn run<F>(self, mut event_handler: F) -> ! + where + F: FnMut(Event<T>, &RootActiveEventLoop), + { + let target = RootActiveEventLoop { p: self.elw.p.clone(), _marker: PhantomData }; + + // SAFETY: Don't use `move` to make sure we leak the `event_handler` and `target`. + let handler: Box<dyn FnMut(Event<()>)> = Box::new(|event| { + let event = match event.map_nonuser_event() { + Ok(event) => event, + Err(Event::UserEvent(())) => Event::UserEvent( + self.user_event_receiver + .try_recv() + .expect("handler woken up without user event"), + ), + Err(_) => unreachable!(), + }; + event_handler(event, &target) + }); + // SAFETY: The `transmute` is necessary because `run()` requires `'static`. This is safe + // because this function will never return and all resources not cleaned up by the point we + // `throw` will leak, making this actually `'static`. + let handler = unsafe { + std::mem::transmute::<Box<dyn FnMut(Event<()>)>, Box<dyn FnMut(Event<()>) + 'static>>( + handler, + ) + }; + self.elw.p.run(handler, false); + + // Throw an exception to break out of Rust execution and use unreachable to tell the + // compiler this function won't return, giving it a return type of '!' + backend::throw( + "Using exceptions for control flow, don't mind me. This isn't actually an error!", + ); + + unreachable!(); + } + + pub fn spawn<F>(self, mut event_handler: F) + where + F: 'static + FnMut(Event<T>, &RootActiveEventLoop), + { + let target = RootActiveEventLoop { p: self.elw.p.clone(), _marker: PhantomData }; + + self.elw.p.run( + Box::new(move |event| { + let event = match event.map_nonuser_event() { + Ok(event) => event, + Err(Event::UserEvent(())) => Event::UserEvent( + self.user_event_receiver + .try_recv() + .expect("handler woken up without user event"), + ), + Err(_) => unreachable!(), + }; + event_handler(event, &target) + }), + true, + ); + } + + pub fn create_proxy(&self) -> EventLoopProxy<T> { + EventLoopProxy::new(self.elw.p.waker(), self.user_event_sender.clone()) + } + + pub fn window_target(&self) -> &RootActiveEventLoop { + &self.elw + } + + pub fn set_poll_strategy(&self, strategy: PollStrategy) { + self.elw.set_poll_strategy(strategy); + } + + pub fn poll_strategy(&self) -> PollStrategy { + self.elw.poll_strategy() + } + + pub fn set_wait_until_strategy(&self, strategy: WaitUntilStrategy) { + self.elw.set_wait_until_strategy(strategy); + } + + pub fn wait_until_strategy(&self) -> WaitUntilStrategy { + self.elw.wait_until_strategy() + } +} diff --git a/app/vendor/rune/vendor/winit/src/platform_impl/web/event_loop/proxy.rs b/app/vendor/rune/vendor/winit/src/platform_impl/web/event_loop/proxy.rs new file mode 100644 index 0000000..bd8e714 --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/platform_impl/web/event_loop/proxy.rs @@ -0,0 +1,29 @@ +use std::rc::Weak; +use std::sync::mpsc::{SendError, Sender}; + +use super::runner::Execution; +use crate::event_loop::EventLoopClosed; +use crate::platform_impl::platform::r#async::Waker; + +pub struct EventLoopProxy<T: 'static> { + runner: Waker<Weak<Execution>>, + sender: Sender<T>, +} + +impl<T: 'static> EventLoopProxy<T> { + pub fn new(runner: Waker<Weak<Execution>>, sender: Sender<T>) -> Self { + Self { runner, sender } + } + + pub fn send_event(&self, event: T) -> Result<(), EventLoopClosed<T>> { + self.sender.send(event).map_err(|SendError(event)| EventLoopClosed(event))?; + self.runner.wake(); + Ok(()) + } +} + +impl<T: 'static> Clone for EventLoopProxy<T> { + fn clone(&self) -> Self { + Self { runner: self.runner.clone(), sender: self.sender.clone() } + } +} diff --git a/app/vendor/rune/vendor/winit/src/platform_impl/web/event_loop/runner.rs b/app/vendor/rune/vendor/winit/src/platform_impl/web/event_loop/runner.rs new file mode 100644 index 0000000..d9ba3d3 --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/platform_impl/web/event_loop/runner.rs @@ -0,0 +1,808 @@ +use std::cell::{Cell, RefCell}; +use std::collections::{HashSet, VecDeque}; +use std::iter; +use std::num::NonZeroUsize; +use std::ops::Deref; +use std::rc::{Rc, Weak}; + +use wasm_bindgen::prelude::Closure; +use wasm_bindgen::JsCast; +use web_sys::{Document, KeyboardEvent, PageTransitionEvent, PointerEvent, WheelEvent}; +use web_time::{Duration, Instant}; + +use super::super::main_thread::MainThreadMarker; +use super::super::DeviceId; +use super::backend; +use super::state::State; +use crate::dpi::PhysicalSize; +use crate::event::{ + DeviceEvent, DeviceId as RootDeviceId, ElementState, Event, RawKeyEvent, StartCause, + WindowEvent, +}; +use crate::event_loop::{ControlFlow, DeviceEvents}; +use crate::platform::web::{PollStrategy, WaitUntilStrategy}; +use crate::platform_impl::platform::backend::EventListenerHandle; +use crate::platform_impl::platform::r#async::{DispatchRunner, Waker, WakerSpawner}; +use crate::platform_impl::platform::window::Inner; +use crate::window::WindowId; + +pub struct Shared(Rc<Execution>); + +pub(super) type EventHandler = dyn FnMut(Event<()>); + +impl Clone for Shared { + fn clone(&self) -> Self { + Shared(self.0.clone()) + } +} + +type OnEventHandle<T> = RefCell<Option<EventListenerHandle<dyn FnMut(T)>>>; + +pub struct Execution { + main_thread: MainThreadMarker, + proxy_spawner: WakerSpawner<Weak<Self>>, + control_flow: Cell<ControlFlow>, + poll_strategy: Cell<PollStrategy>, + wait_until_strategy: Cell<WaitUntilStrategy>, + exit: Cell<bool>, + runner: RefCell<RunnerEnum>, + suspended: Cell<bool>, + event_loop_recreation: Cell<bool>, + events: RefCell<VecDeque<EventWrapper>>, + id: RefCell<u32>, + window: web_sys::Window, + document: Document, + #[allow(clippy::type_complexity)] + all_canvases: RefCell<Vec<(WindowId, Weak<RefCell<backend::Canvas>>, DispatchRunner<Inner>)>>, + redraw_pending: RefCell<HashSet<WindowId>>, + destroy_pending: RefCell<VecDeque<WindowId>>, + page_transition_event_handle: RefCell<Option<backend::PageTransitionEventHandle>>, + device_events: Cell<DeviceEvents>, + on_mouse_move: OnEventHandle<PointerEvent>, + on_wheel: OnEventHandle<WheelEvent>, + on_mouse_press: OnEventHandle<PointerEvent>, + on_mouse_release: OnEventHandle<PointerEvent>, + on_key_press: OnEventHandle<KeyboardEvent>, + on_key_release: OnEventHandle<KeyboardEvent>, + on_visibility_change: OnEventHandle<web_sys::Event>, +} + +enum RunnerEnum { + /// The `EventLoop` is created but not being run. + Pending, + /// The `EventLoop` is being run. + Running(Runner), + /// The `EventLoop` is exited after being started with `EventLoop::run_app`. Since + /// `EventLoop::run_app` takes ownership of the `EventLoop`, we can be certain + /// that this event loop will never be run again. + Destroyed, +} + +impl RunnerEnum { + fn maybe_runner(&self) -> Option<&Runner> { + match self { + RunnerEnum::Running(runner) => Some(runner), + _ => None, + } + } +} + +struct Runner { + state: State, + event_handler: Box<EventHandler>, +} + +impl Runner { + pub fn new(event_handler: Box<EventHandler>) -> Self { + Runner { state: State::Init, event_handler } + } + + /// Returns the corresponding `StartCause` for the current `state`, or `None` + /// when in `Exit` state. + fn maybe_start_cause(&self) -> Option<StartCause> { + Some(match self.state { + State::Init => StartCause::Init, + State::Poll { .. } => StartCause::Poll, + State::Wait { start } => StartCause::WaitCancelled { start, requested_resume: None }, + State::WaitUntil { start, end, .. } => { + StartCause::WaitCancelled { start, requested_resume: Some(end) } + }, + State::Exit => return None, + }) + } + + fn handle_single_event(&mut self, runner: &Shared, event: impl Into<EventWrapper>) { + match event.into() { + EventWrapper::Event(event) => (self.event_handler)(event), + EventWrapper::ScaleChange { canvas, size, scale } => { + if let Some(canvas) = canvas.upgrade() { + canvas.borrow().handle_scale_change( + runner, + |event| (self.event_handler)(event), + size, + scale, + ) + } + }, + } + } +} + +impl Shared { + pub fn new() -> Self { + let main_thread = MainThreadMarker::new().expect("only callable from inside the `Window`"); + #[allow(clippy::disallowed_methods)] + let window = web_sys::window().expect("only callable from inside the `Window`"); + #[allow(clippy::disallowed_methods)] + let document = window.document().expect("Failed to obtain document"); + + Shared(Rc::<Execution>::new_cyclic(|weak| { + let proxy_spawner = + WakerSpawner::new(main_thread, weak.clone(), |runner, count, local| { + if let Some(runner) = runner.upgrade() { + Shared(runner).send_user_events(count, local) + } + }) + .expect("`EventLoop` has to be created in the main thread"); + + Execution { + main_thread, + proxy_spawner, + control_flow: Cell::new(ControlFlow::default()), + poll_strategy: Cell::new(PollStrategy::default()), + wait_until_strategy: Cell::new(WaitUntilStrategy::default()), + exit: Cell::new(false), + runner: RefCell::new(RunnerEnum::Pending), + suspended: Cell::new(false), + event_loop_recreation: Cell::new(false), + events: RefCell::new(VecDeque::new()), + window, + document, + id: RefCell::new(0), + all_canvases: RefCell::new(Vec::new()), + redraw_pending: RefCell::new(HashSet::new()), + destroy_pending: RefCell::new(VecDeque::new()), + page_transition_event_handle: RefCell::new(None), + device_events: Cell::default(), + on_mouse_move: RefCell::new(None), + on_wheel: RefCell::new(None), + on_mouse_press: RefCell::new(None), + on_mouse_release: RefCell::new(None), + on_key_press: RefCell::new(None), + on_key_release: RefCell::new(None), + on_visibility_change: RefCell::new(None), + } + })) + } + + pub fn main_thread(&self) -> MainThreadMarker { + self.0.main_thread + } + + pub fn window(&self) -> &web_sys::Window { + &self.0.window + } + + pub fn document(&self) -> &Document { + &self.0.document + } + + pub fn add_canvas( + &self, + id: WindowId, + canvas: Weak<RefCell<backend::Canvas>>, + runner: DispatchRunner<Inner>, + ) { + self.0.all_canvases.borrow_mut().push((id, canvas, runner)); + } + + pub fn notify_destroy_window(&self, id: WindowId) { + self.0.destroy_pending.borrow_mut().push_back(id); + } + + // Set the event callback to use for the event loop runner + // This the event callback is a fairly thin layer over the user-provided callback that closes + // over a RootActiveEventLoop reference + pub fn set_listener(&self, event_handler: Box<EventHandler>) { + { + let mut runner = self.0.runner.borrow_mut(); + assert!(matches!(*runner, RunnerEnum::Pending)); + *runner = RunnerEnum::Running(Runner::new(event_handler)); + } + self.init(); + + *self.0.page_transition_event_handle.borrow_mut() = Some(backend::on_page_transition( + self.window().clone(), + { + let runner = self.clone(); + move |event: PageTransitionEvent| { + if event.persisted() { + runner.0.suspended.set(false); + runner.send_event(Event::Resumed); + } + } + }, + { + let runner = self.clone(); + move |event: PageTransitionEvent| { + runner.0.suspended.set(true); + if event.persisted() { + runner.send_event(Event::Suspended); + } else { + runner.handle_unload(); + } + } + }, + )); + + let runner = self.clone(); + let window = self.window().clone(); + *self.0.on_mouse_move.borrow_mut() = Some(EventListenerHandle::new( + self.window().clone(), + "pointermove", + Closure::new(move |event: PointerEvent| { + if !runner.device_events() { + return; + } + + // chorded button event + let device_id = RootDeviceId(DeviceId(event.pointer_id())); + + if let Some(button) = backend::event::mouse_button(&event) { + let state = if backend::event::mouse_buttons(&event).contains(button.into()) { + ElementState::Pressed + } else { + ElementState::Released + }; + + runner.send_event(Event::DeviceEvent { + device_id, + event: DeviceEvent::Button { button: button.to_id(), state }, + }); + + return; + } + + // pointer move event + let mut delta = backend::event::MouseDelta::init(&window, &event); + runner.send_events(backend::event::pointer_move_event(event).flat_map(|event| { + let delta = delta.delta(&event).to_physical(backend::scale_factor(&window)); + + let x_motion = (delta.x != 0.0).then_some(Event::DeviceEvent { + device_id, + event: DeviceEvent::Motion { axis: 0, value: delta.x }, + }); + + let y_motion = (delta.y != 0.0).then_some(Event::DeviceEvent { + device_id, + event: DeviceEvent::Motion { axis: 1, value: delta.y }, + }); + + x_motion.into_iter().chain(y_motion).chain(iter::once(Event::DeviceEvent { + device_id, + event: DeviceEvent::MouseMotion { delta: (delta.x, delta.y) }, + })) + })); + }), + )); + let runner = self.clone(); + let window = self.window().clone(); + *self.0.on_wheel.borrow_mut() = Some(EventListenerHandle::new( + self.window().clone(), + "wheel", + Closure::new(move |event: WheelEvent| { + if !runner.device_events() { + return; + } + + if let Some(delta) = backend::event::mouse_scroll_delta(&window, &event) { + runner.send_event(Event::DeviceEvent { + device_id: RootDeviceId(DeviceId(0)), + event: DeviceEvent::MouseWheel { delta }, + }); + } + }), + )); + let runner = self.clone(); + *self.0.on_mouse_press.borrow_mut() = Some(EventListenerHandle::new( + self.window().clone(), + "pointerdown", + Closure::new(move |event: PointerEvent| { + if !runner.device_events() { + return; + } + + let button = backend::event::mouse_button(&event).expect("no mouse button pressed"); + runner.send_event(Event::DeviceEvent { + device_id: RootDeviceId(DeviceId(event.pointer_id())), + event: DeviceEvent::Button { + button: button.to_id(), + state: ElementState::Pressed, + }, + }); + }), + )); + let runner = self.clone(); + *self.0.on_mouse_release.borrow_mut() = Some(EventListenerHandle::new( + self.window().clone(), + "pointerup", + Closure::new(move |event: PointerEvent| { + if !runner.device_events() { + return; + } + + let button = backend::event::mouse_button(&event).expect("no mouse button pressed"); + runner.send_event(Event::DeviceEvent { + device_id: RootDeviceId(DeviceId(event.pointer_id())), + event: DeviceEvent::Button { + button: button.to_id(), + state: ElementState::Released, + }, + }); + }), + )); + let runner = self.clone(); + *self.0.on_key_press.borrow_mut() = Some(EventListenerHandle::new( + self.window().clone(), + "keydown", + Closure::new(move |event: KeyboardEvent| { + if !runner.device_events() { + return; + } + + runner.send_event(Event::DeviceEvent { + device_id: RootDeviceId(DeviceId::dummy()), + event: DeviceEvent::Key(RawKeyEvent { + physical_key: backend::event::key_code(&event), + state: ElementState::Pressed, + }), + }); + }), + )); + let runner = self.clone(); + *self.0.on_key_release.borrow_mut() = Some(EventListenerHandle::new( + self.window().clone(), + "keyup", + Closure::new(move |event: KeyboardEvent| { + if !runner.device_events() { + return; + } + + runner.send_event(Event::DeviceEvent { + device_id: RootDeviceId(DeviceId::dummy()), + event: DeviceEvent::Key(RawKeyEvent { + physical_key: backend::event::key_code(&event), + state: ElementState::Released, + }), + }); + }), + )); + let runner = self.clone(); + *self.0.on_visibility_change.borrow_mut() = Some(EventListenerHandle::new( + // Safari <14 doesn't support the `visibilitychange` event on `Window`. + self.document().clone(), + "visibilitychange", + Closure::new(move |_| { + if !runner.0.suspended.get() { + for (id, canvas, _) in &*runner.0.all_canvases.borrow() { + if let Some(canvas) = canvas.upgrade() { + let is_visible = backend::is_visible(runner.document()); + // only fire if: + // - not visible and intersects + // - not visible and we don't know if it intersects yet + // - visible and intersects + if let (false, Some(true) | None) | (true, Some(true)) = + (is_visible, canvas.borrow().is_intersecting) + { + runner.send_event(Event::WindowEvent { + window_id: *id, + event: WindowEvent::Occluded(!is_visible), + }); + } + } + } + } + }), + )); + } + + // Generate a strictly increasing ID + // This is used to differentiate windows when handling events + pub fn generate_id(&self) -> u32 { + let mut id = self.0.id.borrow_mut(); + *id += 1; + + *id + } + + pub fn request_redraw(&self, id: WindowId) { + self.0.redraw_pending.borrow_mut().insert(id); + self.send_events::<EventWrapper>(iter::empty()); + } + + pub fn init(&self) { + // NB: For consistency all platforms must emit a 'resumed' event even though web + // applications don't themselves have a formal suspend/resume lifecycle. + self.run_until_cleared([Event::NewEvents(StartCause::Init), Event::Resumed].into_iter()); + } + + // Run the polling logic for the Poll ControlFlow, which involves clearing the queue + pub fn poll(&self) { + let start_cause = Event::NewEvents(StartCause::Poll); + self.run_until_cleared(iter::once(start_cause)); + } + + // Run the logic for waking from a WaitUntil, which involves clearing the queue + // Generally there shouldn't be events built up when this is called + pub fn resume_time_reached(&self, start: Instant, requested_resume: Instant) { + let start_cause = + Event::NewEvents(StartCause::ResumeTimeReached { start, requested_resume }); + self.run_until_cleared(iter::once(start_cause)); + } + + // Add an event to the event loop runner, from the user or an event handler + // + // It will determine if the event should be immediately sent to the user or buffered for later + pub(crate) fn send_event<E: Into<EventWrapper>>(&self, event: E) { + self.send_events(iter::once(event)); + } + + // Add a series of user events to the event loop runner + // + // This will schedule the event loop to wake up instead of waking it up immediately if its not + // running. + pub(crate) fn send_user_events(&self, count: NonZeroUsize, local: bool) { + // If the event loop is closed, it should discard any new events + if self.is_closed() { + return; + } + + if local { + // If the loop is not running and triggered locally, queue on next microtick. + if let Ok(RunnerEnum::Running(_)) = + self.0.runner.try_borrow().as_ref().map(Deref::deref) + { + self.window().queue_microtask( + &Closure::once_into_js({ + let this = Rc::downgrade(&self.0); + move || { + if let Some(shared) = this.upgrade() { + Shared(shared).send_events( + iter::repeat(Event::UserEvent(())).take(count.get()), + ) + } + } + }) + .unchecked_into(), + ); + + return; + } + } + + self.send_events(iter::repeat(Event::UserEvent(())).take(count.get())) + } + + // Add a series of events to the event loop runner + // + // It will determine if the event should be immediately sent to the user or buffered for later + pub(crate) fn send_events<E: Into<EventWrapper>>(&self, events: impl IntoIterator<Item = E>) { + // If the event loop is closed, it should discard any new events + if self.is_closed() { + return; + } + // If we can run the event processing right now, or need to queue this and wait for later + let mut process_immediately = true; + match self.0.runner.try_borrow().as_ref().map(Deref::deref) { + Ok(RunnerEnum::Running(ref runner)) => { + // If we're currently polling, queue this and wait for the poll() method to be + // called. + if let State::Poll { .. } = runner.state { + process_immediately = false; + } + }, + Ok(RunnerEnum::Pending) => { + // The runner still hasn't been attached: queue this event and wait for it to be + process_immediately = false; + }, + // Some other code is mutating the runner, which most likely means + // the event loop is running and busy. So we queue this event for + // it to be processed later. + Err(_) => { + process_immediately = false; + }, + // This is unreachable since `self.is_closed() == true`. + Ok(RunnerEnum::Destroyed) => unreachable!(), + } + if !process_immediately { + // Queue these events to look at later + self.0.events.borrow_mut().extend(events.into_iter().map(Into::into)); + return; + } + // At this point, we know this is a fresh set of events + // Now we determine why new events are incoming, and handle the events + let start_cause = match (self.0.runner.borrow().maybe_runner()) + .unwrap_or_else(|| { + unreachable!("The runner cannot process events when it is not attached") + }) + .maybe_start_cause() + { + Some(c) => c, + // If we're in the exit state, don't do event processing + None => return, + }; + // Take the start event, then the events provided to this function, and run an iteration of + // the event loop + let start_event = Event::NewEvents(start_cause); + let events = + iter::once(EventWrapper::from(start_event)).chain(events.into_iter().map(Into::into)); + self.run_until_cleared(events); + } + + // Process the destroy-pending windows. This should only be called from + // `run_until_cleared`, somewhere between emitting `NewEvents` and `AboutToWait`. + fn process_destroy_pending_windows(&self) { + while let Some(id) = self.0.destroy_pending.borrow_mut().pop_front() { + self.0.all_canvases.borrow_mut().retain(|&(item_id, ..)| item_id != id); + self.handle_event(Event::WindowEvent { + window_id: id, + event: crate::event::WindowEvent::Destroyed, + }); + self.0.redraw_pending.borrow_mut().remove(&id); + } + } + + // Given the set of new events, run the event loop until the main events and redraw events are + // cleared + // + // This will also process any events that have been queued or that are queued during processing + fn run_until_cleared<E: Into<EventWrapper>>(&self, events: impl Iterator<Item = E>) { + for event in events { + self.handle_event(event.into()); + } + self.process_destroy_pending_windows(); + + // Collect all of the redraw events to avoid double-locking the RefCell + let redraw_events: Vec<WindowId> = self.0.redraw_pending.borrow_mut().drain().collect(); + for window_id in redraw_events { + self.handle_event(Event::WindowEvent { + window_id, + event: WindowEvent::RedrawRequested, + }); + } + + self.handle_event(Event::AboutToWait); + + self.apply_control_flow(); + // If the event loop is closed, it has been closed this iteration and now the closing + // event should be emitted + if self.is_closed() { + self.handle_loop_destroyed(); + } + } + + fn handle_unload(&self) { + self.exit(); + self.apply_control_flow(); + // We don't call `handle_loop_destroyed` here because we don't need to + // perform cleanup when the web browser is going to destroy the page. + self.handle_event(Event::LoopExiting); + } + + // handle_event takes in events and either queues them or applies a callback + // + // It should only ever be called from `run_until_cleared`. + fn handle_event(&self, event: impl Into<EventWrapper>) { + if self.is_closed() { + self.exit(); + } + match *self.0.runner.borrow_mut() { + RunnerEnum::Running(ref mut runner) => { + runner.handle_single_event(self, event); + }, + // If an event is being handled without a runner somehow, add it to the event queue so + // it will eventually be processed + RunnerEnum::Pending => self.0.events.borrow_mut().push_back(event.into()), + // If the Runner has been destroyed, there is nothing to do. + RunnerEnum::Destroyed => return, + } + + let is_closed = self.exiting(); + + // Don't take events out of the queue if the loop is closed or the runner doesn't exist + // If the runner doesn't exist and this method recurses, it will recurse infinitely + if !is_closed && self.0.runner.borrow().maybe_runner().is_some() { + // Pre-fetch window commands to avoid having to wait until the next event loop cycle + // and potentially block other threads in the meantime. + for (_, window, runner) in self.0.all_canvases.borrow().iter() { + if let Some(window) = window.upgrade() { + runner.run(); + drop(window) + } + } + + // Take an event out of the queue and handle it + // Make sure not to let the borrow_mut live during the next handle_event + let event = { + let mut events = self.0.events.borrow_mut(); + + // Pre-fetch `UserEvent`s to avoid having to wait until the next event loop cycle. + events.extend( + iter::repeat(Event::UserEvent(())) + .take(self.0.proxy_spawner.fetch()) + .map(EventWrapper::from), + ); + + events.pop_front() + }; + if let Some(event) = event { + self.handle_event(event); + } + } + } + + // Apply the new ControlFlow that has been selected by the user + // Start any necessary timeouts etc + fn apply_control_flow(&self) { + let new_state = if self.exiting() { + State::Exit + } else { + match self.control_flow() { + ControlFlow::Poll => { + let cloned = self.clone(); + State::Poll { + _request: backend::Schedule::new( + self.poll_strategy(), + self.window(), + move || cloned.poll(), + ), + } + }, + ControlFlow::Wait => State::Wait { start: Instant::now() }, + ControlFlow::WaitUntil(end) => { + let start = Instant::now(); + + let delay = if end <= start { Duration::from_millis(0) } else { end - start }; + + let cloned = self.clone(); + + State::WaitUntil { + start, + end, + _timeout: backend::Schedule::new_with_duration( + self.wait_until_strategy(), + self.window(), + move || cloned.resume_time_reached(start, end), + delay, + ), + } + }, + } + }; + + if let RunnerEnum::Running(ref mut runner) = *self.0.runner.borrow_mut() { + runner.state = new_state; + } + } + + fn handle_loop_destroyed(&self) { + self.handle_event(Event::LoopExiting); + let all_canvases = std::mem::take(&mut *self.0.all_canvases.borrow_mut()); + *self.0.page_transition_event_handle.borrow_mut() = None; + *self.0.on_mouse_move.borrow_mut() = None; + *self.0.on_wheel.borrow_mut() = None; + *self.0.on_mouse_press.borrow_mut() = None; + *self.0.on_mouse_release.borrow_mut() = None; + *self.0.on_key_press.borrow_mut() = None; + *self.0.on_key_release.borrow_mut() = None; + *self.0.on_visibility_change.borrow_mut() = None; + // Dropping the `Runner` drops the event handler closure, which will in + // turn drop all `Window`s moved into the closure. + *self.0.runner.borrow_mut() = RunnerEnum::Destroyed; + for (_, canvas, _) in all_canvases { + // In case any remaining `Window`s are still not dropped, we will need + // to explicitly remove the event handlers associated with their canvases. + if let Some(canvas) = canvas.upgrade() { + let mut canvas = canvas.borrow_mut(); + canvas.remove_listeners(); + } + } + // At this point, the `self.0` `Rc` should only be strongly referenced + // by the following: + // * `self`, i.e. the item which triggered this event loop wakeup, which is usually a + // `wasm-bindgen` `Closure`, which will be dropped after returning to the JS glue code. + // * The `ActiveEventLoop` leaked inside `EventLoop::run_app` due to the JS exception thrown + // at the end. + // * For each undropped `Window`: + // * The `register_redraw_request` closure. + // * The `destroy_fn` closure. + if self.0.event_loop_recreation.get() { + crate::event_loop::EventLoopBuilder::<()>::allow_event_loop_recreation(); + } + } + + // Check if the event loop is currently closed + fn is_closed(&self) -> bool { + match self.0.runner.try_borrow().as_ref().map(Deref::deref) { + Ok(RunnerEnum::Running(runner)) => runner.state.exiting(), + // The event loop is not closed since it is not initialized. + Ok(RunnerEnum::Pending) => false, + // The event loop is closed since it has been destroyed. + Ok(RunnerEnum::Destroyed) => true, + // Some other code is mutating the runner, which most likely means + // the event loop is running and busy. + Err(_) => false, + } + } + + pub fn listen_device_events(&self, allowed: DeviceEvents) { + self.0.device_events.set(allowed) + } + + fn device_events(&self) -> bool { + match self.0.device_events.get() { + DeviceEvents::Always => true, + DeviceEvents::WhenFocused => { + self.0.all_canvases.borrow().iter().any(|(_, canvas, _)| { + if let Some(canvas) = canvas.upgrade() { + canvas.borrow().has_focus.get() + } else { + false + } + }) + }, + DeviceEvents::Never => false, + } + } + + pub fn event_loop_recreation(&self, allow: bool) { + self.0.event_loop_recreation.set(allow) + } + + pub(crate) fn control_flow(&self) -> ControlFlow { + self.0.control_flow.get() + } + + pub(crate) fn set_control_flow(&self, control_flow: ControlFlow) { + self.0.control_flow.set(control_flow) + } + + pub(crate) fn exit(&self) { + self.0.exit.set(true) + } + + pub(crate) fn exiting(&self) -> bool { + self.0.exit.get() + } + + pub(crate) fn set_poll_strategy(&self, strategy: PollStrategy) { + self.0.poll_strategy.set(strategy) + } + + pub(crate) fn poll_strategy(&self) -> PollStrategy { + self.0.poll_strategy.get() + } + + pub(crate) fn set_wait_until_strategy(&self, strategy: WaitUntilStrategy) { + self.0.wait_until_strategy.set(strategy) + } + + pub(crate) fn wait_until_strategy(&self) -> WaitUntilStrategy { + self.0.wait_until_strategy.get() + } + + pub(crate) fn waker(&self) -> Waker<Weak<Execution>> { + self.0.proxy_spawner.waker() + } +} + +pub(crate) enum EventWrapper { + Event(Event<()>), + ScaleChange { canvas: Weak<RefCell<backend::Canvas>>, size: PhysicalSize<u32>, scale: f64 }, +} + +impl From<Event<()>> for EventWrapper { + fn from(value: Event<()>) -> Self { + Self::Event(value) + } +} diff --git a/app/vendor/rune/vendor/winit/src/platform_impl/web/event_loop/state.rs b/app/vendor/rune/vendor/winit/src/platform_impl/web/event_loop/state.rs new file mode 100644 index 0000000..d06e30e --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/platform_impl/web/event_loop/state.rs @@ -0,0 +1,18 @@ +use super::backend; + +use web_time::Instant; + +#[derive(Debug)] +pub enum State { + Init, + WaitUntil { _timeout: backend::Schedule, start: Instant, end: Instant }, + Wait { start: Instant }, + Poll { _request: backend::Schedule }, + Exit, +} + +impl State { + pub fn exiting(&self) -> bool { + matches!(self, State::Exit) + } +} diff --git a/app/vendor/rune/vendor/winit/src/platform_impl/web/event_loop/window_target.rs b/app/vendor/rune/vendor/winit/src/platform_impl/web/event_loop/window_target.rs new file mode 100644 index 0000000..d741f09 --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/platform_impl/web/event_loop/window_target.rs @@ -0,0 +1,685 @@ +use std::cell::{Cell, RefCell}; +use std::clone::Clone; +use std::collections::vec_deque::IntoIter as VecDequeIter; +use std::collections::VecDeque; +use std::iter; +use std::rc::{Rc, Weak}; + +use web_sys::Element; + +use super::super::monitor::MonitorHandle; +use super::super::KeyEventExtra; +use super::device::DeviceId; +use super::runner::{EventWrapper, Execution}; +use super::window::WindowId; +use super::{backend, runner}; +use crate::event::{ + DeviceId as RootDeviceId, ElementState, Event, KeyEvent, Touch, TouchPhase, WindowEvent, +}; +use crate::event_loop::{ControlFlow, DeviceEvents}; +use crate::keyboard::ModifiersState; +use crate::platform::web::{CustomCursorFuture, PollStrategy, WaitUntilStrategy}; +use crate::platform_impl::platform::cursor::CustomCursor; +use crate::platform_impl::platform::r#async::Waker; +use crate::window::{ + CustomCursor as RootCustomCursor, CustomCursorSource, Theme, WindowId as RootWindowId, +}; + +#[derive(Default)] +struct ModifiersShared(Rc<Cell<ModifiersState>>); + +impl ModifiersShared { + fn set(&self, new: ModifiersState) { + self.0.set(new) + } + + fn get(&self) -> ModifiersState { + self.0.get() + } +} + +impl Clone for ModifiersShared { + fn clone(&self) -> Self { + Self(Rc::clone(&self.0)) + } +} + +#[derive(Clone)] +pub struct ActiveEventLoop { + pub(crate) runner: runner::Shared, + modifiers: ModifiersShared, +} + +impl ActiveEventLoop { + pub fn new() -> Self { + Self { runner: runner::Shared::new(), modifiers: ModifiersShared::default() } + } + + pub fn run(&self, event_handler: Box<runner::EventHandler>, event_loop_recreation: bool) { + self.runner.event_loop_recreation(event_loop_recreation); + self.runner.set_listener(event_handler); + } + + pub fn generate_id(&self) -> WindowId { + WindowId(self.runner.generate_id()) + } + + pub fn create_custom_cursor(&self, source: CustomCursorSource) -> RootCustomCursor { + RootCustomCursor { inner: CustomCursor::new(self, source.inner) } + } + + pub fn create_custom_cursor_async(&self, source: CustomCursorSource) -> CustomCursorFuture { + CustomCursorFuture(CustomCursor::new_async(self, source.inner)) + } + + pub fn register(&self, canvas: &Rc<RefCell<backend::Canvas>>, id: WindowId) { + let canvas_clone = canvas.clone(); + let mut canvas = canvas.borrow_mut(); + #[cfg(any(feature = "rwh_04", feature = "rwh_05"))] + canvas.set_attribute("data-raw-handle", &id.0.to_string()); + + canvas.on_touch_start(); + + let runner = self.runner.clone(); + let has_focus = canvas.has_focus.clone(); + let modifiers = self.modifiers.clone(); + canvas.on_blur(move || { + has_focus.set(false); + + let clear_modifiers = (!modifiers.get().is_empty()).then(|| { + modifiers.set(ModifiersState::empty()); + Event::WindowEvent { + window_id: RootWindowId(id), + event: WindowEvent::ModifiersChanged(ModifiersState::empty().into()), + } + }); + + runner.send_events(clear_modifiers.into_iter().chain(iter::once(Event::WindowEvent { + window_id: RootWindowId(id), + event: WindowEvent::Focused(false), + }))); + }); + + let runner = self.runner.clone(); + let has_focus = canvas.has_focus.clone(); + canvas.on_focus(move || { + if !has_focus.replace(true) { + runner.send_event(Event::WindowEvent { + window_id: RootWindowId(id), + event: WindowEvent::Focused(true), + }); + } + }); + + // It is possible that at this point the canvas has + // been focused before the callback can be called. + let focused = canvas + .document() + .active_element() + .filter(|element| { + let canvas: &Element = canvas.raw(); + element == canvas + }) + .is_some(); + + if focused { + canvas.has_focus.set(true); + self.runner.send_event(Event::WindowEvent { + window_id: RootWindowId(id), + event: WindowEvent::Focused(true), + }) + } + + let runner = self.runner.clone(); + let modifiers = self.modifiers.clone(); + canvas.on_keyboard_press( + move |physical_key, logical_key, text, location, repeat, active_modifiers| { + let modifiers_changed = (modifiers.get() != active_modifiers).then(|| { + modifiers.set(active_modifiers); + Event::WindowEvent { + window_id: RootWindowId(id), + event: WindowEvent::ModifiersChanged(active_modifiers.into()), + } + }); + + let device_id = RootDeviceId(DeviceId::dummy()); + + runner.send_events( + iter::once(Event::WindowEvent { + window_id: RootWindowId(id), + event: WindowEvent::KeyboardInput { + device_id, + event: KeyEvent { + physical_key, + logical_key, + text, + location, + state: ElementState::Pressed, + repeat, + platform_specific: KeyEventExtra, + }, + is_synthetic: false, + }, + }) + .chain(modifiers_changed), + ); + }, + ); + + let runner = self.runner.clone(); + let modifiers = self.modifiers.clone(); + canvas.on_keyboard_release( + move |physical_key, logical_key, text, location, repeat, active_modifiers| { + let modifiers_changed = (modifiers.get() != active_modifiers).then(|| { + modifiers.set(active_modifiers); + Event::WindowEvent { + window_id: RootWindowId(id), + event: WindowEvent::ModifiersChanged(active_modifiers.into()), + } + }); + + let device_id = RootDeviceId(DeviceId::dummy()); + + runner.send_events( + iter::once(Event::WindowEvent { + window_id: RootWindowId(id), + event: WindowEvent::KeyboardInput { + device_id, + event: KeyEvent { + physical_key, + logical_key, + text, + location, + state: ElementState::Released, + repeat, + platform_specific: KeyEventExtra, + }, + is_synthetic: false, + }, + }) + .chain(modifiers_changed), + ) + }, + ); + + let has_focus = canvas.has_focus.clone(); + canvas.on_cursor_leave({ + let runner = self.runner.clone(); + let has_focus = has_focus.clone(); + let modifiers = self.modifiers.clone(); + + move |active_modifiers, pointer_id| { + let focus = (has_focus.get() && modifiers.get() != active_modifiers).then(|| { + modifiers.set(active_modifiers); + Event::WindowEvent { + window_id: RootWindowId(id), + event: WindowEvent::ModifiersChanged(active_modifiers.into()), + } + }); + + let pointer = pointer_id.map(|pointer_id| Event::WindowEvent { + window_id: RootWindowId(id), + event: WindowEvent::CursorLeft { + device_id: RootDeviceId(DeviceId(pointer_id)), + }, + }); + + if focus.is_some() || pointer.is_some() { + runner.send_events(focus.into_iter().chain(pointer)) + } + } + }); + + canvas.on_cursor_enter({ + let runner = self.runner.clone(); + let has_focus = has_focus.clone(); + let modifiers = self.modifiers.clone(); + + move |active_modifiers, pointer_id| { + let focus = (has_focus.get() && modifiers.get() != active_modifiers).then(|| { + modifiers.set(active_modifiers); + Event::WindowEvent { + window_id: RootWindowId(id), + event: WindowEvent::ModifiersChanged(active_modifiers.into()), + } + }); + + let pointer = pointer_id.map(|pointer_id| Event::WindowEvent { + window_id: RootWindowId(id), + event: WindowEvent::CursorEntered { + device_id: RootDeviceId(DeviceId(pointer_id)), + }, + }); + + if focus.is_some() || pointer.is_some() { + runner.send_events(focus.into_iter().chain(pointer)) + } + } + }); + + canvas.on_cursor_move( + { + let runner = self.runner.clone(); + let has_focus = has_focus.clone(); + let modifiers = self.modifiers.clone(); + + move |active_modifiers, pointer_id, events| { + let modifiers = + (has_focus.get() && modifiers.get() != active_modifiers).then(|| { + modifiers.set(active_modifiers); + Event::WindowEvent { + window_id: RootWindowId(id), + event: WindowEvent::ModifiersChanged(active_modifiers.into()), + } + }); + + runner.send_events(modifiers.into_iter().chain(events.flat_map(|position| { + let device_id = RootDeviceId(DeviceId(pointer_id)); + + iter::once(Event::WindowEvent { + window_id: RootWindowId(id), + event: WindowEvent::CursorMoved { device_id, position }, + }) + }))); + } + }, + { + let runner = self.runner.clone(); + let has_focus = has_focus.clone(); + let modifiers = self.modifiers.clone(); + + move |active_modifiers, device_id, events| { + let modifiers = + (has_focus.get() && modifiers.get() != active_modifiers).then(|| { + modifiers.set(active_modifiers); + Event::WindowEvent { + window_id: RootWindowId(id), + event: WindowEvent::ModifiersChanged(active_modifiers.into()), + } + }); + + runner.send_events(modifiers.into_iter().chain(events.map( + |(location, force)| Event::WindowEvent { + window_id: RootWindowId(id), + event: WindowEvent::Touch(Touch { + id: device_id as u64, + device_id: RootDeviceId(DeviceId(device_id)), + phase: TouchPhase::Moved, + force: Some(force), + location, + }), + }, + ))); + } + }, + { + let runner = self.runner.clone(); + let has_focus = has_focus.clone(); + let modifiers = self.modifiers.clone(); + + move |active_modifiers, + pointer_id, + position: crate::dpi::PhysicalPosition<f64>, + buttons, + button| { + let modifiers = + (has_focus.get() && modifiers.get() != active_modifiers).then(|| { + modifiers.set(active_modifiers); + Event::WindowEvent { + window_id: RootWindowId(id), + event: WindowEvent::ModifiersChanged(active_modifiers.into()), + } + }); + + let device_id = RootDeviceId(DeviceId(pointer_id)); + + let state = if buttons.contains(button.into()) { + ElementState::Pressed + } else { + ElementState::Released + }; + + // A chorded button event may come in without any prior CursorMoved events, + // therefore we should send a CursorMoved event to make sure that the + // user code has the correct cursor position. + runner.send_events(modifiers.into_iter().chain([ + Event::WindowEvent { + window_id: RootWindowId(id), + event: WindowEvent::CursorMoved { device_id, position }, + }, + Event::WindowEvent { + window_id: RootWindowId(id), + event: WindowEvent::MouseInput { device_id, state, button }, + }, + ])); + } + }, + ); + + canvas.on_mouse_press( + { + let runner = self.runner.clone(); + let modifiers = self.modifiers.clone(); + + move |active_modifiers, pointer_id, position, button| { + let modifiers = (modifiers.get() != active_modifiers).then(|| { + modifiers.set(active_modifiers); + Event::WindowEvent { + window_id: RootWindowId(id), + event: WindowEvent::ModifiersChanged(active_modifiers.into()), + } + }); + + let device_id: RootDeviceId = RootDeviceId(DeviceId(pointer_id)); + + // A mouse down event may come in without any prior CursorMoved events, + // therefore we should send a CursorMoved event to make sure that the + // user code has the correct cursor position. + runner.send_events(modifiers.into_iter().chain([ + Event::WindowEvent { + window_id: RootWindowId(id), + event: WindowEvent::CursorMoved { device_id, position }, + }, + Event::WindowEvent { + window_id: RootWindowId(id), + event: WindowEvent::MouseInput { + device_id, + state: ElementState::Pressed, + button, + }, + }, + ])); + } + }, + { + let runner = self.runner.clone(); + let modifiers = self.modifiers.clone(); + + move |active_modifiers, device_id, location, force| { + let modifiers = (modifiers.get() != active_modifiers).then(|| { + modifiers.set(active_modifiers); + Event::WindowEvent { + window_id: RootWindowId(id), + event: WindowEvent::ModifiersChanged(active_modifiers.into()), + } + }); + + runner.send_events(modifiers.into_iter().chain(iter::once( + Event::WindowEvent { + window_id: RootWindowId(id), + event: WindowEvent::Touch(Touch { + id: device_id as u64, + device_id: RootDeviceId(DeviceId(device_id)), + phase: TouchPhase::Started, + force: Some(force), + location, + }), + }, + ))) + } + }, + ); + + canvas.on_mouse_release( + { + let runner = self.runner.clone(); + let has_focus = has_focus.clone(); + let modifiers = self.modifiers.clone(); + + move |active_modifiers, pointer_id, position, button| { + let modifiers = + (has_focus.get() && modifiers.get() != active_modifiers).then(|| { + modifiers.set(active_modifiers); + Event::WindowEvent { + window_id: RootWindowId(id), + event: WindowEvent::ModifiersChanged(active_modifiers.into()), + } + }); + + let device_id: RootDeviceId = RootDeviceId(DeviceId(pointer_id)); + + // A mouse up event may come in without any prior CursorMoved events, + // therefore we should send a CursorMoved event to make sure that the + // user code has the correct cursor position. + runner.send_events(modifiers.into_iter().chain([ + Event::WindowEvent { + window_id: RootWindowId(id), + event: WindowEvent::CursorMoved { device_id, position }, + }, + Event::WindowEvent { + window_id: RootWindowId(id), + event: WindowEvent::MouseInput { + device_id, + state: ElementState::Released, + button, + }, + }, + ])); + } + }, + { + let runner_touch = self.runner.clone(); + let has_focus = has_focus.clone(); + let modifiers = self.modifiers.clone(); + + move |active_modifiers, device_id, location, force| { + let modifiers = + (has_focus.get() && modifiers.get() != active_modifiers).then(|| { + modifiers.set(active_modifiers); + Event::WindowEvent { + window_id: RootWindowId(id), + event: WindowEvent::ModifiersChanged(active_modifiers.into()), + } + }); + + runner_touch.send_events(modifiers.into_iter().chain(iter::once( + Event::WindowEvent { + window_id: RootWindowId(id), + event: WindowEvent::Touch(Touch { + id: device_id as u64, + device_id: RootDeviceId(DeviceId(device_id)), + phase: TouchPhase::Ended, + force: Some(force), + location, + }), + }, + ))); + } + }, + ); + + let runner = self.runner.clone(); + let modifiers = self.modifiers.clone(); + canvas.on_mouse_wheel(move |pointer_id, delta, active_modifiers| { + let modifiers_changed = + (has_focus.get() && modifiers.get() != active_modifiers).then(|| { + modifiers.set(active_modifiers); + Event::WindowEvent { + window_id: RootWindowId(id), + event: WindowEvent::ModifiersChanged(active_modifiers.into()), + } + }); + + runner.send_events(modifiers_changed.into_iter().chain(iter::once( + Event::WindowEvent { + window_id: RootWindowId(id), + event: WindowEvent::MouseWheel { + device_id: RootDeviceId(DeviceId(pointer_id)), + delta, + phase: TouchPhase::Moved, + }, + }, + ))); + }); + + let runner = self.runner.clone(); + canvas.on_touch_cancel(move |device_id, location, force| { + runner.send_event(Event::WindowEvent { + window_id: RootWindowId(id), + event: WindowEvent::Touch(Touch { + id: device_id as u64, + device_id: RootDeviceId(DeviceId(device_id)), + phase: TouchPhase::Cancelled, + force: Some(force), + location, + }), + }); + }); + + let runner = self.runner.clone(); + canvas.on_dark_mode(move |is_dark_mode| { + let theme = if is_dark_mode { Theme::Dark } else { Theme::Light }; + runner.send_event(Event::WindowEvent { + window_id: RootWindowId(id), + event: WindowEvent::ThemeChanged(theme), + }); + }); + + canvas.on_resize_scale( + { + let runner = self.runner.clone(); + let canvas = canvas_clone.clone(); + + move |size, scale| { + runner.send_event(EventWrapper::ScaleChange { + canvas: Rc::downgrade(&canvas), + size, + scale, + }) + } + }, + { + let runner = self.runner.clone(); + let canvas = canvas_clone.clone(); + + move |new_size| { + let canvas = canvas.borrow(); + canvas.set_current_size(new_size); + if canvas.old_size() != new_size { + canvas.set_old_size(new_size); + runner.send_event(Event::WindowEvent { + window_id: RootWindowId(id), + event: WindowEvent::Resized(new_size), + }); + canvas.request_animation_frame(); + } + } + }, + ); + + let runner = self.runner.clone(); + canvas.on_intersection(move |is_intersecting| { + // only fire if visible while skipping the first event if it's intersecting + if backend::is_visible(runner.document()) + && !(is_intersecting && canvas_clone.borrow().is_intersecting.is_none()) + { + runner.send_event(Event::WindowEvent { + window_id: RootWindowId(id), + event: WindowEvent::Occluded(!is_intersecting), + }); + } + + canvas_clone.borrow_mut().is_intersecting = Some(is_intersecting); + }); + + let runner = self.runner.clone(); + canvas.on_animation_frame(move || runner.request_redraw(RootWindowId(id))); + + canvas.on_context_menu(); + } + + pub fn available_monitors(&self) -> VecDequeIter<MonitorHandle> { + VecDeque::new().into_iter() + } + + pub fn primary_monitor(&self) -> Option<MonitorHandle> { + None + } + + #[cfg(feature = "rwh_05")] + #[inline] + pub fn raw_display_handle_rwh_05(&self) -> rwh_05::RawDisplayHandle { + rwh_05::RawDisplayHandle::Web(rwh_05::WebDisplayHandle::empty()) + } + + #[cfg(feature = "rwh_06")] + #[inline] + pub fn raw_display_handle_rwh_06( + &self, + ) -> Result<rwh_06::RawDisplayHandle, rwh_06::HandleError> { + Ok(rwh_06::RawDisplayHandle::Web(rwh_06::WebDisplayHandle::new())) + } + + pub fn listen_device_events(&self, allowed: DeviceEvents) { + self.runner.listen_device_events(allowed) + } + + pub fn system_theme(&self) -> Option<Theme> { + backend::is_dark_mode(self.runner.window()).map(|is_dark_mode| { + if is_dark_mode { + Theme::Dark + } else { + Theme::Light + } + }) + } + + pub(crate) fn set_control_flow(&self, control_flow: ControlFlow) { + self.runner.set_control_flow(control_flow) + } + + pub(crate) fn control_flow(&self) -> ControlFlow { + self.runner.control_flow() + } + + pub(crate) fn exit(&self) { + self.runner.exit() + } + + pub(crate) fn exiting(&self) -> bool { + self.runner.exiting() + } + + pub(crate) fn set_poll_strategy(&self, strategy: PollStrategy) { + self.runner.set_poll_strategy(strategy) + } + + pub(crate) fn poll_strategy(&self) -> PollStrategy { + self.runner.poll_strategy() + } + + pub(crate) fn set_wait_until_strategy(&self, strategy: WaitUntilStrategy) { + self.runner.set_wait_until_strategy(strategy) + } + + pub(crate) fn wait_until_strategy(&self) -> WaitUntilStrategy { + self.runner.wait_until_strategy() + } + + pub(crate) fn waker(&self) -> Waker<Weak<Execution>> { + self.runner.waker() + } + + pub(crate) fn owned_display_handle(&self) -> OwnedDisplayHandle { + OwnedDisplayHandle + } +} + +#[derive(Clone)] +pub(crate) struct OwnedDisplayHandle; + +impl OwnedDisplayHandle { + #[cfg(feature = "rwh_05")] + #[inline] + pub fn raw_display_handle_rwh_05(&self) -> rwh_05::RawDisplayHandle { + rwh_05::WebDisplayHandle::empty().into() + } + + #[cfg(feature = "rwh_06")] + #[inline] + pub fn raw_display_handle_rwh_06( + &self, + ) -> Result<rwh_06::RawDisplayHandle, rwh_06::HandleError> { + Ok(rwh_06::WebDisplayHandle::new().into()) + } +} diff --git a/app/vendor/rune/vendor/winit/src/platform_impl/web/keyboard.rs b/app/vendor/rune/vendor/winit/src/platform_impl/web/keyboard.rs new file mode 100644 index 0000000..6f8d69c --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/platform_impl/web/keyboard.rs @@ -0,0 +1,522 @@ +use smol_str::SmolStr; + +use crate::keyboard::{Key, KeyCode, NamedKey, NativeKey, NativeKeyCode, PhysicalKey}; + +#[derive(Debug, Clone, Eq, PartialEq, Hash)] +pub(crate) struct KeyEventExtra; + +impl Key { + pub(crate) fn from_key_attribute_value(kav: &str) -> Self { + Key::Named(match kav { + "Unidentified" => return Key::Unidentified(NativeKey::Web(SmolStr::new(kav))), + "Dead" => return Key::Dead(None), + "Alt" => NamedKey::Alt, + "AltGraph" => NamedKey::AltGraph, + "CapsLock" => NamedKey::CapsLock, + "Control" => NamedKey::Control, + "Fn" => NamedKey::Fn, + "FnLock" => NamedKey::FnLock, + "NumLock" => NamedKey::NumLock, + "ScrollLock" => NamedKey::ScrollLock, + "Shift" => NamedKey::Shift, + "Symbol" => NamedKey::Symbol, + "SymbolLock" => NamedKey::SymbolLock, + "Hyper" => NamedKey::Hyper, + "Meta" => NamedKey::Super, + "Enter" => NamedKey::Enter, + "Tab" => NamedKey::Tab, + " " => NamedKey::Space, + "ArrowDown" => NamedKey::ArrowDown, + "ArrowLeft" => NamedKey::ArrowLeft, + "ArrowRight" => NamedKey::ArrowRight, + "ArrowUp" => NamedKey::ArrowUp, + "End" => NamedKey::End, + "Home" => NamedKey::Home, + "PageDown" => NamedKey::PageDown, + "PageUp" => NamedKey::PageUp, + "Backspace" => NamedKey::Backspace, + "Clear" => NamedKey::Clear, + "Copy" => NamedKey::Copy, + "CrSel" => NamedKey::CrSel, + "Cut" => NamedKey::Cut, + "Delete" => NamedKey::Delete, + "EraseEof" => NamedKey::EraseEof, + "ExSel" => NamedKey::ExSel, + "Insert" => NamedKey::Insert, + "Paste" => NamedKey::Paste, + "Redo" => NamedKey::Redo, + "Undo" => NamedKey::Undo, + "Accept" => NamedKey::Accept, + "Again" => NamedKey::Again, + "Attn" => NamedKey::Attn, + "Cancel" => NamedKey::Cancel, + "ContextMenu" => NamedKey::ContextMenu, + "Escape" => NamedKey::Escape, + "Execute" => NamedKey::Execute, + "Find" => NamedKey::Find, + "Help" => NamedKey::Help, + "Pause" => NamedKey::Pause, + "Play" => NamedKey::Play, + "Props" => NamedKey::Props, + "Select" => NamedKey::Select, + "ZoomIn" => NamedKey::ZoomIn, + "ZoomOut" => NamedKey::ZoomOut, + "BrightnessDown" => NamedKey::BrightnessDown, + "BrightnessUp" => NamedKey::BrightnessUp, + "Eject" => NamedKey::Eject, + "LogOff" => NamedKey::LogOff, + "Power" => NamedKey::Power, + "PowerOff" => NamedKey::PowerOff, + "PrintScreen" => NamedKey::PrintScreen, + "Hibernate" => NamedKey::Hibernate, + "Standby" => NamedKey::Standby, + "WakeUp" => NamedKey::WakeUp, + "AllCandidates" => NamedKey::AllCandidates, + "Alphanumeric" => NamedKey::Alphanumeric, + "CodeInput" => NamedKey::CodeInput, + "Compose" => NamedKey::Compose, + "Convert" => NamedKey::Convert, + "FinalMode" => NamedKey::FinalMode, + "GroupFirst" => NamedKey::GroupFirst, + "GroupLast" => NamedKey::GroupLast, + "GroupNext" => NamedKey::GroupNext, + "GroupPrevious" => NamedKey::GroupPrevious, + "ModeChange" => NamedKey::ModeChange, + "NextCandidate" => NamedKey::NextCandidate, + "NonConvert" => NamedKey::NonConvert, + "PreviousCandidate" => NamedKey::PreviousCandidate, + "Process" => NamedKey::Process, + "SingleCandidate" => NamedKey::SingleCandidate, + "HangulMode" => NamedKey::HangulMode, + "HanjaMode" => NamedKey::HanjaMode, + "JunjaMode" => NamedKey::JunjaMode, + "Eisu" => NamedKey::Eisu, + "Hankaku" => NamedKey::Hankaku, + "Hiragana" => NamedKey::Hiragana, + "HiraganaKatakana" => NamedKey::HiraganaKatakana, + "KanaMode" => NamedKey::KanaMode, + "KanjiMode" => NamedKey::KanjiMode, + "Katakana" => NamedKey::Katakana, + "Romaji" => NamedKey::Romaji, + "Zenkaku" => NamedKey::Zenkaku, + "ZenkakuHankaku" => NamedKey::ZenkakuHankaku, + "Soft1" => NamedKey::Soft1, + "Soft2" => NamedKey::Soft2, + "Soft3" => NamedKey::Soft3, + "Soft4" => NamedKey::Soft4, + "ChannelDown" => NamedKey::ChannelDown, + "ChannelUp" => NamedKey::ChannelUp, + "Close" => NamedKey::Close, + "MailForward" => NamedKey::MailForward, + "MailReply" => NamedKey::MailReply, + "MailSend" => NamedKey::MailSend, + "MediaClose" => NamedKey::MediaClose, + "MediaFastForward" => NamedKey::MediaFastForward, + "MediaPause" => NamedKey::MediaPause, + "MediaPlay" => NamedKey::MediaPlay, + "MediaPlayPause" => NamedKey::MediaPlayPause, + "MediaRecord" => NamedKey::MediaRecord, + "MediaRewind" => NamedKey::MediaRewind, + "MediaStop" => NamedKey::MediaStop, + "MediaTrackNext" => NamedKey::MediaTrackNext, + "MediaTrackPrevious" => NamedKey::MediaTrackPrevious, + "New" => NamedKey::New, + "Open" => NamedKey::Open, + "Print" => NamedKey::Print, + "Save" => NamedKey::Save, + "SpellCheck" => NamedKey::SpellCheck, + "Key11" => NamedKey::Key11, + "Key12" => NamedKey::Key12, + "AudioBalanceLeft" => NamedKey::AudioBalanceLeft, + "AudioBalanceRight" => NamedKey::AudioBalanceRight, + "AudioBassBoostDown" => NamedKey::AudioBassBoostDown, + "AudioBassBoostToggle" => NamedKey::AudioBassBoostToggle, + "AudioBassBoostUp" => NamedKey::AudioBassBoostUp, + "AudioFaderFront" => NamedKey::AudioFaderFront, + "AudioFaderRear" => NamedKey::AudioFaderRear, + "AudioSurroundModeNext" => NamedKey::AudioSurroundModeNext, + "AudioTrebleDown" => NamedKey::AudioTrebleDown, + "AudioTrebleUp" => NamedKey::AudioTrebleUp, + "AudioVolumeDown" => NamedKey::AudioVolumeDown, + "AudioVolumeUp" => NamedKey::AudioVolumeUp, + "AudioVolumeMute" => NamedKey::AudioVolumeMute, + "MicrophoneToggle" => NamedKey::MicrophoneToggle, + "MicrophoneVolumeDown" => NamedKey::MicrophoneVolumeDown, + "MicrophoneVolumeUp" => NamedKey::MicrophoneVolumeUp, + "MicrophoneVolumeMute" => NamedKey::MicrophoneVolumeMute, + "SpeechCorrectionList" => NamedKey::SpeechCorrectionList, + "SpeechInputToggle" => NamedKey::SpeechInputToggle, + "LaunchApplication1" => NamedKey::LaunchApplication1, + "LaunchApplication2" => NamedKey::LaunchApplication2, + "LaunchCalendar" => NamedKey::LaunchCalendar, + "LaunchContacts" => NamedKey::LaunchContacts, + "LaunchMail" => NamedKey::LaunchMail, + "LaunchMediaPlayer" => NamedKey::LaunchMediaPlayer, + "LaunchMusicPlayer" => NamedKey::LaunchMusicPlayer, + "LaunchPhone" => NamedKey::LaunchPhone, + "LaunchScreenSaver" => NamedKey::LaunchScreenSaver, + "LaunchSpreadsheet" => NamedKey::LaunchSpreadsheet, + "LaunchWebBrowser" => NamedKey::LaunchWebBrowser, + "LaunchWebCam" => NamedKey::LaunchWebCam, + "LaunchWordProcessor" => NamedKey::LaunchWordProcessor, + "BrowserBack" => NamedKey::BrowserBack, + "BrowserFavorites" => NamedKey::BrowserFavorites, + "BrowserForward" => NamedKey::BrowserForward, + "BrowserHome" => NamedKey::BrowserHome, + "BrowserRefresh" => NamedKey::BrowserRefresh, + "BrowserSearch" => NamedKey::BrowserSearch, + "BrowserStop" => NamedKey::BrowserStop, + "AppSwitch" => NamedKey::AppSwitch, + "Call" => NamedKey::Call, + "Camera" => NamedKey::Camera, + "CameraFocus" => NamedKey::CameraFocus, + "EndCall" => NamedKey::EndCall, + "GoBack" => NamedKey::GoBack, + "GoHome" => NamedKey::GoHome, + "HeadsetHook" => NamedKey::HeadsetHook, + "LastNumberRedial" => NamedKey::LastNumberRedial, + "Notification" => NamedKey::Notification, + "MannerMode" => NamedKey::MannerMode, + "VoiceDial" => NamedKey::VoiceDial, + "TV" => NamedKey::TV, + "TV3DMode" => NamedKey::TV3DMode, + "TVAntennaCable" => NamedKey::TVAntennaCable, + "TVAudioDescription" => NamedKey::TVAudioDescription, + "TVAudioDescriptionMixDown" => NamedKey::TVAudioDescriptionMixDown, + "TVAudioDescriptionMixUp" => NamedKey::TVAudioDescriptionMixUp, + "TVContentsMenu" => NamedKey::TVContentsMenu, + "TVDataService" => NamedKey::TVDataService, + "TVInput" => NamedKey::TVInput, + "TVInputComponent1" => NamedKey::TVInputComponent1, + "TVInputComponent2" => NamedKey::TVInputComponent2, + "TVInputComposite1" => NamedKey::TVInputComposite1, + "TVInputComposite2" => NamedKey::TVInputComposite2, + "TVInputHDMI1" => NamedKey::TVInputHDMI1, + "TVInputHDMI2" => NamedKey::TVInputHDMI2, + "TVInputHDMI3" => NamedKey::TVInputHDMI3, + "TVInputHDMI4" => NamedKey::TVInputHDMI4, + "TVInputVGA1" => NamedKey::TVInputVGA1, + "TVMediaContext" => NamedKey::TVMediaContext, + "TVNetwork" => NamedKey::TVNetwork, + "TVNumberEntry" => NamedKey::TVNumberEntry, + "TVPower" => NamedKey::TVPower, + "TVRadioService" => NamedKey::TVRadioService, + "TVSatellite" => NamedKey::TVSatellite, + "TVSatelliteBS" => NamedKey::TVSatelliteBS, + "TVSatelliteCS" => NamedKey::TVSatelliteCS, + "TVSatelliteToggle" => NamedKey::TVSatelliteToggle, + "TVTerrestrialAnalog" => NamedKey::TVTerrestrialAnalog, + "TVTerrestrialDigital" => NamedKey::TVTerrestrialDigital, + "TVTimer" => NamedKey::TVTimer, + "AVRInput" => NamedKey::AVRInput, + "AVRPower" => NamedKey::AVRPower, + "ColorF0Red" => NamedKey::ColorF0Red, + "ColorF1Green" => NamedKey::ColorF1Green, + "ColorF2Yellow" => NamedKey::ColorF2Yellow, + "ColorF3Blue" => NamedKey::ColorF3Blue, + "ColorF4Grey" => NamedKey::ColorF4Grey, + "ColorF5Brown" => NamedKey::ColorF5Brown, + "ClosedCaptionToggle" => NamedKey::ClosedCaptionToggle, + "Dimmer" => NamedKey::Dimmer, + "DisplaySwap" => NamedKey::DisplaySwap, + "DVR" => NamedKey::DVR, + "Exit" => NamedKey::Exit, + "FavoriteClear0" => NamedKey::FavoriteClear0, + "FavoriteClear1" => NamedKey::FavoriteClear1, + "FavoriteClear2" => NamedKey::FavoriteClear2, + "FavoriteClear3" => NamedKey::FavoriteClear3, + "FavoriteRecall0" => NamedKey::FavoriteRecall0, + "FavoriteRecall1" => NamedKey::FavoriteRecall1, + "FavoriteRecall2" => NamedKey::FavoriteRecall2, + "FavoriteRecall3" => NamedKey::FavoriteRecall3, + "FavoriteStore0" => NamedKey::FavoriteStore0, + "FavoriteStore1" => NamedKey::FavoriteStore1, + "FavoriteStore2" => NamedKey::FavoriteStore2, + "FavoriteStore3" => NamedKey::FavoriteStore3, + "Guide" => NamedKey::Guide, + "GuideNextDay" => NamedKey::GuideNextDay, + "GuidePreviousDay" => NamedKey::GuidePreviousDay, + "Info" => NamedKey::Info, + "InstantReplay" => NamedKey::InstantReplay, + "Link" => NamedKey::Link, + "ListProgram" => NamedKey::ListProgram, + "LiveContent" => NamedKey::LiveContent, + "Lock" => NamedKey::Lock, + "MediaApps" => NamedKey::MediaApps, + "MediaAudioTrack" => NamedKey::MediaAudioTrack, + "MediaLast" => NamedKey::MediaLast, + "MediaSkipBackward" => NamedKey::MediaSkipBackward, + "MediaSkipForward" => NamedKey::MediaSkipForward, + "MediaStepBackward" => NamedKey::MediaStepBackward, + "MediaStepForward" => NamedKey::MediaStepForward, + "MediaTopMenu" => NamedKey::MediaTopMenu, + "NavigateIn" => NamedKey::NavigateIn, + "NavigateNext" => NamedKey::NavigateNext, + "NavigateOut" => NamedKey::NavigateOut, + "NavigatePrevious" => NamedKey::NavigatePrevious, + "NextFavoriteChannel" => NamedKey::NextFavoriteChannel, + "NextUserProfile" => NamedKey::NextUserProfile, + "OnDemand" => NamedKey::OnDemand, + "Pairing" => NamedKey::Pairing, + "PinPDown" => NamedKey::PinPDown, + "PinPMove" => NamedKey::PinPMove, + "PinPToggle" => NamedKey::PinPToggle, + "PinPUp" => NamedKey::PinPUp, + "PlaySpeedDown" => NamedKey::PlaySpeedDown, + "PlaySpeedReset" => NamedKey::PlaySpeedReset, + "PlaySpeedUp" => NamedKey::PlaySpeedUp, + "RandomToggle" => NamedKey::RandomToggle, + "RcLowBattery" => NamedKey::RcLowBattery, + "RecordSpeedNext" => NamedKey::RecordSpeedNext, + "RfBypass" => NamedKey::RfBypass, + "ScanChannelsToggle" => NamedKey::ScanChannelsToggle, + "ScreenModeNext" => NamedKey::ScreenModeNext, + "Settings" => NamedKey::Settings, + "SplitScreenToggle" => NamedKey::SplitScreenToggle, + "STBInput" => NamedKey::STBInput, + "STBPower" => NamedKey::STBPower, + "Subtitle" => NamedKey::Subtitle, + "Teletext" => NamedKey::Teletext, + "VideoModeNext" => NamedKey::VideoModeNext, + "Wink" => NamedKey::Wink, + "ZoomToggle" => NamedKey::ZoomToggle, + "F1" => NamedKey::F1, + "F2" => NamedKey::F2, + "F3" => NamedKey::F3, + "F4" => NamedKey::F4, + "F5" => NamedKey::F5, + "F6" => NamedKey::F6, + "F7" => NamedKey::F7, + "F8" => NamedKey::F8, + "F9" => NamedKey::F9, + "F10" => NamedKey::F10, + "F11" => NamedKey::F11, + "F12" => NamedKey::F12, + "F13" => NamedKey::F13, + "F14" => NamedKey::F14, + "F15" => NamedKey::F15, + "F16" => NamedKey::F16, + "F17" => NamedKey::F17, + "F18" => NamedKey::F18, + "F19" => NamedKey::F19, + "F20" => NamedKey::F20, + "F21" => NamedKey::F21, + "F22" => NamedKey::F22, + "F23" => NamedKey::F23, + "F24" => NamedKey::F24, + "F25" => NamedKey::F25, + "F26" => NamedKey::F26, + "F27" => NamedKey::F27, + "F28" => NamedKey::F28, + "F29" => NamedKey::F29, + "F30" => NamedKey::F30, + "F31" => NamedKey::F31, + "F32" => NamedKey::F32, + "F33" => NamedKey::F33, + "F34" => NamedKey::F34, + "F35" => NamedKey::F35, + string => return Key::Character(SmolStr::new(string)), + }) + } +} + +impl PhysicalKey { + pub fn from_key_code_attribute_value(kcav: &str) -> Self { + PhysicalKey::Code(match kcav { + "Backquote" => KeyCode::Backquote, + "Backslash" => KeyCode::Backslash, + "BracketLeft" => KeyCode::BracketLeft, + "BracketRight" => KeyCode::BracketRight, + "Comma" => KeyCode::Comma, + "Digit0" => KeyCode::Digit0, + "Digit1" => KeyCode::Digit1, + "Digit2" => KeyCode::Digit2, + "Digit3" => KeyCode::Digit3, + "Digit4" => KeyCode::Digit4, + "Digit5" => KeyCode::Digit5, + "Digit6" => KeyCode::Digit6, + "Digit7" => KeyCode::Digit7, + "Digit8" => KeyCode::Digit8, + "Digit9" => KeyCode::Digit9, + "Equal" => KeyCode::Equal, + "IntlBackslash" => KeyCode::IntlBackslash, + "IntlRo" => KeyCode::IntlRo, + "IntlYen" => KeyCode::IntlYen, + "KeyA" => KeyCode::KeyA, + "KeyB" => KeyCode::KeyB, + "KeyC" => KeyCode::KeyC, + "KeyD" => KeyCode::KeyD, + "KeyE" => KeyCode::KeyE, + "KeyF" => KeyCode::KeyF, + "KeyG" => KeyCode::KeyG, + "KeyH" => KeyCode::KeyH, + "KeyI" => KeyCode::KeyI, + "KeyJ" => KeyCode::KeyJ, + "KeyK" => KeyCode::KeyK, + "KeyL" => KeyCode::KeyL, + "KeyM" => KeyCode::KeyM, + "KeyN" => KeyCode::KeyN, + "KeyO" => KeyCode::KeyO, + "KeyP" => KeyCode::KeyP, + "KeyQ" => KeyCode::KeyQ, + "KeyR" => KeyCode::KeyR, + "KeyS" => KeyCode::KeyS, + "KeyT" => KeyCode::KeyT, + "KeyU" => KeyCode::KeyU, + "KeyV" => KeyCode::KeyV, + "KeyW" => KeyCode::KeyW, + "KeyX" => KeyCode::KeyX, + "KeyY" => KeyCode::KeyY, + "KeyZ" => KeyCode::KeyZ, + "Minus" => KeyCode::Minus, + "Period" => KeyCode::Period, + "Quote" => KeyCode::Quote, + "Semicolon" => KeyCode::Semicolon, + "Slash" => KeyCode::Slash, + "AltLeft" => KeyCode::AltLeft, + "AltRight" => KeyCode::AltRight, + "Backspace" => KeyCode::Backspace, + "CapsLock" => KeyCode::CapsLock, + "ContextMenu" => KeyCode::ContextMenu, + "ControlLeft" => KeyCode::ControlLeft, + "ControlRight" => KeyCode::ControlRight, + "Enter" => KeyCode::Enter, + "MetaLeft" => KeyCode::SuperLeft, + "MetaRight" => KeyCode::SuperRight, + "ShiftLeft" => KeyCode::ShiftLeft, + "ShiftRight" => KeyCode::ShiftRight, + "Space" => KeyCode::Space, + "Tab" => KeyCode::Tab, + "Convert" => KeyCode::Convert, + "KanaMode" => KeyCode::KanaMode, + "Lang1" => KeyCode::Lang1, + "Lang2" => KeyCode::Lang2, + "Lang3" => KeyCode::Lang3, + "Lang4" => KeyCode::Lang4, + "Lang5" => KeyCode::Lang5, + "NonConvert" => KeyCode::NonConvert, + "Delete" => KeyCode::Delete, + "End" => KeyCode::End, + "Help" => KeyCode::Help, + "Home" => KeyCode::Home, + "Insert" => KeyCode::Insert, + "PageDown" => KeyCode::PageDown, + "PageUp" => KeyCode::PageUp, + "ArrowDown" => KeyCode::ArrowDown, + "ArrowLeft" => KeyCode::ArrowLeft, + "ArrowRight" => KeyCode::ArrowRight, + "ArrowUp" => KeyCode::ArrowUp, + "NumLock" => KeyCode::NumLock, + "Numpad0" => KeyCode::Numpad0, + "Numpad1" => KeyCode::Numpad1, + "Numpad2" => KeyCode::Numpad2, + "Numpad3" => KeyCode::Numpad3, + "Numpad4" => KeyCode::Numpad4, + "Numpad5" => KeyCode::Numpad5, + "Numpad6" => KeyCode::Numpad6, + "Numpad7" => KeyCode::Numpad7, + "Numpad8" => KeyCode::Numpad8, + "Numpad9" => KeyCode::Numpad9, + "NumpadAdd" => KeyCode::NumpadAdd, + "NumpadBackspace" => KeyCode::NumpadBackspace, + "NumpadClear" => KeyCode::NumpadClear, + "NumpadClearEntry" => KeyCode::NumpadClearEntry, + "NumpadComma" => KeyCode::NumpadComma, + "NumpadDecimal" => KeyCode::NumpadDecimal, + "NumpadDivide" => KeyCode::NumpadDivide, + "NumpadEnter" => KeyCode::NumpadEnter, + "NumpadEqual" => KeyCode::NumpadEqual, + "NumpadHash" => KeyCode::NumpadHash, + "NumpadMemoryAdd" => KeyCode::NumpadMemoryAdd, + "NumpadMemoryClear" => KeyCode::NumpadMemoryClear, + "NumpadMemoryRecall" => KeyCode::NumpadMemoryRecall, + "NumpadMemoryStore" => KeyCode::NumpadMemoryStore, + "NumpadMemorySubtract" => KeyCode::NumpadMemorySubtract, + "NumpadMultiply" => KeyCode::NumpadMultiply, + "NumpadParenLeft" => KeyCode::NumpadParenLeft, + "NumpadParenRight" => KeyCode::NumpadParenRight, + "NumpadStar" => KeyCode::NumpadStar, + "NumpadSubtract" => KeyCode::NumpadSubtract, + "Escape" => KeyCode::Escape, + "Fn" => KeyCode::Fn, + "FnLock" => KeyCode::FnLock, + "PrintScreen" => KeyCode::PrintScreen, + "ScrollLock" => KeyCode::ScrollLock, + "Pause" => KeyCode::Pause, + "BrowserBack" => KeyCode::BrowserBack, + "BrowserFavorites" => KeyCode::BrowserFavorites, + "BrowserForward" => KeyCode::BrowserForward, + "BrowserHome" => KeyCode::BrowserHome, + "BrowserRefresh" => KeyCode::BrowserRefresh, + "BrowserSearch" => KeyCode::BrowserSearch, + "BrowserStop" => KeyCode::BrowserStop, + "Eject" => KeyCode::Eject, + "LaunchApp1" => KeyCode::LaunchApp1, + "LaunchApp2" => KeyCode::LaunchApp2, + "LaunchMail" => KeyCode::LaunchMail, + "MediaPlayPause" => KeyCode::MediaPlayPause, + "MediaSelect" => KeyCode::MediaSelect, + "MediaStop" => KeyCode::MediaStop, + "MediaTrackNext" => KeyCode::MediaTrackNext, + "MediaTrackPrevious" => KeyCode::MediaTrackPrevious, + "Power" => KeyCode::Power, + "Sleep" => KeyCode::Sleep, + "AudioVolumeDown" => KeyCode::AudioVolumeDown, + "AudioVolumeMute" => KeyCode::AudioVolumeMute, + "AudioVolumeUp" => KeyCode::AudioVolumeUp, + "WakeUp" => KeyCode::WakeUp, + "Hyper" => KeyCode::Hyper, + "Turbo" => KeyCode::Turbo, + "Abort" => KeyCode::Abort, + "Resume" => KeyCode::Resume, + "Suspend" => KeyCode::Suspend, + "Again" => KeyCode::Again, + "Copy" => KeyCode::Copy, + "Cut" => KeyCode::Cut, + "Find" => KeyCode::Find, + "Open" => KeyCode::Open, + "Paste" => KeyCode::Paste, + "Props" => KeyCode::Props, + "Select" => KeyCode::Select, + "Undo" => KeyCode::Undo, + "Hiragana" => KeyCode::Hiragana, + "Katakana" => KeyCode::Katakana, + "F1" => KeyCode::F1, + "F2" => KeyCode::F2, + "F3" => KeyCode::F3, + "F4" => KeyCode::F4, + "F5" => KeyCode::F5, + "F6" => KeyCode::F6, + "F7" => KeyCode::F7, + "F8" => KeyCode::F8, + "F9" => KeyCode::F9, + "F10" => KeyCode::F10, + "F11" => KeyCode::F11, + "F12" => KeyCode::F12, + "F13" => KeyCode::F13, + "F14" => KeyCode::F14, + "F15" => KeyCode::F15, + "F16" => KeyCode::F16, + "F17" => KeyCode::F17, + "F18" => KeyCode::F18, + "F19" => KeyCode::F19, + "F20" => KeyCode::F20, + "F21" => KeyCode::F21, + "F22" => KeyCode::F22, + "F23" => KeyCode::F23, + "F24" => KeyCode::F24, + "F25" => KeyCode::F25, + "F26" => KeyCode::F26, + "F27" => KeyCode::F27, + "F28" => KeyCode::F28, + "F29" => KeyCode::F29, + "F30" => KeyCode::F30, + "F31" => KeyCode::F31, + "F32" => KeyCode::F32, + "F33" => KeyCode::F33, + "F34" => KeyCode::F34, + "F35" => KeyCode::F35, + _ => return PhysicalKey::Unidentified(NativeKeyCode::Unidentified), + }) + } +} diff --git a/app/vendor/rune/vendor/winit/src/platform_impl/web/main_thread.rs b/app/vendor/rune/vendor/winit/src/platform_impl/web/main_thread.rs new file mode 100644 index 0000000..59a2ac5 --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/platform_impl/web/main_thread.rs @@ -0,0 +1,96 @@ +use std::fmt::{self, Debug, Formatter}; +use std::marker::PhantomData; +use std::mem; +use std::sync::OnceLock; + +use wasm_bindgen::prelude::wasm_bindgen; +use wasm_bindgen::{JsCast, JsValue}; + +use super::r#async::{self, Sender}; + +thread_local! { + static MAIN_THREAD: bool = { + #[wasm_bindgen] + extern "C" { + #[derive(Clone)] + type Global; + + #[wasm_bindgen(method, getter, js_name = Window)] + fn window(this: &Global) -> JsValue; + } + + let global: Global = js_sys::global().unchecked_into(); + !global.window().is_undefined() + }; +} + +#[derive(Clone, Copy, Debug)] +pub struct MainThreadMarker(PhantomData<*const ()>); + +impl MainThreadMarker { + pub fn new() -> Option<Self> { + MAIN_THREAD.with(|is| is.then_some(Self(PhantomData))) + } +} + +pub struct MainThreadSafe<T: 'static>(Option<T>); + +impl<T> MainThreadSafe<T> { + pub fn new(_: MainThreadMarker, value: T) -> Self { + DROP_HANDLER.get_or_init(|| { + let (sender, receiver) = r#async::channel(); + wasm_bindgen_futures::spawn_local( + async move { while receiver.next().await.is_ok() {} }, + ); + + sender + }); + + Self(Some(value)) + } + + pub fn into_inner(mut self, _: MainThreadMarker) -> T { + self.0.take().expect("already taken or dropped") + } + + pub fn get(&self, _: MainThreadMarker) -> &T { + self.0.as_ref().expect("already taken or dropped") + } +} + +impl<T: Debug> Debug for MainThreadSafe<T> { + fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { + if MainThreadMarker::new().is_some() { + f.debug_tuple("MainThreadSafe").field(&self.0).finish() + } else { + f.debug_struct("MainThreadSafe").finish_non_exhaustive() + } + } +} + +impl<T> Drop for MainThreadSafe<T> { + fn drop(&mut self) { + if let Some(value) = self.0.take() { + if mem::needs_drop::<T>() && MainThreadMarker::new().is_none() { + DROP_HANDLER + .get() + .expect("drop handler not initialized when setting canvas") + .send(DropBox(Box::new(value))) + .expect("sender dropped in main thread") + } + } + } +} + +unsafe impl<T> Send for MainThreadSafe<T> {} +unsafe impl<T> Sync for MainThreadSafe<T> {} + +static DROP_HANDLER: OnceLock<Sender<DropBox>> = OnceLock::new(); + +struct DropBox(#[allow(dead_code)] Box<dyn Any>); + +unsafe impl Send for DropBox {} +unsafe impl Sync for DropBox {} + +trait Any {} +impl<T> Any for T {} diff --git a/app/vendor/rune/vendor/winit/src/platform_impl/web/mod.rs b/app/vendor/rune/vendor/winit/src/platform_impl/web/mod.rs new file mode 100644 index 0000000..969d8bb --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/platform_impl/web/mod.rs @@ -0,0 +1,50 @@ +// Brief introduction to the internals of the web backend: +// The web backend used to support both wasm-bindgen and stdweb as methods of binding to the +// environment. Because they are both supporting the same underlying APIs, the actual web bindings +// are cordoned off into backend abstractions, which present the thinnest unifying layer possible. +// +// When adding support for new events or interactions with the browser, first consult trusted +// documentation (such as MDN) to ensure it is well-standardised and supported across many browsers. +// Once you have decided on the relevant web APIs, add support to both backends. +// +// The backend is used by the rest of the module to implement Winit's business logic, which forms +// the rest of the code. 'device', 'error', 'monitor', and 'window' define web-specific structures +// for winit's cross-platform structures. They are all relatively simple translations. +// +// The event_loop module handles listening for and processing events. 'Proxy' implements +// EventLoopProxy and 'WindowTarget' implements ActiveEventLoop. WindowTarget also handles +// registering the event handlers. The 'Execution' struct in the 'runner' module handles taking +// incoming events (from the registered handlers) and ensuring they are passed to the user in a +// compliant way. + +// TODO: FP, remove when <https://github.com/rust-lang/rust-clippy/issues/12377> is fixed. +#![allow(clippy::empty_docs)] + +mod r#async; +mod cursor; +mod device; +mod error; +mod event_loop; +mod keyboard; +mod main_thread; +mod monitor; +mod web_sys; +mod window; + +pub use self::device::DeviceId; +pub use self::error::OsError; +pub(crate) use self::event_loop::{ + ActiveEventLoop, EventLoop, EventLoopProxy, OwnedDisplayHandle, + PlatformSpecificEventLoopAttributes, +}; +pub use self::monitor::{MonitorHandle, VideoModeHandle}; +pub use self::window::{PlatformSpecificWindowAttributes, Window, WindowId}; + +pub(crate) use self::keyboard::KeyEventExtra; +use self::web_sys as backend; +pub(crate) use crate::icon::NoIcon as PlatformIcon; +pub(crate) use crate::platform_impl::Fullscreen; +pub(crate) use cursor::{ + CustomCursor as PlatformCustomCursor, CustomCursorFuture, + CustomCursorSource as PlatformCustomCursorSource, +}; diff --git a/app/vendor/rune/vendor/winit/src/platform_impl/web/monitor.rs b/app/vendor/rune/vendor/winit/src/platform_impl/web/monitor.rs new file mode 100644 index 0000000..1870284 --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/platform_impl/web/monitor.rs @@ -0,0 +1,53 @@ +use std::iter::Empty; + +use crate::dpi::{PhysicalPosition, PhysicalSize}; + +#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub struct MonitorHandle; + +impl MonitorHandle { + pub fn scale_factor(&self) -> f64 { + unreachable!() + } + + pub fn position(&self) -> PhysicalPosition<i32> { + unreachable!() + } + + pub fn name(&self) -> Option<String> { + unreachable!() + } + + pub fn refresh_rate_millihertz(&self) -> Option<u32> { + unreachable!() + } + + pub fn size(&self) -> PhysicalSize<u32> { + unreachable!() + } + + pub fn video_modes(&self) -> Empty<VideoModeHandle> { + unreachable!() + } +} + +#[derive(Clone, Debug, PartialEq, Eq, Hash)] +pub struct VideoModeHandle; + +impl VideoModeHandle { + pub fn size(&self) -> PhysicalSize<u32> { + unreachable!(); + } + + pub fn bit_depth(&self) -> u16 { + unreachable!(); + } + + pub fn refresh_rate_millihertz(&self) -> u32 { + unreachable!(); + } + + pub fn monitor(&self) -> MonitorHandle { + unreachable!(); + } +} diff --git a/app/vendor/rune/vendor/winit/src/platform_impl/web/web_sys/animation_frame.rs b/app/vendor/rune/vendor/winit/src/platform_impl/web/web_sys/animation_frame.rs new file mode 100644 index 0000000..17aa8f6 --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/platform_impl/web/web_sys/animation_frame.rs @@ -0,0 +1,60 @@ +use std::cell::Cell; +use std::rc::Rc; +use wasm_bindgen::closure::Closure; +use wasm_bindgen::JsCast; + +pub struct AnimationFrameHandler { + window: web_sys::Window, + closure: Closure<dyn FnMut()>, + handle: Rc<Cell<Option<i32>>>, +} + +impl AnimationFrameHandler { + pub fn new(window: web_sys::Window) -> Self { + let handle = Rc::new(Cell::new(None)); + let closure = Closure::new({ + let handle = handle.clone(); + move || handle.set(None) + }); + + Self { window, closure, handle } + } + + pub fn on_animation_frame<F>(&mut self, mut f: F) + where + F: 'static + FnMut(), + { + let handle = self.handle.clone(); + self.closure = Closure::new(move || { + handle.set(None); + f(); + }) + } + + pub fn request(&self) { + if let Some(handle) = self.handle.take() { + self.window.cancel_animation_frame(handle).expect("Failed to cancel animation frame"); + } + + let handle = self + .window + .request_animation_frame(self.closure.as_ref().unchecked_ref()) + .expect("Failed to request animation frame"); + + self.handle.set(Some(handle)); + } + + pub fn cancel(&mut self) { + if let Some(handle) = self.handle.take() { + self.window.cancel_animation_frame(handle).expect("Failed to cancel animation frame"); + } + } +} + +impl Drop for AnimationFrameHandler { + fn drop(&mut self) { + if let Some(handle) = self.handle.take() { + self.window.cancel_animation_frame(handle).expect("Failed to cancel animation frame"); + } + } +} diff --git a/app/vendor/rune/vendor/winit/src/platform_impl/web/web_sys/canvas.rs b/app/vendor/rune/vendor/winit/src/platform_impl/web/web_sys/canvas.rs new file mode 100644 index 0000000..84dde9f --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/platform_impl/web/web_sys/canvas.rs @@ -0,0 +1,565 @@ +use std::cell::Cell; +use std::ops::Deref; +use std::rc::Rc; +use std::sync::{Arc, Mutex}; + +use smol_str::SmolStr; +use wasm_bindgen::closure::Closure; +use wasm_bindgen::JsCast; +use web_sys::{ + CssStyleDeclaration, Document, Event, FocusEvent, HtmlCanvasElement, KeyboardEvent, + PointerEvent, WheelEvent, +}; + +use crate::dpi::{LogicalPosition, PhysicalPosition, PhysicalSize}; +use crate::error::OsError as RootOE; +use crate::event::{Force, InnerSizeWriter, MouseButton, MouseScrollDelta}; +use crate::keyboard::{Key, KeyLocation, ModifiersState, PhysicalKey}; +use crate::platform_impl::OsError; +use crate::window::{WindowAttributes, WindowId as RootWindowId}; + +use super::super::cursor::CursorHandler; +use super::super::main_thread::MainThreadMarker; +use super::super::WindowId; +use super::animation_frame::AnimationFrameHandler; +use super::event_handle::EventListenerHandle; +use super::intersection_handle::IntersectionObserverHandle; +use super::media_query_handle::MediaQueryListHandle; +use super::pointer::PointerHandler; +use super::{event, fullscreen, ButtonsState, ResizeScaleHandle}; + +#[allow(dead_code)] +pub struct Canvas { + common: Common, + id: WindowId, + pub has_focus: Rc<Cell<bool>>, + pub prevent_default: Rc<Cell<bool>>, + pub is_intersecting: Option<bool>, + on_touch_start: Option<EventListenerHandle<dyn FnMut(Event)>>, + on_focus: Option<EventListenerHandle<dyn FnMut(FocusEvent)>>, + on_blur: Option<EventListenerHandle<dyn FnMut(FocusEvent)>>, + on_keyboard_release: Option<EventListenerHandle<dyn FnMut(KeyboardEvent)>>, + on_keyboard_press: Option<EventListenerHandle<dyn FnMut(KeyboardEvent)>>, + on_mouse_wheel: Option<EventListenerHandle<dyn FnMut(WheelEvent)>>, + on_dark_mode: Option<MediaQueryListHandle>, + pointer_handler: PointerHandler, + on_resize_scale: Option<ResizeScaleHandle>, + on_intersect: Option<IntersectionObserverHandle>, + animation_frame_handler: AnimationFrameHandler, + on_touch_end: Option<EventListenerHandle<dyn FnMut(Event)>>, + on_context_menu: Option<EventListenerHandle<dyn FnMut(PointerEvent)>>, + pub cursor: CursorHandler, +} + +pub struct Common { + pub window: web_sys::Window, + pub document: Document, + /// Note: resizing the HTMLCanvasElement should go through `backend::set_canvas_size` to ensure + /// the DPI factor is maintained. Note: this is read-only because we use a pointer to this + /// for [`WindowHandle`][rwh_06::WindowHandle]. + raw: Rc<HtmlCanvasElement>, + style: Style, + old_size: Rc<Cell<PhysicalSize<u32>>>, + current_size: Rc<Cell<PhysicalSize<u32>>>, +} + +#[derive(Clone, Debug)] +pub struct Style { + read: CssStyleDeclaration, + write: CssStyleDeclaration, +} + +impl Canvas { + pub(crate) fn create( + main_thread: MainThreadMarker, + id: WindowId, + window: web_sys::Window, + document: Document, + attr: &mut WindowAttributes, + ) -> Result<Self, RootOE> { + let canvas = match attr.platform_specific.canvas.take().map(|canvas| { + Arc::try_unwrap(canvas) + .map(|canvas| canvas.into_inner(main_thread)) + .unwrap_or_else(|canvas| canvas.get(main_thread).clone()) + }) { + Some(canvas) => canvas, + None => document + .create_element("canvas") + .map_err(|_| os_error!(OsError("Failed to create canvas element".to_owned())))? + .unchecked_into(), + }; + + if attr.platform_specific.append && !document.contains(Some(&canvas)) { + document + .body() + .expect("Failed to get body from document") + .append_child(&canvas) + .expect("Failed to append canvas to body"); + } + + // A tabindex is needed in order to capture local keyboard events. + // A "0" value means that the element should be focusable in + // sequential keyboard navigation, but its order is defined by the + // document's source order. + // https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/tabindex + if attr.platform_specific.focusable { + canvas + .set_attribute("tabindex", "0") + .map_err(|_| os_error!(OsError("Failed to set a tabindex".to_owned())))?; + } + + let style = Style::new(&window, &canvas); + + let cursor = CursorHandler::new(main_thread, canvas.clone(), style.clone()); + + let common = Common { + window: window.clone(), + document: document.clone(), + raw: Rc::new(canvas.clone()), + style, + old_size: Rc::default(), + current_size: Rc::default(), + }; + + if let Some(size) = attr.inner_size { + let size = size.to_logical(super::scale_factor(&common.window)); + super::set_canvas_size(&common.document, &common.raw, &common.style, size); + } + + if let Some(size) = attr.min_inner_size { + let size = size.to_logical(super::scale_factor(&common.window)); + super::set_canvas_min_size(&common.document, &common.raw, &common.style, Some(size)); + } + + if let Some(size) = attr.max_inner_size { + let size = size.to_logical(super::scale_factor(&common.window)); + super::set_canvas_max_size(&common.document, &common.raw, &common.style, Some(size)); + } + + if let Some(position) = attr.position { + let position = position.to_logical(super::scale_factor(&common.window)); + super::set_canvas_position(&common.document, &common.raw, &common.style, position); + } + + if attr.fullscreen.is_some() { + fullscreen::request_fullscreen(&document, &canvas); + } + + if attr.active { + let _ = common.raw.focus(); + } + + Ok(Canvas { + common, + id, + has_focus: Rc::new(Cell::new(false)), + prevent_default: Rc::new(Cell::new(attr.platform_specific.prevent_default)), + is_intersecting: None, + on_touch_start: None, + on_blur: None, + on_focus: None, + on_keyboard_release: None, + on_keyboard_press: None, + on_mouse_wheel: None, + on_dark_mode: None, + pointer_handler: PointerHandler::new(), + on_resize_scale: None, + on_intersect: None, + animation_frame_handler: AnimationFrameHandler::new(window), + on_touch_end: None, + on_context_menu: None, + cursor, + }) + } + + pub fn set_cursor_lock(&self, lock: bool) -> Result<(), RootOE> { + if lock { + self.raw().request_pointer_lock(); + } else { + self.common.document.exit_pointer_lock(); + } + Ok(()) + } + + pub fn set_attribute(&self, attribute: &str, value: &str) { + self.common + .raw + .set_attribute(attribute, value) + .unwrap_or_else(|err| panic!("error: {err:?}\nSet attribute: {attribute}")) + } + + pub fn position(&self) -> LogicalPosition<f64> { + let bounds = self.common.raw.get_bounding_client_rect(); + let mut position = LogicalPosition { x: bounds.x(), y: bounds.y() }; + + if self.document().contains(Some(self.raw())) && self.style().get("display") != "none" { + position.x += super::style_size_property(self.style(), "border-left-width") + + super::style_size_property(self.style(), "padding-left"); + position.y += super::style_size_property(self.style(), "border-top-width") + + super::style_size_property(self.style(), "padding-top"); + } + + position + } + + #[inline] + pub fn old_size(&self) -> PhysicalSize<u32> { + self.common.old_size.get() + } + + #[inline] + pub fn inner_size(&self) -> PhysicalSize<u32> { + self.common.current_size.get() + } + + #[inline] + pub fn set_old_size(&self, size: PhysicalSize<u32>) { + self.common.old_size.set(size) + } + + #[inline] + pub fn set_current_size(&self, size: PhysicalSize<u32>) { + self.common.current_size.set(size) + } + + #[inline] + pub fn window(&self) -> &web_sys::Window { + &self.common.window + } + + #[inline] + pub fn document(&self) -> &Document { + &self.common.document + } + + #[inline] + pub fn raw(&self) -> &HtmlCanvasElement { + &self.common.raw + } + + #[inline] + pub fn style(&self) -> &Style { + &self.common.style + } + + pub fn on_touch_start(&mut self) { + let prevent_default = Rc::clone(&self.prevent_default); + self.on_touch_start = Some(self.common.add_event("touchstart", move |event: Event| { + if prevent_default.get() { + event.prevent_default(); + } + })); + } + + pub fn on_blur<F>(&mut self, mut handler: F) + where + F: 'static + FnMut(), + { + self.on_blur = Some(self.common.add_event("blur", move |_: FocusEvent| { + handler(); + })); + } + + pub fn on_focus<F>(&mut self, mut handler: F) + where + F: 'static + FnMut(), + { + self.on_focus = Some(self.common.add_event("focus", move |_: FocusEvent| { + handler(); + })); + } + + pub fn on_keyboard_release<F>(&mut self, mut handler: F) + where + F: 'static + FnMut(PhysicalKey, Key, Option<SmolStr>, KeyLocation, bool, ModifiersState), + { + let prevent_default = Rc::clone(&self.prevent_default); + self.on_keyboard_release = + Some(self.common.add_event("keyup", move |event: KeyboardEvent| { + if prevent_default.get() { + event.prevent_default(); + } + let key = event::key(&event); + let modifiers = event::keyboard_modifiers(&event); + handler( + event::key_code(&event), + key, + event::key_text(&event), + event::key_location(&event), + event.repeat(), + modifiers, + ); + })); + } + + pub fn on_keyboard_press<F>(&mut self, mut handler: F) + where + F: 'static + FnMut(PhysicalKey, Key, Option<SmolStr>, KeyLocation, bool, ModifiersState), + { + let prevent_default = Rc::clone(&self.prevent_default); + self.on_keyboard_press = + Some(self.common.add_event("keydown", move |event: KeyboardEvent| { + if prevent_default.get() { + event.prevent_default(); + } + let key = event::key(&event); + let modifiers = event::keyboard_modifiers(&event); + handler( + event::key_code(&event), + key, + event::key_text(&event), + event::key_location(&event), + event.repeat(), + modifiers, + ); + })); + } + + pub fn on_cursor_leave<F>(&mut self, handler: F) + where + F: 'static + FnMut(ModifiersState, Option<i32>), + { + self.pointer_handler.on_cursor_leave(&self.common, handler) + } + + pub fn on_cursor_enter<F>(&mut self, handler: F) + where + F: 'static + FnMut(ModifiersState, Option<i32>), + { + self.pointer_handler.on_cursor_enter(&self.common, handler) + } + + pub fn on_mouse_release<M, T>(&mut self, mouse_handler: M, touch_handler: T) + where + M: 'static + FnMut(ModifiersState, i32, PhysicalPosition<f64>, MouseButton), + T: 'static + FnMut(ModifiersState, i32, PhysicalPosition<f64>, Force), + { + self.pointer_handler.on_mouse_release(&self.common, mouse_handler, touch_handler) + } + + pub fn on_mouse_press<M, T>(&mut self, mouse_handler: M, touch_handler: T) + where + M: 'static + FnMut(ModifiersState, i32, PhysicalPosition<f64>, MouseButton), + T: 'static + FnMut(ModifiersState, i32, PhysicalPosition<f64>, Force), + { + self.pointer_handler.on_mouse_press( + &self.common, + mouse_handler, + touch_handler, + Rc::clone(&self.prevent_default), + ) + } + + pub fn on_cursor_move<M, T, B>(&mut self, mouse_handler: M, touch_handler: T, button_handler: B) + where + M: 'static + FnMut(ModifiersState, i32, &mut dyn Iterator<Item = PhysicalPosition<f64>>), + T: 'static + + FnMut(ModifiersState, i32, &mut dyn Iterator<Item = (PhysicalPosition<f64>, Force)>), + B: 'static + FnMut(ModifiersState, i32, PhysicalPosition<f64>, ButtonsState, MouseButton), + { + self.pointer_handler.on_cursor_move( + &self.common, + mouse_handler, + touch_handler, + button_handler, + Rc::clone(&self.prevent_default), + ) + } + + pub fn on_touch_cancel<F>(&mut self, handler: F) + where + F: 'static + FnMut(i32, PhysicalPosition<f64>, Force), + { + self.pointer_handler.on_touch_cancel(&self.common, handler) + } + + pub fn on_mouse_wheel<F>(&mut self, mut handler: F) + where + F: 'static + FnMut(i32, MouseScrollDelta, ModifiersState), + { + let window = self.common.window.clone(); + let prevent_default = Rc::clone(&self.prevent_default); + self.on_mouse_wheel = Some(self.common.add_event("wheel", move |event: WheelEvent| { + if prevent_default.get() { + event.prevent_default(); + } + + if let Some(delta) = event::mouse_scroll_delta(&window, &event) { + let modifiers = event::mouse_modifiers(&event); + handler(0, delta, modifiers); + } + })); + } + + pub fn on_dark_mode<F>(&mut self, mut handler: F) + where + F: 'static + FnMut(bool), + { + self.on_dark_mode = Some(MediaQueryListHandle::new( + &self.common.window, + "(prefers-color-scheme: dark)", + move |mql| handler(mql.matches()), + )); + } + + pub(crate) fn on_resize_scale<S, R>(&mut self, scale_handler: S, size_handler: R) + where + S: 'static + Fn(PhysicalSize<u32>, f64), + R: 'static + Fn(PhysicalSize<u32>), + { + self.on_resize_scale = Some(ResizeScaleHandle::new( + self.window().clone(), + self.document().clone(), + self.raw().clone(), + self.style().clone(), + scale_handler, + size_handler, + )); + } + + pub(crate) fn on_intersection<F>(&mut self, handler: F) + where + F: 'static + FnMut(bool), + { + self.on_intersect = Some(IntersectionObserverHandle::new(self.raw(), handler)); + } + + pub(crate) fn on_animation_frame<F>(&mut self, f: F) + where + F: 'static + FnMut(), + { + self.animation_frame_handler.on_animation_frame(f) + } + + pub(crate) fn on_context_menu(&mut self) { + let prevent_default = Rc::clone(&self.prevent_default); + self.on_context_menu = + Some(self.common.add_event("contextmenu", move |event: PointerEvent| { + if prevent_default.get() { + event.prevent_default(); + } + })); + } + + pub fn request_fullscreen(&self) { + fullscreen::request_fullscreen(self.document(), self.raw()); + } + + pub fn exit_fullscreen(&self) { + fullscreen::exit_fullscreen(self.document(), self.raw()); + } + + pub fn is_fullscreen(&self) -> bool { + fullscreen::is_fullscreen(self.document(), self.raw()) + } + + pub fn request_animation_frame(&self) { + self.animation_frame_handler.request(); + } + + pub(crate) fn handle_scale_change( + &self, + runner: &super::super::event_loop::runner::Shared, + event_handler: impl FnOnce(crate::event::Event<()>), + current_size: PhysicalSize<u32>, + scale: f64, + ) { + // First, we send the `ScaleFactorChanged` event: + self.set_current_size(current_size); + let new_size = { + let new_size = Arc::new(Mutex::new(current_size)); + event_handler(crate::event::Event::WindowEvent { + window_id: RootWindowId(self.id), + event: crate::event::WindowEvent::ScaleFactorChanged { + scale_factor: scale, + inner_size_writer: InnerSizeWriter::new(Arc::downgrade(&new_size)), + }, + }); + + let new_size = *new_size.lock().unwrap(); + new_size + }; + + if current_size != new_size { + // Then we resize the canvas to the new size, a new + // `Resized` event will be sent by the `ResizeObserver`: + let new_size = new_size.to_logical(scale); + super::set_canvas_size(self.document(), self.raw(), self.style(), new_size); + + // Set the size might not trigger the event because the calculation is inaccurate. + self.on_resize_scale + .as_ref() + .expect("expected Window to still be active") + .notify_resize(); + } else if self.old_size() != new_size { + // Then we at least send a resized event. + self.set_old_size(new_size); + runner.send_event(crate::event::Event::WindowEvent { + window_id: RootWindowId(self.id), + event: crate::event::WindowEvent::Resized(new_size), + }) + } + } + + pub fn remove_listeners(&mut self) { + self.on_touch_start = None; + self.on_focus = None; + self.on_blur = None; + self.on_keyboard_release = None; + self.on_keyboard_press = None; + self.on_mouse_wheel = None; + self.on_dark_mode = None; + self.pointer_handler.remove_listeners(); + self.on_resize_scale = None; + self.on_intersect = None; + self.animation_frame_handler.cancel(); + self.on_touch_end = None; + self.on_context_menu = None; + } +} + +impl Common { + pub fn add_event<E, F>( + &self, + event_name: &'static str, + handler: F, + ) -> EventListenerHandle<dyn FnMut(E)> + where + E: 'static + AsRef<web_sys::Event> + wasm_bindgen::convert::FromWasmAbi, + F: 'static + FnMut(E), + { + EventListenerHandle::new(self.raw.deref().clone(), event_name, Closure::new(handler)) + } + + pub fn raw(&self) -> &HtmlCanvasElement { + &self.raw + } +} + +impl Style { + fn new(window: &web_sys::Window, canvas: &HtmlCanvasElement) -> Self { + #[allow(clippy::disallowed_methods)] + let read = window + .get_computed_style(canvas) + .expect("Failed to obtain computed style") + // this can't fail: we aren't using a pseudo-element + .expect("Invalid pseudo-element"); + + #[allow(clippy::disallowed_methods)] + let write = canvas.style(); + + Self { read, write } + } + + pub(crate) fn get(&self, property: &str) -> String { + self.read.get_property_value(property).expect("Invalid property") + } + + pub(crate) fn remove(&self, property: &str) { + self.write.remove_property(property).expect("Property is read only"); + } + + pub(crate) fn set(&self, property: &str, value: &str) { + self.write.set_property(property, value).expect("Property is read only"); + } +} diff --git a/app/vendor/rune/vendor/winit/src/platform_impl/web/web_sys/event.rs b/app/vendor/rune/vendor/winit/src/platform_impl/web/web_sys/event.rs new file mode 100644 index 0000000..ddd1257 --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/platform_impl/web/web_sys/event.rs @@ -0,0 +1,270 @@ +use crate::event::{MouseButton, MouseScrollDelta}; +use crate::keyboard::{Key, KeyLocation, ModifiersState, NamedKey, PhysicalKey}; + +use dpi::{LogicalPosition, PhysicalPosition, Position}; +use smol_str::SmolStr; +use std::cell::OnceCell; +use wasm_bindgen::prelude::wasm_bindgen; +use wasm_bindgen::{JsCast, JsValue}; +use web_sys::{KeyboardEvent, MouseEvent, PointerEvent, WheelEvent}; + +use super::Engine; + +bitflags::bitflags! { + // https://www.w3.org/TR/pointerevents3/#the-buttons-property + #[derive(Debug, Clone, Copy, PartialEq, Eq)] + pub struct ButtonsState: u16 { + const LEFT = 0b00001; + const RIGHT = 0b00010; + const MIDDLE = 0b00100; + const BACK = 0b01000; + const FORWARD = 0b10000; + } +} + +impl From<ButtonsState> for MouseButton { + fn from(value: ButtonsState) -> Self { + match value { + ButtonsState::LEFT => MouseButton::Left, + ButtonsState::RIGHT => MouseButton::Right, + ButtonsState::MIDDLE => MouseButton::Middle, + ButtonsState::BACK => MouseButton::Back, + ButtonsState::FORWARD => MouseButton::Forward, + _ => MouseButton::Other(value.bits()), + } + } +} + +impl From<MouseButton> for ButtonsState { + fn from(value: MouseButton) -> Self { + match value { + MouseButton::Left => ButtonsState::LEFT, + MouseButton::Right => ButtonsState::RIGHT, + MouseButton::Middle => ButtonsState::MIDDLE, + MouseButton::Back => ButtonsState::BACK, + MouseButton::Forward => ButtonsState::FORWARD, + MouseButton::Other(value) => ButtonsState::from_bits_retain(value), + } + } +} + +pub fn mouse_buttons(event: &MouseEvent) -> ButtonsState { + ButtonsState::from_bits_retain(event.buttons()) +} + +pub fn mouse_button(event: &MouseEvent) -> Option<MouseButton> { + // https://www.w3.org/TR/pointerevents3/#the-button-property + match event.button() { + -1 => None, + 0 => Some(MouseButton::Left), + 1 => Some(MouseButton::Middle), + 2 => Some(MouseButton::Right), + 3 => Some(MouseButton::Back), + 4 => Some(MouseButton::Forward), + i => { + Some(MouseButton::Other(i.try_into().expect("unexpected negative mouse button value"))) + }, + } +} + +impl MouseButton { + pub fn to_id(self) -> u32 { + match self { + MouseButton::Left => 0, + MouseButton::Right => 1, + MouseButton::Middle => 2, + MouseButton::Back => 3, + MouseButton::Forward => 4, + MouseButton::Other(value) => value.into(), + } + } +} + +pub fn mouse_position(event: &MouseEvent) -> LogicalPosition<f64> { + #[wasm_bindgen] + extern "C" { + type MouseEventExt; + + #[wasm_bindgen(method, getter, js_name = offsetX)] + fn offset_x(this: &MouseEventExt) -> f64; + + #[wasm_bindgen(method, getter, js_name = offsetY)] + fn offset_y(this: &MouseEventExt) -> f64; + } + + let event: &MouseEventExt = event.unchecked_ref(); + + LogicalPosition { x: event.offset_x(), y: event.offset_y() } +} + +// TODO: Remove this when Firefox supports correct movement values in coalesced events and browsers +// have agreed on what coordinate space `movementX/Y` is using. +// See <https://bugzilla.mozilla.org/show_bug.cgi?id=1753724>. +// See <https://github.com/w3c/pointerlock/issues/42>. +pub enum MouseDelta { + Chromium, + Gecko { old_position: LogicalPosition<f64>, old_delta: LogicalPosition<f64> }, + Other, +} + +impl MouseDelta { + pub fn init(window: &web_sys::Window, event: &PointerEvent) -> Self { + match super::engine(window) { + Some(Engine::Chromium) => Self::Chromium, + // Firefox has wrong movement values in coalesced events. + Some(Engine::Gecko) if has_coalesced_events_support(event) => Self::Gecko { + old_position: mouse_position(event), + old_delta: LogicalPosition::new( + event.movement_x() as f64, + event.movement_y() as f64, + ), + }, + _ => Self::Other, + } + } + + pub fn delta(&mut self, event: &MouseEvent) -> Position { + match self { + MouseDelta::Chromium => { + PhysicalPosition::new(event.movement_x(), event.movement_y()).into() + }, + MouseDelta::Gecko { old_position, old_delta } => { + let new_position = mouse_position(event); + let x = new_position.x - old_position.x + old_delta.x; + let y = new_position.y - old_position.y + old_delta.y; + *old_position = new_position; + *old_delta = LogicalPosition::new(0., 0.); + LogicalPosition::new(x, y).into() + }, + MouseDelta::Other => { + LogicalPosition::new(event.movement_x(), event.movement_y()).into() + }, + } + } +} + +pub fn mouse_scroll_delta( + window: &web_sys::Window, + event: &WheelEvent, +) -> Option<MouseScrollDelta> { + let x = -event.delta_x(); + let y = -event.delta_y(); + + match event.delta_mode() { + WheelEvent::DOM_DELTA_LINE => Some(MouseScrollDelta::LineDelta(x as f32, y as f32)), + WheelEvent::DOM_DELTA_PIXEL => { + let delta = LogicalPosition::new(x, y).to_physical(super::scale_factor(window)); + Some(MouseScrollDelta::PixelDelta(delta)) + }, + _ => None, + } +} + +pub fn key_code(event: &KeyboardEvent) -> PhysicalKey { + let code = event.code(); + PhysicalKey::from_key_code_attribute_value(&code) +} + +pub fn key(event: &KeyboardEvent) -> Key { + Key::from_key_attribute_value(&event.key()) +} + +pub fn key_text(event: &KeyboardEvent) -> Option<SmolStr> { + let key = event.key(); + let key = Key::from_key_attribute_value(&key); + match &key { + Key::Character(text) => Some(text.clone()), + Key::Named(NamedKey::Tab) => Some(SmolStr::new("\t")), + Key::Named(NamedKey::Enter) => Some(SmolStr::new("\r")), + Key::Named(NamedKey::Space) => Some(SmolStr::new(" ")), + _ => None, + } + .map(SmolStr::new) +} + +pub fn key_location(event: &KeyboardEvent) -> KeyLocation { + match event.location() { + KeyboardEvent::DOM_KEY_LOCATION_LEFT => KeyLocation::Left, + KeyboardEvent::DOM_KEY_LOCATION_RIGHT => KeyLocation::Right, + KeyboardEvent::DOM_KEY_LOCATION_NUMPAD => KeyLocation::Numpad, + KeyboardEvent::DOM_KEY_LOCATION_STANDARD => KeyLocation::Standard, + location => { + tracing::warn!("Unexpected key location: {location}"); + KeyLocation::Standard + }, + } +} + +pub fn keyboard_modifiers(event: &KeyboardEvent) -> ModifiersState { + let mut state = ModifiersState::empty(); + + if event.shift_key() { + state |= ModifiersState::SHIFT; + } + if event.ctrl_key() { + state |= ModifiersState::CONTROL; + } + if event.alt_key() { + state |= ModifiersState::ALT; + } + if event.meta_key() { + state |= ModifiersState::SUPER; + } + + state +} + +pub fn mouse_modifiers(event: &MouseEvent) -> ModifiersState { + let mut state = ModifiersState::empty(); + + if event.shift_key() { + state |= ModifiersState::SHIFT; + } + if event.ctrl_key() { + state |= ModifiersState::CONTROL; + } + if event.alt_key() { + state |= ModifiersState::ALT; + } + if event.meta_key() { + state |= ModifiersState::SUPER; + } + + state +} + +pub fn pointer_move_event(event: PointerEvent) -> impl Iterator<Item = PointerEvent> { + // make a single iterator depending on the availability of coalesced events + if has_coalesced_events_support(&event) { + None.into_iter().chain( + Some(event.get_coalesced_events().into_iter().map(PointerEvent::unchecked_from_js)) + .into_iter() + .flatten(), + ) + } else { + Some(event).into_iter().chain(None.into_iter().flatten()) + } +} + +// TODO: Remove when Safari supports `getCoalescedEvents`. +// See <https://bugs.webkit.org/show_bug.cgi?id=210454>. +pub fn has_coalesced_events_support(event: &PointerEvent) -> bool { + thread_local! { + static COALESCED_EVENTS_SUPPORT: OnceCell<bool> = const { OnceCell::new() }; + } + + COALESCED_EVENTS_SUPPORT.with(|support| { + *support.get_or_init(|| { + #[wasm_bindgen] + extern "C" { + type PointerCoalescedEventsSupport; + + #[wasm_bindgen(method, getter, js_name = getCoalescedEvents)] + fn has_get_coalesced_events(this: &PointerCoalescedEventsSupport) -> JsValue; + } + + let support: &PointerCoalescedEventsSupport = event.unchecked_ref(); + !support.has_get_coalesced_events().is_undefined() + }) + }) +} diff --git a/app/vendor/rune/vendor/winit/src/platform_impl/web/web_sys/event_handle.rs b/app/vendor/rune/vendor/winit/src/platform_impl/web/web_sys/event_handle.rs new file mode 100644 index 0000000..4474af3 --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/platform_impl/web/web_sys/event_handle.rs @@ -0,0 +1,38 @@ +use wasm_bindgen::prelude::Closure; +use wasm_bindgen::JsCast; +use web_sys::EventTarget; + +pub struct EventListenerHandle<T: ?Sized> { + target: EventTarget, + event_type: &'static str, + listener: Closure<T>, +} + +impl<T: ?Sized> EventListenerHandle<T> { + pub fn new<U>(target: U, event_type: &'static str, listener: Closure<T>) -> Self + where + U: Into<EventTarget>, + { + let target = target.into(); + target + .add_event_listener_with_callback(event_type, listener.as_ref().unchecked_ref()) + .expect("Failed to add event listener"); + EventListenerHandle { target, event_type, listener } + } +} + +impl<T: ?Sized> Drop for EventListenerHandle<T> { + fn drop(&mut self) { + self.target + .remove_event_listener_with_callback( + self.event_type, + self.listener.as_ref().unchecked_ref(), + ) + .unwrap_or_else(|e| { + web_sys::console::error_2( + &format!("Error removing event listener {}", self.event_type).into(), + &e, + ) + }); + } +} diff --git a/app/vendor/rune/vendor/winit/src/platform_impl/web/web_sys/fullscreen.rs b/app/vendor/rune/vendor/winit/src/platform_impl/web/web_sys/fullscreen.rs new file mode 100644 index 0000000..867d34a --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/platform_impl/web/web_sys/fullscreen.rs @@ -0,0 +1,103 @@ +use std::cell::OnceCell; + +use js_sys::Promise; +use wasm_bindgen::closure::Closure; +use wasm_bindgen::prelude::wasm_bindgen; +use wasm_bindgen::{JsCast, JsValue}; +use web_sys::{Document, Element, HtmlCanvasElement}; + +pub fn request_fullscreen(document: &Document, canvas: &HtmlCanvasElement) { + if is_fullscreen(document, canvas) { + return; + } + + #[wasm_bindgen] + extern "C" { + #[wasm_bindgen(extends = HtmlCanvasElement)] + type RequestFullscreen; + + #[wasm_bindgen(method, js_name = requestFullscreen)] + fn request_fullscreen(this: &RequestFullscreen) -> Promise; + + #[wasm_bindgen(method, js_name = webkitRequestFullscreen)] + fn webkit_request_fullscreen(this: &RequestFullscreen); + } + + let canvas: &RequestFullscreen = canvas.unchecked_ref(); + + if has_fullscreen_api_support(canvas) { + thread_local! { + static REJECT_HANDLER: Closure<dyn FnMut(JsValue)> = Closure::new(|_| ()); + } + REJECT_HANDLER.with(|handler| { + let _ = canvas.request_fullscreen().catch(handler); + }); + } else { + canvas.webkit_request_fullscreen(); + } +} + +pub fn is_fullscreen(document: &Document, canvas: &HtmlCanvasElement) -> bool { + #[wasm_bindgen] + extern "C" { + type FullscreenElement; + + #[wasm_bindgen(method, getter, js_name = webkitFullscreenElement)] + fn webkit_fullscreen_element(this: &FullscreenElement) -> Option<Element>; + } + + let element = if has_fullscreen_api_support(canvas) { + #[allow(clippy::disallowed_methods)] + document.fullscreen_element() + } else { + let document: &FullscreenElement = document.unchecked_ref(); + document.webkit_fullscreen_element() + }; + + match element { + Some(element) => { + let canvas: &Element = canvas; + canvas == &element + }, + None => false, + } +} + +pub fn exit_fullscreen(document: &Document, canvas: &HtmlCanvasElement) { + #[wasm_bindgen] + extern "C" { + type ExitFullscreen; + + #[wasm_bindgen(method, js_name = webkitExitFullscreen)] + fn webkit_exit_fullscreen(this: &ExitFullscreen); + } + + if has_fullscreen_api_support(canvas) { + #[allow(clippy::disallowed_methods)] + document.exit_fullscreen() + } else { + let document: &ExitFullscreen = document.unchecked_ref(); + document.webkit_exit_fullscreen() + } +} + +fn has_fullscreen_api_support(canvas: &HtmlCanvasElement) -> bool { + thread_local! { + static FULLSCREEN_API_SUPPORT: OnceCell<bool> = const { OnceCell::new() }; + } + + FULLSCREEN_API_SUPPORT.with(|support| { + *support.get_or_init(|| { + #[wasm_bindgen] + extern "C" { + type CanvasFullScreenApiSupport; + + #[wasm_bindgen(method, getter, js_name = requestFullscreen)] + fn has_request_fullscreen(this: &CanvasFullScreenApiSupport) -> JsValue; + } + + let support: &CanvasFullScreenApiSupport = canvas.unchecked_ref(); + !support.has_request_fullscreen().is_undefined() + }) + }) +} diff --git a/app/vendor/rune/vendor/winit/src/platform_impl/web/web_sys/intersection_handle.rs b/app/vendor/rune/vendor/winit/src/platform_impl/web/web_sys/intersection_handle.rs new file mode 100644 index 0000000..9f63e84 --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/platform_impl/web/web_sys/intersection_handle.rs @@ -0,0 +1,33 @@ +use js_sys::Array; +use wasm_bindgen::prelude::Closure; +use wasm_bindgen::JsCast; +use web_sys::{Element, IntersectionObserver, IntersectionObserverEntry}; + +pub(super) struct IntersectionObserverHandle { + observer: IntersectionObserver, + _closure: Closure<dyn FnMut(Array)>, +} + +impl IntersectionObserverHandle { + pub fn new<F>(element: &Element, mut callback: F) -> Self + where + F: 'static + FnMut(bool), + { + let closure = Closure::new(move |entries: Array| { + let entry: IntersectionObserverEntry = entries.get(0).unchecked_into(); + callback(entry.is_intersecting()); + }); + let observer = IntersectionObserver::new(closure.as_ref().unchecked_ref()) + // we don't provide any `options` + .expect("Invalid `options`"); + observer.observe(element); + + Self { observer, _closure: closure } + } +} + +impl Drop for IntersectionObserverHandle { + fn drop(&mut self) { + self.observer.disconnect() + } +} diff --git a/app/vendor/rune/vendor/winit/src/platform_impl/web/web_sys/media_query_handle.rs b/app/vendor/rune/vendor/winit/src/platform_impl/web/web_sys/media_query_handle.rs new file mode 100644 index 0000000..766157a --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/platform_impl/web/web_sys/media_query_handle.rs @@ -0,0 +1,48 @@ +use wasm_bindgen::prelude::Closure; +use wasm_bindgen::JsCast; +use web_sys::MediaQueryList; + +pub(super) struct MediaQueryListHandle { + mql: MediaQueryList, + closure: Closure<dyn FnMut()>, +} + +impl MediaQueryListHandle { + pub fn new<F>(window: &web_sys::Window, media_query: &str, mut listener: F) -> Self + where + F: 'static + FnMut(&MediaQueryList), + { + let mql = window + .match_media(media_query) + .expect("Failed to parse media query") + .expect("Found empty media query"); + + let closure = Closure::new({ + let mql = mql.clone(); + move || listener(&mql) + }); + // TODO: Replace obsolete `addListener()` with `addEventListener()` and use + // `MediaQueryListEvent` instead of cloning the `MediaQueryList`. + // Requires Safari v14. + mql.add_listener_with_opt_callback(Some(closure.as_ref().unchecked_ref())) + .expect("Invalid listener"); + + Self { mql, closure } + } + + pub fn mql(&self) -> &MediaQueryList { + &self.mql + } +} + +impl Drop for MediaQueryListHandle { + fn drop(&mut self) { + remove_listener(&self.mql, &self.closure); + } +} + +fn remove_listener(mql: &MediaQueryList, listener: &Closure<dyn FnMut()>) { + mql.remove_listener_with_opt_callback(Some(listener.as_ref().unchecked_ref())).unwrap_or_else( + |e| web_sys::console::error_2(&"Error removing media query listener".into(), &e), + ); +} diff --git a/app/vendor/rune/vendor/winit/src/platform_impl/web/web_sys/mod.rs b/app/vendor/rune/vendor/winit/src/platform_impl/web/web_sys/mod.rs new file mode 100644 index 0000000..08962b4 --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/platform_impl/web/web_sys/mod.rs @@ -0,0 +1,233 @@ +mod animation_frame; +mod canvas; +pub mod event; +mod event_handle; +mod fullscreen; +mod intersection_handle; +mod media_query_handle; +mod pointer; +mod resize_scaling; +mod schedule; + +use std::sync::OnceLock; + +pub use self::canvas::{Canvas, Style}; +pub use self::event::ButtonsState; +pub use self::event_handle::EventListenerHandle; +pub use self::resize_scaling::ResizeScaleHandle; +pub use self::schedule::Schedule; + +use crate::dpi::{LogicalPosition, LogicalSize}; +use js_sys::Array; +use wasm_bindgen::closure::Closure; +use wasm_bindgen::prelude::wasm_bindgen; +use wasm_bindgen::JsCast; +use web_sys::{ + Document, HtmlCanvasElement, Navigator, PageTransitionEvent, VisibilityState, Window, +}; + +pub fn throw(msg: &str) { + wasm_bindgen::throw_str(msg); +} + +pub struct PageTransitionEventHandle { + _show_listener: event_handle::EventListenerHandle<dyn FnMut(PageTransitionEvent)>, + _hide_listener: event_handle::EventListenerHandle<dyn FnMut(PageTransitionEvent)>, +} + +pub fn on_page_transition( + window: web_sys::Window, + show_handler: impl FnMut(PageTransitionEvent) + 'static, + hide_handler: impl FnMut(PageTransitionEvent) + 'static, +) -> PageTransitionEventHandle { + let show_closure = Closure::new(show_handler); + let hide_closure = Closure::new(hide_handler); + + let show_listener = + event_handle::EventListenerHandle::new(window.clone(), "pageshow", show_closure); + let hide_listener = event_handle::EventListenerHandle::new(window, "pagehide", hide_closure); + PageTransitionEventHandle { _show_listener: show_listener, _hide_listener: hide_listener } +} + +pub fn scale_factor(window: &web_sys::Window) -> f64 { + window.device_pixel_ratio() +} + +fn fix_canvas_size(style: &Style, mut size: LogicalSize<f64>) -> LogicalSize<f64> { + if style.get("box-sizing") == "border-box" { + size.width += style_size_property(style, "border-left-width") + + style_size_property(style, "border-right-width") + + style_size_property(style, "padding-left") + + style_size_property(style, "padding-right"); + size.height += style_size_property(style, "border-top-width") + + style_size_property(style, "border-bottom-width") + + style_size_property(style, "padding-top") + + style_size_property(style, "padding-bottom"); + } + + size +} + +pub fn set_canvas_size( + document: &Document, + raw: &HtmlCanvasElement, + style: &Style, + new_size: LogicalSize<f64>, +) { + if !document.contains(Some(raw)) || style.get("display") == "none" { + return; + } + + let new_size = fix_canvas_size(style, new_size); + + style.set("width", &format!("{}px", new_size.width)); + style.set("height", &format!("{}px", new_size.height)); +} + +pub fn set_canvas_min_size( + document: &Document, + raw: &HtmlCanvasElement, + style: &Style, + dimensions: Option<LogicalSize<f64>>, +) { + if let Some(dimensions) = dimensions { + if !document.contains(Some(raw)) || style.get("display") == "none" { + return; + } + + let new_size = fix_canvas_size(style, dimensions); + + style.set("min-width", &format!("{}px", new_size.width)); + style.set("min-height", &format!("{}px", new_size.height)); + } else { + style.remove("min-width"); + style.remove("min-height"); + } +} + +pub fn set_canvas_max_size( + document: &Document, + raw: &HtmlCanvasElement, + style: &Style, + dimensions: Option<LogicalSize<f64>>, +) { + if let Some(dimensions) = dimensions { + if !document.contains(Some(raw)) || style.get("display") == "none" { + return; + } + + let new_size = fix_canvas_size(style, dimensions); + + style.set("max-width", &format!("{}px", new_size.width)); + style.set("max-height", &format!("{}px", new_size.height)); + } else { + style.remove("max-width"); + style.remove("max-height"); + } +} + +pub fn set_canvas_position( + document: &Document, + raw: &HtmlCanvasElement, + style: &Style, + mut position: LogicalPosition<f64>, +) { + if document.contains(Some(raw)) && style.get("display") != "none" { + position.x -= style_size_property(style, "margin-left") + + style_size_property(style, "border-left-width") + + style_size_property(style, "padding-left"); + position.y -= style_size_property(style, "margin-top") + + style_size_property(style, "border-top-width") + + style_size_property(style, "padding-top"); + } + + style.set("position", "fixed"); + style.set("left", &format!("{}px", position.x)); + style.set("top", &format!("{}px", position.y)); +} + +/// This function will panic if the element is not inserted in the DOM +/// or is not a CSS property that represents a size in pixel. +pub fn style_size_property(style: &Style, property: &str) -> f64 { + let prop = style.get(property); + prop.strip_suffix("px") + .expect("Element was not inserted into the DOM or is not a size in pixel") + .parse() + .expect("CSS property is not a size in pixel") +} + +pub fn is_dark_mode(window: &web_sys::Window) -> Option<bool> { + window.match_media("(prefers-color-scheme: dark)").ok().flatten().map(|media| media.matches()) +} + +pub fn is_visible(document: &Document) -> bool { + document.visibility_state() == VisibilityState::Visible +} + +pub type RawCanvasType = HtmlCanvasElement; + +#[derive(Clone, Copy)] +pub enum Engine { + Chromium, + Gecko, + WebKit, +} + +pub fn engine(window: &Window) -> Option<Engine> { + static ENGINE: OnceLock<Option<Engine>> = OnceLock::new(); + + #[wasm_bindgen] + extern "C" { + #[wasm_bindgen(extends = Navigator)] + type NavigatorExt; + + #[wasm_bindgen(method, getter, js_name = userAgentData)] + fn user_agent_data(this: &NavigatorExt) -> Option<NavigatorUaData>; + + type NavigatorUaData; + + #[wasm_bindgen(method, getter)] + fn brands(this: &NavigatorUaData) -> Array; + + type NavigatorUaBrandVersion; + + #[wasm_bindgen(method, getter)] + fn brand(this: &NavigatorUaBrandVersion) -> String; + } + + *ENGINE.get_or_init(|| { + let navigator: NavigatorExt = window.navigator().unchecked_into(); + + if let Some(data) = navigator.user_agent_data() { + for brand in data + .brands() + .iter() + .map(NavigatorUaBrandVersion::unchecked_from_js) + .map(|brand| brand.brand()) + { + match brand.as_str() { + "Chromium" => return Some(Engine::Chromium), + // TODO: verify when Firefox actually implements it. + "Gecko" => return Some(Engine::Gecko), + // TODO: verify when Safari actually implements it. + "WebKit" => return Some(Engine::WebKit), + _ => (), + } + } + + None + } else { + let data = navigator.user_agent().ok()?; + + if data.contains("Chrome/") { + Some(Engine::Chromium) + } else if data.contains("Gecko/") { + Some(Engine::Gecko) + } else if data.contains("AppleWebKit/") { + Some(Engine::WebKit) + } else { + None + } + } + }) +} diff --git a/app/vendor/rune/vendor/winit/src/platform_impl/web/web_sys/pointer.rs b/app/vendor/rune/vendor/winit/src/platform_impl/web/web_sys/pointer.rs new file mode 100644 index 0000000..3ee168b --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/platform_impl/web/web_sys/pointer.rs @@ -0,0 +1,244 @@ +use std::cell::Cell; +use std::rc::Rc; + +use super::canvas::Common; +use super::event; +use super::event_handle::EventListenerHandle; +use crate::dpi::PhysicalPosition; +use crate::event::{Force, MouseButton}; +use crate::keyboard::ModifiersState; + +use event::ButtonsState; +use web_sys::PointerEvent; + +#[allow(dead_code)] +pub(super) struct PointerHandler { + on_cursor_leave: Option<EventListenerHandle<dyn FnMut(PointerEvent)>>, + on_cursor_enter: Option<EventListenerHandle<dyn FnMut(PointerEvent)>>, + on_cursor_move: Option<EventListenerHandle<dyn FnMut(PointerEvent)>>, + on_pointer_press: Option<EventListenerHandle<dyn FnMut(PointerEvent)>>, + on_pointer_release: Option<EventListenerHandle<dyn FnMut(PointerEvent)>>, + on_touch_cancel: Option<EventListenerHandle<dyn FnMut(PointerEvent)>>, +} + +impl PointerHandler { + pub fn new() -> Self { + Self { + on_cursor_leave: None, + on_cursor_enter: None, + on_cursor_move: None, + on_pointer_press: None, + on_pointer_release: None, + on_touch_cancel: None, + } + } + + pub fn on_cursor_leave<F>(&mut self, canvas_common: &Common, mut handler: F) + where + F: 'static + FnMut(ModifiersState, Option<i32>), + { + self.on_cursor_leave = + Some(canvas_common.add_event("pointerout", move |event: PointerEvent| { + let modifiers = event::mouse_modifiers(&event); + + // touch events are handled separately + // handling them here would produce duplicate mouse events, inconsistent with + // other platforms. + let pointer_id = (event.pointer_type() != "touch").then(|| event.pointer_id()); + + handler(modifiers, pointer_id); + })); + } + + pub fn on_cursor_enter<F>(&mut self, canvas_common: &Common, mut handler: F) + where + F: 'static + FnMut(ModifiersState, Option<i32>), + { + self.on_cursor_enter = + Some(canvas_common.add_event("pointerover", move |event: PointerEvent| { + let modifiers = event::mouse_modifiers(&event); + + // touch events are handled separately + // handling them here would produce duplicate mouse events, inconsistent with + // other platforms. + let pointer_id = (event.pointer_type() != "touch").then(|| event.pointer_id()); + + handler(modifiers, pointer_id); + })); + } + + pub fn on_mouse_release<M, T>( + &mut self, + canvas_common: &Common, + mut mouse_handler: M, + mut touch_handler: T, + ) where + M: 'static + FnMut(ModifiersState, i32, PhysicalPosition<f64>, MouseButton), + T: 'static + FnMut(ModifiersState, i32, PhysicalPosition<f64>, Force), + { + let window = canvas_common.window.clone(); + self.on_pointer_release = + Some(canvas_common.add_event("pointerup", move |event: PointerEvent| { + let modifiers = event::mouse_modifiers(&event); + + match event.pointer_type().as_str() { + "touch" => touch_handler( + modifiers, + event.pointer_id(), + event::mouse_position(&event).to_physical(super::scale_factor(&window)), + Force::Normalized(event.pressure() as f64), + ), + _ => mouse_handler( + modifiers, + event.pointer_id(), + event::mouse_position(&event).to_physical(super::scale_factor(&window)), + event::mouse_button(&event).expect("no mouse button released"), + ), + } + })); + } + + pub fn on_mouse_press<M, T>( + &mut self, + canvas_common: &Common, + mut mouse_handler: M, + mut touch_handler: T, + prevent_default: Rc<Cell<bool>>, + ) where + M: 'static + FnMut(ModifiersState, i32, PhysicalPosition<f64>, MouseButton), + T: 'static + FnMut(ModifiersState, i32, PhysicalPosition<f64>, Force), + { + let window = canvas_common.window.clone(); + let canvas = canvas_common.raw().clone(); + self.on_pointer_press = + Some(canvas_common.add_event("pointerdown", move |event: PointerEvent| { + if prevent_default.get() { + // prevent text selection + event.prevent_default(); + // but still focus element + let _ = canvas.focus(); + } + + let modifiers = event::mouse_modifiers(&event); + let pointer_type = &event.pointer_type(); + + match pointer_type.as_str() { + "touch" => { + touch_handler( + modifiers, + event.pointer_id(), + event::mouse_position(&event).to_physical(super::scale_factor(&window)), + Force::Normalized(event.pressure() as f64), + ); + }, + _ => { + mouse_handler( + modifiers, + event.pointer_id(), + event::mouse_position(&event).to_physical(super::scale_factor(&window)), + event::mouse_button(&event).expect("no mouse button pressed"), + ); + + if pointer_type == "mouse" { + // Error is swallowed here since the error would occur every time the + // mouse is clicked when the cursor is + // grabbed, and there is probably not a + // situation where this could fail, that we + // care if it fails. + let _e = canvas.set_pointer_capture(event.pointer_id()); + } + }, + } + })); + } + + pub fn on_cursor_move<M, T, B>( + &mut self, + canvas_common: &Common, + mut mouse_handler: M, + mut touch_handler: T, + mut button_handler: B, + prevent_default: Rc<Cell<bool>>, + ) where + M: 'static + FnMut(ModifiersState, i32, &mut dyn Iterator<Item = PhysicalPosition<f64>>), + T: 'static + + FnMut(ModifiersState, i32, &mut dyn Iterator<Item = (PhysicalPosition<f64>, Force)>), + B: 'static + FnMut(ModifiersState, i32, PhysicalPosition<f64>, ButtonsState, MouseButton), + { + let window = canvas_common.window.clone(); + let canvas = canvas_common.raw().clone(); + self.on_cursor_move = + Some(canvas_common.add_event("pointermove", move |event: PointerEvent| { + let modifiers = event::mouse_modifiers(&event); + + let id = event.pointer_id(); + + // chorded button event + if let Some(button) = event::mouse_button(&event) { + if prevent_default.get() { + // prevent text selection + event.prevent_default(); + // but still focus element + let _ = canvas.focus(); + } + + button_handler( + modifiers, + id, + event::mouse_position(&event).to_physical(super::scale_factor(&window)), + event::mouse_buttons(&event), + button, + ); + + return; + } + + // pointer move event + let scale = super::scale_factor(&window); + match event.pointer_type().as_str() { + "touch" => touch_handler( + modifiers, + id, + &mut event::pointer_move_event(event).map(|event| { + ( + event::mouse_position(&event).to_physical(scale), + Force::Normalized(event.pressure() as f64), + ) + }), + ), + _ => mouse_handler( + modifiers, + id, + &mut event::pointer_move_event(event) + .map(|event| event::mouse_position(&event).to_physical(scale)), + ), + }; + })); + } + + pub fn on_touch_cancel<F>(&mut self, canvas_common: &Common, mut handler: F) + where + F: 'static + FnMut(i32, PhysicalPosition<f64>, Force), + { + let window = canvas_common.window.clone(); + self.on_touch_cancel = + Some(canvas_common.add_event("pointercancel", move |event: PointerEvent| { + if event.pointer_type() == "touch" { + handler( + event.pointer_id(), + event::mouse_position(&event).to_physical(super::scale_factor(&window)), + Force::Normalized(event.pressure() as f64), + ); + } + })); + } + + pub fn remove_listeners(&mut self) { + self.on_cursor_leave = None; + self.on_cursor_enter = None; + self.on_cursor_move = None; + self.on_pointer_press = None; + self.on_pointer_release = None; + self.on_touch_cancel = None; + } +} diff --git a/app/vendor/rune/vendor/winit/src/platform_impl/web/web_sys/resize_scaling.rs b/app/vendor/rune/vendor/winit/src/platform_impl/web/web_sys/resize_scaling.rs new file mode 100644 index 0000000..4d10b3a --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/platform_impl/web/web_sys/resize_scaling.rs @@ -0,0 +1,302 @@ +use js_sys::{Array, Object}; +use tracing::warn; +use wasm_bindgen::prelude::{wasm_bindgen, Closure}; +use wasm_bindgen::{JsCast, JsValue}; +use web_sys::{ + Document, HtmlCanvasElement, MediaQueryList, ResizeObserver, ResizeObserverBoxOptions, + ResizeObserverEntry, ResizeObserverOptions, ResizeObserverSize, Window, +}; + +use crate::dpi::{LogicalSize, PhysicalSize}; + +use super::super::backend; +use super::canvas::Style; +use super::media_query_handle::MediaQueryListHandle; + +use std::cell::{Cell, RefCell}; +use std::rc::Rc; + +pub struct ResizeScaleHandle(Rc<ResizeScaleInternal>); + +impl ResizeScaleHandle { + pub(crate) fn new<S, R>( + window: Window, + document: Document, + canvas: HtmlCanvasElement, + style: Style, + scale_handler: S, + resize_handler: R, + ) -> Self + where + S: 'static + Fn(PhysicalSize<u32>, f64), + R: 'static + Fn(PhysicalSize<u32>), + { + Self(ResizeScaleInternal::new( + window, + document, + canvas, + style, + scale_handler, + resize_handler, + )) + } + + pub(crate) fn notify_resize(&self) { + self.0.notify() + } +} + +/// This is a helper type to help manage the `MediaQueryList` used for detecting +/// changes of the `devicePixelRatio`. +struct ResizeScaleInternal { + window: Window, + document: Document, + canvas: HtmlCanvasElement, + style: Style, + mql: RefCell<MediaQueryListHandle>, + observer: ResizeObserver, + _observer_closure: Closure<dyn FnMut(Array, ResizeObserver)>, + scale_handler: Box<dyn Fn(PhysicalSize<u32>, f64)>, + resize_handler: Box<dyn Fn(PhysicalSize<u32>)>, + notify_scale: Cell<bool>, +} + +impl ResizeScaleInternal { + fn new<S, R>( + window: Window, + document: Document, + canvas: HtmlCanvasElement, + style: Style, + scale_handler: S, + resize_handler: R, + ) -> Rc<Self> + where + S: 'static + Fn(PhysicalSize<u32>, f64), + R: 'static + Fn(PhysicalSize<u32>), + { + Rc::<ResizeScaleInternal>::new_cyclic(|weak_self| { + let mql = Self::create_mql(&window, { + let weak_self = weak_self.clone(); + move |mql| { + if let Some(rc_self) = weak_self.upgrade() { + Self::handle_scale(rc_self, mql); + } + } + }); + + let weak_self = weak_self.clone(); + let observer_closure = Closure::new(move |entries: Array, _| { + if let Some(this) = weak_self.upgrade() { + let size = this.process_entry(entries); + + if this.notify_scale.replace(false) { + let scale = backend::scale_factor(&this.window); + (this.scale_handler)(size, scale) + } else { + (this.resize_handler)(size) + } + } + }); + let observer = Self::create_observer(&canvas, observer_closure.as_ref()); + + Self { + window, + document, + canvas, + style, + mql: RefCell::new(mql), + observer, + _observer_closure: observer_closure, + scale_handler: Box::new(scale_handler), + resize_handler: Box::new(resize_handler), + notify_scale: Cell::new(false), + } + }) + } + + fn create_mql<F>(window: &Window, closure: F) -> MediaQueryListHandle + where + F: 'static + FnMut(&MediaQueryList), + { + let current_scale = super::scale_factor(window); + // TODO: Remove `-webkit-device-pixel-ratio`. Requires Safari v16. + let media_query = format!( + "(resolution: {current_scale}dppx), + (-webkit-device-pixel-ratio: {current_scale})", + ); + let mql = MediaQueryListHandle::new(window, &media_query, closure); + debug_assert!( + mql.mql().matches(), + "created media query doesn't match, {current_scale} != {}", + super::scale_factor(window) + ); + mql + } + + fn create_observer(canvas: &HtmlCanvasElement, closure: &JsValue) -> ResizeObserver { + let observer = ResizeObserver::new(closure.as_ref().unchecked_ref()) + .expect("Failed to create `ResizeObserver`"); + + // Safari doesn't support `devicePixelContentBoxSize` + if has_device_pixel_support() { + let options = ResizeObserverOptions::new(); + options.set_box(ResizeObserverBoxOptions::DevicePixelContentBox); + observer.observe_with_options(canvas, &options); + } else { + observer.observe(canvas); + } + + observer + } + + fn notify(&self) { + if !self.document.contains(Some(&self.canvas)) || self.style.get("display") == "none" { + let size = PhysicalSize::new(0, 0); + + if self.notify_scale.replace(false) { + let scale = backend::scale_factor(&self.window); + (self.scale_handler)(size, scale) + } else { + (self.resize_handler)(size) + } + + return; + } + + // Safari doesn't support `devicePixelContentBoxSize` + if has_device_pixel_support() { + self.observer.unobserve(&self.canvas); + self.observer.observe(&self.canvas); + + return; + } + + let mut size = LogicalSize::new( + backend::style_size_property(&self.style, "width"), + backend::style_size_property(&self.style, "height"), + ); + + if self.style.get("box-sizing") == "border-box" { + size.width -= backend::style_size_property(&self.style, "border-left-width") + + backend::style_size_property(&self.style, "border-right-width") + + backend::style_size_property(&self.style, "padding-left") + + backend::style_size_property(&self.style, "padding-right"); + size.height -= backend::style_size_property(&self.style, "border-top-width") + + backend::style_size_property(&self.style, "border-bottom-width") + + backend::style_size_property(&self.style, "padding-top") + + backend::style_size_property(&self.style, "padding-bottom"); + } + + let size = size.to_physical(backend::scale_factor(&self.window)); + + if self.notify_scale.replace(false) { + let scale = backend::scale_factor(&self.window); + (self.scale_handler)(size, scale) + } else { + (self.resize_handler)(size) + } + } + + fn handle_scale(self: Rc<Self>, mql: &MediaQueryList) { + let weak_self = Rc::downgrade(&self); + let scale = super::scale_factor(&self.window); + + // TODO: confirm/reproduce this problem, see: + // <https://github.com/rust-windowing/winit/issues/2597>. + // This should never happen, but if it does then apparently the scale factor didn't change. + if mql.matches() { + warn!( + "media query tracking scale factor was triggered without a change:\nMedia Query: \ + {}\nCurrent Scale: {scale}", + mql.media(), + ); + return; + } + + let new_mql = Self::create_mql(&self.window, move |mql| { + if let Some(rc_self) = weak_self.upgrade() { + Self::handle_scale(rc_self, mql); + } + }); + self.mql.replace(new_mql); + + self.notify_scale.set(true); + self.notify(); + } + + fn process_entry(&self, entries: Array) -> PhysicalSize<u32> { + let entry: ResizeObserverEntry = entries.get(0).unchecked_into(); + + // Safari doesn't support `devicePixelContentBoxSize` + if !has_device_pixel_support() { + let rect = entry.content_rect(); + + return LogicalSize::new(rect.width(), rect.height()) + .to_physical(backend::scale_factor(&self.window)); + } + + let entry: ResizeObserverSize = + entry.device_pixel_content_box_size().get(0).unchecked_into(); + + let writing_mode = self.style.get("writing-mode"); + + // means the canvas is not inserted into the DOM + if writing_mode.is_empty() { + debug_assert_eq!(entry.inline_size(), 0.); + debug_assert_eq!(entry.block_size(), 0.); + + return PhysicalSize::new(0, 0); + } + + let horizontal = match writing_mode.as_str() { + _ if writing_mode.starts_with("horizontal") => true, + _ if writing_mode.starts_with("vertical") | writing_mode.starts_with("sideways") => { + false + }, + // deprecated values + "lr" | "lr-tb" | "rl" => true, + "tb" | "tb-lr" | "tb-rl" => false, + _ => { + warn!("unrecognized `writing-mode`, assuming horizontal"); + true + }, + }; + + if horizontal { + PhysicalSize::new(entry.inline_size() as u32, entry.block_size() as u32) + } else { + PhysicalSize::new(entry.block_size() as u32, entry.inline_size() as u32) + } + } +} + +impl Drop for ResizeScaleInternal { + fn drop(&mut self) { + self.observer.disconnect(); + } +} + +// TODO: Remove when Safari supports `devicePixelContentBoxSize`. +// See <https://bugs.webkit.org/show_bug.cgi?id=219005>. +pub fn has_device_pixel_support() -> bool { + thread_local! { + static DEVICE_PIXEL_SUPPORT: bool = { + #[wasm_bindgen] + extern "C" { + type ResizeObserverEntryExt; + + #[wasm_bindgen(js_class = ResizeObserverEntry, static_method_of = ResizeObserverEntryExt, getter)] + fn prototype() -> Object; + } + + let prototype = ResizeObserverEntryExt::prototype(); + let descriptor = Object::get_own_property_descriptor( + &prototype, + &JsValue::from_str("devicePixelContentBoxSize"), + ); + !descriptor.is_undefined() + }; + } + + DEVICE_PIXEL_SUPPORT.with(|support| *support) +} diff --git a/app/vendor/rune/vendor/winit/src/platform_impl/web/web_sys/schedule.rs b/app/vendor/rune/vendor/winit/src/platform_impl/web/web_sys/schedule.rs new file mode 100644 index 0000000..eb97068 --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/platform_impl/web/web_sys/schedule.rs @@ -0,0 +1,342 @@ +use js_sys::{Array, Function, Object, Promise, Reflect}; +use std::cell::OnceCell; +use std::time::Duration; +use wasm_bindgen::closure::Closure; +use wasm_bindgen::prelude::wasm_bindgen; +use wasm_bindgen::{JsCast, JsValue}; +use web_sys::{ + AbortController, AbortSignal, Blob, BlobPropertyBag, MessageChannel, MessagePort, Url, Worker, +}; + +use crate::platform::web::{PollStrategy, WaitUntilStrategy}; + +#[derive(Debug)] +pub struct Schedule { + _closure: Closure<dyn FnMut()>, + inner: Inner, +} + +#[derive(Debug)] +enum Inner { + Scheduler { + controller: AbortController, + }, + IdleCallback { + window: web_sys::Window, + handle: u32, + }, + Timeout { + window: web_sys::Window, + handle: i32, + port: MessagePort, + _timeout_closure: Closure<dyn FnMut()>, + }, + Worker(MessagePort), +} + +impl Schedule { + pub fn new<F>(strategy: PollStrategy, window: &web_sys::Window, f: F) -> Schedule + where + F: 'static + FnMut(), + { + if strategy == PollStrategy::Scheduler && has_scheduler_support(window) { + Self::new_scheduler(window, f, None) + } else if strategy == PollStrategy::IdleCallback && has_idle_callback_support(window) { + Self::new_idle_callback(window.clone(), f) + } else { + Self::new_timeout(window.clone(), f, None) + } + } + + pub fn new_with_duration<F>( + strategy: WaitUntilStrategy, + window: &web_sys::Window, + f: F, + duration: Duration, + ) -> Schedule + where + F: 'static + FnMut(), + { + match strategy { + WaitUntilStrategy::Scheduler => { + if has_scheduler_support(window) { + Self::new_scheduler(window, f, Some(duration)) + } else { + Self::new_timeout(window.clone(), f, Some(duration)) + } + }, + WaitUntilStrategy::Worker => Self::new_worker(f, duration), + } + } + + fn new_scheduler<F>(window: &web_sys::Window, f: F, duration: Option<Duration>) -> Schedule + where + F: 'static + FnMut(), + { + let window: &WindowSupportExt = window.unchecked_ref(); + let scheduler = window.scheduler(); + + let closure = Closure::new(f); + let mut options = SchedulerPostTaskOptions::new(); + let controller = AbortController::new().expect("Failed to create `AbortController`"); + options.signal(&controller.signal()); + + if let Some(duration) = duration { + // `Duration::as_millis()` always rounds down (because of truncation), we want to round + // up instead. This makes sure that the we never wake up **before** the given time. + let duration = duration + .as_secs() + .checked_mul(1000) + .and_then(|secs| secs.checked_add(duration_millis_ceil(duration).into())) + .unwrap_or(u64::MAX); + + options.delay(duration as f64); + } + + thread_local! { + static REJECT_HANDLER: Closure<dyn FnMut(JsValue)> = Closure::new(|_| ()); + } + REJECT_HANDLER.with(|handler| { + let _ = scheduler + .post_task_with_options(closure.as_ref().unchecked_ref(), &options) + .catch(handler); + }); + + Schedule { _closure: closure, inner: Inner::Scheduler { controller } } + } + + fn new_idle_callback<F>(window: web_sys::Window, f: F) -> Schedule + where + F: 'static + FnMut(), + { + let closure = Closure::new(f); + let handle = window + .request_idle_callback(closure.as_ref().unchecked_ref()) + .expect("Failed to request idle callback"); + + Schedule { _closure: closure, inner: Inner::IdleCallback { window, handle } } + } + + fn new_timeout<F>(window: web_sys::Window, f: F, duration: Option<Duration>) -> Schedule + where + F: 'static + FnMut(), + { + let channel = MessageChannel::new().unwrap(); + let closure = Closure::new(f); + let port_1 = channel.port1(); + port_1.set_onmessage(Some(closure.as_ref().unchecked_ref())); + port_1.start(); + + let port_2 = channel.port2(); + let timeout_closure = Closure::new(move || { + port_2.post_message(&JsValue::UNDEFINED).expect("Failed to send message") + }); + let handle = if let Some(duration) = duration { + // `Duration::as_millis()` always rounds down (because of truncation), we want to round + // up instead. This makes sure that the we never wake up **before** the given time. + let duration = duration + .as_secs() + .try_into() + .ok() + .and_then(|secs: i32| secs.checked_mul(1000)) + .and_then(|secs: i32| { + let millis: i32 = duration_millis_ceil(duration) + .try_into() + .expect("millis are somehow bigger then 1K"); + secs.checked_add(millis) + }) + .unwrap_or(i32::MAX); + + window.set_timeout_with_callback_and_timeout_and_arguments_0( + timeout_closure.as_ref().unchecked_ref(), + duration, + ) + } else { + window.set_timeout_with_callback(timeout_closure.as_ref().unchecked_ref()) + } + .expect("Failed to set timeout"); + + Schedule { + _closure: closure, + inner: Inner::Timeout { + window, + handle, + port: port_1, + _timeout_closure: timeout_closure, + }, + } + } + + fn new_worker<F>(f: F, duration: Duration) -> Schedule + where + F: 'static + FnMut(), + { + thread_local! { + static URL: ScriptUrl = ScriptUrl::new(include_str!("worker.min.js")); + static WORKER: Worker = URL.with(|url| Worker::new(&url.0)).expect("`new Worker()` is not expected to fail with a local script"); + } + + let channel = MessageChannel::new().unwrap(); + let closure = Closure::new(f); + let port_1 = channel.port1(); + port_1.set_onmessage(Some(closure.as_ref().unchecked_ref())); + port_1.start(); + + // `Duration::as_millis()` always rounds down (because of truncation), we want to round + // up instead. This makes sure that the we never wake up **before** the given time. + let duration = duration + .as_secs() + .try_into() + .ok() + .and_then(|secs: u32| secs.checked_mul(1000)) + .and_then(|secs| secs.checked_add(duration_millis_ceil(duration))) + .unwrap_or(u32::MAX); + + WORKER + .with(|worker| { + let port_2 = channel.port2(); + worker.post_message_with_transfer( + &Array::of2(&port_2, &duration.into()), + &Array::of1(&port_2).into(), + ) + }) + .expect("`Worker.postMessage()` is not expected to fail"); + + Schedule { _closure: closure, inner: Inner::Worker(port_1) } + } +} + +impl Drop for Schedule { + fn drop(&mut self) { + match &self.inner { + Inner::Scheduler { controller, .. } => controller.abort(), + Inner::IdleCallback { window, handle, .. } => window.cancel_idle_callback(*handle), + Inner::Timeout { window, handle, port, .. } => { + window.clear_timeout_with_handle(*handle); + port.close(); + port.set_onmessage(None); + }, + Inner::Worker(port) => { + port.close(); + port.set_onmessage(None); + }, + } + } +} + +// TODO: Replace with `u32::div_ceil()` when we hit Rust v1.73. +fn duration_millis_ceil(duration: Duration) -> u32 { + let micros = duration.subsec_micros(); + + // From <https://doc.rust-lang.org/1.73.0/src/core/num/uint_macros.rs.html#2086-2094>. + let d = micros / 1000; + let r = micros % 1000; + if r > 0 && 1000 > 0 { + d + 1 + } else { + d + } +} + +fn has_scheduler_support(window: &web_sys::Window) -> bool { + thread_local! { + static SCHEDULER_SUPPORT: OnceCell<bool> = const { OnceCell::new() }; + } + + SCHEDULER_SUPPORT.with(|support| { + *support.get_or_init(|| { + #[wasm_bindgen] + extern "C" { + type SchedulerSupport; + + #[wasm_bindgen(method, getter, js_name = scheduler)] + fn has_scheduler(this: &SchedulerSupport) -> JsValue; + } + + let support: &SchedulerSupport = window.unchecked_ref(); + + !support.has_scheduler().is_undefined() + }) + }) +} + +fn has_idle_callback_support(window: &web_sys::Window) -> bool { + thread_local! { + static IDLE_CALLBACK_SUPPORT: OnceCell<bool> = const { OnceCell::new() }; + } + + IDLE_CALLBACK_SUPPORT.with(|support| { + *support.get_or_init(|| { + #[wasm_bindgen] + extern "C" { + type IdleCallbackSupport; + + #[wasm_bindgen(method, getter, js_name = requestIdleCallback)] + fn has_request_idle_callback(this: &IdleCallbackSupport) -> JsValue; + } + + let support: &IdleCallbackSupport = window.unchecked_ref(); + !support.has_request_idle_callback().is_undefined() + }) + }) +} + +struct ScriptUrl(String); + +impl ScriptUrl { + fn new(script: &str) -> Self { + let sequence = Array::of1(&script.into()); + let property = BlobPropertyBag::new(); + property.set_type("text/javascript"); + let blob = Blob::new_with_str_sequence_and_options(&sequence, &property) + .expect("`new Blob()` should never throw"); + + let url = Url::create_object_url_with_blob(&blob) + .expect("`URL.createObjectURL()` should never throw"); + + Self(url) + } +} + +impl Drop for ScriptUrl { + fn drop(&mut self) { + Url::revoke_object_url(&self.0).expect("`URL.revokeObjectURL()` should never throw"); + } +} + +#[wasm_bindgen] +extern "C" { + type WindowSupportExt; + + #[wasm_bindgen(method, getter)] + fn scheduler(this: &WindowSupportExt) -> Scheduler; + + type Scheduler; + + #[wasm_bindgen(method, js_name = postTask)] + fn post_task_with_options( + this: &Scheduler, + callback: &Function, + options: &SchedulerPostTaskOptions, + ) -> Promise; + + type SchedulerPostTaskOptions; +} + +impl SchedulerPostTaskOptions { + fn new() -> Self { + Object::new().unchecked_into() + } + + fn delay(&mut self, val: f64) -> &mut Self { + let r = Reflect::set(self, &JsValue::from("delay"), &val.into()); + debug_assert!(r.is_ok(), "Failed to set `delay` property"); + self + } + + fn signal(&mut self, val: &AbortSignal) -> &mut Self { + let r = Reflect::set(self, &JsValue::from("signal"), &val.into()); + debug_assert!(r.is_ok(), "Failed to set `signal` property"); + self + } +} diff --git a/app/vendor/rune/vendor/winit/src/platform_impl/web/web_sys/worker.js b/app/vendor/rune/vendor/winit/src/platform_impl/web/web_sys/worker.js new file mode 100644 index 0000000..5a8411e --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/platform_impl/web/web_sys/worker.js @@ -0,0 +1,10 @@ +onmessage = event => { + const [port, timeout] = event.data + const f = () => port.postMessage(undefined) + + if ('scheduler' in this) { + scheduler.postTask(f, { delay: timeout }) + } else { + setTimeout(f, timeout) + } +} diff --git a/app/vendor/rune/vendor/winit/src/platform_impl/web/web_sys/worker.min.js b/app/vendor/rune/vendor/winit/src/platform_impl/web/web_sys/worker.min.js new file mode 100644 index 0000000..fd394a7 --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/platform_impl/web/web_sys/worker.min.js @@ -0,0 +1 @@ +onmessage=e=>{let[s,t]=e.data,a=()=>s.postMessage(void 0);"scheduler"in this?scheduler.postTask(a,{delay:t}):setTimeout(a,t)}; diff --git a/app/vendor/rune/vendor/winit/src/platform_impl/web/window.rs b/app/vendor/rune/vendor/winit/src/platform_impl/web/window.rs new file mode 100644 index 0000000..29ca730 --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/platform_impl/web/window.rs @@ -0,0 +1,477 @@ +use crate::dpi::{PhysicalPosition, PhysicalSize, Position, Size}; +use crate::error::{ExternalError, NotSupportedError, OsError as RootOE}; +use crate::icon::Icon; +use crate::window::{ + Cursor, CursorGrabMode, ImePurpose, ResizeDirection, Theme, UserAttentionType, + WindowAttributes, WindowButtons, WindowId as RootWI, WindowLevel, +}; + +use super::main_thread::{MainThreadMarker, MainThreadSafe}; +use super::monitor::MonitorHandle; +use super::r#async::Dispatcher; +use super::{backend, ActiveEventLoop, Fullscreen}; +use web_sys::HtmlCanvasElement; + +use std::cell::RefCell; +use std::collections::VecDeque; +use std::rc::Rc; +use std::sync::Arc; + +pub struct Window { + inner: Dispatcher<Inner>, +} + +pub struct Inner { + id: WindowId, + pub window: web_sys::Window, + canvas: Rc<RefCell<backend::Canvas>>, + destroy_fn: Option<Box<dyn FnOnce()>>, +} + +impl Window { + pub(crate) fn new( + target: &ActiveEventLoop, + mut attr: WindowAttributes, + ) -> Result<Self, RootOE> { + let id = target.generate_id(); + + let window = target.runner.window(); + let document = target.runner.document(); + let canvas = backend::Canvas::create( + target.runner.main_thread(), + id, + window.clone(), + document.clone(), + &mut attr, + )?; + let canvas = Rc::new(RefCell::new(canvas)); + + target.register(&canvas, id); + + let runner = target.runner.clone(); + let destroy_fn = Box::new(move || runner.notify_destroy_window(RootWI(id))); + + let inner = Inner { id, window: window.clone(), canvas, destroy_fn: Some(destroy_fn) }; + + inner.set_title(&attr.title); + inner.set_maximized(attr.maximized); + inner.set_visible(attr.visible); + inner.set_window_icon(attr.window_icon); + inner.set_cursor(attr.cursor); + + let canvas = Rc::downgrade(&inner.canvas); + let (dispatcher, runner) = Dispatcher::new(target.runner.main_thread(), inner).unwrap(); + target.runner.add_canvas(RootWI(id), canvas, runner); + + Ok(Window { inner: dispatcher }) + } + + pub(crate) fn maybe_queue_on_main(&self, f: impl FnOnce(&Inner) + Send + 'static) { + self.inner.dispatch(f) + } + + pub(crate) fn maybe_wait_on_main<R: Send>(&self, f: impl FnOnce(&Inner) -> R + Send) -> R { + self.inner.queue(f) + } + + pub fn canvas(&self) -> Option<HtmlCanvasElement> { + self.inner.value().map(|inner| inner.canvas.borrow().raw().clone()) + } + + pub(crate) fn prevent_default(&self) -> bool { + self.inner.queue(|inner| inner.canvas.borrow().prevent_default.get()) + } + + pub(crate) fn set_prevent_default(&self, prevent_default: bool) { + self.inner.dispatch(move |inner| inner.canvas.borrow().prevent_default.set(prevent_default)) + } + + #[cfg(feature = "rwh_06")] + #[inline] + pub fn raw_window_handle_rwh_06(&self) -> Result<rwh_06::RawWindowHandle, rwh_06::HandleError> { + self.inner + .value() + .map(|inner| { + let canvas = inner.canvas.borrow(); + // SAFETY: This will only work if the reference to `HtmlCanvasElement` stays valid. + let canvas: &wasm_bindgen::JsValue = canvas.raw(); + let window_handle = + rwh_06::WebCanvasWindowHandle::new(std::ptr::NonNull::from(canvas).cast()); + rwh_06::RawWindowHandle::WebCanvas(window_handle) + }) + .ok_or(rwh_06::HandleError::Unavailable) + } + + #[cfg(feature = "rwh_06")] + #[inline] + pub(crate) fn raw_display_handle_rwh_06( + &self, + ) -> Result<rwh_06::RawDisplayHandle, rwh_06::HandleError> { + Ok(rwh_06::RawDisplayHandle::Web(rwh_06::WebDisplayHandle::new())) + } +} + +impl Inner { + pub fn set_title(&self, title: &str) { + self.canvas.borrow().set_attribute("alt", title) + } + + pub fn set_transparent(&self, _transparent: bool) {} + + pub fn set_blur(&self, _blur: bool) {} + + pub fn set_visible(&self, _visible: bool) { + // Intentionally a no-op + } + + #[inline] + pub fn is_visible(&self) -> Option<bool> { + None + } + + pub fn request_redraw(&self) { + self.canvas.borrow().request_animation_frame(); + } + + pub fn pre_present_notify(&self) {} + + pub fn outer_position(&self) -> Result<PhysicalPosition<i32>, NotSupportedError> { + Ok(self.canvas.borrow().position().to_physical(self.scale_factor())) + } + + pub fn inner_position(&self) -> Result<PhysicalPosition<i32>, NotSupportedError> { + // Note: the canvas element has no window decorations, so this is equal to `outer_position`. + self.outer_position() + } + + pub fn set_outer_position(&self, position: Position) { + let canvas = self.canvas.borrow(); + let position = position.to_logical::<f64>(self.scale_factor()); + + backend::set_canvas_position(canvas.document(), canvas.raw(), canvas.style(), position) + } + + #[inline] + pub fn inner_size(&self) -> PhysicalSize<u32> { + self.canvas.borrow().inner_size() + } + + #[inline] + pub fn outer_size(&self) -> PhysicalSize<u32> { + // Note: the canvas element has no window decorations, so this is equal to `inner_size`. + self.inner_size() + } + + #[inline] + pub fn request_inner_size(&self, size: Size) -> Option<PhysicalSize<u32>> { + let size = size.to_logical(self.scale_factor()); + let canvas = self.canvas.borrow(); + backend::set_canvas_size(canvas.document(), canvas.raw(), canvas.style(), size); + None + } + + #[inline] + pub fn set_min_inner_size(&self, dimensions: Option<Size>) { + let dimensions = dimensions.map(|dimensions| dimensions.to_logical(self.scale_factor())); + let canvas = self.canvas.borrow(); + backend::set_canvas_min_size(canvas.document(), canvas.raw(), canvas.style(), dimensions) + } + + #[inline] + pub fn set_max_inner_size(&self, dimensions: Option<Size>) { + let dimensions = dimensions.map(|dimensions| dimensions.to_logical(self.scale_factor())); + let canvas = self.canvas.borrow(); + backend::set_canvas_max_size(canvas.document(), canvas.raw(), canvas.style(), dimensions) + } + + #[inline] + pub fn resize_increments(&self) -> Option<PhysicalSize<u32>> { + None + } + + #[inline] + pub fn set_resize_increments(&self, _increments: Option<Size>) { + // Intentionally a no-op: users can't resize canvas elements + } + + #[inline] + pub fn set_resizable(&self, _resizable: bool) { + // Intentionally a no-op: users can't resize canvas elements + } + + pub fn is_resizable(&self) -> bool { + true + } + + #[inline] + pub fn set_enabled_buttons(&self, _buttons: WindowButtons) {} + + #[inline] + pub fn enabled_buttons(&self) -> WindowButtons { + WindowButtons::all() + } + + #[inline] + pub fn scale_factor(&self) -> f64 { + super::backend::scale_factor(&self.window) + } + + #[inline] + pub fn set_cursor(&self, cursor: Cursor) { + self.canvas.borrow_mut().cursor.set_cursor(cursor) + } + + #[inline] + pub fn set_cursor_position(&self, _position: Position) -> Result<(), ExternalError> { + Err(ExternalError::NotSupported(NotSupportedError::new())) + } + + #[inline] + pub fn set_cursor_grab(&self, mode: CursorGrabMode) -> Result<(), ExternalError> { + let lock = match mode { + CursorGrabMode::None => false, + CursorGrabMode::Locked => true, + CursorGrabMode::Confined => { + return Err(ExternalError::NotSupported(NotSupportedError::new())) + }, + }; + + self.canvas.borrow().set_cursor_lock(lock).map_err(ExternalError::Os) + } + + #[inline] + pub fn set_cursor_visible(&self, visible: bool) { + self.canvas.borrow_mut().cursor.set_cursor_visible(visible) + } + + #[inline] + pub fn drag_window(&self) -> Result<(), ExternalError> { + Err(ExternalError::NotSupported(NotSupportedError::new())) + } + + #[inline] + pub fn drag_resize_window(&self, _direction: ResizeDirection) -> Result<(), ExternalError> { + Err(ExternalError::NotSupported(NotSupportedError::new())) + } + + #[inline] + pub fn show_window_menu(&self, _position: Position) {} + + #[inline] + pub fn set_cursor_hittest(&self, _hittest: bool) -> Result<(), ExternalError> { + Err(ExternalError::NotSupported(NotSupportedError::new())) + } + + #[inline] + pub fn set_minimized(&self, _minimized: bool) { + // Intentionally a no-op, as canvases cannot be 'minimized' + } + + #[inline] + pub fn is_minimized(&self) -> Option<bool> { + // Canvas cannot be 'minimized' + Some(false) + } + + #[inline] + pub fn set_maximized(&self, _maximized: bool) { + // Intentionally a no-op, as canvases cannot be 'maximized' + } + + #[inline] + pub fn is_maximized(&self) -> bool { + // Canvas cannot be 'maximized' + false + } + + #[inline] + pub(crate) fn fullscreen(&self) -> Option<Fullscreen> { + if self.canvas.borrow().is_fullscreen() { + Some(Fullscreen::Borderless(None)) + } else { + None + } + } + + #[inline] + pub(crate) fn set_fullscreen(&self, fullscreen: Option<Fullscreen>) { + let canvas = &self.canvas.borrow(); + + if fullscreen.is_some() { + canvas.request_fullscreen(); + } else { + canvas.exit_fullscreen() + } + } + + #[inline] + pub fn set_decorations(&self, _decorations: bool) { + // Intentionally a no-op, no canvas decorations + } + + pub fn is_decorated(&self) -> bool { + true + } + + #[inline] + pub fn set_window_level(&self, _level: WindowLevel) { + // Intentionally a no-op, no window ordering + } + + #[inline] + pub fn set_window_icon(&self, _window_icon: Option<Icon>) { + // Currently an intentional no-op + } + + #[inline] + pub fn set_ime_cursor_area(&self, _position: Position, _size: Size) { + // Currently a no-op as it does not seem there is good support for this on web + } + + #[inline] + pub fn set_ime_allowed(&self, _allowed: bool) { + // Currently not implemented + } + + #[inline] + pub fn set_ime_purpose(&self, _purpose: ImePurpose) { + // Currently not implemented + } + + #[inline] + pub fn focus_window(&self) { + let _ = self.canvas.borrow().raw().focus(); + } + + #[inline] + pub fn request_user_attention(&self, _request_type: Option<UserAttentionType>) { + // Currently an intentional no-op + } + + #[inline] + pub fn current_monitor(&self) -> Option<MonitorHandle> { + None + } + + #[inline] + pub fn available_monitors(&self) -> VecDeque<MonitorHandle> { + VecDeque::new() + } + + #[inline] + pub fn primary_monitor(&self) -> Option<MonitorHandle> { + None + } + + #[inline] + pub fn id(&self) -> WindowId { + self.id + } + + #[cfg(feature = "rwh_04")] + #[inline] + pub fn raw_window_handle_rwh_04(&self) -> rwh_04::RawWindowHandle { + let mut window_handle = rwh_04::WebHandle::empty(); + window_handle.id = self.id.0; + rwh_04::RawWindowHandle::Web(window_handle) + } + + #[cfg(feature = "rwh_05")] + #[inline] + pub fn raw_window_handle_rwh_05(&self) -> rwh_05::RawWindowHandle { + let mut window_handle = rwh_05::WebWindowHandle::empty(); + window_handle.id = self.id.0; + rwh_05::RawWindowHandle::Web(window_handle) + } + + #[cfg(feature = "rwh_05")] + #[inline] + pub fn raw_display_handle_rwh_05(&self) -> rwh_05::RawDisplayHandle { + rwh_05::RawDisplayHandle::Web(rwh_05::WebDisplayHandle::empty()) + } + + #[inline] + pub fn set_theme(&self, _theme: Option<Theme>) {} + + #[inline] + pub fn theme(&self) -> Option<Theme> { + backend::is_dark_mode(&self.window).map(|is_dark_mode| { + if is_dark_mode { + Theme::Dark + } else { + Theme::Light + } + }) + } + + pub fn set_content_protected(&self, _protected: bool) {} + + #[inline] + pub fn has_focus(&self) -> bool { + self.canvas.borrow().has_focus.get() + } + + pub fn title(&self) -> String { + String::new() + } + + pub fn reset_dead_keys(&self) { + // Not supported + } +} + +impl Drop for Inner { + fn drop(&mut self) { + if let Some(destroy_fn) = self.destroy_fn.take() { + destroy_fn(); + } + } +} +#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub struct WindowId(pub(crate) u32); + +impl WindowId { + pub const fn dummy() -> Self { + Self(0) + } +} + +impl From<WindowId> for u64 { + fn from(window_id: WindowId) -> Self { + window_id.0 as u64 + } +} + +impl From<u64> for WindowId { + fn from(raw_id: u64) -> Self { + Self(raw_id as u32) + } +} + +#[derive(Clone, Debug)] +pub struct PlatformSpecificWindowAttributes { + pub(crate) canvas: Option<Arc<MainThreadSafe<backend::RawCanvasType>>>, + pub(crate) prevent_default: bool, + pub(crate) focusable: bool, + pub(crate) append: bool, +} + +impl PlatformSpecificWindowAttributes { + pub(crate) fn set_canvas(&mut self, canvas: Option<backend::RawCanvasType>) { + let Some(canvas) = canvas else { + self.canvas = None; + return; + }; + + let main_thread = MainThreadMarker::new() + .expect("received a `HtmlCanvasElement` outside the window context"); + + self.canvas = Some(Arc::new(MainThreadSafe::new(main_thread, canvas))); + } +} + +impl Default for PlatformSpecificWindowAttributes { + fn default() -> Self { + Self { canvas: None, prevent_default: true, focusable: true, append: false } + } +} diff --git a/app/vendor/rune/vendor/winit/src/platform_impl/windows/dark_mode.rs b/app/vendor/rune/vendor/winit/src/platform_impl/windows/dark_mode.rs new file mode 100644 index 0000000..67c4fc5 --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/platform_impl/windows/dark_mode.rs @@ -0,0 +1,174 @@ +/// This is a simple implementation of support for Windows Dark Mode, +/// which is inspired by the solution in https://github.com/ysc3839/win32-darkmode +use std::{ffi::c_void, ptr}; + +use crate::utils::Lazy; +use windows_sys::core::PCSTR; +use windows_sys::Win32::Foundation::{BOOL, HWND, NTSTATUS, S_OK}; +use windows_sys::Win32::System::LibraryLoader::{ + GetProcAddress, LoadLibraryExA, LOAD_LIBRARY_SEARCH_SYSTEM32, +}; +use windows_sys::Win32::System::SystemInformation::OSVERSIONINFOW; +use windows_sys::Win32::UI::Accessibility::{HCF_HIGHCONTRASTON, HIGHCONTRASTA}; +use windows_sys::Win32::UI::Controls::SetWindowTheme; +use windows_sys::Win32::UI::WindowsAndMessaging::{SystemParametersInfoA, SPI_GETHIGHCONTRAST}; + +use crate::window::Theme; + +use super::util; + +static WIN10_BUILD_VERSION: Lazy<Option<u32>> = Lazy::new(|| { + type RtlGetVersion = unsafe extern "system" fn(*mut OSVERSIONINFOW) -> NTSTATUS; + let handle = get_function!("ntdll.dll", RtlGetVersion); + + if let Some(rtl_get_version) = handle { + unsafe { + let mut vi = OSVERSIONINFOW { + dwOSVersionInfoSize: 0, + dwMajorVersion: 0, + dwMinorVersion: 0, + dwBuildNumber: 0, + dwPlatformId: 0, + szCSDVersion: [0; 128], + }; + + let status = (rtl_get_version)(&mut vi); + + if status >= 0 && vi.dwMajorVersion == 10 && vi.dwMinorVersion == 0 { + Some(vi.dwBuildNumber) + } else { + None + } + } + } else { + None + } +}); + +static DARK_MODE_SUPPORTED: Lazy<bool> = Lazy::new(|| { + // We won't try to do anything for windows versions < 17763 + // (Windows 10 October 2018 update) + match *WIN10_BUILD_VERSION { + Some(v) => v >= 17763, + None => false, + } +}); + +static DARK_THEME_NAME: Lazy<Vec<u16>> = Lazy::new(|| util::encode_wide("DarkMode_Explorer")); +static LIGHT_THEME_NAME: Lazy<Vec<u16>> = Lazy::new(|| util::encode_wide("")); + +/// Attempt to set a theme on a window, if necessary. +/// Returns the theme that was picked +pub fn try_theme(hwnd: HWND, preferred_theme: Option<Theme>) -> Theme { + if *DARK_MODE_SUPPORTED { + let is_dark_mode = match preferred_theme { + Some(theme) => theme == Theme::Dark, + None => should_use_dark_mode(), + }; + + let theme = if is_dark_mode { Theme::Dark } else { Theme::Light }; + let theme_name = match theme { + Theme::Dark => DARK_THEME_NAME.as_ptr(), + Theme::Light => LIGHT_THEME_NAME.as_ptr(), + }; + + let status = unsafe { SetWindowTheme(hwnd, theme_name, ptr::null()) }; + + if status == S_OK && set_dark_mode_for_window(hwnd, is_dark_mode) { + return theme; + } + } + + Theme::Light +} + +fn set_dark_mode_for_window(hwnd: HWND, is_dark_mode: bool) -> bool { + // Uses Windows undocumented API SetWindowCompositionAttribute, + // as seen in win32-darkmode example linked at top of file. + + type SetWindowCompositionAttribute = + unsafe extern "system" fn(HWND, *mut WINDOWCOMPOSITIONATTRIBDATA) -> BOOL; + + #[allow(clippy::upper_case_acronyms)] + type WINDOWCOMPOSITIONATTRIB = u32; + const WCA_USEDARKMODECOLORS: WINDOWCOMPOSITIONATTRIB = 26; + + #[allow(non_snake_case)] + #[allow(clippy::upper_case_acronyms)] + #[repr(C)] + struct WINDOWCOMPOSITIONATTRIBDATA { + Attrib: WINDOWCOMPOSITIONATTRIB, + pvData: *mut c_void, + cbData: usize, + } + + static SET_WINDOW_COMPOSITION_ATTRIBUTE: Lazy<Option<SetWindowCompositionAttribute>> = + Lazy::new(|| get_function!("user32.dll", SetWindowCompositionAttribute)); + + if let Some(set_window_composition_attribute) = *SET_WINDOW_COMPOSITION_ATTRIBUTE { + unsafe { + // SetWindowCompositionAttribute needs a bigbool (i32), not bool. + let mut is_dark_mode_bigbool = BOOL::from(is_dark_mode); + + let mut data = WINDOWCOMPOSITIONATTRIBDATA { + Attrib: WCA_USEDARKMODECOLORS, + pvData: &mut is_dark_mode_bigbool as *mut _ as _, + cbData: std::mem::size_of_val(&is_dark_mode_bigbool) as _, + }; + + let status = set_window_composition_attribute(hwnd, &mut data); + + status != false.into() + } + } else { + false + } +} + +pub fn should_use_dark_mode() -> bool { + should_apps_use_dark_mode() && !is_high_contrast() +} + +fn should_apps_use_dark_mode() -> bool { + type ShouldAppsUseDarkMode = unsafe extern "system" fn() -> bool; + static SHOULD_APPS_USE_DARK_MODE: Lazy<Option<ShouldAppsUseDarkMode>> = Lazy::new(|| unsafe { + const UXTHEME_SHOULDAPPSUSEDARKMODE_ORDINAL: PCSTR = 132 as PCSTR; + + // We won't try to do anything for windows versions < 17763 + // (Windows 10 October 2018 update) + if !*DARK_MODE_SUPPORTED { + return None; + } + + // Rune: load uxtheme.dll from System32 only, not the app directory or CWD. + let module = + LoadLibraryExA("uxtheme.dll\0".as_ptr().cast(), 0, LOAD_LIBRARY_SEARCH_SYSTEM32); + + if module == 0 { + return None; + } + + let handle = GetProcAddress(module, UXTHEME_SHOULDAPPSUSEDARKMODE_ORDINAL); + + handle.map(|handle| std::mem::transmute(handle)) + }); + + SHOULD_APPS_USE_DARK_MODE + .map(|should_apps_use_dark_mode| unsafe { (should_apps_use_dark_mode)() }) + .unwrap_or(false) +} + +fn is_high_contrast() -> bool { + let mut hc = HIGHCONTRASTA { cbSize: 0, dwFlags: 0, lpszDefaultScheme: ptr::null_mut() }; + + let ok = unsafe { + SystemParametersInfoA( + SPI_GETHIGHCONTRAST, + std::mem::size_of_val(&hc) as _, + &mut hc as *mut _ as _, + 0, + ) + }; + + ok != false.into() && util::has_flag(hc.dwFlags, HCF_HIGHCONTRASTON) +} diff --git a/app/vendor/rune/vendor/winit/src/platform_impl/windows/definitions.rs b/app/vendor/rune/vendor/winit/src/platform_impl/windows/definitions.rs new file mode 100644 index 0000000..c015ffc --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/platform_impl/windows/definitions.rs @@ -0,0 +1,148 @@ +#![allow(non_snake_case)] +#![allow(non_upper_case_globals)] + +use std::ffi::c_void; + +use windows_sys::core::{IUnknown, GUID, HRESULT}; +use windows_sys::Win32::Foundation::{BOOL, HWND, POINTL}; +use windows_sys::Win32::System::Com::{ + IAdviseSink, IDataObject, IEnumFORMATETC, IEnumSTATDATA, FORMATETC, STGMEDIUM, +}; + +#[repr(C)] +pub struct IUnknownVtbl { + pub QueryInterface: unsafe extern "system" fn( + This: *mut IUnknown, + riid: *const GUID, + ppvObject: *mut *mut c_void, + ) -> HRESULT, + pub AddRef: unsafe extern "system" fn(This: *mut IUnknown) -> u32, + pub Release: unsafe extern "system" fn(This: *mut IUnknown) -> u32, +} + +#[repr(C)] +pub struct IDataObjectVtbl { + pub parent: IUnknownVtbl, + pub GetData: unsafe extern "system" fn( + This: *mut IDataObject, + pformatetcIn: *const FORMATETC, + pmedium: *mut STGMEDIUM, + ) -> HRESULT, + pub GetDataHere: unsafe extern "system" fn( + This: *mut IDataObject, + pformatetc: *const FORMATETC, + pmedium: *mut STGMEDIUM, + ) -> HRESULT, + QueryGetData: + unsafe extern "system" fn(This: *mut IDataObject, pformatetc: *const FORMATETC) -> HRESULT, + pub GetCanonicalFormatEtc: unsafe extern "system" fn( + This: *mut IDataObject, + pformatetcIn: *const FORMATETC, + pformatetcOut: *mut FORMATETC, + ) -> HRESULT, + pub SetData: unsafe extern "system" fn( + This: *mut IDataObject, + pformatetc: *const FORMATETC, + pformatetcOut: *const FORMATETC, + fRelease: BOOL, + ) -> HRESULT, + pub EnumFormatEtc: unsafe extern "system" fn( + This: *mut IDataObject, + dwDirection: u32, + ppenumFormatEtc: *mut *mut IEnumFORMATETC, + ) -> HRESULT, + pub DAdvise: unsafe extern "system" fn( + This: *mut IDataObject, + pformatetc: *const FORMATETC, + advf: u32, + pAdvSInk: *const IAdviseSink, + pdwConnection: *mut u32, + ) -> HRESULT, + pub DUnadvise: unsafe extern "system" fn(This: *mut IDataObject, dwConnection: u32) -> HRESULT, + pub EnumDAdvise: unsafe extern "system" fn( + This: *mut IDataObject, + ppenumAdvise: *const *const IEnumSTATDATA, + ) -> HRESULT, +} + +#[repr(C)] +pub struct IDropTargetVtbl { + pub parent: IUnknownVtbl, + pub DragEnter: unsafe extern "system" fn( + This: *mut IDropTarget, + pDataObj: *const IDataObject, + grfKeyState: u32, + pt: *const POINTL, + pdwEffect: *mut u32, + ) -> HRESULT, + pub DragOver: unsafe extern "system" fn( + This: *mut IDropTarget, + grfKeyState: u32, + pt: *const POINTL, + pdwEffect: *mut u32, + ) -> HRESULT, + pub DragLeave: unsafe extern "system" fn(This: *mut IDropTarget) -> HRESULT, + pub Drop: unsafe extern "system" fn( + This: *mut IDropTarget, + pDataObj: *const IDataObject, + grfKeyState: u32, + pt: *const POINTL, + pdwEffect: *mut u32, + ) -> HRESULT, +} + +#[repr(C)] +pub struct IDropTarget { + pub lpVtbl: *const IDropTargetVtbl, +} + +#[repr(C)] +pub struct ITaskbarListVtbl { + pub parent: IUnknownVtbl, + pub HrInit: unsafe extern "system" fn(This: *mut ITaskbarList) -> HRESULT, + pub AddTab: unsafe extern "system" fn(This: *mut ITaskbarList, hwnd: HWND) -> HRESULT, + pub DeleteTab: unsafe extern "system" fn(This: *mut ITaskbarList, hwnd: HWND) -> HRESULT, + pub ActivateTab: unsafe extern "system" fn(This: *mut ITaskbarList, hwnd: HWND) -> HRESULT, + pub SetActiveAlt: unsafe extern "system" fn(This: *mut ITaskbarList, hwnd: HWND) -> HRESULT, +} + +#[repr(C)] +pub struct ITaskbarList { + pub lpVtbl: *const ITaskbarListVtbl, +} + +#[repr(C)] +pub struct ITaskbarList2Vtbl { + pub parent: ITaskbarListVtbl, + pub MarkFullscreenWindow: unsafe extern "system" fn( + This: *mut ITaskbarList2, + hwnd: HWND, + fFullscreen: BOOL, + ) -> HRESULT, +} + +#[repr(C)] +pub struct ITaskbarList2 { + pub lpVtbl: *const ITaskbarList2Vtbl, +} + +pub const CLSID_TaskbarList: GUID = GUID { + data1: 0x56fdf344, + data2: 0xfd6d, + data3: 0x11d0, + data4: [0x95, 0x8a, 0x00, 0x60, 0x97, 0xc9, 0xa0, 0x90], +}; + +pub const IID_ITaskbarList: GUID = GUID { + data1: 0x56fdf342, + data2: 0xfd6d, + data3: 0x11d0, + data4: [0x95, 0x8a, 0x00, 0x60, 0x97, 0xc9, 0xa0, 0x90], +}; + +pub const IID_ITaskbarList2: GUID = GUID { + data1: 0x602d4995, + data2: 0xb13a, + data3: 0x429b, + data4: [0xa6, 0x6e, 0x19, 0x35, 0xe4, 0x4f, 0x43, 0x17], +}; diff --git a/app/vendor/rune/vendor/winit/src/platform_impl/windows/dpi.rs b/app/vendor/rune/vendor/winit/src/platform_impl/windows/dpi.rs new file mode 100644 index 0000000..5880069 --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/platform_impl/windows/dpi.rs @@ -0,0 +1,112 @@ +#![allow(non_snake_case, unused_unsafe)] + +use std::sync::Once; + +use windows_sys::Win32::Foundation::{HWND, S_OK}; +use windows_sys::Win32::Graphics::Gdi::{ + GetDC, GetDeviceCaps, MonitorFromWindow, HMONITOR, LOGPIXELSX, MONITOR_DEFAULTTONEAREST, +}; +use windows_sys::Win32::UI::HiDpi::{ + DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE, DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2, + MDT_EFFECTIVE_DPI, PROCESS_PER_MONITOR_DPI_AWARE, +}; +use windows_sys::Win32::UI::WindowsAndMessaging::IsProcessDPIAware; + +use crate::platform_impl::platform::util::{ + ENABLE_NON_CLIENT_DPI_SCALING, GET_DPI_FOR_MONITOR, GET_DPI_FOR_WINDOW, SET_PROCESS_DPI_AWARE, + SET_PROCESS_DPI_AWARENESS, SET_PROCESS_DPI_AWARENESS_CONTEXT, +}; + +pub fn become_dpi_aware() { + static ENABLE_DPI_AWARENESS: Once = Once::new(); + ENABLE_DPI_AWARENESS.call_once(|| { + unsafe { + if let Some(SetProcessDpiAwarenessContext) = *SET_PROCESS_DPI_AWARENESS_CONTEXT { + // We are on Windows 10 Anniversary Update (1607) or later. + if SetProcessDpiAwarenessContext(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2) + == false.into() + { + // V2 only works with Windows 10 Creators Update (1703). Try using the older + // V1 if we can't set V2. + SetProcessDpiAwarenessContext(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE); + } + } else if let Some(SetProcessDpiAwareness) = *SET_PROCESS_DPI_AWARENESS { + // We are on Windows 8.1 or later. + SetProcessDpiAwareness(PROCESS_PER_MONITOR_DPI_AWARE); + } else if let Some(SetProcessDPIAware) = *SET_PROCESS_DPI_AWARE { + // We are on Vista or later. + SetProcessDPIAware(); + } + } + }); +} + +pub fn enable_non_client_dpi_scaling(hwnd: HWND) { + unsafe { + if let Some(EnableNonClientDpiScaling) = *ENABLE_NON_CLIENT_DPI_SCALING { + EnableNonClientDpiScaling(hwnd); + } + } +} + +pub fn get_monitor_dpi(hmonitor: HMONITOR) -> Option<u32> { + unsafe { + if let Some(GetDpiForMonitor) = *GET_DPI_FOR_MONITOR { + // We are on Windows 8.1 or later. + let mut dpi_x = 0; + let mut dpi_y = 0; + if GetDpiForMonitor(hmonitor, MDT_EFFECTIVE_DPI, &mut dpi_x, &mut dpi_y) == S_OK { + // MSDN says that "the values of *dpiX and *dpiY are identical. You only need to + // record one of the values to determine the DPI and respond appropriately". + // https://msdn.microsoft.com/en-us/library/windows/desktop/dn280510(v=vs.85).aspx + return Some(dpi_x); + } + } + } + None +} + +pub const BASE_DPI: u32 = 96; +pub fn dpi_to_scale_factor(dpi: u32) -> f64 { + dpi as f64 / BASE_DPI as f64 +} + +pub unsafe fn hwnd_dpi(hwnd: HWND) -> u32 { + let hdc = unsafe { GetDC(hwnd) }; + if hdc == 0 { + panic!("[winit] `GetDC` returned null!"); + } + if let Some(GetDpiForWindow) = *GET_DPI_FOR_WINDOW { + // We are on Windows 10 Anniversary Update (1607) or later. + match unsafe { GetDpiForWindow(hwnd) } { + 0 => BASE_DPI, // 0 is returned if hwnd is invalid + dpi => dpi, + } + } else if let Some(GetDpiForMonitor) = *GET_DPI_FOR_MONITOR { + // We are on Windows 8.1 or later. + let monitor = unsafe { MonitorFromWindow(hwnd, MONITOR_DEFAULTTONEAREST) }; + if monitor == 0 { + return BASE_DPI; + } + + let mut dpi_x = 0; + let mut dpi_y = 0; + if unsafe { GetDpiForMonitor(monitor, MDT_EFFECTIVE_DPI, &mut dpi_x, &mut dpi_y) } == S_OK { + dpi_x + } else { + BASE_DPI + } + } else { + // We are on Vista or later. + if unsafe { IsProcessDPIAware() } != false.into() { + // If the process is DPI aware, then scaling must be handled by the application using + // this DPI value. + unsafe { GetDeviceCaps(hdc, LOGPIXELSX as i32) as u32 } + } else { + // If the process is DPI unaware, then scaling is performed by the OS; we thus return + // 96 (scale factor 1.0) to prevent the window from being re-scaled by both the + // application and the WM. + BASE_DPI + } + } +} diff --git a/app/vendor/rune/vendor/winit/src/platform_impl/windows/drop_handler.rs b/app/vendor/rune/vendor/winit/src/platform_impl/windows/drop_handler.rs new file mode 100644 index 0000000..38cb5c5 --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/platform_impl/windows/drop_handler.rs @@ -0,0 +1,237 @@ +use std::ffi::{c_void, OsString}; +use std::os::windows::ffi::OsStringExt; +use std::path::PathBuf; +use std::ptr; +use std::sync::atomic::{AtomicUsize, Ordering}; + +use windows_sys::core::{IUnknown, GUID, HRESULT}; +use windows_sys::Win32::Foundation::{DV_E_FORMATETC, HWND, POINTL, S_OK}; +use windows_sys::Win32::System::Com::{IDataObject, DVASPECT_CONTENT, FORMATETC, TYMED_HGLOBAL}; +use windows_sys::Win32::System::Ole::{CF_HDROP, DROPEFFECT_COPY, DROPEFFECT_NONE}; +use windows_sys::Win32::UI::Shell::{DragFinish, DragQueryFileW, HDROP}; + +use tracing::debug; + +use crate::platform_impl::platform::definitions::{ + IDataObjectVtbl, IDropTarget, IDropTargetVtbl, IUnknownVtbl, +}; +use crate::platform_impl::platform::WindowId; + +use crate::event::Event; +use crate::window::WindowId as RootWindowId; + +#[repr(C)] +pub struct FileDropHandlerData { + pub interface: IDropTarget, + refcount: AtomicUsize, + window: HWND, + send_event: Box<dyn Fn(Event<()>)>, + cursor_effect: u32, + hovered_is_valid: bool, /* If the currently hovered item is not valid there must not be any + * `HoveredFileCancelled` emitted */ +} + +pub struct FileDropHandler { + pub data: *mut FileDropHandlerData, +} + +#[allow(non_snake_case)] +impl FileDropHandler { + pub fn new(window: HWND, send_event: Box<dyn Fn(Event<()>)>) -> FileDropHandler { + let data = Box::new(FileDropHandlerData { + interface: IDropTarget { lpVtbl: &DROP_TARGET_VTBL as *const IDropTargetVtbl }, + refcount: AtomicUsize::new(1), + window, + send_event, + cursor_effect: DROPEFFECT_NONE, + hovered_is_valid: false, + }); + FileDropHandler { data: Box::into_raw(data) } + } + + // Implement IUnknown + pub unsafe extern "system" fn QueryInterface( + _this: *mut IUnknown, + _riid: *const GUID, + _ppvObject: *mut *mut c_void, + ) -> HRESULT { + // This function doesn't appear to be required for an `IDropTarget`. + // An implementation would be nice however. + unimplemented!(); + } + + pub unsafe extern "system" fn AddRef(this: *mut IUnknown) -> u32 { + let drop_handler_data = unsafe { Self::from_interface(this) }; + let count = drop_handler_data.refcount.fetch_add(1, Ordering::Release) + 1; + count as u32 + } + + pub unsafe extern "system" fn Release(this: *mut IUnknown) -> u32 { + let drop_handler = unsafe { Self::from_interface(this) }; + let count = drop_handler.refcount.fetch_sub(1, Ordering::Release) - 1; + if count == 0 { + // Destroy the underlying data + drop(unsafe { Box::from_raw(drop_handler as *mut FileDropHandlerData) }); + } + count as u32 + } + + pub unsafe extern "system" fn DragEnter( + this: *mut IDropTarget, + pDataObj: *const IDataObject, + _grfKeyState: u32, + _pt: *const POINTL, + pdwEffect: *mut u32, + ) -> HRESULT { + use crate::event::WindowEvent::HoveredFile; + let drop_handler = unsafe { Self::from_interface(this) }; + let hdrop = unsafe { + Self::iterate_filenames(pDataObj, |filename| { + drop_handler.send_event(Event::WindowEvent { + window_id: RootWindowId(WindowId(drop_handler.window)), + event: HoveredFile(filename), + }); + }) + }; + drop_handler.hovered_is_valid = hdrop.is_some(); + drop_handler.cursor_effect = + if drop_handler.hovered_is_valid { DROPEFFECT_COPY } else { DROPEFFECT_NONE }; + unsafe { + *pdwEffect = drop_handler.cursor_effect; + } + + S_OK + } + + pub unsafe extern "system" fn DragOver( + this: *mut IDropTarget, + _grfKeyState: u32, + _pt: *const POINTL, + pdwEffect: *mut u32, + ) -> HRESULT { + let drop_handler = unsafe { Self::from_interface(this) }; + unsafe { + *pdwEffect = drop_handler.cursor_effect; + } + + S_OK + } + + pub unsafe extern "system" fn DragLeave(this: *mut IDropTarget) -> HRESULT { + use crate::event::WindowEvent::HoveredFileCancelled; + let drop_handler = unsafe { Self::from_interface(this) }; + if drop_handler.hovered_is_valid { + drop_handler.send_event(Event::WindowEvent { + window_id: RootWindowId(WindowId(drop_handler.window)), + event: HoveredFileCancelled, + }); + } + + S_OK + } + + pub unsafe extern "system" fn Drop( + this: *mut IDropTarget, + pDataObj: *const IDataObject, + _grfKeyState: u32, + _pt: *const POINTL, + _pdwEffect: *mut u32, + ) -> HRESULT { + use crate::event::WindowEvent::DroppedFile; + let drop_handler = unsafe { Self::from_interface(this) }; + let hdrop = unsafe { + Self::iterate_filenames(pDataObj, |filename| { + drop_handler.send_event(Event::WindowEvent { + window_id: RootWindowId(WindowId(drop_handler.window)), + event: DroppedFile(filename), + }); + }) + }; + if let Some(hdrop) = hdrop { + unsafe { DragFinish(hdrop) }; + } + + S_OK + } + + unsafe fn from_interface<'a, InterfaceT>(this: *mut InterfaceT) -> &'a mut FileDropHandlerData { + unsafe { &mut *(this as *mut _) } + } + + unsafe fn iterate_filenames<F>(data_obj: *const IDataObject, callback: F) -> Option<HDROP> + where + F: Fn(PathBuf), + { + let drop_format = FORMATETC { + cfFormat: CF_HDROP, + ptd: ptr::null_mut(), + dwAspect: DVASPECT_CONTENT, + lindex: -1, + tymed: TYMED_HGLOBAL as u32, + }; + + let mut medium = unsafe { std::mem::zeroed() }; + let get_data_fn = unsafe { (*(*data_obj).cast::<IDataObjectVtbl>()).GetData }; + let get_data_result = unsafe { get_data_fn(data_obj as *mut _, &drop_format, &mut medium) }; + if get_data_result >= 0 { + let hdrop = unsafe { medium.u.hGlobal as HDROP }; + + // The second parameter (0xFFFFFFFF) instructs the function to return the item count + let item_count = unsafe { DragQueryFileW(hdrop, 0xffffffff, ptr::null_mut(), 0) }; + + for i in 0..item_count { + // Get the length of the path string NOT including the terminating null character. + // Previously, this was using a fixed size array of MAX_PATH length, but the + // Windows API allows longer paths under certain circumstances. + let character_count = + unsafe { DragQueryFileW(hdrop, i, ptr::null_mut(), 0) as usize }; + let str_len = character_count + 1; + + // Fill path_buf with the null-terminated file name + let mut path_buf = Vec::with_capacity(str_len); + unsafe { + DragQueryFileW(hdrop, i, path_buf.as_mut_ptr(), str_len as u32); + path_buf.set_len(str_len); + } + + callback(OsString::from_wide(&path_buf[0..character_count]).into()); + } + + Some(hdrop) + } else if get_data_result == DV_E_FORMATETC { + // If the dropped item is not a file this error will occur. + // In this case it is OK to return without taking further action. + debug!("Error occurred while processing dropped/hovered item: item is not a file."); + None + } else { + debug!("Unexpected error occurred while processing dropped/hovered item."); + None + } + } +} + +impl FileDropHandlerData { + fn send_event(&self, event: Event<()>) { + (self.send_event)(event); + } +} + +impl Drop for FileDropHandler { + fn drop(&mut self) { + unsafe { + FileDropHandler::Release(self.data as *mut IUnknown); + } + } +} + +static DROP_TARGET_VTBL: IDropTargetVtbl = IDropTargetVtbl { + parent: IUnknownVtbl { + QueryInterface: FileDropHandler::QueryInterface, + AddRef: FileDropHandler::AddRef, + Release: FileDropHandler::Release, + }, + DragEnter: FileDropHandler::DragEnter, + DragOver: FileDropHandler::DragOver, + DragLeave: FileDropHandler::DragLeave, + Drop: FileDropHandler::Drop, +}; diff --git a/app/vendor/rune/vendor/winit/src/platform_impl/windows/event_loop.rs b/app/vendor/rune/vendor/winit/src/platform_impl/windows/event_loop.rs new file mode 100644 index 0000000..c386d64 --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/platform_impl/windows/event_loop.rs @@ -0,0 +1,2697 @@ +#![allow(non_snake_case)] + +mod runner; + +use std::cell::Cell; +use std::collections::VecDeque; +use std::ffi::c_void; +use std::marker::PhantomData; +use std::os::windows::io::{AsRawHandle as _, FromRawHandle as _, OwnedHandle, RawHandle}; +use std::rc::Rc; +use std::sync::atomic::{AtomicU32, Ordering}; +use std::sync::mpsc::{self, Receiver, Sender}; +use std::sync::{Arc, Mutex, MutexGuard}; +use std::time::{Duration, Instant}; +use std::{mem, panic, ptr}; + +use crate::utils::Lazy; + +use windows_sys::Win32::Devices::HumanInterfaceDevice::MOUSE_MOVE_RELATIVE; +use windows_sys::Win32::Foundation::{ + GetLastError, BOOL, FALSE, HANDLE, HWND, LPARAM, LRESULT, POINT, RECT, WAIT_FAILED, WPARAM, +}; +use windows_sys::Win32::Graphics::Dwm::{DwmSetWindowAttribute, DWMWA_CLOAK}; +use windows_sys::Win32::Graphics::Gdi::{ + GetMonitorInfoW, MonitorFromRect, MonitorFromWindow, RedrawWindow, ScreenToClient, + ValidateRect, MONITORINFO, MONITOR_DEFAULTTONULL, RDW_INTERNALPAINT, SC_SCREENSAVE, +}; +use windows_sys::Win32::System::Ole::RevokeDragDrop; +use windows_sys::Win32::System::Threading::{ + CreateWaitableTimerExW, GetCurrentThreadId, SetWaitableTimer, + CREATE_WAITABLE_TIMER_HIGH_RESOLUTION, INFINITE, TIMER_ALL_ACCESS, +}; +use windows_sys::Win32::UI::Controls::{HOVER_DEFAULT, WM_MOUSELEAVE}; +use windows_sys::Win32::UI::Input::Ime::{GCS_COMPSTR, GCS_RESULTSTR, ISC_SHOWUICOMPOSITIONWINDOW}; +use windows_sys::Win32::UI::Input::KeyboardAndMouse::{ + ReleaseCapture, SetCapture, TrackMouseEvent, TME_LEAVE, TRACKMOUSEEVENT, +}; +use windows_sys::Win32::UI::Input::Pointer::{ + POINTER_FLAG_DOWN, POINTER_FLAG_UP, POINTER_FLAG_UPDATE, +}; +use windows_sys::Win32::UI::Input::Touch::{ + CloseTouchInputHandle, GetTouchInputInfo, TOUCHEVENTF_DOWN, TOUCHEVENTF_MOVE, TOUCHEVENTF_UP, + TOUCHINPUT, +}; +use windows_sys::Win32::UI::Input::{RAWINPUT, RIM_TYPEKEYBOARD, RIM_TYPEMOUSE}; +use windows_sys::Win32::UI::WindowsAndMessaging::{ + CreateWindowExW, DefWindowProcW, DestroyWindow, DispatchMessageW, GetClientRect, GetCursorPos, + GetMenu, LoadCursorW, MsgWaitForMultipleObjectsEx, PeekMessageW, PostMessageW, + RegisterClassExW, RegisterWindowMessageA, SetCursor, SetWindowPos, TranslateMessage, + CREATESTRUCTW, GIDC_ARRIVAL, GIDC_REMOVAL, GWL_STYLE, GWL_USERDATA, HTCAPTION, HTCLIENT, + MINMAXINFO, MNC_CLOSE, MSG, MWMO_INPUTAVAILABLE, NCCALCSIZE_PARAMS, PM_REMOVE, PT_PEN, + PT_TOUCH, QS_ALLINPUT, RI_MOUSE_HWHEEL, RI_MOUSE_WHEEL, SC_MINIMIZE, SC_RESTORE, + SIZE_MAXIMIZED, SWP_NOACTIVATE, SWP_NOMOVE, SWP_NOSIZE, SWP_NOZORDER, WHEEL_DELTA, WINDOWPOS, + WMSZ_BOTTOM, WMSZ_BOTTOMLEFT, WMSZ_BOTTOMRIGHT, WMSZ_LEFT, WMSZ_RIGHT, WMSZ_TOP, WMSZ_TOPLEFT, + WMSZ_TOPRIGHT, WM_CAPTURECHANGED, WM_CHAR, WM_CLOSE, WM_CREATE, WM_DESTROY, WM_DPICHANGED, + WM_ENTERSIZEMOVE, WM_EXITSIZEMOVE, WM_GETMINMAXINFO, WM_IME_COMPOSITION, WM_IME_ENDCOMPOSITION, + WM_IME_SETCONTEXT, WM_IME_STARTCOMPOSITION, WM_INPUT, WM_INPUT_DEVICE_CHANGE, WM_KEYDOWN, + WM_KEYUP, WM_KILLFOCUS, WM_LBUTTONDOWN, WM_LBUTTONUP, WM_MBUTTONDOWN, WM_MBUTTONUP, + WM_MENUCHAR, WM_MOUSEHWHEEL, WM_MOUSEMOVE, WM_MOUSEWHEEL, WM_NCACTIVATE, WM_NCCALCSIZE, + WM_NCCREATE, WM_NCDESTROY, WM_NCLBUTTONDOWN, WM_PAINT, WM_POINTERDOWN, WM_POINTERUP, + WM_POINTERUPDATE, WM_RBUTTONDOWN, WM_RBUTTONUP, WM_SETCURSOR, WM_SETFOCUS, WM_SETTINGCHANGE, + WM_SIZE, WM_SIZING, WM_SYSCOMMAND, WM_SYSKEYDOWN, WM_SYSKEYUP, WM_TOUCH, WM_WINDOWPOSCHANGED, + WM_WINDOWPOSCHANGING, WM_XBUTTONDOWN, WM_XBUTTONUP, WNDCLASSEXW, WS_EX_LAYERED, + WS_EX_NOACTIVATE, WS_EX_TOOLWINDOW, WS_EX_TRANSPARENT, WS_OVERLAPPED, WS_POPUP, WS_VISIBLE, +}; + +use crate::dpi::{PhysicalPosition, PhysicalSize}; +use crate::error::EventLoopError; +use crate::event::{ + DeviceEvent, Event, Force, Ime, InnerSizeWriter, RawKeyEvent, Touch, TouchPhase, WindowEvent, +}; +use crate::event_loop::{ActiveEventLoop as RootAEL, ControlFlow, DeviceEvents, EventLoopClosed}; +use crate::keyboard::ModifiersState; +use crate::platform::pump_events::PumpStatus; +use crate::platform_impl::platform::dark_mode::try_theme; +use crate::platform_impl::platform::dpi::{become_dpi_aware, dpi_to_scale_factor}; +use crate::platform_impl::platform::drop_handler::FileDropHandler; +use crate::platform_impl::platform::icon::WinCursor; +use crate::platform_impl::platform::ime::ImeContext; +use crate::platform_impl::platform::keyboard::KeyEventBuilder; +use crate::platform_impl::platform::keyboard_layout::LAYOUT_CACHE; +use crate::platform_impl::platform::monitor::{self, MonitorHandle}; +use crate::platform_impl::platform::window::InitData; +use crate::platform_impl::platform::window_state::{ + CursorFlags, ImeState, WindowFlags, WindowState, +}; +use crate::platform_impl::platform::{ + raw_input, util, wrap_device_id, Fullscreen, WindowId, DEVICE_ID, +}; +use crate::window::{ + CustomCursor as RootCustomCursor, CustomCursorSource, Theme, WindowId as RootWindowId, +}; +use runner::{EventLoopRunner, EventLoopRunnerShared}; + +use super::window::set_skip_taskbar; +use super::SelectedCursor; + +/// some backends like macos uses an uninhabited `Never` type, +/// on windows, `UserEvent`s are also dispatched through the +/// WNDPROC callback, and due to the re-entrant nature of the +/// callback, recursively delivered events must be queued in a +/// buffer, the current implementation put this queue in +/// `EventLoopRunner`, which is shared between the event pumping +/// loop and the callback. because it's hard to decide from the +/// outside whether a event needs to be buffered, I decided not +/// use `Event<Never>` for the shared runner state, but use unit +/// as a placeholder so user events can be buffered as usual, +/// the real `UserEvent` is pulled from the mpsc channel directly +/// when the placeholder event is delivered to the event handler +pub(crate) struct UserEventPlaceholder; + +// here below, the generic `EventLoopRunnerShared<T>` is replaced with +// `EventLoopRunnerShared<UserEventPlaceholder>` so we can get rid +// of the generic parameter T in types which don't depend on T. +// this is the approach which requires minimum changes to current +// backend implementation. it should be considered transitional +// and should be refactored and cleaned up eventually, I hope. + +pub(crate) struct WindowData { + pub window_state: Arc<Mutex<WindowState>>, + pub event_loop_runner: EventLoopRunnerShared<UserEventPlaceholder>, + pub key_event_builder: KeyEventBuilder, + pub _file_drop_handler: Option<FileDropHandler>, + pub userdata_removed: Cell<bool>, + pub recurse_depth: Cell<u32>, +} + +impl WindowData { + fn send_event(&self, event: Event<UserEventPlaceholder>) { + self.event_loop_runner.send_event(event); + } + + fn window_state_lock(&self) -> MutexGuard<'_, WindowState> { + self.window_state.lock().unwrap() + } +} + +struct ThreadMsgTargetData { + event_loop_runner: EventLoopRunnerShared<UserEventPlaceholder>, +} + +impl ThreadMsgTargetData { + fn send_event(&self, event: Event<UserEventPlaceholder>) { + self.event_loop_runner.send_event(event); + } +} + +/// The result of a subclass procedure (the message handling callback) +#[derive(Clone, Copy)] +pub(crate) enum ProcResult { + DefWindowProc(WPARAM), + Value(isize), +} + +pub struct EventLoop<T: 'static> { + user_event_sender: Sender<T>, + user_event_receiver: Receiver<T>, + window_target: RootAEL, + msg_hook: Option<Box<dyn FnMut(*const c_void) -> bool + 'static>>, + // It is a timer used on timed waits. + // It is created lazily in case if we have `ControlFlow::WaitUntil`. + // Keep it as a field to avoid recreating it on every `ControlFlow::WaitUntil`. + high_resolution_timer: Option<OwnedHandle>, +} + +pub(crate) struct PlatformSpecificEventLoopAttributes { + pub(crate) any_thread: bool, + pub(crate) dpi_aware: bool, + pub(crate) msg_hook: Option<Box<dyn FnMut(*const c_void) -> bool + 'static>>, +} + +impl Default for PlatformSpecificEventLoopAttributes { + fn default() -> Self { + Self { any_thread: false, dpi_aware: true, msg_hook: None } + } +} + +pub struct ActiveEventLoop { + thread_id: u32, + thread_msg_target: HWND, + pub(crate) runner_shared: EventLoopRunnerShared<UserEventPlaceholder>, +} + +impl<T: 'static> EventLoop<T> { + pub(crate) fn new( + attributes: &mut PlatformSpecificEventLoopAttributes, + ) -> Result<Self, EventLoopError> { + let thread_id = unsafe { GetCurrentThreadId() }; + + if !attributes.any_thread && thread_id != main_thread_id() { + panic!( + "Initializing the event loop outside of the main thread is a significant \ + cross-platform compatibility hazard. If you absolutely need to create an \ + EventLoop on a different thread, you can use the \ + `EventLoopBuilderExtWindows::any_thread` function." + ); + } + + if attributes.dpi_aware { + become_dpi_aware(); + } + + let thread_msg_target = create_event_target_window(); + + let runner_shared = Rc::new(EventLoopRunner::new(thread_msg_target)); + + let (user_event_sender, user_event_receiver) = mpsc::channel(); + insert_event_target_window_data(thread_msg_target, runner_shared.clone()); + raw_input::register_all_mice_and_keyboards_for_raw_input( + thread_msg_target, + Default::default(), + ); + + Ok(EventLoop { + user_event_sender, + user_event_receiver, + window_target: RootAEL { + p: ActiveEventLoop { thread_id, thread_msg_target, runner_shared }, + _marker: PhantomData, + }, + msg_hook: attributes.msg_hook.take(), + high_resolution_timer: None, + }) + } + + pub fn window_target(&self) -> &RootAEL { + &self.window_target + } + + pub fn run<F>(mut self, event_handler: F) -> Result<(), EventLoopError> + where + F: FnMut(Event<T>, &RootAEL), + { + self.run_on_demand(event_handler) + } + + pub fn run_on_demand<F>(&mut self, mut event_handler: F) -> Result<(), EventLoopError> + where + F: FnMut(Event<T>, &RootAEL), + { + { + let runner = &self.window_target.p.runner_shared; + + let event_loop_windows_ref = &self.window_target; + let user_event_receiver = &self.user_event_receiver; + // # Safety + // We make sure to call runner.clear_event_handler() before + // returning + unsafe { + runner.set_event_handler(move |event| { + // the shared `EventLoopRunner` is not parameterized + // `EventLoopProxy::send_event()` calls `PostMessage` + // to wakeup and dispatch a placeholder `UserEvent`, + // when we received the placeholder event here, the + // real UserEvent(T) should already be put in the + // mpsc channel and ready to be pulled + let event = match event.map_nonuser_event() { + Ok(non_user_event) => non_user_event, + Err(_user_event_placeholder) => Event::UserEvent( + user_event_receiver + .try_recv() + .expect("user event signaled but not received"), + ), + }; + event_handler(event, event_loop_windows_ref) + }); + } + } + + let exit_code = loop { + self.wait_for_messages(None); + // wait_for_messages calls user application before and after waiting + // so it may have decided to exit. + if let Some(code) = self.exit_code() { + break code; + } + + self.dispatch_peeked_messages(); + + if let Some(code) = self.exit_code() { + break code; + } + }; + + let runner = &self.window_target.p.runner_shared; + runner.loop_destroyed(); + + // # Safety + // We assume that this will effectively call `runner.clear_event_handler()` + // to meet the safety requirements for calling `runner.set_event_handler()` above. + runner.reset_runner(); + + if exit_code == 0 { + Ok(()) + } else { + Err(EventLoopError::ExitFailure(exit_code)) + } + } + + pub fn pump_events<F>(&mut self, timeout: Option<Duration>, mut event_handler: F) -> PumpStatus + where + F: FnMut(Event<T>, &RootAEL), + { + { + let runner = &self.window_target.p.runner_shared; + let event_loop_windows_ref = &self.window_target; + let user_event_receiver = &self.user_event_receiver; + + // # Safety + // We make sure to call runner.clear_event_handler() before + // returning + // + // Note: we're currently assuming nothing can panic and unwind + // to leave the runner in an unsound state with an associated + // event handler. + unsafe { + runner.set_event_handler(move |event| { + let event = match event.map_nonuser_event() { + Ok(non_user_event) => non_user_event, + Err(_user_event_placeholder) => Event::UserEvent( + user_event_receiver + .recv() + .expect("user event signaled but not received"), + ), + }; + event_handler(event, event_loop_windows_ref) + }); + runner.wakeup(); + } + } + + if self.exit_code().is_none() { + self.wait_for_messages(timeout); + } + // wait_for_messages calls user application before and after waiting + // so it may have decided to exit. + if self.exit_code().is_none() { + self.dispatch_peeked_messages(); + } + + let runner = &self.window_target.p.runner_shared; + + let status = if let Some(code) = runner.exit_code() { + runner.loop_destroyed(); + + // Immediately reset the internal state for the loop to allow + // the loop to be run more than once. + runner.reset_runner(); + PumpStatus::Exit(code) + } else { + runner.prepare_wait(); + PumpStatus::Continue + }; + + // We wait until we've checked for an exit status before clearing the + // application callback, in case we need to dispatch a LoopExiting event + // + // # Safety + // This pairs up with our call to `runner.set_event_handler` and ensures + // the application's callback can't be held beyond its lifetime. + runner.clear_event_handler(); + + status + } + + /// Waits until new event messages arrive to be peeked. + /// Doesn't peek messages itself. + /// + /// Parameter timeout is optional. This method would wait for the smaller timeout + /// between the argument and a timeout from control flow. + fn wait_for_messages(&mut self, timeout: Option<Duration>) { + let runner = &self.window_target.p.runner_shared; + + // We aim to be consistent with the MacOS backend which has a RunLoop + // observer that will dispatch AboutToWait when about to wait for + // events, and NewEvents after the RunLoop wakes up. + // + // We emulate similar behaviour by treating `MsgWaitForMultipleObjectsEx` as our wait + // point and wake up point (when it returns) and we drain all other + // pending messages via `PeekMessage` until we come back to "wait" via + // `MsgWaitForMultipleObjectsEx`. + // + runner.prepare_wait(); + wait_for_messages_impl(&mut self.high_resolution_timer, runner.control_flow(), timeout); + // Before we potentially exit, make sure to consistently emit an event for the wake up + runner.wakeup(); + } + + /// Dispatch all queued messages via `PeekMessageW` + fn dispatch_peeked_messages(&mut self) { + let runner = &self.window_target.p.runner_shared; + + // We generally want to continue dispatching all pending messages + // but we also allow dispatching to be interrupted as a means to + // ensure the `pump_events` won't indefinitely block an external + // event loop if there are too many pending events. This interrupt + // flag will be set after dispatching `RedrawRequested` events. + runner.interrupt_msg_dispatch.set(false); + + // # Safety + // The Windows API has no documented requirement for bitwise + // initializing a `MSG` struct (it can be uninitialized memory for the C + // API) and there's no API to construct or initialize a `MSG`. This + // is the simplest way avoid uninitialized memory in Rust + let mut msg: MSG = unsafe { mem::zeroed() }; + + loop { + unsafe { + if PeekMessageW(&mut msg, 0, 0, 0, PM_REMOVE) == false.into() { + break; + } + + let handled = if let Some(callback) = self.msg_hook.as_deref_mut() { + callback(&mut msg as *mut _ as *mut _) + } else { + false + }; + if !handled { + TranslateMessage(&msg); + DispatchMessageW(&msg); + } + } + + if let Err(payload) = runner.take_panic_error() { + runner.reset_runner(); + panic::resume_unwind(payload); + } + + if let Some(_code) = runner.exit_code() { + break; + } + + if runner.interrupt_msg_dispatch.get() { + break; + } + } + } + + pub fn create_proxy(&self) -> EventLoopProxy<T> { + EventLoopProxy { + target_window: self.window_target.p.thread_msg_target, + event_send: self.user_event_sender.clone(), + } + } + + fn exit_code(&self) -> Option<i32> { + self.window_target.p.exit_code() + } +} + +impl ActiveEventLoop { + #[inline(always)] + pub(crate) fn create_thread_executor(&self) -> EventLoopThreadExecutor { + EventLoopThreadExecutor { thread_id: self.thread_id, target_window: self.thread_msg_target } + } + + pub fn create_custom_cursor(&self, source: CustomCursorSource) -> RootCustomCursor { + let inner = match WinCursor::new(&source.inner.0) { + Ok(cursor) => cursor, + Err(err) => { + tracing::warn!("Failed to create custom cursor: {err}"); + WinCursor::Failed + }, + }; + + RootCustomCursor { inner } + } + + // TODO: Investigate opportunities for caching + pub fn available_monitors(&self) -> VecDeque<MonitorHandle> { + monitor::available_monitors() + } + + pub fn primary_monitor(&self) -> Option<MonitorHandle> { + let monitor = monitor::primary_monitor(); + Some(monitor) + } + + #[cfg(feature = "rwh_05")] + pub fn raw_display_handle_rwh_05(&self) -> rwh_05::RawDisplayHandle { + rwh_05::RawDisplayHandle::Windows(rwh_05::WindowsDisplayHandle::empty()) + } + + #[cfg(feature = "rwh_06")] + pub fn raw_display_handle_rwh_06( + &self, + ) -> Result<rwh_06::RawDisplayHandle, rwh_06::HandleError> { + Ok(rwh_06::RawDisplayHandle::Windows(rwh_06::WindowsDisplayHandle::new())) + } + + pub fn listen_device_events(&self, allowed: DeviceEvents) { + raw_input::register_all_mice_and_keyboards_for_raw_input(self.thread_msg_target, allowed); + } + + pub fn system_theme(&self) -> Option<Theme> { + Some(if super::dark_mode::should_use_dark_mode() { Theme::Dark } else { Theme::Light }) + } + + pub(crate) fn set_control_flow(&self, control_flow: ControlFlow) { + self.runner_shared.set_control_flow(control_flow) + } + + pub(crate) fn control_flow(&self) -> ControlFlow { + self.runner_shared.control_flow() + } + + pub(crate) fn exit(&self) { + self.runner_shared.set_exit_code(0) + } + + pub(crate) fn exiting(&self) -> bool { + self.runner_shared.exit_code().is_some() + } + + pub(crate) fn clear_exit(&self) { + self.runner_shared.clear_exit(); + } + + pub(crate) fn owned_display_handle(&self) -> OwnedDisplayHandle { + OwnedDisplayHandle + } + + fn exit_code(&self) -> Option<i32> { + self.runner_shared.exit_code() + } +} + +#[derive(Clone)] +pub(crate) struct OwnedDisplayHandle; + +impl OwnedDisplayHandle { + #[cfg(feature = "rwh_05")] + #[inline] + pub fn raw_display_handle_rwh_05(&self) -> rwh_05::RawDisplayHandle { + rwh_05::WindowsDisplayHandle::empty().into() + } + + #[cfg(feature = "rwh_06")] + #[inline] + pub fn raw_display_handle_rwh_06( + &self, + ) -> Result<rwh_06::RawDisplayHandle, rwh_06::HandleError> { + Ok(rwh_06::WindowsDisplayHandle::new().into()) + } +} + +/// Returns the id of the main thread. +/// +/// Windows has no real API to check if the current executing thread is the "main thread", unlike +/// macOS. +/// +/// Windows will let us look up the current thread's id, but there's no API that lets us check what +/// the id of the main thread is. We would somehow need to get the main thread's id before a +/// developer could spin off any other threads inside of the main entrypoint in order to emulate the +/// capabilities of other platforms. +/// +/// We can get the id of the main thread by using CRT initialization. CRT initialization can be used +/// to setup global state within a program. The OS will call a list of function pointers which +/// assign values to a static variable. To have get a hold of the main thread id, we need to place +/// our function pointer inside of the `.CRT$XCU` section so it is called before the main +/// entrypoint. +/// +/// Full details of CRT initialization can be found here: +/// <https://docs.microsoft.com/en-us/cpp/c-runtime-library/crt-initialization?view=msvc-160> +fn main_thread_id() -> u32 { + static mut MAIN_THREAD_ID: u32 = 0; + + // Function pointer used in CRT initialization section to set the above static field's value. + + // Mark as used so this is not removable. + #[used] + #[allow(non_upper_case_globals)] + // Place the function pointer inside of CRT initialization section so it is loaded before + // main entrypoint. + // + // See: https://doc.rust-lang.org/stable/reference/abi.html#the-link_section-attribute + #[link_section = ".CRT$XCU"] + static INIT_MAIN_THREAD_ID: unsafe extern "C" fn() = { + unsafe extern "C" fn initer() { + unsafe { + MAIN_THREAD_ID = GetCurrentThreadId(); + } + } + initer + }; + + unsafe { MAIN_THREAD_ID } +} + +/// Returns the minimum `Option<Duration>`, taking into account that `None` +/// equates to an infinite timeout, not a zero timeout (so can't just use +/// `Option::min`) +fn min_timeout(a: Option<Duration>, b: Option<Duration>) -> Option<Duration> { + a.map_or(b, |a_timeout| b.map_or(Some(a_timeout), |b_timeout| Some(a_timeout.min(b_timeout)))) +} + +// Implementation taken from https://github.com/rust-lang/rust/blob/db5476571d9b27c862b95c1e64764b0ac8980e23/src/libstd/sys/windows/mod.rs +fn dur2timeout(dur: Duration) -> u32 { + // Note that a duration is a (u64, u32) (seconds, nanoseconds) pair, and the + // timeouts in windows APIs are typically u32 milliseconds. To translate, we + // have two pieces to take care of: + // + // * Nanosecond precision is rounded up + // * Greater than u32::MAX milliseconds (50 days) is rounded up to INFINITE (never time out). + dur.as_secs() + .checked_mul(1000) + .and_then(|ms| ms.checked_add((dur.subsec_nanos() as u64) / 1_000_000)) + .and_then( + |ms| { + if dur.subsec_nanos() % 1_000_000 > 0 { + ms.checked_add(1) + } else { + Some(ms) + } + }, + ) + .map(|ms| if ms > u32::MAX as u64 { INFINITE } else { ms as u32 }) + .unwrap_or(INFINITE) +} + +impl<T> Drop for EventLoop<T> { + fn drop(&mut self) { + unsafe { + DestroyWindow(self.window_target.p.thread_msg_target); + } + } +} + +/// Set upper limit for waiting time to avoid overflows. +/// I chose 50 days as a limit because it is used in dur2timeout. +const FIFTY_DAYS: Duration = Duration::from_secs(50_u64 * 24 * 60 * 60); +/// Waitable timers use 100 ns intervals to indicate due time. +/// <https://learn.microsoft.com/en-us/windows/win32/api/synchapi/nf-synchapi-setwaitabletimer#parameters> +/// And there is no point waiting using other ways for such small timings +/// because they are even less precise (can overshoot by few ms). +const MIN_WAIT: Duration = Duration::from_nanos(100); + +fn create_high_resolution_timer() -> Option<OwnedHandle> { + unsafe { + let handle: HANDLE = CreateWaitableTimerExW( + ptr::null(), + ptr::null(), + CREATE_WAITABLE_TIMER_HIGH_RESOLUTION, + TIMER_ALL_ACCESS, + ); + // CREATE_WAITABLE_TIMER_HIGH_RESOLUTION is supported only after + // Win10 1803 but it is already default option for rustc + // (std uses it to implement `std::thread::sleep`). + if handle == 0 { + None + } else { + Some(OwnedHandle::from_raw_handle(handle as *mut c_void)) + } + } +} + +/// This function should not return error if parameters are valid +/// but there is no guarantee about that at MSDN docs +/// so we return result of GetLastError if fail. +/// +/// ## Safety +/// +/// timer must be a valid timer handle created by [create_high_resolution_timer]. +/// timeout divided by 100 nanoseconds must be more than 0 and less than i64::MAX. +unsafe fn set_high_resolution_timer(timer: RawHandle, timeout: Duration) -> Result<(), u32> { + const INTERVAL_NS: u32 = MIN_WAIT.subsec_nanos(); + const INTERVALS_IN_SEC: u64 = (Duration::from_secs(1).as_nanos() / INTERVAL_NS as u128) as u64; + let intervals_to_wait: u64 = + timeout.as_secs() * INTERVALS_IN_SEC + u64::from(timeout.subsec_nanos() / INTERVAL_NS); + debug_assert!(intervals_to_wait < i64::MAX as u64, "Must be called with smaller duration",); + // Use negative time to indicate relative time. + let due_time: i64 = -(intervals_to_wait as i64); + unsafe { + let set_result = SetWaitableTimer(timer as HANDLE, &due_time, 0, None, ptr::null(), FALSE); + if set_result != FALSE { + Ok(()) + } else { + Err(GetLastError()) + } + } +} + +/// Implementation detail of [EventLoop::wait_for_messages]. +/// +/// Does actual system-level waiting and doesn't process any messages itself, +/// including winits internal notifications about waiting and new messages arrival. +fn wait_for_messages_impl( + high_resolution_timer: &mut Option<OwnedHandle>, + control_flow: ControlFlow, + timeout: Option<Duration>, +) { + let timeout = { + let control_flow_timeout = match control_flow { + ControlFlow::Wait => None, + ControlFlow::Poll => Some(Duration::ZERO), + ControlFlow::WaitUntil(wait_deadline) => { + let start = Instant::now(); + Some(wait_deadline.saturating_duration_since(start)) + }, + }; + let timeout = min_timeout(timeout, control_flow_timeout); + if timeout == Some(Duration::ZERO) { + // Do not wait if we don't have time. + return; + } + // Now we decided to wait so need to do some clamping + // to avoid problems with overflow and calling WinAPI with invalid parameters. + timeout + .map(|t| t.min(FIFTY_DAYS)) + // If timeout is less than minimally supported by Windows, + // increase it to that minimum. Who want less than microsecond delays anyway? + .map(|t| t.max(MIN_WAIT)) + }; + + if timeout.is_some() && high_resolution_timer.is_none() { + *high_resolution_timer = create_high_resolution_timer(); + } + + let high_resolution_timer: Option<RawHandle> = + high_resolution_timer.as_ref().map(OwnedHandle::as_raw_handle); + + let use_timer: bool; + if let (Some(handle), Some(timeout)) = (high_resolution_timer, timeout) { + let res = unsafe { + // Safety: handle can be Some only if we succeeded in creating high resolution + // timer. We properly clamped timeout so it can be used as argument + // to timer. + set_high_resolution_timer(handle, timeout) + }; + if let Err(error_code) = res { + // We successfully got timer but failed to set it? + // Should be some bug in our code. + tracing::trace!("Failed to set high resolution timer: last error {}", error_code); + use_timer = false; + } else { + use_timer = true; + } + } else { + use_timer = false; + } + + unsafe { + // Either: + // 1. User wants to wait indefinitely if timeout is not set. + // 2. We failed to get and set high resolution timer and we need something instead of it. + let wait_duration_ms = timeout.map(dur2timeout).unwrap_or(INFINITE); + + let (num_handles, raw_handles) = + if use_timer { (1, [high_resolution_timer.unwrap()]) } else { (0, [ptr::null_mut()]) }; + + // We must use `QS_ALLINPUT` to wake on accessibility messages. + let result = MsgWaitForMultipleObjectsEx( + num_handles, + raw_handles.as_ptr() as *const _, + wait_duration_ms, + QS_ALLINPUT, + MWMO_INPUTAVAILABLE, + ); + if result == WAIT_FAILED { + // Well, nothing smart to do in such case. + // Treat it as spurious wake up. + tracing::warn!("Failed to MsgWaitForMultipleObjectsEx: error code {}", GetLastError(),); + } + } +} + +pub(crate) struct EventLoopThreadExecutor { + thread_id: u32, + target_window: HWND, +} + +unsafe impl Send for EventLoopThreadExecutor {} +unsafe impl Sync for EventLoopThreadExecutor {} + +impl EventLoopThreadExecutor { + /// Check to see if we're in the parent event loop's thread. + pub(super) fn in_event_loop_thread(&self) -> bool { + let cur_thread_id = unsafe { GetCurrentThreadId() }; + self.thread_id == cur_thread_id + } + + /// Executes a function in the event loop thread. If we're already in the event loop thread, + /// we just call the function directly. + /// + /// The `Inserted` can be used to inject a `WindowState` for the callback to use. The state is + /// removed automatically if the callback receives a `WM_CLOSE` message for the window. + /// + /// Note that if you are using this to change some property of a window and updating + /// `WindowState` then you should call this within the lock of `WindowState`. Otherwise the + /// events may be sent to the other thread in different order to the one in which you set + /// `WindowState`, leaving them out of sync. + /// + /// Note that we use a FnMut instead of a FnOnce because we're too lazy to create an equivalent + /// to the unstable FnBox. + pub(super) fn execute_in_thread<F>(&self, mut function: F) + where + F: FnMut() + Send + 'static, + { + unsafe { + if self.in_event_loop_thread() { + function(); + } else { + // We double-box because the first box is a fat pointer. + let boxed2: ThreadExecFn = Box::new(Box::new(function)); + + let raw = Box::into_raw(boxed2); + + let res = PostMessageW(self.target_window, EXEC_MSG_ID.get(), raw as usize, 0); + assert!(res != false.into(), "PostMessage failed; is the messages queue full?"); + } + } + } +} + +type ThreadExecFn = Box<Box<dyn FnMut()>>; + +pub struct EventLoopProxy<T: 'static> { + target_window: HWND, + event_send: Sender<T>, +} +unsafe impl<T: Send + 'static> Send for EventLoopProxy<T> {} + +impl<T: 'static> Clone for EventLoopProxy<T> { + fn clone(&self) -> Self { + Self { target_window: self.target_window, event_send: self.event_send.clone() } + } +} + +impl<T: 'static> EventLoopProxy<T> { + pub fn send_event(&self, event: T) -> Result<(), EventLoopClosed<T>> { + self.event_send + .send(event) + .map(|result| { + unsafe { PostMessageW(self.target_window, USER_EVENT_MSG_ID.get(), 0, 0) }; + result + }) + .map_err(|e| EventLoopClosed(e.0)) + } +} + +/// A lazily-initialized window message ID. +pub struct LazyMessageId { + /// The ID. + id: AtomicU32, + + /// The name of the message. + name: &'static str, +} + +/// An invalid custom window ID. +const INVALID_ID: u32 = 0x0; + +impl LazyMessageId { + /// Create a new `LazyId`. + const fn new(name: &'static str) -> Self { + Self { id: AtomicU32::new(INVALID_ID), name } + } + + /// Get the message ID. + pub fn get(&self) -> u32 { + // Load the ID. + let id = self.id.load(Ordering::Relaxed); + + if id != INVALID_ID { + return id; + } + + // Register the message. + // SAFETY: We are sure that the pointer is a valid C string ending with '\0'. + assert!(self.name.ends_with('\0')); + let new_id = unsafe { RegisterWindowMessageA(self.name.as_ptr()) }; + + assert_ne!( + new_id, + 0, + "RegisterWindowMessageA returned zero for '{}': {}", + self.name, + std::io::Error::last_os_error() + ); + + // Store the new ID. Since `RegisterWindowMessageA` returns the same value for any given + // string, the target value will always either be a). `INVALID_ID` or b). the + // correct ID. Therefore a compare-and-swap operation here (or really any + // consideration) is never necessary. + self.id.store(new_id, Ordering::Relaxed); + + new_id + } +} + +// Message sent by the `EventLoopProxy` when we want to wake up the thread. +// WPARAM and LPARAM are unused. +static USER_EVENT_MSG_ID: LazyMessageId = LazyMessageId::new("Winit::WakeupMsg\0"); +// Message sent when we want to execute a closure in the thread. +// WPARAM contains a Box<Box<dyn FnMut()>> that must be retrieved with `Box::from_raw`, +// and LPARAM is unused. +static EXEC_MSG_ID: LazyMessageId = LazyMessageId::new("Winit::ExecMsg\0"); +// Message sent by a `Window` when it wants to be destroyed by the main thread. +// WPARAM and LPARAM are unused. +pub(crate) static DESTROY_MSG_ID: LazyMessageId = LazyMessageId::new("Winit::DestroyMsg\0"); +// WPARAM is a bool specifying the `WindowFlags::MARKER_RETAIN_STATE_ON_SIZE` flag. See the +// documentation in the `window_state` module for more information. +pub(crate) static SET_RETAIN_STATE_ON_SIZE_MSG_ID: LazyMessageId = + LazyMessageId::new("Winit::SetRetainMaximized\0"); +static THREAD_EVENT_TARGET_WINDOW_CLASS: Lazy<Vec<u16>> = + Lazy::new(|| util::encode_wide("Winit Thread Event Target")); +/// When the taskbar is created, it registers a message with the "TaskbarCreated" string and then +/// broadcasts this message to all top-level windows <https://docs.microsoft.com/en-us/windows/win32/shell/taskbar#taskbar-creation-notification> +pub(crate) static TASKBAR_CREATED: LazyMessageId = LazyMessageId::new("TaskbarCreated\0"); + +fn create_event_target_window() -> HWND { + use windows_sys::Win32::UI::WindowsAndMessaging::{CS_HREDRAW, CS_VREDRAW}; + unsafe { + let class = WNDCLASSEXW { + cbSize: mem::size_of::<WNDCLASSEXW>() as u32, + style: CS_HREDRAW | CS_VREDRAW, + lpfnWndProc: Some(thread_event_target_callback), + cbClsExtra: 0, + cbWndExtra: 0, + hInstance: util::get_instance_handle(), + hIcon: 0, + hCursor: 0, // must be null in order for cursor state to work properly + hbrBackground: 0, + lpszMenuName: ptr::null(), + lpszClassName: THREAD_EVENT_TARGET_WINDOW_CLASS.as_ptr(), + hIconSm: 0, + }; + + RegisterClassExW(&class); + } + + unsafe { + // WS_EX_TOOLWINDOW prevents this window from ever showing up in the taskbar, which + // we want to avoid. If you remove this style, this window won't show up in the + // taskbar *initially*, but it can show up at some later point. This can sometimes + // happen on its own after several hours have passed, although this has proven + // difficult to reproduce. Alternatively, it can be manually triggered by killing + // `explorer.exe` and then starting the process back up. + // It is unclear why the bug is triggered by waiting for several hours. + let window = CreateWindowExW( + WS_EX_NOACTIVATE | WS_EX_TRANSPARENT | WS_EX_LAYERED | WS_EX_TOOLWINDOW, + THREAD_EVENT_TARGET_WINDOW_CLASS.as_ptr(), + ptr::null(), + WS_OVERLAPPED, + 0, + 0, + 0, + 0, + 0, + 0, + util::get_instance_handle(), + ptr::null(), + ); + // Rune: cloaked before it's made visible, so what walks the desktop's windows never meets + // it: UI Automation (screen readers) listed it as an unnamed 22x22 pane at 0,0, and window + // pickers that skip cloaked windows skip it. A cloaked window still gets WM_PAINT; a + // message-only or hidden one doesn't. + let cloak: BOOL = 1; + DwmSetWindowAttribute( + window, + DWMWA_CLOAK as u32, + &cloak as *const BOOL as *const c_void, + mem::size_of::<BOOL>() as u32, + ); + + super::set_window_long( + window, + GWL_STYLE, + // The window technically has to be visible to receive WM_PAINT messages (which are + // used for delivering events during resizes), but it isn't displayed to + // the user because of the LAYERED style. + (WS_VISIBLE | WS_POPUP) as isize, + ); + window + } +} + +fn insert_event_target_window_data( + thread_msg_target: HWND, + event_loop_runner: EventLoopRunnerShared<UserEventPlaceholder>, +) { + let userdata = ThreadMsgTargetData { event_loop_runner }; + let input_ptr = Box::into_raw(Box::new(userdata)); + + unsafe { super::set_window_long(thread_msg_target, GWL_USERDATA, input_ptr as isize) }; +} + +/// Capture mouse input, allowing `window` to receive mouse events when the cursor is outside of +/// the window. +unsafe fn capture_mouse(window: HWND, window_state: &mut WindowState) { + window_state.mouse.capture_count += 1; + unsafe { SetCapture(window) }; +} + +/// Release mouse input, stopping windows on this thread from receiving mouse input when the cursor +/// is outside the window. +unsafe fn release_mouse(mut window_state: MutexGuard<'_, WindowState>) { + window_state.mouse.capture_count = window_state.mouse.capture_count.saturating_sub(1); + if window_state.mouse.capture_count == 0 { + // ReleaseCapture() causes a WM_CAPTURECHANGED where we lock the window_state. + drop(window_state); + unsafe { ReleaseCapture() }; + } +} + +fn normalize_pointer_pressure(pressure: u32) -> Option<Force> { + match pressure { + 1..=1024 => Some(Force::Normalized(pressure as f64 / 1024.0)), + _ => None, + } +} + +/// Emit a `ModifiersChanged` event whenever modifiers have changed. +/// Returns the current modifier state +fn update_modifiers(window: HWND, userdata: &WindowData) { + use crate::event::WindowEvent::ModifiersChanged; + + let modifiers = { + let mut layouts = LAYOUT_CACHE.lock().unwrap(); + layouts.get_agnostic_mods() + }; + + let mut window_state = userdata.window_state.lock().unwrap(); + if window_state.modifiers_state != modifiers { + window_state.modifiers_state = modifiers; + + // Drop lock + drop(window_state); + + userdata.send_event(Event::WindowEvent { + window_id: RootWindowId(WindowId(window)), + event: ModifiersChanged(modifiers.into()), + }); + } +} + +unsafe fn gain_active_focus(window: HWND, userdata: &WindowData) { + use crate::event::WindowEvent::Focused; + + update_modifiers(window, userdata); + + userdata.send_event(Event::WindowEvent { + window_id: RootWindowId(WindowId(window)), + event: Focused(true), + }); +} + +unsafe fn lose_active_focus(window: HWND, userdata: &WindowData) { + use crate::event::WindowEvent::{Focused, ModifiersChanged}; + + userdata.window_state_lock().modifiers_state = ModifiersState::empty(); + userdata.send_event(Event::WindowEvent { + window_id: RootWindowId(WindowId(window)), + event: ModifiersChanged(ModifiersState::empty().into()), + }); + + userdata.send_event(Event::WindowEvent { + window_id: RootWindowId(WindowId(window)), + event: Focused(false), + }); +} + +/// Any window whose callback is configured to this function will have its events propagated +/// through the events loop of the thread the window was created in. +// This is the callback that is called by `DispatchMessage` in the events loop. +// +// Returning 0 tells the Win32 API that the message has been processed. +// FIXME: detect WM_DWMCOMPOSITIONCHANGED and call DwmEnableBlurBehindWindow if necessary +pub(super) unsafe extern "system" fn public_window_callback( + window: HWND, + msg: u32, + wparam: WPARAM, + lparam: LPARAM, +) -> LRESULT { + let userdata = unsafe { super::get_window_long(window, GWL_USERDATA) }; + + let userdata_ptr = match (userdata, msg) { + (0, WM_NCCREATE) => { + let createstruct = unsafe { &mut *(lparam as *mut CREATESTRUCTW) }; + let initdata = unsafe { &mut *(createstruct.lpCreateParams as *mut InitData<'_>) }; + + let result = match unsafe { initdata.on_nccreate(window) } { + Some(userdata) => unsafe { + super::set_window_long(window, GWL_USERDATA, userdata as _); + DefWindowProcW(window, msg, wparam, lparam) + }, + None => -1, // failed to create the window + }; + + return result; + }, + // Getting here should quite frankly be impossible, + // but we'll make window creation fail here just in case. + (0, WM_CREATE) => return -1, + (_, WM_CREATE) => unsafe { + let createstruct = &mut *(lparam as *mut CREATESTRUCTW); + let initdata = createstruct.lpCreateParams; + let initdata = &mut *(initdata as *mut InitData<'_>); + + initdata.on_create(); + return DefWindowProcW(window, msg, wparam, lparam); + }, + (0, _) => return unsafe { DefWindowProcW(window, msg, wparam, lparam) }, + _ => userdata as *mut WindowData, + }; + + let (result, userdata_removed, recurse_depth) = { + let userdata = unsafe { &*(userdata_ptr) }; + + userdata.recurse_depth.set(userdata.recurse_depth.get() + 1); + + let result = unsafe { public_window_callback_inner(window, msg, wparam, lparam, userdata) }; + + let userdata_removed = userdata.userdata_removed.get(); + let recurse_depth = userdata.recurse_depth.get() - 1; + userdata.recurse_depth.set(recurse_depth); + + (result, userdata_removed, recurse_depth) + }; + + if userdata_removed && recurse_depth == 0 { + drop(unsafe { Box::from_raw(userdata_ptr) }); + } + + result +} + +unsafe fn public_window_callback_inner( + window: HWND, + msg: u32, + wparam: WPARAM, + lparam: LPARAM, + userdata: &WindowData, +) -> LRESULT { + let mut result = ProcResult::DefWindowProc(wparam); + + // Send new modifiers before sending key events. + let mods_changed_callback = || match msg { + WM_KEYDOWN | WM_SYSKEYDOWN | WM_KEYUP | WM_SYSKEYUP => { + update_modifiers(window, userdata); + result = ProcResult::Value(0); + }, + _ => (), + }; + userdata + .event_loop_runner + .catch_unwind(mods_changed_callback) + .unwrap_or_else(|| result = ProcResult::Value(-1)); + + let keyboard_callback = || { + use crate::event::WindowEvent::KeyboardInput; + // Rune: a bare WM_CHAR is dropped while an input method's composition is open. + let ime_composing = + msg == WM_CHAR && userdata.window_state_lock().ime_state != ImeState::Disabled; + let events = userdata.key_event_builder.process_message( + window, + msg, + wparam, + lparam, + ime_composing, + &mut result, + ); + for event in events { + userdata.send_event(Event::WindowEvent { + window_id: RootWindowId(WindowId(window)), + event: KeyboardInput { + device_id: DEVICE_ID, + event: event.event, + is_synthetic: event.is_synthetic, + }, + }); + } + }; + userdata + .event_loop_runner + .catch_unwind(keyboard_callback) + .unwrap_or_else(|| result = ProcResult::Value(-1)); + + // I decided to bind the closure to `callback` and pass it to catch_unwind rather than passing + // the closure to catch_unwind directly so that the match body indentation wouldn't change and + // the git blame and history would be preserved. + let callback = || match msg { + WM_NCCALCSIZE => { + let window_flags = userdata.window_state_lock().window_flags; + if wparam == 0 || window_flags.contains(WindowFlags::MARKER_DECORATIONS) { + result = ProcResult::DefWindowProc(wparam); + return; + } + + let params = unsafe { &mut *(lparam as *mut NCCALCSIZE_PARAMS) }; + + if util::is_maximized(window) { + // Limit the window size when maximized to the current monitor. + // Otherwise it would include the non-existent decorations. + // + // Use `MonitorFromRect` instead of `MonitorFromWindow` to select + // the correct monitor here. + // See https://github.com/MicrosoftEdge/WebView2Feedback/issues/2549 + let monitor = unsafe { MonitorFromRect(&params.rgrc[0], MONITOR_DEFAULTTONULL) }; + if let Ok(monitor_info) = monitor::get_monitor_info(monitor) { + params.rgrc[0] = monitor_info.monitorInfo.rcWork; + } + } else if window_flags.contains(WindowFlags::MARKER_UNDECORATED_SHADOW) { + // Extend the client area to cover the whole non-client area. + // https://docs.microsoft.com/en-us/windows/win32/winmsg/wm-nccalcsize#remarks + // + // HACK(msiglreith): To add the drop shadow we slightly tweak the non-client area. + // This leads to a small black 1px border on the top. Adding a margin manually + // on all 4 borders would result in the caption getting drawn by the DWM. + // + // Another option would be to allow the DWM to paint inside the client area. + // Unfortunately this results in janky resize behavior, where the compositor is + // ahead of the window surface. Currently, there seems no option to achieve this + // with the Windows API. + params.rgrc[0].top += 1; + params.rgrc[0].bottom += 1; + } + + result = ProcResult::Value(0); + }, + + WM_ENTERSIZEMOVE => { + userdata + .window_state_lock() + .set_window_flags_in_place(|f| f.insert(WindowFlags::MARKER_IN_SIZE_MOVE)); + result = ProcResult::Value(0); + }, + + WM_EXITSIZEMOVE => { + let mut state = userdata.window_state_lock(); + if state.dragging { + state.dragging = false; + unsafe { PostMessageW(window, WM_LBUTTONUP, 0, lparam) }; + } + + state.set_window_flags_in_place(|f| f.remove(WindowFlags::MARKER_IN_SIZE_MOVE)); + result = ProcResult::Value(0); + }, + + WM_NCLBUTTONDOWN => { + if wparam == HTCAPTION as _ { + // Prevent the user event loop from pausing when left clicking the title bar. + // + // When the user interacts with the title bar, Windows enters the modal event + // loop. Currently, a left click causes a pause for about 500ms. Sending a dummy + // mouse-move event seems to cancel the modal loop early, preventing the pause. + // The application will never see this dummy event. + // + // The mouse coordinates are encoded into the lparam value, however the WM_MOUSEMOVE + // event is not using the same coordinate system of the WM_NCLBUTTONDOWN event. + // One uses client-area coordinates and the other is screen-coordinates. In any + // case, passing the lparam as-is with the dummy event does not seem the cancel + // the modal loop. + // + // However, passing in a value of 0 has been observed to always cancel the pause. + // + // Other notes: + // + // For some unknown reason, the cursor will blink when clicking the title bar. + // Cancelling the modal loop early causes the blink to happen *immediately*. + // Otherwise, the blank happens *after* the pause. + // + // When right-click the title bar, the system window menu is presented to the user, + // and the modal event loop begins. This dummy event does *not* prevent the freeze + // in the main event loop caused by that popup menu. + let lparam = 0; + unsafe { PostMessageW(window, WM_MOUSEMOVE, 0, lparam) }; + } + result = ProcResult::DefWindowProc(wparam); + }, + + WM_CLOSE => { + use crate::event::WindowEvent::CloseRequested; + userdata.send_event(Event::WindowEvent { + window_id: RootWindowId(WindowId(window)), + event: CloseRequested, + }); + result = ProcResult::Value(0); + }, + + WM_DESTROY => { + use crate::event::WindowEvent::Destroyed; + unsafe { RevokeDragDrop(window) }; + userdata.send_event(Event::WindowEvent { + window_id: RootWindowId(WindowId(window)), + event: Destroyed, + }); + result = ProcResult::Value(0); + }, + + WM_NCDESTROY => { + unsafe { super::set_window_long(window, GWL_USERDATA, 0) }; + userdata.userdata_removed.set(true); + result = ProcResult::Value(0); + }, + + WM_PAINT => { + userdata.window_state_lock().redraw_requested = + userdata.event_loop_runner.should_buffer(); + + // We'll buffer only in response to `UpdateWindow`, if win32 decides to redraw the + // window outside the normal flow of the event loop. This way mark event as handled + // and request a normal redraw with `RedrawWindow`. + if !userdata.event_loop_runner.should_buffer() { + userdata.send_event(Event::WindowEvent { + window_id: RootWindowId(WindowId(window)), + event: WindowEvent::RedrawRequested, + }); + } + + // NOTE: calling `RedrawWindow` during `WM_PAINT` does nothing, since to mark + // `WM_PAINT` as handled we should call the `DefWindowProcW`. Call it and check whether + // user asked for redraw during `RedrawRequested` event handling and request it again + // after marking `WM_PAINT` as handled. + result = ProcResult::Value(unsafe { DefWindowProcW(window, msg, wparam, lparam) }); + if std::mem::take(&mut userdata.window_state_lock().redraw_requested) { + unsafe { RedrawWindow(window, ptr::null(), 0, RDW_INTERNALPAINT) }; + } + }, + WM_WINDOWPOSCHANGING => { + let mut window_state = userdata.window_state_lock(); + if let Some(ref mut fullscreen) = window_state.fullscreen { + let window_pos = unsafe { &mut *(lparam as *mut WINDOWPOS) }; + let new_rect = RECT { + left: window_pos.x, + top: window_pos.y, + right: window_pos.x + window_pos.cx, + bottom: window_pos.y + window_pos.cy, + }; + + const NOMOVE_OR_NOSIZE: u32 = SWP_NOMOVE | SWP_NOSIZE; + + let new_rect = if window_pos.flags & NOMOVE_OR_NOSIZE != 0 { + let cur_rect = util::WindowArea::Outer.get_rect(window).expect( + "Unexpected GetWindowRect failure; please report this error to \ + rust-windowing/winit", + ); + + match window_pos.flags & NOMOVE_OR_NOSIZE { + NOMOVE_OR_NOSIZE => None, + + SWP_NOMOVE => Some(RECT { + left: cur_rect.left, + top: cur_rect.top, + right: cur_rect.left + window_pos.cx, + bottom: cur_rect.top + window_pos.cy, + }), + + SWP_NOSIZE => Some(RECT { + left: window_pos.x, + top: window_pos.y, + right: window_pos.x - cur_rect.left + cur_rect.right, + bottom: window_pos.y - cur_rect.top + cur_rect.bottom, + }), + + _ => unreachable!(), + } + } else { + Some(new_rect) + }; + + if let Some(new_rect) = new_rect { + let new_monitor = unsafe { MonitorFromRect(&new_rect, MONITOR_DEFAULTTONULL) }; + match fullscreen { + Fullscreen::Borderless(ref mut fullscreen_monitor) => { + if new_monitor != 0 + && fullscreen_monitor + .as_ref() + .map(|monitor| new_monitor != monitor.hmonitor()) + .unwrap_or(true) + { + if let Ok(new_monitor_info) = monitor::get_monitor_info(new_monitor) + { + let new_monitor_rect = new_monitor_info.monitorInfo.rcMonitor; + window_pos.x = new_monitor_rect.left; + window_pos.y = new_monitor_rect.top; + window_pos.cx = new_monitor_rect.right - new_monitor_rect.left; + window_pos.cy = new_monitor_rect.bottom - new_monitor_rect.top; + } + *fullscreen_monitor = Some(MonitorHandle::new(new_monitor)); + } + }, + Fullscreen::Exclusive(ref video_mode) => { + let old_monitor = video_mode.monitor.hmonitor(); + if let Ok(old_monitor_info) = monitor::get_monitor_info(old_monitor) { + let old_monitor_rect = old_monitor_info.monitorInfo.rcMonitor; + window_pos.x = old_monitor_rect.left; + window_pos.y = old_monitor_rect.top; + window_pos.cx = old_monitor_rect.right - old_monitor_rect.left; + window_pos.cy = old_monitor_rect.bottom - old_monitor_rect.top; + } + }, + } + } + } + + result = ProcResult::Value(0); + }, + + // WM_MOVE supplies client area positions, so we send Moved here instead. + WM_WINDOWPOSCHANGED => { + use crate::event::WindowEvent::Moved; + + let windowpos = lparam as *const WINDOWPOS; + if unsafe { (*windowpos).flags & SWP_NOMOVE != SWP_NOMOVE } { + let physical_position = + unsafe { PhysicalPosition::new((*windowpos).x, (*windowpos).y) }; + userdata.send_event(Event::WindowEvent { + window_id: RootWindowId(WindowId(window)), + event: Moved(physical_position), + }); + } + + // This is necessary for us to still get sent WM_SIZE. + result = ProcResult::DefWindowProc(wparam); + }, + + WM_SIZE => { + use crate::event::WindowEvent::Resized; + let w = super::loword(lparam as u32) as u32; + let h = super::hiword(lparam as u32) as u32; + + let physical_size = PhysicalSize::new(w, h); + let event = Event::WindowEvent { + window_id: RootWindowId(WindowId(window)), + event: Resized(physical_size), + }; + + { + let mut w = userdata.window_state_lock(); + // See WindowFlags::MARKER_RETAIN_STATE_ON_SIZE docs for info on why this `if` check + // exists. + if !w.window_flags().contains(WindowFlags::MARKER_RETAIN_STATE_ON_SIZE) { + let maximized = wparam == SIZE_MAXIMIZED as usize; + w.set_window_flags_in_place(|f| f.set(WindowFlags::MAXIMIZED, maximized)); + } + } + userdata.send_event(event); + result = ProcResult::Value(0); + }, + + WM_SIZING => { + /// Calculate the amount to add to round `value` to the nearest multiple of `increment`. + fn snap_to_nearest_increment_delta(value: i32, increment: i32) -> i32 { + let half_one = increment / 2; + let half_two = increment - half_one; + half_one - (value - half_two) % increment + } + + let scale_factor = userdata.window_state_lock().scale_factor; + let Some(inc) = userdata + .window_state_lock() + .resize_increments + .map(|inc| inc.to_physical(scale_factor)) + .filter(|inc| inc.width > 0 && inc.height > 0) + else { + result = ProcResult::Value(0); + return; + }; + + let side = wparam as u32; + // The desired new size of the window, decorations included. + let rect = unsafe { &mut *(lparam as *mut RECT) }; + + // We need to calculate the dimensions of the window decorations to get the true + // size of the window's contents + let adj_rect = userdata + .window_state_lock() + .window_flags + .adjust_rect(window, *rect) + .unwrap_or(*rect); + let deco_width = rect.left - adj_rect.left + adj_rect.right - rect.right; + let deco_height = rect.top - adj_rect.top + adj_rect.bottom - rect.bottom; + + let width = rect.right - rect.left - deco_width; + let height = rect.bottom - rect.top - deco_height; + + let mut width_delta = snap_to_nearest_increment_delta(width, inc.width); + let mut height_delta = snap_to_nearest_increment_delta(height, inc.height); + + // Windows won't bound check the value of `rect` after we're done here, so we + // have to check manually. If the width/height we snap to would go out of bounds, just + // set it equal to the min/max bound. + let min_size = + userdata.window_state_lock().min_size.map(|size| size.to_physical(scale_factor)); + let max_size = + userdata.window_state_lock().max_size.map(|size| size.to_physical(scale_factor)); + let final_width = width + width_delta; + let final_height = height + height_delta; + if let Some(min_size) = min_size { + if final_width < min_size.width { + width_delta += min_size.width - final_width; + } + if final_height < min_size.height { + height_delta += min_size.height - final_height; + } + } + if let Some(max_size) = max_size { + if final_width > max_size.width { + width_delta -= final_width - max_size.width; + } + if final_height > max_size.height { + height_delta -= final_height - max_size.height; + } + } + + match side { + WMSZ_LEFT | WMSZ_BOTTOMLEFT | WMSZ_TOPLEFT => { + rect.left -= width_delta; + }, + WMSZ_RIGHT | WMSZ_BOTTOMRIGHT | WMSZ_TOPRIGHT => { + rect.right += width_delta; + }, + _ => {}, + } + + match side { + WMSZ_TOP | WMSZ_TOPLEFT | WMSZ_TOPRIGHT => { + rect.top -= height_delta; + }, + WMSZ_BOTTOM | WMSZ_BOTTOMLEFT | WMSZ_BOTTOMRIGHT => { + rect.bottom += height_delta; + }, + _ => {}, + } + + result = ProcResult::DefWindowProc(wparam); + }, + + WM_MENUCHAR => { + result = ProcResult::Value((MNC_CLOSE << 16) as isize); + }, + + WM_IME_STARTCOMPOSITION => { + let ime_allowed = userdata.window_state_lock().ime_allowed; + if ime_allowed { + userdata.window_state_lock().ime_state = ImeState::Enabled; + + userdata.send_event(Event::WindowEvent { + window_id: RootWindowId(WindowId(window)), + event: WindowEvent::Ime(Ime::Enabled), + }); + } + + result = ProcResult::DefWindowProc(wparam); + }, + + WM_IME_COMPOSITION => { + let ime_allowed_and_composing = { + let w = userdata.window_state_lock(); + w.ime_allowed && w.ime_state != ImeState::Disabled + }; + // Windows Hangul IME sends WM_IME_COMPOSITION after WM_IME_ENDCOMPOSITION, so + // check whether composing. + if ime_allowed_and_composing { + let ime_context = unsafe { ImeContext::current(window) }; + + if lparam == 0 { + userdata.send_event(Event::WindowEvent { + window_id: RootWindowId(WindowId(window)), + event: WindowEvent::Ime(Ime::Preedit(String::new(), None)), + }); + } + + // Google Japanese Input and ATOK have both flags, so + // first, receive composing result if exist. + if (lparam as u32 & GCS_RESULTSTR) != 0 { + if let Some(text) = unsafe { ime_context.get_composed_text() } { + userdata.window_state_lock().ime_state = ImeState::Enabled; + + userdata.send_event(Event::WindowEvent { + window_id: RootWindowId(WindowId(window)), + event: WindowEvent::Ime(Ime::Preedit(String::new(), None)), + }); + userdata.send_event(Event::WindowEvent { + window_id: RootWindowId(WindowId(window)), + event: WindowEvent::Ime(Ime::Commit(text)), + }); + } + } + + // Next, receive preedit range for next composing if exist. + if (lparam as u32 & GCS_COMPSTR) != 0 { + if let Some((text, first, last)) = + unsafe { ime_context.get_composing_text_and_cursor() } + { + userdata.window_state_lock().ime_state = ImeState::Preedit; + let cursor_range = first.map(|f| (f, last.unwrap_or(f))); + + userdata.send_event(Event::WindowEvent { + window_id: RootWindowId(WindowId(window)), + event: WindowEvent::Ime(Ime::Preedit(text, cursor_range)), + }); + } + } + } + + // Not calling DefWindowProc to hide composing text drawn by IME. + result = ProcResult::Value(0); + }, + + WM_IME_ENDCOMPOSITION => { + let ime_allowed_or_composing = { + let w = userdata.window_state_lock(); + w.ime_allowed || w.ime_state != ImeState::Disabled + }; + if ime_allowed_or_composing { + if userdata.window_state_lock().ime_state == ImeState::Preedit { + // Windows Hangul IME sends WM_IME_COMPOSITION after WM_IME_ENDCOMPOSITION, so + // trying receiving composing result and commit if exists. + let ime_context = unsafe { ImeContext::current(window) }; + if let Some(text) = unsafe { ime_context.get_composed_text() } { + userdata.send_event(Event::WindowEvent { + window_id: RootWindowId(WindowId(window)), + event: WindowEvent::Ime(Ime::Preedit(String::new(), None)), + }); + userdata.send_event(Event::WindowEvent { + window_id: RootWindowId(WindowId(window)), + event: WindowEvent::Ime(Ime::Commit(text)), + }); + } + } + + userdata.window_state_lock().ime_state = ImeState::Disabled; + + userdata.send_event(Event::WindowEvent { + window_id: RootWindowId(WindowId(window)), + event: WindowEvent::Ime(Ime::Disabled), + }); + } + + result = ProcResult::DefWindowProc(wparam); + }, + + WM_IME_SETCONTEXT => { + // IME UI visibility flags are in lparam. + let lparam = lparam & !(ISC_SHOWUICOMPOSITIONWINDOW as isize); + result = ProcResult::Value(unsafe { DefWindowProcW(window, msg, wparam, lparam) }); + }, + + // this is necessary for us to maintain minimize/restore state + WM_SYSCOMMAND => { + if wparam == SC_RESTORE as usize { + let mut w = userdata.window_state_lock(); + w.set_window_flags_in_place(|f| f.set(WindowFlags::MINIMIZED, false)); + } + if wparam == SC_MINIMIZE as usize { + let mut w = userdata.window_state_lock(); + w.set_window_flags_in_place(|f| f.set(WindowFlags::MINIMIZED, true)); + } + // Send `WindowEvent::Minimized` here if we decide to implement one + + if wparam == SC_SCREENSAVE as usize { + let window_state = userdata.window_state_lock(); + if window_state.fullscreen.is_some() { + result = ProcResult::Value(0); + return; + } + } + + result = ProcResult::DefWindowProc(wparam); + }, + + WM_MOUSEMOVE => { + use crate::event::WindowEvent::{CursorEntered, CursorLeft, CursorMoved}; + + let x = super::get_x_lparam(lparam as u32) as i32; + let y = super::get_y_lparam(lparam as u32) as i32; + let position = PhysicalPosition::new(x as f64, y as f64); + + let cursor_moved; + { + let mut w = userdata.window_state_lock(); + let mouse_was_inside_window = + w.mouse.cursor_flags().contains(CursorFlags::IN_WINDOW); + + match get_pointer_move_kind(window, mouse_was_inside_window, x, y) { + PointerMoveKind::Enter => { + w.mouse + .set_cursor_flags(window, |f| f.set(CursorFlags::IN_WINDOW, true)) + .ok(); + + drop(w); + userdata.send_event(Event::WindowEvent { + window_id: RootWindowId(WindowId(window)), + event: CursorEntered { device_id: DEVICE_ID }, + }); + + // Calling TrackMouseEvent in order to receive mouse leave events. + unsafe { + TrackMouseEvent(&mut TRACKMOUSEEVENT { + cbSize: mem::size_of::<TRACKMOUSEEVENT>() as u32, + dwFlags: TME_LEAVE, + hwndTrack: window, + dwHoverTime: HOVER_DEFAULT, + }) + }; + }, + PointerMoveKind::Leave => { + w.mouse + .set_cursor_flags(window, |f| f.set(CursorFlags::IN_WINDOW, false)) + .ok(); + + drop(w); + userdata.send_event(Event::WindowEvent { + window_id: RootWindowId(WindowId(window)), + event: CursorLeft { device_id: DEVICE_ID }, + }); + }, + PointerMoveKind::None => drop(w), + } + + // handle spurious WM_MOUSEMOVE messages + // see https://devblogs.microsoft.com/oldnewthing/20031001-00/?p=42343 + // and http://debugandconquer.blogspot.com/2015/08/the-cause-of-spurious-mouse-move.html + let mut w = userdata.window_state_lock(); + cursor_moved = w.mouse.last_position != Some(position); + w.mouse.last_position = Some(position); + } + + if cursor_moved { + update_modifiers(window, userdata); + + userdata.send_event(Event::WindowEvent { + window_id: RootWindowId(WindowId(window)), + event: CursorMoved { device_id: DEVICE_ID, position }, + }); + } + + result = ProcResult::Value(0); + }, + + WM_MOUSELEAVE => { + use crate::event::WindowEvent::CursorLeft; + { + let mut w = userdata.window_state_lock(); + w.mouse.set_cursor_flags(window, |f| f.set(CursorFlags::IN_WINDOW, false)).ok(); + } + + userdata.send_event(Event::WindowEvent { + window_id: RootWindowId(WindowId(window)), + event: CursorLeft { device_id: DEVICE_ID }, + }); + + result = ProcResult::Value(0); + }, + + WM_MOUSEWHEEL => { + use crate::event::MouseScrollDelta::LineDelta; + + let value = (wparam >> 16) as i16; + let value = value as f32 / WHEEL_DELTA as f32; + + update_modifiers(window, userdata); + + userdata.send_event(Event::WindowEvent { + window_id: RootWindowId(WindowId(window)), + event: WindowEvent::MouseWheel { + device_id: DEVICE_ID, + delta: LineDelta(0.0, value), + phase: TouchPhase::Moved, + }, + }); + + result = ProcResult::Value(0); + }, + + WM_MOUSEHWHEEL => { + use crate::event::MouseScrollDelta::LineDelta; + + let value = (wparam >> 16) as i16; + let value = -value as f32 / WHEEL_DELTA as f32; // NOTE: inverted! See https://github.com/rust-windowing/winit/pull/2105/ + + update_modifiers(window, userdata); + + userdata.send_event(Event::WindowEvent { + window_id: RootWindowId(WindowId(window)), + event: WindowEvent::MouseWheel { + device_id: DEVICE_ID, + delta: LineDelta(value, 0.0), + phase: TouchPhase::Moved, + }, + }); + + result = ProcResult::Value(0); + }, + + WM_KEYDOWN | WM_SYSKEYDOWN => { + if msg == WM_SYSKEYDOWN { + result = ProcResult::DefWindowProc(wparam); + } + }, + + WM_KEYUP | WM_SYSKEYUP => { + if msg == WM_SYSKEYUP && unsafe { GetMenu(window) != 0 } { + // let Windows handle event if the window has a native menu, a modal event loop + // is started here on Alt key up. + result = ProcResult::DefWindowProc(wparam); + } + }, + + WM_LBUTTONDOWN => { + use crate::event::ElementState::Pressed; + use crate::event::MouseButton::Left; + use crate::event::WindowEvent::MouseInput; + + unsafe { capture_mouse(window, &mut userdata.window_state_lock()) }; + + update_modifiers(window, userdata); + + userdata.send_event(Event::WindowEvent { + window_id: RootWindowId(WindowId(window)), + event: MouseInput { device_id: DEVICE_ID, state: Pressed, button: Left }, + }); + result = ProcResult::Value(0); + }, + + WM_LBUTTONUP => { + use crate::event::ElementState::Released; + use crate::event::MouseButton::Left; + use crate::event::WindowEvent::MouseInput; + + unsafe { release_mouse(userdata.window_state_lock()) }; + + update_modifiers(window, userdata); + + userdata.send_event(Event::WindowEvent { + window_id: RootWindowId(WindowId(window)), + event: MouseInput { device_id: DEVICE_ID, state: Released, button: Left }, + }); + result = ProcResult::Value(0); + }, + + WM_RBUTTONDOWN => { + use crate::event::ElementState::Pressed; + use crate::event::MouseButton::Right; + use crate::event::WindowEvent::MouseInput; + + unsafe { capture_mouse(window, &mut userdata.window_state_lock()) }; + + update_modifiers(window, userdata); + + userdata.send_event(Event::WindowEvent { + window_id: RootWindowId(WindowId(window)), + event: MouseInput { device_id: DEVICE_ID, state: Pressed, button: Right }, + }); + result = ProcResult::Value(0); + }, + + WM_RBUTTONUP => { + use crate::event::ElementState::Released; + use crate::event::MouseButton::Right; + use crate::event::WindowEvent::MouseInput; + + unsafe { release_mouse(userdata.window_state_lock()) }; + + update_modifiers(window, userdata); + + userdata.send_event(Event::WindowEvent { + window_id: RootWindowId(WindowId(window)), + event: MouseInput { device_id: DEVICE_ID, state: Released, button: Right }, + }); + result = ProcResult::Value(0); + }, + + WM_MBUTTONDOWN => { + use crate::event::ElementState::Pressed; + use crate::event::MouseButton::Middle; + use crate::event::WindowEvent::MouseInput; + + unsafe { capture_mouse(window, &mut userdata.window_state_lock()) }; + + update_modifiers(window, userdata); + + userdata.send_event(Event::WindowEvent { + window_id: RootWindowId(WindowId(window)), + event: MouseInput { device_id: DEVICE_ID, state: Pressed, button: Middle }, + }); + result = ProcResult::Value(0); + }, + + WM_MBUTTONUP => { + use crate::event::ElementState::Released; + use crate::event::MouseButton::Middle; + use crate::event::WindowEvent::MouseInput; + + unsafe { release_mouse(userdata.window_state_lock()) }; + + update_modifiers(window, userdata); + + userdata.send_event(Event::WindowEvent { + window_id: RootWindowId(WindowId(window)), + event: MouseInput { device_id: DEVICE_ID, state: Released, button: Middle }, + }); + result = ProcResult::Value(0); + }, + + WM_XBUTTONDOWN => { + use crate::event::ElementState::Pressed; + use crate::event::MouseButton::{Back, Forward, Other}; + use crate::event::WindowEvent::MouseInput; + let xbutton = super::get_xbutton_wparam(wparam as u32); + + unsafe { capture_mouse(window, &mut userdata.window_state_lock()) }; + + update_modifiers(window, userdata); + + userdata.send_event(Event::WindowEvent { + window_id: RootWindowId(WindowId(window)), + event: MouseInput { + device_id: DEVICE_ID, + state: Pressed, + button: match xbutton { + 1 => Back, + 2 => Forward, + _ => Other(xbutton), + }, + }, + }); + result = ProcResult::Value(0); + }, + + WM_XBUTTONUP => { + use crate::event::ElementState::Released; + use crate::event::MouseButton::{Back, Forward, Other}; + use crate::event::WindowEvent::MouseInput; + let xbutton = super::get_xbutton_wparam(wparam as u32); + + unsafe { release_mouse(userdata.window_state_lock()) }; + + update_modifiers(window, userdata); + + userdata.send_event(Event::WindowEvent { + window_id: RootWindowId(WindowId(window)), + event: MouseInput { + device_id: DEVICE_ID, + state: Released, + button: match xbutton { + 1 => Back, + 2 => Forward, + _ => Other(xbutton), + }, + }, + }); + result = ProcResult::Value(0); + }, + + WM_CAPTURECHANGED => { + // lparam here is a handle to the window which is gaining mouse capture. + // If it is the same as our window, then we're essentially retaining the capture. This + // can happen if `SetCapture` is called on our window when it already has the mouse + // capture. + if lparam != window { + userdata.window_state_lock().mouse.capture_count = 0; + } + result = ProcResult::Value(0); + }, + + WM_TOUCH => { + let pcount = super::loword(wparam as u32) as usize; + let mut inputs = Vec::with_capacity(pcount); + let htouch = lparam; + if unsafe { + GetTouchInputInfo( + htouch, + pcount as u32, + inputs.as_mut_ptr(), + mem::size_of::<TOUCHINPUT>() as i32, + ) > 0 + } { + unsafe { inputs.set_len(pcount) }; + for input in &inputs { + let mut location = POINT { x: input.x / 100, y: input.y / 100 }; + + if unsafe { ScreenToClient(window, &mut location) } == false.into() { + continue; + } + + let x = location.x as f64 + (input.x % 100) as f64 / 100f64; + let y = location.y as f64 + (input.y % 100) as f64 / 100f64; + let location = PhysicalPosition::new(x, y); + userdata.send_event(Event::WindowEvent { + window_id: RootWindowId(WindowId(window)), + event: WindowEvent::Touch(Touch { + phase: if util::has_flag(input.dwFlags, TOUCHEVENTF_DOWN) { + TouchPhase::Started + } else if util::has_flag(input.dwFlags, TOUCHEVENTF_UP) { + TouchPhase::Ended + } else if util::has_flag(input.dwFlags, TOUCHEVENTF_MOVE) { + TouchPhase::Moved + } else { + continue; + }, + location, + force: None, // WM_TOUCH doesn't support pressure information + id: input.dwID as u64, + device_id: DEVICE_ID, + }), + }); + } + } + unsafe { CloseTouchInputHandle(htouch) }; + result = ProcResult::Value(0); + }, + + WM_POINTERDOWN | WM_POINTERUPDATE | WM_POINTERUP => { + if let ( + Some(GetPointerFrameInfoHistory), + Some(SkipPointerFrameMessages), + Some(GetPointerDeviceRects), + ) = ( + *util::GET_POINTER_FRAME_INFO_HISTORY, + *util::SKIP_POINTER_FRAME_MESSAGES, + *util::GET_POINTER_DEVICE_RECTS, + ) { + let pointer_id = super::loword(wparam as u32) as u32; + let mut entries_count = 0u32; + let mut pointers_count = 0u32; + if unsafe { + GetPointerFrameInfoHistory( + pointer_id, + &mut entries_count, + &mut pointers_count, + ptr::null_mut(), + ) + } == false.into() + { + result = ProcResult::Value(0); + return; + } + + let pointer_info_count = (entries_count * pointers_count) as usize; + let mut pointer_infos = Vec::with_capacity(pointer_info_count); + if unsafe { + GetPointerFrameInfoHistory( + pointer_id, + &mut entries_count, + &mut pointers_count, + pointer_infos.as_mut_ptr(), + ) + } == false.into() + { + result = ProcResult::Value(0); + return; + } + unsafe { pointer_infos.set_len(pointer_info_count) }; + + // https://docs.microsoft.com/en-us/windows/desktop/api/winuser/nf-winuser-getpointerframeinfohistory + // The information retrieved appears in reverse chronological order, with the most + // recent entry in the first row of the returned array + for pointer_info in pointer_infos.iter().rev() { + let mut device_rect = mem::MaybeUninit::uninit(); + let mut display_rect = mem::MaybeUninit::uninit(); + + if unsafe { + GetPointerDeviceRects( + pointer_info.sourceDevice, + device_rect.as_mut_ptr(), + display_rect.as_mut_ptr(), + ) + } == false.into() + { + continue; + } + + let device_rect = unsafe { device_rect.assume_init() }; + let display_rect = unsafe { display_rect.assume_init() }; + + // For the most precise himetric to pixel conversion we calculate the ratio + // between the resolution of the display device (pixel) and + // the touch device (himetric). + let himetric_to_pixel_ratio_x = (display_rect.right - display_rect.left) as f64 + / (device_rect.right - device_rect.left) as f64; + let himetric_to_pixel_ratio_y = (display_rect.bottom - display_rect.top) as f64 + / (device_rect.bottom - device_rect.top) as f64; + + // ptHimetricLocation's origin is 0,0 even on multi-monitor setups. + // On multi-monitor setups we need to translate the himetric location to the + // rect of the display device it's attached to. + let x = display_rect.left as f64 + + pointer_info.ptHimetricLocation.x as f64 * himetric_to_pixel_ratio_x; + let y = display_rect.top as f64 + + pointer_info.ptHimetricLocation.y as f64 * himetric_to_pixel_ratio_y; + + let mut location = POINT { x: x.floor() as i32, y: y.floor() as i32 }; + + if unsafe { ScreenToClient(window, &mut location) } == false.into() { + continue; + } + + let force = match pointer_info.pointerType { + PT_TOUCH => { + let mut touch_info = mem::MaybeUninit::uninit(); + util::GET_POINTER_TOUCH_INFO.and_then(|GetPointerTouchInfo| { + match unsafe { + GetPointerTouchInfo( + pointer_info.pointerId, + touch_info.as_mut_ptr(), + ) + } { + 0 => None, + _ => normalize_pointer_pressure(unsafe { + touch_info.assume_init().pressure + }), + } + }) + }, + PT_PEN => { + let mut pen_info = mem::MaybeUninit::uninit(); + util::GET_POINTER_PEN_INFO.and_then(|GetPointerPenInfo| { + match unsafe { + GetPointerPenInfo(pointer_info.pointerId, pen_info.as_mut_ptr()) + } { + 0 => None, + _ => normalize_pointer_pressure(unsafe { + pen_info.assume_init().pressure + }), + } + }) + }, + _ => None, + }; + + let x = location.x as f64 + x.fract(); + let y = location.y as f64 + y.fract(); + let location = PhysicalPosition::new(x, y); + userdata.send_event(Event::WindowEvent { + window_id: RootWindowId(WindowId(window)), + event: WindowEvent::Touch(Touch { + phase: if util::has_flag(pointer_info.pointerFlags, POINTER_FLAG_DOWN) { + TouchPhase::Started + } else if util::has_flag(pointer_info.pointerFlags, POINTER_FLAG_UP) { + TouchPhase::Ended + } else if util::has_flag(pointer_info.pointerFlags, POINTER_FLAG_UPDATE) + { + TouchPhase::Moved + } else { + continue; + }, + location, + force, + id: pointer_info.pointerId as u64, + device_id: DEVICE_ID, + }), + }); + } + + unsafe { SkipPointerFrameMessages(pointer_id) }; + } + result = ProcResult::Value(0); + }, + + WM_NCACTIVATE => { + let is_active = wparam != false.into(); + let active_focus_changed = userdata.window_state_lock().set_active(is_active); + if active_focus_changed { + if is_active { + unsafe { gain_active_focus(window, userdata) }; + } else { + unsafe { lose_active_focus(window, userdata) }; + } + } + result = ProcResult::DefWindowProc(wparam); + }, + + WM_SETFOCUS => { + let active_focus_changed = userdata.window_state_lock().set_focused(true); + if active_focus_changed { + unsafe { gain_active_focus(window, userdata) }; + } + result = ProcResult::Value(0); + }, + + WM_KILLFOCUS => { + let active_focus_changed = userdata.window_state_lock().set_focused(false); + if active_focus_changed { + unsafe { lose_active_focus(window, userdata) }; + } + result = ProcResult::Value(0); + }, + + WM_SETCURSOR => { + let set_cursor_to = { + let window_state = userdata.window_state_lock(); + // The return value for the preceding `WM_NCHITTEST` message is conveniently + // provided through the low-order word of lParam. We use that here since + // `WM_MOUSEMOVE` seems to come after `WM_SETCURSOR` for a given cursor movement. + let in_client_area = super::loword(lparam as u32) as u32 == HTCLIENT; + if in_client_area { + Some(window_state.mouse.selected_cursor.clone()) + } else { + None + } + }; + + match set_cursor_to { + Some(selected_cursor) => { + let hcursor = match selected_cursor { + SelectedCursor::Named(cursor_icon) => unsafe { + LoadCursorW(0, util::to_windows_cursor(cursor_icon)) + }, + SelectedCursor::Custom(cursor) => cursor.as_raw_handle(), + }; + unsafe { SetCursor(hcursor) }; + result = ProcResult::Value(0); + }, + None => result = ProcResult::DefWindowProc(wparam), + } + }, + + WM_GETMINMAXINFO => { + let mmi = lparam as *mut MINMAXINFO; + + let window_state = userdata.window_state_lock(); + let window_flags = window_state.window_flags; + + if window_state.min_size.is_some() || window_state.max_size.is_some() { + if let Some(min_size) = window_state.min_size { + let min_size = min_size.to_physical(window_state.scale_factor); + let (width, height): (u32, u32) = + window_flags.adjust_size(window, min_size).into(); + unsafe { (*mmi).ptMinTrackSize = POINT { x: width as i32, y: height as i32 } }; + } + if let Some(max_size) = window_state.max_size { + let max_size = max_size.to_physical(window_state.scale_factor); + let (width, height): (u32, u32) = + window_flags.adjust_size(window, max_size).into(); + unsafe { (*mmi).ptMaxTrackSize = POINT { x: width as i32, y: height as i32 } }; + } + } + + result = ProcResult::Value(0); + }, + + // Only sent on Windows 8.1 or newer. On Windows 7 and older user has to log out to change + // DPI, therefore all applications are closed while DPI is changing. + WM_DPICHANGED => { + use crate::event::WindowEvent::ScaleFactorChanged; + + // This message actually provides two DPI values - x and y. However MSDN says that + // "you only need to use either the X-axis or the Y-axis value when scaling your + // application since they are the same". + // https://msdn.microsoft.com/en-us/library/windows/desktop/dn312083(v=vs.85).aspx + let new_dpi_x = super::loword(wparam as u32) as u32; + let new_scale_factor = dpi_to_scale_factor(new_dpi_x); + let old_scale_factor: f64; + + let (allow_resize, window_flags) = { + let mut window_state = userdata.window_state_lock(); + old_scale_factor = window_state.scale_factor; + window_state.scale_factor = new_scale_factor; + + if new_scale_factor == old_scale_factor { + result = ProcResult::Value(0); + return; + } + + let allow_resize = window_state.fullscreen.is_none() + && !window_state.window_flags().contains(WindowFlags::MAXIMIZED); + + (allow_resize, window_state.window_flags) + }; + + // New size as suggested by Windows. + let suggested_rect = unsafe { *(lparam as *const RECT) }; + + // The window rect provided is the window's outer size, not it's inner size. However, + // win32 doesn't provide an `UnadjustWindowRectEx` function to get the client rect from + // the outer rect, so we instead adjust the window rect to get the decoration margins + // and remove them from the outer size. + let margin_left: i32; + let margin_top: i32; + // let margin_right: i32; + // let margin_bottom: i32; + { + let adjusted_rect = + window_flags.adjust_rect(window, suggested_rect).unwrap_or(suggested_rect); + margin_left = suggested_rect.left - adjusted_rect.left; + margin_top = suggested_rect.top - adjusted_rect.top; + // margin_right = adjusted_rect.right - suggested_rect.right; + // margin_bottom = adjusted_rect.bottom - suggested_rect.bottom; + } + + let old_physical_inner_rect = util::WindowArea::Inner + .get_rect(window) + .expect("failed to query (old) inner window area"); + let old_physical_inner_size = PhysicalSize::new( + (old_physical_inner_rect.right - old_physical_inner_rect.left) as u32, + (old_physical_inner_rect.bottom - old_physical_inner_rect.top) as u32, + ); + + // `allow_resize` prevents us from re-applying DPI adjustment to the restored size after + // exiting fullscreen (the restored size is already DPI adjusted). + let new_physical_inner_size = match allow_resize { + // We calculate our own size because the default suggested rect doesn't do a great + // job of preserving the window's logical size. + true => old_physical_inner_size + .to_logical::<f64>(old_scale_factor) + .to_physical::<u32>(new_scale_factor), + false => old_physical_inner_size, + }; + + let new_inner_size = Arc::new(Mutex::new(new_physical_inner_size)); + userdata.send_event(Event::WindowEvent { + window_id: RootWindowId(WindowId(window)), + event: ScaleFactorChanged { + scale_factor: new_scale_factor, + inner_size_writer: InnerSizeWriter::new(Arc::downgrade(&new_inner_size)), + }, + }); + + let new_physical_inner_size = *new_inner_size.lock().unwrap(); + drop(new_inner_size); + + let dragging_window: bool; + + { + let window_state = userdata.window_state_lock(); + dragging_window = + window_state.window_flags().contains(WindowFlags::MARKER_IN_SIZE_MOVE); + // Unset maximized if we're changing the window's size. + if new_physical_inner_size != old_physical_inner_size { + WindowState::set_window_flags(window_state, window, |f| { + f.set(WindowFlags::MAXIMIZED, false) + }); + } + } + + let new_outer_rect: RECT; + { + let suggested_ul = + (suggested_rect.left + margin_left, suggested_rect.top + margin_top); + + let mut conservative_rect = RECT { + left: suggested_ul.0, + top: suggested_ul.1, + right: suggested_ul.0 + new_physical_inner_size.width as i32, + bottom: suggested_ul.1 + new_physical_inner_size.height as i32, + }; + + conservative_rect = window_flags + .adjust_rect(window, conservative_rect) + .unwrap_or(conservative_rect); + + // If we're dragging the window, offset the window so that the cursor's + // relative horizontal position in the title bar is preserved. + if dragging_window { + let bias = { + let cursor_pos = { + let mut pos = unsafe { mem::zeroed() }; + unsafe { GetCursorPos(&mut pos) }; + pos + }; + let suggested_cursor_horizontal_ratio = (cursor_pos.x - suggested_rect.left) + as f64 + / (suggested_rect.right - suggested_rect.left) as f64; + + (cursor_pos.x + - (suggested_cursor_horizontal_ratio + * (conservative_rect.right - conservative_rect.left) as f64) + as i32) + - conservative_rect.left + }; + conservative_rect.left += bias; + conservative_rect.right += bias; + } + + // Check to see if the new window rect is on the monitor with the new DPI factor. + // If it isn't, offset the window so that it is. + let new_dpi_monitor = unsafe { MonitorFromWindow(window, MONITOR_DEFAULTTONULL) }; + let conservative_rect_monitor = + unsafe { MonitorFromRect(&conservative_rect, MONITOR_DEFAULTTONULL) }; + new_outer_rect = if conservative_rect_monitor == new_dpi_monitor { + conservative_rect + } else { + let get_monitor_rect = |monitor| { + let mut monitor_info = MONITORINFO { + cbSize: mem::size_of::<MONITORINFO>() as _, + ..unsafe { mem::zeroed() } + }; + unsafe { GetMonitorInfoW(monitor, &mut monitor_info) }; + monitor_info.rcMonitor + }; + let wrong_monitor = conservative_rect_monitor; + let wrong_monitor_rect = get_monitor_rect(wrong_monitor); + let new_monitor_rect = get_monitor_rect(new_dpi_monitor); + + // The direction to nudge the window in to get the window onto the monitor with + // the new DPI factor. We calculate this by seeing which monitor edges are + // shared and nudging away from the wrong monitor based on those. + #[allow(clippy::bool_to_int_with_if)] + let delta_nudge_to_dpi_monitor = ( + if wrong_monitor_rect.left == new_monitor_rect.right { + -1 + } else if wrong_monitor_rect.right == new_monitor_rect.left { + 1 + } else { + 0 + }, + if wrong_monitor_rect.bottom == new_monitor_rect.top { + 1 + } else if wrong_monitor_rect.top == new_monitor_rect.bottom { + -1 + } else { + 0 + }, + ); + + let abort_after_iterations = new_monitor_rect.right - new_monitor_rect.left + + new_monitor_rect.bottom + - new_monitor_rect.top; + for _ in 0..abort_after_iterations { + conservative_rect.left += delta_nudge_to_dpi_monitor.0; + conservative_rect.right += delta_nudge_to_dpi_monitor.0; + conservative_rect.top += delta_nudge_to_dpi_monitor.1; + conservative_rect.bottom += delta_nudge_to_dpi_monitor.1; + + if unsafe { MonitorFromRect(&conservative_rect, MONITOR_DEFAULTTONULL) } + == new_dpi_monitor + { + break; + } + } + + conservative_rect + }; + } + + unsafe { + SetWindowPos( + window, + 0, + new_outer_rect.left, + new_outer_rect.top, + new_outer_rect.right - new_outer_rect.left, + new_outer_rect.bottom - new_outer_rect.top, + SWP_NOZORDER | SWP_NOACTIVATE, + ) + }; + + result = ProcResult::Value(0); + }, + + WM_SETTINGCHANGE => { + use crate::event::WindowEvent::ThemeChanged; + + let preferred_theme = userdata.window_state_lock().preferred_theme; + + if preferred_theme.is_none() { + let new_theme = try_theme(window, preferred_theme); + let mut window_state = userdata.window_state_lock(); + + if window_state.current_theme != new_theme { + window_state.current_theme = new_theme; + drop(window_state); + userdata.send_event(Event::WindowEvent { + window_id: RootWindowId(WindowId(window)), + event: ThemeChanged(new_theme), + }); + } + } + result = ProcResult::DefWindowProc(wparam); + }, + + _ => { + if msg == DESTROY_MSG_ID.get() { + unsafe { DestroyWindow(window) }; + result = ProcResult::Value(0); + } else if msg == SET_RETAIN_STATE_ON_SIZE_MSG_ID.get() { + let mut window_state = userdata.window_state_lock(); + window_state.set_window_flags_in_place(|f| { + f.set(WindowFlags::MARKER_RETAIN_STATE_ON_SIZE, wparam != 0) + }); + result = ProcResult::Value(0); + } else if msg == TASKBAR_CREATED.get() { + let window_state = userdata.window_state_lock(); + unsafe { set_skip_taskbar(window, window_state.skip_taskbar) }; + result = ProcResult::DefWindowProc(wparam); + } else { + result = ProcResult::DefWindowProc(wparam); + } + }, + }; + + userdata + .event_loop_runner + .catch_unwind(callback) + .unwrap_or_else(|| result = ProcResult::Value(-1)); + + match result { + ProcResult::DefWindowProc(wparam) => unsafe { DefWindowProcW(window, msg, wparam, lparam) }, + ProcResult::Value(val) => val, + } +} + +unsafe extern "system" fn thread_event_target_callback( + window: HWND, + msg: u32, + wparam: WPARAM, + lparam: LPARAM, +) -> LRESULT { + let userdata_ptr = + unsafe { super::get_window_long(window, GWL_USERDATA) } as *mut ThreadMsgTargetData; + if userdata_ptr.is_null() { + // `userdata_ptr` will always be null for the first `WM_GETMINMAXINFO`, as well as + // `WM_NCCREATE` and `WM_CREATE`. + return unsafe { DefWindowProcW(window, msg, wparam, lparam) }; + } + let userdata = unsafe { Box::from_raw(userdata_ptr) }; + + if msg != WM_PAINT { + unsafe { RedrawWindow(window, ptr::null(), 0, RDW_INTERNALPAINT) }; + } + + let mut userdata_removed = false; + + // I decided to bind the closure to `callback` and pass it to catch_unwind rather than passing + // the closure to catch_unwind directly so that the match body indentation wouldn't change and + // the git blame and history would be preserved. + let callback = || match msg { + WM_NCDESTROY => { + unsafe { super::set_window_long(window, GWL_USERDATA, 0) }; + userdata_removed = true; + 0 + }, + WM_PAINT => unsafe { + ValidateRect(window, ptr::null()); + // Default WM_PAINT behaviour. This makes sure modals and popups are shown immediately + // when opening them. + DefWindowProcW(window, msg, wparam, lparam) + }, + + WM_INPUT_DEVICE_CHANGE => { + let event = match wparam as u32 { + GIDC_ARRIVAL => DeviceEvent::Added, + GIDC_REMOVAL => DeviceEvent::Removed, + _ => unreachable!(), + }; + + userdata + .send_event(Event::DeviceEvent { device_id: wrap_device_id(lparam as u32), event }); + + 0 + }, + + WM_INPUT => { + if let Some(data) = raw_input::get_raw_input_data(lparam as _) { + unsafe { handle_raw_input(&userdata, data) }; + } + + unsafe { DefWindowProcW(window, msg, wparam, lparam) } + }, + + _ if msg == USER_EVENT_MSG_ID.get() => { + // synthesis a placeholder UserEvent, so that if the callback is + // re-entered it can be buffered for later delivery. the real + // user event is still in the mpsc channel and will be pulled + // once the placeholder event is delivered to the wrapper + // `event_handler` + userdata.send_event(Event::UserEvent(UserEventPlaceholder)); + 0 + }, + _ if msg == EXEC_MSG_ID.get() => { + let mut function: ThreadExecFn = unsafe { Box::from_raw(wparam as *mut _) }; + function(); + 0 + }, + _ => unsafe { DefWindowProcW(window, msg, wparam, lparam) }, + }; + + let result = userdata.event_loop_runner.catch_unwind(callback).unwrap_or(-1); + if userdata_removed { + drop(userdata); + } else { + Box::leak(userdata); + } + result +} + +unsafe fn handle_raw_input(userdata: &ThreadMsgTargetData, data: RAWINPUT) { + use crate::event::DeviceEvent::{Button, Key, Motion, MouseMotion, MouseWheel}; + use crate::event::ElementState::{Pressed, Released}; + use crate::event::MouseScrollDelta::LineDelta; + + let device_id = wrap_device_id(data.header.hDevice as _); + + if data.header.dwType == RIM_TYPEMOUSE { + let mouse = unsafe { data.data.mouse }; + + if util::has_flag(mouse.usFlags as u32, MOUSE_MOVE_RELATIVE) { + let x = mouse.lLastX as f64; + let y = mouse.lLastY as f64; + + if x != 0.0 { + userdata.send_event(Event::DeviceEvent { + device_id, + event: Motion { axis: 0, value: x }, + }); + } + + if y != 0.0 { + userdata.send_event(Event::DeviceEvent { + device_id, + event: Motion { axis: 1, value: y }, + }); + } + + if x != 0.0 || y != 0.0 { + userdata.send_event(Event::DeviceEvent { + device_id, + event: MouseMotion { delta: (x, y) }, + }); + } + } + + let button_flags = unsafe { mouse.Anonymous.Anonymous.usButtonFlags }; + if util::has_flag(button_flags as u32, RI_MOUSE_WHEEL) { + let button_data = unsafe { mouse.Anonymous.Anonymous.usButtonData } as i16; + let delta = button_data as f32 / WHEEL_DELTA as f32; + userdata.send_event(Event::DeviceEvent { + device_id, + event: MouseWheel { delta: LineDelta(0.0, delta) }, + }); + } + if util::has_flag(button_flags as u32, RI_MOUSE_HWHEEL) { + let button_data = unsafe { mouse.Anonymous.Anonymous.usButtonData } as i16; + let delta = -button_data as f32 / WHEEL_DELTA as f32; + userdata.send_event(Event::DeviceEvent { + device_id, + event: MouseWheel { delta: LineDelta(delta, 0.0) }, + }); + } + + let button_state = raw_input::get_raw_mouse_button_state(button_flags as u32); + for (button, state) in button_state.iter().enumerate() { + if let Some(state) = *state { + userdata.send_event(Event::DeviceEvent { + device_id, + event: Button { button: button as _, state }, + }); + } + } + } else if data.header.dwType == RIM_TYPEKEYBOARD { + let keyboard = unsafe { data.data.keyboard }; + + let pressed = keyboard.Message == WM_KEYDOWN || keyboard.Message == WM_SYSKEYDOWN; + let released = keyboard.Message == WM_KEYUP || keyboard.Message == WM_SYSKEYUP; + + if !pressed && !released { + return; + } + + if let Some(physical_key) = raw_input::get_keyboard_physical_key(keyboard) { + let state = if pressed { Pressed } else { Released }; + + userdata.send_event(Event::DeviceEvent { + device_id, + event: Key(RawKeyEvent { physical_key, state }), + }); + } + } +} + +enum PointerMoveKind { + /// Pointer entered to the window. + Enter, + /// Pointer leaved the window client area. + Leave, + /// Pointer is inside the window or `GetClientRect` failed. + None, +} + +fn get_pointer_move_kind( + window: HWND, + mouse_was_inside_window: bool, + x: i32, + y: i32, +) -> PointerMoveKind { + let rect: RECT = unsafe { + let mut rect: RECT = mem::zeroed(); + if GetClientRect(window, &mut rect) == false.into() { + return PointerMoveKind::None; // exit early if GetClientRect failed + } + rect + }; + + let x = (rect.left..rect.right).contains(&x); + let y = (rect.top..rect.bottom).contains(&y); + + if !mouse_was_inside_window && x && y { + PointerMoveKind::Enter + } else if mouse_was_inside_window && !(x && y) { + PointerMoveKind::Leave + } else { + PointerMoveKind::None + } +} diff --git a/app/vendor/rune/vendor/winit/src/platform_impl/windows/event_loop/runner.rs b/app/vendor/rune/vendor/winit/src/platform_impl/windows/event_loop/runner.rs new file mode 100644 index 0000000..3243ec4 --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/platform_impl/windows/event_loop/runner.rs @@ -0,0 +1,406 @@ +use std::any::Any; +use std::cell::{Cell, RefCell}; +use std::collections::VecDeque; +use std::rc::Rc; +use std::sync::{Arc, Mutex}; +use std::time::Instant; +use std::{mem, panic}; + +use windows_sys::Win32::Foundation::HWND; + +use crate::dpi::PhysicalSize; +use crate::event::{Event, InnerSizeWriter, StartCause, WindowEvent}; +use crate::platform_impl::platform::event_loop::{WindowData, GWL_USERDATA}; +use crate::platform_impl::platform::get_window_long; +use crate::window::WindowId; + +use super::ControlFlow; + +pub(crate) type EventLoopRunnerShared<T> = Rc<EventLoopRunner<T>>; + +type EventHandler<T> = Cell<Option<Box<dyn FnMut(Event<T>)>>>; + +pub(crate) struct EventLoopRunner<T: 'static> { + // The event loop's win32 handles + pub(super) thread_msg_target: HWND, + + // Setting this will ensure pump_events will return to the external + // loop asap. E.g. set after each RedrawRequested to ensure pump_events + // can't stall an external loop beyond a frame + pub(super) interrupt_msg_dispatch: Cell<bool>, + + control_flow: Cell<ControlFlow>, + exit: Cell<Option<i32>>, + runner_state: Cell<RunnerState>, + last_events_cleared: Cell<Instant>, + event_handler: EventHandler<T>, + event_buffer: RefCell<VecDeque<BufferedEvent<T>>>, + + panic_error: Cell<Option<PanicError>>, +} + +pub type PanicError = Box<dyn Any + Send + 'static>; + +/// See `move_state_to` function for details on how the state loop works. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub(crate) enum RunnerState { + /// The event loop has just been created, and an `Init` event must be sent. + Uninitialized, + /// The event loop is idling. + Idle, + /// The event loop is handling the OS's events and sending them to the user's callback. + /// `NewEvents` has been sent, and `AboutToWait` hasn't. + HandlingMainEvents, + /// The event loop has been destroyed. No other events will be emitted. + Destroyed, +} + +enum BufferedEvent<T: 'static> { + Event(Event<T>), + ScaleFactorChanged(WindowId, f64, PhysicalSize<u32>), +} + +impl<T> EventLoopRunner<T> { + pub(crate) fn new(thread_msg_target: HWND) -> EventLoopRunner<T> { + EventLoopRunner { + thread_msg_target, + interrupt_msg_dispatch: Cell::new(false), + runner_state: Cell::new(RunnerState::Uninitialized), + control_flow: Cell::new(ControlFlow::default()), + exit: Cell::new(None), + panic_error: Cell::new(None), + last_events_cleared: Cell::new(Instant::now()), + event_handler: Cell::new(None), + event_buffer: RefCell::new(VecDeque::new()), + } + } + + /// Associate the application's event handler with the runner + /// + /// # Safety + /// This is ignoring the lifetime of the application handler (which may not + /// outlive the EventLoopRunner) and can lead to undefined behaviour if + /// the handler is not cleared before the end of real lifetime. + /// + /// All public APIs that take an event handler (`run`, `run_on_demand`, + /// `pump_events`) _must_ pair a call to `set_event_handler` with + /// a call to `clear_event_handler` before returning to avoid + /// undefined behaviour. + pub(crate) unsafe fn set_event_handler<F>(&self, f: F) + where + F: FnMut(Event<T>), + { + // Erase closure lifetime. + // SAFETY: Caller upholds that the lifetime of the closure is upheld. + let f = unsafe { + mem::transmute::<Box<dyn FnMut(Event<T>)>, Box<dyn FnMut(Event<T>)>>(Box::new(f)) + }; + let old_event_handler = self.event_handler.replace(Some(f)); + assert!(old_event_handler.is_none()); + } + + pub(crate) fn clear_event_handler(&self) { + self.event_handler.set(None); + } + + pub(crate) fn reset_runner(&self) { + let EventLoopRunner { + thread_msg_target: _, + interrupt_msg_dispatch, + runner_state, + panic_error, + control_flow: _, + exit, + last_events_cleared: _, + event_handler, + event_buffer: _, + } = self; + interrupt_msg_dispatch.set(false); + runner_state.set(RunnerState::Uninitialized); + panic_error.set(None); + exit.set(None); + event_handler.set(None); + } +} + +/// State retrieval functions. +impl<T> EventLoopRunner<T> { + #[allow(unused)] + pub fn thread_msg_target(&self) -> HWND { + self.thread_msg_target + } + + pub fn take_panic_error(&self) -> Result<(), PanicError> { + match self.panic_error.take() { + Some(err) => Err(err), + None => Ok(()), + } + } + + pub fn set_control_flow(&self, control_flow: ControlFlow) { + self.control_flow.set(control_flow) + } + + pub fn control_flow(&self) -> ControlFlow { + self.control_flow.get() + } + + pub fn set_exit_code(&self, code: i32) { + self.exit.set(Some(code)) + } + + pub fn exit_code(&self) -> Option<i32> { + self.exit.get() + } + + pub fn clear_exit(&self) { + self.exit.set(None); + } + + pub fn should_buffer(&self) -> bool { + let handler = self.event_handler.take(); + let should_buffer = handler.is_none(); + self.event_handler.set(handler); + should_buffer + } +} + +/// Misc. functions +impl<T> EventLoopRunner<T> { + pub fn catch_unwind<R>(&self, f: impl FnOnce() -> R) -> Option<R> { + let panic_error = self.panic_error.take(); + if panic_error.is_none() { + let result = panic::catch_unwind(panic::AssertUnwindSafe(f)); + + // Check to see if the panic error was set in a re-entrant call to catch_unwind inside + // of `f`. If it was, that error takes priority. If it wasn't, check if our call to + // catch_unwind caught any panics and set panic_error appropriately. + match self.panic_error.take() { + None => match result { + Ok(r) => Some(r), + Err(e) => { + self.panic_error.set(Some(e)); + None + }, + }, + Some(e) => { + self.panic_error.set(Some(e)); + None + }, + } + } else { + self.panic_error.set(panic_error); + None + } + } +} + +/// Event dispatch functions. +impl<T> EventLoopRunner<T> { + pub(crate) fn prepare_wait(&self) { + self.move_state_to(RunnerState::Idle); + } + + pub(crate) fn wakeup(&self) { + self.move_state_to(RunnerState::HandlingMainEvents); + } + + pub(crate) fn send_event(&self, event: Event<T>) { + if let Event::WindowEvent { event: WindowEvent::RedrawRequested, .. } = event { + self.call_event_handler(event); + // As a rule, to ensure that `pump_events` can't block an external event loop + // for too long, we always guarantee that `pump_events` will return control to + // the external loop asap after a `RedrawRequested` event is dispatched. + self.interrupt_msg_dispatch.set(true); + } else if self.should_buffer() { + // If the runner is already borrowed, we're in the middle of an event loop invocation. + // Add the event to a buffer to be processed later. + self.event_buffer.borrow_mut().push_back(BufferedEvent::from_event(event)) + } else { + self.call_event_handler(event); + self.dispatch_buffered_events(); + } + } + + pub(crate) fn loop_destroyed(&self) { + self.move_state_to(RunnerState::Destroyed); + } + + fn call_event_handler(&self, event: Event<T>) { + self.catch_unwind(|| { + let mut event_handler = self.event_handler.take().expect( + "either event handler is re-entrant (likely), or no event handler is registered \ + (very unlikely)", + ); + + event_handler(event); + + assert!(self.event_handler.replace(Some(event_handler)).is_none()); + }); + } + + fn dispatch_buffered_events(&self) { + loop { + // We do this instead of using a `while let` loop because if we use a `while let` + // loop the reference returned `borrow_mut()` doesn't get dropped until the end + // of the loop's body and attempts to add events to the event buffer while in + // `process_event` will fail. + let buffered_event_opt = self.event_buffer.borrow_mut().pop_front(); + match buffered_event_opt { + Some(e) => e.dispatch_event(|e| self.call_event_handler(e)), + None => break, + } + } + } + + /// Dispatch control flow events (`NewEvents`, `AboutToWait`, and + /// `LoopExiting`) as necessary to bring the internal `RunnerState` to the + /// new runner state. + /// + /// The state transitions are defined as follows: + /// + /// ```text + /// Uninitialized + /// | + /// V + /// Idle + /// ^ | + /// | V + /// HandlingMainEvents + /// | + /// V + /// Destroyed + /// ``` + /// + /// Attempting to transition back to `Uninitialized` will result in a panic. Attempting to + /// transition *from* `Destroyed` will also result in a panic. Transitioning to the current + /// state is a no-op. Even if the `new_runner_state` isn't the immediate next state in the + /// runner state machine (e.g. `self.runner_state == HandlingMainEvents` and + /// `new_runner_state == Idle`), the intermediate state transitions will still be executed. + fn move_state_to(&self, new_runner_state: RunnerState) { + use RunnerState::{Destroyed, HandlingMainEvents, Idle, Uninitialized}; + + match (self.runner_state.replace(new_runner_state), new_runner_state) { + (Uninitialized, Uninitialized) + | (Idle, Idle) + | (HandlingMainEvents, HandlingMainEvents) + | (Destroyed, Destroyed) => (), + + // State transitions that initialize the event loop. + (Uninitialized, HandlingMainEvents) => { + self.call_new_events(true); + }, + (Uninitialized, Idle) => { + self.call_new_events(true); + self.call_event_handler(Event::AboutToWait); + self.last_events_cleared.set(Instant::now()); + }, + (Uninitialized, Destroyed) => { + self.call_new_events(true); + self.call_event_handler(Event::AboutToWait); + self.last_events_cleared.set(Instant::now()); + self.call_event_handler(Event::LoopExiting); + }, + (_, Uninitialized) => panic!("cannot move state to Uninitialized"), + + // State transitions that start the event handling process. + (Idle, HandlingMainEvents) => { + self.call_new_events(false); + }, + (Idle, Destroyed) => { + self.call_event_handler(Event::LoopExiting); + }, + + (HandlingMainEvents, Idle) => { + // This is always the last event we dispatch before waiting for new events + self.call_event_handler(Event::AboutToWait); + self.last_events_cleared.set(Instant::now()); + }, + (HandlingMainEvents, Destroyed) => { + self.call_event_handler(Event::AboutToWait); + self.last_events_cleared.set(Instant::now()); + self.call_event_handler(Event::LoopExiting); + }, + + (Destroyed, _) => panic!("cannot move state from Destroyed"), + } + } + + fn call_new_events(&self, init: bool) { + let start_cause = match (init, self.control_flow(), self.exit.get()) { + (true, ..) => StartCause::Init, + (false, ControlFlow::Poll, None) => StartCause::Poll, + (false, _, Some(_)) | (false, ControlFlow::Wait, None) => StartCause::WaitCancelled { + requested_resume: None, + start: self.last_events_cleared.get(), + }, + (false, ControlFlow::WaitUntil(requested_resume), None) => { + if Instant::now() < requested_resume { + StartCause::WaitCancelled { + requested_resume: Some(requested_resume), + start: self.last_events_cleared.get(), + } + } else { + StartCause::ResumeTimeReached { + requested_resume, + start: self.last_events_cleared.get(), + } + } + }, + }; + self.call_event_handler(Event::NewEvents(start_cause)); + // NB: For consistency all platforms must emit a 'resumed' event even though Windows + // applications don't themselves have a formal suspend/resume lifecycle. + if init { + self.call_event_handler(Event::Resumed); + } + self.dispatch_buffered_events(); + } +} + +impl<T> BufferedEvent<T> { + pub fn from_event(event: Event<T>) -> BufferedEvent<T> { + match event { + Event::WindowEvent { + event: WindowEvent::ScaleFactorChanged { scale_factor, inner_size_writer }, + window_id, + } => BufferedEvent::ScaleFactorChanged( + window_id, + scale_factor, + *inner_size_writer.new_inner_size.upgrade().unwrap().lock().unwrap(), + ), + event => BufferedEvent::Event(event), + } + } + + pub fn dispatch_event(self, dispatch: impl FnOnce(Event<T>)) { + match self { + Self::Event(event) => dispatch(event), + Self::ScaleFactorChanged(window_id, scale_factor, new_inner_size) => { + let user_new_inner_size = Arc::new(Mutex::new(new_inner_size)); + dispatch(Event::WindowEvent { + window_id, + event: WindowEvent::ScaleFactorChanged { + scale_factor, + inner_size_writer: InnerSizeWriter::new(Arc::downgrade( + &user_new_inner_size, + )), + }, + }); + let inner_size = *user_new_inner_size.lock().unwrap(); + + drop(user_new_inner_size); + + if inner_size != new_inner_size { + let window_flags = unsafe { + let userdata = + get_window_long(window_id.0.into(), GWL_USERDATA) as *mut WindowData; + (*userdata).window_state_lock().window_flags + }; + + window_flags.set_size((window_id.0).0, inner_size); + } + }, + } + } +} diff --git a/app/vendor/rune/vendor/winit/src/platform_impl/windows/icon.rs b/app/vendor/rune/vendor/winit/src/platform_impl/windows/icon.rs new file mode 100644 index 0000000..4e5fe69 --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/platform_impl/windows/icon.rs @@ -0,0 +1,265 @@ +use std::ffi::c_void; +use std::path::Path; +use std::sync::Arc; +use std::{fmt, io, mem}; + +use cursor_icon::CursorIcon; +use windows_sys::core::PCWSTR; +use windows_sys::Win32::Foundation::HWND; +use windows_sys::Win32::Graphics::Gdi::{ + CreateBitmap, CreateCompatibleBitmap, DeleteObject, GetDC, ReleaseDC, SetBitmapBits, +}; +use windows_sys::Win32::UI::WindowsAndMessaging::{ + CreateIcon, CreateIconIndirect, DestroyCursor, DestroyIcon, LoadImageW, SendMessageW, HCURSOR, + HICON, ICONINFO, ICON_BIG, ICON_SMALL, IMAGE_ICON, LR_DEFAULTSIZE, LR_LOADFROMFILE, WM_SETICON, +}; + +use crate::cursor::CursorImage; +use crate::dpi::PhysicalSize; +use crate::icon::*; + +use super::util; + +impl Pixel { + fn convert_to_bgra(&mut self) { + mem::swap(&mut self.r, &mut self.b); + } +} + +impl RgbaIcon { + fn into_windows_icon(self) -> Result<WinIcon, BadIcon> { + let rgba = self.rgba; + let pixel_count = rgba.len() / PIXEL_SIZE; + let mut and_mask = Vec::with_capacity(pixel_count); + let pixels = + unsafe { std::slice::from_raw_parts_mut(rgba.as_ptr() as *mut Pixel, pixel_count) }; + for pixel in pixels { + and_mask.push(pixel.a.wrapping_sub(u8::MAX)); // invert alpha channel + pixel.convert_to_bgra(); + } + assert_eq!(and_mask.len(), pixel_count); + let handle = unsafe { + CreateIcon( + 0, + self.width as i32, + self.height as i32, + 1, + (PIXEL_SIZE * 8) as u8, + and_mask.as_ptr(), + rgba.as_ptr(), + ) + }; + if handle != 0 { + Ok(WinIcon::from_handle(handle)) + } else { + Err(BadIcon::OsError(io::Error::last_os_error())) + } + } +} + +#[derive(Debug)] +pub enum IconType { + Small = ICON_SMALL as isize, + Big = ICON_BIG as isize, +} + +#[derive(Debug)] +struct RaiiIcon { + handle: HICON, +} + +#[derive(Clone)] +pub struct WinIcon { + inner: Arc<RaiiIcon>, +} + +unsafe impl Send for WinIcon {} + +impl WinIcon { + pub fn as_raw_handle(&self) -> HICON { + self.inner.handle + } + + pub fn from_path<P: AsRef<Path>>( + path: P, + size: Option<PhysicalSize<u32>>, + ) -> Result<Self, BadIcon> { + // width / height of 0 along with LR_DEFAULTSIZE tells windows to load the default icon size + let (width, height) = size.map(Into::into).unwrap_or((0, 0)); + + let wide_path = util::encode_wide(path.as_ref()); + + let handle = unsafe { + LoadImageW( + 0, + wide_path.as_ptr(), + IMAGE_ICON, + width, + height, + LR_DEFAULTSIZE | LR_LOADFROMFILE, + ) + }; + if handle != 0 { + Ok(WinIcon::from_handle(handle as HICON)) + } else { + Err(BadIcon::OsError(io::Error::last_os_error())) + } + } + + pub fn from_resource( + resource_id: u16, + size: Option<PhysicalSize<u32>>, + ) -> Result<Self, BadIcon> { + Self::from_resource_ptr(resource_id as PCWSTR, size) + } + + pub fn from_resource_name( + resource_name: &str, + size: Option<PhysicalSize<u32>>, + ) -> Result<Self, BadIcon> { + let wide_name = util::encode_wide(resource_name); + Self::from_resource_ptr(wide_name.as_ptr(), size) + } + + fn from_resource_ptr( + resource: PCWSTR, + size: Option<PhysicalSize<u32>>, + ) -> Result<Self, BadIcon> { + // width / height of 0 along with LR_DEFAULTSIZE tells windows to load the default icon size + let (width, height) = size.map(Into::into).unwrap_or((0, 0)); + let handle = unsafe { + LoadImageW( + util::get_instance_handle(), + resource, + IMAGE_ICON, + width, + height, + LR_DEFAULTSIZE, + ) + }; + if handle != 0 { + Ok(WinIcon::from_handle(handle as HICON)) + } else { + Err(BadIcon::OsError(io::Error::last_os_error())) + } + } + + pub fn from_rgba(rgba: Vec<u8>, width: u32, height: u32) -> Result<Self, BadIcon> { + let rgba_icon = RgbaIcon::from_rgba(rgba, width, height)?; + rgba_icon.into_windows_icon() + } + + pub fn set_for_window(&self, hwnd: HWND, icon_type: IconType) { + unsafe { + SendMessageW(hwnd, WM_SETICON, icon_type as usize, self.as_raw_handle()); + } + } + + fn from_handle(handle: HICON) -> Self { + Self { inner: Arc::new(RaiiIcon { handle }) } + } +} + +impl Drop for RaiiIcon { + fn drop(&mut self) { + unsafe { DestroyIcon(self.handle) }; + } +} + +impl fmt::Debug for WinIcon { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> { + (*self.inner).fmt(formatter) + } +} + +pub fn unset_for_window(hwnd: HWND, icon_type: IconType) { + unsafe { + SendMessageW(hwnd, WM_SETICON, icon_type as usize, 0); + } +} + +#[derive(Debug, Clone)] +pub enum SelectedCursor { + Named(CursorIcon), + Custom(Arc<RaiiCursor>), +} + +impl Default for SelectedCursor { + fn default() -> Self { + Self::Named(Default::default()) + } +} + +#[derive(Clone, Debug, Hash, Eq, PartialEq)] +pub enum WinCursor { + Cursor(Arc<RaiiCursor>), + Failed, +} + +impl WinCursor { + pub(crate) fn new(image: &CursorImage) -> Result<Self, io::Error> { + let mut bgra = image.rgba.clone(); + bgra.chunks_exact_mut(4).for_each(|chunk| chunk.swap(0, 2)); + + let w = image.width as i32; + let h = image.height as i32; + + unsafe { + let hdc_screen = GetDC(0); + if hdc_screen == 0 { + return Err(io::Error::last_os_error()); + } + let hbm_color = CreateCompatibleBitmap(hdc_screen, w, h); + ReleaseDC(0, hdc_screen); + if hbm_color == 0 { + return Err(io::Error::last_os_error()); + } + if SetBitmapBits(hbm_color, bgra.len() as u32, bgra.as_ptr() as *const c_void) == 0 { + DeleteObject(hbm_color); + return Err(io::Error::last_os_error()); + }; + + // Mask created according to https://learn.microsoft.com/en-us/windows/win32/api/wingdi/nf-wingdi-createbitmap#parameters + let mask_bits: Vec<u8> = vec![0xff; ((((w + 15) >> 4) << 1) * h) as usize]; + let hbm_mask = CreateBitmap(w, h, 1, 1, mask_bits.as_ptr() as *const _); + if hbm_mask == 0 { + DeleteObject(hbm_color); + return Err(io::Error::last_os_error()); + } + + let icon_info = ICONINFO { + fIcon: 0, + xHotspot: image.hotspot_x as u32, + yHotspot: image.hotspot_y as u32, + hbmMask: hbm_mask, + hbmColor: hbm_color, + }; + + let handle = CreateIconIndirect(&icon_info as *const _); + DeleteObject(hbm_color); + DeleteObject(hbm_mask); + if handle == 0 { + return Err(io::Error::last_os_error()); + } + + Ok(Self::Cursor(Arc::new(RaiiCursor { handle }))) + } + } +} + +#[derive(Debug, Hash, Eq, PartialEq)] +pub struct RaiiCursor { + handle: HCURSOR, +} + +impl Drop for RaiiCursor { + fn drop(&mut self) { + unsafe { DestroyCursor(self.handle) }; + } +} + +impl RaiiCursor { + pub fn as_raw_handle(&self) -> HICON { + self.handle + } +} diff --git a/app/vendor/rune/vendor/winit/src/platform_impl/windows/ime.rs b/app/vendor/rune/vendor/winit/src/platform_impl/windows/ime.rs new file mode 100644 index 0000000..eb65abf --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/platform_impl/windows/ime.rs @@ -0,0 +1,162 @@ +use std::ffi::{c_void, OsString}; +use std::os::windows::prelude::OsStringExt; +use std::ptr::null_mut; + +use windows_sys::Win32::Foundation::{POINT, RECT}; +use windows_sys::Win32::Globalization::HIMC; +use windows_sys::Win32::UI::Input::Ime::{ + ImmAssociateContextEx, ImmGetCompositionStringW, ImmGetContext, ImmReleaseContext, + ImmSetCandidateWindow, ImmSetCompositionWindow, ATTR_TARGET_CONVERTED, + ATTR_TARGET_NOTCONVERTED, CANDIDATEFORM, CFS_EXCLUDE, CFS_POINT, COMPOSITIONFORM, GCS_COMPATTR, + GCS_COMPSTR, GCS_CURSORPOS, GCS_RESULTSTR, IACE_CHILDREN, IACE_DEFAULT, +}; +use windows_sys::Win32::UI::WindowsAndMessaging::{GetSystemMetrics, SM_IMMENABLED}; + +use crate::dpi::{Position, Size}; +use crate::platform::windows::HWND; + +pub struct ImeContext { + hwnd: HWND, + himc: HIMC, +} + +impl ImeContext { + pub unsafe fn current(hwnd: HWND) -> Self { + let himc = unsafe { ImmGetContext(hwnd) }; + ImeContext { hwnd, himc } + } + + pub unsafe fn get_composing_text_and_cursor( + &self, + ) -> Option<(String, Option<usize>, Option<usize>)> { + let text = unsafe { self.get_composition_string(GCS_COMPSTR) }?; + let attrs = unsafe { self.get_composition_data(GCS_COMPATTR) }.unwrap_or_default(); + + let mut first = None; + let mut last = None; + let mut boundary_before_char = 0; + let mut attr_idx = 0; + + for chr in text.chars() { + let Some(attr) = attrs.get(attr_idx).copied() else { + break; + }; + + let char_is_targeted = + attr as u32 == ATTR_TARGET_CONVERTED || attr as u32 == ATTR_TARGET_NOTCONVERTED; + + if first.is_none() && char_is_targeted { + first = Some(boundary_before_char); + } else if first.is_some() && last.is_none() && !char_is_targeted { + last = Some(boundary_before_char); + } + + boundary_before_char += chr.len_utf8(); + attr_idx += chr.len_utf16(); + } + + if first.is_some() && last.is_none() { + last = Some(text.len()); + } else if first.is_none() { + // IME haven't split words and select any clause yet, so trying to retrieve normal + // cursor. + let cursor = unsafe { self.get_composition_cursor(&text) }; + first = cursor; + last = cursor; + } + + Some((text, first, last)) + } + + pub unsafe fn get_composed_text(&self) -> Option<String> { + unsafe { self.get_composition_string(GCS_RESULTSTR) } + } + + unsafe fn get_composition_cursor(&self, text: &str) -> Option<usize> { + let cursor = unsafe { ImmGetCompositionStringW(self.himc, GCS_CURSORPOS, null_mut(), 0) }; + (cursor >= 0).then(|| text.chars().take(cursor as _).map(|c| c.len_utf8()).sum()) + } + + unsafe fn get_composition_string(&self, gcs_mode: u32) -> Option<String> { + let data = unsafe { self.get_composition_data(gcs_mode) }?; + let (prefix, shorts, suffix) = unsafe { data.align_to::<u16>() }; + if prefix.is_empty() && suffix.is_empty() { + OsString::from_wide(shorts).into_string().ok() + } else { + None + } + } + + unsafe fn get_composition_data(&self, gcs_mode: u32) -> Option<Vec<u8>> { + let size = match unsafe { ImmGetCompositionStringW(self.himc, gcs_mode, null_mut(), 0) } { + 0 => return Some(Vec::new()), + size if size < 0 => return None, + size => size, + }; + + let mut buf = Vec::<u8>::with_capacity(size as _); + let size = unsafe { + ImmGetCompositionStringW( + self.himc, + gcs_mode, + buf.as_mut_ptr() as *mut c_void, + size as _, + ) + }; + + if size < 0 { + None + } else { + unsafe { buf.set_len(size as _) }; + Some(buf) + } + } + + pub unsafe fn set_ime_cursor_area(&self, spot: Position, size: Size, scale_factor: f64) { + if !unsafe { ImeContext::system_has_ime() } { + return; + } + + let (x, y) = spot.to_physical::<i32>(scale_factor).into(); + let (width, height): (i32, i32) = size.to_physical::<i32>(scale_factor).into(); + let rc_area = RECT { left: x, top: y, right: x + width, bottom: y + height }; + let candidate_form = CANDIDATEFORM { + dwIndex: 0, + dwStyle: CFS_EXCLUDE, + ptCurrentPos: POINT { x, y }, + rcArea: rc_area, + }; + let composition_form = COMPOSITIONFORM { + dwStyle: CFS_POINT, + ptCurrentPos: POINT { x, y: y + height }, + rcArea: rc_area, + }; + + unsafe { + ImmSetCompositionWindow(self.himc, &composition_form); + ImmSetCandidateWindow(self.himc, &candidate_form); + } + } + + pub unsafe fn set_ime_allowed(hwnd: HWND, allowed: bool) { + if !unsafe { ImeContext::system_has_ime() } { + return; + } + + if allowed { + unsafe { ImmAssociateContextEx(hwnd, 0, IACE_DEFAULT) }; + } else { + unsafe { ImmAssociateContextEx(hwnd, 0, IACE_CHILDREN) }; + } + } + + unsafe fn system_has_ime() -> bool { + unsafe { GetSystemMetrics(SM_IMMENABLED) != 0 } + } +} + +impl Drop for ImeContext { + fn drop(&mut self) { + unsafe { ImmReleaseContext(self.hwnd, self.himc) }; + } +} diff --git a/app/vendor/rune/vendor/winit/src/platform_impl/windows/keyboard.rs b/app/vendor/rune/vendor/winit/src/platform_impl/windows/keyboard.rs new file mode 100644 index 0000000..482bf05 --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/platform_impl/windows/keyboard.rs @@ -0,0 +1,1805 @@ +use std::char; +use std::ffi::OsString; +use std::mem::MaybeUninit; +use std::os::windows::ffi::OsStringExt; +use std::sync::atomic::AtomicU32; +use std::sync::atomic::Ordering::Relaxed; +use std::collections::VecDeque; +use std::sync::{Mutex, MutexGuard}; +use std::time::{Duration, Instant}; + +use windows_sys::Win32::Foundation::{HWND, LPARAM, WPARAM}; +use windows_sys::Win32::System::SystemServices::LANG_KOREAN; +use windows_sys::Win32::UI::Input::KeyboardAndMouse::{ + GetAsyncKeyState, GetKeyState, GetKeyboardLayout, GetKeyboardState, MapVirtualKeyExW, + MAPVK_VK_TO_VSC_EX, MAPVK_VSC_TO_VK_EX, VIRTUAL_KEY, VK_ABNT_C2, VK_ADD, VK_CAPITAL, VK_CLEAR, + VK_CONTROL, VK_DECIMAL, VK_DELETE, VK_DIVIDE, VK_DOWN, VK_END, VK_F4, VK_HOME, VK_INSERT, + VK_LCONTROL, VK_LEFT, VK_LMENU, VK_LSHIFT, VK_LWIN, VK_MENU, VK_MULTIPLY, VK_NEXT, VK_NUMLOCK, + VK_NUMPAD0, VK_NUMPAD1, VK_NUMPAD2, VK_NUMPAD3, VK_NUMPAD4, VK_NUMPAD5, VK_NUMPAD6, VK_NUMPAD7, + VK_NUMPAD8, VK_NUMPAD9, VK_PACKET, VK_PRIOR, VK_RCONTROL, VK_RETURN, VK_RIGHT, VK_RMENU, + VK_RSHIFT, VK_RWIN, VK_SCROLL, VK_SHIFT, VK_SUBTRACT, VK_UP, +}; +use windows_sys::Win32::UI::TextServices::HKL; +use windows_sys::Win32::UI::WindowsAndMessaging::{ + PeekMessageW, MSG, PM_NOREMOVE, WM_CHAR, WM_DEADCHAR, WM_KEYDOWN, WM_KEYFIRST, WM_KEYLAST, + WM_KEYUP, WM_KILLFOCUS, WM_SETFOCUS, WM_SYSCHAR, WM_SYSDEADCHAR, WM_SYSKEYDOWN, WM_SYSKEYUP, +}; + +use smol_str::SmolStr; +use tracing::{trace, warn}; +use unicode_segmentation::UnicodeSegmentation; + +use crate::event::{ElementState, KeyEvent}; +use crate::keyboard::{Key, KeyCode, KeyLocation, NamedKey, NativeKey, NativeKeyCode, PhysicalKey}; +use crate::platform_impl::platform::event_loop::ProcResult; +use crate::platform_impl::platform::keyboard_layout::{ + Layout, LayoutCache, WindowsModifiers, LAYOUT_CACHE, +}; +use crate::platform_impl::platform::{loword, primarylangid, KeyEventExtra}; + +pub type ExScancode = u16; + +pub struct MessageAsKeyEvent { + pub event: KeyEvent, + pub is_synthetic: bool, +} + +/// Stores information required to make `KeyEvent`s. +/// +/// A single Winit `KeyEvent` contains information which the Windows API passes to the application +/// in multiple window messages. In other words: a Winit `KeyEvent` cannot be built from a single +/// window message. Therefore, this type keeps track of certain information from previous events so +/// that a `KeyEvent` can be constructed when the last event related to a keypress is received. +/// +/// `PeekMessage` is sometimes used to determine whether the next window message still belongs to +/// the current keypress. If it doesn't and the current state represents a key event waiting to be +/// dispatched, then said event is considered complete and is dispatched. +/// +/// The sequence of window messages for a key press event is the following: +/// - Exactly one WM_KEYDOWN / WM_SYSKEYDOWN +/// - Zero or one WM_DEADCHAR / WM_SYSDEADCHAR +/// - Zero or more WM_CHAR / WM_SYSCHAR. These messages each come with a UTF-16 code unit which when +/// put together in the sequence they arrived in, forms the text which is the result of pressing +/// the key. +/// +/// Key release messages are a bit different due to the fact that they don't contribute to +/// text input. The "sequence" only consists of one WM_KEYUP / WM_SYSKEYUP event. +pub struct KeyEventBuilder { + event_info: Mutex<Option<PartialKeyEventInfo>>, + // Rune: high surrogate waiting for its matching low surrogate across consecutive VK_PACKET or + // bare WM_CHAR messages (Win+. emoji panel, Win+H voice typing, SendInput KEYEVENTF_UNICODE). + pending_high_surrogate: Mutex<Option<u16>>, + // Rune: recent key-downs whose `TranslateMessage` character may still arrive after their + // key-up (a program that posts keys), to tell that copy from other text. + translated: Mutex<VecDeque<Translated>>, + // Rune: the `lParam` of the key-down whose event takes the `WM_CHAR`s that follow it. + building: Mutex<Option<LPARAM>>, + pending: PendingEventQueue<MessageAsKeyEvent>, +} +impl Default for KeyEventBuilder { + fn default() -> Self { + KeyEventBuilder { + event_info: Mutex::new(None), + pending_high_surrogate: Mutex::new(None), + translated: Mutex::new(VecDeque::new()), + building: Mutex::new(None), + pending: Default::default(), + } + } +} +impl KeyEventBuilder { + /// Call this function for every window message. + /// Returns Some() if this window message completes a KeyEvent. + /// Returns None otherwise. + /// `ime_composing`: an input method's composition is open in the window (Rune). + pub(crate) fn process_message( + &self, + hwnd: HWND, + msg_kind: u32, + wparam: WPARAM, + lparam: LPARAM, + ime_composing: bool, + result: &mut ProcResult, + ) -> Vec<MessageAsKeyEvent> { + enum MatchResult { + Nothing, + TokenToRemove(PendingMessageToken), + MessagesToDispatch(Vec<MessageAsKeyEvent>), + } + + let mut matcher = || -> MatchResult { + match msg_kind { + WM_SETFOCUS => { + // synthesize keydown events + let kbd_state = get_async_kbd_state(); + let key_events = Self::synthesize_kbd_state(ElementState::Pressed, &kbd_state); + MatchResult::MessagesToDispatch(self.pending.complete_multi(key_events)) + }, + WM_KILLFOCUS => { + *self.pending_high_surrogate.lock().unwrap() = None; + self.translated.lock().unwrap().clear(); + // synthesize keyup events + let kbd_state = get_kbd_state(); + let key_events = Self::synthesize_kbd_state(ElementState::Released, &kbd_state); + MatchResult::MessagesToDispatch(self.pending.complete_multi(key_events)) + }, + WM_KEYDOWN | WM_SYSKEYDOWN => { + if msg_kind == WM_SYSKEYDOWN && wparam as VIRTUAL_KEY == VK_F4 { + // Don't dispatch Alt+F4 to the application. + // This is handled in `event_loop.rs` + return MatchResult::Nothing; + } + // Rune: preserve an unpaired high surrogate across the two VK_PACKET presses + // that deliver a supplementary-plane Unicode character; drop it on any real key. + if wparam as VIRTUAL_KEY != VK_PACKET { + *self.pending_high_surrogate.lock().unwrap() = None; + } + // Rune: `TranslateMessage` has already posted this key's character, with this + // `lParam`; a program that posted the key-up too gets it after the key-up. + let noted = msg_kind == WM_KEYDOWN && wparam as VIRTUAL_KEY != VK_PACKET; + if noted { + note_key_down(&mut self.translated.lock().unwrap(), lparam, Instant::now()); + } + *self.building.lock().unwrap() = noted.then_some(lparam); + let pending_token = self.pending.add_pending(); + *result = ProcResult::Value(0); + + let next_msg = next_kbd_msg(hwnd); + + let mut layouts = LAYOUT_CACHE.lock().unwrap(); + let mut finished_event_info = Some(PartialKeyEventInfo::from_message( + wparam, + lparam, + ElementState::Pressed, + &mut layouts, + )); + let mut event_info = self.event_info.lock().unwrap(); + *event_info = None; + if let Some(next_msg) = next_msg { + let next_msg_kind = next_msg.message; + let next_belongs_to_this = !matches!( + next_msg_kind, + WM_KEYDOWN | WM_SYSKEYDOWN | WM_KEYUP | WM_SYSKEYUP + ); + if next_belongs_to_this { + // The next OS event belongs to this Winit event, so let's just + // store the partial information, and add to it in the upcoming events + *event_info = finished_event_info.take(); + } else { + let (_, layout) = layouts.get_current_layout(); + let is_fake = { + let curr_event = finished_event_info.as_ref().unwrap(); + is_current_fake(curr_event, next_msg, layout) + }; + if is_fake { + finished_event_info = None; + } + } + } + if let Some(event_info) = finished_event_info { + let ev = event_info.finalize(); + return MatchResult::MessagesToDispatch(self.pending.complete_pending( + pending_token, + MessageAsKeyEvent { event: ev, is_synthetic: false }, + )); + } + MatchResult::TokenToRemove(pending_token) + }, + WM_DEADCHAR | WM_SYSDEADCHAR => { + let pending_token = self.pending.add_pending(); + *result = ProcResult::Value(0); + // At this point, we know that there isn't going to be any more events related + // to this key press + let event_info = self.event_info.lock().unwrap().take().unwrap(); + let ev = event_info.finalize(); + MatchResult::MessagesToDispatch(self.pending.complete_pending( + pending_token, + MessageAsKeyEvent { event: ev, is_synthetic: false }, + )) + }, + WM_CHAR | WM_SYSCHAR => { + let mut event_info = self.event_info.lock().unwrap(); + if event_info.is_none() { + // Rune: a WM_CHAR with no preceding WM_KEYDOWN (text expanders, password + // managers, assistive tools, remote input) still carries text, as Chromium + // takes it. WM_SYSCHAR stays ignored so Alt+key mnemonics never type text. + drop(event_info); + if msg_kind == WM_SYSCHAR { + trace!("Received a SYSCHAR message with no `event_info`; ignoring."); + return MatchResult::Nothing; + } + let pending_token = self.pending.add_pending(); + *result = ProcResult::Value(0); + // Rune: a posted key's own character, after a key-up that came first, + // when that key already typed it: not text a second time. + if bare_char_is_copy(&mut self.translated.lock().unwrap(), wparam, lparam, Instant::now()) { + return MatchResult::TokenToRemove(pending_token); + } + let mut pending_high = self.pending_high_surrogate.lock().unwrap(); + let Some(text) = bare_char_text(&mut pending_high, wparam, ime_composing) + else { + return MatchResult::TokenToRemove(pending_token); + }; + let ev = standalone_char_event(text, (lparam & 0xffff) > 1); + return MatchResult::MessagesToDispatch(self.pending.complete_pending( + pending_token, + MessageAsKeyEvent { event: ev, is_synthetic: false }, + )); + } + let pending_token = self.pending.add_pending(); + *result = ProcResult::Value(0); + if let Some(ev_info) = event_info.as_mut() { + if keyed_char_is_text(wparam, ev_info.vkey) { + append_wparam_utf16(wparam, &mut ev_info.utf16parts); + if let Some(down) = *self.building.lock().unwrap() { + note_keyed_text(&mut self.translated.lock().unwrap(), down, wparam); + } + } + } + // It's important that we unlock the mutex, and create the pending event token + // before calling `next_msg` + std::mem::drop(event_info); + let next_msg = next_kbd_msg(hwnd); + let more_char_coming = next_msg + .map(|m| matches!(m.message, WM_CHAR | WM_SYSCHAR)) + .unwrap_or(false); + if more_char_coming { + // No need to produce an event just yet, because there are still more + // characters that need to be appended to this keyboard event + MatchResult::TokenToRemove(pending_token) + } else { + let mut event_info = self.event_info.lock().unwrap(); + let mut event_info = match event_info.take() { + Some(ev_info) => ev_info, + None => { + warn!("The event_info was None when it was expected to be some"); + return MatchResult::TokenToRemove(pending_token); + }, + }; + let paired = resolve_surrogates( + &mut self.pending_high_surrogate.lock().unwrap(), + &mut event_info.utf16parts, + ); + if !paired && event_info.vkey == VK_PACKET { + // Rune: high half of a VK_PACKET surrogate pair; wait for the low half. + return MatchResult::TokenToRemove(pending_token); + } + let mut layouts = LAYOUT_CACHE.lock().unwrap(); + // It's okay to call `ToUnicode` here, because at this point the dead key + // is already consumed by the character. + let kbd_state = get_kbd_state(); + let mod_state = WindowsModifiers::active_modifiers(&kbd_state); + + let (_, layout) = layouts.get_current_layout(); + let ctrl_on = if layout.has_alt_graph { + let alt_on = mod_state.contains(WindowsModifiers::ALT); + !alt_on && mod_state.contains(WindowsModifiers::CONTROL) + } else { + mod_state.contains(WindowsModifiers::CONTROL) + }; + + // If Ctrl is not pressed (or this is VK_PACKET Unicode injection), just + // use the text with all modifiers because that already consumed the dead + // key. Otherwise, we would interpret the character incorrectly, missing + // the dead key. + if !ctrl_on || event_info.vkey == VK_PACKET { + event_info.text = PartialText::System(event_info.utf16parts.clone()); + } else { + let mod_no_ctrl = mod_state.remove_only_ctrl(); + let num_lock_on = kbd_state[VK_NUMLOCK as usize] & 1 != 0; + let vkey = event_info.vkey; + let physical_key = &event_info.physical_key; + let key = layout.get_key(mod_no_ctrl, num_lock_on, vkey, physical_key); + event_info.text = PartialText::Text(key.to_text().map(SmolStr::new)); + } + let ev = event_info.finalize(); + MatchResult::MessagesToDispatch(self.pending.complete_pending( + pending_token, + MessageAsKeyEvent { event: ev, is_synthetic: false }, + )) + } + }, + WM_KEYUP | WM_SYSKEYUP => { + let pending_token = self.pending.add_pending(); + *result = ProcResult::Value(0); + + let mut layouts = LAYOUT_CACHE.lock().unwrap(); + let event_info = PartialKeyEventInfo::from_message( + wparam, + lparam, + ElementState::Released, + &mut layouts, + ); + // We MUST release the layout lock before calling `next_kbd_msg`, otherwise it + // may deadlock + drop(layouts); + // It's important that we create the pending token before reading the next + // message. + let next_msg = next_kbd_msg(hwnd); + let mut valid_event_info = Some(event_info); + if let Some(next_msg) = next_msg { + let mut layouts = LAYOUT_CACHE.lock().unwrap(); + let (_, layout) = layouts.get_current_layout(); + let is_fake = { + let event_info = valid_event_info.as_ref().unwrap(); + is_current_fake(event_info, next_msg, layout) + }; + if is_fake { + valid_event_info = None; + } + } + if let Some(event_info) = valid_event_info { + let event = event_info.finalize(); + return MatchResult::MessagesToDispatch(self.pending.complete_pending( + pending_token, + MessageAsKeyEvent { event, is_synthetic: false }, + )); + } + MatchResult::TokenToRemove(pending_token) + }, + _ => MatchResult::Nothing, + } + }; + let matcher_result = matcher(); + match matcher_result { + MatchResult::TokenToRemove(t) => self.pending.remove_pending(t), + MatchResult::MessagesToDispatch(m) => m, + MatchResult::Nothing => Vec::new(), + } + } + + // Allowing nominimal_bool lint because the `is_key_pressed` macro triggers this warning + // and I don't know of another way to resolve it and also keeping the macro + #[allow(clippy::nonminimal_bool)] + fn synthesize_kbd_state( + key_state: ElementState, + kbd_state: &[u8; 256], + ) -> Vec<MessageAsKeyEvent> { + let mut key_events = Vec::new(); + + let mut layouts = LAYOUT_CACHE.lock().unwrap(); + let (locale_id, _) = layouts.get_current_layout(); + + macro_rules! is_key_pressed { + ($vk:expr) => { + kbd_state[$vk as usize] & 0x80 != 0 + }; + } + + // Is caps-lock active? Note that this is different from caps-lock + // being held down. + let caps_lock_on = kbd_state[VK_CAPITAL as usize] & 1 != 0; + let num_lock_on = kbd_state[VK_NUMLOCK as usize] & 1 != 0; + + // We are synthesizing the press event for caps-lock first for the following reasons: + // 1. If caps-lock is *not* held down but *is* active, then we have to synthesize all + // printable keys, respecting the caps-lock state. + // 2. If caps-lock is held down, we could choose to synthesize its keypress after every + // other key, in which case all other keys *must* be synthesized as if the caps-lock + // state was be the opposite of what it currently is. + // -- + // For the sake of simplicity we are choosing to always synthesize + // caps-lock first, and always use the current caps-lock state + // to determine the produced text + if is_key_pressed!(VK_CAPITAL) { + let event = Self::create_synthetic( + VK_CAPITAL, + key_state, + caps_lock_on, + num_lock_on, + locale_id as HKL, + &mut layouts, + ); + if let Some(event) = event { + key_events.push(event); + } + } + let do_non_modifier = |key_events: &mut Vec<_>, layouts: &mut _| { + for vk in 0..256 { + match vk { + VK_CONTROL | VK_LCONTROL | VK_RCONTROL | VK_SHIFT | VK_LSHIFT | VK_RSHIFT + | VK_MENU | VK_LMENU | VK_RMENU | VK_CAPITAL => continue, + _ => (), + } + if !is_key_pressed!(vk) { + continue; + } + let event = Self::create_synthetic( + vk, + key_state, + caps_lock_on, + num_lock_on, + locale_id as HKL, + layouts, + ); + if let Some(event) = event { + key_events.push(event); + } + } + }; + let do_modifier = |key_events: &mut Vec<_>, layouts: &mut _| { + const CLEAR_MODIFIER_VKS: [VIRTUAL_KEY; 6] = + [VK_LCONTROL, VK_LSHIFT, VK_LMENU, VK_RCONTROL, VK_RSHIFT, VK_RMENU]; + for vk in CLEAR_MODIFIER_VKS.iter() { + if is_key_pressed!(*vk) { + let event = Self::create_synthetic( + *vk, + key_state, + caps_lock_on, + num_lock_on, + locale_id as HKL, + layouts, + ); + if let Some(event) = event { + key_events.push(event); + } + } + } + }; + + // Be cheeky and sequence modifier and non-modifier + // key events such that non-modifier keys are not affected + // by modifiers (except for caps-lock) + match key_state { + ElementState::Pressed => { + do_non_modifier(&mut key_events, &mut layouts); + do_modifier(&mut key_events, &mut layouts); + }, + ElementState::Released => { + do_modifier(&mut key_events, &mut layouts); + do_non_modifier(&mut key_events, &mut layouts); + }, + } + + key_events + } + + fn create_synthetic( + vk: VIRTUAL_KEY, + key_state: ElementState, + caps_lock_on: bool, + num_lock_on: bool, + locale_id: HKL, + layouts: &mut MutexGuard<'_, LayoutCache>, + ) -> Option<MessageAsKeyEvent> { + let scancode = unsafe { MapVirtualKeyExW(vk as u32, MAPVK_VK_TO_VSC_EX, locale_id) }; + if scancode == 0 { + return None; + } + let scancode = scancode as ExScancode; + let physical_key = scancode_to_physicalkey(scancode as u32); + let mods = + if caps_lock_on { WindowsModifiers::CAPS_LOCK } else { WindowsModifiers::empty() }; + let layout = layouts.layouts.get(&(locale_id as u64)).unwrap(); + let logical_key = layout.get_key(mods, num_lock_on, vk, &physical_key); + let key_without_modifiers = + layout.get_key(WindowsModifiers::empty(), false, vk, &physical_key); + let text = if key_state == ElementState::Pressed { + logical_key.to_text().map(SmolStr::new) + } else { + None + }; + let event_info = PartialKeyEventInfo { + vkey: vk, + logical_key: PartialLogicalKey::This(logical_key.clone()), + key_without_modifiers, + key_state, + is_repeat: false, + physical_key, + location: get_location(scancode, locale_id), + utf16parts: Vec::with_capacity(8), + text: PartialText::Text(text.clone()), + }; + + let mut event = event_info.finalize(); + event.logical_key = logical_key; + event.platform_specific.text_with_all_modifiers = text; + Some(MessageAsKeyEvent { event, is_synthetic: true }) + } +} + +enum PartialText { + // Unicode + System(Vec<u16>), + Text(Option<SmolStr>), +} + +enum PartialLogicalKey { + /// Use the text provided by the WM_CHAR messages and report that as a `Character` variant. If + /// the text consists of multiple grapheme clusters (user-perceived characters) that means that + /// dead key could not be combined with the second input, and in that case we should fall back + /// to using what would have without a dead-key input. + TextOr(Key), + + /// Use the value directly provided by this variant + This(Key), +} + +struct PartialKeyEventInfo { + vkey: VIRTUAL_KEY, + key_state: ElementState, + is_repeat: bool, + physical_key: PhysicalKey, + location: KeyLocation, + logical_key: PartialLogicalKey, + + key_without_modifiers: Key, + + /// The UTF-16 code units of the text that was produced by the keypress event. + /// This take all modifiers into account. Including CTRL + utf16parts: Vec<u16>, + + text: PartialText, +} + +impl PartialKeyEventInfo { + fn from_message( + wparam: WPARAM, + lparam: LPARAM, + state: ElementState, + layouts: &mut MutexGuard<'_, LayoutCache>, + ) -> Self { + const NO_MODS: WindowsModifiers = WindowsModifiers::empty(); + + let (_, layout) = layouts.get_current_layout(); + let lparam_struct = destructure_key_lparam(lparam); + let vkey = wparam as VIRTUAL_KEY; + let scancode = if lparam_struct.scancode == 0 { + // In some cases (often with media keys) the device reports a scancode of 0 but a + // valid virtual key. In these cases we obtain the scancode from the virtual key. + unsafe { MapVirtualKeyExW(vkey as u32, MAPVK_VK_TO_VSC_EX, layout.hkl as HKL) as u16 } + } else { + new_ex_scancode(lparam_struct.scancode, lparam_struct.extended) + }; + // Rune: a VK_PACKET carries text, not a key: it is named as a bare WM_CHAR is + // (`standalone_char_event`), `Unidentified(NativeKeyCode::Unidentified)`, which Windows + // never reports for a real key (an unknown scan code is `NativeKeyCode::Windows(_)`). + let physical_key = if vkey == VK_PACKET { + PhysicalKey::Unidentified(NativeKeyCode::Unidentified) + } else { + scancode_to_physicalkey(scancode as u32) + }; + let location = get_location(scancode, layout.hkl as HKL); + + let kbd_state = get_kbd_state(); + let mods = WindowsModifiers::active_modifiers(&kbd_state); + let mods_without_ctrl = mods.remove_only_ctrl(); + let num_lock_on = kbd_state[VK_NUMLOCK as usize] & 1 != 0; + + // On Windows Ctrl+NumLock = Pause (and apparently Ctrl+Pause -> NumLock). In these cases + // the KeyCode still stores the real key, so in the name of consistency across platforms, we + // circumvent this mapping and force the key values to match the keycode. + // For more on this, read the article by Raymond Chen, titled: + // "Why does Ctrl+ScrollLock cancel dialogs?" + // https://devblogs.microsoft.com/oldnewthing/20080211-00/?p=23503 + let code_as_key = if mods.contains(WindowsModifiers::CONTROL) { + match physical_key { + PhysicalKey::Code(KeyCode::NumLock) => Some(Key::Named(NamedKey::NumLock)), + PhysicalKey::Code(KeyCode::Pause) => Some(Key::Named(NamedKey::Pause)), + _ => None, + } + } else { + None + }; + + let preliminary_logical_key = + layout.get_key(mods_without_ctrl, num_lock_on, vkey, &physical_key); + let key_is_char = matches!(preliminary_logical_key, Key::Character(_)); + let is_pressed = state == ElementState::Pressed; + + let logical_key = if let Some(key) = code_as_key.clone() { + PartialLogicalKey::This(key) + } else if is_pressed + && (vkey == VK_PACKET || (key_is_char && !mods.contains(WindowsModifiers::CONTROL))) + { + // In some cases we want to use the UNICHAR text for logical_key in order to allow + // dead keys (and Rune's VK_PACKET Unicode injection) to supply `logical_key`. + PartialLogicalKey::TextOr(preliminary_logical_key) + } else { + PartialLogicalKey::This(preliminary_logical_key) + }; + let key_without_modifiers = if let Some(key) = code_as_key { + key + } else { + match layout.get_key(NO_MODS, false, vkey, &physical_key) { + // We convert dead keys into their character. + // The reason for this is that `key_without_modifiers` is designed for key-bindings, + // but the US International layout treats `'` (apostrophe) as a dead key and the + // regular US layout treats it a character. In order for a single binding + // configuration to work with both layouts, we forward each dead key as a character. + Key::Dead(k) => { + if let Some(ch) = k { + // I'm avoiding the heap allocation. I don't want to talk about it :( + let mut utf8 = [0; 4]; + let s = ch.encode_utf8(&mut utf8); + Key::Character(SmolStr::new(s)) + } else { + Key::Unidentified(NativeKey::Unidentified) + } + }, + key => key, + } + }; + + PartialKeyEventInfo { + vkey, + key_state: state, + logical_key, + key_without_modifiers, + is_repeat: lparam_struct.is_repeat, + physical_key, + location, + utf16parts: Vec::with_capacity(8), + text: PartialText::System(Vec::new()), + } + } + + fn finalize(self) -> KeyEvent { + let mut char_with_all_modifiers = None; + if !self.utf16parts.is_empty() { + let os_string = OsString::from_wide(&self.utf16parts); + if let Ok(string) = os_string.into_string() { + char_with_all_modifiers = Some(SmolStr::new(string)); + } + } + + // The text without Ctrl + let mut text = None; + match self.text { + PartialText::System(wide) => { + if !wide.is_empty() { + let os_string = OsString::from_wide(&wide); + if let Ok(string) = os_string.into_string() { + text = Some(SmolStr::new(string)); + } + } + }, + PartialText::Text(s) => { + text = s.map(SmolStr::new); + }, + } + + let logical_key = match self.logical_key { + PartialLogicalKey::TextOr(fallback) => match text.as_ref() { + Some(s) => { + // Rune: a VK_PACKET names its text as the key, unless the text is a control + // character: that keeps the `Unidentified` key it had before. + let packet = self.vkey == VK_PACKET; + if (packet && s.chars().any(char::is_control)) + || (!packet && s.grapheme_indices(true).count() > 1) + { + fallback + } else { + Key::Character(s.clone()) + } + }, + None => Key::Unidentified(NativeKey::Windows(self.vkey)), + }, + PartialLogicalKey::This(v) => v, + }; + + KeyEvent { + physical_key: self.physical_key, + logical_key, + text, + location: self.location, + state: self.key_state, + repeat: self.is_repeat, + platform_specific: KeyEventExtra { + text_with_all_modifiers: char_with_all_modifiers, + key_without_modifiers: self.key_without_modifiers, + }, + } + } +} + +/// Rune: whether a `WM_CHAR` that follows a key-down is part of that key's text. `TranslateMessage` +/// adds `WM_CHAR(0)` after a VK_PACKET key-down that carries no packet (one a program posted): it +/// is not the packet's text. A real key's NUL (Ctrl+2, Ctrl+@) is that key's text, as before. +fn keyed_char_is_text(wparam: WPARAM, vkey: VIRTUAL_KEY) -> bool { + !(wparam == 0 && vkey == VK_PACKET) +} + +/// Rune: a recent `WM_KEYDOWN` whose character `TranslateMessage` posted with the same `lParam`. +/// A program that posts a key-down and its key-up together gets that character AFTER the key-up, +/// with no key in progress. `typed` is the character the key's own event already took (from a +/// `WM_CHAR` that program posted between the two), if any. +#[derive(Clone, Copy, Debug, PartialEq)] +struct Translated { + lparam: LPARAM, + typed: Option<WPARAM>, + at: Instant, +} + +/// How many key-downs are remembered, and for how long: a copy comes within a few messages. The +/// count is far above any burst inside the second, so no typed key's entry is lost to it. +const TRANSLATED_KEEP: usize = 256; +const TRANSLATED_FOR: Duration = Duration::from_secs(1); + +/// Rune: a `WM_KEYDOWN` with `lparam` happened at `now`. +fn note_key_down(list: &mut VecDeque<Translated>, lparam: LPARAM, now: Instant) { + list.retain(|t| now.saturating_duration_since(t.at) < TRANSLATED_FOR); + list.push_back(Translated { lparam, typed: None, at: now }); + while list.len() > TRANSLATED_KEEP { + list.pop_front(); + } +} + +/// Rune: the event of the key-down with `down` took `wparam` as its text. A hardware key's own +/// copy is that `WM_CHAR` (posted messages come before input), so nothing more follows it. +fn note_keyed_text(list: &mut VecDeque<Translated>, down: LPARAM, wparam: WPARAM) { + if let Some(t) = list.iter_mut().rev().find(|t| t.lparam == down && t.typed.is_none()) { + t.typed = Some(wparam); + } +} + +/// Rune: whether a bare `WM_CHAR` is a remembered key-down's own copy of the character that key +/// already typed (dropped), rather than text. A key-down that typed nothing yet claims a copy +/// with its `lParam` first (oldest first): that copy is its character, and types once. Only then +/// does a key-down that typed this same character claim it, and the copy is dropped. Any other +/// `lParam` (programs that post text alone post 0 or 1), or an entry older than a second, matches +/// nothing. Each entry is claimed once. +fn bare_char_is_copy(list: &mut VecDeque<Translated>, wparam: WPARAM, lparam: LPARAM, now: Instant) -> bool { + list.retain(|t| now.saturating_duration_since(t.at) < TRANSLATED_FOR); + if let Some(i) = list.iter().position(|t| t.lparam == lparam && t.typed.is_none()) { + list.remove(i); + return false; + } + if let Some(i) = list.iter().position(|t| t.lparam == lparam && t.typed == Some(wparam)) { + list.remove(i); + return true; + } + false +} + +/// Rune: appends a `WM_CHAR` `wparam` (UTF-16 surrogate unit or Unicode scalar) onto +/// `utf16parts`. +fn append_wparam_utf16(wparam: WPARAM, utf16parts: &mut Vec<u16>) { + let is_high_surrogate = (0xd800..=0xdbff).contains(&wparam); + let is_low_surrogate = (0xdc00..=0xdfff).contains(&wparam); + if is_high_surrogate || is_low_surrogate { + utf16parts.push(wparam as u16); + } else if let Some(ch) = char::from_u32(wparam as u32) { + let mut buf = [0u16; 2]; + utf16parts.extend_from_slice(ch.encode_utf16(&mut buf)); + } +} + +/// Rune: pairs a pending high surrogate with an incoming leading low surrogate, and stashes a +/// trailing lone high surrogate for the next `WM_CHAR`. Returns `false` when `units` held only +/// that lone high surrogate so the caller waits for the low half instead of dropping it, and when +/// `units` is empty (a VK_PACKET key-down whose only `WM_CHAR` was the NUL): nothing to type, and +/// a waiting high half keeps waiting. +fn resolve_surrogates(pending: &mut Option<u16>, units: &mut Vec<u16>) -> bool { + if units.is_empty() { + return false; + } + if units.first().copied().is_some_and(|u| (0xdc00..=0xdfff).contains(&u)) { + if let Some(hi) = pending.take() { + units.insert(0, hi); + } + } else { + *pending = None; + } + if units.last().copied().is_some_and(|u| (0xd800..=0xdbff).contains(&u)) { + *pending = units.pop(); + if units.is_empty() { + return false; + } + } + true +} + +/// Rune: the text a `WM_CHAR` with no preceding `WM_KEYDOWN` types, if any. A high surrogate +/// waits in `pending` for its low half; a lone half is dropped, never inserted. Control +/// characters (Backspace, Enter, Escape, DEL, …) are not text: they act only as keys. While an +/// input method's composition is open its result arrives as `Ime::Commit`, so a stray `WM_CHAR` +/// then would type the text twice: it is dropped. A NUL (the `WM_CHAR(0)` that `TranslateMessage` +/// adds after a posted VK_PACKET key-down) changes nothing, not even a waiting high surrogate. +fn bare_char_text(pending: &mut Option<u16>, wparam: WPARAM, ime_composing: bool) -> Option<String> { + if wparam == 0 { + return None; + } + if ime_composing { + *pending = None; + return None; + } + let mut units = Vec::with_capacity(2); + append_wparam_utf16(wparam, &mut units); + if !resolve_surrogates(pending, &mut units) { + return None; + } + let text = String::from_utf16(&units).ok()?; + (!text.is_empty() && !text.chars().any(char::is_control)).then_some(text) +} + +/// Rune: a pressed `KeyEvent` that types `text` and names no physical key. +fn standalone_char_event(text: String, is_repeat: bool) -> KeyEvent { + let text = SmolStr::new(text); + KeyEvent { + physical_key: PhysicalKey::Unidentified(NativeKeyCode::Unidentified), + logical_key: Key::Character(text.clone()), + text: Some(text.clone()), + location: KeyLocation::Standard, + state: ElementState::Pressed, + repeat: is_repeat, + platform_specific: KeyEventExtra { + text_with_all_modifiers: Some(text), + key_without_modifiers: Key::Unidentified(NativeKey::Unidentified), + }, + } +} + +#[cfg(test)] +mod rune_bare_char_tests { + use super::{bare_char_text, keyed_char_is_text, resolve_surrogates}; + use windows_sys::Win32::UI::Input::KeyboardAndMouse::{VK_2, VK_A, VK_PACKET}; + + const NONE: Option<String> = None; + + fn s(text: &str) -> Option<String> { + Some(text.to_owned()) + } + + /// Feeds `units` as consecutive bare `WM_CHAR`s and returns the text each one typed. + fn feed(units: &[usize], ime_composing: bool) -> Vec<Option<String>> { + let mut pending = None; + units.iter().map(|&u| bare_char_text(&mut pending, u, ime_composing)).collect() + } + + #[test] + fn bmp_characters_type_themselves() { + assert_eq!(feed(&[0x61, 0xe9, 0x65e5], false), [s("a"), s("é"), s("日")]); + } + + #[test] + fn a_surrogate_pair_split_over_two_messages_types_one_character() { + assert_eq!(feed(&[0xd83d, 0xde00], false), [NONE, s("😀")]); + } + + #[test] + fn a_lone_surrogate_half_is_dropped() { + // High half then a BMP character: the high half is dropped, the character types. + assert_eq!(feed(&[0xd83d, 0x61], false), [NONE, s("a")]); + // Low half with no high half before it. + assert_eq!(feed(&[0xde00], false), [NONE]); + // Two high halves: the first is dropped, the second pairs with the low half. + assert_eq!(feed(&[0xd83d, 0xd83d, 0xde00], false), [NONE, NONE, s("😀")]); + } + + #[test] + fn an_empty_packet_key_down_keeps_the_waiting_high_half() { + let mut pending = None; + // The high half's VK_PACKET key-down: it waits. + let mut high = vec![0xd83d]; + assert!(!resolve_surrogates(&mut pending, &mut high)); + assert_eq!(pending, Some(0xd83d)); + // The low half's VK_PACKET key-down completes with empty text (its only WM_CHAR was the + // NUL): nothing to type, and the high half keeps waiting. + let mut empty = Vec::new(); + assert!(!resolve_surrogates(&mut pending, &mut empty)); + assert_eq!(pending, Some(0xd83d)); + // The low half's character then arrives: one emoji. + assert_eq!(bare_char_text(&mut pending, 0xde00, false), s("😀")); + assert_eq!(pending, None); + } + + #[test] + fn only_a_packet_key_downs_nul_is_left_out_of_its_text() { + // The NUL `TranslateMessage` adds after a posted VK_PACKET key-down is not text. + assert!(!keyed_char_is_text(0, VK_PACKET)); + // The packet's real characters are. + assert!(keyed_char_is_text('a' as usize, VK_PACKET)); + assert!(keyed_char_is_text(0xd83d, VK_PACKET)); + // A real key's NUL (Ctrl+2) stays that key's text, as before. + assert!(keyed_char_is_text(0, VK_2)); + assert!(keyed_char_is_text(0, VK_A)); + } + + #[test] + fn a_nul_between_the_halves_neither_types_nor_breaks_the_pair() { + // `TranslateMessage` adds `WM_CHAR(0)` after a posted VK_PACKET key-down. + assert_eq!(feed(&[0xd83d, 0x00, 0xde00], false), [NONE, NONE, s("😀")]); + assert_eq!(feed(&[0x00, 0x61, 0x00], false), [NONE, s("a"), NONE]); + } + + #[test] + fn a_combining_mark_types_after_its_base() { + assert_eq!(feed(&[0x65, 0x301], false), [s("e"), s("\u{301}")]); + } + + #[test] + fn control_characters_are_not_text() { + for c in [0x08, 0x09, 0x0a, 0x0d, 0x1b, 0x7f, 0x00, 0x85] { + assert_eq!(feed(&[c], false), [NONE], "U+{c:04X}"); + } + } + + #[test] + fn nothing_types_while_an_ime_composition_is_open() { + assert_eq!(feed(&[0x61, 0xd83d, 0xde00], true), [NONE, NONE, NONE]); + // A high half that arrived before the composition opened does not pair after it. + let mut pending = None; + assert_eq!(bare_char_text(&mut pending, 0xd83d, false), None); + assert_eq!(bare_char_text(&mut pending, 0xde00, true), None); + assert_eq!(bare_char_text(&mut pending, 0xde00, false), None); + } +} + +#[cfg(test)] +mod rune_posted_key_tests { + //! What a posted key's `TranslateMessage` copy does, for each order of key messages. Each test + //! replays the order through the same calls the key-down, keyed `WM_CHAR` and bare `WM_CHAR` + //! handlers make, and counts the characters that type. + use std::collections::VecDeque; + use std::time::{Duration, Instant}; + + use super::{bare_char_is_copy, note_key_down, note_keyed_text, Translated}; + + const H: usize = 'h' as usize; + const E: usize = 'e' as usize; + const L: usize = 'l' as usize; + // lParam: repeat count 1, scan code in bits 16-23 (as `TranslateMessage` copies it). + fn lp(scan: isize) -> isize { 1 | (scan << 16) } + + /// The text a sequence types: keyed chars type with their key; a bare char types unless it is + /// a copy of text its key already typed. + struct Replay { list: VecDeque<Translated>, now: Instant, typed: String } + impl Replay { + fn new() -> Self { Self { list: VecDeque::new(), now: Instant::now(), typed: String::new() } } + fn down(&mut self, lparam: isize) { note_key_down(&mut self.list, lparam, self.now); } + fn keyed(&mut self, down: isize, ch: usize) { note_keyed_text(&mut self.list, down, ch); self.typed.push(char::from_u32(ch as u32).unwrap()); } + fn bare(&mut self, ch: usize, lparam: isize) { + if !bare_char_is_copy(&mut self.list, ch, lparam, self.now) { self.typed.push(char::from_u32(ch as u32).unwrap()); } + } + fn wait(&mut self, d: Duration) { self.now += d; } + } + + #[test] + fn hardware_order_types_each_char_once() { + // down, its own char (posted before the key-up, which is input), up. + let mut r = Replay::new(); + for (ch, scan) in [(H, 0x23), (E, 0x12), (L, 0x26), (L, 0x26)] { r.down(lp(scan)); r.keyed(lp(scan), ch); } + assert_eq!(r.typed, "hell"); + } + + #[test] + fn down_and_up_back_to_back_type_the_late_copy_once() { + // The key's event takes no text (its key-up came first); its copy arrives bare. + let mut r = Replay::new(); + r.down(lp(0x23)); + r.bare(H, lp(0x23)); + assert_eq!(r.typed, "h"); + } + + #[test] + fn all_downs_then_all_ups_type_every_copy_once_in_order() { + let mut r = Replay::new(); + for scan in [0x23, 0x12, 0x26, 0x26] { r.down(lp(scan)); } + for (ch, scan) in [(H, 0x23), (E, 0x12), (L, 0x26), (L, 0x26)] { r.bare(ch, lp(scan)); } + assert_eq!(r.typed, "hell"); + } + + #[test] + fn down_char_up_does_not_type_the_copy_again() { + // A program posts key-down, WM_CHAR and key-up together: the explicit char types with the + // key; TranslateMessage's copy lands after the key-up (driver log, 02:58 run: `hhelloo`). + let mut r = Replay::new(); + for (ch, scan) in [(H, 0x23), (E, 0x12), (L, 0x26), (L, 0x26)] { r.down(lp(scan)); r.keyed(lp(scan), ch); } + for (ch, scan) in [(H, 0x23), (E, 0x12), (L, 0x26), (L, 0x26)] { r.bare(ch, lp(scan)); } + assert_eq!(r.typed, "hell"); + } + + #[test] + fn bare_text_from_a_program_types_as_before() { + // Programs that post text alone post lParam 0 or 1: never a remembered key-down's. + let mut r = Replay::new(); + r.down(lp(0x23)); + r.keyed(lp(0x23), H); + for ch in [E, L, L] { r.bare(ch, 1); } + r.bare(H, 0); + assert_eq!(r.typed, "hellh"); + } + + #[test] + fn with_nothing_remembered_every_bare_char_types() { + // VK_PACKET and bare paths: no key-down was remembered (VK_PACKET is never noted). + let mut r = Replay::new(); + r.bare(0xe9, 1); + r.bare(H, lp(0x23)); + assert_eq!(r.typed, "éh"); + } + + #[test] + fn a_held_key_s_repeats_type_one_char_each_and_nothing_is_dropped() { + // Auto-repeat: the same scan code, bit 30 (previous state) set, each repeat with its own char. + let rep = lp(0x26) | (1 << 30); + let mut r = Replay::new(); + r.down(lp(0x26)); + r.keyed(lp(0x26), L); + for _ in 0..5 { r.wait(Duration::from_millis(33)); r.down(rep); r.keyed(rep, L); } + assert_eq!(r.typed, "llllll"); + // A program's bare text afterwards still types. + r.bare(L, 1); + assert_eq!(r.typed, "lllllll"); + } + + #[test] + fn the_same_key_posted_twice_types_twice() { + // down, up, down, up, then the two copies: each copy belongs to one press. + let mut r = Replay::new(); + r.down(lp(0x26)); + r.down(lp(0x26)); + r.bare(L, lp(0x26)); + r.bare(L, lp(0x26)); + assert_eq!(r.typed, "ll"); + // And with explicit chars (down + char + up, twice): two l, no copies. + let mut r = Replay::new(); + r.down(lp(0x26)); r.keyed(lp(0x26), L); + r.down(lp(0x26)); r.keyed(lp(0x26), L); + r.bare(L, lp(0x26)); + r.bare(L, lp(0x26)); + assert_eq!(r.typed, "ll"); + } + + #[test] + fn a_stale_key_down_never_eats_later_text() { + // An entry older than a second matches nothing: later bare text with the same lParam types. + let mut r = Replay::new(); + r.down(lp(0x23)); + r.keyed(lp(0x23), H); + r.wait(Duration::from_millis(1001)); + r.bare(H, lp(0x23)); + assert_eq!(r.typed, "hh"); + // A different character with that lParam is not the copy either. + let mut r = Replay::new(); + r.down(lp(0x23)); + r.keyed(lp(0x23), H); + r.bare(E, lp(0x23)); + assert_eq!(r.typed, "he"); + } + + #[test] + fn a_real_key_s_entry_never_takes_a_later_posted_key_s_copy() { + // A real H (its char keyed), then a program's H down + up with the same lParam inside the + // second: the late copy belongs to the program's key, which typed nothing: it types. + let mut r = Replay::new(); + r.down(lp(0x23)); + r.keyed(lp(0x23), H); + r.wait(Duration::from_millis(200)); + r.down(lp(0x23)); + r.bare(H, lp(0x23)); + assert_eq!(r.typed, "hh"); + } + + #[test] + fn a_burst_of_forty_posted_letters_types_each_once() { + // down + char + up for forty letters, every copy after them: no typed entry is evicted. + let letters: Vec<(usize, isize)> = (0..40).map(|i| ('a' as usize + i % 26, 0x10 + (i % 26) as isize)).collect(); + let mut r = Replay::new(); + for &(ch, scan) in &letters { r.down(lp(scan)); r.keyed(lp(scan), ch); } + for &(ch, scan) in &letters { r.bare(ch, lp(scan)); } + let want: String = letters.iter().map(|&(ch, _)| char::from_u32(ch as u32).unwrap()).collect(); + assert_eq!(r.typed, want); + } + + #[test] + fn at_most_two_hundred_fifty_six_key_downs_are_remembered() { + let mut list = VecDeque::new(); + let now = Instant::now(); + for scan in 0..300 { note_key_down(&mut list, lp(scan), now); } + assert_eq!(list.len(), 256); + assert_eq!(list.front().map(|t| t.lparam), Some(lp(44)), "the oldest go first"); + } +} + +#[cfg(test)] +mod rune_posted_key_handler_tests { + //! The same orders as real messages through `KeyEventBuilder::process_message`: posted to this + //! test thread's own queue, taken off it in order and handed to the handler with no window + //! (`hwnd` 0, so `next_kbd_msg` peeks this thread's queue as it peeks the window's). The test + //! posts `TranslateMessage`'s copy itself, where the driver log shows it: after the key-up, + //! with the key-down's `lParam`. + use std::mem::MaybeUninit; + + use windows_sys::Win32::System::Threading::GetCurrentThreadId; + use windows_sys::Win32::UI::Input::KeyboardAndMouse::VK_PACKET; + use windows_sys::Win32::UI::WindowsAndMessaging::{ + PeekMessageW, PostThreadMessageW, MSG, PM_NOREMOVE, PM_REMOVE, WM_CHAR, WM_KEYDOWN, + WM_KEYUP, WM_KILLFOCUS, + }; + + use super::KeyEventBuilder; + use crate::event::ElementState; + use crate::platform_impl::platform::event_loop::ProcResult; + + const VK_H: usize = 0x48; + const VK_E: usize = 0x45; + const H: usize = 'h' as usize; + const E: usize = 'e' as usize; + fn lp(scan: isize) -> isize { 1 | (scan << 16) } + fn up(scan: isize) -> isize { lp(scan) | (3 << 30) } + + /// Posts `messages` to this thread, then hands each to the handler in queue order; the text + /// of every pressed key event, in order. + fn feed(builder: &KeyEventBuilder, messages: &[(u32, usize, isize)]) -> String { + let mut msg = MaybeUninit::<MSG>::zeroed(); + // SAFETY: plain Win32 calls on this thread's own queue; `msg` is written before it is read. + unsafe { + PeekMessageW(msg.as_mut_ptr(), 0, 0, 0, PM_NOREMOVE); + let thread = GetCurrentThreadId(); + for &(kind, wparam, lparam) in messages { + assert_ne!(PostThreadMessageW(thread, kind, wparam, lparam), 0, "post {kind:#x}"); + } + let mut typed = String::new(); + while PeekMessageW(msg.as_mut_ptr(), 0, 0, 0, PM_REMOVE) != 0 { + let m = msg.assume_init_ref(); + let mut result = ProcResult::DefWindowProc(m.wParam); + for ev in builder.process_message(0, m.message, m.wParam, m.lParam, false, &mut result) { + if ev.event.state == ElementState::Pressed { + typed.push_str(ev.event.text.as_deref().unwrap_or("")); + } + } + } + typed + } + } + + #[test] + fn down_char_up_then_the_copy_types_once() { + let b = KeyEventBuilder::default(); + let typed = feed(&b, &[ + (WM_KEYDOWN, VK_H, lp(0x23)), (WM_CHAR, H, lp(0x23)), (WM_KEYUP, VK_H, up(0x23)), + (WM_KEYDOWN, VK_E, lp(0x12)), (WM_CHAR, E, lp(0x12)), (WM_KEYUP, VK_E, up(0x12)), + (WM_CHAR, H, lp(0x23)), (WM_CHAR, E, lp(0x12)), + ]); + assert_eq!(typed, "he", "the bare path consulted the list and dropped both copies"); + } + + #[test] + fn down_up_then_the_copy_types_once() { + let b = KeyEventBuilder::default(); + let typed = feed(&b, &[(WM_KEYDOWN, VK_H, lp(0x23)), (WM_KEYUP, VK_H, up(0x23)), (WM_CHAR, H, lp(0x23))]); + assert_eq!(typed, "h"); + } + + #[test] + fn a_real_key_then_a_posted_key_s_copy_types_twice() { + // Hardware order (the char comes before the key-up), then a program's down + up + copy. + let b = KeyEventBuilder::default(); + let typed = feed(&b, &[ + (WM_KEYDOWN, VK_H, lp(0x23)), (WM_CHAR, H, lp(0x23)), (WM_KEYUP, VK_H, up(0x23)), + (WM_KEYDOWN, VK_H, lp(0x23)), (WM_KEYUP, VK_H, up(0x23)), (WM_CHAR, H, lp(0x23)), + ]); + assert_eq!(typed, "hh"); + } + + #[test] + fn bare_text_from_a_program_types() { + let b = KeyEventBuilder::default(); + assert_eq!(feed(&b, &[(WM_CHAR, H, 1), (WM_CHAR, E, 0)]), "he"); + } + + #[test] + fn a_vk_packet_key_down_is_not_remembered() { + let b = KeyEventBuilder::default(); + let typed = feed(&b, &[(WM_KEYDOWN, VK_PACKET as usize, 1), (WM_CHAR, 0xe9, 1), (WM_KEYUP, VK_PACKET as usize, up(0))]); + assert_eq!(typed, "é"); + assert!(b.translated.lock().unwrap().is_empty()); + } + + #[test] + fn focus_loss_forgets_every_key_down() { + let b = KeyEventBuilder::default(); + feed(&b, &[(WM_KEYDOWN, VK_H, lp(0x23)), (WM_CHAR, H, lp(0x23)), (WM_KEYUP, VK_H, up(0x23))]); + assert_eq!(b.translated.lock().unwrap().len(), 1); + feed(&b, &[(WM_KILLFOCUS, 0, 0)]); + assert!(b.translated.lock().unwrap().is_empty()); + // So a copy arriving after focus came back types as text. + assert_eq!(feed(&b, &[(WM_CHAR, H, lp(0x23))]), "h"); + } +} + +#[derive(Debug, Copy, Clone)] +struct KeyLParam { + pub scancode: u8, + pub extended: bool, + + /// This is `previous_state XOR transition_state`. See the lParam for WM_KEYDOWN and WM_KEYUP + /// for further details. + pub is_repeat: bool, +} + +fn destructure_key_lparam(lparam: LPARAM) -> KeyLParam { + let previous_state = (lparam >> 30) & 0x01; + let transition_state = (lparam >> 31) & 0x01; + KeyLParam { + scancode: ((lparam >> 16) & 0xff) as u8, + extended: ((lparam >> 24) & 0x01) != 0, + is_repeat: (previous_state ^ transition_state) != 0, + } +} + +#[inline] +fn new_ex_scancode(scancode: u8, extended: bool) -> ExScancode { + (scancode as u16) | (if extended { 0xe000 } else { 0 }) +} + +#[inline] +fn ex_scancode_from_lparam(lparam: LPARAM) -> ExScancode { + let lparam = destructure_key_lparam(lparam); + new_ex_scancode(lparam.scancode, lparam.extended) +} + +/// Gets the keyboard state as reported by messages that have been removed from the event queue. +/// See also: get_async_kbd_state +fn get_kbd_state() -> [u8; 256] { + unsafe { + let mut kbd_state: MaybeUninit<[u8; 256]> = MaybeUninit::uninit(); + GetKeyboardState(kbd_state.as_mut_ptr() as *mut u8); + kbd_state.assume_init() + } +} + +/// Gets the current keyboard state regardless of whether the corresponding keyboard events have +/// been removed from the event queue. See also: get_kbd_state +#[allow(clippy::uninit_assumed_init)] +fn get_async_kbd_state() -> [u8; 256] { + unsafe { + let mut kbd_state: [u8; 256] = [0; 256]; + for (vk, state) in kbd_state.iter_mut().enumerate() { + let vk = vk as VIRTUAL_KEY; + let async_state = GetAsyncKeyState(vk as i32); + let is_down = (async_state & (1 << 15)) != 0; + *state = if is_down { 0x80 } else { 0 }; + + if matches!(vk, VK_CAPITAL | VK_NUMLOCK | VK_SCROLL) { + // Toggle states aren't reported by `GetAsyncKeyState` + let toggle_state = GetKeyState(vk as i32); + let is_active = (toggle_state & 1) != 0; + *state |= u8::from(is_active); + } + } + kbd_state + } +} + +/// On windows, AltGr == Ctrl + Alt +/// +/// Due to this equivalence, the system generates a fake Ctrl key-press (and key-release) preceding +/// every AltGr key-press (and key-release). We check if the current event is a Ctrl event and if +/// the next event is a right Alt (AltGr) event. If this is the case, the current event must be the +/// fake Ctrl event. +fn is_current_fake(curr_info: &PartialKeyEventInfo, next_msg: MSG, layout: &Layout) -> bool { + let curr_is_ctrl = + matches!(curr_info.logical_key, PartialLogicalKey::This(Key::Named(NamedKey::Control))); + if layout.has_alt_graph { + let next_code = ex_scancode_from_lparam(next_msg.lParam); + let next_is_altgr = next_code == 0xe038; // 0xE038 is right alt + if curr_is_ctrl && next_is_altgr { + return true; + } + } + false +} + +enum PendingMessage<T> { + Incomplete, + Complete(T), +} +struct IdentifiedPendingMessage<T> { + token: PendingMessageToken, + msg: PendingMessage<T>, +} +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct PendingMessageToken(u32); + +/// While processing keyboard events, we sometimes need +/// to call `PeekMessageW` (`next_msg`). But `PeekMessageW` +/// can also call the event handler, which means that the new event +/// gets processed before finishing to process the one that came before. +/// +/// This would mean that the application receives events in the wrong order. +/// To avoid this, we keep track whether we are in the middle of processing +/// an event. Such an event is an "incomplete pending event". A +/// "complete pending event" is one that has already finished processing, but +/// hasn't been dispatched to the application because there still are incomplete +/// pending events that came before it. +/// +/// When we finish processing an event, we call `complete_pending`, +/// which returns an empty array if there are incomplete pending events, but +/// if all pending events are complete, then it returns all pending events in +/// the order they were encountered. These can then be dispatched to the application +pub struct PendingEventQueue<T> { + pending: Mutex<Vec<IdentifiedPendingMessage<T>>>, + next_id: AtomicU32, +} +impl<T> PendingEventQueue<T> { + /// Add a new pending event to the "pending queue" + pub fn add_pending(&self) -> PendingMessageToken { + let token = self.next_token(); + let mut pending = self.pending.lock().unwrap(); + pending.push(IdentifiedPendingMessage { token, msg: PendingMessage::Incomplete }); + token + } + + /// Returns all finished pending events + /// + /// If the return value is non empty, it's guaranteed to contain `msg` + /// + /// See also: `add_pending` + pub fn complete_pending(&self, token: PendingMessageToken, msg: T) -> Vec<T> { + let mut pending = self.pending.lock().unwrap(); + let mut target_is_first = false; + for (i, pending_msg) in pending.iter_mut().enumerate() { + if pending_msg.token == token { + pending_msg.msg = PendingMessage::Complete(msg); + if i == 0 { + target_is_first = true; + } + break; + } + } + if target_is_first { + // If the message that we just finished was the first one in the pending queue, + // then we can empty the queue, and dispatch all of the messages. + Self::drain_pending(&mut *pending) + } else { + Vec::new() + } + } + + pub fn complete_multi(&self, msgs: Vec<T>) -> Vec<T> { + let mut pending = self.pending.lock().unwrap(); + if pending.is_empty() { + return msgs; + } + pending.reserve(msgs.len()); + for msg in msgs { + pending.push(IdentifiedPendingMessage { + token: self.next_token(), + msg: PendingMessage::Complete(msg), + }); + } + Vec::new() + } + + /// Returns all finished pending events + /// + /// It's safe to call this even if the element isn't in the list anymore + /// + /// See also: `add_pending` + pub fn remove_pending(&self, token: PendingMessageToken) -> Vec<T> { + let mut pending = self.pending.lock().unwrap(); + let mut was_first = false; + if let Some(m) = pending.first() { + if m.token == token { + was_first = true; + } + } + pending.retain(|m| m.token != token); + if was_first { + Self::drain_pending(&mut *pending) + } else { + Vec::new() + } + } + + fn drain_pending(pending: &mut Vec<IdentifiedPendingMessage<T>>) -> Vec<T> { + pending + .drain(..) + .map(|m| match m.msg { + PendingMessage::Complete(msg) => msg, + PendingMessage::Incomplete => { + panic!( + "Found an incomplete pending message when collecting messages. This \ + indicates a bug in winit." + ) + }, + }) + .collect() + } + + fn next_token(&self) -> PendingMessageToken { + // It's okay for the u32 to overflow here. Yes, that could mean + // that two different messages have the same token, + // but that would only happen after having about 4 billion + // messages sitting in the pending queue. + // + // In that case, having two identical tokens is the least of your concerns. + let id = self.next_id.fetch_add(1, Relaxed); + PendingMessageToken(id) + } +} +impl<T> Default for PendingEventQueue<T> { + fn default() -> Self { + PendingEventQueue { pending: Mutex::new(Vec::new()), next_id: AtomicU32::new(0) } + } +} + +/// WARNING: Due to using PeekMessage, the event handler +/// function may get called during this function. +/// (Re-entrance to the event handler) +/// +/// This can cause a deadlock if calling this function +/// while having a mutex locked. +/// +/// It can also cause code to get executed in a surprising order. +pub fn next_kbd_msg(hwnd: HWND) -> Option<MSG> { + unsafe { + let mut next_msg = MaybeUninit::uninit(); + let peek_retval = + PeekMessageW(next_msg.as_mut_ptr(), hwnd, WM_KEYFIRST, WM_KEYLAST, PM_NOREMOVE); + (peek_retval != 0).then(|| next_msg.assume_init()) + } +} + +fn get_location(scancode: ExScancode, hkl: HKL) -> KeyLocation { + const ABNT_C2: VIRTUAL_KEY = VK_ABNT_C2 as VIRTUAL_KEY; + + let extension = 0xe000; + let extended = (scancode & extension) == extension; + let vkey = unsafe { MapVirtualKeyExW(scancode as u32, MAPVK_VSC_TO_VK_EX, hkl) as VIRTUAL_KEY }; + + // Use the native VKEY and the extended flag to cover most cases + // This is taken from the `druid` GUI library, specifically + // druid-shell/src/platform/windows/keyboard.rs + match vkey { + VK_LSHIFT | VK_LCONTROL | VK_LMENU | VK_LWIN => KeyLocation::Left, + VK_RSHIFT | VK_RCONTROL | VK_RMENU | VK_RWIN => KeyLocation::Right, + VK_RETURN if extended => KeyLocation::Numpad, + VK_INSERT | VK_DELETE | VK_END | VK_DOWN | VK_NEXT | VK_LEFT | VK_CLEAR | VK_RIGHT + | VK_HOME | VK_UP | VK_PRIOR => { + if extended { + KeyLocation::Standard + } else { + KeyLocation::Numpad + } + }, + VK_NUMPAD0 | VK_NUMPAD1 | VK_NUMPAD2 | VK_NUMPAD3 | VK_NUMPAD4 | VK_NUMPAD5 + | VK_NUMPAD6 | VK_NUMPAD7 | VK_NUMPAD8 | VK_NUMPAD9 | VK_DECIMAL | VK_DIVIDE + | VK_MULTIPLY | VK_SUBTRACT | VK_ADD | ABNT_C2 => KeyLocation::Numpad, + _ => KeyLocation::Standard, + } +} + +pub(crate) fn physicalkey_to_scancode(physical_key: PhysicalKey) -> Option<u32> { + // See `scancode_to_physicalkey` for more info + + let hkl = unsafe { GetKeyboardLayout(0) }; + + let primary_lang_id = primarylangid(loword(hkl as u32)); + let is_korean = primary_lang_id as u32 == LANG_KOREAN; + + let code = match physical_key { + PhysicalKey::Code(code) => code, + PhysicalKey::Unidentified(code) => { + return match code { + NativeKeyCode::Windows(scancode) => Some(scancode as u32), + _ => None, + }; + }, + }; + + match code { + KeyCode::Backquote => Some(0x0029), + KeyCode::Backslash => Some(0x002b), + KeyCode::Backspace => Some(0x000e), + KeyCode::BracketLeft => Some(0x001a), + KeyCode::BracketRight => Some(0x001b), + KeyCode::Comma => Some(0x0033), + KeyCode::Digit0 => Some(0x000b), + KeyCode::Digit1 => Some(0x0002), + KeyCode::Digit2 => Some(0x0003), + KeyCode::Digit3 => Some(0x0004), + KeyCode::Digit4 => Some(0x0005), + KeyCode::Digit5 => Some(0x0006), + KeyCode::Digit6 => Some(0x0007), + KeyCode::Digit7 => Some(0x0008), + KeyCode::Digit8 => Some(0x0009), + KeyCode::Digit9 => Some(0x000a), + KeyCode::Equal => Some(0x000d), + KeyCode::IntlBackslash => Some(0x0056), + KeyCode::IntlRo => Some(0x0073), + KeyCode::IntlYen => Some(0x007d), + KeyCode::KeyA => Some(0x001e), + KeyCode::KeyB => Some(0x0030), + KeyCode::KeyC => Some(0x002e), + KeyCode::KeyD => Some(0x0020), + KeyCode::KeyE => Some(0x0012), + KeyCode::KeyF => Some(0x0021), + KeyCode::KeyG => Some(0x0022), + KeyCode::KeyH => Some(0x0023), + KeyCode::KeyI => Some(0x0017), + KeyCode::KeyJ => Some(0x0024), + KeyCode::KeyK => Some(0x0025), + KeyCode::KeyL => Some(0x0026), + KeyCode::KeyM => Some(0x0032), + KeyCode::KeyN => Some(0x0031), + KeyCode::KeyO => Some(0x0018), + KeyCode::KeyP => Some(0x0019), + KeyCode::KeyQ => Some(0x0010), + KeyCode::KeyR => Some(0x0013), + KeyCode::KeyS => Some(0x001f), + KeyCode::KeyT => Some(0x0014), + KeyCode::KeyU => Some(0x0016), + KeyCode::KeyV => Some(0x002f), + KeyCode::KeyW => Some(0x0011), + KeyCode::KeyX => Some(0x002d), + KeyCode::KeyY => Some(0x0015), + KeyCode::KeyZ => Some(0x002c), + KeyCode::Minus => Some(0x000c), + KeyCode::Period => Some(0x0034), + KeyCode::Quote => Some(0x0028), + KeyCode::Semicolon => Some(0x0027), + KeyCode::Slash => Some(0x0035), + KeyCode::AltLeft => Some(0x0038), + KeyCode::AltRight => Some(0xe038), + KeyCode::CapsLock => Some(0x003a), + KeyCode::ContextMenu => Some(0xe05d), + KeyCode::ControlLeft => Some(0x001d), + KeyCode::ControlRight => Some(0xe01d), + KeyCode::Enter => Some(0x001c), + KeyCode::SuperLeft => Some(0xe05b), + KeyCode::SuperRight => Some(0xe05c), + KeyCode::ShiftLeft => Some(0x002a), + KeyCode::ShiftRight => Some(0x0036), + KeyCode::Space => Some(0x0039), + KeyCode::Tab => Some(0x000f), + KeyCode::Convert => Some(0x0079), + KeyCode::Lang1 => { + if is_korean { + Some(0xe0f2) + } else { + Some(0x0072) + } + }, + KeyCode::Lang2 => { + if is_korean { + Some(0xe0f1) + } else { + Some(0x0071) + } + }, + KeyCode::KanaMode => Some(0x0070), + KeyCode::NonConvert => Some(0x007b), + KeyCode::Delete => Some(0xe053), + KeyCode::End => Some(0xe04f), + KeyCode::Home => Some(0xe047), + KeyCode::Insert => Some(0xe052), + KeyCode::PageDown => Some(0xe051), + KeyCode::PageUp => Some(0xe049), + KeyCode::ArrowDown => Some(0xe050), + KeyCode::ArrowLeft => Some(0xe04b), + KeyCode::ArrowRight => Some(0xe04d), + KeyCode::ArrowUp => Some(0xe048), + KeyCode::NumLock => Some(0xe045), + KeyCode::Numpad0 => Some(0x0052), + KeyCode::Numpad1 => Some(0x004f), + KeyCode::Numpad2 => Some(0x0050), + KeyCode::Numpad3 => Some(0x0051), + KeyCode::Numpad4 => Some(0x004b), + KeyCode::Numpad5 => Some(0x004c), + KeyCode::Numpad6 => Some(0x004d), + KeyCode::Numpad7 => Some(0x0047), + KeyCode::Numpad8 => Some(0x0048), + KeyCode::Numpad9 => Some(0x0049), + KeyCode::NumpadAdd => Some(0x004e), + KeyCode::NumpadComma => Some(0x007e), + KeyCode::NumpadDecimal => Some(0x0053), + KeyCode::NumpadDivide => Some(0xe035), + KeyCode::NumpadEnter => Some(0xe01c), + KeyCode::NumpadEqual => Some(0x0059), + KeyCode::NumpadMultiply => Some(0x0037), + KeyCode::NumpadSubtract => Some(0x004a), + KeyCode::Escape => Some(0x0001), + KeyCode::F1 => Some(0x003b), + KeyCode::F2 => Some(0x003c), + KeyCode::F3 => Some(0x003d), + KeyCode::F4 => Some(0x003e), + KeyCode::F5 => Some(0x003f), + KeyCode::F6 => Some(0x0040), + KeyCode::F7 => Some(0x0041), + KeyCode::F8 => Some(0x0042), + KeyCode::F9 => Some(0x0043), + KeyCode::F10 => Some(0x0044), + KeyCode::F11 => Some(0x0057), + KeyCode::F12 => Some(0x0058), + KeyCode::F13 => Some(0x0064), + KeyCode::F14 => Some(0x0065), + KeyCode::F15 => Some(0x0066), + KeyCode::F16 => Some(0x0067), + KeyCode::F17 => Some(0x0068), + KeyCode::F18 => Some(0x0069), + KeyCode::F19 => Some(0x006a), + KeyCode::F20 => Some(0x006b), + KeyCode::F21 => Some(0x006c), + KeyCode::F22 => Some(0x006d), + KeyCode::F23 => Some(0x006e), + KeyCode::F24 => Some(0x0076), + KeyCode::PrintScreen => Some(0xe037), + // KeyCode::PrintScreen => Some(0x0054), // Alt + PrintScreen + KeyCode::ScrollLock => Some(0x0046), + KeyCode::Pause => Some(0x0045), + // KeyCode::Pause => Some(0xE046), // Ctrl + Pause + KeyCode::BrowserBack => Some(0xe06a), + KeyCode::BrowserFavorites => Some(0xe066), + KeyCode::BrowserForward => Some(0xe069), + KeyCode::BrowserHome => Some(0xe032), + KeyCode::BrowserRefresh => Some(0xe067), + KeyCode::BrowserSearch => Some(0xe065), + KeyCode::BrowserStop => Some(0xe068), + KeyCode::LaunchApp1 => Some(0xe06b), + KeyCode::LaunchApp2 => Some(0xe021), + KeyCode::LaunchMail => Some(0xe06c), + KeyCode::MediaPlayPause => Some(0xe022), + KeyCode::MediaSelect => Some(0xe06d), + KeyCode::MediaStop => Some(0xe024), + KeyCode::MediaTrackNext => Some(0xe019), + KeyCode::MediaTrackPrevious => Some(0xe010), + KeyCode::Power => Some(0xe05e), + KeyCode::AudioVolumeDown => Some(0xe02e), + KeyCode::AudioVolumeMute => Some(0xe020), + KeyCode::AudioVolumeUp => Some(0xe030), + _ => None, + } +} + +pub(crate) fn scancode_to_physicalkey(scancode: u32) -> PhysicalKey { + // See: https://www.win.tue.nl/~aeb/linux/kbd/scancodes-1.html + // and: https://www.w3.org/TR/uievents-code/ + // and: The widget/NativeKeyToDOMCodeName.h file in the firefox source + + PhysicalKey::Code(match scancode { + 0x0029 => KeyCode::Backquote, + 0x002b => KeyCode::Backslash, + 0x000e => KeyCode::Backspace, + 0x001a => KeyCode::BracketLeft, + 0x001b => KeyCode::BracketRight, + 0x0033 => KeyCode::Comma, + 0x000b => KeyCode::Digit0, + 0x0002 => KeyCode::Digit1, + 0x0003 => KeyCode::Digit2, + 0x0004 => KeyCode::Digit3, + 0x0005 => KeyCode::Digit4, + 0x0006 => KeyCode::Digit5, + 0x0007 => KeyCode::Digit6, + 0x0008 => KeyCode::Digit7, + 0x0009 => KeyCode::Digit8, + 0x000a => KeyCode::Digit9, + 0x000d => KeyCode::Equal, + 0x0056 => KeyCode::IntlBackslash, + 0x0073 => KeyCode::IntlRo, + 0x007d => KeyCode::IntlYen, + 0x001e => KeyCode::KeyA, + 0x0030 => KeyCode::KeyB, + 0x002e => KeyCode::KeyC, + 0x0020 => KeyCode::KeyD, + 0x0012 => KeyCode::KeyE, + 0x0021 => KeyCode::KeyF, + 0x0022 => KeyCode::KeyG, + 0x0023 => KeyCode::KeyH, + 0x0017 => KeyCode::KeyI, + 0x0024 => KeyCode::KeyJ, + 0x0025 => KeyCode::KeyK, + 0x0026 => KeyCode::KeyL, + 0x0032 => KeyCode::KeyM, + 0x0031 => KeyCode::KeyN, + 0x0018 => KeyCode::KeyO, + 0x0019 => KeyCode::KeyP, + 0x0010 => KeyCode::KeyQ, + 0x0013 => KeyCode::KeyR, + 0x001f => KeyCode::KeyS, + 0x0014 => KeyCode::KeyT, + 0x0016 => KeyCode::KeyU, + 0x002f => KeyCode::KeyV, + 0x0011 => KeyCode::KeyW, + 0x002d => KeyCode::KeyX, + 0x0015 => KeyCode::KeyY, + 0x002c => KeyCode::KeyZ, + 0x000c => KeyCode::Minus, + 0x0034 => KeyCode::Period, + 0x0028 => KeyCode::Quote, + 0x0027 => KeyCode::Semicolon, + 0x0035 => KeyCode::Slash, + 0x0038 => KeyCode::AltLeft, + 0xe038 => KeyCode::AltRight, + 0x003a => KeyCode::CapsLock, + 0xe05d => KeyCode::ContextMenu, + 0x001d => KeyCode::ControlLeft, + 0xe01d => KeyCode::ControlRight, + 0x001c => KeyCode::Enter, + 0xe05b => KeyCode::SuperLeft, + 0xe05c => KeyCode::SuperRight, + 0x002a => KeyCode::ShiftLeft, + 0x0036 => KeyCode::ShiftRight, + 0x0039 => KeyCode::Space, + 0x000f => KeyCode::Tab, + 0x0079 => KeyCode::Convert, + 0x0072 => KeyCode::Lang1, // for non-Korean layout + 0xe0f2 => KeyCode::Lang1, // for Korean layout + 0x0071 => KeyCode::Lang2, // for non-Korean layout + 0xe0f1 => KeyCode::Lang2, // for Korean layout + 0x0070 => KeyCode::KanaMode, + 0x007b => KeyCode::NonConvert, + 0xe053 => KeyCode::Delete, + 0xe04f => KeyCode::End, + 0xe047 => KeyCode::Home, + 0xe052 => KeyCode::Insert, + 0xe051 => KeyCode::PageDown, + 0xe049 => KeyCode::PageUp, + 0xe050 => KeyCode::ArrowDown, + 0xe04b => KeyCode::ArrowLeft, + 0xe04d => KeyCode::ArrowRight, + 0xe048 => KeyCode::ArrowUp, + 0xe045 => KeyCode::NumLock, + 0x0052 => KeyCode::Numpad0, + 0x004f => KeyCode::Numpad1, + 0x0050 => KeyCode::Numpad2, + 0x0051 => KeyCode::Numpad3, + 0x004b => KeyCode::Numpad4, + 0x004c => KeyCode::Numpad5, + 0x004d => KeyCode::Numpad6, + 0x0047 => KeyCode::Numpad7, + 0x0048 => KeyCode::Numpad8, + 0x0049 => KeyCode::Numpad9, + 0x004e => KeyCode::NumpadAdd, + 0x007e => KeyCode::NumpadComma, + 0x0053 => KeyCode::NumpadDecimal, + 0xe035 => KeyCode::NumpadDivide, + 0xe01c => KeyCode::NumpadEnter, + 0x0059 => KeyCode::NumpadEqual, + 0x0037 => KeyCode::NumpadMultiply, + 0x004a => KeyCode::NumpadSubtract, + 0x0001 => KeyCode::Escape, + 0x003b => KeyCode::F1, + 0x003c => KeyCode::F2, + 0x003d => KeyCode::F3, + 0x003e => KeyCode::F4, + 0x003f => KeyCode::F5, + 0x0040 => KeyCode::F6, + 0x0041 => KeyCode::F7, + 0x0042 => KeyCode::F8, + 0x0043 => KeyCode::F9, + 0x0044 => KeyCode::F10, + 0x0057 => KeyCode::F11, + 0x0058 => KeyCode::F12, + 0x0064 => KeyCode::F13, + 0x0065 => KeyCode::F14, + 0x0066 => KeyCode::F15, + 0x0067 => KeyCode::F16, + 0x0068 => KeyCode::F17, + 0x0069 => KeyCode::F18, + 0x006a => KeyCode::F19, + 0x006b => KeyCode::F20, + 0x006c => KeyCode::F21, + 0x006d => KeyCode::F22, + 0x006e => KeyCode::F23, + 0x0076 => KeyCode::F24, + 0xe037 => KeyCode::PrintScreen, + 0x0054 => KeyCode::PrintScreen, // Alt + PrintScreen + 0x0046 => KeyCode::ScrollLock, + 0x0045 => KeyCode::Pause, + 0xe046 => KeyCode::Pause, // Ctrl + Pause + 0xe06a => KeyCode::BrowserBack, + 0xe066 => KeyCode::BrowserFavorites, + 0xe069 => KeyCode::BrowserForward, + 0xe032 => KeyCode::BrowserHome, + 0xe067 => KeyCode::BrowserRefresh, + 0xe065 => KeyCode::BrowserSearch, + 0xe068 => KeyCode::BrowserStop, + 0xe06b => KeyCode::LaunchApp1, + 0xe021 => KeyCode::LaunchApp2, + 0xe06c => KeyCode::LaunchMail, + 0xe022 => KeyCode::MediaPlayPause, + 0xe06d => KeyCode::MediaSelect, + 0xe024 => KeyCode::MediaStop, + 0xe019 => KeyCode::MediaTrackNext, + 0xe010 => KeyCode::MediaTrackPrevious, + 0xe05e => KeyCode::Power, + 0xe02e => KeyCode::AudioVolumeDown, + 0xe020 => KeyCode::AudioVolumeMute, + 0xe030 => KeyCode::AudioVolumeUp, + _ => return PhysicalKey::Unidentified(NativeKeyCode::Windows(scancode as u16)), + }) +} diff --git a/app/vendor/rune/vendor/winit/src/platform_impl/windows/keyboard_layout.rs b/app/vendor/rune/vendor/winit/src/platform_impl/windows/keyboard_layout.rs new file mode 100644 index 0000000..6b4488b --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/platform_impl/windows/keyboard_layout.rs @@ -0,0 +1,998 @@ +use std::collections::hash_map::Entry; +use std::collections::{HashMap, HashSet}; +use std::ffi::OsString; +use std::os::windows::ffi::OsStringExt; +use std::sync::Mutex; + +use crate::utils::Lazy; +use smol_str::SmolStr; +use windows_sys::Win32::System::SystemServices::{LANG_JAPANESE, LANG_KOREAN}; +use windows_sys::Win32::UI::Input::KeyboardAndMouse::{ + GetKeyState, GetKeyboardLayout, MapVirtualKeyExW, ToUnicodeEx, MAPVK_VK_TO_VSC_EX, VIRTUAL_KEY, + VK_ACCEPT, VK_ADD, VK_APPS, VK_ATTN, VK_BACK, VK_BROWSER_BACK, VK_BROWSER_FAVORITES, + VK_BROWSER_FORWARD, VK_BROWSER_HOME, VK_BROWSER_REFRESH, VK_BROWSER_SEARCH, VK_BROWSER_STOP, + VK_CANCEL, VK_CAPITAL, VK_CLEAR, VK_CONTROL, VK_CONVERT, VK_CRSEL, VK_DECIMAL, VK_DELETE, + VK_DIVIDE, VK_DOWN, VK_END, VK_EREOF, VK_ESCAPE, VK_EXECUTE, VK_EXSEL, VK_F1, VK_F10, VK_F11, + VK_F12, VK_F13, VK_F14, VK_F15, VK_F16, VK_F17, VK_F18, VK_F19, VK_F2, VK_F20, VK_F21, VK_F22, + VK_F23, VK_F24, VK_F3, VK_F4, VK_F5, VK_F6, VK_F7, VK_F8, VK_F9, VK_FINAL, VK_GAMEPAD_A, + VK_GAMEPAD_B, VK_GAMEPAD_DPAD_DOWN, VK_GAMEPAD_DPAD_LEFT, VK_GAMEPAD_DPAD_RIGHT, + VK_GAMEPAD_DPAD_UP, VK_GAMEPAD_LEFT_SHOULDER, VK_GAMEPAD_LEFT_THUMBSTICK_BUTTON, + VK_GAMEPAD_LEFT_THUMBSTICK_DOWN, VK_GAMEPAD_LEFT_THUMBSTICK_LEFT, + VK_GAMEPAD_LEFT_THUMBSTICK_RIGHT, VK_GAMEPAD_LEFT_THUMBSTICK_UP, VK_GAMEPAD_LEFT_TRIGGER, + VK_GAMEPAD_MENU, VK_GAMEPAD_RIGHT_SHOULDER, VK_GAMEPAD_RIGHT_THUMBSTICK_BUTTON, + VK_GAMEPAD_RIGHT_THUMBSTICK_DOWN, VK_GAMEPAD_RIGHT_THUMBSTICK_LEFT, + VK_GAMEPAD_RIGHT_THUMBSTICK_RIGHT, VK_GAMEPAD_RIGHT_THUMBSTICK_UP, VK_GAMEPAD_RIGHT_TRIGGER, + VK_GAMEPAD_VIEW, VK_GAMEPAD_X, VK_GAMEPAD_Y, VK_HANGUL, VK_HANJA, VK_HELP, VK_HOME, VK_ICO_00, + VK_ICO_CLEAR, VK_ICO_HELP, VK_INSERT, VK_JUNJA, VK_KANA, VK_KANJI, VK_LAUNCH_APP1, + VK_LAUNCH_APP2, VK_LAUNCH_MAIL, VK_LAUNCH_MEDIA_SELECT, VK_LBUTTON, VK_LCONTROL, VK_LEFT, + VK_LMENU, VK_LSHIFT, VK_LWIN, VK_MBUTTON, VK_MEDIA_NEXT_TRACK, VK_MEDIA_PLAY_PAUSE, + VK_MEDIA_PREV_TRACK, VK_MEDIA_STOP, VK_MENU, VK_MODECHANGE, VK_MULTIPLY, VK_NAVIGATION_ACCEPT, + VK_NAVIGATION_CANCEL, VK_NAVIGATION_DOWN, VK_NAVIGATION_LEFT, VK_NAVIGATION_MENU, + VK_NAVIGATION_RIGHT, VK_NAVIGATION_UP, VK_NAVIGATION_VIEW, VK_NEXT, VK_NONAME, VK_NONCONVERT, + VK_NUMLOCK, VK_NUMPAD0, VK_NUMPAD1, VK_NUMPAD2, VK_NUMPAD3, VK_NUMPAD4, VK_NUMPAD5, VK_NUMPAD6, + VK_NUMPAD7, VK_NUMPAD8, VK_NUMPAD9, VK_OEM_1, VK_OEM_102, VK_OEM_2, VK_OEM_3, VK_OEM_4, + VK_OEM_5, VK_OEM_6, VK_OEM_7, VK_OEM_8, VK_OEM_ATTN, VK_OEM_AUTO, VK_OEM_AX, VK_OEM_BACKTAB, + VK_OEM_CLEAR, VK_OEM_COMMA, VK_OEM_COPY, VK_OEM_CUSEL, VK_OEM_ENLW, VK_OEM_FINISH, + VK_OEM_FJ_LOYA, VK_OEM_FJ_MASSHOU, VK_OEM_FJ_ROYA, VK_OEM_FJ_TOUROKU, VK_OEM_JUMP, + VK_OEM_MINUS, VK_OEM_NEC_EQUAL, VK_OEM_PA1, VK_OEM_PA2, VK_OEM_PA3, VK_OEM_PERIOD, VK_OEM_PLUS, + VK_OEM_RESET, VK_OEM_WSCTRL, VK_PA1, VK_PACKET, VK_PAUSE, VK_PLAY, VK_PRINT, VK_PRIOR, + VK_PROCESSKEY, VK_RBUTTON, VK_RCONTROL, VK_RETURN, VK_RIGHT, VK_RMENU, VK_RSHIFT, VK_RWIN, + VK_SCROLL, VK_SELECT, VK_SEPARATOR, VK_SHIFT, VK_SLEEP, VK_SNAPSHOT, VK_SPACE, VK_SUBTRACT, + VK_TAB, VK_UP, VK_VOLUME_DOWN, VK_VOLUME_MUTE, VK_VOLUME_UP, VK_XBUTTON1, VK_XBUTTON2, VK_ZOOM, +}; +use windows_sys::Win32::UI::TextServices::HKL; + +use crate::keyboard::{Key, KeyCode, ModifiersState, NamedKey, NativeKey, PhysicalKey}; +use crate::platform_impl::{loword, primarylangid, scancode_to_physicalkey}; + +pub(crate) static LAYOUT_CACHE: Lazy<Mutex<LayoutCache>> = + Lazy::new(|| Mutex::new(LayoutCache::default())); + +/// Builds the layout cache's entry for the keyboard layout of thread `thread`, on the calling +/// thread. The first key or mouse message a window's thread handles builds it otherwise (every +/// virtual key through `ToUnicodeEx`, 8-10 ms), so a window's first input waited for it. +pub(crate) fn warm_layout(thread: u32) { + let hkl = unsafe { GetKeyboardLayout(thread) } as u64; + if LAYOUT_CACHE.lock().unwrap().layouts.contains_key(&hkl) { + return; + } + let layout = LayoutCache::prepare_layout(hkl); + LAYOUT_CACHE.lock().unwrap().layouts.entry(hkl).or_insert(layout); +} + +fn key_pressed(vkey: VIRTUAL_KEY) -> bool { + unsafe { (GetKeyState(vkey as i32) & (1 << 15)) == (1 << 15) } +} + +const NUMPAD_VKEYS: [VIRTUAL_KEY; 16] = [ + VK_NUMPAD0, + VK_NUMPAD1, + VK_NUMPAD2, + VK_NUMPAD3, + VK_NUMPAD4, + VK_NUMPAD5, + VK_NUMPAD6, + VK_NUMPAD7, + VK_NUMPAD8, + VK_NUMPAD9, + VK_MULTIPLY, + VK_ADD, + VK_SEPARATOR, + VK_SUBTRACT, + VK_DECIMAL, + VK_DIVIDE, +]; + +static NUMPAD_KEYCODES: Lazy<HashSet<KeyCode>> = Lazy::new(|| { + let mut keycodes = HashSet::new(); + keycodes.insert(KeyCode::Numpad0); + keycodes.insert(KeyCode::Numpad1); + keycodes.insert(KeyCode::Numpad2); + keycodes.insert(KeyCode::Numpad3); + keycodes.insert(KeyCode::Numpad4); + keycodes.insert(KeyCode::Numpad5); + keycodes.insert(KeyCode::Numpad6); + keycodes.insert(KeyCode::Numpad7); + keycodes.insert(KeyCode::Numpad8); + keycodes.insert(KeyCode::Numpad9); + keycodes.insert(KeyCode::NumpadMultiply); + keycodes.insert(KeyCode::NumpadAdd); + keycodes.insert(KeyCode::NumpadComma); + keycodes.insert(KeyCode::NumpadSubtract); + keycodes.insert(KeyCode::NumpadDecimal); + keycodes.insert(KeyCode::NumpadDivide); + keycodes +}); + +bitflags::bitflags! { + #[derive(Clone, Copy, PartialEq, Eq, Hash)] + pub struct WindowsModifiers : u8 { + const SHIFT = 1 << 0; + const CONTROL = 1 << 1; + const ALT = 1 << 2; + const CAPS_LOCK = 1 << 3; + const FLAGS_END = 1 << 4; + } +} + +impl WindowsModifiers { + pub fn active_modifiers(key_state: &[u8; 256]) -> WindowsModifiers { + let shift = key_state[VK_SHIFT as usize] & 0x80 != 0; + let lshift = key_state[VK_LSHIFT as usize] & 0x80 != 0; + let rshift = key_state[VK_RSHIFT as usize] & 0x80 != 0; + + let control = key_state[VK_CONTROL as usize] & 0x80 != 0; + let lcontrol = key_state[VK_LCONTROL as usize] & 0x80 != 0; + let rcontrol = key_state[VK_RCONTROL as usize] & 0x80 != 0; + + let alt = key_state[VK_MENU as usize] & 0x80 != 0; + let lalt = key_state[VK_LMENU as usize] & 0x80 != 0; + let ralt = key_state[VK_RMENU as usize] & 0x80 != 0; + + let caps = key_state[VK_CAPITAL as usize] & 0x01 != 0; + + let mut result = WindowsModifiers::empty(); + if shift || lshift || rshift { + result.insert(WindowsModifiers::SHIFT); + } + if control || lcontrol || rcontrol { + result.insert(WindowsModifiers::CONTROL); + } + if alt || lalt || ralt { + result.insert(WindowsModifiers::ALT); + } + if caps { + result.insert(WindowsModifiers::CAPS_LOCK); + } + + result + } + + pub fn apply_to_kbd_state(self, key_state: &mut [u8; 256]) { + if self.intersects(Self::SHIFT) { + key_state[VK_SHIFT as usize] |= 0x80; + } else { + key_state[VK_SHIFT as usize] &= !0x80; + key_state[VK_LSHIFT as usize] &= !0x80; + key_state[VK_RSHIFT as usize] &= !0x80; + } + if self.intersects(Self::CONTROL) { + key_state[VK_CONTROL as usize] |= 0x80; + } else { + key_state[VK_CONTROL as usize] &= !0x80; + key_state[VK_LCONTROL as usize] &= !0x80; + key_state[VK_RCONTROL as usize] &= !0x80; + } + if self.intersects(Self::ALT) { + key_state[VK_MENU as usize] |= 0x80; + } else { + key_state[VK_MENU as usize] &= !0x80; + key_state[VK_LMENU as usize] &= !0x80; + key_state[VK_RMENU as usize] &= !0x80; + } + if self.intersects(Self::CAPS_LOCK) { + key_state[VK_CAPITAL as usize] |= 0x01; + } else { + key_state[VK_CAPITAL as usize] &= !0x01; + } + } + + /// Removes the control modifier if the alt modifier is not present. + /// This is useful because on Windows: (Control + Alt) == AltGr + /// but we don't want to interfere with the AltGr state. + pub fn remove_only_ctrl(mut self) -> WindowsModifiers { + if !self.contains(WindowsModifiers::ALT) { + self.remove(WindowsModifiers::CONTROL); + } + self + } +} + +pub(crate) struct Layout { + pub hkl: u64, + + /// Maps numpad keys from Windows virtual key to a `Key`. + /// + /// This is useful because some numpad keys generate different characters based on the locale. + /// For example `VK_DECIMAL` is sometimes "." and sometimes ",". Note: numpad-specific virtual + /// keys are only produced by Windows when the NumLock is active. + /// + /// Making this field separate from the `keys` field saves having to add NumLock as a modifier + /// to `WindowsModifiers`, which would double the number of items in keys. + pub numlock_on_keys: HashMap<VIRTUAL_KEY, Key>, + /// Like `numlock_on_keys` but this will map to the key that would be produced if numlock was + /// off. The keys of this map are identical to the keys of `numlock_on_keys`. + pub numlock_off_keys: HashMap<VIRTUAL_KEY, Key>, + + /// Maps a modifier state to group of key strings + /// We're not using `ModifiersState` here because that object cannot express caps lock, + /// but we need to handle caps lock too. + /// + /// This map shouldn't need to exist. + /// However currently this seems to be the only good way + /// of getting the label for the pressed key. Note that calling `ToUnicode` + /// just when the key is pressed/released would be enough if `ToUnicode` wouldn't + /// change the keyboard state (it clears the dead key). There is a flag to prevent + /// changing the state, but that flag requires Windows 10, version 1607 or newer) + pub keys: HashMap<WindowsModifiers, HashMap<KeyCode, Key>>, + pub has_alt_graph: bool, +} + +impl Layout { + pub fn get_key( + &self, + mods: WindowsModifiers, + num_lock_on: bool, + vkey: VIRTUAL_KEY, + physical_key: &PhysicalKey, + ) -> Key { + let native_code = NativeKey::Windows(vkey); + + let unknown_alt = vkey == VK_MENU; + if !unknown_alt { + // Here we try using the virtual key directly but if the virtual key doesn't distinguish + // between left and right alt, we can't report AltGr. Therefore, we only do this if the + // key is not the "unknown alt" key. + // + // The reason for using the virtual key directly is that `MapVirtualKeyExW` (used when + // building the keys map) sometimes maps virtual keys to odd scancodes that don't match + // the scancode coming from the KEYDOWN message for the same key. For example: `VK_LEFT` + // is mapped to `0x004B`, but the scancode for the left arrow is `0xE04B`. + let key_from_vkey = + vkey_to_non_char_key(vkey, native_code.clone(), self.hkl, self.has_alt_graph); + + if !matches!(key_from_vkey, Key::Unidentified(_)) { + return key_from_vkey; + } + } + if num_lock_on { + if let Some(key) = self.numlock_on_keys.get(&vkey) { + return key.clone(); + } + } else if let Some(key) = self.numlock_off_keys.get(&vkey) { + return key.clone(); + } + if let PhysicalKey::Code(code) = physical_key { + if let Some(keys) = self.keys.get(&mods) { + if let Some(key) = keys.get(code) { + return key.clone(); + } + } + } + Key::Unidentified(native_code) + } +} + +#[derive(Default)] +pub(crate) struct LayoutCache { + /// Maps locale identifiers (HKL) to layouts + pub layouts: HashMap<u64, Layout>, +} + +impl LayoutCache { + /// Checks whether the current layout is already known and + /// prepares the layout if it isn't known. + /// The current layout is then returned. + pub fn get_current_layout(&mut self) -> (u64, &Layout) { + let locale_id = unsafe { GetKeyboardLayout(0) } as u64; + match self.layouts.entry(locale_id) { + Entry::Occupied(entry) => (locale_id, entry.into_mut()), + Entry::Vacant(entry) => { + let layout = Self::prepare_layout(locale_id); + (locale_id, entry.insert(layout)) + }, + } + } + + pub fn get_agnostic_mods(&mut self) -> ModifiersState { + let (_, layout) = self.get_current_layout(); + let filter_out_altgr = layout.has_alt_graph && key_pressed(VK_RMENU); + let mut mods = ModifiersState::empty(); + mods.set(ModifiersState::SHIFT, key_pressed(VK_SHIFT)); + mods.set(ModifiersState::CONTROL, key_pressed(VK_CONTROL) && !filter_out_altgr); + mods.set(ModifiersState::ALT, key_pressed(VK_MENU) && !filter_out_altgr); + mods.set(ModifiersState::SUPER, key_pressed(VK_LWIN) || key_pressed(VK_RWIN)); + mods + } + + fn prepare_layout(locale_id: u64) -> Layout { + let mut layout = Layout { + hkl: locale_id, + numlock_on_keys: Default::default(), + numlock_off_keys: Default::default(), + keys: Default::default(), + has_alt_graph: false, + }; + + // We initialize the keyboard state with all zeros to + // simulate a scenario when no modifier is active. + let mut key_state = [0u8; 256]; + + // `MapVirtualKeyExW` maps (non-numpad-specific) virtual keys to scancodes as if numlock + // was off. We rely on this behavior to find all virtual keys which are not numpad-specific + // but map to the numpad. + // + // src_vkey: VK ==> scancode: u16 (on the numpad) + // + // Then we convert the source virtual key into a `Key` and the scancode into a virtual key + // to get the reverse mapping. + // + // src_vkey: VK ==> scancode: u16 (on the numpad) + // || || + // \/ \/ + // map_value: Key <- map_vkey: VK + layout.numlock_off_keys.reserve(NUMPAD_KEYCODES.len()); + for vk in 0..256 { + let scancode = unsafe { MapVirtualKeyExW(vk, MAPVK_VK_TO_VSC_EX, locale_id as HKL) }; + if scancode == 0 { + continue; + } + let keycode = match scancode_to_physicalkey(scancode) { + PhysicalKey::Code(code) => code, + // TODO: validate that we can skip on unidentified keys (probably never occurs?) + _ => continue, + }; + if !is_numpad_specific(vk as VIRTUAL_KEY) && NUMPAD_KEYCODES.contains(&keycode) { + let native_code = NativeKey::Windows(vk as VIRTUAL_KEY); + let map_vkey = keycode_to_vkey(keycode, locale_id); + if map_vkey == 0 { + continue; + } + let map_value = + vkey_to_non_char_key(vk as VIRTUAL_KEY, native_code, locale_id, false); + if matches!(map_value, Key::Unidentified(_)) { + continue; + } + layout.numlock_off_keys.insert(map_vkey, map_value); + } + } + + layout.numlock_on_keys.reserve(NUMPAD_VKEYS.len()); + for vk in NUMPAD_VKEYS.iter() { + let vk = (*vk) as u32; + let scancode = unsafe { MapVirtualKeyExW(vk, MAPVK_VK_TO_VSC_EX, locale_id as HKL) }; + let unicode = Self::to_unicode_string(&key_state, vk, scancode, locale_id); + if let ToUnicodeResult::Str(s) = unicode { + layout.numlock_on_keys.insert(vk as VIRTUAL_KEY, Key::Character(SmolStr::new(s))); + } + } + + // Iterate through every combination of modifiers + let mods_end = WindowsModifiers::FLAGS_END.bits(); + for mod_state in 0..mods_end { + let mut keys_for_this_mod = HashMap::with_capacity(256); + + let mod_state = WindowsModifiers::from_bits_retain(mod_state); + mod_state.apply_to_kbd_state(&mut key_state); + + // Virtual key values are in the domain [0, 255]. + // This is reinforced by the fact that the keyboard state array has 256 + // elements. This array is allowed to be indexed by virtual key values + // giving the key state for the virtual key used for indexing. + for vk in 0..256 { + let scancode = + unsafe { MapVirtualKeyExW(vk, MAPVK_VK_TO_VSC_EX, locale_id as HKL) }; + if scancode == 0 { + continue; + } + + let native_code = NativeKey::Windows(vk as VIRTUAL_KEY); + let key_code = match scancode_to_physicalkey(scancode) { + PhysicalKey::Code(code) => code, + // TODO: validate that we can skip on unidentified keys (probably never occurs?) + _ => continue, + }; + // Let's try to get the key from just the scancode and vk + // We don't necessarily know yet if AltGraph is present on this layout so we'll + // assume it isn't. Then we'll do a second pass where we set the "AltRight" keys to + // "AltGr" in case we find out that there's an AltGraph. + let preliminary_key = + vkey_to_non_char_key(vk as VIRTUAL_KEY, native_code, locale_id, false); + match preliminary_key { + Key::Unidentified(_) => (), + _ => { + keys_for_this_mod.insert(key_code, preliminary_key); + continue; + }, + } + + let unicode = Self::to_unicode_string(&key_state, vk, scancode, locale_id); + let key = match unicode { + ToUnicodeResult::Str(str) => Key::Character(SmolStr::new(str)), + ToUnicodeResult::Dead(dead_char) => { + // println!("{:?} - {:?} produced dead {:?}", key_code, mod_state, + // dead_char); + Key::Dead(dead_char) + }, + ToUnicodeResult::None => { + let has_alt = mod_state.contains(WindowsModifiers::ALT); + let has_ctrl = mod_state.contains(WindowsModifiers::CONTROL); + // HACK: `ToUnicodeEx` seems to fail getting the string for the numpad + // divide key, so we handle that explicitly here + if !has_alt && !has_ctrl && key_code == KeyCode::NumpadDivide { + Key::Character(SmolStr::new("/")) + } else { + // Just use the unidentified key, we got earlier + preliminary_key + } + }, + }; + + // Check for alt graph. + // The logic is that if a key pressed with no modifier produces + // a different `Character` from when it's pressed with CTRL+ALT then the layout + // has AltGr. + let ctrl_alt: WindowsModifiers = WindowsModifiers::CONTROL | WindowsModifiers::ALT; + let is_in_ctrl_alt = mod_state == ctrl_alt; + if !layout.has_alt_graph && is_in_ctrl_alt { + // Unwrapping here because if we are in the ctrl+alt modifier state + // then the alt modifier state must have come before. + let simple_keys = layout.keys.get(&WindowsModifiers::empty()).unwrap(); + if let Some(Key::Character(key_no_altgr)) = simple_keys.get(&key_code) { + if let Key::Character(key) = &key { + layout.has_alt_graph = key != key_no_altgr; + } + } + } + + keys_for_this_mod.insert(key_code, key); + } + layout.keys.insert(mod_state, keys_for_this_mod); + } + + // Second pass: replace right alt keys with AltGr if the layout has alt graph + if layout.has_alt_graph { + for mod_state in 0..mods_end { + let mod_state = WindowsModifiers::from_bits_retain(mod_state); + if let Some(keys) = layout.keys.get_mut(&mod_state) { + if let Some(key) = keys.get_mut(&KeyCode::AltRight) { + *key = Key::Named(NamedKey::AltGraph); + } + } + } + } + + layout + } + + fn to_unicode_string( + key_state: &[u8; 256], + vkey: u32, + scancode: u32, + locale_id: u64, + ) -> ToUnicodeResult { + unsafe { + let mut label_wide = [0u16; 8]; + let mut wide_len = ToUnicodeEx( + vkey, + scancode, + (&key_state[0]) as *const _, + (&mut label_wide[0]) as *mut _, + label_wide.len() as i32, + 0, + locale_id as HKL, + ); + if wide_len < 0 { + // If it's dead, we run `ToUnicode` again to consume the dead-key + wide_len = ToUnicodeEx( + vkey, + scancode, + (&key_state[0]) as *const _, + (&mut label_wide[0]) as *mut _, + label_wide.len() as i32, + 0, + locale_id as HKL, + ); + if wide_len > 0 { + let os_string = OsString::from_wide(&label_wide[0..wide_len as usize]); + if let Ok(label_str) = os_string.into_string() { + if let Some(ch) = label_str.chars().next() { + return ToUnicodeResult::Dead(Some(ch)); + } + } + } + return ToUnicodeResult::Dead(None); + } + if wide_len > 0 { + let os_string = OsString::from_wide(&label_wide[0..wide_len as usize]); + if let Ok(label_str) = os_string.into_string() { + return ToUnicodeResult::Str(label_str); + } + } + } + ToUnicodeResult::None + } +} + +#[derive(Debug, Clone, Eq, PartialEq)] +enum ToUnicodeResult { + Str(String), + Dead(Option<char>), + None, +} + +fn is_numpad_specific(vk: VIRTUAL_KEY) -> bool { + matches!( + vk, + VK_NUMPAD0 + | VK_NUMPAD1 + | VK_NUMPAD2 + | VK_NUMPAD3 + | VK_NUMPAD4 + | VK_NUMPAD5 + | VK_NUMPAD6 + | VK_NUMPAD7 + | VK_NUMPAD8 + | VK_NUMPAD9 + | VK_ADD + | VK_SUBTRACT + | VK_DIVIDE + | VK_DECIMAL + | VK_SEPARATOR + ) +} + +fn keycode_to_vkey(keycode: KeyCode, hkl: u64) -> VIRTUAL_KEY { + let primary_lang_id = primarylangid(loword(hkl as u32)); + let is_korean = primary_lang_id as u32 == LANG_KOREAN; + let is_japanese = primary_lang_id as u32 == LANG_JAPANESE; + + match keycode { + KeyCode::Backquote => 0, + KeyCode::Backslash => 0, + KeyCode::BracketLeft => 0, + KeyCode::BracketRight => 0, + KeyCode::Comma => 0, + KeyCode::Digit0 => 0, + KeyCode::Digit1 => 0, + KeyCode::Digit2 => 0, + KeyCode::Digit3 => 0, + KeyCode::Digit4 => 0, + KeyCode::Digit5 => 0, + KeyCode::Digit6 => 0, + KeyCode::Digit7 => 0, + KeyCode::Digit8 => 0, + KeyCode::Digit9 => 0, + KeyCode::Equal => 0, + KeyCode::IntlBackslash => 0, + KeyCode::IntlRo => 0, + KeyCode::IntlYen => 0, + KeyCode::KeyA => 0, + KeyCode::KeyB => 0, + KeyCode::KeyC => 0, + KeyCode::KeyD => 0, + KeyCode::KeyE => 0, + KeyCode::KeyF => 0, + KeyCode::KeyG => 0, + KeyCode::KeyH => 0, + KeyCode::KeyI => 0, + KeyCode::KeyJ => 0, + KeyCode::KeyK => 0, + KeyCode::KeyL => 0, + KeyCode::KeyM => 0, + KeyCode::KeyN => 0, + KeyCode::KeyO => 0, + KeyCode::KeyP => 0, + KeyCode::KeyQ => 0, + KeyCode::KeyR => 0, + KeyCode::KeyS => 0, + KeyCode::KeyT => 0, + KeyCode::KeyU => 0, + KeyCode::KeyV => 0, + KeyCode::KeyW => 0, + KeyCode::KeyX => 0, + KeyCode::KeyY => 0, + KeyCode::KeyZ => 0, + KeyCode::Minus => 0, + KeyCode::Period => 0, + KeyCode::Quote => 0, + KeyCode::Semicolon => 0, + KeyCode::Slash => 0, + KeyCode::AltLeft => VK_LMENU, + KeyCode::AltRight => VK_RMENU, + KeyCode::Backspace => VK_BACK, + KeyCode::CapsLock => VK_CAPITAL, + KeyCode::ContextMenu => VK_APPS, + KeyCode::ControlLeft => VK_LCONTROL, + KeyCode::ControlRight => VK_RCONTROL, + KeyCode::Enter => VK_RETURN, + KeyCode::SuperLeft => VK_LWIN, + KeyCode::SuperRight => VK_RWIN, + KeyCode::ShiftLeft => VK_RSHIFT, + KeyCode::ShiftRight => VK_LSHIFT, + KeyCode::Space => VK_SPACE, + KeyCode::Tab => VK_TAB, + KeyCode::Convert => VK_CONVERT, + KeyCode::KanaMode => VK_KANA, + KeyCode::Lang1 if is_korean => VK_HANGUL, + KeyCode::Lang1 if is_japanese => VK_KANA, + KeyCode::Lang2 if is_korean => VK_HANJA, + KeyCode::Lang2 if is_japanese => 0, + KeyCode::Lang3 if is_japanese => VK_OEM_FINISH, + KeyCode::Lang4 if is_japanese => 0, + KeyCode::Lang5 if is_japanese => 0, + KeyCode::NonConvert => VK_NONCONVERT, + KeyCode::Delete => VK_DELETE, + KeyCode::End => VK_END, + KeyCode::Help => VK_HELP, + KeyCode::Home => VK_HOME, + KeyCode::Insert => VK_INSERT, + KeyCode::PageDown => VK_NEXT, + KeyCode::PageUp => VK_PRIOR, + KeyCode::ArrowDown => VK_DOWN, + KeyCode::ArrowLeft => VK_LEFT, + KeyCode::ArrowRight => VK_RIGHT, + KeyCode::ArrowUp => VK_UP, + KeyCode::NumLock => VK_NUMLOCK, + KeyCode::Numpad0 => VK_NUMPAD0, + KeyCode::Numpad1 => VK_NUMPAD1, + KeyCode::Numpad2 => VK_NUMPAD2, + KeyCode::Numpad3 => VK_NUMPAD3, + KeyCode::Numpad4 => VK_NUMPAD4, + KeyCode::Numpad5 => VK_NUMPAD5, + KeyCode::Numpad6 => VK_NUMPAD6, + KeyCode::Numpad7 => VK_NUMPAD7, + KeyCode::Numpad8 => VK_NUMPAD8, + KeyCode::Numpad9 => VK_NUMPAD9, + KeyCode::NumpadAdd => VK_ADD, + KeyCode::NumpadBackspace => VK_BACK, + KeyCode::NumpadClear => VK_CLEAR, + KeyCode::NumpadClearEntry => 0, + KeyCode::NumpadComma => VK_SEPARATOR, + KeyCode::NumpadDecimal => VK_DECIMAL, + KeyCode::NumpadDivide => VK_DIVIDE, + KeyCode::NumpadEnter => VK_RETURN, + KeyCode::NumpadEqual => 0, + KeyCode::NumpadHash => 0, + KeyCode::NumpadMemoryAdd => 0, + KeyCode::NumpadMemoryClear => 0, + KeyCode::NumpadMemoryRecall => 0, + KeyCode::NumpadMemoryStore => 0, + KeyCode::NumpadMemorySubtract => 0, + KeyCode::NumpadMultiply => VK_MULTIPLY, + KeyCode::NumpadParenLeft => 0, + KeyCode::NumpadParenRight => 0, + KeyCode::NumpadStar => 0, + KeyCode::NumpadSubtract => VK_SUBTRACT, + KeyCode::Escape => VK_ESCAPE, + KeyCode::Fn => 0, + KeyCode::FnLock => 0, + KeyCode::PrintScreen => VK_SNAPSHOT, + KeyCode::ScrollLock => VK_SCROLL, + KeyCode::Pause => VK_PAUSE, + KeyCode::BrowserBack => VK_BROWSER_BACK, + KeyCode::BrowserFavorites => VK_BROWSER_FAVORITES, + KeyCode::BrowserForward => VK_BROWSER_FORWARD, + KeyCode::BrowserHome => VK_BROWSER_HOME, + KeyCode::BrowserRefresh => VK_BROWSER_REFRESH, + KeyCode::BrowserSearch => VK_BROWSER_SEARCH, + KeyCode::BrowserStop => VK_BROWSER_STOP, + KeyCode::Eject => 0, + KeyCode::LaunchApp1 => VK_LAUNCH_APP1, + KeyCode::LaunchApp2 => VK_LAUNCH_APP2, + KeyCode::LaunchMail => VK_LAUNCH_MAIL, + KeyCode::MediaPlayPause => VK_MEDIA_PLAY_PAUSE, + KeyCode::MediaSelect => VK_LAUNCH_MEDIA_SELECT, + KeyCode::MediaStop => VK_MEDIA_STOP, + KeyCode::MediaTrackNext => VK_MEDIA_NEXT_TRACK, + KeyCode::MediaTrackPrevious => VK_MEDIA_PREV_TRACK, + KeyCode::Power => 0, + KeyCode::Sleep => 0, + KeyCode::AudioVolumeDown => VK_VOLUME_DOWN, + KeyCode::AudioVolumeMute => VK_VOLUME_MUTE, + KeyCode::AudioVolumeUp => VK_VOLUME_UP, + KeyCode::WakeUp => 0, + KeyCode::Hyper => 0, + KeyCode::Turbo => 0, + KeyCode::Abort => 0, + KeyCode::Resume => 0, + KeyCode::Suspend => 0, + KeyCode::Again => 0, + KeyCode::Copy => 0, + KeyCode::Cut => 0, + KeyCode::Find => 0, + KeyCode::Open => 0, + KeyCode::Paste => 0, + KeyCode::Props => 0, + KeyCode::Select => VK_SELECT, + KeyCode::Undo => 0, + KeyCode::Hiragana => 0, + KeyCode::Katakana => 0, + KeyCode::F1 => VK_F1, + KeyCode::F2 => VK_F2, + KeyCode::F3 => VK_F3, + KeyCode::F4 => VK_F4, + KeyCode::F5 => VK_F5, + KeyCode::F6 => VK_F6, + KeyCode::F7 => VK_F7, + KeyCode::F8 => VK_F8, + KeyCode::F9 => VK_F9, + KeyCode::F10 => VK_F10, + KeyCode::F11 => VK_F11, + KeyCode::F12 => VK_F12, + KeyCode::F13 => VK_F13, + KeyCode::F14 => VK_F14, + KeyCode::F15 => VK_F15, + KeyCode::F16 => VK_F16, + KeyCode::F17 => VK_F17, + KeyCode::F18 => VK_F18, + KeyCode::F19 => VK_F19, + KeyCode::F20 => VK_F20, + KeyCode::F21 => VK_F21, + KeyCode::F22 => VK_F22, + KeyCode::F23 => VK_F23, + KeyCode::F24 => VK_F24, + KeyCode::F25 => 0, + KeyCode::F26 => 0, + KeyCode::F27 => 0, + KeyCode::F28 => 0, + KeyCode::F29 => 0, + KeyCode::F30 => 0, + KeyCode::F31 => 0, + KeyCode::F32 => 0, + KeyCode::F33 => 0, + KeyCode::F34 => 0, + KeyCode::F35 => 0, + _ => 0, + } +} + +/// This converts virtual keys to `Key`s. Only virtual keys which can be unambiguously converted to +/// a `Key`, with only the information passed in as arguments, are converted. +/// +/// In other words: this function does not need to "prepare" the current layout in order to do +/// the conversion, but as such it cannot convert certain keys, like language-specific character +/// keys. +/// +/// The result includes all non-character keys defined within `Key` plus characters from numpad +/// keys. For example, backspace and tab are included. +fn vkey_to_non_char_key( + vkey: VIRTUAL_KEY, + native_code: NativeKey, + hkl: u64, + has_alt_graph: bool, +) -> Key { + // List of the Web key names and their corresponding platform-native key names: + // https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key/Key_Values + + let primary_lang_id = primarylangid(loword(hkl as u32)); + let is_korean = primary_lang_id as u32 == LANG_KOREAN; + let is_japanese = primary_lang_id as u32 == LANG_JAPANESE; + + match vkey { + VK_LBUTTON => Key::Unidentified(NativeKey::Unidentified), // Mouse + VK_RBUTTON => Key::Unidentified(NativeKey::Unidentified), // Mouse + + // I don't think this can be represented with a Key + VK_CANCEL => Key::Unidentified(native_code), + + VK_MBUTTON => Key::Unidentified(NativeKey::Unidentified), // Mouse + VK_XBUTTON1 => Key::Unidentified(NativeKey::Unidentified), // Mouse + VK_XBUTTON2 => Key::Unidentified(NativeKey::Unidentified), // Mouse + VK_BACK => Key::Named(NamedKey::Backspace), + VK_TAB => Key::Named(NamedKey::Tab), + VK_CLEAR => Key::Named(NamedKey::Clear), + VK_RETURN => Key::Named(NamedKey::Enter), + VK_SHIFT => Key::Named(NamedKey::Shift), + VK_CONTROL => Key::Named(NamedKey::Control), + VK_MENU => Key::Named(NamedKey::Alt), + VK_PAUSE => Key::Named(NamedKey::Pause), + VK_CAPITAL => Key::Named(NamedKey::CapsLock), + + // VK_HANGEUL => Key::Named(NamedKey::HangulMode), // Deprecated in favour of VK_HANGUL + + // VK_HANGUL and VK_KANA are defined as the same constant, therefore + // we use appropriate conditions to differentiate between them + VK_HANGUL if is_korean => Key::Named(NamedKey::HangulMode), + VK_KANA if is_japanese => Key::Named(NamedKey::KanaMode), + + VK_JUNJA => Key::Named(NamedKey::JunjaMode), + VK_FINAL => Key::Named(NamedKey::FinalMode), + + // VK_HANJA and VK_KANJI are defined as the same constant, therefore + // we use appropriate conditions to differentiate between them + VK_HANJA if is_korean => Key::Named(NamedKey::HanjaMode), + VK_KANJI if is_japanese => Key::Named(NamedKey::KanjiMode), + + VK_ESCAPE => Key::Named(NamedKey::Escape), + VK_CONVERT => Key::Named(NamedKey::Convert), + VK_NONCONVERT => Key::Named(NamedKey::NonConvert), + VK_ACCEPT => Key::Named(NamedKey::Accept), + VK_MODECHANGE => Key::Named(NamedKey::ModeChange), + VK_SPACE => Key::Named(NamedKey::Space), + VK_PRIOR => Key::Named(NamedKey::PageUp), + VK_NEXT => Key::Named(NamedKey::PageDown), + VK_END => Key::Named(NamedKey::End), + VK_HOME => Key::Named(NamedKey::Home), + VK_LEFT => Key::Named(NamedKey::ArrowLeft), + VK_UP => Key::Named(NamedKey::ArrowUp), + VK_RIGHT => Key::Named(NamedKey::ArrowRight), + VK_DOWN => Key::Named(NamedKey::ArrowDown), + VK_SELECT => Key::Named(NamedKey::Select), + VK_PRINT => Key::Named(NamedKey::Print), + VK_EXECUTE => Key::Named(NamedKey::Execute), + VK_SNAPSHOT => Key::Named(NamedKey::PrintScreen), + VK_INSERT => Key::Named(NamedKey::Insert), + VK_DELETE => Key::Named(NamedKey::Delete), + VK_HELP => Key::Named(NamedKey::Help), + VK_LWIN => Key::Named(NamedKey::Super), + VK_RWIN => Key::Named(NamedKey::Super), + VK_APPS => Key::Named(NamedKey::ContextMenu), + VK_SLEEP => Key::Named(NamedKey::Standby), + + // Numpad keys produce characters + VK_NUMPAD0 => Key::Unidentified(native_code), + VK_NUMPAD1 => Key::Unidentified(native_code), + VK_NUMPAD2 => Key::Unidentified(native_code), + VK_NUMPAD3 => Key::Unidentified(native_code), + VK_NUMPAD4 => Key::Unidentified(native_code), + VK_NUMPAD5 => Key::Unidentified(native_code), + VK_NUMPAD6 => Key::Unidentified(native_code), + VK_NUMPAD7 => Key::Unidentified(native_code), + VK_NUMPAD8 => Key::Unidentified(native_code), + VK_NUMPAD9 => Key::Unidentified(native_code), + VK_MULTIPLY => Key::Unidentified(native_code), + VK_ADD => Key::Unidentified(native_code), + VK_SEPARATOR => Key::Unidentified(native_code), + VK_SUBTRACT => Key::Unidentified(native_code), + VK_DECIMAL => Key::Unidentified(native_code), + VK_DIVIDE => Key::Unidentified(native_code), + + VK_F1 => Key::Named(NamedKey::F1), + VK_F2 => Key::Named(NamedKey::F2), + VK_F3 => Key::Named(NamedKey::F3), + VK_F4 => Key::Named(NamedKey::F4), + VK_F5 => Key::Named(NamedKey::F5), + VK_F6 => Key::Named(NamedKey::F6), + VK_F7 => Key::Named(NamedKey::F7), + VK_F8 => Key::Named(NamedKey::F8), + VK_F9 => Key::Named(NamedKey::F9), + VK_F10 => Key::Named(NamedKey::F10), + VK_F11 => Key::Named(NamedKey::F11), + VK_F12 => Key::Named(NamedKey::F12), + VK_F13 => Key::Named(NamedKey::F13), + VK_F14 => Key::Named(NamedKey::F14), + VK_F15 => Key::Named(NamedKey::F15), + VK_F16 => Key::Named(NamedKey::F16), + VK_F17 => Key::Named(NamedKey::F17), + VK_F18 => Key::Named(NamedKey::F18), + VK_F19 => Key::Named(NamedKey::F19), + VK_F20 => Key::Named(NamedKey::F20), + VK_F21 => Key::Named(NamedKey::F21), + VK_F22 => Key::Named(NamedKey::F22), + VK_F23 => Key::Named(NamedKey::F23), + VK_F24 => Key::Named(NamedKey::F24), + VK_NAVIGATION_VIEW => Key::Unidentified(native_code), + VK_NAVIGATION_MENU => Key::Unidentified(native_code), + VK_NAVIGATION_UP => Key::Unidentified(native_code), + VK_NAVIGATION_DOWN => Key::Unidentified(native_code), + VK_NAVIGATION_LEFT => Key::Unidentified(native_code), + VK_NAVIGATION_RIGHT => Key::Unidentified(native_code), + VK_NAVIGATION_ACCEPT => Key::Unidentified(native_code), + VK_NAVIGATION_CANCEL => Key::Unidentified(native_code), + VK_NUMLOCK => Key::Named(NamedKey::NumLock), + VK_SCROLL => Key::Named(NamedKey::ScrollLock), + VK_OEM_NEC_EQUAL => Key::Unidentified(native_code), + // VK_OEM_FJ_JISHO => Key::Unidentified(native_code), // Conflicts with `VK_OEM_NEC_EQUAL` + VK_OEM_FJ_MASSHOU => Key::Unidentified(native_code), + VK_OEM_FJ_TOUROKU => Key::Unidentified(native_code), + VK_OEM_FJ_LOYA => Key::Unidentified(native_code), + VK_OEM_FJ_ROYA => Key::Unidentified(native_code), + VK_LSHIFT => Key::Named(NamedKey::Shift), + VK_RSHIFT => Key::Named(NamedKey::Shift), + VK_LCONTROL => Key::Named(NamedKey::Control), + VK_RCONTROL => Key::Named(NamedKey::Control), + VK_LMENU => Key::Named(NamedKey::Alt), + VK_RMENU => { + if has_alt_graph { + Key::Named(NamedKey::AltGraph) + } else { + Key::Named(NamedKey::Alt) + } + }, + VK_BROWSER_BACK => Key::Named(NamedKey::BrowserBack), + VK_BROWSER_FORWARD => Key::Named(NamedKey::BrowserForward), + VK_BROWSER_REFRESH => Key::Named(NamedKey::BrowserRefresh), + VK_BROWSER_STOP => Key::Named(NamedKey::BrowserStop), + VK_BROWSER_SEARCH => Key::Named(NamedKey::BrowserSearch), + VK_BROWSER_FAVORITES => Key::Named(NamedKey::BrowserFavorites), + VK_BROWSER_HOME => Key::Named(NamedKey::BrowserHome), + VK_VOLUME_MUTE => Key::Named(NamedKey::AudioVolumeMute), + VK_VOLUME_DOWN => Key::Named(NamedKey::AudioVolumeDown), + VK_VOLUME_UP => Key::Named(NamedKey::AudioVolumeUp), + VK_MEDIA_NEXT_TRACK => Key::Named(NamedKey::MediaTrackNext), + VK_MEDIA_PREV_TRACK => Key::Named(NamedKey::MediaTrackPrevious), + VK_MEDIA_STOP => Key::Named(NamedKey::MediaStop), + VK_MEDIA_PLAY_PAUSE => Key::Named(NamedKey::MediaPlayPause), + VK_LAUNCH_MAIL => Key::Named(NamedKey::LaunchMail), + VK_LAUNCH_MEDIA_SELECT => Key::Named(NamedKey::LaunchMediaPlayer), + VK_LAUNCH_APP1 => Key::Named(NamedKey::LaunchApplication1), + VK_LAUNCH_APP2 => Key::Named(NamedKey::LaunchApplication2), + + // This function only converts "non-printable" + VK_OEM_1 => Key::Unidentified(native_code), + VK_OEM_PLUS => Key::Unidentified(native_code), + VK_OEM_COMMA => Key::Unidentified(native_code), + VK_OEM_MINUS => Key::Unidentified(native_code), + VK_OEM_PERIOD => Key::Unidentified(native_code), + VK_OEM_2 => Key::Unidentified(native_code), + VK_OEM_3 => Key::Unidentified(native_code), + + VK_GAMEPAD_A => Key::Unidentified(native_code), + VK_GAMEPAD_B => Key::Unidentified(native_code), + VK_GAMEPAD_X => Key::Unidentified(native_code), + VK_GAMEPAD_Y => Key::Unidentified(native_code), + VK_GAMEPAD_RIGHT_SHOULDER => Key::Unidentified(native_code), + VK_GAMEPAD_LEFT_SHOULDER => Key::Unidentified(native_code), + VK_GAMEPAD_LEFT_TRIGGER => Key::Unidentified(native_code), + VK_GAMEPAD_RIGHT_TRIGGER => Key::Unidentified(native_code), + VK_GAMEPAD_DPAD_UP => Key::Unidentified(native_code), + VK_GAMEPAD_DPAD_DOWN => Key::Unidentified(native_code), + VK_GAMEPAD_DPAD_LEFT => Key::Unidentified(native_code), + VK_GAMEPAD_DPAD_RIGHT => Key::Unidentified(native_code), + VK_GAMEPAD_MENU => Key::Unidentified(native_code), + VK_GAMEPAD_VIEW => Key::Unidentified(native_code), + VK_GAMEPAD_LEFT_THUMBSTICK_BUTTON => Key::Unidentified(native_code), + VK_GAMEPAD_RIGHT_THUMBSTICK_BUTTON => Key::Unidentified(native_code), + VK_GAMEPAD_LEFT_THUMBSTICK_UP => Key::Unidentified(native_code), + VK_GAMEPAD_LEFT_THUMBSTICK_DOWN => Key::Unidentified(native_code), + VK_GAMEPAD_LEFT_THUMBSTICK_RIGHT => Key::Unidentified(native_code), + VK_GAMEPAD_LEFT_THUMBSTICK_LEFT => Key::Unidentified(native_code), + VK_GAMEPAD_RIGHT_THUMBSTICK_UP => Key::Unidentified(native_code), + VK_GAMEPAD_RIGHT_THUMBSTICK_DOWN => Key::Unidentified(native_code), + VK_GAMEPAD_RIGHT_THUMBSTICK_RIGHT => Key::Unidentified(native_code), + VK_GAMEPAD_RIGHT_THUMBSTICK_LEFT => Key::Unidentified(native_code), + + // This function only converts "non-printable" + VK_OEM_4 => Key::Unidentified(native_code), + VK_OEM_5 => Key::Unidentified(native_code), + VK_OEM_6 => Key::Unidentified(native_code), + VK_OEM_7 => Key::Unidentified(native_code), + VK_OEM_8 => Key::Unidentified(native_code), + VK_OEM_AX => Key::Unidentified(native_code), + VK_OEM_102 => Key::Unidentified(native_code), + + VK_ICO_HELP => Key::Unidentified(native_code), + VK_ICO_00 => Key::Unidentified(native_code), + + VK_PROCESSKEY => Key::Named(NamedKey::Process), + + VK_ICO_CLEAR => Key::Unidentified(native_code), + VK_PACKET => Key::Unidentified(native_code), + VK_OEM_RESET => Key::Unidentified(native_code), + VK_OEM_JUMP => Key::Unidentified(native_code), + VK_OEM_PA1 => Key::Unidentified(native_code), + VK_OEM_PA2 => Key::Unidentified(native_code), + VK_OEM_PA3 => Key::Unidentified(native_code), + VK_OEM_WSCTRL => Key::Unidentified(native_code), + VK_OEM_CUSEL => Key::Unidentified(native_code), + + VK_OEM_ATTN => Key::Named(NamedKey::Attn), + VK_OEM_FINISH => { + if is_japanese { + Key::Named(NamedKey::Katakana) + } else { + // This matches IE and Firefox behaviour according to + // https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key/Key_Values + // At the time of writing, there is no `NamedKey::Finish` variant as + // Finish is not mentioned at https://w3c.github.io/uievents-key/ + // Also see: https://github.com/pyfisch/keyboard-types/issues/9 + Key::Unidentified(native_code) + } + }, + VK_OEM_COPY => Key::Named(NamedKey::Copy), + VK_OEM_AUTO => Key::Named(NamedKey::Hankaku), + VK_OEM_ENLW => Key::Named(NamedKey::Zenkaku), + VK_OEM_BACKTAB => Key::Named(NamedKey::Romaji), + VK_ATTN => Key::Named(NamedKey::KanaMode), + VK_CRSEL => Key::Named(NamedKey::CrSel), + VK_EXSEL => Key::Named(NamedKey::ExSel), + VK_EREOF => Key::Named(NamedKey::EraseEof), + VK_PLAY => Key::Named(NamedKey::Play), + VK_ZOOM => Key::Named(NamedKey::ZoomToggle), + VK_NONAME => Key::Unidentified(native_code), + VK_PA1 => Key::Unidentified(native_code), + VK_OEM_CLEAR => Key::Named(NamedKey::Clear), + _ => Key::Unidentified(native_code), + } +} diff --git a/app/vendor/rune/vendor/winit/src/platform_impl/windows/minimal_ime.rs b/app/vendor/rune/vendor/winit/src/platform_impl/windows/minimal_ime.rs new file mode 100644 index 0000000..71600ab --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/platform_impl/windows/minimal_ime.rs @@ -0,0 +1,67 @@ +use std::sync::{ + atomic::{AtomicBool, Ordering::Relaxed}, + Mutex, +}; + +use winapi::{ + shared::{ + minwindef::{LPARAM, WPARAM}, + windef::HWND, + }, + um::winuser, +}; + +use crate::platform_impl::platform::{event_loop::ProcResult, keyboard::next_kbd_msg}; + +pub struct MinimalIme { + // True if we're currently receiving messages belonging to a finished IME session. + getting_ime_text: AtomicBool, + + utf16parts: Mutex<Vec<u16>>, +} +impl Default for MinimalIme { + fn default() -> Self { + MinimalIme { + getting_ime_text: AtomicBool::new(false), + utf16parts: Mutex::new(Vec::with_capacity(16)), + } + } +} +impl MinimalIme { + pub(crate) fn process_message( + &self, + hwnd: HWND, + msg_kind: u32, + wparam: WPARAM, + _lparam: LPARAM, + result: &mut ProcResult, + ) -> Option<String> { + match msg_kind { + winuser::WM_IME_ENDCOMPOSITION => { + self.getting_ime_text.store(true, Relaxed); + } + winuser::WM_CHAR | winuser::WM_SYSCHAR => { + if self.getting_ime_text.load(Relaxed) { + *result = ProcResult::Value(0); + self.utf16parts.lock().unwrap().push(wparam as u16); + // It's important that we push the new character and release the lock + // before getting the next message + let next_msg = next_kbd_msg(hwnd); + let more_char_coming = next_msg + .map(|m| matches!(m.message, winuser::WM_CHAR | winuser::WM_SYSCHAR)) + .unwrap_or(false); + if !more_char_coming { + let mut utf16parts = self.utf16parts.lock().unwrap(); + let result = String::from_utf16(&utf16parts).ok(); + utf16parts.clear(); + self.getting_ime_text.store(false, Relaxed); + return result; + } + } + } + _ => (), + } + + None + } +} diff --git a/app/vendor/rune/vendor/winit/src/platform_impl/windows/mod.rs b/app/vendor/rune/vendor/winit/src/platform_impl/windows/mod.rs new file mode 100644 index 0000000..89a61a2 --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/platform_impl/windows/mod.rs @@ -0,0 +1,197 @@ +use smol_str::SmolStr; +use windows_sys::Win32::Foundation::{HANDLE, HWND}; +use windows_sys::Win32::UI::WindowsAndMessaging::{HMENU, WINDOW_LONG_PTR_INDEX}; + +pub(crate) use self::event_loop::{ + ActiveEventLoop, EventLoop, EventLoopProxy, OwnedDisplayHandle, + PlatformSpecificEventLoopAttributes, +}; +pub(crate) use self::icon::{SelectedCursor, WinIcon}; +pub(crate) use self::keyboard::{physicalkey_to_scancode, scancode_to_physicalkey}; +pub(crate) use self::keyboard_layout::warm_layout; +pub(crate) use self::monitor::{MonitorHandle, VideoModeHandle}; +pub(crate) use self::window::Window; + +pub(crate) use self::icon::WinCursor as PlatformCustomCursor; +pub use self::icon::WinIcon as PlatformIcon; +pub(crate) use crate::cursor::OnlyCursorImageSource as PlatformCustomCursorSource; +use crate::platform_impl::Fullscreen; + +use crate::event::DeviceId as RootDeviceId; +use crate::icon::Icon; +use crate::keyboard::Key; +use crate::platform::windows::{BackdropType, Color, CornerPreference}; + +#[derive(Clone, Debug)] +pub struct PlatformSpecificWindowAttributes { + pub owner: Option<HWND>, + pub menu: Option<HMENU>, + pub taskbar_icon: Option<Icon>, + pub no_redirection_bitmap: bool, + pub drag_and_drop: bool, + pub skip_taskbar: bool, + pub class_name: String, + pub decoration_shadow: bool, + pub backdrop_type: BackdropType, + pub clip_children: bool, + pub border_color: Option<Color>, + pub title_background_color: Option<Color>, + pub title_text_color: Option<Color>, + pub corner_preference: Option<CornerPreference>, +} + +impl Default for PlatformSpecificWindowAttributes { + fn default() -> Self { + Self { + owner: None, + menu: None, + taskbar_icon: None, + no_redirection_bitmap: false, + drag_and_drop: true, + skip_taskbar: false, + class_name: "Window Class".to_string(), + decoration_shadow: false, + backdrop_type: BackdropType::default(), + clip_children: true, + border_color: None, + title_background_color: None, + title_text_color: None, + corner_preference: None, + } + } +} + +unsafe impl Send for PlatformSpecificWindowAttributes {} +unsafe impl Sync for PlatformSpecificWindowAttributes {} + +#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub struct DeviceId(u32); + +impl DeviceId { + pub const fn dummy() -> Self { + DeviceId(0) + } +} + +impl DeviceId { + pub fn persistent_identifier(&self) -> Option<String> { + if self.0 != 0 { + raw_input::get_raw_input_device_name(self.0 as HANDLE) + } else { + None + } + } +} + +// Constant device ID, to be removed when this backend is updated to report real device IDs. +const DEVICE_ID: RootDeviceId = RootDeviceId(DeviceId(0)); + +fn wrap_device_id(id: u32) -> RootDeviceId { + RootDeviceId(DeviceId(id)) +} + +pub type OsError = std::io::Error; + +#[derive(Debug, Clone, Eq, PartialEq, Hash)] +pub struct KeyEventExtra { + pub text_with_all_modifiers: Option<SmolStr>, + pub key_without_modifiers: Key, +} + +#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub struct WindowId(HWND); +unsafe impl Send for WindowId {} +unsafe impl Sync for WindowId {} + +impl WindowId { + pub const fn dummy() -> Self { + WindowId(0) + } +} + +impl From<WindowId> for u64 { + fn from(window_id: WindowId) -> Self { + window_id.0 as u64 + } +} + +impl From<WindowId> for HWND { + fn from(window_id: WindowId) -> Self { + window_id.0 + } +} + +impl From<u64> for WindowId { + fn from(raw_id: u64) -> Self { + Self(raw_id as HWND) + } +} + +#[inline(always)] +const fn get_xbutton_wparam(x: u32) -> u16 { + hiword(x) +} + +#[inline(always)] +const fn get_x_lparam(x: u32) -> i16 { + loword(x) as _ +} + +#[inline(always)] +const fn get_y_lparam(x: u32) -> i16 { + hiword(x) as _ +} + +#[inline(always)] +pub(crate) const fn primarylangid(lgid: u16) -> u16 { + lgid & 0x3ff +} + +#[inline(always)] +pub(crate) const fn loword(x: u32) -> u16 { + (x & 0xffff) as u16 +} + +#[inline(always)] +const fn hiword(x: u32) -> u16 { + ((x >> 16) & 0xffff) as u16 +} + +#[inline(always)] +unsafe fn get_window_long(hwnd: HWND, nindex: WINDOW_LONG_PTR_INDEX) -> isize { + #[cfg(target_pointer_width = "64")] + return unsafe { windows_sys::Win32::UI::WindowsAndMessaging::GetWindowLongPtrW(hwnd, nindex) }; + #[cfg(target_pointer_width = "32")] + return unsafe { + windows_sys::Win32::UI::WindowsAndMessaging::GetWindowLongW(hwnd, nindex) as isize + }; +} + +#[inline(always)] +unsafe fn set_window_long(hwnd: HWND, nindex: WINDOW_LONG_PTR_INDEX, dwnewlong: isize) -> isize { + #[cfg(target_pointer_width = "64")] + return unsafe { + windows_sys::Win32::UI::WindowsAndMessaging::SetWindowLongPtrW(hwnd, nindex, dwnewlong) + }; + #[cfg(target_pointer_width = "32")] + return unsafe { + windows_sys::Win32::UI::WindowsAndMessaging::SetWindowLongW(hwnd, nindex, dwnewlong as i32) + as isize + }; +} + +#[macro_use] +mod util; +mod dark_mode; +mod definitions; +mod dpi; +mod drop_handler; +mod event_loop; +mod icon; +mod ime; +mod keyboard; +mod keyboard_layout; +mod monitor; +mod raw_input; +mod window; +mod window_state; diff --git a/app/vendor/rune/vendor/winit/src/platform_impl/windows/monitor.rs b/app/vendor/rune/vendor/winit/src/platform_impl/windows/monitor.rs new file mode 100644 index 0000000..9a880db --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/platform_impl/windows/monitor.rs @@ -0,0 +1,256 @@ +use std::collections::{BTreeSet, VecDeque}; +use std::hash::Hash; +use std::{io, mem, ptr}; + +use windows_sys::Win32::Foundation::{BOOL, HWND, LPARAM, POINT, RECT}; +use windows_sys::Win32::Graphics::Gdi::{ + EnumDisplayMonitors, EnumDisplaySettingsExW, GetMonitorInfoW, MonitorFromPoint, + MonitorFromWindow, DEVMODEW, DM_BITSPERPEL, DM_DISPLAYFREQUENCY, DM_PELSHEIGHT, DM_PELSWIDTH, + ENUM_CURRENT_SETTINGS, HDC, HMONITOR, MONITORINFO, MONITORINFOEXW, MONITOR_DEFAULTTONEAREST, + MONITOR_DEFAULTTOPRIMARY, +}; + +use super::util::decode_wide; +use crate::dpi::{PhysicalPosition, PhysicalSize}; +use crate::monitor::VideoModeHandle as RootVideoModeHandle; +use crate::platform_impl::platform::dpi::{dpi_to_scale_factor, get_monitor_dpi}; +use crate::platform_impl::platform::util::has_flag; +use crate::platform_impl::platform::window::Window; + +#[derive(Clone)] +pub struct VideoModeHandle { + pub(crate) size: (u32, u32), + pub(crate) bit_depth: u16, + pub(crate) refresh_rate_millihertz: u32, + pub(crate) monitor: MonitorHandle, + // DEVMODEW is huge so we box it to avoid blowing up the size of winit::window::Fullscreen + pub(crate) native_video_mode: Box<DEVMODEW>, +} + +impl PartialEq for VideoModeHandle { + fn eq(&self, other: &Self) -> bool { + self.size == other.size + && self.bit_depth == other.bit_depth + && self.refresh_rate_millihertz == other.refresh_rate_millihertz + && self.monitor == other.monitor + } +} + +impl Eq for VideoModeHandle {} + +impl std::hash::Hash for VideoModeHandle { + fn hash<H: std::hash::Hasher>(&self, state: &mut H) { + self.size.hash(state); + self.bit_depth.hash(state); + self.refresh_rate_millihertz.hash(state); + self.monitor.hash(state); + } +} + +impl std::fmt::Debug for VideoModeHandle { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("VideoModeHandle") + .field("size", &self.size) + .field("bit_depth", &self.bit_depth) + .field("refresh_rate_millihertz", &self.refresh_rate_millihertz) + .field("monitor", &self.monitor) + .finish() + } +} + +impl VideoModeHandle { + pub fn size(&self) -> PhysicalSize<u32> { + self.size.into() + } + + pub fn bit_depth(&self) -> u16 { + self.bit_depth + } + + pub fn refresh_rate_millihertz(&self) -> u32 { + self.refresh_rate_millihertz + } + + pub fn monitor(&self) -> MonitorHandle { + self.monitor.clone() + } +} + +#[derive(Debug, Clone, Eq, PartialEq, Hash, PartialOrd, Ord)] +pub struct MonitorHandle(HMONITOR); + +// Send is not implemented for HMONITOR, we have to wrap it and implement it manually. +// For more info see: +// https://github.com/retep998/winapi-rs/issues/360 +// https://github.com/retep998/winapi-rs/issues/396 + +unsafe impl Send for MonitorHandle {} + +unsafe extern "system" fn monitor_enum_proc( + hmonitor: HMONITOR, + _hdc: HDC, + _place: *mut RECT, + data: LPARAM, +) -> BOOL { + let monitors = data as *mut VecDeque<MonitorHandle>; + unsafe { (*monitors).push_back(MonitorHandle::new(hmonitor)) }; + true.into() // continue enumeration +} + +pub fn available_monitors() -> VecDeque<MonitorHandle> { + let mut monitors: VecDeque<MonitorHandle> = VecDeque::new(); + unsafe { + EnumDisplayMonitors( + 0, + ptr::null(), + Some(monitor_enum_proc), + &mut monitors as *mut _ as LPARAM, + ); + } + monitors +} + +pub fn primary_monitor() -> MonitorHandle { + const ORIGIN: POINT = POINT { x: 0, y: 0 }; + let hmonitor = unsafe { MonitorFromPoint(ORIGIN, MONITOR_DEFAULTTOPRIMARY) }; + MonitorHandle::new(hmonitor) +} + +pub fn current_monitor(hwnd: HWND) -> MonitorHandle { + let hmonitor = unsafe { MonitorFromWindow(hwnd, MONITOR_DEFAULTTONEAREST) }; + MonitorHandle::new(hmonitor) +} + +impl Window { + pub fn available_monitors(&self) -> VecDeque<MonitorHandle> { + available_monitors() + } + + pub fn primary_monitor(&self) -> Option<MonitorHandle> { + let monitor = primary_monitor(); + Some(monitor) + } +} + +pub(crate) fn get_monitor_info(hmonitor: HMONITOR) -> Result<MONITORINFOEXW, io::Error> { + let mut monitor_info: MONITORINFOEXW = unsafe { mem::zeroed() }; + monitor_info.monitorInfo.cbSize = mem::size_of::<MONITORINFOEXW>() as u32; + let status = unsafe { + GetMonitorInfoW(hmonitor, &mut monitor_info as *mut MONITORINFOEXW as *mut MONITORINFO) + }; + if status == false.into() { + Err(io::Error::last_os_error()) + } else { + Ok(monitor_info) + } +} + +impl MonitorHandle { + pub(crate) fn new(hmonitor: HMONITOR) -> Self { + MonitorHandle(hmonitor) + } + + #[inline] + pub fn name(&self) -> Option<String> { + let monitor_info = get_monitor_info(self.0).unwrap(); + Some(decode_wide(&monitor_info.szDevice).to_string_lossy().to_string()) + } + + #[inline] + pub fn native_identifier(&self) -> String { + self.name().unwrap() + } + + #[inline] + pub fn hmonitor(&self) -> HMONITOR { + self.0 + } + + #[inline] + pub fn size(&self) -> PhysicalSize<u32> { + let rc_monitor = get_monitor_info(self.0).unwrap().monitorInfo.rcMonitor; + PhysicalSize { + width: (rc_monitor.right - rc_monitor.left) as u32, + height: (rc_monitor.bottom - rc_monitor.top) as u32, + } + } + + #[inline] + pub fn refresh_rate_millihertz(&self) -> Option<u32> { + let monitor_info = get_monitor_info(self.0).ok()?; + let device_name = monitor_info.szDevice.as_ptr(); + unsafe { + let mut mode: DEVMODEW = mem::zeroed(); + mode.dmSize = mem::size_of_val(&mode) as u16; + if EnumDisplaySettingsExW(device_name, ENUM_CURRENT_SETTINGS, &mut mode, 0) + == false.into() + { + None + } else { + Some(mode.dmDisplayFrequency * 1000) + } + } + } + + #[inline] + pub fn position(&self) -> PhysicalPosition<i32> { + get_monitor_info(self.0) + .map(|info| { + let rc_monitor = info.monitorInfo.rcMonitor; + PhysicalPosition { x: rc_monitor.left, y: rc_monitor.top } + }) + .unwrap_or(PhysicalPosition { x: 0, y: 0 }) + } + + #[inline] + pub fn scale_factor(&self) -> f64 { + dpi_to_scale_factor(get_monitor_dpi(self.0).unwrap_or(96)) + } + + #[inline] + pub fn video_modes(&self) -> impl Iterator<Item = VideoModeHandle> { + // EnumDisplaySettingsExW can return duplicate values (or some of the + // fields are probably changing, but we aren't looking at those fields + // anyway), so we're using a BTreeSet deduplicate + let mut modes = BTreeSet::<RootVideoModeHandle>::new(); + let mod_map = |mode: RootVideoModeHandle| mode.video_mode; + + let monitor_info = match get_monitor_info(self.0) { + Ok(monitor_info) => monitor_info, + Err(error) => { + tracing::warn!("Error from get_monitor_info: {error}"); + return modes.into_iter().map(mod_map); + }, + }; + + let device_name = monitor_info.szDevice.as_ptr(); + + let mut i = 0; + loop { + let mut mode: DEVMODEW = unsafe { mem::zeroed() }; + mode.dmSize = mem::size_of_val(&mode) as u16; + if unsafe { EnumDisplaySettingsExW(device_name, i, &mut mode, 0) } == false.into() { + break; + } + + const REQUIRED_FIELDS: u32 = + DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT | DM_DISPLAYFREQUENCY; + assert!(has_flag(mode.dmFields, REQUIRED_FIELDS)); + + // Use Ord impl of RootVideoModeHandle + modes.insert(RootVideoModeHandle { + video_mode: VideoModeHandle { + size: (mode.dmPelsWidth, mode.dmPelsHeight), + bit_depth: mode.dmBitsPerPel as u16, + refresh_rate_millihertz: mode.dmDisplayFrequency * 1000, + monitor: self.clone(), + native_video_mode: Box::new(mode), + }, + }); + + i += 1; + } + + modes.into_iter().map(mod_map) + } +} diff --git a/app/vendor/rune/vendor/winit/src/platform_impl/windows/raw_input.rs b/app/vendor/rune/vendor/winit/src/platform_impl/windows/raw_input.rs new file mode 100644 index 0000000..f78a7bb --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/platform_impl/windows/raw_input.rs @@ -0,0 +1,301 @@ +use std::mem::{self, size_of}; +use std::ptr; + +use windows_sys::Win32::Devices::HumanInterfaceDevice::{ + HID_USAGE_GENERIC_KEYBOARD, HID_USAGE_GENERIC_MOUSE, HID_USAGE_PAGE_GENERIC, +}; +use windows_sys::Win32::Foundation::{HANDLE, HWND}; +use windows_sys::Win32::UI::Input::KeyboardAndMouse::{ + MapVirtualKeyW, MAPVK_VK_TO_VSC_EX, VK_NUMLOCK, VK_SHIFT, +}; +use windows_sys::Win32::UI::Input::{ + GetRawInputData, GetRawInputDeviceInfoW, GetRawInputDeviceList, RegisterRawInputDevices, + HRAWINPUT, RAWINPUT, RAWINPUTDEVICE, RAWINPUTDEVICELIST, RAWINPUTHEADER, RAWKEYBOARD, + RIDEV_DEVNOTIFY, RIDEV_INPUTSINK, RIDEV_REMOVE, RIDI_DEVICEINFO, RIDI_DEVICENAME, + RID_DEVICE_INFO, RID_DEVICE_INFO_HID, RID_DEVICE_INFO_KEYBOARD, RID_DEVICE_INFO_MOUSE, + RID_INPUT, RIM_TYPEHID, RIM_TYPEKEYBOARD, RIM_TYPEMOUSE, +}; +use windows_sys::Win32::UI::WindowsAndMessaging::{ + RI_KEY_E0, RI_KEY_E1, RI_MOUSE_BUTTON_1_DOWN, RI_MOUSE_BUTTON_1_UP, RI_MOUSE_BUTTON_2_DOWN, + RI_MOUSE_BUTTON_2_UP, RI_MOUSE_BUTTON_3_DOWN, RI_MOUSE_BUTTON_3_UP, RI_MOUSE_BUTTON_4_DOWN, + RI_MOUSE_BUTTON_4_UP, RI_MOUSE_BUTTON_5_DOWN, RI_MOUSE_BUTTON_5_UP, +}; + +use super::scancode_to_physicalkey; +use crate::event::ElementState; +use crate::event_loop::DeviceEvents; +use crate::keyboard::{KeyCode, PhysicalKey}; +use crate::platform_impl::platform::util; + +#[allow(dead_code)] +pub fn get_raw_input_device_list() -> Option<Vec<RAWINPUTDEVICELIST>> { + let list_size = size_of::<RAWINPUTDEVICELIST>() as u32; + + let mut num_devices = 0; + let status = unsafe { GetRawInputDeviceList(ptr::null_mut(), &mut num_devices, list_size) }; + + if status == u32::MAX { + return None; + } + + let mut buffer = Vec::with_capacity(num_devices as _); + + let num_stored = + unsafe { GetRawInputDeviceList(buffer.as_mut_ptr(), &mut num_devices, list_size) }; + + if num_stored == u32::MAX { + return None; + } + + debug_assert_eq!(num_devices, num_stored); + + unsafe { buffer.set_len(num_devices as _) }; + + Some(buffer) +} + +#[allow(dead_code)] +pub enum RawDeviceInfo { + Mouse(RID_DEVICE_INFO_MOUSE), + Keyboard(RID_DEVICE_INFO_KEYBOARD), + Hid(RID_DEVICE_INFO_HID), +} + +impl From<RID_DEVICE_INFO> for RawDeviceInfo { + fn from(info: RID_DEVICE_INFO) -> Self { + unsafe { + match info.dwType { + RIM_TYPEMOUSE => RawDeviceInfo::Mouse(info.Anonymous.mouse), + RIM_TYPEKEYBOARD => RawDeviceInfo::Keyboard(info.Anonymous.keyboard), + RIM_TYPEHID => RawDeviceInfo::Hid(info.Anonymous.hid), + _ => unreachable!(), + } + } + } +} + +#[allow(dead_code)] +pub fn get_raw_input_device_info(handle: HANDLE) -> Option<RawDeviceInfo> { + let mut info: RID_DEVICE_INFO = unsafe { mem::zeroed() }; + let info_size = size_of::<RID_DEVICE_INFO>() as u32; + + info.cbSize = info_size; + + let mut minimum_size = 0; + let status = unsafe { + GetRawInputDeviceInfoW(handle, RIDI_DEVICEINFO, &mut info as *mut _ as _, &mut minimum_size) + }; + + if status == u32::MAX || status == 0 { + return None; + } + + debug_assert_eq!(info_size, status); + + Some(info.into()) +} + +pub fn get_raw_input_device_name(handle: HANDLE) -> Option<String> { + let mut minimum_size = 0; + let status = unsafe { + GetRawInputDeviceInfoW(handle, RIDI_DEVICENAME, ptr::null_mut(), &mut minimum_size) + }; + + if status != 0 { + return None; + } + + let mut name: Vec<u16> = Vec::with_capacity(minimum_size as _); + + let status = unsafe { + GetRawInputDeviceInfoW(handle, RIDI_DEVICENAME, name.as_ptr() as _, &mut minimum_size) + }; + + if status == u32::MAX || status == 0 { + return None; + } + + debug_assert_eq!(minimum_size, status); + + unsafe { name.set_len(minimum_size as _) }; + + util::decode_wide(&name).into_string().ok() +} + +pub fn register_raw_input_devices(devices: &[RAWINPUTDEVICE]) -> bool { + let device_size = size_of::<RAWINPUTDEVICE>() as u32; + + unsafe { + RegisterRawInputDevices(devices.as_ptr(), devices.len() as u32, device_size) == true.into() + } +} + +pub fn register_all_mice_and_keyboards_for_raw_input( + mut window_handle: HWND, + filter: DeviceEvents, +) -> bool { + // RIDEV_DEVNOTIFY: receive hotplug events + // RIDEV_INPUTSINK: receive events even if we're not in the foreground + // RIDEV_REMOVE: don't receive device events (requires NULL hwndTarget) + let flags = match filter { + DeviceEvents::Never => { + window_handle = 0; + RIDEV_REMOVE + }, + DeviceEvents::WhenFocused => RIDEV_DEVNOTIFY, + DeviceEvents::Always => RIDEV_DEVNOTIFY | RIDEV_INPUTSINK, + }; + + let devices: [RAWINPUTDEVICE; 2] = [ + RAWINPUTDEVICE { + usUsagePage: HID_USAGE_PAGE_GENERIC, + usUsage: HID_USAGE_GENERIC_MOUSE, + dwFlags: flags, + hwndTarget: window_handle, + }, + RAWINPUTDEVICE { + usUsagePage: HID_USAGE_PAGE_GENERIC, + usUsage: HID_USAGE_GENERIC_KEYBOARD, + dwFlags: flags, + hwndTarget: window_handle, + }, + ]; + + register_raw_input_devices(&devices) +} + +pub fn get_raw_input_data(handle: HRAWINPUT) -> Option<RAWINPUT> { + let mut data: RAWINPUT = unsafe { mem::zeroed() }; + let mut data_size = size_of::<RAWINPUT>() as u32; + let header_size = size_of::<RAWINPUTHEADER>() as u32; + + let status = unsafe { + GetRawInputData(handle, RID_INPUT, &mut data as *mut _ as _, &mut data_size, header_size) + }; + + if status == u32::MAX || status == 0 { + return None; + } + + Some(data) +} + +fn button_flags_to_element_state( + button_flags: u32, + down_flag: u32, + up_flag: u32, +) -> Option<ElementState> { + // We assume the same button won't be simultaneously pressed and released. + if util::has_flag(button_flags, down_flag) { + Some(ElementState::Pressed) + } else if util::has_flag(button_flags, up_flag) { + Some(ElementState::Released) + } else { + None + } +} + +pub fn get_raw_mouse_button_state(button_flags: u32) -> [Option<ElementState>; 5] { + [ + button_flags_to_element_state(button_flags, RI_MOUSE_BUTTON_1_DOWN, RI_MOUSE_BUTTON_1_UP), + button_flags_to_element_state(button_flags, RI_MOUSE_BUTTON_2_DOWN, RI_MOUSE_BUTTON_2_UP), + button_flags_to_element_state(button_flags, RI_MOUSE_BUTTON_3_DOWN, RI_MOUSE_BUTTON_3_UP), + button_flags_to_element_state(button_flags, RI_MOUSE_BUTTON_4_DOWN, RI_MOUSE_BUTTON_4_UP), + button_flags_to_element_state(button_flags, RI_MOUSE_BUTTON_5_DOWN, RI_MOUSE_BUTTON_5_UP), + ] +} + +pub fn get_keyboard_physical_key(keyboard: RAWKEYBOARD) -> Option<PhysicalKey> { + let extension = { + if util::has_flag(keyboard.Flags, RI_KEY_E0 as _) { + 0xe000 + } else if util::has_flag(keyboard.Flags, RI_KEY_E1 as _) { + 0xe100 + } else { + 0x0000 + } + }; + let scancode = if keyboard.MakeCode == 0 { + // In some cases (often with media keys) the device reports a scancode of 0 but a + // valid virtual key. In these cases we obtain the scancode from the virtual key. + unsafe { MapVirtualKeyW(keyboard.VKey as u32, MAPVK_VK_TO_VSC_EX) as u16 } + } else { + keyboard.MakeCode | extension + }; + if scancode == 0xe11d || scancode == 0xe02a { + // At the hardware (or driver?) level, pressing the Pause key is equivalent to pressing + // Ctrl+NumLock. + // This equivalence means that if the user presses Pause, the keyboard will emit two + // subsequent keypresses: + // 1, 0xE11D - Which is a left Ctrl (0x1D) with an extension flag (0xE100) + // 2, 0x0045 - Which on its own can be interpreted as Pause + // + // There's another combination which isn't quite an equivalence: + // PrtSc used to be Shift+Asterisk. This means that on some keyboards, pressing + // PrtSc (print screen) produces the following sequence: + // 1, 0xE02A - Which is a left shift (0x2A) with an extension flag (0xE000) + // 2, 0xE037 - Which is a numpad multiply (0x37) with an extension flag (0xE000). This on + // its own it can be interpreted as PrtSc + // + // For this reason, if we encounter the first keypress, we simply ignore it, trusting + // that there's going to be another event coming, from which we can extract the + // appropriate key. + // For more on this, read the article by Raymond Chen, titled: + // "Why does Ctrl+ScrollLock cancel dialogs?" + // https://devblogs.microsoft.com/oldnewthing/20080211-00/?p=23503 + return None; + } + let physical_key = if keyboard.VKey == VK_NUMLOCK { + // Historically, the NumLock and the Pause key were one and the same physical key. + // The user could trigger Pause by pressing Ctrl+NumLock. + // Now these are often physically separate and the two keys can be differentiated by + // checking the extension flag of the scancode. NumLock is 0xE045, Pause is 0x0045. + // + // However in this event, both keys are reported as 0x0045 even on modern hardware. + // Therefore we use the virtual key instead to determine whether it's a NumLock and + // set the KeyCode accordingly. + // + // For more on this, read the article by Raymond Chen, titled: + // "Why does Ctrl+ScrollLock cancel dialogs?" + // https://devblogs.microsoft.com/oldnewthing/20080211-00/?p=23503 + PhysicalKey::Code(KeyCode::NumLock) + } else { + scancode_to_physicalkey(scancode as u32) + }; + if keyboard.VKey == VK_SHIFT { + if let PhysicalKey::Code( + KeyCode::NumpadDecimal + | KeyCode::Numpad0 + | KeyCode::Numpad1 + | KeyCode::Numpad2 + | KeyCode::Numpad3 + | KeyCode::Numpad4 + | KeyCode::Numpad5 + | KeyCode::Numpad6 + | KeyCode::Numpad7 + | KeyCode::Numpad8 + | KeyCode::Numpad9, + ) = physical_key + { + // On Windows, holding the Shift key makes numpad keys behave as if NumLock + // wasn't active. The way this is exposed to applications by the system is that + // the application receives a fake key release event for the shift key at the + // moment when the numpad key is pressed, just before receiving the numpad key + // as well. + // + // The issue is that in the raw device event (here), the fake shift release + // event reports the numpad key as the scancode. Unfortunately, the event + // doesn't have any information to tell whether it's the + // left shift or the right shift that needs to get the fake + // release (or press) event so we don't forward this + // event to the application at all. + // + // For more on this, read the article by Raymond Chen, titled: + // "The shift key overrides NumLock" + // https://devblogs.microsoft.com/oldnewthing/20040906-00/?p=37953 + return None; + } + } + + Some(physical_key) +} diff --git a/app/vendor/rune/vendor/winit/src/platform_impl/windows/util.rs b/app/vendor/rune/vendor/winit/src/platform_impl/windows/util.rs new file mode 100644 index 0000000..c398067 --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/platform_impl/windows/util.rs @@ -0,0 +1,283 @@ +use std::ffi::{c_void, OsStr, OsString}; +use std::iter::once; +use std::ops::BitAnd; +use std::os::windows::prelude::{OsStrExt, OsStringExt}; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::{io, mem, ptr}; + +use crate::utils::Lazy; +use windows_sys::core::{HRESULT, PCWSTR}; +use windows_sys::Win32::Foundation::{BOOL, HANDLE, HMODULE, HWND, POINT, RECT}; +use windows_sys::Win32::Graphics::Gdi::{ClientToScreen, HMONITOR}; +use windows_sys::Win32::System::LibraryLoader::{ + GetProcAddress, LoadLibraryExA, LOAD_LIBRARY_SEARCH_SYSTEM32, +}; +use windows_sys::Win32::System::SystemServices::IMAGE_DOS_HEADER; +use windows_sys::Win32::UI::HiDpi::{ + DPI_AWARENESS_CONTEXT, MONITOR_DPI_TYPE, PROCESS_DPI_AWARENESS, +}; +use windows_sys::Win32::UI::Input::KeyboardAndMouse::GetActiveWindow; +use windows_sys::Win32::UI::Input::Pointer::{POINTER_INFO, POINTER_PEN_INFO, POINTER_TOUCH_INFO}; +use windows_sys::Win32::UI::WindowsAndMessaging::{ + ClipCursor, GetClientRect, GetClipCursor, GetCursorPos, GetSystemMetrics, GetWindowPlacement, + GetWindowRect, IsIconic, ShowCursor, IDC_APPSTARTING, IDC_ARROW, IDC_CROSS, IDC_HAND, IDC_HELP, + IDC_IBEAM, IDC_NO, IDC_SIZEALL, IDC_SIZENESW, IDC_SIZENS, IDC_SIZENWSE, IDC_SIZEWE, IDC_WAIT, + SM_CXVIRTUALSCREEN, SM_CYVIRTUALSCREEN, SM_XVIRTUALSCREEN, SM_YVIRTUALSCREEN, SW_MAXIMIZE, + WINDOWPLACEMENT, +}; + +use crate::window::CursorIcon; + +pub fn encode_wide(string: impl AsRef<OsStr>) -> Vec<u16> { + string.as_ref().encode_wide().chain(once(0)).collect() +} + +pub fn decode_wide(mut wide_c_string: &[u16]) -> OsString { + if let Some(null_pos) = wide_c_string.iter().position(|c| *c == 0) { + wide_c_string = &wide_c_string[..null_pos]; + } + + OsString::from_wide(wide_c_string) +} + +pub fn has_flag<T>(bitset: T, flag: T) -> bool +where + T: Copy + PartialEq + BitAnd<T, Output = T>, +{ + bitset & flag == flag +} + +pub(crate) fn win_to_err(result: BOOL) -> Result<(), io::Error> { + if result != false.into() { + Ok(()) + } else { + Err(io::Error::last_os_error()) + } +} + +pub enum WindowArea { + Outer, + Inner, +} + +impl WindowArea { + pub fn get_rect(self, hwnd: HWND) -> Result<RECT, io::Error> { + let mut rect = unsafe { mem::zeroed() }; + + match self { + WindowArea::Outer => { + win_to_err(unsafe { GetWindowRect(hwnd, &mut rect) })?; + }, + WindowArea::Inner => unsafe { + let mut top_left = mem::zeroed(); + + win_to_err(ClientToScreen(hwnd, &mut top_left))?; + win_to_err(GetClientRect(hwnd, &mut rect))?; + rect.left += top_left.x; + rect.top += top_left.y; + rect.right += top_left.x; + rect.bottom += top_left.y; + }, + } + + Ok(rect) + } +} + +pub fn is_maximized(window: HWND) -> bool { + unsafe { + let mut placement: WINDOWPLACEMENT = mem::zeroed(); + placement.length = mem::size_of::<WINDOWPLACEMENT>() as u32; + GetWindowPlacement(window, &mut placement); + placement.showCmd == SW_MAXIMIZE as u32 + } +} + +pub fn set_cursor_hidden(hidden: bool) { + static HIDDEN: AtomicBool = AtomicBool::new(false); + let changed = HIDDEN.swap(hidden, Ordering::SeqCst) ^ hidden; + if changed { + unsafe { ShowCursor(BOOL::from(!hidden)) }; + } +} + +pub fn get_cursor_position() -> Result<POINT, io::Error> { + unsafe { + let mut point: POINT = mem::zeroed(); + win_to_err(GetCursorPos(&mut point)).map(|_| point) + } +} + +pub fn get_cursor_clip() -> Result<RECT, io::Error> { + unsafe { + let mut rect: RECT = mem::zeroed(); + win_to_err(GetClipCursor(&mut rect)).map(|_| rect) + } +} + +/// Sets the cursor's clip rect. +/// +/// Note that calling this will automatically dispatch a `WM_MOUSEMOVE` event. +pub fn set_cursor_clip(rect: Option<RECT>) -> Result<(), io::Error> { + unsafe { + let rect_ptr = rect.as_ref().map(|r| r as *const RECT).unwrap_or(ptr::null()); + win_to_err(ClipCursor(rect_ptr)) + } +} + +pub fn get_desktop_rect() -> RECT { + unsafe { + let left = GetSystemMetrics(SM_XVIRTUALSCREEN); + let top = GetSystemMetrics(SM_YVIRTUALSCREEN); + RECT { + left, + top, + right: left + GetSystemMetrics(SM_CXVIRTUALSCREEN), + bottom: top + GetSystemMetrics(SM_CYVIRTUALSCREEN), + } + } +} + +pub fn is_focused(window: HWND) -> bool { + window == unsafe { GetActiveWindow() } +} + +pub fn is_minimized(window: HWND) -> bool { + unsafe { IsIconic(window) != false.into() } +} + +pub fn get_instance_handle() -> HMODULE { + // Gets the instance handle by taking the address of the + // pseudo-variable created by the microsoft linker: + // https://devblogs.microsoft.com/oldnewthing/20041025-00/?p=37483 + + // This is preferred over GetModuleHandle(NULL) because it also works in DLLs: + // https://stackoverflow.com/questions/21718027/getmodulehandlenull-vs-hinstance + + extern "C" { + static __ImageBase: IMAGE_DOS_HEADER; + } + + unsafe { &__ImageBase as *const _ as _ } +} + +pub(crate) fn to_windows_cursor(cursor: CursorIcon) -> PCWSTR { + match cursor { + CursorIcon::Default => IDC_ARROW, + CursorIcon::Pointer => IDC_HAND, + CursorIcon::Crosshair => IDC_CROSS, + CursorIcon::Text | CursorIcon::VerticalText => IDC_IBEAM, + CursorIcon::NotAllowed | CursorIcon::NoDrop => IDC_NO, + CursorIcon::Grab | CursorIcon::Grabbing | CursorIcon::Move | CursorIcon::AllScroll => { + IDC_SIZEALL + }, + CursorIcon::EResize + | CursorIcon::WResize + | CursorIcon::EwResize + | CursorIcon::ColResize => IDC_SIZEWE, + CursorIcon::NResize + | CursorIcon::SResize + | CursorIcon::NsResize + | CursorIcon::RowResize => IDC_SIZENS, + CursorIcon::NeResize | CursorIcon::SwResize | CursorIcon::NeswResize => IDC_SIZENESW, + CursorIcon::NwResize | CursorIcon::SeResize | CursorIcon::NwseResize => IDC_SIZENWSE, + CursorIcon::Wait => IDC_WAIT, + CursorIcon::Progress => IDC_APPSTARTING, + CursorIcon::Help => IDC_HELP, + _ => IDC_ARROW, // use arrow for the missing cases. + } +} + +// Helper function to dynamically load function pointer as some functions +// may not be available on all Windows platforms supported by winit. +// +// `library` and `function` must be zero-terminated. +pub(super) fn get_function_impl(library: &str, function: &str) -> Option<*const c_void> { + assert_eq!(library.chars().last(), Some('\0')); + assert_eq!(function.chars().last(), Some('\0')); + + // Library names we will use are ASCII so we can use the A version to avoid string conversion. + // Rune: load Windows system DLLs from System32 only, not the app directory or CWD. + let module = unsafe { LoadLibraryExA(library.as_ptr(), 0, LOAD_LIBRARY_SEARCH_SYSTEM32) }; + if module == 0 { + return None; + } + + unsafe { GetProcAddress(module, function.as_ptr()) }.map(|function_ptr| function_ptr as _) +} + +macro_rules! get_function { + ($lib:expr, $func:ident) => { + crate::platform_impl::platform::util::get_function_impl( + concat!($lib, '\0'), + concat!(stringify!($func), '\0'), + ) + .map(|f| unsafe { std::mem::transmute::<*const _, $func>(f) }) + }; +} + +pub type SetProcessDPIAware = unsafe extern "system" fn() -> BOOL; +pub type SetProcessDpiAwareness = + unsafe extern "system" fn(value: PROCESS_DPI_AWARENESS) -> HRESULT; +pub type SetProcessDpiAwarenessContext = + unsafe extern "system" fn(value: DPI_AWARENESS_CONTEXT) -> BOOL; +pub type GetDpiForWindow = unsafe extern "system" fn(hwnd: HWND) -> u32; +pub type GetDpiForMonitor = unsafe extern "system" fn( + hmonitor: HMONITOR, + dpi_type: MONITOR_DPI_TYPE, + dpi_x: *mut u32, + dpi_y: *mut u32, +) -> HRESULT; +pub type EnableNonClientDpiScaling = unsafe extern "system" fn(hwnd: HWND) -> BOOL; +pub type AdjustWindowRectExForDpi = unsafe extern "system" fn( + rect: *mut RECT, + dw_style: u32, + b_menu: BOOL, + dw_ex_style: u32, + dpi: u32, +) -> BOOL; + +pub type GetPointerFrameInfoHistory = unsafe extern "system" fn( + pointer_id: u32, + entries_count: *mut u32, + pointer_count: *mut u32, + pointer_info: *mut POINTER_INFO, +) -> BOOL; + +pub type SkipPointerFrameMessages = unsafe extern "system" fn(pointer_id: u32) -> BOOL; +pub type GetPointerDeviceRects = unsafe extern "system" fn( + device: HANDLE, + pointer_device_rect: *mut RECT, + display_rect: *mut RECT, +) -> BOOL; + +pub type GetPointerTouchInfo = + unsafe extern "system" fn(pointer_id: u32, touch_info: *mut POINTER_TOUCH_INFO) -> BOOL; + +pub type GetPointerPenInfo = + unsafe extern "system" fn(point_id: u32, pen_info: *mut POINTER_PEN_INFO) -> BOOL; + +pub(crate) static GET_DPI_FOR_WINDOW: Lazy<Option<GetDpiForWindow>> = + Lazy::new(|| get_function!("user32.dll", GetDpiForWindow)); +pub(crate) static ADJUST_WINDOW_RECT_EX_FOR_DPI: Lazy<Option<AdjustWindowRectExForDpi>> = + Lazy::new(|| get_function!("user32.dll", AdjustWindowRectExForDpi)); +pub(crate) static GET_DPI_FOR_MONITOR: Lazy<Option<GetDpiForMonitor>> = + Lazy::new(|| get_function!("shcore.dll", GetDpiForMonitor)); +pub(crate) static ENABLE_NON_CLIENT_DPI_SCALING: Lazy<Option<EnableNonClientDpiScaling>> = + Lazy::new(|| get_function!("user32.dll", EnableNonClientDpiScaling)); +pub(crate) static SET_PROCESS_DPI_AWARENESS_CONTEXT: Lazy<Option<SetProcessDpiAwarenessContext>> = + Lazy::new(|| get_function!("user32.dll", SetProcessDpiAwarenessContext)); +pub(crate) static SET_PROCESS_DPI_AWARENESS: Lazy<Option<SetProcessDpiAwareness>> = + Lazy::new(|| get_function!("shcore.dll", SetProcessDpiAwareness)); +pub(crate) static SET_PROCESS_DPI_AWARE: Lazy<Option<SetProcessDPIAware>> = + Lazy::new(|| get_function!("user32.dll", SetProcessDPIAware)); +pub(crate) static GET_POINTER_FRAME_INFO_HISTORY: Lazy<Option<GetPointerFrameInfoHistory>> = + Lazy::new(|| get_function!("user32.dll", GetPointerFrameInfoHistory)); +pub(crate) static SKIP_POINTER_FRAME_MESSAGES: Lazy<Option<SkipPointerFrameMessages>> = + Lazy::new(|| get_function!("user32.dll", SkipPointerFrameMessages)); +pub(crate) static GET_POINTER_DEVICE_RECTS: Lazy<Option<GetPointerDeviceRects>> = + Lazy::new(|| get_function!("user32.dll", GetPointerDeviceRects)); +pub(crate) static GET_POINTER_TOUCH_INFO: Lazy<Option<GetPointerTouchInfo>> = + Lazy::new(|| get_function!("user32.dll", GetPointerTouchInfo)); +pub(crate) static GET_POINTER_PEN_INFO: Lazy<Option<GetPointerPenInfo>> = + Lazy::new(|| get_function!("user32.dll", GetPointerPenInfo)); diff --git a/app/vendor/rune/vendor/winit/src/platform_impl/windows/window.rs b/app/vendor/rune/vendor/winit/src/platform_impl/windows/window.rs new file mode 100644 index 0000000..1fcf1f2 --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/platform_impl/windows/window.rs @@ -0,0 +1,1597 @@ +#![cfg(windows_platform)] + +use std::cell::Cell; +use std::ffi::c_void; +use std::mem::{self, MaybeUninit}; +use std::sync::mpsc::channel; +use std::sync::{Arc, Mutex, MutexGuard}; +use std::{io, panic, ptr}; + +use windows_sys::Win32::Foundation::{ + HWND, LPARAM, OLE_E_WRONGCOMPOBJ, POINT, POINTS, RECT, RPC_E_CHANGED_MODE, S_OK, WPARAM, +}; +use windows_sys::Win32::Graphics::Dwm::{ + DwmEnableBlurBehindWindow, DwmSetWindowAttribute, DWMWA_BORDER_COLOR, DWMWA_CAPTION_COLOR, + DWMWA_SYSTEMBACKDROP_TYPE, DWMWA_TEXT_COLOR, DWMWA_WINDOW_CORNER_PREFERENCE, DWM_BB_BLURREGION, + DWM_BB_ENABLE, DWM_BLURBEHIND, DWM_SYSTEMBACKDROP_TYPE, DWM_WINDOW_CORNER_PREFERENCE, +}; +use windows_sys::Win32::Graphics::Gdi::{ + ChangeDisplaySettingsExW, ClientToScreen, CreateRectRgn, DeleteObject, InvalidateRgn, + RedrawWindow, CDS_FULLSCREEN, DISP_CHANGE_BADFLAGS, DISP_CHANGE_BADMODE, DISP_CHANGE_BADPARAM, + DISP_CHANGE_FAILED, DISP_CHANGE_SUCCESSFUL, RDW_INTERNALPAINT, +}; +use windows_sys::Win32::System::Com::{ + CoCreateInstance, CoInitializeEx, CoUninitialize, CLSCTX_ALL, COINIT_APARTMENTTHREADED, +}; +use windows_sys::Win32::System::Ole::{OleInitialize, RegisterDragDrop}; +use windows_sys::Win32::UI::Input::KeyboardAndMouse::{ + EnableWindow, GetActiveWindow, MapVirtualKeyW, ReleaseCapture, SendInput, ToUnicode, INPUT, + INPUT_0, INPUT_KEYBOARD, KEYBDINPUT, KEYEVENTF_EXTENDEDKEY, KEYEVENTF_KEYUP, MAPVK_VK_TO_VSC, + VIRTUAL_KEY, VK_LMENU, VK_MENU, VK_SPACE, +}; +use windows_sys::Win32::UI::Input::Touch::{RegisterTouchWindow, TWF_WANTPALM}; +use windows_sys::Win32::UI::WindowsAndMessaging::{ + CreateWindowExW, EnableMenuItem, FlashWindowEx, GetClientRect, GetCursorPos, + GetForegroundWindow, GetSystemMenu, GetSystemMetrics, GetWindowPlacement, GetWindowTextLengthW, + GetWindowTextW, IsWindowVisible, LoadCursorW, PeekMessageW, PostMessageW, RegisterClassExW, + SetCursor, SetCursorPos, SetForegroundWindow, SetMenuDefaultItem, SetWindowDisplayAffinity, + SetWindowPlacement, SetWindowPos, SetWindowTextW, TrackPopupMenu, CS_HREDRAW, CS_VREDRAW, + CW_USEDEFAULT, FLASHWINFO, FLASHW_ALL, FLASHW_STOP, FLASHW_TIMERNOFG, FLASHW_TRAY, + GWLP_HINSTANCE, HTBOTTOM, HTBOTTOMLEFT, HTBOTTOMRIGHT, HTCAPTION, HTLEFT, HTRIGHT, HTTOP, + HTTOPLEFT, HTTOPRIGHT, MENU_ITEM_STATE, MFS_DISABLED, MFS_ENABLED, MF_BYCOMMAND, NID_READY, + PM_NOREMOVE, SC_CLOSE, SC_MAXIMIZE, SC_MINIMIZE, SC_MOVE, SC_RESTORE, SC_SIZE, SM_DIGITIZER, + SWP_ASYNCWINDOWPOS, SWP_NOACTIVATE, SWP_NOSIZE, SWP_NOZORDER, TPM_LEFTALIGN, TPM_RETURNCMD, + WDA_EXCLUDEFROMCAPTURE, WDA_NONE, WM_NCLBUTTONDOWN, WM_SYSCOMMAND, WNDCLASSEXW, +}; + +use tracing::warn; + +use crate::cursor::Cursor; +use crate::dpi::{PhysicalPosition, PhysicalSize, Position, Size}; +use crate::error::{ExternalError, NotSupportedError, OsError as RootOsError}; +use crate::icon::Icon; +use crate::platform::windows::{BackdropType, Color, CornerPreference}; +use crate::platform_impl::platform::dark_mode::try_theme; +use crate::platform_impl::platform::definitions::{ + CLSID_TaskbarList, IID_ITaskbarList, IID_ITaskbarList2, ITaskbarList, ITaskbarList2, +}; +use crate::platform_impl::platform::dpi::{ + dpi_to_scale_factor, enable_non_client_dpi_scaling, hwnd_dpi, +}; +use crate::platform_impl::platform::drop_handler::FileDropHandler; +use crate::platform_impl::platform::event_loop::{self, ActiveEventLoop, DESTROY_MSG_ID}; +use crate::platform_impl::platform::icon::{self, IconType, WinCursor}; +use crate::platform_impl::platform::ime::ImeContext; +use crate::platform_impl::platform::keyboard::KeyEventBuilder; +use crate::platform_impl::platform::monitor::{self, MonitorHandle}; +use crate::platform_impl::platform::window_state::{ + CursorFlags, SavedWindow, WindowFlags, WindowState, +}; +use crate::platform_impl::platform::{util, Fullscreen, SelectedCursor, WindowId}; +use crate::window::{ + CursorGrabMode, ImePurpose, ResizeDirection, Theme, UserAttentionType, WindowAttributes, + WindowButtons, WindowLevel, +}; + +/// The Win32 implementation of the main `Window` object. +pub(crate) struct Window { + /// Main handle for the window. + window: HWND, + + /// The current window state. + window_state: Arc<Mutex<WindowState>>, + + // The events loop proxy. + thread_executor: event_loop::EventLoopThreadExecutor, +} + +impl Window { + pub(crate) fn new( + event_loop: &ActiveEventLoop, + w_attr: WindowAttributes, + ) -> Result<Window, RootOsError> { + // We dispatch an `init` function because of code style. + // First person to remove the need for cloning here gets a cookie! + // + // done. you owe me -- ossi + unsafe { init(w_attr, event_loop) } + } + + pub(crate) fn maybe_queue_on_main(&self, f: impl FnOnce(&Self) + Send + 'static) { + // TODO: Use `thread_executor` here + f(self) + } + + pub(crate) fn maybe_wait_on_main<R: Send>(&self, f: impl FnOnce(&Self) -> R + Send) -> R { + // TODO: Use `thread_executor` here + f(self) + } + + fn window_state_lock(&self) -> MutexGuard<'_, WindowState> { + self.window_state.lock().unwrap() + } + + pub fn set_title(&self, text: &str) { + let wide_text = util::encode_wide(text); + unsafe { + SetWindowTextW(self.hwnd(), wide_text.as_ptr()); + } + } + + pub fn set_transparent(&self, transparent: bool) { + let window = self.window; + let window_state = Arc::clone(&self.window_state); + self.thread_executor.execute_in_thread(move || { + let _ = &window; + WindowState::set_window_flags(window_state.lock().unwrap(), window, |f| { + f.set(WindowFlags::TRANSPARENT, transparent) + }); + }); + } + + pub fn set_blur(&self, _blur: bool) {} + + #[inline] + pub fn set_visible(&self, visible: bool) { + let window = self.window; + let window_state = Arc::clone(&self.window_state); + self.thread_executor.execute_in_thread(move || { + let _ = &window; + WindowState::set_window_flags(window_state.lock().unwrap(), window, |f| { + f.set(WindowFlags::VISIBLE, visible) + }); + }); + } + + #[inline] + pub fn is_visible(&self) -> Option<bool> { + Some(unsafe { IsWindowVisible(self.window) == 1 }) + } + + #[inline] + pub fn request_redraw(&self) { + // NOTE: mark that we requested a redraw to handle requests during `WM_PAINT` handling. + self.window_state.lock().unwrap().redraw_requested = true; + unsafe { + RedrawWindow(self.hwnd(), ptr::null(), 0, RDW_INTERNALPAINT); + } + } + + #[inline] + pub fn pre_present_notify(&self) {} + + #[inline] + pub fn outer_position(&self) -> Result<PhysicalPosition<i32>, NotSupportedError> { + util::WindowArea::Outer + .get_rect(self.hwnd()) + .map(|rect| Ok(PhysicalPosition::new(rect.left, rect.top))) + .expect( + "Unexpected GetWindowRect failure; please report this error to \ + rust-windowing/winit", + ) + } + + #[inline] + pub fn inner_position(&self) -> Result<PhysicalPosition<i32>, NotSupportedError> { + let mut position: POINT = unsafe { mem::zeroed() }; + if unsafe { ClientToScreen(self.hwnd(), &mut position) } == false.into() { + panic!( + "Unexpected ClientToScreen failure: please report this error to \ + rust-windowing/winit" + ) + } + Ok(PhysicalPosition::new(position.x, position.y)) + } + + #[inline] + pub fn set_outer_position(&self, position: Position) { + let (x, y): (i32, i32) = position.to_physical::<i32>(self.scale_factor()).into(); + + let window_state = Arc::clone(&self.window_state); + let window = self.window; + self.thread_executor.execute_in_thread(move || { + let _ = &window; + WindowState::set_window_flags(window_state.lock().unwrap(), window, |f| { + f.set(WindowFlags::MAXIMIZED, false) + }); + }); + + unsafe { + SetWindowPos( + self.hwnd(), + 0, + x, + y, + 0, + 0, + SWP_ASYNCWINDOWPOS | SWP_NOZORDER | SWP_NOSIZE | SWP_NOACTIVATE, + ); + InvalidateRgn(self.hwnd(), 0, false.into()); + } + } + + #[inline] + pub fn inner_size(&self) -> PhysicalSize<u32> { + let mut rect: RECT = unsafe { mem::zeroed() }; + if unsafe { GetClientRect(self.hwnd(), &mut rect) } == false.into() { + panic!( + "Unexpected GetClientRect failure: please report this error to \ + rust-windowing/winit" + ) + } + PhysicalSize::new((rect.right - rect.left) as u32, (rect.bottom - rect.top) as u32) + } + + #[inline] + pub fn outer_size(&self) -> PhysicalSize<u32> { + util::WindowArea::Outer + .get_rect(self.hwnd()) + .map(|rect| { + PhysicalSize::new((rect.right - rect.left) as u32, (rect.bottom - rect.top) as u32) + }) + .unwrap() + } + + #[inline] + pub fn request_inner_size(&self, size: Size) -> Option<PhysicalSize<u32>> { + let scale_factor = self.scale_factor(); + let physical_size = size.to_physical::<u32>(scale_factor); + + let window_flags = self.window_state_lock().window_flags; + window_flags.set_size(self.hwnd(), physical_size); + + if physical_size != self.inner_size() { + let window_state = Arc::clone(&self.window_state); + let window = self.window; + self.thread_executor.execute_in_thread(move || { + let _ = &window; + WindowState::set_window_flags(window_state.lock().unwrap(), window, |f| { + f.set(WindowFlags::MAXIMIZED, false) + }); + }); + } + + None + } + + #[inline] + pub fn set_min_inner_size(&self, size: Option<Size>) { + self.window_state_lock().min_size = size; + // Make windows re-check the window size bounds. + let size = self.inner_size(); + self.request_inner_size(size.into()); + } + + #[inline] + pub fn set_max_inner_size(&self, size: Option<Size>) { + self.window_state_lock().max_size = size; + // Make windows re-check the window size bounds. + let size = self.inner_size(); + self.request_inner_size(size.into()); + } + + #[inline] + pub fn resize_increments(&self) -> Option<PhysicalSize<u32>> { + let w = self.window_state_lock(); + let scale_factor = w.scale_factor; + w.resize_increments.map(|size| size.to_physical(scale_factor)) + } + + #[inline] + pub fn set_resize_increments(&self, increments: Option<Size>) { + self.window_state_lock().resize_increments = increments; + } + + #[inline] + pub fn set_resizable(&self, resizable: bool) { + let window = self.window; + let window_state = Arc::clone(&self.window_state); + + self.thread_executor.execute_in_thread(move || { + let _ = &window; + WindowState::set_window_flags(window_state.lock().unwrap(), window, |f| { + f.set(WindowFlags::RESIZABLE, resizable) + }); + }); + } + + #[inline] + pub fn is_resizable(&self) -> bool { + let window_state = self.window_state_lock(); + window_state.window_flags.contains(WindowFlags::RESIZABLE) + } + + #[inline] + pub fn set_enabled_buttons(&self, buttons: WindowButtons) { + let window = self.window; + let window_state = Arc::clone(&self.window_state); + + self.thread_executor.execute_in_thread(move || { + let _ = &window; + WindowState::set_window_flags(window_state.lock().unwrap(), window, |f| { + f.set(WindowFlags::MINIMIZABLE, buttons.contains(WindowButtons::MINIMIZE)); + f.set(WindowFlags::MAXIMIZABLE, buttons.contains(WindowButtons::MAXIMIZE)); + f.set(WindowFlags::CLOSABLE, buttons.contains(WindowButtons::CLOSE)) + }); + }); + } + + pub fn enabled_buttons(&self) -> WindowButtons { + let mut buttons = WindowButtons::empty(); + let window_state = self.window_state_lock(); + if window_state.window_flags.contains(WindowFlags::MINIMIZABLE) { + buttons |= WindowButtons::MINIMIZE; + } + if window_state.window_flags.contains(WindowFlags::MAXIMIZABLE) { + buttons |= WindowButtons::MAXIMIZE; + } + if window_state.window_flags.contains(WindowFlags::CLOSABLE) { + buttons |= WindowButtons::CLOSE; + } + buttons + } + + /// Returns the `hwnd` of this window. + #[inline] + pub fn hwnd(&self) -> HWND { + self.window + } + + #[cfg(feature = "rwh_04")] + #[inline] + pub fn raw_window_handle_rwh_04(&self) -> rwh_04::RawWindowHandle { + let mut window_handle = rwh_04::Win32Handle::empty(); + window_handle.hwnd = self.window as *mut _; + let hinstance = unsafe { super::get_window_long(self.hwnd(), GWLP_HINSTANCE) }; + window_handle.hinstance = hinstance as *mut _; + rwh_04::RawWindowHandle::Win32(window_handle) + } + + #[cfg(feature = "rwh_05")] + #[inline] + pub fn raw_window_handle_rwh_05(&self) -> rwh_05::RawWindowHandle { + let mut window_handle = rwh_05::Win32WindowHandle::empty(); + window_handle.hwnd = self.window as *mut _; + let hinstance = unsafe { super::get_window_long(self.hwnd(), GWLP_HINSTANCE) }; + window_handle.hinstance = hinstance as *mut _; + rwh_05::RawWindowHandle::Win32(window_handle) + } + + #[cfg(feature = "rwh_05")] + #[inline] + pub fn raw_display_handle_rwh_05(&self) -> rwh_05::RawDisplayHandle { + rwh_05::RawDisplayHandle::Windows(rwh_05::WindowsDisplayHandle::empty()) + } + + #[cfg(feature = "rwh_06")] + #[inline] + pub unsafe fn rwh_06_no_thread_check( + &self, + ) -> Result<rwh_06::RawWindowHandle, rwh_06::HandleError> { + let mut window_handle = rwh_06::Win32WindowHandle::new(unsafe { + // SAFETY: Handle will never be zero. + std::num::NonZeroIsize::new_unchecked(self.window) + }); + let hinstance = unsafe { super::get_window_long(self.hwnd(), GWLP_HINSTANCE) }; + window_handle.hinstance = std::num::NonZeroIsize::new(hinstance); + Ok(rwh_06::RawWindowHandle::Win32(window_handle)) + } + + #[cfg(feature = "rwh_06")] + #[inline] + pub fn raw_window_handle_rwh_06(&self) -> Result<rwh_06::RawWindowHandle, rwh_06::HandleError> { + // TODO: Write a test once integration framework is ready to ensure that it holds. + // If we aren't in the GUI thread, we can't return the window. + if !self.thread_executor.in_event_loop_thread() { + tracing::error!("tried to access window handle outside of the main thread"); + return Err(rwh_06::HandleError::Unavailable); + } + + // SAFETY: We are on the correct thread. + unsafe { self.rwh_06_no_thread_check() } + } + + #[cfg(feature = "rwh_06")] + #[inline] + pub fn raw_display_handle_rwh_06( + &self, + ) -> Result<rwh_06::RawDisplayHandle, rwh_06::HandleError> { + Ok(rwh_06::RawDisplayHandle::Windows(rwh_06::WindowsDisplayHandle::new())) + } + + #[inline] + pub fn set_cursor(&self, cursor: Cursor) { + match cursor { + Cursor::Icon(icon) => { + self.window_state_lock().mouse.selected_cursor = SelectedCursor::Named(icon); + self.thread_executor.execute_in_thread(move || unsafe { + let cursor = LoadCursorW(0, util::to_windows_cursor(icon)); + SetCursor(cursor); + }); + }, + Cursor::Custom(cursor) => { + let new_cursor = match cursor.inner { + WinCursor::Cursor(cursor) => cursor, + WinCursor::Failed => { + warn!("Requested to apply failed cursor"); + return; + }, + }; + self.window_state_lock().mouse.selected_cursor = + SelectedCursor::Custom(new_cursor.clone()); + self.thread_executor.execute_in_thread(move || unsafe { + SetCursor(new_cursor.as_raw_handle()); + }); + }, + } + } + + #[inline] + pub fn set_cursor_grab(&self, mode: CursorGrabMode) -> Result<(), ExternalError> { + let window = self.window; + let window_state = Arc::clone(&self.window_state); + let (tx, rx) = channel(); + + self.thread_executor.execute_in_thread(move || { + let _ = &window; + let result = window_state + .lock() + .unwrap() + .mouse + .set_cursor_flags(window, |f| { + f.set(CursorFlags::GRABBED, mode != CursorGrabMode::None); + f.set(CursorFlags::LOCKED, mode == CursorGrabMode::Locked); + }) + .map_err(|e| ExternalError::Os(os_error!(e))); + let _ = tx.send(result); + }); + rx.recv().unwrap() + } + + #[inline] + pub fn set_cursor_visible(&self, visible: bool) { + let window = self.window; + let window_state = Arc::clone(&self.window_state); + let (tx, rx) = channel(); + + self.thread_executor.execute_in_thread(move || { + let _ = &window; + let result = window_state + .lock() + .unwrap() + .mouse + .set_cursor_flags(window, |f| f.set(CursorFlags::HIDDEN, !visible)) + .map_err(|e| e.to_string()); + let _ = tx.send(result); + }); + rx.recv().unwrap().ok(); + } + + #[inline] + pub fn scale_factor(&self) -> f64 { + self.window_state_lock().scale_factor + } + + #[inline] + pub fn set_cursor_position(&self, position: Position) -> Result<(), ExternalError> { + let scale_factor = self.scale_factor(); + let (x, y) = position.to_physical::<i32>(scale_factor).into(); + + let mut point = POINT { x, y }; + unsafe { + if ClientToScreen(self.hwnd(), &mut point) == false.into() { + return Err(ExternalError::Os(os_error!(io::Error::last_os_error()))); + } + if SetCursorPos(point.x, point.y) == false.into() { + return Err(ExternalError::Os(os_error!(io::Error::last_os_error()))); + } + } + Ok(()) + } + + unsafe fn handle_os_dragging(&self, wparam: WPARAM) { + let window = self.window; + let window_state = self.window_state.clone(); + + self.thread_executor.execute_in_thread(move || { + { + let mut guard = window_state.lock().unwrap(); + if !guard.dragging { + guard.dragging = true; + } else { + return; + } + } + + let points = { + let mut pos = unsafe { mem::zeroed() }; + unsafe { GetCursorPos(&mut pos) }; + pos + }; + let points = POINTS { x: points.x as i16, y: points.y as i16 }; + + // ReleaseCapture needs to execute on the main thread + unsafe { ReleaseCapture() }; + + unsafe { + PostMessageW(window, WM_NCLBUTTONDOWN, wparam, &points as *const _ as LPARAM) + }; + }); + } + + #[inline] + pub fn drag_window(&self) -> Result<(), ExternalError> { + unsafe { + self.handle_os_dragging(HTCAPTION as WPARAM); + } + + Ok(()) + } + + #[inline] + pub fn drag_resize_window(&self, direction: ResizeDirection) -> Result<(), ExternalError> { + unsafe { + self.handle_os_dragging(match direction { + ResizeDirection::East => HTRIGHT, + ResizeDirection::North => HTTOP, + ResizeDirection::NorthEast => HTTOPRIGHT, + ResizeDirection::NorthWest => HTTOPLEFT, + ResizeDirection::South => HTBOTTOM, + ResizeDirection::SouthEast => HTBOTTOMRIGHT, + ResizeDirection::SouthWest => HTBOTTOMLEFT, + ResizeDirection::West => HTLEFT, + } as WPARAM); + } + + Ok(()) + } + + unsafe fn handle_showing_window_menu(&self, position: Position) { + unsafe { + let point = { + let mut point = POINT { x: 0, y: 0 }; + let scale_factor = self.scale_factor(); + let (x, y) = position.to_physical::<i32>(scale_factor).into(); + point.x = x; + point.y = y; + if ClientToScreen(self.hwnd(), &mut point) == false.into() { + warn!( + "Can't convert client-area coordinates to screen coordinates when showing \ + window menu." + ); + return; + } + point + }; + + // get the current system menu + let h_menu = GetSystemMenu(self.hwnd(), 0); + if h_menu == 0 { + warn!("The corresponding window doesn't have a system menu"); + // This situation should not be treated as an error so just return without showing + // menu. + return; + } + + fn enable(b: bool) -> MENU_ITEM_STATE { + if b { + MFS_ENABLED + } else { + MFS_DISABLED + } + } + + // Change the menu items according to the current window status. + + let restore_btn = enable(self.is_maximized() && self.is_resizable()); + let size_btn = enable(!self.is_maximized() && self.is_resizable()); + let maximize_btn = enable(!self.is_maximized() && self.is_resizable()); + + EnableMenuItem(h_menu, SC_RESTORE, MF_BYCOMMAND | restore_btn); + EnableMenuItem(h_menu, SC_MOVE, MF_BYCOMMAND | enable(!self.is_maximized())); + EnableMenuItem(h_menu, SC_SIZE, MF_BYCOMMAND | size_btn); + EnableMenuItem(h_menu, SC_MINIMIZE, MF_BYCOMMAND | MFS_ENABLED); + EnableMenuItem(h_menu, SC_MAXIMIZE, MF_BYCOMMAND | maximize_btn); + EnableMenuItem(h_menu, SC_CLOSE, MF_BYCOMMAND | MFS_ENABLED); + + // Set the default menu item. + SetMenuDefaultItem(h_menu, SC_CLOSE, 0); + + // Popup the system menu at the position. + let result = TrackPopupMenu( + h_menu, + TPM_RETURNCMD | TPM_LEFTALIGN, /* for now im using LTR, but we have to use user + * layout direction */ + point.x, + point.y, + 0, + self.hwnd(), + std::ptr::null_mut(), + ); + + if result == 0 { + // User canceled the menu, no need to continue. + return; + } + + // Send the command that the user select to the corresponding window. + if PostMessageW(self.hwnd(), WM_SYSCOMMAND, result as _, 0) == 0 { + warn!("Can't post the system menu message to the window."); + } + } + } + + #[inline] + pub fn show_window_menu(&self, position: Position) { + unsafe { + self.handle_showing_window_menu(position); + } + } + + #[inline] + pub fn set_cursor_hittest(&self, hittest: bool) -> Result<(), ExternalError> { + let window = self.window; + let window_state = Arc::clone(&self.window_state); + self.thread_executor.execute_in_thread(move || { + WindowState::set_window_flags(window_state.lock().unwrap(), window, |f| { + f.set(WindowFlags::IGNORE_CURSOR_EVENT, !hittest) + }); + }); + + Ok(()) + } + + #[inline] + pub fn id(&self) -> WindowId { + WindowId(self.hwnd()) + } + + #[inline] + pub fn set_minimized(&self, minimized: bool) { + let window = self.window; + let window_state = Arc::clone(&self.window_state); + + let is_minimized = util::is_minimized(self.hwnd()); + + self.thread_executor.execute_in_thread(move || { + let _ = &window; + WindowState::set_window_flags_in_place(&mut window_state.lock().unwrap(), |f| { + f.set(WindowFlags::MINIMIZED, is_minimized) + }); + WindowState::set_window_flags(window_state.lock().unwrap(), window, |f| { + f.set(WindowFlags::MINIMIZED, minimized) + }); + }); + } + + #[inline] + pub fn is_minimized(&self) -> Option<bool> { + Some(util::is_minimized(self.hwnd())) + } + + #[inline] + pub fn set_maximized(&self, maximized: bool) { + let window = self.window; + let window_state = Arc::clone(&self.window_state); + + self.thread_executor.execute_in_thread(move || { + let _ = &window; + WindowState::set_window_flags(window_state.lock().unwrap(), window, |f| { + f.set(WindowFlags::MAXIMIZED, maximized) + }); + }); + } + + #[inline] + pub fn is_maximized(&self) -> bool { + let window_state = self.window_state_lock(); + window_state.window_flags.contains(WindowFlags::MAXIMIZED) + } + + #[inline] + pub fn fullscreen(&self) -> Option<Fullscreen> { + let window_state = self.window_state_lock(); + window_state.fullscreen.clone() + } + + #[inline] + pub fn set_fullscreen(&self, fullscreen: Option<Fullscreen>) { + let window = self.window; + let window_state = Arc::clone(&self.window_state); + + let mut window_state_lock = window_state.lock().unwrap(); + let old_fullscreen = window_state_lock.fullscreen.clone(); + + match (&old_fullscreen, &fullscreen) { + // Return if we already are in the same fullscreen mode + _ if old_fullscreen == fullscreen => return, + // Return if saved Borderless(monitor) is the same as current monitor when requested + // fullscreen is Borderless(None) + (Some(Fullscreen::Borderless(Some(monitor))), Some(Fullscreen::Borderless(None))) + if *monitor == monitor::current_monitor(window) => + { + return + }, + _ => {}, + } + + window_state_lock.fullscreen.clone_from(&fullscreen); + drop(window_state_lock); + + self.thread_executor.execute_in_thread(move || { + let _ = &window; + // Change video mode if we're transitioning to or from exclusive + // fullscreen + match (&old_fullscreen, &fullscreen) { + (_, Some(Fullscreen::Exclusive(video_mode))) => { + let monitor = video_mode.monitor(); + let monitor_info = monitor::get_monitor_info(monitor.hmonitor()).unwrap(); + + let res = unsafe { + ChangeDisplaySettingsExW( + monitor_info.szDevice.as_ptr(), + &*video_mode.native_video_mode, + 0, + CDS_FULLSCREEN, + ptr::null(), + ) + }; + + debug_assert!(res != DISP_CHANGE_BADFLAGS); + debug_assert!(res != DISP_CHANGE_BADMODE); + debug_assert!(res != DISP_CHANGE_BADPARAM); + debug_assert!(res != DISP_CHANGE_FAILED); + assert_eq!(res, DISP_CHANGE_SUCCESSFUL); + }, + (Some(Fullscreen::Exclusive(_)), _) => { + let res = unsafe { + ChangeDisplaySettingsExW( + ptr::null(), + ptr::null(), + 0, + CDS_FULLSCREEN, + ptr::null(), + ) + }; + + debug_assert!(res != DISP_CHANGE_BADFLAGS); + debug_assert!(res != DISP_CHANGE_BADMODE); + debug_assert!(res != DISP_CHANGE_BADPARAM); + debug_assert!(res != DISP_CHANGE_FAILED); + assert_eq!(res, DISP_CHANGE_SUCCESSFUL); + }, + _ => (), + } + + unsafe { + // There are some scenarios where calling `ChangeDisplaySettingsExW` takes long + // enough to execute that the DWM thinks our program has frozen and takes over + // our program's window. When that happens, the `SetWindowPos` call below gets + // eaten and the window doesn't get set to the proper fullscreen position. + // + // Calling `PeekMessageW` here notifies Windows that our process is still running + // fine, taking control back from the DWM and ensuring that the `SetWindowPos` call + // below goes through. + let mut msg = mem::zeroed(); + PeekMessageW(&mut msg, 0, 0, 0, PM_NOREMOVE); + } + + // Update window style + WindowState::set_window_flags(window_state.lock().unwrap(), window, |f| { + f.set( + WindowFlags::MARKER_EXCLUSIVE_FULLSCREEN, + matches!(fullscreen, Some(Fullscreen::Exclusive(_))), + ); + f.set( + WindowFlags::MARKER_BORDERLESS_FULLSCREEN, + matches!(fullscreen, Some(Fullscreen::Borderless(_))), + ); + }); + + // Mark as fullscreen window wrt to z-order + // + // this needs to be called before the below fullscreen SetWindowPos as this itself + // will generate WM_SIZE messages of the old window size that can race with what we set + // below + unsafe { + taskbar_mark_fullscreen(window, fullscreen.is_some()); + } + + // Update window bounds + match &fullscreen { + Some(fullscreen) => { + // Save window bounds before entering fullscreen + let placement = unsafe { + let mut placement = mem::zeroed(); + GetWindowPlacement(window, &mut placement); + placement + }; + + window_state.lock().unwrap().saved_window = Some(SavedWindow { placement }); + + let monitor = match &fullscreen { + Fullscreen::Exclusive(video_mode) => video_mode.monitor(), + Fullscreen::Borderless(Some(monitor)) => monitor.clone(), + Fullscreen::Borderless(None) => monitor::current_monitor(window), + }; + + let position: (i32, i32) = monitor.position().into(); + let size: (u32, u32) = monitor.size().into(); + + unsafe { + SetWindowPos( + window, + 0, + position.0, + position.1, + size.0 as i32, + size.1 as i32, + SWP_ASYNCWINDOWPOS | SWP_NOZORDER, + ); + InvalidateRgn(window, 0, false.into()); + } + }, + None => { + let mut window_state_lock = window_state.lock().unwrap(); + if let Some(SavedWindow { placement }) = window_state_lock.saved_window.take() { + drop(window_state_lock); + unsafe { + SetWindowPlacement(window, &placement); + InvalidateRgn(window, 0, false.into()); + } + } + }, + } + }); + } + + #[inline] + pub fn set_decorations(&self, decorations: bool) { + let window = self.window; + let window_state = Arc::clone(&self.window_state); + + self.thread_executor.execute_in_thread(move || { + let _ = &window; + WindowState::set_window_flags(window_state.lock().unwrap(), window, |f| { + f.set(WindowFlags::MARKER_DECORATIONS, decorations) + }); + }); + } + + #[inline] + pub fn is_decorated(&self) -> bool { + let window_state = self.window_state_lock(); + window_state.window_flags.contains(WindowFlags::MARKER_DECORATIONS) + } + + #[inline] + pub fn set_window_level(&self, level: WindowLevel) { + let window = self.window; + let window_state = Arc::clone(&self.window_state); + + self.thread_executor.execute_in_thread(move || { + let _ = &window; + WindowState::set_window_flags(window_state.lock().unwrap(), window, |f| { + f.set(WindowFlags::ALWAYS_ON_TOP, level == WindowLevel::AlwaysOnTop); + f.set(WindowFlags::ALWAYS_ON_BOTTOM, level == WindowLevel::AlwaysOnBottom); + }); + }); + } + + #[inline] + pub fn current_monitor(&self) -> Option<MonitorHandle> { + Some(monitor::current_monitor(self.hwnd())) + } + + #[inline] + pub fn set_window_icon(&self, window_icon: Option<Icon>) { + if let Some(ref window_icon) = window_icon { + window_icon.inner.set_for_window(self.hwnd(), IconType::Small); + } else { + icon::unset_for_window(self.hwnd(), IconType::Small); + } + self.window_state_lock().window_icon = window_icon; + } + + #[inline] + pub fn set_enable(&self, enabled: bool) { + unsafe { EnableWindow(self.hwnd(), enabled.into()) }; + } + + #[inline] + pub fn set_taskbar_icon(&self, taskbar_icon: Option<Icon>) { + if let Some(ref taskbar_icon) = taskbar_icon { + taskbar_icon.inner.set_for_window(self.hwnd(), IconType::Big); + } else { + icon::unset_for_window(self.hwnd(), IconType::Big); + } + self.window_state_lock().taskbar_icon = taskbar_icon; + } + + #[inline] + pub fn set_ime_cursor_area(&self, spot: Position, size: Size) { + let window = self.window; + let state = self.window_state.clone(); + self.thread_executor.execute_in_thread(move || unsafe { + let scale_factor = state.lock().unwrap().scale_factor; + ImeContext::current(window).set_ime_cursor_area(spot, size, scale_factor); + }); + } + + #[inline] + pub fn set_ime_allowed(&self, allowed: bool) { + let window = self.window; + let state = self.window_state.clone(); + self.thread_executor.execute_in_thread(move || unsafe { + state.lock().unwrap().ime_allowed = allowed; + ImeContext::set_ime_allowed(window, allowed); + }) + } + + #[inline] + pub fn set_ime_purpose(&self, _purpose: ImePurpose) {} + + #[inline] + pub fn request_user_attention(&self, request_type: Option<UserAttentionType>) { + let window = self.window; + let active_window_handle = unsafe { GetActiveWindow() }; + if window == active_window_handle { + return; + } + + self.thread_executor.execute_in_thread(move || unsafe { + let (flags, count) = request_type + .map(|ty| match ty { + UserAttentionType::Critical => (FLASHW_ALL | FLASHW_TIMERNOFG, u32::MAX), + UserAttentionType::Informational => (FLASHW_TRAY | FLASHW_TIMERNOFG, 0), + }) + .unwrap_or((FLASHW_STOP, 0)); + + let flash_info = FLASHWINFO { + cbSize: mem::size_of::<FLASHWINFO>() as u32, + hwnd: window, + dwFlags: flags, + uCount: count, + dwTimeout: 0, + }; + FlashWindowEx(&flash_info); + }); + } + + #[inline] + pub fn set_theme(&self, theme: Option<Theme>) { + try_theme(self.window, theme); + } + + #[inline] + pub fn theme(&self) -> Option<Theme> { + Some(self.window_state_lock().current_theme) + } + + #[inline] + pub fn has_focus(&self) -> bool { + let window_state = self.window_state.lock().unwrap(); + window_state.has_active_focus() + } + + pub fn title(&self) -> String { + let len = unsafe { GetWindowTextLengthW(self.window) } + 1; + let mut buf = vec![0; len as usize]; + unsafe { GetWindowTextW(self.window, buf.as_mut_ptr(), len) }; + util::decode_wide(&buf).to_string_lossy().to_string() + } + + #[inline] + pub fn set_skip_taskbar(&self, skip: bool) { + self.window_state_lock().skip_taskbar = skip; + unsafe { set_skip_taskbar(self.hwnd(), skip) }; + } + + #[inline] + pub fn set_undecorated_shadow(&self, shadow: bool) { + let window = self.window; + let window_state = Arc::clone(&self.window_state); + + self.thread_executor.execute_in_thread(move || { + let _ = &window; + WindowState::set_window_flags(window_state.lock().unwrap(), window, |f| { + f.set(WindowFlags::MARKER_UNDECORATED_SHADOW, shadow) + }); + }); + } + + #[inline] + pub fn set_system_backdrop(&self, backdrop_type: BackdropType) { + unsafe { + DwmSetWindowAttribute( + self.hwnd(), + DWMWA_SYSTEMBACKDROP_TYPE as u32, + &(backdrop_type as i32) as *const _ as _, + mem::size_of::<DWM_SYSTEMBACKDROP_TYPE>() as _, + ); + } + } + + #[inline] + pub fn focus_window(&self) { + let window_flags = self.window_state_lock().window_flags(); + + let is_visible = window_flags.contains(WindowFlags::VISIBLE); + let is_minimized = util::is_minimized(self.hwnd()); + let is_foreground = self.window == unsafe { GetForegroundWindow() }; + + if is_visible && !is_minimized && !is_foreground { + unsafe { force_window_active(self.window) }; + } + } + + #[inline] + pub fn set_content_protected(&self, protected: bool) { + unsafe { + SetWindowDisplayAffinity( + self.hwnd(), + if protected { WDA_EXCLUDEFROMCAPTURE } else { WDA_NONE }, + ) + }; + } + + #[inline] + pub fn reset_dead_keys(&self) { + // `ToUnicode` consumes the dead-key by default, so we are constructing a fake (but valid) + // key input which we can call `ToUnicode` with. + unsafe { + let vk = VK_SPACE as VIRTUAL_KEY; + let scancode = MapVirtualKeyW(vk as u32, MAPVK_VK_TO_VSC); + let kbd_state = [0; 256]; + let mut char_buff = [MaybeUninit::uninit(); 8]; + ToUnicode( + vk as u32, + scancode, + kbd_state.as_ptr(), + char_buff[0].as_mut_ptr(), + char_buff.len() as i32, + 0, + ); + } + } + + #[inline] + pub fn set_border_color(&self, color: Color) { + unsafe { + DwmSetWindowAttribute( + self.hwnd(), + DWMWA_BORDER_COLOR as u32, + &color as *const _ as _, + mem::size_of::<Color>() as _, + ); + } + } + + #[inline] + pub fn set_title_background_color(&self, color: Color) { + unsafe { + DwmSetWindowAttribute( + self.hwnd(), + DWMWA_CAPTION_COLOR as u32, + &color as *const _ as _, + mem::size_of::<Color>() as _, + ); + } + } + + #[inline] + pub fn set_title_text_color(&self, color: Color) { + unsafe { + DwmSetWindowAttribute( + self.hwnd(), + DWMWA_TEXT_COLOR as u32, + &color as *const _ as _, + mem::size_of::<Color>() as _, + ); + } + } + + #[inline] + pub fn set_corner_preference(&self, preference: CornerPreference) { + unsafe { + DwmSetWindowAttribute( + self.hwnd(), + DWMWA_WINDOW_CORNER_PREFERENCE as u32, + &(preference as DWM_WINDOW_CORNER_PREFERENCE) as *const _ as _, + mem::size_of::<DWM_WINDOW_CORNER_PREFERENCE>() as _, + ); + } + } +} + +impl Drop for Window { + #[inline] + fn drop(&mut self) { + unsafe { + // The window must be destroyed from the same thread that created it, so we send a + // custom message to be handled by our callback to do the actual work. + PostMessageW(self.hwnd(), DESTROY_MSG_ID.get(), 0, 0); + } + } +} + +pub(super) struct InitData<'a> { + // inputs + pub event_loop: &'a ActiveEventLoop, + pub attributes: WindowAttributes, + pub window_flags: WindowFlags, + // outputs + pub window: Option<Window>, +} + +impl InitData<'_> { + unsafe fn create_window(&self, window: HWND) -> Window { + // Register for touch events if applicable + { + let digitizer = unsafe { GetSystemMetrics(SM_DIGITIZER) as u32 }; + if digitizer & NID_READY != 0 { + unsafe { RegisterTouchWindow(window, TWF_WANTPALM) }; + } + } + + let dpi = unsafe { hwnd_dpi(window) }; + let scale_factor = dpi_to_scale_factor(dpi); + + // If the system theme is dark, we need to set the window theme now + // before we update the window flags (and possibly show the + // window for the first time). + let current_theme = try_theme(window, self.attributes.preferred_theme); + + let window_state = { + let window_state = WindowState::new( + &self.attributes, + scale_factor, + current_theme, + self.attributes.preferred_theme, + ); + let window_state = Arc::new(Mutex::new(window_state)); + WindowState::set_window_flags(window_state.lock().unwrap(), window, |f| { + *f = self.window_flags + }); + window_state + }; + + enable_non_client_dpi_scaling(window); + + unsafe { ImeContext::set_ime_allowed(window, false) }; + + Window { window, window_state, thread_executor: self.event_loop.create_thread_executor() } + } + + unsafe fn create_window_data(&self, win: &Window) -> event_loop::WindowData { + let file_drop_handler = if self.attributes.platform_specific.drag_and_drop { + let ole_init_result = unsafe { OleInitialize(ptr::null_mut()) }; + // It is ok if the initialize result is `S_FALSE` because it might happen that + // multiple windows are created on the same thread. + if ole_init_result == OLE_E_WRONGCOMPOBJ { + panic!("OleInitialize failed! Result was: `OLE_E_WRONGCOMPOBJ`"); + } else if ole_init_result == RPC_E_CHANGED_MODE { + panic!( + "OleInitialize failed! Result was: `RPC_E_CHANGED_MODE`. Make sure other \ + crates are not using multithreaded COM library on the same thread or disable \ + drag and drop support." + ); + } + + let file_drop_runner = self.event_loop.runner_shared.clone(); + let file_drop_handler = FileDropHandler::new( + win.window, + Box::new(move |event| { + if let Ok(e) = event.map_nonuser_event() { + file_drop_runner.send_event(e) + } + }), + ); + + let handler_interface_ptr = + unsafe { &mut (*file_drop_handler.data).interface as *mut _ as *mut c_void }; + + assert_eq!(unsafe { RegisterDragDrop(win.window, handler_interface_ptr) }, S_OK); + Some(file_drop_handler) + } else { + None + }; + + event_loop::WindowData { + window_state: win.window_state.clone(), + event_loop_runner: self.event_loop.runner_shared.clone(), + key_event_builder: KeyEventBuilder::default(), + _file_drop_handler: file_drop_handler, + userdata_removed: Cell::new(false), + recurse_depth: Cell::new(0), + } + } + + // Returns a pointer to window user data on success. + // The user data will be registered for the window and can be accessed within the window event + // callback. + pub unsafe fn on_nccreate(&mut self, window: HWND) -> Option<isize> { + let runner = self.event_loop.runner_shared.clone(); + let result = runner.catch_unwind(|| { + let window = unsafe { self.create_window(window) }; + let window_data = unsafe { self.create_window_data(&window) }; + (window, window_data) + }); + + result.map(|(win, userdata)| { + self.window = Some(win); + let userdata = Box::into_raw(Box::new(userdata)); + userdata as _ + }) + } + + pub unsafe fn on_create(&mut self) { + let win = self.window.as_mut().expect("failed window creation"); + + // making the window transparent + if self.attributes.transparent && !self.attributes.platform_specific.no_redirection_bitmap { + // Empty region for the blur effect, so the window is fully transparent + let region = unsafe { CreateRectRgn(0, 0, -1, -1) }; + + let bb = DWM_BLURBEHIND { + dwFlags: DWM_BB_ENABLE | DWM_BB_BLURREGION, + fEnable: true.into(), + hRgnBlur: region, + fTransitionOnMaximized: false.into(), + }; + let hr = unsafe { DwmEnableBlurBehindWindow(win.hwnd(), &bb) }; + if hr < 0 { + warn!("Setting transparent window is failed. HRESULT Code: 0x{:X}", hr); + } + unsafe { DeleteObject(region) }; + } + + // A new window is on the taskbar already: only taking it off needs the TaskbarList COM + // object (CoInitializeEx and CoCreateInstance on this thread, about 7,800 us and nine + // shell DLLs before the window's first frame). + if self.attributes.platform_specific.skip_taskbar { + win.set_skip_taskbar(true); + } + win.set_window_icon(self.attributes.window_icon.clone()); + win.set_taskbar_icon(self.attributes.platform_specific.taskbar_icon.clone()); + + let attributes = self.attributes.clone(); + + if attributes.content_protected { + win.set_content_protected(true); + } + + win.set_cursor(attributes.cursor); + + // Set visible before setting the size to ensure the + // attribute is correctly applied. + win.set_visible(attributes.visible); + + win.set_enabled_buttons(attributes.enabled_buttons); + + let size = attributes.inner_size.unwrap_or_else(|| PhysicalSize::new(800, 600).into()); + let max_size = attributes + .max_inner_size + .unwrap_or_else(|| PhysicalSize::new(f64::MAX, f64::MAX).into()); + let min_size = attributes.min_inner_size.unwrap_or_else(|| PhysicalSize::new(0, 0).into()); + let clamped_size = Size::clamp(size, min_size, max_size, win.scale_factor()); + win.request_inner_size(clamped_size); + + // let margins = MARGINS { + // cxLeftWidth: 1, + // cxRightWidth: 1, + // cyTopHeight: 1, + // cyBottomHeight: 1, + // }; + // dbg!(DwmExtendFrameIntoClientArea(win.hwnd(), &margins as *const _)); + + if let Some(position) = attributes.position { + win.set_outer_position(position); + } + + win.set_system_backdrop(self.attributes.platform_specific.backdrop_type); + + if let Some(color) = self.attributes.platform_specific.border_color { + win.set_border_color(color); + } + if let Some(color) = self.attributes.platform_specific.title_background_color { + win.set_title_background_color(color); + } + if let Some(color) = self.attributes.platform_specific.title_text_color { + win.set_title_text_color(color); + } + if let Some(corner) = self.attributes.platform_specific.corner_preference { + win.set_corner_preference(corner); + } + } +} +unsafe fn init( + attributes: WindowAttributes, + event_loop: &ActiveEventLoop, +) -> Result<Window, RootOsError> { + let title = util::encode_wide(&attributes.title); + + let class_name = util::encode_wide(&attributes.platform_specific.class_name); + unsafe { register_window_class(&class_name) }; + + let mut window_flags = WindowFlags::empty(); + window_flags.set(WindowFlags::MARKER_DECORATIONS, attributes.decorations); + window_flags.set( + WindowFlags::MARKER_UNDECORATED_SHADOW, + attributes.platform_specific.decoration_shadow, + ); + window_flags + .set(WindowFlags::ALWAYS_ON_TOP, attributes.window_level == WindowLevel::AlwaysOnTop); + window_flags + .set(WindowFlags::ALWAYS_ON_BOTTOM, attributes.window_level == WindowLevel::AlwaysOnBottom); + window_flags + .set(WindowFlags::NO_BACK_BUFFER, attributes.platform_specific.no_redirection_bitmap); + window_flags.set(WindowFlags::MARKER_ACTIVATE, attributes.active); + window_flags.set(WindowFlags::TRANSPARENT, attributes.transparent); + // WindowFlags::VISIBLE and MAXIMIZED are set down below after the window has been configured. + window_flags.set(WindowFlags::RESIZABLE, attributes.resizable); + // Will be changed later using `window.set_enabled_buttons` but we need to set a default here + // so the diffing later can work. + window_flags.set(WindowFlags::CLOSABLE, true); + // The window is made with the boxes it asks for, so `set_enabled_buttons` in `on_create` + // changes nothing: adding them there rewrote its styles and changed its frame again + // (`SWP_FRAMECHANGED`, about 1,000 us before its first frame). + window_flags.set(WindowFlags::MINIMIZABLE, attributes.enabled_buttons.contains(WindowButtons::MINIMIZE)); + window_flags.set(WindowFlags::MAXIMIZABLE, attributes.enabled_buttons.contains(WindowButtons::MAXIMIZE)); + window_flags.set(WindowFlags::CLIP_CHILDREN, attributes.platform_specific.clip_children); + + let mut fallback_parent = || match attributes.platform_specific.owner { + Some(parent) => { + window_flags.set(WindowFlags::POPUP, true); + Some(parent) + }, + None => { + window_flags.set(WindowFlags::ON_TASKBAR, true); + None + }, + }; + + #[cfg(feature = "rwh_06")] + let parent = match attributes.parent_window.as_ref().map(|handle| handle.0) { + Some(rwh_06::RawWindowHandle::Win32(handle)) => { + window_flags.set(WindowFlags::CHILD, true); + if attributes.platform_specific.menu.is_some() { + warn!("Setting a menu on a child window is unsupported"); + } + Some(handle.hwnd.get() as HWND) + }, + Some(raw) => unreachable!("Invalid raw window handle {raw:?} on Windows"), + None => fallback_parent(), + }; + + #[cfg(not(feature = "rwh_06"))] + let parent = fallback_parent(); + + let menu = attributes.platform_specific.menu; + let fullscreen = attributes.fullscreen.clone(); + let maximized = attributes.maximized; + // A window with a physical position is made there, at its size, so it is born on its + // display at that display's scale. Made at the default place (the primary display) and moved + // there afterwards, it would cross to the other display's scale (WM_DPICHANGED) and be + // resized to keep its logical size: a window saved on a 150 % display beside a 100 % primary + // would reopen half as large again. + let (x, y, width, height) = match (attributes.position, attributes.inner_size) { + (Some(Position::Physical(p)), Some(Size::Physical(s))) => { + (p.x, p.y, s.width as i32, s.height as i32) + }, + (Some(Position::Physical(p)), _) => (p.x, p.y, CW_USEDEFAULT, CW_USEDEFAULT), + _ => (CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT), + }; + let mut initdata = InitData { event_loop, attributes, window_flags, window: None }; + + let (style, ex_style) = window_flags.to_window_styles(); + let handle = unsafe { + CreateWindowExW( + ex_style, + class_name.as_ptr(), + title.as_ptr(), + style, + x, + y, + width, + height, + parent.unwrap_or(0), + menu.unwrap_or(0), + util::get_instance_handle(), + &mut initdata as *mut _ as *mut _, + ) + }; + + // If the window creation in `InitData` panicked, then should resume panicking here + if let Err(panic_error) = event_loop.runner_shared.take_panic_error() { + panic::resume_unwind(panic_error) + } + + if handle == 0 { + return Err(os_error!(io::Error::last_os_error())); + } + + // If the handle is non-null, then window creation must have succeeded, which means + // that we *must* have populated the `InitData.window` field. + let win = initdata.window.unwrap(); + + // Need to set FULLSCREEN or MAXIMIZED after CreateWindowEx + // This is because if the size is changed in WM_CREATE, the restored size will be stored in that + // size. + if fullscreen.is_some() { + win.set_fullscreen(fullscreen.map(Into::into)); + unsafe { force_window_active(win.window) }; + } else if maximized { + win.set_maximized(true); + } + + Ok(win) +} + +unsafe fn register_window_class(class_name: &[u16]) { + let class = WNDCLASSEXW { + cbSize: mem::size_of::<WNDCLASSEXW>() as u32, + style: CS_HREDRAW | CS_VREDRAW, + lpfnWndProc: Some(super::event_loop::public_window_callback), + cbClsExtra: 0, + cbWndExtra: 0, + hInstance: util::get_instance_handle(), + hIcon: 0, + hCursor: 0, // must be null in order for cursor state to work properly + hbrBackground: 0, + lpszMenuName: ptr::null(), + lpszClassName: class_name.as_ptr(), + hIconSm: 0, + }; + + // We ignore errors because registering the same window class twice would trigger + // an error, and because errors here are detected during CreateWindowEx anyway. + // Also since there is no weird element in the struct, there is no reason for this + // call to fail. + unsafe { RegisterClassExW(&class) }; +} + +struct ComInitialized(#[allow(dead_code)] *mut ()); +impl Drop for ComInitialized { + fn drop(&mut self) { + unsafe { CoUninitialize() }; + } +} + +thread_local! { + static COM_INITIALIZED: ComInitialized = { + unsafe { + CoInitializeEx(ptr::null(), COINIT_APARTMENTTHREADED as u32); + ComInitialized(ptr::null_mut()) + } + }; + + static TASKBAR_LIST: Cell<*mut ITaskbarList> = const { Cell::new(ptr::null_mut()) }; + static TASKBAR_LIST2: Cell<*mut ITaskbarList2> = const { Cell::new(ptr::null_mut()) }; +} + +pub fn com_initialized() { + COM_INITIALIZED.with(|_| {}); +} + +// Reference Implementation: +// https://github.com/chromium/chromium/blob/f18e79d901f56154f80eea1e2218544285e62623/ui/views/win/fullscreen_handler.cc +// +// As per MSDN marking the window as fullscreen should ensure that the +// taskbar is moved to the bottom of the Z-order when the fullscreen window +// is activated. If the window is not fullscreen, the Shell falls back to +// heuristics to determine how the window should be treated, which means +// that it could still consider the window as fullscreen. :( +unsafe fn taskbar_mark_fullscreen(handle: HWND, fullscreen: bool) { + com_initialized(); + + TASKBAR_LIST2.with(|task_bar_list2_ptr| { + let mut task_bar_list2 = task_bar_list2_ptr.get(); + + if task_bar_list2.is_null() { + let hr = unsafe { + CoCreateInstance( + &CLSID_TaskbarList, + ptr::null_mut(), + CLSCTX_ALL, + &IID_ITaskbarList2, + &mut task_bar_list2 as *mut _ as *mut _, + ) + }; + if hr != S_OK { + // In visual studio retrieving the taskbar list fails + return; + } + + let hr_init = unsafe { (*(*task_bar_list2).lpVtbl).parent.HrInit }; + if unsafe { hr_init(task_bar_list2.cast()) } != S_OK { + // In some old windows, the taskbar object could not be created, we just ignore it + return; + } + task_bar_list2_ptr.set(task_bar_list2) + } + + task_bar_list2 = task_bar_list2_ptr.get(); + let mark_fullscreen_window = unsafe { (*(*task_bar_list2).lpVtbl).MarkFullscreenWindow }; + unsafe { mark_fullscreen_window(task_bar_list2, handle, fullscreen.into()) }; + }) +} + +pub(crate) unsafe fn set_skip_taskbar(hwnd: HWND, skip: bool) { + com_initialized(); + TASKBAR_LIST.with(|task_bar_list_ptr| { + let mut task_bar_list = task_bar_list_ptr.get(); + + if task_bar_list.is_null() { + let hr = unsafe { + CoCreateInstance( + &CLSID_TaskbarList, + ptr::null_mut(), + CLSCTX_ALL, + &IID_ITaskbarList, + &mut task_bar_list as *mut _ as *mut _, + ) + }; + if hr != S_OK { + // In visual studio retrieving the taskbar list fails + return; + } + + let hr_init = unsafe { (*(*task_bar_list).lpVtbl).HrInit }; + if unsafe { hr_init(task_bar_list.cast()) } != S_OK { + // In some old windows, the taskbar object could not be created, we just ignore it + return; + } + task_bar_list_ptr.set(task_bar_list) + } + + task_bar_list = task_bar_list_ptr.get(); + if skip { + let delete_tab = unsafe { (*(*task_bar_list).lpVtbl).DeleteTab }; + unsafe { delete_tab(task_bar_list, hwnd) }; + } else { + let add_tab = unsafe { (*(*task_bar_list).lpVtbl).AddTab }; + unsafe { add_tab(task_bar_list, hwnd) }; + } + }); +} + +unsafe fn force_window_active(handle: HWND) { + // In some situation, calling SetForegroundWindow could not bring up the window, + // This is a little hack which can "steal" the foreground window permission + // We only call this function in the window creation, so it should be fine. + // See : https://stackoverflow.com/questions/10740346/setforegroundwindow-only-working-while-visual-studio-is-open + let alt_sc = unsafe { MapVirtualKeyW(VK_MENU as u32, MAPVK_VK_TO_VSC) }; + + let inputs = [ + INPUT { + r#type: INPUT_KEYBOARD, + Anonymous: INPUT_0 { + ki: KEYBDINPUT { + wVk: VK_LMENU, + wScan: alt_sc as u16, + dwFlags: KEYEVENTF_EXTENDEDKEY, + dwExtraInfo: 0, + time: 0, + }, + }, + }, + INPUT { + r#type: INPUT_KEYBOARD, + Anonymous: INPUT_0 { + ki: KEYBDINPUT { + wVk: VK_LMENU, + wScan: alt_sc as u16, + dwFlags: KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, + dwExtraInfo: 0, + time: 0, + }, + }, + }, + ]; + + // Simulate a key press and release + unsafe { SendInput(inputs.len() as u32, inputs.as_ptr(), mem::size_of::<INPUT>() as i32) }; + + unsafe { SetForegroundWindow(handle) }; +} diff --git a/app/vendor/rune/vendor/winit/src/platform_impl/windows/window_state.rs b/app/vendor/rune/vendor/winit/src/platform_impl/windows/window_state.rs new file mode 100644 index 0000000..bfe251b --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/platform_impl/windows/window_state.rs @@ -0,0 +1,553 @@ +use crate::dpi::{PhysicalPosition, PhysicalSize, Size}; +use crate::icon::Icon; +use crate::keyboard::ModifiersState; +use crate::platform_impl::platform::{event_loop, util, Fullscreen, SelectedCursor}; +use crate::window::{Theme, WindowAttributes}; +use bitflags::bitflags; +use std::io; +use std::sync::MutexGuard; +use windows_sys::Win32::Foundation::{HWND, RECT}; +use windows_sys::Win32::Graphics::Gdi::InvalidateRgn; +use windows_sys::Win32::UI::WindowsAndMessaging::{ + AdjustWindowRectEx, EnableMenuItem, GetMenu, GetSystemMenu, GetWindowLongW, SendMessageW, + SetWindowLongW, SetWindowPos, ShowWindow, GWL_EXSTYLE, GWL_STYLE, HWND_BOTTOM, HWND_NOTOPMOST, + HWND_TOPMOST, MF_BYCOMMAND, MF_DISABLED, MF_ENABLED, SC_CLOSE, SWP_ASYNCWINDOWPOS, + SWP_FRAMECHANGED, SWP_NOACTIVATE, SWP_NOMOVE, SWP_NOREPOSITION, SWP_NOSIZE, SWP_NOZORDER, + SW_HIDE, SW_MAXIMIZE, SW_MINIMIZE, SW_RESTORE, SW_SHOW, SW_SHOWNOACTIVATE, WINDOWPLACEMENT, + WINDOW_EX_STYLE, WINDOW_STYLE, WS_BORDER, WS_CAPTION, WS_CHILD, WS_CLIPCHILDREN, + WS_CLIPSIBLINGS, WS_EX_ACCEPTFILES, WS_EX_APPWINDOW, WS_EX_LAYERED, WS_EX_NOREDIRECTIONBITMAP, + WS_EX_TOPMOST, WS_EX_TRANSPARENT, WS_EX_WINDOWEDGE, WS_MAXIMIZE, WS_MAXIMIZEBOX, WS_MINIMIZE, + WS_MINIMIZEBOX, WS_OVERLAPPEDWINDOW, WS_POPUP, WS_SIZEBOX, WS_SYSMENU, WS_VISIBLE, +}; + +/// Contains information about states and the window that the callback is going to use. +pub(crate) struct WindowState { + pub mouse: MouseProperties, + + /// Used by `WM_GETMINMAXINFO`. + pub min_size: Option<Size>, + pub max_size: Option<Size>, + + pub resize_increments: Option<Size>, + + pub window_icon: Option<Icon>, + pub taskbar_icon: Option<Icon>, + + pub saved_window: Option<SavedWindow>, + pub scale_factor: f64, + + pub modifiers_state: ModifiersState, + pub fullscreen: Option<Fullscreen>, + pub current_theme: Theme, + pub preferred_theme: Option<Theme>, + + pub window_flags: WindowFlags, + + pub ime_state: ImeState, + pub ime_allowed: bool, + + // Used by WM_NCACTIVATE, WM_SETFOCUS and WM_KILLFOCUS + pub is_active: bool, + pub is_focused: bool, + + // Flag whether redraw was requested. + pub redraw_requested: bool, + + pub dragging: bool, + + pub skip_taskbar: bool, +} + +#[derive(Clone)] +pub struct SavedWindow { + pub placement: WINDOWPLACEMENT, +} + +#[derive(Clone)] +pub struct MouseProperties { + pub(crate) selected_cursor: SelectedCursor, + pub capture_count: u32, + cursor_flags: CursorFlags, + pub last_position: Option<PhysicalPosition<f64>>, +} + +bitflags! { + #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] + pub struct CursorFlags: u8 { + const GRABBED = 1 << 0; + const HIDDEN = 1 << 1; + const IN_WINDOW = 1 << 2; + const LOCKED = 1 << 3; + } +} +bitflags! { + #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] + pub struct WindowFlags: u32 { + const RESIZABLE = 1 << 0; + const MINIMIZABLE = 1 << 1; + const MAXIMIZABLE = 1 << 2; + const CLOSABLE = 1 << 3; + const VISIBLE = 1 << 4; + const ON_TASKBAR = 1 << 5; + const ALWAYS_ON_TOP = 1 << 6; + const ALWAYS_ON_BOTTOM = 1 << 7; + const NO_BACK_BUFFER = 1 << 8; + const TRANSPARENT = 1 << 9; + const CHILD = 1 << 10; + const MAXIMIZED = 1 << 11; + const POPUP = 1 << 12; + + /// Marker flag for fullscreen. Should always match `WindowState::fullscreen`, but is + /// included here to make masking easier. + const MARKER_EXCLUSIVE_FULLSCREEN = 1 << 13; + const MARKER_BORDERLESS_FULLSCREEN = 1 << 14; + + /// The `WM_SIZE` event contains some parameters that can effect the state of `WindowFlags`. + /// In most cases, it's okay to let those parameters change the state. However, when we're + /// running the `WindowFlags::apply_diff` function, we *don't* want those parameters to + /// effect our stored state, because the purpose of `apply_diff` is to update the actual + /// window's state to match our stored state. This controls whether to accept those changes. + const MARKER_RETAIN_STATE_ON_SIZE = 1 << 15; + + const MARKER_IN_SIZE_MOVE = 1 << 16; + + const MINIMIZED = 1 << 17; + + const IGNORE_CURSOR_EVENT = 1 << 18; + + /// Fully decorated window (incl. caption, border and drop shadow). + const MARKER_DECORATIONS = 1 << 19; + /// Drop shadow for undecorated windows. + const MARKER_UNDECORATED_SHADOW = 1 << 20; + + const MARKER_ACTIVATE = 1 << 21; + + const CLIP_CHILDREN = 1 << 22; + + const EXCLUSIVE_FULLSCREEN_OR_MASK = WindowFlags::ALWAYS_ON_TOP.bits(); + } +} + +#[derive(Eq, PartialEq)] +pub enum ImeState { + Disabled, + Enabled, + Preedit, +} + +impl WindowState { + pub(crate) fn new( + attributes: &WindowAttributes, + scale_factor: f64, + current_theme: Theme, + preferred_theme: Option<Theme>, + ) -> WindowState { + WindowState { + mouse: MouseProperties { + selected_cursor: SelectedCursor::default(), + capture_count: 0, + cursor_flags: CursorFlags::empty(), + last_position: None, + }, + + min_size: attributes.min_inner_size, + max_size: attributes.max_inner_size, + + resize_increments: attributes.resize_increments, + + window_icon: attributes.window_icon.clone(), + taskbar_icon: None, + + saved_window: None, + scale_factor, + + modifiers_state: ModifiersState::default(), + fullscreen: None, + current_theme, + preferred_theme, + window_flags: WindowFlags::empty(), + + ime_state: ImeState::Disabled, + ime_allowed: false, + + is_active: false, + is_focused: false, + redraw_requested: false, + + dragging: false, + + skip_taskbar: false, + } + } + + pub fn window_flags(&self) -> WindowFlags { + self.window_flags + } + + pub fn set_window_flags<F>(mut this: MutexGuard<'_, Self>, window: HWND, f: F) + where + F: FnOnce(&mut WindowFlags), + { + let old_flags = this.window_flags; + f(&mut this.window_flags); + let new_flags = this.window_flags; + + drop(this); + old_flags.apply_diff(window, new_flags); + } + + pub fn set_window_flags_in_place<F>(&mut self, f: F) + where + F: FnOnce(&mut WindowFlags), + { + f(&mut self.window_flags); + } + + pub fn has_active_focus(&self) -> bool { + self.is_active && self.is_focused + } + + // Updates is_active and returns whether active-focus state has changed + pub fn set_active(&mut self, is_active: bool) -> bool { + let old = self.has_active_focus(); + self.is_active = is_active; + old != self.has_active_focus() + } + + // Updates is_focused and returns whether active-focus state has changed + pub fn set_focused(&mut self, is_focused: bool) -> bool { + let old = self.has_active_focus(); + self.is_focused = is_focused; + old != self.has_active_focus() + } +} + +impl MouseProperties { + pub fn cursor_flags(&self) -> CursorFlags { + self.cursor_flags + } + + pub fn set_cursor_flags<F>(&mut self, window: HWND, f: F) -> Result<(), io::Error> + where + F: FnOnce(&mut CursorFlags), + { + let old_flags = self.cursor_flags; + f(&mut self.cursor_flags); + match self.cursor_flags.refresh_os_cursor(window) { + Ok(()) => (), + Err(e) => { + self.cursor_flags = old_flags; + return Err(e); + }, + } + + Ok(()) + } +} + +impl WindowFlags { + fn mask(mut self) -> WindowFlags { + if self.contains(WindowFlags::MARKER_EXCLUSIVE_FULLSCREEN) { + self |= WindowFlags::EXCLUSIVE_FULLSCREEN_OR_MASK; + } + self + } + + pub fn to_window_styles(self) -> (WINDOW_STYLE, WINDOW_EX_STYLE) { + // Required styles to properly support common window functionality like aero snap. + let mut style = WS_CAPTION | WS_BORDER | WS_CLIPSIBLINGS | WS_SYSMENU; + let mut style_ex = WS_EX_WINDOWEDGE | WS_EX_ACCEPTFILES; + + if self.contains(WindowFlags::RESIZABLE) { + style |= WS_SIZEBOX; + } + if self.contains(WindowFlags::MAXIMIZABLE) { + style |= WS_MAXIMIZEBOX; + } + if self.contains(WindowFlags::MINIMIZABLE) { + style |= WS_MINIMIZEBOX; + } + if self.contains(WindowFlags::VISIBLE) { + style |= WS_VISIBLE; + } + if self.contains(WindowFlags::ON_TASKBAR) { + style_ex |= WS_EX_APPWINDOW; + } + if self.contains(WindowFlags::ALWAYS_ON_TOP) { + style_ex |= WS_EX_TOPMOST; + } + if self.contains(WindowFlags::NO_BACK_BUFFER) { + style_ex |= WS_EX_NOREDIRECTIONBITMAP; + } + if self.contains(WindowFlags::CHILD) { + style |= WS_CHILD; // This is incompatible with WS_POPUP if that gets added eventually. + + // Remove decorations window styles for child + if !self.contains(WindowFlags::MARKER_DECORATIONS) { + style &= !(WS_CAPTION | WS_BORDER); + style_ex &= !WS_EX_WINDOWEDGE; + } + } + if self.contains(WindowFlags::POPUP) { + style |= WS_POPUP; + } + if self.contains(WindowFlags::MINIMIZED) { + style |= WS_MINIMIZE; + } + if self.contains(WindowFlags::MAXIMIZED) { + style |= WS_MAXIMIZE; + } + if self.contains(WindowFlags::IGNORE_CURSOR_EVENT) { + style_ex |= WS_EX_TRANSPARENT | WS_EX_LAYERED; + } + if self.contains(WindowFlags::CLIP_CHILDREN) { + style |= WS_CLIPCHILDREN; + } + + if self.intersects( + WindowFlags::MARKER_EXCLUSIVE_FULLSCREEN | WindowFlags::MARKER_BORDERLESS_FULLSCREEN, + ) { + style &= !WS_OVERLAPPEDWINDOW; + } + + (style, style_ex) + } + + /// Adjust the window client rectangle to the return value, if present. + fn apply_diff(mut self, window: HWND, mut new: WindowFlags) { + self = self.mask(); + new = new.mask(); + + let mut diff = self ^ new; + + if diff == WindowFlags::empty() { + return; + } + + if new.contains(WindowFlags::VISIBLE) { + let flag = if !self.contains(WindowFlags::MARKER_ACTIVATE) { + self.set(WindowFlags::MARKER_ACTIVATE, true); + SW_SHOWNOACTIVATE + } else { + SW_SHOW + }; + unsafe { + ShowWindow(window, flag); + } + } + + if diff.intersects(WindowFlags::ALWAYS_ON_TOP | WindowFlags::ALWAYS_ON_BOTTOM) { + unsafe { + SetWindowPos( + window, + match ( + new.contains(WindowFlags::ALWAYS_ON_TOP), + new.contains(WindowFlags::ALWAYS_ON_BOTTOM), + ) { + (true, false) => HWND_TOPMOST, + (false, false) => HWND_NOTOPMOST, + (false, true) => HWND_BOTTOM, + (true, true) => unreachable!(), + }, + 0, + 0, + 0, + 0, + SWP_ASYNCWINDOWPOS | SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE, + ); + InvalidateRgn(window, 0, false.into()); + } + } + + if diff.contains(WindowFlags::MAXIMIZED) || new.contains(WindowFlags::MAXIMIZED) { + unsafe { + ShowWindow(window, match new.contains(WindowFlags::MAXIMIZED) { + true => SW_MAXIMIZE, + false => SW_RESTORE, + }); + } + } + + // Minimize operations should execute after maximize for proper window animations + if diff.contains(WindowFlags::MINIMIZED) { + unsafe { + ShowWindow(window, match new.contains(WindowFlags::MINIMIZED) { + true => SW_MINIMIZE, + false => SW_RESTORE, + }); + } + + diff.remove(WindowFlags::MINIMIZED); + } + + // A new window's system menu has Close enabled: the menu (`GetSystemMenu` makes the + // window its own copy, about 1,200 us before its first frame) is touched only to change it. + if diff.contains(WindowFlags::CLOSABLE) && !(self.is_empty() && new.contains(WindowFlags::CLOSABLE)) { + let flags = MF_BYCOMMAND + | if new.contains(WindowFlags::CLOSABLE) { MF_ENABLED } else { MF_DISABLED }; + + unsafe { + EnableMenuItem(GetSystemMenu(window, 0), SC_CLOSE, flags); + } + } + + if !new.contains(WindowFlags::VISIBLE) { + unsafe { + ShowWindow(window, SW_HIDE); + } + } + + // A show or a hide alone: ShowWindow set WS_VISIBLE itself. Writing the styles again and + // refreshing the frame (SWP_FRAMECHANGED) cost a window's first show about 2,200 us. + if diff == WindowFlags::VISIBLE { + return; + } + + if diff != WindowFlags::empty() { + let (style, style_ex) = new.to_window_styles(); + + unsafe { + SendMessageW(window, event_loop::SET_RETAIN_STATE_ON_SIZE_MSG_ID.get(), 1, 0); + + // This condition is necessary to avoid having an unrestorable window + if !new.contains(WindowFlags::MINIMIZED) { + SetWindowLongW(window, GWL_STYLE, style as i32); + SetWindowLongW(window, GWL_EXSTYLE, style_ex as i32); + } + + let mut flags = SWP_NOZORDER | SWP_NOMOVE | SWP_NOSIZE | SWP_FRAMECHANGED; + + // We generally don't want style changes here to affect window + // focus, but for fullscreen windows they must be activated + // (i.e. focused) so that they appear on top of the taskbar + if !new.contains(WindowFlags::MARKER_EXCLUSIVE_FULLSCREEN) + && !new.contains(WindowFlags::MARKER_BORDERLESS_FULLSCREEN) + { + flags |= SWP_NOACTIVATE; + } + + // Refresh the window frame + SetWindowPos(window, 0, 0, 0, 0, 0, flags); + SendMessageW(window, event_loop::SET_RETAIN_STATE_ON_SIZE_MSG_ID.get(), 0, 0); + } + } + } + + pub fn adjust_rect(self, hwnd: HWND, mut rect: RECT) -> Result<RECT, io::Error> { + unsafe { + let mut style = GetWindowLongW(hwnd, GWL_STYLE) as u32; + let style_ex = GetWindowLongW(hwnd, GWL_EXSTYLE) as u32; + + // Frameless style implemented by manually overriding the non-client area in + // `WM_NCCALCSIZE`. + if !self.contains(WindowFlags::MARKER_DECORATIONS) { + style &= !(WS_CAPTION | WS_SIZEBOX); + } + + util::win_to_err({ + let b_menu = GetMenu(hwnd) != 0; + if let (Some(get_dpi_for_window), Some(adjust_window_rect_ex_for_dpi)) = + (*util::GET_DPI_FOR_WINDOW, *util::ADJUST_WINDOW_RECT_EX_FOR_DPI) + { + let dpi = get_dpi_for_window(hwnd); + adjust_window_rect_ex_for_dpi(&mut rect, style, b_menu.into(), style_ex, dpi) + } else { + AdjustWindowRectEx(&mut rect, style, b_menu.into(), style_ex) + } + })?; + Ok(rect) + } + } + + pub fn adjust_size(self, hwnd: HWND, size: PhysicalSize<u32>) -> PhysicalSize<u32> { + let (width, height): (u32, u32) = size.into(); + let rect = RECT { left: 0, right: width as i32, top: 0, bottom: height as i32 }; + let rect = self.adjust_rect(hwnd, rect).unwrap_or(rect); + + let outer_x = (rect.right - rect.left).abs(); + let outer_y = (rect.top - rect.bottom).abs(); + + PhysicalSize::new(outer_x as _, outer_y as _) + } + + pub fn set_size(self, hwnd: HWND, size: PhysicalSize<u32>) { + unsafe { + let (width, height): (u32, u32) = self.adjust_size(hwnd, size).into(); + SetWindowPos( + hwnd, + 0, + 0, + 0, + width as _, + height as _, + SWP_ASYNCWINDOWPOS | SWP_NOZORDER | SWP_NOREPOSITION | SWP_NOMOVE | SWP_NOACTIVATE, + ); + InvalidateRgn(hwnd, 0, false.into()); + } + } +} + +impl CursorFlags { + fn refresh_os_cursor(self, window: HWND) -> Result<(), io::Error> { + let client_rect = util::WindowArea::Inner.get_rect(window)?; + + if util::is_focused(window) { + let cursor_clip = match self.contains(CursorFlags::GRABBED) { + true => { + if self.contains(CursorFlags::LOCKED) { + if let Ok(pos) = util::get_cursor_position() { + Some(RECT { + left: pos.x, + right: pos.x + 1, + top: pos.y, + bottom: pos.y + 1, + }) + } else { + // If lock is applied while the cursor is not available, lock it to the + // middle of the window. + let cx = (client_rect.left + client_rect.right) / 2; + let cy = (client_rect.top + client_rect.bottom) / 2; + Some(RECT { left: cx, right: cx + 1, top: cy, bottom: cy + 1 }) + } + } else if self.contains(CursorFlags::HIDDEN) { + // Confine the cursor to the center of the window if the cursor is hidden. + // This avoids problems with the cursor activating + // the taskbar if the window borders or overlaps that. + let cx = (client_rect.left + client_rect.right) / 2; + let cy = (client_rect.top + client_rect.bottom) / 2; + Some(RECT { left: cx, right: cx + 1, top: cy, bottom: cy + 1 }) + } else { + Some(client_rect) + } + }, + false => None, + }; + + let rect_to_tuple = |rect: RECT| (rect.left, rect.top, rect.right, rect.bottom); + let active_cursor_clip = rect_to_tuple(util::get_cursor_clip()?); + let desktop_rect = rect_to_tuple(util::get_desktop_rect()); + + let active_cursor_clip = match desktop_rect == active_cursor_clip { + true => None, + false => Some(active_cursor_clip), + }; + + // We do this check because calling `set_cursor_clip` incessantly will flood the event + // loop with `WM_MOUSEMOVE` events, and `refresh_os_cursor` is called by + // `set_cursor_flags` which at times gets called once every iteration of the + // eventloop. + if active_cursor_clip != cursor_clip.map(rect_to_tuple) { + util::set_cursor_clip(cursor_clip)?; + } + } + + let cursor_in_client = self.contains(CursorFlags::IN_WINDOW); + if cursor_in_client { + util::set_cursor_hidden(self.contains(CursorFlags::HIDDEN)); + } else { + util::set_cursor_hidden(false); + } + + Ok(()) + } +} diff --git a/app/vendor/rune/vendor/winit/src/utils.rs b/app/vendor/rune/vendor/winit/src/utils.rs new file mode 100644 index 0000000..d9631ed --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/utils.rs @@ -0,0 +1,28 @@ +// A poly-fill for `lazy_cell` +// Replace with std::sync::LazyLock when https://github.com/rust-lang/rust/issues/109736 is stabilized. + +// This isn't used on every platform, which can come up as dead code warnings. +#![allow(dead_code)] + +use std::ops::Deref; +use std::sync::OnceLock; + +pub(crate) struct Lazy<T> { + cell: OnceLock<T>, + init: fn() -> T, +} + +impl<T> Lazy<T> { + pub const fn new(f: fn() -> T) -> Self { + Self { cell: OnceLock::new(), init: f } + } +} + +impl<T> Deref for Lazy<T> { + type Target = T; + + #[inline] + fn deref(&self) -> &'_ T { + self.cell.get_or_init(self.init) + } +} diff --git a/app/vendor/rune/vendor/winit/src/window.rs b/app/vendor/rune/vendor/winit/src/window.rs new file mode 100644 index 0000000..e0158ef --- /dev/null +++ b/app/vendor/rune/vendor/winit/src/window.rs @@ -0,0 +1,1876 @@ +//! The [`Window`] struct and associated types. +use std::fmt; + +use crate::dpi::{PhysicalPosition, PhysicalSize, Position, Size}; +use crate::error::{ExternalError, NotSupportedError}; +use crate::monitor::{MonitorHandle, VideoModeHandle}; +use crate::platform_impl::{self, PlatformSpecificWindowAttributes}; + +pub use crate::cursor::{BadImage, Cursor, CustomCursor, CustomCursorSource, MAX_CURSOR_SIZE}; +pub use crate::icon::{BadIcon, Icon}; + +#[doc(inline)] +pub use cursor_icon::{CursorIcon, ParseError as CursorIconParseError}; +#[cfg(feature = "serde")] +use serde::{Deserialize, Serialize}; + +/// Represents a window. +/// +/// The window is closed when dropped. +/// +/// ## Threading +/// +/// This is `Send + Sync`, meaning that it can be freely used from other +/// threads. +/// +/// However, some platforms (macOS, Web and iOS) only allow user interface +/// interactions on the main thread, so on those platforms, if you use the +/// window from a thread other than the main, the code is scheduled to run on +/// the main thread, and your thread may be blocked until that completes. +/// +/// ## Platform-specific +/// +/// **Web:** The [`Window`], which is represented by a `HTMLElementCanvas`, can +/// not be closed by dropping the [`Window`]. +pub struct Window { + pub(crate) window: platform_impl::Window, +} + +impl fmt::Debug for Window { + fn fmt(&self, fmtr: &mut fmt::Formatter<'_>) -> fmt::Result { + fmtr.pad("Window { .. }") + } +} + +impl Drop for Window { + /// This will close the [`Window`]. + /// + /// See [`Window`] for more details. + fn drop(&mut self) { + self.window.maybe_wait_on_main(|w| { + // If the window is in exclusive fullscreen, we must restore the desktop + // video mode (generally this would be done on application exit, but + // closing the window doesn't necessarily always mean application exit, + // such as when there are multiple windows) + if let Some(Fullscreen::Exclusive(_)) = w.fullscreen().map(|f| f.into()) { + w.set_fullscreen(None); + } + }) + } +} + +/// Identifier of a window. Unique for each window. +/// +/// Can be obtained with [`window.id()`][`Window::id`]. +/// +/// Whenever you receive an event specific to a window, this event contains a `WindowId` which you +/// can then compare to the ids of your windows. +#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub struct WindowId(pub(crate) platform_impl::WindowId); + +impl WindowId { + /// Returns a dummy id, useful for unit testing. + /// + /// # Notes + /// + /// The only guarantee made about the return value of this function is that + /// it will always be equal to itself and to future values returned by this function. + /// No other guarantees are made. This may be equal to a real [`WindowId`]. + pub const fn dummy() -> Self { + WindowId(platform_impl::WindowId::dummy()) + } +} + +impl fmt::Debug for WindowId { + fn fmt(&self, fmtr: &mut fmt::Formatter<'_>) -> fmt::Result { + self.0.fmt(fmtr) + } +} + +impl From<WindowId> for u64 { + fn from(window_id: WindowId) -> Self { + window_id.0.into() + } +} + +impl From<u64> for WindowId { + fn from(raw_id: u64) -> Self { + Self(raw_id.into()) + } +} + +/// Attributes used when creating a window. +#[derive(Debug, Clone)] +pub struct WindowAttributes { + pub inner_size: Option<Size>, + pub min_inner_size: Option<Size>, + pub max_inner_size: Option<Size>, + pub position: Option<Position>, + pub resizable: bool, + pub enabled_buttons: WindowButtons, + pub title: String, + pub maximized: bool, + pub visible: bool, + pub transparent: bool, + pub blur: bool, + pub decorations: bool, + pub window_icon: Option<Icon>, + pub preferred_theme: Option<Theme>, + pub resize_increments: Option<Size>, + pub content_protected: bool, + pub window_level: WindowLevel, + pub active: bool, + pub cursor: Cursor, + #[cfg(feature = "rwh_06")] + pub(crate) parent_window: Option<SendSyncRawWindowHandle>, + pub fullscreen: Option<Fullscreen>, + // Platform-specific configuration. + #[allow(dead_code)] + pub(crate) platform_specific: PlatformSpecificWindowAttributes, +} + +impl Default for WindowAttributes { + #[inline] + fn default() -> WindowAttributes { + WindowAttributes { + inner_size: None, + min_inner_size: None, + max_inner_size: None, + position: None, + resizable: true, + enabled_buttons: WindowButtons::all(), + title: "winit window".to_owned(), + maximized: false, + fullscreen: None, + visible: true, + transparent: false, + blur: false, + decorations: true, + window_level: Default::default(), + window_icon: None, + preferred_theme: None, + resize_increments: None, + content_protected: false, + cursor: Cursor::default(), + #[cfg(feature = "rwh_06")] + parent_window: None, + active: true, + platform_specific: Default::default(), + } + } +} + +/// Wrapper for [`rwh_06::RawWindowHandle`] for [`WindowAttributes::parent_window`]. +/// +/// # Safety +/// +/// The user has to account for that when using [`WindowAttributes::with_parent_window()`], +/// which is `unsafe`. +#[derive(Debug, Clone)] +#[cfg(feature = "rwh_06")] +pub(crate) struct SendSyncRawWindowHandle(pub(crate) rwh_06::RawWindowHandle); + +#[cfg(feature = "rwh_06")] +unsafe impl Send for SendSyncRawWindowHandle {} +#[cfg(feature = "rwh_06")] +unsafe impl Sync for SendSyncRawWindowHandle {} + +impl WindowAttributes { + /// Initializes new attributes with default values. + #[inline] + #[deprecated = "use `Window::default_attributes` instead"] + pub fn new() -> Self { + Default::default() + } +} + +impl WindowAttributes { + /// Get the parent window stored on the attributes. + #[cfg(feature = "rwh_06")] + pub fn parent_window(&self) -> Option<&rwh_06::RawWindowHandle> { + self.parent_window.as_ref().map(|handle| &handle.0) + } + + /// Requests the window to be of specific dimensions. + /// + /// If this is not set, some platform-specific dimensions will be used. + /// + /// See [`Window::request_inner_size`] for details. + #[inline] + pub fn with_inner_size<S: Into<Size>>(mut self, size: S) -> Self { + self.inner_size = Some(size.into()); + self + } + + /// Sets the minimum dimensions a window can have. + /// + /// If this is not set, the window will have no minimum dimensions (aside + /// from reserved). + /// + /// See [`Window::set_min_inner_size`] for details. + #[inline] + pub fn with_min_inner_size<S: Into<Size>>(mut self, min_size: S) -> Self { + self.min_inner_size = Some(min_size.into()); + self + } + + /// Sets the maximum dimensions a window can have. + /// + /// If this is not set, the window will have no maximum or will be set to + /// the primary monitor's dimensions by the platform. + /// + /// See [`Window::set_max_inner_size`] for details. + #[inline] + pub fn with_max_inner_size<S: Into<Size>>(mut self, max_size: S) -> Self { + self.max_inner_size = Some(max_size.into()); + self + } + + /// Sets a desired initial position for the window. + /// + /// If this is not set, some platform-specific position will be chosen. + /// + /// See [`Window::set_outer_position`] for details. + /// + /// ## Platform-specific + /// + /// - **macOS:** The top left corner position of the window content, the window's "inner" + /// position. The window title bar will be placed above it. The window will be positioned such + /// that it fits on screen, maintaining set `inner_size` if any. If you need to precisely + /// position the top left corner of the whole window you have to use + /// [`Window::set_outer_position`] after creating the window. + /// - **Windows:** The top left corner position of the window title bar, the window's "outer" + /// position. There may be a small gap between this position and the window due to the + /// specifics of the Window Manager. + /// - **X11:** The top left corner of the window, the window's "outer" position. + /// - **Others:** Ignored. + #[inline] + pub fn with_position<P: Into<Position>>(mut self, position: P) -> Self { + self.position = Some(position.into()); + self + } + + /// Sets whether the window is resizable or not. + /// + /// The default is `true`. + /// + /// See [`Window::set_resizable`] for details. + #[inline] + pub fn with_resizable(mut self, resizable: bool) -> Self { + self.resizable = resizable; + self + } + + /// Sets the enabled window buttons. + /// + /// The default is [`WindowButtons::all`] + /// + /// See [`Window::set_enabled_buttons`] for details. + #[inline] + pub fn with_enabled_buttons(mut self, buttons: WindowButtons) -> Self { + self.enabled_buttons = buttons; + self + } + + /// Sets the initial title of the window in the title bar. + /// + /// The default is `"winit window"`. + /// + /// See [`Window::set_title`] for details. + #[inline] + pub fn with_title<T: Into<String>>(mut self, title: T) -> Self { + self.title = title.into(); + self + } + + /// Sets whether the window should be put into fullscreen upon creation. + /// + /// The default is `None`. + /// + /// See [`Window::set_fullscreen`] for details. + #[inline] + pub fn with_fullscreen(mut self, fullscreen: Option<Fullscreen>) -> Self { + self.fullscreen = fullscreen; + self + } + + /// Request that the window is maximized upon creation. + /// + /// The default is `false`. + /// + /// See [`Window::set_maximized`] for details. + #[inline] + pub fn with_maximized(mut self, maximized: bool) -> Self { + self.maximized = maximized; + self + } + + /// Sets whether the window will be initially visible or hidden. + /// + /// The default is to show the window. + /// + /// See [`Window::set_visible`] for details. + #[inline] + pub fn with_visible(mut self, visible: bool) -> Self { + self.visible = visible; + self + } + + /// Sets whether the background of the window should be transparent. + /// + /// If this is `true`, writing colors with alpha values different than + /// `1.0` will produce a transparent window. On some platforms this + /// is more of a hint for the system and you'd still have the alpha + /// buffer. To control it see [`Window::set_transparent`]. + /// + /// The default is `false`. + #[inline] + pub fn with_transparent(mut self, transparent: bool) -> Self { + self.transparent = transparent; + self + } + + /// Sets whether the background of the window should be blurred by the system. + /// + /// The default is `false`. + /// + /// See [`Window::set_blur`] for details. + #[inline] + pub fn with_blur(mut self, blur: bool) -> Self { + self.blur = blur; + self + } + + /// Get whether the window will support transparency. + #[inline] + pub fn transparent(&self) -> bool { + self.transparent + } + + /// Sets whether the window should have a border, a title bar, etc. + /// + /// The default is `true`. + /// + /// See [`Window::set_decorations`] for details. + #[inline] + pub fn with_decorations(mut self, decorations: bool) -> Self { + self.decorations = decorations; + self + } + + /// Sets the window level. + /// + /// This is just a hint to the OS, and the system could ignore it. + /// + /// The default is [`WindowLevel::Normal`]. + /// + /// See [`WindowLevel`] for details. + #[inline] + pub fn with_window_level(mut self, level: WindowLevel) -> Self { + self.window_level = level; + self + } + + /// Sets the window icon. + /// + /// The default is `None`. + /// + /// See [`Window::set_window_icon`] for details. + #[inline] + pub fn with_window_icon(mut self, window_icon: Option<Icon>) -> Self { + self.window_icon = window_icon; + self + } + + /// Sets a specific theme for the window. + /// + /// If `None` is provided, the window will use the system theme. + /// + /// The default is `None`. + /// + /// ## Platform-specific + /// + /// - **Wayland:** This controls only CSD. When using `None` it'll try to use dbus to get the + /// system preference. When explicit theme is used, this will avoid dbus all together. + /// - **x11:** Build window with `_GTK_THEME_VARIANT` hint set to `dark` or `light`. + /// - **iOS / Android / Web / x11 / Orbital:** Ignored. + #[inline] + pub fn with_theme(mut self, theme: Option<Theme>) -> Self { + self.preferred_theme = theme; + self + } + + /// Build window with resize increments hint. + /// + /// The default is `None`. + /// + /// See [`Window::set_resize_increments`] for details. + #[inline] + pub fn with_resize_increments<S: Into<Size>>(mut self, resize_increments: S) -> Self { + self.resize_increments = Some(resize_increments.into()); + self + } + + /// Prevents the window contents from being captured by other apps. + /// + /// The default is `false`. + /// + /// ## Platform-specific + /// + /// - **macOS**: if `false`, [`NSWindowSharingNone`] is used but doesn't completely prevent all + /// apps from reading the window content, for instance, QuickTime. + /// - **iOS / Android / Web / x11 / Orbital:** Ignored. + /// + /// [`NSWindowSharingNone`]: https://developer.apple.com/documentation/appkit/nswindowsharingtype/nswindowsharingnone + #[inline] + pub fn with_content_protected(mut self, protected: bool) -> Self { + self.content_protected = protected; + self + } + + /// Whether the window will be initially focused or not. + /// + /// The window should be assumed as not focused by default + /// following by the [`WindowEvent::Focused`]. + /// + /// ## Platform-specific: + /// + /// **Android / iOS / X11 / Wayland / Orbital:** Unsupported. + /// + /// [`WindowEvent::Focused`]: crate::event::WindowEvent::Focused. + #[inline] + pub fn with_active(mut self, active: bool) -> Self { + self.active = active; + self + } + + /// Modifies the cursor icon of the window. + /// + /// The default is [`CursorIcon::Default`]. + /// + /// See [`Window::set_cursor()`] for more details. + #[inline] + pub fn with_cursor(mut self, cursor: impl Into<Cursor>) -> Self { + self.cursor = cursor.into(); + self + } + + /// Build window with parent window. + /// + /// The default is `None`. + /// + /// ## Safety + /// + /// `parent_window` must be a valid window handle. + /// + /// ## Platform-specific + /// + /// - **Windows** : A child window has the WS_CHILD style and is confined + /// to the client area of its parent window. For more information, see + /// <https://docs.microsoft.com/en-us/windows/win32/winmsg/window-features#child-windows> + /// - **X11**: A child window is confined to the client area of its parent window. + /// - **Android / iOS / Wayland / Web:** Unsupported. + #[cfg(feature = "rwh_06")] + #[inline] + pub unsafe fn with_parent_window( + mut self, + parent_window: Option<rwh_06::RawWindowHandle>, + ) -> Self { + self.parent_window = parent_window.map(SendSyncRawWindowHandle); + self + } +} + +/// Base Window functions. +impl Window { + /// Create a new [`WindowAttributes`] which allows modifying the window's attributes before + /// creation. + #[inline] + pub fn default_attributes() -> WindowAttributes { + WindowAttributes::default() + } + + /// Returns an identifier unique to the window. + #[inline] + pub fn id(&self) -> WindowId { + let _span = tracing::debug_span!("winit::Window::id",).entered(); + + self.window.maybe_wait_on_main(|w| WindowId(w.id())) + } + + /// Returns the scale factor that can be used to map logical pixels to physical pixels, and + /// vice versa. + /// + /// Note that this value can change depending on user action (for example if the window is + /// moved to another screen); as such, tracking [`WindowEvent::ScaleFactorChanged`] events is + /// the most robust way to track the DPI you need to use to draw. + /// + /// This value may differ from [`MonitorHandle::scale_factor`]. + /// + /// See the [`dpi`] crate for more information. + /// + /// ## Platform-specific + /// + /// The scale factor is calculated differently on different platforms: + /// + /// - **Windows:** On Windows 8 and 10, per-monitor scaling is readily configured by users from + /// the display settings. While users are free to select any option they want, they're only + /// given a selection of "nice" scale factors, i.e. 1.0, 1.25, 1.5... on Windows 7. The scale + /// factor is global and changing it requires logging out. See [this article][windows_1] for + /// technical details. + /// - **macOS:** Recent macOS versions allow the user to change the scaling factor for specific + /// displays. When available, the user may pick a per-monitor scaling factor from a set of + /// pre-defined settings. All "retina displays" have a scaling factor above 1.0 by default, + /// but the specific value varies across devices. + /// - **X11:** Many man-hours have been spent trying to figure out how to handle DPI in X11. + /// Winit currently uses a three-pronged approach: + /// + Use the value in the `WINIT_X11_SCALE_FACTOR` environment variable if present. + /// + If not present, use the value set in `Xft.dpi` in Xresources. + /// + Otherwise, calculate the scale factor based on the millimeter monitor dimensions + /// provided by XRandR. + /// + /// If `WINIT_X11_SCALE_FACTOR` is set to `randr`, it'll ignore the `Xft.dpi` field and use + /// the XRandR scaling method. Generally speaking, you should try to configure the + /// standard system variables to do what you want before resorting to + /// `WINIT_X11_SCALE_FACTOR`. + /// - **Wayland:** The scale factor is suggested by the compositor for each window individually + /// by using the wp-fractional-scale protocol if available. Falls back to integer-scale + /// factors otherwise. + /// + /// The monitor scale factor may differ from the window scale factor. + /// - **iOS:** Scale factors are set by Apple to the value that best suits the device, and range + /// from `1.0` to `3.0`. See [this article][apple_1] and [this article][apple_2] for more + /// information. + /// + /// This uses the underlying `UIView`'s [`contentScaleFactor`]. + /// - **Android:** Scale factors are set by the manufacturer to the value that best suits the + /// device, and range from `1.0` to `4.0`. See [this article][android_1] for more information. + /// + /// This is currently unimplemented, and this function always returns 1.0. + /// - **Web:** The scale factor is the ratio between CSS pixels and the physical device pixels. + /// In other words, it is the value of [`window.devicePixelRatio`][web_1]. It is affected by + /// both the screen scaling and the browser zoom level and can go below `1.0`. + /// - **Orbital:** This is currently unimplemented, and this function always returns 1.0. + /// + /// [`WindowEvent::ScaleFactorChanged`]: crate::event::WindowEvent::ScaleFactorChanged + /// [windows_1]: https://docs.microsoft.com/en-us/windows/win32/hidpi/high-dpi-desktop-application-development-on-windows + /// [apple_1]: https://developer.apple.com/library/archive/documentation/DeviceInformation/Reference/iOSDeviceCompatibility/Displays/Displays.html + /// [apple_2]: https://developer.apple.com/design/human-interface-guidelines/macos/icons-and-images/image-size-and-resolution/ + /// [android_1]: https://developer.android.com/training/multiscreen/screendensities + /// [web_1]: https://developer.mozilla.org/en-US/docs/Web/API/Window/devicePixelRatio + /// [`contentScaleFactor`]: https://developer.apple.com/documentation/uikit/uiview/1622657-contentscalefactor?language=objc + #[inline] + pub fn scale_factor(&self) -> f64 { + let _span = tracing::debug_span!("winit::Window::scale_factor",).entered(); + + self.window.maybe_wait_on_main(|w| w.scale_factor()) + } + + /// Queues a [`WindowEvent::RedrawRequested`] event to be emitted that aligns with the windowing + /// system drawing loop. + /// + /// This is the **strongly encouraged** method of redrawing windows, as it can integrate with + /// OS-requested redraws (e.g. when a window gets resized). To improve the event delivery + /// consider using [`Window::pre_present_notify`] as described in docs. + /// + /// Applications should always aim to redraw whenever they receive a `RedrawRequested` event. + /// + /// There are no strong guarantees about when exactly a `RedrawRequest` event will be emitted + /// with respect to other events, since the requirements can vary significantly between + /// windowing systems. + /// + /// However as the event aligns with the windowing system drawing loop, it may not arrive in + /// same or even next event loop iteration. + /// + /// ## Platform-specific + /// + /// - **Windows** This API uses `RedrawWindow` to request a `WM_PAINT` message and + /// `RedrawRequested` is emitted in sync with any `WM_PAINT` messages. + /// - **iOS:** Can only be called on the main thread. + /// - **Wayland:** The events are aligned with the frame callbacks when + /// [`Window::pre_present_notify`] is used. + /// - **Web:** [`WindowEvent::RedrawRequested`] will be aligned with the + /// `requestAnimationFrame`. + /// + /// [`WindowEvent::RedrawRequested`]: crate::event::WindowEvent::RedrawRequested + #[inline] + pub fn request_redraw(&self) { + let _span = tracing::debug_span!("winit::Window::request_redraw",).entered(); + + self.window.maybe_queue_on_main(|w| w.request_redraw()) + } + + /// Notify the windowing system before presenting to the window. + /// + /// You should call this event after your drawing operations, but before you submit + /// the buffer to the display or commit your drawings. Doing so will help winit to properly + /// schedule and make assumptions about its internal state. For example, it could properly + /// throttle [`WindowEvent::RedrawRequested`]. + /// + /// ## Example + /// + /// This example illustrates how it looks with OpenGL, but it applies to other graphics + /// APIs and software rendering. + /// + /// ```no_run + /// # use winit::window::Window; + /// # fn swap_buffers() {} + /// # fn scope(window: &Window) { + /// // Do the actual drawing with OpenGL. + /// + /// // Notify winit that we're about to submit buffer to the windowing system. + /// window.pre_present_notify(); + /// + /// // Submit buffer to the windowing system. + /// swap_buffers(); + /// # } + /// ``` + /// + /// ## Platform-specific + /// + /// - **Android / iOS / X11 / Web / Windows / macOS / Orbital:** Unsupported. + /// - **Wayland:** Schedules a frame callback to throttle [`WindowEvent::RedrawRequested`]. + /// + /// [`WindowEvent::RedrawRequested`]: crate::event::WindowEvent::RedrawRequested + #[inline] + pub fn pre_present_notify(&self) { + let _span = tracing::debug_span!("winit::Window::pre_present_notify",).entered(); + + self.window.maybe_queue_on_main(|w| w.pre_present_notify()); + } + + /// Reset the dead key state of the keyboard. + /// + /// This is useful when a dead key is bound to trigger an action. Then + /// this function can be called to reset the dead key state so that + /// follow-up text input won't be affected by the dead key. + /// + /// ## Platform-specific + /// - **Web, macOS:** Does nothing + // --------------------------- + // Developers' Note: If this cannot be implemented on every desktop platform + // at least, then this function should be provided through a platform specific + // extension trait + pub fn reset_dead_keys(&self) { + let _span = tracing::debug_span!("winit::Window::reset_dead_keys",).entered(); + + self.window.maybe_queue_on_main(|w| w.reset_dead_keys()) + } +} + +/// Position and size functions. +impl Window { + /// Returns the position of the top-left hand corner of the window's client area relative to the + /// top-left hand corner of the desktop. + /// + /// The same conditions that apply to [`Window::outer_position`] apply to this method. + /// + /// ## Platform-specific + /// + /// - **iOS:** Can only be called on the main thread. Returns the top left coordinates of the + /// window's [safe area] in the screen space coordinate system. + /// - **Web:** Returns the top-left coordinates relative to the viewport. _Note: this returns + /// the same value as [`Window::outer_position`]._ + /// - **Android / Wayland:** Always returns [`NotSupportedError`]. + /// + /// [safe area]: https://developer.apple.com/documentation/uikit/uiview/2891103-safeareainsets?language=objc + #[inline] + pub fn inner_position(&self) -> Result<PhysicalPosition<i32>, NotSupportedError> { + let _span = tracing::debug_span!("winit::Window::inner_position",).entered(); + + self.window.maybe_wait_on_main(|w| w.inner_position()) + } + + /// Returns the position of the top-left hand corner of the window relative to the + /// top-left hand corner of the desktop. + /// + /// Note that the top-left hand corner of the desktop is not necessarily the same as + /// the screen. If the user uses a desktop with multiple monitors, the top-left hand corner + /// of the desktop is the top-left hand corner of the monitor at the top-left of the desktop. + /// + /// The coordinates can be negative if the top-left hand corner of the window is outside + /// of the visible screen region. + /// + /// ## Platform-specific + /// + /// - **iOS:** Can only be called on the main thread. Returns the top left coordinates of the + /// window in the screen space coordinate system. + /// - **Web:** Returns the top-left coordinates relative to the viewport. + /// - **Android / Wayland:** Always returns [`NotSupportedError`]. + #[inline] + pub fn outer_position(&self) -> Result<PhysicalPosition<i32>, NotSupportedError> { + let _span = tracing::debug_span!("winit::Window::outer_position",).entered(); + + self.window.maybe_wait_on_main(|w| w.outer_position()) + } + + /// Modifies the position of the window. + /// + /// See [`Window::outer_position`] for more information about the coordinates. + /// This automatically un-maximizes the window if it's maximized. + /// + /// ```no_run + /// # use winit::dpi::{LogicalPosition, PhysicalPosition}; + /// # use winit::window::Window; + /// # fn scope(window: &Window) { + /// // Specify the position in logical dimensions like this: + /// window.set_outer_position(LogicalPosition::new(400.0, 200.0)); + /// + /// // Or specify the position in physical dimensions like this: + /// window.set_outer_position(PhysicalPosition::new(400, 200)); + /// # } + /// ``` + /// + /// ## Platform-specific + /// + /// - **iOS:** Can only be called on the main thread. Sets the top left coordinates of the + /// window in the screen space coordinate system. + /// - **Web:** Sets the top-left coordinates relative to the viewport. Doesn't account for CSS + /// [`transform`]. + /// - **Android / Wayland:** Unsupported. + /// + /// [`transform`]: https://developer.mozilla.org/en-US/docs/Web/CSS/transform + #[inline] + pub fn set_outer_position<P: Into<Position>>(&self, position: P) { + let position = position.into(); + let _span = tracing::debug_span!( + "winit::Window::set_outer_position", + position = ?position + ) + .entered(); + + self.window.maybe_queue_on_main(move |w| w.set_outer_position(position)) + } + + /// Returns the physical size of the window's client area. + /// + /// The client area is the content of the window, excluding the title bar and borders. + /// + /// ## Platform-specific + /// + /// - **iOS:** Can only be called on the main thread. Returns the `PhysicalSize` of the window's + /// [safe area] in screen space coordinates. + /// - **Web:** Returns the size of the canvas element. Doesn't account for CSS [`transform`]. + /// + /// [safe area]: https://developer.apple.com/documentation/uikit/uiview/2891103-safeareainsets?language=objc + /// [`transform`]: https://developer.mozilla.org/en-US/docs/Web/CSS/transform + #[inline] + pub fn inner_size(&self) -> PhysicalSize<u32> { + let _span = tracing::debug_span!("winit::Window::inner_size",).entered(); + + self.window.maybe_wait_on_main(|w| w.inner_size()) + } + + /// Request the new size for the window. + /// + /// On platforms where the size is entirely controlled by the user the + /// applied size will be returned immediately, resize event in such case + /// may not be generated. + /// + /// On platforms where resizing is disallowed by the windowing system, the current + /// inner size is returned immediately, and the user one is ignored. + /// + /// When `None` is returned, it means that the request went to the display system, + /// and the actual size will be delivered later with the [`WindowEvent::Resized`]. + /// + /// See [`Window::inner_size`] for more information about the values. + /// + /// The request could automatically un-maximize the window if it's maximized. + /// + /// ```no_run + /// # use winit::dpi::{LogicalSize, PhysicalSize}; + /// # use winit::window::Window; + /// # fn scope(window: &Window) { + /// // Specify the size in logical dimensions like this: + /// let _ = window.request_inner_size(LogicalSize::new(400.0, 200.0)); + /// + /// // Or specify the size in physical dimensions like this: + /// let _ = window.request_inner_size(PhysicalSize::new(400, 200)); + /// # } + /// ``` + /// + /// ## Platform-specific + /// + /// - **Web:** Sets the size of the canvas element. Doesn't account for CSS [`transform`]. + /// + /// [`WindowEvent::Resized`]: crate::event::WindowEvent::Resized + /// [`transform`]: https://developer.mozilla.org/en-US/docs/Web/CSS/transform + #[inline] + #[must_use] + pub fn request_inner_size<S: Into<Size>>(&self, size: S) -> Option<PhysicalSize<u32>> { + let size = size.into(); + let _span = tracing::debug_span!( + "winit::Window::request_inner_size", + size = ?size + ) + .entered(); + self.window.maybe_wait_on_main(|w| w.request_inner_size(size)) + } + + /// Returns the physical size of the entire window. + /// + /// These dimensions include the title bar and borders. If you don't want that (and you usually + /// don't), use [`Window::inner_size`] instead. + /// + /// ## Platform-specific + /// + /// - **iOS:** Can only be called on the main thread. Returns the [`PhysicalSize`] of the window + /// in screen space coordinates. + /// - **Web:** Returns the size of the canvas element. _Note: this returns the same value as + /// [`Window::inner_size`]._ + #[inline] + pub fn outer_size(&self) -> PhysicalSize<u32> { + let _span = tracing::debug_span!("winit::Window::outer_size",).entered(); + self.window.maybe_wait_on_main(|w| w.outer_size()) + } + + /// Sets a minimum dimension size for the window. + /// + /// ```no_run + /// # use winit::dpi::{LogicalSize, PhysicalSize}; + /// # use winit::window::Window; + /// # fn scope(window: &Window) { + /// // Specify the size in logical dimensions like this: + /// window.set_min_inner_size(Some(LogicalSize::new(400.0, 200.0))); + /// + /// // Or specify the size in physical dimensions like this: + /// window.set_min_inner_size(Some(PhysicalSize::new(400, 200))); + /// # } + /// ``` + /// + /// ## Platform-specific + /// + /// - **iOS / Android / Orbital:** Unsupported. + #[inline] + pub fn set_min_inner_size<S: Into<Size>>(&self, min_size: Option<S>) { + let min_size = min_size.map(|s| s.into()); + let _span = tracing::debug_span!( + "winit::Window::set_min_inner_size", + min_size = ?min_size + ) + .entered(); + self.window.maybe_queue_on_main(move |w| w.set_min_inner_size(min_size)) + } + + /// Sets a maximum dimension size for the window. + /// + /// ```no_run + /// # use winit::dpi::{LogicalSize, PhysicalSize}; + /// # use winit::window::Window; + /// # fn scope(window: &Window) { + /// // Specify the size in logical dimensions like this: + /// window.set_max_inner_size(Some(LogicalSize::new(400.0, 200.0))); + /// + /// // Or specify the size in physical dimensions like this: + /// window.set_max_inner_size(Some(PhysicalSize::new(400, 200))); + /// # } + /// ``` + /// + /// ## Platform-specific + /// + /// - **iOS / Android / Orbital:** Unsupported. + #[inline] + pub fn set_max_inner_size<S: Into<Size>>(&self, max_size: Option<S>) { + let max_size = max_size.map(|s| s.into()); + let _span = tracing::debug_span!( + "winit::Window::max_size", + max_size = ?max_size + ) + .entered(); + self.window.maybe_queue_on_main(move |w| w.set_max_inner_size(max_size)) + } + + /// Returns window resize increments if any were set. + /// + /// ## Platform-specific + /// + /// - **iOS / Android / Web / Orbital:** Always returns [`None`]. + #[inline] + pub fn resize_increments(&self) -> Option<PhysicalSize<u32>> { + let _span = tracing::debug_span!("winit::Window::resize_increments",).entered(); + self.window.maybe_wait_on_main(|w| w.resize_increments()) + } + + /// Sets window resize increments. + /// + /// This is a niche constraint hint usually employed by terminal emulators + /// and other apps that need "blocky" resizes. + /// + /// ## Platform-specific + /// + /// - **macOS:** Increments are converted to logical size and then macOS rounds them to whole + /// numbers. + /// - **iOS / Android / Web / Orbital:** Unsupported. + #[inline] + pub fn set_resize_increments<S: Into<Size>>(&self, increments: Option<S>) { + let increments = increments.map(Into::into); + let _span = tracing::debug_span!( + "winit::Window::set_resize_increments", + increments = ?increments + ) + .entered(); + self.window.maybe_queue_on_main(move |w| w.set_resize_increments(increments)) + } +} + +/// Misc. attribute functions. +impl Window { + /// Modifies the title of the window. + /// + /// ## Platform-specific + /// + /// - **iOS / Android:** Unsupported. + #[inline] + pub fn set_title(&self, title: &str) { + let _span = tracing::debug_span!("winit::Window::set_title", title).entered(); + self.window.maybe_wait_on_main(|w| w.set_title(title)) + } + + /// Change the window transparency state. + /// + /// This is just a hint that may not change anything about + /// the window transparency, however doing a mismatch between + /// the content of your window and this hint may result in + /// visual artifacts. + /// + /// The default value follows the [`WindowAttributes::with_transparent`]. + /// + /// ## Platform-specific + /// + /// - **macOS:** This will reset the window's background color. + /// - **Web / iOS / Android:** Unsupported. + /// - **X11:** Can only be set while building the window, with + /// [`WindowAttributes::with_transparent`]. + #[inline] + pub fn set_transparent(&self, transparent: bool) { + let _span = tracing::debug_span!("winit::Window::set_transparent", transparent).entered(); + self.window.maybe_queue_on_main(move |w| w.set_transparent(transparent)) + } + + /// Change the window blur state. + /// + /// If `true`, this will make the transparent window background blurry. + /// + /// ## Platform-specific + /// + /// - **Android / iOS / X11 / Web / Windows:** Unsupported. + /// - **Wayland:** Only works with org_kde_kwin_blur_manager protocol. + #[inline] + pub fn set_blur(&self, blur: bool) { + let _span = tracing::debug_span!("winit::Window::set_blur", blur).entered(); + self.window.maybe_queue_on_main(move |w| w.set_blur(blur)) + } + + /// Modifies the window's visibility. + /// + /// If `false`, this will hide the window. If `true`, this will show the window. + /// + /// ## Platform-specific + /// + /// - **Android / Wayland / Web:** Unsupported. + /// - **iOS:** Can only be called on the main thread. + #[inline] + pub fn set_visible(&self, visible: bool) { + let _span = tracing::debug_span!("winit::Window::set_visible", visible).entered(); + self.window.maybe_queue_on_main(move |w| w.set_visible(visible)) + } + + /// Gets the window's current visibility state. + /// + /// `None` means it couldn't be determined, so it is not recommended to use this to drive your + /// rendering backend. + /// + /// ## Platform-specific + /// + /// - **X11:** Not implemented. + /// - **Wayland / iOS / Android / Web:** Unsupported. + #[inline] + pub fn is_visible(&self) -> Option<bool> { + let _span = tracing::debug_span!("winit::Window::is_visible",).entered(); + self.window.maybe_wait_on_main(|w| w.is_visible()) + } + + /// Sets whether the window is resizable or not. + /// + /// Note that making the window unresizable doesn't exempt you from handling + /// [`WindowEvent::Resized`], as that event can still be triggered by DPI scaling, entering + /// fullscreen mode, etc. Also, the window could still be resized by calling + /// [`Window::request_inner_size`]. + /// + /// ## Platform-specific + /// + /// This only has an effect on desktop platforms. + /// + /// - **X11:** Due to a bug in XFCE, this has no effect on Xfwm. + /// - **iOS / Android / Web:** Unsupported. + /// + /// [`WindowEvent::Resized`]: crate::event::WindowEvent::Resized + #[inline] + pub fn set_resizable(&self, resizable: bool) { + let _span = tracing::debug_span!("winit::Window::set_resizable", resizable).entered(); + self.window.maybe_queue_on_main(move |w| w.set_resizable(resizable)) + } + + /// Gets the window's current resizable state. + /// + /// ## Platform-specific + /// + /// - **X11:** Not implemented. + /// - **iOS / Android / Web:** Unsupported. + #[inline] + pub fn is_resizable(&self) -> bool { + let _span = tracing::debug_span!("winit::Window::is_resizable",).entered(); + self.window.maybe_wait_on_main(|w| w.is_resizable()) + } + + /// Sets the enabled window buttons. + /// + /// ## Platform-specific + /// + /// - **Wayland / X11 / Orbital:** Not implemented. + /// - **Web / iOS / Android:** Unsupported. + pub fn set_enabled_buttons(&self, buttons: WindowButtons) { + let _span = tracing::debug_span!( + "winit::Window::set_enabled_buttons", + buttons = ?buttons + ) + .entered(); + self.window.maybe_queue_on_main(move |w| w.set_enabled_buttons(buttons)) + } + + /// Gets the enabled window buttons. + /// + /// ## Platform-specific + /// + /// - **Wayland / X11 / Orbital:** Not implemented. Always returns [`WindowButtons::all`]. + /// - **Web / iOS / Android:** Unsupported. Always returns [`WindowButtons::all`]. + pub fn enabled_buttons(&self) -> WindowButtons { + let _span = tracing::debug_span!("winit::Window::enabled_buttons",).entered(); + self.window.maybe_wait_on_main(|w| w.enabled_buttons()) + } + + /// Sets the window to minimized or back + /// + /// ## Platform-specific + /// + /// - **iOS / Android / Web / Orbital:** Unsupported. + /// - **Wayland:** Un-minimize is unsupported. + #[inline] + pub fn set_minimized(&self, minimized: bool) { + let _span = tracing::debug_span!("winit::Window::set_minimized", minimized).entered(); + self.window.maybe_queue_on_main(move |w| w.set_minimized(minimized)) + } + + /// Gets the window's current minimized state. + /// + /// `None` will be returned, if the minimized state couldn't be determined. + /// + /// ## Note + /// + /// - You shouldn't stop rendering for minimized windows, however you could lower the fps. + /// + /// ## Platform-specific + /// + /// - **Wayland**: always `None`. + /// - **iOS / Android / Web / Orbital:** Unsupported. + #[inline] + pub fn is_minimized(&self) -> Option<bool> { + let _span = tracing::debug_span!("winit::Window::is_minimized",).entered(); + self.window.maybe_wait_on_main(|w| w.is_minimized()) + } + + /// Sets the window to maximized or back. + /// + /// ## Platform-specific + /// + /// - **iOS / Android / Web:** Unsupported. + #[inline] + pub fn set_maximized(&self, maximized: bool) { + let _span = tracing::debug_span!("winit::Window::set_maximized", maximized).entered(); + self.window.maybe_queue_on_main(move |w| w.set_maximized(maximized)) + } + + /// Gets the window's current maximized state. + /// + /// ## Platform-specific + /// + /// - **iOS / Android / Web:** Unsupported. + #[inline] + pub fn is_maximized(&self) -> bool { + let _span = tracing::debug_span!("winit::Window::is_maximized",).entered(); + self.window.maybe_wait_on_main(|w| w.is_maximized()) + } + + /// Sets the window to fullscreen or back. + /// + /// ## Platform-specific + /// + /// - **macOS:** [`Fullscreen::Exclusive`] provides true exclusive mode with a video mode + /// change. *Caveat!* macOS doesn't provide task switching (or spaces!) while in exclusive + /// fullscreen mode. This mode should be used when a video mode change is desired, but for a + /// better user experience, borderless fullscreen might be preferred. + /// + /// [`Fullscreen::Borderless`] provides a borderless fullscreen window on a + /// separate space. This is the idiomatic way for fullscreen games to work + /// on macOS. See `WindowExtMacOs::set_simple_fullscreen` if + /// separate spaces are not preferred. + /// + /// The dock and the menu bar are disabled in exclusive fullscreen mode. + /// - **iOS:** Can only be called on the main thread. + /// - **Wayland:** Does not support exclusive fullscreen mode and will no-op a request. + /// - **Windows:** Screen saver is disabled in fullscreen mode. + /// - **Android / Orbital:** Unsupported. + /// - **Web:** Does nothing without a [transient activation]. + /// + /// [transient activation]: https://developer.mozilla.org/en-US/docs/Glossary/Transient_activation + #[inline] + pub fn set_fullscreen(&self, fullscreen: Option<Fullscreen>) { + let _span = tracing::debug_span!( + "winit::Window::set_fullscreen", + fullscreen = ?fullscreen + ) + .entered(); + self.window.maybe_queue_on_main(move |w| w.set_fullscreen(fullscreen.map(|f| f.into()))) + } + + /// Gets the window's current fullscreen state. + /// + /// ## Platform-specific + /// + /// - **iOS:** Can only be called on the main thread. + /// - **Android / Orbital:** Will always return `None`. + /// - **Wayland:** Can return `Borderless(None)` when there are no monitors. + /// - **Web:** Can only return `None` or `Borderless(None)`. + #[inline] + pub fn fullscreen(&self) -> Option<Fullscreen> { + let _span = tracing::debug_span!("winit::Window::fullscreen",).entered(); + self.window.maybe_wait_on_main(|w| w.fullscreen().map(|f| f.into())) + } + + /// Turn window decorations on or off. + /// + /// Enable/disable window decorations provided by the server or Winit. + /// By default this is enabled. Note that fullscreen windows and windows on + /// mobile and web platforms naturally do not have decorations. + /// + /// ## Platform-specific + /// + /// - **iOS / Android / Web:** No effect. + #[inline] + pub fn set_decorations(&self, decorations: bool) { + let _span = tracing::debug_span!("winit::Window::set_decorations", decorations).entered(); + self.window.maybe_queue_on_main(move |w| w.set_decorations(decorations)) + } + + /// Gets the window's current decorations state. + /// + /// Returns `true` when windows are decorated (server-side or by Winit). + /// Also returns `true` when no decorations are required (mobile, web). + /// + /// ## Platform-specific + /// + /// - **iOS / Android / Web:** Always returns `true`. + #[inline] + pub fn is_decorated(&self) -> bool { + let _span = tracing::debug_span!("winit::Window::is_decorated",).entered(); + self.window.maybe_wait_on_main(|w| w.is_decorated()) + } + + /// Change the window level. + /// + /// This is just a hint to the OS, and the system could ignore it. + /// + /// See [`WindowLevel`] for details. + pub fn set_window_level(&self, level: WindowLevel) { + let _span = tracing::debug_span!( + "winit::Window::set_window_level", + level = ?level + ) + .entered(); + self.window.maybe_queue_on_main(move |w| w.set_window_level(level)) + } + + /// Sets the window icon. + /// + /// On Windows and X11, this is typically the small icon in the top-left + /// corner of the titlebar. + /// + /// ## Platform-specific + /// + /// - **iOS / Android / Web / Wayland / macOS / Orbital:** Unsupported. + /// + /// - **Windows:** Sets `ICON_SMALL`. The base size for a window icon is 16x16, but it's + /// recommended to account for screen scaling and pick a multiple of that, i.e. 32x32. + /// + /// - **X11:** Has no universal guidelines for icon sizes, so you're at the whims of the WM. + /// That said, it's usually in the same ballpark as on Windows. + #[inline] + pub fn set_window_icon(&self, window_icon: Option<Icon>) { + let _span = tracing::debug_span!("winit::Window::set_window_icon",).entered(); + self.window.maybe_queue_on_main(move |w| w.set_window_icon(window_icon)) + } + + /// Set the IME cursor editing area, where the `position` is the top left corner of that area + /// and `size` is the size of this area starting from the position. An example of such area + /// could be a input field in the UI or line in the editor. + /// + /// The windowing system could place a candidate box close to that area, but try to not obscure + /// the specified area, so the user input to it stays visible. + /// + /// The candidate box is the window / popup / overlay that allows you to select the desired + /// characters. The look of this box may differ between input devices, even on the same + /// platform. + /// + /// (Apple's official term is "candidate window", see their [chinese] and [japanese] guides). + /// + /// ## Example + /// + /// ```no_run + /// # use winit::dpi::{LogicalPosition, PhysicalPosition, LogicalSize, PhysicalSize}; + /// # use winit::window::Window; + /// # fn scope(window: &Window) { + /// // Specify the position in logical dimensions like this: + /// window.set_ime_cursor_area(LogicalPosition::new(400.0, 200.0), LogicalSize::new(100, 100)); + /// + /// // Or specify the position in physical dimensions like this: + /// window.set_ime_cursor_area(PhysicalPosition::new(400, 200), PhysicalSize::new(100, 100)); + /// # } + /// ``` + /// + /// ## Platform-specific + /// + /// - **X11:** - area is not supported, only position. + /// - **iOS / Android / Web / Orbital:** Unsupported. + /// + /// [chinese]: https://support.apple.com/guide/chinese-input-method/use-the-candidate-window-cim12992/104/mac/12.0 + /// [japanese]: https://support.apple.com/guide/japanese-input-method/use-the-candidate-window-jpim10262/6.3/mac/12.0 + #[inline] + pub fn set_ime_cursor_area<P: Into<Position>, S: Into<Size>>(&self, position: P, size: S) { + let position = position.into(); + let size = size.into(); + let _span = tracing::debug_span!( + "winit::Window::set_ime_cursor_area", + position = ?position, + size = ?size, + ) + .entered(); + self.window.maybe_queue_on_main(move |w| w.set_ime_cursor_area(position, size)) + } + + /// Sets whether the window should get IME events + /// + /// When IME is allowed, the window will receive [`Ime`] events, and during the + /// preedit phase the window will NOT get [`KeyboardInput`] events. The window + /// should allow IME while it is expecting text input. + /// + /// When IME is not allowed, the window won't receive [`Ime`] events, and will + /// receive [`KeyboardInput`] events for every keypress instead. Not allowing + /// IME is useful for games for example. + /// + /// IME is **not** allowed by default. + /// + /// ## Platform-specific + /// + /// - **macOS:** IME must be enabled to receive text-input where dead-key sequences are + /// combined. + /// - **iOS / Android:** This will show / hide the soft keyboard. + /// - **Web / Orbital:** Unsupported. + /// - **X11**: Enabling IME will disable dead keys reporting during compose. + /// + /// [`Ime`]: crate::event::WindowEvent::Ime + /// [`KeyboardInput`]: crate::event::WindowEvent::KeyboardInput + #[inline] + pub fn set_ime_allowed(&self, allowed: bool) { + let _span = tracing::debug_span!("winit::Window::set_ime_allowed", allowed).entered(); + self.window.maybe_queue_on_main(move |w| w.set_ime_allowed(allowed)) + } + + /// Sets the IME purpose for the window using [`ImePurpose`]. + /// + /// ## Platform-specific + /// + /// - **iOS / Android / Web / Windows / X11 / macOS / Orbital:** Unsupported. + #[inline] + pub fn set_ime_purpose(&self, purpose: ImePurpose) { + let _span = tracing::debug_span!( + "winit::Window::set_ime_purpose", + purpose = ?purpose + ) + .entered(); + self.window.maybe_queue_on_main(move |w| w.set_ime_purpose(purpose)) + } + + /// Brings the window to the front and sets input focus. Has no effect if the window is + /// already in focus, minimized, or not visible. + /// + /// This method steals input focus from other applications. Do not use this method unless + /// you are certain that's what the user wants. Focus stealing can cause an extremely disruptive + /// user experience. + /// + /// ## Platform-specific + /// + /// - **iOS / Android / Wayland / Orbital:** Unsupported. + #[inline] + pub fn focus_window(&self) { + let _span = tracing::debug_span!("winit::Window::focus_window",).entered(); + self.window.maybe_queue_on_main(|w| w.focus_window()) + } + + /// Gets whether the window has keyboard focus. + /// + /// This queries the same state information as [`WindowEvent::Focused`]. + /// + /// [`WindowEvent::Focused`]: crate::event::WindowEvent::Focused + #[inline] + pub fn has_focus(&self) -> bool { + let _span = tracing::debug_span!("winit::Window::has_focus",).entered(); + self.window.maybe_wait_on_main(|w| w.has_focus()) + } + + /// Requests user attention to the window, this has no effect if the application + /// is already focused. How requesting for user attention manifests is platform dependent, + /// see [`UserAttentionType`] for details. + /// + /// Providing `None` will unset the request for user attention. Unsetting the request for + /// user attention might not be done automatically by the WM when the window receives input. + /// + /// ## Platform-specific + /// + /// - **iOS / Android / Web / Orbital:** Unsupported. + /// - **macOS:** `None` has no effect. + /// - **X11:** Requests for user attention must be manually cleared. + /// - **Wayland:** Requires `xdg_activation_v1` protocol, `None` has no effect. + #[inline] + pub fn request_user_attention(&self, request_type: Option<UserAttentionType>) { + let _span = tracing::debug_span!( + "winit::Window::request_user_attention", + request_type = ?request_type + ) + .entered(); + self.window.maybe_queue_on_main(move |w| w.request_user_attention(request_type)) + } + + /// Set or override the window theme. + /// + /// Specify `None` to reset the theme to the system default. + /// + /// ## Platform-specific + /// + /// - **Wayland:** Sets the theme for the client side decorations. Using `None` will use dbus to + /// get the system preference. + /// - **X11:** Sets `_GTK_THEME_VARIANT` hint to `dark` or `light` and if `None` is used, it + /// will default to [`Theme::Dark`]. + /// - **iOS / Android / Web / Orbital:** Unsupported. + #[inline] + pub fn set_theme(&self, theme: Option<Theme>) { + let _span = tracing::debug_span!( + "winit::Window::set_theme", + theme = ?theme + ) + .entered(); + self.window.maybe_queue_on_main(move |w| w.set_theme(theme)) + } + + /// Returns the current window theme. + /// + /// Returns `None` if it cannot be determined on the current platform. + /// + /// ## Platform-specific + /// + /// - **iOS / Android / x11 / Orbital:** Unsupported. + /// - **Wayland:** Only returns theme overrides. + #[inline] + pub fn theme(&self) -> Option<Theme> { + let _span = tracing::debug_span!("winit::Window::theme",).entered(); + self.window.maybe_wait_on_main(|w| w.theme()) + } + + /// Prevents the window contents from being captured by other apps. + /// + /// ## Platform-specific + /// + /// - **macOS**: if `false`, [`NSWindowSharingNone`] is used but doesn't completely prevent all + /// apps from reading the window content, for instance, QuickTime. + /// - **iOS / Android / x11 / Wayland / Web / Orbital:** Unsupported. + /// + /// [`NSWindowSharingNone`]: https://developer.apple.com/documentation/appkit/nswindowsharingtype/nswindowsharingnone + pub fn set_content_protected(&self, protected: bool) { + let _span = + tracing::debug_span!("winit::Window::set_content_protected", protected).entered(); + self.window.maybe_queue_on_main(move |w| w.set_content_protected(protected)) + } + + /// Gets the current title of the window. + /// + /// ## Platform-specific + /// + /// - **iOS / Android / x11 / Wayland / Web:** Unsupported. Always returns an empty string. + #[inline] + pub fn title(&self) -> String { + let _span = tracing::debug_span!("winit::Window::title",).entered(); + self.window.maybe_wait_on_main(|w| w.title()) + } +} + +/// Cursor functions. +impl Window { + /// Modifies the cursor icon of the window. + /// + /// ## Platform-specific + /// + /// - **iOS / Android / Orbital:** Unsupported. + /// - **Web:** Custom cursors have to be loaded and decoded first, until then the previous + /// cursor is shown. + #[inline] + pub fn set_cursor(&self, cursor: impl Into<Cursor>) { + let cursor = cursor.into(); + let _span = tracing::debug_span!("winit::Window::set_cursor",).entered(); + self.window.maybe_queue_on_main(move |w| w.set_cursor(cursor)) + } + + /// Deprecated! Use [`Window::set_cursor()`] instead. + #[deprecated = "Renamed to `set_cursor`"] + #[inline] + pub fn set_cursor_icon(&self, icon: CursorIcon) { + self.set_cursor(icon) + } + + /// Changes the position of the cursor in window coordinates. + /// + /// ```no_run + /// # use winit::dpi::{LogicalPosition, PhysicalPosition}; + /// # use winit::window::Window; + /// # fn scope(window: &Window) { + /// // Specify the position in logical dimensions like this: + /// window.set_cursor_position(LogicalPosition::new(400.0, 200.0)); + /// + /// // Or specify the position in physical dimensions like this: + /// window.set_cursor_position(PhysicalPosition::new(400, 200)); + /// # } + /// ``` + /// + /// ## Platform-specific + /// + /// - **Wayland**: Cursor must be in [`CursorGrabMode::Locked`]. + /// - **iOS / Android / Web / Orbital:** Always returns an [`ExternalError::NotSupported`]. + #[inline] + pub fn set_cursor_position<P: Into<Position>>(&self, position: P) -> Result<(), ExternalError> { + let position = position.into(); + let _span = tracing::debug_span!( + "winit::Window::set_cursor_position", + position = ?position + ) + .entered(); + self.window.maybe_wait_on_main(|w| w.set_cursor_position(position)) + } + + /// Set grabbing [mode][CursorGrabMode] on the cursor preventing it from leaving the window. + /// + /// # Example + /// + /// First try confining the cursor, and if that fails, try locking it instead. + /// + /// ```no_run + /// # use winit::window::{CursorGrabMode, Window}; + /// # fn scope(window: &Window) { + /// window + /// .set_cursor_grab(CursorGrabMode::Confined) + /// .or_else(|_e| window.set_cursor_grab(CursorGrabMode::Locked)) + /// .unwrap(); + /// # } + /// ``` + #[inline] + pub fn set_cursor_grab(&self, mode: CursorGrabMode) -> Result<(), ExternalError> { + let _span = tracing::debug_span!( + "winit::Window::set_cursor_grab", + mode = ?mode + ) + .entered(); + self.window.maybe_wait_on_main(|w| w.set_cursor_grab(mode)) + } + + /// Modifies the cursor's visibility. + /// + /// If `false`, this will hide the cursor. If `true`, this will show the cursor. + /// + /// ## Platform-specific + /// + /// - **Windows:** The cursor is only hidden within the confines of the window. + /// - **X11:** The cursor is only hidden within the confines of the window. + /// - **Wayland:** The cursor is only hidden within the confines of the window. + /// - **macOS:** The cursor is hidden as long as the window has input focus, even if the cursor + /// is outside of the window. + /// - **iOS / Android:** Unsupported. + #[inline] + pub fn set_cursor_visible(&self, visible: bool) { + let _span = tracing::debug_span!("winit::Window::set_cursor_visible", visible).entered(); + self.window.maybe_queue_on_main(move |w| w.set_cursor_visible(visible)) + } + + /// Moves the window with the left mouse button until the button is released. + /// + /// There's no guarantee that this will work unless the left mouse button was pressed + /// immediately before this function is called. + /// + /// ## Platform-specific + /// + /// - **X11:** Un-grabs the cursor. + /// - **Wayland:** Requires the cursor to be inside the window to be dragged. + /// - **macOS:** May prevent the button release event to be triggered. + /// - **iOS / Android / Web:** Always returns an [`ExternalError::NotSupported`]. + #[inline] + pub fn drag_window(&self) -> Result<(), ExternalError> { + let _span = tracing::debug_span!("winit::Window::drag_window",).entered(); + self.window.maybe_wait_on_main(|w| w.drag_window()) + } + + /// Resizes the window with the left mouse button until the button is released. + /// + /// There's no guarantee that this will work unless the left mouse button was pressed + /// immediately before this function is called. + /// + /// ## Platform-specific + /// + /// - **macOS:** Always returns an [`ExternalError::NotSupported`] + /// - **iOS / Android / Web:** Always returns an [`ExternalError::NotSupported`]. + #[inline] + pub fn drag_resize_window(&self, direction: ResizeDirection) -> Result<(), ExternalError> { + let _span = tracing::debug_span!( + "winit::Window::drag_resize_window", + direction = ?direction + ) + .entered(); + self.window.maybe_wait_on_main(|w| w.drag_resize_window(direction)) + } + + /// Show [window menu] at a specified position . + /// + /// This is the context menu that is normally shown when interacting with + /// the title bar. This is useful when implementing custom decorations. + /// + /// ## Platform-specific + /// **Android / iOS / macOS / Orbital / Wayland / Web / X11:** Unsupported. + /// + /// [window menu]: https://en.wikipedia.org/wiki/Common_menus_in_Microsoft_Windows#System_menu + pub fn show_window_menu(&self, position: impl Into<Position>) { + let position = position.into(); + let _span = tracing::debug_span!( + "winit::Window::show_window_menu", + position = ?position + ) + .entered(); + self.window.maybe_queue_on_main(move |w| w.show_window_menu(position)) + } + + /// Modifies whether the window catches cursor events. + /// + /// If `true`, the window will catch the cursor events. If `false`, events are passed through + /// the window such that any other window behind it receives them. By default hittest is + /// enabled. + /// + /// ## Platform-specific + /// + /// - **iOS / Android / Web / Orbital:** Always returns an [`ExternalError::NotSupported`]. + #[inline] + pub fn set_cursor_hittest(&self, hittest: bool) -> Result<(), ExternalError> { + let _span = tracing::debug_span!("winit::Window::set_cursor_hittest", hittest).entered(); + self.window.maybe_wait_on_main(|w| w.set_cursor_hittest(hittest)) + } +} + +/// Monitor info functions. +impl Window { + /// Returns the monitor on which the window currently resides. + /// + /// Returns `None` if current monitor can't be detected. + #[inline] + pub fn current_monitor(&self) -> Option<MonitorHandle> { + let _span = tracing::debug_span!("winit::Window::current_monitor",).entered(); + self.window.maybe_wait_on_main(|w| w.current_monitor().map(|inner| MonitorHandle { inner })) + } + + /// Returns the list of all the monitors available on the system. + /// + /// This is the same as [`ActiveEventLoop::available_monitors`], and is provided for + /// convenience. + /// + /// [`ActiveEventLoop::available_monitors`]: crate::event_loop::ActiveEventLoop::available_monitors + #[inline] + pub fn available_monitors(&self) -> impl Iterator<Item = MonitorHandle> { + let _span = tracing::debug_span!("winit::Window::available_monitors",).entered(); + self.window.maybe_wait_on_main(|w| { + w.available_monitors().into_iter().map(|inner| MonitorHandle { inner }) + }) + } + + /// Returns the primary monitor of the system. + /// + /// Returns `None` if it can't identify any monitor as a primary one. + /// + /// This is the same as [`ActiveEventLoop::primary_monitor`], and is provided for convenience. + /// + /// ## Platform-specific + /// + /// **Wayland / Web:** Always returns `None`. + /// + /// [`ActiveEventLoop::primary_monitor`]: crate::event_loop::ActiveEventLoop::primary_monitor + #[inline] + pub fn primary_monitor(&self) -> Option<MonitorHandle> { + let _span = tracing::debug_span!("winit::Window::primary_monitor",).entered(); + self.window.maybe_wait_on_main(|w| w.primary_monitor().map(|inner| MonitorHandle { inner })) + } +} + +#[cfg(feature = "rwh_06")] +impl rwh_06::HasWindowHandle for Window { + fn window_handle(&self) -> Result<rwh_06::WindowHandle<'_>, rwh_06::HandleError> { + let raw = self.window.raw_window_handle_rwh_06()?; + + // SAFETY: The window handle will never be deallocated while the window is alive, + // and the main thread safety requirements are upheld internally by each platform. + Ok(unsafe { rwh_06::WindowHandle::borrow_raw(raw) }) + } +} + +#[cfg(feature = "rwh_06")] +impl rwh_06::HasDisplayHandle for Window { + fn display_handle(&self) -> Result<rwh_06::DisplayHandle<'_>, rwh_06::HandleError> { + let raw = self.window.raw_display_handle_rwh_06()?; + + // SAFETY: The window handle will never be deallocated while the window is alive, + // and the main thread safety requirements are upheld internally by each platform. + Ok(unsafe { rwh_06::DisplayHandle::borrow_raw(raw) }) + } +} + +/// Wrapper to make objects `Send`. +/// +/// # Safety +/// +/// This is not safe! This is only used for `RawWindowHandle`, which only has unsafe getters. +#[cfg(any(feature = "rwh_05", feature = "rwh_04"))] +struct UnsafeSendWrapper<T>(T); + +#[cfg(any(feature = "rwh_05", feature = "rwh_04"))] +unsafe impl<T> Send for UnsafeSendWrapper<T> {} + +#[cfg(feature = "rwh_05")] +unsafe impl rwh_05::HasRawWindowHandle for Window { + fn raw_window_handle(&self) -> rwh_05::RawWindowHandle { + self.window.maybe_wait_on_main(|w| UnsafeSendWrapper(w.raw_window_handle_rwh_05())).0 + } +} + +#[cfg(feature = "rwh_05")] +unsafe impl rwh_05::HasRawDisplayHandle for Window { + /// Returns a [`rwh_05::RawDisplayHandle`] used by the [`EventLoop`] that + /// created a window. + /// + /// [`EventLoop`]: crate::event_loop::EventLoop + fn raw_display_handle(&self) -> rwh_05::RawDisplayHandle { + self.window.maybe_wait_on_main(|w| UnsafeSendWrapper(w.raw_display_handle_rwh_05())).0 + } +} + +#[cfg(feature = "rwh_04")] +unsafe impl rwh_04::HasRawWindowHandle for Window { + fn raw_window_handle(&self) -> rwh_04::RawWindowHandle { + self.window.maybe_wait_on_main(|w| UnsafeSendWrapper(w.raw_window_handle_rwh_04())).0 + } +} + +/// The behavior of cursor grabbing. +/// +/// Use this enum with [`Window::set_cursor_grab`] to grab the cursor. +#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)] +#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] +pub enum CursorGrabMode { + /// No grabbing of the cursor is performed. + None, + + /// The cursor is confined to the window area. + /// + /// There's no guarantee that the cursor will be hidden. You should hide it by yourself if you + /// want to do so. + /// + /// ## Platform-specific + /// + /// - **macOS:** Not implemented. Always returns [`ExternalError::NotSupported`] for now. + /// - **iOS / Android / Web:** Always returns an [`ExternalError::NotSupported`]. + Confined, + + /// The cursor is locked inside the window area to the certain position. + /// + /// There's no guarantee that the cursor will be hidden. You should hide it by yourself if you + /// want to do so. + /// + /// ## Platform-specific + /// + /// - **X11:** Not implemented. Always returns [`ExternalError::NotSupported`] for now. + /// - **iOS / Android:** Always returns an [`ExternalError::NotSupported`]. + Locked, +} + +/// Defines the orientation that a window resize will be performed. +#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)] +pub enum ResizeDirection { + East, + North, + NorthEast, + NorthWest, + South, + SouthEast, + SouthWest, + West, +} + +impl From<ResizeDirection> for CursorIcon { + fn from(direction: ResizeDirection) -> Self { + use ResizeDirection::*; + match direction { + East => CursorIcon::EResize, + North => CursorIcon::NResize, + NorthEast => CursorIcon::NeResize, + NorthWest => CursorIcon::NwResize, + South => CursorIcon::SResize, + SouthEast => CursorIcon::SeResize, + SouthWest => CursorIcon::SwResize, + West => CursorIcon::WResize, + } + } +} + +/// Fullscreen modes. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Fullscreen { + Exclusive(VideoModeHandle), + + /// Providing `None` to `Borderless` will fullscreen on the current monitor. + Borderless(Option<MonitorHandle>), +} + +/// The theme variant to use. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] +pub enum Theme { + /// Use the light variant. + Light, + + /// Use the dark variant. + Dark, +} + +/// ## Platform-specific +/// +/// - **X11:** Sets the WM's `XUrgencyHint`. No distinction between [`Critical`] and +/// [`Informational`]. +/// +/// [`Critical`]: Self::Critical +/// [`Informational`]: Self::Informational +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub enum UserAttentionType { + /// ## Platform-specific + /// + /// - **macOS:** Bounces the dock icon until the application is in focus. + /// - **Windows:** Flashes both the window and the taskbar button until the application is in + /// focus. + Critical, + + /// ## Platform-specific + /// + /// - **macOS:** Bounces the dock icon once. + /// - **Windows:** Flashes the taskbar button until the application is in focus. + #[default] + Informational, +} + +bitflags::bitflags! { + #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] + pub struct WindowButtons: u32 { + const CLOSE = 1 << 0; + const MINIMIZE = 1 << 1; + const MAXIMIZE = 1 << 2; + } +} + +/// A window level groups windows with respect to their z-position. +/// +/// The relative ordering between windows in different window levels is fixed. +/// The z-order of a window within the same window level may change dynamically on user interaction. +/// +/// ## Platform-specific +/// +/// - **iOS / Android / Web / Wayland:** Unsupported. +#[derive(Debug, Default, PartialEq, Eq, Clone, Copy)] +pub enum WindowLevel { + /// The window will always be below normal windows. + /// + /// This is useful for a widget-based app. + AlwaysOnBottom, + + /// The default. + #[default] + Normal, + + /// The window will always be on top of normal windows. + AlwaysOnTop, +} + +/// Generic IME purposes for use in [`Window::set_ime_purpose`]. +/// +/// The purpose may improve UX by optimizing the IME for the specific use case, +/// if winit can express the purpose to the platform and the platform reacts accordingly. +/// +/// ## Platform-specific +/// +/// - **iOS / Android / Web / Windows / X11 / macOS / Orbital:** Unsupported. +#[derive(Default, Debug, PartialEq, Eq, Clone, Copy)] +#[non_exhaustive] +pub enum ImePurpose { + /// No special hints for the IME (default). + #[default] + Normal, + /// The IME is used for password input. + Password, + /// The IME is used to input into a terminal. + /// + /// For example, that could alter OSK on Wayland to show extra buttons. + Terminal, +} + +/// An opaque token used to activate the [`Window`]. +/// +/// [`Window`]: crate::window::Window +#[derive(Debug, PartialEq, Eq, Clone)] +pub struct ActivationToken { + pub(crate) token: String, +} + +impl ActivationToken { + /// Make an [`ActivationToken`] from a string. + /// + /// This method should be used to wrap tokens passed by side channels to your application, like + /// dbus. + /// + /// The validity of the token is ensured by the windowing system. Using the invalid token will + /// only result in the side effect of the operation involving it being ignored (e.g. window + /// won't get focused automatically), but won't yield any errors. + /// + /// To obtain a valid token, use + #[cfg_attr( + any(x11_platform, wayland_platform, docsrs), + doc = " [`request_activation_token`](crate::platform::startup_notify::WindowExtStartupNotify::request_activation_token)." + )] + #[cfg_attr( + not(any(x11_platform, wayland_platform, docsrs)), + doc = " `request_activation_token`." + )] + pub fn from_raw(token: String) -> Self { + Self { token } + } + + /// Convert the token to its string representation to later pass via IPC. + pub fn into_raw(self) -> String { + self.token + } +} diff --git a/app/vendor/rune/vendor/winit/tests/send_objects.rs b/app/vendor/rune/vendor/winit/tests/send_objects.rs new file mode 100644 index 0000000..b8a5d3b --- /dev/null +++ b/app/vendor/rune/vendor/winit/tests/send_objects.rs @@ -0,0 +1,36 @@ +#[allow(dead_code)] +fn needs_send<T: Send>() {} + +#[test] +fn event_loop_proxy_send() { + #[allow(dead_code)] + fn is_send<T: 'static + Send>() { + // ensures that `winit::EventLoopProxy<T: Send>` implements `Send` + needs_send::<winit::event_loop::EventLoopProxy<T>>(); + } +} + +#[test] +fn window_send() { + // ensures that `winit::Window` implements `Send` + needs_send::<winit::window::Window>(); +} + +#[test] +fn window_builder_send() { + needs_send::<winit::window::WindowAttributes>(); +} + +#[test] +fn ids_send() { + // ensures that the various `..Id` types implement `Send` + needs_send::<winit::window::WindowId>(); + needs_send::<winit::event::DeviceId>(); + needs_send::<winit::monitor::MonitorHandle>(); +} + +#[test] +fn custom_cursor_send() { + needs_send::<winit::window::CustomCursorSource>(); + needs_send::<winit::window::CustomCursor>(); +} diff --git a/app/vendor/rune/vendor/winit/tests/serde_objects.rs b/app/vendor/rune/vendor/winit/tests/serde_objects.rs new file mode 100644 index 0000000..c427373 --- /dev/null +++ b/app/vendor/rune/vendor/winit/tests/serde_objects.rs @@ -0,0 +1,38 @@ +#![cfg(feature = "serde")] + +use serde::{Deserialize, Serialize}; +use winit::dpi::{LogicalPosition, LogicalSize, PhysicalPosition, PhysicalSize}; +use winit::event::{ElementState, MouseButton, MouseScrollDelta, TouchPhase}; +use winit::keyboard::{Key, KeyCode, KeyLocation, ModifiersState, NamedKey, PhysicalKey}; +use winit::window::CursorIcon; + +#[allow(dead_code)] +fn needs_serde<S: Serialize + Deserialize<'static>>() {} + +#[test] +fn window_serde() { + needs_serde::<CursorIcon>(); +} + +#[test] +fn events_serde() { + needs_serde::<TouchPhase>(); + needs_serde::<ElementState>(); + needs_serde::<MouseButton>(); + needs_serde::<MouseScrollDelta>(); + needs_serde::<Key>(); + needs_serde::<NamedKey>(); + needs_serde::<KeyCode>(); + needs_serde::<PhysicalKey>(); + needs_serde::<KeyLocation>(); + needs_serde::<ModifiersState>(); +} + +#[test] +fn dpi_serde() { + needs_serde::<LogicalPosition<f64>>(); + needs_serde::<PhysicalPosition<i32>>(); + needs_serde::<PhysicalPosition<f64>>(); + needs_serde::<LogicalSize<f64>>(); + needs_serde::<PhysicalSize<u32>>(); +} diff --git a/app/vendor/rune/vendor/winit/tests/sync_object.rs b/app/vendor/rune/vendor/winit/tests/sync_object.rs new file mode 100644 index 0000000..c7abbeb --- /dev/null +++ b/app/vendor/rune/vendor/winit/tests/sync_object.rs @@ -0,0 +1,28 @@ +#[allow(dead_code)] +fn needs_sync<T: Sync>() {} + +#[test] +fn event_loop_proxy_send() { + #[allow(dead_code)] + fn is_send<T: 'static + Send>() { + // ensures that `winit::EventLoopProxy<T: Send>` implements `Sync` + needs_sync::<winit::event_loop::EventLoopProxy<T>>(); + } +} + +#[test] +fn window_sync() { + // ensures that `winit::Window` implements `Sync` + needs_sync::<winit::window::Window>(); +} + +#[test] +fn window_builder_sync() { + needs_sync::<winit::window::WindowAttributes>(); +} + +#[test] +fn custom_cursor_sync() { + needs_sync::<winit::window::CustomCursorSource>(); + needs_sync::<winit::window::CustomCursor>(); +} diff --git a/app/vendor/rune/www/.gitignore b/app/vendor/rune/www/.gitignore new file mode 100644 index 0000000..f8755f9 --- /dev/null +++ b/app/vendor/rune/www/.gitignore @@ -0,0 +1,5 @@ +node_modules/ +dist/ +.cloudflare/ +# Built by scripts/build.ts from www/app; never committed. +src/wasm/ diff --git a/app/vendor/rune/www/README.md b/app/vendor/rune/www/README.md new file mode 100644 index 0000000..67530e0 --- /dev/null +++ b/app/vendor/rune/www/README.md @@ -0,0 +1,83 @@ +# Rune www + +Rune's public page, written in Rune. The whole page is one Rune app, `app/` (package `rune-www`), in web document +mode: the browser scrolls a semantic mirror of it (headings, paragraphs, real links, landmarks), and the canvas draws +the part in view. The same app writes its own static HTML with `--html`, which is the page's first paint and what +crawlers, readers without WebGPU and readers without JavaScript get. + +- `bun run build`: builds `app/` to wasm (`src/wasm/`, size-optimized with LTO and `wasm-opt`), typechecks, bundles + `src/main.ts` and the Worker with Vite, then runs the native app with `--html` to write `index.html` and `404.html`, + and adds `robots.txt`, `sitemap.xml` and `llms.txt`, into `.cloudflare/output/v0/workers/default/assets/` (Build + Output for the `cf` CLI). `--mode dev` builds for dev.anoma.ly: `noindex` on every page and a `Disallow: /` + robots.txt. `--no-opt` skips the size passes for a quicker, larger build. +- `bun run serve`: serves the build through `worker.ts` with brotli, close to what Cloudflare does, at + `http://127.0.0.1:4253/rune/`. It caches compressed files, so restart it after a build. +- `bun run check`: typecheck only. `cargo test -p rune-www` tests the app. + +The build needs Rust with the `wasm32-unknown-unknown` target, the `wasm-bindgen` CLI at the version in `Cargo.lock` +and binaryen's `wasm-opt`. Unset `RUSTC_WRAPPER` if you use a compiler cache, so it can't undo the path stripping +`scripts/web-build.sh` does. + +Copy and sections live in `app/src/`: the hero and its live card in `hero.rs`, the rest in `sections.rs`, the spring +demo in `springs.rs`, the frame diagram in `pipeline.rs`, the wordmark in `wordmark.rs` and colours, type and spacing in +`tokens.rs`. Headings state the point of their section, not a topic. The tree is the same at every width and only +styles change at the breakpoints, so the static page switches them with `@media` rules. + +## Loading + +`index.html` is the template (title, description, Open Graph and Twitter cards, canonical URL); `scripts/build.ts` +fills it in, adds JSON-LD, and the app writes the page's body into it, laid out at each breakpoint. That page paints +on its own with no script. + +`src/main.ts` then loads Rune, only where `navigator.gpu` exists, and only after the static page has painted its +largest text, so the wasm never competes with it. Rune's first frame matches the static page, then hides the static +copy (it stays in the DOM, inert, so nothing shifts). Without WebGPU, or if the wasm fails, the static page stays. + +The wasm isn't committed: Rune's history is public and keeps every file forever. CI builds it before every deploy, +which is why changes to Rune deploy the page too. + +## Hosting and deploys + +The page is served at https://anoma.ly/rune and https://dev.anoma.ly/rune. + +- A push to `dev` that touches `www/` or Rune deploys https://dev.anoma.ly/rune (Worker `rune-www-dev`). +- A push to `production` that touches `www/` or Rune deploys https://anoma.ly/rune (Worker `rune-www-production`). To + release, fast-forward it to `dev`: `git push origin dev:production`. +- A pull request runs the tests and the dev build and deploys nothing. + +`.github/workflows/www.yml` runs `bun run build` and `cf deploy --prebuilt` with the `CLOUDFLARE_API_TOKEN` and +`CLOUDFLARE_ACCOUNT_ID` secrets, the same ones the docs site uses. + +`cloudflare.config.ts` defines both environments, selected by the build mode. `worker.ts` redirects other hosts to the +canonical one, strips the base path `/rune` (from `src/base.ts`), serves the static files and sets cache headers: +hashed assets (the wasm and its glue) for a year; images and fonts for a day, then revalidated. `workers.dev` and +preview URLs are off. + +## Images and fonts + +`bun run images` cuts the page's images from Rune's own headless renders in `demo/` and the docs site's shots into +AVIF at the widths the page shows, into `public/img/`. The widths and aspect ratios match the `Picture`s in +`app/src/sections.rs`, which hand the browser a `srcset` so it picks one size; every image has its box before it loads. + +The metal, glass and light stills are drawn by `examples/site-scenes`, which runs rune-fx and rune-light headless at +2x over a frame Rune draws. Their PNGs aren't committed, only the cut images, so render them before `bun run images`: + +```sh +cargo run --release -p site-scenes # all three, into target/site-scenes/ +cargo run --release -p site-scenes -- --only glass --t 2.5 +``` + +`--t` is the effect clock in seconds; the liquid metal's flow and the light's sway depend on it. + +`bun run icons` draws the favicons, app icons and `og.png` from the wordmark's pixels in `src/brand/pixels.ts`. + +The Geist fonts in `public/fonts/` are TTF, because Rune loads fonts by URL and doesn't read WOFF2; the static page +uses the same files. + +## Motion + +Nothing moves on first paint, and an idle page draws no frames. The wordmark's ᚱ catches a light on hover, and now and +then in the masthead while it's on screen. The hero card's switch and puck, and the spring demo, run `rune-motion`'s +springs, so a retarget keeps the current velocity and a held puck follows the finger without animation. The frame +diagram runs once when it comes into view and again on a click. Under reduced motion, travel becomes a short fade and +the idle light stays off. diff --git a/app/vendor/rune/www/app/Cargo.toml b/app/vendor/rune/www/app/Cargo.toml new file mode 100644 index 0000000..4167510 --- /dev/null +++ b/app/vendor/rune/www/app/Cargo.toml @@ -0,0 +1,25 @@ +[package] +name = "rune-www" +version = "0.0.1" +edition.workspace = true +license.workspace = true +description = "Rune's home page, drawn by Rune." +publish = false + +[lib] +crate-type = ["cdylib", "rlib"] + +[[bin]] +name = "rune-www" +path = "src/main.rs" + +[dependencies] +rune = { workspace = true } +rune-kit = { workspace = true, default-features = true } +rune-motion = { workspace = true } + +[target.'cfg(target_arch = "wasm32")'.dependencies] +wasm-bindgen = { workspace = true } + +[lints] +workspace = true diff --git a/app/vendor/rune/www/app/src/code.rs b/app/vendor/rune/www/app/src/code.rs new file mode 100644 index 0000000..563d275 --- /dev/null +++ b/app/vendor/rune/www/app/src/code.rs @@ -0,0 +1,133 @@ +//! Code examples cut from Rune's own source when the page is built, so an example can't drift +//! from the code it shows. A piece starts at the first line beginning with `from` (attributes +//! above it come along) and ends at `to`, just before `until`, or at the closing brace at the +//! starting line's indent. A marker that stops matching fails the tests. + +use rune::{El, Span, col, rich, row, text}; +use rune_kit::syntax::{Paint, Syntax, highlight}; + +use crate::REPO; +use crate::tokens::*; +use crate::ui::hairline; + +const HELLO: &str = include_str!("../../../examples/hello/src/main.rs"); +const SPRING_TESTS: &str = include_str!("../../../crates/rune-motion/tests/integration/spring.rs"); + +/// Where a snippet ends. +#[derive(Clone, Copy)] +pub enum End { + /// Just before the first later line starting with this, trailing blank lines dropped. + Until(&'static str), + /// At the first line from the start that starts with this. + To(&'static str), + /// At the closing brace at the first line's indent. + Brace, +} + +pub struct Snippet { + pub file: &'static str, + source: &'static str, + from: &'static str, + end: End, +} + +pub const HELLO_VIEW: Snippet = Snippet { file: "examples/hello/src/main.rs", source: HELLO, from: "fn view(", end: End::Until("fn main()") }; +pub const HELLO_TEST: Snippet = Snippet { file: "examples/hello/src/main.rs", source: HELLO, from: " fn a_tap_flips_the_switch", end: End::Brace }; +pub const RETARGET: Snippet = Snippet { + file: "crates/rune-motion/tests/integration/spring.rs", + source: SPRING_TESTS, + from: "fn animated_value_retargets_keeping_velocity", + end: End::To(" assert!((a.velocity(0.1) - v1).abs()"), +}; + +/// A cut: the code and the 1-based lines it came from. +#[derive(Debug, PartialEq)] +pub struct Cut { + pub code: String, + pub start: usize, + pub end: usize, +} + +fn indent(line: &str) -> usize { + line.len() - line.trim_start().len() +} + +impl Snippet { + pub fn cut(&self) -> Option<Cut> { + let lines: Vec<&str> = self.source.trim_end_matches('\n').split('\n').collect(); + let first = lines.iter().position(|l| l.starts_with(self.from))?; + let mut start = first; + while start > 0 && lines[start - 1].trim().starts_with("#[") { + start -= 1; + } + let end = match self.end { + End::Until(until) => { + let mut end = (first + 1..lines.len()).find(|&i| lines[i].starts_with(until))?.checked_sub(1)?; + while end > first && lines[end].trim().is_empty() { + end -= 1; + } + end + } + End::To(to) => (first..lines.len()).find(|&i| lines[i].starts_with(to))?, + End::Brace => { + let close = format!("{}}}", &lines[first][..indent(lines[first])]); + (first + 1..lines.len()).find(|&i| lines[i].trim_end() == close)? + } + }; + let taken = &lines[start..=end]; + let pad = taken.iter().filter(|l| !l.trim().is_empty()).map(|l| indent(l)).min().unwrap_or(0); + let mut out: Vec<String> = taken.iter().map(|l| l.get(pad..).unwrap_or("").to_owned()).collect(); + // A block cut short keeps its shape: an elision inside, then its closing brace. + let joined = out.join("\n"); + if joined.matches('{').count() > joined.matches('}').count() { + let lead = " ".repeat(indent(lines[first]).saturating_sub(pad)); + out.push(format!("{lead} // …")); + out.push(format!("{lead}}}")); + } + Some(Cut { code: out.join("\n"), start: start + 1, end: end + 1 }) + } +} + +fn paint(kind: Syntax) -> rune::Color { + match kind { + Syntax::Keyword => code_keyword(), + Syntax::String | Syntax::Number => code_string(), + Syntax::Function => code_call(), + Syntax::Comment => fg3(), + Syntax::Punctuation => fg2(), + _ => fg(), + } +} + +/// `code` as Rust, coloured like the rest of the page's code. +pub fn colored(code: &str) -> Vec<Span> { + highlight(Some("rust"), code) + .iter() + .map(|(range, p)| { + let color = match p { + Paint::Kind(k) => paint(*k), + Paint::Color(c) => *c, + }; + Span::new(range.start, range.end).color(color) + }) + .collect() +} + +/// A code block: the file and lines it came from, linked to GitHub, over the code. +pub fn block(key: &str, s: &Snippet) -> El { + let Some(cut) = s.cut() else { return col().key(key) }; + let href = format!("{REPO}/blob/dev/{}#L{}-L{}", s.file, cut.start, cut.end); + let file = format!("{}:{}–{}", s.file, cut.start, cut.end); + let lines_from = s.file.len(); + let head = row().key("head").w_full().justify_between().gap(16.0).px(16.0).py(8.0) + .child(row().key("source").href(href).shrink().hover_group() + .child(rich(file.clone(), vec![Span::new(0, lines_from).color(fg2()), Span::new(lines_from, file.len()).color(fg3())]) + .font(MONO_12).color(fg2()).wrap_anywhere().shrink().group_color(fg()))) + .child(text("Rust").font(MONO_12).color(fg3())); + let body = col().key("scroll").w_full().scroll_x() + .child(rich(cut.code.clone(), colored(&cut.code)).key("code").font(CODE).color(fg()).selectable(true).padding(16.0)); + col().key(key).role("figure").w_full().min_w(0.0).radius(R2).fill(surface1()).border(1.0, line()).clip_rounded(R2) + .child(head) + .child(hairline("rule")) + .child(body) +} diff --git a/app/vendor/rune/www/app/src/hero.rs b/app/vendor/rune/www/app/src/hero.rs new file mode 100644 index 0000000..2bfbeb9 --- /dev/null +++ b/app/vendor/rune/www/app/src/hero.rs @@ -0,0 +1,174 @@ +//! The hero: the wordmark, the claim, the lede and two buttons, beside a live card you can play +//! with (a switch, a spring picker and a puck to throw along a track). Nothing on it moves +//! until you touch it. + +use rune::tok; +use rune::{Color, Cx, Drag, El, Phase, Spring, TextStyle, Tx, col, el, oklch, oklcha, row, text}; + +use crate::tokens::*; +use crate::ui::{Button, button, prose}; +use crate::wordmark::{Glow, wordmark}; +use crate::{DOCS, REPO, State}; + +const SPRINGS: [(&str, Spring); 3] = + [("Snappy", Spring::new(0.25, 0.0)), ("Smooth", Spring::new(0.4, 0.0)), ("Bouncy", Spring::new(0.5, 0.3))]; +const CARD_W: f32 = 376.0; +const STAGE_H: f32 = 320.0; +const PUCK: f32 = 28.0; +const STOPS: usize = 4; + +pub struct Card { + pub on: bool, + pub spring: usize, + /// The puck's position along the track, 0 to 1. + pub at: f32, +} + +impl Default for Card { + fn default() -> Self { + Self { on: true, spring: 2, at: 0.0 } + } +} + +fn snap(at: f32) -> f32 { + let n = (STOPS - 1) as f32; + (at * n).round() / n +} + +fn switch(c: &Card) -> El { + let t = tok::theme(true); + let (w, h, k) = (44.0, 26.0, 22.0); + let inset = (h - k) / 2.0; + el().key("switch").role("switch").label("Lights").checked(c.on).focusable(true) + .size(w, h).radius(h / 2.0) + .fill(if c.on { ink() } else { t.control_off }) + .motion(SPRINGS[c.spring].1) + .on_press(|s: &mut State| s.card.on = !s.card.on) + .child(el().key("knob").size(k, k).radius(k / 2.0).fill(t.knob) + .absolute(if c.on { w - k - inset } else { inset }, inset) + .shadow(1.0, 3.0, t.knob_shadow)) +} + +fn picker(c: &Card, seg: f32) -> El { + let t = tok::theme(true); + let (h, pad) = (32.0, 3.0); + let mut segs = row().key("springs"); + for (i, (name, _)) in SPRINGS.into_iter().enumerate() { + let selected = i == c.spring; + segs = segs.child( + el().key(name).role("radio").label(name).checked(selected).focusable(true) + .size(seg, h - 2.0 * pad).center() + .on_press(move |s: &mut State| s.card.spring = i) + .child(text(name).font(TextStyle::new(13.0, 500.0)).color(if selected { t.text } else { t.text_secondary })), + ); + } + el().key("picker").role("radiogroup").label("Spring").size(seg * 3.0 + 2.0 * pad, h).radius(h / 2.0).fill(t.control_track) + .child(el().key("thumb").size(seg, h - 2.0 * pad).radius((h - 2.0 * pad) / 2.0) + .absolute(pad + seg * c.spring as f32, pad) + .fill(oklcha(1.0, 0.0, 0.0, 0.12)) + .motion(SPRINGS[c.spring].1)) + .child(segs.absolute(pad, pad)) +} + +fn track(c: &Card, track_w: f32) -> El { + let t = tok::theme(true); + let travel = track_w - PUCK; + let to_at = move |x: f32| ((x - PUCK / 2.0) / travel).clamp(0.0, 1.0); + let mut stops = row().key("stops").w(travel).h(PUCK).absolute(PUCK / 2.0, 0.0); + for i in 0..STOPS { + let x = travel * i as f32 / (STOPS - 1) as f32; + stops = stops.child(el().key(format!("stop-{i}")).size(4.0, 4.0).radius(2.0) + .fill(oklcha(1.0, 0.0, 0.0, 0.22)).absolute(x - 2.0, PUCK / 2.0 - 2.0)); + } + el().key("track").role("slider").label("Puck").range_value(f64::from(c.at), 0.0, 1.0) + .range_step(1.0 / (STOPS - 1) as f64) + .on_step(|s: &mut State, steps, _| s.card.at = snap(s.card.at + steps as f32 / (STOPS - 1) as f32).clamp(0.0, 1.0)) + .size(track_w, PUCK) + .motion(SPRINGS[c.spring].1) + .on_drag(move |s: &mut State, d: &mut Drag, tx: &mut Tx| match d.phase { + Phase::Down => { + d.data = s.card.at; + let puck = PUCK / 2.0 + s.card.at * travel; + if (d.x - puck).abs() > PUCK / 2.0 + 4.0 { + // Tapped the track: the puck springs to the nearest stop, keeping its speed. + s.card.at = snap(to_at(d.x)); + } + } + Phase::Move => { + let puck = PUCK / 2.0 + d.data * travel; + let grab = if (d.start_x - puck).abs() <= PUCK / 2.0 + 4.0 { d.start_x - puck } else { 0.0 }; + s.card.at = to_at(d.x - grab); + tx.instant(); + } + Phase::Up => { + s.card.at = if d.cancelled() { d.data } else { snap(s.card.at) }; + } + }) + .child(el().key("rail").size(travel, 2.0).radius(1.0).fill(t.control_off) + .absolute(PUCK / 2.0, PUCK / 2.0 - 1.0).a11y_hidden()) + .child(el().key("lit").size(travel * c.at, 2.0).radius(1.0).fill(ink()) + .absolute(PUCK / 2.0, PUCK / 2.0 - 1.0).a11y_hidden()) + .child(stops.a11y_hidden()) + .child(el().key("puck").size(PUCK, PUCK).radius(PUCK / 2.0).fill(t.knob) + .absolute(travel * c.at, 0.0) + .shadow(2.0, 8.0, oklcha(0.0, 0.0, 0.0, 0.5)).a11y_hidden()) +} + +fn line_of(key: &str, label: &str, control: El) -> El { + let t = tok::theme(true); + row().key(key).w_full().h(36.0).center_y() + .child(text(label.to_owned()).font(TextStyle::new(14.0, 400.0)).color(t.text_secondary).grow(1.0)) + .child(control) +} + +/// The live card in its black stage, with a caption. +fn live(c: &Card, cx: &Cx<State>, bp: Bp) -> El { + let stage = cx.layout_size("stage").map_or(520.0, |[w, _]| w); + let card_w = (stage - 16.0).clamp(280.0, CARD_W); + let pad = if card_w < CARD_W { 20.0 } else { 32.0 }; + let inner = card_w - 2.0 * pad; + let seg = ((inner - 76.0) / 3.0).min(88.0); + let card = col().key("card").w(card_w).padding(pad).gap(16.0).radius(20.0) + .fill(oklch(0.17, 0.006, 265.0)) + .border(1.0, oklcha(1.0, 0.0, 0.0, 0.08)) + .child(line_of("lights", "Lights", switch(c))) + .child(line_of("spring", "Spring", picker(c, seg))) + .child(el().key("gap").h(8.0)) + .child(track(c, inner)); + let live = col().key("live").role("figure").min_w(0.0) + .child(col().key("stage").w_full().h(STAGE_H).center().radius(R2).fill(Color::BLACK).border(1.0, line()).child(card)) + .child(text("Drawn by Rune, live. Flip the switch, pick a spring, throw the puck.").key("caption") + .font(TEXT_13).color(fg3()).wrap().mt(12.0)); + if bp.stack_hero() { live.w_full() } else { live.w(520.0) } +} + +pub fn hero(s: &State, cx: &Cx<State>, bp: Bp, glow: Glow) -> El { + let cell = cx.layout_with("hero-text", { + let width = s.glyphs.width as f32; + move |r| (r[2] / width).floor().clamp(2.0, 10.0) as u8 + }).unwrap_or(8); + let reduced = cx.is_reduced_motion(); + let masthead = col().key("masthead").w_full().label("Rune").role("image") + .on_hover_change(|s: &mut State, on: bool, _tx: &mut Tx| if on { let now = s.clock_now(); s.glints.masthead(now) }) + .on_visible(move |s: &mut State, on: bool, _tx: &mut Tx| { + let now = s.clock_now(); + s.glints.masthead_visible(on, reduced, now); + }) + .child(wordmark(&s.glyphs, f32::from(cell), glow)); + let text_col = col().key("hero-text").min_w(0.0); + let text_col = if bp.stack_hero() { text_col.w_full() } else { text_col.w(0.0).grow(1.0) }; + let text_col = text_col + .child(masthead) + .child(text("A Rust UI framework that draws every frame itself, at 120\u{a0}Hz.").key("hero-h").role("heading").level(1) + .font(bp.h1()).color(fg()).wrap().selectable(true).max_w(bp.h1().size * 16.0).mt(if bp.phone() { 32.0 } else { 48.0 })) + .child(prose("lede", "Rune brings its own GPU renderer, text, layout and springs. Views are plain Rust, a small app's first window opens in about 300\u{a0}ms, and the same code runs on macOS, Windows, Linux, iOS and the web.", bp.lede(), fg2()) + .max_w(MEASURE).mt(24.0)) + .child(row().key("actions").flex_wrap().gap(12.0).mt(32.0) + .child(button("github", "View on GitHub", REPO, Button::GitHub)) + .child(button("guide", "Read the guide", DOCS, Button::Secondary))); + let body = if bp.stack_hero() { col().gap(48.0) } else { row().gap(64.0).center_y() }; + body.key("hero").w_full() + .pt(if bp.stack_hero() { 32.0 } else { 64.0 }).pb(128.0) + .child(text_col) + .child(live(&s.card, cx, bp)) +} diff --git a/app/vendor/rune/www/app/src/lib.rs b/app/vendor/rune/www/app/src/lib.rs new file mode 100644 index 0000000..d785061 --- /dev/null +++ b/app/vendor/rune/www/app/src/lib.rs @@ -0,0 +1,190 @@ +//! Rune's home page, drawn by Rune. The page is one Rune app in web document mode: the browser +//! scrolls a semantic mirror of it (real headings, paragraphs and links), and the canvas draws +//! the band in view. `--html` exports the same tree as the static first frame, so the page reads +//! before the wasm arrives and without it. + +#![forbid(unsafe_code)] + +use std::collections::HashSet; +use std::time::Duration; + +use rune::time::Instant; +use rune::{AppSpec, Cx, El, ImageCache, Tx, col, memo}; + +mod code; +mod hero; +mod pipeline; +mod sections; +mod springs; +mod tokens; +mod ui; +mod wordmark; + +use sections::{HELLO, HOME, LIGHT, GLASS, METAL, SESSION, STREAMING, ready}; +use tokens::*; +use wordmark::{Glints, Glyphs, Which}; + +pub const TITLE: &str = "Rune · A Rust UI framework with its own GPU renderer"; +pub const REPO: &str = "https://github.com/anomalyco/rune"; +pub const DOCS: &str = "https://github.com/anomalyco/rune/blob/dev/crates/rune/README.md"; +/// The home page, relative to the site's host. +pub const BRAND: &str = "/rune/"; +/// The commit the Cargo line pins: the one the site was built from. +pub const REV: &str = match option_env!("RUNE_REV") { + Some(rev) => rev, + None => "dev", +}; +/// How long the copy button says "Copied". +const COPIED: f64 = 1.6; + +pub struct State { + glyphs: Glyphs, + card: hero::Card, + spring: springs::Demo, + pipeline: pipeline::Pipeline, + glints: Glints, + images: Option<ImageCache>, + /// The sections whose pictures the reader has reached: below-the-fold files are asked for + /// then, so a first scroll isn't competing with seven decodes and uploads. + seen: HashSet<&'static str>, + copied_until: Option<f64>, + /// The frame's time, in seconds since start, and when it was read. + clock: (f64, Instant), + not_found: bool, +} + +impl State { + fn new() -> State { + State { + glyphs: Glyphs::new(), + card: hero::Card::default(), + spring: springs::Demo::default(), + pipeline: pipeline::Pipeline::default(), + glints: Glints::default(), + images: None, + seen: HashSet::new(), + copied_until: None, + clock: (0.0, rune::time::now()), + not_found: not_found(), + } + } + + /// Now, on the frame clock: for handlers, which run between frames. + fn clock_now(&self) -> f64 { + self.clock.0 + self.clock.1.elapsed().as_secs_f64() + } + + fn copied(&mut self) { + self.copied_until = Some(self.clock_now() + COPIED); + } +} + +/// The 404 page is exported natively with `RUNE_WWW_PAGE=404`; the browser never runs it. +fn not_found() -> bool { + rune::env::var("RUNE_WWW_PAGE").is_some_and(|p| p == "404") +} + +fn poll(s: &mut State, t: f64, tx: &mut Tx) -> bool { + s.clock = (t, rune::time::now()); + let mut changed = false; + let mut moving = false; + let was = s.spring.running(); + let on = s.spring.tick(t); + changed |= was || on; + moving |= on; + let was = s.pipeline.active(); + let on = s.pipeline.tick(t); + changed |= was || on; + moving |= on; + let (glinted, glinting, next) = s.glints.tick(t); + changed |= glinted; + moving |= glinting; + if let Some(next) = next { + tx.wake_after(Duration::from_secs_f64((next - t).max(0.0))); + } + if let Some(until) = s.copied_until { + if t >= until { + s.copied_until = None; + changed = true; + } else { + tx.wake_after(Duration::from_secs_f64(until - t)); + } + } + if moving { + tx.wake_after(Duration::ZERO); + } + changed +} + +fn view(s: &State, cx: &mut Cx<State>) -> El { + let bp = cx.layout_with("page", |r| Bp::of(r[2])).unwrap_or(Bp { at: 1000 }); + let reduced = cx.is_reduced_motion(); + let t = s.clock.0; + let gutter = bp.gutter(); + let framed = |e: El| e.w_full().max_w(CONTENT + 2.0 * gutter).px(gutter); + let main = if s.not_found { col().child(sections::not_found(bp)) } else { home(s, cx, bp, reduced) }; + col().key("page").w_full().fill(BG).items_center() + .child(framed(sections::topbar(s, s.glints.glow(Which::Brand, t, reduced)))) + .child(framed(main.key("main").role("main"))) + .child(framed(sections::footer())) +} + +fn home(s: &State, cx: &Cx<State>, bp: Bp, reduced: bool) -> El { + let images = s.images.as_ref(); + let glow = s.glints.glow(Which::Masthead, s.clock.0, reduced); + let springs = sections::springs_intro(bp) + .child(springs::demo(s, cx, bp)) + .child(memo("retarget", bp, sections::retarget_code)); + let frame = sections::frame_intro(bp).child(pipeline::pipeline(&s.pipeline, cx.layout_size("pl"), bp, reduced)); + let (hello, _hello) = ready(images, cx, &[&HELLO]); + // The rest of the page's pictures arrive when their section does; an export outside a browser + // has every file on disk and writes them all. + let eager = cfg!(not(target_arch = "wasm32")); + let shown = |name: &str| eager || s.seen.contains(name); + let (gallery, _gallery) = if shown("renderer") { ready(images, cx, &[&METAL, &GLASS, &LIGHT]) } else { (Vec::new(), Vec::new()) }; + let (shots, _shots) = if shown("opencode") { ready(images, cx, &[&SESSION, &HOME, &STREAMING]) } else { (Vec::new(), Vec::new()) }; + col().w_full() + .child(hero::hero(s, cx, bp, glow)) + .child(memo("views", (bp, hello), || sections::views(cx, images, bp))) + .child(springs) + .child(frame) + .child(memo("renderer", (bp, gallery), || sections::gallery(cx, images, bp))) + .child(memo("opencode", (bp, shots), || sections::opencode(cx, images, bp))) + .child(memo("agents", bp, || sections::agents(bp))) + .child(memo("platforms", bp, || sections::platforms(bp))) + .child(sections::cta(bp, s.copied_until.is_some())) +} + +pub fn spec() -> AppSpec<State> { + AppSpec { + families: ("Geist", "Geist Mono"), + setup: Some(|s, waker| s.images = Some(ImageCache::new(waker))), + poll: Some(poll), + ..AppSpec::new(TITLE, (1200.0, 900.0), State::new, view) + } +} + +/// The page as an app: document mode, with the page's own font files. +pub fn app() -> rune::App<State> { + rune::App::new(spec()).web_document().font_url("fonts/geist.ttf").font_url("fonts/geist-mono.ttf") +} + +#[cfg_attr(target_arch = "wasm32", wasm_bindgen::prelude::wasm_bindgen(start))] +pub fn start() { + #[cfg(target_arch = "wasm32")] + if let Err(error) = app().try_run() { + log_error(&error); + } + #[cfg(not(target_arch = "wasm32"))] + app().run(); +} + +#[cfg(target_arch = "wasm32")] +#[wasm_bindgen::prelude::wasm_bindgen] +extern "C" { + #[wasm_bindgen(js_namespace = console, js_name = error)] + fn log_error(message: &str); +} + +#[cfg(test)] +mod tests; diff --git a/app/vendor/rune/www/app/src/main.rs b/app/vendor/rune/www/app/src/main.rs new file mode 100644 index 0000000..5053832 --- /dev/null +++ b/app/vendor/rune/www/app/src/main.rs @@ -0,0 +1,5 @@ +#![forbid(unsafe_code)] + +fn main() { + rune_www::start(); +} diff --git a/app/vendor/rune/www/app/src/pipeline.rs b/app/vendor/rune/www/app/src/pipeline.rs new file mode 100644 index 0000000..6256912 --- /dev/null +++ b/app/vendor/rune/www/app/src/pipeline.rs @@ -0,0 +1,235 @@ +//! One frame's path as a row of steps (a column on a phone). When it comes into view a light +//! runs along it once, warming each step as it passes; a click runs it again. Under reduced +//! motion the steps light together and fade. + +use rune::{Color, El, col, el, row, text}; + +use crate::State; +use crate::tokens::*; + +pub const STEPS: [(&str, &str); 7] = [ + ("Input", "pointer, keys, text"), + ("State", "your struct, changed"), + ("View", "your view, called again"), + ("Diff", "keyed, against the last"), + ("Layout", "flex and grid, by Taffy"), + ("Springs", "position and velocity"), + ("Draw", "one instanced draw"), +]; + +/// Seconds from the first step to the last. +const TRAVEL: f64 = 1.8; +const RISE: f64 = 0.06; +/// Cooling time constant: a lit step fades, it never cuts out. +const TAU: f64 = 0.32; +const COMET: f32 = 64.0; +const GAP_ROW: f32 = 12.0; +const GAP_COL: f32 = 8.0; + +fn smootherstep(x: f64) -> f64 { + let x = x.clamp(0.0, 1.0); + x * x * x * (x * (x * 6.0 - 15.0) + 10.0) +} + +/// When the head passes step `i`, in seconds after the start. +fn passes(i: usize) -> f64 { + let target = i as f64 / (STEPS.len() - 1) as f64; + let (mut lo, mut hi) = (0.0, 1.0); + for _ in 0..18 { + let m = (lo + hi) / 2.0; + if smootherstep(m) < target { lo = m } else { hi = m } + } + lo * TRAVEL +} + +#[derive(Default)] +pub struct Pipeline { + /// When the light set off, while it's lit. + start: Option<f64>, + /// When the reduced-motion fade began, while it shows. + fade: Option<f64>, + played: bool, + visible: bool, + /// The time the view draws. + t: f64, +} + +/// What a frame of the light looks like. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Light { + pub heat: [f32; 7], + /// Where the head is (0 to 1 along the steps) and how bright. + pub head: f32, + pub comet: f32, +} + +impl Light { + const DARK: Light = Light { heat: [0.0; 7], head: 0.0, comet: 0.0 }; +} + +impl Pipeline { + pub fn active(&self) -> bool { + self.start.is_some() || self.fade.is_some() + } + + pub fn play(&mut self, now: f64, reduced: bool) { + if reduced { + self.fade = Some(now); + } else { + self.start = Some(now); + } + } + + pub fn set_visible(&mut self, on: bool, now: f64, reduced: bool) { + self.visible = on; + if !on { + // Off screen: finish cooled, without drawing the rest. + self.start = None; + self.fade = None; + } else if !self.played { + self.played = true; + self.play(now, reduced); + } + } + + pub fn light(&self) -> Light { + if let Some(f) = self.fade { + let s = self.t - f; + let h = if s < 0.75 { smootherstep(s / 0.15) } else { 1.0 - smootherstep((s - 0.75) / 0.15) } as f32; + return Light { heat: [h; 7], ..Light::DARK }; + } + let Some(start) = self.start else { return Light::DARK }; + let t = self.t - start; + let tail = t - TRAVEL; + let comet = if tail < 0.0 { 1.0 } else { (-tail / TAU).exp() as f32 }; + let mut heat = [0.0; 7]; + for (i, h) in heat.iter_mut().enumerate() { + let since = t - passes(i); + let tau = if i == STEPS.len() - 1 { TAU * 2.5 } else { TAU }; + let v = if since < 0.0 { 0.0 } else if since < RISE { since / RISE } else { (-(since - RISE) / tau).exp() }; + *h = if v > 0.004 { v as f32 } else { 0.0 }; + } + Light { heat, head: smootherstep(t / TRAVEL) as f32, comet: if comet > 0.004 { comet } else { 0.0 } } + } + + /// Advances to `now`. True while the light is on. + pub fn tick(&mut self, now: f64) -> bool { + self.t = now; + if let Some(f) = self.fade + && now - f >= 0.9 + { + self.fade = None; + } + if let Some(s) = self.start { + let light = self.light(); + let lit = now - s < TRAVEL || light.comet > 0.0 || light.heat.iter().any(|&h| h > 0.0); + if !lit { + self.start = None; + } + } + self.start.is_some() || self.fade.is_some() + } +} + +/// The centre of each step in a box `w` by `h`, laid out as a row or a column. +fn centers(w: f32, h: f32, stacked: bool) -> Vec<[f32; 2]> { + let n = STEPS.len() as f32; + (0..STEPS.len()) + .map(|i| { + let i = i as f32; + if stacked { + let step = (h - GAP_COL * (n - 1.0)) / n; + [w / 2.0, i * (step + GAP_COL) + step / 2.0] + } else { + let step = (w - GAP_ROW * (n - 1.0)) / n; + [i * (step + GAP_ROW) + step / 2.0, h / 2.0] + } + }) + .collect() +} + +fn along(c: &[[f32; 2]], p: f32) -> [f32; 2] { + let span = (c.len() - 1) as f32 * p.clamp(0.0, 1.0); + let i = (span.floor() as usize).min(c.len() - 2); + let f = span - i as f32; + let (a, b) = (c[i], c[i + 1]); + [a[0] + (b[0] - a[0]) * f, a[1] + (b[1] - a[1]) * f] +} + +fn step(i: usize, heat: f32, stacked: bool) -> El { + let (name, note) = STEPS[i]; + let body = if stacked { row().justify_between().gap(16.0) } else { col().gap(4.0).min_h(96.0).w(0.0).grow(1.0) }; + let glow = ink().alpha(0.35); + body.key(format!("pl-{}", name.to_lowercase())).role("listitem").padding(12.0).radius(R2).fill(rune::oklch(0.15, 0.004, 265.0)).border(1.0, line()) + .child(el().key("heat").pin(Some(0.0), Some(0.0), Some(0.0), Some(0.0)).radius(R2) + .fill(ink().alpha(0.18)).border(1.0, ink().alpha(0.7)).shadow(0.0, 24.0, glow) + .opacity(heat).a11y_hidden()) + .child(text(name).key("name").font(TEXT_14_MEDIUM).color(fg())) + .child(text(note).key("note").font(MONO_12).color(fg3()).wrap()) +} + +pub fn pipeline(p: &Pipeline, size: Option<[f32; 2]>, bp: Bp, reduced: bool) -> El { + let stacked = bp.stack_split(); + let light = p.light(); + let [w, h] = size.unwrap_or([1000.0, 96.0]); + let c = centers(w, h, stacked); + let (a, b) = (c[0], c[STEPS.len() - 1]); + let wire = if stacked { el().size(1.0, b[1] - a[1]) } else { el().size(b[0] - a[0], 1.0) }; + let head = along(&c, light.head); + let comet = el().key("comet").size(COMET, COMET).radius(COMET / 2.0) + .radial_gradient([0.5, 0.5], COMET / 2.0, [(0.0, glint()), (0.2, ink().alpha(0.6)), (1.0, Color::TRANSPARENT)]) + .absolute(head[0] - COMET / 2.0, head[1] - COMET / 2.0) + .opacity(light.comet).a11y_hidden(); + let body = if stacked { col().gap(GAP_COL) } else { row().gap(GAP_ROW) }; + let mut steps = body.key("pl").role("list").label("One frame, step by step").w_full(); + for i in 0..STEPS.len() { + steps = steps.child(step(i, light.heat[i], stacked)); + } + // The wire and the light run behind the steps, outside the list so it holds only steps. + let diagram = col().key("pl-box").w_full() + .on_press(move |s: &mut State| { + let now = s.clock_now(); + s.pipeline.play(now, reduced); + }) + .on_visible(move |s: &mut State, on, _tx: &mut rune::Tx| { + let now = s.clock_now(); + s.pipeline.set_visible(on, now, reduced); + }) + .child(wire.key("wire").fill(line2()).absolute(a[0], a[1]).a11y_hidden()) + .child(comet) + .child(steps); + col().key("pipeline").role("figure").w_full().mt(32.0) + .child(diagram) + .child(text("Click the diagram to run the frame again.").key("caption").font(TEXT_13).color(fg3()).wrap().max_w(MEASURE).mt(12.0)) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_light_runs_once_and_cools() { + let mut p = Pipeline::default(); + p.set_visible(true, 1.0, false); + assert!(p.tick(1.0)); + assert!(p.tick(1.0 + TRAVEL / 2.0)); + let mid = p.light(); + assert!(mid.heat[0] > 0.0 && mid.heat[6] == 0.0, "{mid:?}"); + assert!(p.tick(1.0 + TRAVEL + 0.1)); + assert!(!p.tick(1.0 + TRAVEL + 6.0), "it stops asking for frames once cool"); + assert_eq!(p.light(), Light::DARK); + p.set_visible(false, 9.0, false); + p.set_visible(true, 10.0, false); + assert!(!p.tick(10.0), "it plays on the first view only"); + } + + #[test] + fn reduced_motion_fades_every_step_together() { + let mut p = Pipeline::default(); + p.set_visible(true, 0.0, true); + assert!(p.tick(0.4)); + assert_eq!(p.light().heat, [1.0; 7]); + assert_eq!(p.light().comet, 0.0); + assert!(!p.tick(1.0)); + } +} diff --git a/app/vendor/rune/www/app/src/sections.rs b/app/vendor/rune/www/app/src/sections.rs new file mode 100644 index 0000000..6119f31 --- /dev/null +++ b/app/vendor/rune/www/app/src/sections.rs @@ -0,0 +1,288 @@ +//! The page below the hero: each section a heading that says its point, a paragraph, and the +//! code, demo or pictures that back it. The tree is the same at every width; only styles change +//! at the breakpoints, so the static page can switch them with `@media` rules. + +use rune::{Color, Cx, El, Image, ImageCache, Span, SurfaceFit, TextStyle, Tx, col, el, rich, row, text}; + +use crate::code::{self, HELLO_TEST, HELLO_VIEW, RETARGET}; +use crate::tokens::*; +use crate::ui::{Button, button, hairline, intro, linked, nav_link, prose}; +use crate::wordmark::{Glow, wordmark}; +use crate::{BRAND, DOCS, REPO, REV, State}; + +/// A section: its heading (an anchor at `id`) and what follows. +pub fn section(id: &str, title: &str, bp: Bp) -> El { + let h2 = bp.h2(); + col().key(id).role("region").label(title).w_full().pt(if bp.phone() { 32.0 } else { 64.0 }).pb(32.0) + .child(text(title.to_owned()).key(format!("{id}-h")).role("heading").level(2) + .font(h2).color(fg()).wrap().selectable(true).max_w(h2.size * 22.0)) +} + +/// `e` across the whole width when the parent stacks, else a share `grow` of the row. +pub fn fill(e: El, stacked: bool, grow: f32) -> El { + if stacked { e.w_full() } else { e.w(0.0).grow(grow) } +} + +pub struct Picture<'a> { + pub name: &'a str, + /// The widths, in pixels, it was exported at: `img/{name}-{width}.avif`. + pub widths: &'a [u32], + /// How wide it shows, at most, in points: the guess before layout. + pub pt: f32, + pub alt: &'a str, + /// Width over height, so the page keeps its place before the image arrives. + pub aspect: f32, +} + +impl Picture<'_> { + /// The file for the width it shows at, from every size there is. It plans for at most 2.2 + /// times its box: past that the extra pixels of a larger file are bytes the browser decodes + /// and Rune mip-maps and uploads on the main thread, and a 345-point phone tile at `@3x` + /// can't tell 760 pixels from 1520. + fn image(&self, images: Option<&ImageCache>, cx: &Cx<State>) -> Option<Image> { + let shown = cx.layout_size(self.name).map_or(self.pt, |s| s[0]); + let scale = cx.env().scale.max(1.0); + let plan = shown.min(shown * 2.2 / scale); + let urls: Vec<(String, u32)> = self.widths.iter().map(|&w| (format!("img/{}-{w}.avif", self.name), w)).collect(); + let sources: Vec<(&str, u32)> = urls.iter().map(|(u, w)| (u.as_str(), *w)).collect(); + images.map(|c| c.url_set(&sources, plan, scale)) + } + + /// The image as an element, `fit` into its box. + pub fn el(&self, images: Option<&ImageCache>, cx: &Cx<State>, fit: SurfaceFit) -> El { + let e = el().key(self.name.to_owned()).role("image").label(self.alt).w_full(); + match self.image(images, cx) { + Some(img) => e.pixels_fit(img.pixels(), fit), + None => e, + } + } +} + +/// Which file each picture in `pics` shows and whether it has arrived, for a memo's version. +/// Hold the handles while the memo builds, so its elements find the same images. +pub fn ready(images: Option<&ImageCache>, cx: &Cx<State>, pics: &[&Picture]) -> (Vec<(Option<String>, bool)>, Vec<Image>) { + let held: Vec<Image> = pics.iter().filter_map(|p| p.image(images, cx)).collect(); + (held.iter().map(|i| (i.pixels().source_url().map(str::to_owned), i.is_ready())).collect(), held) +} + +pub const HELLO: Picture = Picture { + name: "hello", + widths: &[320, 640], + pt: 320.0, + alt: "A dark window reading “Lights on” above a blue switch that is on", + aspect: 1.6, +}; +pub const METAL: Picture = + Picture { name: "metal", widths: &[760, 1520], pt: 740.0, alt: "A ball of liquid chrome on black, reflecting a cool studio light", aspect: 16.0 / 9.0 }; +pub const GLASS: Picture = Picture { + name: "glass", + widths: &[380, 760], + pt: 360.0, + alt: "A frosted glass tile over a blue disc, sharp beside the glass and soft through it", + aspect: 16.0 / 9.0, +}; +pub const LIGHT: Picture = + Picture { name: "light", widths: &[380, 760], pt: 360.0, alt: "Nine raised keys under one soft light, the middle one lit blue", aspect: 16.0 / 9.0 }; +pub const SESSION: Picture = Picture { + name: "opencode-session", + widths: &[720, 1120, 1680, 2240], + pt: 1120.0, + alt: "OpenCode drawn by Rune: a session with a sidebar of projects and a conversation with code", + aspect: 2560.0 / 1640.0, +}; +pub const HOME: Picture = + Picture { name: "opencode-home", widths: &[560, 1100], pt: 548.0, alt: "OpenCode drawn by Rune: the home screen with a prompt field", aspect: 2560.0 / 1640.0 }; +pub const STREAMING: Picture = + Picture { name: "opencode-streaming", widths: &[560, 1100], pt: 548.0, alt: "OpenCode drawn by Rune: a reply streaming in", aspect: 2560.0 / 1640.0 }; + +/// The header: the wordmark home and two links. +pub fn topbar(s: &State, glow: Glow) -> El { + row().key("top").role("banner").w_full().h(TOPBAR).justify_between().center_y() + .child(row().key("brand").href(BRAND).label("Rune home").h(28.0).center_y() + .on_hover_change(|s: &mut State, on: bool, _tx: &mut Tx| if on { let now = s.clock_now(); s.glints.brand(now) }) + .child(wordmark(&s.glyphs, 2.0, glow))) + .child(row().key("nav").role("navigation").label("Rune").gap(24.0) + .child(nav_link("nav-guide", "Guide", DOCS, TEXT_14)) + .child(nav_link("nav-github", "GitHub", REPO, TEXT_14))) +} + +pub fn views(cx: &Cx<State>, images: Option<&ImageCache>, bp: Bp) -> El { + let stacked = bp.stack_split(); + let shot = col().key("shot").role("figure").gap(8.0) + .child(HELLO.el(images, cx, SurfaceFit::Fill).aspect_ratio(HELLO.aspect).radius(R2)) + .child(prose("caption", "What it draws, rendered headless with `--snap`", TEXT_13, fg3())); + let split = if stacked { col() } else { row() }.key("split").w_full().gap(24.0).mt(32.0) + .child(fill(code::block("hello", &HELLO_VIEW), stacked, 1.0)) + .child(if stacked { shot.w_full().max_w(320.0) } else { shot.w(320.0) }); + section("views", "A view is a plain Rust function of your state.", bp) + .child(intro("views-p", "There is no markup and no macro language. `view` reads the state and returns elements; a handler changes the state and Rune draws what follows. Give an element `.motion()` and it moves to its new layout on a spring.")) + .child(split) +} + +pub fn springs_intro(bp: Bp) -> El { + section("springs", "Every animation is a spring that keeps its speed when you change your mind.", bp) + .child(intro("springs-p", "Springs take SwiftUI's numbers, a duration and a bounce, and are solved exactly, so a retarget starts from where the value is and how fast it's going. Nothing animates on the first frame, a finger moves things directly, and reduced motion swaps travel for a short fade.")) +} + +pub fn retarget_code() -> El { + code::block("retarget", &RETARGET).mt(32.0) +} + +pub fn frame_intro(bp: Bp) -> El { + section("frame", "Every frame takes the same short path, from your input to one draw call.", bp) + .child(intro("frame-p", "Input changes your state. Rune calls your view, diffs it by key against the last one, lays it out with Taffy, moves what changed on springs and draws the whole window as one batch of instanced quads. At 120\u{a0}Hz all of it has 8.33\u{a0}ms, and an idle window draws nothing.")) +} + +/// A gallery tile: the render fading into the page's black at its edges, its caption under it. +fn tile(cx: &Cx<State>, images: Option<&ImageCache>, p: &Picture, caption: &str, frame: impl FnOnce(El) -> El) -> El { + let key = format!("{}-frame", p.name); + let [w, h] = cx.layout_size(&key).unwrap_or([360.0, 202.5]); + let vignette = el().key("vignette").pin(Some(0.0), Some(0.0), Some(0.0), Some(0.0)) + .radial_gradient([0.5, 0.5], [w / 2.0, h / 2.0], [(0.58, Color::TRANSPARENT), (1.0, Color::BLACK)]) + .a11y_hidden(); + let img = p.el(images, cx, SurfaceFit::Fill).h_full(); + col().key(format!("{}-tile", p.name)).role("figure").w_full() + .child(frame(el().key(key).w_full().radius(R2).clip_rounded(R2).child(img).child(vignette))) + .child(text(caption.to_owned()).key("caption").font(TEXT_13).color(fg3()).w_full().align(rune::Align::Center)) +} + +pub fn gallery(cx: &Cx<State>, images: Option<&ImageCache>, bp: Bp) -> El { + let stacked = bp.stack_gallery(); + let metal = tile(cx, images, &METAL, "Liquid metal", |f| if stacked { f.aspect_ratio(METAL.aspect) } else { f.grow(1.0) }); + let small = |p: &Picture, caption: &str| tile(cx, images, p, caption, |f| f.aspect_ratio(p.aspect)); + let side = col().key("side").gap(24.0).child(small(&GLASS, "Frosted glass")).child(small(&LIGHT, "Raised keys under one light")); + let body = if stacked { col() } else { row() }.key("gallery").w_full().gap(24.0).mt(32.0) + // Two of three columns and the gap between them: 24 + 2/3 of what's left after both gaps. + .child(if stacked { metal.w_full() } else { metal.w(24.0).grow(2.0) }) + .child(fill(side, stacked, 1.0)); + section("renderer", "Metal, glass and light are drawn by the same renderer.", bp) + .child(intro("renderer-p", "They're GPU shaders, drawn live. These stills come straight out of Rune.")) + .child(body) + // The pictures are megabytes to read back and upload: they're asked for when the section + // comes on screen, not while the reader is still on the hero. + .on_visible(|s: &mut State, on: bool, _: &mut Tx| if on { s.seen.insert("renderer"); }) +} + +fn screen(cx: &Cx<State>, images: Option<&ImageCache>, p: &Picture) -> El { + let img = p.el(images, cx, SurfaceFit::Fill).aspect_ratio(p.aspect); + col().key(format!("{}-fig", p.name)).role("figure").w_full().radius(R2).clip_rounded(R2) + .child(img) + .child(el().key("outline").pin(Some(0.0), Some(0.0), Some(0.0), Some(0.0)).radius(R2).border(1.0, line()).a11y_hidden()) +} + +pub fn opencode(cx: &Cx<State>, images: Option<&ImageCache>, bp: Bp) -> El { + let stacked = bp.stack_gallery(); + let pair = if stacked { col() } else { row() }.key("pair").w_full().gap(24.0) + .child(fill(screen(cx, images, &HOME), stacked, 1.0)) + .child(fill(screen(cx, images, &STREAMING), stacked, 1.0)); + section("opencode", "OpenCode's desktop app is the test Rune is built against.", bp) + .child(intro("opencode-p", "Rune's first big job is rebuilding OpenCode's desktop app and raising its bar: long streaming sessions, markdown and code, window chrome and scroll momentum. These screens are drawn by Rune.")) + .child(col().key("screens").w_full().gap(24.0).mt(32.0).child(screen(cx, images, &SESSION)).child(pair)) + .on_visible(|s: &mut State, on: bool, _: &mut Tx| if on { s.seen.insert("opencode"); }) +} + +const FACTS: [(&str, &str); 3] = [ + ("A reference renderer.", "`rune-ref` draws the same scenes on the CPU, and golden tests hold the GPU within two levels per channel of it."), + ("A motion audit.", "Example apps run scripted scenarios headless at 120\u{a0}fps, and a checker flags snaps, pops, jumps and retargets that lose their speed."), + ("Over 2,600 tests", "across the framework, its components and its motion."), +]; + +pub fn agents(bp: Bp) -> El { + let stacked = bp.stack_split(); + let mut facts = if stacked { col() } else { row() }.key("facts").role("list").w_full().gap(24.0).mt(32.0); + for (i, (lead, rest)) in FACTS.into_iter().enumerate() { + let item = col().key(format!("fact-{i}")).role("listitem").gap(4.0) + .child(text(lead).key("lead").font(TEXT_14_MEDIUM).color(fg()).wrap().selectable(true)) + .child(prose("rest", rest, TEXT_14, fg2())); + facts = facts.child(fill(item, stacked, 1.0)); + } + section("agents", "An agent can build, run and check a Rune app without a screen.", bp) + .child(intro("agents-p", "Tests drive the real runtime: tap an element by key, step the clock, read where things are. Any app renders headless to a PNG with `--snap`, to a strip of frames with `--frames`, and prints its element tree with `--tree`.")) + .child(code::block("hello-test", &HELLO_TEST).mt(32.0)) + .child(facts) +} + +const PLATFORMS: [(&str, &str); 5] = [ + ("macOS", "Rune's own Metal backend"), + ("Windows", "wgpu; windows stay hidden until their first frame"), + ("Linux", "wgpu on X11 and Wayland"), + ("iOS", "Embedded in UIKit or SwiftUI"), + ("Web", "WebGPU on one canvas, experimental"), +]; + +pub fn platforms(bp: Bp) -> El { + let stacked = bp.stack_split(); + let mut list = if stacked { col() } else { row() }.key("platforms-list").role("list").w_full().mt(32.0).radius(R2).border(1.0, line()); + for (i, (name, note)) in PLATFORMS.into_iter().enumerate() { + let item = if stacked { row().justify_between().center_y().gap(16.0) } else { col().gap(4.0) }; + let item = fill(item, stacked, 1.0); + let mut item = item.key(name.to_lowercase()).role("listitem").padding(16.0) + .child(text(name).key("name").font(TEXT_16_MEDIUM).color(fg())) + .child(text(note).key("note").font(TEXT_13).color(fg3()).wrap().shrink().align(if stacked { rune::Align::End } else { rune::Align::Start })); + if i > 0 { + // The hairline between this platform and the last, inside the item so the list holds only items. + let rule = el().key("rule").fill(line()).a11y_hidden(); + let rule = if stacked { rule.pin(Some(0.0), Some(0.0), Some(0.0), None).h(1.0) } else { rule.pin(Some(0.0), Some(0.0), None, Some(0.0)).w(1.0) }; + item = item.child(rule); + } + list = list.child(item); + } + section("platforms", "The same code runs on macOS, Windows, Linux, iOS and the web.", bp).child(list) +} + +/// The Cargo line, as the CTA shows and copies it. +pub fn cargo_line() -> String { + format!("rune = {{ git = \"{REPO}\", rev = \"{REV}\" }}") +} + +fn cargo_spans(line: &str) -> Vec<Span> { + let mut spans = vec![Span::new(0, 4).color(code_call())]; + let mut in_string = None; + for (i, c) in line.char_indices() { + match (c, in_string) { + ('"', None) => in_string = Some(i), + ('"', Some(start)) => { + spans.push(Span::new(start, i + 1).color(code_string())); + in_string = None; + } + ('=' | '{' | '}' | ',', None) => spans.push(Span::new(i, i + 1).color(fg2())), + _ => {} + } + } + spans +} + +pub fn cta(bp: Bp, copied: bool) -> El { + let cargo = cargo_line(); + let copy = row().key("copy").role("button").label(if copied { "Copied" } else { "Copy" }).focusable(true) + .h(28.0).px(12.0).mr(8.0).radius(14.0).center_y().fill(surface2()).hover(Color::WHITE.alpha(0.04)) + .on_press_tx(|s: &mut State, tx: &mut Tx| { + tx.copy(cargo_line()); + s.copied(); + }) + .child(text(if copied { "Copied" } else { "Copy" }).font(TEXT_12_MEDIUM).color(fg2()).a11y_hidden()); + let copyline = row().key("copyline").w_full().max_w(832.0).mt(32.0).center_y().radius(R2).fill(surface1()).border(1.0, line()) + .child(col().key("scroll").w(0.0).grow(1.0).min_w(0.0).scroll_x().scroll_edge_fade(24.0) + .child(rich(cargo.clone(), cargo_spans(&cargo)).key("cargo").font(MONO_13).color(fg()).selectable(true).px(16.0).py(12.0))) + .child(copy); + section("cta", "Pin a commit and start with one view.", bp).pb(96.0) + .child(intro("cta-p", "Rune isn't on crates.io yet. Add it from Git at a commit, then start from `examples/hello`.")) + .child(copyline) + .child(row().key("actions").flex_wrap().gap(12.0).mt(32.0) + .child(button("cta-guide", "Read the guide", DOCS, Button::Primary)) + .child(button("cta-examples", "Browse the examples", &format!("{REPO}/tree/dev/examples"), Button::Secondary))) +} + +pub fn footer() -> El { + row().key("footer").role("contentinfo").w_full().justify_between().flex_wrap().gaps(8.0, 24.0).py(32.0) + .child(hairline("rule").pin(Some(0.0), Some(0.0), Some(0.0), None)) + .child(text("Rune is open source under the MIT license.").key("license").font(TEXT_13).color(fg3()).selectable(true)) + .child(linked("made", "Made by [Anomaly](https://anoma.ly).", TEXT_13, fg3())) +} + +/// The page for a path that isn't there. +pub fn not_found(bp: Bp) -> El { + col().key("notfound").w_full().py(96.0).min_h(480.0) + .child(text("There's no page here.").key("notfound-h").role("heading").level(1).font(TextStyle::new(40.0, 500.0).lh(48.0).tracking(-1.0)).color(fg()).wrap()) + .child(linked("notfound-p", &format!("Try [Rune's home page]({BRAND}) or the [code on GitHub]({REPO})."), bp.lede(), fg2()).mt(24.0)) +} diff --git a/app/vendor/rune/www/app/src/springs.rs b/app/vendor/rune/www/app/src/springs.rs new file mode 100644 index 0000000..4f300f3 --- /dev/null +++ b/app/vendor/rune/www/app/src/springs.rs @@ -0,0 +1,331 @@ +//! The springs demo: a puck on a track driven by one of Rune's springs. Click to send it +//! somewhere, click again before it lands, or grab it and throw it. The trace under it plots +//! its position over the last 2.4 s: with velocity kept, every retarget bends the curve +//! smoothly. It draws frames only while something moves and only while it's on screen. + +use std::collections::VecDeque; + +use rune::{AnimExt, Color, Cx, Drag, El, LineCap, Phase, Shape, Spring, TextStyle, Tx, Velocity, canvas, col, el, oklcha, row, text}; +use rune_motion::Animated; + +use crate::State; +use crate::tokens::*; +use crate::ui::shape_dot; + +pub const SPRINGS: [(&str, &str, Spring); 3] = [ + ("Snappy", "0.25s", Spring::new(0.25, 0.0)), + ("Smooth", "0.4s", Spring::new(0.4, 0.0)), + ("Bouncy", "0.5s · 0.3", Spring::new(0.5, 0.3)), +]; +const STOPS: usize = 5; +/// Seconds of history in the trace. +const WINDOW: f64 = 2.4; +const STAGE_H: f32 = 72.0; +const TRACE_H: f32 = 96.0; +const PUCK: f32 = 32.0; +/// How close to the puck's centre a press catches it, in points. +const GRAB: f32 = 22.0; + +fn snap(x: f32) -> f32 { + let n = (STOPS - 1) as f32; + (x.clamp(0.0, 1.0) * n).round() / n +} + +#[derive(Clone, Copy, Debug)] +struct Sample { + t: f64, + x: f32, + target: f32, + kick: bool, +} + +#[derive(Debug)] +struct Grab { + offset: f32, + /// Recent (time, position) pairs, for the throw's speed. + pts: VecDeque<(f64, f32)>, + /// Holding the puck. A press on the track sends it there instead, until the pointer moves. + live: bool, +} + +pub struct Demo { + pub which: usize, + pub keep: bool, + anim: Animated<f32>, + samples: VecDeque<Sample>, + kicked: bool, + last_motion: f64, + grab: Option<Grab>, + visible: bool, + running: bool, + /// Where the last frame drew the puck (0 to 1) and when. + pub x: f32, + t: f64, +} + +impl Default for Demo { + fn default() -> Self { + Demo { + which: 2, + keep: true, + anim: Animated::new(0.0), + samples: VecDeque::new(), + kicked: false, + last_motion: f64::NEG_INFINITY, + grab: None, + visible: false, + running: false, + x: 0.0, + t: 0.0, + } + } +} + +impl Demo { + fn spring(&self) -> Spring { + SPRINGS[self.which].2 + } + + pub fn running(&self) -> bool { + self.running + } + + pub fn target(&self) -> f32 { + self.anim.target() + } + + /// Sends the puck to `target` from where it is, keeping its speed unless "Keep velocity" + /// is off. Reduced motion puts it there. + fn retarget(&mut self, target: f32, now: f64, reduced: bool) { + if reduced { + self.anim.set(target); + } else if self.keep { + self.anim.animate_to(target, self.spring(), now); + } else { + self.anim.animate_to(target, self.spring().velocity(Velocity::Zero), now); + } + self.kick(now); + } + + fn kick(&mut self, now: f64) { + self.kicked = true; + self.last_motion = now; + if self.visible { + self.running = true; + } + } + + pub fn step(&mut self, dir: i32, now: f64, reduced: bool) { + let to = snap(self.anim.target() + dir as f32 / (STOPS - 1) as f32); + self.retarget(to, now, reduced); + } + + pub fn press(&mut self, at: f32, travel: f32, now: f64, reduced: bool) { + let x = self.anim.sample(now); + let on_puck = ((at - x) * travel).abs() < GRAB; + self.grab = Some(Grab { offset: at - x, pts: VecDeque::from([(now, at)]), live: on_puck }); + if on_puck { + // Caught: the finger holds it where it is, with no animation while it's held. + self.anim.set(x); + self.kick(now); + } else { + self.retarget(at, now, reduced); + } + } + + pub fn drag(&mut self, at: f32, travel: f32, now: f64) { + let Some(g) = self.grab.as_mut() else { return }; + g.pts.push_back((now, at)); + if g.pts.len() > 6 { + g.pts.pop_front(); + } + if !g.live { + // A press on the track sent the puck there; moving 4 points takes it over from + // wherever it is now. + if (at - g.pts[0].1).abs() * travel < 4.0 { + return; + } + g.live = true; + g.offset = at - self.anim.sample(now); + } + self.anim.set((at - g.offset).clamp(0.0, 1.0)); + self.kick(now); + } + + pub fn release(&mut self, now: f64, reduced: bool) { + let Some(g) = self.grab.take() else { return }; + if !g.live { + return; + } + let pts: Vec<_> = g.pts.iter().filter(|(t, _)| now - t < 0.1).collect(); + let v = match (pts.first(), pts.last()) { + (Some(a), Some(b)) if pts.len() > 1 => (b.1 - a.1) / ((b.0 - a.0) as f32).max(0.008), + _ => 0.0, + }; + let x = self.anim.sample(now); + let target = snap(x + v * 0.12); + if reduced { + self.anim.set(target); + } else { + self.anim.release(if self.keep { v } else { 0.0 }, target, self.spring(), now); + } + self.kick(now); + } + + pub fn set_visible(&mut self, on: bool, now: f64) { + self.visible = on; + self.running = on && now - self.last_motion < WINDOW; + } + + /// Advances to `now`: samples the puck into the trace. True while it draws frames. + pub fn tick(&mut self, now: f64) -> bool { + if !self.running { + return false; + } + if self.grab.is_some() || !self.anim.is_settled(now) { + self.last_motion = now; + } + self.x = self.anim.sample(now); + self.t = now; + self.samples.push_back(Sample { t: now, x: self.x, target: self.anim.target(), kick: self.kicked }); + self.kicked = false; + while self.samples.len() > 2 && self.samples[1].t < now - WINDOW { + self.samples.pop_front(); + } + if now - self.last_motion > WINDOW { + self.running = false; + } + true + } +} + +/// The puck's position from a press `x` points into a stage `w` wide, 0 to 1. +fn frac(x: f32, w: f32) -> f32 { + ((x - 32.0) / travel(w)).clamp(0.0, 1.0) +} + +fn travel(w: f32) -> f32 { + (w - 64.0).max(1.0) +} + +/// `points` dashed `on` then `off` points along their length. +fn dashed(mut shape: Shape, points: &[[f32; 2]], on: f32, off: f32, width: f32, color: Color) -> Shape { + let mut phase = 0.0f32; + for w in points.windows(2) { + let (a, b) = (w[0], w[1]); + let len = (b[0] - a[0]).hypot(b[1] - a[1]); + let mut d = 0.0; + while d < len { + let period = on + off; + let into = phase % period; + let left = if into < on { on - into } else { period - into }; + let step = left.min(len - d); + if into < on { + let p = |s: f32| [a[0] + (b[0] - a[0]) * s / len, a[1] + (b[1] - a[1]) * s / len]; + shape = shape.line(p(d), p(d + step), width, LineCap::Butt, color); + } + d += step; + phase += step; + } + } + shape +} + +fn trace(d: &Demo, w: f32) -> Shape { + let h = TRACE_H; + let pad = 8.0; + let x_at = |t: f64| w - ((d.t - t) / WINDOW) as f32 * w; + // Bouncy springs overshoot: leave room above and below the track's ends. + let y_at = |v: f32| h - pad - (v + 0.15) / 1.3 * (h - 2.0 * pad); + let mut shape = Shape::new(); + if d.samples.len() < 2 { + return shape; + } + let target: Vec<[f32; 2]> = d.samples.iter().map(|s| [x_at(s.t), y_at(s.target)]).collect(); + shape = dashed(shape, &target, 2.0, 4.0, 1.0, Color::WHITE.alpha(0.12)); + let path: Vec<[f32; 2]> = d.samples.iter().map(|s| [x_at(s.t), y_at(s.x)]).collect(); + shape = shape.stroke(path, 1.5, ink()); + for s in d.samples.iter().filter(|s| s.kick) { + shape = shape_dot([x_at(s.t), y_at(s.x)], 2.5, glint(), shape); + } + shape +} + +fn segmented(d: &Demo, stacked: bool) -> El { + let mut segs = row().key("springs").role("radiogroup").label("Spring").padding(3.0).radius(18.0).fill(surface2()); + for (i, (name, note, _)) in SPRINGS.into_iter().enumerate() { + let on = i == d.which; + let seg = if stacked { col().py(4.0) } else { row().h(30.0).gap(8.0).center_y() }; + segs = segs.child(seg.key(name).role("radio").label(name).checked(on).focusable(true).px(12.0).radius(15.0) + .fill(if on { surface3() } else { Color::TRANSPARENT }).hover_group() + .on_press(move |s: &mut State| s.spring.which = i) + .child(text(name).font(TextStyle::new(13.0, 500.0).lh(20.0)).color(if on { fg() } else { fg2() }).group_color(fg())) + .child(text(note).font(MONO_12).color(fg3()).a11y_hidden())); + } + segs +} + +fn checkbox(on: bool) -> El { + let mut b = el().key("box").size(16.0, 16.0).radius(4.0).center(); + b = if on { + b.fill(ink()).child(canvas(Shape::new().view_box(16.0, 16.0) + .stroke(vec![[4.0, 8.5], [7.0, 11.5], [12.0, 5.0]], 2.0, Color::BLACK)).key("tick").size(16.0, 16.0)) + } else { + b.border(1.5, line2()) + }; + row().key("keep").role("checkbox").label("Keep velocity").checked(on).focusable(true).gap(8.0).center_y() + .on_press(|s: &mut State| s.spring.keep = !s.spring.keep) + .child(b.a11y_hidden()) + .child(text("Keep velocity").font(TEXT_14).color(fg2()).a11y_hidden()) +} + +pub fn demo(s: &State, cx: &Cx<State>, bp: Bp) -> El { + let d = &s.spring; + let reduced = cx.is_reduced_motion(); + let w = cx.layout_size("spring-stage").map_or(600.0, |[w, _]| w); + let travel_w = travel(w); + let mut rail = el().key("rail").h(2.0).radius(1.0).fill(surface3()).pin(Some(32.0), Some(35.0), Some(32.0), None).a11y_hidden(); + for i in 0..STOPS { + let x = travel_w * i as f32 / (STOPS - 1) as f32; + rail = rail.child(el().key(format!("stop-{i}")).size(4.0, 4.0).radius(2.0).fill(line2()).absolute(x - 2.0, -1.0)); + } + let puck = el().key("puck").size(PUCK, PUCK).radius(PUCK / 2.0).fill(fg()) + .absolute(16.0 + d.x * travel_w, 20.0) + .shadow(2.0, 8.0, oklcha(0.0, 0.0, 0.0, 0.5)) + .box_shadow(rune::Shadow { x: 0.0, y: 0.0, blur: 0.0, spread: 4.0, color: ink().alpha(0.25), inset: false }) + .a11y_hidden(); + let stage = el().key("spring-stage").w_full().h(STAGE_H).radius(R2).fill(surface1()).border(1.0, line()) + .role("slider").label("Puck position").focusable(true) + .range_value(f64::from(d.target()), 0.0, 1.0).range_step(1.0 / (STOPS - 1) as f64) + .on_step(move |s: &mut State, steps, _| { + let now = s.clock_now(); + s.spring.step(steps.signum(), now, reduced); + }) + .on_drag(move |s: &mut State, g: &mut Drag, _tx: &mut Tx| { + let now = s.clock_now(); + let at = frac(g.x, g.w); + match g.phase { + Phase::Down => s.spring.press(at, travel(g.w), now, reduced), + Phase::Move => s.spring.drag(at, travel(g.w), now), + Phase::Up => s.spring.release(now, reduced), + } + }) + .on_visible(|s: &mut State, on, _tx: &mut Tx| { + let now = s.clock_now(); + s.spring.set_visible(on, now); + }) + .child(rail) + .child(puck); + let trace_w = cx.layout_size("trace").map_or(w, |[w, _]| w); + let trace = canvas(trace(d, trace_w)).key("trace").w_full().h(TRACE_H).mt(8.0) + .clip_fade_linear(trace_w * 0.25, 0.0, 0.0, 0.0).a11y_hidden(); + let controls = row().key("controls").w_full().justify_between().flex_wrap().gaps(12.0, 24.0).center_y().mt(16.0) + .child(segmented(d, bp.narrow())) + .child(checkbox(d.keep)); + col().key("spring-demo").role("figure").w_full().mt(32.0) + .child(stage) + .child(trace) + .child(controls) + .child(text("Click the track, then click somewhere else before the puck lands. Or grab it and throw it. Turn off \u{201c}Keep velocity\u{201d} to see a spring that starts from rest every time.") + .key("caption").font(TEXT_13).color(fg3()).wrap().max_w(MEASURE).mt(12.0)) +} diff --git a/app/vendor/rune/www/app/src/tests.rs b/app/vendor/rune/www/app/src/tests.rs new file mode 100644 index 0000000..49b9304 --- /dev/null +++ b/app/vendor/rune/www/app/src/tests.rs @@ -0,0 +1,58 @@ +use rune::{Env, Runtime}; + +use super::*; +use crate::code::{HELLO_TEST, HELLO_VIEW, RETARGET}; + +fn page(width: f32) -> Runtime<State> { + let mut rt = Runtime::new(State::new(), view, (width, 900.0), Env::new(true, 2.0)); + for _ in 0..3 { + rt.frame(0.0); + } + rt +} + +fn paths(rt: &Runtime<State>) -> Vec<String> { + rt.elements().into_iter().filter(|e| !e.exiting).map(|e| e.path).collect() +} + +#[test] +fn every_snippet_still_cuts() { + for s in [&HELLO_VIEW, &HELLO_TEST, &RETARGET] { + let cut = s.cut().unwrap_or_else(|| panic!("{}: a marker stopped matching", s.file)); + assert!(cut.start <= cut.end && cut.code.lines().count() > 3, "{}: {cut:?}", s.file); + assert_eq!(cut.code.matches('{').count(), cut.code.matches('}').count(), "{}: braces balance\n{}", s.file, cut.code); + } +} + +/// The static page keeps the narrowest width's tree and switches styles with `@media`, so every +/// width must build the same elements. +#[test] +fn every_breakpoint_builds_the_same_tree() { + let narrow = paths(&page(360.0)); + assert!(narrow.len() > 100, "{} elements", narrow.len()); + for w in [400.0, 560.0, 760.0, 860.0, 1000.0, 1400.0] { + let wide = paths(&page(w)); + let only: Vec<_> = wide.iter().filter(|p| !narrow.contains(p)).chain(narrow.iter().filter(|p| !wide.contains(p))).collect(); + assert!(only.is_empty(), "at {w}: {only:?}"); + } +} + +#[test] +fn the_breakpoint_follows_the_window() { + let mut rt = page(1200.0); + let hero = |rt: &Runtime<State>| rt.presented("hero-text").unwrap().0; + let wide = hero(&rt); + rt.set_viewport((390.0, 900.0), 2.0); + for _ in 0..3 { + rt.frame(0.0); + } + let narrow = hero(&rt); + assert!(wide[2] < 1200.0 - 520.0, "the card sits beside the text: {wide:?}"); + assert!((narrow[2] - (390.0 - 32.0)).abs() < 1.0, "and under it on a phone: {narrow:?}"); +} + +#[test] +fn the_cargo_line_names_the_repo_and_a_rev() { + let line = sections::cargo_line(); + assert!(line.starts_with("rune = { git = \"https://github.com/anomalyco/rune\", rev = \""), "{line}"); +} diff --git a/app/vendor/rune/www/app/src/tokens.rs b/app/vendor/rune/www/app/src/tokens.rs new file mode 100644 index 0000000..0fa7548 --- /dev/null +++ b/app/vendor/rune/www/app/src/tokens.rs @@ -0,0 +1,113 @@ +//! The page's tokens: black, one neutral at four strengths, hairlines as translucent white and +//! Rune's blue ink as the only accent. One sans (Geist) and one mono (Geist Mono), line heights +//! on the 4 pt grid. + +use rune::{Color, TextStyle, oklch}; + +pub const BG: Color = Color::BLACK; + +pub fn fg() -> Color { + rune::color::hex("#ededed").unwrap_or(Color::WHITE) +} +pub fn fg2() -> Color { + Color::WHITE.alpha(0.62) +} +pub fn fg3() -> Color { + Color::WHITE.alpha(0.5) +} +pub fn surface1() -> Color { + Color::WHITE.alpha(0.03) +} +pub fn surface2() -> Color { + Color::WHITE.alpha(0.06) +} +pub fn surface3() -> Color { + Color::WHITE.alpha(0.1) +} +pub fn line() -> Color { + Color::WHITE.alpha(0.09) +} +pub fn line2() -> Color { + Color::WHITE.alpha(0.16) +} +pub fn ink() -> Color { + oklch(0.74, 0.14, 245.0) +} +pub fn glint() -> Color { + oklch(0.97, 0.035, 245.0) +} +pub fn code_keyword() -> Color { + oklch(0.74, 0.12, 25.0) +} +pub fn code_string() -> Color { + oklch(0.84, 0.06, 80.0) +} +pub fn code_call() -> Color { + oklch(0.84, 0.045, 235.0) +} + +pub const R2: f32 = 8.0; +/// The content column's width, before gutters. +pub const CONTENT: f32 = 1120.0; +/// Paragraphs stop at this width (36rem). +pub const MEASURE: f32 = 576.0; +pub const TOPBAR: f32 = 52.0; + +pub const TEXT_12_MEDIUM: TextStyle = TextStyle::new(12.0, 500.0).lh(16.0); +pub const TEXT_13: TextStyle = TextStyle::new(13.0, 400.0).lh(20.0); +pub const TEXT_14: TextStyle = TextStyle::new(14.0, 400.0).lh(22.0); +pub const TEXT_14_MEDIUM: TextStyle = TextStyle::new(14.0, 500.0).lh(22.0); +pub const TEXT_16: TextStyle = TextStyle::new(16.0, 400.0).lh(26.0); +pub const TEXT_16_MEDIUM: TextStyle = TextStyle::new(16.0, 500.0).lh(26.0); +pub const MONO_12: TextStyle = TextStyle::new(12.0, 400.0).lh(16.0).mono(); +pub const MONO_13: TextStyle = TextStyle::new(13.0, 400.0).lh(20.0).mono(); +/// Code blocks: mono 12 on 20 pt lines. +pub const CODE: TextStyle = TextStyle::new(12.0, 400.0).lh(20.0).mono(); + +/// The page's breakpoints, read from its width once per resize that crosses one. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub struct Bp { + /// The widest breakpoint at or under the page's width: 0, 400, 560, 760, 860 or 1000. + pub at: u16, +} + +impl Bp { + pub const STEPS: [u16; 6] = [0, 400, 560, 760, 860, 1000]; + + pub fn of(width: f32) -> Bp { + let at = Self::STEPS.iter().rev().copied().find(|&s| width >= f32::from(s)).unwrap_or(0); + Bp { at } + } + /// Under 400: 16 pt gutters. + pub fn narrow(self) -> bool { + self.at < 400 + } + /// Under 560: smaller headings and section padding. + pub fn phone(self) -> bool { + self.at < 560 + } + /// Under 760: the gallery and OpenCode screens stack. + pub fn stack_gallery(self) -> bool { + self.at < 760 + } + /// Under 860: code beside its output, the frame diagram, facts and platforms stack. + pub fn stack_split(self) -> bool { + self.at < 860 + } + /// Under 1000: the hero's live card goes under its text. + pub fn stack_hero(self) -> bool { + self.at < 1000 + } + pub fn gutter(self) -> f32 { + if self.narrow() { 16.0 } else { 24.0 } + } + pub fn h1(self) -> TextStyle { + if self.phone() { TextStyle::new(36.0, 500.0).lh(44.0).tracking(-0.9) } else { TextStyle::new(40.0, 500.0).lh(48.0).tracking(-1.0) } + } + pub fn h2(self) -> TextStyle { + if self.phone() { TextStyle::new(24.0, 500.0).lh(32.0).tracking(-0.48) } else { TextStyle::new(28.0, 500.0).lh(36.0).tracking(-0.56) } + } + pub fn lede(self) -> TextStyle { + if self.phone() { TEXT_16 } else { TextStyle::new(18.0, 400.0).lh(28.0) } + } +} diff --git a/app/vendor/rune/www/app/src/ui.rs b/app/vendor/rune/www/app/src/ui.rs new file mode 100644 index 0000000..a80e306 --- /dev/null +++ b/app/vendor/rune/www/app/src/ui.rs @@ -0,0 +1,214 @@ +//! The page's small parts: hairlines, paragraphs with inline code, buttons and links. + +use rune::{Color, El, Link, LinkPaint, Path, Shape, Span, TextStyle, Tx, canvas, el, rich, row, text}; + +use crate::tokens::*; + +pub fn hairline(key: &str) -> El { + el().key(key).w_full().h(1.0).fill(line()).a11y_hidden() +} + +/// `s` with each `` `code` `` set in mono 13 at the text's full strength, as the page sets +/// identifiers inside prose. +pub fn prose(key: &str, s: &str, style: TextStyle, color: Color) -> El { + let mut content = String::with_capacity(s.len()); + let mut spans = Vec::new(); + for (i, piece) in s.split('`').enumerate() { + let at = content.len(); + content.push_str(piece); + if i % 2 == 1 { + spans.push(Span::new(at, content.len()).mono().size(13.0).color(fg())); + } + } + rich(content, spans).key(key).font(style).color(color).wrap().selectable(true) +} + +/// A section's paragraph under its heading. +pub fn intro(key: &str, s: &str) -> El { + prose(key, s, TEXT_16, fg2()).max_w(MEASURE).mt(16.0) +} + +#[derive(Clone, Copy, PartialEq)] +pub enum Button { + /// White, with GitHub's mark. + GitHub, + /// White: the main action. + Primary, + /// Quiet: the rest. + Secondary, +} + +/// A pill button that is a link. +pub fn button(key: &str, label: &str, href: &str, kind: Button) -> El { + let primary = kind != Button::Secondary; + let (fill, hover, ink) = if primary { (fg(), Color::WHITE, Color::BLACK) } else { (surface2(), Color::WHITE.alpha(0.04), fg()) }; + let mut b = row().key(key).href(href).h(40.0).px(16.0).gap(8.0).center_y().radius(20.0).fill(fill).hover(hover).press_scale(0.98); + if kind == Button::GitHub { + b = b.child(github_mark(Color::BLACK)); + } + if !primary { + b = b.border(1.0, line()); + } + b.child(text(label.to_owned()).font(TEXT_14_MEDIUM).color(ink)) +} + +/// `s` with `[label](url)` links in it, the links at full strength. +pub fn linked(key: &str, s: &str, style: TextStyle, color: Color) -> El { + let mut content = String::with_capacity(s.len()); + let mut links = Vec::new(); + let mut rest = s; + while let Some(open) = rest.find('[') { + let Some(mid) = rest[open..].find("](").map(|m| open + m) else { break }; + let Some(close) = rest[mid..].find(')').map(|c| mid + c) else { break }; + content.push_str(&rest[..open]); + let at = content.len(); + content.push_str(&rest[open + 1..mid]); + links.push((at..content.len(), rest[mid + 2..close].to_owned())); + rest = &rest[close + 1..]; + } + content.push_str(rest); + let spans = links.iter().map(|(r, _)| Span::new(r.start, r.end).color(fg())).collect(); + let mut t = rich(content, spans).key(key).font(style).color(color).wrap().selectable(true); + for (r, url) in links { + t = t.link(Link::new(r, url).hover(LinkPaint::default().underline(fg()))); + } + t.on_link(|_: &mut crate::State, url: &str, tx: &mut Tx| { + tx.open_url(url).ok(); + }) +} + +/// A text link in a row of them: quiet until hovered. +pub fn nav_link(key: &str, label: &str, href: &str, style: TextStyle) -> El { + row().key(key).href(href).hover_group() + .child(text(label.to_owned()).font(style).color(fg2()).group_color(fg())) +} + +/// GitHub's mark, 16 points. +pub fn github_mark(color: Color) -> El { + canvas(Shape::new().view_box(16.0, 16.0).fill_path(&mark_path(), color)).key("mark").size(16.0, 16.0).a11y_hidden() +} + +/// GitHub's octocat mark on a 16-unit square, from its SVG path. +fn mark_path() -> Path { + svg_path("M8 0C3.58 0 0 3.58 0 8c0 3.54 2.29 6.53 5.47 7.59.4.07.55-.17.55-.38 0-.19-.01-.82-.01-1.49-2.01.37-2.53-.49-2.69-.94-.09-.23-.48-.94-.82-1.13-.28-.15-.68-.52-.01-.53.63-.01 1.08.58 1.23.82.72 1.21 1.87.87 2.33.66.07-.52.28-.87.51-1.07-1.78-.2-3.64-.89-3.64-3.95 0-.87.31-1.59.82-2.15-.08-.2-.36-1.02.08-2.12 0 0 .67-.21 2.2.82.64-.18 1.32-.27 2-.27s1.36.09 2 .27c1.53-1.04 2.2-.82 2.2-.82.44 1.1.16 1.92.08 2.12.51.56.82 1.27.82 2.15 0 3.07-1.87 3.75-3.65 3.95.29.25.54.73.54 1.48 0 1.07-.01 1.93-.01 2.2 0 .21.15.46.55.38A8.01 8.01 0 0 0 16 8c0-4.42-3.58-8-8-8") +} + +/// The numbers in an SVG path's data, in order. +fn numbers(d: &str) -> Vec<f32> { + let mut out = Vec::new(); + let mut cur = String::new(); + let flush = |cur: &mut String, out: &mut Vec<f32>| { + if let Ok(v) = cur.parse() { + out.push(v); + } + cur.clear(); + }; + for c in d.chars() { + match c { + '0'..='9' => cur.push(c), + '.' if cur.contains('.') => { + flush(&mut cur, &mut out); + cur.push(c); + } + '.' => cur.push(c), + '-' => { + flush(&mut cur, &mut out); + cur.push(c); + } + _ => flush(&mut cur, &mut out), + } + } + flush(&mut cur, &mut out); + out +} + +/// A path from SVG path data with the commands GitHub's mark uses (M, C, c, s, A as a straight +/// line's worth of curve) in absolute and relative forms. +pub fn svg_path(d: &str) -> Path { + let mut path = Path::new(); + let mut at = [0.0f32; 2]; + let mut start = at; + let mut ctrl = at; + let mut cmds = Vec::new(); + let mut piece = String::new(); + for c in d.chars() { + if c.is_ascii_alphabetic() { + if !piece.is_empty() { + cmds.push(std::mem::take(&mut piece)); + } + } + piece.push(c); + } + cmds.push(piece); + for cmd in cmds { + let mut chars = cmd.chars(); + let Some(op) = chars.next() else { continue }; + let n = numbers(chars.as_str()); + let rel = op.is_ascii_lowercase(); + let off = |p: [f32; 2], at: [f32; 2]| if rel { [p[0] + at[0], p[1] + at[1]] } else { p }; + match op.to_ascii_uppercase() { + 'M' => { + for (i, p) in n.chunks_exact(2).enumerate() { + at = off([p[0], p[1]], at); + path = if i == 0 { path.move_to(at) } else { path.line_to(at) }; + if i == 0 { + start = at; + } + } + ctrl = at; + } + 'L' => { + for p in n.chunks_exact(2) { + at = off([p[0], p[1]], at); + path = path.line_to(at); + } + ctrl = at; + } + 'C' => { + for p in n.chunks_exact(6) { + let (c1, c2, end) = (off([p[0], p[1]], at), off([p[2], p[3]], at), off([p[4], p[5]], at)); + path = path.cubic_to(c1, c2, end); + ctrl = c2; + at = end; + } + } + 'S' => { + for p in n.chunks_exact(4) { + let c1 = [2.0 * at[0] - ctrl[0], 2.0 * at[1] - ctrl[1]]; + let (c2, end) = (off([p[0], p[1]], at), off([p[2], p[3]], at)); + path = path.cubic_to(c1, c2, end); + ctrl = c2; + at = end; + } + } + 'A' => { + // The mark's one arc is a quarter turn of a circle; a quadratic through its + // corner draws it closely enough at 16 points. + for p in n.chunks_exact(7) { + let end = off([p[5], p[6]], at); + let corner = [end[0], at[1]]; + path = path.quad_to(corner, end); + at = end; + ctrl = at; + } + } + 'Z' => { + path = path.close(); + at = start; + ctrl = at; + } + _ => {} + } + } + path +} + +pub fn shape_dot(center: [f32; 2], r: f32, color: Color, shape: Shape) -> Shape { + let pts: Vec<[f32; 2]> = (0..12) + .map(|i| { + let a = i as f32 / 12.0 * std::f32::consts::TAU; + [center[0] + r * a.cos(), center[1] + r * a.sin()] + }) + .collect(); + shape.fill(pts, color) +} diff --git a/app/vendor/rune/www/app/src/wordmark.rs b/app/vendor/rune/www/app/src/wordmark.rs new file mode 100644 index 0000000..4da44b5 --- /dev/null +++ b/app/vendor/rune/www/app/src/wordmark.rs @@ -0,0 +1,344 @@ +//! ᚱUNE on Anomaly's pixel grid: letters 11 pixels tall, 2-pixel stems, notched corners, fitted one +//! clear pixel apart. The R is the rune ᚱ (raidō), so the name is spelled with a real rune and +//! still reads as RUNE. Drawn as one shape, so the static page gets it as an inline SVG. +//! +//! A light runs down the ᚱ's strokes on hover (and every 5 to 9 s in the masthead while it's on +//! screen): each cell warms in 40 ms and cools with a 180 ms time constant. + +use rune::{El, Shape, canvas}; + +use crate::tokens::{glint, ink}; + +const RUNE: [&str; 11] = [ + "###....", "####...", "##.##..", "##..##.", "##..##.", "##.##..", "####...", "##.##..", "##..##.", "##...##", "##...##", +]; +const U: [&str; 11] = [ + "##...##", "##...##", "##...##", "##...##", "##...##", "##...##", "##...##", "##...##", "##...##", "#######", ".#####.", +]; +const N: [&str; 11] = [ + "###...##", "####..##", "####..##", "####..##", "##.##.##", "##.##.##", "##.##.##", "##..####", "##..####", "##..####", + "##...###", +]; +const E: [&str; 11] = [ + "######", "######", "##....", "##....", "#####.", "#####.", "##....", "##....", "##....", "######", "######", +]; + +pub const CAP: usize = 11; + +/// The glint's travel along the ᚱ, its rise and its cooling time constant, in seconds. +const TRAVEL: f64 = 0.7; +const RISE: f64 = 0.04; +const TAU: f64 = 0.18; + +fn ink_cells(rows: &[&str]) -> Vec<(i32, i32)> { + rows.iter().enumerate().flat_map(|(y, r)| r.bytes().enumerate().filter(|&(_, c)| c == b'#').map(move |(x, _)| (x as i32, y as i32))).collect() +} + +/// Where `next` starts after `prev` (placed at `at`): as far left as keeps one clear pixel +/// between their ink in every direction, diagonals included. +fn fit(prev: &[&str], at: i32, next: &[&str]) -> i32 { + let a: Vec<_> = ink_cells(prev).into_iter().map(|(x, y)| (x + at, y)).collect(); + let b = ink_cells(next); + let mut x = at + 1; + while a.iter().any(|&(ax, ay)| b.iter().any(|&(bx, by)| (bx + x - ax).abs() <= 1 && (by - ay).abs() <= 1)) { + x += 1; + } + x +} + +pub struct Glyphs { + /// Each glyph's rows and where it starts. + pub glyphs: Vec<(&'static [&'static str], i32)>, + pub width: usize, + /// The ᚱ's cells with their place along its carve path, 0 to 1. + pub carve: Vec<(i32, i32, f32)>, +} + +impl Glyphs { + pub fn new() -> Glyphs { + let mut glyphs: Vec<(&'static [&'static str], i32)> = Vec::new(); + for rows in [&RUNE[..], &U[..], &N[..], &E[..]] { + let x = glyphs.last().map_or(0, |&(prev, at)| fit(prev, at, rows)); + glyphs.push((rows, x)); + } + let &(last, at) = glyphs.last().unwrap(); + let width = at as usize + last[0].len(); + Glyphs { glyphs, width, carve: carve_order(&RUNE) } + } +} + +/// Rows to rectangles, merging each row's runs so no seams show between pixels. +fn runs(rows: &[&str], dx: i32, out: &mut Vec<[f32; 4]>) { + for (y, row) in rows.iter().enumerate() { + let row = row.as_bytes(); + let mut x = 0; + while x < row.len() { + if row[x] != b'#' { + x += 1; + continue; + } + let start = x; + while x < row.len() && row[x] == b'#' { + x += 1; + } + out.push([(dx + start as i32) as f32, y as f32, (x - start) as f32, 1.0]); + } + } +} + +fn rect(r: [f32; 4]) -> Vec<[f32; 2]> { + let [x, y, w, h] = r; + vec![[x, y], [x + w, y], [x + w, y + h], [x, y + h]] +} + +/// ᚱ's carve order: the stave top to bottom, then the bowl out and back, then the leg. Each +/// cell gets the arc length (0 to 1) of its nearest point on that path. +fn carve_order(rows: &[&str]) -> Vec<(i32, i32, f32)> { + let path: [[[f32; 2]; 2]; 4] = + [[[1.0, 0.5], [1.0, 10.5]], [[1.5, 0.5], [5.0, 3.5]], [[5.0, 3.5], [1.5, 6.5]], [[2.5, 6.5], [6.0, 10.5]]]; + let lens: Vec<f32> = path.iter().map(|[a, b]| (b[0] - a[0]).hypot(b[1] - a[1])).collect(); + let total: f32 = lens.iter().sum(); + ink_cells(rows) + .into_iter() + .map(|(x, y)| { + let c = [x as f32 + 0.5, y as f32 + 0.5]; + let (mut best, mut arc, mut acc) = (f32::INFINITY, 0.0, 0.0); + for (i, [a, b]) in path.iter().enumerate() { + let (dx, dy) = (b[0] - a[0], b[1] - a[1]); + let p = (((c[0] - a[0]) * dx + (c[1] - a[1]) * dy) / (dx * dx + dy * dy)).clamp(0.0, 1.0); + let d = (a[0] + dx * p - c[0]).hypot(a[1] + dy * p - c[1]); + if d < best - 1e-6 { + best = d; + arc = acc + p * lens[i]; + } + acc += lens[i]; + } + (x, y, arc / total) + }) + .collect() +} + +fn ease_in_out(p: f64) -> f64 { + if p < 0.5 { 2.0 * p * p } else { 1.0 - (-2.0 * p + 2.0).powi(2) / 2.0 } +} + +/// When the head passes `order` (0 to 1) along the carve, in seconds after the start. +fn passes(order: f32) -> f64 { + let (mut lo, mut hi) = (0.0, 1.0); + for _ in 0..20 { + let m = (lo + hi) / 2.0; + if ease_in_out(m) < f64::from(order) { lo = m } else { hi = m } + } + (lo + hi) / 2.0 * TRAVEL +} + +/// How lit a cell at `order` is `t` seconds into a glint (0 to 1). +pub fn heat(order: f32, t: f64) -> f32 { + let since = t - passes(order); + if since < 0.0 { + 0.0 + } else if since < RISE { + (since / RISE) as f32 + } else { + let h = (-(since - RISE) / TAU).exp() as f32; + if h > 0.004 { h } else { 0.0 } + } +} + +/// How long a glint runs before every cell has cooled. +pub const GLINT_SECONDS: f64 = TRAVEL + RISE + TAU * 6.0; + +/// How the ᚱ is lit. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub enum Glow { + /// At rest. + #[default] + Off, + /// A light running down the strokes, this many seconds in. + Glint(f64), + /// Reduced motion: the whole letter lit this much (0 to 1), with no travel. + Lit(f32), +} + +/// The wordmark at `cell` points a pixel, lit as `glow` says. +pub fn wordmark(g: &Glyphs, cell: f32, glow: Glow) -> El { + let mut rects = Vec::new(); + for &(rows, x) in &g.glyphs { + runs(rows, x, &mut rects); + } + let mut shape = Shape::new().view_box(g.width as f32, CAP as f32); + for r in rects { + shape = shape.fill(rect(r), ink()); + } + let hot = glint(); + for &(x, y, order) in &g.carve { + let h = match glow { + Glow::Off => 0.0, + Glow::Glint(t) => heat(order, t), + Glow::Lit(level) => level, + }; + if h > 0.0 { + shape = shape.fill(rect([x as f32, y as f32, 1.0, 1.0]), hot.alpha(h)); + } + } + canvas(shape).key("wordmark").size(cell * g.width as f32, cell * CAP as f32).a11y_hidden() +} + +/// Reduced motion's stand-in for a glint, `t` seconds in: the letter fades to lit in 90 ms, +/// holds half a second and fades back. None once it's over. +pub fn lit(t: f64) -> Option<f32> { + const FADE: f64 = 0.09; + const HOLD: f64 = 0.5; + let level = if t < 0.0 { + return None; + } else if t < FADE { + t / FADE + } else if t < FADE + HOLD { + 1.0 + } else if t < 2.0 * FADE + HOLD { + 1.0 - (t - FADE - HOLD) / FADE + } else { + return None; + }; + Some(level as f32) +} + +/// When each wordmark's light started, and when the masthead's next idle one is due. +#[derive(Default)] +pub struct Glints { + masthead: Option<f64>, + brand: Option<f64>, + next: Option<f64>, + /// Reduced motion, as the view last saw it: idle glints skip. + reduced: bool, + seed: u32, +} + +impl Glints { + pub fn masthead(&mut self, now: f64) { + start(&mut self.masthead, now); + } + + pub fn brand(&mut self, now: f64) { + start(&mut self.brand, now); + } + + /// The masthead came on screen or left: idle glints run every 5 to 9 s while it shows. + pub fn masthead_visible(&mut self, on: bool, reduced: bool, now: f64) { + self.reduced = reduced; + self.next = on.then(|| now + self.pause()); + } + + fn pause(&mut self) -> f64 { + // xorshift: the gaps only need to not line up. + let mut x = self.seed.wrapping_add(0x9e37_79b9) | 1; + x ^= x << 13; + x ^= x >> 17; + x ^= x << 5; + self.seed = x; + 5.0 + 4.0 * f64::from(x) / f64::from(u32::MAX) + } + + /// Advances to `now`: returns (changed, still moving) and sets when to look again. + pub fn tick(&mut self, now: f64) -> (bool, bool, Option<f64>) { + if let Some(at) = self.next + && now >= at + { + if !self.reduced { + start(&mut self.masthead, now); + } + self.next = Some(now + self.pause()); + } + let mut changed = false; + let mut moving = false; + for g in [&mut self.masthead, &mut self.brand] { + if let Some(at) = *g { + changed = true; + if now - at >= GLINT_SECONDS { + *g = None; + } else { + moving = true; + } + } + } + (changed, moving, self.next) + } + + pub fn glow(&self, which: Which, now: f64, reduced: bool) -> Glow { + let Some(at) = (match which { + Which::Masthead => self.masthead, + Which::Brand => self.brand, + }) else { + return Glow::Off; + }; + let t = now - at; + if reduced { + lit(t).map_or(Glow::Off, Glow::Lit) + } else if (0.0..GLINT_SECONDS).contains(&t) { + Glow::Glint(t) + } else { + Glow::Off + } + } +} + +#[derive(Clone, Copy)] +pub enum Which { + Masthead, + Brand, +} + +/// Starts a light unless one is still running, so hovering in and out doesn't restart it. +fn start(at: &mut Option<f64>, now: f64) { + if at.is_none_or(|a| now - a >= GLINT_SECONDS) { + *at = Some(now); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn idle_glints_wait_five_to_nine_seconds_and_stop_off_screen() { + let mut g = Glints::default(); + g.masthead_visible(true, false, 0.0); + let (_, moving, next) = g.tick(1.0); + let at = next.unwrap(); + assert!(!moving && (5.0..=9.0).contains(&at), "{at}"); + let (changed, moving, _) = g.tick(at); + assert!(changed && moving); + assert!(matches!(g.glow(Which::Masthead, at + 0.1, false), Glow::Glint(_))); + g.masthead_visible(false, false, at + 0.2); + let (_, _, next) = g.tick(at + GLINT_SECONDS + 1.0); + assert_eq!(next, None); + assert_eq!(g.glow(Which::Masthead, at + GLINT_SECONDS + 1.0, false), Glow::Off); + } + + #[test] + fn reduced_motion_lights_on_hover_only() { + let mut g = Glints::default(); + g.masthead_visible(true, true, 0.0); + let (_, _, next) = g.tick(0.0); + let (changed, ..) = g.tick(next.unwrap()); + assert!(!changed, "no idle light under reduced motion"); + g.masthead(20.0); + assert_eq!(g.glow(Which::Masthead, 20.3, true), Glow::Lit(1.0)); + } + + #[test] + fn letters_fit_one_clear_pixel_apart() { + let g = Glyphs::new(); + let starts: Vec<i32> = g.glyphs.iter().map(|&(_, x)| x).collect(); + assert_eq!(starts[0], 0); + assert!(starts.windows(2).all(|w| w[1] > w[0]), "{starts:?}"); + assert_eq!(g.carve.len(), ink_cells(&RUNE).len()); + assert!(g.carve.iter().all(|&(_, _, o)| (0.0..=1.0).contains(&o))); + } + + #[test] + fn a_glint_warms_the_stave_first_and_cools_to_nothing() { + assert!(heat(0.0, 0.03) > heat(0.9, 0.03)); + assert_eq!(heat(0.5, GLINT_SECONDS), 0.0); + } +} diff --git a/app/vendor/rune/www/bun.lock b/app/vendor/rune/www/bun.lock new file mode 100644 index 0000000..a8e33ea --- /dev/null +++ b/app/vendor/rune/www/bun.lock @@ -0,0 +1,409 @@ +{ + "lockfileVersion": 2, + "configVersion": 1, + "workspaces": { + "": { + "name": "rune-www", + "devDependencies": { + "@cloudflare/build-output-utils": "0.8.5", + "@cloudflare/vite-plugin": "2.0.0-beta.v.4", + "@types/bun": "1.3.13", + "@types/node": "25.5.0", + "cf": "1.0.0-beta.12", + "typescript": "6.0.2", + "vite": "8.1.3", + }, + }, + }, + "packages": { + "@cloudflare/build-output-utils": ["@cloudflare/build-output-utils@0.8.5", "", { "dependencies": { "@cloudflare/config": "0.23.0" } }, "sha512-xnwcDCyBSErZeOj5eUy1gTrmVjwIY51TZ0Pz9W7mZqLGA3IkIckud7dNtFdGhKSXL2szfxBRbGM4R4qFE4SoPA=="], + + "@cloudflare/codemods": ["@cloudflare/codemods@0.4.0", "", { "bin": { "cloudflare-codemods": "dist/bin.mjs" } }, "sha512-qeRpKNXtvqhTtagx/5cLmDaFx/voBhWJ1S6SdFdBkE3OtgcPVz+Q8MtIG26zltW9Z0Icsu2FGBxV5RFmuHI/Bg=="], + + "@cloudflare/config": ["@cloudflare/config@0.23.0", "", { "dependencies": { "zod": "4.4.3" } }, "sha512-oE0S7X54esZmJHr9hhCoqODR+yTxxkSYWCLtRiItQdPs0gQuqYw9a13zChhK+8DmdCUJIFBsMAR6t+mfu8g+9w=="], + + "@cloudflare/runtime-types": ["@cloudflare/runtime-types@0.1.15", "", { "dependencies": { "miniflare": "5.20261019.2-beta", "workerd": "1.20261019.1" } }, "sha512-E8WCMGir4IRp/ksqodMWGpxHJvgtfgW9lbVM5mNAdWrnonMNOtGocyxVt6hG8/RGW9sjFWR7F7Cp3SCF1Cz6zg=="], + + "@cloudflare/unenv-preset": ["@cloudflare/unenv-preset@2.16.2", "", { "peerDependencies": { "unenv": "2.0.0-rc.24", "workerd": ">1.20260305.0 <2.0.0-0" }, "optionalPeers": ["workerd"] }, "sha512-JBP1+Z7ZSNG/d4mRP+y8VC5dka3tZVMLEZRvS+rzQ4DGV1EoxRFQckcJTTkXbHSQiTj0DtNI01Zwb/V2fX0mvQ=="], + + "@cloudflare/vite-plugin": ["@cloudflare/vite-plugin@2.0.0-beta.v.4", "", { "dependencies": { "@cloudflare/build-output-utils": "0.9.4", "@cloudflare/config": "0.28.0", "@cloudflare/runtime-types": "0.1.15", "@cloudflare/unenv-preset": "2.16.2", "miniflare": "5.20261019.2-beta", "unenv": "2.0.0-rc.24", "ws": "8.21.0" }, "peerDependencies": { "vite": "^7.0.0 || ^8.0.0" }, "bin": { "cf-vite": "bin/cf-vite" } }, "sha512-VNlj5o1Uc3IbfoDIA03jD/vd7hGDgbnx/Sjof6xYVpvCW0CRug67dQN0nabyKKSa27tvdSp0l1i+veTuNurA6g=="], + + "@cloudflare/workerd-darwin-64": ["@cloudflare/workerd-darwin-64@1.20261019.1", "", { "os": "darwin", "cpu": "x64" }, "sha512-5ZILbAta/fBQvhmAYeCE7dKMMYIr7N9wJEX50fEGLKSIwGtvT0HzSfHNIK/O7cBQ4gHQ2WfIiPClvwcye6E0fA=="], + + "@cloudflare/workerd-darwin-arm64": ["@cloudflare/workerd-darwin-arm64@1.20261019.1", "", { "os": "darwin", "cpu": "arm64" }, "sha512-cww2Ab6lVMxpTiEEjKmPI58p5EMo0vYTZSH+3WkqXJdQgc3ES66GuL247+U2B2YWajhhu2tqj7jySrXneU749g=="], + + "@cloudflare/workerd-linux-64": ["@cloudflare/workerd-linux-64@1.20261019.1", "", { "os": "linux", "cpu": "x64" }, "sha512-4++VRi9vkQROYqrpZYOixIJuVDmujkwrT4kszsxNFlvcmsX6Mr2GumvxIN3gIixS3vJUh3Umdtkthqj5X0S3Xw=="], + + "@cloudflare/workerd-linux-arm64": ["@cloudflare/workerd-linux-arm64@1.20261019.1", "", { "os": "linux", "cpu": "arm64" }, "sha512-75PVtJOwfjScQ53sbLtQXI7D8yP1c21t+WEUPaYbqkzaz4ZqfR5wAd+zuWs8G5Q7kOj2SQIvEfY5Sn8Y+UVrnA=="], + + "@cloudflare/workerd-windows-64": ["@cloudflare/workerd-windows-64@1.20261019.1", "", { "os": "win32", "cpu": "x64" }, "sha512-z49fvKTETMCnG6wnMcQwxx9CpryFceiKz04FRjq26EkhCyzRNJ6c3UXhyZz3r5f1CXnnBZc5DcU8ZouPkUJCqw=="], + + "@cspotcode/source-map-support": ["@cspotcode/source-map-support@0.8.1", "", { "dependencies": { "@jridgewell/trace-mapping": "0.3.9" } }, "sha512-IchNf6dN4tHoMFIn/7OE8LWZ19Y6q/67Bmf6vnGREv8RSbBVb9LPJxEcnwrcwX6ixSvaiGoomAUvu4YSxXrVgw=="], + + "@emnapi/core": ["@emnapi/core@1.11.1", "", { "dependencies": { "@emnapi/wasi-threads": "1.2.2", "tslib": "^2.4.0" } }, "sha512-RSvbQmHzdKzNsLYa/wHrbc3KN4sYLKAdPZxqiM2HATqv/SBk2/ENSHpvXGaLOMcsAyz0poEGqkmmKYG3OWiJEQ=="], + + "@emnapi/runtime": ["@emnapi/runtime@1.11.1", "", { "dependencies": { "tslib": "^2.4.0" } }, "sha512-vgj7R3y3Wgx24IQaGPA/R6YFXLHVMOZ0uVEyIQPaWs+rd1AzfEMXlAC22FYwO1XkKR6NPsq7mUandH8oIRdZFw=="], + + "@emnapi/wasi-threads": ["@emnapi/wasi-threads@1.2.2", "", { "dependencies": { "tslib": "^2.4.0" } }, "sha512-c95qOXkHdydNKhscBTebqEC1CVAZpyqOfVfBzQ1qgzyl3gfeldUjIggDbIZgDKsHLgnsM+igH7TJ/eAasaVuMA=="], + + "@img/colour": ["@img/colour@1.1.0", "", {}, "sha512-Td76q7j57o/tLVdgS746cYARfSyxk8iEfRxewL9h4OMzYhbW4TAcppl0mT4eyqXddh6L/jwoM75mo7ixa/pCeQ=="], + + "@img/sharp-darwin-arm64": ["@img/sharp-darwin-arm64@0.35.5", "", { "optionalDependencies": { "@img/sharp-libvips-darwin-arm64": "1.3.4" }, "os": "darwin", "cpu": "arm64" }, "sha512-QRUlFQ0WxvdWyqqG/WtI3iupfD5rBzmCHXSdPsY91sAtVtTo7Q4cb6zOccZ3gqEqkr0f1As1ehLqmEpDsRf+lg=="], + + "@img/sharp-darwin-x64": ["@img/sharp-darwin-x64@0.35.5", "", { "optionalDependencies": { "@img/sharp-libvips-darwin-x64": "1.3.4" }, "os": "darwin", "cpu": "x64" }, "sha512-+BR255RhDlpygUpOc/Jdt1nT6DQ3XG/ERo5wbcdOf5Q320dKtPCKPLR1LJs9VGXRaMa8l1uUa0tkCNOXiAxZUw=="], + + "@img/sharp-freebsd-wasm32": ["@img/sharp-freebsd-wasm32@0.35.5", "", { "dependencies": { "@img/sharp-wasm32": "0.35.5" }, "os": "freebsd" }, "sha512-Y/z91nEZ4uIBX5X3nfTovjU9lHNKFYbL2lpHCLVNmXQK03VIZvXBBt0KxbPGp2SdGSF+2mQU4e+hQaWOt86iAw=="], + + "@img/sharp-libvips-darwin-arm64": ["@img/sharp-libvips-darwin-arm64@1.3.4", "", { "os": "darwin", "cpu": "arm64" }, "sha512-5R89nBYiRdUlSWJxPhO+GVtaXzXSxKnRu/xqMn3KTA3L9EB9Oy/P+Nn2f2vlhPuUdy/Zusb2DarbyTpGCfEDuw=="], + + "@img/sharp-libvips-darwin-x64": ["@img/sharp-libvips-darwin-x64@1.3.4", "", { "os": "darwin", "cpu": "x64" }, "sha512-iR2OKH80yi0U+dUplyh3/xdpFvps6YkCwsXenIJxqxR1v9o+xtKTGbS9H7cps+2Vxjc8B1j96p75NmTGjIhtpQ=="], + + "@img/sharp-libvips-linux-arm": ["@img/sharp-libvips-linux-arm@1.3.4", "", { "os": "linux", "cpu": "arm", "libc": "glibc" }, "sha512-LmRtTsOHuvM2+wlO2Db37dx5MiZhB0FvSunciw48YjdOkZz9KAiRbm8ujeMOA1INqmei5NapFxYEK1D1ZSidmw=="], + + "@img/sharp-libvips-linux-arm64": ["@img/sharp-libvips-linux-arm64@1.3.4", "", { "os": "linux", "cpu": "arm64", "libc": "glibc" }, "sha512-Y3dgX/6lE2QhQb+Gxy0WZxfg9MEm/JBjamZpS2IklP7xIQoKN4hzAm7KcMVGtaVDt3neE9OKBC7vAfonA/Lr1A=="], + + "@img/sharp-libvips-linux-ppc64": ["@img/sharp-libvips-linux-ppc64@1.3.4", "", { "os": "linux", "cpu": "ppc64", "libc": "glibc" }, "sha512-Le6boB8Tai0Nis+gIxIpKx68UDVVIqdR8Tin5Yf1z2LJJQLDJvCDRqRu+jC2qCoD+eIomonmOwB4smBRxfVpYQ=="], + + "@img/sharp-libvips-linux-riscv64": ["@img/sharp-libvips-linux-riscv64@1.3.4", "", { "os": "linux", "cpu": "none", "libc": "glibc" }, "sha512-aHkkIEHPRdQEegJN20MLmGtxYD9R2wQr3Cwpddnu5+YKMt6Uzax7S9h5gpZTo8wyrGuZSlfQ63OevL5mTyOC7Q=="], + + "@img/sharp-libvips-linux-s390x": ["@img/sharp-libvips-linux-s390x@1.3.4", "", { "os": "linux", "cpu": "s390x", "libc": "glibc" }, "sha512-ra/mB6MikESDUO7Yg+Mi95bFBb9GsObURuhnOv3OqknjGe9sZrG8tCe9q0xSIGrtLgvgw0gKnFWcK4blSgQOuQ=="], + + "@img/sharp-libvips-linux-x64": ["@img/sharp-libvips-linux-x64@1.3.4", "", { "os": "linux", "cpu": "x64", "libc": "glibc" }, "sha512-GJ//SSXbnwSDes02umB3nDJLFcQzw8a18V8fyhqr6tV515tOEMdImjjxj1AoafMRz56F3PHgftnj1QEKSU1zkw=="], + + "@img/sharp-libvips-linuxmusl-arm64": ["@img/sharp-libvips-linuxmusl-arm64@1.3.4", "", { "os": "linux", "cpu": "arm64", "libc": "musl" }, "sha512-hvulFwtjUcagsis6BBxHwGFwWoNZjgYmULGVrZcyfNbjA8hKILbRxGg15/7w5HDyXHXUos/j6baAWqnCyQ2DWA=="], + + "@img/sharp-libvips-linuxmusl-x64": ["@img/sharp-libvips-linuxmusl-x64@1.3.4", "", { "os": "linux", "cpu": "x64", "libc": "musl" }, "sha512-6zXKeE/p39I1AmA3cJG35eyBGNqNddLnUXjhwBnsGjFPWqf5VKkDBEqaEkPDoTEtkxwi2vv8Tcr2mDyP4So7Fg=="], + + "@img/sharp-linux-arm": ["@img/sharp-linux-arm@0.35.5", "", { "optionalDependencies": { "@img/sharp-libvips-linux-arm": "1.3.4" }, "os": "linux", "cpu": "arm", "libc": "glibc" }, "sha512-LEaXK2WdXVK5ykcw0buWyPMsmLLL2vpHLD6yrNSW+JGEL3BZPA4tpKN6iaMc4AxTTAoaX/sU1rOL51lcIz48ZQ=="], + + "@img/sharp-linux-arm64": ["@img/sharp-linux-arm64@0.35.5", "", { "optionalDependencies": { "@img/sharp-libvips-linux-arm64": "1.3.4" }, "os": "linux", "cpu": "arm64", "libc": "glibc" }, "sha512-LYVx5JTsOM2CBzmxreh+nl64/3H6Xb09iSLknqH47z2T2DFFxDeFLP5y4dJwe6H7uGQlHPyEEtIqyo3DYsRwdQ=="], + + "@img/sharp-linux-ppc64": ["@img/sharp-linux-ppc64@0.35.5", "", { "optionalDependencies": { "@img/sharp-libvips-linux-ppc64": "1.3.4" }, "os": "linux", "cpu": "ppc64", "libc": "glibc" }, "sha512-QVxAAq8evVRI9ia2vqgwrmWucn5Dfv+JdWzj75pD8omHLPSP7f8p20O8jxzjCcuCEQEOtYOZUmX1hkiZ0kdevA=="], + + "@img/sharp-linux-riscv64": ["@img/sharp-linux-riscv64@0.35.5", "", { "optionalDependencies": { "@img/sharp-libvips-linux-riscv64": "1.3.4" }, "os": "linux", "cpu": "none", "libc": "glibc" }, "sha512-LtdreXguaavKODPIfzJ4kffx7UNt1omwtK0rch4EBbbSTXPnxWmYSayXdLJw0fJzQ97kHt1gL/yh4tvU+nCyRQ=="], + + "@img/sharp-linux-s390x": ["@img/sharp-linux-s390x@0.35.5", "", { "optionalDependencies": { "@img/sharp-libvips-linux-s390x": "1.3.4" }, "os": "linux", "cpu": "s390x", "libc": "glibc" }, "sha512-UZasTOFiYzotTsGOCu42BfUzP6Tu6Do/947iRm1RsLKvlllxwGcn4RN27LibGWceix4Y+Pmw3jsnTcCQIgWjqA=="], + + "@img/sharp-linux-x64": ["@img/sharp-linux-x64@0.35.5", "", { "optionalDependencies": { "@img/sharp-libvips-linux-x64": "1.3.4" }, "os": "linux", "cpu": "x64", "libc": "glibc" }, "sha512-SxFtLTeJInhAA9Q836kux2vZNeOBQEx658qvbboZScr0wIARym3IcGmW7KpVD5sbVg0Ojy+udFQdayYIZyoNog=="], + + "@img/sharp-linuxmusl-arm64": ["@img/sharp-linuxmusl-arm64@0.35.5", "", { "optionalDependencies": { "@img/sharp-libvips-linuxmusl-arm64": "1.3.4" }, "os": "linux", "cpu": "arm64", "libc": "musl" }, "sha512-9HbMclmI1zlNkFRs3z9/eBtDjfD0sGlrX1z6b1qwmiFY5ElDLh4BC0LPBdVp7z1DXFiKlIcznf+ZlsuZzLxQqg=="], + + "@img/sharp-linuxmusl-x64": ["@img/sharp-linuxmusl-x64@0.35.5", "", { "optionalDependencies": { "@img/sharp-libvips-linuxmusl-x64": "1.3.4" }, "os": "linux", "cpu": "x64", "libc": "musl" }, "sha512-4KOphqB035HrVdqLZfCgMzzERrQkkzOwRhl4OAkRO1YCldbaFjySXMaK534Mo0V+LndnlJk+sbUyLeU0ULyD1A=="], + + "@img/sharp-wasm32": ["@img/sharp-wasm32@0.35.5", "", { "dependencies": { "@emnapi/runtime": "^1.11.3" } }, "sha512-Ptsga1su4tQx+LLF1ECS9U6nz5kmrXKo6XVbtR48Ke3ZRxxgaWBu7IDtEe1quo8hiupwm6WFqxVlXaSf7IINGQ=="], + + "@img/sharp-webcontainers-wasm32": ["@img/sharp-webcontainers-wasm32@0.35.5", "", { "dependencies": { "@img/sharp-wasm32": "0.35.5" }, "cpu": "none" }, "sha512-hfhF/FmoQyTUkA0bIKFOtw536BQSeBMe6BF6QyWlrPxT754+TFLaZ7sKKTfvvM0yJgKgaYTwnFCIZ/GuDw5SUA=="], + + "@img/sharp-win32-arm64": ["@img/sharp-win32-arm64@0.35.5", "", { "os": "win32", "cpu": "arm64" }, "sha512-X4t7g+7ZA5DKblCBEXGjUqqemj4vczING/5viFwAL8h4N3qYeyjwdCvRLHi4EdOUI+2Z7UFlp1VM+p/AuEtm6Q=="], + + "@img/sharp-win32-ia32": ["@img/sharp-win32-ia32@0.35.5", "", { "os": "win32", "cpu": "ia32" }, "sha512-5Zm82LoBc43nhwNybZlG7Y1KO//Zhsn306fQl29ZOuStHLGTo3BWL83q3cznX0poxSAMuYL1On/BHBxkBeKr6A=="], + + "@img/sharp-win32-x64": ["@img/sharp-win32-x64@0.35.5", "", { "os": "win32", "cpu": "x64" }, "sha512-x76eH0vEiHlcMQu8Y8IenntaACtddpT6W0wmXtWrnKcnKI7ME5DdgqhAD6SEWOEl1v2zDvkZDhFA9KnURwpfqg=="], + + "@jridgewell/resolve-uri": ["@jridgewell/resolve-uri@3.1.2", "", {}, "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw=="], + + "@jridgewell/sourcemap-codec": ["@jridgewell/sourcemap-codec@1.6.0", "", {}, "sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw=="], + + "@jridgewell/trace-mapping": ["@jridgewell/trace-mapping@0.3.9", "", { "dependencies": { "@jridgewell/resolve-uri": "^3.0.3", "@jridgewell/sourcemap-codec": "^1.4.10" } }, "sha512-3Belt6tdc8bPgAtbcmdtNJlirVoTmEb5e2gC94PnkwEW9jI6CAHUeoG85tjWP5WquqfavoMtMwiG4P926ZKKuQ=="], + + "@napi-rs/wasm-runtime": ["@napi-rs/wasm-runtime@1.2.7", "", { "dependencies": { "@tybys/wasm-util": "^0.10.3" }, "peerDependencies": { "@emnapi/core": "^1.7.1 || 2.0.0-beta.2 || 2.0.0-beta.3", "@emnapi/runtime": "^1.7.1 || 2.0.0-beta.2 || 2.0.0-beta.3" } }, "sha512-zJccwplOAbgfZju95IUHazLnx9RAPtPN2YGJXI6UbrgeaR9QfPjGrQL6ERkSAtnVCA4Q+83ApGyaX5zdpCaKkQ=="], + + "@oxc-project/types": ["@oxc-project/types@0.139.0", "", {}, "sha512-r9gHphtCs+1M7J0pw6Sn/hh/Wpa/iQrOOkrNAlVLF/gHq+/CJmHIWKKUUhdWjcD6CIa8idarspCsASiXCXvFUw=="], + + "@poppinss/colors": ["@poppinss/colors@4.1.6", "", { "dependencies": { "kleur": "^4.1.5" } }, "sha512-H9xkIdFswbS8n1d6vmRd8+c10t2Qe+rZITbbDHHkQixH5+2x1FDGmi/0K+WgWiqQFKPSlIYB7jlH6Kpfn6Fleg=="], + + "@poppinss/dumper": ["@poppinss/dumper@0.6.5", "", { "dependencies": { "@poppinss/colors": "^4.1.5", "@sindresorhus/is": "^7.0.2", "supports-color": "^10.0.0" } }, "sha512-NBdYIb90J7LfOI32dOewKI1r7wnkiH6m920puQ3qHUeZkxNkQiFnXVWoE6YtFSv6QOiPPf7ys6i+HWWecDz7sw=="], + + "@poppinss/exception": ["@poppinss/exception@1.2.3", "", {}, "sha512-dCED+QRChTVatE9ibtoaxc+WkdzOSjYTKi/+uacHWIsfodVfpsueo3+DKpgU5Px8qXjgmXkSvhXvSCz3fnP9lw=="], + + "@rolldown/binding-android-arm64": ["@rolldown/binding-android-arm64@1.1.5", "", { "os": "android", "cpu": "arm64" }, "sha512-lZg8fqIv2v7FF237bwMgzGZEJvGL79/s5knJ/i6FmsGF4XXlzccZ4jb+TrFIxtSSxFtIpdsgrPZeMk1I9AFcyQ=="], + + "@rolldown/binding-darwin-arm64": ["@rolldown/binding-darwin-arm64@1.1.5", "", { "os": "darwin", "cpu": "arm64" }, "sha512-51Bnx9pNiMRKSUNtBfySkNJ9vMU9Hh3I1ozDd6gyPPYzaXCfnptUcEZxXGYFn+ul2dtcMUiqGR1Yai2K10uoTw=="], + + "@rolldown/binding-darwin-x64": ["@rolldown/binding-darwin-x64@1.1.5", "", { "os": "darwin", "cpu": "x64" }, "sha512-Tm+gbfC0aHu1tBA/JvKQh32S0K6YgCHkiAF4/W6xX0K0RmNuc94VeK419dJoE65R5aRxmo+noZQSWrAMF6yb6g=="], + + "@rolldown/binding-freebsd-x64": ["@rolldown/binding-freebsd-x64@1.1.5", "", { "os": "freebsd", "cpu": "x64" }, "sha512-JMzDKCCXq93YccG5gz3hvOs1oXRKAf0XYpfOS88e+wZrC8Iugj6j68867vrYZkvpDDpKn/KoKORThmchMpF6TA=="], + + "@rolldown/binding-linux-arm-gnueabihf": ["@rolldown/binding-linux-arm-gnueabihf@1.1.5", "", { "os": "linux", "cpu": "arm" }, "sha512-uML21j2K5TfPGutKxub+M+nLjZIrWjXQ5Grx4lCe/nimTj9B4L63zHpjXLl4y0L3mcm2htEQIb06oCG/szerNw=="], + + "@rolldown/binding-linux-arm64-gnu": ["@rolldown/binding-linux-arm64-gnu@1.1.5", "", { "os": "linux", "cpu": "arm64", "libc": "glibc" }, "sha512-navSiuTMogvnQoZoM/v+l3ZWo50/NTwSHSzheABx/RCnmUPaKwq9qSo4Br2OYRs21+Fz8uFqITZM3H4opOB0/Q=="], + + "@rolldown/binding-linux-arm64-musl": ["@rolldown/binding-linux-arm64-musl@1.1.5", "", { "os": "linux", "cpu": "arm64", "libc": "musl" }, "sha512-lAryqH7IteztmCXQXk0etKj4wBQ7Gx5S6LjKhsgp9zb8I5bsuvU/2llH1hDQcjsFeqIsovMVN339/8pUDDBXxA=="], + + "@rolldown/binding-linux-ppc64-gnu": ["@rolldown/binding-linux-ppc64-gnu@1.1.5", "", { "os": "linux", "cpu": "ppc64", "libc": "glibc" }, "sha512-fsK/sNBnxzBlL4O1JNrZakVQxPspqpED5dLtNsZS9oOKmtSpdNIzxH2kkol5HYTWJN47sE20ztMJPxfZ89qGOg=="], + + "@rolldown/binding-linux-s390x-gnu": ["@rolldown/binding-linux-s390x-gnu@1.1.5", "", { "os": "linux", "cpu": "s390x", "libc": "glibc" }, "sha512-gLYb4BIadlfTOYT5gO503n8zQjXflgzpD0FcyKh0Mzx3rqCZKnHoJWV9xe1KXUJ5lx2JfcSHr/mhzS0PC/McAA=="], + + "@rolldown/binding-linux-x64-gnu": ["@rolldown/binding-linux-x64-gnu@1.1.5", "", { "os": "linux", "cpu": "x64", "libc": "glibc" }, "sha512-FjcpEKUyJygHgs1o50VYNvkt5+7Le/VEdYt0AkRpkL33MnyQfwr8l5mXwMmfmTbyMPr5vJLC+8/Gd9gXnwU1QQ=="], + + "@rolldown/binding-linux-x64-musl": ["@rolldown/binding-linux-x64-musl@1.1.5", "", { "os": "linux", "cpu": "x64", "libc": "musl" }, "sha512-Me+PfPI2TMeOQk0gYWfLQZtTktrmzbr8cDboqX83XKc7UrgAi55gF+2dUkWdxd19n55Essp2yeca+O9N5rBxHg=="], + + "@rolldown/binding-openharmony-arm64": ["@rolldown/binding-openharmony-arm64@1.1.5", "", { "os": "none", "cpu": "arm64" }, "sha512-yc5WrLzXks6zCQfn9Oxr8pORKyl/pF+QjHmW/Qx3qu0oyrrNC+y2JLTU1E2rcWYAmzlnqngWXHQjy51VzW70Vw=="], + + "@rolldown/binding-wasm32-wasi": ["@rolldown/binding-wasm32-wasi@1.1.5", "", { "dependencies": { "@emnapi/core": "1.11.1", "@emnapi/runtime": "1.11.1", "@napi-rs/wasm-runtime": "^1.1.6" }, "cpu": "none" }, "sha512-VbQGPX2b4r48TAMIM2cjgluIM1HYutm4pcTEJsle7iEP7sB1dFqtPLBVbdLAZCxy1txCcPxf4QFf4v8uvltPqA=="], + + "@rolldown/binding-win32-arm64-msvc": ["@rolldown/binding-win32-arm64-msvc@1.1.5", "", { "os": "win32", "cpu": "arm64" }, "sha512-gHv82k63z4qpV5+Q1y/12KrK0ltWBukVDI8nZcbT7Tt/ZlOIVwppazneq0F93oDxTo3IgAMEDIoQh3E2n6mVsw=="], + + "@rolldown/binding-win32-x64-msvc": ["@rolldown/binding-win32-x64-msvc@1.1.5", "", { "os": "win32", "cpu": "x64" }, "sha512-tTZuDBPw85tEN5PQi1pnEBzDy0Z49HtScLAbD5t6hyeU92A95pRWaSMw1GZZi/RwgSgUIl0xrSlXIT/9QzvYSA=="], + + "@rolldown/pluginutils": ["@rolldown/pluginutils@1.0.1", "", {}, "sha512-2j9bGt5Jh8hj+vPtgzPtl72j0yRxHAyumoo6TNfAjsLB04UtpSvPbPcDcBMxz7n+9CYB0c1GxQFxYRg2jimqGw=="], + + "@sindresorhus/is": ["@sindresorhus/is@7.2.0", "", {}, "sha512-P1Cz1dWaFfR4IR+U13mqqiGsLFf1KbayybWwdd2vfctdV6hDpUkgCY0nKOLLTMSoRd/jJNjtbqzf13K8DCCXQw=="], + + "@speed-highlight/core": ["@speed-highlight/core@1.2.24", "", {}, "sha512-qeW2e1l78afw8VhRPfPQ1Gjj+KU5XFQ/OFV5ti6eTa9bruO7mJyZtA4vw0ofqmA3tKCkROE9xLk3VZoeRc98nw=="], + + "@tybys/wasm-util": ["@tybys/wasm-util@0.10.4", "", { "dependencies": { "tslib": "^2.4.0" } }, "sha512-W3c4gRigFS0T/Ma4qIYF3GDAc5AQdHb1yL5znJT1Zv1YaD9Kitx656wBjvr19qbiosmZT8lWDM5BEMynUqX65A=="], + + "@types/bun": ["@types/bun@1.3.13", "", { "dependencies": { "bun-types": "1.3.13" } }, "sha512-9fqXWk5YIHGGnUau9TEi+qdlTYDAnOj+xLCmSTwXfAIqXr2x4tytJb43E9uCvt09zJURKXwAtkoH4nLQfzeTXw=="], + + "@types/node": ["@types/node@25.5.0", "", { "dependencies": { "undici-types": "~7.18.0" } }, "sha512-jp2P3tQMSxWugkCUKLRPVUpGaL5MVFwF8RDuSRztfwgN1wmqJeMSbKlnEtQqU8UrhTmzEmZdu2I6v2dpp7XIxw=="], + + "blake3-wasm": ["blake3-wasm@2.1.5", "", {}, "sha512-F1+K8EbfOZE49dtoPtmxUQrpXaBIl3ICvasLh+nJta0xkz+9kF/7uet9fLnwKqhDrmj6g+6K3Tw9yQPUg2ka5g=="], + + "bun-types": ["bun-types@1.3.13", "", { "dependencies": { "@types/node": "*" } }, "sha512-QXKeHLlOLqQX9LgYaHJfzdBaV21T63HhFJnvuRCcjZiaUDpbs5ED1MgxbMra71CsryN/1dAoXuJJJwIv/2drVA=="], + + "cf": ["cf@1.0.0-beta.12", "", { "dependencies": { "@cloudflare/build-output-utils": "0.8.5", "@cloudflare/codemods": "0.4.0", "@cloudflare/config": "0.23.0", "@cloudflare/runtime-types": "0.1.7", "blake3-wasm": "2.1.5", "miniflare": "5.20260930.0-alpha", "minisearch": "7.2.0" }, "bin": { "cf": "./bin/cf", "cloudflare": "./bin/cf" } }, "sha512-tyQ+Jpnw+4NDwDtl7ZNteXBm7N0TeJ6gYww79kkabpcYoCEXkUUpmt9BlDUKH8ub17tjAeiuyqa9NQzH0vp2Aw=="], + + "cookie": ["cookie@1.1.1", "", {}, "sha512-ei8Aos7ja0weRpFzJnEA9UHJ/7XQmqglbRwnf2ATjcB9Wq874VKH9kfjjirM6UhU2/E5fFYadylyhFldcqSidQ=="], + + "detect-libc": ["detect-libc@2.1.2", "", {}, "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ=="], + + "error-stack-parser-es": ["error-stack-parser-es@1.0.5", "", {}, "sha512-5qucVt2XcuGMcEGgWI7i+yZpmpByQ8J1lHhcL7PwqCwu9FPP3VUXzT4ltHe5i2z9dePwEHcDVOAfSnHsOlCXRA=="], + + "fdir": ["fdir@6.5.0", "", { "peerDependencies": { "picomatch": "^3 || ^4" }, "optionalPeers": ["picomatch"] }, "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg=="], + + "fsevents": ["fsevents@2.3.3", "", { "os": "darwin", "hasInstallScript": true }, "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw=="], + + "kleur": ["kleur@4.1.5", "", {}, "sha512-o+NO+8WrRiQEE4/7nwRJhN1HWpVmJm511pBHUxPLtp0BUISzlBplORYSmTclCnJvQq2tKu/sgl3xVpkc7ZWuQQ=="], + + "lightningcss": ["lightningcss@1.33.0", "", { "dependencies": { "detect-libc": "^2.0.3" }, "optionalDependencies": { "lightningcss-android-arm64": "1.33.0", "lightningcss-darwin-arm64": "1.33.0", "lightningcss-darwin-x64": "1.33.0", "lightningcss-freebsd-x64": "1.33.0", "lightningcss-linux-arm-gnueabihf": "1.33.0", "lightningcss-linux-arm64-gnu": "1.33.0", "lightningcss-linux-arm64-musl": "1.33.0", "lightningcss-linux-x64-gnu": "1.33.0", "lightningcss-linux-x64-musl": "1.33.0", "lightningcss-win32-arm64-msvc": "1.33.0", "lightningcss-win32-x64-msvc": "1.33.0" } }, "sha512-WkUDrojuJs0xkgGf2udWxa3yGBRxPtxUkB79i6aCZLRgc7PM8fZe9TosfPDcvEpQZbuFASnHYmRLBLUbmLOIIA=="], + + "lightningcss-android-arm64": ["lightningcss-android-arm64@1.33.0", "", { "os": "android", "cpu": "arm64" }, "sha512-gEpRTalKdosp4Bb8qWtc2iOgE5SeIHlpS1up9bFq2wAyYhl1UdTObYiHe98zEM9SQvSoqQZ1IQD0JNpg3Ml5pg=="], + + "lightningcss-darwin-arm64": ["lightningcss-darwin-arm64@1.33.0", "", { "os": "darwin", "cpu": "arm64" }, "sha512-Sciaz8eenNTKn9b3t7+xr0ipTp9YxKQY4npwQ3mrRuL0BAVHBLyZxofhaKBAVtzmtRZ/zTyo0/to4B1uWG/Djg=="], + + "lightningcss-darwin-x64": ["lightningcss-darwin-x64@1.33.0", "", { "os": "darwin", "cpu": "x64" }, "sha512-Z5UPAxzrjlWNNyGy6i65cJzzvgJ5D3T6wMvs+gWpY9d7qRhANrxqAp6LhxIgZhWEw18RfJTGcRxjuLIBr+m8XQ=="], + + "lightningcss-freebsd-x64": ["lightningcss-freebsd-x64@1.33.0", "", { "os": "freebsd", "cpu": "x64" }, "sha512-QQM/Ti/hQajJwCY+RiWuCZ9sdtI/XQk7nDK5vC8kkdwixezOlDgvDx7+RT+QjK6FcFT4MpsuoBnHIo/O3StRRg=="], + + "lightningcss-linux-arm-gnueabihf": ["lightningcss-linux-arm-gnueabihf@1.33.0", "", { "os": "linux", "cpu": "arm" }, "sha512-N7FVBe6iS24MlM6R/4RBTxGhQheZGs7tiQ9U32UtF75NzP5Q7xWPRqLBCKxlRQRk3rY1jCIPLzx7WzOhuUIRLQ=="], + + "lightningcss-linux-arm64-gnu": ["lightningcss-linux-arm64-gnu@1.33.0", "", { "os": "linux", "cpu": "arm64", "libc": "glibc" }, "sha512-j2v/itmy4HlNxlc6voKXYgBqNi0Ng2LShg4z7GufpEgs05P+2suBVyi9I6YHq5uoVFx9ETin3eCEhLVyXGQnKg=="], + + "lightningcss-linux-arm64-musl": ["lightningcss-linux-arm64-musl@1.33.0", "", { "os": "linux", "cpu": "arm64", "libc": "musl" }, "sha512-yiO5ROMuYQgXbC60yjZU5CYSFZGKXL0HFATXt9mHJn1+zW55oCtMI9NfcVhYLMFDL7gV7oBPon/EmMMGg2OvtQ=="], + + "lightningcss-linux-x64-gnu": ["lightningcss-linux-x64-gnu@1.33.0", "", { "os": "linux", "cpu": "x64", "libc": "glibc" }, "sha512-ar+Ju7LmcN0Jo4FpL4hpFybwNG9/3A/Br5KW2n2jyODg3MEZXaDYADdemoNS+BDNfMgKvylJLj4S5tyRActuAg=="], + + "lightningcss-linux-x64-musl": ["lightningcss-linux-x64-musl@1.33.0", "", { "os": "linux", "cpu": "x64", "libc": "musl" }, "sha512-RYiYbkokw0trfKqqzfF55lginwEPrD3OJDfTuJzFs1MK6iFnDenaz1fqLLtX4ITG3OktJQXOeTaw1awrBAlZPw=="], + + "lightningcss-win32-arm64-msvc": ["lightningcss-win32-arm64-msvc@1.33.0", "", { "os": "win32", "cpu": "arm64" }, "sha512-1K+MPfLSFVpphzpdbfkhlWk6wBrTObBzS2T6db10PNOZgR9GoVsAWzwNyuhUYYbTp23j+4RrncfujZ4uAzXvwA=="], + + "lightningcss-win32-x64-msvc": ["lightningcss-win32-x64-msvc@1.33.0", "", { "os": "win32", "cpu": "x64" }, "sha512-OlEICDx/Xl0FqSp4bry8zFnCvGpig3Gl4gCquvYwHuqJKEC1+n9NgDniFvqHGmMv1ZkqDJrDqKKSykTDX+ehuA=="], + + "miniflare": ["miniflare@5.20261019.2-beta", "", { "dependencies": { "@cspotcode/source-map-support": "0.8.1", "sharp": "0.35.5", "undici": "7.29.1", "workerd": "1.20261019.1", "ws": "8.21.0", "youch": "4.1.0-beta.10" } }, "sha512-QNgCA/axizZ7kv7RV3nwbRoz+w4watBlwIsyXjwgYHw4eSw5BrR1F2152s3Kz+Bzy/YxjKFHrZl3LzBRbPgYoQ=="], + + "minisearch": ["minisearch@7.2.0", "", {}, "sha512-dqT2XBYUOZOiC5t2HRnwADjhNS2cecp9u+TJRiJ1Qp/f5qjkeT5APcGPjHw+bz89Ms8Jp+cG4AlE+QZ/QnDglg=="], + + "nanoid": ["nanoid@3.3.20", "", { "bin": { "nanoid": "bin/nanoid.cjs" } }, "sha512-uKdg2G3GNCKQn9byYOpxbGqrT2fGO5KRt5J/8b3pok8rT6qxGWF6hxMyJiEYtAf+FVyYuD9hRaDqX5uPFYJ4ZQ=="], + + "pathe": ["pathe@2.0.3", "", {}, "sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w=="], + + "picocolors": ["picocolors@1.1.1", "", {}, "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA=="], + + "picomatch": ["picomatch@4.0.7", "", {}, "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA=="], + + "postcss": ["postcss@8.5.32", "", { "dependencies": { "nanoid": "^3.3.20", "picocolors": "^1.1.1", "source-map-js": "^1.2.2" } }, "sha512-LJlKCCAUFKOuZxipUdYw1NzIITEsPcgyOG9LkvRJvuKj/bRzbuRY0ARXvL0pWGpsZvn8jku+LMep2eU0seHp8g=="], + + "rolldown": ["rolldown@1.1.5", "", { "dependencies": { "@oxc-project/types": "=0.139.0", "@rolldown/pluginutils": "^1.0.0" }, "optionalDependencies": { "@rolldown/binding-android-arm64": "1.1.5", "@rolldown/binding-darwin-arm64": "1.1.5", "@rolldown/binding-darwin-x64": "1.1.5", "@rolldown/binding-freebsd-x64": "1.1.5", "@rolldown/binding-linux-arm-gnueabihf": "1.1.5", "@rolldown/binding-linux-arm64-gnu": "1.1.5", "@rolldown/binding-linux-arm64-musl": "1.1.5", "@rolldown/binding-linux-ppc64-gnu": "1.1.5", "@rolldown/binding-linux-s390x-gnu": "1.1.5", "@rolldown/binding-linux-x64-gnu": "1.1.5", "@rolldown/binding-linux-x64-musl": "1.1.5", "@rolldown/binding-openharmony-arm64": "1.1.5", "@rolldown/binding-wasm32-wasi": "1.1.5", "@rolldown/binding-win32-arm64-msvc": "1.1.5", "@rolldown/binding-win32-x64-msvc": "1.1.5" }, "bin": { "rolldown": "./bin/cli.mjs" } }, "sha512-t9z29cJjXf/vxQ8dyhCSpt6H6aSwHTk8cT5I3iy6SMXuFpk5mB6PL6XfC8PCwrPTx93udwKUm9HRteAlTGBLiA=="], + + "semver": ["semver@7.8.6", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-9lpSSU4Mly3mrtruwLs1eLK6+gzbzqeBFwRNjIjE+9LuDpWdYctrQlQ3ej1Ilgi7gknpsTRnPoLP8DpCHqHIJw=="], + + "sharp": ["sharp@0.35.5", "", { "dependencies": { "@img/colour": "^1.1.0", "detect-libc": "^2.1.2", "semver": "^7.8.5" }, "optionalDependencies": { "@img/sharp-darwin-arm64": "0.35.5", "@img/sharp-darwin-x64": "0.35.5", "@img/sharp-freebsd-wasm32": "0.35.5", "@img/sharp-libvips-darwin-arm64": "1.3.4", "@img/sharp-libvips-darwin-x64": "1.3.4", "@img/sharp-libvips-linux-arm": "1.3.4", "@img/sharp-libvips-linux-arm64": "1.3.4", "@img/sharp-libvips-linux-ppc64": "1.3.4", "@img/sharp-libvips-linux-riscv64": "1.3.4", "@img/sharp-libvips-linux-s390x": "1.3.4", "@img/sharp-libvips-linux-x64": "1.3.4", "@img/sharp-libvips-linuxmusl-arm64": "1.3.4", "@img/sharp-libvips-linuxmusl-x64": "1.3.4", "@img/sharp-linux-arm": "0.35.5", "@img/sharp-linux-arm64": "0.35.5", "@img/sharp-linux-ppc64": "0.35.5", "@img/sharp-linux-riscv64": "0.35.5", "@img/sharp-linux-s390x": "0.35.5", "@img/sharp-linux-x64": "0.35.5", "@img/sharp-linuxmusl-arm64": "0.35.5", "@img/sharp-linuxmusl-x64": "0.35.5", "@img/sharp-webcontainers-wasm32": "0.35.5", "@img/sharp-win32-arm64": "0.35.5", "@img/sharp-win32-ia32": "0.35.5", "@img/sharp-win32-x64": "0.35.5" }, "peerDependencies": { "@types/node": "*" }, "optionalPeers": ["@types/node"] }, "sha512-Ywn4OnzGukp7CDMrp08RQ50YKmuwG47brZgIVPTvBaaAfQlRlygrRqSrxdCiL9M+LlzLBiJ68IR1QqvzHyjC7g=="], + + "source-map-js": ["source-map-js@1.2.2", "", {}, "sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw=="], + + "supports-color": ["supports-color@10.2.2", "", {}, "sha512-SS+jx45GF1QjgEXQx4NJZV9ImqmO2NPz5FNsIHrsDjh2YsHnawpan7SNQ1o8NuhrbHZy9AZhIoCUiCeaW/C80g=="], + + "tinyglobby": ["tinyglobby@0.2.17", "", { "dependencies": { "fdir": "^6.5.0", "picomatch": "^4.0.4" } }, "sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g=="], + + "tslib": ["tslib@2.9.1", "", {}, "sha512-a4Ux9VKuIMHsOS7ENbEq6hK2ZGYIT27Rtl0E4eD9KqwxhKiQeMZE/9xb3IdYwWaSOyIBQLExhQgXDTYoiCxnWA=="], + + "typescript": ["typescript@6.0.2", "", { "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" } }, "sha512-bGdAIrZ0wiGDo5l8c++HWtbaNCWTS4UTv7RaTH/ThVIgjkveJt83m74bBHMJkuCbslY8ixgLBVZJIOiQlQTjfQ=="], + + "undici": ["undici@7.29.1", "", {}, "sha512-RYONW2MeafgYlkVOKYKkA/Ag7BmXqgIWCa8t1m0JcxrQg9pI9lEqRhAOruOBCbAohOa/gkCF+iPi9hrgvTzu6Q=="], + + "undici-types": ["undici-types@7.18.2", "", {}, "sha512-AsuCzffGHJybSaRrmr5eHr81mwJU3kjw6M+uprWvCXiNeN9SOGwQ3Jn8jb8m3Z6izVgknn1R0FTCEAP2QrLY/w=="], + + "unenv": ["unenv@2.0.0-rc.24", "", { "dependencies": { "pathe": "^2.0.3" } }, "sha512-i7qRCmY42zmCwnYlh9H2SvLEypEFGye5iRmEMKjcGi7zk9UquigRjFtTLz0TYqr0ZGLZhaMHl/foy1bZR+Cwlw=="], + + "vite": ["vite@8.1.3", "", { "dependencies": { "lightningcss": "^1.32.0", "picomatch": "^4.0.4", "postcss": "^8.5.16", "rolldown": "~1.1.3", "tinyglobby": "^0.2.17" }, "optionalDependencies": { "fsevents": "~2.3.3" }, "peerDependencies": { "@types/node": "^20.19.0 || >=22.12.0", "@vitejs/devtools": "^0.3.0", "esbuild": "^0.27.0 || ^0.28.0", "jiti": ">=1.21.0", "less": "^4.0.0", "sass": "^1.70.0", "sass-embedded": "^1.70.0", "stylus": ">=0.54.8", "sugarss": "^5.0.0", "terser": "^5.16.0", "tsx": "^4.8.1", "yaml": "^2.4.2" }, "optionalPeers": ["@types/node", "@vitejs/devtools", "esbuild", "jiti", "less", "sass", "sass-embedded", "stylus", "sugarss", "terser", "tsx", "yaml"], "bin": { "vite": "bin/vite.js" } }, "sha512-Ds+gBRbj0lwRO2Y5hwnUBdxSwlAve9LeRyU4sNnAr0ewW0gWF0n5bgXgUzbgZ49MV9BVUAQUFYVcDUcilUExMA=="], + + "workerd": ["workerd@1.20261019.1", "", { "optionalDependencies": { "@cloudflare/workerd-darwin-64": "1.20261019.1", "@cloudflare/workerd-darwin-arm64": "1.20261019.1", "@cloudflare/workerd-linux-64": "1.20261019.1", "@cloudflare/workerd-linux-arm64": "1.20261019.1", "@cloudflare/workerd-windows-64": "1.20261019.1" }, "hasInstallScript": true, "bin": { "workerd": "bin/workerd" } }, "sha512-UUYRUq/7DmeCl11YriNbcVbjUZVLtt8uuCXFu+nz77hGFf8d4DEVXoCYtnA+MlBatE4+wxoj47DVqzK3xGBAiw=="], + + "ws": ["ws@8.21.0", "", { "peerDependencies": { "bufferutil": "^4.0.1", "utf-8-validate": ">=5.0.2" }, "optionalPeers": ["bufferutil", "utf-8-validate"] }, "sha512-Vsp28b7DRcimFQvrqu2Wek3z1iYxDCWqHYB8Qsnk/S4RfaCQzPGPyBNuVjJV3cd6UiKtUtp6sNM77gWvzcCH+g=="], + + "youch": ["youch@4.1.0-beta.10", "", { "dependencies": { "@poppinss/colors": "^4.1.5", "@poppinss/dumper": "^0.6.4", "@speed-highlight/core": "^1.2.7", "cookie": "^1.0.2", "youch-core": "^0.3.3" } }, "sha512-rLfVLB4FgQneDr0dv1oddCVZmKjcJ6yX6mS4pU82Mq/Dt9a3cLZQ62pDBL4AUO+uVrCvtWz3ZFUL2HFAFJ/BXQ=="], + + "youch-core": ["youch-core@0.3.3", "", { "dependencies": { "@poppinss/exception": "^1.2.2", "error-stack-parser-es": "^1.0.5" } }, "sha512-ho7XuGjLaJ2hWHoK8yFnsUGy2Y5uDpqSTq1FkHLK4/oqKtyUU1AFbOOxY4IpC9f0fTLjwYbslUz0Po5BpD1wrA=="], + + "zod": ["zod@4.4.3", "", {}, "sha512-ytENFjIJFl2UwYglde2jchW2Hwm4GJFLDiSXWdTrJQBIN9Fcyp7n4DhxJEiWNAJMV1/BqWfW/kkg71UDcHJyTQ=="], + + "@cloudflare/vite-plugin/@cloudflare/build-output-utils": ["@cloudflare/build-output-utils@0.9.4", "", { "dependencies": { "@cloudflare/config": "0.28.0" } }, "sha512-5rVdn81HEP2Uugs/wSfXu5XbadaZQkgKZl1xwkKb3kgatSOpTH2vszBXWTRh4IlE1vHnc3LwHcnc2O4TcXVbuQ=="], + + "@cloudflare/vite-plugin/@cloudflare/config": ["@cloudflare/config@0.28.0", "", { "dependencies": { "zod": "4.6.5" } }, "sha512-2SaZn5rzNSxAR5VQYIlMm8+zHj2EGfLbaN+abYiPXDI42IFRCHSENpDxjAQpLj2NZnUVszHY4h6T1XljwHk5eQ=="], + + "@img/sharp-wasm32/@emnapi/runtime": ["@emnapi/runtime@1.11.3", "", { "dependencies": { "tslib": "^2.4.0" } }, "sha512-Xz4Tpyki7XyrpbUK1jR1AhdAdaXyhhY4lZ3neLodmhpuWfy2PAQN5B46sAiU4liOXGLkHypn/qU+jvfWSCYYLA=="], + + "cf/@cloudflare/runtime-types": ["@cloudflare/runtime-types@0.1.7", "", { "dependencies": { "miniflare": "5.20261001.0-alpha", "workerd": "1.20261001.1" } }, "sha512-avgC1wfTunbVea8HOq4ygiQ0WFQVNxcUHOQvH9TM47+0NTdsVTqB8rPQg6Tb5BfVkcWh/a0RAjk+Elr/h35mtQ=="], + + "cf/miniflare": ["miniflare@5.20260930.0-alpha", "", { "dependencies": { "@cspotcode/source-map-support": "0.8.1", "sharp": "0.35.4", "undici": "7.29.1", "workerd": "1.20260930.2", "ws": "8.21.0", "youch": "4.1.0-beta.10" } }, "sha512-vZljfRtOEeynbhJtuvYsnCU8t6zF5wIUm9ql4YFHB7zvYw2+F2tpT0BzXjzaa++eiUIml1gsODCf02qShBmJdg=="], + + "@cloudflare/vite-plugin/@cloudflare/config/zod": ["zod@4.6.5", "", {}, "sha512-v5l/aFXZQeai4awLbOpSoHecE9UiMrnfx75tEXLjNonXVARxQ5mOeipTjROUchszUNCqnE+hqAMujRsRHsut2Q=="], + + "cf/@cloudflare/runtime-types/miniflare": ["miniflare@5.20261001.0-alpha", "", { "dependencies": { "@cspotcode/source-map-support": "0.8.1", "sharp": "0.35.4", "undici": "7.29.1", "workerd": "1.20261001.1", "ws": "8.21.0", "youch": "4.1.0-beta.10" } }, "sha512-GaimS5mSIOMyvd16ga+e1/QkI8cmp3z35QPHFex0DktqNQf2RVZQwMPQXdyoUreUiFP/0Gpe2MoQInTyMAD5xA=="], + + "cf/@cloudflare/runtime-types/workerd": ["workerd@1.20261001.1", "", { "optionalDependencies": { "@cloudflare/workerd-darwin-64": "1.20261001.1", "@cloudflare/workerd-darwin-arm64": "1.20261001.1", "@cloudflare/workerd-linux-64": "1.20261001.1", "@cloudflare/workerd-linux-arm64": "1.20261001.1", "@cloudflare/workerd-windows-64": "1.20261001.1" }, "hasInstallScript": true, "bin": { "workerd": "bin/workerd" } }, "sha512-d/SIYHFO0PT/wiFZg8in4NpRIxYuFwslX1HdylOtWkBIIUmSpkGFhK820cV84XACFylwJ48xuRoWW/8DWDPsPQ=="], + + "cf/miniflare/sharp": ["sharp@0.35.4", "", { "dependencies": { "@img/colour": "^1.1.0", "detect-libc": "^2.1.2", "semver": "^7.8.5" }, "optionalDependencies": { "@img/sharp-darwin-arm64": "0.35.4", "@img/sharp-darwin-x64": "0.35.4", "@img/sharp-freebsd-wasm32": "0.35.4", "@img/sharp-libvips-darwin-arm64": "1.3.3", "@img/sharp-libvips-darwin-x64": "1.3.3", "@img/sharp-libvips-linux-arm": "1.3.3", "@img/sharp-libvips-linux-arm64": "1.3.3", "@img/sharp-libvips-linux-ppc64": "1.3.3", "@img/sharp-libvips-linux-riscv64": "1.3.3", "@img/sharp-libvips-linux-s390x": "1.3.3", "@img/sharp-libvips-linux-x64": "1.3.3", "@img/sharp-libvips-linuxmusl-arm64": "1.3.3", "@img/sharp-libvips-linuxmusl-x64": "1.3.3", "@img/sharp-linux-arm": "0.35.4", "@img/sharp-linux-arm64": "0.35.4", "@img/sharp-linux-ppc64": "0.35.4", "@img/sharp-linux-riscv64": "0.35.4", "@img/sharp-linux-s390x": "0.35.4", "@img/sharp-linux-x64": "0.35.4", "@img/sharp-linuxmusl-arm64": "0.35.4", "@img/sharp-linuxmusl-x64": "0.35.4", "@img/sharp-webcontainers-wasm32": "0.35.4", "@img/sharp-win32-arm64": "0.35.4", "@img/sharp-win32-ia32": "0.35.4", "@img/sharp-win32-x64": "0.35.4" }, "peerDependencies": { "@types/node": "*" }, "optionalPeers": ["@types/node"] }, "sha512-n++8XWcj+jCOr2IOl7h8LbKnGBDY4aPbmprMONBNFdn0ImXqpGVv5zliDs0V9HbmbCQLpbuo2ej9rAoOQTvMDA=="], + + "cf/miniflare/workerd": ["workerd@1.20260930.2", "", { "optionalDependencies": { "@cloudflare/workerd-darwin-64": "1.20260930.2", "@cloudflare/workerd-darwin-arm64": "1.20260930.2", "@cloudflare/workerd-linux-64": "1.20260930.2", "@cloudflare/workerd-linux-arm64": "1.20260930.2", "@cloudflare/workerd-windows-64": "1.20260930.2" }, "hasInstallScript": true, "bin": { "workerd": "bin/workerd" } }, "sha512-k1lQzEiGyCDqaRsR5+o9PBT5wVU5omtas6hXx3spbEHHMFo8a7tkAixVCMsWFeiT7xhrmg21Hd6a9jLNrkcUMg=="], + + "cf/@cloudflare/runtime-types/miniflare/sharp": ["sharp@0.35.4", "", { "dependencies": { "@img/colour": "^1.1.0", "detect-libc": "^2.1.2", "semver": "^7.8.5" }, "optionalDependencies": { "@img/sharp-darwin-arm64": "0.35.4", "@img/sharp-darwin-x64": "0.35.4", "@img/sharp-freebsd-wasm32": "0.35.4", "@img/sharp-libvips-darwin-arm64": "1.3.3", "@img/sharp-libvips-darwin-x64": "1.3.3", "@img/sharp-libvips-linux-arm": "1.3.3", "@img/sharp-libvips-linux-arm64": "1.3.3", "@img/sharp-libvips-linux-ppc64": "1.3.3", "@img/sharp-libvips-linux-riscv64": "1.3.3", "@img/sharp-libvips-linux-s390x": "1.3.3", "@img/sharp-libvips-linux-x64": "1.3.3", "@img/sharp-libvips-linuxmusl-arm64": "1.3.3", "@img/sharp-libvips-linuxmusl-x64": "1.3.3", "@img/sharp-linux-arm": "0.35.4", "@img/sharp-linux-arm64": "0.35.4", "@img/sharp-linux-ppc64": "0.35.4", "@img/sharp-linux-riscv64": "0.35.4", "@img/sharp-linux-s390x": "0.35.4", "@img/sharp-linux-x64": "0.35.4", "@img/sharp-linuxmusl-arm64": "0.35.4", "@img/sharp-linuxmusl-x64": "0.35.4", "@img/sharp-webcontainers-wasm32": "0.35.4", "@img/sharp-win32-arm64": "0.35.4", "@img/sharp-win32-ia32": "0.35.4", "@img/sharp-win32-x64": "0.35.4" }, "peerDependencies": { "@types/node": "*" }, "optionalPeers": ["@types/node"] }, "sha512-n++8XWcj+jCOr2IOl7h8LbKnGBDY4aPbmprMONBNFdn0ImXqpGVv5zliDs0V9HbmbCQLpbuo2ej9rAoOQTvMDA=="], + + "cf/@cloudflare/runtime-types/workerd/@cloudflare/workerd-darwin-64": ["@cloudflare/workerd-darwin-64@1.20261001.1", "", { "os": "darwin", "cpu": "x64" }, "sha512-4cgSgDf28JSw/P5Dj5GCS59hzVqS5XnmGAWNkvYHLI6ODU9idGaMMNEuhJXDkEG/lsABmlVlnCgsdh2VbKWepw=="], + + "cf/@cloudflare/runtime-types/workerd/@cloudflare/workerd-darwin-arm64": ["@cloudflare/workerd-darwin-arm64@1.20261001.1", "", { "os": "darwin", "cpu": "arm64" }, "sha512-8ulAWruEVouNmEIsQsy9WSSCS9zkLu93W2MTwp5esiFyoPp05BNSVFIFsYSPi1pkFmBBd7fsnwMpbLkaJLaVPQ=="], + + "cf/@cloudflare/runtime-types/workerd/@cloudflare/workerd-linux-64": ["@cloudflare/workerd-linux-64@1.20261001.1", "", { "os": "linux", "cpu": "x64" }, "sha512-kZbTZJGrhsMOdqZ2BIybjaBRLZjYsRLWj7mcNw/6Y3hodOhp5MrNzcz4iWGwNVWwyIV+7Pl+/LX5VcgnRqdHOg=="], + + "cf/@cloudflare/runtime-types/workerd/@cloudflare/workerd-linux-arm64": ["@cloudflare/workerd-linux-arm64@1.20261001.1", "", { "os": "linux", "cpu": "arm64" }, "sha512-oOk3Zj6k/8oP0FJgZBWDn7+BqbsqIMEMaV95pulHPVbwVu4wYoLfQq2hp0vkbCNsCFLqZb7cqixXdrwD54ZIow=="], + + "cf/@cloudflare/runtime-types/workerd/@cloudflare/workerd-windows-64": ["@cloudflare/workerd-windows-64@1.20261001.1", "", { "os": "win32", "cpu": "x64" }, "sha512-uRxm5W4VyBkoSaoP1BfOuH0873tE+vxsknF4sab6/5YIRvIAufChq3QDp+zlAn67PuGPGcn7W8QraA0t4ucmOQ=="], + + "cf/miniflare/sharp/@img/sharp-darwin-arm64": ["@img/sharp-darwin-arm64@0.35.4", "", { "optionalDependencies": { "@img/sharp-libvips-darwin-arm64": "1.3.3" }, "os": "darwin", "cpu": "arm64" }, "sha512-Uhfl4V4lhP2nbUVF9+hyH1+luj86f1gUFeo8ALYxFoULoU+G87D43BfeMP8XHsk9boxAnCY/bf2EHwhA7MuGsA=="], + + "cf/miniflare/sharp/@img/sharp-darwin-x64": ["@img/sharp-darwin-x64@0.35.4", "", { "optionalDependencies": { "@img/sharp-libvips-darwin-x64": "1.3.3" }, "os": "darwin", "cpu": "x64" }, "sha512-hWniXY3bG5qKpkKrAwPe4y+VTPmf086YQAnkxWh7uA1YrlRouWGa0M0Mxj3ZjnXFkv7/TD1bTy9lGUK26vRvWw=="], + + "cf/miniflare/sharp/@img/sharp-freebsd-wasm32": ["@img/sharp-freebsd-wasm32@0.35.4", "", { "dependencies": { "@img/sharp-wasm32": "0.35.4" }, "os": "freebsd" }, "sha512-lIsKw/BU+kjB4eZjxrYrZmwOJYi3Ajrv66iAlBmUPyKc3HpnloevB1g3wxGD9P/5BbQ1brBGl65VRRrCvQDEqA=="], + + "cf/miniflare/sharp/@img/sharp-libvips-darwin-arm64": ["@img/sharp-libvips-darwin-arm64@1.3.3", "", { "os": "darwin", "cpu": "arm64" }, "sha512-suTBPTDGrI9WodccaDdwZItTSaBYASlBk1NSfElSHrUfzu3szG6lvIF58+WiFvnfzuK8ZBFS5zE00PxqxnRiPg=="], + + "cf/miniflare/sharp/@img/sharp-libvips-darwin-x64": ["@img/sharp-libvips-darwin-x64@1.3.3", "", { "os": "darwin", "cpu": "x64" }, "sha512-FVJZ5mITMobmXIz/hPDTw0EintTW5H3WfrxwLqEqjiIihlu+hVRyGrFQ60xl0Lxn7Bt3zdpevPaQi0HEzqz9fw=="], + + "cf/miniflare/sharp/@img/sharp-libvips-linux-arm": ["@img/sharp-libvips-linux-arm@1.3.3", "", { "os": "linux", "cpu": "arm", "libc": "glibc" }, "sha512-3rbU4vqXXc3hY/OiXdl52xZvT0F1yEngWfvqudtPJg/KkyiaQw2DRsFrNzpmLvfavbwOq3qXn36GP8obHRULQA=="], + + "cf/miniflare/sharp/@img/sharp-libvips-linux-arm64": ["@img/sharp-libvips-linux-arm64@1.3.3", "", { "os": "linux", "cpu": "arm64", "libc": "glibc" }, "sha512-0DaL0A6Xu6sQSQFwe4iVCrKWU2cCTItnRsYsCdxAMm9NF6twAA9BKnoqy4hqz4+azQ0JHuA26qiUKsf1XJ/v5A=="], + + "cf/miniflare/sharp/@img/sharp-libvips-linux-ppc64": ["@img/sharp-libvips-linux-ppc64@1.3.3", "", { "os": "linux", "cpu": "ppc64", "libc": "glibc" }, "sha512-cdn1OvUBwsXhbC0zSzJnNzf5MZ/mTrobawDvNXBTxe8VtqKAm0sRuEY2Evzovb/w9JMk4TvRxqt1mekSuJz64w=="], + + "cf/miniflare/sharp/@img/sharp-libvips-linux-riscv64": ["@img/sharp-libvips-linux-riscv64@1.3.3", "", { "os": "linux", "cpu": "none", "libc": "glibc" }, "sha512-HjPVx7yKz+0lqdhDlTw1tt90wamBoxhiXpvl1XZpJLiHH4RCJ5yDTqH+VlYPv2fwFs89JFw4c1IexYOcQUi4IQ=="], + + "cf/miniflare/sharp/@img/sharp-libvips-linux-s390x": ["@img/sharp-libvips-linux-s390x@1.3.3", "", { "os": "linux", "cpu": "s390x", "libc": "glibc" }, "sha512-neWLh+3yCNThxnfy3c4BbVBeGgt9aftno+XbT56iK28RgeDs3UOFWviLWlUu0bArYVYJaFDK+RRohbicUNCm8Q=="], + + "cf/miniflare/sharp/@img/sharp-libvips-linux-x64": ["@img/sharp-libvips-linux-x64@1.3.3", "", { "os": "linux", "cpu": "x64", "libc": "glibc" }, "sha512-4vKmvAst9nrowcqquKFAyZJUDolUaIp8uRiN0mWFguJ1IplC9/pitXtlnnlU4aa/eJw3J7i67V+pwUL+wZGdsA=="], + + "cf/miniflare/sharp/@img/sharp-libvips-linuxmusl-arm64": ["@img/sharp-libvips-linuxmusl-arm64@1.3.3", "", { "os": "linux", "cpu": "arm64", "libc": "musl" }, "sha512-Y9kQaLMuNoB0bPYOOdcZMaseNrFpPodIWWMrx+CZyydf2xn68j9WYc6sWWRrDwNkzCQjKYfc68L7jKjGlHMibw=="], + + "cf/miniflare/sharp/@img/sharp-libvips-linuxmusl-x64": ["@img/sharp-libvips-linuxmusl-x64@1.3.3", "", { "os": "linux", "cpu": "x64", "libc": "musl" }, "sha512-fj8Mv0HHfD1Rr+4I68+3agJynxDWtBFgicTbSOb9Bke6pIwzGcJ+RX/yHjmiEGFMCavY/dxvem7MyNaJF+wDiw=="], + + "cf/miniflare/sharp/@img/sharp-linux-arm": ["@img/sharp-linux-arm@0.35.4", "", { "optionalDependencies": { "@img/sharp-libvips-linux-arm": "1.3.3" }, "os": "linux", "cpu": "arm", "libc": "glibc" }, "sha512-7OAS8gI0EReKGVN2HssHlM6umJgxF5VI3xN0p9FA91p/YO+ou5hiNghLdZ5BEHztwaaK5+bLKRf8x/o2L2nk9A=="], + + "cf/miniflare/sharp/@img/sharp-linux-arm64": ["@img/sharp-linux-arm64@0.35.4", "", { "optionalDependencies": { "@img/sharp-libvips-linux-arm64": "1.3.3" }, "os": "linux", "cpu": "arm64", "libc": "glibc" }, "sha512-De4jpEnAU8Hd5oT0j1G3uL4ZvTuipVMn7YC6vPaJhy6/7EwEae0SVAoBrUMYQbkLGDm85taVWwuPc1a44LTzCQ=="], + + "cf/miniflare/sharp/@img/sharp-linux-ppc64": ["@img/sharp-linux-ppc64@0.35.4", "", { "optionalDependencies": { "@img/sharp-libvips-linux-ppc64": "1.3.3" }, "os": "linux", "cpu": "ppc64", "libc": "glibc" }, "sha512-2oYZJeIl4kCcMGk4ouZVjnkCtFrpQFlNEtJ6GbxzhHQchwH0NH/qEb9ykmOl29dqwMq+JhFdZn+1ak2FKhI9fQ=="], + + "cf/miniflare/sharp/@img/sharp-linux-riscv64": ["@img/sharp-linux-riscv64@0.35.4", "", { "optionalDependencies": { "@img/sharp-libvips-linux-riscv64": "1.3.3" }, "os": "linux", "cpu": "none", "libc": "glibc" }, "sha512-cPbNChoRURAWdebDIHSenxRpgEdy7JkPydSnUxRm9VvKD7m0/xVaR/8Fzlu81pk5nHEvHH87UZUA7cTtwnbJSA=="], + + "cf/miniflare/sharp/@img/sharp-linux-s390x": ["@img/sharp-linux-s390x@0.35.4", "", { "optionalDependencies": { "@img/sharp-libvips-linux-s390x": "1.3.3" }, "os": "linux", "cpu": "s390x", "libc": "glibc" }, "sha512-RY0JFY8Fd6RonCBtHz+DvadaPkXDSI1AUn6yWL9TipqkZ1vY8w8evqdgyDFnkm4/K1ve1TvZiaePP5oSd4+WVQ=="], + + "cf/miniflare/sharp/@img/sharp-linux-x64": ["@img/sharp-linux-x64@0.35.4", "", { "optionalDependencies": { "@img/sharp-libvips-linux-x64": "1.3.3" }, "os": "linux", "cpu": "x64", "libc": "glibc" }, "sha512-9qvvEAuk8k89TfWUoX2htWjbAMX8p+NxCppjpcg5k6xMsjhBQPTsoIh36h9Qde4WRuGpJeYnOjdosDn/cnv+OA=="], + + "cf/miniflare/sharp/@img/sharp-linuxmusl-arm64": ["@img/sharp-linuxmusl-arm64@0.35.4", "", { "optionalDependencies": { "@img/sharp-libvips-linuxmusl-arm64": "1.3.3" }, "os": "linux", "cpu": "arm64", "libc": "musl" }, "sha512-KB5jxpfWQTr0nc3xdHtWChdbifHrBGsd2SM62Eyxrl8afikm+f5qGBU75SJIZBT/S1MC8XyacdlXBMSWq6OURA=="], + + "cf/miniflare/sharp/@img/sharp-linuxmusl-x64": ["@img/sharp-linuxmusl-x64@0.35.4", "", { "optionalDependencies": { "@img/sharp-libvips-linuxmusl-x64": "1.3.3" }, "os": "linux", "cpu": "x64", "libc": "musl" }, "sha512-f+eZJZIQNEEd26RPSW+76chwOf1XtA2Y/O+5ocVyLliHkeih3e+jhLVBdNTd2rS3IbNXK8+ug93Vf5ZXtF5Lxg=="], + + "cf/miniflare/sharp/@img/sharp-webcontainers-wasm32": ["@img/sharp-webcontainers-wasm32@0.35.4", "", { "dependencies": { "@img/sharp-wasm32": "0.35.4" }, "cpu": "none" }, "sha512-ESfNkywmCfPNyaZjxooddJQiQ+l/nTpGEOGthxiLnIHXC/CmcBixnfwUleX9mCz9ovrUUvKMap/pm8RYbzfwaA=="], + + "cf/miniflare/sharp/@img/sharp-win32-arm64": ["@img/sharp-win32-arm64@0.35.4", "", { "os": "win32", "cpu": "arm64" }, "sha512-iNdlBX9gLVvqe2I3uIJSIKTq6wckP/DYxZtcqxm09x5Gi24DnFBmPAWZmr60ZyYMG0xlzo6goG3670ar+RXvRw=="], + + "cf/miniflare/sharp/@img/sharp-win32-ia32": ["@img/sharp-win32-ia32@0.35.4", "", { "os": "win32", "cpu": "ia32" }, "sha512-kqRsbaa5CS6KHlpxnN7WhE6vAAugXyZButpRdvDWetlv6Qv4N9WTcrWzF7tXfB9T7MsoadqdI8hmwLq6UlLvtw=="], + + "cf/miniflare/sharp/@img/sharp-win32-x64": ["@img/sharp-win32-x64@0.35.4", "", { "os": "win32", "cpu": "x64" }, "sha512-XtmnYhBcrORsJ4XJngyzr/EWP0hRZLAZRFaApdKuviyqF78+ylxh2y06ZmtULAMOnObJ3ucpN0AcwSWnMowTRg=="], + + "cf/miniflare/workerd/@cloudflare/workerd-darwin-64": ["@cloudflare/workerd-darwin-64@1.20260930.2", "", { "os": "darwin", "cpu": "x64" }, "sha512-wxKsfekWeev6xkjHEMx3x7nz6WfWOn1/scQ8geqWQhUm8qRl1ZRZhjnj+rucIMLhLhP9RGSYMZIjEm3AV0zwVQ=="], + + "cf/miniflare/workerd/@cloudflare/workerd-darwin-arm64": ["@cloudflare/workerd-darwin-arm64@1.20260930.2", "", { "os": "darwin", "cpu": "arm64" }, "sha512-cviPpheZGQ2H5X+Ctxd3wfxhksNrdyoNprjSgg3br2+psetKacjdEvK8CILdN/2GF+u1KOExvr45amSL6lgzGA=="], + + "cf/miniflare/workerd/@cloudflare/workerd-linux-64": ["@cloudflare/workerd-linux-64@1.20260930.2", "", { "os": "linux", "cpu": "x64" }, "sha512-cwrJAC5y/avPd1OzGyhc5OvUUfPXBFc065TY5CjXp7Hb3dhiTx6JeB5Pc8L3G8L8M44HyAfRHSpoLtRr+SR3cQ=="], + + "cf/miniflare/workerd/@cloudflare/workerd-linux-arm64": ["@cloudflare/workerd-linux-arm64@1.20260930.2", "", { "os": "linux", "cpu": "arm64" }, "sha512-FHucB4gak1IuT+IxLx3KbtMBMapZhcqD9EdhHvBxk1FpHwD2QU5x26MRRVN53jIKG/O25HUmE9yffb3cMANQgw=="], + + "cf/miniflare/workerd/@cloudflare/workerd-windows-64": ["@cloudflare/workerd-windows-64@1.20260930.2", "", { "os": "win32", "cpu": "x64" }, "sha512-JHFMdGFMqP+M2QiVzZq1S8Ie66Gvxo7Og5EYz/KtmDvGCqge5L3lK+ksZxAhF3j/tpSLqdvlUvcTKoR9PkwTTQ=="], + + "cf/@cloudflare/runtime-types/miniflare/sharp/@img/sharp-darwin-arm64": ["@img/sharp-darwin-arm64@0.35.4", "", { "optionalDependencies": { "@img/sharp-libvips-darwin-arm64": "1.3.3" }, "os": "darwin", "cpu": "arm64" }, "sha512-Uhfl4V4lhP2nbUVF9+hyH1+luj86f1gUFeo8ALYxFoULoU+G87D43BfeMP8XHsk9boxAnCY/bf2EHwhA7MuGsA=="], + + "cf/@cloudflare/runtime-types/miniflare/sharp/@img/sharp-darwin-x64": ["@img/sharp-darwin-x64@0.35.4", "", { "optionalDependencies": { "@img/sharp-libvips-darwin-x64": "1.3.3" }, "os": "darwin", "cpu": "x64" }, "sha512-hWniXY3bG5qKpkKrAwPe4y+VTPmf086YQAnkxWh7uA1YrlRouWGa0M0Mxj3ZjnXFkv7/TD1bTy9lGUK26vRvWw=="], + + "cf/@cloudflare/runtime-types/miniflare/sharp/@img/sharp-freebsd-wasm32": ["@img/sharp-freebsd-wasm32@0.35.4", "", { "dependencies": { "@img/sharp-wasm32": "0.35.4" }, "os": "freebsd" }, "sha512-lIsKw/BU+kjB4eZjxrYrZmwOJYi3Ajrv66iAlBmUPyKc3HpnloevB1g3wxGD9P/5BbQ1brBGl65VRRrCvQDEqA=="], + + "cf/@cloudflare/runtime-types/miniflare/sharp/@img/sharp-libvips-darwin-arm64": ["@img/sharp-libvips-darwin-arm64@1.3.3", "", { "os": "darwin", "cpu": "arm64" }, "sha512-suTBPTDGrI9WodccaDdwZItTSaBYASlBk1NSfElSHrUfzu3szG6lvIF58+WiFvnfzuK8ZBFS5zE00PxqxnRiPg=="], + + "cf/@cloudflare/runtime-types/miniflare/sharp/@img/sharp-libvips-darwin-x64": ["@img/sharp-libvips-darwin-x64@1.3.3", "", { "os": "darwin", "cpu": "x64" }, "sha512-FVJZ5mITMobmXIz/hPDTw0EintTW5H3WfrxwLqEqjiIihlu+hVRyGrFQ60xl0Lxn7Bt3zdpevPaQi0HEzqz9fw=="], + + "cf/@cloudflare/runtime-types/miniflare/sharp/@img/sharp-libvips-linux-arm": ["@img/sharp-libvips-linux-arm@1.3.3", "", { "os": "linux", "cpu": "arm", "libc": "glibc" }, "sha512-3rbU4vqXXc3hY/OiXdl52xZvT0F1yEngWfvqudtPJg/KkyiaQw2DRsFrNzpmLvfavbwOq3qXn36GP8obHRULQA=="], + + "cf/@cloudflare/runtime-types/miniflare/sharp/@img/sharp-libvips-linux-arm64": ["@img/sharp-libvips-linux-arm64@1.3.3", "", { "os": "linux", "cpu": "arm64", "libc": "glibc" }, "sha512-0DaL0A6Xu6sQSQFwe4iVCrKWU2cCTItnRsYsCdxAMm9NF6twAA9BKnoqy4hqz4+azQ0JHuA26qiUKsf1XJ/v5A=="], + + "cf/@cloudflare/runtime-types/miniflare/sharp/@img/sharp-libvips-linux-ppc64": ["@img/sharp-libvips-linux-ppc64@1.3.3", "", { "os": "linux", "cpu": "ppc64", "libc": "glibc" }, "sha512-cdn1OvUBwsXhbC0zSzJnNzf5MZ/mTrobawDvNXBTxe8VtqKAm0sRuEY2Evzovb/w9JMk4TvRxqt1mekSuJz64w=="], + + "cf/@cloudflare/runtime-types/miniflare/sharp/@img/sharp-libvips-linux-riscv64": ["@img/sharp-libvips-linux-riscv64@1.3.3", "", { "os": "linux", "cpu": "none", "libc": "glibc" }, "sha512-HjPVx7yKz+0lqdhDlTw1tt90wamBoxhiXpvl1XZpJLiHH4RCJ5yDTqH+VlYPv2fwFs89JFw4c1IexYOcQUi4IQ=="], + + "cf/@cloudflare/runtime-types/miniflare/sharp/@img/sharp-libvips-linux-s390x": ["@img/sharp-libvips-linux-s390x@1.3.3", "", { "os": "linux", "cpu": "s390x", "libc": "glibc" }, "sha512-neWLh+3yCNThxnfy3c4BbVBeGgt9aftno+XbT56iK28RgeDs3UOFWviLWlUu0bArYVYJaFDK+RRohbicUNCm8Q=="], + + "cf/@cloudflare/runtime-types/miniflare/sharp/@img/sharp-libvips-linux-x64": ["@img/sharp-libvips-linux-x64@1.3.3", "", { "os": "linux", "cpu": "x64", "libc": "glibc" }, "sha512-4vKmvAst9nrowcqquKFAyZJUDolUaIp8uRiN0mWFguJ1IplC9/pitXtlnnlU4aa/eJw3J7i67V+pwUL+wZGdsA=="], + + "cf/@cloudflare/runtime-types/miniflare/sharp/@img/sharp-libvips-linuxmusl-arm64": ["@img/sharp-libvips-linuxmusl-arm64@1.3.3", "", { "os": "linux", "cpu": "arm64", "libc": "musl" }, "sha512-Y9kQaLMuNoB0bPYOOdcZMaseNrFpPodIWWMrx+CZyydf2xn68j9WYc6sWWRrDwNkzCQjKYfc68L7jKjGlHMibw=="], + + "cf/@cloudflare/runtime-types/miniflare/sharp/@img/sharp-libvips-linuxmusl-x64": ["@img/sharp-libvips-linuxmusl-x64@1.3.3", "", { "os": "linux", "cpu": "x64", "libc": "musl" }, "sha512-fj8Mv0HHfD1Rr+4I68+3agJynxDWtBFgicTbSOb9Bke6pIwzGcJ+RX/yHjmiEGFMCavY/dxvem7MyNaJF+wDiw=="], + + "cf/@cloudflare/runtime-types/miniflare/sharp/@img/sharp-linux-arm": ["@img/sharp-linux-arm@0.35.4", "", { "optionalDependencies": { "@img/sharp-libvips-linux-arm": "1.3.3" }, "os": "linux", "cpu": "arm", "libc": "glibc" }, "sha512-7OAS8gI0EReKGVN2HssHlM6umJgxF5VI3xN0p9FA91p/YO+ou5hiNghLdZ5BEHztwaaK5+bLKRf8x/o2L2nk9A=="], + + "cf/@cloudflare/runtime-types/miniflare/sharp/@img/sharp-linux-arm64": ["@img/sharp-linux-arm64@0.35.4", "", { "optionalDependencies": { "@img/sharp-libvips-linux-arm64": "1.3.3" }, "os": "linux", "cpu": "arm64", "libc": "glibc" }, "sha512-De4jpEnAU8Hd5oT0j1G3uL4ZvTuipVMn7YC6vPaJhy6/7EwEae0SVAoBrUMYQbkLGDm85taVWwuPc1a44LTzCQ=="], + + "cf/@cloudflare/runtime-types/miniflare/sharp/@img/sharp-linux-ppc64": ["@img/sharp-linux-ppc64@0.35.4", "", { "optionalDependencies": { "@img/sharp-libvips-linux-ppc64": "1.3.3" }, "os": "linux", "cpu": "ppc64", "libc": "glibc" }, "sha512-2oYZJeIl4kCcMGk4ouZVjnkCtFrpQFlNEtJ6GbxzhHQchwH0NH/qEb9ykmOl29dqwMq+JhFdZn+1ak2FKhI9fQ=="], + + "cf/@cloudflare/runtime-types/miniflare/sharp/@img/sharp-linux-riscv64": ["@img/sharp-linux-riscv64@0.35.4", "", { "optionalDependencies": { "@img/sharp-libvips-linux-riscv64": "1.3.3" }, "os": "linux", "cpu": "none", "libc": "glibc" }, "sha512-cPbNChoRURAWdebDIHSenxRpgEdy7JkPydSnUxRm9VvKD7m0/xVaR/8Fzlu81pk5nHEvHH87UZUA7cTtwnbJSA=="], + + "cf/@cloudflare/runtime-types/miniflare/sharp/@img/sharp-linux-s390x": ["@img/sharp-linux-s390x@0.35.4", "", { "optionalDependencies": { "@img/sharp-libvips-linux-s390x": "1.3.3" }, "os": "linux", "cpu": "s390x", "libc": "glibc" }, "sha512-RY0JFY8Fd6RonCBtHz+DvadaPkXDSI1AUn6yWL9TipqkZ1vY8w8evqdgyDFnkm4/K1ve1TvZiaePP5oSd4+WVQ=="], + + "cf/@cloudflare/runtime-types/miniflare/sharp/@img/sharp-linux-x64": ["@img/sharp-linux-x64@0.35.4", "", { "optionalDependencies": { "@img/sharp-libvips-linux-x64": "1.3.3" }, "os": "linux", "cpu": "x64", "libc": "glibc" }, "sha512-9qvvEAuk8k89TfWUoX2htWjbAMX8p+NxCppjpcg5k6xMsjhBQPTsoIh36h9Qde4WRuGpJeYnOjdosDn/cnv+OA=="], + + "cf/@cloudflare/runtime-types/miniflare/sharp/@img/sharp-linuxmusl-arm64": ["@img/sharp-linuxmusl-arm64@0.35.4", "", { "optionalDependencies": { "@img/sharp-libvips-linuxmusl-arm64": "1.3.3" }, "os": "linux", "cpu": "arm64", "libc": "musl" }, "sha512-KB5jxpfWQTr0nc3xdHtWChdbifHrBGsd2SM62Eyxrl8afikm+f5qGBU75SJIZBT/S1MC8XyacdlXBMSWq6OURA=="], + + "cf/@cloudflare/runtime-types/miniflare/sharp/@img/sharp-linuxmusl-x64": ["@img/sharp-linuxmusl-x64@0.35.4", "", { "optionalDependencies": { "@img/sharp-libvips-linuxmusl-x64": "1.3.3" }, "os": "linux", "cpu": "x64", "libc": "musl" }, "sha512-f+eZJZIQNEEd26RPSW+76chwOf1XtA2Y/O+5ocVyLliHkeih3e+jhLVBdNTd2rS3IbNXK8+ug93Vf5ZXtF5Lxg=="], + + "cf/@cloudflare/runtime-types/miniflare/sharp/@img/sharp-webcontainers-wasm32": ["@img/sharp-webcontainers-wasm32@0.35.4", "", { "dependencies": { "@img/sharp-wasm32": "0.35.4" }, "cpu": "none" }, "sha512-ESfNkywmCfPNyaZjxooddJQiQ+l/nTpGEOGthxiLnIHXC/CmcBixnfwUleX9mCz9ovrUUvKMap/pm8RYbzfwaA=="], + + "cf/@cloudflare/runtime-types/miniflare/sharp/@img/sharp-win32-arm64": ["@img/sharp-win32-arm64@0.35.4", "", { "os": "win32", "cpu": "arm64" }, "sha512-iNdlBX9gLVvqe2I3uIJSIKTq6wckP/DYxZtcqxm09x5Gi24DnFBmPAWZmr60ZyYMG0xlzo6goG3670ar+RXvRw=="], + + "cf/@cloudflare/runtime-types/miniflare/sharp/@img/sharp-win32-ia32": ["@img/sharp-win32-ia32@0.35.4", "", { "os": "win32", "cpu": "ia32" }, "sha512-kqRsbaa5CS6KHlpxnN7WhE6vAAugXyZButpRdvDWetlv6Qv4N9WTcrWzF7tXfB9T7MsoadqdI8hmwLq6UlLvtw=="], + + "cf/@cloudflare/runtime-types/miniflare/sharp/@img/sharp-win32-x64": ["@img/sharp-win32-x64@0.35.4", "", { "os": "win32", "cpu": "x64" }, "sha512-XtmnYhBcrORsJ4XJngyzr/EWP0hRZLAZRFaApdKuviyqF78+ylxh2y06ZmtULAMOnObJ3ucpN0AcwSWnMowTRg=="], + + "cf/miniflare/sharp/@img/sharp-freebsd-wasm32/@img/sharp-wasm32": ["@img/sharp-wasm32@0.35.4", "", { "dependencies": { "@emnapi/runtime": "^1.11.3" } }, "sha512-zQnl4Kwp7Q6NHsENtU2T/00Zi+w3AQNwz3+UaTyVBy2FpXrzXzGjndpK61onhZjRtRpQXxCTeqw19bVyXOh7jA=="], + + "cf/miniflare/sharp/@img/sharp-webcontainers-wasm32/@img/sharp-wasm32": ["@img/sharp-wasm32@0.35.4", "", { "dependencies": { "@emnapi/runtime": "^1.11.3" } }, "sha512-zQnl4Kwp7Q6NHsENtU2T/00Zi+w3AQNwz3+UaTyVBy2FpXrzXzGjndpK61onhZjRtRpQXxCTeqw19bVyXOh7jA=="], + + "cf/@cloudflare/runtime-types/miniflare/sharp/@img/sharp-freebsd-wasm32/@img/sharp-wasm32": ["@img/sharp-wasm32@0.35.4", "", { "dependencies": { "@emnapi/runtime": "^1.11.3" } }, "sha512-zQnl4Kwp7Q6NHsENtU2T/00Zi+w3AQNwz3+UaTyVBy2FpXrzXzGjndpK61onhZjRtRpQXxCTeqw19bVyXOh7jA=="], + + "cf/@cloudflare/runtime-types/miniflare/sharp/@img/sharp-webcontainers-wasm32/@img/sharp-wasm32": ["@img/sharp-wasm32@0.35.4", "", { "dependencies": { "@emnapi/runtime": "^1.11.3" } }, "sha512-zQnl4Kwp7Q6NHsENtU2T/00Zi+w3AQNwz3+UaTyVBy2FpXrzXzGjndpK61onhZjRtRpQXxCTeqw19bVyXOh7jA=="], + + "cf/miniflare/sharp/@img/sharp-freebsd-wasm32/@img/sharp-wasm32/@emnapi/runtime": ["@emnapi/runtime@1.11.3", "", { "dependencies": { "tslib": "^2.4.0" } }, "sha512-Xz4Tpyki7XyrpbUK1jR1AhdAdaXyhhY4lZ3neLodmhpuWfy2PAQN5B46sAiU4liOXGLkHypn/qU+jvfWSCYYLA=="], + + "cf/miniflare/sharp/@img/sharp-webcontainers-wasm32/@img/sharp-wasm32/@emnapi/runtime": ["@emnapi/runtime@1.11.3", "", { "dependencies": { "tslib": "^2.4.0" } }, "sha512-Xz4Tpyki7XyrpbUK1jR1AhdAdaXyhhY4lZ3neLodmhpuWfy2PAQN5B46sAiU4liOXGLkHypn/qU+jvfWSCYYLA=="], + + "cf/@cloudflare/runtime-types/miniflare/sharp/@img/sharp-freebsd-wasm32/@img/sharp-wasm32/@emnapi/runtime": ["@emnapi/runtime@1.11.3", "", { "dependencies": { "tslib": "^2.4.0" } }, "sha512-Xz4Tpyki7XyrpbUK1jR1AhdAdaXyhhY4lZ3neLodmhpuWfy2PAQN5B46sAiU4liOXGLkHypn/qU+jvfWSCYYLA=="], + + "cf/@cloudflare/runtime-types/miniflare/sharp/@img/sharp-webcontainers-wasm32/@img/sharp-wasm32/@emnapi/runtime": ["@emnapi/runtime@1.11.3", "", { "dependencies": { "tslib": "^2.4.0" } }, "sha512-Xz4Tpyki7XyrpbUK1jR1AhdAdaXyhhY4lZ3neLodmhpuWfy2PAQN5B46sAiU4liOXGLkHypn/qU+jvfWSCYYLA=="], + } +} diff --git a/app/vendor/rune/www/cloudflare.config.ts b/app/vendor/rune/www/cloudflare.config.ts new file mode 100644 index 0000000..5e81142 --- /dev/null +++ b/app/vendor/rune/www/cloudflare.config.ts @@ -0,0 +1,26 @@ +import { bindings, defineConfig, triggers } from "cf/config" +import { BASE_PATH, hostForMode } from "./src/base.ts" + +// `--mode dev` builds and deploys the dev Worker on dev.anoma.ly; any other mode is production on anoma.ly. +// The account comes from CLOUDFLARE_ACCOUNT_ID. +export default defineConfig(({ mode }) => { + const host = hostForMode(mode) + return { + worker: { + name: mode === "dev" ? "rune-www-dev" : "rune-www-production", + compatibilityDate: "2026-10-13", + entrypoint: "./worker.ts", + assets: { runWorkerFirst: true }, + env: { + ASSETS: bindings.assets(), + CANONICAL_HOST: bindings.text(host), + }, + triggers: [ + triggers.fetch({ pattern: `${host}${BASE_PATH}`, zone: host }), + triggers.fetch({ pattern: `${host}${BASE_PATH}/*`, zone: host }), + ], + workersDev: false, + previewUrls: false, + }, + } +}) diff --git a/app/vendor/rune/www/index.html b/app/vendor/rune/www/index.html new file mode 100644 index 0000000..c98c926 --- /dev/null +++ b/app/vendor/rune/www/index.html @@ -0,0 +1,54 @@ +<!doctype html> +<html lang="en"> + <head> + <meta charset="UTF-8" /> + <meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover" /> + <meta name="color-scheme" content="dark" /> + <meta name="theme-color" content="#000000" /> + <!--robots--> + <title>__TITLE__</title> + <meta name="description" content="__DESCRIPTION__" /> + <link rel="canonical" href="__URL__" /> + <meta property="og:type" content="website" /> + <meta property="og:site_name" content="Rune" /> + <meta property="og:locale" content="en_US" /> + <meta property="og:title" content="__SHARE_TITLE__" /> + <meta property="og:description" content="__DESCRIPTION__" /> + <meta property="og:url" content="__URL__" /> + <meta property="og:image" content="__ORIGIN__/og.png" /> + <meta property="og:image:type" content="image/png" /> + <meta property="og:image:width" content="1200" /> + <meta property="og:image:height" content="630" /> + <meta property="og:image:alt" content="ᚱUNE in blue pixel letters on black, the R the rune ᚱ" /> + <meta name="twitter:card" content="summary_large_image" /> + <meta name="twitter:title" content="__SHARE_TITLE__" /> + <meta name="twitter:description" content="__DESCRIPTION__" /> + <meta name="twitter:image" content="__ORIGIN__/og.png" /> + <link rel="icon" href="%BASE_URL%favicon.ico" sizes="16x16 32x32" /> + <link rel="icon" type="image/svg+xml" href="%BASE_URL%favicon.svg" /> + <link rel="apple-touch-icon" href="%BASE_URL%apple-touch-icon.png" /> + <link rel="manifest" href="%BASE_URL%site.webmanifest" /> + <link rel="alternate" type="text/plain" href="%BASE_URL%llms.txt" title="llms.txt" /> + <!-- Rune reads the same files, so the page and the canvas share one download. --> + <link rel="preload" href="%BASE_URL%fonts/geist.ttf" as="font" type="font/ttf" crossorigin /> + <link rel="preload" href="%BASE_URL%fonts/geist-mono.ttf" as="font" type="font/ttf" crossorigin /> + <style> + @font-face { font-family: "Geist"; src: url("/fonts/geist.ttf") format("truetype"); font-weight: 100 900; font-display: swap; } + @font-face { font-family: "Geist Mono"; src: url("/fonts/geist-mono.ttf") format("truetype"); font-weight: 100 900; font-display: swap; } + :root { + --rune-sans: "Geist", ui-sans-serif, system-ui, -apple-system, "Segoe UI", sans-serif; + --rune-mono: "Geist Mono", ui-monospace, "SF Mono", Menlo, monospace; + } + html { background: #000; color: #ededed; font: 400 16px/24px var(--rune-sans); -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; text-size-adjust: 100%; } + body { margin: 0; } + :focus-visible { outline: 2px solid oklch(0.74 0.14 245); outline-offset: 2px; border-radius: 4px; } + ::selection { background: oklch(0.74 0.14 245 / 0.4); } + </style> + <!-- rune:css --> + <!--jsonld--> + </head> + <body> + <!-- rune:body --> + <script type="module" src="/src/main.ts"></script> + </body> +</html> diff --git a/app/vendor/rune/www/package.json b/app/vendor/rune/www/package.json new file mode 100644 index 0000000..5a656f1 --- /dev/null +++ b/app/vendor/rune/www/package.json @@ -0,0 +1,25 @@ +{ + "name": "rune-www", + "version": "0.0.0", + "private": true, + "type": "module", + "scripts": { + "build": "bun scripts/build.ts", + "preview": "vite preview --outDir .cloudflare/output/v0/workers/default/assets", + "serve": "bun scripts/serve.ts", + "check": "tsc --noEmit", + "icons": "bun scripts/icons.ts", + "images": "bun scripts/images.ts", + "deploy:dev": "bun scripts/build.ts --mode dev && cf deploy --prebuilt --mode dev", + "deploy:production": "bun scripts/build.ts --mode production && cf deploy --prebuilt --mode production" + }, + "devDependencies": { + "@cloudflare/build-output-utils": "0.8.5", + "@cloudflare/vite-plugin": "2.0.0-beta.v.4", + "@types/bun": "1.3.13", + "@types/node": "25.5.0", + "cf": "1.0.0-beta.12", + "typescript": "6.0.2", + "vite": "8.1.3" + } +} diff --git a/app/vendor/rune/www/public/apple-touch-icon.png b/app/vendor/rune/www/public/apple-touch-icon.png new file mode 100644 index 0000000..b7c70fe Binary files /dev/null and b/app/vendor/rune/www/public/apple-touch-icon.png differ diff --git a/app/vendor/rune/www/public/favicon.ico b/app/vendor/rune/www/public/favicon.ico new file mode 100644 index 0000000..7a6671d Binary files /dev/null and b/app/vendor/rune/www/public/favicon.ico differ diff --git a/app/vendor/rune/www/public/favicon.svg b/app/vendor/rune/www/public/favicon.svg new file mode 100644 index 0000000..3dd9fc0 --- /dev/null +++ b/app/vendor/rune/www/public/favicon.svg @@ -0,0 +1 @@ +<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 16 16" shape-rendering="crispEdges" fill="#54b3fd"><rect x="3" y="1" width="4" height="1"/><rect x="3" y="2" width="5" height="1"/><rect x="3" y="3" width="6" height="1"/><rect x="3" y="4" width="3" height="1"/><rect x="7" y="4" width="3" height="1"/><rect x="3" y="5" width="3" height="1"/><rect x="8" y="5" width="3" height="1"/><rect x="3" y="6" width="3" height="1"/><rect x="8" y="6" width="3" height="1"/><rect x="3" y="7" width="3" height="1"/><rect x="7" y="7" width="3" height="1"/><rect x="3" y="8" width="6" height="1"/><rect x="3" y="9" width="5" height="1"/><rect x="3" y="10" width="6" height="1"/><rect x="3" y="11" width="3" height="1"/><rect x="7" y="11" width="3" height="1"/><rect x="3" y="12" width="3" height="1"/><rect x="8" y="12" width="3" height="1"/><rect x="3" y="13" width="3" height="1"/><rect x="9" y="13" width="3" height="1"/><rect x="3" y="14" width="3" height="1"/><rect x="10" y="14" width="3" height="1"/></svg> diff --git a/app/vendor/rune/www/public/fonts/geist-OFL.txt b/app/vendor/rune/www/public/fonts/geist-OFL.txt new file mode 100644 index 0000000..8d003fe --- /dev/null +++ b/app/vendor/rune/www/public/fonts/geist-OFL.txt @@ -0,0 +1,92 @@ +Copyright (c) 2023 Vercel, in collaboration with basement.studio + +This Font Software is licensed under the SIL Open Font License, Version 1.1. +This license is copied below, and is also available with a FAQ at: +http://scripts.sil.org/OFL + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION AND CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. diff --git a/app/vendor/rune/www/public/fonts/geist-mono.ttf b/app/vendor/rune/www/public/fonts/geist-mono.ttf new file mode 100644 index 0000000..2e43194 Binary files /dev/null and b/app/vendor/rune/www/public/fonts/geist-mono.ttf differ diff --git a/app/vendor/rune/www/public/fonts/geist.ttf b/app/vendor/rune/www/public/fonts/geist.ttf new file mode 100644 index 0000000..174ee5c Binary files /dev/null and b/app/vendor/rune/www/public/fonts/geist.ttf differ diff --git a/app/vendor/rune/www/public/icon-192.png b/app/vendor/rune/www/public/icon-192.png new file mode 100644 index 0000000..3d0a4a0 Binary files /dev/null and b/app/vendor/rune/www/public/icon-192.png differ diff --git a/app/vendor/rune/www/public/icon-512.png b/app/vendor/rune/www/public/icon-512.png new file mode 100644 index 0000000..26eef21 Binary files /dev/null and b/app/vendor/rune/www/public/icon-512.png differ diff --git a/app/vendor/rune/www/public/img/glass-380.avif b/app/vendor/rune/www/public/img/glass-380.avif new file mode 100644 index 0000000..34a3846 Binary files /dev/null and b/app/vendor/rune/www/public/img/glass-380.avif differ diff --git a/app/vendor/rune/www/public/img/glass-760.avif b/app/vendor/rune/www/public/img/glass-760.avif new file mode 100644 index 0000000..56dcd51 Binary files /dev/null and b/app/vendor/rune/www/public/img/glass-760.avif differ diff --git a/app/vendor/rune/www/public/img/hello-320.avif b/app/vendor/rune/www/public/img/hello-320.avif new file mode 100644 index 0000000..33162da Binary files /dev/null and b/app/vendor/rune/www/public/img/hello-320.avif differ diff --git a/app/vendor/rune/www/public/img/hello-640.avif b/app/vendor/rune/www/public/img/hello-640.avif new file mode 100644 index 0000000..a2ef16d Binary files /dev/null and b/app/vendor/rune/www/public/img/hello-640.avif differ diff --git a/app/vendor/rune/www/public/img/light-380.avif b/app/vendor/rune/www/public/img/light-380.avif new file mode 100644 index 0000000..962bbd1 Binary files /dev/null and b/app/vendor/rune/www/public/img/light-380.avif differ diff --git a/app/vendor/rune/www/public/img/light-760.avif b/app/vendor/rune/www/public/img/light-760.avif new file mode 100644 index 0000000..40a0d04 Binary files /dev/null and b/app/vendor/rune/www/public/img/light-760.avif differ diff --git a/app/vendor/rune/www/public/img/metal-1520.avif b/app/vendor/rune/www/public/img/metal-1520.avif new file mode 100644 index 0000000..9bb47a5 Binary files /dev/null and b/app/vendor/rune/www/public/img/metal-1520.avif differ diff --git a/app/vendor/rune/www/public/img/metal-760.avif b/app/vendor/rune/www/public/img/metal-760.avif new file mode 100644 index 0000000..b774d9b Binary files /dev/null and b/app/vendor/rune/www/public/img/metal-760.avif differ diff --git a/app/vendor/rune/www/public/img/opencode-home-1100.avif b/app/vendor/rune/www/public/img/opencode-home-1100.avif new file mode 100644 index 0000000..a96e0b2 Binary files /dev/null and b/app/vendor/rune/www/public/img/opencode-home-1100.avif differ diff --git a/app/vendor/rune/www/public/img/opencode-home-560.avif b/app/vendor/rune/www/public/img/opencode-home-560.avif new file mode 100644 index 0000000..d09e6dc Binary files /dev/null and b/app/vendor/rune/www/public/img/opencode-home-560.avif differ diff --git a/app/vendor/rune/www/public/img/opencode-session-1120.avif b/app/vendor/rune/www/public/img/opencode-session-1120.avif new file mode 100644 index 0000000..a951537 Binary files /dev/null and b/app/vendor/rune/www/public/img/opencode-session-1120.avif differ diff --git a/app/vendor/rune/www/public/img/opencode-session-1680.avif b/app/vendor/rune/www/public/img/opencode-session-1680.avif new file mode 100644 index 0000000..667df35 Binary files /dev/null and b/app/vendor/rune/www/public/img/opencode-session-1680.avif differ diff --git a/app/vendor/rune/www/public/img/opencode-session-2240.avif b/app/vendor/rune/www/public/img/opencode-session-2240.avif new file mode 100644 index 0000000..cb57141 Binary files /dev/null and b/app/vendor/rune/www/public/img/opencode-session-2240.avif differ diff --git a/app/vendor/rune/www/public/img/opencode-session-720.avif b/app/vendor/rune/www/public/img/opencode-session-720.avif new file mode 100644 index 0000000..a6cb15e Binary files /dev/null and b/app/vendor/rune/www/public/img/opencode-session-720.avif differ diff --git a/app/vendor/rune/www/public/img/opencode-streaming-1100.avif b/app/vendor/rune/www/public/img/opencode-streaming-1100.avif new file mode 100644 index 0000000..5f88e37 Binary files /dev/null and b/app/vendor/rune/www/public/img/opencode-streaming-1100.avif differ diff --git a/app/vendor/rune/www/public/img/opencode-streaming-560.avif b/app/vendor/rune/www/public/img/opencode-streaming-560.avif new file mode 100644 index 0000000..fa11392 Binary files /dev/null and b/app/vendor/rune/www/public/img/opencode-streaming-560.avif differ diff --git a/app/vendor/rune/www/public/og.png b/app/vendor/rune/www/public/og.png new file mode 100644 index 0000000..b0fe521 Binary files /dev/null and b/app/vendor/rune/www/public/og.png differ diff --git a/app/vendor/rune/www/public/site.webmanifest b/app/vendor/rune/www/public/site.webmanifest new file mode 100644 index 0000000..7a97a62 --- /dev/null +++ b/app/vendor/rune/www/public/site.webmanifest @@ -0,0 +1,13 @@ +{ + "name": "Rune", + "short_name": "Rune", + "description": "A Rust UI framework with its own GPU renderer, text, layout and spring animation.", + "start_url": "./", + "display": "browser", + "background_color": "#000000", + "theme_color": "#000000", + "icons": [ + { "src": "icon-192.png", "sizes": "192x192", "type": "image/png" }, + { "src": "icon-512.png", "sizes": "512x512", "type": "image/png" } + ] +} diff --git a/app/vendor/rune/www/scripts/build.ts b/app/vendor/rune/www/scripts/build.ts new file mode 100644 index 0000000..a7bbfe3 --- /dev/null +++ b/app/vendor/rune/www/scripts/build.ts @@ -0,0 +1,130 @@ +#!/usr/bin/env bun +// `bun run build [--mode dev]`: the page is the Rune app in app/. This builds it to wasm (src/wasm/), bundles +// src/main.ts and the Worker with Vite into Build Output, then has the app write its own static HTML (`--html`) into +// index.html and 404.html, and adds robots.txt, sitemap.xml and llms.txt. +// Needs Rust with the wasm32-unknown-unknown target, the wasm-bindgen CLI at the version in Cargo.lock and binaryen's +// wasm-opt (`--no-opt` skips it). +import { readFileSync, writeFileSync } from "node:fs" +import { join, relative, resolve } from "node:path" +import { parseArgs } from "node:util" +import { getWorkerAssetsDir } from "@cloudflare/build-output-utils" +import { $ } from "bun" +import { BASE_PATH, hostForMode } from "../src/base" +import { DESCRIPTION, REPO, SHARE_TITLE, TITLE } from "../src/meta" + +const { values } = parseArgs({ + options: { mode: { type: "string", default: "production" }, "no-opt": { type: "boolean", default: false } }, +}) +const production = values.mode !== "dev" +const origin = `https://${hostForMode(values.mode)}${BASE_PATH}` + +const www = resolve(import.meta.dirname, "..") +const repo = resolve(www, "..") +// The commit the page tells you to pin: the one it was built from (or $RUNE_REV, outside a checkout). +const rev = process.env.RUNE_REV ?? (await $`git rev-parse --short=12 HEAD`.cwd(repo).text()).trim() +const env = { ...process.env, RUNE_REV: rev } +const cargo = process.env.CARGO ?? "cargo" +// The widths the static page is taken at: its breakpoints and the narrowest phone. +const widths = "360,400,560,760,860,1000" + +// Smallest wasm: optimized for size with whole-program LTO, then wasm-opt. `--no-opt` builds quicker and larger. +const size = values["no-opt"] ? {} : { CARGO_PROFILE_RELEASE_OPT_LEVEL: "z", CARGO_PROFILE_RELEASE_LTO: "fat" } +const opt = values["no-opt"] ? [] : ["--opt"] +await $`scripts/web-build.sh rune-www --out www/src/wasm --no-html ${opt}`.cwd(repo).env({ ...env, ...size }) +await $`tsc --noEmit`.cwd(www) +await $`vite build --mode ${values.mode}`.cwd(www) + +const dir = getWorkerAssetsDir(www) +const built = readFileSync(join(dir, "index.html"), "utf8") +const escape = (s: string) => s.replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/</g, "&lt;").replace(/>/g, "&gt;") + +const jsonld = { + "@context": "https://schema.org", + "@graph": [ + { "@type": "WebSite", name: "Rune", url: `${origin}/` }, + { + "@type": "SoftwareSourceCode", + name: "Rune", + description: DESCRIPTION, + url: `${origin}/`, + codeRepository: REPO, + programmingLanguage: "Rust", + runtimePlatform: ["macOS", "Windows", "Linux", "Web (WebGPU)", "iOS"], + author: { "@type": "Organization", name: "Anomaly", url: "https://anoma.ly" }, + }, + ], +} + +const head = (path: string, title: string, description: string, html: string) => + html + .replace("<!--robots-->", production ? "" : `<meta name="robots" content="noindex, nofollow" />`) + .replace("<!--jsonld-->", path === "/" ? `<script type="application/ld+json">${JSON.stringify(jsonld)}</script>` : "") + .replaceAll("__URL__", `${origin}${path}`) + .replaceAll("__SHARE_TITLE__", escape(path === "/" ? SHARE_TITLE : title)) + .replaceAll("__TITLE__", escape(title)) + .replaceAll("__DESCRIPTION__", escape(description)) + .replaceAll("__ORIGIN__", origin) + +// The app lays itself out at each width and writes the page into the template; run from public/ so it finds the fonts. +const page = async (file: string, template: string, extra: Record<string, string> = {}) => { + const path = join(dir, file) + writeFileSync(path, template) + await $`${cargo} run -q -p rune-www -- --html ${path} --html-widths ${widths} --html-template ${path}` + .cwd(join(www, "public")) + .env({ ...env, ...extra }) +} + +await page("index.html", head("/", TITLE, DESCRIPTION, built)) +// The Worker serves this for any missing path under the base, with a 404. It has no wasm and no canonical URL. +const notFound = head("/404", "Not found · Rune", "There's no page here.", built) + .replace(/\s*<script type="module"[^>]*><\/script>/g, "") + .replace(/\s*<link rel="modulepreload"[^>]*>/g, "") + .replace(/\s*<link rel="canonical"[^>]*>/, "") +await page("404.html", notFound, { RUNE_WWW_PAGE: "404" }) + +// Dev is for checking before release: keep it out of search. +writeFileSync( + join(dir, "robots.txt"), + production ? `User-agent: *\nAllow: /\n\nSitemap: ${origin}/sitemap.xml\n` : "User-agent: *\nDisallow: /\n", +) +if (production) { + writeFileSync( + join(dir, "sitemap.xml"), + `<?xml version="1.0" encoding="UTF-8"?>\n<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\n <url><loc>${origin}/</loc></url>\n</urlset>\n`, + ) +} + +// llms.txt (llmstxt.org): what Rune is and where to read more. +writeFileSync( + join(dir, "llms.txt"), + [ + "# Rune", + "", + `> ${DESCRIPTION}`, + "", + "Rune is a Rust UI framework. Views are plain Rust functions of state; Rune diffs them, lays them out with Taffy,", + "animates layout and properties with springs, and draws every frame with one instanced GPU draw. It runs on macOS", + "(its own Metal backend), Windows, Linux, iOS (embedded in UIKit or SwiftUI) and the web (WebGPU, experimental).", + "", + "This page is itself a Rune app: the HTML is what the app writes with `--html`, and the canvas is the same app.", + "", + "## Source", + "", + `- [anomalyco/rune](${REPO}): the code`, + `- [crates/rune/README.md](${REPO}/blob/dev/crates/rune/README.md): the framework guide`, + `- [WEB.md](${REPO}/blob/dev/WEB.md): building a Rune app for the browser`, + `- [CHANGELOG.md](${REPO}/blob/dev/CHANGELOG.md): what changed, newest first`, + `- [www/app](${REPO}/tree/dev/www/app): this page's source`, + "", + "## Use it", + "", + "Add Rune to Cargo.toml pinned to a commit:", + "", + "```toml", + `rune = { git = "${REPO}", rev = "${rev}" }`, + "```", + "", + ].join("\n"), +) + +console.log(`Built ${production ? "production" : "dev"} into ${relative(www, dir)}/`) diff --git a/app/vendor/rune/www/scripts/icons.ts b/app/vendor/rune/www/scripts/icons.ts new file mode 100644 index 0000000..901fe84 --- /dev/null +++ b/app/vendor/rune/www/scripts/icons.ts @@ -0,0 +1,94 @@ +#!/usr/bin/env bun +// `bun scripts/icons.ts`: draws the brand into public/: favicon.svg and favicon.ico (16 and 32) from the 16-cell ᚱ on +// transparent; apple-touch-icon.png (180), icon-192.png and icon-512.png from the wordmark's ᚱ on black; and og.png +// (1200 × 630), the whole wordmark on black. Every cell is a whole number of pixels, so the PNGs are written directly, +// with no browser. +import { writeFileSync } from "node:fs" +import { join, resolve } from "node:path" +import { deflateSync } from "node:zlib" +import { ICON16, INK, WORDMARK, oklch, runs, type Grid } from "../src/brand/pixels" + +const out = resolve(import.meta.dirname, "..", "public") +const ink = oklch(...INK).map(c => Math.round(c * 255)) as [number, number, number] +const hex = `#${ink.map(c => c.toString(16).padStart(2, "0")).join("")}` + +const crcTable = Array.from({ length: 256 }, (_, n) => { + let c = n + for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1 + return c >>> 0 +}) +const crc = (bytes: Uint8Array) => { + let c = 0xffffffff + for (const b of bytes) c = crcTable[(c ^ b) & 0xff]! ^ (c >>> 8) + return (c ^ 0xffffffff) >>> 0 +} +function chunk(type: string, data: Uint8Array) { + const body = new Uint8Array(4 + data.length) + body.set(new TextEncoder().encode(type)) + body.set(data, 4) + const out = new Uint8Array(12 + data.length) + const dv = new DataView(out.buffer) + dv.setUint32(0, data.length) + out.set(body, 4) + dv.setUint32(8 + data.length, crc(body)) + return out +} + +/** `rows` at `px` pixels a cell, centred in a `width` × `height` image on `background` (null for transparent), as an + * RGBA PNG. */ +function png(rows: Grid, px: number, background: [number, number, number] | null, width: number, height = width) { + const w = rows[0]!.length * px, h = rows.length * px + const ox = Math.floor((width - w) / 2), oy = Math.floor((height - h) / 2) + const raw = new Uint8Array(height * (width * 4 + 1)) + for (let y = 0; y < height; y++) { + const row = y * (width * 4 + 1) + for (let x = 0; x < width; x++) { + const cx = Math.floor((x - ox) / px), cy = Math.floor((y - oy) / px) + const on = x >= ox && y >= oy && rows[cy]?.[cx] === "#" + const rgb = on ? ink : background + if (rgb) raw.set([...rgb, 255], row + 1 + x * 4) + } + } + const header = new Uint8Array(13) + const dv = new DataView(header.buffer) + dv.setUint32(0, width) + dv.setUint32(4, height) + header.set([8, 6, 0, 0, 0], 8) + const parts = [new Uint8Array([137, 80, 78, 71, 13, 10, 26, 10]), chunk("IHDR", header), chunk("IDAT", deflateSync(raw)), chunk("IEND", new Uint8Array())] + return Buffer.concat(parts) +} + +/** An ICO holding PNGs, one entry per size. */ +function ico(images: { png: Uint8Array; size: number }[]) { + const header = 6 + 16 * images.length + const out = new Uint8Array(header + images.reduce((n, i) => n + i.png.length, 0)) + const dv = new DataView(out.buffer) + dv.setUint16(2, 1, true) + dv.setUint16(4, images.length, true) + let offset = header + images.forEach(({ png, size }, k) => { + const e = 6 + 16 * k + out[e] = size + out[e + 1] = size + dv.setUint16(e + 4, 1, true) + dv.setUint16(e + 6, 32, true) + dv.setUint32(e + 8, png.length, true) + dv.setUint32(e + 12, offset, true) + out.set(png, offset) + offset += png.length + }) + return out +} + +const rune = WORDMARK.glyphs[0]!.rows +const black: [number, number, number] = [0, 0, 0] +for (const [name, size, px] of [["icon-512.png", 512, 32], ["icon-192.png", 192, 12], ["apple-touch-icon.png", 180, 12]] as const) { + writeFileSync(join(out, name), png(rune, px, black, size)) +} +writeFileSync(join(out, "favicon.ico"), ico([32, 16].map(size => ({ size, png: png(ICON16, size / 16, null, size) })))) +const word = Array.from({ length: WORDMARK.height }, (_, y) => + Array.from({ length: WORDMARK.width }, (_, x) => (WORDMARK.glyphs.some(g => g.rows[y]?.[x - g.x] === "#") ? "#" : ".")).join("")) +writeFileSync(join(out, "og.png"), png(word, 24, black, 1200, 630)) +const rects = runs(ICON16).map(([x, y, w, h]) => `<rect x="${x}" y="${y}" width="${w}" height="${h}"/>`).join("") +writeFileSync(join(out, "favicon.svg"), `<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 16 16" shape-rendering="crispEdges" fill="${hex}">${rects}</svg>\n`) +console.log(`Icons in ${ink.join(",")} (${hex}) → ${out}`) diff --git a/app/vendor/rune/www/scripts/images.ts b/app/vendor/rune/www/scripts/images.ts new file mode 100644 index 0000000..713d48f --- /dev/null +++ b/app/vendor/rune/www/scripts/images.ts @@ -0,0 +1,43 @@ +#!/usr/bin/env bun +// `bun run images`: cuts the page's images from Rune's own renders in demo/ into AVIF at the sizes the page shows +// them, into public/img/. The widths and aspect ratios here match the `Picture`s in app/src/sections.rs. +// Needs ImageMagick 7 with AVIF. The outputs are committed, so a build never needs it. +import { mkdirSync, rmSync, statSync } from "node:fs" +import { join, resolve } from "node:path" +import { $ } from "bun" + +// Gallery tiles are 16:9, so crop renders of other shapes to 16:9 here. `smooth` is for soft gradients on black, which +// band in 8-bit: it encodes 10-bit AVIF at a higher quality. +type Spec = { src: string; crop?: [number, number, number, number]; widths: number[]; smooth?: boolean } + +const repo = resolve(import.meta.dirname, "..", "..") +const www = resolve(import.meta.dirname, "..") +const out = join(www, "public", "img") + +export const specs: Record<string, Spec> = { + hello: { src: "site/public/shots/hello-on.png", widths: [320, 640] }, + "opencode-session": { src: "demo/opencode/session-top.png", widths: [720, 1120, 1680, 2240] }, + "opencode-home": { src: "demo/opencode/home.png", widths: [560, 1100] }, + "opencode-streaming": { src: "demo/opencode/streaming.png", widths: [560, 1100] }, + // `cargo run --release -p site-scenes` renders these into target/; they aren't committed. + metal: { src: "target/site-scenes/metal.png", widths: [760, 1520], smooth: true }, + glass: { src: "target/site-scenes/glass.png", crop: [240, 135, 1440, 810], widths: [380, 760], smooth: true }, + light: { src: "target/site-scenes/light.png", crop: [240, 135, 1440, 810], widths: [380, 760], smooth: true }, +} + +rmSync(out, { recursive: true, force: true }) +mkdirSync(out, { recursive: true }) +let bytes = 0 +for (const [name, spec] of Object.entries(specs)) { + const src = join(repo, spec.src) + const crop = spec.crop ? ["-crop", `${spec.crop[2]}x${spec.crop[3]}+${spec.crop[0]}+${spec.crop[1]}`, "+repage"] : [] + const w0 = spec.crop ? spec.crop[2] : Number(await $`magick identify -format "%w" ${src}`.text()) + const widths = spec.widths.filter(w => w <= w0) + for (const w of widths) { + const [quality, depth] = spec.smooth ? [70, 10] : [52, 8] + const file = join(out, `${name}-${w}.avif`) + await $`magick ${src} ${crop} -resize ${w}x -strip -depth ${depth} -quality ${quality} ${file}`.quiet() + bytes += statSync(file).size + } +} +console.log(`${Object.keys(specs).length} images, ${(bytes / 1024).toFixed(0)} KB → public/img/`) diff --git a/app/vendor/rune/www/scripts/serve.ts b/app/vendor/rune/www/scripts/serve.ts new file mode 100644 index 0000000..ca4ea41 --- /dev/null +++ b/app/vendor/rune/www/scripts/serve.ts @@ -0,0 +1,52 @@ +#!/usr/bin/env bun +// `bun run serve [--port 4253]`: serves the built site through worker.ts, with a stand-in for the ASSETS binding that +// reads the build output, so the base path, 404 page and headers are the Worker's own. Run `bun run build` first. +import { existsSync, statSync } from "node:fs" +import { extname, join, resolve } from "node:path" +import { parseArgs } from "node:util" +import { brotliCompressSync, constants } from "node:zlib" +import { getWorkerAssetsDir } from "@cloudflare/build-output-utils" +import worker from "../worker" + +const { values } = parseArgs({ options: { port: { type: "string", default: "4253" }, host: { type: "string", default: "127.0.0.1" } } }) +const dir = getWorkerAssetsDir(resolve(import.meta.dirname, "..")) +if (!existsSync(join(dir, "index.html"))) throw new Error(`${dir}/index.html not found; run \`bun run build\` first`) + +const file = (p: string) => existsSync(p) && statSync(p).isFile() ? p : undefined + +// Static assets as Cloudflare serves them with html_handling "auto-trailing-slash": /x finds x.html or x/index.html. +const ASSETS = { + async fetch(request: Request) { + const path = decodeURIComponent(new URL(request.url).pathname) + const base = join(dir, path) + const hit = path.endsWith("/") ? file(join(base, "index.html")) : file(base) ?? file(`${base}.html`) + if (!hit) return new Response("Not found", { status: 404 }) + const html = extname(hit) === ".html" + return new Response(Bun.file(hit), { headers: html ? { "Content-Type": "text/html; charset=utf-8", "Cache-Control": "no-cache" } : {} }) + }, +} + +// Cloudflare compresses text and wasm on the way out; do the same so timings here are close to the real thing. +const squeezable = /^(text\/|application\/(javascript|json|wasm|manifest\+json)|image\/(svg|x-icon)|font\/(ttf|otf))/ +const squeezed = new Map<string, Buffer>() + +const server = Bun.serve({ + hostname: values.host, + port: Number(values.port), + async fetch(request) { + const response = await worker.fetch(request, { ASSETS, CANONICAL_HOST: "localhost", ANY_HOST: "1" }) + const type = response.headers.get("Content-Type") ?? "" + if (!response.ok || !squeezable.test(type) || !request.headers.get("Accept-Encoding")?.includes("br")) return response + const key = new URL(request.url).pathname + let body = squeezed.get(key) + if (!body) { + body = brotliCompressSync(new Uint8Array(await response.arrayBuffer()), { params: { [constants.BROTLI_PARAM_QUALITY]: 5 } }) + squeezed.set(key, body) + } + const headers = new Headers(response.headers) + headers.set("Content-Encoding", "br") + headers.delete("Content-Length") + return new Response(new Uint8Array(body), { status: response.status, headers }) + }, +}) +console.log(`rune-www on ${server.url}rune/`) diff --git a/app/vendor/rune/www/src/base.ts b/app/vendor/rune/www/src/base.ts new file mode 100644 index 0000000..873986f --- /dev/null +++ b/app/vendor/rune/www/src/base.ts @@ -0,0 +1,19 @@ +// The site lives under /rune on anoma.ly (production) and dev.anoma.ly (dev). +// Files keep root-relative paths internally ("/og.png"); these helpers add and remove the prefix at the edges. +export const BASE_PATH = "/rune" + +// The build mode (`--mode dev`) picks the environment; every other mode builds production. +export function hostForMode(mode: string | undefined): string { + return mode === "dev" ? "dev.anoma.ly" : "anoma.ly" +} + +export function withBase(path: string): string { + return `${BASE_PATH}${path}` +} + +// Returns the site path for a request path, or undefined when it is outside the base. +export function stripBase(pathname: string): string | undefined { + if (pathname === BASE_PATH) return "/" + if (!pathname.startsWith(`${BASE_PATH}/`)) return undefined + return pathname.slice(BASE_PATH.length) +} diff --git a/app/vendor/rune/www/src/brand/pixels.ts b/app/vendor/rune/www/src/brand/pixels.ts new file mode 100644 index 0000000..8614922 --- /dev/null +++ b/app/vendor/rune/www/src/brand/pixels.ts @@ -0,0 +1,159 @@ +// ᚱUNE on Anomaly's pixel grid: letters 11 pixels tall, 2-pixel stems, notched corners, fitted one clear pixel apart. +// The R is the rune ᚱ (raidō), so the name is spelled with a real rune and still reads as RUNE. Plain data and string +// builders, so the site and the icon script draw the same pixels. + +export type Grid = readonly string[] +const grid = (s: string): Grid => s.trim().split("\n").map(row => row.trim()) + +const GLYPHS: Record<string, Grid> = { + // The stave, a pointed bowl and a straight leg, all on 45° steps two pixels thick. + ᚱ: grid(` +###.... +####... +##.##.. +##..##. +##..##. +##.##.. +####... +##.##.. +##..##. +##...## +##...##`), + U: grid(` +##...## +##...## +##...## +##...## +##...## +##...## +##...## +##...## +##...## +####### +.#####.`), + N: grid(` +###...## +####..## +####..## +####..## +##.##.## +##.##.## +##.##.## +##..#### +##..#### +##..#### +##...###`), + E: grid(` +###### +###### +##.... +##.... +#####. +#####. +##.... +##.... +##.... +###### +######`), +} + +export const CAP = 11 + +/** The ᚱ redrawn for 16 and 32 px favicons: 3-pixel stems, one or two device pixels per cell. */ +export const ICON16: Grid = grid(` +................ +...####......... +...#####........ +...######....... +...###.###...... +...###..###..... +...###..###..... +...###.###...... +...######....... +...#####........ +...######....... +...###.###...... +...###..###..... +...###...###.... +...###....###... +................`) + +/** A pixel rectangle: x, y, width, height. */ +export type Rect = readonly [number, number, number, number] +export interface Glyph { char: string; x: number; rows: Grid } + +const ink = (rows: Grid) => rows.flatMap((row, y) => [...row].flatMap((c, x) => (c === "#" ? [[x, y] as const] : []))) + +/** Where `next` starts after `prev` (placed at `at`): as far left as keeps one clear pixel between their ink in every + * direction, diagonals included. */ +function fit(prev: Grid, at: number, next: Grid) { + const a = ink(prev).map(([x, y]) => [x + at, y] as const), b = ink(next) + let x = at + 1 + while (a.some(([ax, ay]) => b.some(([bx, by]) => Math.abs(bx + x - ax) <= 1 && Math.abs(by - ay) <= 1))) x++ + return x +} + +export const WORDMARK = (() => { + const glyphs: Glyph[] = [] + for (const char of "ᚱUNE") { + const rows = GLYPHS[char]! + const last = glyphs[glyphs.length - 1] + glyphs.push({ char, x: last ? fit(last.rows, last.x, rows) : 0, rows }) + } + const last = glyphs[glyphs.length - 1]! + return { glyphs, width: last.x + last.rows[0]!.length, height: CAP } +})() + +/** Rows to rectangles, merging each row's runs so no seams show between pixels. */ +export function runs(rows: Grid, dx = 0, dy = 0): Rect[] { + const out: Rect[] = [] + rows.forEach((row, y) => { + for (let x = 0; x < row.length; x++) { + if (row[x] !== "#") continue + let end = x + while (row[end] === "#") end++ + out.push([dx + x, dy + y, end - x, 1]) + x = end + } + }) + return out +} + +/** ᚱ's carve order: the stave top to bottom, then the bowl out and back, then the leg. Each cell gets the arc length + * (0–1) of its nearest point on that path. */ +export function carveOrder(rows: Grid): [number, number, number][] { + const path = [[[1, .5], [1, 10.5]], [[1.5, .5], [5, 3.5]], [[5, 3.5], [1.5, 6.5]], [[2.5, 6.5], [6, 10.5]]] as const + const lens = path.map(([a, b]) => Math.hypot(b[0] - a[0], b[1] - a[1])) + const total = lens.reduce((s, l) => s + l, 0) + return ink(rows).map(([x, y]) => { + const c = [x + .5, y + .5] as const + let best = Infinity, arc = 0, acc = 0 + path.forEach(([a, b], i) => { + const dx = b[0] - a[0], dy = b[1] - a[1] + const p = Math.max(0, Math.min(1, ((c[0] - a[0]) * dx + (c[1] - a[1]) * dy) / (dx * dx + dy * dy))) + const d = Math.hypot(a[0] + dx * p - c[0], a[1] + dy * p - c[1]) + if (d < best - 1e-6) { best = d; arc = acc + p * lens[i]! } + acc += lens[i]! + }) + return [x, y, arc / total] + }) +} + +/** OKLCH to gamma-encoded sRGB, 0–1 per channel. */ +export function oklch(l: number, c: number, hDeg: number): [number, number, number] { + const h = (hDeg * Math.PI) / 180, a = c * Math.cos(h), b = c * Math.sin(h) + const l_ = (l + .3963377774 * a + .2158037573 * b) ** 3 + const m_ = (l - .1055613458 * a - .0638541728 * b) ** 3 + const s_ = (l - .0894841775 * a - 1.291485548 * b) ** 3 + const lin = [ + 4.0767416621 * l_ - 3.3077115913 * m_ + .2309699292 * s_, + -1.2684380046 * l_ + 2.6097574011 * m_ - .3413193965 * s_, + -.0041960863 * l_ - .7034186147 * m_ + 1.707614701 * s_, + ] + const gamma = (x: number) => { x = Math.min(1, Math.max(0, x)); return x <= .0031308 ? 12.92 * x : 1.055 * x ** (1 / 2.4) - .055 } + return [gamma(lin[0]!), gamma(lin[1]!), gamma(lin[2]!)] +} + +/** Rune's ink, `--ink` in site.css, and the light the carve runs. */ +export const INK: [number, number, number] = [.74, .14, 245] +export const HOT: [number, number, number] = [.97, .035, 245] diff --git a/app/vendor/rune/www/src/main.ts b/app/vendor/rune/www/src/main.ts new file mode 100644 index 0000000..5a77c74 --- /dev/null +++ b/app/vendor/rune/www/src/main.ts @@ -0,0 +1,22 @@ +// The page is already here as static HTML; this hands it to Rune, which draws the same page on the GPU and hides +// the static copy once its first frame is up. Without WebGPU, or if the wasm fails, the static page stays. +// Rune's glue loads with the wasm, after the page has painted, not with the page. +const start = () => void import("./wasm/app.js").then(rune => rune.default()).catch(error => console.error(error)) + +// Once the static page has painted its largest text, so Rune's download never competes with it. +function afterFirstPaint(then: () => void) { + const type = PerformanceObserver.supportedEntryTypes?.includes("largest-contentful-paint") ? "largest-contentful-paint" : "paint" + let done = false + const go = () => { + if (done) return + done = true + observer.disconnect() + setTimeout(then, 0) + } + const observer = new PerformanceObserver(go) + observer.observe({ type, buffered: true }) + // A background tab paints nothing until it's shown. + setTimeout(go, 3000) +} + +if ("gpu" in navigator) afterFirstPaint(start) diff --git a/app/vendor/rune/www/src/meta.ts b/app/vendor/rune/www/src/meta.ts new file mode 100644 index 0000000..a309096 --- /dev/null +++ b/app/vendor/rune/www/src/meta.ts @@ -0,0 +1,7 @@ +export const REPO = "https://github.com/anomalyco/rune" +export const DOCS = `${REPO}/blob/dev/crates/rune/README.md` +export const TITLE = "Rune · A Rust UI framework with its own GPU renderer" +/** Link previews cut long titles, so shares get a short one. */ +export const SHARE_TITLE = "Rune, a Rust UI framework" +export const DESCRIPTION = + "A Rust UI framework with its own GPU renderer, text, layout and springs. Views are plain Rust, and one codebase runs on macOS, Windows, Linux, iOS and the web." diff --git a/app/vendor/rune/www/src/wasm.d.ts b/app/vendor/rune/www/src/wasm.d.ts new file mode 100644 index 0000000..11b2513 --- /dev/null +++ b/app/vendor/rune/www/src/wasm.d.ts @@ -0,0 +1,5 @@ +// src/wasm/ is built by scripts/build.ts and never committed. This types its entry point until it exists. +declare module "*/wasm/app.js" { + const init: () => Promise<unknown> + export default init +} diff --git a/app/vendor/rune/www/tsconfig.json b/app/vendor/rune/www/tsconfig.json new file mode 100644 index 0000000..8a132ed --- /dev/null +++ b/app/vendor/rune/www/tsconfig.json @@ -0,0 +1,20 @@ +{ + "compilerOptions": { + "target": "esnext", + "lib": ["es2023", "dom", "dom.iterable"], + "moduleDetection": "force", + "module": "esnext", + "moduleResolution": "bundler", + "resolveJsonModule": true, + "types": ["vite/client", "bun", "node"], + "strict": true, + "noUnusedLocals": true, + "noEmit": true, + "allowImportingTsExtensions": true, + "esModuleInterop": true, + "isolatedModules": true, + "verbatimModuleSyntax": true, + "skipLibCheck": true + }, + "include": ["src", "scripts", "worker.ts", "vite.config.ts", "cloudflare.config.ts"] +} diff --git a/app/vendor/rune/www/vite.config.ts b/app/vendor/rune/www/vite.config.ts new file mode 100644 index 0000000..efb03d2 --- /dev/null +++ b/app/vendor/rune/www/vite.config.ts @@ -0,0 +1,22 @@ +import { cloudflare } from "@cloudflare/vite-plugin" +import { defineConfig } from "vite" +import { BASE_PATH } from "./src/base" + +// Vite only bundles src/main.ts with the wasm Rune builds into src/wasm/, and the Cloudflare plugin shapes the result +// into Build Output for `cf deploy`. scripts/build.ts then writes the page into index.html. +export default defineConfig({ + plugins: [cloudflare()], + base: `${BASE_PATH}/`, + build: { + outDir: "dist", + emptyOutDir: true, + assetsInlineLimit: 0, + sourcemap: true, + }, + preview: { + host: "127.0.0.1", + port: 4253, + strictPort: true, + allowedHosts: [".ts.net"], + }, +}) diff --git a/app/vendor/rune/www/worker.ts b/app/vendor/rune/www/worker.ts new file mode 100644 index 0000000..1772a51 --- /dev/null +++ b/app/vendor/rune/www/worker.ts @@ -0,0 +1,53 @@ +import { BASE_PATH, stripBase, withBase } from "./src/base" + +type Env = { + ASSETS: { fetch(request: Request): Promise<Response> } + CANONICAL_HOST: string + ANY_HOST?: string +} + +export default { + async fetch(request: Request, env: Env): Promise<Response> { + const url = new URL(request.url) + + if (!env.ANY_HOST && (url.hostname !== env.CANONICAL_HOST || url.protocol !== "https:")) { + url.protocol = "https:" + url.hostname = env.CANONICAL_HOST + url.port = "" + return Response.redirect(url.toString(), 301) + } + + if (url.pathname === BASE_PATH) { + url.pathname = `${BASE_PATH}/` + return Response.redirect(url.toString(), 301) + } + + // Paths outside the base aren't ours. + const path = stripBase(url.pathname) + if (path === undefined) return new Response("Not found", { status: 404 }) + + const assetUrl = new URL(url) + assetUrl.pathname = path + let response = await env.ASSETS.fetch(new Request(assetUrl, request)) + if (response.status === 404) { + const page = await env.ASSETS.fetch(new Request(new URL("/404", assetUrl))) + if (page.ok) response = new Response(page.body, { status: 404, headers: page.headers }) + } + const headers = new Headers(response.headers) + // Asset redirects (trailing slashes, /index.html) point at root-relative paths. + const location = headers.get("Location") + if (location?.startsWith("/")) headers.set("Location", withBase(location)) + if (path.startsWith("/assets/")) { + headers.set("Cache-Control", "public, max-age=31536000, immutable") + } else if (/^\/(img|fonts)\//.test(path)) { + headers.set("Cache-Control", "public, max-age=86400, stale-while-revalidate=604800") + } + headers.set("X-Content-Type-Options", "nosniff") + headers.set("Referrer-Policy", "strict-origin-when-cross-origin") + return new Response(response.body, { + status: response.status, + statusText: response.statusText, + headers, + }) + }, +} diff --git a/docs/rune-upstream.md b/docs/rune-upstream.md index e6ddecc..574b537 100644 --- a/docs/rune-upstream.md +++ b/docs/rune-upstream.md @@ -1,13 +1,8 @@ -# Rune fixes this app waits on +# Rune fixes this app waits on (the first two are cherry-picked, see the note at the end) Three faults live in rune, not here. Each one names the file, what happens, and how to check the fix. The app carries a workaround for the second and third. -The pin in `app/Cargo.toml` is `4ddf696`. Updating to `main` (`db7c080`) does not fix any of -them: `crates/rune/src/video` and `crates/rune/src/window/video_layer.rs` are identical between -the two revisions, and `main` does not build on Windows here because its windows-sys 0.61 -migration is unfinished (`Win32::Foundation::BOOL` now lives in `windows_sys::core`). - ## 1. A paused clip draws nothing `window/video_layer.rs` takes a clip off its compositor layer as soon as it is not running, and @@ -46,3 +41,19 @@ and plays silent. The app works around it in `app/src/screens/review.rs` with a second, audio-only player over the same file, kept in step by `keep_in_step`. + +## Cherry-picks on the vendored checkout + +Rune comes from `app/vendor/rune`, a checkout of `63ad0209` on branch `ported`, carrying two +fixes cherry-picked from the upstream issues (both written against `eb9f1104` and ported across +the refactors that landed since): + +- #1320, two commits: a pause while a clip is layered holds the layer's newest picture and + takes the pause's time from it, and the surface gets that picture when the window draws the + clip again. This fixes faults 1 and 2 above. +- #1325, two commits: a video's sound is read ahead of the clock on a reader of its own, and + the sound leads the clock from the device's own position. This fixes fault 3 above. + +`app/Cargo.toml` points `rune`, `rune-kit` and `rune-notify` at the checkout's crates by path. +To take a newer upstream rev: fetch in `app/vendor/rune`, rebase or re-apply the four commits +of `ported` on the new rev, and drop the workarounds below once the fixes arrive upstream.